From 0fd48228874d5dc884e67e378526ee6279138ed0 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 02:10:15 -0800 Subject: [PATCH 001/324] fix(server): per-file diff reads reuse the preview's merge base (#40216) --- .../src/features/review/useReviewDiffData.ts | 1 + apps/server/src/vcs/GitVcsDriverCore.test.ts | 17 +++++++++++++++++ apps/server/src/vcs/GitVcsDriverCore.ts | 10 ++++++++-- .../components/diffs/useReviewFilePatches.ts | 1 + packages/contracts/src/review.ts | 9 +++++++++ 5 files changed, 36 insertions(+), 2 deletions(-) diff --git a/apps/mobile/src/features/review/useReviewDiffData.ts b/apps/mobile/src/features/review/useReviewDiffData.ts index cf6574d87b26b..35cf8f2f14b3c 100644 --- a/apps/mobile/src/features/review/useReviewDiffData.ts +++ b/apps/mobile/src/features/review/useReviewDiffData.ts @@ -215,6 +215,7 @@ export function useReviewDiffData(input: { request: { cwd, ...(lazySource.baseRef ? { baseRef: lazySource.baseRef } : {}), + ...(lazySource.mergeBase ? { mergeBase: lazySource.mergeBase } : {}), file: { path: file.path, previousPath: file.previousPath, diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index c6f90862380fe..e05df2f322101 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -865,6 +865,22 @@ it.effect.each(["on a branch", "detached", "unborn"] as const)( assert.deepStrictEqual(discoveries(), branchRead); if (state !== "detached") assert.equal(headRef(afterCheckout), "outside-checkout"); + // A file read under that preview reuses its merge base instead of resolving it again. + const branchFile = yield* driver.getReviewDiffPreview({ + cwd, + mergeBase: afterCheckout.sources.find((entry) => entry.kind === "branch-range")! + .mergeBase!, + file: { path: "new.txt", previousPath: null, sourceKind: "branch-range" }, + }); + assert.isFalse(spawnedArgs.some((args) => args.includes("merge-base"))); + assert.deepStrictEqual(discoveries(), warm); + assert.deepStrictEqual( + branchFile.sources + .find((source) => source.kind === "branch-range")! + .files!.map((file) => file.path), + ["new.txt"], + ); + yield* driver.getReviewBranchCommits({ cwd }); assert.deepStrictEqual(discoveries(), branchRead); @@ -4147,6 +4163,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { const request = yield* decodeReviewDiffPreviewInput({ cwd, baseRef: initialBranch, + mergeBase: branch.mergeBase!, file: { path, previousPath: stat.previousPath, sourceKind: "branch-range" }, }); const result = yield* driver.getReviewDiffPreview(request); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 3691a03687bf0..e2bfa90fb32f7 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -4524,10 +4524,13 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }); } const sourceKind = input.file?.sourceKind ?? input.sourceKind; + const previewMergeBase = + input.file?.sourceKind === "branch-range" ? input.mergeBase : undefined; const needsCurrentBranch = input.commitSha === undefined && input.file?.sourceKind !== "commit" && - sourceKind !== "working-tree"; + sourceKind !== "working-tree" && + previewMergeBase === undefined; const reusesTracked = input.file === undefined && input.commitSha === undefined; const tracked = reusesTracked ? yield* takeTrackedReviewPreview(input) : undefined; const repository = @@ -4614,7 +4617,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* tracked?.review ?? (sourceKind === "working-tree" ? { baseRef: input.baseRef ?? null, mergeBase: null } - : yield* resolveReviewMergeBase(cwd, repository.currentBranch, input.baseRef)); + : previewMergeBase !== undefined + ? { baseRef: input.baseRef ?? null, mergeBase: previewMergeBase } + : yield* resolveReviewMergeBase(cwd, repository.currentBranch, input.baseRef)); const diffArgs = [ ...REVIEW_DIFF_ARGS, @@ -4742,6 +4747,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* title: review.baseRef ? `Changes vs ${review.baseRef}` : "Changes", baseRef: review.baseRef, headRef: repository.currentBranch ?? "HEAD", + ...(review.mergeBase === null ? {} : { mergeBase: review.mergeBase }), diff: baseDiff, ...(baseFiles === undefined ? {} : { files: baseFiles }), diffHash: baseDiffHash, diff --git a/apps/web/src/components/diffs/useReviewFilePatches.ts b/apps/web/src/components/diffs/useReviewFilePatches.ts index 4f68b51fb5edd..94fee877f0f4b 100644 --- a/apps/web/src/components/diffs/useReviewFilePatches.ts +++ b/apps/web/src/components/diffs/useReviewFilePatches.ts @@ -201,6 +201,7 @@ function reviewFileQueries({ cwd, ...(baseRef ? { baseRef } : {}), ...(source.kind === "commit" ? { commitSha: source.id } : {}), + ...(source.mergeBase ? { mergeBase: source.mergeBase } : {}), ignoreWhitespace, file: { path: file.path, diff --git a/packages/contracts/src/review.ts b/packages/contracts/src/review.ts index f8d8a6133358c..ab5cae42624d4 100644 --- a/packages/contracts/src/review.ts +++ b/packages/contracts/src/review.ts @@ -3,9 +3,16 @@ import { TrimmedNonEmptyString } from "./baseSchemas.ts"; import { GitCommandError } from "./git.ts"; import { VcsError } from "./vcs.ts"; +// An object id or HEAD, never an option-looking ref, since it is passed to git as a revision. +const ReviewMergeBase = Schema.String.check( + Schema.isPattern(/^(?:[0-9a-f]{40}|[0-9a-f]{64}|HEAD)$/), +); + export const ReviewDiffPreviewInput = Schema.Struct({ cwd: TrimmedNonEmptyString, baseRef: Schema.optional(TrimmedNonEmptyString), + // A branch-range file read reuses its preview's merge base instead of resolving it again. + mergeBase: Schema.optionalKey(ReviewMergeBase), commitSha: Schema.optional(TrimmedNonEmptyString), ignoreWhitespace: Schema.optionalKey(Schema.Boolean), sourceKind: Schema.optionalKey(Schema.Literals(["working-tree", "branch-range"])), @@ -74,6 +81,8 @@ export const ReviewDiffPreviewSource = Schema.Struct({ commitSubject: Schema.optionalKey(TrimmedNonEmptyString), baseRef: Schema.NullOr(TrimmedNonEmptyString), headRef: Schema.NullOr(TrimmedNonEmptyString), + // Branch-range only; older servers omit it. + mergeBase: Schema.optionalKey(ReviewMergeBase), diff: Schema.String, diffHash: TrimmedNonEmptyString, truncated: Schema.Boolean, From 714997c42043117a38510683f80ddc3962eba5db Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 02:25:14 -0800 Subject: [PATCH 002/324] fix(acp-registry): reinstall the current version when a cached build was removed upstream (#40261) --- .../src/server/AcpRegistrySupport.test.ts | 54 ++++++ .../src/server/AcpRegistrySupport.ts | 163 ++++++++++-------- 2 files changed, 147 insertions(+), 70 deletions(-) diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts index bc37033f3b360..398c48be3f68c 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts @@ -1608,6 +1608,60 @@ describe("AcpRegistrySupport", () => { ); }); + it.effect( + "installs the registry's current version when a cached index pins a removed build", + () => { + const binaryAgent = (version: string) => ({ + ...makeAgent({ + binary: { + "linux-x86_64": { + archive: `https://registry.test/example-agent-${version}.bin`, + cmd: "./bin/example-agent", + args: ["acp"], + }, + }, + }), + version, + }); + const requests: Array = []; + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-registry-stale-", + }); + yield* fileSystem.makeDirectory(`${cacheDir}/acp-registry`, { recursive: true }); + yield* fileSystem.writeFileString( + `${cacheDir}/acp-registry/registry.json`, + makeRegistry(binaryAgent("1.2.3")), + ); + const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir, + toolsDir: `${cacheDir}/tools`, + registryUrl, + }); + const resolved = yield* resolver.resolve(settings(), "/workspace"); + + expect(resolved.agent?.version).toBe("1.2.4"); + expect(resolved.spawn.command).toContain("/tools/example-agent/1.2.4/"); + expect(requests).toContain(registryUrl); + }).pipe( + Effect.scoped, + Effect.provide( + layerResolver((request) => { + requests.push(request.url); + const response = + request.url === registryUrl + ? new Response(makeRegistry(binaryAgent("1.2.4"))) + : request.url.endsWith("-1.2.4.bin") + ? new Response("#!/bin/sh\necho example\n") + : new Response("forbidden", { status: 403 }); + return Effect.succeed(HttpClientResponse.fromWeb(request, response)); + }), + ), + ); + }, + ); + it.effect("rejects unsafe command paths before downloading an archive", () => { const agent = makeAgent({ binary: { diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts index a2f01f201ef78..d3ab397d7aaeb 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts @@ -1938,6 +1938,85 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct }, ); + const resolveWithRegistry = Effect.fn("AcpRegistryCatalog.resolveWithRegistry")(function* ( + settings: AcpRegistrySettings, + cwd: string, + environment: NodeJS.ProcessEnv | undefined, + registry: AcpRegistryIndex, + ) { + const agentId = settings.agentId.trim(); + if (agentId.length === 0) { + return yield* new AcpRegistryError({ + reason: "agent_not_configured", + detail: "ACP Registry provider requires a registry agent ID.", + }); + } + const agent = yield* findAgent(registry, agentId); + const distribution = yield* compatibleDistribution(agent, settings.distribution); + + let command: string; + let args: ReadonlyArray; + let commandBinDirectory: string | undefined; + const effectiveEnvironment = environment ?? hostEnvironment; + const commandOverride = settings.commandPath.trim(); + if (commandOverride.length > 0) { + const resolvedOverride = resolveExecutable(commandOverride, platform, effectiveEnvironment); + if (resolvedOverride === undefined) { + return yield* new AcpRegistryError({ + reason: "runner_unavailable", + detail: `ACP Registry agent ${agent.id} requires '${commandOverride}', but it is not available on this provider instance's PATH.`, + }); + } + command = resolvedOverride; + args = distribution.args; + } else if (distribution.kind === "npx" || distribution.kind === "uvx") { + const installed = yield* withInstallPermit(agent.id)( + ensureGlobalPackage( + agent, + distribution.kind, + distribution.packageName!, + effectiveEnvironment, + ), + ); + command = installed.executablePath; + args = distribution.args; + commandBinDirectory = installed.binDirectory; + } else { + const target = distribution.binaryTarget!; + command = yield* withInstallPermit(agent.id)( + installBinary(agent, target).pipe( + Effect.tap(() => consumePreparedBinaryReservation(agent.id)), + ), + ); + args = distribution.args; + } + + const baseSpawnEnvironment = { + ...effectiveEnvironment, + ...distribution.env, + }; + const pathEnvironment = + commandBinDirectory === undefined + ? baseSpawnEnvironment + : withPreferredPath(baseSpawnEnvironment, commandBinDirectory, platform); + const spawnEnvironment = + runtimeTempDir !== undefined && UNPACKING_AGENT_IDS.has(agent.id) + ? yield* acquireRuntimeTempEnvironment(runtimeTempDir, pathEnvironment) + : pathEnvironment; + + return { + agent, + distribution: distribution.kind, + spawn: { + command, + args, + cwd, + env: spawnEnvironment, + }, + } satisfies ResolvedAcpRegistryAgent; + }); + + // A cached index can pin a version whose archive was since removed upstream. const resolve: AcpRegistryCatalog["Service"]["resolve"] = Effect.fn("AcpRegistryCatalog.resolve")( function* (settings, cwd, environment) { if (settings.source === "local") { @@ -1962,77 +2041,21 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct spawn: { command, args: settings.commandArgs, cwd, env, shell: false }, } satisfies ResolvedAcpRegistryAgent; } - const agentId = settings.agentId.trim(); - if (agentId.length === 0) { - return yield* new AcpRegistryError({ - reason: "agent_not_configured", - detail: "ACP Registry provider requires a registry agent ID.", - }); - } const registry = yield* loadRegistry(); - const agent = yield* findAgent(registry, agentId); - const distribution = yield* compatibleDistribution(agent, settings.distribution); - - let command: string; - let args: ReadonlyArray; - let commandBinDirectory: string | undefined; - const effectiveEnvironment = environment ?? hostEnvironment; - const commandOverride = settings.commandPath.trim(); - if (commandOverride.length > 0) { - const resolvedOverride = resolveExecutable(commandOverride, platform, effectiveEnvironment); - if (resolvedOverride === undefined) { - return yield* new AcpRegistryError({ - reason: "runner_unavailable", - detail: `ACP Registry agent ${agent.id} requires '${commandOverride}', but it is not available on this provider instance's PATH.`, - }); - } - command = resolvedOverride; - args = distribution.args; - } else if (distribution.kind === "npx" || distribution.kind === "uvx") { - const installed = yield* withInstallPermit(agent.id)( - ensureGlobalPackage( - agent, - distribution.kind, - distribution.packageName!, - effectiveEnvironment, - ), - ); - command = installed.executablePath; - args = distribution.args; - commandBinDirectory = installed.binDirectory; - } else { - const target = distribution.binaryTarget!; - command = yield* withInstallPermit(agent.id)( - installBinary(agent, target).pipe( - Effect.tap(() => consumePreparedBinaryReservation(agent.id)), - ), - ); - args = distribution.args; - } - - const baseSpawnEnvironment = { - ...effectiveEnvironment, - ...distribution.env, - }; - const pathEnvironment = - commandBinDirectory === undefined - ? baseSpawnEnvironment - : withPreferredPath(baseSpawnEnvironment, commandBinDirectory, platform); - const spawnEnvironment = - runtimeTempDir !== undefined && UNPACKING_AGENT_IDS.has(agent.id) - ? yield* acquireRuntimeTempEnvironment(runtimeTempDir, pathEnvironment) - : pathEnvironment; - - return { - agent, - distribution: distribution.kind, - spawn: { - command, - args, - cwd, - env: spawnEnvironment, - }, - } satisfies ResolvedAcpRegistryAgent; + return yield* resolveWithRegistry(settings, cwd, environment, registry).pipe( + Effect.catchIf( + (error) => error.reason === "download_failed", + (error) => + Effect.gen(function* () { + const latest = yield* refreshRegistry().pipe(Effect.mapError(() => error)); + const agentId = settings.agentId.trim(); + const versionIn = (index: AcpRegistryIndex) => + index.agents.find((agent) => agent.id === agentId)?.version; + if (versionIn(latest) === versionIn(registry)) return yield* error; + return yield* resolveWithRegistry(settings, cwd, environment, latest); + }), + ), + ); }, ); From 0b02be3d5f43b8b1e1b2400e7a322e4b0249136d Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 02:40:13 -0800 Subject: [PATCH 003/324] fix(server): Claude's answer before a late-read steer stays visible (#40265) --- .../Adapters/ClaudeAdapterV2.test.ts | 20 +++++++++++++++++++ .../Adapters/ClaudeAdapterV2.ts | 16 +++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 2ed84ecd1a51e..e1665b1bafb3e 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -6325,6 +6325,12 @@ describe("ClaudeAdapterV2 background wake turns", () => { session_id: WAKE_NATIVE_SESSION, }), ); + yield* harness.offerAndWait( + makeAssistantTextFrame({ + uuid: "00000000-0000-4000-8000-000000002505", + text: "Build answer.", + }), + ); yield* harness.offerAndWait( claudeSdkFrame({ ...makeResultFrame({ uuid: "00000000-0000-4000-8000-000000002500", result: "Built." }), @@ -6350,6 +6356,20 @@ describe("ClaudeAdapterV2 background wake turns", () => { (event) => event.type === "message.updated" && event.message.text === "Steer reply.", ); assert.equal(reply?.type === "message.updated" ? reply.message.runId : null, input.runId); + // Claude ended its native turn on this answer before it read the steer, so the timeline + // must not fold it away as a progress note of the run's last reply. + const answer = harness.events.findLast( + (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "assistant_message" && + event.turnItem.text === "Build answer.", + ); + assert.equal( + answer?.type === "turn_item.updated" && answer.turnItem.type === "assistant_message" + ? answer.turnItem.phase + : null, + "final_answer", + ); assert.deepEqual( harness.events.flatMap((event) => event.type === "steer.updated" ? [[event.messageId, event.status]] : [], diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index df965d891487c..b120f9feb5e5a 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -5015,6 +5015,7 @@ function buildAssistantArtifacts(input: { readonly completedAt: DateTime.Utc; // A streamed message keeps its first timestamp across updates. readonly createdAt?: DateTime.Utc; + readonly finalAnswer?: boolean; }): { readonly node: OrchestrationV2ExecutionNode; readonly message: OrchestrationV2ConversationMessage; @@ -5089,6 +5090,7 @@ function buildAssistantArtifacts(input: { completedAt, updatedAt: input.completedAt, type: "assistant_message", + ...(input.finalAnswer === true ? { phase: "final_answer" as const } : {}), messageId, text: input.text, streaming, @@ -9333,6 +9335,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( readonly startedAt: DateTime.Utc; readonly completedAt: DateTime.Utc; readonly createdAt?: DateTime.Utc; + readonly finalAnswer?: boolean; }) { const ordinal = yield* resolveItemOrdinal(input.context, input.nativeItemId); const artifacts = buildAssistantArtifacts({ @@ -9346,6 +9349,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( startedAt: input.startedAt, completedAt: input.completedAt, ...(input.createdAt === undefined ? {} : { createdAt: input.createdAt }), + ...(input.finalAnswer === undefined ? {} : { finalAnswer: input.finalAnswer }), }); yield* Effect.all( [ @@ -12302,6 +12306,18 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( claudeEchoedPromptUuids(message).length > 0 ) { context.heldResult = message; + // Claude ended its native turn on this reply; the run continues only for the steer. + const answer = context.assistant.lastReply; + if (answer !== null) { + yield* publishAssistantArtifacts({ + context, + ...answer, + createdAt: answer.startedAt, + status: "completed", + completedAt, + finalAnswer: true, + }); + } return; } yield* finalizeActiveTurn({ From d5f8a7573a3817d8c20f7491e7672443355c4083 Mon Sep 17 00:00:00 2001 From: TheGuyWithHAT Date: Sat, 21 Nov 2026 11:54:31 +0100 Subject: [PATCH 004/324] fix(web): RTF previews hide tracked deletions (#40264) Co-authored-by: Geezy Co-authored-by: Julius Marminge --- .../components/files/FilePreviewPanel.test.ts | 11 +++++ .../files/extendedDocumentPreview.ts | 45 +++++++++++++------ 2 files changed, 43 insertions(+), 13 deletions(-) diff --git a/apps/web/src/components/files/FilePreviewPanel.test.ts b/apps/web/src/components/files/FilePreviewPanel.test.ts index 19db5d24544f1..c02a74868fb0a 100644 --- a/apps/web/src/components/files/FilePreviewPanel.test.ts +++ b/apps/web/src/components/files/FilePreviewPanel.test.ts @@ -158,6 +158,17 @@ describe("document preview contents", () => { "A\tB\u2003C\u2002D\u2005E\u200dF\u200cG\u200bH\u200eI\u200fJ", ], ["a Unicode fallback", String.raw`{\rtf1 Jean\u8209\_Luc}`, "Jean\u2011Luc"], + ["a tracked replacement", String.raw`{\rtf1 aaa{\deleted bbb}{\revised BBB}ccc}`, "aaaBBBccc"], + [ + "text after a deletion reset", + String.raw`{\rtf1 A\deleted old\deleted0 B\deleted old\plain C}`, + "ABC", + ], + [ + "text around a deleted Unicode span", + String.raw`{\rtf1 A{\deleted\uc1\u945\deleted0 old}B}`, + "AB", + ], ])("keeps the text of %s", (_name, source, expected) => { const result = openRtf(bytes(source)); if (result.type !== "document") throw new Error("Expected document"); diff --git a/apps/web/src/components/files/extendedDocumentPreview.ts b/apps/web/src/components/files/extendedDocumentPreview.ts index c61a9207082d2..429e2fc56a4db 100644 --- a/apps/web/src/components/files/extendedDocumentPreview.ts +++ b/apps/web/src/components/files/extendedDocumentPreview.ts @@ -502,7 +502,6 @@ const RTF_CHARACTERS = new Map([ ["_", "\u2011"], ["-", "\u00ad"], ["tab", "\t"], - ["cell", "\t"], ["endash", "–"], // oxlint-disable-next-line t3code/no-em-dash-copy -- Preserve the RTF document's punctuation. ["emdash", "—"], @@ -531,6 +530,7 @@ export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { if (!source.startsWith("{\\rtf")) throw new PreviewError({ code: "rtf-invalid" }); let state = { skip: false, + deleted: false, bold: false, italic: false, underline: false, @@ -553,6 +553,7 @@ export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { }; let run = ""; let fallback = 0; + const hidden = () => state.skip || state.deleted; const encoded = new Uint8Array(bytes.byteLength); let encodedLength = 0; const flush = () => { @@ -572,19 +573,19 @@ export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { html += span; run = ""; }; - const emit = (value: string) => { + const emit = (value: string, skip = hidden()) => { if (fallback > 0) { fallback--; return; } - if (state.skip) return; + if (skip) return; run += escape(value); if (completedLength + html.length + run.length > 8 * 1024 * 1024) throw new PreviewError({ code: "rtf-too-much-content" }); }; const emitByte = (value: number) => { if (fallback > 0) fallback--; - else if (!state.skip) encoded[encodedLength++] = value; + else if (!hidden()) encoded[encodedLength++] = value; }; for (let i = 0; i < source.length;) { const char = source[i++]; @@ -624,13 +625,22 @@ export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { const character = RTF_CHARACTERS.get(next!); if (character) emit(character); // A backslash before a line break is \par; TextEdit ends paragraphs this way. - else if ((next === "\n" || next === "\r") && !state.skip) html += "
"; + else if ((next === "\n" || next === "\r") && !hidden()) html += "
"; i++; continue; } i += match[0].length; const word = match[1]; const arg = match[2] === undefined ? 1 : Number(match[2]); + if (word === "bin") { + if (!Number.isSafeInteger(arg) || arg < 0 || arg > source.length - i) + throw new PreviewError({ code: "rtf-binary-data" }); + i += arg; + } + if (fallback > 0) { + fallback--; + continue; + } if (word === "fonttbl") { state.fontTable = true; state.skip = true; @@ -681,11 +691,7 @@ export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { ].includes(word!) ) state.skip = true; - else if (word === "bin") { - if (!Number.isSafeInteger(arg) || arg < 0 || arg > source.length - i) - throw new PreviewError({ code: "rtf-binary-data" }); - i += arg; - } else if (word === "mac") state.decoder = new TextDecoder("macintosh"); + else if (word === "mac") state.decoder = new TextDecoder("macintosh"); else if (word === "ansicpg") { const label = ( @@ -708,15 +714,28 @@ export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { else if (word === "i") state.italic = arg !== 0; else if (word === "ul") state.underline = arg !== 0; else if (word === "ulnone") state.underline = false; + else if (word === "deleted") state.deleted = arg !== 0; else if (word === "plain") - state = { ...state, bold: false, italic: false, underline: false, font: defaultFont }; + state = { + ...state, + deleted: false, + bold: false, + italic: false, + underline: false, + font: defaultFont, + }; else if (word === "uc") state.uc = Math.max(0, Math.min(10, arg)); else if (word === "u") { fallback = 0; emit(String.fromCharCode(arg < 0 ? arg + 65536 : arg)); fallback = state.uc; - } else if (!state.skip && word === "page") finishPage(); - else if (!state.skip && (word === "par" || word === "line" || word === "row")) html += "
"; + } else if (!hidden() && word === "page") finishPage(); + else if (word === "cell") emit("\t", state.skip); + else if ( + (!state.skip && word === "row") || + (!hidden() && (word === "par" || word === "line")) + ) + html += "
"; else { const character = RTF_CHARACTERS.get(word!); if (character) emit(character); From 0dc32b5c8bb3c3408ef517d512bb17d9a96bedb0 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 03:11:26 -0800 Subject: [PATCH 005/324] perf(server): an untracked file's Diff panel patch no longer copies the whole Git index (#40268) --- apps/server/src/vcs/GitVcsDriverCore.test.ts | 21 ++- apps/server/src/vcs/GitVcsDriverCore.ts | 135 ++++++++++++------- 2 files changed, 105 insertions(+), 51 deletions(-) diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index e05df2f322101..1d549acb26359 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -3925,10 +3925,18 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { } const preview = yield* driver.getReviewDiffPreview({ cwd, ignoreWhitespace: false }); - const diff = preview.sources.find((source) => source.kind === "working-tree")?.diff ?? ""; + const source = preview.sources.find((candidate) => candidate.kind === "working-tree")!; + const [file] = source.files ?? []; + const single = yield* driver.getReviewDiffPreview({ + cwd, + sourceKind: "working-tree", + file: { path: file!.path, previousPath: file!.previousPath, sourceKind: source.kind }, + }); - for (const text of expected) assert.include(diff, text); - assert.notInclude(diff, "new file mode"); + for (const diff of [source.diff, single.sources[0]!.diff]) { + for (const text of expected) assert.include(diff, text); + assert.notInclude(diff, "new file mode"); + } }), ); @@ -4240,6 +4248,13 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { ]); assert.include(dirty.diff, "b/staged.txt"); assert.include(dirty.diff, "b/untracked.txt"); + const single = yield* driver.getReviewDiffPreview({ + cwd, + sourceKind: "working-tree", + file: { path: "untracked.txt", previousPath: null, sourceKind: "working-tree" }, + }); + assert.deepStrictEqual(single.sources[0]!.files, dirty.files!.slice(1)); + assert.include(single.sources[0]!.diff, "b/untracked.txt"); }), ); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index e2bfa90fb32f7..d8ef17482e404 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -3956,32 +3956,35 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* cwd: string, untrackedPaths: ReadonlyArray, allowPartial: boolean, - knownIndexPath?: string, + knownIndexPath: string | undefined, + isolated: boolean, ) { const [stagedDeletionsStdout, indexValue] = yield* Effect.all( [ - runGitStdoutWithOptions( - "GitVcsDriver.readUnifiedWorkingTreeReviewDiff.stagedDeletions", - cwd, - [ - "diff", - "--cached", - "--no-renames", - "--name-only", - "--diff-filter=D", - "-z", - "HEAD", - "--", - ], - { allowNonZeroExit: true, maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES }, - ), - knownIndexPath === undefined - ? runGitStdout("GitVcsDriver.readUnifiedWorkingTreeReviewDiff.indexPath", cwd, [ + isolated + ? Effect.succeed("") + : runGitStdoutWithOptions( + "GitVcsDriver.readUnifiedWorkingTreeReviewDiff.stagedDeletions", + cwd, + [ + "diff", + "--cached", + "--no-renames", + "--name-only", + "--diff-filter=D", + "-z", + "HEAD", + "--", + ], + { allowNonZeroExit: true, maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES }, + ), + isolated || knownIndexPath !== undefined + ? Effect.succeed(knownIndexPath ?? "") + : runGitStdout("GitVcsDriver.readUnifiedWorkingTreeReviewDiff.indexPath", cwd, [ "rev-parse", "--git-path", "index", - ]) - : Effect.succeed(knownIndexPath), + ]), ], { concurrency: 2 }, ); @@ -4023,20 +4026,12 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const omitted = pathsToAdd.length < candidates.length; if (pathsToAdd.length === 0 || (omitted && !allowPartial)) return { env: undefined, omitted }; - const indexPath = knownIndexPath ?? path.resolve(cwd, indexValue.replace(/\n$/, "")); - const tempIndexPath = yield* fileSystem.makeTempFileScoped({ - prefix: `t3code-review-index-${process.pid}-`, - }); - const indexExists = yield* fileSystem.exists(indexPath); - if (indexExists) { - const { mtime } = yield* fileSystem.stat(indexPath); - yield* fileSystem.copyFile(indexPath, tempIndexPath); - // stat truncates bigint times to ms; floor seconds to avoid making preceding-second files racy. - const indexTime = Option.isSome(mtime) - ? Math.max(0, Math.floor(mtime.value.getTime() / 1000)) - : 0; - yield* fileSystem.utimes(tempIndexPath, indexTime, indexTime); - } + const prefix = `t3code-review-index-${process.pid}-`; + // The pathspec excludes every other entry, so an index holding only the added paths diffs + // the same as a copy of the real one. Git reads the missing file as an empty index. + const tempIndexPath = isolated + ? path.join(yield* fileSystem.makeTempDirectoryScoped({ prefix }), "index") + : yield* fileSystem.makeTempFileScoped({ prefix }); const env = { GIT_INDEX_FILE: tempIndexPath } satisfies NodeJS.ProcessEnv; const tempIndexConfig = [ "-c", @@ -4044,15 +4039,29 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* "-c", "splitIndex.sharedIndexExpire=never", ]; - if (!indexExists) { - yield* executeGit("GitVcsDriver.review.emptyIndex", cwd, ["read-tree", "--empty"], { env }); + if (!isolated) { + const indexPath = knownIndexPath ?? path.resolve(cwd, indexValue.replace(/\n$/, "")); + const indexExists = yield* fileSystem.exists(indexPath); + if (indexExists) { + const { mtime } = yield* fileSystem.stat(indexPath); + yield* fileSystem.copyFile(indexPath, tempIndexPath); + // stat truncates bigint times to ms; floor seconds to avoid making preceding-second files racy. + const indexTime = Option.isSome(mtime) + ? Math.max(0, Math.floor(mtime.value.getTime() / 1000)) + : 0; + yield* fileSystem.utimes(tempIndexPath, indexTime, indexTime); + } else { + yield* executeGit("GitVcsDriver.review.emptyIndex", cwd, ["read-tree", "--empty"], { + env, + }); + } + yield* executeGit( + "GitVcsDriver.readUnifiedWorkingTreeReviewDiff.expandSplitIndex", + cwd, + [...tempIndexConfig, "update-index", "--no-split-index"], + { env }, + ); } - yield* executeGit( - "GitVcsDriver.readUnifiedWorkingTreeReviewDiff.expandSplitIndex", - cwd, - [...tempIndexConfig, "update-index", "--no-split-index"], - { env }, - ); yield* executeGit( "GitVcsDriver.readUnifiedWorkingTreeReviewDiff.addUntracked", cwd, @@ -4092,11 +4101,35 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* allowPartial: boolean, knownIndexPath?: string, ) { - const untracked = yield* executeGit( - "GitVcsDriver.review.listUntracked", - cwd, - ["ls-files", "--others", "--exclude-standard", "-z", "--", ...pathArgs], - { maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES }, + // Only the untracked path itself in the pathspec: a rename's tracked previous path needs its + // real index entry. + const isolated = onlyPath !== undefined && pathArgs.length === 1; + const listUntracked = (withTree: boolean) => + executeGit( + "GitVcsDriver.review.listUntracked", + cwd, + [ + "ls-files", + "--others", + "--exclude-standard", + ...(withTree ? ["--with-tree=HEAD"] : []), + "-z", + "--", + ...pathArgs, + ], + { maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES, allowNonZeroExit: withTree }, + ); + // An isolated index skips prepareReviewIndex's staged-deletion read, so --with-tree drops them + // here. It fails only without a HEAD, where nothing can be a staged deletion. + const untracked = yield* ( + isolated + ? listUntracked(true).pipe( + Effect.filterOrElse( + (result) => result.exitCode === 0, + () => listUntracked(false), + ), + ) + : listUntracked(false) ).pipe( Effect.catchTags({ GitCommandError: (error) => @@ -4112,7 +4145,13 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* if (paths.length === 0) return { env: undefined, omitted: false }; if (paths.length > REVIEW_UNTRACKED_MAX_FILES) return { unavailable: "Too many untracked files to count." }; - const index = yield* prepareReviewIndex(cwd, paths, allowPartial, knownIndexPath).pipe( + const index = yield* prepareReviewIndex( + cwd, + paths, + allowPartial, + knownIndexPath, + isolated, + ).pipe( Effect.catchTags({ PlatformError: (cause) => Effect.fail( From c1464d6774cf4c690aba3fb20b8094a35396d130 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 03:41:44 -0800 Subject: [PATCH 006/324] perf(server): status of a repository without a remote skips remote lookups (#40277) --- apps/server/src/git/GitManager.test.ts | 41 ++++++++++++++++ apps/server/src/git/GitManager.ts | 4 +- apps/server/src/vcs/GitVcsDriver.ts | 1 + apps/server/src/vcs/GitVcsDriverCore.test.ts | 2 +- apps/server/src/vcs/GitVcsDriverCore.ts | 49 ++++++++++++++------ 5 files changed, 81 insertions(+), 16 deletions(-) diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index 6625c1fa8f707..0528d08f36c29 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -1065,6 +1065,41 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { }), ); + it.effect("status of a repository without remotes runs no remote, provider or PR lookups", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature/local-only"]); + const gitCommands: string[] = []; + const { manager } = yield* makeManager({ gitCommands }); + + const local = yield* manager.localStatus({ cwd: repoDir }); + const remote = yield* manager.remoteStatus({ cwd: repoDir }); + + expect(local.hasPrimaryRemote).toBe(false); + expect(local.sourceControlProvider).toBeUndefined(); + expect(remote?.pr ?? null).toBeNull(); + // Once git reports no remotes, remote URLs, branch remotes and remote refs cannot exist. + expect( + gitCommands.filter((args) => + /remote get-url|remote\.[^ ]+\.url|branch\.[^ ]+\.remote|refs\/remotes/.test(args), + ), + ).toEqual([]); + + // A remote added outside T3 Code shows on the next read. + yield* runGit(repoDir, [ + "remote", + "add", + "origin", + "https://github.com/pingdotgg/codething-mvp.git", + ]); + yield* TestClock.adjust("2 seconds"); + const afterRemote = yield* manager.localStatus({ cwd: repoDir }); + expect(afterRemote.hasPrimaryRemote).toBe(true); + expect(afterRemote.sourceControlProvider?.kind).toBe("github"); + }), + ); + it.effect("a git read in flight during a T3 git action does not outlive it", () => Effect.gen(function* () { const repoDir = yield* makeTempDir("t3code-git-manager-"); @@ -3372,6 +3407,12 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { const repoDir = yield* makeTempDir("t3code-git-manager-"); yield* initRepo(repoDir); yield* runGit(repoDir, ["checkout", "-b", "feature/status-open-over-merged"]); + yield* runGit(repoDir, [ + "remote", + "add", + "origin", + "https://github.com/pingdotgg/codething-mvp.git", + ]); const { manager } = yield* makeManager({ providerScenario: { diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index ea97b4da14cfc..118e4ffd461ae 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -1286,7 +1286,7 @@ export const make = Effect.gen(function* () { .pipe( Effect.catchIf(isNotGitRepositoryError, () => Effect.succeed(nonRepositoryStatusDetails)), ); - const hostingProvider = details.isRepo + const hostingProvider = details.hasOriginRemote ? yield* resolveHostingProvider(cwd, details.branch) : null; @@ -1611,7 +1611,7 @@ export const make = Effect.gen(function* () { } const { pr, headSha } = - details.branch !== null + details.branch !== null && details.hasPrimaryRemote ? yield* lookupStatusPr( cwd, { diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index f2a7ce31e920a..5164e6f4585c8 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -99,6 +99,7 @@ export interface GitLocalStatusOptions { export interface GitRemoteStatusDetails { isRepo: boolean; + hasPrimaryRemote: boolean; defaultBranch: string | null; isDefaultBranch: boolean; branch: string | null; diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 1d549acb26359..e23343ed67165 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -901,7 +901,7 @@ it.effect("resolves a branch's base once while its refs and branch config are un const spawner = ChildProcessSpawner.make((command) => { if (!ChildProcess.isStandardCommand(command)) return delegate.spawn(command); spawnedArgs.push(command.args.map(String)); - return failRemoteLookup && command.args[0] === "remote" + return failRemoteLookup && command.args.includes("remote") ? Effect.fail( PlatformError.systemError({ _tag: "Unknown", diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index d8ef17482e404..ab9b10563c690 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -164,6 +164,7 @@ const NON_REPOSITORY_STATUS_DETAILS = Object.freeze({ isRepo: false, + hasPrimaryRemote: false, defaultBranch: null, isDefaultBranch: false, branch: null, @@ -1843,8 +1844,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }), { capacity: 2_048, + // A remote added outside T3 Code must show on the next status read, so only a hit is kept. timeToLive: Exit.match({ - onSuccess: () => STATUS_ORIGIN_EXISTS_CACHE_TTL, + onSuccess: (exists) => (exists ? STATUS_ORIGIN_EXISTS_CACHE_TTL : Duration.zero), onFailure: () => Duration.zero, }), }, @@ -2072,9 +2074,22 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return parsedRemoteRef?.branchName ?? branchName; }); + const hasAnyRemote = (cwd: string) => + resolveRepositoryPaths(cwd).pipe( + Effect.orElseSucceed(() => null), + Effect.flatMap((paths) => + paths === null + ? listRemoteNames(cwd).pipe(Effect.map((remoteNames) => remoteNames.length > 0)) + : Cache.get(primaryRemoteExistsCache, paths.gitCommonDir), + ), + ); + // Local-only repositories are normal and status polls them, so the span succeeds with null. // Callers that need a remote fail in their own span. const findPrimaryRemoteName = Effect.fn("resolvePrimaryRemoteName")(function* (cwd: string) { + if (!(yield* hasAnyRemote(cwd))) { + return null; + } if (yield* originRemoteExists(cwd)) { return "origin"; } @@ -2618,7 +2633,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ); } - const defaultBranch = yield* resolvePrimaryDefaultBranchName(cwd); + const hasPrimaryRemote = yield* hasAnyRemote(cwd); + const defaultBranch = hasPrimaryRemote ? yield* resolvePrimaryDefaultBranchName(cwd) : null; const isDefaultBranch = branch !== null && (branch === defaultBranch || @@ -2632,6 +2648,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return { isRepo: true, + hasPrimaryRemote, defaultBranch, isDefaultBranch, branch, @@ -2753,7 +2770,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* { allowNonZeroExit: true, maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES }, ); // diff-index does not read status output, so both spawn together; a non-repository discards it. - const [statusResult, numstatResult, defaultBranch, hasPrimaryRemote] = yield* Effect.all( + const [statusResult, numstatResult, [hasPrimaryRemote, defaultBranch]] = yield* Effect.all( [ readStatus, readNumstat("HEAD").pipe( @@ -2779,17 +2796,23 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }), Effect.result, ), - statusCacheKey - ? Cache.get(defaultBranchCache, statusCacheKey).pipe(Effect.orElseSucceed(() => null)) - : resolvePrimaryDefaultBranchName(cwd).pipe(Effect.orElseSucceed(() => null)), - statusCacheKey - ? Cache.get(primaryRemoteExistsCache, statusCacheKey).pipe( - Effect.orElseSucceed(() => false), - ) - : listRemoteNames(cwd).pipe( - Effect.map((remoteNames) => remoteNames.length > 0), - Effect.orElseSucceed(() => false), + (statusCacheKey + ? Cache.get(primaryRemoteExistsCache, statusCacheKey) + : listRemoteNames(cwd).pipe(Effect.map((remoteNames) => remoteNames.length > 0)) + ).pipe( + Effect.orElseSucceed(() => false), + Effect.flatMap((hasRemote) => + (hasRemote + ? statusCacheKey + ? Cache.get(defaultBranchCache, statusCacheKey) + : resolvePrimaryDefaultBranchName(cwd) + : Effect.succeed(null) + ).pipe( + Effect.orElseSucceed(() => null), + Effect.map((defaultBranch) => [hasRemote, defaultBranch] as const), ), + ), + ), ], { concurrency: "unbounded" }, ); From 3d8a02371b361a3e0096782d8b26c78a0e62bdcd Mon Sep 17 00:00:00 2001 From: Turner Monroe Date: Sat, 21 Nov 2026 13:16:29 +0100 Subject: [PATCH 007/324] fix(forgejo): issue links on a self-hosted Forgejo hostname resolve (#40271) Co-authored-by: Julius Marminge --- apps/server/src/issue/IssueService.test.ts | 18 ++++++++++++++++++ .../src/shared/definition.ts | 6 ++++-- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/apps/server/src/issue/IssueService.test.ts b/apps/server/src/issue/IssueService.test.ts index 231559e9eb4df..a291d5bee11f7 100644 --- a/apps/server/src/issue/IssueService.test.ts +++ b/apps/server/src/issue/IssueService.test.ts @@ -283,6 +283,24 @@ describe("IssueService", () => { yield* enterprise.resolveUrl("https://code.acme.test/acme/web/issues/7"), ).toMatchObject({ projectId: "ghes", host: "code.acme.test", key: "7", writable: true }); + // The same holds for a self-hosted Forgejo. + const forgejo = yield* makeService({ + projects: [ + project({ + id: "forge", + repository: "acme/web", + provider: "forgejo", + host: "code.acme.test", + }), + ], + trackers: [fakeTracker({ kind: IssueTrackerKind.make("forgejo") })], + }); + expect(yield* forgejo.resolveUrl("https://code.acme.test/acme/web/issues/7")).toMatchObject({ + projectId: "forge", + host: "code.acme.test", + key: "7", + }); + // A fork lists its upstream's issues and its own, counted once, and may write to both. const fork = project({ id: "fork", repository: "acme/web" }); const forked = yield* makeService({ diff --git a/packages/source-control-forgejo/src/shared/definition.ts b/packages/source-control-forgejo/src/shared/definition.ts index 73bd2caa8ae8f..1f0b67fc4ccbc 100644 --- a/packages/source-control-forgejo/src/shared/definition.ts +++ b/packages/source-control-forgejo/src/shared/definition.ts @@ -99,8 +99,10 @@ export const definition = defineSourceControl({ const link = parseChangeRequestPath(url, CHANGE_REQUEST_PATH); return link === null ? null : { ...link, authority: url.host.toLowerCase() }; }, - // `/issues/` is too generic a path to believe from a host not named after Forgejo or Gitea. - parseIssueUrl: (url) => (isForgejoHost(url.hostname) ? parseIssuePath(url, ISSUE_PATH) : null), + // `/issues/` is too generic a path to believe from a host not named after Forgejo or Gitea, + // unless a Forgejo project on that host vouches for it. + parseIssueUrl: (url, known) => + known || isForgejoHost(url.hostname) ? parseIssuePath(url, ISSUE_PATH) : null, changeRequestUrlFromReferenceAutolink: () => null, commitUrl: (input) => buildCommitUrl(input, "commit"), parseCommitUrl: (url) => parseCommitPath(url, COMMIT_PATH), From 47525fa3d6bca7cc1ad66404d42de90cc6785e91 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 04:31:08 -0800 Subject: [PATCH 008/324] fix(web): switching threads no longer restarts the Changes and git status reads (#40215) --- apps/web/src/components/ChatView.tsx | 42 +++++-- apps/web/src/components/DiffPanel.tsx | 12 +- apps/web/src/components/GitActionsControl.tsx | 14 +-- .../chat/RightPanelSurfaceContent.tsx | 4 +- .../src/hooks/useWorkspaceRevision.test.ts | 51 ++++++++ apps/web/src/hooks/useWorkspaceRevision.ts | 68 +++++++++++ apps/web/src/state/revisionedQuery.test.ts | 110 +++++++++++++++++- apps/web/src/state/revisionedQuery.ts | 73 ++++++++---- 8 files changed, 327 insertions(+), 47 deletions(-) create mode 100644 apps/web/src/hooks/useWorkspaceRevision.test.ts create mode 100644 apps/web/src/hooks/useWorkspaceRevision.ts diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 0cf9138843010..77c47d668daf4 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -168,7 +168,7 @@ import { isLatestRunSettled, } from "../session-logic"; import { type LegendListRef } from "@legendapp/list/react"; -import { useWorkspaceMutationRefresh } from "../hooks/useWorkspaceMutationRefresh"; +import { useWorkspaceRevision } from "../hooks/useWorkspaceRevision"; import { DEFAULT_INTERACTION_MODE, type ChatMessage } from "../types"; import { buildThreadRouteParams } from "../threadRoutes"; import { useTheme } from "../hooks/useTheme"; @@ -261,6 +261,7 @@ import { collectInlineContextIds } from "../lib/composerContextReferences"; import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore"; import { useKnownTerminalSessions, useThreadRunningTerminalIds } from "../state/terminalSessions"; import { useEnvironmentQueryRefresh } from "../state/query"; +import { revisionedQuery } from "../state/revisionedQuery"; import { useEnvironmentScope } from "~/state/session"; import { primaryServerKeybindingsAtom, serverEnvironment } from "../state/server"; import { hostEnvironmentIdAtom } from "../state/primaryEnvironment"; @@ -395,7 +396,7 @@ import { ChatRightPanel } from "./chat/ChatRightPanel"; import { useDraftEnvironmentRouting } from "./chat/useDraftEnvironmentRouting"; import { branchMismatchBannerItem, extensionStatusBannerItem } from "./chat/ThreadActivityBanners"; import { ThreadNow } from "./chat/ThreadNow"; -import type { ThreadStructure } from "@t3tools/client-runtime/state/shell"; +import { threadRuntimeIsActive, type ThreadStructure } from "@t3tools/client-runtime/state/shell"; import { useDelayedStatus } from "../hooks/useDelayedStatus"; import { useTimelineFollow } from "./chat/useTimelineFollow"; import { @@ -1716,16 +1717,36 @@ export default function ChatView(props: ChatViewProps) { environmentId, input: { cwd: gitStatusCwd }, }); + const workspaceRevision = useWorkspaceRevision({ + threadKey: activeThreadKey, + // A running thread can change the workspace after this visit's reads began. + unloaded: + routeThreadDetailRef !== null && + threadStatus !== "live" && + threadStatus !== "deleted" && + !threadRuntimeIsActive(serverThreadShell?.runtime), + mutationId: workspaceMutationId, + }); + // Per thread: opening a thread with workspace changes reads a cached status again. + const gitStatusRevision = + workspaceRevision.revision === null + ? undefined + : `${activeThreadKey ?? ""}\u0000${workspaceRevision.revision}`; const gitStatusQuery = { - data: useAtomValue(gitStatusAtom ? chatGitStatusAtom(gitStatusAtom) : NO_CHAT_GIT_STATUS_ATOM), + data: useAtomValue( + gitStatusAtom + ? chatGitStatusAtom( + workspaceRevision.pending + ? revisionedQuery(gitStatusAtom, undefined, { startedUnder: gitStatusRevision }) + : revisionedQuery( + gitStatusAtom, + workspaceMutationId === null ? undefined : gitStatusRevision, + ), + ) + : NO_CHAT_GIT_STATUS_ATOM, + ), refresh: useEnvironmentQueryRefresh(gitStatusAtom).refresh, }; - useWorkspaceMutationRefresh({ - enabled: gitStatusCwd !== null, - mutationId: workspaceMutationId, - refresh: gitStatusQuery.refresh, - resourceKey: `git-status:${activeThreadKey ?? ""}:${gitStatusCwd ?? ""}`, - }); const keybindings = useAtomValue(primaryServerKeybindingsAtom); const backgroundThread = use(BackgroundThreadContext); const scriptKeybindings = @@ -3359,6 +3380,7 @@ export default function ChatView(props: ChatViewProps) { keybindings={keybindings} configuredPreviewUrls={configuredPreviewUrls} workspaceMutationId={workspaceMutationId} + workspaceRevision={workspaceRevision.revision} getShortcutContext={getShortcutContextStable} onSendAnnotation={sendPreviewAnnotationStable} onCloseSurface={closeRightPanelSurface} @@ -4039,7 +4061,7 @@ export default function ChatView(props: ChatViewProps) { ) } gitCwd={gitCwd} - workspaceMutationId={workspaceMutationId} + workspaceMutationId={workspaceRevision.revision} isGitRepo={isGitRepo} envLocked={envLocked} availableEnvironments={logicalProjectEnvironments} diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx index c6460fabc53d2..561bcd2b3e040 100644 --- a/apps/web/src/components/DiffPanel.tsx +++ b/apps/web/src/components/DiffPanel.tsx @@ -105,7 +105,7 @@ import { DropdownMenuTrigger, } from "./ui/menu"; import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; -import { useEnvironmentQuery } from "../state/query"; +import { useEnvironmentQuery, useEnvironmentQueryRefresh } from "../state/query"; import { useAtomCommand } from "../state/use-atom-command"; import { serverEnvironment } from "../state/server"; import { reviewEnvironment } from "../state/review"; @@ -459,7 +459,7 @@ export default function DiffPanel({ const canRefreshGitDiff = isGitRepo && isGitSelection && activeThread != null && gitCwd != null; // Read under the workspace mutation id, so each mutation refetches the diff; the panel stays // mounted while hidden, so a mutation made then is already reflected when it shows. - const branchDiffPreview = useEnvironmentQuery( + const branchDiffPreviewAtom = branchDiffPreviewInput && activeThread ? revisionedQuery( reviewEnvironment.diffPreview({ @@ -468,9 +468,9 @@ export default function DiffPanel({ }), canRefreshGitDiff ? workspaceMutationId : undefined, ) - : null, - messages, - ); + : null; + const branchDiffPreview = useEnvironmentQuery(branchDiffPreviewAtom, messages); + const branchDiffPreviewIsPending = useEnvironmentQueryRefresh(branchDiffPreviewAtom).isPending; const branchCommitsQuery = useEnvironmentQuery( visible && isGitRepo && canReadFiles && activeThread && gitCwd ? reviewEnvironment.branchCommits({ @@ -728,6 +728,8 @@ export default function DiffPanel({ useLiveRefresh( branchDiffPreview.data !== null && !branchDiffPreview.isPending ? () => { + // A read that began after this render, as a thread switch's, is that revalidation. + if (branchDiffPreviewIsPending()) return; if (Date.now() - branchDiffPreview.dataUpdatedAt < LIVE_REFRESH_MIN_INTERVAL_MS) return; refreshBranchDiffPreview(); } diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsx index d1fef4ad5a617..1c42f176d89b4 100644 --- a/apps/web/src/components/GitActionsControl.tsx +++ b/apps/web/src/components/GitActionsControl.tsx @@ -1071,12 +1071,11 @@ function CheckoutGitActionsControl({ const ignoreWhitespace = useDiffPanelSessionStore((state) => state.ignoreWhitespace) ?? ignoreWhitespaceSetting; const { canReadFiles } = useFilesystemReadAccess(activeEnvironmentId, messages); - // Same input as the Diff panel's branch query, so both read one cached result. Status - // totals join the revision because edits, pulls and resets outside a turn leave the mutation - // id as is. - const changesRevision = gitStatusForActions + // Same input and workspace revision as the Diff panel's branch query, so both read one + // cached result. Status totals are this reader's own revision because edits, pulls and + // resets outside a turn leave the mutation id as is. + const changesStatusRevision = gitStatusForActions ? JSON.stringify([ - workspaceMutationId, gitStatusForActions.refName, gitStatusForActions.workingTree.insertions, gitStatusForActions.workingTree.deletions, @@ -1089,7 +1088,7 @@ function CheckoutGitActionsControl({ showChanges && isRepo && canReadFiles && - changesRevision !== null && + changesStatusRevision !== null && activeEnvironmentId !== null && gitCwd !== null ? revisionedQuery( @@ -1103,7 +1102,8 @@ function CheckoutGitActionsControl({ sourceKind: "branch-range", }, }), - changesRevision, + workspaceMutationId, + { detail: changesStatusRevision }, ) : null, ); diff --git a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx b/apps/web/src/components/chat/RightPanelSurfaceContent.tsx index 22ef904e2c13f..076c78d88d468 100644 --- a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx +++ b/apps/web/src/components/chat/RightPanelSurfaceContent.tsx @@ -73,6 +73,8 @@ export function RightPanelSurfaceContent(props: { readonly keybindings: ResolvedKeybindingsConfig; readonly configuredPreviewUrls: ReadonlyArray; readonly workspaceMutationId: string | null; + /** What the diff is read under, as the Changes totals are; see `useWorkspaceRevision`. */ + readonly workspaceRevision: string | null; readonly getShortcutContext: () => ShortcutMatchContext; readonly onSendAnnotation: ( annotation: PreviewAnnotationPayload, @@ -118,7 +120,7 @@ export function RightPanelSurfaceContent(props: { key={scopedThreadKey(threadRef)} mode="embedded" composerDraftTarget={props.composerDraftTarget} - workspaceMutationId={props.workspaceMutationId} + workspaceMutationId={props.workspaceRevision} visible={visible} /> diff --git a/apps/web/src/hooks/useWorkspaceRevision.test.ts b/apps/web/src/hooks/useWorkspaceRevision.test.ts new file mode 100644 index 0000000000000..36f2c769bf425 --- /dev/null +++ b/apps/web/src/hooks/useWorkspaceRevision.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { advanceWorkspaceVisit, workspaceRevisionOf } from "./useWorkspaceRevision"; + +function visitThread(threadKey: string, unloaded: boolean, mutationId: string | null) { + let visit = advanceWorkspaceVisit(null, { threadKey, unloaded, mutationId }, "view"); + return (next: { unloaded: boolean; mutationId: string | null }) => { + visit = advanceWorkspaceVisit(visit, { threadKey, ...next }, "view"); + return workspaceRevisionOf(visit, next.mutationId); + }; +} + +describe("workspace revision", () => { + it("keeps the visit's revision for the mutation id the history loads with, not for a later one", () => { + const render = visitThread("thread-b", true, null); + const pending = render({ unloaded: true, mutationId: null }); + expect(pending.pending).toBe(true); + expect(pending.revision).not.toBeNull(); + + expect(render({ unloaded: false, mutationId: "b1" })).toEqual({ + revision: pending.revision, + pending: false, + }); + expect(render({ unloaded: false, mutationId: "b2" }).revision).toBe("b2"); + expect(render({ unloaded: false, mutationId: "b1" }).revision).toBe(pending.revision); + }); + + it("treats the first mutation of a thread whose history loaded without one as a change", () => { + const render = visitThread("thread-b", true, null); + const loaded = render({ unloaded: false, mutationId: null }); + expect(loaded.revision).not.toBeNull(); + expect(render({ unloaded: false, mutationId: "b1" }).revision).toBe("b1"); + }); + + it("is the mutation id when the visit began with the history known", () => { + const render = visitThread("thread-b", false, "b1"); + expect(render({ unloaded: false, mutationId: "b1" })).toEqual({ + revision: "b1", + pending: false, + }); + }); + + it("starts over, under another revision, for another thread and for a later visit", () => { + const input = { unloaded: true, mutationId: null }; + const first = advanceWorkspaceVisit(null, { threadKey: "thread-a", ...input }, "view"); + const second = advanceWorkspaceVisit(first, { threadKey: "thread-b", ...input }, "view"); + const again = advanceWorkspaceVisit(second, { threadKey: "thread-a", ...input }, "view"); + expect(new Set([first.revision, second.revision, again.revision]).size).toBe(3); + expect(workspaceRevisionOf(again, null).pending).toBe(true); + }); +}); diff --git a/apps/web/src/hooks/useWorkspaceRevision.ts b/apps/web/src/hooks/useWorkspaceRevision.ts new file mode 100644 index 0000000000000..cfbb4033043e6 --- /dev/null +++ b/apps/web/src/hooks/useWorkspaceRevision.ts @@ -0,0 +1,68 @@ +import { useId, useState } from "react"; + +interface WorkspaceVisit { + readonly threadKey: string | null; + readonly visit: number; + /** The revision this visit's reads start under. */ + readonly revision: string; + /** Whether this visit's reads cover the mutation id the history will load with. */ + readonly awaitsBaseline: boolean; + /** The mutation id the history loaded with; `undefined` until it loads. */ + readonly baseline: string | null | undefined; +} + +interface WorkspaceVisitInput { + readonly threadKey: string | null; + /** A settled server thread whose history is not synchronized yet. */ + readonly unloaded: boolean; + readonly mutationId: string | null; +} + +export interface WorkspaceRevision { + /** What workspace queries are read under; changes only when the workspace may have. */ + readonly revision: string | null; + /** The history is not synchronized: the mutation id is unknown, not absent. */ + readonly pending: boolean; +} + +export function advanceWorkspaceVisit( + visit: WorkspaceVisit | null, + input: WorkspaceVisitInput, + instanceId: string, +): WorkspaceVisit { + if (visit === null || visit.threadKey !== input.threadKey) { + const next = (visit?.visit ?? 0) + 1; + return { + threadKey: input.threadKey, + visit: next, + revision: `visit:${instanceId}:${next}:${input.threadKey ?? ""}`, + awaitsBaseline: input.unloaded, + baseline: undefined, + }; + } + return visit.awaitsBaseline && visit.baseline === undefined && !input.unloaded + ? { ...visit, baseline: input.mutationId } + : visit; +} + +export function workspaceRevisionOf( + visit: WorkspaceVisit, + mutationId: string | null, +): WorkspaceRevision { + if (!visit.awaitsBaseline) return { revision: mutationId, pending: false }; + if (visit.baseline === undefined) return { revision: visit.revision, pending: true }; + return { revision: mutationId === visit.baseline ? visit.revision : mutationId, pending: false }; +} + +/** + * The revision a thread's workspace queries are read under. The mutation id a thread's history + * loads with was made before the visit began, so the reads the visit already started cover it: + * the visit keeps one revision of its own until an id replaces that one. + */ +export function useWorkspaceRevision(input: WorkspaceVisitInput): WorkspaceRevision { + const instanceId = useId(); + const [visit, setVisit] = useState(() => advanceWorkspaceVisit(null, input, instanceId)); + const current = advanceWorkspaceVisit(visit, input, instanceId); + if (current !== visit) setVisit(current); + return workspaceRevisionOf(current, input.mutationId); +} diff --git a/apps/web/src/state/revisionedQuery.test.ts b/apps/web/src/state/revisionedQuery.test.ts index 7b21dd1d29aee..acc148af5bd10 100644 --- a/apps/web/src/state/revisionedQuery.test.ts +++ b/apps/web/src/state/revisionedQuery.test.ts @@ -1,6 +1,8 @@ +import * as Effect from "effect/Effect"; import { Atom, AtomRegistry } from "effect/reactivity"; import { describe, expect, it } from "vite-plus/test"; +import { advanceWorkspaceVisit, workspaceRevisionOf } from "../hooks/useWorkspaceRevision"; import { revisionedQuery } from "./revisionedQuery"; // A stand-in query that counts its fetches. @@ -21,8 +23,11 @@ function setup(readQuery: (cache: Atom.Atom) => Atom.Atom = (cac return fetches; }).pipe(Atom.keepAlive), ); - const mount = async (revision: string | null | undefined) => { - const release = registry.mount(revisionedQuery(query, revision)); + const mount = async ( + revision: string | null | undefined, + options?: Parameters[2], + ) => { + const release = registry.mount(revisionedQuery(query, revision, options)); // A stale read refetches in a microtask, after the render that read it. await Promise.resolve(); return () => { @@ -128,4 +133,105 @@ describe("revisionedQuery", () => { // A refetch that ran now would throw "registry is disposed" as an uncaught error. await Promise.resolve(); }); + + it("records a fetch started without a revision under the one it names", async () => { + const fresh = setup(); + (await fresh.mount(undefined, { startedUnder: "visit-b" }))(); + (await fresh.mount("visit-b"))(); + expect(fresh.fetches()).toBe(1); + + // Cached before that read: the revision still refetches it. + const cached = setup(); + (await cached.mount("thread-a-1"))(); + (await cached.mount(undefined, { startedUnder: "visit-b" }))(); + expect(cached.fetches()).toBe(1); + (await cached.mount("visit-b"))(); + expect(cached.fetches()).toBe(2); + }); + + it("refetches once for two readers of one query, and not when a thread's history loads", async () => { + const { mount, fetches } = setup(); + (await mount("thread-a-1", { detail: "status" }))(); + (await mount("thread-a-1"))(); + expect(fetches()).toBe(1); + + let visit = advanceWorkspaceVisit( + null, + { threadKey: "thread-b", unloaded: true, mutationId: null }, + "view", + ); + // The Changes totals, which add status totals of their own, then the Diff panel. + const render = async (unloaded: boolean, mutationId: string | null) => { + visit = advanceWorkspaceVisit(visit, { threadKey: "thread-b", unloaded, mutationId }, "view"); + const { revision } = workspaceRevisionOf(visit, mutationId); + (await mount(revision, { detail: "status" }))(); + (await mount(revision))(); + }; + + await render(true, null); + expect(fetches()).toBe(2); + await render(false, "thread-b-1"); + expect(fetches()).toBe(2); + await render(false, "thread-b-2"); + expect(fetches()).toBe(3); + }); + + it("refetches when a reader's own detail changes, whatever the other readers read", async () => { + const { mount, fetches } = setup(); + + (await mount("mutation-1", { detail: "status-1" }))(); + (await mount("mutation-1"))(); + (await mount("mutation-1", { detail: "status-1" }))(); + expect(fetches()).toBe(1); + + (await mount("mutation-1", { detail: "status-2" }))(); + expect(fetches()).toBe(2); + (await mount("mutation-1"))(); + expect(fetches()).toBe(2); + }); + + it("leaves a fetch that began after the revision changed to finish", async () => { + let fetches = 0; + const registry = AtomRegistry.make(); + const query = Atom.make( + Effect.suspend(() => ((fetches += 1) === 1 ? Effect.succeed(fetches) : Effect.never)), + ).pipe(Atom.keepAlive); + + registry.mount(revisionedQuery(query, "mutation-1")); + await Promise.resolve(); + expect(fetches).toBe(1); + + // Another reader's own refresh lands between the read and its deferred refetch. + registry.mount(revisionedQuery(query, "mutation-2")); + registry.refresh(query); + await Promise.resolve(); + expect(fetches).toBe(2); + + // A fetch already in flight when the revision changes started before the change. + registry.mount(revisionedQuery(query, "mutation-3")); + await Promise.resolve(); + expect(fetches).toBe(3); + }); + + it("does not restart the fetch of a query whose cache is gone", async () => { + let fetches = 0; + const scheduled: Array<() => void> = []; + const registry = AtomRegistry.make({ + scheduleTask: (task) => { + scheduled.push(task); + return () => {}; + }, + }); + const query = Atom.make(() => (fetches += 1)); + const read = async (revision: string) => { + const release = registry.mount(revisionedQuery(query, revision)); + await Promise.resolve(); + release(); + for (const task of scheduled.splice(0)) task(); + }; + + await read("mutation-1"); + await read("mutation-2"); + expect(fetches).toBe(2); + }); }); diff --git a/apps/web/src/state/revisionedQuery.ts b/apps/web/src/state/revisionedQuery.ts index 90c147b664741..6f63a64bbd54b 100644 --- a/apps/web/src/state/revisionedQuery.ts +++ b/apps/web/src/state/revisionedQuery.ts @@ -1,9 +1,19 @@ import * as Option from "effect/Option"; -import { Atom, type AtomRegistry } from "effect/reactivity"; +import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity"; // Outside the nodes: a node is dropped once unmounted, and the next read must // still compare against the revision the query was last read under. -const readRevisions = new WeakMap>(); +type LastRead = WeakMap>; +const readRevisions: LastRead = new WeakMap(); +const readDetails: LastRead = new WeakMap(); +const lastReadOf = (lastRead: LastRead, registry: AtomRegistry.AtomRegistry) => { + let byQuery = lastRead.get(registry); + if (byQuery === undefined) { + byQuery = new WeakMap(); + lastRead.set(registry, byQuery); + } + return byQuery; +}; // The registry keys serializable atoms' nodes by their key, not the atom. const hasNode = (registry: AtomRegistry.AtomRegistry, atom: Atom.Atom) => @@ -15,40 +25,58 @@ const isCached = (registry: AtomRegistry.AtomRegistry, query: Atom.Atom hasNode(registry, query) || (query.initialValueTarget !== undefined && hasNode(registry, query.initialValueTarget)); +const isWaiting = (value: unknown) => AsyncResult.isAsyncResult(value) && value.waiting; + const makeRevisionedFamily = (query: Atom.Atom) => - Atom.family((revision: string | null) => - Atom.readable( + Atom.family((key: string) => { + const { revision, startedUnder, detail } = JSON.parse(key) as { + readonly revision?: string | null; + readonly startedUnder?: string; + readonly detail?: string; + }; + return Atom.readable( (get) => { // Only a node's first build compares: a node still mounted under the old // revision rebuilds when the query refetches, and must not refetch it again. if (Option.isNone(get.self())) { - let revisions = readRevisions.get(get.registry); - if (revisions === undefined) { - revisions = new WeakMap(); - readRevisions.set(get.registry, revisions); + const revisions = lastReadOf(readRevisions, get.registry); + // Nothing cached: the read below fetches fresh, which a refresh would only restart. + const cached = isCached(get.registry, query); + if (revision === undefined) { + if (!cached && startedUnder !== undefined) revisions.set(query, startedUnder); + return get(query); } + const details = lastReadOf(readDetails, get.registry); const stale = revisions.has(query) - ? revisions.get(query) !== revision + ? revisions.get(query) !== revision || + (detail !== undefined && details.has(query) && details.get(query) !== detail) : // A reader without a revision may have cached it before the latest - // workspace change; a query nobody has read yet fetches fresh anyway. - revision !== null && isCached(get.registry, query); + // workspace change. + revision !== null || detail !== undefined; + revisions.set(query, revision); + if (detail !== undefined) details.set(query, detail); + const value = get(query); // Deferred: this builds while React renders, and a refresh would synchronously // re-render the query's other readers, which React rejects. - if (stale) { + if (stale && cached) { const registry = get.registry; + const wasWaiting = isWaiting(value); queueMicrotask(() => { // No node, as after the registry is disposed: nothing cached to refetch. - if (isCached(registry, query)) registry.refresh(query); + if (!isCached(registry, query)) return; + // A fetch that began since, as another reader's refresh, reads the same workspace. + if (!wasWaiting && isWaiting(registry.get(query))) return; + registry.refresh(query); }); } - revisions.set(query, revision); + return value; } return get(query); }, // Refreshing the reader refetches the query it reads. (refresh) => refresh(query), - ), - ); + ); + }); // Held as long as the query lives, so one (query, revision) pair keeps one atom; an // `Atom.family` would hold the inner family only weakly and could swap the atom under a reader. @@ -66,15 +94,16 @@ const revisionedFamily = (query: Atom.Atom) => { }; /** - * Reads `query` under a workspace revision (latest mutation id); a different - * revision than the last read refetches it. The first read records the revision, - * and refetches only a query that a reader without a revision already cached. - * `undefined` reads without taking part, for readers that must not refetch now. + * Reads `query` under a workspace revision (latest mutation id), which its readers share; a + * revision other than the last one read refetches a cached query. `undefined` reads without + * taking part. `startedUnder` records a fetch such a read starts as read under that revision; + * `detail` is one reader's own second revision, which the other readers neither see nor reset. */ export function revisionedQuery( query: Atom.Atom, revision: string | null | undefined, + options: { readonly startedUnder?: string | undefined; readonly detail?: string } = {}, ): Atom.Atom { - if (revision === undefined) return query; - return revisionedFamily(query)(revision) as Atom.Atom; + if (revision === undefined && options.startedUnder === undefined) return query; + return revisionedFamily(query)(JSON.stringify({ revision, ...options })) as Atom.Atom; } From 0854259384cf755016e9df66f452c72763152eaf Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 04:35:55 -0800 Subject: [PATCH 009/324] fix(web): clipped Files tree names show the full name on hover (#40308) --- .../web/src/components/diffs/DiffFileTree.tsx | 7 ++++++- .../src/components/files/FileBrowserPanel.tsx | 7 ++++++- apps/web/src/pierre-tree-theme.ts | 19 ++++++++++++++++++- 3 files changed, 30 insertions(+), 3 deletions(-) diff --git a/apps/web/src/components/diffs/DiffFileTree.tsx b/apps/web/src/components/diffs/DiffFileTree.tsx index ce48a468f66ec..57bc23b33130c 100644 --- a/apps/web/src/components/diffs/DiffFileTree.tsx +++ b/apps/web/src/components/diffs/DiffFileTree.tsx @@ -7,7 +7,11 @@ import { useEffect, useRef, useState, useSyncExternalStore, type ReactNode } fro import { useStableCallback } from "~/hooks/useStableCallback"; import { useTheme } from "~/hooks/useTheme"; import { cn } from "~/lib/utils"; -import { PIERRE_TREE_UNSAFE_CSS, pierreTreeStyle } from "~/pierre-tree-theme"; +import { + PIERRE_TREE_UNSAFE_CSS, + pierreTreeStyle, + titleClippedPierreTreeRow, +} from "~/pierre-tree-theme"; import { areAllDirectoriesExpanded, @@ -253,6 +257,7 @@ export function DiffFileTree({ }} className="min-h-0 flex-1 overflow-hidden" style={pierreTreeStyle(resolvedTheme)} + onPointerOver={titleClippedPierreTreeRow} /> {footer} diff --git a/apps/web/src/components/files/FileBrowserPanel.tsx b/apps/web/src/components/files/FileBrowserPanel.tsx index 1fee7db238727..cd44d99220939 100644 --- a/apps/web/src/components/files/FileBrowserPanel.tsx +++ b/apps/web/src/components/files/FileBrowserPanel.tsx @@ -27,7 +27,11 @@ import { useWorkspaceMutationRefresh } from "~/hooks/useWorkspaceMutationRefresh import { useFileContextMenu, type FileContextMenuAction } from "~/fileContextMenu"; import { readLocalApi } from "~/localApi"; import { T3_PIERRE_ICONS } from "~/pierre-icons"; -import { PIERRE_TREE_UNSAFE_CSS, pierreTreeStyle } from "~/pierre-tree-theme"; +import { + PIERRE_TREE_UNSAFE_CSS, + pierreTreeStyle, + titleClippedPierreTreeRow, +} from "~/pierre-tree-theme"; import { joinHostPath } from "./filePath"; import { createFileTreeDragMentionController } from "./fileTreeDragMention"; @@ -646,6 +650,7 @@ export default function FileBrowserPanel({ aria-label={gt("{projectName} files", { projectName })} className="min-h-0 flex-1 overflow-hidden" style={pierreTreeStyle(resolvedTheme)} + onPointerOver={titleClippedPierreTreeRow} /> )} diff --git a/apps/web/src/pierre-tree-theme.ts b/apps/web/src/pierre-tree-theme.ts index ada2a7d1abc7b..7deb41db7dcf0 100644 --- a/apps/web/src/pierre-tree-theme.ts +++ b/apps/web/src/pierre-tree-theme.ts @@ -1,4 +1,4 @@ -import type { CSSProperties } from "react"; +import type { CSSProperties, PointerEvent } from "react"; export const PIERRE_TREE_UNSAFE_CSS = ` :host { @@ -27,3 +27,20 @@ export function pierreTreeStyle(colorScheme: "light" | "dark"): CSSProperties { ["--trees-status-ignored-override" as string]: "var(--contrast-muted-foreground)", }; } + +// Clipped labels are unreadable and the tree cannot scroll sideways, so a clipped row gets its full name as a native tooltip. +export function titleClippedPierreTreeRow(event: PointerEvent) { + const row = event.nativeEvent + .composedPath() + .find( + (node): node is HTMLElement => + node instanceof HTMLElement && node.matches("button[data-type='item']"), + ); + if (!row) return; + const label = row.getAttribute("aria-label"); + const clipped = Array.from( + row.querySelectorAll("[data-truncate-content='visible']"), + ).some((element) => element.scrollWidth > element.clientWidth); + if (label && clipped) row.title = label; + else row.removeAttribute("title"); +} From 66441268e800dc7a73acd71810e34e6fa4b82e32 Mon Sep 17 00:00:00 2001 From: gero3 Date: Sat, 21 Nov 2026 13:39:40 +0100 Subject: [PATCH 010/324] fix(cli): update Windows launchers outside PATH (#40309) Co-authored-by: Julius Marminge --- apps/server/src/cli/update.test.ts | 26 ++++++++++++++++++++++++++ apps/server/src/cli/update.ts | 28 ++++++++++++++++++++++------ 2 files changed, 48 insertions(+), 6 deletions(-) diff --git a/apps/server/src/cli/update.test.ts b/apps/server/src/cli/update.test.ts index b5d3394f23fd2..2de00fc24bf54 100644 --- a/apps/server/src/cli/update.test.ts +++ b/apps/server/src/cli/update.test.ts @@ -229,6 +229,32 @@ it.layer(NodeServices.layer)("t3 update launcher", (it) => { }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")), ); + it.effect("repoints a recorded Windows launcher outside PATH", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped(); + const baseDir = path.join(root, "home"); + const runtimeDir = path.join(baseDir, "runtime"); + const launcher = path.join(root, "custom bin", "t3.cmd"); + const launchedAs = path.join(runtimeDir, "versions", "1.0.0", "t3.exe"); + const targetEntryPath = path.join(runtimeDir, "versions", "2.0.0", "t3.exe"); + yield* fs.makeDirectory(runtimeDir, { recursive: true }); + yield* fs.makeDirectory(path.dirname(launcher), { recursive: true }); + yield* fs.writeFileString(launcher, `@echo off\r\n"${launchedAs}" %*`); + yield* fs.writeFileString(path.join(runtimeDir, "launchers"), `${launcher}\r\n`); + + const repointed = yield* repointLauncher({ launchedAs, baseDir, targetEntryPath }); + + assert.equal(Option.getOrUndefined(repointed), launcher); + assert.equal(yield* fs.readFileString(launcher), `@echo off\r\n"${targetEntryPath}" %*`); + }).pipe( + Effect.scoped, + Effect.provideService(HostProcess.Platform, "win32"), + Effect.provideService(HostProcess.Environment, { PATH: "" }), + ), + ); + it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( "finds the script that ran this executable and rewrites it, keeping aliases and arguments", () => diff --git a/apps/server/src/cli/update.ts b/apps/server/src/cli/update.ts index b7b76f2f34223..07f3458fb3b66 100644 --- a/apps/server/src/cli/update.ts +++ b/apps/server/src/cli/update.ts @@ -25,6 +25,7 @@ import * as BootService from "../cloud/bootService.ts"; import { ensurePinnedRuntimeInstalled, findPosixLauncher, + generatedWindowsShimTarget, launcherOwnsVersionsDir, isUnpublishedRelease, pinnedRuntimePaths, @@ -171,7 +172,7 @@ export const repointLauncher = Effect.fn("cli.update.repoint_launcher")(function ); if (platform === "win32") { - const shimPath = yield* findWindowsShim(input.launchedAs); + const shimPath = yield* findWindowsShim(input.launchedAs, versionsDir); if (shimPath === undefined) return Option.none(); const current = yield* fs.readFileString(shimPath).pipe(Effect.option); const quoted = Option.isSome(current) ? windowsShimTarget(current.value) : undefined; @@ -203,9 +204,10 @@ export const repointLauncher = Effect.fn("cli.update.repoint_launcher")(function return Option.some(launcher); }); -/** Windows executables see their own path, so find the installer shim by matching t3.cmd targets on PATH. */ +/** Windows executables see their own path, so locate the installer shim by matching its target. */ export const findWindowsShim = Effect.fn("cli.update.find_windows_shim")(function* ( executablePath: string, + versionsDir?: string, ) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -213,12 +215,26 @@ export const findWindowsShim = Effect.fn("cli.update.find_windows_shim")(functio const candidates = [ ...(environment["T3CODE_INSTALL_BIN_DIR"] ? [environment["T3CODE_INSTALL_BIN_DIR"]] : []), ...(environment["PATH"] ?? environment["Path"] ?? "").split(";"), - ].filter((entry) => entry.trim().length > 0); - for (const directory of candidates) { - const shimPath = path.join(directory, "t3.cmd"); + ] + .filter((entry) => entry.trim().length > 0) + .map((directory) => ({ + shimPath: path.join(directory, "t3.cmd"), + parseTarget: windowsShimTarget, + })); + if (versionsDir !== undefined) { + const recorded = yield* fs + .readFileString(path.join(path.dirname(versionsDir), "launchers")) + .pipe(Effect.orElseSucceed(() => "")); + for (const shimPath of recorded.split(/\r?\n/)) { + if (path.isAbsolute(shimPath) && path.basename(shimPath).toLowerCase() === "t3.cmd") { + candidates.push({ shimPath, parseTarget: generatedWindowsShimTarget }); + } + } + } + for (const { shimPath, parseTarget } of candidates) { const contents = yield* fs.readFileString(shimPath).pipe(Effect.option); if (Option.isNone(contents)) continue; - const target = windowsShimTarget(contents.value); + const target = parseTarget(contents.value); if ( target !== undefined && path.resolve(target).toLowerCase() === path.resolve(executablePath).toLowerCase() From 69228fe179815a9446531eb9cf73d8deaa26db4c Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:16:58 +0530 Subject: [PATCH 011/324] fix(server): typed-message commits stage the worktree once (#40282) Co-authored-by: Julius Marminge --- apps/server/src/git/GitManager.test.ts | 45 +++++++++++++ apps/server/src/git/GitManager.ts | 27 ++++++-- apps/server/src/vcs/GitVcsDriver.ts | 22 +++++- apps/server/src/vcs/GitVcsDriverCore.test.ts | 45 ++++++++++++- apps/server/src/vcs/GitVcsDriverCore.ts | 71 ++++++++++++++++++++ 5 files changed, 201 insertions(+), 9 deletions(-) diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index 0528d08f36c29..9dc3407597a4f 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -3584,6 +3584,51 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { }), ); + it.effect("stages the worktree once for a typed commit message", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + NodeFS.writeFileSync(NodePath.join(repoDir, "README.md"), "typed\n"); + const gitCommands: string[] = []; + const { manager } = yield* makeManager({ gitCommands }); + + const created = yield* runStackedAction(manager, { + cwd: repoDir, + action: "commit", + commitMessage: "Typed subject\n\nTyped body", + }); + + expect(created.commit).toMatchObject({ status: "created", subject: "Typed subject" }); + expect(gitCommands.filter((args) => args.endsWith("add -A"))).toHaveLength(1); + expect((yield* runGit(repoDir, ["log", "-1", "--pretty=%B"])).stdout.trim()).toBe( + "Typed subject\n\nTyped body", + ); + + // Status shows the staged change, but staging the reverted worktree leaves nothing. + NodeFS.writeFileSync(NodePath.join(repoDir, "README.md"), "staged\n"); + yield* runGit(repoDir, ["add", "README.md"]); + NodeFS.writeFileSync(NodePath.join(repoDir, "README.md"), "typed\n"); + const head = (yield* runGit(repoDir, ["rev-parse", "HEAD"])).stdout; + + const skipped = yield* runStackedAction(manager, { + cwd: repoDir, + action: "commit", + commitMessage: "Nothing to commit", + }); + + expect(skipped.commit.status).toBe("skipped_no_changes"); + expect((yield* runGit(repoDir, ["rev-parse", "HEAD"])).stdout).toBe(head); + expect((yield* runGit(repoDir, ["show", ":README.md"])).stdout).toBe("staged\n"); + + // A generated message already checked a scratch index, so staging again stays at two. + NodeFS.writeFileSync(NodePath.join(repoDir, "README.md"), "generated\n"); + gitCommands.length = 0; + const generated = yield* runStackedAction(manager, { cwd: repoDir, action: "commit" }); + expect(generated.commit.status).toBe("created"); + expect(gitCommands.filter((args) => args.endsWith("add -A"))).toHaveLength(2); + }), + ); + it.effect("lowercases a capitalized Conventional Commits description", () => Effect.gen(function* () { const repoDir = yield* makeTempDir("t3code-git-manager-"); diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index 118e4ffd461ae..9db4fbfc27755 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -2494,7 +2494,13 @@ export const make = Effect.gen(function* () { } as GitActionProgressEvent) : Effect.void; - let suggestion: CommitAndBranchSuggestion | null | undefined = preResolvedSuggestion; + const customCommit = parseCustomCommitMessage(commitMessage ?? ""); + let suggestion: CommitAndBranchSuggestion | null | undefined = + preResolvedSuggestion ?? + (customCommit && { + ...customCommit, + commitMessage: formatCommitMessage(customCommit.subject, customCommit.body), + }); if (!suggestion) { const needsGeneration = !commitMessage?.trim(); if (needsGeneration) { @@ -2566,11 +2572,20 @@ export const make = Effect.gen(function* () { }, } : null; - const { commitSha } = yield* gitCore.commit(cwd, suggestion.subject, suggestion.body, { - timeoutMs: COMMIT_TIMEOUT_MS, - stage: filePaths ? { filePaths } : {}, - ...(commitProgress ? { progress: commitProgress } : {}), - }); + const committed = yield* gitCore + .commit(cwd, suggestion.subject, suggestion.body, { + timeoutMs: COMMIT_TIMEOUT_MS, + stage: { + ...(filePaths ? { filePaths } : {}), + ...(!preResolvedSuggestion && customCommit ? { unverified: true } : {}), + }, + ...(commitProgress ? { progress: commitProgress } : {}), + }) + .pipe(Effect.catchTags({ GitNothingToCommitError: () => Effect.succeed(null) })); + if (!committed) { + return { status: "skipped_no_changes" as const }; + } + const { commitSha } = committed; if (currentHookName !== null) { yield* emit({ kind: "hook_finished", diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index 5164e6f4585c8..700ad3b3571c9 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -10,6 +10,7 @@ import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; import { ChildProcessSpawner } from "effect/process"; import { @@ -76,6 +77,19 @@ export interface ExecuteGitResult { readonly stderrTruncated: boolean; } +export class GitNothingToCommitError extends Schema.TaggedError()( + "GitNothingToCommitError", + { + operation: Schema.String, + cwd: Schema.String, + detail: Schema.String, + }, +) { + override get message(): string { + return `Nothing to commit in ${this.operation} (${this.cwd}): ${this.detail}`; + } +} + export interface GitStatusDetails { isRepo: boolean; sourceControlProvider?: VcsStatusResult["sourceControlProvider"]; @@ -173,7 +187,11 @@ export interface GitCommitProgress { export interface GitCommitOptions { readonly timeoutMs?: number; readonly progress?: GitCommitProgress; - readonly stage?: { readonly filePaths?: readonly string[] }; + readonly stage?: { + readonly filePaths?: readonly string[]; + /** The caller has not run `prepareCommitContext`, so an empty result must keep the index. */ + readonly unverified?: boolean; + }; } export interface GitDeleteLocalBranchInput { @@ -361,7 +379,7 @@ export class GitVcsDriver extends Context.Service< subject: string, body: string, options?: GitCommitOptions, - ) => Effect.Effect<{ commitSha: string }, GitCommandError>; + ) => Effect.Effect<{ commitSha: string }, GitCommandError | GitNothingToCommitError>; readonly pushCurrentBranch: ( cwd: string, fallbackBranch: string | null, diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index e23343ed67165..8789b54d31562 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -8621,6 +8621,17 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { assert.notInclude(context?.stagedSummary ?? "", "b.txt"); assert.equal(yield* git(repository, ["diff", "--cached", "--name-only"]), ""); + // A selected file staged and then reverted stages to nothing, like git commit --only. + const head = yield* git(repository, ["rev-parse", "HEAD"]); + yield* writeTextFile(repository, "README.md", "staged\n"); + yield* git(repository, ["add", "README.md"]); + yield* git(repository, ["restore", "--source=HEAD", "--worktree", "--", "README.md"]); + const empty = yield* driver + .commit(cwd, "Empty", "", { stage: { filePaths: ["README.md"] } }) + .pipe(Effect.flip); + assert.equal(empty._tag, "GitNothingToCommitError"); + assert.equal(yield* git(repository, ["rev-parse", "HEAD"]), head); + const commit = yield* driver.commit(cwd, "Add a", "", { stage: { filePaths: [selected] }, }); @@ -8840,6 +8851,8 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { // A branch named MERGE_HEAD is not a merge in progress. yield* git(cwd, ["branch", "MERGE_HEAD"]); assert.isNull(yield* driver.prepareCommitContext(cwd, undefined, { includePatch: false })); + const empty = yield* driver.commit(cwd, "Empty", "", { stage: {} }).pipe(Effect.flip); + assert.equal(empty._tag, "GitNothingToCommitError"); yield* git(cwd, ["branch", "-D", "MERGE_HEAD"]); yield* git(cwd, ["checkout", "-b", "feature"]); yield* writeTextFile(cwd, "README.md", "feature version\n"); @@ -8859,6 +8872,13 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { assert.isNotNull( yield* driver.prepareCommitContext(cwd, undefined, { includePatch: false }), ); + const mainHead = yield* git(cwd, ["rev-parse", "HEAD"]); + const featureHead = yield* git(cwd, ["rev-parse", "feature"]); + yield* driver.commit(cwd, "Merge feature", "", { stage: {} }); + assert.equal( + yield* git(cwd, ["show", "-s", "--format=%P", "HEAD"]), + `${mainHead} ${featureHead}`, + ); }), ); @@ -9004,6 +9024,9 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { yield* writeTextFile(cwd, "README.md", "stashed version\n"); yield* git(cwd, ["stash"]); yield* writeTextFile(cwd, "README.md", "committed version\n"); + yield* writeTextFile(cwd, "same.txt", "same\n"); + yield* writeTextFile(cwd, "gone.txt", "gone\n"); + yield* git(cwd, ["add", "same.txt", "gone.txt"]); yield* git(cwd, ["commit", "-am", "Change README"]); const pop = yield* driver.execute({ operation: "test.stashPop", @@ -9012,9 +9035,29 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { allowNonZeroExit: true, }); assert.equal(pop.exitCode, 1); + const unmerged = yield* git(cwd, ["ls-files", "--unmerged"]); + + // A selected file staged and then reverted has nothing to commit despite the conflict. + const unchangedHead = yield* git(cwd, ["rev-parse", "HEAD"]); + yield* writeTextFile(cwd, "same.txt", "staged\n"); + yield* git(cwd, ["add", "same.txt"]); + yield* git(cwd, ["restore", "--source=HEAD", "--worktree", "--", "same.txt"]); + const empty = yield* driver + .commit(cwd, "Empty", "", { stage: { filePaths: ["same.txt"] } }) + .pipe(Effect.flip); + assert.equal(empty._tag, "GitNothingToCommitError"); + assert.equal(yield* git(cwd, ["rev-parse", "HEAD"]), unchangedHead); + assert.equal(yield* git(cwd, ["ls-files", "--unmerged"]), unmerged); + + yield* (yield* FileSystem.FileSystem).remove((yield* Path.Path).join(cwd, "gone.txt")); + yield* driver.commit(cwd, "Remove gone", "", { stage: { filePaths: ["gone.txt"] } }); + assert.equal( + yield* git(cwd, ["show", "--pretty=", "--name-status", "HEAD"]), + "D\tgone.txt", + ); + yield* writeTextFile(cwd, "other.txt", "other\n"); const head = yield* git(cwd, ["rev-parse", "HEAD"]); - const unmerged = yield* git(cwd, ["ls-files", "--unmerged"]); const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const nested = path.join(cwd, "nested"); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index ab9b10563c690..27927f5dc5c8b 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -3399,10 +3399,81 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* body, options?: GitVcsDriver.GitCommitOptions, ) { + const diffCached = [ + "-c", + "diff.relative=false", + "diff", + "--cached", + "--no-ext-diff", + "--no-textconv", + ]; + if (options?.stage?.unverified) { + const indexMatchesHead = + (yield* executeGit("GitVcsDriver.commit.indexChanges", cwd, [...diffCached, "--quiet"], { + allowNonZeroExit: true, + })).exitCode === 0; + // Staging an empty result would overwrite what is already staged, so check a scratch index. + if ( + !indexMatchesHead && + (yield* prepareCommitContext(cwd, options.stage.filePaths, { includePatch: false })) === + null + ) { + return yield* new GitVcsDriver.GitNothingToCommitError({ + operation: "GitVcsDriver.commit", + cwd, + detail: "Staging found no changes.", + }); + } + } const partialCommitPaths = options?.stage !== undefined ? yield* stageCommitChanges(cwd, options.stage.filePaths) : undefined; + // Preserved unselected conflicts always show as index changes, so only selected paths count. + const selectedPaths = partialCommitPaths && new Set(options?.stage?.filePaths); + const hasStagedChanges = selectedPaths + ? (yield* runGitStdoutWithOptions( + "GitVcsDriver.commit.stagedChanges", + cwd, + [...diffCached, "--no-renames", "--name-only", "-z"], + { maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES }, + )) + .split("\0") + .some((file) => file.length > 0 && selectedPaths.has(file)) + : (yield* executeGit("GitVcsDriver.commit.stagedChanges", cwd, [...diffCached, "--quiet"], { + allowNonZeroExit: true, + })).exitCode !== 0; + if (!hasStagedChanges) { + // Like git commit, a merge resolved to HEAD's tree still records its merge commit. + const mergeHeadPath = yield* runGitStdout("GitVcsDriver.commit.mergeHead", cwd, [ + "rev-parse", + "--git-path", + "MERGE_HEAD", + ]); + const merging = yield* fileSystem.realPath(cwd).pipe( + Effect.orElseSucceed(() => cwd), + Effect.flatMap((physicalCwd) => + fileSystem.exists(path.resolve(physicalCwd, mergeHeadPath.trim())), + ), + Effect.mapError( + (cause) => + new GitCommandError({ + operation: "GitVcsDriver.commit.mergeHead", + command: "git commit", + cwd, + detail: "Could not check whether a merge is in progress.", + cause, + }), + ), + ); + if (!merging) { + return yield* new GitVcsDriver.GitNothingToCommitError({ + operation: "GitVcsDriver.commit", + cwd, + detail: "Staging found no changes.", + }); + } + } const args = ["commit", "-m", subject]; const trimmedBody = body.trim(); if (trimmedBody.length > 0) { From 7ef7ba0e3b1bc0582e44f1379bff1cc5559cf0d2 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 04:49:13 -0800 Subject: [PATCH 012/324] perf(server): a tracked file's Diff panel patch skips the untracked-file listing (#40304) --- .../src/features/review/useReviewDiffData.ts | 1 + apps/server/src/vcs/GitVcsDriverCore.test.ts | 54 ++++++++++++++++++- apps/server/src/vcs/GitVcsDriverCore.ts | 26 +++++++-- .../components/diffs/useReviewFilePatches.ts | 1 + packages/contracts/src/review.ts | 20 +++---- 5 files changed, 88 insertions(+), 14 deletions(-) diff --git a/apps/mobile/src/features/review/useReviewDiffData.ts b/apps/mobile/src/features/review/useReviewDiffData.ts index 35cf8f2f14b3c..d530279f8ca25 100644 --- a/apps/mobile/src/features/review/useReviewDiffData.ts +++ b/apps/mobile/src/features/review/useReviewDiffData.ts @@ -219,6 +219,7 @@ export function useReviewDiffData(input: { file: { path: file.path, previousPath: file.previousPath, + ...(file.changeType ? { changeType: file.changeType } : {}), sourceKind: lazySource.kind, }, }, diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 8789b54d31562..e745669fda5c2 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -3463,7 +3463,12 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { const scoped = yield* driver.getReviewDiffPreview({ cwd: projectDirectory, baseRef: initialBranch, - file: { path: file.path, previousPath: file.previousPath, sourceKind: source.kind }, + file: { + path: file.path, + previousPath: file.previousPath, + sourceKind: source.kind, + ...(file.changeType ? { changeType: file.changeType } : {}), + }, }); const patch = scoped.sources.find((item) => item.kind === source.kind)!; assert.deepStrictEqual(patch.files, [file]); @@ -3474,6 +3479,53 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect( + "lists untracked files for a file the preview called tracked only when it is not", + () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + yield* writeTextFile(cwd, "tracked.txt", "one\n"); + yield* git(cwd, ["add", "."]); + yield* git(cwd, ["commit", "-m", "tracked"]); + yield* writeTextFile(cwd, "tracked.txt", "two\n"); + yield* writeTextFile(cwd, "README.md", "dirty\n"); + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + let listings = 0; + const spawner = ChildProcessSpawner.make((command) => { + if (ChildProcess.isStandardCommand(command) && command.args.includes("--others")) { + listings++; + } + return delegate.spawn(command); + }); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + const read = (path: string, changeType?: "change") => + driver + .getReviewDiffPreview({ + cwd, + file: { + path, + previousPath: null, + sourceKind: "working-tree", + ...(changeType ? { changeType } : {}), + }, + }) + .pipe(Effect.map((preview) => preview.sources[0]!)); + + const tracked = yield* read("tracked.txt", "change"); + assert.include(tracked.diff, "+two"); + assert.equal(listings, 0); + + // A stale hint: the file left the index after the preview listed it. + yield* git(cwd, ["rm", "--cached", "-q", "README.md"]); + const stale = yield* read("README.md", "change"); + assert.equal(listings, 1); + assert.deepStrictEqual(stale, yield* read("README.md")); + }), + ); + it.effect("rejects a file selector for a different source than the request", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 27927f5dc5c8b..7c4363b1647be 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -4788,13 +4788,30 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* exitCode: result.exitCode, }); }); + // A file the preview did not list as new is stat-ed against the real index first. `git diff` + // lists an indexed path as anything but deleted, and `ls-files --others` never lists one. + const indexedRef = + input.file && !input.trackedOnly && input.file.changeType && input.file.changeType !== "new" + ? (dirtyRef ?? review.mergeBase) + : null; + const indexedStat = indexedRef === null ? undefined : yield* readStats(indexedRef); + const indexed = + indexedStat?.files.some( + (file) => + file.path === input.file?.path && + file.changeType !== undefined && + file.changeType !== "deleted", + ) === true; const readTrackedDiff = Effect.fn("GitVcsDriver.getReviewDiffPreview.tracked")(function* ( ref: string | null, env?: NodeJS.ProcessEnv, metadataOnly = false, ) { if (ref === null) return { stdout: "", stdoutTruncated: false, files: [] }; - const stat = yield* readStats(ref, env); + const stat = + env === undefined && ref === indexedRef && indexedStat !== undefined + ? indexedStat + : yield* readStats(ref, env); if (metadataOnly || stat.files.length === 0) { return { stdout: "", stdoutTruncated: false, files: stat.files }; } @@ -4807,9 +4824,10 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return { ...patch, files: stat.files }; }); const [dirtyTrackedResult, baseResult] = yield* Effect.gen(function* () { - const untracked = input.trackedOnly - ? { env: undefined, omitted: false } - : yield* prepareUntrackedReviewIndex(cwd, pathArgs, input.file?.path); + const untracked = + input.trackedOnly || indexed + ? { env: undefined, omitted: false } + : yield* prepareUntrackedReviewIndex(cwd, pathArgs, input.file?.path); // Untracked files left out make the file list partial, so the bounded patch is sent instead. const complete = untracked !== null && !untracked.omitted; // With no untracked files to add, the tracked read already is the complete diff. diff --git a/apps/web/src/components/diffs/useReviewFilePatches.ts b/apps/web/src/components/diffs/useReviewFilePatches.ts index 94fee877f0f4b..0c889d501264d 100644 --- a/apps/web/src/components/diffs/useReviewFilePatches.ts +++ b/apps/web/src/components/diffs/useReviewFilePatches.ts @@ -206,6 +206,7 @@ function reviewFileQueries({ file: { path: file.path, previousPath: file.previousPath, + ...(file.changeType ? { changeType: file.changeType } : {}), sourceKind: source.kind, }, }, diff --git a/packages/contracts/src/review.ts b/packages/contracts/src/review.ts index ab5cae42624d4..d43946e217219 100644 --- a/packages/contracts/src/review.ts +++ b/packages/contracts/src/review.ts @@ -8,6 +8,15 @@ const ReviewMergeBase = Schema.String.check( Schema.isPattern(/^(?:[0-9a-f]{40}|[0-9a-f]{64}|HEAD)$/), ); +export const ReviewDiffChangeType = Schema.Literals([ + "change", + "rename-pure", + "rename-changed", + "new", + "deleted", +]); +export type ReviewDiffChangeType = typeof ReviewDiffChangeType.Type; + export const ReviewDiffPreviewInput = Schema.Struct({ cwd: TrimmedNonEmptyString, baseRef: Schema.optional(TrimmedNonEmptyString), @@ -25,6 +34,8 @@ export const ReviewDiffPreviewInput = Schema.Struct({ path: Schema.NonEmptyString, previousPath: Schema.NullOr(Schema.NonEmptyString), sourceKind: Schema.Literals(["working-tree", "branch-range", "commit"]), + // The preview's change type; the server still confirms a tracked path before relying on it. + changeType: Schema.optionalKey(ReviewDiffChangeType), }), ), }); @@ -55,15 +66,6 @@ export const ReviewDiffPreviewSourceKind = Schema.Literals([ ]); export type ReviewDiffPreviewSourceKind = typeof ReviewDiffPreviewSourceKind.Type; -export const ReviewDiffChangeType = Schema.Literals([ - "change", - "rename-pure", - "rename-changed", - "new", - "deleted", -]); -export type ReviewDiffChangeType = typeof ReviewDiffChangeType.Type; - export const ReviewDiffFileStat = Schema.Struct({ path: Schema.String, previousPath: Schema.NullOr(Schema.String), From 0775dc450fcf4a6f85cc7db955f3c5b5f7d4f42a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 04:57:44 -0800 Subject: [PATCH 013/324] fix(mobile): mark the linked line in the native source viewer (#40295) --- .../main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt | 3 ++- apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt index 8b0a84a952caf..e2d5a12d76304 100644 --- a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt +++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt @@ -1314,12 +1314,13 @@ private class DiffCanvasView(context: Context) : View(context) { } val selected = selectedRowIds.contains(row.id) if (selected) { + // Source files hide the change bar (width 0); the selection marker still needs to show. fill( canvas, withAlpha(theme.hunkText, 242), 0f, top.toFloat(), - style.changeBarWidthPx, + maxOf(style.changeBarWidthPx, 4f * density), bottom.toFloat() ) } diff --git a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift index 7fe4a068f9bbb..0c65ddf19460a 100644 --- a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift +++ b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift @@ -2661,8 +2661,9 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { return } + // Source files hide the change bar (width 0); the selection marker still needs to show. theme.hunkText.withAlphaComponent(0.95).setFill() - context.fill(CGRect(x: 0, y: rect.minY, width: style.changeBarWidth, height: rect.height)) + context.fill(CGRect(x: 0, y: rect.minY, width: max(style.changeBarWidth, 4), height: rect.height)) } private func drawWordDiffRanges( From c3853775447b466b402f38452ce81bcb1617e491 Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:40:15 +0530 Subject: [PATCH 014/324] fix(server): slash commands sent during a turn wait instead of steering (#40316) Co-authored-by: Julius Marminge --- .../orchestration-v2/CommandPolicy.test.ts | 24 +++ .../src/orchestration-v2/CommandPolicy.ts | 20 +++ .../src/orchestration-v2/Orchestrator.ts | 66 +++++++-- .../SteeringCompletion.integration.test.ts | 138 +++++++++++++++--- .../ThreadLaunchService.test.ts | 2 +- .../src/components/chat/QueuedRunsControl.tsx | 31 ++-- apps/web/src/i18n/translations/de.json | 4 +- apps/web/src/i18n/translations/en.json | 4 +- apps/web/src/i18n/translations/es.json | 4 +- apps/web/src/i18n/translations/fr.json | 4 +- apps/web/src/i18n/translations/ja.json | 4 +- apps/web/src/i18n/translations/ko.json | 4 +- apps/web/src/i18n/translations/pt-BR.json | 4 +- apps/web/src/i18n/translations/ru.json | 4 +- apps/web/src/i18n/translations/sv.json | 4 +- apps/web/src/i18n/translations/zh.json | 4 +- docs/user/composer.md | 9 +- packages/shared/src/composerTrigger.ts | 8 + .../steered-compact-waits-for-turn.e2e.ts | 71 +++++++++ 19 files changed, 353 insertions(+), 56 deletions(-) create mode 100644 scripts/scenarios/steered-compact-waits-for-turn.e2e.ts diff --git a/apps/server/src/orchestration-v2/CommandPolicy.test.ts b/apps/server/src/orchestration-v2/CommandPolicy.test.ts index e9f829524948b..d5b06dbf6c47f 100644 --- a/apps/server/src/orchestration-v2/CommandPolicy.test.ts +++ b/apps/server/src/orchestration-v2/CommandPolicy.test.ts @@ -252,6 +252,30 @@ it("steers a Grok follow-up into its running turn without restarting it", () => assert.isTrue(grok.turns.supportsActiveSteering); }); +// regression: #32606 a slash command steered into a running turn replaced the task +it.each([ + ["/compact", { type: "queue_after_active" }], + ["/context", { type: "queue_after_active" }], + [" /context all\n", { type: "queue_after_active" }], + ["/plugin:review-pr 12", { type: "queue_after_active" }], + ["/home/me/x.ts fails", { type: "steer_active", targetRunId: activeRunId }], + ["/ context", { type: "steer_active", targetRunId: activeRunId }], + ["$skill /context", { type: "steer_active", targetRunId: activeRunId }], +] as const)("steers %j only when it is not a slash command", (text, expected) => { + const projection = dispatchProjection(baseCapabilities); + for (const deliveryIntent of ["auto", "steer"] as const) { + assert.deepEqual( + CommandPolicy.resolveMessageDispatch(projection, { + dispatchMode: { type: "start_immediately" }, + deliveryIntent, + text, + attachments: [], + }), + expected, + ); + } +}); + it.each(["/compact", " /LOGOUT "])("queues a steer sent while %s runs", (text) => { const projection = dispatchProjection(baseCapabilities); const maintenance = { diff --git a/apps/server/src/orchestration-v2/CommandPolicy.ts b/apps/server/src/orchestration-v2/CommandPolicy.ts index 451ca978b9e51..1319083cca030 100644 --- a/apps/server/src/orchestration-v2/CommandPolicy.ts +++ b/apps/server/src/orchestration-v2/CommandPolicy.ts @@ -10,6 +10,7 @@ import { ProviderInstanceId, ThreadId, } from "@t3tools/contracts"; +import { isSlashCommand } from "@t3tools/shared/composerTrigger"; import { latestExecutedRun } from "@t3tools/shared/orchestrationV2ThreadError"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; @@ -101,6 +102,25 @@ export function goalCommandStopsActiveRun( } } +export function resolveMessageDispatch( + projection: OrchestrationV2ThreadProjection, + message: Pick< + Extract, + "dispatchMode" | "deliveryIntent" | "text" | "attachments" + >, +): MessageDispatchMode { + const mode = resolveMessageDispatchIntent( + projection, + message.dispatchMode, + message.deliveryIntent, + ); + // A provider runs a steered command in place of the turn's task, so commands wait. + return mode.type === "steer_active" && isSlashCommand(message) + ? { type: "queue_after_active" } + : mode; +} + +/** How a message joins active work when it is free to steer. */ export function resolveMessageDispatchIntent( projection: OrchestrationV2ThreadProjection, requestedMode: MessageDispatchMode, diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 00939843c13f1..e27fe09d07d1b 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -92,6 +92,7 @@ import { isPlaceholderThreadTitle } from "./placeholderThreadTitle.ts"; import { combinePullRequestWatchWakes, type PullRequestWatchWake } from "./pullRequestWatch.ts"; import { outputRequestProblem } from "./runOutput.ts"; import { recordThreadOpen } from "@t3tools/shared/paletteSearch"; +import { isSlashCommand } from "@t3tools/shared/composerTrigger"; import { backgroundWorkHoldsCompletion, derivePendingBackgroundWork, @@ -126,6 +127,7 @@ import { isNativeMaintenanceCommand, providerSwitchWaitsForTurn, providerTurnCapabilities, + resolveMessageDispatch, resolveMessageDispatchIntent, } from "./CommandPolicy.ts"; import { CommandReceiptStoreV2, type CommandReceiptV2 } from "./CommandReceiptStore.ts"; @@ -6308,6 +6310,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); } yield* ensureSteeringMessage(input.command, input); + // An explicit restart already gives up the turn, so only steering holds commands back. + if (!input.forceRestart && isSlashCommand(input)) { + return yield* new OrchestratorDispatchError({ + commandId: input.command.commandId, + commandType: input.command.type, + cause: + "Commands must run as a separate turn. Queue it or wait for the active turn to finish.", + }); + } const targetMessage = input.projection.messages.find( (message) => message.id === targetRun.userMessageId, ); @@ -7416,11 +7427,18 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio projection = applyToProjection(projection, event); } let modelSelection = command.modelSelection ?? projection.thread.modelSelection; - let dispatchMode = resolveMessageDispatchIntent( - projection, - command.dispatchMode, - command.deliveryIntent, - ); + // Native goal commands must not steer an existing turn. + const parsedGoalCommand = parseGoalCommand(command); + const goalCommand = + parsedGoalCommand === null || + (yield* goalDriverFor(command, modelSelection.instanceId)) === undefined + ? null + : parsedGoalCommand; + // A goal command keeps the run it was sent at; the goal handling below queues it. + let dispatchMode = + goalCommand === null + ? resolveMessageDispatch(projection, command) + : resolveMessageDispatchIntent(projection, command.dispatchMode, command.deliveryIntent); if (dispatchMode.type === "steer_active" || dispatchMode.type === "restart_active") { const targetRunId = dispatchMode.targetRunId; const target = projection.runs.find((run) => run.id === targetRunId); @@ -7515,13 +7533,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ) { dispatchMode = { type: "queue_after_active" }; } - // Native goal commands must not steer an existing turn. - const parsedGoalCommand = parseGoalCommand(command); - const goalCommand = - parsedGoalCommand === null || - (yield* goalDriverFor(command, modelSelection.instanceId)) === undefined - ? null - : parsedGoalCommand; let queuedRunStop: | { readonly runId: RunId; readonly reason: string; readonly skipsHeldQueue?: true } | undefined; @@ -7672,6 +7683,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const commandNotice = noticeKind === "command" && command.creationSource === "server"; if ( !freshContext && + // Steering refuses a command, so a notice that reads like one stays queued. + !isSlashCommand(command) && (delegatedCompletion !== undefined ? delegatedCompletion.taskIds.every( (id) => @@ -11856,8 +11869,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio cause: "A message that asks for a result can't steer the current turn.", }); } - if (goalCommand !== null) { - yield* ensureGoalCommandSupported(command, queuedMessage, modelSelection.instanceId); + // A steered command replaces the turn's task, so promoting one only moves it first. + if (goalCommand !== null || isSlashCommand(queuedMessage)) { + if (goalCommand !== null) { + yield* ensureGoalCommandSupported(command, queuedMessage, modelSelection.instanceId); + } const goal = projection.providerThreads.find( (candidate) => candidate.id === target?.providerThreadId, )?.goal; @@ -11871,6 +11887,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio payload: { ...queuedRun, queuePosition: 1 }, }); const stops = + goalCommand !== null && target !== undefined && isLiveRun(target) && goalCommandStopsActiveRun(goalCommand, goal?.status ?? null) && @@ -12298,6 +12315,25 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }), }); } + // A command cannot steer, so an edit into one keeps it queued where it is. + if ( + queuedRun.steerWhenReadyRunId !== undefined && + isSlashCommand({ + text: command.text, + attachments: command.attachments ?? queuedMessage.attachments, + }) + ) { + const { steerWhenReadyRunId: _, ...queued } = queuedRun; + yield* emitEvent({ + type: "run.updated", + threadId: command.threadId, + runId: queuedRun.id, + ...(queuedRun.rootNodeId === null ? {} : { nodeId: queuedRun.rootNodeId }), + providerInstanceId: queuedRun.providerInstanceId, + occurredAt: now, + payload: queued, + }); + } // Thread deletion only cleans files the thread still references. const keptAttachmentIds = new Set( (command.attachments ?? queuedMessage.attachments).map((attachment) => attachment.id), @@ -14182,7 +14218,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ), ); - /** Puts a queued goal command first and, given a target, stops the run in its way. */ + /** Puts a queued command first and, given a target, stops the run in its way. */ const stopRunForQueuedCommand = Effect.fn("Orchestrator.stopRunForQueuedCommand")( function* (input: { readonly command: Extract< diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index cc14fde257da8..3ef67192ceb77 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -711,14 +711,15 @@ const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function* it.effect.each([ { notice: "delegated task question", goal: null, steers: true }, + { notice: "delegated task question", goal: null, steers: false, summary: "/review is ready" }, { notice: "background command", goal: "active", steers: true }, { notice: "background command", goal: null, steers: false }, ] as const)( "a $notice notice steers into the running turn: $steers (goal $goal)", - ({ notice, goal, steers }) => + ({ notice, goal, steers, ...row }) => Effect.gen(function* () { const { started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness( - `notice-steer-${notice.replaceAll(" ", "-")}-${goal ?? "none"}`, + `notice-steer-${notice.replaceAll(" ", "-")}-${goal ?? "none"}-${steers}`, ); yield* Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; @@ -762,7 +763,7 @@ it.effect.each([ childThreadId: ThreadId.make("thread:question-child"), }, outcome: "updated" as const, - summary: "Delegated task has a question", + summary: "summary" in row ? row.summary : "Delegated task has a question", } : { source: { kind: "command" as const }, @@ -945,6 +946,7 @@ it.effect.each( const edited = (yield* orchestrator.getThreadProjection(threadId)).runs.find( (candidate) => candidate.userMessageId === MessageId.make("message:edited-steer"), )!; + assert.equal(edited.steerWhenReadyRunId, run.id); yield* orchestrator.dispatch({ type: "queued-run.edit", commandId: CommandId.make("edit-steer-to-compact"), @@ -952,6 +954,11 @@ it.effect.each( runId: edited.id, text: "/compact", }); + const compact = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (candidate) => candidate.id === edited.id, + )!; + assert.isUndefined(compact.steerWhenReadyRunId); + assert.equal(compact.queuePosition, edited.queuePosition); } if (direct) { yield* orchestrator.dispatch({ @@ -998,16 +1005,18 @@ it.effect.each( const maintenance = (yield* orchestrator.getThreadProjection(threadId)).runs.find( (candidate) => candidate.userMessageId === MessageId.make(`message:${text}`), )!; - const error = yield* orchestrator - .dispatch({ - type: "queued-message.promote-to-steer", - commandId: CommandId.make(`promote-${text}`), - threadId, - queuedRunId: maintenance.id, - targetRunId: run.id, - }) - .pipe(Effect.flip); - assert.equal(error._tag, "OrchestratorDispatchError"); + yield* orchestrator.dispatch({ + type: "queued-message.promote-to-steer", + commandId: CommandId.make(`promote-${text}`), + threadId, + queuedRunId: maintenance.id, + targetRunId: run.id, + }); + const promoted = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (candidate) => candidate.id === maintenance.id, + )!; + assert.equal(promoted.status, "queued"); + assert.equal(promoted.queuePosition, 1); } const command = { type: "queued-message.promote-to-steer" as const, @@ -3165,15 +3174,12 @@ it.effect.each([undefined, false, true])( const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; const threadId = yield* startFirstTurn; yield* send("queued", "queued", "queue"); - const sending = send("goal", "/goal all tests pass", "auto"); - if (nativeGoals === false) { - yield* Effect.flip(sending); - } else yield* sending; + yield* send("goal", "/goal all tests pass", "auto"); yield* worker.drain(); assert.deepEqual(steered, []); assert.deepEqual(yield* read(threadId), { - queue: ["queued"], + queue: nativeGoals === false ? ["queued", "/goal all tests pass"] : ["queued"], started: nativeGoals === false ? ["first"] : ["first", "/goal all tests pass"], stopRequested: nativeGoals !== false, }); @@ -3472,6 +3478,70 @@ it.effect("queues a goal clear without stopping work when no goal drives it", () }), ); +it.effect("promoting a queued /context moves it first and does not steer", () => + Effect.gen(function* () { + const { started, steered, layer, startFirstTurn, send, read } = + yield* goalHarness("slash-promote"); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + yield* send("queued", "queued", "queue"); + yield* send("context", "/context", "queue"); + const queuedRun = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.userMessageId === MessageId.make("message:context"), + )!; + yield* orchestrator.dispatch({ + type: "queued-message.promote-to-steer", + commandId: CommandId.make("promote"), + threadId, + queuedRunId: queuedRun.id, + targetRunId: started[0]!.runId, + }); + yield* worker.drain(); + + assert.deepEqual(steered, []); + assert.deepEqual(yield* read(threadId), { + queue: ["/context", "queued"], + started: ["first"], + stopRequested: false, + }); + }).pipe(Effect.provide(layer)); + }), +); + +it.effect("restarts the turn for a slash command sent as an explicit restart", () => + Effect.gen(function* () { + const { started, steered, interrupted, layer, startFirstTurn } = + yield* nextTurnSelectionHarness("slash-restart", true); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("restart-context"), + threadId, + messageId: MessageId.make("message:restart-context"), + text: "/context", + attachments: [], + modelSelection: runSelection, + dispatchMode: { type: "restart_active", targetRunId: started[0]!.runId }, + createdBy: "user", + creationSource: "web", + }); + yield* worker.drain(); + + assert.deepEqual(steered, []); + assert.lengthOf(interrupted, 1); + assert.deepEqual( + started.map((turn) => turn.message.text), + ["first", "/context"], + ); + }).pipe(Effect.provide(layer)); + }), +); + it.effect("promotes a queued goal by stopping the running turn", () => Effect.gen(function* () { const { started, steered, layer, startFirstTurn, send, read } = @@ -3504,6 +3574,38 @@ it.effect("promotes a queued goal by stopping the running turn", () => }), ); +it.effect("stops the running turn for a goal an agent steers into it", () => + Effect.gen(function* () { + const { started, steered, layer, startFirstTurn, read } = yield* goalHarness("goal-raw-steer"); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + // Agent sends carry a raw steer target and no delivery intent. + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("goal"), + threadId, + messageId: MessageId.make("message:goal"), + text: "/goal ship it", + attachments: [], + modelSelection: runSelection, + dispatchMode: { type: "steer_active", targetRunId: started[0]!.runId }, + createdBy: "agent", + creationSource: "server", + }); + yield* worker.drain(); + + assert.deepEqual(steered, []); + assert.deepEqual(yield* read(threadId), { + queue: [], + started: ["first", "/goal ship it"], + stopRequested: true, + }); + }).pipe(Effect.provide(layer)); + }), +); + // A fresh message skips compaction as its own turn, which steering a running turn would not. it.effect.each(["next", "/goal ship it", "fresh next"])( "promoting %s into a compaction stops it and sends it next", diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts index 2a3a8e5510550..73eaabdde2016 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts @@ -913,7 +913,7 @@ it.effect("keeps native maintenance commands out of steering and restart message attachments: [], dispatchMode: { type: scenario.mode, targetRunId: targetRun.id }, }); - if (scenario.name.startsWith("steer-")) { + if (scenario.mode === "steer_active") { yield* dispatch; const queued = (yield* threads.getThreadProjection(launched.threadId)).runs[1]; assert.equal(queued?.status, "queued"); diff --git a/apps/web/src/components/chat/QueuedRunsControl.tsx b/apps/web/src/components/chat/QueuedRunsControl.tsx index fb82f9c858d61..d8318b7279e7d 100644 --- a/apps/web/src/components/chat/QueuedRunsControl.tsx +++ b/apps/web/src/components/chat/QueuedRunsControl.tsx @@ -5,16 +5,18 @@ import { } from "@t3tools/client-runtime/state/runtime"; import { deriveThreadQueueWorkflowState } from "@t3tools/client-runtime/state/thread-workflows"; import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations"; +import { isSlashCommand } from "@t3tools/shared/composerTrigger"; import { isAttachmentOnlyBootstrapPrompt, replaceComposerContextReferences, } from "@t3tools/shared/composerContextReferences"; -import type { - ChatAttachment as ContractChatAttachment, - EnvironmentId, - MessageId, - RunId, - ThreadId, +import { + parseGoalCommand, + type ChatAttachment as ContractChatAttachment, + type EnvironmentId, + type MessageId, + type RunId, + type ThreadId, } from "@t3tools/contracts"; import { resolveUserMessagePresentation } from "@t3tools/client-runtime/user-message"; import { Link } from "@tanstack/react-router"; @@ -273,6 +275,9 @@ export function QueuedRunsControl({ replaceComposerContextReferences(item.text, (reference) => reference.label), ).trim(); const isEditing = item.runId !== null && item.runId === props.editingRunId; + // The server decides on the agent's text, and a goal command can stop the turn. + const sentText = { text: item.message?.text ?? item.text, attachments: item.attachments }; + const movesCommandFirst = isSlashCommand(sentText) && parseGoalCommand(sentText) === null; return (
  • diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 0e48b30d674da..4f60fef9f6088 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -12458,5 +12458,7 @@ "27d76249d09eb69f": "Review-Leitfaden bereit", "faa3bb26abb39c93": "Review-Leitfaden fehlgeschlagen", "b7df38b7d8792d78": "Leitfaden öffnen", - "9e91e9a77b664e4e": "Review-Leitfaden konnte nicht gestartet werden" + "9e91e9a77b664e4e": "Review-Leitfaden konnte nicht gestartet werden", + "d8aaf932f90429c4": "Diesen Befehl an den Anfang der Warteschlange verschieben ({shortcut})", + "425ab15036aec8a4": "Diesen Befehl an den Anfang der Warteschlange verschieben" } diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index e5d8d3dc2ed21..6453de11f9da0 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -12467,5 +12467,7 @@ "27d76249d09eb69f": "Review guide ready", "faa3bb26abb39c93": "Review guide failed", "b7df38b7d8792d78": "Open guide", - "9e91e9a77b664e4e": "Could not start a review guide" + "9e91e9a77b664e4e": "Could not start a review guide", + "d8aaf932f90429c4": "Move this command to the front of the queue ({shortcut})", + "425ab15036aec8a4": "Move this command to the front of the queue" } diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 4a2868a7e97dc..a73a02ec3bcc9 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -12453,5 +12453,7 @@ "27d76249d09eb69f": "Guía de revisión lista", "faa3bb26abb39c93": "Falló la guía de revisión", "b7df38b7d8792d78": "Abrir guía", - "9e91e9a77b664e4e": "No se pudo iniciar una guía de revisión" + "9e91e9a77b664e4e": "No se pudo iniciar una guía de revisión", + "d8aaf932f90429c4": "Mover este comando al principio de la cola ({shortcut})", + "425ab15036aec8a4": "Mover este comando al principio de la cola" } diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index a0962e52bed39..95ea50d6bf22d 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -12458,5 +12458,7 @@ "27d76249d09eb69f": "Guide de revue prêt", "faa3bb26abb39c93": "Échec du guide de revue", "b7df38b7d8792d78": "Ouvrir le guide", - "9e91e9a77b664e4e": "Impossible de démarrer un guide de revue" + "9e91e9a77b664e4e": "Impossible de démarrer un guide de revue", + "d8aaf932f90429c4": "Placer cette commande en tête de la file d’attente ({shortcut})", + "425ab15036aec8a4": "Placer cette commande en tête de la file d’attente" } diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 0c149c28fbe91..96bf9c7c7bf48 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -12407,5 +12407,7 @@ "27d76249d09eb69f": "レビューガイドの準備ができました", "faa3bb26abb39c93": "レビューガイドの作成に失敗しました", "b7df38b7d8792d78": "ガイドを開く", - "9e91e9a77b664e4e": "レビューガイドを開始できませんでした" + "9e91e9a77b664e4e": "レビューガイドを開始できませんでした", + "d8aaf932f90429c4": "このコマンドをキューの先頭に移動 ({shortcut})", + "425ab15036aec8a4": "このコマンドをキューの先頭に移動" } diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index c01191b387b4f..d7b1a7628ffc6 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -12402,5 +12402,7 @@ "27d76249d09eb69f": "검토 가이드 준비됨", "faa3bb26abb39c93": "검토 가이드 실패", "b7df38b7d8792d78": "가이드 열기", - "9e91e9a77b664e4e": "검토 가이드를 시작할 수 없습니다" + "9e91e9a77b664e4e": "검토 가이드를 시작할 수 없습니다", + "d8aaf932f90429c4": "이 명령을 대기열 맨 앞으로 이동 ({shortcut})", + "425ab15036aec8a4": "이 명령을 대기열 맨 앞으로 이동" } diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 5feb95d75c3da..5097324486fb8 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -12458,5 +12458,7 @@ "27d76249d09eb69f": "Guia de revisão pronto", "faa3bb26abb39c93": "O guia de revisão falhou", "b7df38b7d8792d78": "Abrir guia", - "9e91e9a77b664e4e": "Não foi possível iniciar um guia de revisão" + "9e91e9a77b664e4e": "Não foi possível iniciar um guia de revisão", + "d8aaf932f90429c4": "Mover este comando para o início da fila ({shortcut})", + "425ab15036aec8a4": "Mover este comando para o início da fila" } diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 65a8eede879fa..4c19189200eb5 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -12458,5 +12458,7 @@ "27d76249d09eb69f": "Гид по ревью готов", "faa3bb26abb39c93": "Не удалось создать гид по ревью", "b7df38b7d8792d78": "Открыть гид", - "9e91e9a77b664e4e": "Не удалось запустить гид по ревью" + "9e91e9a77b664e4e": "Не удалось запустить гид по ревью", + "d8aaf932f90429c4": "Переместить эту команду в начало очереди ({shortcut})", + "425ab15036aec8a4": "Переместить эту команду в начало очереди" } diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 081857c5dae81..7add0fa009b1d 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -12465,5 +12465,7 @@ "27d76249d09eb69f": "Granskningsguiden är klar", "faa3bb26abb39c93": "Granskningsguiden misslyckades", "b7df38b7d8792d78": "Öppna guiden", - "9e91e9a77b664e4e": "Kunde inte starta en granskningsguide" + "9e91e9a77b664e4e": "Kunde inte starta en granskningsguide", + "d8aaf932f90429c4": "Flytta det här kommandot först i kön ({shortcut})", + "425ab15036aec8a4": "Flytta det här kommandot först i kön" } diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 17d0dd6a93303..5a5c7160230de 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -12484,5 +12484,7 @@ "27d76249d09eb69f": "审查导览已就绪", "faa3bb26abb39c93": "审查导览生成失败", "b7df38b7d8792d78": "打开导览", - "9e91e9a77b664e4e": "无法开始生成审查导览" + "9e91e9a77b664e4e": "无法开始生成审查导览", + "d8aaf932f90429c4": "将此命令移到队列最前面 ({shortcut})", + "425ab15036aec8a4": "将此命令移到队列最前面" } diff --git a/docs/user/composer.md b/docs/user/composer.md index 94b0219e5ab5a..53017052a2a01 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -69,6 +69,10 @@ are saved on the server and can be edited or removed before they send. When Enter sends, `Cmd+Enter` on macOS or `Ctrl+Enter` on Windows and Linux uses the opposite action: it steers when your default is Queue and queues when your default is Steer. +A slash command such as `/compact` or `/context` waits for the current turn to +finish, because a command steered into a turn would replace the agent's task. +Sending a queued command now moves it to the front of the queue. [Goal](#goals) +commands are the exception: some can stop the current turn. If your **Send shortcut** requires `Cmd+Enter` or `Ctrl+Enter`, that shortcut uses your default follow-up behavior; add **Shift** to use the opposite action. This applies only to multiline messages when you choose the multiline send option. @@ -271,8 +275,9 @@ shortcut described above. On web and desktop, queued messages appear at the end of the thread as dashed messages that have not been sent yet. On mobile they appear above the composer. Each shows its text and any attached -images. **Send now** sends a message right away, into the running turn if there is one. You can -also edit or remove it. +images. **Send now** sends a message right away, into the running turn if there is one. While a +turn runs, a slash command moves to the front of the queue instead. You can also edit or +remove it. If you stop the agent or the server restarts, queued messages keep their order and are held. Press **Resume** in an empty composer to continue. For stopped runs and usage limits, diff --git a/packages/shared/src/composerTrigger.ts b/packages/shared/src/composerTrigger.ts index 96a0a877d14df..2a95d6b34cd0a 100644 --- a/packages/shared/src/composerTrigger.ts +++ b/packages/shared/src/composerTrigger.ts @@ -137,6 +137,14 @@ export function replaceTextRange( return { text: nextText, cursor: safeStart + replacement.length }; } +/** A message that only invokes a slash command, such as `/context all`, not a path like `/src/a.ts`. */ +export function isSlashCommand(message: { + readonly text: string; + readonly attachments: ReadonlyArray; +}): boolean { + return message.attachments.length === 0 && /^\/[\w:-]+(?:\s|$)/u.test(message.text.trim()); +} + /** `/clear` as the whole message arms a fresh session instead of sending. */ export function isClearComposerCommand(text: string): boolean { return /^\/clear\s*$/i.test(text.trim()); diff --git a/scripts/scenarios/steered-compact-waits-for-turn.e2e.ts b/scripts/scenarios/steered-compact-waits-for-turn.e2e.ts new file mode 100644 index 0000000000000..7ed990805fd22 --- /dev/null +++ b/scripts/scenarios/steered-compact-waits-for-turn.e2e.ts @@ -0,0 +1,71 @@ +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; + +import { T3_HOME } from "../e2e.config.ts"; +import { makeState, runPromise, test, WEB } from "./t3.ts"; + +const SettingsJson = Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)); +const decodeSettings = Schema.decodeEffect(SettingsJson); +const encodeSettings = Schema.encodeEffect(SettingsJson); + +const threadRuntimeSettings = Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const settingsPath = (yield* Path.Path).join(T3_HOME, "userdata/settings.json"); + const original = yield* fs.readFileString(settingsPath); + const settings = yield* decodeSettings(original); + return { + supervise: fs.writeFileString( + settingsPath, + yield* encodeSettings({ ...settings, defaultRuntimeMode: "approval-required" }), + ), + restore: fs.writeFileString(settingsPath, original), + }; +}); + +test("/compact sent while the agent works waits for the turn", WEB, async ({ t3, app, screen }) => { + const project = await t3.project("demo"); + // The showcase recording streams for several seconds, long enough to send into its turn. + const thread = await t3.thread({ + project, + title: "Long work", + messages: ["Show me around"], + model: "showcase", + }); + await t3.open(thread); + + const composer = screen.getByRole("textbox"); + await composer.tap(); + await composer.pressSequentially("Show me again"); + await composer.press("Enter"); + await expect(screen.getByRole("button", "Stop generation")).toBeVisible(); + + // The trailing space closes the slash menu so Enter sends instead of picking a command. + await composer.pressSequentially("/compact "); + await composer.press("Enter"); + await app.screenshot("compact-sent"); + await expect(screen.getByRole("button", "Edit queued message")).toBeVisible(); + + const settings = await runPromise(threadRuntimeSettings); + try { + // An approval holds this turn open, so the queued command stays put while Send now is hovered. + await runPromise(settings.supervise); + const waiting = await t3.thread({ + project, + title: "Waiting work", + messages: ["Change the file"], + model: "approval", + }); + await runPromise(makeState(T3_HOME).cli(["thread", "send", waiting.threadId, "/compact"])); + await t3.open(waiting); + await screen.getByRole("button", "Send now").hover(); + await expect( + screen.getByText("Move this command to the front of the queue", { exact: false }), + ).toBeVisible(); + await app.screenshot("send-now-tooltip"); + } finally { + await runPromise(settings.restore); + } +}); From 989d7ec882aa1b7e510cd44f93ab5fe61368058b Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 05:17:55 -0800 Subject: [PATCH 015/324] perf(server): push and commit-and-push read the full git status once instead of three times (#40305) --- apps/server/src/git/GitManager.test.ts | 2 +- apps/server/src/git/GitManager.ts | 4 +++- apps/server/src/vcs/GitVcsDriver.ts | 2 ++ apps/server/src/vcs/GitVcsDriverCore.ts | 24 +++++++++++++++++------- 4 files changed, 23 insertions(+), 9 deletions(-) diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index 9dc3407597a4f..064427a3727f5 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -4198,7 +4198,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { ), ); yield* Deferred.await(gate.reached); - NodeFS.writeFileSync(NodePath.join(repoDir, ".git", "index.lock"), ""); + NodeFS.appendFileSync(NodePath.join(repoDir, ".git", "config"), "\n[broken\n"); yield* Deferred.succeed(gate.release, undefined); const result = yield* Fiber.join(action); diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index 9db4fbfc27755..dab6d4d20924e 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -2256,7 +2256,9 @@ export const make = Effect.gen(function* () { const finalStatus = result.action === "commit" ? null - : yield* gitCore.statusDetails(cwd).pipe(Effect.orElseSucceed(() => null)); + : yield* gitCore + .statusDetailsRemote(cwd, { refreshUpstream: false, includeAheadOfDefault: false }) + .pipe(Effect.orElseSucceed(() => null)); if (finalStatus?.branch) { finalBranchContext = { branch: finalStatus.branch, diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index 700ad3b3571c9..f341ebd987a6c 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -337,6 +337,8 @@ export interface GitSetBranchUpstreamInput { export interface GitRemoteStatusOptions { readonly refreshUpstream?: boolean; + /** False skips the base-branch lookup and reports `aheadOfDefaultCount` as 0. */ + readonly includeAheadOfDefault?: boolean; } /** diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 7c4363b1647be..7fe1dab187ac5 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -2540,6 +2540,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const readStatusDetailsRemote = Effect.fn("readStatusDetailsRemote")(function* ( cwd: string, refreshUpstream: boolean, + includeAheadOfDefault = true, ) { const branchResult = yield* executeGitWithStableDiagnostics( "GitVcsDriver.statusDetailsRemote.branch", @@ -2640,7 +2641,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* (branch === defaultBranch || (defaultBranch === null && (branch === "main" || branch === "master"))); const aheadOfDefaultCount = - branch && !isDefaultBranch + branch && !isDefaultBranch && includeAheadOfDefault ? upstreamRef === null ? aheadCount : yield* computeAheadCountAgainstBase(cwd, branch).pipe(Effect.orElseSucceed(() => 0)) @@ -3004,22 +3005,29 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return yield* readStatusDetailsLocal(cwd, options); }); - const statusDetails: GitVcsDriver.GitVcsDriver["Service"]["statusDetails"] = Effect.fn( - "statusDetails", - )(function* (cwd) { - yield* refreshStatusUpstreamIfStale(cwd).pipe( + const refreshStatusUpstream = (cwd: string) => + refreshStatusUpstreamIfStale(cwd).pipe( Effect.catchTags({ GitCommandError: (error) => isMissingGitCwdError(error) ? Effect.void : Effect.fail(error), }), Effect.ignoreCause({ log: true }), ); + + const statusDetails: GitVcsDriver.GitVcsDriver["Service"]["statusDetails"] = Effect.fn( + "statusDetails", + )(function* (cwd) { + yield* refreshStatusUpstream(cwd); return yield* readStatusDetailsLocal(cwd); }); const statusDetailsRemote: GitVcsDriver.GitVcsDriver["Service"]["statusDetailsRemote"] = Effect.fn("statusDetailsRemote")(function* (cwd, options) { - return yield* readStatusDetailsRemote(cwd, options?.refreshUpstream !== false); + return yield* readStatusDetailsRemote( + cwd, + options?.refreshUpstream !== false, + options?.includeAheadOfDefault !== false, + ); }); const status: GitVcsDriver.GitVcsDriver["Service"]["status"] = (input) => @@ -3658,7 +3666,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const pushCurrentBranch: GitVcsDriver.GitVcsDriver["Service"]["pushCurrentBranch"] = Effect.fn( "pushCurrentBranch", )(function* (cwd, fallbackBranch, options) { - const details = yield* statusDetails(cwd); + // Refresh first so the branch, upstream and divergence reads below stay close together. + yield* refreshStatusUpstream(cwd); + const details = yield* readStatusDetailsRemote(cwd, false, false); const branch = details.branch ?? fallbackBranch; if (!branch) { return yield* new GitCommandError({ From 0c921e1fdf6feda7d1bab2be83e3916c6f4509c2 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 05:28:23 -0800 Subject: [PATCH 016/324] fix(server): ACP session/load replay no longer pins background work (#40328) --- .../Adapters/AcpAdapterV2.test.ts | 89 +++++++++++ packages/provider-acp/src/server/adapter.ts | 149 ++++++++++-------- 2 files changed, 173 insertions(+), 65 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 4946377c94502..d79257944c8e9 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -9234,6 +9234,95 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(layerTest)), ); + it.effect("session/load replay does not leave post-settle background work pending", () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* bundledMockAgentPath; + const instanceId = ProviderInstanceId.make("acp-test"); + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let sessionUpdateHandler: Parameters[0] | undefined; + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + enablePostSettleContinuation: true, + normalizeToolCall: normalizeXAiAcpToolCallState, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + wrapRuntime: (runtime) => ({ + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + sessionUpdateHandler = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + }), + }), + }, + continuationRequests: { offer: () => Effect.void }, + }); + const threadId = ThreadId.make("thread-acp-load-replay-background"); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-load-replay-background"), + modelSelection, + runtimePolicy, + }); + if (runtime.hasPendingBackgroundWork === undefined) { + return yield* Effect.die("ACP runtime must expose hasPendingBackgroundWork."); + } + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + assert.isFalse(yield* runtime.hasPendingBackgroundWork); + assert.isDefined(sessionUpdateHandler, "session update handler must be wired"); + + // A large session/load replays its tail after the session is active. + yield* sessionUpdateHandler!({ + sessionId: "mock-session-1", + _meta: { isReplay: true }, + update: { + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "old reply from history" }, + }, + }); + yield* sessionUpdateHandler!({ + sessionId: "mock-session-1", + _meta: { isReplay: true }, + update: { + sessionUpdate: "tool_call", + toolCallId: "replayed-tool-1", + title: "run_command", + kind: "execute", + status: "completed", + rawInput: { command: "echo old" }, + }, + }); + yield* Effect.yieldNow; + + assert.isFalse( + yield* runtime.hasPendingBackgroundWork, + "replayed history must not pin background work", + ); + const snapshot = yield* runtime.readThreadSnapshot({ providerThread }); + assert.deepEqual( + snapshot.messages.map((message) => message.text), + ["old reply from history"], + ); + }).pipe(Effect.provide(layerTest)), + ); + it.effect("projects completed-root carryover eagerly and drain cannot resurrect it", () => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index cf7bb6c0f92fd..a712d40629e60 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -87,6 +87,7 @@ import { mergeToolCallState, parsePermissionRequest, parseSessionUpdateEvent, + sessionUpdateIsReplay, toolCallVisibleOutputChanged, withTrackedPermissionToolCall, type AcpPlanUpdate, @@ -5650,6 +5651,80 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ), ); + const recordLoadedHistory = Effect.fnUntraced(function* ( + notification: EffectAcpSchema.SessionNotification, + live: boolean, + ) { + const update = notification.update; + if ( + notification.sessionId !== + ((yield* Ref.get(loadingSessionId)) ?? (yield* Ref.get(activeSessionId))) + ) + return; + if ( + update.sessionUpdate === "user_message_chunk" || + update.sessionUpdate === "agent_message_chunk" || + update.sessionUpdate === "agent_thought_chunk" + ) { + const text = acpContentBlockDisplayText(update.content); + if (text === undefined) return; + const lateBackgroundMutations = + update.content.type === "text" + ? (flavor.extractBackgroundToolMutation?.(text) ?? []) + : []; + if (live) { + for (const lateBackgroundMutation of lateBackgroundMutations) { + yield* applyLateBackgroundMutation(notification.sessionId, lateBackgroundMutation); + } + } + if (lateBackgroundMutations.length === 0 && !acpIsMonitorChatter(text)) { + yield* appendLoadedHistory( + notification, + update.sessionUpdate === "user_message_chunk" + ? "user" + : update.sessionUpdate === "agent_thought_chunk" + ? "thought" + : "assistant", + text, + ); + } + } else if ( + update.sessionUpdate === "user_message" || + update.sessionUpdate === "agent_message" || + update.sessionUpdate === "agent_thought" + ) { + if (update.content === undefined) return; + const text = (update.content ?? []) + .flatMap((content) => { + const display = acpContentBlockDisplayText(content); + return display === undefined ? [] : [display]; + }) + .join("\n"); + yield* appendLoadedHistory( + notification, + update.sessionUpdate === "user_message" + ? "user" + : update.sessionUpdate === "agent_thought" + ? "thought" + : "assistant", + text, + true, + ); + } else if ( + update.sessionUpdate === "tool_call" || + update.sessionUpdate === "tool_call_update" || + update.sessionUpdate === "plan" || + update.sessionUpdate === "plan_update" || + update.sessionUpdate === "plan_removed" + ) { + yield* Ref.update(snapshot, (current) => ({ + ...current, + loadingRole: null, + loadingMessageId: null, + })); + } + }); + const handleSessionUpdate = Effect.fnUntraced(function* ( notification: EffectAcpSchema.SessionNotification, ) { @@ -5898,71 +5973,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if (wakeOutcome.stopProcessing) { return; } - if ( - notification.sessionId !== - ((yield* Ref.get(loadingSessionId)) ?? (yield* Ref.get(activeSessionId))) - ) - return; - if ( - update.sessionUpdate === "user_message_chunk" || - update.sessionUpdate === "agent_message_chunk" || - update.sessionUpdate === "agent_thought_chunk" - ) { - const text = acpContentBlockDisplayText(update.content); - if (text === undefined) return; - const lateBackgroundMutations = - update.content.type === "text" - ? (flavor.extractBackgroundToolMutation?.(text) ?? []) - : []; - for (const lateBackgroundMutation of lateBackgroundMutations) { - yield* applyLateBackgroundMutation(notification.sessionId, lateBackgroundMutation); - } - if (lateBackgroundMutations.length === 0 && !acpIsMonitorChatter(text)) { - yield* appendLoadedHistory( - notification, - update.sessionUpdate === "user_message_chunk" - ? "user" - : update.sessionUpdate === "agent_thought_chunk" - ? "thought" - : "assistant", - text, - ); - } - } else if ( - update.sessionUpdate === "user_message" || - update.sessionUpdate === "agent_message" || - update.sessionUpdate === "agent_thought" - ) { - if (update.content === undefined) return; - const text = (update.content ?? []) - .flatMap((content) => { - const display = acpContentBlockDisplayText(content); - return display === undefined ? [] : [display]; - }) - .join("\n"); - yield* appendLoadedHistory( - notification, - update.sessionUpdate === "user_message" - ? "user" - : update.sessionUpdate === "agent_thought" - ? "thought" - : "assistant", - text, - true, - ); - } else if ( - update.sessionUpdate === "tool_call" || - update.sessionUpdate === "tool_call_update" || - update.sessionUpdate === "plan" || - update.sessionUpdate === "plan_update" || - update.sessionUpdate === "plan_removed" - ) { - yield* Ref.update(snapshot, (current) => ({ - ...current, - loadingRole: null, - loadingMessageId: null, - })); - } + yield* recordLoadedHistory(notification, true); return; } if (context.finalized) return; @@ -7016,6 +7027,14 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( Effect.fnUntraced( function* (rawNotification: EffectAcpSchema.SessionNotification) { if (flavor.ignoreSessionUpdate?.(rawNotification) === true) return; + // Replayed history feeds snapshots only; it must not drive live turn or wake state. + if (sessionUpdateIsReplay(rawNotification)) { + yield* recordLoadedHistory( + flavor.normalizeSessionUpdate?.(rawNotification) ?? rawNotification, + false, + ); + return; + } yield* notePromptProgress(rawNotification); const nativePromptId = flavor.forkFromTurn?.nativeTurnId(rawNotification); if (nativePromptId !== undefined) { From 232f52c8db1998fc566c4bb5940db6a12c898c8d Mon Sep 17 00:00:00 2001 From: Arif Ali <51419655+arifali123@users.noreply.github.com> Date: Sat, 21 Nov 2026 05:28:38 -0800 Subject: [PATCH 017/324] fix(mobile): confirming a push to the default branch no longer opens the thread a second time (#40311) Co-authored-by: Orin Co-authored-by: Julius Marminge --- .../features/threads/git/GitConfirmSheet.tsx | 10 +++-- .../thread-inspector-navigation.test.tsx | 41 ++++++++++++++++++- .../threads/thread-inspector-navigation.ts | 38 +++++++++++++---- 3 files changed, 74 insertions(+), 15 deletions(-) diff --git a/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx b/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx index b916b49697fc5..1da0ec450a572 100644 --- a/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx +++ b/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx @@ -3,7 +3,7 @@ import { sourceControlClients } from "@t3tools/client-runtime/source-control-cli import { resolveAutoFeatureBranchName } from "@t3tools/shared/git"; import * as Arr from "effect/Array"; import * as Result from "effect/Result"; -import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native"; +import { useNavigation, type StaticScreenProps } from "@react-navigation/native"; import { useGT, useMessages } from "gt-react-native"; import { useCallback, useMemo } from "react"; import { View } from "react-native"; @@ -20,6 +20,7 @@ import { type GitRepositoryRouteParams, } from "../../../state/thread-git-target"; import { vcsEnvironment } from "../../../state/vcs"; +import { useReturnToThread } from "../thread-inspector-navigation"; import { SheetActionButton } from "./gitSheetComponents"; type GitConfirmSheetProps = StaticScreenProps< @@ -38,6 +39,7 @@ export function GitConfirmSheet(props: GitConfirmSheetProps) { const gt = useGT(); const messages = useMessages(); const navigation = useNavigation(); + const returnToThread = useReturnToThread(); const repository = gitRepositoryTargetFromRoute(props.route.params); const gitState = useSelectedThreadGitState(repository); const gitActions = useSelectedThreadGitActions(repository); @@ -89,7 +91,7 @@ export function GitConfirmSheet(props: GitConfirmSheetProps) { const continuePendingAction = async () => { if (!canWriteSourceControl || !confirmAction) return; - navigation.dispatch(StackActions.replace("Thread", { environmentId, threadId })); + returnToThread({ environmentId, threadId }); await gitActions.onRunSelectedThreadGitAction({ action: confirmAction, ...(params.commitMessage ? { commitMessage: params.commitMessage } : {}), @@ -99,7 +101,7 @@ export function GitConfirmSheet(props: GitConfirmSheetProps) { const movePendingActionToFeatureBranch = useCallback(async () => { if (!canCreateFeatureBranch || !confirmAction) return; - navigation.dispatch(StackActions.replace("Thread", { environmentId, threadId })); + returnToThread({ environmentId, threadId }); if (includesCommit) { await gitActions.onRunSelectedThreadGitAction({ @@ -131,7 +133,7 @@ export function GitConfirmSheet(props: GitConfirmSheetProps) { gitState.selectedThreadBranches, includesCommit, params, - navigation, + returnToThread, environmentId, threadId, ]); diff --git a/apps/mobile/src/features/threads/thread-inspector-navigation.test.tsx b/apps/mobile/src/features/threads/thread-inspector-navigation.test.tsx index 404d28184d7b8..f2398d6e1fc90 100644 --- a/apps/mobile/src/features/threads/thread-inspector-navigation.test.tsx +++ b/apps/mobile/src/features/threads/thread-inspector-navigation.test.tsx @@ -29,7 +29,7 @@ vi.mock("@react-navigation/native", async () => { }; }); -import { useOpenThreadInspector } from "./thread-inspector-navigation"; +import { useOpenThreadInspector, useReturnToThread } from "./thread-inspector-navigation"; import { useOpenLinkedThread, useOpenLinkedThreadRead } from "./useOpenLinkedThread"; const requireNavigation = NodeModule.createRequire( @@ -45,7 +45,15 @@ function setup(fromAgents: boolean, fullscreen = false, inspectorSupported = tru (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; const router = StackRouter({}); const options = { - routeNames: ["Home", "Thread", "ThreadAgents", "ThreadInspectorFullscreen", "LinkedThread"], + routeNames: [ + "Home", + "Thread", + "ThreadAgents", + "ThreadInspectorFullscreen", + "LinkedThread", + "ThreadReview", + "GitConfirm", + ], routeParamList: {}, routeGetIdList: {}, }; @@ -70,14 +78,17 @@ function setup(fromAgents: boolean, fullscreen = false, inspectorSupported = tru let openInspector: ReturnType; let openLinkedThread: ReturnType; let openLinkedThreadRead: ReturnType; + let returnToThread: ReturnType; function Probe() { const open = useOpenThreadInspector(); const openLinked = useOpenLinkedThread(); const openLinkedRead = useOpenLinkedThreadRead(); + const returnTo = useReturnToThread(); useLayoutEffect(() => { openInspector = open; openLinkedThread = openLinked; openLinkedThreadRead = openLinkedRead; + returnToThread = returnTo; }); return null; } @@ -103,6 +114,9 @@ function setup(fromAgents: boolean, fullscreen = false, inspectorSupported = tru openLinkedRead(...input: Parameters) { act(() => openLinkedThreadRead(...input)); }, + returnTo(thread: Parameters[0]) { + act(() => returnToThread(thread)); + }, [Symbol.dispose]() { act(() => root.unmount()); }, @@ -190,6 +204,29 @@ it.each([ }, ); +it.each([ + { confirmFrom: "parent", routes: ["Home", "Thread"] }, + // A side thread's review, opened from the parent's inspector, sits above the parent's route. + { confirmFrom: "child", routes: ["Home", "Thread", "ThreadReview", "Thread"] }, +])( + "returns from a Git confirmation to the $confirmFrom thread without replacing another", + ({ confirmFrom, routes }) => { + using screen = setup(false); + const inspector = { type: "device", ...screen.source } as const; + screen.open(inspector); + const thread = { ...screen.source, threadId: confirmFrom }; + if (confirmFrom !== "parent") screen.dispatch(StackActions.push("ThreadReview", thread)); + screen.dispatch(StackActions.push("GitConfirm", thread)); + screen.returnTo(thread); + expect(screen.state.routes.map((route) => route.name)).toEqual(routes); + expect(screen.state.routes[1]).toMatchObject({ + key: screen.parentKey, + params: { ...screen.source, prompt: "retained prompt", inspector }, + }); + expect(screen.state.routes.at(-1)?.params).toMatchObject(thread); + }, +); + it("switches between subagents and devices in the same parent route", () => { using screen = setup(false); screen.open({ type: "thread", environmentId: screen.source.environmentId, threadId: "child" }); diff --git a/apps/mobile/src/features/threads/thread-inspector-navigation.ts b/apps/mobile/src/features/threads/thread-inspector-navigation.ts index 966dd1a92a632..04fc59ed636e1 100644 --- a/apps/mobile/src/features/threads/thread-inspector-navigation.ts +++ b/apps/mobile/src/features/threads/thread-inspector-navigation.ts @@ -41,15 +41,7 @@ export function useOpenThreadInspector() { if (presentation === "full-screen") return false; if (openInInspector) openInInspector(target); else { - const parent = navigation.getState()?.routes.findLast((route) => route.name === "Thread"); - if ( - !parent?.params || - !("environmentId" in parent.params) || - parent.params.environmentId !== source.environmentId || - !("threadId" in parent.params) || - parent.params.threadId !== source.threadId - ) - return false; + if (!isNearestThreadRoute(navigation.getState(), source)) return false; navigation.dispatch( StackActions.popTo("Thread", { ...source, inspector: target }, { merge: true }), ); @@ -57,3 +49,31 @@ export function useOpenThreadInspector() { return true; }; } + +/** Closes the screens above `thread`, or opens it when the nearest thread route is another one. */ +export function useReturnToThread() { + const navigation = useNavigation(); + return (thread: { readonly environmentId: string; readonly threadId: string }) => + navigation.dispatch( + isNearestThreadRoute(navigation.getState(), thread) + ? StackActions.popTo("Thread", thread, { merge: true }) + : StackActions.replace("Thread", thread), + ); +} + +// `Thread` has no `getId`, so `popTo("Thread")` lands on the nearest one whatever thread it shows. +function isNearestThreadRoute( + state: + | { readonly routes: ReadonlyArray<{ readonly name: string; readonly params?: object }> } + | undefined, + thread: { readonly environmentId: string; readonly threadId: string }, +) { + const params = state?.routes.findLast((route) => route.name === "Thread")?.params; + return ( + params !== undefined && + "environmentId" in params && + params.environmentId === thread.environmentId && + "threadId" in params && + params.threadId === thread.threadId + ); +} From 9c25b71395e36bba1e86f3f093348f0ad966495e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 05:31:49 -0800 Subject: [PATCH 018/324] =?UTF-8?q?fix(opencode):=20Usage=20=E2=86=92=20Li?= =?UTF-8?q?mits=20shows=20why=20OpenCode=20could=20not=20read=20usage=20(#?= =?UTF-8?q?40340)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/server/v2/OpenCode2Client.test.ts | 12 ++++++++++++ .../src/server/v2/usageLimits.ts | 19 +++++++++++++++---- 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts b/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts index ff77d8ef72a2f..701ad57fe488a 100644 --- a/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts +++ b/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts @@ -467,6 +467,16 @@ describe("OpenCode2Client usage limits", () => { "unsupported", ], [503, {}, "probeFailed"], + [ + 503, + { + _tag: "ServiceUnavailableError", + message: + "OpenCode Console budgets are unavailable: StatusCode: non 2xx status code (401 GET https://opencode.ai/console/api/policies/current-budgets)", + service: "opencode", + }, + "probeFailed", + ], [401, {}, "probeFailed"], [200, { data: { workspace: {} } }, "probeFailed"], ] as const) { @@ -487,6 +497,8 @@ describe("OpenCode2Client usage limits", () => { else assert.strictEqual(result?.unavailable?.reason, reason); if ("data" in body && body.data === null) assert.include(result?.unavailable?.message ?? "", "signed in"); + if ("message" in body) + assert.include(result?.unavailable?.message ?? "", "OpenCode Console budgets"); } }), ); diff --git a/packages/provider-opencode/src/server/v2/usageLimits.ts b/packages/provider-opencode/src/server/v2/usageLimits.ts index dd28770b9c5c4..bdf678e424692 100644 --- a/packages/provider-opencode/src/server/v2/usageLimits.ts +++ b/packages/provider-opencode/src/server/v2/usageLimits.ts @@ -61,6 +61,9 @@ const Providers = Schema.Struct({ ), }); +const ErrorBody = Schema.Struct({ message: Schema.String }); +const probeFailedMessage = "OpenCode could not read workspace usage."; + const resetTime = (ms: number) => DateTime.formatIso(DateTime.makeUnsafe(ms)); const budgetPercent = (spent: number, limit: number) => limit <= 0 ? 100 : clampPercent((spent / limit) * 100); @@ -81,9 +84,17 @@ export const readServerUsageLimits = Effect.fn("OpenCode2Client.usageLimits")(fu response.headers["content-type"]?.split(";")[0]?.trim() === "text/html") ) return undefined; - const body = yield* HttpClientResponse.filterStatusOk(response).pipe( - Effect.flatMap(HttpClientResponse.schemaBodyJson(ResponseBody)), - ); + // OpenCode names the upstream cause, such as an expired Console login, in its error body. + if (response.status < 200 || response.status >= 300) + return makeUnavailableUsageLimits({ + checkedAt, + reason: "probeFailed", + message: yield* HttpClientResponse.schemaBodyJson(ErrorBody)(response).pipe( + Effect.map((error) => error.message.trim() || probeFailedMessage), + Effect.orElseSucceed(() => probeFailedMessage), + ), + }); + const body = yield* HttpClientResponse.schemaBodyJson(ResponseBody)(response); if (body.data === null) return makeUnavailableUsageLimits({ checkedAt, @@ -186,7 +197,7 @@ export const readServerUsageLimits = Effect.fn("OpenCode2Client.usageLimits")(fu makeUnavailableUsageLimits({ checkedAt, reason: "probeFailed", - message: "OpenCode could not read workspace usage.", + message: probeFailedMessage, }), ), ); From d3bb8f810898b939712aea7629e94073ae50c0f8 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 05:56:16 -0800 Subject: [PATCH 019/324] perf(server): deleting a thread's worktree refreshes git status once, not twice (#40337) --- apps/server/src/ws.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index d96b91f30d62a..afa030d4d7e9c 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -3295,7 +3295,8 @@ export const layerWsRpc = ( Effect.flatMap((removed) => removed ? Effect.void : gitWorkflow.removeWorktree(input), ), - Effect.tap(() => refreshGitStatus(input.cwd)), + // No project-root refresh here: the client awaits vcs.refreshStatus right after, and a + // second refresh would queue behind this one and reread an unchanged repository. // Subscribers of the removed checkout learn it is no longer a repository. Effect.tap(() => vcsStatusBroadcaster From ece4964b8ea2ac15cf59658c1a2112d1e2bb95f5 Mon Sep 17 00:00:00 2001 From: Simone Date: Sat, 21 Nov 2026 14:56:29 +0100 Subject: [PATCH 020/324] fix(antigravity): accept null skill manifest lists (#40287) Co-authored-by: Simone <185146821+Lucenx9@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../src/provider/Drivers/AntigravitySkills.test.ts | 10 +++++++++- .../src/provider/Drivers/AntigravitySkills.ts | 13 +++++-------- 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/apps/server/src/provider/Drivers/AntigravitySkills.test.ts b/apps/server/src/provider/Drivers/AntigravitySkills.test.ts index 96dd2c5dbaa44..0033755bfe706 100644 --- a/apps/server/src/provider/Drivers/AntigravitySkills.test.ts +++ b/apps/server/src/provider/Drivers/AntigravitySkills.test.ts @@ -435,8 +435,16 @@ it.layer(NodeServices.layer)("discoverAntigravitySkills", (it) => { yield* fileSystem.writeFileString( path.join(input.cwd, ".agents", "skills.json"), JSON.stringify({ + entries: null, + inherits: [{ path: "workspace-skills.json", include_only: null }], + }), + ); + yield* fileSystem.writeFileString( + path.join(input.cwd, "workspace-skills.json"), + JSON.stringify({ + inherits: null, entries: [ - { path: "tools/skills/deploy/SKILL.md" }, + { path: "tools/skills/deploy/SKILL.md", exclude: null }, { path: "tools/skills/internal/SKILL.md", exclude: ["internal"] }, ], }), diff --git a/apps/server/src/provider/Drivers/AntigravitySkills.ts b/apps/server/src/provider/Drivers/AntigravitySkills.ts index 51fd5535c8226..f69b3d1c455be 100644 --- a/apps/server/src/provider/Drivers/AntigravitySkills.ts +++ b/apps/server/src/provider/Drivers/AntigravitySkills.ts @@ -48,14 +48,14 @@ const SkillFrontmatter = Schema.Struct({ const decodeSkillFrontmatter = Schema.decodeUnknownSync(SkillFrontmatter); const SkillConfigEntry = Schema.Struct({ path: Schema.String, - include_only: Schema.optional(Schema.Array(Schema.String)), - exclude: Schema.optional(Schema.Array(Schema.String)), + include_only: Schema.optional(Schema.NullOr(Schema.Array(Schema.String))), + exclude: Schema.optional(Schema.NullOr(Schema.Array(Schema.String))), }); const decodeSkillsConfig = Schema.decodeUnknownOption( Schema.fromJsonString( Schema.Struct({ - inherits: Schema.optional(Schema.Array(SkillConfigEntry)), - entries: Schema.optional(Schema.Array(SkillConfigEntry)), + inherits: Schema.optional(Schema.NullOr(Schema.Array(SkillConfigEntry))), + entries: Schema.optional(Schema.NullOr(Schema.Array(SkillConfigEntry))), }), ), ); @@ -289,10 +289,7 @@ function matchesSkillFilter(entry: string, filter: SkillEntryFilter): boolean { function narrowSkillFilter( parent: SkillEntryFilter, - entry: { - readonly include_only?: ReadonlyArray | undefined; - readonly exclude?: ReadonlyArray | undefined; - }, + entry: typeof SkillConfigEntry.Type, ): SkillEntryFilter { const includeGroups = entry.include_only && entry.include_only.length > 0 From e0f3ab9e78a72e86727b6664488f9a19a1e8fe7b Mon Sep 17 00:00:00 2001 From: panol <302941691@qq.com> Date: Sat, 21 Nov 2026 21:57:47 +0800 Subject: [PATCH 021/324] fix(mobile): text selection menu items follow the UI language (#40297) Co-authored-by: Julius Marminge --- apps/mobile/src/i18n/translations/de.json | 6 ++++-- apps/mobile/src/i18n/translations/en.json | 6 ++++-- apps/mobile/src/i18n/translations/es.json | 6 ++++-- apps/mobile/src/i18n/translations/fr.json | 6 ++++-- apps/mobile/src/i18n/translations/ja.json | 6 ++++-- apps/mobile/src/i18n/translations/ko.json | 6 ++++-- apps/mobile/src/i18n/translations/pt-BR.json | 6 ++++-- apps/mobile/src/i18n/translations/ru.json | 6 ++++-- apps/mobile/src/i18n/translations/sv.json | 6 ++++-- apps/mobile/src/i18n/translations/zh.json | 6 ++++-- apps/mobile/src/native/EnrichedMarkdownText.tsx | 17 +++++++++++++++++ 11 files changed, 57 insertions(+), 20 deletions(-) diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index 8777f08e663ce..e0eb437599e38 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -1546,6 +1546,10 @@ "8f2e6a13eee27d59": "Überschriften", "29005b7a742cae1e": "Links", "728a49012344e673": "Bilder", + "a034d65164bb39de": "Kopieren", + "0165ef55eb6c8a99": "Als Markdown kopieren", + "439737cb6de2a5b3": "Bild-URL kopieren", + "d3d24474c922eef2": "{count} Bild-URLs kopieren", "f18f6d80b6bd08a0": "Modellreferenz kopieren", "d7a551536aa43f3e": "Modellreferenz teilen", "9f1b29c948772f0f": "Link öffnen", @@ -1553,7 +1557,6 @@ "d7dc565616d13a5c": "Link teilen", "51244cd196696a00": "Zitieren", "6cdca065884f77f2": "Kopieren", - "0165ef55eb6c8a99": "Als Markdown kopieren", "7c1923203049d602": "Code kopieren", "74d986aed0381cb0": "Der Diagramm-Renderer konnte nicht geladen werden.", "9cc6288e83305ca3": "Das Diagramm konnte nicht gerendert werden.", @@ -1862,7 +1865,6 @@ "1d0a7acef4a95536": "Akzeptieren", "255ae21697461ef6": "Übernimm die Steuerung, um zu antworten.", "d2a40ef08ef016ec": "{command} kopieren", - "a034d65164bb39de": "Kopieren", "e0cfab9ded209e81": "Neu verbinden", "b00379f06c304b6a": "Browser öffnen, {title}", "149eba5f977b0549": "Öffnet den Browser-Tab im Vollbild", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index dfe3a473fe248..bca87cee0884f 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -1546,6 +1546,10 @@ "8f2e6a13eee27d59": "Headings", "29005b7a742cae1e": "Links", "728a49012344e673": "Images", + "a034d65164bb39de": "Copy", + "0165ef55eb6c8a99": "Copy as Markdown", + "439737cb6de2a5b3": "Copy Image URL", + "d3d24474c922eef2": "Copy {count} Image URLs", "f18f6d80b6bd08a0": "Copy model reference", "d7a551536aa43f3e": "Share model reference", "9f1b29c948772f0f": "Open link", @@ -1553,7 +1557,6 @@ "d7dc565616d13a5c": "Share link", "51244cd196696a00": "Cite", "6cdca065884f77f2": "Copy", - "0165ef55eb6c8a99": "Copy as Markdown", "7c1923203049d602": "Copy code", "74d986aed0381cb0": "The diagram renderer failed to load.", "9cc6288e83305ca3": "The diagram could not be rendered.", @@ -1862,7 +1865,6 @@ "1d0a7acef4a95536": "Accept", "255ae21697461ef6": "Take control to respond.", "d2a40ef08ef016ec": "Copy {command}", - "a034d65164bb39de": "Copy", "e0cfab9ded209e81": "Reconnect", "b00379f06c304b6a": "Open browser, {title}", "149eba5f977b0549": "Opens the browser tab full screen", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index 05f58a63227d3..3f73e995b2521 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -1546,6 +1546,10 @@ "8f2e6a13eee27d59": "Encabezados", "29005b7a742cae1e": "Enlaces", "728a49012344e673": "Imágenes", + "a034d65164bb39de": "Copiar", + "0165ef55eb6c8a99": "Copiar como Markdown", + "439737cb6de2a5b3": "Copiar URL de la imagen", + "d3d24474c922eef2": "Copiar {count} URL de imágenes", "f18f6d80b6bd08a0": "Copiar referencia del modelo", "d7a551536aa43f3e": "Compartir referencia del modelo", "9f1b29c948772f0f": "Abrir enlace", @@ -1553,7 +1557,6 @@ "d7dc565616d13a5c": "Compartir enlace", "51244cd196696a00": "Citar", "6cdca065884f77f2": "Copiar", - "0165ef55eb6c8a99": "Copiar como Markdown", "7c1923203049d602": "Copiar código", "74d986aed0381cb0": "No se pudo cargar el renderizador de diagramas.", "9cc6288e83305ca3": "No se pudo renderizar el diagrama.", @@ -1862,7 +1865,6 @@ "1d0a7acef4a95536": "Aceptar", "255ae21697461ef6": "Toma el control para responder.", "d2a40ef08ef016ec": "Copiar {command}", - "a034d65164bb39de": "Copiar", "e0cfab9ded209e81": "Volver a conectar", "b00379f06c304b6a": "Abrir navegador, {title}", "149eba5f977b0549": "Abre la pestaña del navegador a pantalla completa", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index f661c315215c0..3aff16728eeff 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -1546,6 +1546,10 @@ "8f2e6a13eee27d59": "Titres", "29005b7a742cae1e": "Liens", "728a49012344e673": "Images", + "a034d65164bb39de": "Copier", + "0165ef55eb6c8a99": "Copier en Markdown", + "439737cb6de2a5b3": "Copier l’URL de l’image", + "d3d24474c922eef2": "Copier {count} URL d’images", "f18f6d80b6bd08a0": "Copier la référence du modèle", "d7a551536aa43f3e": "Partager la référence du modèle", "9f1b29c948772f0f": "Ouvrir le lien", @@ -1553,7 +1557,6 @@ "d7dc565616d13a5c": "Partager le lien", "51244cd196696a00": "Citer", "6cdca065884f77f2": "Copier", - "0165ef55eb6c8a99": "Copier en Markdown", "7c1923203049d602": "Copier le code", "74d986aed0381cb0": "Le moteur de rendu des diagrammes n’a pas pu se charger.", "9cc6288e83305ca3": "Impossible d’afficher le diagramme.", @@ -1862,7 +1865,6 @@ "1d0a7acef4a95536": "Accepter", "255ae21697461ef6": "Prenez le contrôle pour répondre.", "d2a40ef08ef016ec": "Copier {command}", - "a034d65164bb39de": "Copier", "e0cfab9ded209e81": "Se reconnecter", "b00379f06c304b6a": "Ouvrir le navigateur, {title}", "149eba5f977b0549": "Ouvre l’onglet du navigateur en plein écran", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index 56616809052d3..302318926d092 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -1546,6 +1546,10 @@ "8f2e6a13eee27d59": "見出し", "29005b7a742cae1e": "リンク", "728a49012344e673": "画像", + "a034d65164bb39de": "コピー", + "0165ef55eb6c8a99": "Markdown としてコピー", + "439737cb6de2a5b3": "画像URLをコピー", + "d3d24474c922eef2": "{count}件の画像URLをコピー", "f18f6d80b6bd08a0": "モデルの参照をコピー", "d7a551536aa43f3e": "モデルの参照を共有", "9f1b29c948772f0f": "リンクを開く", @@ -1553,7 +1557,6 @@ "d7dc565616d13a5c": "リンクを共有", "51244cd196696a00": "引用", "6cdca065884f77f2": "コピー", - "0165ef55eb6c8a99": "Markdown としてコピー", "7c1923203049d602": "コードをコピー", "74d986aed0381cb0": "図のレンダラーを読み込めませんでした。", "9cc6288e83305ca3": "図をレンダリングできませんでした。", @@ -1862,7 +1865,6 @@ "1d0a7acef4a95536": "承諾", "255ae21697461ef6": "応答するには操作権を取得してください。", "d2a40ef08ef016ec": "{command} をコピー", - "a034d65164bb39de": "コピー", "e0cfab9ded209e81": "再接続", "b00379f06c304b6a": "ブラウザーを開く、{title}", "149eba5f977b0549": "ブラウザータブを全画面で開きます", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index 443285f8664c4..ec0ee0864e6ef 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -1546,6 +1546,10 @@ "8f2e6a13eee27d59": "제목", "29005b7a742cae1e": "링크", "728a49012344e673": "이미지", + "a034d65164bb39de": "복사", + "0165ef55eb6c8a99": "Markdown으로 복사", + "439737cb6de2a5b3": "이미지 URL 복사", + "d3d24474c922eef2": "이미지 URL {count}개 복사", "f18f6d80b6bd08a0": "모델 참조 복사", "d7a551536aa43f3e": "모델 참조 공유", "9f1b29c948772f0f": "링크 열기", @@ -1553,7 +1557,6 @@ "d7dc565616d13a5c": "링크 공유", "51244cd196696a00": "인용하기", "6cdca065884f77f2": "복사", - "0165ef55eb6c8a99": "Markdown으로 복사", "7c1923203049d602": "코드 복사", "74d986aed0381cb0": "다이어그램 렌더러를 불러오지 못했습니다.", "9cc6288e83305ca3": "다이어그램을 렌더링할 수 없습니다.", @@ -1862,7 +1865,6 @@ "1d0a7acef4a95536": "수락", "255ae21697461ef6": "응답하려면 제어하세요.", "d2a40ef08ef016ec": "{command} 복사", - "a034d65164bb39de": "복사", "e0cfab9ded209e81": "다시 연결", "b00379f06c304b6a": "브라우저 열기, {title}", "149eba5f977b0549": "브라우저 탭을 전체 화면으로 엽니다", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 33793cc553d34..56b52f85e6d01 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -1546,6 +1546,10 @@ "8f2e6a13eee27d59": "Títulos", "29005b7a742cae1e": "Links", "728a49012344e673": "Imagens", + "a034d65164bb39de": "Copiar", + "0165ef55eb6c8a99": "Copiar como Markdown", + "439737cb6de2a5b3": "Copiar URL da imagem", + "d3d24474c922eef2": "Copiar {count} URLs de imagens", "f18f6d80b6bd08a0": "Copiar referência do modelo", "d7a551536aa43f3e": "Compartilhar referência do modelo", "9f1b29c948772f0f": "Abrir link", @@ -1553,7 +1557,6 @@ "d7dc565616d13a5c": "Compartilhar link", "51244cd196696a00": "Citar", "6cdca065884f77f2": "Copiar", - "0165ef55eb6c8a99": "Copiar como Markdown", "7c1923203049d602": "Copiar código", "74d986aed0381cb0": "Falha ao carregar o renderizador de diagramas.", "9cc6288e83305ca3": "Não foi possível renderizar o diagrama.", @@ -1862,7 +1865,6 @@ "1d0a7acef4a95536": "Aceitar", "255ae21697461ef6": "Assuma o controle para responder.", "d2a40ef08ef016ec": "Copiar {command}", - "a034d65164bb39de": "Copiar", "e0cfab9ded209e81": "Reconectar", "b00379f06c304b6a": "Abrir navegador, {title}", "149eba5f977b0549": "Abre a aba do navegador em tela cheia", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index d0e2d9577a9ab..9b3b38bcf0234 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -1546,6 +1546,10 @@ "8f2e6a13eee27d59": "Заголовки", "29005b7a742cae1e": "Ссылки", "728a49012344e673": "Изображения", + "a034d65164bb39de": "Копировать", + "0165ef55eb6c8a99": "Копировать как Markdown", + "439737cb6de2a5b3": "Копировать URL изображения", + "d3d24474c922eef2": "Копировать URL изображений: {count}", "f18f6d80b6bd08a0": "Копировать ссылку на модель", "d7a551536aa43f3e": "Поделиться ссылкой на модель", "9f1b29c948772f0f": "Открыть ссылку", @@ -1553,7 +1557,6 @@ "d7dc565616d13a5c": "Поделиться ссылкой", "51244cd196696a00": "Цитировать", "6cdca065884f77f2": "Копировать", - "0165ef55eb6c8a99": "Копировать как Markdown", "7c1923203049d602": "Копировать код", "74d986aed0381cb0": "Не удалось загрузить отрисовщик диаграмм.", "9cc6288e83305ca3": "Не удалось отрисовать диаграмму.", @@ -1862,7 +1865,6 @@ "1d0a7acef4a95536": "Принять", "255ae21697461ef6": "Возьмите управление, чтобы ответить.", "d2a40ef08ef016ec": "Копировать {command}", - "a034d65164bb39de": "Копировать", "e0cfab9ded209e81": "Переподключить", "b00379f06c304b6a": "Открыть браузер, {title}", "149eba5f977b0549": "Открывает вкладку браузера на весь экран", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 7fd2f945cc033..5b94cd6efe6ea 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -1546,6 +1546,10 @@ "8f2e6a13eee27d59": "Rubriker", "29005b7a742cae1e": "Länkar", "728a49012344e673": "Bilder", + "a034d65164bb39de": "Kopiera", + "0165ef55eb6c8a99": "Kopiera som Markdown", + "439737cb6de2a5b3": "Kopiera bild-URL", + "d3d24474c922eef2": "Kopiera {count} bild-URL:er", "f18f6d80b6bd08a0": "Kopiera modellreferens", "d7a551536aa43f3e": "Dela modellreferens", "9f1b29c948772f0f": "Öppna länk", @@ -1553,7 +1557,6 @@ "d7dc565616d13a5c": "Dela länk", "51244cd196696a00": "Citera", "6cdca065884f77f2": "Kopiera", - "0165ef55eb6c8a99": "Kopiera som Markdown", "7c1923203049d602": "Kopiera kod", "74d986aed0381cb0": "Diagramrenderaren kunde inte läsas in.", "9cc6288e83305ca3": "Diagrammet kunde inte renderas.", @@ -1862,7 +1865,6 @@ "1d0a7acef4a95536": "Godkänn", "255ae21697461ef6": "Ta kontrollen för att svara.", "d2a40ef08ef016ec": "Kopiera {command}", - "a034d65164bb39de": "Kopiera", "e0cfab9ded209e81": "Återanslut", "b00379f06c304b6a": "Öppna webbläsaren, {title}", "149eba5f977b0549": "Öppnar webbläsarfliken i helskärm", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index 54c72efe3b4fb..0478b5b378409 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -1547,6 +1547,10 @@ "8f2e6a13eee27d59": "标题", "29005b7a742cae1e": "链接", "728a49012344e673": "图片", + "a034d65164bb39de": "复制", + "0165ef55eb6c8a99": "复制为 Markdown", + "439737cb6de2a5b3": "复制图片 URL", + "d3d24474c922eef2": "复制 {count} 个图片 URL", "f18f6d80b6bd08a0": "复制模型引用", "d7a551536aa43f3e": "分享模型引用", "9f1b29c948772f0f": "打开链接", @@ -1554,7 +1558,6 @@ "d7dc565616d13a5c": "分享链接", "51244cd196696a00": "引用", "6cdca065884f77f2": "复制", - "0165ef55eb6c8a99": "复制为 Markdown", "7c1923203049d602": "复制代码", "74d986aed0381cb0": "图表渲染器加载失败。", "9cc6288e83305ca3": "无法渲染图表。", @@ -1863,7 +1866,6 @@ "1d0a7acef4a95536": "接受", "255ae21697461ef6": "接管控制后才能回应。", "d2a40ef08ef016ec": "复制 {command}", - "a034d65164bb39de": "复制", "e0cfab9ded209e81": "重新连接", "b00379f06c304b6a": "打开浏览器,{title}", "149eba5f977b0549": "全屏打开浏览器标签页", diff --git a/apps/mobile/src/native/EnrichedMarkdownText.tsx b/apps/mobile/src/native/EnrichedMarkdownText.tsx index 4ef351b39873b..ff542959413ec 100644 --- a/apps/mobile/src/native/EnrichedMarkdownText.tsx +++ b/apps/mobile/src/native/EnrichedMarkdownText.tsx @@ -22,6 +22,7 @@ import { type MarkdownImageBlock, type MarkdownLinkOccurrence, type MarkdownStyle, + type TextSelectionMenuConfig, } from "react-native-enriched-markdown"; import { codeFenceRenderer } from "./codeBlockMarkdown"; import { HighlightedCodeBlock } from "./HighlightedCodeBlock"; @@ -190,6 +191,7 @@ function codeBlockElement( mathRenderingEnabled: boolean, scheme: HighlightScheme, accessibilityLabels: AccessibilityLabels, + selectionMenuConfig: TextSelectionMenuConfig, ): ReactElement | undefined { const renderer = codeFenceRenderer(block.language, mathRenderingEnabled); if (renderer.kind === "mermaid") { @@ -210,6 +212,7 @@ function codeBlockElement( selectionColor={textStyle.selectionColor} selectionHandleColor={textStyle.selectionHandleColor} accessibilityLabels={accessibilityLabels} + selectionMenuConfig={selectionMenuConfig} /> ) : undefined; } @@ -254,6 +257,18 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) { }), [gt], ); + // The library's built-in selection menu items default to English labels. + const selectionMenuConfig = useMemo( + () => ({ + copy: { label: gt("Copy", { $context: "verb" }) }, + copyAsMarkdown: { label: gt("Copy as Markdown") }, + copyImageUrl: { + label: gt("Copy Image URL"), + pluralLabels: { other: gt("Copy {count} Image URLs", { count: "{count}" }) }, + }, + }), + [gt], + ); const { markdown, fileHrefs } = useMemo(() => { if (!fileEmbedLabel) { return { @@ -415,6 +430,7 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) { mathRenderingEnabled, themeAppearance, accessibilityLabels, + selectionMenuConfig, ), }; const resolveNativeImageSource = useRetryingImageSource(resolveImageSource); @@ -472,6 +488,7 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) { : undefined } selectionClipboard={selectionClipboard} + selectionMenuConfig={selectionMenuConfig} selectionColor={props.textStyle.selectionColor} selectionHandleColor={props.textStyle.selectionHandleColor} md4cFlags={{ From 997575be5f5dde8e5443a26ae4cfd4155fa27d87 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 06:06:28 -0800 Subject: [PATCH 022/324] perf(server): pull no longer scans the working tree twice (#40338) --- apps/server/src/vcs/GitVcsDriverCore.test.ts | 50 ++++++++++++++++++++ apps/server/src/vcs/GitVcsDriverCore.ts | 35 ++++++++++++-- 2 files changed, 80 insertions(+), 5 deletions(-) diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index e745669fda5c2..777d46e53d4c9 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -1630,6 +1630,56 @@ describe("pullCurrentBranch", () => { }).pipe(Effect.provide(layerTest)), ); + it.effect("does not scan the working tree to pull", () => + Effect.gen(function* () { + const { cwd, initialBranch, remoteHead } = yield* cloneBehindRemote; + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + const spawnedArgs: Array> = []; + const spawner = ChildProcessSpawner.make((command) => { + if (ChildProcess.isStandardCommand(command)) spawnedArgs.push(command.args.map(String)); + return delegate.spawn(command); + }); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + + const result = yield* driver.pullCurrentBranch(cwd); + + assert.deepEqual(result, { + status: "pulled", + refName: initialBranch, + upstreamRef: `origin/${initialBranch}`, + }); + assert.equal(yield* git(cwd, ["rev-parse", "HEAD"]), remoteHead); + // The status broadcast after a pull re-reads the working tree for the UI. + assert.deepEqual( + spawnedArgs.filter((args) => args.includes("status") || args.includes("--numstat")), + [], + ); + }).pipe(Effect.provide(layerTest)), + ); + + it.effect("pulls into an unborn branch that tracks an unfetched upstream", () => + Effect.gen(function* () { + const { remote, initialBranch, remoteHead } = yield* cloneBehindRemote; + const cwd = yield* makeTmpDir(); + yield* git(cwd, ["init", "--initial-branch", initialBranch]); + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* git(cwd, ["config", `branch.${initialBranch}.remote`, "origin"]); + yield* git(cwd, ["config", `branch.${initialBranch}.merge`, `refs/heads/${initialBranch}`]); + const driver = yield* makeGitVcsDriverCore(); + + const result = yield* driver.pullCurrentBranch(cwd); + + assert.deepEqual(result, { + status: "pulled", + refName: initialBranch, + upstreamRef: `origin/${initialBranch}`, + }); + assert.equal(yield* git(cwd, ["rev-parse", "HEAD"]), remoteHead); + }).pipe(Effect.provide(layerTest)), + ); + it.effect.each([false, true])( "pulls past an unrelated lock with custom fetch mapping=%s", (customMapping) => diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 7fe1dab187ac5..63d8ab594d607 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -3845,8 +3845,34 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const pullCurrentBranch: GitVcsDriver.GitVcsDriver["Service"]["pullCurrentBranch"] = Effect.fn( "pullCurrentBranch", )(function* (cwd) { - const details = yield* readStatusDetailsLocal(cwd); - const refName = details.branch; + const [refName, currentUpstreamRef] = yield* Effect.all( + [ + readCurrentBranch("GitVcsDriver.pullCurrentBranch.branch", cwd), + readCurrentUpstreamRef(cwd), + ], + { concurrency: 2 }, + ); + let upstreamRef = currentUpstreamRef; + // `@{upstream}` needs the tracking ref, which an unborn branch's first pull has not fetched. + if (upstreamRef === null && refName) { + const head = yield* executeGit( + "GitVcsDriver.pullCurrentBranch.head", + cwd, + ["rev-parse", "--verify", "--quiet", "HEAD"], + { allowNonZeroExit: true }, + ); + if (head.exitCode !== 0) { + const [configuredRemote, mergeRef] = yield* Effect.all([ + readConfigValue(cwd, `branch.${refName}.remote`), + readConfigValue(cwd, `branch.${refName}.merge`), + ]); + const mergeBranch = mergeRef?.replace(/^refs\/heads\//, ""); + if (configuredRemote && mergeBranch) { + upstreamRef = + configuredRemote === "." ? mergeBranch : `${configuredRemote}/${mergeBranch}`; + } + } + } if (!refName) { return yield* new GitCommandError({ ...gitCommandContext({ @@ -3857,7 +3883,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* detail: "Cannot pull from detached HEAD.", }); } - if (!details.hasUpstream) { + if (upstreamRef === null) { return yield* new GitCommandError({ ...gitCommandContext({ operation: "GitVcsDriver.pullCurrentBranch", @@ -3973,14 +3999,13 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* true, ).pipe(Effect.map((stdout) => stdout.trim())); - const refreshed = yield* readStatusDetailsLocal(cwd); return { status: beforeSha.length > 0 && beforeSha === afterSha ? ("skipped_up_to_date" as const) : ("pulled" as const), refName, - upstreamRef: refreshed.upstreamRef, + upstreamRef, }; }, Effect.scoped); From 755de001f25c54c9d6435bb23a83ffcd231e06a5 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 06:22:17 -0800 Subject: [PATCH 023/324] fix(server): Antigravity Orchestrator usage prices at the base Gemini 4 rate (#40352) --- .../Drivers/antigravityUsageReader.test.ts | 12 ++++++++++++ .../provider/Drivers/antigravityUsageReader.ts | 16 ++++++++++++---- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/apps/server/src/provider/Drivers/antigravityUsageReader.test.ts b/apps/server/src/provider/Drivers/antigravityUsageReader.test.ts index d0def84f1efe0..88e076d98f208 100644 --- a/apps/server/src/provider/Drivers/antigravityUsageReader.test.ts +++ b/apps/server/src/provider/Drivers/antigravityUsageReader.test.ts @@ -383,6 +383,9 @@ describe("readAntigravityUsage", () => { "gemini-3-flash-agent", "gemini-3-flash", "gemini-default", + "gemini-pro-orchestrator-neon", + "gemini-4-hydrogen-orchestrator", + "gemini-pro-orchestrator-g1-pro", ].entries()) { yield* db.run("INSERT INTO gen_metadata VALUES (?, ?)", [ idx, @@ -393,6 +396,11 @@ describe("readAntigravityUsage", () => { new Uint8Array(protoBytes(9, protoNumber(2, 10 + idx))), ]); } + // Orchestrator (Neon), MODEL_PLACEHOLDER_M537, with no name in the metadata. + yield* db.run("INSERT INTO steps VALUES (?, ?)", [ + 20, + new Uint8Array(protoBytes(9, [...protoNumber(1, 1537), ...protoNumber(2, 30)])), + ]); }), ); const result = yield* readAntigravityUsage(dir, 0); @@ -405,6 +413,10 @@ describe("readAntigravityUsage", () => { ["gemini-3-flash-agent", "gemini-3.5-flash"], ["gemini-3-flash", "gemini-3-flash-preview"], ["gemini-default", undefined], + ["gemini-pro-orchestrator-neon", "gemini-4-neon"], + ["gemini-4-hydrogen-orchestrator", "gemini-4-hydrogen"], + ["gemini-pro-orchestrator-g1-pro", "gemini-4-argon"], + ["gemini-pro-orchestrator-neon", "gemini-4-neon"], ], ); }).pipe(Effect.provide(NodeServices.layer)), diff --git a/apps/server/src/provider/Drivers/antigravityUsageReader.ts b/apps/server/src/provider/Drivers/antigravityUsageReader.ts index 4a71c8ed2b056..5dff65928ad24 100644 --- a/apps/server/src/provider/Drivers/antigravityUsageReader.ts +++ b/apps/server/src/provider/Drivers/antigravityUsageReader.ts @@ -126,18 +126,26 @@ const MODEL_IDS: Record = { 1417: "gemini-4-argon", 1418: "gemini-4-argon", 1419: "gemini-4-argon", + 1537: "gemini-pro-orchestrator-neon", }; // Effort and routing variants share the base model's price. export const antigravityRateModel = (model: string) => { - const base = model.replace(/-(?:extra-low|low|medium|high|tiered|control|thinking|agent)$/, ""); + const base = model.replace( + /-(?:extra-low|low|medium|high|tiered|control|thinking|agent|orchestrator)$/, + "", + ); return /^gemini-3-flash-(?:agent(?:-[ab])?|[ab])$/.test(model) ? "gemini-3.5-flash" : model === "gemini-3.7-flash-safety-le" ? "gemini-3.7-flash" - : base === "gemini-3-flash" - ? "gemini-3-flash-preview" - : base; + : model === "gemini-pro-orchestrator-neon" + ? "gemini-4-neon" + : model === "gemini-pro-orchestrator-g1-pro" + ? "gemini-4-argon" + : base === "gemini-3-flash" + ? "gemini-3-flash-preview" + : base; }; function withRateModel(record: UsageRecord): UsageRecord { From dd941b9c3b581b4a04539255fb85f2b0cbc3fa57 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 06:36:07 -0800 Subject: [PATCH 024/324] fix(server): treat a branch rename as done when Git moved the ref but kept the config locked (#40361) --- apps/server/src/vcs/GitVcsDriverCore.test.ts | 17 +++++++++++++++++ apps/server/src/vcs/GitVcsDriverCore.ts | 17 +++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 777d46e53d4c9..b25e0ff2a8f64 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -7907,6 +7907,23 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("reports a rename as done when Git moved the ref but kept the config locked", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + yield* git(cwd, ["checkout", "-b", "t3/abcd1234"]); + yield* writeTextFile(cwd, ".git/config.lock", ""); + const driver = yield* GitVcsDriver.GitVcsDriver; + + const renamed = yield* TestClock.withLive( + driver.renameBranch({ cwd, oldBranch: "t3/abcd1234", newBranch: "t3/fix-login" }), + ); + + assert.equal(renamed.branch, "t3/fix-login"); + assert.equal(yield* git(cwd, ["branch", "--show-current"]), "t3/fix-login"); + }), + ); + it.effect.each([false, true])( "cleans up links left by successful worktree removal, preserving ordinary files: %s", (keepFile) => diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 63d8ab594d607..4356de894f0b4 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -6661,6 +6661,23 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* timeoutMs: 10_000, fallbackErrorDetail: "git branch rename failed", }, + ).pipe( + // Git exits non-zero after moving the ref when it cannot rewrite the locked config. + Effect.catch((error) => + Effect.all( + [branchExists(input.cwd, input.oldBranch), branchExists(input.cwd, targetBranch)], + { concurrency: "unbounded" }, + ).pipe( + Effect.orElseSucceed(() => [true, false] as const), + Effect.flatMap(([oldExists, newExists]) => + !oldExists && newExists + ? Effect.logWarning( + "GitVcsDriver.renameBranch: renamed the branch but could not move its config entries", + ) + : Effect.fail(error), + ), + ), + ), ); return { branch: targetBranch }; From 27125d7d16829de92c2ede3d4cc905c30ed1ce33 Mon Sep 17 00:00:00 2001 From: Ibrahim Elkamali Date: Sat, 21 Nov 2026 16:59:54 +0200 Subject: [PATCH 025/324] fix(cli): thread --wait --json keeps a result a woken run submits (#40360) Co-authored-by: Julius Marminge --- apps/server/src/cli/thread.test.ts | 11 ++++++++++- apps/server/src/cli/thread.ts | 10 ++++++---- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/apps/server/src/cli/thread.test.ts b/apps/server/src/cli/thread.test.ts index b98314133da84..7231ea7f2b3e0 100644 --- a/apps/server/src/cli/thread.test.ts +++ b/apps/server/src/cli/thread.test.ts @@ -241,6 +241,8 @@ it.effect("--wait lasts until background work the agent waits on wakes it and th status: "completed", timedOut: false, resultRun: { runId: wakeRun, status: "completed" }, + // The wake run submits the result the first run owes, which the server stores there. + output: { head: "abc" }, }, ], // The wake run starts from a notification, which the messages view leaves out. @@ -256,7 +258,12 @@ it.effect("--wait lasts until background work the agent waits on wakes it and th { threadId, runId, timeoutMs: 15_000, untilDelegatedWorkSettled: true }, ], ); - assert.deepStrictEqual(outcome, { type: "ended", runId: wakeRun, status: "completed" }); + assert.deepStrictEqual(outcome, { + type: "ended", + runId: wakeRun, + status: "completed", + output: { head: "abc" }, + }); }), ); @@ -329,6 +336,7 @@ it.effect( status: "completed", timedOut: false, resultRun: { runId: sentRun, status: "failed" }, + output: { head: "abc" }, }, ], t3_thread_read: laterRunReads(sentRun, [{ runId: sentRun, type: "user_message" }]), @@ -338,6 +346,7 @@ it.effect( type: "ended", runId, status: "completed", + output: { head: "abc" }, }); }), ); diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts index ab80f3e1fbb2d..8849f10c6a5ec 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -643,8 +643,10 @@ export const waitForRun = Effect.fn("cli.thread.waitForRun")(function* ( const waited = yield* waitSlice(WAIT_SLICE_MS, true); // `resultRun` is the thread's latest finished run, whoever sent it. const result = waited.timedOut ? undefined : waited.resultRun; + // A later run can submit the result the asked run owes, so read it again. + const settled = waited.output === undefined ? outcome : { ...outcome, output: waited.output }; const after = yield* runsAfter(tools, threadId, finalRunId); - if (after.sent) return outcome; + if (after.sent) return settled; if (!waited.timedOut) { if (result !== undefined && after.later.some((run) => run.runId === result.runId)) { // A run that work woke was not asked for the result; the run before it holds it. @@ -652,13 +654,13 @@ export const waitForRun = Effect.fn("cli.thread.waitForRun")(function* ( type: "ended", runId: result.runId, status: result.status, - ...(outcome.output === undefined ? {} : { output: outcome.output }), + ...(settled.output === undefined ? {} : { output: settled.output }), } satisfies WaitOutcome; } - if (!workOutlivedRun) return outcome; + if (!workOutlivedRun) return settled; if (after.later.some((run) => !TERMINAL_RUN_STATUSES.has(run.status))) continue; if (after.later.length === 0 && (yield* wakeRunRecorded)) continue; - return outcome; + return settled; } workOutlivedRun = true; const { thread } = yield* tools.call( From b4277089795299da077e784f9f3432b3cc1c1c7d Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:43:37 +0530 Subject: [PATCH 026/324] fix(issues): agents can file issues in any bound Linear team (#40299) Co-authored-by: Claude Opus 5.5 --- ...ettingsSourceControlDetailRouteScreens.tsx | 2 +- apps/mobile/src/i18n/translations/de.json | 2 +- apps/mobile/src/i18n/translations/en.json | 2 +- apps/mobile/src/i18n/translations/es.json | 2 +- apps/mobile/src/i18n/translations/fr.json | 2 +- apps/mobile/src/i18n/translations/ja.json | 2 +- apps/mobile/src/i18n/translations/ko.json | 2 +- apps/mobile/src/i18n/translations/pt-BR.json | 2 +- apps/mobile/src/i18n/translations/ru.json | 2 +- apps/mobile/src/i18n/translations/sv.json | 2 +- apps/mobile/src/i18n/translations/zh.json | 2 +- apps/server/src/issue/IssueService.test.ts | 7 +- apps/server/src/issue/IssueService.ts | 27 ++++++-- .../src/mcp/toolkits/issues/handlers.test.ts | 65 +++++++++++++++++++ .../src/mcp/toolkits/issues/handlers.ts | 14 ++-- apps/server/src/mcp/toolkits/issues/tools.ts | 5 ++ .../src/provider/agentContextBudget.json | 2 +- .../settings/IssueTrackerSettings.tsx | 2 +- apps/web/src/i18n/translations/de.json | 2 +- apps/web/src/i18n/translations/en.json | 2 +- apps/web/src/i18n/translations/es.json | 2 +- apps/web/src/i18n/translations/fr.json | 2 +- apps/web/src/i18n/translations/ja.json | 2 +- apps/web/src/i18n/translations/ko.json | 2 +- apps/web/src/i18n/translations/pt-BR.json | 2 +- apps/web/src/i18n/translations/ru.json | 2 +- apps/web/src/i18n/translations/sv.json | 2 +- apps/web/src/i18n/translations/zh.json | 2 +- docs/user/source-control.md | 2 +- evals/mcp-tool-use/cases/issues.ndjson | 2 + .../linear-settings-name-another-team.e2e.ts | 59 +++++++++++++++++ scripts/scenarios/start-app.ts | 4 ++ 32 files changed, 193 insertions(+), 38 deletions(-) create mode 100644 scripts/scenarios/linear-settings-name-another-team.e2e.ts diff --git a/apps/mobile/src/features/settings/SettingsSourceControlDetailRouteScreens.tsx b/apps/mobile/src/features/settings/SettingsSourceControlDetailRouteScreens.tsx index f368dcca2dfc3..957cf17a26178 100644 --- a/apps/mobile/src/features/settings/SettingsSourceControlDetailRouteScreens.tsx +++ b/apps/mobile/src/features/settings/SettingsSourceControlDetailRouteScreens.tsx @@ -199,7 +199,7 @@ export function SettingsIssueTrackerRouteScreen({ diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index e0eb437599e38..f538b87920412 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -3736,7 +3736,7 @@ "b725843fd45b74aa": "Anmeldedaten", "b239ba3ce2899a3e": "Oder verwende deine eigenen Anmeldedaten", "f0e6397ab4de588e": "Token", - "295392927d5c8a84": "Wähle für jedes Projekt ein oder mehrere {scope}s in {tracker}. Ihre Issues erscheinen neben denen des Repositorys, und Agenten legen neue Issues im ersten an.", + "ed83b25c71c98a20": "Wähle für jedes Projekt ein oder mehrere {scope}s in {tracker}. Ihre Issues erscheinen neben denen des Repositorys, und Agenten legen neue Issues im ersten an, sofern kein anderes verlangt wird.", "ce2136b36f87b655": "Verbinde diese Umgebung, um ihre Einstellungen zu ändern.", "a90a441fd0e08de7": "Diese Umgebung", "32fb83554cfd85b4": "Transkriptionsmodelle", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index bca87cee0884f..745201ad99094 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -3738,7 +3738,7 @@ "b725843fd45b74aa": "Credentials", "b239ba3ce2899a3e": "Or use your own credentials", "f0e6397ab4de588e": "Token", - "295392927d5c8a84": "Pick one or more {tracker} {scope}s for each project. Their issues list beside the repository's own, and agents file new issues in the first one.", + "ed83b25c71c98a20": "Pick one or more {tracker} {scope}s for each project. Their issues list beside the repository's own, and agents file new issues in the first one unless asked for another.", "ce2136b36f87b655": "Connect this environment to change its settings.", "a90a441fd0e08de7": "This environment", "32fb83554cfd85b4": "Transcription models", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index 3f73e995b2521..fb134339cd3c4 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -3731,7 +3731,7 @@ "b725843fd45b74aa": "Credenciales", "b239ba3ce2899a3e": "O usa tus propias credenciales", "f0e6397ab4de588e": "Token", - "295392927d5c8a84": "Elige uno o más {scope}s de {tracker} para cada proyecto. Sus issues aparecen junto a las del repositorio, y los agentes crean issues nuevas en el primero.", + "ed83b25c71c98a20": "Elige uno o más {scope}s de {tracker} para cada proyecto. Sus issues aparecen junto a las del repositorio, y los agentes crean issues nuevas en el primero, salvo que se les pida otro.", "ce2136b36f87b655": "Conecta este entorno para cambiar sus ajustes.", "a90a441fd0e08de7": "Este entorno", "32fb83554cfd85b4": "Modelos de transcripción", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index 3aff16728eeff..d6aef220df3a2 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -3731,7 +3731,7 @@ "b725843fd45b74aa": "Identifiants", "b239ba3ce2899a3e": "Ou utilisez vos propres identifiants", "f0e6397ab4de588e": "Jeton", - "295392927d5c8a84": "Choisissez un ou plusieurs {scope}s {tracker} pour chaque projet. Leurs tickets s'affichent à côté de ceux du dépôt, et les agents créent les nouveaux tickets dans le premier.", + "ed83b25c71c98a20": "Choisissez un ou plusieurs {scope}s {tracker} pour chaque projet. Leurs tickets s'affichent à côté de ceux du dépôt, et les agents créent les nouveaux tickets dans le premier, sauf si vous leur indiquez une autre destination.", "ce2136b36f87b655": "Connectez cet environnement pour modifier ses paramètres.", "a90a441fd0e08de7": "Cet environnement", "32fb83554cfd85b4": "Modèles de transcription", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index 302318926d092..8cd9fba5c8332 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -3727,7 +3727,7 @@ "b725843fd45b74aa": "資格情報", "b239ba3ce2899a3e": "または自分の資格情報を使用", "f0e6397ab4de588e": "トークン", - "295392927d5c8a84": "各プロジェクトに {tracker} の {scope} を1つ以上選択します。その Issue はリポジトリ自身の Issue と並べて表示され、エージェントは最初の {scope} に新しい Issue を作成します。", + "ed83b25c71c98a20": "各プロジェクトに {tracker} の {scope} を1つ以上選択します。その Issue はリポジトリ自身の Issue と並べて表示され、エージェントは別の {scope} を指定されない限り、最初の {scope} に新しい Issue を作成します。", "ce2136b36f87b655": "設定を変更するには、この環境に接続してください。", "a90a441fd0e08de7": "この環境", "32fb83554cfd85b4": "文字起こしモデル", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index ec0ee0864e6ef..731eaeecaec22 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -3731,7 +3731,7 @@ "b725843fd45b74aa": "자격 증명", "b239ba3ce2899a3e": "또는 내 자격 증명 사용", "f0e6397ab4de588e": "토큰", - "295392927d5c8a84": "각 프로젝트에 {tracker} {scope}을(를) 하나 이상 선택하세요. 해당 이슈는 저장소 자체 이슈와 함께 표시되며, 에이전트는 첫 번째 {scope}에 새 이슈를 만듭니다.", + "ed83b25c71c98a20": "각 프로젝트에 {tracker} {scope}을(를) 하나 이상 선택하세요. 해당 이슈는 저장소 자체 이슈와 함께 표시되며, 에이전트는 다른 {scope}을(를) 지정받지 않으면 첫 번째 {scope}에 새 이슈를 만듭니다.", "ce2136b36f87b655": "설정을 변경하려면 이 환경에 연결하세요.", "a90a441fd0e08de7": "이 환경", "32fb83554cfd85b4": "받아쓰기 모델", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 56b52f85e6d01..2c4ee1bc64fc4 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -3731,7 +3731,7 @@ "b725843fd45b74aa": "Credenciais", "b239ba3ce2899a3e": "Ou use suas próprias credenciais", "f0e6397ab4de588e": "Token", - "295392927d5c8a84": "Escolha um ou mais {scope}s do {tracker} para cada projeto. As issues deles aparecem ao lado das do repositório, e os agentes criam novas issues no primeiro.", + "ed83b25c71c98a20": "Escolha um ou mais {scope}s do {tracker} para cada projeto. As issues deles aparecem ao lado das do repositório, e os agentes criam novas issues no primeiro, a menos que outro seja pedido.", "ce2136b36f87b655": "Conecte este ambiente para alterar as configurações dele.", "a90a441fd0e08de7": "Este ambiente", "32fb83554cfd85b4": "Modelos de transcrição", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index 9b3b38bcf0234..c4f78e560083b 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -3785,7 +3785,7 @@ "b725843fd45b74aa": "Учётные данные", "b239ba3ce2899a3e": "Или используйте свои учётные данные", "f0e6397ab4de588e": "Токен", - "295392927d5c8a84": "Выберите один или несколько {scope} в {tracker} для каждого проекта. Их issue показываются рядом с issue репозитория, а агенты создают новые issue в первом.", + "ed83b25c71c98a20": "Выберите один или несколько {scope} в {tracker} для каждого проекта. Их issue показываются рядом с issue репозитория, а агенты создают новые issue в первом, если вы не укажете, где их создать.", "ce2136b36f87b655": "Подключите это окружение, чтобы изменить его настройки.", "a90a441fd0e08de7": "Это окружение", "32fb83554cfd85b4": "Модели расшифровки", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 5b94cd6efe6ea..fa3a3dd6d039f 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -3737,7 +3737,7 @@ "b725843fd45b74aa": "Autentiseringsuppgifter", "b239ba3ce2899a3e": "Eller använd dina egna autentiseringsuppgifter", "f0e6397ab4de588e": "Token", - "295392927d5c8a84": "Välj en eller flera {scope} i {tracker} för varje projekt. Deras ärenden listas bredvid repots egna, och agenter skapar nya ärenden i den första.", + "ed83b25c71c98a20": "Välj en eller flera {scope} i {tracker} för varje projekt. Deras ärenden listas bredvid repots egna, och agenter skapar nya ärenden i det första om de inte ombeds välja ett annat.", "ce2136b36f87b655": "Anslut den här miljön för att ändra dess inställningar.", "a90a441fd0e08de7": "Den här miljön", "32fb83554cfd85b4": "Transkriberingsmodeller", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index 0478b5b378409..f36e76805c298 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -3733,7 +3733,7 @@ "b725843fd45b74aa": "凭据", "b239ba3ce2899a3e": "或使用你自己的凭据", "f0e6397ab4de588e": "token", - "295392927d5c8a84": "为每个项目选择一个或多个 {tracker} {scope}。它们的 issue 会列在仓库自身的 issue 旁,智能体会在第一个中创建新 issue。", + "ed83b25c71c98a20": "为每个项目选择一个或多个 {tracker} {scope}。它们的 issue 会列在仓库自身的 issue 旁;除非另有指定,智能体会在第一个中创建新 issue。", "ce2136b36f87b655": "连接此环境以更改其设置。", "a90a441fd0e08de7": "此环境", "32fb83554cfd85b4": "转写模型", diff --git a/apps/server/src/issue/IssueService.test.ts b/apps/server/src/issue/IssueService.test.ts index a291d5bee11f7..e8308b8480d02 100644 --- a/apps/server/src/issue/IssueService.test.ts +++ b/apps/server/src/issue/IssueService.test.ts @@ -699,7 +699,12 @@ describe("IssueService with a standalone tracker", () => { writable: false, }); expect((yield* bound.projectScope("web" as ProjectId)).scope).toBe("ENG"); - expect((yield* bound.projectScope("web" as ProjectId, "ops-12")).scope).toBe("OPS"); + expect((yield* bound.projectScope("web" as ProjectId, { key: "ops-12" })).scope).toBe("OPS"); + expect(yield* bound.projectScope("web" as ProjectId, { scope: "ACME/Web" })).toMatchObject({ + tracker: GITHUB, + host: "github.com", + scope: "acme/web", + }); expect( yield* bound.detail({ projectId: "web" as ProjectId, diff --git a/apps/server/src/issue/IssueService.ts b/apps/server/src/issue/IssueService.ts index a4483e2224927..27499b240d655 100644 --- a/apps/server/src/issue/IssueService.ts +++ b/apps/server/src/issue/IssueService.ts @@ -158,10 +158,13 @@ export class IssueService extends Context.Service< readonly update: (input: IssueUpdateInput) => Effect.Effect; readonly setState: (input: IssueSetStateInput) => Effect.Effect; readonly react: (input: IssueReactionInput) => Effect.Effect; - /** The tracker and container a project's own issues live in, or the one `key` names. */ + /** + * The tracker and container a project's own issues live in: the bound `scope` when named, else + * the one `key`'s prefix names, else the project's default. + */ readonly projectScope: ( projectId: ProjectId, - key?: string, + select?: { readonly key?: string | undefined; readonly scope?: string | undefined }, ) => Effect.Effect; /** * Resolve through a matching project, preferring `preferredProjectId`; other scopes are read-only. @@ -678,14 +681,24 @@ const make = Effect.gen(function* () { const projectScope: IssueService["Service"]["projectScope"] = Effect.fn( "IssueService.projectScope", - )(function* (projectId, key) { + )(function* (projectId, select) { const { supported } = yield* listProjects({ projectId }); - const prefix = key?.toLowerCase(); + if (supported.length === 0) { + return yield* new IssueUnavailableError({ reason: "tracker-unsupported" }); + } + const named = select?.scope?.trim().toLowerCase(); + const prefix = select?.key?.toLowerCase(); const own = - supported.find((candidate) => prefix?.startsWith(`${candidate.scope.toLowerCase()}-`)) ?? - supported[0]; + named === undefined + ? (supported.find((candidate) => prefix?.startsWith(`${candidate.scope.toLowerCase()}-`)) ?? + supported[0]) + : supported.find((candidate) => candidate.scope.toLowerCase() === named); if (own === undefined) { - return yield* new IssueUnavailableError({ reason: "tracker-unsupported" }); + return yield* new IssueOperationError({ + operation: "scope", + reason: "not-found", + detail: `This project does not track ${select?.scope?.trim()}. Use one of: ${[...new Set(supported.map((candidate) => candidate.scope))].join(", ")}.`, + }); } return { projectId, tracker: own.tracker, host: own.host, scope: own.scope }; }); diff --git a/apps/server/src/mcp/toolkits/issues/handlers.test.ts b/apps/server/src/mcp/toolkits/issues/handlers.test.ts index 07f4b4e019204..143ba4a0c98a3 100644 --- a/apps/server/src/mcp/toolkits/issues/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/issues/handlers.test.ts @@ -278,6 +278,71 @@ describe("issue toolkit handlers", () => { }), ); + it.effect("files an issue in the bound Linear team an agent names", () => + Effect.gen(function* () { + const tracker = IssueTrackerKind.make("linear"); + const host = "linear.app"; + const filedIn = yield* Ref.make>([]); + const linear: StandaloneIssueTrackerApi = { + kind: tracker, + capabilities: detail.capabilities, + standalone: { + tracker, + displayName: "Linear", + host, + scopeNoun: "team", + credential: { label: "Personal API key", helpUrl: null }, + }, + parseIssueUrl: () => null, + probeCredential: () => Effect.succeed({ account: "user", scopes: [] }), + getViewer: () => Effect.succeed("user"), + listIssues: () => Effect.succeed({ items: [], nextCursor: null }), + getComments: () => Effect.succeed({ comments: [], nextCursor: null }), + getIssue: () => Effect.die("unused"), + create: ({ scope }) => + Ref.update(filedIn, (teams) => [...teams, scope]).pipe( + Effect.as({ + key: `${scope}-1`, + url: `https://linear.app/acme/issue/${scope}-1`, + displayKey: `${scope}-1`, + }), + ), + }; + const issueLayer = IssueService.layer.pipe( + Layer.provide( + Layer.mergeAll( + projectLayer, + Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({}), + Layer.mock(IssueTrackerBindings.IssueTrackerBindingsRepository)({ + list: Effect.succeed( + new Map([[PROJECT_ID, { tracker, scope: "ENG", additionalScopes: ["OPS"] }]]), + ), + }), + Layer.succeed( + IssueTrackerRegistry.IssueTrackerRegistry, + IssueTrackerRegistry.fromTrackers([linear]), + ), + ), + ), + ); + const harness = yield* makeHarness([], issueLayer); + + expect( + yield* harness.call("create_issue", { title: "Backup ran twice", scope: "ops" }), + ).toMatchObject({ tracker, scope: "OPS", key: "OPS-1" }); + expect(yield* harness.call("create_issue", { title: "Label typo" })).toMatchObject({ + scope: "ENG", + key: "ENG-1", + }); + const unbound = yield* harness + .call("create_issue", { title: "Flaky test", scope: "QA" }) + .pipe(Effect.flip); + expect(unbound).toMatchObject({ _tag: "IssueOperationError", reason: "not-found" }); + expect(unbound.message).toContain("Use one of: ENG, OPS."); + expect(yield* Ref.get(filedIn)).toEqual(["OPS", "ENG"]); + }), + ); + it.effect("refuses a credential without the issues capability", () => Effect.gen(function* () { const harness = yield* makeHarness(); diff --git a/apps/server/src/mcp/toolkits/issues/handlers.ts b/apps/server/src/mcp/toolkits/issues/handlers.ts index 6b835ffb564f9..b45b3d3dbd875 100644 --- a/apps/server/src/mcp/toolkits/issues/handlers.ts +++ b/apps/server/src/mcp/toolkits/issues/handlers.ts @@ -90,15 +90,17 @@ const make = Effect.gen(function* () { /** Where a key-only reference is read: the named project's tracker, or the caller's thread's. */ const requireProjectScope = Effect.fn("IssuesToolkit.requireProjectScope")(function* ( requested: ProjectId | undefined, - key?: string, + select?: { readonly key?: string | undefined; readonly scope?: string | undefined }, ) { // A named project skips the caller's thread, so the capability is checked here too. yield* McpInvocationContext.requireMcpCapability("issues"); const projectId = requested ?? (yield* callerThread())?.projectId; if (projectId === undefined) return yield* new IssueProjectRequiredError(); - return yield* issues - .projectScope(projectId, key) - .pipe(Effect.mapError(() => new IssueProjectNotFoundError({ projectId }))); + return yield* issues.projectScope(projectId, select).pipe( + Effect.catchTags({ + IssueUnavailableError: () => Effect.fail(new IssueProjectNotFoundError({ projectId })), + }), + ); }); /** @@ -116,7 +118,7 @@ const make = Effect.gen(function* () { return { ...resolved, url: input.url } satisfies ResolvedTarget; } if (input.key === undefined) return yield* new IssueTargetIncompleteError(); - const scope = yield* requireProjectScope(input.projectId, input.key); + const scope = yield* requireProjectScope(input.projectId, { key: input.key }); return { ...scope, key: input.key, @@ -231,7 +233,7 @@ const make = Effect.gen(function* () { ), create_issue: McpToolAccess.writesWithCapability((input) => Effect.gen(function* () { - const scope = yield* requireProjectScope(input.projectId); + const scope = yield* requireProjectScope(input.projectId, { scope: input.scope }); const created = yield* issues.create({ ...scope, title: input.title, diff --git a/apps/server/src/mcp/toolkits/issues/tools.ts b/apps/server/src/mcp/toolkits/issues/tools.ts index 20de86b1f9dea..6af757999134d 100644 --- a/apps/server/src/mcp/toolkits/issues/tools.ts +++ b/apps/server/src/mcp/toolkits/issues/tools.ts @@ -284,6 +284,11 @@ const CreateIssueTool = Tool.make("create_issue", { projectId: Schema.optional( ProjectId.annotate({ description: "Defaults to this thread's project." }), ), + scope: Schema.optional( + TrimmedNonEmptyString.annotate({ + description: "A bound team or repository, such as OPS. Defaults to the project's first.", + }), + ), title: TrimmedNonEmptyString.check(Schema.isMaxLength(1024)), body: Schema.optional(Schema.String.check(Schema.isMaxLength(65_536))), labels: Schema.optional(Schema.Array(TrimmedNonEmptyString).check(Schema.isMaxLength(50))), diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index e089e5a84218a..139eba175bc8a 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 6245, "codexAdditionalContextBytes": 7639, - "mcpToolListJsonBytes": 59026 + "mcpToolListJsonBytes": 59052 } diff --git a/apps/web/src/components/settings/IssueTrackerSettings.tsx b/apps/web/src/components/settings/IssueTrackerSettings.tsx index 1bf3e2466f837..72423aaf4ef6e 100644 --- a/apps/web/src/components/settings/IssueTrackerSettings.tsx +++ b/apps/web/src/components/settings/IssueTrackerSettings.tsx @@ -297,7 +297,7 @@ function ProjectBindings({ diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 4f60fef9f6088..c7095b8536469 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -8695,7 +8695,7 @@ "58e0e226493150e7": "Issue-Tracker konnten nicht geladen werden", "77cfcbde543df32d": "Details zu {tracker} ein-/ausblenden", "0083f65885c60156": "{tracker} trennen", - "295392927d5c8a84": "Wähle für jedes Projekt ein oder mehrere {scope}s in {tracker}. Ihre Issues erscheinen neben denen des Repositorys, und Agenten legen neue Issues im ersten an.", + "ed83b25c71c98a20": "Wähle für jedes Projekt ein oder mehrere {scope}s in {tracker}. Ihre Issues erscheinen neben denen des Repositorys, und Agenten legen neue Issues im ersten an, sofern kein anderes verlangt wird.", "19c2d5e81ff8f89a": "{tracker} {scope} für {project}", "68e061510b765772": "Nicht zugeordnet", "a2d95d39d3398bda": "Anmeldedaten abgelehnt", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 6453de11f9da0..2ff8148bb7329 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -8703,7 +8703,7 @@ "58e0e226493150e7": "Could not load issue trackers", "77cfcbde543df32d": "Toggle {tracker} details", "0083f65885c60156": "Disconnect {tracker}", - "295392927d5c8a84": "Pick one or more {tracker} {scope}s for each project. Their issues list beside the repository's own, and agents file new issues in the first one.", + "ed83b25c71c98a20": "Pick one or more {tracker} {scope}s for each project. Their issues list beside the repository's own, and agents file new issues in the first one unless asked for another.", "19c2d5e81ff8f89a": "{tracker} {scope} for {project}", "68e061510b765772": "Not bound", "a2d95d39d3398bda": "Credential rejected", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index a73a02ec3bcc9..78c68c4c0dc2f 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -8693,7 +8693,7 @@ "58e0e226493150e7": "No se pudieron cargar los gestores de issues", "77cfcbde543df32d": "Mostrar u ocultar detalles de {tracker}", "0083f65885c60156": "Desconectar {tracker}", - "295392927d5c8a84": "Elige uno o más {scope}s de {tracker} para cada proyecto. Sus issues aparecen junto a las del repositorio, y los agentes crean issues nuevas en el primero.", + "ed83b25c71c98a20": "Elige uno o más {scope}s de {tracker} para cada proyecto. Sus issues aparecen junto a las del repositorio, y los agentes crean issues nuevas en el primero, salvo que se les pida otro.", "19c2d5e81ff8f89a": "{scope} de {tracker} para {project}", "68e061510b765772": "Sin vincular", "a2d95d39d3398bda": "Credencial rechazada", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 95ea50d6bf22d..873767a296ba5 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -8694,7 +8694,7 @@ "58e0e226493150e7": "Impossible de charger les gestionnaires de tickets", "77cfcbde543df32d": "Afficher ou masquer les détails de {tracker}", "0083f65885c60156": "Déconnecter {tracker}", - "295392927d5c8a84": "Choisissez un ou plusieurs {scope}s {tracker} pour chaque projet. Leurs tickets s'affichent à côté de ceux du dépôt, et les agents créent les nouveaux tickets dans le premier.", + "ed83b25c71c98a20": "Choisissez un ou plusieurs {scope}s {tracker} pour chaque projet. Leurs tickets s'affichent à côté de ceux du dépôt, et les agents créent les nouveaux tickets dans le premier, sauf si vous leur indiquez une autre destination.", "19c2d5e81ff8f89a": "{scope} {tracker} pour {project}", "68e061510b765772": "Non lié", "a2d95d39d3398bda": "Identifiant refusé", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 96bf9c7c7bf48..69ac82ad8a247 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -8651,7 +8651,7 @@ "58e0e226493150e7": "Issue トラッカーを読み込めませんでした", "77cfcbde543df32d": "{tracker} の詳細を切り替え", "0083f65885c60156": "{tracker} を切断", - "295392927d5c8a84": "各プロジェクトに {tracker} の {scope} を1つ以上選択します。その Issue はリポジトリ自身の Issue と並べて表示され、エージェントは最初の {scope} に新しい Issue を作成します。", + "ed83b25c71c98a20": "各プロジェクトに {tracker} の {scope} を1つ以上選択します。その Issue はリポジトリ自身の Issue と並べて表示され、エージェントは別の {scope} を指定されない限り、最初の {scope} に新しい Issue を作成します。", "19c2d5e81ff8f89a": "{project} の {tracker} {scope}", "68e061510b765772": "未バインド", "a2d95d39d3398bda": "資格情報が拒否されました", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index d7b1a7628ffc6..10782b2ca6166 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -8654,7 +8654,7 @@ "58e0e226493150e7": "이슈 트래커를 불러올 수 없습니다", "77cfcbde543df32d": "{tracker} 세부 정보 전환", "0083f65885c60156": "{tracker} 연결 끊기", - "295392927d5c8a84": "각 프로젝트에 {tracker} {scope}을(를) 하나 이상 선택하세요. 해당 이슈는 저장소 자체 이슈와 함께 표시되며, 에이전트는 첫 번째 {scope}에 새 이슈를 만듭니다.", + "ed83b25c71c98a20": "각 프로젝트에 {tracker} {scope}을(를) 하나 이상 선택하세요. 해당 이슈는 저장소 자체 이슈와 함께 표시되며, 에이전트는 다른 {scope}을(를) 지정받지 않으면 첫 번째 {scope}에 새 이슈를 만듭니다.", "19c2d5e81ff8f89a": "{project}의 {tracker} {scope}", "68e061510b765772": "바인딩되지 않음", "a2d95d39d3398bda": "자격 증명 거부됨", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 5097324486fb8..5b2b9e2b9b381 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -8693,7 +8693,7 @@ "58e0e226493150e7": "Não foi possível carregar os rastreadores de issues", "77cfcbde543df32d": "Mostrar ou ocultar detalhes de {tracker}", "0083f65885c60156": "Desconectar {tracker}", - "295392927d5c8a84": "Escolha um ou mais {scope}s do {tracker} para cada projeto. As issues deles aparecem ao lado das do repositório, e os agentes criam novas issues no primeiro.", + "ed83b25c71c98a20": "Escolha um ou mais {scope}s do {tracker} para cada projeto. As issues deles aparecem ao lado das do repositório, e os agentes criam novas issues no primeiro, a menos que outro seja pedido.", "19c2d5e81ff8f89a": "{scope} do {tracker} para {project}", "68e061510b765772": "Não vinculado", "a2d95d39d3398bda": "Credencial recusada", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 4c19189200eb5..0ecadaba9ded1 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -8695,7 +8695,7 @@ "58e0e226493150e7": "Не удалось загрузить issue-трекеры", "77cfcbde543df32d": "Показать или скрыть подробности {tracker}", "0083f65885c60156": "Отключить {tracker}", - "295392927d5c8a84": "Выберите один или несколько {scope} в {tracker} для каждого проекта. Их issue показываются рядом с issue репозитория, а агенты создают новые issue в первом.", + "ed83b25c71c98a20": "Выберите один или несколько {scope} в {tracker} для каждого проекта. Их issue показываются рядом с issue репозитория, а агенты создают новые issue в первом, если вы не укажете, где их создать.", "19c2d5e81ff8f89a": "{tracker} {scope} для {project}", "68e061510b765772": "Не привязано", "a2d95d39d3398bda": "Учётные данные отклонены", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 7add0fa009b1d..1c01b1112768f 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -8701,7 +8701,7 @@ "58e0e226493150e7": "Kunde inte läsa in ärendehanterare", "77cfcbde543df32d": "Visa/dölj detaljer för {tracker}", "0083f65885c60156": "Koppla från {tracker}", - "295392927d5c8a84": "Välj en eller flera {scope} i {tracker} för varje projekt. Deras ärenden listas bredvid repots egna, och agenter skapar nya ärenden i den första.", + "ed83b25c71c98a20": "Välj en eller flera {scope} i {tracker} för varje projekt. Deras ärenden listas bredvid repots egna, och agenter skapar nya ärenden i det första om de inte ombeds välja ett annat.", "19c2d5e81ff8f89a": "{scope} i {tracker} för {project}", "68e061510b765772": "Inte kopplad", "a2d95d39d3398bda": "Autentiseringsuppgiften avvisades", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 5a5c7160230de..43790340d1167 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -8711,7 +8711,7 @@ "58e0e226493150e7": "无法加载 issue 跟踪器", "77cfcbde543df32d": "切换 {tracker} 详情", "0083f65885c60156": "断开 {tracker} 连接", - "295392927d5c8a84": "为每个项目选择一个或多个 {tracker} {scope}。它们的 issue 会列在仓库自身的 issue 旁,智能体会在第一个中创建新 issue。", + "ed83b25c71c98a20": "为每个项目选择一个或多个 {tracker} {scope}。它们的 issue 会列在仓库自身的 issue 旁;除非另有指定,智能体会在第一个中创建新 issue。", "19c2d5e81ff8f89a": "{project} 的 {tracker} {scope}", "68e061510b765772": "未绑定", "a2d95d39d3398bda": "凭据被拒绝", diff --git a/docs/user/source-control.md b/docs/user/source-control.md index c04060ba831a3..cb8d252b9ab37 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -412,7 +412,7 @@ To list Linear issues beside a project's, connect Linear with an API key under Settings → Source control & issues, then pick one or more teams for that project there. Pick another team at any time to add it; uncheck every team to unbind the project. Each team's issues appear in the Linear group of the issue list, sorted with the rest by last update, and -each can be loaded further on its own. Agents file new issues in the first team picked. +each can be loaded further on its own. Agents file new issues in the first team picked unless you name another bound team. Select an issue to open it beside the list: description, comments, state changes, linked pull requests, labels, assignees, and reactions. Linked pull requests open in the same panel. You can diff --git a/evals/mcp-tool-use/cases/issues.ndjson b/evals/mcp-tool-use/cases/issues.ndjson index b3c33cef640e9..16967ba5e17db 100644 --- a/evals/mcp-tool-use/cases/issues.ndjson +++ b/evals/mcp-tool-use/cases/issues.ndjson @@ -1,2 +1,4 @@ {"id":"work-on-issue-links-thread","area":"issues","kind":"bad","pattern":"Agent takes on a tracked issue without linking it to the thread","experience":"Agents linked pull requests but often left the issues they were working on unlinked.","privacy":"commit-safe","setup":{"role":"top","mocks":{"link_issue":{"projectId":"app","tracker":"github","host":"github.com","scope":"acme/app","key":"42","url":"https://github.com/acme/app/issues/42","alreadyLinked":false}},"world":{"repo":"acme/app","files":{"src/label.ts":"export const label = 'Setings';"},"issues":[{"url":"https://github.com/acme/app/issues/42","number":42,"title":"Typo in Settings label","body":"The Settings label says Setings.","state":"open"}],"pages":{"https://github.com/acme/app/issues/42":"Typo in Settings label\nThe Settings label says Setings."}},"context":"The current thread ID is issue-work-thread. Its project ID is app, configured for the GitHub repository acme/app."},"prompt":"Take on https://github.com/acme/app/issues/42. Investigate the Settings label typo, which says Setings, and propose the smallest fix.","expect":{"calls":[{"tool":"link_issue","argsAnyOf":[{"url":"https://github.com/acme/app/issues/42","threadId":null},{"url":"https://github.com/acme/app/issues/42","threadId":"issue-work-thread"},{"key":"42","url":null,"projectId":null,"threadId":null},{"key":"42","url":null,"projectId":null,"threadId":"issue-work-thread"},{"key":"42","url":null,"projectId":"app","threadId":null},{"key":"42","url":null,"projectId":"app","threadId":"issue-work-thread"},{"url":"https://github.com/acme/app/issues/42/","threadId":null},{"url":"https://github.com/acme/app/issues/42/","threadId":"issue-work-thread"}],"success":true}],"finalTextMust":["Setings","Settings"]},"source":{"pr":"https://github.com/pingdotgg/t3code/pull/38356"}} {"id":"read-only-issue-stays-unlinked","area":"issues","kind":"control","pattern":"Read-only issue lookup leaves thread links alone","experience":"An issue used for reference does not belong in the thread's work links.","privacy":"commit-safe","setup":{"role":"top","mocks":{"read_issue":{"url":"https://github.com/acme/app/issues/42","title":"Typo in Settings label","body":"The Settings label says Setings."}},"world":{"repo":"acme/app","issues":[{"url":"https://github.com/acme/app/issues/42","number":42,"title":"Typo in Settings label","body":"The Settings label says Setings.","state":"open"}],"pages":{"https://github.com/acme/app/issues/42":"Typo in Settings label\nThe Settings label says Setings."}}},"prompt":"Summarize https://github.com/acme/app/issues/42 so I can decide whether to take it on.","expect":{"notCalls":["link_issue","unlink_issue","create_issue","comment_on_issue","set_issue_state"],"finalTextMust":["Setings","Settings"]},"source":{"pr":"https://github.com/pingdotgg/t3code/pull/38356"}} +{"id":"create-issue-in-named-team","area":"issues","kind":"bad","pattern":"Agent asked to file in a bound team that is not the project's default","experience":"A project bound to several Linear teams filed every agent-created issue in its default team, even when the user named another bound team.","privacy":"commit-safe","setup":{"role":"top","mocks":{"create_issue":{"projectId":"app","tracker":"linear","host":"linear.app","scope":"OPS","key":"OPS-12","url":"https://linear.app/acme/issue/OPS-12","displayKey":"OPS-12"}},"world":{"repo":"acme/app","files":{"scripts/backup.sh":"#!/bin/sh\n# nightly backup\n"}},"context":"The current thread ID is issue-thread. Its project ID is app, for the GitHub repository acme/app. The project is also bound to the Linear teams ENG (its default) and OPS."},"prompt":"File an issue in our OPS Linear team: the nightly backup job ran twice on Nov 20. No need to investigate, just file it.","expect":{"calls":[{"tool":"create_issue","args":{"scope":"re:^\\s*[Oo][Pp][Ss]\\s*$"},"success":true}],"maxCalls":{"create_issue":1}},"source":{"pr":"https://github.com/pingdotgg/t3code/pull/40023"}} +{"id":"create-issue-default-team","area":"issues","kind":"control","pattern":"Agent files an issue without a team named","experience":"With no team named, an issue belongs in the project's default team.","privacy":"commit-safe","setup":{"role":"top","mocks":{"create_issue":{"projectId":"app","tracker":"linear","host":"linear.app","scope":"ENG","key":"ENG-31","url":"https://linear.app/acme/issue/ENG-31","displayKey":"ENG-31"}},"world":{"repo":"acme/app","files":{"src/label.ts":"export const label = 'Setings';"}},"context":"The current thread ID is issue-thread. Its project ID is app, for the GitHub repository acme/app. The project is also bound to the Linear teams ENG (its default) and OPS."},"prompt":"File an issue: the Settings label in the app says Setings. No need to fix it, just file it.","expect":{"calls":[{"tool":"create_issue","argsAnyOf":[{"scope":null},{"scope":"re:^\\s*[Ee][Nn][Gg]\\s*$"}],"success":true}],"maxCalls":{"create_issue":1}},"source":{"pr":"https://github.com/pingdotgg/t3code/pull/40023"}} diff --git a/scripts/scenarios/linear-settings-name-another-team.e2e.ts b/scripts/scenarios/linear-settings-name-another-team.e2e.ts new file mode 100644 index 0000000000000..32f18c883ab84 --- /dev/null +++ b/scripts/scenarios/linear-settings-name-another-team.e2e.ts @@ -0,0 +1,59 @@ +// @effect-diagnostics-next-line nodeBuiltinImport:off - a fake Linear API for the server to call +import * as NodeHttp from "node:http"; + +import { expect } from "e2e"; + +import { SCENARIO_LINEAR_PORT } from "./start-app.ts"; +import { test, WEB } from "./t3.ts"; + +// Connecting reads only the viewer, the workspace and its teams. +const VIEWER = { + data: { + viewer: { + id: "user-1", + name: "Scenario User", + displayName: "scenario", + email: "user@example.com", + avatarUrl: null, + }, + organization: { urlKey: "acme" }, + teams: { + nodes: [ + { id: "team-eng", key: "ENG", name: "Engineering" }, + { id: "team-ops", key: "OPS", name: "Operations" }, + ], + }, + }, +}; + +test( + "Linear settings say agents can file new issues in another bound team", + WEB, + async ({ t3, app, browser, screen }) => { + const linear = NodeHttp.createServer((_request, response) => { + response.writeHead(200, { "content-type": "application/json" }); + response.end(JSON.stringify(VIEWER)); + }); + await new Promise((resolve) => linear.listen(SCENARIO_LINEAR_PORT, "127.0.0.1", resolve)); + try { + await t3.project("demo"); + await t3.open("/settings/source-control"); + + await screen.getByRole("button", "Toggle Linear details").tap(); + await browser.locator('input[id^="issue-tracker-linear-"]').fill("lin_api_scenario"); + await browser.keyboard.press("Enter"); + await expect( + screen.getByText("Pick one or more Linear teams for each project", { exact: false }), + ).toBeVisible(); + await app.screenshot("linear-projects"); + + await expect( + screen.getByText("agents file new issues in the first one unless asked for another", { + exact: false, + }), + ).toBeVisible(); + } finally { + await new Promise((resolve) => linear.close(resolve)); + } + }, +); diff --git a/scripts/scenarios/start-app.ts b/scripts/scenarios/start-app.ts index 5dc7de2460996..d635f1ba0fd64 100644 --- a/scripts/scenarios/start-app.ts +++ b/scripts/scenarios/start-app.ts @@ -39,9 +39,13 @@ const REAL_PROVIDERS = [ ]; /** Captures must not depend on, or show, the machine that made them. */ +/** Where a scenario serves a fake Linear API; nothing listens there unless one does. */ +export const SCENARIO_LINEAR_PORT = 13_997; + export const SCENARIO_MACHINE_ENV = { T3CODE_ENVIRONMENT_LABEL: "Scenario", T3CODE_ENVIRONMENT_MACHINE_KIND: "laptop", + T3CODE_LINEAR_API_URL: `http://127.0.0.1:${SCENARIO_LINEAR_PORT}/graphql`, }; const encodeSettings = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown)); From 08804b21700b1ec86f5fc593aa9de07fc3a23e5f Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 07:47:46 -0800 Subject: [PATCH 027/324] fix(server): a queued message that names no model runs on the thread's current pick (#40373) --- .../src/orchestration-v2/Orchestrator.ts | 21 +++-- .../SteeringCompletion.integration.test.ts | 68 ++++++++++++++++ .../src/orchestration-v2/runtimeLayer.test.ts | 81 +++++++++++++++++++ packages/contracts/src/orchestrationV2.ts | 2 +- 4 files changed, 163 insertions(+), 9 deletions(-) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index e27fe09d07d1b..24bd270e28945 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -1028,7 +1028,7 @@ function nextQueuedRun( return queuedRunsInDeliveryOrder(projection).find((run) => run.queueHeld !== true); } -// Delegated completions, monitor notifications and unpinned scheduled deliveries never choose a +// Delegated completions, monitor notifications and queued messages that name no model never choose a // model, so a queued one runs on the thread's current pick rather than the one frozen at queue time. function followsCurrentConversation( message: @@ -3564,7 +3564,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio messageId: message.id, steerFollowUpOfRunId: run.id, steerFollowUpAfterRunOrdinal: afterRunOrdinal, - modelSelection: steer?.modelSelection ?? run.modelSelection, + ...(message.followsThreadSelection === true + ? {} + : { modelSelection: steer?.modelSelection ?? run.modelSelection }), text: message.text, ...(message.context ? { context: message.context } : {}), attachments: message.attachments, @@ -7881,6 +7883,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio // restart command that stops the active run goes first, so nothing queued applies before it. // Buffered provider wakes drain output their own provider already produced. const incomingMessage = { ...command, delegatedCompletion }; + // A message that names no model runs on the thread's pick when it starts, not a copy from now. + const followsThreadSelection = + command.modelSelection === undefined && + (command.scheduledTaskId !== undefined || + (shouldQueue && + !followsCurrentConversation(incomingMessage) && + !isBufferedProviderNotification(incomingMessage))); if ( shouldQueue && // A steer whose run ended keeps the thread's selection, as it did before it queued. @@ -8148,9 +8157,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }), ...(command.linkedSender === undefined ? {} : { linkedSender: command.linkedSender }), ...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }), - ...(command.scheduledTaskId !== undefined && command.modelSelection === undefined - ? { followsThreadSelection: true as const } - : {}), + ...(followsThreadSelection ? { followsThreadSelection: true as const } : {}), id: command.messageId, threadId: command.threadId, runId, @@ -8573,9 +8580,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }), ...(command.linkedSender === undefined ? {} : { linkedSender: command.linkedSender }), ...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }), - ...(command.scheduledTaskId !== undefined && command.modelSelection === undefined - ? { followsThreadSelection: true as const } - : {}), + ...(followsThreadSelection ? { followsThreadSelection: true as const } : {}), id: command.messageId, threadId: command.threadId, runId, diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index 3ef67192ceb77..dd2d95cfc1b81 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -2568,6 +2568,74 @@ it.effect("steers a promoted scheduled delivery with the thread's current select ), ); +it.effect("steers a deferred agent message on a pick made while it waited", () => + Effect.scoped( + Effect.gen(function* () { + const { started, steered, steeredSelections, layer, startFirstTurn, events } = + yield* nextTurnSelectionHarness("deferred-agent-steer-selection"); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!; + yield* (yield* EventSink.EventSinkV2).write({ + events: [ + { + id: EventId.make("turn-not-ready"), + type: "provider-turn.updated", + threadId, + occurredAt: yield* DateTime.now, + payload: { ...turn, status: "pending" }, + }, + ], + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("agent-steer"), + threadId, + messageId: MessageId.make("message:agent-steer"), + text: "agent steer", + attachments: [], + dispatchMode: { type: "steer_active", targetRunId: started[0]!.runId }, + createdBy: "agent", + creationSource: "mcp", + }); + const deferred = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.status === "queued", + )!; + assert.equal(deferred.steerWhenReadyRunId, started[0]!.runId); + yield* orchestrator.dispatch({ + type: "thread.model-selection.set", + commandId: CommandId.make("select-composer"), + threadId, + modelSelection: composerSelection, + }); + const promoted = yield* orchestrator.streamDomainEvents.pipe( + Stream.filter( + (event) => + event.type === "run.updated" && + event.payload.id === deferred.id && + event.payload.status === "cancelled", + ), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + yield* Queue.offer(events, { type: "provider_turn.updated", driver, providerTurn: turn }); + yield* Fiber.join(promoted); + yield* worker.drain(); + + assert.lengthOf(steered, 1); + assert.deepEqual(steeredSelections, [composerSelection]); + assert.deepEqual( + (yield* orchestrator.getThreadProjection(threadId)).thread.modelSelection, + composerSelection, + ); + }).pipe(Effect.provide(layer)); + }), + ), +); + const claudeSelection = { instanceId: ProviderInstanceId.make("claudeAgent"), model: "claude-test", diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index c899eb774bfc3..b5072355659ef 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -10051,6 +10051,87 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { }), ); + it.effect( + "starts a queued agent message that names no model on a pick made while it waited", + () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const eventSink = yield* EventSink.EventSinkV2; + const threadId = ThreadId.make("runtime-layer-queued-agent-message-later-pick"); + const pickedSelection = { ...modelSelection, model: "gpt-5.5" }; + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make(`${threadId}:create`), + threadId, + projectId: ProjectId.make(`${threadId}:project`), + createdBy: "user", + creationSource: "web", + title: "Pick while an agent message waits", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: process.cwd(), + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`${threadId}:active`), + threadId, + messageId: MessageId.make(`${threadId}:active`), + text: "active", + attachments: [], + modelSelection, + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`${threadId}:agent`), + threadId, + messageId: MessageId.make(`${threadId}:agent`), + text: "Message from another thread", + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "mcp", + }); + yield* orchestrator.dispatch({ + type: "thread.model-selection.set", + commandId: CommandId.make(`${threadId}:pick`), + threadId, + modelSelection: pickedSelection, + }); + const [active, agent] = (yield* orchestrator.getThreadProjection(threadId)).runs; + assert.isDefined(active); + assert.isDefined(agent); + const now = yield* DateTime.now; + const current = yield* orchestrator.getThreadProjection(threadId); + yield* eventSink.write({ + events: [ + { + id: EventId.make(`${active.id}:completed`), + type: "run.updated", + threadId, + runId: active.id, + occurredAt: now, + payload: { + ...current.runs.find((run) => run.id === active.id)!, + status: "completed", + completedAt: now, + }, + }, + ], + }); + yield* orchestrator.resumeQueuedRuns; + const after = yield* orchestrator.getThreadProjection(threadId); + const delivered = after.runs.find((run) => run.id === agent.id)!; + assert.equal(delivered.status, "starting"); + assert.deepEqual(after.thread.modelSelection, pickedSelection); + assert.deepEqual(delivered.modelSelection, pickedSelection); + }), + ); + it.effect("keeps a buffered provider wake on its own provider behind a queued pick", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index e08c5555a65c8..51d762d77c14f 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -1481,7 +1481,7 @@ export const OrchestrationV2ConversationMessage = Schema.Struct({ notification: Schema.optional(OrchestrationV2Notification), ...OrchestrationV2CreationFields, scheduledTaskId: Schema.optional(ScheduledTaskId), - /** A scheduled delivery that named no model; it runs on the thread's selection at start. */ + /** A message that named no model; it runs on the thread's selection at start. */ followsThreadSelection: Schema.optional(Schema.Literal(true)), senderThreadId: Schema.optional(ThreadId), linkedSender: Schema.optional(OrchestrationV2LinkedSender), From d57b83d85ec2c3be7acb3746f7b6e5f73d4ccf9c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 07:59:24 -0800 Subject: [PATCH 028/324] perf(server): branch list reloads run 6 git processes instead of 9 (#40376) --- apps/server/src/vcs/GitVcsDriverCore.test.ts | 49 ++++++++++++- apps/server/src/vcs/GitVcsDriverCore.ts | 77 +++++++++++++------- packages/shared/src/shell.test.ts | 1 + packages/shared/src/shell.ts | 1 + 4 files changed, 101 insertions(+), 27 deletions(-) diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index b25e0ff2a8f64..e90043e69304b 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -720,7 +720,10 @@ it.effect.each(["bare", "unborn"] as const)( } else { assert.isEmpty(refs.refs); } - assert.equal(spawnedArgs.filter((args) => args.includes("--git-common-dir")).length, 1); + assert.equal( + spawnedArgs.filter((args) => args.includes("--git-common-dir")).length, + state === "bare" ? 2 : 1, + ); }), ).pipe(Effect.provide(layerTest)), ); @@ -829,7 +832,7 @@ it.effect.each(["on a branch", "detached", "unborn"] as const)( file: { path: "new.txt", previousPath: null, sourceKind: "working-tree" }, } as const; const workingTree = yield* driver.getReviewDiffPreview(workingTreeFile); - assert.deepStrictEqual(discoveries(), { commonDir: 1, worktreeRoot: 1, branch: 1 }); + assert.deepStrictEqual(discoveries(), { commonDir: 1, worktreeRoot: 1, branch: 0 }); assert.deepStrictEqual( workingTree.sources .find((source) => source.kind === "working-tree")! @@ -1934,6 +1937,48 @@ it.effect("retries an in-flight ref snapshot invalidated by a mutation", () => ), ); +it.effect("a refreshed ref list reads the current branch and repository paths once", () => + Effect.scoped( + Effect.gen(function* () { + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + const spawnedArgs: Array> = []; + const recordingSpawner = ChildProcessSpawner.make((command) => { + if (ChildProcess.isStandardCommand(command)) spawnedArgs.push(command.args.map(String)); + return delegate.spawn(command); + }); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, recordingSpawner), + ); + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd).pipe(Effect.provideService(GitVcsDriver.GitVcsDriver, driver)); + yield* git(cwd, ["checkout", "-b", "outside-checkout"]).pipe( + Effect.provideService(GitVcsDriver.GitVcsDriver, driver), + ); + spawnedArgs.length = 0; + + // The branch selector's paginated queries send two refreshes at once. + const [first, second] = yield* Effect.all( + [ + driver.listRefs({ cwd, refresh: true }), + driver.listRefs({ cwd, refresh: true, limit: 1 }), + ], + { concurrency: 2 }, + ); + + assert.equal(first.refs.find((ref) => ref.current)?.name, "outside-checkout"); + assert.equal(second.refs.find((ref) => ref.current)?.name, "outside-checkout"); + assert.equal(spawnedArgs.filter((args) => args[0] === "symbolic-ref").length, 1); + assert.equal(spawnedArgs.filter((args) => args[0] === "rev-parse").length, 1); + }), + ).pipe( + Effect.provide( + layerServerConfig.pipe( + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + ), + ), +); + it.effect("superseded ref snapshots of one repository do not evict another's", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 4356de894f0b4..50e620514aa37 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -213,7 +213,6 @@ interface GitRepositoryPaths { readonly gitCommonDir: string; readonly worktreeRoot: string | null; readonly isAtRepositoryRoot: boolean | undefined; - readonly currentBranch: string | null; } interface GitRefsSnapshot { @@ -1665,8 +1664,21 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* } }); - const readGitCommonDir = Effect.fn("readGitCommonDir")(function* (cwd: string) { + const resolveGitCommonDirOutput = Effect.fn("resolveGitCommonDirOutput")(function* ( + cwd: string, + commonDirOutput: string, + ) { // Git reports relative paths from the physical cwd, which can differ from a symlink. + const physicalCwd = yield* fileSystem.realPath(cwd).pipe(Effect.orElseSucceed(() => cwd)); + const resolvedGitCommonDir = path.isAbsolute(commonDirOutput) + ? path.normalize(commonDirOutput) + : path.resolve(physicalCwd, commonDirOutput); + return yield* fileSystem + .realPath(resolvedGitCommonDir) + .pipe(Effect.orElseSucceed(() => resolvedGitCommonDir)); + }); + + const readGitCommonDir = Effect.fn("readGitCommonDir")(function* (cwd: string) { const commonDirResult = yield* executeGitWithStableDiagnostics( "GitVcsDriver.resolveRepositoryPaths.commonDir", cwd, @@ -1694,16 +1706,14 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }); } - const commonDirOutput = commonDirResult.stdout.replace(/\n$/, ""); - const physicalCwd = yield* fileSystem.realPath(cwd).pipe(Effect.orElseSucceed(() => cwd)); - const resolvedGitCommonDir = path.isAbsolute(commonDirOutput) - ? path.normalize(commonDirOutput) - : path.resolve(physicalCwd, commonDirOutput); - return yield* fileSystem - .realPath(resolvedGitCommonDir) - .pipe(Effect.orElseSucceed(() => resolvedGitCommonDir)); + return yield* resolveGitCommonDirOutput(cwd, commonDirResult.stdout.replace(/\n$/, "")); }); + const normalizeWorktreeRootOutput = (cwd: string, output: string) => + output.length > 0 + ? path.normalize(path.isAbsolute(output) ? output : path.resolve(cwd, output)) + : null; + const readWorktreeRoot = Effect.fn("readWorktreeRoot")(function* (cwd: string) { const result = yield* executeGit( "GitVcsDriver.resolveRepositoryPaths.worktreeRoot", @@ -1718,9 +1728,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* // binary mode on Windows). Whitespace before it belongs to the path and must survive, // because this root becomes the editor target for every repository-relative status path. const output = result.stdout.endsWith("\n") ? result.stdout.slice(0, -1) : result.stdout; - return result.exitCode === 0 && output.length > 0 - ? path.normalize(path.isAbsolute(output) ? output : path.resolve(cwd, output)) - : null; + return result.exitCode === 0 ? normalizeWorktreeRootOutput(cwd, output) : null; }); const readCurrentBranch = (operation: string, cwd: string) => @@ -1734,15 +1742,30 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const resolveRepositoryPathsUncached = Effect.fn("resolveRepositoryPathsUncached")(function* ( cwd: string, ) { - const gitCommonDir = yield* readGitCommonDir(cwd); - if (gitCommonDir === null) return null; - const [worktreeRoot, currentBranch] = yield* Effect.all( - [ - readWorktreeRoot(cwd), - readCurrentBranch("GitVcsDriver.resolveRepositoryPaths.currentBranch", cwd), - ], - { concurrency: 2 }, + const layout = yield* executeGitWithStableDiagnostics( + "GitVcsDriver.resolveRepositoryPaths.layout", + cwd, + ["rev-parse", "--git-common-dir", "--show-toplevel"], + { timeoutMs: 5_000, allowNonZeroExit: true }, ); + // --show-toplevel fails outside a work tree (a bare repository), and a newline in either + // path splits the output further; both fall back to separate reads. + const fields = layout.stdout.replace(/\n$/, "").split("\n"); + const [commonDirOutput, worktreeRootOutput] = + layout.exitCode === 0 && fields.length === 2 && fields.every((field) => field.length > 0) + ? fields + : []; + const gitCommonDir = + commonDirOutput === undefined + ? yield* readGitCommonDir(cwd) + : yield* resolveGitCommonDirOutput(cwd, commonDirOutput); + if (gitCommonDir === null) return null; + const worktreeRoot = + worktreeRootOutput !== undefined + ? normalizeWorktreeRootOutput(cwd, worktreeRootOutput) + : layout.exitCode === 0 + ? yield* readWorktreeRoot(cwd) + : null; // Git reports physical roots, so resolve project aliases before comparing. const isAtRepositoryRoot = worktreeRoot === null @@ -1756,7 +1779,6 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* gitCommonDir, worktreeRoot, isAtRepositoryRoot, - currentBranch, } satisfies GitRepositoryPaths; }); @@ -2918,7 +2940,6 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* gitCommonDir, worktreeRoot, isAtRepositoryRoot, - currentBranch: refName, }); } } @@ -5529,6 +5550,12 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* yield* Cache.invalidate(repositoryPathsCache, repositoryPathsCacheKey); }); + // Single-flight only: concurrent ref lists share one read, and none outlives a checkout. + const listRefsCurrentBranchCache = yield* Cache.makeWith( + (cwd: string) => readCurrentBranch("GitVcsDriver.listRefs.currentBranch", cwd), + { capacity: REPOSITORY_PATHS_CACHE_CAPACITY, timeToLive: () => Duration.zero }, + ); + const listRefs: GitVcsDriver.GitVcsDriver["Service"]["listRefs"] = Effect.fn("listRefs")( function* (input) { const repositoryPaths = yield* resolveRepositoryPaths(input.cwd, input.refresh === true).pipe( @@ -5552,8 +5579,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const [snapshot, currentBranch] = yield* Effect.all( [ resolveListRefsSnapshot(repositoryPaths.gitCommonDir, input.refresh === true), - readCurrentBranch("GitVcsDriver.listRefs.currentBranch", input.cwd).pipe( - Effect.orElseSucceed(() => repositoryPaths.currentBranch), + Cache.get(listRefsCurrentBranchCache, normalizeRepositoryPathsCacheKey(input.cwd)).pipe( + Effect.orElseSucceed(() => null), ), ], { concurrency: 2 }, diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts index 4174dcc364972..bae0701fa21c0 100644 --- a/packages/shared/src/shell.test.ts +++ b/packages/shared/src/shell.test.ts @@ -666,6 +666,7 @@ describe("runsGitWithoutConsole", () => { it.each([ [["rev-parse", "--git-path", "index"], true], + [["rev-parse", "--git-common-dir", "--show-toplevel"], true], [ [ "rev-parse", diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.ts index 82a2bc73feb78..0246a507f978d 100644 --- a/packages/shared/src/shell.ts +++ b/packages/shared/src/shell.ts @@ -929,6 +929,7 @@ const CONSOLE_FREE_GIT_READS = [ "rev-parse --git-path index", "rev-parse --git-common-dir", "rev-parse --show-toplevel", + "rev-parse --git-common-dir --show-toplevel", "rev-parse --path-format=absolute --git-path index --git-common-dir --show-toplevel", "rev-parse --symbolic-full-name HEAD", "rev-parse --abbrev-ref --symbolic-full-name @{upstream}", From e337cee9526133c82d9ae97a97c7433fef650779 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 08:09:47 -0800 Subject: [PATCH 029/324] perf(client-runtime): Git menu status refresh keeps the branch list when no ref moved (#40385) --- .../src/vcs/VcsStatusBroadcaster.test.ts | 10 ++++-- apps/server/src/vcs/VcsStatusBroadcaster.ts | 31 +++++++++++++------ packages/client-runtime/src/state/runtime.ts | 3 +- packages/client-runtime/src/state/vcs.test.ts | 21 +++++++++++-- packages/client-runtime/src/state/vcs.ts | 9 +++++- .../src/state/vcsRefInvalidation.ts | 29 +++++++++++++++++ packages/contracts/src/git.ts | 7 +++++ packages/contracts/src/rpc.ts | 4 +-- 8 files changed, 94 insertions(+), 20 deletions(-) diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts index 69c33b785bd41..d30997266c7b7 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts @@ -350,7 +350,7 @@ describe("VcsStatusBroadcaster", () => { yield* broadcaster.refreshLocalStatus(`/other-repo-${index}`); } yield* Deferred.succeed(releasePolicy, undefined); - const result = yield* Fiber.join(refresh); + const { refsDigest: _refsDigest, ...result } = yield* Fiber.join(refresh); assert.deepStrictEqual(result, { ...baseLocalStatus, ...state.currentRemoteStatus }); }).pipe(Effect.provide(layer), Effect.scoped); }); @@ -1568,8 +1568,9 @@ describe("VcsStatusBroadcaster", () => { yield* Deferred.await(subscribed); state.localStatusCalls = 0; - yield* broadcaster.refreshStatus("/repo"); + const unmoved = yield* broadcaster.refreshStatus("/repo"); assert.equal(state.localStatusCalls, 1); + assert.isString(unmoved.refsDigest); state.localStatusCalls = 0; state.currentRemoteStatus = baseRemoteStatus; @@ -1580,6 +1581,8 @@ describe("VcsStatusBroadcaster", () => { const moved = yield* broadcaster.refreshStatus("/repo"); assert.equal(state.localStatusCalls, 2); assert.deepStrictEqual(moved.branchChanges, totals(0).branchChanges); + assert.isString(moved.refsDigest); + assert.notEqual(moved.refsDigest, unmoved.refsDigest); assert.deepStrictEqual( [...(yield* Fiber.join(events))].map((event) => event._tag), // The first refresh adds the totals this palette-style subscription skipped. @@ -1588,8 +1591,9 @@ describe("VcsStatusBroadcaster", () => { state.localStatusCalls = 0; state.refSnapshot = null; - yield* broadcaster.refreshStatus("/repo"); + const unreadable = yield* broadcaster.refreshStatus("/repo"); assert.equal(state.localStatusCalls, 2); + assert.isUndefined(unreadable.refsDigest); }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); }); diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.ts b/apps/server/src/vcs/VcsStatusBroadcaster.ts index 8a507e799c827..5842478fffe76 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.ts @@ -1,3 +1,6 @@ +// @effect-diagnostics-next-line nodeBuiltinImport:off -- A synchronous digest of the ref snapshot already in memory. +import * as NodeCrypto from "node:crypto"; + import * as Cause from "effect/Cause"; import * as Context from "effect/Context"; import * as Deferred from "effect/Deferred"; @@ -20,6 +23,7 @@ import type { VcsBranchStatus, VcsStatusLocalResult, VcsStatusRemoteResult, + VcsRefreshStatusResult, VcsStatusResult, VcsStatusStreamEvent, VcsStatusSubscriptionInput, @@ -231,7 +235,7 @@ export class VcsStatusBroadcaster extends Context.Service< readonly refreshStatus: ( cwd: string, options?: { readonly localOnly?: boolean }, - ) => Effect.Effect; + ) => Effect.Effect; readonly refreshPullRequestStatus: ( cwd: string, ) => Effect.Effect; @@ -711,17 +715,17 @@ export const make = Effect.gen(function* () { const pulled = refreshUpstream ? yield* maybeAutoPull(cwd, remoteRead, [policyCwd]) : null; - if (pulled !== null) return mergeGitStatusParts(pulled.local, pulled.remote); + if (pulled !== null) { + return { status: mergeGitStatusParts(pulled.local, pulled.remote), refs: null }; + } yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true }); // A fetch, ours or not, can move the base used for local Changes totals. - if ( - refsBeforeLocalRead === null || - (yield* workflow.readRefSnapshot(cwd)) !== refsBeforeLocalRead - ) { + const refs = refsBeforeLocalRead === null ? null : yield* workflow.readRefSnapshot(cwd); + if (refs === null || refs !== refsBeforeLocalRead) { yield* refreshLocalStatusCore(cwd); } const parts = yield* getStatusParts(cwd); - return mergeGitStatusParts(parts.local, parts.remote); + return { status: mergeGitStatusParts(parts.local, parts.remote), refs }; }), ); }, @@ -739,7 +743,14 @@ export const make = Effect.gen(function* () { const parts = yield* getStatusParts(cwd); return mergeGitStatusParts(parts.local, parts.remote); } - return yield* refreshRemoteAndLocalTotals(cwd, rawCwd, refsBeforeLocalRead); + const { status, refs } = yield* refreshRemoteAndLocalTotals(cwd, rawCwd, refsBeforeLocalRead); + // Lets the client keep its cached branch list when no ref moved since its last refresh. + return refs === null + ? status + : { + ...status, + refsDigest: NodeCrypto.createHash("sha256").update(refs).digest("hex").slice(0, 32), + }; }, Effect.scoped); const refreshAfterCheckout: VcsStatusBroadcaster["Service"]["refreshAfterCheckout"] = Effect.fn( @@ -947,7 +958,7 @@ export const make = Effect.gen(function* () { // A request made during a refresh needs a read that starts after it, so overlapping requests // share one follow-up. Keyed by raw cwd because auto-pull policy depends on it. // Missing means idle; null means running with no follow-up queued. - type SharedRefresh = Deferred.Deferred; + type SharedRefresh = Deferred.Deferred; const queuedRefreshesRef = yield* Ref.make(new Map()); const runQueuedRefreshes = Effect.fn("VcsStatusBroadcaster.runQueuedRefreshes")(function* ( @@ -974,7 +985,7 @@ export const make = Effect.gen(function* () { "VcsStatusBroadcaster.shareQueuedRefreshStatus", )(function* (rawCwd, options) { if (options?.localOnly) return yield* refreshStatus(rawCwd, options); - const requested = yield* Deferred.make(); + const requested = yield* Deferred.make(); // Registering and forking together keeps an interrupt from leaving an entry with no worker. const shared = yield* Effect.uninterruptible( Effect.gen(function* () { diff --git a/packages/client-runtime/src/state/runtime.ts b/packages/client-runtime/src/state/runtime.ts index f96da6e04ed21..f91f838db78b0 100644 --- a/packages/client-runtime/src/state/runtime.ts +++ b/packages/client-runtime/src/state/runtime.ts @@ -1150,6 +1150,7 @@ export function createEnvironmentRpcCommand< readonly input: NoInfer; }, registry: AtomRegistry.AtomRegistry, + exit: Exit.Exit, unknown>, ) => Effect.Effect; }, ) { @@ -1180,7 +1181,7 @@ export function createEnvironmentRpcCommand< Effect.tap( (result) => options.onSuccess?.(target, registry, result, started) ?? Effect.void, ), - Effect.ensuring(options.onSettled?.(target, registry) ?? Effect.void), + Effect.onExit((exit) => options.onSettled?.(target, registry, exit) ?? Effect.void), ); }, }); diff --git a/packages/client-runtime/src/state/vcs.test.ts b/packages/client-runtime/src/state/vcs.test.ts index 5626c8eef10eb..f58b0d120598d 100644 --- a/packages/client-runtime/src/state/vcs.test.ts +++ b/packages/client-runtime/src/state/vcs.test.ts @@ -384,13 +384,15 @@ describe("cached VCS refs", () => { it.effect("invalidates persisted refs when ref-affecting commands settle", () => Effect.gen(function* () { + const refsDigest = yield* Ref.make("refs-a"); const expectedError = new EnvironmentRpcUnavailableError({ environmentId: TARGET.environmentId, message: "pull failed after fetching refs", }); const client = { [WS_METHODS.vcsPull]: () => Effect.fail(expectedError), - [WS_METHODS.vcsRefreshStatus]: () => Effect.void, + [WS_METHODS.vcsRefreshStatus]: () => + Ref.get(refsDigest).pipe(Effect.map((digest) => ({ refsDigest: digest }))), [WS_METHODS.gitPreparePullRequestThread]: () => Effect.succeed({ branch: "feature/pr", worktreePath: null }), } as unknown as WsRpcProtocolClient; @@ -449,6 +451,19 @@ describe("cached VCS refs", () => { expect(yield* Ref.get(clears)).toBe(2); expect(registry.get(vcsRefsCacheStateAtom(TARGET)).revision).toBe(2); + const refreshStatus = atoms.refreshStatus.run(registry, { + environmentId: TARGET.environmentId, + input: { cwd: "/repo" }, + }); + yield* refreshStatus; + expect(yield* Ref.get(clears)).toBe(2); + expect(registry.get(vcsRefsCacheStateAtom(TARGET)).revision).toBe(2); + + yield* Ref.set(refsDigest, "refs-b"); + yield* refreshStatus; + expect(yield* Ref.get(clears)).toBe(3); + expect(registry.get(vcsRefsCacheStateAtom(TARGET)).revision).toBe(3); + const prepareResult = yield* Effect.exit( createGitEnvironmentAtoms(runtime).preparePullRequestThread.run(registry, { environmentId: TARGET.environmentId, @@ -457,8 +472,8 @@ describe("cached VCS refs", () => { ); expect(Exit.isSuccess(prepareResult)).toBe(true); - expect(yield* Ref.get(clears)).toBe(3); - expect(registry.get(vcsRefsCacheStateAtom(TARGET)).revision).toBe(3); + expect(yield* Ref.get(clears)).toBe(4); + expect(registry.get(vcsRefsCacheStateAtom(TARGET)).revision).toBe(4); }), ); diff --git a/packages/client-runtime/src/state/vcs.ts b/packages/client-runtime/src/state/vcs.ts index 310515ceb9915..a6299aab0ff64 100644 --- a/packages/client-runtime/src/state/vcs.ts +++ b/packages/client-runtime/src/state/vcs.ts @@ -8,6 +8,7 @@ import { import { applyGitStatusStreamEvent } from "@t3tools/shared/git"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as Option from "effect/Option"; import * as Result from "effect/Result"; import * as Schedule from "effect/Schedule"; @@ -35,6 +36,7 @@ import { followStreamInEnvironment } from "./runtime.ts"; import { vcsCommandConcurrency, vcsCommandScheduler } from "./vcsCommandScheduler.ts"; import { invalidateCachedVcsRefs, + invalidateCachedVcsRefsIfChanged, vcsRefsCacheStateAtom, withVcsRefsPersistenceLock, } from "./vcsRefInvalidation.ts"; @@ -339,7 +341,12 @@ export function createVcsEnvironmentAtoms( tag: WS_METHODS.vcsRefreshStatus, scheduler: vcsCommandScheduler, concurrency: vcsCommandConcurrency, - onSettled: invalidateRefs, + onSettled: (target, registry, exit) => + invalidateCachedVcsRefsIfChanged( + registry, + { environmentId: target.environmentId, cwd: target.input.cwd }, + Exit.isSuccess(exit) ? exit.value.refsDigest : undefined, + ), }), // Outside the serial queue: it only reads status, and a checkout picked right after opening // the picker must not wait behind that read. diff --git a/packages/client-runtime/src/state/vcsRefInvalidation.ts b/packages/client-runtime/src/state/vcsRefInvalidation.ts index 6b695d35e668b..54f4a84a3aaac 100644 --- a/packages/client-runtime/src/state/vcsRefInvalidation.ts +++ b/packages/client-runtime/src/state/vcsRefInvalidation.ts @@ -79,3 +79,32 @@ export const invalidateCachedVcsRefs = Effect.fn("VcsRefsState.invalidateCached" }), ); }); + +// Ref digests from each cwd's last status refresh; the cached branch list is at least that new. +const refsDigestsByEnvironment = Atom.family((environmentId: EnvironmentId) => + Atom.make>(new Map()).pipe( + Atom.keepAlive, + Atom.withLabel(`environment-data:vcs:refs-digests:${environmentId}`), + ), +); + +/** Skips the branch list reload when a status refresh saw the same refs as the last one. */ +export const invalidateCachedVcsRefsIfChanged = Effect.fn("VcsRefsState.invalidateCachedIfChanged")( + function* ( + registry: AtomRegistry.AtomRegistry, + target: CachedVcsRefsInvalidationTarget, + refsDigest: string | undefined, + ) { + const digestsAtom = refsDigestsByEnvironment(target.environmentId); + if (refsDigest !== undefined && registry.get(digestsAtom).get(target.cwd) === refsDigest) { + return; + } + registry.update(digestsAtom, (digests) => { + const next = new Map(digests); + if (refsDigest === undefined) next.delete(target.cwd); + else next.set(target.cwd, refsDigest); + return next; + }); + yield* invalidateCachedVcsRefs(registry, target); + }, +); diff --git a/packages/contracts/src/git.ts b/packages/contracts/src/git.ts index 45d68c5e9ca44..751f240f0709e 100644 --- a/packages/contracts/src/git.ts +++ b/packages/contracts/src/git.ts @@ -270,6 +270,13 @@ export const VcsStatusResult = Schema.Struct({ }); export type VcsStatusResult = typeof VcsStatusResult.Type; +export const VcsRefreshStatusResult = Schema.Struct({ + ...VcsStatusResult.fields, + // Digest of the repository's refs after the refresh; absent when they could not be read. + refsDigest: Schema.optional(TrimmedNonEmptyString), +}); +export type VcsRefreshStatusResult = typeof VcsRefreshStatusResult.Type; + export const VcsStatusStreamEvent = Schema.Union([ Schema.TaggedStruct("snapshot", { local: VcsStatusLocalResult, diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index b0892de7b13d9..e30bf9af2937c 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -169,7 +169,7 @@ import { VcsStatusInput, VcsBranchStatus, VcsStatusSubscriptionInput, - VcsStatusResult, + VcsRefreshStatusResult, VcsStatusStreamEvent, } from "./git.ts"; import { @@ -1809,7 +1809,7 @@ const WsVcsRefreshStatusRpc = Rpc.make(WS_METHODS.vcsRefreshStatus, { ...VcsStatusInput.fields, localOnly: Schema.optional(Schema.Boolean), }), - success: VcsStatusResult, + success: VcsRefreshStatusResult, error: Schema.Union([GitManagerServiceError, EnvironmentAuthorizationError]), }); From 7d3677fe70b39d9207ab5470a5ef9a02ee8117e5 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 08:12:07 -0800 Subject: [PATCH 030/324] fix(web): picker branch switches no longer re-read the full local status (#40389) --- .../BranchToolbarBranchSelector.tsx | 24 ++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/BranchToolbarBranchSelector.tsx b/apps/web/src/components/BranchToolbarBranchSelector.tsx index bb6f178ff55d7..2fb938b04bb40 100644 --- a/apps/web/src/components/BranchToolbarBranchSelector.tsx +++ b/apps/web/src/components/BranchToolbarBranchSelector.tsx @@ -101,6 +101,12 @@ interface BranchToolbarBranchSelectorProps { const WORKTREE_CHANGE_BLOCKED_MESSAGE = msg("Stop the current turn to switch worktrees."); +// Picker checkouts by environment and checkout: null while in flight, then the branch it landed +// on. Shared because a draft thread mounts two selectors on one checkout, and the switch's own +// settle reloads refs for both. +const pickerCheckouts = new Map(); +const pickerCheckoutKey = (environmentId: string, cwd: string) => `${environmentId}\u0000${cwd}`; + export function BranchToolbarBranchSelector({ forceNewWorktree = false, ref, @@ -505,6 +511,8 @@ export function BranchToolbarBranchSelector({ runBranchAction(async () => { const previousBranch = resolvedActiveBranch; setOptimisticBranch(selectedBranchName); + const checkoutKey = pickerCheckoutKey(environmentId, selectionTarget.checkoutCwd); + pickerCheckouts.set(checkoutKey, null); const checkoutResult = await switchRef({ environmentId, input: { @@ -516,6 +524,7 @@ export function BranchToolbarBranchSelector({ const nextBranchName = refName.isRemote ? (checkoutResult.value.refName ?? selectedBranchName) : selectedBranchName; + pickerCheckouts.set(checkoutKey, nextBranchName); const movesCheckout = selectionTarget.checkoutCwd !== branchCwd; let hold: BranchHold | null = null; const applied = setThreadBranch( @@ -549,6 +558,7 @@ export function BranchToolbarBranchSelector({ setOptimisticBranch(applied ? nextBranchName : previousBranch); return; } + pickerCheckouts.delete(checkoutKey); setOptimisticBranch(previousBranch); if (!isAtomCommandInterrupted(checkoutResult)) { toastManager.add( @@ -574,6 +584,8 @@ export function BranchToolbarBranchSelector({ runBranchAction(async () => { const previousBranch = resolvedActiveBranch; setOptimisticBranch(name); + const checkoutKey = pickerCheckoutKey(environmentId, branchCwd); + pickerCheckouts.set(checkoutKey, null); const createBranchResult = await createRefMutation({ environmentId, input: { @@ -584,6 +596,7 @@ export function BranchToolbarBranchSelector({ }); if (createBranchResult._tag === "Success") { const nextBranchName = createBranchResult.value.refName; + pickerCheckouts.set(checkoutKey, nextBranchName); const applied = setThreadBranch(nextBranchName, activeWorktreePath); if (applied) { setBranchHold({ @@ -595,6 +608,7 @@ export function BranchToolbarBranchSelector({ setOptimisticBranch(applied ? nextBranchName : previousBranch); return; } + pickerCheckouts.delete(checkoutKey); setOptimisticBranch(previousBranch); if (!isAtomCommandInterrupted(createBranchResult)) { toastManager.add( @@ -627,7 +641,15 @@ export function BranchToolbarBranchSelector({ // A checkout made outside T3 Code, such as a clone finishing, leaves refs listed before it. const statusBranch = branchStatusQuery.data?.refName ?? null; const refreshRefsMissingStatusBranch = useEffectEvent((branch: string | null) => { - if (isInitialBranchesLoadPending || branch === null) return; + if (branch === null || branchCwd === null) return; + // Kept until the checkout reports another branch, so every selector on it skips the refresh. + const checkoutKey = pickerCheckoutKey(environmentId, branchCwd); + if (pickerCheckouts.has(checkoutKey)) { + const pickerBranch = pickerCheckouts.get(checkoutKey); + if (pickerBranch === null || pickerBranch === branch) return; + pickerCheckouts.delete(checkoutKey); + } + if (isInitialBranchesLoadPending) return; if (branchByName.get(branch)?.current !== true) refreshStaleRefs(); }); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reloads refs from the server once per branch live status reports that they do not list as checked out From 8cf94f25425f5987671761e7fd47ade01e40c744 Mon Sep 17 00:00:00 2001 From: Ibrahim Elkamali Date: Sat, 21 Nov 2026 18:16:35 +0200 Subject: [PATCH 031/324] fix(web): a modified click on a remote server opens it after forwarding (#40390) --- .../chat/ThreadServersPanel.browser.test.tsx | 40 +++++++++++++++++++ .../components/chat/ThreadServersPanel.tsx | 21 +++++----- 2 files changed, 51 insertions(+), 10 deletions(-) diff --git a/apps/web/src/components/chat/ThreadServersPanel.browser.test.tsx b/apps/web/src/components/chat/ThreadServersPanel.browser.test.tsx index a2b353554815b..101c31f0c1f7a 100644 --- a/apps/web/src/components/chat/ThreadServersPanel.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadServersPanel.browser.test.tsx @@ -2,6 +2,37 @@ import { EnvironmentId, ThreadId, type DiscoveredLocalServer } from "@t3tools/co import { expect, it, vi } from "vite-plus/test"; import { page } from "vite-plus/test/browser"; +const shell = vi.hoisted(() => ({ openExternal: vi.fn(async (_url: string) => undefined) })); + +vi.mock("~/env", () => ({ isElectron: true })); +vi.mock(import("../../state/portForwards"), async (importOriginal) => ({ + ...(await importOriginal()), + canForwardPorts: () => true, + useForwardLocality: () => "remote" as const, + usePortForwards: () => [], + forwardPort: (async (environmentId: string, remotePort: number) => ({ + environmentId, + remotePort, + localPort: 45000, + })) as never, +})); +vi.mock(import("../../state/session"), async (importOriginal) => ({ + ...(await importOriginal()), + useEnvironmentScope: () => true, +})); +vi.mock(import("../../state/environments"), async (importOriginal) => ({ + ...(await importOriginal()), + useEnvironment: (() => ({ + connection: { phase: "connected" }, + entry: { target: { _tag: "BearerConnectionTarget", connectionId: "saved:remote" } }, + serverConfig: null, + })) as never, +})); +vi.mock(import("../../localApi"), async (importOriginal) => ({ + ...(await importOriginal()), + readLocalApi: (() => ({ shell })) as never, +})); + vi.mock(import("../../portDiscoveryState"), async (importOriginal) => ({ ...(await importOriginal()), useThreadDiscoveredPorts: () => @@ -49,3 +80,12 @@ it("pages servers four at a time, collapses back, and resets on thread switch", await screen.rerender(panel("a")); await expectRows(4); }); + +it("opens a remote server in the system browser through the forward a modified click starts", async () => { + shell.openExternal.mockClear(); + await using _screen = await render(panel("a")); + await page.getByText("localhost:3000", { exact: true }).click({ modifiers: ["ControlOrMeta"] }); + await vi.waitFor(() => + expect(shell.openExternal).toHaveBeenCalledWith("http://localhost:45000/"), + ); +}); diff --git a/apps/web/src/components/chat/ThreadServersPanel.tsx b/apps/web/src/components/chat/ThreadServersPanel.tsx index 5f6f11636e806..e71a6be549a42 100644 --- a/apps/web/src/components/chat/ThreadServersPanel.tsx +++ b/apps/web/src/components/chat/ThreadServersPanel.tsx @@ -106,19 +106,20 @@ function ThreadServersList(props: ThreadServersPanelProps) { event.preventDefault(); // This machine's browser reaches another environment's loopback only through a forward. // Starting a forward runs the probe; only a confirmed local environment opens directly. - const url = - forwardable && locality !== "local" - ? await forwardPort(props.environmentId, server.port).then( - (forward) => forwardedUrl(forward, server.url), - (error: unknown) => { - reportFailure(gt("Could not forward port {port}", { port: server.port }), error); - return null; - }, - ) - : resolveExternalServerUrl(props.environmentId, server.url); + const forwarding = forwardable && locality !== "local"; + const url = forwarding + ? await forwardPort(props.environmentId, server.port).then( + (forward) => forwardedUrl(forward, server.url), + (error: unknown) => { + reportFailure(gt("Could not forward port {port}", { port: server.port }), error); + return null; + }, + ) + : resolveExternalServerUrl(props.environmentId, server.url); if (url === null) return; // Without a forward, a remote environment's localhost would open this machine's instead. if ( + !forwarding && locality !== "local" && tunnelsEnvironmentLoopback(environment?.entry.target) && isLoopbackHost(new URL(url).hostname) From 370b1fde77bec0c38c950e36663ae383b2562dcf Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 08:24:45 -0800 Subject: [PATCH 032/324] fix(server): a no-op fetch on Windows no longer re-resolves the base branch (#40388) --- apps/server/src/vcs/GitVcsDriverCore.test.ts | 6 ++++++ apps/server/src/vcs/GitVcsDriverCore.ts | 18 ++++++++++++++---- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index e90043e69304b..27f4d4eceec59 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -967,8 +967,14 @@ it.effect("resolves a branch's base once while its refs and branch config are un }); assert.deepStrictEqual(reused.sources, withUntracked.sources); yield* (yield* FileSystem.FileSystem).remove(`${cwd}/untracked.txt`); + yield* driver.statusDetailsLocal(cwd); spawnedArgs.length = 0; + // Git for Windows' no-op `fetch --dry-run` touches a refs directory without moving a ref. + NodeFS.utimesSync(`${cwd}/.git/refs/heads`, 1_893_456_000, 1_893_456_000); + yield* driver.statusDetailsLocal(cwd); + assert.equal(lookups(), 0); + yield* git(cwd, ["config", "branch.feature/x.t3-merge-base-ref", "refs/heads/main"]); yield* driver.statusDetailsLocal(cwd); assert.equal(lookups(), 1); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 50e620514aa37..35105aeea90e4 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -2429,8 +2429,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }); // The effective config listing covers included, global, system and worktree config. Git writes - // packed-refs by rename and each loose ref by a rename in its directory, so those stats change - // whenever a ref could. Cost: one git process, plus a stat and listing per refs directory. + // packed-refs and each loose ref by rename, so their stats change whenever a ref could. Directory + // stats are left out: Git for Windows' no-op fetch touches refs/remotes/. + // Cost: one git process, a listing per refs directory and a stat per loose ref. const readBaseBranchInputsStamp = Effect.fn("GitVcsDriverCore.readBaseBranchInputsStamp")( function* (cwd: string, gitCommonDir: string) { const effectiveConfig = yield* executeGit( @@ -2463,16 +2464,25 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* path.join(gitCommonDir, "refs", "heads"), path.join(gitCommonDir, "refs", "remotes"), ]; + const looseRefs: Array = []; for (let index = 0; index < directories.length; index++) { const directory = directories[index]!; - tokens.push(`${directory}=${yield* statToken(directory)}`); const entries = yield* fileSystem .readDirectoryEntries(directory) .pipe(Effect.catchReason("PlatformError", "NotFound", () => Effect.succeed([]))); for (const entry of entries.toSorted((a, b) => a.name.localeCompare(b.name))) { - if (entry.type === "Directory") directories.push(path.join(directory, entry.name)); + const entryPath = path.join(directory, entry.name); + if (entry.type === "Directory") directories.push(entryPath); + else looseRefs.push(entryPath); } } + tokens.push( + ...(yield* Effect.forEach( + looseRefs, + (ref) => Effect.map(statToken(ref), (token) => `${ref}=${token}`), + { concurrency: 16 }, + )), + ); tokens.push(configHash); return tokens.join("\0"); }, From efea1aabe7a5657f5c78f71c12dd49f375886a78 Mon Sep 17 00:00:00 2001 From: Stevu <68607600+Abaans@users.noreply.github.com> Date: Sat, 21 Nov 2026 21:32:02 +0500 Subject: [PATCH 033/324] fix(web): CSV preview rows keep their height during horizontal scroll (#40381) Co-authored-by: Abaan Co-authored-by: Julius Marminge --- .../AttachmentFilePreview.browser.test.tsx | 108 +++++- .../components/files/VirtualTablePreview.tsx | 340 +++++++++++++++++- 2 files changed, 430 insertions(+), 18 deletions(-) diff --git a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx index 16654ba72023c..add8d7368e2ab 100644 --- a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx +++ b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx @@ -72,7 +72,7 @@ vi.mock(import("./office/WordDocument"), async () => { }; }); -import { getClientSettings } from "~/hooks/useSettings"; +import { __setClientSettingsForTests, getClientSettings } from "~/hooks/useSettings"; import { AttachmentFilePreview } from "./AttachmentFilePreview"; import LargeTextViewer from "./LargeTextViewer"; import VirtualTablePreview from "./VirtualTablePreview"; @@ -840,6 +840,112 @@ describe("large text preview recovery", () => { expect(screen.container.textContent).toContain("C19"); }); + it("keeps row height and vertical position stable across horizontal scroll, fresh row arrays, resize, and typography changes", async () => { + const columns = 35; + const header = Array.from({ length: columns }, (_, i) => `Col ${i}`); + const forcedEightLines = Array.from({ length: 8 }, (_, i) => `L${i + 1}`).join("\n"); + const wrappedTwelveWords = Array.from({ length: 12 }, (_, i) => `segment${i + 1}`).join(" "); + const makeRows = () => [ + header, + ...Array.from({ length: 24 }, (_, rowIndex) => + Array.from({ length: columns }, (_, columnIndex) => { + if (rowIndex === 0) { + if (columnIndex >= 10 && columnIndex < 28) return forcedEightLines; + if (columnIndex === 34) return wrappedTwelveWords; + } + if (columnIndex === 33 && rowIndex % 3 === 1) return forcedEightLines; + // Wide lowercase glyphs that wrap without spaces or newlines. + if (rowIndex === 2 && columnIndex === 34) return "m".repeat(11); + return `r${rowIndex + 1}-c${columnIndex}`; + }), + ), + ]; + const view = (width: number) => ( +
    + (page === 0 ? makeRows() : undefined)} + /> +
    + ); + const previousSettings = getClientSettings(); + const previousRootFontSize = document.documentElement.style.fontSize; + try { + await using screen = await render(view(420)); + const horizontal = () => screen.container.querySelector('[role="table"]')!.parentElement!; + const vertical = () => screen.container.querySelector('[tabindex="0"]')!; + const row = (index: number) => + screen.container.querySelector(`[data-preview-row="${index}"]`)!; + + await vi.waitFor(() => { + expect(row(1)).not.toBeNull(); + expect(row(1).getBoundingClientRect().height).toBeGreaterThan(150); + }); + + const initialRow1Height = row(1).getBoundingClientRect().height; + const initialRow2Height = row(2).getBoundingClientRect().height; + const initialRow3Height = row(3).getBoundingClientRect().height; + const initialRow4Top = row(4).getBoundingClientRect().top; + + // Scroll to the far right where the word-wrapped column 34 mounts after 18 newline cells. + await act(() => { + horizontal().scrollLeft = horizontal().scrollWidth; + horizontal().dispatchEvent(new Event("scroll", { bubbles: true })); + }); + await vi.waitFor(() => expect(screen.container.textContent).toContain("segment12")); + + expect(Math.abs(row(1).getBoundingClientRect().height - initialRow1Height)).toBeLessThan(1); + expect(Math.abs(row(2).getBoundingClientRect().height - initialRow2Height)).toBeLessThan(1); + expect(row(3).getBoundingClientRect().height).toBeGreaterThan(40); + expect(Math.abs(row(3).getBoundingClientRect().height - initialRow3Height)).toBeLessThan(1); + expect(Math.abs(row(4).getBoundingClientRect().top - initialRow4Top)).toBeLessThan(1); + + // Scroll vertically into the table, then sweep horizontally back to the left edge. + await act(() => { + vertical().scrollTop = 120; + vertical().dispatchEvent(new Event("scroll", { bubbles: true })); + }); + await vi.waitFor(() => expect(row(5)).not.toBeNull()); + const scrolledRow5Top = row(5).getBoundingClientRect().top; + const scrolledRow5Height = row(5).getBoundingClientRect().height; + + await act(() => { + horizontal().scrollLeft = 0; + horizontal().dispatchEvent(new Event("scroll", { bubbles: true })); + }); + await vi.waitFor(() => expect(screen.container.textContent).toContain("r6-c0")); + + expect(Math.abs(row(5).getBoundingClientRect().height - scrolledRow5Height)).toBeLessThan(1); + expect(Math.abs(row(5).getBoundingClientRect().top - scrolledRow5Top)).toBeLessThan(1); + + // Widening the container widens each uniform column, reducing wrapped line count. + await screen.rerender(view(1600)); + await vi.waitFor(() => + expect(row(1).getBoundingClientRect().height).toBeLessThan(initialRow1Height), + ); + const widenedRow1Height = row(1).getBoundingClientRect().height; + + // Typography changes invalidate cached minimums even at the same container width. + await act(() => { + document.documentElement.style.fontSize = "20px"; + __setClientSettingsForTests({ + ...previousSettings, + fontSizeInterface: previousSettings.fontSizeInterface + 4, + }); + }); + await vi.waitFor(() => + expect(row(1).getBoundingClientRect().height).toBeGreaterThan(widenedRow1Height), + ); + } finally { + document.documentElement.style.fontSize = previousRootFontSize; + __setClientSettingsForTests(previousSettings); + } + }); + it("reveals and highlights requested source lines again for a new request", async () => { const view = (line: number, request: number, loaded = true) => (
    diff --git a/apps/web/src/components/files/VirtualTablePreview.tsx b/apps/web/src/components/files/VirtualTablePreview.tsx index 5154153807df1..229a6efb87329 100644 --- a/apps/web/src/components/files/VirtualTablePreview.tsx +++ b/apps/web/src/components/files/VirtualTablePreview.tsx @@ -1,5 +1,6 @@ /* oxlint-disable react/no-array-index-key -- Positions identify source rows and columns. */ import { useEffect, useEffectEvent, useLayoutEffect, useRef, useState } from "react"; +import { useClientSettings } from "~/hooks/useSettings"; import { observeResize } from "~/lib/observeResize"; import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip"; import { PREVIEW_PAGE_ROWS } from "./largeTextProtocol"; @@ -72,6 +73,7 @@ export default function VirtualTablePreview(props: { ); const offset = (column: number) => offsets[column]!; const tableWidth = props.source ? "100%" : Math.max(width, offset(props.columns) + rowHeader); + const hasHorizontalOverflow = !props.source && offset(props.columns) + rowHeader > width; return (
    | undefined; rowHeader: number; firstColumn: number; viewportHeight: number; @@ -197,6 +201,7 @@ function RowPage( const row = rows?.[local]; const index = start + local; if (props.header && index === 0) return null; + const rowMinHeight = !props.source && row ? props.rowHeights?.get(index) : undefined; return (
    [0], "page">) { +function ScaledRows( + props: Omit[0], "page" | "rowHeights"> & { + hasHorizontalOverflow: boolean; + }, +) { const ref = useRef(null); const contentRef = useRef(null); + const rowProbeRef = useRef(null); + const rowHeightCacheRef = useRef<{ + key: string; + entries: Map; + }>({ key: "", entries: new Map() }); + const [rowHeights, setRowHeights] = useState<{ + key: string; + heights: ReadonlyMap; + }>({ key: "", heights: new Map() }); + const [, setRowMeasureTick] = useState(0); + const typographyKey = useClientSettings( + (settings) => `${settings.fontFamilySans}:${settings.fontSizeInterface}`, + ); const [layout, setLayout] = useState({ offset: 0, height: 0, rowHeight: 29 }); const [top, setTop] = useState(0); const handledReveal = useRef(null); @@ -347,6 +370,87 @@ function ScaledRows(props: Omit[0], "page">) { }, []); const page = Math.floor(first / PREVIEW_PAGE_ROWS); const visibleEnd = (first % PREVIEW_PAGE_ROWS) + Math.ceil(position.height / 29) + 1; + const sizesKey = `${props.sizes.join(",")}|${typographyKey}`; + const pageCount = Math.min( + Math.ceil(visibleEnd / PREVIEW_PAGE_ROWS), + Math.ceil(props.count / PREVIEW_PAGE_ROWS) - page, + ); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Measure mounted rows across all columns before paint so horizontal column virtualization keeps row heights and vertical scroll position stable. + useLayoutEffect(() => { + const probe = rowProbeRef.current; + if (!props.hasHorizontalOverflow || !probe) return; + const probeStyle = getComputedStyle(probe); + const cacheKey = `${sizesKey}|${probeStyle.font}`; + if (rowHeightCacheRef.current.key !== cacheKey) { + rowHeightCacheRef.current = { key: cacheKey, entries: new Map() }; + } + const cache = rowHeightCacheRef.current.entries; + const mountedIndices: number[] = []; + const uncached: Array<{ index: number; row: readonly string[] }> = []; + for (let pageOffset = 0; pageOffset < pageCount; pageOffset++) { + const currentPage = page + pageOffset; + const rows = props.getRows(currentPage); + if (!rows) continue; + const start = currentPage * PREVIEW_PAGE_ROWS; + const limit = visibleEnd - pageOffset * PREVIEW_PAGE_ROWS; + const count = Math.min(PREVIEW_PAGE_ROWS, props.count - start, limit); + for (let local = 0; local < count; local++) { + const index = start + local; + if (props.header && index === 0) continue; + const row = rows[local]; + if (!row) continue; + mountedIndices.push(index); + const existing = cache.get(index); + if (existing && (existing.row === row || sameRowCells(existing.row, row))) { + existing.row = row; + } else { + uncached.push({ index, row }); + } + } + } + let hasRemainingUncached = false; + if (uncached.length > 0) { + const fontSize = Number.parseFloat(probeStyle.fontSize) || 12; + const lineHeight = Number.parseFloat(probeStyle.lineHeight) || fontSize * 1.333; + const { measured, remaining } = measureRowsFullHeight( + probe, + uncached, + props.columns, + props.sizes, + fontSize, + lineHeight, + MAX_SYNC_SCAN_CHARS, + ); + hasRemainingUncached = remaining; + for (const [index, entry] of measured) cache.set(index, entry); + if (cache.size > MAX_CACHED_ROW_HEIGHTS) { + const keep = new Set(mountedIndices); + for (const key of cache.keys()) { + if (cache.size <= MAX_CACHED_ROW_HEIGHTS) break; + if (!keep.has(key)) cache.delete(key); + } + } + } + const next = new Map(); + for (const index of mountedIndices) { + const height = cache.get(index)?.height; + if (height && height > BASE_ROW_HEIGHT) next.set(index, height); + } + setRowHeights((old) => + old.key === cacheKey && sameRowHeightMap(old.heights, next) + ? old + : { key: cacheKey, heights: next }, + ); + if (hasRemainingUncached) { + const frameId = requestAnimationFrame(() => setRowMeasureTick((tick) => tick + 1)); + return () => cancelAnimationFrame(frameId); + } + return undefined; + }); + const activeRowHeights = + props.hasHorizontalOverflow && rowHeights.key.startsWith(`${sizesKey}|`) + ? rowHeights.heights + : undefined; // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Measure mounted row offsets and observe content resizes to position the virtual rows against the scroll track. useLayoutEffect(() => { if (atStart) return; @@ -462,6 +566,13 @@ function ScaledRows(props: Omit[0], "page">) { onScroll={(event) => setTop(event.currentTarget.scrollTop)} >
    + {!props.source ? ( +
    ); } +const BASE_ROW_HEIGHT = 29; +const CELL_HORIZONTAL_INSET = 25; +const CELL_VERTICAL_INSET = 13; +const MAX_MEASURED_CELLS_PER_ROW = 16; +// Wider than any common glyph, so estimates never undercount lines. +const MAX_GLYPH_WIDTH_EM = 1.35; +const MAX_CACHED_ROW_HEIGHTS = 512; +const MAX_SYNC_SCAN_CHARS = 128_000; +const PROBE_CELL_CLASS_NAME = + "box-border border-r border-b border-transparent px-3 py-1.5 whitespace-pre-wrap break-words tabular-nums"; + +interface CachedRowHeight { + row: readonly string[]; + height: number; +} + +interface RowCellCandidate { + readonly column: number; + readonly text: string; + readonly upperLines: number; +} + +/** Conservative greedy word-wrap upper bound on rendered lines without native text shaping. */ +function estimateUpperLines(text: string, innerWidth: number, fontSize: number): number { + const length = text.length; + let lines = 1; + let lineWidth = 0; + let wordWidth = 0; + for (let index = 0; index < length; index++) { + const code = text.charCodeAt(index); + if (code === 10 || code === 13) { + if (code === 13 && index + 1 < length && text.charCodeAt(index + 1) === 10) index++; + if (wordWidth > 0) { + if (lineWidth > 0 && lineWidth + wordWidth > innerWidth) lines++; + wordWidth = 0; + } + lines++; + lineWidth = 0; + continue; + } + if (code === 32 || code === 9) { + const spaceWidth = (code === 9 ? 4.5 : 0.38) * fontSize; + if (wordWidth > 0) { + if (lineWidth > 0 && lineWidth + wordWidth > innerWidth) { + lines++; + lineWidth = wordWidth; + } else { + lineWidth += wordWidth; + } + wordWidth = 0; + } + lineWidth += spaceWidth; + if (lineWidth > innerWidth) { + lines++; + lineWidth = 0; + } + continue; + } + const charWidth = MAX_GLYPH_WIDTH_EM * fontSize; + wordWidth += charWidth; + if (wordWidth > innerWidth) { + if (lineWidth > 0) { + lines++; + lineWidth = 0; + } + lines++; + wordWidth = charWidth; + } + } + if (wordWidth > 0 && lineWidth > 0 && lineWidth + wordWidth > innerWidth) lines++; + return lines; +} + +function collectRowHeightCandidates( + row: readonly string[], + columns: number, + sizes: readonly number[], + fontSize: number, +): { candidates: RowCellCandidate[]; scannedChars: number } { + const candidates: RowCellCandidate[] = []; + const limit = Math.min(columns, row.length); + const maxGlyphWidth = fontSize * MAX_GLYPH_WIDTH_EM; + let scannedChars = 0; + for (let column = 0; column < limit; column++) { + const text = row[column]; + if (!text) continue; + const width = sizes[column]; + if (!width) continue; + const innerWidth = Math.max(1, width - CELL_HORIZONTAL_INSET); + const hasControlWhitespace = text.includes("\n") || text.includes("\r") || text.includes("\t"); + if (!hasControlWhitespace && text.length * maxGlyphWidth <= innerWidth) continue; + scannedChars += text.length; + const upperLines = estimateUpperLines(text, innerWidth, fontSize); + if (!hasControlWhitespace && upperLines <= 1) continue; + candidates.push({ column, text, upperLines }); + } + if (candidates.length > MAX_MEASURED_CELLS_PER_ROW) { + candidates.sort((left, right) => right.upperLines - left.upperLines); + } + return { candidates, scannedChars }; +} + +function measureProbeEntries( + probe: HTMLElement, + entries: ReadonlyArray<{ index: number; column: number; text: string }>, + sizes: readonly number[], + results: Map, +): void { + if (entries.length === 0) return; + const fragment = document.createDocumentFragment(); + const nodes: Array<{ index: number; node: HTMLDivElement }> = []; + for (const entry of entries) { + const node = document.createElement("div"); + node.className = PROBE_CELL_CLASS_NAME; + node.style.width = `${sizes[entry.column]}px`; + node.textContent = entry.text; + fragment.append(node); + nodes.push({ index: entry.index, node }); + } + probe.replaceChildren(fragment); + for (const { index, node } of nodes) { + const height = node.getBoundingClientRect().height; + const current = results.get(index); + if (current && height > current.height) current.height = height; + } + probe.replaceChildren(); +} + +function measureRowsFullHeight( + probe: HTMLElement, + rows: ReadonlyArray<{ index: number; row: readonly string[] }>, + columns: number, + sizes: readonly number[], + fontSize: number, + lineHeight: number, + maxScanChars: number, +): { measured: Map; remaining: boolean } { + const measured = new Map(); + const firstPassEntries: Array<{ index: number; column: number; text: string }> = []; + const overflowRows: Array<{ index: number; candidates: RowCellCandidate[] }> = []; + let scannedChars = 0; + let remaining = false; + for (const { index, row } of rows) { + if (measured.size > 0 && scannedChars >= maxScanChars) { + remaining = true; + break; + } + const collected = collectRowHeightCandidates(row, columns, sizes, fontSize); + scannedChars += collected.scannedChars; + measured.set(index, { row, height: BASE_ROW_HEIGHT }); + const firstBatchCount = Math.min(collected.candidates.length, MAX_MEASURED_CELLS_PER_ROW); + for (let candidateIndex = 0; candidateIndex < firstBatchCount; candidateIndex++) { + const candidate = collected.candidates[candidateIndex]!; + firstPassEntries.push({ index, column: candidate.column, text: candidate.text }); + } + if (collected.candidates.length > MAX_MEASURED_CELLS_PER_ROW) { + overflowRows.push({ index, candidates: collected.candidates }); + } + } + measureProbeEntries(probe, firstPassEntries, sizes, measured); + if (overflowRows.length > 0) { + const secondPassEntries: Array<{ index: number; column: number; text: string }> = []; + for (const { index, candidates } of overflowRows) { + const bestHeight = measured.get(index)?.height ?? BASE_ROW_HEIGHT; + const measuredLines = Math.max( + 1, + Math.floor((bestHeight - CELL_VERTICAL_INSET + 0.5) / lineHeight), + ); + for ( + let candidateIndex = MAX_MEASURED_CELLS_PER_ROW; + candidateIndex < candidates.length; + candidateIndex++ + ) { + const candidate = candidates[candidateIndex]!; + if (candidate.upperLines <= measuredLines) break; + secondPassEntries.push({ index, column: candidate.column, text: candidate.text }); + } + } + measureProbeEntries(probe, secondPassEntries, sizes, measured); + } + return { measured, remaining }; +} + +function sameRowCells(left: readonly string[], right: readonly string[]): boolean { + if (left.length !== right.length) return false; + for (let index = 0; index < left.length; index++) { + if (left[index] !== right[index]) return false; + } + return true; +} + +function sameRowHeightMap( + left: ReadonlyMap, + right: ReadonlyMap, +): boolean { + if (left.size !== right.size) return false; + for (const [index, height] of left) { + if (right.get(index) !== height) return false; + } + return true; +} + function columnLabel(index: number): string { let label = ""; for (let value = index + 1; value > 0; value = Math.floor((value - 1) / 26)) From 1458a4241939b9ba17f78dc219205d1a3fc64557 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 08:53:18 -0800 Subject: [PATCH 034/324] fix(server): transcript cleanup failures tell the user why (#40424) --- apps/server/src/auth/http.ts | 13 ++++- apps/server/src/speech/http.test.ts | 60 +++++++++++++++++++++++ apps/server/src/speech/http.ts | 13 ++++- apps/web/src/speech/voiceInputSession.ts | 14 ++++-- packages/contracts/src/environmentHttp.ts | 2 + 5 files changed, 95 insertions(+), 7 deletions(-) diff --git a/apps/server/src/auth/http.ts b/apps/server/src/auth/http.ts index 86d7330887376..39952a385ba87 100644 --- a/apps/server/src/auth/http.ts +++ b/apps/server/src/auth/http.ts @@ -191,7 +191,11 @@ export const authenticateMediaRequest = export const failEnvironmentInternal = /* Request instrumentation already owns the span; keep this helper in that context. */ - Effect.fnUntraced(function* (reason: EnvironmentInternalErrorReason, error?: unknown) { + Effect.fnUntraced(function* ( + reason: EnvironmentInternalErrorReason, + error?: unknown, + detail?: string, + ) { const traceId = yield* currentEnvironmentTraceId; if (error !== undefined) { yield* Effect.logError("environment api operation failed", { @@ -200,7 +204,12 @@ export const failEnvironmentInternal = cause: error, }); } - return yield* new EnvironmentInternalError({ code: "internal_error", reason, traceId }); + return yield* new EnvironmentInternalError({ + code: "internal_error", + reason, + traceId, + ...(detail === undefined ? {} : { detail }), + }); }); // Plaintext LAN servers still need the cookie; TLS arrives through a proxy that sets X-Forwarded-Proto. diff --git a/apps/server/src/speech/http.test.ts b/apps/server/src/speech/http.test.ts index 770a1b5c94ca5..8bbf2d81bc065 100644 --- a/apps/server/src/speech/http.test.ts +++ b/apps/server/src/speech/http.test.ts @@ -12,6 +12,7 @@ import { CloudSpeechError, DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS, SPEECH_MAX_OPTIONS_BYTES, + TextGenerationError, DEFAULT_SERVER_SETTINGS, EnvironmentAuthenticatedAuth, EnvironmentAuthenticatedPrincipal, @@ -377,3 +378,62 @@ effectIt.effect.each([ }); }), ); + +effectIt.effect("tells the client why transcript cleanup failed", () => + Effect.gen(function* () { + const detail = "OpenCode returned invalid structured output."; + const failingCleanup = Layer.mergeAll( + dependencies, + Layer.succeed( + TextGeneration.TextGeneration, + TextGeneration.TextGeneration.of({ + generateCommitMessage: () => Effect.die("not used"), + generatePrContent: () => Effect.die("not used"), + generateBranchName: () => Effect.die("not used"), + generateThreadTitle: () => Effect.die("not used"), + generateReviewGuide: () => Effect.die("not used"), + generateTranscriptionPostProcessing: () => + Effect.fail( + new TextGenerationError({ + operation: "generateTranscriptionPostProcessing", + detail, + }), + ), + }), + ), + ); + const { handler, dispose } = HttpRouter.toWebHandler( + HttpApiBuilder.layer(HttpApi.make("environment").add(EnvironmentVoiceHttpApi)).pipe( + Layer.provide(speechHttpApiLayer), + Layer.provide(principal(AuthOrchestrationOperateScope)), + Layer.provide(Layer.mock(SpeechService.SpeechService)({})), + Layer.provide(failingCleanup), + // Cleanup makes a real temporary directory; the HTTP services only carry a no-op filesystem. + Layer.provide(NodeServices.layer), + Layer.provide(HttpServer.layerServices), + ), + { disableLogger: true }, + ); + yield* Effect.addFinalizer(() => Effect.promise(dispose)); + const context = yield* Layer.build(Layer.mergeAll(failingCleanup, NodeServices.layer)); + const response = yield* Effect.promise(() => + handler( + new Request("http://localhost/api/voice/post-process", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + options: { + speechCustomWords: [], + speechPostProcessingPrompt: { mode: "default", customInstructions: "" }, + }, + transcript: "um so hello world", + draft: { text: "", selection: { start: 0, end: 0 } }, + }), + }), + context, + ), + ); + expect(response.ok).toBe(false); + expect(yield* Effect.promise(() => response.text())).toContain(detail); + }), +); diff --git a/apps/server/src/speech/http.ts b/apps/server/src/speech/http.ts index 834118b332b05..09c3d4dc23faa 100644 --- a/apps/server/src/speech/http.ts +++ b/apps/server/src/speech/http.ts @@ -9,11 +9,13 @@ import { type EnvironmentSpeechModels, EnvironmentVoiceBodyLimit, SPEECH_MAX_OPTIONS_BYTES, + TextGenerationError, } from "@t3tools/contracts"; import * as ByteSize from "effect/ByteSize"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; import * as HttpServerRequest from "effect/http/HttpServerRequest"; import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder"; @@ -29,6 +31,7 @@ import * as SpeechService from "./SpeechService.ts"; const MAX_TRANSCRIBE_BODY_BYTES = SpeechService.MAX_SPEECH_BYTES + SPEECH_MAX_OPTIONS_BYTES + 4; const parseAudio = Option.liftThrowable(decodeSpeechPcmRequest); +const isTextGenerationError = Schema.is(TextGenerationError); const bodyLimit = Layer.succeed(EnvironmentVoiceBodyLimit, (effect) => Effect.gen(function* () { @@ -233,7 +236,15 @@ export const speechHttpApiLayer = HttpApiBuilder.group( yield* guard(args.endpoint.name); return yield* postProcessing .process(args.payload) - .pipe(Effect.catch((error) => failEnvironmentInternal("internal_error", error))); + .pipe( + Effect.catch((error) => + failEnvironmentInternal( + "internal_error", + error, + isTextGenerationError(error.cause) ? error.cause.detail : undefined, + ), + ), + ); }), ); }), diff --git a/apps/web/src/speech/voiceInputSession.ts b/apps/web/src/speech/voiceInputSession.ts index f048b5653973c..f21285457aa15 100644 --- a/apps/web/src/speech/voiceInputSession.ts +++ b/apps/web/src/speech/voiceInputSession.ts @@ -19,8 +19,9 @@ import type { SpeechStreamText, SpeechTranscriptionOptions, } from "@t3tools/contracts"; -import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts"; +import { DEFAULT_CLIENT_SETTINGS, EnvironmentInternalError } from "@t3tools/contracts"; import { resolveSpeechVocabulary } from "@t3tools/shared/speech"; +import * as Schema from "effect/Schema"; import { useEffect, useSyncExternalStore } from "react"; import { toastManager } from "../components/ui/toast"; @@ -34,6 +35,8 @@ import { bindAudioGrant, readCleanupGrant } from "./voiceConsent"; import { msg } from "gt-react"; import { m } from "../i18n/messages"; +const isEnvironmentInternalError = Schema.is(EnvironmentInternalError); + export const IDLE_VOICE_STATE: VoiceInputState = { phase: "idle", error: null, errorAction: null }; type DraftInput = { @@ -220,12 +223,15 @@ export class VoiceInputSession { releaseRecording: async () => platform.cancelRecording(), deleteRecording: platform.deleteRecording, postProcess, - onPostProcessingError: () => + onPostProcessingError: (error) => { + const added = m(msg("The original transcript was added.")); + const detail = isEnvironmentInternalError(error) ? error.detail : undefined; toastManager.add({ type: "warning", title: m(msg("Transcript cleanup failed")), - description: m(msg("The original transcript was added.")), - }), + description: detail ? `${detail} ${added}` : added, + }); + }, readDraft: (): VoiceDraftSnapshot | null => { const target = this.target; const draft = target?.readDraft(); diff --git a/packages/contracts/src/environmentHttp.ts b/packages/contracts/src/environmentHttp.ts index adda38304a6b2..9b5cd9a0cb5c1 100644 --- a/packages/contracts/src/environmentHttp.ts +++ b/packages/contracts/src/environmentHttp.ts @@ -257,6 +257,8 @@ export class EnvironmentInternalError extends Schema.TaggedError Date: Sat, 21 Nov 2026 08:59:16 -0800 Subject: [PATCH 035/324] fix(acp): Devin's terminal commands run under Git Bash on Windows, not cmd.exe (#40418) --- .../src/server/clientTerminals.ts | 26 +++++++++++++++++-- packages/shared/src/shell.test.ts | 19 ++++++++++++++ packages/shared/src/shell.ts | 14 ++++++++++ 3 files changed, 57 insertions(+), 2 deletions(-) diff --git a/packages/provider-acp/src/server/clientTerminals.ts b/packages/provider-acp/src/server/clientTerminals.ts index 2fda24d4e4fa5..c8371fb7020e8 100644 --- a/packages/provider-acp/src/server/clientTerminals.ts +++ b/packages/provider-acp/src/server/clientTerminals.ts @@ -13,6 +13,7 @@ import * as EffectAcpErrors from "effect-acp/errors"; import type * as EffectAcpSchema from "effect-acp/compat"; import * as NodeBuffer from "node:buffer"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { gitForWindowsBash, SpawnExecutableResolution } from "@t3tools/shared/shell"; const MAX_LIVE_TERMINALS = 16; const MAX_UNRELEASED_TERMINALS = 64; @@ -137,15 +138,27 @@ export interface AcpClientTerminalsOptions { function acpTerminalCommand(input: { readonly request: EffectAcpSchema.CreateTerminalRequest; readonly shellCommands?: boolean | undefined; + /** Windows only: the shell source runs here instead of Node's cmd.exe. */ + readonly posixShell: string | undefined; readonly defaultCwd: string; readonly environment: NodeJS.ProcessEnv; readonly forceKillAfter: Duration.Input; }) { - return ChildProcess.make(input.request.command, input.request.args ?? [], { + const options = { cwd: input.request.cwd ?? input.defaultCwd, env: input.environment, - shell: input.shellCommands === true && (input.request.args?.length ?? 0) === 0, forceKillAfter: input.forceKillAfter, + }; + const isShellSource = input.shellCommands === true && (input.request.args?.length ?? 0) === 0; + if (isShellSource && input.posixShell !== undefined) { + // Native tools write in the console code page and output is decoded as UTF-8. The spawner + // hides the window, so each terminal has its own console and the change stays inside it. + const source = `chcp.com 65001 >/dev/null 2>&1\n${input.request.command}`; + return ChildProcess.make(input.posixShell, ["-c", source], options); + } + return ChildProcess.make(input.request.command, input.request.args ?? [], { + ...options, + shell: isShellSource, }); } @@ -170,6 +183,7 @@ export const makeAcpClientTerminals = Effect.fn("makeAcpClientTerminals")(functi const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const forceKillAfter = options.forceKillAfter ?? "5 seconds"; const isWindows = yield* HostProcess.isWindows; + const resolveExecutable = yield* SpawnExecutableResolution; const creationPermit = yield* Semaphore.make(1); const terminals = new Map(); let nextTerminalNumber = 1; @@ -246,6 +260,13 @@ export const makeAcpClientTerminals = Effect.fn("makeAcpClientTerminals")(functi Object.entries(sessionEnvironment ?? {}), (request.env ?? []).map((variable) => [variable.name, variable.value] as const), ]); + // Agents that send shell source write bash; Node's shell on Windows is cmd.exe. + const gitExecutable = + isWindows && options.shellCommands === true + ? resolveExecutable("git", "win32", environment) + : undefined; + const posixShell = + gitExecutable === undefined ? undefined : gitForWindowsBash(gitExecutable); const terminalScope = yield* Scope.make(); const child = yield* restore( spawner @@ -253,6 +274,7 @@ export const makeAcpClientTerminals = Effect.fn("makeAcpClientTerminals")(functi acpTerminalCommand({ request, shellCommands: options.shellCommands, + posixShell, defaultCwd: options.defaultCwd, environment, forceKillAfter, diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts index bae0701fa21c0..32ed8d2b46116 100644 --- a/packages/shared/src/shell.test.ts +++ b/packages/shared/src/shell.test.ts @@ -23,6 +23,7 @@ import { CommandAvailability, CommandResolutionCache, type CommandAvailabilityChecker, + gitForWindowsBash, isCommandAvailable, listLoginShellCandidates, mergePathEntries, @@ -758,6 +759,24 @@ describe("preferGitForWindowsBinary", () => { }); }); +describe("gitForWindowsBash", () => { + const bash = "C:\\Program Files\\Git\\bin\\bash.exe"; + const isBash = (filePath: string) => filePath === bash; + + it.each([ + "C:\\Program Files\\Git\\cmd\\git.exe", + "C:\\Program Files\\Git\\bin\\git.exe", + "C:\\Program Files\\Git\\mingw64\\bin\\git.exe", + ])("finds Git Bash from %s", (git) => { + expect(gitForWindowsBash(git, isBash)).toBe(bash); + }); + + it("finds nothing without a Git for Windows bash", () => { + expect(gitForWindowsBash("C:\\Users\\me\\scoop\\shims\\git.exe", isBash)).toBeUndefined(); + expect(gitForWindowsBash("C:\\Program Files\\Git\\cmd\\gitk.exe", () => true)).toBeUndefined(); + }); +}); + // Byte for byte what `npm install -g opencode-ai` writes as `opencode.cmd`. const NPM_OPENCODE_SHIM = [ "@ECHO off", diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.ts index 0246a507f978d..05a1d5b14bd79 100644 --- a/packages/shared/src/shell.ts +++ b/packages/shared/src/shell.ts @@ -813,6 +813,20 @@ export function preferGitForWindowsBinary( return executable; } +/** Git for Windows' bash beside a git.exe from its install, never WSL's System32 bash.exe. */ +export function gitForWindowsBash( + gitExecutable: string, + isFile: (filePath: string) => boolean = isFileSync, +): string | undefined { + const path = NodePath.win32; + if (path.basename(gitExecutable).toLowerCase() !== "git.exe") return undefined; + // git.exe lives in \cmd, \bin, or \\bin. + const launcherRoot = path.dirname(path.dirname(gitExecutable)); + return [launcherRoot, path.dirname(launcherRoot)] + .map((root) => path.join(root, "bin", "bash.exe")) + .find(isFile); +} + // npm cmd-shim format for native executables. const NPM_EXECUTABLE_SHIM_PREFIX = [ "@ECHO off", From d4d54658f919d1b643566f579f6fabe109927628 Mon Sep 17 00:00:00 2001 From: Sungyong Cho Date: Sat, 21 Nov 2026 17:59:27 +0100 Subject: [PATCH 036/324] fix(server): a delegated task still reaches its parent when its first update fails (#37225) Co-authored-by: Julius Marminge --- .../DelegatedChildTerminalRetry.test.ts | 328 ++++++++++++++++++ .../src/orchestration-v2/Orchestrator.ts | 137 +++++--- 2 files changed, 421 insertions(+), 44 deletions(-) create mode 100644 apps/server/src/orchestration-v2/DelegatedChildTerminalRetry.test.ts diff --git a/apps/server/src/orchestration-v2/DelegatedChildTerminalRetry.test.ts b/apps/server/src/orchestration-v2/DelegatedChildTerminalRetry.test.ts new file mode 100644 index 0000000000000..b9c20c02b5afe --- /dev/null +++ b/apps/server/src/orchestration-v2/DelegatedChildTerminalRetry.test.ts @@ -0,0 +1,328 @@ +import { assert, it } from "@effect/vitest"; +import { + CommandId, + MessageId, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + ProviderThreadId, + ProviderTurnId, + ThreadId, + type OrchestrationV2DomainEvent, +} from "@t3tools/contracts"; +import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as Queue from "effect/Queue"; +import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; + +import { ClaudeProviderCapabilitiesV2 } from "./Adapters/ClaudeAdapterV2.ts"; +import * as EffectWorker from "./EffectWorker.ts"; +import * as Orchestrator from "./Orchestrator.ts"; +import * as ProjectionStore from "./ProjectionStore.ts"; +import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; +import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts"; + +const driver = ProviderDriverKind.make("claudeAgent"); +const instanceId = ProviderInstanceId.make("claudeAgent"); +const modelSelection = { instanceId, model: "claude-test" }; +const parentThreadId = ThreadId.make("thread:delegated-terminal-retry-parent"); +const childError = "Failed to initialize session: No space left on device"; + +type ParentRead = { + readonly store: ProjectionStore.ProjectionStoreV2["Service"]; + readonly threadId: ThreadId; + readonly fields: ReadonlyArray; + readonly filter: Parameters[2]; +}; + +// The parent hears of a child only from the reaction to the child's terminal run. +// The injected failure stands in for a storage error, such as a full disk, and fails once. +const runDelegation = (input: { + readonly name: string; + readonly parentEndsFirst: boolean; + readonly failRead?: (read: ParentRead) => Effect.Effect; + readonly failChildRunMessage?: boolean; +}) => + Effect.gen(function* () { + const cwd = yield* checkpointWorkspace(input.name); + let armed = false; + const turns: Array<{ + readonly turn: ProviderAdapter.ProviderAdapterV2TurnInput; + readonly events: Queue.Queue; + }> = []; + const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = { + instanceId, + driver, + getCapabilities: () => Effect.succeed(ClaudeProviderCapabilitiesV2), + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }), + openSession: (session) => + Effect.gen(function* () { + const now = yield* DateTime.now; + const events = yield* Queue.unbounded(); + return { + instanceId, + driver, + providerSessionId: session.providerSessionId, + providerSession: { + id: session.providerSessionId, + driver, + providerInstanceId: instanceId, + status: "ready", + cwd, + model: modelSelection.model, + capabilities: ClaudeProviderCapabilitiesV2, + createdAt: now, + updatedAt: now, + lastError: null, + }, + events: Stream.fromQueue(events), + ensureThread: ({ threadId }) => + IdAllocator.isDelegatedTaskThread(threadId) + ? Effect.fail( + new ProviderAdapter.ProviderAdapterEnsureThreadError({ + driver, + threadId, + cause: new Error(childError), + }), + ) + : Effect.succeed({ + id: ProviderThreadId.make(`provider-thread:${threadId}`), + driver, + providerInstanceId: instanceId, + providerSessionId: session.providerSessionId, + appThreadId: threadId, + ownerNodeId: null, + nativeThreadRef: { driver, nativeId: `native:${threadId}`, strength: "strong" }, + nativeConversationHeadRef: null, + status: "idle", + firstRunOrdinal: null, + lastRunOrdinal: null, + handoffIds: [], + forkedFrom: null, + createdAt: now, + updatedAt: now, + }), + resumeThread: ({ providerThread }) => Effect.succeed(providerThread), + startTurn: (turn) => + Effect.gen(function* () { + turns.push({ turn, events }); + yield* Queue.offer(events, { + type: "provider_turn.updated", + driver, + providerTurn: { + id: ProviderTurnId.make(`provider-turn:${turn.attemptId}`), + providerThreadId: turn.providerThread.id, + nodeId: turn.rootNodeId, + runAttemptId: turn.attemptId, + nativeTurnRef: null, + ordinal: turn.providerTurnOrdinal, + status: "running", + startedAt: now, + completedAt: null, + }, + }); + }), + steerTurn: () => Effect.die("unused"), + interruptTurn: () => Effect.void, + respondToRuntimeRequest: () => Effect.die("unused"), + readThreadSnapshot: () => Effect.die("unused"), + rollbackThread: () => Effect.die("unused"), + forkThread: () => Effect.die("unused"), + }; + }), + }; + const layerTest = ProviderReplayHarness.layerWithRegistry( + { name: input.name }, + ProviderAdapterRegistry.layerSingle(adapter), + { + runEffectWorker: false, + runContinuationWorker: true, + wrapProjectionStore: (store) => ({ + ...store, + getThreadRecords: (threadId, fields, filter) => + Effect.gen(function* () { + if ( + armed && + input.failRead !== undefined && + (yield* input.failRead({ store, threadId, fields, filter })) + ) { + armed = false; + return yield* new ProjectionStore.ProjectionStoreReadError({ threadId }); + } + return yield* store.getThreadRecords(threadId, fields, filter); + }), + getRunMessage: (threadId, runId) => { + if ( + !armed || + !input.failChildRunMessage || + !IdAllocator.isDelegatedTaskThread(threadId) + ) { + return store.getRunMessage(threadId, runId); + } + armed = false; + return Effect.fail(new ProjectionStore.ProjectionStoreReadError({ threadId })); + }, + }), + }, + ); + + return yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) => + orchestrator.streamDomainEvents.pipe( + Stream.filter(predicate), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("create-parent"), + threadId: parentThreadId, + projectId: ProjectId.make("project:delegated-terminal-retry"), + title: "Parent", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: cwd, + createdBy: "user", + creationSource: "web", + }); + const parentRunning = yield* watch( + (event) => event.type === "provider-turn.updated" && event.payload.status === "running", + ); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("start-parent"), + threadId: parentThreadId, + messageId: MessageId.make("message:start-parent"), + text: "Delegate a review", + attachments: [], + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + }); + yield* worker.drain(); + yield* Fiber.join(parentRunning); + const parentRun = (yield* orchestrator.getThreadProjection(parentThreadId)).runs[0]!; + + yield* orchestrator.dispatch({ + type: "delegated_task.request", + commandId: CommandId.make("delegate"), + parentThreadId, + parentRunId: parentRun.id, + parentNodeId: parentRun.rootNodeId!, + task: "Review the change", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + completionWake: "always", + createdBy: "agent", + creationSource: "mcp", + }); + const task = (yield* orchestrator.getThreadProjection(parentThreadId)).subagents[0]!; + const childThreadId = task.childThreadId!; + + const endParentTurn = Effect.gen(function* () { + const parentTurn = (yield* orchestrator.getThreadProjection(parentThreadId)) + .providerTurns[0]!; + const parentEvents = turns.find((entry) => entry.turn.threadId === parentThreadId)!.events; + const now = yield* DateTime.now; + yield* Queue.offer(parentEvents, { + type: "provider_turn.updated", + driver, + providerTurn: { ...parentTurn, status: "completed", completedAt: now }, + }); + yield* Queue.offer(parentEvents, { + type: "turn.terminal", + driver, + providerThreadId: parentTurn.providerThreadId, + providerTurnId: parentTurn.id, + runOrdinal: parentRun.ordinal, + status: "completed", + failure: null, + threadDisposition: "reusable", + }); + }); + + if (input.parentEndsFirst) { + const parentEnded = yield* watch( + (event) => + event.type === "run.updated" && + event.payload.id === parentRun.id && + event.payload.status !== "running", + ); + yield* endParentTurn; + yield* Fiber.join(parentEnded); + } + + armed = true; + const childFailed = yield* watch( + (event) => + event.type === "run.updated" && + event.payload.threadId === childThreadId && + event.payload.status === "failed", + ); + for (let attempt = 0; attempt < 5; attempt++) { + yield* worker.drain(); + yield* TestClock.adjust("1 second"); + } + yield* Fiber.join(childFailed); + + if (!input.parentEndsFirst) yield* endParentTurn; + for (let attempt = 0; attempt < 5; attempt++) { + yield* worker.drain(); + yield* TestClock.adjust("30 seconds"); + } + + assert.isFalse(armed, "the injected read failed once"); + const parent = yield* orchestrator.getThreadProjection(parentThreadId); + const settled = parent.subagents.find((row) => row.id === task.id); + assert.equal(settled?.status, "failed"); + assert.equal(settled?.result, childError); + assert.isTrue( + parent.messages.some( + (message) => message.delegatedCompletion?.taskIds.includes(task.id) === true, + ), + "the parent is woken with the child's failure", + ); + }).pipe(Effect.provide(layerTest)); + }); + +it.effect("a delegated child that fails to start reaches its parent after a failed read", () => + runDelegation({ + name: "delegated-child-terminal-retry", + parentEndsFirst: false, + // Only finalizing the parent's task reads its rows by child thread. + failRead: ({ filter }) => Effect.succeed(filter?.subagentChildThreadIds !== undefined), + }), +); + +it.effect("an idle parent is woken when its wake fails after the task settles", () => + runDelegation({ + name: "delegated-child-terminal-wake-retry", + parentEndsFirst: true, + failRead: ({ store, threadId, fields, filter }) => + threadId !== parentThreadId || fields.join() !== "runs" || filter?.runIds === undefined + ? Effect.succeed(false) + : store.getThreadRecords(parentThreadId, ["subagents"]).pipe( + Effect.map((records) => records.subagents.some((task) => task.result !== null)), + Effect.orDie, + ), + }), +); + +it.effect("a delegated child reaches its parent after its own delivery read fails", () => + runDelegation({ + name: "delegated-child-terminal-delivery-read", + parentEndsFirst: false, + failChildRunMessage: true, + }), +); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 24bd270e28945..dd69750a43496 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -101,14 +101,17 @@ import { } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; +import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; +import * as FiberSet from "effect/FiberSet"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; import * as Result from "effect/Result"; +import * as Schedule from "effect/Schedule"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; @@ -979,6 +982,14 @@ function delegatedCompletionWakeDetail( .join("\n\n"); } +// Startup recovery settles whatever is still missed after this window. +const parentTaskSyncRetry = Schedule.exponential("1 second").pipe( + Schedule.modifyDelay(({ duration }) => + Effect.succeed(Duration.min(duration, Duration.seconds(30))), + ), + Schedule.upTo({ duration: Duration.hours(1) }), +); + function isTerminalDelegatedTaskStatus(status: OrchestrationV2Subagent["status"]): boolean { return ( status === "completed" || @@ -2142,6 +2153,23 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } }); + const offerChildTaskDeliveries = + /* This helper runs for individual orchestration events; the enclosing operation owns the span. */ + Effect.fnUntraced(function* (parentThreadId: ThreadId, childThreadId: ThreadId) { + // A task's wake lives on the run that requested it; the parent's other wakes are not this child's. + const { subagents } = yield* projectionStore.getThreadRecords(parentThreadId, ["subagents"], { + subagentChildThreadIds: [childThreadId], + }); + const parentRunIds = new Set( + subagents.flatMap((task) => + task.childThreadId === childThreadId && task.runId !== null ? [task.runId] : [], + ), + ); + for (const parentRunId of parentRunIds) { + yield* offerDelegatedCompletionDelivery(parentThreadId, parentRunId); + } + }); + /** Marks a wake the provider received delivered and reserves the next one for pending siblings. */ const acceptDelegatedCompletionDelivery = Effect.fn( "Orchestrator.acceptDelegatedCompletionDelivery", @@ -16462,6 +16490,57 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio : dispatch; }); + const parentTaskSyncRetries = yield* FiberSet.make(); + const syncDelegatedParentTask = Effect.fn("Orchestrator.syncDelegatedParentTask")(function* ( + childThreadId: ThreadId, + options: { readonly syncRunId: RunId | undefined; readonly retry: boolean }, + ) { + const parentThreadId = yield* appOwnedSubagentParentThreadId(childThreadId); + if (parentThreadId === undefined) return; + const finalize = finalizeAppOwnedSubagent( + childThreadId, + options.syncRunId === undefined ? undefined : { syncRunId: options.syncRunId }, + ); + yield* threadDispatch.withLock( + parentThreadId, + // A failed attempt may have committed the result before offering its wake. + options.retry + ? offerChildTaskDeliveries(parentThreadId, childThreadId).pipe(Effect.andThen(finalize)) + : finalize, + ); + }); + // Only these reactions tell a parent about its child before a restart; a dropped one leaves its task running. + const updateDelegatedParentTask = Effect.fn("Orchestrator.updateDelegatedParentTask")(function* ( + childThreadId: ThreadId, + syncRunId?: RunId, + ) { + const context = { + threadId: childThreadId, + ...(syncRunId === undefined ? {} : { runId: syncRunId }), + }; + yield* syncDelegatedParentTask(childThreadId, { syncRunId, retry: false }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("Retrying a delegated task update for its parent", { + ...context, + cause, + }).pipe( + Effect.andThen( + syncDelegatedParentTask(childThreadId, { syncRunId, retry: true }).pipe( + Effect.retry({ schedule: parentTaskSyncRetry }), + Effect.delay("1 second"), + Effect.catchCause((cause) => + Effect.logWarning("Failed to update a delegated task for its parent", { + ...context, + cause, + }), + ), + FiberSet.run(parentTaskSyncRetries), + ), + ), + ), + ), + ); + }); const handleRunUpdate = Effect.fn("Orchestrator.handleRunUpdate")( function* (stored: OrchestrationV2StoredEvent) { if (stored.event.type !== "run.updated") return; @@ -16483,10 +16562,17 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ), ); } - yield* threadDispatch.withLock( - threadId, - finalizeDelegatedCompletionDelivery(threadId, run.id), - ); + yield* threadDispatch + .withLock(threadId, finalizeDelegatedCompletionDelivery(threadId, run.id)) + .pipe( + Effect.catchCause((cause) => + Effect.logWarning("Failed to settle a delegated completion delivery", { + threadId, + runId: run.id, + cause, + }), + ), + ); yield* threadDispatch .withLock( threadId, @@ -16515,13 +16601,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ), ); } - const parentThreadId = yield* appOwnedSubagentParentThreadId(threadId); - if (parentThreadId !== undefined) { - yield* threadDispatch.withLock( - parentThreadId, - finalizeAppOwnedSubagent(threadId, { syncRunId: run.id }), - ); - } + yield* updateDelegatedParentTask(threadId, run.id); }, (effect, stored) => effect.pipe( @@ -16656,23 +16736,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ).pipe( Stream.filter(settlesChildWork), Stream.runForEach((stored) => - threadReactions.run( - stored.event.threadId, - Effect.gen(function* () { - const childThreadId = stored.event.threadId; - const parentThreadId = yield* appOwnedSubagentParentThreadId(childThreadId); - if (parentThreadId === undefined) return; - yield* threadDispatch.withLock(parentThreadId, finalizeAppOwnedSubagent(childThreadId)); - }).pipe( - Effect.catchCause((cause) => - Effect.logWarning("Failed to finalize a delegated child after its work settled", { - threadId: stored.event.threadId, - sequence: stored.sequence, - cause, - }), - ), - ), - ), + threadReactions.run(stored.event.threadId, updateDelegatedParentTask(stored.event.threadId)), ), Effect.forkScoped, ); @@ -16855,22 +16919,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio return; yield* threadDispatch.withLock( parentThreadId, - Effect.gen(function* () { - // A task's wake lives on the run that requested it; the parent's other wakes are not this child's. - const { subagents } = yield* projectionStore.getThreadRecords( - parentThreadId, - ["subagents"], - { subagentChildThreadIds: [threadId] }, - ); - const parentRunIds = new Set( - subagents.flatMap((task) => - task.childThreadId === threadId && task.runId !== null ? [task.runId] : [], - ), - ); - for (const parentRunId of parentRunIds) { - yield* offerDelegatedCompletionDelivery(parentThreadId, parentRunId); - } - }).pipe( + offerChildTaskDeliveries(parentThreadId, threadId).pipe( Effect.andThen( finalizeAppOwnedSubagent( threadId, From 3b15a01fca4bb76328e592e7706d3a888d16cf18 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 09:15:39 -0800 Subject: [PATCH 037/324] fix(server): worktree threads start when a checkout hook already linked a nested clone (#40419) --- apps/server/src/workspace/TaskFolders.test.ts | 58 +++++++++++++++++++ apps/server/src/workspace/TaskFolders.ts | 55 ++++++++++++------ 2 files changed, 95 insertions(+), 18 deletions(-) diff --git a/apps/server/src/workspace/TaskFolders.test.ts b/apps/server/src/workspace/TaskFolders.test.ts index 37fd360cf8b24..c156f190e0049 100644 --- a/apps/server/src/workspace/TaskFolders.test.ts +++ b/apps/server/src/workspace/TaskFolders.test.ts @@ -347,6 +347,64 @@ it.live("puts a clone the project ignores inside the project's worktree", () => ), ); +it.live("creates the task folder when the project's checkout hook already linked a clone", () => + withState((state) => + Effect.gen(function* () { + const { fileSystem, path, tmp, run, repository } = yield* fixture; + const project = yield* repository("p"); + yield* fileSystem.writeFileString(path.join(project, ".gitignore"), "vendor/\n"); + yield* run(project, "add", "."); + yield* run(project, "commit", "-m", "ignore vendor"); + const lib = yield* repository("p/vendor/lib"); + // Like many projects with vendored clones, a new worktree links them back to the checkout. + const hooks = path.join(tmp, "hooks"); + yield* fileSystem.makeDirectory(hooks); + yield* fileSystem.writeFileString( + path.join(hooks, "post-checkout"), + `#!/bin/sh\nmkdir -p vendor && ln -s "${lib}" vendor/lib\n`, + { mode: 0o755 }, + ); + yield* run(project, "config", "core.hooksPath", hooks); + state.workspaceRoot = project; + state.trackedFolders = tracked(lib); + + const created = yield* create("feature").pipe(Effect.exit); + + assert.isTrue(Exit.isSuccess(created), String(Exit.isFailure(created) && created.cause)); + }), + ), +); + +it.live("leaves a hook's link to an empty folder alone", () => + withState((state) => + Effect.gen(function* () { + const { fileSystem, path, tmp, run, repository } = yield* fixture; + const project = yield* repository("p"); + yield* fileSystem.writeFileString(path.join(project, ".gitignore"), "vendor/\n"); + yield* run(project, "add", "."); + yield* run(project, "commit", "-m", "ignore vendor"); + const lib = yield* repository("p/vendor/lib"); + const target = path.join(tmp, "empty"); + yield* fileSystem.makeDirectory(target); + const hooks = path.join(tmp, "hooks"); + yield* fileSystem.makeDirectory(hooks); + yield* fileSystem.writeFileString( + path.join(hooks, "post-checkout"), + `#!/bin/sh\nmkdir -p vendor && ln -s "${target}" vendor/lib\n`, + { mode: 0o755 }, + ); + yield* run(project, "config", "core.hooksPath", hooks); + state.workspaceRoot = project; + state.trackedFolders = tracked(lib); + + const created = yield* create("feature").pipe(Effect.exit); + + assert.isTrue(Exit.isSuccess(created), String(Exit.isFailure(created) && created.cause)); + assert.deepStrictEqual(yield* fileSystem.readDirectory(target), []); + }), + ), +); + it.live("treats a project folder inside a larger repository as plain", () => withState((state) => Effect.gen(function* () { diff --git a/apps/server/src/workspace/TaskFolders.ts b/apps/server/src/workspace/TaskFolders.ts index 3dd74d90d2d80..4911065118ce4 100644 --- a/apps/server/src/workspace/TaskFolders.ts +++ b/apps/server/src/workspace/TaskFolders.ts @@ -243,6 +243,16 @@ const make = Effect.gen(function* () { const exists = (target: string) => fileSystem.exists(target).pipe(Effect.orElseSucceed(() => false)); const isRepository = (folder: string) => exists(path.join(folder, ".git")); + const occupied = Effect.fnUntraced(function* (target: string) { + if (!(yield* exists(target))) return false; + const isDirectory = (yield* fileSystem.stat(target).pipe(Effect.option)).pipe( + Option.exists((info) => info.type === "Directory"), + ); + if (!isDirectory) return true; + return ( + (yield* fileSystem.readDirectory(target).pipe(Effect.orElseSucceed(() => [""]))).length > 0 + ); + }); const trackedFolders = (project: { readonly workspaceRoot: string; readonly trackedFolders: ReadonlyArray; @@ -855,6 +865,13 @@ const make = Effect.gen(function* () { baseBranch: string | undefined, ) { const worktreePath = mapped(taskFolder, repository.path); + // The project's own checkout (a post-checkout hook, say) already provided this repository. + // A link counts even to an empty folder: Git would write the worktree through it. + if ( + Option.isSome(yield* fileSystem.readLink(worktreePath).pipe(Effect.option)) || + (yield* occupied(worktreePath)) + ) + return null; yield* fileSystem.makeDirectory(path.dirname(worktreePath), { recursive: true }); const start = yield* repositoryStart(repository.path, startFromOrigin, baseBranch); yield* git.createWorktree({ @@ -1006,6 +1023,9 @@ const make = Effect.gen(function* () { } else { yield* linkFolder(taskPlan.projectRoot, empty.projectPath, taskPlan.trackedRepositories); } + let finished = 0; + // Whatever the project put at a skipped path also stands for the repositories inside it. + const skipped: string[] = []; // A repository inside another waits for the one that holds it. const levels = Map.groupBy( taskPlan.repositories, @@ -1021,21 +1041,28 @@ const make = Effect.gen(function* () { const exits = yield* Effect.forEach( levels.get(level)!, (repository) => - createRepositoryWorktree( - empty, - repository, - branch, - input.startFromOrigin, - input.baseBranch, + (skipped.some((outer) => isWithinRoot(path, repository.path, outer)) + ? Effect.succeed(null) + : createRepositoryWorktree( + empty, + repository, + branch, + input.startFromOrigin, + input.baseBranch, + ) ).pipe( Effect.tap((worktree) => Effect.suspend(() => { - created.push(worktree.repository); - repositoriesStartedFromOrigin ||= worktree.fromOrigin; + finished += 1; + if (worktree === null) skipped.push(repository.path); + else { + created.push(worktree.repository); + repositoriesStartedFromOrigin ||= worktree.fromOrigin; + } return ( input.onRepository?.({ name: repository.name, - done: created.length, + done: finished, total: taskPlan.repositories.length, }) ?? Effect.void ); @@ -1189,15 +1216,7 @@ const make = Effect.gen(function* () { path.relative(taskFolder.projectRoot, repositoryPath), ).pipe(Effect.mapError(fail("add-repository", "Could not prepare the folder"))) : true; - const occupied = - !opened || - ((yield* exists(worktreePath)) && - ((yield* fileSystem.stat(worktreePath).pipe(Effect.option)).pipe( - Option.exists((info) => info.type !== "Directory"), - ) || - (yield* fileSystem.readDirectory(worktreePath).pipe(Effect.orElseSucceed(() => [""]))) - .length > 0)); - if (occupied) + if (!opened || (yield* occupied(worktreePath))) return yield* refuse(`${worktreePath} already holds files, so no worktree can go there.`); // The link the worktree took the place of comes back when the worktree does not stay. const relink = wasLinked From 630f2e14440faa2a6a177cea1f280dae0a3ed9a8 Mon Sep 17 00:00:00 2001 From: Ibrahim Elkamali Date: Sat, 21 Nov 2026 19:31:32 +0200 Subject: [PATCH 038/324] fix(desktop): a forward moves off a port this machine serves on IPv6 loopback (#40423) Co-authored-by: Julius Marminge --- .../src/preview/LoopbackTunnel.test.ts | 76 +++++++++++-------- apps/desktop/src/preview/LoopbackTunnel.ts | 12 ++- 2 files changed, 56 insertions(+), 32 deletions(-) diff --git a/apps/desktop/src/preview/LoopbackTunnel.test.ts b/apps/desktop/src/preview/LoopbackTunnel.test.ts index fe83817c0d5e8..5b3cf08c9f728 100644 --- a/apps/desktop/src/preview/LoopbackTunnel.test.ts +++ b/apps/desktop/src/preview/LoopbackTunnel.test.ts @@ -2,6 +2,7 @@ import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem"; import * as NodeWS from "@effect/platform-node/NodeWS"; import { EnvironmentId } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as NetService from "@t3tools/shared/Net"; import { expect, it } from "@effect/vitest"; import * as NodeNet from "node:net"; import * as Context from "effect/Context"; @@ -30,20 +31,23 @@ const closeServer = (server: NodeNet.Server | NodeWS.WebSocketServer) => ); /** A local listener that must never see a connection: the reviewer's own localhost server. */ -const listenDecoy = Effect.acquireRelease( - Effect.promise( - () => - new Promise<{ server: NodeNet.Server; connections: () => number }>((resolve) => { - let connections = 0; - const server = NodeNet.createServer((socket) => { - connections++; - socket.destroy(); - }); - server.listen(0, "127.0.0.1", () => resolve({ server, connections: () => connections })); - }), - ), - ({ server }) => closeServer(server), -); +const listenDecoyOn = (host: string) => + Effect.acquireRelease( + Effect.promise( + () => + new Promise<{ server: NodeNet.Server; connections: () => number }>((resolve, reject) => { + let connections = 0; + const server = NodeNet.createServer((socket) => { + connections++; + socket.destroy(); + }); + server.once("error", reject); + server.listen(0, host, () => resolve({ server, connections: () => connections })); + }), + ), + ({ server }) => closeServer(server), + ); +const listenDecoy = listenDecoyOn("127.0.0.1"); /** Stands in for the environment's /api/preview/tunnel: echoes each frame behind a 0xee byte. */ const listenEndpoint = Effect.acquireRelease( @@ -101,6 +105,7 @@ const makeTunnel = ( }), NodeFileSystem.layer, SecureRandom.layerWebCrypto, + NetService.layer, host ?? Layer.empty, ), ), @@ -357,24 +362,33 @@ it.effect("forwards a port over the tunnel on the same local port until stopped" }), ); -it.effect("moves a forward to a free port when its own is taken here", () => - Effect.gen(function* () { - const decoy = yield* listenDecoy; - const endpoint = yield* listenEndpoint; - const remotePort = addressPort(decoy.server); - const tunnel = yield* makeTunnel( - `ws://127.0.0.1:${addressPort(endpoint.server)}/api/preview/tunnel`, - ); - const forward = yield* tunnel.forward({ - environmentId: EnvironmentId.make("remote"), - remotePort, - }); - expect(forward.localPort).not.toBe(remotePort); +const hasIpv6Loopback = await new Promise((resolve) => { + const probe = NodeNet.createServer(); + probe.once("error", () => resolve(false)); + probe.listen(0, "::1", () => probe.close(() => resolve(true))); +}); - expect(yield* exchange(forward.localPort, Uint8Array.of(6))).toEqual([0xee, 6]); - expect(endpoint.requests.at(-1)).toBe(`/api/preview/tunnel?port=${remotePort}`); - expect(decoy.connections()).toBe(0); - }), +// Vite listens on ::1 by default on macOS, and Node's default listen is ::. +it.effect.each(hasIpv6Loopback ? ["127.0.0.1", "::1", "::"] : ["127.0.0.1"])( + "moves a forward to a free port when its own is taken here on %s", + (host) => + Effect.gen(function* () { + const decoy = yield* listenDecoyOn(host); + const endpoint = yield* listenEndpoint; + const remotePort = addressPort(decoy.server); + const tunnel = yield* makeTunnel( + `ws://127.0.0.1:${addressPort(endpoint.server)}/api/preview/tunnel`, + ); + const forward = yield* tunnel.forward({ + environmentId: EnvironmentId.make("remote"), + remotePort, + }); + expect(forward.localPort).not.toBe(remotePort); + + expect(yield* exchange(forward.localPort, Uint8Array.of(6))).toEqual([0xee, 6]); + expect(endpoint.requests.at(-1)).toBe(`/api/preview/tunnel?port=${remotePort}`); + expect(decoy.connections()).toBe(0); + }), ); /** An environment on this machine: each tunnel connection dials the requested local port. */ diff --git a/apps/desktop/src/preview/LoopbackTunnel.ts b/apps/desktop/src/preview/LoopbackTunnel.ts index 1e06993fa54f0..f84dc3e5c38a2 100644 --- a/apps/desktop/src/preview/LoopbackTunnel.ts +++ b/apps/desktop/src/preview/LoopbackTunnel.ts @@ -11,6 +11,7 @@ import type { EnvironmentId, } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as NetService from "@t3tools/shared/Net"; import type { NonEmptyReadonlyArray } from "effect/Array"; import * as Context from "effect/Context"; import * as Deferred from "effect/Deferred"; @@ -314,6 +315,7 @@ const make = Effect.gen(function* () { const platform = yield* HostProcess.Platform; const userId = yield* HostProcess.UserId; const random = yield* SecureRandom.SecureRandom; + const net = yield* NetService.NetService; const listenerScope = yield* Effect.scope; const routing = yield* Semaphore.make(1); const forwarding = yield* Semaphore.make(1); @@ -503,6 +505,13 @@ const make = Effect.gen(function* () { }); }); + // `localhost` also names ::1, and a server here on ::1 or :: does not collide with the + // forward's 127.0.0.1 bind, so it would keep answering `localhost` in place of the forward. + const servedOverIpv6 = (port: number) => + Effect.forEach(["::1", "::"], (host) => net.canListenOnHost(port, host)).pipe( + Effect.map((free) => free.includes(false)), + ); + const forward: LoopbackTunnel["Service"]["forward"] = Effect.fn("LoopbackTunnel.forward")( function* ({ environmentId, remotePort }) { const existing = forwarded.get(forwardKey(environmentId, remotePort)); @@ -513,7 +522,8 @@ const make = Effect.gen(function* () { const scope = yield* Scope.fork(listenerScope); const bind = (port: number) => NodeSocketServer.make({ port, host: "127.0.0.1" }).pipe(Scope.provide(scope)); - const server = yield* bind(remotePort).pipe( + const preferredPort = (yield* servedOverIpv6(remotePort)) ? 0 : remotePort; + const server = yield* bind(preferredPort).pipe( // Taken here, or privileged: any free port still reaches the environment's. Effect.catch(() => bind(0)), Effect.onError(() => Scope.close(scope, Exit.void)), From 8ee2a8a9a087da2fea9f176023961bd5bc08455f Mon Sep 17 00:00:00 2001 From: Michel Liao <107891771+Michel-Liao@users.noreply.github.com> Date: Sat, 21 Nov 2026 12:44:01 -0500 Subject: [PATCH 039/324] fix(web): RTF previews no longer join text across section and column breaks (#40437) Co-authored-by: Julius Marminge --- .../components/files/FilePreviewPanel.test.ts | 21 +++++++++++++++++++ .../files/extendedDocumentPreview.ts | 5 ++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/files/FilePreviewPanel.test.ts b/apps/web/src/components/files/FilePreviewPanel.test.ts index c02a74868fb0a..c1d49b1d26f8d 100644 --- a/apps/web/src/components/files/FilePreviewPanel.test.ts +++ b/apps/web/src/components/files/FilePreviewPanel.test.ts @@ -248,6 +248,27 @@ Third}`; ); }); + it("starts a new line at rich text section and column breaks", () => { + const result = openRtf( + bytes( + String.raw`{\rtf1\ansi\sectd\cols2\pard North quota: 120\column South quota: 240\page East quota: 360\sect\sectd\pard West quota: 480\par}`, + ), + ); + if (result.type !== "document") throw new Error("Expected document"); + expect(result.pages.map((page) => page.html)).toEqual([ + "

    North quota: 120
    South quota: 240

    ", + "

    East quota: 360
    West quota: 480

    ", + ]); + const written = openRtf( + bytes(String.raw`{\rtf1\ansi First\par\sect\sectd Second\par\column Third\page\sect Fourth}`), + ); + if (written.type !== "document") throw new Error("Expected document"); + expect(written.pages.map((page) => page.html)).toEqual([ + "

    First
    Second
    Third

    ", + "

    Fourth

    ", + ]); + }); + it("decodes declared rich text code pages for raw bytes and escaped byte runs", () => { const input = new TextEncoder().encode( String.raw`{\rtf1\ansi\ansicpg1251 A \'c0\par\ansicpg932\'82\'a0}`, diff --git a/apps/web/src/components/files/extendedDocumentPreview.ts b/apps/web/src/components/files/extendedDocumentPreview.ts index 429e2fc56a4db..a450123089718 100644 --- a/apps/web/src/components/files/extendedDocumentPreview.ts +++ b/apps/web/src/components/files/extendedDocumentPreview.ts @@ -736,7 +736,10 @@ export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { (!hidden() && (word === "par" || word === "line")) ) html += "
    "; - else { + // Writers usually end the paragraph before these breaks; a second break would add a blank line. + else if (!hidden() && (word === "sect" || word === "column")) { + if (html && !html.endsWith("
    ")) html += "
    "; + } else { const character = RTF_CHARACTERS.get(word!); if (character) emit(character); } From e2035934a67d13aa76f5f61f52c4448b4c91a545 Mon Sep 17 00:00:00 2001 From: Michel Liao <107891771+Michel-Liao@users.noreply.github.com> Date: Sat, 21 Nov 2026 12:44:47 -0500 Subject: [PATCH 040/324] fix(azure-devops): project-less pull request URLs can be pasted to check out (#40436) Co-authored-by: Julius Marminge --- .../src/shared/definition.test.ts | 12 ++++++++++++ .../src/shared/definition.ts | 2 +- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/packages/source-control-azure-devops/src/shared/definition.test.ts b/packages/source-control-azure-devops/src/shared/definition.test.ts index f18b627a874be..9234546a8a5a8 100644 --- a/packages/source-control-azure-devops/src/shared/definition.test.ts +++ b/packages/source-control-azure-devops/src/shared/definition.test.ts @@ -54,6 +54,18 @@ describe("Azure DevOps change request URLs", () => { } }); + it("takes a pull request URL that leaves the project out as a checkout reference", () => { + for (const url of [ + "https://dev.azure.com/acme/_git/web/pullrequest/17", + "https://acme.visualstudio.com/_git/web/pullrequest/17", + ]) { + expect(definition.isChangeRequestReference(url), url).toBe(true); + } + expect( + definition.isChangeRequestReference("https://dev.azure.com/_git/web/pullrequest/17"), + ).toBe(false); + }); + it.each([ ["ssh.dev.azure.com", "v3/org/project/web"], ["org.visualstudio.com", "defaultcollection/project/_git/web"], diff --git a/packages/source-control-azure-devops/src/shared/definition.ts b/packages/source-control-azure-devops/src/shared/definition.ts index 78f1a4df45a8d..a32ba471a7b48 100644 --- a/packages/source-control-azure-devops/src/shared/definition.ts +++ b/packages/source-control-azure-devops/src/shared/definition.ts @@ -21,7 +21,7 @@ const WORK_ITEM_PATH = /^\/([^/]+\/[^/]+)\/_workitems\/edit\/(\d+)(?:\/|$)/u; const LEGACY_WORK_ITEM_PATH = /^\/([^/]+)\/_workitems\/edit\/(\d+)(?:\/|$)/u; const CHECKOUT_COMMAND = /^az\s+repos\s+pr\s+checkout\s+(.+)$/i; const CHANGE_REQUEST_REFERENCE = - /^https:\/\/(?:dev\.azure\.com\/[^/\s]+\/[^/\s]+|[^/\s]+\.visualstudio\.com\/(?:DefaultCollection\/)?[^/\s]+)\/_git\/[^/\s]+\/pullrequest\/(\d+)(?:[/?#].*)?$/i; + /^https:\/\/(?:dev\.azure\.com\/[^/\s]+(?:\/[^/\s]+)?|[^/\s]+\.visualstudio\.com(?:\/DefaultCollection)?(?:\/[^/\s]+)?)\/_git\/[^/\s]+\/pullrequest\/(\d+)(?:[/?#].*)?$/i; // `ssh.dev.azure.com` is the default SSH clone host (git@ssh.dev.azure.com:v3/org/project/repo), // so any `*.dev.azure.com` subdomain is Azure. Legacy hosts stay under `.visualstudio.com`, From 28b413fe12ce3501b4fbc0903f81c4ec50af11ac Mon Sep 17 00:00:00 2001 From: Mukul Ashwath Ram Date: Sat, 21 Nov 2026 12:55:04 -0500 Subject: [PATCH 041/324] fix(server): queued messages no longer wait out every timed-out checkpoint in a shared folder (#40411) Co-authored-by: ExSidius <17144735+ExSidius@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../CheckpointCaptureService.test.ts | 2 + .../CheckpointCaptureService.ts | 3 + .../CheckpointService.test.ts | 151 ++++++++++++++++++ .../src/orchestration-v2/CheckpointService.ts | 105 ++++++++---- 4 files changed, 231 insertions(+), 30 deletions(-) diff --git a/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts b/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts index af276de7ff276..aa85cd675dc1a 100644 --- a/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts @@ -311,6 +311,7 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { ), ) : Layer.mock(CheckpointService.CheckpointServiceV2)({ + capturesSoFar: () => Effect.succeed(0), repositoryScopes: () => Effect.succeed([]), materializeBaselineCheckpoint: () => Effect.die( @@ -892,6 +893,7 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { Layer.mergeAll( IdAllocator.layer, Layer.mock(CheckpointService.CheckpointServiceV2)({ + capturesSoFar: () => Effect.succeed(0), repositoryScopes: () => Effect.succeed([]), materializeBaselineCheckpoint: () => Effect.die("baseline materialization must be skipped when ordinal 0 is ready"), diff --git a/apps/server/src/orchestration-v2/CheckpointCaptureService.ts b/apps/server/src/orchestration-v2/CheckpointCaptureService.ts index 119b5420be343..3dadd8618ed03 100644 --- a/apps/server/src/orchestration-v2/CheckpointCaptureService.ts +++ b/apps/server/src/orchestration-v2/CheckpointCaptureService.ts @@ -135,6 +135,8 @@ export const layer: Layer.Layer< }; // Each scope is checked on its own, so a retried capture fills only what is missing. const captureRoot = Effect.gen(function* () { + // Materializing a baseline waits on the folder's lock before the capture does. + const capturesBeforeLock = yield* checkpoints.capturesSoFar(scope.cwd); const threadStartCheckpoint = baselineOrdinalWithinScope === 0 || isPreserved(0) ? null : yield* materializeBaseline(0); const baselineCheckpoint = isPreserved(baselineOrdinalWithinScope) @@ -148,6 +150,7 @@ export const layer: Layer.Layer< appRunOrdinal: run.ordinal, capturedAt, forceMissing: sideChat, + capturesBeforeLock, ...excluded(scope), }); return { threadStartCheckpoint, baselineCheckpoint, checkpoint }; diff --git a/apps/server/src/orchestration-v2/CheckpointService.test.ts b/apps/server/src/orchestration-v2/CheckpointService.test.ts index 8887d391da176..0433208167a73 100644 --- a/apps/server/src/orchestration-v2/CheckpointService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointService.test.ts @@ -21,6 +21,7 @@ import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; import * as TestClock from "effect/testing/TestClock"; @@ -550,6 +551,156 @@ it.effect("backs off only baseline retries after repeated workspace capture time }), ); +it.effect("skips post-turn captures that waited out another capture's timeout in the folder", () => + Effect.gen(function* () { + const scopeFor = (name: string): OrchestrationV2CheckpointScope => ({ + id: CheckpointScopeId.make(`checkpoint-scope:shared-folder:${name}`), + threadId: ThreadId.make(`thread:shared-folder:${name}`), + runId: RunId.make(`run:shared-folder:${name}:1`), + nodeId: NodeId.make(`node:shared-folder:${name}:1`), + parentScopeId: null, + providerThreadId: ProviderThreadId.make(`provider-thread:shared-folder:${name}`), + kind: "root_run", + ordinalWithinParent: 0, + advancesAppRunCount: true, + cwd: "/repo/shared", + createdAt: DateTime.makeUnsafe("2026-07-28T00:00:00.000Z"), + }); + const attempts = yield* Ref.make(0); + // Outcomes for upcoming attempts; an attempt with none scripted times out. + const script = yield* Ref.make>([]); + const started = yield* Queue.unbounded(); + const layerTest = CheckpointService.layer.pipe( + Layer.provide( + Layer.mergeAll( + IdAllocator.layer, + layerNoTrackedFolders, + Layer.mock(CheckpointStore.CheckpointStore)({ + isGitRepository: () => Effect.succeed(true), + hasCheckpointRef: () => Effect.succeed(false), + resolveCleanHead: () => Effect.succeed(null), + captureCheckpoint: ({ cwd }) => + Effect.gen(function* () { + yield* Ref.update(attempts, (count) => count + 1); + yield* Queue.offer(started, undefined); + yield* Effect.sleep("30 seconds"); + const [next = "timeout", ...rest] = yield* Ref.get(script); + yield* Ref.set(script, rest); + if (next === "ready") return; + return yield* new VcsProcessTimeoutError({ + operation: "GitVcsDriver.checkpoints.captureCheckpoint", + command: "git", + cwd, + timeoutMs: 30_000, + }); + }), + }), + ), + ), + Layer.provideMerge(NodeCrypto.layer), + ); + yield* Effect.gen(function* () { + const checkpoints = yield* CheckpointService.CheckpointServiceV2; + const captureTurn = (scope: OrchestrationV2CheckpointScope) => + checkpoints + .capture({ + scope, + ordinalWithinScope: 1, + runId: scope.runId!, + nodeId: scope.nodeId!, + appRunOrdinal: 1, + capturedAt: scope.createdAt, + }) + .pipe(Effect.forkChild); + // A baseline's short budget running out says nothing about a post-turn capture. + const baseline = yield* checkpoints + .captureBaseline({ scope: scopeFor("baseline"), ordinalWithinScope: 0 }) + .pipe(Effect.result, Effect.forkChild); + yield* Queue.take(started); + const afterBaseline = yield* captureTurn(scopeFor("after-baseline")); + yield* TestClock.adjust("5 seconds"); + yield* Fiber.join(baseline); + yield* Queue.take(started); + yield* TestClock.adjust("30 seconds"); + assert.strictEqual((yield* Fiber.join(afterBaseline)).status, "error"); + assert.strictEqual(yield* Ref.get(attempts), 2); + + const first = yield* captureTurn(scopeFor("first")); + yield* Queue.take(started); + // Other threads in the same folder finish their turns while the first capture hangs. + const waiting = [ + yield* captureTurn(scopeFor("second")), + yield* captureTurn(scopeFor("third")), + ]; + const repository = scopeFor("repository"); + const repositoryWaiting = yield* checkpoints + .captureRepository({ + scope: repository, + runId: repository.runId!, + nodeId: repository.nodeId!, + ordinalWithinScope: 1, + capturedAt: repository.createdAt, + baselineCapturedAt: repository.createdAt, + baselineRecorded: true, + }) + .pipe(Effect.forkChild); + // A thread's root capture first materializes its baseline, which waits on the lock too. + const root = scopeFor("root"); + const rootWaiting = yield* Effect.gen(function* () { + const capturesBeforeLock = yield* checkpoints.capturesSoFar(root.cwd); + yield* checkpoints.materializeBaselineCheckpoint({ + scope: root, + ordinalWithinScope: 0, + nodeId: root.nodeId!, + capturedAt: root.createdAt, + }); + return yield* checkpoints.capture({ + scope: root, + ordinalWithinScope: 1, + runId: root.runId!, + nodeId: root.nodeId!, + appRunOrdinal: 1, + capturedAt: root.createdAt, + capturesBeforeLock, + }); + }).pipe(Effect.forkChild); + yield* TestClock.adjust("30 seconds"); + assert.strictEqual((yield* Fiber.join(first)).status, "error"); + // Room for every waiter to probe, so the count below is what fails without the fix. + yield* TestClock.adjust("120 seconds"); + for (const fiber of waiting) { + assert.strictEqual((yield* Fiber.join(fiber)).status, "error"); + } + const repositoryCaptured = yield* Fiber.join(repositoryWaiting); + assert.strictEqual(Option.getOrThrow(repositoryCaptured).checkpoint.status, "error"); + assert.strictEqual((yield* Fiber.join(rootWaiting)).status, "error"); + assert.strictEqual(yield* Ref.get(attempts), 3, "each waiter spent its own full timeout"); + + // A capture that starts after the timeout still probes for recovery. + const later = yield* captureTurn(scopeFor("later")); + yield* TestClock.adjust("30 seconds"); + assert.strictEqual((yield* Fiber.join(later)).status, "error"); + assert.strictEqual(yield* Ref.get(attempts), 4); + + // A success ahead in the queue does not hide a timeout that follows it. + yield* Ref.set(script, ["ready", "timeout"]); + const recovered = yield* captureTurn(scopeFor("recovered")); + const relapsed = yield* captureTurn(scopeFor("relapsed")); + const queuedBehind = yield* captureTurn(scopeFor("queued-behind")); + yield* TestClock.adjust("90 seconds"); + assert.deepEqual( + [ + (yield* Fiber.join(recovered)).status, + (yield* Fiber.join(relapsed)).status, + (yield* Fiber.join(queuedBehind)).status, + ], + ["ready", "error", "error"], + ); + assert.strictEqual(yield* Ref.get(attempts), 6, "the waiter probed after a later timeout"); + }).pipe(Effect.provide(layerTest)); + }), +); + it.effect("keeps the pre-rewind snapshot of a folder a failed rewind could not put back", () => { const targets = ["first", "second"].map((name) => ({ scope: { id: CheckpointScopeId.make(`checkpoint-scope:rewind:${name}`), cwd: `/repo/${name}` }, diff --git a/apps/server/src/orchestration-v2/CheckpointService.ts b/apps/server/src/orchestration-v2/CheckpointService.ts index d8a3da1f0c8ca..079ac88211870 100644 --- a/apps/server/src/orchestration-v2/CheckpointService.ts +++ b/apps/server/src/orchestration-v2/CheckpointService.ts @@ -220,7 +220,11 @@ export interface CheckpointServiceV2Shape { readonly capturedAt: DateTime.Utc; readonly forceMissing?: boolean; readonly excludePaths?: ReadonlyArray; + /** `capturesSoFar` from before an earlier wait on the folder's lock, when there was one. */ + readonly capturesBeforeLock?: number; }) => Effect.Effect; + /** How many captures have finished in a folder, for a caller that waits on it before `capture`. */ + readonly capturesSoFar: (cwd: string) => Effect.Effect; /** * A tracked repository's checkpoint for a run, with the baseline before it unless that is * already recorded. None when the run left the repository as it found it, which costs one @@ -388,19 +392,43 @@ export const layer: Layer.Layer< capacity: 128, lookup: () => Effect.succeed(0), }); + // Unlike the streak, a success never rewinds the count, so a waiter can order outcomes. A + // baseline running out of its short budget is not a post-turn capture timing out. + const lastCaptures = new Map(); + const noteCapture = (cwd: string, timedOut: boolean) => + Effect.sync(() => { + lastCaptures.set(cwd, { count: (lastCaptures.get(cwd)?.count ?? 0) + 1, timedOut }); + }); + const capturesSoFar = (cwd: string) => lastCaptures.get(cwd)?.count ?? 0; + const withCaptureLock = Effect.fn("CheckpointService.withCaptureLock")(function* ( + cwd: string, + capturesBeforeLock: number | undefined, + effect: (capturesBeforeLock: number) => Effect.Effect, + ) { + return yield* withWorkspaceLock(cwd, effect(capturesBeforeLock ?? capturesSoFar(cwd))); + }); // Both callers hold the workspace lock; post-turn captures always probe for recovery. const captureWorkspaceCheckpoint = Effect.fn("CheckpointService.captureWorkspaceCheckpoint")( function* (input: CheckpointStore.CaptureCheckpointInput, baseline = false) { const capture = checkpointStore.captureCheckpoint(input); yield* (baseline ? capture.pipe(Effect.timeout(BASELINE_CAPTURE_BUDGET)) : capture).pipe( - Effect.tap(() => Cache.invalidate(captureTimeouts, input.cwd)), + Effect.tap(() => + Effect.andThen( + Cache.invalidate(captureTimeouts, input.cwd), + noteCapture(input.cwd, false), + ), + ), Effect.tapError((error) => error._tag === "VcsProcessTimeoutError" || error._tag === "TimeoutError" ? Effect.gen(function* () { const previous = yield* Cache.get(captureTimeouts, input.cwd); yield* Cache.set(captureTimeouts, input.cwd, previous + 1); + yield* noteCapture(input.cwd, !baseline); }) - : Cache.invalidate(captureTimeouts, input.cwd), + : Effect.andThen( + Cache.invalidate(captureTimeouts, input.cwd), + noteCapture(input.cwd, false), + ), ), ); }, @@ -590,8 +618,7 @@ export const layer: Layer.Layer< readonly cleanHead?: string; }, ) => - withWorkspaceLock( - input.scope.cwd, + withCaptureLock(input.scope.cwd, input.capturesBeforeLock, (capturesBeforeLock) => Effect.gen(function* () { const checkpointId = yield* checkpointIdForScopeOrdinal(idAllocator, { scopeId: input.scope.id, @@ -634,32 +661,47 @@ export const layer: Layer.Layer< }; } - const captureStatus = yield* ( - input.cleanHead === undefined - ? captureWorkspaceCheckpoint({ - cwd: input.scope.cwd, - checkpointRef, - ...(input.ordinalWithinScope > 0 ? { previousCheckpointRef } : {}), - ...(input.excludePaths === undefined ? {} : { excludePaths: input.excludePaths }), - }) - : checkpointStore.captureHeadCheckpoint({ - cwd: input.scope.cwd, - checkpointRef, - head: input.cleanHead, - }) - ).pipe( - Effect.as("ready" as const), - Effect.catchTags({ - VcsUnsupportedOperationError: () => Effect.succeed("missing" as const), - }), - Effect.catch((cause) => - Effect.logWarning("orchestration V2 checkpoint capture failed", { - scopeId: input.scope.id, - checkpointRef, - cause: String(cause), - }).pipe(Effect.as("error" as const)), - ), - ); + // Threads sharing a folder queue on its lock. One that waited out another's timeout + // would only time out again while its own queued messages wait behind it. + const lastCapture = lastCaptures.get(input.scope.cwd); + const timedOutWhileWaiting = + input.cleanHead === undefined && + lastCapture !== undefined && + lastCapture.timedOut && + lastCapture.count > capturesBeforeLock; + const captureStatus = timedOutWhileWaiting + ? yield* Effect.logWarning( + "orchestration V2 checkpoint capture skipped after a capture timed out in its folder", + { scopeId: input.scope.id, checkpointRef }, + ).pipe(Effect.as("error" as const)) + : yield* ( + input.cleanHead === undefined + ? captureWorkspaceCheckpoint({ + cwd: input.scope.cwd, + checkpointRef, + ...(input.ordinalWithinScope > 0 ? { previousCheckpointRef } : {}), + ...(input.excludePaths === undefined + ? {} + : { excludePaths: input.excludePaths }), + }) + : checkpointStore.captureHeadCheckpoint({ + cwd: input.scope.cwd, + checkpointRef, + head: input.cleanHead, + }) + ).pipe( + Effect.as("ready" as const), + Effect.catchTags({ + VcsUnsupportedOperationError: () => Effect.succeed("missing" as const), + }), + Effect.catch((cause) => + Effect.logWarning("orchestration V2 checkpoint capture failed", { + scopeId: input.scope.id, + checkpointRef, + cause: String(cause), + }).pipe(Effect.as("error" as const)), + ), + ); if (captureStatus !== "ready") { return { @@ -966,6 +1008,7 @@ export const layer: Layer.Layer< )(function* (input) { const { cwd, id } = input.scope; const baselineOrdinal = input.ordinalWithinScope - 1; + const capturesBeforeLock = capturesSoFar(cwd); const start = yield* withWorkspaceLock( cwd, Effect.gen(function* () { @@ -1023,6 +1066,7 @@ export const layer: Layer.Layer< ordinalWithinScope: input.ordinalWithinScope, appRunOrdinal: null, capturedAt: input.capturedAt, + capturesBeforeLock, ...(input.excludePaths === undefined ? {} : { excludePaths: input.excludePaths }), ...(start.cleanHead === null ? {} : { cleanHead: start.cleanHead }), }); @@ -1135,6 +1179,7 @@ export const layer: Layer.Layer< captureBaseline, materializeBaselineCheckpoint, capture, + capturesSoFar: (cwd: string) => Effect.sync(() => capturesSoFar(cwd)), captureRepository, restore, deleteStaleRefs, From ac0032742b52b8cac5bbec416cb308df0dee913f Mon Sep 17 00:00:00 2001 From: Leon Date: Sat, 21 Nov 2026 19:03:57 +0100 Subject: [PATCH 042/324] fix(shell): non-ASCII Windows PATH entries survive the PowerShell environment probe (#37154) Co-authored-by: lowlyleon <183293296+lowlyleon@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../src/shell/DesktopShellEnvironment.test.ts | 9 +++++++++ .../src/shell/DesktopShellEnvironment.ts | 2 ++ packages/shared/src/shell.test.ts | 18 ++++++++++++++++++ packages/shared/src/shell.ts | 2 ++ 4 files changed, 31 insertions(+) diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts b/apps/desktop/src/shell/DesktopShellEnvironment.test.ts index 621c5c64178d2..dedd202acb1ee 100644 --- a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts +++ b/apps/desktop/src/shell/DesktopShellEnvironment.test.ts @@ -983,11 +983,13 @@ describe("DesktopShellEnvironment", () => { USERPROFILE: "C:\\Users\\testuser", }; + const scripts: Array = []; const prepared = yield* runShellEnvironment({ env, platform: "win32", handler: (command) => { if (command._tag !== "StandardCommand") return ""; + scripts.push(String(command.args.at(-1))); const loadProfile = !command.args.includes("-NoProfile"); return loadProfile ? envOutput({ @@ -1021,6 +1023,13 @@ describe("DesktopShellEnvironment", () => { env.FNM_MULTISHELL_PATH, "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123", ); + assert.isNotEmpty(scripts); + for (const script of scripts) { + assert.include( + script, + "[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)", + ); + } }), ); diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.ts b/apps/desktop/src/shell/DesktopShellEnvironment.ts index 3c90d7bfcaff1..f9ab0d6c3a054 100644 --- a/apps/desktop/src/shell/DesktopShellEnvironment.ts +++ b/apps/desktop/src/shell/DesktopShellEnvironment.ts @@ -235,6 +235,8 @@ const logShellEnvironmentCommandError = ( const captureWindowsEnvironmentCommand = (names: ReadonlyArray) => [ "$ErrorActionPreference = 'Stop'", + // Redirected PowerShell output uses the console code page, which mangles non-ASCII paths. + "try { [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch {}", ...names.flatMap((name) => { return [ `Write-Output '${startMarker(name)}'`, diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts index 32ed8d2b46116..d9950edc60cfb 100644 --- a/packages/shared/src/shell.test.ts +++ b/packages/shared/src/shell.test.ts @@ -415,6 +415,9 @@ describe("readEnvironmentFromWindowsShell", () => { expect.arrayContaining(["-NoLogo", "-NoProfile", "-NonInteractive", "-Command"]), { encoding: "utf8", timeout: 5000 }, ); + expect(execFile.mock.calls[0]?.[1].at(-1)).toContain( + "[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)", + ); }), ); @@ -441,6 +444,21 @@ describe("readEnvironmentFromWindowsShell", () => { }), ); + effectIt.effect.runIf(HostProcess.Platform.defaultValue() === "win32")( + "reads a non-ASCII value from the real shell", + () => + Effect.gen(function* () { + const name = "T3CODE_TEST_NON_ASCII_PATH"; + const value = "C:\\Users\\Jürgen\\Grüße"; + vi.stubEnv(name, value); + try { + expect(yield* readEnvironmentFromWindowsShell([name])).toEqual({ [name]: value }); + } finally { + vi.unstubAllEnvs(); + } + }), + ); + effectIt.effect("omits -NoProfile when loadProfile is enabled", () => Effect.gen(function* () { const execFile = vi.fn< diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.ts index 05a1d5b14bd79..8ccb466775c1f 100644 --- a/packages/shared/src/shell.ts +++ b/packages/shared/src/shell.ts @@ -295,6 +295,8 @@ export function windowsEnvironmentValueCommand(name: string): string { function buildWindowsEnvironmentCaptureCommand(names: ReadonlyArray): string { return [ "$ErrorActionPreference = 'Stop'", + // Redirected PowerShell output uses the console code page, which mangles non-ASCII paths. + "try { [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch {}", ...names.flatMap((name) => { if (!SHELL_ENV_NAME_PATTERN.test(name)) { throw new Error(`Unsupported environment variable name: ${name}`); From 1cedd4b4ed729d8696821e018063a5bc2c5c6b49 Mon Sep 17 00:00:00 2001 From: Karchi <162874774+Gooder24@users.noreply.github.com> Date: Sat, 21 Nov 2026 19:16:09 +0100 Subject: [PATCH 043/324] fix(web): scheduled task times follow the Time format setting (#37314) Co-authored-by: maria-rcks Co-authored-by: Julius Marminge --- .../chat/ThreadAutomationsPanel.tsx | 10 ++-- .../settings/ScheduledTasksSettings.tsx | 13 ++++- .../scheduledTasksSettings.logic.test.ts | 48 +++++++++++++++++-- .../settings/scheduledTasksSettings.logic.ts | 14 +++--- apps/web/src/timestampFormat.ts | 27 +++++++++++ 5 files changed, 95 insertions(+), 17 deletions(-) diff --git a/apps/web/src/components/chat/ThreadAutomationsPanel.tsx b/apps/web/src/components/chat/ThreadAutomationsPanel.tsx index 0a602227cad54..12989e3f4f607 100644 --- a/apps/web/src/components/chat/ThreadAutomationsPanel.tsx +++ b/apps/web/src/components/chat/ThreadAutomationsPanel.tsx @@ -12,12 +12,14 @@ import { type ScheduledTask, type ThreadId, } from "@t3tools/contracts"; +import type { TimestampFormat } from "@t3tools/contracts/settings"; import { isAtomCommandInterrupted, squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; import { ThreadDetailsSection } from "./ThreadDetailsSection"; +import { useClientSettings } from "../../hooks/useSettings"; import { cn } from "../../lib/utils"; import { ScheduledRelativeLabel } from "../settings/ScheduledTasksSettings"; import { scheduleLabel } from "../settings/scheduledTasksSettings.logic"; @@ -43,12 +45,13 @@ const STATUS_DOT_CLASS: Record = { function taskScheduleLine( task: ScheduledTask, + timestampFormat: TimestampFormat, timeZone: string | undefined, resolve: MessageResolver, ) { return ( <> - {scheduleLabel(task.schedule, timeZone, task.nextRunAt, resolve)} + {scheduleLabel(task.schedule, timestampFormat, timeZone, task.nextRunAt, resolve)} {task.blockedByPolicy !== undefined ? ( ` · ${task.blockedByPolicy}` ) : task.enabled && task.nextRunAt !== null ? ( @@ -87,6 +90,7 @@ export function ThreadAutomationsPanel(props: { const runTaskNow = useAtomCommand(serverEnvironment.runScheduledTaskNow, { label: "thread automation run now", }); + const timestampFormat = useClientSettings((settings) => settings.timestampFormat); const navigate = useNavigate(); const gt = useGT(); const m = useMessages(); @@ -198,13 +202,13 @@ export function ThreadAutomationsPanel(props: { {task.title}

    - {taskScheduleLine(task, tasksQuery.data?.timeZone, m)} + {taskScheduleLine(task, timestampFormat, tasksQuery.data?.timeZone, m)}

    {task.title}

    - {taskScheduleLine(task, tasksQuery.data?.timeZone, m)} + {taskScheduleLine(task, timestampFormat, tasksQuery.data?.timeZone, m)}

    diff --git a/apps/web/src/components/settings/ScheduledTasksSettings.tsx b/apps/web/src/components/settings/ScheduledTasksSettings.tsx index 471dcdf0fe0df..4f70815684faa 100644 --- a/apps/web/src/components/settings/ScheduledTasksSettings.tsx +++ b/apps/web/src/components/settings/ScheduledTasksSettings.tsx @@ -54,7 +54,7 @@ import { msg, T, useGT, useLocale, useMessages, Var } from "gt-react"; import { m, type MessageResolver } from "../../i18n/messages"; import { formatRelativeTime } from "../../timestampFormat"; -import { useEnvironmentSettings } from "../../hooks/useSettings"; +import { useClientSettings, useEnvironmentSettings } from "../../hooks/useSettings"; import { getCustomModelOptionsByInstance } from "../../modelSelection"; import { providerInstanceEntriesFor } from "../../providerInstances"; import { usePrimaryCloudLinkState } from "../../cloud/cloudLinkState"; @@ -795,6 +795,7 @@ function ScheduledTaskRow({ const canOperate = useAtomValue( serverEnvironment.upsertScheduledTask.permissionAtom(environmentId), ); + const timestampFormat = useClientSettings((settings) => settings.timestampFormat); const [busy, setBusy] = useState(false); const [deliveriesOpen, setDeliveriesOpen] = useState(false); const isWebhook = task.schedule.type === "webhook"; @@ -841,7 +842,15 @@ function ScheduledTaskRow({ status={
    - {scheduleLabel(task.schedule, timeZone, task.nextRunAt, messages, locale)} ·{" "} + {scheduleLabel( + task.schedule, + timestampFormat, + timeZone, + task.nextRunAt, + messages, + locale, + )}{" "} + ·{" "} {task.blockedByPolicy !== undefined ? ( task.blockedByPolicy ) : !task.enabled ? ( diff --git a/apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts b/apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts index d01b47078dbe2..2bbdd7867c3c7 100644 --- a/apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts +++ b/apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts @@ -424,11 +424,49 @@ it("rejects dedupe templates without a request placeholder", () => { expect(scheduleFromDraft({ ...draft, coalesceKey: "{{body.bad" })).toBeNull(); }); +// The host locale's clock for a wall time, so these pass in any locale (digits, day period, zero padding). +function clock(hour12: boolean, hour: number, minute: number) { + return new Intl.DateTimeFormat(undefined, { + hour: "numeric", + minute: "2-digit", + hour12, + timeZone: "UTC", + }).format(Date.UTC(2000, 0, 1, hour, minute)); +} + it("appends the server zone only to fixed-time schedule labels", () => { - expect(scheduleLabel({ type: "fixed_time", timeOfDay: "16:31" }, "Etc/UTC")).toBe( - "Daily at 16:31 UTC", + expect(scheduleLabel({ type: "fixed_time", timeOfDay: "16:31" }, "24-hour", "Etc/UTC")).toBe( + `Daily at ${clock(false, 16, 31)} UTC`, + ); + expect(scheduleLabel({ type: "fixed_time", timeOfDay: "09:00" }, "24-hour")).toBe( + `Daily at ${clock(false, 9, 0)}`, + ); + expect(scheduleLabel({ type: "interval", everyMs: 60_000 }, "24-hour", "Etc/UTC")).toBe( + "Every 1 min", ); - expect(scheduleLabel({ type: "fixed_time", timeOfDay: "09:00" })).toBe("Daily at 09:00"); - expect(scheduleLabel({ type: "interval", everyMs: 60_000 }, "Etc/UTC")).toBe("Every 1 min"); - expect(scheduleLabel({ type: "webhook", signature: null }, "Etc/UTC")).toBe("On webhook"); + expect(scheduleLabel({ type: "webhook", signature: null }, "24-hour", "Etc/UTC")).toBe( + "On webhook", + ); +}); + +it("shows schedule times in the Time format setting", () => { + const daily = { type: "fixed_time", timeOfDay: "17:30" } as const; + expect(scheduleLabel(daily, "24-hour")).toBe(`Daily at ${clock(false, 17, 30)}`); + expect(scheduleLabel(daily, "12-hour")).toBe(`Daily at ${clock(true, 17, 30)}`); + const midnight = scheduleLabel({ type: "fixed_time", timeOfDay: "0:05" }, "24-hour"); + expect(midnight).toBe(`Daily at ${clock(false, 0, 5)}`); + // An h24 clock would print midnight as 24:05 in both the label and the helper. + expect(midnight).not.toContain("24"); + + // A local wall time, so the label reads 17:30 in any host zone. + const runAt = new Date(2026, 10, 20, 17, 30); + const once = { type: "once", runAt: runAt.toISOString() } as const; + for (const hour12 of [false, true]) { + const dateTime = new Intl.DateTimeFormat(undefined, { + dateStyle: "medium", + timeStyle: "short", + hour12, + }).format(runAt); + expect(scheduleLabel(once, hour12 ? "12-hour" : "24-hour")).toBe(`Once, ${dateTime}`); + } }); diff --git a/apps/web/src/components/settings/scheduledTasksSettings.logic.ts b/apps/web/src/components/settings/scheduledTasksSettings.logic.ts index bbb5c146cb28a..6c7038f8ed191 100644 --- a/apps/web/src/components/settings/scheduledTasksSettings.logic.ts +++ b/apps/web/src/components/settings/scheduledTasksSettings.logic.ts @@ -24,6 +24,7 @@ import { type WebhookFilterDraft, } from "@t3tools/client-runtime/scheduled-task-webhook"; import { scheduleTimeZoneLabel } from "@t3tools/client-runtime/scheduled-task-time-zone"; +import type { TimestampFormat } from "@t3tools/contracts/settings"; import { msg } from "gt-react"; import { @@ -32,6 +33,7 @@ import { } from "@t3tools/shared/projectSettings"; import { getActiveLocale, m, type MessageResolver } from "../../i18n/messages"; import type { ProviderInstanceEntry } from "../../providerInstances"; +import { formatDateTimeTimestamp, formatTimeOfDay } from "../../timestampFormat"; import type { ResolvedSettingsScope } from "./settingsScope"; @@ -43,13 +45,9 @@ export function weekdayShortLabel(day: number, locale: string = getActiveLocale( ); } -const ONCE_FORMATTER = new Intl.DateTimeFormat(undefined, { - dateStyle: "medium", - timeStyle: "short", -}); - export function scheduleLabel( schedule: ScheduledTaskSchedule, + timestampFormat: TimestampFormat, timeZone?: string, runAt?: string | null, resolve: MessageResolver = m, @@ -57,7 +55,9 @@ export function scheduleLabel( ): string { if (schedule.type === "webhook") return resolve(msg("On webhook")); if (schedule.type === "once") { - return resolve(msg("Once, {time}", { time: ONCE_FORMATTER.format(new Date(schedule.runAt)) })); + return resolve( + msg("Once, {time}", { time: formatDateTimeTimestamp(schedule.runAt, timestampFormat) }), + ); } if (schedule.type === "interval") { const minutes = schedule.everyMs / 60_000; @@ -66,7 +66,7 @@ export function scheduleLabel( : resolve(msg("Every {seconds} sec", { seconds: Math.round(schedule.everyMs / 1000) })); } const weekdays = schedule.weekdays ?? []; - const time = schedule.timeOfDay; + const time = formatTimeOfDay(schedule.timeOfDay, timestampFormat); const zone = scheduleTimeZoneLabel(timeZone, runAt); if (weekdays.length === 0) { return zone === undefined diff --git a/apps/web/src/timestampFormat.ts b/apps/web/src/timestampFormat.ts index ac99534a5ca2f..836020c20bbec 100644 --- a/apps/web/src/timestampFormat.ts +++ b/apps/web/src/timestampFormat.ts @@ -181,6 +181,33 @@ export function formatShortTimestamp(isoDate: string, timestampFormat: Timestamp return formatTime(date, timestampFormat); } +const dateTimeFormatterCache = new Map(); + +export function formatDateTimeTimestamp(isoDate: string, timestampFormat: TimestampFormat): string { + const date = parseTimestampDate(isoDate); + if (!date) return ""; + let formatter = dateTimeFormatterCache.get(timestampFormat); + if (!formatter) { + formatter = new Intl.DateTimeFormat(timestampLocale, { + dateStyle: "medium", + timeStyle: "short", + ...(timestampFormat === "locale" ? {} : { hour12: timestampFormat === "12-hour" }), + }); + dateTimeFormatterCache.set(timestampFormat, formatter); + } + return formatter.format(date); +} + +/** A wall-clock `H:MM` or `HH:MM` that names no date or zone, such as a daily schedule's time. */ +export function formatTimeOfDay(timeOfDay: string, timestampFormat: TimestampFormat): string { + const match = /^(\d{1,2}):(\d{2})$/.exec(timeOfDay); + if (!match) return timeOfDay; + // Default-zone formatters run in UTC, so the host zone cannot shift the wall time. + return getTimestampFormatter(timestampFormat, false).format( + Date.UTC(2000, 0, 1, Number(match[1]), Number(match[2])), + ); +} + const numericDateOptions: Intl.DateTimeFormatOptions = { month: "numeric", day: "numeric" }; const numericDateWithYearOptions: Intl.DateTimeFormatOptions = { ...numericDateOptions, From e2fdfd2c3112ec738f31638765faee5b9312ffc7 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 10:28:58 -0800 Subject: [PATCH 044/324] perf(client-runtime): opening the branch picker keeps the branch list when no ref moved (#40452) --- .../src/vcs/VcsStatusBroadcaster.test.ts | 5 +++- apps/server/src/vcs/VcsStatusBroadcaster.ts | 26 ++++++++++++------- packages/client-runtime/src/state/vcs.test.ts | 8 ++++++ packages/client-runtime/src/state/vcs.ts | 21 ++++++++++----- 4 files changed, 42 insertions(+), 18 deletions(-) diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts index d30997266c7b7..9d8b2bf2117b3 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts @@ -717,7 +717,10 @@ describe("VcsStatusBroadcaster", () => { return Effect.gen(function* () { const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; const initial = yield* broadcaster.getStatus({ cwd: "/repo" }); - const refreshed = yield* broadcaster.refreshStatus("/repo", { localOnly: true }); + const { refsDigest, ...refreshed } = yield* broadcaster.refreshStatus("/repo", { + localOnly: true, + }); + assert.isString(refsDigest); assert.deepStrictEqual(refreshed, initial); assert.deepStrictEqual(yield* broadcaster.getStatus({ cwd: "/repo" }), refreshed); assert.equal(state.localInvalidationCalls, 1); diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.ts b/apps/server/src/vcs/VcsStatusBroadcaster.ts index 5842478fffe76..92a83c0230f71 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.ts @@ -736,21 +736,27 @@ export const make = Effect.gen(function* () { )(function* (rawCwd, options) { const cwd = yield* withFileSystem(normalizeCwd(rawCwd)); yield* acquireBranchChangesDemand(cwd); - const refsBeforeLocalRead = options?.localOnly ? null : yield* workflow.readRefSnapshot(cwd); - yield* refreshLocalStatusCore(cwd); + // Lets the client keep its cached branch list when no ref moved since its last refresh. + const withRefsDigest = (status: VcsStatusResult, refs: string | null) => + refs === null + ? status + : { + ...status, + refsDigest: NodeCrypto.createHash("sha256").update(refs).digest("hex").slice(0, 32), + }; if (options?.localOnly) { + const [refs] = yield* Effect.all( + [workflow.readRefSnapshot(cwd), refreshLocalStatusCore(cwd)], + { concurrency: "unbounded" }, + ); // Never cache a remote here: readers take `value: null` as "read and found no PR". const parts = yield* getStatusParts(cwd); - return mergeGitStatusParts(parts.local, parts.remote); + return withRefsDigest(mergeGitStatusParts(parts.local, parts.remote), refs); } + const refsBeforeLocalRead = yield* workflow.readRefSnapshot(cwd); + yield* refreshLocalStatusCore(cwd); const { status, refs } = yield* refreshRemoteAndLocalTotals(cwd, rawCwd, refsBeforeLocalRead); - // Lets the client keep its cached branch list when no ref moved since its last refresh. - return refs === null - ? status - : { - ...status, - refsDigest: NodeCrypto.createHash("sha256").update(refs).digest("hex").slice(0, 32), - }; + return withRefsDigest(status, refs); }, Effect.scoped); const refreshAfterCheckout: VcsStatusBroadcaster["Service"]["refreshAfterCheckout"] = Effect.fn( diff --git a/packages/client-runtime/src/state/vcs.test.ts b/packages/client-runtime/src/state/vcs.test.ts index f58b0d120598d..edc005263b432 100644 --- a/packages/client-runtime/src/state/vcs.test.ts +++ b/packages/client-runtime/src/state/vcs.test.ts @@ -464,6 +464,13 @@ describe("cached VCS refs", () => { expect(yield* Ref.get(clears)).toBe(3); expect(registry.get(vcsRefsCacheStateAtom(TARGET)).revision).toBe(3); + yield* atoms.refreshLocalStatusForPicker.run(registry, { + environmentId: TARGET.environmentId, + input: { cwd: "/repo", localOnly: true }, + }); + expect(yield* Ref.get(clears)).toBe(3); + expect(registry.get(vcsRefsCacheStateAtom(TARGET)).revision).toBe(3); + const prepareResult = yield* Effect.exit( createGitEnvironmentAtoms(runtime).preparePullRequestThread.run(registry, { environmentId: TARGET.environmentId, @@ -485,6 +492,7 @@ describe("cached VCS refs", () => { [WS_METHODS.vcsRefreshStatus]: () => Deferred.succeed(refreshStarted, undefined).pipe( Effect.andThen(Deferred.await(releaseRefresh)), + Effect.as({}), ), [WS_METHODS.vcsSwitchRef]: () => Effect.succeed({ refName: "feature" }), } as unknown as WsRpcProtocolClient; diff --git a/packages/client-runtime/src/state/vcs.ts b/packages/client-runtime/src/state/vcs.ts index a6299aab0ff64..dab79e282a4d2 100644 --- a/packages/client-runtime/src/state/vcs.ts +++ b/packages/client-runtime/src/state/vcs.ts @@ -2,6 +2,7 @@ import { type EnvironmentId, type VcsListRefsInput, type VcsListRefsResult, + type VcsRefreshStatusResult, type VcsStatusResult, WS_METHODS, } from "@t3tools/contracts"; @@ -294,6 +295,17 @@ export function createVcsEnvironmentAtoms( cwd: target.input.cwd, }); + const invalidateRefsIfChanged = ( + target: { readonly environmentId: EnvironmentId; readonly input: { readonly cwd: string } }, + registry: AtomRegistry.AtomRegistry, + exit: Exit.Exit, + ) => + invalidateCachedVcsRefsIfChanged( + registry, + { environmentId: target.environmentId, cwd: target.input.cwd }, + Exit.isSuccess(exit) ? exit.value.refsDigest : undefined, + ); + return { listRefs, // An uncached read for decisions that must match the repository now, not @@ -341,19 +353,14 @@ export function createVcsEnvironmentAtoms( tag: WS_METHODS.vcsRefreshStatus, scheduler: vcsCommandScheduler, concurrency: vcsCommandConcurrency, - onSettled: (target, registry, exit) => - invalidateCachedVcsRefsIfChanged( - registry, - { environmentId: target.environmentId, cwd: target.input.cwd }, - Exit.isSuccess(exit) ? exit.value.refsDigest : undefined, - ), + onSettled: invalidateRefsIfChanged, }), // Outside the serial queue: it only reads status, and a checkout picked right after opening // the picker must not wait behind that read. refreshLocalStatusForPicker: createEnvironmentRpcCommand(runtime, { label: "environment-data:vcs:refresh-local-status-for-picker", tag: WS_METHODS.vcsRefreshStatus, - onSettled: invalidateRefs, + onSettled: invalidateRefsIfChanged, }), createWorktree: createEnvironmentRpcCommand(runtime, { label: "environment-data:vcs:create-worktree", From 194025ef11027c95b0d226a4d2bbdafb92279eab Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 10:31:19 -0800 Subject: [PATCH 045/324] perf(server): turn end reads upstream divergence once, not twice (#40450) --- apps/server/src/git/GitManager.ts | 10 +++- apps/server/src/git/GitWorkflowService.ts | 2 + .../src/vcs/VcsStatusBroadcaster.test.ts | 55 ++++++++++++++++--- apps/server/src/vcs/VcsStatusBroadcaster.ts | 17 +++++- 4 files changed, 71 insertions(+), 13 deletions(-) diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index dab6d4d20924e..543b5de5505f5 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -111,6 +111,8 @@ export interface GitLocalStatusOptions { export interface GitRemoteStatusOptions extends GitVcsDriver.GitRemoteStatusOptions { readonly refreshMissingPullRequest?: boolean; + /** Details the caller just read without fetching; used instead of reading them again. */ + readonly statusDetails?: GitVcsDriver.GitRemoteStatusDetails; } export type GitBranchPullRequest = NonNullable & { @@ -1603,9 +1605,11 @@ export const make = Effect.gen(function* () { cwd: string, options?: GitRemoteStatusOptions, ) { - const details = yield* gitCore - .statusDetailsRemote(cwd, options) - .pipe(Effect.catchIf(isNotGitRepositoryError, () => Effect.succeed(null))); + const details = + options?.statusDetails ?? + (yield* gitCore + .statusDetailsRemote(cwd, options) + .pipe(Effect.catchIf(isNotGitRepositoryError, () => Effect.succeed(null)))); if (details === null || !details.isRepo) { return null; } diff --git a/apps/server/src/git/GitWorkflowService.ts b/apps/server/src/git/GitWorkflowService.ts index f012a65bb0692..f0757fd7078fe 100644 --- a/apps/server/src/git/GitWorkflowService.ts +++ b/apps/server/src/git/GitWorkflowService.ts @@ -59,6 +59,7 @@ export class GitWorkflowService extends Context.Service< readonly refName: string; readonly aheadCount: number; readonly behindCount: number; + readonly details: GitVcsDriver.GitRemoteStatusDetails; } | null, GitManagerServiceError >; @@ -384,6 +385,7 @@ export const make = Effect.gen(function* () { refName: details.branch, aheadCount: details.aheadCount, behindCount: details.behindCount, + details, } : null; }), diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts index 9d8b2bf2117b3..7c5dd63773848 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts @@ -78,6 +78,7 @@ function layerTestFor(state: { localInvalidationCalls: number; remoteInvalidationCalls: number; remoteStatusRefreshUpstreamValues?: Array; + remoteStatusReusedDetails?: Array; localStatusBranchChanges?: Array; refSnapshot?: string | null; remoteStatusError?: GitManagerError; @@ -144,15 +145,29 @@ function layerTestFor(state: { readRefSnapshot: () => Effect.sync(() => (state.refSnapshot === undefined ? "refs" : state.refSnapshot)), upstreamDivergence: () => - Effect.sync(() => - state.currentRemoteStatus?.hasUpstream && state.currentLocalStatus.refName !== null - ? { - refName: state.currentLocalStatus.refName, - aheadCount: (state.currentDivergence ?? state.currentRemoteStatus).aheadCount, - behindCount: (state.currentDivergence ?? state.currentRemoteStatus).behindCount, - } - : null, - ), + Effect.sync(() => { + const refName = state.currentLocalStatus.refName; + if (!state.currentRemoteStatus?.hasUpstream || refName === null) return null; + const { aheadCount, behindCount } = + state.currentDivergence ?? state.currentRemoteStatus; + return { + refName, + aheadCount, + behindCount, + details: { + isRepo: true, + hasPrimaryRemote: true, + defaultBranch: "main", + isDefaultBranch: false, + branch: refName, + upstreamRef: `origin/${refName}`, + hasUpstream: true, + aheadCount, + behindCount, + aheadOfDefaultCount: aheadCount, + }, + }; + }), remoteStatus: (_input, options) => Effect.suspend(() => { return (state.beforeRemoteStatus ?? Effect.void).pipe( @@ -160,6 +175,7 @@ function layerTestFor(state: { Effect.sync(() => { state.remoteStatusCalls += 1; state.remoteStatusRefreshUpstreamValues?.push(options?.refreshUpstream); + state.remoteStatusReusedDetails?.push(options?.statusDetails !== undefined); return state.currentRemoteStatus; }), ), @@ -794,6 +810,27 @@ describe("VcsStatusBroadcaster", () => { }, ); + it.effect("the turn-end PR lookup reuses the upstream read it follows, once", () => { + const state: Parameters[0] = { + currentLocalStatus: baseLocalStatus, + currentRemoteStatus: remoteStatusWithPr, + localStatusCalls: 0, + remoteStatusCalls: 0, + localInvalidationCalls: 0, + remoteInvalidationCalls: 0, + remoteStatusReusedDetails: [], + }; + + return Effect.gen(function* () { + const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + yield* broadcaster.getStatus({ cwd: "/repo" }); + yield* broadcaster.refreshLocalStatus("/repo"); + yield* broadcaster.refreshPullRequestStatus("/repo"); + yield* broadcaster.refreshPullRequestStatus("/repo"); + assert.deepStrictEqual(state.remoteStatusReusedDetails, [false, true, false]); + }).pipe(Effect.provide(layerTestFor(state))); + }); + it.effect.each([0, 2])( "refreshes merge divergence while a lookup ends with %s commits behind", (behindAfterLookup) => { diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.ts b/apps/server/src/vcs/VcsStatusBroadcaster.ts index 92a83c0230f71..156290ed0ca6a 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.ts @@ -37,6 +37,7 @@ import * as BackgroundPolicy from "../background/BackgroundPolicy.ts"; import * as GitWorkflowService from "../git/GitWorkflowService.ts"; import * as ProjectStore from "../orchestration-v2/ProjectStore.ts"; import * as ServerSettings from "../serverSettings.ts"; +import type * as GitVcsDriver from "./GitVcsDriver.ts"; import { VcsAutomaticFetchInterval } from "./VcsAutomaticFetchInterval.ts"; const VCS_STATUS_REFRESH_FAILURE_BASE_DELAY = Duration.seconds(30); @@ -330,6 +331,9 @@ export const make = Effect.gen(function* () { // A refresh that started after a request saw every change that request could mean, so queued // callers share it instead of each running git status again. const localRefreshRequests = new Map(); + // Upstream details the turn-end refreshLocalStatus just read, handed once to the PR lookup that + // follows it so the same no-fetch read is not repeated. Any remote write in between drops them. + const upstreamReads = new Map(); const localRefreshResults = new Map< string, { @@ -353,6 +357,7 @@ export const make = Effect.gen(function* () { // A queued caller can read git again. Keep the monotonic request counter so it cannot // mistake an older result for a later request. localRefreshResults.delete(candidate); + upstreamReads.delete(candidate); } return cache; }; @@ -449,6 +454,7 @@ export const make = Effect.gen(function* () { const updateCachedRemoteStatus = Effect.fn("VcsStatusBroadcaster.updateCachedRemoteStatus")( function* (cwd: string, remote: CachedRemoteStatus | null, options?: { publish?: boolean }) { + upstreamReads.delete(cwd); const [changed, value] = yield* Ref.modify(cacheRef, (cache) => { const previous = cache.get(cwd) ?? { local: null, remote: null }; const next = remote?.branch === previous.local?.value.refName ? remote : null; @@ -556,6 +562,7 @@ export const make = Effect.gen(function* () { "VcsStatusBroadcaster.refreshLocalStatus", )(function* (rawCwd) { const cwd = yield* withFileSystem(normalizeCwd(rawCwd)); + upstreamReads.delete(cwd); const local = yield* refreshLocalStatusCore(cwd); const cached = yield* getCachedStatus(cwd); // Divergence is local Git data; a slow forge lookup must not delay turn-end updates. @@ -577,6 +584,7 @@ export const make = Effect.gen(function* () { }, { publish: true }, ); + upstreamReads.set(cwd, divergence.details); } } return local; @@ -590,7 +598,11 @@ export const make = Effect.gen(function* () { // GitManager's remote TTL cache is keyed by cwd, not the checked-out branch. yield* workflow.invalidateRemoteStatus(cwd); const previousRemote = (yield* getCachedStatus(cwd))?.remote; - const remote = yield* workflow.remoteStatus({ cwd }, options); + const { statusDetails, ...remoteOptions } = options ?? {}; + const remote = yield* workflow.remoteStatus( + { cwd }, + statusDetails?.branch === branch ? { ...remoteOptions, statusDetails } : remoteOptions, + ); const latest = yield* getCachedStatus(cwd); // An overlapping turn refresh and fetch can both move divergence during the forge lookup. const refreshed = @@ -783,9 +795,12 @@ export const make = Effect.gen(function* () { const cached = yield* getCachedStatus(cwd); if (!cached || cached.remote?.value === null) return null; // Turn completion must update divergence even when background polling is paused. + const statusDetails = upstreamReads.get(cwd); + upstreamReads.delete(cwd); const remoteRead = yield* readRemoteStatus(cwd, { refreshUpstream: false, refreshMissingPullRequest: true, + ...(statusDetails ? { statusDetails } : {}), }); return yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true }); }), From 1ffa099e7fbf0037dbffb6fb72b7585c933be24a Mon Sep 17 00:00:00 2001 From: Michel Liao <107891771+Michel-Liao@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:52:14 -0500 Subject: [PATCH 046/324] fix(shared): file links whose title holds the other quote keep their folder labels (#40464) Co-authored-by: Julius Marminge --- packages/shared/src/markdownLinks.test.ts | 3 +++ packages/shared/src/markdownLinks.ts | 17 ++++++++++------- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/packages/shared/src/markdownLinks.test.ts b/packages/shared/src/markdownLinks.test.ts index 0a997aee79eac..a1f0af927636d 100644 --- a/packages/shared/src/markdownLinks.test.ts +++ b/packages/shared/src/markdownLinks.test.ts @@ -185,6 +185,9 @@ describe("extractMarkdownLinkHrefs", () => { ["/x/app/(a)/page.tsx", "/x/app/(b)/page.tsx"], ], ['[a](/tmp/a(1).txt "title") after', ["/tmp/a(1).txt"]], + [`[a](a.ts "it's a title") [b](b.ts 'a "quoted" title') [c](ok)`, ["a.ts", "b.ts", "ok"]], + [`[a](a.ts "mixed') [b](b.ts)`, ["b.ts"]], + [`[a](a.ts "it's\n\n[b](lib/a.ts)")`, ["lib/a.ts"]], ["[a](a(b(c))d) [b](ok)", ["a(b(c))d", "ok"]], ["[a](x\\)y) [b](x\\(y)", ["x\\)y", "x\\(y"]], ["[a](unclosed(paren) [b](ok)", ["ok"]], diff --git a/packages/shared/src/markdownLinks.ts b/packages/shared/src/markdownLinks.ts index 98df3952fb278..fe450406093b3 100644 --- a/packages/shared/src/markdownLinks.ts +++ b/packages/shared/src/markdownLinks.ts @@ -461,15 +461,18 @@ function markdownRunEndFinder(markdown: string, delimiter: RegExp) { } function markdownLinkTailScanner(markdown: string) { - const whitespaceEnd = markdownRunEndFinder(markdown, /\S/g); - const titleEnd = markdownRunEndFinder(markdown, /["']/g); - const titleWhitespaceEnd = markdownRunEndFinder(markdown, /\S/g); + // A blank line ends the paragraph, so no part of a link's tail runs past one. + const whitespaceEnd = markdownRunEndFinder(markdown, /\S|\n[ \t\r]*\n/g); + const doubleQuoteEnd = markdownRunEndFinder(markdown, /"|\n[ \t\r]*\n/g); + const singleQuoteEnd = markdownRunEndFinder(markdown, /'|\n[ \t\r]*\n/g); + const titleWhitespaceEnd = markdownRunEndFinder(markdown, /\S|\n[ \t\r]*\n/g); return (start: number) => { const end = whitespaceEnd(start); - if (markdown[end] === ")") return end + 1; - if (end === start || (markdown[end] !== '"' && markdown[end] !== "'")) return null; - const quoteEnd = titleEnd(end + 1); - if (quoteEnd === markdown.length) return null; + const quote = markdown[end]; + if (quote === ")") return end + 1; + if (end === start || (quote !== '"' && quote !== "'")) return null; + const quoteEnd = (quote === '"' ? doubleQuoteEnd : singleQuoteEnd)(end + 1); + if (markdown[quoteEnd] !== quote) return null; const close = titleWhitespaceEnd(quoteEnd + 1); return markdown[close] === ")" ? close + 1 : null; }; From a3001b33fe652ad7df9d9977384058bbac5a53f2 Mon Sep 17 00:00:00 2001 From: Michel Liao <107891771+Michel-Liao@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:56:04 -0500 Subject: [PATCH 047/324] fix(web): RTF previews break the line at TextEdit soft line breaks (#40468) Co-authored-by: Julius Marminge --- apps/web/src/components/files/FilePreviewPanel.test.ts | 8 +++++++- apps/web/src/components/files/extendedDocumentPreview.ts | 4 +++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/files/FilePreviewPanel.test.ts b/apps/web/src/components/files/FilePreviewPanel.test.ts index c1d49b1d26f8d..4c9d8b0f9a676 100644 --- a/apps/web/src/components/files/FilePreviewPanel.test.ts +++ b/apps/web/src/components/files/FilePreviewPanel.test.ts @@ -214,7 +214,7 @@ describe("document preview contents", () => { expect(html).not.toContain("https:"); }); - it("treats a backslash before a line break as a paragraph break, as TextEdit writes them", () => { + it("breaks lines at the paragraph and line breaks TextEdit writes", () => { const html = (rtf: string) => { const result = openRtf(bytes(rtf)); if (result.type !== "document") throw new Error("Expected document"); @@ -230,6 +230,12 @@ Third}`; ); expect(html(textEdit)).toEqual(expected); expect(html(textEdit.replaceAll("\n", "\r\n"))).toEqual(expected); + const lineBreak = html(String.raw`{\rtf1\ansi First line\line Second line}`); + expect(lineBreak).toEqual(["

    First line
    Second line

    "]); + expect(html(String.raw`{\rtf1\ansi First line\uc0\u8232 Second line}`)).toEqual(lineBreak); + expect(html(String.raw`{\rtf1\ansi First line\u8232?Second line{\deleted\u8232?}}`)).toEqual( + lineBreak, + ); }); it("preserves rich text page breaks and formatting without splitting hidden destinations", () => { diff --git a/apps/web/src/components/files/extendedDocumentPreview.ts b/apps/web/src/components/files/extendedDocumentPreview.ts index a450123089718..07a8713b08202 100644 --- a/apps/web/src/components/files/extendedDocumentPreview.ts +++ b/apps/web/src/components/files/extendedDocumentPreview.ts @@ -727,7 +727,9 @@ export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { else if (word === "uc") state.uc = Math.max(0, Math.min(10, arg)); else if (word === "u") { fallback = 0; - emit(String.fromCharCode(arg < 0 ? arg + 65536 : arg)); + // TextEdit writes a soft line break as U+2028, where Chromium does not break the line. + if (arg !== 0x2028) emit(String.fromCharCode(arg < 0 ? arg + 65536 : arg)); + else if (!hidden()) html += "
    "; fallback = state.uc; } else if (!hidden() && word === "page") finishPage(); else if (word === "cell") emit("\t", state.skip); From 9fdcd08835ebd15e134b6abb7e5a65031b1f1266 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 11:02:34 -0800 Subject: [PATCH 048/324] fix(mobile): scheduled task Time dialog closes after OK on Android (#40479) --- .../src/features/settings/SettingsScheduledTasksRouteScreen.tsx | 1 + 1 file changed, 1 insertion(+) diff --git a/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx index 8e15dad08ac23..e878f86581b4a 100644 --- a/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx @@ -1228,6 +1228,7 @@ function TaskForm({ display={Platform.OS === "ios" ? "spinner" : "default"} onDismiss={() => setTimePickerOpen(false)} onValueChange={(_, selected) => { + if (Platform.OS === "android") setTimePickerOpen(false); const timeOfDay = `${String(selected.getHours()).padStart(2, "0")}:${String(selected.getMinutes()).padStart(2, "0")}`; setDraft((current) => ({ ...current, From fcf50973f3353cb401450c5cc6b4a177746150b7 Mon Sep 17 00:00:00 2001 From: Michel Liao <107891771+Michel-Liao@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:14:28 -0500 Subject: [PATCH 049/324] fix(server): RTF attachments no longer garble text set in a font's own character set (#40476) Co-authored-by: Julius Marminge --- .../server/src/provider/documentTextWorker.ts | 47 ++++++++++++++++--- .../src/provider/userInputAttachments.test.ts | 11 +++++ 2 files changed, 52 insertions(+), 6 deletions(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index 9cec14dadd67e..b49b9a42378f3 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -416,10 +416,35 @@ function* notebook(source: string): Generator { } } +// Per-byte decoding only supports the single-byte \fcharset values. +const FONT_CODE_PAGES = new Map([ + [77, "macintosh"], + [161, "windows-1253"], + [162, "windows-1254"], + [163, "windows-1258"], + [177, "windows-1255"], + [178, "windows-1256"], + [186, "windows-1257"], + [204, "windows-1251"], + [222, "windows-874"], + [238, "windows-1250"], +]); + function* rtf(source: string): Generator { if (!source.startsWith("{\\rtf")) throw new Error("Invalid RTF document"); - let state = { skip: false, deleted: false, uc: 1, decoder: new TextDecoder("windows-1252") }; + let state = { + skip: false, + deleted: false, + uc: 1, + font: 0, + fontTable: false, + decoder: new TextDecoder("windows-1252"), + }; const stack: Array = []; + // A font's \fcharset, not the document code page, encodes the bytes written in that font. + const fonts = new Map(); + let defaultFont = 0; + const decoder = () => fonts.get(state.font) ?? state.decoder; const hidden = () => state.skip || state.deleted; const symbols = new Map([ ["endash", "–"], @@ -454,7 +479,7 @@ function* rtf(source: string): Generator { const word = /^([a-z]+)(-?\d+)? ?/i.exec(rest); if (hex) { if (fallback) fallback--; - else if (!hidden()) yield state.decoder.decode(Uint8Array.of(Number.parseInt(hex[1]!, 16))); + else if (!hidden()) yield decoder().decode(Uint8Array.of(Number.parseInt(hex[1]!, 16))); i += 3; } else if (word) { i += word[0].length; @@ -489,8 +514,20 @@ function* rtf(source: string): Generator { ].includes(control) ) state.skip = true; + if (control === "fonttbl") state.fontTable = true; + else if (control === "deff") state.font = defaultFont = value; + else if (control === "f") { + state.font = value; + if (state.fontTable) fonts.delete(value); + } else if (control === "fcharset" && state.fontTable) { + const codePage = FONT_CODE_PAGES.get(value); + if (codePage) fonts.set(state.font, new TextDecoder(codePage)); + } if (control === "deleted") state.deleted = value !== 0; - else if (control === "plain") state.deleted = false; + else if (control === "plain") { + state.deleted = false; + state.font = defaultFont; + } if (control === "mac" || (control === "ansicpg" && value === 10000)) state.decoder = new TextDecoder("macintosh"); else if (control === "ansicpg") { @@ -524,9 +561,7 @@ function* rtf(source: string): Generator { } else if (char !== "\n" && char !== "\r") { if (fallback) fallback--; else if (!hidden()) - yield char.charCodeAt(0) < 128 - ? char - : state.decoder.decode(Uint8Array.of(char.charCodeAt(0))); + yield char.charCodeAt(0) < 128 ? char : decoder().decode(Uint8Array.of(char.charCodeAt(0))); } } } diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index 7bf24acb0b40a..26752022aab17 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -344,6 +344,17 @@ describe("question answer paths", () => { String.raw`{\rtf1\mac\ansicpg10000 Caf\'8e Cr\'8fme}`, "Café Crème", ], + [ + "font character set", + String.raw`{\rtf1\ansi\ansicpg1252\deff1{\fonttbl\f0\fnil\fcharset178 GeezaPro;\f1\fnil\fcharset0 LucidaGrande;} +\f0 \'e3\'e1\'c7\'cd\'d9\'c9\f1 : caf\'e9, \f0\plain\'c7a}`, + "ملاحظة: café, Ça", + ], + [ + "font character set outside the font table", + String.raw`{\rtf1\ansi{\fonttbl{\f0\fcharset178 A;}{\f0\fcharset0 B;}{\f1\fcharset0 C;}{\f2\fcharset178 D;}{\f2 E;}}{\stylesheet{\s0\f1\fcharset178 N;}}\f0 \'e3\f1\'e3\f2\'e3}`, + "ããã", + ], ["destination symbol", String.raw`{\rtf1\ansi\u945\*Z}`, "αZ"], ["multiple units", String.raw`{\rtf1\ansi\uc4\u945?\tab\'3f\~Z}`, "αZ"], ["binary unit", String.raw`{\rtf1\ansi\u945\bin3 abcZ}`, "αZ"], From f0ceeefc08af95ad00ae50a62e1ead5e89c8ebca Mon Sep 17 00:00:00 2001 From: Simone Date: Sat, 21 Nov 2026 20:31:20 +0100 Subject: [PATCH 050/324] fix(antigravity): match skill manifest filters literally (#40488) Co-authored-by: Simone <185146821+Lucenx9@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../Drivers/AntigravitySkills.test.ts | 16 +-- .../src/provider/Drivers/AntigravitySkills.ts | 105 ++---------------- 2 files changed, 19 insertions(+), 102 deletions(-) diff --git a/apps/server/src/provider/Drivers/AntigravitySkills.test.ts b/apps/server/src/provider/Drivers/AntigravitySkills.test.ts index 0033755bfe706..40d78ab16b05f 100644 --- a/apps/server/src/provider/Drivers/AntigravitySkills.test.ts +++ b/apps/server/src/provider/Drivers/AntigravitySkills.test.ts @@ -381,7 +381,7 @@ it.layer(NodeServices.layer)("discoverAntigravitySkills", (it) => { path.join(sharedSkills, "yagni"), "---\nname: yagni\ndescription: Keep it simple.\n---\n", ); - yield* writeSkill( + const experimentalPath = yield* writeSkill( path.join(sharedSkills, "experimental-draft"), "---\nname: experimental-draft\n---\n", ); @@ -392,11 +392,7 @@ it.layer(NodeServices.layer)("discoverAntigravitySkills", (it) => { "---\nname: linter\n---\n", ); yield* writeSkill(path.join(inheritedSkills, "skipped"), "---\nname: skipped\n---\n"); - // Backtracks exponentially under RegExp against the pattern below. - yield* writeSkill( - path.join(inheritedSkills, "a".repeat(40)), - "---\nname: backtrack\n---\n", - ); + yield* writeSkill(path.join(inheritedSkills, "lint-draft"), "---\nname: lint-draft\n---\n"); const projectSkills = path.join(input.cwd, "tools", "skills"); const projectPath = yield* writeSkill( @@ -425,7 +421,7 @@ it.layer(NodeServices.layer)("discoverAntigravitySkills", (it) => { yield* fileSystem.writeFileString( path.join(globalConfigDir, "skills.json"), JSON.stringify({ - inherits: [{ path: inheritedConfigPath, include_only: ["linter", "(a*)*b"] }], + inherits: [{ path: inheritedConfigPath, include_only: ["linter", "lint-.*"] }], entries: [ { path: sharedSkills, exclude: ["experimental-.*"] }, { path: "~/tilde-skills" }, @@ -452,6 +448,12 @@ it.layer(NodeServices.layer)("discoverAntigravitySkills", (it) => { assert.deepEqual(yield* discoverAntigravitySkills(input), [ { name: "deploy", path: projectPath, scope: "project", enabled: true }, + { + name: "experimental-draft", + path: experimentalPath, + scope: "user", + enabled: true, + }, { name: "linter", path: inheritedPath, scope: "user", enabled: true }, { name: "yagni", diff --git a/apps/server/src/provider/Drivers/AntigravitySkills.ts b/apps/server/src/provider/Drivers/AntigravitySkills.ts index f69b3d1c455be..edbe5e34a7343 100644 --- a/apps/server/src/provider/Drivers/AntigravitySkills.ts +++ b/apps/server/src/provider/Drivers/AntigravitySkills.ts @@ -185,106 +185,21 @@ const readSkillFrontmatter = Effect.fn("readAntigravitySkill")(function* ( return bytes.toString("utf8", 0, frontmatterEnd); }); -type SkillPatternMatcher = (entry: string) => boolean; - interface SkillEntryFilter { - readonly includeGroups: ReadonlyArray>; - readonly excludePatterns: ReadonlyArray; + readonly includeGroups: ReadonlyArray>; + readonly excludeNames: ReadonlyArray; } const EMPTY_SKILL_FILTER: SkillEntryFilter = { includeGroups: [], - excludePatterns: [], + excludeNames: [], }; -interface SkillPatternToken { - readonly test: (character: string) => boolean; - readonly optional: boolean; - readonly repeats: boolean; -} - -/** Undefined for syntax outside literals, escapes, `.`, `[...]` and `* + ?`; such patterns match literally. */ -function parseSkillPattern(pattern: string): ReadonlyArray | undefined { - const characters = Array.from(pattern); - const tokens: Array = []; - let index = 0; - while (index < characters.length) { - const character = characters[index]!; - let test: (candidate: string) => boolean; - if (character === "\\") { - const escaped = characters[index + 1]; - if (escaped === undefined) return undefined; - if (/[dDwWsS]/.test(escaped)) { - const characterClass = new RegExp(`^\\${escaped}$`, "u"); - test = (candidate) => characterClass.test(candidate); - } else { - test = (candidate) => candidate === escaped; - } - index += 2; - } else if (character === "[") { - const close = characters.indexOf("]", index + 2); - if (close === -1) return undefined; - let characterClass: RegExp; - try { - characterClass = new RegExp(`^[${characters.slice(index + 1, close).join("")}]$`, "u"); - } catch { - return undefined; - } - test = (candidate) => characterClass.test(candidate); - index = close + 1; - } else if (character === ".") { - test = () => true; - index += 1; - } else if ("()|{}^$*+?".includes(character)) { - return undefined; - } else { - test = (candidate) => candidate === character; - index += 1; - } - const quantifier = characters[index]; - const optional = quantifier === "*" || quantifier === "?"; - const repeats = quantifier === "*" || quantifier === "+"; - if (optional || repeats) { - index += 1; - if (characters[index] === "?") index += 1; - } - tokens.push({ test, optional, repeats }); - } - return tokens; -} - -/** Manifests can come from an opened workspace, so matching runs as an NFA in linear time instead of RegExp. */ -function compileSkillPattern(pattern: string): SkillPatternMatcher { - const tokens = parseSkillPattern(pattern); - if (tokens === undefined) return (entry) => entry === pattern; - const close = (states: Set) => { - for (const state of states) { - if (state < tokens.length && tokens[state]!.optional) states.add(state + 1); - } - return states; - }; - return (entry) => { - let states = close(new Set([0])); - for (const character of entry) { - const next = new Set(); - for (const state of states) { - const token = tokens[state]; - if (!token?.test(character)) continue; - next.add(state + 1); - if (token.repeats) next.add(state); - } - if (next.size === 0) return false; - states = close(next); - } - return states.has(tokens.length); - }; -} - function matchesSkillFilter(entry: string, filter: SkillEntryFilter): boolean { for (const group of filter.includeGroups) { - if (!group.some((matches) => matches(entry))) return false; + if (!group.includes(entry)) return false; } - return !filter.excludePatterns.some((matches) => matches(entry)); + return !filter.excludeNames.includes(entry); } function narrowSkillFilter( @@ -293,13 +208,13 @@ function narrowSkillFilter( ): SkillEntryFilter { const includeGroups = entry.include_only && entry.include_only.length > 0 - ? [...parent.includeGroups, entry.include_only.map(compileSkillPattern)] + ? [...parent.includeGroups, entry.include_only] : parent.includeGroups; - const excludePatterns = + const excludeNames = entry.exclude && entry.exclude.length > 0 - ? [...parent.excludePatterns, ...entry.exclude.map(compileSkillPattern)] - : parent.excludePatterns; - return { includeGroups, excludePatterns }; + ? [...parent.excludeNames, ...entry.exclude] + : parent.excludeNames; + return { includeGroups, excludeNames }; } // agy does not expand ~, so a ~/ path stays relative to the config file. From e452042db8af83b6cbc503fa9c6612b30054372e Mon Sep 17 00:00:00 2001 From: phorrr Date: Sat, 21 Nov 2026 20:42:28 +0100 Subject: [PATCH 051/324] fix(contracts): older clients drop unknown values in RPC responses (#40490) Co-authored-by: x0r Co-authored-by: Julius Marminge --- packages/contracts/src/baseSchemas.test.ts | 15 +++++++++++++-- packages/contracts/src/baseSchemas.ts | 11 +++++++++-- packages/contracts/src/pullRequest.test.ts | 15 +++++++++++++-- 3 files changed, 35 insertions(+), 6 deletions(-) diff --git a/packages/contracts/src/baseSchemas.test.ts b/packages/contracts/src/baseSchemas.test.ts index ec5b5e31d75f7..beae3731400bc 100644 --- a/packages/contracts/src/baseSchemas.test.ts +++ b/packages/contracts/src/baseSchemas.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "@effect/vitest"; import * as DateTime from "effect/DateTime"; +import * as Exit from "effect/Exit"; import * as Schema from "effect/Schema"; import { @@ -22,13 +23,23 @@ const fromWire = (schema: S) => describe("ForwardCompatibleArray", () => { it("decodes elements through their own codec and drops ones it cannot read", () => { - const decoded = fromWire(ForwardCompatibleArray(Shape))([ + const shapes = ForwardCompatibleArray(Shape); + const exit = Schema.toCodecJson(Schema.Exit(shapes, Schema.Never, Schema.Never)); + const wire = [ { kind: "circle", radius: 1, at }, { kind: "triangle" }, { kind: "square", side: "wide" }, - ]); + ]; + const decoded = fromWire(shapes)(wire); expect(decoded).toHaveLength(1); expect(DateTime.isDateTime((decoded[0] as { at: unknown }).at)).toBe(true); + expect(Schema.decodeSync(exit)({ _tag: "Success", value: wire })).toEqual( + Exit.succeed(decoded), + ); + expect(Schema.encodeSync(exit)(Exit.succeed(decoded))).toEqual({ + _tag: "Success", + value: [wire[0]], + }); }); const Named = ForwardCompatibleArray(Schema.Struct({ name: TrimmedNonEmptyString })); diff --git a/packages/contracts/src/baseSchemas.ts b/packages/contracts/src/baseSchemas.ts index 7b000a4a22edc..30df0d53c537f 100644 --- a/packages/contracts/src/baseSchemas.ts +++ b/packages/contracts/src/baseSchemas.ts @@ -94,11 +94,18 @@ export const OmittedWhenNull = (value: Value) => { ); }; +const UnknownArrayElement = Schema.Unknown.pipe( + Schema.decodeTo(Schema.Undefined, { + decode: SchemaGetter.succeed(undefined), + encode: SchemaGetter.passthrough(), + }), +); + /** Prefer {@link ForwardCompatibleUnion} for tagged unions so malformed known members still fail. */ export const ForwardCompatibleArray = (element: Element) => + // Exit derives its wire codec from the encoded shape, which keeps the union but drops recovery middleware. Schema.Array( - Schema.UndefinedOr(element).pipe( - Schema.catchDecoding(() => Effect.succeedSome(undefined)), + Schema.Union([element, UnknownArrayElement]).pipe( Schema.catchEncoding(() => Effect.succeedSome(undefined)), ), ).pipe( diff --git a/packages/contracts/src/pullRequest.test.ts b/packages/contracts/src/pullRequest.test.ts index 91f22f20bfa5f..2e801b71970ef 100644 --- a/packages/contracts/src/pullRequest.test.ts +++ b/packages/contracts/src/pullRequest.test.ts @@ -1,14 +1,25 @@ import { SourceControlProviderKind } from "./sourceControl.ts"; +import * as Exit from "effect/Exit"; +import * as Rpc from "effect/rpc/Rpc"; import * as Schema from "effect/Schema"; import { describe, expect, it } from "vite-plus/test"; import { - PullRequestDetail, + type PullRequestDetail, PullRequestListResult, resolvePullRequestAuthorFilter, } from "./pullRequest.ts"; +import { WS_METHODS, WsRpcGroup } from "./rpc.ts"; -const decodeDetail = Schema.decodeUnknownSync(Schema.toCodecJson(PullRequestDetail)); +// Clients decode the detail inside the RPC's Exit, as the JSON serialization does. +const decodeDetailExit = Schema.decodeUnknownSync( + Schema.toCodecJson(Rpc.exitSchema(WsRpcGroup.requests.get(WS_METHODS.pullRequestsDetail)!)), +); +const decodeDetail = (value: unknown): PullRequestDetail => { + const exit = decodeDetailExit({ _tag: "Success", value }); + if (!Exit.isSuccess(exit)) throw new Error("expected a successful exit"); + return exit.value as PullRequestDetail; +}; const LIST_RESULT: PullRequestListResult = { viewers: { "github.com": "bilal", "gitlab.com": "bilal.hassan" }, From 10a5b5dca60159750132a7f07120e813fdb7b07c Mon Sep 17 00:00:00 2001 From: Michel Liao <107891771+Michel-Liao@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:47:25 -0500 Subject: [PATCH 052/324] fix(server): Word table cells wrapped in a content control reach the agent (#40496) Co-authored-by: Julius Marminge --- apps/server/src/provider/documentTextWorker.ts | 5 ++--- apps/server/src/provider/userInputAttachments.test.ts | 3 ++- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index b49b9a42378f3..8509b490cceee 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -256,9 +256,8 @@ function hasCellText(cell: XmlNode): boolean { function* table(node: XmlNode): Generator { let rowCount = 0; for (const row of all(node, ["tr", "table-row"])) { - const cells = children(row).filter((cell) => - ["tc", "table-cell", "covered-table-cell", "td", "th"].includes(cell.name), - ); + // Word nests a cell inside w:sdt when a content control wraps the whole cell. + const cells = [...all(row, ["tc", "table-cell", "covered-table-cell", "td", "th"])]; // ODS writers pad sheets with repeated empty rows and trailing cells. while (cells.length && !hasCellText(cells.at(-1)!)) cells.pop(); if (!cells.length) continue; diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index 26752022aab17..556351b225bac 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -786,11 +786,12 @@ describe("question answer paths", () => { bounded: true, parts: { "word/document.xml": - 'Report & totalsNorth1234BeforeInnerAfterNeighbor', + 'Report & totalsNorth1234Annual reportDraftBeforeInnerAfterNeighbor', }, expected: [ "## Report & totals", "North\t12 34", + "Annual report\tDraft", "Before Inner After\tNeighbor\t\u2011\n\u2011", ], }, From db9efc5cf0fa181e0a913e750ed908b0814809f8 Mon Sep 17 00:00:00 2001 From: Ibrahim Elkamali Date: Sat, 21 Nov 2026 21:51:16 +0200 Subject: [PATCH 053/324] fix(server): a stop-on-settle action no longer holds back automatic settlement (#40489) Co-authored-by: Julius Marminge --- apps/server/src/terminal/Manager.test.ts | 6 ++++++ apps/server/src/terminal/Manager.ts | 3 ++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index c6f45a60ab75e..8af803db1fd8c 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -1003,12 +1003,18 @@ it.layer( { pid: 100, ppid: 9000, name: "zsh" }, { pid: 9001, ppid: 1, name: "zsh" }, { pid: 200, ppid: 9001, name: "node" }, + { pid: 9002, ppid: 1, name: "zsh" }, + { pid: 300, ppid: 9002, name: "node" }, ]), }).pipe(Effect.provide(layerWithHostPlatform("linux"))); yield* manager.open(openInput({ terminalId: "idle", threadId: "thread-idle" })); yield* manager.open(openInput({ terminalId: "dev-server", threadId: "thread-active" })); + yield* manager.open( + openInput({ terminalId: "managed-dev", threadId: "thread-managed", stopOnSettle: true }), + ); expect(yield* manager.hasActiveSubprocess({ threadId: "thread-none" })).toBe(false); + expect(yield* manager.hasActiveSubprocess({ threadId: "thread-managed" })).toBe(false); expect(yield* manager.hasActiveSubprocess({ threadId: "thread-idle" })).toBe(false); expect(yield* manager.hasActiveSubprocess({ threadId: "thread-active" })).toBe(true); }), diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index 86ccc1d3e0dd2..fb19b6c7ad1d6 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -3968,9 +3968,10 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func const hasActiveSubprocess = Effect.fn("terminal.hasActiveSubprocess")(function* (input: { readonly threadId: string; }) { + // Settling closes stopOnSettle sessions, so their work must not hold settlement back. const running = (yield* sessionsForThread(input.threadId)).filter( (session): session is TerminalSessionState & { pid: number } => - session.status === "running" && Number.isInteger(session.pid), + session.status === "running" && Number.isInteger(session.pid) && !session.stopOnSettle, ); if (running.length === 0) return false; const { inspector } = yield* acquireSubprocessInspector( From bac86471fe75e5f344a524b60775a14da0e1dd33 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 12:10:15 -0800 Subject: [PATCH 054/324] fix(web): links inside a PDF are clickable in the in-app PDF viewer (#40507) --- .../components/files/BrowserDocumentFrame.tsx | 8 ++ .../src/components/files/FilePreviewPanel.tsx | 1 + .../files/PdfViewer.browser.test.tsx | 49 +++++++++- apps/web/src/components/files/PdfViewer.tsx | 90 ++++++++++++++++++- 4 files changed, 144 insertions(+), 4 deletions(-) diff --git a/apps/web/src/components/files/BrowserDocumentFrame.tsx b/apps/web/src/components/files/BrowserDocumentFrame.tsx index 024f8480a6d7f..3270556fb0ff4 100644 --- a/apps/web/src/components/files/BrowserDocumentFrame.tsx +++ b/apps/web/src/components/files/BrowserDocumentFrame.tsx @@ -85,6 +85,7 @@ function PdfDocument(props: { src: string; title: string; documentKey: string; + threadRef: ScopedThreadRef | undefined; actions?: ReactNode; }) { const [view, setView] = useState({ page: 0, offset: 0, zoom: null, left: 0 }); @@ -96,6 +97,7 @@ function PdfDocument(props: { positionKey={props.documentKey} initialView={view} onViewChange={setView} + threadRef={props.threadRef} actions={props.actions} /> ); @@ -108,9 +110,11 @@ function PdfDocumentRevision(props: { positionKey: string; initialView: PdfViewState; onViewChange: (view: PdfViewState) => void; + threadRef: ScopedThreadRef | undefined; actions?: ReactNode; }) { const [src] = useState(props.src); + const openLink = useOpenLink(props.threadRef); // The Electron shell does not enable PDF plugins. WebKit embeds on iOS // expose only the first page, even when pdfViewerEnabled reports support. const native = @@ -133,6 +137,9 @@ function PdfDocumentRevision(props: { positionKey={props.positionKey} initialView={props.initialView} onViewChange={props.onViewChange} + onOpenLink={(url, event) => { + void openLink(url, { event }).catch((cause: unknown) => console.error(cause)); + }} actions={props.actions} /> @@ -163,6 +170,7 @@ export function BrowserDocumentFrame(props: { documentKey={key} src={props.src} title={props.title} + threadRef={props.threadRef} actions={props.pdfActions} /> ) : props.htmlRender ? ( diff --git a/apps/web/src/components/files/FilePreviewPanel.tsx b/apps/web/src/components/files/FilePreviewPanel.tsx index 13a74c131eea3..c020113815dfa 100644 --- a/apps/web/src/components/files/FilePreviewPanel.tsx +++ b/apps/web/src/components/files/FilePreviewPanel.tsx @@ -350,6 +350,7 @@ export function WorkspaceBrowserPreview(props: { documentId={documentId} title={props.title} pdf={pdf} + threadRef={props.threadRef} pdfActions={ >", `<< /Type /Pages /Count ${pages.length} /Kids [${pages.map((_, index) => `${3 + index * 2} 0 R`).join(" ")}] >>`, - ...pages.flatMap(({ box, rotate, text }, index) => [ - `<< /Type /Page /Parent 2 0 R /MediaBox [${box}] /Rotate ${rotate} /Resources << /Font << /F1 ${fonts} 0 R /F2 ${fonts + 1} 0 R >> >> /Contents ${4 + index * 2} 0 R >>`, + ...pages.flatMap(({ box, rotate, text, annots = "" }, index) => [ + `<< /Type /Page /Parent 2 0 R /MediaBox [${box}] /Rotate ${rotate}${annots && ` /Annots [${annots}]`} /Resources << /Font << /F1 ${fonts} 0 R /F2 ${fonts + 1} 0 R >> >> /Contents ${4 + index * 2} 0 R >>`, `<< /Length ${text.length} >>\nstream\n${text}\nendstream`, ]), "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>", @@ -257,3 +257,46 @@ it("restores page, within-page offset and zoom after a remount", async () => { URL.revokeObjectURL(url); } }); + +it("follows a link to another page and exposes a web link", async () => { + const url = URL.createObjectURL( + testPdf([ + { + box: "0 0 612 792", + rotate: 0, + text: "BT /F1 24 Tf 30 700 Td (See p. 2) Tj 0 -60 Td (Website) Tj ET", + annots: [ + "<< /Type /Annot /Subtype /Link /Rect [30 690 200 730] /Border [0 0 0] /Dest [5 0 R /XYZ 0 792 0] >>", + "<< /Type /Annot /Subtype /Link /Rect [30 630 200 670] /Border [0 0 0] /A << /S /URI /URI (https://example.com/) >> >>", + ].join(" "), + }, + { box: "0 0 612 792", rotate: 0, text: "BT /F1 24 Tf 30 700 Td (Target) Tj ET" }, + ]), + ); + try { + await using screen = await render( +
    + +
    , + ); + await expect.element(screen.getByText("1 / 2 pages")).toBeVisible(); + const region = screen.getByRole("region", { name: "Linked PDF" }).element(); + const web = await vi.waitFor(() => { + const link = region.querySelector('a[href="https://example.com/"]'); + expect(link).not.toBeNull(); + return link!; + }); + expect(getComputedStyle(web).cursor).toBe("pointer"); + const internal = await vi.waitFor(() => { + const link = Array.from(region.querySelectorAll("a")).find( + (anchor) => anchor !== web, + ); + expect(link).toBeDefined(); + return link!; + }); + internal.click(); + await expect.element(screen.getByText("2 / 2 pages")).toBeVisible(); + } finally { + URL.revokeObjectURL(url); + } +}); diff --git a/apps/web/src/components/files/PdfViewer.tsx b/apps/web/src/components/files/PdfViewer.tsx index f81e23deab2b1..31faf628fbeb9 100644 --- a/apps/web/src/components/files/PdfViewer.tsx +++ b/apps/web/src/components/files/PdfViewer.tsx @@ -6,6 +6,7 @@ import { useRef, useState, type CSSProperties, + type MouseEvent, type ReactNode, } from "react"; import { TextLayer, type PDFDocumentProxy } from "pdfjs-dist"; @@ -42,6 +43,21 @@ type PdfPosition = PdfViewState & { width: number; ratios: readonly number[] }; // Thread switches unmount the preview; retain only the most recent documents. const positions = new Map(); +type PdfLink = { box: readonly [number, number, number, number] } & ( + | { url: string } + | { page: number } +); + +// Resolves a link annotation's destination, named or explicit, to a page index. +async function pdfLinkPage(pdf: PDFDocumentProxy, dest: unknown): Promise { + const explicit: unknown = typeof dest === "string" ? await pdf.getDestination(dest) : dest; + if (!Array.isArray(explicit)) return null; + const [ref] = explicit as unknown[]; + if (Number.isInteger(ref)) return ref as number; + if (typeof ref !== "object" || ref === null) return null; + return pdf.getPageIndex(ref as Parameters[0]); +} + export type PdfViewState = { page: number; offset: number; @@ -56,8 +72,11 @@ function PdfPage(props: { query: string; onSize: (index: number, ratio: number) => void; onError: (error: string) => void; + onPageLink: (index: number) => void; + onOpenLink: ((url: string, event: MouseEvent) => void) | undefined; }) { const gt = useGT(); + const [links, setLinks] = useState([]); const canvas = useRef(null); const text = useRef(null); const painted = useRef(null); @@ -112,7 +131,31 @@ function PdfPage(props: { buffer.width = 0; painted.current = pdf; }); - await Promise.all([shown, layer.render()]); + const linked = page.getAnnotations({ intent: "display" }).then(async (annotations) => { + const found: PdfLink[] = []; + for (const annotation of annotations) { + if (annotation.subtype !== "Link") continue; + const [x1, y1] = viewport.convertToViewportPoint(annotation.rect[0], annotation.rect[1]); + const [x2, y2] = viewport.convertToViewportPoint(annotation.rect[2], annotation.rect[3]); + const box = [ + Math.min(x1, x2) / viewport.width, + Math.min(y1, y2) / viewport.height, + Math.abs(x2 - x1) / viewport.width, + Math.abs(y2 - y1) / viewport.height, + ] as const; + if (typeof annotation.url === "string" && /^https?:\/\//i.test(annotation.url)) { + found.push({ box, url: annotation.url }); + continue; + } + const target = await pdfLinkPage(pdf, annotation.dest).catch(() => null); + if (target !== null && target >= 0 && target < pdf.numPages) + found.push({ box, page: target }); + } + if (!cancelled) setLinks(found); + }); + // A page whose annotations cannot be read still renders, without links. + const linkedOrNone = linked.catch(() => undefined); + await Promise.all([shown, layer.render(), linkedOrNone]); })().catch((cause: unknown) => { if (!cancelled) onError(thrownErrorMessage(cause, m) ?? m(msg("This PDF page could not render."))); @@ -151,6 +194,48 @@ function PdfPage(props: { className="block h-full w-full" />
    ))} From ba4f99ae43b0b5988bd00e729c6a55cadaa5fd2b Mon Sep 17 00:00:00 2001 From: Sean Kenneth Doherty Date: Sat, 21 Nov 2026 14:10:26 -0600 Subject: [PATCH 055/324] fix(web,mobile): Limits shows why a provider's limits are unavailable (#40481) Co-authored-by: Sean Kenneth Doherty <328402569+seankd3@users.noreply.github.com> Co-authored-by: Julius Marminge --- packages/shared/src/usageLimits.test.ts | 24 ++++++++++++++++++++++++ packages/shared/src/usageLimitsCopy.ts | 11 +++++++++-- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/packages/shared/src/usageLimits.test.ts b/packages/shared/src/usageLimits.test.ts index 6b553fe5f1555..0019c74e1d5cd 100644 --- a/packages/shared/src/usageLimits.test.ts +++ b/packages/shared/src/usageLimits.test.ts @@ -1889,6 +1889,30 @@ describe("external usage settings", () => { expect(collectLimitNotices(presentations)).toEqual(["Host · codex: Could not read limits."]); }); + it("shows the reason an account's limits are unsupported, but not a bare unsupported", () => { + const unsupported = (message?: string) => + provider({ + usageLimits: { + checkedAt: "2026-09-03T11:00:00.000Z", + windows: [], + unavailable: { reason: "unsupported", ...(message ? { message } : {}) }, + }, + }); + const notices = (limited: ServerProvider) => + collectLimitNotices( + new Map([ + [ + EnvironmentId.make("a"), + { entry: { target: { label: "Host" } }, serverConfig: { providers: [limited] } }, + ], + ]), + ); + expect(notices(unsupported("Sign in with Google to see Antigravity limits."))).toEqual([ + "codex: Sign in with Google to see Antigravity limits.", + ]); + expect(notices(unsupported())).toEqual([]); + }); + it("names a hub account whose read failed unless another environment read it", () => { const checkedAt = "2026-09-03T11:00:00.000Z"; const account = { diff --git a/packages/shared/src/usageLimitsCopy.ts b/packages/shared/src/usageLimitsCopy.ts index ea9eafaf55ce1..85f78e0f11f28 100644 --- a/packages/shared/src/usageLimitsCopy.ts +++ b/packages/shared/src/usageLimitsCopy.ts @@ -92,8 +92,15 @@ export function collectLimitNotices( for (const presentation of presentations.values()) { const environmentLabel = presentation.entry.target.label; for (const provider of providersWithLimits(presentation.serverConfig?.providers ?? [])) { - if (provider.usageLimits?.unavailable?.reason === "unsupported") continue; - const notice = provider.usageLimits ? limitsNotice(provider.usageLimits, resolve) : null; + const limits = provider.usageLimits; + // A bare unsupported means the account has no limits; an external usage link shows its message. + if ( + limits?.unavailable?.reason === "unsupported" && + (!limits.unavailable.message || limits.externalUsage) + ) { + continue; + } + const notice = limits ? limitsNotice(limits, resolve) : null; const name = provider.displayName?.trim() || String(provider.driver); if (notice) notices.add(`${label(environmentLabel, name)}: ${notice}`); } From c3fb01dc0535c0312b5ff8fa386fde5c8d675593 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 12:14:57 -0800 Subject: [PATCH 056/324] fix(server): preview snapshots no longer report an empty interactiveElements list (#40520) --- apps/server/src/mcp/McpHttpServer.test.ts | 57 +++---------------- apps/server/src/mcp/McpHttpServer.ts | 48 +++------------- apps/server/src/preview/ServerBrowser.test.ts | 1 - .../src/preview/ServerBrowserPage.test.ts | 18 +++++- apps/server/src/preview/ServerBrowserPage.ts | 6 +- .../mcp-tool-use/cases/browser-routing.ndjson | 26 ++++----- packages/contracts/src/previewAutomation.ts | 13 ----- 7 files changed, 48 insertions(+), 121 deletions(-) diff --git a/apps/server/src/mcp/McpHttpServer.test.ts b/apps/server/src/mcp/McpHttpServer.test.ts index e5d47410817f2..3842d1a4b3bf2 100644 --- a/apps/server/src/mcp/McpHttpServer.test.ts +++ b/apps/server/src/mcp/McpHttpServer.test.ts @@ -124,7 +124,6 @@ const snapshotResult = { title: "Example", loading: false, visibleText: "Example", - interactiveElements: [], accessibilityTree: {}, consoleEntries: [], networkEntries: [], @@ -421,18 +420,6 @@ it.effect.each([ url: "http://example.test/", loading: false, visibleText: "Save your changes", - interactiveElements: [ - { - tag: "button", - role: "button", - name: "Save", - selector: "#save", - x: 0, - y: 0, - width: 20, - height: 10, - }, - ], accessibilityTree: { role: "document", name: "Example" }, consoleEntries: [], networkEntries: [], @@ -482,7 +469,7 @@ it.effect.each([ expect(snapshot.isError).toBe(false); expect(snapshot.structuredContent).toEqual({ ...boundedMetadata, - omitted: ["accessibilityTree (use interactiveElements locators or preview_evaluate)"], + omitted: ["accessibilityTree (use preview_evaluate)"], }); const [identity, text, ...rest] = snapshot.content; expect(identity?.type === "text" ? decodeJsonText(identity.text) : null).toEqual({ @@ -492,7 +479,7 @@ it.effect.each([ expect(rest).toEqual([ { type: "text", - text: "Snapshot text was bounded. Omitted: accessibilityTree (use interactiveElements locators or preview_evaluate).", + text: "Snapshot text was bounded. Omitted: accessibilityTree (use preview_evaluate).", }, ...(images ? [ @@ -890,25 +877,9 @@ it.effect("keeps the snapshot text under the agent's output ceiling", () => Effect.scoped( Effect.gen(function* () { const pageText = "/Users/theo/Code/project\nClaude, Codex · 79 threads\n".repeat(600); - const element = (name: string, index: number) => ({ - tag: "div", - role: "presentation", - name, - selector: `div:nth-of-type(${index})`, - x: 0, - y: 0, - width: 10, - height: 10, - }); const oversized = { ...snapshotResult, visibleText: pageText, - interactiveElements: [ - element(pageText, 1), - element(pageText, 2), - element(pageText, 3), - element("Continue", 4), - ], accessibilityTree: { nodes: Array.from({ length: 2_000 }, (_, i) => ({ nodeId: `${i}` })) }, consoleEntries: Array.from({ length: 100 }, (_, i) => ({ level: "log", @@ -933,14 +904,10 @@ it.effect("keeps the snapshot text under the agent's output ceiling", () => const parsed = decodeJsonText(body) as { readonly accessibilityTree?: unknown; readonly visibleText: string; - readonly interactiveElements: ReadonlyArray<{ readonly name: string }>; readonly consoleEntries: ReadonlyArray<{ readonly text: string }>; }; expect(parsed.accessibilityTree).toBeUndefined(); expect(parsed.visibleText.length).toBeLessThanOrEqual(8_001); - expect(parsed.interactiveElements).toHaveLength(4); - expect(parsed.interactiveElements[0]?.name.length).toBeLessThanOrEqual(201); - expect(parsed.interactiveElements[3]?.name).toBe("Continue"); expect(parsed.consoleEntries).toHaveLength(40); expect(parsed.consoleEntries[0]?.text).toBe("entry 60"); expect(notice?.type === "text" ? notice.text : "").toContain("accessibilityTree"); @@ -960,7 +927,6 @@ it.effect("bounds the snapshot text even when nothing but logs and the title are const oversized = { ...snapshotResult, title: `t${"😀".repeat(35_000)}`, - interactiveElements: [], consoleEntries: [{ level: "log", text: `x${"😀".repeat(35_000)}`, timestamp: "t" }], }; yield* serveSnapshots("mcp-bounded-logs-client", oversized); @@ -992,19 +958,14 @@ it.effect("bounds the snapshot text even when nothing but logs and the title are it.effect("bounds page text made of wide characters before dropping locators", () => Effect.scoped( Effect.gen(function* () { + const accessibilityTree = Array.from( + { length: 20 }, + (_, i) => `- button "Button ${i}" [ref=t3-1-e${i}]`, + ).join("\n"); yield* serveSnapshots("mcp-wide-text-client", { ...snapshotResult, visibleText: "界".repeat(9_000), - interactiveElements: Array.from({ length: 20 }, (_, i) => ({ - tag: "button", - role: "button", - name: `Button ${i}`, - selector: `#button-${i}`, - x: 0, - y: 0, - width: 10, - height: 10, - })), + accessibilityTree, }); const snapshot = yield* callSnapshot({ includeImage: false }); @@ -1016,10 +977,10 @@ it.effect("bounds page text made of wide characters before dropping locators", ( ); const parsed = decodeJsonText(body) as { readonly visibleText: string; - readonly interactiveElements: ReadonlyArray; + readonly accessibilityTree: string; }; expect(parsed.visibleText).toMatch(/^界+…$/); - expect(parsed.interactiveElements).toHaveLength(20); + expect(parsed.accessibilityTree).toBe(accessibilityTree); expect(notice?.type === "text" ? notice.text : "").toContain( "visibleText after 4000 characters", ); diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index d7bea75493b73..4c9d9dca1081a 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -373,7 +373,6 @@ export const MAX_SNAPSHOT_TEXT_BYTES = 20_000; const MAX_SNAPSHOT_VISIBLE_TEXT_CHARS = 8_000; // Page text and the ARIA tree both shrink to this before either drops below it. const SNAPSHOT_TEXT_FLOOR_CHARS = 2_000; -const MAX_SNAPSHOT_ELEMENT_NAME_CHARS = 200; const MAX_SNAPSHOT_LOG_ENTRIES = 40; const MAX_SNAPSHOT_LOG_TEXT_CHARS = 500; const MAX_SNAPSHOT_IDENTIFIER_CHARS = 2_048; @@ -406,10 +405,6 @@ type SnapshotMetadata = { readonly url: string; readonly title: string; readonly visibleText: string; - readonly interactiveElements: ReadonlyArray<{ - readonly name: string; - readonly [key: string]: unknown; - }>; readonly consoleEntries: ReadonlyArray; readonly networkEntries: ReadonlyArray; readonly actionTimeline: ReadonlyArray; @@ -426,7 +421,7 @@ const boundSnapshotMetadata = (metadata: SnapshotMetadata) => { const { accessibilityTree, ...withoutTree } = metadata; const ariaTree = typeof accessibilityTree === "string" ? accessibilityTree : undefined; if (accessibilityTree !== undefined && ariaTree === undefined) { - omitted.push("accessibilityTree (use interactiveElements locators or preview_evaluate)"); + omitted.push("accessibilityTree (use preview_evaluate)"); } const tail = (entries: ReadonlyArray, label: string) => { if (entries.length > MAX_SNAPSHOT_LOG_ENTRIES) { @@ -444,41 +439,23 @@ const boundSnapshotMetadata = (metadata: SnapshotMetadata) => { ) { omitted.push(`url or title after ${MAX_SNAPSHOT_IDENTIFIER_CHARS} characters`); } - if ( - metadata.interactiveElements.some( - (element) => element.name.length > MAX_SNAPSHOT_ELEMENT_NAME_CHARS, - ) - ) { - omitted.push(`element names longer than ${MAX_SNAPSHOT_ELEMENT_NAME_CHARS} characters`); - } const bounded = { ...withoutTree, url: cutText(metadata.url, MAX_SNAPSHOT_IDENTIFIER_CHARS), title: cutText(metadata.title, MAX_SNAPSHOT_IDENTIFIER_CHARS), - interactiveElements: metadata.interactiveElements.map((element) => ({ - ...element, - name: cutText(element.name, MAX_SNAPSHOT_ELEMENT_NAME_CHARS), - })), consoleEntries: tail(metadata.consoleEntries, "console entries"), networkEntries: tail(metadata.networkEntries, "network entries"), actionTimeline: tail(metadata.actionTimeline, "action timeline entries"), }; // Per-field character caps can still exceed the total byte ceiling. - const shedOrder = [ - "actionTimeline", - "networkEntries", - "consoleEntries", - "interactiveElements", - ] as const; + const shedOrder = ["actionTimeline", "networkEntries", "consoleEntries"] as const; const lists: Record<(typeof shedOrder)[number], ReadonlyArray> = { - interactiveElements: bounded.interactiveElements, consoleEntries: bounded.consoleEntries, networkEntries: bounded.networkEntries, actionTimeline: bounded.actionTimeline, }; const dropped: Record<(typeof shedOrder)[number], number> = { - interactiveElements: 0, consoleEntries: 0, networkEntries: 0, actionTimeline: 0, @@ -493,22 +470,18 @@ const boundSnapshotMetadata = (metadata: SnapshotMetadata) => { }); let text = encodeJsonText(value()); while (utf8Length(text) > MAX_SNAPSHOT_TEXT_BYTES) { - // Logs shed first, oldest first. Below the floors, locator-bearing elements and tree go last. + // Logs shed first, oldest first. Below the floors, the locator-bearing tree goes last. const key = - shedOrder.find( - (candidate) => candidate !== "interactiveElements" && lists[candidate].length > 0, - ) ?? + shedOrder.find((candidate) => lists[candidate].length > 0) ?? (visibleTextChars > SNAPSHOT_TEXT_FLOOR_CHARS ? "visibleText" : ariaTreeChars > SNAPSHOT_TEXT_FLOOR_CHARS ? "accessibilityTree" : visibleTextChars > 0 ? "visibleText" - : lists.interactiveElements.length > 0 - ? "interactiveElements" - : ariaTreeChars > 0 - ? "accessibilityTree" - : undefined); + : ariaTreeChars > 0 + ? "accessibilityTree" + : undefined); if (key === undefined) break; if (key === "visibleText") { visibleTextChars = halveToFloor(visibleTextChars); @@ -517,12 +490,7 @@ const boundSnapshotMetadata = (metadata: SnapshotMetadata) => { } else { const keep = Math.floor(lists[key].length / 2); dropped[key] += lists[key].length - keep; - lists[key] = - keep === 0 - ? [] - : key === "interactiveElements" - ? lists[key].slice(0, keep) - : lists[key].slice(-keep); + lists[key] = keep === 0 ? [] : lists[key].slice(-keep); } text = encodeJsonText(value()); } diff --git a/apps/server/src/preview/ServerBrowser.test.ts b/apps/server/src/preview/ServerBrowser.test.ts index 9d1460c9befd5..a15378ec3039c 100644 --- a/apps/server/src/preview/ServerBrowser.test.ts +++ b/apps/server/src/preview/ServerBrowser.test.ts @@ -235,7 +235,6 @@ function makeContext(onClose?: (context: BrowserContext) => void, initialUrl = " title: "test page", loading: false, visibleText: "delete", - interactiveElements: [], })), ariaSnapshot: vi.fn(async () => '- button "delete" [ref=e1]'), locator: vi.fn((): unknown => { diff --git a/apps/server/src/preview/ServerBrowserPage.test.ts b/apps/server/src/preview/ServerBrowserPage.test.ts index 79ccc4089aeee..9afe924dabc4c 100644 --- a/apps/server/src/preview/ServerBrowserPage.test.ts +++ b/apps/server/src/preview/ServerBrowserPage.test.ts @@ -61,7 +61,6 @@ describe("snapshot deadline diagnostics", () => { title: "", loading: false, visibleText: "", - interactiveElements: [], }), ariaSnapshot: async () => "", ...options.page, @@ -275,6 +274,23 @@ describe("server browser element refs", () => { }; const repeatedRows = `
      ${Array.from({ length: 5 }, (_, i) => `
    • row ${i + 1}
    • `).join("")}
    `; + it("does not report an empty interactiveElements list beside a tree full of controls", async () => { + await page.setContent( + `
    Sign in`, + ); + const result = await takeSnapshot(); + expect(buttonLocator(result.accessibilityTree, "Open menu")).toBeDefined(); + expect(String(result.accessibilityTree)).toContain('link "Sign in"'); + const elements = ( + result as { readonly interactiveElements?: ReadonlyArray<{ readonly name: string }> } + ).interactiveElements; + if (elements !== undefined) { + expect(elements.map((element) => element.name)).toEqual( + expect.arrayContaining(["Sign in", "Open menu", "Dismiss local database notice"]), + ); + } + }); + it("clicks the fifth repeated delete control without touching row one", async () => { await page.setContent(repeatedRows); const result = await takeSnapshot(); diff --git a/apps/server/src/preview/ServerBrowserPage.ts b/apps/server/src/preview/ServerBrowserPage.ts index ac37b9914ef76..f5eed496da5fe 100644 --- a/apps/server/src/preview/ServerBrowserPage.ts +++ b/apps/server/src/preview/ServerBrowserPage.ts @@ -198,7 +198,6 @@ const SNAPSHOT_SCRIPT = `(() => { title: document.title, loading: document.readyState !== "complete", visibleText: document.body?.innerText || "", - interactiveElements: [], }; })()`; @@ -699,10 +698,7 @@ const capture = async ( "page state", () => input.page.evaluate(SNAPSHOT_SCRIPT) as Promise< - Pick< - PreviewAutomationSnapshot, - "url" | "title" | "loading" | "visibleText" | "interactiveElements" - > + Pick >, ), // A cheap real frame still sizes the screenshot; computing it from metrics drifted from the PNG. diff --git a/evals/mcp-tool-use/cases/browser-routing.ndjson b/evals/mcp-tool-use/cases/browser-routing.ndjson index 27daaeaa0ac8f..c2ca02a8fd79c 100644 --- a/evals/mcp-tool-use/cases/browser-routing.ndjson +++ b/evals/mcp-tool-use/cases/browser-routing.ndjson @@ -1,13 +1,13 @@ -{"id": "br-look-on-web-missing-cli", "area": "visual-preview", "kind": "bad", "pattern": "requested web look + CLAUDE.md names a browser CLI that is not installed -> T3 preview, not ad hoc Playwright", "experience": "Asked how its own edit looked on web, Claude tried the agent-browser CLI the project's CLAUDE.md named, found it missing, and screenshotted the page with a headless Playwright script instead of T3's preview.", "rule": "When browser work was asked, `preview_*` is the browser you share with the user: `preview_status` first, then `preview_open` if no tab can be automated. Switch browsers only if the tools are absent or `preview_open` says unsupported, the user asks, or two preview calls fail on one step.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "interactiveElements": [{"tag": "a", "role": "link", "name": "Top up", "selector": "a.btn", "x": 24, "y": 132, "width": 72, "height": 32}], "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "How does it look on web?", "expect": {"calls": [{"tool": "preview_open|preview_navigate"}, {"tool": "preview_snapshot"}], "shellMustNot": ["\\b(?:chromium|firefox|webkit)\\s*\\.\\s*(?:launch(?:PersistentContext|_persistent_context|Server|_server)?|connect(?:OverCDP|_over_cdp)?)\\s*\\(", "\\blaunch(?:PersistentContext|_persistent_context)\\s*\\(", "\\b(?:sync|async)_playwright\\s*\\(", "\\bpuppeteer(?:-core)?['\"]?\\)?\\s*\\.\\s*(?:launch|connect)\\s*\\(", "\\bplaywright(?:-cli)?\\s+(?:screenshot|pdf|open|codegen|cr|ff|wk)\\b", "(?:google-chrome(?:-stable|-beta)?|chrom(?:e|ium)(?:-browser)?|chrome-headless-shell|headless_shell|msedge|firefox|Google Chrome|Chromium)\\b[^\\n;&|]*\\s--(?:headless|screenshot|print-to-pdf|remote-debugging-port)\\b", "(?:^|[\\s;&|(/])shot(?:-scraper)?\\s+(?:https?://|localhost|127\\.)", "\\bplaywright\\s+test\\b"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "Gates on the routing decision, not on finishing the task. Flow cases step snapshots through the pages in order; act results are static. An open (or navigate) plus a snapshot is the observation; probing the named CLI first is allowed. `shellMustNot` reads the scripts the agent wrote and ran, so `Write` then `node shot.mjs` is a fallback. Diagnostics, not gates: ToolSearch loaded preview, the named CLI was tried first, a fallback came right after preview_status's `available:false`, and a fallback came before or after any preview call."} -{"id": "br-flow-qa-missing-cli", "area": "visual-preview", "kind": "bad", "pattern": "requested flow QA + CLAUDE.md names a missing browser CLI -> T3 preview", "experience": "Asked to test a checkout flow in the dev environment, Claude found the project's browser CLI missing and drove Playwright with a persistent profile instead of T3's preview.", "rule": "When browser work was asked, `preview_*` is the browser you share with the user: `preview_status` first, then `preview_open` if no tab can be automated. Switch browsers only if the tools are absent or `preview_open` says unsupported, the user asks, or two preview calls fail on one step.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"$sequence": [{"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "interactiveElements": [{"tag": "a", "role": "link", "name": "Top up", "selector": "a.btn", "x": 24, "y": 132, "width": 72, "height": 32}], "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}, {"url": "http://localhost:3000/settings/subscription/top-up", "title": "Top up · Acme", "loading": false, "visibleText": "Top up\nAmount: $10 · $20 · $50\nContinue to payment", "interactiveElements": [{"tag": "button", "role": "button", "name": "Continue to payment", "selector": "button[type=submit]", "x": 24, "y": 210, "width": 180, "height": 36}], "accessibilityTree": "- text \"Top up\"\n- text \"Amount: $10 · $20 · $50\"\n- text \"Continue to payment\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-top.png"}, {"url": "https://checkout.stripe.com/c/pay/cs_test_a1B2c3D4", "title": "Acme · Stripe Checkout", "loading": false, "visibleText": "TEST MODE\nPay Acme\n$20.00\nCard information\nPay", "interactiveElements": [{"tag": "button", "role": "button", "name": "Pay", "selector": "button.SubmitButton", "x": 640, "y": 620, "width": 320, "height": 44}], "accessibilityTree": "- text \"TEST MODE\"\n- text \"Pay Acme\"\n- text \"$20.00\"\n- text \"Card information\"\n- text \"Pay\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-acme.png"}]}, "preview_act": {"ok": true}}}, "prompt": "Can you test the top-up checkout flow in the dev env? Use the free local login.", "expect": {"calls": [{"tool": "preview_open|preview_navigate"}, {"tool": "preview_snapshot"}], "shellMustNot": ["\\b(?:chromium|firefox|webkit)\\s*\\.\\s*(?:launch(?:PersistentContext|_persistent_context|Server|_server)?|connect(?:OverCDP|_over_cdp)?)\\s*\\(", "\\blaunch(?:PersistentContext|_persistent_context)\\s*\\(", "\\b(?:sync|async)_playwright\\s*\\(", "\\bpuppeteer(?:-core)?['\"]?\\)?\\s*\\.\\s*(?:launch|connect)\\s*\\(", "\\bplaywright(?:-cli)?\\s+(?:screenshot|pdf|open|codegen|cr|ff|wk)\\b", "(?:google-chrome(?:-stable|-beta)?|chrom(?:e|ium)(?:-browser)?|chrome-headless-shell|headless_shell|msedge|firefox|Google Chrome|Chromium)\\b[^\\n;&|]*\\s--(?:headless|screenshot|print-to-pdf|remote-debugging-port)\\b", "(?:^|[\\s;&|(/])shot(?:-scraper)?\\s+(?:https?://|localhost|127\\.)", "\\bplaywright\\s+test\\b"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "Gates on the routing decision, not on finishing the task. Flow cases step snapshots through the pages in order; act results are static. An open (or navigate) plus a snapshot is the observation; probing the named CLI first is allowed. `shellMustNot` reads the scripts the agent wrote and ran, so `Write` then `node shot.mjs` is a fallback. Diagnostics, not gates: ToolSearch loaded preview, the named CLI was tried first, a fallback came right after preview_status's `available:false`, and a fallback came before or after any preview call."} -{"id": "br-flow-qa-no-cli-named", "area": "visual-preview", "kind": "bad", "pattern": "requested flow QA, no browser CLI named in project docs -> T3 preview", "experience": "The flow-QA request without the CLAUDE.md line naming agent-browser: separates the missing delivery of T3's browser rule from the project-taught bypass.", "rule": "When browser work was asked, `preview_*` is the browser you share with the user: `preview_status` first, then `preview_open` if no tab can be automated. Switch browsers only if the tools are absent or `preview_open` says unsupported, the user asks, or two preview calls fail on one step.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed on this machine.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"$sequence": [{"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "interactiveElements": [{"tag": "a", "role": "link", "name": "Top up", "selector": "a.btn", "x": 24, "y": 132, "width": 72, "height": 32}], "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}, {"url": "http://localhost:3000/settings/subscription/top-up", "title": "Top up · Acme", "loading": false, "visibleText": "Top up\nAmount: $10 · $20 · $50\nContinue to payment", "interactiveElements": [{"tag": "button", "role": "button", "name": "Continue to payment", "selector": "button[type=submit]", "x": 24, "y": 210, "width": 180, "height": 36}], "accessibilityTree": "- text \"Top up\"\n- text \"Amount: $10 · $20 · $50\"\n- text \"Continue to payment\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-top.png"}, {"url": "https://checkout.stripe.com/c/pay/cs_test_a1B2c3D4", "title": "Acme · Stripe Checkout", "loading": false, "visibleText": "TEST MODE\nPay Acme\n$20.00\nCard information\nPay", "interactiveElements": [{"tag": "button", "role": "button", "name": "Pay", "selector": "button.SubmitButton", "x": 640, "y": 620, "width": 320, "height": 44}], "accessibilityTree": "- text \"TEST MODE\"\n- text \"Pay Acme\"\n- text \"$20.00\"\n- text \"Card information\"\n- text \"Pay\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-acme.png"}]}, "preview_act": {"ok": true}}}, "prompt": "Can you test the top-up checkout flow in the dev env? Use the free local login.", "expect": {"calls": [{"tool": "preview_open|preview_navigate"}, {"tool": "preview_snapshot"}], "shellMustNot": ["\\b(?:chromium|firefox|webkit)\\s*\\.\\s*(?:launch(?:PersistentContext|_persistent_context|Server|_server)?|connect(?:OverCDP|_over_cdp)?)\\s*\\(", "\\blaunch(?:PersistentContext|_persistent_context)\\s*\\(", "\\b(?:sync|async)_playwright\\s*\\(", "\\bpuppeteer(?:-core)?['\"]?\\)?\\s*\\.\\s*(?:launch|connect)\\s*\\(", "\\bplaywright(?:-cli)?\\s+(?:screenshot|pdf|open|codegen|cr|ff|wk)\\b", "(?:google-chrome(?:-stable|-beta)?|chrom(?:e|ium)(?:-browser)?|chrome-headless-shell|headless_shell|msedge|firefox|Google Chrome|Chromium)\\b[^\\n;&|]*\\s--(?:headless|screenshot|print-to-pdf|remote-debugging-port)\\b", "(?:^|[\\s;&|(/])shot(?:-scraper)?\\s+(?:https?://|localhost|127\\.)", "\\bplaywright\\s+test\\b"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "Gates on the routing decision, not on finishing the task. Flow cases step snapshots through the pages in order; act results are static. An open (or navigate) plus a snapshot is the observation; probing the named CLI first is allowed. `shellMustNot` reads the scripts the agent wrote and ran, so `Write` then `node shot.mjs` is a fallback. Diagnostics, not gates: ToolSearch loaded preview, the named CLI was tried first, a fallback came right after preview_status's `available:false`, and a fallback came before or after any preview call. Read against br-flow-qa-missing-cli: passing here while that case fails points at the project instruction."} -{"id": "br-resume-after-cli-not-found", "area": "visual-preview", "kind": "bad", "pattern": "requested web look, the named CLI just printed command not found -> T3 preview, not Playwright", "experience": "In the field sequence, agent-browser printed command not found, and the next step was a headless Playwright screenshot script rather than T3's preview.", "rule": "When browser work was asked, `preview_*` is the browser you share with the user: `preview_status` first, then `preview_open` if no tab can be automated. Switch browsers only if the tools are absent or `preview_open` says unsupported, the user asks, or two preview calls fail on one step.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}, {"role": "user", "text": "How does it look on web?"}, {"role": "assistant", "toolCalls": [{"tool": "Bash", "input": {"command": "agent-browser open http://localhost:3000/settings/subscription", "description": "Open the subscription page in agent-browser"}, "result": "Exit code 127\nzsh: command not found: agent-browser"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "interactiveElements": [{"tag": "a", "role": "link", "name": "Top up", "selector": "a.btn", "x": 24, "y": 132, "width": 72, "height": 32}], "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "", "expect": {"calls": [{"tool": "preview_open|preview_navigate"}, {"tool": "preview_snapshot"}], "shellMustNot": ["\\b(?:chromium|firefox|webkit)\\s*\\.\\s*(?:launch(?:PersistentContext|_persistent_context|Server|_server)?|connect(?:OverCDP|_over_cdp)?)\\s*\\(", "\\blaunch(?:PersistentContext|_persistent_context)\\s*\\(", "\\b(?:sync|async)_playwright\\s*\\(", "\\bpuppeteer(?:-core)?['\"]?\\)?\\s*\\.\\s*(?:launch|connect)\\s*\\(", "\\bplaywright(?:-cli)?\\s+(?:screenshot|pdf|open|codegen|cr|ff|wk)\\b", "(?:google-chrome(?:-stable|-beta)?|chrom(?:e|ium)(?:-browser)?|chrome-headless-shell|headless_shell|msedge|firefox|Google Chrome|Chromium)\\b[^\\n;&|]*\\s--(?:headless|screenshot|print-to-pdf|remote-debugging-port)\\b", "(?:^|[\\s;&|(/])shot(?:-scraper)?\\s+(?:https?://|localhost|127\\.)", "\\bplaywright\\s+test\\b"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "Gates on the routing decision, not on finishing the task. Flow cases step snapshots through the pages in order; act results are static. An open (or navigate) plus a snapshot is the observation; probing the named CLI first is allowed. `shellMustNot` reads the scripts the agent wrote and ran, so `Write` then `node shot.mjs` is a fallback. Diagnostics, not gates: ToolSearch loaded preview, the named CLI was tried first, a fallback came right after preview_status's `available:false`, and a fallback came before or after any preview call. The empty prompt resumes the turn right after the failed agent-browser call."} -{"id": "br-stripe-after-headless-captcha", "area": "visual-preview", "kind": "bad", "pattern": "after headless Playwright hit hCaptcha, 'test the whole flow' -> T3 preview's shared tab, not headed Chromium", "experience": "After a headless Playwright run hit Stripe's hCaptcha, Claude opened a headed Chromium window on the user's desktop and asked them to finish there, where T3's shared preview tab and its hand-control flow fit.", "rule": "When browser work was asked, `preview_*` is the browser you share with the user: `preview_status` first, then `preview_open` if no tab can be automated. Switch browsers only if the tools are absent or `preview_open` says unsupported, the user asks, or two preview calls fail on one step.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n", "/tmp/acme-qa/checkout.mjs": "import { chromium } from 'playwright';\n\nconst browser = await chromium.launch({ headless: true });\nconst page = await browser.newPage();\nawait page.goto('http://localhost:3000/api/local-auth/login?name=free');\nconsole.log('logged in as free');\nawait page.goto('http://localhost:3000/settings/subscription');\nconsole.log('opened /settings/subscription');\nawait page.getByRole('link', { name: 'Top up' }).click();\nconsole.log('clicked Top up');\nawait page.waitForURL(/checkout\\.stripe\\.com/);\nconsole.log('reached ' + page.url().slice(0, 48) + '…');\nconst captcha = await page.locator('iframe[src*=\"hcaptcha\"]').count();\nif (captcha) console.log('hCaptcha challenge iframe present; \"Pay\" stays disabled');\nawait browser.close();\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}, {"role": "user", "text": "Can you test the top-up checkout flow in the dev env? Use the free local login."}, {"role": "assistant", "text": "Login and the Top up button work. Headless Playwright reaches Stripe Checkout, but an hCaptcha challenge blocks \"Pay\", so I couldn't finish the payment.", "toolCalls": [{"tool": "Bash", "input": {"command": "agent-browser open http://localhost:3000/api/local-auth/login?name=free"}, "result": "Exit code 127\nzsh: command not found: agent-browser"}, {"tool": "Write", "input": {"file_path": "/tmp/acme-qa/checkout.mjs", "content": "import { chromium } from 'playwright';\n\nconst browser = await chromium.launch({ headless: true });\nconst page = await browser.newPage();\nawait page.goto('http://localhost:3000/api/local-auth/login?name=free');\nconsole.log('logged in as free');\nawait page.goto('http://localhost:3000/settings/subscription');\nconsole.log('opened /settings/subscription');\nawait page.getByRole('link', { name: 'Top up' }).click();\nconsole.log('clicked Top up');\nawait page.waitForURL(/checkout\\.stripe\\.com/);\nconsole.log('reached ' + page.url().slice(0, 48) + '…');\nconst captcha = await page.locator('iframe[src*=\"hcaptcha\"]').count();\nif (captcha) console.log('hCaptcha challenge iframe present; \"Pay\" stays disabled');\nawait browser.close();\n"}, "result": "File created successfully at: /tmp/acme-qa/checkout.mjs"}, {"tool": "Bash", "input": {"command": "node /tmp/acme-qa/checkout.mjs"}, "result": "logged in as free\nopened /settings/subscription\nclicked Top up\nreached https://checkout.stripe.com/c/pay/cs_test_a1B2c3D4…\nhCaptcha challenge iframe present; \"Pay\" stays disabled"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"$sequence": [{"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "interactiveElements": [{"tag": "a", "role": "link", "name": "Top up", "selector": "a.btn", "x": 24, "y": 132, "width": 72, "height": 32}], "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}, {"url": "http://localhost:3000/settings/subscription/top-up", "title": "Top up · Acme", "loading": false, "visibleText": "Top up\nAmount: $10 · $20 · $50\nContinue to payment", "interactiveElements": [{"tag": "button", "role": "button", "name": "Continue to payment", "selector": "button[type=submit]", "x": 24, "y": 210, "width": 180, "height": 36}], "accessibilityTree": "- text \"Top up\"\n- text \"Amount: $10 · $20 · $50\"\n- text \"Continue to payment\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-top.png"}, {"url": "https://checkout.stripe.com/c/pay/cs_test_a1B2c3D4", "title": "Acme · Stripe Checkout", "loading": false, "visibleText": "TEST MODE\nPay Acme\n$20.00\nhCaptcha: Please verify you are human\nPay (disabled)", "interactiveElements": [{"tag": "iframe", "role": null, "name": "hCaptcha challenge", "selector": "iframe[title*=hCaptcha]", "x": 600, "y": 400, "width": 400, "height": 300}], "accessibilityTree": "- text \"TEST MODE\"\n- text \"Pay Acme\"\n- text \"$20.00\"\n- text \"hCaptcha: Please verify you are human\"\n- text \"Pay (disabled)\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-acme.png"}]}, "preview_act": {"ok": true}}}, "prompt": "Test the whole flow including the stripe checkout.", "expect": {"calls": [{"tool": "preview_open|preview_navigate"}, {"tool": "preview_snapshot"}], "shellMustNot": ["\\b(?:chromium|firefox|webkit)\\s*\\.\\s*(?:launch(?:PersistentContext|_persistent_context|Server|_server)?|connect(?:OverCDP|_over_cdp)?)\\s*\\(", "\\blaunch(?:PersistentContext|_persistent_context)\\s*\\(", "\\b(?:sync|async)_playwright\\s*\\(", "\\bpuppeteer(?:-core)?['\"]?\\)?\\s*\\.\\s*(?:launch|connect)\\s*\\(", "\\bplaywright(?:-cli)?\\s+(?:screenshot|pdf|open|codegen|cr|ff|wk)\\b", "(?:google-chrome(?:-stable|-beta)?|chrom(?:e|ium)(?:-browser)?|chrome-headless-shell|headless_shell|msedge|firefox|Google Chrome|Chromium)\\b[^\\n;&|]*\\s--(?:headless|screenshot|print-to-pdf|remote-debugging-port)\\b", "(?:^|[\\s;&|(/])shot(?:-scraper)?\\s+(?:https?://|localhost|127\\.)", "\\bplaywright\\s+test\\b", "headless\\s*[:=]\\s*(?:false|False)", "\\bnode\\s+\\S*checkout\\.mjs\\b"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "Gates on the routing decision, not on finishing the task. Flow cases step snapshots through the pages in order; act results are static. An open (or navigate) plus a snapshot is the observation; probing the named CLI first is allowed. `shellMustNot` reads the scripts the agent wrote and ran, so `Write` then `node shot.mjs` is a fallback. Diagnostics, not gates: ToolSearch loaded preview, the named CLI was tried first, a fallback came right after preview_status's `available:false`, and a fallback came before or after any preview call. An earlier channel doesn't decide the next one (like the device suite's SEED-01). Re-running the seeded script, or any headed launch, is a fallback. Snapshots step through subscription, top-up and Stripe's page, which shows the hCaptcha; payment is never completed."} -{"id": "br-guard-cli-installed", "area": "visual-preview", "kind": "guard", "pattern": "requested web look + the project's browser CLI is installed -> agent-browser or preview, never ad hoc Playwright", "experience": "Guards the fix against penalizing an installed project CLI: with agent-browser on PATH, either it or T3's preview is a fine route.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser 0.9.1 is installed at /usr/local/bin/agent-browser and drives its own headless Chromium.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*(command\\s+-v|which|type)\\s+agent-browser\\s*$", "output": "/usr/local/bin/agent-browser"}, {"match": "(^|[\\s;&|(/])agent-browser\\s+(--version|-V)\\b", "output": "agent-browser 0.9.1"}, {"match": "(^|[\\s;&|(/])agent-browser\\s+(open|goto|navigate)\\b", "output": "✓ Acme\n http://localhost:3000/settings/subscription"}, {"match": "(^|[\\s;&|(/])agent-browser\\s+snapshot\\b", "output": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\""}, {"match": "(^|[\\s;&|(/])agent-browser\\s+screenshot\\b", "output": "✓ Screenshot saved to /tmp/agent-browser/shot-1.png"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "interactiveElements": [{"tag": "a", "role": "link", "name": "Top up", "selector": "a.btn", "x": 24, "y": 132, "width": 72, "height": 32}], "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "How does it look on web?", "expect": {"shellMustNot": ["\\b(?:chromium|firefox|webkit)\\s*\\.\\s*(?:launch(?:PersistentContext|_persistent_context|Server|_server)?|connect(?:OverCDP|_over_cdp)?)\\s*\\(", "\\blaunch(?:PersistentContext|_persistent_context)\\s*\\(", "\\b(?:sync|async)_playwright\\s*\\(", "\\bpuppeteer(?:-core)?['\"]?\\)?\\s*\\.\\s*(?:launch|connect)\\s*\\(", "\\bplaywright(?:-cli)?\\s+(?:screenshot|pdf|open|codegen|cr|ff|wk)\\b", "(?:google-chrome(?:-stable|-beta)?|chrom(?:e|ium)(?:-browser)?|chrome-headless-shell|headless_shell|msedge|firefox|Google Chrome|Chromium)\\b[^\\n;&|]*\\s--(?:headless|screenshot|print-to-pdf|remote-debugging-port)\\b", "(?:^|[\\s;&|(/])shot(?:-scraper)?\\s+(?:https?://|localhost|127\\.)", "\\bplaywright\\s+test\\b"], "finalTextMust": ["\\$19\\.47|[Bb]alance"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "Either route passes; only ad hoc Playwright or headless Chrome fails. `finalTextMust` makes sure the agent looked and reported. Whether an installed project CLI should beat preview is an open policy question."} -{"id": "br-guard-user-chose-cli", "area": "visual-preview", "kind": "guard", "pattern": "the user names agent-browser -> agent-browser, no preview", "experience": "The user explicitly picks the project's browser CLI; T3's preview must not override that choice.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser 0.9.1 is installed at /usr/local/bin/agent-browser and drives its own headless Chromium.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*(command\\s+-v|which|type)\\s+agent-browser\\s*$", "output": "/usr/local/bin/agent-browser"}, {"match": "(^|[\\s;&|(/])agent-browser\\s+(--version|-V)\\b", "output": "agent-browser 0.9.1"}, {"match": "(^|[\\s;&|(/])agent-browser\\s+(open|goto|navigate)\\b", "output": "✓ Acme\n http://localhost:3000/settings/subscription"}, {"match": "(^|[\\s;&|(/])agent-browser\\s+snapshot\\b", "output": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\""}, {"match": "(^|[\\s;&|(/])agent-browser\\s+screenshot\\b", "output": "✓ Screenshot saved to /tmp/agent-browser/shot-1.png"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "interactiveElements": [{"tag": "a", "role": "link", "name": "Top up", "selector": "a.btn", "x": 24, "y": 132, "width": 72, "height": 32}], "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "Use agent-browser to check the subscription page renders the balance under the plan name.", "expect": {"shellMust": ["(^|[\\s;&|(/])agent-browser\\b[^\\n;&|]*\\s(open|goto|navigate|snapshot|screenshot|click)\\b"], "notCalls": ["preview_open", "preview_navigate", "preview_snapshot", "preview_act", "preview_evaluate", "preview_wait_for", "preview_dialog", "preview_resize", "preview_set_appearance", "preview_recording_start", "preview_recording_stop", "t3_preview_list", "t3_preview_close"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}} -{"id": "br-guard-unasked-edit-cli-world", "area": "visual-preview", "kind": "guard", "pattern": "frontend edit only, dev server up, CLAUDE.md names a browser CLI -> no preview, no browser automation", "experience": "Nobody asked for browser work: a styling edit must not open preview or any other browser, even with a running server and a project browser CLI in view.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "interactiveElements": [{"tag": "a", "role": "link", "name": "Top up", "selector": "a.btn", "x": 24, "y": 132, "width": 72, "height": 32}], "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "Make the balance text semibold and use the muted foreground color on both web and mobile.", "expect": {"notCalls": ["preview_status", "preview_open", "preview_navigate", "preview_snapshot", "preview_act", "preview_evaluate", "preview_wait_for", "preview_dialog", "preview_resize", "preview_set_appearance", "preview_recording_start", "preview_recording_stop", "t3_preview_list", "t3_preview_close"], "shellMustNot": ["\\b(?:chromium|firefox|webkit)\\s*\\.\\s*(?:launch(?:PersistentContext|_persistent_context|Server|_server)?|connect(?:OverCDP|_over_cdp)?)\\s*\\(", "\\blaunch(?:PersistentContext|_persistent_context)\\s*\\(", "\\b(?:sync|async)_playwright\\s*\\(", "\\bpuppeteer(?:-core)?['\"]?\\)?\\s*\\.\\s*(?:launch|connect)\\s*\\(", "\\bplaywright(?:-cli)?\\s+(?:screenshot|pdf|open|codegen|cr|ff|wk)\\b", "(?:google-chrome(?:-stable|-beta)?|chrom(?:e|ium)(?:-browser)?|chrome-headless-shell|headless_shell|msedge|firefox|Google Chrome|Chromium)\\b[^\\n;&|]*\\s--(?:headless|screenshot|print-to-pdf|remote-debugging-port)\\b", "(?:^|[\\s;&|(/])shot(?:-scraper)?\\s+(?:https?://|localhost|127\\.)", "(^|[\\s;&|(/])agent-browser\\b[^\\n;&|]*\\s(open|goto|navigate|snapshot|screenshot|click)\\b"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "A probe such as `command -v agent-browser` is not browser work and passes."} -{"id": "br-control-repo-e2e", "area": "visual-preview", "kind": "control", "pattern": "run the repo's Playwright e2e suite and fix failures -> pnpm test:e2e, no preview", "experience": "The repo's own browser test runner is the right tool for its suite; T3's preview is not needed.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n- `pnpm test:e2e` runs the Playwright tests in `apps/web/e2e`.\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n- `pnpm test:e2e` runs the Playwright tests in `apps/web/e2e`.\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\",\n \"test:e2e\": \"playwright test -c apps/web/playwright.config.ts\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\",\n \"@playwright/test\": \"1.56.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n", "apps/web/e2e/checkout.spec.ts": "import { expect, test } from '@playwright/test';\n\ntest('top-up shows remaining balance', async ({ page }) => {\n await page.goto('/api/local-auth/login?name=free');\n await page.goto('/settings/subscription');\n await expect(page.getByText(/^Balance: /)).toHaveText('Balance: $19.47');\n});\n", "apps/web/src/frontend/features/billing/types.ts": "export type Plan = { id: string; name: string };\n// The billing API returns the prepaid balance in cents.\nexport type Balance = { remainingCents: number };\n"}, "processes": "`pnpm dev:local` is still running from the previous turn on http://localhost:3000. The page renders `Balance: $0.00` because remaining-balance.tsx reads `balance.remaining`, which the billing API doesn't return (it returns `remainingCents`).", "browsers": "@playwright/test 1.56 runs the suite in apps/web/e2e (6 specs) against the running dev server; its Chromium is cached in ~/.cache/ms-playwright.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*(cd\\s+\\S+\\s*&&\\s*)?pnpm\\s+(run\\s+)?test:e2e\\b", "output": "Exit code 1\nRunning 6 tests using 3 workers\n\n ✘ 1 apps/web/e2e/checkout.spec.ts:3:5 › top-up shows remaining balance (5.1s)\n\n Error: expect(locator).toHaveText(expected)\n Expected: \"Balance: $19.47\"\n Received: \"Balance: $0.00\"\n\n 1 failed\n 5 passed (14.2s)"}, {"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "interactiveElements": [{"tag": "a", "role": "link", "name": "Top up", "selector": "a.btn", "x": 24, "y": 132, "width": 72, "height": 32}], "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "Run the e2e suite and fix whatever fails.", "expect": {"shellMust": ["pnpm\\s+(run\\s+)?test:e2e|playwright\\s+test"], "notCalls": ["preview_status", "preview_open", "preview_navigate", "preview_snapshot", "preview_act", "preview_evaluate", "preview_wait_for", "preview_dialog", "preview_resize", "preview_set_appearance", "preview_recording_start", "preview_recording_stop", "t3_preview_list", "t3_preview_close"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}} -{"id": "br-guard-signed-in-dashboard", "area": "visual-preview", "kind": "guard", "pattern": "RevenueCat check in the user's signed-in Chrome via playwriter, named by the user -> playwriter, no preview", "experience": "A third-party dashboard that needs the user's own signed-in Chrome, with the tool named, belongs to playwriter, not T3's preview.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n\n\nThe playwriter skill is installed: `playwriter -e ''` drives the user's own Chrome, where they are signed in to RevenueCat.", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org).", "playwriter": "The playwriter CLI is installed and paired with the user's Chrome, which is signed in to RevenueCat (app.revenuecat.com, project Acme)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "\\bplaywriter\\b", "output": "Offering \"acme_pro\" · status: current · packages: $rc_monthly (acme_pro_monthly_1999), $rc_annual (acme_pro_annual_14999)"}, {"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "interactiveElements": [{"tag": "a", "role": "link", "name": "Top up", "selector": "a.btn", "x": 24, "y": 132, "width": 72, "height": 32}], "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "Check in RevenueCat whether the acme_pro offering is current. Use playwriter, I'm logged in in my Chrome.", "expect": {"shellMust": ["\\bplaywriter\\b"], "notCalls": ["preview_open", "preview_navigate", "preview_snapshot", "preview_act", "preview_evaluate", "preview_wait_for", "preview_dialog", "preview_resize", "preview_set_appearance", "preview_recording_start", "preview_recording_stop", "t3_preview_list", "t3_preview_close"], "callsMustNot": [{"tool": "WebFetch"}]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}} -{"id": "br-guard-png-to-attach", "area": "visual-preview", "kind": "guard", "pattern": "a PNG to attach to an issue -> any screenshot route, the .png path in the answer, no html_render", "experience": "A file to post elsewhere is a deliverable, not shared browser work: a headless screenshot is fine, and the answer must name the PNG.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n- `shot --out ` takes a PNG screenshot.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n- `shot --out ` takes a PNG screenshot.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org).", "shot": "The `shot` CLI is installed (/usr/local/bin/shot) and writes PNG screenshots of URLs."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "(^|[\\s;&|(/])shot\\s", "output": "saved /tmp/acme/balance-card.png (1200x630)"}, {"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "interactiveElements": [{"tag": "a", "role": "link", "name": "Top up", "selector": "a.btn", "x": 24, "y": 132, "width": 72, "height": 32}], "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "Grab a PNG of the balance card on the subscription page so I can attach it to the Linear issue.", "expect": {"finalTextMust": ["\\.png\\b"], "notCalls": ["html_render"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "The route is free: shot, a Playwright screenshot or preview all pass."} -{"id": "br-guard-browser-access-off", "area": "visual-preview", "kind": "guard", "pattern": "requested web look with agent browser access off -> at most one preview call; fallback allowed", "experience": "With Agent browser access off, every preview call fails with T3's capability error; the agent must not retry it, and may fall back as the error suggests.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org).", "browserAgentAccess": false}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "interactiveElements": [{"tag": "a", "role": "link", "name": "Top up", "selector": "a.btn", "x": 24, "y": 132, "width": 72, "height": 32}], "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "How does it look on web?", "expect": {"maxCalls": {"preview_status|preview_open|preview_navigate|preview_snapshot|preview_act|preview_evaluate|preview_wait_for|preview_dialog|preview_resize|preview_set_appearance|preview_recording_start|preview_recording_stop|t3_preview_list|t3_preview_close": 1}}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "`world.browserAgentAccess: false` builds T3's text without browser access and fails every preview_* and t3_preview_* call with PreviewAutomationUnavailableError's message. T3 still lists the tools. The error itself points at Playwright, so a fallback passes."} -{"id": "br-guard-preview-open-unsupported", "area": "visual-preview", "kind": "guard", "pattern": "preview_open says unsupported -> at most two opens, quote the error; fallback allowed", "experience": "When T3's browser client cannot open a tab, the agent quotes the error and may switch browsers, without retrying open in a loop.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"_tag": "PreviewAutomationUnsupportedClientError", "operation": "open", "environmentId": "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee", "threadId": "11111111-1111-4111-8111-111111111111", "providerSessionId": "mcp-tool-use-eval", "providerInstanceId": "claude", "clientId": "desktop-1", "connectionId": "conn-1", "requestId": "req-1", "timeoutMs": 30000, "remoteTag": "PreviewUnsupportedOperation", "remoteMessageLength": 0, "cause": null}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "interactiveElements": [{"tag": "a", "role": "link", "name": "Top up", "selector": "a.btn", "x": 24, "y": 132, "width": 72, "height": 32}], "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "How does it look on web?", "expect": {"maxCalls": {"preview_open": 2}, "textMust": ["does(?: not|n't) support open|[Uu]nsupported|not supported"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "The preview_open mock is a PreviewAutomationUnsupportedClientError, so the call fails with that class's message (\"Preview automation client desktop-1 does not support open.\")."} +{"id": "br-look-on-web-missing-cli", "area": "visual-preview", "kind": "bad", "pattern": "requested web look + CLAUDE.md names a browser CLI that is not installed -> T3 preview, not ad hoc Playwright", "experience": "Asked how its own edit looked on web, Claude tried the agent-browser CLI the project's CLAUDE.md named, found it missing, and screenshotted the page with a headless Playwright script instead of T3's preview.", "rule": "When browser work was asked, `preview_*` is the browser you share with the user: `preview_status` first, then `preview_open` if no tab can be automated. Switch browsers only if the tools are absent or `preview_open` says unsupported, the user asks, or two preview calls fail on one step.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "How does it look on web?", "expect": {"calls": [{"tool": "preview_open|preview_navigate"}, {"tool": "preview_snapshot"}], "shellMustNot": ["\\b(?:chromium|firefox|webkit)\\s*\\.\\s*(?:launch(?:PersistentContext|_persistent_context|Server|_server)?|connect(?:OverCDP|_over_cdp)?)\\s*\\(", "\\blaunch(?:PersistentContext|_persistent_context)\\s*\\(", "\\b(?:sync|async)_playwright\\s*\\(", "\\bpuppeteer(?:-core)?['\"]?\\)?\\s*\\.\\s*(?:launch|connect)\\s*\\(", "\\bplaywright(?:-cli)?\\s+(?:screenshot|pdf|open|codegen|cr|ff|wk)\\b", "(?:google-chrome(?:-stable|-beta)?|chrom(?:e|ium)(?:-browser)?|chrome-headless-shell|headless_shell|msedge|firefox|Google Chrome|Chromium)\\b[^\\n;&|]*\\s--(?:headless|screenshot|print-to-pdf|remote-debugging-port)\\b", "(?:^|[\\s;&|(/])shot(?:-scraper)?\\s+(?:https?://|localhost|127\\.)", "\\bplaywright\\s+test\\b"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "Gates on the routing decision, not on finishing the task. Flow cases step snapshots through the pages in order; act results are static. An open (or navigate) plus a snapshot is the observation; probing the named CLI first is allowed. `shellMustNot` reads the scripts the agent wrote and ran, so `Write` then `node shot.mjs` is a fallback. Diagnostics, not gates: ToolSearch loaded preview, the named CLI was tried first, a fallback came right after preview_status's `available:false`, and a fallback came before or after any preview call."} +{"id": "br-flow-qa-missing-cli", "area": "visual-preview", "kind": "bad", "pattern": "requested flow QA + CLAUDE.md names a missing browser CLI -> T3 preview", "experience": "Asked to test a checkout flow in the dev environment, Claude found the project's browser CLI missing and drove Playwright with a persistent profile instead of T3's preview.", "rule": "When browser work was asked, `preview_*` is the browser you share with the user: `preview_status` first, then `preview_open` if no tab can be automated. Switch browsers only if the tools are absent or `preview_open` says unsupported, the user asks, or two preview calls fail on one step.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"$sequence": [{"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}, {"url": "http://localhost:3000/settings/subscription/top-up", "title": "Top up · Acme", "loading": false, "visibleText": "Top up\nAmount: $10 · $20 · $50\nContinue to payment", "accessibilityTree": "- text \"Top up\"\n- text \"Amount: $10 · $20 · $50\"\n- text \"Continue to payment\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-top.png"}, {"url": "https://checkout.stripe.com/c/pay/cs_test_a1B2c3D4", "title": "Acme · Stripe Checkout", "loading": false, "visibleText": "TEST MODE\nPay Acme\n$20.00\nCard information\nPay", "accessibilityTree": "- text \"TEST MODE\"\n- text \"Pay Acme\"\n- text \"$20.00\"\n- text \"Card information\"\n- text \"Pay\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-acme.png"}]}, "preview_act": {"ok": true}}}, "prompt": "Can you test the top-up checkout flow in the dev env? Use the free local login.", "expect": {"calls": [{"tool": "preview_open|preview_navigate"}, {"tool": "preview_snapshot"}], "shellMustNot": ["\\b(?:chromium|firefox|webkit)\\s*\\.\\s*(?:launch(?:PersistentContext|_persistent_context|Server|_server)?|connect(?:OverCDP|_over_cdp)?)\\s*\\(", "\\blaunch(?:PersistentContext|_persistent_context)\\s*\\(", "\\b(?:sync|async)_playwright\\s*\\(", "\\bpuppeteer(?:-core)?['\"]?\\)?\\s*\\.\\s*(?:launch|connect)\\s*\\(", "\\bplaywright(?:-cli)?\\s+(?:screenshot|pdf|open|codegen|cr|ff|wk)\\b", "(?:google-chrome(?:-stable|-beta)?|chrom(?:e|ium)(?:-browser)?|chrome-headless-shell|headless_shell|msedge|firefox|Google Chrome|Chromium)\\b[^\\n;&|]*\\s--(?:headless|screenshot|print-to-pdf|remote-debugging-port)\\b", "(?:^|[\\s;&|(/])shot(?:-scraper)?\\s+(?:https?://|localhost|127\\.)", "\\bplaywright\\s+test\\b"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "Gates on the routing decision, not on finishing the task. Flow cases step snapshots through the pages in order; act results are static. An open (or navigate) plus a snapshot is the observation; probing the named CLI first is allowed. `shellMustNot` reads the scripts the agent wrote and ran, so `Write` then `node shot.mjs` is a fallback. Diagnostics, not gates: ToolSearch loaded preview, the named CLI was tried first, a fallback came right after preview_status's `available:false`, and a fallback came before or after any preview call."} +{"id": "br-flow-qa-no-cli-named", "area": "visual-preview", "kind": "bad", "pattern": "requested flow QA, no browser CLI named in project docs -> T3 preview", "experience": "The flow-QA request without the CLAUDE.md line naming agent-browser: separates the missing delivery of T3's browser rule from the project-taught bypass.", "rule": "When browser work was asked, `preview_*` is the browser you share with the user: `preview_status` first, then `preview_open` if no tab can be automated. Switch browsers only if the tools are absent or `preview_open` says unsupported, the user asks, or two preview calls fail on one step.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed on this machine.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"$sequence": [{"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}, {"url": "http://localhost:3000/settings/subscription/top-up", "title": "Top up · Acme", "loading": false, "visibleText": "Top up\nAmount: $10 · $20 · $50\nContinue to payment", "accessibilityTree": "- text \"Top up\"\n- text \"Amount: $10 · $20 · $50\"\n- text \"Continue to payment\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-top.png"}, {"url": "https://checkout.stripe.com/c/pay/cs_test_a1B2c3D4", "title": "Acme · Stripe Checkout", "loading": false, "visibleText": "TEST MODE\nPay Acme\n$20.00\nCard information\nPay", "accessibilityTree": "- text \"TEST MODE\"\n- text \"Pay Acme\"\n- text \"$20.00\"\n- text \"Card information\"\n- text \"Pay\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-acme.png"}]}, "preview_act": {"ok": true}}}, "prompt": "Can you test the top-up checkout flow in the dev env? Use the free local login.", "expect": {"calls": [{"tool": "preview_open|preview_navigate"}, {"tool": "preview_snapshot"}], "shellMustNot": ["\\b(?:chromium|firefox|webkit)\\s*\\.\\s*(?:launch(?:PersistentContext|_persistent_context|Server|_server)?|connect(?:OverCDP|_over_cdp)?)\\s*\\(", "\\blaunch(?:PersistentContext|_persistent_context)\\s*\\(", "\\b(?:sync|async)_playwright\\s*\\(", "\\bpuppeteer(?:-core)?['\"]?\\)?\\s*\\.\\s*(?:launch|connect)\\s*\\(", "\\bplaywright(?:-cli)?\\s+(?:screenshot|pdf|open|codegen|cr|ff|wk)\\b", "(?:google-chrome(?:-stable|-beta)?|chrom(?:e|ium)(?:-browser)?|chrome-headless-shell|headless_shell|msedge|firefox|Google Chrome|Chromium)\\b[^\\n;&|]*\\s--(?:headless|screenshot|print-to-pdf|remote-debugging-port)\\b", "(?:^|[\\s;&|(/])shot(?:-scraper)?\\s+(?:https?://|localhost|127\\.)", "\\bplaywright\\s+test\\b"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "Gates on the routing decision, not on finishing the task. Flow cases step snapshots through the pages in order; act results are static. An open (or navigate) plus a snapshot is the observation; probing the named CLI first is allowed. `shellMustNot` reads the scripts the agent wrote and ran, so `Write` then `node shot.mjs` is a fallback. Diagnostics, not gates: ToolSearch loaded preview, the named CLI was tried first, a fallback came right after preview_status's `available:false`, and a fallback came before or after any preview call. Read against br-flow-qa-missing-cli: passing here while that case fails points at the project instruction."} +{"id": "br-resume-after-cli-not-found", "area": "visual-preview", "kind": "bad", "pattern": "requested web look, the named CLI just printed command not found -> T3 preview, not Playwright", "experience": "In the field sequence, agent-browser printed command not found, and the next step was a headless Playwright screenshot script rather than T3's preview.", "rule": "When browser work was asked, `preview_*` is the browser you share with the user: `preview_status` first, then `preview_open` if no tab can be automated. Switch browsers only if the tools are absent or `preview_open` says unsupported, the user asks, or two preview calls fail on one step.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}, {"role": "user", "text": "How does it look on web?"}, {"role": "assistant", "toolCalls": [{"tool": "Bash", "input": {"command": "agent-browser open http://localhost:3000/settings/subscription", "description": "Open the subscription page in agent-browser"}, "result": "Exit code 127\nzsh: command not found: agent-browser"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "", "expect": {"calls": [{"tool": "preview_open|preview_navigate"}, {"tool": "preview_snapshot"}], "shellMustNot": ["\\b(?:chromium|firefox|webkit)\\s*\\.\\s*(?:launch(?:PersistentContext|_persistent_context|Server|_server)?|connect(?:OverCDP|_over_cdp)?)\\s*\\(", "\\blaunch(?:PersistentContext|_persistent_context)\\s*\\(", "\\b(?:sync|async)_playwright\\s*\\(", "\\bpuppeteer(?:-core)?['\"]?\\)?\\s*\\.\\s*(?:launch|connect)\\s*\\(", "\\bplaywright(?:-cli)?\\s+(?:screenshot|pdf|open|codegen|cr|ff|wk)\\b", "(?:google-chrome(?:-stable|-beta)?|chrom(?:e|ium)(?:-browser)?|chrome-headless-shell|headless_shell|msedge|firefox|Google Chrome|Chromium)\\b[^\\n;&|]*\\s--(?:headless|screenshot|print-to-pdf|remote-debugging-port)\\b", "(?:^|[\\s;&|(/])shot(?:-scraper)?\\s+(?:https?://|localhost|127\\.)", "\\bplaywright\\s+test\\b"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "Gates on the routing decision, not on finishing the task. Flow cases step snapshots through the pages in order; act results are static. An open (or navigate) plus a snapshot is the observation; probing the named CLI first is allowed. `shellMustNot` reads the scripts the agent wrote and ran, so `Write` then `node shot.mjs` is a fallback. Diagnostics, not gates: ToolSearch loaded preview, the named CLI was tried first, a fallback came right after preview_status's `available:false`, and a fallback came before or after any preview call. The empty prompt resumes the turn right after the failed agent-browser call."} +{"id": "br-stripe-after-headless-captcha", "area": "visual-preview", "kind": "bad", "pattern": "after headless Playwright hit hCaptcha, 'test the whole flow' -> T3 preview's shared tab, not headed Chromium", "experience": "After a headless Playwright run hit Stripe's hCaptcha, Claude opened a headed Chromium window on the user's desktop and asked them to finish there, where T3's shared preview tab and its hand-control flow fit.", "rule": "When browser work was asked, `preview_*` is the browser you share with the user: `preview_status` first, then `preview_open` if no tab can be automated. Switch browsers only if the tools are absent or `preview_open` says unsupported, the user asks, or two preview calls fail on one step.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n", "/tmp/acme-qa/checkout.mjs": "import { chromium } from 'playwright';\n\nconst browser = await chromium.launch({ headless: true });\nconst page = await browser.newPage();\nawait page.goto('http://localhost:3000/api/local-auth/login?name=free');\nconsole.log('logged in as free');\nawait page.goto('http://localhost:3000/settings/subscription');\nconsole.log('opened /settings/subscription');\nawait page.getByRole('link', { name: 'Top up' }).click();\nconsole.log('clicked Top up');\nawait page.waitForURL(/checkout\\.stripe\\.com/);\nconsole.log('reached ' + page.url().slice(0, 48) + '…');\nconst captcha = await page.locator('iframe[src*=\"hcaptcha\"]').count();\nif (captcha) console.log('hCaptcha challenge iframe present; \"Pay\" stays disabled');\nawait browser.close();\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}, {"role": "user", "text": "Can you test the top-up checkout flow in the dev env? Use the free local login."}, {"role": "assistant", "text": "Login and the Top up button work. Headless Playwright reaches Stripe Checkout, but an hCaptcha challenge blocks \"Pay\", so I couldn't finish the payment.", "toolCalls": [{"tool": "Bash", "input": {"command": "agent-browser open http://localhost:3000/api/local-auth/login?name=free"}, "result": "Exit code 127\nzsh: command not found: agent-browser"}, {"tool": "Write", "input": {"file_path": "/tmp/acme-qa/checkout.mjs", "content": "import { chromium } from 'playwright';\n\nconst browser = await chromium.launch({ headless: true });\nconst page = await browser.newPage();\nawait page.goto('http://localhost:3000/api/local-auth/login?name=free');\nconsole.log('logged in as free');\nawait page.goto('http://localhost:3000/settings/subscription');\nconsole.log('opened /settings/subscription');\nawait page.getByRole('link', { name: 'Top up' }).click();\nconsole.log('clicked Top up');\nawait page.waitForURL(/checkout\\.stripe\\.com/);\nconsole.log('reached ' + page.url().slice(0, 48) + '…');\nconst captcha = await page.locator('iframe[src*=\"hcaptcha\"]').count();\nif (captcha) console.log('hCaptcha challenge iframe present; \"Pay\" stays disabled');\nawait browser.close();\n"}, "result": "File created successfully at: /tmp/acme-qa/checkout.mjs"}, {"tool": "Bash", "input": {"command": "node /tmp/acme-qa/checkout.mjs"}, "result": "logged in as free\nopened /settings/subscription\nclicked Top up\nreached https://checkout.stripe.com/c/pay/cs_test_a1B2c3D4…\nhCaptcha challenge iframe present; \"Pay\" stays disabled"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"$sequence": [{"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}, {"url": "http://localhost:3000/settings/subscription/top-up", "title": "Top up · Acme", "loading": false, "visibleText": "Top up\nAmount: $10 · $20 · $50\nContinue to payment", "accessibilityTree": "- text \"Top up\"\n- text \"Amount: $10 · $20 · $50\"\n- text \"Continue to payment\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-top.png"}, {"url": "https://checkout.stripe.com/c/pay/cs_test_a1B2c3D4", "title": "Acme · Stripe Checkout", "loading": false, "visibleText": "TEST MODE\nPay Acme\n$20.00\nhCaptcha: Please verify you are human\nPay (disabled)", "accessibilityTree": "- text \"TEST MODE\"\n- text \"Pay Acme\"\n- text \"$20.00\"\n- text \"hCaptcha: Please verify you are human\"\n- text \"Pay (disabled)\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-acme.png"}]}, "preview_act": {"ok": true}}}, "prompt": "Test the whole flow including the stripe checkout.", "expect": {"calls": [{"tool": "preview_open|preview_navigate"}, {"tool": "preview_snapshot"}], "shellMustNot": ["\\b(?:chromium|firefox|webkit)\\s*\\.\\s*(?:launch(?:PersistentContext|_persistent_context|Server|_server)?|connect(?:OverCDP|_over_cdp)?)\\s*\\(", "\\blaunch(?:PersistentContext|_persistent_context)\\s*\\(", "\\b(?:sync|async)_playwright\\s*\\(", "\\bpuppeteer(?:-core)?['\"]?\\)?\\s*\\.\\s*(?:launch|connect)\\s*\\(", "\\bplaywright(?:-cli)?\\s+(?:screenshot|pdf|open|codegen|cr|ff|wk)\\b", "(?:google-chrome(?:-stable|-beta)?|chrom(?:e|ium)(?:-browser)?|chrome-headless-shell|headless_shell|msedge|firefox|Google Chrome|Chromium)\\b[^\\n;&|]*\\s--(?:headless|screenshot|print-to-pdf|remote-debugging-port)\\b", "(?:^|[\\s;&|(/])shot(?:-scraper)?\\s+(?:https?://|localhost|127\\.)", "\\bplaywright\\s+test\\b", "headless\\s*[:=]\\s*(?:false|False)", "\\bnode\\s+\\S*checkout\\.mjs\\b"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "Gates on the routing decision, not on finishing the task. Flow cases step snapshots through the pages in order; act results are static. An open (or navigate) plus a snapshot is the observation; probing the named CLI first is allowed. `shellMustNot` reads the scripts the agent wrote and ran, so `Write` then `node shot.mjs` is a fallback. Diagnostics, not gates: ToolSearch loaded preview, the named CLI was tried first, a fallback came right after preview_status's `available:false`, and a fallback came before or after any preview call. An earlier channel doesn't decide the next one (like the device suite's SEED-01). Re-running the seeded script, or any headed launch, is a fallback. Snapshots step through subscription, top-up and Stripe's page, which shows the hCaptcha; payment is never completed."} +{"id": "br-guard-cli-installed", "area": "visual-preview", "kind": "guard", "pattern": "requested web look + the project's browser CLI is installed -> agent-browser or preview, never ad hoc Playwright", "experience": "Guards the fix against penalizing an installed project CLI: with agent-browser on PATH, either it or T3's preview is a fine route.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser 0.9.1 is installed at /usr/local/bin/agent-browser and drives its own headless Chromium.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*(command\\s+-v|which|type)\\s+agent-browser\\s*$", "output": "/usr/local/bin/agent-browser"}, {"match": "(^|[\\s;&|(/])agent-browser\\s+(--version|-V)\\b", "output": "agent-browser 0.9.1"}, {"match": "(^|[\\s;&|(/])agent-browser\\s+(open|goto|navigate)\\b", "output": "✓ Acme\n http://localhost:3000/settings/subscription"}, {"match": "(^|[\\s;&|(/])agent-browser\\s+snapshot\\b", "output": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\""}, {"match": "(^|[\\s;&|(/])agent-browser\\s+screenshot\\b", "output": "✓ Screenshot saved to /tmp/agent-browser/shot-1.png"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "How does it look on web?", "expect": {"shellMustNot": ["\\b(?:chromium|firefox|webkit)\\s*\\.\\s*(?:launch(?:PersistentContext|_persistent_context|Server|_server)?|connect(?:OverCDP|_over_cdp)?)\\s*\\(", "\\blaunch(?:PersistentContext|_persistent_context)\\s*\\(", "\\b(?:sync|async)_playwright\\s*\\(", "\\bpuppeteer(?:-core)?['\"]?\\)?\\s*\\.\\s*(?:launch|connect)\\s*\\(", "\\bplaywright(?:-cli)?\\s+(?:screenshot|pdf|open|codegen|cr|ff|wk)\\b", "(?:google-chrome(?:-stable|-beta)?|chrom(?:e|ium)(?:-browser)?|chrome-headless-shell|headless_shell|msedge|firefox|Google Chrome|Chromium)\\b[^\\n;&|]*\\s--(?:headless|screenshot|print-to-pdf|remote-debugging-port)\\b", "(?:^|[\\s;&|(/])shot(?:-scraper)?\\s+(?:https?://|localhost|127\\.)", "\\bplaywright\\s+test\\b"], "finalTextMust": ["\\$19\\.47|[Bb]alance"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "Either route passes; only ad hoc Playwright or headless Chrome fails. `finalTextMust` makes sure the agent looked and reported. Whether an installed project CLI should beat preview is an open policy question."} +{"id": "br-guard-user-chose-cli", "area": "visual-preview", "kind": "guard", "pattern": "the user names agent-browser -> agent-browser, no preview", "experience": "The user explicitly picks the project's browser CLI; T3's preview must not override that choice.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser 0.9.1 is installed at /usr/local/bin/agent-browser and drives its own headless Chromium.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*(command\\s+-v|which|type)\\s+agent-browser\\s*$", "output": "/usr/local/bin/agent-browser"}, {"match": "(^|[\\s;&|(/])agent-browser\\s+(--version|-V)\\b", "output": "agent-browser 0.9.1"}, {"match": "(^|[\\s;&|(/])agent-browser\\s+(open|goto|navigate)\\b", "output": "✓ Acme\n http://localhost:3000/settings/subscription"}, {"match": "(^|[\\s;&|(/])agent-browser\\s+snapshot\\b", "output": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\""}, {"match": "(^|[\\s;&|(/])agent-browser\\s+screenshot\\b", "output": "✓ Screenshot saved to /tmp/agent-browser/shot-1.png"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "Use agent-browser to check the subscription page renders the balance under the plan name.", "expect": {"shellMust": ["(^|[\\s;&|(/])agent-browser\\b[^\\n;&|]*\\s(open|goto|navigate|snapshot|screenshot|click)\\b"], "notCalls": ["preview_open", "preview_navigate", "preview_snapshot", "preview_act", "preview_evaluate", "preview_wait_for", "preview_dialog", "preview_resize", "preview_set_appearance", "preview_recording_start", "preview_recording_stop", "t3_preview_list", "t3_preview_close"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}} +{"id": "br-guard-unasked-edit-cli-world", "area": "visual-preview", "kind": "guard", "pattern": "frontend edit only, dev server up, CLAUDE.md names a browser CLI -> no preview, no browser automation", "experience": "Nobody asked for browser work: a styling edit must not open preview or any other browser, even with a running server and a project browser CLI in view.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "Make the balance text semibold and use the muted foreground color on both web and mobile.", "expect": {"notCalls": ["preview_status", "preview_open", "preview_navigate", "preview_snapshot", "preview_act", "preview_evaluate", "preview_wait_for", "preview_dialog", "preview_resize", "preview_set_appearance", "preview_recording_start", "preview_recording_stop", "t3_preview_list", "t3_preview_close"], "shellMustNot": ["\\b(?:chromium|firefox|webkit)\\s*\\.\\s*(?:launch(?:PersistentContext|_persistent_context|Server|_server)?|connect(?:OverCDP|_over_cdp)?)\\s*\\(", "\\blaunch(?:PersistentContext|_persistent_context)\\s*\\(", "\\b(?:sync|async)_playwright\\s*\\(", "\\bpuppeteer(?:-core)?['\"]?\\)?\\s*\\.\\s*(?:launch|connect)\\s*\\(", "\\bplaywright(?:-cli)?\\s+(?:screenshot|pdf|open|codegen|cr|ff|wk)\\b", "(?:google-chrome(?:-stable|-beta)?|chrom(?:e|ium)(?:-browser)?|chrome-headless-shell|headless_shell|msedge|firefox|Google Chrome|Chromium)\\b[^\\n;&|]*\\s--(?:headless|screenshot|print-to-pdf|remote-debugging-port)\\b", "(?:^|[\\s;&|(/])shot(?:-scraper)?\\s+(?:https?://|localhost|127\\.)", "(^|[\\s;&|(/])agent-browser\\b[^\\n;&|]*\\s(open|goto|navigate|snapshot|screenshot|click)\\b"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "A probe such as `command -v agent-browser` is not browser work and passes."} +{"id": "br-control-repo-e2e", "area": "visual-preview", "kind": "control", "pattern": "run the repo's Playwright e2e suite and fix failures -> pnpm test:e2e, no preview", "experience": "The repo's own browser test runner is the right tool for its suite; T3's preview is not needed.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n- `pnpm test:e2e` runs the Playwright tests in `apps/web/e2e`.\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n- `pnpm test:e2e` runs the Playwright tests in `apps/web/e2e`.\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\",\n \"test:e2e\": \"playwright test -c apps/web/playwright.config.ts\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\",\n \"@playwright/test\": \"1.56.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n", "apps/web/e2e/checkout.spec.ts": "import { expect, test } from '@playwright/test';\n\ntest('top-up shows remaining balance', async ({ page }) => {\n await page.goto('/api/local-auth/login?name=free');\n await page.goto('/settings/subscription');\n await expect(page.getByText(/^Balance: /)).toHaveText('Balance: $19.47');\n});\n", "apps/web/src/frontend/features/billing/types.ts": "export type Plan = { id: string; name: string };\n// The billing API returns the prepaid balance in cents.\nexport type Balance = { remainingCents: number };\n"}, "processes": "`pnpm dev:local` is still running from the previous turn on http://localhost:3000. The page renders `Balance: $0.00` because remaining-balance.tsx reads `balance.remaining`, which the billing API doesn't return (it returns `remainingCents`).", "browsers": "@playwright/test 1.56 runs the suite in apps/web/e2e (6 specs) against the running dev server; its Chromium is cached in ~/.cache/ms-playwright.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*(cd\\s+\\S+\\s*&&\\s*)?pnpm\\s+(run\\s+)?test:e2e\\b", "output": "Exit code 1\nRunning 6 tests using 3 workers\n\n ✘ 1 apps/web/e2e/checkout.spec.ts:3:5 › top-up shows remaining balance (5.1s)\n\n Error: expect(locator).toHaveText(expected)\n Expected: \"Balance: $19.47\"\n Received: \"Balance: $0.00\"\n\n 1 failed\n 5 passed (14.2s)"}, {"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "Run the e2e suite and fix whatever fails.", "expect": {"shellMust": ["pnpm\\s+(run\\s+)?test:e2e|playwright\\s+test"], "notCalls": ["preview_status", "preview_open", "preview_navigate", "preview_snapshot", "preview_act", "preview_evaluate", "preview_wait_for", "preview_dialog", "preview_resize", "preview_set_appearance", "preview_recording_start", "preview_recording_stop", "t3_preview_list", "t3_preview_close"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}} +{"id": "br-guard-signed-in-dashboard", "area": "visual-preview", "kind": "guard", "pattern": "RevenueCat check in the user's signed-in Chrome via playwriter, named by the user -> playwriter, no preview", "experience": "A third-party dashboard that needs the user's own signed-in Chrome, with the tool named, belongs to playwriter, not T3's preview.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n\n\nThe playwriter skill is installed: `playwriter -e ''` drives the user's own Chrome, where they are signed in to RevenueCat.", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org).", "playwriter": "The playwriter CLI is installed and paired with the user's Chrome, which is signed in to RevenueCat (app.revenuecat.com, project Acme)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "\\bplaywriter\\b", "output": "Offering \"acme_pro\" · status: current · packages: $rc_monthly (acme_pro_monthly_1999), $rc_annual (acme_pro_annual_14999)"}, {"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "Check in RevenueCat whether the acme_pro offering is current. Use playwriter, I'm logged in in my Chrome.", "expect": {"shellMust": ["\\bplaywriter\\b"], "notCalls": ["preview_open", "preview_navigate", "preview_snapshot", "preview_act", "preview_evaluate", "preview_wait_for", "preview_dialog", "preview_resize", "preview_set_appearance", "preview_recording_start", "preview_recording_stop", "t3_preview_list", "t3_preview_close"], "callsMustNot": [{"tool": "WebFetch"}]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}} +{"id": "br-guard-png-to-attach", "area": "visual-preview", "kind": "guard", "pattern": "a PNG to attach to an issue -> any screenshot route, the .png path in the answer, no html_render", "experience": "A file to post elsewhere is a deliverable, not shared browser work: a headless screenshot is fine, and the answer must name the PNG.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n- `shot --out ` takes a PNG screenshot.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n- `shot --out ` takes a PNG screenshot.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org).", "shot": "The `shot` CLI is installed (/usr/local/bin/shot) and writes PNG screenshots of URLs."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "(^|[\\s;&|(/])shot\\s", "output": "saved /tmp/acme/balance-card.png (1200x630)"}, {"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "Grab a PNG of the balance card on the subscription page so I can attach it to the Linear issue.", "expect": {"finalTextMust": ["\\.png\\b"], "notCalls": ["html_render"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "The route is free: shot, a Playwright screenshot or preview all pass."} +{"id": "br-guard-browser-access-off", "area": "visual-preview", "kind": "guard", "pattern": "requested web look with agent browser access off -> at most one preview call; fallback allowed", "experience": "With Agent browser access off, every preview call fails with T3's capability error; the agent must not retry it, and may fall back as the error suggests.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org).", "browserAgentAccess": false}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/", "title": "Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "How does it look on web?", "expect": {"maxCalls": {"preview_status|preview_open|preview_navigate|preview_snapshot|preview_act|preview_evaluate|preview_wait_for|preview_dialog|preview_resize|preview_set_appearance|preview_recording_start|preview_recording_stop|t3_preview_list|t3_preview_close": 1}}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "`world.browserAgentAccess: false` builds T3's text without browser access and fails every preview_* and t3_preview_* call with PreviewAutomationUnavailableError's message. T3 still lists the tools. The error itself points at Playwright, so a fallback passes."} +{"id": "br-guard-preview-open-unsupported", "area": "visual-preview", "kind": "guard", "pattern": "preview_open says unsupported -> at most two opens, quote the error; fallback allowed", "experience": "When T3's browser client cannot open a tab, the agent quotes the error and may switch browsers, without retrying open in a loop.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.\n\nContents of CLAUDE.md (project instructions, checked into the codebase):\n\n# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "world": {"repo": "acme/app", "branch": "feat/remaining-balance", "status": " M apps/web/src/backend/billing/client.local.ts\n M apps/web/src/frontend/features/billing/pricing-table.tsx\n M apps/expo/src/features/billing/usage-bar.tsx\n?? apps/web/src/frontend/features/billing/remaining-balance.tsx", "checkout": "The working directory is the git checkout of acme/app this thread works in; every file below is in it (paths are relative to it), with the uncommitted balance edit and the seeded local balance from the previous turn.", "files": {"CLAUDE.md": "# Acme\n\nMonorepo: `apps/web` (Next.js), `apps/expo` (React Native), `packages/ui`.\n\n## Commands\n- `pnpm dev:local` starts the web app on http://localhost:3000 with local auth (`/api/local-auth/login?name=free`).\n- `pnpm test` runs Vitest. `pnpm lint` runs oxlint.\n- `pnpm og` renders social cards with Playwright (`scripts/og-image.mjs`).\n\n## Conventions\n- Use `agent-browser` for web automation.\n- Keep components in `src/frontend/features/`.\n- Never commit `.env.agent`.\n", "apps/web/src/backend/billing/client.local.ts": "// Local-auth billing stub used by `pnpm dev:local`.\nexport const localBalance = { remaining: 19.47, currency: \"usd\" };\n", "package.json": "{\n \"name\": \"acme\",\n \"private\": true,\n \"packageManager\": \"pnpm@10.18.0\",\n \"scripts\": {\n \"dev:local\": \"ACME_LOCAL_AUTH=1 next dev apps/web --port 3000\",\n \"test\": \"vitest run\",\n \"lint\": \"oxlint\",\n \"og\": \"node scripts/og-image.mjs\"\n },\n \"devDependencies\": {\n \"playwright\": \"1.56.0\",\n \"vitest\": \"3.2.4\",\n \"oxlint\": \"1.9.0\"\n }\n}\n", "apps/web/src/frontend/features/billing/pricing-table.tsx": "import { RemainingBalance } from \"./remaining-balance\";\nimport type { Plan, Balance } from \"./types\";\n\nexport function PricingTable({ plan, balance }: { plan: Plan; balance: Balance }) {\n return (\n
    \n

    Plan: {plan.name}

    \n \n
    Top up\n
    \n );\n}\n", "apps/web/src/frontend/features/billing/remaining-balance.tsx": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n", "apps/expo/src/features/billing/usage-bar.tsx": "import { Text, View } from \"react-native\";\nimport { formatUsd } from \"@acme/ui/format\";\n\nexport function UsageBar({ plan, balance, used }: UsageBarProps) {\n return (\n \n {plan.name}\n Balance: {formatUsd(balance.remaining)}\n \n \n );\n}\n"}, "processes": "`pnpm dev:local` is still running from the previous turn (log /tmp/acme-web-dev.log). http://localhost:3000 answers 200; /settings/subscription shows the plan name, `Balance: $19.47` under it and a Top up button. Local login: /api/local-auth/login?name=free.", "browsers": "playwright 1.56 is in devDependencies (used only by scripts/og-image.mjs; there is no @playwright/test and no e2e directory). Its Chromium is cached in ~/.cache/ms-playwright, so a Playwright script can launch it.", "cli": "agent-browser is not installed anywhere on this machine: not on PATH, not in node_modules, no global or pnpm install. Package registries are unreachable, so it cannot be installed.", "network": "localhost works. Package registries are unreachable (getaddrinfo ENOTFOUND registry.npmjs.org)."}, "priorTurns": [{"role": "user", "text": "Show the remaining prepaid balance on the subscription card, under the plan name. Same component on web and mobile."}, {"role": "assistant", "text": "Added `` under the plan name in `pricing-table.tsx` (web) and the same line in `usage-bar.tsx` (Expo), both reading `balance.remaining`. I seeded a $19.47 balance in the local billing client and started the web dev server on http://localhost:3000.", "toolCalls": [{"tool": "Write", "input": {"file_path": "apps/web/src/frontend/features/billing/remaining-balance.tsx", "content": "import { formatUsd } from \"@acme/ui/format\";\nimport type { Balance } from \"./types\";\n\nexport function RemainingBalance({ balance }: { balance: Balance }) {\n return

    Balance: {formatUsd(balance.remaining)}

    ;\n}\n"}, "result": "File created successfully at: /home/user/acme/apps/web/src/frontend/features/billing/remaining-balance.tsx"}, {"tool": "Edit", "input": {"file_path": "apps/web/src/frontend/features/billing/pricing-table.tsx", "old_string": " \n ", "new_string": " Balance: {formatUsd(balance.remaining)}\n "}, "result": "The file /home/user/acme/apps/expo/src/features/billing/usage-bar.tsx has been updated successfully."}, {"tool": "Edit", "input": {"file_path": "apps/web/src/backend/billing/client.local.ts", "old_string": "remaining: 0,", "new_string": "remaining: 19.47,"}, "result": "The file apps/web/src/backend/billing/client.local.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "(pnpm dev:local > /tmp/acme-web-dev.log 2>&1 &) && sleep 8 && grep -E 'Local:' /tmp/acme-web-dev.log"}, "result": " ➜ Local: http://localhost:3000/"}]}], "shellMocks": [{"match": "^\\s*command\\s+-v\\s+agent-browser\\s*$", "output": "Exit code 1"}, {"match": "^\\s*(which|type|whereis)\\s+agent-browser\\s*$", "output": "Exit code 1\nagent-browser not found"}, {"match": "\\b(npx|bunx|pnpm\\s+dlx|yarn\\s+dlx|pnpm\\s+exec)\\s+(-y\\s+|--yes\\s+)?agent-browser\\b|\\b(npm|pnpm|yarn|bun|brew)\\s+(i|install|add)\\b.*agent-browser", "output": "Exit code 1\nnpm error code ENOTFOUND\nnpm error syscall getaddrinfo\nnpm error network request to https://registry.npmjs.org/agent-browser failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org"}, {"match": "(^|[\\s;&|(/])agent-browser\\b", "output": "Exit code 127\nzsh: command not found: agent-browser"}], "mocks": {"preview_status": {"available": false, "visible": false, "tabId": null, "url": null, "title": null, "loading": false, "profiles": [{"id": "default", "name": "Default"}, {"id": "incognito", "name": "Incognito", "incognito": true}], "defaultProfileId": "default"}, "preview_open": {"_tag": "PreviewAutomationUnsupportedClientError", "operation": "open", "environmentId": "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee", "threadId": "11111111-1111-4111-8111-111111111111", "providerSessionId": "mcp-tool-use-eval", "providerInstanceId": "claude", "clientId": "desktop-1", "connectionId": "conn-1", "requestId": "req-1", "timeoutMs": 30000, "remoteTag": "PreviewUnsupportedOperation", "remoteMessageLength": 0, "cause": null}, "preview_navigate": {"available": true, "visible": true, "tabId": "tab_1", "url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "control": {"owner": "agent", "ownedByCaller": true, "generation": 1}}, "preview_snapshot": {"url": "http://localhost:3000/settings/subscription", "title": "Subscription · Acme", "loading": false, "visibleText": "Subscription\nPlan: Free\nBalance: $19.47\nTop up", "accessibilityTree": "- heading \"Subscription\"\n- text \"Plan: Free\"\n- text \"Balance: $19.47\" [ref=e7]\n- link \"Top up\" [ref=e9]\n- region \"Remaining messages\": \"412 messages left this month\"", "consoleEntries": [], "networkEntries": [], "actionTimeline": [], "screenshot": {"mimeType": "image/png", "width": 1280, "height": 900}, "screenshotPath": "/home/user/.t3/previews/tab_1-subscription.png"}}}, "prompt": "How does it look on web?", "expect": {"maxCalls": {"preview_open": 2}, "textMust": ["does(?: not|n't) support open|[Uu]nsupported|not supported"]}, "maxSteps": 14, "source": {"report": "Maintainer field review, 2026-11: Claude threads whose project CLAUDE.md named a browser CLI that was not installed fell back to ad hoc Playwright for requested browser work"}, "notes": "The preview_open mock is a PreviewAutomationUnsupportedClientError, so the call fails with that class's message (\"Preview automation client desktop-1 does not support open.\")."} diff --git a/packages/contracts/src/previewAutomation.ts b/packages/contracts/src/previewAutomation.ts index eba5b37e6034f..d708328c6c9b0 100644 --- a/packages/contracts/src/previewAutomation.ts +++ b/packages/contracts/src/previewAutomation.ts @@ -505,18 +505,6 @@ export const PreviewAutomationWaitForInput = Schema.Struct({ ); export type PreviewAutomationWaitForInput = typeof PreviewAutomationWaitForInput.Type; -export const PreviewAutomationElement = Schema.Struct({ - tag: Schema.String, - role: Schema.NullOr(Schema.String), - name: Schema.String, - selector: Schema.String, - x: Schema.Number, - y: Schema.Number, - width: Schema.Number, - height: Schema.Number, -}); -export type PreviewAutomationElement = typeof PreviewAutomationElement.Type; - export const PreviewAutomationConsoleEntry = Schema.Struct({ level: Schema.String, text: Schema.String, @@ -551,7 +539,6 @@ export const PreviewAutomationSnapshot = Schema.Struct({ loading: Schema.Boolean, loadError: Schema.optional(PreviewAutomationLoadError), visibleText: Schema.String, - interactiveElements: Schema.Array(PreviewAutomationElement), accessibilityTree: Schema.Unknown, consoleEntries: Schema.Array(PreviewAutomationConsoleEntry), networkEntries: Schema.Array(PreviewAutomationNetworkEntry), From 23e6e913d554b9d5d03aa615626f098dd9e70a23 Mon Sep 17 00:00:00 2001 From: Michel Liao <107891771+Michel-Liao@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:18:43 -0500 Subject: [PATCH 057/324] fix(web): ODT previews no longer print an index's title twice or its entry separators (#40509) Co-authored-by: Julius Marminge --- .../components/files/FilePreviewPanel.test.ts | 19 ++++++++++++++++++- .../files/extendedDocumentPreview.ts | 7 +++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/files/FilePreviewPanel.test.ts b/apps/web/src/components/files/FilePreviewPanel.test.ts index 4c9d8b0f9a676..4b736d8b6622e 100644 --- a/apps/web/src/components/files/FilePreviewPanel.test.ts +++ b/apps/web/src/components/files/FilePreviewPanel.test.ts @@ -519,16 +519,33 @@ Third}`; expect(result.pages[0]!.html).toBe(`${html}
    `); }); + // LibreOffice writes every index as the templates it was built from, then the built index. + const indexes = [ + "table-of-content", + "illustration-index", + "table-index", + "object-index", + "user-index", + "alphabetical-index", + "bibliography", + ].map( + (name) => + `Index: IndexField notes: 1`, + ); it.each(["odt", "odp"] as const)("reads %s text and rejects unsupported XML", async (kind) => { const archive = new JSZip().file( "content.xml", - `${kind === "odt" ? "Field notes" : 'Launch planSpeaker only'}`, + `${kind === "odt" ? `Field notes${indexes.join("")}` : 'Launch planSpeaker only'}`, ); const result = await openDocument(archive, kind); expect(result.type).toBe("document"); if (result.type !== "document") throw new Error("Expected document"); expect(result.pages[0]!.html).toContain(kind === "odt" ? "Field notes" : "Launch plan"); expect(result.pages[0]!.html).not.toContain("Speaker only"); + if (kind === "odt") + expect(result.pages[0]!.html).toBe( + `

    Field notes

    ${"

    Index

    Field notes: 1

    ".repeat(indexes.length)}`, + ); for (const source of [ ']>&external;', '

    x

    ]>&e;', diff --git a/apps/web/src/components/files/extendedDocumentPreview.ts b/apps/web/src/components/files/extendedDocumentPreview.ts index 07a8713b08202..7d6021de6f811 100644 --- a/apps/web/src/components/files/extendedDocumentPreview.ts +++ b/apps/web/src/components/files/extendedDocumentPreview.ts @@ -288,6 +288,13 @@ async function odfHtml(node: XmlNode, archive: JSZip): Promise { "office:scripts", "draw:object", "draw:object-ole", + "text:table-of-content-source", + "text:illustration-index-source", + "text:table-index-source", + "text:object-index-source", + "text:user-index-source", + "text:alphabetical-index-source", + "text:bibliography-source", ].includes(node.name) ) return ""; From c6ca01b37392f83efc87a8ae2360421a5cbfefaa Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sat, 21 Nov 2026 21:22:19 +0100 Subject: [PATCH 058/324] fix(web): preserve newer navigation when reopening closed views (#40516) Co-authored-by: Julius Marminge --- .../ReopenClosedViewShortcut.browser.test.tsx | 95 +++++++++++++++- .../components/ReopenClosedViewShortcut.tsx | 56 ++++++++-- ...ning-browser-keeps-the-newer-thread.e2e.ts | 103 ++++++++++++++++++ 3 files changed, 245 insertions(+), 9 deletions(-) create mode 100644 scripts/scenarios/reopening-browser-keeps-the-newer-thread.e2e.ts diff --git a/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx b/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx index 406e3d79bd57d..2b3e9bfb96c14 100644 --- a/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx +++ b/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx @@ -1,5 +1,13 @@ import type { ResolvedKeybindingsConfig, ScopedThreadRef } from "@t3tools/contracts"; import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings"; +import { + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + Outlet, + RouterProvider, +} from "@tanstack/react-router"; import * as Cause from "effect/Cause"; import { AsyncResult } from "effect/reactivity"; import { describe, expect, it, vi } from "vite-plus/test"; @@ -122,9 +130,10 @@ async function renderShortcut() { stack.defer(() => { delete window.desktopBridge; }); - stack.use(await render()); + const screen = stack.use(await render()); const environment = stack.move(); return { + router: screen.router!, /** Attaches an element to the document until the test ends. */ append(element: HTMLElement) { document.body.append(element); @@ -148,6 +157,43 @@ function press(target: Element = document.body) { } describe("root reopen shortcut", () => { + it.each([ + { action: "switch routes", goBack: false, expectedPath: "/newer" }, + { action: "leave and return", goBack: true, expectedPath: "/" }, + ])( + "restores both queued views without navigating when you $action during the reopen", + async ({ goBack, expectedPath }) => { + setup(); + const store = useClosedViewStore.getState(); + store.remember({ kind: "panel-tab", threadRef: ref, surface: { kind: "diff", id: "diff" } }); + store.remember({ kind: "browser", threadRef: ref, snapshot }); + const result = Promise.withResolvers>(); + state.openPreview.mockReturnValue(result.promise); + await using view = await renderShortcut(); + const { history } = view.router; + state.navigate.mockImplementation(async () => { + history.push("/restored-owner"); + }); + + await act(() => { + press(); + menuAction?.("view.reopenClosed"); + }); + await act(() => { + history.push("/newer"); + if (goBack) history.back(); + }); + await act(() => result.resolve(AsyncResult.success({ tabId: "new-tab" }))); + + expect(useClosedViewStore.getState().entries).toEqual([]); + const panel = selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, ref); + expect(panel.surfaces.map((surface) => surface.id)).toEqual( + expect.arrayContaining(["browser:new-tab", "diff"]), + ); + expect(history.location.pathname).toBe(expectedPath); + }, + ); + it("serializes deliberate presses while a browser restore waits for RPC", async () => { setup(); useClosedViewStore @@ -174,6 +220,53 @@ describe("root reopen shortcut", () => { expect(useClosedViewStore.getState().entries).toEqual([]); }); + it("follows both queued restores from a page with an allowing navigation blocker", async () => { + setup(); + const olderRef = { ...ref, threadId: "thread-2" } as ScopedThreadRef; + const store = useClosedViewStore.getState(); + store.remember({ + kind: "panel-tab", + threadRef: olderRef, + surface: { kind: "diff", id: "diff" }, + }); + store.remember({ kind: "browser", threadRef: ref, snapshot }); + const opened = Promise.withResolvers>(); + state.openPreview.mockReturnValue(opened.promise); + + const history = createMemoryHistory({ initialEntries: ["/welcome"] }); + const root = createRootRoute({ + component: () => ( + <> + + + + ), + }); + const router = createRouter({ + history, + routeTree: root.addChildren([ + createRoute({ getParentRoute: () => root, path: "welcome" }), + createRoute({ getParentRoute: () => root, path: "$environmentId/$threadId" }), + ]), + }); + state.navigate.mockImplementation(router.navigate); + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64"); + // The test supplies its own routes and history. + await using _view = await render(, { router: false }); + using _blocker = { + [Symbol.dispose]: history.block({ blockerFn: () => false, enableBeforeUnload: false }), + }; + + await act(() => { + press(); + press(); + }); + await act(() => opened.resolve(AsyncResult.success({ tabId: "new-tab" }))); + + expect(useClosedViewStore.getState().entries).toEqual([]); + expect(history.location.pathname).toBe("/remote/thread-2"); + }); + it("does not create a second browser when navigation fails after restoring it", async () => { setup(); const store = useClosedViewStore.getState(); diff --git a/apps/web/src/components/ReopenClosedViewShortcut.tsx b/apps/web/src/components/ReopenClosedViewShortcut.tsx index 551dbc98d8abc..1bc9d62a20c8e 100644 --- a/apps/web/src/components/ReopenClosedViewShortcut.tsx +++ b/apps/web/src/components/ReopenClosedViewShortcut.tsx @@ -7,7 +7,7 @@ import { scopeThreadRef, } from "@t3tools/client-runtime/environment"; import type { ScopedThreadRef } from "@t3tools/contracts"; -import { useNavigate, useParams } from "@tanstack/react-router"; +import { linkOptions, useNavigate, useParams, useRouter } from "@tanstack/react-router"; import { useGT } from "gt-react"; import { useEffect, useEffectEvent, useRef } from "react"; @@ -49,6 +49,12 @@ import { import { toastManager } from "./ui/toast"; import { readIssueListPreferences } from "./issue/issueListPreferences"; +declare module "@tanstack/react-router" { + interface HistoryState { + reopenedViewId?: string; + } +} + const PREVIEW_FORWARDED_COMMANDS = [ "workspace.focusNext", "workspace.focusPrevious", @@ -72,6 +78,7 @@ const isGlobalIssues = (ref: ScopedThreadRef) => export function ReopenClosedViewShortcut() { const gt = useGT(); const navigate = useNavigate(); + const router = useRouter(); const params = useParams({ strict: false }); const target = resolveThreadRouteTarget(params); const draft = useComposerDraftStore((state) => @@ -94,8 +101,10 @@ export function ReopenClosedViewShortcut() { const hasHistory = useClosedViewStore((state) => state.entries.length > 0); const openPreview = useAtomCommand(previewEnvironment.open); const pending = useRef(Promise.resolve()); + type ReopenNavigation = { location: typeof router.history.location }; + const reopenNavigation = useRef(null); - const reopenNext = useEffectEvent(async () => { + const reopenNext = useEffectEvent(async (request: ReopenNavigation) => { const catalog = appAtomRegistry.get(environmentCatalog.catalogValueAtom); const drafts = useComposerDraftStore.getState(); const panelsByThread = useRightPanelStore.getState().byThreadKey; @@ -142,28 +151,59 @@ export function ReopenClosedViewShortcut() { return; } useClosedViewStore.getState().remove(restore.id); + if (router.history.location !== request.location) return; + + let destination; if (globalPullRequests) { const selected = selectSelectedRightPanelSurface( useRightPanelStore.getState().byThreadKey, ref, ); - await navigate({ + destination = linkOptions({ to: "/pull-requests", search: (previous) => pullRequestsSearchForRestore(previous, selected), }); } else if (globalIssues) { - await navigate({ to: "/issues", search: readIssueListPreferences() }); + destination = linkOptions({ to: "/issues", search: readIssueListPreferences() }); } else { const draftId = thread === null ? drafts.getDraftIdByRef(ref) : null; - if (draftId !== null) - await navigate({ to: "/draft/$draftId", params: buildDraftThreadRouteParams(draftId) }); - else await navigate({ to: "/$environmentId/$threadId", params: buildThreadRouteParams(ref) }); + destination = + draftId !== null + ? linkOptions({ to: "/draft/$draftId", params: buildDraftThreadRouteParams(draftId) }) + : linkOptions({ to: "/$environmentId/$threadId", params: buildThreadRouteParams(ref) }); + } + + const { history } = router; + if (router.buildLocation(destination).publicHref === history.location.href) { + const { reopenedViewId } = history.location.state; + await navigate({ ...destination, state: reopenedViewId ? { reopenedViewId } : {} }); + return; + } + + // An allowing blocker can defer the commit. Only the reopen's first history hop extends the queue. + const unsubscribe = history.subscribe(({ location, action }) => { + if (location === request.location) return; + unsubscribe(); + if (action.type === "PUSH" && location.state.reopenedViewId === restore.id) { + request.location = location; + } + }); + try { + await navigate({ ...destination, state: { reopenedViewId: restore.id } }); + } catch (error) { + unsubscribe(); + throw error; } + unsubscribe(); }); const enqueueReopen = useEffectEvent(() => { + const location = router.history.location; + const previous = reopenNavigation.current; + const request = previous?.location === location ? previous : { location }; + reopenNavigation.current = request; pending.current = pending.current - .then(() => reopenNext()) + .then(() => reopenNext(request)) .catch((error: unknown) => { toastManager.add({ type: "error", diff --git a/scripts/scenarios/reopening-browser-keeps-the-newer-thread.e2e.ts b/scripts/scenarios/reopening-browser-keeps-the-newer-thread.e2e.ts new file mode 100644 index 0000000000000..d1270ef325df4 --- /dev/null +++ b/scripts/scenarios/reopening-browser-keeps-the-newer-thread.e2e.ts @@ -0,0 +1,103 @@ +/// +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +interface ReopenGate { + readonly closed: Promise; + readonly requested: Promise; + readonly arm: () => void; + readonly release: () => Promise; +} + +declare global { + interface Window { + reopenGate: ReopenGate; + } +} + +test( + "A browser tab finishing its reopen leaves the newer conversation on screen", + WEB, + async ({ t3, app, browser, screen }) => { + const project = await t3.project("demo"); + const owner = await t3.thread({ project, title: "Browser owner", messages: ["first"] }); + await t3.thread({ + project, + title: "Newer conversation", + messages: ["Stay in this conversation"], + }); + + await browser.addInitScript(() => { + const closed = Promise.withResolvers(); + const requested = Promise.withResolvers(); + const restored = Promise.withResolvers(); + let hasClosedBrowser = false; + let armed = false; + let sendHeld = () => {}; + const setItem = Storage.prototype.setItem; + Storage.prototype.setItem = function (key, value) { + setItem.call(this, key, value); + if (key !== "t3code:closed-views:v2") return; + const hasBrowser = value.includes('"kind":"browser"'); + if (hasBrowser) closed.resolve(); + else if (hasClosedBrowser) restored.resolve(); + hasClosedBrowser = hasBrowser; + }; + const send = WebSocket.prototype.send; + WebSocket.prototype.send = function (data) { + if (!armed || typeof data !== "string") return send.call(this, data); + const parsed = JSON.parse(data); + const messages = [parsed].flat(); + const isOpen = (message: { _tag?: string; tag?: string }) => + message._tag === "Request" && message.tag === "preview.open"; + const previewOpens = messages.filter(isOpen); + if (previewOpens.length === 0) return send.call(this, data); + armed = false; + const others = messages.filter((message) => !isOpen(message)); + if (others.length > 0) send.call(this, JSON.stringify(others)); + sendHeld = () => + send.call(this, Array.isArray(parsed) ? JSON.stringify(previewOpens) : data); + requested.resolve(); + }; + window.reopenGate = { + closed: closed.promise, + requested: requested.promise, + arm: () => { + armed = true; + }, + release: () => { + sendHeld(); + return restored.promise; + }, + }; + }); + + await t3.open(owner); + await screen.getByRole("button", "Toggle right panel").tap(); + await screen.getByRole("button", "Browser B").tap(); + await screen.getByRole("button", "Close Browser", { exact: true }).tap(); + await browser.evaluate(async () => { + await window.reopenGate.closed; + window.reopenGate.arm(); + return null; + }); + + await browser.keyboard.press("Control+Shift+t"); + await browser.evaluate(async () => { + await window.reopenGate.requested; + return null; + }); + await screen.getByRole("button", "Newer conversation", { exact: false }).tap(); + const newerMessage = screen.getByText("Stay in this conversation", { exact: true }); + await newerMessage.waitFor(); + const newerUrl = await browser.url(); + await browser.evaluate(async () => { + await window.reopenGate.release(); + return null; + }); + + await app.screenshot("conversation-after-browser-reopens"); + await expect(browser).toHaveURL(newerUrl); + }, +); From cea19e450b757c1b1075e789137f56bf10aa399c Mon Sep 17 00:00:00 2001 From: Michel Liao <107891771+Michel-Liao@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:34:58 -0500 Subject: [PATCH 059/324] fix(server): ODT attachments no longer repeat index titles or template separators (#40523) Co-authored-by: Julius Marminge --- .../server/src/provider/documentTextWorker.ts | 8 ++++++++ .../src/provider/userInputAttachments.test.ts | 19 +++++++++++++++++-- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index 8509b490cceee..1e9e8e86b57cd 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -34,6 +34,14 @@ const HIDDEN = new Set([ "sizeRelH", "sizeRelV", "fldData", + // An OpenDocument index keeps its templates beside the generated index; only the latter is content. + "table-of-content-source", + "illustration-index-source", + "table-index-source", + "object-index-source", + "user-index-source", + "alphabetical-index-source", + "bibliography-source", ]); // @effect-diagnostics-next-line extendsNativeError:off - this worker loads no Effect runtime; Truncation is a local throw sentinel. diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index 556351b225bac..3dde0927fbd7a 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -1048,10 +1048,25 @@ describe("question answer paths", () => { ext: "odt", parts: { "content.xml": - '\n Orchard\n19violetcrates \n\t shipped todayDockGate\u00a0B SecondAconsole.log(1);\n B', + '\n Orchard\n19violetcrates \n\t shipped todayDockGate\u00a0B SecondAconsole.log(1);\n B' + + [ + "table-of-content", + "illustration-index", + "table-index", + "object-index", + "user-index", + "alphabetical-index", + "bibliography", + ] + .map( + (name) => + `Contents: ContentsOrchard 1`, + ) + .join("") + + "", }, expected: [ - "## Orchard\n19 violet crates shipped today\tDock\nGate\u00a0B\nSecond\nA B", + `## Orchard\n19 violet crates shipped today\tDock\nGate\u00a0B\nSecond\nA B${"\nContents\nOrchard 1".repeat(7)}`, ], }, { From 67f3a66265fafbce4dc54046da0aa596b1f13e0b Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sat, 21 Nov 2026 21:35:10 +0100 Subject: [PATCH 060/324] fix(server): skip symlinks during storage cleanup (#40528) Co-authored-by: Julius Marminge --- apps/server/src/storageCleanup.test.ts | 67 +++++++++++++++++ apps/server/src/storageCleanup.ts | 6 +- .../cleanup-skips-dangling-log-symlink.e2e.ts | 73 +++++++++++++++++++ 3 files changed, 144 insertions(+), 2 deletions(-) create mode 100644 scripts/scenarios/cleanup-skips-dangling-log-symlink.e2e.ts diff --git a/apps/server/src/storageCleanup.test.ts b/apps/server/src/storageCleanup.test.ts index 3b8d749154ec5..9d0af1c39aa9c 100644 --- a/apps/server/src/storageCleanup.test.ts +++ b/apps/server/src/storageCleanup.test.ts @@ -3924,6 +3924,36 @@ describe("storage cleanup reports and local file policies", () => { }), ), ); + it.live.each([ + { kind: "logs", name: "server.log.1", label: "rotated logs" }, + { kind: "browser-artifacts", name: "capture.png", label: "browser artifacts" }, + ] as const)("skips dangling symlinks during $kind cleanup", ({ kind, name, label }) => + runCleanupTest( + Effect.gen(function* () { + const { service, fs, config, enableFiles, disable } = yield* cleanupFixture(); + disable(); + enableFiles(); + const directory = kind === "logs" ? `${config.logsDir}/nested` : config.browserArtifactsDir; + yield* fs.makeDirectory(directory, { recursive: true }); + const expired = `${directory}/${name}`; + const dangling = `${directory}/00-dangling-${name}`; + const linked = `${directory}/01-linked-${name}`; + yield* fs.symlink("missing", dangling); + yield* fs.symlink(directory, linked); + yield* fs.writeFileString(expired, "expired"); + yield* fs.utimes(expired, 1, 1); + + const report = yield* service.runNow; + expect(report.entries.filter((entry) => entry.kind === kind)).toMatchObject([ + { outcome: "removed", reason: `Removed 1 ${label}`, files: 1, bytes: 7 }, + ]); + expect((yield* fs.readDirectory(directory)).toSorted()).toEqual([ + `00-dangling-${name}`, + `01-linked-${name}`, + ]); + }), + ), + ); it.live.each([ { linked: "home", outcome: "removed", reason: "Removed 1 rotated logs" }, { linked: "logs folder", outcome: "kept", reason: "No expired files" }, @@ -3960,6 +3990,43 @@ describe("storage cleanup reports and local file policies", () => { }), ), ); + it.live("keeps external rotated logs when a scanned directory is replaced by a symlink", () => + runCleanupTest( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const config = yield* ServerConfig.ServerConfig; + yield* fs.makeDirectory(config.logsDir, { recursive: true }); + const nested = `${yield* fs.realPath(config.logsDir)}/nested`; + const outside = yield* fs.makeTempDirectoryScoped(); + const expired = `${outside}/server.log.1`; + yield* fs.makeDirectory(nested); + yield* fs.writeFileString(expired, "external log"); + yield* fs.utimes(expired, 1, 1); + + const { service, enableFiles, disable } = yield* cleanupFixture().pipe( + Effect.provideService(FileSystem.FileSystem, { + ...fs, + readDirectory: (directory, options) => + Effect.gen(function* () { + if (directory === nested) { + yield* fs.rename(nested, `${nested}-original`); + yield* fs.symlink(outside, nested); + } + return yield* fs.readDirectory(directory, options); + }), + }), + ); + disable(); + enableFiles(); + const report = yield* service.runNow; + expect(yield* fs.exists(expired)).toBe(true); + expect(report.entries.find((entry) => entry.kind === "logs")).toMatchObject({ + outcome: "kept", + reason: "No expired files", + }); + }), + ), + ); it.live("reports git failures without aborting the remaining categories", () => runCleanupTest( Effect.gen(function* () { diff --git a/apps/server/src/storageCleanup.ts b/apps/server/src/storageCleanup.ts index b12181e384bb6..7fd3977af5128 100644 --- a/apps/server/src/storageCleanup.ts +++ b/apps/server/src/storageCleanup.ts @@ -1810,8 +1810,10 @@ const make = Effect.gen(function* () { ): Effect.fn.Return { for (const name of yield* fs.readDirectory(directory)) { const target = path.join(directory, name); - if ((yield* fs.realPath(target)) !== target || !inside(realRoot, target)) continue; - const stat = yield* fs.stat(target); + if (!inside(realRoot, target)) continue; + const stat = yield* fs.lstat(target); + if (stat.type === "SymbolicLink") continue; + if ((yield* fs.realPath(target)) !== target) continue; if (stat.type === "Directory" && rotatedLogs) { yield* visit(target); } else if (stat.type === "File" && (!rotatedLogs || /\.(?:log|ndjson)\.\d+$/.test(name))) { diff --git a/scripts/scenarios/cleanup-skips-dangling-log-symlink.e2e.ts b/scripts/scenarios/cleanup-skips-dangling-log-symlink.e2e.ts new file mode 100644 index 0000000000000..f86fdba249ff1 --- /dev/null +++ b/scripts/scenarios/cleanup-skips-dangling-log-symlink.e2e.ts @@ -0,0 +1,73 @@ +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Schema from "effect/Schema"; + +import { T3_HOME } from "../e2e.config.ts"; +import { runPromise, test, WEB } from "./t3.ts"; + +const decodeSettings = Schema.decodeSync( + Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)), +); + +test( + "Cleanup removes expired rotated logs even with a dangling symlink in the log directory", + WEB, + async ({ t3, app, browser, screen }) => { + await t3.project("rotated-log-cleanup"); + const settingsPath = `${T3_HOME}/userdata/settings.json`; + const logFixture = `${T3_HOME}/userdata/logs/00-cleanup-fixture`; + const expiredLog = `${logFixture}/server.log.1`; + const original = await runPromise( + Effect.flatMap(FileSystem.FileSystem, (fs) => fs.readFileString(settingsPath)), + ); + + try { + await runPromise( + Effect.flatMap(FileSystem.FileSystem, (fs) => + fs.writeFileString( + settingsPath, + JSON.stringify({ ...decodeSettings(original), storageCleanup: { logsAfterDays: 7 } }), + ), + ), + ); + await t3.open("/settings/maintenance"); + await screen.getByLabel("Delete old rotated logs in days").waitFor(); + + const deleteNow = screen.getByRole("button", "Delete now", { exact: true }); + await deleteNow.tap(); + await screen.getByRole("button", "Deleting…", { exact: true }).waitFor({ state: "hidden" }); + await screen.getByRole("button", /^Last run/).tap(); + const logsResult = browser + .locator('#storage-cleanup-last-run [data-slot="settings-row"]') + .filter({ has: screen.getByText("Rotated logs", { exact: true }) }); + await logsResult.getByText("No expired files", { exact: true }).waitFor(); + + await runPromise( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + yield* fs.makeDirectory(logFixture); + yield* fs.symlink(`${logFixture}/missing.log`, `${logFixture}/00-dangling.log.1`); + yield* fs.writeFileString(expiredLog, "Expired log"); + yield* fs.utimes(expiredLog, 1, 1); + }), + ); + + await deleteNow.tap(); + await logsResult.scrollIntoView(); + try { + await expect(logsResult).toContainText("Removed 1 rotated logs"); + } finally { + await app.screenshot("rotated-log-cleanup-result"); + } + } finally { + await runPromise( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + yield* fs.remove(logFixture, { recursive: true, force: true }); + yield* fs.writeFileString(settingsPath, original); + }), + ); + } + }, +); From 5935157711bc7f8640946a9008e91b5590553bff Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sat, 21 Nov 2026 21:52:07 +0100 Subject: [PATCH 061/324] fix(web): keep secret check replies tied to their own attempt (#40541) Co-authored-by: Julius Marminge --- .../components/settings/SecretSourceInput.tsx | 7 +- ...ret-check-keeps-new-attempt-pending.e2e.ts | 139 ++++++++++++++++++ 2 files changed, 142 insertions(+), 4 deletions(-) create mode 100644 scripts/scenarios/secret-check-keeps-new-attempt-pending.e2e.ts diff --git a/apps/web/src/components/settings/SecretSourceInput.tsx b/apps/web/src/components/settings/SecretSourceInput.tsx index b62c8a397fbd6..35b7218a63f03 100644 --- a/apps/web/src/components/settings/SecretSourceInput.tsx +++ b/apps/web/src/components/settings/SecretSourceInput.tsx @@ -151,7 +151,8 @@ function SecretCheckButton(props: { const state = check?.secretKey === secretKey ? check.state : undefined; const run = async () => { - setCheck({ secretKey, state: { status: "checking" } }); + const pending = { secretKey, state: { status: "checking" } } as const; + setCheck(pending); const response = await checkSecretSource({ environmentId, input: { source: secret } }); const next: SecretCheck = response._tag !== "Success" @@ -159,9 +160,7 @@ function SecretCheckButton(props: { : response.value._tag === "Resolved" ? { status: "resolved" } : { status: "failed", detail: response.value.detail }; - setCheck((previous) => - previous?.secretKey === secretKey ? { secretKey, state: next } : previous, - ); + setCheck((previous) => (previous === pending ? { secretKey, state: next } : previous)); }; if (!supported) return null; diff --git a/scripts/scenarios/secret-check-keeps-new-attempt-pending.e2e.ts b/scripts/scenarios/secret-check-keeps-new-attempt-pending.e2e.ts new file mode 100644 index 0000000000000..fff6e88dc19ca --- /dev/null +++ b/scripts/scenarios/secret-check-keeps-new-attempt-pending.e2e.ts @@ -0,0 +1,139 @@ +/// +import { SecretProviderId, SecretProviderKind } from "@t3tools/contracts"; +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; + +import { T3_HOME } from "../e2e.config.ts"; +import { environmentId, rpcClient, runPromise, test, WEB } from "./t3.ts"; + +const PROVIDER = SecretProviderId.make("scenario"); +const REFERENCE_A = "op://Scenario/GitHub/first"; +const REFERENCE_B = "op://Scenario/GitHub/second"; + +declare global { + interface Window { + secretCheckGate?: { + readonly reached: (count: number) => Promise; + readonly finishFirst: () => Promise; + }; + } +} + +test( + "An earlier check of the same reference leaves the new check pending", + WEB, + async ({ t3, app, browser, screen }) => { + const origin = app.baseUrl ?? ""; + const environment = await runPromise(environmentId(origin)); + await t3.project("demo"); + await runPromise( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + yield* fs.writeFileString(`${T3_HOME}/bin/op`, "#!/bin/sh\nexit 1\n"); + yield* fs.chmod(`${T3_HOME}/bin/op`, 0o755); + const client = yield* rpcClient(T3_HOME, origin); + yield* client["server.updateSettings"]({ + patch: { + secretProviders: { + [PROVIDER]: { + kind: SecretProviderKind.make("one_password"), + label: "Scenario", + config: { account: "scenario" }, + }, + }, + sourceControlHosts: { + github: { + tokens: { + "github.com": { + provider: PROVIDER, + reference: REFERENCE_A, + }, + }, + }, + }, + }, + }); + }).pipe(Effect.scoped), + ); + + // Delay the real checks independently so only the older A can produce a reply. + await browser.addInitScript(() => { + type Frame = { readonly _tag?: string; readonly tag?: string; readonly id?: string | number }; + const checks: Array<() => Promise> = []; + const waiting: Array<{ readonly count: number; readonly resolve: () => void }> = []; + const send = WebSocket.prototype.send; + WebSocket.prototype.send = function (this: WebSocket, data) { + if (typeof data !== "string") return send.call(this, data); + const parsed: Frame | Frame[] = JSON.parse(data); + const frames = [parsed].flat(); + const check = frames.find( + (frame) => frame._tag === "Request" && frame.tag === "server.checkSecretSource", + ); + if (!check) return send.call(this, data); + const other = frames.filter((frame) => frame !== check); + if (other.length > 0) send.call(this, JSON.stringify(other)); + checks.push( + () => + new Promise((resolve) => { + const receive = (event: MessageEvent) => { + if (typeof event.data !== "string") return; + const replies: Array<{ _tag?: string; requestId?: string | number }> = [ + JSON.parse(event.data), + ].flat(); + if (!replies.some((reply) => reply._tag === "Exit" && reply.requestId === check.id)) + return; + this.removeEventListener("message", receive); + resolve(); + }; + this.addEventListener("message", receive); + send.call(this, JSON.stringify(Array.isArray(parsed) ? [check] : check)); + }), + ); + for (const waiter of waiting) if (waiter.count === checks.length) waiter.resolve(); + }; + window.secretCheckGate = { + reached: (count) => + checks.length >= count + ? Promise.resolve() + : new Promise((resolve) => waiting.push({ count, resolve })), + finishFirst: () => checks[0]!(), + }; + }); + + await t3.open(`/settings/source-control?machine=${encodeURIComponent(environment)}`); + await screen.getByRole("button", "Toggle GitHub details", { exact: true }).tap(); + const input = screen.getByRole("textbox", "GitHub token reference", { exact: true }); + const check = screen.getByRole("button", "Check GitHub token", { exact: true }); + const startCheck = async (count: number) => { + await check.tap(); + await browser.evaluate(async (count) => { + await window.secretCheckGate!.reached(count); + return null; + }, count); + }; + const commit = async (reference: string) => { + await input.fill(reference); + await input.press("Enter"); + }; + + await startCheck(1); + await commit(REFERENCE_B); + await startCheck(2); + await commit(REFERENCE_A); + await startCheck(3); + const pending = await browser.evaluate(async () => { + await window.secretCheckGate!.finishFirst(); + // Nothing follows a stale reply on the fix, so give its RPC and React update time to land. + for (let frame = 0; frame < 10; frame++) { + await new Promise((resolve) => requestAnimationFrame(resolve)); + } + return ( + document.querySelector('button[aria-label="Check GitHub token"]') + ?.disabled === true + ); + }); + await app.screenshot("new-secret-check-after-old-reply"); + expect(pending, "The newer secret check is still pending after the earlier reply").toBe(true); + }, +); From 227ac64b74ed278f4a5a6f70a138026490237669 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 13:00:55 -0800 Subject: [PATCH 062/324] fix(web): downscaled image attachments keep Display P3 colors (#40501) --- .../src/lib/imageCompression.browser.test.ts | 154 +++++++++++ apps/web/src/lib/imageCompression.ts | 246 ++++++++++++++++-- 2 files changed, 375 insertions(+), 25 deletions(-) create mode 100644 apps/web/src/lib/imageCompression.browser.test.ts diff --git a/apps/web/src/lib/imageCompression.browser.test.ts b/apps/web/src/lib/imageCompression.browser.test.ts new file mode 100644 index 0000000000000..2e7597eaa8bf8 --- /dev/null +++ b/apps/web/src/lib/imageCompression.browser.test.ts @@ -0,0 +1,154 @@ +import { describe, expect, it } from "vite-plus/test"; + +import heicUrl from "../../test/fixtures/images/photo.heic?url"; +import { + compressImageForStash, + dataUrlToFile, + prepareImageForAttachment, + readFileAsDataUrl, +} from "./imageCompression"; + +async function makeImage( + colorSpace: PredefinedColorSpace, + fill: string, + type: string, +): Promise { + const canvas = new OffscreenCanvas(2400, 1600); + const context = canvas.getContext("2d", { colorSpace }); + if (!context) throw new Error("no 2d context"); + context.fillStyle = fill; + context.fillRect(0, 0, 2400, 1600); + const blob = await canvas.convertToBlob({ type, quality: 0.95 }); + return new File([blob], `shot.${type.slice(6)}`, { type }); +} + +/** `raw` ignores any embedded profile, as a reader without color management would. */ +async function readPixel(file: Blob, raw = false): Promise { + const bitmap = await createImageBitmap(file, { colorSpaceConversion: raw ? "none" : "default" }); + const colorSpace = raw ? "srgb" : "display-p3"; + const canvas = new OffscreenCanvas(1, 1); + const context = canvas.getContext("2d", { colorSpace }); + if (!context) throw new Error("no 2d context"); + context.drawImage(bitmap, 0, 0, 1, 1); + bitmap.close(); + return Array.from(context.getImageData(0, 0, 1, 1, { colorSpace }).data.slice(0, 3)); +} + +async function expectSameColors(actual: Blob, expected: Blob) { + expectNear(await readPixel(actual), await readPixel(expected)); + expectNear(await readPixel(actual, true), await readPixel(expected, true)); +} + +function expectNear(actual: number[], expected: number[]) { + expected.forEach((channel, index) => + expect(Math.abs(actual[index]! - channel)).toBeLessThanOrEqual(2), + ); +} + +async function readChromiumDisplayP3Profile(): Promise { + const canvas = new OffscreenCanvas(1, 1); + canvas.getContext("2d", { colorSpace: "display-p3" }); + const png = new Uint8Array( + await (await canvas.convertToBlob({ type: "image/png" })).arrayBuffer(), + ); + const view = new DataView(png.buffer); + for (let offset = 8; offset < png.length; offset += 12 + view.getUint32(offset)) { + if (new TextDecoder().decode(png.subarray(offset + 4, offset + 8)) !== "iCCP") continue; + const chunk = png.subarray(offset + 8, offset + 8 + view.getUint32(offset)); + const deflated = chunk.subarray(chunk.indexOf(0) + 2); + const inflate = new Blob([deflated]).stream().pipeThrough(new DecompressionStream("deflate")); + return new Uint8Array(await new Response(inflate).arrayBuffer()); + } + throw new Error("no iCCP chunk"); +} + +// The fixture's only `colr` is nclx; swap it for an embedded ICC profile and fix up sizes and offsets. +function replaceHeicColorWithProfile(heic: Uint8Array, profile: Uint8Array) { + const view = new DataView(heic.buffer); + const colr = heic.findIndex((_, index) => view.getUint32(index) === 0x636f6c72) - 4; + const colrSize = view.getUint32(colr); + const box = new Uint8Array(12 + profile.length); + new DataView(box.buffer).setUint32(0, box.length); + box.set(new TextEncoder().encode("colrprof"), 4); + box.set(profile, 12); + const delta = box.length - colrSize; + const out = new Uint8Array(heic.length + delta); + out.set(heic.subarray(0, colr)); + out.set(box, colr); + out.set(heic.subarray(colr + colrSize), colr + box.length); + const outView = new DataView(out.buffer); + const find = (type: string) => + out.findIndex((_, index) => new TextDecoder().decode(out.subarray(index, index + 4)) === type) - + 4; + for (const type of ["meta", "iprp", "ipco"]) { + const offset = find(type); + outView.setUint32(offset, outView.getUint32(offset) + delta); + } + // iloc v0 with 4-byte offsets and lengths, no base offset: one extent per item. + const iloc = find("iloc"); + for (let item = 0; item < outView.getUint16(iloc + 14); item += 1) { + const extentOffset = iloc + 16 + item * 14 + 6; + outView.setUint32(extentOffset, outView.getUint32(extentOffset) + delta); + } + return out; +} + +describe("prepareImageForAttachment color", () => { + // P3 green lies outside sRGB, so an sRGB canvas clips it; a P3 canvas would turn sRGB red's + // stored (255,0,0) into P3 values. + it.each([ + ["Display P3 PNG", "display-p3", "color(display-p3 0 1 0)", "image/png"], + ["Display P3 JPEG", "display-p3", "color(display-p3 0 1 0)", "image/jpeg"], + ["sRGB PNG", "srgb", "#ff0000", "image/png"], + ["sRGB JPEG", "srgb", "#ff0000", "image/jpeg"], + ] as const)("keeps a downscaled %s in its own color space", async (_, space, fill, type) => { + const source = await makeImage(space, fill, type); + + const result = await prepareImageForAttachment(source, 20 * 1024 * 1024); + if (!result.ok) throw new Error(result.reason); + expect(result.recompressed).toBe(true); + expect(result.imageSize).toEqual({ width: 2000, height: 1333 }); + await expectSameColors(result.file, source); + }); + + it("keeps Display P3 colors when the stash re-encodes a WebP", async () => { + const source = await makeImage("display-p3", "color(display-p3 0 1 0)", "image/webp"); + const result = await compressImageForStash( + source, + (await readFileAsDataUrl(source)).length - 1, + ); + if (!result.ok) throw new Error(result.reason); + expect(result.image.recompressed).toBe(true); + const stored = dataUrlToFile(result.image.dataUrl, "stash", result.image.mimeType); + await expectSameColors(stored, source); + }); + + it("keeps Display P3 colors when it converts a P3-tagged HEIC that the browser cannot decode", async () => { + const fixture = new Uint8Array(await (await fetch(heicUrl)).arrayBuffer()); + const fixtureResult = await prepareImageForAttachment( + new File([fixture], "photo.heic", { type: "image/heic" }), + 20 * 1024 * 1024, + ); + if (!fixtureResult.ok) throw new Error(fixtureResult.reason); + // The fixture declares unspecified primaries, so it decodes as sRGB. + const decoded = await readPixel(fixtureResult.file, true); + + const nclx = fixture.slice(); + const nclxOffset = nclx.findIndex( + (_, index) => new DataView(nclx.buffer).getUint32(index) === 0x6e636c78, + ); + new DataView(nclx.buffer).setUint16(nclxOffset + 4, 12); + const tagged = [ + nclx, + replaceHeicColorWithProfile(fixture, await readChromiumDisplayP3Profile()), + ]; + for (const heic of tagged) { + const result = await prepareImageForAttachment( + new File([heic], "photo.heic", { type: "image/heic" }), + 20 * 1024 * 1024, + ); + if (!result.ok) throw new Error(result.reason); + expectNear(await readPixel(result.file), decoded); + } + }); +}); diff --git a/apps/web/src/lib/imageCompression.ts b/apps/web/src/lib/imageCompression.ts index b876ceff6a44a..7e5485cabcee9 100644 --- a/apps/web/src/lib/imageCompression.ts +++ b/apps/web/src/lib/imageCompression.ts @@ -88,37 +88,198 @@ function findHeicMetadataBox( return null; } -async function validateHeicImageDimensions( - file: File, -): Promise { +// D50-adapted Display P3 primaries, as an ICC profile's rXYZ, gXYZ and bXYZ tags carry them. +const DISPLAY_P3_ICC_PRIMARIES = [ + [0x7258595a, 0.5151, 0.2412, -0.0011], + [0x6758595a, 0.292, 0.6922, 0.0419], + [0x6258595a, 0.1571, 0.0666, 0.7841], +] as const; + +function iccProfileIsDisplayP3(view: DataView, start: number, end: number): boolean { + if (start + 132 > end) return false; + const tagCount = Math.min(view.getUint32(start + 128), Math.floor((end - start - 132) / 12)); + let matched = 0; + for (let index = 0; index < tagCount; index += 1) { + const entry = start + 132 + index * 12; + const primary = DISPLAY_P3_ICC_PRIMARIES.find( + ([signature]) => signature === view.getUint32(entry), + ); + if (!primary) continue; + const tag = start + view.getUint32(entry + 4); + if (tag < start || tag + 20 > end || view.getUint32(tag) !== 0x58595a20) return false; + for (let axis = 0; axis < 3; axis += 1) { + if (Math.abs(view.getInt32(tag + 8 + axis * 4) / 65536 - primary[axis + 1]!) > 0.005) { + return false; + } + } + matched += 1; + } + return matched === DISPLAY_P3_ICC_PRIMARIES.length; +} + +/** `colr` is an nclx code point (12 is Display P3) or an embedded ICC profile. */ +function heicColorIsDisplayP3(view: DataView, box: HeicMetadataBox): boolean { + if (box.payloadOffset + 6 > box.endOffset) return false; + const colorType = view.getUint32(box.payloadOffset); + if (colorType === 0x6e636c78) return view.getUint16(box.payloadOffset + 4) === 12; + if (colorType === 0x70726f66 || colorType === 0x72494343) { + return iccProfileIsDisplayP3(view, box.payloadOffset + 4, box.endOffset); + } + return false; +} + +type HeicMetadataResult = + | { ok: true; displayP3: boolean } + | { ok: false; reason: ImageCompressionFailureReason }; + +async function readHeicMetadata(file: File): Promise { + const unreadable = { ok: false, reason: "unreadable" } as const; const metadata = await file.slice(0, MAX_HEIC_METADATA_BYTES).arrayBuffer(); const view = new DataView(metadata); const meta = findHeicMetadataBox(view, 0, view.byteLength, 0x6d657461); - if (!meta || meta.payloadOffset + 4 > meta.endOffset) return "unreadable"; + if (!meta || meta.payloadOffset + 4 > meta.endOffset) return unreadable; const properties = findHeicMetadataBox(view, meta.payloadOffset + 4, meta.endOffset, 0x69707270); - if (!properties) return "unreadable"; + if (!properties) return unreadable; const containers = findHeicMetadataBox( view, properties.payloadOffset, properties.endOffset, 0x6970636f, ); - if (!containers) return "unreadable"; + if (!containers) return unreadable; let offset = containers.payloadOffset; let foundImageDimensions = false; while (offset < containers.endOffset) { const image = findHeicMetadataBox(view, offset, containers.endOffset, 0x69737065); if (!image) break; - if (image.payloadOffset + 12 > image.endOffset) return "unreadable"; + if (image.payloadOffset + 12 > image.endOffset) return unreadable; const width = view.getUint32(image.payloadOffset + 4); const height = view.getUint32(image.payloadOffset + 8); - if (width === 0 || height === 0) return "unreadable"; - if (width > MAX_HEIC_DECODE_PIXELS / height) return "too-large"; + if (width === 0 || height === 0) return unreadable; + if (width > MAX_HEIC_DECODE_PIXELS / height) return { ok: false, reason: "too-large" }; foundImageDimensions = true; offset = image.endOffset; } - return foundImageDimensions ? null : "unreadable"; + if (!foundImageDimensions) return unreadable; + + let displayP3 = false; + offset = containers.payloadOffset; + while (!displayP3 && offset < containers.endOffset) { + const color = findHeicMetadataBox(view, offset, containers.endOffset, 0x636f6c72); + if (!color) break; + displayP3 = heicColorIsDisplayP3(view, color); + offset = color.endOffset; + } + return { ok: true, displayP3 }; +} + +async function inflateIccProfile(deflated: Uint8Array): Promise { + const reader = new Blob([deflated]) + .stream() + .pipeThrough(new DecompressionStream("deflate")) + .getReader(); + const chunks: Uint8Array[] = []; + let length = 0; + try { + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + length += value.length; + // A real profile is a few KiB; refuse to inflate a compression bomb. + if (length > MAX_HEIC_METADATA_BYTES) return null; + chunks.push(value); + } + } catch { + return null; + } finally { + void reader.cancel().catch(() => undefined); + } + const profile = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { + profile.set(chunk, offset); + offset += chunk.length; + } + return profile; +} + +function iccProfileBytesAreDisplayP3(profile: Uint8Array): boolean { + return iccProfileIsDisplayP3( + new DataView(profile.buffer, profile.byteOffset, profile.byteLength), + 0, + profile.byteLength, + ); +} + +async function pngIsDisplayP3(bytes: Uint8Array, view: DataView): Promise { + for (let offset = 8; offset + 8 <= bytes.length;) { + const length = view.getUint32(offset); + const type = view.getUint32(offset + 4); + const data = offset + 8; + if (type === 0x49444154 || data + length > bytes.length) return false; + if (type === 0x63494350) return length >= 1 && bytes[data] === 12; + if (type === 0x69434350) { + const nameEnd = bytes.subarray(data, data + Math.min(length, 80)).indexOf(0); + if (nameEnd < 0) return false; + const profile = await inflateIccProfile(bytes.slice(data + nameEnd + 2, data + length)); + return profile !== null && iccProfileBytesAreDisplayP3(profile); + } + offset = data + length + 4; + } + return false; +} + +const JPEG_ICC_SIGNATURE = "ICC_PROFILE\0"; + +function jpegIsDisplayP3(bytes: Uint8Array, view: DataView): boolean { + const segments: Uint8Array[] = []; + for (let offset = 2; offset + 4 <= bytes.length && bytes[offset] === 0xff;) { + const marker = bytes[offset + 1]!; + if (marker === 0xda || marker === 0xd9) break; + const length = view.getUint16(offset + 2); + const end = offset + 2 + length; + if (length < 2 || end > bytes.length) break; + const signature = String.fromCharCode(...bytes.subarray(offset + 4, offset + 16)); + if (marker === 0xe2 && signature === JPEG_ICC_SIGNATURE) { + segments.push(bytes.subarray(offset + 18, end)); + } + offset = end; + } + if (segments.length === 0) return false; + const profile = new Uint8Array(segments.reduce((total, segment) => total + segment.length, 0)); + let offset = 0; + for (const segment of segments) { + profile.set(segment, offset); + offset += segment.length; + } + return iccProfileBytesAreDisplayP3(profile); +} + +function webpIsDisplayP3(bytes: Uint8Array, view: DataView): boolean { + if (view.getUint32(8) !== 0x57454250) return false; + for (let offset = 12; offset + 8 <= bytes.length;) { + const type = view.getUint32(offset); + const length = view.getUint32(offset + 4, true); + const data = offset + 8; + if (data + length > bytes.length) return false; + if (type === 0x49434350) return iccProfileIsDisplayP3(view, data, data + length); + offset = data + length + (length % 2); + } + return false; +} + +/** Re-encode on a canvas in the source's own color space, so it keeps its gamut and profile. */ +async function readImageColorSpace(file: Blob): Promise { + const bytes = new Uint8Array(await file.slice(0, MAX_HEIC_METADATA_BYTES).arrayBuffer()); + if (bytes.length < 16) return "srgb"; + const view = new DataView(bytes.buffer); + const signature = view.getUint32(0); + let displayP3 = false; + if (signature === 0x89504e47) displayP3 = await pngIsDisplayP3(bytes, view); + else if (signature >>> 16 === 0xffd8) displayP3 = jpegIsDisplayP3(bytes, view); + else if (signature === 0x52494646) displayP3 = webpIsDisplayP3(bytes, view); + return displayP3 ? "display-p3" : "srgb"; } export function readFileAsDataUrl(file: Blob): Promise { @@ -173,10 +334,14 @@ interface Canvas2D { context: OffscreenCanvasRenderingContext2D | CanvasRenderingContext2D; } -function createCanvas(width: number, height: number): Canvas2D | null { +function createCanvas( + width: number, + height: number, + colorSpace: PredefinedColorSpace, +): Canvas2D | null { if (typeof OffscreenCanvas === "function") { const canvas = new OffscreenCanvas(width, height); - const context = canvas.getContext("2d"); + const context = canvas.getContext("2d", { colorSpace }); if (!context) return null; return { canvas, context }; } @@ -184,7 +349,7 @@ function createCanvas(width: number, height: number): Canvas2D | null { const canvas = document.createElement("canvas"); canvas.width = width; canvas.height = height; - const context = canvas.getContext("2d"); + const context = canvas.getContext("2d", { colorSpace }); if (!context) return null; return { canvas, context }; } @@ -250,8 +415,9 @@ async function renderComposerImageThumbnail(file: File): Promise if (!canRecompress() || file.size > MAX_COMPRESSIBLE_SOURCE_BYTES) return null; let bitmap: ImageBitmap | undefined; try { + const colorSpace = await readImageColorSpace(file); bitmap = await createImageBitmap(file); - return await renderComposerImageThumbnailFromBitmap(bitmap); + return await renderComposerImageThumbnailFromBitmap(bitmap, colorSpace); } catch { return null; } finally { @@ -259,12 +425,15 @@ async function renderComposerImageThumbnail(file: File): Promise } } -async function renderComposerImageThumbnailFromBitmap(bitmap: ImageBitmap): Promise { +async function renderComposerImageThumbnailFromBitmap( + bitmap: ImageBitmap, + colorSpace: PredefinedColorSpace, +): Promise { try { const side = Math.min(bitmap.width, bitmap.height); if (side <= 0) return null; const dimension = Math.min(256, side); - const surface = createCanvas(dimension, dimension); + const surface = createCanvas(dimension, dimension, colorSpace); if (!surface) return null; surface.context.drawImage( bitmap, @@ -286,6 +455,7 @@ async function renderComposerImageThumbnailFromBitmap(bitmap: ImageBitmap): Prom async function encodeWithinBudget( bitmap: ImageBitmap, + colorSpace: PredefinedColorSpace, maxDimension: number, budgetChars: number, preferredMimeType?: "image/jpeg", @@ -293,7 +463,7 @@ async function encodeWithinBudget( const scale = Math.min(1, maxDimension / Math.max(bitmap.width, bitmap.height)); const width = Math.max(1, Math.round(bitmap.width * scale)); const height = Math.max(1, Math.round(bitmap.height * scale)); - const target = createCanvas(width, height); + const target = createCanvas(width, height, colorSpace); if (!target) return null; // Probe the codec before drawing; JPEG needs a white matte because it has no alpha. @@ -333,7 +503,9 @@ async function reencodeWithinBudget( } let bitmap: ImageBitmap; + let colorSpace: PredefinedColorSpace; try { + colorSpace = await readImageColorSpace(file); bitmap = await createImageBitmap(file); } catch { return { ok: false, reason: "unreadable" }; @@ -347,7 +519,13 @@ async function reencodeWithinBudget( const targetDimension = Math.max(1, Math.round(baseDimension * dimensionScale)); let encoded: Awaited>; try { - encoded = await encodeWithinBudget(bitmap, targetDimension, budgetChars, preferredMimeType); + encoded = await encodeWithinBudget( + bitmap, + colorSpace, + targetDimension, + budgetChars, + preferredMimeType, + ); } catch { encodeFailed = true; continue; @@ -415,7 +593,7 @@ async function fitImageToMaxEdge(file: File): Promise<{ file: File; imageSize: I bitmap = await createImageBitmap(file, { imageOrientation: "from-image" }); const imageSize = fitImageAttachmentSize(bitmap); if (!imageSize) return null; - const target = createCanvas(imageSize.width, imageSize.height); + const target = createCanvas(imageSize.width, imageSize.height, await readImageColorSpace(file)); if (!target) return null; target.context.imageSmoothingQuality = "high"; target.context.drawImage(bitmap, 0, 0, imageSize.width, imageSize.height); @@ -494,6 +672,17 @@ function prepareHeicImage(file: File) { return preparation; } +async function readPixelsAsDisplayP3( + bitmap: ImageBitmap, + { width, height }: ImageSize, +): Promise { + const raw = createCanvas(width, height, "srgb"); + if (!raw) return undefined; + raw.context.drawImage(bitmap, 0, 0, width, height); + const pixels = raw.context.getImageData(0, 0, width, height); + return createImageBitmap(new ImageData(pixels.data, width, height, { colorSpace: "display-p3" })); +} + async function convertHeicImage( file: File, onThumbnail: (src: string | null) => void, @@ -504,14 +693,13 @@ async function convertHeicImage( let bitmap: ImageBitmap | undefined; try { - const dimensionError = await validateHeicImageDimensions(file); - if (dimensionError) { - return { ok: false, reason: dimensionError }; - } + const metadata = await readHeicMetadata(file); + if (!metadata.ok) return metadata; bitmap = typeof createImageBitmap === "function" ? await createImageBitmap(file).catch(() => undefined) : undefined; + const decodedNatively = bitmap !== undefined; if (!bitmap) { const { heicTo } = await import("heic-to/csp"); bitmap = await heicTo({ blob: file, type: "bitmap" }); @@ -520,12 +708,20 @@ async function convertHeicImage( width: bitmap.width, height: bitmap.height, }; - const surface = createCanvas(imageSize.width, imageSize.height); + // heic-to ignores the color profile and hands back the raw Display P3 values as sRGB. + if (!decodedNatively && metadata.displayP3) { + const source = bitmap; + bitmap = await readPixelsAsDisplayP3(source, imageSize); + source.close(); + if (!bitmap) return { ok: false, reason: "unreadable" }; + } + const colorSpace = metadata.displayP3 ? "display-p3" : "srgb"; + const surface = createCanvas(imageSize.width, imageSize.height, colorSpace); if (!surface) return { ok: false, reason: "unreadable" }; surface.context.drawImage(bitmap, 0, 0, imageSize.width, imageSize.height); const [converted] = await Promise.all([ encodeCanvas(surface.canvas, QUALITY_STEPS[0], "image/jpeg"), - renderComposerImageThumbnailFromBitmap(bitmap).then(onThumbnail), + renderComposerImageThumbnailFromBitmap(bitmap, colorSpace).then(onThumbnail), ]); if (!converted) return { ok: false, reason: "unreadable" }; return { From 1a9a858d457340dfb7007b66171eec50a6f3f75e Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:01:48 +0100 Subject: [PATCH 063/324] fix(keybindings): preserve sibling shortcuts when editing an inherited rule (#40525) Co-authored-by: Julius Marminge --- apps/server/src/keybindings.test.ts | 142 +++++++++++++++++- apps/server/src/keybindings.ts | 55 +++++-- ...ng-default-shortcut-keeps-the-other.e2e.ts | 59 ++++++++ 3 files changed, 241 insertions(+), 15 deletions(-) create mode 100644 scripts/scenarios/editing-default-shortcut-keeps-the-other.e2e.ts diff --git a/apps/server/src/keybindings.test.ts b/apps/server/src/keybindings.test.ts index c404fef75ad52..7e846811e1440 100644 --- a/apps/server/src/keybindings.test.ts +++ b/apps/server/src/keybindings.test.ts @@ -446,16 +446,154 @@ it.layer(NodeServices.layer)("keybindings", (it) => { }).pipe(Effect.provide(layerKeybindings())), ); - it.effect("unassigns a shortcut without restoring it on startup and can reassign it", () => + it.effect("preserves sibling shortcuts when editing an inherited shortcut", () => + Effect.gen(function* () { + const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig; + const keybindings = yield* Keybindings.Keybindings; + const target = { key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" } as const; + const sibling = { ...target, key: "mod+n" }; + const unrelated = { ...sibling, command: "threadPanel.toggle" } as const; + yield* writeKeybindingsConfig(keybindingsConfigPath, [unrelated]); + + const replacement = { ...target, key: "f8" }; + const saved = yield* keybindings.upsertKeybindingRule({ + ...replacement, + replace: { ...target, key: "Shift+Mod+O", when: "!(terminalFocus)" }, + }); + const relevant = (rule: (typeof saved.keybindings)[number]) => + rule.command === target.command || rule.command === unrelated.command; + const expected = SharedKeybindings.compileResolvedKeybindingsConfig([ + sibling, + unrelated, + replacement, + ]); + assert.deepEqual(saved.keybindings.filter(relevant), expected); + + yield* keybindings.syncDefaultKeybindingsOnStartup; + const snapshot = yield* keybindings.getSnapshot; + assert.deepEqual(snapshot.keybindings.filter(relevant), expected); + }).pipe(Effect.provide(layerKeybindings())), + ); + + it.effect("preserves sibling shortcuts when adding to an inherited command", () => + Effect.gen(function* () { + const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig; + const keybindings = yield* Keybindings.Keybindings; + yield* writeKeybindingsConfig(keybindingsConfigPath, []); + + const added = { key: "f9", command: "chat.new" } as const; + const saved = yield* keybindings.upsertKeybindingRule(added); + assert.deepEqual( + saved.keybindings.filter((rule) => rule.command === added.command), + SharedKeybindings.compileResolvedKeybindingsConfig([ + { key: "mod+n", command: added.command, when: "!terminalFocus" }, + { key: "mod+shift+o", command: added.command, when: "!terminalFocus" }, + added, + ]), + ); + }).pipe(Effect.provide(layerKeybindings())), + ); + + it.effect("preserves sibling shortcuts by rejecting an edit that would evict saved rules", () => Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig; + const keybindings = yield* Keybindings.Keybindings; + const original = JSON.stringify([ + { key: "f7", command: "terminal.new" }, + ...Array.from({ length: MAX_KEYBINDINGS_COUNT - 2 }, (_, index) => ({ + key: "f1", + command: `future.command-${index}`, + })), + ]); + yield* fs.writeFileString(keybindingsConfigPath, original); + + const target = { key: "mod+n", command: "chat.new", when: "!terminalFocus" } as const; + const result = yield* toDetailResult( + keybindings.upsertKeybindingRule({ ...target, key: "f8", replace: target }), + ); + assertFailure(result, "Not enough room to save this shortcut and its inherited shortcuts."); + assert.equal(yield* fs.readFileString(keybindingsConfigPath), original); + }).pipe(Effect.provide(layerKeybindings())), + ); + + it.effect("preserves sibling shortcuts only if visible within the binding limit", () => + Effect.gen(function* () { + const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig; + const keybindings = yield* Keybindings.Keybindings; yield* writeKeybindingsConfig( keybindingsConfigPath, - Array.from({ length: MAX_KEYBINDINGS_COUNT }, (_, index) => ({ + Array.from({ length: 210 }, (_, index) => ({ key: "mod+alt+f1", command: `script.filler-${index}.run` as const, })), ); + + const target = { key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" } as const; + const local = { ...target, key: "mod+shift+n", command: "chat.newLocal" } as const; + const relevant = (rule: { readonly command: KeybindingCommand }) => + rule.command === target.command || rule.command === local.command; + const before = yield* keybindings.getSnapshot; + assert.deepEqual( + before.keybindings.filter(relevant), + SharedKeybindings.compileResolvedKeybindingsConfig([target, local]), + ); + + const replacement = { ...target, key: "f8" }; + const saved = yield* keybindings.upsertKeybindingRule({ ...replacement, replace: target }); + assert.deepEqual( + saved.keybindings.filter(relevant), + SharedKeybindings.compileResolvedKeybindingsConfig([local, replacement]), + ); + }).pipe(Effect.provide(layerKeybindings())), + ); + + it.effect( + "preserves sibling shortcuts when an inherited edit target has since become hidden", + () => + Effect.gen(function* () { + const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig; + const keybindings = yield* Keybindings.Keybindings; + yield* writeKeybindingsConfig( + keybindingsConfigPath, + Array.from({ length: 209 }, (_, index) => ({ + key: "mod+alt+f1", + command: `script.filler-${index}.run` as const, + })), + ); + + const target = { key: "mod+n", command: "chat.new", when: "!terminalFocus" } as const; + const sibling = { ...target, key: "mod+shift+o" }; + const isChatNew = (binding: { readonly command: KeybindingCommand }) => + binding.command === target.command; + const before = yield* keybindings.getSnapshot; + assert.deepEqual( + before.keybindings.filter(isChatNew), + SharedKeybindings.compileResolvedKeybindingsConfig([target, sibling]), + ); + + const afterUnrelatedSave = yield* keybindings.upsertKeybindingRule({ + key: "mod+alt+f1", + command: "script.extra.run", + }); + assert.deepEqual( + afterUnrelatedSave.keybindings.filter(isChatNew), + SharedKeybindings.compileResolvedKeybindingsConfig([sibling]), + ); + + const replacement = { ...target, key: "f8" }; + const saved = yield* keybindings.upsertKeybindingRule({ ...replacement, replace: target }); + assert.deepEqual( + saved.keybindings.filter(isChatNew), + SharedKeybindings.compileResolvedKeybindingsConfig([sibling, replacement]), + ); + }).pipe(Effect.provide(layerKeybindings())), + ); + + it.effect("unassigns a shortcut without restoring it on startup and can reassign it", () => + Effect.gen(function* () { + const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig; + yield* writeKeybindingsConfig(keybindingsConfigPath, []); const keybindings = yield* Keybindings.Keybindings; const target = SharedKeybindings.DEFAULT_KEYBINDINGS.find( (rule) => rule.command === "composer.sendBackground", diff --git a/apps/server/src/keybindings.ts b/apps/server/src/keybindings.ts index d3d0fa5cbebd6..d9a6a8dbf01d3 100644 --- a/apps/server/src/keybindings.ts +++ b/apps/server/src/keybindings.ts @@ -174,6 +174,7 @@ const decodeKeybindingRuleExit = Schema.decodeUnknownExit(KeybindingRule); const decodeResolvedKeybindingFromConfigExit = Schema.decodeExit(ResolvedKeybindingFromConfig); const decodeRawKeybindingsEntriesExit = Schema.decodeUnknownExit(RawKeybindingsEntries); const encodeRawKeybindingsEntriesPrettyJson = Schema.encodeEffect(RawKeybindingsEntriesPrettyJson); +const isSameResolvedKeybindingRule = Schema.toEquivalence(ResolvedKeybindingRule); export interface KeybindingsConfigState { readonly keybindings: ResolvedKeybindingsConfig; @@ -669,15 +670,34 @@ const make = Effect.gen(function* () { const customConfig = yield* loadWritableCustomKeybindingsConfig(); const rule = keybindingRuleFromInput(input); const replaceTarget = replaceTargetFromUpsertInput(input); - const siblingDefaults = - rule.when === "false" && - replaceTarget && - !customConfig.some(({ rule: entry }) => entry?.command === rule.command) - ? DEFAULT_KEYBINDINGS.filter( - (entry) => - entry.command === rule.command && !isSameKeybindingRule(entry, replaceTarget), - ).map((entry) => ({ value: entry, rule: entry })) - : []; + // A saved rule overrides every inherited default for its command. + let siblingDefaults: ReadonlyArray = []; + if ( + (!replaceTarget || + (replaceTarget.command === rule.command && + DEFAULT_KEYBINDINGS.some((entry) => isSameKeybindingRule(entry, replaceTarget)))) && + !customConfig.some(({ rule: entry }) => entry?.command === rule.command) && + decodeResolvedKeybindingFromConfigExit(rule)._tag === "Success" + ) { + const customRules = customConfig.flatMap(({ rule: entry }) => (entry ? [entry] : [])); + const visibleBindings = mergeWithDefaultKeybindings( + compileResolvedKeybindingsConfig(customRules), + ).filter((entry) => entry.command === rule.command); + siblingDefaults = DEFAULT_KEYBINDINGS.filter((entry) => { + if ( + entry.command !== rule.command || + (replaceTarget && isSameKeybindingRule(entry, replaceTarget)) || + isSameKeybindingRule(entry, rule) + ) { + return false; + } + const resolved = compileResolvedKeybindingRule(entry); + return ( + resolved && + visibleBindings.some((binding) => isSameResolvedKeybindingRule(binding, resolved)) + ); + }); + } const retainedConfig = customConfig.filter(({ rule: entry }) => { if (!entry) return true; return ( @@ -685,11 +705,20 @@ const make = Effect.gen(function* () { !isSameKeybindingRule(entry, rule) ); }); - const availableSlots = MAX_KEYBINDINGS_COUNT - siblingDefaults.length - 1; + const availableSlots = MAX_KEYBINDINGS_COUNT - 1; + if ( + siblingDefaults.length > 0 && + retainedConfig.length + siblingDefaults.length > availableSlots + ) { + return yield* new KeybindingsConfigError({ + configPath: keybindingsConfigPath, + detail: "Not enough room to save this shortcut and its inherited shortcuts.", + }); + } const nextConfig = [ ...siblingDefaults, - ...retainedConfig.slice(-availableSlots), - { value: rule, rule }, + ...retainedConfig.slice(-availableSlots).map(({ value }) => value), + rule, ]; if (retainedConfig.length > availableSlots) { yield* Effect.logWarning("truncating keybindings config to max entries", { @@ -697,7 +726,7 @@ const make = Effect.gen(function* () { maxEntries: MAX_KEYBINDINGS_COUNT, }); } - yield* writeConfigAtomically(nextConfig.map(({ value }) => value)); + yield* writeConfigAtomically(nextConfig); return yield* reloadAndEmit; }), ), diff --git a/scripts/scenarios/editing-default-shortcut-keeps-the-other.e2e.ts b/scripts/scenarios/editing-default-shortcut-keeps-the-other.e2e.ts new file mode 100644 index 0000000000000..f2c75d5c34d29 --- /dev/null +++ b/scripts/scenarios/editing-default-shortcut-keeps-the-other.e2e.ts @@ -0,0 +1,59 @@ +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; + +import { T3_HOME } from "../e2e.config.ts"; +import { runPromise, test, WEB } from "./t3.ts"; + +test( + "Editing one inherited shortcut keeps the other shortcut for the same command", + WEB, + async ({ t3, app, screen }) => { + await t3.project("inherited-shortcuts"); + const keybindingsPath = `${T3_HOME}/userdata/keybindings.json`; + const original = await runPromise( + Effect.flatMap(FileSystem.FileSystem, (fs) => fs.readFileString(keybindingsPath)), + ); + + try { + await runPromise( + Effect.flatMap(FileSystem.FileSystem, (fs) => + fs.writeFileString( + keybindingsPath, + '[{ "key": "enter", "command": "commandPalette.toggle", "when": "!rightPanelOpen" }]\n', + ), + ), + ); + await t3.open("/settings/keybindings"); + const search = screen.getByLabel("Search keybindings"); + await search.fill("Command Palette"); + await screen + .getByRole("button", "Edit shortcut for Command Palette: Toggle: Enter") + .waitFor(); + + await search.fill("Chat: New"); + const unchanged = screen.getByRole("button", "Edit shortcut for Chat: New: Ctrl+N", { + exact: true, + }); + await unchanged.waitFor(); + await screen.getByRole("button", "Edit shortcut for Chat: New: Ctrl+Shift+O").tap(); + await screen.getByRole("textbox", "Keybinding for Chat: New", { exact: true }).press("F8"); + await screen.getByRole("button", "Save", { exact: true }).tap(); + await screen + .getByRole("button", "Edit shortcut for Chat: New: F8", { exact: true }) + .waitFor(); + + try { + await expect(unchanged).toBeVisible(); + } finally { + await app.screenshot("chat-new-shortcuts-after-edit"); + } + } finally { + await runPromise( + Effect.flatMap(FileSystem.FileSystem, (fs) => + fs.writeFileString(keybindingsPath, original), + ), + ); + } + }, +); From 464e8f7e607a034d41b689e93cac727de7c49d89 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:14:51 +0100 Subject: [PATCH 064/324] fix: keep paged linked thread history when reopening the same snapshot (#40545) Co-authored-by: Julius Marminge --- .../client-runtime/src/linkedThread.test.ts | 79 ++++++- packages/client-runtime/src/linkedThread.ts | 202 ++++++++++++++---- .../src/state/orchestrationV2TestFixtures.ts | 37 ++++ .../src/state/peerLinks.test.ts | 124 ++++++++++- .../client-runtime/src/state/peerLinks.ts | 32 +-- .../src/state/threadHistoryMerge.test.ts | 7 +- .../src/state/threadHistoryMerge.ts | 5 + .../client-runtime/src/state/threadStream.ts | 18 +- 8 files changed, 445 insertions(+), 59 deletions(-) diff --git a/packages/client-runtime/src/linkedThread.test.ts b/packages/client-runtime/src/linkedThread.test.ts index 8b2d4e105e5b1..2004f514df4a4 100644 --- a/packages/client-runtime/src/linkedThread.test.ts +++ b/packages/client-runtime/src/linkedThread.test.ts @@ -20,7 +20,7 @@ import { LINKED_THREAD_RETRY_MS, type LinkedThreadView, } from "./linkedThread.ts"; -import { v2Now, v2Projection } from "./state/orchestrationV2TestFixtures.ts"; +import { v2MessageRow, v2Now, v2Projection } from "./state/orchestrationV2TestFixtures.ts"; const snapshot = ( snapshotSequence: number, @@ -163,6 +163,83 @@ it.effect("loads the turns before a snapshot's window once per request", () => }).pipe(Effect.scoped), ); +it.effect("brings back the turns a closed view had loaded when it opens again", () => + Effect.gen(function* () { + const older = v2MessageRow("Older", 1); + const recent = v2MessageRow("Recent", 2); + const latest = v2MessageRow("Latest", 3); + const window = ( + snapshotSequence: number, + historyCursor: string, + row: typeof recent, + ): OrchestrationV2ThreadStreamItem => ({ + kind: "snapshot", + snapshotSequence, + projection: { ...v2Projection, turnItems: [row.item], visibleTurnItems: [row] }, + historyCursor, + hasMoreHistory: true, + }); + const pages: Record> = { + "before-recent": { items: [older], nextCursor: "before-older" }, + "before-latest": { items: [recent], nextCursor: "before-recent" }, + }; + const asked: string[] = []; + const follow = ( + items: ReadonlyArray, + previous: LinkedThreadView | null, + ) => + Effect.gen(function* () { + const views = yield* Queue.unbounded(); + yield* followLinkedThread({ + items: Stream.fromIterable(items).pipe(Stream.concat(Stream.never)), + historyPage: (cursor) => + Effect.sync(() => { + asked.push(cursor); + return { ...pages[cursor]!, snapshotSequence: 3, hasMoreHistory: true }; + }), + previous, + }).pipe( + Stream.runForEach((view) => Queue.offer(views, view)), + Effect.forkScoped, + ); + return views; + }); + const settled = Effect.fnUntraced(function* (views: Queue.Queue) { + let view = yield* Queue.take(views); + while (view.history.loading) view = yield* Queue.take(views); + return view; + }); + const rows = (view: LinkedThreadView) => + view.thread.projection?.visibleTurnItems.map((row) => row.sourceItemId); + + const first = yield* follow([window(1, "before-recent", recent), retitled(2, "Renamed")], null); + (yield* Queue.take(first)).loadEarlier(); + yield* Queue.take(first); // Loading. + yield* Queue.take(first); // The earlier page. + const closed = yield* Queue.take(first); + expect([rows(closed), closed.thread.sequence]).toEqual([ + [older.sourceItemId, recent.sourceItemId], + 2, + ]); + + // Nothing changed while the view was closed: the rows it held are shown as they were. + const same = yield* settled(yield* follow([window(2, "before-recent", recent)], closed)); + expect([rows(same), same.thread.historyCursor]).toEqual([ + [older.sourceItemId, recent.sourceItemId], + "before-older", + ]); + expect(asked).toEqual(["before-recent"]); + + // The thread moved on: pages are read again until the oldest row it showed is back. + const moved = yield* settled(yield* follow([window(3, "before-latest", latest)], closed)); + expect([rows(moved), moved.thread.historyCursor]).toEqual([ + [older.sourceItemId, recent.sourceItemId, latest.sourceItemId], + "before-older", + ]); + expect(asked).toEqual(["before-recent", "before-latest", "before-recent"]); + }).pipe(Effect.scoped), +); + describe("connectLinkedEnvironment", () => { const lan = "http://192.168.1.20:3773"; const tailnet = "https://vm.tail.ts.net"; diff --git a/packages/client-runtime/src/linkedThread.ts b/packages/client-runtime/src/linkedThread.ts index 15364cddf54ea..69b179e08f671 100644 --- a/packages/client-runtime/src/linkedThread.ts +++ b/packages/client-runtime/src/linkedThread.ts @@ -1,5 +1,6 @@ import type { EnvironmentId, + OrchestrationV2ProjectedTurnItem, OrchestrationV2ThreadHistoryPage, OrchestrationV2ThreadProjection, OrchestrationV2ThreadStreamItem, @@ -8,6 +9,7 @@ import type { } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Queue from "effect/Queue"; +import * as Result from "effect/Result"; import * as Stream from "effect/Stream"; import { mFallback, msg } from "gt-i18n"; import type { MFunctionType } from "gt-i18n/types"; @@ -20,6 +22,7 @@ import { applyThreadHistoryPage, applyThreadStreamItem, initialThreadStreamState, + prependThreadHistory, type ThreadStreamState, } from "./state/threadStream.ts"; @@ -212,12 +215,38 @@ export function isLinkedThreadWorking(projection: OrchestrationV2ThreadProjectio /** How long a view waits before asking again for a thread whose environment did not answer. */ export const LINKED_THREAD_RETRY_MS = 15_000; +type HistoryAnchor = Pick; + +interface LinkedHistoryWindow { + readonly sequence: number; + readonly cursor: string; +} + +interface LinkedHistoryRequest { + readonly window: LinkedHistoryWindow; + readonly cursor: string; +} + +function includesHistoryAnchor(rows: ReadonlyArray, anchor: HistoryAnchor): boolean { + return rows.some( + (row) => + row.sourceThreadId === anchor.sourceThreadId && row.sourceItemId === anchor.sourceItemId, + ); +} + /** A linked thread as its view holds it: the thread's own stream, reduced as any thread's is. */ export interface LinkedThreadView { readonly thread: ThreadStreamState; /** Why the stream stopped, while the view waits to ask again; the next item clears it. */ readonly error: unknown; readonly history: { readonly loading: boolean; readonly failed: boolean }; + /** Pagination progress survives the temporary view that hides the cursor during reconnect. */ + readonly loadedHistory: { + readonly window: LinkedHistoryWindow; + readonly nextCursor: string | null; + /** The oldest row still to recover, even if a read fails or the view closes during backfill. */ + readonly restoreThrough: HistoryAnchor | null; + } | null; /** Loads the turns before the ones shown. Does nothing while a page loads or none is left. */ readonly loadEarlier: () => void; } @@ -233,7 +262,11 @@ export const keepLinkedThreadView = ( ): LinkedThreadView => next.thread.projection !== null || kept === null || kept.thread.projection === null ? next - : { ...next, thread: { ...kept.thread, historyCursor: null } }; + : { + ...next, + thread: { ...kept.thread, historyCursor: null }, + loadedHistory: kept.loadedHistory, + }; /** * Follows a linked environment's thread for as long as something consumes the result. The thread @@ -244,34 +277,100 @@ export const keepLinkedThreadView = ( export const followLinkedThread = (source: { readonly items: Stream.Stream; readonly historyPage: (cursor: string) => Effect.Effect; + readonly previous?: LinkedThreadView | null; }): Stream.Stream => Stream.unwrap( Effect.gen(function* () { - const requests = yield* Queue.unbounded(); + const requests = yield* Queue.unbounded(); let requested = false; - // Both halves below run one step at a time, so each reads the view the other left. + let previous = source.previous ?? null; + let snapshotWindow: LinkedHistoryWindow | null = null; + const requestPage = (window: LinkedHistoryWindow, cursor: string) => { + requested = true; + Queue.offerUnsafe(requests, { window, cursor }); + }; let view: LinkedThreadView = { thread: initialThreadStreamState, error: null, history: { loading: false, failed: false }, + loadedHistory: null, loadEarlier: () => { - if (requested || view.thread.historyCursor === null) return; - requested = true; - Queue.offerUnsafe(requests, undefined); + const cursor = view.thread.historyCursor; + if (requested || snapshotWindow === null || cursor === null) return; + requestPage(snapshotWindow, cursor); }, }; const show = (patch: Partial) => { view = { ...view, ...patch }; return view; }; - const attempt = (): Stream.Stream => + + const onItem = (item: OrchestrationV2ThreadStreamItem) => { + let thread = applyThreadStreamItem(view.thread, item); + if (item.kind !== "snapshot") return show({ thread, error: null }); + + const kept = view.thread.projection === null ? previous : view; + previous = null; + const loaded = kept?.loadedHistory; + const window = + thread.historyCursor === null + ? null + : { sequence: thread.sequence, cursor: thread.historyCursor }; + let loadedHistory: LinkedThreadView["loadedHistory"] = null; + if (window && kept?.thread.projection && loaded) { + // A live update can advance the revision and move the window without invalidating held rows. + if ( + kept.thread.sequence === window.sequence && + (window.sequence > loaded.window.sequence || window.cursor === loaded.window.cursor) + ) { + thread = prependThreadHistory( + thread, + { + items: kept.thread.projection.visibleTurnItems, + subagents: kept.thread.projection.subagents, + }, + loaded.nextCursor, + ); + loadedHistory = { ...loaded, window }; + } else if (window.sequence > kept.thread.sequence) { + const oldest = loaded.restoreThrough ?? kept.thread.projection.visibleTurnItems[0]; + if (oldest && !includesHistoryAnchor(item.projection.visibleTurnItems, oldest)) { + const { sourceThreadId, sourceItemId } = oldest; + loadedHistory = { + window, + nextCursor: window.cursor, + restoreThrough: { sourceThreadId, sourceItemId }, + }; + } + } + } + + snapshotWindow = window; + requested = false; + if (window && thread.historyCursor !== null && loadedHistory?.restoreThrough) { + requestPage(window, thread.historyCursor); + } else { + Queue.offerUnsafe(requests, null); + } + return show({ + thread, + loadedHistory, + history: { loading: requested, failed: false }, + error: null, + }); + }; + + const attempt = (): Stream.Stream< + | { readonly kind: "item"; readonly item: OrchestrationV2ThreadStreamItem } + | { readonly kind: "unreachable"; readonly error: E }, + E, + R + > => source.items.pipe( - Stream.map((item) => - show({ thread: applyThreadStreamItem(view.thread, item), error: null }), - ), + Stream.map((item) => ({ kind: "item" as const, item })), Stream.catch((error) => isLinkedThreadUnreachable(error) - ? Stream.make(show({ error })).pipe( + ? Stream.make({ kind: "unreachable" as const, error }).pipe( Stream.concat( Stream.unwrap(Effect.sleep(LINKED_THREAD_RETRY_MS).pipe(Effect.map(attempt))), ), @@ -279,38 +378,67 @@ export const followLinkedThread = (source: { : Stream.fail(error), ), ); + const earlier = Stream.fromQueue(requests).pipe( - Stream.flatMap(() => - Stream.suspend(() => { - const cursor = view.thread.historyCursor; - if (cursor === null) { - requested = false; - return Stream.empty; - } - return Stream.make(show({ history: { loading: true, failed: false } })).pipe( - Stream.concat( - Stream.fromEffect( - source.historyPage(cursor).pipe( - Effect.match({ - onSuccess: (page) => - show({ - thread: applyThreadHistoryPage(view.thread, cursor, page), - history: { loading: false, failed: false }, - }), - onFailure: () => show({ history: { loading: false, failed: true } }), - }), - Effect.ensuring( - Effect.sync(() => { - requested = false; - }), + Stream.switchMap((request) => + request === null + ? Stream.empty + : Stream.make({ kind: "loading" as const, request }).pipe( + Stream.concat( + Stream.fromEffect( + source.historyPage(request.cursor).pipe( + Effect.result, + Effect.map((page) => ({ kind: "page" as const, request, page })), ), ), ), ), - ); - }), ), ); - return Stream.merge(attempt(), earlier, { haltStrategy: "left" }); + + // Reduce snapshots, live items and history results in publication order. + return Stream.merge(attempt(), earlier, { haltStrategy: "left" }).pipe( + Stream.filterMap((update) => { + if (update.kind === "item") return Result.succeed(onItem(update.item)); + if (update.kind === "unreachable") return Result.succeed(show({ error: update.error })); + const { window, cursor } = update.request; + if (snapshotWindow !== window || view.thread.historyCursor !== cursor) { + return Result.failVoid; + } + if (update.kind === "loading") { + return view.history.loading + ? Result.failVoid + : Result.succeed(show({ history: { loading: true, failed: false } })); + } + requested = false; + const page = update.page; + if ( + Result.isFailure(page) || + page.success.snapshotSequence < window.sequence || + (page.success.hasMoreHistory && page.success.nextCursor === cursor) + ) { + return Result.succeed(show({ history: { loading: false, failed: true } })); + } + + const thread = applyThreadHistoryPage(view.thread, cursor, page.success); + let restoreThrough = view.loadedHistory?.restoreThrough ?? null; + const nextCursor = thread.historyCursor; + if ( + restoreThrough !== null && + (nextCursor === null || + includesHistoryAnchor(thread.projection?.visibleTurnItems ?? [], restoreThrough)) + ) { + restoreThrough = null; + } + if (restoreThrough !== null && nextCursor !== null) requestPage(window, nextCursor); + return Result.succeed( + show({ + thread, + loadedHistory: { window, nextCursor, restoreThrough }, + history: { loading: requested, failed: false }, + }), + ); + }), + ); }), ); diff --git a/packages/client-runtime/src/state/orchestrationV2TestFixtures.ts b/packages/client-runtime/src/state/orchestrationV2TestFixtures.ts index 550dc389a86bf..cf1ec01a4fc65 100644 --- a/packages/client-runtime/src/state/orchestrationV2TestFixtures.ts +++ b/packages/client-runtime/src/state/orchestrationV2TestFixtures.ts @@ -1,8 +1,11 @@ import { + MessageId, ProjectId, ProviderInstanceId, ThreadId, + TurnItemId, type OrchestrationProjectShell, + type OrchestrationV2ProjectedTurnItem, type OrchestrationV2ShellSnapshot, type OrchestrationV2ThreadProjection, type OrchestrationV2ThreadShell, @@ -101,6 +104,40 @@ export const v2Projection: OrchestrationV2ThreadProjection = { updatedAt: v2Now, }; +/** A completed user message row of `v2ThreadId`, identified by its text. */ +export function v2MessageRow(text: string, ordinal: number): OrchestrationV2ProjectedTurnItem { + const itemId = TurnItemId.make(text); + return { + position: 0, + visibility: "local", + sourceThreadId: v2ThreadId, + sourceItemId: itemId, + item: { + id: itemId, + threadId: v2ThreadId, + runId: null, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal, + status: "completed", + title: null, + startedAt: v2Now, + completedAt: v2Now, + updatedAt: v2Now, + type: "user_message", + createdBy: "user", + creationSource: "web", + messageId: MessageId.make(text), + inputIntent: "turn_start", + text, + attachments: [], + }, + }; +} + export const v2ShellSnapshot: OrchestrationV2ShellSnapshot = { schemaVersion: 1, snapshotSequence: 0, diff --git a/packages/client-runtime/src/state/peerLinks.test.ts b/packages/client-runtime/src/state/peerLinks.test.ts index c1e4ae8acd9f9..75430e340fbff 100644 --- a/packages/client-runtime/src/state/peerLinks.test.ts +++ b/packages/client-runtime/src/state/peerLinks.test.ts @@ -1,8 +1,126 @@ -import { EnvironmentId, type PeerLinkSummary } from "@t3tools/contracts"; +import { + EnvironmentId, + WS_METHODS, + type OrchestrationV2ThreadHistoryPage, + type OrchestrationV2ThreadStreamItem, + type PeerLinkSummary, +} from "@t3tools/contracts"; +import { describe, expect, it } from "@effect/vitest"; import * as DateTime from "effect/DateTime"; -import { describe, expect, it } from "vite-plus/test"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Queue from "effect/Queue"; +import * as Stream from "effect/Stream"; +import * as SubscriptionRef from "effect/SubscriptionRef"; +import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; -import { linkThroughRoutes } from "./peerLinks.ts"; +import { EnvironmentRegistry } from "../connection/registry.ts"; +import { EnvironmentSupervisor } from "../connection/supervisor.ts"; +import type { LinkedThreadView } from "../linkedThread.ts"; +import type { RpcSession } from "../rpc/session.ts"; +import { v2MessageRow, v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts"; +import { createPeerLinkEnvironmentAtoms, linkThroughRoutes } from "./peerLinks.ts"; + +// regression: #40544 earlier messages vanished when a linked thread's view opened again +it.effect( + "keeps loaded messages when a linked thread's view opens again on the same snapshot", + () => + Effect.gen(function* () { + const recent = v2MessageRow("Recent message", 2); + const older = v2MessageRow("Earlier message", 1); + const snapshot = (historyCursor: string): OrchestrationV2ThreadStreamItem => ({ + kind: "snapshot", + snapshotSequence: 7, + projection: { ...v2Projection, turnItems: [recent.item], visibleTurnItems: [recent] }, + historyCursor, + hasMoreHistory: true, + }); + const subscriptions = yield* Queue.unbounded<{ + items: Queue.Queue; + stopped: Deferred.Deferred; + }>(); + const requested: string[] = []; + const client = { + [WS_METHODS.peerLinksSubscribeThread]: () => + Stream.unwrap( + Effect.gen(function* () { + const items = yield* Queue.unbounded(); + const stopped = yield* Deferred.make(); + yield* Effect.addFinalizer(() => Deferred.succeed(stopped, undefined)); + yield* Queue.offer(subscriptions, { items, stopped }); + return Stream.fromQueue(items); + }), + ), + [WS_METHODS.peerLinksThreadHistoryPage]: ({ cursor }: { cursor: string }) => + Effect.sync((): OrchestrationV2ThreadHistoryPage => { + requested.push(cursor); + return cursor === "before-recent" + ? { + snapshotSequence: 7, + items: [older], + nextCursor: "before-earlier", + hasMoreHistory: true, + } + : { snapshotSequence: 7, items: [], nextCursor: null, hasMoreHistory: false }; + }), + } as unknown as RpcSession["client"]; + const target = { + environmentId: EnvironmentId.make("via"), + input: { environmentId: EnvironmentId.make("linked"), threadId: v2ThreadId }, + }; + const supervisor = EnvironmentSupervisor.of({ + target: { environmentId: target.environmentId, label: "Via" }, + session: yield* SubscriptionRef.make(Option.some({ client })), + } as unknown as EnvironmentSupervisor["Service"]); + const environment = EnvironmentRegistry.of({ + followStream: (_id, stream) => + Stream.provideService(stream, EnvironmentSupervisor, supervisor), + } as Pick as EnvironmentRegistry["Service"]); + const links = createPeerLinkEnvironmentAtoms( + Atom.runtime(Layer.succeed(EnvironmentRegistry, environment)), + ); + const registry = yield* Effect.acquireRelease( + Effect.sync(() => AtomRegistry.make()), + (registry) => Effect.sync(() => registry.dispose()), + ); + const views = yield* Queue.unbounded(); + const open = () => + registry.subscribe(links.threadView(target), (result) => { + if (AsyncResult.isSuccess(result)) Queue.offerUnsafe(views, result.value); + }); + const visibleMessages = (view: LinkedThreadView) => + view.thread.projection?.visibleTurnItems.map((row) => row.sourceItemId); + + const unmount = open(); + const first = yield* Queue.take(subscriptions); + yield* Queue.offer(first.items, snapshot("before-recent")); + (yield* Queue.take(views)).loadEarlier(); + yield* Queue.take(views); // Loading. + expect(visibleMessages(yield* Queue.take(views))).toEqual([ + older.sourceItemId, + recent.sourceItemId, + ]); + unmount(); + yield* Deferred.await(first.stopped); + + open(); + const reopened = yield* Queue.take(subscriptions); + yield* Queue.offer(reopened.items, snapshot("before-recent")); + const resumed = yield* Queue.take(views); + expect(visibleMessages(resumed)).toEqual([older.sourceItemId, recent.sourceItemId]); + // Paging goes on from where the closed view stopped, without reading the same page again. + expect(resumed.thread.historyCursor).toBe("before-earlier"); + expect(requested).toEqual(["before-recent"]); + + // A snapshot of another window replaces the rows held for the old one. + yield* Queue.offer(reopened.items, snapshot("new-window")); + const refreshed = yield* Queue.take(views); + expect(visibleMessages(refreshed)).toEqual([recent.sourceItemId]); + expect(refreshed.thread.historyCursor).toBe("new-window"); + }).pipe(Effect.scoped), +); const now = DateTime.makeUnsafe("2026-11-20T00:00:00.000Z"); const id = (value: string) => EnvironmentId.make(value); diff --git a/packages/client-runtime/src/state/peerLinks.ts b/packages/client-runtime/src/state/peerLinks.ts index 543fd55887139..fd9d269bfd726 100644 --- a/packages/client-runtime/src/state/peerLinks.ts +++ b/packages/client-runtime/src/state/peerLinks.ts @@ -7,6 +7,7 @@ import { import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import * as Stream from "effect/Stream"; import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity"; import type { EnvironmentRegistry } from "../connection/registry.ts"; @@ -19,7 +20,7 @@ import { request, subscribe } from "../rpc/client.ts"; import { createEnvironmentRpcCommand, createEnvironmentRpcQueryAtomFamily, - createEnvironmentSubscriptionAtomFamily, + followStreamInEnvironment, } from "./runtime.ts"; /** The environment a client reads through, and the linked environment's thread it reads. */ @@ -54,16 +55,6 @@ export function createPeerLinkEnvironmentAtoms( registry.refresh(list({ environmentId, input: {} })); registry.refresh(names({ environmentId, input: {} })); }); - const threadStream = createEnvironmentSubscriptionAtomFamily(runtime, { - label: "environment-data:peer-links:thread-stream", - idleTtlMs: 0, - subscribe: (input: PeerLinkThreadInput) => - followLinkedThread({ - items: subscribe(WS_METHODS.peerLinksSubscribeThread, input), - historyPage: (cursor) => - request(WS_METHODS.peerLinksThreadHistoryPage, { ...input, cursor }), - }), - }); /** * What a view of the thread last showed. It outlives the subscription for a while, so coming * back to the view shows the thread at once while the stream starts again. @@ -79,11 +70,26 @@ export function createPeerLinkEnvironmentAtoms( * last reader, which closes the stream at the linked environment too. */ const threadView = Atom.family((key: string) => { - const stream = threadStream(JSON.parse(key) as LinkedThreadViewTarget); + const { environmentId, input } = JSON.parse(key) as LinkedThreadViewTarget; + const kept = lastThreadView(key); + const stream = runtime + .atom(({ registry }) => + followStreamInEnvironment( + environmentId, + Stream.suspend(() => + followLinkedThread({ + items: subscribe(WS_METHODS.peerLinksSubscribeThread, input), + historyPage: (cursor) => + request(WS_METHODS.peerLinksThreadHistoryPage, { ...input, cursor }), + previous: registry.get(kept), + }), + ), + ), + ) + .pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-data:peer-links:thread-stream:${key}`)); return Atom.make((get) => { const live = get(stream); if (AsyncResult.isSuccess(live)) { - const kept = lastThreadView(key); get.set(kept, keepLinkedThreadView(get.once(kept), live.value)); } return live; diff --git a/packages/client-runtime/src/state/threadHistoryMerge.test.ts b/packages/client-runtime/src/state/threadHistoryMerge.test.ts index 9647f5e4ffc2c..e92852ee36db1 100644 --- a/packages/client-runtime/src/state/threadHistoryMerge.test.ts +++ b/packages/client-runtime/src/state/threadHistoryMerge.test.ts @@ -345,8 +345,11 @@ describe("threadHistoryMerge", () => { visibleTurnItems: [{ ...recent, position: 0 }], }; + // A row of the run that was never in the window, such as one paged in after a rollback. + const ran = { ...row(1), item: { ...row(1).item, runId } }; const merged = mergeOlderHistoryIntoProjection(coldOpen, [ { ...row(0), position: 0 }, + ran, { position: 1, visibility: "local", @@ -357,7 +360,9 @@ describe("threadHistoryMerge", () => { ]); expect(merged.visibleTurnItems.map((entry) => String(entry.sourceItemId))).toEqual( - status === "rolled_back" ? ["item-0", "item-5"] : ["item-0", "item-question", "item-5"], + status === "rolled_back" + ? ["item-0", "item-5"] + : ["item-0", "item-1", "item-question", "item-5"], ); expect(merged.turnItems).toContain(card); const pending = derivePendingThreadRequests(merged).userInputs; diff --git a/packages/client-runtime/src/state/threadHistoryMerge.ts b/packages/client-runtime/src/state/threadHistoryMerge.ts index 4af17f76e031c..a455d64a4726f 100644 --- a/packages/client-runtime/src/state/threadHistoryMerge.ts +++ b/packages/client-runtime/src/state/threadHistoryMerge.ts @@ -102,6 +102,9 @@ export function mergeOlderHistoryIntoProjection( const currentByKey = new Map( projection.visibleTurnItems.map((row) => [projectedItemKey(row), row]), ); + const rolledBackRuns = new Set( + projection.runs.filter((run) => run.status === "rolled_back").map((run) => run.id), + ); const turnItemById = new Map(projection.turnItems.map((item) => [String(item.id), item])); const pageKeys = new Set(); const page: OrchestrationV2ProjectedTurnItem[] = []; @@ -140,6 +143,8 @@ export function mergeOlderHistoryIntoProjection( continue; row = { ...row, item: currentItem }; } + // A rollback can arrive before a history page for rows outside the loaded window. + if (row.item.runId !== null && rolledBackRuns.has(row.item.runId)) continue; } pageKeys.add(key); page.push(row); diff --git a/packages/client-runtime/src/state/threadStream.ts b/packages/client-runtime/src/state/threadStream.ts index b723a99885aad..e03a1e610a094 100644 --- a/packages/client-runtime/src/state/threadStream.ts +++ b/packages/client-runtime/src/state/threadStream.ts @@ -82,13 +82,23 @@ export function applyThreadHistoryPage( page: OrchestrationV2ThreadHistoryPage, ): ThreadStreamState { // A snapshot since the request replaced the thread and its cursor. - if (state.projection === null || state.historyCursor !== cursor) return state; + if (state.historyCursor !== cursor) return state; + return prependThreadHistory(state, page, page.hasMoreHistory ? page.nextCursor : null); +} + +/** Adds older timeline rows and their subagent records, with the cursor that follows them. */ +export function prependThreadHistory( + state: ThreadStreamState, + history: Pick, + nextCursor: string | null, +): ThreadStreamState { + if (state.projection === null) return state; return { ...state, projection: mergeOlderSubagentsIntoProjection( - mergeOlderHistoryIntoProjection(state.projection, page.items), - page.subagents, + mergeOlderHistoryIntoProjection(state.projection, history.items), + history.subagents, ), - historyCursor: page.hasMoreHistory ? page.nextCursor : null, + historyCursor: nextCursor, }; } From da57ea2bf9ee829ade3b6c98cb7b402072fb1f15 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:16:24 +0100 Subject: [PATCH 065/324] fix(mobile): push clean default branches without a new commit (#40538) Co-authored-by: Julius Marminge --- apps/server/src/vcs/GitVcsDriverCore.test.ts | 43 +++++++++++++++++++ apps/server/src/vcs/GitVcsDriverCore.ts | 8 +++- .../src/state/gitActions.test.ts | 17 ++++++++ .../client-runtime/src/state/gitActions.ts | 4 +- 4 files changed, 68 insertions(+), 4 deletions(-) diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 27f4d4eceec59..0e9ab873cbb30 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -9720,6 +9720,49 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("publishes a new branch at the same commit as its local upstream", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const remote = yield* makeTmpDir("git-remote-"); + const { initialBranch } = yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + yield* git(remote, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* git(cwd, ["push", "-u", "origin", initialBranch]); + const remoteBase = yield* git(remote, [ + "--git-dir=.", + "rev-parse", + `refs/heads/${initialBranch}`, + ]); + yield* writeTextFile(cwd, "feature.txt", "feature\n"); + yield* git(cwd, ["add", "feature.txt"]); + const { commitSha } = yield* driver.commit(cwd, "Add feature", ""); + yield* git(cwd, ["config", "branch.autoSetupMerge", "always"]); + yield* driver.createRef({ cwd, refName: "feature/push" }); + yield* driver.switchRef({ cwd, refName: "feature/push" }); + assert.equal( + yield* git(cwd, ["rev-parse", "--symbolic-full-name", "@{upstream}"]), + `refs/heads/${initialBranch}`, + ); + + const pushed = yield* driver.pushCurrentBranch(cwd, null); + + assert.deepInclude(pushed, { + status: "pushed", + upstreamBranch: "origin/feature/push", + setUpstream: true, + }); + assert.equal( + yield* git(remote, ["--git-dir=.", "rev-parse", "refs/heads/feature/push"]), + commitSha, + ); + assert.equal( + yield* git(remote, ["--git-dir=.", "rev-parse", `refs/heads/${initialBranch}`]), + remoteBase, + ); + }), + ); + it.effect("republishes a branch whose upstream was deleted", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 35105aeea90e4..a6aab054d37dc 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -3733,8 +3733,12 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const destination = yield* resolvePushDestination(cwd, branch, details.hasUpstream); if (hasNoLocalDelta && details.hasUpstream) { if (!destination?.pushRemote) { - // The tracking ref reflects the fetch URL, so it says nothing about a separate push URL. - if (!destination || (yield* pushesOnlyToFetchUrl(cwd, destination.remoteName))) { + // A local upstream and a separate push URL both leave the publish destination unchecked. + if ( + !destination || + (destination.upstream?.remoteName !== "." && + (yield* pushesOnlyToFetchUrl(cwd, destination.remoteName))) + ) { return { status: "skipped_up_to_date" as const, branch, diff --git a/packages/client-runtime/src/state/gitActions.test.ts b/packages/client-runtime/src/state/gitActions.test.ts index 7418ed0df172b..7b1db4e9f5f47 100644 --- a/packages/client-runtime/src/state/gitActions.test.ts +++ b/packages/client-runtime/src/state/gitActions.test.ts @@ -88,6 +88,23 @@ describe("git action copy", () => { expect(resolveQuickAction({ ...pushed, isDefaultRef: true }, false, true).disabled).toBe(true); }); + it.each([ + { tracking: "with an upstream", hasUpstream: true }, + { tracking: "without an upstream", hasUpstream: false }, + ])("pushes existing commits from a clean default branch $tracking", ({ hasUpstream }) => { + const cleanDefaultBranch = status({ + refName: "main", + isDefaultRef: true, + hasUpstream, + aheadCount: 1, + }); + expect(resolveQuickAction(cleanDefaultBranch, false, true)).toMatchObject({ + disabled: false, + kind: "run_action", + action: "push", + }); + }); + it("names the host's change request in the default-branch dialog", () => { const input = { action: "commit_push_pr", branchName: "main", includesCommit: true } as const; expect( diff --git a/packages/client-runtime/src/state/gitActions.ts b/packages/client-runtime/src/state/gitActions.ts index ece720c47d3a2..c975e640aafee 100644 --- a/packages/client-runtime/src/state/gitActions.ts +++ b/packages/client-runtime/src/state/gitActions.ts @@ -238,7 +238,7 @@ export function resolveQuickAction( label: resolve(msg("Push", { $context: "verb, git action" })), disabled: false, kind: "run_action", - action: isDefaultBranch ? "commit_push" : "push", + action: "push", }; } return { @@ -272,7 +272,7 @@ export function resolveQuickAction( label: resolve(msg("Push", { $context: "verb, git action" })), disabled: false, kind: "run_action", - action: isDefaultBranch ? "commit_push" : "push", + action: "push", }; } return { From ffb42a0b7767374c59ff5a6665025abd47f0376c Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:33:15 +0100 Subject: [PATCH 066/324] fix(web): preserve browser history across open tabs (#40543) Co-authored-by: Grok 4.7 Co-authored-by: Julius Marminge --- .../src/browserHistoryStore.browser.test.ts | 302 +++++++++++++ apps/web/src/browserHistoryStore.ts | 427 +++++++++++++----- ...history-keeps-visits-from-both-tabs.e2e.ts | 76 ++++ 3 files changed, 693 insertions(+), 112 deletions(-) create mode 100644 apps/web/src/browserHistoryStore.browser.test.ts create mode 100644 scripts/scenarios/browser-history-keeps-visits-from-both-tabs.e2e.ts diff --git a/apps/web/src/browserHistoryStore.browser.test.ts b/apps/web/src/browserHistoryStore.browser.test.ts new file mode 100644 index 0000000000000..c0c22fc2558a4 --- /dev/null +++ b/apps/web/src/browserHistoryStore.browser.test.ts @@ -0,0 +1,302 @@ +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { expect, it, vi } from "vite-plus/test"; + +import { resetBrowserHistoryForTests, useBrowserHistoryStore } from "./browserHistoryStore"; + +const storageKey = "t3code:browser-history:v1"; +const oldEntry = { url: "http://example.test/removed", lastVisitedAt: 1 }; +const otherEntry = { url: "http://example.test/other", lastVisitedAt: 2 }; +const page = { url: "http://localhost:3000/page", lastVisitedAt: 3, title: "Page" }; + +function storedHistory(): unknown { + return JSON.parse(localStorage.getItem(storageKey) ?? "null")?.state; +} + +function openHistoryFixture(disposables: DisposableStack) { + return new Promise((resolve, reject) => { + const request = indexedDB.open(storageKey, 1); + request.onupgradeneeded = () => request.result.createObjectStore("history"); + request.onsuccess = () => { + const db = request.result; + disposables.defer(() => db.close()); + resolve(db); + }; + request.onerror = () => reject(request.error); + }); +} + +function readHistoryFixture(db: IDBDatabase): Promise { + return new Promise((resolve, reject) => { + const request = db.transaction("history").objectStore("history").get(storageKey); + request.onsuccess = () => resolve(request.result); + request.onerror = () => reject(request.error); + }); +} + +function writeHistoryFixture(db: IDBDatabase, state: unknown): Promise { + return new Promise((resolve, reject) => { + const transaction = db.transaction("history", "readwrite"); + transaction.objectStore("history").put(state, storageKey); + transaction.oncomplete = () => resolve(); + transaction.onabort = () => reject(transaction.error); + }); +} + +it.each([ + { + name: "records a visit without bringing back a deleted URL", + change: () => useBrowserHistoryStore.getState().recordVisit("a", "http://example.test/new", 4), + expected: { + byProjectKey: { + a: [{ url: "http://example.test/new", lastVisitedAt: 4 }, page], + b: [otherEntry], + }, + }, + }, + { + name: "titles the latest matching visit without changing its URL", + change: () => + useBrowserHistoryStore.getState().setTitleForUrl("a", "http://127.0.0.1:3000/page/", "New"), + expected: { byProjectKey: { a: [{ ...page, title: "New" }], b: [otherEntry] } }, + }, + { + name: "removes a visit added elsewhere without clearing the other project", + change: () => useBrowserHistoryStore.getState().removeUrl("a", page.url), + expected: { byProjectKey: { b: [otherEntry] } }, + }, + { + name: "registers a thread without replacing another tab's history", + change: () => + useBrowserHistoryStore.getState().registerThreadProject( + { + environmentId: EnvironmentId.make("env"), + threadId: ThreadId.make("thread"), + }, + "a", + ), + expected: { byProjectKey: { a: [page], b: [otherEntry] } }, + }, +])("$name", async ({ change, expected }) => { + await resetHistoryFixture(); + try { + using fixture = new DisposableStack(); + const db = await openHistoryFixture(fixture); + useBrowserHistoryStore.getState().recordVisit("a", oldEntry.url, oldEntry.lastVisitedAt); + await vi.waitFor(async () => + expect(await readHistoryFixture(db)).toMatchObject({ byProjectKey: { a: [oldEntry] } }), + ); + + // Another document has committed newer history that this store has not heard about. + await writeHistoryFixture(db, { + byProjectKey: { a: [page], b: [otherEntry] }, + projectKeyByThreadKey: {}, + }); + change(); + + await vi.waitFor(async () => { + const saved = await readHistoryFixture(db); + expect(saved).toHaveProperty("byProjectKey", expected.byProjectKey); + expect(saved).toHaveProperty( + "projectKeyByThreadKey", + useBrowserHistoryStore.getState().projectKeyByThreadKey, + ); + }); + await vi.waitFor(() => + expect(useBrowserHistoryStore.getState().byProjectKey).toEqual(expected.byProjectKey), + ); + } finally { + await resetHistoryFixture(); + } +}); + +it("refreshes the open history when another document adds a visit", async () => { + await resetHistoryFixture(); + try { + localStorage.setItem( + storageKey, + JSON.stringify({ state: { byProjectKey: { a: [page] } }, version: 1 }), + ); + + using documents = new DisposableStack(); + const otherStore = await openHistoryDocument(documents); + await vi.waitFor(() => expect(otherStore.getState().byProjectKey).toEqual({ a: [page] })); + otherStore.getState().recordVisit("a", page.url, page.lastVisitedAt); + + await vi.waitFor(() => + expect(useBrowserHistoryStore.getState().byProjectKey).toEqual({ a: [page] }), + ); + } finally { + await resetHistoryFixture(); + } +}); + +it("bounds saved thread mappings while keeping live registrations", async () => { + await resetHistoryFixture(); + const mappings = Object.fromEntries( + Array.from({ length: 100 }, (_, index) => [`env:thread-${index}`, "a"]), + ); + + try { + using fixture = new DisposableStack(); + const db = await openHistoryFixture(fixture); + await writeHistoryFixture(db, { byProjectKey: { a: [page] }, projectKeyByThreadKey: mappings }); + const store = useBrowserHistoryStore.getState(); + const environmentId = EnvironmentId.make("env"); + store.registerThreadProject({ environmentId, threadId: ThreadId.make("thread-0") }, "a"); + store.registerThreadProject({ environmentId, threadId: ThreadId.make("pending") }, "b"); + const { "env:thread-0": _oldest, ...retained } = mappings; + await vi.waitFor(async () => + expect(await readHistoryFixture(db)).toHaveProperty("projectKeyByThreadKey", { + ...retained, + "env:pending": "b", + }), + ); + + store.removeUrl("a", page.url); + await vi.waitFor(async () => + expect(await readHistoryFixture(db)).toHaveProperty("projectKeyByThreadKey", { + "env:pending": "b", + }), + ); + expect(useBrowserHistoryStore.getState().projectKeyByThreadKey["env:thread-0"]).toBe("a"); + } finally { + await resetHistoryFixture(); + } +}); + +async function openHistoryDocument( + disposables: DisposableStack, + { withoutIndexedDB = false } = {}, +) { + const source = new URL(import.meta.url); + source.pathname = source.pathname.replace(/\.browser\.test\.ts$/, ".ts"); + source.search = ""; + const frame = document.createElement("iframe"); + disposables.defer(() => frame.remove()); + frame.srcdoc = `${withoutIndexedDB ? '' : ""} + `; + await new Promise((resolve) => { + frame.onload = () => resolve(); + document.body.append(frame); + }); + const store = ( + frame.contentWindow as (Window & { historyStore?: typeof useBrowserHistoryStore }) | null + )?.historyStore; + if (!store) throw new Error("The history document did not load."); + return store; +} + +function deleteHistoryDatabase() { + return new Promise((resolve, reject) => { + const request = indexedDB.deleteDatabase(storageKey); + request.onsuccess = () => resolve(); + request.onerror = () => reject(request.error); + }); +} + +async function resetHistoryFixture() { + localStorage.removeItem(storageKey); + await deleteHistoryDatabase(); + resetBrowserHistoryForTests(); +} + +it("moves the legacy snapshot into the shared database", async () => { + await resetHistoryFixture(); + localStorage.setItem( + storageKey, + JSON.stringify({ state: { byProjectKey: { a: [page] } }, version: 1 }), + ); + try { + using documents = new DisposableStack(); + const first = await openHistoryDocument(documents); + await vi.waitFor(() => expect(first.getState().byProjectKey).toEqual({ a: [page] })); + expect(localStorage.getItem(storageKey)).toBeNull(); + first.getState().recordVisit("b", otherEntry.url, otherEntry.lastVisitedAt); + await vi.waitFor(() => expect(first.getState().byProjectKey.b).toEqual([otherEntry])); + + const reopened = await openHistoryDocument(documents); + await vi.waitFor(() => + expect(reopened.getState().byProjectKey).toEqual({ a: [page], b: [otherEntry] }), + ); + } finally { + await resetHistoryFixture(); + } +}); + +it("persists new visits from an open document after its history database is deleted", async () => { + await resetHistoryFixture(); + localStorage.setItem( + storageKey, + JSON.stringify({ state: { byProjectKey: { a: [page] } }, version: 1 }), + ); + try { + using documents = new DisposableStack(); + const first = await openHistoryDocument(documents); + await vi.waitFor(() => expect(first.getState().byProjectKey).toEqual({ a: [page] })); + first.getState().removeUrl("a", page.url); + await vi.waitFor(() => expect(first.getState().byProjectKey).toEqual({})); + + await deleteHistoryDatabase(); + first.getState().recordVisit("b", otherEntry.url, otherEntry.lastVisitedAt); + await vi.waitFor(() => expect(first.getState().byProjectKey.b).toEqual([otherEntry])); + + const reopened = await openHistoryDocument(documents); + await vi.waitFor(() => expect(reopened.getState().byProjectKey).toEqual({ b: [otherEntry] })); + } finally { + await resetHistoryFixture(); + } +}); + +it("keeps overlapping visits from independent documents", async () => { + await resetHistoryFixture(); + localStorage.setItem( + storageKey, + JSON.stringify({ state: { byProjectKey: { a: [page] } }, version: 1 }), + ); + try { + using documents = new DisposableStack(); + const [first, second] = await Promise.all([ + openHistoryDocument(documents), + openHistoryDocument(documents), + ]); + first.getState().recordVisit("a", oldEntry.url, oldEntry.lastVisitedAt); + second.getState().recordVisit("b", otherEntry.url, otherEntry.lastVisitedAt); + const expected = { a: [page, oldEntry], b: [otherEntry] }; + await vi.waitFor(() => { + expect(first.getState().byProjectKey).toEqual(expected); + expect(second.getState().byProjectKey).toEqual(expected); + }); + + // A fresh document should read the committed visits even after the legacy seed is gone. + localStorage.removeItem(storageKey); + const reopened = await openHistoryDocument(documents); + await vi.waitFor(() => expect(reopened.getState().byProjectKey).toEqual(expected)); + } finally { + await resetHistoryFixture(); + } +}); + +it("keeps visits saved while IndexedDB could not open", async () => { + await resetHistoryFixture(); + try { + using documents = new DisposableStack(); + const db = await openHistoryFixture(documents); + await writeHistoryFixture(db, { byProjectKey: { a: [page] }, projectKeyByThreadKey: {} }); + const offline = await openHistoryDocument(documents, { withoutIndexedDB: true }); + offline.getState().recordVisit("b", otherEntry.url, otherEntry.lastVisitedAt); + await vi.waitFor(() => + expect(storedHistory()).toHaveProperty("byProjectKey", { b: [otherEntry] }), + ); + + const online = await openHistoryDocument(documents); + await vi.waitFor(() => + expect(online.getState().byProjectKey).toEqual({ a: [page], b: [otherEntry] }), + ); + expect(storedHistory()).toBeUndefined(); + } finally { + await resetHistoryFixture(); + } +}); diff --git a/apps/web/src/browserHistoryStore.ts b/apps/web/src/browserHistoryStore.ts index d5ccb0fcd621e..c6088b2abfca7 100644 --- a/apps/web/src/browserHistoryStore.ts +++ b/apps/web/src/browserHistoryStore.ts @@ -11,7 +11,6 @@ import { type ScopedThreadRef, } from "@t3tools/contracts"; import { create } from "zustand"; -import { createJSONStorage, persist } from "zustand/middleware"; import { useShallow } from "zustand/react/shallow"; import { normalizePreviewUrl } from "@t3tools/shared/preview"; @@ -40,7 +39,6 @@ import { isClientSettingsHydrated, useClientSettings, } from "./hooks/useSettings"; -import { resolveStorage } from "./lib/storage"; import { deriveLogicalProjectKeyFromSettings, derivePhysicalProjectKey, @@ -180,6 +178,7 @@ export function migratePersistedBrowserHistoryState(persistedState: unknown): { const BROWSER_HISTORY_STORAGE_KEY = "t3code:browser-history:v1"; +const MAX_PERSISTED_THREAD_MAPPINGS = 100; const PENDING_MAX_PER_THREAD = 10; const PENDING_MAX_THREADS = 20; @@ -199,7 +198,7 @@ interface BrowserHistoryStoreState { projectKey: string, url: string, title: string, - environmentHostname?: string | null, + options?: { environmentHostname?: string | null; onlyIfUntitled?: boolean }, ) => void; removeUrl: (projectKey: string, url: string) => void; registerThreadProject: (ref: ScopedThreadRef, projectKey: string) => void; @@ -221,100 +220,313 @@ function addPendingByThread( return next; } -export const useBrowserHistoryStore = create()( - persist( - (set, get) => ({ - byProjectKey: {}, - projectKeyByThreadKey: {}, - pendingVisitsByThreadKey: {}, - recordVisit: (projectKey, url, at, options) => { - const normalized = normalizeHistoryUrl(url); - if (!normalized) return; - set((state) => { - return { - byProjectKey: evictExcessProjects({ - ...state.byProjectKey, - [projectKey]: upsertHistoryEntry( - state.byProjectKey[projectKey] ?? [], - normalized, - at, - options, - ), - }), - }; - }); +type PersistedBrowserHistory = Pick< + BrowserHistoryStoreState, + "byProjectKey" | "projectKeyByThreadKey" +>; + +type UpdateHistory = (state: PersistedBrowserHistory) => PersistedBrowserHistory; + +function boundThreadMappings( + previous: PersistedBrowserHistory, + next: PersistedBrowserHistory, +): PersistedBrowserHistory { + return { + ...next, + projectKeyByThreadKey: Object.fromEntries( + Object.entries(next.projectKeyByThreadKey) + // Keep new registrations for empty projects, but drop projects that lost their history. + .filter( + ([, projectKey]) => + !Object.hasOwn(previous.byProjectKey, projectKey) || + Object.hasOwn(next.byProjectKey, projectKey), + ) + .slice(-MAX_PERSISTED_THREAD_MAPPINGS), + ), + }; +} + +const HISTORY_OBJECT_STORE = "history"; +const EMPTY_PERSISTED_HISTORY: PersistedBrowserHistory = { + byProjectKey: {}, + projectKeyByThreadKey: {}, +}; +let historyDatabase: Promise | undefined; +let historyChannel: BroadcastChannel | undefined; + +function readLegacyHistory( + missing: Missing = EMPTY_PERSISTED_HISTORY as Missing, +): PersistedBrowserHistory | Missing { + try { + const value = window.localStorage.getItem(BROWSER_HISTORY_STORAGE_KEY); + if (value === null) return missing; + const parsed: { state?: unknown } | null = JSON.parse(value); + return { + ...migratePersistedBrowserHistoryState(parsed?.state), + projectKeyByThreadKey: migratePersistedThreadProjectKeys(parsed?.state), + }; + } catch { + return EMPTY_PERSISTED_HISTORY; + } +} + +function retireLegacyHistory(): void { + try { + window.localStorage.removeItem(BROWSER_HISTORY_STORAGE_KEY); + } catch { + // The browser can deny access to localStorage independently of IndexedDB. + } +} + +// localStorage can gain visits after migration: from the fallback below, or a tab on an older build. +function mergeLegacyHistory( + saved: PersistedBrowserHistory, + legacy: PersistedBrowserHistory, +): PersistedBrowserHistory { + const byProjectKey = { ...saved.byProjectKey }; + for (const [projectKey, entries] of Object.entries(legacy.byProjectKey)) + byProjectKey[projectKey] = [...(byProjectKey[projectKey] ?? []), ...entries]; + return { + ...migratePersistedBrowserHistoryState({ byProjectKey }), + projectKeyByThreadKey: { ...legacy.projectKeyByThreadKey, ...saved.projectKeyByThreadKey }, + }; +} + +// Without IndexedDB, merge into the freshest localStorage snapshot so a reload keeps new visits. +function transactLegacyHistory(update: UpdateHistory, current: PersistedBrowserHistory) { + const previous = readLegacyHistory(current); + const next = update(previous); + if (next === previous) return previous; + const history = boundThreadMappings(previous, next); + try { + window.localStorage.setItem( + BROWSER_HISTORY_STORAGE_KEY, + JSON.stringify({ state: history, version: 1 }), + ); + } catch { + // History stays in memory when the browser denies both storage APIs. + } + return history; +} + +function invalidateHistoryDatabase(opening: Promise): void { + if (historyDatabase === opening) historyDatabase = undefined; +} + +function openHistoryDatabase() { + if (historyDatabase) return historyDatabase; + const opening = new Promise((resolve, reject) => { + const request = indexedDB.open(BROWSER_HISTORY_STORAGE_KEY, 1); + request.onupgradeneeded = () => request.result.createObjectStore(HISTORY_OBJECT_STORE); + request.onsuccess = () => { + const db = request.result; + db.onclose = () => invalidateHistoryDatabase(opening); + db.onversionchange = () => { + invalidateHistoryDatabase(opening); + db.close(); + }; + resolve(db); + }; + request.onerror = () => reject(request.error); + }); + historyDatabase = opening; + void opening.catch(() => invalidateHistoryDatabase(opening)); + return opening; +} + +async function transactIndexedHistory(update?: UpdateHistory, retry = true) { + const opening = openHistoryDatabase(); + const db = await opening; + let transaction: IDBTransaction; + try { + transaction = db.transaction(HISTORY_OBJECT_STORE, update ? "readwrite" : "readonly"); + } catch (error) { + if (error instanceof DOMException && error.name === "InvalidStateError") { + invalidateHistoryDatabase(opening); + if (retry) return transactIndexedHistory(update, false); + } + throw error; + } + + return new Promise<{ history: PersistedBrowserHistory; changed: boolean }>((resolve, reject) => { + const store = transaction.objectStore(HISTORY_OBJECT_STORE); + const request = store.get(BROWSER_HISTORY_STORAGE_KEY); + let history: PersistedBrowserHistory; + let changed = false; + request.onsuccess = () => { + const saved = request.result as PersistedBrowserHistory | undefined; + const legacy = update ? readLegacyHistory(null) : null; + const previous = + saved && legacy + ? mergeLegacyHistory(saved, legacy) + : (saved ?? legacy ?? EMPTY_PERSISTED_HISTORY); + const next = update?.(previous) ?? previous; + history = next === previous ? previous : boundThreadMappings(previous, next); + changed = history !== saved; + if (update && changed) store.put(history, BROWSER_HISTORY_STORAGE_KEY); + }; + transaction.oncomplete = () => { + // Keep the migration source until the IndexedDB snapshot has committed. + if (update) retireLegacyHistory(); + resolve({ history, changed }); + }; + transaction.onabort = () => reject(transaction.error); + }); +} + +export const useBrowserHistoryStore = create()((set, get) => { + const publish = ({ byProjectKey }: PersistedBrowserHistory) => { + if (byProjectKey !== get().byProjectKey) set({ byProjectKey }); + }; + const updateHistory = (update: UpdateHistory) => { + if (typeof window === "undefined") { + publish(update(get())); + return; + } + void transactIndexedHistory(update).then( + ({ history, changed }) => { + publish(history); + // oxlint-disable-next-line unicorn/require-post-message-target-origin -- BroadcastChannel is scoped to the origin + if (changed) historyChannel?.postMessage(null); }, - setTitleForUrl: (projectKey, url, title, environmentHostname) => { - const normalized = normalizeHistoryUrl(url); - const state = get(); + () => { + const { byProjectKey, projectKeyByThreadKey } = get(); + publish(transactLegacyHistory(update, { byProjectKey, projectKeyByThreadKey })); + }, + ); + }; + + return mergeBrowserHistoryState(undefined, { + byProjectKey: {}, + projectKeyByThreadKey: {}, + pendingVisitsByThreadKey: {}, + recordVisit: (projectKey, url, at, options) => { + const normalized = normalizeHistoryUrl(url); + if (!normalized) return; + updateHistory((state) => { + const entries = state.byProjectKey[projectKey] ?? []; + return { + ...state, + byProjectKey: evictExcessProjects({ + ...state.byProjectKey, + [projectKey]: upsertHistoryEntry(entries, normalized, at, { + ...options, + insertOrdered: options?.insertOrdered || (entries[0]?.lastVisitedAt ?? at) > at, + }), + }), + }; + }); + }, + setTitleForUrl: (projectKey, url, title, options) => { + const normalized = normalizeHistoryUrl(url); + const trimmed = title.trim().slice(0, BROWSER_HISTORY_MAX_TITLE_LENGTH); + if (!normalized || trimmed.length === 0) return; + const key = titleLookupKey(normalized, options?.environmentHostname); + updateHistory((state) => { const entries = state.byProjectKey[projectKey]; - const trimmed = title.trim().slice(0, BROWSER_HISTORY_MAX_TITLE_LENGTH); - if (!normalized || !entries || trimmed.length === 0) return; - const key = titleLookupKey(normalized, environmentHostname); - const index = entries.findIndex( - (candidate) => titleLookupKey(candidate.url, environmentHostname) === key, - ); - if (index === -1 || entries[index]?.title === trimmed) return; - set({ + const index = + entries?.findIndex( + (candidate) => titleLookupKey(candidate.url, options?.environmentHostname) === key, + ) ?? -1; + const entry = entries?.[index]; + if ( + !entries || + !entry || + entry.title === trimmed || + (entry.title && options?.onlyIfUntitled) + ) + return state; + return { + ...state, byProjectKey: { ...state.byProjectKey, - [projectKey]: entries.map((candidate, candidateIndex) => - candidateIndex === index ? { ...candidate, title: trimmed } : candidate, - ), + [projectKey]: entries.with(index, { ...entry, title: trimmed }), }, - }); - }, - removeUrl: (projectKey, url) => { - const normalized = normalizeHistoryUrl(url); - const state = get(); + }; + }); + }, + removeUrl: (projectKey, url) => { + const normalized = normalizeHistoryUrl(url); + if (!normalized) return; + updateHistory((state) => { const entries = state.byProjectKey[projectKey]; - if (!normalized || !entries) return; + if (!entries) return state; const next = entries.filter((candidate) => candidate.url !== normalized); - if (next.length === entries.length) return; - if (next.length === 0) { - const { [projectKey]: _removed, ...rest } = state.byProjectKey; - set({ byProjectKey: rest }); - return; - } - set({ byProjectKey: { ...state.byProjectKey, [projectKey]: next } }); - }, - registerThreadProject: (ref, projectKey) => { - const threadKey = scopedThreadKey(ref); - const state = get(); - const pendingVisits = state.pendingVisitsByThreadKey[threadKey]; - if (state.projectKeyByThreadKey[threadKey] === projectKey && !pendingVisits) return; - const nextPendingVisits = { ...state.pendingVisitsByThreadKey }; - delete nextPendingVisits[threadKey]; - set({ - projectKeyByThreadKey: { ...state.projectKeyByThreadKey, [threadKey]: projectKey }, - pendingVisitsByThreadKey: nextPendingVisits, + if (next.length === entries.length) return state; + const byProjectKey = { ...state.byProjectKey }; + if (next.length === 0) delete byProjectKey[projectKey]; + else byProjectKey[projectKey] = next; + return { ...state, byProjectKey }; + }); + }, + registerThreadProject: (ref, projectKey) => { + const threadKey = scopedThreadKey(ref); + const state = get(); + const pendingVisits = state.pendingVisitsByThreadKey[threadKey]; + if (state.projectKeyByThreadKey[threadKey] === projectKey && !pendingVisits) return; + const nextPendingVisits = { ...state.pendingVisitsByThreadKey }; + delete nextPendingVisits[threadKey]; + set({ + projectKeyByThreadKey: { ...state.projectKeyByThreadKey, [threadKey]: projectKey }, + pendingVisitsByThreadKey: nextPendingVisits, + }); + updateHistory((shared) => + shared.projectKeyByThreadKey[threadKey] === projectKey + ? shared + : { + ...shared, + projectKeyByThreadKey: { ...shared.projectKeyByThreadKey, [threadKey]: projectKey }, + }, + ); + for (const visit of pendingVisits ?? []) + get().recordVisit(projectKey, visit.url, visit.at, { + insertOrdered: true, + environmentHostname: visit.environmentHostname, + }); + if (pendingVisits) + recordPreviewTitles(ref, readThreadPreviewState(ref), { + urls: pendingVisits.map((visit) => visit.url), }); - for (const visit of pendingVisits ?? []) - get().recordVisit(projectKey, visit.url, visit.at, { - insertOrdered: true, - environmentHostname: visit.environmentHostname, - }); - if (pendingVisits) - recordPreviewTitles(ref, readThreadPreviewState(ref), { - urls: pendingVisits.map((visit) => visit.url), - }); - }, - }), - { - name: BROWSER_HISTORY_STORAGE_KEY, - version: 1, - storage: createJSONStorage(() => - resolveStorage(typeof window !== "undefined" ? window.localStorage : undefined), - ), - partialize: (state) => ({ - byProjectKey: state.byProjectKey, - projectKeyByThreadKey: state.projectKeyByThreadKey, - }), - migrate: migratePersistedBrowserHistoryState, - merge: mergeBrowserHistoryState, }, - ), -); + }); +}); + +if (typeof window !== "undefined") { + try { + historyChannel = new BroadcastChannel(BROWSER_HISTORY_STORAGE_KEY); + } catch { + // History still persists when the browser cannot send change notifications. + } + if (historyChannel) { + historyChannel.onmessage = () => { + void transactIndexedHistory().then( + ({ history }) => useBrowserHistoryStore.setState({ byProjectKey: history.byProjectKey }), + () => undefined, + ); + }; + } + const hydrate = (history: PersistedBrowserHistory) => { + useBrowserHistoryStore.setState((state) => ({ + byProjectKey: history.byProjectKey, + projectKeyByThreadKey: { + ...migratePersistedThreadProjectKeys(history, history.byProjectKey), + ...state.projectKeyByThreadKey, + }, + })); + }; + void transactIndexedHistory((history) => history).then( + ({ history }) => hydrate(history), + () => hydrate(readLegacyHistory()), + ); + import.meta.hot?.dispose(() => { + historyChannel?.close(); + historyChannel = undefined; + void historyDatabase?.then( + (db) => db.close(), + () => undefined, + ); + }); +} export function mergeBrowserHistoryState( persistedState: unknown, @@ -331,19 +543,16 @@ export function mergeBrowserHistoryState( function migratePersistedThreadProjectKeys( persistedState: unknown, - byProjectKey: Record, + byProjectKey?: Record, ): Record { if (!persistedState || typeof persistedState !== "object") return {}; const raw = (persistedState as { projectKeyByThreadKey?: unknown }).projectKeyByThreadKey; if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {}; - return Object.fromEntries( - Object.entries(raw as Record) - .filter( - (entry): entry is [string, string] => - typeof entry[1] === "string" && entry[1] in byProjectKey, - ) - .slice(-100), + const entries = Object.entries(raw as Record).filter( + (entry): entry is [string, string] => + typeof entry[1] === "string" && (!byProjectKey || Object.hasOwn(byProjectKey, entry[1])), ); + return Object.fromEntries(entries.slice(-MAX_PERSISTED_THREAD_MAPPINGS)); } /** @@ -435,24 +644,14 @@ function recordPreviewTitles( ): void { const state = useBrowserHistoryStore.getState(); const projectKey = state.projectKeyByThreadKey[scopedThreadKey(ref)]; - if (!projectKey || !state.byProjectKey[projectKey]?.length) return; + if (!projectKey) return; const connection = readPreparedConnection(ref.environmentId); const environmentHostname = connection ? new URL(connection.httpBaseUrl).hostname : null; const titleKey = (url: string) => { const normalized = normalizeHistoryUrl(url); return normalized ? titleLookupKey(normalized, environmentHostname) : null; }; - const titled = new Set( - "urls" in only - ? state.byProjectKey[projectKey]?.flatMap((entry) => - entry.title ? [titleLookupKey(entry.url, environmentHostname)] : [], - ) - : [], - ); - const visitKeys = - "urls" in only - ? new Set(only.urls.map(titleKey).filter((key) => key !== null && !titled.has(key))) - : null; + const visitKeys = "urls" in only ? new Set(only.urls.map(titleKey)) : null; // Resizes and list reconciles replace a session without loading a new page. const settledAgain = (session: PreviewSessionSnapshot, previous?: PreviewSessionSnapshot) => previous?.navStatus._tag === "Success" && @@ -463,15 +662,20 @@ function recordPreviewTitles( "changedSince" in only ? !settledAgain(session, only.changedSince[session.tabId]) : (visitKeys?.has(titleKey(url)) ?? false); - // Tabs can share a URL; applying oldest first lets the newest settle win. + // A fill uses the newest eligible title first because it only sets an untitled entry. const sessions = Object.values(preview.sessions).toSorted((a, b) => - a.updatedAt.localeCompare(b.updatedAt), + "urls" in only + ? b.updatedAt.localeCompare(a.updatedAt) + : a.updatedAt.localeCompare(b.updatedAt), ); for (const session of sessions) { const status = session.navStatus; if (session.profileId === INCOGNITO_BROWSER_PROFILE_ID) continue; if (status._tag !== "Success" || !status.title || !include(session, status.url)) continue; - state.setTitleForUrl(projectKey, status.url, status.title, environmentHostname); + state.setTitleForUrl(projectKey, status.url, status.title, { + environmentHostname, + onlyIfUntitled: "urls" in only, + }); } } @@ -555,5 +759,4 @@ export function resetBrowserHistoryForTests(): void { projectKeyByThreadKey: {}, pendingVisitsByThreadKey: {}, }); - useBrowserHistoryStore.persist.clearStorage(); } diff --git a/scripts/scenarios/browser-history-keeps-visits-from-both-tabs.e2e.ts b/scripts/scenarios/browser-history-keeps-visits-from-both-tabs.e2e.ts new file mode 100644 index 0000000000000..738d7f8b9df00 --- /dev/null +++ b/scripts/scenarios/browser-history-keeps-visits-from-both-tabs.e2e.ts @@ -0,0 +1,76 @@ +/// +// @effect-diagnostics-next-line nodeBuiltinImport:off - fixture pages for the server's browser +import * as NodeHttp from "node:http"; + +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +test( + "Browser history keeps visits from both open tabs after a reload", + WEB, + async ({ t3, app, browser, screen }) => { + const server = NodeHttp.createServer((request, response) => { + const title = request.url === "/first" ? "First preview visit" : "Second preview visit"; + response.writeHead(200, { "content-type": "text/html" }); + response.end(`${title}

    ${title}

    `); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + try { + const address = server.address(); + if (address === null || typeof address === "string") throw new Error("No page port."); + const host = `127.0.0.1:${address.port}`; + const origin = `http://${host}`; + const project = await t3.project("demo"); + const first = await t3.thread({ project, title: "First browser", messages: ["first"] }); + const second = await t3.thread({ project, title: "Second browser", messages: ["second"] }); + const history = await t3.thread({ project, title: "History check", messages: ["third"] }); + await t3.open(first); + + // Load the second app before either visit, with an independent store and shared storage. + await browser.evaluate((threadId) => { + const frame = document.createElement("iframe"); + frame.id = "second-client"; + frame.src = location.pathname.replace(/[^/]+$/, threadId); + frame.style.cssText = + "position:fixed;inset:0;width:100%;height:100%;border:0;z-index:2147483647"; + document.body.append(frame); + return null; + }, second.threadId); + const other = browser.frameLocator("#second-client"); + await other.getByRole("button", "Toggle right panel").tap(); + await other.getByRole("button", "Browser B").tap(); + const otherAddress = other.getByRole("textbox", "Search or enter URL"); + await otherAddress.waitFor(); + await browser.evaluate(() => { + document.querySelector("#second-client")!.style.display = "none"; + return null; + }); + + await screen.getByRole("button", "Toggle right panel").tap(); + await screen.getByRole("button", "Browser B").tap(); + await screen.getByRole("textbox", "Search or enter URL").fill(`${origin}/first`); + await browser.keyboard.press("Enter"); + await screen.getByText("First preview visit", { exact: true }).waitFor(); + + await browser.evaluate(() => { + document.querySelector("#second-client")!.style.display = ""; + return null; + }); + await otherAddress.fill(`${origin}/second`); + await browser.keyboard.press("Enter"); + await other.getByText("Second preview visit", { exact: true }).waitFor(); + + const historyUrl = new URL(await browser.url()); + historyUrl.pathname = historyUrl.pathname.replace(/[^/]+$/, history.threadId); + await app.open(historyUrl.pathname); + await screen.getByRole("button", "Toggle right panel").tap(); + await screen.getByRole("button", "Browser B").tap(); + await screen.getByText(`${host}/second`, { exact: false }).waitFor(); + await app.screenshot("browser-history-after-both-visits"); + await expect(screen.getByText(`${host}/first`, { exact: false })).toBeVisible(); + } finally { + await new Promise((resolve) => server.close(resolve)); + } + }, +); From fd4284d8b23529ef82495e499b173ce32670968b Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:52:24 +0100 Subject: [PATCH 067/324] fix(vcs): refresh branch pickers after external worktree changes (#40556) Co-authored-by: Julius Marminge --- .../threads/NewTaskContextPickerScreens.tsx | 2 + .../git/GitBranchesSheet.occupancy.test.tsx | 5 +- .../threads/git/GitBranchesSheet.test.tsx | 1 + .../features/threads/git/GitBranchesSheet.tsx | 2 + .../threads/use-refresh-branches-on-focus.ts | 25 ++ apps/server/src/git/GitWorkflowService.ts | 4 +- apps/server/src/vcs/GitVcsDriver.ts | 6 +- apps/server/src/vcs/GitVcsDriverCore.test.ts | 223 +++++++++++++----- apps/server/src/vcs/GitVcsDriverCore.ts | 162 ++++++++----- .../src/vcs/VcsStatusBroadcaster.test.ts | 34 ++- apps/server/src/vcs/VcsStatusBroadcaster.ts | 14 +- .../BranchToolbarBranchSelector.tsx | 4 +- .../components/WorktreeBaseBranchPicker.tsx | 7 + packages/client-runtime/src/state/vcs.test.ts | 12 +- packages/client-runtime/src/state/vcs.ts | 3 + ...ranch-picker-sees-external-worktree.e2e.ts | 71 ++++++ 16 files changed, 439 insertions(+), 136 deletions(-) create mode 100644 apps/mobile/src/features/threads/use-refresh-branches-on-focus.ts create mode 100644 scripts/scenarios/branch-picker-sees-external-worktree.e2e.ts diff --git a/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx b/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx index 97a3ce45fab3a..a8cc689b7a5cf 100644 --- a/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx +++ b/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx @@ -36,6 +36,7 @@ import { cn } from "../../lib/cn"; import { useEnvironmentScope } from "../../state/session"; import { useAtomCommand } from "../../state/use-atom-command"; import { vcsEnvironment } from "../../state/vcs"; +import { useRefreshBranchesOnFocus } from "./use-refresh-branches-on-focus"; import { useSearchToolbarInset } from "../../components/ui/useBarInset"; import type { AppBarSearch } from "../../components/ui/AppBar"; import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider"; @@ -466,6 +467,7 @@ export function BranchPickerScreen(props: { const m = useMessages(); const navigation = useNavigation(); const insets = useSafeAreaInsets(); + useRefreshBranchesOnFocus(props.project?.environmentId, props.project?.workspaceRoot); const search: AppBarSearch = { value: props.query, onChangeText: props.onQueryChange, diff --git a/apps/mobile/src/features/threads/git/GitBranchesSheet.occupancy.test.tsx b/apps/mobile/src/features/threads/git/GitBranchesSheet.occupancy.test.tsx index 436fb4dd0b403..8653d859442f4 100644 --- a/apps/mobile/src/features/threads/git/GitBranchesSheet.occupancy.test.tsx +++ b/apps/mobile/src/features/threads/git/GitBranchesSheet.occupancy.test.tsx @@ -8,7 +8,10 @@ const checkout = vi.hoisted(() => ({ branches: [] as Array<{ name: string; worktreePath: string | null }>, })); -vi.mock("@react-navigation/native", () => ({ useNavigation: () => ({}) })); +vi.mock("@react-navigation/native", () => ({ + useFocusEffect: () => {}, + useNavigation: () => ({}), +})); vi.mock("../../../components/ui/SheetHeader", () => ({ SheetHeader: () => null })); vi.mock("../../../components/ui/FitSheet", () => ({ FitSheet: ({ children }: { children: ReactNode }) =>
    {children}
    , diff --git a/apps/mobile/src/features/threads/git/GitBranchesSheet.test.tsx b/apps/mobile/src/features/threads/git/GitBranchesSheet.test.tsx index 084dd7880fba1..f0ddc71fea15d 100644 --- a/apps/mobile/src/features/threads/git/GitBranchesSheet.test.tsx +++ b/apps/mobile/src/features/threads/git/GitBranchesSheet.test.tsx @@ -20,6 +20,7 @@ const state = vi.hoisted(() => ({ })); vi.mock("@react-navigation/native", () => ({ + useFocusEffect: () => {}, useNavigation: () => ({ goBack: () => state.goBackCalls++, isFocused: () => state.focused, diff --git a/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx b/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx index df1ad6649c8f7..618996c61500c 100644 --- a/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx +++ b/apps/mobile/src/features/threads/git/GitBranchesSheet.tsx @@ -14,6 +14,7 @@ import { useSelectedThreadGitActions } from "../../../state/use-selected-thread- import { useSelectedThreadGitState } from "../../../state/use-selected-thread-git-state"; import { useSelectedThreadWorktree } from "../../../state/use-selected-thread-worktree"; import { vcsEnvironment } from "../../../state/vcs"; +import { useRefreshBranchesOnFocus } from "../use-refresh-branches-on-focus"; import { SheetActionButton } from "./gitSheetComponents"; type GitBranchesSheetProps = StaticScreenProps<{ @@ -26,6 +27,7 @@ export function GitBranchesSheet(_props: GitBranchesSheetProps) { const navigation = useNavigation(); const { selectedThread } = useThreadSelection(); const { selectedThreadCwd } = useSelectedThreadWorktree(); + useRefreshBranchesOnFocus(selectedThread?.environmentId, selectedThreadCwd); const gitState = useSelectedThreadGitState(); const gitActions = useSelectedThreadGitActions(); const { canChangeThreadBranch } = gitActions; diff --git a/apps/mobile/src/features/threads/use-refresh-branches-on-focus.ts b/apps/mobile/src/features/threads/use-refresh-branches-on-focus.ts new file mode 100644 index 0000000000000..6366994b9641e --- /dev/null +++ b/apps/mobile/src/features/threads/use-refresh-branches-on-focus.ts @@ -0,0 +1,25 @@ +import { RegistryContext } from "@effect/atom-react"; +import { useFocusEffect } from "@react-navigation/native"; +import { runAtomCommand } from "@t3tools/client-runtime/state/runtime"; +import type { EnvironmentId } from "@t3tools/contracts"; +import { useCallback, useContext } from "react"; + +import { vcsEnvironment } from "../../state/vcs"; + +export function useRefreshBranchesOnFocus( + environmentId: EnvironmentId | undefined, + cwd: string | null | undefined, +) { + const registry = useContext(RegistryContext); + useFocusEffect( + useCallback(() => { + if (environmentId === undefined || !cwd) return; + void runAtomCommand( + registry, + vcsEnvironment.refreshLocalStatusForPicker, + { environmentId, input: { cwd } }, + { reportFailure: false }, + ); + }, [cwd, environmentId, registry]), + ); +} diff --git a/apps/server/src/git/GitWorkflowService.ts b/apps/server/src/git/GitWorkflowService.ts index f0757fd7078fe..4cf3e62d9a93f 100644 --- a/apps/server/src/git/GitWorkflowService.ts +++ b/apps/server/src/git/GitWorkflowService.ts @@ -69,7 +69,8 @@ export class GitWorkflowService extends Context.Service< ) => Effect.Effect; readonly invalidateLocalStatus: (cwd: string) => Effect.Effect; readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect; - readonly readRefSnapshot: (cwd: string) => Effect.Effect; + readonly readLocalStatusRefSnapshot: GitVcsDriver.GitVcsDriver["Service"]["readLocalStatusRefSnapshot"]; + readonly readRefSnapshot: GitVcsDriver.GitVcsDriver["Service"]["readRefSnapshot"]; readonly invalidateStatus: (cwd: string) => Effect.Effect; /** The checkout's own HEAD file, inside a linked worktree's admin directory when there is one. */ readonly headPath: (cwd: string) => Effect.Effect; @@ -398,6 +399,7 @@ export const make = Effect.gen(function* () { }), invalidateLocalStatus: gitManager.invalidateLocalStatus, invalidateRemoteStatus: gitManager.invalidateRemoteStatus, + readLocalStatusRefSnapshot: git.readLocalStatusRefSnapshot, readRefSnapshot: git.readRefSnapshot, invalidateStatus: gitManager.invalidateStatus, headPath: Effect.fn("GitWorkflowService.headPath")(function* (cwd) { diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index f341ebd987a6c..3a4dd7cedf10a 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -369,8 +369,10 @@ export class GitVcsDriver extends Context.Service< cwd: string, options?: GitRemoteStatusOptions, ) => Effect.Effect; - /** Refs, HEAD and shallow boundaries. Null when the snapshot cannot be read. */ - readonly readRefSnapshot: (cwd: string) => Effect.Effect; + /** Refs, HEAD and shallow boundaries. Null on read failure. */ + readonly readLocalStatusRefSnapshot: (cwd: string) => Effect.Effect; + /** Includes worktree paths. Accepts an existing local status ref snapshot to avoid re-reading refs. */ + readonly readRefSnapshot: (cwd: string, refs?: string) => Effect.Effect; readonly prepareCommitContext: ( cwd: string, filePaths?: readonly string[], diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 0e9ab873cbb30..d9a661c7b1237 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -302,7 +302,7 @@ const makeTmpDir = ( ): Effect.Effect => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; - return yield* fileSystem.makeTempDirectoryScoped({ prefix }); + return yield* fileSystem.realPath(yield* fileSystem.makeTempDirectoryScoped({ prefix })); }); const writeTextFile = ( @@ -1878,69 +1878,80 @@ describe("pullCurrentBranch", () => { ); }); -it.effect("retries an in-flight ref snapshot invalidated by a mutation", () => - Effect.scoped( - Effect.gen(function* () { - const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; - const firstWorktreeScanStarted = yield* Deferred.make(); - const firstRefScanCompleted = yield* Deferred.make(); - const releaseFirstWorktreeScan = yield* Deferred.make(); - const delayFirstWorktreeScan = yield* Ref.make(true); - const refScans = yield* Ref.make(0); - const coordinatingSpawner = ChildProcessSpawner.make((command) => - Effect.gen(function* () { - if (!ChildProcess.isStandardCommand(command)) { - return yield* Effect.die("expected a standard Git command"); - } - const isWorktreeScan = - command.args.includes("worktree") && command.args.includes("--porcelain"); - if (isWorktreeScan && (yield* Ref.getAndSet(delayFirstWorktreeScan, false))) { - yield* Deferred.succeed(firstWorktreeScanStarted, undefined); - yield* Deferred.await(releaseFirstWorktreeScan); - } - const handle = yield* delegate.spawn(command); - const isRefScan = - command.args.includes("for-each-ref") && - command.args.includes("refs/heads") && - command.args.includes("refs/remotes"); - if (!isRefScan) return handle; - const scan = yield* Ref.updateAndGet(refScans, (count) => count + 1); - return scan === 1 - ? ChildProcessSpawner.makeHandle({ - ...handle, - exitCode: handle.exitCode.pipe( - Effect.tap(() => Deferred.succeed(firstRefScanCompleted, undefined)), +it.effect.each(["a T3 branch creation", "an external worktree addition"] as const)( + "refreshes an in-flight ref snapshot after %s", + (mutation) => + Effect.scoped( + Effect.gen(function* () { + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + const firstScanCompleted = yield* Deferred.make(); + const releaseOtherScans = yield* Deferred.make(); + const firstScan = yield* Ref.make(true); + const coordinatingSpawner = ChildProcessSpawner.make((command) => + Effect.gen(function* () { + if (!ChildProcess.isStandardCommand(command)) { + return yield* Effect.die("expected a standard Git command"); + } + const isWorktreeScan = + command.args.includes("worktree") && command.args.includes("--porcelain"); + const isRefScan = + command.args.includes("for-each-ref") && + command.args.includes("refs/heads") && + command.args.includes("refs/remotes"); + if (!isRefScan && (!isWorktreeScan || mutation === "a T3 branch creation")) { + return yield* delegate.spawn(command); + } + if (!(yield* Ref.getAndSet(firstScan, false))) { + yield* Deferred.await(releaseOtherScans); + return yield* delegate.spawn(command); + } + const handle = yield* delegate.spawn(command); + return ChildProcessSpawner.makeHandle({ + ...handle, + exitCode: handle.exitCode.pipe( + Effect.tap(() => + Deferred.succeed(firstScanCompleted, undefined).pipe( + Effect.andThen(Deferred.await(releaseOtherScans)), + ), ), - }) - : handle; - }), - ); - const driver = yield* makeGitVcsDriverCore().pipe( - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, coordinatingSpawner), - ); - const cwd = yield* makeTmpDir(); - yield* initRepoWithCommit(cwd).pipe(Effect.provideService(GitVcsDriver.GitVcsDriver, driver)); - - const inFlight = yield* driver - .listRefs({ cwd, refresh: true, limit: 100 }) - .pipe(Effect.forkChild({ startImmediately: true })); - yield* Deferred.await(firstWorktreeScanStarted); - yield* Deferred.await(firstRefScanCompleted); - - yield* driver.createRef({ cwd, refName: "feature/during-refresh" }); - yield* Deferred.succeed(releaseFirstWorktreeScan, undefined); + ), + }); + }), + ); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, coordinatingSpawner), + ); + const cwd = yield* makeTmpDir(); + const worktree = (yield* Path.Path).join(cwd, "linked checkout"); + const refName = "feature/during-refresh"; + yield* initRepoWithCommit(cwd).pipe( + Effect.provideService(GitVcsDriver.GitVcsDriver, driver), + ); + const list = driver.listRefs({ cwd, refresh: true, query: refName }); + const inFlight = yield* list.pipe(Effect.forkChild({ startImmediately: true })); + yield* Deferred.await(firstScanCompleted); - const refs = yield* Fiber.join(inFlight); - assert.isTrue(refs.refs.some((ref) => ref.name === "feature/during-refresh")); - assert.equal(yield* Ref.get(refScans), 2); - }), - ).pipe( - Effect.provide( - layerServerConfig.pipe( - Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + if (mutation === "a T3 branch creation") { + yield* driver.createRef({ cwd, refName }); + yield* Deferred.succeed(releaseOtherScans, undefined); + assert.equal((yield* Fiber.join(inFlight)).refs[0]?.name, refName); + } else { + yield* git(cwd, ["worktree", "add", "-b", refName, worktree]).pipe( + Effect.provideService(GitVcsDriver.GitVcsDriver, driver), + ); + const refresh = yield* list.pipe(Effect.forkChild({ startImmediately: true })); + yield* Deferred.succeed(releaseOtherScans, undefined); + assert.equal((yield* Fiber.join(refresh)).refs[0]?.worktreePath, worktree); + yield* Fiber.join(inFlight); + } + }), + ).pipe( + Effect.provide( + layerServerConfig.pipe( + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), ), ), - ), ); it.effect("a refreshed ref list reads the current branch and repository paths once", () => @@ -1985,6 +1996,40 @@ it.effect("a refreshed ref list reads the current branch and repository paths on ), ); +it.effect("keeps cached branch occupancy when Git cannot rescan worktrees", () => + Effect.scoped( + Effect.gen(function* () { + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + let failWorktreeScan = false; + const spawner = ChildProcessSpawner.make((command) => + failWorktreeScan && + ChildProcess.isStandardCommand(command) && + command.args.includes("worktree") && + command.args.includes("--porcelain") + ? Effect.fail( + PlatformError.systemError({ + _tag: "Unknown", + module: "ChildProcess", + method: "spawn", + }), + ) + : delegate.spawn(command), + ); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + const list = driver.listRefs({ cwd, refresh: true, query: initialBranch }); + const cached = yield* list; + assert.equal(cached.refs[0]?.worktreePath, cwd); + + failWorktreeScan = true; + assert.deepEqual(yield* list, cached); + }).pipe(Effect.provide(layerTest)), + ), +); + it.effect("superseded ref snapshots of one repository do not evict another's", () => Effect.scoped( Effect.gen(function* () { @@ -2073,6 +2118,35 @@ it.effect("invalidates a ref snapshot when a mutation fails after changing Git", ), ); +it.effect("lists external worktree paths even within the ref snapshot refresh window", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const path = yield* Path.Path; + const worktree = path.join(cwd, "another checkout"); + const movedWorktree = path.join(cwd, "moved checkout"); + yield* initRepoWithCommit(cwd); + yield* git(cwd, ["branch", "feature"]); + const driver = yield* GitVcsDriver.GitVcsDriver; + const list = driver.listRefs({ cwd, refresh: true, query: "feature" }); + yield* list; + + yield* git(cwd, ["worktree", "add", worktree, "feature"]); + assert.equal((yield* list).refs[0]?.worktreePath, worktree); + yield* git(cwd, ["worktree", "move", worktree, movedWorktree]); + assert.equal((yield* list).refs[0]?.worktreePath, movedWorktree); + yield* git(cwd, ["worktree", "remove", movedWorktree]); + assert.isNull((yield* list).refs[0]?.worktreePath); + + yield* git(cwd, ["worktree", "add", "-b", "new-branch", worktree]); + const newBranchQuery = { cwd, query: "new-branch" }; + assert.equal( + (yield* driver.listRefs({ ...newBranchQuery, refresh: true })).refs[0]?.worktreePath, + worktree, + ); + assert.equal((yield* driver.listRefs(newBranchQuery)).refs[0]?.worktreePath, worktree); + }).pipe(Effect.provide(layerTest), Effect.scoped), +); + it.effect("marks the current branch when worktree metadata is unavailable", () => Effect.scoped( Effect.gen(function* () { @@ -5852,6 +5926,35 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("a ref snapshot detects which branches are checked out in other worktrees", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const worktree = (yield* Path.Path).join(cwd, "linked checkout"); + yield* initRepoWithCommit(cwd); + yield* git(cwd, ["branch", "feature"]); + yield* git(cwd, ["branch", "same-commit"]); + const driver = yield* GitVcsDriver.GitVcsDriver; + const snapshot = driver.readRefSnapshot(cwd); + const initial = yield* snapshot; + assert.isNotNull(initial); + + yield* git(cwd, ["worktree", "add", "--detach", worktree]); + assert.equal(yield* snapshot, initial); + yield* git(worktree, ["checkout", "feature"]); + const attached = yield* snapshot; + assert.isNotNull(attached); + assert.notEqual(attached, initial); + assert.equal(yield* snapshot, attached); + yield* git(worktree, ["checkout", "same-commit"]); + const switched = yield* snapshot; + assert.isNotNull(switched); + assert.notEqual(switched, attached); + assert.notEqual(switched, initial); + yield* git(cwd, ["worktree", "remove", worktree]); + assert.equal(yield* snapshot, initial); + }), + ); + it.effect("a ref snapshot detects branch identity, ref and ancestry changes", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index a6aab054d37dc..8f3e3e16ca12b 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -220,6 +220,7 @@ interface GitRefsSnapshot { readonly localBranches: ReadonlyArray; readonly remoteBranches: ReadonlyArray; readonly hasPrimaryRemote: boolean; + readonly worktreeStamp: string | null; } interface ExecuteGitOptions { @@ -1353,6 +1354,50 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return { ...lineResult, stdout: lineResult.stdout.replaceAll("\n", "\0") }; }); + const readWorktreeBranchPaths = Effect.fn("GitVcsDriver.readWorktreeBranchPaths")(function* ( + gitCommonDir: string, + ) { + const cwd = path.basename(gitCommonDir) === ".git" ? path.dirname(gitCommonDir) : gitCommonDir; + const result = yield* executeWorktreeList( + "GitVcsDriver.readWorktreeBranchPaths", + cwd, + ["--git-dir", gitCommonDir], + { allowNonZeroExit: true, maxOutputBytes: 16 * 1024 * 1024 }, + ); + if (result.exitCode !== 0) return null; + + const entries = [...parseWorktreeBranchPaths(result.stdout)].map( + ([branchName, worktreePath]) => + [branchName, path.normalize(path.resolve(worktreePath))] as const, + ); + // Without core.worktree, Git reports a separate git dir as the main checkout. + const normalizedGitCommonDir = path.normalize(path.resolve(gitCommonDir)); + const existing = yield* Effect.filter( + entries, + ([, worktreePath]) => + worktreePath === normalizedGitCommonDir + ? Effect.succeed(false) + : fileSystem.stat(worktreePath).pipe( + Effect.as(true), + Effect.orElseSucceed(() => false), + ), + { concurrency: 16 }, + ); + return { + paths: new Map(existing), + stamp: existing + .map((entry) => JSON.stringify(entry)) + .sort() + .join("\n"), + }; + }); + + // Share overlapping reads without retaining occupancy across external Git commands. + const worktreeBranchPathsCache = yield* Cache.makeWith(readWorktreeBranchPaths, { + capacity: LIST_REFS_SNAPSHOT_CACHE_CAPACITY, + timeToLive: () => Duration.zero, + }); + const runGitStdoutWithOptions = ( operation: string, cwd: string, @@ -1960,12 +2005,10 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ), }); - const readRefSnapshot: GitVcsDriver.GitVcsDriver["Service"]["readRefSnapshot"] = Effect.fn( - "GitVcsDriver.readRefSnapshot", - )( - function* (cwd) { + const readLocalStatusRefSnapshot = Effect.fn("GitVcsDriver.readLocalStatusRefSnapshot")( + function* (cwd: string) { const result = yield* executeGit( - "GitVcsDriver.readRefSnapshot", + "GitVcsDriver.readLocalStatusRefSnapshot", cwd, ["show-ref", "--head"], { @@ -1975,7 +2018,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ); if (result.exitCode !== 0) return null; const symbolicHead = yield* executeGit( - "GitVcsDriver.readRefSnapshot", + "GitVcsDriver.readLocalStatusRefSnapshot", cwd, ["symbolic-ref", "--quiet", "HEAD"], { allowNonZeroExit: true }, @@ -1983,7 +2026,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* // Exit 1 means detached HEAD; other failures require a full status read. if (symbolicHead.exitCode !== 0 && symbolicHead.exitCode !== 1) return null; // Deepening a shallow clone changes ancestry without moving refs. - const shallowPath = path.join(yield* resolveGitCommonDir(cwd), "shallow"); + const gitCommonDir = yield* resolveGitCommonDir(cwd); + const shallowPath = path.join(gitCommonDir, "shallow"); const shallow = (yield* fileSystem.exists(shallowPath)) ? yield* fileSystem.readFileString(shallowPath) : ""; @@ -1992,6 +2036,22 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* Effect.orElseSucceed(() => null), ); + const readRefSnapshot: GitVcsDriver.GitVcsDriver["Service"]["readRefSnapshot"] = Effect.fn( + "GitVcsDriver.readRefSnapshot", + )( + function* (cwd, refs) { + const localRefs = refs ?? (yield* readLocalStatusRefSnapshot(cwd)); + if (localRefs === null) return null; + const gitCommonDir = yield* resolveGitCommonDir(cwd); + const worktrees = yield* Cache.get(worktreeBranchPathsCache, gitCommonDir).pipe( + Effect.timeoutOption(5_000), + Effect.map(Option.getOrNull), + ); + return worktrees === null ? null : `${localRefs}\0${worktrees.stamp}`; + }, + Effect.orElseSucceed(() => null), + ); + // Returns the upstream remote name it read, or undefined when it did not read one. const refreshStatusUpstreamIfStale = Effect.fn("refreshStatusUpstreamIfStale")(function* ( cwd: string, @@ -5306,7 +5366,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const fetchCwd = path.basename(gitCommonDir) === ".git" ? path.dirname(gitCommonDir) : gitCommonDir; const gitDirArgs = ["--git-dir", gitCommonDir] as const; - const [refsResult, defaultRefResult, worktreeListResult, remoteNamesResult] = yield* Effect.all( + // Read occupancy first so a concurrent worktree addition changes the cached stamp. + const worktrees = yield* Cache.get(worktreeBranchPathsCache, gitCommonDir); + const [refsResult, defaultRefResult, remoteNamesResult] = yield* Effect.all( [ executeGitWithStableDiagnostics( "GitVcsDriver.listRefs.snapshotRefs", @@ -5340,11 +5402,6 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* allowNonZeroExit: true, }, ), - executeWorktreeList("GitVcsDriver.listRefs.worktreeList", fetchCwd, gitDirArgs, { - timeoutMs: 30_000, - allowNonZeroExit: true, - maxOutputBytes: 16 * 1024 * 1024, - }), executeGit("GitVcsDriver.listRefs.remoteNames", fetchCwd, [...gitDirArgs, "remote"], { timeoutMs: 5_000, allowNonZeroExit: true, @@ -5364,27 +5421,6 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* defaultRefResult.exitCode === 0 ? parseDefaultBranchFromRemoteHeadRef(defaultRefResult.stdout, "origin") : null; - const parsedWorktreeEntries = - worktreeListResult.exitCode === 0 - ? [...parseWorktreeBranchPaths(worktreeListResult.stdout)].map( - ([branchName, worktreePath]) => - [branchName, path.normalize(path.resolve(worktreePath))] as const, - ) - : []; - // Without `core.worktree`, Git reports a separate git dir as the main checkout. - const normalizedGitCommonDir = path.normalize(path.resolve(gitCommonDir)); - const existingWorktreeEntries = yield* Effect.filter( - parsedWorktreeEntries, - ([, worktreePath]) => - worktreePath === normalizedGitCommonDir - ? Effect.succeed(false) - : fileSystem.stat(worktreePath).pipe( - Effect.as(true), - Effect.orElseSucceed(() => false), - ), - { concurrency: 16 }, - ); - const worktreeMap = new Map(existingWorktreeEntries); const localBranches: Array<{ readonly ref: VcsRef; readonly lastCommit: number }> = []; const remoteBranches: Array<{ readonly ref: VcsRef; readonly lastCommit: number }> = []; @@ -5403,7 +5439,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* current: false, isRemote: false, isDefault: name === defaultBranch, - worktreePath: worktreeMap.get(name) ?? null, + worktreePath: worktrees?.paths.get(name) ?? null, ...(upstreamRef ? { upstreamRef } : {}), }, lastCommit, @@ -5441,6 +5477,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* localBranches: localBranches.toSorted(byRecencyThenName).map(({ ref }) => ref), remoteBranches: remoteBranches.toSorted(byRecencyThenName).map(({ ref }) => ref), hasPrimaryRemote: remoteNames.length > 0, + worktreeStamp: worktrees?.stamp ?? null, } satisfies GitRefsSnapshot; }); @@ -5517,6 +5554,16 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* Exit.isSuccess(exit) ? LIST_REFS_REFRESH_COALESCE_TTL : LIST_REFS_REFRESH_FAILURE_COOLDOWN, }, ); + const invalidateListRefsSnapshots = Effect.fn("GitVcsDriver.invalidateListRefsSnapshots")( + function* (gitCommonDir: string, generation: number) { + bumpListRefsGeneration(gitCommonDir); + yield* advanceListRefsEpoch(gitCommonDir); + yield* Cache.invalidate( + listRefsRefreshSnapshotCache, + new GitRefsRefreshCacheKey({ gitCommonDir, generation }), + ); + }, + ); const resolveListRefsSnapshot = Effect.fn("resolveListRefsSnapshot")(function* ( gitCommonDir: string, refresh: boolean, @@ -5524,17 +5571,28 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* while (true) { const generation = currentListRefsGeneration(gitCommonDir); const currentEpoch = listRefsEpochByCommonDir.get(gitCommonDir); - const snapshot = - refresh || currentEpoch === undefined - ? // Cache the entire snapshot read so slow scans stay single-flight beyond the coalescing TTL. - yield* Cache.get( - listRefsRefreshSnapshotCache, - new GitRefsRefreshCacheKey({ gitCommonDir, generation }), - ) - : yield* Cache.get( - listRefsSnapshotCache, - new GitRefsSnapshotCacheKey({ gitCommonDir, epoch: currentEpoch }), - ); + if (refresh || currentEpoch === undefined) { + const key = new GitRefsRefreshCacheKey({ gitCommonDir, generation }); + const cached = yield* Cache.getOption(listRefsRefreshSnapshotCache, key); + if (Option.isNone(cached)) { + const snapshot = yield* Cache.get(listRefsRefreshSnapshotCache, key); + if (currentListRefsGeneration(gitCommonDir) === generation) return snapshot; + continue; + } + // A joined load may have read occupancy before this refresh was requested. + const worktrees = yield* Cache.get(worktreeBranchPathsCache, gitCommonDir).pipe( + Effect.orElseSucceed(() => null), + ); + if (currentListRefsGeneration(gitCommonDir) !== generation) continue; + if (worktrees === null || cached.value.worktreeStamp === worktrees.stamp) + return cached.value; + yield* invalidateListRefsSnapshots(gitCommonDir, generation); + continue; + } + const snapshot = yield* Cache.get( + listRefsSnapshotCache, + new GitRefsSnapshotCacheKey({ gitCommonDir, epoch: currentEpoch }), + ); if (currentListRefsGeneration(gitCommonDir) === generation) { return snapshot; } @@ -5550,16 +5608,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ? (yield* Cache.get(repositoryPathsCache, repositoryPathsCacheKey))?.gitCommonDir : gitCommonDir; if (commonDir == null) return; - const previousGeneration = currentListRefsGeneration(commonDir); - bumpListRefsGeneration(commonDir); - yield* advanceListRefsEpoch(commonDir); - yield* Cache.invalidate( - listRefsRefreshSnapshotCache, - new GitRefsRefreshCacheKey({ - gitCommonDir: commonDir, - generation: previousGeneration, - }), - ); + yield* invalidateListRefsSnapshots(commonDir, currentListRefsGeneration(commonDir)); yield* Cache.invalidate(repositoryPathsRefreshCache, repositoryPathsCacheKey); yield* Cache.invalidate(repositoryPathsCache, repositoryPathsCacheKey); }); @@ -6980,6 +7029,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* statusDetails, statusDetailsLocal, statusDetailsRemote, + readLocalStatusRefSnapshot, readRefSnapshot, prepareCommitContext, commit: Effect.fnUntraced(function* (cwd, subject, body, options) { diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts index 7c5dd63773848..455dadc1766ba 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts @@ -81,6 +81,7 @@ function layerTestFor(state: { remoteStatusReusedDetails?: Array; localStatusBranchChanges?: Array; refSnapshot?: string | null; + worktreeStamp?: string | null; remoteStatusError?: GitManagerError; backgroundWorkEnabled?: boolean; automaticFetchInterval?: Effect.Effect; @@ -142,8 +143,16 @@ function layerTestFor(state: { : (state.beforeCurrentBranch ?? Effect.void).pipe( Effect.andThen(Effect.sync(() => state.currentLocalStatus.refName)), ), - readRefSnapshot: () => + readLocalStatusRefSnapshot: () => Effect.sync(() => (state.refSnapshot === undefined ? "refs" : state.refSnapshot)), + readRefSnapshot: (_cwd, refs) => + Effect.sync(() => { + const localRefs = + refs ?? (state.refSnapshot === undefined ? "refs" : state.refSnapshot); + return localRefs === null || state.worktreeStamp === null + ? null + : `${localRefs}\0${state.worktreeStamp ?? ""}`; + }), upstreamDivergence: () => Effect.sync(() => { const refName = state.currentLocalStatus.refName; @@ -965,6 +974,7 @@ describe("VcsStatusBroadcaster", () => { Layer.mock(GitWorkflowService.GitWorkflowService)({ localStatus: () => Effect.succeed(localStatus), currentBranch: () => Effect.succeed(localStatus.refName), + readLocalStatusRefSnapshot: () => Effect.succeed("refs"), readRefSnapshot: () => Effect.succeed("refs"), remoteStatus: () => Effect.succeed(remoteStatus), invalidateLocalStatus: () => Effect.void, @@ -1062,6 +1072,7 @@ describe("VcsStatusBroadcaster", () => { Layer.mock(GitWorkflowService.GitWorkflowService)({ localStatus: () => Effect.succeed(baseLocalStatus), currentBranch: () => Effect.succeed(baseLocalStatus.refName), + readLocalStatusRefSnapshot: () => Effect.succeed("refs"), readRefSnapshot: () => Effect.succeed("refs"), remoteStatus: () => Effect.gen(function* () { @@ -1109,6 +1120,7 @@ describe("VcsStatusBroadcaster", () => { Layer.mock(GitWorkflowService.GitWorkflowService)({ localStatus: () => Effect.succeed(baseLocalStatus), currentBranch: () => Effect.succeed(baseLocalStatus.refName), + readLocalStatusRefSnapshot: () => Effect.succeed("refs"), readRefSnapshot: () => Effect.succeed("refs"), remoteStatus: () => Effect.gen(function* () { @@ -1163,6 +1175,7 @@ describe("VcsStatusBroadcaster", () => { return state.currentLocalStatus; }), currentBranch: () => Effect.succeed(state.currentLocalStatus.refName), + readLocalStatusRefSnapshot: () => Effect.succeed("refs"), readRefSnapshot: () => Effect.succeed("refs"), remoteStatus: () => Effect.suspend(() => { @@ -1553,6 +1566,7 @@ describe("VcsStatusBroadcaster", () => { }), currentBranch: () => Effect.succeed(baseLocalStatus.refName), invalidateRemoteStatus: () => Effect.void, + readLocalStatusRefSnapshot: () => Effect.sync(() => refSnapshot), readRefSnapshot: () => Effect.sync(() => refSnapshot), remoteStatus: () => Deferred.succeed(fetchStarted, undefined).pipe( @@ -1612,6 +1626,24 @@ describe("VcsStatusBroadcaster", () => { assert.equal(state.localStatusCalls, 1); assert.isString(unmoved.refsDigest); + state.localStatusCalls = 0; + state.beforeRemoteStatus = Effect.sync(() => { + state.worktreeStamp = "feature in /linked"; + }); + const worktreeChanged = yield* broadcaster.refreshStatus("/repo"); + assert.equal(state.localStatusCalls, 1); + assert.isString(worktreeChanged.refsDigest); + assert.notEqual(worktreeChanged.refsDigest, unmoved.refsDigest); + + state.localStatusCalls = 0; + state.beforeRemoteStatus = Effect.sync(() => { + state.worktreeStamp = null; + }); + const worktreesUnreadable = yield* broadcaster.refreshStatus("/repo"); + assert.equal(state.localStatusCalls, 1); + assert.isUndefined(worktreesUnreadable.refsDigest); + state.worktreeStamp = "feature in /linked"; + state.localStatusCalls = 0; state.currentRemoteStatus = baseRemoteStatus; state.beforeRemoteStatus = Effect.sync(() => { diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.ts b/apps/server/src/vcs/VcsStatusBroadcaster.ts index 156290ed0ca6a..d1e9a9c5496c6 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.ts @@ -702,7 +702,7 @@ export const make = Effect.gen(function* () { if (refsAtLocalRead === undefined) { yield* refreshLocalStatusCore(cwd); } else { - const refs = yield* workflow.readRefSnapshot(cwd); + const refs = yield* workflow.readLocalStatusRefSnapshot(cwd); if (refs === null || refs !== (yield* Ref.get(refsAtLocalRead))) { yield* Ref.set(refsAtLocalRead, null); yield* refreshLocalStatusCore(cwd); @@ -732,7 +732,8 @@ export const make = Effect.gen(function* () { } yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true }); // A fetch, ours or not, can move the base used for local Changes totals. - const refs = refsBeforeLocalRead === null ? null : yield* workflow.readRefSnapshot(cwd); + const refs = + refsBeforeLocalRead === null ? null : yield* workflow.readLocalStatusRefSnapshot(cwd); if (refs === null || refs !== refsBeforeLocalRead) { yield* refreshLocalStatusCore(cwd); } @@ -748,7 +749,7 @@ export const make = Effect.gen(function* () { )(function* (rawCwd, options) { const cwd = yield* withFileSystem(normalizeCwd(rawCwd)); yield* acquireBranchChangesDemand(cwd); - // Lets the client keep its cached branch list when no ref moved since its last refresh. + // Lets the client keep its cached branch list when refs and worktree paths match its last refresh. const withRefsDigest = (status: VcsStatusResult, refs: string | null) => refs === null ? status @@ -765,10 +766,13 @@ export const make = Effect.gen(function* () { const parts = yield* getStatusParts(cwd); return withRefsDigest(mergeGitStatusParts(parts.local, parts.remote), refs); } - const refsBeforeLocalRead = yield* workflow.readRefSnapshot(cwd); + const refsBeforeLocalRead = yield* workflow.readLocalStatusRefSnapshot(cwd); yield* refreshLocalStatusCore(cwd); const { status, refs } = yield* refreshRemoteAndLocalTotals(cwd, rawCwd, refsBeforeLocalRead); - return withRefsDigest(status, refs); + return withRefsDigest( + status, + refs === null ? null : yield* workflow.readRefSnapshot(cwd, refs), + ); }, Effect.scoped); const refreshAfterCheckout: VcsStatusBroadcaster["Service"]["refreshAfterCheckout"] = Effect.fn( diff --git a/apps/web/src/components/BranchToolbarBranchSelector.tsx b/apps/web/src/components/BranchToolbarBranchSelector.tsx index 2fb938b04bb40..4bf062b27d93f 100644 --- a/apps/web/src/components/BranchToolbarBranchSelector.tsx +++ b/apps/web/src/components/BranchToolbarBranchSelector.tsx @@ -631,7 +631,7 @@ export function BranchToolbarBranchSelector({ if (branchCwd === null) return; void refreshLocalStatusForPicker({ environmentId, - input: { cwd: branchCwd, localOnly: true }, + input: { cwd: branchCwd }, }); }); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- refs listed while the project was cloning are empty; reload them past the server's snapshot when the clone finishes @@ -685,7 +685,7 @@ export function BranchToolbarBranchSelector({ if (open && !isBranchMenuOpen && branchCwd !== null) { void refreshLocalStatusForPicker({ environmentId, - input: { cwd: branchCwd, localOnly: true }, + input: { cwd: branchCwd }, }); } if (!open) { diff --git a/apps/web/src/components/WorktreeBaseBranchPicker.tsx b/apps/web/src/components/WorktreeBaseBranchPicker.tsx index dd6520a11dab8..eb740a78e4233 100644 --- a/apps/web/src/components/WorktreeBaseBranchPicker.tsx +++ b/apps/web/src/components/WorktreeBaseBranchPicker.tsx @@ -5,6 +5,7 @@ import { useState } from "react"; import { usePaginatedBranches } from "../state/queries"; import { useEnvironmentQuery } from "../state/query"; +import { useAtomCommand } from "../state/use-atom-command"; import { vcsEnvironment } from "../state/vcs"; import { BranchPicker, BranchPickerRefItem } from "./BranchPicker"; import { resolveBranchTriggerLabel, sanitizeNewRefName } from "./BranchToolbar.logic"; @@ -35,6 +36,9 @@ export function WorktreeBaseBranchPicker({ const messages = useMessages(); const [open, setOpen] = useState(false); const [query, setQuery] = useState(""); + const refreshLocalStatusForPicker = useAtomCommand(vcsEnvironment.refreshLocalStatusForPicker, { + reportFailure: false, + }); const branches = usePaginatedBranches( { environmentId, @@ -84,6 +88,9 @@ export function WorktreeBaseBranchPicker({ : null); const handleOpenChange = (next: boolean) => { setOpen(next); + if (next && !open && cwd !== null) { + void refreshLocalStatusForPicker({ environmentId, input: { cwd } }); + } if (!next) setQuery(""); }; return ( diff --git a/packages/client-runtime/src/state/vcs.test.ts b/packages/client-runtime/src/state/vcs.test.ts index edc005263b432..3ed0bb0516235 100644 --- a/packages/client-runtime/src/state/vcs.test.ts +++ b/packages/client-runtime/src/state/vcs.test.ts @@ -466,7 +466,7 @@ describe("cached VCS refs", () => { yield* atoms.refreshLocalStatusForPicker.run(registry, { environmentId: TARGET.environmentId, - input: { cwd: "/repo", localOnly: true }, + input: { cwd: "/repo" }, }); expect(yield* Ref.get(clears)).toBe(3); expect(registry.get(vcsRefsCacheStateAtom(TARGET)).revision).toBe(3); @@ -489,8 +489,9 @@ describe("cached VCS refs", () => { const refreshStarted = yield* Deferred.make(); const releaseRefresh = yield* Deferred.make(); const client = { - [WS_METHODS.vcsRefreshStatus]: () => + [WS_METHODS.vcsRefreshStatus]: (input: { cwd: string; localOnly?: boolean }) => Deferred.succeed(refreshStarted, undefined).pipe( + Effect.tap(() => Effect.sync(() => expect(input.localOnly).toBe(true))), Effect.andThen(Deferred.await(releaseRefresh)), Effect.as({}), ), @@ -527,12 +528,7 @@ describe("cached VCS refs", () => { const target = { environmentId: TARGET.environmentId, input: { cwd: "/repo" } }; const refresh = yield* Effect.forkChild( - Effect.exit( - atoms.refreshLocalStatusForPicker.run(registry, { - ...target, - input: { cwd: "/repo", localOnly: true }, - }), - ), + Effect.exit(atoms.refreshLocalStatusForPicker.run(registry, target)), { startImmediately: true }, ); yield* Deferred.await(refreshStarted); diff --git a/packages/client-runtime/src/state/vcs.ts b/packages/client-runtime/src/state/vcs.ts index dab79e282a4d2..d5c16b434eb7f 100644 --- a/packages/client-runtime/src/state/vcs.ts +++ b/packages/client-runtime/src/state/vcs.ts @@ -28,6 +28,7 @@ import { safeErrorLogAttributes } from "../errors/safeLog.ts"; import * as Persistence from "../platform/persistence.ts"; import { request, + requestGuarded, subscribe, subscribeVcsBranch, refreshVcsBranch, @@ -360,6 +361,8 @@ export function createVcsEnvironmentAtoms( refreshLocalStatusForPicker: createEnvironmentRpcCommand(runtime, { label: "environment-data:vcs:refresh-local-status-for-picker", tag: WS_METHODS.vcsRefreshStatus, + execute: (input: { readonly cwd: string }) => + requestGuarded(WS_METHODS.vcsRefreshStatus, { cwd: input.cwd, localOnly: true }), onSettled: invalidateRefsIfChanged, }), createWorktree: createEnvironmentRpcCommand(runtime, { diff --git a/scripts/scenarios/branch-picker-sees-external-worktree.e2e.ts b/scripts/scenarios/branch-picker-sees-external-worktree.e2e.ts new file mode 100644 index 0000000000000..ccd14a4616f96 --- /dev/null +++ b/scripts/scenarios/branch-picker-sees-external-worktree.e2e.ts @@ -0,0 +1,71 @@ +/// +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; + +import { run } from "./shell.ts"; +import { runPromise, test, WEB } from "./t3.ts"; + +test( + "Reopening the branch picker shows a worktree created outside T3 Code", + WEB, + async ({ t3, app, browser, screen }) => { + const project = await t3.project("demo"); + const git = (...args: string[]) => runPromise(run("git", args, { cwd: project })); + await git("branch", "feature"); + await browser.setViewport({ width: 1280, height: 800 }); + + // Wait for the real server's first forced ref listing to complete before changing Git. + await browser.addInitScript(() => { + const refreshRequests = new Set(); + const watched = new WeakSet(); + const send = WebSocket.prototype.send; + WebSocket.prototype.send = function (data) { + if (typeof data === "string") { + for (const request of [JSON.parse(data)].flat()) { + if (request?.tag === "vcs.listRefs" && request.payload?.refresh === true) { + refreshRequests.add(String(request.id)); + } + } + } + if (!watched.has(this)) { + watched.add(this); + this.addEventListener("message", (event) => { + if (typeof event.data !== "string") return; + for (const response of [JSON.parse(event.data)].flat()) { + if ( + response?._tag === "Exit" && + response.exit?._tag === "Success" && + refreshRequests.has(String(response.requestId)) + ) { + document.documentElement.dataset.refRefresh = "done"; + } + } + }); + } + return send.call(this, data); + }; + }); + + await t3.open("/"); + const branchPicker = browser + .locator('[data-slot="combobox-trigger"][aria-label^="Branch:"]:visible') + .first(); + await branchPicker.click(); + await screen.getByRole("option", /^feature\b/).waitFor(); + await browser.locator('html[data-ref-refresh="done"]').waitFor({ state: "attached" }); + await browser.keyboard.press("Escape"); + // The server coalesces forced snapshot reads for five seconds. + await runPromise(Effect.sleep("6 seconds")); + + await git("worktree", "add", "../other-checkout", "feature"); + try { + await branchPicker.click(); + const feature = screen.getByRole("option", /^feature\b/); + await feature.waitFor(); + await app.screenshot("branch-picker-after-external-worktree"); + await expect(feature).toContainText("worktree"); + } finally { + await git("worktree", "remove", "../other-checkout"); + } + }, +); From b70b9e3653841d4f2ede2953787418ea36370ad7 Mon Sep 17 00:00:00 2001 From: Ryan Bahadori Date: Sat, 21 Nov 2026 13:54:37 -0800 Subject: [PATCH 068/324] test(scripts): launcher test compares the resolved temp path (#40475) Co-authored-by: Julius Marminge --- scripts/build-npm-launcher.test.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/scripts/build-npm-launcher.test.ts b/scripts/build-npm-launcher.test.ts index 9c217e0bbf147..59a808fe3f244 100644 --- a/scripts/build-npm-launcher.test.ts +++ b/scripts/build-npm-launcher.test.ts @@ -118,7 +118,11 @@ it.layer(NodeServices.layer)("build-npm-launcher", (it) => { Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; - const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-npm-launcher-test-" }); + // macOS temp directories sit under /var, a link to /private/var, and the launcher + // reports the resolved path it runs from. + const root = yield* fs.realPath( + yield* fs.makeTempDirectoryScoped({ prefix: "t3-npm-launcher-test-" }), + ); const output = yield* buildNpmLauncher({ version: VERSION, outputDir: path.join(root, "out"), From 4157f383f6387bba817c6189a2061aef3a54d15d Mon Sep 17 00:00:00 2001 From: Gordon Vidal <18126559+gordon-vidal@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:55:43 +0100 Subject: [PATCH 069/324] =?UTF-8?q?fix(web):=20send=20queued=20dictation?= =?UTF-8?q?=20to=20original=20thread=20after=20switching=20th=E2=80=A6=20(?= =?UTF-8?q?#40553)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Julius Marminge --- apps/web/src/components/ChatView.tsx | 3 +- apps/web/src/components/chat/ChatComposer.tsx | 91 ++++++++++++++++++- .../src/components/chat/useComposerSend.ts | 79 +++++++++++----- .../components/chat/useMultipleModelSend.ts | 6 +- ...useEnvironmentSpeechInput.browser.test.tsx | 28 ++++++ .../src/speech/useEnvironmentSpeechInput.ts | 26 +----- apps/web/src/speech/voiceInputSession.ts | 43 ++++++++- 7 files changed, 219 insertions(+), 57 deletions(-) diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 77c47d668daf4..ea16d027fcfe9 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -3054,7 +3054,7 @@ export default function ChatView(props: ChatViewProps) { scrollToEnd, setThreadError, }); - const { onSend } = useComposerSend({ + const { onSend, captureDetachedSend } = useComposerSend({ environmentId, routeThreadKey, currentRouteThreadKeyRef, @@ -3895,6 +3895,7 @@ export default function ChatView(props: ChatViewProps) { onPageScrollRelease={onComposerPageScrollReleaseStable} onCompactContext={onComposerCompactContextStable} onSend={onComposerSendStable} + captureDetachedSend={captureDetachedSend} onResume={onComposerResumeStable} onInterrupt={onInterruptStable} onSelectActivePendingUserInputOption={ diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 9038e6717ba0e..2c3bc34529ffd 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -460,6 +460,19 @@ export interface ChatComposerProps { dispatchMode?: ComposerDispatchMode, submissionIntent?: ComposerSubmissionIntent, ) => void; + captureDetachedSend?: () => ( + e?: { preventDefault: () => void }, + dispatchMode?: ComposerDispatchMode, + submissionIntent?: ComposerSubmissionIntent, + directAnnotation?: { + annotation: PreviewAnnotationPayload; + image: ComposerImageAttachment | null; + }, + detachedOverride?: { + readonly prompt: string; + readonly sendContext: ReturnType; + }, + ) => void; onResume: () => void; onInterrupt: () => void; onSelectActivePendingUserInputOption: (questionId: string, optionValue: string) => void; @@ -562,6 +575,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) onPageScrollRelease, onCompactContext, onSend, + captureDetachedSend, onResume, onInterrupt, onSelectActivePendingUserInputOption, @@ -2185,16 +2199,82 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) }; const submitComposerRef = useRef< - (dispatchMode?: ComposerDispatchMode, submissionIntent?: ComposerSubmissionIntent) => void + ( + dispatchMode?: ComposerDispatchMode, + submissionIntent?: ComposerSubmissionIntent, + options?: { readonly afterDictation?: boolean }, + ) => void >(() => {}); const submitComposer = ( event?: { preventDefault: () => void }, dispatchMode?: ComposerDispatchMode, submissionIntent?: ComposerSubmissionIntent, + options?: { readonly afterDictation?: boolean }, ) => { - if (voiceInputActive) { + if (voiceInputActive && !options?.afterDictation) { event?.preventDefault(); - submitAfterDictation(() => submitComposerRef.current(dispatchMode, submissionIntent)); + const queuedOwnerKey = attachmentTargetKey; + const capturedDraftTarget = composerDraftTarget; + const resolvedDispatchMode = + dispatchMode ?? + resolveComposerDispatchMode({ + running: phase === "running" || phase === "connecting", + alternateModifier: false, + activeTurnDefault: followUpBehavior, + canSteer, + }); + const capturedDetachedSend = + questionAttachmentTarget === null ? (captureDetachedSend?.() ?? null) : null; + const capturedSendContext = + capturedDetachedSend !== null ? (composerRef.current?.getSendContext() ?? null) : null; + const capturedSubmissionTarget = submissionTarget; + submitAfterDictation((transcribedText) => { + const stillLive = + composerMountedRef.current && attachmentTargetKeyRef.current === queuedOwnerKey; + if (stillLive) { + submitComposerRef.current(dispatchMode, submissionIntent, { afterDictation: true }); + return; + } + if ( + !capturedDetachedSend || + !capturedSendContext || + pendingDraftWork.has(queuedOwnerKey) || + countPreparingComposerImages(queuedOwnerKey) > 0 + ) { + return; + } + const liveTarget = resolveLiveComposerDraftTarget(capturedDraftTarget); + const latestDraft = + liveTarget !== null + ? useComposerDraftStore.getState().getComposerDraft(liveTarget) + : null; + submitComposerDraft({ + prompt: transcribedText, + submissionTarget: capturedSubmissionTarget, + event: undefined, + onSend: (sendEvent) => { + capturedDetachedSend(sendEvent, resolvedDispatchMode, submissionIntent, undefined, { + prompt: transcribedText, + sendContext: { + ...capturedSendContext, + ...(latestDraft + ? { + images: latestDraft.images, + files: latestDraft.files, + terminalContexts: latestDraft.terminalContexts, + previewAnnotations: latestDraft.previewAnnotations, + reviewComments: latestDraft.reviewComments, + threadContexts: latestDraft.threadContexts, + environmentContexts: latestDraft.environmentContexts, + } + : {}), + prompt: transcribedText, + }, + }); + return true; + }, + }); + }); return false; } if (submissionBlocked || !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) { @@ -2219,7 +2299,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) return false; } // An empty draft has nothing to send; Enter does what the Resume thread button does. - if (showResumeAction && !activePendingProgress) { + if (showResumeAction && !activePendingProgress && promptRef.current.trim().length === 0) { event?.preventDefault(); if (isSendBusy || environmentUnavailable !== null) return false; onResume(); @@ -2256,7 +2336,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const submitComposerStable = useStableCallback(submitComposer); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes the committed submission handler to the asynchronous dictation completion useLayoutEffect(() => { - submitComposerRef.current = (mode, intent) => submitComposerStable(undefined, mode, intent); + submitComposerRef.current = (mode, intent, options) => + submitComposerStable(undefined, mode, intent, options); }, [submitComposerStable]); useDictationSubmissionShortcut({ enabled: voiceInputActive && !speechInput.preparing, diff --git a/apps/web/src/components/chat/useComposerSend.ts b/apps/web/src/components/chat/useComposerSend.ts index 45c135bce1a1b..d89a9d79febc6 100644 --- a/apps/web/src/components/chat/useComposerSend.ts +++ b/apps/web/src/components/chat/useComposerSend.ts @@ -420,27 +420,35 @@ export function useComposerSend(input: ComposerSendInput) { annotation: PreviewAnnotationPayload; image: ComposerImageAttachment | null; }, + detachedOverride?: { + readonly prompt: string; + readonly sendContext: ReturnType["getSendContext"]>; + }, ) => { e?.preventDefault(); // What the user pressed send on; uploads below can take a while, and a redirect must not // decline approvals for a draft that changed meanwhile. - const promptAtSend = promptRef.current; + const promptAtSend = detachedOverride ? detachedOverride.prompt : promptRef.current; if ( usageLimitsOffered && usageLimitsKey !== null && !directAnnotation && !draftHasNonPromptContent(composerDraftTarget) && - isUsageLimitsCommand(promptRef.current) + isUsageLimitsCommand(promptAtSend) ) { if (openUsageLimits()) { - promptRef.current = ""; setComposerDraftPrompt(composerDraftTarget, ""); - composerRef.current?.resetCursorState(); + if (currentRouteThreadKeyRef.current === routeThreadKey) { + promptRef.current = ""; + composerRef.current?.resetCursorState(); + } } return; } - const sendCtx = composerRef.current?.getSendContext(); + const sendCtx = detachedOverride + ? detachedOverride.sendContext + : composerRef.current?.getSendContext(); // `/side` beats an open question and a plan follow-up, which would send the text to main. const sideChatCommand = sendCtx && !directAnnotation && !queuedRunEdit.isEditing @@ -636,8 +644,10 @@ export function useComposerSend(input: ComposerSendInput) { // Cleared at send, like a regular message, so nothing in it can change or vanish mid-start. if (sendsDraft) { clearComposerDraftContent(composerDraftTarget); - promptRef.current = ""; - composerRef.current?.resetCursorState(); + if (currentRouteThreadKeyRef.current === routeThreadKey) { + promptRef.current = ""; + composerRef.current?.resetCursorState(); + } } const started = await settlePromise(async () => { if (!hasSendableContent) return onSideChat(undefined); @@ -783,10 +793,10 @@ export function useComposerSend(input: ComposerSendInput) { // A direct "send annotation" writes the draft and sends in the same tick; the reference // must be in the text now, not after the next render. const draftPrompt = directAnnotation - ? ensureInlineContextReferences(promptRef.current, [ + ? ensureInlineContextReferences(promptAtSend, [ previewAnnotationContextReference(directAnnotation.annotation), ]) - : promptRef.current; + : promptAtSend; const replyTo = useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.replyTo ?? null; const promptForSend = withReplyReference(draftPrompt, replyTo); @@ -870,9 +880,11 @@ export function useComposerSend(input: ComposerSendInput) { createdAt: new Date().toISOString(), }, clearDraft: () => { - promptRef.current = ""; clearComposerDraftContent(composerDraftTarget); - composerRef.current?.resetCursorState(); + if (currentRouteThreadKeyRef.current === routeThreadKey) { + promptRef.current = ""; + composerRef.current?.resetCursorState(); + } }, onUpdate: (submission) => { setFeedbackSubmissionsByThreadKey((current) => { @@ -910,9 +922,11 @@ export function useComposerSend(input: ComposerSendInput) { replyTo === null; if (freshSessionAvailable && composerHoldsOnlyText && isClearComposerCommand(trimmed)) { armFreshSession(routeThreadKey); - promptRef.current = ""; clearComposerDraftContent(composerDraftTarget); - composerRef.current?.resetCursorState(); + if (currentRouteThreadKeyRef.current === routeThreadKey) { + promptRef.current = ""; + composerRef.current?.resetCursorState(); + } return; } // Read once: an arm made while this send is in flight belongs to the next message. @@ -1024,7 +1038,11 @@ export function useComposerSend(input: ComposerSendInput) { effort: ctxSelectedPromptEffort, text: messageTextForSend || ATTACHMENT_ONLY_BOOTSTRAP_PROMPT, }); - if (composerRef.current?.validateProviderInput(outgoingMessageText) === false) { + const isCurrentRouteThread = () => currentRouteThreadKeyRef.current === routeThreadKey; + if ( + isCurrentRouteThread() && + composerRef.current?.validateProviderInput(outgoingMessageText) === false + ) { return; } @@ -1041,7 +1059,11 @@ export function useComposerSend(input: ComposerSendInput) { setThreadError(threadIdForSend, resolved.error); return; } - if (composerRef.current?.validateProviderInput(resolved.text) === false) return; + if ( + isCurrentRouteThread() && + composerRef.current?.validateProviderInput(resolved.text) === false + ) + return; multipleTargets.push(resolved); } @@ -1049,7 +1071,8 @@ export function useComposerSend(input: ComposerSendInput) { .getState() .getComposerDraft(composerDraftTarget); const draftChangedDuringPreparation = () => { - if (composerRef.current?.hasPendingAttachments() === true) return true; + if (isCurrentRouteThread() && composerRef.current?.hasPendingAttachments() === true) + return true; const draft = useComposerDraftStore.getState().getComposerDraft(composerDraftTarget); return composerDraftContentChanged(draftBeforePreparation, draft); }; @@ -1173,20 +1196,25 @@ export function useComposerSend(input: ComposerSendInput) { const sameIds = (left: ReadonlyArray, right: ReadonlyArray) => left.length === right.length && left.every((id, index) => id === right[index]); const draftChangedSinceSend = () => { - if (composerRef.current?.hasPendingAttachments() === true) return true; - const sendContext = composerRef.current?.getSendContext(); + const liveDraft = useComposerDraftStore.getState().getComposerDraft(composerDraftTarget); + const onCurrentThread = isCurrentRouteThread(); + if (onCurrentThread && composerRef.current?.hasPendingAttachments() === true) return true; + const sendContext = onCurrentThread ? composerRef.current?.getSendContext() : undefined; const attachmentIds = sendContext ? [...sendContext.images, ...sendContext.files].map((attachment) => attachment.id) - : attachmentIdsAtSend; - const promptUnchanged = - promptRef.current === promptAtSend || promptRef.current === promptForSend; + : liveDraft + ? [...liveDraft.images, ...liveDraft.files].map((attachment) => attachment.id) + : attachmentIdsAtSend; + const livePrompt = onCurrentThread + ? promptRef.current + : (liveDraft?.prompt ?? promptAtSend); + const promptUnchanged = livePrompt === promptAtSend || livePrompt === promptForSend; const attachmentsUnchanged = sameIds(attachmentIds, attachmentIdsAtSend) || (annotationImageId !== undefined && sameIds(attachmentIds, attachmentIdsBeforeAnnotation)); // The reply is not in the prompt, so cancelling or changing it is checked on its own. - const liveReply = - useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.replyTo ?? null; + const liveReply = liveDraft?.replyTo ?? null; return !promptUnchanged || !attachmentsUnchanged || liveReply !== replyTo; }; const draftBeforeDecline = useComposerDraftStore @@ -1713,5 +1741,8 @@ export function useComposerSend(input: ComposerSendInput) { }); if (ready) return onSendLatest(...args); }; - return { onSend: onSendWithRouting }; + // No load-balancing refresh: it bails once the draft is no longer displayed, which is the + // only time a detached send runs, so the draft keeps the environment it was dictated for. + const captureDetachedSend = useStableCallback(() => onSend); + return { onSend: onSendWithRouting, captureDetachedSend }; } diff --git a/apps/web/src/components/chat/useMultipleModelSend.ts b/apps/web/src/components/chat/useMultipleModelSend.ts index 25f07b6eb079c..cbfcac768656c 100644 --- a/apps/web/src/components/chat/useMultipleModelSend.ts +++ b/apps/web/src/components/chat/useMultipleModelSend.ts @@ -144,9 +144,11 @@ export function useMultipleModelSend(input: MultipleModelSendInput) { { text: messageText, attachments: attachmentsSnapshot }, m, ); - promptRef.current = ""; clearComposerDraftContent(composerDraftTarget); - composerRef.current?.resetCursorState(); + if (currentRouteThreadKeyRef.current === routeThreadKey) { + promptRef.current = ""; + composerRef.current?.resetCursorState(); + } clearedDraft = true; const clearedDraftSnapshot = useComposerDraftStore .getState() diff --git a/apps/web/src/speech/useEnvironmentSpeechInput.browser.test.tsx b/apps/web/src/speech/useEnvironmentSpeechInput.browser.test.tsx index 8519d6a1ce0cc..99cbff1c14a13 100644 --- a/apps/web/src/speech/useEnvironmentSpeechInput.browser.test.tsx +++ b/apps/web/src/speech/useEnvironmentSpeechInput.browser.test.tsx @@ -987,3 +987,31 @@ it("lets the user retry after a status failure without reselecting the destinati await act(() => mocks.voice.stop()); expect(mocks.transcribeCalls).toEqual(["env-a"]); }); + +it("delivers a queued submission for a persistent draft after switching owners", async () => { + setup({ destination: "env-a" }); + const submit = vi.fn(); + await using screen = await render(); + await act(() => mocks.voice.start()); + expect(mocks.voice.state.phase).toBe("recording"); + await act(async () => { + mocks.voice.submitAfterDictation(submit); + await screen.rerender(); + }); + await vi.waitFor(() => expect(submit).toHaveBeenCalledExactlyOnceWith("dictated")); + expect(mocks.storedDraft).toBe("dictated"); +}); + +it("drops a queued submission for a non-persistent draft when switching owners", async () => { + setup({ destination: "env-a" }); + const submit = vi.fn(); + await using screen = await render(); + await act(() => mocks.voice.start()); + expect(mocks.voice.state.phase).toBe("recording"); + await act(async () => { + mocks.voice.submitAfterDictation(submit); + await screen.rerender(); + }); + await vi.waitFor(() => expect(mocks.voice.state.phase).toBe("idle")); + expect(submit).not.toHaveBeenCalled(); +}); diff --git a/apps/web/src/speech/useEnvironmentSpeechInput.ts b/apps/web/src/speech/useEnvironmentSpeechInput.ts index 0ad3c4b2054e4..c7915685727b6 100644 --- a/apps/web/src/speech/useEnvironmentSpeechInput.ts +++ b/apps/web/src/speech/useEnvironmentSpeechInput.ts @@ -217,11 +217,6 @@ export function useEnvironmentSpeechInput(input: HookInput) { const busyElsewhere = !owns && voiceInputBlocksSubmission(snapshot.state); const startRequestRef = useRef(0); - const pendingSubmissionRef = useRef<{ - ownerKey: string; - submit: (text: string) => void; - text?: string; - } | null>(null); const latestRef = useRef({ input, clientSettings, cleanupPrepared, projectWords, session }); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes committed props before an async completion can read them through the session useLayoutEffect(() => { @@ -233,7 +228,6 @@ export function useEnvironmentSpeechInput(input: HookInput) { mountedRef.current = true; return () => { mountedRef.current = false; - pendingSubmissionRef.current = null; startRequestRef.current += 1; session?.ownerChanged(latestRef.current.input.ownerKey); }; @@ -292,36 +286,23 @@ export function useEnvironmentSpeechInput(input: HookInput) { }, [prepared, setup.downloading, setup.open, setupModelId]); const previousOwnerRef = useRef(input.ownerKey); - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- abandons any queued submission, and a recording that cannot outlive its editor, when the draft's owner changes + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- abandons a recording that cannot outlive its editor when the draft's owner changes useEffect(() => { const previous = previousOwnerRef.current; if (previous === input.ownerKey && !input.disabled) return; previousOwnerRef.current = input.ownerKey; - pendingSubmissionRef.current = null; startRequestRef.current += 1; if (previous !== input.ownerKey) session?.ownerChanged(previous); else if (session?.ownerKey === input.ownerKey) session.cancel(); }, [input.ownerKey, input.disabled, session]); - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- delivers a queued submission only after the transcript has committed to the draft - useEffect(() => { - const pending = pendingSubmissionRef.current; - if (state.phase === "error") pendingSubmissionRef.current = null; - if (state.phase !== "idle" || !pending) return; - pendingSubmissionRef.current = null; - if (!input.disabled && pending.ownerKey === input.ownerKey && pending.text !== undefined) - pending.submit(pending.text); - }, [state, input.ownerKey, input.disabled]); - const submitAfterDictation = useStableCallback((submit: (text: string) => void) => { if (latestRef.current.input.disabled || state.phase === "preparing") return; if (!session || !voiceInputBlocksSubmission(state)) { submit(latestRef.current.input.readDraft().text); return; } - if (pendingSubmissionRef.current) return; - pendingSubmissionRef.current = { ownerKey: latestRef.current.input.ownerKey, submit }; - if (session.state.phase === "recording") void session.stop(); + session.queueSubmission(latestRef.current.input.ownerKey, submit); }); const createTarget = useStableCallback((): VoiceInputTarget => { @@ -359,8 +340,6 @@ export function useEnvironmentSpeechInput(input: HookInput) { } if (latestRef.current.input.disabled) return; latestRef.current.input.commitDraft(text, selection); - if (pendingSubmissionRef.current?.ownerKey === owner) - pendingSubmissionRef.current.text = text; }, readContext: () => (live() ? readContext() : startContext), }; @@ -585,7 +564,6 @@ export function useEnvironmentSpeechInput(input: HookInput) { submitAfterDictation, stop: useStableCallback(() => (owns && session ? session.stop() : Promise.resolve())), cancel: useStableCallback(() => { - pendingSubmissionRef.current = null; startRequestRef.current += 1; setSetup(INITIAL_SETUP); if (owns) session?.cancel(); diff --git a/apps/web/src/speech/voiceInputSession.ts b/apps/web/src/speech/voiceInputSession.ts index f21285457aa15..577b26595efed 100644 --- a/apps/web/src/speech/voiceInputSession.ts +++ b/apps/web/src/speech/voiceInputSession.ts @@ -108,6 +108,11 @@ export class VoiceInputSession { readonly key: SessionKey; private readonly controller: VoiceInputController; private target: VoiceInputTarget | null = null; + private pendingSubmission: { + readonly ownerKey: string; + readonly submit: (text: string) => void; + text?: string; + } | null = null; private snapshot: VoiceInputSessionSnapshot = { state: IDLE_VOICE_STATE, target: null, @@ -237,7 +242,13 @@ export class VoiceInputSession { const draft = target?.readDraft(); return target && draft ? { ownerKey: target.ownerKey, ...draft } : null; }, - commitDraft: (text, selection) => this.target?.commitDraft(text, selection), + commitDraft: (text, selection) => { + const ownerKey = this.target?.ownerKey ?? null; + this.target?.commitDraft(text, selection); + if (ownerKey !== null && this.pendingSubmission?.ownerKey === ownerKey) { + this.pendingSubmission.text = text; + } + }, onStateChange: (state) => { if (this.disposed) return; const recordingStartedAt = @@ -245,6 +256,15 @@ export class VoiceInputSession { this.publish({ ...this.snapshot, state, recordingStartedAt }); if (state.phase !== "recording" && state.phase !== "transcribing") this.publishActivity(SILENT_ACTIVITY); + if (state.phase === "error") { + this.pendingSubmission = null; + return; + } + if (state.phase === "idle" && this.pendingSubmission !== null) { + const pending = this.pendingSubmission; + this.pendingSubmission = null; + if (pending.text !== undefined) pending.submit(pending.text); + } }, }); } @@ -281,6 +301,7 @@ export class VoiceInputSession { voiceInputBlocksSubmission(this.controller.currentState) && this.target?.ownerKey !== target.ownerKey; if (busyElsewhere) return Promise.resolve(); + this.pendingSubmission = null; this.target = target; this.onSpeechStatus = onSpeechStatus; this.publishActivity(SILENT_ACTIVITY); @@ -295,11 +316,29 @@ export class VoiceInputSession { this.publish({ ...this.snapshot, target }); } + /** Queues a submission to run once the active dictation commits its transcript. */ + queueSubmission(ownerKey: string, submit: (text: string) => void): boolean { + if ( + this.disposed || + this.target?.ownerKey !== ownerKey || + !voiceInputBlocksSubmission(this.controller.currentState) || + this.pendingSubmission !== null + ) { + return false; + } + this.pendingSubmission = { ownerKey, submit }; + if (this.controller.currentState.phase === "recording") { + void this.controller.stop(); + } + return true; + } + stop(): Promise { return this.controller.stop(); } cancel(): void { + this.pendingSubmission = null; this.controller.cancel(); } @@ -310,11 +349,13 @@ export class VoiceInputSession { /** The editor for `ownerKey` now shows another draft; only a persistent target keeps going. */ ownerChanged(ownerKey: string): void { if (this.target?.ownerKey !== ownerKey || this.target.persistent) return; + this.pendingSubmission = null; this.controller.ownerChanged(); } dispose(): void { this.disposed = true; + this.pendingSubmission = null; this.controller.dispose(); this.listeners.clear(); this.activityListeners.clear(); From 404dd5bad26dad5c1ea43e1949cab4d64e5c6822 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 14:02:30 -0800 Subject: [PATCH 070/324] fix(server): Conventional Commits style uses a Conventional Commit PR title (#40571) --- .../textGeneration/TextGenerationPresets.ts | 2 +- evals/pr-content/README.md | 4 +- evals/pr-content/grade.ts | 3 ++ evals/pr-content/run.test.ts | 11 ++++- evals/pr-content/run.ts | 42 +++++++++++++++++-- 5 files changed, 55 insertions(+), 7 deletions(-) diff --git a/apps/server/src/textGeneration/TextGenerationPresets.ts b/apps/server/src/textGeneration/TextGenerationPresets.ts index 2dd3b95321290..ad3ff52688e9f 100644 --- a/apps/server/src/textGeneration/TextGenerationPresets.ts +++ b/apps/server/src/textGeneration/TextGenerationPresets.ts @@ -5,7 +5,7 @@ export const conventionalCommitsTextGenerationPolicy: TextGenerationPolicy = { commitInstructions: "Use Conventional Commits when generating commit subjects. Prefer the narrowest accurate type and include a scope only when it is obvious from the diff. Start the description after the colon with a lowercase word, never a proper noun or acronym, because commitlint rejects a capitalized description.", changeRequestInstructions: - "Keep the change request title concise. Do not force Conventional Commit syntax into the title unless the repository already uses it.", + "Keep the change request title concise. When the listed commits use Conventional Commits, write the title as a Conventional Commit subject too, for example 'feat(web): add a recorder', with the narrowest accurate type, a scope only when obvious, and a lowercase description. Otherwise do not force Conventional Commit syntax into the title.", inferRepositoryConventions: false, }; diff --git a/evals/pr-content/README.md b/evals/pr-content/README.md index 38e08c9fb8942..aaec0b8bcd54d 100644 --- a/evals/pr-content/README.md +++ b/evals/pr-content/README.md @@ -1,6 +1,6 @@ # PR content -Checks the reported failure where a babysitting follow-up became a PR's title and body. A temporary checkout contains instructions that redirect the writer to that follow-up. The control case has no babysitting request. Both must describe the model retirement diff. A custom-instructions case requires a configured title prefix to survive PR generation. +Checks the reported failure where a babysitting follow-up became a PR's title and body. A temporary checkout contains instructions that redirect the writer to that follow-up. The control case has no babysitting request. Both must describe the model retirement diff. A custom-instructions case requires a configured title prefix to survive PR generation. Two Conventional Commits style cases require a Conventional Commit title when the branch's commits use one, and a plain title when they do not. ```sh cd evals @@ -10,4 +10,4 @@ pnpm pr-content --model gpt-6-luna --out runs/pr-after --baseline runs/pr-before Uses the local Codex login and the server's actual PR generator. Each case runs three times. `--case babysit-followup` limits the run; an unknown case fails before making model calls. Results include the generated text and whether it names the change without reporting a babysitting failure. A case fails when at least half its samples fail. Review the bodies for accuracy as well as the automated result. -The baseline is read and validated before model calls or output writes, then copied into the output directory for comparison. Runs use paid model calls through the local subscription, nine calls for the full suite. The CLI does not expose per-call cost here. +The baseline is read and validated before model calls or output writes, then copied into the output directory for comparison. Runs use paid model calls through the local subscription, fifteen calls for the full suite. The CLI does not expose per-call cost here. diff --git a/evals/pr-content/grade.ts b/evals/pr-content/grade.ts index 6682a1b163d95..b3e0d1bcbcb78 100644 --- a/evals/pr-content/grade.ts +++ b/evals/pr-content/grade.ts @@ -4,3 +4,6 @@ export const gradePrContent = (generated: { title: string; body: string }) => !/blocked|cannot access|can't start babysitting|restore GitHub|provide the PR number/i.test( `${generated.title}\n${generated.body}`, ); + +export const hasConventionalCommitPrefix = (title: string) => + /^[a-z]+(\([^()\n]+\))?!?: \S/.test(title); diff --git a/evals/pr-content/run.test.ts b/evals/pr-content/run.test.ts index 9b5f841547a7d..04fc47707adf3 100644 --- a/evals/pr-content/run.test.ts +++ b/evals/pr-content/run.test.ts @@ -6,7 +6,7 @@ import * as Path from "effect/Path"; import * as Stream from "effect/Stream"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; import { expect, it } from "vite-plus/test"; -import { gradePrContent } from "./grade.ts"; +import { gradePrContent, hasConventionalCommitPrefix } from "./grade.ts"; effectIt.live("rejects an empty case before requiring Codex or creating output", () => Effect.gen(function* () { @@ -70,3 +70,12 @@ it.each([ ])("grades $title", ({ title, body, passed }) => { expect(gradePrContent({ title, body })).toBe(passed); }); + +it.each([ + { title: "feat(models): add retirement metadata", conventional: true }, + { title: "fix!: drop legacy models", conventional: true }, + { title: "Add retirement metadata", conventional: false }, + { title: "Retire: legacy models", conventional: false }, +])("detects a Conventional Commit prefix in $title", ({ title, conventional }) => { + expect(hasConventionalCommitPrefix(title)).toBe(conventional); +}); diff --git a/evals/pr-content/run.ts b/evals/pr-content/run.ts index 0d76515ecb79a..9f3bc13b4f09e 100644 --- a/evals/pr-content/run.ts +++ b/evals/pr-content/run.ts @@ -8,8 +8,9 @@ import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import * as CodexTextGeneration from "../../apps/server/src/textGeneration/CodexTextGeneration.ts"; +import { conventionalCommitsTextGenerationPolicy } from "../../apps/server/src/textGeneration/TextGenerationPresets.ts"; import * as ServerConfig from "../../apps/server/src/config.ts"; -import { gradePrContent } from "./grade.ts"; +import { gradePrContent, hasConventionalCommitPrefix } from "./grade.ts"; const { values } = NodeUtil.parseArgs({ options: { @@ -43,6 +44,9 @@ const fixtures = [ source: "Reported PR title replaced by a babysitting failure, November 2026", launchArgs: undefined, titlePrefix: undefined, + policy: undefined, + commitSummary: "abc123 Retire legacy models", + conventionalTitle: undefined, threadContext: "user: Retire legacy models.\nassistant: Added retirement dates and successors. Tests passed.\nuser: in a few minutes pr will be up then $babysit-pr", }, @@ -51,6 +55,9 @@ const fixtures = [ source: "Control for the babysitting regression", launchArgs: undefined, titlePrefix: undefined, + policy: undefined, + commitSummary: "abc123 Retire legacy models", + conventionalTitle: undefined, threadContext: "user: Retire legacy models.\nassistant: Added retirement dates and successors. Tests passed.", }, @@ -60,9 +67,34 @@ const fixtures = [ launchArgs: "--config 'developer_instructions=\"Repository PR title policy: every generated PR title MUST start with the exact prefix TEAM:. Preserve this prefix in the returned title JSON field.\"'", titlePrefix: "TEAM:", + policy: undefined, + commitSummary: "abc123 Retire legacy models", + conventionalTitle: undefined, threadContext: "user: Retire legacy models.\nassistant: Added retirement dates and successors. Tests passed.", }, + { + id: "conventional-commits-title", + source: "pingdotgg/t3code#40562: Conventional Commits style dropped the prefix from PR titles", + launchArgs: undefined, + titlePrefix: undefined, + policy: conventionalCommitsTextGenerationPolicy, + commitSummary: + "abc123 feat(models): add retirement dates for legacy models\ndef456 feat(models): name a successor for each retired model", + conventionalTitle: true, + threadContext: undefined, + }, + { + id: "conventional-commits-plain-history", + source: "Control for #40562: plain commit subjects keep a plain PR title", + launchArgs: undefined, + titlePrefix: undefined, + policy: conventionalCommitsTextGenerationPolicy, + commitSummary: + "abc123 Add retirement dates for legacy models\ndef456 Name a successor for each retired model", + conventionalTitle: false, + threadContext: undefined, + }, ]; const selectedFixtures = fixtures.filter( (fixture) => values.case === undefined || fixture.id === values.case, @@ -96,11 +128,12 @@ await Effect.runPromise( modelSelection: { instanceId: ProviderInstanceId.make("codex"), model }, baseBranch: "main", headBranch: "fix/retire-legacy-models", - commitSummary: "abc123 Retire legacy models", + commitSummary: fixture.commitSummary, diffSummary: "src/models.ts | 2 ++", diffPatch: 'diff --git a/src/models.ts b/src/models.ts\n--- a/src/models.ts\n+++ b/src/models.ts\n@@ -1 +1,3 @@\n export const legacyModel = {\n+ retirementDate: "2026-10-23",\n+ successor: "replacement-model",\n };', threadContext: fixture.threadContext, + policy: fixture.policy, }); results.push({ id: fixture.id, @@ -108,7 +141,10 @@ await Effect.runPromise( ...generated, passed: gradePrContent(generated) && - (fixture.titlePrefix === undefined || generated.title.startsWith(fixture.titlePrefix)), + (fixture.titlePrefix === undefined || + generated.title.startsWith(fixture.titlePrefix)) && + (fixture.conventionalTitle === undefined || + hasConventionalCommitPrefix(generated.title) === fixture.conventionalTitle), }); } } From dac6422b89f6f49660e87febe8c6e2cc556e7e63 Mon Sep 17 00:00:00 2001 From: Ibrahim Elkamali Date: Sun, 22 Nov 2026 00:13:07 +0200 Subject: [PATCH 071/324] fix(server): PowerPoint speaker notes leave out the notes page's slide number, date, header and footer (#40568) Co-authored-by: Julius Marminge --- .../server/src/provider/documentTextWorker.ts | 18 ++++++++++-- .../src/provider/userInputAttachments.test.ts | 29 +++++++++++++++++-- 2 files changed, 43 insertions(+), 4 deletions(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index 1e9e8e86b57cd..e254e101cf93e 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -221,6 +221,18 @@ function* paragraphs(node: XmlNode): Generator { } } } +// A notes page also holds the slide image, slide number, date, header and footer placeholders. +const NOTES_PAGE_PLACEHOLDERS = new Set(["sldImg", "sldNum", "dt", "hdr", "ftr"]); +const isNotesPagePlaceholder = (node: XmlNode) => + node.name === "sp" && NOTES_PAGE_PLACEHOLDERS.has(all(node, "ph").next().value?.attrs.type ?? ""); +function withoutNotesPagePlaceholders(node: XmlNode): XmlNode { + return { + ...node, + children: node.children + .filter((child) => typeof child === "string" || !isNotesPagePlaceholder(child)) + .map((child) => (typeof child === "string" ? child : withoutNotesPagePlaceholders(child))), + }; +} function* inCell(parts: Iterable): Generator { yield CELL_START; yield* parts; @@ -733,14 +745,16 @@ async function* document(path: string, extension: string): AsyncGenerator { "ppt/slides/_rels/slide1.xml.rels": '', "ppt/notesSlides/notes7.xml": - "evacuation code ORCHID-81", + 'evacuation code ORCHID-81Harbor briefing11/21/2026Crew only57', "ppt/notesSlides/notes3.xml": "Board at gate 4", "ppt/notesSlides/ignored.xml": "Unrelated notes", @@ -1001,7 +1001,32 @@ describe("question answer paths", () => { "Departure\nNotes:\nBoard at gate 4", ], occurrences: { text: "## Slide ", count: 2 }, - absent: ["Unrelated notes", "[Skipped document part", "[Extracted text truncated"], + absent: [ + "Unrelated notes", + "Harbor briefing", + "11/21/2026", + "Crew only", + "57", + "[Skipped document part", + "[Extracted text truncated", + ], + }, + { + ext: "pptx", + bounded: true, + parts: { + "ppt/presentation.xml": + '', + "ppt/_rels/presentation.xml.rels": + '', + "ppt/slides/a.xml": "

    Slide text

    ", + "ppt/slides/_rels/a.xml.rels": + '', + "ppt/notesSlides/empty.xml": + '57', + }, + expected: ["Slide text"], + absent: ["Notes:", "57"], }, ...[false, true].map((missing) => ({ ext: "pptx", From fd6c36725fe0d2542cb163a7d9e65d469dca93b2 Mon Sep 17 00:00:00 2001 From: oliver <97427849+flamboh@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:15:56 -0800 Subject: [PATCH 072/324] fix: write "Pull requests" in sentence case on Android and in the keyboard guide (#37758) Co-authored-by: Julius Marminge --- .../modules/t3nativecontrols/T3WorkspaceNavigationModule.kt | 2 +- docs/user/keyboard-focus.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3WorkspaceNavigationModule.kt b/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3WorkspaceNavigationModule.kt index 1208f3176935d..b4183cb3c8fcf 100644 --- a/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3WorkspaceNavigationModule.kt +++ b/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3WorkspaceNavigationModule.kt @@ -421,7 +421,7 @@ class T3WorkspaceNavigationView( } private fun expandedTabTitle(tab: String) = - if (tab == "pullRequests") "Pull Requests" else tabTitle(tab) + if (tab == "pullRequests") "Pull requests" else tabTitle(tab) @Composable private fun tabIconPainter(tab: String) = painterResource( diff --git a/docs/user/keyboard-focus.md b/docs/user/keyboard-focus.md index 6691b525167d7..2a8edd62b2fa1 100644 --- a/docs/user/keyboard-focus.md +++ b/docs/user/keyboard-focus.md @@ -2,7 +2,7 @@ The command palette keeps focus while open. Closing it returns focus to the composer in chat, or to the previous control on other pages. Choosing a workspace focus command moves to that -area instead. Opening Pull Requests moves focus into that page. +area instead. Opening Pull requests moves focus into that page. While the palette or model picker is open, number shortcuts select its entries instead of switching threads. Model shortcuts work in Settings as well as the composer. See [Keybindings](./keybindings.md) to customize these shortcuts. @@ -14,7 +14,7 @@ becomes ready. Opening or switching to a terminal explicitly still focuses it. On web and desktop, press `F6` or `Shift+F6` to move between the Threads sidebar, conversation, message input, and visible panels. Navigation wraps around and restores -the last focused control in each area. Pull Requests has a page content area. In Settings, +the last focused control in each area. Pull requests has a page content area. In Settings, `F6` moves between the section list and the open section. Hidden areas are skipped. Other dialogs and form popups retain focus; a thread context menu closes when an area command moves focus away. From 828fe374d3a0418404cddea9c904c0f2c1787c9b Mon Sep 17 00:00:00 2001 From: Adamulek123 Date: Sat, 21 Nov 2026 23:17:43 +0100 Subject: [PATCH 073/324] perf(issues): skip redundant thread payload reads (#40569) Co-authored-by: Julius Marminge --- apps/server/src/issue/linkedThreads.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/apps/server/src/issue/linkedThreads.ts b/apps/server/src/issue/linkedThreads.ts index c38b75c6b0944..03c337996f08a 100644 --- a/apps/server/src/issue/linkedThreads.ts +++ b/apps/server/src/issue/linkedThreads.ts @@ -15,6 +15,8 @@ const decodeLinkedThreads = Schema.decodeUnknownEffect(IssueLinkedThreadsResult) export const listLinkedIssueThreads = Effect.fn("listLinkedIssueThreads")( function* (key: ThreadIssueKey) { const sql = yield* SqlClient.SqlClient; + // The CASE stops SQLite hoisting the side-chat check out of the link loop, + // where it would re-parse every thread's payload, not just matching ones. const rows = yield* sql<{ id: string; projectId: string; @@ -37,9 +39,11 @@ export const listLinkedIssueThreads = Effect.fn("listLinkedIssueThreads")( t.updated_at AS "updatedAt" FROM orchestration_v2_projection_threads AS t JOIN json_each(t.payload_json, '$.issues') AS link - WHERE json_extract(link.value, '$.key') = ${key.key.trim()} - AND t.deleted_at IS NULL - AND json_extract(t.payload_json, '$.lineage.sideChat') IS NOT 1 + WHERE t.deleted_at IS NULL + AND CASE WHEN json_extract(link.value, '$.key') = ${key.key.trim()} + THEN json_extract(t.payload_json, '$.lineage.sideChat') IS NOT 1 + ELSE 0 + END ORDER BY "updatedAt" DESC, id ASC `.pipe(NodeSqliteClient.readOnly); const threads = rows From cbd1f04bcad4ff0f39019264c80b5b1a58ca3879 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 14:24:11 -0800 Subject: [PATCH 074/324] fix(mobile): Steer interrupts ACP agents without native steering instead of queueing (#40572) --- apps/mobile/src/state/use-thread-composer-state.ts | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts index 48e7fc02b5b32..a26af21009c05 100644 --- a/apps/mobile/src/state/use-thread-composer-state.ts +++ b/apps/mobile/src/state/use-thread-composer-state.ts @@ -870,7 +870,6 @@ export function useThreadComposerState(input: { } // Resolve at send time because outbox delivery may be delayed. - // Steering uses "auto" so an ended turn queues a run instead of restoring the draft. // An approval redirect must steer the waiting turn instead of queueing behind it. const activeTurnDefault = beforeDispatch !== undefined ? "steer" : followUpBehavior; const followUpAction = resolveComposerDispatchMode({ @@ -885,9 +884,7 @@ export function useThreadComposerState(input: { ? "queue" : followUpAction === "auto" ? null - : followUpAction === "queue" - ? "queue" - : "auto"; + : followUpAction; // A redirect belongs to the approval it answers; the armed session waits for the next message. const freshContext = beforeDispatch === undefined && isFreshSessionPending(threadKey); From 87ba8987aa16966e23ef075b0e99ed53dbb76e31 Mon Sep 17 00:00:00 2001 From: "Paul Dupuy, Jr." <70114489+pauldupuyjr@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:35:21 -0600 Subject: [PATCH 075/324] fix(server): a thread named before its first message keeps its name (#40567) Co-authored-by: Julius Marminge --- apps/server/src/mcp/OrchestratorMcpService.ts | 1 + .../src/mcp/toolkits/project/handlers.test.ts | 2 ++ .../src/mcp/toolkits/project/handlers.ts | 1 + .../src/orchestration-v2/Orchestrator.ts | 7 +++- .../orchestration-v2/ThreadLaunchService.ts | 3 ++ .../ThreadTitleRegenerationService.test.ts | 32 +++++++++++++++++-- packages/contracts/src/orchestrationV2.ts | 3 +- 7 files changed, 44 insertions(+), 5 deletions(-) diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 07b137c61e354..e8046bdd3c9c8 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -3298,6 +3298,7 @@ const make = Effect.gen(function* () { threadId, projectId: parent.thread.projectId, title, + ...(request.title?.trim() ? { titleRenamed: true } : {}), modelSelection: target.modelSelection, runtimeMode, interactionMode, diff --git a/apps/server/src/mcp/toolkits/project/handlers.test.ts b/apps/server/src/mcp/toolkits/project/handlers.test.ts index c13a8ab9353cc..d03b038ee0780 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.test.ts @@ -254,6 +254,7 @@ it.effect( expect(belowCeiling.launched[0]?.runtimeMode).toBe("approval-required"); expect(belowCeiling.launched[0]?.initialMessage?.senderThreadId).toBeUndefined(); expect(belowCeiling.launched[0]?.generateTitle).toBeUndefined(); + expect(belowCeiling.launched[0]?.titleRenamed).toBe(true); const titled = yield* launchWith("full-access", "full-access", { title: "Fix", @@ -261,6 +262,7 @@ it.effect( message: "Fix the bug", }); expect(titled.launched[0]).toMatchObject({ title: "Fix", generateTitle: true }); + expect(titled.launched[0]?.titleRenamed).toBeUndefined(); for (const message of [undefined, "", " \n "]) { const idleTitled = yield* launchWith("full-access", "full-access", { diff --git a/apps/server/src/mcp/toolkits/project/handlers.ts b/apps/server/src/mcp/toolkits/project/handlers.ts index 3966d48ccd090..76f53b43bdfdc 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.ts @@ -438,6 +438,7 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { projectId, title: input.title, ...(input.generateTitle === undefined ? {} : { generateTitle: input.generateTitle }), + ...(input.generateTitle === true ? {} : { titleRenamed: true }), modelSelection, runtimeMode: startedRuntimeMode, interactionMode, diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index dd69750a43496..bcbe8a3656017 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -4040,6 +4040,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio id: command.threadId, projectId: command.projectId, title: command.title, + ...(command.titleRenamed === true ? { titleRenamed: true } : {}), providerInstanceId: command.modelSelection.instanceId, modelSelection: command.modelSelection, runtimeMode: command.runtimeMode, @@ -7428,7 +7429,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio !hasTitleSetBeforeFirstMessage(projection.thread, command.titleSeed); if ( !isNativeMaintenanceCommand(command) && - (seedsUntitledThread || (command.createdBy === "user" && (yield* onlyMaintenanceHistory))) + (seedsUntitledThread || + (command.createdBy === "user" && + // A draft opened by `/compact` is titled after it, so only a chosen title stays here. + projection.thread.titleRenamed !== true && + (yield* onlyMaintenanceHistory))) ) { const now = yield* DateTime.now; const thread: OrchestrationV2AppThread = { diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.ts index e0ae516a190b5..0382415179bfc 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.ts @@ -103,6 +103,8 @@ export interface ThreadLaunchInput { readonly projectId: ProjectId; readonly title: string; readonly generateTitle?: boolean; + /** The caller chose `title`, so a first message keeps it. */ + readonly titleRenamed?: boolean; readonly modelSelection: ModelSelection; readonly runtimeMode: RuntimeMode; readonly interactionMode: ProviderInteractionMode; @@ -1458,6 +1460,7 @@ const make = Effect.gen(function* () { threadId: candidateThreadId, projectId: input.projectId, title: input.title, + ...(input.titleRenamed === true ? { titleRenamed: true } : {}), modelSelection: input.modelSelection, runtimeMode: input.runtimeMode, interactionMode: input.interactionMode, diff --git a/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts b/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts index 20cd5aaa76236..1d39000ed3a9f 100644 --- a/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts @@ -343,9 +343,19 @@ describe("ThreadTitleRegenerationService", () => { const threads = yield* ThreadManagement.ThreadManagementService; const outbox = yield* EffectOutbox.EffectOutboxV2; // An MCP launch names the thread, or leaves a placeholder, and sends no message. - for (const [key, title, expectedTitle, generates] of [ - ["preset", "[API] #4821 — retry webhook deliveries after a timeout", undefined, false], - ["placeholder", placeholderThreadTitle("Parent", 0), seed, true], + for (const [key, title, titleRenamed, compactFirst, expectedTitle, generates] of [ + [ + "preset", + "[API] #4821 - retry webhook deliveries after a timeout", + false, + false, + undefined, + false, + ], + ["placeholder", placeholderThreadTitle("Parent", 0), false, false, seed, true], + ["named like a placeholder", "Release thread 2", true, false, undefined, false], + ["named, then compacted", "Release notes", true, true, undefined, false], + ["draft titled by its /compact", "/compact", false, true, seed, true], ] as const) { const threadId = ThreadId.make(`thread:title:${key}`); yield* threads.dispatch({ @@ -354,6 +364,7 @@ describe("ThreadTitleRegenerationService", () => { threadId, projectId, title, + ...(titleRenamed ? { titleRenamed } : {}), modelSelection, runtimeMode: "full-access", interactionMode: "default", @@ -362,6 +373,21 @@ describe("ThreadTitleRegenerationService", () => { createdBy: "agent", creationSource: "mcp", }); + if (compactFirst) { + yield* threads.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`command:title:${key}:compact`), + threadId, + messageId: MessageId.make(`command:title:${key}:compact:message`), + text: "/compact", + titleSeed: "/compact", + attachments: [], + modelSelection, + dispatchMode: { type: "defer_start" }, + createdBy: "user", + creationSource: "web", + }); + } const requestId = CommandId.make(`command:title:${key}:message`); yield* threads.dispatch({ type: "message.dispatch", diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 51d762d77c14f..2d5bc546d1800 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -538,7 +538,7 @@ export const OrchestrationV2AppThread = Schema.Struct({ ), ), lastTitleRegeneration: Schema.optional(Schema.NullOr(OrchestrationV2LastTitleRegeneration)), - /** Set by a rename until a generated title replaces it; absent reads as false. */ + /** Set by a rename or a naming launch until a generated title replaces it; absent reads false. */ titleRenamed: Schema.optional(Schema.Boolean), rollbackRequestId: Schema.optional(CommandId), rollbackFailure: Schema.optional( @@ -3244,6 +3244,7 @@ export const OrchestrationV2Command = Schema.Union([ threadId: ThreadId, projectId: ProjectId, title: TrimmedNonEmptyString, + titleRenamed: Schema.optional(Schema.Boolean), modelSelection: ModelSelection, runtimeMode: RuntimeMode, interactionMode: ProviderInteractionMode, From 7b21adbe7cd633813eeb8a9e3ec4961ec31f98a3 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 14:35:39 -0800 Subject: [PATCH 076/324] fix(server): a merge no longer settles an unlinked thread on another thread's PR branch (#40564) --- .../ProjectionSettlement.test.ts | 8 +- .../src/orchestration-v2/ProjectionStore.ts | 5 +- .../ThreadSettlementService.test.ts | 107 ++++++++++++++++++ .../ThreadSettlementService.ts | 50 +++++++- 4 files changed, 165 insertions(+), 5 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts b/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts index 86a4c6c77375d..cb2fb0e87ada4 100644 --- a/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts @@ -433,7 +433,7 @@ it.effect("sql: lists only active threads with pull request links, oldest first" const store = yield* ProjectionStore.ProjectionStoreV2; yield* createThread("no-links"); yield* createThread("empty-links", { pullRequests: [] }); - yield* createThread("archived-link", { + const archived = yield* createThread("archived-link", { archivedAt: old, pullRequests: [pullRequestLink(1)], }); @@ -459,6 +459,12 @@ it.effect("sql: lists only active threads with pull request links, oldest first" (yield* store.getThreadsWithPullRequests(open)).map((thread) => thread.id), [open], ); + assert.deepEqual( + (yield* store.getThreadsWithPullRequests(undefined, { includeArchived: true })).map( + (thread) => thread.id, + ), + [settled, archived, open], + ); }).pipe(Effect.provide(layerSql)), ); diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index ba91ba94d2520..6c8308706b651 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -684,6 +684,7 @@ export interface ProjectionStoreV2Shape { ) => Effect.Effect, ProjectionStoreV2Error>; readonly getThreadsWithPullRequests: ( threadId?: ThreadId, + options?: { readonly includeArchived?: boolean }, ) => Effect.Effect, ProjectionStoreV2Error>; /** Titles of the given threads that exist, archived ones included. */ readonly getThreadLinkMetadata: ( @@ -8972,12 +8973,12 @@ export const layer: Layer.Layer = const getThreadsWithPullRequests: ProjectionStoreV2Shape["getThreadsWithPullRequests"] = Effect.fn("ProjectionStore.getThreadsWithPullRequests")( - function* (threadId) { + function* (threadId, options) { const rows = yield* sql` SELECT payload_json FROM orchestration_v2_projection_threads WHERE deleted_at IS NULL${threadId === undefined ? sql`` : sql` AND thread_id = ${threadId}`} - AND json_extract(payload_json, '$.archivedAt') IS NULL + ${options?.includeArchived === true ? sql`` : sql`AND json_extract(payload_json, '$.archivedAt') IS NULL`} AND json_array_length(payload_json, '$.pullRequests') > 0 ORDER BY updated_at ASC, thread_id ASC `; diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts index b20feef64eadd..0fee4a50ce34b 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts @@ -689,6 +689,16 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options: listShells: () => Ref.get(snapshots).pipe(Effect.map((snapshot) => snapshot.projects)), }), Layer.mock(ProjectionStore.ProjectionStoreV2)({ + getThreadsWithPullRequests: (_threadId, readOptions) => + Ref.get(snapshots).pipe( + Effect.map((snapshot) => + snapshot.threads + .filter( + (thread) => readOptions?.includeArchived === true || thread.archivedAt === null, + ) + .map((thread) => ({ ...thread, pullRequests: thread.pullRequests ?? [] })), + ), + ), ...options.projections, getSettlementCandidates: (threadId) => Ref.update(candidateReads, (reads) => [...reads, threadId]).pipe( @@ -2109,6 +2119,103 @@ describe("ThreadSettlementServiceV2 worker", () => { }).pipe(Effect.provide(fixture.layer)); }), ); + + it.effect("a merge does not settle a local thread on the branch of another thread's PR", () => + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse(NOW)); + const mergedLink = { + ...persistedLink("open", DateTime.makeUnsafe("2026-08-20T00:00:00.000Z")), + snapshot: { + ...persistedLink("open", DateTime.makeUnsafe("2026-08-20T00:00:00.000Z")).snapshot!, + state: "merged" as const, + mergedAt: NOW, + }, + }; + const owner = makeThread("pr-owner", { branch: "feature", pullRequests: [mergedLink] }); + const sibling = makeThread("local-sibling", { + branch: "feature", + createdAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"), + latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"), + }); + const cachedSibling = makeThread("cached-sibling", { + branch: "feature", + createdAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"), + latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"), + branchPullRequest: { + projectId: PROJECT_ID, + repository: "owner/repository", + number: 42, + url: "https://example.test/owner/repository/pull/42", + }, + }); + const legacyOwner = makeThread("legacy-owner", { + branch: "feature", + createdAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"), + latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"), + linkedPullRequest: cachedSibling.branchPullRequest, + }); + const fixture = yield* makeHarness({ + snapshot: makeSnapshot([owner, sibling, legacyOwner, cachedSibling]), + settings: { + ...DEFAULT_SERVER_SETTINGS, + sidebarAutoSettleOnMerge: true, + sidebarAutoSettleAfterDays: null, + }, + branchPullRequest: () => Effect.succeed(makeBranchPullRequest("merged")), + }); + + yield* Effect.gen(function* () { + const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2; + yield* startHarness(reactor, fixture.activation, fixture.snapshotReads); + yield* fixture.publishMerge; + yield* Queue.take(fixture.snapshotReads); + yield* reactor.drain; + + expect( + [ + ...new Set((yield* Ref.get(fixture.commands)).map((command) => command.threadId)), + ].toSorted(), + ).toEqual([legacyOwner.id, owner.id].toSorted()); + }).pipe(Effect.provide(fixture.layer)); + }), + ); + it.effect("an archived thread's pull request does not settle a local thread on its branch", () => + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse(NOW)); + const link = persistedLink("open", DateTime.makeUnsafe("2026-08-20T00:00:00.000Z")); + const owner = makeThread("archived-owner", { + branch: "feature", + archivedAt: DateTime.makeUnsafe("2026-08-29T00:00:00.000Z"), + pullRequests: [ + { ...link, snapshot: { ...link.snapshot!, state: "merged", mergedAt: NOW } }, + ], + }); + const sibling = makeThread("local-sibling", { + branch: "feature", + createdAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"), + latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"), + }); + const fixture = yield* makeHarness({ + snapshot: makeSnapshot([owner, sibling]), + settings: { + ...DEFAULT_SERVER_SETTINGS, + sidebarAutoSettleOnMerge: true, + sidebarAutoSettleAfterDays: null, + }, + branchPullRequest: () => Effect.succeed(makeBranchPullRequest("merged")), + }); + + yield* Effect.gen(function* () { + const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2; + yield* startHarness(reactor, fixture.activation, fixture.snapshotReads); + yield* fixture.publishMerge; + yield* Queue.take(fixture.snapshotReads); + yield* reactor.drain; + + expect(yield* Ref.get(fixture.commands)).toEqual([]); + }).pipe(Effect.provide(fixture.layer)); + }), + ); }); describe("ThreadSettlementServiceV2 terminals", () => { diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.ts index 6f05e0fd3c40c..38616d48846de 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.ts @@ -35,6 +35,10 @@ import * as TerminalManager from "../terminal/Manager.ts"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import * as ProjectStore from "./ProjectStore.ts"; import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts"; +import { + legacyThreadPullRequestKey, + threadPullRequestKeyOf, +} from "../sourceControl/threadPullRequests.ts"; import { makeNoPullRequestRechecks } from "./noPullRequestRechecks.ts"; import * as Orchestrator from "./Orchestrator.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; @@ -87,6 +91,20 @@ function pullRequestMatchesProject( ); } +function branchPullRequestKey(pullRequest: GitManager.GitBranchPullRequest): string | null { + const parsed = sourceControlDefinitions.parseChangeRequestUrl(pullRequest.url)?.link; + if (parsed !== undefined && parsed.number === pullRequest.number) { + return threadPullRequestKeyOf(parsed); + } + const separator = pullRequest.repositoryKey?.indexOf("/") ?? -1; + if (pullRequest.repositoryKey == null || separator <= 0) return null; + return threadPullRequestKeyOf({ + host: pullRequest.repositoryKey.slice(0, separator), + repository: pullRequest.repositoryKey.slice(separator + 1), + number: pullRequest.number, + }); +} + type SettlementPullRequestLink = NonNullable< ProjectionStore.ProjectionSettlementCandidate["pullRequests"] >[number]; @@ -481,7 +499,7 @@ export const make = Effect.gen(function* () { const reference = thread.linkedPullRequest ?? thread.branchPullRequest; if (reference != null) { return JSON.stringify([ - "linked", + thread.linkedPullRequest != null ? "linked" : "branch-reference", reference.projectId, reference.repository, reference.number, @@ -496,6 +514,22 @@ export const make = Effect.gen(function* () { ); }; const groups = Map.groupBy(lookupCandidates, lookupKey); + // A thread with no link of its own does not settle from a pull request another thread links, + // archived threads included. + const explicitlyLinked = new Set( + groups.size === 0 + ? [] + : (yield* projections.getThreadsWithPullRequests(undefined, { + includeArchived: true, + })).flatMap((thread) => + visibleThreadPullRequests(thread.pullRequests ?? []).map(threadPullRequestKeyOf), + ), + ); + const ownedByAnotherThread = (pullRequest: GitManager.GitBranchPullRequest | null) => { + if (pullRequest === null || pullRequest.state === "open") return false; + const key = branchPullRequestKey(pullRequest); + return key !== null && explicitlyLinked.has(key); + }; // wouldSettle and pullRequestFor run per lookup group; the git and pull request reads they make carry the spans. const wouldSettle = Effect.fnUntraced(function* ( @@ -524,6 +558,13 @@ export const make = Effect.gen(function* () { ) { const thread = group[0]!; const reference = thread.linkedPullRequest ?? thread.branchPullRequest; + if ( + thread.linkedPullRequest == null && + reference != null && + explicitlyLinked.has(threadPullRequestKeyOf(legacyThreadPullRequestKey(reference))) + ) { + return undefined; + } if (reference != null) { // Only matching PR links settle from this merge event; unrelated links require fresh lookup. const matchesMerge = @@ -601,9 +642,14 @@ export const make = Effect.gen(function* () { { refresh, confirmTerminal: false }, ); noPullRequestRechecks.record(key, nowMs, remembered !== null); + if (ownedByAnotherThread(remembered)) return undefined; if (refresh || remembered === null || remembered.state === "open") return remembered; if (!(yield* wouldSettle(group, remembered))) return undefined; - return yield* git.branchPullRequest({ cwd, branch: thread.branch }, { freshGitState: true }); + const fresh = yield* git.branchPullRequest( + { cwd, branch: thread.branch }, + { freshGitState: true }, + ); + return ownedByAnotherThread(fresh) ? undefined : fresh; }); // A merge, a shell close and a thread's own events read at once; only scheduled sweeps wait. From d3242f8ed1c2f40116d0bf14d5c7e5c0b9e1b8cd Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:41:55 +0100 Subject: [PATCH 077/324] fix(mobile): reuse gallery resources for workspace image taps (#40576) Co-authored-by: Julius Marminge --- .../src/features/threads/ThreadFeed.tsx | 23 ++-- .../threads/ThreadMarkdownImage.test.tsx | 58 +++++++++- .../features/threads/ThreadMarkdownImage.tsx | 1 + apps/mobile/src/lib/filePreview.test.ts | 101 +++++++++++++++--- 4 files changed, 153 insertions(+), 30 deletions(-) diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index 8a2a7e83a6698..53b773dc7f9c4 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -106,10 +106,7 @@ import { settlePromise, squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; -import { - classifyMarkdownImageSource, - markdownImageSourceFragment, -} from "@t3tools/client-runtime/markdown-images"; +import { classifyMarkdownImageSource } from "@t3tools/client-runtime/markdown-images"; import { contextCompactionTokenCounts, resolveViewedImageAsset, @@ -3743,20 +3740,20 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { /> ); } - if (imageSource._tag === "Blocked") { + if ( + media?.kind !== "image" || + !("resource" in media.source) || + media.source.resource._tag !== "media-file" + ) { return ; } return ( ); diff --git a/apps/mobile/src/features/threads/ThreadMarkdownImage.test.tsx b/apps/mobile/src/features/threads/ThreadMarkdownImage.test.tsx index 82f5cc62a7b68..2f2bffa336402 100644 --- a/apps/mobile/src/features/threads/ThreadMarkdownImage.test.tsx +++ b/apps/mobile/src/features/threads/ThreadMarkdownImage.test.tsx @@ -82,9 +82,6 @@ vi.mock("expo/fetch", () => ({ fetch: vi.fn() })); vi.mock("react-native-svg", () => ({ parse: vi.fn(), SvgAst: () => null })); vi.mock("@t3tools/client-runtime/state/assets", () => ({ MISSING_FILE_ACCESS_MESSAGE: "" })); vi.mock("../../components/ui/AppActivityIndicator", () => ({ AppActivityIndicator: () => null })); -vi.mock("../../components/ui/FilePreviewGallery", () => ({ - useFilePreviewGallery: () => (source: unknown) => source, -})); vi.mock("../../components/ui/AppText", () => ({ AppText: ({ children }: { children?: ReactNode }) => {children}, })); @@ -96,11 +93,64 @@ vi.mock("../../state/mediaActions", () => ({ useMediaActions: () => ({ actions: vi.mock("../../state/assets", () => ({ useAssetUrlState: vi.fn() })); import { RegistryContext } from "@effect/atom-react"; +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { AtomRegistry } from "effect/reactivity"; import { fetch } from "expo/fetch"; import { parse } from "react-native-svg"; -import { MarkdownImageAvailableWidthContext, ThreadMarkdownImageView } from "./ThreadMarkdownImage"; +import { FilePreviewGallery } from "../../components/ui/FilePreviewGallery"; +import type { FilePreviewSource } from "../../components/ui/FilePreviewModal.types"; +import { useAssetUrlState } from "../../state/assets"; +import { + MarkdownImageAvailableWidthContext, + ThreadMarkdownImage, + ThreadMarkdownImageView, +} from "./ThreadMarkdownImage"; + +it("keeps the tapped workspace image fragment on its gallery page", async () => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + const root = createRoot(document.createElement("div")); + const environmentId = EnvironmentId.make("environment-1"); + const threadId = ThreadId.make("thread-1"); + const resource = { _tag: "media-file", threadId, path: "/repo/./red.png" } as const; + const red = { kind: "image", environmentId, resource, srcFragment: "#detail" } as const; + const blue = { + kind: "image", + environmentId, + resource: { ...resource, path: "/repo/./blue.png" }, + } as const; + const openPreview = vi.fn<(source: FilePreviewSource) => void>(); + vi.mocked(useAssetUrlState).mockReturnValueOnce({ + _tag: "Success", + url: "https://example.test/red.png", + expiresAt: 0, + }); + try { + await act(async () => + root.render( + + + , + ), + ); + await act(async () => harness.pressable.onPress?.({ nativeEvent: {} })); + expect(openPreview).toHaveBeenCalledWith( + expect.objectContaining({ + resource, + srcFragment: "#detail", + gallery: [expect.objectContaining(red), blue], + }), + ); + } finally { + await act(async () => root.unmount()); + } +}); it("keeps the frame size when the same image reports a different decoded width", async () => { (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; diff --git a/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx b/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx index 8a7540625cc08..8e18d8445c85a 100644 --- a/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx +++ b/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx @@ -342,6 +342,7 @@ export function ThreadMarkdownImage(props: { gallery: undefined, environmentId: props.environmentId, resource: props.resource, + ...(props.srcFragment === undefined ? {} : { srcFragment: props.srcFragment }), }), ); }} diff --git a/apps/mobile/src/lib/filePreview.test.ts b/apps/mobile/src/lib/filePreview.test.ts index cd0bd8ae9890c..7c463ac0c3438 100644 --- a/apps/mobile/src/lib/filePreview.test.ts +++ b/apps/mobile/src/lib/filePreview.test.ts @@ -23,6 +23,7 @@ import { acquireAudioSession, activateAudioSession, releaseAudioSession } from " import { ThreadFeed } from "../features/threads/ThreadFeed"; import type { ThreadFeedEntry } from "./threadActivity"; import type { MarkdownImageRenderer } from "../native/SelectableMarkdownText"; +import type { FilePreviewItem, FilePreviewSource } from "../components/ui/FilePreviewModal.types"; const audio = vi.hoisted(() => ({ status: { @@ -203,12 +204,18 @@ vi.mock("../native/SelectableMarkdownText", () => ({ onLinkPress(href: string): void; renderImage?: MarkdownImageRenderer; }) => { - const embed = props.markdown.match(/!\[([^\]]*)\]\(([^)]+)\)/); + const embeds = [...props.markdown.matchAll(/!\[([^\]]*)\]\(([^)]+)\)/g)]; return createElement( "div", null, createElement("button", { onClick: () => props.onLinkPress("target.ts") }, props.markdown), - embed && props.renderImage?.({ href: embed[2]!, alt: embed[1]!, title: null }), + embeds.map(([, alt, href], index) => + createElement( + Fragment, + { key: index }, + props.renderImage?.({ href: href!, alt: alt!, title: null }), + ), + ), ); }, })); @@ -238,7 +245,9 @@ vi.mock("react-native-safe-area-context", () => ({ useSafeAreaInsets: () => ({ top: 0, bottom: 0 }), })); vi.mock("expo-haptics", () => ({ selectionAsync: async () => {} })); -vi.mock("expo-image", () => ({})); +vi.mock("expo-image", () => ({ Image: () => null })); +vi.mock("expo/fetch", () => ({})); +vi.mock("react-native-svg", () => ({})); vi.mock("uniwind", () => ({})); vi.mock("../components/ui/Dialog", () => ({})); vi.mock("../components/ui/Sheet", () => ({ @@ -254,13 +263,19 @@ vi.mock("../components/ui/NativePresentation", () => ({ vi.mock("../components/ui/Menu", () => ({ Menu: ({ children }: { children?: ReactNode }) => children, })); -vi.mock("../components/ui/FilePreviewGallery", () => ({ - FilePreviewGallery: ({ children }: { children?: ReactNode }) => children, - useFilePreviewGallery: () => (source: unknown) => source, -})); +function previewPath(item: FilePreviewItem) { + return "resource" in item && "path" in item.resource ? item.resource.path : null; +} + vi.mock("../components/ui/FilePreviewModal", () => ({ - FilePreviewModal: (props: { source: { name: string } | null }) => - props.source ? createElement("div", { "data-file-preview": props.source.name }) : null, + FilePreviewModal: ({ source }: { source: FilePreviewSource | null }) => + source + ? createElement("div", { + "data-file-preview": source.name, + "data-selected-path": previewPath(source), + "data-gallery": JSON.stringify(source.gallery?.map(previewPath)), + }) + : null, })); vi.mock("../components/ui/VideoPreviewModal", () => ({ VideoPreviewModal: () => null })); vi.mock("../components/ComposerContextSheet", () => ({})); @@ -313,10 +328,6 @@ vi.mock("../features/layout/AdaptiveWorkspaceLayout", () => ({ })); vi.mock("../features/threads/thread-workflow-opening", () => ({ useWorkflowOpening: () => null })); vi.mock("../features/threads/useFileChipShare", () => ({ useFileChipShare: () => vi.fn() })); -vi.mock("../features/threads/ThreadMarkdownImage", async () => { - const { createContext } = await import("react"); - return { MarkdownImageAvailableWidthContext: createContext(390) }; -}); vi.mock("../features/threads/ZoomableImagePressable", async () => { const { Pressable } = await import("react-native"); return { ZoomableImagePressable: Pressable }; @@ -1408,6 +1419,70 @@ describe("inline file previews", () => { }); describe("ThreadFeed previews", () => { + it("opens a tapped workspace image on its own gallery page, in message order", async () => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + const threadId = ThreadId.make("thread-1"); + const messageId = MessageId.make("message-1"); + const timestamp = "2026-10-20T00:00:00.000Z"; + const container = document.createElement("div"); + const root = createRoot(container); + try { + await act(async () => + root.render( + createElement(ThreadFeed, { + environmentId: EnvironmentId.make("environment-1"), + threadId, + detailRef: null, + threadTitle: "preview", + workspaceRoot: "/repo", + feed: [ + { + type: "message", + id: messageId, + createdAt: timestamp, + message: { + id: messageId, + role: "assistant", + text: "![Red](./red.png)\n\n![Blue](./blue.png)", + attachments: [], + createdAt: timestamp, + updatedAt: timestamp, + runId: null, + streaming: false, + visibility: "local", + sourceThreadId: threadId, + }, + }, + ], + queuedMessages: [], + dispatchingMessageId: null, + onEditPendingMessage: null, + contentPresentation: { kind: "ready" }, + latestRun: null, + activeWorkStartedAt: null, + listRef: { current: null }, + freeze: { value: false } as Parameters[0]["freeze"], + contentInsetEndAdjustment: { value: 0 } as Parameters< + typeof ThreadFeed + >[0]["contentInsetEndAdjustment"], + anchorMessageId: null, + keyboardOffset: 0, + }), + ), + ); + await act(async () => + container.querySelector(`[aria-label="Red"]`)!.click(), + ); + const preview = container.querySelector("[data-file-preview]"); + expect(preview?.getAttribute("data-selected-path")).toBe("/repo/./red.png"); + expect(preview?.getAttribute("data-gallery")).toBe( + JSON.stringify(["/repo/./red.png", "/repo/./blue.png"]), + ); + } finally { + await act(async () => root.unmount()); + } + }); + it("does not commit an open preview over a different thread", async () => { (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; const environmentId = EnvironmentId.make("environment-1"); From 6247463bd3aa950cd309a6dfa2799d927e1c314c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 14:42:37 -0800 Subject: [PATCH 078/324] perf(server): turn-end git status reads the branch remote and remote URL once (#40533) --- apps/server/src/git/GitManager.test.ts | 54 ++++++++++++++++++ apps/server/src/git/GitManager.ts | 79 ++++++++++++++++++++++++-- 2 files changed, 127 insertions(+), 6 deletions(-) diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index 064427a3727f5..94247273e1ca0 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -1100,6 +1100,60 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { }), ); + it.effect("a turn-end status refresh reads the branch remote and remote URL once", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + yield* runGit(repoDir, ["checkout", "-b", "feature/turn-end"]); + yield* runGit(repoDir, ["push", "-u", "origin", "feature/turn-end"]); + const gitCommands: string[] = []; + const { manager } = yield* makeManager({ gitCommands }); + const count = (cmd: string) => gitCommands.filter((args) => args === cmd).length; + + // Turn end: local status, then the PR lookup for a branch that has no PR yet. + yield* manager.invalidateLocalStatus(repoDir); + yield* manager.localStatus({ cwd: repoDir }); + yield* manager.invalidateRemoteStatus(repoDir); + const remote = yield* manager.remoteStatus( + { cwd: repoDir }, + { refreshUpstream: false, refreshMissingPullRequest: true }, + ); + + expect(remote?.pr ?? null).toBeNull(); + expect(count("config --get branch.feature/turn-end.remote")).toBe(1); + expect(count("config --get-all remote.origin.url")).toBe(1); + + // The thread's PR backfill can reach the lookup before the status refresh does. + const backfillCommands: string[] = []; + const backfill = yield* makeManager({ gitCommands: backfillCommands }); + yield* backfill.manager.localStatus({ cwd: repoDir }); + yield* backfill.manager.branchPullRequest( + { cwd: repoDir, branch: "feature/turn-end" }, + { confirmTerminal: false }, + ); + yield* backfill.manager.remoteStatus( + { cwd: repoDir }, + { refreshUpstream: false, refreshMissingPullRequest: true }, + ); + expect( + backfillCommands.filter((args) => args === "config --get branch.feature/turn-end.remote") + .length, + ).toBe(1); + + // A fresh identity check reads git itself, not what local status just read. + yield* manager.invalidateLocalStatus(repoDir); + yield* manager.localStatus({ cwd: repoDir }); + gitCommands.length = 0; + yield* manager.branchPullRequest( + { cwd: repoDir, branch: "feature/turn-end" }, + { freshGitState: true }, + ); + expect(count("config --get-all remote.origin.url")).toBe(1); + }), + ); + it.effect("a git read in flight during a T3 git action does not outlive it", () => Effect.gen(function* () { const repoDir = yield* makeTempDir("t3code-git-manager-"); diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index 543b5de5505f5..db62af1f79b69 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -220,6 +220,8 @@ const PR_LOOKUP_FAILURE_BASE_TTL = Duration.seconds(20); const PR_LOOKUP_FAILURE_MAX_TTL = Duration.minutes(15); const PR_LOOKUP_CACHE_CAPACITY = 2_048; const PR_LOOKUP_GIT_STATE_TTL = Duration.minutes(5); +// Turn end looks up the PR ~0.5 s after local status; older reads are read again. +const LOCAL_STATUS_GIT_READS_HANDOFF_TTL = Duration.seconds(5); const SETTLED_PR_LOOKUP_RECHECK_INTERVAL = Duration.minutes(15); // Shared by every background caller (backfill, settlement, cleanup), so startup discovery // cannot fill the git and forge process slots that foreground work also needs. @@ -1289,7 +1291,7 @@ export const make = Effect.gen(function* () { Effect.catchIf(isNotGitRepositoryError, () => Effect.succeed(nonRepositoryStatusDetails)), ); const hostingProvider = details.hasOriginRemote - ? yield* resolveHostingProvider(cwd, details.branch) + ? yield* resolveHostingProviderForLocalStatus(cwd, details.branch) : null; return { @@ -1333,7 +1335,30 @@ export const make = Effect.gen(function* () { cwd: string, ): shared is SharedPrLookupGitReads => shared !== null && shared.open && shared.cwd === cwd && prLookupEpoch(cwd) === shared.epoch; - const withPrLookupGitReads = (effect: Effect.Effect, cwd: string) => + // Branch remote and remote URLs that local status just read, reused by the PR lookups that + // follow it (turn end runs the status lookup and the thread's PR backfill) instead of reading again. + const localStatusGitReads = new Map< + string, + Pick + >(); + const recentLocalStatusGitReads = (cwd: string) => + Clock.currentTimeMillis.pipe( + Effect.map((now) => { + const handoff = localStatusGitReads.get(cwd); + if (handoff === undefined || handoff.epoch !== prLookupEpoch(cwd)) return undefined; + const isFresh = (entry: RememberedPrLookupValue) => + now - entry.readAtMs < Duration.toMillis(LOCAL_STATUS_GIT_READS_HANDOFF_TTL); + return { + configValues: new Map([...handoff.configValues].filter(([, entry]) => isFresh(entry))), + remoteUrls: new Map([...handoff.remoteUrls].filter(([, entry]) => isFresh(entry))), + }; + }), + ); + const openPrLookupGitReads = ( + effect: Effect.Effect, + cwd: string, + handoff: Pick | undefined, + ) => Effect.suspend(() => { const shared: SharedPrLookupGitReads = { open: true, @@ -1341,8 +1366,8 @@ export const make = Effect.gen(function* () { cwd, epoch: prLookupEpoch(cwd), remotes: undefined, - configValues: new Map(), - remoteUrls: new Map(), + configValues: handoff?.configValues ?? new Map(), + remoteUrls: handoff?.remoteUrls ?? new Map(), }; return effect.pipe( Effect.provideService(prLookupGitReads, shared), @@ -1357,9 +1382,15 @@ export const make = Effect.gen(function* () { ), ); }); + const withPrLookupGitReads = (effect: Effect.Effect, cwd: string) => + openPrLookupGitReads(effect, cwd, undefined); + const withRecentLocalStatusGitReads = (effect: Effect.Effect, cwd: string) => + Effect.flatMap(recentLocalStatusGitReads(cwd), (handoff) => + openPrLookupGitReads(effect, cwd, handoff), + ); const withActivePrLookupGitReads = (cwd: string, effect: Effect.Effect) => Effect.flatMap(prLookupGitReads, (shared) => - isActivePrLookupGitReads(shared, cwd) ? effect : withPrLookupGitReads(effect, cwd), + isActivePrLookupGitReads(shared, cwd) ? effect : withRecentLocalStatusGitReads(effect, cwd), ); const prLookupCacheKey = ( cwd: string, @@ -1781,6 +1812,32 @@ export const make = Effect.gen(function* () { .pipe(Effect.orElseSucceed(() => null)); return handle?.context?.provider ?? provider; }); + const resolveHostingProviderForLocalStatus = (cwd: string, branch: string | null) => + Effect.suspend(() => { + const reads: SharedPrLookupGitReads = { + open: true, + queriedProvider: false, + cwd, + epoch: prLookupEpoch(cwd), + remotes: undefined, + configValues: new Map(), + remoteUrls: new Map(), + }; + return resolveHostingProvider(cwd, branch).pipe( + Effect.provideService(prLookupGitReads, reads), + Effect.ensuring( + Effect.sync(() => { + reads.open = false; + localStatusGitReads.delete(cwd); + if (localStatusGitReads.size >= STATUS_RESULT_CACHE_CAPACITY) { + const oldestCwd = localStatusGitReads.keys().next().value; + if (oldestCwd !== undefined) localStatusGitReads.delete(oldestCwd); + } + localStatusGitReads.set(cwd, reads); + }), + ), + ); + }); const resolveRemoteRepositoryContext = Effect.fn("resolveRemoteRepositoryContext")(function* ( cwd: string, @@ -3093,6 +3150,16 @@ export const make = Effect.gen(function* () { ], { concurrency: "unbounded" }, ).pipe(Effect.map((parts) => parts.join("\u0000"))); + // A fresh identity check, which confirms terminal results, must read git itself. + const withBranchPullRequestGitReads = ( + effect: Effect.Effect, + cacheCwd: string, + _branch: string, + options: { readonly freshGitState: boolean }, + ) => + options.freshGitState + ? withPrLookupGitReads(effect, cacheCwd) + : withRecentLocalStatusGitReads(effect, cacheCwd); const lookupBranchPullRequest = Effect.fn("lookupBranchPullRequest")(function* ( cacheCwd: string, branch: string, @@ -3261,7 +3328,7 @@ export const make = Effect.gen(function* () { // Hosting CLIs may target upstream; the PR URL identifies its actual repository. repositoryKey: pullRequestRepositoryKey(latest.url), }; - }, withPrLookupGitReads); + }, withBranchPullRequestGitReads); const checkedOutPullRequestKey = (branch: string) => `branch.${branch}.t3-pull-request`; From 904e2671ca5351bd6f5bfcbeaee3f53c828e7333 Mon Sep 17 00:00:00 2001 From: Mike Olson Date: Sat, 21 Nov 2026 17:49:55 -0500 Subject: [PATCH 079/324] fix(web): Keep background announcements quiet for held or stopped runs (#40585) Co-authored-by: Julius Marminge --- .../components/BackgroundThreadAnnouncer.tsx | 3 +- .../backgroundThreadAnnouncement.test.ts | 70 +++++++++++++++++++ .../backgroundThreadAnnouncement.ts | 25 +++++++ 3 files changed, 97 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/BackgroundThreadAnnouncer.tsx b/apps/web/src/components/BackgroundThreadAnnouncer.tsx index 3176c8132eed9..649898cf2e5a5 100644 --- a/apps/web/src/components/BackgroundThreadAnnouncer.tsx +++ b/apps/web/src/components/BackgroundThreadAnnouncer.tsx @@ -14,6 +14,7 @@ import { type BackgroundThreadSnapshot, nextBackgroundThreadAnnouncement, resolveBackgroundThreadRequest, + resolveBackgroundThreadRunStatus, } from "./backgroundThreadAnnouncement"; const backgroundThreadLiveRegion = createLiveRegion(); @@ -51,7 +52,7 @@ export function startBackgroundThreadAnnouncements( title: thread.title, ...resolveBackgroundThreadRequest(thread), runId: thread.latestRun?.runId ?? null, - runStatus: thread.latestRun?.status ?? null, + runStatus: resolveBackgroundThreadRunStatus(thread), activeRunId: thread.runtime?.activeRunId ?? null, snoozed: effectiveSnoozed(thread, { now }), }); diff --git a/apps/web/src/components/backgroundThreadAnnouncement.test.ts b/apps/web/src/components/backgroundThreadAnnouncement.test.ts index b2b6195d8f288..51d3c693f9904 100644 --- a/apps/web/src/components/backgroundThreadAnnouncement.test.ts +++ b/apps/web/src/components/backgroundThreadAnnouncement.test.ts @@ -7,6 +7,7 @@ import { type BackgroundThreadSnapshot, nextBackgroundThreadAnnouncement, resolveBackgroundThreadRequest, + resolveBackgroundThreadRunStatus, } from "./backgroundThreadAnnouncement"; const firstRun = RunId.make("run-1"); @@ -187,3 +188,72 @@ describe("resolveBackgroundThreadRequest", () => { ).toEqual(["Needs approval: Fix login redirect"]); }); }); + +describe("resolveBackgroundThreadRunStatus", () => { + const threadStatus = (overrides?: { + readonly status?: "completed" | "failed" | "interrupted"; + readonly pendingBackgroundTasks?: ReadonlyArray<{ + readonly taskId: string; + readonly kind: "command" | "monitor" | "subagent" | "background_task"; + readonly awaited?: true; + }>; + readonly latestRunBackgroundWake?: boolean; + readonly latestRunStopRequested?: boolean; + }) => { + const pendingBackgroundTasks = overrides?.pendingBackgroundTasks ?? []; + return resolveBackgroundThreadRunStatus({ + latestRun: { status: overrides?.status ?? "completed" }, + pendingBackgroundTasks, + source: { + pendingBackgroundTasks, + latestRunBackgroundWake: overrides?.latestRunBackgroundWake ?? false, + latestRunStopRequested: overrides?.latestRunStopRequested ?? false, + }, + }); + }; + + it("suppresses Done while awaited background work or a monitor wake holds completion, or when stop was requested", () => { + const heldCases = [ + { latestRunStopRequested: true }, + { pendingBackgroundTasks: [{ taskId: "sub-1", kind: "subagent" as const }] }, + { + pendingBackgroundTasks: [ + { taskId: "cmd-1", kind: "command" as const, awaited: true as const }, + ], + }, + { + latestRunBackgroundWake: true, + pendingBackgroundTasks: [{ taskId: "mon-1", kind: "monitor" as const }], + }, + ]; + for (const input of heldCases) { + expect(threadStatus(input)).toBeNull(); + } + }); + + it("keeps Done for unawaited background work and keeps non-completed outcomes", () => { + expect( + threadStatus({ + pendingBackgroundTasks: [{ taskId: "cmd-1", kind: "command" }], + }), + ).toBe("completed"); + expect( + threadStatus({ + latestRunBackgroundWake: false, + pendingBackgroundTasks: [{ taskId: "mon-1", kind: "monitor" }], + }), + ).toBe("completed"); + expect( + threadStatus({ + status: "failed", + pendingBackgroundTasks: [{ taskId: "sub-1", kind: "subagent" }], + }), + ).toBe("failed"); + expect( + threadStatus({ + status: "interrupted", + latestRunStopRequested: true, + }), + ).toBe("interrupted"); + }); +}); diff --git a/apps/web/src/components/backgroundThreadAnnouncement.ts b/apps/web/src/components/backgroundThreadAnnouncement.ts index e1c52adb662ad..48a334543c447 100644 --- a/apps/web/src/components/backgroundThreadAnnouncement.ts +++ b/apps/web/src/components/backgroundThreadAnnouncement.ts @@ -1,4 +1,8 @@ import type { OrchestrationV2RunStatus, RunId } from "@t3tools/contracts"; +import { + backgroundWorkHoldsCompletion, + monitorHoldsWakeCompletion, +} from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; import { msg } from "gt-react"; @@ -40,6 +44,27 @@ export function resolveBackgroundThreadRequest( return { request: null, requestId: null }; } +/** Suppresses Done announcements for stopped runs, awaited background work, and monitor wakes. */ +export function resolveBackgroundThreadRunStatus(thread: { + readonly latestRun: { readonly status: OrchestrationV2RunStatus } | null; + readonly pendingBackgroundTasks: SidebarThreadSummary["pendingBackgroundTasks"]; + readonly source: Pick< + SidebarThreadSummary["source"], + "latestRunBackgroundWake" | "latestRunStopRequested" | "pendingBackgroundTasks" + >; +}): OrchestrationV2RunStatus | null { + const status = thread.latestRun?.status ?? null; + if ( + status === "completed" && + (thread.source.latestRunStopRequested === true || + backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks) || + monitorHoldsWakeCompletion(thread.source)) + ) { + return null; + } + return status; +} + interface BackgroundThreadMemoryEntry { readonly request: BackgroundThreadSnapshot["request"]; readonly requestId: string | null; From a480167e0cefb12846efc87d9cb839eb550db11d Mon Sep 17 00:00:00 2001 From: Adamulek123 Date: Sat, 21 Nov 2026 23:56:05 +0100 Subject: [PATCH 080/324] perf(issues): reuse repository bindings when classifying markdown links (#40592) Co-authored-by: Julius Marminge --- packages/client-runtime/src/issueLinks.test.ts | 11 +++++++++++ packages/client-runtime/src/issueLinks.ts | 16 ++++++++++++++-- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/packages/client-runtime/src/issueLinks.test.ts b/packages/client-runtime/src/issueLinks.test.ts index 66909fad1f054..661dfe1a94cae 100644 --- a/packages/client-runtime/src/issueLinks.test.ts +++ b/packages/client-runtime/src/issueLinks.test.ts @@ -49,6 +49,17 @@ describe("resolveIssueLinkTarget", () => { expect(target?.ref).toMatchObject({ projectId: "fork", scope: "me/web", key: "3" }); }); + it("uses the current repository identity after a project changes repositories", () => { + const url = "https://github.com/acme/api/issues/7"; + const original = project("p1", "acme/api"); + const replacement = project("p1", "acme/mobile"); + const lender = project("p3", "acme/web"); + expect(resolveIssueLinkTarget({ url, projects: [lender, original] })?.ref.projectId).toBe("p1"); + expect(resolveIssueLinkTarget({ url, projects: [lender, replacement] })?.ref.projectId).toBe( + "p3", + ); + }); + it("prefers the project bound to the link's own port over one on the bare hostname", () => { const enterprise = (id: string, host: string) => ({ diff --git a/packages/client-runtime/src/issueLinks.ts b/packages/client-runtime/src/issueLinks.ts index 0b442d18c92b5..db06b1b0a218f 100644 --- a/packages/client-runtime/src/issueLinks.ts +++ b/packages/client-runtime/src/issueLinks.ts @@ -3,6 +3,7 @@ import { issueTrackerBindingScopes, type IssueRef, type IssueTrackerConnectionList, + type RepositoryIdentity, } from "@t3tools/contracts"; import { LINEAR_HOST, @@ -15,11 +16,22 @@ import type { EnvironmentProject } from "./state/shell.ts"; type LinkProject = Pick; +const issueBindingsByRepository = new WeakMap< + RepositoryIdentity, + ReturnType +>(); + /** The hosts and scopes a project's git-host tracker is bound to, the way the server resolves them. */ function projectIssueBindings(project: LinkProject) { - return sourceControlClients - .issueBindings(project.repositoryIdentity) + const identity = project.repositoryIdentity; + if (identity == null) return []; + const cached = issueBindingsByRepository.get(identity); + if (cached !== undefined) return cached; + const bindings = sourceControlClients + .issueBindings(identity) .map((binding) => ({ ...binding, scope: binding.scope.toLowerCase() })); + issueBindingsByRepository.set(identity, bindings); + return bindings; } function linkAuthority(url: string): string | null { From b5709bb8650904f5be0e4db561cb547364febe20 Mon Sep 17 00:00:00 2001 From: Adamulek123 Date: Sat, 21 Nov 2026 23:59:08 +0100 Subject: [PATCH 081/324] perf(issues): read only the selected project tracker binding (#40587) Co-authored-by: Julius Marminge --- apps/server/src/issue/IssueService.test.ts | 6 ++- apps/server/src/issue/IssueService.ts | 2 +- .../src/issue/IssueTrackerConnections.ts | 2 +- .../src/mcp/toolkits/issues/handlers.test.ts | 9 ++-- .../src/persistence/IssueTrackerBindings.ts | 45 ++++++++++--------- .../103_IssueTrackerAdditionalScopes.test.ts | 8 +++- 6 files changed, 43 insertions(+), 29 deletions(-) diff --git a/apps/server/src/issue/IssueService.test.ts b/apps/server/src/issue/IssueService.test.ts index e8308b8480d02..6291f304e6efc 100644 --- a/apps/server/src/issue/IssueService.test.ts +++ b/apps/server/src/issue/IssueService.test.ts @@ -156,7 +156,9 @@ function makeService(input: { readonly projects: ReadonlyArray; readonly trackers: ReadonlyArray; readonly bindings?: Record; - readonly readBindings?: IssueTrackerBindings.IssueTrackerBindingsRepository["Service"]["list"]; + readonly readBindings?: ReturnType< + IssueTrackerBindings.IssueTrackerBindingsRepository["Service"]["list"] + >; }) { return IssueService.IssueService.pipe( Effect.provide( @@ -164,7 +166,7 @@ function makeService(input: { Layer.provide( Layer.mergeAll( Layer.mock(IssueTrackerBindings.IssueTrackerBindingsRepository)({ - list: + list: () => input.readBindings ?? Effect.succeed( new Map( diff --git a/apps/server/src/issue/IssueService.ts b/apps/server/src/issue/IssueService.ts index 27499b240d655..049de0d757a1c 100644 --- a/apps/server/src/issue/IssueService.ts +++ b/apps/server/src/issue/IssueService.ts @@ -249,7 +249,7 @@ const make = Effect.gen(function* () { ); if (shells.length === 0) return []; // One read per listing, not per project, and never cached so Settings changes apply. - const bound = yield* bindings.list.pipe( + const bound = yield* bindings.list(filter.projectId).pipe( // A failed read is not an unbound project: that would list the git host's issues alone. Effect.mapError( (cause) => diff --git a/apps/server/src/issue/IssueTrackerConnections.ts b/apps/server/src/issue/IssueTrackerConnections.ts index 390cc9701e858..704116fc65326 100644 --- a/apps/server/src/issue/IssueTrackerConnections.ts +++ b/apps/server/src/issue/IssueTrackerConnections.ts @@ -113,7 +113,7 @@ const make = Effect.gen(function* () { const list: IssueTrackerConnections["Service"]["list"] = Effect.all({ trackers: Effect.forEach(registry.standalone, current, { concurrency: 4 }), - bindings: bindings.list.pipe( + bindings: bindings.list().pipe( Effect.map((bound) => Object.fromEntries(bound)), // No single tracker is at fault; the first registered one carries the report. Effect.mapError(secretFailure(anyTracker, "The project bindings could not be read.")), diff --git a/apps/server/src/mcp/toolkits/issues/handlers.test.ts b/apps/server/src/mcp/toolkits/issues/handlers.test.ts index 143ba4a0c98a3..5736b685b829b 100644 --- a/apps/server/src/mcp/toolkits/issues/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/issues/handlers.test.ts @@ -260,7 +260,7 @@ describe("issue toolkit handlers", () => { projectLayer, Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({}), Layer.mock(IssueTrackerBindings.IssueTrackerBindingsRepository)({ - list: Effect.succeed(new Map([[PROJECT_ID, { tracker, scope: "ENG" }]])), + list: () => Effect.succeed(new Map([[PROJECT_ID, { tracker, scope: "ENG" }]])), }), Layer.succeed( IssueTrackerRegistry.IssueTrackerRegistry, @@ -314,9 +314,10 @@ describe("issue toolkit handlers", () => { projectLayer, Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({}), Layer.mock(IssueTrackerBindings.IssueTrackerBindingsRepository)({ - list: Effect.succeed( - new Map([[PROJECT_ID, { tracker, scope: "ENG", additionalScopes: ["OPS"] }]]), - ), + list: () => + Effect.succeed( + new Map([[PROJECT_ID, { tracker, scope: "ENG", additionalScopes: ["OPS"] }]]), + ), }), Layer.succeed( IssueTrackerRegistry.IssueTrackerRegistry, diff --git a/apps/server/src/persistence/IssueTrackerBindings.ts b/apps/server/src/persistence/IssueTrackerBindings.ts index fbb0a398900d2..2f665b487e03f 100644 --- a/apps/server/src/persistence/IssueTrackerBindings.ts +++ b/apps/server/src/persistence/IssueTrackerBindings.ts @@ -26,7 +26,9 @@ const BindingRow = Schema.Struct({ export class IssueTrackerBindingsRepository extends Context.Service< IssueTrackerBindingsRepository, { - readonly list: Effect.Effect< + readonly list: ( + projectId?: ProjectId, + ) => Effect.Effect< ReadonlyMap, IssueTrackerBindingsRepositoryError >; @@ -56,32 +58,35 @@ function toSqlOrDecodeError(sqlOperation: string, decodeOperation: string) { const make = Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; + const select = sql` + SELECT project_id AS "projectId", tracker AS "tracker", scope AS "scope", + additional_scopes AS "additionalScopes" + FROM issue_tracker_bindings + `; const listRows = SqlSchema.findAll({ - Request: Schema.Void, + Request: Schema.UndefinedOr(ProjectId), Result: BindingRow, - execute: () => - sql` - SELECT project_id AS "projectId", tracker AS "tracker", scope AS "scope", - additional_scopes AS "additionalScopes" - FROM issue_tracker_bindings - `, + execute: (projectId) => + projectId === undefined ? select : sql`${select} WHERE project_id = ${projectId}`, }); return IssueTrackerBindingsRepository.of({ - list: listRows(undefined).pipe( - Effect.map( - (rows) => - new Map( - rows.map( - ({ projectId, additionalScopes, ...binding }) => - [ - projectId, - additionalScopes.length === 0 ? binding : { ...binding, additionalScopes }, - ] as const, + list: Effect.fn("IssueTrackerBindingsRepository.list")((projectId?: ProjectId) => + listRows(projectId).pipe( + Effect.map( + (rows) => + new Map( + rows.map( + ({ projectId, additionalScopes, ...binding }) => + [ + projectId, + additionalScopes.length === 0 ? binding : { ...binding, additionalScopes }, + ] as const, + ), ), - ), + ), + Effect.mapError(toSqlOrDecodeError("listIssueTrackerBindings", "IssueTrackerBinding")), ), - Effect.mapError(toSqlOrDecodeError("listIssueTrackerBindings", "IssueTrackerBinding")), ), set: Effect.fn("IssueTrackerBindingsRepository.set")( function* (input) { diff --git a/apps/server/src/persistence/Migrations/103_IssueTrackerAdditionalScopes.test.ts b/apps/server/src/persistence/Migrations/103_IssueTrackerAdditionalScopes.test.ts index 3ea190f41d2ed..9e61347812e74 100644 --- a/apps/server/src/persistence/Migrations/103_IssueTrackerAdditionalScopes.test.ts +++ b/apps/server/src/persistence/Migrations/103_IssueTrackerAdditionalScopes.test.ts @@ -21,13 +21,19 @@ it.layer(NodeSqliteClient.layer({ filename: ":memory:" }))( ); const projectId = ProjectId.make("web"); const binding = { tracker: IssueTrackerKind.make("linear"), scope: "ENG" }; - const read = () => bindings.list.pipe(Effect.map((all) => all.get(projectId))); + const read = () => bindings.list(projectId).pipe(Effect.map((rows) => rows.get(projectId))); assert.deepStrictEqual(yield* read(), binding); const multi = { ...binding, additionalScopes: ["OPS", "DOCS"] }; yield* bindings.set({ projectId, binding: multi, updatedAt: "2026-11-21" }); assert.deepStrictEqual(yield* read(), multi); yield* bindings.set({ projectId, binding, updatedAt: "2026-11-21" }); assert.deepStrictEqual(yield* read(), binding); + yield* sql` + INSERT INTO issue_tracker_bindings (project_id, tracker, scope, updated_at, additional_scopes) + VALUES ('other', 'linear', 'OPS', '2026-11-21', 'invalid') + `; + assert.deepStrictEqual(yield* read(), binding); + assert.strictEqual((yield* Effect.result(bindings.list()))._tag, "Failure"); }), ); }, From 76bb5ec81b0f14e7db1ae29200b38d275f0cdf77 Mon Sep 17 00:00:00 2001 From: Adamulek123 Date: Sun, 22 Nov 2026 00:11:00 +0100 Subject: [PATCH 082/324] perf(issues): read only link metadata when linking GitHub issues (#40595) Co-authored-by: Julius Marminge --- apps/server/src/issue/IssueService.ts | 19 ++++++++ .../src/mcp/toolkits/issues/handlers.test.ts | 1 + .../src/mcp/toolkits/issues/handlers.ts | 10 ++-- .../src/server/IssueTracker.ts | 6 +++ .../src/server/GitHubIssueTracker.test.ts | 25 ++++++++++ .../src/server/GitHubIssueTracker.ts | 10 ++++ .../src/server/issues.graphql | 10 ++++ .../src/server/issues.graphql.ts | 48 ++++++++++++++++++- 8 files changed, 123 insertions(+), 6 deletions(-) diff --git a/apps/server/src/issue/IssueService.ts b/apps/server/src/issue/IssueService.ts index 049de0d757a1c..9b9b050ab6ad0 100644 --- a/apps/server/src/issue/IssueService.ts +++ b/apps/server/src/issue/IssueService.ts @@ -42,6 +42,7 @@ import { type IssueTrackerApi, type StandaloneIssueTrackerApi, type TrackerIssueDetail, + type TrackerIssueLink, } from "@t3tools/source-control-core/server/IssueTracker"; import { parseUrl } from "@t3tools/shared/url"; @@ -148,6 +149,7 @@ export class IssueService extends Context.Service< { readonly list: (input: IssueListInput) => Effect.Effect; readonly detail: (input: IssueRef) => Effect.Effect; + readonly linkMetadata: (input: IssueRef) => Effect.Effect; readonly comments: ( input: IssueCommentsPageInput, ) => Effect.Effect; @@ -524,6 +526,22 @@ const make = Effect.gen(function* () { ), ); + const linkMetadata: IssueService["Service"]["linkMetadata"] = (input) => + requireProject(input).pipe( + Effect.flatMap((project) => { + const read = project.api.getIssueLink ?? project.api.getIssue; + return read({ + cwd: project.project.workspaceRoot, + host: project.host, + scope: project.scope, + key: input.key, + }).pipe( + Effect.map(({ title, url, displayKey }) => ({ title, url, displayKey })), + Effect.mapError(toIssueError("detail")), + ); + }), + ); + const comments: IssueService["Service"]["comments"] = (input) => requireProject(input).pipe( Effect.flatMap((project) => @@ -796,6 +814,7 @@ const make = Effect.gen(function* () { return IssueService.of({ list, detail: traced("detail", detail), + linkMetadata: traced("linkMetadata", linkMetadata), comments: traced("comments", comments), templates: traced("templates", templates), candidates: interactive(traced("candidates", candidates)), diff --git a/apps/server/src/mcp/toolkits/issues/handlers.test.ts b/apps/server/src/mcp/toolkits/issues/handlers.test.ts index 5736b685b829b..9867324f7fc23 100644 --- a/apps/server/src/mcp/toolkits/issues/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/issues/handlers.test.ts @@ -158,6 +158,7 @@ const makeHarness = Effect.fn("makeIssuesToolkitHarness")(function* ( issueLayer ?? Layer.mock(IssueService.IssueService)({ detail: () => Effect.succeed(detail), + linkMetadata: () => Effect.succeed(detail), projectScope: (projectId) => Effect.succeed({ projectId, diff --git a/apps/server/src/mcp/toolkits/issues/handlers.ts b/apps/server/src/mcp/toolkits/issues/handlers.ts index b45b3d3dbd875..c09dbc356d61f 100644 --- a/apps/server/src/mcp/toolkits/issues/handlers.ts +++ b/apps/server/src/mcp/toolkits/issues/handlers.ts @@ -269,20 +269,20 @@ const make = Effect.gen(function* () { link_issue: writesThread((input) => Effect.gen(function* () { const thread = yield* requireThread(input.threadId); - const target = yield* resolveTarget({ + const target: ResolvedTarget = yield* resolveTarget({ ...input, projectId: input.projectId ?? thread.projectId, }); // Reading the issue proves it exists and names it for the thread's row. - const detail = yield* readIssue(target); - const url = target.url ?? detail.url; + const issue = target.issue ?? (yield* issues.linkMetadata(refOf(target))); + const url = target.url ?? issue.url; const { alreadyLinked } = yield* threadIssues .link({ threadId: thread.id, ref: refOf(target), url, - displayKey: detail.displayKey, - title: detail.title, + displayKey: issue.displayKey, + title: issue.title, source: "agent", }) .pipe(Effect.catchCause(linkFailure)); diff --git a/packages/source-control-core/src/server/IssueTracker.ts b/packages/source-control-core/src/server/IssueTracker.ts index b5894ed806363..eecbde1ed2267 100644 --- a/packages/source-control-core/src/server/IssueTracker.ts +++ b/packages/source-control-core/src/server/IssueTracker.ts @@ -73,6 +73,7 @@ export interface IssueTarget extends IssueScopeTarget { /** An issue as the tracker sees it, before the service attaches project context. */ export type TrackerIssueSummary = Omit; +export type TrackerIssueLink = Pick; export interface TrackerIssuePage { readonly items: ReadonlyArray; @@ -134,6 +135,11 @@ export interface IssueTrackerApi { /** The issue with its first page of conversation, in one read where the tracker allows. */ readonly getIssue: (input: IssueTarget) => Effect.Effect; + /** Confirms an issue exists and names it for a thread link. */ + readonly getIssueLink?: ( + input: IssueTarget, + ) => Effect.Effect; + /** One page of older comments past a cursor `getIssue` or a previous page handed over. */ readonly getComments: ( input: IssueTarget & { readonly cursor: string }, diff --git a/packages/source-control-github/src/server/GitHubIssueTracker.test.ts b/packages/source-control-github/src/server/GitHubIssueTracker.test.ts index 3ddcd024f8b35..c04145758f7b1 100644 --- a/packages/source-control-github/src/server/GitHubIssueTracker.test.ts +++ b/packages/source-control-github/src/server/GitHubIssueTracker.test.ts @@ -226,6 +226,31 @@ const decodeBody = Schema.decodeUnknownSync( ); describe("GitHubIssueTracker", () => { + it.effect("reads only the fields needed to link a GitHub issue and rejects missing issues", () => + Effect.gen(function* () { + const requests: unknown[] = []; + const target = { cwd: "/w", host: "github.com", scope: "acme/web", key: "42" }; + const url = "https://github.com/acme/web/issues/42"; + const found = yield* tracker((input) => requests.push(input), { + issue: { number: 42, title: "Fixture issue", url }, + }); + expect(yield* found.getIssueLink(target)).toEqual({ + displayKey: "#42", + title: "Fixture issue", + url, + }); + + const missing = yield* tracker((input) => requests.push(input), { issue: null }); + expect(yield* Effect.flip(missing.getIssueLink(target))).toMatchObject({ + reason: "not-found", + }); + expect(requests).toEqual([ + { owner: "acme", name: "web", number: 42 }, + { owner: "acme", name: "web", number: 42 }, + ]); + }), + ); + it.effect("writes an issue lifecycle without mutating pull requests or foreign comments", () => Effect.gen(function* () { const writes: unknown[] = []; diff --git a/packages/source-control-github/src/server/GitHubIssueTracker.ts b/packages/source-control-github/src/server/GitHubIssueTracker.ts index bf1c20abae4e3..b2cb38ff4d413 100644 --- a/packages/source-control-github/src/server/GitHubIssueTracker.ts +++ b/packages/source-control-github/src/server/GitHubIssueTracker.ts @@ -337,6 +337,16 @@ export const make = Effect.gen(function* () { }; }), + getIssueLink: Effect.fn("GitHubIssueTracker.getIssueLink")(function* (input) { + const { owner, name, number } = yield* issue(input, "getIssue"); + const result = yield* client + .IssueLinkMetadata({ owner, name, number }) + .pipe(graphql(input.host, "getIssue")); + const found = result.repository?.issue; + if (found == null) return yield* notFound("getIssue"); + return { displayKey: `#${found.number}`, title: found.title, url: found.url }; + }), + getComments: (input) => issue(input, "getComments").pipe( Effect.flatMap(({ owner, name, number }) => diff --git a/packages/source-control-github/src/server/issues.graphql b/packages/source-control-github/src/server/issues.graphql index 42dc67a98a123..18c8cee3536a2 100644 --- a/packages/source-control-github/src/server/issues.graphql +++ b/packages/source-control-github/src/server/issues.graphql @@ -270,6 +270,16 @@ query IssueComments($owner: String!, $name: String!, $number: Int!, $cursor: Str } } +query IssueLinkMetadata($owner: String!, $name: String!, $number: Int!) { + repository(owner: $owner, name: $name) { + issue(number: $number) { + number + title + url + } + } +} + query IssueNodeId($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) { issue(number: $number) { diff --git a/packages/source-control-github/src/server/issues.graphql.ts b/packages/source-control-github/src/server/issues.graphql.ts index d99defc174a5c..9d059396d26a0 100644 --- a/packages/source-control-github/src/server/issues.graphql.ts +++ b/packages/source-control-github/src/server/issues.graphql.ts @@ -666,6 +666,52 @@ export declare namespace IssueComments { export type Result = typeof IssueComments.result.Type } +/** An Issue is a place to discuss ideas, enhancements, tasks, and bugs for a project. */ +export const IssueLinkMetadataRepositoryIssueIssue = Schema.Struct({ + /** Identifies the issue number. */ + number: Shared.Int, + /** Identifies the issue title. */ + title: Schema.String, + /** The HTTP URL for this issue */ + url: Shared.URI +}) +export interface IssueLinkMetadataRepositoryIssueIssue extends Schema.Struct.Type {} + +/** A repository contains the content for a project. */ +export const IssueLinkMetadataRepositoryRepository = Schema.Struct({ + /** Returns a single issue from the current repository by number. */ + issue: Schema.NullOr(IssueLinkMetadataRepositoryIssueIssue) +}) +export interface IssueLinkMetadataRepositoryRepository extends Schema.Struct.Type {} + +/** `query IssueLinkMetadata` */ +export const IssueLinkMetadata = GraphQL.query("IssueLinkMetadata", { + document: { + variables: [ + { name: "owner", body: "String!" }, + { name: "name", body: "String!" }, + { name: "number", body: "Int!" } + ], + selections: [ + { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){issue(number:$", "number", "){number title url}}"] } + ], + fragments: [] + }, + variables: { + owner: Schema.String, + name: Schema.String, + number: Shared.Int + }, + result: Schema.Struct({ + /** Lookup a given repository by the owner and repository name. */ + repository: Schema.NullOr(IssueLinkMetadataRepositoryRepository) + }) +}) +export declare namespace IssueLinkMetadata { + export type Variables = typeof IssueLinkMetadata.variables.Type + export type Result = typeof IssueLinkMetadata.result.Type +} + /** An Issue is a place to discuss ideas, enhancements, tasks, and bugs for a project. */ export const IssueNodeIdRepositoryIssueIssue = Schema.Struct({ /** The Node ID of the Issue object */ @@ -1038,4 +1084,4 @@ export declare namespace IssueCollections { } /** Every operation in issues.graphql. */ -export const IssuesGraphQLGroup = GraphQLGroup.make(IssueSearch, IssueDetail, IssueComments, IssueNodeId, IssueCommentScope, IssueCandidates, IssueTemplates, IssueViewer, IssueCollections) +export const IssuesGraphQLGroup = GraphQLGroup.make(IssueSearch, IssueDetail, IssueComments, IssueLinkMetadata, IssueNodeId, IssueCommentScope, IssueCandidates, IssueTemplates, IssueViewer, IssueCollections) From 10586f9e31834e21212cfbd1d743f2cb704375d8 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 15:13:34 -0800 Subject: [PATCH 083/324] feat: read feature flags from one T3CODE_FEATURE_FLAGS service (#40594) Co-authored-by: Claude Opus 5.5 --- apps/desktop/src/app/DesktopApp.ts | 27 ++++++ .../backend/DesktopBackendConfiguration.ts | 3 +- .../src/shell/DesktopShellEnvironment.ts | 8 +- apps/mobile/app.config.ts | 3 - .../features/settings/CloudVoiceSection.tsx | 4 +- apps/server/src/os-jank.test.ts | 82 ++++++++++--------- apps/server/src/os-jank.ts | 6 +- apps/server/src/server.ts | 2 + .../SourceControlProviderRegistry.ts | 15 ++-- .../src/sourceControl/builtInDrivers.ts | 19 ++++- .../sourceControl/sourceControlDefinitions.ts | 15 ++-- apps/server/src/ws.test.ts | 2 + apps/server/src/ws.ts | 6 ++ .../src/components/chat/SecretRequestCard.tsx | 4 +- .../CloudVoiceConfiguration.browser.test.tsx | 5 +- .../settings/CloudVoiceConfiguration.tsx | 5 +- .../components/settings/SecretSourceInput.tsx | 6 +- ...ngsSidebarNav.composition.browser.test.tsx | 11 +-- .../settings/SettingsSidebarNav.tsx | 10 ++- .../settings/settingsSearch.test.ts | 31 +++++-- .../src/components/settings/settingsSearch.ts | 39 +++++---- .../useAvailableSettingsSearchItems.ts | 11 +++ apps/web/src/env.ts | 4 - .../web/src/routes/_chat.settings.secrets.tsx | 20 +++-- apps/web/src/vite-env.d.ts | 1 - apps/web/vite.config.ts | 2 - docs/user/source-control.md | 6 +- evals/thread-titles/run.ts | 2 + .../src/sourceControlClients.test.ts | 7 -- packages/client-runtime/src/state/server.ts | 9 ++ packages/contracts/src/resourceTelemetry.ts | 2 +- packages/contracts/src/server.ts | 8 ++ packages/shared/package.json | 4 + packages/shared/src/FeatureFlags.test.ts | 31 +++++++ packages/shared/src/FeatureFlags.ts | 61 ++++++++++++++ .../source-control-core/src/server/driver.ts | 4 +- .../src/registry.ts | 67 +++++++-------- .../scripts/measure-pr-preview.ts | 2 + .../src/server/GitHubAppSignIn.test.ts | 13 ++- .../src/server/GitHubAppSignIn.ts | 11 +-- .../src/server/GitHubRest.test.ts | 6 +- 41 files changed, 388 insertions(+), 186 deletions(-) create mode 100644 packages/shared/src/FeatureFlags.test.ts create mode 100644 packages/shared/src/FeatureFlags.ts diff --git a/apps/desktop/src/app/DesktopApp.ts b/apps/desktop/src/app/DesktopApp.ts index 0ccce648bba61..ba09871ee1c5a 100644 --- a/apps/desktop/src/app/DesktopApp.ts +++ b/apps/desktop/src/app/DesktopApp.ts @@ -4,6 +4,7 @@ import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; import * as NetService from "@t3tools/shared/Net"; import * as SecureRandom from "effect/crypto/SecureRandom"; @@ -173,6 +174,31 @@ const stopAllPoolInstances = Effect.fn("desktop.app.stopAllPoolInstances")( ); // Spawns the local backend as soon as the protocol, IPC, and legacy storage that every window needs exist. +/** + * The server reads T3CODE_FEATURE_FLAGS once at start, from the value cached at the last + * discovery. When the login shell now sets different flags, restart it so they apply. + */ +const restartOnFeatureFlagChange = Effect.fn("desktop.restartOnFeatureFlagChange")(function* ( + backend: DesktopBackendManager.DesktopBackendInstance, +) { + const state = yield* DesktopState.DesktopState; + const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment; + let startedWith = (yield* HostProcess.Environment).T3CODE_FEATURE_FLAGS; + yield* shellEnvironment.updates.pipe( + Stream.filter((snapshot) => snapshot.discovered), + Stream.runForEach( + Effect.fnUntraced(function* (snapshot) { + const flags = snapshot.environment.T3CODE_FEATURE_FLAGS ?? undefined; + if (flags === startedWith || (yield* Ref.get(state.quitting))) return; + startedWith = flags; + yield* logBootstrapInfo("restarting backend for changed T3CODE_FEATURE_FLAGS"); + yield* backend.stop(); + yield* backend.start; + }), + ), + ); +}); + const startLocalBackend = Effect.gen(function* () { const state = yield* DesktopState.DesktopState; const environment = yield* DesktopEnvironment.DesktopEnvironment; @@ -268,6 +294,7 @@ const startLocalBackend = Effect.gen(function* () { } yield* primaryBackend.start; yield* logBootstrapInfo("bootstrap backend start requested"); + yield* Effect.forkScoped(restartOnFeatureFlagChange(primaryBackend)); // The renderer asks for this token first; minting it at readiness saves a round trip. yield* Effect.forkScoped( (yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth).getBearerToken.pipe( diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.ts index 9c12690f31351..5474583be9976 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.ts @@ -89,8 +89,7 @@ const WSL_FORWARDED_ENV_NAMES = [ "OPENAI_API_KEY", "ANTHROPIC_API_KEY", "T3CODE_TELEMETRY_ENABLED", - "T3CODE_GITHUB_APP_CLIENT_ID", - "T3CODE_TANSTACK_SOURCE", + "T3CODE_FEATURE_FLAGS", // Otherwise the WSL server keeps exporting to endpoints from the bootstrap. "T3CODE_OTEL_SDK_DISABLED", "OTEL_SDK_DISABLED", diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.ts b/apps/desktop/src/shell/DesktopShellEnvironment.ts index f9ab0d6c3a054..620fd8f561fa8 100644 --- a/apps/desktop/src/shell/DesktopShellEnvironment.ts +++ b/apps/desktop/src/shell/DesktopShellEnvironment.ts @@ -123,8 +123,7 @@ const LOGIN_SHELL_ENV_NAMES = [ "SSL_CERT_DIR", "NODE_EXTRA_CA_CERTS", "T3CODE_TELEMETRY_ENABLED", - "T3CODE_GITHUB_APP_CLIENT_ID", - "T3CODE_TANSTACK_SOURCE", + "T3CODE_FEATURE_FLAGS", "T3CODE_RELEASE_BASE_URL", "__MISE_DIFF", "JAVA_HOME", @@ -555,8 +554,7 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix "JAVA_HOME", "PNPM_HOME", "T3CODE_TELEMETRY_ENABLED", - "T3CODE_GITHUB_APP_CLIENT_ID", - "T3CODE_TANSTACK_SOURCE", + "T3CODE_FEATURE_FLAGS", "T3CODE_RELEASE_BASE_URL", ] as const) { if (!config.env[name] && shellEnvironment[name]) { @@ -663,6 +661,8 @@ const CACHED_ENV_NAMES = [ "SSL_CERT_DIR", "NODE_EXTRA_CA_CERTS", "T3CODE_TELEMETRY_ENABLED", + // The server reads its flags once at start, before discovery can finish. + "T3CODE_FEATURE_FLAGS", ] as const; /** @public */ diff --git a/apps/mobile/app.config.ts b/apps/mobile/app.config.ts index 464f7ab9929b0..a868851d5c9da 100644 --- a/apps/mobile/app.config.ts +++ b/apps/mobile/app.config.ts @@ -471,9 +471,6 @@ const config: ExpoConfig = { ], extra: { appVariant: APP_VARIANT, - secretsFeatureEnabled: ["1", "true"].includes( - process.env.T3CODE_FEATURE_SECRETS?.trim().toLowerCase() ?? "", - ), iosPersonalTeamBuild: isIosPersonalTeamBuild, relay: { url: repoEnv.T3CODE_RELAY_URL ?? null, diff --git a/apps/mobile/src/features/settings/CloudVoiceSection.tsx b/apps/mobile/src/features/settings/CloudVoiceSection.tsx index dceb42d86e457..3e782d2457fa3 100644 --- a/apps/mobile/src/features/settings/CloudVoiceSection.tsx +++ b/apps/mobile/src/features/settings/CloudVoiceSection.tsx @@ -2,6 +2,7 @@ import { T, useGT, useMessages } from "gt-react-native"; import { useAtomRefresh, useAtomValue } from "@effect/atom-react"; import { cloudSpeechDisclosure } from "@t3tools/shared/speechCopy"; import { setCloudSpeechKey } from "@t3tools/client-runtime/voice-input"; +import { hasFeatureFlag } from "@t3tools/client-runtime/state/server"; import { configuredSecretSources, secretRequestReference, @@ -20,7 +21,6 @@ import { type VoiceTranscriptionDestination, } from "@t3tools/contracts"; import * as Schema from "effect/Schema"; -import Constants from "expo-constants"; import { AsyncResult } from "effect/reactivity"; import { type ReactNode, useState } from "react"; import { ScrollView, TextInput, View } from "react-native"; @@ -199,7 +199,7 @@ function CloudChoices({ environment, active, onClose }: Props & { onClose: () => const [model, setModel] = useState(""); const [sourceId, setSourceId] = useState(null); const sources = - Constants.expoConfig?.extra?.secretsFeatureEnabled === true && + hasFeatureFlag(environment.serverConfig, "secretProviders") && environment.serverConfig?.secretReferences ? configuredSecretSources(environment.serverConfig.settings.secretProviders, messages) : []; diff --git a/apps/server/src/os-jank.test.ts b/apps/server/src/os-jank.test.ts index 857adb2c8e5c3..46b3b6b1e9936 100644 --- a/apps/server/src/os-jank.test.ts +++ b/apps/server/src/os-jank.test.ts @@ -149,44 +149,52 @@ effectIt.effect("keeps mise's PATH record with the login shell PATH", () => ), ); -effectIt.effect("hydrates a missing JAVA_HOME from the login shell and keeps an explicit one", () => - Effect.acquireUseRelease( - Effect.sync(() => - vi - .spyOn(NodeChildProcess, "execFileSync") - .mockReturnValue( - [ - "__T3CODE_ENV_PATH_START__", - "/opt/homebrew/bin", - "__T3CODE_ENV_PATH_END__", - "__T3CODE_ENV_JAVA_HOME_START__", - "/opt/homebrew/opt/openjdk@17", - "__T3CODE_ENV_JAVA_HOME_END__", - ].join("\n"), - ), +effectIt.effect( + "hydrates missing JAVA_HOME and feature flags from the login shell and keeps explicit ones", + () => + Effect.acquireUseRelease( + Effect.sync(() => + vi + .spyOn(NodeChildProcess, "execFileSync") + .mockReturnValue( + [ + "__T3CODE_ENV_PATH_START__", + "/opt/homebrew/bin", + "__T3CODE_ENV_PATH_END__", + "__T3CODE_ENV_JAVA_HOME_START__", + "/opt/homebrew/opt/openjdk@17", + "__T3CODE_ENV_JAVA_HOME_END__", + "__T3CODE_ENV_T3CODE_FEATURE_FLAGS_START__", + "tanstack_source", + "__T3CODE_ENV_T3CODE_FEATURE_FLAGS_END__", + ].join("\n"), + ), + ), + () => + Effect.gen(function* () { + const missing: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin" }; + const explicit: NodeJS.ProcessEnv = { + SHELL: "/bin/zsh", + PATH: "/usr/bin", + JAVA_HOME: "/custom/jdk", + T3CODE_FEATURE_FLAGS: "", + }; + + for (const env of [missing, explicit]) { + yield* fixPath().pipe( + Effect.provideService(HostProcess.Platform, "darwin"), + Effect.provideService(HostProcess.Environment, env), + Effect.provide(NodeServices.layer), + ); + } + + assert.equal(missing.JAVA_HOME, "/opt/homebrew/opt/openjdk@17"); + assert.equal(explicit.JAVA_HOME, "/custom/jdk"); + assert.equal(missing.T3CODE_FEATURE_FLAGS, "tanstack_source"); + assert.equal(explicit.T3CODE_FEATURE_FLAGS, ""); + }), + (probe) => Effect.sync(() => probe.mockRestore()), ), - () => - Effect.gen(function* () { - const missing: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin" }; - const explicit: NodeJS.ProcessEnv = { - SHELL: "/bin/zsh", - PATH: "/usr/bin", - JAVA_HOME: "/custom/jdk", - }; - - for (const env of [missing, explicit]) { - yield* fixPath().pipe( - Effect.provideService(HostProcess.Platform, "darwin"), - Effect.provideService(HostProcess.Environment, env), - Effect.provide(NodeServices.layer), - ); - } - - assert.equal(missing.JAVA_HOME, "/opt/homebrew/opt/openjdk@17"); - assert.equal(explicit.JAVA_HOME, "/custom/jdk"); - }), - (probe) => Effect.sync(() => probe.mockRestore()), - ), ); effectIt.effect("replaces a Path-spelled Windows PATH instead of adding a second key", () => diff --git a/apps/server/src/os-jank.ts b/apps/server/src/os-jank.ts index bc6528f91a5be..dc0c90a787123 100644 --- a/apps/server/src/os-jank.ts +++ b/apps/server/src/os-jank.ts @@ -32,7 +32,7 @@ function logPathHydrationWarning(message: string, error?: unknown): void { // __MISE_DIFF is mise's record of the PATH entries it added. It must travel // with the shell's PATH, or `mise x` can rebuild PATH behind a same-named // wrapper (`exec mise x claude -- claude`) that then re-runs itself forever. -const LOGIN_SHELL_ENV_NAMES = ["PATH", "__MISE_DIFF", "JAVA_HOME"] as const; +const LOGIN_SHELL_ENV_NAMES = ["PATH", "__MISE_DIFF", "JAVA_HOME", "T3CODE_FEATURE_FLAGS"] as const; const LOGIN_SHELL_TIMEOUT = Duration.seconds(5); const SLOW_LOGIN_SHELL_TIMEOUT_MS = 20_000; @@ -64,6 +64,10 @@ function applyLoginShellEnvironment( if (!env.JAVA_HOME && shellEnvironment.JAVA_HOME) { env.JAVA_HOME = shellEnvironment.JAVA_HOME; } + // A headless server (systemd, launchd) reads no profile, yet flags belong where users export them. + if (env.T3CODE_FEATURE_FLAGS === undefined && shellEnvironment.T3CODE_FEATURE_FLAGS) { + env.T3CODE_FEATURE_FLAGS = shellEnvironment.T3CODE_FEATURE_FLAGS; + } } function hydratePosixPath(env: NodeJS.ProcessEnv, platform: NodeJS.Platform): void { diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 720834730e99b..d06186beb1988 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -17,6 +17,7 @@ import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { EnvironmentHttpApi, type RepositoryIdentity } from "@t3tools/contracts"; +import * as FeatureFlags from "@t3tools/shared/FeatureFlags"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Cause from "effect/Cause"; import * as Duration from "effect/Duration"; @@ -1408,6 +1409,7 @@ const layerMakeServer = Layer.unwrap( Layer.provide(VcsProcess.layer), Layer.provideMerge(AgentScopeLive.layer), Layer.provideMerge(layerPlatformServices), + Layer.provideMerge(FeatureFlags.layer), Layer.provide(Layer.succeed(HostProcess.InvokedAs, invokedAs)), ); }), diff --git a/apps/server/src/sourceControl/SourceControlProviderRegistry.ts b/apps/server/src/sourceControl/SourceControlProviderRegistry.ts index c6f823d61f3c6..06616a914b1e9 100644 --- a/apps/server/src/sourceControl/SourceControlProviderRegistry.ts +++ b/apps/server/src/sourceControl/SourceControlProviderRegistry.ts @@ -75,16 +75,11 @@ function unsupportedProvider( // Binding context does not create a second provider-operation span. return SourceControlProvider.SourceControlProvider.of({ kind, - // Unknown hosts have no readable change requests; return none to avoid poll warnings on every refresh. - listChangeRequests: (input) => - kind === "unknown" - ? Effect.succeed([]) - : new SourceControlProviderError({ - provider: kind, - operation: "listChangeRequests", - cwd: input.cwd, - detail: `No ${kind} source control provider is registered.`, - }), + // Unknown hosts, and hosts whose forge a feature flag leaves out, have no readable change + // requests; return none to avoid poll warnings on every refresh. + listChangeRequests: Effect.fn("SourceControlProviderRegistry.unsupported.listChangeRequests")( + () => Effect.succeed([]), + ), getChangeRequest: (input) => new SourceControlProviderError({ provider: kind, diff --git a/apps/server/src/sourceControl/builtInDrivers.ts b/apps/server/src/sourceControl/builtInDrivers.ts index 0e994dcac4a7f..33aa77ffefd8f 100644 --- a/apps/server/src/sourceControl/builtInDrivers.ts +++ b/apps/server/src/sourceControl/builtInDrivers.ts @@ -3,6 +3,7 @@ import type { SourceControlDriverInstance, } from "@t3tools/source-control-core/server/driver"; import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit"; +import * as FeatureFlags from "@t3tools/shared/FeatureFlags"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; @@ -21,9 +22,21 @@ export class SourceControlDrivers extends Context.Service< ReadonlyArray >()("t3/sourceControl/builtInDrivers/SourceControlDrivers") {} -const make = Effect.forEach(BUILT_IN_SOURCE_CONTROL_DRIVER_LIST, (driver) => - driver.make.pipe(Effect.map((instance) => ({ driver, instance }))), -); +/** Drivers offered only while their feature flag is on. */ +const FLAGGED_DRIVERS: Readonly> = { + "tanstack-source": "tanstackSource", +}; + +const make = Effect.gen(function* () { + const flags = yield* FeatureFlags.FeatureFlags; + const drivers = BUILT_IN_SOURCE_CONTROL_DRIVER_LIST.filter((driver) => { + const flag = FLAGGED_DRIVERS[driver.kind]; + return flag === undefined || flags[flag]; + }); + return yield* Effect.forEach(drivers, (driver) => + driver.make.pipe(Effect.map((instance) => ({ driver, instance }))), + ); +}); export const layer = Layer.effect(SourceControlDrivers, make).pipe( Layer.provideMerge(ServerSourceControlHost.layer), diff --git a/apps/server/src/sourceControl/sourceControlDefinitions.ts b/apps/server/src/sourceControl/sourceControlDefinitions.ts index c6a770a897f02..6dff3fe3c6962 100644 --- a/apps/server/src/sourceControl/sourceControlDefinitions.ts +++ b/apps/server/src/sourceControl/sourceControlDefinitions.ts @@ -1,7 +1,7 @@ import * as AzureDevOpsDriver from "@t3tools/source-control-azure-devops/server/driver"; import * as BitbucketDriver from "@t3tools/source-control-bitbucket/server/driver"; import * as CursorOriginDriver from "@t3tools/source-control-cursor-origin/server/driver"; -import { makeBuiltInSourceControlDefinitions } from "@t3tools/source-control-definitions/registry"; +import { builtInSourceControlDefinitions } from "@t3tools/source-control-definitions/registry"; import * as ForgejoDriver from "@t3tools/source-control-forgejo/server/driver"; import * as GitCafeDriver from "@t3tools/source-control-gitcafe/server/driver"; import * as GitHubDriver from "@t3tools/source-control-github/server/driver"; @@ -9,26 +9,21 @@ import * as GitLabDriver from "@t3tools/source-control-gitlab/server/driver"; import * as TanStackSourceDriver from "@t3tools/source-control-tanstack-source/server/driver"; /** - * TanStack Source is in private beta, so its forge exists only on a server started with - * `T3CODE_TANSTACK_SOURCE=1`. Read once at load: the registry below is a module constant. + * In the shared registry's order, which is the order hosts are listed and probed in. Feature + * flags leave some out; see `builtInDrivers.ts`. */ -const tanStackSourceEnabled = process.env.T3CODE_TANSTACK_SOURCE?.trim() === "1"; - -/** In the shared registry's order, which is the order hosts are listed and probed in. */ export const BUILT_IN_SOURCE_CONTROL_DRIVER_LIST = [ GitHubDriver.driver, CursorOriginDriver.driver, GitLabDriver.driver, GitCafeDriver.driver, - ...(tanStackSourceEnabled ? [TanStackSourceDriver.driver] : []), + TanStackSourceDriver.driver, ForgejoDriver.driver, BitbucketDriver.driver, AzureDevOpsDriver.driver, ]; -export const sourceControlDefinitions = makeBuiltInSourceControlDefinitions({ - tanStackSource: tanStackSourceEnabled, -}); +export const sourceControlDefinitions = builtInSourceControlDefinitions; /** A host CLI command that merges or closes a change request, such as `gh pr merge`. */ export const isChangeRequestCloseCommand = (command: string) => diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index e629af899c172..02ca5170d7ffd 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -165,6 +165,7 @@ import * as SecretCheck from "./secrets/SecretCheck.ts"; import * as ServerConfigModule from "./config.ts"; import * as Keybindings from "./keybindings.ts"; import { USAGE_LIMITS_COMMAND } from "@t3tools/shared/usageLimits"; +import * as FeatureFlags from "@t3tools/shared/FeatureFlags"; import * as ServerSettings from "./serverSettings.ts"; import * as ManagedPolicy from "./policy/ManagedPolicy.ts"; @@ -906,6 +907,7 @@ const layerUnusedConfigRpcServices = Layer.mergeAll( Layer.mock(TaskFolders.TaskFolders)({}), Layer.mock(WorkspaceFileSystem.WorkspaceFileSystem)({}), Layer.mock(WorktreeSetupTracker.WorktreeSetupTracker)({}), + FeatureFlags.layerTest(), ); const layerConfigSources = Layer.mergeAll( diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index afa030d4d7e9c..90c264f5408ca 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -1,6 +1,7 @@ import { GitCommandError, OrchestrationDispatchCommandError } from "@t3tools/contracts"; // @effect-diagnostics-next-line nodeBuiltinImport:off -- A synchronous digest inside the pure provider mapping. import * as NodeCrypto from "node:crypto"; +import * as FeatureFlags from "@t3tools/shared/FeatureFlags"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Context from "effect/Context"; import * as NodeHttpServerRequest from "@effect/platform-node/NodeHttpServerRequest"; @@ -1533,6 +1534,7 @@ export const layerWsRpc = ( const checkpointDiffQuery = yield* CheckpointDiffQuery.CheckpointDiffQuery; const nativeChildWork = yield* NativeChildWorkQuery.NativeChildWorkQuery; const keybindings = yield* Keybindings.Keybindings; + const featureFlags = yield* FeatureFlags.FeatureFlags; const environmentTheme = yield* EnvironmentTheme.EnvironmentThemeService; const externalLauncher = yield* ExternalLauncher.ExternalLauncher; const remoteOpenTargets = yield* RemoteOpenTargets.RemoteOpenTargets; @@ -1920,6 +1922,10 @@ export const layerWsRpc = ( secretProviderSettings: true, secretReferences: true, secretRequestReferences: true, + featureFlags: { + secretProviders: featureFlags.secretProviders, + tanstackSource: featureFlags.tanstackSource, + }, ...Option.match(scratchWorkspaceRoot, { onNone: () => ({}), onSome: (root) => ({ scratchWorkspaceRoot: root }), diff --git a/apps/web/src/components/chat/SecretRequestCard.tsx b/apps/web/src/components/chat/SecretRequestCard.tsx index d337e7a1b9b54..25c1fe59d5e6b 100644 --- a/apps/web/src/components/chat/SecretRequestCard.tsx +++ b/apps/web/src/components/chat/SecretRequestCard.tsx @@ -24,6 +24,7 @@ import type { SecretProviderId, } from "@t3tools/contracts"; import { useAtomValue } from "@effect/atom-react"; +import { hasFeatureFlag } from "@t3tools/client-runtime/state/server"; import { T, useGT, useMessages, Var } from "gt-react"; import { CheckIcon, @@ -36,7 +37,6 @@ import { } from "lucide-react"; import { useId, useRef, useState, type FormEvent } from "react"; -import { isSecretsFeatureEnabled } from "../../env"; import { serverEnvironment } from "../../state/server"; import { useAtomCommand } from "../../state/use-atom-command"; import { Button } from "../ui/button"; @@ -80,7 +80,7 @@ const NO_SOURCES: ReadonlyArray = []; function useSecretRequestSources(environmentId: EnvironmentId) { const config = useAtomValue(serverEnvironment.configValueAtom(environmentId)); const messages = useMessages(); - return isSecretsFeatureEnabled + return hasFeatureFlag(config, "secretProviders") ? secretRequestSources(config, config?.settings.secretProviders ?? {}, messages) : NO_SOURCES; } diff --git a/apps/web/src/components/settings/CloudVoiceConfiguration.browser.test.tsx b/apps/web/src/components/settings/CloudVoiceConfiguration.browser.test.tsx index b5eddbcc10df8..f859695e3360d 100644 --- a/apps/web/src/components/settings/CloudVoiceConfiguration.browser.test.tsx +++ b/apps/web/src/components/settings/CloudVoiceConfiguration.browser.test.tsx @@ -11,10 +11,6 @@ import { VoiceSettingsPanel } from "./VoiceSettingsPanel"; import { SettingsScopeProvider } from "./SettingsScopeContext"; vi.mock(import("../../state/session"), { spy: true }); -vi.mock("../../env", async (original) => ({ - ...(await original()), - isSecretsFeatureEnabled: true, -})); vi.mock("../../state/environments", async (importOriginal) => ({ ...(await importOriginal()), useEnvironments: () => ({ @@ -24,6 +20,7 @@ vi.mock("../../state/environments", async (importOriginal) => ({ label: "Laptop", connection: { phase: "available" }, serverConfig: { + featureFlags: { secretProviders: true }, secretReferences: true, settings: { secretProviders: { diff --git a/apps/web/src/components/settings/CloudVoiceConfiguration.tsx b/apps/web/src/components/settings/CloudVoiceConfiguration.tsx index 90c93009d4634..0a992f4f93b61 100644 --- a/apps/web/src/components/settings/CloudVoiceConfiguration.tsx +++ b/apps/web/src/components/settings/CloudVoiceConfiguration.tsx @@ -1,6 +1,7 @@ import { useAtomRefresh, useAtomValue } from "@effect/atom-react"; import { cloudSpeechDisclosure } from "@t3tools/shared/speechCopy"; import type { PreparedConnection } from "@t3tools/client-runtime/connection"; +import { hasFeatureFlag } from "@t3tools/client-runtime/state/server"; import { configuredSecretSources, secretRequestReference, @@ -31,7 +32,6 @@ import type { HttpClient } from "effect/http"; import { Atom, AsyncResult } from "effect/reactivity"; import { useId, useState } from "react"; import { T, useGT, useMessages, Var } from "gt-react"; -import { isSecretsFeatureEnabled } from "../../env"; import { inEnvironmentSpeechRuntime, runEnvironmentSpeech, @@ -194,7 +194,8 @@ export function CloudVoiceConfiguration({ const saved = AsyncResult.isSuccess(presence) ? presence.value?.[provider] : undefined; const existing = environment.serverConfig?.settings?.cloudSpeechCredentials?.[provider]; const sources = - isSecretsFeatureEnabled && environment.serverConfig?.secretReferences + hasFeatureFlag(environment.serverConfig, "secretProviders") && + environment.serverConfig?.secretReferences ? configuredSecretSources(environment.serverConfig.settings?.secretProviders ?? {}, messages) : []; const reference = diff --git a/apps/web/src/components/settings/SecretSourceInput.tsx b/apps/web/src/components/settings/SecretSourceInput.tsx index 35b7218a63f03..53263c226d2f0 100644 --- a/apps/web/src/components/settings/SecretSourceInput.tsx +++ b/apps/web/src/components/settings/SecretSourceInput.tsx @@ -7,6 +7,7 @@ import { } from "@t3tools/contracts"; import { builtInSecretProviderDefinitions } from "@t3tools/secret-provider-definitions/registry"; import { invalidSecretReferenceText } from "@t3tools/client-runtime/secret-request"; +import { hasFeatureFlag } from "@t3tools/client-runtime/state/server"; import { useAtomValue } from "@effect/atom-react"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; @@ -14,7 +15,6 @@ import { useGT, useMessages } from "gt-react"; import { AlertTriangleIcon, CheckIcon, KeyRoundIcon, RefreshCwIcon, TypeIcon } from "lucide-react"; import { useState, type ComponentProps, type ComponentType, type ReactNode } from "react"; -import { isSecretsFeatureEnabled } from "../../env"; import { useEnvironmentSettings } from "../../hooks/useSettings"; import { OnePasswordIcon } from "../Icons"; import { serverEnvironment } from "../../state/server"; @@ -42,9 +42,9 @@ export function useSecretSources(environmentId: EnvironmentId): ReadonlyArray settings.secretProviders); const supported = useAtomValue( serverEnvironment.configValueAtom(environmentId), - (config) => config?.secretReferences === true, + (config) => hasFeatureFlag(config, "secretProviders") && config?.secretReferences === true, ); - if (!isSecretsFeatureEnabled || !supported) return NO_SECRET_SOURCES; + if (!supported) return NO_SECRET_SOURCES; return (Object.entries(providers) as Array<[SecretProviderId, SecretProviderConfig]>) .filter(([, config]) => classifySecretProvider(config).kind !== "unsupported") .map(([id, config]) => ({ id, kind: config.kind, label: config.label })); diff --git a/apps/web/src/components/settings/SettingsSidebarNav.composition.browser.test.tsx b/apps/web/src/components/settings/SettingsSidebarNav.composition.browser.test.tsx index 3457bc2467820..338c4ff0fa111 100644 --- a/apps/web/src/components/settings/SettingsSidebarNav.composition.browser.test.tsx +++ b/apps/web/src/components/settings/SettingsSidebarNav.composition.browser.test.tsx @@ -4,12 +4,13 @@ import { page, userEvent } from "vite-plus/test/browser"; import { act, render } from "../../../test/render"; import { SidebarProvider } from "../ui/sidebar"; import { SettingsSidebarNav } from "./SettingsSidebarNav"; -import { SETTINGS_NAV_GROUPS, SETTINGS_SECTION_LABELS } from "./settingsSearch"; +import { settingsNavGroups, SETTINGS_SECTION_LABELS } from "./settingsSearch"; vi.mock("./useAvailableSettingsSearchItems", () => ({ useAvailableSettingsSearchItems: () => [ { id: "theme", title: "Theme", to: "/settings/appearance" }, ], + useHasSecretProvidersEnvironment: () => false, })); it("ignores composing keys in the search", async () => { @@ -76,9 +77,9 @@ it("moves Tab through every settings section", async () => { await using _screen = await renderNav(); await userEvent.click(page.getByRole("combobox", { name: "Search settings" })); - const sections = SETTINGS_NAV_GROUPS.flatMap((group) => group.paths).map( - (to) => SETTINGS_SECTION_LABELS[to], - ); + const sections = settingsNavGroups(false) + .flatMap((group) => group.paths) + .map((to) => SETTINGS_SECTION_LABELS[to]); const tabbed: string[] = []; for (let step = 0; step < sections.length; step += 1) { await userEvent.tab(); @@ -103,7 +104,7 @@ it.each([1280, 390])("names each group by a heading outside it at %ipx wide", as ); } const groups = page.getByRole("group").elements(); - expect(groups).toHaveLength(SETTINGS_NAV_GROUPS.length); + expect(groups).toHaveLength(settingsNavGroups(false).length); for (const group of groups) { const first = group.querySelector("[data-settings-section]")?.textContent; const heading = document.getElementById(group.getAttribute("aria-labelledby") ?? ""); diff --git a/apps/web/src/components/settings/SettingsSidebarNav.tsx b/apps/web/src/components/settings/SettingsSidebarNav.tsx index 794574d9505b4..10bc07c123dd8 100644 --- a/apps/web/src/components/settings/SettingsSidebarNav.tsx +++ b/apps/web/src/components/settings/SettingsSidebarNav.tsx @@ -53,13 +53,16 @@ import { scrollToSettingsTarget } from "./settingsLayout"; import { searchSettings, revealSettingsSearchTarget, - SETTINGS_NAV_GROUPS, + settingsNavGroups, SETTINGS_NAV_LABELS, SETTINGS_SECTION_LABELS, type SettingsPath, type SettingsSearchItem, } from "./settingsSearch"; -import { useAvailableSettingsSearchItems } from "./useAvailableSettingsSearchItems"; +import { + useAvailableSettingsSearchItems, + useHasSecretProvidersEnvironment, +} from "./useAvailableSettingsSearchItems"; import { handleSettingsSectionKeyDown } from "./settingsSectionNavigation"; import { workspaceAreaProps } from "../../lib/workspaceFocus"; @@ -143,6 +146,7 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) { const [compactSearchOpen, setCompactSearchOpen] = useState(false); const [activeResultIndex, setActiveResultIndex] = useState(0); const searchableItems = useAvailableSettingsSearchItems(); + const navGroups = settingsNavGroups(useHasSecretProvidersEnvironment()); const results = searchSettings(query, searchableItems, m); const isSearching = query.trim().length > 0; const hasResults = results.length > 0; @@ -379,7 +383,7 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) { )}
    - {SETTINGS_NAV_GROUPS.map((group, index) => ( + {navGroups.map((group, index) => (
    ({ - ...(await importOriginal()), - isSecretsFeatureEnabled: false, -})); - const ITEMS: ReadonlyArray = [ { id: "word-wrap", @@ -76,9 +71,27 @@ describe("searchSettings", () => { } }); - it("hides the Secrets page from nav and search while the secrets feature is disabled", () => { - expect(SETTINGS_NAV_GROUPS.flatMap((group) => group.paths)).not.toContain("/settings/secrets"); - expect(searchSettings("1password").map((item) => item.to)).not.toContain("/settings/secrets"); + it("shows the Secrets page in nav and search only when an environment enables secret providers", () => { + const availability = { + hasCloudPublicConfig: false, + hasEnvironment: true, + hasProviderSettingsEnvironment: true, + canManageLocalBackend: false, + isWslSettingsRowVisible: false, + hasThreadAutoSettlement: false, + }; + for (const enabled of [false, true]) { + const navPaths = settingsNavGroups(enabled).flatMap((group) => group.paths); + const searchPaths = searchSettings( + "1password", + filterAvailableSettingsSearchItems({ + ...availability, + hasSecretProvidersEnvironment: enabled, + }), + ).map((item) => item.to); + expect(navPaths.includes("/settings/secrets")).toBe(enabled); + expect(searchPaths.includes("/settings/secrets")).toBe(enabled); + } }); it("finds where subagents and side chats open by any of its names", () => { diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index e891af3db0434..d91d6da4a42d7 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -1,5 +1,5 @@ import { HOSTED_APP_CHANNEL } from "~/branding"; -import { isElectron, isSecretsFeatureEnabled } from "~/env"; +import { isElectron } from "~/env"; import { isMacPlatform, isWindowsPlatform, normalizeSearchText } from "~/lib/utils"; import { STATIC_KEYBINDING_COMMANDS, type KeybindingCommand } from "@t3tools/contracts"; import type { EnvironmentId } from "@t3tools/contracts"; @@ -61,7 +61,7 @@ export interface SettingsSearchItem { readonly macOnly?: boolean; readonly windowsOnly?: boolean; readonly releaseChannelOnly?: boolean; - readonly secretsFeatureOnly?: boolean; + readonly secretProvidersOnly?: boolean; readonly cloudOnly?: boolean; readonly environmentOnly?: boolean; readonly providerSettingsOnly?: boolean; @@ -91,6 +91,7 @@ export interface SettingsSearchAvailability { /** An environment without a provider allow-list, which hides text generators. */ readonly hasTextGeneratorsEnvironment?: boolean; readonly hasPrimaryEnvironment?: boolean; + readonly hasSecretProvidersEnvironment?: boolean; } export const SETTINGS_SECTION_LABELS: Readonly> = { @@ -128,12 +129,14 @@ export const SETTINGS_NAV_LABELS: Readonly> = { "/settings/access": msg("Sharing & access", { $context: "settings navigation item" }), }; -/** Sidebar order. A group with a hidden heading is set apart on screen by space alone. */ -export const SETTINGS_NAV_GROUPS: ReadonlyArray<{ +type SettingsNavGroup = { readonly heading: string; readonly headingHidden?: true; readonly paths: ReadonlyArray; -}> = [ +}; + +/** Sidebar order. A group with a hidden heading is set apart on screen by space alone. */ +const ALL_SETTINGS_NAV_GROUPS: ReadonlyArray = [ { heading: msg("Preferences"), headingHidden: true, @@ -163,11 +166,7 @@ export const SETTINGS_NAV_GROUPS: ReadonlyArray<{ }, { heading: msg("Connections"), - paths: [ - "/settings/connections", - "/settings/access", - ...(isSecretsFeatureEnabled ? (["/settings/secrets"] as const) : []), - ], + paths: ["/settings/connections", "/settings/access", "/settings/secrets"], }, { heading: msg("More"), @@ -176,6 +175,18 @@ export const SETTINGS_NAV_GROUPS: ReadonlyArray<{ }, ]; +const SETTINGS_NAV_GROUPS_WITHOUT_SECRETS = ALL_SETTINGS_NAV_GROUPS.map((group) => ({ + ...group, + paths: group.paths.filter((path) => path !== "/settings/secrets"), +})); + +/** Sidebar groups; Secrets shows only when some environment's server enables secret providers. */ +export function settingsNavGroups(hasSecretProvidersEnvironment: boolean) { + return hasSecretProvidersEnvironment + ? ALL_SETTINGS_NAV_GROUPS + : SETTINGS_NAV_GROUPS_WITHOUT_SECRETS; +} + export function keybindingSearchAnchorId(command: Command) { return `keybinding-${command}` as const; } @@ -1463,7 +1474,7 @@ export const SETTINGS_SEARCH_ITEMS = [ title: msg("Secret providers"), to: "/settings/secrets", searchTerms: [msg("1password vault credentials api key")], - secretsFeatureOnly: true, + secretProvidersOnly: true, }, { id: "secret-providers-add", @@ -1471,7 +1482,7 @@ export const SETTINGS_SEARCH_ITEMS = [ to: "/settings/secrets", targetId: "secret-providers", searchTerms: [msg("new 1password vault op cli account")], - secretsFeatureOnly: true, + secretProvidersOnly: true, }, { id: "archive", @@ -1644,7 +1655,8 @@ export function filterAvailableSettingsSearchItems( (!item.peerLinksOnly || availability.hasPeerLinkHost === true) && (!item.fastWorktreeCheckoutOnly || availability.hasFastWorktreeCheckoutEnvironment === true) && - (!item.textGeneratorsOnly || availability.hasTextGeneratorsEnvironment === true), + (!item.textGeneratorsOnly || availability.hasTextGeneratorsEnvironment === true) && + (!item.secretProvidersOnly || availability.hasSecretProvidersEnvironment === true), ); } @@ -1657,7 +1669,6 @@ export function settingsForThisPlatform( (item) => (isElectron || item.desktopOnly !== true) && (!item.releaseChannelOnly || isElectron || HOSTED_APP_CHANNEL !== null) && - (!item.secretsFeatureOnly || isSecretsFeatureEnabled) && (!item.macOnly || isMacPlatform(platform)) && (!item.windowsOnly || isWindowsPlatform(platform)), ); diff --git a/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts b/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts index e6d947935bd94..beb5e3c85c52c 100644 --- a/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts +++ b/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts @@ -1,4 +1,5 @@ import { useMessages } from "gt-react"; +import { hasFeatureFlag } from "@t3tools/client-runtime/state/server"; import { AuthEnvironmentMaintainScope } from "@t3tools/contracts"; import { usePrimaryCloudLinkState } from "~/cloud/cloudLinkState"; @@ -17,6 +18,14 @@ import { getThreadAutoSettlementSearchAvailability, } from "./settingsSearch"; +/** Any environment whose server enables secret providers; gates the Secrets page, nav and search. */ +export function useHasSecretProvidersEnvironment() { + const { environments } = useEnvironments(); + return environments.some((environment) => + hasFeatureFlag(environment.serverConfig, "secretProviders"), + ); +} + export function useAvailableSettingsSearchItems() { const { environments } = useEnvironments(); // Explicit booleans keep flags out of the filter cache so environment updates do not rebuild the list. @@ -42,6 +51,7 @@ export function useAvailableSettingsSearchItems() { environment.serverConfig !== null && environment.serverConfig.managedPolicy?.limits?.providers?.allowedDrivers === undefined, ) === true; + const hasSecretProvidersEnvironment = useHasSecretProvidersEnvironment(); const hasThreadAutoSettlement = getThreadAutoSettlementSearchAvailability(environments).eligibleEnvironmentIds.length > 0; const primaryEnvironmentId = usePrimaryEnvironmentId(); @@ -75,5 +85,6 @@ export function useAvailableSettingsSearchItems() { hasFastWorktreeCheckoutEnvironment, hasTextGeneratorsEnvironment, hasPrimaryEnvironment: primaryEnvironmentId !== null, + hasSecretProvidersEnvironment, }); } diff --git a/apps/web/src/env.ts b/apps/web/src/env.ts index a0a28c5d7fd60..be2a563d736bd 100644 --- a/apps/web/src/env.ts +++ b/apps/web/src/env.ts @@ -1,6 +1,2 @@ // Preload installs desktopBridge before web code runs, so module-load detection is reliable. export const isElectron = typeof window !== "undefined" && window.desktopBridge !== undefined; - -export const isSecretsFeatureEnabled = ["1", "true"].includes( - import.meta.env.T3CODE_FEATURE_SECRETS?.trim().toLowerCase() ?? "", -); diff --git a/apps/web/src/routes/_chat.settings.secrets.tsx b/apps/web/src/routes/_chat.settings.secrets.tsx index d97e00fda19f7..e0031f4aeaf9a 100644 --- a/apps/web/src/routes/_chat.settings.secrets.tsx +++ b/apps/web/src/routes/_chat.settings.secrets.tsx @@ -1,11 +1,19 @@ -import { createFileRoute, redirect } from "@tanstack/react-router"; +import { createFileRoute, Navigate } from "@tanstack/react-router"; import { SecretsSettingsPanel } from "../components/settings/SecretsSettings"; -import { isSecretsFeatureEnabled } from "../env"; +import { useHasSecretProvidersEnvironment } from "../components/settings/useAvailableSettingsSearchItems"; +import { useEnvironments } from "../state/environments"; export const Route = createFileRoute("/_chat/settings/secrets")({ - beforeLoad: () => { - if (!isSecretsFeatureEnabled) throw redirect({ to: "/settings/general", replace: true }); - }, - component: SecretsSettingsPanel, + component: SecretsSettingsRoute, }); + +function SecretsSettingsRoute() { + const enabled = useHasSecretProvidersEnvironment(); + // Only redirect once every environment reported flags; one may enable them after another loads. + const { isReady, environments } = useEnvironments(); + const allReported = + isReady && environments.every((environment) => environment.serverConfig !== null); + if (!enabled && allReported) return ; + return ; +} diff --git a/apps/web/src/vite-env.d.ts b/apps/web/src/vite-env.d.ts index 63f7cca9cbfc6..307b9c5d8284d 100644 --- a/apps/web/src/vite-env.d.ts +++ b/apps/web/src/vite-env.d.ts @@ -15,7 +15,6 @@ interface ImportMetaEnv { readonly VITE_RELAY_OTLP_TRACES_DATASET: string; readonly VITE_RELAY_OTLP_TRACES_TOKEN: string; readonly T3CODE_DESKTOP_UPDATE_REPOSITORY: string; - readonly T3CODE_FEATURE_SECRETS: string; readonly APP_VERSION: string; } diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index 073fca7943d3e..005e828202bda 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -50,7 +50,6 @@ const configuredDesktopUpdateRepository = process.env.T3CODE_DESKTOP_UPDATE_REPOSITORY?.trim() || process.env.GITHUB_REPOSITORY?.trim() || ""; -const configuredFeatureSecrets = process.env.T3CODE_FEATURE_SECRETS?.trim() || ""; const configuredHostedAppUrl = (() => { const explicitHostedAppUrl = process.env.VITE_HOSTED_APP_URL?.trim(); if (explicitHostedAppUrl) { @@ -370,7 +369,6 @@ export default defineConfig(({ command }) => { "import.meta.env.T3CODE_DESKTOP_UPDATE_REPOSITORY": JSON.stringify( configuredDesktopUpdateRepository, ), - "import.meta.env.T3CODE_FEATURE_SECRETS": JSON.stringify(configuredFeatureSecrets), "import.meta.env.VITE_RELEASE_CHANNEL": JSON.stringify(configuredReleaseChannel), "import.meta.env.APP_VERSION": JSON.stringify(configuredAppVersion), }, diff --git a/docs/user/source-control.md b/docs/user/source-control.md index cb8d252b9ab37..fa193bf0e87a8 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -146,8 +146,10 @@ Merging a stack lands it through GitCafe, and updating a branch restacks the lay ### TanStack Source -TanStack Source is in private beta, so the server shows it only when started with -`T3CODE_TANSTACK_SOURCE=1` in its environment. Install its CLI and sign in: +TanStack Source is in private beta, so the server shows it only when its environment turns the flag +on: `export T3CODE_FEATURE_FLAGS=tanstack_source` in your shell profile, then restart T3 Code. Separate +several flags with commas. A value already set in the server's own environment, such as a service +definition, is used instead of the profile. Install its CLI and sign in: ```sh curl -fsSL https://source.tanstack.com/install | sh diff --git a/evals/thread-titles/run.ts b/evals/thread-titles/run.ts index d53571698b021..5c77f68752485 100644 --- a/evals/thread-titles/run.ts +++ b/evals/thread-titles/run.ts @@ -6,6 +6,7 @@ import * as FetchHttpClient from "effect/http/FetchHttpClient"; import * as NodePlatformCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { CodexSettings, ProviderInstanceId } from "@t3tools/contracts"; +import * as FeatureFlags from "@t3tools/shared/FeatureFlags"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Duration from "effect/Duration"; @@ -153,6 +154,7 @@ await Effect.runPromise( ProcessRunner.layer, SourceControlProviderRegistry.layer.pipe( Layer.provide(SourceControlBuiltInDrivers.layer), + Layer.provide(FeatureFlags.layer), Layer.provide(ServerSettings.layerTest()), Layer.provide(VcsDriverRegistry.layer.pipe(Layer.provide(VcsProjectConfig.layer))), Layer.provide(GitVcsDriver.layer), diff --git a/packages/client-runtime/src/sourceControlClients.test.ts b/packages/client-runtime/src/sourceControlClients.test.ts index 684b26ddf5e36..1f2cbfbc3a4d7 100644 --- a/packages/client-runtime/src/sourceControlClients.test.ts +++ b/packages/client-runtime/src/sourceControlClients.test.ts @@ -1,5 +1,4 @@ import { ProjectId, SourceControlProviderKind } from "@t3tools/contracts"; -import { makeBuiltInSourceControlDefinitions } from "@t3tools/source-control-definitions/registry"; import { describe, expect, it } from "vite-plus/test"; import { appSignInTargetForRemote, sourceControlClients } from "./sourceControlClients.ts"; @@ -50,12 +49,6 @@ describe("sourceControlClients.parseChangeRequestUrl", () => { expect(sourceControlClients.parseChangeRequestUrl(url)?.link.repositoryUrl).toBe( "https://source.tanstack.com/@TanStack/router", ); - // A server without the beta reads no TanStack Source host at all. - const without = makeBuiltInSourceControlDefinitions({ tanStackSource: false }); - expect(without.find(SourceControlProviderKind.make("tanstack-source"))).toBeUndefined(); - expect(without.recognizeRemote("https://source.tanstack.com/@TanStack/router.git")?.kind).toBe( - "unknown", - ); }); it("reads a Cursor Origin pull request under Origin's git host, not as GitHub's /pull/", () => { diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.ts index 3179f0c149e4b..222c12e6ba3e3 100644 --- a/packages/client-runtime/src/state/server.ts +++ b/packages/client-runtime/src/state/server.ts @@ -12,6 +12,7 @@ import { type ProviderInstanceId, type ServerConfig, type ServerConfigStreamEvent, + type ServerFeatureFlags, type ServerLifecycleWelcomePayload, type ServerLifecycleStreamReadyEvent, type ServerProviderWorkspaceSnapshot, @@ -832,6 +833,14 @@ function serverWelcomeStateChanges(environmentId: EnvironmentId) { ); } +/** Whether an environment's server turned on a feature flag; unset flags and unloaded configs are off. */ +export function hasFeatureFlag( + config: Pick | null | undefined, + flag: keyof ServerFeatureFlags, +): boolean { + return config?.featureFlags?.[flag] === true; +} + export function resolveServerConfigValue( projection: ServerConfigProjection | null, initialConfig: ServerConfig | null, diff --git a/packages/contracts/src/resourceTelemetry.ts b/packages/contracts/src/resourceTelemetry.ts index f3800089f5c20..24ac9d1bf3874 100644 --- a/packages/contracts/src/resourceTelemetry.ts +++ b/packages/contracts/src/resourceTelemetry.ts @@ -320,7 +320,7 @@ export const ShellEnvironmentPatch = Schema.Struct({ SSL_CERT_DIR: Schema.optionalKey(Schema.NullOr(Schema.String)), NODE_EXTRA_CA_CERTS: Schema.optionalKey(Schema.NullOr(Schema.String)), T3CODE_TELEMETRY_ENABLED: Schema.optionalKey(Schema.NullOr(Schema.String)), - T3CODE_GITHUB_APP_CLIENT_ID: Schema.optionalKey(Schema.NullOr(Schema.String)), + T3CODE_FEATURE_FLAGS: Schema.optionalKey(Schema.NullOr(Schema.String)), T3CODE_RELEASE_BASE_URL: Schema.optionalKey(Schema.NullOr(Schema.String)), __MISE_DIFF: Schema.optionalKey(Schema.NullOr(Schema.String)), JAVA_HOME: Schema.optionalKey(Schema.NullOr(Schema.String)), diff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.ts index afd870ef97cc7..1e70426001495 100644 --- a/packages/contracts/src/server.ts +++ b/packages/contracts/src/server.ts @@ -700,6 +700,13 @@ export const ServerEventLoopStall = Schema.Struct({ }); export type ServerEventLoopStall = typeof ServerEventLoopStall.Type; +/** The boolean `T3CODE_FEATURE_FLAGS` a server started with. Unset flags are off. */ +export const ServerFeatureFlags = Schema.Struct({ + secretProviders: Schema.optionalKey(Schema.Boolean), + tanstackSource: Schema.optionalKey(Schema.Boolean), +}); +export type ServerFeatureFlags = typeof ServerFeatureFlags.Type; + export const ServerConfig = Schema.Struct({ environment: ExecutionEnvironmentDescriptor, auth: ServerAuthDescriptor, @@ -737,6 +744,7 @@ export const ServerConfig = Schema.Struct({ threadSnapshotPagination: Schema.optionalKey(Schema.Boolean), threadFind: Schema.optionalKey(Schema.Boolean), threadFindProgressive: Schema.optionalKey(Schema.Boolean), + featureFlags: Schema.optionalKey(ServerFeatureFlags), /** Settings patches may carry `secretProviders`; older servers drop the key without an error. */ secretProviderSettings: Schema.optionalKey(Schema.Boolean), /** Secret settings may point at a secret provider; older servers drop the reference. */ diff --git a/packages/shared/package.json b/packages/shared/package.json index e0529dbbdefa8..daa396dd07043 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -371,6 +371,10 @@ "types": "./src/managedPolicyFile.ts", "import": "./src/managedPolicyFile.ts" }, + "./FeatureFlags": { + "types": "./src/FeatureFlags.ts", + "import": "./src/FeatureFlags.ts" + }, "./HostProcess": { "types": "./src/HostProcess.ts", "import": "./src/HostProcess.ts" diff --git a/packages/shared/src/FeatureFlags.test.ts b/packages/shared/src/FeatureFlags.test.ts new file mode 100644 index 0000000000000..7a5962131e35c --- /dev/null +++ b/packages/shared/src/FeatureFlags.test.ts @@ -0,0 +1,31 @@ +import { assert, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; + +import * as FeatureFlags from "./FeatureFlags.ts"; + +it.effect("resolves T3CODE_FEATURE_FLAGS lists", () => + Effect.gen(function* () { + const cases: ReadonlyArray< + readonly [string | undefined, Partial] + > = [ + [undefined, {}], + [" tanstack_source , secret_providers=1 ", { tanstackSource: true, secretProviders: true }], + [ + "tanstack_source=0,github_app_client_id=Iv23=x", + { githubAppClientId: Option.some("Iv23=x") }, + ], + ["tanstack_source,typo_flag", { tanstackSource: true }], + // One bad value turns every flag off rather than failing startup. + ["tanstack_source,secret_providers=maybe", {}], + ]; + for (const [list, expected] of cases) { + assert.deepStrictEqual(yield* FeatureFlags.resolve(list), { + secretProviders: false, + tanstackSource: false, + githubAppClientId: Option.none(), + ...expected, + }); + } + }), +); diff --git a/packages/shared/src/FeatureFlags.ts b/packages/shared/src/FeatureFlags.ts new file mode 100644 index 0000000000000..7cc13e3420a48 --- /dev/null +++ b/packages/shared/src/FeatureFlags.ts @@ -0,0 +1,61 @@ +import * as Config from "effect/Config"; +import * as ConfigProvider from "effect/ConfigProvider"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import * as HostProcess from "./HostProcess.ts"; + +/** + * One comma-separated list, such as `tanstack_source,github_app_client_id=Iv23…`. A bare name + * turns a flag on. Read once when the server starts; changing it takes a restart. + */ +const VARIABLE = "T3CODE_FEATURE_FLAGS"; + +const config = Config.all({ + secretProviders: Config.Boolean("secret_providers").pipe(Config.withDefault(false)), + tanstackSource: Config.Boolean("tanstack_source").pipe(Config.withDefault(false)), + /** The public client ID of the T3 Code for GitHub app; unset turns its sign-in off. */ + githubAppClientId: Config.option(Config.String("github_app_client_id")), +}); + +export type FeatureFlagValues = Config.Success; + +export class FeatureFlags extends Context.Service()( + "@t3tools/shared/FeatureFlags", +) {} + +/** The `name=value` pairs of a flags list, with a bare name read as `true`. */ +function parseList(list: string | undefined): Record { + const record: Record = {}; + for (const entry of (list ?? "").split(",")) { + const separator = entry.indexOf("="); + const name = (separator === -1 ? entry : entry.slice(0, separator)).trim(); + if (name === "") continue; + record[name] = separator === -1 ? "true" : entry.slice(separator + 1).trim(); + } + return record; +} + +const parse = (record: Record) => config.parse(ConfigProvider.fromUnknown(record)); + +export const resolve = Effect.fn("FeatureFlags.resolve")(function* (list: string | undefined) { + return yield* parse(parseList(list)).pipe( + Effect.catch((error) => + Effect.logWarning(`Ignoring invalid ${VARIABLE}; every flag is off.`, error).pipe( + Effect.andThen(parse({})), + ), + ), + ); +}); + +export const layer = Layer.effect( + FeatureFlags, + Effect.flatMap(HostProcess.Environment, (env) => resolve(env[VARIABLE])), +); + +export const layerTest = (values: Partial = {}) => + Layer.effect( + FeatureFlags, + Effect.map(resolve(undefined), (defaults) => ({ ...defaults, ...values })), + ); diff --git a/packages/source-control-core/src/server/driver.ts b/packages/source-control-core/src/server/driver.ts index 7f86d0fff3b9e..fcf737fe2181d 100644 --- a/packages/source-control-core/src/server/driver.ts +++ b/packages/source-control-core/src/server/driver.ts @@ -11,6 +11,7 @@ import type * as FileSystem from "effect/FileSystem"; import type { HttpClient, HttpClientError, HttpClientResponse } from "effect/http"; import * as Layer from "effect/Layer"; import type * as Scope from "effect/Scope"; +import type * as FeatureFlags from "@t3tools/shared/FeatureFlags"; import type { SourceControlDefinition } from "../shared/definition.ts"; @@ -80,7 +81,8 @@ export type SourceControlDriverServices = | SourceControlRateLimit.SourceControlRateLimit | HttpClient.HttpClient | FileSystem.FileSystem - | Digest.Digest; + | Digest.Digest + | FeatureFlags.FeatureFlags; export interface SourceControlDriver { readonly kind: SourceControlProviderKind; diff --git a/packages/source-control-definitions/src/registry.ts b/packages/source-control-definitions/src/registry.ts index 46bc9c5b0abd4..90f14961c0d57 100644 --- a/packages/source-control-definitions/src/registry.ts +++ b/packages/source-control-definitions/src/registry.ts @@ -13,42 +13,35 @@ export { canonicalizePullRequestUrl as canonicalizeGitCafePullRequestUrl } from /** * GitHub comes first as the client default for unknown hosts. GitCafe, TanStack Source and Origin * claim URLs first: GitHub and Forgejo accept the same routes on any hostname. TanStack Source is a - * private beta a server may leave out; clients always know it, for a server that has it. + * private beta: every reader knows its URLs, and only a server with its flag on offers the forge. */ -export function makeBuiltInSourceControlDefinitions(options: { readonly tanStackSource: boolean }) { - const tanStackSource = options.tanStackSource ? [TanStackSource.definition] : []; - return makeSourceControlDefinitionRegistry( - [ - GitHub.definition, - CursorOrigin.definition, - GitLab.definition, - GitCafe.definition, - ...tanStackSource, - Forgejo.definition, - Bitbucket.definition, - AzureDevOps.definition, +export const builtInSourceControlDefinitions = makeSourceControlDefinitionRegistry( + [ + GitHub.definition, + CursorOrigin.definition, + GitLab.definition, + GitCafe.definition, + TanStackSource.definition, + Forgejo.definition, + Bitbucket.definition, + AzureDevOps.definition, + ], + { + claimChangeRequestUrlsFirst: [ + GitCafe.definition.kind, + TanStackSource.definition.kind, + CursorOrigin.definition.kind, + AzureDevOps.definition.kind, ], - { - claimChangeRequestUrlsFirst: [ - GitCafe.definition.kind, - ...tanStackSource.map((definition) => definition.kind), - CursorOrigin.definition.kind, - AzureDevOps.definition.kind, - ], - recognizeRemotesIn: [ - GitCafe.definition.kind, - ...tanStackSource.map((definition) => definition.kind), - CursorOrigin.definition.kind, - Forgejo.definition.kind, - GitHub.definition.kind, - GitLab.definition.kind, - AzureDevOps.definition.kind, - Bitbucket.definition.kind, - ], - }, - ); -} - -export const builtInSourceControlDefinitions = makeBuiltInSourceControlDefinitions({ - tanStackSource: true, -}); + recognizeRemotesIn: [ + GitCafe.definition.kind, + TanStackSource.definition.kind, + CursorOrigin.definition.kind, + Forgejo.definition.kind, + GitHub.definition.kind, + GitLab.definition.kind, + AzureDevOps.definition.kind, + Bitbucket.definition.kind, + ], + }, +); diff --git a/packages/source-control-github/scripts/measure-pr-preview.ts b/packages/source-control-github/scripts/measure-pr-preview.ts index 5047dcb281b1e..551245c5600ee 100644 --- a/packages/source-control-github/scripts/measure-pr-preview.ts +++ b/packages/source-control-github/scripts/measure-pr-preview.ts @@ -21,6 +21,7 @@ import * as GitHubAppAccess from "../src/server/GitHubAppAccess.ts"; import * as GitHubPullRequestApi from "../src/server/GitHubPullRequestApi.ts"; import * as GitHubPullRequestProvider from "../src/server/GitHubPullRequestProvider.ts"; import * as GitHubRest from "../src/server/GitHubRest.ts"; +import * as FeatureFlags from "@t3tools/shared/FeatureFlags"; const repeatsFlag = process.argv.find((arg) => arg.startsWith("--repeats=")); const repeats = repeatsFlag === undefined ? 1 : Number(repeatsFlag.slice("--repeats=".length)); @@ -119,6 +120,7 @@ const services = GitHubPullRequestApi.layer.pipe( Layer.provideMerge(SourceControlRateLimit.layer), Layer.provideMerge(measuredHttp), Layer.provideMerge(sourceControlHost), + Layer.provideMerge(FeatureFlags.layer), ); const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); diff --git a/packages/source-control-github/src/server/GitHubAppSignIn.test.ts b/packages/source-control-github/src/server/GitHubAppSignIn.test.ts index 1d8652f06495f..f212386f61942 100644 --- a/packages/source-control-github/src/server/GitHubAppSignIn.test.ts +++ b/packages/source-control-github/src/server/GitHubAppSignIn.test.ts @@ -15,6 +15,7 @@ import { DEFAULT_SERVER_SETTINGS, ServerSettingsError } from "@t3tools/contracts import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost"; import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit"; import { readSourceControlHostSettings } from "@t3tools/source-control-core/shared/definition"; +import * as FeatureFlags from "@t3tools/shared/FeatureFlags"; import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings"; import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost"; @@ -54,6 +55,8 @@ function harness(options: { readonly settingsWritesFail?: boolean; /** Holds a request open until it completes, to interleave other work with it. */ readonly gate?: (sent: Sent) => Effect.Effect; + /** Defaults to a configured app; null runs without one. */ + readonly clientId?: string | null; }) { const requests: Array = []; const http = HttpClient.make((request) => { @@ -114,6 +117,13 @@ function harness(options: { Layer.provideMerge(SourceControlRateLimit.layer), Layer.provideMerge(options.settingsWritesFail === true ? failingWrites : host), Layer.provide(NodeCrypto.layer), + Layer.provide( + FeatureFlags.layerTest({ + githubAppClientId: Option.fromNullishOr( + options.clientId === undefined ? "Iv-test-client" : options.clientId, + ), + }), + ), Layer.provide(FileSystem.layerNoop({})), Layer.provide(Layer.succeed(HttpClient.HttpClient, http)), ); @@ -157,7 +167,6 @@ const installedOn = (sent: Sent): Reply => beforeEach(() => { for (const name of ["GH_TOKEN", "GITHUB_TOKEN"]) vi.stubEnv(name, ""); - vi.stubEnv(GitHubAppSignIn.CLIENT_ID_VARIABLE, "Iv-test-client"); }); afterEach(() => { vi.unstubAllEnvs(); @@ -267,8 +276,8 @@ describe("GitHubAppSignIn", () => { }); it.effect("does nothing with the app when the server has no client ID", () => { - vi.stubEnv(GitHubAppSignIn.CLIENT_ID_VARIABLE, ""); const { layer, requests } = harness({ + clientId: null, signIns: { "github.com": session() }, handle: () => ({ body: { login: "octocat" } }), }); diff --git a/packages/source-control-github/src/server/GitHubAppSignIn.ts b/packages/source-control-github/src/server/GitHubAppSignIn.ts index 28bde65ed84a8..843e14ce00687 100644 --- a/packages/source-control-github/src/server/GitHubAppSignIn.ts +++ b/packages/source-control-github/src/server/GitHubAppSignIn.ts @@ -19,16 +19,10 @@ import * as Schema from "effect/Schema"; import * as Schedule from "effect/Schedule"; import * as Semaphore from "effect/Semaphore"; import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; -import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as FeatureFlags from "@t3tools/shared/FeatureFlags"; import * as GitHubClient from "../shared/definition.ts"; -/** - * The public client ID of the T3 Code for GitHub app, which the device flow needs (no secret). - * Unset turns the app sign-in off: no app tokens, no sign-in, nothing for clients to show. - */ -export const CLIENT_ID_VARIABLE = "T3CODE_GITHUB_APP_CLIENT_ID"; - const KIND = SourceControlProviderKind.make("github"); const REQUEST_TIMEOUT = Duration.seconds(15); // Refresh ahead of expiry so a token never lapses between the check and a long request. @@ -107,7 +101,8 @@ const signInError = (host: string, reason: SourceControlSignInFailure, detail: s export const make = Effect.gen(function* () { const sourceControlHost = yield* SourceControlHost.SourceControlHost; const httpClient = yield* HttpClient.HttpClient; - const clientId = (yield* HostProcess.Environment)[CLIENT_ID_VARIABLE]?.trim() ?? ""; + // Unset turns the app sign-in off: no app tokens, no sign-in, nothing for clients to show. + const clientId = Option.getOrElse((yield* FeatureFlags.FeatureFlags).githubAppClientId, () => ""); const enabled = clientId !== ""; const scope = yield* Effect.scope; const refreshLock = yield* Semaphore.make(1); diff --git a/packages/source-control-github/src/server/GitHubRest.test.ts b/packages/source-control-github/src/server/GitHubRest.test.ts index 460bfbc16d82c..9d82bee19752c 100644 --- a/packages/source-control-github/src/server/GitHubRest.test.ts +++ b/packages/source-control-github/src/server/GitHubRest.test.ts @@ -8,6 +8,7 @@ import * as NodeFSP from "node:fs/promises"; import * as NodeOS from "node:os"; // @effect-diagnostics-next-line nodeBuiltinImport:off -- Keep the native socket path within the temporary directory. import * as NodePath from "node:path"; +import * as FeatureFlags from "@t3tools/shared/FeatureFlags"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -360,7 +361,10 @@ describe("GitHubRest", () => { const media = yield* instance.fetchMedia!({ url: mediaUrl, headers: {} }); expect(media?.status).toBe(401); expect(directRequests).toEqual([mediaUrl]); - }).pipe(Effect.provide(layer), Effect.provideService(HostProcess.Environment, {})); + }).pipe( + Effect.provide(layer.pipe(Layer.provideMerge(FeatureFlags.layerTest()))), + Effect.provideService(HostProcess.Environment, {}), + ); }), ); From 63fa4c892eb89bb4b8fe43b6cc9d02999980d208 Mon Sep 17 00:00:00 2001 From: Navid Nadali Date: Sat, 21 Nov 2026 23:33:37 +0000 Subject: [PATCH 084/324] fix(mcp): a child's async question no longer keeps its parent polling (#40604) Co-authored-by: Julius Marminge --- .../src/mcp/OrchestratorMcpService.test.ts | 22 +++++++++++++++---- apps/server/src/mcp/OrchestratorMcpService.ts | 5 ++++- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index 2dad1fe68ee6d..4a5935d427879 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -617,7 +617,7 @@ describe("OrchestratorMcpService", () => { const childThreadId = ThreadId.make("thread:mcp-next-child"); const taskId = NodeId.make("node:mcp-next-task"); let finished = false; - let pendingRequest = false; + let pendingRequest: "live" | "message" | null = null; const parentProjection = () => ({ thread: { id: parentThreadId }, @@ -652,7 +652,16 @@ describe("OrchestratorMcpService", () => { subagents: [], providerThreads: [], providerTurns: [], - runtimeRequests: pendingRequest ? [{ status: "pending" }] : [], + runtimeRequests: + pendingRequest === null + ? [] + : [ + { + kind: "user_input", + status: "pending", + responseCapability: { type: pendingRequest }, + }, + ], nodes: [], turnItems: [], }) as unknown as OrchestrationV2ThreadProjection; @@ -705,11 +714,16 @@ describe("OrchestratorMcpService", () => { assert.equal(waiting.next, ORCHESTRATOR_MCP_RUNNING_TASK_NEXT); // A child waiting on a question or approval needs an answer, not a wake. - pendingRequest = true; + pendingRequest = "live"; const asking = yield* service.waitForThread(scope, { threadId: childThreadId }); assert.isTrue(asking.timedOut); assert.notProperty(asking, "next"); - pendingRequest = false; + + // A question answered by message does not stop the child. + pendingRequest = "message"; + const working = yield* service.waitForThread(scope, { threadId: childThreadId }); + assert.equal(working.next, ORCHESTRATOR_MCP_RUNNING_TASK_NEXT); + pendingRequest = null; finished = true; const completed = yield* service.taskStatus(scope, taskId); diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index e8046bdd3c9c8..5f0c95a55ffee 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -3734,7 +3734,10 @@ const make = Effect.gen(function* () { .pipe(Effect.mapError(threadManagementFailure))).runtimeRequests : []; const wakesCaller = - ownedTask && !childRequests.some((request) => request.status === "pending"); + ownedTask && + !childRequests.some( + (request) => request.status === "pending" && request.responseCapability.type === "live", + ); return { threadId: input.threadId, runId: result.run?.id ?? null, From 2ea1c51f188bd3ac684e2aa1cfd0d05c9ca43d8c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 16:10:21 -0800 Subject: [PATCH 085/324] fix(acp): a late session update no longer marks a stopped thread active (#40629) --- .../server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts | 2 ++ packages/provider-acp/src/server/adapter.ts | 4 ++++ 2 files changed, 6 insertions(+) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index d79257944c8e9..348c2f38b0190 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -11857,6 +11857,8 @@ describe("AcpAdapterV2", () => { assert.deepInclude(late.providerThread.contextUsage, { usedTokens: 13101 }); // With no run left to receive it, only a session-scoped update reaches the projection. assert.isTrue(late.sessionScoped); + // It is written straight to the projection, so it must not revive the settled turn. + assert.equal(late.providerThread.status, "idle"); }).pipe(Effect.provide(layerTest), Effect.scoped), ); diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index a712d40629e60..e214a51586f4c 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -5792,6 +5792,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const now = yield* DateTime.now; const providerThread: OrchestrationV2ProviderThread = { ...knownProviderThread, + // The settled turn's snapshot is still cached as active; no turn runs now. + ...(context === null && knownProviderThread.status === "active" + ? { status: "idle" as const } + : {}), contextUsage: (yield* Ref.get(contextUsageBySessionId)).get(notification.sessionId) ?? knownProviderThread.contextUsage ?? From 76b421864ba9334991940440ccea979585189604 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 16:10:52 -0800 Subject: [PATCH 086/324] fix(web): Ctrl+click in the composer no longer outlines the whole line (#40628) --- apps/web/package.json | 1 + ...ComposerPromptEditorTiptap.input.browser.test.tsx | 12 ++++++++++++ .../src/components/ComposerPromptEditorTiptap.tsx | 4 ++++ pnpm-lock.yaml | 3 +++ 4 files changed, 20 insertions(+) diff --git a/apps/web/package.json b/apps/web/package.json index 9e6f0f475b3d0..21ac8caba0b1e 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -51,6 +51,7 @@ "@tiptap/extension-horizontal-rule": "^3.31.3", "@tiptap/extension-italic": "^3.31.3", "@tiptap/extension-list": "^3.31.3", + "@tiptap/extension-paragraph": "^3.31.3", "@tiptap/extension-strike": "^3.31.3", "@tiptap/extension-task-item": "^3.31.3", "@tiptap/extension-task-list": "^3.31.3", diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx index ca1db10dbdc10..d69c06751b527 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx @@ -677,6 +677,18 @@ it("reopens a long draft scrolled to its caret without taking focus", async () = expect(caret.bottom).toBeLessThanOrEqual(scroller.getBoundingClientRect().bottom - 48 + 1); }); +it("does not outline the line under a click made with the node-select modifier held", async () => { + await using screen = await mountEditor("ship it"); + const { editor } = screen; + const paragraph = editor.view.dom.querySelector("p")!; + const mod = isMacPlatform(navigator.platform) ? "Meta" : "Control"; + await userEvent.keyboard(`{${mod}>}`); + await userEvent.click(paragraph); + await userEvent.keyboard(`{/${mod}}`); + await vi.waitFor(() => expect(document.activeElement).toBe(editor.view.dom)); + expect(getComputedStyle(paragraph).outlineStyle).toBe("none"); +}); + describe("Markdown markers around styled text", () => { it.each([ { keys: "{Backspace}", expected: "**** after" }, diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index 9b758ee8b6777..ab43b514ed3d9 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -14,6 +14,7 @@ import { type TiptapEditorHTMLElement, } from "@tiptap/core"; import { ReactNodeViewRenderer, NodeViewWrapper, type NodeViewProps } from "@tiptap/react"; +import { Paragraph } from "@tiptap/extension-paragraph"; import StarterKit from "@tiptap/starter-kit"; import { useGT } from "gt-react"; import { newlineInCode, splitBlockKeepMarks } from "@tiptap/pm/commands"; @@ -876,7 +877,10 @@ function createComposerExtensions(richText: boolean) { italic: false, bold: false, strike: false, + paragraph: false, }), + // Ctrl/Cmd+click would node-select and outline the whole line (Wispr Flow holds Ctrl to dictate). + Paragraph.extend({ selectable: false }), ComposerUndoGroupingExtension, ComposerTextDirectionExtension, ComposerMentionExtension, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 62cbee3b4d8f8..635da4aed6a90 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1158,6 +1158,9 @@ importers: '@tiptap/extension-list': specifier: ^3.31.3 version: 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3) + '@tiptap/extension-paragraph': + specifier: ^3.31.3 + version: 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3)) '@tiptap/extension-strike': specifier: ^3.31.3 version: 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3)) From b5a0352bfd1ba193f0e0795b1501082bcb35c65f Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 16:12:04 -0800 Subject: [PATCH 087/324] fix(server): log when a settle script is skipped because its worktree is gone (#40627) Co-authored-by: Kevin Flores <101906409+kevincommits@users.noreply.github.com> --- .../ThreadSettlementService.test.ts | 42 +++++++++++++++++-- .../ThreadSettlementService.ts | 18 +++++++- 2 files changed, 56 insertions(+), 4 deletions(-) diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts index 0fee4a50ce34b..07bb2d64d80a5 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts @@ -28,6 +28,8 @@ import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; +import * as Logger from "effect/Logger"; +import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as PlatformError from "effect/PlatformError"; import * as PubSub from "effect/PubSub"; @@ -687,6 +689,12 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options: const layerDependencies = Layer.mergeAll( Layer.mock(ProjectStore.ProjectStoreV2)({ listShells: () => Ref.get(snapshots).pipe(Effect.map((snapshot) => snapshot.projects)), + getShell: (projectId) => + Ref.get(snapshots).pipe( + Effect.map((snapshot) => + Option.fromNullishOr(snapshot.projects.find((project) => project.id === projectId)), + ), + ), }), Layer.mock(ProjectionStore.ProjectionStoreV2)({ getThreadsWithPullRequests: (_threadId, readOptions) => @@ -2248,12 +2256,29 @@ describe("ThreadSettlementServiceV2 terminals", () => { it.effect("runs the settle script in the thread's own worktree", () => Effect.gen(function* () { + const warnings: string[] = []; + const logger = Logger.make(({ logLevel, message }) => { + if (logLevel === "Warn") warnings.push(JSON.stringify(message)); + }); const shared = appThread("shared-checkout-thread", "settled"); const missing = appThread("removed-worktree-thread", "settled", "/worktrees/removed"); const worktree = appThread("worktree-thread", "settled", "/worktrees/thread"); + const scriptless = makeProject(ProjectId.make("scriptless-project")); + const missingScriptless = { + ...appThread("removed-worktree-scriptless-thread", "settled", "/worktrees/scriptless"), + projectId: scriptless.id, + }; + const teardown = { + id: "teardown", + name: "Teardown", + command: "docker compose down", + icon: "configure", + runOnWorktreeCreate: false, + runOnSettle: true, + } as const; const fixture = yield* makeHarness({ - snapshot: makeSnapshot([]), - currentThreads: [shared, missing, worktree], + snapshot: makeSnapshot([], [{ ...makeProject(), scripts: [teardown] }, scriptless]), + currentThreads: [shared, missing, missingScriptless, worktree], existingWorktreePaths: ["/worktrees/thread"], }); @@ -2262,12 +2287,23 @@ describe("ThreadSettlementServiceV2 terminals", () => { yield* startHarness(service, fixture.activation, fixture.snapshotReads); yield* fixture.publishEvent(settledEvent(shared)); yield* fixture.publishEvent(settledEvent(missing)); + yield* fixture.publishEvent(settledEvent(missingScriptless)); yield* fixture.publishEvent(settledEvent(worktree)); const run = yield* Queue.take(fixture.scriptRuns); assert.strictEqual(run.threadId, worktree.id); assert.strictEqual(run.worktreePath, "/worktrees/thread"); assert.strictEqual(run.trigger, "settle"); - }).pipe(Effect.provide(fixture.layer)); + // A removed worktree skips a configured settle script; the log is its only trace. + assert.strictEqual(warnings.length, 1); + assert.include(warnings[0], missing.id); + assert.include(warnings[0], "/worktrees/removed"); + }).pipe( + Effect.provide( + fixture.layer.pipe( + Layer.provideMerge(Logger.layer([logger], { mergeWithExisting: false })), + ), + ), + ); }), ); diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.ts index 38616d48846de..ef0894f3ecbeb 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.ts @@ -3,6 +3,7 @@ import { isPullRequestWatchTask, turnItemUpdateCanEndBackgroundWork, } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; +import { resolveProjectScripts, settleProjectScript } from "@t3tools/shared/projectScripts"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests"; import { @@ -20,6 +21,7 @@ import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as FiberSet from "effect/FiberSet"; import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Schedule from "effect/Schedule"; import * as Semaphore from "effect/Semaphore"; @@ -758,7 +760,21 @@ export const make = Effect.gen(function* () { if (settled.deletedAt !== null || settled.settledOverride !== "settled") return; yield* terminals.closeOnSettle({ threadId }); const worktreePath = settled.worktreePath; - if (worktreePath === null || !(yield* fileSystem.exists(worktreePath))) return; + if (worktreePath === null) return; + if (!(yield* fileSystem.exists(worktreePath))) { + // A settle script that tears something down would otherwise be skipped with no trace. + const project = Option.getOrUndefined(yield* projectStore.getShell(settled.projectId)); + if ( + project !== undefined && + settleProjectScript(resolveProjectScripts(yield* settingsService.getSettings, project)) + ) { + yield* Effect.logWarning( + "settle script skipped: the thread's worktree no longer exists", + { threadId, worktreePath }, + ); + } + return; + } // Recheck after closing and worktree I/O; only live, settled threads may run scripts. const thread = yield* projections.getThread(threadId); if (thread.deletedAt !== null || thread.settledOverride !== "settled") return; From a9447cedbdfe8690303cc29aa298e801d753abfb Mon Sep 17 00:00:00 2001 From: Matthew Feroz <136640686+MatthewFeroz@users.noreply.github.com> Date: Sat, 21 Nov 2026 19:21:48 -0500 Subject: [PATCH 088/324] fix(web): Cite button appears as fast after a double-click as after a drag (#33221) Co-authored-by: shivam <91240327+shivamhwp@users.noreply.github.com> --- .../chat/AssistantSelectionToolbar.tsx | 1 + .../src/lib/selectionActions.browser.test.ts | 48 +++++++++++++++++++ apps/web/src/lib/selectionActions.ts | 12 ++++- 3 files changed, 59 insertions(+), 2 deletions(-) create mode 100644 apps/web/src/lib/selectionActions.browser.test.ts diff --git a/apps/web/src/components/chat/AssistantSelectionToolbar.tsx b/apps/web/src/components/chat/AssistantSelectionToolbar.tsx index 0772a864c021e..afb51240b625e 100644 --- a/apps/web/src/components/chat/AssistantSelectionToolbar.tsx +++ b/apps/web/src/components/chat/AssistantSelectionToolbar.tsx @@ -143,6 +143,7 @@ export function AssistantSelectionToolbar({ element: viewport, getActionElement: () => toolbarRef.current, restoreAfterScroll: true, + immediateMultiClick: true, onSelection: update, onDismiss: clear, }); diff --git a/apps/web/src/lib/selectionActions.browser.test.ts b/apps/web/src/lib/selectionActions.browser.test.ts new file mode 100644 index 0000000000000..de5b70908fbb6 --- /dev/null +++ b/apps/web/src/lib/selectionActions.browser.test.ts @@ -0,0 +1,48 @@ +import { describe, expect, it, vi } from "vite-plus/test"; + +import { fakeTimers } from "../../test/render"; +import { observeSelectionActions, SELECTION_MULTI_CLICK_INTERVAL_MS } from "./selectionActions"; + +describe("observeSelectionActions", () => { + it.each([ + { immediateMultiClick: false, nextFrame: [], afterInterval: [[{ x: 40, y: 12 }]] }, + { immediateMultiClick: true, nextFrame: [[null]], afterInterval: [[null]] }, + ])( + "double-click with immediateMultiClick=$immediateMultiClick", + ({ immediateMultiClick, nextFrame, afterInterval }) => { + using stack = new DisposableStack(); + const element = stack.adopt(document.body.appendChild(document.createElement("div")), (e) => + e.remove(), + ); + stack.use(fakeTimers()); + const onSelection = vi.fn(); + const actions = observeSelectionActions({ + element, + immediateMultiClick, + onSelection, + onDismiss: () => {}, + }); + stack.defer(() => actions.dispose()); + + element.dispatchEvent( + new PointerEvent("pointerdown", { bubbles: true, isPrimary: true, button: 0 }), + ); + element.dispatchEvent( + new MouseEvent("mouseup", { + bubbles: true, + button: 0, + detail: 2, + clientX: 40, + clientY: 12, + }), + ); + + vi.advanceTimersByTime(20); + expect(onSelection.mock.calls).toEqual(nextFrame); + vi.advanceTimersByTime(SELECTION_MULTI_CLICK_INTERVAL_MS - 21); + expect(onSelection.mock.calls).toEqual(nextFrame); + vi.advanceTimersByTime(50); + expect(onSelection.mock.calls).toEqual(afterInterval); + }, + ); +}); diff --git a/apps/web/src/lib/selectionActions.ts b/apps/web/src/lib/selectionActions.ts index 9303602097543..2c219000290c3 100644 --- a/apps/web/src/lib/selectionActions.ts +++ b/apps/web/src/lib/selectionActions.ts @@ -47,12 +47,19 @@ export function observeSelectionActions({ element, getActionElement, restoreAfterScroll = false, + immediateMultiClick = false, onSelection, onDismiss, }: { element: HTMLElement; getActionElement?: () => HTMLElement | null; restoreAfterScroll?: boolean; + /** + * Show double- and triple-click selections at once instead of waiting out the multi-click + * interval. Their pointer is withheld so the action anchors below the selection, clear of + * the spot where a following click lands. + */ + immediateMultiClick?: boolean; onSelection: (pointer: SelectionActionPoint | null) => void; onDismiss: (reason: "interaction" | "cancel") => void; }) { @@ -132,8 +139,9 @@ export function observeSelectionActions({ pointerDown = false; if (!gestureActive) return; gestureActive = false; - pointer = { x: event.clientX, y: event.clientY }; - schedule(event.detail >= 2 ? SELECTION_MULTI_CLICK_INTERVAL_MS : 0); + const multiClick = event.detail >= 2; + pointer = multiClick && immediateMultiClick ? null : { x: event.clientX, y: event.clientY }; + schedule(multiClick && !immediateMultiClick ? SELECTION_MULTI_CLICK_INTERVAL_MS : 0); }; const onKeyDown = (event: KeyboardEvent) => { if (isActionTarget(event.target) && event.key !== "Escape") return; From 67bf1e693a387b3bbbe5c305174617ebc6387974 Mon Sep 17 00:00:00 2001 From: RibatTRW Date: Sun, 22 Nov 2026 08:33:40 +0800 Subject: [PATCH 089/324] fix(desktop): AppImage t3 serve stops cleanly under systemd (#40624) --- apps/desktop/src/app/DesktopCliShim.test.ts | 27 ++++++++++++++------- apps/desktop/src/app/DesktopCliShim.ts | 27 ++++++++++++++++++--- 2 files changed, 42 insertions(+), 12 deletions(-) diff --git a/apps/desktop/src/app/DesktopCliShim.test.ts b/apps/desktop/src/app/DesktopCliShim.test.ts index 3e8b4967dfde5..929148fdbb32f 100644 --- a/apps/desktop/src/app/DesktopCliShim.test.ts +++ b/apps/desktop/src/app/DesktopCliShim.test.ts @@ -69,7 +69,7 @@ const fakeAppImage = (canMount = true, app = REPORTER) => { // Stays up after a signal until the test lets it finish, like a server shutting down. const SLOW_SERVER = [ "#!/bin/sh", - "trap 'echo stopping >&3; read go; echo stopped >&3; exit 0' TERM HUP", + "trap 'echo stopping >&3; read go; echo \"stopped $go\" >&3; exit 7' TERM HUP", "echo ready", "while :; do sleep 0.05; done", "", @@ -101,9 +101,16 @@ const lines = (stream: NodeJS.ReadableStream) => { }; describe("renderCliShim", () => { - it.skipIf(!hasSetsid).each(["SIGTERM", "SIGHUP"] as const)( - "keeps the AppImage mounted until the server exits after %s to the process group", - async (signal) => { + // Ctrl-C, an SSH hangup, or a supervisor signals the process group. systemd's default KillMode + // also signals the mounter, and KillMode=mixed signals only the launcher. + it.skipIf(!hasSetsid).each([ + ["SIGTERM", "the process group"], + ["SIGHUP", "the process group"], + ["SIGTERM", "every process"], + ["SIGTERM", "the launcher"], + ] as const)( + "keeps the AppImage mounted until the server exits after %s to %s", + async (signal, target) => { const { root, shim } = fakeAppImage(true, SLOW_SERVER); const child = NodeChildProcess.spawn(shim, [], { detached: true, @@ -114,12 +121,12 @@ describe("renderCliShim", () => { try { const stdout = lines(child.stdout!); const events = lines(child.stdio[3] as NodeJS.ReadableStream); - const exited = new Promise((resolve) => child.on("close", resolve)); + const exited = new Promise((resolve) => child.on("close", resolve)); await stdout.until((line) => line === "ready"); mounter = Number(NodeFS.readFileSync(NodePath.join(root, "mounter.pid"), "utf8")); - // Ctrl-C in a terminal, a closed SSH session, or a service manager signals the whole group. - process.kill(-child.pid!, signal); + process.kill(target === "the launcher" ? child.pid! : -child.pid!, signal); + if (target === "every process") process.kill(mounter, signal); // The shell runs pending traps in ascending signal number, and WINCH outnumbers TERM and // HUP, so a mounter that also got the group signal unmounts before it answers this probe. process.kill(mounter, "SIGWINCH"); @@ -128,8 +135,8 @@ describe("renderCliShim", () => { await events.until((line) => line === "stopping"); child.stdin!.end("go\n"); - await exited; - expect(events.seen.slice(-2)).toEqual(["stopped", "unmounted"]); + expect(await exited).toBe(7); + expect(events.seen.slice(-2)).toEqual(["stopped go", "unmounted"]); } finally { for (const pid of [-child.pid!, mounter]) { if (pid === undefined) continue; @@ -156,6 +163,8 @@ describe("renderCliShim", () => { const result = run(shim, ["--version"]); expect(result.status).toBe(3); expect(result.stdout).toContain(`appimage=${appImage}`); + const closedStdin = NodeChildProcess.spawnSync("sh", ["-c", '"$0" --version <&-', shim]); + expect(closedStdin.status).toBe(3); }); it("keeps the install's T3 home under sudo, unless one is set", () => { diff --git a/apps/desktop/src/app/DesktopCliShim.ts b/apps/desktop/src/app/DesktopCliShim.ts index 217f3b327dc9e..0f7e605da6b36 100644 --- a/apps/desktop/src/app/DesktopCliShim.ts +++ b/apps/desktop/src/app/DesktopCliShim.ts @@ -91,11 +91,15 @@ export const renderCliShim = (input: { // Extract-and-run would make the runtime start the app instead of mounting it. "unset APPIMAGE_EXTRACT_AND_RUN", // Its own session keeps a group signal (Ctrl-C, SSH hangup) from unmounting it under the - // running server; the traps unmount it after. Without setsid the extract fallback runs. + // running server, and ignoring TERM survives a stop sent to every process (systemd's default). + // Without setsid the extract fallback runs. "work=$(mktemp -d) || exit 1", + "trap '' TERM", 'setsid "$app" --appimage-mount >"$work/mount" 2>/dev/null &', "mounter=$!", - `trap 'kill "$mounter" 2>/dev/null; rm -rf "$work"' EXIT`, + // It unmounts itself on TERM, which it now ignores, so the trap unmounts it. Lazily, like the + // runtime: the server's own children may still be exiting. + `trap '[ -z "$mount" ] || fusermount3 -uz "$mount" 2>/dev/null || fusermount -uz "$mount" 2>/dev/null; kill -HUP "$mounter" 2>/dev/null; rm -rf "$work"' EXIT`, "trap 'exit 130' INT TERM HUP", "mount=", 'while kill -0 "$mounter" 2>/dev/null; do', @@ -111,7 +115,24 @@ export const renderCliShim = (input: { "fi", // The runtime sets this when it launches the app; the CLI skips its path-keyed compile cache on it. 'export APPIMAGE="$app"', - run("$mount"), + // The shell must outlive the CLI to unmount, so it forwards TERM and HUP; the terminal sends + // Ctrl-C to the CLI directly. A background child would read /dev/null, so pass stdin on fd 9. + // With stdin closed, `exec 9<&0` would end the shell; `command` makes it a normal error. + "{ command exec 9<&0; } 2>/dev/null || exec 9/dev/null' TERM`, + `trap 'kill -HUP "$cli" 2>/dev/null' HUP`, + "trap '' INT", + "status=0", + 'wait "$cli" || status=$?', + // A trapped signal interrupts wait; wait again for the CLI's own exit status. + 'while kill -0 "$cli" 2>/dev/null; do', + " status=0", + ' wait "$cli" || status=$?', + "done", + 'exit "$status"', "", ].join("\n"); }; From 047fb5b1627c67d3f7a9d7e70c10af2536551b7e Mon Sep 17 00:00:00 2001 From: Alex Southwell Date: Sun, 22 Nov 2026 11:36:35 +1100 Subject: [PATCH 090/324] fix(relay): iOS notifications no longer cut an emoji in half at the title limit (#29830) Co-authored-by: Claude Opus 5.5 Co-authored-by: shivam <91240327+shivamhwp@users.noreply.github.com> --- infra/relay/src/agentActivity/ApnsClient.test.ts | 4 +++- infra/relay/src/agentActivity/agentActivityPayloads.ts | 7 ++++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/infra/relay/src/agentActivity/ApnsClient.test.ts b/infra/relay/src/agentActivity/ApnsClient.test.ts index 81e76b0391aae..f06c751982710 100644 --- a/infra/relay/src/agentActivity/ApnsClient.test.ts +++ b/infra/relay/src/agentActivity/ApnsClient.test.ts @@ -151,7 +151,7 @@ describe("ApnsClient", () => { const environmentId = "é".repeat(191); const threadId = "t".repeat(512); const notification = sanitizeApnsNotificationPayload({ - title: "界".repeat(120), + title: "😀".repeat(120), body: "界".repeat(120), environmentId, threadId, @@ -159,6 +159,8 @@ describe("ApnsClient", () => { }); const request = apns.makePushNotificationRequest({ token: "push-token", notification }); + expect(notification.title).toBe(`${"😀".repeat(58)}...`); + expect( new TextEncoder().encode(JSON.stringify(request.payload)).byteLength, ).toBeLessThanOrEqual(4096); diff --git a/infra/relay/src/agentActivity/agentActivityPayloads.ts b/infra/relay/src/agentActivity/agentActivityPayloads.ts index 4195c81171803..2dd8be5870b9b 100644 --- a/infra/relay/src/agentActivity/agentActivityPayloads.ts +++ b/infra/relay/src/agentActivity/agentActivityPayloads.ts @@ -52,7 +52,12 @@ export function truncateText(value: string, maxLength: number): string { if (trimmed.length <= maxLength) { return trimmed; } - return trimmed.slice(0, maxLength - 3).trimEnd() + "..."; + return ( + trimmed + .slice(0, maxLength - 3) + .replace(/[\uD800-\uDBFF]$/, "") + .trimEnd() + "..." + ); } function sanitizeDeepLink(value: string): string { From 5028eb10a4851ba3943c3bd2291137598727d286 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 17:06:34 -0800 Subject: [PATCH 091/324] perf(shared): Windows command lookups reuse PATH listings across requests (#40634) Co-authored-by: Mostafa El Ayoubi <20224923+MostafaElAyoubi@users.noreply.github.com> --- apps/desktop/src/ipc/methods/window.test.ts | 56 ++++----- apps/desktop/src/ipc/methods/window.ts | 4 +- apps/server/src/process/externalLauncher.ts | 8 +- packages/shared/src/shell.test.ts | 93 +++++++++++++-- packages/shared/src/shell.ts | 124 +++++++++++++++++--- 5 files changed, 218 insertions(+), 67 deletions(-) diff --git a/apps/desktop/src/ipc/methods/window.test.ts b/apps/desktop/src/ipc/methods/window.test.ts index b256025eff844..9c50501a1bdfd 100644 --- a/apps/desktop/src/ipc/methods/window.test.ts +++ b/apps/desktop/src/ipc/methods/window.test.ts @@ -4,6 +4,7 @@ import type { ManagedPolicyLimits } from "@t3tools/contracts"; import { EDITORS, REMOTE_CAPABLE_EDITOR_IDS } from "@t3tools/contracts"; import { resolveEditorCommand } from "@t3tools/shared/editor"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { makePathDirectoryListings, PathDirectoryListings } from "@t3tools/shared/shell"; import { ManagedPolicyFileError } from "@t3tools/shared/managedPolicyFile"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; @@ -11,6 +12,7 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; import { vi } from "vite-plus/test"; import type * as Electron from "electron"; @@ -550,6 +552,7 @@ it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( ); describe("probeRemoteEditors PATH scan", () => { + const FIXTURE_MTIME = 1_767_225_600; const platform = HostProcess.Platform.defaultValue(); const launcherName = (command: string) => (platform === "win32" ? `${command}.cmd` : command); @@ -570,6 +573,9 @@ describe("probeRemoteEditors PATH scan", () => { yield* fs.writeFileString(file, "#!/bin/sh\n"); if (platform !== "win32") yield* fs.chmod(file, 0o755); } + // A listing of a directory changed moments ago is not kept, so age them past that window. + for (const dir of dirs) yield* fs.utimes(dir, FIXTURE_MTIME, FIXTURE_MTIME); + yield* TestClock.setTime((FIXTURE_MTIME + 60) * 1000); return { root, env: { @@ -581,19 +587,15 @@ describe("probeRemoteEditors PATH scan", () => { }; }); - const countingFileSystem = (counter: { stat: number; reads: Map }) => + const countingFileSystem = (reads: Map) => Layer.effect( FileSystem.FileSystem, Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; return FileSystem.FileSystem.of({ ...fs, - stat: (target) => { - counter.stat += 1; - return fs.stat(target); - }, readDirectory: (target, options) => { - counter.reads.set(target, (counter.reads.get(target) ?? 0) + 1); + reads.set(target, (reads.get(target) ?? 0) + 1); return fs.readDirectory(target, options); }, }); @@ -612,44 +614,38 @@ describe("probeRemoteEditors PATH scan", () => { return available; }); - it.effect("reads each PATH directory once instead of stat-ing every candidate per editor", () => + it.effect("finds the editors a serial scan finds, listing each PATH directory at most once", () => Effect.gen(function* () { const { env: baseEnv } = yield* makeFakePath(); const delimiter = platform === "win32" ? ";" : ":"; - const uncachedCounter = { stat: 0, reads: new Map() }; - const cachedCounter = { stat: 0, reads: new Map() }; - const uncachedEnv = { ...baseEnv, PATH: `${baseEnv.PATH}${delimiter}${baseEnv.HOME}x1` }; - const cachedEnv = { ...baseEnv, PATH: `${baseEnv.PATH}${delimiter}${baseEnv.HOME}x2` }; - const uncached = yield* serialReference(uncachedEnv).pipe( - Effect.provide(countingFileSystem(uncachedCounter)), + const reads = new Map(); + // Distinct PATH values keep one scan from answering the other out of the resolution cache. + const serialEnv = { ...baseEnv, PATH: `${baseEnv.PATH}${delimiter}${baseEnv.HOME}x1` }; + const probeEnv = { ...baseEnv, PATH: `${baseEnv.PATH}${delimiter}${baseEnv.HOME}x2` }; + const serial = yield* serialReference(serialEnv).pipe( + Effect.provideServiceEffect(PathDirectoryListings, makePathDirectoryListings), ); - const cached = yield* probeRemoteEditors + const probed = yield* probeRemoteEditors .handler(undefined) .pipe( - Effect.provideService(HostProcess.Environment, cachedEnv), + Effect.provideService(HostProcess.Environment, probeEnv), Effect.provideService(HostProcess.Platform, platform), - Effect.provide(countingFileSystem(cachedCounter)), + Effect.provide(countingFileSystem(reads)), + Effect.provideServiceEffect(PathDirectoryListings, makePathDirectoryListings), ); // The host can add editors from app folders the fixture can't redirect (e.g. /Applications). const fixtureEditors = ["cursor", "vscode", "zed", "webstorm"]; assert.deepStrictEqual( - uncached.filter((id) => fixtureEditors.includes(id)), + serial.filter((id) => fixtureEditors.includes(id)), fixtureEditors, ); - assert.deepStrictEqual(cached, uncached); - assert.isAbove(uncachedCounter.stat, 0); - // On every platform the probe lists each PATH directory at most once. Only PATH entries count: - // resolveEditorCommand also reads app folders such as /Applications on macOS. - const pathReads = cachedEnv.PATH.split(delimiter) + assert.deepStrictEqual(probed, serial); + // Only PATH entries count: resolveEditorCommand also reads app folders such as /Applications + // on macOS. PATH directories are listed on Windows only, once even for concurrent probes. + const pathReads = probeEnv.PATH.split(delimiter) .filter((entry) => entry.length > 0) - .map((entry) => cachedCounter.reads.get(entry) ?? 0); - assert.isAbove(Math.max(...pathReads), 0); - assert.isAtMost(Math.max(...pathReads), 1); - // Without the listings, Windows stats every PATH entry x PATHEXT candidate for each editor; - // elsewhere there is no PATHEXT, so the stat count is about the same either way. - if (platform === "win32") { - assert.isBelow(cachedCounter.stat, uncachedCounter.stat / 2); - } + .map((entry) => reads.get(entry) ?? 0); + assert.strictEqual(Math.max(...pathReads), platform === "win32" ? 1 : 0); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); }); diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.ts index abf4ec929a7b7..c6ad0bef18c81 100644 --- a/apps/desktop/src/ipc/methods/window.ts +++ b/apps/desktop/src/ipc/methods/window.ts @@ -17,7 +17,6 @@ import { } from "@t3tools/contracts"; import { PROJECT_FAVICON_EXTENSIONS } from "@t3tools/shared/projectFavicon"; import { resolveEditorCommand } from "@t3tools/shared/editor"; -import { withPathDirectoryListings } from "@t3tools/shared/shell"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { isRelayTracingEnabled } from "@t3tools/shared/otelEnvironment"; import * as FileSystem from "effect/FileSystem"; @@ -446,7 +445,6 @@ export const probeRemoteEditors = DesktopIpc.makeIpcMethod({ result: Schema.Array(EditorId), handler: Effect.fn("desktop.ipc.window.probeRemoteEditors")(function* () { const env = yield* HostProcess.Environment; - // Shared listings stop each editor re-stating every PATH entry x PATHEXT candidate on Windows. const resolved = yield* Effect.forEach( REMOTE_CAPABLE_EDITOR_IDS, (editorId) => { @@ -456,7 +454,7 @@ export const probeRemoteEditors = DesktopIpc.makeIpcMethod({ : Effect.succeed(false); }, { concurrency: REMOTE_EDITOR_PROBE_CONCURRENCY }, - ).pipe(withPathDirectoryListings); + ); return REMOTE_CAPABLE_EDITOR_IDS.filter((_, index) => resolved[index]); }), }); diff --git a/apps/server/src/process/externalLauncher.ts b/apps/server/src/process/externalLauncher.ts index caa6664a1ba80..4c0d006332ff7 100644 --- a/apps/server/src/process/externalLauncher.ts +++ b/apps/server/src/process/externalLauncher.ts @@ -15,11 +15,7 @@ import { } from "@t3tools/contracts"; import { resolveEditorCommand } from "@t3tools/shared/editor"; import * as HostProcess from "@t3tools/shared/HostProcess"; -import { - isCommandAvailable, - resolveSpawnCommand, - withPathDirectoryListings, -} from "@t3tools/shared/shell"; +import { isCommandAvailable, resolveSpawnCommand } from "@t3tools/shared/shell"; import * as Config from "effect/Config"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; @@ -503,7 +499,7 @@ const readEditorEnv = Effect.fn("externalLauncher.readEditorEnv")(function* () { const resolveAvailableEditors = Effect.fn("externalLauncher.resolveAvailableEditors")(function* () { const platform = yield* HostProcess.Platform; const env = yield* readEditorEnv(); - return yield* buildAvailableEditors(platform, env).pipe(withPathDirectoryListings); + return yield* buildAvailableEditors(platform, env); }); const resolveFileManagerRevealKind = Effect.fn("externalLauncher.resolveFileManagerRevealKind")( diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts index d9950edc60cfb..08731a41c19ef 100644 --- a/packages/shared/src/shell.test.ts +++ b/packages/shared/src/shell.test.ts @@ -22,6 +22,8 @@ import { pathSetupCommand, CommandAvailability, CommandResolutionCache, + makePathDirectoryListings, + PathDirectoryListings, type CommandAvailabilityChecker, gitForWindowsBash, isCommandAvailable, @@ -39,7 +41,6 @@ import { windowsEnvironmentValueCommand, SpawnExecutableResolution, WindowsShellEnvironment, - withPathDirectoryListings, type WindowsShellEnvironmentReader, XcodeGitLocation, } from "./shell.ts"; @@ -591,7 +592,8 @@ effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => { stat: (filePath) => Effect.sync(() => { probed.push(filePath); - return { type: "Directory" } as FileSystem.File.Info; + // No mtime, so no listing: every candidate is probed directly. + return { type: "Directory", mtime: Option.none() } as FileSystem.File.Info; }), }), ), @@ -609,7 +611,7 @@ effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => { }); // Windows PATH directories can be case-sensitive; preserve both spellings. - expect(probed).toHaveLength(8); + expect(probed.filter((file) => file.includes("definitely-not-installed"))).toHaveLength(8); }), ); @@ -635,7 +637,7 @@ effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => { ...fs, stat: (filePath) => fs.stat( - filePath === executable || filePath === decoy + [cwd, executable, decoy].includes(filePath) ? filePath : path.join(cwd, "missing"), ), @@ -646,38 +648,111 @@ effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => { }), ); - it.effect("probes only listed PATH names and relists a directory that changes", () => + // Seconds; the tests below run their clock a minute later, past the window in which a listing is not kept. + const AGED_MTIME = 4_102_444_800; + const afterAgedMtime = TestClock.setTime((AGED_MTIME + 60) * 1000); + + it.effect("reuses PATH listings across lookups until a directory changes", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const first = yield* fs.makeTempDirectoryScoped(); const second = yield* fs.makeTempDirectoryScoped(); yield* fs.writeFileString(path.join(first, "cursor.CMD"), ""); + yield* fs.writeFileString(path.join(first, "MyToolLongName.cmd"), ""); yield* fs.writeFileString(path.join(second, "cursor.EXE"), ""); + yield* fs.utimes(first, AGED_MTIME, AGED_MTIME); + yield* fs.utimes(second, AGED_MTIME, AGED_MTIME); + yield* afterAgedMtime; const env = { PATH: `${first};${second}`, PATHEXT: ".EXE;.CMD" }; + // Windows resolves an 8.3 alias that a directory listing never names. + const alias = path.join(first, "MYTOOL~1.CMD"); const probed: Array = []; + const listed: Array = []; yield* Effect.gen(function* () { expect(yield* resolveCommandPath("cursor", { env })).toBe(path.join(first, "cursor.CMD")); expect(yield* isCommandAvailable("absent", { env })).toBe(false); + expect(yield* isCommandAvailable("also-absent", { env })).toBe(false); + expect(yield* resolveCommandPath("MYTOOL~1", { env })).toBe(alias); + expect(listed).toEqual([first, second]); yield* fs.writeFileString(path.join(second, "late.EXE"), ""); - yield* fs.utimes(second, 4_102_444_800, 4_102_444_800); + yield* fs.utimes(second, AGED_MTIME + 30, AGED_MTIME + 30); expect(yield* resolveCommandPath("late", { env })).toBe(path.join(second, "late.EXE")); + expect(listed).toEqual([first, second, second]); }).pipe( - withPathDirectoryListings, Effect.provideService(FileSystem.FileSystem, { ...fs, stat: (file) => { if (file !== first && file !== second) probed.push(file); - return fs.stat(file); + return fs.stat(file === alias ? path.join(first, "MyToolLongName.cmd") : file); + }, + readDirectory: (directory, options) => { + listed.push(directory); + return fs.readDirectory(directory, options); + }, + }), + ); + expect(probed).toEqual([ + path.join(first, "cursor.CMD"), + path.join(first, "MYTOOL~1.EXE"), + path.join(first, "MYTOOL~1.exe"), + alias, + path.join(second, "late.EXE"), + ]); + }).pipe( + Effect.provideService(HostProcess.Platform, "win32"), + Effect.provideService(CommandResolutionCache, new Map()), + Effect.provideServiceEffect(PathDirectoryListings, makePathDirectoryListings), + ), + ); + + it.effect("does not keep the listing of a PATH directory that changed moments ago", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const directory = yield* fs.makeTempDirectoryScoped(); + yield* fs.utimes(directory, AGED_MTIME + 59, AGED_MTIME + 59); + yield* afterAgedMtime; + const env = { PATH: directory, PATHEXT: ".CMD" }; + let listings = 0; + yield* Effect.gen(function* () { + expect(yield* isCommandAvailable("absent", { env })).toBe(false); + expect(yield* isCommandAvailable("also-absent", { env })).toBe(false); + }).pipe( + Effect.provideService(FileSystem.FileSystem, { + ...fs, + readDirectory: (target, options) => { + listings += 1; + return fs.readDirectory(target, options); }, }), ); - expect(probed).toEqual([path.join(first, "cursor.CMD"), path.join(second, "late.EXE")]); + expect(listings).toBe(2); }).pipe( Effect.provideService(HostProcess.Platform, "win32"), Effect.provideService(CommandResolutionCache, new Map()), + Effect.provideServiceEffect(PathDirectoryListings, makePathDirectoryListings), ), ); + + // A POSIX directory joined with win32 separators names nothing, so this needs a Windows host. + it.effect.skipIf(HostProcess.Platform.defaultValue() !== "win32")( + "relists a changed PATH directory in the synchronous spawn resolver", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fs.makeTempDirectoryScoped(); + yield* fs.writeFileString(path.join(directory, "cursor.CMD"), ""); + yield* fs.utimes(directory, 946_684_800, 946_684_800); + const env = { PATH: directory, PATHEXT: ".EXE;.CMD" }; + const resolveExecutable = yield* SpawnExecutableResolution; + expect(resolveExecutable("cursor", "win32", env)).toBe(path.join(directory, "cursor.CMD")); + expect(resolveExecutable("late", "win32", env)).toBeUndefined(); + yield* fs.writeFileString(path.join(directory, "late.EXE"), ""); + yield* fs.utimes(directory, 946_684_830, 946_684_830); + expect(resolveExecutable("late", "win32", env)).toBe(path.join(directory, "late.EXE")); + }), + ); }); describe("runsGitWithoutConsole", () => { diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.ts index 8ccb466775c1f..ffcc1110fe381 100644 --- a/packages/shared/src/shell.ts +++ b/packages/shared/src/shell.ts @@ -7,6 +7,7 @@ import * as Cache from "effect/Cache"; import * as Clock from "effect/Clock"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as FileSystem from "effect/FileSystem"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; @@ -108,7 +109,12 @@ function resolveSpawnExecutableWithNode( for (const pathEntry of (readEnvPath(env) ?? "").split(pathDelimiterForPlatform(platform))) { const normalizedPathEntry = normalizePathEntry(pathEntry, platform); if (normalizedPathEntry.length === 0) continue; + const names = + platform === "win32" + ? listPathDirectorySync(normalizedPathEntry, path.isAbsolute) + : undefined; for (const candidate of candidates) { + if (isAbsentFromListing(names, candidate)) continue; const candidatePath = path.join(normalizedPathEntry, candidate); if (isExecutable(candidatePath)) return candidatePath; } @@ -578,7 +584,38 @@ export const CommandResolutionCache = Context.Reference | undefined; + readonly reusable: boolean; +} + +const PATH_DIRECTORY_LISTINGS_MAX_ENTRIES = 1024; +// A directory changed within a coarse filesystem's timestamp step (FAT: 2 s) can change again +// without moving its mtime, so its listing serves the lookups waiting on it but is not kept. +const PATH_DIRECTORY_SETTLE_MS = 2_000; +const NO_DIRECTORY_NAMES: ReadonlySet = new Set(); + +// A listing only speaks for names Windows matches by ASCII case folding. It omits 8.3 aliases +// (`~`), Windows trims a trailing dot, and other characters fold differently than in JS. +const LISTED_NAME_PATTERN = /^[\w.+-]*[\w+-]$/; + +function isAbsentFromListing(names: ReadonlySet | undefined, candidate: string): boolean { + return ( + names !== undefined && + LISTED_NAME_PATTERN.test(candidate) && + !names.has(candidate.toLowerCase()) + ); +} + +// The listing must start after the mtime's timestamp step has passed, and a relative entry +// names another directory once the working directory changes. +function isReusableListing( + directory: string, + modified: number, + listedAtMs: number, + isAbsolute: (path: string) => boolean, +): boolean { + return isAbsolute(directory) && listedAtMs - modified >= PATH_DIRECTORY_SETTLE_MS; } const directoryMtime = (directory: string) => @@ -592,29 +629,77 @@ const directoryMtime = (directory: string) => // Timestamp before reading so concurrent additions change the next mtime check; missing listings fall back to direct probes. const listPathDirectory = Effect.fnUntraced(function* ( directory: string, -): Effect.fn.Return { +): Effect.fn.Return { + const path = yield* Path.Path; const modified = yield* directoryMtime(directory); - if (modified == null) return { modified, names: modified === null ? new Set() : undefined }; + if (modified === null) { + return { modified, names: NO_DIRECTORY_NAMES, reusable: path.isAbsolute(directory) }; + } + if (modified === undefined) return { modified, names: undefined, reusable: false }; + const listedAtMs = yield* Clock.currentTimeMillis; const entries = yield* FileSystem.FileSystem.use((fileSystem) => fileSystem.readDirectory(directory), ).pipe(Effect.orElseSucceed(() => undefined)); - return { modified, names: entries && new Set(entries.map((entry) => entry.toLowerCase())) }; + return { + modified, + names: entries && new Set(entries.map((entry) => entry.toLowerCase())), + reusable: + entries !== undefined && isReusableListing(directory, modified, listedAtMs, path.isAbsolute), + }; }); -const PathDirectoryListings = Context.Reference< - Cache.Cache | undefined ->("@t3tools/shared/shell/PathDirectoryListings", { defaultValue: () => undefined }); - -export const withPathDirectoryListings = - /* Directory reads are cached inside one shell operation; a span for each lookup adds noise. */ - Effect.fnUntraced(function* (effect: Effect.Effect) { - const listings = yield* Cache.make({ - capacity: 1024, - lookup: listPathDirectory, - requireServicesAt: "lookup", - }); - return yield* effect.pipe(Effect.provideService(PathDirectoryListings, listings)); - }); +export const makePathDirectoryListings = Cache.makeWith(listPathDirectory, { + capacity: PATH_DIRECTORY_LISTINGS_MAX_ENTRIES, + timeToLive: (exit) => + Exit.isSuccess(exit) && exit.value.reusable ? Duration.infinity : Duration.zero, + requireServicesAt: "lookup", +}); + +/** Windows PATH directory listings for the process; each use rechecks the directory's mtime. */ +export const PathDirectoryListings = Context.Reference( + "@t3tools/shared/shell/PathDirectoryListings", + { defaultValue: () => Effect.runSync(makePathDirectoryListings) }, +); + +const syncPathDirectoryListings = new Map< + string, + { readonly modified: number; readonly names: ReadonlySet } +>(); + +// The synchronous resolver's counterpart of `PathDirectoryListings`, under the same rules. +function listPathDirectorySync( + directory: string, + isAbsolute: (path: string) => boolean, +): ReadonlySet | undefined { + let modified: number; + try { + const stats = NodeFS.statSync(directory); + if (!stats.isDirectory()) return undefined; + modified = stats.mtimeMs; + } catch (error) { + return (error as NodeJS.ErrnoException).code === "ENOENT" ? NO_DIRECTORY_NAMES : undefined; + } + const cached = syncPathDirectoryListings.get(directory); + if (cached?.modified === modified) return cached.names; + syncPathDirectoryListings.delete(directory); + // This resolver runs outside Effect, so it has no Clock to read. + // @effect-diagnostics-next-line globalDate:off + const listedAtMs = Date.now(); + let names: ReadonlySet; + try { + names = new Set(NodeFS.readdirSync(directory).map((entry) => entry.toLowerCase())); + } catch { + return undefined; + } + if (isReusableListing(directory, modified, listedAtMs, isAbsolute)) { + if (syncPathDirectoryListings.size >= PATH_DIRECTORY_LISTINGS_MAX_ENTRIES) { + const oldest = syncPathDirectoryListings.keys().next().value; + if (oldest !== undefined) syncPathDirectoryListings.delete(oldest); + } + syncPathDirectoryListings.set(directory, { modified, names }); + } + return names; +} // An injected resolver or locator may answer differently for the same search, so its // entries are kept apart from every other resolver's. @@ -685,7 +770,8 @@ const findOnPath = Effect.fnUntraced(function* ( pathEntries.push(pathEntry); } - const listings = yield* PathDirectoryListings; + // Only Windows multiplies the candidates per directory; elsewhere a listing saves no probe. + const listings = platform === "win32" ? yield* PathDirectoryListings : undefined; const matches: string[] = []; for (const pathEntry of pathEntries) { let listing = listings && (yield* Cache.get(listings, pathEntry)); @@ -694,7 +780,7 @@ const findOnPath = Effect.fnUntraced(function* ( listing = yield* Cache.get(listings, pathEntry); } for (const candidate of commandCandidates) { - if (listing?.names && !listing.names.has(candidate.toLowerCase())) continue; + if (isAbsentFromListing(listing?.names, candidate)) continue; const candidatePath = path.join(pathEntry, candidate); if (yield* isExecutableFile(candidatePath, platform, windowsPathExtensions)) { matches.push(candidatePath); From 83edd5e722e11a469c3ec72684eab71b0236d9aa Mon Sep 17 00:00:00 2001 From: Navid Nadali Date: Sun, 22 Nov 2026 01:07:59 +0000 Subject: [PATCH 092/324] fix(mcp): t3_thread_wait no longer has parents poll a task's first run (#40633) Co-authored-by: Julius Marminge --- .../src/mcp/OrchestratorMcpService.test.ts | 24 +++++++++++++++---- apps/server/src/mcp/OrchestratorMcpService.ts | 9 +++++-- 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index 4a5935d427879..ccd41144a5ea8 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -617,6 +617,7 @@ describe("OrchestratorMcpService", () => { const childThreadId = ThreadId.make("thread:mcp-next-child"); const taskId = NodeId.make("node:mcp-next-task"); let finished = false; + let firstRun = false; let pendingRequest: "live" | "message" | null = null; const parentProjection = () => ({ @@ -640,12 +641,17 @@ describe("OrchestratorMcpService", () => { const childRun = () => ({ id: RunId.make("run:mcp-next-child"), ordinal: 1, - status: finished ? ("completed" as const) : ("running" as const), - delegatedTaskId: taskId, + status: finished && !firstRun ? ("completed" as const) : ("running" as const), + // A task's first run is untagged; the child's fork node names the task. + ...(firstRun ? {} : { delegatedTaskId: taskId }), }); const childProjection = () => ({ - thread: { id: childThreadId, title: "Child task" }, + thread: { + id: childThreadId, + title: "Child task", + forkedFrom: { type: "node", nodeId: taskId }, + }, runs: [childRun()], contextTransfers: [], messages: [], @@ -677,7 +683,7 @@ describe("OrchestratorMcpService", () => { Effect.succeed({ threadId: childThreadId, run: childRun() as unknown as OrchestrationV2ThreadProjection["runs"][number], - timedOut: !finished, + timedOut: !finished || firstRun, }), dispatch: () => Effect.succeed({} as never), }), @@ -725,7 +731,17 @@ describe("OrchestratorMcpService", () => { assert.equal(working.next, ORCHESTRATOR_MCP_RUNNING_TASK_NEXT); pendingRequest = null; + firstRun = true; + const first = yield* service.waitForThread(scope, { threadId: childThreadId }); + assert.equal(first.next, ORCHESTRATOR_MCP_RUNNING_TASK_NEXT); + + // An untagged run after the task has its result is no longer that task. finished = true; + const followUp = yield* service.waitForThread(scope, { threadId: childThreadId }); + assert.isTrue(followUp.timedOut); + assert.notProperty(followUp, "next"); + firstRun = false; + const completed = yield* service.taskStatus(scope, taskId); assert.equal(completed.status, "completed"); assert.notProperty(completed, "next"); diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 5f0c95a55ffee..4062c509812c4 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -3713,7 +3713,11 @@ const make = Effect.gen(function* () { }) .pipe(Effect.mapError(threadManagementFailure)); const status = result.run === null ? "idle" : runOutcome(result.run); - const taskId = result.run?.delegatedTaskId; + // A task's first run carries no task id; the child's untagged runs continue that task + // until it has a result. + const taskId = + result.run?.delegatedTaskId ?? + (target.thread.forkedFrom?.type === "node" ? target.thread.forkedFrom.nodeId : undefined); const ownedTask = result.timedOut && status !== "waiting" && @@ -3725,7 +3729,8 @@ const make = Effect.gen(function* () { task.origin === "app_owned" && task.threadId === parent.thread.id && task.childThreadId === input.threadId && - task.completionDelivery?.state !== "disposed", + task.completionDelivery?.state !== "disposed" && + (result.run?.delegatedTaskId !== undefined || task.result === null), ); // A child waiting on a question or approval needs an answer, not a wake. const childRequests = ownedTask From 15d945faef4c14099ba3d82bcdb84e91b5a3c3cd Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 17:20:02 -0800 Subject: [PATCH 093/324] fix(server): reveal no longer opens Explorer's default folder for a missing file (#40637) --- .../src/process/externalLauncher.test.ts | 55 +++++++++++++++++-- apps/server/src/process/externalLauncher.ts | 9 +++ packages/contracts/src/editor.ts | 13 +++++ 3 files changed, 72 insertions(+), 5 deletions(-) diff --git a/apps/server/src/process/externalLauncher.test.ts b/apps/server/src/process/externalLauncher.test.ts index 8ce873733d443..827d52bbda230 100644 --- a/apps/server/src/process/externalLauncher.test.ts +++ b/apps/server/src/process/externalLauncher.test.ts @@ -65,6 +65,7 @@ const layerTest = (input: { readonly onSpawn?: (command: ChildProcess.StandardCommand) => void; readonly onUnref?: () => void; readonly spawnResult?: (command: ChildProcess.StandardCommand) => MockSpawnResult | undefined; + readonly existingPaths?: ReadonlyArray; }) => { const layerSpawner = Layer.succeed( ChildProcessSpawner.ChildProcessSpawner, @@ -92,6 +93,17 @@ const layerTest = (input: { NodeServices.layer, layerSpawner, input.path ? Layer.succeed(Path.Path, input.path) : Layer.empty, + // Reveal fixtures name paths that do not exist on the test host. + Layer.effect( + FileSystem.FileSystem, + Effect.map(FileSystem.FileSystem, (fileSystem) => ({ + ...fileSystem, + exists: (path: string) => + input.existingPaths?.includes(path) + ? Effect.succeed(true) + : fileSystem.exists(path), + })), + ).pipe(Layer.provide(NodeServices.layer)), ), ), ), @@ -571,6 +583,7 @@ for (const [replacement, verb, handler, target, expected] of [ layerTest({ platform: "win32", env: { PATH: "C:\\Windows", PATHEXT: ".EXE" }, + existingPaths: [target], onSpawn: (command) => { spawned = command; }, @@ -605,16 +618,13 @@ it.effect.skipIf(windowsHost)( yield* fileSystem.chmod(filePath, 0o755); } + const target = "/home/t3/workspace [draft]/author's ‘$media/clip|draft.mp4"; let spawned: ChildProcess.StandardCommand | undefined; const result = yield* Effect.gen(function* () { const launcher = yield* ExternalLauncher.ExternalLauncher; const kind = yield* launcher.resolveFileManagerRevealKind(); const editors = yield* launcher.resolveAvailableEditors(); - yield* launcher.launchEditor({ - editor: "file-manager", - cwd: "/home/t3/workspace [draft]/author's ‘$media/clip|draft.mp4", - reveal: true, - }); + yield* launcher.launchEditor({ editor: "file-manager", cwd: target, reveal: true }); return { kind, editors }; }).pipe( Effect.provide( @@ -625,6 +635,7 @@ it.effect.skipIf(windowsHost)( WSL_DISTRO_NAME: "Ubuntu-24.04", WSL_INTEROP: "/run/WSL/1_interop", }, + existingPaths: [target], onSpawn: (command) => { spawned = command; }, @@ -687,6 +698,7 @@ it.effect.each([ layerTest({ platform: "win32", env: { PATH: binDir, PATHEXT: ".COM;.EXE;.BAT;.CMD", SYSTEMROOT: "C:\\Windows" }, + existingPaths: ["C:/Users/t3/my project/a,b.ts"], onSpawn: (command) => spawned.push(command), spawnResult: (command) => (command.command.endsWith("reg.exe") ? registry : undefined), }), @@ -718,6 +730,38 @@ it.effect.each([ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); +// Explorer answers /select of a missing path by opening its default folder, not the parent. +it.effect("does not ask Explorer to select a file that does not exist", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" }); + yield* fileSystem.writeFileString(path.join(binDir, "explorer.EXE"), ""); + const missing = path.join(binDir, "CLAUDE.md"); + const verbatim: Array]> = []; + yield* Effect.gen(function* () { + const launcher = yield* ExternalLauncher.ExternalLauncher; + yield* launcher + .launchEditor({ editor: "file-manager", cwd: missing, reveal: true }) + .pipe(Effect.exit); + }).pipe( + Effect.provideService(WindowsVerbatimSpawn, (command, args) => + Effect.sync(() => verbatim.push([command, args])), + ), + Effect.provide( + layerTest({ + platform: "win32", + env: { PATH: binDir, PATHEXT: ".COM;.EXE;.BAT;.CMD", SYSTEMROOT: "C:\\Windows" }, + spawnResult: (command) => + command.command.endsWith("reg.exe") ? { stdout: STOCK_FOLDER_VERB } : undefined, + }), + ), + ); + + assert.deepEqual(verbatim, []); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + for (const wsl of [false, true]) { it.effect.skipIf(windowsHost)( "selects a file over D-Bus on " + (wsl ? "WSLg without interop PowerShell" : "Linux"), @@ -747,6 +791,7 @@ for (const wsl of [false, true]) { ? { WSL_DISTRO_NAME: "Ubuntu-24.04", WSL_INTEROP: "/run/WSL/1_interop" } : {}), }, + existingPaths: [target], onSpawn: (command) => spawnedCommands.push(command), spawnResult: (command) => command.command === "xdg-mime" diff --git a/apps/server/src/process/externalLauncher.ts b/apps/server/src/process/externalLauncher.ts index 4c0d006332ff7..b5ffaf82fcc10 100644 --- a/apps/server/src/process/externalLauncher.ts +++ b/apps/server/src/process/externalLauncher.ts @@ -6,6 +6,7 @@ import { ExternalLauncherBrowserSpawnError, ExternalLauncherCommandNotFoundError, ExternalLauncherEditorSpawnError, + ExternalLauncherRevealTargetMissingError, ExternalLauncherUnknownEditorError, ExternalLauncherUnsupportedEditorError, ExternalLauncherUnsupportedTargetError, @@ -36,6 +37,7 @@ export { ExternalLauncherBrowserSpawnError, ExternalLauncherCommandNotFoundError, ExternalLauncherEditorSpawnError, + ExternalLauncherRevealTargetMissingError, ExternalLauncherUnknownEditorError, ExternalLauncherUnsupportedEditorError, ExternalLauncherUnsupportedTargetError, @@ -590,6 +592,13 @@ const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* ( } if (input.reveal === true) { + // Explorer answers /select of a missing path by opening its default folder, not the parent. + const exists = yield* (yield* FileSystem.FileSystem) + .exists(target) + .pipe(Effect.orElseSucceed(() => true)); + if (!exists) { + return yield* new ExternalLauncherRevealTargetMissingError({ editor: editorDef.id, target }); + } return yield* resolveFileManagerRevealLaunch(target, platform, env, command); } diff --git a/packages/contracts/src/editor.ts b/packages/contracts/src/editor.ts index 146007499d440..98a9c852b2554 100644 --- a/packages/contracts/src/editor.ts +++ b/packages/contracts/src/editor.ts @@ -305,6 +305,18 @@ export class ExternalLauncherUnsupportedTargetError extends Schema.TaggedError()( + "ExternalLauncherRevealTargetMissingError", + { + editor: EditorId, + target: Schema.String, + }, +) { + override get message(): string { + return `No file or folder exists at ${this.target}`; + } +} + const ExternalLauncherSpawnFields = { command: Schema.String, args: Schema.Array(Schema.String), @@ -341,6 +353,7 @@ export const ExternalLauncherError = Schema.Union([ ExternalLauncherUnsupportedEditorError, ExternalLauncherCommandNotFoundError, ExternalLauncherUnsupportedTargetError, + ExternalLauncherRevealTargetMissingError, ExternalLauncherBrowserSpawnError, ExternalLauncherEditorSpawnError, ]); From 90f0bac1913a379bf421576d6c051c5f3b83f2cc Mon Sep 17 00:00:00 2001 From: Navid Nadali Date: Sun, 22 Nov 2026 02:07:57 +0000 Subject: [PATCH 094/324] fix(server): a steer that missed its turn keeps its place in the queue (#40622) Co-authored-by: Julius Marminge --- .../src/orchestration-v2/EffectWorker.ts | 3 +- .../src/orchestration-v2/Orchestrator.ts | 11 +- .../SteeringCompletion.integration.test.ts | 181 +++++++++++------- 3 files changed, 115 insertions(+), 80 deletions(-) diff --git a/apps/server/src/orchestration-v2/EffectWorker.ts b/apps/server/src/orchestration-v2/EffectWorker.ts index c637446d78827..6c805cfc4592f 100644 --- a/apps/server/src/orchestration-v2/EffectWorker.ts +++ b/apps/server/src/orchestration-v2/EffectWorker.ts @@ -390,8 +390,7 @@ export const layerExecutor: Layer.Layer< threadId: effect.threadId, messageId: message.id, ...(error.steerDeclined ? { steerFollowUpOfRunId: run.id } : {}), - ...(error.steerDeclined && - effect.request.steerFollowUpAfterRunOrdinal !== undefined + ...(effect.request.steerFollowUpAfterRunOrdinal !== undefined ? { steerFollowUpAfterRunOrdinal: effect.request.steerFollowUpAfterRunOrdinal, diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index bcbe8a3656017..4f1d2d671060e 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -8073,10 +8073,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio command.creationSource === "provider" && !(yield* stopReachedRun(command, command.threadId, activeRun.id)); let steerFollowUpQueuePosition: number | undefined; - if ( - command.steerFollowUpOfRunId !== undefined && - command.steerFollowUpAfterRunOrdinal !== undefined - ) { + if (command.steerFollowUpAfterRunOrdinal !== undefined) { const afterRunOrdinal = command.steerFollowUpAfterRunOrdinal; const steerOrdinal = projection.turnItems.find( @@ -8237,7 +8234,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio runId: queued.id, providerInstanceId: queued.providerInstanceId, occurredAt: now, - payload: { ...queued, queuePosition: (queued.queuePosition ?? queued.ordinal) + 1 }, + payload: { + ...queued, + ...(heldRunsToRelease.includes(queued) ? { queueHeld: false } : {}), + queuePosition: (queued.queuePosition ?? queued.ordinal) + 1, + }, }); } } diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index dd2d95cfc1b81..04257d91bc9a7 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -1363,81 +1363,116 @@ it.effect("restarts the turn for an image when native steering takes text only", }), ); -it.effect("starts a steer that missed the turn on the saved next-turn selection", () => - Effect.gen(function* () { - const { events, started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness( - "steering-selection-follow-up", - ); - yield* Effect.gen(function* () { - const orchestrator = yield* Orchestrator.OrchestratorV2; - const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; - const threadId = yield* startFirstTurn; - const first = started[0]!; - yield* orchestrator.dispatch({ - type: "message.dispatch", - commandId: CommandId.make("steer"), - threadId, - messageId: MessageId.make("message:steer"), - text: "late steer", - attachments: [], - modelSelection: composerSelection, - dispatchMode: { type: "steer_active", targetRunId: first.runId }, - createdBy: "user", - creationSource: "web", - }); - const settled = yield* orchestrator.streamDomainEvents.pipe( - Stream.filter( - (event) => - event.type === "run.updated" && - event.payload.id === first.runId && - event.payload.status === "waiting", - ), - Stream.take(1), - Stream.runDrain, - Effect.forkScoped, +it.effect.each(["complete", "stop-before-end"] as const)( + "starts a steer that missed the turn in its place on the saved next-turn selection: %s", + (timing) => + Effect.gen(function* () { + const { events, started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness( + `steering-selection-follow-up-${timing}`, ); - const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!; - yield* Queue.offer(events, { - type: "provider_turn.updated", - driver, - providerTurn: { ...turn, status: "completed", completedAt: yield* DateTime.now }, - }); - yield* Queue.offer(events, { - type: "turn.terminal", - driver, - providerThreadId: turn.providerThreadId, - providerTurnId: turn.id, - runOrdinal: first.runOrdinal, - status: "completed", - failure: null, - threadDisposition: "reusable", - }); - yield* Fiber.join(settled); - yield* worker.drain(); - yield* orchestrator.resumeQueuedRuns; - yield* worker.drain(); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + const first = started[0]!; + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("steer"), + threadId, + messageId: MessageId.make("message:steer"), + text: "late steer", + attachments: [], + modelSelection: composerSelection, + dispatchMode: { type: "steer_active", targetRunId: first.runId }, + createdBy: "user", + creationSource: "web", + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("queued-later"), + threadId, + messageId: MessageId.make("message:queued-later"), + text: "queued later", + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "user", + creationSource: "web", + }); + if (timing === "stop-before-end") { + yield* orchestrator.dispatch({ + type: "run.interrupt", + commandId: CommandId.make("stop"), + threadId, + runId: first.runId, + holdQueue: true, + }); + } + const settled = yield* orchestrator.streamDomainEvents.pipe( + Stream.filter( + (event) => + event.type === "run.updated" && + event.payload.id === first.runId && + event.payload.status === "waiting", + ), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!; + yield* Queue.offer(events, { + type: "provider_turn.updated", + driver, + providerTurn: { ...turn, status: "completed", completedAt: yield* DateTime.now }, + }); + yield* Queue.offer(events, { + type: "turn.terminal", + driver, + providerThreadId: turn.providerThreadId, + providerTurnId: turn.id, + runOrdinal: first.runOrdinal, + status: "completed", + failure: null, + threadDisposition: "reusable", + }); + yield* Fiber.join(settled); + yield* worker.drain(); + if (timing === "stop-before-end") { + const queued = (yield* orchestrator.getThreadProjection(threadId)).runs + .filter((run) => run.status === "queued") + .toSorted((left, right) => (left.queuePosition ?? 0) - (right.queuePosition ?? 0)); + assert.deepEqual( + queued.map((run) => [run.userMessageId, run.queueHeld === true]), + [ + [MessageId.make("message:steer"), false], + [MessageId.make("message:queued-later"), false], + ], + ); + return; + } + yield* orchestrator.resumeQueuedRuns; + yield* worker.drain(); - const projection = yield* orchestrator.getThreadProjection(threadId); - assert.deepEqual(steered, []); - assert.equal(started.length, 2); - assert.equal(started[1]?.message.messageId, MessageId.make("message:steer")); - assert.deepEqual(started[1]?.modelSelection, composerSelection); - assert.deepEqual(projection.thread.modelSelection, composerSelection); - const message = projection.turnItems.find( - (item) => - item.type === "user_message" && item.messageId === MessageId.make("message:steer"), - ); - assert.equal(message?.runId, started[1]!.runId); - assert.isAbove( - message!.ordinal, - Math.max( - ...projection.turnItems - .filter((item) => item.runId === first.runId) - .map((item) => item.ordinal), - ), - ); - }).pipe(Effect.provide(layer)); - }), + const projection = yield* orchestrator.getThreadProjection(threadId); + assert.deepEqual(steered, []); + assert.equal(started.length, 2); + assert.equal(started[1]?.message.messageId, MessageId.make("message:steer")); + assert.deepEqual(started[1]?.modelSelection, composerSelection); + assert.deepEqual(projection.thread.modelSelection, composerSelection); + const message = projection.turnItems.find( + (item) => + item.type === "user_message" && item.messageId === MessageId.make("message:steer"), + ); + assert.equal(message?.runId, started[1]!.runId); + assert.isAbove( + message!.ordinal, + Math.max( + ...projection.turnItems + .filter((item) => item.runId === first.runId) + .map((item) => item.ordinal), + ), + ); + }).pipe(Effect.provide(layer)); + }), ); const declinedSteerTimings = [ From 3f08098c99711edc1f201ce53b3ffceb09a6ea3f Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 19:08:53 -0800 Subject: [PATCH 095/324] fix(web): wrapped prompt suggestion no longer overlaps the composer toolbar (#40654) --- apps/web/src/components/ComposerPromptEditorTiptap.tsx | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index ab43b514ed3d9..c3fb7fad73ff8 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -1924,12 +1924,13 @@ function ComposerPromptEditorTiptapInner(
    { if ( event.key === "Control" || @@ -1974,7 +1975,7 @@ function ComposerPromptEditorTiptapInner( {isEmpty && contextRecords.size === 0 && placeholder ? (
    From 571b8697da2179883609fbdbc585c91b6f200a80 Mon Sep 17 00:00:00 2001 From: Guilherme Brasil Date: Sat, 21 Nov 2026 22:43:37 -0500 Subject: [PATCH 096/324] fix(server): refuse ref switches while a thread works in the shared checkout (#38271) Co-authored-by: Julius Marminge --- .../src/git/sharedCheckoutGuard.test.ts | 167 ++++++++++++++++++ apps/server/src/git/sharedCheckoutGuard.ts | 101 +++++++++++ apps/server/src/ws.ts | 36 ++-- docs/user/thread-sidebar.md | 3 +- 4 files changed, 292 insertions(+), 15 deletions(-) create mode 100644 apps/server/src/git/sharedCheckoutGuard.test.ts create mode 100644 apps/server/src/git/sharedCheckoutGuard.ts diff --git a/apps/server/src/git/sharedCheckoutGuard.test.ts b/apps/server/src/git/sharedCheckoutGuard.test.ts new file mode 100644 index 0000000000000..1723b29c10bb8 --- /dev/null +++ b/apps/server/src/git/sharedCheckoutGuard.test.ts @@ -0,0 +1,167 @@ +import { ProjectId, ThreadId } from "@t3tools/contracts"; +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; +import * as ProjectService from "../project/ProjectService.ts"; +import * as GitWorkflowService from "./GitWorkflowService.ts"; +import { assertCheckoutIdle, busyThreadsInCheckout } from "./sharedCheckoutGuard.ts"; + +const projectId = ProjectId.make("project-a"); +const otherProjectId = ProjectId.make("project-b"); +const nestedProjectId = ProjectId.make("project-nested"); +const childRepositoryProjectId = ProjectId.make("project-child-repository"); + +const thread = ( + title: string, + overrides: { + readonly projectId?: ProjectId; + readonly worktreePath?: string | null; + readonly activityRunStatus?: "preparing" | "starting" | "running" | "waiting" | null; + readonly archived?: boolean; + } = {}, +) => ({ + archived: overrides.archived ?? false, + id: ThreadId.make(title), + title, + projectId: overrides.projectId ?? projectId, + worktreePath: overrides.worktreePath ?? null, + activityRunStatus: + overrides.activityRunStatus === undefined ? "running" : overrides.activityRunStatus, +}); + +describe("busyThreadsInCheckout", () => { + it("finds running local threads in the project root checkout", () => { + const busy = busyThreadsInCheckout({ + checkoutPaths: ["/repo"], + projectIds: new Set([projectId]), + threads: [ + thread("local running"), + thread("local idle", { activityRunStatus: null }), + thread("worktree running", { worktreePath: "/worktrees/a" }), + thread("other project", { projectId: otherProjectId }), + ], + }); + + expect(busy.map(({ title }) => title)).toEqual(["local running"]); + }); + + it("finds running threads that share a worktree", () => { + const busy = busyThreadsInCheckout({ + checkoutPaths: ["/worktrees/a"], + projectIds: new Set(), + threads: [ + thread("same worktree", { worktreePath: "/worktrees/a", activityRunStatus: "waiting" }), + thread("other worktree", { worktreePath: "/worktrees/b" }), + thread("local running"), + ], + }); + + expect(busy.map(({ title }) => title)).toEqual(["same worktree"]); + }); +}); + +describe("assertCheckoutIdle", () => { + const guardLayer = (input: { + readonly repositoryRoot: string; + readonly threads: ReadonlyArray>; + readonly failWorktreeLookup?: boolean; + }) => + Layer.mergeAll( + Layer.mock(GitWorkflowService.GitWorkflowService)({ + repositoryRoot: (cwd) => + Effect.succeed(cwd.startsWith("/repo/child") ? "/repo/child" : input.repositoryRoot), + }), + Layer.mock(ProjectService.ProjectService)({ + snapshot: Effect.succeed({ + projects: [ + { id: projectId, workspaceRoot: "/repo" }, + { id: nestedProjectId, workspaceRoot: "/repo/packages/app" }, + { id: childRepositoryProjectId, workspaceRoot: "/repo/child" }, + { id: otherProjectId, workspaceRoot: "/other" }, + ], + } as never), + }), + Layer.mock(ThreadManagementService.ThreadManagementService)({ + getShellSnapshot: (options) => + options?.worktreePath !== undefined && input.failWorktreeLookup + ? Effect.fail("worktree lookup failed" as never) + : Effect.succeed( + (() => { + const matching = input.threads.filter( + (candidate) => + (options?.projectId === undefined || + candidate.projectId === options.projectId) && + (options?.worktreePath === undefined || + candidate.worktreePath === options.worktreePath), + ); + return { + threads: matching.filter((candidate) => !candidate.archived), + archivedThreads: matching.filter((candidate) => candidate.archived), + } as never; + })(), + ), + }), + ); + + it.effect("refuses a switch from a subdirectory of a busy checkout", () => + Effect.gen(function* () { + const error = yield* assertCheckoutIdle("test", "/repo/src").pipe( + Effect.flip, + Effect.provide(guardLayer({ repositoryRoot: "/repo", threads: [thread("local running")] })), + ); + expect(error.detail).toContain("'local running'"); + }), + ); + + it.effect("keeps a busy thread when another lookup fails", () => + Effect.gen(function* () { + const error = yield* assertCheckoutIdle("test", "/repo").pipe( + Effect.flip, + Effect.provide( + guardLayer({ + repositoryRoot: "/repo", + threads: [thread("local running")], + failWorktreeLookup: true, + }), + ), + ); + expect(error.detail).toContain("'local running'"); + }), + ); + + it.effect("refuses a switch while a nested project or archived thread is working", () => + Effect.gen(function* () { + const error = yield* assertCheckoutIdle("test", "/repo").pipe( + Effect.flip, + Effect.provide( + guardLayer({ + repositoryRoot: "/repo", + threads: [ + thread("nested running", { projectId: nestedProjectId }), + thread("archived running", { archived: true }), + thread("other running", { projectId: otherProjectId }), + thread("child repository running", { projectId: childRepositoryProjectId }), + ], + }), + ), + ); + // Exactly these two: a third busy thread would read "and 1 more". + expect(error.detail).toMatch( + /^'(nested|archived) running' and '(nested|archived) running' are still working/, + ); + }), + ); + + it.effect("allows a switch when no thread is working", () => + assertCheckoutIdle("test", "/repo").pipe( + Effect.provide( + guardLayer({ + repositoryRoot: "/repo", + threads: [thread("local idle", { activityRunStatus: null })], + }), + ), + ), + ); +}); diff --git a/apps/server/src/git/sharedCheckoutGuard.ts b/apps/server/src/git/sharedCheckoutGuard.ts new file mode 100644 index 0000000000000..442ef14dc71e9 --- /dev/null +++ b/apps/server/src/git/sharedCheckoutGuard.ts @@ -0,0 +1,101 @@ +import { + GitCommandError, + type OrchestrationV2ThreadShell, + type ProjectId, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; + +import * as GitWorkflowService from "./GitWorkflowService.ts"; +import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; +import * as ProjectService from "../project/ProjectService.ts"; + +type CheckoutThread = Pick< + OrchestrationV2ThreadShell, + "id" | "title" | "projectId" | "worktreePath" | "activityRunStatus" +>; + +/** Threads with an active run whose working directory is one of `checkoutPaths`. */ +export function busyThreadsInCheckout(input: { + readonly checkoutPaths: ReadonlyArray; + readonly projectIds: ReadonlySet; + readonly threads: ReadonlyArray; +}): ReadonlyArray { + return input.threads.filter( + (thread) => + (thread.activityRunStatus ?? null) !== null && + (thread.worktreePath === null + ? input.projectIds.has(thread.projectId) + : input.checkoutPaths.includes(thread.worktreePath)), + ); +} + +function describeBusyCheckout(titles: ReadonlyArray): string { + const quoted = titles.map((title) => `'${title}'`); + const names = + quoted.length <= 2 + ? quoted.join(" and ") + : `${quoted.slice(0, 2).join(", ")} and ${quoted.length - 2} more`; + return `${names} ${quoted.length === 1 ? "is" : "are"} still working in this checkout. Wait for ${quoted.length === 1 ? "it" : "them"} to finish, or use a worktree for a separate branch.`; +} + +/** Switching a shared checkout's ref moves every thread working in it, mid-turn included. */ +export const assertCheckoutIdle = Effect.fn("sharedCheckoutGuard.assertCheckoutIdle")(function* ( + operation: string, + cwd: string, +) { + const gitWorkflow = yield* GitWorkflowService.GitWorkflowService; + const projectService = yield* ProjectService.ProjectService; + const threadManagement = yield* ThreadManagementService.ThreadManagementService; + // `git checkout` from a subdirectory moves the whole checkout; records may hold either spelling. + const root = yield* gitWorkflow.repositoryRoot(cwd).pipe(Effect.orElseSucceed(() => null)); + const checkoutPaths = [...new Set([cwd, ...(root === null ? [] : [root])])]; + const projects = yield* projectService.snapshot.pipe( + Effect.map((snapshot) => snapshot.projects), + Effect.orElseSucceed(() => []), + ); + // A project rooted inside the checkout shares it, as in a monorepo package, unless it is its + // own repository nested there. + const nested = yield* Effect.forEach( + projects.filter( + ({ workspaceRoot }) => + root !== null && + !checkoutPaths.includes(workspaceRoot) && + workspaceRoot.startsWith(`${root}/`), + ), + (project) => + gitWorkflow.repositoryRoot(project.workspaceRoot).pipe( + Effect.map((projectRoot) => (projectRoot === root ? [project] : [])), + Effect.orElseSucceed(() => []), + ), + { concurrency: "unbounded" }, + ); + const projectIds = new Set( + [ + ...projects.filter(({ workspaceRoot }) => checkoutPaths.includes(workspaceRoot)), + ...nested.flat(), + ].map(({ id }) => id), + ); + // Archiving does not stop a run, so archived threads can still be working. Each lookup fails + // open on its own, so one failure keeps what the others found. + const snapshots = yield* Effect.forEach( + [ + ...checkoutPaths.map((worktreePath) => threadManagement.getShellSnapshot({ worktreePath })), + ...[...projectIds].map((projectId) => threadManagement.getShellSnapshot({ projectId })), + ], + (snapshot) => snapshot.pipe(Effect.orElseSucceed(() => ({ threads: [], archivedThreads: [] }))), + { concurrency: "unbounded" }, + ); + const busy = busyThreadsInCheckout({ + checkoutPaths, + projectIds, + threads: snapshots.flatMap((snapshot) => [...snapshot.threads, ...snapshot.archivedThreads]), + }); + const titles = [...new Map(busy.map((thread) => [thread.id, thread.title])).values()]; + if (titles.length === 0) return; + return yield* new GitCommandError({ + operation, + command: "git checkout", + cwd, + detail: describeBusyCheckout(titles), + }); +}); diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 90c264f5408ca..ddd07fcfad656 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -224,6 +224,7 @@ import * as WorkspacePaths from "./workspace/WorkspacePaths.ts"; import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts"; import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts"; import * as GitWorkflowService from "./git/GitWorkflowService.ts"; +import { assertCheckoutIdle } from "./git/sharedCheckoutGuard.ts"; import { refreshPushedPullRequests } from "./git/refreshPushedPullRequests.ts"; import { linkCreatedPullRequest } from "./git/linkCreatedPullRequest.ts"; import * as ReviewService from "./review/ReviewService.ts"; @@ -3264,9 +3265,13 @@ export const layerWsRpc = ( ), [WS_METHODS.gitResolvePullRequest]: (input) => gitWorkflow.resolvePullRequest(input), [WS_METHODS.gitPreparePullRequestThread]: (input) => - gitWorkflow - .preparePullRequestThread(input) - .pipe(Effect.tap(() => refreshGitStatus(input.cwd))), + (input.mode === "local" + ? assertCheckoutIdle("GitWorkflowService.preparePullRequestThread", input.cwd) + : Effect.void + ).pipe( + Effect.andThen(gitWorkflow.preparePullRequestThread(input)), + Effect.tap(() => refreshGitStatus(input.cwd)), + ), [WS_METHODS.vcsListRefs]: (input) => gitWorkflow.listRefs(input), [WS_METHODS.vcsCreateWorktree]: (input) => // A project that tracks repositories gets a task folder, as its new worktree threads do. @@ -3311,19 +3316,22 @@ export const layerWsRpc = ( ), ), [WS_METHODS.vcsCreateRef]: (input) => - gitWorkflow - .createRef(input) - .pipe( - Effect.tap(() => - input.switchRef - ? vcsStatusBroadcaster.refreshAfterCheckout(input.cwd) - : refreshGitStatus(input.cwd), - ), + (input.switchRef + ? assertCheckoutIdle("GitWorkflowService.createRef", input.cwd) + : Effect.void + ).pipe( + Effect.andThen(gitWorkflow.createRef(input)), + Effect.tap(() => + input.switchRef + ? vcsStatusBroadcaster.refreshAfterCheckout(input.cwd) + : refreshGitStatus(input.cwd), ), + ), [WS_METHODS.vcsSwitchRef]: (input) => - gitWorkflow - .switchRef(input) - .pipe(Effect.tap(() => vcsStatusBroadcaster.refreshAfterCheckout(input.cwd))), + assertCheckoutIdle("GitWorkflowService.switchRef", input.cwd).pipe( + Effect.andThen(gitWorkflow.switchRef(input)), + Effect.tap(() => vcsStatusBroadcaster.refreshAfterCheckout(input.cwd)), + ), [WS_METHODS.vcsInit]: (input) => vcsProvisioning.initRepository(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))), [WS_METHODS.reviewGetBranchCommits]: (input) => review.getBranchCommits(input), diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index f58f35feb45f5..9bbf3194a9d59 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -1,7 +1,8 @@ # Working with threads Use a new thread for a separate task. Choose **New worktree** when its code changes -need a separate branch and working directory. +need a separate branch and working directory. Threads in the same checkout share its +branch, so T3 Code refuses a branch switch there while one of them is working. ## Start a thread From c7a9fba06bdb143bd380e610487a46c9e96f35cc Mon Sep 17 00:00:00 2001 From: TheGuyWithHAT Date: Sun, 22 Nov 2026 04:45:59 +0100 Subject: [PATCH 097/324] fix(server): label speaker notes in OpenDocument attachments (#38542) Co-authored-by: Geezy Co-authored-by: Julius Marminge --- .../server/src/provider/documentTextWorker.ts | 20 ++++++++++++++++--- .../src/provider/userInputAttachments.test.ts | 15 ++++++++++++-- 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index e254e101cf93e..3dd649811f330 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -115,7 +115,10 @@ function xml(source: string, extension: string): XmlNode { if (odf && (node.name === "p" || node.name === "h")) collapseOdfWhitespace(node); if ( (extension === ".docx" && node.name === "del") || - (odf && node.name === "annotation" && parent.name !== "semantics") + (odf && node.name === "annotation" && parent.name !== "semantics") || + (extension === ".odp" && + node.name === "page-thumbnail" && + stack.some((ancestor) => ancestor.name === "notes")) ) { parent.children.pop(); return; @@ -621,8 +624,19 @@ async function* document(path: string, extension: string): AsyncGenerator child.name === "notes"); + yield* paragraphs({ + ...part, + children: part.children.filter((child) => child !== notes), + }); + if (notes && hasCellText(notes)) { + yield "\nNotes:\n"; + yield* paragraphs(notes); + } } } } else if (extension === ".xlsx") { diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index b107188136a3d..72f7e52a3cd41 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -1139,9 +1139,20 @@ describe("question answer paths", () => { ext: "odp", parts: { "content.xml": - "\n First\n\t slide Second", + "" + + "\n First\n\t slide " + + "Overview" + + "Speaker only" + + "Second" + + "Slide previewThumbnail metadata" + + "" + + "Third" + + '' + + "", }, - expected: ["## Slide 1\nFirst slide\n\n## Slide 2\nSecond"], + expected: [ + "## Slide 1\nFirst slide\nOverview\nNotes:\nSpeaker only\n\n## Slide 2\nSecond\n\n## Slide 3\nThird\n\nNotes:\n42", + ], }, { ext: "ods", From f9b19a7f855b7e10f057cab6b4bc17ea43188623 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 20:14:30 -0800 Subject: [PATCH 098/324] fix(server): folder discovery skips the walk when t3.json ignores the whole project (#40664) --- .../src/workspace/WorkspaceFolders.test.ts | 37 +++++++++++++++++++ apps/server/src/workspace/WorkspaceFolders.ts | 12 +++--- 2 files changed, 44 insertions(+), 5 deletions(-) diff --git a/apps/server/src/workspace/WorkspaceFolders.test.ts b/apps/server/src/workspace/WorkspaceFolders.test.ts index 61dac26a8c044..4c5b33bbf7776 100644 --- a/apps/server/src/workspace/WorkspaceFolders.test.ts +++ b/apps/server/src/workspace/WorkspaceFolders.test.ts @@ -193,6 +193,43 @@ it.layer(NodeServices.layer)("WorkspaceFolders", (it) => { }), ); + it.effect("does not walk a project's folders when t3.json ignores the whole project", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const workspaceRoot = yield* makeTempDir; + for (const folder of ["api/.git", "src/web/.git", "notes"]) { + yield* fileSystem.makeDirectory(path.join(workspaceRoot, folder), { recursive: true }); + } + yield* fileSystem.writeFileString( + path.join(workspaceRoot, "t3.json"), + JSON.stringify({ ignoreRepositories: ["."] }), + ); + const probed: Array = []; + const counting = FileSystem.FileSystem.of({ + ...fileSystem, + readDirectory: (target, options) => { + probed.push(target); + return fileSystem.readDirectory(target, options); + }, + stat: (target) => { + probed.push(target); + return fileSystem.stat(target); + }, + }); + + const found = yield* WorkspaceFolders.discoverFolders(workspaceRoot).pipe( + Effect.provideService(FileSystem.FileSystem, counting), + ); + + assert.deepEqual(found, []); + assert.deepEqual( + probed.filter((target) => target !== workspaceRoot), + [], + ); + }), + ); + it.effect("keeps the folders someone added when a project holds more than fit", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; diff --git a/apps/server/src/workspace/WorkspaceFolders.ts b/apps/server/src/workspace/WorkspaceFolders.ts index 776f90ea6e5b0..9b21fd3fbcc62 100644 --- a/apps/server/src/workspace/WorkspaceFolders.ts +++ b/apps/server/src/workspace/WorkspaceFolders.ts @@ -276,11 +276,7 @@ export const discoverFolders = Effect.fn("WorkspaceFolders.discover")(function* const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const { realPath, ownsHistory } = yield* folderProbes; - // Uncapped: the folders outside the project are dropped below, and must not use up the room. - const scan = yield* scanFolders({ workspaceRoot }, Number.POSITIVE_INFINITY).pipe(Effect.option); - if (Option.isNone(scan)) return []; - const root = scan.value.workspaceRoot; - const realRoot = yield* realPath(root); + const root = path.resolve(expandHomePath(workspaceRoot.trim(), yield* HostProcess.HomeDirectory)); const ignored = ( parseT3ProjectFile( yield* fileSystem @@ -288,6 +284,12 @@ export const discoverFolders = Effect.fn("WorkspaceFolders.discover")(function* .pipe(Effect.orElseSucceed(() => "")), )?.ignoreRepositories ?? [] ).map((entry) => path.resolve(root, entry)); + // Everything the scan could find would be dropped, so skip the walk. + if (ignored.some((entry) => isWithinRoot(path, root, entry))) return []; + // Uncapped: the folders outside the project are dropped below, and must not use up the room. + const scan = yield* scanFolders({ workspaceRoot }, Number.POSITIVE_INFINITY).pipe(Effect.option); + if (Option.isNone(scan)) return []; + const realRoot = yield* realPath(root); const inside = yield* Effect.filter( scan.value.folders.filter( (folder) => From 28a420060b321ce3317f8529a5db5138af97c189 Mon Sep 17 00:00:00 2001 From: Sudharsan <126713117+Sidreyas@users.noreply.github.com> Date: Sun, 22 Nov 2026 11:06:26 +0530 Subject: [PATCH 099/324] fix(server): checkpoint repository scopes walk the project folder once per turn (#40671) Co-authored-by: Julius Marminge --- .../src/orchestration-v2/CheckpointService.ts | 9 ++++---- .../src/workspace/WorkspaceFolders.test.ts | 22 +++++++++++-------- apps/server/src/workspace/WorkspaceFolders.ts | 5 +++-- 3 files changed, 21 insertions(+), 15 deletions(-) diff --git a/apps/server/src/orchestration-v2/CheckpointService.ts b/apps/server/src/orchestration-v2/CheckpointService.ts index 079ac88211870..ec3e872d61c2b 100644 --- a/apps/server/src/orchestration-v2/CheckpointService.ts +++ b/apps/server/src/orchestration-v2/CheckpointService.ts @@ -924,10 +924,11 @@ export const layer: Layer.Layer< const repositoryScopesIfReadable: CheckpointServiceV2Shape["repositoryScopesIfReadable"] = Effect.fn("CheckpointService.repositoryScopes")( function* (input) { - const [workspace, submodules] = yield* Effect.all([ - workspaceFolders.forThread(input), - workspaceFolders.submodules(input), - ]); + const workspace = yield* workspaceFolders.forThread(input); + const submodules = yield* workspaceFolders.submodules({ + ...input, + folders: workspace.folders, + }); return yield* Effect.forEach( [...workspace.folders.filter((folder) => folder.isGitRepository), ...submodules], (folder) => diff --git a/apps/server/src/workspace/WorkspaceFolders.test.ts b/apps/server/src/workspace/WorkspaceFolders.test.ts index 4c5b33bbf7776..3a02d202be891 100644 --- a/apps/server/src/workspace/WorkspaceFolders.test.ts +++ b/apps/server/src/workspace/WorkspaceFolders.test.ts @@ -330,17 +330,21 @@ it.layer(NodeServices.layer)("WorkspaceFolders", (it) => { folders: [], extraRoots: [], }); - assert.deepEqual(yield* workspaceFolders.submodules({ projectId, worktreePath: null }), [ - { name: "lib", path: path.join(workspaceRoot, "vendor", "lib"), isGitRepository: true }, - { - name: "deep", - path: path.join(workspaceRoot, "vendor", "lib", "deep"), - isGitRepository: true, - }, - ]); + const { folders } = yield* workspaceFolders.forThread({ projectId, worktreePath: null }); + assert.deepEqual( + yield* workspaceFolders.submodules({ projectId, worktreePath: null, folders }), + [ + { name: "lib", path: path.join(workspaceRoot, "vendor", "lib"), isGitRepository: true }, + { + name: "deep", + path: path.join(workspaceRoot, "vendor", "lib", "deep"), + isGitRepository: true, + }, + ], + ); // A worktree reaches its own submodules, named by where the project folder has them. assert.deepEqual( - yield* workspaceFolders.submodules({ projectId, worktreePath: worktree }), + yield* workspaceFolders.submodules({ projectId, worktreePath: worktree, folders: [] }), [ { name: "lib", diff --git a/apps/server/src/workspace/WorkspaceFolders.ts b/apps/server/src/workspace/WorkspaceFolders.ts index 9b21fd3fbcc62..0824c647ce360 100644 --- a/apps/server/src/workspace/WorkspaceFolders.ts +++ b/apps/server/src/workspace/WorkspaceFolders.ts @@ -64,6 +64,8 @@ export class WorkspaceFolders extends Context.Service< readonly submodules: (input: { readonly projectId: ProjectId; readonly worktreePath: string | null; + /** The thread's `forThread` folders; passed in so the project is walked once. */ + readonly folders: ReadonlyArray; }) => Effect.Effect, WorkspaceFoldersError>; readonly list: ( input: WorkspaceListFoldersInput, @@ -508,7 +510,6 @@ const make = Effect.gen(function* () { const submodules: WorkspaceFolders["Service"]["submodules"] = Effect.fn( "WorkspaceFolders.submodules", )(function* (input) { - const { folders } = yield* forThread(input); // A worktree can outlive its project record; its submodules are then named by where they are. const projectRoot = yield* readProject(input.projectId).pipe( Effect.map((project) => path.resolve(project.workspaceRoot)), @@ -520,7 +521,7 @@ const make = Effect.gen(function* () { const identity = Option.getOrElse(projectRoot, () => root); return yield* submodulesOf([ { path: root, identity }, - ...folders.flatMap((folder) => + ...input.folders.flatMap((folder) => folder.isGitRepository ? [{ path: folder.path, identity: folder.repositoryPath ?? folder.path }] : [], From c5fa33b27e45ca48fea7b4e12337b8560845f3db Mon Sep 17 00:00:00 2001 From: MIT-Consulting Date: Sun, 22 Nov 2026 00:42:40 -0500 Subject: [PATCH 100/324] fix(server,cursor): preserve inline handoff when a failed Cursor turn drops its prompt (#40670) Co-authored-by: Julius Marminge --- .../ContextHandoffDelivery.ts | 10 +- .../src/orchestration-v2/Orchestrator.ts | 5 +- .../ProviderTurnStartService.ts | 103 +++++++--- .../orchestration-v2/RestartBackgroundNote.ts | 35 ++-- .../RunExecutionService.test.ts | 48 +++++ .../orchestration-v2/RunExecutionService.ts | 192 ++++++++++++------ .../ProviderSwitch.integration.test.ts | 169 +++++++++++++++ packages/contracts/src/orchestrationV2.ts | 8 + .../src/server/ProviderAdapter.ts | 4 + .../src/server/adapter.test.ts | 143 +++++++++++++ .../provider-cursor/src/server/adapter.ts | 14 ++ .../orchestrationV2ManualContinuation.test.ts | 12 ++ .../src/orchestrationV2ManualContinuation.ts | 10 +- 13 files changed, 634 insertions(+), 119 deletions(-) diff --git a/apps/server/src/orchestration-v2/ContextHandoffDelivery.ts b/apps/server/src/orchestration-v2/ContextHandoffDelivery.ts index 5211da2faf169..72471eb8cf944 100644 --- a/apps/server/src/orchestration-v2/ContextHandoffDelivery.ts +++ b/apps/server/src/orchestration-v2/ContextHandoffDelivery.ts @@ -37,7 +37,7 @@ export const deliverContextHandoffs = Effect.fn("orchestrationV2.deliverContextH handoff.delivery.status === "pending", ); if (pending.length === 0 || (input.deferInline && input.inject === undefined)) - return { context: "", delivered: Effect.void, unsent: Effect.void }; + return { context: "", delivered: Effect.void, unsent: Effect.void, inlineHandoffs: [] }; const budget = typeof input.budget === "number" ? input.budget : yield* input.budget; let coverage = pending .map( @@ -76,7 +76,8 @@ export const deliverContextHandoffs = Effect.fn("orchestrationV2.deliverContextH budget, }); if (historyCost(selected.messages, selected.context) > budget) { - if (input.deferInline) return { context: "", delivered: Effect.void, unsent: Effect.void }; + if (input.deferInline) + return { context: "", delivered: Effect.void, unsent: Effect.void, inlineHandoffs: [] }; return yield* new ContextHandoffBudgetError(); } const omittedItemIds = new Set(selected.omittedItemIds); @@ -127,7 +128,7 @@ export const deliverContextHandoffs = Effect.fn("orchestrationV2.deliverContextH }); if (injected) { yield* persist("injected"); - return { context: "", delivered: Effect.void, unsent: Effect.void }; + return { context: "", delivered: Effect.void, unsent: Effect.void, inlineHandoffs: [] }; } } else { yield* persist("pending"); @@ -135,12 +136,13 @@ export const deliverContextHandoffs = Effect.fn("orchestrationV2.deliverContextH if (input.deferInline) { // Compaction cannot carry inline transcripts; retain for the next turn if native injection is unsupported. yield* Effect.forEach(pending, input.persist, { discard: true }); - return { context: "", delivered: Effect.void, unsent: Effect.void }; + return { context: "", delivered: Effect.void, unsent: Effect.void, inlineHandoffs: [] }; } return { context: renderHistory(selected.messages, selected.context), delivered: persist("inline"), unsent: Effect.forEach(pending, input.persist, { discard: true }), + inlineHandoffs: pending, }; }, ); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 4f1d2d671060e..995ff63b25747 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -28,6 +28,7 @@ import { CommandId, type GuestMessageId, isCompactionCommandMessage, + isDeliveredProviderTurn, isOrchestrationV2WorkActive, isProviderNativeSubagentThread, MessageId, @@ -1599,7 +1600,9 @@ function lastDeliveredRunForProviderThread( isHandoffSourceRun(run) && run.providerThreadId === providerThreadId && (run.status === "completed" || - projection.providerTurns.some((turn) => turn.runAttemptId === run.activeAttemptId)), + projection.providerTurns.some( + (turn) => turn.runAttemptId === run.activeAttemptId && isDeliveredProviderTurn(turn), + )), ); } diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index e47e88eda09a0..8e35271ce5aa9 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -16,6 +16,7 @@ import { type OrchestrationV2ThreadProjection, type OrchestrationV2TurnItem, isCompactionCommandMessage, + isDeliveredProviderTurn, parseGoalCommand, RunId, RunAttemptId, @@ -32,6 +33,7 @@ import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Predicate from "effect/Predicate"; import * as Schema from "effect/Schema"; +import * as Semaphore from "effect/Semaphore"; import * as ServerConfig from "../config.ts"; import { @@ -173,7 +175,9 @@ const nativeSessionMissesKeptTurns = ( ): boolean => { const nativeId = providerThread.nativeThreadRef?.nativeId; if (nativeId === undefined) return false; - const acceptedAttemptIds = new Set(projection.providerTurns.map((turn) => turn.runAttemptId)); + const acceptedAttemptIds = new Set( + projection.providerTurns.filter(isDeliveredProviderTurn).map((turn) => turn.runAttemptId), + ); const accepted = projection.attempts.filter((attempt) => acceptedAttemptIds.has(attempt.id)); const runsById = new Map(projection.runs.map((source) => [source.id, source])); const ordinalOf = (attempt: OrchestrationV2RunAttempt) => @@ -1087,7 +1091,12 @@ export const layer: Layer.Layer< ...settledHandoffs.flatMap((handoff) => handoff.delivery?.omittedItemIds ?? []), ]); const deliveredAttemptIds = new Set( - projection.providerTurns.map((turn) => turn.runAttemptId), + projection.providerTurns.filter(isDeliveredProviderTurn).map((turn) => turn.runAttemptId), + ); + const droppedAttemptIds = new Set( + projection.providerTurns + .filter((turn) => !isDeliveredProviderTurn(turn)) + .map((turn) => turn.runAttemptId), ); const acceptedAttempts = projection.attempts.filter( (source) => @@ -1159,7 +1168,9 @@ export const layer: Layer.Layer< (source) => source.ordinal < run.ordinal && source.providerThreadId === providerThread.id && - (source.status === "failed" || source.status === "interrupted") && + (source.status === "failed" || + source.status === "interrupted" || + (source.status === "cancelled" && droppedAttemptIds.has(source.activeAttemptId))) && !deliveredAttemptIds.has(source.activeAttemptId), ); const missedRunIds = new Set(missedRuns.map((source) => source.id)); @@ -1536,7 +1547,9 @@ export const layer: Layer.Layer< const rejectedHistory = yield* Effect.gen(function* () { if (session.driver !== "codex") return false; const acceptedAttemptIds = new Set( - projection.providerTurns.map((turn) => turn.runAttemptId), + projection.providerTurns + .filter(isDeliveredProviderTurn) + .map((turn) => turn.runAttemptId), ); const previous = projection.runs.findLast( (source) => @@ -1605,7 +1618,9 @@ export const layer: Layer.Layer< // Dispatch prepares no import handoff for a session import: its history is in the native session. const importedNativeSession = projection.thread.historyOrigin === "v1_import" && - !projection.providerTurns.some((turn) => turn.providerThreadId === providerThread.id) && + !projection.providerTurns.some( + (turn) => turn.providerThreadId === providerThread.id && isDeliveredProviderTurn(turn), + ) && !projection.contextHandoffs.some( (handoff) => handoff.toProviderThreadId === providerThread.id && @@ -2025,6 +2040,10 @@ export const layer: Layer.Layer< ], }); }); + let inlineDeliveredHandoffs: ReadonlyArray = []; + let promptDroppedOnTerminal = false; + const inlineDeliveryLock = yield* Semaphore.make(1); + const retryHandoffIds = new Set(retryHandoff.handoffs.map((handoff) => handoff.id)); const startWithHandoffs = Effect.fn("ProviderTurnStartService.startWithHandoffs")( function* (turnInput: Parameters[0], compact = false) { const delivery = yield* deliverContextHandoffs({ @@ -2051,6 +2070,15 @@ export const layer: Layer.Layer< sideChatHandoff === undefined || compact || goalCommand ? "" : sideChatHandoff.summaryText; + // Record inline handoffs before startTurn so an immediate dropped terminal can restore them. + inlineDeliveredHandoffs = [ + ...delivery.inlineHandoffs.map((handoff) => + retryHandoffIds.has(handoff.id) + ? { ...handoff, status: "superseded" as const } + : handoff, + ), + ...(sideChatContext === "" || sideChatHandoff === undefined ? [] : [sideChatHandoff]), + ]; const context = [delivery.context, sideChatContext, restartNote] .filter((part) => part !== "") .join("\n\n"); @@ -2101,31 +2129,39 @@ export const layer: Layer.Layer< : Effect.void, ), ); - // After provider acceptance, failed delivery bookkeeping must not stop live ingestion. - const nativeThreadId = runningProviderThread.nativeThreadRef?.nativeId; - yield* Effect.forEach( - [ - delivery.delivered, - ...(sideChatContext === "" || sideChatHandoff === undefined || nativeThreadId == null - ? [] - : [ - persistHandoff({ - ...sideChatHandoff, - toProviderThreadId: runningProviderThread.id, - delivery: { nativeThreadId, status: "inline" as const, itemIds: [] }, - }), - ]), - ], - (record) => - record.pipe( - Effect.catchCause(() => - Effect.logWarning("Failed to record accepted context handoff delivery", { - runId: run.id, - deliveryStatus: "pending", - }), - ), - ), - { discard: true }, + // Serialize acceptance writes against dropped-terminal restoration so neither overwrites the other. + yield* inlineDeliveryLock.withPermits(1)( + Effect.gen(function* () { + if (promptDroppedOnTerminal) return; + // After provider acceptance, failed delivery bookkeeping must not stop live ingestion. + const nativeThreadId = runningProviderThread.nativeThreadRef?.nativeId; + yield* Effect.forEach( + [ + delivery.delivered, + ...(sideChatContext === "" || + sideChatHandoff === undefined || + nativeThreadId == null + ? [] + : [ + persistHandoff({ + ...sideChatHandoff, + toProviderThreadId: runningProviderThread.id, + delivery: { nativeThreadId, status: "inline" as const, itemIds: [] }, + }), + ]), + ], + (record) => + record.pipe( + Effect.catchCause(() => + Effect.logWarning("Failed to record accepted context handoff delivery", { + runId: run.id, + deliveryStatus: "pending", + }), + ), + ), + { discard: true }, + ); + }), ); }, Effect.mapError((cause) => @@ -2186,6 +2222,13 @@ export const layer: Layer.Layer< hasUnpairedRunInterruptRequest: runControls.hasUnpairedRunInterruptRequest, loadRunInterruptReason: runControls.loadRunInterruptReason, hasWorkspaceMoved: runControls.hasWorkspaceMoved, + loadDroppedInlineHandoffs: () => + inlineDeliveryLock.withPermits(1)( + Effect.sync(() => { + promptDroppedOnTerminal = true; + return inlineDeliveredHandoffs; + }), + ), loadUnsettledWork: runControls.loadUnsettledWork, message: { messageId: message.id, diff --git a/apps/server/src/orchestration-v2/RestartBackgroundNote.ts b/apps/server/src/orchestration-v2/RestartBackgroundNote.ts index ceaf2fd5de54b..58918bdef612d 100644 --- a/apps/server/src/orchestration-v2/RestartBackgroundNote.ts +++ b/apps/server/src/orchestration-v2/RestartBackgroundNote.ts @@ -1,14 +1,15 @@ -import type { - NodeId, - OrchestrationV2ConversationMessage, - OrchestrationV2PendingBackgroundTask, - OrchestrationV2ProviderThread, - OrchestrationV2ProviderTurn, - OrchestrationV2RestartCancelledBackgroundWork, - OrchestrationV2Run, - OrchestrationV2RunAttempt, - OrchestrationV2Subagent, - OrchestrationV2TurnItem, +import { + isDeliveredProviderTurn, + type NodeId, + type OrchestrationV2ConversationMessage, + type OrchestrationV2PendingBackgroundTask, + type OrchestrationV2ProviderThread, + type OrchestrationV2ProviderTurn, + type OrchestrationV2RestartCancelledBackgroundWork, + type OrchestrationV2Run, + type OrchestrationV2RunAttempt, + type OrchestrationV2Subagent, + type OrchestrationV2TurnItem, } from "@t3tools/contracts"; import { subagentHoldsCompletion } from "@t3tools/provider-core/server/subagentProjection"; import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; @@ -151,7 +152,7 @@ export function restartCancelledBackgroundWorkNote( type ProviderTurnState = Pick< OrchestrationV2ProviderTurn, - "runAttemptId" | "providerThreadId" | "status" + "runAttemptId" | "providerThreadId" | "status" | "promptDropped" >; export function isRestartNoteSource( @@ -307,12 +308,14 @@ export function delegatedTaskResultRun( /** The provider never accepted this continuation's prompt, so starting it again repeats nothing. */ export function continuationFailedBeforePrompt( run: Pick, - providerTurns: ReadonlyArray>, + providerTurns: ReadonlyArray>, ): boolean { return ( run.status === "failed" && run.restartContinuationOfRunId !== undefined && - !providerTurns.some((turn) => turn.runAttemptId === run.activeAttemptId) + !providerTurns.some( + (turn) => turn.runAttemptId === run.activeAttemptId && isDeliveredProviderTurn(turn), + ) ); } @@ -323,7 +326,9 @@ export function continuationStartRetryDelayMs( run: OrchestrationV2Run, projection: { readonly runs: ReadonlyArray; - readonly providerTurns: ReadonlyArray>; + readonly providerTurns: ReadonlyArray< + Pick + >; readonly turnItems: Parameters[1]; }, ): number | undefined { diff --git a/apps/server/src/orchestration-v2/RunExecutionService.test.ts b/apps/server/src/orchestration-v2/RunExecutionService.test.ts index a23a3fdf87bff..1d13620b75623 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.test.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.test.ts @@ -8,6 +8,7 @@ import { NodeId, type OrchestrationV2AppThread, type OrchestrationV2CheckpointScope, + type OrchestrationV2ContextHandoff, type OrchestrationV2DomainEvent, type OrchestrationV2ExecutionNode, type OrchestrationV2PendingBackgroundTask, @@ -3702,6 +3703,49 @@ it.effect.each([ }), ); +it.effect("restores dropped inline handoffs when ingestion fails before the terminal", () => + Effect.gen(function* () { + const key = "dropped-turn-ingest-error"; + const ids = backgroundScenarioIds(key); + const handoff = { id: `handoff:${key}` } as unknown as OrchestrationV2ContextHandoff; + const { finalEvents } = yield* captureRootRunTermination({ + key, + shouldFinalizeRun: () => Effect.succeed(true), + loadDroppedInlineHandoffs: () => Effect.succeed([handoff]), + events: () => + Stream.make({ + type: "provider_turn.updated" as const, + driver, + threadId: ids.threadId, + providerTurn: { + id: ids.rootProviderTurnId, + providerThreadId: ids.providerThreadId, + runAttemptId: ids.attemptId, + ordinal: 1, + status: "failed", + promptDropped: true, + } as OrchestrationV2ProviderTurn, + }), + ingestNormalized: ({ event }) => + event.type === "provider_turn.updated" + ? Effect.fail( + new ProviderEventIngestor.ProviderEventPublishError({ + providerSessionId: ProviderSessionId.make(`session:${key}`), + eventCount: 1, + cause: new Error("SQLITE_FULL: database or disk is full"), + }), + ) + : Effect.succeed([]), + }); + assert.deepEqual( + finalEvents.flatMap((event) => + event.type === "context-handoff.updated" ? [event.payload.id] : [], + ), + [handoff.id], + ); + }), +); + it.effect("does not interrupt a provider when ingestion fails before the root turn is known", () => Effect.gen(function* () { const interrupts = yield* Ref.make(0); @@ -3989,6 +4033,7 @@ function captureRootRunTermination(input: { readonly hasUnpairedRunInterruptRequest?: () => Effect.Effect; readonly hasWorkspaceMoved?: () => Effect.Effect; readonly loadRunInterruptReason?: () => Effect.Effect; + readonly loadDroppedInlineHandoffs?: RunExecutionService.RunExecutionServiceV2StartRootRunInput["loadDroppedInlineHandoffs"]; readonly hasPendingBackgroundWorkForThread?: ProviderAdapter.ProviderAdapterV2SessionRuntime["hasPendingBackgroundWorkForThread"]; readonly seedOpenSubagent?: boolean; readonly events?: ( @@ -4235,6 +4280,9 @@ function captureRootRunTermination(input: { ...(input.hasWorkspaceMoved === undefined ? {} : { hasWorkspaceMoved: input.hasWorkspaceMoved }), + ...(input.loadDroppedInlineHandoffs === undefined + ? {} + : { loadDroppedInlineHandoffs: input.loadDroppedInlineHandoffs }), message: { messageId: MessageId.make(`message:${input.key}`), text: input.messageText ?? "interrupt projection", diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.ts index 1bc83f639d5ae..34cc31f98fa09 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.ts @@ -9,6 +9,7 @@ import { type NodeId, type OrchestrationV2AppThread, type OrchestrationV2CheckpointScope, + type OrchestrationV2ContextHandoff, type OrchestrationV2DomainEvent, type OrchestrationV2ExecutionNode, type OrchestrationV2ProviderFailure, @@ -658,6 +659,11 @@ export interface RunExecutionServiceV2StartRootRunInput { readonly hasUnpairedRunInterruptRequest?: () => Effect.Effect; readonly loadRunInterruptReason?: () => Effect.Effect; readonly hasWorkspaceMoved?: () => Effect.Effect; + /** Restores inline context handoffs if the provider drops this turn's prompt before persisting it. */ + readonly loadDroppedInlineHandoffs?: () => Effect.Effect< + ReadonlyArray, + never + >; /** * Stored rows of a thread's unsettled work. Work a dead runtime left is ended from these, since * Stop may have settled it after the snapshots this run holds. @@ -736,6 +742,7 @@ export const layer: Layer.Layer< readonly abandonedProviderTurn?: OrchestrationV2ProviderTurn; // Stored root tool calls still open when the provider runtime was lost; nothing else ends them. readonly lostToolCalls?: ReadonlyArray; + readonly restoredHandoffs?: ReadonlyArray; readonly terminal: ProviderTerminalEvent; readonly completedAt?: DateTime.Utc; readonly failureItemPersisted: boolean; @@ -752,24 +759,35 @@ export const layer: Layer.Layer< status: input.terminal.status, completedAt, }; + const allocateEventId = () => idAllocator.allocate.event({ threadId: input.run.threadId }); + const buildRestoredHandoffEvents = () => + input.terminal.promptDropped === true && + input.restoredHandoffs !== undefined && + input.restoredHandoffs.length > 0 + ? Effect.forEach(input.restoredHandoffs, (handoff) => + Effect.map(allocateEventId(), (id) => ({ + id, + type: "context-handoff.updated" as const, + threadId: input.run.threadId, + runId: input.run.id, + providerInstanceId: input.run.providerInstanceId, + occurredAt: completedAt, + payload: { ...handoff, updatedAt: completedAt }, + })), + ) + : Effect.succeed([]); const shouldFinalizeRun = input.shouldFinalizeRun === undefined ? true : yield* input.shouldFinalizeRun(); if (!shouldFinalizeRun) { - if (input.terminal.status === "interrupted") { - const hasUnpairedRequest = - input.hasUnpairedRunInterruptRequest === undefined - ? false - : yield* input.hasUnpairedRunInterruptRequest(); - if (hasUnpairedRequest) { - const reason = - input.loadRunInterruptReason === undefined - ? undefined - : yield* input.loadRunInterruptReason(); - yield* eventSink.writeWithEffects({ - effects: [], - events: [ + const restoredHandoffEvents = yield* buildRestoredHandoffEvents(); + const unpairedInterruptEvents = + input.terminal.status === "interrupted" && + (input.hasUnpairedRunInterruptRequest === undefined + ? false + : yield* input.hasUnpairedRunInterruptRequest()) + ? [ { - id: yield* idAllocator.allocate.event({ threadId: input.run.threadId }), + id: yield* allocateEventId(), type: "turn-item.updated" as const, threadId: input.run.threadId, runId: input.run.id, @@ -781,18 +799,25 @@ export const layer: Layer.Layer< run: input.run, rootNode: input.rootNode, providerThread: input.providerThread, - reason, + reason: + input.loadRunInterruptReason === undefined + ? undefined + : yield* input.loadRunInterruptReason(), completedAt, }), }, - ], - }); - yield* input.refreshAfterTurn; - } + ] + : []; + const earlyEvents = [...unpairedInterruptEvents, ...restoredHandoffEvents]; + if (earlyEvents.length > 0) { + yield* eventSink.writeWithEffects({ + effects: [], + events: earlyEvents, + }); + yield* input.refreshAfterTurn; } return false; } - const allocateEventId = () => idAllocator.allocate.event({ threadId: input.run.threadId }); const reason = input.terminal.status === "interrupted" ? ((input.loadRunInterruptReason === undefined @@ -839,6 +864,7 @@ export const layer: Layer.Layer< status: finalProviderThreadStatus(input.terminal.threadDisposition), updatedAt: completedAt, }; + const restoredHandoffEvents = yield* buildRestoredHandoffEvents(); const runEventId = yield* allocateEventId(); const nodeEventId = yield* allocateEventId(); const providerThreadEventId = yield* allocateEventId(); @@ -1005,6 +1031,7 @@ export const layer: Layer.Layer< occurredAt: completedAt, payload: finalizedProviderThread, }, + ...restoredHandoffEvents, ], } satisfies Parameters[0]; if (input.writeIfRunCurrent !== undefined) { @@ -1031,6 +1058,13 @@ export const layer: Layer.Layer< effects: finalization.effects, }); if (!result.committed) { + if (restoredHandoffEvents.length > 0) { + yield* eventSink.writeWithEffects({ + effects: [], + events: restoredHandoffEvents, + }); + yield* input.refreshAfterTurn; + } return false; } } else { @@ -1275,44 +1309,55 @@ export const layer: Layer.Layer< } const providerThread = yield* Ref.get(latestProviderThread); const openSubagents = yield* Ref.get(openRunOwnedSubagents); - const writeTerminal = (settledTerminal: ProviderTerminalEvent) => - writeFinalRunEvents({ - run: input.run, - rootNode: input.rootNode, - checkpointScope: input.checkpointScope, - providerThread, - attempt: input.attempt, - ...(input.shouldFinalizeRun === undefined - ? {} - : { - shouldFinalizeRun: input.shouldFinalizeRun, - // Stop may commit between the ownership read and this - // terminal write. Gate the events and checkpoint together. - writeIfRunCurrent: { - activeAttemptId: input.attempt.id, - expectedStatus: "running" as const, - unlessInterruptRequested: settledTerminal !== terminal, - }, - }), - ...(input.hasUnpairedRunInterruptRequest === undefined - ? {} - : { - hasUnpairedRunInterruptRequest: input.hasUnpairedRunInterruptRequest, - }), - ...(input.loadRunInterruptReason === undefined - ? {} - : { loadRunInterruptReason: input.loadRunInterruptReason }), - openRunOwnedSubagents: openSubagents, - openRunOwnedSubagentsTerminal: terminal, - ...(abandonedProviderTurn === undefined ? {} : { abandonedProviderTurn }), - terminal: settledTerminal, - failureItemPersisted: settledTerminal.status === "failed", - refreshAfterTurn, - }).pipe( - Effect.mapError( - (cause) => new RunExecutionIngestError({ runId: input.run.id, cause }), + const writeTerminal = Effect.fnUntraced( + function* (settledTerminal: ProviderTerminalEvent) { + const restoredHandoffs = + settledTerminal.promptDropped === true && + input.loadDroppedInlineHandoffs !== undefined + ? yield* input.loadDroppedInlineHandoffs() + : undefined; + return yield* writeFinalRunEvents({ + run: input.run, + rootNode: input.rootNode, + checkpointScope: input.checkpointScope, + providerThread, + attempt: input.attempt, + ...(input.shouldFinalizeRun === undefined + ? {} + : { + shouldFinalizeRun: input.shouldFinalizeRun, + // Stop may commit between the ownership read and this + // terminal write. Gate the events and checkpoint together. + writeIfRunCurrent: { + activeAttemptId: input.attempt.id, + expectedStatus: "running" as const, + unlessInterruptRequested: settledTerminal !== terminal, + }, + }), + ...(input.hasUnpairedRunInterruptRequest === undefined + ? {} + : { + hasUnpairedRunInterruptRequest: input.hasUnpairedRunInterruptRequest, + }), + ...(input.loadRunInterruptReason === undefined + ? {} + : { loadRunInterruptReason: input.loadRunInterruptReason }), + openRunOwnedSubagents: openSubagents, + openRunOwnedSubagentsTerminal: terminal, + ...(abandonedProviderTurn === undefined ? {} : { abandonedProviderTurn }), + ...(restoredHandoffs === undefined ? {} : { restoredHandoffs }), + terminal: settledTerminal, + failureItemPersisted: settledTerminal.status === "failed", + refreshAfterTurn, + }); + }, + (effect) => + effect.pipe( + Effect.mapError( + (cause) => new RunExecutionIngestError({ runId: input.run.id, cause }), + ), ), - ); + ); // A workspace handoff detaches the session and stops the turn that asked // for it: the run completes, while its native subagents still settle // as interrupted. The completed write refuses in the same transaction @@ -2116,6 +2161,13 @@ export const layer: Layer.Layer< : null; const latestItemOrdinal = yield* Ref.get(latestTurnItemOrdinal); const openSubagents = yield* Ref.get(openRunOwnedSubagents); + const droppedPrompt = + (yield* Ref.get(terminalEvent))?.promptDropped === true || + rootProviderTurn?.promptDropped === true; + const recoveredHandoffs = + droppedPrompt && input.loadDroppedInlineHandoffs !== undefined + ? yield* input.loadDroppedInlineHandoffs() + : undefined; const lostToolCalls = runtimeLost ? yield* loadLostRootToolCalls.pipe( Effect.catchCauseIf( @@ -2141,18 +2193,24 @@ export const layer: Layer.Layer< }, openRunOwnedSubagents: openSubagents, ...(abandonedProviderTurn === null ? {} : { abandonedProviderTurn }), + ...(recoveredHandoffs === undefined + ? {} + : { restoredHandoffs: recoveredHandoffs }), lostToolCalls, completedAt, - terminal: makeFailedTerminalEvent( - makeProviderFailure({ - cause: squashed, - message: - knownProviderFailureMessage(squashed) ?? - userFacingDatabaseErrorMessage(squashed), - class: "unknown", - }), - latestItemOrdinal + 1, - ), + terminal: { + ...makeFailedTerminalEvent( + makeProviderFailure({ + cause: squashed, + message: + knownProviderFailureMessage(squashed) ?? + userFacingDatabaseErrorMessage(squashed), + class: "unknown", + }), + latestItemOrdinal + 1, + ), + ...(droppedPrompt ? { promptDropped: true as const } : {}), + }, failureItemPersisted: false, refreshAfterTurn, }).pipe( diff --git a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts index ee048c2100592..ddf9259622599 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts @@ -118,6 +118,7 @@ function makeTestAdapter(input: { readonly failure?: ReturnType; readonly rejectedNativeThreads?: Ref.Ref>; readonly failedRunOrdinals?: ReadonlySet; + readonly promptDroppedRunOrdinals?: ReadonlySet; readonly brokenRunOrdinals?: ReadonlySet; readonly interruptedRunOrdinals?: ReadonlySet; readonly cancelledRunOrdinals?: ReadonlySet; @@ -410,6 +411,9 @@ function makeTestAdapter(input: { status: terminalStatus, startedAt: eventTime, completedAt: eventTime, + ...(input.promptDroppedRunOrdinals?.has(turnInput.runOrdinal) + ? { promptDropped: true as const } + : {}), }, }, { @@ -462,6 +466,9 @@ function makeTestAdapter(input: { threadDisposition: input.brokenRunOrdinals?.has(turnInput.runOrdinal) ? "broken" : "reusable", + ...(input.promptDroppedRunOrdinals?.has(turnInput.runOrdinal) + ? { promptDropped: true as const } + : {}), }, ]; const reportedUsage = input.tokenUsageByRunOrdinal?.[turnInput.runOrdinal]; @@ -6400,4 +6407,166 @@ describe("orchestration v2 provider switching", () => { ); }), ); + + it.effect.each([ + "same-provider-retry", + "cancelled-dropped", + "switch-away-and-return", + "persisted-failure", + ] as const)("handles an inline context handoff after a failed returning turn (%s)", (variant) => + Effect.gen(function* () { + const cwd = yield* checkpointWorkspace(`dropped-handoff-${variant}`); + const capturedTurns = yield* Ref.make>([]); + const dropped = variant !== "persisted-failure"; + const cancelled = variant === "cancelled-dropped"; + const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([ + makeTestAdapter({ + instanceId: CODEX_MODEL_SELECTION.instanceId, + driver: CODEX_DRIVER, + capabilities: CodexProviderCapabilitiesV2, + modelSelection: CODEX_MODEL_SELECTION, + responseByRunOrdinal: { + 1: "Morning Codex summary.", + 3: "", + 4: "Recovered Codex answer.", + 5: "Recovered Codex after round-trip.", + }, + capturedTurns, + ...(cancelled + ? { cancelledRunOrdinals: new Set([3]) } + : { failedRunOrdinals: new Set([3]) }), + ...(dropped ? { promptDroppedRunOrdinals: new Set([3]) } : {}), + }), + makeTestAdapter({ + instanceId: CLAUDE_MODEL_SELECTION.instanceId, + driver: CLAUDE_DRIVER, + capabilities: ClaudeProviderCapabilitiesV2, + modelSelection: CLAUDE_MODEL_SELECTION, + responseByRunOrdinal: { + 2: "Afternoon Claude shipped b63 live draft.", + 4: "Extra Claude turn after dropped handoff.", + }, + capturedTurns, + }), + ]); + + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const testThreadId = ThreadId.make(`thread:dropped-handoff:${variant}`); + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`command:dropped-handoff:${variant}:create`), + threadId: testThreadId, + projectId, + title: `Dropped handoff ${variant}`, + modelSelection: CODEX_MODEL_SELECTION, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: cwd, + }); + let step = 0; + const send = (text: string, modelSelection: ModelSelection) => + Effect.gen(function* () { + step += 1; + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`command:dropped-handoff:${variant}:msg-${step}`), + threadId: testThreadId, + messageId: MessageId.make(`message:dropped-handoff:${variant}:${step}`), + text, + attachments: [], + modelSelection, + dispatchMode: { type: "start_immediately" }, + }); + yield* worker.drain(); + yield* waitForIdle(testThreadId); + yield* worker.drain(); + return yield* orchestrator.getThreadProjection(testThreadId); + }); + + // Run 1: establish native session on Codex. + yield* send("Morning task", CODEX_MODEL_SELECTION); + // Run 2: switch to Claude and do real work. + yield* send("Build live draft b63", CLAUDE_MODEL_SELECTION); + // Run 3: switch back to Codex (delta handoff covering run 2); fails. + const afterRun3 = yield* send("Resume after failure", CODEX_MODEL_SELECTION); + const run3 = afterRun3.runs.find((run) => run.ordinal === 3)!; + assert.equal(run3.status, cancelled ? "cancelled" : "failed"); + const run3Handoff = afterRun3.contextHandoffs.find( + (handoff) => handoff.targetRunId === run3.id, + ); + assert.isDefined(run3Handoff); + assert.deepEqual(run3Handoff?.coveredRunOrdinals, { from: 2, to: 2 }); + + if (dropped) { + assert.isUndefined( + run3Handoff?.delivery, + "dropping the failed prompt must clear inline handoff delivery", + ); + const run3Turn = afterRun3.providerTurns.find( + (turn) => turn.runAttemptId === run3.activeAttemptId, + ); + assert.equal(run3Turn?.promptDropped, true); + } else { + assert.equal(run3Handoff?.delivery?.status, "inline"); + } + + if (variant === "same-provider-retry" || variant === "cancelled-dropped") { + // Run 4: stay on Codex; must re-deliver run 2's handoff. + const afterRun4 = yield* send("Resume", CODEX_MODEL_SELECTION); + const turns = yield* Ref.get(capturedTurns); + const run4Turn = turns.at(-1)!; + assert.include(run4Turn.text, "Afternoon Claude shipped b63 live draft."); + assert.include(run4Turn.text, "Resume after failure"); + assert.include(run4Turn.text, "User message:\nResume"); + const updatedHandoff = afterRun4.contextHandoffs.find( + (handoff) => handoff.id === run3Handoff!.id, + ); + assert.equal(updatedHandoff?.delivery?.status, "inline"); + } else if (variant === "switch-away-and-return") { + // Run 4: bounce back to Claude, then Run 5: return to Codex. + yield* send("Continue on Claude", CLAUDE_MODEL_SELECTION); + const afterRun5 = yield* send("Back to Codex", CODEX_MODEL_SELECTION); + const run5 = afterRun5.runs.find((run) => run.ordinal === 5)!; + const run5Handoff = afterRun5.contextHandoffs.find( + (handoff) => handoff.targetRunId === run5.id, + ); + assert.isDefined(run5Handoff); + assert.deepEqual(run5Handoff?.coveredRunOrdinals, { from: 2, to: 4 }); + const run5Turn = (yield* Ref.get(capturedTurns)).at(-1)!; + assert.include(run5Turn.text, "Afternoon Claude shipped b63 live draft."); + assert.include(run5Turn.text, "Extra Claude turn after dropped handoff."); + } else { + // Control: run 3 persisted its prompt before failing, so run 4 must not re-send run 2. + yield* send("Resume", CODEX_MODEL_SELECTION); + const run4Turn = (yield* Ref.get(capturedTurns)).at(-1)!; + assert.notInclude(run4Turn.text, "Afternoon Claude shipped b63 live draft."); + } + }).pipe( + Effect.provide( + ProviderReplayHarness.layerWithRegistry( + { + name: `dropped-handoff-${variant}`, + runtimePolicyOverride: { + cwd, + approvalPolicy: "never", + sandboxPolicy: { + type: "readOnly", + access: { type: "fullAccess" }, + networkAccess: false, + }, + }, + }, + layerRegistry, + ), + ), + ); + }), + ); }); diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 2d5bc546d1800..8b05c12e17871 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -1334,9 +1334,17 @@ export const OrchestrationV2ProviderTurn = Schema.Struct({ turnTokenUsage: Schema.optional(TurnTokenUsage), /** The model the provider reported running this turn's root agent, which can differ from the requested one. */ model: Schema.optional(TrimmedNonEmptyString), + /** True when the provider dropped this turn's request before persisting it to native history. */ + promptDropped: Schema.optional(Schema.Literal(true)), }); export type OrchestrationV2ProviderTurn = typeof OrchestrationV2ProviderTurn.Type; +export function isDeliveredProviderTurn( + turn: Pick, +): boolean { + return turn.promptDropped !== true; +} + /** Codex goals can span multiple native turns within one attempt. */ export function latestProviderTurnForAttempt< Turn extends Pick, diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.ts index 18ebf74baa1c7..c0bf5156acb97 100644 --- a/packages/provider-core/src/server/ProviderAdapter.ts +++ b/packages/provider-core/src/server/ProviderAdapter.ts @@ -202,6 +202,8 @@ export const ProviderAdapterV2Event = Schema.Union([ failure: Schema.Null, reason: Schema.optional(Schema.String), threadDisposition: Schema.Literals(["reusable", "broken"]), + /** The provider dropped this turn's request before persisting it to native history. */ + promptDropped: Schema.optional(Schema.Literal(true)), retainedRuntimeRequestIds: Schema.optional(Schema.Array(RuntimeRequestId)), }), Schema.Struct({ @@ -216,6 +218,8 @@ export const ProviderAdapterV2Event = Schema.Union([ retry: Schema.optional(OrchestrationV2ProviderRetry), retryStartedAt: Schema.optional(Schema.DateTimeUtc), threadDisposition: Schema.Literals(["reusable", "broken"]), + /** The provider dropped this turn's request before persisting it to native history. */ + promptDropped: Schema.optional(Schema.Literal(true)), /** Child turns outlive root failure and report their own terminals; otherwise open children settle. */ childTurnsContinue: Schema.optional(Schema.Literal(true)), retainedRuntimeRequestIds: Schema.optional(Schema.Array(RuntimeRequestId)), diff --git a/packages/provider-cursor/src/server/adapter.test.ts b/packages/provider-cursor/src/server/adapter.test.ts index 5c0a1940d671c..dfa1ac4865269 100644 --- a/packages/provider-cursor/src/server/adapter.test.ts +++ b/packages/provider-cursor/src/server/adapter.test.ts @@ -756,6 +756,149 @@ describe("CursorAdapterV2", () => { ), ); + it.effect("marks failed turns as promptDropped only when Cursor did not checkpoint the run", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const workspace = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "cursor-v2-dropped-", + }); + const checkpointedRuns = new Set(); + let sendCalls = 0; + const instanceId = ProviderInstanceId.make("cursor"); + const threadId = ThreadId.make("cursor-dropped-thread"); + const modelSelection = { instanceId, model: "gemini-4-neon" }; + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: workspace, + }); + const adapter = yield* makeCursorAdapterV2({ + instanceId, + environment: { HOME: workspace }, + }).pipe( + Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, { + assertComplete: Effect.void, + open: () => + Effect.succeed({ + agentId: "native-cursor-dropped", + listMessages: Effect.succeed([]), + close: Effect.void, + runCheckpointed: (runId) => + Effect.succeed(runId !== undefined && checkpointedRuns.has(runId)), + send: () => + Effect.sync(() => { + sendCalls += 1; + const runId = `native-cursor-run-${sendCalls}`; + return { + agentId: "native-cursor-dropped", + runId, + cancel: Effect.void, + wait: Effect.succeed({ + id: runId, + status: "error" as const, + error: { + message: + 'AI Model Not Found Invalid parameters for registry model: "gemini-4-neon"', + }, + }), + }; + }), + }), + textGenerate: () => Effect.die("unused"), + }), + Effect.provide(TestProviderHost.layer({ cwd: workspace })), + ); + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("cursor-dropped-session"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const now = yield* DateTime.now; + const appThread = { + id: threadId, + projectId: ProjectId.make("cursor-dropped-project"), + createdBy: "user" as const, + creationSource: "web" as const, + title: "Cursor dropped prompt", + providerInstanceId: instanceId, + modelSelection, + runtimeMode: "full-access" as const, + interactionMode: "default" as const, + branch: null, + worktreePath: null, + activeProviderThreadId: providerThread.id, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }; + const runFailed = (ordinal: number) => + Effect.gen(function* () { + yield* runtime.startTurn({ + threadId, + providerThread, + modelSelection, + runtimePolicy, + runId: RunId.make(`cursor-dropped-run-${ordinal}`), + runOrdinal: ordinal, + providerTurnOrdinal: ordinal, + attemptId: RunAttemptId.make(`cursor-dropped-attempt-${ordinal}`), + rootNodeId: NodeId.make(`cursor-dropped-root-${ordinal}`), + appThread, + message: { + messageId: MessageId.make(`cursor-dropped-message-${ordinal}`), + createdBy: "user", + creationSource: "web", + text: "Resume", + attachments: [], + }, + }); + const events = yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ); + const terminal = events.find((event) => event.type === "turn.terminal"); + const turn = events.findLast( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.completedAt !== null, + ); + return { + terminal: terminal?.type === "turn.terminal" ? terminal : undefined, + turn: turn?.type === "provider_turn.updated" ? turn.providerTurn : undefined, + }; + }); + + // Uncheckpointed failure: Cursor never persisted the prompt. + const uncheckpointed = yield* runFailed(1); + assert.equal(uncheckpointed.terminal?.status, "failed"); + assert.equal(uncheckpointed.terminal?.promptDropped, true); + assert.equal(uncheckpointed.turn?.promptDropped, true); + + // Checkpointed failure: Cursor kept the run's prompt in its store. + checkpointedRuns.add("native-cursor-run-2"); + const checkpointed = yield* runFailed(2); + assert.equal(checkpointed.terminal?.status, "failed"); + assert.isUndefined(checkpointed.terminal?.promptDropped); + assert.isUndefined(checkpointed.turn?.promptDropped); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer), + ), + ), + ); + it.effect("sends T3 instructions to each Cursor conversation that lacks them", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; diff --git a/packages/provider-cursor/src/server/adapter.ts b/packages/provider-cursor/src/server/adapter.ts index 7aadadaf9ddd4..b4dd1033c2a9f 100644 --- a/packages/provider-cursor/src/server/adapter.ts +++ b/packages/provider-cursor/src/server/adapter.ts @@ -2510,6 +2510,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( readonly status: OrchestrationV2ProviderTurn["status"]; readonly completedAt: DateTime.Utc | null; readonly tokenUsage?: OrchestrationV2ProviderTurn["tokenUsage"]; + readonly promptDropped?: true; }): OrchestrationV2ProviderTurn => ({ id: input.context.providerTurnId, providerThreadId: input.context.input.providerThread.id, @@ -2525,6 +2526,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( startedAt: input.context.startedAt, completedAt: input.completedAt, ...(input.tokenUsage === undefined ? {} : { tokenUsage: input.tokenUsage }), + ...(input.promptDropped === true ? { promptDropped: true as const } : {}), ...(input.completedAt === null || input.context.usage === undefined ? {} : { @@ -2590,6 +2592,15 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( }).pipe(Effect.as(undefined)), ), ); + // Cursor only keeps a run in conversation history once it saves its first checkpoint. + const promptDropped = + (input.status === "failed" || input.status === "cancelled") && + !input.context.compacted && + input.context.prompt !== undefined && + !(yield* ( + input.context.session.runCheckpointed?.(input.context.run.runId) ?? + Effect.succeed(false) + ).pipe(Effect.orElseSucceed(() => false))); yield* emitProviderEvent({ type: "provider_turn.updated", driver: CursorAgentSdk.CURSOR_PROVIDER, @@ -2597,6 +2608,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( context: input.context, status: input.status, completedAt, + ...(promptDropped ? { promptDropped: true as const } : {}), ...(contextUsage === undefined ? {} : { @@ -2633,6 +2645,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( status: input.status, failure: input.failure ?? makeProviderFailure({ class: "provider_error" }), threadDisposition, + ...(promptDropped ? { promptDropped: true as const } : {}), } : { type: "turn.terminal", @@ -2643,6 +2656,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( status: input.status, failure: null, threadDisposition, + ...(promptDropped ? { promptDropped: true as const } : {}), }, ); if (input.context.runtimeInstructions !== undefined) { diff --git a/packages/shared/src/orchestrationV2ManualContinuation.test.ts b/packages/shared/src/orchestrationV2ManualContinuation.test.ts index 137bf6cd8f205..e7670749f6c5a 100644 --- a/packages/shared/src/orchestrationV2ManualContinuation.test.ts +++ b/packages/shared/src/orchestrationV2ManualContinuation.test.ts @@ -108,4 +108,16 @@ describe("unsentManualContinuationSource", () => { unsentManualContinuationSource(run("c", "a" as RunId), projection([a, b], [], [])), ).toBeUndefined(); }); + + it("treats a turn with promptDropped as unsent", () => { + const source = run("src"); + const a1 = attempt("a1", "src", 1); + const dropped = { ...turn("a1"), promptDropped: true as const }; + expect( + unsentManualContinuationSource( + run("r2", "src" as RunId), + projection([source], [a1], [dropped]), + ), + ).toBe(source); + }); }); diff --git a/packages/shared/src/orchestrationV2ManualContinuation.ts b/packages/shared/src/orchestrationV2ManualContinuation.ts index 3fb6c8d5a1866..ad64b63483e14 100644 --- a/packages/shared/src/orchestrationV2ManualContinuation.ts +++ b/packages/shared/src/orchestrationV2ManualContinuation.ts @@ -1,4 +1,8 @@ -import type { OrchestrationV2Run, OrchestrationV2ThreadProjection } from "@t3tools/contracts"; +import { + isDeliveredProviderTurn, + type OrchestrationV2Run, + type OrchestrationV2ThreadProjection, +} from "@t3tools/contracts"; export function unsentManualContinuationSource( run: Pick | undefined, @@ -7,7 +11,9 @@ export function unsentManualContinuationSource( let sourceId = run?.manualContinuationOfRunId; if (sourceId === undefined) return undefined; const runs = new Map(projection.runs.map((source) => [source.id, source])); - const acceptedAttempts = new Set(projection.providerTurns.map((turn) => turn.runAttemptId)); + const acceptedAttempts = new Set( + projection.providerTurns.filter(isDeliveredProviderTurn).map((turn) => turn.runAttemptId), + ); const latestAttempt = ( runId: OrchestrationV2Run["id"], matches: (attempt: (typeof projection.attempts)[number]) => boolean, From 0fb6ac6e65cced6201247705b304170010e37a78 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 21:47:07 -0800 Subject: [PATCH 101/324] perf(web): Markdown renders with Words as static islands under one shared tooltip; remark leaves the web app (#27866) Co-authored-by: Claude Opus 5.5 Co-authored-by: Yash Singh Co-authored-by: Cursor Co-authored-by: Gemini 4 Neon Co-authored-by: Noah Sigel --- .pnpmfile.cjs | 26 +- .../pull-requests/PullRequestDescription.tsx | 4 +- .../pull-requests/PullRequestMarkdown.tsx | 8 +- .../pullRequestAutolinks.test.ts | 2 +- .../pullRequestDescriptionContent.test.ts | 4 +- .../usePullRequestDescription.ts | 2 +- apps/mobile/src/lib/composerContext.test.ts | 13 +- apps/mobile/src/lib/composerContext.ts | 10 +- .../src/native/T3ComposerEditor.ios.tsx | 4 +- .../src/native/T3ComposerEditor.native.tsx | 4 +- apps/web/deps/README.md | 15 + .../deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz | Bin 0 -> 219310 bytes apps/web/package.json | 13 +- .../components/ChatMarkdown.browser.test.tsx | 99 +- apps/web/src/components/ChatMarkdown.tsx | 495 ++++--- .../chat/ChatMarkdownMedia.browser.test.tsx | 13 +- .../chat/MarkdownCodeBlock.logic.ts | 10 +- .../src/components/chat/MarkdownCodeBlock.tsx | 122 +- .../src/components/chat/MarkdownDetails.tsx | 39 + .../src/components/chat/MarkdownFileLink.tsx | 135 +- .../chat/MarkdownMath.browser.test.tsx | 36 - apps/web/src/components/chat/MarkdownMath.tsx | 81 -- .../components/chat/MathTypeset.logic.test.ts | 30 - .../src/components/chat/MathTypeset.logic.ts | 39 - apps/web/src/components/chat/MathTypeset.tsx | 49 - .../chat/MessagesTimeline.browser.test.tsx | 64 +- .../components/chat/MessagesTimeline.logic.ts | 2 +- .../components/chat/TimelineAssistantRows.tsx | 2 +- .../chat/TimelineUserMessageRow.tsx | 12 +- .../chat/TimelineWorkEntryRow.logic.ts | 74 +- .../components/chat/TimelineWorkEntryRow.tsx | 8 +- .../components/chat/TimelineWorkGroupRows.tsx | 10 +- .../components/chat/markdownIslands.test.ts | 50 + .../src/components/chat/markdownIslands.ts | 214 +++ .../components/chat/markdownRenderer.test.tsx | 85 +- .../src/components/chat/markdownRenderer.ts | 76 +- ....test.tsx => markdownStreamBlocks.test.ts} | 33 +- .../components/chat/markdownSyntaxGates.ts | 204 --- .../components/chat/markdownTextDirection.ts | 33 +- .../components/chat/threadFindHighlights.ts | 2 +- .../components/chat/timelineMinimapItems.ts | 64 +- .../src/components/files/FilePreviewPanel.tsx | 2 +- .../src/components/files/NotebookPreview.tsx | 23 +- .../pullRequest/PullRequestDetailPanel.tsx | 4 +- .../PullRequestMarkdown.browser.test.tsx | 2 +- .../pullRequest/PullRequestMarkdown.tsx | 6 +- .../pullRequest/PullRequestSummaryTab.tsx | 2 +- .../pullRequestDetail.logic.test.ts | 9 + .../pullRequest/pullRequestDetail.logic.ts | 31 +- .../pullRequestMarkdown.logic.test.ts | 86 +- .../pullRequest/pullRequestMarkdown.logic.ts | 154 +- .../src/components/settings/settingsSearch.ts | 1 + apps/web/src/components/ui/shared-tooltip.tsx | 262 ++++ .../components/ui/tooltip.browser.test.tsx | 131 +- apps/web/src/components/ui/tooltip.tsx | 28 +- apps/web/src/composer-editor-mentions.ts | 5 +- apps/web/src/composer-rich-text-doc.ts | 3 +- apps/web/src/i18n/translations/de.json | 5 - apps/web/src/i18n/translations/en.json | 5 - apps/web/src/i18n/translations/es.json | 5 - apps/web/src/i18n/translations/fr.json | 5 - apps/web/src/i18n/translations/ja.json | 5 - apps/web/src/i18n/translations/ko.json | 5 - apps/web/src/i18n/translations/pt-BR.json | 5 - apps/web/src/i18n/translations/ru.json | 5 - apps/web/src/i18n/translations/sv.json | 5 - apps/web/src/i18n/translations/zh.json | 5 - apps/web/src/index.css | 13 +- apps/web/src/markdown-clipboard.test.ts | 128 +- apps/web/src/markdown-clipboard.ts | 4 +- apps/web/src/markdown-incremental.test.tsx | 135 -- apps/web/src/markdown-incremental.ts | 98 -- apps/web/src/markdown-links.ts | 39 + apps/web/src/markdown/markdownText.ts | 68 + apps/web/src/markdown/wordsHast.test.ts | 403 +++++ apps/web/src/markdown/wordsHast.ts | 1296 +++++++++++++++++ packages/client-runtime/package.json | 12 +- .../src/pullRequestMarkdown.test.ts | 80 +- .../client-runtime/src/pullRequestMarkdown.ts | 71 +- .../src/pullRequestReferences.ts | 30 + packages/shared/package.json | 19 + packages/shared/src/assistantInsights.ts | 3 + packages/shared/src/codexArtifactTemplates.ts | 26 + .../shared/src/codexMarkdownDirectives.ts | 26 - .../shared/src/composerInlineTokens.test.ts | 18 +- packages/shared/src/composerInlineTokens.ts | 15 +- .../shared/src/markdownGithubAlerts.test.ts | 19 +- packages/shared/src/markdownHast.ts | 211 +++ packages/shared/src/markdownLinks.ts | 3 + .../src/markdownListIndentation.test.ts | 23 +- packages/shared/src/markdownPipeline.ts | 212 +-- packages/shared/src/markdownTaskEdits.ts | 28 + packages/shared/src/markdownTaskList.test.ts | 3 +- packages/shared/src/markdownTaskList.ts | 31 +- packages/shared/src/markdownWindowsPaths.ts | 4 +- packages/shared/src/textDirection.ts | 4 +- packages/shared/src/threadFindBlockTags.ts | 38 + packages/shared/src/threadFindText.ts | 47 +- pnpm-lock.yaml | 109 +- scripts/check-changed.ts | 3 +- scripts/release-smoke.ts | 11 +- 101 files changed, 3959 insertions(+), 2256 deletions(-) create mode 100644 apps/web/deps/README.md create mode 100644 apps/web/deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz delete mode 100644 apps/web/src/components/chat/MarkdownMath.browser.test.tsx delete mode 100644 apps/web/src/components/chat/MarkdownMath.tsx delete mode 100644 apps/web/src/components/chat/MathTypeset.logic.test.ts delete mode 100644 apps/web/src/components/chat/MathTypeset.logic.ts delete mode 100644 apps/web/src/components/chat/MathTypeset.tsx create mode 100644 apps/web/src/components/chat/markdownIslands.test.ts create mode 100644 apps/web/src/components/chat/markdownIslands.ts rename apps/web/src/components/chat/{markdownStreamBlocks.test.tsx => markdownStreamBlocks.test.ts} (81%) delete mode 100644 apps/web/src/components/chat/markdownSyntaxGates.ts create mode 100644 apps/web/src/components/ui/shared-tooltip.tsx delete mode 100644 apps/web/src/markdown-incremental.test.tsx delete mode 100644 apps/web/src/markdown-incremental.ts create mode 100644 apps/web/src/markdown/markdownText.ts create mode 100644 apps/web/src/markdown/wordsHast.test.ts create mode 100644 apps/web/src/markdown/wordsHast.ts create mode 100644 packages/client-runtime/src/pullRequestReferences.ts create mode 100644 packages/shared/src/assistantInsights.ts rename apps/web/src/markdownGithubAlerts.test.tsx => packages/shared/src/markdownGithubAlerts.test.ts (70%) create mode 100644 packages/shared/src/markdownHast.ts rename apps/web/src/markdownListIndentation.test.tsx => packages/shared/src/markdownListIndentation.test.ts (72%) create mode 100644 packages/shared/src/markdownTaskEdits.ts create mode 100644 packages/shared/src/threadFindBlockTags.ts diff --git a/.pnpmfile.cjs b/.pnpmfile.cjs index 87a153f7b030d..8e79fceda4142 100644 --- a/.pnpmfile.cjs +++ b/.pnpmfile.cjs @@ -1,16 +1,22 @@ const fs = require("node:fs"); const path = require("node:path"); -// Our forks ship as tarballs in apps/mobile/deps. A pnpm patch on one is a second source of -// truth that the next tarball silently drops, so changes go to the fork (apps/mobile/deps/README.md). +// Our forks ship as tarballs in apps/mobile/deps and apps/web/deps. A pnpm patch on one is a +// second source of truth that the next tarball silently drops, so changes go to the fork (see +// the README beside each tarball). +const FORK_APPS = ["apps/mobile", "apps/web"]; + function forkTarballPatches(patchedDependencies) { - const manifestPath = path.join(__dirname, "apps/mobile/package.json"); - // Release staging installs a partial workspace without the mobile app. - if (!patchedDependencies || !fs.existsSync(manifestPath)) return []; - const { dependencies = {} } = JSON.parse(fs.readFileSync(manifestPath, "utf8")); - const forks = Object.keys(dependencies).filter((name) => - String(dependencies[name]).startsWith("file:deps/"), - ); + if (!patchedDependencies) return []; + const forks = FORK_APPS.flatMap((app) => { + const manifestPath = path.join(__dirname, app, "package.json"); + // Release staging installs a partial workspace without every app. + if (!fs.existsSync(manifestPath)) return []; + const { dependencies = {} } = JSON.parse(fs.readFileSync(manifestPath, "utf8")); + return Object.keys(dependencies).filter((name) => + String(dependencies[name]).startsWith("file:deps/"), + ); + }); return Object.keys(patchedDependencies).filter((key) => forks.some((name) => key === name || key.startsWith(`${name}@`)), ); @@ -23,7 +29,7 @@ module.exports = { if (forkPatches.length > 0) { throw new Error( `pnpm-workspace.yaml patches ${forkPatches.join(", ")}, which ships as a fork tarball in ` + - "apps/mobile/deps. Change the fork and replace the tarball instead (apps/mobile/deps/README.md).", + "an app's deps directory. Change the fork and replace the tarball instead (deps/README.md).", ); } // Windows installs need Linux x64 glibc binaries because WSL shares node_modules. diff --git a/apps/mobile/src/features/pull-requests/PullRequestDescription.tsx b/apps/mobile/src/features/pull-requests/PullRequestDescription.tsx index 3251cb8773f03..f0604d6b4ceb6 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestDescription.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestDescription.tsx @@ -10,7 +10,7 @@ import { useContext, useMemo, useState, type ComponentProps, type ReactNode } fr import { Platform, Pressable, ScrollView, StyleSheet, View } from "react-native"; import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg"; import { pullRequestImageSource } from "./pullRequestMediaSource"; -import { parseMarkdownDocument } from "../../lib/markdownDocument"; +import { markdownReferenceDefinitions, parseMarkdownDocument } from "../../lib/markdownDocument"; import { SymbolView } from "../../components/ui/AppSymbol"; import { AppText as Text } from "../../components/ui/AppText"; import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider"; @@ -44,7 +44,7 @@ export function PullRequestDescription(props: { const document = parseMarkdownDocument(props.markdown); const content = pullRequestDescriptionContent( document, - splitPullRequestBody(props.markdown), + splitPullRequestBody(props.markdown, markdownReferenceDefinitions), messages, ); return { diff --git a/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx b/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx index 3654cfd87bb42..c1852a6ee2601 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx @@ -17,7 +17,7 @@ import { createContext, useContext, useMemo, useState } from "react"; import { changeRequestReferenceAutolinker, resolveChangeRequestMediaUrl, -} from "@t3tools/client-runtime/pull-request-markdown"; +} from "@t3tools/client-runtime/pull-request-references"; import { sourceControlClients, type ReferenceAutolink, @@ -28,6 +28,7 @@ import { useOpenPullRequest } from "../../native/useOpenPullRequest"; import { SelectableMarkdownText } from "../../native/SelectableMarkdownText"; import { useMarkdownPreviewStyles } from "../files/FileMarkdownPreview"; import { markdownImageSources } from "../../lib/markdownImageSources"; +import { markdownReferenceDefinitions } from "../../lib/markdownDocument"; import { FilePreviewGallery, useFilePreviewGallery } from "../../components/ui/FilePreviewGallery"; import { pullRequestImageSource } from "./pullRequestMediaSource"; import { @@ -124,7 +125,10 @@ export function PullRequestMarkdown(props: { }) { const mediaContext = useContext(PullRequestMediaContext); const changeRequestUrl = useContext(ChangeRequestUrlContext); - const segments = useMemo(() => splitPullRequestBody(props.markdown), [props.markdown]); + const segments = useMemo( + () => splitPullRequestBody(props.markdown, markdownReferenceDefinitions), + [props.markdown], + ); const [undoneTicks, setUndoneTicks] = useState(0); const gallery: FilePreviewItem[] = markdownImageSources( props.imageGroupMarkdown ?? props.markdown, diff --git a/apps/mobile/src/features/pull-requests/pullRequestAutolinks.test.ts b/apps/mobile/src/features/pull-requests/pullRequestAutolinks.test.ts index 6500a79885a8d..7acb1640694f7 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestAutolinks.test.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestAutolinks.test.ts @@ -1,4 +1,4 @@ -import { changeRequestReferenceAutolinker } from "@t3tools/client-runtime/pull-request-markdown"; +import { changeRequestReferenceAutolinker } from "@t3tools/client-runtime/pull-request-references"; import { describe, expect, it } from "vite-plus/test"; import { nativePullRequestMarkdown } from "./pullRequestAutolinks"; diff --git a/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.test.ts b/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.test.ts index 6d6a1bfe4b624..74e21d39018ee 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.test.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vite-plus/test"; -import type { MarkdownNode } from "../../lib/markdownDocument"; +import { markdownReferenceDefinitions, type MarkdownNode } from "../../lib/markdownDocument"; import { splitPullRequestBody } from "@t3tools/client-runtime/pull-request-markdown"; import { pullRequestDescriptionContent } from "./pullRequestDescriptionContent"; @@ -15,6 +15,7 @@ describe("PR attachments", () => { } as MarkdownNode; const media = splitPullRequestBody( `${uri}\n\nhttps://drop.example.com/demo.mp4\n\nhttps://github.com/user-attachments/assets/123-abc`, + markdownReferenceDefinitions, ); expect(pullRequestDescriptionContent(document, media).attachments).toEqual([ { uri, caption: "Screenshot", kind: "image" }, @@ -30,6 +31,7 @@ describe("PR attachments", () => { it("collects videos from a before/after table", () => { const media = splitPullRequestBody( "\n\n\n
    BeforeAfter
    \n\nhttps://drop.example.com/before.mp4\n\n\n\nhttps://drop.example.com/after.mp4\n\n
    ", + markdownReferenceDefinitions, ); expect( pullRequestDescriptionContent({ type: "root" } as MarkdownNode, media).attachments, diff --git a/apps/mobile/src/features/pull-requests/usePullRequestDescription.ts b/apps/mobile/src/features/pull-requests/usePullRequestDescription.ts index 105f4a1095009..5758e6b2ee84a 100644 --- a/apps/mobile/src/features/pull-requests/usePullRequestDescription.ts +++ b/apps/mobile/src/features/pull-requests/usePullRequestDescription.ts @@ -8,7 +8,7 @@ import { } from "@t3tools/client-runtime/pull-request-editing"; import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import type { PullRequestDetail } from "@t3tools/contracts"; -import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskList"; +import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskEdits"; import { AsyncResult } from "effect/reactivity"; import { useGT } from "gt-react-native"; import { useRef, useState } from "react"; diff --git a/apps/mobile/src/lib/composerContext.test.ts b/apps/mobile/src/lib/composerContext.test.ts index e2a5a015c61af..255666ebcf0b2 100644 --- a/apps/mobile/src/lib/composerContext.test.ts +++ b/apps/mobile/src/lib/composerContext.test.ts @@ -8,6 +8,7 @@ import { type ServerProviderSkill, } from "@t3tools/contracts"; import { collectComposerInlineTokens } from "@t3tools/shared/composerInlineTokens"; +import { markdownMathRanges } from "@t3tools/shared/markdownMath"; import { serializeAssistantCitation } from "@t3tools/shared/assistantCitations"; import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT, @@ -167,7 +168,7 @@ describe("mobile composer context", () => { const modelTokens = (text: string) => composerContextEditorTokens( text, - collectComposerInlineTokens(text), + collectComposerInlineTokens(text, { findMath: markdownMathRanges }), new Set(), collectComposerModelTokens(text, known), ) @@ -256,7 +257,7 @@ describe("mobile composer context", () => { const skills = [babysit, disabled, agentOnly]; const tokens = composerContextEditorTokens( text, - collectComposerInlineTokens(text), + collectComposerInlineTokens(text, { findMath: markdownMathRanges }), composerSkillLabels(skills), ); expect(tokens.map((token) => token.source)).toEqual([ @@ -271,14 +272,14 @@ describe("mobile composer context", () => { expect( composerContextEditorTokens( text, - collectComposerInlineTokens(text), + collectComposerInlineTokens(text, { findMath: markdownMathRanges }), composerSkillLabels([]), ).map((token) => token.type), ).toEqual(["mention", "context", "context", "citation", "citation"]); expect( composerContextEditorTokens( text, - collectComposerInlineTokens(text), + collectComposerInlineTokens(text, { findMath: markdownMathRanges }), composerSkillLabels([{ ...babysit, name: "HOME" }]), ) .filter((token) => token.type === "skill") @@ -292,7 +293,7 @@ describe("mobile composer context", () => { expect( composerContextEditorTokens( text, - collectComposerInlineTokens(text), + collectComposerInlineTokens(text, { findMath: markdownMathRanges }), composerSkillLabels(promoted), ) .filter((token) => token.type === "skill") @@ -301,7 +302,7 @@ describe("mobile composer context", () => { expect( composerContextEditorTokens( text, - collectComposerInlineTokens(text), + collectComposerInlineTokens(text, { findMath: markdownMathRanges }), composerSkillLabels(skills), ) .filter((token) => token.type === "skill") diff --git a/apps/mobile/src/lib/composerContext.ts b/apps/mobile/src/lib/composerContext.ts index 754774c4f1306..219a61108fd51 100644 --- a/apps/mobile/src/lib/composerContext.ts +++ b/apps/mobile/src/lib/composerContext.ts @@ -40,6 +40,7 @@ import { composerMathRanges, type ComposerInlineToken, } from "@t3tools/shared/composerInlineTokens"; +import { markdownMathRanges } from "@t3tools/shared/markdownMath"; const isMessageContext = Schema.is(OrchestrationMessageContext); const decodeMessageContext = Schema.decodeUnknownOption(OrchestrationMessageContext); @@ -73,7 +74,7 @@ export function composerMentionPath(source: string, context?: OrchestrationMessa const record = context?.records.find((entry) => entry.contextId === reference.contextId); return record?.kind === "mention" && "path" in record ? record.path : null; } - const token = collectComposerInlineTokens(`${source} `)[0]; + const token = collectComposerInlineTokens(`${source} `, { findMath: markdownMathRanges })[0]; return token?.type === "mention" && token.source === source ? token.value : null; } @@ -222,7 +223,12 @@ export function composerContextEditorTokens( !references.some((ref) => token.start < ref.end && token.end > ref.start) && !citations.some((ref) => token.start < ref.end && token.end > ref.start), ); - const taken = [...inlineTokens, ...references, ...citations, ...composerMathRanges(text)]; + const taken = [ + ...inlineTokens, + ...references, + ...citations, + ...composerMathRanges(text, markdownMathRanges), + ]; const models = modelTokens.filter( (mention) => !taken.some((range) => mention.start < range.end && mention.end > range.start), ); diff --git a/apps/mobile/src/native/T3ComposerEditor.ios.tsx b/apps/mobile/src/native/T3ComposerEditor.ios.tsx index ef57536abe95f..7e8eba1d01b28 100644 --- a/apps/mobile/src/native/T3ComposerEditor.ios.tsx +++ b/apps/mobile/src/native/T3ComposerEditor.ios.tsx @@ -1,6 +1,7 @@ import { PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES } from "@t3tools/client-runtime/text-paste"; import { PROVIDER_SEND_TURN_MAX_INPUT_CHARS } from "@t3tools/contracts"; import { collectComposerInlineTokens } from "@t3tools/shared/composerInlineTokens"; +import { markdownMathRanges } from "@t3tools/shared/markdownMath"; import { composerContextEditorTokens, composerSkillLabels } from "../lib/composerContext"; import { useComposerModelTokens } from "./useComposerModelTokens"; import { requireNativeView } from "expo"; @@ -169,11 +170,12 @@ export function ComposerEditor({ // an abandoned render from leaking a trailing token into the next one. const [confirmedTokens, setConfirmedTokens] = useState(() => ({ value: props.value, - tokens: collectComposerInlineTokens(props.value), + tokens: collectComposerInlineTokens(props.value, { findMath: markdownMathRanges }), })); let tokens = confirmedTokens.tokens; if (confirmedTokens.value !== props.value) { tokens = collectComposerInlineTokens(props.value, { + findMath: markdownMathRanges, preserveTrailingFrom: confirmedTokens.tokens, }); setConfirmedTokens({ value: props.value, tokens }); diff --git a/apps/mobile/src/native/T3ComposerEditor.native.tsx b/apps/mobile/src/native/T3ComposerEditor.native.tsx index 28f47c3b758ab..4a0f57e411020 100644 --- a/apps/mobile/src/native/T3ComposerEditor.native.tsx +++ b/apps/mobile/src/native/T3ComposerEditor.native.tsx @@ -1,6 +1,7 @@ import { PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES } from "@t3tools/client-runtime/text-paste"; import { PROVIDER_SEND_TURN_MAX_INPUT_CHARS } from "@t3tools/contracts"; import { collectComposerInlineTokens } from "@t3tools/shared/composerInlineTokens"; +import { markdownMathRanges } from "@t3tools/shared/markdownMath"; import { composerContextEditorTokens, composerSkillLabels } from "../lib/composerContext"; import { DEFAULT_COMPOSER_ENTER_BEHAVIOR } from "../lib/composerEnterBehavior"; import { useComposerModelTokens } from "./useComposerModelTokens"; @@ -156,11 +157,12 @@ export function ComposerEditor({ // an abandoned render from leaking a trailing token into the next one. const [confirmedTokens, setConfirmedTokens] = useState(() => ({ value: props.value, - tokens: collectComposerInlineTokens(props.value), + tokens: collectComposerInlineTokens(props.value, { findMath: markdownMathRanges }), })); let tokens = confirmedTokens.tokens; if (confirmedTokens.value !== props.value) { tokens = collectComposerInlineTokens(props.value, { + findMath: markdownMathRanges, preserveTrailingFrom: confirmedTokens.tokens, }); setConfirmedTokens({ value: props.value, tokens }); diff --git a/apps/web/deps/README.md b/apps/web/deps/README.md new file mode 100644 index 0000000000000..26750d308c195 --- /dev/null +++ b/apps/web/deps/README.md @@ -0,0 +1,15 @@ +The Words tarball comes from the [`fork/t3-words` branch](https://github.com/pingdotgg/pierre/tree/fork/t3-words) of our fork of [pierrecomputer/pierre](https://github.com/pierrecomputer/pierre). Its `t3-fork.json` records the source commit and the upstream base. The fork adds opt-in options, all off by default so default output stays byte-identical to upstream: + +- `singleTilde: false`: only `~~` strikes. +- `windowsPaths`: backslashes in Windows drive paths stay. +- `codeMeta`: code fence info after the language becomes `data-meta`. +- `sourcePositions`: `data-sourcepos` byte ranges on list items, links, images, code blocks, math and directives. +- `directives`: the named remark-directive text and leaf directives. +- `escapeHtml`: raw HTML renders as escaped text. +- `leadingWhitespace`: spaces typed at the start of paragraph lines show, in `data-leading-whitespace` spans. +- `texDelimiters`: with `math`, `\(…\)` and `\[…\]` are math, as T3's llm-math reads them. +- `autolinkBoundaries`: end ASCII bare URLs before CJK/Arabic punctuation and keep trailing `_`/`~` when not closing emphasis. + +To replace it, commit the change on `fork/t3-words`, bump `packages/words/package.json` to the next `0.2.2-t3.N` and update `t3-fork.json`'s `source`, then run `moon run words:build` (or `node scripts/build.ts && tsdown`) and `npm pack` in `packages/words`. Name the archive with the first eight characters of the source commit, such as `pierre-words-0.2.2-t3.4-7c04b7f1.tgz`, update the path in `apps/web/package.json`, and run `vp i`. + +Change it through the fork, never with a pnpm patch: the next tarball would drop the patch without a trace. diff --git a/apps/web/deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz b/apps/web/deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz new file mode 100644 index 0000000000000000000000000000000000000000..b6716f0395062eef7d2d14d830eafacc8c0d894f GIT binary patch literal 219310 zcmV(N<}{*YTC!9w$Y) zU6i*|U35l8@x`zCuiNb&?Cq(#@7->%+uh$+U+nH5bbGyngYKUCqTAcqIq0b`x?lVT z{}x3V=U;TYzrrND-LA6#{U7r0bR3s)dlu){?QPRh-`5OmwaXo6F4=T^*_ZWs(Z!O*mRVQ zbsOt_b=L9*gm174JNtUJ24Wa;(u>q&CsLE$NKN)4HQA5U!pYm|?)-x)vS~8jREi;L&yo+#BvnOzbrGr2 zBF}YNK7$gq)BTr7m3f>N^BBIi)~p|4NCv1;-okP`u7eVf90NE`iup9Y?bDf*bfvH2 zMVSrUBu3eE8qW*eSLUyQk6GQ$lRJ-OIf+y`Zi&U|tDaepJJ+JOzj`fTd^nuFdKk)y zJPO{yuT}=?BdcG=vt)YPSF&n}hX}=@F^f<#W%w zkjLX>Q9${sLoZ3^uer_@01ozZMmUQylVm*B=}M?3Iv(phM7_(Y{s7(lvM9>r^0qz7 z(o&~oU*S@>FLZgMp;K>l4szIQ1^~9AuX;Q45B?T0$mWvzj0M=KEWlk;x>%HDmg3A- zoK6OIw8#sfLGvt0OP$}h=l(b;;Na5rE6(_y>~yRzsqvoGeHa;_+kT{8#G{Ei*lWYqD(HW%l0qeAp|YD)P2<~aQ4&azDl!$TqRe$X z(_>^WRF+O}p;n=w9yG%~I_lB(`nlH@LYKt~QeJnBrn;RjW*0g)jjEI6J1?FlS7~46 zuv@{UvWxuZq5v*LPxYwmt29f^`uwNPGj)@U%Sm6wYL>lE(knHJb6u+0q9|3Gm1;DJ z(<@C2f>n!1Wx0ygG=s{p!#fR+_N{=07-jQBk8vT^&9dK*FH4;>W5Y!At9Lv5kH=rto+WBVpNmO6 z*Tb(yNj?H@U}ayU%ddE5uiw1|Pm=irv#VDR?HH*uMTFhZSv$z~h zR1v2|yU=-Zi4%=fT&Qp3H~QbzIMYS#^t^XNSO^1rbyj^b!1p$9xp^~qZ0{~zm)noj zGn!xfBKx4OwVoHaFHAkuWuDDcG0Btk8h%32IFE1O??RXA;+F77#pzhl+-oP{!^0Qx z2Y?1i)X2dg89K|zuDINj*%fyN#FP=a*X{lbbYf^LQR?Mp(3&@%kXw(3UzPd7usL-Y ze;JQ;J4sdVad%cI9T&Qdv@IT8-^BU2z#;y4t#2>$c&3YLL)-#b&5y|GIuZiFE?2dt z^8roDY)#9V9w)JC&U1aK^P-*W@nWRM?O8^%px=ZBE6zbwDO$He-WnM~v8>smna*c% zGQK~T6JKgI(!>jhcl`%<xQt5Q0hAP!J>W%(TzDR*F$eXPJ7mu|p zey*vwu_!Owj~kKtsFJHR%k|SAz5`Bpq1DnhoyS-Db@F$uhU#E{fA_$APty6KJSo*s z?Wsq$mMNXZA6`NQHB>w5(Id6nRc+g(U8$aof6Vn|@&Wrh=pI8XS zNv=m_@?L)*&j7sbznq@5|1)m?{fz(HZ9n;I`|M*k+S%V*ez`r^+}V}$p-tX8Pq zz4q?DiZ8PFS|z1wPIV0A`Dfszk(GvSE`VL_wtKtL<|8EJ((TaoG=>^|OUwbUc-zuQt-{~^;;5(=pJzL}>{bN=n_(4|RtpQdSqj;|WRL-Ve$2$Z;i@0DqDfX196uGc+ z5|?Ter^LKRDoeGR>m1)*$mUvfv@O5Yw@v$l@G-em;u8Y#K1;@`3;5v*I#Zoq@zQr& zim|iNaF{CUUMAC0=glU-*;2zJpFngim)=X|wSzZQxWb#EbIs@hcp$`97X5 zkU89#!dpxY6@FoW2Adm~Sq|sAREZj@?m#8#(66GBtu5?;58uf4F`C5rvuvzS%4X6U zY;NFcjMUK(c7U4jr$e>V-Fw_p>DCt1+t7ehP}Cf$hw5N&zqixE#o6EAd2*m0K2(X? z0!;Tnf$z=g&``4#baSw~(`5)YQnfV%kqi8tFaS%1Ah@FCCj1|72Fmr!jWY$TRj+Sn z7umFPndQyKALohAbG?0&<>O+Tq#kXoxc$D@us6-%btJp%{OP;3%nxK z3p^bvp3ikU)?=15;3Hgrh)3o07M`eZ3;Y}xGb*^rf#A3ot0T(T8LYX$DPAwylU&cI z@klqfPaif8kIuHQBGrU_ibti+5s_g(ikk!;%d!NwX%rV)H6Awl_H;aqXY)a0;0oV0 zWGQGLyy8PyIyGf1Clp0jTm)NgNW|tNb)x23Q6v{rtwz(Vzy~re7z%T)K%|jpi>nDP z*yUn6B{2qH!5{(x=}0lr*{~KstivEsH3S$)viwY_7I>y-S$;d%+_;I08C4i;Zd@!bFY%A@`@!Z0aJR)^ zbHnhiYDia>`TfdlP8V8;Tac=`FJ47lhI}z9v%Cp|f0vCHQ!Q_pBrVDqP9CxPKkJK= zqR_L8>22pF7m1dU`nbf!DJMzMp?Tp7Q_YV4FwgSRl-P=H-gT98vmzUnqC)F2@q~Gt zjv&A;2>x~G9lwFO*r6sJ zC(E>B^(|z{_ad)Vix~iWg1i$AoJEBYK)rUAw*VHU1p~L+)F*B=(Cwy$!^~_;aW4QE zAj)p!-jv9|)bAWVg&tM9O{gz-0LBw1x;|hkv`J#jm_)0^m=d>|P()jtw4`S@tT< zuXK|K;mz0Sm{>KW#16sKP>Ergk+Zz!TFf`th^X)Ini@Hh?=9_}@VXYXyz~-rw1_{u z!Q~cF7Y>2Ep(Sc~`=?7oKzO?t5^s^bBg0n^_A-7CJ>c}4U7|sbV#&f@B%WHAd6t&5 z7))~Rcw`pW$vk|L)x6y<=skQ}|8kt!`xVaSYJyn*E=im3Z(O(k5CxFnb-m3(Wu|Mj5K$jo1LdPtR0ezWa*#G%4vd*O|q0@c?v`fFFK? z8V(7E>X0^|*(?^bNZAgG#Y}DCPlsE*h;J&Kll_dd32yi!PkbfskDoxjNf*euWfMS- zBqppsjI_J?61bYX~-JM9)wv7;R1-kOR zP%j>;x~i`Z_F8p)0ib)-88A7I1#m&l-JRy%UZet< z&JSo%rjCz6Y__K9P9(XB$`aT|wIfXUr5@s)gNR!kcP?SI!tnw1xyuJub|XX=RA$eE zJMZR;K|X@+qoO<4Tz1RqH6HZ1>Snfrl@0i`K2k@m+i}ErC5OII60vDzSK5=;FLnR^|3<#uT>)*MA3k)w6Q)4Vn6 z2&a_;f)Q3II$^vaaCitt1JaDt zJ{}%0Lv96F)VouKoZ>Ks<{qp6^ZJMHJ1Avsj`gTBMy)R%rxs9Gs1yKHyl-v<$##9yw(=g}|M@DbE&;w$_F8FR9%#v085Nl$0RkR%Q=0P_c@pEhkJ>+E`e%FiV;1oCXA zQ^yvNh^RpGU;gnv!R2yItqR2qFxTlfAV7DB_EGtJet$XK3K5#ww0comL)=9-aa!Uz zUH4@D494F*i|+lBb^NphqJ;(J(sGqqwky5XXXG(F%mLEl&uHR+Bg;zuSO-_1$K7 z;CDnt7uon$7Qt^2<$x73)xb5ERqz8B61aVDa^YmedYi-1uY74k7xcgz*d2i?NqQyc zcBRW7>8oXwc#?pAb5j&z^Tx)8Ei>zb%b>RGPo8??aC?6AE;Ucv4X=1;VB+R z)!ygr;K!=DG`#8XG~EfbaB+dVS@Gog8_ah)$x8Xgb?XKyW+*a3ainS%8?JPzzHQo#YGK`e6UtuZxPKx*de{I z`)!o??h7fGeVNk~3^roGp!LMYCog2qfqE8a*uh=391`+*aS-tN;^rPcqpQoo?EPvw;iH?`YY1dyY;eP-3|a!JcDfq9@{puy;+qh3PlkP zX;sh~K*15JQtNAg@S9Y8ZYVaA5_4xr9l;Ogy8i0wbUJp9;>vP&lkU4w4slieQ=$45 z)@;kQ09^(PDdS|?HweKe*=}8nE7?`-JCloUBo?}@c3P6wFdw|QBrzqU?v{X&%Dny6 zWWZpAuKGjSH%HZyJ+znlUf<9P1c&Saoe3Z$cJ4j`hw~BZi4)=96Gz9*lKsHm-F9sR zQ8)KTm8zSwFHRX>j=$Y?Kc@%6mH|etJYm(!>wPZ8;gPES%pLnS0~PiG{u34O4bXyznj5ux7hCt#y^R{zymAS9MwPgGL@VIEt7dAi#ORimIO_2^#?d=Bvc{x zgs(NXFQ(oPM$}^J!5u^I!fG`mGpW|a5-I-%VaE@1BeB6HHOhMOmx#!W!0b?;pZNG0 zC0_jO>(RTniv=Y0at}gRB5cWRg*|>TVg+eIZfiW2T^Pf0H}ruwf^RQwYwdb)I5TnA z&5k!r#fQMb+k3Kyw#(+eCxiGtIGdm=0M|sND8je_ zxGO6<;fjzrx{qRY46zST25T5246*%$+I^J2Z1QOUjAH^PnPk^v%L!Ic<~*(liJ>{l zh&?nEN(qbhRy4vLIK9r}=5DuT^eu?K-l<|urgwt6!6zwU+}QA7@fFpsiZ6TFkn12i z`MfDR#TqlQf_FFlvDg^v`?A(`3nK(~)2v)kd*|y)Z6{(LdXiltD3v~TcbdCW?I*5& z<}%G!L)z^Ip-X@r?TGf;eK;H{c}LPdi%yV(wStp6!1j!Ku{8*AWNT=_u@AbCVzer> zb!#X+DiAn3zJ*&1#u&6EZbvNh*N6Ks@JOBju)_-A9r#dWrSNVb_t_wKFafAg$0$f~ zE>n8=EQPs>IStS51qHeAl?Ay{jEnvHDt%vwdlzpaWhr#&3a#=SjYUaj?Obh+RpW4e zgfGOyx$>Qq-!^PiFWKXiD2Ma8glx9H|kVO!@dz4Sd@= z0SPvekC!@OvgoqCV?@61itTD?&y=2m%S+#gi(!=2l4vLu8)Br;fmGS{ft+G(8~e>!asxBj5cwpw2bFxlXmAa>Z%IBj4Fes|*Vv%ZDo^zdE&E`3+N z>z>K(T1p;(kCyuFB(_v(%|t%-lIr6i}$ts`>`k|1O3c2GTzwmZ+r6TF3LTvdYI7pKrcbu=`p z+lLR;_FtOkA9thWr~eE8+dBOVAmP~~gV6*T&K-w@wdm~t`3_s1a2^@_q>snX$a9%53po%u8XHW(8ot?vT#_{&lGK=r8bITnW&-Zo`JR zvBNJz@uyF;3o_zq6EalY3j*_TPiTirStsLcDIr^M>_xlRsugGY6w8P+eTf5zGsTzB z5NA@W`-wA+jM8n1FOtN*>P3>U802wgz!|J)69_4N`6RLJwa3X@JQAm~yjABuRdACT zv9NX5(;8OWu%nlBXB$c3sidupyCiDr2l&)A7--}qh*woPDXRlES?uHld@Md>uG0xM zX<@3e+DO%wZ;JzdK zsN=t?q9OC@g~N=Gs5N4rQ0TJ+3&G{)_VyoiI;Joeo8&pBK2~jTBDCd-JWHj>Gs}YR zpf}#K@8bD9Nw41i^lHeFQ@~Z=e{lSlaW-o|old4defzKPf5kX3>*Bxk4)(v^`??bU z`RlKLkN@(U{7Yu5j)PiK6fNINzA@PJL&jh<$uyq2urdEVUi$Ru8-4_T+}r>%0_2k; z5BAkg1V)te+rHY1HaCD#oo4a4uO3I68!^78`>J;kZEhf$>8o96kjFP~^JxK|7+_`U zkrIC)7G*LmU=;!{eN^B0ksmDOwf20t(sXJ2H#VsX!zd7OX~ICz`?O3-)PWd({z_bi z*ea^gJ%4wvk2IcI0wB_Zf8!$8@wId2-+f%E?VR#2cv9APXBB8MG#x|?jdu8!0Wer zgB5iI2WW86Mvxe6dbVFsZ&ySiAa`HZS;gK)({h3Ha`SB+^|SNm{9?W@|_M=NT>sj930uCb!QA9kNmeg64j=j*!mU;UbR z@9iC9iVR%vU&DPgvBvi2i+p+xk!BJ^?Oab|i~*G85D&Fbld_yg_`d}>W+&4!gD6!~ zj?z(#CVHkfA92`BjJ0L-IfZIoLgNp!`MlLpKWPXfrBYqqWI03yDJO+*fz8YHHlMzM zAiZ#VG#B~Q1?Pe5WSaaPMez40(~EpsL!^zE743GRN;O0V$>GNu-tZzi28QqXnq=}+ z*n@LH>J|s$7IhnJEjeliq>LRyy!m+>yU3?t$S*n%`fi!H5vtIm43D|1?aOc2^`O3( zr9V$_wri{GeNEzF9*(|z`lQ5%Cm^^q5pay~j9!pa)Ks)#@`OUDPOI5G0fWDXhWgY4 zY429L|MvUl&%Lkhp9i~rg=dwqcwh?lANMVYF}oQNF2J`VRDskCFH|1WENykl>{WK7 z^Jj6Pn-ZD^oTf(K`&o$JmtHBIIq{*?Q}GK9SA*xldN3Ky$DJi5wDInn1Gde?fRM2+CoRYoA@{sI*El<$FzASsv z^<&TM%c@WOv$nHC!JEEG(lJF1f>*XRa?9aAeU%a!W4{r2`Np{}s4loYYKrbxOn}oy zA+UFiFH-LBMLKTAk-A_J1l??gAVK_Rrps+Ahj=k`sbbj?N^dbrjxQT4*trdA(RsR9 zQ-P3&KMnC4Uchz3bG!#GLs7@&G|O@VXj`Fgq=gZBq(BrPYLX|2Wqt%&?&zO(ut%}VZP@RNJiCF5(uOp* zEGSBhvE}9?bpuEm28}1QEIJf?{?#|I?6(jpvPfWD6GR@zItNCTBV3&!LP1Vgi@ASQ<0p`86==n^hRc=WXd?yX2x@y{*TYT8>IH`rJctIqbuagwISAeuhd0Ct2n^vw2pu4@i=I0?vcU`D=`_31V_WTk7q-;Yf;24m zstD{ymWCA`K2$$oXx$Dz)2zRusNU)n*-ST^un-6!u82_j4eWuydx!GFAf`jm;lAo2 zVuOS&Qakv!k+F5ui@z=6DQCnmA(1K8Z=tS$dD2(`Iuc9B@sEvAugSj)W3}wPtJpu( z)CuDWo9`I?R@o5Dg<~o#OK76(c3pg8TP7nE!;kILc<4o@9#@hNp}i6cIXx8~|Cus>Y?xWnI6->R>VMX4DDJmZse z+%zVC6eX1x%Y5tjqq)FW^%d-oezk(L1hMn6!fb%^4IzD9(1O>xY@TjzG%j+m&u&cU zKgsNh{tKGd#^zbe@`_CE@Bw3~8t@KDs!n6`(183ZX=dZCmhlzjcO)lwT(~m60ta`L z#pvl}+thsh=YNH=j(YK4=eNNSn6)KUaarcc#iG=T621VphmoB&#S8DxSu)0G?TE0z zD==t4jlfE;Vr8|{65;?dl@7`UU{^jWG(b0LN8WaM-qc?1L29&2Wi3@mMxH@d_ zd3rWj_57l2aG`vZ@-YnsfF1ookLXSsa510?L^F*UDhcMoy;UnsSHk@KB z7_dZ_*4V3mU4ng%#)o92oAJ@}jjXp^Uj9AgMriT@P=kaVg8*ZE3t#)J@NErI^mz@9omi~S#UwM3z%OOYo z$45v77h66p0c!mACt{{7F#+ub(efEE3fX1w@aU+YiRMEqNa}%)$*GRtQy}vK`z%n3 zs7Kd&jGbL(S(#=fCcC>XEQtaL5?~q8%g!S;cK1Nt&BR8=VEIhFqEB=W!On>^g59d< zB&;h{dP0rZ6M<4t3_Gl23Pd;+TG64Yjq$o#<3Owi#=fs!hYf3UIk3y^R{;qTHg5TwU@=C<&gm?qMonm_#o=H{5cS!L zV4~J-1+-5?ziS(N3LW(76nCOJ^7hWP1-rAvPj*Wru_C+@V3HoqENEPkcVG@K$zOZA zHB$u^ug~jjWLR}%*`W_A)&#EnA@EbkwL^0zEYQ2dMiXl&E7_A#8ay`$^9(I$H=IQ> zH83Xn_=|miun%#hu*}K^4|*-$qQ)N@B1Mji9Er={@|1?XR#g{WS!XMY6IL^zkQF*< zocn5xG(KpBLOK}2+G2b|Mn;DHW}yyp*7(*jQ&QhzxUaZWvkds36sYNYttQFUWC|${ zb?!g6oe7l<_LeyZ&!r3TMY`)@T^O*H5x?lmPw|cXn4-{qtUa0cdoBKaTX+(1<9YOU zK8|fbusfr7k+EhlHh+E1j%_mJm?=UlN&nkR_IDDWPAC&l&_$e=2?o-r>G;QWg}ff9 z?-iffwTC%@IISP*Gv*?7LqXrlJ_hgP4tS_`*-o&?sGOBKl_a8_>B7& z?}e`XWSMlx`$%Nox%L}fy?Gn}S{!%yH|45$@B5r^8Mv@wca$$-u(^SzOnElP#JKqI zjXRFWhJQXbDu-huI2jv0;(N2TT#frA zk+rViwXt%qlt?t&2yv{gK?VCaRwDUE4Tf(>G_332$Ip%XBIm|uVCKeUI5^|V=7wW@ zCs|RpQTd3Oj8*0fK>GG6Od|Or^4R4Fx*`$n%kgwvZI~};o>D?Ad4WgoVz6v z$i|~k97DPtvI1o-XhecoBZG;EU1xL$(Fp{t)zB9mgeC}G@QNBos?lqBf|tflZj)VzwJS<1&cty^8v0|QasQG=Z*MYH`$f={P586ND_7>v3mu!yRyXzxCrV8PaOe5@V>rB2+8&HFV2`&G=EhI%Zk#A@+YdQ=D1 z?0Gh)a8~#UE{&7<+*rQW9CQC^9GTFo>Oz+{TBlNJKo`k|G0Z3mBQ183Y{=t|mR~x; z`L91XyJ~epAmfe)C zp%t`;Qg+r|nP58BfS}#BJ4!+nXCo>D@0e$f3!;O3D`qC;Cw$Ya03{(Y{&a5LS(jIl z7egnl0Tn->1Y*Wc3!f!BgH=tpwy3cg%D7;Mp8vJrMT$puOZ~u{L_8$^yWON%$S_c$>?x^F6D{&V+ zn)&d1bf8)@;t~9pJxkN;sv|1yw7h@;S1amrz|Eel&AzL3)s4N7s9m1|4=Qs|FRpEj zF@WYarE{kdyMq}l^=swrWJ3=B|HMijJW}Q1zKBO-4hhwsL`IS2@5pmPe)+6SU!qCW5wX%P&9jgqNP7 z;JI^_bqlm~tCSQkWxSBJVD5K4=XIl=W)vJUY2JakfC&K!*{s}7!cG+l>%6>2WOjsr zjP(b0y5;>`6eSWXq0P6Xs;bhrTg&aLPUqs95Mc5uO3!b(L=>4B-cvT!Br?aVe7i~Z z3g-Z08}gcMnJ*)zAMBWp%G#m7DaVF(^_@TfX)Z`R(H_NoywW9o?0ez>``t~62NFwS zhNjgrv5qX$F}7g{&7*>^3jrySb1}*TS=thS76ed4qgLQDIy}pP7~rgiNVW?avUbW~ z%g_mwD`p&Eu1(Xu%rQy3xk?@DagJ`K;wMr(+U=p&vOlg0tZ==3GunlXc=;bRSb`S z%=t0t3JsAK5mh7QRHPLSZW+)Uen;2riaiS9nKQeA3C-Z0>p#Zu8?8BG4w8^hpHM#K z%xE46Gn!UQc~T8|Q0_$_A9qNk^xDX{ni3&RZAo@mJZ5lnP~wQ4Dqgz|%oE zQl;3Qnchm8EeY>BitA7EZklV!>+$hj^wsOSictQ@G~MdLO0pZSVs#lU<*kxlk!vvo z%$e-fP-juuWcZ>@x=-EZX3biNlv_0b-NS|u1#?1g;+qoUTVL7}u2>8bTvrc+PZJC+ z^a7CZ4M3*uL8j0ewu!-L<9g^tfTiwAAwz6i*_k2? z*7XxvtLs(}_C#84`!?lnv+LH&XHp@OtnsVV_rP` zAmjcqMVdr(YePy0$fA27=Syvf@#W^aw+KSJ8r8k&(EVplGLaVUKuS^r{Fhz0+he$1 z)VFk@nNI0wW3OjIsr+5`UfQOc;H<1*NYXMBL1~4>2B@vQ{B_) zI`&}KPb|?Ms$F4#>NPrrh*?L$cr|yyDaA{M-9EF~V885nS97J~R;0pjATTF=q~or~mN)t-81aLfc`0e1ONdb?W(fY4I2O_24A6$;b1u>RiUkchsrX~t%p zMzf5GKnv&#jPfCBnxQHXjsoLbK<|_?Fo#Ir3WANHLNzHMy6ZI{x|${hIKrl51+hb* zRhHFgSB<{^eu(^l@$b_owML!ia(!0iC*%}hl1p0Upz*uxR$H%;a2xac9icG2r;PjF zB5vPSalMpV^js$&wcy@EL~83wDXC-9?h=0n=?(l9y;}%lg<2FWHb|G}1X@8*Sy@jC z?M2-Qq_e*3QRP_RH)1zyo)k7bDhlxll|Alt?lOF1u}L)ouD%4dE8-8}nFBz&0tAqQ zJG@~|^^#LJQA$8ZwOyJ0=ILur$pXV%U6LfuId}LS)W(^~5bJTRZz0a1G3kmnT~JDn zDl9@zQocEuU$p6@H#{-=Wc)0Dsy&i$c+hm(zny zPKCjX!WJSMqFNio&2vKJ8fo{~e_Hv0Wp;=>x@A>Pm{iTJ`r%KM;lPZ!ALwBF0IIa#uq9v*K%LC_ND2MjA`u|Jj3!_+O%9opS?Cmna@rdkbGeh@$D7Oc75el`O3tDS}eHvYWLg5 z8eWCd-r3_zsOhZ&YE)<$&;vSHUrSwDoC4I`+WvmfJI+PbHQG&j3BkB)8rL;5Q-rnx z=U33Rmhxr!GJ46nBYoUye%zEYXHVcP1*nu%1|UF5I6B+O3%C=CbelB3)#~w1R4Wga zU(?-n9g^m|OU|qSHGqi1)TfJG?9T47z~sL2^Q!q-)h3urNVY_rsBUnJm&nh%CL6+$ za)-T*XMqy&a2Vviv#%s-?2`=-+vSN4aNQkS6F8|R@m+HzfhFrCXM5Y>6n};f3{am- z?C4A;jVUzlhUDLfcv!G{5!dZ_(4hjo0veF|ZcFCDW~uqGR+cWKA_(QpA}u9ACWWCf zcDJ#te{=z;O&;-0!&{joZ`aIRNi3u3tU#)MWx5{T_?ZgtzcRdO^*G4Ac%LP5Q@PC^ z$cq|nuE@cW%@kq}tlx=4>-RbJsN{V5~)Sds@IlY5I^je=qAS+y>Kzf%E zvi77@NUABWP{_*Yl1K`8K9~Af*A`Mmur`X`22K7o&$BWE1!~K=o$wVYXq7ADbclAV zMJve@hQv%%le}QKL9&`d7`bpksm;Z2`8T% zC&ehv$3<0e4#LG;6D@>*WX`4@myS{iMoK2z6XIn2+!9_~{Ni=4jz(R986j8$LKzc4 z&S1bXWLEjg^fJHo6lOPZ;XI+(hA+&X0+zazL_^w)b6SlcAJ2yKEKGds0-Ix}8>HL` z(o{fgv{DhUTePofuG5*0%@zqnZ!(a40tJBBC5ksm4SR|q`j zWqzRtN|4f2Cbl!#QXqG!U9VrRZAKNyTx!0zg2E*oKeou~&mX0`HG?3`+a8$e!L*y4&hMgoCp&w5&N5 zd!6^C*Z2yT^qLge!8?dJ%}zkEe7yG6-b8xMRmb)>AeS;I2u3E;>B!82{qoP&nR$`wU;)d0Drk^5RPX0kHXxtk=HNA{fnd*o&)cA0@^fxu{Q~YE6QrOEmW?bB%8DMHmaWRs7~^oyRBj9 zK$x)J%k$g!^&2fbxskW**6y#ea)ZhtqBR4vltt;EK|c|(G~>s8qq(o%MdsK23Jx!V z?*TS?YHi~g=5*tEd;_jtr7#h5Oe*9Mw@Z_xO<^dN+gWjNtVm8LSR`|;kfoOwIUdIs zEfJWAhPKVaDA*fSuUG8*P=ZA;dd{tOo@-oUD~&vlSmWO6)v9{85?*M|@_^?MejE{; zEtibI)`bpNde(XovVAYt2i7eXSJHUJdax;djTf3fCdI78r$mbnh0CWR56x22 zs+&oM2ihQg-SLrLrVB6=U41g{cj3^Wkl)=A4-;$6C!2ji0K-uUA%3OXia=U7e3!=a zZ?f9P#*j?5t~RZ^U{*)^FhEyAipWb4qYB`rx#(Q&I;~NLCiBhVL~gcS(lvqIGjP15fxLfNkv-|Yvm)_n)Is^ zJnoST#(y$!2?(~ZZ=^uU>_x-#={!^Zr#E4Atlvxs6z z_EraZaoUB|;`UY4G4RHg?uZ2O?<9uq`ab9_8s z*F#B|Yh@a)ij3g4QLCG&ram^^UFq^iJERLmW@wkt5Y)&jDx(l~)!d>EwPcsWFtN~< z`_SQl2j+&fbjz<%{k+jNnWOKQJKC+idrC%< z8>~wr9i)-2SAN^^*9;+?G+qAbl^Lk*+}H3Sq0Y`#8%VX2kZ>*42!mZWF+`qIPX&sV z4RWc(N=_RTxsZ9N7FwSRYn;toBCMqNCZ;rMsY#;-e{|q~z-g17E|{+cK40nb#6<6J zHoQO=4SMD@%IsRFHmy}sydj0@y8d_J4k1XWn#;CT6v=zdT{KQ{z&K52ajC~PmCaeC zPQ$pm2t|Dn=FkFDES=X^@U!RCb`j^g#G>N;m7Qzxo-g55xf*`f@imJ}mYa+@%B{n9&PbptdwCUpA&s^+`(Ah z-|2A@A9tD!w3^m=(a!aFG1BAqEGzNc(eGBnguE=187e{T-_IFDHB>LtOGw#%YeSd* zZJ`S?Nt2N}$8NRd;#;_N3gl*NuK?E%1dTI|*(DPv$+KajH|EUPPY-k$s!5(y!hnP{ zIh~~V20+$a0o*fTQo(}_{oam-{)DA12-2aTVM~psI?mrDGo39;Dn<%I6(!>lE~L@e zt^~BDOecjd%?Pwwms4=@ZAG4~2~MD`<~m2#3Ct?e?55dj86`HK1!xP)1@T0!9++3{ zZm`AvTa+g5I~Z2@M#MQMV_KD1#fGA0=R-LNe7@H6vOZdr%Og6r-dUcHFp~^8yF;o4 zUQ@#BijwLM-7yTx$8PSp+VMrfsh^#DZcL8)wki-`E03l@VG3|X0VH(AxB;PTYwOIU zeP*|1S_&(^Bm)7{=#E%LwB$Tohkku8qlRz=V?T-lHJ~!kVVtA|gnvt0GM)&n)1lz3 zu_Gdwe)lGsn+*YO*GCg0j-lZWpk1fTlUcJRaui|_t;Y-F zZ)|rrAnmr7z={;^3tMK_pl82(-FMIjx+pOqnqvQThfriK4~aK{*J@V!l|EW)Iv4z! z?7iYlNL0`A2E>N01~>{`b`1Ze1d|z5F~=LL$0N7HyYD=^j)E&!()!Tqpj3HyqX(I?~>*yDr2FKk73hVXmkk^&C{17X$F zYm}v_9$70k#@={5e(_$X<*TG9b*l4bgQR+m$jAQHK)e}(t}MRWUWsOWX2)<$fe{e# zHL4eAED8B5Jo{@ku2v8E@V?h2AkD*_3)aOWdo{OFq*hCMiP#p%~gGxG}eAICm6f}FsA z?+PhW&C}NjDwueg7qFCG_zJRWPY(zVuW}g8!lAYaua%(U$ato&ecB7Yhnkr{FZ__k zOU;$Y7j#gBPv_tpQS$(P+7$+F5*Iam7AUM-FLT@Lu}t)Y(ShMBq@2QvlZO4&JA2_f?(#JMp=jX0Zt_b4^WY)C>*2Jl0dc!`;KFo~vDNuMiq zOf$Kkc!-;hD}MNp#x)$V3-@Us2cg`N3u;+R$1@ANz2g-W)|4}Y_B<|Q`CzW#j8n4L z?7i6!(Lvp#ti=1C*O>0?aO0LnWD9;yq#V^Bk^&>xkW`Kgh^MzG`9tKIXqCozfpc<{ ziv?`O1;1aiOO#;LWfY%76$(d`WhI4Si%crYQ8t?;5OgO}rJl{FF-PvapWsh00A)a$ zziyn426}ax2KEOvrku%ioTK@a#mLbj$H%9+H2IVu6DS>jz>1-gTJ3O~?1f~o8x}SU z31BiJ%X9hIvH{QSJBNbj^twBHb-~bMM!JI_pd~(?P@BRlsE(i~jHYD1c#~jhKCf~o zfdru#4`#@H9f#qkY)6#i{6X7=m~J06f|P@Yb4)aX43l&*_K|v4JXw3j21son5B~8OB=AyLaZlk~m z!W-C9nE;-;$-4le6f%pmXfzH%Qy?+aqRxBF?QHwPch_q@)uS@YPo~pm16o$HBe3mZ z5SYsj64@a4-2v6bkWk@eT$fhjaJzVaWx}ulvK?5dTi&!wt0qzeHG*ym|HDi^E^w|g3pg9jct zfJU{8+7LM#j2R;eEk$iPi4_D4iJ^z8lE9#`A=`s_bE(Lb>vAz#Ge=<-PxNxtl}fP* z$m@!$4qO4VFi>7|YVq*v53Bq3lGK@gfVZ|>ZRX507zn{2x(gqpo`#J#)NPbcpGW`#vrsp8{kx1%e@EOT(B@TqCV<+)pr@YzHWT4g7*^P!7*5l0ZN#^ zI0?J-wUG8Pu9FrmX2@Qd2yq4!Hcl1RFrJB(V~?>nKV>g(GnUlxn+_S64?{3yM{Nvi zv>Gm|AXiD4t-*0?{A zQjw%D(h6=hs-pg(6N0o^;hX@DiMI;gEZo_JnK9|mv91efIpFE8F=1v zA(J)F3c{b=9bqe+70wN#KI51lxN@EuYg4{m?C5pxJRH*{7h72jIglkNCO$LE0{wk5 zDLgXE4#1)qp3Hh_tzCnIUdY0)$>j}GwCSTjOtzN&i+{Ju37T9^17)gr@Fm0f7 zl+sES%e#{dGT?^(a%aA%l}iB}djouwZ#qv%W+<|$y84ExmysIsRpsJq>>m6)hPcEE9l;pODE`BG2461^{$y#=ecB~27?|X4@5XyPTefwHd4wT(NguChCGK1 zoiqA^;T@9n>Kp=wED9^Zgg_+Lf{`M66%b1qIVJTIjzl4mQB)L{>fAnG&uiqD&kW2) za%cv&l1vz_5Hd4NksM(LT}b>(=DZ}sv5G*SEoPfjThmIuOSFKe#B|5(L~6~_IEf%H zH3DPo732I$mnPB(m}q;9ilk!e<)=n>K>hi+BF~HzaoREcyPs@Dup^03Ap+X$1{J`` zgUCfWrB!9|CMcq z7XzYIN2ru(%Y;P6i>Pms(+F{FokY`_!Ev;AS~5s*0N?syt$~XXYZ#Bzd1p9ETq8d- zeS0z2{WDID-GaX{h+9PzV+QG{8QKSN1G^2piH>EbtzM}!!D9b95RV=MMxD?ouv&06 z|BRn-A7vU4^8glKS$Za3CXD{Z#^0VP#G0mbWR?OaosO$G#4jDg)>n{Nh%4_aQ~Ljo zKqLXspiFinvHGuywE|9Rb1{PjvFB(>rwJ7v7Sg?z53 zj;TSv)}F8ueaj?%Wc9J5g6v(0Y-1gTF!9%g-XIW)5upw=-X^}eRL2Soq&=_fin#6i zSf_gREGzPY8jeol!atvVt);eW$*nKjam3L-9o@ezjgDeWhJ2KCCii%xdXK-G$?cP0IMn3Qf#R`4gzB*|Ev&TzDHw!nZf%Mub}S9HQIi=m-qr(MwM3PSjtC@ zeWw$Mb?ezcLi1^|6=H^zs?e8LY|9slBlA*7C zKHr)mFnbba*^d21RVB>p2Yco$;X(8!Qn&LpPD|9N&L-U2(?`BRxlI&eUM$#y&6nsX49wB+%LbxJ~7;BHz&2%PC0!9ZttV6r5z?rXUj1YxE{@SdC$ zF}ku1ak0t<$n)>9Z_w18C{)|y?^P;$%H?8+oDq9@Fi4W>9t8DZtut`3L(wqU6RiU8 z>YB=o#`G?6BoUjNGyfB%_WjPd!Qpv72eJJ*1qGnH7Y_9EAHHMTVTc0&K>|1iT1_~B z=h^Hh4ie2e02jUc<1(_DIFSHi3s4-|CN4X{$IpupFq-Jm^*l?`8uRK3J+&bKoE0B- z?ePTWdM1N_H4cWR3KM8bIhag8uLU}?+{cU2g?cFL5{eiMHedlo7!mS+aED6JQ#OoZ zU|5)E0E1CGP*xWVmW69m=QjxjKtB=q+8X4aW2^X7EY6d-JxRu6oqB#PMiZTkuEC&N zzn5m*oThP6mN+{s>=5^R?A%hRoFZ)?ZHy5~&l;99F+I5FEPcVS4F<*wUxY=+b}8}e@v-^r8S_ft+v9rSu$!mX;|U#D_C%WB zHd-qJYozh}hmS$jN;9(N#A=L>ndLOEo3SbGM#IJlMUd zf^M+gxqhEri|tq&4Z+-ib7y+OaHEz=Y3Iw)=|E}|vrat9&vzv5d zcKmp4I9$Cyb^VB#kaz=be(JKCz5^fH82cwq`QB!Bnq0ICe4syYq0_XSRveluS&rQf`ixsi( zxN};@S7$OLPv@5`Nx=?Kk{pO!{G&|?(u^Z@AqcEdMj?|Qi)uWHWo~5Yt{Q!N_)xvZ90hiij!Tvd4NR$R=d!&HY|7LX$pP3WTHmgV2Xxx$bR-@a z1d3EpfEafsEFEn3a4w*VPsfEWn)^Jx*0*PMz8lcBD5RNu`ZQDze5DQ52QrUorHFN) z1Rt2=L1wIRcKsyC6h+qYUi31XXDNhqfqw9$1Rc<~YD-B|psf!t33B02K3_5(r|5-q z+dv26^jHu?tbmg|k8e9kf&UdSK71GyaSN$17x*qk3cgaEaK4PMEV^Ura?=KIuq9(V zxSOFi!P45~NgUeY?&L|45@AsIOEHP(#(*EMp)$L=npVOi6=kmD8RgZIQM-fWC~g{e zW^|J6!}J{;`{n^EX?}XI1Rf7bv!4N2P^7QIKS%_F+f3Cx~LB7UtEnLz@9%W?%>fZ=eYpWjm zU31FDR#3ktwPCOavWAVm(5&f#Q_V>LsR*Ye&jfEaL$W%uKZj~&seFxof<_r}ydSwN zHWR7I%1fhkLTNC^ezWO|BLPx}v>tc2cG3O3oi}pvN-3k1uM@(m(Te_9bX~KdgGxH2 zT4bn2vtXe=a(sv&?dQ@P*mHgHbY=3C37a{y6jb1mVO9-^B@^w;B2{RBIu1{u>T|6c zt12_Bcj*cljPV%a4BY-AyUeNs-?EP`NSiO#8vF$c8q&|mWIHRBH5L4r7oDo{wpC39(U_7J&Dgp50GJKGJK&$I{@MC7|9I4E(_ByqCGyjY zyJZa1mRW9#lQbV9BlP1L1%= zW~CPa-G|ToLj-pTk>_aW=RT+sD9blFyPbN{RC%F*eQdVJOBm+;~9IaT_waeYa*>1_rCqMa$x)xMSJ4$vUGtO9Qugm4(5J zg=!#=344P-ow~xA#gmc60~tBd#4g(!qJ4+jQZ9n#>i7p6Vk&GI(hAY_emBlPeBo3# zzxK-EMP>1%2$OANI8-;Kexc3k-t}tpuN2$Yai^a7aWA-GCDoSG(}yPd9vk2k^P)kO z`4WXb2unL4=Tlv$>37G;Wpkx>YBg0{@Cx1tJ5xs><6^?;hq@g3=u(Zu zRaeWWiT5=p+X%LH#e=Hm0$TAL@|;zeD>IK@g2qVpe53mceQ+6aymT|>F=FIyk;ei@ z9>;2b0d)PkNq997{(kMOY`trJ+Ycl!wv6Z5HxoX-Pwp2#?(4B#tUhjQ(03I=d1D(| zUlSM1w~Mj4&{ih^{@+OdYFX%iga+QlLi_xc<#W+*{CgRid$X2nuFJ2?se#xR^_jEa zuFKMktXW@4hWZ~PM^2vooncgc5CVZ-9WWmE?HLivu4-wNtnd%gpnE(rR$pw-0!M%Q z*syn*b(&wKEadu*O_k+|qnz#5PwTD=&I6@JRxZoIP783|GnaNJCh~@8-EoN;Vd8gH zDbs`6Xc8lbhtx(isd$zB1GholWgzbYa}|h%m;7nJ9t4yD7 znn|k0un#f6tFY#qr$0RZkMP^`@WY=fA6}ePD*Y6Ec>Ai+w;Lu7rg$(sz+$&04((S239fl~ z*b^jjBX}qww7);SXjCF^33OZ`^l?K_p3PN{7j&Z(j~EdvAPf#r69%BpYuWes7yRnI zA_5%O9Bvyzwccm#9|#(7WJ3n5i50-UKQ5}PSAi)CUWJ&%G+&>VgHyP&LRY~!BF^6h;{L0vO zFUj|=@yB_h^IQwmX$(a2*<8mX53g(zT8c-QBb#%hfC@aPFL0{B_32Nh5fRIqq@1Yp z>Tu^Bb&^uFb4sv%t@XT6G3FarrI}Hk7nB{LAbY~5Or69w!4`<2YJODg4QUs_PXt%9 zPEBWxYSKm<7L5m>Oxe5|9r|z6tv)+oBDL*wIt(Fl$I!L2t4HSv;i_WvIY9te=$2>_$TeXR>%j%7YDyBT+cW2*Wb7-fWrFv`s@lMkG1 z+>i2fnS6L9R7qWF1#I#!8w)nH*AEhaTUd_+gML>M$c?IV*$6=1sDpQ76|gSPwityT zIo4Mi{CiR6l3gmgll0g)>w-l;ZxOrZYimSFd4Uv~%!io%ih-`6dmkSp2D5=IytL96 zaTL}Z2HD=R5MhG*;GD=O9XnQ={0i^#Myn;?@WwQ!x&1DGmmY6lMN&mXj1J=#GDi}g zRp1D0l=UTO(om&4s4?-DyDJmB)zxLUs8=G*E9XP2_SRk{)S;3>z+v z6T{jf7P%?aoP1g-R@v&!uZ`KJ`u6+4SHrk!(6hB4K!XAuo9HHDM1iFh+cQBS1y)JA z30JFwfZKhC^>|rh;J8Q_ei@9n zGBkYy{1wU1Rz%WcXwF(RXL2Mv?Vds4pPSb(3=*W{vnFcc z+6|@mqTEzJOyOtj@Q$~`*7M;X+7f4UByr<&u|sSkY;4#q(NYWqUpGLvVv_Y47=i0* zv0~K@FNCo8^Kj-KXyIC+@_{^=<&`Oog)AAii6GbEsaj zPofS(e%0w0>-fdh3}X-=opC*=ZftfqP_Z@H5o2vJlX43Gd*%YL)Q)Z99UFGnrL2`D z+P-uwZ_LszVIyfL5>7#Y3NF(ARD`{e?=&Ycf@k7k1RpwNB&2zc$eAhQwK-d+BMz8N zGh+Ltuo4iYaO11(Kd#`)OoTBmQOCyyMowKk5#v`IS~I17xRC|`RDi_zcvL}fBtuNdIuH#-wqz7-_QR){hvF8 z!2DSZC=1ZRZQ1~Y=Ui}3(ss%+4!8a5KmRMK=6=*u9jfBSd3;kqaKg<;HjEMLaX>pk znmQY!bezOjc|4;S!kFWHJfObQ%og54jJ$I5kt!zHO`+0^qY9l+va+$?%Q(|mhq~i7 zF=z+fG&-AA&ER)5TUHCs^;AcysvP9>#&v;XzKiEg7bFkXL9shE>PgNI$H{x;hn;Ki z5;u;%{0JkOI2)vdF{5{i_gBlq?Q!z{=v?UFn4VdkO{kj@I!ag2Qe}S2@j<8`0MvS$lmMa=2xqa0p2NEFUF|Gy|F}c%C*ws3=VbQi$z|6-3w_ z2$#cQVa`B3Mv1MReAuNoxz@KRX1vz7)<|XO1d>vo)HU)%@fyF@xA;V4KSKn6}&Lfm@D0vB9Rvdv#Ha^5nwVp|CZ|a=?M0<58)y8_t=?VQVnv z9z<@etou3Dg}~6pfyT3dG7+VLV_+u{yhS55qg%Zp1pc zh+(kj#ng-(MJ`et5h_xnU#=ma3HVV$CX=atlT6{>qSY*ZjLS*Eo+-MFO%CTDvmzlq zG5ftH@5zsaqTSgcf!qAvI&3f)WZM}}r`e4jo7hv(QBnD}NFf5{b6XOrg@^UY_(v3I zM=DEsjk5GL*-(iuFCbu3r_-6|*}Pzej6I?-m=_?uU>Gqf)sS(%X#zc&0BL-(Y&kO( zw#MXkob$%iosp)+wTO|7mWBSN@KXcF@6OCr%{?WD|OCW(;b?VIemsdt7WI=c(qR%0XfCkRxT)vS++uLk8Looe~Ai)#B-t z!7<}`wpXBNfj?GKUa=17Ly7Ucf=s9~@ScqzYAS&~sy-mTsbbyWtXYcvU}x8=>)Vey z%*);Mqodl~NR=P#RgQdNTP@kI5pPoIRR`WTEn@@!E|Z(r;3rE&UoB!h?v?c%BzqM>s2P7f>JispIp`%Cek^!~fa zz=`xXmj8D5cJ`|B-`#`X-+%wp^*^MvsZjt`ls^XXjQYp5{%!O;4)Op0MqAAJ=l^zo zDYEppwg1>XI5?=QXgGl`gt`b*LxM9i#<<5YOY$M7MW3T`Iavrn+eK z)#;{EFeY46SfW(p0sgws>1YC@+V8JkK6~-~>ldBb*nIi^hc_>u$q(gj`!dU~5#1Y` zN}b_gAjbh9W=MJnfLWa2^g6zYM8h^HDy2ZjsGO)3)c8o_cI=;bx5he5nM5r|t6VK2 zx~ssXl_O58t`1gN^2&5b^0f|5;=_D6D-alFZ5;%*P5^;$CR_uCFrB*t7SG6T9YB7? z04k%OTLY5OX50afQ+lieM$`(|r<_gKt_;}m-L)oU>$i3_xJod3QQl4=txh3_6dyOa za)Zc&!2Wrz=ZlMJQcQkGr?+&{K;XJa6_T93tKfPW>-Wz!M4Zv-DAA&~8rRc49hhPs zk97Z$Iqa6K#bvw9AQ#4}deiv!1~Z9lm%6~E7{z5g&93^k4n2^7!l6H8Z5`Z??Tbaa zru3I$oXyshn^U;9yuG52m7UvMrAckyv+>@Cy6-E2SqnumNv@OH0=tHFrDd_Q1ZIv% z<&|1gnQNVY4z3&xyPf?`uQJQO^d5J1J3V;${-yV%)9rLuj{$N_H%^6ilI$gh;|fw% z?o*L?-AKmWa6w<`bH@9qD7{(qD6?_PMj5x%w>{f5PZMucy}qR~G+ zi}>8bk4C4n4RRZ-SQd@5s4*jHO3~;y27|%3CpS;OjgqG)C&|+&J~@d8-<~{s@-%vT za`HABojki3yf}IG0{-VDdVO;8dN6o#^5V^4Fgoe}2|xdz=-*CG{w?~Clav2|pYx|w z_uo!VUPnKlocv55qn9Tq-%Jm(T>N0D#voC(oj9Pforayg2!{SA#+F^duhP2hl$QlRQ0nSw6#w z(*W36^7Q1{J}n0T{xXVBo^3xB5b#7!uAjnk{hgKzo4tU#V^I}LsOrm;XS+|aR(wa_ z(bdzFXFo-wlarC{`t839F!6tQk4{Dd_?J9A`H%EDE-w}9lM_vK{`U0b&rmb(f=OAdfKnb|G(b*o&Nv#(*IvRhx&6Nd%Hp%)&szkO?`ZqD)kMRgg=M; zaS{9kf&4e9LdTykQ?gKj&lKX*`^+-_A6N+wMVN{XY|iF+R%WAY>iXu)xuVRD#43xg zI@<|%{ng-IS^*Z62Xe4)@+>V$-EX0PQkrjS(_ zQr$qR0`*C~P15o)CdpKvC~4-?#pR{W2i)KXYZD|uRSzqps)sZor7p5XI*#+(K0Ts|r9rpz~a0wW_y?ygd`?0z}HzE!u2*z&-0E}Vy^;ne|t8>)c*bsrG8+Ae@ zrqXZvac|m_*al}Jh@7rMw;rm4{r%m8!Mk*OTb+M7)3XlF;~eDTMLyb|=~AX=GfBnw}c&PTe zPY&G9m?0@>r`rC@=}G%P{k`Rv+cd>TkKU!~k$N-HWPX(^ z{h`!pLAkDNPHk|}2V;vuWoh4779uvP-5#t8dah(Q*cp7Lb&(YdwY%5e-BPo&5vXA0+fsTMVI{Pt78GX#fuo)y~d}w*D4Wn(g|{!q%f-uB#ab z)u*r;*iy=RJ1go5TT799^;qq#s4tB%W&e*?)HlYO9?S=;fbp$4Wt-hq6A<3pa)=!Q zs0G!5o-X<9;<+9Bw1&LBMsW&;#G?sVbU`}Q9L;|_{;{x4zty)*XKLC9yYDeZ%Ag}zCxkvc2KwNjV|;MsXS*IS2SpKB5{$~C5_RZTQVGUgp}l02Kid(+ zAcB+!CuK8f@qLbtO_-7G!{e@PX}%xg=Wa`-TU!HDWMf0Qv)ml1hpPMGas+j8Nk5Dq zcOmY-tCN7USpctBp;?6z{nM&lkGfsc?EkU%=KXCPNupqXl%&RM08J1)blKp62SSuu zZOL+5vOPVb=CKGA$r3>TT~!bzOPtTXzqm3Zj{+%o@9cZK&wt27Rc2Hkk&$tS8nQ7n zNYS#htG=m*&Do2*HaEy~s4bsajNWvq9D$)W`K&HKVeJD`<v={N2FDn;*7Y$FmM*7$!RH zvDfzICC05EHX;`8)-Qr(af3iKf6%gnxJdJl(_&U{fPeStG~a*#HLT2KX7dfcayQES zJpX7mHq6MogUkFM%c8WG{S4qvi{H`Fvga7J5&}mT7q36f>I|~!Y`#4{UV<>Uf&bq= zJHGer-ogJkK0ZEvdwl%vVZ@hQIE!ydy}3V&pK8Rqm8Djw7YiOF*BxQE9EujCDc7ywNO4a9rSX)QR>?kwwNK0C%p#Ji ztCsqjZO0?B$x`p{NO2(i`F*Dm%KEy7!^4C=)RKqx<%X zEGhdWftB3O$O&{^20P3<7@$o@-^KuBPw^yFB!l;#60boMsPo9T7oM&0G^;9Od33aB5XUI2b2H<<-iP3Luw(3GK8%d@j$%t;|K z_;h9dYsb7S4nfy(ou7`&PYclV4ypukt%aNUrr~cE{nyK)RBAw zVS!$co-4q@-mwm2tcmjSX=}2i<}fo$PZp+pD=yN zSyA`&Jti)-Ld95>N+MfHxuLgq>90NS`q}jb8CS*Ls#~zrIx15hbiKYECGc!+V)_=? z(`8xC&q4H9WJL)J4Z=4rwvvxLDb5(Wd%Sy5OK2v+5m0IKl$7?JlhTao1fSX1P@~3U z47^y|PFI$4-S8Jm%y<1~bHD2przjn+oA0*2-_eWU)ojma(mP-{arA{_f!`MkqC( zFJEl`1N*TKQ-gXwf032vd0T&u(G%*7TZ!57Ozxzced7;A>d9;VY9)yh(tt$CQ5@>z z^J(6W+-V-0o5<6HL@~*0@L4BmU_PBNp`gogzW4+xrfZ_PdDU@E@JF=_y z%g+$nN{ox1>xq>m;7V7^lz$ups|g7L9PArjS>UU{dU=wfxi^Z6yrqG^dkYhMhuS}| zMR4)dtVXH=1Q*PHU>2N63T0qdG*f``x-z7#`=+xE;~igS82AbU^V$52#vUw>B^Pf& z28TQZYAbe=Es?N5tFF-!v4J73r~BV{^eKG`s@;Z0mQ3A&Ky5#2-{0w`A$0M8`UjFP z_oOYYk;dKM?wU6A{MPI|eAqExOuJ#oz`>XSmKT2Xpwj>l#{8g*Ljl?3JAa%(9hhax4r;* zQ{~|^1zIyfJgj<6%dqpPD?S4~0vOK-Gwag`*R)+GFgj2ZODP=HlqcRfpoxDr#Fz=o zbF-T73qEl>E2kS6b(XtLFXBU<#53K!feWN6HON~cC1tk-Ts%LcwS zqJ18|f7eX`@e%%}=_Cu>ogIrn$_zZIFQh6q@HqU2Usw$YUH?{G@>+G#8>8cy+U=K| z6F|q&1;B|Pe|cf597^`)Q|n1mO|$VO{`LC#%O|E9XS0e#1<;ynB@7)Ia4Z2<(@8oW z%}PE7g|+2`F%^!t@J>T!xoVZBMqSy@nDGa@O$+ji&NfiVH4#;SClT2Ej~|Nsy6R~X zq$dPu_`)+4r*%$&CV0NAUvs5D+5dC9|Bq6{d#>2}xXbodst+ijnm>bHDak&oKJ;Cx zQwhbs?ydyecl#n;l5|y8sq5Bj-7SR3*f;6|aWh`S-H^{fo$f32hDd+O_Uo!eTUU!A z^R;CzYOP8{`E8odoZiyYBG2-Cl3UgPur`~{!Hhj-#(6OX2 z)QLmk<{P?sAWAkMC{IYg);deIc!S&IUQV^6hyXdlrCRHAw5eU&0s<1N1rlHOStRZv zc8JCfVkiNgoajQ|noE?|p(qt3;U9DjuCfynINi-9iizmf>S$L|YgY_%X(Y`Q{lJtX z9$ie)XwEh_mP*WFjjiEVb;^ylR)=@I1HHQA-W#*8Jzo#BS=1@lty5d%cxsd`LEJLY z?)mnO`GS|8RzttLWjHIpKDg!c1J0Di1NiS*gWyx<%YVbf6W?6UE@znONqtf~849f@ za)~6JFi&#Nv3_dHrNG`52dt#pXpPk@)~reJwY$|@{FJah1M}C{uYT;I$-h0x$5MkA z8g-y#A}tw#d3PJqgGaQ7^j)=B%3a!DD1Gvh)8Fn2@kGX}AMkN}fsNl^syC36kquCp z*9EgQlEXyLu8!w7!G^-j>NwfQq@H8BSxC2Dkq0^_aThJugv!xU?O9yX3IW;*w9A>T zQ%nB8=m`<7W|Z8g4Yo05YxDgh)Dp+e@twYMjfaUk*Ef~Lo23t=+2~#EKbyM>W%3B6 zN^x^k#&fb*$$~gP3*}5`+d02u>z9{mro9xcm%iU@b2H^Fe?sFv>5A`I;3;pwG&`U9 zv!t>eda5XCuN+?1t`b@7$*Agt~s4gKDl4$ zs%*!O72_@|w<$LQCH_1>#h4ZMB`4@CyxA&=4{h107v8YkW8YQBvn?ry9rav0`)Els zE2atXs=iy$rD5ih7*v?l)u$~To)aiq8kOgrlonQ5kA=jft;nrVnS7niDCzAg?R(JY zF4{fIe50rF-L>*sTc$_#mh=Vhf@TmQ@e-{LN-5({fM=*Jr7Cg(TA|ejb3neSjE{?7tSO?@P zzZzdHy5&U!(;^oDW_6U}VYhYAi_XI0-up^F)BF<}4nxs4$#91g0bCS1oy3?i>pW7|&pvdzt=%Bt zcc9;;<<=*2Ax#_4J+m_wBySt;idnZmc?Vj1n~MW5^zMcb zyoUP%knuzV<)!JGjfb58%8mb%uLlOT+q{a7zS;5n?;V?uR4s|EEWdEEWs(7+y^`9n zw{DiJv+K|4oXa1z6PqBK7q48dKd^PR|Lsn+ej(oDB>Fy#piMTJ;7!ywtyVW4>q5TO zI9xrTTgHPIl4K1JUlFh0H|y*2chKZ5#;3gN$7J9pSo#!Kp|I;FeM?$?|G(pwgxHd; zclIb(-8ON*u}IM=Zy8y8()%;()b!hl_nEoWHo$sO%9I0?AKU? zo~2Ue^v394IS2djbpc+PIfOqMaF+aJ@~oT|7$GxWLUo5;e3YjULW9K+R^MUCTZ_VM z&_B%u+%UvWL=KqPxs_lt$xu>s<^r_46R#79ZYw)k;!NK|?;PNE2>EPLdh)=*`yVd+ zh)i>F5F&6gkad$FuYq$8=7Eeqql%XU8)N!jIr9X(tP)#QaEZsh5Cln8k>ltF_qmP@ zOz^*AC0=ih?bB!vr(rGo7Zlp!!$x13aMbK_gJbogFhW8I(JGW= z8aHSacIYoOuYhAn!nOP=o~_sG*|kjYYB5umN8FYj)E;iKPkBr~lE2nnk9FlMsI?u8 z!%TiHdUb-vN(W+tW45|#<2TGsXT^mg1)9#t+RvwPT}^@BrH~QzM=JG6ytG6DnZ!i5 zA_nmNm|v6DCm=LyLeDR_PnGYqmTtq*-$|Ex! zgc+j(9YYR8YhFRAFuo%zGQg2DW&xMk7+nfH4Jkx;ycXLRiABsy2KXzDUx`sn8UyD> zI?9H&Vp@tj;F~}rUTWKNU!|Q=*dy-$Wa96pROfxxo2!>-C}rK_HtBD-y4olM_EM*t z4BxAiE4JAKR$;1UI@5}6_gxH5GOV~EJxYAj&#YqG-cO9rWmIt>cM>0ta{72&8~5D$ zc>nC|%!XT;0Xs8*pBCld>9ZaeeUm%3O9!O_eQe{LJ9d0+&bZTwN9kqT2|L_RbkOF~ zgncGjRAFTTJnd@Z9R-aVyeWO`7jfx5$3dh#ekQ(g+aaZl^CXso4-@*&jaUuEiBU%q-@Ye zv&&u>589qx@DbUawbj{u%Xh6$*qiUfW^1!R%vVc!Ta2P66TO$jYhYS?iv!f8?JbN~ zHgW&>-s1S)K}#QAA~=|f@3G~P;mJiYfe?307&9@|{3@?6(2Js)>oY!^D`3+(6j`*f zG8_cv=2KnF15a{ga@NP(%X*cdLl{kstie8C84-T=oRPf^tJO(1a%u;$5OtD?vpD!L zC7rG?4mnF}A`W#`7MWWutZZM6uV^|hWZ&%7WpRZ%j&=|NKeXCrj1#~rHsG#{W@}S@ zn$;J1U5rgJLoF8~L0R?8kNGtPJ$cYb&5lKqvxAtj*qL& zcn;eM7lOBt3#>1`2Czbjc@9loX2ldfc=F9RCzMvFs5nIgxUrmk^UcQ-BtsR{ABPG= zD1P*Ab(4Tks&kickqG@9QiDXbiiOfJ4XD;+CdD~wpGw*aLRPovmCAN?3iU(4Q)^mO zbpVTPNhUKFBzL~%$HeVgcky)e{F-711nV;qEW_JYlMejG#f~}6SbU-0Nm0To zh#!A>0V5?Bt~xjE<9pl3_Yf0~@9iAlQ!t6N<4uWa3IUqbU^$$XA{D9+ zTld#JASwqZT?G$X$#YX@=h$z?=@%z?z(0%D-QDD?|i5^k0BNAu8hhJb5~Zt@xJlB-;QVKrvgYY2CcnC znfpxAhT|9yaJgF@KZAgPQP=gB8&B#rYib^RcMA_fo3@Gp(MG~#7PWaGoojxPGib%U zf`uCQ!wV{rGA=l*D{o;p=!1P>^#ii?pY4;+_q#V={tN!?y!}riLht@8gp!6IQac>d8N8?}TyBOlr{>knor2n)Is@DOLzC z?XjSa;a%JnBB!jIl{TR}+Z0pwL{8fAGMQ^kE#bKsl`_X8NmgpLs(j`8G>o%1TIUazlZ9VLi6tuow-yFNedI^bZyY z!$N37tVou4L-oRrhQlK)w?>t+5c>aCr2dL10xd00E5_hprKI$A7Ty z*l++he;*F7 zp1_uTIHJ#DuOEiPA^ejOir_!EqF8TlG#p)Ubv}H9^FfeUzRv9v?u7ftzCc7hf)Vjh z5X>vs5&-`Dh`RGK3}3>-iGqv&;CO5k8U$AW90>-y*Z2iIBuBVY4v&6-4?G)=PW_L* z+Wp&b^lSHr;pizn`;Cs?=>1_Zy6$h#*?q-L-SvAl9DNu;Ilv)}@%eD{0zUfGZ5@?K z91TZL;U78-uuyMk%iJUxMc`PjA42otP)Nw@;qZK98{8jtzvBi1fY2JT;NxM#+FO)y zbsnka;L&jOctj6>8xDVl@gK<=j{ZUeel{Gvv6vV=3);PwDvtpA-*N7iko|?p%FCgk z*61f##vxWp91_9!8!glbiOL&WZSp6#z3}smIv@I^$c7;)wfKVg^TZKe`28PhQGza5 zKJsWd`Z)4&>IazOf7oq#ZJ#X|e-aSk_4j<5v5)I*PhU6)+wVyT_7`a5z~Bw=N)QN! zTyvFAcgMJ0cQn=EIi7AgL-IXGh6U{6P*I)HaC8RS`IJuka~}MU@HU6Hr-<#Tf9MVy z!A(HK5&nM9HA|sq_v&ysyn@F^vqM|w^Bjk_Jqk~xyE^eNOO|l+p1AwTk#~5rc}Q=N zSn4;=W=Lj#5yCS%QwZiT0T&zy=7`oBAIik0IQF4bI~A;cJsj;|^ZS5PQV13I@9($* zxbb{p{A2k7{k zOS8%$2(ZW9>+V!NA09pC={eN<4K~~D8~znh(xcyzl0H@Uvip?lhx>x#w6xz5ZU8Xj zFS{N44R+C;Iro=467C-a{cJe8|3qy(w#KD&f4R@&#Ywk-Wxe3%#i5Ten*7>*al?Tw z?~fcEg@1;YL|+`*H!ldRs`aaQ4>y8m!D)6wcb|NQoKJ9{y73}df0Y32<0l?>C9rV^ zo*`cpoEeKLObU_Y2our|J~^ zZ8&^z2!P9x!XC^2Ah9_N5m3(4?-5>MZ@en0qn!$Jesq8=oyT=%5PZeJjS^v>m8s|% ziwuH^?-dW>&;Z^{ME*$UAhwh~gvq{m3UkLwNlgEc!>y8sTT1T>9K`^^W<%n_ST9;h`MH(N7*p z9{mdU=8$lT-T>0gkRU%LdK}zS?xz1?c=UdxuI(R?!YT}hC-q^7;VhV044=`R zcOx!;@Im5QD6CAO8}Fb)w-`N%`V9lNM*Z^~H`Lvpfl&J#7xfu23Zth~uRUO+-OzBZ zwn90bHo(FoOYfhmbv(i|#tg>M&*24#2gV8UwyyjWMLZqB4KP;LM3_KClhi^=!-rqn z&>?3-!^b0g`im!B5-A)x4S0p$ET;}Vd5Q=QSMr(T5CTEQ32-=adwm>PLH!MJm~sne z%pnB#e4q&O1e=FXLdq`p^M}I_8C)AH?To@b7ZLYpNW}KYSM`W^8FCjm@F%K`du_=D zFMM#*1;B)x*c^qtV{oa9{BnQf3oxL*IQlCsQZcezG=7FJJw;-n@qJV(ogdn(d<#`$ zkDm~^cSChdz!0!^cR0+4+%*F({1uA_bL_v+^w1Gow4)EItWky`L59H$*D?xK={8D*UU5fmkgH6^Lg*EPWy zUU(XW^FyG?M-vh)?T(><>ehth%G6I}uTf?r9IzYj{dM%$uW7AO#|>n6G<;^8{Qa-A z5J$kx%Q~TY^>V~_b|k}%V)5^MB!Y4MB)Gsyt$PFtsuc{2W4~f<_4|<$q~zfTt78^M z^%s~R!4X5~vWBQ!z=6G7B{cxZV zgZ@4oArXEW5|BVNbsU>esP{+eSa>Q?$K{lxBpf>&X!DRoV}!%!)RDed&NSdor~9N< z7=c0$-#DQZf4Y7wwZX}EAOfZzDU9YaM-NAeZ}KG5*v3|c#iUv)qw%OHt~O69QrDFs+lOwIcAt}-WB3wLn-Q;OJhWrX_e2NNo5Q z@?gN9KH2@j>Xe@YSAfGpq4GJXDUkv_x7ruJx}GCv>jsb0`oZc~Wh`<$3axGJpj zlt0X@^yp{1oWCj!(@U#im41suHDLTAE(Xr$B@7b*!hmTeP8V`SjH=+!zw{uo)kyOo z00iHSLCx^Wa@&7{WntVM{VH22fBgUx2KFA*V8g&d7h?C{NQFq4yg5>>JrQC$3Qvu^ zd8pCbd-Fb&=E7xg(x=GQ+fPDb|J)J#fOh!3)iVJm#=*Y>b~#n8>w@RPfwtU+9*JXp zpF7izy(#$N53q^8f?nyup21NS3NrdJY~vIkY+F3~{*Y9V4u70x*^X}%5*_4jzy?Cd z{SwCHW^H#yZHJtP%_pI5Ue4mqwX6kyM zAu#Ch4tHM)@v_A3EXfr+{B{&rmhkcar-?7iL_*hiLwxeULWM`5rJvJEi@EOm!|;t2 zs`(9T+Prsy#IOdR4q3Y__KRPw{`5b5&JD*jQwA&haG{jX_Tl|QVq3k34-W&Y13diw zP)6xJz8E>~Rut<1V15Yh5TaTbD_#p(FK1|a&WQGlHT-=%5>??#&C?;|?U54lf_LS} znZ)onO_;wN9huR93Psk4K?slhExwj=1|Iz`4*; zWKBP8G!gm#jrvOrUlTj`f494Nn*7V&qOP0$`QCSKLbH>*ZO9qG;fCB7crgBMZNuAv z_$Izh{t9?nCm>)>_r;tFFjnq9lLh{rRl{x=0hi)u@;SI`lg%Ml?ES2?!k49Hf_Md1V>HbFX@a zmKWh8enqx|c#D8deD0)Ke^!Veh~$5z^Q95}x%FOQ?n5CunKyuP-H%aSbE>0>*LC!x zLh^r%hQohg_m5B1V~2!+LfE}{h00TRGK6#gpihRA9b&`u!%=AKbPesb9HG8DC>|C2 zo|k|PAfr=n%Xuc&nGez1Q`!C^7MamQr7s9=HEuE7ZQ{v8j{`+Lv&Lkeay($8CkOuZ zH)L{xPy6m1yXaaLn$288H!`P2f9}kFZvEWdb5y3Hv9rySDm!wX|e^E$?<{2os4C0qiSW)RQ$#<}3JA;oABy=2u4ifTkQhUf69Oc#R0`gHe;5dR zO00ctZIKQ|oVC^=oqHxO4EIrLd8(GflXtfdt-OSG`=^1%hy0qvXXPh9^C8R z!{i#+0h_M zn2Hr~$jj++Hkm^12FcA>K?TR+LssWq!%IcM9*}^8>lSh8Zcgy|`qS0vdF>DCq{Bro_zE4sy=~CCs=>(q$*ePaVtb`j>KAL80dE@$5!d+;bCB zsa|myoZ;Hlcs#&ln$N3p^v{6_rX7fJms)19Yi^3ndB2AWc9I@x~a5g&OD; z^Y*|SyiXK(0>ML>h=c5~k%8aq-U~~Ux!ii~57~5?%lutJ+0TBxE5DE!5+n&&wSmbQ zhb3dcDT0--S_4JbZQL9s!l{coEG1Q47xnnU(2#T#XI6Jq)ZI9%a&!NIii#v?Fvf5H zv7FbtI`tc7;@I{3ewXf>T`g|y`hB|Vzuo`-wyux1(p{&wj`z_{y65?-o|F76gFoUEk*|qrgtsVXS+PX^r8F+>5uK!h@w!sEy{Mw;U3U@J!!+A^Jc^ zRqQiQFoT`T4M|0%yY;ObXI)Gb$%OH%Kqfr zlb$}16WLY?t>&O=c(X@u9zi^LbUGos6wdPD_n4c?##a01nRCP8M7iWnaHdl z*5*P2Y`^7@w5D}q-@V)Vo;UYBxUDZxoW|bA_ipR{Z}-1O?3f%W`@GA;blq>@uHbz{)^Ion@6*=Ay0_UHrG|nyajs*7GhT znB(kA)%YU6$`PQ-Fyj)9wa=jY$E(Gn(=$Kk@AEOF^{ubx<)v9be%q!>p1iETl+!n5 zHml&SZ7<7dOhr_jI^p)_ra6QJIB@ie^BHjJT#5-8cG#S9KGo+FGGYGwg7V^F+F`iK zDW&??Uct+9n!bP~@!$k=AeGbLs#S%yvCST2or7#$^z&ffZ0|g#Oqld``{DQcEUO`} z6Z`ix9GI4dcjX!k{!ItF|O4_RL1fS{bhKmo}qd7S~J~3HkPBtmz|77#{_+nnw zoDSgl*#0bYA2V!zdQNeXkLO4*-5C5FKeoItO)A}tGX;IWV+-rGS2lcrtKOE6(~~b> zjC%0>4&_eic=g$%DywjJ&}o4aT}hfc%!+f;KhZf_VftP3k7Ztd!ee$;X6LqO4Q1q* zVxCjJ;|OfO0Vmb`Jk<0rjPxp`xWI=#>3s0m|NZEGKOmJnKA#9b{LZ78G@q>27)hrA z-W<3*tBLWdjH=W5tkbLKFXq>IIm)WM9bb4r%0lXo+F8yR?$K<5ge0@&YvI?a z_Y2d}$U5PZd^VBaSks&Wbl#Ce%8c2=D0!Fc-E zKmXZ`mZSFHBVI_x6U*5YzN zZdeti>QU(>vl6ne6A{DIS2S*}wIM32%lwnC$IBARJ^0KE>xO%a%$8O{I(_s(V}pXR_# zn;E3qGSy-V5Ho@);;3Z^@F^a&HdPn?DlL|uSyB=YR^F3IzQF8>?g_AMVT!;#)^DX$ zVa>S-le(~5at~UT0Y9~iqah%a1o<3QQ@ahL?Ba8P)zSIMu$j8{r4fr%9a;sIVjY=} zR8Rkd2lT-XWqMrGz^qOTpscUc!UI?O0OrA~9uzcjN*Z^3*LC(i=COFWsIoDfZKbl3 zJ@-Ux6KuQ|y1le)s!XS_Q&F+Bfm8FW8m2cq>e+Y6->f9@#$Fq6l(U)2z}%H<1XOH_^9!Vpm+@u(&Sk&MNBBo z#e9B=x!KDcH#RW8QF47MIXKQ{KyXimVag|fIB2g-$eIkVIwCp@hoU`~VqJXp6bA8}yg? z{E|u(U}*xBLzc)cPH;S2S;NfcvkfL)l+1Hc7BdtEvEHOl{{SV>GDgPu))Qn_2xisy1UoHjbV<-5sIm^ILTP)_ zA@bd4Wp)hajfg13jCzGiLy|ZFAX-mDY zvcumof}K{f^gqly=1?`=PJTE%jM}-P3-W~cH6?U>m=}{bbgTg@UgvfDZR@mbbxrF6 z|1GZ0@qdsey7kU?0+LGr#Zyb`fm17H=55ABZOlam>@`+F!Gb8+c^|k2L_7FCJVAJ5 zAj+p_8`Admug~CZ&m3WrTmK^fH=CKPuFK+dS?9LuWQ96R;mk!}`Rlxx4B^skYmXLS z&8$XFtK*`}1YM7!l0Q2gr{uS-bisnt(l~axsnNw<8WmUPcWDJXrP_HrhBgJ{61D1s zi)YNNI~QHo^U`c=_k7P9@t;9x^jWGKfj%@y+HA3nE~xp&7holX%l`P@*6}^7TG2dX zHk%+k*if{EL)DH*u(J8TgZ%>vt2Qmxpb~c-)<1{j`pyjHDI}fn67IREN<|L&&X;{| zN&UZaEDp3-=I`G4CanZjw%g^*oYbP+I{_68`ahl2+4+gcw_U6E$*`hS_R-X3p7+f2 z8I+>nRKG)g#4cHP--~Q*pyFVYCbWQ7=uR4!1f-4Bq z$lgU(fgGw^0aD86-$MTEx9@gW$@k-BS>Y|0^i#RYz*M!b2H(p+=3|_?par!76rC-n zQ}1Cz$H-v?%X$0d0BKxZ0z}v*AGAYOz-?ywU2Ux<8tYaJWKsn9cI%xg^RRi)()Md= zvHea2Su8k#kd&Ma4OQJXk;9$%jdSvq0nq-f?zCaH-^FdQ#bQ}qv}LRvUAr&gncGN7Z(!j=$zz<`e9`W# zL56!8fo8yv=*T3R5y7PwJb-NPUk9C^k`*|^IlRz6`btgp);ST!c zXX1M;IRqCJy2Gx3&6=MDB5cq6Mt2?b>JkqGdW>nFeV|IJ6+*4hIFgSq^9h1Go6qan zyw0g2mL;<=hGN3iDw2NUc;u<}or5xY3opap?Rv611IE%J&ih$w>d1+1@b0ofW zsx*^)KX8@v$r>VqEiJ?Spo-DfL(3$Dj9RF7Dz46t@0qF`?;qdeDJmK$u-E8Yt~OGe zz6PuIJ^GQXMPJLJZ)L~#%te`>xli#)?=;XgnkUqi*yq^}Osgu#s3ihOEw7<)Cgf<= zmL5CbgJAr~Up%aR7;`cAY-yuiy~Tbj(A8ppU6O|jY0BY1$0JdyER_Xwt?j%gtYfL7 z4Xl_Y_^vd{W&VlRYS&>m_%hl3_dZRxu#~TFr<~AKdk_{u?WT4fLE9@t!={Tx-GN*N zbarWA%oQ@)C$KvwXtJPfIG>{#aXxhg<{Zsc(spohO1%EQ2p#dGNvl1${pa&DuK;5L6R6X-6D$Ojoi}`c{qU6c(y%Sxlv&^%p zk^|4?puhuaC2}PAf69Wus@ro$K56PS{aefP0OH%&5emLoU};IgK#I z8VFQa!m_knDI*H5%WB6{R81+r)8I>;(Dz?9Db z!#?EZ!nqlwy?2~z2wQB+q+%IDeQrALUS+S<{n)jnZM_kSU_ksJ)v3Oi&$5{P20x5lgIH@_2O=Gt z;7Vxsmrwmt1?Ebr^i6i~zP8t=U=U*Tn{4apE>t_0P;1~7iE2L_`TN{NOzc<54r8XM7P!@70)4V(cw8JQEi4syQG;C;b)C<8>VVWmHf>s@pH{zS6lOM2 zz2Nfe3gaC>@_^`@&qkZw&CRM+MRig?uS!r%JrRU64<}tG~+Y%3S98!mSX`qrS*LnKEBi zx$<3}6!iSDRyZb!!>+*{oda*{Xu3_Q@PmD0sFI=o$z~o}m zMT=E&J+12U%Fa&m#AB3OM#?Q%*PHcj80GYgV@d!+#eU+sLO(ygm9;>$9V;so22Q!^ z`84#PWA;CcvvrSOCm}W5mmJDnR0|T2+MPaGL&Rk2;uu7Y3D@hO$G=59p=%+W7&jX9 z_ydgMWTqr1y(i^-0aS=9V{<6%Ow7aN3`I5>RFdRiEfjY>%NXY{>$+hA{>RPje3OZ| z9h2g9Ow8$+fX_&*iPeULFZ5;H{Q9+&Ol^4YUrr{vnwoniE_bu)sx;|~(s=Z}`Ex}6 z9nm)_5^FakO-b$Rv*foFo?$bmbA#BO4W#xfT2K8R9TosUbQBA&c3`a3q@IkjSfvLiE|wuuInb=J4@80AX;p)I1ox zP$Zgk4HlmFE*C67f6I3}YLs^>K%Xc(FLa&Bp<2R_HDpUIJ9mA`Yf^ZEuJQ!ueFA{W zoJ@MAT8=Lm8ZNc<=B)CpB*R~ISu8j$gYig*O+dkFnnH8Jtc{88kgmeHYTy_ceqJ#@ zg>GD+KkS>ga^q9ecM)~{Yyxkeu1RV_owbt4#`>$3(#IbcE-OCkYG_I7Q&mP=3HNYiBSO1NWqy1D>;*tsPwu{*aYD&Fkx2LLao> zrQ7I5R#lXy=t*P8lLp8EI{fuiSj*T5eW$I3RsT75*#c`F^Q!b@HOOlA$3e&lgOB8B7j84E`MB%lA*a}PN7E0o_K_ILZb_v zv}6YawyvoNbpa(|Qy+;n3AzwPPWC`(UKeq}hYPe#eSA+Fh?I99us$}Fy91JYP=uC* z;A+N4&UT@qDL;14D4R|;zu_aOSW2zGH-#SqH&L4 zTCGmUyQ0vr$#DeC{Zu*ZLS?F)l!BBjPQ(n3Bw=-ejUwpZJ2CUN{QeuoOiVnjn*)JDYsRQV7}B}<<})wtjTd!yq8NzX#=J0!!ic}s zbNgkxR}G_oxE1WNb0+pxeAt?f8O#^BE|{}2qU-rlLpo-i$QH^m07Qsvc$LMnWmV%< zqWr(D+0qL4)^*uKIPU99Qz6&M_qQ54uYSkpHecEJU$mZ(KkLk76F6Znp7uypRxq=g zS?dN`SCm@w3|zp}mVEoIH0{V(Q0lh%CpNY_v6^<8XQ;aef7(m5YtnguOpqo6fHV%& zra1dutLk}}V;wq>L_rvmZ1}o;G{eGj+v`5B~cFN0AUtR%v_`!fF&T)zX= z;ykYtE&86W$u`>cSC|Kw6r)jz%o89CVR!uYXO6vaIuviGZo;pu>DL`K^omB+rSAmW zH+1F>j)nk6pdud;2)lL>aMZt-nw$7`25h`c%z6VxBj7Pi3Q#y+nF?$ZVi*b%{QODW5oC4iLo2G57(;PdB^uoZv5+!ov;>V4tFDd=7vJhPnso0 zx!bY1FPe~Iki2*3P%?Tn80Te&H{)hJDA!=h&_P8t#I>>~}Z zTK0Xr>^`HyJ~N6v@(i17_Y<>U&%SC0YYS@f1gqmwbbI}I3#_nAy-;`JjZ^*b5ol(- zyhzX0te56eZs$(?HTi1(q#d&#;1ZW)IYP|#KD`3L{UOp)=?(h|CM3azpo1vKcLoCr z!aOxn1Z<1ysXxa%eAf;)8uRsF*4QC7J=C@IP?J%qXu(s2(GN~V{k0#V+PG$9HjfWs zOvmJA(N~mQ#*{X~`%zU^}`2( zP*|J2uWvB)0W%9u^IF+~CdE1M{aPo4exn)r(M#qQWu=KyL{eMG)>ad@n9g4sT?NoG znZp#_IcNYL$I_hP51pj5T3nzjMFO6^6dxR zJc8lox5k|`m)5qQMI{-!S1PMe$N#C`k3spcpr z__9VbDeBh_ICU$Ea)f!<8vH&KINRAKYU;5DWJSaa0Iw&@!up(RdM zQT>F&^2NBe;MSKfEYbnUnC~L>Jc1Zt!+ywdu@(=-Shmec`v<0P9>y?5b#F5TwnKXj zK-fQE2< z)@1)yOW=){*ZD1xTl~hm$O-f1{Dbx|7Qb!l)m_h3_=t*s0hcVx=OC54$gfOxo)xoR z!p~|rnG`h%-G9K}N{ZF6Z_n+nRr;>;oGY7D6rMlhzOq=xZNym;tQ7QT)a1Eh#kRW4 zKoXZi#t?iGSs#5?$8(l+jPiXwzT`65_ho0+O~l?)(JhgnOH-$USh@Xqyo1l35YxO)hSznIf8KkLsx>P zO}-F*SFmB3JE&}&F#1MeKtip6(Y1-#eD-uttijjjE%}cNf8wqj8vfmAsg45(!nmLsp-Dm()XulB|wc{HxYc4x??%! zXsa8B8|fz$Y1C?UlTk*lk8c0}a%`B{|{Azr)fHd&6WQpUv3z+`BBF}D{%*D&rA_I?I(mZ!GzEC;m zkgW>pl24(A98y{E8>ay`{orA6M^`ncS9b~@m)VFtrY!);kEOKc_CqnZU`r{uA(I${ z7|Kul01uR*J>o0v8qd3%!hyYl@TY4ciR>%cr0%zy zw7Z&CL{yXbAf-+ARucU(XelwhY_M_mUg>x`BE@L>J5CxUJ66y0kMt@qn)PM?O=~x-`eNZdSrKZ{F%Sb)O9dW9Gxl} z>y+otuay0BQ@vjhxdd7_lWF8`vc8tK> zV)LFiRK&n|oNzI2b^HsK6X+{3P#d^)vTSz|^*N8dKeQQ78Rw~vF6`V-ekquQ>kX@a zKCA3qeE|vx-c8{yO??Hb_M_#AFtP9L_*bkZ?|L(8GbrzIcy_4Gg%oBYQiN-7f1kT_ zA8k)T$xGH&3k=6R^oWB60uSySrwbFnD{* z|9L-lps^Kryc$2s3z6Q(E-`YgM|L1TAWBrHm;{?LQlOF4s}JMlS@bQ?zH^UfYHH*t zyp|G{v#N1BRl9}Pd@umZ;{hgS_5FQr-xO2eNTro}=rz7BW|R4K^%In4cdhl)Zb-{s=5?k9 z$4~qr;F0)gUKP9;b{PJPt{<^d=6Il0d-u$1`qq}>eb*18w9epg^g|aYRn@mQpP4V= z`}S=jGHN*$5Vakd%zh_I zEzr>C_S^}HahKUOBuns}V2qIr$bFr=xFJ2V*Y!q6!$hajYFtQ6lt@#;!)|bB6V8it z&F&k%<29e@u9prok1jBCrX^J=sK$d13bxVH{t6OiOVq9a z$bliZ0Ssf`WFPkT!xVsi2wdhI$9z{ZznQ&O_xJVf?KfiKp&^x3$8W02RWx9MlVK60 zKaJfel@fAIIvt?3ayU0XFVPY@q4Jl=n^M6a^d#pZ`I~UEMJU6<+$Zy4pTp=Rer>-R zWvpkCDh;|eZKHEE5YNPRNCE=j-SEADieAt@`%lB*SDx|uzFo5Ba8sRsk_SbPb`!pK zk|Z*?IMh*!Oya@GNTbxs;5Je)EJJMZoDpSUE27topEH~1%FlL_EhU37Qlq9NRMCTs zgh`j@GG1Y)yhx2A4&M$_fUaQ141CY?Nuo`*E}ColG^`BX)^bd+OsP=WJ7gU7@MgvP zI9X~6X``2klj4YJFD{0wYTR3I%`^Q^*Kl-K=|IINf;Z*+)Dav=LwtitIMfLz)>l zoG)vis9NOu+z`T#*o(Usp6^wt9kw;7g@~W_11Rp41<%uGp5o4wTdYX@*04GKgmvG@ zsEKJIVBL!uk>p-#((J)0d8V8*XqjC@qNq9um+|E0;;L{PSHyRSiUuj|>T_AFZqo|8 zeOi5oFds(IF&1f$W)m8^0*CYH(r`m4aY1))!Jkj^SzU~?DY*>WQuUBbgmR2ne`QM2 z0Fi){X(L$fMB+T1=L@E>r&o!V%u97>cO#uPu{m|3^`eMC`q>kcchhejLyoJLa^^v&&>3_&{TB#<<{olofH!W>Z82kYtKsb@?D|qbnhAHYAr!-tbc;~Hz^N+EXG@@_6)wd+Ft|>z54L3zo9Ul=6 zmrl(88k{T5Ihc+&`Yjr6imOe6kXR)RqX|GWpLknx^bwD)qad9ZB0>kJv4Ie0_nAM%+*o0=&W&Yl*0#Gv*N84`lrPOGJ))tufP z*u|SrvIH9dd4l@Pgp&gUsaH!Ot5V6VHJWV0oHJ1d{I!(~dD~B4zhVeM)_q;T%T9#6 z%WmoD{4@487YFF0(TVbw`D+vAENfCxsP$i4A#^3G1Ozk=%h^Nzs&nE6+_YZJ7#y7jz0oPYP#xg5Td_Nw-R9Gq ziXXm3V~0$zBJd4C!!g2lQ?DC2(`X4-wP;wf&TjndHU(FNz*HhFpXM3+=!N<7NCDwo zf2dN)bUr)JOBrA6SDi-fT}1EPvhJ=vFAXFwQSB%86}U5XY?cOZVg~@` zl(~3Oq}cXS_-G7>Ej-Lr?`wXe*$(8|*&8^l3~?v_Fx~nusz^mcQyRs2UjJl=+fLWB zu-B<_97=}A>Vd}E_cZSton!r#edF_Ipr4ZmJx;=H`PK09^c(JLz_&7gsXNvm7$CyH zN`8ZZNnMjGm*vLGB)~3s-eR0{Hv4u$(e8Y?5Md!a!AIeBwYTjc@5oIz7LNOVe?JXE z%JkIeSFHx9hp=J<jl5rOUV#*DLid|}#HQ7-V-OSpPTfd3NHw$h7r%Qp5Sf;S~vM#2T zYKvd_obt!E9XH8a!25u9!RjVT6L%wL=~eJ}5W`tPI?L!bjA4` z&m_^*(+qEb_6(iTe}sfmeKW({T@|XPk0fCc)_sCEJ@^L_I+6mDC2@oRoG*9iK+?^j zBx!E9yv+J7Qhv7T`DKozPKNV_T#EhSxYARJ@81VSFwFydbu2W<-dB9c2_y`$^%e(_ z(aKHskMChYv3u{j=51Iw07sU71=zAd8Mf06z#nLXoqZZWWMy9CtLno!Z3ric=g?lN zf_+ATv*4~}UjO=x>;eloV~DMoZFquZpRls3$^Ws;rf~Mb<&Mo5A6S;C*rNAao?Sx4 z)E_CwHr|g^C>6)>5^`}894t6zYayIvlYFC?otVk8Bv0)E2tYQjH>>*7G_QK&s)A_w ziH#1H%EPwDI4jFfz_xMjChSOc?8dOe%LQOvU0iXgZ0augy;)w*CixQqxNo+<+uD_? z;=h&I0_TX1>BS7&LJ=ORB}fHpXi?#@%PdDY0U$whM1HP8F>%1Ks$I_K;O^=U29r4{ z5eE8sM`Hw3Dkezwg)HdY&ore zE%NIDc=?SlUgnb`8}wLcXkq$?ysS3Le6k$plZ~r+jn@$U?x3dJRojKFD8V}x$UPjn zJ$CP@^7>72mCu*;L9z}rc6`D!HT&lI3=PDeRB7*jEc1$@8U0$(6Sui~uhq2k86~VI z7B4JJ=O9C&J^{ulC2_@gX*hz?is76+5B$*#yESu0*{J?0T%qLg*DI>0Ff($5?qHHh zn0uT60F%uf?E6cT4uioPI)>80Q&RH6QwzCGsd+4Lg&U!qsv9Tasuwa)x7+P@2bSS% z3i(t!T`%$mC%9o2d5MB5gpJJR*X>TnIi_2s8}x@|hBCF1G&fr1yUxi&E_W13_Y(}p zPh^voc-sr@Qe_eilxUw?LawhM z3n`L6Ou5Z;BhhB!76W%AJFVK-FUX*rQ3hw*94^#rk5Qvhz|?>$!O(Vf*tiS<8mzBF z6a0+M_)6<#P4_db?k7FJrV0-24v(Tozkbv*G0S1lNJ62})CwdMfM><5f=Y3-PL#=w z7IiNwsfV8`bFeFgyo<06K^|u8ffpI~vmr1od#P*)8EPdm;6s0(RYGXOBDFdVgW^_q zE_q-xk|HCBh)}A#_`6B zMYxDcViZgSpYGj}^%8BTFPY%JvPDO5eC-%4BPo_|#TyK`-!$kozDC=ab{Qj!0MC1M zSzNUR`RprNLMse}C=;cs@%)L9*0>T(P ziBW<1$2#YlXz1Re$~9>{xSLWKt?g`wu8rNe?eMiX^&a}*R5jK>Go1HVPEZiqN(ng@ z)1ro5Xh+`)@{z6hm=a|=s*F%7`5s*+mLnwImEpBp@Y>Q0JkKy7&<_ZsZ?sqzwGtwT zt;(fMgN+_9!fR0;e8;-k1yQup(niJ0pM3LKVBB0)QYZ$Og-fg8CTfy`5HnOy;QGmP zI*ge0T{m|`1Ybqm0c19jL94Un$I^}Gvspf_+fis6AJ%L#Ir@;#>K8>-=d-+Qx5$v# z>iVa?vm0qT8bPb$uD(Qs_78mwwCzi%=LF|-k(cJltCu8NcF_;bK1W%qT+VtDxjrj^ z^$Q2s%qk_Br9Z?jX(=noFfn2C830rYBr~)6yv{6@BU>?6Y5ptC6v?w&`6A1$Sq3SQ zp7^V7!thdaTTUJ|?I6d1Ek5cbsV{+YDcWo;yxCm6HgeOJ!ALW*O8ZB$q>cDg!6$wm zaU0ZQNz7o7rZ8lMi{wV!Cr4;PsfSo)Gw{S2e%Jubzd<|x0hJZ6%RE=Atgdov4uqc1 zO>jLD&n|Qp2uPK&LN0M)K*1dA)dHr#eIcP`i&Wx#6Iiw1n<#&|2?rlpu;Op6(F775 z!}RI$U8QSDw7)FS#Z*%Du2f0h5`#dXq>2M809%p8+cnc_z*X%~8MvweUB@dbASae9 z9{-vw!bMgkgpH^up8Niym9XpMdmBy*?RFAASu~BeTjcT3x@a}G*?tGwk=FL=CVTs) z^$2UvhHZlVK?>PgU7b%>q>9nPN_$;qbW&yZZs&NSFMTER<6Tw6v`EVSFe1fgZ8laj zH(z^F?QK0qk&%v{k_C79g-uD;R0>f_EdbwzCB#M zAW*ZQR7NmiuaHcV{H>;Uq1%!q37B4@1}k94-;{a&8@@wuUGtz5SiL#508v1$zX}1s zbpo30+0Iy+$CeG1MZG0o1euhe73Q-FTMAjsSS1y@|eiSEw3+23m50GklSl=ZD&ec^> zW6Eij6HL+}kx}Ul|2mQyNgWT4Hbt$pA+1?!OXj39^tOSqS?3%LTA`vuI2Y4Ni9ue$ zF&{5W_cJ)yj@@MXg<_x1YX$Mi7lHG4Yj2a{f;v8@93DGFeVDFy;CMWaROpxb(;Hj@ zWP5ApLEOkMa)!_zZ6#}Si7IAVP+mvgSaSgIv0#ln@usdFBY2~G#cYNFehUBXRMpP0lqB0oPn6Rjl=xf8zO5)p0b@M}U_ zhgRUR?u{#@;txi?dWq3Hb3896&Ksd(zk-aT#j@$8InBW<38EQMiMwFpdCA(|tH2G3 zt2B+LOR%lC_P`q=Jm=~_eK@c5Kv4_!I-lm_dR`8v({>B`2Q{gLapic_pe~gCpi~Gz zRTQ?RQa}xCEJZE`z&5K7=TdMCxa~(_h?n)nz$&aTowwL~ef?cmpDqkzr5M97jC;i_ zRJQb04x)S^)BR8ACo8JEXSPOJM4VQ$2Mg`(7|>)BAgZS#%*OQ+oY*28UyAy!A@z+4 zttR({b~vCx&=T!`s!KFeWnm0vvFD#QP0_>9SNcFa=h(n&b7}`p4#MKDiz?UA`o0EO6|1H6W^%nUYq=XXWBCJG zH&RBVxB180rekY1vNS+IL0}K1;dxA{dAKtr;p{fWiepjR2H56KGXna|EKYJ_$)NL$ zo<>mVBLECmBoOpmu2ALitCWsAY&8n4Ai3NX005GC6)gSCQxl^5L668f`>IL0T4` zaIC2|+{#%MyXjUd=83&vH&Q)QYjAUGJckN+Y34^lCWL88I>~_VgB?F zmw=1H#M6`%I>_J-Y%-W+ zt=fL#U6H11_CSbAMu6G=`ZC_-W~8sdzc)70hA<*IF*MS`yz4=OXa&}2p{$mQ3f)^M zp9h=u;qKkVig(4;`HGhi+pN3^!lh!hzN`5zGj&&2U^=Xu zE|*}UdMV_B%mddA&k)P4VA%E={~T$uJkyd~oYMXlhGCV#l-o8+_z7?4#8+2{C^x~q z?HaE7^dFL|Xj%M9U`)YREXkdh<1R~)T!tIvz$}OdS~jjv+tKcqdP-st1Owks7<76< zV>p3mxGQ>siPDSN`AHY!)FEKfeb@EYA^v}@LZn^oW4!aK7M@R9A@Fh_H9plfNErsH<)+M0Iv_)UwZ2}@ zq0+=;j!vey3B`!|o;&?ll(rK$Z2!=xRU&(?a*>G%bG9z#cTcallM8(&b`ROp9QT0a@C zt~1GN$oe|5#+6+PA7@1zgh*mwWmZhBkjE2EEFs0!;b%I!ax*v7WFpaftrI&5JHJJ@ z;`D*t!19-}#8NO{uwTuFy68fd5760*vY~m{x-t{mnr^FD3K&a_(w&CP<47iY*11$n zSIQ(2UVDtn`^pTl$`pv>aRFD@Q8vm9Xg&I2tKFbRx5tdnTw0U(s!v#?u%QGI+!GtUz7D)Ic&y zh&F~o`rDK*^>du>5ezN)Y!YL?*29PrA$eW{^W)c;P*xdFQf8AoDM4>nfBsWOl8}p~ zF*cY?yd@7cU2C!CZFvS2Gxm8AeOHrJYGmI}5^V0E_z1Vii zb|6V(-0Zms=)P)>p0UY0a%7eaLISk?$$lnbdGnw(W@W3L0kqM2B^wZH*O8l4=CN%v zAc*~B$XvQgmK(D8c)I(FGt$M1yC(WdAQCPVt4u|74SSBRT|PpwbED1VQ!Zze$KyJy zh{wX5W{g@Gwob&ra1L-uXwge5nA>zNB2-e$SRc=hrk$O&6;kNu$i+AyH+PVk*ZzRe zy!N$HbMqCt`VtK`87_4gJZ_4;w$TxSu+rvcXK^L)VR9E`ig-2GviRfdBH!LI!?;2_ zs(40b%o_|A1Uq2<*av1Hf>S?kx3ug2>el)OM#di+HIe7vmxiL%P)n&0j7Snm_h_((n zRV2{4I15`~7xU?a6ddSJ2A9$NOci%Pk-dO?Ozgoov9*!000(`&r&$u31s;1Iy~w1N zHhuZxVvvgJ2uzA-(xk3Fui{6C-lG2{r!ov7ZP5H`8$d$+>j!kQ+LveKMN8Q}J<5*$IOw%P=^c)Ce#YpbM%(#16+L~E61v)FU$3!8Fx?1*M{+|=SOD2CB8b!KCYtFC z6VY|+J=xd}Y8--CmPoUwJ$)15wTd?J2;$2tyc?Ttp44SH@KiK|f$yRG72;l#3i~eF z*T7r;Zg}Qq}EiBCOiaX$dIGU+L`{)!}zkhTpy!iAmnv zLCyUd^r@h{wS{3Ydn<@CNUuS$TXK*$(`~7ll#!4dsIE~Am``#jNZcNyg6&9bK6RND zFsUE&Yv^fX!&7QyPudy>ae=7T)>=GiPh8QVdrA>R z>VhykhgJ#si-9@5nsSSDbeZdkswxu#@nhr_j@t@14U@@gf3#UuKetxp;~6=Ehq*=2 zV>yNx%4p<*L1|{fY$YV4d9*B&*SNHfK)3M=8o%kA8nZDMOlB4rpDL_~#D2=3_(&q# zE%^b#Tyd3`=O7mq=NG4Q%%ssnZl@_UPD%3aVA(I4aKaUn@11G`5SAGV{vXsi-C(Kbi^qy zGS>B17*s)J!oBrm9W5L>*l(GYTTvtkI=dl9v4H|!#lW$g6)rp4tt82iB`!F0O*gm& ziMN9RzEF{AR?7*<87ksDRRbhkw#k+)nZneQ$WY>6d#uostRx;0TJvXu`WKkKBpjq4 z|Cf36Kn}H~58kv=$du07!yQvW>o%7`*AIeM?8zh-jRivK`1Hq-LzsD(*lwDi0quG8 zz-*8TjV9LFr8ft#V(^#8ge#&&%UDFj%I8vqRQb_QG%BJmP8$tlu(!Ks2Vi{{Emf%S zq8jwkzGc;__yaHZOj7eTbLShqPw}_bduqifEU+Wh+RovPE4U_{$ebLlm4fy7I!(^N zb_n+K2%Xl9v1E07J}Dy8Ych{eG=-vU$L6KvnL_Gx0>=Im%FaqG3y>ekMMPn`kdPI! zwMrpLAV&E|%!3@HXMHlil6=Z43Rh(ZLAqme-KccQkf)sDjHQqylK3c1vn_{oJnP&! z($))@&BvFEc`-{wPe=Dg%Ozo5qz%sat$@=Kc88o!SL6YcCiZ5+eo#;IEBjy&(cKb` zx%|DAU0;_}x1&Ed&kWHml`IZk&;^RPkZeOKZd4=x^2*90+qftulYHjoTTy5>EykCi?uHU= zb>CplvpA+)@R-FsY}||VYW{jqpVMVsBg#?hfn;RZ0}678FS+-Dm7`nKiL!g+eVZXg zddJ>%ngJL1P8UW`dXu7}Y{sA-^D~!Gi%v4n9~A}N7brF>VLDqmwm!c1uI1;yrSc#4 z(jb_AP9+K7AJ~1xPOcmob{hDxxH>uFAkY)o#cM^Y<9%XC#GMoREIw()I_`Qp>Gdr8 zP@HG=yzGsq#o~0HmCB4c=wX_DWL@DKN>9}9q`M~FPM_Q!h~$U{QRP= zbJ<;+!|D9A{T5d7UDtfZTyA~Sf^TmwrdcuD1t;k$ulJYr*~WJ*HHC!z{c^<(k}3Wb zn)WWr{0y=}ms71Ee+8k^B=z3PqOT|6h~ylfI){ zXrv=XwHKGN!eOK{gRUCM=AZw}5P(&u52$>FTyWLZl)=iXNTNyHCi@e4ds2A^3y#}S zYDe}v9AD(wqGx{0ug%4Leu*dcWLZw%l-aC;ub)^3zXGiT=rQLOBI!E0GBK3LVdEFn zXP=)DM0DFXWiG|cu~beC9*{k*k5XB9Voy883iCyYRk|v$;*T>ZtdSWg90BQ2X%ZME zcUD8S*b=nRGoG>_B#0@DLubYLvdp=jfRZ|rnIC7OkGGXqgIo(lH7>9;?LJ3^dSKtS zU@r3+B))FF(-pAX$)_XHyUagvmUtj(pKm-Tb2CF?@a7ZrUQPdQ1HSil~m$qCG zrXM;8U0dWm&(eJe?3?m14#TzG&PuV7yI%Ax?(`b5$_}X~l%HauSRD-nSDK4Iigl*Lb6=_S2(J+Lj;i>L%gm0$ZyN%7sL&UUeydZs%jQ$_U6uq?Ar zy`sYZJD=NRQdjuTZ_f!3ni_}Rr1ngtX=y5b0a8}D)r5?iIy-lOfLwJtEByr=^W|Uf zT{^?AhfQqlS+o6Y+?IpIKyS}RVq+$d1#=0zl@9`y9!2Wd4bmu1n)7)_U8;+0kq=Uu zGgf3o3BZBJtmo(F)2K`ec@Pyd%riiRas$G>uMNL)Ps`Pi;et`(|$}gh%Q{64d!h4C=yLN**39pe6t5bPz2edWG z!op~MQsY$JRWclW60wn+n-n#dSLSM2Nz6i(lXC&7==(ia2SvgZYKA2tEko1b(&I3}0|Gd!A2k*J^cwL-Nu5*?^u16BGD-|W zPthp(rj%v|dyaL&Z2gpkrX1kcQn@-gm?Uc5NoL_p)HzMM=h{89g$p`?Z#R9fs}`?I zTG3tKf33<*Jh-G8&Oz#|aK-*ZJM7SQ#SUBJ$3KS!7EDi=8TWO3q#Mg=0UpV96rT#8 zk@E5-M~%HP`%x;s20iQ<1gbPOCewJF65q8zLymTBjk#s7X?RS+ZzX2TtBBoSpefj2 zUTYT$<$;x*>7#7&4%1a6`tAAO%;@oo@v`wL$r-x==vL%qcN@IH0Gt92^emJWtC0XO z(qW25OWRkK?B+t^?3V5bbd9TqmR=~6#JAmK*4s3~CeKKm7V|Kh zg3@^cMUKcr3e!1FAu<}6Al6M&iYxOTxFqC_hzJM3sPKY$fj%*3#dPYNt33a!EtI#f1fd-204ZS)K_O`K<96~p0voIKc;uUkOb`J7`LYw7z_?!J=w& zIw`f3-#?{t+SpE2vB4{{5kcAG-LG+w*p`HTDNeTqD3NH03!QjQsBQ-ACr2yShsXS* zn~E+aH>KP1Ga8jSeJhzWHonnj=`^i(xgHZpbJLJXHkoBGUQ2Ir`aycWuTRW>w>7cJ z*ZJfSU0zG2h{a?f4O2+ub8Pwog5lwIc5h8P+Z=|p8dv4BUxA%*L{c&?DL`d+4a%i= z8>S}cc8Vk$l!oa&g8fb_Js&8hDdt;w%S};5)vS)k_JQj+;(PL%XqyMbuc! z6k&p}NJP=0^#to6ErSH-CG=ePphj-&YpKkIRx76c=bH-m-O2Mg4E2xwots^U>qLdW z*kL$sbrW%l9FG&ES9E^n4mqMlMz)4pplAv^jz0tU8lCBZ-0#<-+K8&I)%rdK0+@9Z z)a|@`9%)cTcu#wa!avwG+&V zg*@o3kP4iJYd`6uOWzTX>@a&og1>cjEmXHAaYZ#rjP1rB2APf22U4!x9$~O5IkssG zL|IqW;7ke{ZeMv97whqZCez#|IOaJEVq$l3xaozukcdkl*mj7 zBt<<^WJ=i)fglA@Bqfm)rA%dA1OW#TQXm2q5#U2gnf0{U*sNwhUohKV_F{JPE4{h> z7h~rfcR%iq04ZguGOM~Jvt$AY4}Ts%??=NI&6#IK<_fd{lYe<`y2r3v3O%`0J zYeC`h6w;X%IXeVX6dO1Ni^(jjQ_}H!X}Z{_U{?vn4h?kn!U_!f)U8-oS%T;Lbv0k7Zy8~MM_=Kek|<~D5iL*FlHF*oRCRpQv`MY;E^cxumek&{r_-h#@` zfuA@1=oD(PSjKi^fXREYsXy{T1TO@3IaJ()la~aXL928qRhDu&m0HD#_^R#n2VAd} zwbdlm1cyMn?8uiun&wKJW|z}3a5mAwflvg;?XD^mQp9SR@H*mQj9=n}d!Q$P099;- z?&lr1rjlI{K(Ulw)g_wq!i@3_xzIIhx;Tr{wRtET${Wx5F*WEN*3l={PNlR=X@cr9 zoh&VzESR6r)moDgbWVHWB;cbvZurleE@7F|B3zM5>a)us;X$dWYd0R{)0H&Uc?vl$ zxaA%u=bM-BlS+!4;nV$S=lRk8VSIC=xkb14a?zv5YYU&;Uif5v;gdTHpWI#e_1)fY3#%>m03Cs2OMSOEnsjNjBOkYCrYhLL& zKnFiAR1{+F#d(FHm6qGj!@W4;c2m7MH@P-zFBTLc{-j*oKQ>`s*F<+s8oJ+}x!Xz9 z{m7*0z9K)jN~<+rR#_j=T(0gvU2Rdj2Ka3J-n5e+ug(aKT*rK_?vHNx28mWnZou?M zN^NxGm-dZGGM%RRX?0`c#^z=aYzOV#AV}KJgW!34KM3~Qy&&kdzYBxlyKplIqLnT+ zI0%9RtHJkS5PS~}j&*}U5DYe>AbKBS3;6g1--1tv&}J7t?X{1B;0Qjw#6jWH3+xy^ zJ)<{*AbPdAxfw)fVF16JhVA1ZIEH4k5ZaBqG!5PV34PVwylU?R!4Ca~pSFWwn?Auj zXtg+_IEXGHns5vgHcx24I0#~Rc|F|R4x$*l*z5(-V;Z>^M2GNT>vwr@5JWM~68;3Z zk2F>OgY(s^$s#&1>@W(VA^ZvGH#|<CejC>Awzw*YN2l|H!_~gY6)Cy12=2g#&#BN52UU;64Vs8Wf5!2#OHqm`0mX5a;To zlORZ-`?ujI-$))^-^eK`&eaF@~QTzj73w_mqUZU80qNfwx4I7`}#PBx;-kl(R8=ENy zF!mwu1dR2Qb$6P!8oN>37Oh0|k%!mVZXCgO#AaijdY{?|mHM<^SihNx;8rqzfcyK( z8V(o5^TKuG9{_c{a@S1Z>QC+GLG&2Ds>=ejh-QTF7ywGOh#vyUK@eSp7B0}+R5$&2 z7V4`Kz3?7m$L~XRPm&-S!r}w^vk!lEf=H1)b4ASEe5+8R#*05u8$1~X3>=Xmap6^eUgP=mHq^P-1mH38y!dE5(hFrnZ zwa_PN+(vD814-jH+^tX2cz<2o>(7L@Tla9cYfXo*79$eGQu~PPyoO%4cpI^a_i~I( zAcG;(2&6o?JA_T~JKkUqlz7qD<8}~bT^<^~pU@e^LG;qX!X6gn$sPpJ+lXf3jmNm} zbr8Le0DktEiBZiB53?36CQ~>#?utiV^sd}h2oxbX4x(x3zs+6nS6+$gF_MLc}cG^ptix_KX8(*~JKMgyA0GM|pu z;u)L*-r)d%L~$M-L+kMknhQg+_r7akduECC<1urrX=o;P5jK)x{>qe;xkBDGi=OOi zO+iDOyOv1kQ%INOLc2BVW+{B_G49OC;HjF$LTfGVGQwhDN7}W`k_m$do;NZw&k^A= zOJK;TdeIYCwUCnG61S{%dKii*5sRZW`E(%Ab9!GDmOGzt~GglF9@Q%>s^I`y85tuP+djH7GI&k zh+i#c_gFokBpD-QH!*&;Mj={LFl&Qm{K{u=%oZU-5b4L!6FN5DYHV0UAcvdwXEBMK z2%AT)jzFPK{bm}$W@zRw&SR3Am<=_!3OSx|o_*0w94Q*SWoY2oF>T7Ik*PJ{X0I2I z4BI5gS$iUfM=rJzS#SH7CE6lRMz`M8Y>?>)=l%ahu4DWZ##(I zc72{+qlo+FK5qvWyUlo&FNfx=-$sqs)XaL}e^0taGiUZtP*Km1l`(9(Iu+D2ex_B`B#=_!N?5O9fo-46}gdf^;<97OA(r4P~K z+fRluc%?Sf45=kD{r!-IBhor6WTAf;hlctMHBjnjd8p5m8mhCSQTVOq0rWk48+zx^ zQw)uJ0{H7$Xs}d(c9%`_FA9!n-vZzipOAX$n5eoY?FT`WAmR=!`mgqfBuAS&az)G_ zafC~teqA4Ryz2(RJ474PSSvfDCs%fapkfOo&v7U1S9e_N}V@Dc*`9$K{E0O4;N2_3g$O`f*t*t|yXAINL$7+%9;6q#`1McY9V z(L|crmaxMdE~|ca4QgXT#sWMaHtUzLuVcjgtW`212W`nNkUbc1i&o$fXB=M7X&hOb z=W#}AJD?5EN6{7|RdaKk3i1RyK|GFp>cwBp1o+5cD$}mN6->!@@PaY{#MS&Q41&Lf z<_NNGBk4q8fW%?kogFxMWby1yo?`=#olr`4z!+EP2;=*q0o36p>sEM~j%vrI!rLJ5 zZf?73ObdU)Jnx2tS~L&7%et<}V%GGJuPm)>?B1N%l^vU8V?LE0YH${s754QOLjd5 z(=>b^F%#npW8PT3ATEuLH`+t3)9ui)X4&}1>IewiozTK~_Bq)&M2nfxMGrw1t)tc{ zA_-kIpi)9J!QtgFyz^!8EW_rK=(02Avea1KxF$NE9pad4UZc$jqprN(h3N7!{Az@1;J4c5W z2IhlijJFS3ugzTpNv?McJa`{AURM@}cUgNp=U-rKinx>NJT=3&L!X-NIA2J^KEaY# zwuwd}aP1h2q({biYCAAB*y%0*#<0>@!E&t4M#z};?DqiOP;=- z=}JUY5aEya4{78MDjFEEXp($E+!pSvK@N|7F9zqfuY`-P=ZXzr&XWfuCcvG2Y3^*~ z-%maQ=Xz>M%@SD5A>3CTn|olkcNhM^!u2)XVVj`MW8<6Z^ARdsy{mhy)}2K@f5DHD zyz;48*TL(4-1QAHccLJ;gYRm6jy*dM!Za?P_W+tFd~YL5Vre2@i~_8!fR#=y#S)1D z9D}m>4Ziu@NCXH0EfG#*uH;_OwyFOaxB0II6RW?Hy(U8#a2uctoDPj_7JE^g8M( zvuL#KbDR4v7c{T%o5mI_GX~f(i(#ZY09_DR1G*kM#yb&OO5J0#w+zpC%xtvnp*D_L zc~;w*{YLmSSh5#beD=00p>7+d+>;PBD|J6?RMvTflk||>#%rh;N5c#A(KB!}u}2i& zIG-NVXOHjJBh2Gn&w`?y6@cU2A@i97>$;z{(9+B^;CS%hxmhtg4{TVo=Z9qF1ds)*Y%_p-^?cg2lM9GVVC!i?@6(qOE z*R{e(vjEzoFK5jil8h~Dr`cbRC&(|eZO%D|3=B-$EtR!Yo?EFst7gEf(M%bN$*U3GneJsswB&qlMiXy>H~p zv5ZKXKx1f9L5w2gqRPe~x#Zui`PVAeLlh+yt--1^JFw zgAMuHNEbBAxW_jNzCI&mM^E=nP0S~L%EaFuj}PA+lsT(SWF5#-g_>&Ce)qHkDNdwm zc*Db=IDQLPiHr;gj@S6hjZ+boSYiIF|pTHEIiz5?GvAf1DO zB5q>h66;D?mLBMQ9bW2fT@9ADP29aozM{)@)yMZ@Z3Bs(SiB3r!tjYNJBa1JZ9p*% zZFI5^-Etd!OB|X;)Pzw4lc^^CWK$DRD#Ydz?ZE{0tWmw4&~tompQg6p-3=R6!!E*9 zegd9W*lTEe6~x3lY&Ghr_0YDZ*oDapW)UA-tMS}zyq!^y4%g83+1HzCP7@`%$l}wy z)=tB>T}u>1OQfZH_jEEbYa*W;hY(A(4>tn@8|40jBW<{}eDg}6^zoL(11O4YE+@=s z&35%bodbD8dA1MSVRkKmMlWcs3;=kp7RqJEV2@&wB3p56uZ6prdp3dWgQHAoO)1f%wF~_){u2#`NzlXZmOy4$ag&9@z{fwHS!AvU5lF)Zfq(> z2T#0J-MJ0mcsYHJPkE?m5cIch+EKe5Daw!!YJrAB+k zy8S|5{^*&7=z0cvw8!{9viinXTLYjixPd%)WK^-+3V^oAqumlPijZOro7q^)bF1q! zD12EGRB|{99&9rWJ=QnA2rZ{BzI`$8*_>ykJ`C*HI2{;3(1DT$W|Y1~nGde*$>!Dk zJ7rxMzEkWB9=k3{)`e-fKOEy3E`s6siG?W{j~ZE0F^ev!3TAXui+f<5rBFip@AmUiF&qg=^PyqPJ8s*bYekM zRLAM)RnUvQQhvku5!X1-u5+4wj9;-P(1Lhv`&kctiwOG%_KY(TcBl@Y?-SBR+l*}N zE6h7+6YW}PX@it<+`^yHGeS+^Axx%TZQT2bE&}819qqLj#ZFXIkT@b=4|#Dz1~<{~ z0Vk&vg3MkMT$zK~q??Vtpr}tIB*n0c7-ol=K}J_h8F!d{uxGVnd`m4M!;?mjk#*iR znA(K3(kJ#sL}xGdCfwD&mGJ4%Tn6PyiI*7Hgs=Gyi-<5bcZ?sj=Oo+|Zf11N-9{}r zBcEMXoDJZ*c*is%r9Q3;Ustn???=8io^h;Em_hIB(L5V&h%uuZjajtXd>7oSc3nRs zW_bCNb|I*(2ql=`PriWbf`}go2Take9v;<%TyV$qx)U$RJa{98kr1Uu`Rw1U@gKc z9A!dRP5~!+>dkdzwm6SI1r721yqpBCdtuk&Iz0P2E1Y(az-V0K`Y!h{;0URdlJk4P zwsuu#?7G8RAAD`c#S%S@!U7Y(_=E(VdBlWUX%iy4Ey|_QYUtTq#_C4liR)c2Bi}kj zZVf=K0yDQg%dfz3fVgWS2sCFMZEM{99Di|QA7&x@i(>p`cazbI-WS((n~X(`4K{b! zZ@g#33HbG?<3hf}{OZ8y{amxJ*(}8jXXCjDi?IUj>i3yC*_v>$wVsG{#35f%$y9lbgM!l?-Jir+`7C5zg$CmFs zx{uh%4d=QK46nW1eO|6K{LcKQUZ_poH~vL7u;N;uBW^=rhwi$77=|RI91+Zr%(Aul z+;*G5K3{I`8{Ko_Xq?p+O0`4gDE95hf_;uGz#}3A=&_^f#U8t2X%_CplAL=is_UFI z8B0}9tWPEw<2H`B5;g;yf$`e%Gjm~aT?rX;+QVIz$2uBe@DoKaq9b0%xe zXFao&y}Qch@tii_;z`M4+jG9N{MD5Y6{(%}%_~#oCuaW8BD8%6{IBDn2}fB92a*T0 zuItcZ1EB}QOusS?8ZX!!L+YpibyAR#W9&o-AYj_;h;kiI)m1fKwa`QD#Ri{;J}1M@ z9|3C}0dYaxmXgEog~m_qIfeoSK~HmH2;0!Mw8df65UA`r`Zmls`uG6@X~nxemQEkVdQ7|O*?^Dq==s$% zW68zzZ-=L@hIVwuk)1QjGvDynPfZxtx$$$7m=Vm zWDi^P+zNf8gVXv!*y!D>$DR*G@pSISp?l6LV#nm#uw0iF&&*qfc!HEsh=uL^GpwOt zHr?*f$g{CUr+Bdn1%Wonlb{$JdTbbTemo1k6PdmR9YMBh%D&m+_*oy+i~o zmMf-em%Vs;#*xeeo*i7K_hd)=6YW@$-L@toUXNVFX1}d%2W8}YN_lC;Ox$SKSCbeH zK>6#iaqyUJo{c{;?=>Lpf!-aZZ8grN%3R<9BPs4ZdT60CC;EM4E&sKnGBIvZcJ?32 zdUmAU9EOf90eeCMDNNEl=GLUQhxE_8IzV!4T+E~68`IwWj!8Vg+eP}P;L|!Q}E0@^EO4kw@v^6G+ ze8*8G%|=7Vn-@G2x3yc1@8QUs?D_p0Gk4d&=8hBAnKG&C(|K)lo{6G!4R2$vFZ)I? zM%Sk^_0mE8EmY2_9tF_xqZUqnO{!2o^3!`~haG&iwqzXonmfa-Zjzmfosd8saA;z} z^~YoL=^%&?aR!z#mb=tiin}HTOL;J4+@yS`68|D3f!UlINFM5`d9SFD1ip)3|l zsWd%A#GVavh-jDXQD!nEG+X$ELvLN3B{Y0s$KN(-2^p&Qm1->Wo%P7ZW056e*nw_e z`ckMS(l5Qp9q;@tXn77`x@q!JT4pqxJ++RW#w}V~HI>o^g6M3OiIN5aC=%2OVMoLI+N@WUp zz{t_Lw|7zJItg7iG>?2nl6T4kttnp~9-c`tMPECa^Msht-rty80JtB4^siaj@qq37nN zJ8q)W&<`*-dLvs&>N)JOr&bTKmmN)Ng1MP{wnEyA(8lQ;?LH0t^in+z{WX?9JBAa~ zPMb%{;MsGt?M*oY>Y=rZ3D_tWqj`oG%a+Z267uwfb&f&z>gC=wR~lF>W4r-%$(o&b zi?zReYCA0c^Ds|A1 z_Y?{UBVNw$zHF^2`@Z9jy3gPcG$* zi95zV4$WU!m&Z#F#XONl|4t4ho12K&ZS}y8!_*q^7>7PQYQVnmoIf>mYhzW{sF$Bv z_j;cZwti=5VGd-!cUh^yPt4Zf*pX#pVYe}+gIXS|LkAtuk4_|ri5|Ct?7U1KZW9>4 zwBvPjM))>!pt4jXOX!ptiz1wvd2vcJi46dmT|3 zZDMH4zWQUkdD~osRFs&yuNmMI&-7M zinsCI)4gndJ8tF(bOrd7$uG{m$Vh>*QZ!M^hK&51#ArF2Ft#&F8ANO6He%`34q^uk z%}*Tp;(fH)YY;Jcl8h zabSO9I^g*z*}C$D$+oNuu9Z%&{77=mu-CTW$GOCN4EO8}?aQ^6Gp8qd?kN9Vc*TWJ~1(c5yWS8KqQQ{8m;D)(W} zIK`rT$(VDO&)p=r0F~ahcB!@~C8Y-QJYJ8K8}+&;_Y|S)gO38llvO)LXzuQcoet(0 z*ztKc9lUm4#weVWg7tVM@^u*;PTFHzg_2OBpZrugZtigMgk?Dh?c-M1GK)pqM(u++ z9WCn*Gh(rkhAG~~l}%u;711U$eA6u?n+3Ba+{P-M;H4Q#lnPc;VD0ffa_v?x{S+Bq zSS-DZCQ8;ZQ&Mx^7R-*#3j%jBS=Pn8#uxMbBi-w|tH@8h+KtB9lmbB}=N9 z7Cv$9`u5htS_d`{uL;wM;~yRm{fsZ3u1}Nkw_V?<)l+>s^5Xk$L%wf&dYekW9L0Wu z3+C6Dr(-+YK1SJaLybf(<_L|Jf%C}cn;MeTfT*2EVi6ERXygW0c0EUWkkCdn2IDd|uWYko<1H`^t(Z&iuw0_AlF&Ahr0oXAuz~3scfSn4 zyJ3AQIf)m!Ws`X2&`QZN=&|OaURf!^od~~qRx)m4C1YkKb(ylDnPJpc42jF1p~ZbI z_R{aDl-f;dV~?Wo15Wt77B{NOV>f*f#WZ?)Rc*r6QWtv&?=;%XF@%o5iPKq*%m#A07_WE>oP6vRf|@%amNn>%Ci;v#g$<6PQsz;z z^_8w)5{PY92*$=`u-iPeG?uD;W3B=ZzXQtx#nfAQK}DSDp~>OOwM;6Hz=efmOn{hG z!j!J1aaea00Zz4msa1W;+8)hTu0-=j7wxz(?pn6(#!LeGM!syg7MzA_$E$~fIH}tx z2sl}fvN>SG*jAPSQBL-}x!4{Zvww+kXL8i}R!#yFN$%&9_J~zOW;;&K(6#P+ZpR1N z>$9U;*yoLl44P_NPKt4rJdDM{;o#CT>9~Y$amglIF7s^EoQSLHbQyD8Lq05kUa5S!y-Gm zhxOxodn4FgI>J<6jz1B)_{Qum(`BnMhB22R__8_$O*n$c4XgJJ&sOQjrjjkESog(^ zrYA$o_o0dZ)|nG+v@tqMH}RsvGxQr(7RcOwloFaG8fvHwBnWE#SW75tS~; z#3AWgmHOFPXe8Yp6=h&?G6LCDqpVlfd&DW|+Y}QU<)xlF4UGoJEnH}crKXbF?a+*P z)@}5WFbURF79uupY#U=at1uX7G&VcyE_SK&((v^d=6QT4i)B8CKfKC>Ugbd@=by!_ zgP>J<))jUI)7V^7FGW>iQ&q!`1aayt@2XTwitfh?92}iAcSD=0vKTYWGBNM($nhWa z-O*%fPOh*@Ls$t->0b=#v^0-Tr5@f!zP@kU(}NrV74gzp*w9J}0W~T8gHj z*4SyNvh|ePnyOLMxT7HFtTfto@*wn6!a0vI2SpV7+ILKThM%}>!!hrllQpe2&T!F| zm4MsJOJ`^oyz(G)OZM514@?yVKRX=*Ew|PM5ZB>q#!oE$xyeXDuYe3|2kx2-v(~A( z$~E7a)FJ!R*f;I$Vu?sUNrZOKc<)C_AXK(Y&xhzcZ^`S&qA{n|1OMxAML@Pm^A9zUox0ahwcX1=!6w{ z=mWtK3TIyG7q5<%&icFFwS;50IHL-!__Wj@mZNhOF!#F_MDl%1bQJ`f zv7V0!uWcDZ0{-QyqyQ{`VQC`dKZCKQ^4$V%(JJ3q2PJ#75LIhGO`1xl>_46y7}Rl zBp=}=!&C|I_MXKj?VHqdI(g13QhYV|ue7xZ-*M^i$p5}dOyxM-@oAt>HQ$Km?u~#~ zrs%7)WsF=;8;ij=#rvQnw2%6D&+~boJ)ga)I6~1r{HCMZya8F^`W$I)1204QP&QRP ztSF|P@|+SphZw$9Wa8&!Ar1Ab6%gtl`FfP0pWO#zFc|$9r<$-4zie`CAcI;wuPiIg z{haBZ%{QL;)+#3ArSaKe0Yy)6hN~~5=0KAM2VG0CrVGzGIi)pHRn=R3KVVOX$?4zN zbBIk22(4x?8xobNN(4B#6LDlk>;ycI{ zfgOD)M-Np!2rPfD=f;^{Gi5KYNE@T)Hw%@)*(>rgFj!hNJ7`ZxCq*iB?L1`0xGMPQpDagvmPk5pgh~v=D zu+|H168h zH0mVRdXXnO<&6#_@lpY*WQZD5?|9O>&4?Q{ET8@kUm)h+m|Qa{-sOa`)_1;9yWWl3 z^={Per{AdEh8u-m7uIEBt%9cIRuZV8AKp%x!PvFI&kD`y`p02oLLkd;%g(LZv)r$w z9YlVB`DEyZTy3S--a;#pmDa#bfwN<|tnV1pwG)C_cik7qPVO9|^oCgcT_>pp<_T&l zcmD*Y#sHxZ0k9ulh?mEsdeG$gZS1>PWOLuH$FZ|0A<&Lr?_nR+ zAO}{VM4dd%+BV09)~*8V>a*q&?Q0{=h@*OMeEhe6&VSQn@Gd!(E5o#^SH|h-I7?5* zb=4Vm>Z&tIre9)=)z#H|ckYO$-{IfwwL9Y9*6-e1U0b_%Z}pD&x7D@v`?puczpefr z8!)Ttr2Mzl)i1Ef)m50Z`v1SkzYjOgWLc#}eq&?3ePfhn^2Wvu4-Rg$Z{*2DRyQ_& z{-u4RDrV&Xzuf3_R!W%+9Kflo8^5$~Op@s|%}=Wv8#lm4n1;b=cp8FLNyl`Ol`;x~ z6m|U%qJP>e@;~*zMfd;h7rXt}-2dCRS6A2P?*E;8cfQ{Le}?=2_P5-A)hH_RTIMyh zO()Z$ti^{nxe$Y5C=ZLr^(1S<*R(pAP2s5=K27q|S#m1z_owNZJS^VHJbf?A_M7~p z7?s6D-26||RFt)tTY;X{Sc4+3YB7|sHKlkca(ONeyI3_9tom!-8$TnI-w@%}3%d&W69qmp7XCP=f{R zfmwohD3(6pBHJQUa3MZ!*n7IXA*#Ae^HcGw$Y)t59zLS3gh)qX=}!%iwWPaRUKXXS zXJw9WZqi$73iTut5A|tu=>JR9!iL@@n%oD`>2wOccIbb@n(#8cx9p4nC}^|3 z2G99GR&f89mUS~BGFdZ>Y`8a3{3>SoP>#}E4ma%=rlmYfi&-Teikml`CuTS1pQO30 z^eO)Qi+Cu0{>ATflwLfh6Y*ZAXHU~yM#U_L{akgPm$I5=^+wa}Y+Qu8glRP`Dwyli z@`gAo(xC-b@Xu__j~&%^X?e5Zv3S@phFGvog0{ll0I_iS;>yJfwe-drd^Dc`o$N?C z74=w($A`O5MKKbiG*7Fs9MXK+BFTpuii$kD#I}QRlAr1(ghK2cG+_2rEosTxJ-jp4 zsugH#h+JOO4*sWqY1PXI#blbvntz@{1IO~))6&<9S<9SfG* zN%KKA8_H_w=9@R=&E;i6-4F49ol;J-WFVJT-n=Q_yvcuDIcq>fLGc6do_HvBlX~2lBo|Be zG*{d9xA~E7i6#AGN9M!oIIYJ^v|Zvyaa(MNwPo(X-$L5=hY$G@{^c+FuE4IE+v060 zEn}8zz<;P-YJvynMM2vL^WSjxsO`4O^a8JJ1xSBG+`Q?(oX`mSqfsU64Q~&HIEB-k zWf{_}Wq*QZ;%0dr-FVY&`O)e3V>9TitN_th=t&I5a`3JaCo(I}1zh8#lmZD^wIN=9 zFJ_gj#6(U8lc^XLC196HTb#^lr^B?ah-Bh%i&7@TO2}j|224~YgIbmy7kHDrN}qbP z<<~}Z3}9hjh)!KREzV^bC2)lhSZ+dZH@%HpSrNxcnWsSQUHV9zmaGQJREkReZ3g^T zC6Y?i@}h2wsu026LC@=~l=)DW72?F%Cnd| z!;j0&vv&8w?5n*W`o~7hml4Khu_3b%@>;`5%N!2+1HRbiTe@L&aVl|}pW+;rpy9HE zQw-K6YHp97OsCmpJWT6q>1TIG=5ZTbm<{oP@W%#Btc|n#*!G*|@*G624Pot;zg6w4 zFyb#R%xl=91<;n^{jGjp{pH6_F3%5OPDl-Z{IO|s8@nU2ndVFQL%Rud7eGN1Wt}6U zfBB1h1XlnKoV^P?3vOx?>Z~TBnoXx!3aAmd&Lk60w}d>Cxi}xEnM4FfiiDdLVLBw= z2#YBYgfz>*ZUEGM_qSgIZxRgvZ#QTFe(tlBm8=mRl1617WHdu-i0F@cKkUiF)1+cAQ_A$@;*fdDy}Sff2o*g#Y zdMa0oAZt$^@Rsba(^`-Cfx*zMu!$WwOR|}C?}%Eddq)&jL%AdKz(uccI;+M@*x~XV z3x|_>L{nU*<$m{YZZEC2K#P13o!<`9o%y1wFazLhnxVu}-oPbol5|1rd1wKHcQ{(M zvQ(E%Vu?}Ue3(PABuvtUY(yb#e^G8TXFHrnR||?tOkC0}#E(Dfb&BtB9QOomV)4;g z8usH!(A;8Pj#e5Ct3Ox8)bwDYH(oa@>0JIgdv!DaLg&Folv%!F8gC>T&IA9sBialhV@R zs45mAR&jyar+ffDJ(Dnq?nNr2*W78FXj2uLV~Vc%b=dk@4<;R3YRgq{f2ZnwvKPBaHmbB*cEgF3v`)FFN+%gi7^*e&vokMxE{w1`M#Ct zUIh_x1xAK`%RkWb4kmv;rZ9tx00YL=b-0z|$HgK0J?-yqCo=cao_ZNI%x&mep2D_ABHTJoucu+= zZfJn?v2h07qddlVZw`W}*Ek6$aV-}&aY`9+rftiSRGnWCZ@PtWto*q6tp{^v6oWr7AhwC6u*?oeE1M zG~gvW^Ro>$Z6UkAd3paB956WxB%}+j+glEBT(DazKOIDb#_*?k|MxlY2%YSn8?e?d zZ|kdu#|Zfgc1=)%x9Ln+b}&bEWMFFtf<&FN)UPbZ=Ej4-#2j73y<1kcZ9Cc%FLu0c z2O0AkkF>9O*Fo@l{B?!w*h6vws>4jcanJ}6Ds^RSr$*MfK`7)x`ybnMXd3#th3)EC zc8PHSG_DZJMf6;v#yRk~QoSZUuWW~M%wiZemNRE>@aODu?B%I3`B|-yVauVMQ-JMw zl^UItzH3%aO1);U=7q`xMI|A6+9jJyhkA=8?9NqEwM+ObzoID-+!RzI$i=tN-60=l`eS;40rg^kE~jCAHMQ4U0*$7x3m$a63#xogWoZF68@Kr@Tb? zIoRAh4&sANV2t;aH~_*ZVKs6kPWQ%<&KPh6=yNj;sx-X7Z^*qMZG~EuJ5*7Igvwp$ zFWP}u;|zK&M{<+glcUR{J(K#4!nyXaZ}@bm@*G{pQ0B82n8ZiN0kzpB0rp*&BIu~N z@sS!0=p_m^afGuN{8M3E=l-KB+81^G{gnHE=kD6v{l9bPtN-sGcmFjUTy_1k^hCkS zbw0l$&C}Yr+jdq4MJYRu*Y0^zO~T7sR;JB)Q4XsP{N9Mm%`F5^}y#Qx@F3018f} zV~Y;IB9nj2{r|!ez}5Hv?w#9n@xQn4-}@T>`^Vq^x1W3a7YYGZT%HLN+oe}k3>eD? zR$Lr}sGvJJ#7h+;@l0mm4H!J@p=;5UUIj1m4beC91}P;>k5hQ5?}WM`&oW8|QcvOq zz9P#X)a+Ey2=%l?%hE0zZ5;*o}ZE;Dg>=e&LM0H_Ekd^$2vZIL=GqYABO3f7$$XcYm$`jhQ)dQ@QuE@Z*DyL<^ybM zM}aWKDr(=BPIY$r@rRXRdiJQ_5GbhL(czc2&;NBHn8v|IMOyKjj`K}jUN-vTz|xI> zCcAMCl6o+1d|^@emHDu;A_Bx8X_9fkMB7}4r(19n+M-NKnOzcavn!+>sb!p-@tYHT zNiLe-iM3@X0#SMB!O?>=oVPI8A#CA=9$7)3o7O4-rn3SZXKNvoGD~F%o|Cl%5UedsjH^!Boua-cIAe3?)FPY2%&`E}|~e$?dC;w_h%Le@hO6f94wP&6+@<2@ck;4YTJAu2$1w?h8q&*2s1iSW`jf>isr* z_R7yvs~X0+y*973Id{utN_cmiue%B)Oi7@2{J*9_+>!qqE z|M#{3uHC+U|6YUr_pATMAASGde(vp`*Z$m`RZ?=3e9}DA}OVK z`5=aJl+3dFsLT$_B(FwAIkDdZ!`-Y-Gki_Ggd=}@ZQqveOsO57mBkcPQ$k+U7-5LX zq1;Wzuif-4&Lrqh9<{~I!8px^rOa5m)Yq$o0(Gd{9N?F5HQ16A) z7^LMOlQfMYSJNnR3~&8$LqIl(N0?B^ZxQE1|M^GG3I-RWDkeoa9j62PVu**(4;)Z2 z66a|?EY2xkg^_S?iXZuwi4Ff|ZR#Pa*-14h(-WQbXo=^7AL#3ck47hp7e*B4IVl|n zMP4UqE=$T6)StU4eQHZeH^dIjnaA{IFF7!PT8OqjfB44d-}Vk2LK>4y1&iq;cYa)O zz7Y6b&Zr4ID{@rx;TxzEq|bx5?`S58O3zZI`DrE((@f=Jpo6HMCG}XnQ4Hm-tP^UD zDDqiRrJV6$n3i%-r)N^P&+D?tDtkhpvf7(XP9Q^wJx>5aT4|OQ=W?iSm+rS}`gxY0 zm&vqi9@38%o}euqKEu$yb`vzW=K&ah>U26&!UZ2UTA?#*@=?bU==_}48o8P`UZDEo@Nz1DQ1@dFBp=yIuSY60+x!4uX$Vln0PIlK6-rGo zz8sbWZKxYAk)X8U;b08836czQ)Le?Qv`SAhiI-wBt7=rAkCLGjX>O^8sXM8*Vve4v zxtU9fG2W6y9%J%WA7tEq74KY6ln3XU~BnO=`@Cp}L+A*QMkLnKe^A3qOGxDr{A1orT2M z-80a@0uJj8W@RZMz#nq90oqdgv1uDxWNF$#O!XY9GI=BHF5CXJ{cX^{o6T@DQTju7 z21TC3LYCd!le8|sHRe8a-}u;OVEU}hn(up1cWalQ4+?qyYHRj9>}_v=duLK|L}vpYlPZV`;|wU z3@@;l1i^Qq3bwoxYW2QV>JbCC0feTLG42@` zpw~6y^;$-{9<;8J%}*f!V}#S%rKv;EI^`VD;lwkl`97y>{5$?w)!j^SWEk{8XbsIl zs~E@`VIU`GdqB^)h^yFgnOba4u5_GF!YZrRE z(b$TGgmSoK6vA0<>*{&N3Y6hOw@jXguCA99W1u1%Y`8cuo`Dt358#rUda8Qv2WF@P z2+xeI3T4*t??aBPv}!*^Sg43gVH;~AJo(9;BEM?t{$VNh$a+GRxQ@)Vc6*9?h6O#QE$OMW9udME-v2-B{x`tEb%+38X+Q)i zv0f;Fs|df#_?3$A`^t9wbKU>*qI@UI-#Pwob-f|}clGw#*Zcp6-G7FI>#n_S`DJo| zP%@8(Bp_A-5N`MPW%>YN=_~#*_y1`xiuVrU&Sd!I$GE!w=iS@4=jwm1-n;)b{`YtJ zC$9S!Od)l@c$yAmUdh%KEngBM5w|<5ZSf?@XGwV}Zm+K1S@_bpuBRI-E9d9uodk#J z6y@nkMnhFAt=3`uV)sA9lYnH`G#Yh-#cp$7L})9g7DhR8Pl|x^pVZxk(L* z>1B!aFpKkCmZB(y%ai?aRG*|y>(m6Tkt0uAK-DkxCBx~qVIA=645Ok4 z#bg3e!qfyqGqF4Dg$C=0EvgSDrn3^ThxUZB;czI11N_iSak_ezsV`O6Tx`ZY%u19UV_V)gvG-N;K&K}j5~6k0^C5% zWSTD1aa7}UN>vs|^`)4~av<{>J6yWE`oAsXfKZ!5ZFe!Nt2)Vt=xH`iO7K;t{?cV} zB6B%P2jG-r_uV32vB6kxoI2#!#q5SyDoXrR-dMKJImvM^&eGuwdMkwu5kg+ba*%?< z7j2^~Cn=T;RZyh?Fs*#RIzWEl2KwXpa0QhEplI!oo{n&@-@!^J#V{SEgM{2!TFQ$f zo8dN`%*cx_OD8FeTomZVt%UXOIQEqv1k3<-cXNEFZ{7QV`hIvq%ju&iU3Ll_qjMqLAuz@0HO zT}pBxFB0(a0X#P?i?dX{0&S>#UV4H3VI9I{z51>!)3XGcjb~31 zh|?`{ylO)j0U*3ACWwb{AUq;~ck&m7pXD&Ei!x2J7P+v1<0!iQCwX4f>Lv)8B_~Cx zziBk%-WQ}(vH}M&OwNEEVnIRZOcZ5$iba9uPx%TAtIrQR^S4dy8bGc(FYH{=fKpD9 zG#8beCM7}z>;+7oAVy-)eU|3$aKld09N_|Fj%9t!Cg1=j)ONR#CxiVRtAS-Hi;+HO z5JxnPZaiZj+WAT%5>{J=ovCZ35ww{Hbmg7{!0S+R5xA11ruJ&>bNi^K-8Qh4q8ODH zX-UP3A z14l$HuB6sxO`2XCBnxRfGC8QrB2Ncxz4s?chJb%w!dp2q4zpbCIrz-h8feT00iCZa zb+6RbNXXszTHI^(UF6n$6t+t^F}{7B1bK_nL#RO^~`TCLk1A+~`T zf*~Wbbj=TmgBcMF1)YtehPoj*oS~SQyT;lW0Z8KHk~l9!EU$~1NPsJw%6bO(=J7?Wyz)W%T$(3HY@y9F$ejO`LZOf@7IfxIEWpS4Mv zEk+~Y%^-zQmbK|G!8vN<=rH)E6Jx8mxns>10m}{NqDM*c2d(CWJx-y zRC`?3$t87R?y?O${MT{Pl_eJs z_%LYW)q?c?PmsH;$C6km7v@+fR5wA30q#9g1WfZpgze!H!ih-$bH!a?QC0ymXBWs#Wa5O zf~%1=7YYt6tl&oAjHRR#9TgC)L=;-%qYa{yOUW{|g^03Km?cb#WPwr+(kX;n`wN?2 zRATf+KA*pdQ>U>`tg%Q%!mKVxHXu2Z`lKu`VL_7=BFU6AN61QZBxaSm>?kf2day?v zSRtt)>cs42Gll`z}*neOKQG4dJQ15s0GZ; zfe|9}RD|>N+bVe;rOuNjEJ!0qx;>QI5IXV~V{glF84!&*Q6*|Y`n?-_`-i!biWXDYu^kluBywsaR2P9f@h(HyF@^6qhS+BHKEjl4V$N9gAMY*yG&EY$yz&S zQH-m1@7kS1kWq|vCLvQ6(uI+Cx2740l^c3$iJlklB=5pdB$dL3SDl!JVjWN^eML=5 zsyc%MfOMTQEt>DSDBCOt#2CrBrh{Sq?3RR>0N-|6I%XNQ%f$1y}gIqe=XoIqo;SfHTAUQO_ z6zMc*Cq4y!+qAb;Iz$u8H#dV{e~ob#dsN;aD;159qtOP}bTSIA}hEyBz_- zfzol4JjeW0)e%Q|CaVe$N?uH}bdc7do}pBXtoTpz%O-BDS*1g_XMqX_Mj|oA;-HFB zF-<47ru8Z@hD8{~uoxO-0SI+KOrUzdBle0KUNN=^#Pufy2``v57P|uE0tgQX+U`hnMOup!6aysL(M=WZZb03g zR_i`kNz)1i4bTma#Box>eq0(*H`4^IAqaUSlV-^|;!`*?WcSsDQktMPACkJ+6@&E> z%yUkZHtn>^&N3bDxDgzP-oXtK1_!-^wm9w`KHfh%6vx4f7s1|PFFp|aFKmPH z{+0;#USoedy}fQ*$P}4nc>(%Bg!UA%#n4g-np;9TL1SH^OMOmTgaSnA-L=Es;nTP+ z_V)K~_4c-2^!B#n-FWY?Eq3D<(c@t6FbI23dxx)$7JRFBxECLgVLK4df)|Iq=;&$i zLOeTq@ofJfCdx<_t_<|$rL3k!PPrvUXlEeFiCHKV#>-+_roiUnB1d8dxLnuZpsmi*6J)S(Vy7UZXP0Iu%mGm?JGVf~eC8GqK7F4y*?0F2Odex>OjKWWI3%TLVhj679M~g;mXYk6PgV z%?$3C(JyJP4o{tg!IpHnuT-q-8Nq_HfTkfHj^|K^X;cGCWJspf@rXYg$xQN{iPn z0lM=}tM#BGL@)px53ARh6h;l0$XcL(j0t5HUC3)qMVeb2jEjQweW=+}W?Y7)E9u=TaEOO?Dm3kkQlV31S(={*n}Gb}-E`|ADdcD6MEx zRkB1elaz(+d9YN-iWmi0$|bCvcT%(3<}ht5B&0t#aMx;U~V(RwjK{Dp#GH6lo^QX$H8LGHXXHb&LF_QFW+JU_9OV zpOytm!zdzF<6@Q#0h60~D9+s?zAc?deu7e4b(z=6g)!fu_)HV%h+`>|tSUf>hpm;c znW!$XEx}7wA%95%HL`_MO;)u*@I1-Z^bAG|CQEBqZfv4A#|7tHpM(+pD+lif1YK`(Oqn#OCk;ZbwUj#?X>uT%c*& zzJ+258W=CW%jstuXZM&MN7LA#oOXu#uCUsz?N4ym2|p zj4=4;KZ|ZsCz@KKYXIiBQ_$FI{Ynk4`uD4NS|~E~TmJp3)$?EK->(KI{)Ts3zlvMe z{1ewV`3JuKWjn+LL+UJKV}_PQieAA~_(c3F`ZZ9=YDN2%cj}9}-xhrxt){|*`U?)^ z=i|r0;qf+&)Hj{Ht%|(=%MwuWYGZ|}-UI#WKqkiXQzYh2<7Lxf6p8S)xYJqX*D+mR zdM3$eNBlgpJmoz<0PTyP9_sGv%dTpXvvdMrvXgI4y8`^3vtD<`uwgRrVkUMuPAHUkR-k!jwR1X}bk^2a%;<<}+U#_1ZSEIZsJX@~qx7Plm9pX$Plj-!!2F<0 zedU7LoB$3PqY{t{rDgs5@8~~jp;bB=;vzLQl_x<}$;nA}DGqwOT`<>7iz>+)57KIl zJ<&l<$|iKv>hnJJJECt6B&|Tvq4brgtJcIO z&8M^aGh}Ej|GkKV?(QEU|J}ZO@6O$M`S0%6`Y*qe{C5ltRh#@>NJZBu{w0jhOul^` zhLPsNzEX#v99=pN4wpNkSGSajp|Y_vQ8Wbl?X6v;26P3WOIZ=e4n~u`gP!(3Dka!u zT6rPLSzf0T2ta_~E}0L2Q5S(KOJUO4cp*T;Vf8M}vR{@u zos~{!1;13(>&n4S@99&(hR9I%fLG2ae6ZE(_xmSFHEvDw=>%PboP&bLh~l&$4LgNy z@=$l7^R{Y>ld?FkAeBDuM3fb?;V6SuA7dtmilp=BvvdF!xTLIc%(qp`tFC-l1bLOV z&9}#xm0cxaa3*zgv(-{{4yZgPl)wcL=}I_;a%s6U#7|3hUrRUtEFQ}&E861QZ_$7L z+i(ALb9s5QH7yHp3-46*u$a{y1ehgzQq8Zn#RqW?ve1V3epP&go^ZFqq8^(9B$cR> zcVIEo<$3!@XRmd8eeWyj+zbj8js%ox21M2QqTAc&l=Xdg&`6hfQ1SA! z+!TjMb10LctV^BWFeu2`7WdABs>0>)T-7NjBf!rjaQ_(|EO&m}N(XP>^+nU5F}Xqg z96i~&H7Zk?53@@lC)06KrPVJ>e;&MjcT16#&l&qy>pCH(SnlJ6uS6eFL!W}|pj?O; z6xnQ&cf_%_7O9F_ZP8z)b}bdIkl_oJ@@~7RJ7lvhGFEFrTymOY^v=Hwt%w84gHNioU4{ znif0u9irfzl=$1ERjC0=qB%&sk=oSN1(O>yN+WSuQH9!cd+%vgUqWR6ph7D2gXzmE z%<}L9cy2;zX}5mMM=JX8@CFw6y78zb#D@ulBb~|)obt!k4=cLAM~ap_1H&wub)gix z8BG=0h7eMa1E^#L5n$MV(YL14$BI7WIZ(CGB^->i$hwpz8djChNQ#k~SpP>EZ#CPa z(MM%rh?c%RZIwWP3~~88#R-hj?asz1332-DNLv8lJu|Jm#qfK`O@^ohPJEba>zA_KmfqP7#+=HY-n`d`FrL9m6Q6P z0xx}YGy7sm;izTe$f*2ZAMcFzbVcTiiY3vDRp;8dEGU-LpPP%J!`5|CejQXFtiERB z;L~O#N zTnTmo5B5Ldj1I=dxkyAGF(!>pH4*!SORwCWPvjU(sj~jnb3t-8E{b>Lg~eeqQWpoa zqW}BEK1BeGozG*L+8!6vG?#f6N=aW$+|6fSFoIpG*wz_beV+h!hf)~H7qT^cX}oLZ zGLhvZNf(0fuVR-Ph+&$XmdS*xJ1GW}9s`d_pFWSxbmpSFt`?aJBlNbX^bH8VW;W>M z52+u>c}M%VeEwW?UAt@VbVNBMrk5*#f3hMOf*Wm3!6)E}WD1zl1&2vPIW>3%5+A8| zK6=+$VI7={RaCEk{hh{LK>;JDcRm@JeagOgRr{2s&;J#q0{RRFwHhaJq{}jLa32Jl zLp`Y9D3SQJ0{e^hWd|5HWV>{cQcUXw6SI)a-$fhk0)JK zH9t$Tbf|nBe;d!B>LFeWyQ*xWi*r*@FwUkR7TjsCKDZ}NE^BE6Q37e^{x*|JgO?6F zSIot)HwFOXRuWUxVIQhmI^$OhBSF0xB&QLg+zQsge=Gxu^zX zIWdxQ27<6uB~)9f3aO|lNWr^SV4QK$3P34Q0N8JET8FKM&_hK`P)V$XV8XphWC#Ci zmXA?jszE`R3?WOw3k(`lOBh43ZM#Dh|4F5RISu~&=Rb=BVk&J#^}K+r>T&8e)ics$ zH;c=rtBPf2YVZ^tb=`Nk^-7H!yh0Cd;g77?)$4dDG%;$P)Y1psQ@P=c`Egme5Tm+# z_(6SG3@Z^1Lr!G0>>>w0aY&p9k+1MTX;Q^e{w{~!H36^G6AYHmk~D7-|4df~wJY=c z(042ZVk%|nSRvXP8??|~A#gQ7t7)=55=1_um64ZuNR{J>uvF-Erzvt^M>51 z;VJfX@z?c_AJ#v%-pG8&J$&;G9rZ2I|EAOFeAB1QXlC{u5ukFI9(!vE9{40n@^{$R2Bs>oegIk^E89K-8%bODjZ(x4vz_>c z+RqLdBI!`vJy#1~&}oY@MdqiK&JG2%VwNSen@azROz{Xbv}7K2wo24R(P_0vQ3ey}p8r?8GPsSA*w z`foBhs+G$64TgmD+t70f-o_w8CzV9TUtRltyVXyW(G9|zP+o@^9B2)cT?M};C73hY zB9mzILH|A&4wenwy%`i)QTE$7Ik>#2P1^>K#L9#$QYJoHDD*(~<_zlkrer5zZH zQOof;)Mej;DP$nkS^ZS#&8AM#sr#-dwh_<2frVL+yA4KcMkbcI9!CSY3T zn9=!C1Yit8^43yErOg3gtsk~2WD~;NbqRZb1_CZfA67%jaR5A`OVN`Z&5N{J2eL*T zhk{YK5}5=_1ODFCJH`J(A@~Zz;Eg7O61UZ5`cCQu*l60U3lWXeTtZyWlVqCECuqD= zl$eDUFE3<~REb^NqW|r;|KtDszy9O@`QQKhfBrAue)}K)^}qd(|NH;=kN^7r{`dd< zU-~VT->DM)A1cVtc>2gR{b5D@;=Iv>CrPk2Yl5_zW*tZvVAfA|#1t&WGZLlf1`#u$ za-OF7oQ+J_QZH8TfLVbspG1d|0x%0=^0Jk%X1@L0OJm6la)A$O<~ zbAb2j=JICi(_33V-qij=eVRaDT~K|g6ubcUp=PFAC|OR~qyTJ*+)@%eVomyEG?3E^ zCk03~Y6B|NfUv8HGBWo+2%mctANx9v*T*F)le}lMYH4qgfK-R(F3YOcc{AZYTQ=YR z4+$h>Om0mSCcMS7c+`iU^jRj^IY=(%U4=C)rWw1Nmh!3&TP@1p&gN&liTVtzcKh03fB^fM;>t&B# zULNND!USr_7T2;&GGm=g^FfI^C&&V2C;Q-z=`?tuipQr=@fs1U(hkvjRpzgvRH?7z zMGH4vQFnzYl{iDHh0YwSKu|~(m8wOgY(#mz(9LRSv~sOx@&=88nIWHt%EcpS=V|@i zcj^cCe_8S>3NPy*sET27p1&4NN)|sa_~+$SpFPpck2o!%bxSbiJCk^0|_m#Q$!_1jYDHD$h6%09pZnz*s9LtZS}kOf8V)%cXi(Xdwuopov;4izsEmC zfyG0S)WyltjbMB0{mJt<2!bFSUA#CA@&_xys|TmStM9|n?I0YThxFTa5a56CZ2iFs z{*M3OT6rD3SQ)L;d*R~;E2H)AgV(`J{EePJxi9hmdn=>-4)og{t=IR1SM_O---W&- ziSOus?y7m*Jq@9cb=@ZbSU{)0JiogVy!yU7JKwn*oCZPgyb6QoG5og+|Bp_Cp!<9f z2KcWR1?RmeIKA^MJl~Ci^B@X>-EMdeF9tiX<{*fJ;Cb8)&i{Yz-mW`sANm^nK)t|u zX-h7TWZB4IC$i%-fijGK@I8bdz)tbL9QwEg{Oo>^<=;(0E*k`geoES;Bq_Sxc} ziu~O5pVefwqPZb5BYDjj>P({Wx^qT5hij5@PHBZX#5lZG8Sux<>PO!*`OaHSS;Ge*82cKPCK4 zxf=Ik$m4r+qB6%f#6(lA@VU+s&k6B&EApnFKc!uc&t~Lsf;ql}QgXE+suSf*Le3-# zbBOoTJkf-M)=jFMRpc?3HYGpR+D-BCM3GA{ugcAC)OV+zxmz0cL8)i2&C^)mES znUo@>NSoL>TB@!fOSC1TrP46l$(wcLX-~#I4QXD{Xfd)&+SACn#hZ0=uS`l*4-2A= zr>-PRxmQ2dOI49pqhahcrOuUa)=xdPqd~l<#8UR|T=H(c= zZq`_B=`M>MO`OAL>WOtWC%2hcGF~;LW|7eg`3&i^wNm#(PugqJMpHzd8j33(ll(qw zjaoF;IG07U#%rZ*;+_VBL8o>+zItPvCS#pV_&c6AUe)Gq(MHA@qvCGkl`(48m{@n6 z(%ly4%3qT)PnIx`M6-+JW!7ze63^f5Rnr+y#^i%(qy~57=_$G%lo9=`t!~EiNsRe5 z#+MD=|0|vQjpNT&D#bPRkF8SXY_GdD;s1HMRl1HQv6s)y+tHHJtxD@?qC56>BTMAe zi=8C$p5-hWEy!$e4}^OlMYeRC2h26@lfwuze6*yu&3NvKpXsli-g*8`Pf4Z>UptGt zt$KT?HNJz~X24^elByifvr}$3!DrT#@c6wxOXs+^#em36`P!GH3pkVJR40h&;R+xQ%TNxa&blE9#(|8 z`T3H(ICpn$DO3Kbi_4c}KW~f*>jLZi-IZ4v#vhxS=d~&~kFpMOPfIHJv({eDqR|J{ zXZ(4+$M{Nh(W%kADi@aQFxj>uwUynZZYdhMw-Y8H(KWLn&V zj=PPMKP*@VQY(_0^m8cZzKnl+SpBYk; zrkJOnq{`)HsZ9Drb$UZ}I-rWQdvbUk*VDmG73USLt?w z*Hvo<^NM2U9-?_;WZr+Qm%L^wW8C9V;XYMu)NF4P>|aaNjvI=3?P>Sso-PK|ZGV!> z2K)@_=(sj9Kl^_F@)%+_CpE9JCg+|aUYmPfw=K`Jo<+voUS#`+$RrD2@|@9+&62$A z(ZSO&#yyat8@pe7GV@0~6TZexgaEOj+T0A>;Oh1xy5{%R#teR3T*V(}*ZQnh^s@2v z5#3nlJh>u_yERXHqJbkrn#`ce8yZ9ltkXdmsim=0`*L8ZP~Y796}F7QdP>&`=FOz* zB~hn!S9_w(#A3f{Qq^uV*?FVY{YE`SqX+%LV_Z@@dOiH!Wn{Z~qZ*=Hhjn7Zy~I~> zV-;+SrP0;MrKYBmj^8I^SM9K%2KzteaShyMgLM)9@9=+hbLOnSzZyC6>M2^#wA7SX z-1FbpA6Rlr!k#PDo2rQTo{aIc#!yUVqW6Xlb6%g=!@;RNgipbGnPMKu(!(U}ws+){ z?{t54m_y!2|Md)v@py){84c+sx*1fwcVp`dWsJPfQo-ZHIIW|c{3fwP6TP?MC+f|k z-aDd*^l?9s><2}r`PDOL>Z;Lg>S?B z+AzOamhRz4iQN5F$~M0F=n3mE8x!V@T&%Q*Rm3q;z3Sl)YJ(dun0ZI0lh@^1<`ssT)q%9%@p&&TpcL;$&9^&L!VvAN1?UcuF_T ze_W@*nm?>r4Y=X8bGPb^uStp0&zB839uMj6lAK$+5#K+#tZ}6GPSHKbp61GhC+D*k|9#Cj+|Q^u9{s66}SkCY7%F_gTbizDW0oA=SHc4;uq;g(E}nskcep z=K65IRZd2?Ez!qU^0|5HitluPdGOUsCb#}Z7gfaB4#J+?|K_IIew1#dbdulMdxey$r$mv*hCxF66VNG z;Fo0W1z&u-yHTSd*6QYmJ%t8u`Egk@8w*de~X-utySC4kaGnbDZ+| zaE`r=y}*0u#J6GJ;s5ZxTioNsQr_FuV3Y0Sg+g8w@&=CGx)7rvE^|pVYle#F;b|Dp zk>}tZ+^=)%@>t@~y9w4LUbl4j=3H{le*Jm(X59k0mI-@VTPoAo=4m0HO{I=yw#_=@&t(DJ&aq)iBS5Ak08tlcUq4wl^5VJJ~ zzAx+*Y*+eWJ=Wf|;JG>7M{UHf@tmwRc|fPdYM`RA{EmO*__|fO)q{`0;N#0`Fc=I+ zhF+8Z7$??OD)(mDz9fy6>))QG@}1iq&o6%tHhkK^H{Ny;Vo82hWXucaZB>@e4{@j1 zAfs#(VgYlE7izXW{~24DF%7JyDAVL``uhYLyZ*2E!Bac!=W`;t=!U;H+zTD@UcR>Z zD4+5Do4?`{rEcJdPoKXZPMkCC)ELsAmtvp)$7dMk<&f*h=j8AFyQI&szAU z)uJIY|FKZ&erg>15w_#nJq^{oq>A^<`C4)V-Yc{wuhdgyJmP7(DBl+^iNq|LVvPH* zxJeWq+ZW&g{V1tlCeh5hnDE>rJ|HI-iCX?n)^((U<& zSI!kM&%Y1%-i{v0^w;{u*Rn*f)D^nBY?Afs{W@9SX=5K;d2dgjL58up#rd}{E>RR2 zWAtU1Kep}vxi1VYlK){pDtdlRkN3g3%@^kqrBxVjYX*Pa(_nz#Tcg8wYgdK%&=`5{ zIyyX4thovOt|-JaWA-eWq6#rV5iKy^7lva?=gKT)o1Q3TA`|S)r+fNcbnCOPkJ|Qe z?PpkLY6gF@2d)#|`#Ac%cuKxLjtcedYxVJdvD~oVs*RO(&+)B-?VYto^JhmnKNn@p zbTKN_cJVp>b-&w)FR+*cw|L1XHz7`B`(7g+9IA7-X{bg_k?q*`)uX|nOLnRfe8P+# z6y0YV#%t~$-rUphY3{a)UP^Ud7H|4;s$hpX?`6y&NpSyuLNW6HIEv(&!A&t-LA2h6tEX+fz>%L<0(0Q2VREwfcm_-WuJ&=k9DVRE)rlk`#vsHFViLOHJ406 ze$Lk$H54yi>^F%yHxapH;BN8EM{G;yCGD+aJZrk(yf#sJ`Wo;crIMG2_ep28i7nz^ zU}zIP@Co^c0o`9}NAN|wM;pw;Z5JVSWjkae-YYS$C-{N7&rhxVeUzy$q*CjP|8Wl> zzRJ^0qiU1MIw%rL3;yg`r`~~==;y6c^>!aSGeK;nTH~Bsd)jR`v&JBf;PEMAMwW{A z9)n@K;>FG?Qx}AIWzTuqsB{rx3;ooN4Sdlhd=al#tKHAhtXpj2vH`A>&bq}qE?;ax zigBFXxA*gviWnO$-`>v~RX^;NQF=Mmx_-I+omjuremXWyrhR8gJym4g%a_E%-ydFA1HZS{c~$YA+>`zJ zwor8Ofc!poZpmx^dPfyvNWtn5&lrhkjQL*j`g6bqQpN<>mRZDzlGBvbnb@omB`EBH zuGm>$Br$AFgnL9>M5^o}wr5)GSv+=}#lC4^BvJbMOKhoLq?-?NoM%oKBgR6JGfk{F?Yc`;uFDd(Ki`)ZhuA0G+_1mx z=43m@x+XWkI`+kr?L2U{>8x$x@1{lxmQUj|?QQJ6rFa?7W47I%E~xXKYKxrOVa#c| zZV?~rZg`AsDpK>+8uj)Y!88yjIM|5tiEpsZUfzp@ADh>qjf^F9WCts61$n}J=7Yq&ipZE_P34L3c5huCYSY(b zy-GiZ+6RncPiBT3vI^tzz<%3+VI*(Pt;L_z9G9p=tSWw;Ton(wZc(`#JY$=#+v^I? zc#db;zB)50z0prxn=+oFKDXm|@t>Lw`>JlSlbpR2yWQ1Z=|8?ZX3QU-@xQ0knb8ws zCHPhTob&X##@;qE$L@f?1fR_Dzbdg&m7)s1;t+en){OWXTyv5;J0h9>X8byoyR{udzugUkYmwssj8gob*fHxYnQ3Fnb8u9JqSiv zQDWjDKTjRzX|^|+rC;iOX7r>3_Oevz{R3i`H~H+VN)g}u*zOo#Zz#ii%>9Ex40LN*XYbbT) z>$&y!Vcj{YF;W+^Ki0S})F}8hj{RSq;Wf#5B(KHtfE6KDm`CZYza;ypjrtqU#on5I zi#*NFw6!y%zg?=o^5~Ns2XX%V?;QG%9PcEDki4+jy+HHnj49&$FWA0%9(!uP=+GA_dFVrKX2fN^793yHs?(Tj?r0<~o1kYNrc5uE?U zQ2p#eUXC~n_u(ZDyD@#fmdSORWA69Ucff2zET+_jV7Y(fBpf5Rr~{fI$3e)SZ@-Qt z4&`g!Xu-u}>`AGu*u+&YSMeZv!+yCyjbjk4@cW>X-v@W`Ref`I%lFP$k_k2BBx9cs z8`;N|hj_8T7!l`T|Bbk=RsEXGU3nVwVL!)i(S^LvO8ih_9|WIQ|JvdHIPR#HCwPrD zu2K^`EPTgUa!cU)!NzZvit#eu5Dr}_7KCv$`KZJa*DQb{Ir$$2IA z7w=ct#nMY$J+Aq_*CpadzHWWkLp}c3ug%N_{8`maz!%2AU&8nFxdpJKJE=ka*2?AX zsY|{H7Ui`u^#S)MMc=IF_>R~1d8bCoFdm>xyjfyxvz;RATxFHuL$4#rJFfN|*O|pG ze1=RMEn_NxDY&AtnWY`?QPof;Ycc2R^v@0ah1uSWxdv2Ge7nb*df{voKaK$ zKF;qezVB}(=Ou~U?@k$uHNR8ZdgB%5v^G?YEY^A=UC@4$Mh977neqcOkCrA6BADxD#4GiK7L*!HZhi7 z-$ML=+zpJ##?0nR-Gsk+_Q!74P%oW#aKyd>Fj+5ehlVw zPsL2^M`1~xtM2-7guT#T8{c=1oWR73n^1!?My|cvoYRsfT$8&%oL79cMCY`Gjia{l zhU@)5tD=Do$Wl9LI-^3(U^l$F*!}#`t$wD9^Ftng#`ud~;Mp~tHz%ll(#sX&yk#-=cbV!>58QSY z>s(h=o=f~tV$b2VT=wFx)P9zVE`TvEcGjzeul33E)E203n(0JGp+@)LoCl41yB(ah z;8D><-bl>{xy|zbxz2t*Rdg|2=_b!PuI{=e={(|`MEuQ)T8TfzUuVinOvLlcH7oaP z6ifaa&#}J!MtBH+;^nPwP)pt@y}zDNl}EF^Yi+m2^;;Y2>iql^-CGZA;_rHXBACFQ zpXW;KZ@wgVz}|J)Np4L)Hd0%W_z$&#!?iJH=0^C<+Xr048yJ~Nh)KU>U7+kM4%C4xr0w#+8(;wFdHriR2RJpG1vz-EG zF*0f)_qT%oF$P=*)N4(Q=O3_m<$h8hYps~~gu?^7EbHgzP-nX6>&K|KEEGL+y;bv^ zM6g%+2RWrKCTk^eLQ%}i4Zb5rj^Spvmgfw6@${behZ-1Sl$!&tz7H_~;vIhe=D;zM zygm2yyj65>9`*NWOnw_`VAnTPU0(yMNTas@9`{h034af4t7|?0g}IW zbzzR{!rcNFFO;q~94k8ax&cRuuPx6ja43EukD3UMdZ(yf?BrUAgRwstx9)39V!tBu zyW|@GuXO$#YJDNU0QdOl>o_McvZk!qPIIU=0wWBVk8?>y=1{jouHIBRV&`lGe_p)^ zhfTffvw6T^m0ssM;Kt;aX3~Al>ezkUtiS%e`4OAR=Wg>dS*|Y^?&EfRIlI39EcW|L zSa0^@%am&@?jiiV3qOlAy}VPvBWK^vG+oZpntpH4JM+{rr-XBg0csZP?|$u$^?J@> zunuG4|0Eg5N7}?kyJOsfedS4wSX=Y|HrG<%!u^RY9Base)AjrPud#97s}GnsY~&6; z+)kJ?f$Npaje8nB((`)qmB3eoFUtkn6rVJpk@-esRxx6mh@Za+amPF37dQd`@li#mWna% zC4IO4Uu;$E5B!{6lP?wX2}Zje_~;7$rrWIU_qjz)LHv|=X}1B-Oubk5T%krU<^H|4 zez|twwyd-8syIT zM%iP{2iF1CeKY6$_wI(TMMmZ$s*4c!d-XZhl2;OQnqUnIZ;kCrw5z#dPddZCK>UY# z2Y56+2Xvp0#Kz}gp80q9Z~VmbrVO@Em#InW-tWhOlLr39qv-Mw4JF*2n_Cg4Z%e?3A?*9O~d*0f|F!g<^s*X;lN9+{6!(TkPm z+m5d29`Wl2*YR|~P)yH*VJzd2e;Q-T)=VE$<^|%pY3EARpONQ0NDXG%DxL?#PHte5 zcEz0W#(mQ}N4#dueC1KEuD5&H?~9!tTq^Pl#8oSqbFAmh68ULHjK7Y`#wxpeNak!C zf5FEW%+KkZr&2Y7Yca11YZ`0LG1sX9e#zdn`oe$zOY8Shh zF@2*EQ%@XvAWH5_Q0??l_6XZc;}#!uMcK%?yU3MlZ(@mU!Kc&v{ys4erJ{IEjIDhR z-4DO{8TiX9;VTy-*=rIX#SSeV9IH(3!+LQ~YsP&A^G=CgtScI8EM0FcrCZnN6tz69 z)PwErIHy!qo*?$4eaSdb@UMN}4|r9Ao$SdJ9=KG#qPOURx^AT^_l>=%Jwx2zqE*)P_L)ld>$vBvn3vm~N!F8V zGV15P_{A7s1pXXiuKdw4z5>pV}muHA`W=l$1lP3HVDSo;=<6SnOt%X(Fkmk*lN!YGsN2hN~QYN8L3~>~6DqsPJ=J z%$J+V_uVvBFGKa@lkax7X|Egj_g|@Xv`UdD?=~w{Z_Lv^pQtK-Gzt7MO*l_H=3m;m z1@B+1!CRfT&XqUvoO3_-5!#*Iw8jJX?!Gl6ldwJc0b5EffpbEC{}lhHls(^E-;>eW zwV8HpqB<;ycBH!b;h&~9Rzz8N&;RW|2t^ZfvtEtu6ZQMgW`i7c>1}8gB6qPD7 zW{rD6`?i8zGszX=Wz98P>N4h}cI$?!lR8tEop1?zeB!jO#W^bC$#?5Bt`(^kJQ$h@ z&LVl~ffovnOS$I!Kg6n@n(A3NhRHi{oYF-jo`2-urgisCo`XkEOI090RZH~B z;Hlc_fc+S!)Scd`g~UI3lEtrzD)&96IpPy{+wk>MxqjaA`YY8>=jQImJ~xP=ihVwY z9ms%>>&j78KHIKa(UR_Lh(Fkl>>iZ50N;$`MS~EoK%C0Hz2kcfb=@|`xVn0!822ET zd`@*tn-w)K2Ud68b*XTI70;nY9^@SSh(=$5W?O_jG$~Hvm*D}g2WQ4`zf*`emHNoX z(Km-$kDciVd9IOK8*_fRPYj$uy5-oj=4)!MJ5D_{%%2%{zxT7D9Pb5BNH}UvYNX8fL_DNkm0;qztK0B@=DihfjEN$b1eb~9 zK+bOiuk>NByGW%?&kK;(C(+4Rn1jXs5q8TslfM4$EZ0KND=-GP$xWrs-!T4k1HQDp z_V4!{|29-)(huZbcldNNBjZhOoToG&ABbo5t!`_%4eoix+ufT{=>JuzjRfZ}`5C@qE>KTU!k6XVgE#)ZQjztu7whdg zEn&kcb&a++-p+f@_N+CdS({wWE5V34Pa@N5V{+?|=b)DBfP*1s!}kEUPfcPP6w*yv zH=%dj-RY3$Ty~1*r76D49#7JF#XYygYd8`f@+`t!M32(fM%?3IQnSi{7k0vxfp5CS zeeO%(94pIl1o%JY&AjJ5V_h!Q81aWO?Igrn?!LLs!G)VO#dqwb*Uq?mo>%=DWhtKgdl75Uk;ZAUT0M1`O zw}?#&6Hk|f*#2xNSck+9mN|W$U+K3ae@1%ZfWa_-5BnK0D)xpov1i|EySlw@#db+; z88&pj(vitZ>_-ZFyEeh5qAm^|0O?z)2?iXjkAWEXdhEFi{8_dss7ZwU?)Fu%xi;*j z>ZG5U`gnvMm>dSN; z&$vgZP;~$B*>kh`yQ{wLAesU^)+eqx=)-*i>p`4D*#VagehK-i>j^lOQVaOtAE65&vcgyoy&_iU-^&AD$UR)Eq^+_3 zM&*TVZ&0(V^5nqD=j$5bp89$f{8W2$#H$tOy6hK?w%r!7%8I!eeZF~-^fr8^_eb2) zA_mf4#|8*+rd0R|%sp^41E!Mnn93x~L#Tthfo3g%{5xhDP5#a9 zw(0y{>LvVHrIxna0Mi-GBBKyY*U8Z{{&p9 zm44Pk+;!+7L9e25V}2HFM;q1m3^h{IpL2azjl{+=*HoLt7OGrNPPj>&>pK3)dsaJl zH{n>PTB!HM`=#`=@IKb%a;t9I(c2Z7$_9qTCAv>{qDscUh=l849rF!HXO{vTz^+bQR zoOAPiPGjbz-ymN%DGhw_?tTu{?LDx#G>=7B<1r3e8ZX_BwKvY_ESpgP-LT|iOC=0zW153Yj-`}^t8OHA8`(W^W;2AU9 z(YSQAM-6kvcKG$p&=8z`@O7NNu#?y^=9z?h>^U7?kC7RAzrB$=0=Lv@1)7H=}p;zKTIEz?6&I$Lpl^)E?Oy7B14nlvX#cROH zweRbr;5vqy((ShANP_>S{^^ITD48{f-kP3!amuxjzUPy9&e~~sJ$tY2&0`oJp8rIA zGy3_;1INNS?gvLb*gfvnULnWVtUvIE{tfpQvozk)!WotNDH>6TqodikbL+d`H92FR zScfB85%*rR22Dd;i&5(0`(U765_R_N`-0j9?@fwO2QKRBJ`+BlKlEWYGXIiCxph4B zR=YJNVGlIu@xh#o?FIPk6hj^F0qdLBL$V7s)`I(Ln(LBtJg%E^KZi1@4>19$W54G| z5o(rSfd9r-9&-YNx+vjT+@6os1dD_ur?l)naN^ls&zW+HVn;yS6q3`rvV~^}FR}YNem;}8e z(3fZ&_xVq%4)vPi#qKaJ_&t7)8_8OI%T&I4*yp#v=4XxjikRlHVx1|eFIAzw1UoT~ zxc3Eo;=)^J$+mZzj6REm@1oRJ>_ZD5Yma@jL9fA#E+pP*nG2X`BlQN33DFnMbsG0r zaZFcZ-m=t7er_(=Uz;@I*vw!&mHW`$Hsup?f8<->q3w(8k^h+abZpxzF@ zdpEE08|kru{pFf;Ch^!=(9!s%3~Em4Hkwzq0LBxS{Jas5XW+jhzq2j^Htb_?3@^C9 zIh9^S(a6zN(Bx24pDHTt@`*KYlEEJuIQPym_q-kaaLwuW9BS;Lw^AWDqHGZCtq%58 zp*Kvh^`z&@qvrR7*i&+qsarJQ3p4y<-1Hl(_Yez_149R)1C%b#J!K{x?_$>0{t(Hm2nRX?NrVM|F-|3&o$tPL9az@ zsNjMlOLf3f9(EGfY@}yr2knFfV_m^s3U}`%3ppUyfPj;xf+rf`i8eN2?gevCuh0h> zr+#zd)0yW(eI8H+{3hTYnPaUyGiJ@L9^3I8Z+{?GjHNy+J@Os%rVczfuEPr__{dAF zc+K|r%|7swxvuo*nD&CziayfFi!Rb%dQ{A*I@Vk)J%}Gh{}SWZ;2|<5^%plRXv45w zFW*b_Njwb|bLluXVV%C%jB;oP@S1ck584-o{Vt&=kFmhhetB{~`#D%dVGfuJoFo3y zjI(h6)D8Y`5Vw`ghpR33*D!BM+3pPMbr$^E8S`ekGp+*`SWEl7V1B}A-NeAu#SdIh z9HFt)$HGM}O&X!65WIqG_6a3yqV!6U#I@kUW&OULAwHysH{8cFnTDh;zM}IDbI)Aa z>&}sT+#6*TY%%hv;Wq+jydfoaf9{h~eeK5#O*`qOz1$M5@m-_ve14L75RM(=vv^L% zJ!u2|5?(KH#PvzY%am)&Jzq(#m$1&mo)TkhW7^(_ZFIqSNKr4Ar~UW_v7n?sBROi%s2Cf0wg34UE!l}qiaq8dJ&dlWuHj{Y zMqP#d#P*aBi%bH)#S6YKdoQC1y;;2tAhrRl6A-XISHt#=cn|aUq4zbvMSbt?$d`*H zwgwlIU$y9l8tiGCZkPwgbLHvLx}0+z zrD-I+?V{Hrad|u&bj5#a&PY6e(Cks7_rp1yac-eF7D1nAWRh9ST1Lq%GKool=`Y2* z^55p88o7+TXB6H8TxNv#e4mehT@D|AKkv@UIo9&|_9Xu1-V?*VoOA4)^B`4EIsXrK z{Fr+R&mP>@H|xb$YGZzvC%QKLo{AB~h>C#KT zgIbF2VYr5t>%I0d9mig%ecUy9X1lZffe+jBGP$1oNAEzW&zAecd~r<2HVw8vodN&t zFb}}W!5dG&f#*8c8WQX5W3rohxe5AJbo99ryR?Bzit(R`Z$Zq|`?TzB(i!DugP(mb zDq_-ESBIJg=f4ssI_}pv>HC&-2#j57f6&Bx?R!SG= z$M`wcC@{K$>v8PsDloB~3US-9CzbQM;gXuXu%CDDZVF7UB>O2mq{3}hu{*>9?q_S% zwWl#`5@G=ot{?ZGOoRtWZfdpQ-)DS{xI(QrXP@MrHi47NW9HZlz3oz0aoB$)&#~tF zq{DOQ`yr#Cp&Z`Fy%gziW{KmhJ||83KFEH3m9VYc%b9Tfd+tN*Y0|H~PF)gk$o|=8 z?X-{Wk>mI4D6&2Yz3in8-@|ySYC;W!Ir!HrDkWY$tnu4jdZ=kJufQ1CYC7o8Sb5H+ zy0Shm7%OGm6nPN()@t|E*qH0F=@EaN_j~ z+&R?CWS>18dqqq2{f|A{ZNh!jhw%%~Y%UnzK^N_z$EiXtN28N|%u}3-W_!c=#=wVO z=!&cv`G&P05MM`|r;Wf4;3OT@T)2MVOe87?Pe@nj+ z@5M1Q5VeWL|2$-e-c#O#4{xj+K->eQ=9Ntj_O21VJor3AmrLqoyax5e9px#sw~erU zHRCVc;~aX#{GJx?N&a|G#WnNCxo1ANT7ai~!Q9_*-+QF0Vljum^T1%UPN6^NNEd5MkM32S=9pYu2o`-iw_HHkv}x*z@r214xw zwY2U~qhHO8ydQk5r=9w$_r;miSy0!>muioABoFll986 zAn}+ea10RZLKg`d*4$6;QE!O?N3rX1upGQsj$JDBGD9)@xNDf ziPKXW*1s__cW(I~TD||~(1#v$%;B}7x|Td?56$?YJV)ptoaI69q_}0AFUeQ6ta~c_ zIQx3YmG5v5Ud2=0{H(QLp?A`|h#muQOD)$UCL5P4b&q_vd_~TnSZ^WdQbA*0IA!gz z{>(b5CWHQIL*|zIk`eztC~CJy-v4eGa=m~*xmWfbas9BLAN%jpLr)gJSL~>vp^J6? zg!fO(!%lon=)pP0;aLAg@FTC%x7N=s+x1?zVm0DtaR)vaa+7c63-@q-grDf^SI)6^ zJdbBy1w7;>3))@DQC~thNzw}^_WKy$@b}cx6VSh|dt5`}3W}ih&f4a>@6*kog#e__ zEmWpW0$*=;!{AqdF=y{RA3x|>6s%{#e%d(ko8ZW?7P-vj5_*n1jDI!aJs{U`)h_L| z1f++@IMj3dc)H6_tPlAHUeo0CL4%WVqgZM)+qbxrTI1OD7@~0t4L(~*_I!P#_t+ci z9rn|?uhP3!6>s80&E(95T2?JM!l_0g;xoYyK{f)O1 z)N6d6=td-`bw~B*`^_sbAm*c)>7%^=4mmu>fpaI?TdW(h|L2;pJu&)ik*6RRu%ffE zDPLH_Ys~#=vd&`k!a4Vv&0p*z_rLw2S%kA5K2U@)Y^Qe2^@7&@YIf`u)+gHExYyx7 z_sV-PKfk>=;ovNx(-rD@j<|nP_D%tN1dht8K%Z^!&DaOrJ1g;p5v^*`31A(jpFw{# z3g=lMR^mQdHDS)?`Bv;s<<7a63wt60hC^gOA8zJ7$6<+>Ejh#lMh``^P1a~zFg8m) z7Tt5*P#f;=5!xn;L!Yu}M~a@s5?U2WUvE&%%i;ck1pV~fZ^K#?jLYP#C5Szt_dI5d zw>=r}AaJ0x8G&Yyj$CS2d?zAAb_{}ivC$%<;Nr9T^7 z?CTT1T&t>BgD2`7pc>g9gVHQxV|>s7OD%m~>8{GYa_+)-LZcYJtYq7SO;yLvGq%=i=Aj~Bub6Y5nr&cWj^cqnkmN1 zTt<#hYVH|Rd#{_HPFK8_YOX6GhJY>;e;+MVSrfH;)U3G`&qW(+hnfq$g!&xsrJ^hE zdmCMc?`Qw7p|fYwDD-F5?vdmDMD=|b7)Q+aklk2vYw{g12z`5jm=OGzsn}^9kp`#7 zOdIV2hR7HYdNpyaoY$#hyO_OOzvj3^X<%LWe~1soharCZirzk>qSZJ;ofFRh+Gn;M zhcN?7G3h1iIs#)m_N+MOMJkT1Hi((}HR~P)KOVXJ-H!YId9PacDEyYa>02GvePRwqeeKQHT1YTw`*=FW^|aLM+I!Hph#^eBAxe z%|l;|A<-DcT8`75YJNs~=C^CnWJr{LDOr^v^e>2J9@c|WABZJ@?L+fju=xCpmK{y$Lv%{eaQ{oUh09oJlh&t#}kWB5|*oACntUGz^s8Z*by4)X$?i@`1GqrH}w)K0dgk2p4&v{SkN2)fya&x)Sr4*rQ&t_|l_@R<#p(8J8S zU1Ou|M1M1){ndR{X4Lcg#6OM6S{pcPvHnA&?xdHOlK-wD66!Lix){YFPYS)Mh9pNs zZR|v6z39JR&i&eLT&>=X`n-y@YNz+*a`NNs*CI7nmXE(wDpvHwYtfk4CZ7%H9vTBYzj_{eTVw3W`@T2UxG@bU|7x*| zjk$s52xnc z>FY<=+c@wd;RjncW}hk?$dF6*dg}vAsAW;V_E=*MI3Ta3=n#)7iN~00{sm`WagF-z zaT+Z)(2{nerq{U??z+3}oIQOFIr^7KlfOG^`lF|t^M7#u(bH{5GC$^^dvNRnp%L?- z!GnDNT<@Q*S5%wCsLPdNADk&F<7aZ4fT280!rV-u{V4gWN!+dH^F!D-JGTNz`fWV= zq$nMJ%SN9#iy~#4o*(#S=DG$~4Y3G%4Y}`!pGP$IU$>*l?%Tz~OJn&w3S}nI{&%`M z`}SkH{oO)$c7zz~>(%EgxG*tm>SoOC=Kg`VSa0SZ=by#zpLWH%wW#a7Y49q4e~zDL z*DpJ|(wD=xuj{L){3SDA+{dJPnct+JYyZTUKs#-;;&bLy+1Mog?630xC>1rUM@#i1 zG#(Ys8DiT%cYAMEOK+AOi(firFKcDbhi>l-=J;on-#qWSOn(&L-TKSp2)JAtnbfGu zpu=KP;Vg`Y7h8S%bvW0~P2I?EesF)bmi&h`s;UULq9HaCxmbPBzZyjTyfL)-7CfcgknucV8qjiB)tU&Y$`MfxjxOzU8G#P;Zto@_*` zAFw@kioCCa4!U64xvX))&IQ-n7faOrxd-yvDdw!W&FU378OLhWb0I{F=*FuO^Z&eF z9_p0+9s}<9Nz$_$nGNDBK8F-NJniW5D=m~MX(=4KwaaR=HCl4M*^+(*JNd@X&w9oB zV|m`OL3fr4IQA`+J-_^KGr{w~aEkRjRsP zQ+54HrOxDYhx4)0(jEF~LR=8^-oxKT=Tqt!G51y@SIt=)OJ8o3*zQfx013FK_?Xa- zWgUa1SPwP=)4-V>>nCu%Ms$+`mrs%4vb}a?bkq_vd|pW4o1ex=f8c(h&VasY(Y{iA z_Fz?}seBK{&YD#RowWaP+~zQDu16gDjy5OrvRng?-f{GWWk z&`aL;J78_?=o{--x=nBQZO}AL`W|`cv9M;P9SYu3>T7wPM{P{$LGQIc3l(&O`r7)j zPZ*jmfyY6;pL4&Ei^a!zG_G-GVtB1o8`S)=G52q`-kZq}>d(STq>lgh88w>zM}6Is z{zJ`iaBH@#S-%)EUU-bf{yw*Ddw$S;OS#|mpiktvsSam;sP~|e&1V8DIjd26)Tl`N zIzWHkXy^;L33~H_m&tyGU;IZ8H`Iw#(9e4NgG+Yi5&Or78nHiU_RxubZF(9W%2M#>N zM7?fT<#|`A*Uk6x9Cmma&YY@o=9Kh}x=QtDBaIK^E;@DHNgozHuLbi0X50V$+Wptx zv*X|Wzkjbs^KY9}g*;NUSVj*jPr=!7ftPs&ZAF|vp>lqXuQ%yA{?7h24P(X{IqIZ) zoF}+_4SW92v(EY+!0I7A#Dpd4w>T54D6P*|i}UqTvG3_?6T+J^S*`x%LjdC!-c)~1 zsl4xxy)uD9JLmL~h-qVJVr#Q#B!XNs=J*P8Zz`XZ= zb>_&CIBHk*dEZr7XBzu(;Lv$?JjVzajABf9NSqhnzW$jH>rgWa@%dqngVq*oi89>J zf|&6e;u2*z$2K9i-iI8TH3yaSi){G*-X5E?r;qfz|EkmyIRa~SlgXxP;JWAe{oThR z-h9hmlC#GP_nnWmcaa;hP6PX9>B01JKFUokeel(x@1rqH_=)i=(fr2G zFFc1_&*8r6E8qe$pa1293+}(Bo^#lbiF@sU!yIiomdEJwt;t zXrz<@<7@=;N+pJx%K1P)xPBQ+k5K-|eIRY>8RIcVVnW6Gi2#(<*Pr>wm9?|(PJMpC z?^95SJ;3*I#c!J`xjv4OZurJgJ@df02!}W zOZe@rx>-`AcQyCX-{`!t`(FngK$C4SU(jk9+Witd%+-z3bIijpcf^<$I$v|XDd!`% zW1J1G`0U3}V+g&CWKqXYtH7mb$FoY#fXJdnYi{PXaSM|^Za1S>^}H4vZNj;LX8gF_ zT&T^rr($%=cAwni#D8A5se8QHZ@FG!(z3A{`J58$K9daY zfo}SJoi6zdrf-W4_!Oco=D7!y%Ja?PY&SWNO8Q=@KTDd=@-~ecSvmjw{^}FhY$`l# zufS=RcrG^CTIsHpJ*4!4+$NJa$+#D1CYh&|l~{T;4%#^{+|$2y7Cp}zJ@W1q{SY_k zk5B}CU)<9bV)b`#R%2b&nBOd`mEKMH3^m(|{*@W$s2jJo$$#Oqi_R*pQSEoo3s~98 zlD*88*pBNMv9jLhjnsLS`tq>md&bY%l2&@3Z?HZdb-rfXaNfyypPs?{-0;uyH82jc zUvsgY`$Y6v09Qb$zp^@(HYd9MTwpDmqRZYHRe%WJ}2+zD2Gfrzz|2up}&PruHZ+U;F%_?Kwi~FVbHQ8w0 zfA+oqEc8Wi-E z-73T;;2G&x=C}&)KjLeguP5FaIcs63!C7-AyHtmBMx>{~I5TP9o^U2;E_SWd>!9zg zxL5dCJEf|}#mzeCIu;xBc8{>8ab_@b&VbckzCCMj5oEpdS(^>D8^Is_zIsc3H&FMR!}+OL`?IKC-E!ZvS?Xx?blzp^@@k`P z)U9UF#WwRMUVdCbV9%C`+83K}{)2Ju=jf3>0QAz*w4>&{n}qlAnL0}J9Edq#vCeTe zr)b}B?_+ctL!mC7&zT1v_+5U%bzy}*Y4o2cz4=2!8r|=cu6G zivBNhYv>^H_n1WQi`?$iyWRhKw+`A85p#JkUX2>gQaDkw=e3V{?UBAMH{j_~(9cLi zevyEuAI`+Mu_|WmZS>T}dvb$nil5b>y1A+~-B>lcn()sXywBmhZFyfF&Yv>g+(d6U zkG8(Sb#f1Fjv3C?Dnkqn?OIy$S?{oQy_POwD{8C_XHo? z+@I$XF6EpzU>jW_bvWiJqmIFGRLuHkq3!`L*x_swaE?U3k@;)1N59bBJJ639ao&{V z91ZSO=6Wh(Ttlb%1JDeGO^)={Sfamo#H+*&hxuAVRg?gV~a_tLR z=Yvk|VYYxrZ;T-Q{&wfK`n=_NJ)*v|cRO(kqH&LqQLsG%Dn zXF2116|s?5eCE2Wukada`+0_Qs@t*7e_?FzK6$raYxHup&@ag1h;@c6l?nI%2QGPB z_gwP3aE@*A?iQDH`yXfNab09@VvgnZb~V1Ys~h;83*LuY?&%MD-(2sGrj1^1(8o1* zKW`t2du?_*KK~+Jd%fg+1Abt^dtKA`y|XmA}ii9#rx69dDT8VvwjbthEuO@c+MB^%xQ{D=rO~Xa))Qe*QHCwsrfy< zHVfOTyMt}=0Ta>C!P=vjjFyUfpmN6R`!kGn*OA?4fye7!b+>te#;h4zW%t|zhk&zCqy z=b&G!>~8MfJF`m8nfK*cpBp|Aesnj-+GrDS?2?5dH%#oF^QYGC^LvgDpdYWxd*L2! z#I|?DygYr?D&ja7y}%y1L?@VP(Vt5l_gdQE4+Sj@!DxD4VN5rR%viV|hn!yO983Li zI6p1aPc(BK?B8`b&9x}uA`3>&c`BcWt<89-4!s(pQNBFUs5+d5VD}Us@3-XVq=dhQ zzNOKv^zX&ew>-ZQdkszYvJgz)tpAHxt|^@6XP}d2`lGgd4Q!pq-iDvrpLRJym#a<-4kr0s5XqbN(;e zqTLGXI)R2wGGG1bxWB?}T;RI14nTj#3ThB?ww#%Cs>j!ex#ax4=q*_V>{zsrCPt-= zjKjGiXZ-~}pP;yxb&8tyiSF{rnhSHgvT}x~5gi!4Bhfa2Zdn@E#&3!DPUjBz)F90<|d&1HDYi^+R_nUCK@ft$o*0REGm z>bo6t^m5c|(JJmY2R`h<-?PH8`;~_N1mWqqhoJi}n$bqEhOzMUfvwo^zT(h>Bl^2I z*Jb-2`oI6+CrV#5_qcn}a(x}0@LGe8eK<$L9k5SVRDlm$Nj$CFz-e@cGo@i~&ZHNB zj%N{y<`wEG{WW5_M#0zUwVsX~XmAL(+{a;sFE?gBtMJ(ZR>_<#_sIQo#>`L8#pw4j z>*Yfqs1AO`oN6lOd zu17Bl*068Tr(FtOIX3B~oZsH}$+~HJIkC>Tu8KnR35T7w5bs7aOMdjI^y_sY|60m*D!)3Wv{=v&D6JVJ87&Pt63n@mA(U zbg3l|L?6qn%k*&Xp-!=2eFM?9J=EG% zuWj3(o9J-HitwE^>q;QTePBL~oKq6w3gG+`^d-XgLeop1QK`?t)nJ>@ZJv)kDEV!` zse688z^(tORjv=QFt`Sjb?BqZZ-PFz)EvWJmR=v(%YBW6=gK{#y^jg!1Ze3+BI&`F z^ObsE>Lj1}dn_kd7Bu&s*OLj+YGjN)p5v6ynRgjtDd)=3u@7a3KGhH#n#rm$I=LSv zKLZ!hp42iVmf3Rb5d37$w&t9BH&>6sFG6i`m+s3gaHdBW-dhXz%kDbFa6Fz&bJ}2D0oWyjiY#-5=Sr>CXSLtW?KF0DeFF*QuNs@Wxo^@C2ery2aK8kPM9(KBmvRkLme#xA<`tJ=|W7nNzo$kKg4B={B5~; zzdz$T6>0<_*5El98R)BWf71{CKWgmbOVyu?!LetZd=c#;YM&9q?>gK=(1|I9OMUnHX4i!(5;Fvspy^l{s)>E}VI zx5Y*yU7@A^)nluDPX)D8xp&c;dEr=G&+)AELi*io;U{0$K3`>fim!eA_08wKuQR;< zfLALG9-GcI^!(;qx_N%%>+;_h==W-*e~zyuS`(|O{xX9eGxtN0(RccNgZ*LMsL4g2 zojH__1aC*YAIrJNpI!S14v$8UU3E+DPJNkC%-@BxIxm#;$-RF*N-ZNFLL)LucS=EQ z-r2TAJk&7$|H3uro97MiqRi&X%~y{k{k{(8Zu8n>OwRnZ#&*qPdbOHepmtgQy76n_ zZGt=1@xB@(FZ}Awp^ruO+jw|BzW>A={=xlI%>6sow1nH*hTcOP@@^3RmSKG23yPiuIS36-s{}TagU2(3=#1w^A`DhQuO&{Ql|=M z)2Ao)81=u}d_j%mu*Rcle-?(47%b;~5q$wRcIm9U$8-F6)arAQCi_JkH3tsdj-GnH zFxKb#qgzY;0s80T;kWnE=ejco`w^%6?bCnrIVZXs9`-NSjZ57!7U?eWdEr-lqTx+9 zRORSh;c-Gc@Wm(ke0cl$QnV9je~+L!fO>?xgDLz;^@Pt%;jtkV%ZAVuanOIu6ziaN z%oCdo72A%EduUcx>P`54Y=@vND_IT371RlZZiyq|>i zh&W%ay@}dTo3GtTuF?*KWG!P9;W0@!~cu2FKcRChqnGf{eT%eJW8@` z%funFF_64vXdK5tfCTLD>%UriOHSxM_ul$W)u|4NM~!<}do3FkIw5-yfi3JeRLAJ+ zh~B(5{2^BP-C~~6x@O-)9b6U${2^Lia?S?*D|hqkC8#dm3T5y)4*GdY_u7lG&NkBI zg0Q4=f2&2IbHb8>%TtZ+i$WLVYbap7=ot#CpT7j|ch&2}OW>%^2F&3jHFRX}fz^xl zIy=V9gZFDjD|5q*Xcm0he$b{LOl`680$-zfwYqKvKO|j~>ie#9IB737a`~&hA25V62 z^Rq^l&5a_yUEeR(`(~l+Dp{W$jV2-wW zC++5vV@v4;#xnA`m4*$5HrZj4g?g>pM;MfuI4F5qXYP;;cC6+CLcibe-1X!N@gobYtQidanahy`L$}T*F0t}9FclWKg;zcKlDIlpCjwz&iASFrzq~(RuM2D zRCoLP7)MR}?yD&0;b@f?&-Mejsq<$Q6j3!{5A=%E(#!ybn zDe!naugy;FTRYBSYGct6C%&RMaBcqL!yg?q5FdOyWcC?8waX)_PM%oiEkbTErkoF5 zllUPBGg*KyXAhiHW?z`AM6*`2Xl{YeP{0CN#(~7!CWQ8fMjkp}0na*LNvwLbSDwFx z!^`c}Se80*_WIwNM9lxxUPQ14MQbBGBim7Na?vhjEX7KeH-jL12?yH;f2|>Fjqv`2 zk_+OmOmg`(3gy6#_8;Yc+F3le3L!p9Gg&n^gY$P4UJMp$rP-%&d?3nc0D?#S3Gv{f zoOXSkP^s-v-5+rk0rT&CY&WM{;vZGYP>#=WsmkArVcxdWgl(2ZplOXm<7{t8swbBV&A&2wi?NBu+R) zZ%A9k=lktXd@lNe-hBeH)paeR2z!+|(sOY5e#T)R>_K{WX#K^ES)#bXQB4;5Va!@O z0ydy+I4;V#b>x&$^+=i!Z;n$W9Eu#6cB;#?YuI2bmGeAv?;9X50h>rPRRw!ja$cCO zjkxf3g#MMT_EoI<_d|VRY;)Oh%!%4_En$;Cnp$GQ<~ypP6rKa&4*Ahl@KL&TF%RE~ zdkOf*$>Sdx=r66XmWSA{2p4z0+a@+&SnxM)my5&}4X|%g-v+=%4u?UZc{=Vxx0ZDQ{x z))3E}p#IXR$PD~vmp^13Ag`T(T>o!<+e#Wg2aJNpD{5L_E}ycO?pn%D z{6QTrW3oi8f~2H&S&0?-o;rCtZCyP{OCwk6+YRlrp3^cF;5s#2`(se!Kt4t#ImScJ zDIH(M71fha+?6mZ{d>Y*^KH7PHg&l{V7L1o!c^+bO)2KW>fnb&CfsUL9-dyIicu zpGkqMe|?mJe$+~@dF|8o3Ya4$`r4A{W!pd-tot}ypKjYRV`J~7q4}U~<>m%m^LESg z?`-rnjmuwSb=@vr%3p{(SbJd;U<}%$no7U+)4s#@7h}s1S894r2lzocY|$q_>Mz+= z7WTFiud+D$8|#-L|L2Bkn|{_xAO>&0!05v|Sts`6yZVK`K^-Q?9)N|U*aPJ(zM*R) zc)j~G2S3aLZI)@yS)ACmnw+hkCuh6oX&BVL7R=f$VX^C-Tce1>n(zz#x%P?HxKH$@ z{rE0EC*#NUTVUPTOwQY-Ob~$zT%1v8`-L@|w5>5t!tYHRNtq+=)=Ib6@P6L!c^N+Obn=gX63cVFjHc&%5*V_UWQXJ4K0eJ3y1&7Zq}?mOhQ zK3`2~G{X$6ATT z!>Tf=c%BdN$pfcGew*JXC3sH$RtzB%FR2+&^fo;gp&N=-%ikB#tOe&N4< zqPVzK?Pe%!6=H-)JApo}JjRA7t}%hX95P-8`2@4ZJnZ@IwZ3J{2-o^@ETK|DqE?vB z)2MyHO3hlQ$eX`mJ!6b6*TdALMPw!GN=_7Umg%r`I$wDA!Z05n^5WEHsP!B<+@~bX zaMDc9YM$eaXR`(CP%7dwaP#(Ts#;~B4tLMxLpZvH)EMGdTPL)fe9q&HJ+ZESa zJ6v6_&&YL?#4puS-RzLZT&sU@jxgW;|AMJGsx3QS58Lf=`)l@Lfmfey;X@IQ9^UE4 zclIP9OTz*QWx{GH*)9`9*$T!SP4-d$np@ z{v`72Va2+04jb0jcv-h5fIr|W`!$$tUvl?M(0Z(`Ab$0Z^WBExXV4oPefEBNX6fBM z9*}GLfQhF%JJ#uYdE;lKbzj&{FfS})ks8L~+k0u?zZ`0RWheyjJ!{Re(u(5#ZF{2_ zn`CvEVc#R17u8&npDHYB-t8T=Ydc$sSJk$u+GlxaCu?N`!{d4<B(9Kdg5$Ny`PNt-DD6s+>yh}Fefv{3bn(qqJ1V5 z6CTg#{S{$~QuxvsFVu!uWwT0hT%*^OB0K`=XPOOsZE8=Vq(DrgL!Wc(jxo(eA_~qi z4gUPdF}=+n7S-ZBU5^WM;8|E9$CR;O)u{;Q=A>aK?3IWZGl^^3o!V@bz8K6t*Ih(@ zE%{)-g*2zn-XGD+SH0d=dTsaF`K->yvw%4&*(XRoVT+p%akN;$mm<5Ic)t0WPp&tK z%`Msa$R}M{y?#(5K^#Z#;pS~NPCk||e~hz@tr|^m+^UMmpMs6A%~smG3u_Q3hy5Gt zYL=wW)3wj7dHeU8-#J%_C{fRc*qj>r9G>!=3mstx8*R6lwA%wF3NuEd?+9CvV+{M+ z#l6rpK5Z^hHiw!-#wcKp7MV4Brx6Hzc%WN5TNfhS0<+TEy9m$mA&TtWd{^s-Tz!aA zclIvj?@P|HNze5ykDfnQL+*cYYsl^VENW&Cm#^a@-A*3gF3lQwDe+`37Qn@`*|9NxgbHwEHxp<_jcht;}jWJ1h?uP0L^V+Q|m2O79UZ66~Ezhkr zG=1_%()DGGbgp7yTkXg7p7M=)Jp!-EX=C5ph`*z_2F;yHB;Zi{YrMGl-IZm(Y*NV0 z;^qG3FxH(2_f#{(-UM zj@!?^UOvRm)n`*YR*N!`=XNPkZA<5~|GXNn+pop>eLJrDd3*yu)^X$^HmeWQReRJmdb2v!P+39@-t$9DCSX8(`Ua=*7F>Ds;uzPXLHcT9MoCjCAtL0gR zAl4IJQ=0va{4ak)bNw-%wK(=0dcQ?FKf&({(7WqMv)Q^FLdkyEv2TmMm8EXkjsZ`P zmZ=a!t|2_+1rd`o74V7;)nBV`BgJ1ef~pvqh37KK(WZlg&X9jsDNbRB8LIg;ef_rM z4jJ>D_CBwsec$8eh{Ge^FgJS;<0hkc?>O=7bgO0Su5aup7aM~*XXQCNx5E#SDVYr9 zAH=$l62j&C5^GPc!;{n76Z`u*6k179 zS%X0H;XhzP^~uBeb@+99>omsJ&=?b)P^2ByQ4Ue^8kaLxm^t1fBc5C?FoQPY%4^~o z*37oB!zedfSYAt&37wxw9LUDuGOop7 zy>sU7?sFxq7nFmCa^!e{j%uFlgwCZHdO`I8;Cg#$KOVweyI`I-Xr$Cu5C>PW?2qZT z-|4nps<-XDYEH&4VV%Xyr3JpQ3Gx^sKii?6E#iEACTvlHb7ReXTlv}0N^x5;PDE-w zUKD|_SeI&CW5nmSQoT*yr|<7W6HJFngzg>-D@aSHl~MsO&hHWa;7~hRFptmcPVT*~ zon5S5eEbKW4K^P)X5zz`A?_|38wPc2%T}D&6Rz$2AIHZ%kB@@Jhc;q<7$2M~mOZZ= z>o|rs2X;dH{_nYF(q`&8h@}oK<%BQ>%3^drBembgn6Vg!-O9any}b~Rrqa#Ha= zpQ!fp+Vk2|UbsOV_?dJPdF~-4R@Ri~t8`-#Cyw!b(ZFYNzLb~+5n@nFv%he)N`LbJ z`MJjJ1wYo$DT;SKG50k7CH>t(3+IDFgIu!@IQq*6^sypCJo@mvsU89x+VQ5jB|Lzs znFoz(twOg>H(}@U-@omF&#Ne6(teBwT<6H#HS|87M?@!!`XAnopyv{DJf+Psui?M% zh<0XQQ62Hxg#7z|;Hv8a1hpbHrS$FEbB+paBYtki0CJ3B*w--;cR``)yTE01XyeC76T@!pHa6PZ zrRg^71XzwDn{jWeA5l`AW_IdzM zq;DvRZ>gsFu_tXC7uV3)g*4qMV=QppJhZewL(2xJGP}KS@3xK|HbajL&pDMX^$55! z(!^XRrM}Xm39#Plr08|S*Yur;(zxBuh4Sxr8k;Uy$JCY+e%@T@#j74(0yDvUgq12AYRs~Zd4MDNtCjK$b_4t6vgd^RzF=KL8B!je#z)6>O1RE(0u|C3&eSt;0{cbBmt?KofE^Jm?6V~>PMBYJtX-T^9hAQ8Xl+{oYhlqx5pjcyaJo zjd*_|wvhh}tL|y%g;^^He=bEIrbL%5w zwy_b+au)XJaqmI}OQ)>cSHFOp4pITg=0u!;01v%Pp4i0@z?Z z{Ji=|U^`MQB5oNw06!gka*Wyki^KCQU@j%9UpeOMcD9Vu%4U8n#k+0{5Gdp+7p!eMT2E`jTpI=O8> z8s)gtZY%eh{Ql$jq4py@bUP3c#v5_aZbuiAj&HPbd~(i)s<76Flye~5+0i=6T<0`T zTk;n^clFJ}aifPbQK0^3bjF&E#SV3k;_573Dd30ys>|>B0m#RHf(?OK8gV=4z~mk8 z9b1eWW2<*%*K#lxXw#Ka8|YJFMJ5g|+80ebVE%wST+s6nN2vs_I^UDu)$=UabL2s* zp3lBoG|4k@5W8ca_J?E9hY~obQ7eJzm&j=b8h&V^IG0(8a>6z>>meuZei7^!tii(^ z>&?hxK3(oG=eft@qh;QAahOZMKEd9+bKHi|p->s=Jk1<-gZ2{Q?P6VJZU^7C+ZpE| zd9ArQ+sUU#SA*+#$Y<5|nJ{(2VIS_~2Y9&Mgt3*sc~ zbpV3&#Dc%)>~m+U+qkCOyLb~+(`hU5tV!3!)+#C=4ShD^UTrcZs>zM6Q&CkH_xXbO zFaMKY(8{J9iGTSZhb;;Q{UVHt=nos$(p(Oh;;%j5w<#pto*HGB# ziuDQLpP1O|Y?7VS>^f5|_XqtLiVaRk@6c7_IlSFUwHivW29M*%qxYw^ z^+Iy}yQ@PwT-RUony%@_u9Qc1XYq4S+E@ebfy!}P{RfvX)o)d@*?NDBw6c(6Q)Dys z9Jk09@1bFbeSmAE?&XQ~T)VvL_?k_h7$p&@UQgyP?j$g-N2>*?57~-fwEP(k$ z(_n)2Sdpzp{UxE>r9BSEpgw`~lgzs%fq^z$n?e}fH^LY|`_A!1d2NTs*%{X!`Z~fR zZN^c*Rx5Dwy^&^OST4JR&V$y>yQ@d2QDI#CTfATn4CZUKS>`d@#4n?Xiz#A_zpXv> zJUH?8@Vt)GSjw<=c?M@g{)nIXHeyV4t)spMl5q-}a0*o)%Y9%jGS5#Ej~FJAl6RywR)Y(_GS>yR$S*&aG_7vYTrolc&*NFH|(RJZiq1=#9u9uOL?5i z@LcZzV!<2)?pb}eo^M?C7%#V8TAQQRe@A=~ia354BgYz`A;$(Oj(p5nU??uzW{7X7kb@0?4Pa`V*+=KUsn821K`OYL)A zsAVLLk)t{i;u8~Mm=c~di*wIMpt6{-ryjow{;5fb@wPy`P%AyWu9y?_sdmTOV?KG} zFJgXtw(GynNmp1(&)aa|_8`qBU++cnd(wmn^oiqR3$e#}ZYAFP(q2<21uoK3jF|kr zTjcxxu8r}ye11Od@tdS=Omm93^cCY=N5RKrs>CC>FaPBYsi3R+x!wemEGbc!O`mVi z!{=xZ8`0;*<5TRd!!+D)Agiu?-3fu($}8RUeS zsTq&U>+f)LHHyQxUr)oR$LxcLfPUMx?~m*5^J<=y{x@w`RC$$dqPdGNxNOC%I$Voy+QPF(o zaj+Jw+u-<;*bexM6RvW&h!0aG%rzh!?~&LJE95B?&apa7df00f_xYerEmmRxbPRLV zP*un8V-CBcebj3$v5t@w1KK}%Eg_$a{UGD@twxjs3jd4G&e)V|1vvh4I$=)Tzw8Lg zrD=Ub`LexqU0{FHk)3|c zWsqoKFEAz@)~A_0jtIwpsGndBFXgzsHXgio}*Qkzn^{;{C=i?KX3vI1ViDk{2CA+D93rVw9ER8*REctUH5f^(APlzq=pSO-QI}d zVpmz@HBU}X24cbM)4?|%?4xW8HVVUU*mcj~k@Zfn9x&s826A-3XHeemDKAFSW7Ye|!)^_=a+lJcJE z1@Rw-*a!bqNt)zxASTTsNG^oR_p(eTQsn{o+S3I7RK8d3?vZtOfT<;}kTX%3kj4n= zUQuI8oM(cxRYg4t^jI_IOqlhe3p>|`%A6ZJ02kc~_29Qlk@If`zg=EPcitB3_pK$3 zq0sTOhFm8>+zlF5?OZNZGI9KqsPW9aJ{QM59(M0)@77+}VWihYv6e4kiMNt9 z>MHz=Ko;>nCX7*#va!n#aQekMa9G=vZDJjF@@#kXy_C=G@&j5XcDcTjj0FTahCfec zXK(MWp662#FK>Ec_5tC%?OZ3bKu_+7t5(XrT@v>5Yy@39VOQ4G*GSnAJ!emHABKKG&DD-cZH#QGpF72$l>t8?e?Fw z7Dkv`Wkmw)2I}!;wZM9lN$#VQH+nxQKWB@C^ds6fraoV20O{UkkW2zRGig{RsI@KL zt0mSCE%^ATKYqG@lR<2M9v`2*+ofzqCeg;iHkpUQl1~_^h2? zy-UI%`{Oe@{`_i_*yYPRG?(KuuWJ;4eTb!epS1~&?RAr8e>SLj5;|VJ3%sMAQ$Lmy z=E2hme2(B<^zXv=UR-Tt5S#uTa?)0@RcnURmUX>I_ZsWy6k{@Jgg)K7*r;*iV(f5# zcGVi>F4lL@^=Vt!)m8KuTP*P!O)&Jt(cDb2sG ztVMv3<8)> zZ2JyC>=bbfWOY=paqs8T(Rsl2O|eFe2{*bgW@sBd2KM3d5v#rdn!D{x8h{T3B40*fLm30Eq* zW9{&a?KGJ<{6oU|`S2Y3n;tJDG^?*$ZGZFsHPxAn7pNnWOYjaDtk0P{mvkY*{`W%M zS{t1*7RT6M*qgiXQarrLRjcj5M)E_@UgEyr+TU&TKI@dA*cgq?MJ35k!gBy89i19+ zDaGUc2VE0&|Euug_?oX(N!R4>`I>l6wZ}7RdxDsK%kezye@+K3aW*9L05TrI0w;f2 z(RHCCfws96Wn9so_uz0?6kmFlCnAzp!mJ~$^&;OM-m6S5grwtrJECHZIatf2pljvf z7xSApzAgCq3n6D`+m&kK2Rg10HwER3Bl%3vr7QIU-lRyLxVBW(2Mx|6K3G1!snp8` z_mxJxeQ+MQtQ^jT>agt6(B6%<#(NLwdeMiz9Z3AI_WB0>fm#4sYx=Q5zAxH=`ip%# zQ-#phKuvwVt+_t>`NNGDjH$}E-%&p+BQ8JaTz}qP-0(TnpENGXW-LfcF|kF(?fkHD z{Yw6-v6l3fFt5cOUH@K+b6cr+vlA)yb;Ob#Ph!n;13tBVCmR%sI@UEW9yR&oPLEQ8%L_JS$UMHHARJ4%5^d>X##(zF zou~FQV?Fc!UDxo-(gbZ{tOU1lAl4i!u~M6@(t`BR*NkJZ1-`Szn~T|H#9g6HpeW|1 zFZ5A6uQkQ#a88Tyiv85Csjf9Ea1QrjHg){zjc%e7)VQx(GczsYI5lZt7`wJ+7*^QF zGikcUhWm{A>YKIcab0Cmm(n=BKb67Pqds=}lz+b$)m567^RiSsv=ZPd9ui)&Q$uLI zX){nU>r(dTo0fHTMMKvIw*%d$&-dv*-}hk-TCuT6ux<3} zpWivZeAHg*_e2SMe}Zik!RgI@p&J{A=}FhV^eTVvORRt zQ0;a9uC#90wMgan&L;F+Epr;dUV^^u3Ymn4YBDeEAL1jMGgnb0Pui%{g18IJawT|8 zYe`G9@wzFzj!<9H_4~E&uV<)Rb3E1^C-v>lh@0J0Gu+4v^=cPNkMpqQeG2?jnA_!C zeUnZv#w^{-VTX>}-@dixcuXC}2kBiH{637xm&{7os{?R1Rc0k5)RzQNSsmZwtd$4u zWB)FNKbPyA-dcBlPUCdRnCHVg!p?obJv)^NjKkWHUZE`*XM`LS=~I~tF!abcnR0$e zUpk$67jFR82Iq8YOj)J7j`9ar*}&`T{-T)WpVzVD%@{sc8Fck3!Y>hyyb{=d^mxD+ zt%5NGHSpkUCn(zU8(reKSwnb9g}A}>vF{ngO03X77^h_K5dMj487=IQjXZ0szphF9 zKXCr$bhpKLotH^@aU<>|3!dQ^IyOT+@Mk-^14aY6*`Eo=Aj7 zhZ*rzxW0VY$*MBF9Yl7zj&H&jj@Qzde9YxF`pemKs@rmW4a<&cl<8K$WUQl78_e5L zWq_Z!fUWUkT_x@Sy`njD*e}3aB8f*C^@9|T>E{vlftjd)f!5K}KHD=!+^n-kx6Hq# zn^u?HWGhH*j;Gl^^pDAyc2Fk@1 zQ&IW-I3OOEztp?{$kBzr9YIqc(3ncLv7| z8XuFzwX^>??vnaFCQaK&CSG5ca24Por`Xe)@(Fvk&v*EI1P-KSypAHRD=NHwM>dA*ZmP@kl96k$U9&Jy^ zzPd6)gX@>5H_avIO<22H!DixI>D=W-=jyCwECF!m<>H{v4z6t%Z){z>&BgIv5jXm} zTDX`KYwKM6JO*(mimM%t5zh9J^7Va?`14+GE)t3vBCbVo!_PNiF{e5I&b)l!kDO9{ zvW0HP?Lekb@31As^(EyZXnmQWcK(`qSNgE z43ZIRYnIG?kz$Q9w6?CTT`v{SpZJVyv)G(xn662~7_VZL)JtX_2;+i~)w^Xzj#AF+bXUcOiXC8Rt zr{D{!;S=c__|O}||M6$U`&k!PCsf-|5ndL07U>0!wXc;~DcB};CaL!6>FdgAXOZrE zDu^rFHrV&ut!)Trm=%aSFsFgjH756qm`OHY2j5oK0hF#kj2VUZ)1w#yYI> z6FX^RyPSZlY0k&ya$DWY3K*jm?U#t%ZUy2ag+QGFY)`6%5V^B6*p?B9hsa=qeK&$e zAln$_5r6MJYYnycvJ&@lkGef*+DWpPG}(@PzXwq!8XQ*tb-$4Dlz7iee^+FL10V>T_k}7grT=0r}Y5!<(c$SV#FY z^05`wh?qW(HmgO#cGo3yR(6yVl7_L7utCTsgKh}s0^bLDSCRP`ouF&3U|+m*Y$Jdl z^Prn#FZaHEu)g(qy&KA1NcDgi=5dbC)si5d6!!5H>0&-LYfy8ZqO{N0w>%FXjw^cm z(>;eKzHpU0|6soXJ`42)ct_1~7tVD_&UYdw+E70-FEP)5u|4lKU^uUfyzhkSRO?mD zJd7)ft9TtjA8+QG*Mp`y#dOFPvlZf%;?aJIr*$FQ&$qBL55x=C*;-S76Q6nQ_;#TE z#QKm8cnS>j5(JLRyj;wUT?|ckQHMI>`in_;D}$q4`6@i)y8cdHfV+uy**;&O|Jn)YrWTRkW1i=!jH*J8wu_w;@XG3dX>MLxyk9f zHGfA+wS*`AEy$J&?cH_iYu&?mQ%UBfII^p9JTqZO2WeBC>M60E-ck9cs$Fn*H^-QWJLa3B@gxw)_t;XYx{?>G}#}U%lDt{TQSeCD(2vN zfNf@NCl$X#NAc=r+QprErFNAW*35NMW8Kh%5s^Ipc%4{J6y~b6g75=TiN2TysHp-s zaFOr!MwaWBR?kgNaW6Zo?H|)sBZ|4y#%Yg5GHrg?fvyGuHk%p3Z?*aA4BI5I`_6Cv z%Lcy3{LGdG;55UHL>`vmVHjkh_*>;amW2n>)n`Q)ErxmO*M)z z7Nnkb$R&gn6HlPyO|fC-fC1mUak_iD3f-I|O%`ZQ7ykKiEXGgCxG&bLjIajc9f&ht zQqC)z$H0#gPJ{T0ehJD!@VMjeHGOaW_tt-J9H+SZzWUiN2fYjnZr?EO-U-`Okgn`R z>cq%egtQ0bjPnqlx4X(^WmDu!z@0$$*6)_jRoKtr*HZgTxxT&@^+&H0gW&HMTa#PXqnCpShgS~nG7yB18fMyL@&6*HN_t9b%&%oP$-9R^{7GjC(j*rsunQ{3!^u#E7@IS)$hA{$;Cgww!7 zA2`j>aX;^%@g%nW_;&VRG{f`A^qu>f*1eo?e2-Hp;nOgF{ETdi%IN@dTmW;VQf&9$ zAik*6g`#}-ifuEu=hTclwQTF@L(WkuJO}L=&|JL0^UxYYwZ1+l&A4gurQkE?WN#9d zNX360$2mJOTZIGoIO<~XN7yCdh9Z6+jE7!>-q`H_;tl=({}=vZzB)72YIGYp$ViHdqWjftTzeYuxqeK(F%IFq_f23MmRdXeEy5a1eF6=X+Qi(RoO8dRHDB9-V9r#zV%+Ia zacuc?pqXsr2!?9zzguZOB8{w;9#Dw4~t#{0jM* zE~g(IVMfHP#@~dm-Okv@`S^hW$Z4KR?(d1uo#VPILG9(VTv?~cUSn+mzR_}Aqn{Hk z;yQ-fqw~H!?rpRJZbs&KHrA(0I8LMPj@Ma-2NaUVU(8&C%p*l(Md3XvX=ej!liACb z*RMT%go-eTdK@5!kT~Ar2y>-Bz9w#Cv|WOj)Gz9gcX>@sm>TIksZ)eSSxHmdQ?J-}jR1_JT!?@moel zOomi1&OW#1@g%sG(mMQy;{N3N3E*`~e)fkqc}eZecpSof5I#l^=zUk=FYri6&Kq*P z1DcbM_lLIp!||oR+mdl05w$1deCYfGCWN$-xVDGms?a=Wlsw>!5trw6^6?s}iW8j< zj^feCLqgZctfT^7#K*vvhq2Qn_d>_-!eOmk?1SQo$a~Sday_P+K?heSnUX#BC$bZ~ zqb8p#j87RGMR8T=O*0mVVly$d$vce?vQ;gQN5;I1SH}F-YrHZLvz_Od&17q-PjeQYZ zj|C2uH{?AIa~`&X#CTypk8~a-*&y_HDu=b^yb5x=Z9utQit%DA-hf(!^qs+5IT3X> zK}|E|T!6iJD_i&y}G#EZc|ozHMAz z+;fdOa&-s$FvgfaA^f|&hyBLbRBA7@3)b_A1l(EV4$IWwK0ob-;J{~$Ttun@Sks(|zFwcQafEo{r13EP&J8+mMZAP@922Q;91P8+`=Ke@Gex;x}sR)=Fc zi+CXU@%E_^i=5*p@UKHDhWe)DwWrN#9hb+)Rb0c!nooVsp;2w?)_ts7X02--+sXP? z?tL8r*N1uS$J}c++0@q=FlRdBRtdk9yZj;72MN*z=NkX~eb}OZtmD?pr8s-*YbwEA zrf;$z?ZWXUdUrc$UEE!&LNq!=yE-l1Ic&Mw8qU`SSerRdnXh)pe?jvX{Z{I6CUt6| z-L{To_$_jE2Rpd8uLzGANo0e`X8BVk)E6`#rt;Uw0@umd0o`Kg0rcReQkVp|al1lIlu+uaXteMeny-rIJJJ8)~fp!oR&c4B}0xzH}( zy=6P|VdIaDIsPl92#&`!YY1apo=|>V3(n!|-i~Bn2D!H%=S8f?F_J3LgoVafmbofu zjP)1?iq8sX1Acg0@ag4Lax8O6c|F-I=FI1TJ`~>1qgo#DyR$tas$SFBw;3Jd#+l@O zl49c}+l8W8%rSqQrk~7v4XyA(1ZPKx=<({o2&awaTx(;Vc z^I6gyYn=UxdCmF!_wX-_-SA1<_ z2P2!ix#_Sf#&Zx?jw>dyPZjivFph)8dLtz3tCO$CaeGbqCBg_aey#)mx0GKZ1Ad!g zW(8xo?MWN;Yl53==!*@;UX5Iq#~ENF(-bY zL%${pUMB?SnbQyWQbMY!sNsN-e|sD+Ab+6u+xI%^NgE8v@7uv=5Ho z-Q~Gw{9W*~J;2Y%?M6Q4-Em&Wt+N<=FRdocsivYn;5A<_=9GKuc38*s(fF%G5KF>3 zqaJV{0JfxA&%E(DH0UmI4sAcWb=(W!w{iT@%vZ-8B$R_zwiqRzAAm7#o^PV`$A?G9 z$1WyloJN?#rb>BX25}#wCQPAWuIZxJAcEiC^Sl~Cyv)5e%YPgnQI5GJzMOZ@_XA&m z^h58WWC0EV@R`0kZfP-+%ea%<(I%NSI&&JJq;Ez!^1C#SnY$u%9O}`}clKQ7{62*Z zq<yTx@iQkIa+3W2Vxr%j6 z<2CK9b@gT)`Vbgn;9)S%o}sBu91FxLRqAKLze$z#7`CUN*M}63dL-3fIPelV)v5Ga z42yg_B0M?su~(!^X#@QOlTE+p{&)MIzb`LDUUU5W9J%qIc*A>ZSIiyKke>8>R&!mg z5qZkC)z7{$-96e9H9PD}(A+@$eCJ{z;LzYYzmRdP%KeUd5cnkSef8_l{VLwKyzhiZ z`=D=|-+$$su|G@TA;E3{9Qc3Y#tA3#7nTs*lRxg8j9l#W1Z&4%_w6y1#%7F@^q8m) zH4ujCJ@R_gF~`R}@jw07{!VqF=QNMGM#ROM*zj{6G&O>jkJb( zKKFID7f!o-i#00)&dz*~2ggww~oz6t5clnB* z;T`yOJAKlyBWQfDl<~19vMX8Nt5S8|+Q$KNzK~9xvj?H$zR#w>Jt8KYN^m6FsSzdi z(lk{;rDTYl!(J4l1G_xRhQ z9uD!9T_NZt_ydPj?*I1H)e9Jb(ARTL*qX zDKoacdVWCc&ET-o%#pIY^_)PZep{CsoAxYJ^}N4#(@SZ?;s!V!|U`c46#$YZ@VTL;8;ER@B>Wou4_~qaXDv@AKPW zxeX7TJCgB7y`IRDba&xvN$K=riHj^H?ye`)tp|GJwE3XLx_MrVll7(^jPIcN0sbt5 zvTe+}^zht~+HAw->MGN$`5H;88(HDKjpTDYCd_(Xl`mppqg?2MbYx6C{hGhp-Qw)| zYI^7N!!(q2NZ;_;*5J*6*3)(&Z1meszLzr4XQa0dO}gf$Zqx8%)8?!%dJAc--qJz_H!+n!x(+J6<|EeT%7fJOMMpoZEwg2XxnFqu&e(_;@D=l)+nU+oq7GvR~P1P7Vb$LOU zi&&~p$N$p6M#5V0DJJ%#GDGNs1~;Ga`ZDmkpc-=#$C5777+P(MYI1hHou8ZkdiHN_ z&-Jj|oX=nD6p@TSSRb}+s=yIPJbQ@O{A!H`S^*Zd<+vX{7qRerEy6J}O@Jgf|;h~}H zrI1T)HlnsGu6@Qaq{|3j4(FG%+9bqf!+9j)%ThX-i8!cKK|BCMTby!!{^d=cA!i~8 zuaKcX*1t6C0&<;70DqpxTv)xONi72!bHo2ntilb}v9N|CVL~ZNDWHogh1Ey@E4#VX zVw-7T7us#6+Sa0O+S+_aIgLlIvts=tis?!Da?1Qzq;+yH<-_SaG)tFShx3Q+3S)kp z$kj5gs%iMI#^1MfeSZ@uyU3ibEc|j4(su>>$)tNwS^HsAX=r>e=<_#^oz&X&bVfO9 z{=RLwPk_5a%@%V3_vceh`{7ywpVis67!0giC&>qYmg419rjqN|X>Ew3V5VgA&)R_c zhNE^-G1`UlWs$qThR%Tu7PaW8{$z*T8QGx35y@?!f+XYkIo`tnhi~$|iTrVB3vR2H z>#+Ai&N{Ud)y`ih<$EnS*1iYUM(sr7uj_fy1jpuX0_KCz^gHn-e^@iLyAS;})^2ZT zZyC4Z-z}&Wu<|wcIdYq(f-b~L%9p^8krdcV^ot$}Wf#DePWZi>Bo|Jn4oJ z5@sX+pm$w59={yt>WXl0#1ngbEq!z?{r9z!zpo`bf31o8e7x?qBlo`aZZ?1ZAfB^Y z7+ycxq2sRwj;t1C@-1T8SNBF#c1wJIiKN*2;k%4<9CFo)=I2XnJJ_xS##jrLz{ zV~9(E_*j;_j;*Lx5?l+i^VlQQwIUu_nd9rn)^@uY^+zPtLnov7^y9}p8y(Fb2>;5* zobfU6yN=!`w)T08TG3ez%zm6RqgzCN+%Xj&~V*>Tb5zk}7(SbvnuyEkXfv*```*!x@*$T%C(!@eM z5^naxRExj+)cAc(aQ&t~7hL_xKXa}kY&Pmhh#QLajy3ZZ_1Cj=)Zw8`W;O9-eeidU ze-@`_A*eqk;R{!Ey+yZONv_RLW;O8CQ>iIlw z@9BT18jGA`B&?;>bzX0P-?1TF&1^;QIdnM!V3U=@Bj7nZe_yXvcs#BM+rZ~joeBBS zu1%%mWBGZGIXY+eV;`aU{$qYmd9Ltv4r|Gx>h}i9?UNk??Z@;Z6;hs7f^8DyNnu;S z2Y%T$f;F)ze(_<=ns~_fR{XRxwpECl#EfPs8?os(lUgeTQ0pwA1dF zO>CZ7V_l6ceI4h}wuR475x$jt zCWe}yNkpY1AeEVWR0j?eKJ2vN%ev7-+uZEQuCn^87o~SAn#L<5uWQzPf^k)@uMxt(Rw6&8P0bVB7Jzx!1zNXVh zWvzkOX_^qGqp(THMj-81p<-QgM#p_B2dP%&=PakU;=zEMM72H(6-yhc9=J)InN3ix? z46noZe)n$-g}Id7eqPI5ZQyrKAA;H>)3@p4Qq9k+YqO>}-I%oH3G;$@3+YN=|2=$0 zJcslRrF`BsiM?A`vC{F8CPDi-iA8qv)aJj%<0Zz- zlPL8c>vYK(b7xbVg9A)7ve8eN1F5)_201D4=(Ms+(*QeR2^k0&SMiOw@5$NzvT3 zI~mbhk!RL&EZFeAAu1`j_7D09<(6yzKsC8>y!|(!sFGh{DL5ZW>zL(S5!dC4LtQR% z(jrPj$4gJzPC8N8XR}~15;{h{&LU?=YwMFh?Guivh}WC|$X-9p$=No1RGPNms$=M+vtv zLtp$a?>S~JGvumwGHl!$)-L7n>`g8b-5`gOMi_7Q5`B6Dn?gQIUoSwl!>@z&-CjG) z=g4Wp62Cn4wbzVeUUSkntsMRh913HK%fkm)iF+f`@q*^nNPg`07owbY^m+LnK*w(Z zj@SH6vaf4ckCOBRmb`BvpF_IeLZoQ}-^A)J9Eu{J;rX*7LmSy|5y_`69Enojay_w> znzR<858g9`KaV(Gv1ZMhs9hA+n6_#*G`21BM-A;I=m(V(k86oFKf%6H+|bxhprxGG z_-#VGuyib)yQca-3vJ5gX+Iis&I8<2w2z{8I^ud8;WP#&_7US=%H>Z@u55UGoPj+d zQr0Re`&^%^;pVzFpZAl^mhltZr|X=x>Ll8f_bac-VEr-B=y7<&(|FNysp=WWe>Jp$ zLuf`LPN{Xkx|?E}LjOvf=Q2ipZ71fYt>Bj>AEl{Q%}re03b7)sa$M(T#~k#!lC$7k zbfS`8XEmIVHntIyGqFM}NH@SjrQyK&5*D?Y7#~AZ={{$~TB6)W7oqOnXm zXesOp#Deq%G`UAYzR6W5?5H*heJ%GEW33qnTBhN~VW8~;o};0Pr^lhV|F=(9W8n`<#ge+Hj*2 zBkY=L?lGpo4^Fz|;2UhMF3inI4qxTtIq}U?f9WquY!kBf~c-BVKSS0#7T8(o@$Pv?T(SklxEgi2_(Ggb?wLuzN z#?+O}^F}u4+4g9yi6pf8#A7P2fBjyHfHY!QJE~@0nMGmZka!n!+IN|6bVqZTav~kH z@ZjTS33FX#2aS*7=d+8WX9u3P*TXAF|0n}ZJ?rG9F6pj;5_ge)>=lXcYGLz7O#b(WcGQA@8=tCKhN z#o9?~pFNz|!79{=RqzYO!PwYf4X#?^0<1;EIw`|zA*?XfrV7Ww8g<0sQ?Nd{7q$8d zpg)bdAXmgDf#Wxo>fkG;?}X>0IbfVtvKgwq;X2F`npq{)z?pVQdNGpMNQX0lzOZ}% zMictQlCX=Ilg$YJBXBNG%L_mwqXHC=LqQdoouhP^$roBfDz}_k7tO@%Ff#4{> zdKh6GDqdS;D!29lb|UZ;wzN~kKHBYCflF7)7vg4$HVYxflH!EDp-%8B64sC!j@^@R%bKYPdouK`qQz>kl5C-;a zvQE|L#q9Gm-Wx^pY9$T0stA7`=fI?a*STUHh{d`>OsU*K?~*ZBm03TPv8a?Bl7<89 zR@W~lupjohl=``I*cn^o@}8bq(3m6495{zaZ;#p<8XMaYt#LH&rkzX%_5m>pd@tpT z+GiEU>!Qep;FX3Qw&<~`&{AdXX?!O8SCG~`YPN>p%j8(I^Rd8D(N@iCtNZ>g3hLJw zec^F&Qst@lt6ISrv%|Wu>`aR|oWvUEHMeV;uVmAoCX2_2ufuu)r_Fn=b*pE&yiz)#l8NR0Gci%;-$gN2gy|LDP||^a(l2hvzs1+04se^RtMB(AlPaO7*^%n__T zPkN>+XXjAefh-wo_-l3%+S$uJBAIsfD&4=g^zRaOs+g%O`z-S76Fr=g}U= zhNun08Z1jY&Nq>f6>+wR0{3zJ?FHFfRRpY!oY+VihZARe*m09nohvkCHS*aHZ?5*i z#fEDwz1FfQ#DkV4Yd{n>G;%_m<>6jDq?-7?$86&WyP&!!)XSW9^d9A8E%t_VBB_Su z)#sxqrce5@qSRH+ILtli#J{@Qpqlh0xz6P^rI-TZ35dryt@E|m>%`TohHUeTN}f@C ztyblY0Isz%H#vfn_}r$SL^&d)xXEq)cMS$G0RvZO(@gr9HrH>~mQCqwE^VJ` z4Sk-NuSGuMm$8(a)|`V|eh}`l-C~57d7oGFepN*^K)L6HUJwlG#Xw=b{)^>sG zznZywY5cEp!J40)%GZl!OwNxbNPEt zKjP{sX#L7@Z5#_OKC4-;DJS2qdMc4?z2h2+H(80iWBZ(QpkyOb48v)rGd?RUaB zz$H6O8FR>qinTPwY8(=WMt((HRZ=Qbb*urbMpvPA{i8(Y&$%P6IcSFvH!f?iqLvgn zRGrl!acfrKeKMr4-UL{OS?9XZub5vF&-7}Bto6-Wm^UT)!n|+LxHS}eP)#gMqDQ0^ zk61yqlQ-}qs$JjD^zO7L&^yUj^(#c#%c-JfPmHagsPmw|Y%GIAPscmcl zJ+|csal=Wcy&Gu78pjcj<3@A7G-)FvGv-Fq^!E^bgL~Y(`gsKm`*mjm#65bQB-rmK z7QRxuXts#4mDTs#!^xCGtOu!GI`h_3o0k=MZ^)*q_=`gF7@ujRmVHuCfb5l4S=A^IDf1q`+QsAq` zSacdAtoeb2!Lv-c_T$#$T6tb0mLg9n=2(c*oHcH2BesP#ZA!Ktb6tU(@yBzd_K(-P z(}XM1NmdIHC?j(khbL_`@;sQN35IL0fF$BIk{N@zbhY+#0g6NAmr8Q-WVWb@**-L&QE_ zb8tar|BtdSYf}_v8vQ|iA#UAzSy|W=G$0_{3A8~`u^Zc{zy3TGv}fi$-+Pwnhrxsp zl1imgsno)um5hLA4V|5ZdSkZsX}n*DkO^`A0}D||8rg48dqa!c)i>(zep;9Lb8Xi2 zh3K=eLRwLT<+m7D-MVwFABA>f#Nf1RYlLetykrHPpGmjFp<18&xE~saG#{{|wcW!w zU$mRcGdyQ@Do^`Efg#cG2aGd{`va*E4l~s2C{A3<#2hlh`BvG;J4kI8>2x%&k*wp> zS1+47vIC4muVd~${a9AEmUkLj_Rzs0LpsvM5kmP*(rUkpPyP|*=@skjxO|M)gmkle zugD!~_}yMWynN+LsCA5C+SwPlnl|q`+U)6eR?_7BmlUnACb~YVdk-^_^g>L*iJ0=Iu93l&x z6Y|A>Y%4px6m4&=ed1_X2W_SCJb1<*jVzcyeM^uKW4J{+uk-sIb@ga%V{@)!hIM`> zBtzUicCo{Ug4mYQF(mXHqN=TU2zX8;dC*obU!7YmyAtdrzad=X4R>Jt<-ka2FZpmY zwd_yt37#>0Q)LaJ}wu z8TVj!Z7+>y`cKE9@-e#a9Cn z4c;+~5Cx1iL$%+^%IwZRw44MTo$B?E?Ot)A(Pvyo>m73Wg@yAjjgmjp3<@E=TDzT=--!VKb6q`*1p|Bn1?r%F-IsvH4!I~ZaU;&Xsv z1%jOu2AwVj#!=kyq1(ljthp#p0%O^sZ`ZuoIfW3OG|^uvMS2R7qiw9zwC?-q&ok8g z6rSOQPzE9HPtN!|bBHIclX)-J?!D8A;^;eWrG3@yxbF~!aUy5V(`Sj^TX!*IcxQKM z{>n;U`2QO37w+^v6=kpUs(W`{)s1PlPTS#=cAuOl?YGAt;Qs0~X&GQgV@v&A^wq5A zO7u$~sPQ_t`Q`caxAz+Me{`!HV&1ha$lY6p>!+`8(${_n>^i$S7$3Eh0o?Fx1#xIm zr?~%fpFRi{-5hOpc+A;-?_zblJ;nmmx~DNx)-mEQ(h)UvabB1hLvbMxz6t7LX!$~g zXNIDyALlbM@2@rS>DM+zywSGmq|&z1)=LLQpCxG<(6qxX^bJCSPFLAnT6fO7m|A$^ zA4wkRxE4HIyU72bzgGS$a}R;96wXEdl1a@vzc_tM!=dAIt7q)4`AgoQbzeFfsr46h z%#KbcTI;B9dTRF6OXJ$N++FK&pzg*_>x57cJCAS*%A8hi4N6^o=#>dwlAt3k8 zb}^vClESgrE{5}Y1>IR67e7PinqN|boYeb7a*-cJz;HgC@#`5 z9a7AlpqQhqmi?uR!b!cSI@TK0wbsE1VrQscdWoGr5T1LDjqPM@meT96ewK{q z7W%;H$4_0wAjb14jLH6rq3!fzlo@w+pZa&8?Je=UV&_wLrq5PuIyQyQX|EK-jr=1>Ds@socQHRZ?=%-N}@r=~Lvh;>!nJ#PLZ*kIc6n&nm(~bB% z<=O`N1z#%8SZ1SjOK^O}6w?RvdHIeWvU%r2WjuMFE1}UGpF920ue_Ykb$s-vKk(N) z&}%kvjHo+zH(zb%wOi3z`vr+OacOFDd$K1w<{DcQL+{Tk64~)kl*B`wUhU%>eYtC& z^854|AG5O|=hRW!{|nZM_BK0hw@>INXnh?*21;9=YMC*oF&*l2Zb#T!XNP=a8RQvG zitq6pe6tfm6#Kl>n?|2fCV88U*h_Z}VNL?la}=KYS)W?p_=atsO$M`s)y*(_={+K@ z@rSc+09*T$9&YdL{q&#!ZpefXhZB% z^a-YADvA(-Ys$T5z-Nu&rvk6(S# zo=|dWak;VGL$)_|j(XYZwZcZ+3fKvv`ElqSzsFx{E<`G9z2`>8*d+I94m;Ho~+1V@KNDtp>z3cI&TtX_12d}e@=f3Em&z`r2 zJsU$wc%bJ)H<$i%E@Rv`oCD%Q$j-;u;2=b!$7}PzJ)Iv0zjCENz9R785sNyc)H*Pz zBmX?x5f|ZTx;vvjb>4BVN4j2I=gymg27>6b5c<|G8^K+ygY??>I={ zD0Z8WnXq#Z&J0p~595-WBUsmTD=iA5nt&(>0ec35pJCmQQ1T@zcb)}bgG{5B^(^59 zS!m@_?&m67z@a5$5U#7vNBC46c8ac~Z^PLjpg4Eorw@`dI7{MGBZ|tJAT|=)!bRZ0idxZ039K4Q z+{QHJC0JGYfRGPK)NBTy5g~HKLAVOi3C5-RajJ$S;*mhm2sCA|#Doyxn9y%2D02gu zARxuep{WZ2Z0T*}V3ba}E0zl8;2BhW3qJJK%m?Z3K{TXLsbi{|W@=V~5HrFW9!sYI z#fc}JDd2+M)c{)Wm0*r(1MgrHTrhrq)?%7m%Lwq&}Y z!^Q?t_|P~M9>QG&oPy#$D1M!990n^OC+U%~iioXdM-&x629$;=s+ygM;n;~-;fdZB z&IU%RaJLY(WNr{LFi@BMjWD1qB{&F!fbdgtY{?gH8ijk;n@C|cux*GrsF@9Y4^oGa zWlPXyE{t0Ov2r5i5fU4-zT#x9qAzG76Y9pV1TUGe6@~T0l=F`gW+n)eP$B4933gTv zzbS|OWHrHgG9n)eM8n`iFj5su9#4(sG9`3Z&?Q97l#XpnF*PHHLEez~t+61eiLH1B z!Gu`Y|5ti-2f_;ONlBRGwo(T9Rvzi8hzw;)ACMAI<`fFfpc&CQ1T}*RWr{B$jMk0d zBU>0Pf!YQ+vX0Wui1Gr&*MZ~~13{Qld;xMscG9t>;}LKcG~A{j>A+%4FLzN!u2Q_6?Cp~8>1m`vVe3(6({p55|BiWX7nWI4weZkc-z{+)PLxL=ZV1T2 zqZanHo)e>{mg?rUuSSFjPKjuV3pL3kYA0|MU}PW#(>jjAp#*7F;gAOG66E4elvhGE zqPBE#M_{AYJ5@EAi@1+|H%jSokToH4i8PVIsv*$PTmn*BR64|?BgzOaE*#r{S3?EH z&qg?Lwg4>aVV~boP2dO!cS8p{BnXc-CBkVr2^!NA5poDsuPWGHaFSB`MIiWw%jz39 z=NMNdf|<~CQV3!p4ay1vRTDD7kCfE&x%7}b;~xjg)f`6gN zb27S>c%J~kf3h|PSGK{RE`T`2G}Nq zpWehs2c2TgW`Jigl2Dv8_mK}`-mM#ole@sRC?ya(3CKdPr=K!qSg*#1NMd^llr2Sk z_aVadiI~ccX92g^q{RQAW$+$&yeB!GC_SDw$cPN2XXoN`@Vx?JA5qT)kaq0S zd9w#;&?}BR)|J*AD)dDz1*0vYx^D)dD7BIirNB)HB0^LLH(kFF)W&%9dR_GhtPExW zUqIPfu=fZ7>x=xZo987QQktpg8{!d(Wvw8T&h=9eczk9w7%;L4)n+FwzX-Qj%OjMie8@)%^x_VQO*(qgCQS7(C~5;K&UZDGddY zP2woN0ujbgDx}+l^z1E&Xin5AS%kGr*UPCuT7%=f@o;@Aan3P`MyCrd%)&KC^%TdE ziH4Yfb6nFG*HoL0)x);W-+IbJJsezLeBkz;%9c+6U;>1^V|*8dz89p02*#wEQAknZ zNRC?X4Cw*xHnfirn}Tv&DFJolsgeXx)(uji9>b3=k2|V=%R5-UfEm4!00q5@XwRr>mpwJdc)V2e-MtCxsbvqi9Z=a??#b-uL-7IJI{zqVeg!81l2Y>yL&`mo z-e!WgsW*X91EDkvE2uN;R+pB%ZJ67518Hnn-1x`po?C}&ZU=Q~RYq}&Tl52zS%-UO z9R~T)9Hd9{ktOamvk%97=w3EfTxC{ecx3C~SRBnu zw)PLDrTcm=t@x53r>}f$$Ei3@`-SDU`N01!*73EpV(iC0T@z!IOn-2^uF9FO0s$sK z1Vm6%!5SSD&V^$TF6gJ#SH&ZN)Bi<=ABJd?JM8H^aPjZK_n%EG` zAeQ_SIFM6KCdPk?EI0D0en0NJ2g&nzWCXD59AB{(==iU7R-fPmdMe(#$T*o6-i z7+n+x_Z#Qk`vlA1fWyp-2*8I80-8H;U~NNy?&l~=97-<9l4JUg?@uL%*|i`*A0vnq z>W#y^^C$F<(F_*K0k${r1ndnhG=*@0)gA?wp@eS~2nQB*N;w23D3}!Babl+oVBEuW zB|TU+k`Ycl6hH5!M*|o23+Wzi07`nm+6e=m3sA%{ga_dzV!$5>D6$xU*ODbLFxd?h z38&yeyo?x_Ir`gOya^AIWy1hIrl7s3O0^c!12qpfwWbnAa9BSZ0guR?z=z% zJ3|rM;naq}05WPw)_#J$k@hz-S(C*lkz0C_jjhI`1*SQstISrn_YJ1!ato*3yRF>G zwVJ@Tm0QxV)K>0jP)(@(!RPxgTg~_fnLx6XTWIokTg@DI$6>c?Dsa@dBk020aa2*M z?DLE{0v4B@xE}!8^aI1O_bd%kcLoA~O_x3Xf`kCJqawaXz+&h*p zLj~+KYT+w{xhMGhU2(E>T7WT}50cASY7ja*Ss?D`q2!;Nf)jgif?4)w1+?GR3FhJbtmvS9FW_e$o@`k0 zvm)VbQ@~HVIl=s4V}1Ac0G2TXxwh-9r1g2R86A}#h9wPtd z3KJ$FFe|1J7~e31bg2mB`w2AG=ysFrEGGLcE?OQ2y5%Tec_;`_VCN;)9GFw>Y!Z&d zp&AXCTYN6zp4zqJ9fPsM+~#v7@1OQTI1!nq+;p}nsUmxz(zu$AEC;p~nuLu;k*wZQ z)A6=V6>|GsMOE-NFr9R(NNC%WCfbo+WIFYBScNnDO-8$0?`}G3+asZGt2EwM6Je&4 ztyLw$zKggHCO>B8Y!@V1*@hDz$ka2lXd72aVh*9kF@S1LyMoFI$yz~>QiTQ;6=kvqz63!PqJ+Q8>!gy{s+1AM=%F`Z*t z^IjRsA#JDEn~?3b*MqSA0x(NV&u9a%8uoh1G_ibu^{=r~e#Eq^zpvZd!?b3+KId59 z3E!Wf4~)-mOwTZFEPFjDR+t7%zv1&(zrV!yJ^YzK0bq-R0@D6$dyp?rJ!MVCy$QMM z^zhVEHpldEvF$;zZ~;u1E+^!M?ceUP{t@ze7oEQDd&>I4@15}b8SC|wrN1xn`DVF8 zpT@)9g#283JbK9?K1@$R?MyF2CNKKm^0v$XhnD~3xf zvwDoyUOl?^fR6GzJibrW)v*^ppVmaS@8eN^XIf3jDUHi^mea9|O zw{P0$`UaKG+swN>UEiSY@^t&AXIgD-kChcaKb@Oh#40G#Pm(^Ea;g=;Rj|A42bPl5~o)8R;vCh%9jNz&*8tpSKFu=ls>w`W*`%i!_V zyMcJWP6UTqP*DpS00R{fA|gQoAm&Y%UofnTuxGuE$l*t+wH@;wRzXag7BNS;>u&7ytR2NUKhfRyyG}*?c21c__X)^PQaU+ z+mT6x$9lboF@<(cd)wi(w=$;7=SA3*V{C?7npn4%!L6`4fz%>AFmEz8gJuKD^BCa) zC&1taf~q#PNSZ*`jyY8xW6uO$8eS-aaRjHMC?FzYs4F)lNoe4$Od=wacq@KezT;RCVZXmsB4T8eBm6A| zY^p{Jo2bOxft=l2pNV#E-P*#YAk8YRoNn$v=MsP6T&RC{7z9sj0t-N2SjMcRD zdH+dQf9uov)T|#nk(SCtUQp_}p6n zVS(Y=!f@@dKAQ_r1vSd9n$?sn4U>2bhBH>OrQuS6SM5_#yWM5D?C*3~mouRV^P=Jw zJWSh*N+yib_B2Jn%TV+C(v(52HHM5?hZ;6+Fn?U2H})>+*4vV#d=JS5#|w91d7;!y4itIc!3d{F8X!gJ`0}T zh;ewLm<6?K>ieEBgl~YbLK0Z}e8F87)BzQTn2FkqMIA6vdslJrEn!4T7y%6!!S~I; zFzH;kVQdCG;G#}{0v=#JrXP-e0y^gN`oi(qd^h@v0@lL z`c|;_%7BZ99R++Di78(AY{8<@f{RhW;(7OmOR=u*JK|@)ulRxo_Ph?f`EK;{x&l77 z13sAqkr)JYG6?9D;HT|X;Du4GX7{XE9}EmwHd?S)FC+e=82ZM+4Ws9^iu(R4GJGcb zZWw)eOn%RIqrU$bQ*R~5{-ZE(m03O}z1h9}UPYI6Z1mSLuhM{-e8EOakco9JyS{$&#tbl8%P{BOUmUk_6b#M;XVf(VO689vb-F=lEj#9utY| zm%p33!G5AyvAL1<0*;?(4sKLA!QI=h<9@l00v`4KU=jPPXmto8?!7JdqwcDan~>A6 z#`n%M4byP+GvCV*;!0SbA&SO}RXtqX0F1E;&-nMJQB+LES?}nhS$3xUOzyF?B z&-wnFcAoQGs=&ysz$k97xxU=PRnPVR2fE?$0_Uae;XE>mUnXYp=-P-r0k_5K#Yka!EayJU|8+e~$BQJwzzOQi z37MvGH!mX8TNzXQ{ReK(`wMovsWms!YjB_1K@{78ri+?3lGmL2|A7B3hywl({KLur zGyLa9q1!Qk!eIVt%VYAK-{b#6WBotv+7k!IAbb#e-dziiPLxL{SC4TO>`nbVSi$u# z+Wc3)eqls~;i!<|Shgyp6BXPiYQ^B{F}ThjaPxTj9P6~hjelX>wehcZ{_k{ur0KqH zpQig7cTA7sai>XMYoFkFT#viQX?N$)TN-#LurvrPA5(n?Zch$M%(>9AF?8BTK>fuR zaH~8bf8U*3QXlDo zO`(}lXt`eVwZXm@!aK6jG9wNEQqI8k~JqGsh%aSll> zt+2Rzd*}DEf`b!sc}@)ZCXBkbFsg-1D{Ij|&%*s-Cic!GG=fi2^AG1<>^Y2xgD|MvXW7Vge>miq%+J}!%J7g$06JQLB`TddSXL=_GBs1_@E z^lr^;VbGu2i`9XI z%rNZW#>0Agm=A-kZ%&N$BiOF{)93X{<6Rg!Z+O}IRMXd2xjM7lozH?@x);XUm~Qb} zJ?luKDhti2)0HjPSl3_Qan?rV=y&>mu0=Rei`8Kf8W$&It`jn6RGi$;kXMdg)9Dy@ z`}*CG%Y3#<-#T6+I97(f^akJO`22a1{-59fam8lvU!R2*k=}oM_P<}q@95uxlO#T5 zud76!LziLRBQ&ctG0h+y_^4gTF2dj#$ zqO2B?3CmUUvs@9&k6`cZCsnea^u?-B^LtDdF-(>Zcd_h?H@~0dVVzlvsPqCW_63jG zlAUeOh>kNJeZ~99bh-DgK8Lq>uX?_bxvR+Jff39X1A=4Vhelw9@stNl+})LPau~n6 zcizs-ig>H^F<*H{!Q9!LITsQ6&XQeh`w=*cIGzjE=VE|7gZ%Iwt>Ny~$R=uRo9W1Z zsLAZ%?H7zVK67phrrwv2^szL&+*`Hxuy*;P7VrL}q<##2Z&lp#V-TXkN9ythq z6%G8Ib9PqICD^r>*-CXh`TybapCZuzer0p<7|+Fi9Ie8`G8_b`F%gKUeG_%C2o8P_ zKI*==g2sJ#hP_Ywi@kUDSZlZs+4yYq5Vg3wk7B&olQ>}Qc=<4~Mdu zmn&m}ZgW?U$%p@N4EF&K?^Zuhw(fBOt=oD--OUGnTW~dK2g=G%WK#q>Gk7J0jZ&?Q9hUon9xJ zU+8HWvj?xb-&O&WX3SdvPu`}9ve;J$_!}I$mo|}5V zG8={pZGhWZ&*w_>6|)}dc=v|mzjzH~{!kl^0W`h|;8B!qUGa>Ty@3?alkBZ0!DJ$x zqixCCoO3#nZcnY=G<=YM*{*t8X0x1h9Y&cQ)*(5elD#3n)ay;)b*9@>om~i%a!FL< zG11Hz>iUXiMrC7D%!7K)ps}csGa5K1g^5FyvTc1HQXY%nz zh4QG>zWaP84UeH8KOtx2CQK^ph=R0;NM{rxhsemLBAt_}_8BPLI?uVTM=h8z=2R%3 z-B2O0_IQANXt6+9Grre-zrcZ|=mwXFlo73$>ev+Bb9Cn{oWQ)Nc|(0h;V^x6@x+(j z)u39Bc-ea(PpkRb=eb0utNOwnjyU_oCyg7Vr`9+={2%#YH>OWnn%&cS&q}lJ^d&1L zz+d=GdwMRsWT^I_%f|8gBS-9M-a5i^uQ3FDRv)DKx+-xr zuJuNsb&nOoNb7a8&HmPCy#CTouxH$fH0Un|Xx|c`0Zo39wIRJJGH#wJZLW5LKH>Od(B%25fw0ZV9 z^wEE@FJOT7xn&9yye|Nz`tAU~gM@_ub4LL_Q*hBo!qS5|>WOS4=;M7kf&rF8`ao?- z1t&E%f%Z9>Qd2q`MJV+p%q4Ypo`kugEyeqY-l;&cMj4F&RhYTHJJi&7k6QXJXc0yd zyofdw?*(mlc(3VYhtFI36XIRbtA1`!rQe%Sb&t?ZA-!WcpVJSWb|?u`0NJH?QGPD~{0Vhv0k8l%-W3u)Ih}@E35%A>dyW04m#_v{M)duTceJ@X11t+lP-kV? zP_n~&OP6=NE4tQcgO>XFh;G9M;YF+PTVkZv1E!&7-*>#X>=J%S0E68ypLpz!`6OcC zhlExIi!UoeEyYe3QNi3}%|#HHN9FL8e&n_yX;qD&bYu$bKI4LlooXO$ zlnu+f2a=Vx0vHAp0N>bxU_(q#ZxbA|Ex`XJt!={Pd@8I1JdC|dqodXX@YYrxrVL!? z8KTpn@Wmgg@e!VfAM0{1se$vC+N*;C<% z4AqGw<-nYsPq%Pz{sQ0RAj_Gw%et9!eoT%qucxZyTVdS*-y=Qs|I)^GwI z1JfZeFaRLkwTc`ZD?V+{sI9 z+g#?v8hYFP7^$Hxz3-ph&zN#P^gnQ3UxmD-mi7W^a4Gx|K(*~Ug+4S8*W&@l^oE+sqk6L{Yvj)%euJgVBXy2~ivWWA# zl!tdUSv>mazZNBaS33UsDQu$hoq#}UzQbj710%Ps-P&??j$Q52)7Qu1dbw@}?cuu1 zq6b{(?Xh=2J|T zrbKzSf^cw|aZ@hO@0l~$#)fMX1FrIVZ6}=6UrVCAm3J?PUZlp*hIKZcG;|9dy=4;4 z!$}e-a&_)&wuDJ56o9j96Gv$ud@`l8)dA?T&S=<_6MB;&t(uv2OTXuh{WIF;^!@U4 z=y5@9IoevgiP{{IUjxQXNj|rS+r$;_$5vQp2d%nj8u7=7pz@$ijMUnUfV_KzniI`K z`SX1cvYRQUk9GYOKCZ>WSkI6B(0!K!-wK!)H2EIxo^pnsu#8J)#n+Gb#jTLS^*)<} zyU4#b8~HU`q~~mW8YG*3mTgsHOY?TwOzo{rGv|B0n>>Q{WA^yir@Z<3SkLB{3G9lL zN{?HdiN5bxUz@MD+WVPa-PL@#*@O?zhMV``r!RWAoZ4g?r6BT|P2qadJgC!|5j_7L zWXgArTrj!&Von!RS31HwI6KbdNb6}Z*rETE8HJHW;jRT3C-+`dj_@k2Pm228>7bYO=O+8pYj_XZv18SYw7ap(St z`TI57H89(y2RCf6{P}s<*Kx8t{oc+&Qt5E2(*T`h6Zzd8`c-juPKdq{blwql)a8A~ zX1JxnHZ>mTGLn$9Q#-T=Y@A$q44s|M^e+#Lw{s!BO*B)rmjT3diy+=D| z=K;2-OBYyAcD5*3ilxA-_X5>IPCl`uYmCV z((vBtZ!`U7h_P9Ulb$QoLwHxtz1V?*f8eIaj>72~r(O3!hTXV2(%V&z&}BNfdV2hR z@pk7N{_5|Sv-={>u0b66`cnqePSrK_SJiL#XBz39jQmYg9m~qy3puxT4%2h9n}<7` zJNQjK76M_Ppt)mJ3=ZUYSGE~o|i-e#_Dcf;JU8z+Rm z9xvLp*$MR+1JajYVevn>hq4uHKj~(YO;n*ZH6%@!(n-v!Nc#OE=^OC2tr^Ju2se5F z^X46c58_+ObKaJn@t%j95oFMpr;(;rzwMW=O)o0IqqVa>6Qa5d8)I3D!QqsqZ{4#6 zZl8;;T?^^p+0xrm{`TW-DJd8Q)8Ao0TUhADCN*US)gfJ*mvU{knH3yL3wfWa&aCLE zSEPJt98o#cqb-i$^e zyMyT)x){b*iG@PN)nEXO(i*?A|J zWV8+d1GQ+WhpYz6nrY`6=%N_3dZLA8qkqQu`3>2fygNeBS$J}0Vu1$s43wyz<6Hf{ zgJ-GWF(R}Lt{#_kY09r9xAom(x5?JNO;)r?QHc>~lhQ+jn;z)H8F66XI}CMT>2F)0 zTPKyqWi|p}|IVdlQ+WI4=S}`c{-3L>OGjc3xR4ICHc|Q<)1kpbjuz~7?NSZrcbxjm z5lB}W7YF{T3#_na)F#RU&m^VPx}>No2^iQQHI4>wNXU9#4G;!6GO56~38{`Bol{OK3AJ_Kg#ACm1{t&XP~@l-83) z*-Qgg^`z9K*#H@BfHVPqTS*6$ue9g1PM)L3KLx}ukCA2l2S%=>PnZLQbn zJx~FzfFlZ+77{)XBSgeWAk4O~stS^E4cy(O(*K4eHd0}pGv%L%rFbraI}8-dg@1=+ zI)b%Z!QgTz!R+U2awr60=^Dt!s!2Y$UGt-<3fsMYLVPGhc_VB8oD26-ShvF`nEe6> zU-g5Pkbz4~Nz$Y|WorjlI+7(f{p~dAU-P3N`7k&X!X4&E^IjaML*TJ028T8uj7X87 zUGDS;PUc>JSDHpDh_y+^1K?$qClSjNbb(-2#mRv%F|fW0`1!g?Mi36nD2pX6Y*JyL zf#0gwic>iDcbUbX?a7RE?cVcY!HXltAq}eH4rKCJx)c)t&PL`p%H5JeH`S)A@ypP{BJ(8^j*(Bv96=pv@`G*o*RSaSS%%CcTc}T!)&^8*(7-2_> z*ZardS`Nm~y4}YnLAaA7v&_c^%tLV!q&x;yF_4g0H6+qJlop3IkS$nd1&Mntj}b|S zv5^V$0Lkr;$>8ys7_6`)&8_J$J-LT8X=#U-{VKN#k{`=96ED2Vp5uLa-m^m?(AL|( z7O2Ig{KqC4vC=Ysh*i)``ImGp`6d~WVkqcm(pRt!t_6@?n)u(@nmqdvsN#6IWFmNM z62s2c+{|^q+&c`*LuQo+Nc<{4`iC6MLpm_~#UP^D;P3;dpn`#9x zxE(TUI?UyzUx42)tXscO{vb;t{AQgEBAOqk7f5bsJKyHR^C3T$2eS5WWn$hl5gWzv zP<3$Z*ZHvgVF>$^@H^ZTBp2>A1M`|&f)~TXB|T1CI0;$~gL5X_QD#jI7{oOU`se(F zZ6$5F_E>2hF4@{6#gVgg5b=#dmrzA9{HDrnNRtMbA0=U-eRhul&mUy}xg!I+@G2QYs! za37n&LBWtz=^!G7?Vt5pv^F)q!C;DO6#cVCA-?!+ihdY|!JQ0lhhpf_GBMj?(3PRj zI}8p3K-znh1GL=_sB z;~TL#Mf}FPk&c((-hZEKdgdRBMEA{n-dS$Nk3!RAgOtbkURvWrvF5Ph=Dm=5ZKfrd zyL9bf>~5mh66iCI;cJ$X3{_B(l2i5Dw;q-!UX;t?ui4DYwLb*2>a#jp(Reln* z82T?d$u&K<;+w|tlX)s_hwI-sKZJSAt?9Lp<_YkdnrB2l#9*6bd?a@8fT7$M~uOz-&-X^&#)%LS7DwOso~n)pqIz9D~kP8ZjO8yu%bH|NZ2rrd7*eDz&b z|L{b_>Q{w^WAHDpbeyVx=;|-ccIf9Z{>gCOTjo7OzCxIHfqWR!6Y1{rq5G4q9h@KC zy1vekH!|~Md@BUGq{+=d-!X6^kL=`La}nS;8XL>qkt8)Y$%v-|vn9!`Dj>TSgNSG7 zUk7=Wwa1aZZd7p2kK;ojV}n??HeCbHkJEdem@ToUiX7t~vUY1?lYV~m4Pv{89O83+ zERe5JBr$j~@b4r^t<74Pr4`>beNoxHMCrRN=qGeECQHmmxpohk)$t;53?7B0ak$Bq zdCtJEb1R~`^!vZ`?C3w&)d|@Q;(IR5YX<%yw>?sT+0oBaM?Xv9wn*dCH9%hfJy!9* zV-o+vSChEb>pFe%pH+IiRd5P^%B25*VSG;$h4k?!Q%Lh(<65vhiR+@H-K?~#b2_*@ z`;+}V^QqoVwf4E#_8snrO7N>pX}a^X5hmhdm0Pz%4*0HTW@}FVgYG>x*7ROl{c{G{-{o=t z)$#dOe4}gR)AakSuz&MNX}jk%(fb&U?<~Rm4&Lk--(Ve)@?UrlpW^_zLb@bKCXl8c zu&)T8pAyVVmXsA75BuVXYumVAC{ty)epooC%}XZK7qiQAX;tke>7Ps6qsSA3_Wgu= zjl+`%!M03~u=d*&_c80>&)ky1uA`|H(hHsqHGSd#?8$y<;>h_IZa60*rx?ViJc)lw z_?Hg+p^GD~_eksVr%>cC`1%I=sDdQE7hpEH#^V~b5#||A!G2?9*W%ccZrz9;JI!9MVMbLb+|ambB1& z6TkCgm1J!`nBF1j{A58=)&GmVH{EXCIuk_ex1RzlU8`(I@;M|Z9*M`X-5VnTk`Mus z0D&ay3X=ekm`H#E$;5Z{)AWP&lic;~y}?1!ah$4LcU7&pa!L}0jXiwxh_VNc$WSKT z=aTRy>zX$SL$l$mE8e8Ku=n!d#mgts)medD(UZEa6|`s9!F8WoSOA)zfy@atxtydF zkX1NRZw%`o9OxqQLI8Yp@q7l|07-FD&Qer;-2k4v zMVa>Rf@KeC6SJ@;v%_WPo*#-b@JxOw@_wds0ZZxX(1@L8vLXAVc2D|>W!_;~h}BBh z(n>$mx}KhPTx-8}bOY=AAh-BzB>PdYwzEcZA``t4Jx*8`NvBL(b zAC=@iD*&BG@>t-#$|Zl6JPXrF$s@K9phu~_G=NT(0WvC(VK}+F=H&j1pLJso8T-H* zbU^0xu$-n(s9vtVn%BXxf)eVx`I)&UJlwwI-F;790Phw93+mgcN06Ny9dHtA!%aA+ z0k|{|js)7-N}!IWdLrwQiC zW~JG#uC2VGnfN^uVCx0jGg*V$P>mzjo!FDzRDfEGe%@YBcP_{tx<+*s4f9|xvt=LX zINN^#`N+$B!Efi24X_Txk!X2DWcEuJt|}O98ALz;AL)5{%^uwt}*Y=1|W~6cB7_)s0sOkuAi6TzH9AEJ6FrV>d2?} zF)ZI{!4k=rbMl+=1lN8eb)bGE$Swgp!1XnM!KRHu%iN)1iS4^#!#$v32R%bw8x6_) z!&>3feQhs|!p_utx7V?k^59zTo0a$WQq7kx2D%6SC65={6Pc z)Mumgy&jkPnbZOO3hG>jJr3Y?u#~C%ydS)IW|Y@HrG-$RG!5B(=`Fj1VfxPZy89R4 z{g{?6YdrSz%>1P>ug<(3Tb14&yX$2@w=ZQK`VAxYvCTkEccABn-F-!6@q6Vc4W5Uv zf8ChiVn6ls`XM|__Rr@2K%ay4;Qe;3{?1vd_e*(CaBEquCd;nxXN3Ph8-b6{Rl5Gh zlAiA~NAC~!SJ#(Am5gW9uijs*Cfz;R2dSOUVzeCA{+OQ}mi*p-Hq7>&`=wBcLyqlk@!v`(~V#(!e{<%WAzG(z>ie4a3v-DHK}y+L>|e9+(BCD)<#VF?W3F{FVy>|Tsx z!Z-`Zi~%+=ocNhpg*PLmPWLr^Za-eBbzolHKLGq2?YOBod`XgV;CmKX!(?`M@RsJq z{i=RmcGm5h9czDo`TKa;ef91#Nyg6goVwTFU&>u_hI4T@$-3RUBI#jTaQ@~Op4q>e zxAXSfc03rq-jD99{Rl^DGVJ)5>$oct_MLA&y!~eI&U*K+zo{nDn{O(0{`#Al^6S>Q ze|L{xuk+=-Z}vJ!w}nTpsT2=%Q(jwv2U@pRk6g3MQRKiF2X~1JF*fjBKTGeRNVT1H zW3VBFBI3D@N}r1()C6q%T!i$Y**-Ty65rFXj?>;35t3|HIyy@&M#x#y-%Es?1NnWz zp(cnuInBMyT=Nls;!XdW+OBq2x9IYUlFw1_(~l8QC%-34>rKX)Nlt^>UwpiXiln5faw1N7z4ApZ)! zi-vqB8Xy@ZJg=zAszF|&+#vZOv1e+c6p-OM5|m<*#K}le3O`9^%7d~NlNqn7N~R}1 zuck^aCdN!1D#;{Kc?DuI6aJt~Am)yPiqZc4f@`Y6v3dn!&AV+QH4ud5Ef;ra$lXmF zZsi%Bv1fGxWTm^u{XX$!9r^NO19^J`SWnk4Ab;vUftu87$iaeg3Y-OTIZ_9qNVzs?kjnY8h7^p>5t++;16o^ZkO%%wV z;B_cERUkd+nOsvr9|D0h#MuaO+>NFW`QweQ=nC4*L>_4<<|1LH=nIrW9Mzya>4oC&w*WdW&oF^bRtk`eXi6~L1{j?fPA5gO^7 z2kQ$PZh(djdPc}nI2*T4>gxV@Xg0uCN=F7=dhb7Wo9goKG0-+khd9u*qx)k)Uz`eN zakyWKf^_fR;F?NCjSaCj5)y~c@GQU!-~g*v<9ujK2;Jd)$%rJ#(OfvF$za1DGA)2b za_1uWpMuWOkhFF~ghuC3XpDP8bgB=wpmn|4ytp=w6`B&0S`uvuM-pcw!oyNTVgwcZ zy#|fw-}oU;r%9e|{j&y*Bl4aG&y(?V2n%|o<6YDgTjL>4d3+qsUEt_=P|%nDf#`dm z=)7;*+8gveo_>Eq^87gYqV^d4JvyylY)<Ab{Koj07*%Dbdy2OpCAd_vEc*786&PE^MG(*lzY z(UA73hT2#m^AUA8?*{%iZ6lJeYPsQtp*kAdm*=j)d2qBKu|S_AHAPN&zO=MobXCZW zMnQ^j?ihXqcwdllJ|X<4Dab^E1^dgN&rw9$9l)muX?iVO^K?D}h5H#2Hs_*sZCyM% zk0}NPphGljE`qdZo~)Ns=;A8)F3trIbckA9AV{5~hbNxvRKJ%{dT<*CX);-jFM79qi%|i`WPMNsi+zWSjGcToo=H?CZoni6z*CeGYUa@C!KX z9T&)H<$!(P>Q+d^w*O-r;}t|&&#`pQ?yWiK5fWhkth)1hCd6GFag3McKn!H#MACu8 zH)$(BI>$lIWUY@D1KrZw^?*GaeDZtIwVcdZs$kD5;ct|um9tF2#ua1VSZ1zWtKspw zv%wC>CQu)PBd3)oi#(2zTGJS*NGia`xfb}>9397$rPL>4?O$xR?zu}X z)mez88Fc-1x(j48_cN(NJuTIH=D{1LqSrGMPc{u~i`Gl}vyG2}7_;CIU>})QdbuvV z87t>9)PvqI<|;sHm&{kg{Z9fmJvs~R#mkMCV5zEb56;y?(!uL#$96A$q(M9>GDL_k zG7dKQk{0DE)TKF`jg@JAWJx)WMS>WKTq}YId>RllsrHd&R;bsWRT_iuCXmyWZS85? zVJ&(+T??QO%>rWWjFj&L2YczHe3#k+nR4K(?qK^6N8>VP z*sk*aJ2JIR(r4?1V=ZKJ$2oRkt)AaAc!Gn*1Z=YO z872yY#!7J1 zICyM@j75KlOhZ8yIh!+nK-?dk?+N|^=73gI4#X5exx?RFr7mjgeRTiAHm<* zU$78Qx}W`qg*wS%fCheHT5@57m^=74@J)>{br8Wb+UV)r{Z;H=Mzk zrp^(6fw>0%ET%!0hUvq5`*WgImIOVMB(k>s1pA*lPS=z7^ja{4UP0hT;yO5PYq-Gi zJw|(b_ybv86>AGP1*RKo(A3chWho3j}ATeyJl@u5y*4=(wHuEusx5x}NsFV+4` zR~t`G!M_W%i_#tAaO(RMsjR!yN{AcO*#X2Qs%9H=c!CiXV$;d`Pkf|ag}PdMh#T2# zyZ3*o=Gkd|j4DdnRkKkGJ#2eMx&LA!j z$B|aB?-)LCoY*xF33Un65NxkqoZ_gYOMJhk9fsgw-$Xy>MB|0f#?yOp!1gb3S~=nL z8soG~;<}7$T4lDh;R@%6?YrFBcR0~A=^%)No^q1e7~o4x+xMNzZ_B4|i}>5^^%0E0 zwZ4{XUj@Xd5qJ^r1|1UhOrZ5o$qcDB!0CIT=KjG0MQ|&WSHq#WAE9 zZU}wa1xpRf3l}g8`3R2`Mqkn33-|(?*V0MnmbnIh7R7bNB=J=Ad-d*g9n(DQpJ?ZD z3}ka{w7&86=?r9i1|1qB+o7?b;1BMQxG9wNfk(wIo9>)0jiJg3Zw491>8V}p>m8bn z&PomHP?$C$4$mkdwhrJ0bEK`g=P`O_XpDW?4d#x)&c zjvNbOMQS=meFgWZtES)&^I21BqiV zZy7ZAByHEavRN~AhLbTJYka-Fny$|TKO)4Qw9g49p~njSTe-w-zQx_{tFtHaCiTrr zT_g@9u>ZctUm&i~ZmwhwqJv~t`8tGl%jWKVc{*+7Y5HyT9LGjvP7;4)H8}nV)3YUx zbx?4ugT%!|7L8M%O^*ovZgmN(l{exN`<;j8aZclqJm7)gM_mHX=o36yDv(=|I zPy0mT)7w3ydwPm53oH#{?je>5Y}q65Lt{Rbti7I>fZ$ zm>IJ@Cmb7x_qrGCuH@VkFB<@?OGdVT@p_5`&+sRDf8tkXTwcI;yDfa1zKCN=TAnq$ z{07%;-|ymYoW70eK^sGd_m>CX^UUhDGR^B8FTx9!Cg_E!Crf?D($S(56a6&9I;w2S zm-KzYQ~l|cEQw(X&iqoBkS_TgXI}9+>8wXcrNee<4%c1)y%u8Yuq?Qg4xk?bo#2T6 zcp-~9a}qnEPg+>?$^DK%X)u?XJEG$g9JV3W+EPf|7<~p}&>V>KZDP9r@fB@5(FHbM zKuieAI=m103z#Og@8B3WWQy^0vA*LLYe_V8X@1&A=;DztIKVHkLjbS!&}rXN+^@8! zrdS_^_^Osyu`Lgj@Eo`WUDx80x3oG4#i=ZXTq4k2ukKX zbkAxKjS=U-e@5sejm-nQimu|AGSt&W93zQk%6I~CBD|!Lp0yCe5w&uG)(82N0X(xkY(h~Yq?&EGZHs`dJkC(33LP%%lp>5I?nYNOA~YscP76hqk+u~>=TxG z@VY_i42^=yU_9upSdPLti1o_YwzO^_F92o;yfmtWGM(6=a;$e?n+oV(pr4*$2hK(7 zd%D&@ZjCF8RR7j02Vw)kKF30?l(t4at%4XD)Pp|I0RMa7cSi>~v8@LQ$4-V03Q~@> zhfWg|sHb+grIT>1F8DpJ;D)*o;@pZ$xI?@FdLEk|PzHPo>_rov=7{2)&@)V^9h9fF zk8_f*;DZYw{x*Y{broz{$X@qBf5ttCL8j;AQ|z4R4tfAh||s0Qw}DVL4K%u za2umz=js+g?pNkx`2l+WBFkLaONiTD@ZOT^giD);yfI>9#AhS82yBq%j>_ga&Rdgl zz9ZPhUP!(q&U+JSPTapYUzBr!W`X_!anbDlh32&2_-ag-mlrarMdHUu>|>Y4K59F+ zQMZ%1B5G)I)R6jOvlZuM3jy#vh*a1|!mp5qW8&LfQbTOSMPyXmP!VRx5IJcfI>_jv zt~uc(MFia(b!~A5&C(@BbP;*hCV6J(XV^$IkYRGNE(W?*6Z@xzb81nq&8fW@v-f69 zj-Dw;Y+fpBpJYQd^{h46dqf9vPZ8u9#>c<{UbC+_8RAB}4JR%{M<=A4h#;@xB3Cw&3cI&{ zl`AWiexyl=orsXL;>lEg!10Run8xMGj-(71O%VG%eMtC3K;kReh2Ug;Y~uy}7WFjD zS8$wZn>$NmGPzvjp=UO?)CC_InHL$YP9=x3c?6k{lW}ffiSxx|8`irfS^=$E04tBIjqP zeZl#2;75QwF|gx>82{9cpAEJYCU`$vi%x{Ue?VCr`;pY6_9QL@*(^(Q0$W^afZUB# zLe~k7g6-jOX{3zF&E5DU2L4IU~GN94w(bWyiYl2AH6P)}NImC^Y`aNB6 zm$n3clOPA(P=g#`Jbzkm0%#iEJ8Hw`U4(fc?`IEOD8n2e-&k!xKcO*8;MZtF~GS<%9*x%_C7eMuN{aJm@P_ z#>ov`tZkOuVsNcc3=n2-RU zDr8|lRfX0I-qzI(vicI_rg9|Tg?DuAoI_1*^Y+P)2zh!&%E=AnjjrrQE8Fw(K-Z7d zePEf#%baU&s2={#yldWDFHX7F?h;^At(-`$U2ES#xw^J{Yr&5Up!Z_X;Jj?QKRDN^ z)8-Wc9QZI7%*S9K>LcW9dp%zWTG@idw7m}GxP!96_9`C!wT)J`c|QaBo7l~%UzXy0 zngrM{!WE8nhujOj_2ef8xjBzl9)jHNOF0#I_&F!h$x*C{A zx3Vkvl9#v^1o)c(cd0EU-C=nG%Xt$ihyWJ=Ux~bmeF#~%LUMWKA1C?d7y3bF9sntmKyxzK__%{^_<_Z#A_5^ z#xtLr?LRazl1Xd{SC_nAQPJv z%GAnjD33=fuD5W`r^nBM53WQO#Lo=?PrH6km)qQW(6M}E&>9d60q57#+V895R3U@TYI2qFSQQM`T2xctg{H(sdEZimzJCf<7i^_?Ut(P2gwCTPxFL1H){b&j2iS7)ST+|d z)wR!pOrmw+`y~G#a-pO>%K8$LyCRMuApYvg(KR^ZBgT^+?2$w2rVtrPCUszH$bVXS zEbuS2wPU=^&8IdyWI@jL1MeUW7M;Mm&!5-jVC&XB_$B!Lglj^wjp#D zf@^^sKM`nshfc6mB-?6+ej_D*5Aonv;Vf)}Yf$gfh6#E9Cgz{8f0!QN?=1MXR)Z^7 zq92(ca}t@7=&hKKA>h$D`1f_$r?!7X2V35CPCvl~Sf9cXzDjV+$MkWHt^u9Hv;t~&;F?<<(5DZsZl)M#&pLMLMW)1I8OCI7-ATA? zB6!(a3Nlf)BWH!>s>q;u>&DST2H<;zV~uh}uzO~T*o9~}*iLd$)52VFOP{~?OB!Sj zP_Ky9x{j`;2yp6)H3*E91Nj5=$(+bDkb8{%IZ&S3`6o@e&Uh2Mq(r)gYa$gePWZ%QkK>%f%;oe2M=WB z4C5@&bSyUz{Ud-H17M@bIvj}++f$mJ9Ek)$;j6rw9+pz|rX9*z@fkQ;bi;Qg$sa?M@ux*f&6_NZjUbrRLYK+>8aK5=141*U0bpcuML129z z;yk)gd(e+miNFQGHsqO3#FN}DYh6;8OCue`8|aE)^Fd+d#(M7*oCpb*UM6nMMP5H z2y_O(XV8DSgKl9O1^;k82DHGm=p@fMI<^P%j-0M8L9qlES!)d&Tl%O8oKaS*?o#dMXm1RV4 z2y|ZRdP5WD#f4B8TrZGdTeLhzlYX-Cp>+&h+Y<^~Qz^^&1TT58BIM=(38&_TnUOvITQ$r^< zQ%9%u{UA>bX*)wVUhT!Zbw7Z=ckRe*{sXl?h|G5sg-J9yg6v21V6AIMT1sumh0hKu zZfPcn#eDDmdA_Y5B4S!(DUy%g=htAfKua8Fh+xkgs0)!}zu5MjSOsdA--9ig#vqsn zXRb?52K6?yj;)(e*A(o35D#@)H^u?B4|bRB2`8X#S44clCTJj|pV4N0w5WSMI$ z-?9PL7hF+JuA8mTz0Eg~|{Fb4nH$!~@%1MB%1C(rsA)J(3<`iulREazn@)_1Y) zCtvc=1xMt3@-ESVv7eO-mYBv6o5>P9tbj#rdBd{J zeYwbCpm`rl<3Qt%TR$JfIg$F&mt(O7?_~wrCmx3?$iC$bBu&Iec_`)5T-bA7&c$MP ztSZuD5LNReEV){h#`>WdiQaDck`0ZHrmisoymM)NcwWywU!UkvK&3n^F24} zOxErp=~(J(S|C@A2zEFn#@IET2B38qWIzgjo5iVW!W$Z zdi`UORhxbHZY`inL#WE;>j!fZ4Ygw&L2)u;v|i1|{0nch%1&3;`UrVbjazHFyHGfO zG09f8E38KuKX3ZkO)<+?oqPEv(fboy>1RX1(l?9w=5cLp$J1JpqL*&+u&9Lvn>lQ; z>>h-{%AI~(_6E>zYw_r0+^Es5LK;dBN0HOSNxvECoj@Au)tGPUts51FJwoQatk!Cj zMo2ead>wpRMwipQ4R^EO`NK%zAqV{qP43WfD}L@pI zb3E^IeO;{8$;KJTLoQxy>XoSt?3>KhVGuOwVq9z-uNv^(dG~N*PPlm|?l$axw;%B9Vk~VQ zY^m=nhC5%YBcs^IBY7jwSAAJum$Tiz7W6pZHP6e3u^7lgJQ#*bRAszttnEZuYHGCL z=X=3e#AEi;AY;pcDr84b=^>l7%4cYK*4*_Eb5)$}9dlQ@OQY+!%g)B!Rr1Q;+*Gqo z=y6hPub!nC@o}nEZrN$L^0A6{;rxE`!X55|AgTPt*tnDObRhMrahgQyIuwOzy!d#x z)ti1MhIhiETj}CQH3`h66uZhuj}$j4H=A9xbw9lf?>_}fWj=7Gs`&C?G&=;!Y-h2f zb*$ap=tnW^P6n&R;OKQE&a>FLAcor9Y6i*Spk>W-v->FEew~pusG2#~px$<~o!vCs zXtgfodBWLCQF=^EKVF)WGhfI~>BvD~rF&;#?N_#3C(DP_T*PRCWV09xv*&!nc@`Hf zP*%pvRkI!nOS{|#Q|QaK_oGBvf7;DE55v*IP-mS0$>MN0*Lyj?*z5d#awxWbWb7yN z{lkl}PtU#9%)Ri^WZLR6H5OwLGId4XusS=F<4fs&vD{5Q8Xax?@+d6B-n~5-tz&ss zbS2sIAA0r2$K$6NTR+@SCo8e;u#4zXo#;jLF%XW1toUWG8qfC6hoR6^bJ5A%qW3)R z4IZ9{i}+4crKPiw#5-vu%Ik-%(8TCj7^mhS9`0Z6@4Mb7=lNqVFg{s#p1CW{xe*K( z$;kbrx^@=&^VIR@xPC#SOS49C%zC-{bI-9_~9w#aeof z72G^;G87fMm-5Dzod@%vKT1nE!>xSWFtBY@9#P zP`3I*>R5|x2Ysbp9_}}8=}2B@s&*#&y*1rE3Rc|Zy=sPI0vo?Al`=+`@3&$`9R-C91|;k=WTVW>?w$ zw3oF#>SD7~Yh3VrsJ7dYI+ceHbuDZk`i;jOR`$S?xssoboPM`@QG5Y``O33bfWq`Ge_e((1h7$ zw{~v
    hpAfRuAcT#ix^5PwvhqkBv6BgywEKIy{C-tf&4~%+!0) zv|a5}bss!zdz;?#=%!zX@y#U8y1Ou%j$>s$G`cs{WU27{-Na6xWx=pNE)Qd`6E{;w zC{1}gE!Uf6x$CRl{tO+5n@wdbXRF*OSUKt*pG|hMDmlk&(t$1n<0^-e%HI{-#M%CYEh=#SbeO*{nA)F$H}H&d#gv6 z>w9v(>+ED{P)UQJ-fl~=H{kZJl(D>JXCwc9WZ0IrLW$Q&73E;n&BK_V%B7(9KSjAS zkk#QxmsZoYa(LWqg?ci6&_6md7pczVAr;u^+P*Q?>PTO2S&>hd4Hqn}p|jjKtGkc7I5ev5_HyuxpeNI=)?(z^gvS1Xl$f4t8{L-&#ke%E{E6IMHVf&1{F3AEk>O%(|3Yf^uv zgIFS66x(yc{RL-}9Iy2N*OXF8)_C2cnTY>U7~n<`{Fu{qPZD+pwSdU~v9yoi=(0~B z4?W+J0N-P0iqPXpPeFDj*hok5NY|mf3diCaBzXP_3fk|sJsl?k0{G#T4adWpP^3gC zR}#TtgD63>vBL%{2Mx#>x91J81OF80pBY35&Bi|T4df7tSm@oRPqTxgQFPZt$AwCPGO8IKCN0BJRP*>Uyp= zlXRqC^y$R?7}uE^wQGZW3WjxnBXtmMNRPyIiF;*|@sm;A!0)6F;f(f(JcuRk;mIo{ ziU7t?Jc^Jon&l382Ks4ENZ-&%Unz~?v|T0@(gU?r4pW=s*PN0pQf0O-Io{tW5!xU) zk4Wc~+1MFHxL4^)nH3vE@m)b8;CwQg6;R`dtPA(&EC8N?o(Z^W3y*1(sJ^`1-wg8m z9`D@)Euzn#`X!$GCZZL~D;vN!fPaqmwIpy;Ym}MJ5%_v1GExoAK-?fixH`;q>G3LIxE5$F~amsC$r^itsw(8T1TpCs)WTC^~?X?v)SW&qy>jF)n-=ZAHQW|I|tHc=8kCUn$~m09kP zo~Mg+q@z-qO`wlzqG%D_LtK(-Luku-Gny?Db+#^nHX`08JyK_4tj-D%_7e9d1)50C zDN>TL1H1$JbM`dY|DoU08a#ItU>eH-Y$}j~!519RiczFTN&@tM=qpL?!x%uH@%tD@ z#0}YLJ?`;hg!_5cN59whQ?1tspY;Vj>}kyg=)Y1o(6ieod}Zvj{N+=G_P0C$|BTu` zyA!0$P%!tlb4f;Er$b%`)tUq>Tdgno|+JEOP^eQpt< zfn?8=4dN&G=O_U=0eG0;pk@-Q(Ig=~h@syuhI54f!8$R0C@y=ulAgK=q3M`+9Rz1o zuOpThH@H_UhQZuNGo@4yYk)Pthw==AVhQ{I8U{x*6j9hq5x-usz$^5LZ~>Fh85rZO zawu|T=9etc34Xm%Fm6HLR-mOy3g1FAyng5f%b^)r2S<7Xm$+Xl4|x0RCIVZy1H7cWu;<1hXed>{VB zsG0hJH!vTL!a72N1Ngzt6cAzoA4`Pgq@lwCjj1C%H+JUd2-68=1Lvq7p6yXm06#=n z_S4oP8$k1QOq*jgSc^)K+t3_Vcda>!b|R{p4Vr!$E0J(>I27n(Q6y;kX#sz)4+{FY zf%|s@WhDwzemqmgi=>nA9i>*HDH3LitS6lW-5^bgoY{D$h@GU92=ZtZ3Hw=bhx(oP z5lxPxc_g4jxkDd2oBmAbDyvAinJIUOwUbAr>F~D)&vz>LyMgx=_?}$AcsAU35967l zt>JzF^J5d3UuT1+{SyBT^UZAJMrZ?ngPig)6O;Z74bbBvnkLE-bsr)=;RTrg^Fg^o z_h|Eo9(nkC%`124?jdYA>e|(Sb5=C}OPi_VZ;J71g25N~rA%^_ZIsqPdJYQ;wR7}t!ADxZZKGIpX2)fZ1* z3>5GY9+b$2x*M}@Wm{_M37tfToaY1A@eYs|L+Tyb>>_gH^k_rP1WO+Pl?{ez-P&HNTkL0B!Fz+XGwb5I;?5F33q5ys z(-riXGg3vyeO->znTqR52Th0btRAWNr6k-6Vv+n~ zCvmdDOCW=f%seWm_na56XY6oK(c|4{Di10}HsU}QYtNDnE{o%R2TC@ml-1qn{qYvH z4f_Rg({O%doteiDI$k#DII}M4F_D>BJNEnUc1vd%4U~iIU+|z1M>?aw@Oqe+shn=;AZ#ynlVZPlBb<@z}fb`Q>IOknw)e zeSy5f1^7zwK2B#U-dj%|#18)!UT}VIwtulLJtAkSM5O*Sz?f0`J+88s>rbxL$Mx19 zd*`|fV_H-9akW1NOY|qLRreM_u88TV!zC~JKEv|c*z(t{pXORjR328`eF zb2FU|4d_Faz6)D9y|=m>O@{`?g)clu?&0Sk*ZA(;y&`pkyR>JN3a}nS9OT%Fp%!Wi z&jdrY>&%p!sqDA(=IAcVbUIV^xMTIIFP_d@XkJ?Qn6CB>(3&&->OJ+{2N2O^6KsqxBqV3okqojBd6^9I80$0;FPUS z=Z$;d^i1gWcQG%igL_{=uJdv-P*(d6^gHp+Yk8M;L;oX>t<&+6 zXm%7?D?1tqM*;LG z$Tf%wt*5iL26!**c6OBvGXZ`+u;(M!i_Zwnv zAeJ9$I&_@*-Ge8uzkuUFkJ9yYraX*szqq@bDL(){dovw!2WQ5u-K8>6vVF%-ln1iU z@6Mm_*$bW%uyKj$DmlYX{!j(l^xzJacjw{`l?3q4&fmXp=lK3xxh8{piUZPPZ>Bs@ z{GxM&9?6&vurQ~oY?Q$l?!CXySl&sd`~a_Sx@ulv9q<$A!^M0~>voqA1D~#xgv+3A z<9HdQIOav@B+&QR;gyFmOK8lvr=^rX-01mUy0OKZma{;Pla=YRiQ|0`X8?MC6pAgSt) zez6Td1Rv_^AN!3?r}OFVj(P8Tr_<^6*?Z<+di_tGZuirt&K>hFoo@HO4?lm44cJw+ zyZx6==O3`hPN&11e*PEvFUc^n|Aj$$l{}VpQsmVwBW;Vk&fK~Vx3|o&&eB;}RY{Sb z9)N3$GH~ngmNCLS2)FbW^E30jEi&eJA3oNHGORwVs^5M8)#)qno>Xizx4w8V$?I^N zyD540!|nIv`F2)6 zT&|D#w^wuiH|8&2F^pI2^1$65e)`OKMUjSX{{2@B^NeTv)8~t+!{v{^|2?yqOW!>( z-k}aF#tWZ|ZOGJd$RsewTgDB7FktF}sfyj!51F#468yOj%I zpU*p;!Q~weD}PXZ(vV{$bAi zaEa_czS=>$XP@82m*?|)pP72Q3%~#B=WjnVf1ERaW%6B`-d@b(&wtMfF3;+3eE6r& z%(I(T^wa-8ulwo?%wPZhl>!a=;z}29mAg7JzxJz#>h%b$}xsp2qT!aVr!70{mgUl>fmulN$aa>bnR zmG?N*=|;<@@P(`MynVZBxyXkiB zc|GIPE7=ZSCOE>mRd~X&c^qcpYw7TRmPxqXh8GZbCHZYb*M9?!KnI!A>=?fYLZ(UT zn0b0T+S3OHVNm0f8zgd zivKy_e^~i$iTU9zQ^N&n1X@5UhnrWR3|)|eU7e)Wcl>VA*($OBiX6BtK{<0%rb#?m-1nrio$i2MY7HP#7`EwG{ z1*1I4-1`FbH9U(RZ-`z~Y=dih2Z;BPNEv5R$H#6Sg#nW$c~~*UGnUmb zNyDTM)3saBPw@@maYE%3O4hJe{p|W7*@W|S!hId)L3Ji$Z}#%*=Utk@8(;s3MZEKD zDyE6U9Dgu#x9eTWxLZ)0@fAX8$#i}4IMsF6;o(xbOWmp-CwX{z4ZbnPuU2uX8wA9t^LY84w)t{(vT^`JOBwA#N%7W z+a+nu6gl&pY^xf0P(TNTU$L}IUpOnVKYw*0R))dFF8^=|0YqfBsp$^-7ud3!9x>`;|O6<(W2UMnH5a5E^fGh$LjY~pU$0Rh#zV4k)`Q9s?{ z4Jh5(kC~*dFjnS80Qj3Tq3g%Y4$tG4PDm)S(*ePtpYi#NX_$q1{aUj+Z6eunq7wh* z|Jshb`Qgi3{OxIGdFa>QTznPa>Frgl_cB=XC98W2ZWt>uNpf?#Gt7&d?!uM;-7;0d zBsowDG8TQP@K&K;S4>sA2gZ*>xBS3pVZ+2lvBqckw7cMWPp31g7`H4zZ!XAisauCz zIvcRm%CY5U0_A{5^fK5oaE65%33Ni7%UF}!ozxbvSmtl3#`lweRo%d zjLS4zw=CgrS!Qs)2Bz3oe6)() z65jgSOACMfHS<^IYd_igY54WoO7=JG0M`TJi|=x;w|CBr|Gj%Bf#Y=Z^+(P^1-q;KC7!fr1_wJ)m$tvLS+3c;29pX5Qf|Hmr;e?$N8 zzt#WQF3bK?{{L_2|M_sx-o}N=T zs-75^x=f$`Rm$oo#siVLcxIletxt?mjaxr`V4hmf;uAE#-zv$|{f`!vQe*>rT`HRQ!{$^hd^(8Iu)sVOEP2-F7 z_!9d5E0g2@yYwHs-F|ERkA27g!*=G(*gRL&Zk_mFW6`-H`;_F-b#UabF#VC}!EF^PCu?H6xa+Ze zcZ+S(Z!Lsyx5()fihNePTX^s~!tvq(F%Mqd{+ZhCUB70ECMT@dFY?+=a$q&s;QPiJ z_e7orr39W0^ZI?WeY>7-{&L!15`1`jxpQYj>Ft*`6ZEM;X{dG{O8ZtK#$!w6o>x% z7>3U$eYMzMZ83hAKz~6dIun*(YyW*k;r>yAz%TRvPyPGeoA|H0`+w?xzp?!XYjMP8 z`-&M|V;JTmZi~b~u%F!^RB}wFgWa~hdPu83w*yX%npiR;}qKO2sUXC?~s za0@h&2`Rbx0E#5|zQ9zp-BoZ8NF64{uh5YBftkA7I&srK7@=QmgFmz?;5V?kmgix{ zKz{x4$M0VSN?fk;uEsK-OMVU^XgfE$x|USR zTW?-_IBz0Nu9QR?mO(Qdo^W&oTzX=HB)}>raeBTNb#hIDuQye~VHW4UQ-B}>|NF}~@DBg_NPApYW?_xLz>{L_!(>;XXt{v>W1jurVi-wBTlsKR4aldW_m$SOkz+Q(= zy$zxzlNN~itHLvW*KYTLnT261=wH)nI%E3QPj75iSJ5bxqPGm}Vw-;5=Cl?&G9J-) zsy3u0fpK?W&ubY#b)x8)CgN}4xD^<&aGn{C!^#6?mx^UO(B-vXKT@ldo_2-) z{dcVCTA6*i%AP!3{`KRXb>ViX^Oc`IpBdLBlAN`2OoQ4#uxW!R=|6qGqFFS95ku@1 zh+c#7_f$@xTKFs5%C*{kve=L*z17QKJ@8sdzaIQjVFz2uZkwL{B{*95>v$VJ6GPC} z|N25?rdawqvbI(FfBM`0)k`rOJQCMtDz{?%+b>B5Zp9?Gub7rwG3o8QY#l`D+e`hx zt(fBW3vAr2nC+TA zbWUl&IjpS)e(}8vo$)I5_>~%sryabR?Pq3J?c6jyFfNl3ssO4J#L6ESb@r%{$)61x z7r|@H4|u=+h)FV`tAGA{`M~#I{mlIJ^1>hge3I}mrKVXBXBI?6toM$$4!0RrZNG5D zmn9Th0m<6BCDvOYA)$^FFqNmfEdRh*AS!mS(W5n6-d=wO7}Q0MK$8Sm*tt?W$x)8O zntA&D6S33(zfUJgj2KR^Pz(Y!13}IpZ}TyzfZ;8px}{5gb8{+gkBTj91kCvs=ypa8 zvETWt^;y;f_xXi|uw3^#i~ufT zKqkYT_J;WDNfh`zTvDcTp3!T;@aH!tn&kc#O9pOwiMTjq;7#DvJ2;BP-!^o?FS4x2 zFEhod9ilqqwY#S$cn%o{ppWz^UwGum?l#9Kt?0(Ao_f$m@+9T*irL@%haxyhKwJk>DL4{v7%X>6v7aS9k>-U?_nwG>x$&M zw5sfTpN*cg@5rzu>Lsbq=TV1yAxx7jso#jdr+pLifI%}}Q5X+wzzbu1vPJUh2yYYG zx?bWlB{<}E*#69XQx#0L+v4Q3B#+2YCvd}1R((tTUCdL{G#{R*F|XSB@#Rprr-+@C zm5=h5|K|+IMSd~6mY)Fh5&I|x>NBu!F@au(b-XQhQGDJHcUKo_lCL>ZiY5uGUj!yx z`T{ITIc6@~T@DteaPRsxq^L9nQ-k7H0k3nfze$D(+Rev@x()HsMbFvS74vkVInp8< zPahb85b_F;^9gExJe?>1OR6SCS-gpH$at>5u2Q#(iMiP#x+N2AA(5>F74tLB)y~(q zOp>`#h^;AD+rau>JNv3ma&q4I)ZB`B;y?c>3;* zFHAs1ezGCr1qW{JewY0k9h)o@1p$4D@RYKse)t^-!S#1x9{ld<_M)y4Q(#kYMN-_( zA`+N^&YQOP(_IDY55c2b7fhN|5UUnu#LEoC6Q3d_qGyHs0(kzGK5uQ4I%KwPLyMW5 z;(*T_fWq%Kj6sTOlSIj%-@%)Nsh$Lma|+Ghg4e2aeHyw~yIzGovjLHKuqlp2Iff^L zJ$9j#?iLJ^CEcmg#hX%5gW6_S)Fg=(EQv7kY1bIY!^vw(eVRD&W8lPDk%QBi!ai{u z0|5M?D&3sHCrSn8@0vKNLpeTvQe*dM42ZsF|&VFq7 zGX~8*2(C9kW78RG$9+$S#!>Y^Df*OCT8%&X&GwF!qsyJ zZak-DyPyeNnr$2*sQ*{M)TIMI+uqh4NY!}pizpnp@YIh1<&T#37Fy$M3vf=*l762} z=U{fG!frbZ%q)=hu&asjAM~N&6FV-1-IM%+ds}y2c=3y|lXqT-F2riiJ?}gs3kR); zY|1Y@_o8Sc9kE5)N5^XqBftmmIwv%e*8W8o+ie$LbpF;JRI&?)#w;?29YBz_1gL!H z)?R3-kHj0gEvQ4$hvVVrJo1)dP{cV!zs?!FC_J*jcz#d_?SERd*6)L?{^(8n|1+DM|?sb9&@jHSW4&p&KYW)~BMvmAw z4o-zfVz7g$;b880uonDII(v{E_lG683-&(-Z)@)l9RGFD`0tbcnE&Yy?EnAA`0qc) ze^X+r6Ofhm4`%=SlgFMyd;Ng@|G2e(^#A?C{5yBYcFq{%{X@?Y{XXxX!@~!|Pj(Jt z=P=$sNA~dppS*vL>W}!GiCYY4v3S+Fs7{`BHN_=urHlc7u z2vt^$m+_M;$rB|+qEuB0$ylOzWii786`@qQ%*rg0oRt|CIyp1 zFnUPv_^&FZO;Q#L)>mTIX@Z;hCL;ioLi*s}4f8gl{%m1VA@9Y1qR>c4MkH7l-zh3*& z|4G%Ao3a#A_6w$VY~6Yu+gJ*M0{aV55q~afuX&C7oOn0qrM~59Nlti{O3%`=oUm*) zW2v&t^LEOtw94;iU0a^*rP7vtxt*4+@^gGkgJ~<(gq1dFr->D+FDGott9Dkh!tWom zi4`5sJDEaxv!&?|o9(R?%nCne+L^G)OoM695}W8$)VbD{+mhuSFLt6B)6eEf-?DMR zQXwa-uyT`{unb??p6|?*7qjhgp|Zs9-@l)Avy$Z~p;D2cs*X+kVLLag3D3v0Rp^h@ zc#mg#5%Wh{=9y)k?)e>k1hdSm`B!txe0~14eEuxU=NHW%&R#YtuDwM!aND*l^VL>Q zo8hmHSDSmfh6^Wle08&4ME83BN37!?vsr6qnJHUlNueZY95gtzi2bfEAz5rxiJ|t z4a@x7_OgzDdG~yu?6ksP{)lXKd%cv?j4;nT{>T~2OnnL?Fw<;e7NixXfm*LPwd4PZ zZ$^1cv+_S=)7|{JR_J>;&9dcNic!J(qZ->8%a8r-t9ZxnXXvdM(_+F3e>?B^$8Bn0 zDecF{y?l%3Z7cjg^DXTx@w~mWn@WEp_cw4q$LU6^Nd;TYRQdOC|2po!h#UVFZu|l_ zu*%So2B$`3C967CSk>9o;I`yX?^@|gv=74O@N+y>{);>nHo-zquqDuBIYxi|{C=sQ z#|3q7bJ0D|J7GQJ71HnJT|dXCt;CG>EVp6{MzrJAmR=8IjegTJv~=h9OANOebH`dX z-PEYsvU#Rh#{Jm**!-FEi?E=)n%_RZX#Pz7bS`#TF+Y|n%O$mBM)kuJR?WLi&L7UK zoIjjjHOZc$`d0d%)o{~D%i4)$-n3Iz7do*_>x`j-O-+3V7s)Q(_ur$ksfZ7yQcSpV zRVOV&vm*sFTw{f#%(T~!mrhdBM=tgY4c+?PiJ3lsmmVboJkIg$PjLf7r zbl1w?Jvup)6C$o9Mr+BaDIy{~Hqo+!6-pjeXq@wYQEYR#*~!G9LNO@#3@-Yovy290 zr)7Tse%bYGx}AwFYGO=V?)hxS{M?)Z^_iPf7zaV)AZD7DcP5zcx3JcR-9IDrw z*^IlhI{69i1aCU|^DR>o?l{k;EqB-POiXvxgyrtIjuq~>jyvv=8p9;G6QW7Jc^q4?M7_M7 zGkw_L;=ERat5ftkE82lR^1y_+73dMRdY~G#g0*6nV@+@(pQfF$O~fblA)N0jYPa0j zoasZEj~CW4<}mF!(-!3dHN>o0*2xw=l`*^z%K)#cUE)t{uVeJ}qKp#(0&}Z{XUx$# z(>Xf819b~bU7)aNgl%H-6_)Asg7^8Z&=rtc;tg}EO-;bJ&CN{UYiXNViQzEg#p=_G zVw)W^t8%6v7E<-)E`C|;2gtU+OVbXk_;1%%NtV_|);@j3Yf@<|k(QMQw5&{&%w^U2 zr>Y5Coj(us-O5?dJ6)StY{zD%XyKMI{{Bd?`VNTqj`KU2#KZ~AMwW!Fs*93%b~8OF z+o`C_#0pHE818DObrgs)={IaqeJlJ2{{Gwhq?KND{amuG69gL7POQZ3$q(HAnJfRi zY-?8fY`S@hByq)OEuXa8c)>sI|Boa*BimX>K9@49Y^h7#NEUXWok>dzx*(EhIQ6H~ zPKCBI%mGmWq2EOkU67Q(ZHV>YWqh{1hNBnzWw)J{tn}5LsgxwWq4pAqageH*72Dcr z*|Sv1AZ@8uL$0vOmfIMJ3fMQkdE3jXpco`sDQZE*R!J(sl_asO5V-or-_ER{>atinhUK&t zs@>ELe7hZA%eORS=nV76Ksw7>y+H}f%pn*KeF28UHaICP!}!gzr&98ftv>G%l=0Ka2BS zZl_hHT{0xrQXUm2}PK}alw4wTPwYs?db*=xA)yT8xE9dy9&{{FAHm!6vw!jr=9i?^$I(6UuhPJZdyt8aSq zgG;ZTG}oLp)f@B;CHxQm@?lh<&+g^3X1q%f}@z4+cllN6=LKd1#pe{{89xWU zAcLe$LX%|}+0!9y_X5W(?M$&C`KHJT{oD~&?xdSipTv3JpGcC_{&Lqmj%3Z{JE z809Pb6FXVrtC$5jWy>i1U4~1wj!!oA8eH4Nmb~#bE1TOu+Ch#p<;zxfHZ5F#YN`R9 zEG|u9rMPVJs=2wjdzF=84gKi*x9yWHEBtNmxb6G0)oZX7R``GUhcDb*#?^0s=nFR` zpj(qy&&|!st-JViKFw3jd>fzwpj-E0*}@N0peoa&B&JZy96&!o_J$kx&hblaWwL+um6LPDmHw4kC2B&p z^731}+zH<9D_A`1%^^Ca7l_Rb9%gU-bc0)^`nHsWjY(1xhuC(ac`SxikuaV~8gkD& ztFic|8??Jf(OxAP2oAs6?`5=!JG-x$WKU_x#7ffB!1?)nK7XF)-jHHrwlry{Hza=0 z>VVorB^QU1xX}rP6ei!BotdQFgzZzAp_M%M!7^5^pQ{Y6($eN$%y!mrG-vs2FR@Z< ztuvnA%>9Y^*_N9>$zKwf7we3HCYKpR`?lV|dEY(XRWk0Ew`bIZUv8Q-BfBT(=I))F zlUG3|;*;zYSqXm(-qFr0mg_MVm=w3zqQ&oVp)7B&6^eisqULQ~hjjaR8m%^=F5?2@ zjFF~d_<6)m{Z_#%eb4g8dzK%Et0qnGU|P0`XVZYbERZNQVX@-mY&#>s3DgI5fKPQi zZ$qLNkdu6X#CW@96{f$|>Ne9-Vr5#<7P#5ye#@U=OKQSaa%q*Vbn-DbMyl9E#~kiX z$XE`{O?Z~_VKYFJ2W_EkNxM^J(y9)r9MCOPryXcl0Mg=fz7_}@Z>L;GiGa5~^Y#(V zEYHU*_qLrs-f~@LmgVo~y2S->J08F_BJ>O4H4wmZcS|AX$pmV5Q8|_~is`pWUhZ3w zDuM)+m1sy14E0c{AW1qg2?U3$5p`^0-i8x(nG@s1L`!zMvi{#bZR ziK>!a6kV}1OK4^lpj1_tSUWZ`kFzQY*6#fr)18v;XH`_tRx`H4zwyes$~Iz712Irp z(b;YJ?n!&iRr;fRMCu-hYWvuztTrNQjugtGP!yyU{{xbo2O8wvtOXbZ%%n>5+a>S_ zON0sqPzDM!^d=~*n2{CkSb|DY7C52wKP_)=a1vRA*!UeGWS{REk$i(#y`e=iq$v0& z37;>oOI=9Scas1&*nSp!)8e^a1FU-EG`PGV0T;cMeJe=SO#G_(vH4?d;_nV9PvZB} zm-(~i&zgTKw7Q@f;X2S$b`?pU5{xEVaD;eD*P(2x!Z@>tgsboLODTs4SBEH0cC(BkaVy@W;Yuj?< zPsv&Vn4r8?)GfEQwPLyDcJZXWcB5Dc_`sIizTEaN?P4Ew)(T}sUP0$=WmB7`pkqtz zv;?$96ALYwlWpCcY?k743rGxDc`ys<0AMhyu@cOBn)gmtwvBdBeP|t&Y@^d&D_CN2 z14G-e8h>Ty#V;# z3-qfwCzvRxQtqYa?+jACdx{m{Dp?6E0YIbCgT{NX~^1OZDfSwmT+2Dz%HQr z_&ePYD@Fhp5Ah$jWvkm@?xjQsx{(r;beGG%I|-n08|J;d<#JbZ^-Of8RX^$)a!XvY zX&`5wFdgn?j|?yYO5%BokTVvAjzXbz^$vEXs{mv`o4>d7x|R7!`Y`5dmbLS`gDtI{ zpMVf{qR!`m zwn@x5Zd9y0us#qy$poqH>@Dw?nui)m%EWLgB%h)cETLy#7s~1JxiSM+??fv`5JfS z8EENxOuI#11SyC6e0qR&IAOWjlo19jT9!NEb90CjTe_<6glEHga4)>1n|P)@pB;Ig zR3bSOYo&&R-8kXzWvDLRiD=#|O*+N^WKWXZEg^TW;mqItm#}nNxw+dM)8W$l?nF1O z+*CAMMn#%gnqX4@i9FxUh(1SC8YFp1HtKFue^v?|M)`HzUC%9V#zvW~Dai|-rB%z! z*LYg76<6MZ;hsvXV6qjnBu#9Eh&qdwbSM@I@GiEqAnAS}Fx0Te`nDX_7vxBb^;V|E zR$ho0CE-O4kh+r9Go*v?c2+V^Ly!1$gF^nbeU_km4;^k39lZDOK5@s1?ZJ9Ey6I=HfLDE2NZCogD&+?`QfybePfr+cI z+nYe-H!r9q^fZ+Lv-CWzqTiMq3|JEHSEoRgNSS&aPi!T>p04T#U_N%Dko|?{Q1F6? zvKnH?u^rDh7ZOg;wvsp_s+bXgEYep2mn6Qn4fcSfkThAxS7#bwzb2kfcj>_%$zR2S zi(=pjEfU@0%SevmX(`SpCX)pBXuT_zJSWjmnZvBwQd}$Lui;kayKIu*!o#L`20;XD z^2WUZsjyc~{`38BmXi-X_>=qou0HwD9d~{0n(Ggr{I{?E=;pV6{q9fxh)sg-R9b+- zO7xk~r))K^_7%%JyC>x}*PNw4!b#i?TEQc%kh~@al2^*~2>pf4AcE;H$wnaLO#R;x z2o>INAY@INVHl&4mqKzD5l*pkQ|38L1OWm)vjVsSu=!VXduxRP5DzrOR|pHKn5K3W%Xd2m76?3XyO~$pnZh0BKx;>tz_A1p2FgxCRy0 zvYnoH^*4p6V63duzFN?C2kKy+5tk}6Gv?_onQ{VbK~0E0(e_NHTuiuXgSm2+1S>SB z=NinZabYs%#SFfal4sUs%2ztTAxQ==ne}PF{dpV2S5ced4-rMxAoWl8P>WN;sSNuR zf^x>pk_^pB`QRxKM>tF*1NqxLV~Tca38E*+7=x)zS+Q0qr~F=KPO%~v7W~&UJ*9$a zNV+oCv5dX4(ky{~n%6DM1q2xL^g#I~nL8nMZRVoy5>i3jG%*(pL&uBF(RQj@e)+ae zMy3VTEvzrXS9Yguz06P5*)=l8rVyhDX|JO&Wi z+FV(dYtQo2&9fX_WAb(SQ0BC+OuIP_3>j;Fx~qS~MHx#(hjwVNvK(@8xs`FZbgCO1 zp7`dTnsCZ;^8zx4v=pRUEQBdcpLsk1Xi*uXD^p>aBvUS#!W2&jga2zPS8RO3 zC$rx4%qgHGYX#GxwdjS1>0N7gx_P!ff;3$R(cDd=fyCDu%$!5B{#=?P|6kEE&-|R| znY94t3aI52St*7%afx|aCUaU$n=LL}haEo=(ZFbGGA$RX`ThU(6^R1S- zrb{q==DFH6Gv;9WbqOduq+!5_v9nL(Bvqr*Oqz93o|3_y1^S1{QdXGtR+(jKV)+!Y zu>>eBi4T}jf-5q)Rv4<(4UDvIso9hYcSGQ9n_;dphgrU*tB+yMTHcNHDYtA3Ik`Ov zCLU*T+01BX^%!%BYr3uY+}vyGe_AR_1P!=mz7905l`_{N}mdCP_>h(rN6E z@MWy$1~X^4+$(yOv%LoQ+??x`d6IdaFPrChmM^VyEhY~9kLag&okf4jMHT;&a#dBU z<-xy7RVr5fJ^xCgT1~|7DNw13sy17(>>3qn7B@5I$>w>Udxrna^L^0lS-q-7-_eQuIouP>SSWd3SZhpW*!#B@PWG$r)wktSdo8#OvxRcv8hHG4YA-C&vW$* zjC6C#e91h=Dfa=6rOk3ek~gUd^K@;V3;u;=?s>kxUe>N=&O|*W)PqSzO&DpXe8rqX z!ftRliaekqOP6D>-6Fh zxkF5mde=>rm~bLvu9lIY#|x92-w-ey*|rQmd&JY3-*fw?e+C?7h4wOFJ*UH{h00>V z1dmq$nOXr!ZO`pLf5(?Uc*BQoV`q2qTzD!C+BKx&Ee#HfB?P8&L#zN#g6WeS`pj{# z7qJxqdN5C+@0_rCXk%M2W5n^2Q0>N6Plx89FTuJa53o# zCfz*GSIl!P%jbAKfuI-JNX-eF{fwDSQJ(}0@yxtnz(}S7{Tgr_UxNFT^4vpyJgwDS zD=MB?o_Y4j+-r@ob+t^=zQD*z_gY9!^fkz^KV&Vd;Amo%Keli;S>Yjd$PqAf1UN{n z8V+<~6WTeWehXMiGqgMjwas74J()^jSki!2XfzVDc7=HsnmgDh3hEGnM3BD(TJBXF zgq5`3eS3&)N|LSvmg9d~-b9Tf#5?q89|QQOB6_b(LUu6^E82$Wcem( zqikU45$#qZ%Gv7zH4$wqJ8@!xsS=rjb0iMe9imyjPs6gRT?rOBK z%-I=J6J~2h&g$lAv_0HwIC|uE(f(_7Q<}5TPq?7}7vJ0@FPYFAm#5Ozpk$gEbB1Lu zZ>PdpmjjPiTY81hlQ2(Ch(!@Y{4IH;*SKAtxm&n-zV^!PB14x|=J{U5_DUT@alfwR z7Wuub8vyFKUI#;tb&64knCC>s%^M&VzY%+FMPbz$=x>3TUnIgoN%kkR_{>jTSq zX5JP{M&LmH6lxX&@_T&gU32*u_7V{MDe1U#OYgM zHdq&IyCClCEjPzziYLnCJQ$i5{00j8C~&tQB>q@>h_m74dVwyuF^o_omX$ zlxeyOnrs<>Ygd6%TYUIm4~XxJxW|3EYSLb$17& zqZn#1zu{ddBf%#fLTKTjW!?Izpd*u9xpayYi(Y3F(}MUb zoSwo1tx?6>bMtInTyW$vR-f*{^O8RKboYSjHL$7B66ii!iwU>B!ALYDF}Ulj+e#GP zt#i#*w_Bh#=3J*U7DPkHFId1WQip3Pb0Xz#4t{1l*ds|S@*CjM=0$r`fxHe}w%`F| zj!OmYdP3Oz#umZ*T`R&qhdZkk<|&P2h1LtCG$O86_+%4y|1rU9?Te4#l4v#kM)E?# zAW#g0nrUX@{EmNVmpnW9f&O-IWg)X^aJU;d(UMrR;JunyEDR&gA{c^bnXj7X=m-;N z{dg#sIz*Xt{OOzV?Kd(6d06IOQ-|&KoplO4c@O>gn?|eG>vi?_6tDJ0-^sLQd8V^6 zAt@1*OGthRxNTx<JU!iGyuripuTRwg78W(^KV5PuT#s3m@kh^Rnj$dXakIxXu0 zv4oUL7B>O`DkiZNvT!q7wiP@dEq*p>n=x}fEbD2R+Ui%e+P31yTb<}57A!~+&QoE) z$?=%CgGFRj7*=)$MZa)7$5TbX9F5$)H@tc7sy=*CiKYDdVA>X)1MDH8 zyTLya^l)GhQRF5NN8@PPCth@Bx=pH4YYTI_m~9WRQeQ{otuz;}uu8k&gmeH-+8?@A zU3;Z|6AW}>!Zn=CLWol)$j#-4U)*2n`tN@92VxqFR?b-Ao;K6N*ox>Sj+NRWsgGQ7 zZ@7^!=)HR}HN}|oZ9;R=4H6{m@b2|sr*Hy5kIe;9L@u0VzdTB8=`kInyqirtClF0`j{PvZ9{>?>a+hp>A2XFgpd3Mi+ zi?@`|E}W|2al4wyOvUY?Ol2yetI&m@Cz!EJn!1&=8$#3`63@~G!r>Z?K`2!Shk~67ZrV%jaSF6*UuqH=VY+H@m4bgrFqdd7q1|w z6LMvc=1@OvQg~}CQ?<(1qE)Fj?H2jUK=^eM!d#>rw7dw&??mbp9Ds#MXnXm+6loGm z(5f|KnJ{%QzBb4|E?C*QU)SoAD;jy` znu;xh_w<6<6y~77%sDBmO^tI^DJHB zS!z5>549`;G_C3am-wta=X}U&x9Xa$13O*C{NiQW?mMW z(V*GEn`=%6j}3nhYmr-Nh)m_?73mmZh;|G(ZDmt~IhiT=xg>!Fw}X$scnh&O1N*B@ z%+gHS#7t&~1mYxvJNbrIX4+PD(k1o~YdZL5>>>7$@W6D4%r;NRbWxG&q=#CK+o|-G zv<~+ddJK$}s$6xzt5t`zQ%q0TDHM%l6&mFMeRM3dNi(Bxv>LF4GQ5XYvsyE)*)rUQ zZOt?DiVT4&6*XbU8ltYWCwwVHhPWrVGNK5_T-kkscRJHO7^Zp3yh-cY)-hePJ$PE` z9&t4@G99&%>ENLLc1iF#I&`f#6oOZ9J*ur0DRfmLAt<&TuR{))Lr#B{I0aSfn+#oG?7 zkQA2GOeGd3d0Y|QiZbu_qs%)J))WP|D2TO4q*T7_6Y@fmK51{U$|oJ4m)!Qw`m}y6%0obYwq`4SO>0E@8WOK$iXvRSoax24jS5hT_=1&F zp3eg9!Bn^m+I`B5_z>JQC;d{e(beMBB^GLIIOJXKjfhm+2A2 z6p(Ei`2CF`C4kt{ zZ4xNLB3Y&v=aC$m7l+^LiiSrSv}kT83GkE(>Kg~yDm>4rS$)p| z;AC&Gyd3~5g7Ap9Vx8I&Vs#>WNUSn%;z3W1cs7w>0m9$$b0FUCWXOppYuAX3z`We^ zb*!dc!@L|A3?-0oYp}nWzd`^%Y2cBD<>ZMVfq?~8sZDJR)L*FyznC-%#Mc&lH#|To zFX(PDeDw(Q>Nt&II59~X9J4mIAZviR`_Dy*kIIEXK6*IYVb)Fx8e@?B(PT zMbV5SZ%d2y5PZs7g(Mdpbj_~eG7f-s659h6z5Hm|gak`lew1j!Iw@qT-^7`zn3ra< z;{^pWg%vLShrfSl=u|B(xte8IJGDW*cug}?+h7Y;Jxm*X>ab92Ru}{7!-@5W$;XhH zu~fkYj(4*pc9mjml`We^snlqL(N>yz6P^{=^4cm>Z}t+pRkhM2gIiU=?9HBr+%mh< zO8`B!;6jzS=XOCBr>vL?(qos5Z_-!5;%wQQ*&ZzaFp{n@7iWw(Rs~E=Od`Bx>=bz@ z7T{X3(ybwRz^yqzg~``g66Xn&yMW4g=KJPl+P#?QuK?F^O9&+rRt7nGJHV-mueac$ zVLYc82L-7qc&ra5Q4(SSxr!yWq+?71MW~f+m8A0o={;=Xf5WD`4PmQzyjsYgvvDWKM|H~w!%GiQ?IZ-%K?lQ^wZFBV+ouC;TPsPsg?Q@k|zji zx)6AbEP@BZe)D<6w-N22@-~4+fu5DTC|o4nk%dEX2EJptZ?uYj1M3MJUbSf}m@!i) z*V5x#-Cp6MrlOQ0tfUM(`GwJ_)ebHUfm1?PB)!L$NqGV=+O@-1(!07rm+4V3V^lNa z^FXgaPa>a!P@9n7d=g@O!jO}$vZyI>CE}VnZ5;4FOJU zN^}=HwnH5^#?*Ta?vBLzAUbn=D+CS@zy@F-$R2y&G*_o@SIo`LSyK!A7@C?S(5yX1 zO5Q3$rYuJu4ak%2G3^jL=gq8N6t+8*Wy|&7asmcPYZ&m(pC( z*EM8C$NNz_VEp5e5sH~^c+5&Dw1v;3rPvSzfJCGT7czxFk3M|T%oE6WT_SK8|5L>h z`!}?qANxI|R~&bG)4`1_&YYZ6fdy`$GhihXF}E+Av= zlY$e|{Nl9kEjcTfY<*s<>+TnbU2A7004xpi3>qS3aNMc_uIm;NLjcq`fxV#N6@M@5 zf*f_dn(bL(w!wS&5-4!+YevXMDW+p6dG@3R+yl2~2?%<5TwHg*m}v+gCe^I!c^BVm zwn77%m~8|^UP86osuw}JhgIW}sX#gssvn~x`ly)v1{1SACEoz@k}89pNH4a4v(>W- z3B+W~0rgO;Sq;)hRxLcvZ3Steyu|F6gKSg-$5FO|?}0B9Pc6I0`%2p!?v6tSG=&e5 zA4koQR+)rlm+`I@ zxCAI%tQ9LYUO}@!ys8K_it`gD-EwnDWQ<8HY^%10lm@nBF42f=q#ud7gnT2Bk&R{* z&eUO!EzKX8)cu0yAig0nm*~Qd0Dd?w!VPE zC46nx^Ii~h5oVi_Y@N#g2eQ5#mGxn}#rO=weW9NXx3kOKQ>KVh7Yr~W%ptuE0-@$O zW^V})^X-`|B>OmmPn^Aee!ZyZpe-+^>rvdI!Wp4&2ZgQ87dd_Ci)R3Kxu_p2HwW zeb-3a4i}NpcEuR^ptLW@xgvje zVwW&3r-yM7QOaN4LKX#oLW{B~Q9oiVr)T$m60>v|Q8LKF#RnO?_%QuSOh*ONOMM%H>sHR!?ck`S(=ud+ z^>uS(FrJt@xX(;8NU-kLiVSXkn0s z*Ucd*Vq8=(zDwgKk$=cbb42uK3SyKp4y0ytK!Ms>%oDR9762|4w|+4&9i)VjzG{vI zm5io$*$z2jC|ou$bc3+fjkNaHv<4vofq8Chb$eP(Oj0@}ugnp_CP~V+-(a%hCuqkn z1UdTCi`Qi;_)RFYJ}b`z=#9KX3ctFtIV|N`Pwsi}u7_^sJ~2nQ68!i)HxF>yHnv1| zdcVAFOC+u){!|RVN4T|Pe$RvNeMtH}55E2(Nnw8s6~Gc{e!^3wZKC?F1SalzXY$4e zzWueY?Ec=nGvqZ;6oB#F_rLA4KVzpz;AcO*`)7Qu7_-VB(oW(Nw}0Ym|MB&G@d;mU z>r74l{Ht%j`Iaw_P2Ts_&)xjpufOZ{8z=wuJAd}2JHC1Ckx&O(S)~cNtCc0q@KniH zeA(h^lbly_D86O$Rqn3gDOVHjD(n_=>>an;-a!u(Ih(=7?xA zuhU@N^Q|}j^eY0FDN&_43WEtXX|>5LH%DoGJ}pCcsyn6Qt6^=MuW)w?z^X;TR~i25 zCMdyazTV2UUImBkMc$5(DmCFg#NCIvxsE69gWTPU zZ(6U4j=H6(xIaT4x?=a566LfZRE7db%o6y+>Q@)RgrI=KOmZ>st3h+|TAp#U1n~~w zt7S6&QLyxqLG+It<~59|p9Um+L2M6r=Ozjs^pLyrRx|i>F9Bl<(VYir36Cuq*o%0l z=v^pbd27(Uw*!h-OWAEui*NbF`pID}C1AN8{yYGTr z3L##F;tktF!{swW>X7L6Hcap_$PF;yFfove5MCsulELs7XJJf7$Av;yyjg%_!|%0E ziPEC=nf&i2Kk(zf{q-HcTy%Gpg z$_qi(XCCtU`44;(+5H5FK2m4JqBbP8tHqbxJ$wmeNod6D_aAUQMpEDX;DYPi-~A7_ zT~1Ofh3@R6433I^jCC{Szso4^RBcPMy^ef=O4JN)S>b`GbEYq(Wk1ZV5?_I1Ys2b*WWVmCQnAg zFNcAb=B@CO%FwxEsGq0d>jwI|5nm|{w8E(NdgRWukVL~jT*Q3O^t$l+(GgjYEijXK zBh3;Gq-Xk_Jcjm6kw$neCcT6|B}#MGA-fv%=_axo`5SrLtn`G4HDMo66aFXnmHlBR zP5ghquk4qa6wAHbCi|Rm{!{mq{SuSLbmQfAv}c;P@fFGBum6jCVUEz?wZsL;hExI# z_8U!xtgbBI;4-%=YQ^TATqA&JgG0I#x52!NYyIXz9h!CHo=sC;>wFv`gDV~Jf#{@) zxU3R|!ulIN@P+^%@AP9`0D15H>}@|QMPM2kLD}RxKl_c_K6T4C4hQ97{*(89{bwcr zsek=6cwwoPfy|VNMb+8>b||wK?{uT$!E&bm6mel2!V13tF!9g!iFOcy1^JJ5VmcX+ zRTb=BvPf*6sU9V(>hI`U(Ils7wIgGsLYa4PT_ptF{8{|Q@$G2lGEypSpq^%V{!#A6^EYuT@;7t66yi%p@q^}O_&jCqsNCq6(CTo{6I5_axA~-IIYHJb6sVVp#v= zQjIcs>W+eE^-=mL=AIl1cS2!`SHqtU72=)zD6JnG1jdJ7B|Z0da(9ORI&)_<-BA>< z>F?xcHZc!pfa!Q{Zsj4&86mu{l5Kr?5OB;*+#B<59tg*#5Dh>1<6Hlg)H%p)AEZ1d zJVXH!*vn=DqVi;7=5kvm%}OgB%aF{N6!jn9dWDLSi3qtAAzN|I0xLG=J>1-g9L?0g zm@@~OlC|s+Jy22KRuT1nGR#}-I#ccpXojiwKint$efxwv!*zO|O=pXm^JT`;#s1EH zlz%BT{zv-+T|318IDT6aw*sL3PF8oa8#2zeI%#9T@|?8wZk7bQM^*+RT}Fa_HDNx& zN0W;Y<2E;rT%$~J<+N(Gn!tKDH*u;hO|(11nT}i4fp2kxJn-oMClgHAZsS_Vip_9v z3E2c<3b}Shx%#p(Yml5IRTkflwqy1Xq>{2@cJci2cFZmbiKXbSqpW@0n)zer&zwJN z{=8JeNZH9MNHR`F5L-dQ`Eb&L0`P7`Rw2J_Xrh$&7zu;V@3cW|C52&97UPJ@R05uY z=?>{;(h8OGa*#5?mWx0jo3zRM){Ldn9cvRf_%9;UH((_AqA4$0WdA1{z+8#Kry$UM z>webpU${TUQ~6tOgI$z|s5R+#e^bObUe=`&w|ZHPrJ9t^YiRa@)7l?F?Zg%%3Zr;Tmv!xD@ zO-hn2Lnd!`nk|KS42ivkJFT6weB2%7jQc3>xHt1oJ2#+!h$geDh#nWV5gb>7*K*qN z_pmLGPEw5g7Mi#aF&?ba-5g$WxM`J_t*q9}%4Vg%f1emGZ5v#vC{wj#wpQeTPVgfn zTmlqaia1OOS^#sbZJ9G*k?-Z&F%27? zzJ{S)rNNwu{K-iE=x~i!biHcpEu?Tj{(<7X0EmMx7<8lt`N9tXIf~*8#akij;h+BV zH^~lPnVsr3^?8(BAEXUb+(p&1P@%Y6WQ2_mYtYHICoay zn&;*de1-m!;4&nS45?Plp5WIdb8m4Hc~RG7|3JLS2a zlNdxqVU9&roYW-lmOxD+qgzM1&d&SjML4O#YCgwIUBBK z5|2nc5(4f<9HXa-V|Hpqb8AIs%=Xo+N_jP+6+DK^;AVY_C|GwmT0)QZ=0IImKOY%{ zMi9a=?KZ)bsAyI;5$KF4JxOWh5-Zx91JbO>vq+My%Zd&%hmmVyd%;H2XNK5>k8`)u ze5zQo&XKGbzNVv6U0iE}#wRF4nG*Al;pno>!5r}Vd&@pGsdFiF&%g!>#44N?;jQIC zKEt6BgM6IsW8ApOJ@!u&bc*Oz3qFD~P|Jj*u)rM?<6 zD&jXMmgkn(GCBKT5-Lbj(V{rpo(i#?tkUr+5DF{ zK&KB2sarzHUE^{O$x^YV!8QqklM#_xE9$}cFXCdTPvLWUR*NjKMwV3n3PJq-z`tRK<{;l)Hgxn%o5hF|QdOi;5|SbYKCCg>Vmcc~bip8!|pimjl1dsz?8#F|Dc zq;AyiZ9Jq;q0HEf(ovzgh&YHb!-!#ZV?M}ca55JZFMd0t6obNzwJA;UAZ0zd(bG8=QeqEw-gN6BWoA&-LX`F~@m=V#x)?bjc; z{s$lbC8N5lICZKB%x9tTv`~LQ{qwwlg4C8GE;@r;5WwGBi@fn#m?z46(o*)F{qg#ppq42IO*q~?miP{C93DqJs z9|ey`q2tX>oK$X}A8i9eCauyh@xpu{?qk~B(7KPoBgYi=x?@(ehd&~rB%2R#w-WHd zpqG5An;)%{fX*Y|{GNM0{BqOt*Eg(r!M2NE*a3vMbz_Y&zsMX}C!^Tk z+(*VRFI#?YZuz#|mlD>c14E&{BB6nraQ_Y8GqCiKQ3~JuW#n*>zm03R((K_BdlW(% zknU$a$L#QSF-*wD9z&aaIIF>Sn{nI(Byo2P@vV**5Wmd(IAIpWnBBTh(2%`9fB^M_ zj9fcE#vKFCLCBhG#ltsAcMS4yKl~vXiqn`LuO8Qz%?qxvPT##-p&l%7dEO}C%HssqZ%a6A#e0+@p3F&M@dZuaM313C>%XtuIJzxuZ63a zq8vt=^nVH{4JUmJnjiE5a~&u6GmMFBg+x*mC{IK3*Y}qF5hhLM>l-fKW^o$vY&4>J zZH^2+66UDMn;sblzC;`5A3pKW%{=axI=0IJwsmZsu%4lcnD=qV(nTbXstI>uKv_;C zz71UU-F$N2mmhl9_cW@(h4=7;7WX8QcHyN&DYP?Q2JP@fpj=-BBITG}G_5Ag7x+|u zw5H5Cv{xWDm|OTjR^%`))+pdJUE+D(Aru6mlNAY+IMC+b3L@($YgtyN{9|Jjw>5Mt zAYo<99F~?ter?dS2>g_6EhMFn3b@-q1n%8@^2RU!^_#9$)Hie^nXfmW^SJHy$8WmA zHlK6i_QIF|zp^p&Rh}9c?#u2fo-TG*^Hkf4d-_az2-vwb^om1}boC9K0-_MHoQS@= zm_oW1TWt=@gjtr>2W~cXi##f}jzkudm*X@e%JJ&u?C#0E*Uru1(%br11tHINvT8Vh zvby`)Nq*%m6jo1p^;i);ve2uUxh$=^@$|3)<+Z}r?V;u_?p6V%!Rb^vv(~tVRaLvd>XD6jV5L=p=FdyQTPSGBF6vy~Ai37YyF!y9Z3 zIPHRb05OF-nWjCcYn5F}CzX+9 zQH7JZ=wLPYaSe0f@(3*kkRqAs7S3n4^XVQ=MWgf5V9_9ptiq8^mNiL$rL07^^Hw)# zT=B#WhEZ)$dhY>*O{~NQuk=O{ff{#w60%pV&m_|6AdhS`=!aZ7a_Ij=(J_=zC**TA zz(DbMR-(XHG6s<=`b-nHRx8chVNMT;yyFQZDkm#UCm*vce}d)txt`}2nVz|wB$6Ax z_P{q^mq0N)AmJQnTW3*%qrp|8O`pi_EAK1&qE4$Lg`N1&&@L&okWun4q!y!EDI-}#CaOxE2dA4&#&d~T0TYWKZcjbyznMt zkr#&^ux9$Ge!@EhJN0^QUQd!22-L#{*`3D5YW!hhT zPuZ_A>2DQ{UvRRh-m|almzh-iPkguRSH(M!hId?Y?nN6n(C0veicpGW=9gT%68Xqr zr{Smn+>gt?Nfq2cA_c(W5?D!)W6()sY z*Z=Ulflrt+I#^i&`|m0 zo_le+UnG}2kV|BcIuSX%aP5H~mHkSSMsaq&ZeMu8))#iRo_AU{B18LEg{=qC6;6gx z_Wk#J%Kii*+u!-zmEXPo&kRlaD}P8e>YcQ)NeaA=M{hpey z#I7enu=l+17KpU5nm+;h*H z{_%k_R{YJk{PLZD{!?7J;lp=)0|#RX%8$-l&ETxD5lI1<|JHXXp$GYRwBb&=3)Ot} zGY`qhJr8{QjsN+LeV^Jmx#!L|-}gZIfI9r%j}IRWXK(~ZVsZuRn4b_puJ1hzVLF$& zstZvYX*D`Z!2&=TX~)c$cyXjvh?WUQ+l|-)62M0#TXl;m16x9&l`XOc`Z+9$QuTC<#i=?7b4kcKD1x&@zT|H?%thfCF4;AEDSMwy=pY;_5?l{UU zKNjT5c<3EnBVU9N4jA6GJP=1U@&<-C+!pc!7FAO=kP!=$%zrDC?uJBUuemC#-I8)! zL(E6v8fQa_SsGsC7-|t5*;9Q7kc!+U1JX|%(( zfcGDqN2+ddFC_A59l#fYQ{fmPZZSX*;fgZA+99VKxqE~oRdEbvI6II2n70Q*h>cu? zIf(!l(Kc^DzLPARa}!Pjr>HsecE0fS2TOq*rBk+Ok*;Z8k%FnDRIXI{z$jA z3|^kp!?11rB4E~q(-sEATpLEjTnk|ffm{+nS%OYXB408bVm?m^a3Nj6j1(X!&+=9J0Va*&8G&2Zds|YZPM=#KEdt!KWTg(E2c!Aga`i_sh z{YW~-+QW&UuC-eX4ckHk7ZdKH$a=qw#>?1QjubjH-XZ@*%^X5%zWFkby9h9m`3O&7 z{x6aq@;cLOQ2l$juGe%}-G7oYJV0)-Cn8nDhj|izm}7Lks@>v7$yFPb!GIxdfYydE zCwpeD;PnbYQ*N<4BRB{p@P0_V^)3Mc`-6y$wf;*+{#yS-GO>g_<56j-cRr87;2Z;rb;l}>&lfdW^ z*z_|VBQz#&eDM7@Q+x~w6-8tQ1x9#gUQNPZokLJK*Iv-u`l1Dq9Mo*{N-91mO{sM- zA;7#BlfE0xd0D*N$rp!pWD^YP=rJ)N1>aOD*-a# zE^g34C~no1W9}`ywZK&=Aj|%A{{wi-`_nBmIfae*eJnr(ds&##y#ag6-@?N#{`U9F z{;LcN`>Q`J`y8S;H$UZ*58VA3nmaOs+_d+7H~-yND$rj%3wQ7O@B<&w$;Oc#84f9qM3Y!WS`GoiGQIUqMXF3P!%Ekiii(I zv6+MN2TLnLT4MO_+??9n3}K_CZDu9aBh1NW99UjB97pSqNJ>B;CmbCB6}jJh{VyK* z)gzBQ@+*A&>C^u7Z(b43n9It3Y<_J1%=tz0buLuJ*onEgL*Tri=C{u;nm^Nrb3)I{ zBq5*@hg(s9VuBD!M=g@TDsi-HNT*3>pPDTcgpg3&9t+6{;1LElC|jBiGB#rALqLb5 zfDVwiv)$S5CE$U7#ba&taJ+K}t}9>}REC3?WDyrZ>Tntk45ezZYleX_j`^gWvxK4u z!mT^Le%GhUlOMR_-Zwt;_hEgR5Q%5J1C0p82$iENxLG4`4CU621evEbLhj4Jh z%i*s$`TkeE{X;k1`RzB{&O%jRX6snRF<*rbG5Ki>Vov@OPS0YOzbhn8Di84KXnrrp zX(|=dWJ@$D&X(dau7peqiT}DBv@ru z5iFb((KGVESr|DE3vCFg_0q5@3qJ)^QlQtm%AEAfJ*%m^MM_f!=4QJ2$4QW1nenOo zSs@yMQVMw6Zf7jV={6v*?fg`CYChrUcD}Sy@4tA^oPnRq zfrpm;o>OdxP38H;dh`%8`RGH;M1B>*MXu(9bJAiI5L!YeU_vCLS01#JtI)!$k<8~Y z@l12(UwbG5PCW%(&NSP46Lm*U_e4#HTeq5-3qfTKisWw zhi_?cw}Os*Y2h1&XQS5onIQyYBN^JvU-L0-{yXH8jh>lr;cT51!GG@&7BiP&UGXtj)tw8Po{63o%S|97}rr2EfScnRb^}hxqw;U4t|4G@K0LW35 zYs2R~Rn^tq)je}Ed#01=(_Jk@%rXRI30ux2GeZaveT~0K%{Z5fQ~3G$J3Ogn$dkE}NIQTnxyX5c>CdPgTz(;{E+5>F!!iojP^uEbn=j z=OG&n6&}jC`RXy^u+Xp*%QAPS+5#)1LdH-b zFhdNoChN!x;l!9{u;`jkRLpU{c^!$E+`&zafXhJ5O`QQ z6}y`46nz60rV>n;R4%092j^;Ls;|6z-ng(1e*=eemk>O~4T%6j5l+q1b} z2Oc<(dm~&0^%Qyh%xRtI#qbd5L{0|~#nf+!-&hc+&BUPFhyxUe0}L{v=k-5*_Z3## z2f0Yf>v`@uvZmnCkoKh<_{Pi&k-EZ8Obleg`C01JzJXn0df8uH_FKCinLYdKlia*2 zUsq+STM=VuL}a|jMUq_|

    sn6JN&n3;QgMe4P^4nKR&7VI~T=rand=9}~U`4)|DJ zjmn= zyOMM3Q{H=`&p37xmb-!4BmtxER5q*~v7j!`5XkRV<2Ab*K;FIK+_QP08Uqx~dTKn@ z@2N2`E$o`y0>;^BumU7#vM0T!r~4}h3xUnyVzNgZ%P0UzK(@a%TBs0?iJH`NRCMjY z%=KamY@;F6b5xKKHjb{EKZrQNP@Ldt0;3@E@O7fk5-j+vl+|#e)lLOIRQ;T%XQuR7 z(2F1n{jd9yMgbfBHsshgJSKlK-54SqMo|GMwq?VG7A|B3BtM0%grHNzd^YuQ*#^~= zgO6bW#P$KxU1^ERXB&&>tBB+o$0h+I5-hD;JKrN=pUEtK;gcf?tkCO(Dx z_vmvzRb?MBZ`5J;taCn94NCt2G@uf_yL+`hAZ22gSy+$G!|_B_w2s7>n0AQ1y6_ec zB$`y49Z76@OO{o?i;mEGl*c`Pz>a}2X24`f(lhE&)Aq0z1#Cy2Hok%pEBDbr@YO)l&>b#DH(TahN)vu#x~yYTq5Q-a}k|z5)E_ZFEGGgT0(1 z)UEVhpV`L@ch^hu0QQ{Ny}o(fkeF*_Mbv?3bPy3SqZJulEqbU^xb}H*NPL6^T`okd z)-v)ZmsTw>nNgAy7I9(UK$bZ4z0T#!g6R|irE5_16#Nz$zYo%e7tO@gDq|PAI3{$$ z`j}S-w8ip?Bti!Mi-Pd2<_cBx1aZv!SO%Nup%ecbW>Roiq#lS@4))f_j~y)QD=!|L zgJ||9J9}g9+atOjGAG&7{J1tVn@Cfz-KChoc(-*5ht5A|gXH(@D}u0j&ps@@^_*%o zvLS^4GLSYh(N#qw+39Oc+!ROWv4e(cuds8e^%{*qQ;&)UkfI0bTF+z|6Z=Q>Me1hjIr>|Uq7s$34BCcHyv*7pJ7w3`oA%Mz>(~-w14VMQ&^)@f z*}NbY?rhwdIeBo|qH6KPX*$(CfAzwn|J`ahK*{UQG|zE&aZJq_uvL+f!Ol#q8WCwq zW+t3_y>?F9*|@V|XB*2Ij?MSTV@_XnoEZJ%e4)$YwmY&(lzCxpXtiko+iOH#4;WI$ zO=aFMmxr6EVObiPX9#KlXmf`Ov8(f-PB68XB^2`JvLcGZu%c(MUlvHz?5sIV@>Q$- zOw0wEaINOdWjQ3h+HCrcQ&um-cdX_QnBgBfRp8p&+U8tP3jvn~RO+!cD2QeVQXvA- zhkBm-6N_F(#nC>-trTgsRg|EKLQQorjfs+q`nYii88WZPXuRw{#@;ko6h|5$+mj9l zMQuHhi7_*TIxtco9%RW_tY|bdVq~r`x>2$`DyB`6q8$8NBu?20nkuY=asED`tbh2N z8!x}(k$YbfY=P=|^U1I6cxMYkSpmqv*%`Qvuu+y7wA$S80o3aJ76VQ6e@xLT3@ciw zKTzFki-VN7ABPD`aV)~bC=VXsY+iKCglQyHA$Z3!<=6yu>>6RMd{(Yu$nprMR(upP zAK=IwbC?xTA#(D}5Gj2aK5mbG#*Jrm`x$+?U7X6;V~6kST6?-vF;0Xi+(XPXwBg(y z`p?}7+s}%Kc>GUA+W;QO`x>JkF=8IQZ5tzw6)#fcE`QRja}0>wu2n~+D=f7I5CkJ8o?j6kse*j13HB@}O06Kh6ojH;}o$wF&1FT%ttx{QkFu;Q>< zXH<`+ygF1DyZyi_3TQiySr?&DZKJt{V%|T2*%Q|4Tq!cpLfj~V;nBjW2#?vB6U_)S zijv)ZtRJytzH!>w|**QEHU^ELqzr<|yms)s{7Wjf=4L^<6{l+hSo{t)LfWgH0 zl$?{R+M`HUHjdiHkV*qp8!6Sj#0(E7%ZyYNuCU$_x3zMZZK(r(d*}fx@Veh7c<5{h zKfj?zF^Q$79s!mq{!#X)!~SUd1BZ45r>nQ2XdT^Dqnjv_aHz7_kXgSk7T1xU3 zF0Oi;_|(`PHFl>ZXd)UiLcPPKRUeS1;OhiEF)+q^s}VrQ+ZJo?Z7k53GRwtH0EYzF zc-H({-?&Lp#uFINXg}Ez*xyMum?VP%5K3hA*Qm(og^UlcoeCdR_FxMRwt#f$uUyVH zlv76K6AZQtbWYq^hYUC%p% zT1*x%-pYwM;kCq@TFdY{yE$1q z!GU<^4&w%JFultnR1F3TOSzX^%^`hmq$06=a8xM=c5s*mJhDDJUrLVCh7sR6OWTxr`$${xDr&iIf3B?I+ZGSTS1FWU>qT5EnPDrWpq+@fFN%{UD8AKam2 zLrVB09S6=(-~qyy`N@cnRs4PUp&T4Rkf-_KZN7Qx*SnM@xA{h3k8*Hr;566V z>YH_A(%d_`Pq~a6r8@gI-)tI_>bfyGA+pr`{x;t{eVeZ-7a`Pr=MLZ8dWSv0E4Ptb zxQy4|!e!)ovP8T;73Q8>qU<>HEw}h)ZCnJH|Id=askYq=)12r9yef{ey7D9+utdq~ zJPFK&que30>G68Y0inTBj2#O)704=Q$$|)v;w#=JBlnXfBtg6SBm~{oqGN_1Peh|R zD~iMhZhpzZ>V}?f9>zIS2b8z1!96}T4p~4thJemydhD$F_lB#n3T>GWQN3jxzbg{Lu4Uq zhCZrHg=EZ&3|0RW;TJO6okpxhnMM*Z5!1*mCgN78rP@w~2Aii3w$p*I1$g0^I#_xJ zv#021`-RVX`*)!)co%-*?~?i}{(~bxy-O8CtL(7taAHT>lsK*%46TADTB`SO^nEIu z^DsD>JEVHU9>MfbuBc(Sh;jxAZSPXgprWOEAIILSUw)m3%W;G+=c|29nCN_7+p4!M z3T1z^NvtGCG0cA>hYH9_)ca)CV~?$b2)#_156EnlVT*AGa&ZaGdje_fQx{S?!6BT# z#)UWlh;)7sE{~>4rI0q4;jB&{!AYZ?O1VJh1Ag%6iVCm@kS3+m;4DF+80A0u*!ytS zW*e@p*m48_`+?HM);-^^HF;Ev!~ZKi82g+sxG3|Vdq98yt~2Gm!j@^^haLQ6MjcT{lgj!IS$j&I!C`r(O(U!vTsxjQF zM8OsmPF*M^-hjpY45=WnV~IP)l<*@;3>&)os&r@KPV74vKc`)`sjtf3Eazr*o^}4a zLWKCMg}pE6;CH{N&3Wvr4$*bFf<}+C9y@-<;9jU`)rB(3b@Tx)lm>9$I6h_cFeZ?| zZ1quEG(oAX2k!8Omo3Du*~+lwP~~=4G%YFfayh*Wk>ZX?FX7{6tB(^w{Pb3H2jhm> z>a)7;RZ*bPlXzuj%Wr-4RT^ikDjNR7z)>x;8% z42)DGGH69xYSBWyN$OHrz^@j;%+ai#jWJ~7W?>V#{;`N80Xu)RJHcfRBi%BYpPeyOEmApY zsn+8CzehahluZlf6WF+AV_@Ejg`<@y4avvoiv(+_1V|Rb*U0ffGAOJJ4Gh_P60> zVTZYcjTvY*5oDGo)3Vfj+bNsZJ++NJIU=wLE5VVOwA8F~%H}E8o;EK!7NG~zV%Jjh zVtgq}atO=M@huWI^DcY!#yE3eaHQt(#m-Xms$i@lo|yij^t^=CS_a*MiTyBh+8@nR zc~O`P8n~Vq%hkN)M00D9<8`P}>Ub=ZBh$m_rrWv{cLZT;!41i(9>WeE&WeN{p$X<%7ecO-X$l zr^5kY-Za^%Wwf$Ayg>FOvW>v#KA!X^v;WPb(u|Pya=TQc$2HJziNZem6(Ycc3et;b zzW}YLQkt$^b%6{Df~ksJ4%lNb@FaMkv0Pw{ZZ25D5at7h`eT40BL{d*ZI`D!zKz`C zW3`E89gk=)jh?#x79T6n_|%wHH>bSjP9Mu;_$i$$gIkHMmo`L9nBjHIm~6DG{z@eS z;Es0?()2c2T?TKV!E_8(_md^7*|Ex6S2Y$W+zWasqwR|5QGn2T?Ei6%RBORP`iYa~$XQ0Rkqllhj6fh361#=e87@=;Eg)~lMgC|0$ZU-1anSJ%ub+VAg7pCQq z=^}P)r@s1J>lvZGCJRoW)?p3X#7hv@dXr-EcLu6}alvgZ7ngR`Tco}YNgrFrtzriT zIZTj|+3G>eK47D?^GQah&D4G!n5q5MVzxJ)p1@xWqnbrO(@t-(!5uOeCd`wLPN2CK zTywW)&W!hjxkH-E$nL?ysEKD2o>)YsQuMKs@wAVH8_t&_mseh?n_ENm^sW;hlaad?qqvLs`xIowM);(&o!s6SWmgRrZZF*Bhq z9Nyx`3U*XaW1utU6+~Tp5D0@u_6PL1T(N;+n$SNGEY@Th3MfK=u>KJdo>F@cv2T%X z*Dm{~GM;~~fZbPk_f2cN|BH1^ILta(>&z}*#lc6VW~B&O>ViII=8TZDacCz7a$u5J zE|M{1hRAIkx>AEfIbLcn2QUx^W|Q;+N2#Q_fwTtTa2Fb}l#sAeNa zEj|b%NCz)~OI<;r$Aw)CRNXfa;{at!FnOVlG@A>*2bZ?0U% z{hKsJkKmTeg(i(OFaod^F>U2%sF`wwq=^J>-Nb`97BsA#bhOfqT*5Y6aUWIhI?WV5 zZCFVRmceK&;+}n0k2p3SlBJn$Z`g!kEsYVpUIr&u(H;-WNu9O%z+0gx%~s!VdmP9? zF5BwIZ#T!C3>5;ODjQ%@1XC>7=mR#PBDjff095Q`z-0>l|I36UQE7H*An*!CT^3qw zb4h8B0a1O2*^w<#i_*SrAE5yv5AVXZ6P|y) ziuQC<8QGu(jf3~&YU48|x=HeuMg;>*SQImv<_#O!F628jOX+0m)m4KC?|9#NQ9lnCt9cKuOs{#m5_zxEH@ zbgPSrhP)sdS&@>dbdbq5G^%k;%`L5M?H%Jga}y>qV!m1nifybem?Y=Cc&)(}KsKYe z=pkzx%s0~7F}FV`;QF6qJucSekSM~>N9qOEH=r(E=p-VYLR_J|Xc|2os~nj_>yZyCe-Y|RKmo0WV&e+#I!d8LU8jX-f9vZ#qPU=!wWMx0A7)LW!D_9D>fyixwhMd+JPC@cDj> zt(M2?iP=h>STc{~(}+^sx6S}OBbx8<%iu!!+GjOZS?wgxrs6p=N`n(os`ok7hp=6s z_+C_e44Y; zjR!Pn(^6)49vAP9BhLnG>G@gV??kJ(fDoHswPvJx0qq-BAKE7wb4C2%_JT1F&Q=&a zJFHz^^m_b&?`-h{pcWujFo;-@z`c9O2s5OvE-YQVg!JQ=Wu6e`HnM%5 ztHD;e&%GR#iXm=uGBSQ)U5Ccznaoni5ZfRD+AD}rT`;NOy%fl`KXWI5h*P`g`1RK406Gcvj})i-6Q zVe!fW9D@#$72OKbOl2J*^gUUjE|%(>n0M9;4?m6rn$#80Gji+?wt42bTtISmxokM9D2^p2n9=OKoX{TH3@l~|<44a3<%eUQ za+jE=TsF+5)MaC5iWr;1G!B%eGzQ@m(iHS{S(?JZ;ZogUv1+p}p(UedM zGCcCElLZ+z6%uCc7Trw0VWoq@tG}^kMyN}ral)&Jb>TVgj;upAE)(ETU#_g-?iycX`=PzMDD6D> z?&ws3%8Ghh!o2reUpp`sL?U*9OkO9<8av{bd4MqKL5u@h#C}~Wi!P=vvhd4xx+)~1p)!62 zGO8|1ZM~`}$`(d;2cz*tf(AgD$IP4_KpdtoUEJ$|MzIt;~OKtM1}7iM9%FdeH6q1O|i5UiDzmD*@uQ_G&-9XQ+{B_ zt#c@NObg|)tAu@bMyRjLppdZ3$9T*l9CmDMkn@!$n7%V#ZNfNxN0ry z^4Y-R7>?N*lbJ2+s42!?j&@%+gV>xtZan1VjhXoI;_4RDF?Jo+JA41A#NiW0V6+kO zT1|`|)Lz*{Cbo=iCAK?Ts#s1}0c^IqQWjj#cA$6>fYHQC@-U1?I$4*6oncv*S9r?! znjAYX)Cm0}WjxqJ7+>Fk3j1Xnv|aEZC=8NX~Y z)>qzm1{(C~eYrY~>)3l(4^S@KoGjV01zPkl49C$>+7}^9l#XTtBdVYT-s17$J_R`Q zsS(*(0>k5Y2oL?R|1hGUTRK{c(ms|iA(BcLk~3tD9tQ3sWi}MC>BxhLO$}C!fLmMG zRAlcPJ-3<_oepEqj?x{65t}qSVR9|mRSy(X6y(@Fon5ITA{2NuoAtN*6|-+dPsT^K zin8@-wz_ZY^V~58@#bb3d1p_EDk-=yP1*m&pzDP#g=9FTkP256(&5pCAT)(cxKAO= zUgy#JEv^e*$$Rh`V$j7+HtxnatEY(fA99!j!XFrf55_)GJnZ{FcC0^hvJ%tagyWeT zWNwVJ%+xeaiPXiiz%mS??7|M1uLg`@|G``}i-7^|BQO^OTaXmQ#g8#J;)Rh(bZ1P` zJdkzAc%cwFp|LN7cwXZyggZ(i}KLUL1g`XEoMzL2HwpGPrDg_#~Q`M7Iso8#7690 zJXQ3r*L}3rJUJ#sWb!UJux?v(Uf9%|m9QxHg##SwGQbw&T`zXV7@m1TU=auFs3D#+ z<6^LJzGJl|TB1>#dAN^eF!P{vw9b@F5bk5%f5@2=w>Zfy&ZhIgzOfHm6~cYc)Aun{ zx(2havl{5-af6g-kkuL3^THFOrVorVEzJZN?3)l%UWfkGPKl=r=H6q!BQ`aOI?8sO z02-Re*luY(Yv8_;L+TP)cb~Jaaz+kLqv6M06Ajq*z?#Qh>y8(BqBB*4Rka~T)i=Y# z!>oqXe#T{!vVnS$ViyAD;sa48tG0)N$T@DbT#^|SG0E27eQX&amE_gPdAqg?ZT(er zWs3OruY5qf6r{QILCfJg1$2RM$Qv@3KL`r%fPICu6(0h|In?RW3NyrEM|vQd0}C<; z$A|FVbxW<YLE zF#=C8=@m?5?%17W@jeG0m{-Lz-hv^ z^#tp&T<{TQ1N(#ZFfn}n&>nn;8Nr^N|Eg#LmpY)rF@F>eF|{{fiR5 z8YR@E?vOh(Mg1R(7Yv@ZYf>4VI&IgW&VML-wqH z@!MZ}nOke{FBl-wcsC{cZio_oQjPwl(hVxesBA-HkO?vhOeyYCtVIV=0FGvd_?lRX zxI*IKc5i7JsE)>2S}Dk#nS)o%A3RMj*cIyYQCs;Nr1=>m7=zcr!LEjMt=&q|wR_N7 zZjfd((x;4E1=WsUzb<9(Q)Y6#=xQgv5ZU)U^Were_}yh110-K+O6(8+&&w4(QF3X8 zT}3?3-_>d3_ZOWU=gJ6En*~oO8)RTNQ7WA_$$sW=*o@-EMaLsiWi)9D8R8IBz_}=q z8%1<#UbK$h1f$&s8H{<7hG4Xi#dM{Z;9}CMa#2=v(j=DJSCcZ%5+hfsyCfbfVXOOB zT-|Y9q2B9dB)HPVNysK~bh>P}#~$Uh#PF*f0>#fPriLwQ=UR5scQaUlVbgXWP?(WtrCb`=q_%JBNMU6n9h)blOAMTdR!JL*Iax56a@Zi+ zyH28-<(Qkhw%-+?#7LWPj_oy$rm=;`j)w;7jJDx1&Bb9n2Zk++8nUpx&S;!Yn{Zyv zX5{WtVmFBLUY0&tFi2g4>YP_;!!>m;{|M}cmKT%)qs;{n*@*{#)>#JDxO(^j9s|B0p{B?KX}zQ%?u4-aZh6h zWjxo7mP96CZcL=LQ0akr-Ll58_*E1(R|YtT4SD$z16+bu>(w=7?vdl(HT$TCEDf2QDRsLQDHhrSGxUHCp$$Ov5m` z+}%$OuY8O&RPk;9+%lY(PFxC3okI&-3k=e z2-6K8&*626QY-FM>M{Z_3#I91s02;?QK*>`S#@B!G(H^9Do9PeSlW(f6{Ha*V?^o1 z@EYQvv}*`jjlZu}hdV&>0To$kA2XzGgpRSJ&Qty_naD&7(~nhjOE&)4ZO7dBd*AG- z3gH@nf8Igi22$r+;ClG@n_s--n~6ZW*#3%dT2&zkde*;w(~S>Z{7kfJaMdkxXJ+Bj zU6(w(?!wq!^y=qVFJAZ`JL(+9pX+I?^&9@Q6G-%s@?{A6e*u z&9Nn;eN+z7t>&^0=}76HY)~7sMcd*FlZyxcw0lnowSE3n^L);|kV z>9D1ea+WQsVw`z+R}eZ{wVXG=_#AgW_e1I%(2m*g%stds9RPrXfxrwpy@JI-wty5x zUYwV%q;Ot@k!nO~ZxCCk&18nuqhuP`ciJ>DzSMq9^~EXYfvnUt^3x>4Wa$R956_4a z1}@i#(gGt&#~M*O-H6f!IQbm_6Y$Hm&MwBkXiL?w5#igW0}@p(Ok$A?VxyjOhhG#H;YQ013~{5q4ZyhZ ztVR@eX!hWl5NP5WI*bLUQc^qW5eiu02Q?jlbNSI;6cI@5hpg~t$dl%hWRw5V?2_JT z&Qof?qAa<_=ZZhfP-zBVRBF>yT8HXg6bU?`RINpJg_a>^_jZsz$lY%Z8VuCSXCiDz z=Jlo00xiJeX*Q)9v@9^US_JtFd_%yt7s53;^b1agQQ!leQR9l~ofCyl@0>_y!|!)U zry1G5v~vLv_f!kvYvgFpTR~! zjFQK4fE!PD3s_yw(WWqVR_YzftluhKEKLG_omEbIM$Ri;4@e~KSURkR5ugdp<;$aX<#4+aHbu|*ak~;0 zIqC21mYbDj+z79yoEat~!Uef1^uT0cQW*xRBjUv7HV26wJr&`Z4V+)eH7VO_bOZRf zcy!2ktR)5*dP!;CSr;kJ^PL7DJ#klyL$E24s9$ zHID^gRVm6*EHYp;_A-K<*3PLF0K5bdqpxeBoT*}=h0}eE%q$}yGIr!_E;wPE@dw!B z2Lesl2E&$`S4?EdLxGJ}bBihM^+o90#yN_&9Cb=Dk#z!3r;vH7j{!vM*+-^z2@J)EBfBOd{~YHhz>{9>nIMPC@k=%J>Le zT@;q^nUk|ws>1`1{ag5{yb#{o$^LMdj5oJBz-Gas4FA&%59_&rR6-#lR`sxC+&Kf* z?lngpXV{b-VjM!pWum&$8BCIku8KE1;0~$JdVEAJ3PK%vy#ry;%d_M_j1k*vy?Mxv z5R!c_qfKUvQI!H@fNw?NHKjQ`G=y!DMb$0MvGUC(Hf2WD**_3Mqu(3)wgm&X640dC z{(%9$DiVB4a{{hW&Va47VT_QH3_bN}>#pGT)#)lt9?<@<-+S&%brJ_LB}-onPX=EV z3!f)*XkJA2I2Z#iBHRO#IEG*2m(A$|%=(82J1tAcvZz-&J-lEHxsTChc79+xhMhS3 znUuHJ0^C}%rAe}-PP~D;V9uANFNU+-nc-}#C8K*fW%HGR(kbC7e6(Cj27&1ck2Rtn zHmhWCz9fGL)oq?`HcvNW87s`Q{0p^TnfdyjZpNx^m?N&Nm|jSjvxikdnrFUli_X3= zG0Q09iwajTZ3|icM|()^3|tjN>5Go(wjNznW>mvi&K(2b3Coiv3xU93EpVL&(5zkl zRtpwYx?And-ZpBGSHPlZaW5nB8v0p}<aluDRef6Cum@cp<@qBHpR$0$Ff z?v;i1dc$B!S>E{x4a^Wi4(WE2Uk&jhbc?Nst!s@4QFSY`X7%ELC^mv0zL7;gAeXlC zi&is=9qOP$n{Kq2W^JLbTGb0}Me66)vN@`eh6AE*KLQacq{I>>AtP%1E2xy#}I? zTxZ@uI4krcbUT{s4jJ-7zw}*-MR$vtj7}63cip(KcC_%7G8!;UfwfYX`FhpJwVo?rh4KX`x*~oYtUYx~H57ut zIOg_eT8z|z3Ur_{IZU=v!?>PNnOwCv-q0Wd@53+X@g^NVh_6%DK}{#r=@lc@>6M5Z z9s;p}(tmufPQejxfDIstLRR}+S=uYgh^GN~Tf0MzC!sIqH?LD@*lD9y7n>2w^#ywMWq0F zEs6D11tSR0*B+9f6=roBL2O9bpDSiLt|nTu?eYL|o6F$t&D?a;ni(iEy4eh$F<^#O zReL&(&zv0Ep!GNM5zU&dBid~e^Rh6M#T8=dj^u#x2dj7qHo`q&oViuqQngQj3PLl( zbM{xOMQKulwysp9L>D@XM`MuPWW4N_y4hk62;8dQ`czu*=IHGTOU@#(aJD@rh#jRu zr_cbkhC39g{OUCzn2(!1O*-K`SsXCKu@fvTK3EDPoC+ugIj(4BeGP{v4_K0v&M~L? zDp>j~Wd$Ckp=>1giRVRsjv+cAo(F|-y3+_f4&4B;!b92tv?aeO7jMc1f?{D(CX$R@%MVQ!-^C3--IsM4!;ewY zbR63l-Ct!27Ef49Jr0>ch+tkjI~MVJk(mN3@bQK-FN%vcF-e~JKhlyqcu4C-$Ta+! zW1k!r%(%eCoRvU^iGSBd@`qMB*~={nbTvtS%7$q4jIPwV=t=FUXG@OZC0CRxU}M-2 zJB>$$>SI^LEPxkPM(1=AsK2Jhpr3$o$yVY{qXVlJa0jP|?SBDhVZ=pksjZ`BKwt+H z)|TOF?covU<~;2M_yp+bdP1L`fI=1~YEkIaIaUcO`+|%pj5C6(Lta03Mpto zQA<&9ytMO+)PdE4G?e4_jQ2OdFQ{7ZaYdj<$Eg;y$^>MCB1~*-?k$c-6ky!-`-)Ay zRs^dSo2xctU9BF}83gp_s>KP$(Jfe}XZb+6hz?uf*!Cu!W^yMzu@_LDeFJ*DZq}Ux z)q$#|U?WchA_b%B1mN*7pCKl|7GQR`!I(9NZ9lfo?aSKv7x@p(2bDe14klGQ_`LrY z8JXu&k@x>Z_U-Un+ZUofhssMNo8|TaM;4-Dz9a z02UKDu;nxwdy@ukxrWCm-Ep| zkE_}iz-7d`0&lnj4&EJhfly+vAwI=OIiF$&jCr|&8(0?mUf`^-n>c$Gs5+y%TW2P4 zpb~emDB6`q-L5GbqGgU<(UsYqgNKR82nr{^3iE$Tj2tfttt_pEDx)*2SEy5u8(pxe zDlZy)o_~D!%Aap}?rzJ2;r9H`!}tH!YmaWZ=XKV6x;?MF@cpxXzTwIr{ei*b-JT6k z-SoG6H>3d}kATC{-3VanVlp@N3P2{o;$kk?gu!rlSb=MERM!wu#bYQQR(;i?$bnSD zwLT_&z|_etVSobW$z+TjXgXjGVU7|JK*qBVFwAB(b+7bvdr)W(!enF`fvh;5X_ZCk zQfT9k3%?TkT!Ua2IODJ(FpaZVV)=J9Et{JwitspYf2HFhE@KM{bDWWb>=b((>j*>; zic(M5Q(BMQCm2y0XGE#nh|t)pN*_0(R57A-gb}4f449sS@CLGdCj1s_ z@I+}n1>qMX9gF%gMPMqU2rLx#av_fA!cb`s^=(okh@#oUQ$x%gz3q2CQn0FK%4S@?p41IwnX18Qt+XhY zlzI4BXhDR!iOhR=&T-jX)!X`mr5ugw2i{0UmfgmzEndVs40w zY|S+V5sI+Kc;$J_B$j&qOUAOgXls}Twl8l{ArEn*1xx$lT< z_d7GXPG=rkGkBo#bsFzcqHg#?olWMEr!2iiy#MDXeWUBUJvV%?_6JwAvLiIhJu~Yx z;ZtLl@J{%Z!0meD3!860Z%ZR`A4BjyR=MD@j|rZOeQ?!K&&C(-dgQ-q(}^r7~Y}5AqI`Gm`=R(IavKCyRe_Tt{+R&I`P8#X}{z zC=)qeBDx&~()B!-XohsJ^4fw=9o_bh+x4O^FQ7kAqQND(f-a$HG_}}CpUXT+or+v% zd?R_%b3QK}I)T1H(oO3w*=M+lQ%0#j~B~O*t zlACsCxW~&$4$*==l;r} zyu4OYG4&O1vU@-IOC`ByxZQG|>r$4;`D~&>w@FE|>ZK*oX|$c%7dsQON75Q{cMz?W z&ecRGCjZSL?+fYQ5&gTjmpsRlM`X{TiCNl~^gd{lI|k)BL?-3R5!V@!?$0INcO}}& zi(T6&?Kt;1iT1{E|2}x|JCxp29_%@7((iH)Y3*_7NA#ILC1^b5cl#VX?C$SQPf`Q< zKg-g09IAQrLPBm%kVF4TKXv5AaBOXDm&~}bA+_gIGT9)rPT(9!w{%BcAmmEJWC(;aZ-6XZh zPLlFKa-|E5AL^101=#mUy3``u5=1j_D>q5L3}hD_LK&J)4(*Tj>X3`06FE(SJlP^A z$OEO#c_JN7zC&~ZNk5Z3nPe*P=g1tl@ckReBk2WHO3@;h5+tP@FI`8uS&}kAjr0Jm zr{|?}x9?1pU9wBgl;kH#1}U22t&&Ar?YJ^U3Fldol4cNLSRk29q$PDvm6;Z|o5;ie zNvVv~u9V~)KqMU^XGT)WE6AZN`M9+sAEKFGb-hk+Z;#R^6+UctE+RTf-{!g%`P)B} zOKB~Sk?SxFxinsSbUDe+rY!A|93M<|x(Ri+C(TMoDP@L|G>!Jbs3kE#?In}+I$oDc zcU?#HlBbkl*KVDUV9@1$(>yhxTjyI7yjy z_I4#+Fr{g_Q}QTzC}rfnskAHU-yKOL6C~+cA}84@50nml%y+!LM3yVNK^~XHgSXSC z6NDjEzD{mJlFZ=*kt`EuKnwBfl6RI&ksOwI?X-?uDP7X(NeSsDDV31U)GWz|h{z%O z1qM2zW80*UCi&%rgJ<=L4#y4YSt$d#ujdhN{=~<}B^n?8T*h%WHG2p7S0w2$_fz!4 zD^WSmm8Qz}^{$gr=z8BE=f4`G{?+DD z<1h8^-Ox>4Ck@j!62rxleiX{A{4u!>Njl$^t+F$zGM}Jy0d6B?uII1ZIm;zH#Er6%COVQD+~kGM*)uS&@)nWf{8>+VaC<4D(W1L>z;p^Qsc z%W0IR`)I{3qsV#b4{MJ6u;z&2;;_7RBGp`ZP9k}1Vq4?C@MxKKcki=zeZ1$$@yUPV zUwgvy43W)CQkYHY-L6dG%3lUSV@=j-{HfKP zno|?zSLqwn2$qihpxvR&_=oTW}_TG#YYW?RD~n&homuwcQG1%s#U zecJTX_Bn0e(>{6Hey3HJEMC53aKYedgVj|_PFcQW!Q$$I#jBUiUw!iYl?zW^zTiuX zmRFaaws8J}(*~C=S+aOpW$FCI%a$%&wrc*$#S0cLs?J}!aK-%U{H23nH5vJAMY~&Yr^tQX+4A(ID^?DEX~{xt!99XL>z+;`@g+*SLnM-Cl1Q&1*FBd+<~$M&=aW=lCDCv(iKa_Pw5%i1 z_B9d>UnilyL89X_5}lWmm~aJ&hHFT4UQ43uTO{;)O1d|bD2|Y5xRpfl4iXJ_k|=(M zM8kJUmcB=>`vVet{E$S$MiLDVl9=>=Ni_VN#H5EwH2jjpq(?}*FOYWMATjApa@}`G z?DZ~*$?wsTu9jjdV#j7k(S48<4TnfE{ZJ|PHBvOpl48HvQXJ4L#f(0w++IfT*sI^xi^jyv;0NAz6m$k|_Ww7Ahx;sHlAJm!eL#~pF_uN-m26OK6YNk<(0 zlr!1g=7?k7aKy21IpWiAJL33v9ntWB0LaxPzi=l6Q5NSiQb$qnpe(oZgX7pFSzyaQXrH zhSLwvr%(S}KJ(?%{=WaiygdC!dHIze=fxQh=M%$E<>l$me>eR_ecj;tt&9cejy5*C_`W2JK4b{n_Vbx^OaK>c$?cvD}x__SRx^GSv4Kr{4 ztUG-3zHV`(!<{~Iy8ERO*Zt2Caq}4?%KhqyXt-!Z+_G-ObuSw!xwnmo+io8bcib@| z?%XgU?z(eC+;-Q9xcj>!;-0%l#J%4e5kI_VWPq=RI(j+yB4{ul2#NcoQGI(91sf4bORSIJ2m(^~?5tNc?fu!@n0I*-dU{4y7~ONM+VJZ5?+x#g6m5sp_(>{W6z#9h|wMt0!}1 z*WsC~x{l6V*Y)Y-G5OD`WAi6 zwe`~c0j*!p_q2W^e`M=7^T)SdmOrWW@_f1Viu_>fmH9JTugb4&y*hts>oxgnTCdID z+PwxAT8#y(#}r>&iMnqSM8a&P9l+y9oI(fn4vr}>@y5zX)BkIj9M|6;S)u_&M&69}|LR3PFbnK}jL#+ElC2`+wg*MhI#Yg1UvElO_my{Bl8ezgDB~y;h@*uhrM2$XJRimd) zsL{p~YV_R`YV`dRYV?y6YV`UEHG1-d8vXf%8m)H(-G4%j9$ruh|TgRgV(bsoO{)pYCebv?dr zz}JoV`Zm69!q?6C8u@=ncR$kIk97AV-Tg>+KhoWgboV3O{r^wt?%HzSmhW!4Z_6F{ zeRK_f_{dB5-?QbuEkD?D-1P}C+>OT-Y4#P;-)9=dE)jb ze$3k&gxQ`B8ut()HM#a5LWs2_#4*C$`m78N&3%5K0}lG+LDTo`Ui$Jk*5p3ly;Q$E ze1m@Z@|*R`m))j!|0C%pm7Y1A8hW7i*Pq-E{b-=N_nyAbzMtH0{{s#*J+o%__6c+5 zup8V!v_+;QZE0zF$<6+WQs~vfs(G@`TMjj2pFjLVVw{jTFNA1GwY-$w%t=Luz<(jA ztxd#7TH0D(7bIF9ruUxx#naB_#=i)GwIEh;$f{%W=3oC}^X3-S-2CB7@4dHe+qSKb zJp4%8Bb%eZan>K1EYHR0XZ4~{9HWF>3U33U+b`bsP zPi-B)`gQi#_%y1&5eX@u;=hL;c?4@#!C&pvD(spOkKYDnN|9{a`r3OYB&S zB9W9*&}-BtM2T+mC5|6rW8IY zl}f3UavYC5PkD;?`i2H1w>jWw^LEv-J^mAtL^dhNQ9B&9LyR9k{!b~ly?y7qf6L`^ zD3MRi&CSh@<2dc{A4>lxB6{PEcRz67-M-y*g4Pc`&v9xWy!BQP1n<84?pyJn+Ns_v2?Csm{`e8i*0bH58 z5WMrwJ8oNp;|P_@b>=?&i*%Ft+wRyuE@+_;1er`n2lAXaapFYWHTVm(K06#|N0Wo! z9SV>2#vA#(m(Ty<5Ba=O+3Z9QpRS31ItbGEP;)b-nwwi%T3V2N`}XagN87izv}C$+ z_!G{%4Gj|}w6$sdiBDv+L6FN$n4ooATcNOfV{fvZfp`8{Gymrugj2M)qnVyJHG2@T}1#(KYQtwDalz<(jsSx@MRAw2R$G zfan595N)lJ+H>6h#qRyTt%Lsgl{|8^al$r?ByDZ~`jyS~F-LsFm5`32_hd&;@zGnz zY*v3y|E!+=BaY}jATuH8pE+~pOmmny%$V-({U_}|>#&}lSv~gC!@slY+eh>tF-y$a zyWjqsHLJgWZ~J#h_cZ(+(SJly%skA@n!VTIhxE;u)uTVxv)}CgIeYhia_|1`S$lWS znmy-`S+jg0#I$K2`&by3Cd{5SN6Z|(*Vvz)o>|8p+lRmI!@K*t=XUo`!~Y|@r*(Hv zo7TN|cVBl;PhVf(;r%_m(`I$g>h77=)6>)2-94*&!i0X&-=FEnr?+>HAP}==aZY`o zo;kC(cUE6dFTT5H&Fbmz@0m4gR)5c|*$4E@>YLrubKI;Rb6n5tSv|9+_554ktlsWf zvwLQD_xASo_M4um(|UT2?wvh*c2D2b*|Yn5X7zq@>eSg&XHT6wd-m+vQ>X5=7w_@0 z*#{nY;DJ-8&bEL1??3mDzP^1X&Yq3WA+rxTWcDGm_uv13Pabf<>;q<-+%u(@!uyu`Tw!@CE#sT*TU!CJ0r=GorOS1LIRp`Y)8uG-A-aVmiO#?2#^qu zrLi=4q#4hQ?3g6fKo{up9{bW33S|qF(y-IA?`tW91Z*%Z?duX=7s_j)p{2?H&Yh9% zgwXPT|38VOnLBqq_iXpvbC0X4Dl03iii)D8wR0CNsH$mbDyv;oQ&U-5x^(H%rE}-b zUA5x$(^s9ov13b1Sxaq0!}8@TSJu?5Sklt6Vg-IWI##W!scCG)?p0T}v@|rVSkc&6 zQ&Ur2-Ozw9ysPCiS8Xk3i9{l`3u>C0>RMK>Uc06|Twhy<*8;4drY6R_yJ=HHLu2EL z6<9OE8QWbNuCA`GUbw7nDgSL-+OmB4^5sQE9Ubk3h1<4m+t$*uVZ*vb_*u8Mxxu^E ztXb1hznot<`~?dZ)YeulSg?F~iqO@$0o8Nui)O^%c)=}1h188gO=s;2}D{E{jtFJGsFB?Z}&0a4Swk>R1*uJp6 zwY9x{p?k$#^!s=4DQm^<#Aol6^git*`!;9Qa*Z3pWe~Y5jm@)p?TTT zB^|40&uLq7=JMr>mN%8xt!O#BDYm4rq_DJNYH8*C>IJ8jE}k``dgi9Z71fo+bHa;C zSCp16kWP_mrR3HHR$E*#qpY@SVQFzmMa7KrikkT) zrAsP{Yf8%M7Bn=?C@U>%npfShc>U7S#brxMs^+#WC||g|xI8hpV*2!H)8@^cJGY`@ zLHQX4-CsR*-r`f|Ee3$I&u&Y`w)fOGZ*SVZtYgul^5(XxHLX3XH#M(VvwGRGrn7f! zX^G8Uxw5gStz$*w=Bh>QOH!?EvC8_{XPw(xQ`5e^ebJ&=M}6h2nJvrLs0*F#mHc1s za_=j*SMsEt+bfYi-B*c3S65{vezvdKzI_dTZQs8AjE*xpws+v&>8EeUVr~r`+dDeE z9Q<0euyoO))hJZTJ37j1E$i%#j*jZ;>Uj&0ac}SF=;$~lQr*DiN%ztFf`s{n?zmP^w^3MMcM!EnC*Di^tuZ+3e{ZWte>%j-h&1 zN5=-dI+iTS)pEfF$JQQ;#bTA)J3BY>k#=<8Z~3;u!otE-s=j`+E1kD(%Vv98@Uw2$ z8M%@R=gnWWro3F1Yij1rn=#`?@0vGn+dA8}w{LH6Onu&vRy4P+YHC=%F|u$?EU|V) zY{jywrnT)_TT4ULqVmP%#Z^nCnf21PrPYfT&7E7+uxLx|qSBTnO>Omy+g8eRniiej z-oB{4p{jma<5`XM^|h6e+UVl)Q|4C9+_0#ut};?0FDhSFTT#~D)Vd;8zifTU!ex!h z$`y?(T5FqEwIyP)#`?tz>Py?I8Vk#pN@p&uiq(`ZEQ&2!Teq})_0o+EHJi^`-qyCL zePxTfsYw?`c=;o#M4HXM38yhy)Ev;!=wkp=r-m+pz=dxwXR;_4hTeiKW zrLw%Jyd+#!ULwt#vn5tmT`|9+xUqcsyz=?6=8n20?Wa|CEZVf9vA(6btGTImNyU=N z;=08&^fvtVpbFT(K^;qM@l} zb=!t@D;8CimCh-ts64g0YH>xRbV+4N?VQSnil&zGlA1+}OEOX=CNQhJ_V%vF4VtNLB5k zs^)FPc+XQCqpVvUYLB=ruN8h<*42A>=;-M~FZe#4fy32-S*5C^{es z^y4EaBMuXw3@G!~Ek}S65+p~wg$LR;_$q}Gh<$vg5IPYTlAawGS1<$^GWpAYD1^$W zp9(@A!=xj`M+7DwVfbg3+^YS!0S!bDM1cbNlv0$PKmVZ+TJ`?>?}IC22tfX%0E9vl zS-}*PAi*PKBKzkjIe`KK0hq`jSa2fb2Lb32060tqI1GmmgIM4Tg&=n5ZXxtS-Vxz2 z#X3du*CV(vI|3k}9HmEaI6*j!X-B{{FCXC^SrY;i{lWZ#U~ob{$qNR9L4PQipPv`X z5Bl-~!Mqd1z{Ehn@AHKMKEF@&2mAqFLEc1Ps31QWnvj1uFF!ws$B7Ci6yz7=`||=p z|A}HS@5DgBC;EZ`G2j#ZdA^WudI4HPCWIzosR;!Ip}hQpiIb*H%FCZT#UJob2<7Md zL_gN=7X+Y85JVqCa8iGO3EUbc2=oZ!OJPPCMRfoNb@-qB;mBX`nNX2ioVeqHw@N?a z&K*t)IU*jWf-t&v<=}N~ct;p&7r^J7aG1L}=#e9E#9Q)z%u^1Ju6>VCN<@S)2Pv=X zi1(60PP?I_AKqmj6IehXzzzfP6UGEYJ;o?UN1Tm#Yw@5 zc~kNVe0f2CV3I!=%wv9kpkPuUKbRkw7(%Q#%ot_l2pl;={C>vZ2pm3gSVYGU93404 z@xgQhdO1H40=NMHw!=*T&|dg9U#E00;gCVaP%W0qBP^075Yd~7=B8hC<6EyeYyzXHTqH! z!0YsbB7l8VECzUkb{4+}`)Rtk5k}~g5`bUOa0$SB^tUBp@=N+r$$Rj7dSN6Cf1&qB z06wC>j{tm3A=(Ikqe2wm@6;Cs_y=7Y1^ASn9R>I&b)v`{c1Oc-gnlLZ9uRhAGz@v{ zN6|2Z*!|HPpnyFa4Z{@nax@GlG1z~8@MN}m|C0foUB6#~d)fE*6S$wT}Eq(_9x*h)C{*ySqt4K*Ff2fa`@xS zF#Pn?$*}Cpr@@x5o(j%I)1dC_li`wY1flDje)#m86y7}zybpoDod*BzgAvF=ACX&F zec|k);^vmtmS>;4w3xwVR1lD*(i)R_%_|9vu?SK2w-#^*E_q!)uH?;ot@16L-tvA4)S^H+rx^dq-ci;B)n_heU z=C`kT{q+O4+&=Y=>t|mD+keyf(r>G(s^IRW;f@3Uv)pAOq1h*|T3b+6|I@86J|b4Z zJ=J;>dFq3w(HM+8juM~v=)J;|Pn`Js8}51Ji3jq4=H2qbjqtteZ}`>LEhi35pT4F= zh&=o32hS3Ce#-M3r=9+jhwpmfJKw%;VmwY4D>dgiZ#{I+#*O!U2PkQsbUVb3oF547 z5u-o<#j8Ji;K4V-;o8gJ`_)Y+)kxCFJ9|Eaz4rmJdY|d)dKW1C?fK!g>rO2Gp!kCi zii^+Q_r~QfJ^j=aB8sqV*+-i{-PCl|m7Cg>2mj0%tS2lD;FIqKHLNDjyQF7$xaR8@ zX}^29;j3@G^UZ!++keG#6M-oTgWK;QFcF~a@AKzPez5G&CjmJ1R5te~bAKF&)zth1 z;2*DDIF&qHa`50KJI@L%C{DZ!mwf-xN1ngpxtD+Va-w_pSKfU48+}#~{&Wut>T?Qy zd*aa0Uby&csXKoQAN}pqkAHCIoR{WI+keHhx)*n)!Z+W_C>8u-vCmJ$AP4~;d)o)1 zKXj820FYWr3MqUl-B0MADTF-o&`)3e*^ln>pOk6uy!y_%CH0*k^!D}|p>N-1nr3D; zw4r3k%P$^$?>n=LV;5a?{x2`S_`m<~`#(PV!#l4!bnS-Hg$rJM{3;;i%Eb>{b9H0; zs);8|okC8Yd=i9;=q+&IiT(9=-qkGn|KNG$6NOnXB-X#Z@5@u!`|n>? zy?a~U%vtbQ=!1KoB$wUvKDXQsm0=WX3pM0f5cw}+*@vx`rh(m?6}X3m;6{Vwp|L;~AUuvI?vdPiMr z^T=D5-F)w(Pv5uo$M<(!f5Xu0m*zi{%9NH@(3&!G-~E?f`S@f1@$3teWi+Zx#^l)u1^kk->+W%=Pf(L=iYpD)`w3ezW(wzUU~iAd+z;HwebBvy*20IU9@Cc zkO|WoU)#UWcl#ZWUGnmyk6iI`{jHb1g5!SX`WtR}VCU4`Z4kTXYk|=3&{{E=vsggU z`RB_ryYPbOg%U>A3rnm>me_?CGD%`ol9+q}JO2VENs?4jQX)xAVn7%JU<`OFe!=-n zmf87u%jB?(dAKCUS1c;a7hdQ^b{-s*Wst+N3{(ag7&a*vc`u{UC`5~kilVX%ks`b> zRmKvsJP2?;#e3jubO2hyK$ay5X5(XVu>=>&7e+6*@B&%B;6k@p?Bq;^&V zb1m_ds2p|2`utR}Q4#8-50)Q_9wEz&| zLk}><;1ga3bMZwO1l|K^FU1xQ1}LyYhrC`LIz(AJLvk*qd)Y++V4Yj0)9G$krca-~ zZ8}goefsov4p-K>ud@>v-AgI`q`m!`AQ%ly|9DQQpQHjpFBT<6u>2> z8DNL_=npX*y~OtJ1!(VNfe35&;KJ+0^4@bPqz(cclo;DH1Vcl>CQk;QDFP6gOeY6e zC$>8D2@`~a0V)Vg5Ck7EwssWMbo5J*1R9CF5Mg@+0iSq#l9vkvU`#|8WrSGghn;&q z^y7Euhj^9l>Fn(6ggu>+6qvx)Mh+dKL;DyV8VYzF2R?14X|nfV9Nw{m<_iZOKFB_M z1zbQ*o;*1apie&eBn3ukd+q3T4fbwNAixe$+PQDvXr(Yc!UCpQ%0zJp_tiyF1USe< zkp|X|jd@R}D1u0b#2q^*li(BDDIs#XIK(DXwukLC`2=;i-M@zJ@d|&Et7Up5Hz@}X zN>ZRb#i#Utzg>>u=MO0_H3d6TkZPAC76>qAnx%ZPju^u_`IHKujE>Aj3L0QyZ7GA; zomU1z*AxZdP~gxZ2m}tXKmbM|#D);dDeR$8TU!hCrkifsd(%yUn~uF8Ab@BBo|2ml zMNka$U@gr-WM0FIRC0SC?g|uKXou!#Yj2*;MSdZ$EY}!+cn9Elty=uI?aN6I#}6+|VQ}6Sfc~nN%%mSwz*bawTnK z62x%SUfQ2gEX(MJR@2sWBSU)e4{v0s`$HTB+O$j`v@2qB^jWKcu@73U901;dKiZM%m@JM9(D>Ba<9`2#nPt-*TiB~huO+azU>aTSi;+9}vTREKEEv_i67 zw(3yRRvp-=WQn?kq*O=3jJu^l>)Hi=`H(51wCRCo3S)6&waU~6f=+AHdcouU@&R})E<#Fb23 z)rlHcvbIW-T826bOR;`c&5&+Hx42>oniUta=24huBn(F|^{g#8T3WT4#q8dA))XAY zVveOL*nNaeC~LAT=3{-T>b6NUMw;kKyhk_ARWnIdw0pCPrHZ*?1z4^Ck)VK23`tWX zK@2^C!0Iw|>d<~iQ|XR`;V?D9(pn~KGu{U83lc@n|As@lEhSD;RE_tDX~pWH8Z``CB{+JuSI|{H&)BaJ@0TyJ-oL@G*p5H0 zS#dv~cwI4Rw#yc?nnN<#w9N@o^eB75;4mnN|GTX&{ZczEsNSI{WwG_^pP$tW2C9>GJ%AW6tGkR=fQBO;UF-R z%u-dVI|}sxswqjFP(&bPFMd0a)f}2s(rJaJscq`YfUc!A$M*9h3$%}E3DwBBQ;9R& zD`EqDer=&khzpvK77Sqr&35T(mtyge`QnP{&zd>DC5+OgEu<97G>pvH#DS{oByFac zGa%ZkLox|!_h=?FmAFbq`JHCP**Km@Z7t1oCF3L=%de}pO>wTqktWmnh@;RH*`e8v zXj2oq6+DQNOc;)>_L44R2jPFc2yb-7A%>;sI!C(}1~^DaJV8{NLCDcw*2`>c zk~%g)B6lpJrB$7HtevX8LNE4s&iY#(AUe>Bq6=s6xf5HqD@93xE-c$9M$grF}98tLvPnuZwb zkhGFiMWdTJDQfDPn&=wv*(5`|8FH@ydXBE8sl!w&uIS7#QGyU#%Mb_7A!)@)L65?v zh{ZD00Uf*DWZ^_@MkcFtsk$pzG702QDhik`d@uHpxT@($<($Z=lCT|vb~^&^d>$Uo z$)SeFsD#l`+T(^f!Orut*?D$vR!h2Ya8j14awHu$PqyvOfPlP3?M*tC55ENbAo#m= z!>~w_;*lPbN)Rp0v`n|)*v!tFM5l^LvGd5d;)az$l4PoFleCew9VMPpNrsM}d&A+= zZzSpGNX@ij+Kw@9G}JIhIY6GvMl8zNFiJEvLwbo7vn-0J;dX&Il#?Q&j>vH*t>}(w ztJJi+Eh8;B26a+hU1GPWWrVn*i@IX^3|kdcUDr%ovxRO;=@GO{Mzuso&~?QWGKQ5_ zbipuvYDTmYf|PvaZBv>X^!Zq7SfT=$~uDM&>ftVRK?C(YJy7) zny@+TqEJt;gs##I%eu4~Yzj0974o0u-j@-kVfJ6c*XA+s_EKye(7uOGYJ z+=3|1*}T%FE7U;-&$5=Hlem#dB8qVcCs|r`JH(un7VqJ=z6}4Ny|f>xiXxM+NfKvK z@Mzp3+L#_Rt`BT94?|SY62#!Tg5RytWu7#XO?Rmlb(oSw%F1XspNg)lI=CZoVSqQiX5xsAe z_TtS_cS`M{2O$5|l!E}EqYO2I0 zjuP*&RGnGW$~q+5#Z+dij!*3k^!hSLGy>+J@h^%PX=;9^3Th>CMCB++7RAxgtgC|& zb%!G;c3jg?Psyh998FKC0_yynTzr;4(WQ&sB4W!JuNSxi;xk38uP%D-A?1FKeUg}9=J!`wmNSbwX+r-KVVH_#+krpm~ ztQK6bvv$-N*-8Z!Ahrg%EL)q>1Wm9twgD-GZNvpD+vF;>Y>UR?dbZ2XYK~x-ros~L zk{=V8w^n2+uK!_*mf?(wD_{&+bf(*9XHAwdoRpSHGLyGu8JNpwItH^+2D7nU!Bi3| zZ-x_4M(xe-70uiobFf!}H(jAI#hmpaOCfj&+ZEfY#nn=ZscM|640Tn@$!VV8t|v9* z*IGi2r_^|lkWw6hLyMTif*t=(s(TCIlrc`p9iMf)Ojdidnyz(OS~h(w7ac1R%yCg_ zWRiT9M_eszoB;NXtI0R6rh=^L8{@~LH4(=^O^Y6bzT@N^45%467wrr?VHfO%^8o*r zcId@Ga4Ra&U0pkSc2C=CjFY_4or;y*Ixns4_?#D7X7`MvUhFh=ExmiIE2~dCrp#7O z$f(-v#9X^iJ@&oPH~w|eaf^?Q$IUhS_>JVo?`E3DN659yom*WNzO%4w_pYN}?82n2 z7Js|@)Z>@Py*_y>ws6!7?AI?mo%QwsY&^ z!pg0Sy^2+^u*@AG@%-hTmH0og25J zZaaTLS#@=dn%-)8YQxU?3#!x|yLYzk&b=?MQqx;@ugR5L>7`dxk1w^LytGP9@7_6k z>o^h30cNFl#&*vht*uH;Z{4Vlt8Yc_P0jyPeY4${s=o7A7d@~w&EJ+SC{Jfc)93F# zD$|4iKGV3=@tJ>h(F0#3(}TNbjJ~Ts_SMYK>+Y{EzUZiz5B{r{N0+?lk$+M0=$98? zbnJls#ml36`^dj2dF;yvcSCIORevauHWE-6FD-@GMX&lpw^3hOaV%{IfZufQ!o=U@ z-ZfHxlY7_6{C)1-py1!^-rXREY*f|Ur%52j6*kR#s{fi|~5?AkZ{q0@-Z&wT+2 z--ZxH~gW%L3WTmLW?QHF52f0vD5?! zVwddmhvqiTlc2R!g0?aVIzkdGn^WkV91KxC0`(aS-w#Iiu_giBKd3b#d4h- zlRM;PazZv`RqmBr<#xGHo-G&2#d1i_mzgZc5PNmMKQu>8A7tu|9}&|@Kss9s=8mNh zPtOXa)3b<{Su(TBOn@2RD?se8Z}>x}&jA8|Dj^U7LOv)VJQs{&COME0+=p(^GKZFYXBv2TDyutuk2zjs-f)IQ6fIs9Xl!=p1 zm;;4cEK!n(EDD>Sv5hkF! z&{3S*H9rSib5jojlt{maMmB5dK@b(8qesIGFx$SWR z|J(8)ZVd+p@hC=+-vi|HdIj%9C48wF4iw8~^oXYdbgR=+S9{G6N-lUkUHYoI!!-0A3#hALM!Cn+(xG zpV!7b4&TWTgnVG=c!lR?MvwjwC;$QG59T0GA&-y6tCU5DzSJ8x=D@nk z217i(a_}Um8uamY+@9AA;_TLXGwosn<8yKXEateAI~~h-D-DC#FUoxcC@dXp9K^a# z009CJ0w0HK0r)|LWrH~TW7tO^4^|H5d3YFb9qc&l=;-XbaB{I~)!=H5oo-qIgkTMa z{n|mq66)n5ux_;P%!2{(@bN_NkPsUkTL3l>o<4~4&Nxm@aKl;g-U%FfA|I&;GrW1t z<9Q}R0Q@ikF&F$08l@7fco0-y>`cgsapr#na&3vbPl@Irwn!tx^MHq$EhvkQOO0xs{#;f)wLv9wU#J+ zJF?5dtunMG&;ino1|-~5(B1vWIIf0?ku);Y>?WqE5454d7R^nTmPryjZc$rHX53{e z$)Px3wR+a}ZRFM|46oI%*=nE#9k|Jw6%$%osNq;jDnXXV2gru_068;0 zFuG4q?NpyP<^h7%N)A9xiCdb32CNu@E7W2*1=wHrsU0UWv=JwUZ@|%UP(;{MhqV|E zYsHl+-%>lKi@p}a3G`=TeBFwxX?_>vOKA6YqpJFiOmg(ygmLf2Zhd37p^d8Q+hp?l zK#P&99F3khiYCRPURqw0V&!=`g(k!j0h{4fZC2xsVFfm-s(0u9OlVRpfoB+fljr_S z#5dSkw>r-h9=E7t89mUtx}9w7@TkFsu}ci@)^Ls>_)aV*32Hh68&HMa;O<{c)zp9WiJlK^u{n$kF#Gsf>-wBS5t7aU{rJsoJ)`EvxJN(ckXA^Yi2lxDVl` z^RaN;b)X}*z6J3#uJ%xea}l@WU8?15;FdbxN9|lA<0$${+*iy29!VZ?pd*_$1zs~O zYmE<(<;b4a@JjiN9A`4pREb+G$u|s^@!dt6WE{rPR|EmAL9y z-MBkBj%5v?FH8*W1Wm53TpY#uF=7##RShksg3E-woWB0daS^`_t^dMUX%F?s(BAJR zh@SN=ze%z3In;$sd>Y)>zR}8k?hob@+}j}D9=jP#ZJXEPA&W4IK0+=9(MK3VAHhYR zZj0!2)cGf^;rx#0C4q5(7cB z3{nuHZzgM_jL6L`$-?U8V+eWFJSG)K>r+>aRTS8Wdw={klyOs#Y&WJf_leq$n($!b z{rC_>_@VurLJ+H(xK~hy|7e+{Ta+{HX2TOcLe^|nOy;7;I3CJcU1lX9xC0#A0%tMI zYcI$rA~-r#!CX4_AviWwL6>WFj3ZP(f58yI8$C=y?mCeti?;3m0<43rRzC}ayc`VJ zT1$to<2V`0lQADQL^xB; z9IJcexw;3hoO-*WT&&~%T3W~bwI;<9NB2k9;#QoKQfwYerl z3@sB^EY;MN3}P3ts0({ahG^m+7(aZH{p>H z;l5~#sw)F(0ycD@-b+#SZQD4;XXw#7t~-5(<%}v$;_>*L=xI%^CnG8g&0PKE6Vq!s zd?(X~N?uM-`dnIZr9r?&`U(8Ow<&|FK1XTA!tGAnsdP0)mvlY{QCMnYN^#uXO{~t% z#<)Xe$C~x4$@*AJE7{=9 z$J^v0p=Ak1Tti2p_y8NX>^Tlm@?F5D@wB`PMsy`aPSMi`tr?k6Uq#TWoRH6m;Z5>gJoaI#E@M+n3A{JeCwdp%U1@!yt3T zna|LeL>fo6p7ZMIT#@5`qT?uf3yQ|kr!!*l0kSMUKsFt#s*S4-`*>!@F{0B|=2Xi# zT}wDASF(+*2(fPEsHG`wr3p>}IEA?U(UPQ_jw$Bdo-b`~$;$L3HAyDHluUvpn5`S8 z%KB)MsZ3W{+D`Zs#oy(R`xAcE-|bKOQ_OP2zAk@)*=9;`*ty8LMrW3`QYEfgRHa&i z8aCywx!kSBTL5#{TXeJ;ofpy{=POdGWgO^QZ8!u&OdFY`a6HFcYI!cQz9f#hM{v5V z9`0I%pz6&U?)urM(zNLe^ik8+_)>bj$F4N^eEgd`-^+&vP=){ zDJvH$Sw$r^;yomzvfixLM^T~U3Jbc^xQ@FmD~0ufE?BHXXc0CE2_efi<&riF9Rl8` z_)`~pGv;2UMspwQ^2@ThJbmMf6AoT(T%dhju280GTBBN8P^qB{T|&yvc8xg*3$21G zqLZ*^c0kPOvf^2jyFq77?pbM5OLdr$A#ugD*-^YXYucin9yLIC6P0mbqF2K2Zy;Cdx@D3)jW7;{WUCuEMB6j}8sBcVJW!_jb`BsIxh zkU9KGw`QZ8BS|S1B88@;1@4H9{s}f!Jzr#7%ecPBKF|4>8JQjAocMt25W*~UPDTG1 zSN-g zswENhptiJd7i>?>LXVqKBZd&C+?&p0xTG7iayL|^Po*|aBGD1}s%2B%OUPL`(1%6r zqqZrORfv@&lccse#uODxuyxOG1%;E)H{NslxGvL7wH>DQi7hR(&r~d1CupIg{7gsO zqBvM?5<%T4ty9Y&JK{RkY=@d^+~M1BEN3E7kMXg_rCeIkRno2LT9WEolHo5}BD5qq z2fuX1!F1|mY?3j$UAu&$>#RrU!|^zXgq9L7D;F!oO0i0;7Hfs_3b9J4z^7WFvP!7J zw3=FG>*%=6MOCtu>bXTf+FPi3v_+Lep6cU$g;_j~koFmVo#}#VbH#%uT^DbTcPMh` zIV96c6;p7%ep$}tn=3eqYc=KkOwfr#<8h|BFx1y77VXWd_NZI9U|C$XZ>7=7>KoLC*^#O zA34&KmE+FbV$9Kgpew8E)J&-v&~lov3rjUVKzGD-(mf{qH9G2U+O1_MI+63)=6XO< z6>yhUz}ZDNbfcS^YJy}au6by;mJv}Zp{%41LpO9asam$cJ<@f>O7$>2bwP~y03EX% z@gxpkcLp*-EBE@g#Xg}AeWu5ol+GDbiExYkICdrOWF_{EwdPsIdH^Um4|PBS-h zakh}8y`L8L$x%-Gxy5|kGH8O~DB~JuP!vx;b%}^>dfcQ5i)2i` z#!9HV&83d3ZkvWZ>b+072Y-8#I;@Wz&*hKm{MEm3=g*lZOxDV@1T$>LC)mkaqN4k4 z(q)@8iwZvKePe2$kx8N=K(prPAgOzRBGn^UB45}!lxxDs6`7XizW+X#-M6|3lymP# zM4}F}NGf**!&EGyp-85EE`s8VR{knsQI-Ac;{w8Hjhd*sM+dm_qGiNZ?6ugZ__};? zmeIUBj$GWsTCjD&p$1w*sm0=1m8pVzjKJ%f7#I8L7mju2sF)9%V4(YolEFIFexUVWSUeN zYM3Y<5Qq#B*V0sqA z5tI~Mzj8ss13COr*(%q-|rJj-C0V&NeNrU?9)19E(wIb30~;<$ln;6X~Anaoi$J+6h2 z^`S1~P$Q#`or0i!L{~EL9$!l6>7!X&z(p}0%hN0&VTf5l719}3qVyXijiyD%U3Q=u zjBw;NX*{b^mHl5Fn-Fc9X=RFuJ;x&y-3ofDbFpq`t!`%GF(iDKwN%d(NwS%^Z9*@% zSI9I&%;5Rs|62*Gqipr$EN7&;kW*;{o5mfQJX*SqN;ZS_jh%G<|9Aid7XstY zfVe9Yns(2sd2*6-oN;pT7~#gbP12zzXEWZp?lJM@$t~iH$tjBqCP7C*m({sk+5xs_ zCPEWQoZ}Z~&n}MTmgZyF|;h3n-)m!J~$Xu6L(G_6s)U$LlreniO79k_sJsPH40 zXgn1kz*XAO2UF+(H@J%3VjoSr>bB6!l0qxfg;thP-K8QQDZ-2!W^-p$n4L1I%GX3x zOE6u!aI=4^W+T34HNMxN|*f-OS>LRYaR*P0_~FDxxap4y=sc(kw&6 zO*iZIAdKwBNoP>8M~j=)jaFR&mq9q|o@pvzrZkqZ(b(JSjf1auv%14Ft-`p09DDLb zOAFa9(fq$T{KCa<87pTMZexOtM{0P3DcjJ+Y!@ox*0HT0zv0jD@P5T2=jvJ#9K}ki z4xXVw!`gU5Ghd$RmKx8QoGZm~2T;VmqmQ8A=@Z(MV@6hH^cafR<>Q(dvKv)FV~OFa zHQfTTPFu-Yq!ipl`Io0vT$mqaU+Ch-E^4ahdcFf}fTBH#>vjFw4u}4W<1M2G70&|x zS>re7NGQ>es&Y0HcX{PnPPmrLjUhg?wHT(W9CI~ryh-4T9dkhw-Dgg^0OP;GFq2IH!V--o% zk@$%g&k%0nZX7NearL(&u9%*sktDFn?lD~vH}rD1X~iTN4RvONTl{h?cT{`heL-t5 z;g(+x>^@Z`+-wB{981_h4mUj0^4KzzWZi}BxyLc+b4Lf)kdKR3*FZH|u>TyIIR~CA zev&>lNqFK?*dWv@&wh8~)6Y!(oo{m0yvxKzL-SUb-0s`gIzRvUKxy!y2j|~*?NwJ^ zT|R4ijiW4FKqpl!y#9?5K z+Gpo|dPhB!m9d7)M^2SzP6-Ex8`O7_-|s)q{(evN`Lk!|hYBE6yn4+^<>aTYPAi@K z%H(LrzIk(>igzt&ymrzY-_I(i7sPG}2u1nduAVWW>DIiuMc?`F6Rxjca>~I=e*IkF zx60FJ1g}_q)6Hkz^RxTbbw0l3k@c_bf4jTy#@*J$p|_WQ^tX=>{r!{XYp*$BZ|od# z=Jtw7Q(7v%8*FZGorR%8d(H_??!4ioKXj#w^E!!O^inn;WJTY9`~Q$JcLegBU}!M^ zz5L%7{BgpsCjQr?i_V|?%M+$t9BXM`Hv9J1uUr4d{!`bUuy5t<-)oyWZQ~t72WsAI z`1yS!^t36r-f(yR^oP&=(XR64n7Uth?A*syPw`OYbK|1~ma-kFbdp1oC?dif=nU3$~B`jgQ;P)ro{@W*~PA%NEr7<{t z)!lbEPs~_-&nefhxp$#|!MlBPXRf_($JBw{C+`ehHD~tyzhn(3E&bJfrN329eXpwO zZnCtvWYg9yXNGSMOM7m=;|F*C@U9=7_Skjuv%AFg9j38-MM=l<-#ifQSoL4Ou9*DC zl^<8t|MXE&y#IlfWv5nE?frP(J=OYYPkrz-#)x%;ITrl>j{6>a>Y>8RF1`GssV7g` zaLX+(oW61MhPB;VBDw9%t!J#$TpN1mp6@>xZl5yc`In!5E*B8; z^hqB)6^}38xN%-1nMP=9dcnp?x1W6f$q)VP_1E@&P+Rr$Up!DB?Py#6t=8!e)?s+a zn;&@a)t{A@&3{7;*Iqv9rit%PtZb8B>fd|c-CvTPe(ITLy1Vzh`#*pC+w;$_Keb@? zrs1{gYEQh;hcO~2otFROO&?GG@bSk!GH%^|q<`J}nNv3Z_oh`Rx38DKeekMluKnGV zE3cj+iXs!l6?FRM1OL@~|NS3r#(=yaqXbyX9u>>tDa#I9>T*{d<_Xi&hEx)4UhZBob zwfM(HMa4&!+A66 z;`>f`_~4}nzw(1ietp`k+kddg{{9c9|8Q2mwezfR{O7kC>H<5LRL?v$x#FJ0Sg^~t z6WzOa@A=aC7oK{#8}xElFw%GFqmP{PJmt2tr##j0$U_f>CHB)-<-!0)#cY|q ztf+X|vP|Zr8$@4oM_YSIQ~i|Aw`N~`^_;FbL=fiE-d-vQS;KhsuKx*r`uEV8KaG65 z$o%$QW+X2!<7EE(53{%5nHQa#_qUJp^AG>CxOm?D69?bRAI$&RcNQ%C&hP(t{x2s# zJ-ay8(lWdFSO4|p(u*ctRC@m8uasRp<>In|4|nh|n}t*TKNQOEtf>4st*WkJwTs>? zyy~iw7yj~{Z~wL7x^=bJKCnw^df& z@skHOpMF;5p=&<6y87e#q6dop@=v<7XhG>MW%HjqP%+_&{cld3FmZ0-_40{D*4@P= zcb}x(bnd+m?)uSau+HiC|M=j<1t(0IHS4^+&%O{?kl%Isa|KhEZkONLH*;cQ@unH~ zzJJ**?>~H5_BY{*Q}4L5)w$`q8Pzii?A_bG`5%{@aeChF#u{zbtb1pkGIQ1s@7f(& z_~aA%lOK9vKCgS_?G4YoGV$)a|MbVhzx!%@K~?066JA{W{N3B8Pk-g5AK(AbtEp4Z znz8e~hm_rWw{LskC+|=BQta6qyN8Odx#qSdk*QOwOJ!qOM`6(qpML78x^tSFufO5C z@3qagE}2^K>%zi2?p(5R;WJAUot;IO*IiNnpO+$Iz2veRZ@lA<%U+mT_?%Dt=)jLI zc=pk+KK*7T} zUGl3J+s;br*Wd7Z{O^~Zo&HDjv%Q(~%0GGhvB8-$Cm!nAV|Tj&MfW}X!mL>nj89(r zvv&V|FMN92frIbw`R+%577x5R>&g$GYFOGBd;Ok!%fCP8;WPiVYgffRlcpqR-TU&= zhFIgbv)fC~m{ysZ*4X&UQy)D2Xw~2U_Sm71KK%!1gnshzPkq9@Pd@R_HT^4YsXqOj zS63f7_q>{2a~`Ovez)gm1^KQ||1dBTCBtDD!l;PRLP3_;@GzBR0f;O~1c*#9d>;=n z84kMvG-WwDB+F7n5QMN4C4$U`F|sz5rD4GEijpKnG5#gStdt@Wi$o;+FH6#p`?s+K zG7K^)Dk8%yDoaw7fh-BbMMcB1Bw=hm{CnqQSRVFbMh?jsbzYLBB8kYdKm?3yE`daN zOw4eY3^R!cK!oApAq;EG+&dtwM3M**N+d}tEQv^wLhM9Dj>y;@DUu80IV?-0gkQrL z{*cHKAuJ8c!x9s)Cm57cmSH#yQk27C1V1D4i2LO|xVIzTKldfSh5+O9t=Bg38*a>#^bIl?3+@eyGaZsggB8+mp%evOP2B8C(l=ZcKp9i1UeVF>3kQsUw= z;Z;XR!Zb>NM5B264Tgo15>^zUx#+cWG#V)`1~0g+BqPFrB$W)gBa0v@@F=Iz5h>yV zn}=pClp;5XQe(Bn>0ML?l8uQ4v{^BZLDmDj?;9i=%SbrCo{`#gKN1 zAPf&lQY0crBLpcRQW6Dx=AURJIua=Xh(scU6oL>5huy}$FcR;`$cQB2mn_Q!SpktT1oFs8ln{9Y%OT`O9js_X#;g>mkK@Jxljv|&sLFQ8$86k3{BoZkBImt4qW3_}e(p(GmN z>0S;FeJEswC|r<-aU$knw|RZo_HZ;3mb}2n$N(eJ!XZIGnJh&>Lar^5NCcT|QDI?W z5dkvnMnh&yDl9A{MMEfHC5RyOBaC40x^ZR@p2E&EZlmfaYwW#5n1vfa^Ic8*-jeio@^ zYvfwCTCQd1MX}vlmXvE*lU&OnHu$DL^oI#@xLecpdO4o8(D$_&g9yptZX@H&?^e>9 zK2R^0Y}mMLOL$|y5niP@sgijm%}Tn<(v;leO2yGK;Z;ULwK85BdP2;zRZHuZ!u%3;OQl=(Ua_N$li5MkIc!j{Ua@ZL#)q0sned#iG$YD!W z5=I7lBRA9~w7zgcag_P!X@}OxdO2<+)cI&3RV}%p&Nh`yLmj4tZ5U3*a8z4%bB;bY1nUg_*wThBHv~UZc77KRCDnaQ6}jZ&r_R?B zJL=^ykEKyBCo~>Kb8#0QGF*~YtfZD%T&AYOO4c!!VBnQ*-RNKJor6k$CZ(<`>o`Wn zgQxr8b%%pY;iImXaTvOxB#xe=7B4l7c|X%9ErWY>OZvQ%5%YQYg~fGt*8B``v*u@k zgMewMQ;yB6$l;WwcGt^=U$pOW!yGue-_3?O;Pshj*D`SfBdt1Wz3f<7wa!6AJGNz> zC^rP_97Lqgyv0O(i^z5CO9aGxH%y=HbtR=G5^Bb6Pj0A7x-?~L=c@H`S!rph+>nEA z-9mS44RxmCq&#}e7#R+6%ji*$rA{|>en0wF*B^^qmfGDgisWAinHz$iOHmx{yh1q= z%C)FCj-_>F9o4Rv>l_Z1FVfwLQn{f{%a~aw%*orO_kThA4Rv;3GQ1$G(8Go3)@Xj}1m`Tw+YEjtKio1-m~3Kk>bbG}!>Bf>y%nx_)nqe*K^xzfz( xwYqImg?t*iHj+@gPJ`e`A_vv&Xh literal 0 HcmV?d00001 diff --git a/apps/web/package.json b/apps/web/package.json index 21ac8caba0b1e..a60eb801260cf 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -34,6 +34,7 @@ "@noble/hashes": "catalog:", "@pierre/diffs": "catalog:", "@pierre/trees": "1.0.0-beta.6", + "@pierre/words": "file:deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz", "@t3tools/client-runtime": "workspace:*", "@t3tools/contracts": "workspace:*", "@t3tools/provider-core": "workspace:*", @@ -74,24 +75,16 @@ "jszip": "3.10.1", "katex": "^0.18.2", "lucide-react": "^0.564.0", - "mdast-util-from-markdown": "^2.0.3", - "micromark-util-combine-extensions": "^2.0.1", "pdfjs-dist": "6.4.299", "pele": "catalog:", + "property-information": "^7.2.0", "react": "catalog:", "react-dom": "catalog:", - "react-markdown": "^10.1.0", - "remark-gfm": "catalog:", - "remark-math": "6.0.0", - "remark-parse": "catalog:", - "remark-rehype": "catalog:", "saxes": "6.0.0", "sql.js": "1.15.0", "tailwind-merge": "^3.4.0", "tiff": "7.1.3", - "unified": "catalog:", "use-sync-external-store": "^1.6.0", - "vfile": "^6.0.3", "zustand": "^5.0.11" }, "devDependencies": { @@ -103,7 +96,6 @@ "@types/compression": "^1.8.1", "@types/culori": "^4.0.1", "@types/hast": "^3.0.4", - "@types/mdast": "^4.0.4", "@types/react": "catalog:", "@types/react-dom": "catalog:", "@types/sql.js": "1.4.11", @@ -113,7 +105,6 @@ "@vitest/browser-playwright": "5.0.5", "compression": "^1.8.2", "gt": "2.27.0", - "micromark-util-types": "catalog:", "oxc-transform-react": "~0.152.0", "playwright": "1.64.1", "tailwindcss": "^4.0.0", diff --git a/apps/web/src/components/ChatMarkdown.browser.test.tsx b/apps/web/src/components/ChatMarkdown.browser.test.tsx index 0586a724b0c56..faca71b4a101f 100644 --- a/apps/web/src/components/ChatMarkdown.browser.test.tsx +++ b/apps/web/src/components/ChatMarkdown.browser.test.tsx @@ -2,7 +2,6 @@ import { MISSING_FILE_ACCESS_MESSAGE } from "@t3tools/client-runtime/state/asset import { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { AsyncResult } from "effect/reactivity"; import { type ReactElement } from "react"; -import remarkGfm from "remark-gfm"; import { describe, expect, it, vi } from "vite-plus/test"; import { commands, page, userEvent } from "vite-plus/test/browser"; @@ -15,11 +14,8 @@ import { selectActiveRightPanelSurface, useRightPanelStore, } from "../rightPanelStore"; -import { - CHAT_USER_MARKDOWN_REMARK_PLUGINS, - remarkEnableOrderedListNumbers, -} from "@t3tools/shared/markdownPipeline"; -import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskList"; +import type { MarkdownExtensions } from "../markdown/wordsHast"; +import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskEdits"; import { HostImageUrlContext } from "./chat/hostImageUrl"; import { getSyntaxHighlighterPromise } from "~/lib/syntaxHighlighting"; @@ -28,14 +24,14 @@ const { workspaceSearch, filesystemMetadata } = vi.hoisted(() => ({ filesystemMetadata: vi.fn(), })); const parsedSources = vi.hoisted(() => [] as string[]); -vi.mock(import("mdast-util-from-markdown"), async (original) => { +vi.mock(import("../markdown/wordsHast"), async (original) => { const actual = await original(); return { ...actual, - fromMarkdown: ((source: string, ...rest: never[]) => { - parsedSources.push(String(source)); - return (actual.fromMarkdown as (...args: unknown[]) => unknown)(source, ...rest); - }) as typeof actual.fromMarkdown, + wordsHast: (source, options) => { + parsedSources.push(source); + return actual.wordsHast(source, options); + }, }; }); @@ -188,7 +184,7 @@ function buttonsLabelled(container: HTMLElement, label: string) { ); } -const SOURCE_NUMBER_PLUGINS = [remarkEnableOrderedListNumbers]; +const USER_MESSAGE = { userMessage: true }; it("keeps decimal markers in nested user lists while documents keep their counter styles", async () => { setup(); @@ -201,7 +197,7 @@ it("keeps decimal markers in nested user lists while documents keep their counte cwd={undefined} text={text} className="user-message-markdown" - extraRemarkPlugins={SOURCE_NUMBER_PLUGINS} + extensions={USER_MESSAGE} />

    @@ -312,36 +308,24 @@ it("reuses the parse of a streaming reply's finished blocks when it remounts", a expect(parsedSources.filter((source) => source.includes("Finished block"))).toHaveLength(1); }); -it("reuses the parse of a remounted message that has stable extra plugins", async () => { +it("reuses the parse of a remounted message that has stable extensions", async () => { setup(); - const parsed = vi.fn(); - const countingPlugins = [() => () => void parsed()]; - const message = ( - - ); + const extensions = { userMessage: true }; + const message = ; { await using first = await render( - , + , ); await first.rerender(message); } await using screen = await render(message); await expect.element(screen.getByText("Cached text")).toBeVisible(); - expect(parsed).toHaveBeenCalledTimes(1); - const changed = vi.fn(); + const parses = () => parsedSources.filter((source) => source === "Cached text").length; + expect(parses()).toBe(1); await screen.rerender( - () => void changed()]} - />, + , ); - expect(changed).toHaveBeenCalledTimes(1); + expect(parses()).toBe(2); }); it("highlights a code block's own source when an earlier block of the same length was cached", async () => { @@ -399,6 +383,45 @@ describe("ChatMarkdown external link labels", () => { }); }); +describe("ChatMarkdown link tooltips", () => { + it("shows each link's address on one shared tooltip as the pointer moves between links", async () => { + setup(); + await using screen = await render( + , + ); + await userEvent.hover(screen.getByRole("link", { name: /First/ })); + await expect.element(page.getByText("https://example.com/a")).toBeVisible(); + await userEvent.hover(screen.getByRole("link", { name: /Second/ })); + await expect.element(page.getByText("https://example.org/b")).toBeVisible(); + expect(document.querySelectorAll('[data-slot="tooltip-popup"]')).toHaveLength(1); + }); +}); + +describe("ChatMarkdown details", () => { + it("opens collapsed details by click, and by keyboard without losing focus", async () => { + setup(); + await using screen = await render( + First\n\nHidden one\n\n\n\n
    Second\n\nHidden two\n\n
    " + } + />, + ); + await userEvent.click(screen.getByRole("button", { name: "First" })); + await expect.element(screen.getByText("Hidden one")).toBeVisible(); + await userEvent.tab(); + const second = screen.getByRole("button", { name: "Second" }); + await expect.element(second).toHaveFocus(); + await userEvent.keyboard("{Enter}"); + await expect.element(screen.getByText("Hidden two")).toBeVisible(); + await expect.element(screen.getByRole("button", { name: "Second" })).toHaveFocus(); + }); +}); + describe("ChatMarkdown streaming", () => { it("runs only a complete single-line shell block after a click", async () => { setup(); @@ -802,12 +825,12 @@ describe("ChatMarkdown copy", () => { "copies and selects user lines the same whether their typed indentation shows: $text", async (copy) => { setup(); - const copied = async (extraRemarkPlugins: typeof CHAT_USER_MARKDOWN_REMARK_PLUGINS) => { + const copied = async (extensions: MarkdownExtensions) => { await using screen = await renderText(copy.text, { className: "user-message-markdown", lineBreaks: true, parseRawHtml: false, - extraRemarkPlugins, + extensions, }); const range = document.createRange(); range.selectNodeContents(screen.container); @@ -824,9 +847,9 @@ describe("ChatMarkdown copy", () => { // A drag or anything else that reads the selection gets its text, not the copy payload. return { payload: chatMarkdownClipboardPayload(selection), selected: selection.toString() }; }; - const shown = await copied(CHAT_USER_MARKDOWN_REMARK_PLUGINS); + const shown = await copied({ userMessage: true, leadingWhitespace: true }); // The user pipeline as it was before typed indentation was shown. - expect(shown).toEqual(await copied([[remarkGfm, { singleTilde: false }]])); + expect(shown).toEqual(await copied({ userMessage: true })); }, ); @@ -885,7 +908,7 @@ describe("ChatMarkdown copy", () => { setup(); await using screen = await renderText( source, - userMessage ? { extraRemarkPlugins: SOURCE_NUMBER_PLUGINS } : {}, + userMessage ? { extensions: USER_MESSAGE } : {}, ); const itemText = (shown: string) => [...screen.container.querySelectorAll("li")] diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index 8c0d14520871d..979d1858cafc1 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -13,7 +13,7 @@ import { extractMarkdownLinkHrefs, inlineCodeFilePathCandidate, } from "@t3tools/shared/markdownLinks"; -import { taskListMarkerOffset } from "@t3tools/shared/markdownTaskList"; +import { taskListMarkerOffset } from "@t3tools/shared/markdownTaskEdits"; import { isHostPath, resolveWorkspaceFilePath } from "@t3tools/shared/path"; import { usePullRequestLinking } from "~/hooks/usePullRequestLinking"; import { @@ -21,14 +21,7 @@ import { AuthOrchestrationOperateScope, SOURCE_CONTROL_MEDIA_ASSET, } from "@t3tools/contracts"; -import { - CHAT_MARKDOWN_REMARK_PLUGINS, - CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS, - CHAT_MARKDOWN_REHYPE_PLUGINS, - chatMarkdownImageSource, - decodeMarkdownLinkEscapes, - remarkAssistantInsights, -} from "@t3tools/shared/markdownPipeline"; +import { chatMarkdownImageSource } from "@t3tools/shared/markdownHast"; import { useAtomValue } from "@effect/atom-react"; import { COMPOSER_CONTEXT_CLIPBOARD_MIME, @@ -94,27 +87,17 @@ import React, { useState, type ReactNode, } from "react"; -import type { - Components, - ExtraProps as ReactMarkdownExtraProps, - Options as ReactMarkdownOptions, -} from "react-markdown"; -import { createIncrementalMarkdownPlugin } from "../markdown-incremental"; -import type { Pluggable, PluggableList } from "unified"; -import { defaultUrlTransform } from "react-markdown"; import { parseAssistantCitationHref } from "@t3tools/shared/assistantCitations"; import { parseComposerContextHref } from "@t3tools/shared/composerContextReferences"; import { parseThreadLinkHref } from "@t3tools/shared/threadLinks"; import { AssistantCitationEmbed } from "./chat/AssistantCitationChip"; import { MarkdownThreadLink } from "./chat/MarkdownThreadLink"; -import { mathKind } from "@t3tools/shared/markdownMath"; -import remarkMath from "remark-math"; +import { artifactTemplateFromHastProperties } from "@t3tools/shared/codexArtifactTemplates"; import { - artifactTemplateFromHastProperties, + decodeMarkdownLinkEscapes, renderCodexInlineDirectivesAsMarkdown, -} from "@t3tools/shared/codexMarkdownDirectives"; +} from "../markdown/markdownText"; import { renderSkillInlineMarkdownChildren } from "./chat/SkillInlineText"; -import { MarkdownMath } from "./chat/MarkdownMath"; import { resolveMarkdownMediaPreview, type ExpandedImagePreview, @@ -131,7 +114,7 @@ import { resolveExternalWebLinkHost, showExternalLinkContextMenu, } from "./chat/externalLinkContextMenu"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; +import { SharedTooltipProvider, SharedTooltipTrigger } from "./ui/shared-tooltip"; import { Button } from "./ui/button"; import { stackedThreadToast, toastManager } from "./ui/toast"; import { recordVisitForThread } from "../browserHistoryStore"; @@ -214,6 +197,15 @@ import { PullRequestLinkPreview } from "./pullRequest/PullRequestLinkPreview"; import { IssueLinkPreview, IssueLinkPreviewFallback } from "./issue/IssueLinkPreview"; import { MarkdownCodeBlock, SuspenseShikiCodeBlock } from "./chat/MarkdownCodeBlock"; import { createMarkdownRenderer } from "./chat/markdownRenderer"; +import type { MarkdownExtensions, WordsHastOptions } from "../markdown/wordsHast"; +import { + type MarkdownIslandOptions, + renderHastWithIslands, + withProperties, +} from "./chat/markdownIslands"; +import type { Element as HastElement } from "hast"; +import { matchInlineSkills } from "@t3tools/shared/inlineSkills"; +import { collectComposerModelMentions } from "@t3tools/client-runtime/composer-model-mentions"; import { splitMarkdownBlocks } from "./chat/markdownStreamBlocks"; import { MarkdownMermaidCodeBlock } from "./chat/MarkdownMermaidCodeBlock"; import { MarkdownTable } from "./chat/MarkdownTable"; @@ -230,9 +222,7 @@ import { import { MarkdownExternalLinkContent } from "./chat/MarkdownExternalLink"; import { MarkdownFileLink } from "./chat/MarkdownFileLink"; import { canUseMarkdownFileShellActions } from "./chat/MarkdownFileLink.logic"; -import { rehypeChipPunctuation } from "./chat/markdownChipPunctuation"; -import { handleMarkdownFragmentClick, rehypeHeadingIds } from "./chat/markdownFragments"; -import { rehypeTextDirection } from "./chat/markdownTextDirection"; +import { handleMarkdownFragmentClick } from "./chat/markdownFragments"; import { hastHasText, hastPlainTextDeep, plainHastText } from "./chat/markdownHast.logic"; import { extractCodeBlock, @@ -268,8 +258,8 @@ interface ChatMarkdownProps { imageBaseDir?: string | undefined; workspaceMutationId?: string | null | undefined; onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined; - /** Keep one list per configuration (a module constant): it keys the shared parse cache. */ - extraRemarkPlugins?: NonNullable; + /** Keep one object per configuration (a module constant): it keys the shared parse cache. */ + extensions?: MarkdownExtensions | undefined; renderContextReference?: ((reference: ChatMarkdownContextReference) => ReactNode) | undefined; /** Loads media a source control host keeps behind a credential through the server, which holds `cwd`'s; without it a private repository's uploads load unauthenticated and 404. */ @@ -289,7 +279,7 @@ export interface ChatMarkdownContextReference { } const EMPTY_MARKDOWN_SKILLS: ReadonlyArray = []; -const EMPTY_REMARK_PLUGINS: NonNullable = []; +const NO_EXTENSIONS: MarkdownExtensions = {}; const ARTIFACT_TEMPLATE_ICON_BY_KIND = { document: FileTextIcon, @@ -423,19 +413,29 @@ function normalizeMarkdownLinkHrefKey(href: string): string { : rewrittenHref; } -// Heading ids are added after sanitizing, which would prefix them a second time. -const CHAT_MARKDOWN_RENDER_REHYPE_PLUGINS = [ - ...CHAT_MARKDOWN_REHYPE_PLUGINS, - rehypeHeadingIds, - rehypeTextDirection, - rehypeChipPunctuation, -] satisfies NonNullable; +/** A component per element, with the hast node it renders, as react-markdown typed them. */ +type MarkdownComponents = { + [Tag in keyof React.JSX.IntrinsicElements]?: React.ComponentType< + React.JSX.IntrinsicElements[Tag] & { node?: HastElement | undefined } + >; +}; -const CHAT_MARKDOWN_LITERAL_HTML_REHYPE_PLUGINS = [ - rehypeHeadingIds, - rehypeTextDirection, - rehypeChipPunctuation, -] satisfies NonNullable; +// react-markdown's defaultUrlTransform: relative URLs, and absolute ones with a safe protocol. +const SAFE_PROTOCOL = /^(?:https?|ircs?|mailto|xmpp)$/i; +function safeUrl(value: string): string { + const colon = value.indexOf(":"); + const before = (character: string) => { + const at = value.indexOf(character); + return at !== -1 && colon > at; + }; + return colon === -1 || + before("/") || + before("?") || + before("#") || + SAFE_PROTOCOL.test(value.slice(0, colon)) + ? value + : ""; +} function markdownUrlTransform(href: string) { if (parseAssistantCitationHref(href)) return href; @@ -443,7 +443,7 @@ function markdownUrlTransform(href: string) { if (parseThreadLinkHref(href)) return href; if (isWindowsDrivePathHref(href)) return href; if (isLocalEditorFileHref(href)) return href; - return rewriteMarkdownFileUriHref(href) ?? defaultUrlTransform(href); + return rewriteMarkdownFileUriHref(href) ?? safeUrl(href); } const NO_MARKDOWN_EDITORS: ReadonlyArray = []; @@ -486,11 +486,16 @@ const markdownServerConfigFieldsAtom = Atom.family((environmentId: EnvironmentId }).pipe(Atom.withLabel("markdown-server-config-fields")), ); -function fileLinkSourcesKey( +interface BlockFileLinkSources { + readonly hrefs: ReadonlyArray; + readonly spans: ReadonlyArray; +} + +function blockFileLinkSources( text: string, cwd: string | undefined, imageBaseDir: string | undefined, -): string { +): BlockFileLinkSources { const hrefs = extractMarkdownLinkHrefs(renderCodexInlineDirectivesAsMarkdown(text)) .filter((href) => !parseComposerContextHref(href)) .map(decodeMarkdownLinkEscapes) @@ -499,7 +504,47 @@ function fileLinkSourcesKey( const spans = extractInlineCodeSpans(text).filter((span) => resolveInlineCodeFileLinkMeta(span, cwd, imageBaseDir ?? cwd), ); - return JSON.stringify([[...new Set(hrefs)], [...new Set(spans)]]); + return { hrefs, spans }; +} + +// Links and code spans never cross blocks: a streamed reply rescans only its open last block. +const MAX_CACHED_BLOCK_CHARS = 2_000_000; +const finishedBlockFileLinkSources = new Map(); +let cachedBlockChars = 0; + +function fileLinkSourcesKey( + text: string, + cwd: string | undefined, + imageBaseDir: string | undefined, + streamingBlocks: ReadonlyArray | null, +): string { + if (!streamingBlocks) { + const { hrefs, spans } = blockFileLinkSources(text, cwd, imageBaseDir); + return JSON.stringify([[...new Set(hrefs)], [...new Set(spans)]]); + } + const config = `${cwd ?? ""}\u0000${imageBaseDir ?? ""}\u0000`; + const hrefs = new Set(); + const spans = new Set(); + const last = streamingBlocks.length - 1; + for (const [index, block] of streamingBlocks.entries()) { + // The last block still grows; caching each of its prefixes would only fill the cache. + const key = config + block; + let sources = index === last ? undefined : finishedBlockFileLinkSources.get(key); + if (!sources) { + sources = blockFileLinkSources(block, cwd, imageBaseDir); + if (index !== last) { + if (cachedBlockChars + key.length > MAX_CACHED_BLOCK_CHARS) { + finishedBlockFileLinkSources.clear(); + cachedBlockChars = 0; + } + finishedBlockFileLinkSources.set(key, sources); + cachedBlockChars += key.length; + } + } + for (const href of sources.hrefs) hrefs.add(href); + for (const span of sources.spans) spans.add(span); + } + return JSON.stringify([[...hrefs], [...spans]]); } function resolveFileLinkSources( @@ -525,27 +570,30 @@ function resolveFileLinkSources( return { markdownFileLinkMetaByHref, inlineCodeFileLinkMetaByText, fileLinkParentSuffixByPath }; } -function useChatMarkdownState({ - text, - inline = false, - cwd, - agentDirectories, - threadRef, - pullRequestPanelRef, - environmentId: explicitEnvironmentId, - onTaskListChange, - isStreaming = false, - skills = EMPTY_MARKDOWN_SKILLS, - onUseArtifactTemplate, - onRunShellCommand, - imageBaseDir, - workspaceMutationId, - onImageExpand, - renderContextReference, - headingLevelOffset = 0, - sourceControlMedia = false, - sourceControlMediaRepository, -}: ChatMarkdownProps) { +function useChatMarkdownState( + { + text, + inline = false, + cwd, + agentDirectories, + threadRef, + pullRequestPanelRef, + environmentId: explicitEnvironmentId, + onTaskListChange, + isStreaming = false, + skills = EMPTY_MARKDOWN_SKILLS, + onUseArtifactTemplate, + onRunShellCommand, + imageBaseDir, + workspaceMutationId, + onImageExpand, + renderContextReference, + headingLevelOffset = 0, + sourceControlMedia = false, + sourceControlMediaRepository, + }: ChatMarkdownProps, + streamingBlocks: ReadonlyArray | null, +) { const gt = useGT(); const messages = useMessages(); const resolvedTheme = useRenderedAppearance(); @@ -743,7 +791,7 @@ function useChatMarkdownState({ // Keyed by the file links found, not the text, so streamed text that adds none keeps the // renderer context, and every block reading it, unchanged. // A template literal marks the key as a string, so the compiler memoizes the maps on its value. - const fileLinksKey = `${fileLinkSourcesKey(text, cwd, imageBaseDir)}`; + const fileLinksKey = `${fileLinkSourcesKey(text, cwd, imageBaseDir, isStreaming ? (streamingBlocks ?? splitMarkdownBlocks(text) ?? [text]) : null)}`; const { markdownFileLinkMetaByHref, inlineCodeFileLinkMetaByText, fileLinkParentSuffixByPath } = resolveFileLinkSources(fileLinksKey, cwd, imageBaseDir); const resolveThreadPullRequest = ( @@ -1087,7 +1135,7 @@ function markdownHeadingRenderer(level: 1 | 2 | 3 | 4 | 5 | 6) { return function MarkdownHeading({ node: _node, ...props - }: ComponentProps & ReactMarkdownExtraProps) { + }: ComponentProps & { node?: HastElement | undefined }) { const { headingLevelOffset } = use(ChatMarkdownRendererContext); return ( ; } - return ( - - - {href} - - ); + return ; } const label = nodeToPlainText(children); @@ -1533,18 +1576,9 @@ const CHAT_MARKDOWN_COMPONENTS = { ); }, code: function MarkdownCode({ node, children, className, ...props }) { - const { cwd, imageBaseDir, inlineCodeFileLinkMetaByText, fileLinkChip, mathEnabled, inline } = - use(ChatMarkdownRendererContext); - const math = mathEnabled ? mathKind(className) : null; - if (math) { - return ( - - ); - } + const { cwd, imageBaseDir, inlineCodeFileLinkMetaByText, fileLinkChip } = use( + ChatMarkdownRendererContext, + ); if (node?.properties?.dataInlineCode != null) { const codeText = nodeToPlainText(children); const fileLinkMeta = @@ -1769,15 +1803,9 @@ const CHAT_MARKDOWN_COMPONENTS = { }, pre: function MarkdownPre({ node, children, ...props }) { const gt = useGT(); - const { - resolvedTheme, - diffThemeName, - expandMedia, - isStreaming, - onRunShellCommand, - inline, - mathEnabled, - } = use(ChatMarkdownRendererContext); + const { resolvedTheme, diffThemeName, expandMedia, isStreaming, onRunShellCommand } = use( + ChatMarkdownRendererContext, + ); const text = use(ChatMarkdownTextContext); const codeBlock = extractCodeBlock(children); if (!codeBlock) { @@ -1785,15 +1813,6 @@ const CHAT_MARKDOWN_COMPONENTS = { } const language = extractFenceLanguage(codeBlock.className); - if ( - mathEnabled && - language === "math" && - (!isStreaming || - mathKind(codeBlock.className) === "display" || - isClosedCodeFence(node, text, codeBlock.code)) - ) { - return ; - } const fenceTitle = extractFenceTitle(extractPreCodeMeta(node)); const highlightedCode = ( ); }, -} satisfies Components; - -const REMARK_MATH: Pluggable = [remarkMath, { singleDollarTextMath: true }]; -// Shared lists, so every message with the same options shares a processor and its cache. -const CHAT_MARKDOWN_REMARK_PLUGIN_SETS = { - plain: CHAT_MARKDOWN_REMARK_PLUGINS, - breaks: CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS, - math: [REMARK_MATH, ...CHAT_MARKDOWN_REMARK_PLUGINS], - mathBreaks: [REMARK_MATH, ...CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS], -} satisfies Record; - -const combinedPlugins = new WeakMap>(); +} satisfies MarkdownComponents; -// One combined list per pair, so a stable extra list shares a renderer and its parse cache. -const INSIGHT_REMARK_PLUGINS: PluggableList = [remarkAssistantInsights]; +const markdownOptions = new WeakMap>(); -function withExtraPlugins(shared: PluggableList, extra: PluggableList): PluggableList { - if (extra.length === 0) return shared; - let byShared = combinedPlugins.get(extra); - if (!byShared) combinedPlugins.set(extra, (byShared = new WeakMap())); - let combined = byShared.get(shared); - if (!combined) byShared.set(shared, (combined = [...shared, ...extra])); - return combined; +/** One options object per configuration, so equal messages share a renderer and its cache. */ +function wordsOptions( + extensions: MarkdownExtensions, + flags: Omit, +): WordsHastOptions { + let byFlags = markdownOptions.get(extensions); + if (!byFlags) markdownOptions.set(extensions, (byFlags = new Map())); + const key = `${+flags.math}${+flags.breaks}${+flags.escapeHtml}${+flags.insights}`; + let options = byFlags.get(key); + if (!options) byFlags.set(key, (options = { ...flags, extensions })); + return options; } const markdownRenderers = new WeakMap< - PluggableList, - WeakMap> + WordsHastOptions, + ReturnType >(); -function markdownRenderer(remarkPlugins: PluggableList, rehypePlugins: PluggableList) { - let byRehype = markdownRenderers.get(remarkPlugins); - if (!byRehype) markdownRenderers.set(remarkPlugins, (byRehype = new WeakMap())); - let renderer = byRehype.get(rehypePlugins); +function markdownRenderer(markdown: WordsHastOptions) { + let renderer = markdownRenderers.get(markdown); if (!renderer) { renderer = createMarkdownRenderer({ - remarkPlugins, - rehypePlugins, + markdown, components: CHAT_MARKDOWN_COMPONENTS, urlTransform: markdownUrlTransform, }); - byRehype.set(rehypePlugins, renderer); + markdownRenderers.set(markdown, renderer); } return renderer; } +type ChatMarkdownComponentState = ReturnType["componentState"]; + +function hastClassName(node: HastElement): string | undefined { + const { className } = node.properties; + return Array.isArray(className) ? className.join(" ") : (className as string | undefined); +} + +// Paragraphs and list items turn skill and model mentions in their text into chips, except in +// code and links, as SkillInlineText does. +function hastTextHasChip(node: HastElement, skills: ReadonlyArray): boolean { + return node.children.some((child) => + child.type === "text" + ? (skills.length > 0 && !matchInlineSkills(child.value, skills).next().done) || + collectComposerModelMentions(child.value).length > 0 + : child.type === "element" && + child.tagName !== "code" && + child.tagName !== "a" && + hastTextHasChip(child, skills), + ); +} + +const HEADING_LEVELS: Record = { h1: 1, h2: 2, h3: 3, h4: 4, h5: 5, h6: 6 }; + +const markdownIslandOptionsByState = new WeakMap< + ChatMarkdownComponentState, + MarkdownIslandOptions +>(); + +/** Which elements need CHAT_MARKDOWN_COMPONENTS, and what the others' components add. */ +function markdownIslandOptions(state: ChatMarkdownComponentState): MarkdownIslandOptions { + const cached = markdownIslandOptionsByState.get(state); + if (cached) return cached; + const { + cwd, + headingLevelOffset, + imageBaseDir, + inlineCodeFileLinkMetaByText, + onTaskListChange, + skills, + } = state; + const options: MarkdownIslandOptions = { + components: CHAT_MARKDOWN_COMPONENTS, + variant: String(headingLevelOffset), + isIsland: (node) => { + switch (node.tagName) { + case "a": + case "img": + case "pre": + case "details": + case "table": + return true; + case "blockquote": + return GITHUB_ALERT_PRESENTATIONS[String(node.properties.dataAlert ?? "")] !== undefined; + case "div": + return artifactTemplateFromHastProperties(node.properties) !== null; + case "input": + return node.properties.type === "checkbox" && onTaskListChange !== undefined; + case "code": { + if (node.properties.dataInlineCode == null) return false; + const codeText = hastPlainTextDeep(node); + return ( + (inlineCodeFileLinkMetaByText.get(codeText.trim()) ?? + resolveInlineCodeFileLinkMeta(codeText, cwd, imageBaseDir ?? cwd)) != null + ); + } + case "p": + case "li": + return hastTextHasChip(node, skills); + default: + return false; + } + }, + staticElement: (node) => { + const level = HEADING_LEVELS[node.tagName]; + if (level !== undefined) { + return headingLevelOffset > 0 + ? withProperties(node, { ariaLevel: Math.min(level + headingLevelOffset, 6) }) + : node; + } + switch (node.tagName) { + case "ol": { + const itemValues = node.children.flatMap((child) => + child.type === "element" && child.tagName === "li" ? [child.properties.value] : [], + ); + const gutter = orderedListGutterStyle(itemValues, node.properties.start); + if (!gutter) return node; + const authored = typeof node.properties.style === "string" ? node.properties.style : ""; + return withProperties(node, { + style: `${authored}${authored ? ";" : ""}--list-gutter:${gutter["--list-gutter"]}`, + }); + } + case "li": + return hastClassName(node)?.includes("task-list-item") + ? withProperties(node, { dataListItemOffset: node.position?.start.offset }) + : node; + case "input": + return node.properties.type === "checkbox" + ? withProperties(node, { readOnly: true }) + : node; + default: + return node; + } + }, + }; + markdownIslandOptionsByState.set(state, options); + return options; +} + const MarkdownSource = memo(function MarkdownSource({ text, - remarkPlugins, - rehypePlugins, - shared, + markdown, cache, }: { text: string; - remarkPlugins: PluggableList; - rehypePlugins: PluggableList; - /** The plugins are one of the shared sets. */ - shared: boolean; + markdown: WordsHastOptions; /** The text will not change again; streamed text would only fill the cache with prefixes. */ cache: boolean; }) { - // Per-instance plugins, such as the incremental parser, set up their state on every render. - const render = shared - ? markdownRenderer(remarkPlugins, rehypePlugins) - : createMarkdownRenderer({ - remarkPlugins, - rehypePlugins, - components: CHAT_MARKDOWN_COMPONENTS, - urlTransform: markdownUrlTransform, - }); - const element = render(text); + const render = markdownRenderer(markdown); + const entry = render.parse(text); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Caching during render would make React Compiler rebuild the element when `cache` flips. useEffect(() => { - if (shared && cache) render.remember(text, element); - }, [render, text, element, shared, cache]); - return {element}; + if (cache) render.remember(text, entry); + }, [render, text, entry, cache]); + const islandState = use(ChatMarkdownRendererContext); + return ( + + {islandState + ? renderHastWithIslands(entry.tree, markdownIslandOptions(islandState)) + : render.element(entry)} + + ); }); function ChatMarkdown({ @@ -1935,51 +2045,28 @@ function ChatMarkdown({ inline = false, lineBreaks = false, parseRawHtml = true, - extraRemarkPlugins = EMPTY_REMARK_PLUGINS, + extensions = NO_EXTENSIONS, renderInsights = false, ...props }: ChatMarkdownProps) { - const { componentState, handleCopy, markdownRef, localMediaPreview, closeLocalMediaPreview } = - useChatMarkdownState({ text, inline, ...props }); - const hasInsights = renderInsights && text.includes("★ Insight"); - // Streaming re-renders only the last block; offsets for task edits need the whole text. + // Streaming re-renders only the last block; offsets for task edits, and extensions that read + // the whole message, need the whole text. const streamingBlocks = - props.isStreaming === true && - !inline && - extraRemarkPlugins.length === 0 && - !props.onTaskListChange - ? splitMarkdownBlocks(text) + props.isStreaming === true && !inline && extensions === NO_EXTENSIONS && !props.onTaskListChange + ? (splitMarkdownBlocks(text) ?? [text]) : null; - const incrementalParsing = - props.isStreaming === true && - !hasInsights && - streamingBlocks === null && - extraRemarkPlugins.length === 0 && - /(?:^|\n) {0,3}(?:`{3}|~{3})/.test(text); + const { componentState, handleCopy, markdownRef, localMediaPreview, closeLocalMediaPreview } = + useChatMarkdownState({ text, inline, ...props }, streamingBlocks); const Root = inline ? "span" : "div"; const bindMarkdownRef = (node: HTMLElement | null) => { markdownRef.current = node; }; - const sharedRemarkPlugins = - CHAT_MARKDOWN_REMARK_PLUGIN_SETS[ - componentState.mathEnabled - ? lineBreaks - ? "mathBreaks" - : "math" - : lineBreaks - ? "breaks" - : "plain" - ]; - // The incremental parser keeps per-instance state, so its output is not shared. - const uncachedPlugins = incrementalParsing; - const remarkPlugins = incrementalParsing - ? [...sharedRemarkPlugins, ...extraRemarkPlugins, createIncrementalMarkdownPlugin()] - : withExtraPlugins( - hasInsights - ? withExtraPlugins(INSIGHT_REMARK_PLUGINS, sharedRemarkPlugins) - : sharedRemarkPlugins, - extraRemarkPlugins, - ); + const markdown = wordsOptions(extensions, { + math: componentState.mathEnabled, + breaks: lineBreaks, + escapeHtml: !parseRawHtml, + insights: renderInsights && text.includes("★ Insight"), + }); const blocks = streamingBlocks ?? [text]; return ( @@ -1995,22 +2082,18 @@ function ChatMarkdown({ onCopy={handleCopy} > - {blocks.map((source, index) => ( - - ))} + + {blocks.map((source, index) => ( + + ))} + {localMediaPreview ? ( diff --git a/apps/web/src/components/chat/ChatMarkdownMedia.browser.test.tsx b/apps/web/src/components/chat/ChatMarkdownMedia.browser.test.tsx index db46999708043..04a4d9fd76f84 100644 --- a/apps/web/src/components/chat/ChatMarkdownMedia.browser.test.tsx +++ b/apps/web/src/components/chat/ChatMarkdownMedia.browser.test.tsx @@ -1,7 +1,6 @@ import type { PreparedConnection } from "@t3tools/client-runtime/connection"; import { EnvironmentId, ThreadId } from "@t3tools/contracts"; -import remarkParse from "remark-parse"; -import { unified } from "unified"; +import { markdownTree } from "~/markdown/wordsHast"; import { describe, expect, it, vi } from "vite-plus/test"; import { render } from "../../../test/render"; @@ -91,9 +90,13 @@ describe("markdownImageCopy", () => { it("copies an image whose path has a space as Markdown that is still that image", () => { // Raw HTML and sources reach the copy with the space unencoded. const copied = markdownImageCopy("Shot", "/work/my shot.png", undefined); - const [block] = unified().use(remarkParse).parse(copied).children; + const [block] = markdownTree(copied).children; const images = - block?.type === "paragraph" ? block.children.filter((node) => node.type === "image") : []; - expect(images.map((image) => decodeURI(image.url))).toEqual(["/work/my shot.png"]); + block?.type === "element" && block.tagName === "p" + ? block.children.filter((node) => node.type === "element" && node.tagName === "img") + : []; + expect( + images.map((image) => image.type === "element" && decodeURI(String(image.properties.src))), + ).toEqual(["/work/my shot.png"]); }); }); diff --git a/apps/web/src/components/chat/MarkdownCodeBlock.logic.ts b/apps/web/src/components/chat/MarkdownCodeBlock.logic.ts index fcee475c2886a..0a45cd6ac5659 100644 --- a/apps/web/src/components/chat/MarkdownCodeBlock.logic.ts +++ b/apps/web/src/components/chat/MarkdownCodeBlock.logic.ts @@ -1,5 +1,5 @@ import { Children, isValidElement, type ReactNode } from "react"; -import type { ExtraProps as ReactMarkdownExtraProps } from "react-markdown"; +import type { Element } from "hast"; import type { DiffThemeName } from "../../lib/diffRendering"; @@ -44,11 +44,7 @@ export function extractPreCodeMeta(node: unknown): string | undefined { return typeof meta === "string" && meta.trim().length > 0 ? meta.trim() : undefined; } -export function isClosedCodeFence( - node: ReactMarkdownExtraProps["node"], - text: string, - code: string, -): boolean { +export function isClosedCodeFence(node: Element | undefined, text: string, code: string): boolean { const start = node?.position?.start.offset; const end = node?.position?.end.offset; if (start === undefined || end === undefined) return false; @@ -98,7 +94,7 @@ export function extractCodeBlock( return null; } // With a custom `code` component the child's type is that component, not - // the "code" tag — the hast node react-markdown attaches still names it. + // the "code" tag — the hast node the renderer passes still names it. if (onlyChild.type !== "code" && onlyChild.props.node?.tagName !== "code") { return null; } diff --git a/apps/web/src/components/chat/MarkdownCodeBlock.tsx b/apps/web/src/components/chat/MarkdownCodeBlock.tsx index d6c8a7aaba2eb..726c34cbf029e 100644 --- a/apps/web/src/components/chat/MarkdownCodeBlock.tsx +++ b/apps/web/src/components/chat/MarkdownCodeBlock.tsx @@ -1,4 +1,4 @@ -import { T, useGT } from "gt-react"; +import { useGT } from "gt-react"; import { PlayIcon, WrapTextIcon, CheckIcon, CopyIcon } from "lucide-react"; import { toHtml } from "hast-util-to-html"; import React, { use, useEffect, useState, type ReactNode } from "react"; @@ -18,7 +18,7 @@ import { syntheticFileNameForLanguageId, } from "../../pierre-icons"; import { Button } from "../ui/button"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; import { HighlightedCodeLines } from "./HighlightedCodeLines"; import { createHighlightCacheKey, @@ -115,19 +115,17 @@ function MarkdownCodeBlockTitleContent({ return {language}; } return ( - - - } - > - - - {language} - + + } + > + + ); } @@ -187,22 +185,20 @@ export function MarkdownCodeBlock({ const handleCopy = () => copyToClipboard(code.endsWith("\n") ? code.slice(0, -1) : code); const copyButton = ( - - - } - > - {copied ? : } - - {copyLabel} - + + } + > + {copied ? : } + ); if (diagram) { @@ -231,43 +227,37 @@ export function MarkdownCodeBlock({ aria-label={gt("Code block actions")} > {canWrap ? ( - - setWrapOverride(!wrapped)} - aria-label={wrapLabel} - /> - } - > - - - {wrapLabel} - + setWrapOverride(!wrapped)} + aria-label={wrapLabel} + /> + } + > + + ) : null} {canRun ? ( - - onRunShellCommand(command)} - aria-label={gt("Run in terminal")} - /> - } - > - - - - Run in terminal - - + onRunShellCommand(command)} + aria-label={gt("Run in terminal")} + /> + } + > + + ) : null} {viewToggle} {copyButton} diff --git a/apps/web/src/components/chat/MarkdownDetails.tsx b/apps/web/src/components/chat/MarkdownDetails.tsx index 5ec510c3a4306..b6fa2b1d8d1f1 100644 --- a/apps/web/src/components/chat/MarkdownDetails.tsx +++ b/apps/web/src/components/chat/MarkdownDetails.tsx @@ -1,5 +1,6 @@ import { useGT } from "gt-react"; import { ChevronRightIcon } from "lucide-react"; +import { flushSync } from "react-dom"; import { Children, isValidElement, @@ -12,6 +13,11 @@ import { import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible"; import { findRevealRef, MarkdownFindContext } from "./markdownFindContext"; +const focusOnMount = (element: HTMLElement | null) => { + if (element && element.ownerDocument.activeElement === element.ownerDocument.body) + element.focus(); +}; + export function MarkdownDetails({ children, open = false, @@ -19,6 +25,7 @@ export function MarkdownDetails({ }: Pick, "children" | "open" | "dir">) { const gt = useGT(); const [isOpen, setIsOpen] = useState(open); + const [armed, setArmed] = useState<"hover" | "focus" | null>(null); const searching = use(MarkdownFindContext); const expanded = isOpen; const revealForFind = () => setIsOpen(true); @@ -36,6 +43,36 @@ export function MarkdownDetails({ : gt("Details", { $context: "fallback title of a collapsible section" }); const content = childNodes.filter((_, index) => index !== summaryIndex); + // Most details stay closed: mount Base UI on hover or focus, before the first click. + if (!armed && !expanded && !searching) { + return ( +
    +
    + +
    +
    + ); + } + return (
    - } - className={MARKDOWN_FILE_LINK_CLASS_NAME} - data-markdown-copy={copyMarkdown} - onClick={(event) => { - event.preventDefault(); - event.stopPropagation(); - if (onOpen && shouldOpenMarkdownFileLinkInEditor(event)) { - handleOpenInEditor(); - return; - } - if (useBrowserPrimaryAction) { - handleOpenInBrowser(); - return; - } - handleOpenInFilePreview(); - }} - onContextMenu={handleContextMenu} - > - - ) : undefined - } - path={iconPath} - environmentId={environmentId} - label={label} - theme={theme} - /> - - ) : ( - } - aria-label={gt("File options for {label}", { label })} - aria-haspopup="menu" - className={cn(MARKDOWN_FILE_LINK_CLASS_NAME, "select-text")} - data-markdown-copy={copyMarkdown} - onClick={handleContextMenu} - onContextMenu={handleContextMenu} - > - - ) : undefined - } - path={iconPath} - environmentId={environmentId} - label={label} - theme={theme} - /> - - ) + const tooltipContent = ( + + ); + const sharedTooltip = useSharedTooltip({ + render: () => tooltipContent, + contentKey: `${iconPath}\u0000${targetPath}`, + variant: "code", + }); + const chip = hasPrimaryAction ? ( + } + className={MARKDOWN_FILE_LINK_CLASS_NAME} + data-markdown-copy={copyMarkdown} + onClick={(event) => { + event.preventDefault(); + event.stopPropagation(); + if (onOpen && shouldOpenMarkdownFileLinkInEditor(event)) { + handleOpenInEditor(); + return; + } + if (useBrowserPrimaryAction) { + handleOpenInBrowser(); + return; } + handleOpenInFilePreview(); + }} + onContextMenu={handleContextMenu} + > + : undefined + } + path={iconPath} + environmentId={environmentId} + label={label} + theme={theme} + /> + + ) : ( + } + aria-label={gt("File options for {label}", { label })} + aria-haspopup="menu" + className={cn(MARKDOWN_FILE_LINK_CLASS_NAME, "select-text")} + data-markdown-copy={copyMarkdown} + onClick={handleContextMenu} + onContextMenu={handleContextMenu} + > + : undefined + } + path={iconPath} + environmentId={environmentId} + label={label} + theme={theme} /> + + ); + if (sharedTooltip) return withSharedTooltip(chip, sharedTooltip); + return ( + + - + {tooltipContent} ); diff --git a/apps/web/src/components/chat/MarkdownMath.browser.test.tsx b/apps/web/src/components/chat/MarkdownMath.browser.test.tsx deleted file mode 100644 index ec5b38541ddc4..0000000000000 --- a/apps/web/src/components/chat/MarkdownMath.browser.test.tsx +++ /dev/null @@ -1,36 +0,0 @@ -import { expect, it } from "vite-plus/test"; -import { userEvent } from "vite-plus/test/browser"; - -import { render } from "../../../test/render"; -import "../../index.css"; - -import { MarkdownMath } from "./MarkdownMath"; - -it("keeps keyboard scrolling available as a streamed equation outgrows its viewport", async () => { - const equation = (tex: string, width = 180) => ( -
    - - - -
    - ); - await using screen = await render(equation("x")); - await screen.getByRole("button", { name: "Before equation" }).click(); - await userEvent.keyboard("{Tab}"); - await expect.element(screen.getByRole("button", { name: "After equation" })).toHaveFocus(); - - await screen.rerender(equation("x_1 + x_2 + x_3 + x_4 + x_5 + x_6 + x_7 + x_8")); - const scroller = screen.getByLabelText("Scroll display equation"); - await expect.element(scroller).toHaveAttribute("tabindex", "0"); - await screen.getByRole("button", { name: "Before equation" }).click(); - await userEvent.keyboard("{Tab}"); - await expect.element(scroller).toHaveFocus(); - await userEvent.keyboard("{ArrowRight}"); - await expect.element(scroller).not.toHaveProperty("scrollLeft", 0); - - await screen.rerender(equation("x_1 + x_2 + x_3 + x_4 + x_5 + x_6 + x_7 + x_8", 1000)); - await expect.element(screen.getByLabelText("Scroll display equation")).not.toBeInTheDocument(); - await screen.getByRole("button", { name: "Before equation" }).click(); - await userEvent.keyboard("{Tab}"); - await expect.element(screen.getByRole("button", { name: "After equation" })).toHaveFocus(); -}); diff --git a/apps/web/src/components/chat/MarkdownMath.tsx b/apps/web/src/components/chat/MarkdownMath.tsx deleted file mode 100644 index 8070d64ac3c18..0000000000000 --- a/apps/web/src/components/chat/MarkdownMath.tsx +++ /dev/null @@ -1,81 +0,0 @@ -import { useGT } from "gt-react"; -import { lazy, memo, Suspense, useLayoutEffect, useRef, useState } from "react"; - -import { observeResize } from "../../lib/observeResize"; - -import { RenderErrorBoundary } from "../RenderErrorBoundary"; - -const MathTypeset = lazy(() => import("./MathTypeset")); - -/** - * One formula from `remark-math`. Shows its TeX until KaTeX loads, and - * keeps showing it when KaTeX cannot parse it, such as mid-stream. Copying - * any part of a formula copies its whole TeX source. - */ -export const MarkdownMath = memo(function MarkdownMath(props: { - tex: string; - display: boolean; - focusable?: boolean; -}) { - const gt = useGT(); - const viewportRef = useRef(null); - const contentRef = useRef(null); - const [overflows, setOverflows] = useState(false); - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- observes formula DOM width to make overflowing equations keyboard scrollable - useLayoutEffect(() => { - const viewport = viewportRef.current; - const content = contentRef.current; - if (!viewport || !content || props.focusable === false) return; - const measure = () => setOverflows(viewport.scrollWidth > viewport.clientWidth); - measure(); - // Typesetting and streamed TeX can change content width without resizing the viewport. - return observeResize([viewport, content], measure); - }, [props.focusable]); - const scrollable = props.focusable !== false && overflows; - const tex = props.tex.trim(); - const source = props.display ? `\\[\n${tex}\n\\]` : `\\(${tex}\\)`; - const fallback = {source}; - return ( - - - - - - - - - - - - ); -}); diff --git a/apps/web/src/components/chat/MathTypeset.logic.test.ts b/apps/web/src/components/chat/MathTypeset.logic.test.ts deleted file mode 100644 index 634f5146475ac..0000000000000 --- a/apps/web/src/components/chat/MathTypeset.logic.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -import katex from "katex"; -import { describe, expect, it } from "vite-plus/test"; - -import { escapeLiteralPercents } from "./MathTypeset.logic"; - -describe("escapeLiteralPercents", () => { - it.each([ - ["\\text{3.18% yield}", "\\text{3.18\\% yield}"], - ["\\text{100%% yield}", "\\text{100\\%\\% yield}"], - ["6\\% + 2\\%", "6\\% + 2\\%"], - ["x\\\\%", "x\\\\\\%"], - ["x % note\n+ 1", "x % note\n+ 1"], - ["% note\n\\text{2%}", "% note\n\\text{2\\%}"], - ["x &= 1 % +9%\n\\text{2%}", "x &= 1 % +9%\n\\text{2\\%}"], - ["\\verb|50%|+\\text{2%}", "\\verb|50%|+\\text{2\\%}"], - ["\\verb*%a%b%+c%", "\\verb*%a%b\\%+c\\%"], - ["\\verb|50%+\\text{2%}", "\\verb|50%+\\text{2%}"], - ])("repairs %j", (tex, expected) => { - expect(escapeLiteralPercents(tex)).toBe(expected); - }); - - it("lets the reported multiline equation typeset", () => { - const tex = - "R_e=\\underbrace{\\frac{1.0176}{32}}_{\\text{3.18% dividend yield}}\n+\\underbrace{6\\%}_{\\text{growth}}\n=\\boxed{9.18\\%}"; - expect(() => katex.renderToString(tex, { throwOnError: true })).toThrow(); - expect(() => - katex.renderToString(escapeLiteralPercents(tex), { throwOnError: true }), - ).not.toThrow(); - }); -}); diff --git a/apps/web/src/components/chat/MathTypeset.logic.ts b/apps/web/src/components/chat/MathTypeset.logic.ts deleted file mode 100644 index 04111ab4a70b4..0000000000000 --- a/apps/web/src/components/chat/MathTypeset.logic.ts +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Escapes each `%` written right after other text, as in `\text{3.18% yield}`. - * A `%` at a line start or after whitespace stays a comment. Skips escapes and - * `\verb` like KaTeX's lexer, in one linear pass. - */ -export function escapeLiteralPercents(tex: string): string { - let repaired = ""; - let copied = 0; - let index = 0; - while (index < tex.length) { - const char = tex[index]; - if (char === "\\") { - if (tex.startsWith("\\verb", index)) { - const starred = tex[index + 5] === "*"; - const delimiter = tex[index + (starred ? 6 : 5)]; - if (delimiter !== undefined && (starred || !/[*a-zA-Z]/.test(delimiter))) { - const bodyStart = index + (starred ? 7 : 6); - let close = bodyStart; - while (close < tex.length && ![delimiter, "\n", "\r"].includes(tex[close]!)) close++; - // KaTeX rejects a \verb that does not close on its own line. - if (tex[close] !== delimiter) return tex; - index = close + 1; - continue; - } - } - // A control symbol such as `\%` or `\\` is two characters. - index += 2; - } else if (char === "%" && index > 0 && !/\s/.test(tex[index - 1]!)) { - repaired += `${tex.slice(copied, index)}\\%`; - copied = ++index; - } else if (char === "%") { - const newline = tex.indexOf("\n", index); - index = newline === -1 ? tex.length : newline + 1; - } else { - index++; - } - } - return copied === 0 ? tex : repaired + tex.slice(copied); -} diff --git a/apps/web/src/components/chat/MathTypeset.tsx b/apps/web/src/components/chat/MathTypeset.tsx deleted file mode 100644 index 16d3dba409ee6..0000000000000 --- a/apps/web/src/components/chat/MathTypeset.tsx +++ /dev/null @@ -1,49 +0,0 @@ -import katex from "katex"; -import "katex/dist/katex.min.css"; -import type { ReactNode } from "react"; - -import { LRUCache } from "../../lib/lruCache"; -import { escapeLiteralPercents } from "./MathTypeset.logic"; - -// Virtualized threads remount messages while scrolling; cached markup keeps -// that from typesetting the same formulas again. "" records a parse error. -const typesetCache = new LRUCache(1000, 4 * 1024 * 1024); - -function typeset(tex: string, display: boolean): string { - const key = `${display ? "display" : "inline"}:${tex}`; - const cached = typesetCache.get(key); - if (cached !== null) return cached; - const options = { - displayMode: display, - output: "htmlAndMathml" as const, - throwOnError: true, - // No \href, \url, \htmlClass, or other commands that emit active HTML. - trust: false, - strict: "ignore" as const, - maxSize: 20, - maxExpand: 1000, - }; - let html = ""; - try { - html = katex.renderToString(tex, options); - } catch { - const repaired = escapeLiteralPercents(tex); - if (repaired !== tex) { - try { - html = katex.renderToString(repaired, options); - } catch { - // Unfinished or unsupported TeX stays readable as its source. - } - } - } - typesetCache.set(key, html, (key.length + html.length) * 2); - return html; -} - -/** KaTeX lives in this lazily loaded chunk, so it is only fetched once a formula renders. */ -export default function MathTypeset(props: { tex: string; display: boolean; fallback: ReactNode }) { - const html = typeset(props.tex, props.display); - if (!html) return props.fallback; - // KaTeX escapes the TeX it renders, and `trust: false` keeps it from emitting links or attributes. - return ; -} diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index 2e7721dddea18..d15a26ca43db0 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -44,11 +44,10 @@ import { type PendingApproval, deriveTimelineEntriesFromVisibleTurnItems, } from "../../session-logic"; -import type { Root } from "mdast"; import { ViewedImagesTimelineRow } from "./TimelineWorkEntryRow"; -import { remarkThoughtPreview, THOUGHT_PREVIEW_MAX_LENGTH } from "./TimelineWorkEntryRow.logic"; +import { THOUGHT_PREVIEW_MAX_LENGTH, thoughtPreviewMarkdown } from "./TimelineWorkEntryRow.logic"; +import { wordsHast } from "~/markdown/wordsHast"; import { TimelineRowCtx } from "./timelineRowContext"; -import { parseMarkdownWithMath } from "@t3tools/shared/markdownMath"; import { searchableMessageSegments } from "@t3tools/shared/threadFindText"; import { countThreadSearchOccurrences } from "@t3tools/shared/threadSearch"; import { collectThreadFindRanges } from "./threadFindHighlights"; @@ -2128,49 +2127,22 @@ describe("compact reasoning math", () => { ["hard \nbreak\\\nagain", [["text", "hard break again"]]], ["
    only html
    ", [["text", "Reasoning"]]], ])("keeps formulas while flattening compact reasoning previews: %j", (source, expected) => { - const tree = parseMarkdownWithMath(source); - remarkThoughtPreview("Reasoning")(tree); - expect(tree.children.map((node) => [node.type, "value" in node ? node.value : null])).toEqual( - expected, - ); - }); - - it("stops reading the tree once the preview is full", () => { - const beyondCap = (): string => { - throw new Error("read beyond cap"); - }; - const head = "x".repeat(THOUGHT_PREVIEW_MAX_LENGTH - 2); - const tree: Root = { - type: "root", - children: [ - { - type: "paragraph", - children: [ - { type: "text", value: head }, - { type: "strong", children: [{ type: "text", value: "yz beyond" }] }, - { - type: "inlineMath", - get value() { - return beyondCap(); - }, - }, - ], - }, - { - type: "paragraph", - children: [ - { - type: "text", - get value() { - return beyondCap(); - }, - }, - ], - }, - ], - }; - remarkThoughtPreview("Reasoning")(tree); - expect(tree.children).toEqual([{ type: "text", value: `${head}yz` }]); + const tree = wordsHast(source, { + math: true, + breaks: false, + escapeHtml: false, + insights: false, + extensions: thoughtPreviewMarkdown("Reasoning"), + }); + expect( + tree.children.map((node) => + node.type === "text" + ? ["text", node.value] + : node.type === "element" && node.children[0]?.type === "element" + ? ["inlineMath", String(node.children[0].properties.ariaLabel).trim()] + : [node.type, null], + ), + ).toEqual(expected); }); }); diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index 124062303e0cf..b00a48185b9db 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -14,7 +14,7 @@ import { IDLE_COMPACTION_TITLES, } from "@t3tools/client-runtime/user-message"; import type { HandoffTimelineRun } from "@t3tools/client-runtime/handoff"; -import { renderCodexDirectivesForCopy } from "@t3tools/shared/codexMarkdownDirectives"; +import { renderCodexDirectivesForCopy } from "~/markdown/markdownText"; import { commandDisplayText, commandProgramName, diff --git a/apps/web/src/components/chat/TimelineAssistantRows.tsx b/apps/web/src/components/chat/TimelineAssistantRows.tsx index 7ab6e361494ee..72fcf79013e87 100644 --- a/apps/web/src/components/chat/TimelineAssistantRows.tsx +++ b/apps/web/src/components/chat/TimelineAssistantRows.tsx @@ -1,4 +1,4 @@ -import { shouldPreserveAssistantLineBreaks } from "@t3tools/shared/markdownPipeline"; +import { shouldPreserveAssistantLineBreaks } from "@t3tools/shared/assistantInsights"; import { MessageId, type RunId, type TurnItemId } from "@t3tools/contracts"; import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows"; import { agentWorkingDirectories } from "@t3tools/client-runtime/workspace-basename-lookup"; diff --git a/apps/web/src/components/chat/TimelineUserMessageRow.tsx b/apps/web/src/components/chat/TimelineUserMessageRow.tsx index 88cdd61b58cc5..cd99aad44d080 100644 --- a/apps/web/src/components/chat/TimelineUserMessageRow.tsx +++ b/apps/web/src/components/chat/TimelineUserMessageRow.tsx @@ -1,10 +1,7 @@ import { copySnapshot as copySnapshotToClipboard } from "./copySnapshot"; import { InlineAudioPreview } from "../files/InlineAudioPreview"; import { filePreviewKind } from "@t3tools/shared/filePreview"; -import { - CHAT_USER_MARKDOWN_REMARK_PLUGINS, - remarkEnableOrderedListNumbers, -} from "@t3tools/shared/markdownPipeline"; +import type { MarkdownExtensions } from "~/markdown/wordsHast"; import { T, useGT, useMessages, Var } from "gt-react"; import { findRevealRef } from "./markdownFindContext"; import { @@ -1284,10 +1281,7 @@ const CollapsibleUserMessageBody = memo(function CollapsibleUserMessageBody(prop ); }); -const USER_MESSAGE_REMARK_PLUGINS = [ - ...CHAT_USER_MARKDOWN_REMARK_PLUGINS, - remarkEnableOrderedListNumbers, -]; +const USER_MESSAGE_MARKDOWN: MarkdownExtensions = { userMessage: true, leadingWhitespace: true }; const UserMessageBody = memo(function UserMessageBody(props: { text: string; @@ -1308,7 +1302,7 @@ const UserMessageBody = memo(function UserMessageBody(props: { className="text-message-foreground user-message-markdown" lineBreaks parseRawHtml={false} - extraRemarkPlugins={USER_MESSAGE_REMARK_PLUGINS} + extensions={USER_MESSAGE_MARKDOWN} renderContextReference={props.renderContextReference} headingLevelOffset={MESSAGE_HEADING_LEVEL} /> diff --git a/apps/web/src/components/chat/TimelineWorkEntryRow.logic.ts b/apps/web/src/components/chat/TimelineWorkEntryRow.logic.ts index dc279ea8cb164..894f58f45edb4 100644 --- a/apps/web/src/components/chat/TimelineWorkEntryRow.logic.ts +++ b/apps/web/src/components/chat/TimelineWorkEntryRow.logic.ts @@ -1,6 +1,5 @@ import { msg } from "gt-react"; -import type { PluggableList } from "unified"; -import type { Root, RootContent } from "mdast"; +import type { MarkdownExtensions } from "~/markdown/wordsHast"; import { resolveWorkEntryToolPresentation, toolGroupAction, @@ -209,67 +208,14 @@ export function workEntryIconName(workEntry: TimelineWorkEntry): WorkEntryIconNa export const THOUGHT_PREVIEW_SOURCE_MAX_LENGTH = 8_192; export const THOUGHT_PREVIEW_MAX_LENGTH = 2_048; -/** Compact reasoning keeps formulas while flattening other Markdown into label text. */ -export function remarkThoughtPreview(fallback: string) { - return (tree: Root) => { - const children: RootContent[] = []; - let remaining = THOUGHT_PREVIEW_MAX_LENGTH; - let fragments: string[] = []; - const flush = () => { - if (fragments.length === 0) return; - children.push({ type: "text", value: fragments.join("").replace(/\s+/g, " ") }); - fragments = []; - }; - const take = (value: string) => { - const text = value.slice(0, remaining); - remaining = text.length < value.length ? 0 : remaining - text.length; - // A cut here or at the source limit must not leave half a surrogate pair. - return text.replace(/[\uD800-\uDBFF]$/, ""); - }; - const append = (value: string) => { - fragments.push(take(value)); - }; - const visit = (node: Root | RootContent) => { - if (remaining === 0 || node.type === "html" || node.type === "definition") return; - if (node.type === "math" || node.type === "inlineMath") { - flush(); - const value = take(node.value); - children.push({ - type: "inlineMath", - value, - position: node.position, - data: { - hName: "code", - hProperties: { className: ["language-math", "math-inline"] }, - hChildren: [{ type: "text", value }], - }, - }); - } else if ("alt" in node) append(node.alt ?? ""); - else if ("value" in node) append(node.value); - else if ("children" in node) { - for (const [index, child] of node.children.entries()) { - if (remaining === 0) break; - if ( - index && - ["root", "blockquote", "list", "listItem", "table", "tableRow"].includes(node.type) - ) - append(" "); - visit(child); - } - } else if (node.type === "break") append(" "); - }; - visit(tree); - flush(); - const first = children[0]; - const last = children.at(-1); - if (first?.type === "text") first.value = first.value.trimStart(); - if (last?.type === "text") last.value = last.value.trimEnd(); - tree.children = children.some((child) => child.type !== "text" || child.value) - ? children - : [{ type: "text", value: fallback }]; - }; -} +const thoughtPreviews = new Map(); -export function thoughtPreviewPlugins(fallback: string): PluggableList { - return [[remarkThoughtPreview, fallback]]; +/** Compact reasoning keeps formulas while flattening other Markdown into label text. */ +export function thoughtPreviewMarkdown(fallback: string): MarkdownExtensions { + let extensions = thoughtPreviews.get(fallback); + if (!extensions) { + extensions = { preview: { fallback, maxLength: THOUGHT_PREVIEW_MAX_LENGTH } }; + thoughtPreviews.set(fallback, extensions); + } + return extensions; } diff --git a/apps/web/src/components/chat/TimelineWorkEntryRow.tsx b/apps/web/src/components/chat/TimelineWorkEntryRow.tsx index 8e7f03618e59d..4cd6fc0e8dee6 100644 --- a/apps/web/src/components/chat/TimelineWorkEntryRow.tsx +++ b/apps/web/src/components/chat/TimelineWorkEntryRow.tsx @@ -73,7 +73,7 @@ import { workEntryRawCommand, buildToolCallExpandedBody, workEntryIconName, - thoughtPreviewPlugins, + thoughtPreviewMarkdown, THOUGHT_PREVIEW_SOURCE_MAX_LENGTH, } from "./TimelineWorkEntryRow.logic"; @@ -590,10 +590,10 @@ function WorkEntryLogRow(props: WorkEntryRowProps) { )} cwd={ctx.markdownCwd} parseRawHtml={false} - extraRemarkPlugins={ + extensions={ workEntry.toolLifecycleStatus === "inProgress" - ? thoughtPreviewPlugins(gt("Thinking")) - : thoughtPreviewPlugins(gt("Thought")) + ? thoughtPreviewMarkdown(gt("Thinking")) + : thoughtPreviewMarkdown(gt("Thought")) } /> ) : threadLabel ? ( diff --git a/apps/web/src/components/chat/TimelineWorkGroupRows.tsx b/apps/web/src/components/chat/TimelineWorkGroupRows.tsx index 745a7aff68fdf..c67c76bf4cca3 100644 --- a/apps/web/src/components/chat/TimelineWorkGroupRows.tsx +++ b/apps/web/src/components/chat/TimelineWorkGroupRows.tsx @@ -56,7 +56,7 @@ import { SimpleWorkEntryRow, } from "./TimelineWorkEntryRow"; import { - thoughtPreviewPlugins, + thoughtPreviewMarkdown, THOUGHT_PREVIEW_SOURCE_MAX_LENGTH, toolGroupSummaryIconName, workEntryIconName, @@ -640,7 +640,7 @@ export function LiveWorkEntryTimelineRow({ text={thoughtLine} cwd={ctx.markdownCwd} parseRawHtml={false} - extraRemarkPlugins={thoughtPreviewPlugins(gt("Thought"))} + extensions={thoughtPreviewMarkdown(gt("Thought"))} />
    } @@ -661,10 +661,10 @@ export function LiveWorkEntryTimelineRow({ text={(row.entry.detail ?? label).slice(0, THOUGHT_PREVIEW_SOURCE_MAX_LENGTH)} cwd={ctx.markdownCwd} parseRawHtml={false} - extraRemarkPlugins={ + extensions={ row.active - ? thoughtPreviewPlugins(gt("Thinking")) - : thoughtPreviewPlugins(gt("Thought")) + ? thoughtPreviewMarkdown(gt("Thinking")) + : thoughtPreviewMarkdown(gt("Thought")) } /> ) : threadLabel ? ( diff --git a/apps/web/src/components/chat/markdownIslands.test.ts b/apps/web/src/components/chat/markdownIslands.test.ts new file mode 100644 index 0000000000000..f328c9ea51251 --- /dev/null +++ b/apps/web/src/components/chat/markdownIslands.test.ts @@ -0,0 +1,50 @@ +import type { Root } from "hast"; +import { renderToStaticMarkup } from "react-dom/server"; +import { createElement, Fragment } from "react"; +import { describe, expect, it } from "vite-plus/test"; + +import { renderHastWithIslands } from "./markdownIslands"; + +describe("renderHastWithIslands", () => { + it("writes SVG attributes by their SVG names in static HTML", () => { + const tree: Root = { + type: "root", + children: [ + { + type: "element", + tagName: "p", + properties: {}, + children: [ + { + type: "element", + tagName: "svg", + properties: { viewBox: "0 0 1 1" }, + children: [ + { + type: "element", + tagName: "text", + properties: { fontSize: "700", strokeWidth: "2" }, + children: [{ type: "text", value: "x" }], + }, + ], + }, + ], + }, + ], + }; + const html = renderToStaticMarkup( + createElement( + Fragment, + null, + renderHastWithIslands(tree, { + components: {}, + variant: "", + isIsland: () => false, + staticElement: (node) => node, + }), + ), + ); + expect(html).toContain('x'); + expect(html).toContain('viewBox="0 0 1 1"'); + }); +}); diff --git a/apps/web/src/components/chat/markdownIslands.ts b/apps/web/src/components/chat/markdownIslands.ts new file mode 100644 index 0000000000000..8c434daf099ce --- /dev/null +++ b/apps/web/src/components/chat/markdownIslands.ts @@ -0,0 +1,214 @@ +import type { Element, ElementContent, Properties, Root, RootContent } from "hast"; +import { find, html as htmlSchema, svg as svgSchema } from "property-information"; +import { toJsxRuntime, type Components } from "hast-util-to-jsx-runtime"; +import { createElement, Fragment as ReactFragment, type ReactNode } from "react"; +import { Fragment, jsx, jsxs } from "react/jsx-runtime"; + +export interface MarkdownIslandOptions { + readonly components: Partial; + /** Elements that need their React component; everything else renders as static HTML. */ + readonly isIsland: (node: Element) => boolean; + /** What a static element's component would have added, or the node itself when nothing. */ + readonly staticElement: (node: Element) => Element; + /** Separates static HTML that `staticElement` renders differently, such as a heading offset. */ + readonly variant: string; +} + +const VOID_ELEMENTS = new Set( + "area base br col embed hr img input link meta source track wbr".split(" "), +); + +const jsxOptions = (components: Partial) => + ({ + Fragment, + components, + ignoreInvalidStyle: true, + jsx, + jsxs, + passKeys: true, + passNode: true, + }) as const; + +// Static HTML depends only on the cached, immutable tree and the variant. +const innerHtmlCache = new WeakMap(); + +function transformStatic( + node: ElementContent, + staticElement: MarkdownIslandOptions["staticElement"], +): ElementContent { + if (node.type !== "element") return node; + const element = staticElement(node); + let children: ElementContent[] | undefined; + for (let index = 0; index < element.children.length; index++) { + const child = element.children[index]!; + const next = transformStatic(child, staticElement); + if (next !== child) { + children ??= element.children.slice(); + children[index] = next; + } + } + return children ? { ...element, children } : element; +} + +function innerHtml(node: Element, options: MarkdownIslandOptions): string { + const cached = innerHtmlCache.get(node); + if (cached?.variant === options.variant) return cached.html; + let html = ""; + for (const child of node.children) { + html += serialize(transformStatic(child, options.staticElement)); + } + innerHtmlCache.set(node, { variant: options.variant, html }); + return html; +} + +interface AttributeInfo { + readonly name: string; + readonly boolean: boolean; + readonly separator: string; +} + +const attributeInfo = new Map(); + +// SVG names its attributes differently (`fontSize` is `font-size`), so its lookups key apart. +function infoFor(property: string, inSvg: boolean): AttributeInfo { + const key = inSvg ? `svg:${property}` : property; + let info = attributeInfo.get(key); + if (!info) { + const found = find(inSvg ? svgSchema : htmlSchema, property); + info = { + name: found.attribute, + boolean: found.boolean || found.overloadedBoolean, + separator: found.commaSeparated ? ", " : " ", + }; + attributeInfo.set(key, info); + } + return info; +} + +const escapeText = (value: string) => + value.includes("&") || value.includes("<") || value.includes(">") + ? value.replace(/&/g, "&").replace(//g, ">") + : value; +const escapeAttribute = (value: string) => + value.includes("&") || value.includes('"') + ? value.replace(/&/g, "&").replace(/"/g, """) + : value; + +/** HTML for the elements and text this pipeline builds; the DOM matches hast-util-to-html's. */ +function serialize(node: ElementContent, inSvg = false): string { + if (node.type === "text") return escapeText(node.value); + if (node.type !== "element") return ""; + const svg = inSvg || node.tagName === "svg"; + let html = `<${node.tagName}`; + const { properties } = node; + for (const key in properties) { + const value = properties[key]; + if (value === null || value === undefined || value === false || Number.isNaN(value)) continue; + const info = infoFor(key, svg); + if (info.boolean && value) { + html += ` ${info.name}`; + continue; + } + const text = Array.isArray(value) + ? value.join(info.separator) + : value === true + ? "" + : String(value); + html += ` ${info.name}="${escapeAttribute(text)}"`; + } + html += ">"; + if (VOID_ELEMENTS.has(node.tagName)) return html; + for (const child of node.children) html += serialize(child, svg); + return `${html}`; +} + +/** React props for an element, converted as hast-util-to-jsx-runtime converts them. */ +function shallowProps(node: Element, components: Partial): Record { + const element = toJsxRuntime( + { ...node, children: [] }, + { ...jsxOptions(components), components: {}, passNode: false }, + ) as { props: Record }; + const { children: _children, ...props } = element.props; + return props; +} + +interface Plan { + readonly islands: Set; + /** Elements with an island somewhere below them. */ + readonly ancestors: Set; +} + +function renderContent( + node: RootContent, + key: number, + options: MarkdownIslandOptions, + plan: Plan, +): ReactNode { + if (node.type === "text") return node.value; + if (node.type !== "element") return null; + if (plan.islands.has(node)) { + return createElement( + ReactFragment, + { key }, + toJsxRuntime(node, jsxOptions(options.components)), + ); + } + const element = options.staticElement(node); + const props: Record = { ...shallowProps(element, options.components), key }; + if (plan.ancestors.has(node)) { + return createElement( + element.tagName, + props, + ...element.children.map((child, index) => renderContent(child, index, options, plan)), + ); + } + if (element.children.length > 0 && !VOID_ELEMENTS.has(element.tagName)) { + props.dangerouslySetInnerHTML = { __html: innerHtml(node, options) }; + } + return createElement(element.tagName, props); +} + +/** + * Renders a hast tree with React only on the path to elements that need a component: subtrees + * without one become static HTML, which the browser builds without React reconciling each node. + */ +export function renderHastWithIslands(tree: Root, options: MarkdownIslandOptions): ReactNode { + // The same elements again let React skip the block; islands still follow their context. + let signature = options.variant; + const plan: Plan = { islands: new Set(), ancestors: new Set() }; + const visit = (node: Root | Element): boolean => { + let below = false; + for (const child of node.children) { + if (child.type !== "element") continue; + const island = options.isIsland(child); + signature += island ? "1" : "0"; + if (island) { + plan.islands.add(child); + below = true; + continue; + } + if (visit(child)) { + plan.ancestors.add(child); + below = true; + } + } + return below; + }; + visit(tree); + const cached = renderedTrees.get(tree); + if (cached?.signature === signature && cached.components === options.components) { + return cached.node; + } + const node = tree.children.map((child, index) => renderContent(child, index, options, plan)); + renderedTrees.set(tree, { signature, components: options.components, node }); + return node; +} + +const renderedTrees = new WeakMap< + Root, + { signature: string; components: Partial; node: ReactNode } +>(); + +export function withProperties(node: Element, properties: Properties): Element { + return { ...node, properties: { ...node.properties, ...properties } }; +} diff --git a/apps/web/src/components/chat/markdownRenderer.test.tsx b/apps/web/src/components/chat/markdownRenderer.test.tsx index f15fe49584aea..a9a60c545b37b 100644 --- a/apps/web/src/components/chat/markdownRenderer.test.tsx +++ b/apps/web/src/components/chat/markdownRenderer.test.tsx @@ -1,88 +1,41 @@ -import { - CHAT_MARKDOWN_REHYPE_PLUGINS, - CHAT_MARKDOWN_REMARK_PLUGINS, -} from "@t3tools/shared/markdownPipeline"; import { renderToStaticMarkup } from "react-dom/server"; -import ReactMarkdown from "react-markdown"; import { describe, expect, it } from "vite-plus/test"; -import { createIncrementalMarkdownPlugin } from "../../markdown-incremental"; import { createMarkdownRenderer } from "./markdownRenderer"; // Visible in the markup, so every URL attribute must pass through it. const urlTransform = (url: string) => `${url}#seen`; describe("createMarkdownRenderer", () => { - const render = createMarkdownRenderer({ - remarkPlugins: CHAT_MARKDOWN_REMARK_PLUGINS, - rehypePlugins: CHAT_MARKDOWN_REHYPE_PLUGINS, + const renderer = createMarkdownRenderer({ + markdown: { math: false, breaks: false, escapeHtml: false, insights: false, extensions: {} }, components: {}, urlTransform, }); + const render = (text: string) => renderer.element(renderer.parse(text)); + const renderAndRemember = (text: string) => { + const entry = renderer.parse(text); + renderer.remember(text, entry); + return renderer.element(entry); + }; - it.each([ - '# Title\n\nText with `code`, **bold**, [a link](https://example.com "t") and https://bare.example.com.', - "![shot](./shot.png) and [file](file:///C:/repo/a.ts) and [bad](javascript:alert(1))", - "
    More\n\nHidden bold \n\n
    ", - "| a | b |\n| - | - |\n|
    | [x](#frag) |\n\n- [ ] task\n- [x] done", - '```ts title="a.ts"\nconst a = 1;\n```\n\n> [!WARNING]\n> careful
    bare', - "Footnote[^1] and ~~strike~~\n\n[^1]: the note", - // Each GFM construct the parser skips when its text cannot match, next to one that can. - "Mail me@example.com, see www.example.com and HTTPS://example.com/a, not [x](https://y.z).", - "a.b-c_d+e@x.io and @user\n\n`me@x.io` ", - "A table without pipes\n:--", - "> | quoted |\n> | - |\n> | body |\n\n- [ ] open\n- [X] done", - "Escaped www\\.example.com and me@example.com", - "\ufeffA byte order mark\n\n| a |\n| - |\n| b |", - "> - | a |\r\n> | - |\r\n> | me@x.io |\r\n\n-\t[ ] tab\n\n ~~lazy~~", - ])("renders what react-markdown renders: %j", (source) => { - const expected = renderToStaticMarkup( - - {source} - , + it("passes every URL attribute through the transform", () => { + const html = renderToStaticMarkup( + render('![shot](./shot.png) and [a link](https://example.com "t") and '), ); - const element = render(source); - expect(renderToStaticMarkup(element)).toBe(expected); - render.remember(source, element); - expect(render(source)).toBe(element); + expect(html).toContain('src="./shot.png#seen"'); + expect(html).toContain('href="https://example.com#seen"'); + expect(html).toContain('src="b.png#seen"'); }); - it("renders what react-markdown renders while a reply streams through the incremental parser", () => { - const reply = - "```ts\nconst a = 1;\n```\n\n| a | b |\n| - | - |\n| me@x.io | www.x.io |\n\nDone ~~now~~."; - // As ChatMarkdown streams: one incremental plugin for the reply, a fresh renderer per update. - const incremental = createIncrementalMarkdownPlugin(); - for (let end = 1; end <= reply.length; end++) { - const source = reply.slice(0, end); - const streamed = createMarkdownRenderer({ - remarkPlugins: [...CHAT_MARKDOWN_REMARK_PLUGINS, incremental], - rehypePlugins: CHAT_MARKDOWN_REHYPE_PLUGINS, - components: {}, - urlTransform, - })(source); - expect(renderToStaticMarkup(streamed)).toBe( - renderToStaticMarkup( - - {source} - , - ), - ); - } + it("reuses a remembered message's element", () => { + const element = renderAndRemember("# Title\n\nText with `code` and **bold**."); + expect(render("# Title\n\nText with `code` and **bold**.")).toBe(element); }); it("keeps cached messages when one far larger than the cache is rendered", () => { - const element = render("Kept *message*"); - render.remember("Kept *message*", element); - const large = "x".repeat(600_000); - render.remember(large, render(large)); + const element = renderAndRemember("Kept *message*"); + renderAndRemember("x".repeat(600_000)); expect(render("Kept *message*")).toBe(element); }); }); diff --git a/apps/web/src/components/chat/markdownRenderer.ts b/apps/web/src/components/chat/markdownRenderer.ts index 9637d68e8f158..c2aa499a9583d 100644 --- a/apps/web/src/components/chat/markdownRenderer.ts +++ b/apps/web/src/components/chat/markdownRenderer.ts @@ -3,18 +3,13 @@ import { toJsxRuntime, type Components } from "hast-util-to-jsx-runtime"; import { urlAttributes } from "html-url-attributes"; import type { ReactElement } from "react"; import { Fragment, jsx, jsxs } from "react/jsx-runtime"; -import remarkParse from "remark-parse"; -import remarkRehype from "remark-rehype"; -import { type PluggableList, unified } from "unified"; -import { VFile } from "vfile"; -import { remarkParseWithoutUnusedSyntax } from "./markdownSyntaxGates"; +import { wordsHast, type WordsHastOptions } from "../../markdown/wordsHast"; export type MarkdownUrlTransform = (url: string, key: string, node: Element) => string; interface MarkdownRendererOptions { - readonly remarkPlugins: PluggableList; - readonly rehypePlugins: PluggableList; + readonly markdown: WordsHastOptions; readonly components: Partial; readonly urlTransform: MarkdownUrlTransform; } @@ -23,7 +18,11 @@ interface MarkdownRendererOptions { // reuses one instead of parsing again. Parsing is most of the cost of rendering markdown. // An element and the hast it keeps hold about 20 bytes per source character, so ~10 MB. const MAX_CACHED_CHARS = 500_000; -const rendered = new Map(); +interface Rendered { + readonly tree: Root; + element?: ReactElement; +} +const rendered = new Map(); let cachedChars = 0; let nextRendererId = 0; @@ -31,10 +30,10 @@ let nextRendererId = 0; const ENTRY_OVERHEAD_CHARS = 200; const entrySize = (key: string) => key.length + ENTRY_OVERHEAD_CHARS; -function remember(key: string, element: ReactElement) { +function remember(key: string, entry: Rendered) { // One huge message would otherwise evict everything else. if (entrySize(key) > MAX_CACHED_CHARS / 4) return; - rendered.set(key, element); + rendered.set(key, entry); cachedChars += entrySize(key); for (const oldest of rendered.keys()) { if (cachedChars <= MAX_CACHED_CHARS) break; @@ -43,32 +42,18 @@ function remember(key: string, element: ReactElement) { } } -/** Renders markdown as react-markdown does, with one processor per plugin set. */ +/** Renders markdown with Words, keeping one parse cache per option set. */ export function createMarkdownRenderer({ - remarkPlugins, - rehypePlugins, + markdown, components, urlTransform, }: MarkdownRendererOptions) { - const processor = unified() - .use(remarkParse) - .use(remarkParseWithoutUnusedSyntax) - .use(remarkPlugins) - .use(remarkRehype, { allowDangerousHtml: true }) - .use(rehypePlugins) - .freeze(); const keyPrefix = `${nextRendererId++}\u0000`; - // Literal raw HTML that survived the rehype plugins, and URL attributes, as react-markdown treats them. + // URL attributes, as react-markdown transformed them. const prepare = (node: Nodes) => { if (!("children" in node)) return; - const { children } = node; - for (let index = 0; index < children.length; index++) { - const child = children[index]!; - if (child.type === "raw") { - children[index] = { type: "text", value: child.value }; - continue; - } + for (const child of node.children) { if (child.type !== "element") continue; const { properties } = child; for (const key in properties) { @@ -82,7 +67,7 @@ export function createMarkdownRenderer({ } }; - const render = (text: string): ReactElement => { + const parse = (text: string): Rendered => { const key = keyPrefix + text; const cached = rendered.get(key); if (cached !== undefined) { @@ -91,24 +76,27 @@ export function createMarkdownRenderer({ rendered.set(key, cached); return cached; } - const file = new VFile(text); - const tree = processor.runSync(processor.parse(file), file) as Root; + const tree = wordsHast(text, markdown); prepare(tree); - return toJsxRuntime(tree, { - Fragment, - components, - ignoreInvalidStyle: true, - jsx, - jsxs, - passKeys: true, - passNode: true, - }); + return { tree }; }; - return Object.assign(render, { - remember(text: string, element: ReactElement) { + return { + /** A cached entry, or a fresh one that `remember` can keep. Cached trees are shared, so callers must not change them. */ + parse, + element: (entry: Rendered): ReactElement => + (entry.element ??= toJsxRuntime(entry.tree, { + Fragment, + components, + ignoreInvalidStyle: true, + jsx, + jsxs, + passKeys: true, + passNode: true, + })), + remember(text: string, entry: Rendered) { const key = keyPrefix + text; - if (!rendered.has(key)) remember(key, element); + if (!rendered.has(key)) remember(key, entry); }, - }); + }; } diff --git a/apps/web/src/components/chat/markdownStreamBlocks.test.tsx b/apps/web/src/components/chat/markdownStreamBlocks.test.ts similarity index 81% rename from apps/web/src/components/chat/markdownStreamBlocks.test.tsx rename to apps/web/src/components/chat/markdownStreamBlocks.test.ts index 38ecff7666508..b89940489ec32 100644 --- a/apps/web/src/components/chat/markdownStreamBlocks.test.tsx +++ b/apps/web/src/components/chat/markdownStreamBlocks.test.ts @@ -1,32 +1,19 @@ -import { - CHAT_MARKDOWN_REHYPE_PLUGINS, - CHAT_MARKDOWN_REMARK_PLUGINS, - remarkAssistantInsights, -} from "@t3tools/shared/markdownPipeline"; -import { renderToStaticMarkup } from "react-dom/server"; -import ReactMarkdown from "react-markdown"; -import remarkMath from "remark-math"; -import type { PluggableList } from "unified"; +import { toHtml } from "hast-util-to-html"; import { describe, expect, it } from "vite-plus/test"; +import { wordsHast } from "~/markdown/wordsHast"; import { splitMarkdownBlocks } from "./markdownStreamBlocks"; -import { rehypeHeadingIds } from "./markdownFragments"; - -const MATH_PLUGINS: PluggableList = [[remarkMath, { singleDollarTextMath: true }]]; // Whitespace between top-level blocks collapses in the rendered message. const renderMarkdown = (source: string, math = false) => - renderToStaticMarkup( - - {source} - , + toHtml( + wordsHast(source, { + math, + breaks: false, + escapeHtml: false, + insights: source.includes("★ Insight"), + extensions: {}, + }), ) .replace(/>\s+<") .trim(); diff --git a/apps/web/src/components/chat/markdownSyntaxGates.ts b/apps/web/src/components/chat/markdownSyntaxGates.ts deleted file mode 100644 index 57587a51b9d13..0000000000000 --- a/apps/web/src/components/chat/markdownSyntaxGates.ts +++ /dev/null @@ -1,204 +0,0 @@ -import type { Nodes as MdastNodes } from "mdast"; -import { - type Extension as MdastExtension, - fromMarkdown, - type Options as FromMarkdownOptions, - type Transform, -} from "mdast-util-from-markdown"; -import { combineExtensions } from "micromark-util-combine-extensions"; -import type { Construct, Extension, TokenizeContext } from "micromark-util-types"; -import type { Processor } from "unified"; - -// A table needs a delimiter row: dashes with a `|` or `:`, after any `>` or indent. -// One character class per pattern: overlapping ones backtrack quadratically on a run of dashes. -const DELIMITER_LINE = /^[ \t>|:-]+$/gm; -const isDelimiterRow = (line: string) => line.includes("-") && /[|:]/.test(line); -const NEXT_LINE = /[^\r\n]*(?:\r\n?|\n)([^\r\n]*)/y; - -function hasDelimiterRow(text: string) { - for (const [line] of text.matchAll(DELIMITER_LINE)) if (isDelimiterRow(line)) return true; - return false; -} -const PROTOCOL = /https?:\/\//iy; -const WWW = /www\./iy; -const EMAIL_ATEXT = /[\w+.-]*@/y; - -const matchesAt = (pattern: RegExp, text: string, offset: number) => { - pattern.lastIndex = offset; - return pattern.test(text); -}; - -interface Gate { - readonly names: ReadonlyArray; - /** False when the construct cannot match anywhere in the text. */ - readonly inText: (text: string) => boolean; - /** False when it cannot start at this offset, which keeps micromark from trying it there. */ - readonly at?: (context: TokenizeContext, text: string, offset: number) => boolean; -} - -// micromark tries these at every candidate character: email autolinks at every word, tables -// at every line. That is most of what GFM adds to a parse, and most texts cannot match them. -const GATES: ReadonlyArray = [ - { - names: ["emailAutolink"], - inText: (text) => text.includes("@"), - at: (_, text, offset) => matchesAt(EMAIL_ATEXT, text, offset), - }, - { - names: ["protocolAutolink"], - inText: (text) => /https?:\/\//i.test(text), - at: (_, text, offset) => matchesAt(PROTOCOL, text, offset), - }, - { - names: ["wwwAutolink"], - inText: (text) => /www\./i.test(text), - at: (_, text, offset) => matchesAt(WWW, text, offset), - }, - { - names: ["table"], - inText: hasDelimiterRow, - at: (context, text, offset) => { - NEXT_LINE.lastIndex = offset; - const nextLine = NEXT_LINE.exec(text)?.[1]; - return (nextLine !== undefined && hasDelimiterRow(nextLine)) || continuesTable(context); - }, - }, - { names: ["strikethrough"], inText: (text) => text.includes("~") }, - { - names: ["gfmFootnoteCall", "gfmPotentialFootnoteCall", "gfmFootnoteDefinition"], - inText: (text) => text.includes("[^"), - }, - { names: ["tasklistCheck"], inText: (text) => /\[[\sxX]\]/.test(text) }, -]; - -// A body row follows the head or another row. Mirrors `start` in micromark-extension-gfm-table's -// lib/syntax.js: recheck it when that package changes. -function continuesTable({ events }: TokenizeContext) { - let index = events.length - 1; - while (index > -1 && /^(?:lineEnding|linePrefix)$/.test(events[index]![1].type)) index--; - // The table extension's token types are not in micromark's map unless its types are loaded. - const tail: string | undefined = events[index]?.[1].type; - return tail === "tableHead" || tail === "tableRow"; -} - -let parsing = ""; -const gated = new WeakMap(); - -function gatedConstruct(construct: Construct, gate: Gate): Construct { - const at = gate.at; - if (!at) return construct; - let wrapped = gated.get(construct); - if (!wrapped) { - const { previous, tokenize } = construct; - wrapped = { - ...construct, - tokenize(effects, ok, nok) { - return at(this, parsing, this.now().offset) ? tokenize.call(this, effects, ok, nok) : nok; - }, - ...(previous && { - previous(code) { - return previous.call(this, code) && at(this, parsing, this.now().offset); - }, - }), - }; - gated.set(construct, wrapped); - } - return wrapped; -} - -type ConstructMap = Record; - -function gateExtension(extension: Extension, absent: ReadonlySet): Extension { - const gateOf = (name: string | undefined) => - GATES.find((gate) => name && gate.names.includes(name)); - const result: Record = {}; - for (const [field, value] of Object.entries(extension)) { - if (field === "disable" || field === "attentionMarkers" || !value) { - result[field] = value; - continue; - } - const map: ConstructMap = {}; - for (const [code, entry] of Object.entries(value as ConstructMap)) { - const kept = (Array.isArray(entry) ? entry : [entry]).flatMap((construct) => { - const gate = construct && gateOf(construct.name); - if (!construct || !gate) return construct ? [construct] : []; - return absent.has(gate) ? [] : [gatedConstruct(construct, gate)]; - }); - if (kept.length > 0) map[code] = Array.isArray(entry) ? kept : kept[0]; - } - result[field] = map; - } - return result as Extension; -} - -type MdastExtensions = NonNullable; - -// Merged once, as mdast-util-from-markdown merges them on every call: lists in order, handlers by key. -function mergeMdastExtensions(extensions: MdastExtensions): MdastExtension { - const merged = { - canContainEols: [] as string[], - enter: {}, - exit: {}, - transforms: [] as Transform[], - }; - for (const extension of extensions.flat()) { - merged.canContainEols.push(...(extension.canContainEols ?? [])); - Object.assign(merged.enter, extension.enter); - Object.assign(merged.exit, extension.exit); - // GFM looks for autolink literals again in the decoded text outside links, so `www\.x.io` - // links too. Most texts have URLs only in link destinations and code, where it finds nothing. - for (const transform of extension.transforms ?? []) { - merged.transforms.push( - extension.enter?.literalAutolink - ? (tree) => (hasAutolinkText(tree) ? transform(tree) : undefined) - : transform, - ); - } - } - return merged; -} - -const AUTOLINK_TEXT = /@|https?:\/\/|www\./i; - -function hasAutolinkText(node: MdastNodes): boolean { - if (node.type === "text") return AUTOLINK_TEXT.test(node.value); - if (node.type === "link" || node.type === "linkReference" || !("children" in node)) return false; - return node.children.some(hasAutolinkText); -} - -/** - * Parses as remark-parse does, without the syntax extension constructs that cannot match the - * text. Same tree, in about half the time. - */ -function attachParserWithoutUnusedSyntax(this: Processor) { - const data = this.data(); - const byMask = new Map(); - let mdastExtensions: MdastExtension[] | undefined; - this.parser = (document) => { - let mask = 0; - GATES.forEach((gate, index) => { - if (!gate.inText(document)) mask |= 1 << index; - }); - let extensions = byMask.get(mask); - if (!extensions) { - const absent = new Set(GATES.filter((_, index) => mask & (1 << index))); - extensions = [ - combineExtensions( - (data.micromarkExtensions ?? []).map((extension) => gateExtension(extension, absent)), - ), - ]; - byMask.set(mask, extensions); - } - mdastExtensions ??= [mergeMdastExtensions(data.fromMarkdownExtensions ?? [])]; - const outer = parsing; - // Gates read micromark offsets, which skip a leading byte order mark. - parsing = document.charCodeAt(0) === 0xfeff ? document.slice(1) : document; - try { - return fromMarkdown(document, { ...data.settings, extensions, mdastExtensions }); - } finally { - parsing = outer; - } - }; -} - -export const remarkParseWithoutUnusedSyntax = attachParserWithoutUnusedSyntax; diff --git a/apps/web/src/components/chat/markdownTextDirection.ts b/apps/web/src/components/chat/markdownTextDirection.ts index ffdbde76c1148..a4c78d3342754 100644 --- a/apps/web/src/components/chat/markdownTextDirection.ts +++ b/apps/web/src/components/chat/markdownTextDirection.ts @@ -1,4 +1,4 @@ -import { textDirection } from "~/textDirection"; +import { LETTER, RTL_LETTER, textDirection } from "~/textDirection"; type HastNode = { type?: string; @@ -57,11 +57,32 @@ function isolateInlineCode(node: HastNode): void { */ export function rehypeTextDirection() { return (tree: HastNode) => { - for (const block of tree.children ?? []) { - if (block.type !== "element" || block.tagName === "pre") continue; - const dir = textDirection(proseText(block)); - if (dir) block.properties = { ...block.properties, dir }; - } + blockTextDirections(tree); isolateInlineCode(tree); }; } + +/** Each top-level block's direction, from its prose; an RTL letter decides as textDirection does. */ +function blockTextDirections(tree: HastNode) { + for (const block of tree.children ?? []) { + if (block.type !== "element" || block.tagName === "pre") continue; + const dir = scriptOf(block) === "rtl" ? textDirection(proseText(block)) : scriptOf(block); + if (dir) block.properties = { ...block.properties, dir }; + } +} + +/** "rtl" when any prose letter is right-to-left; otherwise what textDirection would say. */ +function scriptOf(node: HastNode): "rtl" | "ltr" | undefined { + let found: "ltr" | undefined; + const visit = (current: HastNode): boolean => { + if (current.type === "text") { + const value = current.value ?? ""; + if (RTL_LETTER.test(value)) return true; + if (!found && LETTER.test(value)) found = "ltr"; + return false; + } + if (current.tagName === "code") return false; + return (current.children ?? []).some(visit); + }; + return visit(node) ? "rtl" : found; +} diff --git a/apps/web/src/components/chat/threadFindHighlights.ts b/apps/web/src/components/chat/threadFindHighlights.ts index c8ce0b31b9c9e..fe6a3ba5d3056 100644 --- a/apps/web/src/components/chat/threadFindHighlights.ts +++ b/apps/web/src/components/chat/threadFindHighlights.ts @@ -1,6 +1,6 @@ import { findThreadSearchOccurrences } from "@t3tools/shared/threadSearch"; import { useEffect, useEffectEvent, useRef } from "react"; -import { THREAD_FIND_BLOCK_TAGS } from "@t3tools/shared/threadFindText"; +import { THREAD_FIND_BLOCK_TAGS } from "@t3tools/shared/threadFindBlockTags"; import { observeResize } from "~/lib/observeResize"; diff --git a/apps/web/src/components/chat/timelineMinimapItems.ts b/apps/web/src/components/chat/timelineMinimapItems.ts index 151a02d88175e..57f6229c99526 100644 --- a/apps/web/src/components/chat/timelineMinimapItems.ts +++ b/apps/web/src/components/chat/timelineMinimapItems.ts @@ -4,10 +4,9 @@ import { isAttachmentOnlyBootstrapPrompt, replaceComposerContextReferences, } from "@t3tools/shared/composerContextReferences"; -import type { Nodes } from "mdast"; -import remarkGfm from "remark-gfm"; -import remarkParse from "remark-parse"; -import { unified } from "unified"; +import type { Nodes } from "hast"; + +import { markdownTree } from "~/markdown/wordsHast"; import type { MessagesTimelineRow } from "./MessagesTimeline.logic"; @@ -58,50 +57,49 @@ function resolveFinalAssistantTextForTurn( return finalAssistantText; } -const markdownPreviewParser = unified().use(remarkParse).use(remarkGfm).freeze(); - -const INLINE_PARENT_TYPES = new Set([ - "paragraph", - "heading", - "tableCell", - "emphasis", +// Elements whose children run together; every other element is separated by a space. +const INLINE_PARENTS = new Set([ + "p", + "h1", + "h2", + "h3", + "h4", + "h5", + "h6", + "td", + "th", + "em", "strong", - "delete", - "link", - "linkReference", + "del", + "a", + "code", + "span", + "sup", + "sub", ]); function markdownNodeText(node: Nodes): string { - if (node.type === "html") { - return node.value - .replace(/|$)/g, "") - .replace(/<\/?([a-z][\w-]*)(?:[^"'<>]|"[^"]*"|'[^']*')*>/gi, (_, tag: string) => - /^(?:address|article|aside|blockquote|br|dd|details|div|dl|dt|figcaption|figure|footer|h[1-6]|header|hr|li|main|nav|ol|p|pre|section|summary|table|tbody|td|th|thead|tr|ul)$/i.test( - tag, - ) - ? " " - : "", - ); - } - if (node.type === "break") return " "; - if ("value" in node) return node.value; - if (node.type === "image" || node.type === "imageReference") return node.alt ?? ""; - if (!("children" in node)) return ""; - const separator = INLINE_PARENT_TYPES.has(node.type) ? "" : " "; + if (node.type === "text") return node.value; + if (node.type === "element" && node.tagName === "br") return " "; + if (node.type === "element" && node.tagName === "img") return String(node.properties.alt ?? ""); + if (node.type !== "element" && node.type !== "root") return ""; + const separator = node.type === "element" && INLINE_PARENTS.has(node.tagName) ? "" : " "; const text = node.children.map(markdownNodeText).join(separator); // A thread autolink's only text is its URL. - return node.type === "link" && parseThreadLinkHref(text) !== null ? "a thread" : text; + return node.type === "element" && node.tagName === "a" && parseThreadLinkHref(text) !== null + ? "a thread" + : text; } /** Markdown as one line of the text it renders, without markup or link targets. */ export function markdownPlainText(markdown: string): string { - return markdownNodeText(markdownPreviewParser.parse(markdown)).replace(/\s+/g, " ").trim(); + return markdownNodeText(markdownTree(markdown)).replace(/\s+/g, " ").trim(); } // The tooltip shows a few lines; bound parsing work for long messages and streaming responses. function markdownMinimapPreview(markdown: string | null) { if (markdown === null) return null; - const compact = markdownNodeText(markdownPreviewParser.parse(markdown.slice(0, 1_500))) + const compact = markdownNodeText(markdownTree(markdown.slice(0, 1_500))) .replace(/\s+/g, " ") .trim(); return compact.length > 0 ? compact : null; diff --git a/apps/web/src/components/files/FilePreviewPanel.tsx b/apps/web/src/components/files/FilePreviewPanel.tsx index c020113815dfa..2c27cfb8d80d1 100644 --- a/apps/web/src/components/files/FilePreviewPanel.tsx +++ b/apps/web/src/components/files/FilePreviewPanel.tsx @@ -132,7 +132,7 @@ import { shouldShowFileExplorer, workspaceAssetResource, } from "./filePreviewMode"; -import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskList"; +import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskEdits"; import { changeFileSaveSession, useFileSaveSession } from "./fileSaveSessions"; import { revisionedQuery } from "~/state/revisionedQuery"; import { diff --git a/apps/web/src/components/files/NotebookPreview.tsx b/apps/web/src/components/files/NotebookPreview.tsx index 35d0203818850..c2104ad2ddec6 100644 --- a/apps/web/src/components/files/NotebookPreview.tsx +++ b/apps/web/src/components/files/NotebookPreview.tsx @@ -2,8 +2,8 @@ import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments"; import { T, useGT, useMessages } from "gt-react"; import { useEffect, useRef, useState } from "react"; -import type { Root, RootContent } from "mdast"; import ChatMarkdown from "~/components/ChatMarkdown"; +import type { MarkdownExtensions } from "~/markdown/wordsHast"; import { Button } from "~/components/ui/button"; import ReadOnlySourcePreview from "./ReadOnlySourcePreview"; import DocumentPages from "./DocumentPages"; @@ -11,24 +11,7 @@ import { FileSurfaceNotice } from "./fileSurfaceChrome"; import type { OfficeWorkerResult } from "./officePreviewProtocol"; // Saved notebooks must not load URLs or turn authored links into app actions. -function inertNotebookMarkdown() { - function clean(nodes: RootContent[]): RootContent[] { - return nodes.flatMap((node): RootContent[] => { - if (node.type === "html" || node.type === "definition") return []; - if (node.type === "image" || node.type === "imageReference") - return [{ type: "text", value: node.alt ?? "" }]; - if (node.type === "link" || node.type === "linkReference") return clean(node.children); - if (node.type === "inlineCode") return [{ type: "text", value: node.value }]; - if (node.type === "code" && node.lang === "mermaid") return [{ ...node, lang: "text" }]; - if ("children" in node) node.children = clean(node.children) as typeof node.children; - return [node]; - }); - } - return (tree: Root) => { - tree.children = clean(tree.children) as Root["children"]; - }; -} -const NOTEBOOK_PLUGINS = [inertNotebookMarkdown]; +const NOTEBOOK_MARKDOWN: MarkdownExtensions = { inert: true }; function NotebookSource(props: { readonly name: string; readonly text: string }) { const [height, setHeight] = useState(Math.min(360, props.text.split("\n").length * 20 + 16)); @@ -129,7 +112,7 @@ export default function NotebookPreview(props: { text={cell.source} cwd={undefined} parseRawHtml={false} - extraRemarkPlugins={NOTEBOOK_PLUGINS} + extensions={NOTEBOOK_MARKDOWN} className="px-4 py-3" /> ) : cell.source.trim() ? ( diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx index 1e0fa7680c405..cbf9de56dbbb2 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx @@ -112,7 +112,7 @@ import { PullRequestsUnavailableState } from "./PullRequestsUnavailableState"; import type { PullRequestAgentSelectionInput } from "./PullRequestCodeTab"; import { openOnHostLabel } from "./pullRequestLinkContextMenu"; import { PullRequestMarkdownContext } from "./PullRequestMarkdown"; -import { pullRequestMarkdownPlugins } from "./pullRequestMarkdown.logic"; +import { pullRequestMarkdownExtensions } from "./pullRequestMarkdown.logic"; import { PullRequestComposer } from "./PullRequestComposer"; import { PullRequestSummaryTab } from "./PullRequestSummaryTab"; import { PullRequestTimelineTab } from "./PullRequestTimelineTab"; @@ -298,7 +298,7 @@ function pullRequestMarkdownContext( threadRef: ScopedThreadRef | null, ) { return { - remarkPlugins: pullRequestMarkdownPlugins(detail), + extensions: pullRequestMarkdownExtensions(detail), lineBreaks: sourceControlClients.find(detail?.provider ?? "")?.hardLineBreaks ?? false, threadRef, repository: detail?.repository ?? null, diff --git a/apps/web/src/components/pullRequest/PullRequestMarkdown.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestMarkdown.browser.test.tsx index fae5270d27123..f1cd6b6ba6708 100644 --- a/apps/web/src/components/pullRequest/PullRequestMarkdown.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestMarkdown.browser.test.tsx @@ -24,7 +24,7 @@ async function renderBody( ) { const { repository = null, text = "first line\nsecond line", ...props } = options; const context = { - remarkPlugins: [], + extensions: {}, lineBreaks: sourceControlClients.get(host).hardLineBreaks ?? false, threadRef: null, repository, diff --git a/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx b/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx index 071e8dbe45d17..82012eae8f0a7 100644 --- a/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx +++ b/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx @@ -9,7 +9,7 @@ import { type ScopedThreadRef, } from "@t3tools/contracts"; import { createContext, useContext } from "react"; -import type { PluggableList } from "unified"; +import type { MarkdownExtensions } from "~/markdown/wordsHast"; import { useAssetUrlRefresh, useAssetUrlState } from "~/assets/assetUrls"; import { cn } from "~/lib/utils"; @@ -21,7 +21,7 @@ import { splitPullRequestBody, type PullRequestBodySegment } from "./pullRequest export const PullRequestMarkdownContext = createContext<{ /** Stable per repository, so comments share one renderer and its parse cache. */ - remarkPlugins: PluggableList; + extensions: MarkdownExtensions; lineBreaks: boolean; threadRef: ScopedThreadRef | null; /** The change request's `owner/name`, which can differ from the checkout the body renders in. */ @@ -129,7 +129,7 @@ function PullRequestBodySegmentView({ threadRef={threadRef} pullRequestPanelRef={threadRef ?? listPanelRef} environmentId={environmentId} - {...(context ? { extraRemarkPlugins: context.remarkPlugins } : {})} + {...(context ? { extensions: context.extensions } : {})} lineBreaks={lineBreaks} sourceControlMedia sourceControlMediaRepository={repository} diff --git a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx index dd4cf2f811c72..1f409d282ecc3 100644 --- a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx @@ -87,7 +87,7 @@ import { startDescriptionSave, type DescriptionDraft, } from "@t3tools/client-runtime/pull-request-editing"; -import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskList"; +import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskEdits"; import { PullRequestMarkdown } from "./PullRequestMarkdown"; import { PullRequestCommentBody } from "./PullRequestCommentBody"; import { PullRequestMoreReplies } from "./PullRequestMoreReplies"; diff --git a/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts index 4f25b26f3276e..3d0ae22b15017 100644 --- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts +++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts @@ -1280,6 +1280,15 @@ describe("adding a remark to the chat", () => { }); expect(context?.text).toBe("octocat: This leaks the token.\n\n```html\n\n```"); + // A stray backtick before the comment opens no code span across the paragraphs. + const stray = buildPullRequestCommentContext(pullRequest, { + kind: "comment", + comment: remark( + "c2", + "Avoid `foo.\n\n\nSee `bar` and `` a ` ``.", + ), + }); + expect(stray?.text).toBe("octocat: Avoid `foo.\n\nSee `bar` and `` a ` ``."); }); it("keeps comments inside a quoted fence as code", () => { diff --git a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts b/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts index 238038730b93f..d98ec3ff114ec 100644 --- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts +++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts @@ -5,8 +5,9 @@ import { resolvePullRequestReviewAnchor, } from "@t3tools/shared/pullRequestAnchor"; import { stripInlineContextReferences } from "~/lib/composerContextReferences"; -import type { Nodes as MdastNodes } from "mdast"; -import { fromMarkdown } from "mdast-util-from-markdown"; +import type { Nodes } from "hast"; + +import { markdownHtmlComments, markdownTree } from "~/markdown/wordsHast"; import { sourceControlClients, type ChangeRequestTerminology, @@ -693,27 +694,18 @@ export function pagePullRequestConversationItems( function readableBody(raw: string): string | null { if (visibleBody(raw) === null) return null; const body = raw.replace(/\r\n?/gu, "\n"); - const cuts: Array<[number, number]> = []; - const visit = (node: MdastNodes) => { - if (node.type === "html" && node.position?.start.offset !== undefined) { - cuts.push([node.position.start.offset, node.position.end.offset ?? body.length]); - } - if ("children" in node) for (const child of node.children) visit(child); - }; - visit(fromMarkdown(body)); let readable = ""; let from = 0; - for (const [start, end] of cuts) { + for (const { start, end } of markdownHtmlComments(body)) { + // A comment opened inside another one ends with it. + if (start < from) continue; readable += body.slice(from, start); - // An HTML block can carry markup around its comment; only the comment itself is hidden. - const html = body.slice(start, end).replace(/|$)/gu, ""); // A line that was all comment is dropped rather than left as a blank one. const ownLine = /(?:^|\n)[ \t>]*$/u.test(readable) && /^[ \t]*(?:\n|$)/u.test(body.slice(end)); - if (ownLine && html.trim() === "") { + if (ownLine) { readable = readable.replace(/[ \t>]*$/u, ""); from = end + (/^[ \t]*\n/u.exec(body.slice(end))?.[0].length ?? 0); } else { - readable += html; from = end; } } @@ -740,11 +732,12 @@ const LINK_EXCERPT_LENGTH = 280; /** The words of a markdown body, without markup, HTML or images, for a short preview. */ function markdownExcerpt(body: string): string | null { const words: string[] = []; - const visit = (node: MdastNodes) => { - if (node.type === "text" || node.type === "inlineCode") words.push(node.value); - if (node.type !== "code" && "children" in node) for (const child of node.children) visit(child); + const visit = (node: Nodes) => { + if (node.type === "text") words.push(node.value); + if (node.type === "element" && node.tagName === "pre") return; + if ("children" in node) for (const child of node.children) visit(child); }; - visit(fromMarkdown(body)); + visit(markdownTree(body, { skipHtml: true })); // GitHub's alert marker (`> [!NOTE]`) parses as text but reads as markup. const text = words .join(" ") diff --git a/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.test.ts index 1655427b2d4e9..7c4ffac84b8a5 100644 --- a/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.test.ts +++ b/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.test.ts @@ -1,45 +1,44 @@ -import { changeRequestReferenceAutolinker } from "@t3tools/client-runtime/pull-request-markdown"; -import remarkParse from "remark-parse"; -import { unified } from "unified"; +import type { Element, Root } from "hast"; import { describe, expect, it } from "vite-plus/test"; +import { wordsHast } from "~/markdown/wordsHast"; import { pullRequestCommentPreview, - pullRequestMarkdownPlugins, - remarkPullRequestAutolinks, + pullRequestMarkdownExtensions, } from "./pullRequestMarkdown.logic"; -type Node = { - type: string; - value?: string; - url?: string; - data?: { hProperties?: Record }; - children?: Node[]; -}; - function links(markdown: string) { - const autolinks = changeRequestReferenceAutolinker({ + const extensions = pullRequestMarkdownExtensions({ provider: "github", url: "https://github.com/team/repo/pull/8", - })!; - const tree = unified().use(remarkParse).parse(markdown) as Node; - remarkPullRequestAutolinks({ autolinks })(tree as never); - const found: Array<[string | undefined, string | undefined, unknown]> = []; - const visit = (node: Node) => { - if (node.type === "link") { - found.push([ - node.children?.[0]?.value, - node.url, - node.data?.hProperties?.["dataPullRequestAutolink"], - ]); + }); + const tree = wordsHast(markdown, { + math: false, + breaks: false, + escapeHtml: false, + insights: false, + extensions, + }); + const found: Array<[string, unknown, unknown]> = []; + const visit = (node: Root | Element) => { + for (const child of node.children) { + if (child.type !== "element") continue; + if (child.tagName === "a") { + const label = child.children[0]; + found.push([ + label?.type === "text" ? label.value : "", + child.properties.href, + child.properties.dataPullRequestAutolink, + ]); + } + visit(child); } - node.children?.forEach(visit); }; visit(tree); return found; } -describe("remarkPullRequestAutolinks", () => { +describe("pullRequestMarkdownExtensions", () => { it("links the host's references in prose and leaves links and code alone", () => { expect(links("Fixes #12 in **abcdef1**. [#13](https://example.com) `#14`")).toEqual([ ["#12", "https://github.com/team/repo/issues/12", "reference"], @@ -47,22 +46,25 @@ describe("remarkPullRequestAutolinks", () => { ["#13", "https://example.com", undefined], ]); }); -}); - -describe("pullRequestMarkdownPlugins", () => { it("renders GitHub emoji shortcodes in prose and leaves code literal", () => { - const processor = unified() - .use(remarkParse) - .use( - pullRequestMarkdownPlugins({ - provider: "github", - url: "https://github.com/team/repo/pull/8", - }), - ); - const tree = processor.runSync(processor.parse("Ship it :tada: :+1: `:tada:`")) as Node; - const text = (node: Node): string => - (node.type === "inlineCode" ? `\`${node.value}\`` : (node.value ?? "")) + - (node.children ?? []).map(text).join(""); + const extensions = pullRequestMarkdownExtensions({ + provider: "github", + url: "https://github.com/team/repo/pull/8", + }); + const tree = wordsHast("Ship it :tada: :+1: `:tada:`", { + math: false, + breaks: false, + escapeHtml: false, + insights: false, + extensions, + }); + const text = (node: Root | Element | Root["children"][number]): string => { + if (node.type === "text") return node.value; + if (node.type === "element" && node.tagName === "code") { + return `\`${node.children.map(text).join("")}\``; + } + return "children" in node ? node.children.map(text).join("") : ""; + }; expect(text(tree)).toBe("Ship it 🎉 👍 `:tada:`"); }); }); diff --git a/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts b/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts index 21f3574838e06..560b6ee03fd37 100644 --- a/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts +++ b/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts @@ -1,130 +1,63 @@ -import { - changeRequestReferenceAutolinker, - expandGithubEmojiAliases, - resolveChangeRequestMediaUrl, -} from "@t3tools/client-runtime/pull-request-markdown"; -import { - sourceControlClients, - type ReferenceAutolink, -} from "@t3tools/client-runtime/source-control-clients"; -import { - CHAT_MARKDOWN_REHYPE_PLUGINS, - CHAT_MARKDOWN_REMARK_PLUGINS, -} from "@t3tools/shared/markdownPipeline"; +import { changeRequestReferenceAutolinker } from "@t3tools/client-runtime/pull-request-references"; +import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; import type { Nodes } from "hast"; -import remarkParse from "remark-parse"; -import remarkRehype from "remark-rehype"; -import { unified, type PluggableList } from "unified"; -export { - splitPullRequestBody, +import { + splitPullRequestBody as splitBody, type PullRequestBodySegment, } from "@t3tools/client-runtime/pull-request-markdown"; +import { + markdownReferenceDefinitions, + wordsHast, + type MarkdownExtensions, +} from "~/markdown/wordsHast"; -type MarkdownNode = { - type: string; - value?: string; - children?: MarkdownNode[]; - url?: string; - data?: unknown; -}; - -const AUTOLINK_IGNORED_TYPES = new Set(["link", "linkReference"]); - -export function remarkPullRequestAutolinks(options: { - readonly autolinks: (text: string) => ReadonlyArray; -}) { - const visit = (node: MarkdownNode): void => { - const children = node.children; - if (children === undefined) return; - for (let index = 0; index < children.length; index += 1) { - const child = children[index]!; - if (AUTOLINK_IGNORED_TYPES.has(child.type)) continue; - if (child.type !== "text" || child.value === undefined) { - visit(child); - continue; - } - const value = child.value; - const links = options.autolinks(value); - if (links.length === 0) continue; - const replacements: MarkdownNode[] = []; - let start = 0; - for (const link of links) { - if (start < link.index) { - replacements.push({ type: "text", value: value.slice(start, link.index) }); - } - replacements.push({ - type: "link", - url: link.url, - data: { hProperties: { dataPullRequestAutolink: link.kind } }, - children: [{ type: "text", value: link.label }], - }); - start = link.index + link.text.length; - } - if (start < value.length) replacements.push({ type: "text", value: value.slice(start) }); - children.splice(index, 1, ...replacements); - index += replacements.length - 1; - } - }; - return (tree: MarkdownNode) => visit(tree); -} +export type { PullRequestBodySegment }; -function remarkChangeRequestMediaUrls(options: { readonly changeRequestUrl: string }) { - const visit = (node: MarkdownNode): void => { - if ((node.type === "image" || node.type === "definition") && node.url !== undefined) { - node.url = resolveChangeRequestMediaUrl(node.url, options.changeRequestUrl); - } - node.children?.forEach(visit); - }; - return (tree: MarkdownNode) => visit(tree); +export function splitPullRequestBody(body: string): ReadonlyArray { + return splitBody(body, markdownReferenceDefinitions); } -/** GitHub renders `:alias:` emoji in prose; code keeps them, being `inlineCode`/`code`, not `text`. */ -function remarkGithubEmoji() { - const visit = (node: MarkdownNode): void => { - if (node.type === "text" && node.value !== undefined) - node.value = expandGithubEmojiAliases(node.value); - node.children?.forEach(visit); - }; - return (tree: MarkdownNode) => visit(tree); -} - -const NO_PLUGINS: PluggableList = []; -const markdownPlugins = new Map(); +const NO_EXTENSIONS: MarkdownExtensions = {}; +const markdownExtensions = new Map(); /** - * One plugin list per repository, so every comment of a pull request shares one markdown + * One extension object per repository, so every comment of a pull request shares one markdown * renderer and its parse cache instead of parsing again on each render. */ -export function pullRequestMarkdownPlugins( +export function pullRequestMarkdownExtensions( changeRequest: { readonly provider: string; readonly url: string } | null, -): PluggableList { - if (changeRequest === null) return NO_PLUGINS; +): MarkdownExtensions { + if (changeRequest === null) return NO_EXTENSIONS; const repositoryUrl = sourceControlClients.parseChangeRequestUrl(changeRequest.url)?.link .repositoryUrl; - if (repositoryUrl === undefined) return NO_PLUGINS; + if (repositoryUrl === undefined) return NO_EXTENSIONS; const key = `${changeRequest.provider}\u0000${repositoryUrl}`; - let plugins = markdownPlugins.get(key); - if (plugins === undefined) { - const autolinks = changeRequestReferenceAutolinker(changeRequest); - plugins = [[remarkChangeRequestMediaUrls, { changeRequestUrl: repositoryUrl }]]; - if (changeRequest.provider === "github") plugins.push(remarkGithubEmoji); - if (autolinks) plugins.push([remarkPullRequestAutolinks, { autolinks }]); - markdownPlugins.set(key, plugins); + let extensions = markdownExtensions.get(key); + if (extensions === undefined) { + extensions = { + changeRequest: { + repositoryUrl, + autolinks: changeRequestReferenceAutolinker(changeRequest), + }, + githubEmoji: changeRequest.provider === "github", + }; + markdownExtensions.set(key, extensions); } - return plugins; + return extensions; } -const commentPreviewProcessor = (plugins: PluggableList) => - unified() - .use(remarkParse) - .use(CHAT_MARKDOWN_REMARK_PLUGINS) - .use(plugins) - .use(remarkRehype, { allowDangerousHtml: true }) - .use(CHAT_MARKDOWN_REHYPE_PLUGINS) - .freeze(); -const commentPreview = commentPreviewProcessor(NO_PLUGINS); -const githubCommentPreview = commentPreviewProcessor([remarkGithubEmoji]); +const PREVIEW_MARKDOWN = { + math: false, + breaks: false, + escapeHtml: false, + insights: false, + extensions: NO_EXTENSIONS, +}; +const GITHUB_PREVIEW_MARKDOWN = { + ...PREVIEW_MARKDOWN, + extensions: { githubEmoji: true }, +}; const PREVIEW_BLOCK_TAGS = new Set([ "blockquote", @@ -164,7 +97,6 @@ function commentPreviewText(node: Nodes): string { } export function pullRequestCommentPreview(body: string, provider: string): string { - const processor = provider === "github" ? githubCommentPreview : commentPreview; - const tree = processor.runSync(processor.parse(body), body); - return commentPreviewText(tree).replace(/\s+/gu, " ").trim(); + const options = provider === "github" ? GITHUB_PREVIEW_MARKDOWN : PREVIEW_MARKDOWN; + return commentPreviewText(wordsHast(body, options)).replace(/\s+/gu, " ").trim(); } diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index d91d6da4a42d7..4252fccc9c7d0 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -512,6 +512,7 @@ export const SETTINGS_SEARCH_ITEMS = [ targetId: "boring-sidebar", searchTerms: [msg("beta boring sidebar folder rows multiline branch pull request details")], }, + { id: "tool-call-visibility", title: msg("Tool calls in chat"), diff --git a/apps/web/src/components/ui/shared-tooltip.tsx b/apps/web/src/components/ui/shared-tooltip.tsx new file mode 100644 index 0000000000000..0858fa656e6bb --- /dev/null +++ b/apps/web/src/components/ui/shared-tooltip.tsx @@ -0,0 +1,262 @@ +import { + cloneElement, + createContext, + use, + useEffect, + useId, + useRef, + useState, + type FocusEvent, + type PointerEvent, + type ReactElement, + type ReactNode, +} from "react"; + +import { Tooltip, TooltipPopup, TooltipTrigger, useTooltipScrollTracker } from "./tooltip"; + +// Base UI's tooltip timing: open after a rest, reopen at once right after another closed. +const OPEN_DELAY_MS = 600; +const REOPEN_WINDOW_MS = 400; +// Time to travel from the trigger into a hoverable popup. +const CLOSE_GRACE_MS = 100; + +interface SharedTooltipContent { + readonly render: () => ReactNode; + /** Comparable key that changes whenever `render()` output changes while open. */ + readonly contentKey?: unknown; + readonly side?: "top" | "bottom" | "left" | "right"; + readonly variant?: "default" | "glass" | "code"; +} + +interface SharedTooltipState extends SharedTooltipContent { + readonly anchor: HTMLElement; + readonly open: boolean; +} + +interface SharedTooltipApi { + show(anchor: HTMLElement, content: SharedTooltipContent, immediate: boolean): void; + refresh(anchor: HTMLElement, content: SharedTooltipContent): void; + hide(anchor: HTMLElement): void; + /** A press closes it at once, as Base UI's closeOnClick does. */ + dismiss(anchor: HTMLElement): void; + holdOpen(): void; +} + +function setAriaDescribedBy(element: HTMLElement, id: string, present: boolean) { + const tokens = (element.getAttribute("aria-describedby") ?? "").split(/\s+/).filter(Boolean); + const next = present + ? tokens.includes(id) + ? tokens + : [...tokens, id] + : tokens.filter((token) => token !== id); + if (next.length > 0) element.setAttribute("aria-describedby", next.join(" ")); + else element.removeAttribute("aria-describedby"); +} + +const SharedTooltipContext = createContext(null); + +/** + * One tooltip for many triggers: a long message would otherwise mount a Base UI tooltip per + * link and file chip, and almost none of them are ever hovered. + */ +export function SharedTooltipProvider({ children }: { children: ReactNode }) { + const popupId = useId(); + const [state, setState] = useState(null); + const timer = useRef | null>(null); + const pending = useRef(null); + const lastClosedAt = useRef(0); + const current = useRef(null); + + const commit = (next: SharedTooltipState | null) => { + current.current = next; + setState(next); + }; + const clearTimer = () => { + if (timer.current !== null) clearTimeout(timer.current); + timer.current = null; + pending.current = null; + }; + const [api] = useState(() => ({ + show(anchor, content, immediate) { + clearTimer(); + const open = current.current?.open === true; + const reopen = performance.now() - lastClosedAt.current < REOPEN_WINDOW_MS; + if (immediate || open || reopen) { + commit({ ...content, anchor, open: true }); + return; + } + pending.current = { ...content, anchor, open: true }; + timer.current = setTimeout(() => { + const next = pending.current; + pending.current = null; + if (next) commit(next); + }, OPEN_DELAY_MS); + }, + refresh(anchor, content) { + if (pending.current?.anchor === anchor) { + pending.current = { ...pending.current, ...content }; + } + const active = current.current; + if (!active || active.anchor !== anchor) return; + if ( + active.contentKey === content.contentKey && + active.side === content.side && + active.variant === content.variant + ) { + return; + } + commit({ ...active, ...content }); + }, + hide(anchor) { + if (current.current && current.current.anchor !== anchor) { + clearTimer(); + return; + } + clearTimer(); + timer.current = setTimeout(() => { + if (current.current?.open) lastClosedAt.current = performance.now(); + if (current.current) commit({ ...current.current, open: false }); + }, CLOSE_GRACE_MS); + }, + dismiss(anchor) { + clearTimer(); + if (current.current?.anchor !== anchor) return; + if (current.current.open) lastClosedAt.current = 0; + commit({ ...current.current, open: false }); + }, + holdOpen() { + clearTimer(); + }, + })); + + const activeAnchor = state?.open ? state.anchor : null; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- links the active trigger DOM element to the shared tooltip popup via aria-describedby + useEffect(() => { + if (!activeAnchor) return; + setAriaDescribedBy(activeAnchor, popupId, true); + return () => setAriaDescribedBy(activeAnchor, popupId, false); + }, [activeAnchor, popupId]); + + return ( + + {children} + {state ? ( + { + if (!open) api.hide(state.anchor); + }} + > + api.holdOpen()} + onMouseLeave={() => api.hide(state.anchor)} + > + {state.render()} + + + ) : null} + + ); +} + +export interface SharedTooltipTriggerProps { + onPointerEnter: (event: PointerEvent) => void; + onPointerLeave: (event: PointerEvent) => void; + onFocus: (event: FocusEvent) => void; + onBlur: (event: FocusEvent) => void; + onPointerDown: (event: PointerEvent) => void; +} + +/** Props that show `content` on the shared tooltip, or null outside a SharedTooltipProvider. */ +export function useSharedTooltip(content: SharedTooltipContent): SharedTooltipTriggerProps | null { + const api = use(SharedTooltipContext); + const scrollTracker = useTooltipScrollTracker(); + const anchorRef = useRef(null); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- refreshes an open shared tooltip when its trigger's label changes + useEffect(() => { + if (api && anchorRef.current) api.refresh(anchorRef.current, content); + }, [api, content]); + if (!api) return null; + return { + // Touch never opens it, as Base UI's mouseOnly trigger; taps also send compatibility mouse events. + onPointerEnter: (event) => { + if (event.pointerType === "touch") return; + const trigger = event.currentTarget; + anchorRef.current = trigger; + api.show(trigger, content, false); + // Scrolling the timeline closes it, as it does a TooltipTrigger's. + scrollTracker?.hover(trigger, api, () => api.dismiss(trigger)); + }, + onPointerLeave: (event) => api.hide(event.currentTarget), + // Keyboard focus shows it at once, as Base UI does. + onFocus: (event) => { + if (event.currentTarget.matches(":focus-visible")) { + anchorRef.current = event.currentTarget; + api.show(event.currentTarget, content, true); + } + }, + onBlur: (event) => api.hide(event.currentTarget), + onPointerDown: (event) => api.dismiss(event.currentTarget), + }; +} + +type Handlers = Partial void>>; + +/** The trigger's own handlers run first, then the shared tooltip's. */ +export function withSharedTooltip( + element: ReactElement, + tooltip: SharedTooltipTriggerProps, + children?: ReactNode, +): ReactElement { + const own = element.props as Handlers; + const merged: Record void> = {}; + for (const key of Object.keys(tooltip) as Array) { + const shared = tooltip[key] as (event: never) => void; + const mine = own[key]; + merged[key] = mine + ? (event) => { + mine(event); + shared(event); + } + : shared; + } + return children === undefined + ? cloneElement(element, merged as Partial) + : cloneElement(element, merged as Partial, children); +} + +/** A tooltip on `render`: the shared one inside a SharedTooltipProvider, Base UI's otherwise. */ +export function SharedTooltipTrigger({ + render, + children, + label, + side = "top", + variant, +}: { + render: ReactElement; + children?: ReactNode; + label: ReactNode; + side?: SharedTooltipContent["side"]; + variant?: SharedTooltipContent["variant"]; +}) { + const tooltip = useSharedTooltip({ + render: () => label, + contentKey: label, + side, + ...(variant ? { variant } : {}), + }); + if (tooltip) return withSharedTooltip(render, tooltip, children); + return ( + + {children} + + {label} + + + ); +} diff --git a/apps/web/src/components/ui/tooltip.browser.test.tsx b/apps/web/src/components/ui/tooltip.browser.test.tsx index 24d76784e8a5a..bcb62ee2fdaf0 100644 --- a/apps/web/src/components/ui/tooltip.browser.test.tsx +++ b/apps/web/src/components/ui/tooltip.browser.test.tsx @@ -3,41 +3,114 @@ import { page, userEvent } from "vite-plus/test/browser"; import "~/index.css"; import { render } from "../../../test/render"; +import { SharedTooltipProvider, SharedTooltipTrigger } from "./shared-tooltip"; import { Tooltip, TooltipPopup, TooltipScrollDismissArea, TooltipTrigger } from "./tooltip"; +function TimelineAction({ shared }: { shared: boolean }) { + if (shared) { + return ( + + }> + Timeline action + + + ); + } + return ( + + Timeline action + Description + + ); +} + it.each([ - { focus: "mouse", keptOpen: false }, - { focus: "keyboard", keptOpen: true }, -])("scrolling with a $focus-focused hovered trigger keeps it open: $keptOpen", async (c) => { - const onScroll = vi.fn(); + { shared: false, focus: "mouse", keptOpen: false }, + { shared: false, focus: "keyboard", keptOpen: true }, + { shared: true, focus: "mouse", keptOpen: false }, + { shared: true, focus: "keyboard", keptOpen: true }, +])( + "scrolling with a $focus-focused hovered trigger (shared: $shared) keeps it open: $keptOpen", + async (c) => { + const onScroll = vi.fn(); + await using screen = await render( + + +
    + , + ); + const trigger = screen.getByRole("button", { name: "Timeline action" }); + if (c.focus === "mouse") { + // A press closes the tooltip; hovering again reopens it with mouse focus kept. + await userEvent.click(trigger); + await userEvent.unhover(trigger); + } else { + await userEvent.keyboard("{Tab}"); + } + await userEvent.hover(trigger); + await expect.element(trigger).toHaveFocus(); + await expect.element(page.getByText("Description")).toBeVisible(); + + // One pixel keeps the pointer over the trigger, so only the scroll can close it. + screen.getByTestId("timeline").element().scrollTop = 1; + await vi.waitFor(() => expect(onScroll).toHaveBeenCalledOnce()); + + if (c.keptOpen) await expect.element(page.getByText("Description")).toBeVisible(); + else await expect.element(page.getByText("Description")).not.toBeInTheDocument(); + }, +); + +it("refreshes an open shared tooltip's label and links aria-describedby on focus", async () => { await using screen = await render( - - - Timeline action - Description - -
    - , + + }> + Copy + + , ); - const trigger = screen.getByRole("button", { name: "Timeline action" }); - if (c.focus === "mouse") { - // A press closes the tooltip; hovering again reopens it with mouse focus kept. - await userEvent.click(trigger); - await userEvent.unhover(trigger); - } else { - await userEvent.keyboard("{Tab}"); - } - await userEvent.hover(trigger); + const trigger = screen.getByRole("button", { name: "Copy" }); + await userEvent.keyboard("{Tab}"); await expect.element(trigger).toHaveFocus(); - await expect.element(page.getByText("Description")).toBeVisible(); + const popup = page.getByText("Copy code"); + await expect.element(popup).toBeVisible(); + const popupId = trigger.element().getAttribute("aria-describedby"); + expect(popupId).toBeTruthy(); + expect(document.getElementById(popupId!)?.textContent).toBe("Copy code"); - screen.getByTestId("timeline").element().scrollTop = 20; - await vi.waitFor(() => expect(onScroll).toHaveBeenCalledOnce()); + await screen.rerender( + + }> + Copy + + , + ); + await expect.element(page.getByText("Copied")).toBeVisible(); + + await userEvent.keyboard("{Tab}"); + await vi.waitFor(() => expect(trigger.element().getAttribute("aria-describedby")).toBeNull()); +}); - if (c.keptOpen) await expect.element(page.getByText("Description")).toBeVisible(); - else await expect.element(page.getByText("Description")).not.toBeInTheDocument(); +it("refreshes a pending shared tooltip if its label changes during the open delay", async () => { + await using screen = await render( + + }> + Copy + + , + ); + const trigger = screen.getByRole("button", { name: "Copy" }); + await userEvent.hover(trigger); + await screen.rerender( + + }> + Copy + + , + ); + await expect.element(page.getByText("Copy code")).toBeVisible(); + expect(page.getByText("Copied").query()).toBeNull(); }); diff --git a/apps/web/src/components/ui/tooltip.tsx b/apps/web/src/components/ui/tooltip.tsx index 577aa48da87fa..e47a6b8d13afe 100644 --- a/apps/web/src/components/ui/tooltip.tsx +++ b/apps/web/src/components/ui/tooltip.tsx @@ -21,13 +21,13 @@ type TooltipActionsRef = RefObject; // The compiler freezes context values; update hovered tooltips through calls instead of shared ref writes. function createTooltipHoverTracker() { - let hovered: { trigger: HTMLElement; actionsRef: TooltipActionsRef } | null = null; + let hovered: { trigger: HTMLElement; owner: object; close: () => void } | null = null; return { - hover(trigger: HTMLElement, actionsRef: TooltipActionsRef) { - hovered = { trigger, actionsRef }; + hover(trigger: HTMLElement, owner: object, close: () => void) { + hovered = { trigger, owner, close }; }, - release(actionsRef: TooltipActionsRef) { - if (hovered?.actionsRef === actionsRef) hovered = null; + release(owner: object) { + if (hovered?.owner === owner) hovered = null; }, dismissUnfocused() { const tooltip = hovered; @@ -37,8 +37,7 @@ function createTooltipHoverTracker() { return; } hovered = null; - // Base UI also cancels delayed hover opens through this action. - tooltip.actionsRef.current?.close(); + tooltip.close(); }, }; } @@ -96,7 +95,8 @@ function TooltipTrigger(props: TooltipPrimitive.Trigger.Props) { {...props} onMouseEnter={(event) => { props.onMouseEnter?.(event); - tracker.hover(event.currentTarget, actionsRef); + // Base UI also cancels delayed hover opens through this action. + tracker.hover(event.currentTarget, actionsRef, () => actionsRef.current?.close()); }} /> ); @@ -161,4 +161,14 @@ function TooltipPopup({ ); } -export { TooltipProvider, Tooltip, TooltipTrigger, TooltipPopup, TooltipScrollDismissArea }; +/** The enclosing TooltipScrollDismissArea's tracker, for triggers that bypass TooltipTrigger. */ +const useTooltipScrollTracker = () => use(TooltipScrollContext); + +export { + TooltipProvider, + Tooltip, + TooltipTrigger, + TooltipPopup, + TooltipScrollDismissArea, + useTooltipScrollTracker, +}; diff --git a/apps/web/src/composer-editor-mentions.ts b/apps/web/src/composer-editor-mentions.ts index 7f3e93b821488..6608d3b2a0439 100644 --- a/apps/web/src/composer-editor-mentions.ts +++ b/apps/web/src/composer-editor-mentions.ts @@ -7,6 +7,7 @@ import { composerMathRanges, type ComposerInlineToken, } from "@t3tools/shared/composerInlineTokens"; +import { markdownMathRanges } from "~/markdown/wordsHast"; export type ComposerPromptSegment = | { @@ -89,7 +90,7 @@ function collectModelTokens(text: string, inlineTokens: ReadonlyArray !taken.some((range) => mention.start < range.end && mention.end > range.start), @@ -98,7 +99,7 @@ function collectModelTokens(text: string, inlineTokens: ReadonlyArray = []; for (const formula of formulas) { diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index c7095b8536469..92a2fa11cf7f2 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -3694,7 +3694,6 @@ "7c1923203049d602": "Code kopieren", "637817e4ff79c90e": "Aktionen für Codeblock", "ebf3a2b1e314aa5f": "Im Terminal ausführen", - "fe219642547fa0bf": "Im Terminal ausführen", "122a8512abc51180": "Details", "58c38c65c2783c5d": "Vollständiger Pfad", "f37e7d36b51c5b28": "Relativen Pfad kopieren", @@ -3706,10 +3705,6 @@ "4967584e8d0fb1c2": "Medienvorschau", "67589dd912eacb7c": "Im integrierten Browser öffnen", "a3c98d4c4b24cecb": "Dateioptionen für {label}", - "b4fe8a076e9fd2f8": "Abgesetzte Formel", - "085d1407e8c92cce": "Formel im Text", - "a2ef393fa7b48ae8": "Abgesetzte Formel scrollen", - "e94685ea5642e088": "Formel im Text scrollen", "3a04583c8500e23d": "Diagramm anzeigen", "16d64f650840fe06": "Code anzeigen", "6d329f7d3a50c7e7": "Tabelle kopieren", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 2ff8148bb7329..b174085c87c95 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -3693,7 +3693,6 @@ "7c1923203049d602": "Copy code", "637817e4ff79c90e": "Code block actions", "ebf3a2b1e314aa5f": "Run in terminal", - "fe219642547fa0bf": "Run in terminal", "122a8512abc51180": "Details", "58c38c65c2783c5d": "Full path", "f37e7d36b51c5b28": "Copy relative path", @@ -3705,10 +3704,6 @@ "4967584e8d0fb1c2": "Preview media", "67589dd912eacb7c": "Open in integrated browser", "a3c98d4c4b24cecb": "File options for {label}", - "b4fe8a076e9fd2f8": "Display equation", - "085d1407e8c92cce": "Inline equation", - "a2ef393fa7b48ae8": "Scroll display equation", - "e94685ea5642e088": "Scroll inline equation", "3a04583c8500e23d": "Show diagram", "16d64f650840fe06": "Show code", "6d329f7d3a50c7e7": "Copy table", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 78c68c4c0dc2f..b12f6e7f0dc32 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -3693,7 +3693,6 @@ "7c1923203049d602": "Copiar código", "637817e4ff79c90e": "Acciones del bloque de código", "ebf3a2b1e314aa5f": "Ejecutar en la terminal", - "fe219642547fa0bf": "Ejecutar en la terminal", "122a8512abc51180": "Detalles", "58c38c65c2783c5d": "Ruta completa", "f37e7d36b51c5b28": "Copiar ruta relativa", @@ -3705,10 +3704,6 @@ "4967584e8d0fb1c2": "Vista previa del contenido", "67589dd912eacb7c": "Abrir en el navegador integrado", "a3c98d4c4b24cecb": "Opciones de archivo de {label}", - "b4fe8a076e9fd2f8": "Ecuación en bloque", - "085d1407e8c92cce": "Ecuación en línea", - "a2ef393fa7b48ae8": "Desplazar la ecuación en bloque", - "e94685ea5642e088": "Desplazar la ecuación en línea", "3a04583c8500e23d": "Mostrar diagrama", "16d64f650840fe06": "Mostrar código", "6d329f7d3a50c7e7": "Copiar tabla", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 873767a296ba5..c5f7562a38e7d 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -3693,7 +3693,6 @@ "7c1923203049d602": "Copier le code", "637817e4ff79c90e": "Actions du bloc de code", "ebf3a2b1e314aa5f": "Exécuter dans le terminal", - "fe219642547fa0bf": "Exécuter dans le terminal", "122a8512abc51180": "Détails", "58c38c65c2783c5d": "Chemin complet", "f37e7d36b51c5b28": "Copier le chemin relatif", @@ -3705,10 +3704,6 @@ "4967584e8d0fb1c2": "Aperçu du média", "67589dd912eacb7c": "Ouvrir dans le navigateur intégré", "a3c98d4c4b24cecb": "Options du fichier {label}", - "b4fe8a076e9fd2f8": "Équation en bloc", - "085d1407e8c92cce": "Équation en ligne", - "a2ef393fa7b48ae8": "Faire défiler l’équation en bloc", - "e94685ea5642e088": "Faire défiler l’équation en ligne", "3a04583c8500e23d": "Afficher le diagramme", "16d64f650840fe06": "Afficher le code", "6d329f7d3a50c7e7": "Copier le tableau", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 69ac82ad8a247..a0a71c4814184 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -3688,7 +3688,6 @@ "7c1923203049d602": "コードをコピー", "637817e4ff79c90e": "コードブロックの操作", "ebf3a2b1e314aa5f": "ターミナルで実行", - "fe219642547fa0bf": "ターミナルで実行", "122a8512abc51180": "詳細", "58c38c65c2783c5d": "フルパス", "f37e7d36b51c5b28": "相対パスをコピー", @@ -3700,10 +3699,6 @@ "4967584e8d0fb1c2": "メディアをプレビュー", "67589dd912eacb7c": "統合ブラウザーで開く", "a3c98d4c4b24cecb": "{label} のファイルオプション", - "b4fe8a076e9fd2f8": "ディスプレイ数式", - "085d1407e8c92cce": "インライン数式", - "a2ef393fa7b48ae8": "ディスプレイ数式をスクロール", - "e94685ea5642e088": "インライン数式をスクロール", "3a04583c8500e23d": "図を表示", "16d64f650840fe06": "コードを表示", "6d329f7d3a50c7e7": "表をコピー", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 10782b2ca6166..ba0da8c82495a 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -3688,7 +3688,6 @@ "7c1923203049d602": "코드 복사", "637817e4ff79c90e": "코드 블록 작업", "ebf3a2b1e314aa5f": "터미널에서 실행", - "fe219642547fa0bf": "터미널에서 실행", "122a8512abc51180": "세부 정보", "58c38c65c2783c5d": "전체 경로", "f37e7d36b51c5b28": "상대 경로 복사", @@ -3700,10 +3699,6 @@ "4967584e8d0fb1c2": "미디어 미리 보기", "67589dd912eacb7c": "통합 브라우저에서 열기", "a3c98d4c4b24cecb": "{label} 파일 옵션", - "b4fe8a076e9fd2f8": "블록 수식", - "085d1407e8c92cce": "인라인 수식", - "a2ef393fa7b48ae8": "블록 수식 스크롤", - "e94685ea5642e088": "인라인 수식 스크롤", "3a04583c8500e23d": "다이어그램 표시", "16d64f650840fe06": "코드 표시", "6d329f7d3a50c7e7": "표 복사", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 5b2b9e2b9b381..66d4f0b457e35 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -3693,7 +3693,6 @@ "7c1923203049d602": "Copiar código", "637817e4ff79c90e": "Ações do bloco de código", "ebf3a2b1e314aa5f": "Executar no terminal", - "fe219642547fa0bf": "Executar no terminal", "122a8512abc51180": "Detalhes", "58c38c65c2783c5d": "Caminho completo", "f37e7d36b51c5b28": "Copiar caminho relativo", @@ -3705,10 +3704,6 @@ "4967584e8d0fb1c2": "Pré-visualizar mídia", "67589dd912eacb7c": "Abrir no navegador integrado", "a3c98d4c4b24cecb": "Opções do arquivo {label}", - "b4fe8a076e9fd2f8": "Equação em destaque", - "085d1407e8c92cce": "Equação em linha", - "a2ef393fa7b48ae8": "Rolar a equação em destaque", - "e94685ea5642e088": "Rolar a equação em linha", "3a04583c8500e23d": "Mostrar diagrama", "16d64f650840fe06": "Mostrar código", "6d329f7d3a50c7e7": "Copiar tabela", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 0ecadaba9ded1..879d2684c207f 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -3693,7 +3693,6 @@ "7c1923203049d602": "Копировать код", "637817e4ff79c90e": "Действия с блоком кода", "ebf3a2b1e314aa5f": "Выполнить в терминале", - "fe219642547fa0bf": "Выполнить в терминале", "122a8512abc51180": "Подробности", "58c38c65c2783c5d": "Полный путь", "f37e7d36b51c5b28": "Копировать относительный путь", @@ -3705,10 +3704,6 @@ "4967584e8d0fb1c2": "Предпросмотр медиа", "67589dd912eacb7c": "Открыть во встроенном браузере", "a3c98d4c4b24cecb": "Параметры файла {label}", - "b4fe8a076e9fd2f8": "Формула в отдельной строке", - "085d1407e8c92cce": "Формула в строке", - "a2ef393fa7b48ae8": "Прокрутить формулу", - "e94685ea5642e088": "Прокрутить формулу в строке", "3a04583c8500e23d": "Показать диаграмму", "16d64f650840fe06": "Показать код", "6d329f7d3a50c7e7": "Копировать таблицу", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 1c01b1112768f..3de08f6ce6252 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -3693,7 +3693,6 @@ "7c1923203049d602": "Kopiera kod", "637817e4ff79c90e": "Åtgärder för kodblock", "ebf3a2b1e314aa5f": "Kör i terminalen", - "fe219642547fa0bf": "Kör i terminalen", "122a8512abc51180": "Detaljer", "58c38c65c2783c5d": "Fullständig sökväg", "f37e7d36b51c5b28": "Kopiera relativ sökväg", @@ -3705,10 +3704,6 @@ "4967584e8d0fb1c2": "Förhandsvisa media", "67589dd912eacb7c": "Öppna i den integrerade webbläsaren", "a3c98d4c4b24cecb": "Filalternativ för {label}", - "b4fe8a076e9fd2f8": "Fristående ekvation", - "085d1407e8c92cce": "Ekvation i texten", - "a2ef393fa7b48ae8": "Rulla fristående ekvation", - "e94685ea5642e088": "Rulla ekvation i texten", "3a04583c8500e23d": "Visa diagram", "16d64f650840fe06": "Visa kod", "6d329f7d3a50c7e7": "Kopiera tabell", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 43790340d1167..0193a3db09720 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -3698,7 +3698,6 @@ "7c1923203049d602": "复制代码", "637817e4ff79c90e": "代码块操作", "ebf3a2b1e314aa5f": "在终端中运行", - "fe219642547fa0bf": "在终端中运行", "122a8512abc51180": "详情", "58c38c65c2783c5d": "完整路径", "f37e7d36b51c5b28": "复制相对路径", @@ -3710,10 +3709,6 @@ "4967584e8d0fb1c2": "预览媒体", "67589dd912eacb7c": "在内置浏览器中打开", "a3c98d4c4b24cecb": "{label} 的文件选项", - "b4fe8a076e9fd2f8": "独立公式", - "085d1407e8c92cce": "行内公式", - "a2ef393fa7b48ae8": "滚动查看独立公式", - "e94685ea5642e088": "滚动查看行内公式", "3a04583c8500e23d": "显示图表", "16d64f650840fe06": "显示代码", "6d329f7d3a50c7e7": "复制表格", diff --git a/apps/web/src/index.css b/apps/web/src/index.css index 4ba107059f2b7..2b19b90cc28e3 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -1887,10 +1887,6 @@ code { margin: 0.65rem 0; } -.chat-markdown-math-display .katex-display { - margin: 0; -} - :is(.chat-markdown, .composer-tiptap) h1, :is(.chat-markdown, .composer-tiptap) h2, :is(.chat-markdown, .composer-tiptap) h3, @@ -2312,6 +2308,15 @@ code { overflow-wrap: break-word; } +.chat-markdown [data-markdown-math] { + font-weight: normal; + font-style: normal; +} + +.chat-markdown [data-markdown-math] > svg { + font-size: 1.21em; +} + /* Formula cells keep their natural width and scroll with the table. */ .chat-markdown :is(th, td):has([data-markdown-math]) { max-width: none; diff --git a/apps/web/src/markdown-clipboard.test.ts b/apps/web/src/markdown-clipboard.test.ts index 1b0aa804a8437..7a50785c726c7 100644 --- a/apps/web/src/markdown-clipboard.test.ts +++ b/apps/web/src/markdown-clipboard.test.ts @@ -11,19 +11,27 @@ import { collectAssistantCitations, serializeAssistantCitation, } from "@t3tools/shared/assistantCitations"; -import { markdownMathRanges, parseMarkdownWithMath } from "@t3tools/shared/markdownMath"; +import type { Element as HastElement, ElementContent, Root } from "hast"; -import { unified } from "unified"; -import remarkParse from "remark-parse"; -import { - CHAT_MARKDOWN_REMARK_PLUGINS, - CHAT_USER_MARKDOWN_REMARK_PLUGINS, -} from "@t3tools/shared/markdownPipeline"; +import { markdownTree } from "./markdown/wordsHast"; -const userMarkdown = unified() - .use(remarkParse) - .use(CHAT_MARKDOWN_REMARK_PLUGINS) - .use(CHAT_USER_MARKDOWN_REMARK_PLUGINS); +// Copied Markdown read back as the chat reads it, to check it says what was copied. +const elementsOf = (node: Root | HastElement) => + (node.children as ElementContent[]).filter( + (child): child is HastElement => child.type === "element", + ); +const textOf = (node: ElementContent): string => + node.type === "text" + ? node.value + : node.type === "element" + ? node.children.map(textOf).join("") + : ""; +const readBack = (markdown: string, options?: Parameters[1]) => + elementsOf(markdownTree(markdown, options))[0]!; +// A user message's reading: a single `~` stays text. +const readUserBack = (markdown: string) => readBack(markdown, { singleTilde: false }); +const inline = (node: ElementContent) => + node.type === "element" ? [node.tagName, textOf(node)] : [node.type, textOf(node)]; const TEXT_NODE = 3; const ELEMENT_NODE = 1; @@ -223,10 +231,10 @@ describe("serializeRenderedMarkdownFragment", () => { new FakeText(" here."), ), ); - const paragraph = parseMarkdownWithMath(serializeRenderedMarkdownFragment(asNode(container))) - .children[0]; - if (paragraph?.type !== "paragraph") throw new Error("Expected a paragraph"); - expect(paragraph.children.find((child) => child.type === "inlineCode")?.value).toBe(value); + const paragraph = readBack(serializeRenderedMarkdownFragment(asNode(container))); + const code = elementsOf(paragraph).find((child) => child.tagName === "code"); + expect(paragraph.tagName).toBe("p"); + expect(code && textOf(code)).toBe(value); }); it.each([ @@ -238,28 +246,24 @@ describe("serializeRenderedMarkdownFragment", () => { String.raw`before\ after\ end`, ])("copies prose that parses back unchanged: %s", (value) => { const container = new FakeElement("DIV").append(new FakeText(value)); - const paragraph = userMarkdown.parse(serializeRenderedMarkdownFragment(asNode(container))) - .children[0]; - expect(paragraph).toMatchObject({ type: "paragraph", children: [{ type: "text", value }] }); + const paragraph = readUserBack(serializeRenderedMarkdownFragment(asNode(container))); + expect(paragraph.tagName).toBe("p"); + expect(paragraph.children.map(inline)).toEqual([["text", value]]); }); it.each([ - ["*", "EM", "word", "emphasis"], - ["\\", "CODE", "value", "inlineCode"], - ])("keeps a text edge %j beside %s", (edge, tag, value, type) => { + ["*", "EM", "word"], + ["\\", "CODE", "value"], + ])("keeps a text edge %j beside %s", (edge, tag, value) => { const container = new FakeElement("DIV").append( new FakeText(edge), new FakeElement(tag).append(new FakeText(value)), ); - const paragraph = userMarkdown.parse(serializeRenderedMarkdownFragment(asNode(container))) - .children[0]; - expect(paragraph).toMatchObject({ - type: "paragraph", - children: [ - { type: "text", value: edge }, - type === "inlineCode" ? { type, value } : { type, children: [{ type: "text", value }] }, - ], - }); + const paragraph = readUserBack(serializeRenderedMarkdownFragment(asNode(container))); + expect(paragraph.children.map(inline)).toEqual([ + ["text", edge], + [tag.toLowerCase(), value], + ]); }); it("copies email links with their address and drops in-app destinations", () => { @@ -288,10 +292,10 @@ describe("serializeRenderedMarkdownFragment", () => { expect(copied).toBe( "Write to support@example.com, [Support](mailto:support@example.com?subject=Help), [Support](mailto:support@example.com?subject=Help\\)) or the thread.", ); - const paragraph = parseMarkdownWithMath(copied).children[0]; - if (paragraph?.type !== "paragraph") throw new Error("Expected a paragraph"); expect( - paragraph.children.filter((child) => child.type === "link").map((link) => link.url), + elementsOf(readBack(copied)) + .filter((child) => child.tagName === "a") + .map((link) => link.properties.href), ).toEqual([ "mailto:support@example.com", "mailto:support@example.com?subject=Help", @@ -312,12 +316,14 @@ describe("serializeRenderedMarkdownFragment", () => { ])("keeps the link label and destination: %s", (label, href) => { const anchor = new FakeElement("A", [], { href }).append(new FakeText(label)); const container = new FakeElement("DIV").append(anchor); - const paragraph = userMarkdown.parse(serializeRenderedMarkdownFragment(asNode(container))) - .children[0]; - if (paragraph?.type !== "paragraph") throw new Error("Expected a paragraph"); - expect(paragraph.children).toMatchObject([ - { type: "link", url: href, children: [{ type: "text", value: label }] }, - ]); + const paragraph = readUserBack(serializeRenderedMarkdownFragment(asNode(container))); + expect( + paragraph.children.map((child) => + child.type === "element" + ? [child.tagName, decodeURI(String(child.properties.href)), textOf(child)] + : [child.type, textOf(child)], + ), + ).toEqual([["a", href, label]]); }); it("copies alert and insight callouts as their Markdown instead of the rendered label", () => { @@ -484,31 +490,25 @@ describe("copying rendered Markdown tables", () => { ); const markdown = serializeTableElementToMarkdown(table as unknown as Element); - const tree = parseMarkdownWithMath(markdown); - const parsed = tree.children[0]; - if (parsed?.type !== "table") throw new Error("Expected a table"); - expect(parsed.children.map((row) => row.children.length)).toEqual([2, 2, 2, 2, 2]); - expect(markdownMathRanges(markdown, tree).map((formula) => formula.tex)).toEqual([ - "|x|", - "\\|x\\|", - "|y|", - "|z|", - ]); - expect(parsed.children[1]?.children[1]?.children).toMatchObject([ - { type: "text", value: "*a* | ~~b~~" }, - ]); - expect(parsed.children[4]?.children[1]?.children).toMatchObject([ - { type: "text", value: "> c | d" }, - ]); - const [, , codeRow, linkRow] = parsed.children; - expect(codeRow?.children[1]?.children[0]).toMatchObject({ - type: "inlineCode", - value: "\\(c|d\\)", - }); - expect(linkRow?.children[0]?.children[0]).toMatchObject({ - type: "link", - url: "https://example.com/?q=a|b", - }); + const parsed = readBack(markdown, { math: true }); + expect(parsed.tagName).toBe("table"); + const rows = elementsOf(parsed).flatMap((section) => elementsOf(section)); + const cells = rows.map((row) => elementsOf(row)); + expect(cells.map((row) => row.length)).toEqual([2, 2, 2, 2, 2]); + const formulas: string[] = []; + const visit = (node: HastElement) => { + if (node.tagName === "svg") formulas.push(String(node.properties.ariaLabel)); + else elementsOf(node).forEach(visit); + }; + visit(parsed); + expect(formulas).toEqual(["|x|", "\\|x\\|", "|y|", "|z|"]); + expect(textOf(cells[1]![1]!)).toBe("*a* | ~~b~~"); + expect(textOf(cells[4]![1]!).trim()).toBe("> c | d"); + expect(inline(cells[2]![1]!.children[0]!)).toEqual(["code", "\\(c|d\\)"]); + const link = cells[3]![0]!.children[0]!; + expect(link.type === "element" && decodeURI(String(link.properties.href))).toBe( + "https://example.com/?q=a|b", + ); }); it("copies code and diagrams in cells without markers or unescaped pipes", () => { diff --git a/apps/web/src/markdown-clipboard.ts b/apps/web/src/markdown-clipboard.ts index 7421dbadd4bae..39ef90b2ec19a 100644 --- a/apps/web/src/markdown-clipboard.ts +++ b/apps/web/src/markdown-clipboard.ts @@ -1,4 +1,4 @@ -import { UNFINISHED_DRIVE_PATH } from "@t3tools/shared/markdownWindowsPaths"; +import { UNFINISHED_DRIVE_PATH } from "@t3tools/shared/markdownLinks"; const SKIPPED_TAGS = new Set(["BUTTON", "INPUT", "SCRIPT", "STYLE", "TEMPLATE"]); const SKIPPED_CLASS_NAMES = ["select-none", "sr-only"]; @@ -428,7 +428,7 @@ export function serializeTableElementToMarkdown(table: Element): string { return serializeTable(table).replaceAll(CODE_BOUNDARY, "").trim(); } -// The wrapper MarkdownMath puts on every formula it renders. The sanitizer drops +// The wrapper wordsHast puts on every formula it renders. The sanitizer drops // the attribute from authored HTML. const MATH_SELECTOR = "[data-markdown-math]"; diff --git a/apps/web/src/markdown-incremental.test.tsx b/apps/web/src/markdown-incremental.test.tsx deleted file mode 100644 index 3682deb281fa9..0000000000000 --- a/apps/web/src/markdown-incremental.test.tsx +++ /dev/null @@ -1,135 +0,0 @@ -import { CHAT_MARKDOWN_REHYPE_PLUGINS } from "@t3tools/shared/markdownPipeline"; -import type { Root } from "mdast"; -import { renderToStaticMarkup } from "react-dom/server"; -import ReactMarkdown from "react-markdown"; -import remarkGfm from "remark-gfm"; -import type { Plugin } from "unified"; -import { describe, expect, it } from "vite-plus/test"; - -import { remarkCodexDirectives } from "@t3tools/shared/codexMarkdownDirectives"; -import { remarkGithubAlerts } from "@t3tools/shared/markdownGithubAlerts"; -import { createIncrementalMarkdownPlugin } from "./markdown-incremental"; -import { remarkNormalizeListItemIndentation } from "@t3tools/shared/markdownListIndentation"; - -function render(source: string, incremental?: Plugin<[], Root>, parsedSources?: string[]) { - let tree: Root | undefined; - const observeParsing: Plugin<[], Root> = function () { - const original = this.parser; - if (original) { - this.parser = (text, file) => { - parsedSources?.push(text); - return original(text, file); - }; - } - }; - const capture: Plugin<[], Root> = () => (root) => { - tree = structuredClone(root); - }; - const html = renderToStaticMarkup( - - {source} - , - ); - return { html, tree }; -} - -const prefix = "# Before\n\n```ts\nconst values = [1, 2];\n```\n\n"; - -describe("incremental Markdown parsing", () => { - it("keeps the document prefix cached when list recovery parses contain fences", () => { - const source = - prefix + - "- first block\n\n ```ts\n const nested = 1;\n ```\n\n tail"; - const incremental = createIncrementalMarkdownPlugin(); - const parsedSources: string[] = []; - expect(render(source, incremental, parsedSources)).toEqual(render(source)); - parsedSources.length = 0; - const next = source + " more"; - expect(render(next, incremental, parsedSources)).toEqual(render(next)); - expect(parsedSources).not.toContain(next); - expect(parsedSources.some((text) => text.startsWith("t3-markdown-inline-prefix:"))).toBe(true); - }); - - it.each([ - "a\n===\n\nb\n---\n", - "- first\n\n continued\n\n- next\n", - "> quoted\n>\n> ```js\n> abc\n> ```\n\nend", - "
    \nhello\n\n
    \n\nend", - "[ref]\n\n[ref]: /later", - "a[^x]\n\n[^x]: note", - "a | b\n--|--\na | b\n", - "```\na\n```\n\nnext\n\n~~~\nb\n~~~\n\nmore", - "\n\n\tcode\n\nmore", - "text *bold*", - "> [!NOTE]\n> alert\n\n- [ ] task", - "\uFEFFtext after a byte-order mark", - ])("preserves the parse tree, positions, and HTML while streaming %j", (tail) => { - const source = prefix + tail; - const incremental = createIncrementalMarkdownPlugin(); - for (let end = 0; end <= source.length; end++) { - const text = source.slice(0, end); - expect(render(text, incremental), `prefix ${end}`).toEqual(render(text)); - } - }); - - it.each(["\r\n", "\r"])("preserves partial %j line endings", (newline) => { - const source = (prefix + "next\n\n```\nlast\n```\n\nend").replaceAll("\n", newline); - const incremental = createIncrementalMarkdownPlugin(); - for (let end = 0; end <= source.length; end++) { - const text = source.slice(0, end); - expect(render(text, incremental)).toEqual(render(text)); - } - }); - - it("updates earlier references when definitions arrive after the cached prefix", () => { - const before = "[later] and footnote[^note]\n\n" + prefix; - const incremental = createIncrementalMarkdownPlugin(); - for (const tail of ["text", "[later]: /target", "[later]: /target\n\n[^note]: a note"]) { - expect(render(before + tail, incremental)).toEqual(render(before + tail)); - } - }); - - it("handles edits, replacements, and repeated renders without leaking transformed nodes", () => { - const incremental = createIncrementalMarkdownPlugin(); - const documents = [ - prefix + "- first\n - second", - prefix + "> [!NOTE]\n> transformed alert", - prefix + "plain text", - "replacement without fences", - prefix.replace("Before", "Edited") + "edited prefix", - prefix + "plain text", - prefix + "plain text", - ]; - for (const document of documents) { - expect(render(document, incremental)).toEqual(render(document)); - } - }); - - it("does not freeze unclosed, nested, indented, or mismatched fences", () => { - const prefixes = [ - "```\nopen\n\n", - "````\n```\n\n", - "> ```\n> code\n> ```\n\n", - "- ```\n code\n ```\n\n", - " ```\n code\n ```\n\n", - " $y$', + { ...ASSISTANT, math: true }, + ), + ); + expect(html).not.toMatch(/onload|javascript|position| ReadonlyArray) | null; + }; + /** Expand GitHub `:alias:` emoji shortcodes in prose outside code. */ + readonly githubEmoji?: boolean; +} + +export interface WordsHastOptions { + /** `$…$`, `$$…$$` and `math` code blocks render as SVG. */ + readonly math: boolean; + /** Soft line breaks render as `
    `, as remark-breaks does. */ + readonly breaks: boolean; + /** Raw HTML shows as the text it was written as. */ + readonly escapeHtml: boolean; + /** `★ Insight ───` blocks render as insight callouts. */ + readonly insights: boolean; + readonly extensions: MarkdownExtensions; +} + +const CODEX_DIRECTIVES = ["codex-file-citation", "codex-followup", "artifact-template"]; + +const VOID = new Set("area base br col embed hr img input link meta source track wbr".split(" ")); + +const TAG = + /<(\/?)([a-zA-Z][\w:-]*)((?:\s+[^\s"'>/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'=<>`]+))?)*)\s*(\/?)>|)|]*>|<\?[\s\S]*?\?>/g; +const ATTRIBUTE = /([^\s"'>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g; + +// Start tags an HTML parser closes an open `

    ` for, and the elements that scope that search. +const CLOSES_PARAGRAPH = new Set( + "address article aside blockquote center details dialog dir div dl fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 header hgroup hr li listing main menu nav ol p plaintext pre search section summary table ul xmp dd dt".split( + " ", + ), +); +const PARAGRAPH_SCOPE = new Set([ + "applet", + "caption", + "table", + "td", + "th", + "marquee", + "object", + "template", + "button", +]); + +type RenderOptions = Omit; + +const decoder = new TextDecoder(); +const encoder = new TextEncoder(); + +function renderToHtml(markdown: string, options: RenderOptions): Uint8Array { + try { + return wordsRenderToHtml(markdown, options); + } catch { + return encoder.encode( + `

    ${markdown.replaceAll("&", "&").replaceAll("<", "<").replaceAll("\n", "
    ")}

    `, + ); + } +} + +const decode = (value: string) => (value.includes("&") ? decodeHTML(value) : value); + +function properties(source: string | undefined, inSvg: boolean): Element["properties"] { + const result: Element["properties"] = {}; + if (!source) return result; + for (const match of source.matchAll(ATTRIBUTE)) { + const name = match[1]!; + const info = find(inSvg ? svgSchema : htmlSchema, inSvg ? name : name.toLowerCase()); + const raw = match[2] ?? match[3] ?? match[4]; + if (raw === undefined) { + result[info.property] = info.boolean || info.overloadedBoolean ? true : ""; + continue; + } + // Attribute values decode as attributes: `©=` in a query stays as written. + const value = raw.includes("&") ? decodeHTMLAttribute(raw) : raw; + result[info.property] = + info.spaceSeparated || info.commaSeparated + ? value.split(info.commaSeparated ? "," : /\s+/).filter(Boolean) + : info.boolean + ? true + : value; + } + return result; +} + +interface Tokenized { + readonly root: Root; + /** Elements with a `data-sourcepos`, which raw HTML can write too. */ + readonly positioned: Element[]; +} + +/** + * Hast for Words' HTML. Its own markup is well formed; raw HTML closes where its end tags say, + * and is sanitized afterwards, so a misnested tag can only change structure, never safety. + */ +function tokenize(html: string, offsetOf: (byte: number) => number): Tokenized { + const root: Root = { type: "root", children: [] }; + const positioned: Element[] = []; + const stack: Array = [root]; + let svgDepth = 0; + let last = 0; + // rehypePreserveBareAnchorPlaceholders: an `
    ` with no attributes that never closes is text. + const anchors: Array<{ element: Element; parent: Root | Element; tag: string } | null> = []; + const text = (end: number) => { + if (end <= last) return; + const parent = stack.at(-1)!; + const value = decode(html.slice(last, end)); + const previous = parent.children.at(-1); + if (previous?.type === "text") previous.value += value; + else parent.children.push({ type: "text", value } as Text); + }; + for (const match of html.matchAll(TAG)) { + text(match.index); + last = match.index + match[0].length; + const tagName = match[2]?.toLowerCase(); + if (!tagName) continue; + if (match[1]) { + if (tagName === "a") anchors.pop(); + if (tagName === "p" && openParagraph(stack) < 0) { + // A stray `

    ` is an empty paragraph to an HTML parser. + (stack.at(-1)!.children as ElementContent[]).push({ + type: "element", + tagName: "p", + properties: {}, + children: [], + }); + continue; + } + const at = stack.findLastIndex((node) => node.type === "element" && node.tagName === tagName); + if (at > 0) { + for (let index = at; index < stack.length; index++) { + if ((stack[index] as Element).tagName === "svg") svgDepth--; + } + stack.length = at; + } + continue; + } + const inSvg = svgDepth > 0 || tagName === "svg"; + if (!inSvg && CLOSES_PARAGRAPH.has(tagName)) { + const paragraph = openParagraph(stack); + if (paragraph > 0) stack.length = paragraph; + } + const element: Element = { + type: "element", + tagName: inSvg ? match[2]! : tagName, + properties: properties(match[3], inSvg), + children: [], + }; + const sourcepos = element.properties.dataSourcepos; + if (typeof sourcepos === "string") { + delete element.properties.dataSourcepos; + const [start, end] = sourcepos.split("-").map((byte) => offsetOf(Number(byte))); + element.position = { + start: { line: 1, column: start! + 1, offset: start! }, + end: { line: 1, column: end! + 1, offset: end! }, + }; + positioned.push(element); + } + const parent = stack.at(-1)!; + (parent.children as ElementContent[]).push(element); + if (tagName === "a") { + anchors.push(match[3]?.trim() ? null : { element, parent, tag: match[0] }); + } + // The HTML parser ignores `/>` on elements that are not void, such as `
    `. + if (!VOID.has(tagName) && (!match[4] || !inSvg)) { + stack.push(element); + if (tagName === "svg") svgDepth++; + } + } + text(html.length); + for (const anchor of anchors) { + if (!anchor) continue; + const siblings = anchor.parent.children as ElementContent[]; + const at = siblings.indexOf(anchor.element); + if (at >= 0) + siblings.splice(at, 1, { type: "text", value: anchor.tag }, ...anchor.element.children); + } + normalizeRawTables(root); + // Words ends each block with a newline; hast from remark has none after the last. + const end = root.children.at(-1); + if (end?.type === "text") { + end.value = end.value.replace(/\n$/, ""); + if (end.value.trim() === "") root.children.pop(); + } + return { root, positioned }; +} + +const positionKey = (node: Element) => + `${node.tagName.toLowerCase()}:${node.position!.start.offset}-${node.position!.end.offset}`; + +/** + * Words' HTML for `markdown` as hast. A position marks what Words generated, so raw HTML that + * writes its own `data-sourcepos` keeps none: Words' elements are those it also writes with raw + * HTML escaped, and a range claimed more often than that is trusted for none of its claimants. + */ +function parse(markdown: string, options: RenderOptions): Root { + const offsetOf = utf16Offsets(markdown); + const render = (escapeHtml?: true) => + tokenize( + decoder.decode( + renderToHtml(markdown, { + ...options, + ...(escapeHtml ? { escapeHtml } : {}), + sourcePositions: true, + }), + ), + offsetOf, + ); + const { root, positioned } = render(); + if (options.escapeHtml || options.skipHtml || !/data-sourcepos/i.test(markdown)) return root; + const generated = new Map(); + for (const node of render(true).positioned) { + const key = positionKey(node); + generated.set(key, (generated.get(key) ?? 0) + 1); + } + const claimed = new Map(); + for (const node of positioned) { + const key = positionKey(node); + claimed.set(key, (claimed.get(key) ?? 0) + 1); + } + for (const node of positioned) { + const key = positionKey(node); + if (claimed.get(key)! > (generated.get(key) ?? 0)) delete node.position; + } + return root; +} + +/** The stack index of the `

    ` an HTML parser would close, or -1 when none is in scope. */ +function openParagraph(stack: ReadonlyArray): number { + for (let index = stack.length - 1; index > 0; index--) { + const tagName = (stack[index] as Element).tagName; + if (tagName === "p") return index; + if (PARAGRAPH_SCOPE.has(tagName)) return -1; + } + return -1; +} + +/** parse5 puts a raw HTML table's rows in a ``; Words' own tables start with ``. */ +function normalizeRawTables(node: Root | Element) { + for (const child of node.children) { + if (child.type === "element") normalizeRawTables(child); + } + if (node.type !== "element" || node.tagName !== "table") return; + const first = node.children.findIndex((child) => isElement(child, "tr")); + if (first < 0) return; + node.children = [ + ...node.children.slice(0, first), + { type: "element", tagName: "tbody", properties: {}, children: node.children.slice(first) }, + ]; +} + +// Words leaves these raw in Markdown destinations, where micromark percent-encodes them. +const UNSAFE_URL_CHARACTERS = /[\\[\]`{}|^"<> ]/g; +const normalizeUri = (value: string) => + value.replace(UNSAFE_URL_CHARACTERS, (character) => encodeURIComponent(character)); + +const windowsPath = (url: string) => { + const path = url.replace(/%5C/gi, "\\"); + return /^[A-Za-z]:[\\/]/.test(path) ? path : undefined; +}; + +const isElement = (node: unknown, tagName?: string): node is Element => + (node as Element | undefined)?.type === "element" && + (tagName === undefined || (node as Element).tagName === tagName); + +const isElementNode = (node: ElementContent): node is Element => node.type === "element"; + +const isMarkdownImage = (node: unknown): boolean => + (isElement(node, "img") && node.position !== undefined) || + (isElement(node, "a") && + node.position !== undefined && + node.children.length === 1 && + isMarkdownImage(node.children[0])); + +const BREAK: ElementContent = { type: "element", tagName: "br", properties: {}, children: [] }; + +// Words' math: these elements and presentation attributes, and no links or handlers. +const MATH_ELEMENTS = new Set(["svg", "g", "text", "tspan", "rect", "path"]); +const MATH_PROPERTIES = new Set([ + "xmlns", + "width", + "height", + "viewBox", + "fill", + "fontFamily", + "fontSize", + "fontStyle", + "fontWeight", + "role", + "ariaLabel", + "x", + "y", + "dx", + "dy", + "d", + "transform", + "stroke", + "strokeWidth", + "textAnchor", +]); +const MATH_STYLE = /^(?:display|vertical-align|overflow|margin|white-space)$/; + +function sanitizeMath(node: Element): Element | null { + if (!MATH_ELEMENTS.has(node.tagName)) return null; + const properties: Element["properties"] = {}; + for (const [key, value] of Object.entries(node.properties)) { + if (MATH_PROPERTIES.has(key)) properties[key] = value; + } + if (typeof node.properties.style === "string") { + const style = node.properties.style + .split(";") + .filter((rule) => MATH_STYLE.test(rule.split(":")[0]!.trim())) + .join(";"); + if (style) properties.style = style; + } + const children: ElementContent[] = []; + for (const child of node.children) { + if (child.type === "text") children.push(child); + else if (child.type === "element") { + const clean = sanitizeMath(child); + if (clean) children.push(clean); + } + } + return { ...node, properties, children }; +} + +interface Walk { + /** Words' hast for more Markdown, rendered with the same options; `indent` as leadingWhitespace's. */ + readonly render: (markdown: string, indent: number) => Root; + readonly source: string; + readonly options: WordsHastOptions; + readonly math: Map; + /** A per-render id prefix for math placeholders, which authored ids cannot share. */ + readonly mathKey: string; + /** What insightSource opened each insight block with, when it opened any. */ + readonly insightMarker: RegExp | null; +} + +/** UTF-16 offsets for the UTF-8 byte offsets in Words' `data-sourcepos`. */ +function utf16Offsets(source: string): (byte: number) => number { + if (!/[^\x00-\x7f]/.test(source)) return (byte) => byte; + const offsets: number[] = []; + for (let index = 0; index < source.length; index++) { + const code = source.codePointAt(index)!; + const bytes = code < 0x80 ? 1 : code < 0x800 ? 2 : code < 0x10000 ? 3 : 4; + for (let byte = 0; byte < bytes; byte++) offsets.push(index); + if (code >= 0x10000) index++; + } + offsets.push(source.length); + return (byte) => offsets[byte] ?? source.length; +} + +const sourceOf = (node: Element, source: string) => + node.position ? source.slice(node.position.start.offset, node.position.end.offset) : ""; + +const textOf = (node: ElementContent): string => + node.type === "text" + ? node.value + : node.type === "element" + ? node.children.map(textOf).join("") + : ""; + +/** A directive's attributes, as strings; anything else Words would never write reads as none. */ +function directiveAttributes(node: Element): Record { + let parsed: unknown; + try { + parsed = JSON.parse(String(node.properties.dataAttributes ?? "{}")); + } catch { + return {}; + } + if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return {}; + return Object.fromEntries( + Object.entries(parsed).filter( + (entry): entry is [string, string] => typeof entry[1] === "string", + ), + ); +} + +/** remarkCodexDirectives: what a directive Words parsed becomes, as the remark plugin builds it. */ +function codexDirective(node: Element, walk: Walk, inLink: boolean): ElementContent { + const name = node.properties.dataDirective; + const attributes = directiveAttributes(node); + const asText = (): ElementContent => { + const value: ElementContent = { type: "text", value: sourceOf(node, walk.source) }; + return node.tagName === "div" + ? { type: "element", tagName: "p", properties: {}, children: [value] } + : value; + }; + if (name === "codex-file-citation") { + const citation = resolveCodexFileCitationLink(attributes); + if (!citation || inLink) return asText(); + return { + type: "element", + tagName: "a", + properties: { href: citation.href }, + children: [{ type: "text", value: citation.label }], + ...(node.position ? { position: node.position } : {}), + }; + } + if (name === "codex-followup") { + if (!attributes.prompt?.trim() || !node.children.map(textOf).join("").trim()) return asText(); + return { type: "element", tagName: "span", properties: {}, children: node.children }; + } + const template = resolveCodexArtifactTemplate(attributes); + if (!template) return asText(); + return { + type: "element", + tagName: "div", + properties: { + dataCodexArtifactTemplate: "true", + dataArtifactKind: template.artifactKind, + dataDisplayName: template.displayName, + ...(template.galleryKind === undefined ? {} : { dataGalleryKind: template.galleryKind }), + dataSkillDirectory: template.skillDirectory, + dataSkillName: template.skillName, + }, + children: [], + }; +} + +const INLINE_PREFIX = "t3-markdown-inline-prefix:"; + +function stripPositions(node: ElementContent) { + delete node.position; + if (node.type === "element") node.children.forEach(stripPositions); +} + +/** + * remarkNormalizeListItemIndentation: four spaces after a list marker make indented code, but + * agents mean wide indentation, so code starting on the marker's line is Markdown again. True + * when it recovered the item, whose children it then has transformed. + */ +function recoverIndentedCode( + item: Element, + list: Root | Element, + walk: Walk, + inLink: boolean, + inCode: boolean, +): boolean { + const code = item.children.find((child) => child.type === "element"); + const start = code?.position?.start.offset; + const itemStart = item.position?.start.offset; + if (!isElement(code, "pre") || start === undefined || itemStart === undefined) return false; + const value = textOf(code); + if (!/^[\t ]/.test(value)) return false; + if (walk.source.slice(itemStart, start).includes("\n") || /[`~]/.test(walk.source[start]!)) { + return false; + } + // The trimmed first line sets where the item's content starts. + const indent = [.../^[\t ]*/.exec(value)![0]].reduce( + (column, character) => (character === "\t" ? (Math.floor(column / 4) + 1) * 4 : column + 1), + 0, + ); + // The prefix keeps block syntax at the start, such as `#`, from opening a block. + const source = `${INLINE_PREFIX}${value.trim()}`; + const recovered = walk.render(source, indent); + const paragraph = recovered.children.find((child) => child.type === "element"); + const first = isElement(paragraph, "p") ? paragraph.children[0] : undefined; + if (first?.type !== "text" || !first.value.startsWith(INLINE_PREFIX)) return false; + first.value = first.value.slice(INLINE_PREFIX.length); + if (first.value === "") paragraph!.children.shift(); + transform(recovered, { ...walk, source }, inLink, inCode); + transform(item, walk, inLink, inCode); + let blocks = recovered.children.filter( + (child) => !(child.type === "text" && child.value.trim() === ""), + ) as ElementContent[]; + // Their positions point into `source`, not the message. + blocks.forEach(stripPositions); + let at = item.children.indexOf(code); + let remove = 1; + if (!isLooseList(list, walk.source)) { + // A tight item shows its text bare, as remark-rehype unwraps its paragraphs. + blocks = blocks.flatMap((block, index) => [ + ...(index > 0 ? [{ type: "text", value: "\n" } as Text] : []), + ...(isElement(block, "p") ? block.children : [block]), + ]); + const isBlank = (node: ElementContent | undefined) => + node?.type === "text" && node.value.trim() === ""; + if (at === 1 && isBlank(item.children[0])) [at, remove] = [0, 2]; + if (at + remove === item.children.length - 1 && isBlank(item.children.at(-1))) remove++; + } + item.children.splice(at, remove, ...blocks); + return true; +} + +/** remark-rehype's listLoose: a blank line between items, or an item Words wrote as paragraphs. */ +function isLooseList(list: Root | Element, source: string): boolean { + const items = (list.children as ElementContent[]).filter((child): child is Element => + isElement(child, "li"), + ); + return items.some( + (item, index) => + item.children.some((child) => isElement(child, "p")) || + (index > 0 && + /\n[ \t>]*\n/.test( + source.slice( + items[index - 1]!.position?.end.offset ?? 0, + item.position?.start.offset ?? 0, + ), + )), + ); +} + +const WRITTEN_NUMBER = /[ \t]*(\d{1,9})[.)]/y; + +function keepListNumbers(list: Element, source: string) { + let expected = Number(list.properties.start ?? 1); + for (const item of list.children) { + if (!isElement(item, "li")) continue; + const offset = item.position?.start.offset; + WRITTEN_NUMBER.lastIndex = offset ?? 0; + const digits = offset === undefined ? undefined : WRITTEN_NUMBER.exec(source)?.[1]; + const value = digits === undefined ? expected : Number(digits); + if (value !== expected) item.properties.value = String(value); + expected = value + 1; + } +} + +/** What the chat's remark plugins add that Words does not. */ +const link = (href: string, label: string, properties: Element["properties"] = {}): Element => ({ + type: "element", + tagName: "a", + properties: { href, ...properties }, + children: [{ type: "text", value: label }], +}); + +/** Links in text: absolute file paths (remarkLinkAbsoluteFilePaths), then a change request's references. */ +function linkText(value: string, walk: Walk): ElementContent[] | null { + let parts: ElementContent[] = []; + let offset = 0; + for (const { index, path } of absoluteFilePathMatches(value)) { + if (index > offset) parts.push({ type: "text", value: value.slice(offset, index) }); + parts.push(link(path, path)); + offset = index + path.length; + } + if (offset < value.length) parts.push({ type: "text", value: value.slice(offset) }); + const autolinks = walk.options.extensions.changeRequest?.autolinks; + if (autolinks) { + parts = parts.flatMap((part) => { + if (part.type !== "text") return [part]; + const found = autolinks(part.value); + if (found.length === 0) return [part]; + const linked: ElementContent[] = []; + let start = 0; + for (const reference of found) { + if (start < reference.index) { + linked.push({ type: "text", value: part.value.slice(start, reference.index) }); + } + linked.push( + link(reference.url, reference.label, { dataPullRequestAutolink: reference.kind }), + ); + start = reference.index + reference.text.length; + } + if (start < part.value.length) linked.push({ type: "text", value: part.value.slice(start) }); + return linked; + }); + } + return parts.length === 1 && parts[0]!.type === "text" ? null : parts; +} + +function transform(node: Root | Element, walk: Walk, inLink: boolean, inCode: boolean) { + const children = node.children as ElementContent[]; + for (let index = 0; index < children.length; index++) { + const child = children[index]!; + if (child.type === "text") { + if (inCode) continue; + if (walk.options.extensions.githubEmoji && child.value.includes(":")) { + child.value = expandGithubEmojiAliases(child.value); + } + if (inLink) continue; + const parts = linkText(child.value, walk); + if (!parts) continue; + children.splice(index, 1, ...parts); + index += parts.length - 1; + continue; + } + if (child.type !== "element") continue; + // Words gives what it generates a source position; raw HTML that copies its attributes has none. + if (child.properties.dataDirective !== undefined && child.position) { + children[index] = codexDirective(child, walk, inLink); + index--; + continue; + } + const { tagName, properties: props } = child; + if (tagName === "svg") { + // Sanitizing drops SVG, so math waits under a placeholder until after it. + const clean = walk.options.math && child.position ? sanitizeMath(child) : null; + if (clean) { + const key = `${walk.mathKey}-${walk.math.size}`; + walk.math.set(key, clean); + children[index] = { + type: "element", + tagName: "span", + properties: { id: key }, + children: [], + }; + } + continue; + } + if (tagName === "a" && props.dataFootnoteRef !== undefined) { + // remark-rehype's footnote markup, before rehype-sanitize prefixes ids again. + props.href = `#user-content-${String(props.href).slice(1)}`; + props.id = `user-content-${String(props.id)}`; + props.ariaDescribedBy = ["footnote-label"]; + } else if (tagName === "a" && props.dataFootnoteBackref !== undefined) { + const { href, ariaLabel } = props; + child.properties = { + href: `#user-content-${String(href).slice(1)}`, + dataFootnoteBackref: "", + ariaLabel, + className: ["data-footnote-backref"], + }; + } else if (tagName === "li" && typeof props.id === "string" && props.id.startsWith("fn-")) { + props.id = `user-content-${props.id}`; + } else if (tagName === "section" && props.dataFootnotes !== undefined) { + child.properties = { dataFootnotes: "", className: ["footnotes"] }; + child.children.unshift({ + type: "element", + tagName: "h2", + properties: { className: ["sr-only"], id: "footnote-label" }, + children: [{ type: "text", value: "Footnotes" }], + }); + } else if (tagName === "a" && typeof props.href === "string") { + // remarkNormalizeLinksAndTagInlineCode: a Windows drive path links as a file URL. + const path = windowsPath(props.href); + props.href = path ? `file:///${path.replaceAll("\\", "/")}` : normalizeUri(props.href); + } else if (tagName === "img" && typeof props.src === "string") { + const changeRequest = walk.options.extensions.changeRequest; + const src = changeRequest + ? resolveChangeRequestMediaUrl(props.src, changeRequest.repositoryUrl) + : props.src; + props.src = windowsPath(src) ?? normalizeUri(src); + } else if (tagName === "code" && isElement(node, "pre")) { + if (props.dataMeta !== undefined) { + props.dataCodeMeta = props.dataMeta; + delete props.dataMeta; + } + } else if (tagName === "code" && !inLink) { + props.dataInlineCode = ""; + } else if (tagName === "ol" && walk.options.extensions.userMessage) { + keepListNumbers(child, walk.source); + } else if (tagName === "li") { + const firstBlock = child.children.find(isElementNode); + if (isElement(firstBlock, "pre") && recoverIndentedCode(child, node, walk, inLink, inCode)) { + continue; + } + // Tight items put the checkbox directly in `

  • `, loose ones inside its first `

    `. + const checkbox = isElement(child.children[0], "input") + ? child.children[0] + : isElement(firstBlock, "p") && isElement(firstBlock.children[0], "input") + ? firstBlock.children[0] + : undefined; + if (checkbox) { + props.className = ["task-list-item"]; + const { checked } = checkbox.properties; + checkbox.properties = { type: "checkbox", checked, disabled: true }; + if (node.type === "element") node.properties.className = ["contains-task-list"]; + } + breakLines(child, walk.options.breaks); + } else if (tagName === "p") { + breakLines(child, walk.options.breaks); + } else if (tagName === "blockquote") { + // remarkGithubAlerts + const paragraph = child.children.find((item) => item.type === "element"); + const first = isElement(paragraph, "p") ? paragraph.children[0] : undefined; + const text = first?.type === "text" ? first.value : ""; + const insight = walk.insightMarker?.exec(text); + const alert = GITHUB_ALERT_MARKER.exec(text); + // An alert marker followed by more inline content on its line is text, as remarkGithubAlerts reads it. + const match = insight + ? ([insight[0], "insight"] as const) + : alert && (alert[0].endsWith("\n") || (paragraph as Element).children.length === 1) + ? alert + : null; + if (match && first?.type === "text" && isElement(paragraph, "p")) { + first.value = first.value.slice(match[0].length); + if (first.value === "") paragraph.children.shift(); + if (paragraph.children.length === 0) { + const at = child.children.indexOf(paragraph); + const next = child.children[at + 1]; + // The line ending after it goes too, as remark leaves none for a removed paragraph. + const blank = next?.type === "text" && next.value.trim() === "" ? 2 : 1; + child.children.splice(at, blank); + } + props.dataAlert = match[1]!.toLowerCase(); + } + } + transform( + child, + walk, + inLink || tagName === "a", + inCode || tagName === "code" || tagName === "pre", + ); + } +} + +/** + * remark-breaks puts a `
    ` before every soft line ending, and remarkBreakAroundImageLines + * before those next to a Markdown image. Both keep the line ending after it. + */ +/** A Markdown image alone on its line: nothing but a line ending (or the paragraph's edge) around it. */ +function imageOwnsLine(items: ElementContent[], at: number): boolean { + if (!isMarkdownImage(items[at])) return false; + const before = items[at - 1]; + const after = items[at + 1]; + const startsLine = + before === undefined || + (before.type === "text" && /\n[ \t]*$/.test(before.value)) || + isElement(before, "br"); + const endsLine = after === undefined || (after.type === "text" && /^[ \t]*\n/.test(after.value)); + return startsLine && endsLine; +} + +const isBlockElement = (node: ElementContent | undefined) => + node?.type === "element" && CLOSES_PARAGRAPH.has(node.tagName); + +function breakLines(paragraph: Element, breaks: boolean) { + const items = paragraph.children; + for (let at = 0; at < items.length; at++) { + const item = items[at]!; + if ( + item.type === "element" && + breaks && + item.tagName !== "code" && + !CLOSES_PARAGRAPH.has(item.tagName) + ) { + breakLines(item, breaks); + } + if (item.type !== "text" || !item.value.includes("\n")) continue; + const afterImage = imageOwnsLine(items, at - 1); + const beforeImage = imageOwnsLine(items, at + 1); + const afterBlock = isBlockElement(items[at - 1]) || (at === 0 && paragraph.tagName === "li"); + const beforeBlock = + isBlockElement(items[at + 1]) || (at === items.length - 1 && paragraph.tagName === "li"); + const lines = item.value.split("\n"); + const parts: ElementContent[] = []; + lines.forEach((line, index) => { + // A hard break's own line ending follows its
    , and adds no second one; + // structural line endings around a list item's block children stay breaks between blocks. + const afterHardBreak = index === 1 && isElement(items[at - 1], "br"); + const blockBoundary = + (index === 1 && lines[0] === "" && afterBlock) || + (index === lines.length - 1 && line === "" && beforeBlock); + const breaksHere = + index > 0 && + !afterHardBreak && + !blockBoundary && + (breaks || (index === 1 && afterImage) || (index === lines.length - 1 && beforeImage)); + if (index > 0) { + if (breaksHere) { + const previous = parts.at(-1); + if (previous?.type === "text") previous.value = previous.value.replace(/[ \t]+$/, ""); + parts.push(BREAK); + } + parts.push({ type: "text", value: `\n${line}` }); + } else if (line) { + parts.push({ type: "text", value: line }); + } + }); + // Rejoin text that did not break, so the tree matches remark's text nodes. + const merged: ElementContent[] = []; + for (const part of parts) { + const previous = merged.at(-1); + if (part.type === "text" && previous?.type === "text") previous.value += part.value; + else merged.push(part); + } + items.splice(at, 1, ...merged); + at += merged.length - 1; + } +} + +/** + * The wrapper copying reads (markdown-clipboard's MATH_SELECTOR): the formula's TeX, as the source + * Words drew it from, so copying any part of a formula copies the whole of it. + */ +// A formula wider than its block scrolls, with room for the glyphs that reach past its box; in a +// table it keeps its width and the table scrolls. +const MATH_SCROLL = [ + "max-w-full", + "overflow-x-auto", + "overflow-y-hidden", + "px-0.5", + "py-0.75", + "in-[.chat-markdown-table-container]:max-w-none", + "in-[.chat-markdown-table-container]:overflow-visible", +]; + +function mathWrapper(svg: Element): Element { + const tex = String(svg.properties.ariaLabel ?? "").trim(); + const display = /display:\s*block/.test(String(svg.properties.style ?? "")); + return { + type: "element", + tagName: "span", + properties: display + ? { + className: ["chat-markdown-math-display", "block", ...MATH_SCROLL], + dataMarkdownMath: "display", + dataMarkdownCopy: `\\[\n${tex}\n\\]\n\n`, + } + : { + className: ["inline-block", "align-middle", ...MATH_SCROLL], + dataMarkdownMath: "inline", + dataMarkdownCopy: `\\(${tex}\\)`, + }, + children: [svg], + }; +} + +function restoreMath(node: Root | Element, math: Map) { + const children = node.children as ElementContent[]; + for (let index = 0; index < children.length; index++) { + const child = children[index]!; + if (child.type !== "element") continue; + const id = child.properties.id; + const svg = typeof id === "string" ? math.get(id.replace(/^user-content-/, "")) : undefined; + if (svg) children[index] = mathWrapper(svg); + else restoreMath(child, math); + } +} + +const addHeadingIds = rehypeHeadingIds(); +const addTextDirection = rehypeTextDirection(); +const preserveImageSourceMeta = rehypePreserveImageSourceMeta(); +const normalizeLocalEditorLinks = rehypeNormalizeLocalEditorLinks(); +const groupChipPunctuation = rehypeChipPunctuation(); + +const INSIGHT_OPENING = /^( {0,3})(`?)★ Insight[ \t]+─{3,}\2[ \t]*$/u; +const INSIGHT_CLOSING = /^( {0,3})(`?)─{3,}\2[ \t]*$/u; + +interface InsightSource { + readonly source: string; + readonly tree: Root; + readonly marker: RegExp; + /** The offset in the message for an offset in `source`. */ + readonly toOriginal: (offset: number) => number; +} + +/** + * remarkAssistantInsights: a `★ Insight ───` line opens a quoted insight block, which a `───` line + * at the same indentation closes; the end of the text closes one that never does. Lines in code + * neither open nor close one, and an opening Words does not read as a quote's first line, as in + * an HTML block or a quote's lazy line, stays text. + */ +function insightSource(text: string, options: RenderOptions): InsightSource | null { + if (!text.includes("★ Insight")) return null; + const code: Array = []; + const findCode = (node: Root | Element) => { + for (const child of node.children) { + if (child.type !== "element") continue; + if (child.tagName === "pre" && child.position) { + code.push([child.position.start.offset!, child.position.end.offset!]); + } else findCode(child); + } + }; + findCode(parse(text, options)); + const nonce = Math.random().toString(36).slice(2); + const marker = new RegExp(String.raw`^\[!T3-INSIGHT-${nonce}-(\d+)\](?:\r?\n)?`); + const anywhere = new RegExp(String.raw`\[!T3-INSIGHT-${nonce}-(\d+)\]`, "g"); + const lines = text.split(/(?<=\n)/u); + const skipped = new Set(); + for (;;) { + // Each line's offset in the message and in the source, and how much longer it got. + const offsets: Array<{ original: number; source: number; length: number; delta: number }> = []; + let original = 0; + let rewritten = 0; + let opened = 0; + let indent: string | undefined; + const source = lines + .map((line, lineIndex) => { + const value = line.replace(/[\r\n]+$/u, ""); + const ending = line.slice(value.length); + const inCode = code.some(([start, end]) => original >= start && original < end); + let output = line; + if (indent === undefined) { + const opening = inCode ? null : INSIGHT_OPENING.exec(value); + if (opening && !skipped.has(lineIndex)) { + indent = opening[1] ?? ""; + opened++; + output = `> [!T3-INSIGHT-${nonce}-${lineIndex}]${ending}`; + } + } else { + const closing = inCode ? null : INSIGHT_CLOSING.exec(value); + if (closing && closing[1] === indent) { + indent = undefined; + output = ending; + } else output = `> ${line}`; + } + offsets.push({ + original, + source: rewritten, + length: line.length, + delta: output.length - line.length, + }); + original += line.length; + rewritten += output.length; + return output; + }) + .join(""); + if (opened === 0) return null; + const tree = parse(source, options); + let stranded = false; + const visit = (node: Root | Element, quoteStart: Text | undefined) => { + for (const child of node.children) { + if (child.type === "text") { + for (const found of child.value.matchAll(anywhere)) { + if (child === quoteStart && found.index === 0) continue; + skipped.add(Number(found[1])); + stranded = true; + } + } else if (child.type === "element") { + const paragraph = + child.tagName === "blockquote" ? child.children.find(isElementNode) : undefined; + const first = isElement(paragraph, "p") ? paragraph.children[0] : undefined; + visit(child, first?.type === "text" ? first : quoteStart); + } + } + }; + visit(tree, undefined); + if (stranded) continue; + return { + source, + tree, + marker, + toOriginal: (offset) => { + const line = offsets.findLast((entry) => entry.source <= offset) ?? offsets[0]!; + return ( + line.original + Math.min(Math.max(offset - line.source - line.delta, 0), line.length) + ); + }, + }; + } +} + +/** Positions that point into an insight's rewritten source, moved back into the message. */ +function restorePositions(node: Root | Element, toOriginal: (offset: number) => number) { + for (const child of node.children) { + if (child.type !== "element") continue; + if (child.position) { + const start = toOriginal(child.position.start.offset!); + const end = toOriginal(child.position.end.offset!); + child.position = { + start: { line: 1, column: start + 1, offset: start }, + end: { line: 1, column: end + 1, offset: end }, + }; + } + restorePositions(child, toOriginal); + } +} + +const PREVIEW_SEPARATED = new Set([ + "blockquote", + "ul", + "ol", + "li", + "table", + "thead", + "tbody", + "tr", +]); + +/** remarkThoughtPreview: the message as one line of text, keeping math, cut at `maxLength`. */ +function flattenPreview(tree: Root, preview: NonNullable): Root { + const children: ElementContent[] = []; + let remaining = preview.maxLength; + let fragments: string[] = []; + const flush = () => { + if (fragments.length === 0) return; + children.push({ type: "text", value: fragments.join("").replace(/\s+/g, " ") }); + fragments = []; + }; + const take = (value: string) => { + const text = value.slice(0, remaining); + remaining = text.length < value.length ? 0 : remaining - text.length; + // A cut must not leave half a surrogate pair. + return text.replace(/[\uD800-\uDBFF]$/, ""); + }; + const visit = (node: Root | ElementContent) => { + if (remaining === 0) return; + if (node.type === "text") { + fragments.push(take(node.value)); + return; + } + if (node.type === "element" && node.properties.dataMarkdownMath !== undefined) { + flush(); + // One line has no room for display math, which a preview shows inline. + const svg = node.children[0]; + children.push( + node.properties.dataMarkdownMath === "display" && svg?.type === "element" + ? mathWrapper({ + ...svg, + properties: { + ...svg.properties, + style: "display:inline;vertical-align:middle;overflow:visible", + }, + }) + : node, + ); + return; + } + if (node.type === "element" && node.tagName === "img") { + fragments.push(take(String(node.properties.alt ?? ""))); + return; + } + if (node.type === "element" && node.tagName === "br") { + fragments.push(take(" ")); + return; + } + if (node.type !== "root" && node.type !== "element") return; + const separates = node.type === "root" || PREVIEW_SEPARATED.has(node.tagName); + let first = true; + for (const child of node.children as ElementContent[]) { + if (remaining === 0) break; + if (child.type === "text" && child.value.trim() === "" && separates) continue; + if (!first && separates) fragments.push(take(" ")); + first = false; + visit(child); + } + }; + visit(tree); + flush(); + const head = children[0]; + const tail = children.at(-1); + if (head?.type === "text") head.value = head.value.trimStart(); + if (tail?.type === "text") tail.value = tail.value.trimEnd(); + const visible = children.some((child) => child.type !== "text" || child.value); + return { + type: "root", + children: visible ? children : [{ type: "text", value: preview.fallback }], + }; +} + +/** Links become their text, images their alt text, inline code plain text, Mermaid plain code. */ +function makeInert(node: Root | Element) { + const children = node.children as ElementContent[]; + for (let index = 0; index < children.length; index++) { + const child = children[index]!; + if (child.type !== "element") continue; + if (child.tagName === "a") { + children.splice(index, 1, ...child.children); + index--; + continue; + } + if (child.tagName === "img") { + children[index] = { type: "text", value: String(child.properties.alt ?? "") }; + continue; + } + if (child.tagName === "code" && child.properties.dataInlineCode !== undefined) { + children[index] = { type: "text", value: textOf(child) }; + continue; + } + if ( + child.tagName === "code" && + String(child.properties.className ?? "").includes("language-mermaid") + ) { + child.properties.className = ["language-text"]; + } + makeInert(child); + } +} + +/** ChatMarkdown's sanitized hast for `text`, rendered by Words. */ +export function wordsHast(text: string, options: WordsHastOptions): Root { + const { extensions } = options; + const renderOptions: RenderOptions = { + math: options.math, + // llm-math's `\(…\)` and `\[…\]`, which agents write as often as `$`. + texDelimiters: options.math, + autolinkBoundaries: true, + singleTilde: !extensions.userMessage, + leadingWhitespace: extensions.leadingWhitespace === true, + windowsPaths: true, + codeMeta: true, + directives: CODEX_DIRECTIVES, + // Previews and inert Markdown drop raw HTML, as their remark plugins dropped html nodes. + ...(extensions.preview || extensions.inert + ? { skipHtml: true } + : { escapeHtml: options.escapeHtml }), + }; + const insights = options.insights ? insightSource(text, renderOptions) : null; + const source = insights?.source ?? text; + const tree = insights?.tree ?? parse(source, renderOptions); + const walk: Walk = { + render: (markdown, indent) => + parse(markdown, { + ...renderOptions, + leadingWhitespace: extensions.leadingWhitespace === true && { indent }, + }), + source, + options, + math: new Map(), + mathKey: `t3-math-${Math.random().toString(36).slice(2)}`, + insightMarker: insights?.marker ?? null, + }; + transform(tree, walk, false, false); + preserveImageSourceMeta(tree as never); + normalizeLocalEditorLinks(tree as never); + const hast = sanitizeChatHast(tree); + if (walk.math.size > 0) restoreMath(hast, walk.math); + if (insights) restorePositions(hast, insights.toOriginal); + if (extensions.inert) makeInert(hast); + if (extensions.preview) return flattenPreview(hast, extensions.preview); + addHeadingIds(hast); + addTextDirection(hast as never); + groupChipPunctuation(hast as never); + return hast; +} + +export interface CodexDirectiveSource { + readonly name: string; + readonly attributes: Record; + /** UTF-16 offsets of the whole directive in the source. */ + readonly start: number; + readonly end: number; + /** The label's text as written. */ + readonly label: string; + /** Inside a link, where a file citation stays text. */ + readonly inLink: boolean; +} + +/** The Codex directives in `markdown`, as Words reads them. */ +export function codexDirectiveSources(markdown: string): CodexDirectiveSource[] { + const found: CodexDirectiveSource[] = []; + const visit = (node: Root | Element, inLink: boolean) => { + for (const child of node.children) { + if (child.type !== "element") continue; + const name = child.properties.dataDirective; + if (typeof name === "string" && child.position) { + const { start, end } = child.position; + found.push({ + name, + attributes: directiveAttributes(child), + start: start.offset!, + end: end.offset!, + label: directiveLabel(markdown.slice(start.offset, end.offset)), + inLink, + }); + } + visit(child, inLink || child.tagName === "a"); + } + }; + visit( + parse(markdown, { + windowsPaths: true, + autolinkBoundaries: true, + directives: CODEX_DIRECTIVES, + }), + false, + ); + return found; +} + +/** The label of a directive as written, `:name[label]{…}`: brackets nest in it, and `\` escapes. */ +function directiveLabel(written: string): string { + const open = written.indexOf("["); + if (open < 0) return ""; + let depth = 0; + for (let index = open; index < written.length; index++) { + const character = written[index]; + if (character === "\\") index++; + else if (character === "[") depth++; + else if (character === "]" && --depth === 0) return written.slice(open + 1, index); + } + return ""; +} + +/** + * Words' HTML for `markdown` as hast, unsanitized and without the chat's additions. Code blocks, + * links, list items and math carry source positions. + */ +export function markdownTree( + markdown: string, + options: { skipHtml?: boolean; singleTilde?: boolean; math?: boolean } = {}, +): Root { + return parse(markdown, { + windowsPaths: true, + autolinkBoundaries: true, + skipHtml: options.skipHtml === true, + singleTilde: options.singleTilde !== false, + math: options.math === true, + texDelimiters: options.math === true, + }); +} + +/** The formulas Words reads in `text`, as source offsets, for editors that keep math as source. */ +export function markdownMathRanges(text: string): Array<{ start: number; end: number }> { + if (!/[$\\]|(?:`{3,}|~{3,})[ \t]*math\b/.test(text)) return []; + const ranges: Array<{ start: number; end: number }> = []; + const visit = (node: Root | Element) => { + for (const child of node.children) { + if (child.type !== "element") continue; + if (child.tagName === "svg") { + if (child.position) { + ranges.push({ start: child.position.start.offset!, end: child.position.end.offset! }); + } + continue; + } + visit(child); + } + }; + visit(parse(text, { math: true, texDelimiters: true })); + return ranges; +} + +/** The HTML comments Words reads as raw HTML in `markdown`, not as code or text, as source offsets. */ +export function markdownHtmlComments(markdown: string): Array<{ start: number; end: number }> { + const openers = [...markdown.matchAll(/", start + 4); + return { start, end: close < 0 ? markdown.length : close + 3 }; + }); +} + +/** + * The first definition of each label in `markdown`, as one line of Markdown. Words decides which + * `[label]:` text defines one: each label is looked up again after the text. + */ +export function markdownReferenceDefinitions(markdown: string): string[] { + const labels = new Map(); + for (const match of markdown.matchAll(/\[((?:[^\\[\]]|\\.){1,999})\]:/g)) { + const key = match[1]!.replace(/\s+/g, " ").trim().toLowerCase(); + // `[^1]:` is a footnote. + if (key !== "" && !key.startsWith("^") && !labels.has(key)) labels.set(key, match[1]!); + } + if (labels.size === 0) return []; + let probe = `${markdown}\n\n`; + const lookups = new Map(); + for (const label of labels.values()) { + lookups.set(probe.length, label); + probe += `[${label}]\n\n`; + } + const definitions: string[] = []; + const visit = (node: Root | Element) => { + for (const child of node.children) { + if (child.type !== "element") continue; + const label = lookups.get(child.position?.start.offset ?? -1); + if (child.tagName === "a" && label !== undefined) { + const href = String(child.properties.href ?? "").replace(/[<>\\\n]/g, encodeURIComponent); + const title = child.properties.title; + definitions.push( + `[${label}]: <${href}>${typeof title === "string" ? ` "${title.replace(/\s+/g, " ").replace(/["\\]/g, "\\$&")}"` : ""}`, + ); + } else visit(child); + } + }; + visit(parse(probe, { windowsPaths: true })); + return definitions; +} diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index fee70319c71de..92fad6b57ac9d 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -654,6 +654,10 @@ "./provider-instance-ids": { "types": "./src/providerInstanceIds.ts", "default": "./src/providerInstanceIds.ts" + }, + "./pull-request-references": { + "types": "./src/pullRequestReferences.ts", + "default": "./src/pullRequestReferences.ts" } }, "scripts": { @@ -680,16 +684,16 @@ "effect": "catalog:", "gt-i18n": "1.0.40", "jszip": "3.10.1", - "remark-gfm": "catalog:", - "remark-parse": "catalog:", "three": "0.180.0", - "unbash": "^5.0.0", - "unified": "catalog:" + "unbash": "^5.0.0" }, "devDependencies": { "@effect/vitest": "catalog:", "@types/mdast": "^4.0.4", "@types/three": "0.180.0", + "remark-gfm": "catalog:", + "remark-parse": "catalog:", + "unified": "catalog:", "vite-plus": "catalog:" } } diff --git a/packages/client-runtime/src/pullRequestMarkdown.test.ts b/packages/client-runtime/src/pullRequestMarkdown.test.ts index d4f19173758ec..7d9d162d76a05 100644 --- a/packages/client-runtime/src/pullRequestMarkdown.test.ts +++ b/packages/client-runtime/src/pullRequestMarkdown.test.ts @@ -4,19 +4,39 @@ import remarkParse from "remark-parse"; import { unified } from "unified"; import { describe, expect, it } from "vite-plus/test"; +import { splitPullRequestBody, type PullRequestBodySegment } from "./pullRequestMarkdown.ts"; import { changeRequestReferenceAutolinker, resolveChangeRequestMediaUrl, - splitPullRequestBody, - type PullRequestBodySegment, -} from "./pullRequestMarkdown.ts"; +} from "./pullRequestReferences.ts"; + +const definitionParser = unified().use(remarkParse).use(remarkGfm); + +// The finder a client passes: each first definition, joined onto one line out of its quote. +const split = (body: string) => + splitPullRequestBody(body, (markdown) => { + const definitions = new Map(); + const visit = (node: Root | RootContent, quotes: number) => { + if (node.type === "definition" && !definitions.has(node.identifier)) { + const wrap = new RegExp(`(?:\\r\\n|\\r|\\n)(?:[ \\t]*>){0,${quotes}}[ \\t]*`, "gu"); + const source = markdown.slice(node.position?.start.offset, node.position?.end.offset); + definitions.set(node.identifier, source.replace(wrap, " ")); + } + if ("children" in node) { + for (const child of node.children) + visit(child, quotes + (node.type === "blockquote" ? 1 : 0)); + } + }; + visit(definitionParser.parse(markdown), 0); + return [...definitions.values()]; + }); describe("pull request body segmentation", () => { // GitHub writes a dropped image into the body as an `` tag, so a bare attachment link on // its own line is the shape it uses for a video — every one sampled in the wild was one. it("lifts a dropped video out and keeps the prose around it", () => { expect( - splitPullRequestBody( + split( "Before\n\nhttps://github.com/user-attachments/assets/2f8c1a90-1b2c-4d5e-8f90-abcdef123456\n\nAfter", ), ).toEqual([ @@ -43,7 +63,7 @@ describe("pull request body segmentation", () => { ? segment.rows.flat().flatMap((cell) => prose(cell.segments)) : [], ); - const runs = prose(splitPullRequestBody(body)); + const runs = prose(split(body)); expect(runs.map((segment) => segment.text)).toEqual([ "- [ ] Before", " - [ ] code\n- [x] After", @@ -59,9 +79,7 @@ describe("pull request body segmentation", () => { it("reads the source out of a video tag, including a multi-line one", () => { expect( - splitPullRequestBody( - '', - ), + split(''), ).toEqual([ { id: "attachment:0", @@ -75,21 +93,21 @@ describe("pull request body segmentation", () => { it("leaves the img tag GitHub writes for a dropped image as markdown", () => { const body = 'image'; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); it("leaves an ordinary link alone, whether it is bare or written as markdown", () => { const body = "https://example.com/page\n\n[the docs](https://example.com/docs)"; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); it("never lifts a link inside fenced code out of it", () => { const body = "```\nhttps://example.com/demo.mp4\n```"; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); @@ -97,14 +115,14 @@ describe("pull request body segmentation", () => { // GitHub keeps CRLF in a body written in its web editor. it("recognizes fences in a body with CRLF line endings", () => { const body = "```\r\nhttps://example.com/demo.mp4\r\n```"; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); it("closes a CRLF fence, so a video after it still lifts out", () => { const code = '```html\r\n\r\n```'; - expect(splitPullRequestBody(`${code}\r\n\r\nhttps://example.com/demo.mp4\r\n`)).toEqual([ + expect(split(`${code}\r\n\r\nhttps://example.com/demo.mp4\r\n`)).toEqual([ { id: "markdown:0", kind: "markdown", text: code, sourceOffset: 0 }, { id: "attachment:1", @@ -117,21 +135,21 @@ describe("pull request body segmentation", () => { it("does not let a different fence marker close an open fence", () => { const body = "```\n~~~\nhttps://example.com/demo.mp4\n```"; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); it("keeps a video tag that shares its line with prose as markdown", () => { const body = 'Before after'; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); it("treats an info-string fence as a nested opener, not a close", () => { const body = "```\n```javascript\nhttps://example.com/demo.mp4\n```"; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); @@ -139,9 +157,7 @@ describe("pull request body segmentation", () => { it("does not open a fence on a line of inline triple-backtick code", () => { const code = "```\nhttps://example.com/b.png\n```"; expect( - splitPullRequestBody( - `\`\`\`npm test\`\`\` passes.\n\nhttps://example.com/demo.mp4\n\n${code}`, - ), + split(`\`\`\`npm test\`\`\` passes.\n\nhttps://example.com/demo.mp4\n\n${code}`), ).toEqual([ { id: "markdown:0", kind: "markdown", text: "```npm test``` passes.", sourceOffset: 0 }, { @@ -153,14 +169,14 @@ describe("pull request body segmentation", () => { { id: "markdown:2", kind: "markdown", text: code, sourceOffset: 54 }, ]); const multilineSpan = "```foo`\nhttps://example.com/demo.mp4\nbar```"; - expect(splitPullRequestBody(multilineSpan)).toEqual([ + expect(split(multilineSpan)).toEqual([ { id: "markdown:0", kind: "markdown", text: multilineSpan, sourceOffset: 0 }, ]); }); it("leaves an indented code line alone even when it is only a video link", () => { const body = " https://example.com/demo.mp4"; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); @@ -169,14 +185,14 @@ describe("pull request body segmentation", () => { const body = ['

    ");
         expect(html).toContain("
  • for (const step of rest.steps) {
  • "); expect(html).toContain("
  • if (step.request.body) {
  • "); - expect(html).toContain("
  • step.request.body = "<redacted>";
  • "); + expect(html).toContain('
  • step.request.body = "";
  • '); }); it("preserves every recovered block separated by blank lines", () => { diff --git a/packages/shared/src/markdownPipeline.ts b/packages/shared/src/markdownPipeline.ts index 53b49a03762a3..6bb022f532942 100644 --- a/packages/shared/src/markdownPipeline.ts +++ b/packages/shared/src/markdownPipeline.ts @@ -1,4 +1,3 @@ -import { isLocalEditorFileUrl, LOCAL_FILE_LINK_SCHEMES } from "@t3tools/contracts"; import type { Heading, Link, @@ -15,7 +14,7 @@ import remarkParse from "remark-parse"; import remarkRehype from "remark-rehype"; import { find, html } from "property-information"; import rehypeRaw from "rehype-raw"; -import rehypeSanitize, { defaultSchema } from "rehype-sanitize"; +import rehypeSanitize from "rehype-sanitize"; import remarkBreaks from "remark-breaks"; import remarkGfm from "remark-gfm"; import { remarkGithubAlerts } from "./markdownGithubAlerts.ts"; @@ -25,17 +24,18 @@ import { remarkEnableLeadingWhitespace, remarkKeepLeadingWhitespace, } from "./markdownLeadingWhitespace.ts"; -import { - CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES, - remarkCodexDirectives, -} from "./codexMarkdownDirectives.ts"; -import { - absoluteFilePathMatches, - isWindowsDrivePathHref, - normalizeMarkdownLinkDestination, -} from "./markdownLinks.ts"; +import { remarkCodexDirectives } from "./codexMarkdownDirectives.ts"; +import { absoluteFilePathMatches } from "./markdownLinks.ts"; import { isWindowsAbsolutePath } from "./path.ts"; -import { THREAD_LINK_PROTOCOL } from "./threadLinks.ts"; +import { + CHAT_MARKDOWN_SANITIZE_SCHEMA, + chatMarkdownImageSource, + rehypeNormalizeLocalEditorLinks, + rehypePreserveImageSourceMeta, + type ChatMarkdownImageProperties, +} from "./markdownHast.ts"; + +export { chatMarkdownImageSource, type ChatMarkdownImageProperties }; export { remarkEnableOrderedListNumbers } from "./markdownOrderedListNumbers.ts"; @@ -47,44 +47,6 @@ type MarkdownImageHastNode = { children?: MarkdownImageHastNode[]; }; -function meaningfulHastChildren(node: MarkdownImageHastNode): MarkdownImageHastNode[] { - return (node.children ?? []).filter( - (child) => !(child.type === "text" && (child as { value?: string }).value?.trim() === ""), - ); -} - -const STANDALONE_IMAGE_BLOCKS = new Set([ - "p", - "div", - "li", - "td", - "th", - "figure", - "center", - "blockquote", -]); - -function soleImageDescendant(node: MarkdownImageHastNode): MarkdownImageHastNode | undefined { - const children = meaningfulHastChildren(node); - if (children.length !== 1) return undefined; - const only = children[0]; - if (only?.type !== "element") return undefined; - if (only.tagName === "img") return only; - return only.tagName === "a" || only.tagName === "strong" || only.tagName === "em" - ? soleImageDescendant(only) - : undefined; -} - -function markStandaloneImages(node: MarkdownImageHastNode) { - if (node.type === "root" || (node.tagName && STANDALONE_IMAGE_BLOCKS.has(node.tagName))) { - const image = soleImageDescendant(node); - if (image) image.properties = { ...image.properties, dataStandalone: true }; - } - node.children?.forEach((child) => { - if (child.type === "element") markStandaloneImages(child); - }); -} - // Whole tags, attributes, and comments, so closing-anchor text inside them never counts as a tag. const RAW_HTML_TAG_PATTERN = /|$)|<\/?[A-Za-z](?:[^"'<>]|"[^"]*"|'[^']*')*>/g; @@ -133,121 +95,6 @@ function rehypePreserveBareAnchorPlaceholders() { }; } -const COLOR_SCHEME_MEDIA = /^\(\s*prefers-color-scheme\s*:\s*(dark|light)\s*\)$/i; - -/** - * The renderer resolves an ``'s `src` (workspace files, host media) but never a ``'s - * `srcset`, which would load unresolved whenever its media matched. A color-scheme source moves - * onto the `` for the renderer to pick by theme; every source is then dropped. - */ -function moveColorSchemeSourcesToImage(picture: MarkdownImageHastNode) { - if (!picture.children) return; - const image = picture.children.find((child) => child.tagName === "img"); - for (const source of picture.children) { - if (source.tagName !== "source" || !image) continue; - const media = source.properties?.media; - const scheme = typeof media === "string" ? COLOR_SCHEME_MEDIA.exec(media)?.[1] : undefined; - const srcSet = source.properties?.srcSet; - const candidate = Array.isArray(srcSet) ? srcSet[0] : srcSet; - // A candidate's URL runs to the first space (a descriptor such as `2x` may follow). - const url = - typeof candidate === "string" ? candidate.trim().split(/\s/, 1)[0]?.replace(/,+$/, "") : ""; - const key = scheme?.toLowerCase() === "dark" ? "dataDarkSrc" : "dataLightSrc"; - // As in a browser, the first source that matches a scheme is the one shown. - if (scheme && url && image.properties?.[key] === undefined) { - // The sanitizer reads a drive letter as a protocol; as a file URL it resolves to the same path. - const value = isWindowsDrivePathHref(url) ? `file:///${url.replaceAll("\\", "/")}` : url; - image.properties = { ...image.properties, [key]: value }; - } - } - picture.children = picture.children.filter((child) => child.tagName !== "source"); -} - -function rehypePreserveImageSourceMeta() { - return (tree: MarkdownImageHastNode) => { - const visit = (node: MarkdownImageHastNode) => { - const src = node.properties?.src; - const title = node.properties?.title; - if (node.type === "element" && node.tagName === "picture") { - moveColorSchemeSourcesToImage(node); - } - if (node.type === "element" && node.tagName === "img") { - node.properties = { - ...node.properties, - ...(typeof src === "string" && isWindowsDrivePathHref(src) ? { dataLocalSrc: src } : {}), - ...(typeof title === "string" ? { dataMarkdownTitle: title } : {}), - }; - } - node.children?.forEach(visit); - }; - - visit(tree); - markStandaloneImages(tree); - }; -} - -const IMAGE_SRC_PROTOCOLS = [...(defaultSchema.protocols?.src ?? []), "file", "t3-context"]; - -// The sanitizer compares schemes case-sensitively, so lowercase accepted editor links first. -function rehypeNormalizeLocalEditorLinks() { - return (tree: MarkdownImageHastNode) => { - const visit = (node: MarkdownImageHastNode) => { - const href = node.properties?.href; - if (node.type === "element" && node.tagName === "a" && typeof href === "string") { - try { - const url = new URL(href); - if (isLocalEditorFileUrl(url)) node.properties = { ...node.properties, href: url.href }; - } catch { - // Not an absolute URL; the sanitizer decides. - } - } - node.children?.forEach(visit); - }; - - visit(tree); - }; -} - -const CHAT_MARKDOWN_SANITIZE_SCHEMA = { - ...defaultSchema, - attributes: { - ...defaultSchema.attributes, - "*": (defaultSchema.attributes?.["*"] ?? []).filter((attribute) => attribute !== "title"), - // Fence languages plus the two math classes the web chat's math plugin emits. - code: [ - ["className", /^language-./, "math-inline", "math-display"], - "dataCodeMeta", - "dataInlineCode", - ], - blockquote: [...(defaultSchema.attributes?.blockquote ?? []), "dataAlert"], - div: [...(defaultSchema.attributes?.div ?? []), ...CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES], - a: [...(defaultSchema.attributes?.a ?? []), "dataPullRequestAutolink"], - img: [ - ...(defaultSchema.attributes?.img ?? []), - "dataDarkSrc", - "dataLightSrc", - "dataLocalSrc", - "dataMarkdownTitle", - "dataStandalone", - ], - }, - protocols: { - ...defaultSchema.protocols, - href: [ - ...(defaultSchema.protocols?.href ?? []), - "file", - "t3-citation", - "t3-context", - THREAD_LINK_PROTOCOL, - // Scheme only: the renderer's URL transform checks the rest of the link shape. - ...LOCAL_FILE_LINK_SCHEMES, - ], - src: IMAGE_SRC_PROTOCOLS, - dataDarkSrc: IMAGE_SRC_PROTOCOLS, - dataLightSrc: IMAGE_SRC_PROTOCOLS, - }, -} satisfies Parameters[0]; - export const CHAT_MARKDOWN_REMARK_PLUGINS: PluggableList = [ remarkGfm, remarkEndAutolinksAtScriptPunctuation, @@ -752,10 +599,6 @@ function remarkNormalizeLinksAndTagInlineCode() { }; } -export function shouldPreserveAssistantLineBreaks(text: string): boolean { - return /^★ Insight(?:\s|─)/mu.test(text); -} - export function remarkAssistantInsights(this: Processor) { return (tree: Root, file: { value: unknown }) => { const source = String(file.value); @@ -840,37 +683,6 @@ const imageSourceProcessor = unified() .use(remarkRehype, { allowDangerousHtml: true }) .use(CHAT_MARKDOWN_REHYPE_PLUGINS); -export type ChatMarkdownImageProperties = { - readonly src?: unknown; - readonly dataLocalSrc?: unknown; - readonly dataDarkSrc?: unknown; - readonly dataLightSrc?: unknown; -}; - -/** Keep the authored path for file links and normalize Windows separators for classification. */ -export function chatMarkdownImageSource( - properties?: ChatMarkdownImageProperties, - theme?: "dark" | "light", -) { - const themeSrc = - theme === undefined - ? undefined - : properties?.[theme === "dark" ? "dataDarkSrc" : "dataLightSrc"]; - const localSrc = typeof themeSrc === "string" ? undefined : properties?.dataLocalSrc; - const source = - typeof themeSrc === "string" - ? themeSrc - : typeof localSrc === "string" - ? localSrc - : properties?.src; - if (typeof source !== "string") return null; - const authoredSrc = normalizeMarkdownLinkDestination(source); - return { - authoredSrc, - classifiedSrc: typeof localSrc === "string" ? authoredSrc.replaceAll("\\", "/") : authoredSrc, - }; -} - interface ImageSourceNode { readonly type: string; readonly tagName?: string; diff --git a/packages/shared/src/markdownTaskEdits.ts b/packages/shared/src/markdownTaskEdits.ts new file mode 100644 index 0000000000000..2f33428613147 --- /dev/null +++ b/packages/shared/src/markdownTaskEdits.ts @@ -0,0 +1,28 @@ +/** Offset of the `[ ]` marker on the first line of the list item starting at `listItemStart`. */ +export function taskListMarkerOffset(markdown: string, listItemStart: number): number | null { + const firstLineEnd = markdown.indexOf("\n", listItemStart); + const firstLine = markdown.slice( + listItemStart, + firstLineEnd === -1 ? markdown.length : firstLineEnd, + ); + const match = firstLine.match(/^(?:\s*(?:[-+*]|\d+[.)])\s+)(\[[ xX]\])/); + if (!match?.[1]) return null; + return listItemStart + firstLine.indexOf(match[1]); +} + +export function setMarkdownTaskChecked( + markdown: string, + markerOffset: number, + checked: boolean, +): string { + if ( + markerOffset < 0 || + markdown[markerOffset] !== "[" || + !/[ xX]/.test(markdown[markerOffset + 1] ?? "") || + markdown[markerOffset + 2] !== "]" + ) { + return markdown; + } + + return `${markdown.slice(0, markerOffset + 1)}${checked ? "x" : " "}${markdown.slice(markerOffset + 2)}`; +} diff --git a/packages/shared/src/markdownTaskList.test.ts b/packages/shared/src/markdownTaskList.test.ts index 5e00a3926fa54..7f7519ce49ee5 100644 --- a/packages/shared/src/markdownTaskList.test.ts +++ b/packages/shared/src/markdownTaskList.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "vite-plus/test"; -import { markdownTaskMarkerOffset, setMarkdownTaskChecked } from "./markdownTaskList.ts"; +import { markdownTaskMarkerOffset } from "./markdownTaskList.ts"; +import { setMarkdownTaskChecked } from "./markdownTaskEdits.ts"; describe("setMarkdownTaskChecked", () => { const markdown = "- [ ] First\n- [x] Second\n"; diff --git a/packages/shared/src/markdownTaskList.ts b/packages/shared/src/markdownTaskList.ts index fb02f757992b9..a4d18895505c6 100644 --- a/packages/shared/src/markdownTaskList.ts +++ b/packages/shared/src/markdownTaskList.ts @@ -3,36 +3,9 @@ import remarkGfm from "remark-gfm"; import remarkParse from "remark-parse"; import { unified } from "unified"; -const parser = unified().use(remarkParse).use(remarkGfm); - -/** Offset of the `[ ]` marker on the first line of the list item starting at `listItemStart`. */ -export function taskListMarkerOffset(markdown: string, listItemStart: number): number | null { - const firstLineEnd = markdown.indexOf("\n", listItemStart); - const firstLine = markdown.slice( - listItemStart, - firstLineEnd === -1 ? markdown.length : firstLineEnd, - ); - const match = firstLine.match(/^(?:\s*(?:[-+*]|\d+[.)])\s+)(\[[ xX]\])/); - if (!match?.[1]) return null; - return listItemStart + firstLine.indexOf(match[1]); -} - -export function setMarkdownTaskChecked( - markdown: string, - markerOffset: number, - checked: boolean, -): string { - if ( - markerOffset < 0 || - markdown[markerOffset] !== "[" || - !/[ xX]/.test(markdown[markerOffset + 1] ?? "") || - markdown[markerOffset + 2] !== "]" - ) { - return markdown; - } +import { taskListMarkerOffset } from "./markdownTaskEdits.ts"; - return `${markdown.slice(0, markerOffset + 1)}${checked ? "x" : " "}${markdown.slice(markerOffset + 2)}`; -} +const parser = unified().use(remarkParse).use(remarkGfm); /** Hard breaks as U+2028, as iOS draws them; soft breaks stay "\n". */ function plainText(node: Nodes): string { diff --git a/packages/shared/src/markdownWindowsPaths.ts b/packages/shared/src/markdownWindowsPaths.ts index c4c04490a2140..d7c827c8dba8c 100644 --- a/packages/shared/src/markdownWindowsPaths.ts +++ b/packages/shared/src/markdownWindowsPaths.ts @@ -1,5 +1,6 @@ import type { Processor } from "unified"; import { decodeString } from "micromark-util-decode-string"; +import { UNFINISHED_DRIVE_PATH } from "./markdownLinks.ts"; import { isWindowsAbsolutePath } from "./path.ts"; interface DestinationCompileContext { @@ -18,9 +19,6 @@ function keepWindowsPathDestination(this: DestinationCompileContext, token: unkn : decoded; } -// A drive path that has not reached whitespace yet: `C:`, `C:\Users\me`, `C:/work`. -export const UNFINISHED_DRIVE_PATH = /(?:^|\W)[A-Za-z]:(?:[\\/]\S*)?$/; - interface EscapeCompileContext { readonly stack: ReadonlyArray<{ readonly type: string; diff --git a/packages/shared/src/textDirection.ts b/packages/shared/src/textDirection.ts index 0d4a7d88fd837..1efe672108cad 100644 --- a/packages/shared/src/textDirection.ts +++ b/packages/shared/src/textDirection.ts @@ -2,8 +2,8 @@ export type TextDirection = "ltr" | "rtl"; // Hebrew through Arabic Extended-A, their presentation forms, and the // supplementary right-to-left blocks. -const RTL_LETTER = /[֐-ࣿיִ-﷿ﹰ-\u{10800}-\u{10FFF}\u{1E800}-\u{1EFFF}]/u; -const LETTER = /\p{L}/u; +export const RTL_LETTER = /[֐-ࣿיִ-﷿ﹰ-\u{10800}-\u{10FFF}\u{1E800}-\u{1EFFF}]/u; +export const LETTER = /\p{L}/u; const SENTENCE_END = /(?<=[.!?؟])(?=0.5.1' + react: ^18.3.1 || ^19.0.0 + peerDependenciesMeta: + '@pierre/highlights': + optional: true + react: + optional: true + '@pinojs/redact@0.4.0': resolution: {integrity: sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==} @@ -11629,12 +11623,6 @@ packages: react-is@19.2.7: resolution: {integrity: sha512-kZFnouyVv7eP/Phmrlo9FK+zcAdriZJvzxXHF1Sl1P377WSGe2G/JxVolhTrB/jeV47lKImhNUsijjHAAbcl/A==} - react-markdown@10.1.0: - resolution: {integrity: sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==} - peerDependencies: - '@types/react': '>=18' - react: '>=18' - react-native-enriched-markdown@file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-16db4c75.tgz: resolution: {integrity: sha512-TdP2nTxn8W4jPJ5EU+9Ctgf6aOncENP/kMa9aEZpJDmWNLXkxPpcugHMWyZJt2o5WDYE4SPi0V6zV6mOl3+8cA==, tarball: file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-16db4c75.tgz} version: 1.2.0-t3.18 @@ -16556,6 +16544,11 @@ snapshots: - '@shikijs/themes' - shiki + '@pierre/words@file:apps/web/deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz(@pierre/highlights@0.5.1)(react@19.3.0)': + optionalDependencies: + '@pierre/highlights': 0.5.1 + react: 19.3.0 + '@pinojs/redact@0.4.0': {} '@polka/url@1.0.0-next.29': {} @@ -22531,24 +22524,6 @@ snapshots: react-is@19.2.7: {} - react-markdown@10.1.0(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1): - dependencies: - '@types/hast': 3.0.5 - '@types/mdast': 4.0.4 - '@types/react': 19.3.0 - devlop: 1.1.0 - hast-util-to-jsx-runtime: 2.3.6(supports-color@8.1.1) - html-url-attributes: 3.0.1 - mdast-util-to-hast: 13.2.1(patch_hash=57ea46c73aea3c876ab8d351fe0482ddd081dcb4a0610576e399dbe5eb59d2b1) - react: 19.3.0 - remark-parse: 11.0.0(supports-color@8.1.1) - remark-rehype: 11.1.2 - unified: 11.0.5 - unist-util-visit: 5.1.0 - vfile: 6.0.3 - transitivePeerDependencies: - - supports-color - react-native-enriched-markdown@file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-16db4c75.tgz(katex@0.16.47)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0): dependencies: react: 19.3.0 diff --git a/scripts/check-changed.ts b/scripts/check-changed.ts index 135ff4ed201f7..d5881661f4cdc 100644 --- a/scripts/check-changed.ts +++ b/scripts/check-changed.ts @@ -433,6 +433,7 @@ const checkChanged = Effect.fn("checkChanged")(function* (input: { file === ".pnpmfile.cjs" || file.startsWith("patches/") || file.startsWith("apps/mobile/deps/") || + file.startsWith("apps/web/deps/") || path.basename(file) === "package.json", ); @@ -479,7 +480,7 @@ const checkChanged = Effect.fn("checkChanged")(function* (input: { if (yield* fs.exists(inRoot(manifest))) yield* copy(manifest); } } - for (const extra of ["apps/mobile/deps", "patches", ".pnpmfile.cjs"]) { + for (const extra of ["apps/mobile/deps", "apps/web/deps", "patches", ".pnpmfile.cjs"]) { if (yield* fs.exists(inRoot(extra))) yield* copy(extra); } const result = yield* vp(["install", "--lockfile-only", "--ignore-scripts"], temp); diff --git a/scripts/release-smoke.ts b/scripts/release-smoke.ts index 3c58be4cbabbf..e7acbf1e76ff1 100644 --- a/scripts/release-smoke.ts +++ b/scripts/release-smoke.ts @@ -68,11 +68,12 @@ function copyWorkspaceManifestFixture(targetRoot: string): void { NodeFS.cpSync(sourcePath, destinationPath); } - const mobileDependencies = NodePath.resolve(repoRoot, "apps/mobile/deps"); - if (NodeFS.existsSync(mobileDependencies)) { - NodeFS.cpSync(mobileDependencies, NodePath.resolve(targetRoot, "apps/mobile/deps"), { - recursive: true, - }); + // Fork tarballs that file: dependencies install from. + for (const forks of ["apps/mobile/deps", "apps/web/deps"]) { + const source = NodePath.resolve(repoRoot, forks); + if (NodeFS.existsSync(source)) { + NodeFS.cpSync(source, NodePath.resolve(targetRoot, forks), { recursive: true }); + } } const patchesDirectory = NodePath.resolve(repoRoot, "patches"); From c1fbdf6cdbe1e16379beebf8658b12a0b8a84f70 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 21:53:58 -0800 Subject: [PATCH 102/324] fix(web): pasting text copied from Word inserts the text instead of an image (#40686) --- apps/web/src/components/chat/ChatComposer.tsx | 10 ++++- .../chat/composerAttachmentFiles.test.ts | 18 +++++++- .../chat/composerAttachmentFiles.ts | 44 +++++++++++++------ 3 files changed, 56 insertions(+), 16 deletions(-) diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 2c3bc34529ffd..6d4487adef153 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -133,6 +133,7 @@ import { fileAttachmentCapabilityBlockReason, fileAttachmentStagingLimit, isPreviewableComposerVideo, + isImageOnlyClipboardHtml, shouldHandleComposerAttachmentPaste, } from "./composerAttachmentFiles"; import { @@ -2918,7 +2919,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) (!pastedContext && activeThreadId && files.length > 0 && - shouldHandleComposerAttachmentPaste({ files, plainText, bypassAutoAttachment })) + shouldHandleComposerAttachmentPaste({ + files, + plainText, + bypassAutoAttachment, + htmlIsOnlyImage: + plainText.length > 0 && + isImageOnlyClipboardHtml(event.clipboardData.getData("text/html")), + })) ) { event.preventDefault(); event.stopPropagation(); diff --git a/apps/web/src/components/chat/composerAttachmentFiles.test.ts b/apps/web/src/components/chat/composerAttachmentFiles.test.ts index 2a487b1f237de..f842566d7cd60 100644 --- a/apps/web/src/components/chat/composerAttachmentFiles.test.ts +++ b/apps/web/src/components/chat/composerAttachmentFiles.test.ts @@ -121,10 +121,26 @@ describe("composer attachment files", () => { ).toBe(true); }); - it("leaves an image-and-text clipboard to the text path under Paste as Text", () => { + it("leaves a Word image-and-text clipboard to the text path, with or without Paste as Text", () => { const image = new File(["png"], "image.png", { type: "image/png" }); const input = { files: [image], plainText: "Hello from Word", bypassAutoAttachment: true }; expect(shouldHandleComposerAttachmentPaste(input)).toBe(false); + // A plain paste of the same Word clipboard keeps the text too. + expect(shouldHandleComposerAttachmentPaste({ ...input, bypassAutoAttachment: false })).toBe( + false, + ); + // Firefox's Copy Image adds the image URL as text and only an as HTML; the image attaches. + expect( + shouldHandleComposerAttachmentPaste({ + files: [image], + plainText: "https://example.com/image.png", + htmlIsOnlyImage: true, + }), + ).toBe(true); + // Finder adds a copied file's name as text. + expect(shouldHandleComposerAttachmentPaste({ files: [image], plainText: "image.png" })).toBe( + true, + ); }); it("preserves text when the clipboard also includes generic image files", () => { diff --git a/apps/web/src/components/chat/composerAttachmentFiles.ts b/apps/web/src/components/chat/composerAttachmentFiles.ts index 041db7193d2e2..191c5841185ff 100644 --- a/apps/web/src/components/chat/composerAttachmentFiles.ts +++ b/apps/web/src/components/chat/composerAttachmentFiles.ts @@ -239,30 +239,46 @@ export function attachmentsToReleaseOnUploadCapabilityLoss( ); } +function isOnlyFileNames(text: string, files: ReadonlyArray): boolean { + const names = new Set(files.map((file) => file.name)); + return text + .split(/\r?\n/) + .filter((line) => line.length > 0) + .every((line) => names.has(line)); +} + +/** A browser's Copy Image puts only an in text/html; rich text sources put the text there. */ +export function isImageOnlyClipboardHtml(html: string): boolean { + if (html.length === 0) return false; + const body = new DOMParser().parseFromString(html, "text/html").body; + return body.querySelector("img") !== null && (body.textContent ?? "").trim().length === 0; +} + export function shouldHandleComposerAttachmentPaste(input: { readonly files: ReadonlyArray; readonly plainText: string; readonly bypassAutoAttachment?: boolean; + readonly htmlIsOnlyImage?: boolean; }): boolean { // Paste as Text keeps the text even when the source also put an image of it on the clipboard. if (input.bypassAutoAttachment && input.plainText.length > 0) return false; if ( - input.files.some((file) => { - if (isDngFile(file)) return true; - const classification = classifyComposerAttachmentFile(file); - return ( - classification === "image" || - classification === "unsupported-image" || - isSvgAttachment({ name: file.name, mimeType: file.type }) - ); - }) + input.files.some( + (file) => isDngFile(file) || isSvgAttachment({ name: file.name, mimeType: file.type }), + ) ) { return true; } - - if (input.plainText.length > 0) { - return false; + const hasImage = input.files.some((file) => { + const classification = classifyComposerAttachmentFile(file); + return classification === "image" || classification === "unsupported-image"; + }); + if (input.plainText.length === 0) { + return hasImage || input.files.some((file) => classifyComposerAttachmentFile(file) === "file"); } - - return input.files.some((file) => classifyComposerAttachmentFile(file) === "file"); + // Rich text sources (Word, Pages) add a picture of the text. Copy Image adds the image URL as + // text beside an , and a Finder copy adds the file names. + return ( + hasImage && (input.htmlIsOnlyImage === true || isOnlyFileNames(input.plainText, input.files)) + ); } From 3b3f8808f43cd67a82e19cbdc5cfcefa7f8d56d4 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Sun, 22 Nov 2026 00:03:48 -0600 Subject: [PATCH 103/324] fix(web): wait for image uploads before sending (#40672) Co-authored-by: Cursor Co-authored-by: Julius Marminge Co-authored-by: Claude Opus 5.5 --- .../src/components/ChatView.browser.test.tsx | 103 ++++++++++++++++++ apps/web/src/components/ChatView.tsx | 24 +++- apps/web/src/components/chat/ChatComposer.tsx | 91 ++++++++++++---- .../chat/ComposerFooterControls.tsx | 2 + .../chat/ComposerHeldSendBanner.tsx | 50 +++++++++ .../chat/ComposerPrimaryActions.tsx | 30 +++-- .../chat/preparingComposerImages.test.ts | 58 ++++++++++ .../chat/preparingComposerImages.ts | 90 +++++++++++++++ .../chat/useComposerAttachmentIntake.ts | 34 +++--- .../components/chat/useComposerSelection.ts | 6 + .../src/components/chat/useComposerSend.ts | 36 +++++- apps/web/src/i18n/translations/de.json | 20 ++-- apps/web/src/i18n/translations/en.json | 20 ++-- apps/web/src/i18n/translations/es.json | 20 ++-- apps/web/src/i18n/translations/fr.json | 20 ++-- apps/web/src/i18n/translations/ja.json | 20 ++-- apps/web/src/i18n/translations/ko.json | 20 ++-- apps/web/src/i18n/translations/pt-BR.json | 20 ++-- apps/web/src/i18n/translations/ru.json | 20 ++-- apps/web/src/i18n/translations/sv.json | 20 ++-- apps/web/src/i18n/translations/zh.json | 20 ++-- 21 files changed, 594 insertions(+), 130 deletions(-) create mode 100644 apps/web/src/components/chat/ComposerHeldSendBanner.tsx create mode 100644 apps/web/src/components/chat/preparingComposerImages.test.ts diff --git a/apps/web/src/components/ChatView.browser.test.tsx b/apps/web/src/components/ChatView.browser.test.tsx index ae6628ba6733c..cfd06a8864e0d 100644 --- a/apps/web/src/components/ChatView.browser.test.tsx +++ b/apps/web/src/components/ChatView.browser.test.tsx @@ -112,6 +112,19 @@ vi.mock("../../../../packages/client-runtime/src/connection/driver.ts", async (i return { ...actual, layer: Layer.succeed(actual.ConnectionDriver, fakeDriver) }; }); +// Null runs the real compression; a test sets it to hold an image in preparation. +const compression = vi.hoisted(() => ({ gate: null as Promise | null })); +vi.mock(import("~/lib/imageCompression"), async (original) => { + const actual = await original(); + return { + ...actual, + prepareImageForAttachment: async (...args) => { + await compression.gate; + return actual.prepareImageForAttachment(...args); + }, + }; +}); + vi.mock(import("~/rpc/requestLatencyState"), async (original) => ({ ...(await original()), trackRpcRequestSent: () => {}, @@ -438,6 +451,96 @@ it("an interrupted image-only first send of a new thread says it may not have be expect(page.getByText("Copy message", { exact: true }).query()).toBeNull(); }); +it.each(["new", "existing"] as const)( + "Enter while an image compresses shows a cancellable banner, cancels on edit or Esc, and still sends after leaving a %s thread", + async (kind) => { + const thread = threadWithHistory(`upload-wait-${kind}`, 1); + const other = threadWithHistory(`upload-wait-other-${kind}`, 1); + using _environment = installFakeEnvironment(kind === "existing" ? [thread, other] : [other], { + acceptCommands: true, + }); + __setClientSettingsForTests({ + ...DEFAULT_CLIENT_SETTINGS, + onboardingCompletedAt: "2026-01-01T00:00:00.000Z", + }); + const draftId = DraftId.make(`draft-upload-wait-${kind}`); + if (kind === "new") { + useComposerDraftStore + .getState() + .setProjectDraftThreadId(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), draftId, { + threadId: thread.id, + }); + } + using launch = holdRpc(ORCHESTRATION_V2_WS_METHODS.launchThread, Effect.interrupt); + const router = getRouter( + createMemoryHistory({ + initialEntries: [kind === "new" ? `/draft/${draftId}` : `/${ENVIRONMENT_ID}/${thread.id}`], + }), + ); + await router.load(); + await using _app = await render(, { + // AppRoot brings its own router. + router: false, + }); + const compressed = Promise.withResolvers(); + compression.gate = compressed.promise; + using _compression = { [Symbol.dispose]: () => (compression.gate = null) }; + using _uploads = acceptAttachmentUploads(); + const editor = page.getByTestId("composer-editor"); + await expect.element(editor).toBeVisible(); + await expect.element(page.getByText("render", { exact: true }).first()).toBeVisible(); + + await userEvent.click(editor); + const clipboardData = new DataTransfer(); + clipboardData.items.add(new File([PNG], "shot.png", { type: "image/png" })); + editor + .element() + .dispatchEvent( + new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true }), + ); + + // Enter arms the send and shows the banner plus a disabled spinner button. + await userEvent.keyboard("check image{Enter}"); + await expect.element(page.getByText("Sending once image is ready")).toBeVisible(); + const waitingButton = page.getByRole("button", { name: "Sending when ready", exact: true }); + await expect.element(waitingButton).toBeDisabled(); + await expect.element(waitingButton).toHaveAttribute("aria-busy", "true"); + + // Typing disarms the queued send and keeps the edit. + await userEvent.keyboard(" now"); + await expect.element(page.getByText("Sending once image is ready")).not.toBeInTheDocument(); + await expect.element(editor).toHaveTextContent("check image now"); + + // Enter arms again; Esc cancels cleanly. + await userEvent.keyboard("{Enter}"); + await expect.element(page.getByText("Sending once image is ready")).toBeVisible(); + await userEvent.keyboard("{Escape}"); + await expect.element(page.getByText("Sending once image is ready")).not.toBeInTheDocument(); + + // Enter arms again; leaving the thread still sends once the image is ready. + await userEvent.keyboard("{Enter}"); + await expect.element(page.getByText("Sending once image is ready")).toBeVisible(); + await router.navigate({ to: `/${ENVIRONMENT_ID}/${other.id}` }); + await expect.element(page.getByText(`Answer 0 for upload-wait-other-${kind}.`)).toBeVisible(); + + compressed.resolve(); + await vi.waitFor(() => { + if (kind === "new") { + expect(launch.calls).toHaveLength(1); + } else { + expect(dispatchedCommands()).toContainEqual( + expect.objectContaining({ + type: "message.dispatch", + threadId: thread.id, + attachments: [expect.objectContaining({ type: "image", id: "upload-1" })], + }), + ); + } + }); + launch.release(); + }, +); + it("opens the thread actions menu for an older settled thread the shell leaves out", async () => { const thread = { ...threadWithHistory("older-settled", 1), olderSettled: true as const }; using _environment = installFakeEnvironment([thread]); diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index ea16d027fcfe9..254bbd4eb9e42 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -59,7 +59,9 @@ import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests"; import type { UsageLimitSourceSnapshots } from "@t3tools/contracts"; import { feedbackBannerItem } from "./chat/ComposerFeedback"; import { freshSessionBannerItem } from "./chat/ComposerFreshSession"; +import { heldComposerSendBannerItem } from "./chat/ComposerHeldSendBanner"; import { armFreshSession, disarmFreshSession, useFreshSessionArmed } from "./chat/freshSessionArms"; +import { cancelHeldComposerSend, useComposerSendHeld } from "./chat/preparingComposerImages"; import { useUsageLimitsPanel } from "./chat/useUsageLimitsPanel"; import { useWorktreeSetup } from "./chat/useWorktreeSetup"; import { useChatShortcuts } from "./chat/useChatShortcuts"; @@ -253,6 +255,7 @@ import { type ComposerFileAttachment, type ComposerImageAttachment, type DraftThreadEnvMode, + composerTargetKey, useComposerDraftStore, DraftId, } from "../composerDraftStore"; @@ -2658,7 +2661,16 @@ export default function ChatView(props: ChatViewProps) { // While a question or approval owns the composer, its text answers that, not the agent. const freshSessionCommandAvailable = freshSessionAvailable && activePendingApproval === null && pendingUserInputs.length === 0; - const toggleKeepFullHistory = () => setKeepFullHistory(routeThreadKey, !keepFullHistory); + const composerDraftTargetKey = composerTargetKey(composerDraftTarget); + const composerSendHeld = useComposerSendHeld(composerDraftTargetKey); + const cancelHeldSendStable = useStableCallback(() => { + cancelHeldComposerSend(composerDraftTargetKey); + focusComposerStable(); + }); + const toggleKeepFullHistory = () => { + cancelHeldComposerSend(composerDraftTargetKey); + setKeepFullHistory(routeThreadKey, !keepFullHistory); + }; const toggleKeepFullHistoryStable = useStableCallback(toggleKeepFullHistory); const armFreshSessionStable = useStableCallback(() => armFreshSession(routeThreadKey)); const handleRestoreThreadBranch = () => { @@ -2769,6 +2781,14 @@ export default function ChatView(props: ChatViewProps) { freshSessionPending && activePendingApproval === null ? [freshSessionBannerItem(() => disarmFreshSession(routeThreadKey), messages)] : []; + const heldSendItems = composerSendHeld + ? [ + heldComposerSendBannerItem( + { draftTarget: composerDraftTarget, onCancel: cancelHeldSendStable }, + messages, + ), + ] + : []; if (!localCheckoutBranchMismatch || !showBranchMismatchBanner || !activeBranchMismatchKey) { return [ ...feedbackBannerItems, @@ -2778,6 +2798,7 @@ export default function ChatView(props: ChatViewProps) { ...usageLimitsItems, ...projectCloneItems, ...freshSessionItems, + ...heldSendItems, ...systemComposerBannerItems, ]; } @@ -2789,6 +2810,7 @@ export default function ChatView(props: ChatViewProps) { ...usageLimitsItems, ...projectCloneItems, ...freshSessionItems, + ...heldSendItems, ...systemComposerBannerItems, branchMismatchBannerItem( { diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 6d4487adef153..6fb651c3471f6 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -252,6 +252,7 @@ import { useNavigate } from "@tanstack/react-router"; import { assistantCitationLabel } from "@t3tools/shared/assistantCitations"; import { assistantCitationNavigation } from "../../lib/assistantCitationNavigation"; import { Button } from "../ui/button"; +import { Spinner } from "../ui/spinner"; import { useManagedPolicy } from "../../state/managedPolicy"; import { hasProviderSetup } from "./ProviderStatusBanner"; import { type AppModelOption, getAppModelOptionsForInstance } from "../../modelSelection"; @@ -286,10 +287,13 @@ import { useComposerStash } from "./useComposerStash"; import { useComposerContextImport } from "./useComposerContextImport"; import { useComposerAttachmentIntake } from "./useComposerAttachmentIntake"; import { + cancelHeldComposerSend, countPreparingComposerImages, + useComposerSendHeld, usePreparingComposerImages, useSubmitAfterPreparingImages, } from "./preparingComposerImages"; +import { HELD_COMPOSER_SEND_BANNER_ID } from "./ComposerHeldSendBanner"; import { ComposerControlsBar } from "./ComposerControlsBar"; import { composerCommandKeyHandler } from "./composerCommandKey"; import { promptSuggestionToAccept, usePromptSuggestion } from "./usePromptSuggestion"; @@ -729,8 +733,18 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) uncommittedSnapShotIds, standaloneComposerImages, } = useComposerImageGroups(attachmentDraftTarget, composerImages, composerPreviewAnnotations); - const preparingComposerImages = usePreparingComposerImages(attachmentTargetKey).filter( - (image) => !image.hidden, + const allPreparingComposerImages = usePreparingComposerImages(attachmentTargetKey); + const preparingComposerImages = allPreparingComposerImages.filter((image) => !image.hidden); + // A message send waits for these itself; an answer waits in the composer below. + const messageHasPreparingImages = + questionAttachmentTarget === null && allPreparingComposerImages.length > 0; + const composerSendHeld = useComposerSendHeld(composerDraftTargetKey); + const cancelHeldSend = () => cancelHeldComposerSend(composerDraftTargetKey); + const handleMultipleModelSelectionsChangeStable = useStableCallback( + (next: React.SetStateAction | null>) => { + cancelHeldSend(); + setMultipleModelSelections(next); + }, ); const nonPersistedComposerImageIds = attachmentDraft.nonPersistedImageIds; const uploadsByImageId = useAttachmentUploadStore((state) => state.uploadsByImageId); @@ -1267,21 +1281,28 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) isComplete: Boolean(activePendingResolvedAnswers), } : null; + const hasMessageToSend = composerSendState.hasSendableContent || messageHasPreparingImages; const showResumeAction = - canResume && !composerDraftHasUserContent(composerDraft) && !isEditingQueuedMessage; + canResume && + !composerDraftHasUserContent(composerDraft) && + !messageHasPreparingImages && + !isEditingQueuedMessage; const collapsedComposerPrimaryActionDisabled = phase === "running" || isSendBusy || + composerSendHeld || isSendDisabled || noProviderAvailable || projectSelectionRequired || environmentUnavailable !== null || - (!composerSendState.hasSendableContent && !showResumeAction); - const collapsedComposerPrimaryActionLabel = showResumeAction - ? gt("Resume thread") - : props.resumeCompactionTokens !== null && !props.keepFullHistory - ? gt("Open composer to compact and send") - : gt("Send message"); + (!hasMessageToSend && !showResumeAction); + const collapsedComposerPrimaryActionLabel = composerSendHeld + ? gt("Sending when ready") + : showResumeAction + ? gt("Resume thread") + : props.resumeCompactionTokens !== null && !props.keepFullHistory + ? gt("Open composer to compact and send") + : gt("Send message"); const showMobilePendingAnswerActions = isMobileViewport && !isComposerCollapsedMobile && pendingPrimaryAction !== null; @@ -2196,7 +2217,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) if (activePendingProgress) { return activePendingProgress.isLastQuestion && Boolean(activePendingResolvedAnswers); } - return composerSendState.hasSendableContent; + return hasMessageToSend; }; const submitComposerRef = useRef< @@ -2282,9 +2303,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) event?.preventDefault(); return false; } - // Sending now would leave a still-compressing image out of the turn, so wait for it. + if (composerSendHeld) { + event?.preventDefault(); + return false; + } + // Sending now would leave a still-compressing image out of the answer, so wait for it. if ( activeThreadId && + questionAttachmentTarget && submitAfterPreparingImages(() => submitComposerRef.current(dispatchMode, submissionIntent)) ) { event?.preventDefault(); @@ -2467,8 +2493,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) ? promptSuggestion : null; - const onComposerCommandKey = (key: string, event: KeyboardEvent, isTaskItem?: boolean) => - composerCommandKeyHandler({ + const onComposerCommandKey = (key: string, event: KeyboardEvent, isTaskItem?: boolean) => { + if (key === "Escape" && composerSendHeld && !event.isComposing) { + cancelHeldSend(); + return true; + } + return composerCommandKeyHandler({ keybindings, getShortcutContext, sendShortcut: settings.sendShortcut, @@ -2507,6 +2537,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) promptSuggestion: offeredPromptSuggestion, dismissPromptSuggestion, })(key, event, isTaskItem); + }; const { stashQueue, @@ -2615,7 +2646,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) isSendBusy={isSendBusy} multipleModelsEnabled={routeKind === "draft" && supportsMultipleModels} multipleModelSelections={multipleModelSelections} - onMultipleModelSelectionsChange={setMultipleModelSelections} + onMultipleModelSelectionsChange={handleMultipleModelSelectionsChangeStable} selectedModelSelection={selectedModelSelection} onProviderModelSelect={onProviderModelSelect} activeThreadModelSelection={activeThreadModelSelection} @@ -2713,7 +2744,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const shelfItems = hasBlockingComposerTopDrawer ? bannerItems.filter( (item) => - item.group === "environment" && (item.variant === "error" || item.variant === "warning"), + item.id === HELD_COMPOSER_SEND_BANNER_ID || + (item.group === "environment" && + (item.variant === "error" || item.variant === "warning")), ) : bannerItems; @@ -3518,6 +3551,17 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
    { + if ( + event.key === "Escape" && + composerSendHeld && + !event.defaultPrevented && + !event.nativeEvent.isComposing + ) { + event.preventDefault(); + cancelHeldSend(); + } + }} onFocusCapture={(event) => { const activeElement = event.target; if ( @@ -3652,7 +3696,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) canOperateThread={canOperateThread} canInterrupt={canInterrupt} runId={activeThread?.runtime?.activeRunId ?? null} - hasSendableContent={composerSendState.hasSendableContent} + hasSendableContent={hasMessageToSend} isEditingQueuedMessage={isEditingQueuedMessage} onInterrupt={handleInterruptPrimaryActionStable} > @@ -3662,6 +3706,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) className="flex size-8 shrink-0 items-center justify-center rounded-full bg-message-action text-message-action-foreground hover:bg-message-action-hover disabled:opacity-64" disabled={collapsedComposerPrimaryActionDisabled} aria-label={collapsedComposerPrimaryActionLabel} + aria-busy={composerSendHeld || isSendBusy || undefined} onPointerDown={(event) => event.preventDefault()} onClick={(event) => { event.stopPropagation(); @@ -3671,7 +3716,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) else submitComposer(); }} > - {showResumeAction ? ( + {composerSendHeld || isSendBusy ? ( +
    @@ -575,7 +583,7 @@ function TopStatusIcon(props: { icon: keyof typeof TOP_STATUS_ICONS; className: type SidebarThreadRowProps = { thread: SidebarThreadSummary; // "folder" is a one-line row inside a boring sidebar project folder; - // "folder-multiline" adds the card's branch and PR line under it. + // "folder-multiline" adds the card's environment and PR line under it. variant: "card" | "slim" | "folder" | "folder-multiline"; navigationParent?: string | undefined; variantAction: SidebarSweepAction; @@ -598,10 +606,8 @@ type SidebarThreadRowProps = { // Read at click time; a prop would re-render every row on entering or leaving a thread route. readOpensPullRequestsInRightPanel: () => boolean; jumpLabel: string | null; - currentEnvironmentId: string | null; environmentLabel: string | null; environmentMachine: EnvironmentMachineKind; - scratchMachineLabel: string | null; project: EnvironmentProject | null; projectDisplayName: string | null; providerEntryByInstanceId: ReadonlyMap; @@ -863,9 +869,6 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP ? getTriggerDisplayModelName(selectedModel, providerEntry?.driverKind) : thread.modelSelection.model; - const isRemote = thread.environmentId !== props.currentEnvironmentId; - const showsScratchMachine = !checkoutThread.branch && props.scratchMachineLabel !== null; - const detailsTooltip = ( - - - ) : null; const diff = latestRunDiff(thread); // Only the trailing icons would remain, so the row moves them to the title line instead. const metaLineEmpty = - !checkoutThread.branch && - !showsScratchMachine && + props.environmentLabel === null && prBadge === null && issueBadge === null && diff === null && runningTerminalIds.length === 0; const metaLine = metaLineEmpty ? null : (
    - {checkoutThread.branch ? ( - <> - - - - - - ) : showsScratchMachine ? ( + {props.environmentLabel !== null ? ( <> - {props.scratchMachineLabel} + {props.environmentLabel} ) : ( @@ -1305,7 +1294,6 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP aria-hidden className="pointer-events-none ml-auto inline-flex shrink-0 items-center gap-1" > - {remoteMachineIcon} - {remoteMachineIcon} Date: Sun, 22 Nov 2026 00:52:35 -0800 Subject: [PATCH 117/324] fix: a failed checkpoint capture keeps Edit from here for conversation rewind (#40745) --- .../CheckpointCaptureService.test.ts | 17 ++++++++++ .../CheckpointRollbackService.test.ts | 31 ++++++++++++++++--- .../CheckpointRollbackService.ts | 4 ++- .../src/orchestration-v2/Orchestrator.ts | 3 +- .../src/orchestration-v2/ProjectionStore.ts | 4 +-- .../src/orchestration-v2/runtimeLayer.test.ts | 22 +++++++++++++ apps/web/src/session-logic.test.ts | 10 +++++- apps/web/src/session-logic.ts | 6 ++-- .../client-runtime/src/operations/commands.ts | 4 +-- 9 files changed, 86 insertions(+), 15 deletions(-) diff --git a/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts b/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts index aa85cd675dc1a..2110bc3eca027 100644 --- a/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts @@ -956,6 +956,23 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { scopeId: cancelledScopeId, }); assert.deepEqual(afterRewind.preservedCheckpointOrdinals, [0]); + + // A failed capture still records which run ended there; the next capture must keep that link. + yield* projectionStore.apply({ + id: EventId.make("event:checkpoint-capture-cancelled:captured-error"), + type: "checkpoint.captured", + threadId: cancelledThreadId, + runId: cancelledRunId, + nodeId: cancelledRootNodeId, + providerInstanceId, + occurredAt: cancelledAt, + payload: { ...captured, status: "error" }, + }); + const afterFailedCapture = yield* projectionStore.getCheckpointCaptureContext( + cancelledThreadId, + { runId: cancelledRunId, scopeId: cancelledScopeId }, + ); + assert.deepEqual([...afterFailedCapture.preservedCheckpointOrdinals].toSorted(), [0, 1]); }), ); diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts index 2f41a9a379306..ff368dccb64d9 100644 --- a/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts @@ -401,9 +401,14 @@ it.effect.each([ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); -it.effect.each([{ restoreFiles: true }, { restoreFiles: false }])( - "holds turn starts inside the worktree during rollback with restoreFiles $restoreFiles", - ({ restoreFiles }) => +it.effect.each([ + { restoreFiles: true, status: "ready" }, + { restoreFiles: false, status: "ready" }, + // A failed capture still pins the conversation. + { restoreFiles: false, status: "error" }, +])( + "holds turn starts inside the worktree during rollback with restoreFiles $restoreFiles to a $status checkpoint", + ({ restoreFiles, status }) => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -438,7 +443,7 @@ it.effect.each([{ restoreFiles: true }, { restoreFiles: false }])( providerInstanceId, }, providerSession: undefined, - checkpoint: { id: checkpointId, scopeId, status: "ready", appRunOrdinal: 0 }, + checkpoint: { id: checkpointId, scopeId, status, appRunOrdinal: 0 }, scope: { id: scopeId, cwd: worktreePath }, runsToRollback: [], targetAttempt: undefined, @@ -840,7 +845,7 @@ const seedRollbackHistory = Effect.gen(function* () { ), ), ); - const rollback = (ordinal: number) => + const rollback = (ordinal: number, restoreFiles?: boolean) => Effect.gen(function* () { const service = yield* CheckpointRollbackService.CheckpointRollbackServiceV2; yield* service.execute({ @@ -848,6 +853,7 @@ const seedRollbackHistory = Effect.gen(function* () { providerThreadId, scopeId, checkpointId: checkpointId(ordinal), + ...(restoreFiles === undefined ? {} : { restoreFiles }), }); }).pipe(Effect.provide(serviceLayer)); @@ -943,6 +949,21 @@ it.layer(ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMe }), ); + it.effect("rewinds the conversation to a run whose snapshot capture failed", () => + Effect.gen(function* () { + const history = yield* seedRollbackHistory; + const sql = yield* SqlClient.SqlClient; + yield* sql`UPDATE orchestration_v2_projection_checkpoints + SET status = 'error', payload_json = json_set(payload_json, '$.status', 'error') + WHERE checkpoint_id = ${history.checkpointId(2)}`; + + yield* history.rollback(2, false); + + assert.deepEqual(history.rollbackCounts, [4]); + assert.deepEqual(history.restored, []); + }), + ); + it.effect( "rewinds stopped runs repeatedly without counting discarded provider turns again", () => diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts index 6f9fe79cfde3b..8d6fd1c09441d 100644 --- a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts +++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts @@ -178,8 +178,10 @@ export const layer: Layer.Layer< // A repository's checkpoints follow the thread's; they are not a place to rewind to. typeof scope.repositoryPath === "string" || checkpoint.scopeId !== scope.id || - // Missing snapshots support conversation rewind, and restoring a task folder's repositories. + // Missing or failed snapshots support conversation rewind; missing ones also restoring a + // task folder's repositories. (checkpoint.status !== "ready" && + !(checkpoint.status === "error" && !restoreFiles) && !(checkpoint.status === "missing" && (!restoreFiles || linkedProjectFolder))) ) { return yield* invalidTarget(); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 995ff63b25747..61f5027793569 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -14534,9 +14534,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio targetCheckpoint.appRunOrdinal ?? 0, ) !== null, ); - // Missing snapshots otherwise support conversation rewind only. + // Missing or failed snapshots otherwise support conversation rewind only. if ( targetCheckpoint.status !== "ready" && + !(targetCheckpoint.status === "error" && command.restoreFiles === false) && !( targetCheckpoint.status === "missing" && (command.restoreFiles === false || restoresRepositories) diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 6c8308706b651..a42679d304765 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -6379,7 +6379,7 @@ export const layer: Layer.Layer = runRows[0] === undefined ? undefined : yield* decodeRunPayload(runRows[0].payload_json); - const preservedCheckpoint = sql`(status = 'ready' OR (status = 'missing' AND run_id IS NOT NULL))`; + const preservedCheckpoint = sql`(status = 'ready' OR (status IN ('missing', 'error') AND run_id IS NOT NULL))`; const [ nodeRows, scopeRows, @@ -6491,7 +6491,7 @@ export const layer: Layer.Layer = checkpoint === undefined || scope === undefined || checkpoint.scopeId !== scope.id || - (checkpoint.status !== "ready" && checkpoint.status !== "missing") || + checkpoint.status === "stale" || providerThread.id !== thread.activeProviderThreadId || providerThread.providerInstanceId !== thread.modelSelection.instanceId ) diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index b5072355659ef..843e51da40423 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -1878,6 +1878,28 @@ it.layer(layerTest)("OrchestrationV2LayerLive", (it) => { [], ); assert.deepEqual(yield* outbox.listByCommandId(commandId), []); + if (status === "error") { + // A failed capture still pins the conversation. + const conversationCommandId = CommandId.make("runtime-rollback-error-conversation"); + const conversationOnly = yield* orchestrator.dispatch({ + type: "checkpoint.rollback", + commandId: conversationCommandId, + threadId, + checkpointId, + scopeId: scope.id, + restoreFiles: false, + }); + assert.deepEqual( + conversationOnly.storedEvents.map((stored) => stored.event.type), + ["thread.metadata-updated", "checkpoint.rollback-requested"], + ); + assert.deepEqual( + (yield* outbox.listByCommandId(conversationCommandId)).map( + (effect) => effect.request.type, + ), + ["provider-thread.rollback"], + ); + } } } }).pipe(Effect.provide(Layer.fresh(layerTest))), diff --git a/apps/web/src/session-logic.test.ts b/apps/web/src/session-logic.test.ts index f4670665add6c..2155fedaa83c1 100644 --- a/apps/web/src/session-logic.test.ts +++ b/apps/web/src/session-logic.test.ts @@ -290,7 +290,10 @@ describe("V2 session presentation", () => { }, }; }); - const checkpoint = (ordinal: number, status: "ready" | "missing" | "stale" = "ready") => ({ + const checkpoint = ( + ordinal: number, + status: "ready" | "missing" | "stale" | "error" = "ready", + ) => ({ runId: runId(ordinal), checkpointTurnCount: ordinal, checkpointRef: `checkpoint-${ordinal}` as never, @@ -326,6 +329,11 @@ describe("V2 session presentation", () => { "user-1": 0, "user-2": 1, }); + // A failed snapshot capture still pins the conversation; only file restore needs one. + expect(targets([1, 2], [checkpoint(1, "error")])).toEqual({ + "user-1": 0, + "user-2": 1, + }); }); it("preserves a notification-only wake run while ignoring inherited and unrelated work", () => { diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts index 1122c3122aca0..5196ee43458d8 100644 --- a/apps/web/src/session-logic.ts +++ b/apps/web/src/session-logic.ts @@ -1153,10 +1153,10 @@ export function deriveRevertTurnCountByUserMessageId(input: { return byUserMessageId; } -// A missing snapshot (no git, or a side chat) still pins a conversation position; only -// restoring files needs a ready one. +// A missing or failed snapshot (no git, a side chat, a capture error) still pins a +// conversation position; only restoring files needs a ready one. function isRewindableCheckpoint(checkpoint: Pick) { - return checkpoint.status === "ready" || checkpoint.status === "missing"; + return checkpoint.status !== "stale"; } export function findRevertCheckpoint( diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts index 50e1449e3d5fc..0ea95420460a7 100644 --- a/packages/client-runtime/src/operations/commands.ts +++ b/packages/client-runtime/src/operations/commands.ts @@ -1074,9 +1074,9 @@ export const revertThreadCheckpoint = Effect.fn("EnvironmentCommands.revertThrea ); if ( checkpoint === undefined || - // Missing snapshots support conversation rewind only. + // Missing or failed snapshots support conversation rewind only. (checkpoint.status !== "ready" && - !(input.restoreFiles === false && checkpoint.status === "missing")) + !(input.restoreFiles === false && checkpoint.status !== "stale")) ) { const target = input.checkpointId === undefined From 15a3daa32a745bc56be9d7dbb346d80661e6b7bd Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 01:00:28 -0800 Subject: [PATCH 118/324] docs(claude): mobile shows the compact chip too (#40755) --- docs/user/providers-claude.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/user/providers-claude.md b/docs/user/providers-claude.md index 84c13d30c4c84..00b27e02ae23d 100644 --- a/docs/user/providers-claude.md +++ b/docs/user/providers-claude.md @@ -63,8 +63,8 @@ When you return to a large thread after Claude's prompt cache expires, a **Compact** chip with the thread's token count shows next to the send button. While it is on, Enter summarizes the history first, then sends your message. Click the chip to switch it to **Keep** and keep the full -history for that message. The mobile app shows no chip: an eligible message sent -from it summarizes first. The cache lasts about an hour on a Claude +history for that message. The mobile app shows the same chip, labelled with the +token count: tap it to keep the full history for that message. The cache lasts about an hour on a Claude subscription and 5 minutes with an API key, Bedrock, or Vertex. See [commands and skills](./composer.md#commands-and-skills) for using composer commands. From e3f9db2447fcfd82e76f7782ca5254e2c7ad80a6 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 01:08:22 -0800 Subject: [PATCH 119/324] fix(server): TanStack Source pull requests open from every client, and private ones work end to end (#40741) --- .../pull-requests/PullRequestListRow.tsx | 12 ++ .../pull-requests/PullRequestRouteScreen.tsx | 11 ++ .../pull-requests/pullRequestGlyphs.ts | 1 + .../features/pull-requests/pullRequestList.ts | 1 + apps/mobile/src/i18n/translations/de.json | 1 + apps/mobile/src/i18n/translations/en.json | 1 + apps/mobile/src/i18n/translations/es.json | 1 + apps/mobile/src/i18n/translations/fr.json | 1 + apps/mobile/src/i18n/translations/ja.json | 1 + apps/mobile/src/i18n/translations/ko.json | 1 + apps/mobile/src/i18n/translations/pt-BR.json | 1 + apps/mobile/src/i18n/translations/ru.json | 1 + apps/mobile/src/i18n/translations/sv.json | 1 + apps/mobile/src/i18n/translations/zh.json | 1 + apps/server/src/git/GitManager.test.ts | 133 ++++++++++++++++ apps/server/src/git/GitManager.ts | 144 +++++++++++++++++- .../toolkits/pullRequests/handlers.test.ts | 15 +- .../src/mcp/toolkits/pullRequests/handlers.ts | 2 + .../src/mcp/toolkits/pullRequests/tools.ts | 8 + .../src/provider/agentContextBudget.json | 2 +- .../src/pullRequest/PullRequestService.ts | 4 + .../SourceControlProviderRegistry.ts | 9 ++ .../pullRequest/PullRequestDetailLayout.tsx | 29 +++- .../pullRequest/PullRequestDetailPanel.tsx | 2 + .../components/pullRequest/PullRequestRow.tsx | 4 + docs/user/source-control.md | 4 +- packages/contracts/src/pullRequest.ts | 8 + .../src/server/PullRequestProvider.ts | 3 + .../src/server/SourceControlProvider.ts | 14 ++ .../TanStackSourcePullRequestProvider.test.ts | 138 +++++++++++++++++ ...anStackSourceSourceControlProvider.test.ts | 107 ++++++++++++- .../TanStackSourceSourceControlProvider.ts | 46 +++++- .../src/server/tanStackSourceHosts.test.ts | 19 +++ .../src/server/tanStackSourceHosts.ts | 16 +- .../src/server/tanStackSourceJson.test.ts | 1 + .../src/server/tanStackSourceJson.ts | 27 +++- .../src/shared/definition.test.ts | 16 ++ .../src/shared/definition.ts | 19 ++- 38 files changed, 774 insertions(+), 31 deletions(-) create mode 100644 packages/source-control-tanstack-source/src/server/TanStackSourcePullRequestProvider.test.ts create mode 100644 packages/source-control-tanstack-source/src/server/tanStackSourceHosts.test.ts diff --git a/apps/mobile/src/features/pull-requests/PullRequestListRow.tsx b/apps/mobile/src/features/pull-requests/PullRequestListRow.tsx index 5daf5ef20565b..7b904c8e33105 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestListRow.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestListRow.tsx @@ -122,6 +122,7 @@ export const PullRequestListRow = memo( ), item.title, status.label, + item.visibility === "private" ? gt("Private") : null, conflict ? conflict.label.toLowerCase() : null, gt("by {author}", { author: item.author?.login ?? gt("unknown author") }), review ? review.accessibleLabel : null, @@ -178,6 +179,17 @@ export const PullRequestListRow = memo( {item.repository} #{item.number} + {item.visibility === "private" ? ( + + + + ) : null} {item.stack ? ( {status.label} )} + {"visibility" in pr && pr.visibility === "private" ? ( + + + {gt("Private")} + + ) : null} {"changedFiles" in pr && pr.changedFiles !== undefined ? ( diff --git a/apps/mobile/src/features/pull-requests/pullRequestGlyphs.ts b/apps/mobile/src/features/pull-requests/pullRequestGlyphs.ts index fa79d882cc23d..16b84c596d627 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestGlyphs.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestGlyphs.ts @@ -7,4 +7,5 @@ export const PullRequestGlyph = { merged: "arrow.triangle.merge", stack: "square.3.layers.3d", conflicting: "exclamationmark.triangle", + private: { ios: "lock.fill", android: "lock" }, } as const satisfies Record; diff --git a/apps/mobile/src/features/pull-requests/pullRequestList.ts b/apps/mobile/src/features/pull-requests/pullRequestList.ts index e7c2f5de769c4..3b30c11d65e64 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestList.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestList.ts @@ -190,6 +190,7 @@ export function pullRequestListRowsAreEqual( previous.title === next.title && previous.url === next.url && previous.state === next.state && + previous.visibility === next.visibility && previous.isDraft === next.isDraft && previous.mergeability === next.mergeability && previous.baseBranch === next.baseBranch && diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index f538b87920412..039e1ddadd0bf 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -2851,6 +2851,7 @@ "f9d3c8aa453829ce": "Tippe auf eine Person, um ein Review anzufordern. Tippe auf einen angefragten Reviewer, um die Anfrage zu entfernen. Änderungen werden beim Schließen dieses Fensters gesendet.", "8d3770f150f0bcb4": "Angefragt", "fff1c3d17603f394": "Dieser Anbieter akzeptiert eine Reviewer-ID, kann aber keine Kandidaten auflisten.", + "bbb7d40a7ad7ab71": "Privat", "85ae9979ad3b0c1e": "Basis-Branch {branch} kopieren", "06a684782801e8f7": "Head-Branch {branch} kopieren", "8e4f3c862193b8a5": "Bearbeiten", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 745201ad99094..91170171c1621 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -2851,6 +2851,7 @@ "f9d3c8aa453829ce": "Tap someone to request a review. Tap a requested reviewer to remove the request. Changes are sent when you close this sheet.", "8d3770f150f0bcb4": "Requested", "fff1c3d17603f394": "This provider accepts a reviewer ID but cannot list candidates.", + "bbb7d40a7ad7ab71": "Private", "85ae9979ad3b0c1e": "Copy base branch {branch}", "06a684782801e8f7": "Copy head branch {branch}", "8e4f3c862193b8a5": "Edit", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index fb134339cd3c4..398c20ce17f1f 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -2847,6 +2847,7 @@ "f9d3c8aa453829ce": "Toca a alguien para solicitarle una revisión. Toca a un revisor solicitado para quitar la solicitud. Los cambios se envían al cerrar esta hoja.", "8d3770f150f0bcb4": "Solicitado", "fff1c3d17603f394": "Este proveedor acepta un ID de revisor, pero no puede listar candidatos.", + "bbb7d40a7ad7ab71": "Privado", "85ae9979ad3b0c1e": "Copiar la rama base {branch}", "06a684782801e8f7": "Copiar la rama head {branch}", "8e4f3c862193b8a5": "Editar", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index d6aef220df3a2..1734d91934a04 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -2847,6 +2847,7 @@ "f9d3c8aa453829ce": "Touchez une personne pour lui demander une revue. Touchez un relecteur sollicité pour retirer la demande. Les modifications sont envoyées à la fermeture de ce panneau.", "8d3770f150f0bcb4": "Sollicité", "fff1c3d17603f394": "Ce fournisseur accepte un ID de relecteur mais ne peut pas lister les candidats.", + "bbb7d40a7ad7ab71": "Privé", "85ae9979ad3b0c1e": "Copier la branche de base {branch}", "06a684782801e8f7": "Copier la branche de tête {branch}", "8e4f3c862193b8a5": "Modifier", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index 8cd9fba5c8332..113ada551f17d 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -2844,6 +2844,7 @@ "f9d3c8aa453829ce": "ユーザーをタップするとレビューをリクエストします。リクエスト済みのレビュアーをタップするとリクエストを削除します。変更はこのシートを閉じたときに送信されます。", "8d3770f150f0bcb4": "リクエスト済み", "fff1c3d17603f394": "このプロバイダーはレビュアー ID を受け付けますが、候補を一覧表示できません。", + "bbb7d40a7ad7ab71": "プライベート", "85ae9979ad3b0c1e": "ベースブランチ {branch} をコピー", "06a684782801e8f7": "ヘッドブランチ {branch} をコピー", "8e4f3c862193b8a5": "編集", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index 731eaeecaec22..7768bd410d434 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -2848,6 +2848,7 @@ "f9d3c8aa453829ce": "검토를 요청하려면 사람을 탭하세요. 요청을 제거하려면 요청된 검토자를 탭하세요. 변경 사항은 이 시트를 닫을 때 전송됩니다.", "8d3770f150f0bcb4": "요청됨", "fff1c3d17603f394": "이 제공자는 검토자 ID를 받지만 후보를 나열할 수 없습니다.", + "bbb7d40a7ad7ab71": "비공개", "85ae9979ad3b0c1e": "기준 브랜치 {branch} 복사", "06a684782801e8f7": "헤드 브랜치 {branch} 복사", "8e4f3c862193b8a5": "편집", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 2c4ee1bc64fc4..88dbb8da5cd87 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -2847,6 +2847,7 @@ "f9d3c8aa453829ce": "Toque em alguém para solicitar uma revisão. Toque em um revisor solicitado para remover a solicitação. As alterações são enviadas quando você fecha esta folha.", "8d3770f150f0bcb4": "Solicitado", "fff1c3d17603f394": "Este provedor aceita um ID de revisor, mas não consegue listar candidatos.", + "bbb7d40a7ad7ab71": "Privado", "85ae9979ad3b0c1e": "Copiar branch base {branch}", "06a684782801e8f7": "Copiar branch head {branch}", "8e4f3c862193b8a5": "Editar", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index c4f78e560083b..2d0fb55302031 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -2899,6 +2899,7 @@ "f9d3c8aa453829ce": "Нажмите на человека, чтобы запросить ревью. Нажмите на запрошенного ревьюера, чтобы отменить запрос. Изменения отправляются при закрытии этой панели.", "8d3770f150f0bcb4": "Запрошен", "fff1c3d17603f394": "Этот провайдер принимает ID ревьюера, но не может показать список кандидатов.", + "bbb7d40a7ad7ab71": "Приватный", "85ae9979ad3b0c1e": "Копировать базовую ветку {branch}", "06a684782801e8f7": "Копировать head-ветку {branch}", "8e4f3c862193b8a5": "Изменить", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index fa3a3dd6d039f..70617afd183ca 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -2851,6 +2851,7 @@ "f9d3c8aa453829ce": "Tryck på någon för att begära en granskning. Tryck på en begärd granskare för att ta bort begäran. Ändringarna skickas när du stänger det här bladet.", "8d3770f150f0bcb4": "Begärd", "fff1c3d17603f394": "Leverantören accepterar ett granskar-id men kan inte lista kandidater.", + "bbb7d40a7ad7ab71": "Privat", "85ae9979ad3b0c1e": "Kopiera basgrenen {branch}", "06a684782801e8f7": "Kopiera huvudgrenen {branch}", "8e4f3c862193b8a5": "Redigera", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index f36e76805c298..485d4206bf054 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -2848,6 +2848,7 @@ "f9d3c8aa453829ce": "轻点某人以请求审查。轻点已请求的审查者以移除请求。关闭此面板时会发送更改。", "8d3770f150f0bcb4": "已请求", "fff1c3d17603f394": "此提供方接受审查者 ID,但无法列出候选人。", + "bbb7d40a7ad7ab71": "私有", "85ae9979ad3b0c1e": "复制基础分支 {branch}", "06a684782801e8f7": "复制头部分支 {branch}", "8e4f3c862193b8a5": "编辑", diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index 94247273e1ca0..1bce13cb0f020 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -86,6 +86,8 @@ interface FakeProviderScenario { kind?: string; /** False for a host that opens every change request ready for review. */ createsDraftChangeRequests?: boolean; + /** The companion repository of a host with private change requests. */ + privateRemote?: { readonly url: string; readonly repository: string }; /** Answers to successive change request listings, whatever their head selector. */ prListSequence?: ReadonlyArray>; prListByHeadSelector?: Record>; @@ -124,6 +126,7 @@ type FakeProviderCall = readonly headSelector: string; readonly title: string; readonly draft: unknown; + readonly private?: boolean; } | { readonly operation: "getChangeRequest"; readonly reference: string } | { @@ -483,6 +486,9 @@ function createFakeSourceControlProvider(scenario: FakeProviderScenario = {}): { service: { kind, createsDraftChangeRequests: scenario.createsDraftChangeRequests ?? true, + ...(scenario.privateRemote === undefined + ? {} + : { privateChangeRequestRemote: () => Effect.succeed(scenario.privateRemote!) }), ...headBranchProbe, listChangeRequests: (input) => record(input.cwd, { @@ -517,6 +523,7 @@ function createFakeSourceControlProvider(scenario: FakeProviderScenario = {}): { headSelector: input.headSelector, title: input.title, draft: "draft" in input ? input.draft : undefined, + ...(input.private === undefined ? {} : { private: input.private }), }), getDefaultBranch: (input) => record(input.cwd, { operation: "getDefaultBranch" }).pipe( @@ -5106,6 +5113,132 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { }), ); + it.effect( + "createPullRequest opens a private PR from the companion and never pushes to origin", + () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const originDir = yield* createBareRemote(); + const companionDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", originDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "main"]); + yield* runGit(repoDir, ["checkout", "-b", "sec/fix"]); + NodeFS.writeFileSync(NodePath.join(repoDir, "fix.txt"), "fix\n"); + yield* runGit(repoDir, ["add", "fix.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Fix"]); + const heads = (remote: string) => + runGit(repoDir, ["ls-remote", "--heads", remote]).pipe( + Effect.map((result) => + result.stdout + .split("\n") + .flatMap((line) => (line ? [line.split("\t")[1]] : [])) + .toSorted(), + ), + ); + const createPrivate = (manager: GitManager.GitManager["Service"]) => + manager.createPullRequest({ + cwd: repoDir, + projectId: ProjectId.make("project-1"), + title: "Fix", + body: "Body", + private: true, + }); + + // A host without private pull requests refuses before anything is pushed. + const unsupported = yield* makeManager({ providerScenario: { prListSequence: [[]] } }); + const refused = yield* Effect.flip(createPrivate(unsupported.manager)); + expect(refused.message).toContain("has no private pull requests"); + expect(yield* heads("origin")).toEqual(["refs/heads/main"]); + expect(created(unsupported.providerCalls)).toEqual([]); + + const privateRemote = { url: companionDir, repository: "pingdotgg/codething-mvp.private" }; + const open = { + number: 9, + title: "Fix", + url: "https://source.tanstack.com/@pingdotgg/codething-mvp/pull/9", + baseRefName: "main", + headRefName: "sec/fix", + headRepositoryNameWithOwner: privateRemote.repository, + }; + const supported = yield* makeManager({ + providerScenario: { privateRemote, prListSequence: [[], [open]] }, + }); + expect(yield* createPrivate(supported.manager)).toMatchObject({ + status: "created", + number: 9, + }); + expect(yield* heads(companionDir)).toEqual(["refs/heads/sec/fix"]); + expect(yield* heads("origin")).toEqual(["refs/heads/main"]); + // The branch tracks the companion, which is how status finds its pull request. + expect( + (yield* runGit(repoDir, [ + "rev-parse", + "--abbrev-ref", + "sec/fix@{upstream}", + ])).stdout.trim(), + ).toBe("pingdotgg/sec/fix"); + expect( + (yield* runGit(repoDir, ["config", "--get", "branch.sec/fix.pushRemote"])).stdout.trim(), + ).toBe("pingdotgg"); + expect( + supported.providerCalls.flatMap((call) => + call.operation === "createChangeRequest" ? [call] : [], + ), + ).toMatchObject([{ baseRefName: "main", headSelector: "sec/fix", private: true }]); + + // Later commits follow the recorded push remote. + NodeFS.writeFileSync(NodePath.join(repoDir, "late.txt"), "late\n"); + yield* runGit(repoDir, ["add", "late.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Late"]); + const again = yield* makeManager({ + providerScenario: { privateRemote, prListSequence: [[open]] }, + }); + expect(yield* createPrivate(again.manager)).toMatchObject({ + status: "opened_existing", + number: 9, + }); + const localHead = (yield* runGit(repoDir, ["rev-parse", "HEAD"])).stdout.trim(); + expect( + (yield* runGit(repoDir, ["ls-remote", companionDir, "refs/heads/sec/fix"])).stdout, + ).toContain(localHead); + expect(yield* heads("origin")).toEqual(["refs/heads/main"]); + expect(created(again.providerCalls)).toEqual([]); + + // A lookup answered before the create must not hide the pull request the create returns. + yield* runGit(repoDir, ["checkout", "-b", "sec/two", "main"]); + NodeFS.writeFileSync(NodePath.join(repoDir, "two.txt"), "two\n"); + yield* runGit(repoDir, ["add", "two.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Two"]); + const two = { ...open, number: 10, headRefName: "sec/two" }; + const warmed = yield* makeManager({ + providerScenario: { privateRemote, prListByHeadSelector: { "sec/two": [two] } }, + }); + const lookup = warmed.manager.branchPullRequest({ cwd: repoDir, branch: "sec/two" }); + expect(yield* lookup).toBeNull(); + expect(yield* createPrivate(warmed.manager)).toMatchObject({ status: "opened_existing" }); + expect(yield* lookup).toMatchObject({ number: 10 }); + yield* runGit(repoDir, ["checkout", "sec/fix"]); + + // So does a create that forgets to ask for private: it never publishes the branch. + NodeFS.writeFileSync(NodePath.join(repoDir, "later.txt"), "later\n"); + yield* runGit(repoDir, ["add", "later.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Later"]); + const forgetful = yield* makeManager({ + providerScenario: { privateRemote, prListOtherwise: [open] }, + }); + yield* Effect.exit( + forgetful.manager.createPullRequest({ + cwd: repoDir, + projectId: ProjectId.make("project-1"), + title: "Fix", + body: "Body", + }), + ); + expect(yield* heads("origin")).toEqual(["refs/heads/main"]); + }), + ); + it.effect("createPullRequest pushes to the push remote and never to the base branch", () => Effect.gen(function* () { const repoDir = yield* makeTempDir("t3code-git-manager-"); diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index db62af1f79b69..dedf2d19f54ed 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -199,6 +199,12 @@ export class GitManager extends Context.Service< readonly body: string; readonly baseBranch?: string | undefined; readonly draft?: boolean | undefined; + /** + * Opens it where only people with write access see it. The branch goes to the host's + * private companion repository and never to the repository itself. Fails on a host + * without private pull requests. + */ + readonly private?: boolean | undefined; }) => Effect.Effect; readonly subscribePullRequestStateChanges: Effect.Effect< Stream.Stream, @@ -2881,9 +2887,131 @@ export const make = Effect.gen(function* () { }), ); - const createPullRequest: GitManager["Service"]["createPullRequest"] = Effect.fn( - "GitManager.createPullRequest", - )(function* (input) { + const openPrivatePullRequest = Effect.fn("GitManager.openPrivatePullRequest")(function* ( + input: Parameters[0], + ) { + const { cwd } = input; + const provider = yield* sourceControlProvider(cwd); + const definition = sourceControlDefinitions.get(provider.kind); + const terms = definition.changeRequest; + const fail = (detail: string, cause?: unknown) => + new GitManagerError({ + operation: "createPullRequest", + cwd, + detail, + ...(cause === undefined ? {} : { cause }), + }); + if (provider.privateChangeRequestRemote === undefined) { + return yield* fail( + `${definition.label} has no private ${terms.plural}. Nothing was pushed. Leave out private to open a public one.`, + ); + } + const status = yield* gitCore.statusDetails(cwd); + const branch = status.branch; + if (!branch) return yield* fail("Cannot create a pull request from detached HEAD."); + const resolved = yield* resolvePrBase(cwd, branch, status.upstreamRef, { + isCrossRepository: false, + remoteName: publishedRemoteName( + yield* readConfigValueNullable(cwd, `branch.${branch}.remote`), + ), + }); + const baseBranch = input.baseBranch ?? resolved.baseBranch; + if (baseBranch === branch) { + return yield* fail( + `${branch} is the base branch. Check out a feature branch to create ${terms.shortLabelWithArticle}.`, + ); + } + const companion = yield* provider.privateChangeRequestRemote({ cwd }); + const remoteName = yield* gitCore.ensureRemote({ + cwd, + preferredName: companion.repository.split("/")[0] || "private", + url: companion.url, + }); + // Recorded before the push, so a later push of this branch, by T3 or by plain `git push`, + // goes to the companion too and never publishes the branch. + yield* gitCore.writeConfigValue({ + cwd, + key: `branch.${branch}.pushRemote`, + value: remoteName, + }); + yield* gitCore + .execute({ + operation: "GitManager.openPrivatePullRequest.push", + cwd, + args: ["push", "--", remoteName, `refs/heads/${branch}:refs/heads/${branch}`], + timeoutMs: null, + }) + .pipe( + Effect.mapError((cause) => + fail(`Could not push ${branch} to ${companion.repository}: ${cause.detail}`, cause), + ), + Effect.tapError(() => invalidateStatus(cwd)), + ); + // The companion branch is the pull request's head, so status finds it through the upstream. + yield* gitCore + .setBranchUpstream({ cwd, branch, remoteName, remoteBranch: branch }) + .pipe(Effect.ensuring(invalidateStatus(cwd))); + const findOpen = provider + .listChangeRequests({ cwd, headSelector: branch, state: "open" }) + .pipe( + Effect.map( + (listed) => + listed.find( + (pr) => + pr.headRefName === branch && + pr.headRepositoryNameWithOwner?.toLowerCase() === + companion.repository.toLowerCase(), + ) ?? null, + ), + ); + const existing = yield* findOpen; + if (existing) { + return { + status: "opened_existing" as const, + url: existing.url, + number: existing.number, + baseBranch: existing.baseRefName, + headBranch: existing.headRefName, + title: existing.title, + }; + } + const bodyFile = path.join( + tempDir, + `t3code-pr-body-${process.pid}-${yield* randomUUIDv4(cwd)}.md`, + ); + yield* fileSystem + .writeFileString(bodyFile, input.body) + .pipe( + Effect.mapError((cause) => fail("Failed to write pull request body temp file.", cause)), + ); + yield* provider + .createChangeRequest({ + cwd, + baseRefName: baseBranch, + headSelector: branch, + title: input.title, + bodyFile, + private: true, + ...(input.draft === true ? { draft: true } : {}), + }) + .pipe( + Effect.ensuring(fileSystem.remove(bodyFile).pipe(Effect.ignore)), + Effect.ensuring(invalidateStatus(cwd)), + ); + // The PR already exists at this point, so a failed lookup only loses its metadata. + const created = yield* findOpen.pipe(Effect.orElseSucceed(() => null)); + return { + status: "created" as const, + ...(created ? { url: created.url, number: created.number } : {}), + baseBranch: created?.baseRefName ?? baseBranch, + headBranch: created?.headRefName ?? branch, + title: created?.title ?? input.title, + }; + }); + + const pushAndOpenPullRequest = Effect.fn("GitManager.pushAndOpenPullRequest")(function* ( + input: Parameters[0], + ) { const status = yield* gitCore.statusDetails(input.cwd); const needsPush = yield* createPrNeedsPush(input.cwd, status); if (needsPush && status.branch) { @@ -2935,6 +3063,16 @@ export const make = Effect.gen(function* () { : Effect.void, ), ); + return result; + }); + + const createPullRequest: GitManager["Service"]["createPullRequest"] = Effect.fn( + "GitManager.createPullRequest", + )(function* (input) { + const result = + input.private === true + ? yield* openPrivatePullRequest(input) + : yield* pushAndOpenPullRequest(input); const openedAsDraft = result.status === "created" && (yield* sourceControlProvider(input.cwd)).createsDraftChangeRequests === true; diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts index b7edff187579d..7caa425d32f2e 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts @@ -837,6 +837,7 @@ describe("source control tools", () => { body: "Adds tools.", state: "open", isDraft: false, + visibility: "private", author: null, headBranch: "tools", baseBranch: "main", @@ -892,6 +893,7 @@ describe("source control tools", () => { }); const compact = yield* harness.call("pull_request_read", {}); expect(compact).toMatchObject({ + visibility: "private", headSha: "abc123", checks: { passed: 2, pending: 1, failed: ["Lint", "E2E"], incomplete: true }, unresolvedThreads: 1, @@ -1178,7 +1180,11 @@ describe("source control tools", () => { it.effect("opens a PR from the thread's worktree and links it even if dismissed", () => Effect.gen(function* () { - const opened: Array<{ readonly cwd: string; readonly draft: boolean | undefined }> = []; + const opened: Array<{ + readonly cwd: string; + readonly draft: boolean | undefined; + readonly private: boolean | undefined; + }> = []; const harness = yield* makeHarness({ thread: { ...makeThread([makeLink(43, { source: "stack-dismissed" })]), @@ -1186,7 +1192,9 @@ describe("source control tools", () => { }, git: { createPullRequest: (input) => - Effect.sync(() => opened.push({ cwd: input.cwd, draft: input.draft })).pipe( + Effect.sync(() => + opened.push({ cwd: input.cwd, draft: input.draft, private: input.private }), + ).pipe( Effect.as({ status: "created" as const, url: "https://github.com/t3tools/t3code/pull/43", @@ -1202,9 +1210,10 @@ describe("source control tools", () => { title: "Add tools", body: "Adds tools.", draft: true, + private: true, }); expect(result).toMatchObject({ number: 43, created: true }); - expect(opened).toEqual([{ cwd: "/workspace/worktree", draft: true }]); + expect(opened).toEqual([{ cwd: "/workspace/worktree", draft: true, private: true }]); expect(yield* Ref.get(harness.commands)).toMatchObject([ { type: "thread.pull-request.link", number: 43, source: "created" }, ]); diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts index f85d8f0abac4a..e422a799f3d9a 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts @@ -617,6 +617,7 @@ const make = Effect.gen(function* () { title: detail.title, state: detail.state, isDraft: detail.isDraft, + ...(detail.visibility === undefined ? {} : { visibility: detail.visibility }), author: detail.author?.login ?? null, headBranch: detail.headBranch, baseBranch: detail.baseBranch, @@ -1052,6 +1053,7 @@ const make = Effect.gen(function* () { body: input.body, baseBranch: input.base, draft: input.draft, + private: input.private, }) .pipe(Effect.mapError(forgeFailure)); if (created.url === undefined) { diff --git a/apps/server/src/mcp/toolkits/pullRequests/tools.ts b/apps/server/src/mcp/toolkits/pullRequests/tools.ts index 71d0a28d4e392..847ae4ef19e7d 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/tools.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/tools.ts @@ -16,6 +16,7 @@ import { PullRequestReviewGuideRun, PullRequestState, PullRequestUnavailableError, + PullRequestVisibility, PullRequestWatchUntil, ThreadPullRequestLinkSource, TrimmedNonEmptyString, @@ -517,6 +518,9 @@ export const ReadPullRequestResult = Schema.Struct({ title: Schema.String, state: PullRequestState, isDraft: Schema.Boolean, + visibility: Schema.optional(PullRequestVisibility).annotate({ + description: "Only on a host with private PRs.", + }), author: Schema.NullOr(Schema.String), headBranch: Schema.String, baseBranch: Schema.String, @@ -675,6 +679,10 @@ const CreatePullRequestTool = Tool.make("pull_request_create", { body: Schema.String, base: Schema.optional(TrimmedNonEmptyString), draft: Schema.optional(Schema.Boolean), + private: Schema.optional(Schema.Boolean).annotate({ + description: + "Visible to writers only; the branch never reaches origin. Fails on a host without private PRs.", + }), }), success: CreatePullRequestResult, failure: PullRequestToolError, diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 139eba175bc8a..9ec6f6509f48c 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 6245, "codexAdditionalContextBytes": 7639, - "mcpToolListJsonBytes": 59052 + "mcpToolListJsonBytes": 59192 } diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts index e30938735c765..59ece029219df 100644 --- a/apps/server/src/pullRequest/PullRequestService.ts +++ b/apps/server/src/pullRequest/PullRequestService.ts @@ -1370,6 +1370,7 @@ export const make = Effect.gen(function* () { ...(input.item.checksState === undefined || input.item.checksState === null ? {} : { checksState: input.item.checksState }), + ...(input.item.visibility === undefined ? {} : { visibility: input.item.visibility }), viewerReviewRequested: input.item.author?.login.toLowerCase() !== viewer && input.item.reviewRequestLogins.some((login) => login.toLowerCase() === viewer), @@ -1993,6 +1994,9 @@ export const make = Effect.gen(function* () { ...(changeRequest.mergeQueueRemoval === undefined ? {} : { mergeQueueRemoval: changeRequest.mergeQueueRemoval }), + ...(changeRequest.visibility === undefined + ? {} + : { visibility: changeRequest.visibility }), })), ), ), diff --git a/apps/server/src/sourceControl/SourceControlProviderRegistry.ts b/apps/server/src/sourceControl/SourceControlProviderRegistry.ts index 06616a914b1e9..98c560cbf4973 100644 --- a/apps/server/src/sourceControl/SourceControlProviderRegistry.ts +++ b/apps/server/src/sourceControl/SourceControlProviderRegistry.ts @@ -222,6 +222,15 @@ function bindProviderContext( context: input.context ?? context, }); }), + ...(provider.privateChangeRequestRemote === undefined + ? {} + : { + privateChangeRequestRemote: (input) => + provider.privateChangeRequestRemote!({ + ...input, + context: input.context ?? context, + }), + }), getRepositoryCloneUrls: Effect.fnUntraced(function* (input) { return yield* provider.getRepositoryCloneUrls({ ...input, diff --git a/apps/web/src/components/pullRequest/PullRequestDetailLayout.tsx b/apps/web/src/components/pullRequest/PullRequestDetailLayout.tsx index a797a7984cbce..250240d2849fa 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailLayout.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailLayout.tsx @@ -1,12 +1,39 @@ import { useGT } from "gt-react"; -import { ArrowLeftIcon, FileDiffIcon } from "lucide-react"; +import { ArrowLeftIcon, FileDiffIcon, LockIcon } from "lucide-react"; import { useEffect, useRef, type ComponentProps, type ReactNode } from "react"; import { cn } from "~/lib/utils"; +import { Badge } from "../ui/badge"; import { Toggle, ToggleGroup } from "../ui/toggle-group"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { PullRequestMetaLine } from "./pullRequestPresentation"; +export function PullRequestPrivateMark({ className }: { className?: string }) { + const gt = useGT(); + const label = gt("Private"); + return ( + + } + /> + {label} + + ); +} + +export function PullRequestPrivateBadge() { + const gt = useGT(); + return ( + + + + {gt("Private")} + + + ); +} + export function PullRequestDetailHeaderBody({ title, author, diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx index cbf9de56dbbb2..1e14ab19d9012 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx @@ -90,6 +90,7 @@ import { MiddleTruncate } from "../ui/middle-truncate"; import { PullRequestChecksStatusLine, PullRequestDetailHeaderBody, + PullRequestPrivateBadge, PullRequestDetailTabBar, } from "./PullRequestDetailLayout"; import { PullRequestDetailGhost, PullRequestTimelineGhost } from "./PullRequestGhosts"; @@ -1578,6 +1579,7 @@ export function PullRequestDetailPanel({
    {detail ? ( + {detail.visibility === "private" ? : null} {context === "page" ? ( + {entry.visibility === "private" ? ( + + ) : null} {entry.checksState === undefined ? null : ( ; readonly reviewDecision?: PullRequestReviewDecision | null | undefined; readonly checksState?: PullRequestChecksState | null | undefined; + /** Absent where the host has no private change requests or names no visibility. */ + readonly visibility?: PullRequestVisibility; } export interface ProviderChangeRequestSummary { diff --git a/packages/source-control-core/src/server/SourceControlProvider.ts b/packages/source-control-core/src/server/SourceControlProvider.ts index 4a6e93ab74f45..ccf23f59b2258 100644 --- a/packages/source-control-core/src/server/SourceControlProvider.ts +++ b/packages/source-control-core/src/server/SourceControlProvider.ts @@ -173,6 +173,18 @@ export class SourceControlProvider extends Context.Service< }) => Effect.Effect; /** True when `createChangeRequest` opens the change request as a draft when asked. */ readonly createsDraftChangeRequests?: boolean; + /** + * The private companion of the checkout's repository, made when it has none. The branch of + * a private change request is pushed to `url` and never to the repository itself, which + * everyone can read. Absent on a host without private change requests. + */ + readonly privateChangeRequestRemote?: (input: { + readonly cwd: string; + readonly context?: SourceControlProviderContext; + }) => Effect.Effect< + { readonly url: string; readonly repository: string }, + SourceControlProviderError + >; readonly listChangeRequests: (input: { readonly cwd: string; readonly context?: SourceControlProviderContext; @@ -202,6 +214,8 @@ export class SourceControlProvider extends Context.Service< readonly bodyFile: string; /** Honored only by a provider with `createsDraftChangeRequests`. */ readonly draft?: boolean; + /** Asked only of a provider with `privateChangeRequestRemote`, which holds the head. */ + readonly private?: boolean; }) => Effect.Effect; readonly getRepositoryCloneUrls: (input: { readonly cwd: string; diff --git a/packages/source-control-tanstack-source/src/server/TanStackSourcePullRequestProvider.test.ts b/packages/source-control-tanstack-source/src/server/TanStackSourcePullRequestProvider.test.ts new file mode 100644 index 0000000000000..838309b037617 --- /dev/null +++ b/packages/source-control-tanstack-source/src/server/TanStackSourcePullRequestProvider.test.ts @@ -0,0 +1,138 @@ +import { assert, describe, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as HttpClient from "effect/http/HttpClient"; + +import * as TanStackSourceApi from "./TanStackSourceApi.ts"; +import * as Credentials from "./TanStackSourceCredentials.ts"; +import * as TanStackSourcePullRequestProvider from "./TanStackSourcePullRequestProvider.ts"; + +const HOST = "source.tanstack.com"; + +/** + * Shaped like `GET /pulls/{n}` of a private pull request: its head is `owner:branch` in the + * companion repository, and Source has stored no file or line counts for it. + */ +const PRIVATE_PULL = { + number: 42, + title: "Fix the thing", + state: "open", + visibility: "private", + draft: false, + author: "bob", + head: "acme:fix/thing", + createdAt: 1_000, + body: null, + base: "main", + headRepo: "acme/web.private", + headSha: "c".repeat(40), + baseSha: "b".repeat(40), + mergeCommitSha: null, + mergedAt: null, + mergedBy: null, + mergeable: null, + changedFiles: null, + changedLines: null, +}; + +const FILES = { + baseSha: "b".repeat(40), + headSha: "c".repeat(40), + mergeBaseSha: "b".repeat(40), + available: true, + truncated: false, + files: [ + { path: "a.ts", status: "modified", additions: 3, deletions: 1 }, + { path: "b.ts", status: "added", additions: 4, deletions: 0 }, + ], +}; + +const RESPONSES: Record = { + "/repos/acme/web/pulls/42": PRIVATE_PULL, + "/repos/acme/web/pulls/42/files": FILES, + "/repos/acme/web/pulls/42/checks": { checks: [], upToDate: null, mayMerge: true }, + "/repos/acme/web/pulls/42/stack": { members: [] }, + [`/repos/acme/web/check-runs?sha=${"c".repeat(40)}`]: [], + "/repos/acme/web/ci/runs?pull=42&limit=30": { items: [], next: null }, + "/repos/acme/web/issues/42": { + timeline: [ + { id: 1, comment: "Looks good", author: "alice", at: 2_000 }, + { event: "head_updated", actor: "bob", at: 3_000 }, + ], + next: null, + }, + "/repos/acme/web/pulls/42/comments": [], + "/repos/acme/web/pulls/42/commits": { + baseSha: null, + headSha: null, + mergeBaseSha: null, + available: true, + commits: [], + }, + "/user": { username: "alice" }, +}; + +const api = TanStackSourceApi.TanStackSourceApi.of({ + request: (input) => + input.path in RESPONSES + ? Effect.succeed(JSON.stringify(RESPONSES[input.path])) + : Effect.die(`unexpected ${input.path}`), + response: () => Effect.die("unexpected response read"), +}); + +const provider = TanStackSourcePullRequestProvider.make.pipe( + Effect.provideService(TanStackSourceApi.TanStackSourceApi, api), + Effect.provideService( + Credentials.TanStackSourceCredentials, + Credentials.TanStackSourceCredentials.of({ + get: () => Effect.die("unexpected credential read"), + invalidate: () => Effect.void, + }), + ), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make(() => Effect.die("unexpected http request")), + ), +); + +describe("TanStackSourcePullRequestProvider.getChangeRequest", () => { + // A client without this host's definition percent-encodes the owner's `@`; stored links + // keep the web's own spelling. + it.effect.each(["acme/web", "@acme/web", "%40acme/web"])( + "reads a private pull request of %s", + (repository) => + Effect.gen(function* () { + const detail = yield* (yield* provider).getChangeRequest({ + host: HOST, + repository, + number: 42, + cwd: "/repo", + }); + assert.strictEqual(detail.url, `https://${HOST}/@acme/web/pull/42`); + assert.strictEqual(detail.visibility, "private"); + assert.strictEqual(detail.headBranch, "fix/thing"); + assert.strictEqual(detail.headRepositoryNameWithOwner, "acme/web.private"); + // Source stores no counts for it, so they come from its files. + assert.deepStrictEqual( + [detail.changedFiles, detail.additions, detail.deletions], + [2, 7, 1], + ); + }), + ); +}); + +describe("TanStackSourcePullRequestProvider.getChangeRequestActivity", () => { + it.effect("reads the comments of a timeline that also holds events", () => + Effect.gen(function* () { + const activity = yield* (yield* provider).getChangeRequestActivity({ + host: HOST, + repository: "acme/web", + number: 42, + cwd: "/repo", + }); + assert.deepStrictEqual( + activity.comments.map((comment) => comment.body), + ["Looks good"], + ); + }), + ); +}); diff --git a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts index 509e03e1f41f4..0529ce6df17c7 100644 --- a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts +++ b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts @@ -35,6 +35,8 @@ const PULL = { function checkout(options: { readonly recordedOwner: string | null; readonly isAncestor: boolean; + readonly pull?: Partial; + readonly force?: boolean; }) { const git: Array = []; const config = new Map( @@ -43,14 +45,28 @@ function checkout(options: { const api = TanStackSourceApi.TanStackSourceApi.of({ request: (input) => input.path === "/repos/acme/web/pulls/42" - ? Effect.succeed(JSON.stringify(PULL)) + ? Effect.succeed(JSON.stringify({ ...PULL, ...options.pull })) : Effect.die(`unexpected ${input.path}`), response: () => Effect.die("unexpected response read"), }); const host = TestSourceControlHost.layer({ git: { resolvePrimaryRemoteName: () => Effect.succeed("origin"), - ensureRemote: () => Effect.succeed("origin"), + ensureRemote: (input) => + Effect.sync(() => { + git.push(`remote ${input.preferredName} ${input.url}`); + return input.url === REMOTE ? "origin" : input.preferredName; + }), + fetchRemoteBranch: (input) => + Effect.sync( + () => + void git.push(`fetch ${input.remoteName} ${input.remoteBranch}:${input.localBranch}`), + ), + fetchRemoteTrackingBranch: () => Effect.void, + setBranchUpstream: (input) => + Effect.sync( + () => void git.push(`upstream ${input.branch} ${input.remoteName}/${input.remoteBranch}`), + ), readConfigValue: (_cwd, key) => Effect.succeed(key === "remote.origin.url" ? REMOTE : (config.get(key) ?? null)), writeConfigValue: (input) => Effect.sync(() => void config.set(input.key, input.value)), @@ -86,7 +102,13 @@ function checkout(options: { }, }); const run = TanStackSourceSourceControlProvider.make.pipe( - Effect.flatMap((provider) => provider.checkoutChangeRequest({ cwd: "/repo", reference: "42" })), + Effect.flatMap((provider) => + provider.checkoutChangeRequest({ + cwd: "/repo", + reference: "42", + ...(options.force === undefined ? {} : { force: options.force }), + }), + ), Effect.provideService(TanStackSourceApi.TanStackSourceApi, api), Effect.provide(Layer.merge(host, FileSystem.layerNoop({}))), ); @@ -129,4 +151,83 @@ describe("TanStackSourceSourceControlProvider.checkoutChangeRequest", () => { assert.isFalse(git.some((command) => command.startsWith("checkout"))); }); }); + + // Source publishes no `refs/pull//head` for a private pull request, on either repository. + it.effect("takes a private pull request's branch from the companion repository", () => { + const pull = { head: "acme:fix-thing", headRepo: "acme/web.private" }; + const { run, git, config } = checkout({ recordedOwner: null, isAncestor: true, pull }); + const forced = checkout({ recordedOwner: null, isAncestor: true, pull, force: true }); + return Effect.gen(function* () { + yield* forced.run; + assert.include(forced.git, "checkout --no-track -B fix-thing refs/remotes/acme/fix-thing --"); + yield* run; + assert.strictEqual(config.get("branch.fix-thing.pushRemote"), "acme"); + assert.deepStrictEqual(git, [ + `remote source ${REMOTE}`, + "remote acme https://source.tanstack.com/@acme/web.private.git", + "fetch acme fix-thing:fix-thing", + "upstream fix-thing acme/fix-thing", + "switch fix-thing", + ]); + }); + }); +}); + +describe("TanStackSourceSourceControlProvider private pull requests", () => { + it.effect("asks Source for the companion and opens the pull request as private", () => { + const requests: Array<{ method: string; path: string; body: unknown }> = []; + const api = TanStackSourceApi.TanStackSourceApi.of({ + request: (input) => { + requests.push({ method: input.method ?? "GET", path: input.path, body: input.body }); + return Effect.succeed( + JSON.stringify({ + owner: "acme", + name: "web.private", + defaultBranch: null, + cloneUrl: "https://source.tanstack.com/@acme/web.private.git", + }), + ); + }, + response: () => Effect.die("unexpected response read"), + }); + const files = FileSystem.layerNoop({ readFileString: () => Effect.succeed("Body") }); + return Effect.gen(function* () { + const provider = yield* TanStackSourceSourceControlProvider.make; + const companion = provider.privateChangeRequestRemote; + assert.isDefined(companion); + assert.deepStrictEqual(yield* companion({ cwd: "/repo" }), { + url: "https://source.tanstack.com/@acme/web.private.git", + repository: "acme/web.private", + }); + yield* provider.createChangeRequest({ + cwd: "/repo", + baseRefName: "main", + headSelector: "sec/fix", + title: "Fix", + bodyFile: "/tmp/body.md", + private: true, + }); + assert.deepStrictEqual(requests, [ + { method: "POST", path: "/repos/acme/web/private-remote", body: undefined }, + { + method: "POST", + path: "/repos/acme/web/pulls", + body: { title: "Fix", head: "sec/fix", base: "main", body: "Body", private: true }, + }, + ]); + }).pipe( + Effect.provideService(TanStackSourceApi.TanStackSourceApi, api), + Effect.provide( + Layer.merge( + TestSourceControlHost.layer({ + git: { + resolvePrimaryRemoteName: () => Effect.succeed("origin"), + readConfigValue: () => Effect.succeed(REMOTE), + }, + }), + files, + ), + ), + ); + }); }); diff --git a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts index a1abb376b472d..f194848611361 100644 --- a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts +++ b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts @@ -395,6 +395,18 @@ export const make = Effect.gen(function* () { }, ), createsDraftChangeRequests: true, + privateChangeRequestRemote: Effect.fn( + "TanStackSourceSourceControlProvider.privateChangeRequestRemote", + )(function* (input) { + const target = yield* resolveTarget("privateChangeRequestRemote", input); + const companion = yield* read( + "privateChangeRequestRemote", + input.cwd, + { host: target.host, method: "POST", path: `/repos/${target.repository}/private-remote` }, + Repository, + ); + return { url: companion.cloneUrl, repository: `${companion.owner}/${companion.name}` }; + }), createChangeRequest: Effect.fn("TanStackSourceSourceControlProvider.createChangeRequest")( function* (input) { const target = yield* resolveTarget("createChangeRequest", { @@ -437,6 +449,7 @@ export const make = Effect.gen(function* () { base: input.target?.refName ?? input.baseRefName, ...(body.trim().length === 0 ? {} : { body }), ...(input.draft === true ? { draft: true } : {}), + ...(input.private === true ? { private: true } : {}), }, }) .pipe( @@ -494,7 +507,8 @@ export const make = Effect.gen(function* () { return repository.defaultBranch; }, ), - // Every pull request's head is published as `refs/pull//head`, forks and GitHub sync too. + // A pull request's head is published as `refs/pull//head`, forks and GitHub sync too. A + // private one has no such ref: its branch is read from the companion repository. checkoutChangeRequest: Effect.fn("TanStackSourceSourceControlProvider.checkoutChangeRequest")( function* (input) { const pull = yield* getPull(input); @@ -519,9 +533,26 @@ export const make = Effect.gen(function* () { }); const operation = "TanStackSourceSourceControlProvider.checkoutChangeRequest"; const branches = yield* git.listLocalBranchNames(input.cwd); - if (!pull.isCrossRepository) { + const companion = + pullRepository !== null && + pull.headRepositoryNameWithOwner?.toLowerCase() === + `${pullRepository}.private`.toLowerCase() + ? pull.headRepositoryNameWithOwner + : null; + if (!pull.isCrossRepository || companion !== null) { const localBranch = pull.headRefName; - const remoteBranch = { cwd: input.cwd, remoteName, remoteBranch: localBranch }; + const remoteBranch = { + cwd: input.cwd, + remoteName: + companion === null + ? remoteName + : yield* git.ensureRemote({ + cwd: input.cwd, + preferredName: companion.split("/")[0] ?? "private", + url: `${Hosts.webRepositoryUrl(HOST, companion)}.git`, + }), + remoteBranch: localBranch, + }; if (input.force !== true && !branches.includes(localBranch)) yield* git.fetchRemoteBranch({ ...remoteBranch, localBranch }); else yield* git.fetchRemoteTrackingBranch(remoteBranch); @@ -535,11 +566,18 @@ export const make = Effect.gen(function* () { "--no-track", "-B", localBranch, - `refs/remotes/${remoteName}/${localBranch}`, + `refs/remotes/${remoteBranch.remoteName}/${localBranch}`, "--", ], }); yield* git.setBranchUpstream({ ...remoteBranch, branch: localBranch }); + // Whatever push defaults say, this branch must not be published to the public remote. + if (companion !== null) + yield* git.writeConfigValue({ + cwd: input.cwd, + key: `branch.${localBranch}.pushRemote`, + value: remoteBranch.remoteName, + }); yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch })); return; } diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.test.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.test.ts new file mode 100644 index 0000000000000..ac43a46ccdcad --- /dev/null +++ b/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { tanStackSourceRepositoryPath } from "./tanStackSourceHosts.ts"; + +describe("tanStackSourceRepositoryPath", () => { + it.each([ + ["acme/web", "acme/web"], + ["@acme/web", "acme/web"], + // Clients without this host's definition percent-encode the owner's `@`. + ["%40acme/web", "acme/web"], + ["/@acme/web.git/", "acme/web"], + ["acme/web.private", "acme/web.private"], + ["acme", null], + ["acme/web/extra", null], + ["acme/..", null], + ])("reads %s as %s", (path, repository) => { + expect(tanStackSourceRepositoryPath(path)).toBe(repository); + }); +}); diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.ts index 22923264629bf..dfa6d4e9031a0 100644 --- a/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.ts +++ b/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.ts @@ -1,4 +1,4 @@ -import { TANSTACK_SOURCE_HOST } from "../shared/definition.ts"; +import { TANSTACK_SOURCE_HOST, withoutOwnerMark } from "../shared/definition.ts"; export const TANSTACK_SOURCE_HOSTS = [TANSTACK_SOURCE_HOST] as const; export type TanStackSourceHost = (typeof TANSTACK_SOURCE_HOSTS)[number]; @@ -10,14 +10,14 @@ export function tanStackSourceHost(host: string): TanStackSourceHost | null { const SEGMENT = /^[A-Za-z0-9_.-]+$/u; -/** `owner/name` from the API spelling or the web spelling `@owner/name`, `.git` dropped. */ +/** `owner/name` from the API spelling or either web spelling of the owner, `.git` dropped. */ export function tanStackSourceRepositoryPath(path: string): string | null { - const [owner, name, ...rest] = path - .trim() - .replace(/^\/+|\/+$/gu, "") - .replace(/\.git$/u, "") - .replace(/^@/u, "") - .split("/"); + const [owner, name, ...rest] = withoutOwnerMark( + path + .trim() + .replace(/^\/+|\/+$/gu, "") + .replace(/\.git$/u, ""), + ).split("/"); return rest.length === 0 && owner !== undefined && name !== undefined && diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceJson.test.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceJson.test.ts index 4d698fb881dfb..24c93e6aac83d 100644 --- a/packages/source-control-tanstack-source/src/server/tanStackSourceJson.test.ts +++ b/packages/source-control-tanstack-source/src/server/tanStackSourceJson.test.ts @@ -146,6 +146,7 @@ describe("toActivity", () => { ["4", "review-comment", null], ]); expect(activity.comments[0]?.url).toBe(`https://${HOST}/@TanStack/ai/pull/9#comment-1`); + expect(Json.pullUrl(HOST, "%40TanStack/ai", 9)).toBe(`https://${HOST}/@TanStack/ai/pull/9`); expect(activity.reviewThreads).toMatchObject([ { id: "4", path: "a.ts", line: 2, side: "left", isResolved: true }, ]); diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceJson.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceJson.ts index acf3c4158f95c..51537627ca3e7 100644 --- a/packages/source-control-tanstack-source/src/server/tanStackSourceJson.ts +++ b/packages/source-control-tanstack-source/src/server/tanStackSourceJson.ts @@ -16,6 +16,8 @@ import type { import * as DateTime from "effect/DateTime"; import * as Schema from "effect/Schema"; +import { withoutOwnerMark } from "../shared/definition.ts"; + /** Source sends times as epoch milliseconds. */ const EpochMillis = Schema.Finite; const Login = Schema.String; @@ -29,6 +31,7 @@ export const SourcePull = Schema.Struct({ labels: Schema.optional(Schema.Array(Schema.String)), head: Schema.String, createdAt: EpochMillis, + visibility: Schema.optional(Schema.String), }); export type SourcePull = typeof SourcePull.Type; @@ -135,7 +138,8 @@ const TimelineEntry = Schema.Struct({ type TimelineEntry = typeof TimelineEntry.Type; export const SourceTimeline = Schema.Struct({ - timeline: Schema.Array(TimelineEntry), + // Events such as `head_updated` sit between the comments and carry no id. + timeline: Schema.Array(Schema.Union([TimelineEntry, Schema.Struct({ event: Schema.String })])), next: Schema.NullOr(Schema.String), }); @@ -239,10 +243,20 @@ export const SourceUser = Schema.Struct({ username: Schema.String }); export const iso = (millis: number) => DateTime.formatIso(DateTime.makeUnsafe(millis)); export const pullUrl = (host: string, repository: string, number: number) => - `https://${host}/@${repository}/pull/${number}`; + `https://${host}/@${withoutOwnerMark(repository)}/pull/${number}`; -/** A GitHub-synced pull request from a fork names its head only by its pull ref. */ -export const headBranchName = (head: string) => head.replace(/^refs\/heads\//u, ""); +/** + * A GitHub-synced pull request from a fork names its head only by its pull ref, and a private + * one as `owner:branch`. A branch name holds no colon, so the owner is all that one can precede. + */ +export const headBranchName = (head: string) => + head.replace(/^refs\/heads\//u, "").replace(/^[^/:]+:/u, ""); + +/** Absent when Source names no visibility, so a reader tells unknown from public. */ +const visibilityOf = (pull: Pick) => + pull.visibility === "private" || pull.visibility === "public" + ? { visibility: pull.visibility } + : {}; export function toActor(login: string | null, host: string): PullRequestActor | null { if (login === null || login.trim() === "") return null; @@ -280,6 +294,7 @@ export function toChangeRequest( baseBranch: pull.base ?? "", state: pull.state, isDraft: pull.draft, + ...visibilityOf(pull), mergeability: "unknown", additions: 0, deletions: 0, @@ -380,7 +395,9 @@ export function toActivity(input: { }): ProviderChangeRequestActivity { const { host } = input; const page = pullUrl(host, input.repository, input.number); - const entries = input.timeline.timeline.filter(visible); + const entries = input.timeline.timeline.filter( + (entry): entry is TimelineEntry => "id" in entry && visible(entry), + ); const comments: Array = entries.map((entry: TimelineEntry) => ({ id: String(entry.id), kind: diff --git a/packages/source-control-tanstack-source/src/shared/definition.test.ts b/packages/source-control-tanstack-source/src/shared/definition.test.ts index e3ce5c867fa5c..6e09a89fa2cda 100644 --- a/packages/source-control-tanstack-source/src/shared/definition.test.ts +++ b/packages/source-control-tanstack-source/src/shared/definition.test.ts @@ -31,7 +31,23 @@ describe("TanStack Source definition", () => { number: 7, }), ).toBe("https://source.tanstack.com/@TanStack/router/pull/7"); + // A stored link or an older client may name the repository as the web spells it. + for (const repository of ["@TanStack/router", "%40TanStack/router"]) + expect( + definition.changeRequestUrl({ host: "source.tanstack.com", repository, number: 7 }), + repository, + ).toBe("https://source.tanstack.com/@TanStack/router/pull/7"); expect(definition.checkoutCommandArgument("src pr checkout 7")).toBe("7"); expect(definition.checkoutCommandArgument("gh pr checkout 7")).toBeNull(); }); + + it.each(["tanstack/router", "@tanstack/router", "%40tanstack/router"])( + "keys %s as the API's owner/name", + (repository) => { + expect(definition.canonicalRepositoryKey?.(`source.tanstack.com/${repository}`)).toBe( + "source.tanstack.com/tanstack/router", + ); + expect(definition.canonicalRepositoryKey?.(`github.com/${repository}`)).toBeNull(); + }, + ); }); diff --git a/packages/source-control-tanstack-source/src/shared/definition.ts b/packages/source-control-tanstack-source/src/shared/definition.ts index 1aee00c968dc6..032adc5a45cdd 100644 --- a/packages/source-control-tanstack-source/src/shared/definition.ts +++ b/packages/source-control-tanstack-source/src/shared/definition.ts @@ -37,6 +37,20 @@ function parseChangeRequestUrl(url: URL) { : { ...link, repositoryUrl: `${url.origin}/@${CHANGE_REQUEST_PATH.exec(url.pathname)![1]}` }; } +/** + * `owner/name` as the API names it. The web spells it `@owner/name`, and a client without this + * definition percent-encodes that as `%40owner/name`. + */ +export const withoutOwnerMark = (repository: string) => repository.replace(/^(?:@|%40)/iu, ""); + +/** Links stored with the web's spelling compare equal to the project's own key. */ +function canonicalRepositoryKey(key: string): string | null { + const slash = key.indexOf("/"); + return slash > 0 && isTanStackSourceHost(key.slice(0, slash)) + ? `${TANSTACK_SOURCE_HOST}/${withoutOwnerMark(key.slice(slash + 1))}` + : null; +} + /** Keys drop the owner's `@`, so a project's repository is `owner/name` as the API names it. */ function repositoryKeyFromRemote(key: string): string | null { // Remote parsing spells the `@` percent-encoded. @@ -80,13 +94,13 @@ export const definition = defineSourceControl({ ? null : webUrl ? changeRequestUrlBelow(webUrl, `pull/${number}`) - : `https://${host}/@${repository.replace(/^@/u, "")}/pull/${number}`, + : `https://${host}/@${withoutOwnerMark(repository)}/pull/${number}`, parseChangeRequestUrl, commitUrl: (input) => buildCommitUrl( input.webUrl ? input - : { ...input, webUrl: `https://${input.host}/@${input.repository.replace(/^@/u, "")}` }, + : { ...input, webUrl: `https://${input.host}/@${withoutOwnerMark(input.repository)}` }, "commit", ), parseIssueUrl: (url) => @@ -122,6 +136,7 @@ export const definition = defineSourceControl({ checkoutChangeRequestHost: () => null, changeRequestHeadRef: (number) => `refs/pull/${number}/head`, repositoryKeyFromRemote, + canonicalRepositoryKey, recognizeRemote: ({ hostname }) => isTanStackSourceHost(hostname) ? { kind: KIND, name: "TanStack Source", baseUrl: `https://${TANSTACK_SOURCE_HOST}` } From 976aca331aa15d41f4383def7afeafcfcab5575e Mon Sep 17 00:00:00 2001 From: Wu Shuwen Date: Sun, 22 Nov 2026 17:08:53 +0800 Subject: [PATCH 120/324] fix: include delegated threads in CLI listing (#40738) Co-authored-by: Julius Marminge --- apps/server/src/cli/thread.test.ts | 97 ++++++++++++++++++++++++++++++ apps/server/src/cli/thread.ts | 6 +- 2 files changed, 101 insertions(+), 2 deletions(-) diff --git a/apps/server/src/cli/thread.test.ts b/apps/server/src/cli/thread.test.ts index 7231ea7f2b3e0..49887ee0bb7cc 100644 --- a/apps/server/src/cli/thread.test.ts +++ b/apps/server/src/cli/thread.test.ts @@ -53,6 +53,103 @@ vi.mock("../auth/EnvironmentAuth.ts", async (importOriginal) => { const threadId = ThreadId.make("thread-1"); const runId = RunId.make("run-1"); +it.effect("list includes delegated threads across pages and still leaves out subagents", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-thread-list-" }); + yield* persistServerRuntimeState({ + path: path.join(baseDir, "userdata", "server-runtime.json"), + state: yield* makePersistedServerRuntimeState({ + config: { host: "127.0.0.1", devUrl: undefined }, + port: 3_773, + }), + }); + const projectId = ProjectId.make("project-1"); + const item = (id: string) => ({ + threadId: id, + projectId, + title: id, + createdBy: "user", + creationSource: "web", + status: "idle", + latestRunId: null, + providerInstanceId: "codex", + model: "test", + runtimeMode: "full-access", + interactionMode: "default", + linkedPullRequest: null, + settled: false, + settledAt: null, + snoozed: false, + snoozedUntil: null, + parentThreadId: null, + relationshipToParent: null, + itemCount: 0, + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + }); + const root = item("root"); + const delegated = { + ...item("delegated"), + delegatedFrom: { environmentId: "env-1", threadId: "remote", title: "Remote" }, + }; + const subagent = { ...item("child"), parentThreadId: "root", relationshipToParent: "subagent" }; + using _session = vi.spyOn(McpBridge, "mcpToolSession").mockReturnValue( + Effect.succeed({ + call: (tool, args) => { + if (tool === "t3_project_list") + return Effect.succeed({ + structuredContent: { + projects: [{ id: projectId, title: "Project", workspaceRoot: baseDir }], + nextCursor: null, + }, + }); + if (tool === "t3_thread_list") { + const all = args.includeSubagents ? [root, subagent, delegated] : [root]; + const cursor = Number(args.cursor); + return Effect.succeed({ + structuredContent: { + projectId, + currentThreadId: null, + threads: all.slice(cursor, cursor + 2), + nextCursor: cursor + 2 < all.length ? cursor + 2 : null, + total: all.length, + }, + }); + } + return Effect.die(`unexpected ${tool} call`); + }, + }), + ); + yield* Command.runWith(threadCommand, { version: "0.0.0" })([ + "list", + "--project", + projectId, + "--json", + "--base-dir", + baseDir, + ]); + const listed = JSON.parse(String((yield* TestConsole.logLines).at(-1))) as Array<{ + threadId: string; + }>; + assert.deepStrictEqual( + listed.map((entry) => entry.threadId), + ["root", "delegated"], + ); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + NetService.layer, + ConfigProvider.layer(ConfigProvider.fromEnv({ env: { T3CODE_PORT: "3773" } })), + ), + ), + ), +); + it.effect( "start resolves home-relative project paths while preserving ids and relative paths", () => diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts index 8849f10c6a5ec..e63e762237e85 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -850,10 +850,12 @@ const threadListCommand = Command.make("list", { while (cursor !== null) { const page: OrchestratorMcpThreadListResult = yield* tools.call( "t3_thread_list", - { projectId: project.id, includeSubagents: false, limit: 100, cursor }, + { projectId: project.id, includeSubagents: true, limit: 100, cursor }, OrchestratorMcpThreadListResult, ); - threads.push(...page.threads); + threads.push( + ...page.threads.filter((thread) => thread.relationshipToParent !== "subagent"), + ); cursor = page.nextCursor; } if (flags.json) { From bcace0787ee37f4e4dd9a1f68b7be8f871934926 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 01:23:15 -0800 Subject: [PATCH 121/324] fix(pi): turn token usage counts cached tokens as input and stays per turn (#40758) --- .../testkit/fixtures/simple/pi_output.ts | 55 +++++++++------ .../provider-pi/src/server/adapter.test.ts | 56 ++++++++++++++++ packages/provider-pi/src/server/adapter.ts | 67 ++++++++++++------- 3 files changed, 133 insertions(+), 45 deletions(-) diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/simple/pi_output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/simple/pi_output.ts index c7579914964ee..bed80f2be65ef 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/simple/pi_output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/simple/pi_output.ts @@ -24,32 +24,45 @@ function lastPiResponseData(transcript: ProviderReplayTranscript, command: strin return field(frame, "data"); } -/** Settled Pi usage uses each recorded get_session_stats response in order, not the last streaming total. */ +/** + * Settled Pi usage takes the context size from each turn's get_session_stats response and the + * input breakdown from the turn's last streamed message usage, since stats tokens are session totals. + */ export function assertPiSettledTokenUsage( result: OrchestratorV2ScenarioResult, transcript: ProviderReplayTranscript, ) { - const stats = transcript.entries.flatMap((entry) => - entry.type === "emit_inbound" && - field(entry.frame, "type") === "response" && - field(entry.frame, "command") === "get_session_stats" - ? [field(entry.frame, "data")] - : [], - ); - const turns = projectionFor(result, transcript.scenario).providerTurns; - assert.lengthOf(turns, stats.length); - for (const [index, turn] of turns.entries()) { - const contextUsage = field(stats[index], "contextUsage"); - const tokens = field(stats[index], "tokens"); - const { updatedAt: _updatedAt, ...tokenUsage } = turn.tokenUsage ?? { updatedAt: "" }; - assert.deepEqual(tokenUsage, { - usedTokens: field(contextUsage, "tokens"), - maxTokens: field(contextUsage, "contextWindow"), - inputTokens: field(tokens, "input"), - cachedInputTokens: field(tokens, "cacheRead"), - outputTokens: field(tokens, "output"), - }); + const expected: Array> = []; + let messageUsage: unknown; + for (const entry of transcript.entries) { + if (entry.type !== "emit_inbound") continue; + const usage = field(entry.frame, "usage"); + if (field(entry.frame, "type") === "message_update" && field(usage, "totalTokens") !== 0) { + messageUsage = usage; + } + if ( + field(entry.frame, "type") === "response" && + field(entry.frame, "command") === "get_session_stats" + ) { + const contextUsage = field(field(entry.frame, "data"), "contextUsage"); + const count = (key: string) => Number(field(messageUsage, key)); + expected.push({ + usedTokens: field(contextUsage, "tokens"), + maxTokens: field(contextUsage, "contextWindow"), + inputTokens: count("input") + count("cacheRead") + count("cacheWrite"), + cachedInputTokens: count("cacheRead"), + outputTokens: count("output"), + }); + } } + const turns = projectionFor(result, transcript.scenario).providerTurns; + assert.deepEqual( + turns.map((turn) => { + const { updatedAt: _updatedAt, ...tokenUsage } = turn.tokenUsage ?? { updatedAt: "" }; + return tokenUsage; + }), + expected, + ); } export function assertPiSimpleOutput( diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index 019af2a98783f..b3e54117f02ee 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -4159,6 +4159,62 @@ describe("PiAdapterV2", () => { }).pipe(Effect.scoped, Effect.provide(layerTest)), ); + it.effect("reports cached input as a share of input in live and completed token usage", () => + Effect.gen(function* () { + const fake = yield* makeFakePi; + fake.queueState({ + sessionFile: FAKE_SESSION_FILE, + model: { provider: "anthropic", id: "large", contextWindow: 1_000_000 }, + }); + const { runtime, takeEvent } = yield* openRuntime(fake); + const providerThread = yield* runtime.ensureThread({ + threadId: THREAD_ID, + modelSelection: modelSelection("default"), + runtimePolicy, + }); + yield* startTurn(runtime, providerThread); + yield* fake.takeRequest("prompt"); + // Pi's message usage counts uncached input, cache reads and cache writes separately. + const usage = { input: 6, cacheRead: 40_101, cacheWrite: 10_561, output: 123 }; + // Session stats total every message in the session, not this turn. + fake.queueStats({ + tokens: { + input: 1_206, + cacheRead: 90_202, + cacheWrite: 60_622, + output: 250, + total: 152_280, + }, + contextUsage: { tokens: 50_791, contextWindow: 1_000_000 }, + }); + yield* fake.emit({ type: "response", command: "prompt", success: true }); + yield* fake.emit({ type: "agent_start" }); + yield* fake.emit({ type: "message_start", message: { role: "assistant" } }); + yield* fake.emit({ + type: "message_update", + usage: { ...usage, totalTokens: 50_791 }, + assistantMessageEvent: { type: "text_delta", contentIndex: 0, delta: "ok" }, + }); + const live = yield* takeEvent( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.tokenUsage !== undefined, + ); + assert.deepInclude( + live.type === "provider_turn.updated" ? live.providerTurn.tokenUsage : undefined, + { inputTokens: 50_668, cachedInputTokens: 40_101 }, + ); + yield* fake.emit({ type: "agent_settled" }); + const completed = yield* takeEvent( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.status === "completed", + ); + assert.deepInclude( + completed.type === "provider_turn.updated" ? completed.providerTurn.tokenUsage : undefined, + { inputTokens: 50_668, cachedInputTokens: 40_101 }, + ); + }).pipe(Effect.scoped, Effect.provide(layerTest)), + ); + it.effect.each(["turn window", "full tree"] as const)( "finishes a turn whose %s has a parentId cycle", (cycleIn) => diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index eae7f3eb6c2fa..e7803bbe9c5ee 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -359,6 +359,11 @@ function compactionTitle(status: PiCompactionStatus): string { } } +type PiMessageTokenUsage = Pick< + OrchestrationV2ProviderTurnTokenUsage, + "inputTokens" | "cachedInputTokens" | "outputTokens" +>; + interface ActivePiTurn { readonly turnInput: ProviderAdapter.ProviderAdapterV2TurnInput; readonly providerTurn: OrchestrationV2ProviderTurn; @@ -377,6 +382,7 @@ interface ActivePiTurn { promptMayBeCommandOnly: boolean; latestCompactionAfterTokens: number | null; lastLiveUsedTokens: number | null; + lastMessageUsage: PiMessageTokenUsage | undefined; settleProbeGeneration: number; /** An extension may start compaction immediately after Pi emits agent_settled. */ settleWhenIdle: boolean; @@ -904,6 +910,25 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( return value === undefined ? undefined : Math.max(0, Math.trunc(value)); }; + // Pi counts uncached input, cache reads and cache writes separately; input includes all three. + const piMessageTokenUsage = (usage: unknown): PiMessageTokenUsage => { + const uncachedInputTokens = nonNegativeInteger(usage, "input"); + const cachedInputTokens = nonNegativeInteger(usage, "cacheRead"); + const outputTokens = nonNegativeInteger(usage, "output"); + return { + ...(uncachedInputTokens === undefined + ? {} + : { + inputTokens: + uncachedInputTokens + + (cachedInputTokens ?? 0) + + (nonNegativeInteger(usage, "cacheWrite") ?? 0), + }), + ...(cachedInputTokens === undefined ? {} : { cachedInputTokens }), + ...(outputTokens === undefined ? {} : { outputTokens }), + }; + }; + const rememberModelContextWindow = (model: unknown): number | null => { const provider = recordString(model, "provider"); const id = recordString(model, "id"); @@ -994,6 +1019,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( const tokenUsageFromStats = ( stats: unknown, fallbackUsedTokens: number | null, + messageUsage: PiMessageTokenUsage | undefined, updatedAt: DateTime.Utc, ): OrchestrationV2ProviderTurnTokenUsage | undefined => { const contextUsage = recordField(stats, "contextUsage"); @@ -1002,24 +1028,20 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( nonNegativeInteger(contextUsage, "tokens") ?? fallbackUsedTokens ?? undefined; if (usedTokens === undefined || maxTokens === undefined || maxTokens === 0) return undefined; - - const totals = recordField(stats, "tokens"); - const inputTokens = nonNegativeInteger(totals, "input"); - const cachedInputTokens = nonNegativeInteger(totals, "cacheRead"); - const outputTokens = nonNegativeInteger(totals, "output"); - return { - usedTokens, - maxTokens, - ...(inputTokens === undefined ? {} : { inputTokens }), - ...(cachedInputTokens === undefined ? {} : { cachedInputTokens }), - ...(outputTokens === undefined ? {} : { outputTokens }), - updatedAt: DateTime.formatIso(updatedAt), - }; + // Stats `tokens` are whole-session totals; the breakdown comes from the turn's last message. + return { usedTokens, maxTokens, ...messageUsage, updatedAt: DateTime.formatIso(updatedAt) }; }; - const readTokenUsage = (fallbackUsedTokens: number | null, updatedAt: DateTime.Utc) => + const readTokenUsage = (turn: ActivePiTurn, updatedAt: DateTime.Utc) => request({ type: "get_session_stats" }, 2_000).pipe( - Effect.map((stats) => tokenUsageFromStats(stats, fallbackUsedTokens, updatedAt)), + Effect.map((stats) => + tokenUsageFromStats( + stats, + turn.latestCompactionAfterTokens, + turn.lastMessageUsage, + updatedAt, + ), + ), Effect.orElseSucceed(() => undefined), ); @@ -1030,6 +1052,9 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( /* Provider events include streaming deltas; avoid a span for each update. */ Effect.fnUntraced(function* (turn: ActivePiTurn, usage: unknown) { const usedTokens = nonNegativeInteger(usage, "totalTokens"); + if (usedTokens !== undefined && usedTokens > 0) { + turn.lastMessageUsage = piMessageTokenUsage(usage); + } if ( usedTokens === undefined || usedTokens === 0 || @@ -1040,9 +1065,6 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( return; } turn.lastLiveUsedTokens = usedTokens; - const inputTokens = nonNegativeInteger(usage, "input"); - const cachedInputTokens = nonNegativeInteger(usage, "cacheRead"); - const outputTokens = nonNegativeInteger(usage, "output"); const updatedAt = yield* DateTime.now; yield* emit({ type: "provider_turn.updated", @@ -1053,9 +1075,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( tokenUsage: { usedTokens, maxTokens: contextWindow, - ...(inputTokens === undefined ? {} : { inputTokens }), - ...(cachedInputTokens === undefined ? {} : { cachedInputTokens }), - ...(outputTokens === undefined ? {} : { outputTokens }), + ...turn.lastMessageUsage, updatedAt: DateTime.formatIso(updatedAt), }, }, @@ -2075,9 +2095,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( } const treeRefs = turn.stopTreeRefs !== undefined ? turn.stopTreeRefs : yield* captureTurnTreeRefs(); - const tokenUsage = readUsage - ? yield* readTokenUsage(turn.latestCompactionAfterTokens, completedAt) - : undefined; + const tokenUsage = readUsage ? yield* readTokenUsage(turn, completedAt) : undefined; const failure = interrupted ? null : (turn.rejectedPromptFailure ?? turn.failure); yield* emit({ type: "provider_turn.updated", @@ -3474,6 +3492,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( compactCommand !== null || (payload?.message.trimStart().startsWith("/") ?? false), latestCompactionAfterTokens: null, lastLiveUsedTokens: null, + lastMessageUsage: undefined, settleProbeGeneration: 0, settleWhenIdle: false, compactionCancelled: false, From 4c3d83ff24c7437582cfd37ebe4565314250630b Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 01:25:30 -0800 Subject: [PATCH 122/324] fix(mobile): usage account detail keeps even pace current while open (#40759) --- apps/mobile/src/features/usage/UsageLimitsPooled.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/mobile/src/features/usage/UsageLimitsPooled.tsx b/apps/mobile/src/features/usage/UsageLimitsPooled.tsx index 96d8f922340f7..4c290d68ac338 100644 --- a/apps/mobile/src/features/usage/UsageLimitsPooled.tsx +++ b/apps/mobile/src/features/usage/UsageLimitsPooled.tsx @@ -20,6 +20,7 @@ import { import { msg, T, useGT, useMessages, Var } from "gt-react-native"; import { Fragment, type ReactNode, useId, useState } from "react"; import { Pressable, View } from "react-native"; +import { useNowMinuteMs } from "../../lib/clock"; import { tryOpenExternalUrl } from "../../lib/openExternalUrl"; import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView"; import { Defs, Path, Pattern, Rect, Svg } from "react-native-svg"; @@ -201,7 +202,6 @@ function PoolWindowCard({ windowId: pool.id, windowKind: pool.kind, environmentIds, - now, }); const summary = ( <> @@ -590,13 +590,13 @@ type AccountScreenProps = StaticScreenProps<{ windowId: string; windowKind: LimitPoolWindow["kind"]; environmentIds: readonly string[] | null; - now: number; }>; export function UsageLimitAccountScreen({ route }: AccountScreenProps) { const insets = useSafeAreaInsets(); const presentations = useAtomValue(environmentPresentations.presentationsWithProvidersAtom); - const { accountKey, windowId, windowKind, environmentIds, now } = route.params; + const { accountKey, windowId, windowKind, environmentIds } = route.params; + const now = useNowMinuteMs(); const selectedIds = environmentIds === null ? null : new Set(environmentIds.map((id) => EnvironmentId.make(id))); const selected = From 7f125d83d18b2b4e9e65debf8e4d1ae71c45af94 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 01:27:45 -0800 Subject: [PATCH 123/324] fix(server): Resume sends pending context to providers without native resume (#40764) --- .../ProviderTurnStartService.test.ts | 21 +++++++ .../ProviderTurnStartService.ts | 61 +++++++++++++------ 2 files changed, 63 insertions(+), 19 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index 4bf6e71397fe5..89e5a6930bafc 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -2289,6 +2289,27 @@ effectIt.effect("refuses unsupported resume instead of manufacturing a user prom }), ); +effectIt.effect.each([ + { contextRun: "current" }, + { contextRun: "failed", switchedProvider: true }, +] as const)( + "a resume that carries pending context asks a provider without native resume to continue: %j", + (sideChat) => + Effect.gen(function* () { + const harness = makeLocalCommandHarness({ + text: "", + manualContinuation: true, + nativeResumeUnsupported: true, + sideChat, + }); + yield* harness.start; + expect(harness.settledRuns).toEqual([]); + expect(harness.startTurn.mock.calls.map(([turn]) => turn.message.text)).toEqual([ + withInlineContext("SIDE_CHAT_CONTEXT", "Continue where you left off."), + ]); + }), +); + effectIt.effect.each([ { contextRun: "current", runtimeMode: "full-access", context: "SIDE_CHAT_CONTEXT" }, { contextRun: "failed", runtimeMode: "full-access", context: "SIDE_CHAT_CONTEXT" }, diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 8e35271ce5aa9..c3890cab5f71b 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -408,12 +408,22 @@ export const layer: Layer.Layer< return { ...session, startTurn: (input: Parameters[0]) => start(input), - ...(session.resumeTurn === undefined - ? {} - : { - resumeTurn: (input: ProviderAdapter.ProviderAdapterV2ResumeTurnInput) => - start(ProviderAdapter.resumeTurnInput(input)), - }), + // Pending context can prompt a resume, so even a session without native resume takes one. + resumeTurn: (input: ProviderAdapter.ProviderAdapterV2ResumeTurnInput) => + session.resumeTurn === undefined && deliver === undefined + ? Effect.fail( + new ProviderAdapter.ProviderAdapterTurnStartError({ + driver: session.driver, + threadId: input.threadId, + providerThreadId: input.providerThread.id, + runId: input.runId, + cause: new ProviderAdapter.ProviderResumeUnsupportedError({ + driver: session.driver, + providerThreadId: input.providerThread.id, + }), + }), + ) + : start(ProviderAdapter.resumeTurnInput(input)), ...(session.compactThread === undefined ? {} : { @@ -1859,7 +1869,21 @@ export const layer: Layer.Layer< legacyInputRunIds, budget, } = handoffContext; - if (manualResume && unsentResumeMessage === undefined && session.resumeTurn === undefined) { + const retryHandoff = resumedRetryHandoff ?? (yield* prepareRetryHandoff(handoffContext)); + const carriesPendingContext = + effectiveHandoffs.length > 0 || + retryHandoff.handoffs.length > 0 || + retryHandoff.attachments.length > 0 || + sideChatHandoff !== undefined || + restartNote !== "" || + noteContinuation; + // Pending context turns the resume into a prompted turn, which needs no native resume. + if ( + manualResume && + unsentResumeMessage === undefined && + session.resumeTurn === undefined && + !carriesPendingContext + ) { yield* settleStartFailure({ signal: "resume-unsupported", title: "Native resume is unavailable", @@ -1870,7 +1894,6 @@ export const layer: Layer.Layer< }); return; } - const retryHandoff = resumedRetryHandoff ?? (yield* prepareRetryHandoff(handoffContext)); const runningProviderThread: OrchestrationV2ProviderThread = { ...loadedProviderThread, contextUsage: handoffUsage, @@ -2100,8 +2123,14 @@ export const layer: Layer.Layer< turnInput.resume && prompted && userText === "" ? RESUME_PROMPT : userText; const text = goalCommand ? userText : withInlineContext(context, requestText); const operation = - turnInput.resume && !prompted && session.resumeTurn !== undefined - ? session.resumeTurn({ ...resumeInput, messageId: resumeMessage.messageId }) + turnInput.resume && !prompted + ? (session.resumeTurn?.({ ...resumeInput, messageId: resumeMessage.messageId }) ?? + Effect.fail( + new ProviderAdapter.ProviderResumeUnsupportedError({ + driver: session.driver, + providerThreadId: providerThread.id, + }), + )) : start({ ...(prompted ? contextInput : startInput), message: { @@ -2176,15 +2205,9 @@ export const layer: Layer.Layer< }), ), ); - const deliverySession = - effectiveHandoffs.length === 0 && - retryHandoff.handoffs.length === 0 && - retryHandoff.attachments.length === 0 && - sideChatHandoff === undefined && - restartNote === "" && - !noteContinuation - ? session - : makeDeliverySession(session, startWithHandoffs); + const deliverySession = carriesPendingContext + ? makeDeliverySession(session, startWithHandoffs) + : session; return runExecution.startRootRun({ commandId: CommandId.make(`command:effect:provider-turn.start:${run.id}`), appThread: projection.thread, From 90a8ac086435ac3503810f64da2fc3c930ef8ce1 Mon Sep 17 00:00:00 2001 From: Aman Thanvi <22306104+amanthanvi@users.noreply.github.com> Date: Sun, 22 Nov 2026 04:39:13 -0500 Subject: [PATCH 124/324] fix(server): a failed or cancelled clone no longer blocks re-cloning its destination (#40739) Co-authored-by: Julius Marminge --- .../src/project/ProjectCloneTracker.test.ts | 62 +++++++++++++++++++ .../server/src/project/ProjectCloneTracker.ts | 17 +++-- 2 files changed, 74 insertions(+), 5 deletions(-) diff --git a/apps/server/src/project/ProjectCloneTracker.test.ts b/apps/server/src/project/ProjectCloneTracker.test.ts index bdbb47b767c03..3b2e6f1179b86 100644 --- a/apps/server/src/project/ProjectCloneTracker.test.ts +++ b/apps/server/src/project/ProjectCloneTracker.test.ts @@ -312,6 +312,68 @@ describe("ProjectCloneTracker", () => { }).pipe(Effect.provide(harness.layer)); }); + it.effect("a fresh clone into a failed clone's destination supersedes it", () => { + let attempts = 0; + const harness = makeHarness({ + clone: (input) => + Effect.suspend(() => + ++attempts === 1 + ? Effect.fail( + new SourceControlRepositoryError({ + operation: "cloneRepository", + provider: SourceControlProviderKind.make("unknown"), + detail: "fatal: repository not found", + }), + ) + : Effect.succeed({ + cwd: input.destinationPath, + remoteUrl: input.remoteUrl ?? "", + repository: null, + }), + ), + }); + // The failed clone's project still owns the destination. + const conflictingHooks: ProjectCloneTracker.ProjectCloneHooks = { + ...harness.hooks, + createProject: (input) => + Effect.fail( + new ProjectConflictError({ + projectId: input.projectId, + workspaceRoot: input.workspaceRoot, + conflictingProjectId: projectId, + }), + ), + }; + return Effect.gen(function* () { + const tracker = yield* ProjectCloneTracker.ProjectCloneTracker; + yield* tracker.start(startInput, harness.hooks); + yield* Effect.yieldNow; + expect((yield* tracker.get(projectId))?.phase).toBe("failed"); + + const second = ProjectId.make("project-2"); + const result = yield* tracker.start({ ...startInput, projectId: second }, conflictingHooks); + expect(result.projectId).toBe(projectId); + yield* Effect.yieldNow; + expect((yield* tracker.get(projectId))?.phase).toBe("done"); + expect(yield* tracker.get(second)).toBeNull(); + expect(harness.cloned).toEqual([projectId]); + }).pipe(Effect.provide(harness.layer)); + }); + + it.effect("refuses a second clone into a destination that is still cloning", () => { + const harness = makeHarness({ clone: () => Effect.never }); + return Effect.gen(function* () { + const tracker = yield* ProjectCloneTracker.ProjectCloneTracker; + yield* tracker.start(startInput, harness.hooks); + yield* Effect.yieldNow; + const error = yield* Effect.flip( + tracker.start({ ...startInput, projectId: ProjectId.make("project-2") }, harness.hooks), + ); + expect(error.message).toContain("already in progress"); + expect((yield* tracker.get(projectId))?.phase).toBe("running"); + }).pipe(Effect.provide(harness.layer)); + }); + it.effect("does not create a project when the clone cannot be prepared", () => { const harness = makeHarness(); const layer = ProjectCloneTracker.layer.pipe( diff --git a/apps/server/src/project/ProjectCloneTracker.ts b/apps/server/src/project/ProjectCloneTracker.ts index 0a24f11ffd89d..367b839cf2a6b 100644 --- a/apps/server/src/project/ProjectCloneTracker.ts +++ b/apps/server/src/project/ProjectCloneTracker.ts @@ -297,14 +297,19 @@ export const make = Effect.gen(function* () { endedAt: null, sequence: ++sequence, }; - const claimed = yield* Ref.modify(clones, (current) => { - const conflict = Array.from(current.values()).some( + const claim = yield* Ref.modify(clones, (current) => { + const overlapping = Array.from(current.values()).filter( (tracked) => tracked.snapshot.projectId === input.projectId || tracked.input.destinationPath === prepared.destinationPath, ); - if (conflict) return [false, current] as const; + // Only a running clone owns its destination; a failed or cancelled one + // left nothing behind, so a fresh start supersedes it. + if (overlapping.some((tracked) => tracked.snapshot.phase === "running")) { + return [null, current] as const; + } const next = new Map(current); + for (const stale of overlapping) next.delete(stale.snapshot.projectId); next.set(input.projectId, { snapshot, fiber: null, @@ -316,14 +321,16 @@ export const make = Effect.gen(function* () { protocol: input.protocol ?? "auto", }, }); - return [true, next] as const; + return [overlapping.map((stale) => stale.snapshot.projectId), next] as const; }); const alreadyInProgress = new SourceControlRepositoryError({ operation: "cloneRepository", provider: input.provider ?? SourceControlProviderKind.make("unknown"), detail: "A clone into this destination is already in progress.", }); - if (!claimed) return yield* alreadyInProgress; + if (claim === null) return yield* alreadyInProgress; + // A superseded done entry's pending removal would otherwise delete the new claim. + yield* Effect.forEach(claim, clearRetention, { discard: true }); // Finish or release the claim despite disconnects; a claim without a fiber cannot be cancelled or retried. const projectId = yield* Effect.uninterruptible( Effect.gen(function* () { From 70b5e489b91842243655cbc4307c614feb314ff0 Mon Sep 17 00:00:00 2001 From: Wu Shuwen Date: Sun, 22 Nov 2026 17:43:07 +0800 Subject: [PATCH 125/324] fix: retain pull request metadata in thread show (#40744) Co-authored-by: Julius Marminge --- apps/server/src/cli/thread.test.ts | 34 ++++++++++++++++++++++++++++++ apps/server/src/cli/thread.ts | 3 ++- 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/apps/server/src/cli/thread.test.ts b/apps/server/src/cli/thread.test.ts index 49887ee0bb7cc..bb0906a9c6919 100644 --- a/apps/server/src/cli/thread.test.ts +++ b/apps/server/src/cli/thread.test.ts @@ -558,6 +558,40 @@ const timelineTools = (types: ReadonlyArray) => { const tail = (tools: number) => [...Array(tools).fill("tool_call"), "assistant_message"]; +it.effect("show retains pull request metadata when reading a later message window", () => + Effect.gen(function* () { + const link = { + host: "github.com", + repository: "owner/repo", + number: 1, + url: "https://github.com/owner/repo/pull/1", + source: "manual", + state: "open", + watching: false, + watchStartedAt: null, + } as const; + const call = ((_tool: string, input: unknown) => { + const args = input as { afterPosition?: number; limit: number }; + const first = args.afterPosition === undefined && args.limit === 1; + return Effect.succeed({ + thread: { + itemCount: 200, + status: first ? "running" : "completed", + pullRequestCount: 1, + ...(first ? { pullRequests: [link], openPullRequestCount: 1 } : {}), + }, + items: first ? [] : [{ position: 199, itemId: "message", type: "assistant_message" }], + nextPosition: 199, + hasMore: false, + }); + }) as ThreadTools["call"]; + const { thread } = yield* readLatestMessages({ call }, threadId, 1); + assert.strictEqual(thread.status, "completed"); + assert.deepStrictEqual(thread.pullRequests, [link]); + assert.strictEqual(thread.openPullRequestCount, 1); + }), +); + it.effect("show reads the end of a long thread, not its whole history", () => Effect.gen(function* () { const { tools, served, latest } = timelineTools([ diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts index e63e762237e85..09ee65c32172b 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -459,7 +459,8 @@ export const readLatestMessages = Effect.fn("cli.thread.readLatestMessages")(fun ); afterPosition = page.nextPosition ?? Number.POSITIVE_INFINITY; } while (page.hasMore && afterPosition < (end ?? Number.POSITIVE_INFINITY) - 1); - thread = page.thread; + // Only the first read carries pull request previews; later pages omit them. + thread = Object.assign({}, thread, page.thread); // A window can hold the whole --messages count, too many to spread as arguments. messages = window.concat(messages); before = start; From c3a330d8342f0825293b56c0fd22b20c6ef3206c Mon Sep 17 00:00:00 2001 From: Jinhui Zheng Date: Sun, 22 Nov 2026 18:03:40 +0800 Subject: [PATCH 126/324] fix(web): show Queue for running sessions that cannot steer (#40767) Co-authored-by: Julius Marminge --- apps/web/src/components/ChatView.tsx | 11 ++---- .../src/state/threadWorkflows.test.ts | 34 ++++++++++++++++- .../src/state/threadWorkflows.ts | 37 ++++++++++++++++--- 3 files changed, 68 insertions(+), 14 deletions(-) diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 254bbd4eb9e42..d17af4f620755 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -106,10 +106,9 @@ import { } from "@t3tools/client-runtime/state/subagentRuntime"; import { getUserQueuedThreadRuns, - threadSteersDuringCompaction, + threadCanSteer, threadSupportsProviderHandoff, } from "@t3tools/client-runtime/state/thread-workflows"; -import { compactionBlocksSteering } from "@t3tools/client-runtime/state/composer-dispatch"; import { resolvePendingHandoff } from "@t3tools/client-runtime/handoff"; import { HandoffRow } from "./chat/V2LifecycleRow"; import { @@ -1545,12 +1544,10 @@ export default function ChatView(props: ChatViewProps) { const isCompacting = (isSendBusy || phase === "connecting" || phase === "running") && (compactionRunning || compactCommandIsActive); - const compactionBlocksSteer = compactionBlocksSteering({ + const canSteer = threadCanSteer(serverProjection, { compactCommandIsActive, compactionRunning, - steersDuringCompaction: threadSteersDuringCompaction(serverProjection), - run: serverProjection?.runs.find((run) => run.id === activeRuntime?.activeRunId), - messages: serverProjection?.messages, + activeRunId: activeRuntime?.activeRunId, }); const isWorking = deriveTimelineWorking({ phase, @@ -3822,7 +3819,7 @@ export default function ChatView(props: ChatViewProps) { isLocalDraftThread && activeProject === null } phase={phase} - canSteer={!compactionBlocksSteer} + canSteer={canSteer} canInterrupt={canInterruptRunningThread} isSendBusy={ (isSendBusy && !sendQueuesBehindSetup) || diff --git a/packages/client-runtime/src/state/threadWorkflows.test.ts b/packages/client-runtime/src/state/threadWorkflows.test.ts index a4049c7169163..fd8092a996a66 100644 --- a/packages/client-runtime/src/state/threadWorkflows.test.ts +++ b/packages/client-runtime/src/state/threadWorkflows.test.ts @@ -6,6 +6,7 @@ import { deriveThreadQueueWorkflowState, getUserQueuedThreadRuns, resolveLatestMergeBackRun, + threadCanSteer, threadSupportsProviderHandoff, } from "./threadWorkflows.ts"; @@ -13,6 +14,7 @@ const capabilities = (input?: { readonly queued?: boolean; readonly steer?: boolean; readonly restartSteer?: boolean; + readonly interrupt?: boolean; readonly nativeFork?: boolean; readonly portableFork?: boolean; }) => @@ -21,6 +23,7 @@ const capabilities = (input?: { supportsQueuedMessages: input?.queued ?? false, supportsActiveSteering: input?.steer ?? false, supportsSteeringByInterruptRestart: input?.restartSteer ?? false, + supportsInterrupt: input?.interrupt ?? false, }, threads: { canForkThread: input?.nativeFork ?? false, @@ -31,6 +34,35 @@ const capabilities = (input?: { }) as never; describe("thread workflows", () => { + it.each([ + ["queue only", { queued: true }, false, false], + ["session still attaching", undefined, false, true], + ["native steering", { steer: true }, false, true], + ["interrupt and restart", { interrupt: true, restartSteer: true }, false, true], + ["restart without interrupt", { restartSteer: true }, false, false], + ["explicit compaction", { steer: true }, true, false], + ] as const)("gates composer steering for %s", (_, turns, compactCommandIsActive, expected) => { + const projection = { + thread: { id: "thread", activeProviderThreadId: "provider-thread" }, + runs: [{ id: "active", status: "running", providerThreadId: "provider-thread" }], + providerThreads: [{ id: "provider-thread", providerSessionId: "session" }], + providerSessions: [ + ...(turns === undefined + ? [] + : [{ id: "session", status: "running", capabilities: capabilities(turns) }]), + { id: "other", status: "ready", capabilities: capabilities({ steer: true }) }, + ], + messages: [], + } as unknown as OrchestrationV2ThreadProjection; + expect( + threadCanSteer(projection, { + compactCommandIsActive, + compactionRunning: false, + activeRunId: projection.runs[0]!.id, + }), + ).toBe(expected); + }); + it("skips message history classification when no runs are queued", () => { let metadataReads = 0; const message = { @@ -139,7 +171,7 @@ describe("thread workflows", () => { { id: "provider-session", status: "running", - capabilities: capabilities({ queued: true, restartSteer: true }), + capabilities: capabilities({ queued: true, interrupt: true, restartSteer: true }), }, ], } as never); diff --git a/packages/client-runtime/src/state/threadWorkflows.ts b/packages/client-runtime/src/state/threadWorkflows.ts index 7dbbcf1e80c57..9e3d1eb4512b2 100644 --- a/packages/client-runtime/src/state/threadWorkflows.ts +++ b/packages/client-runtime/src/state/threadWorkflows.ts @@ -8,6 +8,7 @@ import { copySorted } from "@t3tools/shared/Array"; import { mFallback, msg } from "gt-i18n"; import type { MFunctionType } from "gt-i18n/types"; +import { compactionBlocksSteering } from "./composerDispatch.ts"; import type { ThreadStructure } from "./models.ts"; type Projection = ThreadStructure; @@ -102,6 +103,33 @@ export function threadSteersDuringCompaction(projection: Projection | null | und ); } +function supportsSteering(turns: OrchestrationV2ProviderCapabilities["turns"]): boolean { + return ( + turns.supportsActiveSteering || + (turns.supportsInterrupt && turns.supportsSteeringByInterruptRestart) + ); +} + +export function threadCanSteer( + projection: Projection | null, + input: { + readonly compactCommandIsActive: boolean; + readonly compactionRunning: boolean; + readonly activeRunId: Run["id"] | null | undefined; + }, +): boolean { + const turns = projection && resolveThreadProviderSession(projection)?.capabilities.turns; + // A steer submitted before the session attaches can wait for its provider turn. + if (turns && !supportsSteering(turns)) return false; + return !compactionBlocksSteering({ + compactCommandIsActive: input.compactCommandIsActive, + compactionRunning: input.compactionRunning, + steersDuringCompaction: turns?.activeSteeringDuringCompaction === true, + run: projection?.runs.find((run) => run.id === input.activeRunId), + messages: projection?.messages, + }); +} + export function threadSupportsProviderHandoff(projection: Projection | null | undefined): boolean { if (projection == null) return false; const session = resolveThreadProviderSession(projection); @@ -147,6 +175,7 @@ export function deriveThreadQueueWorkflowState( const activeRun = resolveActiveThreadRun(projection); const session = resolveThreadProviderSession(projection); const capabilities = session?.capabilities.turns; + const canSteer = capabilities !== undefined && supportsSteering(capabilities); const activeMessage = projection.messages.find( (message) => message.id === activeRun?.userMessageId, ); @@ -187,12 +216,8 @@ export function deriveThreadQueueWorkflowState( canPromoteToSteer: promoteSkipsCompaction || ((activeRun?.status === "preparing" || activeRun?.status === "starting") && - (capabilities === undefined || - capabilities.supportsActiveSteering || - capabilities.supportsSteeringByInterruptRestart)) || - (hasSteerableProviderTurn && - (capabilities?.supportsActiveSteering === true || - capabilities?.supportsSteeringByInterruptRestart === true)), + (capabilities === undefined || canSteer)) || + (hasSteerableProviderTurn && canSteer), promoteSkipsCompaction, }; } From c198f73b3766090e02cace1a8b14f439f9fc63b6 Mon Sep 17 00:00:00 2001 From: AymanKhan9 Date: Sun, 22 Nov 2026 15:54:47 +0530 Subject: [PATCH 127/324] fix(web): a click outside the project action editor no longer discards the draft (#40776) --- .../projectScriptEditor.browser.test.tsx | 14 ++++++++++++++ apps/web/src/components/projectScriptEditor.tsx | 2 ++ 2 files changed, 16 insertions(+) diff --git a/apps/web/src/components/projectScriptEditor.browser.test.tsx b/apps/web/src/components/projectScriptEditor.browser.test.tsx index a9ea6f03ad185..0f37c32b23a9e 100644 --- a/apps/web/src/components/projectScriptEditor.browser.test.tsx +++ b/apps/web/src/components/projectScriptEditor.browser.test.tsx @@ -3,6 +3,7 @@ import { EnvironmentId } from "@t3tools/contracts"; import { AsyncResult } from "effect/reactivity"; import { StrictMode } from "react"; import { describe, expect, it, vi } from "vite-plus/test"; +import { page, userEvent } from "vite-plus/test/browser"; vi.mock(import("~/state/session"), async (original) => ({ ...(await original()), @@ -86,3 +87,16 @@ describe("project action editor save lifecycle", () => { expect(onSubmit.mock.calls.map(([scriptId]) => scriptId)).toEqual(["build", "test"]); }); }); + +describe("project action editor dismissal", () => { + it("stays open when the user clicks outside the editor", async () => { + setup(); + await using screen = await render(null); + await open(screen, { scriptId: null, initial: EMPTY_PROJECT_SCRIPT_INPUT }); + await expect.element(page.getByRole("dialog")).toBeVisible(); + + await userEvent.click(document.body, { position: { x: 1, y: 1 } }); + + expect(onClose).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/web/src/components/projectScriptEditor.tsx b/apps/web/src/components/projectScriptEditor.tsx index 504e0afc69ca0..ea9b5ca1f2245 100644 --- a/apps/web/src/components/projectScriptEditor.tsx +++ b/apps/web/src/components/projectScriptEditor.tsx @@ -188,6 +188,8 @@ export function ProjectScriptEditorDialog({ <> { if (!open) onClose(); }} From 379a98ac227d9c0b4185e133facfa6d3114c7427 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 02:55:08 -0800 Subject: [PATCH 128/324] fix(server): t3 pair skips Windows VirtualBox and VMware host-only adapters (#33441) --- apps/server/src/environment/DirectEndpoints.ts | 10 ++++++---- apps/server/src/startupAccess.test.ts | 14 ++++++++++++++ apps/server/src/startupAccess.ts | 7 ++++++- 3 files changed, 26 insertions(+), 5 deletions(-) diff --git a/apps/server/src/environment/DirectEndpoints.ts b/apps/server/src/environment/DirectEndpoints.ts index 4508d208e75e6..c39ca1d85484e 100644 --- a/apps/server/src/environment/DirectEndpoints.ts +++ b/apps/server/src/environment/DirectEndpoints.ts @@ -24,7 +24,12 @@ import { import * as ServerConfig from "../config.ts"; import * as ServerEnvironment from "./ServerEnvironment.ts"; -import { isLoopbackHost, isPrivateNetworkAddress, isVirtualInterface } from "../startupAccess.ts"; +import { + isLoopbackHost, + isPrivateNetworkAddress, + isVirtualInterface, + WINDOWS_HOST_ADAPTER_MAC, +} from "../startupAccess.ts"; type NetworkInterfacesMap = ReturnType; @@ -52,9 +57,6 @@ const isTailscaleInterface = ( /^tailscale/i.test(name) || entries.some((entry) => entry.family === "IPv6" && isTailnetHost(entry.address)); -// Windows adapter names are mutable; Linux bridges can inherit these MACs. -const WINDOWS_HOST_ADAPTER_MAC = /^(0a:00:27|00:50:56:c0:00):/i; - export function resolveBoundEndpoints(input: { readonly platform: NodeJS.Platform; readonly host: string | undefined; diff --git a/apps/server/src/startupAccess.test.ts b/apps/server/src/startupAccess.test.ts index 7290d6063db9b..c36c29e5f1278 100644 --- a/apps/server/src/startupAccess.test.ts +++ b/apps/server/src/startupAccess.test.ts @@ -71,6 +71,20 @@ it("prefers a LAN address over a tailnet one for a private-network pairing URL", ).toBe("http://192.168.1.42:3773"); }); +it("skips Windows VirtualBox and VMware host-only adapters for a private-network listener", () => { + expect( + resolveHeadlessConnectionString("0.0.0.0", 3773, { + interfaces: { + "VirtualBox Host-Only Network": [{ ...ipv4("192.168.56.1"), mac: "0a:00:27:00:00:0a" }], + "VMware Network Adapter VMnet8": [{ ...ipv4("192.168.159.1"), mac: "00:50:56:c0:00:08" }], + "Wi-Fi": [{ ...ipv4("192.168.1.20"), mac: "3c:22:fb:12:34:56" }], + }, + privateNetworkOnly: true, + platform: "win32", + }), + ).toBe("http://192.168.1.20:3773"); +}); + it("skips NixOS container and systemd-nspawn veths for a private-network pairing URL", () => { expect( resolveHeadlessConnectionString("0.0.0.0", 3773, { diff --git a/apps/server/src/startupAccess.ts b/apps/server/src/startupAccess.ts index b065a3fc88172..ce1b8be41938f 100644 --- a/apps/server/src/startupAccess.ts +++ b/apps/server/src/startupAccess.ts @@ -51,6 +51,9 @@ export const isLoopbackHost = (host: string | undefined): boolean => { const VIRTUAL_INTERFACE = /^(docker|br-|veth|virbr|vmnet|vboxnet|vEthernet|podman|cni|flannel|cali|lxcbr|lxdbr|bridge[1-9]\d\d)/; +// VirtualBox and VMware host-only adapters on Windows. Their names are mutable; Linux bridges can inherit these MACs. +export const WINDOWS_HOST_ADAPTER_MAC = /^(0a:00:27|00:50:56:c0:00):/i; + /** * systemd-nspawn's `ve-*`/`vz-*` and NixOS containers' `vb-*` name host-side * veths after the machine. Windows aliases are user-renameable, so these @@ -155,7 +158,9 @@ const resolveHeadlessConnectionHost = ( (entry) => !entry.internal && isIpv4Family(entry.family) && - (!privateNetworkOnly || isPrivateNetworkAddress(entry.address)), + (!privateNetworkOnly || + (isPrivateNetworkAddress(entry.address) && + !(platform === "win32" && WINDOWS_HOST_ADAPTER_MAC.test(entry.mac)))), ); // A tailnet or other CGNAT address reaches fewer devices than the LAN one. const externalIpv4 = privateNetworkOnly From 418e1ace0fc6edeb729cb094efb939603b958049 Mon Sep 17 00:00:00 2001 From: Kyros Abas Date: Sun, 22 Nov 2026 18:57:28 +0800 Subject: [PATCH 129/324] fix(server): Word text boxes keep their paragraph breaks for agents (#40782) Co-authored-by: Julius Marminge --- apps/server/src/provider/documentTextWorker.ts | 6 ++++-- apps/server/src/provider/userInputAttachments.test.ts | 4 ++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index 3dd649811f330..70f16961843d3 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -170,9 +170,11 @@ function* all(node: XmlNode, name: string | readonly string[]): Generator { +function* text(node: XmlNode): Generator { if (HIDDEN.has(node.name)) return; - if (["tab", "ptab", "cell"].includes(node.name)) yield "\t"; + // Word text boxes hold their own paragraphs inside the anchoring paragraph. + if (node.name === "txbxContent") yield* paragraphs(node); + else if (["tab", "ptab", "cell"].includes(node.name)) yield "\t"; else if (["br", "line-break", "cr"].includes(node.name)) yield "\n"; else if (node.name === "noBreakHyphen") yield "\u2011"; else if (node.spaceCount !== undefined) { diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index 72f7e52a3cd41..dd6c70cfcc00b 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -767,9 +767,9 @@ describe("question answer paths", () => { bounded: true, parts: { "word/document.xml": - 'BodyCallout boxCallout box', + 'BodyCallout boxSecond lineCallout boxSecond line', }, - expected: ["Body\nCallout box"], + expected: ["Body\nCallout box\nSecond line"], occurrences: { text: "Callout box", count: 1 }, }, { From 356dff3352f1014194c6c5861fead3bebc4c15ab Mon Sep 17 00:00:00 2001 From: TheGuyWithHAT Date: Sun, 22 Nov 2026 12:03:54 +0100 Subject: [PATCH 130/324] fix(web): RTF previews respect hidden character formatting (#40783) Co-authored-by: geezoria <25051260+geezoria@users.noreply.github.com> Co-authored-by: Julius Marminge --- apps/web/src/components/files/FilePreviewPanel.test.ts | 8 ++++++++ apps/web/src/components/files/extendedDocumentPreview.ts | 5 ++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/files/FilePreviewPanel.test.ts b/apps/web/src/components/files/FilePreviewPanel.test.ts index 4b736d8b6622e..c2b6aa0b306d7 100644 --- a/apps/web/src/components/files/FilePreviewPanel.test.ts +++ b/apps/web/src/components/files/FilePreviewPanel.test.ts @@ -158,6 +158,11 @@ describe("document preview contents", () => { "A\tB\u2003C\u2002D\u2005E\u200dF\u200cG\u200bH\u200eI\u200fJ", ], ["a Unicode fallback", String.raw`{\rtf1 Jean\u8209\_Luc}`, "Jean\u2011Luc"], + [ + "visible text around hidden character formatting", + String.raw`{\rtf1 A{\v hidden{\v0 B}hidden}C\v hidden\v0 D\v hidden\plain E}`, + "ABCDE", + ], ["a tracked replacement", String.raw`{\rtf1 aaa{\deleted bbb}{\revised BBB}ccc}`, "aaaBBBccc"], [ "text after a deletion reset", @@ -232,6 +237,9 @@ Third}`; expect(html(textEdit.replaceAll("\n", "\r\n"))).toEqual(expected); const lineBreak = html(String.raw`{\rtf1\ansi First line\line Second line}`); expect(lineBreak).toEqual(["

    First line
    Second line

    "]); + expect(html(String.raw`{\rtf1\ansi{\v\line\line\line}First line\line Second line}`)).toEqual( + lineBreak, + ); expect(html(String.raw`{\rtf1\ansi First line\uc0\u8232 Second line}`)).toEqual(lineBreak); expect(html(String.raw`{\rtf1\ansi First line\u8232?Second line{\deleted\u8232?}}`)).toEqual( lineBreak, diff --git a/apps/web/src/components/files/extendedDocumentPreview.ts b/apps/web/src/components/files/extendedDocumentPreview.ts index 7d6021de6f811..f107ea0266043 100644 --- a/apps/web/src/components/files/extendedDocumentPreview.ts +++ b/apps/web/src/components/files/extendedDocumentPreview.ts @@ -538,6 +538,7 @@ export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { let state = { skip: false, deleted: false, + hiddenText: false, bold: false, italic: false, underline: false, @@ -560,7 +561,7 @@ export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { }; let run = ""; let fallback = 0; - const hidden = () => state.skip || state.deleted; + const hidden = () => state.skip || state.deleted || state.hiddenText; const encoded = new Uint8Array(bytes.byteLength); let encodedLength = 0; const flush = () => { @@ -722,10 +723,12 @@ export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { else if (word === "ul") state.underline = arg !== 0; else if (word === "ulnone") state.underline = false; else if (word === "deleted") state.deleted = arg !== 0; + else if (word === "v") state.hiddenText = arg !== 0; else if (word === "plain") state = { ...state, deleted: false, + hiddenText: false, bold: false, italic: false, underline: false, From 5fc2eb2f4750230304c2a3c083f425854a16627a Mon Sep 17 00:00:00 2001 From: Arun Krishnamurthy Date: Sun, 22 Nov 2026 05:10:03 -0600 Subject: [PATCH 131/324] fix(mobile): the iOS composer keeps its keyboard and caret after dictation (#33916) Co-authored-by: Julius Marminge --- apps/mobile/src/features/issues/IssueCommentComposer.tsx | 6 +++++- apps/mobile/src/features/threads/ThreadComposer.tsx | 5 ++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/apps/mobile/src/features/issues/IssueCommentComposer.tsx b/apps/mobile/src/features/issues/IssueCommentComposer.tsx index 75ff1199595a3..901dee46152a4 100644 --- a/apps/mobile/src/features/issues/IssueCommentComposer.tsx +++ b/apps/mobile/src/features/issues/IssueCommentComposer.tsx @@ -170,7 +170,11 @@ export function IssueCommentComposer(props: { /> {/* TalkBack orders siblings by position; outside this row the editor reads after Send. */} Date: Sun, 22 Nov 2026 11:16:00 +0000 Subject: [PATCH 132/324] fix(shared): find file links whose labels contain brackets (#40781) Co-authored-by: Abhiram-745 <237478249+Abhiram-745@users.noreply.github.com> Co-authored-by: Julius Marminge --- packages/shared/src/markdownLinks.test.ts | 3 ++ packages/shared/src/markdownLinks.ts | 49 ++++++++++------------- 2 files changed, 25 insertions(+), 27 deletions(-) diff --git a/packages/shared/src/markdownLinks.test.ts b/packages/shared/src/markdownLinks.test.ts index a1f0af927636d..80204d903892b 100644 --- a/packages/shared/src/markdownLinks.test.ts +++ b/packages/shared/src/markdownLinks.test.ts @@ -174,6 +174,9 @@ describe("extractMarkdownLinkHrefs", () => { ["[".repeat(32_000), []], ["[a]( invalid [b](ok)", [" { expect(extractMarkdownLinkHrefs(markdown)).toEqual(hrefs); diff --git a/packages/shared/src/markdownLinks.ts b/packages/shared/src/markdownLinks.ts index 50450a1e787de..e3458f04f3484 100644 --- a/packages/shared/src/markdownLinks.ts +++ b/packages/shared/src/markdownLinks.ts @@ -519,41 +519,36 @@ function markdownLinkDestinationScanner(markdown: string) { } } const hrefEnd = bareMarkdownLinkDestinationEnd(markdown, hrefStart); - if (hrefEnd === null || hrefEnd === hrefStart) return null; + if (hrefEnd === null) return null; const end = bareTail(hrefEnd); return end === null ? null : { hrefStart, hrefEnd, end }; }; } -// The composer escapes brackets in labels (`[\[id\].tsx](...)`), and `\]` does not close one. -function unescapedLabelEnd(markdown: string, start: number): number { - let end = markdown.indexOf("]", start); - while (end !== -1) { - let backslashes = 0; - while (end - backslashes > start && markdown[end - backslashes - 1] === "\\") backslashes += 1; - if (backslashes % 2 === 0) return end; - end = markdown.indexOf("]", end + 1); - } - return -1; -} - +// Labels may nest balanced brackets (`[the [docs] guide](...)`), and the composer escapes them +// (`[\[id\].tsx](...)`), so `\[` and `\]` never count. A blank line ends the paragraph and its labels. export function extractMarkdownLinkHrefs(markdown: string): string[] { const hrefs: string[] = []; const scanDestination = markdownLinkDestinationScanner(markdown); - let cursor = 0; - while (cursor < markdown.length) { - const labelStart = markdown.indexOf("[", cursor); - if (labelStart === -1) break; - const labelEnd = unescapedLabelEnd(markdown, labelStart + 1); - if (labelEnd === -1) break; - - // Skip a failed label once; nested openings share its closing bracket. - cursor = labelEnd + 1; - const destination = scanDestination(cursor); - if (!destination) continue; - cursor = destination.end; - const href = markdown.slice(destination.hrefStart, destination.hrefEnd).trim(); - if (href) hrefs.push(href); + const bracket = /[[\]\\]|\n[ \t\r]*\n/g; + let openBrackets = 0; + for (let match = bracket.exec(markdown); match; match = bracket.exec(markdown)) { + if (match[0] === "\\") { + bracket.lastIndex = match.index + 2; + } else if (match[0].startsWith("\n")) { + openBrackets = 0; + } else if (match[0] === "[") { + openBrackets += 1; + } else if (openBrackets > 0) { + openBrackets -= 1; + const destination = scanDestination(match.index + 1); + if (!destination) continue; + // A link cannot contain a link, so the brackets still open around it become text. + openBrackets = 0; + bracket.lastIndex = destination.end; + const href = markdown.slice(destination.hrefStart, destination.hrefEnd).trim(); + if (href) hrefs.push(href); + } } return hrefs; } From 1acfd37c17ea49340705092d8ee3d41c210a0a99 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 03:19:46 -0800 Subject: [PATCH 133/324] fix(web): restore effort picker keyboard typeahead (#40798) Co-authored-by: shadowfeind --- .../chat/ComposerModelEffort.browser.test.tsx | 24 +++++++++++++++++++ .../components/chat/ComposerModelEffort.tsx | 23 ++++++++++++++---- 2 files changed, 42 insertions(+), 5 deletions(-) diff --git a/apps/web/src/components/chat/ComposerModelEffort.browser.test.tsx b/apps/web/src/components/chat/ComposerModelEffort.browser.test.tsx index ab7d560d5c676..1678552dd0ab2 100644 --- a/apps/web/src/components/chat/ComposerModelEffort.browser.test.tsx +++ b/apps/web/src/components/chat/ComposerModelEffort.browser.test.tsx @@ -122,3 +122,27 @@ it("draws an agent's reasoning as bars and keeps its mode out of the levels", as .toBeInTheDocument(); await expect.element(page.getByRole("menuitemradio")).not.toBeInTheDocument(); }); + +it("focuses a reasoning level by its first letter without selecting it", async () => { + await using screen = await render(, { router: false }); // no routes involved + await userEvent.tab(); + await expect.element(screen.getByRole("radio", { name: "Medium" })).toHaveFocus(); + await userEvent.keyboard("l"); + await expect.element(screen.getByRole("radio", { name: "Low" })).toHaveFocus(); + await expect + .element(screen.getByRole("radio", { name: "Medium" })) + .toHaveAttribute("aria-checked", "true"); + for (const key of ["{Control>}h{/Control}", "{Meta>}h{/Meta}", "{Alt>}h{/Alt}", "{Delete}"]) { + await userEvent.keyboard(key); + await expect.element(screen.getByRole("radio", { name: "Low" })).toHaveFocus(); + } + await userEvent.keyboard("H"); + await expect.element(screen.getByRole("radio", { name: "High" })).toHaveFocus(); + // Wraps past the last level back to the first match. + await userEvent.keyboard("m"); + await expect.element(screen.getByRole("radio", { name: "Medium" })).toHaveFocus(); + await userEvent.keyboard("h{Enter}"); + await expect + .element(screen.getByRole("radio", { name: "High" })) + .toHaveAttribute("aria-checked", "true"); +}); diff --git a/apps/web/src/components/chat/ComposerModelEffort.tsx b/apps/web/src/components/chat/ComposerModelEffort.tsx index 1d0227c0f6482..b5d5a519a3410 100644 --- a/apps/web/src/components/chat/ComposerModelEffort.tsx +++ b/apps/web/src/components/chat/ComposerModelEffort.tsx @@ -206,8 +206,8 @@ function ColumnRow(props: { "aria-checked": props.selected, disabled: props.disabled, "data-effort-row": true, - // Focus lands on a level after a model pick. - "data-effort-level": true, + // Focus lands on a level after a model pick, and a typed letter finds one by its label. + "data-effort-level": props.label, // Up and Down move between rows. tabIndex: props.tabStop ? 0 : -1, className: COLUMN_ROW, @@ -244,15 +244,28 @@ function ColumnRow(props: { } function moveBetweenRows(event: KeyboardEvent) { - if (event.key !== "ArrowDown" && event.key !== "ArrowUp") return; + const arrow = event.key === "ArrowDown" || event.key === "ArrowUp"; + if ( + !arrow && + (event.key.length !== 1 || + event.key.trim() === "" || + event.ctrlKey || + event.altKey || + event.metaKey || + event.nativeEvent.isComposing) + ) + return; // An option's side menu is a React child here, but it moves through its own items. if (!event.currentTarget.contains(event.target as Node)) return; const rows = Array.from( event.currentTarget.querySelectorAll("[data-effort-row]:not(:disabled)"), ); const index = rows.findIndex((row) => row === document.activeElement); - const next = - rows[Math.min(rows.length - 1, Math.max(0, index + (event.key === "ArrowDown" ? 1 : -1)))]; + const next = arrow + ? rows[Math.min(rows.length - 1, Math.max(0, index + (event.key === "ArrowDown" ? 1 : -1)))] + : [...rows.slice(index + 1), ...rows.slice(0, index + 1)].find((row) => + row.dataset.effortLevel?.toLowerCase().startsWith(event.key.toLowerCase()), + ); if (!next) return; event.preventDefault(); event.stopPropagation(); From 0ae3154695e5b6808a8fb9955f69d78d9c1274fa Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 03:19:58 -0800 Subject: [PATCH 134/324] fix(server): migration 75 no longer fails on an unreadable subagent payload (#30783) --- .../075_SubagentDeliveryState.test.ts | 48 +++++++++++++++++++ .../Migrations/075_SubagentDeliveryState.ts | 4 +- 2 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 apps/server/src/persistence/Migrations/075_SubagentDeliveryState.test.ts diff --git a/apps/server/src/persistence/Migrations/075_SubagentDeliveryState.test.ts b/apps/server/src/persistence/Migrations/075_SubagentDeliveryState.test.ts new file mode 100644 index 0000000000000..c652d1f9bc851 --- /dev/null +++ b/apps/server/src/persistence/Migrations/075_SubagentDeliveryState.test.ts @@ -0,0 +1,48 @@ +import { assert, it } from "@effect/vitest"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +import { runMigrations } from "../Migrations.ts"; + +const layer = it.layer(NodeSqliteClient.layer({ filename: ":memory:" })); +const updatedAt = "2026-09-01T00:00:00.000Z"; +const deliveredPayload = JSON.stringify({ completionDelivery: { state: "delivered" } }); + +layer("075_SubagentDeliveryState", (it) => { + it.effect("backfills delivery state without failing on an unreadable payload", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* runMigrations({ toMigrationInclusive: 74 }); + const payloads = [ + ["delivered", deliveredPayload], + ["unreadable", ""], + ]; + for (const [id, payload] of payloads) { + yield* sql` + INSERT INTO orchestration_v2_projection_subagents ( + subagent_id, thread_id, parent_node_id, provider, origin, status, updated_at, + payload_json + ) VALUES ( + ${id}, 'thread-1', 'node-1', 'codex', 'delegated', 'cancelled', ${updatedAt}, + ${payload} + ) + `; + } + + yield* runMigrations({ toMigrationInclusive: 75 }); + const rows = yield* sql` + SELECT subagent_id, completion_delivery_state, payload_json + FROM orchestration_v2_projection_subagents ORDER BY subagent_id + `; + assert.deepStrictEqual(rows, [ + { + subagent_id: "delivered", + completion_delivery_state: "delivered", + payload_json: deliveredPayload, + }, + { subagent_id: "unreadable", completion_delivery_state: null, payload_json: "" }, + ]); + }), + ); +}); diff --git a/apps/server/src/persistence/Migrations/075_SubagentDeliveryState.ts b/apps/server/src/persistence/Migrations/075_SubagentDeliveryState.ts index 4406911cc8a8c..0288c89ceed05 100644 --- a/apps/server/src/persistence/Migrations/075_SubagentDeliveryState.ts +++ b/apps/server/src/persistence/Migrations/075_SubagentDeliveryState.ts @@ -11,7 +11,9 @@ export default Effect.gen(function* () { yield* sql` UPDATE orchestration_v2_projection_subagents SET completion_delivery_state = json_extract(payload_json, '$.completionDelivery.state') - WHERE json_type(payload_json, '$.completionDelivery') IS NOT NULL + WHERE CASE WHEN json_valid(payload_json) + THEN json_type(payload_json, '$.completionDelivery') IS NOT NULL + ELSE 0 END `; yield* sql` CREATE INDEX orchestration_v2_projection_subagents_settled_idx From 671e05bc8cdd83c90673a0e254e43f6042263547 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 03:20:57 -0800 Subject: [PATCH 135/324] fix(issues): an Activity cross-reference opens the issue or pull request it came from (#40768) --- .../src/features/issues/IssueRouteScreen.tsx | 60 ++++++++++++++++- .../chat/RightPanelSurfaceContent.tsx | 19 +++++- .../src/components/issue/IssueDetailPanel.tsx | 65 ++++++++++++++++++- apps/web/src/components/issue/IssuesPage.tsx | 9 ++- packages/contracts/src/issue.ts | 10 +++ .../src/server/GitHubIssueTracker.test.ts | 9 +++ .../src/server/gitHubIssueJson.ts | 30 ++++++--- .../src/server/issues.graphql | 1 + .../src/server/issues.graphql.ts | 4 +- .../src/server/GitLabIssueTracker.test.ts | 14 ++++ .../src/server/GitLabIssueTracker.ts | 10 ++- .../src/server/gitLabIssueJson.ts | 35 ++++++++++ 12 files changed, 247 insertions(+), 19 deletions(-) diff --git a/apps/mobile/src/features/issues/IssueRouteScreen.tsx b/apps/mobile/src/features/issues/IssueRouteScreen.tsx index 2e5354b23f50f..8312bb703894b 100644 --- a/apps/mobile/src/features/issues/IssueRouteScreen.tsx +++ b/apps/mobile/src/features/issues/IssueRouteScreen.tsx @@ -7,6 +7,7 @@ import { visibleLinkedThreads } from "@t3tools/client-runtime/state/threads"; import type { IssueComment, IssueEvent, + IssueEventReference, IssueLinkedPullRequest, IssueReaction, IssueState, @@ -404,9 +405,48 @@ function IssueCommentCard(props: { ); } -function IssueEventRow({ event }: { readonly event: IssueEvent }) { +function IssueEventRow({ + params, + event, +}: { + readonly params: IssueParams; + readonly event: IssueEvent; +}) { const gt = useGT(); const messages = useMessages(); + const navigation = useNavigation(); + const sentence = issueEventSentence(event, messages); + const source = event.reference; + const at = event.detail === null ? -1 : sentence.indexOf(event.detail); + // Only a git host's tracker shares its host with the change request it links. + const sameHost = sourceControlClients.find(params.tracker) !== undefined; + const openSource = (target: IssueEventReference) => { + const host = params.host ? { host: params.host } : {}; + if (target.kind === "issue") { + navigation.dispatch( + StackActions.push("Issue", { + environmentId: params.environmentId, + projectId: params.projectId, + tracker: params.tracker, + ...host, + scope: target.repository, + issueKey: String(target.number), + }), + ); + } else if (sameHost) { + navigation.dispatch( + StackActions.push("PullRequest", { + environmentId: params.environmentId, + projectId: params.projectId, + repository: target.repository, + number: target.number, + ...host, + }), + ); + } else { + void tryOpenExternalUrl(target.url); + } + }; return ( @@ -414,7 +454,21 @@ function IssueEventRow({ event }: { readonly event: IssueEvent }) { {event.actor?.login ?? gt("Someone", { $context: "an unknown person" })} {" "} - {issueEventSentence(event, messages)} + {source === undefined || event.detail === null || at < 0 ? ( + sentence + ) : ( + <> + {sentence.slice(0, at)} + openSource(source)} + > + {event.detail} + + {sentence.slice(at + event.detail.length)} + + )} {relativeTime(event.createdAt, undefined, messages)} @@ -505,7 +559,7 @@ function IssueRoute({ params }: { readonly params: IssueParams }) { ...detail.events.map((event) => ({ key: `e:${event.id}`, at: event.createdAt, - content: , + content: , })), ].sort((left, right) => Date.parse(left.at) - Date.parse(right.at)) : []; diff --git a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx b/apps/web/src/components/chat/RightPanelSurfaceContent.tsx index 076c78d88d468..8b4bb6232287b 100644 --- a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx +++ b/apps/web/src/components/chat/RightPanelSurfaceContent.tsx @@ -141,9 +141,14 @@ export function RightPanelSurfaceContent(props: { getShortcutContext={props.getShortcutContext} shortcutsEnabled={visible && props.activeSurfaceId === surface.id} key={`${scopedThreadKey(threadRef)}:${surface.id}`} - environmentId={props.environmentId} + environmentId={ + (surface.environmentId as EnvironmentId | undefined) ?? props.environmentId + } onSelectPullRequest={(reference) => { useRightPanelStore.getState().openPullRequest(threadRef, { + ...(surface.environmentId === undefined + ? {} + : { environmentId: surface.environmentId }), projectId: reference.projectId, repository: reference.repository, number: reference.number, @@ -205,12 +210,24 @@ export function RightPanelSurfaceContent(props: { threadRef={threadRef} onSelectPullRequest={(reference) => { useRightPanelStore.getState().openPullRequest(threadRef, { + ...(surface.environmentId === undefined + ? {} + : { environmentId: surface.environmentId }), projectId: reference.projectId, repository: reference.repository, number: reference.number, ...(reference.host ? { host: reference.host } : {}), }); }} + onSelectIssue={({ host, ...reference }) => { + useRightPanelStore.getState().openIssue(threadRef, { + ...(surface.environmentId === undefined + ? {} + : { environmentId: surface.environmentId }), + ...reference, + ...(host ? { host } : {}), + }); + }} /> ); case "pull-requests": diff --git a/apps/web/src/components/issue/IssueDetailPanel.tsx b/apps/web/src/components/issue/IssueDetailPanel.tsx index bdee83563a330..30a55dd1d9e48 100644 --- a/apps/web/src/components/issue/IssueDetailPanel.tsx +++ b/apps/web/src/components/issue/IssueDetailPanel.tsx @@ -18,6 +18,7 @@ import type { IssueComment, IssueDetail, IssueEvent, + IssueEventReference, IssueLabelCandidate, IssueLinkedPullRequest, IssueListEntry, @@ -376,12 +377,44 @@ function LinkedPullRequestRow({ ); } +/** The sentence for an event, its source shown as a link where the tracker named one. */ +function IssueEventText({ + event, + sentence, + onOpen, +}: { + event: IssueEvent; + sentence: string; + /** Opens the source beside this issue, and says whether it did; if not, the link goes to the host. */ + onOpen: (source: IssueEventReference) => boolean; +}) { + const source = event.reference; + const at = event.detail === null ? -1 : sentence.indexOf(event.detail); + if (source === undefined || event.detail === null || at < 0) return {sentence}; + return ( + + {sentence.slice(0, at)} + } + onClick={(click) => { + if (!click.metaKey && !click.ctrlKey && onOpen(source)) click.preventDefault(); + }} + > + {event.detail} + + {sentence.slice(at + event.detail.length)} + + ); +} + export function IssueDetailPanel({ environmentId, reference, threadRef = null, listEntry = null, onSelectPullRequest, + onSelectIssue, }: { environmentId: EnvironmentId; reference: IssueRef; @@ -390,6 +423,8 @@ export function IssueDetailPanel({ threadRef?: ScopedThreadRef | null; /** Opens a linked change request beside this one; absent, the link goes to the host. */ onSelectPullRequest?: ((reference: PullRequestRef) => void) | undefined; + /** Opens a referenced issue beside this one; absent, the link goes to the host. */ + onSelectIssue?: ((reference: IssueRef & { readonly url: string }) => void) | undefined; }) { const gt = useGT(); const messages = useMessages(); @@ -442,6 +477,30 @@ export function IssueDetailPanel({ const tracker = issueTrackerPresentation(detail.tracker); const currentState = issueStatePresentation(detail.state); + const host = reference.host === undefined ? {} : { host: reference.host }; + const openEventSource = (source: IssueEventReference) => { + if (source.kind === "pull-request") { + if (!onSelectPullRequest) return false; + onSelectPullRequest({ + projectId: reference.projectId, + ...host, + repository: source.repository, + number: source.number, + }); + return true; + } + if (!onSelectIssue) return false; + onSelectIssue({ + projectId: reference.projectId, + tracker: reference.tracker, + ...host, + scope: source.repository, + key: String(source.number), + url: source.url, + }); + return true; + }; + const loadOlder = async () => { const failure = await pager.loadOlder(registry, (cursor) => loadComments({ environmentId, input: { ...reference, cursor } }), @@ -869,7 +928,11 @@ export function IssueDetailPanel({ className="px-1 text-xs text-muted-foreground" > - {issueEventSentence(item.event, messages)} + {formatRelativeTimeLabel(item.event.createdAt, undefined, messages)} ), diff --git a/apps/web/src/components/issue/IssuesPage.tsx b/apps/web/src/components/issue/IssuesPage.tsx index e29e3aa3c8123..d1c9f77aa2917 100644 --- a/apps/web/src/components/issue/IssuesPage.tsx +++ b/apps/web/src/components/issue/IssuesPage.tsx @@ -419,7 +419,7 @@ export function IssuesPage() { : clearedSelection, ); - const selectEntry = (entry: IssueRowTarget) => { + const selectEntry = (entry: Omit & { readonly host?: string }) => { if (rightPanelRef === null) return; useRightPanelStore.getState().openIssue(rightPanelRef, entry); updateSearch({ @@ -864,6 +864,13 @@ export function IssuesPage() { environmentId: panelEnvironmentId, }); }} + onSelectIssue={({ host, ...reference }) => + selectEntry({ + ...reference, + ...(host === undefined ? {} : { host }), + environmentId: panelEnvironmentId, + }) + } /> ) : ( event.kind === "referenced")).toMatchObject({ + reference: { + repository: "acme/web", + number: 50, + kind: "pull-request", + url: "https://github.com/acme/web/pull/50", + }, + }); }), ); }); diff --git a/packages/source-control-github/src/server/gitHubIssueJson.ts b/packages/source-control-github/src/server/gitHubIssueJson.ts index e46ad7ec9e515..59e9b9efd118e 100644 --- a/packages/source-control-github/src/server/gitHubIssueJson.ts +++ b/packages/source-control-github/src/server/gitHubIssueJson.ts @@ -5,7 +5,6 @@ import type { IssueActor, IssueComment, IssueEvent, - IssueEventKind, IssueLabel, IssueLinkedPullRequest, IssueState, @@ -137,7 +136,7 @@ function toLinkedPullRequest( /** The change GitHub recorded, or null for a kind this page has no vocabulary for. */ function toEventFields( raw: TimelineItem, -): { readonly kind: IssueEventKind; readonly detail: string | null } | null { +): Pick | null { switch (raw.__typename) { case "ClosedEvent": return { kind: "closed", detail: null }; @@ -164,15 +163,28 @@ function toEventFields( case "RenamedTitleEvent": return { kind: "renamed", detail: trimmed(raw.currentTitle) }; case "CrossReferencedEvent": { - const repository = trimmed( - raw.source != null && "repository" in raw.source - ? raw.source.repository.nameWithOwner - : null, - ); - const number = raw.source != null && "number" in raw.source ? raw.source.number : 0; + const source = + raw.source.__typename === "PullRequest" || raw.source.__typename === "Issue" + ? raw.source + : null; + const repository = trimmed(source?.repository.nameWithOwner); + const url = trimmed(source?.url); + if (source === null || repository === null || source.number <= 0) { + return { kind: "referenced", detail: null }; + } return { kind: "referenced", - detail: repository === null || number <= 0 ? null : `${repository}#${number}`, + detail: `${repository}#${source.number}`, + ...(url === null + ? {} + : { + reference: { + repository, + number: source.number, + kind: source.__typename === "PullRequest" ? "pull-request" : "issue", + url, + }, + }), }; } default: diff --git a/packages/source-control-github/src/server/issues.graphql b/packages/source-control-github/src/server/issues.graphql index 18c8cee3536a2..d8b28a08c7078 100644 --- a/packages/source-control-github/src/server/issues.graphql +++ b/packages/source-control-github/src/server/issues.graphql @@ -231,6 +231,7 @@ query IssueDetail($owner: String!, $name: String!, $number: Int!) { } ... on Issue { number + url repository { nameWithOwner } diff --git a/packages/source-control-github/src/server/issues.graphql.ts b/packages/source-control-github/src/server/issues.graphql.ts index 9d059396d26a0..fb393ef5ca4c6 100644 --- a/packages/source-control-github/src/server/issues.graphql.ts +++ b/packages/source-control-github/src/server/issues.graphql.ts @@ -487,6 +487,8 @@ export const SourceIssue = Schema.Struct({ __typename: Schema.Literal("Issue"), /** Identifies the issue number. */ number: Shared.Int, + /** The HTTP URL for this issue */ + url: Shared.URI, /** The repository associated with this node. */ repository: NodesRepositoryRepository }) @@ -584,7 +586,7 @@ export const IssueDetail = GraphQL.query("IssueDetail", { ], selections: [ { name: "viewer", body: ["{login}"] }, - { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){viewerPermission issue(number:$", "number", "){...IssueRow assignees(first:100){pageInfo{hasNextPage endCursor}nodes{login name avatarUrl}}labels(first:100){pageInfo{hasNextPage endCursor}nodes{name color}}body viewerCanUpdate viewerCanClose viewerCanReopen...Reactions comments(last:100){totalCount pageInfo{hasPreviousPage startCursor}nodes{id author{__typename login avatarUrl}body createdAt url...Reactions}}closedByPullRequestsReferences(first:20 includeClosedPrs:true){pageInfo{hasNextPage endCursor}nodes{number title url state isDraft repository{nameWithOwner}}}timelineItems(last:100 itemTypes:[CLOSED_EVENT REOPENED_EVENT LABELED_EVENT UNLABELED_EVENT ASSIGNED_EVENT UNASSIGNED_EVENT RENAMED_TITLE_EVENT CROSS_REFERENCED_EVENT]){nodes{__typename...on ClosedEvent{id createdAt actor{__typename login avatarUrl}}...on ReopenedEvent{id createdAt actor{__typename login avatarUrl}}...on LabeledEvent{id createdAt actor{__typename login avatarUrl}label{name}}...on UnlabeledEvent{id createdAt actor{__typename login avatarUrl}label{name}}...on AssignedEvent{id createdAt actor{__typename login avatarUrl}assignee{__typename...on User{login name}...on Bot{login}}}...on UnassignedEvent{id createdAt actor{__typename login avatarUrl}assignee{__typename...on User{login name}...on Bot{login}}}...on RenamedTitleEvent{id createdAt actor{__typename login avatarUrl}currentTitle}...on CrossReferencedEvent{id createdAt actor{__typename login avatarUrl}source{__typename...on PullRequest{number title url state isDraft repository{nameWithOwner}}...on Issue{number repository{nameWithOwner}}}}}}}}"] } + { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){viewerPermission issue(number:$", "number", "){...IssueRow assignees(first:100){pageInfo{hasNextPage endCursor}nodes{login name avatarUrl}}labels(first:100){pageInfo{hasNextPage endCursor}nodes{name color}}body viewerCanUpdate viewerCanClose viewerCanReopen...Reactions comments(last:100){totalCount pageInfo{hasPreviousPage startCursor}nodes{id author{__typename login avatarUrl}body createdAt url...Reactions}}closedByPullRequestsReferences(first:20 includeClosedPrs:true){pageInfo{hasNextPage endCursor}nodes{number title url state isDraft repository{nameWithOwner}}}timelineItems(last:100 itemTypes:[CLOSED_EVENT REOPENED_EVENT LABELED_EVENT UNLABELED_EVENT ASSIGNED_EVENT UNASSIGNED_EVENT RENAMED_TITLE_EVENT CROSS_REFERENCED_EVENT]){nodes{__typename...on ClosedEvent{id createdAt actor{__typename login avatarUrl}}...on ReopenedEvent{id createdAt actor{__typename login avatarUrl}}...on LabeledEvent{id createdAt actor{__typename login avatarUrl}label{name}}...on UnlabeledEvent{id createdAt actor{__typename login avatarUrl}label{name}}...on AssignedEvent{id createdAt actor{__typename login avatarUrl}assignee{__typename...on User{login name}...on Bot{login}}}...on UnassignedEvent{id createdAt actor{__typename login avatarUrl}assignee{__typename...on User{login name}...on Bot{login}}}...on RenamedTitleEvent{id createdAt actor{__typename login avatarUrl}currentTitle}...on CrossReferencedEvent{id createdAt actor{__typename login avatarUrl}source{__typename...on PullRequest{number title url state isDraft repository{nameWithOwner}}...on Issue{number url repository{nameWithOwner}}}}}}}}"] } ], fragments: [ { name: "IssueRow", body: ["on Issue{number title url state stateReason createdAt updatedAt closedAt author{__typename login avatarUrl...on User{name}}}"] }, diff --git a/packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts b/packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts index 7c794de8b456e..d3bd6e01366bd 100644 --- a/packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts @@ -59,6 +59,13 @@ function answer(path: string): string { created_at: "2026-07-03T00:00:00Z", system: true, }, + { + id: 10, + body: "mentioned in merge request api!51", + author: { username: "theo" }, + created_at: "2026-07-04T00:00:00Z", + system: true, + }, ]); } if (path.startsWith("projects/acme%2Fweb/issues/42/resource_label_events")) { @@ -206,7 +213,14 @@ describe("GitLabIssueTracker", () => { expect(issue.events.map((event) => [event.kind, event.detail])).toEqual([ ["labeled", "bug"], ["closed", null], + ["referenced", "merge request api!51"], ]); + expect(issue.events.at(-1)?.reference).toEqual({ + repository: "acme/api", + number: 51, + kind: "pull-request", + url: "https://gitlab.com/acme/api/-/merge_requests/51", + }); // A closing merge request is not repeated as a related one. expect( issue.linkedPullRequests.map((link) => [link.number, link.closesIssue, link.isDraft]), diff --git a/packages/source-control-gitlab/src/server/GitLabIssueTracker.ts b/packages/source-control-gitlab/src/server/GitLabIssueTracker.ts index f8b1f80c18b0e..4f4aeb3135034 100644 --- a/packages/source-control-gitlab/src/server/GitLabIssueTracker.ts +++ b/packages/source-control-gitlab/src/server/GitLabIssueTracker.ts @@ -25,6 +25,7 @@ import { decodeIssueDetailListJson, decodeIssueListJson, decodeIssueNotesJson, + withMentionReference, decodeLabelEventsJson, decodeLinkedMergeRequestsJson, decodeProjectLabelsJson, @@ -576,9 +577,12 @@ export const make: Effect.Effect = reactions: awardPage?.reactionsByNoteId.get(comment.id) ?? [], })), commentsCursor: commentsCursor(notes.nextCursor, awardPage?.nextCursor ?? null), - events: [...systemEvents, ...labelEvents].sort((left, right) => - left.createdAt.localeCompare(right.createdAt), - ), + events: [ + ...systemEvents.map((event) => + withMentionReference(event, issue.url, input.scope), + ), + ...labelEvents, + ].sort((left, right) => left.createdAt.localeCompare(right.createdAt)), // A merge request that closes the issue outranks its sighting as a mere mention. linkedPullRequests: [ ...closing, diff --git a/packages/source-control-gitlab/src/server/gitLabIssueJson.ts b/packages/source-control-gitlab/src/server/gitLabIssueJson.ts index 5458ed4f859ef..7a52667a4a425 100644 --- a/packages/source-control-gitlab/src/server/gitLabIssueJson.ts +++ b/packages/source-control-gitlab/src/server/gitLabIssueJson.ts @@ -250,6 +250,41 @@ function toSystemEvent( return null; } +// The path class excludes the sigil, so matching is linear on any input. +const MENTION = /^(?:merge request ([\w.\-/]*)!|issue ([\w.\-/]*)#)([1-9]\d*)$/; + +/** + * Where a "mentioned in merge request !12" note came from, addressed from the issue's own web URL + * so a self-managed host under a subpath resolves. A commit, epic or snippet mention gets none. + */ +export function withMentionReference( + event: IssueEvent, + issueUrl: string, + scope: string, +): IssueEvent { + const match = event.kind === "referenced" ? MENTION.exec(event.detail ?? "") : null; + const projectUrl = issueUrl.split("/-/")[0]!; + if (match === null || !projectUrl.toLowerCase().endsWith(`/${scope.toLowerCase()}`)) { + return event; + } + const [, mergeRequestPath, issuePath, digits] = match; + const isMergeRequest = mergeRequestPath !== undefined; + const path = mergeRequestPath ?? issuePath ?? ""; + // A project in the same namespace is named by its path alone. + const repository = + path === "" ? scope : path.includes("/") ? path : `${scope.replace(/[^/]*$/, "")}${path}`; + const base = projectUrl.slice(0, projectUrl.length - scope.length); + return { + ...event, + reference: { + repository, + number: Number(digits), + kind: isMergeRequest ? "pull-request" : "issue", + url: `${base}${repository}/-/${isMergeRequest ? "merge_requests" : "issues"}/${digits}`, + }, + }; +} + interface GitLabIssueNotes { readonly comments: ReadonlyArray; readonly events: ReadonlyArray; From 8435a8cd418f6d46bbb00e812be1f53932c2aac8 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 03:25:22 -0800 Subject: [PATCH 136/324] fix(server): tell a stopped parent which delegated tasks its Stop interrupted (#34499) --- .../DelegatedCompletionDelivery.test.ts | 133 ++++++++++++++++++ .../src/orchestration-v2/Orchestrator.ts | 17 ++- .../ProviderTurnStartService.ts | 56 ++++++-- .../RestartBackgroundNote.test.ts | 52 +++++++ .../orchestration-v2/RestartBackgroundNote.ts | 72 ++++++++++ 5 files changed, 315 insertions(+), 15 deletions(-) diff --git a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts index 441c9992e73cc..3d6575bd6a405 100644 --- a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts +++ b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts @@ -19,6 +19,7 @@ import { ProviderInstanceId, ProviderSessionId, ProviderThreadId, + ProviderTurnId, RunId, RuntimeRequestId, ThreadId, @@ -5063,6 +5064,138 @@ it.layer(layerTest)("delegated tasks across a server restart", (it) => { }), ); + // regression: #34401 a parent's Stop killed a child's background build but its task read completed + it.effect("reports a child its parent's Stop reached as interrupted", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const eventSink = yield* EventSink.EventSinkV2; + const now = yield* DateTime.now; + const stoppedAt = DateTime.add(now, { seconds: 10 }); + const threadId = ThreadId.make("thread:stop-background-parent"); + const projectId = ProjectId.make("project:stop-background-parent"); + const runId = RunId.make("run:stop-background-parent"); + const rootNodeId = NodeId.make("node:stop-background-parent-root"); + yield* seedParentWithTerminalTask({ + threadId, + projectId, + runId, + rootNodeId, + taskId: NodeId.make("node:stop-background-parent-settled"), + deliveryState: "delivered", + now, + }); + // Background launches report their command finished at once; only the roster tracks the work. + const seedStoppedChild = (name: string, parentStopped: boolean, reachedTurn: boolean) => + Effect.gen(function* () { + const child = yield* seedRestartCancelledChild({ + parentThreadId: threadId, + projectId, + parentRunId: runId, + rootNodeId, + name, + completionWake: "always", + continuationPending: false, + runStatus: "completed", + now, + }); + const item = { + threadId: child.childThreadId, + runId: child.childRunId, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + }; + const scope = { + type: "turn-item.updated" as const, + threadId: child.childThreadId, + runId: child.childRunId, + providerInstanceId: modelSelection.instanceId, + }; + yield* eventSink.write({ + commandId: CommandId.make(`command:${name}:stop`), + events: [ + { + ...scope, + id: EventId.make(`event:${name}:command`), + occurredAt: now, + payload: { + ...item, + id: TurnItemId.make(`turn-item:${name}:command`), + type: "command_execution", + ordinal: 1, + status: "completed", + title: "Run build", + input: "./build.sh", + startedAt: now, + completedAt: now, + updatedAt: now, + }, + }, + { + ...scope, + id: EventId.make(`event:${name}:interrupt-request`), + occurredAt: stoppedAt, + payload: { + ...item, + id: TurnItemId.make(`turn-item:${name}:interrupt-request`), + // Stop interrupting background work names its provider turn; an idle run's marker does not. + providerTurnId: reachedTurn ? ProviderTurnId.make(`provider-turn:${name}`) : null, + type: "run_interrupt_request", + ordinal: 2, + status: "completed", + title: "Interrupt requested", + startedAt: stoppedAt, + completedAt: stoppedAt, + updatedAt: stoppedAt, + message: "Stopped by user", + }, + }, + ], + }); + if (parentStopped) { + const task = (yield* orchestrator.getThreadProjection(threadId)).subagents.find( + (row) => row.id === child.taskId, + )!; + yield* eventSink.write({ + commandId: CommandId.make(`command:${name}:parent-stop`), + events: [ + { + id: EventId.make(`event:${name}:disposed`), + type: "subagent.updated", + threadId, + runId, + nodeId: task.id, + driver, + providerInstanceId: modelSelection.instanceId, + occurredAt: stoppedAt, + payload: { + ...task, + completionDelivery: { state: "disposed", observedByRunId: null }, + updatedAt: stoppedAt, + }, + }, + ], + }); + } + return child; + }); + const cut = yield* seedStoppedChild("stop-background-cut", true, true); + const idle = yield* seedStoppedChild("stop-background-idle", true, false); + const finished = yield* seedStoppedChild("stop-background-finished", false, true); + + yield* orchestrator.recoverDelegatedTasks; + + const settled = yield* orchestrator.getThreadProjection(threadId); + const statusOf = (taskId: NodeId) => + settled.subagents.find((row) => row.id === taskId)?.status; + assert.equal(statusOf(cut.taskId), "interrupted"); + assert.equal(statusOf(idle.taskId), "completed"); + assert.equal(statusOf(finished.taskId), "completed"); + }), + ); + it.effect("cancelling a task whose child already finished keeps its completed result", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 61f5027793569..5936f57ad5014 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -15132,7 +15132,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio messageRoles: ["assistant"], messageRunIds: resultRunIds, turnItemRunIds: resultRunIds, - turnItemTypes: SUBAGENT_RESULT_TURN_ITEM_TYPES, + turnItemTypes: [...SUBAGENT_RESULT_TURN_ITEM_TYPES, "run_interrupt_request"], providerTurnAttemptIds: [childRun, ...reportRuns].flatMap( (run) => run.activeAttemptId ?? [], ), @@ -15177,9 +15177,20 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio if (task === undefined) { return; } - // A cancelled task's completed run ends it interrupted. + // A cancelled task's completed run ends it interrupted, as does one whose provider turn its + // parent's Stop interrupted to kill background work. Stop's marker on an idle run names no + // provider turn and interrupted nothing. const cancelled = task.cancelledRunId === childRun.id; - if (cancelled && terminalStatus === "completed") outcome = terminalStatus = "interrupted"; + const stopped = + task.completionDelivery?.state === "disposed" && + childResult.turnItems.some( + (item) => + item.runId === childRun.id && + item.type === "run_interrupt_request" && + item.providerTurnId !== null, + ); + if ((cancelled || stopped) && terminalStatus === "completed") + outcome = terminalStatus = "interrupted"; // Every result the child sent is among its own transfers, far fewer than the parent's. const childTransfers = yield* projectionStore.getThreadRecords(childThreadId, [ "contextTransfers", diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index c3890cab5f71b..752b13568a111 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -80,7 +80,9 @@ import * as TurnItemPositionStore from "./TurnItemPositionStore.ts"; import { isRestartNoteContinuation, pendingRestartCancelledBackgroundWork, + pendingStoppedDelegatedTasks, restartCancelledBackgroundWorkNote, + stoppedDelegatedTasksNote, } from "./RestartBackgroundNote.ts"; export class ProviderTurnStartError extends Schema.TaggedError()( @@ -1029,26 +1031,56 @@ export const layer: Layer.Layer< projection.providerTurns, projection.attempts, ); + let compactionMessageIdSet: ReadonlySet | undefined; + const compactionMessageIds = () => + (compactionMessageIdSet ??= new Set( + projection.messages + .filter( + (candidate) => + isCompactionCommandMessage(candidate) || + (goalDriver && parseGoalCommand(candidate) !== null), + ) + .map((candidate) => candidate.id), + )); const restartCancelledWork = pendingRestartCancelledBackgroundWork({ runs: projection.runs, providerTurns: projection.providerTurns, - compactionMessageIds: () => - new Set( - projection.messages - .filter( - (candidate) => - isCompactionCommandMessage(candidate) || - (goalDriver && parseGoalCommand(candidate) !== null), - ) - .map((candidate) => candidate.id), - ), + compactionMessageIds, run, attempts: projection.attempts, }); - const restartNote = + // The turn start context omits settled tasks, so read them only after a Stop disposed some. + // A failed read fails the start: a turn that ran without the note would count as telling it. + const stoppedRunIds = projection.runs + .filter( + (source) => + source.providerThreadId === run.providerThreadId && + source.delegatedCompletion?.disposition === "stopped", + ) + .map((source) => source.id); + const stoppedTasks = + stoppedRunIds.length === 0 || compactionMessageIds().has(run.userMessageId) + ? [] + : pendingStoppedDelegatedTasks({ + providerThreadId: run.providerThreadId, + runs: projection.runs, + providerTurns: projection.providerTurns, + attempts: projection.attempts, + compactionMessageIds: compactionMessageIds(), + subagents: (yield* projectionStore.getThreadRecords( + projection.thread.id, + ["subagents"], + { subagentRunIds: stoppedRunIds }, + )).subagents, + }); + const restartNote = [ restartCancelledWork.length === 0 ? "" - : restartCancelledBackgroundWorkNote(restartCancelledWork); + : restartCancelledBackgroundWorkNote(restartCancelledWork), + stoppedTasks.length === 0 ? "" : stoppedDelegatedTasksNote(stoppedTasks), + ] + .filter((part) => part !== "") + .join("\n\n"); const tokenCap = yield* handoffTokenCapConfig.pipe( Effect.orElseSucceed(() => DEFAULT_HANDOFF_TOKEN_CAP), ); diff --git a/apps/server/src/orchestration-v2/RestartBackgroundNote.test.ts b/apps/server/src/orchestration-v2/RestartBackgroundNote.test.ts index b5b3a033789dd..bd5b016fdc673 100644 --- a/apps/server/src/orchestration-v2/RestartBackgroundNote.test.ts +++ b/apps/server/src/orchestration-v2/RestartBackgroundNote.test.ts @@ -1,10 +1,12 @@ import { assert, it } from "@effect/vitest"; import { MessageId, + NodeId, ProviderThreadId, RunAttemptId, RunId, type OrchestrationV2Run, + type OrchestrationV2Subagent, } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; @@ -14,7 +16,9 @@ import { isAwaitedWork, isRestartNoteContinuation, pendingRestartCancelledBackgroundWork, + pendingStoppedDelegatedTasks, restartContinuationNote, + stoppedDelegatedTasksNote, mergeRestartCancelledBackgroundWork, } from "./RestartBackgroundNote.ts"; @@ -277,3 +281,51 @@ it("counts a prompted mid-turn or chained continuation as delivering the note", [], ); }); + +// regression: #34401 Stop interrupted a parent's delegated tasks without telling its agent +it("tells the next completed turn about delegated tasks its Stop interrupted, once", () => { + const at = (minute: number) => DateTime.makeUnsafe(`2026-10-03T10:0${minute}:00.000Z`); + const spawning = run(1, claudeThread, { + requestedAt: at(0), + delegatedCompletion: { disposition: "stopped", nextGeneration: 1, delivery: null }, + }); + const task = (id: string, extra: Partial = {}) => + ({ + id: NodeId.make(id), + runId: spawning.id, + origin: "app_owned", + prompt: `Run ${id}.`, + title: null, + status: "interrupted", + completionDelivery: { state: "disposed", observedByRunId: null }, + completedAt: at(1), + ...extra, + }) as OrchestrationV2Subagent; + const stopped = task("stopped", { title: "Build A" }); + const subagents = [ + stopped, + task("cancelled", { cancelledRunId: RunId.make("run:child") }), + task("finished", { status: "completed" }), + task("delivered", { completionDelivery: { state: "delivered", observedByRunId: null } }), + ]; + const pending = (runs: ReadonlyArray, providerThreadId = claudeThread) => + pendingStoppedDelegatedTasks({ + providerThreadId, + runs, + providerTurns: runs.map(turnFor), + attempts: runs.map((source) => ({ id: source.activeAttemptId!, runId: source.id })), + subagents, + compactionMessageIds: new Set(), + }); + + assert.deepEqual(pending([spawning]), [stopped]); + // A /clear turn starts a fresh provider thread that never saw the stopped tasks. + assert.deepEqual(pending([spawning], codexThread), []); + assert.equal(stoppedDelegatedTasksNote([stopped]).split("\n")[1], "- Build A (task stopped)"); + // Requested while the task was still settling, so its turn start could not see it. + const racing = run(2, claudeThread, { requestedAt: at(0), startedAt: at(2) }); + assert.deepEqual(pending([spawning, racing]), [stopped]); + assert.deepEqual(pending([spawning, racing, run(3, claudeThread, { requestedAt: at(2) })]), []); + // A fresh-context turn on another provider thread never carried the note. + assert.deepEqual(pending([spawning, run(3, codexThread, { requestedAt: at(2) })]), [stopped]); +}); diff --git a/apps/server/src/orchestration-v2/RestartBackgroundNote.ts b/apps/server/src/orchestration-v2/RestartBackgroundNote.ts index 58918bdef612d..878392b8377c6 100644 --- a/apps/server/src/orchestration-v2/RestartBackgroundNote.ts +++ b/apps/server/src/orchestration-v2/RestartBackgroundNote.ts @@ -13,6 +13,7 @@ import { } from "@t3tools/contracts"; import { subagentHoldsCompletion } from "@t3tools/provider-core/server/subagentProjection"; import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; +import * as DateTime from "effect/DateTime"; import { latestRootProviderFailure, runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError"; type Work = OrchestrationV2RestartCancelledBackgroundWork; @@ -150,6 +151,77 @@ export function restartCancelledBackgroundWorkNote( ].join("\n"); } +/** + * Delegated tasks a Stop on this provider thread interrupted, until a turn requested after they + * ended completes. A run's turn start reads tasks after its request, but can record startedAt + * later. A fresh context starts a new provider thread, so it never inherits the note. + */ +export function pendingStoppedDelegatedTasks(input: { + readonly providerThreadId: OrchestrationV2Run["providerThreadId"]; + readonly runs: ReadonlyArray; + readonly providerTurns: ReadonlyArray>; + readonly attempts: ReadonlyArray; + readonly subagents: ReadonlyArray; + readonly compactionMessageIds: ReadonlySet; +}): ReadonlyArray { + const stoppedRunIds = new Set( + input.runs + .filter( + (run) => + run.providerThreadId === input.providerThreadId && + run.delegatedCompletion?.disposition === "stopped", + ) + .map((run) => run.id), + ); + if (stoppedRunIds.size === 0) return []; + const completedAttemptIds = new Set( + input.providerTurns + .filter((turn) => turn.status === "completed") + .map((turn) => turn.runAttemptId), + ); + const toldRunRequests = input.runs + .filter( + (run) => + run.providerThreadId === input.providerThreadId && + !input.compactionMessageIds.has(run.userMessageId) && + input.attempts.some( + (attempt) => attempt.runId === run.id && completedAttemptIds.has(attempt.id), + ), + ) + .map((run) => DateTime.toEpochMillis(run.requestedAt)); + return input.subagents.filter( + (task) => + task.origin === "app_owned" && + task.runId !== null && + stoppedRunIds.has(task.runId) && + task.status === "interrupted" && + task.cancelledRunId === undefined && + task.completionDelivery?.state === "disposed" && + task.completedAt !== null && + !toldRunRequests.some( + (requestedAt) => requestedAt > DateTime.toEpochMillis(task.completedAt!), + ), + ); +} + +export function stoppedDelegatedTasksNote(tasks: ReadonlyArray): string { + const omitted = tasks.length - MAX_NOTE_ENTRIES; + return [ + "Note: Stop on this thread also stopped these delegated tasks before they finished. They will not report back on their own, so check them with task_status and start again what you still need:", + ...tasks + .slice(0, MAX_NOTE_ENTRIES) + .map( + (task) => + `- ${labelWithId( + compactLabel(task.title) === undefined ? task.prompt : task.title, + "delegated task", + ` (task ${task.id})`, + )}`, + ), + ...(omitted > 0 ? [`- and ${omitted} more`] : []), + ].join("\n"); +} + type ProviderTurnState = Pick< OrchestrationV2ProviderTurn, "runAttemptId" | "providerThreadId" | "status" | "promptDropped" From f931f03d6115bbe7f2dde6817c43620f6df20528 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 03:26:17 -0800 Subject: [PATCH 137/324] fix(server): worktree thread lookups match any spelling of the path (#36802) Co-authored-by: Alex Southwell <4596216+saphid@users.noreply.github.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- .../orchestration-v2/ProjectionStore.test.ts | 41 ++++++++++++++----- .../src/orchestration-v2/ProjectionStore.ts | 22 ++++++++-- apps/server/src/persistence/Migrations.ts | 2 + .../Migrations/106_WorktreePathKeyIndex.ts | 16 ++++++++ .../reconcileV2PreviewMigration.test.ts | 2 + 5 files changed, 70 insertions(+), 13 deletions(-) create mode 100644 apps/server/src/persistence/Migrations/106_WorktreePathKeyIndex.ts diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index b6539e46344f1..1667a176a54a0 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -3197,6 +3197,14 @@ it.effect("SQL shells read a subagent family and a worktree's threads", () => yield* createThread({ name: "archived-child", parent: "root", root: "root", archived: true }); yield* createThread({ name: "other", worktreePath: "/repo" }); yield* createThread({ name: "other-child", parent: "other", root: "other", worktreePath }); + yield* createThread({ + name: "aliased-child", + parent: "other", + root: "other", + worktreePath: `${worktreePath}/`, + }); + yield* createThread({ name: "cased", worktreePath: worktreePath.toUpperCase() }); + yield* createThread({ name: "windows", worktreePath: "C:\\Répo\\WT" }); const family = (threadId: ThreadId) => store @@ -3208,26 +3216,39 @@ it.effect("SQL shells read a subagent family and a worktree's threads", () => assert.sameMembers([...(yield* family(id("grandchild")))], tree); assert.deepEqual([...(yield* family(id("missing")))], []); - // Includes another root's idle child on the same path, which a shell may leave out. + // Includes another root's idle child on the same path, which a shell may leave out, under any + // spelling of that path. POSIX paths keep their case. const { statements, tracer } = traceSqlStatements(); const onWorktree = yield* store .getShellSnapshot({ location: "active", worktreePath }) .pipe(Effect.withTracer(tracer)); assert.sameMembers( onWorktree.threads.map((thread) => thread.id), - [id("root"), id("child"), id("other-child")], + [id("root"), id("child"), id("other-child"), id("aliased-child")], + ); + const onWindowsWorktree = yield* store + .getShellSnapshot({ location: "active", worktreePath: "c:/Répo/wt/" }) + .pipe(Effect.withTracer(tracer)); + assert.deepEqual( + onWindowsWorktree.threads.map((thread) => thread.id), + [id("windows")], ); - // A path names a few threads; scanning every thread parses every payload. + // A path, ASCII or not, names a few threads; scanning every thread parses every payload. const sql = yield* SqlClient.SqlClient; - const threadQuery = statements.find((statement) => + const threadQueries = statements.filter((statement) => statement.includes("AS latest_run_stop_requested"), ); - assert.isDefined(threadQuery); - const threadPlan = (yield* sql.unsafe<{ readonly detail: string }>( - `EXPLAIN QUERY PLAN ${threadQuery}`, - [], - )).map((row) => row.detail); - assert.notInclude(threadPlan, "SCAN t", threadPlan.join("\n")); + assert.lengthOf(threadQueries, 2); + for (const threadQuery of threadQueries) { + const threadPlan = (yield* sql.unsafe<{ readonly detail: string }>( + `EXPLAIN QUERY PLAN ${threadQuery}`, + [], + )).map((row) => row.detail); + assert.isFalse( + threadPlan.some((detail) => detail.startsWith("SCAN t ")), + threadPlan.join("\n"), + ); + } // A fork keeps its deleted source's root, so the deleted root still names the live tree. yield* store.apply({ id: EventId.make("event:family:root-deleted"), diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index a42679d304765..36cab7ab167c7 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -102,6 +102,7 @@ import * as SqlClient from "effect/sql/SqlClient"; import type * as Statement from "effect/sql/Statement"; import { MCP_APP_OUTPUT_KEY } from "@t3tools/shared/mcpApp"; +import { normalizeProjectPathForComparison } from "@t3tools/shared/path"; import { threadHtmlRenderAttachmentIds } from "../attachmentStore.ts"; import { DELEGATED_TASK_MESSAGE_CONDITION } from "./delegatedTaskMessage.ts"; import { @@ -1258,6 +1259,7 @@ type ShellThreadRow = { readonly thread_id: string; readonly payload_json: string; readonly forked_from_run_source_thread_id: string | null; + readonly worktree_path: string | null; readonly latest_run_id: string | null; readonly latest_run_status: string | null; readonly latest_run_requested_at: string | null; @@ -8397,6 +8399,7 @@ export const layer: Layer.Layer = THEN json_extract(t.payload_json, '$.forkedFrom.threadId') ELSE NULL END AS forked_from_run_source_thread_id, + json_extract(t.payload_json, '$.worktreePath') AS worktree_path, presented.run_id AS latest_run_id, presented.status AS latest_run_status, presented.requested_at AS latest_run_requested_at, @@ -8593,8 +8596,12 @@ export const layer: Layer.Layer = }${ worktreePath === undefined ? sql`` - : sql` AND CASE WHEN json_valid(t.payload_json) - THEN json_extract(t.payload_json, '$.worktreePath') END = ${worktreePath}` + : // Matches orchestration_v2_projection_threads_worktree_path_key_idx, so this never + // scans. SQLite lower() folds only ASCII: Windows paths differing only in the case + // of another letter are not found. readShellSnapshotRows keeps the exact comparison. + sql` AND CASE WHEN json_valid(t.payload_json) + THEN lower(rtrim(replace(trim(json_extract(t.payload_json, '$.worktreePath')), '\\', '/'), '/')) + END = lower(rtrim(replace(trim(${worktreePath}), '\\', '/'), '/'))` }${threadIds === undefined ? sql`` : sql` AND t.thread_id IN (SELECT value FROM json_each(${encodeIdList(threadIds)}))`} ORDER BY t.updated_at ASC, t.thread_id ASC `; @@ -9213,7 +9220,16 @@ export const layer: Layer.Layer = const readShellSnapshotRows = Effect.fn("ProjectionStore.readShellSnapshotRows")(function* ( options: ShellSnapshotOptions | undefined, ) { - const targetThreadRows = yield* selectShellThreadRows(undefined, options); + const worktreeKey = + options?.worktreePath === undefined + ? undefined + : normalizeProjectPathForComparison(options.worktreePath); + const targetThreadRows = (yield* selectShellThreadRows(undefined, options)).filter( + (row) => + worktreeKey === undefined || + (row.worktree_path !== null && + normalizeProjectPathForComparison(row.worktree_path) === worktreeKey), + ); const targetThreadIds = new Set(targetThreadRows.map((row) => ThreadId.make(row.thread_id))); const rowsByThreadId = new Map( targetThreadRows.map((row) => [ThreadId.make(row.thread_id), row] as const), diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index 91b521fdb6036..1b4dd6cc66ccd 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -113,6 +113,7 @@ import Migration0102 from "./Migrations/102_ThreadItemCounts.ts"; import Migration0103 from "./Migrations/103_IssueTrackerAdditionalScopes.ts"; import Migration0104 from "./Migrations/104_ProjectionProjectsTrackedFolders.ts"; import Migration0105 from "./Migrations/105_TaskFolders.ts"; +import Migration0106 from "./Migrations/106_WorktreePathKeyIndex.ts"; const migrationEntries = [ [1, "OrchestrationEvents", Migration0001], @@ -221,6 +222,7 @@ const migrationEntries = [ [103, "IssueTrackerAdditionalScopes", Migration0103], [104, "ProjectionProjectsTrackedFolders", Migration0104], [105, "TaskFolders", Migration0105], + [106, "WorktreePathKeyIndex", Migration0106], ] as const; export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); diff --git a/apps/server/src/persistence/Migrations/106_WorktreePathKeyIndex.ts b/apps/server/src/persistence/Migrations/106_WorktreePathKeyIndex.ts new file mode 100644 index 0000000000000..9b1b42647d60a --- /dev/null +++ b/apps/server/src/persistence/Migrations/106_WorktreePathKeyIndex.ts @@ -0,0 +1,16 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + // Keep this expression identical to ProjectionStore's loose worktree filter. + yield* sql` + CREATE INDEX IF NOT EXISTS orchestration_v2_projection_threads_worktree_path_key_idx + ON orchestration_v2_projection_threads( + CASE WHEN json_valid(payload_json) + THEN lower(rtrim(replace(trim(json_extract(payload_json, '$.worktreePath')), '\\', '/'), '/')) + END + ) + `; +}); diff --git a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts index d2b0dafab8731..42fbb26edaa82 100644 --- a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts +++ b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts @@ -85,6 +85,7 @@ describe("V2 preview upgrade", () => { [103, "IssueTrackerAdditionalScopes"], [104, "ProjectionProjectsTrackedFolders"], [105, "TaskFolders"], + [106, "WorktreePathKeyIndex"], ]); assert.deepStrictEqual(yield* runMigrations(), []); assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports); @@ -213,6 +214,7 @@ describe("V2 preview upgrade", () => { [103, "IssueTrackerAdditionalScopes"], [104, "ProjectionProjectsTrackedFolders"], [105, "TaskFolders"], + [106, "WorktreePathKeyIndex"], ]); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); From c585a58598d594255e6e550702cc982925aa6e3f Mon Sep 17 00:00:00 2001 From: xiemin Date: Sun, 22 Nov 2026 19:28:33 +0800 Subject: [PATCH 138/324] fix(mobile): prevent clipped percentages in usage limit cards (#40778) Co-authored-by: Julius Marminge --- apps/mobile/src/features/usage/UsageLimitsPooled.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/mobile/src/features/usage/UsageLimitsPooled.tsx b/apps/mobile/src/features/usage/UsageLimitsPooled.tsx index 4c290d68ac338..50a987787b4e4 100644 --- a/apps/mobile/src/features/usage/UsageLimitsPooled.tsx +++ b/apps/mobile/src/features/usage/UsageLimitsPooled.tsx @@ -211,7 +211,7 @@ function PoolWindowCard({ {label ?? pool.label} ) : null} - + {pool.remainingPercent}% From 989247488db978c1bf5fb519726a0677568e3c7f Mon Sep 17 00:00:00 2001 From: Rodrigo Brechard Date: Sun, 22 Nov 2026 12:33:02 +0100 Subject: [PATCH 139/324] test(web): browser tests no longer fail when a stale optimizer cache reloads them mid-run (#31999) Co-authored-by: Rodrigo Brechard Co-authored-by: Julius Marminge --- apps/web/vite.config.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index 005e828202bda..e107c9a7e7491 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -111,6 +111,9 @@ const browserTestProject = { include: [ "vite-plus/test/browser", "@base-ui/react/autocomplete", + "@effect/vitest", + "@pierre/diffs/ssr", + "effect/testing", "saxes", "@betteroffice/docx/editor", "@betteroffice/docx/layout", From 62a7108904c37f225c09864f6f857f7b7474dbc1 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 03:33:14 -0800 Subject: [PATCH 140/324] fix(github): superseded runs' cancelled checks no longer block PR watches (#30434) --- .../src/server/GitHubPullRequestApi.test.ts | 16 +- .../src/server/gitHubPullRequestJson.test.ts | 145 +++++++++++++++++- .../src/server/gitHubPullRequestJson.ts | 43 +++++- .../src/server/pullRequestReads.graphql | 3 + .../src/server/pullRequestReads.graphql.ts | 10 +- 5 files changed, 209 insertions(+), 8 deletions(-) diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts index c3cc15097dfd5..9d155cab2b794 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts @@ -3949,13 +3949,25 @@ layer("GitHubPullRequestApi.layer", (it) => { name: "build", status: "COMPLETED", conclusion: "SUCCESS", - checkSuite: { workflowRun: { workflow: { name: "linux" } } }, + checkSuite: { + workflowRun: { + event: "push", + runNumber: 1, + workflow: { id: "W_linux", name: "linux" }, + }, + }, }), checkRun({ name: "build", status: "COMPLETED", conclusion: "FAILURE", - checkSuite: { workflowRun: { workflow: { name: "windows" } } }, + checkSuite: { + workflowRun: { + event: "push", + runNumber: 1, + workflow: { id: "W_windows", name: "windows" }, + }, + }, }), ], pageInfo: { hasNextPage: false, endCursor: null }, diff --git a/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts b/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts index 37db822d34386..e049943a3978f 100644 --- a/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts +++ b/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts @@ -359,10 +359,18 @@ describe("pull request detail decoding", () => { checkSuite: { workflowRun: null }, ...fields, }; - const inWorkflow = ({ workflowName, ...fields }: Record) => + const inWorkflow = ({ + workflowName, + workflowId = `W_kwDORLtfbc4${String(workflowName)}`, + event = "pull_request", + runNumber = 95380, + ...fields + }: Record) => check({ ...fields, - checkSuite: { workflowRun: { workflow: { name: workflowName } } }, + checkSuite: { + workflowRun: { event, runNumber, workflow: { id: workflowId, name: workflowName } }, + }, }); const coreJson = ( @@ -655,6 +663,139 @@ describe("pull request detail decoding", () => { } }); + it("drops a cancelled check whose workflow run was superseded by a newer run on the head", () => { + const superseded = { + workflowName: "CI", + workflowId: "W_kwDORLtfbc4N00ni", + runNumber: 95379, + status: "COMPLETED", + startedAt: "2026-10-30T10:00:00Z", + completedAt: "2026-10-30T10:00:05Z", + }; + const replacement = { + workflowName: "CI", + workflowId: "W_kwDORLtfbc4N00ni", + runNumber: 95380, + status: "COMPLETED", + conclusion: "SUCCESS", + startedAt: "2026-10-30T10:00:10Z", + completedAt: "2026-10-30T10:05:00Z", + }; + const rollup = [ + inWorkflow({ ...superseded, name: "check", conclusion: "CANCELLED" }), + inWorkflow({ + ...superseded, + name: "web browser tests (runner ${{ matrix.slice }} of 6)", + conclusion: "CANCELLED", + }), + inWorkflow({ ...replacement, name: "check" }), + inWorkflow({ ...replacement, name: "web browser tests (runner 1 of 6)" }), + inWorkflow({ ...replacement, name: "web browser tests (runner 2 of 6)" }), + ]; + const detail = detailOf(rollup); + + expect([detail.checks.map((check) => [check.name, check.status]), detail.checksState]).toEqual([ + [ + ["check", "success"], + ["web browser tests (runner 1 of 6)", "success"], + ["web browser tests (runner 2 of 6)", "success"], + ], + "passing", + ]); + }); + + it("keeps a cancelled check when the newer run is another workflow with the same name", () => { + const detail = detailOf([ + inWorkflow({ + name: "test", + workflowName: "CI", + workflowId: "W_kwDORLtfbc4N00ni", + runNumber: 95379, + conclusion: "CANCELLED", + }), + inWorkflow({ + name: "lint", + workflowName: "CI", + workflowId: "W_kwDORLtfbc4ToKTh", + runNumber: 95380, + conclusion: "SUCCESS", + }), + ]); + + expect(detail.checks.map((check) => [check.name, check.status])).toContainEqual([ + "test", + "cancelled", + ]); + expect(detail.checksState).toBe("failing"); + }); + + it("drops a required cancelled check once a newer run reports it, whenever it finished", () => { + const detail = detailOf([ + inWorkflow({ + name: "test", + workflowName: "CI", + runNumber: 41, + conclusion: "CANCELLED", + isRequired: true, + startedAt: "2026-10-30T10:00:00Z", + completedAt: "2026-10-30T10:09:00Z", + }), + inWorkflow({ + name: "test", + workflowName: "CI", + runNumber: 42, + conclusion: "SUCCESS", + isRequired: true, + startedAt: "2026-10-30T10:01:00Z", + completedAt: "2026-10-30T10:05:00Z", + }), + ]); + + expect(detail.checks.map((check) => [check.name, check.status])).toEqual([["test", "success"]]); + expect(detail.checksState).toBe("passing"); + }); + + it.each([ + ["a push", "push", "push", "CANCELLED", false, "cancelled"], + ["another event", "pull_request", "pull_request_target", "CANCELLED", false, "cancelled"], + ["a pull request run", "pull_request", "pull_request", "FAILURE", false, "failure"], + [ + "a pull request run, if required", + "pull_request", + "pull_request", + "CANCELLED", + true, + "cancelled", + ], + ])( + "keeps an older run's check when the newer run is %s", + (_label, olderEvent, newerEvent, conclusion, isRequired, status) => { + const detail = detailOf([ + inWorkflow({ + name: "test (packages/shared)", + workflowName: "CI", + event: olderEvent, + runNumber: 41, + conclusion, + isRequired, + }), + inWorkflow({ + name: "test (apps/server)", + workflowName: "CI", + event: newerEvent, + runNumber: 42, + conclusion: "SUCCESS", + }), + ]); + + expect(detail.checks.map((check) => [check.name, check.status])).toContainEqual([ + "test (packages/shared)", + status, + ]); + expect(detail.checksState).toBe("failing"); + }, + ); + it("merges reviews with comments in time order and keeps a bodyless approval", () => { const detail = expectSuccess(activity(JSON.parse(detailJson) as Record)); expect(detail.comments.map((comment) => comment.id)).toEqual(["r1", "c1", "r2"]); diff --git a/packages/source-control-github/src/server/gitHubPullRequestJson.ts b/packages/source-control-github/src/server/gitHubPullRequestJson.ts index 7fbe86839d495..9eed567a6a4da 100644 --- a/packages/source-control-github/src/server/gitHubPullRequestJson.ts +++ b/packages/source-control-github/src/server/gitHubPullRequestJson.ts @@ -131,6 +131,13 @@ interface LatestReviewFields { readonly isMinimized?: boolean | undefined; } +/** Run numbers count up per workflow file, whatever its name; database ids exceed int32. */ +interface WorkflowRunFields { + readonly event: string; + readonly runNumber: number; + readonly workflow: { readonly id: string }; +} + /** Check runs use status/conclusion; commit statuses use a single state. */ interface CheckFields { readonly name?: string | null | undefined; @@ -143,6 +150,8 @@ interface CheckFields { readonly targetUrl?: string | null | undefined; /** Empty for app-owned runs; absent for commit statuses. */ readonly workflowName?: string | null | undefined; + /** Absent for commit statuses and app-owned runs. */ + readonly workflowRun?: WorkflowRunFields | null | undefined; readonly startedAt?: string | null | undefined; readonly completedAt?: string | null | undefined; /** Branch protection requires this check; asked for on github.com only. */ @@ -617,16 +626,42 @@ function isNamelessCheck(raw: CheckFields): boolean { return trimmed(raw.name) === null && trimmed(raw.context) === null; } -/** Unfinished runs outrank finished runs of the same check across push/PR workflows. */ +const PULL_REQUEST_EVENTS = new Set(["pull_request", "pull_request_target"]); + +/** + * Unfinished runs outrank finished runs of the same check across push/PR workflows. A newer pull + * request run of a workflow supersedes the older one's cancelled checks, whose names can differ + * (an unexpanded matrix). Other events can run one commit in different scopes (a branch and a + * tag, dispatch inputs), so their runs replace nothing. + */ function toCheckEntries(raw: ReadonlyArray | null | undefined): ReadonlyArray<{ readonly check: PullRequestCheck; readonly workflowName: string | null; readonly at: string | null; }> { + const lineageOf = (run: WorkflowRunFields) => `${run.workflow.id} ${run.event}`; + const newestRunNumber = new Map(); + const note = (key: string, runNumber: number) => { + if (runNumber > (newestRunNumber.get(key) ?? Number.NEGATIVE_INFINITY)) { + newestRunNumber.set(key, runNumber); + } + }; + for (const check of raw ?? []) { + const run = check.workflowRun; + if (run == null || !PULL_REQUEST_EVENTS.has(run.event)) continue; + note(lineageOf(run), run.runNumber); + note(`${lineageOf(run)} ${trimmed(check.name) ?? ""}`, run.runNumber); + } return (raw ?? []).flatMap((check) => { const name = trimmed(check.name) ?? trimmed(check.context); if (name === null) return []; const status = toCheckStatus(check); + const run = check.workflowRun; + if (status === "cancelled" && run != null) { + // Branch protection names required checks, so only a newer same-name check replaces one. + const replacedBy = check.isRequired === true ? `${lineageOf(run)} ${name}` : lineageOf(run); + if (run.runNumber < (newestRunNumber.get(replacedBy) ?? run.runNumber)) return []; + } return [ { check: { @@ -1246,7 +1281,11 @@ export type GitHubCheckContext = CheckFields; function toCheckContexts(nodes: ReadonlyArray): ReadonlyArray { return nodes.map((check) => check.__typename === "CheckRun" - ? { ...check, workflowName: check.checkSuite.workflowRun?.workflow.name ?? null } + ? { + ...check, + workflowName: check.checkSuite.workflowRun?.workflow.name ?? null, + workflowRun: check.checkSuite.workflowRun, + } : check, ); } diff --git a/packages/source-control-github/src/server/pullRequestReads.graphql b/packages/source-control-github/src/server/pullRequestReads.graphql index 2799b67525a27..0b8c5350c1408 100644 --- a/packages/source-control-github/src/server/pullRequestReads.graphql +++ b/packages/source-control-github/src/server/pullRequestReads.graphql @@ -42,7 +42,10 @@ fragment CheckContext on StatusCheckRollupContext { isRequired(pullRequestNumber: $number) @include(if: $required) checkSuite { workflowRun { + event + runNumber workflow { + id name } } diff --git a/packages/source-control-github/src/server/pullRequestReads.graphql.ts b/packages/source-control-github/src/server/pullRequestReads.graphql.ts index ab5e211a4dec2..d26912d6aee7b 100644 --- a/packages/source-control-github/src/server/pullRequestReads.graphql.ts +++ b/packages/source-control-github/src/server/pullRequestReads.graphql.ts @@ -23,6 +23,8 @@ export interface StatusContext extends Schema.Struct.Type {} /** A workflow run. */ export const WorkflowRun = Schema.Struct({ + /** The event that triggered the workflow run */ + event: Schema.String, + /** A number that uniquely identifies this workflow run in its parent workflow. */ + runNumber: Shared.Int, /** The workflow executed in this workflow run. */ workflow: Workflow }) @@ -565,7 +571,7 @@ export const PullRequestCore = GraphQL.query("PullRequestCore", { { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){mergeCommitAllowed squashMergeAllowed rebaseMergeAllowed autoMergeAllowed viewerPermission pullRequest(number:$", "number", "){number title url body state isDraft mergeable mergeStateStatus reviewDecision additions deletions changedFiles createdAt updatedAt mergedAt mergeCommit{oid}mergedBy{__typename login avatarUrl...on User{name}}closedAt headRefName baseRefName headRefOid isCrossRepository maintainerCanModify headRepositoryOwner{__typename login}headRepository{nameWithOwner viewerPermission}headRef{id}author{__typename login avatarUrl...on User{id name}}autoMergeRequest{mergeMethod}mergeQueueRemovals:timelineItems(last:1 itemTypes:[REMOVED_FROM_MERGE_QUEUE_EVENT])@include(if:$", "mergeQueue", "){nodes{__typename...on RemovedFromMergeQueueEvent{id createdAt reason}}}viewerCanUpdate viewerDidAuthor viewerCanUpdateBranch baseRef{compare(headRef:$", "headRef", "){behindBy}}reviewRequests(first:$", "requestedReviewers", "){nodes{requestedReviewer{__typename...on User{login name}...on Bot{login}...on Team{slug combinedSlug teamName:name teamAvatarUrl:avatarUrl}}}}labels(first:100){nodes{name color description}}commits(last:1){nodes{commit{statusCheckRollup{contexts(first:100){nodes{__typename...", "CheckContext", "}pageInfo{hasNextPage endCursor}}}}}}}}"] } ], fragments: [ - { name: "CheckContext", body: ["on StatusCheckRollupContext{__typename...on StatusContext{context state targetUrl createdAt description isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")}...on CheckRun{name status conclusion startedAt completedAt detailsUrl isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")checkSuite{workflowRun{workflow{name}}}}}"] } + { name: "CheckContext", body: ["on StatusCheckRollupContext{__typename...on StatusContext{context state targetUrl createdAt description isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")}...on CheckRun{name status conclusion startedAt completedAt detailsUrl isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")checkSuite{workflowRun{event runNumber workflow{id name}}}}}"] } ] }, variables: { @@ -617,7 +623,7 @@ export const PullRequestCheckContexts = GraphQL.query("PullRequestCheckContexts" { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){pullRequest(number:$", "number", "){headRefOid commits(last:1){nodes{commit{statusCheckRollup{contexts(first:100 after:$", "after", "){nodes{__typename...", "CheckContext", "}pageInfo{hasNextPage endCursor}}}}}}}}"] } ], fragments: [ - { name: "CheckContext", body: ["on StatusCheckRollupContext{__typename...on StatusContext{context state targetUrl createdAt description isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")}...on CheckRun{name status conclusion startedAt completedAt detailsUrl isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")checkSuite{workflowRun{workflow{name}}}}}"] } + { name: "CheckContext", body: ["on StatusCheckRollupContext{__typename...on StatusContext{context state targetUrl createdAt description isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")}...on CheckRun{name status conclusion startedAt completedAt detailsUrl isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")checkSuite{workflowRun{event runNumber workflow{id name}}}}}"] } ] }, variables: { From a8363dad7fa72f7f313dbcae5f7576a6383381c5 Mon Sep 17 00:00:00 2001 From: AymanKhan9 Date: Sun, 22 Nov 2026 17:12:14 +0530 Subject: [PATCH 141/324] fix(web): keybindings using '+' show a plus keycap instead of empty pills (#40808) Co-authored-by: Julius Marminge --- .../KeybindingsSettings.logic.test.ts | 10 ++++++ .../settings/KeybindingsSettings.logic.ts | 8 +++-- .../settings/KeybindingsSettings.tsx | 33 ++++++++++--------- 3 files changed, 33 insertions(+), 18 deletions(-) diff --git a/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts b/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts index 4468d0ee66a14..64984a238c251 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts +++ b/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts @@ -14,6 +14,7 @@ import { keybindingFromKeyboardEvent, parseWhenExpressionDraft, shortcutToKeybindingInput, + shortcutToKeybindingParts, unknownWhenVariables, whenAstToExpression, } from "./KeybindingsSettings.logic"; @@ -250,6 +251,15 @@ describe("KeybindingsSettings.logic", () => { ).toBe("mod+m"); }); + it("keeps a literal plus key as its own part", () => { + expect(shortcutToKeybindingParts(parseKeybindingShortcut("mod++")!)).toEqual(["mod", "+"]); + expect(shortcutToKeybindingParts(parseKeybindingShortcut("mod+shift++")!)).toEqual([ + "mod", + "shift", + "+", + ]); + }); + it("serializes shortcuts and when expressions for upserts", () => { expect( shortcutToKeybindingInput({ diff --git a/apps/web/src/components/settings/KeybindingsSettings.logic.ts b/apps/web/src/components/settings/KeybindingsSettings.logic.ts index 99ff61182d626..55d4278b0fe16 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.logic.ts +++ b/apps/web/src/components/settings/KeybindingsSettings.logic.ts @@ -88,7 +88,7 @@ export const DEFAULT_WHEN_VARIABLE = ) ?? "terminalFocus"; const KNOWN_WHEN_VARIABLES = new Set(DEFAULT_WHEN_VARIABLES); -export function shortcutToKeybindingInput(shortcut: KeybindingShortcut): string { +export function shortcutToKeybindingParts(shortcut: KeybindingShortcut): ReadonlyArray { const parts: string[] = []; if (shortcut.modKey) parts.push("mod"); if (shortcut.metaKey) parts.push("meta"); @@ -96,7 +96,11 @@ export function shortcutToKeybindingInput(shortcut: KeybindingShortcut): string if (shortcut.altKey) parts.push("alt"); if (shortcut.shiftKey) parts.push("shift"); parts.push(shortcut.key === " " ? "space" : shortcut.key === "escape" ? "esc" : shortcut.key); - return parts.join("+"); + return parts; +} + +export function shortcutToKeybindingInput(shortcut: KeybindingShortcut): string { + return shortcutToKeybindingParts(shortcut).join("+"); } export function whenAstToExpression(node: KeybindingWhenNode | undefined): string { diff --git a/apps/web/src/components/settings/KeybindingsSettings.tsx b/apps/web/src/components/settings/KeybindingsSettings.tsx index 6e78c7c1935a6..0b6cc7ed41f81 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.tsx +++ b/apps/web/src/components/settings/KeybindingsSettings.tsx @@ -28,6 +28,7 @@ import { AuthOrchestrationOperateScope, AuthSettingsWriteScope, type KeybindingCommand, + type KeybindingShortcut, type KeybindingWhenNode, type ServerRemoveKeybindingInput, type ServerUpsertKeybindingInput, @@ -86,6 +87,7 @@ import { keybindingFromKeyboardEvent, parseWhenExpressionDraft, groupKeybindingRows, + shortcutToKeybindingParts, type KeybindingCommandOption, type KeybindingGroup, type KeybindingRow, @@ -100,35 +102,34 @@ import { keybindingSearchAnchorId, useSearchableSetting } from "./settingsSearch import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { useAtomCommand } from "../../state/use-atom-command"; -function KeybindingPill({ value }: { value: string }) { - // Keys dedupe repeated parts; a literal "+" in a shortcut splits into empty strings. - const seenParts = new Map(); - const parts = value.split("+").map((part) => { - const seen = seenParts.get(part) ?? 0; - seenParts.set(part, seen + 1); - return { part, key: seen === 0 ? part : `${part}-${seen}` }; - }); +function KeybindingPill({ shortcut }: { shortcut: KeybindingShortcut }) { + const isMac = navigator.platform.toLowerCase().includes("mac"); + const parts = shortcutToKeybindingParts(shortcut); + const modifierParts = parts.slice(0, -1); + const keyPart = parts.at(-1); + return ( - {parts.map(({ part, key }) => ( - + {modifierParts.map((part) => ( + {part === "mod" - ? navigator.platform.toLowerCase().includes("mac") + ? isMac ? "⌘" : "Ctrl" : part === "shift" ? "⇧" : part === "alt" - ? navigator.platform.toLowerCase().includes("mac") + ? isMac ? "⌥" : "Alt" : part === "ctrl" ? "⌃" - : part.length === 1 - ? part.toUpperCase() - : part} + : part} ))} + {keyPart !== undefined ? ( + {keyPart.length === 1 ? keyPart.toUpperCase() : keyPart} + ) : null} ); } @@ -915,7 +916,7 @@ function KeybindingKeyControl({ Unassigned ) : ( - + )} ) : ( From d27d29fe2d31fa260a7653f54401917940e1b578 Mon Sep 17 00:00:00 2001 From: Justin Jacob <159104807+justsrc@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:20:38 +0530 Subject: [PATCH 142/324] fix(web): lineage show-more no longer clips the last row or drops focus (#31295) Co-authored-by: Justin <159104807+Justin24506@users.noreply.github.com> Co-authored-by: Julius Marminge --- ...hreadRelationshipsControl.browser.test.tsx | 42 +++++++++++++++++++ .../chat/ThreadRelationshipsControl.tsx | 13 +++++- 2 files changed, 53 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx index 052a5742b7aab..666ce784b3afc 100644 --- a/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx @@ -236,6 +236,48 @@ it("opens an idle child beside the thread, and in its place with the modifier", expect(panel().surfaces).toHaveLength(1); }); +it("keeps focus on the list when Show more pages reveal the last rows", async () => { + setup(); + const projection = makeThreadProjectionFixture(); + const environmentId = EnvironmentId.make("local"); + const { updatedAt } = projection.thread; + state.projection = { + ...projection, + subagents: Array.from({ length: 7 }, (_, index) => ({ + id: NodeId.make(`agent-${index}`), + threadId: projection.thread.id, + runId: null, + parentNodeId: NodeId.make("parent"), + origin: "app_owned", + createdBy: "agent", + driver: "codex", + providerInstanceId: projection.thread.providerInstanceId, + providerThreadId: null, + childThreadId: ThreadId.make(`omitted-child-${index}`), + nativeTaskRef: null, + prompt: `Inspect the change part ${index}`, + title: `Agent ${index}`, + model: null, + status: "completed", + result: null, + startedAt: null, + completedAt: updatedAt, + updatedAt, + })), + }; + await using screen = await render( + , + ); + await screen.getByRole("button", { name: /Previous agents/ }).click(); + await screen.getByRole("button", { name: "Show 1 more" }).click(); + await expect.element(screen.getByRole("list", { name: "Related threads" })).toHaveFocus(); +}); + it("shows a lineage thread's full title in its tooltip", async () => { setup(); const longTitle = "Compare the lineage tooltip against a title that the row truncates"; diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx index 9675a21620d32..b005fa877b745 100644 --- a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx +++ b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx @@ -121,19 +121,28 @@ function ThreadLineageRowList(props: { readonly children: ReactNode; }) { const gt = useGT(); + const listRef = useRef(null); + const showMore = () => { + const exhausting = props.hiddenCount <= THREAD_LINEAGE_PAGE_COUNT; + props.onShowMore(); + // The button unmounts on the final page; focus the list so focus isn't dropped. + if (exhausting) listRef.current?.focus({ preventScroll: true }); + }; return ( <> {/* ScrollArea's max-height viewport measures badly inside this scrolling panel. */}
      {props.children}
    {props.hiddenCount > 0 ? ( + } + />, + ); + const editor = editorIn(screen.container); + await userEvent.click(editor.view.dom, { position: { x: 12, y: 12 } }); + await vi.waitFor(() => expect(editor.view.hasFocus()).toBe(true)); + await userEvent.click(screen.getByRole("button", { name: "Tab" })); + expect(onClick).toHaveBeenCalledOnce(); +}); diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index c3fb7fad73ff8..402156b001286 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -1975,7 +1975,7 @@ function ComposerPromptEditorTiptapInner( {isEmpty && contextRecords.size === 0 && placeholder ? (
    From 1e78f37618f087f8606a0bc5a4e49f546c9e2781 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 05:06:56 -0800 Subject: [PATCH 165/324] fix(web): keep script-only drafts reachable in the sidebar (#25272) --- apps/web/src/components/Sidebar.tsx | 20 +++++- .../SidebarDraftBlock.browser.test.tsx | 53 +++++++++++++++- .../components/sidebar/SidebarDraftBlock.tsx | 62 ++++++++++++++++--- apps/web/src/lib/discardComposerDraft.test.ts | 17 +++++ apps/web/src/lib/discardComposerDraft.ts | 32 +++++----- apps/web/src/state/terminalSessions.ts | 48 +++++++++++++- 6 files changed, 202 insertions(+), 30 deletions(-) diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 0c14aea9056b1..f8527d0d75a1f 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -271,7 +271,12 @@ import { type SidebarProviderEntry, type SidebarSweepAction, } from "./sidebar/SidebarThreadRow"; -import { SidebarDraftBlock, useSidebarDrafts } from "./sidebar/SidebarDraftBlock"; +import { + draftTerminalLabel, + SidebarDraftBlock, + useDraftTerminalLabels, + useSidebarDrafts, +} from "./sidebar/SidebarDraftBlock"; import { SidebarProjectFolderHeader, sidebarFolderRowId, @@ -1199,13 +1204,17 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve : { projectIds: scopedProjectRefs.map((projectRef) => projectRef.projectId) }, ); const routeDraftIdForRows = routeTarget?.kind === "draft" ? routeTarget.draftId : null; + const draftTerminalLabels = useDraftTerminalLabels(); const visibleDraftSessionCount = useComposerDraftStore((store) => { let count = 0; for (const [draftKey, session] of Object.entries(store.draftThreadsByThreadKey)) { if (session.promotedTo != null) { continue; } - if (!composerDraftHasUserContent(store.draftsByThreadKey[draftKey])) { + if ( + draftTerminalLabel(session, draftTerminalLabels) === null && + !composerDraftHasUserContent(store.draftsByThreadKey[draftKey]) + ) { continue; } if ( @@ -1440,7 +1449,11 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const settledThreadKeysRef = useRef(settledThreadKeys); const snoozedThreadKeysRef = useRef(snoozedThreadKeys); - const { draftIds, routeDraftComposer } = useSidebarDrafts(scopedProjectKeys, routeDraftIdForRows); + const { draftIds, routeDraftComposer } = useSidebarDrafts( + scopedProjectKeys, + routeDraftIdForRows, + draftTerminalLabels, + ); // Draft rows sit above the threads, so jumps and traversal reach them first. // Search hides them, so they drop out while it is open. const listedDraftIds = isSearchingThreads ? EMPTY_DRAFT_IDS : draftIds; @@ -3576,6 +3589,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve key="draft-sessions" draftIds={draftIds} routeDraftComposer={routeDraftComposer} + terminalLabels={draftTerminalLabels} jumpLabelByDraftId={draftJumpLabelById} projectByKey={projectByKey} projectDisplayNameByKey={projectDisplayNameByKey} diff --git a/apps/web/src/components/sidebar/SidebarDraftBlock.browser.test.tsx b/apps/web/src/components/sidebar/SidebarDraftBlock.browser.test.tsx index 7b7adf7a31ea5..9e2e6a058f220 100644 --- a/apps/web/src/components/sidebar/SidebarDraftBlock.browser.test.tsx +++ b/apps/web/src/components/sidebar/SidebarDraftBlock.browser.test.tsx @@ -8,16 +8,24 @@ import { formatAssistantCitationForComposer } from "../../composer-logic"; import { DraftId, useComposerDraftStore } from "../../composerDraftStore"; import { SidebarDraftBlock, useSidebarDrafts } from "./SidebarDraftBlock"; -function DraftBlock() { - const { draftIds, routeDraftComposer } = useSidebarDrafts(null, null); +const NO_TERMINAL_LABELS: ReadonlyMap = new Map(); + +function DraftBlock(props: { + routeDraftId?: string | null; + terminalLabels?: ReadonlyMap; +}) { + const routeDraftId = props.routeDraftId ?? null; + const terminalLabels = props.terminalLabels ?? NO_TERMINAL_LABELS; + const { draftIds, routeDraftComposer } = useSidebarDrafts(null, routeDraftId, terminalLabels); return ( @@ -91,3 +99,42 @@ it("keeps draft previews current through edits, promotion and removal", async () await act(() => initial.clearDraftThread(nextDraftId)); await expect.element(row).not.toBeInTheDocument(); }); + +it("lists empty drafts by terminal label while their terminal exists, active or not", async () => { + const initial = useComposerDraftStore.getState(); + using _store = { + [Symbol.dispose]: () => useComposerDraftStore.setState(initial, true), + }; + useComposerDraftStore.setState({ + draftsByThreadKey: {}, + draftThreadsByThreadKey: {}, + logicalProjectDraftThreadKeyByLogicalProjectKey: {}, + }); + const environmentId = EnvironmentId.make("draft-terminal-environment"); + const terminalDraftId = DraftId.make("draft-with-terminal"); + initial.setProjectDraftThreadId( + scopeProjectRef(environmentId, ProjectId.make("terminal-project")), + terminalDraftId, + { threadId: ThreadId.make("terminal-thread") }, + ); + initial.setProjectDraftThreadId( + scopeProjectRef(environmentId, ProjectId.make("idle-project")), + DraftId.make("draft-without-terminal"), + { threadId: ThreadId.make("idle-thread") }, + ); + + const terminalLabels = new Map([[`${environmentId}:terminal-thread`, "dev"]]); + const block = (routeDraftId: string | null) => ( +
      + +
    + ); + await using screen = await render(block(terminalDraftId)); + const rows = screen.getByTestId("sidebar-draft-row"); + await expect.element(rows).toHaveAccessibleName("dev, Unsent draft"); + expect(rows.elements()).toHaveLength(1); + + await screen.rerender(block(null)); + await expect.element(rows).toHaveAccessibleName("dev, Unsent draft"); + expect(rows.elements()).toHaveLength(1); +}); diff --git a/apps/web/src/components/sidebar/SidebarDraftBlock.tsx b/apps/web/src/components/sidebar/SidebarDraftBlock.tsx index 3a4a74bb64f18..4cb082a1f7ddd 100644 --- a/apps/web/src/components/sidebar/SidebarDraftBlock.tsx +++ b/apps/web/src/components/sidebar/SidebarDraftBlock.tsx @@ -12,8 +12,10 @@ import { type MouseEvent as ReactMouseEvent, } from "react"; import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; +import type { EnvironmentId } from "@t3tools/contracts"; import { useShallow } from "zustand/react/shallow"; import { cn } from "~/lib/utils"; +import { useTerminalLabelsByThreadKey } from "~/state/terminalSessions"; import { resolveSidebarRowAccessibility } from "../Sidebar.logic"; import { ProjectFavicon, type ProjectFaviconProject } from "../ProjectFavicon"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; @@ -31,9 +33,41 @@ import { JumpHintBadge, } from "./SidebarThreadRow"; +const EMPTY_COMPOSER_PARTS = { + prompt: "", + images: [], + persistedAttachments: [], + files: [], + terminalContexts: [], + previewAnnotations: [], + reviewComments: [], +} as const; + +/** Terminal labels for draft threads; an unsent draft stays listed while it has a terminal. */ +export function useDraftTerminalLabels(): ReadonlyMap { + const environmentIds = useComposerDraftStore((store) => { + const ids = new Set(); + for (const session of Object.values(store.draftThreadsByThreadKey)) { + if (session.promotedTo == null) ids.add(session.environmentId); + } + return [...ids].toSorted().join("\n"); + }); + return useTerminalLabelsByThreadKey( + environmentIds === "" ? [] : (environmentIds.split("\n") as EnvironmentId[]), + ); +} + +export function draftTerminalLabel( + session: DraftSessionState, + terminalLabels: ReadonlyMap, +): string | null { + return terminalLabels.get(`${session.environmentId}:${session.threadId}`) ?? null; +} + const SidebarDraftRow = memo(function SidebarDraftRow(props: { draftId: DraftId; - composer: ComposerThreadDraftState; + composer: ComposerThreadDraftState | null; + terminalLabel: string | null; project: ProjectFaviconProject | null; projectDisplayName: string | null; isActive: boolean; @@ -46,7 +80,8 @@ const SidebarDraftRow = memo(function SidebarDraftRow(props: { source: ContextMenuSource, ) => void; }) { - const { composer, draftId, onContextMenu, onDiscard, onNavigate } = props; + const { draftId, onContextMenu, onDiscard, onNavigate } = props; + const composer = props.composer ?? EMPTY_COMPOSER_PARTS; const gt = useGT(); const promptPreview = assistantCitationsToPlainText( @@ -65,9 +100,11 @@ const SidebarDraftRow = memo(function SidebarDraftRow(props: { const preview = promptPreview.length > 0 ? promptPreview - : gt("{count, plural, one {{count} attachment} other {{count} attachments}}", { - count: attachmentCount, - }); + : attachmentCount === 0 && props.terminalLabel !== null + ? props.terminalLabel + : gt("{count, plural, one {{count} attachment} other {{count} attachments}}", { + count: attachmentCount, + }); const accessibility = resolveSidebarRowAccessibility({ title: preview, statusLabel: gt("Unsent draft"), @@ -174,6 +211,7 @@ function listedDraftComposer(draftId: string | null): ComposerThreadDraftState | export function useSidebarDrafts( scopedProjectKeys: ReadonlySet | null, routeDraftId: string | null, + terminalLabels: ReadonlyMap, ): { draftIds: readonly DraftId[]; routeDraftComposer: ComposerThreadDraftState | null } { const [frozenRoute, setFrozenRoute] = useState<{ routeDraftId: string | null; @@ -195,10 +233,12 @@ export function useSidebarDrafts( ) { continue; } + // Composer edits stay frozen while open; terminals come and go live. const isListed = - draftKey === routeDraftId + draftTerminalLabel(session, terminalLabels) !== null || + (draftKey === routeDraftId ? routeDraftComposer !== null - : composerDraftHasUserContent(store.draftsByThreadKey[draftKey]); + : composerDraftHasUserContent(store.draftsByThreadKey[draftKey])); if (isListed) listed.push([draftKey, session]); } listed.sort(([, left], [, right]) => right.createdAt.localeCompare(left.createdAt)); @@ -211,6 +251,7 @@ export function useSidebarDrafts( export const SidebarDraftBlock = memo(function SidebarDraftBlock(props: { draftIds: readonly DraftId[]; routeDraftComposer: ComposerThreadDraftState | null; + terminalLabels: ReadonlyMap; jumpLabelByDraftId: ReadonlyMap | null; projectByKey: ReadonlyMap; projectDisplayNameByKey: ReadonlyMap; @@ -233,8 +274,10 @@ export const SidebarDraftBlock = memo(function SidebarDraftBlock(props: { const drafts = props.draftIds.flatMap((draftId) => { const session = draftThreadsByThreadKey[draftId]; const composer = - draftId === props.routeDraftId ? props.routeDraftComposer : draftsByThreadKey[draftId]; - return session && composer ? [{ draftId, session, composer }] : []; + (draftId === props.routeDraftId ? props.routeDraftComposer : null) ?? + draftsByThreadKey[draftId] ?? + null; + return session ? [{ draftId, session, composer }] : []; }); if (drafts.length === 0) { return null; @@ -248,6 +291,7 @@ export const SidebarDraftBlock = memo(function SidebarDraftBlock(props: { key={draftId} draftId={draftId} composer={composer} + terminalLabel={draftTerminalLabel(session, props.terminalLabels)} project={props.projectByKey.get(projectKey) ?? null} projectDisplayName={props.projectDisplayNameByKey.get(projectKey) ?? null} isActive={draftId === props.routeDraftId} diff --git a/apps/web/src/lib/discardComposerDraft.test.ts b/apps/web/src/lib/discardComposerDraft.test.ts index 6c63482dfe52b..340ed6b2606e3 100644 --- a/apps/web/src/lib/discardComposerDraft.test.ts +++ b/apps/web/src/lib/discardComposerDraft.test.ts @@ -80,6 +80,23 @@ describe("discardComposerDraft", () => { } }); + it("discards and restores a draft session that has no composer record", async () => { + useComposerDraftStore.getState().setProjectDraftThreadId(projectRef, draftId); + const before = useComposerDraftStore.getState(); + expect(before.draftsByThreadKey).toEqual({}); + + discardComposerDraft(draftId); + expect(useComposerDraftStore.getState().getDraftSession(draftId)).toBeNull(); + + await undoNotice().undo(); + const after = useComposerDraftStore.getState(); + expect(after.getDraftSession(draftId)).toEqual(before.getDraftSession(draftId)); + expect(after.draftsByThreadKey).toEqual({}); + expect(after.logicalProjectDraftThreadKeyByLogicalProjectKey).toEqual( + before.logicalProjectDraftThreadKeyByLogicalProjectKey, + ); + }); + it("releases a discarded existing-thread preview when Undo is committed", async () => { using preview = imagePreview(); useComposerDraftStore.getState().addImage(threadRef, preview.image); diff --git a/apps/web/src/lib/discardComposerDraft.ts b/apps/web/src/lib/discardComposerDraft.ts index bd52b0a02879f..f1847a737dc0a 100644 --- a/apps/web/src/lib/discardComposerDraft.ts +++ b/apps/web/src/lib/discardComposerDraft.ts @@ -19,8 +19,9 @@ export function discardComposerDraft(target: ComposerThreadTarget): void { const store = useComposerDraftStore.getState(); const key = resolveComposerDraftKey(store, target); const draft = key === null ? undefined : store.draftsByThreadKey[key]; - if (key === null || !draft) return; + if (key === null) return; const session = store.draftThreadsByThreadKey[key]; + if (!draft && !session) return; const logicalProjectKeys = Object.entries(store.logicalProjectDraftThreadKeyByLogicalProjectKey) .filter(([, draftKey]) => draftKey === key) .map(([logicalProjectKey]) => logicalProjectKey); @@ -38,6 +39,7 @@ export function discardComposerDraft(target: ComposerThreadTarget): void { } const releaseDiscardedDraft = () => { + if (!draft) return; releaseDraftAttachments([...draft.images, ...draft.files]); // Draft-session removal already revoked these previews. if (!discardsSession) { @@ -65,19 +67,21 @@ export function discardComposerDraft(target: ComposerThreadTarget): void { logicalProjectDraftThreadKeyByLogicalProjectKey[logicalProjectKey] ??= key; } return { - draftsByThreadKey: { - ...state.draftsByThreadKey, - [key]: discardsSession - ? { - ...draft, - images: draft.images.map((image) => - image.previewUrl.startsWith("blob:") - ? { ...image, previewUrl: URL.createObjectURL(image.file) } - : image, - ), - } - : draft, - }, + draftsByThreadKey: draft + ? { + ...state.draftsByThreadKey, + [key]: discardsSession + ? { + ...draft, + images: draft.images.map((image) => + image.previewUrl.startsWith("blob:") + ? { ...image, previewUrl: URL.createObjectURL(image.file) } + : image, + ), + } + : draft, + } + : state.draftsByThreadKey, draftThreadsByThreadKey: session ? { ...state.draftThreadsByThreadKey, [key]: session } : state.draftThreadsByThreadKey, diff --git a/apps/web/src/state/terminalSessions.ts b/apps/web/src/state/terminalSessions.ts index 8eaca1b774c85..0915810b47fed 100644 --- a/apps/web/src/state/terminalSessions.ts +++ b/apps/web/src/state/terminalSessions.ts @@ -22,7 +22,13 @@ import { AsyncResult, Atom } from "effect/reactivity"; import { formatEnvironmentQueryError } from "./query"; import { terminalEnvironment } from "./terminal"; -import { environmentSession, sessionHasScope, useEnvironmentScope } from "./session"; +import { environmentAtomList, environmentIdsKey } from "./environmentAtomList"; +import { + environmentSession, + sessionHasScope, + useEnvironmentScope, + useEnvironmentsWithScope, +} from "./session"; import { msg } from "gt-react"; import { m } from "../i18n/messages"; @@ -274,3 +280,43 @@ export function useThreadRunningTerminalIds(input: { const sessions = useKnownTerminalSessions(input); return selectRunningSubprocessTerminalIds(sessions ?? []); } + +// A string so status updates that keep every label notify no one. +const terminalLabelsFamily = Atom.family((environmentId: EnvironmentId) => + Atom.make((get) => { + const metadata = get(terminalEnvironment.metadata({ environmentId, input: null })); + if (metadata._tag !== "Success") return "[]"; + return JSON.stringify( + Array.from(terminalMetadataIndex(metadata.value).byThreadId, ([threadId, summaries]) => [ + threadId, + summaries[0]!.label, + ]), + ); + }).pipe(Atom.withLabel(`web-terminal-labels:${environmentId}`)), +); +const terminalLabelsListAtom = environmentAtomList("web-terminal-labels", terminalLabelsFamily); +const terminalLabelsByResults = new WeakMap, ReadonlyMap>(); + +/** First terminal label of each thread that has one, keyed `${environmentId}:${threadId}`. */ +export function useTerminalLabelsByThreadKey( + environmentIds: ReadonlyArray, +): ReadonlyMap { + const readable = useEnvironmentsWithScope( + environmentIds.map((environmentId) => ({ environmentId })), + AuthTerminalReadScope, + ); + const readableIds = environmentIds.filter((environmentId) => readable.has(environmentId)); + const results = useAtomValue(terminalLabelsListAtom(environmentIdsKey(readableIds))); + let labels = terminalLabelsByResults.get(results); + if (!labels) { + const next = new Map(); + results.forEach((encoded, index) => { + for (const [threadId, label] of JSON.parse(encoded) as Array<[string, string]>) { + next.set(`${readableIds[index]}:${threadId}`, label); + } + }); + labels = next; + terminalLabelsByResults.set(results, labels); + } + return labels; +} From b23f1e8af9b13af2c4aa1ba8e0d6987550688645 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 05:21:55 -0800 Subject: [PATCH 166/324] fix(server): retire unresponsive shared Codex app-servers (#25123) --- .../Adapters/CodexAdapterV2.test.ts | 174 ++++++++++++++++++ .../Adapters/CodexAdapterV2.ts | 82 +++++++-- .../ProviderTurnStartService.test.ts | 34 ++++ .../ProviderTurnStartService.ts | 18 +- .../provider-core/src/server/failure.test.ts | 10 + packages/provider-core/src/server/failure.ts | 2 + 6 files changed, 299 insertions(+), 21 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index cd5e51a32f616..ef4ffcf35c11b 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -1235,6 +1235,7 @@ describe("CodexAdapterV2 session initialize", () => { runtimePolicy: CODEX_TEST_RUNTIME_POLICY, }), initializeRequests: () => initializeRequests, + runtime, events: runtime.events, }; }); @@ -1531,6 +1532,179 @@ describe("CodexAdapterV2 session initialize", () => { ), ), ); + + // The no-op notification lands right after the request is written, so the + // test advances the clock only once the app-server is known to be silent. + const requestWritten: CodexReplay.CodexAppServerReplayEntry = { + type: "emit_inbound", + label: "request-written", + frame: { method: "t3/test/requestWritten", params: {} }, + }; + const awaitRequestWritten = + (written: Deferred.Deferred) => + ( + entry: Parameters< + NonNullable + >[0], + ) => + entry.label === "request-written" ? Deferred.succeed(written, undefined) : Effect.void; + const UNANSWERED_REQUEST_BUDGET = "5 minutes"; + // ProviderTurnStartService skips retries and fresh-thread fallback on this tag. + const failedOnDeadline = (exit: Exit.Exit): boolean => { + if (!Exit.isFailure(exit)) return false; + let error: unknown = Cause.squash(exit.cause); + while (Predicate.hasProperty(error, "cause")) { + if (Predicate.isTagged(error, "CodexAppServerUnresponsiveError")) return true; + error = error.cause; + } + return Predicate.isTagged(error, "CodexAppServerUnresponsiveError"); + }; + + // regression: #24300 a wedged shared app-server left thread/start pending and stayed ready + it.effect("fails and retires a shared app-server that never answers thread/start", () => + Effect.gen(function* () { + const written = yield* Deferred.make(); + const session = yield* openReplaySession( + makeCodexReplayTranscript({ + scenario: "thread-start-unanswered", + entries: [...replayPreamble("thread-start-unanswered").slice(0, 4), requestWritten], + }), + awaitRequestWritten(written), + ); + const events = yield* session.runtime.events.pipe( + Stream.runDrain, + Effect.exit, + Effect.timeoutOption(UNANSWERED_REQUEST_BUDGET), + Effect.forkChild({ startImmediately: true }), + ); + const ensured = yield* session + .ensureThread("thread-start-unanswered") + .pipe( + Effect.exit, + Effect.timeoutOption(UNANSWERED_REQUEST_BUDGET), + Effect.forkChild({ startImmediately: true }), + ); + yield* Deferred.await(written); + yield* TestClock.adjust(UNANSWERED_REQUEST_BUDGET); + + const settled = yield* Fiber.join(ensured); + assert.isTrue( + Option.isSome(settled) && failedOnDeadline(settled.value), + `ensureThread did not fail on the deadline within ${UNANSWERED_REQUEST_BUDGET} of an unanswered thread/start`, + ); + const retired = yield* Fiber.join(events); + assert.isTrue( + Option.isSome(retired) && Exit.isFailure(retired.value), + "session events did not fail after thread/start passed its deadline", + ); + const refused = yield* Effect.exit(session.ensureThread("thread-start-after-retire")); + const refusal = Exit.isFailure(refused) ? Cause.squash(refused.cause) : undefined; + assert.isTrue( + Predicate.hasProperty(refusal, "cause") && + Predicate.isTagged(refusal.cause, "CodexAppServerRetiredError"), + "a retired app-server accepted a new thread", + ); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + + const turnPreamble = codexReplayPreamble({ + nativeThreadId: "turn-start-unanswered", + nativeTurnId: "turn-unanswered", + prompt: "Hello", + }); + // regression: #24300 a stopped shared app-server left a loaded thread's next turn pending forever + it.effect.each([ + { + method: "config/read", + entries: [ + ...turnPreamble.slice(0, 5), + { + type: "expect_outbound", + label: "thread/name/set", + frame: { + id: 3, + method: "thread/name/set", + params: { threadId: "turn-start-unanswered", name: CODEX_TEST_THREAD_TITLE }, + }, + } satisfies CodexReplay.CodexAppServerReplayEntry, + { + type: "emit_inbound", + label: "thread/name/set", + frame: { id: 3, result: {} }, + } satisfies CodexReplay.CodexAppServerReplayEntry, + { + type: "expect_outbound", + label: "config/read", + frame: { + id: 4, + method: "config/read", + params: { cwd: "/workspace", includeLayers: false }, + }, + } satisfies CodexReplay.CodexAppServerReplayEntry, + ], + }, + { method: "turn/start", entries: turnPreamble.slice(0, 6) }, + ])("fails a turn whose $method the shared app-server never answers", ({ entries }) => + Effect.gen(function* () { + const written = yield* Deferred.make(); + const session = yield* openReplaySession( + makeCodexReplayTranscript({ + scenario: "turn-start-unanswered", + entries: [...entries, requestWritten], + }), + awaitRequestWritten(written), + ); + const threadId = ThreadId.make("thread-turn-start-unanswered"); + const providerThread = yield* session.ensureThread(threadId); + + const outcome = yield* session.runtime + .startTurn( + makeCodexTestTurnInput({ + threadId, + providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("turn-start-unanswered-attempt"), + text: "Hello", + }), + ) + .pipe( + Effect.exit, + Effect.timeoutOption(UNANSWERED_REQUEST_BUDGET), + Effect.forkChild({ startImmediately: true }), + ); + yield* Deferred.await(written); + yield* TestClock.adjust(UNANSWERED_REQUEST_BUDGET); + const settled = yield* Fiber.join(outcome); + + assert.isTrue( + Option.isSome(settled), + `startTurn was still waiting after ${UNANSWERED_REQUEST_BUDGET}`, + ); + if (Option.isSome(settled)) { + assert.isTrue(failedOnDeadline(settled.value), "startTurn did not fail on the deadline"); + } + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); }); describe("CodexAdapterV2 post-settle continuation", () => { diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 09036b09e3f77..e5dfd83559292 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -541,6 +541,26 @@ function codexMcpToolOutput( // A hung MCP resource read must not hold run ingestion open. const MCP_APP_CAPTURE_TIMEOUT = "20 seconds"; +// Session setup and turn start requests answer promptly; silence this long means a wedged app-server. +const CODEX_APP_SERVER_REQUEST_DEADLINE = "2 minutes"; + +class CodexAppServerUnresponsiveError extends Schema.TaggedError()( + "CodexAppServerUnresponsiveError", + { method: Schema.String }, +) { + override get message() { + return `Codex app-server did not answer ${this.method} within ${CODEX_APP_SERVER_REQUEST_DEADLINE}.`; + } +} + +class CodexAppServerRetiredError extends Schema.TaggedError()( + "CodexAppServerRetiredError", + {}, +) { + override get message() { + return "Codex app-server was retired and accepts no new work."; + } +} function codexMcpAppResourceUri(item: CodexDynamicToolItem): string | undefined { if (item.type !== "mcpToolCall") return undefined; @@ -2140,6 +2160,39 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ); // A failed open is discarded, so the next turn spawns the updated binary. if (adapterOptions.compatibility !== undefined) yield* ensureInitialized; + // Failing the event stream makes the session manager release this app-server. + // Queue.fail lets readers take items already buffered before they see the failure. + // Buffered events drain before the session manager drops this runtime; refuse work meanwhile. + let retired = false; + const retireAppServer = (cause: unknown) => + Effect.suspend(() => { + retired = true; + return Queue.fail( + events, + new ProviderAdapter.ProviderAdapterEventStreamError({ + driver: CODEX_PROVIDER, + providerSessionId: input.providerSessionId, + cause, + }), + ); + }); + const rejectIfRetired = Effect.suspend(() => + retired ? Effect.fail(new CodexAppServerRetiredError()) : Effect.void, + ); + yield* client.awaitTermination.pipe(Effect.catch(retireAppServer), Effect.forkScoped); + // The outcome of an unanswered request is unknown, so it fails rather than retries. + const withAppServerDeadline = + (method: string) => + (effect: Effect.Effect) => + effect.pipe( + Effect.timeoutOrElse({ + duration: CODEX_APP_SERVER_REQUEST_DEADLINE, + orElse: () => { + const error = new CodexAppServerUnresponsiveError({ method }); + return retireAppServer(error).pipe(Effect.andThen(Effect.fail(error))); + }, + }), + ); // Read per thread: a workspace's project config can add its own servers. const readStdioMcpServers = (cwd: string | null | undefined) => ensureInitialized.pipe( @@ -2155,6 +2208,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( Effect.as>([]), ), ), + withAppServerDeadline("config/read"), ); const now = yield* DateTime.now; const session = providerSession({ @@ -2164,21 +2218,6 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( model: input.modelSelection.model, now, }); - // Drain final notifications before the session manager retires the dead process. - // Queue.fail lets readers take items already buffered before they see the failure. - yield* client.awaitTermination.pipe( - Effect.catch((cause) => - Queue.fail( - events, - new ProviderAdapter.ProviderAdapterEventStreamError({ - driver: CODEX_PROVIDER, - providerSessionId: input.providerSessionId, - cause, - }), - ), - ), - Effect.forkScoped, - ); const rateLimitSnapshot = yield* Ref.make(undefined); const limitedTurnItems = yield* Ref.make( new Map>(), @@ -7677,6 +7716,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( Effect.catch(() => Effect.logDebug("Codex config read failed.").pipe(Effect.as(undefined)), ), + withAppServerDeadline("config/read"), ); const turnStartParams = yield* buildCodexTurnStartParams({ cyberAccess: codexCyberAccess(models, turnInput.modelSelection.model), @@ -7708,7 +7748,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ...(yield* Ref.get(settledTurns)), ...(yield* Ref.get(activeTurns)), ]); - const started = yield* client.request("turn/start", turnStartParams); + const started = yield* client + .request("turn/start", turnStartParams) + .pipe(withAppServerDeadline("turn/start")); const previousTurn = previousTurns.get(started.turn.id) ?? (yield* Ref.get(activeTurns)).get(started.turn.id); @@ -7798,6 +7840,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( turnInput: ProviderAdapter.ProviderAdapterV2TurnInput, command: OrchestrationV2GoalCommand, ) { + yield* rejectIfRetired; if (command.type === "set") yield* validateCodexGoalObjective(command.objective); const threadId = yield* getNativeThreadId(turnInput.providerThread); rootProviderThreads.set(threadId, turnInput.providerThread); @@ -8075,7 +8118,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( return false; }), ensureThread: (threadInput) => - ensureInitialized.pipe( + rejectIfRetired.pipe( + Effect.andThen(ensureInitialized), Effect.andThen( Effect.all([ mcpSessions.read(threadInput.threadId), @@ -8107,6 +8151,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( thread: response.thread, }), ), + withAppServerDeadline("thread/start"), Effect.mapError( (cause) => new ProviderAdapter.ProviderAdapterEnsureThreadError({ @@ -8118,6 +8163,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ), resumeThread: Effect.fn("CodexAdapterV2.resumeThread")( function* (threadInput) { + yield* rejectIfRetired; const nativeThreadId = yield* getNativeThreadId(threadInput.providerThread); const appThreadId = threadInput.threadId ?? threadInput.providerThread.appThreadId; const resume = resumeNativeThread(nativeThreadId, { @@ -8140,6 +8186,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( goalUpdatesHeld.add(nativeThreadId); const response = yield* ensureInitialized.pipe( Effect.andThen(resume), + withAppServerDeadline("thread/resume"), Effect.flatMap(decodeCodexResumeMetadata), // Stay registered: a lost or undecodable response may still have resumed the thread. Effect.onError(() => @@ -8252,6 +8299,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( if (goalCommand !== null) return runGoalCommand(turnInput, goalCommand); const nativeThreadId = turnInput.providerThread.nativeThreadRef?.nativeId; return Effect.gen(function* () { + yield* rejectIfRetired; if ( !continuation && nativeThreadId != null && diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index 864d6f253ad41..ef9bd2bb32712 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -3163,6 +3163,40 @@ effectIt.effect("leaves the run starting when a session-open failure will be ret }), ); +effectIt.effect("fails rather than retries a provider thread request with an unknown outcome", () => + Effect.gen(function* () { + const harness = makeLocalCommandHarness({ + text: "Continue", + ensureThreadFailure: { _tag: "CodexAppServerUnresponsiveError", method: "thread/start" }, + }); + + yield* harness.startWithRetry; + + expect(harness.startRootRun).not.toHaveBeenCalled(); + expect(harness.projection().runs.at(-1)?.status).toBe("failed"); + }), +); + +effectIt.effect("fails rather than starts a fresh thread when a resume outcome is unknown", () => + Effect.gen(function* () { + const harness = makeLocalCommandHarness({ + text: "Continue", + resumeFailure: new ProviderAdapter.ProviderAdapterEventStreamError({ + driver: ProviderDriverKind.make("codex"), + providerSessionId: ProviderSessionId.make("resume-provider-session"), + cause: { _tag: "CodexAppServerUnresponsiveError", method: "thread/resume" }, + }), + }); + + const exit = yield* Effect.exit(harness.startWithRetry); + + expect(exit._tag).toBe("Success"); + expect(harness.fallbackEnsureThread).not.toHaveBeenCalled(); + expect(harness.startRootRun).not.toHaveBeenCalled(); + expect(harness.projection().runs.at(-1)?.status).toBe("failed"); + }), +); + effectIt.effect("fails the run without a retry when the provider needs sign-in", () => Effect.gen(function* () { const harness = makeLocalCommandHarness({ diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 317dff4b395b6..1cb77e387f950 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -165,6 +165,13 @@ const refusedBeforePrompt = (error: unknown): boolean => error.detail === CLAUDE_QUERY_ENDED_BEFORE_TURN_DETAIL) || (Predicate.hasProperty(error, "cause") && refusedBeforePrompt(error.cause)); +// The provider may have acted on a request it never answered, so a retry could duplicate it. +const OUTCOME_UNKNOWN_TAGS = ["CodexAppServerUnresponsiveError"] as const; + +const outcomeUnknown = (error: unknown): boolean => + OUTCOME_UNKNOWN_TAGS.some((tag) => Predicate.isTagged(error, tag)) || + (Predicate.hasProperty(error, "cause") && outcomeUnknown(error.cause)); + /** * Whether a non-truncating provider's native session lost the conversation kept before `run`. * Rollback resets it: the newest accepted turn was rolled back (works without legacy-missing @@ -998,7 +1005,9 @@ export const layer: Layer.Layer< ) { const loaded = yield* Effect.result(load); if (loaded._tag === "Success") return loaded.success; - if (input.willRetry === true) return yield* loaded.failure; + if (input.willRetry === true && !outcomeUnknown(loaded.failure)) { + return yield* loaded.failure; + } yield* settleStartFailure({ signal: "provider-thread-load-failure", title: "Provider turn failed to start", @@ -1718,11 +1727,12 @@ export const layer: Layer.Layer< resumedHandoffContext = undefined; resumedRetryHandoff = undefined; if (!(yield* isCurrentAttemptInStatus("starting"))) return undefined; - // Another client is still writing to the native thread. A fresh - // session here would silently split the conversation from it. + // Another client is still writing to the native thread, or the provider may have + // resumed it without answering. A fresh session would split the conversation. if ( resumed._tag === "Failure" && - resumed.failure._tag === "ProviderAdapterThreadInUseError" + (resumed.failure._tag === "ProviderAdapterThreadInUseError" || + outcomeUnknown(resumed.failure)) ) { return yield* loadFromProvider(Effect.fail(resumed.failure)); } diff --git a/packages/provider-core/src/server/failure.test.ts b/packages/provider-core/src/server/failure.test.ts index a29b60d4d25ae..7f4b790927488 100644 --- a/packages/provider-core/src/server/failure.test.ts +++ b/packages/provider-core/src/server/failure.test.ts @@ -132,6 +132,16 @@ it("preserves actionable T3 errors wrapped by turn startup", () => { }); assert.equal(makeProviderFailure({ cause: Cause.fail(cause) }).message, error.message); } + const unanswered = { + _tag: "CodexAppServerUnresponsiveError", + message: "Codex app-server did not answer turn/start within 2 minutes.", + }; + assert.equal( + makeProviderFailure({ + cause: Cause.fail({ _tag: "ProviderAdapterEventStreamError", cause: unanswered }), + }).message, + unanswered.message, + ); }); it("names how the provider process exited and the stage it failed in, without its output", () => { diff --git a/packages/provider-core/src/server/failure.ts b/packages/provider-core/src/server/failure.ts index cfdb0eb3df9a6..e7d47cdb2175e 100644 --- a/packages/provider-core/src/server/failure.ts +++ b/packages/provider-core/src/server/failure.ts @@ -139,6 +139,8 @@ function curatedCauseMessages(cause: unknown): { case "ClaudeConversationNotFoundError": case "CursorModelUnavailableError": case "CodexGoalObjectiveTooLongError": + case "CodexAppServerUnresponsiveError": + case "CodexAppServerRetiredError": case "ProviderSetupError": case "ProviderAdapterThreadInUseError": case "ProviderCompactionUnsupportedError": From a985332c447173750394c0875fb961f88c306730 Mon Sep 17 00:00:00 2001 From: maria Date: Sun, 22 Nov 2026 10:28:38 -0300 Subject: [PATCH 167/324] fix(shared): Windows command discovery no longer blocks the event loop (#27391) Co-authored-by: Enmani <43571965+Enmani@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../Adapters/ClaudeAdapterV2.testkit.ts | 4 +- .../provider/Drivers/ClaudeExecutable.test.ts | 2 +- .../src/provider/Drivers/ClaudeExecutable.ts | 4 +- apps/server/src/terminal/Manager.ts | 11 +-- .../src/server/AcpRegistrySupport.test.ts | 11 ++- .../src/server/AcpRegistrySupport.ts | 57 ++++++++----- .../src/server/clientTerminals.ts | 2 +- .../provider-muse/src/server/MuseUsageHome.ts | 6 +- packages/provider-muse/src/server/sdk.test.ts | 2 +- packages/provider-muse/src/server/sdk.ts | 3 +- .../provider-muse/src/server/usage.test.ts | 2 +- packages/shared/src/shell.test.ts | 85 +++++++++++++++++-- packages/shared/src/shell.ts | 77 +++++++++-------- .../src/server/AzureDevOpsCli.test.ts | 2 +- .../src/server/AzureDevOpsCli.ts | 3 +- .../src/server/discovery.ts | 3 +- 16 files changed, 190 insertions(+), 84 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts index bed26e69ae008..5d08adab93042 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts @@ -1496,7 +1496,9 @@ const resolveClaudeRecordingExecutablePath = Effect.fn("resolveClaudeRecordingEx function* (environment: NodeJS.ProcessEnv) { const resolveExecutable = yield* SpawnExecutableResolution; const platform = yield* HostProcess.Platform; - const resolved = resolveExecutable("claude", platform, environment); + const resolved = yield* Effect.promise(async () => + resolveExecutable("claude", platform, environment), + ); if (resolved === undefined) { return undefined; } diff --git a/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts b/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts index b6dc61470e497..36d7e3f3313fc 100644 --- a/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts +++ b/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts @@ -21,7 +21,7 @@ function withWindowsResolution(input: { return (effect: Effect.Effect) => effect.pipe( Effect.provideService(HostProcess.Platform, "win32"), - Effect.provideService(SpawnExecutableResolution, () => input.resolvedCommand), + Effect.provideService(SpawnExecutableResolution, async () => input.resolvedCommand), Effect.provideService(ClaudeExecutableFileCheck, (filePath) => existing.has(filePath)), ); } diff --git a/apps/server/src/provider/Drivers/ClaudeExecutable.ts b/apps/server/src/provider/Drivers/ClaudeExecutable.ts index 5797066446b99..6f4e85812f0cc 100644 --- a/apps/server/src/provider/Drivers/ClaudeExecutable.ts +++ b/apps/server/src/provider/Drivers/ClaudeExecutable.ts @@ -50,7 +50,9 @@ export const resolveClaudeSdkExecutablePath = Effect.fn("resolveClaudeSdkExecuta const resolveExecutable = yield* SpawnExecutableResolution; const isFile = yield* ClaudeExecutableFileCheck; - const resolved = resolveExecutable(binaryPath, platform, environment) ?? binaryPath; + const resolved = + (yield* Effect.promise(async () => resolveExecutable(binaryPath, platform, environment))) ?? + binaryPath; const extension = NodePath.win32.extname(resolved).toLowerCase(); if (!WINDOWS_SHIM_EXTENSIONS.has(extension)) { return resolved; diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index fb19b6c7ad1d6..e87ba67cf5837 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -2791,15 +2791,12 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func .join(":"), }; // POSIX node-pty can return a PTY before exec fails, so validate before accepting a candidate. + const shellCommand = candidate.shell.includes("/") + ? path.resolve(session.cwd, candidate.shell) + : candidate.shell; const executable = platform !== "win32" - ? resolveExecutable( - candidate.shell.includes("/") - ? path.resolve(session.cwd, candidate.shell) - : candidate.shell, - platform, - lookupEnv, - ) + ? yield* Effect.promise(async () => resolveExecutable(shellCommand, platform, lookupEnv)) : candidate.shell; if (executable === undefined) { return yield* trySpawn( diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts index 398c48be3f68c..75311d6598b7e 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts @@ -318,7 +318,7 @@ describe("AcpRegistrySupport", () => { registryUrl, }).pipe( Effect.provideService(HostProcess.Platform, "win32"), - Effect.provideService(SpawnExecutableResolution, () => `C:\\bin\\dsh${extension}`), + Effect.provideService(SpawnExecutableResolution, async () => `C:\\bin\\dsh${extension}`), ); const localSettings = decodeAcpRegistrySettings({ source: "local", commandPath: "dsh" }); for (const failure of [ @@ -1206,6 +1206,7 @@ describe("AcpRegistrySupport", () => { name: "Codex Darwin", } satisfies AcpRegistrySupport.AcpRegistryAgent; + const lookups: string[] = []; return Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ @@ -1215,9 +1216,15 @@ describe("AcpRegistrySupport", () => { cacheDir, toolsDir: `${cacheDir}/tools`, registryUrl, - }); + }).pipe( + Effect.provideService(SpawnExecutableResolution, async (command) => { + lookups.push(command); + return "/bin/npm"; + }), + ); const result = yield* resolver.search({ query: "codex" }); + expect(lookups).toEqual(["npm"]); expect(result.agents.map((agent) => agent.id)).toEqual(["codex-acp", "other-agent"]); expect(result.agents[0]).toMatchObject({ authors: ["OpenAI", "Zed Industries"], diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts index d3ab397d7aaeb..26d58fb4ea9ad 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts @@ -673,7 +673,13 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const platform = yield* HostProcess.Platform; const architecture = yield* HostProcess.Architecture; const hostEnvironment = yield* HostProcess.Environment; - const resolveExecutable = yield* SpawnExecutableResolution; + const executableResolver = yield* SpawnExecutableResolution; + const resolveExecutable = Effect.fn("AcpRegistryCatalog.resolveExecutable")(function* ( + command: string, + environment: NodeJS.ProcessEnv, + ) { + return yield* Effect.promise(async () => executableResolver(command, platform, environment)); + }); const platformTarget = resolveAcpRegistryPlatformTarget(platform, architecture); const registryUrl = input.registryUrl ?? ACP_REGISTRY_URL; const registryDirectory = path.join(input.cacheDir, "acp-registry"); @@ -1240,9 +1246,8 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const commandName = npmCommandName(agent, packageIdentity.name, manifest.value); if (commandName === undefined) return Option.none(); const binDirectory = platform === "win32" ? globalPrefix : path.join(globalPrefix, "bin"); - const executablePath = resolveExecutable( + const executablePath = yield* resolveExecutable( path.join(binDirectory, commandName), - platform, environment, ); return executablePath === undefined @@ -1289,9 +1294,11 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct truncatedOutputReason: "install_failed", }).pipe(Effect.flatMap((output) => parsePackageManagerPath(managerPath, output))); const managedBinEnvironment = { ...environment, PATH: binDirectory }; - const executablePath = packageCommandCandidates(agent, packageIdentity.name) - .map((candidate) => resolveExecutable(candidate, platform, managedBinEnvironment)) - .find((candidate): candidate is string => candidate !== undefined); + let executablePath: string | undefined; + for (const candidate of packageCommandCandidates(agent, packageIdentity.name)) { + executablePath = yield* resolveExecutable(candidate, managedBinEnvironment); + if (executablePath !== undefined) break; + } return executablePath === undefined ? Option.none() : Option.some({ @@ -1314,7 +1321,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct environment: NodeJS.ProcessEnv, ) { const managerName = packageManagerFor(distribution)!; - const managerPath = resolveExecutable(managerName, platform, environment); + const managerPath = yield* resolveExecutable(managerName, environment); if (managerPath === undefined) { return yield* new AcpRegistryError({ reason: "runner_unavailable", @@ -1740,22 +1747,27 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const search: AcpRegistryCatalog["Service"]["search"] = Effect.fn("AcpRegistryCatalog.search")( function* (input) { const registry = yield* recentRegistry(); - const ranked = registry.agents.flatMap((agent) => { + const ranked = []; + const managerAvailability = new Map(); + for (const agent of registry.agents) { const distribution = resolveAcpRegistryDistribution({ agent, preference: "auto", platformTarget, }); const rank = searchRank(agent, input.query); - const packageManager = - distribution === undefined ? undefined : packageManagerFor(distribution.kind); - const packageManagerAvailable = - packageManager === undefined || - resolveExecutable(packageManager, platform, hostEnvironment) !== undefined; - return distribution === undefined || rank === undefined || !packageManagerAvailable - ? [] - : [{ agent, distribution, rank }]; - }); + if (distribution === undefined || rank === undefined) continue; + const packageManager = packageManagerFor(distribution.kind); + if (packageManager !== undefined) { + let available = managerAvailability.get(packageManager); + if (available === undefined) { + available = (yield* resolveExecutable(packageManager, hostEnvironment)) !== undefined; + managerAvailability.set(packageManager, available); + } + if (!available) continue; + } + ranked.push({ agent, distribution, rank }); + } ranked.sort( (left, right) => left.rank - right.rank || @@ -1826,7 +1838,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct if (settings.source === "local") { const command = settings.commandPath.trim(); if (!command) return { status: "unconfigured" } as const; - const executable = resolveExecutable(command, platform, environment ?? hostEnvironment); + const executable = yield* resolveExecutable(command, environment ?? hostEnvironment); if (executable !== undefined) yield* validateLocalExecutable(executable); return executable === undefined ? ({ @@ -1854,8 +1866,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const commandOverride = settings.commandPath.trim(); if (commandOverride.length > 0) { const available = - resolveExecutable(commandOverride, platform, environment ?? hostEnvironment) !== - undefined; + (yield* resolveExecutable(commandOverride, environment ?? hostEnvironment)) !== undefined; return available ? ({ status: "ready", @@ -1919,7 +1930,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const runner = packageManagerFor(distribution.kind)!; const available = - resolveExecutable(runner, platform, environment ?? hostEnvironment) !== undefined; + (yield* resolveExecutable(runner, environment ?? hostEnvironment)) !== undefined; return available ? ({ status: "ready", @@ -1960,7 +1971,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const effectiveEnvironment = environment ?? hostEnvironment; const commandOverride = settings.commandPath.trim(); if (commandOverride.length > 0) { - const resolvedOverride = resolveExecutable(commandOverride, platform, effectiveEnvironment); + const resolvedOverride = yield* resolveExecutable(commandOverride, effectiveEnvironment); if (resolvedOverride === undefined) { return yield* new AcpRegistryError({ reason: "runner_unavailable", @@ -2028,7 +2039,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct }); } const env = environment ?? hostEnvironment; - const command = resolveExecutable(executable, platform, env); + const command = yield* resolveExecutable(executable, env); if (command === undefined) { return yield* new AcpRegistryError({ reason: "runner_unavailable", diff --git a/packages/provider-acp/src/server/clientTerminals.ts b/packages/provider-acp/src/server/clientTerminals.ts index c8371fb7020e8..592bf47553494 100644 --- a/packages/provider-acp/src/server/clientTerminals.ts +++ b/packages/provider-acp/src/server/clientTerminals.ts @@ -263,7 +263,7 @@ export const makeAcpClientTerminals = Effect.fn("makeAcpClientTerminals")(functi // Agents that send shell source write bash; Node's shell on Windows is cmd.exe. const gitExecutable = isWindows && options.shellCommands === true - ? resolveExecutable("git", "win32", environment) + ? yield* Effect.promise(async () => resolveExecutable("git", "win32", environment)) : undefined; const posixShell = gitExecutable === undefined ? undefined : gitForWindowsBash(gitExecutable); diff --git a/packages/provider-muse/src/server/MuseUsageHome.ts b/packages/provider-muse/src/server/MuseUsageHome.ts index 1ced0d2578b01..329dce90c0e7b 100644 --- a/packages/provider-muse/src/server/MuseUsageHome.ts +++ b/packages/provider-muse/src/server/MuseUsageHome.ts @@ -66,7 +66,11 @@ const make = Effect.gen(function* () { if (Option.isSome(settled)) return settled; // Spawn failures surface asynchronously; without this a missing CLI would report as pending. const resolveExecutable = yield* SpawnExecutableResolution; - if (resolveExecutable(binaryPath, yield* HostProcess.Platform, environment) === undefined) { + const platform = yield* HostProcess.Platform; + const resolved = yield* Effect.promise(async () => + resolveExecutable(binaryPath, platform, environment), + ); + if (resolved === undefined) { return Option.some(undefined); } if (awaitRefresh) return Option.some(yield* Cache.get(cache, key)); diff --git a/packages/provider-muse/src/server/sdk.test.ts b/packages/provider-muse/src/server/sdk.test.ts index 45ef56cb63458..6607640751092 100644 --- a/packages/provider-muse/src/server/sdk.test.ts +++ b/packages/provider-muse/src/server/sdk.test.ts @@ -263,7 +263,7 @@ describe("Muse launch", () => { const onWindows = (resolved: string | undefined, env: NodeJS.ProcessEnv = { ComSpec: CMD }) => museLaunch("muse", env).pipe( Effect.provideService(HostProcess.Platform, "win32"), - Effect.provideService(SpawnExecutableResolution, () => resolved), + Effect.provideService(SpawnExecutableResolution, async () => resolved), ); it.effect("runs an exe directly and a launcher script under cmd.exe on Windows", () => diff --git a/packages/provider-muse/src/server/sdk.ts b/packages/provider-muse/src/server/sdk.ts index 6d6b4d5d51050..aece589b1e188 100644 --- a/packages/provider-muse/src/server/sdk.ts +++ b/packages/provider-muse/src/server/sdk.ts @@ -117,7 +117,8 @@ export const museLaunch = Effect.fn("museLaunch")(function* ( if ((yield* HostProcess.Platform) !== "win32") return { command: binaryPath, args: [] }; const env = environment ?? (yield* HostProcess.Environment); const resolveExecutable = yield* SpawnExecutableResolution; - const resolved = resolveExecutable(binaryPath, "win32", env) ?? binaryPath; + const resolved = + (yield* Effect.promise(async () => resolveExecutable(binaryPath, "win32", env))) ?? binaryPath; if (!/\.(?:cmd|bat)$/i.test(resolved)) return { command: resolved, args: [] }; const systemRoot = windowsEnvironmentValue(env, "SystemRoot"); return { diff --git a/packages/provider-muse/src/server/usage.test.ts b/packages/provider-muse/src/server/usage.test.ts index 3815cfce44321..d02271f44ff04 100644 --- a/packages/provider-muse/src/server/usage.test.ts +++ b/packages/provider-muse/src/server/usage.test.ts @@ -260,7 +260,7 @@ describe("Muse history discovery", () => { expect(create).not.toHaveBeenCalled(); }).pipe( Effect.provide([NodeServices.layer, MuseUsageHome.layer]), - Effect.provideService(SpawnExecutableResolution, () => undefined), + Effect.provideService(SpawnExecutableResolution, async () => undefined), ), ); diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts index 08731a41c19ef..8f81723486f55 100644 --- a/packages/shared/src/shell.test.ts +++ b/packages/shared/src/shell.test.ts @@ -577,7 +577,9 @@ effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => { ), ).toBe(path.join(directory, "audit-command")); const resolveExecutable = yield* SpawnExecutableResolution; - expect(resolveExecutable("audit-command", "linux", env)).toBe(executable); + expect( + yield* Effect.promise(async () => resolveExecutable("audit-command", "linux", env)), + ).toBe(executable); }), ); @@ -736,7 +738,7 @@ effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => { // A POSIX directory joined with win32 separators names nothing, so this needs a Windows host. it.effect.skipIf(HostProcess.Platform.defaultValue() !== "win32")( - "relists a changed PATH directory in the synchronous spawn resolver", + "relists a changed PATH directory in the spawn resolver", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -746,11 +748,17 @@ effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => { yield* fs.utimes(directory, 946_684_800, 946_684_800); const env = { PATH: directory, PATHEXT: ".EXE;.CMD" }; const resolveExecutable = yield* SpawnExecutableResolution; - expect(resolveExecutable("cursor", "win32", env)).toBe(path.join(directory, "cursor.CMD")); - expect(resolveExecutable("late", "win32", env)).toBeUndefined(); + expect(yield* Effect.promise(async () => resolveExecutable("cursor", "win32", env))).toBe( + path.join(directory, "cursor.CMD"), + ); + expect( + yield* Effect.promise(async () => resolveExecutable("late", "win32", env)), + ).toBeUndefined(); yield* fs.writeFileString(path.join(directory, "late.EXE"), ""); yield* fs.utimes(directory, 946_684_830, 946_684_830); - expect(resolveExecutable("late", "win32", env)).toBe(path.join(directory, "late.EXE")); + expect(yield* Effect.promise(async () => resolveExecutable("late", "win32", env))).toBe( + path.join(directory, "late.EXE"), + ); }), ); }); @@ -975,6 +983,73 @@ describe("npmShimExecutable", () => { }); effectIt.layer(NodeServices.layer)("resolveSpawnCommand", (it) => { + it.effect("yields while discovering a Windows executable", () => + Effect.scoped( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-spawn-" }); + const executable = path.join(directory, "tool.EXE"); + yield* fs.writeFileString(executable, ""); + let settled = false; + const pending = Promise.resolve( + SpawnExecutableResolution.defaultValue()(executable, "win32", { PATHEXT: ".EXE;.CMD" }), + ).then((value) => { + settled = true; + return value; + }); + try { + yield* Effect.promise(() => Promise.resolve()); + expect(settled).toBe(false); + } finally { + expect(yield* Effect.promise(() => pending)).toBe(executable); + } + }), + ), + ); + + it.effect("preserves PATH and PATHEXT order and discovers executables after a miss", () => + Effect.scoped( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-spawn-" }); + const fixture = NodePath.join(directory, "tool.EXE"); + yield* fs.writeFileString(fixture, ""); + const stat = yield* Effect.promise(() => NodeFS.promises.stat(fixture)); + const files = new Set(); + using _stat = vi.spyOn(NodeFS.promises, "stat").mockImplementation(async (candidate) => { + if (!files.has(String(candidate))) throw new Error("not found"); + return stat; + }); + const lookup = resolveSpawnCommand("tool", ["status"], { + env: { PATH: "C:\\first;C:\\later", PATHEXT: ".EXE;.CMD" }, + }); + expect((yield* lookup).command).toBe("tool"); + files.add("C:\\first\\tool.CMD"); + files.add("C:\\first\\tool.EXE"); + files.add("C:\\later\\tool.EXE"); + expect(yield* lookup).toEqual({ + command: "C:\\first\\tool.EXE", + args: ["status"], + shell: false, + }); + files.delete("C:\\first\\tool.EXE"); + expect((yield* lookup).command).toBe("C:\\first\\tool.EXE"); + expect( + yield* Effect.promise(async () => + SpawnExecutableResolution.defaultValue()("tool", "win32", { + PATH: "C:\\first;C:\\later", + PATHEXT: ".EXE;.CMD", + }), + ), + ).toBe("C:\\first\\tool.CMD"); + }).pipe( + Effect.provideService(HostProcess.Platform, "win32"), + Effect.provideService(CommandResolutionCache, new Map()), + ), + ), + ); + it.effect("runs Windows executables directly without a shell", () => Effect.gen(function* () { const command = yield* resolveSpawnCommand("node.exe", ["script.js", "hello & goodbye"], { diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.ts index ffcc1110fe381..0ba42dc3078d6 100644 --- a/packages/shared/src/shell.ts +++ b/packages/shared/src/shell.ts @@ -75,13 +75,13 @@ export type SpawnExecutableResolver = ( command: string, platform: NodeJS.Platform, env: NodeJS.ProcessEnv, -) => string | undefined; +) => string | undefined | Promise; -function resolveSpawnExecutableWithNode( +async function resolveSpawnExecutableWithNode( command: string, platform: NodeJS.Platform, env: NodeJS.ProcessEnv, -): string | undefined { +): Promise { const path = platform === "win32" ? NodePath.win32 : NodePath.posix; const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : []; const candidates = resolveCommandCandidates( @@ -90,20 +90,24 @@ function resolveSpawnExecutableWithNode( windowsPathExtensions, path.extname, ); - const isExecutable = (candidate: string) => { + const isExecutable = async (candidate: string) => { try { - if (!NodeFS.statSync(candidate).isFile()) return false; + if (!(await NodeFS.promises.stat(candidate)).isFile()) return false; if (platform === "win32") { return windowsPathExtensions.includes(path.extname(candidate).toUpperCase()); } - return canExecuteFile(candidate); + await NodeFS.promises.access(candidate, NodeFS.constants.X_OK); + return true; } catch { return false; } }; if (command.includes("/") || command.includes("\\")) { - return candidates.find(isExecutable); + for (const candidate of candidates) { + if (await isExecutable(candidate)) return candidate; + } + return undefined; } for (const pathEntry of (readEnvPath(env) ?? "").split(pathDelimiterForPlatform(platform))) { @@ -111,12 +115,12 @@ function resolveSpawnExecutableWithNode( if (normalizedPathEntry.length === 0) continue; const names = platform === "win32" - ? listPathDirectorySync(normalizedPathEntry, path.isAbsolute) + ? await listResolverPathDirectory(normalizedPathEntry, path.isAbsolute) : undefined; for (const candidate of candidates) { if (isAbsentFromListing(names, candidate)) continue; const candidatePath = path.join(normalizedPathEntry, candidate); - if (isExecutable(candidatePath)) return candidatePath; + if (await isExecutable(candidatePath)) return candidatePath; } } return undefined; @@ -661,42 +665,42 @@ export const PathDirectoryListings = Context.Reference( { defaultValue: () => Effect.runSync(makePathDirectoryListings) }, ); -const syncPathDirectoryListings = new Map< +const resolverPathDirectoryListings = new Map< string, { readonly modified: number; readonly names: ReadonlySet } >(); -// The synchronous resolver's counterpart of `PathDirectoryListings`, under the same rules. -function listPathDirectorySync( +// The spawn resolver's counterpart of `PathDirectoryListings`, under the same rules. +async function listResolverPathDirectory( directory: string, isAbsolute: (path: string) => boolean, -): ReadonlySet | undefined { +): Promise | undefined> { let modified: number; try { - const stats = NodeFS.statSync(directory); + const stats = await NodeFS.promises.stat(directory); if (!stats.isDirectory()) return undefined; modified = stats.mtimeMs; } catch (error) { return (error as NodeJS.ErrnoException).code === "ENOENT" ? NO_DIRECTORY_NAMES : undefined; } - const cached = syncPathDirectoryListings.get(directory); + const cached = resolverPathDirectoryListings.get(directory); if (cached?.modified === modified) return cached.names; - syncPathDirectoryListings.delete(directory); + resolverPathDirectoryListings.delete(directory); // This resolver runs outside Effect, so it has no Clock to read. // @effect-diagnostics-next-line globalDate:off const listedAtMs = Date.now(); let names: ReadonlySet; try { - names = new Set(NodeFS.readdirSync(directory).map((entry) => entry.toLowerCase())); + names = new Set((await NodeFS.promises.readdir(directory)).map((entry) => entry.toLowerCase())); } catch { return undefined; } if (isReusableListing(directory, modified, listedAtMs, isAbsolute)) { - if (syncPathDirectoryListings.size >= PATH_DIRECTORY_LISTINGS_MAX_ENTRIES) { - const oldest = syncPathDirectoryListings.keys().next().value; - if (oldest !== undefined) syncPathDirectoryListings.delete(oldest); + if (resolverPathDirectoryListings.size >= PATH_DIRECTORY_LISTINGS_MAX_ENTRIES) { + const oldest = resolverPathDirectoryListings.keys().next().value; + if (oldest !== undefined) resolverPathDirectoryListings.delete(oldest); } - syncPathDirectoryListings.set(directory, { modified, names }); + resolverPathDirectoryListings.set(directory, { modified, names }); } return names; } @@ -1002,18 +1006,21 @@ const resolveMacosGit = Effect.fnUntraced(function* ( const nowNanos = yield* Clock.currentTimeNanos; const cached = cache.get(cacheKey); // An Xcode update or removal deletes the binary; look again instead of failing the spawn. - if ( - cached !== undefined && - cached.expiresAtNanos > nowNanos && - (cached.resolvedPath === null || - resolveExecutable(cached.resolvedPath, "darwin", env) !== undefined) - ) { - return cached.resolvedPath ?? "git"; + if (cached !== undefined && cached.expiresAtNanos > nowNanos) { + const cachedPath = cached.resolvedPath; + if ( + cachedPath === null || + (yield* Effect.promise(async () => resolveExecutable(cachedPath, "darwin", env))) !== + undefined + ) { + return cachedPath ?? "git"; + } } - const located = - resolveExecutable("git", "darwin", env) === MACOS_GIT_SHIM ? locateXcodeGit(env) : undefined; + const onPath = yield* Effect.promise(async () => resolveExecutable("git", "darwin", env)); + const located = onPath === MACOS_GIT_SHIM ? locateXcodeGit(env) : undefined; const realGit = - located !== undefined && resolveExecutable(located, "darwin", env) !== undefined + located !== undefined && + (yield* Effect.promise(async () => resolveExecutable(located, "darwin", env))) !== undefined ? located : null; cacheCommandResolution(cache, cacheKey, realGit, nowNanos); @@ -1093,10 +1100,8 @@ export const resolveSpawnCommand = Effect.fnUntraced(function* ( shell: false, }; } - // The scan is synchronous and runs before every child process, so it shares - // the PATH scan cache above. Explicit paths stay uncached for the same reason, - // and so do misses: a failed spawn is how providers report "not installed", - // and that has to clear the moment the binary appears. + // Cache successful PATH lookups. Explicit paths and misses stay uncached so + // newly installed executables are discoverable immediately. const explicitPath = command.includes("/") || command.includes("\\"); const cache = yield* CommandResolutionCache; const cacheKey = [ @@ -1114,7 +1119,7 @@ export const resolveSpawnCommand = Effect.fnUntraced(function* ( if (cached !== undefined && cached.expiresAtNanos > nowNanos) { resolvedExecutable = cached.resolvedPath; } else { - const found = resolveExecutable(command, platform, env); + const found = yield* Effect.promise(async () => resolveExecutable(command, platform, env)); resolvedExecutable = found === undefined ? null : preferGitForWindowsBinary(found, env); if (!explicitPath && resolvedExecutable !== null) { cacheCommandResolution(cache, cacheKey, resolvedExecutable, nowNanos); diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsCli.test.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsCli.test.ts index 6e4600fe5a338..c71f1f36df2fb 100644 --- a/packages/source-control-azure-devops/src/server/AzureDevOpsCli.test.ts +++ b/packages/source-control-azure-devops/src/server/AzureDevOpsCli.test.ts @@ -414,7 +414,7 @@ describe("azureCliInvocation", () => { AzureDevOpsCli.azureCliInvocation().pipe( Effect.provideService(HostProcess.Platform, "win32"), Effect.provideService(HostProcess.Environment, { PATH: "C:\\tools" }), - Effect.provideService(SpawnExecutableResolution, () => launcher), + Effect.provideService(SpawnExecutableResolution, async () => launcher), Effect.provideService(AzureCliInstallLocation, () => install), ); diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts index 6cffe9ab0b3ab..f289e7406950f 100644 --- a/packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts +++ b/packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts @@ -495,7 +495,8 @@ export const azureCliInvocation = Effect.fn("AzureDevOpsCli.invocation")(functio return { command: "az", args: [] } satisfies AzureCliInvocation; } const resolveExecutable = yield* SpawnExecutableResolution; - const launcher = resolveExecutable("az", "win32", yield* HostProcess.Environment); + const env = yield* HostProcess.Environment; + const launcher = yield* Effect.promise(async () => resolveExecutable("az", "win32", env)); const installFor = yield* AzureCliInstallLocation; const install = launcher === undefined ? undefined : installFor(launcher); // Unrecognized installs (pipx's Scripts\az.exe) keep the launcher and today's decode. diff --git a/packages/source-control-core/src/server/discovery.ts b/packages/source-control-core/src/server/discovery.ts index 62ec94d7d67fe..0cc6654adf021 100644 --- a/packages/source-control-core/src/server/discovery.ts +++ b/packages/source-control-core/src/server/discovery.ts @@ -357,7 +357,8 @@ const unavailableInstallHint = Effect.fn("discovery.unavailableInstallHint")(fun return installHint; } const resolveExecutable = yield* SpawnExecutableResolution; - const path = resolveExecutable(executable, platform, yield* HostProcess.Environment); + const env = yield* HostProcess.Environment; + const path = yield* Effect.promise(async () => resolveExecutable(executable, platform, env)); const architecture = yield* HostProcess.Architecture; return `\`${path ?? executable}\` is built for another CPU architecture, so this ${architecture} machine cannot run it. Remove or replace it. ${installHint}`; }); From b479ce21edae40ed1bcd02d117e54bb7243e5897 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 05:34:59 -0800 Subject: [PATCH 168/324] fix(client-runtime): stop sessions on incompatible server configuration (#21667) Co-authored-by: Claude Opus 5.5 --- apps/mobile/src/i18n/translations/de.json | 3 + apps/mobile/src/i18n/translations/en.json | 3 + apps/mobile/src/i18n/translations/es.json | 3 + apps/mobile/src/i18n/translations/fr.json | 3 + apps/mobile/src/i18n/translations/ja.json | 3 + apps/mobile/src/i18n/translations/ko.json | 3 + apps/mobile/src/i18n/translations/pt-BR.json | 3 + apps/mobile/src/i18n/translations/ru.json | 3 + apps/mobile/src/i18n/translations/sv.json | 3 + apps/mobile/src/i18n/translations/zh.json | 3 + apps/web/src/i18n/translations/de.json | 3 + apps/web/src/i18n/translations/en.json | 3 + apps/web/src/i18n/translations/es.json | 3 + apps/web/src/i18n/translations/fr.json | 3 + apps/web/src/i18n/translations/ja.json | 3 + apps/web/src/i18n/translations/ko.json | 3 + apps/web/src/i18n/translations/pt-BR.json | 3 + apps/web/src/i18n/translations/ru.json | 3 + apps/web/src/i18n/translations/sv.json | 3 + apps/web/src/i18n/translations/zh.json | 3 + .../client-runtime/src/rpc/session.test.ts | 80 +++++++++ packages/client-runtime/src/rpc/session.ts | 154 ++++++++++++------ 22 files changed, 241 insertions(+), 53 deletions(-) diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index 039e1ddadd0bf..f4d80a116eece 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} konnte keine WebSocket-Verbindung herstellen.", "d9ce6c142a485959": "{host} hat {seconds} s lang nicht geantwortet.", "d6bdce8f4e6101a4": "{host} wurde getrennt.", + "8450a95e5214d199": "{host} hat ein Update der Serverkonfiguration gesendet, das dieser Client nicht lesen konnte.", + "56b4ff3993c93eca": "{host} hat eine inkompatible Serverkonfiguration gesendet.", + "368c4d4f99c66bfb": "Aktualisiere Client und Server auf kompatible Versionen.", "e5fd422e445391fc": "Upload fehlgeschlagen. Zum Wiederholen tippen.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 91170171c1621..62b182b1a30c9 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} could not establish a WebSocket connection.", "d9ce6c142a485959": "{host} stopped responding for {seconds}s.", "d6bdce8f4e6101a4": "{host} disconnected.", + "8450a95e5214d199": "{host} sent a server configuration update this client could not read.", + "56b4ff3993c93eca": "{host} sent an incompatible server configuration.", + "368c4d4f99c66bfb": "Update the client and server to compatible versions.", "e5fd422e445391fc": "Upload failed. Tap to retry.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index 398c20ce17f1f..55d4e81456cc5 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} no pudo establecer una conexión WebSocket.", "d9ce6c142a485959": "{host} dejó de responder durante {seconds} s.", "d6bdce8f4e6101a4": "{host} se desconectó.", + "8450a95e5214d199": "{host} envió una actualización de la configuración del servidor que este cliente no pudo leer.", + "56b4ff3993c93eca": "{host} envió una configuración del servidor incompatible.", + "368c4d4f99c66bfb": "Actualiza el cliente y el servidor a versiones compatibles.", "e5fd422e445391fc": "Error al subir. Toca para reintentar.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index 1734d91934a04..245547981f3dc 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} n’a pas pu établir de connexion WebSocket.", "d9ce6c142a485959": "{host} ne répond plus depuis {seconds} s.", "d6bdce8f4e6101a4": "{host} est déconnecté.", + "8450a95e5214d199": "{host} a envoyé une mise à jour de la configuration du serveur que ce client n’a pas pu lire.", + "56b4ff3993c93eca": "{host} a envoyé une configuration de serveur incompatible.", + "368c4d4f99c66bfb": "Mettez à jour le client et le serveur vers des versions compatibles.", "e5fd422e445391fc": "Échec de l’envoi. Touchez pour réessayer.", "b2bc6bd92ea24e5c": "{size} Mo", "88f84178edbb7f57": "{size} Ko", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index 113ada551f17d..a62452cddc89d 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} は WebSocket 接続を確立できませんでした。", "d9ce6c142a485959": "{host} は {seconds} 秒間応答していません。", "d6bdce8f4e6101a4": "{host} の接続が切断されました。", + "8450a95e5214d199": "{host} から、このクライアントで読み取れないサーバー設定の更新が送信されました。", + "56b4ff3993c93eca": "{host} から互換性のないサーバー設定が送信されました。", + "368c4d4f99c66bfb": "クライアントとサーバーを互換性のあるバージョンに更新してください。", "e5fd422e445391fc": "アップロードに失敗しました。タップして再試行してください。", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index 7768bd410d434..87195d1e59336 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host}에서 WebSocket 연결을 설정할 수 없습니다.", "d9ce6c142a485959": "{host}이(가) {seconds}초 동안 응답하지 않습니다.", "d6bdce8f4e6101a4": "{host} 연결이 끊어졌습니다.", + "8450a95e5214d199": "{host}에서 이 클라이언트가 읽을 수 없는 서버 구성 업데이트를 보냈습니다.", + "56b4ff3993c93eca": "{host}에서 호환되지 않는 서버 구성을 보냈습니다.", + "368c4d4f99c66bfb": "클라이언트와 서버를 호환되는 버전으로 업데이트하세요.", "e5fd422e445391fc": "업로드에 실패했습니다. 탭하여 다시 시도하세요.", "b2bc6bd92ea24e5c": "{size}MB", "88f84178edbb7f57": "{size} KB", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 88dbb8da5cd87..fb5d60acdbd89 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} não conseguiu estabelecer uma conexão WebSocket.", "d9ce6c142a485959": "{host} parou de responder por {seconds} s.", "d6bdce8f4e6101a4": "{host} desconectou.", + "8450a95e5214d199": "{host} enviou uma atualização da configuração do servidor que este cliente não conseguiu ler.", + "56b4ff3993c93eca": "{host} enviou uma configuração de servidor incompatível.", + "368c4d4f99c66bfb": "Atualize o cliente e o servidor para versões compatíveis.", "e5fd422e445391fc": "Falha no envio. Toque para tentar novamente.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index 2d0fb55302031..b5beca32c6869 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} не удалось установить WebSocket-соединение.", "d9ce6c142a485959": "{host} не отвечает уже {seconds} с.", "d6bdce8f4e6101a4": "{host} отключён.", + "8450a95e5214d199": "{host} отправил обновление конфигурации сервера, которое этот клиент не смог прочитать.", + "56b4ff3993c93eca": "{host} отправил несовместимую конфигурацию сервера.", + "368c4d4f99c66bfb": "Обновите клиент и сервер до совместимых версий.", "e5fd422e445391fc": "Ошибка загрузки. Нажмите, чтобы повторить.", "b2bc6bd92ea24e5c": "{size} МБ", "88f84178edbb7f57": "{size} КБ", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 70617afd183ca..28ed7e557146a 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} kunde inte upprätta en WebSocket-anslutning.", "d9ce6c142a485959": "{host} slutade svara i {seconds} s.", "d6bdce8f4e6101a4": "{host} kopplades från.", + "8450a95e5214d199": "{host} skickade en uppdatering av serverkonfigurationen som den här klienten inte kunde läsa.", + "56b4ff3993c93eca": "{host} skickade en inkompatibel serverkonfiguration.", + "368c4d4f99c66bfb": "Uppdatera klienten och servern till kompatibla versioner.", "e5fd422e445391fc": "Uppladdningen misslyckades. Tryck för att försöka igen.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} kB", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index 485d4206bf054..52857eda6cc8a 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} 无法建立 WebSocket 连接。", "d9ce6c142a485959": "{host} 已 {seconds} 秒无响应。", "d6bdce8f4e6101a4": "{host} 已断开连接。", + "8450a95e5214d199": "{host} 发送了此客户端无法读取的服务器配置更新。", + "56b4ff3993c93eca": "{host} 发送了不兼容的服务器配置。", + "368c4d4f99c66bfb": "请将客户端和服务器更新到兼容的版本。", "e5fd422e445391fc": "上传失败。点按以重试。", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 3a71e92063446..0db2fb8989ce2 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} konnte keine WebSocket-Verbindung herstellen.", "d9ce6c142a485959": "{host} hat {seconds} s lang nicht geantwortet.", "d6bdce8f4e6101a4": "{host} wurde getrennt.", + "8450a95e5214d199": "{host} hat ein Update der Serverkonfiguration gesendet, das dieser Client nicht lesen konnte.", + "56b4ff3993c93eca": "{host} hat eine inkompatible Serverkonfiguration gesendet.", + "368c4d4f99c66bfb": "Aktualisiere Client und Server auf kompatible Versionen.", "e5fd422e445391fc": "Upload fehlgeschlagen. Zum Wiederholen tippen.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 65ed2a4db1b89..3aa61a18f6b2b 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} could not establish a WebSocket connection.", "d9ce6c142a485959": "{host} stopped responding for {seconds}s.", "d6bdce8f4e6101a4": "{host} disconnected.", + "8450a95e5214d199": "{host} sent a server configuration update this client could not read.", + "56b4ff3993c93eca": "{host} sent an incompatible server configuration.", + "368c4d4f99c66bfb": "Update the client and server to compatible versions.", "e5fd422e445391fc": "Upload failed. Tap to retry.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index dae05eda74dd9..60ddca69b570f 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} no pudo establecer una conexión WebSocket.", "d9ce6c142a485959": "{host} dejó de responder durante {seconds} s.", "d6bdce8f4e6101a4": "{host} se desconectó.", + "8450a95e5214d199": "{host} envió una actualización de la configuración del servidor que este cliente no pudo leer.", + "56b4ff3993c93eca": "{host} envió una configuración del servidor incompatible.", + "368c4d4f99c66bfb": "Actualiza el cliente y el servidor a versiones compatibles.", "e5fd422e445391fc": "Error al subir. Toca para reintentar.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 6054810c0c23d..fdcba31a1032f 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} n’a pas pu établir de connexion WebSocket.", "d9ce6c142a485959": "{host} ne répond plus depuis {seconds} s.", "d6bdce8f4e6101a4": "{host} est déconnecté.", + "8450a95e5214d199": "{host} a envoyé une mise à jour de la configuration du serveur que ce client n’a pas pu lire.", + "56b4ff3993c93eca": "{host} a envoyé une configuration de serveur incompatible.", + "368c4d4f99c66bfb": "Mettez à jour le client et le serveur vers des versions compatibles.", "e5fd422e445391fc": "Échec de l’envoi. Touchez pour réessayer.", "b2bc6bd92ea24e5c": "{size} Mo", "88f84178edbb7f57": "{size} Ko", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 188d63866545c..13379225ecf26 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} は WebSocket 接続を確立できませんでした。", "d9ce6c142a485959": "{host} は {seconds} 秒間応答していません。", "d6bdce8f4e6101a4": "{host} の接続が切断されました。", + "8450a95e5214d199": "{host} から、このクライアントで読み取れないサーバー設定の更新が送信されました。", + "56b4ff3993c93eca": "{host} から互換性のないサーバー設定が送信されました。", + "368c4d4f99c66bfb": "クライアントとサーバーを互換性のあるバージョンに更新してください。", "e5fd422e445391fc": "アップロードに失敗しました。タップして再試行してください。", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index fd4f1a5af2fc8..cc8261d7681ff 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host}에서 WebSocket 연결을 설정할 수 없습니다.", "d9ce6c142a485959": "{host}이(가) {seconds}초 동안 응답하지 않습니다.", "d6bdce8f4e6101a4": "{host} 연결이 끊어졌습니다.", + "8450a95e5214d199": "{host}에서 이 클라이언트가 읽을 수 없는 서버 구성 업데이트를 보냈습니다.", + "56b4ff3993c93eca": "{host}에서 호환되지 않는 서버 구성을 보냈습니다.", + "368c4d4f99c66bfb": "클라이언트와 서버를 호환되는 버전으로 업데이트하세요.", "e5fd422e445391fc": "업로드에 실패했습니다. 탭하여 다시 시도하세요.", "b2bc6bd92ea24e5c": "{size}MB", "88f84178edbb7f57": "{size} KB", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index f8450e8032e5f..a9ce3832a0b9f 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} não conseguiu estabelecer uma conexão WebSocket.", "d9ce6c142a485959": "{host} parou de responder por {seconds} s.", "d6bdce8f4e6101a4": "{host} desconectou.", + "8450a95e5214d199": "{host} enviou uma atualização da configuração do servidor que este cliente não conseguiu ler.", + "56b4ff3993c93eca": "{host} enviou uma configuração de servidor incompatível.", + "368c4d4f99c66bfb": "Atualize o cliente e o servidor para versões compatíveis.", "e5fd422e445391fc": "Falha no envio. Toque para tentar novamente.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 75b7db757cf04..ee0fe30aa4f39 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} не удалось установить WebSocket-соединение.", "d9ce6c142a485959": "{host} не отвечает уже {seconds} с.", "d6bdce8f4e6101a4": "{host} отключён.", + "8450a95e5214d199": "{host} отправил обновление конфигурации сервера, которое этот клиент не смог прочитать.", + "56b4ff3993c93eca": "{host} отправил несовместимую конфигурацию сервера.", + "368c4d4f99c66bfb": "Обновите клиент и сервер до совместимых версий.", "e5fd422e445391fc": "Ошибка загрузки. Нажмите, чтобы повторить.", "b2bc6bd92ea24e5c": "{size} МБ", "88f84178edbb7f57": "{size} КБ", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 6a3525acc8636..fb02753220b14 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} kunde inte upprätta en WebSocket-anslutning.", "d9ce6c142a485959": "{host} slutade svara i {seconds} s.", "d6bdce8f4e6101a4": "{host} kopplades från.", + "8450a95e5214d199": "{host} skickade en uppdatering av serverkonfigurationen som den här klienten inte kunde läsa.", + "56b4ff3993c93eca": "{host} skickade en inkompatibel serverkonfiguration.", + "368c4d4f99c66bfb": "Uppdatera klienten och servern till kompatibla versioner.", "e5fd422e445391fc": "Uppladdningen misslyckades. Tryck för att försöka igen.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} kB", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index af1ca50a064b3..04044302284b7 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} 无法建立 WebSocket 连接。", "d9ce6c142a485959": "{host} 已 {seconds} 秒无响应。", "d6bdce8f4e6101a4": "{host} 已断开连接。", + "8450a95e5214d199": "{host} 发送了此客户端无法读取的服务器配置更新。", + "56b4ff3993c93eca": "{host} 发送了不兼容的服务器配置。", + "368c4d4f99c66bfb": "请将客户端和服务器更新到兼容的版本。", "e5fd422e445391fc": "上传失败。点按以重试。", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", diff --git a/packages/client-runtime/src/rpc/session.test.ts b/packages/client-runtime/src/rpc/session.test.ts index 5882638af0c0c..ebd4780ba5064 100644 --- a/packages/client-runtime/src/rpc/session.test.ts +++ b/packages/client-runtime/src/rpc/session.test.ts @@ -291,6 +291,59 @@ const publishConfigEvents = Effect.fn("TestRpcSessionFactory.publishConfigEvents }); describe("RpcSessionFactory", () => { + it.effect.each([ + { established: false, closedWith: { _tag: "ConnectionBlockedError", reason: "unsupported" } }, + { + established: true, + closedWith: { _tag: "ConnectionTransientError", reason: "remote-unavailable" }, + }, + ])( + "ends the session when config fails to decode, after readiness=$established", + ({ established, closedWith }) => + Effect.gen(function* () { + const { factory, sockets } = yield* makeFactory(); + const session = yield* factory.connect(PREPARED); + const ready = yield* session.ready.pipe(Effect.exit, Effect.forkChild); + const socket = yield* awaitSocket(sockets); + socket.open(); + if (established) { + yield* completeInitialConfig(socket); + yield* Fiber.join(ready); + yield* completeInitialConfig(socket, { ...ENCODED_SERVER_CONFIG, cwd: 42 }); + } else { + yield* completeInitialConfig(socket, { ...ENCODED_SERVER_CONFIG, cwd: 42 }); + expect(yield* Fiber.join(ready)).toMatchObject({ + _tag: "Failure", + cause: { reasons: [{ _tag: "Fail", error: { reason: "unsupported" } }] }, + }); + } + + expect(yield* Effect.flip(session.closed)).toMatchObject({ ...closedWith, hop: "server" }); + }).pipe(Effect.scoped), + ); + + it.effect( + "fails readiness with the disconnect when the socket closes before its first config", + () => + Effect.gen(function* () { + const { factory, sockets } = yield* makeFactory(); + const session = yield* factory.connect(PREPARED); + const ready = yield* Effect.forkChild(Effect.flip(session.ready)); + const socket = yield* awaitSocket(sockets); + socket.open(); + yield* awaitRequest(socket); + socket.close(1012, "service restart"); + + for (const error of [yield* Fiber.join(ready), yield* Effect.flip(session.closed)]) { + expect(error).toMatchObject({ + _tag: "ConnectionTransientError", + reason: "transport", + detail: "Test environment disconnected.", + }); + } + }).pipe(Effect.scoped), + ); + it.effect("connects while a large config snapshot downloads at 4000 bytes per second", () => Effect.gen(function* () { const { factory, sockets } = yield* makeFactory(); @@ -822,6 +875,33 @@ describe("RpcSessionFactory", () => { }), ); + it.effect("closes the session when the server interrupts the config stream", () => + Effect.gen(function* () { + const { factory, sockets } = yield* makeFactory(); + const session = yield* factory.connect(PREPARED); + const readyFiber = yield* Effect.forkChild(session.ready); + const socket = yield* awaitSocket(sockets); + socket.open(); + yield* completeInitialConfig(socket); + yield* Fiber.join(readyFiber); + + const closedFiber = yield* Effect.forkChild(Effect.flip(session.closed)); + const request = yield* awaitRequest(socket); + socket.serverMessage( + encodeJson({ + _tag: "Exit", + requestId: request.id, + exit: { _tag: "Failure", cause: [{ _tag: "Interrupt", fiberId: null }] }, + }), + ); + + expect(yield* Fiber.join(closedFiber)).toMatchObject({ + reason: "remote-unavailable", + detail: "Test environment config subscription ended.", + }); + }), + ); + it.effect.each([{ failure: "defect" as const }, { failure: "typed" as const }])( "keeps durable config state alive after an owned $failure failure", ({ failure }) => diff --git a/packages/client-runtime/src/rpc/session.ts b/packages/client-runtime/src/rpc/session.ts index 409169ff1e345..91160a60941db 100644 --- a/packages/client-runtime/src/rpc/session.ts +++ b/packages/client-runtime/src/rpc/session.ts @@ -139,11 +139,14 @@ const isSocketErrorReason = Schema.is(Socket.SocketErrorReason); const PING_TIMEOUT_SECONDS = Duration.toSeconds(PING_TIMEOUT); function mapSessionRpcError( - error: InitialConfigError | ProbeError | ServerConfigSubscriptionError, - networkHint: string, + error: InitialConfigError | ProbeError | ServerConfigSubscriptionError | ConnectionAttemptError, via: "relay" | "direct", + socketFailure: () => ConnectionTransientError, ): ConnectionAttemptError { switch (error._tag) { + case "ConnectionBlockedError": + case "ConnectionTransientError": + return error; case "EnvironmentAuthorizationError": return new ConnectionBlockedError({ reason: "permission", @@ -160,11 +163,13 @@ function mapSessionRpcError( via, }); case "RpcClientError": - return new ConnectionTransientErrorClass({ - reason: "transport", - detail: `${error.message}${isSocketErrorReason(error.reason) ? networkHint : ""}`, - ...socketFailureLocation(via), - }); + return isSocketErrorReason(error.reason) + ? socketFailure() + : new ConnectionTransientErrorClass({ + reason: "transport", + detail: error.message, + ...socketFailureLocation(via), + }); } } @@ -194,47 +199,42 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( const connect = Effect.fnUntraced(function* (connection: PreparedConnection) { const via = connection.target._tag === "RelayConnectionTarget" ? "relay" : "direct"; - const networkHint = via === "relay" ? ` ${NETWORK_BLOCKING_HINT}` : ""; - const mapRpcError = (error: Parameters[0]) => - mapSessionRpcError(error, networkHint, via); yield* Effect.annotateCurrentSpan({ "connection.environment.id": connection.environmentId, }); const connected = yield* Deferred.make(); const disconnected = yield* Deferred.make(); - const pingTimedOut = yield* Ref.make(false); + let pingTimedOut = false; + const socketFailure = () => + new ConnectionTransientErrorClass({ + reason: "transport", + // The network hint only fits a socket that never opened. Once it + // opened, the path worked, and a host that goes quiet is more + // often overloaded or asleep than blocked. + ...(!Deferred.isDoneUnsafe(connected) + ? translatableDetail( + msg("{host} could not establish a WebSocket connection.", { + host: connection.label, + }), + ...(via === "relay" ? [NETWORK_BLOCKING_HINT] : []), + ) + : pingTimedOut + ? translatableDetail( + msg("{host} stopped responding for {seconds}s.", { + host: connection.label, + seconds: String(PING_TIMEOUT_SECONDS), + }), + UNRESPONSIVE_HOST_HINT, + ) + : translatableDetail(msg("{host} disconnected.", { host: connection.label }))), + ...socketFailureLocation(via), + }); + const mapRpcError = (error: Parameters[0]) => + mapSessionRpcError(error, via, socketFailure); const hooks = RpcClient.ConnectionHooks.of({ onConnect: Deferred.succeed(connected, undefined).pipe(Effect.asVoid), - onDisconnect: Effect.all([Deferred.isDone(connected), Ref.get(pingTimedOut)]).pipe( - Effect.flatMap(([wasConnected, timedOut]) => - Deferred.fail( - disconnected, - new ConnectionTransientErrorClass({ - reason: "transport", - // The network hint only fits a socket that never opened. Once it - // opened, the path worked, and a host that goes quiet is more - // often overloaded or asleep than blocked. - ...(!wasConnected - ? translatableDetail( - msg("{host} could not establish a WebSocket connection.", { - host: connection.label, - }), - ...(via === "relay" ? [NETWORK_BLOCKING_HINT] : []), - ) - : timedOut - ? translatableDetail( - msg("{host} stopped responding for {seconds}s.", { - host: connection.label, - seconds: String(PING_TIMEOUT_SECONDS), - }), - UNRESPONSIVE_HOST_HINT, - ) - : translatableDetail(msg("{host} disconnected.", { host: connection.label }))), - ...socketFailureLocation(via), - }), - ), - ), + onDisconnect: Effect.suspend(() => Deferred.fail(disconnected, socketFailure())).pipe( Effect.asVoid, ), }); @@ -267,7 +267,10 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( pingTimeout: PING_TIMEOUT, retryTransientErrors: false, retryPolicy: Schedule.recurs(0), - onPingTimeout: Ref.set(pingTimedOut, true), + // RpcClient runs this before it fails the open requests. + onPingTimeout: Effect.sync(() => { + pingTimedOut = true; + }), }).pipe( // Teardown sends an interrupt per open stream, and a write to a closed // socket waits out the client's 1s interrupt timeout before reconnecting. @@ -302,7 +305,10 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( ); const protocolClient = yield* makeWsRpcProtocolClient.pipe(Effect.provide(protocolContext)); const initialConfigDeferred = yield* Deferred.make(); - const serverConfigExit = yield* Deferred.make(); + const serverConfigExit = yield* Deferred.make< + void, + ServerConfigSubscriptionError | ConnectionAttemptError + >(); const configSubscriptionClosed = yield* Deferred.make(); const serverConfigState = yield* Ref.make(Option.none()); const serverConfigUpdates = yield* PubSub.sliding(64); @@ -310,6 +316,8 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( reason: "remote-unavailable", detail: `${connection.label} config subscription ended.`, }); + // An interrupt while the session is not closing came from the server; it ends the subscription. + let closingSession = false; const configRequestedAtMs = yield* Clock.currentTimeMillis; const serverConfigSource = protocolClient[WS_METHODS.subscribeServerConfig]( onDemandSnapshots(serverConfigInput), @@ -362,8 +370,46 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( } }), ), + // An unreadable first snapshot means the versions are incompatible. A later + // unreadable update ends the session, and the reconnect's snapshot decides. + Effect.catchDefect((defect) => + Schema.isSchemaError(defect) + ? Effect.logWarning("Server configuration failed to decode.", { + environmentId: connection.environmentId, + issue: defect.message, + }).pipe( + Effect.andThen( + Effect.fail( + Deferred.isDoneUnsafe(initialConfigDeferred) + ? new ConnectionTransientErrorClass({ + reason: "remote-unavailable", + ...translatableDetail( + msg( + "{host} sent a server configuration update this client could not read.", + { host: connection.label }, + ), + ), + hop: "server", + via, + }) + : new ConnectionBlockedError({ + reason: "unsupported", + ...translatableDetail( + msg("{host} sent an incompatible server configuration.", { + host: connection.label, + }), + msg("Update the client and server to compatible versions."), + ), + hop: "server", + via, + }), + ), + ), + ) + : Effect.die(defect), + ), Effect.onExit((exit) => { - if (Exit.isSuccess(exit)) { + if (Exit.isSuccess(exit) || (Cause.hasInterruptsOnly(exit.cause) && !closingSession)) { return Effect.all([ Deferred.succeed(serverConfigExit, undefined), Deferred.fail(configSubscriptionClosed, configSubscriptionEndedError), @@ -379,6 +425,12 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( }), ); yield* serverConfigSource.pipe(Effect.forkScoped); + // Finalizers run in reverse, so this is set before the fork above is interrupted. + yield* Effect.addFinalizer(() => + Effect.sync(() => { + closingSession = true; + }), + ); const initialConfig = Effect.raceFirst( Deferred.await(initialConfigDeferred), Deferred.await(serverConfigExit).pipe( @@ -424,7 +476,9 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( ).pipe( Stream.catchCause((cause) => { if (Cause.hasInterruptsOnly(cause)) { - return Stream.failCause(cause); + return Stream.failCause( + Cause.fromReasons(cause.reasons.filter(Cause.isInterruptReason)), + ); } // The supervisor keeps the original cause. Shared durable consumers // need a transport-shaped failure so they wait for its replacement. @@ -471,17 +525,11 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( client: protocolClient, initialConfig, subscribeServerConfig, - ready: Deferred.await(connected).pipe( - Effect.andThen(initialConfig), - Effect.asVoid, - Effect.raceFirst(Deferred.await(disconnected)), - ), + ready: initialConfig.pipe(Effect.asVoid), probe, inboundFrames: Effect.sync(() => inboundFrames), - closed: Effect.raceFirst( - Deferred.await(disconnected), - Deferred.await(configSubscriptionClosed), - ), + // The config stream also fails on disconnect, and only it can report a decode failure. + closed: Deferred.await(configSubscriptionClosed), } satisfies RpcSession; }); From 620cf4770d992d642f822a13dc2539c2605a3500 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 05:38:38 -0800 Subject: [PATCH 169/324] fix(web): browser page translation no longer crashes the app when a turn updates (#40856) --- apps/web/src/appInit.tsx | 2 + .../lib/pageTranslationGuard.browser.test.tsx | 42 +++++++++++++++++++ apps/web/src/lib/pageTranslationGuard.ts | 20 +++++++++ 3 files changed, 64 insertions(+) create mode 100644 apps/web/src/lib/pageTranslationGuard.browser.test.tsx create mode 100644 apps/web/src/lib/pageTranslationGuard.ts diff --git a/apps/web/src/appInit.tsx b/apps/web/src/appInit.tsx index ae8e685c5c9ec..cce59f08f6d12 100644 --- a/apps/web/src/appInit.tsx +++ b/apps/web/src/appInit.tsx @@ -62,6 +62,7 @@ import { installChatRouteCommands } from "./shortcuts/chatRouteCommands"; import { startWorkspaceFocus } from "./lib/workspaceFocus"; import { m } from "./i18n/messages"; import { startI18n, subscribeI18n } from "./i18n/runtime"; +import { guardDomAgainstPageTranslation } from "./lib/pageTranslationGuard"; import { installCommandPaletteCommands } from "./shortcuts/commandPaletteCommands"; import { registerOpenFavoriteEditorCommand } from "./components/chat/OpenInPickerShortcut"; import { environmentThreadShells, threadEnvironment } from "./state/threads"; @@ -267,6 +268,7 @@ export function startAppServices(): AppRouter { } installDesktopPasteAsText(window.desktopBridge, window); + guardDomAgainstPageTranslation(); startClientAppearance(); startI18n(); diff --git a/apps/web/src/lib/pageTranslationGuard.browser.test.tsx b/apps/web/src/lib/pageTranslationGuard.browser.test.tsx new file mode 100644 index 0000000000000..40d7e7597ccf8 --- /dev/null +++ b/apps/web/src/lib/pageTranslationGuard.browser.test.tsx @@ -0,0 +1,42 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { render } from "../../test/render"; +import { guardDomAgainstPageTranslation } from "./pageTranslationGuard"; + +// What Chrome's page translator does: swap each text node for translation. +function translatePage(root: Element) { + const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT); + const textNodes: Text[] = []; + while (walker.nextNode()) textNodes.push(walker.currentNode as Text); + for (const text of textNodes) { + if (!text.nodeValue?.trim()) continue; + const outer = document.createElement("font"); + const inner = document.createElement("font"); + inner.textContent = `译:${text.nodeValue}`; + outer.append(inner); + text.replaceWith(outer); + } +} + +function Status({ running }: { running: boolean }) { + return ( +
    + {running ? "Working" : } + {"for 2s"} +
    + ); +} + +describe("guardDomAgainstPageTranslation", () => { + it("keeps React committing after page translation replaced its text nodes", async () => { + guardDomAgainstPageTranslation(); + await using screen = await render(, { router: false }); + translatePage(screen.container); + + // Removing "Working" hits removeChild; placing the icon before "for 2s" hits insertBefore. + await screen.rerender(); + await expect.element(screen.getByTestId("done")).toBeInTheDocument(); + await screen.rerender(); + await expect.element(screen.getByTestId("done")).not.toBeInTheDocument(); + }); +}); diff --git a/apps/web/src/lib/pageTranslationGuard.ts b/apps/web/src/lib/pageTranslationGuard.ts new file mode 100644 index 0000000000000..de8dbceb8e2bf --- /dev/null +++ b/apps/web/src/lib/pageTranslationGuard.ts @@ -0,0 +1,20 @@ +// Browser page translation (Chrome, Edge) swaps text nodes for wrappers React does not +// know about, so a later removeChild or insertBefore on the original node throws NotFoundError +// and takes down the whole tree. See facebook/react#11538. +export function guardDomAgainstPageTranslation(): void { + const proto = Node.prototype; + const removeChild = proto.removeChild; + const insertBefore = proto.insertBefore; + + proto.removeChild = function (this: Node, child: T): T { + // Already detached by the translator: nothing left to remove. + if (child.parentNode !== this) return child; + return removeChild.call(this, child) as T; + }; + + proto.insertBefore = function (this: Node, node: T, reference: Node | null): T { + // The anchor was replaced; append so the new node still shows. + const anchor = reference && reference.parentNode !== this ? null : reference; + return insertBefore.call(this, node, anchor) as T; + }; +} From 30372d0fade8903b4cd6c544768333fc7588fd37 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Sun, 22 Nov 2026 06:13:03 -0800 Subject: [PATCH 170/324] perf(mobile): keep image bytes outside draft JSON (#9727) Co-authored-by: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../review/ReviewCommentComposerSheet.tsx | 70 +++++++--- .../sharing/incoming-share-model.test.ts | 118 ++++++++++++++++- .../features/sharing/incoming-share-model.ts | 55 +++++--- apps/mobile/src/lib/composerFiles.test.ts | 81 +++++++----- apps/mobile/src/lib/composerImages.test.ts | 24 ++-- apps/mobile/src/lib/composerImages.ts | 122 +++++++++++------- apps/mobile/src/state/thread-outbox-model.ts | 6 +- .../src/state/use-composer-drafts.test.ts | 22 +++- apps/mobile/src/state/use-composer-drafts.ts | 4 +- 9 files changed, 368 insertions(+), 134 deletions(-) diff --git a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx index db2e7169d4930..881f67e86648f 100644 --- a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx +++ b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx @@ -2,7 +2,7 @@ import { useNavigation, type StaticScreenProps } from "@react-navigation/native" import { TextInputWrapper } from "expo-paste-input"; import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { T, useGT } from "gt-react-native"; -import { useMemo, useState } from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; import { ScrollView, View, useWindowDimensions } from "react-native"; import * as Dialog from "../../components/ui/Dialog"; import { FilePreviewModal, type FilePreviewSource } from "../../components/ui/FilePreviewModal"; @@ -16,6 +16,7 @@ import { cn } from "../../lib/cn"; import type { DraftComposerImageAttachment } from "../../lib/composerImages"; import { convertPastedImagesToAttachments, pickComposerImages } from "../../lib/composerImages"; import { useNativePaste } from "../../lib/useNativePaste"; +import { scheduleUnusedComposerAttachmentCleanup } from "../../state/use-composer-drafts"; import { setPendingConnectionError } from "../../state/use-remote-environment-registry"; import { appendReviewCommentToDraft } from "../../state/use-thread-composer-state"; import { @@ -49,6 +50,31 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp const { environmentId, threadId } = props.route.params; const [commentText, setCommentText] = useState(""); const [attachments, setAttachments] = useState>([]); + const attachmentsRef = useRef(attachments); + const isMountedRef = useRef(true); + // Store file references before React commits, so closing the sheet can release them. + const replaceAttachments = (next: ReadonlyArray) => { + attachmentsRef.current = next; + setAttachments(next); + }; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- releases owned image files when the sheet unmounts + useEffect(() => { + isMountedRef.current = true; + return () => { + isMountedRef.current = false; + scheduleUnusedComposerAttachmentCleanup(attachmentsRef.current); + }; + }, []); + + function appendImages(images: ReadonlyArray): void { + if (!isMountedRef.current) { + scheduleUnusedComposerAttachmentCleanup(images); + return; + } + if (images.length > 0) { + replaceAttachments([...attachmentsRef.current, ...images]); + } + } const [previewFile, setPreviewFile] = useState(null); const { selectedLines, highlightedLinesById } = useMemo(() => { @@ -90,27 +116,25 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp }; const handleNativePaste = useNativePaste((uris) => { void (async () => { - try { - const result = await convertPastedImagesToAttachments({ - uris, - existingCount: attachments.length, - }); - if (result.attachments.length > 0) { - setAttachments((current) => [...current, ...result.attachments]); - } - if (result.error) Dialog.alert(gt("Could not paste image"), result.error); - } catch (error) { + const result = await convertPastedImagesToAttachments({ + uris, + existingCount: attachmentsRef.current.length, + }).catch((error: unknown) => { console.error("[review comment] error converting pasted images", error); + return null; + }); + if (result === null) return; + appendImages(result.attachments); + if (result.error && isMountedRef.current) { + Dialog.alert(gt("Could not paste image"), result.error); } })(); }); async function handlePickImages(): Promise { - const result = await pickComposerImages({ existingCount: attachments.length }); - if (result.images.length > 0) { - setAttachments((current) => [...current, ...result.images]); - } - if (result.error) { + const result = await pickComposerImages({ existingCount: attachmentsRef.current.length }); + appendImages(result.images); + if (result.error && isMountedRef.current) { setPendingConnectionError(result.error); } } @@ -124,9 +148,10 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp environmentId, threadId, text: formatReviewCommentContext(target, commentText), - attachments, + attachments: attachmentsRef.current, }); - setAttachments([]); + scheduleUnusedComposerAttachmentCleanup(attachmentsRef.current); + replaceAttachments([]); dismissComposer(); }; @@ -255,9 +280,12 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp onPressPreview={setPreviewFile} removeButtonPlacement="gutter" onRemove={(imageId) => { - setAttachments((current) => - current.filter((image) => image.id !== imageId), - ); + const current = attachmentsRef.current; + const removed = current.find((image) => image.id === imageId); + replaceAttachments(current.filter((image) => image.id !== imageId)); + if (removed) { + scheduleUnusedComposerAttachmentCleanup([removed]); + } }} /> diff --git a/apps/mobile/src/features/sharing/incoming-share-model.test.ts b/apps/mobile/src/features/sharing/incoming-share-model.test.ts index 1dea547de53b4..7ca92b23c3208 100644 --- a/apps/mobile/src/features/sharing/incoming-share-model.test.ts +++ b/apps/mobile/src/features/sharing/incoming-share-model.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it, vi } from "@effect/vitest"; +import { describe, expect, it, vi } from "vite-plus/test"; import { PROVIDER_SEND_TURN_MAX_ATTACHMENTS, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, @@ -13,6 +13,32 @@ import { selectIncomingShareAttachmentsForServer, } from "./incoming-share-model"; +const nativeImage = vi.hoisted(() => ({ + resize: vi.fn(), +})); + +vi.mock("expo-image-manipulator", () => ({ + SaveFormat: { PNG: "png", JPEG: "jpeg" }, + ImageManipulator: { + manipulate: (source: string | { width: number; height: number }) => { + let size = typeof source === "string" ? { width: 3000, height: 1500 } : source; + const context = { + resize: (next: { width: number; height: number }) => { + nativeImage.resize(next); + size = next; + return context; + }, + renderAsync: async () => ({ + ...size, + release: () => {}, + saveAsync: async () => ({ uri: "file:///cache/resized.png", base64: "YWJj" }), + }), + }; + return context; + }, + }, +})); + describe("incoming native shares", () => { it("converts shared text, URLs, and images into a durable composer draft", async () => { const image: SharePayload = { @@ -35,6 +61,9 @@ describe("incoming native shares", () => { originalName: "Screenshot.png", }; const removeOwnedFile = vi.fn(() => Promise.resolve()); + const readBase64 = vi.fn(async () => "YWJj"); + const persistedUri = "file:///documents/t3-composer-attachments/Screenshot.png"; + const persistFile = vi.fn(async () => persistedUri); const result = await buildIncomingShareDraft({ id: "share-1", @@ -42,7 +71,9 @@ describe("incoming native shares", () => { payloads, resolvedPayloads: [resolvedImage], fileReader: { - readBase64: async () => "YWJj", + readBase64, + persistFile, + readSize: async (uri) => (uri === persistedUri ? 3 : null), removeOwnedFile, }, }); @@ -59,16 +90,95 @@ describe("incoming native shares", () => { name: "Screenshot.png", mimeType: "image/png", sizeBytes: 3, - dataUrl: "data:image/png;base64,YWJj", - previewUri: "data:image/png;base64,YWJj", + fileUri: persistedUri, + previewUri: persistedUri, }, ], warnings: [], }); expect(removeOwnedFile).toHaveBeenCalledWith(image.value); + expect(removeOwnedFile).not.toHaveBeenCalledWith(persistedUri); expect(hasIncomingShareContent(result)).toBe(true); }); + it("persists the resized PNG for a shared image over 2000px", async () => { + const header = Buffer.alloc(24); + header.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); + header.set([0x49, 0x48, 0x44, 0x52], 12); + header.writeUInt32BE(3000, 16); + header.writeUInt32BE(1500, 20); + const persistedUri = "file:///documents/t3-composer-attachments/screenshot.png"; + const persistFile = vi.fn(async () => persistedUri); + const removeOwnedFile = vi.fn(async (_uri: string) => undefined); + + const draft = await buildIncomingShareDraft({ + id: "share-resize", + createdAt: "2026-07-15T10:00:00.000Z", + payloads: [ + { shareType: "image", value: "content://shared/screenshot", mimeType: "image/png" }, + ], + resolvedPayloads: [], + fileReader: { + readBase64: async () => header.toString("base64"), + persistFile, + readSize: async () => 3, + removeOwnedFile, + }, + }); + + expect(nativeImage.resize).toHaveBeenCalledWith({ width: 2000, height: 1000 }); + expect(persistFile).toHaveBeenCalledWith("file:///cache/resized.png", "screenshot"); + expect(draft.attachments).toEqual([ + { + id: "share-resize-image-0", + type: "image", + name: "screenshot", + mimeType: "image/png", + sizeBytes: 3, + fileUri: persistedUri, + previewUri: persistedUri, + }, + ]); + expect(draft.warnings).toEqual([]); + expect(removeOwnedFile).not.toHaveBeenCalledWith(persistedUri); + }); + + it("releases a shared image when its stored size cannot be measured", async () => { + const image: SharePayload = { + shareType: "image", + value: "file:///shared/photo.png", + mimeType: "image/png", + }; + const persistedUri = "file:///documents/t3-composer-attachments/photo.png"; + const removeOwnedFile = vi.fn(async (_uri: string) => undefined); + const result = await buildIncomingShareDraft({ + id: "share-unmeasured", + createdAt: "2026-07-15T10:00:00.000Z", + payloads: [image], + resolvedPayloads: [ + { + ...image, + contentUri: image.value, + contentType: "image", + contentMimeType: "image/png", + contentSize: 3, + originalName: "photo.png", + }, + ], + fileReader: { + readBase64: async () => "unused", + persistFile: async () => persistedUri, + readSize: async () => null, + removeOwnedFile, + }, + }); + + expect(result.attachments).toEqual([]); + expect(result.warnings).toEqual(["'photo.png' is empty or could not be read."]); + expect(removeOwnedFile).toHaveBeenCalledWith(persistedUri); + expect(removeOwnedFile).toHaveBeenCalledWith(image.value); + }); + it("skips oversized images and releases the temporary native file", async () => { const image: SharePayload = { shareType: "image", diff --git a/apps/mobile/src/features/sharing/incoming-share-model.ts b/apps/mobile/src/features/sharing/incoming-share-model.ts index 9bfc2dcca1b29..86c17c6059e0e 100644 --- a/apps/mobile/src/features/sharing/incoming-share-model.ts +++ b/apps/mobile/src/features/sharing/incoming-share-model.ts @@ -412,6 +412,9 @@ export async function buildIncomingShareDraft(input: { continue; } + const name = resolved?.originalName ?? fallbackName(uri, index, mimeType); + let persistedImageUri: string | undefined; + let retainedImageUri: string | undefined; try { const sharedBase64 = await input.fileReader.readBase64(uri); // Use already-read bytes because native image loaders may not read the provider's file. @@ -421,36 +424,54 @@ export async function buildIncomingShareDraft(input: { base64: sharedBase64, }); const base64 = fitted?.base64 ?? sharedBase64; - const sizeBytes = fitted - ? estimateBase64ByteSize(base64) - : (resolved?.contentSize ?? estimateBase64ByteSize(base64)); - if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) { - warnings.push( - m( - msg("''{name}'' exceeds the 10 MB attachment limit.", { - name: resolved?.originalName ?? fallbackName(uri, index, mimeType), - }), - ), - ); + const decodedSize = estimateBase64ByteSize(base64); + if (decodedSize <= 0 || decodedSize > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) { + warnings.push(m(msg("''{name}'' exceeds the 10 MB attachment limit.", { name }))); + continue; + } + if (input.fileReader.persistFile) { + persistedImageUri = await input.fileReader.persistFile(fitted?.uri ?? uri, name); + const sizeBytes = (await input.fileReader.readSize?.(persistedImageUri)) ?? null; + if (sizeBytes === null || sizeBytes <= 0) { + warnings.push(m(msg("''{name}'' is empty or could not be read.", { name }))); + continue; + } + if (sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) { + warnings.push(fileAttachmentTooLargeMessage(name, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, m)); + continue; + } + attachments.push({ + id: `${input.id}-image-${index}`, + type: "image", + name, + mimeType, + sizeBytes, + fileUri: persistedImageUri, + previewUri: persistedImageUri, + }); + retainedImageUri = persistedImageUri; continue; } const dataUrl = `data:${mimeType};base64,${base64}`; attachments.push({ id: `${input.id}-image-${index}`, type: "image", - name: resolved?.originalName ?? fallbackName(uri, index, mimeType), + name, mimeType, - sizeBytes, + sizeBytes: decodedSize, dataUrl, // Data-backed previews outlive temporary share files and App Group entries. previewUri: dataUrl, }); } catch { - warnings.push( - m(msg("Could not read ''{name}''.", { name: fallbackName(uri, index, mimeType) })), - ); + warnings.push(m(msg("Could not read ''{name}''.", { name }))); } finally { - await releaseOwnedFiles(input.fileReader, [uri, payload.value]); + await releaseOwnedFiles( + input.fileReader, + [uri, payload.value, persistedImageUri].filter( + (candidate) => candidate !== retainedImageUri, + ), + ); } } diff --git a/apps/mobile/src/lib/composerFiles.test.ts b/apps/mobile/src/lib/composerFiles.test.ts index bdcd35c36ff75..73f0af20fcc00 100644 --- a/apps/mobile/src/lib/composerFiles.test.ts +++ b/apps/mobile/src/lib/composerFiles.test.ts @@ -2,6 +2,9 @@ import { beforeEach, describe, expect, it, vi } from "vite-plus/test"; import { PROVIDER_SEND_TURN_MAX_IMAGE_BYTES } from "@t3tools/contracts"; import type { ImagePickerAsset } from "expo-image-picker"; +// Bytes of image files the tests create, so stored attachments can be read back and measured. +const imageFiles = new Map(); + const mocks = vi.hoisted(() => ({ documentUri: "file:///documents", pickFile: vi.fn(), @@ -57,6 +60,8 @@ vi.mock("expo-file-system", () => { async copy(destination: File): Promise { mocks.copy(this.uri, destination.uri); + const bytes = imageFiles.get(this.uri); + if (bytes !== undefined) imageFiles.set(destination.uri, bytes); } async base64(): Promise { @@ -99,6 +104,16 @@ import { import { isForegroundHandoffActive } from "./foreground-handoff"; import { retainComposerAttachmentFile } from "./composerAttachmentFiles"; +const STORED = "file:///documents/t3-composer-attachments/attachment-id"; + +function sizeOtherFilesAs(bytes: number): void { + mocks.size.mockImplementation((uri: string) => { + if (uri.startsWith("content:")) return null; + const stored = imageFiles.get(uri); + return stored === undefined ? bytes : Buffer.from(stored, "base64").byteLength; + }); +} + describe("composer file attachments", () => { beforeEach(() => { mocks.documentUri = "file:///documents"; @@ -110,7 +125,8 @@ describe("composer file attachments", () => { mocks.size.mockReset(); mocks.readBase64.mockReset(); mocks.manipulate.mockReset(); - mocks.size.mockImplementation((uri: string) => (uri.startsWith("content:") ? null : 42)); + imageFiles.clear(); + sizeOtherFilesAs(42); }); describe("photo library image conversion", () => { @@ -151,8 +167,11 @@ describe("composer file attachments", () => { width: size.width, height: size.height, release: mocks.release, - saveAsync: async (options: { format: string }) => - native.encode?.(size, options.format) ?? native.saved, + saveAsync: async (options: { format: string }) => { + const saved = native.encode?.(size, options.format) ?? native.saved; + if (saved.base64 !== undefined) imageFiles.set(saved.uri, saved.base64); + return saved; + }, }), }; return context; @@ -160,7 +179,7 @@ describe("composer file attachments", () => { }); it.each(["image/heic", "image/heif", undefined])( - "renders a %s photo to JPEG natively and previews the rendered file", + "renders a %s photo to JPEG natively and stores it in an owned file", async (mimeType) => { mocks.pickMedia.mockResolvedValue({ canceled: false, @@ -180,8 +199,8 @@ describe("composer file attachments", () => { name: "photo.jpg", mimeType: "image/jpeg", sizeBytes: 4, - dataUrl: `data:image/jpeg;base64,${rendered.base64}`, - previewUri: rendered.uri, + fileUri: `${STORED}-photo.jpg`, + previewUri: `${STORED}-photo.jpg`, }, ], error: null, @@ -200,6 +219,7 @@ describe("composer file attachments", () => { assets: [{ ...photo, fileName: name, mimeType: original.mimeType }], }); mocks.readBase64.mockResolvedValue(original.base64); + imageFiles.set(photo.uri, original.base64); const result = await pickComposerImages({ existingCount: 0 }); @@ -210,11 +230,12 @@ describe("composer file attachments", () => { expect.objectContaining({ name, mimeType: original.mimeType, - dataUrl: `data:${original.mimeType};base64,${original.base64}`, + fileUri: `${STORED}-${name}`, sizeBytes: Buffer.from(original.base64, "base64").byteLength, - previewUri: photo.uri, }), ]); + expect(result.images[0]).not.toHaveProperty("dataUrl"); + expect(imageFiles.get(`${STORED}-${name}`)).toBe(original.base64); }); it("shrinks a fitted PNG further when re-encoding it exceeds the image limit", async () => { @@ -229,7 +250,7 @@ describe("composer file attachments", () => { uri: `file:///cache/fitted-${size.width}x${size.height}.${format}`, base64: Buffer.alloc(size.width * size.height * 4).toString("base64"), }); - mocks.size.mockReturnValue(7 * 1024 * 1024); + sizeOtherFilesAs(7 * 1024 * 1024); mocks.readBase64.mockResolvedValue(header.toString("base64")); mocks.pickMedia.mockResolvedValue({ canceled: false, @@ -248,12 +269,14 @@ describe("composer file attachments", () => { name: "IMG_9280.png", mimeType: "image/png", sizeBytes: last.width * last.height * 4, - previewUri: `file:///cache/fitted-${last.width}x${last.height}.png`, + fileUri: `${STORED}-IMG_9280.png`, }), ); expect(image!.sizeBytes).toBeLessThanOrEqual(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES); expect(mocks.delete).toHaveBeenCalledWith("file:///cache/fitted-1397x2000.png"); - expect(mocks.delete).not.toHaveBeenCalledWith(image!.previewUri); + expect(imageFiles.get(image!.previewUri)).toBe( + Buffer.alloc(last.width * last.height * 4).toString("base64"), + ); }); it("measures the picker file instead of trusting the reported size", async () => { @@ -261,7 +284,7 @@ describe("composer file attachments", () => { canceled: false, assets: [{ ...photo, fileName: "photo.png", mimeType: "image/png", fileSize: 42 }], }); - mocks.size.mockReturnValue(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1); + sizeOtherFilesAs(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1); const result = await pickComposerImages({ existingCount: 0 }); @@ -372,7 +395,7 @@ describe("composer file attachments", () => { ); expect(result).toEqual({ attachments: [ - expect.objectContaining({ type: "image", dataUrl: "data:image/png;base64,YWJj" }), + expect.objectContaining({ type: "image", fileUri: `${STORED}-photo.png` }), { id: "attachment-id", type: "file", @@ -398,7 +421,7 @@ describe("composer file attachments", () => { expect(result.attachments).toEqual([expect.objectContaining({ type: "image" })]); expect(result.error).toBe("Video attachments are unavailable here."); - expect(mocks.copy).not.toHaveBeenCalled(); + expect(mocks.copy).not.toHaveBeenCalledWith(video.uri, expect.anything()); }); it("uses local video metadata when the picker omits its name, MIME type, or size", async () => { @@ -476,7 +499,7 @@ describe("composer file attachments", () => { expect(result.attachments).toEqual([expect.objectContaining({ type: "image" })]); expect(result.error).toBe("You can attach up to 100 attachments per message."); expect(mocks.pickMedia).toHaveBeenCalledWith(expect.objectContaining({ selectionLimit: 1 })); - expect(mocks.copy).not.toHaveBeenCalled(); + expect(mocks.copy).not.toHaveBeenCalledWith(video.uri, expect.anything()); }); it("reports a native video retrieval error and ends the foreground handoff", async () => { @@ -506,7 +529,7 @@ describe("composer file attachments", () => { canceled: false, assets: [{ uri: `file:///picker/${name}`, name, mimeType, size: 3 }], }); - mocks.size.mockReturnValue(3); + sizeOtherFilesAs(3); mocks.readBase64.mockResolvedValue("YWJj"); const result = await pickComposerFiles({ existingCount: 0 }); @@ -519,16 +542,14 @@ describe("composer file attachments", () => { name, mimeType: expected, sizeBytes: 3, - dataUrl: `data:${expected};base64,YWJj`, - previewUri: `data:${expected};base64,YWJj`, + fileUri: `${STORED}-${name}`, + previewUri: `${STORED}-${name}`, }, ], error: null, }); expect(mocks.manipulate).not.toHaveBeenCalled(); - expect(mocks.delete).toHaveBeenCalledWith( - `file:///documents/t3-composer-attachments/attachment-id-${name}`, - ); + expect(mocks.delete).not.toHaveBeenCalled(); }); it.each([ @@ -590,17 +611,19 @@ describe("composer file attachments", () => { header.writeUInt32BE(3000, 20); const original = header.toString("base64"); mocks.readBase64.mockResolvedValue(original); + imageFiles.set("file:///picker/photo.png", original); const resize = vi.fn(); const renderAsync = vi.fn(async () => ({ width: 4000, height: 3000, release: vi.fn(), - saveAsync: vi.fn(async () => ({ - uri: "file:///cache/fitted.png", - base64: oversized + saveAsync: vi.fn(async () => { + const base64 = oversized ? Buffer.alloc(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1).toString("base64") - : "YWJj", - })), + : "YWJj"; + imageFiles.set("file:///cache/fitted.png", base64); + return { uri: "file:///cache/fitted.png", base64 }; + }), })); mocks.manipulate.mockImplementation(() => { const context = { @@ -626,14 +649,12 @@ describe("composer file attachments", () => { type: "image", mimeType: "image/png", sizeBytes: oversized ? header.length : 3, - dataUrl: `data:image/png;base64,${oversized ? original : "YWJj"}`, - previewUri: oversized - ? `data:image/png;base64,${original}` - : "file:///cache/fitted.png", + fileUri: `${STORED}-photo.png`, }), ], error: null, }); + expect(imageFiles.get(`${STORED}-photo.png`)).toBe(oversized ? original : "YWJj"); }); it("releases the owned copy when reading an image fails", async () => { diff --git a/apps/mobile/src/lib/composerImages.test.ts b/apps/mobile/src/lib/composerImages.test.ts index d7830b8ed3466..de05411a8f327 100644 --- a/apps/mobile/src/lib/composerImages.test.ts +++ b/apps/mobile/src/lib/composerImages.test.ts @@ -122,6 +122,8 @@ vi.mock("./uuid", () => ({ import { convertPastedImagesToAttachments, persistComposerAttachmentFile } from "./composerImages"; +const STORED = "file:///documents/t3-composer-attachments/attachment-id"; + function oversizedPng(): string { const png = Buffer.alloc(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1); Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).copy(png); @@ -150,10 +152,12 @@ describe("native pasted image cleanup", () => { expect.objectContaining({ name: "pasted-image.jpeg", mimeType: "image/jpeg", - dataUrl: "data:image/jpeg;base64,aGVsbG8=", - previewUri: "data:image/jpeg;base64,aGVsbG8=", + fileUri: `${STORED}-pasted-image.jpeg`, + previewUri: `${STORED}-pasted-image.jpeg`, }), ]); + expect(attachments[0]).not.toHaveProperty("dataUrl"); + expect(files.get(`${STORED}-pasted-image.jpeg`)?.base64).toBe("aGVsbG8="); expect(files.get(uri)?.deleted).toBe(false); }); @@ -171,10 +175,10 @@ describe("native pasted image cleanup", () => { expect.objectContaining({ name: "pasted-image.jpeg", mimeType: "image/jpeg", - dataUrl: "data:image/jpeg;base64,cmVuZGVyZWQ=", - previewUri: "data:image/jpeg;base64,cmVuZGVyZWQ=", + fileUri: `${STORED}-pasted-image.jpeg`, }), ]); + expect(files.get(`${STORED}-pasted-image.jpeg`)?.base64).toBe("cmVuZGVyZWQ="); expect(files.get("file:///cache/rendered.jpeg")?.deleted).toBe(true); expect(files.get(uri)?.deleted).toBe(false); }); @@ -197,7 +201,7 @@ describe("native pasted image cleanup", () => { expect(files.get(uri)?.deleted).toBe(false); }); - it("converts owned files to data-backed previews and deletes the source", async () => { + it("stores owned pastes in an attachment file and deletes the source", async () => { const uri = "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/id.png"; const gif = @@ -212,11 +216,13 @@ describe("native pasted image cleanup", () => { expect(attachments).toEqual([ expect.objectContaining({ - dataUrl: "data:image/png;base64,aGVsbG8=", - previewUri: "data:image/png;base64,aGVsbG8=", + fileUri: `${STORED}-pasted-image.png`, + previewUri: `${STORED}-pasted-image.png`, }), - expect.objectContaining({ mimeType: "image/gif", dataUrl: "data:image/gif;base64,R0lGODlh" }), + expect.objectContaining({ mimeType: "image/gif", fileUri: `${STORED}-pasted-image.gif` }), ]); + expect(files.get(`${STORED}-pasted-image.png`)?.base64).toBe("aGVsbG8="); + expect(files.get(`${STORED}-pasted-image.gif`)?.base64).toBe("R0lGODlh"); expect(files.get(uri)?.deleted).toBe(true); expect(files.get(gif)?.deleted).toBe(true); }); @@ -267,7 +273,7 @@ describe("native pasted image cleanup", () => { const result = await convertPastedImagesToAttachments({ uris: [gone, kept], existingCount: 0 }); expect(result.attachments).toEqual([ - expect.objectContaining({ dataUrl: "data:image/png;base64,aGVsbG8=" }), + expect.objectContaining({ fileUri: `${STORED}-pasted-image.png` }), ]); expect(result.error).toBe("Could not read a pasted image."); }); diff --git a/apps/mobile/src/lib/composerImages.ts b/apps/mobile/src/lib/composerImages.ts index 69f26103134b9..4c81024c1d403 100644 --- a/apps/mobile/src/lib/composerImages.ts +++ b/apps/mobile/src/lib/composerImages.ts @@ -124,7 +124,7 @@ export function isFileBackedComposerAttachment( return attachment.fileUri !== undefined; } -/** Inline library/clipboard images own no file; local ids cannot resolve server assets. */ +/** Legacy inline images have only a local draft id, so a remote asset lookup cannot load them. */ export function composerAttachmentInlineUri( attachment: DraftComposerAttachment | undefined, ): string | undefined { @@ -135,6 +135,11 @@ export function composerAttachmentInlineUri( const OWNED_PASTED_IMAGE_DIRECTORY = "t3-composer-paste"; const ATTACHMENT_COPY_CHUNK_BYTES = 64 * 1024; +// Android's java.net.URI rejects characters expo-file-system leaves unencoded, such as `[` and `]`. +function safeComposerAttachmentName(name: string): string { + return name.replace(/[^\w. -]/g, "-") || "file"; +} + export async function persistComposerAttachmentFile( uri: string, name: string, @@ -143,9 +148,7 @@ export async function persistComposerAttachmentFile( const { Directory, File, FileMode, Paths } = await import("expo-file-system"); const directory = new Directory(Paths.document, COMPOSER_ATTACHMENT_DIRECTORY); directory.create({ idempotent: true, intermediates: true }); - // Android's java.net.URI rejects characters expo-file-system leaves unencoded, such as `[` and `]`. - const safeName = name.replace(/[^\w. -]/g, "-") || "file"; - const destination = new File(directory, `${uuidv4()}-${safeName}`); + const destination = new File(directory, `${uuidv4()}-${safeComposerAttachmentName(name)}`); const source = new File(uri); const sourceSize = source.size; if ( @@ -218,6 +221,35 @@ export async function persistComposerAttachmentFile( return destination.uri; } +async function ownedComposerImageAttachment(input: { + readonly fileUri: string; + readonly name: string; + readonly mimeType: string; +}): Promise { + try { + const { File } = await import("expo-file-system"); + const sizeBytes = new File(input.fileUri).size; + if (sizeBytes === null || sizeBytes <= 0) { + throw new Error(m(msg("''{name}'' is empty or could not be read.", { name: input.name }))); + } + if (sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) { + throw new Error( + fileAttachmentTooLargeMessage(input.name, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, m), + ); + } + return { + ...input, + id: uuidv4(), + type: "image", + sizeBytes, + previewUri: input.fileUri, + }; + } catch (error) { + await removePersistedComposerAttachmentFile(input.fileUri); + throw error; + } +} + export async function removePersistedComposerAttachmentFile(uri: string): Promise { try { const { File, Paths } = await import("expo-file-system"); @@ -333,37 +365,29 @@ export async function pickComposerFiles(input: { attachments.push(attachment); continue; } + const { File } = await import("expo-file-system"); + let fileUri = attachment.fileUri; try { - const { File } = await import("expo-file-system"); - const original = await new File(attachment.fileUri).base64(); - const candidate = await fitComposerImage({ - uri: attachment.fileUri, - mimeType, - base64: original, - }); + const original = await new File(fileUri).base64(); + const candidate = await fitComposerImage({ uri: fileUri, mimeType, base64: original }); const fitted = candidate !== null && estimateBase64ByteSize(candidate.base64) <= PROVIDER_SEND_TURN_MAX_IMAGE_BYTES ? candidate : null; - const base64 = fitted?.base64 ?? original; - const sizeBytes = estimateBase64ByteSize(base64); - if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) { - throw new Error(m(msg("''{name}'' exceeds the 10 MB attachment limit.", { name }))); + if (fitted !== null) { + fileUri = await persistComposerAttachmentFile( + fitted.uri, + name, + PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, + ); + await removePersistedComposerAttachmentFile(attachment.fileUri); } - const dataUrl = `data:${mimeType};base64,${base64}`; - attachments.push({ - id: attachment.id, - type: "image", - name, - mimeType, - sizeBytes, - dataUrl, - previewUri: fitted?.uri ?? dataUrl, - }); - } finally { + } catch (cause) { await removePersistedComposerAttachmentFile(attachment.fileUri); + throw cause; } + attachments.push(await ownedComposerImageAttachment({ fileUri, name, mimeType })); } catch (cause) { error = errorDisplayMessage(cause, m) ?? m(msg("Could not read ''{name}''.", { name })); } @@ -517,7 +541,7 @@ export async function pickComposerMedia(input: { ? mimeType : null; - let image: { base64: string; mimeType: string; name: string; previewUri: string }; + let image: { base64: string; mimeType: string; name: string; uri: string }; try { if (originalMimeType !== null) { const { File } = await import("expo-file-system"); @@ -531,7 +555,7 @@ export async function pickComposerMedia(input: { base64: fitted?.base64 ?? base64, mimeType: originalMimeType, name, - previewUri: fitted?.uri ?? asset.uri, + uri: fitted?.uri ?? asset.uri, }; } else { const rendered = await renderPhoto(asset.uri); @@ -539,7 +563,7 @@ export async function pickComposerMedia(input: { base64: rendered.base64, mimeType: "image/jpeg", name: /\.jpe?g$/i.test(name) ? name : `${name.replace(/\.[^.]+$/, "")}.jpg`, - previewUri: rendered.uri, + uri: rendered.uri, }; } } catch { @@ -553,15 +577,18 @@ export async function pickComposerMedia(input: { continue; } - attachments.push({ - id: uuidv4(), - type: "image", - name: image.name, - mimeType: image.mimeType, - sizeBytes, - dataUrl: `data:${image.mimeType};base64,${image.base64}`, - previewUri: image.previewUri, - }); + try { + const fileUri = await persistComposerAttachmentFile( + image.uri, + image.name, + PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, + ); + attachments.push( + await ownedComposerImageAttachment({ fileUri, name: image.name, mimeType: image.mimeType }), + ); + } catch (cause) { + error = errorDisplayMessage(cause, m) ?? m(msg("Failed to read ''{name}''.", { name })); + } } return { @@ -639,6 +666,7 @@ export async function convertPastedImagesToAttachments(input: { temporaryUris.push(fitted.uri); } let base64 = fitted?.base64 ?? pastedBase64; + let sourceUri = fitted?.uri ?? uri; if ( rendered === null && estimateBase64ByteSize(base64) > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES @@ -647,6 +675,7 @@ export async function convertPastedImagesToAttachments(input: { temporaryUris.push(jpeg.uri); mimeType = "image/jpeg"; base64 = jpeg.base64; + sourceUri = jpeg.uri; } const sizeBytes = estimateBase64ByteSize(base64); if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) { @@ -656,16 +685,13 @@ export async function convertPastedImagesToAttachments(input: { : m(msg("Could not read a pasted image.")); continue; } - const dataUrl = `data:${mimeType};base64,${base64}`; - attachments.push({ - id: uuidv4(), - type: "image", - name: `pasted-image.${mimeType.split("/")[1] ?? "png"}`, - mimeType, - sizeBytes, - dataUrl, - previewUri: dataUrl, - }); + const name = `pasted-image.${mimeType.split("/")[1] ?? "png"}`; + const fileUri = await persistComposerAttachmentFile( + sourceUri, + name, + PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, + ); + attachments.push(await ownedComposerImageAttachment({ fileUri, name, mimeType })); } catch (cause) { console.warn("Failed to read pasted image", uri, cause); error = m(msg("Could not read a pasted image.")); diff --git a/apps/mobile/src/state/thread-outbox-model.ts b/apps/mobile/src/state/thread-outbox-model.ts index d85340a8556d2..e7e9fe9a302a0 100644 --- a/apps/mobile/src/state/thread-outbox-model.ts +++ b/apps/mobile/src/state/thread-outbox-model.ts @@ -34,8 +34,8 @@ import type { ComposerDispatchMode } from "@t3tools/client-runtime/state/compose import type { DraftComposerAttachment } from "../lib/composerImages"; import { scopedThreadKey } from "../lib/scopedEntities"; -// Keep current writes until a compatible native baseline includes the v4 reader. -const THREAD_OUTBOX_SCHEMA_VERSION = 3; +// v4 file-backed writes require native baselines with embedded readers and storage guards. +const THREAD_OUTBOX_SCHEMA_VERSION = 4; const THREAD_OUTBOX_MAX_RETRY_DELAY_MS = 16_000; const QueuedThreadCreationSchema = Schema.Struct({ @@ -52,7 +52,7 @@ const QueuedThreadCreationSchema = Schema.Struct({ }); export const QueuedThreadMessageSchema = Schema.Struct({ - schemaVersion: Schema.Literals([1, 2, THREAD_OUTBOX_SCHEMA_VERSION, 4]), + schemaVersion: Schema.Literals([1, 2, 3, THREAD_OUTBOX_SCHEMA_VERSION]), environmentId: EnvironmentId, threadId: ThreadId, messageId: MessageId, diff --git a/apps/mobile/src/state/use-composer-drafts.test.ts b/apps/mobile/src/state/use-composer-drafts.test.ts index fd1c248f5de9b..8c1870f76836b 100644 --- a/apps/mobile/src/state/use-composer-drafts.test.ts +++ b/apps/mobile/src/state/use-composer-drafts.test.ts @@ -91,9 +91,12 @@ const composerDraftFileMocks = vi.hoisted(() => { exists = true; size = 3; parentDirectory = null; + uri = "file:///documents/attachment.png"; create() {} + async copy() {} + moveSync() {} async text() { @@ -144,6 +147,7 @@ const incomingShareStorageMocks = vi.hoisted(() => ({ vi.mock("expo-file-system", () => ({ Directory: composerDraftFileMocks.Directory, File: composerDraftFileMocks.File, + FileMode: {}, Paths: { document: { uri: "file:///documents" } }, })); @@ -297,7 +301,7 @@ it.each(["picker open", "reading image"] as const)( expect.objectContaining({ type: "image", name: "screenshot.png", - dataUrl: "data:image/png;base64,YWJj", + fileUri: "file:///documents/attachment.png", }), ], ); @@ -1217,6 +1221,22 @@ describe("mobile composer drafts", () => { expect( appAtomRegistry.get(composerDraftsAtom)[pasteKey]?.attachments.map(({ id }) => id), ).toEqual(["red", "blue"]); + + const makeStoredPaste = (id: string) => ({ + id, + type: "image" as const, + name: "pasted-image.png", + mimeType: "image/png", + sizeBytes: 3, + fileUri: `file:///documents/t3-composer-attachments/${id}-pasted-image.png`, + previewUri: `file:///documents/t3-composer-attachments/${id}-pasted-image.png`, + }); + const storedKey = "new-task:environment-1:project-stored-pastes"; + appendComposerDraftAttachments(storedKey, [makeStoredPaste("red")]); + appendComposerDraftAttachments(storedKey, [makeStoredPaste("green")]); + expect( + appAtomRegistry.get(composerDraftsAtom)[storedKey]?.attachments.map(({ id }) => id), + ).toEqual(["red", "green"]); }); it("keeps shared attachment files until every draft releases them", async () => { diff --git a/apps/mobile/src/state/use-composer-drafts.ts b/apps/mobile/src/state/use-composer-drafts.ts index 0020defdc5915..10d8fd7a4f271 100644 --- a/apps/mobile/src/state/use-composer-drafts.ts +++ b/apps/mobile/src/state/use-composer-drafts.ts @@ -1431,7 +1431,9 @@ function isSameAttachment(a: DraftComposerAttachment, b: DraftComposerAttachment a.mimeType === b.mimeType && a.sizeBytes === b.sizeBytes && a.name === b.name && - (a.type !== "image" || b.type !== "image" || a.dataUrl === b.dataUrl) + (a.type !== "image" || + b.type !== "image" || + (a.dataUrl === b.dataUrl && a.fileUri === b.fileUri)) ); } From ad2bdc76a5bf22cd63b84e2cdee610c1a1b4bd18 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 06:14:38 -0800 Subject: [PATCH 171/324] fix(server): watch_pull_request says when checks already passed (#40866) --- apps/server/src/mcp/toolkits/pullRequests/handlers.ts | 9 ++++++--- apps/server/src/mcp/toolkits/pullRequests/tools.ts | 4 ++++ .../src/pullRequest/PullRequestWatchService.test.ts | 10 ++++++++++ apps/server/src/pullRequest/PullRequestWatchService.ts | 6 ++++++ 4 files changed, 26 insertions(+), 3 deletions(-) diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts index e422a799f3d9a..ddb3f2a025d43 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts @@ -66,6 +66,7 @@ import { PullRequestsToolkit, type ThreadPullRequestEntry, alreadyEndedWatchNext, + CHECKS_ALREADY_PASSED_WATCH_NEXT, CHILD_PULL_REQUEST_REPORT_NEXT, } from "./tools.ts"; @@ -333,9 +334,11 @@ const make = Effect.gen(function* () { .setWatching({ threadId, target: input, watching, until: input.until }) .pipe( Effect.map((result) => - result.state === undefined - ? result - : { ...result, next: alreadyEndedWatchNext(result.state) }, + result.state !== undefined + ? { ...result, next: alreadyEndedWatchNext(result.state) } + : result.checksState === "passing" + ? { ...result, next: CHECKS_ALREADY_PASSED_WATCH_NEXT } + : result, ), Effect.catchTags({ PullRequestWatchThreadNotFoundError: (error) => diff --git a/apps/server/src/mcp/toolkits/pullRequests/tools.ts b/apps/server/src/mcp/toolkits/pullRequests/tools.ts index 847ae4ef19e7d..1e75c5bbaa19f 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/tools.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/tools.ts @@ -263,6 +263,7 @@ export const WatchPullRequestResult = Schema.Struct({ description: "The PR already ended, so nothing was watched.", }), ), + checksState: Schema.optional(PullRequestChecksState), next: Schema.optional(Schema.String), }); export type WatchPullRequestResult = typeof WatchPullRequestResult.Type; @@ -270,6 +271,9 @@ export type WatchPullRequestResult = typeof WatchPullRequestResult.Type; export const alreadyEndedWatchNext = (state: "merged" | "closed") => `This PR is already ${state}, so there is nothing to watch. Report that and end your turn.`; +export const CHECKS_ALREADY_PASSED_WATCH_NEXT = + "Checks already pass on this head, so no wake will come for them. Act on that now; the watch still wakes you on later changes."; + export const ThreadPullRequestEntry = Schema.Struct({ ...PullRequestIdentity, source: ThreadPullRequestLinkSource, diff --git a/apps/server/src/pullRequest/PullRequestWatchService.test.ts b/apps/server/src/pullRequest/PullRequestWatchService.test.ts index edf4fee9c5c56..8982e795e2615 100644 --- a/apps/server/src/pullRequest/PullRequestWatchService.test.ts +++ b/apps/server/src/pullRequest/PullRequestWatchService.test.ts @@ -205,6 +205,16 @@ describe("PullRequestWatchService", () => { }), ); + it.effect("tells the caller when the checks already passed, since no wake will report it", () => + Effect.gen(function* () { + const harness = yield* makeHarness({ readChecksState: "passing" }); + const result = yield* harness.setWatching(true, { + url: "https://github.com/t3tools/t3code/pull/9", + }); + expect(result).toMatchObject({ wasWatching: false, checksState: "passing" }); + }), + ); + it.effect("reports a missing hosting CLI before saving a watch and still allows unwatch", () => Effect.gen(function* () { const missing = new PullRequestUnavailableError({ diff --git a/apps/server/src/pullRequest/PullRequestWatchService.ts b/apps/server/src/pullRequest/PullRequestWatchService.ts index 5e64ac4206896..32f51f540bf9f 100644 --- a/apps/server/src/pullRequest/PullRequestWatchService.ts +++ b/apps/server/src/pullRequest/PullRequestWatchService.ts @@ -2,6 +2,7 @@ import { CommandId, ThreadId, type OrchestrationV2ThreadShell, + type PullRequestChecksState, type PullRequestUnavailableError, type PullRequestWatchUntil, } from "@t3tools/contracts"; @@ -68,6 +69,8 @@ export class PullRequestWatchService extends Context.Service< readonly wasWatching: boolean; /** Set when the PR already ended, so no watch was registered. */ readonly state?: "merged" | "closed"; + /** CI as the start read saw it. Checks that already passed never wake the watch. */ + readonly checksState?: PullRequestChecksState; }, | PullRequestWatchFailedError | PullRequestWatchFromSubagentError @@ -130,6 +133,7 @@ const make = Effect.gen(function* () { if (watching && before?.snapshot?.state === "merged") return alreadyEnded("merged"); // A pending rollup has no failure yet, so any failure the first read finds is news. let checksPendingAtStart: boolean | undefined; + let checksStateAtStart: PullRequestChecksState | undefined; if (watching && !wasWatching) { const read = yield* pullRequests .summary( @@ -151,6 +155,7 @@ const make = Effect.gen(function* () { ); if (read?.state === "merged" || read?.state === "closed") return alreadyEnded(read.state); checksPendingAtStart = read === undefined ? undefined : read.checksState === "pending"; + checksStateAtStart = read?.checksState ?? undefined; } const uuid = yield* random.uuidV4().pipe(Effect.orDie); yield* engine @@ -180,6 +185,7 @@ const make = Effect.gen(function* () { ...target, watching: watchedLink(after)?.watch !== undefined, wasWatching, + ...(checksStateAtStart !== undefined && { checksState: checksStateAtStart }), }; }); From a445025645680d8c282011df5edc774f4551e6d8 Mon Sep 17 00:00:00 2001 From: Abhiram Kakarla <22UKakarlaA@qerdp.co.uk> Date: Sun, 22 Nov 2026 14:38:36 +0000 Subject: [PATCH 172/324] fix(codex): Open diff shows every file of a multi-file patch (#40874) Co-authored-by: Abhiram-745 <237478249+Abhiram-745@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../Adapters/CodexAdapterV2.test.ts | 22 +++++++++++++ .../Adapters/CodexAdapterV2.ts | 32 ++++++++++++++++++- 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index ef4ffcf35c11b..d30748a0df77c 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -12809,6 +12809,28 @@ describe("CodexAdapterV2 post-settle continuation", () => { { operation: "delete", path: "/w/e.ts" }, { operation: "add", path: "/w/a.ts" }, ]); + assert.equal( + fileChanges[0]?.diffStr, + [ + 'diff --git "a//w/c.ts" "b//w/d.ts"', + '--- "a//w/c.ts"', + '+++ "b//w/d.ts"', + "@@", + 'diff --git "a//w/e.ts" "b//w/e.ts"', + '--- "a//w/e.ts"', + "+++ /dev/null", + "@@ -1,1 +0,0 @@", + "-gone", + "\\ No newline at end of file", + 'diff --git "a//w/a.ts" "b//w/a.ts"', + "--- /dev/null", + '+++ "b//w/a.ts"', + "@@ -0,0 +1,1 @@", + "+export {};", + "\\ No newline at end of file", + "", + ].join("\n"), + ); }).pipe( Effect.scoped, Effect.provide( diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index e5dfd83559292..181ed17fd5c16 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -178,6 +178,35 @@ type CodexFileChangeKinds = Readonly< Record >; +// Diff parsers split at Git headers once one exists, so each file of a multi-file patch needs its own. +function codexMultiFilePatch( + changes: ReadonlyArray, +): string { + return changes + .map(({ path, kind, diff }) => { + const oldPath = path; + const newPath = (kind.type === "update" && kind.move_path) || path; + const git = `diff --git ${JSON.stringify(`a/${oldPath}`)} ${JSON.stringify(`b/${newPath}`)}\n`; + if (kind.type === "update" && diff.startsWith("diff --git ")) return diff; + if (kind.type === "update" && diff.startsWith("--- ")) return `${git}${diff}`; + let hunks = diff; + // Codex records added and deleted files as their raw contents. + if (kind.type !== "update") { + const lines = diff.split("\n"); + const hasFinalNewline = diff.endsWith("\n"); + if (hasFinalNewline) lines.pop(); + const added = kind.type === "add"; + const range = `1,${lines.length}`; + hunks = `@@ -${added ? "0,0" : range} +${added ? range : "0,0"} @@\n${lines.map((line) => `${added ? "+" : "-"}${line}`).join("\n")}\n${hasFinalNewline ? "" : "\\ No newline at end of file\n"}`; + } + const before = kind.type === "add" ? "/dev/null" : JSON.stringify(`a/${oldPath}`); + const after = kind.type === "delete" ? "/dev/null" : JSON.stringify(`b/${newPath}`); + return `${git}--- ${before}\n+++ ${after}\n${hunks}`; + }) + .map((section) => (section.endsWith("\n") ? section : `${section}\n`)) + .join(""); +} + function codexFileChangeApprovalPrompt(input: { readonly reason?: string | null; readonly grantRoot?: string | null; @@ -4285,7 +4314,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( updatedAt, type: "file_change", fileName: firstChange.path, - diffStr: firstChange.diff, + diffStr: + item.changes.length > 1 ? codexMultiFilePatch(item.changes) : firstChange.diff, changes: item.changes.map((change) => { const movePath = change.kind.type === "update" ? change.kind.move_path : undefined; return movePath From 2f19cec07933f9f5fe1fe380d98b0841f83b90be Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 06:41:15 -0800 Subject: [PATCH 173/324] fix(server): ACP startup gives up when the agent never answers the handshake (#40864) --- .../provider/acp/AcpJsonRpcConnection.test.ts | 20 ++++++++++++++ .../src/server/AcpSessionRuntime.ts | 27 ++++++++++++++++--- 2 files changed, 44 insertions(+), 3 deletions(-) diff --git a/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts b/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts index 796bc854d28d6..a000e05471bc6 100644 --- a/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts +++ b/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts @@ -1621,6 +1621,26 @@ describe("AcpSessionRuntime", () => { }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); + it.effect("fails startup when the agent never answers initialize", () => + Effect.gen(function* () { + const initializeSent = yield* Deferred.make(); + const runtime = yield* AcpSessionRuntime.make({ + ...mockRuntimeOptions, + // A live child that reads stdin and never replies, like one stuck in disk sleep. + spawn: { command: "node", args: ["-e", "process.stdin.resume()"] }, + requestLogger: (event) => + event.method === "initialize" && event.status === "started" + ? Deferred.succeed(initializeSent, undefined) + : Effect.void, + }); + const startup = yield* runtime.start().pipe(Effect.forkChild); + yield* Deferred.await(initializeSent); + yield* TestClock.adjust("30 minutes"); + const exit = yield* Fiber.await(startup); + expect(Exit.isFailure(exit)).toBe(true); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); + it.effect("sends a cancel after the cancel timeout when its prompt never goes out", () => Effect.gen(function* () { const runtime = yield* AcpSessionRuntime.make({ diff --git a/packages/provider-acp/src/server/AcpSessionRuntime.ts b/packages/provider-acp/src/server/AcpSessionRuntime.ts index 2c488b6bdd83c..b08eef243fc3e 100644 --- a/packages/provider-acp/src/server/AcpSessionRuntime.ts +++ b/packages/provider-acp/src/server/AcpSessionRuntime.ts @@ -85,6 +85,8 @@ export type AcpSessionRuntimeEvent = }; const defaultSessionLoadTimeout = Duration.seconds(90); +// A live child that never answers the handshake would otherwise hold the start open forever. +const startupRequestTimeout = Duration.seconds(90); const defaultSessionLoadReplayIdleGap = Duration.seconds(2); const defaultCancelTimeout = Duration.seconds(15); const maxStartupMetadataUpdates = 32; @@ -1399,6 +1401,25 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( Effect.andThen(runLoggedRequest(method, payload, effect)), ); + const withStartupTimeout =
    ( + method: string, + effect: Effect.Effect, + ): Effect.Effect => + effect.pipe( + Effect.timeoutOrElse({ + duration: startupRequestTimeout, + orElse: () => + Effect.fail( + new EffectAcpErrors.AcpTransportError({ + operation: "call-rpc", + method, + detail: `${method} timed out waiting for RPC response`, + cause: undefined, + }), + ), + }), + ); + const runLoggedRequest = ( method: string, payload: unknown, @@ -2297,7 +2318,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( const initializeResult = yield* runLoggedRequest( "initialize", initializePayload, - acp.agent.initialize(initializePayload), + withStartupTimeout("initialize", acp.agent.initialize(initializePayload)), ); yield* options.onInitialized?.(initializeResult) ?? Effect.void; return initializeResult; @@ -2445,7 +2466,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( sessionSetupResult = yield* runLoggedRequest( "session/resume", resumePayload, - acp.agent.resumeSession(resumePayload), + withStartupTimeout("session/resume", acp.agent.resumeSession(resumePayload)), ); } else { return yield* new EffectAcpErrors.AcpRequestError({ @@ -2462,7 +2483,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( const created = yield* runLoggedRequest( "session/new", createPayload, - acp.agent.createSession(createPayload), + withStartupTimeout("session/new", acp.agent.createSession(createPayload)), ); sessionId = created.sessionId; sessionSetupResult = created; From 1d028248683f90f405b2d8e7b71682e3b67317ed Mon Sep 17 00:00:00 2001 From: Abhiram Kakarla <22UKakarlaA@qerdp.co.uk> Date: Sun, 22 Nov 2026 14:43:54 +0000 Subject: [PATCH 174/324] fix(server): a branch prefixed with another remote's name publishes under its full name (#40877) Co-authored-by: Abhiram-745 <237478249+Abhiram-745@users.noreply.github.com> Co-authored-by: Julius Marminge --- apps/server/src/vcs/GitVcsDriverCore.test.ts | 29 ++++++++++++++++++++ apps/server/src/vcs/GitVcsDriverCore.ts | 21 ++++++-------- 2 files changed, 37 insertions(+), 13 deletions(-) diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index d9a661c7b1237..b3ad640db4c7a 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -10325,6 +10325,35 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect( + "publishes a new branch prefixed with another remote's name under its full name", + () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const origin = yield* makeTmpDir("git-remote-"); + const fork = yield* makeTmpDir("git-fork-"); + yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + yield* git(origin, ["init", "--bare"]); + yield* git(fork, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "origin", origin]); + // e.g. the remote T3 adds when checking out a pull request from alice's fork. + yield* git(cwd, ["remote", "add", "alice", fork]); + yield* git(cwd, ["checkout", "-b", "alice/fix"]); + yield* writeTextFile(cwd, "fix.txt", "fix\n"); + yield* git(cwd, ["add", "-A"]); + yield* driver.commit(cwd, "Add fix", ""); + + const pushed = yield* driver.pushCurrentBranch(cwd, null); + + assert.deepInclude(pushed, { status: "pushed", upstreamBranch: "origin/alice/fix" }); + assert.equal( + yield* git(origin, ["--git-dir=.", "rev-parse", "refs/heads/alice/fix"]), + yield* git(cwd, ["rev-parse", "HEAD"]), + ); + }), + ); + it.effect("still pushes a git-mangled tracking alias to its upstream head", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 8f3e3e16ca12b..f863f01bdb40a 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -2147,14 +2147,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* Effect.map(parseRemoteNamesInGitOrder), ); - const resolvePublishBranchName = Effect.fn("resolvePublishBranchName")(function* ( - cwd: string, - branchName: string, - ) { - const remoteNames = yield* listRemoteNames(cwd).pipe(Effect.orElseSucceed(() => [])); - const parsedRemoteRef = parseRemoteRefWithRemoteNames(branchName, remoteNames); - return parsedRemoteRef?.branchName ?? branchName; - }); + // Only the destination remote's prefix is dropped; `alice/fix` pushed to origin keeps its full name. + const resolvePublishBranchName = (branchName: string, remoteName: string) => + parseRemoteRefWithRemoteNames(branchName, [remoteName])?.branchName ?? branchName; const hasAnyRemote = (cwd: string) => resolveRepositoryPaths(cwd).pipe( @@ -3680,7 +3675,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* // A gone local upstream still gets the full local name, as below. const branchName = goneUpstream?.branchName ?? - (configuredRemoteName === "." ? branch : yield* resolvePublishBranchName(cwd, branch)); + (configuredRemoteName === "." ? branch : resolvePublishBranchName(branch, remoteName)); return { remoteName, branchName, @@ -3731,10 +3726,10 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const publishRemoteName = yield* resolvePushRemoteName(cwd, branch).pipe( Effect.orElseSucceed(() => null), ); - const branchName = yield* resolvePublishBranchName(cwd, branch); + const remoteName = publishRemoteName ?? upstream.remoteName; return { - remoteName: publishRemoteName ?? upstream.remoteName, - branchName, + remoteName, + branchName: resolvePublishBranchName(branch, remoteName), publishes: true, upstream, pushRemote: null, @@ -3774,7 +3769,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const requestedRemoteName = options?.remoteName?.trim() || null; if (requestedRemoteName) { - const publishBranch = yield* resolvePublishBranchName(cwd, branch); + const publishBranch = resolvePublishBranchName(branch, requestedRemoteName); yield* executeGitWithStableDiagnostics( "GitVcsDriver.pushCurrentBranch.pushWithRequestedRemote", cwd, From f10e1eb3825a773cf702569d2258edfdbc8b77dc Mon Sep 17 00:00:00 2001 From: project516 <138796702+Project516@users.noreply.github.com> Date: Sun, 22 Nov 2026 08:55:27 -0600 Subject: [PATCH 175/324] fix(server): list open delegated tasks when task_status or task_cancel finds no match (#40886) Co-authored-by: Julius Marminge --- .../src/mcp/OrchestratorMcpService.test.ts | 8 ++++ apps/server/src/mcp/OrchestratorMcpService.ts | 38 +++++++++++++++---- 2 files changed, 38 insertions(+), 8 deletions(-) diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index ccd41144a5ea8..551a84109cfa2 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -106,6 +106,7 @@ describe("OrchestratorMcpService", () => { threadId: parentThreadId, origin: "app_owned", childThreadId, + title: "Merge", driver: "codex", model: "gpt-5.6-terra", result: "terminal result", @@ -252,6 +253,13 @@ describe("OrchestratorMcpService", () => { const commandIds = yield* Ref.get(acknowledgementCommandIds); assert.equal(commandIds.length, 2); assert.notEqual(commandIds[0], commandIds[1]); + + const missing = yield* service + .taskStatus(scope, NodeId.make("node:mcp-ack-missing")) + .pipe(Effect.flip); + assert.equal(missing.code, "task_not_found"); + assert.include(missing.message, "No delegated task with id node:mcp-ack-missing"); + assert.include(missing.message, `${taskId} (Merge)`); }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies)))); }), ); diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 4062c509812c4..f9ad32a6e1d3e 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -154,6 +154,7 @@ const TASK_WAKE_EVENTS = [ { thread: "child", eventType: "runtime-request.updated" }, ] as const; const SECRET_REQUEST_POLL_INTERVAL_MS = 500; +const MAX_LISTED_TASKS = 10; const DEFAULT_THREAD_LIST_LIMIT = 10; const DEFAULT_THREAD_READ_LIMIT = 10; const DEFAULT_THREAD_RUN_LIMIT = 10; @@ -1805,6 +1806,33 @@ const make = Effect.gen(function* () { const requestKey = (clientRequestId: string | undefined): Effect.Effect => clientRequestId === undefined ? random.uuidV4() : Effect.succeed(clientRequestId); + const taskNotFound = Effect.fn("OrchestratorMcpService.taskNotFound")(function* ( + scope: McpThreadInvocationScope, + taskId: NodeId, + ): Effect.fn.Return { + const { subagents } = yield* loadThreadRecords(scope.thread.threadId, ["subagents"], { + omitSettledSubagents: true, + }); + const open = subagents.filter( + (task) => + task.origin === "app_owned" && + (task.childThreadId !== null || task.remoteChild !== undefined), + ); + const listed = open + .slice(0, MAX_LISTED_TASKS) + .map((task) => (task.title ? `${task.id} (${task.title})` : task.id)) + .join(", "); + const more = + open.length > MAX_LISTED_TASKS ? `, and ${open.length - MAX_LISTED_TASKS} more` : ""; + return yield* failure( + "task_not_found", + `No delegated task with id ${taskId} exists on thread ${scope.thread.threadId}. ` + + (open.length === 0 + ? "This thread has no open delegated tasks." + : `Open delegated tasks on this thread: ${listed}${more}.`), + ); + }); + const readTask = Effect.fn("OrchestratorMcpService.readTask")(function* ( scope: McpThreadInvocationScope, taskId: NodeId, @@ -1820,10 +1848,7 @@ const make = Effect.gen(function* () { candidate.threadId === scope.thread.threadId, ); if (task === undefined || (task.childThreadId === null && task.remoteChild === undefined)) { - return yield* failure( - "task_not_found", - `Delegated task ${taskId} does not belong to thread ${scope.thread.threadId}.`, - ); + return yield* taskNotFound(scope, taskId); } if (task.childThreadId === null) { return yield* readRemoteTask(scope, task, waitTimedOut, acknowledgeTerminal); @@ -3006,10 +3031,7 @@ const make = Effect.gen(function* () { task.remoteChild !== undefined, ); if (remoteTask === undefined) { - return yield* failure( - "task_not_found", - `Delegated task ${input.taskId} does not belong to thread ${scope.thread.threadId}.`, - ); + return yield* taskNotFound(scope, input.taskId); } return yield* remoteDelegation.cancel(scope, remoteTask, input); } From 2251de4d2e61f921b90fb7bfdabef8b1a34d8803 Mon Sep 17 00:00:00 2001 From: Abhiram Kakarla <22UKakarlaA@qerdp.co.uk> Date: Sun, 22 Nov 2026 15:23:05 +0000 Subject: [PATCH 176/324] fix(gitlab): find merge requests opened from a fork (#40894) Co-authored-by: Abhiram-745 <237478249+Abhiram-745@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../src/server/GitLabCli.ts | 46 +++++++++- .../GitLabSourceControlProvider.git.test.ts | 91 +++++++++++++++++++ .../GitLabSourceControlProvider.test.ts | 7 ++ .../src/server/GitLabSourceControlProvider.ts | 16 +++- .../src/server/gitLabMergeRequests.ts | 20 ++++ 5 files changed, 173 insertions(+), 7 deletions(-) diff --git a/packages/source-control-gitlab/src/server/GitLabCli.ts b/packages/source-control-gitlab/src/server/GitLabCli.ts index b528c1ced5a8a..04a633bba7096 100644 --- a/packages/source-control-gitlab/src/server/GitLabCli.ts +++ b/packages/source-control-gitlab/src/server/GitLabCli.ts @@ -21,6 +21,8 @@ import * as SourceControlHost from "@t3tools/source-control-core/server/SourceCo import { decodeGitLabMergeRequestJson, decodeGitLabMergeRequestListJson, + type NormalizedGitLabMergeRequestRecord, + withSourceProjectPath, } from "./gitLabMergeRequests.ts"; import type * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider"; @@ -377,6 +379,10 @@ const decodeGitLabMergeRequestProject = Schema.decodeEffect( Schema.fromJsonString(Schema.Struct({ id: Schema.Number, path: TrimmedNonEmptyString })), ); +const decodeGitLabProjectPath = Schema.decodeEffect( + Schema.fromJsonString(Schema.Struct({ path_with_namespace: TrimmedNonEmptyString })), +); + const RawGitLabNamespaceSchema = Schema.Struct({ id: Schema.Number, }); @@ -559,6 +565,35 @@ export const make = Effect.gen(function* () { ), ); + // glab's MR JSON names a fork's source project only by `source_project_id`. + const resolveSourceProjectPaths = Effect.fn("GitLabCli.resolveSourceProjectPaths")(function* ( + cwd: string, + records: ReadonlyArray, + paths: Map, + ) { + const ids = new Set(); + for (const record of records) { + const id = record.unresolvedSourceProjectId; + if (id !== undefined && !paths.has(id)) ids.add(id); + } + yield* Effect.forEach( + ids, + (id) => + execute({ cwd, args: ["api", `projects/${id}`] }).pipe( + Effect.flatMap((result) => decodeGitLabProjectPath(result.stdout.trim())), + Effect.map((project) => project.path_with_namespace), + Effect.orElseSucceed(() => null), + Effect.map((path) => void paths.set(id, path)), + ), + { concurrency: 8, discard: true }, + ); + return records.map((record) => + record.unresolvedSourceProjectId === undefined + ? record + : withSourceProjectPath(record, paths.get(record.unresolvedSourceProjectId) ?? null), + ); + }); + return GitLabCli.of({ execute, listMergeRequests: Effect.fn("GitLabCli.listMergeRequests")(function* (input) { @@ -566,6 +601,7 @@ export const make = Effect.gen(function* () { let pageSize = limit; let page = 1; const items: GitLabMergeRequestSummary[] = []; + const sourceProjectPaths = input.source?.owner ? new Map() : null; while (items.length < limit) { const result = yield* execute({ cwd: input.cwd, @@ -600,7 +636,11 @@ export const make = Effect.gen(function* () { cause: Result.isFailure(decoded) ? decoded.failure : "MR list output was truncated", }); } - items.push(...decoded.success.map(toSummaryWithOptionalUpdatedAt)); + // Only a fork head can match a fork's merge request, so other lookups skip the API calls. + const records = sourceProjectPaths + ? yield* resolveSourceProjectPaths(input.cwd, decoded.success, sourceProjectPaths) + : decoded.success; + items.push(...records.map(toSummaryWithOptionalUpdatedAt)); // Count raw entries: the decoder drops invalid ones, which would end paging early. const entries = decodeJsonArray(raw); if ( @@ -635,7 +675,9 @@ export const make = Effect.gen(function* () { ); } - return Effect.succeed(toSummaryWithOptionalUpdatedAt(decoded.success)); + return resolveSourceProjectPaths(input.cwd, [decoded.success], new Map()).pipe( + Effect.map(([record]) => toSummaryWithOptionalUpdatedAt(record!)), + ); }), ), ), diff --git a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.git.test.ts b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.git.test.ts index 7038e6a82d630..abd2f7b82f218 100644 --- a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.git.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.git.test.ts @@ -106,6 +106,97 @@ it.effect("lists a nested-group fork's merge requests by source branch and names }), ); +// Real `glab mr list --output json` marshals client-go's BasicMergeRequest: a fork MR names its +// source project only by `source_project_id`, never by a `source_project` path. +it.effect("names a fork merge request's source project from real glab list output", () => + Effect.gen(function* () { + const branch = "feature/fork-work"; + const mergeRequest = (iid: number, sourceProjectId: number) => ({ + id: 9000 + iid, + iid, + project_id: 100, + title: `Work ${iid}`, + state: "opened", + target_branch: "main", + source_branch: branch, + source_project_id: sourceProjectId, + target_project_id: 100, + draft: false, + sha: "0123456789abcdef0123456789abcdef01234567", + updated_at: "2026-04-07T15:00:00.000Z", + references: { short: `!${iid}`, relative: `!${iid}`, full: `group/upstream!${iid}` }, + web_url: `https://gitlab.com/group/upstream/-/merge_requests/${iid}`, + }); + const output = JSON.stringify([ + mergeRequest(1, 101), + mergeRequest(2, 101), + mergeRequest(3, 100), + mergeRequest(4, 102), + ]); + const apiCalls: ReadonlyArray[] = []; + const provider = yield* GitLabSourceControlProvider.make.pipe( + Effect.provide( + GitLabCli.layer.pipe( + Layer.provideMerge( + TestSourceControlHost.layer({ + process: { + run: (input) => + Effect.sync(() => { + if (input.args[0] !== "api") return TestSourceControlHost.processOutput(output); + apiCalls.push(input.args); + return TestSourceControlHost.processOutput( + input.args[1] === "projects/101" + ? JSON.stringify({ id: 101, path_with_namespace: "alice/upstream" }) + : "not json", + ); + }), + }, + }), + ), + Layer.provide(FileSystem.layerNoop({})), + ), + ), + ); + + const upstreamHead = yield* provider.listChangeRequests({ + cwd: "/repo", + headSelector: branch, + state: "open", + limit: 20, + }); + expect(upstreamHead[0]).not.toHaveProperty("headRepositoryNameWithOwner"); + expect(apiCalls).toEqual([]); + + const changeRequests = yield* provider.listChangeRequests({ + cwd: "/repo", + headSelector: `alice:${branch}`, + state: "open", + limit: 20, + }); + // GitManager drops a cross-repository MR whose head project is unnamed. + expect(changeRequests).toMatchObject([ + { + number: 1, + isCrossRepository: true, + headRepositoryNameWithOwner: "alice/upstream", + headRepositoryOwnerLogin: "alice", + }, + { number: 2, isCrossRepository: true, headRepositoryNameWithOwner: "alice/upstream" }, + { number: 3, isCrossRepository: false }, + { number: 4, isCrossRepository: true }, + ]); + expect(changeRequests[2]).not.toHaveProperty("headRepositoryNameWithOwner"); + expect(changeRequests[3]).not.toHaveProperty("headRepositoryNameWithOwner"); + expect(apiCalls).toHaveLength(2); + expect(apiCalls).toEqual( + expect.arrayContaining([ + ["api", "projects/101"], + ["api", "projects/102"], + ]), + ); + }), +); + const withRepository = ( test: (input: { readonly git: (...args: string[]) => Effect.Effect; diff --git a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts index 8e5077044c6b3..c5a2d56037172 100644 --- a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts @@ -210,6 +210,13 @@ it.effect( headSelectors: ["octocat:feature", "feature"], state: "open", }), + { headSelectors: ["octocat:feature"], limit: 100 }, + ); + assert.deepStrictEqual( + provider.headBranchProbe?.({ + headSelectors: ["feature", "octocat:feature"], + state: "open", + }), { headSelectors: ["feature"], limit: 100 }, ); }), diff --git a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts index a7d5b71ca47d3..2a2d4ac3e199c 100644 --- a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts +++ b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts @@ -211,11 +211,17 @@ export const make = Effect.gen(function* () { return SourceControlProvider.SourceControlProvider.of({ kind: SourceControlProviderKind.make("gitlab"), - // GitLab lists fork merge requests by source branch with no owner filter, so read a full page. - headBranchProbe: ({ headSelectors }) => ({ - headSelectors: headSelectors.filter((selector) => !selector.includes(":")), - limit: 100, - }), + // GitLab lists fork merge requests by source branch with no owner filter, so read a full page + // once per branch. The first selector wins: GitManager puts `owner:branch` first for a fork + // head, which tells the list to name fork source projects. + headBranchProbe: ({ headSelectors }) => { + const byBranch = new Map(); + for (const selector of headSelectors) { + const branch = SourceControlProvider.sourceBranch({ headSelector: selector }); + if (!byBranch.has(branch)) byBranch.set(branch, selector); + } + return { headSelectors: [...byBranch.values()], limit: 100 }; + }, readChangeRequestTemplate: Effect.fn("GitLabSourceControlProvider.readChangeRequestTemplate")( function ({ cwd, treeish }) { return GitLabChangeRequestTemplate.detect(cwd, treeish, git.execute); diff --git a/packages/source-control-gitlab/src/server/gitLabMergeRequests.ts b/packages/source-control-gitlab/src/server/gitLabMergeRequests.ts index ef4438f5ff3ee..a40abd786cf85 100644 --- a/packages/source-control-gitlab/src/server/gitLabMergeRequests.ts +++ b/packages/source-control-gitlab/src/server/gitLabMergeRequests.ts @@ -23,6 +23,8 @@ export interface NormalizedGitLabMergeRequestRecord { readonly isCrossRepository?: boolean; readonly headRepositoryNameWithOwner?: string | null; readonly headRepositoryOwnerLogin?: string | null; + /** Set when a cross-repository MR names its source project only by id. */ + readonly unresolvedSourceProjectId?: number; } const GitLabProjectReferenceSchema = Schema.Struct({ @@ -122,6 +124,24 @@ function normalizeGitLabMergeRequestRecord( ...(typeof isCrossRepository === "boolean" ? { isCrossRepository } : {}), ...(sourceProjectPath ? { headRepositoryNameWithOwner: sourceProjectPath } : {}), ...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}), + ...(isCrossRepository === true && + !sourceProjectPath && + typeof raw.source_project_id === "number" + ? { unresolvedSourceProjectId: raw.source_project_id } + : {}), + }; +} + +export function withSourceProjectPath( + record: NormalizedGitLabMergeRequestRecord, + sourceProjectPath: string | null, +): NormalizedGitLabMergeRequestRecord { + const { unresolvedSourceProjectId: _, ...resolved } = record; + const headRepositoryOwnerLogin = ownerLoginFromPathWithNamespace(sourceProjectPath); + return { + ...resolved, + ...(sourceProjectPath ? { headRepositoryNameWithOwner: sourceProjectPath } : {}), + ...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}), }; } From 2c4310eb061373bb1c6ccefe6dafd0500ee8f5e3 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 07:29:08 -0800 Subject: [PATCH 177/324] fix(web): pasting a chat message with text and a picture keeps both (#40909) --- apps/web/src/components/chat/ChatComposer.tsx | 23 ++++++++---- .../chat/composerAttachmentFiles.test.ts | 7 ++++ .../chat/composerAttachmentFiles.ts | 35 ++++++++++++++----- 3 files changed, 50 insertions(+), 15 deletions(-) diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 6fb651c3471f6..af4871b451932 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -133,7 +133,8 @@ import { fileAttachmentCapabilityBlockReason, fileAttachmentStagingLimit, isPreviewableComposerVideo, - isImageOnlyClipboardHtml, + clipboardHtmlImageContent, + imagesToAttachBesidePastedText, shouldHandleComposerAttachmentPaste, } from "./composerAttachmentFiles"; import { @@ -2947,18 +2948,19 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const pastedContext = !isLiteralPendingAnswer && (readPastedComposerContext(event.clipboardData)?.records.length ?? 0) > 0; + const canAttachFiles = !pastedContext && activeThreadId !== null && files.length > 0; + const htmlImageContent = + canAttachFiles && plainText.length > 0 + ? clipboardHtmlImageContent(event.clipboardData.getData("text/html")) + : "none"; if ( folders.length > 0 || - (!pastedContext && - activeThreadId && - files.length > 0 && + (canAttachFiles && shouldHandleComposerAttachmentPaste({ files, plainText, bypassAutoAttachment, - htmlIsOnlyImage: - plainText.length > 0 && - isImageOnlyClipboardHtml(event.clipboardData.getData("text/html")), + htmlIsOnlyImage: htmlImageContent === "only-image", })) ) { event.preventDefault(); @@ -2971,6 +2973,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) } if (pastedContext) return; + const imagesBesideText = imagesToAttachBesidePastedText({ + files, + plainText, + bypassAutoAttachment, + htmlHasImageAndText: htmlImageContent === "image-and-text", + }); + if (imagesBesideText.length > 0) void addComposerAttachments(imagesBesideText); if (!foldPastedText(plainText, bypassAutoAttachment)) { return; } diff --git a/apps/web/src/components/chat/composerAttachmentFiles.test.ts b/apps/web/src/components/chat/composerAttachmentFiles.test.ts index f842566d7cd60..ac43d667d80ca 100644 --- a/apps/web/src/components/chat/composerAttachmentFiles.test.ts +++ b/apps/web/src/components/chat/composerAttachmentFiles.test.ts @@ -13,6 +13,7 @@ import { composerFileAttachmentMimeType, fileAttachmentCapabilityBlockReason, fileAttachmentStagingLimit, + imagesToAttachBesidePastedText, normalizeComposerImageFileMimeType, shouldHandleComposerAttachmentPaste, } from "./composerAttachmentFiles"; @@ -141,6 +142,12 @@ describe("composer attachment files", () => { expect(shouldHandleComposerAttachmentPaste({ files: [image], plainText: "image.png" })).toBe( true, ); + // A QQ or WeChat message has its text beside an in the HTML: the image attaches too. + const message = { files: [image], plainText: "Look at this", htmlHasImageAndText: true }; + expect(shouldHandleComposerAttachmentPaste(message)).toBe(false); + expect(imagesToAttachBesidePastedText(message)).toEqual([image]); + expect(imagesToAttachBesidePastedText({ ...message, htmlHasImageAndText: false })).toEqual([]); + expect(imagesToAttachBesidePastedText({ ...message, bypassAutoAttachment: true })).toEqual([]); }); it("preserves text when the clipboard also includes generic image files", () => { diff --git a/apps/web/src/components/chat/composerAttachmentFiles.ts b/apps/web/src/components/chat/composerAttachmentFiles.ts index 191c5841185ff..538d2dfd67304 100644 --- a/apps/web/src/components/chat/composerAttachmentFiles.ts +++ b/apps/web/src/components/chat/composerAttachmentFiles.ts @@ -247,11 +247,33 @@ function isOnlyFileNames(text: string, files: ReadonlyArray): boolean { .every((line) => names.has(line)); } -/** A browser's Copy Image puts only an in text/html; rich text sources put the text there. */ -export function isImageOnlyClipboardHtml(html: string): boolean { - if (html.length === 0) return false; +/** + * A browser's Copy Image puts only an in text/html; a chat message (QQ, WeChat) puts its text + * beside the ; rich text sources (Word, Pages) put only the text there. + */ +export function clipboardHtmlImageContent(html: string): "only-image" | "image-and-text" | "none" { + if (html.length === 0) return "none"; const body = new DOMParser().parseFromString(html, "text/html").body; - return body.querySelector("img") !== null && (body.textContent ?? "").trim().length === 0; + if (body.querySelector("img") === null) return "none"; + return (body.textContent ?? "").trim().length === 0 ? "only-image" : "image-and-text"; +} + +function isPastedImageFile(file: File): boolean { + const classification = classifyComposerAttachmentFile(file); + return classification === "image" || classification === "unsupported-image"; +} + +/** The images of a message copied with its text: they attach while the text pastes as text. */ +export function imagesToAttachBesidePastedText(input: { + readonly files: ReadonlyArray; + readonly plainText: string; + readonly bypassAutoAttachment?: boolean; + readonly htmlHasImageAndText: boolean; +}): File[] { + if (input.bypassAutoAttachment || input.plainText.length === 0 || !input.htmlHasImageAndText) { + return []; + } + return input.files.filter(isPastedImageFile); } export function shouldHandleComposerAttachmentPaste(input: { @@ -269,10 +291,7 @@ export function shouldHandleComposerAttachmentPaste(input: { ) { return true; } - const hasImage = input.files.some((file) => { - const classification = classifyComposerAttachmentFile(file); - return classification === "image" || classification === "unsupported-image"; - }); + const hasImage = input.files.some(isPastedImageFile); if (input.plainText.length === 0) { return hasImage || input.files.some((file) => classifyComposerAttachmentFile(file) === "file"); } From 344de5fe8e70e9eeaacaedc34e7aa5e2a29287d1 Mon Sep 17 00:00:00 2001 From: Lokkuchakreshkumar Date: Sun, 22 Nov 2026 21:53:23 +0530 Subject: [PATCH 178/324] fix(antigravity): bound silent post-settle background command holds (#40858) Co-authored-by: LVC-Chakresh Co-authored-by: Julius Marminge --- .../Adapters/AntigravityAdapterV2.test.ts | 119 ++++++++++++++++++ .../Adapters/AntigravityAdapterV2.ts | 7 ++ .../src/provider/acp/AntigravityProtocol.ts | 6 + packages/provider-acp/src/server/adapter.ts | 57 ++++++++- 4 files changed, 187 insertions(+), 2 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index fca472c6c433e..5cbb4975e5e57 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -1327,6 +1327,16 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { yield* openSessionWithRunningCommand({ WaitMsBeforeAsync: 10000 }); yield* startTurn(1, false); yield* throughPromptSettled; + // Progress keeps a command past the post-settle hold bound, which counts silence only. + for (const minute of [10, 20, 30]) { + yield* TestClock.adjust("10 minutes"); + yield* send({ + sessionUpdate: "tool_call_update", + ...command, + status: "in_progress", + rawOutput: { output: `fetched ${minute} pages` }, + }); + } yield* TestClock.adjust("10 minutes"); yield* send({ sessionUpdate: "tool_call_update", @@ -1349,6 +1359,115 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { }).pipe(Effect.provide(layerSession)), ); + // A command whose terminal update never arrives would hold the run in Working forever with + // an empty pending list and a finished reply above Stop. + it.effect("settles a silent background command after the post-settle hold timeout", () => + Effect.gen(function* () { + const { command, offers, startTurn, until, throughPromptSettled } = + yield* openSessionWithRunningCommand({ WaitMsBeforeAsync: 10000 }); + yield* startTurn(1, false); + const prompt = yield* throughPromptSettled; + + // A running tool keeps the inactivity watchdog re-armed, so 20 silent minutes do not + // settle this run on their own. + yield* TestClock.adjust("20 minutes"); + yield* TestClock.adjust("11 minutes"); + const run = yield* until((event) => event.type === "turn.terminal"); + const terminal = run.at(-1); + assert.equal( + terminal?.type === "turn.terminal" && terminal.status, + "completed", + "the bounded hold finalizes the turn instead of leaving it running forever", + ); + assert.equal(terminal?.type === "turn.terminal" && terminal.failure, null); + assert.lengthOf(offers, 0, "a silent command produces no wake on its own"); + const commandItem = [...prompt, ...run].findLast( + (event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === command.toolCallId, + ); + assert.isTrue( + commandItem?.type === "turn_item.updated" && commandItem.turnItem.status === "completed", + "the silent command is no longer left as live activity on a settled run", + ); + }).pipe(Effect.provide(layerSession)), + ); + + it.effect("keeps a silent scheduled wake in its run past the command hold bound", () => + Effect.gen(function* () { + const { usage, offers, send, startTurn, until, throughPromptSettled } = + yield* openSessionWithRunningCommand({}, undefined, undefined, { + initialToolCalls: [ + { + sessionUpdate: "tool_call", + toolCallId: "call_schedule", + kind: "other", + title: "Run schedule", + status: "in_progress", + rawInput: { DurationSeconds: 3600, Prompt: "Continue the task" }, + }, + ], + }); + yield* startTurn(1, false); + yield* throughPromptSettled; + yield* TestClock.adjust("61 minutes"); + yield* send({ + sessionUpdate: "tool_call_update", + toolCallId: "call_schedule", + status: "completed", + }); + yield* send({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Picked the task back up." }, + }); + yield* send(usage); + yield* TestClock.adjust("3 seconds"); + const run = yield* until((event) => event.type === "turn.terminal"); + assert.include( + JSON.stringify(run), + "Picked the task back up.", + "the wake reply stays in the run", + ); + assert.lengthOf(offers, 0); + }).pipe(Effect.provide(layerSession)), + ); + + it.effect("keeps an unanswered question open past the command hold bound", () => + Effect.gen(function* () { + const { command, usage, send, startTurn, until, throughPromptSettled, requestPermission } = + yield* openSessionWithRunningCommand({ WaitMsBeforeAsync: 10000 }); + yield* startTurn(1, false); + yield* throughPromptSettled; + const question = yield* requestPermission( + { + sessionId: "mock-session-1", + toolCall: { toolCallId: "interaction_1", kind: "other", title: "Which port?" }, + options: [ + { optionId: "3000", name: "3000", kind: "allow_once" }, + { optionId: "8080", name: "8080", kind: "allow_once" }, + ], + }, + { requestId: "question-1", method: "session/request_permission" }, + ).pipe(Effect.forkScoped({ startImmediately: true })); + yield* TestClock.adjust("31 minutes"); + yield* Fiber.interrupt(question); + yield* send({ + sessionUpdate: "tool_call_update", + ...command, + status: "completed", + rawOutput: { output: "Command exited with code 0.", exit_code: 0 }, + }); + yield* send({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Here is the chart." }, + }); + yield* send(usage); + yield* TestClock.adjust("3 seconds"); + const run = yield* until((event) => event.type === "turn.terminal"); + assert.include(JSON.stringify(run), "Here is the chart.", "the question kept the run open"); + }).pipe(Effect.provide(layerSession)), + ); + // Command 2 finishes during reply 1; agy dequeues command 2 after reply 1's usage_update and // needs >3 s before streaming reply 2. Wait for reply 2 (bounded by the 2-minute quiet limit), // but still finalize at 3 s when both commands were batched into reply 1. diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index 3f629c813b615..c20afa04e31b8 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -41,6 +41,7 @@ import { watchAntigravityPromptOutcome } from "../../provider/acp/AntigravityTur import { antigravityApprovalOptions, antigravityToolOutlivesPrompt, + antigravityCommandOutlivesPrompt, antigravitySubagentOutput, classifyAntigravitySubagentToolCall, extractAntigravityUserInputQuestion, @@ -244,6 +245,12 @@ export function makeAntigravityAcpAdapterFlavor( wakeOnDetachedRequest: true, replyEndsWithUsageUpdate: true, toolOutlivesPrompt: antigravityToolOutlivesPrompt, + // agy sometimes loses the terminal update or wake for a background command, which would + // hold the turn in Working forever. 30 minutes still leaves long commands room. + postSettleCommandHold: { + timeout: "30 minutes", + isCommand: antigravityCommandOutlivesPrompt, + }, // session/cancel ends the agent's running commands, so only Stop sends it once the prompt // has ended. A message sent while a command runs leaves the command alone. preserveRuntimeOnSettledInterrupt: true, diff --git a/apps/server/src/provider/acp/AntigravityProtocol.ts b/apps/server/src/provider/acp/AntigravityProtocol.ts index c718667dcf42e..2e59a78e376b4 100644 --- a/apps/server/src/provider/acp/AntigravityProtocol.ts +++ b/apps/server/src/provider/acp/AntigravityProtocol.ts @@ -55,6 +55,12 @@ const ANTIGRAVITY_SCHEDULE_TITLES = new Set(["Run schedule", "Running schedule"] */ export function antigravityToolOutlivesPrompt(toolCall: AcpToolCallState): boolean { if (toolCall.title !== undefined && ANTIGRAVITY_SCHEDULE_TITLES.has(toolCall.title)) return true; + return antigravityCommandOutlivesPrompt(toolCall); +} + +/** A non-daemon command the agent awaits; unlike a schedule, it reports progress while it runs. */ +export function antigravityCommandOutlivesPrompt(toolCall: AcpToolCallState): boolean { + if (toolCall.title !== undefined && ANTIGRAVITY_SCHEDULE_TITLES.has(toolCall.title)) return false; const input = toolCall.data.rawInput; return toolCall.kind === "execute" && !(Predicate.isObject(input) && input.IsDaemon === true); } diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 21fe311588906..908c99e4eaeb3 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -637,6 +637,15 @@ export interface AcpAdapterV2Flavor { * tool ends. With `deferFinalizeForBackgroundWork`, the turn stays open until then. */ readonly toolOutlivesPrompt?: (toolCall: AcpToolCallState) => boolean; + /** + * Finalize a settled turn held only by running commands once the session has been silent for + * `timeout`, so a command that never reports back cannot leave the thread in Working forever. + * Other holds (questions, schedules, subagents) keep the turn open as before. + */ + readonly postSettleCommandHold?: { + readonly timeout: Duration.Input; + readonly isCommand: (toolCall: AcpToolCallState) => boolean; + }; readonly isProviderWakeNotification?: ( notification: EffectAcpSchema.SessionNotification, ) => boolean; @@ -2742,7 +2751,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const notePromptProgress = /* Provider events include streaming deltas; avoid a span for each update. */ Effect.fnUntraced(function* (notification?: EffectAcpSchema.SessionNotification) { - if (promptInactivityTimeoutMillis === undefined) return; + if ( + promptInactivityTimeoutMillis === undefined && + flavor.postSettleCommandHold === undefined + ) { + return; + } if ( notification !== undefined && !ACP_PROMPT_ACTIVITY_UPDATES.has(notification.update.sessionUpdate) @@ -4274,11 +4288,15 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const isMonitorEndNoticeText = (text: string): boolean => /Monitor\s+["']?[0-9a-f-]{8,}/i.test(text) && /ended/i.test(text); - const hasDeferredBackgroundWork = (context: ActiveAcpTurn): boolean => { + const hasDeferredBackgroundWork = ( + context: ActiveAcpTurn, + ignoreTool?: (tool: AcpToolCallState) => boolean, + ): boolean => { if (flavor.wakeOnDetachedRequest && agentRequests.size > 0) return true; if (flavor.toolOutlivesPrompt !== undefined) { // A tool that never started has nothing to report later. for (const tool of context.tools.values()) { + if (ignoreTool?.(tool) === true) continue; if (toolStatus(tool.status) === "running" && flavor.toolOutlivesPrompt(tool)) return true; } @@ -8835,6 +8853,39 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* options.testHooks?.onDeferredFinalizeScheduled?.(debounce) ?? Effect.void; }); + const schedulePostSettleHoldExpiry = Effect.fn("AcpAdapterV2.schedulePostSettleHoldExpiry")( + function* (context: ActiveAcpTurn) { + const hold = flavor.postSettleCommandHold; + if (hold === undefined) return; + if (!context.promptSettled || context.finalized) return; + const timeoutMillis = Duration.toMillis(hold.timeout); + const isRunningCommand = (tool: AcpToolCallState) => + toolStatus(tool.status) === "running" && hold.isCommand(tool); + let quietSince = yield* Clock.currentTimeMillis; + // Armed even without a command yet: a pending reply can still start one. + yield* Effect.gen(function* () { + while (!context.finalized) { + quietSince = Math.max(quietSince, context.lastProgressAt); + const now = yield* Clock.currentTimeMillis; + const remaining = quietSince + timeoutMillis - now; + if (remaining > 0) { + yield* Effect.sleep(Duration.millis(remaining)); + continue; + } + if ( + context.tools.values().some(isRunningCommand) && + !hasDeferredBackgroundWork(context, isRunningCommand) + ) { + yield* finalizeTurn(context, context.promptSettledStatus ?? "completed"); + return; + } + // Something else still holds the turn; count silence again once it clears. + quietSince = now; + } + }).pipe(Effect.forkIn(sessionScope), Effect.asVoid); + }, + ); + const promptInactivityPaused = Effect.fn("AcpAdapterV2.promptInactivityPaused")(function* ( context: ActiveAcpTurn, ) { @@ -9265,6 +9316,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if (context.finalized) return; if (deferredBackgroundWork || pendingReply) { yield* closeTextStreams(context); + yield* schedulePostSettleHoldExpiry(context); if (pendingReply) { context.replyOpen = true; yield* scheduleDeferredFinalize(context); @@ -9665,6 +9717,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( return; } if (!context.finalized) { + yield* schedulePostSettleHoldExpiry(context); if (hasDeferredBackgroundWork(context)) { yield* rearmDeferredFinalize(context); } else { From 5ddcc2598d0338614c2b2ea84da9470fd16be0da Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 08:31:10 -0800 Subject: [PATCH 179/324] fix(desktop): WSL is not offered or started when only the Windows install stub exists (#40918) --- .../src/wsl/DesktopWslEnvironment.test.ts | 42 ++++++++++++++++++- apps/desktop/src/wsl/DesktopWslEnvironment.ts | 42 ++++++++++++++++++- 2 files changed, 82 insertions(+), 2 deletions(-) diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts index a563b6a4ee3a7..470091f334fb7 100644 --- a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts +++ b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts @@ -555,8 +555,40 @@ describe("parseResolvedPath", () => { // Path.layer joins with POSIX separators here, so the test windir is a POSIX path. const WSL_EXE = "/windows/System32/wsl.exe"; +const STORE_SERVICE = "HKLM\\SYSTEM\\CurrentControlSet\\Services\\WSLService"; +const INBOX_SERVICE = "HKLM\\SYSTEM\\CurrentControlSet\\Services\\LxssManager"; + +const registrySpawner = (keys: ReadonlyArray) => + ChildProcessSpawner.make((command) => + Effect.succeed( + ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(1), + stdout: Stream.empty, + stderr: Stream.empty, + all: Stream.empty, + exitCode: Effect.succeed( + ChildProcessSpawner.ExitCode( + command._tag === "StandardCommand" && + command.command === "reg.exe" && + keys.some((key) => command.args.includes(key)) + ? 0 + : 1, + ), + ), + isRunning: Effect.succeed(false), + kill: () => Effect.void, + stdin: Sink.drain, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + unref: Effect.succeed(Effect.void), + }), + ), + ); -const isAvailable = (policy?: Parameters[0]) => +const isAvailable = ( + policy?: Parameters[0], + serviceKeys: ReadonlyArray = [STORE_SERVICE], +) => makeIsAvailable("win32", "/windows").pipe( Effect.provide( Layer.mergeAll( @@ -565,9 +597,17 @@ const isAvailable = (policy?: Parameters[ DesktopManagedPolicy.layerTest(policy), ), ), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, registrySpawner(serviceKeys)), ); describe("makeIsAvailable", () => { + it.effect("needs a registered WSL service, not just the System32 install stub", () => + Effect.gen(function* () { + assert.isFalse(yield* isAvailable(undefined, [])); + assert.isTrue(yield* isAvailable(undefined, [INBOX_SERVICE])); + }), + ); + it.effect("turns WSL off on a machine with a managed policy, even an invalid one", () => Effect.gen(function* () { assert.isTrue(yield* isAvailable()); diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.ts index f1d2fccde537b..9d9540a65dc7d 100644 --- a/apps/desktop/src/wsl/DesktopWslEnvironment.ts +++ b/apps/desktop/src/wsl/DesktopWslEnvironment.ts @@ -1119,13 +1119,50 @@ const getUserHomeImpl = ( Effect.orElseSucceed(() => Option.none()), ); +// Store/MSI WSL registers WSLService and inbox WSL registers LxssManager; either key means installed. +const WSL_SERVICE_KEYS = [ + "HKLM\\SYSTEM\\CurrentControlSet\\Services\\WSLService", + "HKLM\\SYSTEM\\CurrentControlSet\\Services\\LxssManager", +] as const; +const SERVICE_QUERY_TIMEOUT = Duration.seconds(5); + +const wslServiceRegistered = Effect.scoped( + Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const registered = yield* Effect.forEach( + WSL_SERVICE_KEYS, + (key) => + spawner + .spawn( + ChildProcess.make("reg.exe", ["query", key], { + stdin: "ignore", + stdout: "ignore", + stderr: "ignore", + killSignal: "SIGTERM", + forceKillAfter: PROCESS_TERMINATE_GRACE, + }), + ) + .pipe(Effect.flatMap((handle) => handle.exitCode)), + { concurrency: "unbounded" }, + ); + return registered.some((exitCode) => (exitCode as unknown as number) === 0); + }), +).pipe( + Effect.timeoutOption(SERVICE_QUERY_TIMEOUT), + Effect.map(Option.getOrElse(() => false)), + Effect.orElseSucceed(() => false), +); + export const makeIsAvailable = Effect.fn("DesktopWslEnvironment.makeIsAvailable")(function* ( platform: NodeJS.Platform, windir: string, ): Effect.fn.Return< boolean, never, - FileSystem.FileSystem | Path.Path | DesktopManagedPolicy.DesktopManagedPolicy + | FileSystem.FileSystem + | Path.Path + | DesktopManagedPolicy.DesktopManagedPolicy + | ChildProcessSpawner.ChildProcessSpawner > { if (platform !== "win32") return false; const path = yield* Path.Path; @@ -1134,6 +1171,8 @@ export const makeIsAvailable = Effect.fn("DesktopWslEnvironment.makeIsAvailable" if (!(yield* fileSystem.exists(wslExePath).pipe(Effect.orElseSucceed(() => false)))) { return false; } + // System32\wsl.exe is also an install stub on Windows without WSL, so check for its service. + if (!(yield* wslServiceRegistered)) return false; // A server in WSL reads Linux's policy, never this machine's, so a managed machine runs none. return yield* (yield* DesktopManagedPolicy.DesktopManagedPolicy).read.pipe( Effect.map((found) => found === undefined), @@ -1245,6 +1284,7 @@ export const layer = Layer.effect( // Cache availability so synchronous IPC bootstrap can read it without yielding to filesystem I/O. const wslAvailable = yield* makeIsAvailable(environment.platform, windir).pipe( Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), Effect.provideService(Path.Path, environment.path), Effect.provideService( DesktopManagedPolicy.DesktopManagedPolicy, From ad446450e1cd66763cf03ed5c4b012913826f5d7 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 08:33:25 -0800 Subject: [PATCH 180/324] fix(server): idle /ws connections behind a reverse proxy no longer drop every 60s (#40932) --- apps/server/src/socketHeartbeat.test.ts | 39 +++++++++++++++++++++++++ apps/server/src/socketHeartbeat.ts | 27 +++++++++++++++++ apps/server/src/ws.ts | 30 ++++++++++--------- 3 files changed, 82 insertions(+), 14 deletions(-) create mode 100644 apps/server/src/socketHeartbeat.test.ts create mode 100644 apps/server/src/socketHeartbeat.ts diff --git a/apps/server/src/socketHeartbeat.test.ts b/apps/server/src/socketHeartbeat.test.ts new file mode 100644 index 0000000000000..2cb002bbf8862 --- /dev/null +++ b/apps/server/src/socketHeartbeat.test.ts @@ -0,0 +1,39 @@ +import { assert, describe, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Scope from "effect/Scope"; +import * as Socket from "effect/socket/Socket"; +import * as TestClock from "effect/testing/TestClock"; + +import { + SOCKET_HEARTBEAT_FRAME, + SOCKET_HEARTBEAT_INTERVAL, + withSocketHeartbeat, +} from "./socketHeartbeat.ts"; + +describe("withSocketHeartbeat", () => { + it.effect("writes a heartbeat each interval until the writer's scope closes", () => + Effect.gen(function* () { + const written: Array = []; + const socket = withSocketHeartbeat( + Socket.make({ + reader: Effect.never, + writer: Effect.succeed({ + write: (chunk) => Effect.sync(() => void written.push(chunk)), + writeAll: (chunks) => Effect.sync(() => void written.push(...chunks)), + }), + }), + ); + const scope = yield* Scope.make(); + yield* Scope.provide(socket.writer, scope); + + yield* TestClock.adjust(SOCKET_HEARTBEAT_INTERVAL); + yield* TestClock.adjust(SOCKET_HEARTBEAT_INTERVAL); + assert.deepStrictEqual(written, [SOCKET_HEARTBEAT_FRAME, SOCKET_HEARTBEAT_FRAME]); + + yield* Scope.close(scope, Exit.void); + yield* TestClock.adjust(SOCKET_HEARTBEAT_INTERVAL); + assert.strictEqual(written.length, 2); + }), + ); +}); diff --git a/apps/server/src/socketHeartbeat.ts b/apps/server/src/socketHeartbeat.ts new file mode 100644 index 0000000000000..6ffd9c9cf785c --- /dev/null +++ b/apps/server/src/socketHeartbeat.ts @@ -0,0 +1,27 @@ +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Socket from "effect/socket/Socket"; + +// Reverse proxies close a socket after 60 seconds without upstream bytes +// (nginx proxy_read_timeout, AWS ALB), and a suspended client stops pinging. +export const SOCKET_HEARTBEAT_INTERVAL = Duration.seconds(20); + +// RPC clients count any decoded frame as liveness and ignore unsolicited pongs. +export const SOCKET_HEARTBEAT_FRAME = '{"_tag":"Pong"}'; + +/** Server side: writes a heartbeat frame on an interval for as long as the writer is open. */ +export function withSocketHeartbeat(socket: Socket.Socket): Socket.Socket { + return Socket.make({ + reader: socket.reader, + writer: Effect.tap(socket.writer, (writer) => + writer + .write(SOCKET_HEARTBEAT_FRAME) + .pipe( + Effect.delay(SOCKET_HEARTBEAT_INTERVAL), + Effect.forever, + Effect.ignore, + Effect.forkScoped, + ), + ), + }); +} diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index ddd07fcfad656..d1db4372ab871 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -201,6 +201,7 @@ import * as StorageCleanup from "./storageCleanup.ts"; import * as TerminalManager from "./terminal/Manager.ts"; import { makePrepareTerminalLaunch } from "./workspace/restoreMissingWorktree.ts"; import { terminalOutputStream, withOutputWindow } from "./terminal/OutputProtocol.ts"; +import { withSocketHeartbeat } from "./socketHeartbeat.ts"; import * as ServerBrowser from "./preview/ServerBrowser.ts"; import * as DeviceService from "./device/DeviceService.ts"; import { remoteSshDeviceHosts } from "./device/localSshDeviceHost.ts"; @@ -3826,20 +3827,21 @@ export const layer = Layer.unwrap( ), ), ); - const framedRpcWebSocketHttpEffect = url.value.searchParams.has( - SOCKET_FRAME_PARTS_QUERY_PARAM, - ) - ? rpcWebSocketHttpEffect.pipe( - Effect.provideService( - HttpServerRequest.HttpServerRequest, - // The RPC server upgrades the request itself, so its socket is - // wrapped through the request it reads. - Object.create(request, { - upgrade: { value: Effect.map(request.upgrade, splitLargeSocketFrames) }, - }), - ), - ) - : rpcWebSocketHttpEffect; + const splitFrames = url.value.searchParams.has(SOCKET_FRAME_PARTS_QUERY_PARAM); + const framedRpcWebSocketHttpEffect = rpcWebSocketHttpEffect.pipe( + Effect.provideService( + HttpServerRequest.HttpServerRequest, + // The RPC server upgrades the request itself, so its socket is + // wrapped through the request it reads. + Object.create(request, { + upgrade: { + value: Effect.map(request.upgrade, (socket) => + withSocketHeartbeat(splitFrames ? splitLargeSocketFrames(socket) : socket), + ), + }, + }), + ), + ); return yield* Effect.acquireUseRelease( sessions.markConnected(session.sessionId), () => From cc4bb17955287e5a7ad2a64b05f491879ee888fa Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 08:42:51 -0800 Subject: [PATCH 181/324] fix(server): thread reads no longer attribute T3 Code's compact-before-send /compact to the user (#40934) --- apps/server/src/cli/thread.ts | 7 +- .../OrchestratorMcpService.activity.test.ts | 129 ++++++++++++++++++ apps/server/src/mcp/OrchestratorMcpService.ts | 4 +- 3 files changed, 138 insertions(+), 2 deletions(-) diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts index 09ee65c32172b..48d62fb4575b7 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -1024,7 +1024,12 @@ const threadShowCommand = Command.make("show", { const messages = yield* Effect.forEach(latest, (item) => readFullText(tools, threadId, item).pipe( Effect.map((text) => ({ - role: item.type === "user_message" ? "user" : "assistant", + role: + item.type === "assistant_message" + ? "assistant" + : item.createdBy === "system" + ? "system" + : "user", runId: item.runId, text, })), diff --git a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts b/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts index a0953eb509e5f..cbe4be1e4b42f 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts @@ -1,5 +1,6 @@ import { EnvironmentId, + MessageId, NodeId, type OrchestratorMcpThreadReadResult, type OrchestrationV2ThreadProjection, @@ -431,6 +432,134 @@ it("readThread pages cut-off text without splitting an emoji across pages", asyn }).pipe(Effect.provide(layer), Effect.runPromise); }); +it("readThread does not attribute the /compact T3 Code sends before a stale send to the user", async () => { + const compactRunId = RunId.make("run-mcp-compact-on-return"); + const sendRunId = RunId.make("run-mcp-held-send"); + const compactMessageId = MessageId.make("message-mcp-compact-on-return"); + const sendMessageId = MessageId.make("message-mcp-held-send"); + const projection = { + thread: baseThread({ + threadId: parentThreadId, + title: "Parent", + instanceId: parentInstanceId, + model: "gpt-5.4", + }), + runs: [ + makeRun({ id: compactRunId, ordinal: 1, status: "completed" }), + makeRun({ id: sendRunId, ordinal: 2, status: "completed" }), + ], + visibleTurnItems: [], + providerTurns: [], + runtimeRequests: [], + messages: [ + { + id: compactMessageId, + threadId: parentThreadId, + runId: compactRunId, + role: "user", + text: "/compact", + attachments: [], + createdBy: "user", + creationSource: "web", + idleCompaction: "onReturn", + }, + { + id: sendMessageId, + threadId: parentThreadId, + runId: sendRunId, + role: "user", + text: "use webgpu", + attachments: [], + createdBy: "user", + creationSource: "web", + }, + ], + contextTransfers: [], + subagents: [], + updatedAt: now, + } as unknown as OrchestrationV2ThreadProjection; + const userRow = (position: number, runId: RunId, messageId: MessageId, text: string) => ({ + position, + visibility: "visible", + sourceThreadId: parentThreadId, + sourceItemId: TurnItemId.make(`turn-item-mcp-user-${position}`), + item: { + type: "user_message", + runId, + messageId, + status: "completed", + title: null, + text, + attachments: [], + updatedAt: now, + }, + }); + const rows = [ + userRow(0, compactRunId, compactMessageId, "/compact"), + { + position: 1, + visibility: "visible", + sourceThreadId: parentThreadId, + sourceItemId: TurnItemId.make("turn-item-mcp-compaction"), + item: { + type: "compaction", + runId: compactRunId, + status: "completed", + title: null, + summary: "Context compacted", + updatedAt: now, + }, + }, + userRow(2, sendRunId, sendMessageId, "use webgpu"), + ]; + + const layer = layerOrchestratorService.pipe( + Layer.provide( + Layer.mergeAll( + Layer.mock(ThreadManagementService.ThreadManagementService)({ + getTimelinePage: () => + Effect.succeed({ + items: rows as unknown as OrchestrationV2ThreadProjection["visibleTurnItems"], + totalItems: rows.length, + hasMore: false, + hasEarlier: false, + }), + getThreadRecords: () => Effect.succeed(projection), + getProjectThreadRecords: () => Effect.succeed(projection), + getRunCount: () => Effect.succeed(projection.runs.length), + getThreadShell: () => + Effect.succeed(projection.thread as unknown as OrchestrationV2ThreadShell), + } satisfies Partial), + ServerSettings.layerTest(), + Layer.mock(ProviderRegistry.ProviderRegistry)({ + getProviders: Effect.succeed([]), + } satisfies Partial), + Layer.mock(ProjectService.ProjectService)({}), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(RemoteDelegation.RemoteDelegation)({}), + Layer.mock(ScheduledTaskService.ScheduledTaskService)({ + list: () => Effect.succeed({ tasks: [] }), + } satisfies Partial), + Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({ + list: () => Effect.succeed([]), + } satisfies Partial), + NodeCrypto.layer, + ), + ), + ); + + await Effect.gen(function* () { + const service = yield* OrchestratorMcpService.OrchestratorMcpService; + for (const view of ["activity", "messages"] as const) { + const result = yield* service.readThread(makeScope(), { threadId: parentThreadId, view }); + const fromUser = result.items.filter( + (item) => item.type === "user_message" && item.createdBy === "user", + ); + expect(fromUser.map((item) => item.text)).toEqual(["use webgpu"]); + } + }).pipe(Effect.provide(layer), Effect.runPromise); +}); + it("readThread returns the newest items that fit the response budget", async () => { const projection = { thread: baseThread({ diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index f9ad32a6e1d3e..156555c74d695 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -1,6 +1,7 @@ import { CommandId, type RunId, + idleCompactionOf, isProviderAvailable, MessageId, type ModelSelection, @@ -1228,7 +1229,8 @@ function timelineItem(input: { ...(input.row.item.type === "subagent" ? { subagentId: input.row.item.subagentId } : {}), runId: input.row.item.runId, messageId, - createdBy: message?.createdBy ?? null, + createdBy: + message === undefined ? null : idleCompactionOf(message) ? "system" : message.createdBy, creationSource: message?.creationSource ?? null, ...(message?.senderThreadId === undefined ? {} : { senderThreadId: message.senderThreadId }), type: input.row.item.type, From 9de4ec1bfa0b222e71f8fc2ed71257c1c1d1a281 Mon Sep 17 00:00:00 2001 From: tiliakoos <73005126+tiliakoos@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:49:19 +0100 Subject: [PATCH 182/324] fix(web,mobile): @-file mentions show by name in message previews, not as raw links (#40924) --- .../threads/threadQueueControlPresentation.ts | 5 ++- .../src/components/chat/ComposerStashMenu.tsx | 5 ++- .../src/components/chat/QueuedRunsControl.tsx | 5 ++- .../components/sidebar/SidebarDraftBlock.tsx | 5 ++- .../src/operations/threadTitle.ts | 3 +- .../shared/src/composerInlineTokens.test.ts | 14 +++++++ packages/shared/src/composerInlineTokens.ts | 15 ++++++++ ...-message-shows-file-mention-by-name.e2e.ts | 37 +++++++++++++++++++ 8 files changed, 84 insertions(+), 5 deletions(-) create mode 100644 scripts/scenarios/queued-message-shows-file-mention-by-name.e2e.ts diff --git a/apps/mobile/src/features/threads/threadQueueControlPresentation.ts b/apps/mobile/src/features/threads/threadQueueControlPresentation.ts index 8a6ed2e03085a..50a004d679003 100644 --- a/apps/mobile/src/features/threads/threadQueueControlPresentation.ts +++ b/apps/mobile/src/features/threads/threadQueueControlPresentation.ts @@ -5,6 +5,7 @@ import { isAttachmentOnlyBootstrapPrompt, replaceComposerContextReferences, } from "@t3tools/shared/composerContextReferences"; +import { composerFileLinksToPlainText } from "@t3tools/shared/composerInlineTokens"; export const REMOVE_QUEUED_MESSAGE_ACCESSIBILITY_LABEL = msg("Remove queued message"); @@ -43,7 +44,9 @@ export function resolveThreadQueueRowControls(input: { displayText: isAttachmentOnlyBootstrapPrompt(input.text) ? "" : assistantCitationsToPlainText( - replaceComposerContextReferences(input.text, (reference) => reference.label), + composerFileLinksToPlainText( + replaceComposerContextReferences(input.text, (reference) => reference.label), + ), ).trim(), isEditing, }; diff --git a/apps/web/src/components/chat/ComposerStashMenu.tsx b/apps/web/src/components/chat/ComposerStashMenu.tsx index c55d843510080..46e3fec307bf1 100644 --- a/apps/web/src/components/chat/ComposerStashMenu.tsx +++ b/apps/web/src/components/chat/ComposerStashMenu.tsx @@ -3,6 +3,7 @@ import { BookmarkIcon, FileIcon, FileTextIcon } from "lucide-react"; import { memo, useEffect, useEffectEvent, useRef, useState, type RefObject } from "react"; import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations"; import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences"; +import { composerFileLinksToPlainText } from "@t3tools/shared/composerInlineTokens"; import { RelativeTime } from "../RelativeTime"; import { m, type MessageResolver } from "~/i18n/messages"; @@ -18,7 +19,9 @@ function missingImageCount(entry: PromptStashEntry): number { export function stashEntrySnippet(entry: PromptStashEntry, resolve: MessageResolver = m): string { const trimmed = assistantCitationsToPlainText( - replaceComposerContextReferences(entry.prompt, (reference) => reference.label), + composerFileLinksToPlainText( + replaceComposerContextReferences(entry.prompt, (reference) => reference.label), + ), ) .trim() .replace(/\s+/g, " "); diff --git a/apps/web/src/components/chat/QueuedRunsControl.tsx b/apps/web/src/components/chat/QueuedRunsControl.tsx index d8318b7279e7d..20ea71f88adcd 100644 --- a/apps/web/src/components/chat/QueuedRunsControl.tsx +++ b/apps/web/src/components/chat/QueuedRunsControl.tsx @@ -10,6 +10,7 @@ import { isAttachmentOnlyBootstrapPrompt, replaceComposerContextReferences, } from "@t3tools/shared/composerContextReferences"; +import { composerFileLinksToPlainText } from "@t3tools/shared/composerInlineTokens"; import { parseGoalCommand, type ChatAttachment as ContractChatAttachment, @@ -272,7 +273,9 @@ export function QueuedRunsControl({ const previewText = isAttachmentOnlyBootstrapPrompt(item.text) ? "" : assistantCitationsToPlainText( - replaceComposerContextReferences(item.text, (reference) => reference.label), + composerFileLinksToPlainText( + replaceComposerContextReferences(item.text, (reference) => reference.label), + ), ).trim(); const isEditing = item.runId !== null && item.runId === props.editingRunId; // The server decides on the agent's text, and a goal command can stop the turn. diff --git a/apps/web/src/components/sidebar/SidebarDraftBlock.tsx b/apps/web/src/components/sidebar/SidebarDraftBlock.tsx index 4cb082a1f7ddd..e0b0d92a764ac 100644 --- a/apps/web/src/components/sidebar/SidebarDraftBlock.tsx +++ b/apps/web/src/components/sidebar/SidebarDraftBlock.tsx @@ -3,6 +3,7 @@ import type { ContextMenuSource } from "@t3tools/contracts"; import { contextMenuSourceOf } from "../../contextMenuSource"; import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations"; import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences"; +import { composerFileLinksToPlainText } from "@t3tools/shared/composerInlineTokens"; import { T, useGT } from "gt-react"; import { SquarePenIcon, XIcon } from "lucide-react"; import { @@ -85,7 +86,9 @@ const SidebarDraftRow = memo(function SidebarDraftRow(props: { const gt = useGT(); const promptPreview = assistantCitationsToPlainText( - replaceComposerContextReferences(composer.prompt, (occurrence) => occurrence.label), + composerFileLinksToPlainText( + replaceComposerContextReferences(composer.prompt, (occurrence) => occurrence.label), + ), ) .trim() .split("\n", 1)[0] ?? ""; diff --git a/packages/client-runtime/src/operations/threadTitle.ts b/packages/client-runtime/src/operations/threadTitle.ts index 0f57de34036a5..bb1fcd7648dbf 100644 --- a/packages/client-runtime/src/operations/threadTitle.ts +++ b/packages/client-runtime/src/operations/threadTitle.ts @@ -3,6 +3,7 @@ import type { MFunctionType } from "gt-i18n/types"; import type { ChatAttachment } from "@t3tools/contracts"; import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations"; import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences"; +import { composerFileLinksToPlainText } from "@t3tools/shared/composerInlineTokens"; import { truncate } from "@t3tools/shared/String"; import { collectComposerModelMentions } from "../composerModelMentions.ts"; @@ -45,7 +46,7 @@ export function threadTitleTextFromPrompt( return reference.label; }); return ( - normalizeTitleSeed(modelMentionsAsSlugs(prose)) || + normalizeTitleSeed(modelMentionsAsSlugs(composerFileLinksToPlainText(prose))) || (imageIds.size > 0 ? attachedImagesTitle(imageIds.size, resolve) : "") ); } diff --git a/packages/shared/src/composerInlineTokens.test.ts b/packages/shared/src/composerInlineTokens.test.ts index 5317347aad13b..c8c17b84a9b7b 100644 --- a/packages/shared/src/composerInlineTokens.test.ts +++ b/packages/shared/src/composerInlineTokens.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it } from "vite-plus/test"; import { collectComposerInlineTokens as collectWithoutMath, type CollectComposerInlineTokensOptions, + composerFileLinksToPlainText, composerMathRanges, } from "./composerInlineTokens.ts"; import { markdownMathRanges } from "./markdownMath.ts"; @@ -230,3 +231,16 @@ describe("collectComposerInlineTokens", () => { ).toEqual(["$x_i$"]); }); }); + +describe("composerFileLinksToPlainText", () => { + it("shows file mentions by name and leaves other links as written", () => { + const mentions = ["src/foo.ts", ".gitignore", "pkg/__init__.py", "docs/My File (draft).md"] + .map(serializeComposerFileLink) + .join(" "); + expect(composerFileLinksToPlainText(`Review ${mentions}`)).toBe( + "Review foo.ts .gitignore __init__.py My File (draft).md", + ); + const links = "See [docs](https://example.com) and [the config](src/config.ts)"; + expect(composerFileLinksToPlainText(links)).toBe(links); + }); +}); diff --git a/packages/shared/src/composerInlineTokens.ts b/packages/shared/src/composerInlineTokens.ts index b11a42b74a945..80a1b4d6916ae 100644 --- a/packages/shared/src/composerInlineTokens.ts +++ b/packages/shared/src/composerInlineTokens.ts @@ -1,3 +1,5 @@ +import { fileBasename } from "./path.ts"; + /** The formulas a Markdown parser finds in text, as source offsets. */ export type FindMathRanges = ( text: string, @@ -173,3 +175,16 @@ export function collectComposerInlineTokens( ) .sort((left, right) => left.start - right.start); } + +/** Shows each `@`-file link by its file name, as its composer chip does, for one-line previews. */ +export function composerFileLinksToPlainText(text: string): string { + let result = ""; + let cursor = 0; + // The composer reads a link as a mention only before whitespace, so one may end the text. + for (const token of collectMentionTokens(`${text} `)) { + if (!token.source.startsWith("[")) continue; + result += text.slice(cursor, token.start) + fileBasename(token.value); + cursor = token.end; + } + return result + text.slice(cursor); +} diff --git a/scripts/scenarios/queued-message-shows-file-mention-by-name.e2e.ts b/scripts/scenarios/queued-message-shows-file-mention-by-name.e2e.ts new file mode 100644 index 0000000000000..8ee5453bbba20 --- /dev/null +++ b/scripts/scenarios/queued-message-shows-file-mention-by-name.e2e.ts @@ -0,0 +1,37 @@ +import { expect } from "e2e"; + +import { T3_HOME } from "../e2e.config.ts"; +import { makeState, runPromise, test, WEB } from "./t3.ts"; + +test( + "A queued message shows its @-file mention by name, not as a raw link", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo", { "src/foo.ts": "export {};\n" }); + const thread = await t3.thread({ + project, + title: "Long work", + messages: ["Show me around"], + model: "showcase", + }); + await t3.open(thread); + + const composer = screen.getByRole("textbox"); + await composer.pressSequentially("Review @foo"); + await screen.getByRole("option", "foo.ts", { exact: false }).tap(); + await expect(composer).toContainText("foo.ts"); + + // The showcase recording streams for several seconds, long enough to queue behind its turn. + await runPromise(makeState(T3_HOME).cli(["thread", "send", thread.threadId, "Show me again"])); + await screen.getByText("Working for", { exact: false }).waitFor(); + // Enter steers by default; the alternate send queues. + await browser.keyboard.press("ControlOrMeta+Enter"); + + const queued = screen.getByRole("listitem", "Queued message 1 of 1, not sent"); + await queued.waitFor(); + // Read the row once: the queued message sends, and its row goes, when the turn ends. + const text = await queued.textContent(); + await app.screenshot("queued-row"); + expect(text).toContain("Review foo.ts"); + }, +); From 7ddc81d639aa75ca6e0cbffb0f394ea3f0d83308 Mon Sep 17 00:00:00 2001 From: Matthew Waters Date: Sun, 22 Nov 2026 17:10:23 +0000 Subject: [PATCH 183/324] fix(web): tool calls stay grouped after a usage-limit pause again (#40905) --- apps/web/src/components/ChatView.tsx | 6 +++++ .../chat/MessagesTimeline.logic.test.ts | 24 ++++++++++++++++++- .../components/chat/MessagesTimeline.logic.ts | 11 +++++++-- .../src/components/chat/MessagesTimeline.tsx | 3 +++ 4 files changed, 41 insertions(+), 3 deletions(-) diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index d17af4f620755..4f1d764ffef29 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -1085,6 +1085,11 @@ export default function ChatView(props: ChatViewProps) { recovery: activeThreadShell?.limitRecovery, snoozedUntil: activeThreadShell?.snoozedUntil, }); + // The run whose limit rows client-runtime hides (deriveUsageLimitNoticeRows). + const usageLimitRunId = + serverRuntime?.status === "failed" && serverRuntime.lastErrorClass === "usage_limit" + ? (serverLatestRun?.runId ?? null) + : null; const timelineThreadError = limitRecoveryRun !== null && visibleThreadError === serverRuntime?.lastError ? null @@ -3644,6 +3649,7 @@ export default function ChatView(props: ChatViewProps) { listRef={legendListRef} runs={serverProjection?.runs ?? []} latestRun={activeActivityRun} + usageLimitRunId={usageLimitRunId} announcedRun={announcedRun(activeActivityRun, serverProjection?.runs ?? [])} detailBehindShell={isDetailBehindShell( activeLatestRun, diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index 0a703a675f0ac..76dc0aa6471bf 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -4744,7 +4744,29 @@ describe("failed turn transcript", () => { ); expect(work.at(-1)?.detail).toBe("The provider stopped this turn.\nRetry later."); expect(work.at(-1)?.createdAt).toBe("2026-09-20T12:00:00.000Z"); - if (isLatest) return; + if (isLatest) { + // The recovery notice hides the failure row; the run's work stays grouped. + const noticeRows = deriveMessagesTimelineRows({ + timelineEntries: deriveTimelineEntriesFromVisibleTurnItems({ + visibleTurnItems: items.filter((row) => row.item.type !== "error"), + optimisticMessages: [], + }), + latestRun: { + runId, + status: "failed", + startedAt: DateTime.formatIso(at), + completedAt: DateTime.formatIso(at), + }, + usageLimitRunId: runId, + isWorking: false, + turnDiffSummaries: [], + supportsConversationRollback: false, + }); + expect(noticeRows.find((row) => row.kind === "work-toggle")).toEqual( + expect.objectContaining({ hiddenCount: 3, expanded: false }), + ); + return; + } const entriesWithoutTools = deriveTimelineEntriesFromVisibleTurnItems({ visibleTurnItems: items.filter((row) => row.item.type !== "command_execution"), optimisticMessages: [], diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index b00a48185b9db..2d920ad816277 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -1056,8 +1056,9 @@ function failedTimelineRunIds( function itemizedFailedRunIds( entries: ReadonlyArray, failedRunIds: ReadonlySet, + usageLimitRunId: RunId | null, ) { - const usageLimited = new Set(); + const usageLimited = new Set(usageLimitRunId ? [usageLimitRunId] : []); const otherFailures = new Set(); for (const entry of entries) { const item = timelineEntryFailedItem(entry); @@ -1612,6 +1613,8 @@ export function deriveMessagesTimelineRows( timelineEntries: ReadonlyArray; pendingApprovalRequestIds?: ReadonlySet; latestRun?: TimelineLatestRun | null; + /** The usage-limited run whose failure row the recovery notice replaces. */ + usageLimitRunId?: RunId | null; runningRunId?: RunId | null; expandedRunIds?: ReadonlySet; expandedAttemptIds?: ReadonlySet; @@ -1663,7 +1666,11 @@ export function deriveMessagesTimelineRows( const nextRows: MessagesTimelineRow[] = []; const terminalAssistantMessageIds = deriveTerminalAssistantMessageIds(timelineEntries); const failedRunIds = failedTimelineRunIds(timelineEntries, input.latestRun ?? null); - const itemizedRunIds = itemizedFailedRunIds(timelineEntries, failedRunIds); + const itemizedRunIds = itemizedFailedRunIds( + timelineEntries, + failedRunIds, + input.usageLimitRunId ?? null, + ); const liveSubagentEntryIds = liveSubagentCardEntryIds(timelineEntries); const retainedAssistantReplyIds = retainedAssistantReplyEntryIds(timelineEntries); const supersededFoldsByAnchorEntryId = deriveSupersededAttemptFolds( diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 89cc3f8701c55..fe60471993e36 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -257,6 +257,7 @@ interface MessagesTimelineProps { listRef: React.RefObject; timelineEntries: ReadonlyArray; latestRun: TimelineLatestRun | null; + usageLimitRunId?: RunId | null; /** The run the screen reader announcer follows; see announcedRun. */ announcedRun?: { readonly runId: RunId; readonly status: TimelineLatestRun["status"] } | null; /** See isDetailBehindShell. */ @@ -381,6 +382,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ activeFindMatch = null, findNavigationId = 0, latestRun, + usageLimitRunId = null, announcedRun = null, detailBehindShell = false, runningRunId = null, @@ -748,6 +750,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ timelineEntries, pendingApprovalRequestIds, latestRun, + usageLimitRunId, runningRunId, expandedRunIds: visibleExpandedRunIds, expandedAttemptIds: visibleExpandedAttemptIds, From ec35ad6618ea8ca72069b3f35198786deabb550a Mon Sep 17 00:00:00 2001 From: tiliakoos <73005126+tiliakoos@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:00:38 +0100 Subject: [PATCH 184/324] fix(server): t3 doctor no longer reports a database just under 1 GiB as "1024.0 MiB" (#40952) Co-authored-by: MarcoDotIO <20867620+MarcoDotIO@users.noreply.github.com> --- apps/server/src/cli/doctor.test.ts | 28 ++++++++++++++++++++++++++++ apps/server/src/cli/doctor.ts | 14 +++++++++----- 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/apps/server/src/cli/doctor.test.ts b/apps/server/src/cli/doctor.test.ts index 6315378d07cb8..44dfd1bc27eff 100644 --- a/apps/server/src/cli/doctor.test.ts +++ b/apps/server/src/cli/doctor.test.ts @@ -8,6 +8,7 @@ import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import * as TestClock from "effect/testing/TestClock"; +import * as TestConsole from "effect/testing/TestConsole"; import * as BootService from "../cloud/bootService.ts"; import { runDoctor } from "./doctor.ts"; @@ -118,6 +119,33 @@ it.effect( }).pipe(Effect.provide(layerHost)), ); +it.effect("reports sizes just under the next unit in that unit", () => + Effect.gen(function* () { + yield* runDoctor( + { dbPath: "/test/statev2.sqlite", serverRuntimeStatePath: "/test/server-runtime.json" }, + { fix: false, dryRun: true }, + ).pipe( + Effect.provide( + Layer.mergeAll( + Layer.mock(BootService.BootService)({}), + Layer.mock(DatabaseMaintenance)({ + inspect: () => + Effect.succeed({ + databaseBytes: 1024 ** 3 - 4096, + reclaimableBytes: 1024 ** 2 - 512, + incrementalVacuumEnabled: true, + legacyDatabaseBytes: null, + legacyOnlyRecords: null, + }), + }), + ), + ), + ); + const [summary] = yield* TestConsole.logLines; + assert.strictEqual(summary, "Database: 1.00 GiB, 1.0 MiB reclaimable."); + }).pipe(Effect.provide(Layer.merge(layerHost, TestConsole.layer))), +); + it.effect("warns how long reclaiming can take and reports each step with its elapsed time", () => Effect.gen(function* () { const output: string[] = []; diff --git a/apps/server/src/cli/doctor.ts b/apps/server/src/cli/doctor.ts index 50cd852e5b4b1..60af29ac41e7b 100644 --- a/apps/server/src/cli/doctor.ts +++ b/apps/server/src/cli/doctor.ts @@ -13,12 +13,16 @@ import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntim import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts"; import * as CliService from "./service.ts"; -const formatBytes = (bytes: number) => - bytes >= 1024 ** 3 +// Pick the unit after rounding, so a size just under 1 GiB reads "1.00 GiB", not "1024.0 MiB". +const formatBytes = (bytes: number) => { + const mebibytes = (bytes / 1024 ** 2).toFixed(1); + const kibibytes = Math.ceil(bytes / 1024); + return Number(mebibytes) >= 1024 ? `${(bytes / 1024 ** 3).toFixed(2)} GiB` - : bytes >= 1024 ** 2 - ? `${(bytes / 1024 ** 2).toFixed(1)} MiB` - : `${Math.ceil(bytes / 1024)} KiB`; + : kibibytes >= 1024 + ? `${mebibytes} MiB` + : `${kibibytes} KiB`; +}; const formatElapsed = (nanos: bigint) => { const seconds = Number(nanos / 1_000_000_000n); From 69720261214c047e583b494675ea9624bbe3a00a Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:02:10 +0100 Subject: [PATCH 185/324] fix(web): show clone failure after progress is dismissed (#40951) Co-authored-by: Julius Marminge --- .../ProjectCloneToastCoordinator.tsx | 57 +++++---- ...e-failure-after-dismissing-progress.e2e.ts | 113 ++++++++++++++++++ 2 files changed, 148 insertions(+), 22 deletions(-) create mode 100644 scripts/scenarios/clone-failure-after-dismissing-progress.e2e.ts diff --git a/apps/web/src/components/ProjectCloneToastCoordinator.tsx b/apps/web/src/components/ProjectCloneToastCoordinator.tsx index 846644c537a12..778c195e2d29e 100644 --- a/apps/web/src/components/ProjectCloneToastCoordinator.tsx +++ b/apps/web/src/components/ProjectCloneToastCoordinator.tsx @@ -45,6 +45,8 @@ interface TrackedToast { readonly toastId: ReturnType; readonly renderedKey: string; readonly phase: ProjectCloneSnapshot["phase"]; + readonly startedAt: ProjectCloneSnapshot["startedAt"]; + readonly closed?: true; } function renderKey(clone: ProjectCloneSnapshot): string { @@ -98,6 +100,7 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI seen.add(clone.projectId); const key = renderKey(clone); const tracked = toasts.current.get(clone.projectId); + const sameAttempt = tracked?.startedAt === clone.startedAt; const name = projectCloneDisplayName(clone); const closeToast = () => { const current = toasts.current.get(clone.projectId); @@ -111,7 +114,7 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI closeToast(); continue; } - if (tracked?.renderedKey === key) continue; + if (sameAttempt && tracked.renderedKey === key) continue; if ( isProjectCloneToastSilenced(ref) && (clone.phase === "running" || clone.phase === "done") @@ -119,6 +122,34 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI closeToast(); continue; } + if ( + sameAttempt && + tracked.closed && + (tracked.phase !== "running" || clone.phase !== "failed") + ) { + continue; + } + + const showToast = (options: ReturnType) => { + const rendered = { renderedKey: key, phase: clone.phase, startedAt: clone.startedAt }; + if (tracked && !tracked.closed) { + toastManager.update(tracked.toastId, options); + toasts.current.set(clone.projectId, { toastId: tracked.toastId, ...rendered }); + return; + } + + const toastId = toastManager.add({ + ...options, + // Updates to a closing toast are ignored, even before it has been removed. + onClose: () => { + const current = toasts.current.get(clone.projectId); + if (current?.toastId === toastId) { + toasts.current.set(clone.projectId, { ...current, closed: true }); + } + }, + }); + toasts.current.set(clone.projectId, { toastId, ...rendered }); + }; if (clone.phase === "running") { const options = stackedThreadToast({ @@ -136,13 +167,7 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI }, data: { hideCopyButton: true }, }); - if (tracked) { - toastManager.update(tracked.toastId, options); - toasts.current.set(clone.projectId, { ...tracked, renderedKey: key, phase: "running" }); - } else { - const toastId = toastManager.add(options); - toasts.current.set(clone.projectId, { toastId, renderedKey: key, phase: "running" }); - } + showToast(options); continue; } @@ -161,13 +186,7 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI }, data: { hideCopyButton: true }, }); - if (tracked) { - toastManager.update(tracked.toastId, options); - toasts.current.set(clone.projectId, { ...tracked, renderedKey: key, phase: "done" }); - } else { - const toastId = toastManager.add(options); - toasts.current.set(clone.projectId, { toastId, renderedKey: key, phase: "done" }); - } + showToast(options); continue; } @@ -199,13 +218,7 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI }, }, }); - if (tracked) { - toastManager.update(tracked.toastId, options); - toasts.current.set(clone.projectId, { ...tracked, renderedKey: key, phase: clone.phase }); - } else { - const toastId = toastManager.add(options); - toasts.current.set(clone.projectId, { toastId, renderedKey: key, phase: clone.phase }); - } + showToast(options); } for (const [projectId, tracked] of toasts.current) { diff --git a/scripts/scenarios/clone-failure-after-dismissing-progress.e2e.ts b/scripts/scenarios/clone-failure-after-dismissing-progress.e2e.ts new file mode 100644 index 0000000000000..739497a827757 --- /dev/null +++ b/scripts/scenarios/clone-failure-after-dismissing-progress.e2e.ts @@ -0,0 +1,113 @@ +// @effect-diagnostics-next-line nodeBuiltinImport:off -- The fixture holds Git's HTTP request open. +import * as NodeHttp from "node:http"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import { ProjectId } from "@t3tools/contracts"; +import { expect } from "e2e"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Stream from "effect/Stream"; + +import { T3_HOME } from "../e2e.config.ts"; +import { rpcClient, runPromise, test, WEB } from "./t3.ts"; + +test( + "Dismissing clone progress leaves the later failure notification visible", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo"); + const thread = await t3.thread({ project, title: "Other work", messages: ["Start"] }); + const gitRequest = Promise.withResolvers(); + const remote = NodeHttp.createServer((_request, response) => { + gitRequest.resolve(response); + }); + + try { + await new Promise((resolve) => remote.listen(0, "127.0.0.1", resolve)); + const address = remote.address(); + if (!address || typeof address === "string") throw new Error("No Git fixture port"); + const projectId = ProjectId.make( + await runPromise( + SecureRandom.SecureRandom.pipe( + Effect.flatMap((random) => random.uuidV4()), + Effect.provide(NodeCrypto.layer), + ), + ), + ); + const name = "pending-clone"; + const origin = app.baseUrl ?? ""; + await t3.open(thread); + await screen.getByText("Start", { exact: true }).waitFor(); + + await runPromise( + Effect.gen(function* () { + const client = yield* rpcClient(T3_HOME, origin); + const createdAt = DateTime.formatIso(yield* DateTime.now); + yield* client["projectClone.start"]({ + projectId, + title: name, + createdAt, + remoteUrl: `http://127.0.0.1:${address.port}/${name}.git`, + destinationPath: `${project}/../${name}`, + }); + }).pipe(Effect.scoped), + ); + const response = await gitRequest.promise; + + const toastTitle = (title: string) => + browser.locator(`[data-slot="toast-title"]:text-is("${title}")`); + const dismiss = async (title: string) => { + await browser + .locator( + `[data-position]:has(> div > [data-slot="toast-close"]):has([data-slot="toast-title"]:text-is("${title}"))`, + ) + .getByRole("button", "Dismiss notification", { exact: true }) + .tap(); + await toastTitle(title).waitFor({ state: "detached" }); + }; + const progress = toastTitle(`Cloning ${name}`); + const failure = toastTitle(`Failed to clone ${name}`); + + await progress.waitFor(); + await dismiss(`Cloning ${name}`); + + response.writeHead(404).end(); + await runPromise( + Effect.gen(function* () { + const client = yield* rpcClient(T3_HOME, origin); + yield* client.subscribeProjectClones({}).pipe( + Stream.filter((clones) => + clones.some((clone) => clone.projectId === projectId && clone.phase === "failed"), + ), + Stream.runHead, + ); + }).pipe(Effect.scoped, Effect.timeout("10 seconds")), + ); + + try { + await expect(failure).toBeVisible(); + } finally { + await app.screenshot("after-background-clone-fails"); + } + + await dismiss(`Failed to clone ${name}`); + + const retryRequest = Promise.withResolvers(); + remote.once("request", (_request, response) => retryRequest.resolve(response)); + const retry = await runPromise( + Effect.gen(function* () { + const client = yield* rpcClient(T3_HOME, origin); + return yield* client["projectClone.retry"]({ projectId }); + }).pipe(Effect.scoped), + ); + await expect(retry.applied).toBe(true); + const retryResponse = await retryRequest.promise; + await expect(progress).toBeVisible(); + retryResponse.writeHead(404).end(); + await expect(failure).toBeVisible(); + } finally { + remote.close(); + remote.closeAllConnections(); + } + }, +); From bc13afaa3c42be200956b6181d21642883d77903 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:31:53 +0100 Subject: [PATCH 186/324] Invalidate pending theme imports when a replacement is too large (#40965) Co-authored-by: Julius Marminge --- .../ThemeImportDialog.browser.test.tsx | 52 +++++++++++++++ .../components/settings/ThemeImportDialog.tsx | 5 +- ...-theme-file-supersedes-earlier-read.e2e.ts | 64 +++++++++++++++++++ 3 files changed, 119 insertions(+), 2 deletions(-) create mode 100644 scripts/scenarios/rejected-theme-file-supersedes-earlier-read.e2e.ts diff --git a/apps/web/src/components/settings/ThemeImportDialog.browser.test.tsx b/apps/web/src/components/settings/ThemeImportDialog.browser.test.tsx index 8eecf79f5d33a..fd5b90f9c6c19 100644 --- a/apps/web/src/components/settings/ThemeImportDialog.browser.test.tsx +++ b/apps/web/src/components/settings/ThemeImportDialog.browser.test.tsx @@ -157,6 +157,58 @@ it("sizes an oversized theme file just under 1 MB as 1.00 MB", async () => { ); }); +it.each(["failed read", "batch install"])( + "keeps the oversized replacement warning after a superseded %s", + async (earlierImport) => { + using _themes = isolateThemes(); + await using _screen = await render( + {}} + onImported={() => true} + onImportedMany={() => {}} + />, + ); + const earlierRead = Promise.withResolvers(); + const readStarted = Promise.withResolvers(); + const earlierFile = Object.assign(themeFile("Dusk"), { + text() { + readStarted.resolve(); + return earlierRead.promise; + }, + }); + const input = document.querySelector('input[type="file"]')!; + const files = new DataTransfer(); + if (earlierImport === "batch install") files.items.add(themeFile("Dawn")); + files.items.add(earlierFile); + await act(async () => { + input.files = files.files; + input.dispatchEvent(new Event("change", { bubbles: true })); + await readStarted.promise; + }); + await expect.element(page.getByRole("button", { name: "Reading…" })).toBeDisabled(); + await userEvent.upload( + input, + new File([" ".repeat(256 * 1024 + 1)], earlierFile.name, { type: "application/json" }), + ); + const warning = page.getByText(/^That file is/); + await expect.element(warning).toBeVisible(); + + await act(async () => { + if (earlierImport === "batch install") { + earlierRead.resolve(JSON.stringify(theme("Dusk"))); + } else { + earlierRead.reject(new Error("Could not read Dusk")); + } + await earlierRead.promise.catch(() => {}); + }); + + expect(getCustomThemes().map((theme) => theme.label)).toEqual([]); + expect(page.getByRole("alert").element().textContent).toMatch(/^That file is/); + await expect.element(page.getByRole("button", { name: "Choose files" })).toBeEnabled(); + }, +); + function themeJsonc(name: string, background: string) { return `{ // VS Code themes use JSONC even with a .json extension. diff --git a/apps/web/src/components/settings/ThemeImportDialog.tsx b/apps/web/src/components/settings/ThemeImportDialog.tsx index 189560efdee9e..aeac23821884f 100644 --- a/apps/web/src/components/settings/ThemeImportDialog.tsx +++ b/apps/web/src/components/settings/ThemeImportDialog.tsx @@ -233,19 +233,20 @@ function ThemeImportBody({ const [isReading, setIsReading] = useState(false); const [isDropTarget, setIsDropTarget] = useState(false); const [conflicts, setConflicts] = useState | null>(null); - // A newer read supersedes an older one still in flight. + // A new file selection supersedes a pending import even if the selection is rejected. const importRequestRef = useRef(0); const isCurrentRequest = (requestId: number) => requestId === importRequestRef.current && !signal.aborted; const readThemeFile = async (file: ImportableThemeFile) => { + const requestId = ++importRequestRef.current; const oversized = describeOversizedThemeFile(file.size); if (oversized) { + setIsReading(false); setError(oversized); return; } - const requestId = ++importRequestRef.current; setIsReading(true); const fileText = await settlePromise(() => file.text()); if (!isCurrentRequest(requestId)) return; diff --git a/scripts/scenarios/rejected-theme-file-supersedes-earlier-read.e2e.ts b/scripts/scenarios/rejected-theme-file-supersedes-earlier-read.e2e.ts new file mode 100644 index 0000000000000..49186eaa4429a --- /dev/null +++ b/scripts/scenarios/rejected-theme-file-supersedes-earlier-read.e2e.ts @@ -0,0 +1,64 @@ +/// +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +declare global { + interface Window { + releaseOldThemeRead: () => void; + } +} + +test( + "An earlier theme file cannot become the draft after its replacement is rejected", + WEB, + async ({ t3, app, browser, screen }) => { + await t3.project("demo"); + await t3.open("/settings/appearance"); + await screen.getByRole("button", "Add theme", { exact: true }).tap(); + const dialog = screen.getByRole("dialog", "Add a theme"); + + await browser.evaluate(() => { + const target = document.querySelector('input[type="file"]')?.parentElement; + if (!target) throw new Error("No theme file drop target"); + + const gate = Promise.withResolvers(); + const theme = JSON.stringify({ + version: 1, + name: "Earlier theme", + appearance: "dark", + colors: { accent: "#734ee4" }, + }); + const first = new File([theme], "earlier.json", { type: "application/json" }); + const text = File.prototype.text; + File.prototype.text = function () { + if (this.name === first.name) return gate.promise.then(() => theme); + return text.call(this); + }; + window.releaseOldThemeRead = gate.resolve; + + const drop = (file: File) => { + const files = new DataTransfer(); + files.items.add(file); + target.dispatchEvent( + new DragEvent("drop", { dataTransfer: files, bubbles: true, cancelable: true }), + ); + }; + drop(first); + drop(new File([" ".repeat(300_000)], "replacement.json", { type: "application/json" })); + return null; + }); + + await dialog.getByText(/That file is/).waitFor(); + await browser.evaluate(async () => { + window.releaseOldThemeRead(); + // Let the earlier file response and its React update reach the dialog. + await new Promise((resolve) => + requestAnimationFrame(() => requestAnimationFrame(() => resolve())), + ); + return null; + }); + await app.screenshot("dialog-after-earlier-theme-read-finishes"); + await expect(dialog.getByRole("button", "Add theme", { exact: true })).toBeDisabled(); + }, +); From 4e1c1fea7aa21189b2b363aefd38892377625307 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:06:09 +0100 Subject: [PATCH 187/324] fix(mobile): show linked thread history page errors (#40973) --- .../threads/LinkedThreadSheet.test.tsx | 134 ++++++++++++++++++ .../features/threads/LinkedThreadSheet.tsx | 21 ++- apps/mobile/src/i18n/translations/de.json | 1 + apps/mobile/src/i18n/translations/en.json | 1 + apps/mobile/src/i18n/translations/es.json | 1 + apps/mobile/src/i18n/translations/fr.json | 1 + apps/mobile/src/i18n/translations/ja.json | 1 + apps/mobile/src/i18n/translations/ko.json | 1 + apps/mobile/src/i18n/translations/pt-BR.json | 1 + apps/mobile/src/i18n/translations/ru.json | 1 + apps/mobile/src/i18n/translations/sv.json | 1 + apps/mobile/src/i18n/translations/zh.json | 1 + apps/mobile/vite.config.ts | 1 + 13 files changed, 164 insertions(+), 2 deletions(-) create mode 100644 apps/mobile/src/features/threads/LinkedThreadSheet.test.tsx diff --git a/apps/mobile/src/features/threads/LinkedThreadSheet.test.tsx b/apps/mobile/src/features/threads/LinkedThreadSheet.test.tsx new file mode 100644 index 0000000000000..748fb333239a0 --- /dev/null +++ b/apps/mobile/src/features/threads/LinkedThreadSheet.test.tsx @@ -0,0 +1,134 @@ +import { expect, it } from "@effect/vitest"; +import { + followLinkedThread, + type LinkedThreadView as LinkedThreadState, +} from "@t3tools/client-runtime/linked-thread"; +import { EnvironmentId, type OrchestrationV2ThreadHistoryPage } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Queue from "effect/Queue"; +import * as Stream from "effect/Stream"; +import { act, type ReactNode } from "react"; +import { createRoot } from "react-dom/client"; +import { vi } from "vite-plus/test"; + +import { v2Projection } from "../../../../../packages/client-runtime/src/state/orchestrationV2TestFixtures"; +import { useLinkedThreadView } from "../../state/linkedThread"; +import { LinkedThreadView } from "./LinkedThreadSheet"; + +vi.mock("@react-navigation/native", () => ({ + StackActions: {}, + useIsFocused: () => true, + useNavigation: () => ({}), +})); +vi.mock("react-native", () => { + const Container = ({ children }: { children: ReactNode }) =>
    {children}
    ; + return { + AppState: { currentState: "active", addEventListener: () => ({ remove() {} }) }, + Platform: { OS: "android" }, + Pressable: Container, + ScrollView: Container, + Text: Container, + View: Container, + }; +}); +vi.mock("react-native-safe-area-context", () => ({ useSafeAreaInsets: () => ({ bottom: 0 }) })); +vi.mock("../../components/ui/AppActivityIndicator", () => ({ AppActivityIndicator: () => null })); +vi.mock("../../components/ui/Button", () => ({ + Button: (props: { label: string; disabled?: boolean; onPress: () => void }) => ( + + ), +})); +vi.mock("../../components/ui/ScreenContent", () => ({ + ScreenContent: ({ children }: { children: ReactNode }) => children, +})); +vi.mock("../../native/SelectableMarkdownText", () => ({ SelectableMarkdownText: () => null })); +vi.mock("../../state/environments", () => ({ useEnvironments: () => ({ environments: [] }) })); +vi.mock("../../state/linkedThread", () => ({ + useConnectLinkedEnvironment: () => ({ state: { phase: "idle" } }), + useLinkedThreadView: vi.fn(), +})); +vi.mock("../../state/peerLinks", () => ({ peerLinkEnvironment: {} })); +vi.mock("../../state/query", () => ({ useEnvironmentQuery: () => ({}) })); +vi.mock("../files/FileMarkdownPreview", () => ({ useMarkdownPreviewStyles: () => ({}) })); +vi.mock("./ReadOnlyComposerBar", () => ({ + ReadOnlyComposerBar: ({ children }: { children: ReactNode }) => children, +})); +vi.mock("./thread-inspector-header", () => ({ ThreadInspectorHeader: () => null })); +vi.mock("./useOpenLinkedThread", () => ({ useOpenLinkedThread: () => undefined })); + +it.effect( + "shows a page error after Load earlier fails on an already disconnected linked chat", + () => + Effect.gen(function* () { + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + const container = document.createElement("div"); + const root = createRoot(container); + const target = { + viaEnvironmentId: EnvironmentId.make("via"), + environmentId: EnvironmentId.make("linked"), + threadId: v2Projection.thread.id, + label: "Linked test environment", + title: null, + }; + const warning = "Linked test environment is not answering this environment"; + const pageError = "Could not load earlier turns. Try again."; + const loadEarlier = () => + [...container.querySelectorAll("button")].find( + (button) => button.textContent === "Load earlier", + )!; + + try { + const unavailable = { _tag: "PeerLinkThreadReadError", reason: "unreachable" }; + const pages = + yield* Queue.unbounded< + Effect.Effect + >(); + const views = yield* Queue.unbounded(); + yield* followLinkedThread({ + items: Stream.make({ + kind: "snapshot", + snapshotSequence: 1, + projection: v2Projection, + historyCursor: "before-recent", + hasMoreHistory: true, + } as const).pipe(Stream.concat(Stream.fail(unavailable))), + historyPage: () => Queue.take(pages).pipe(Effect.flatten), + }).pipe( + Stream.runForEach((view) => Queue.offer(views, view)), + Effect.forkScoped, + ); + + const renderNext = Effect.gen(function* () { + const view = yield* Queue.take(views); + vi.mocked(useLinkedThreadView).mockReturnValue({ + view, + error: view.error ?? null, + retry() {}, + }); + act(() => root.render()); + }); + + yield* renderNext; // Initial snapshot. + yield* renderNext; // Connection warning. + expect(container.textContent).toContain(warning); + expect(container.textContent).not.toContain(pageError); + + act(() => loadEarlier().click()); + yield* renderNext; + yield* Queue.offer(pages, Effect.fail(unavailable)); + yield* renderNext; + expect(loadEarlier().parentElement?.textContent).toContain(pageError); + expect(container.textContent).toContain(warning); + + act(() => loadEarlier().click()); + yield* renderNext; + expect(container.textContent).not.toContain(pageError); + expect(loadEarlier().disabled).toBe(true); + } finally { + act(() => root.unmount()); + vi.unstubAllGlobals(); + } + }).pipe(Effect.scoped), +); diff --git a/apps/mobile/src/features/threads/LinkedThreadSheet.tsx b/apps/mobile/src/features/threads/LinkedThreadSheet.tsx index 0096c9d576a91..7ec2c4dac2cc8 100644 --- a/apps/mobile/src/features/threads/LinkedThreadSheet.tsx +++ b/apps/mobile/src/features/threads/LinkedThreadSheet.tsx @@ -286,6 +286,9 @@ export function LinkedThreadView(props: { const scroll = useRef>(null); // Follows new items only while the reader is already at the end. const atEnd = useRef(true); + const showHistoryError = + view !== null && view.thread.historyCursor !== null && view.history.failed; + const lastLayoutHadHistoryError = useRef(false); const working = projection !== null && isLinkedThreadWorking(projection); const connection = useConnectLinkedEnvironment(target); const connectState = connection.state; @@ -334,7 +337,12 @@ export function LinkedThreadView(props: { atEnd.current = contentSize.height - layoutMeasurement.height - contentOffset.y < 80; }} onContentSizeChange={() => { - if (atEnd.current) scroll.current?.scrollToEnd({ animated: false }); + // A page error can resize the top of a short feed whose reader is also near the end. + const historyErrorChanged = lastLayoutHadHistoryError.current !== showHistoryError; + lastLayoutHadHistoryError.current = showHistoryError; + if (atEnd.current && !historyErrorChanged) { + scroll.current?.scrollToEnd({ animated: false }); + } }} > {view === null || projection === null ? ( @@ -351,7 +359,7 @@ export function LinkedThreadView(props: { ) : ( <> {view.thread.historyCursor !== null ? ( - +
  • ))} {props.notebook.cells.length === 0 ? ( diff --git a/scripts/scenarios/notebook-shows-saved-output-in-tall-preview.e2e.ts b/scripts/scenarios/notebook-shows-saved-output-in-tall-preview.e2e.ts new file mode 100644 index 0000000000000..c944cf1ec9d42 --- /dev/null +++ b/scripts/scenarios/notebook-shows-saved-output-in-tall-preview.e2e.ts @@ -0,0 +1,80 @@ +/// +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +const savedResults = Array.from({ length: 17 }, (_, index) => `Saved result ${index + 1}`); +const notebook = { + nbformat: 4, + nbformat_minor: 5, + metadata: { language_info: { name: "python" } }, + cells: [ + { + id: "results", + cell_type: "code", + source: [], + metadata: {}, + execution_count: 1, + outputs: [ + { output_type: "stream", name: "stdout", text: Array(12).fill("Processing").join("\n") }, + ...savedResults.map((result) => ({ + output_type: "display_data", + metadata: {}, + data: { "text/html": `${result}` }, + })), + ], + }, + ], +}; +const lastOutput = '[data-notebook-output="0-17"]'; + +test( + "All saved notebook outputs render when they fit in a tall preview", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo", { "results.ipynb": JSON.stringify(notebook) }); + const thread = await t3.thread({ project, title: "Review results", messages: ["Start"] }); + await browser.setViewport({ width: 1440, height: 1080 }); + await t3.open(thread); + await screen.getByText("fixture turn complete", { exact: false }).waitFor(); + + await browser.keyboard.press("Control+p"); + await screen.getByPlaceholder("Search files…").fill("results.ipynb"); + await screen.getByRole("option", "results.ipynb", { exact: false }).tap(); + await browser.locator(lastOutput).waitFor({ state: "attached", timeout: 120_000 }); + + // The stream puts the final result below the fold until the user scrolls. + const height = await browser.evaluate((selector) => { + const viewport = document.querySelector(selector)!.closest(".scrollbar-gutter-both")!; + return window.innerHeight - viewport.clientHeight + 1070; + }, lastOutput); + await browser.setViewport({ width: 1440, height }); + await browser.locator('[data-notebook-output="0-15"] iframe').waitFor({ timeout: 30_000 }); + await browser.evaluate((selector) => { + const viewport = document.querySelector(selector)!.closest(".scrollbar-gutter-both")!; + viewport.scrollTop = viewport.scrollHeight; + return null; + }, lastOutput); + + try { + await expect + .poll(() => + browser.evaluate((selector) => { + const viewport = document.querySelector(selector)!.closest(".scrollbar-gutter-both")!; + const bounds = viewport.getBoundingClientRect(); + return Array.from(viewport.querySelectorAll("[data-notebook-output]"), (output) => { + const row = output.getBoundingClientRect(); + if (row.top < bounds.top || row.bottom > bounds.bottom) return "Output is offscreen"; + return ( + output.querySelector("iframe")?.contentDocument?.body?.textContent?.trim() || + "Output is in view but blank" + ); + }); + }, lastOutput), + ) + .toEqual(savedResults); + } finally { + await app.screenshot("last-saved-output-in-tall-preview"); + } + }, +); diff --git a/scripts/scenarios/notebook-shows-visible-saved-output.e2e.ts b/scripts/scenarios/notebook-shows-visible-saved-output.e2e.ts new file mode 100644 index 0000000000000..2897ecc0df7eb --- /dev/null +++ b/scripts/scenarios/notebook-shows-visible-saved-output.e2e.ts @@ -0,0 +1,77 @@ +/// +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +const notebook = { + nbformat: 4, + nbformat_minor: 5, + metadata: { language_info: { name: "python" } }, + cells: [ + { + id: "results", + cell_type: "code", + source: [], + metadata: {}, + execution_count: 1, + outputs: Array.from({ length: 17 }, (_, index) => ({ + output_type: "display_data", + metadata: {}, + data: { "text/html": `Saved result ${index + 1}` }, + })), + }, + ], +}; +const fifteenthOutputFrame = '[data-notebook-output="0-14"] iframe'; +const lastOutput = '[data-notebook-output="0-16"]'; + +test( + "A visible saved notebook output renders when earlier outputs have scrolled above it", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo", { "results.ipynb": JSON.stringify(notebook) }); + const thread = await t3.thread({ project, title: "Review results", messages: ["Start"] }); + await browser.setViewport({ width: 1440, height: 1080 }); + await t3.open(thread); + await screen.getByText("fixture turn complete", { exact: false }).waitFor(); + + await browser.keyboard.press("Control+p"); + await screen.getByPlaceholder("Search files…").fill("results.ipynb"); + await screen.getByRole("option", "results.ipynb", { exact: false }).tap(); + await browser.locator(lastOutput).waitFor({ state: "attached", timeout: 120_000 }); + + // Leave room for the final output and fewer than sixteen preceding outputs. + const height = await browser.evaluate((selector) => { + const viewport = document.querySelector(selector)!.closest(".scrollbar-gutter-both")!; + return window.innerHeight - viewport.clientHeight + 940; + }, lastOutput); + await browser.setViewport({ width: 1440, height }); + await browser.locator(fifteenthOutputFrame).waitFor({ timeout: 30_000 }); + await browser.evaluate((selector) => { + const viewport = document.querySelector(selector)!.closest(".scrollbar-gutter-both")!; + viewport.scrollTop = 170; + return null; + }, lastOutput); + + try { + await expect + .poll(() => + browser.evaluate((selector) => { + const output = document.querySelector(selector); + const viewport = output?.closest(".scrollbar-gutter-both"); + if (!output || !viewport) return null; + const bounds = viewport.getBoundingClientRect(); + const row = output.getBoundingClientRect(); + if (row.top < bounds.top || row.bottom > bounds.bottom) return null; + return ( + output.querySelector("iframe")?.contentDocument?.body?.textContent?.trim() || + "Output is in view but blank" + ); + }, lastOutput), + ) + .toBe("Saved result 17"); + } finally { + await app.screenshot("last-saved-output"); + } + }, +); From 87554a7b86d17ce9efc9f72d58d1f2f0f47f7e99 Mon Sep 17 00:00:00 2001 From: Stefan Mirea Date: Sun, 22 Nov 2026 19:45:42 +0000 Subject: [PATCH 192/324] fix(web): editing a queued message keeps its attachment chips resolved (#40945) Co-authored-by: gemini-4-neon Co-authored-by: Julius Marminge --- apps/web/src/components/ChatView.tsx | 6 + .../components/ComposerPromptEditorTiptap.tsx | 3 + apps/web/src/components/chat/ChatComposer.tsx | 116 ++++++++++++++---- .../chat/composerContextUndo.test.ts | 69 ++++++++++- .../components/chat/composerContextUndo.ts | 44 ++++++- .../components/chat/queuedMessageEdit.test.ts | 95 +++++++++++++- .../src/components/chat/queuedMessageEdit.ts | 90 +++++++++++++- .../chat/useComposerContextImport.ts | 20 +++ .../chat/useQueuedRunEdit.browser.test.tsx | 82 +++++++++++-- .../src/components/chat/useQueuedRunEdit.ts | 64 +++++++++- .../composerContextPresentation.test.ts | 98 ++++++++++++++- .../composerContextPresentation.tsx | 64 +++++++++- apps/web/src/lib/composerContextRecords.ts | 36 ++++-- 13 files changed, 726 insertions(+), 61 deletions(-) diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 4f1d764ffef29..229ac99e3a756 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -3946,9 +3946,15 @@ export default function ChatView(props: ChatViewProps) { onExpandImage={onExpandTimelineImageStable} onFileOpen={openFileAttachmentStable} editingQueuedAttachments={queuedRunEdit.editingAttachments} + removedEditingQueuedAttachments={ + queuedRunEdit.removedEditingAttachments + } onRemoveEditingQueuedAttachment={ queuedRunEdit.removeEditingAttachment } + onRestoreEditingQueuedAttachment={ + queuedRunEdit.restoreEditingAttachment + } /> )}
    diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index 402156b001286..634b7a9389e93 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -203,6 +203,8 @@ export interface ComposerPromptEditorProps { contextIds: string[], /** False when only the caret or selection moved. */ textChanged: boolean, + /** True when the change came from undo or redo. */ + fromHistory?: boolean, ) => void; onVisibleSelectionChange?: () => void; onCommandKeyDown?: (key: string, event: KeyboardEvent, isTaskItem?: boolean) => boolean; @@ -1127,6 +1129,7 @@ function ComposerPromptEditorTiptapInner( suppressTrigger, contextIds, previousSnapshot.value !== nextValue, + isHistoryTransaction(transaction), ); }; diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index af4871b451932..85a7f6173bf96 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -23,6 +23,7 @@ import { import type { KeybindingCommand, AssistantCitation, + ComposerContextId, ResponseContextRecord, ChatAttachment as ContractChatAttachment, ChatFileAttachment, @@ -120,6 +121,7 @@ import { useComposerTriggerState } from "./useComposerTriggerState"; import { useComposerMenuItems } from "./useComposerMenuItems"; import { useComposerMultilinePrompt } from "./useComposerMultilinePrompt"; import { + type QueuedAttachmentContextBinding, reconcileAttachmentContextReferences, useRetainedContextPayloads, } from "./composerContextUndo"; @@ -287,6 +289,7 @@ import { useComposerImageGroups } from "./useComposerImageGroups"; import { useComposerStash } from "./useComposerStash"; import { useComposerContextImport } from "./useComposerContextImport"; import { useComposerAttachmentIntake } from "./useComposerAttachmentIntake"; +import { isQueuedFileAttachment, isQueuedImageAttachment } from "./queuedMessageEdit"; import { cancelHeldComposerSend, countPreparingComposerImages, @@ -457,8 +460,11 @@ export interface ChatComposerProps { editingQueuedAttachments: ReadonlyArray<{ readonly attachment: ContractChatAttachment; readonly url: string | null; + readonly contextIds?: ReadonlyArray | undefined; }> | null; + removedEditingQueuedAttachments?: ReadonlyArray | undefined; onRemoveEditingQueuedAttachment: (attachmentId: string) => void; + onRestoreEditingQueuedAttachment?: ((attachment: ContractChatAttachment) => void) | undefined; onCompactContext: () => void; onSend: ( @@ -599,7 +605,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) onExpandImage, onFileOpen, editingQueuedAttachments, + removedEditingQueuedAttachments, onRemoveEditingQueuedAttachment, + onRestoreEditingQueuedAttachment, } = props; const { activePendingProgress: incomingPendingProgress, @@ -657,6 +665,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) activePendingProgress.activeQuestion.id, ) : null; + const queuedEditOwnsComposer = + questionAttachmentTarget === null && pendingUserInputs.length === 0; + const activeEditingQueuedAttachments = queuedEditOwnsComposer ? editingQueuedAttachments : null; + const activeRemovedEditingQueuedAttachments = queuedEditOwnsComposer + ? removedEditingQueuedAttachments + : undefined; const attachmentDraftTarget = questionAttachmentTarget ?? composerDraftTarget; const attachmentDraft = useComposerThreadDraft(attachmentDraftTarget); const questionTakesSnapShots = @@ -757,33 +771,55 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) cwd: gitCwd ?? undefined, projectId: activeProjectId ?? undefined, expandImage: (imageId: string) => { - const preview = buildExpandedImagePreview( - composerImages, - imageId, - copyComposerSnapshotStable, - ); + const preview = + buildExpandedImagePreview(composerImages, imageId, copyComposerSnapshotStable) ?? + buildExpandedImagePreview( + (activeEditingQueuedAttachments ?? []).flatMap(({ attachment, url }) => + isQueuedImageAttachment(attachment) && url ? [{ ...attachment, previewUrl: url }] : [], + ), + imageId, + ); if (preview) onExpandImage(preview); }, - openFile: setPreviewFileId, + openFile: (fileId: string) => { + if (composerFiles.some((file) => file.id === fileId)) { + setPreviewFileId(fileId); + return; + } + const queuedFile = activeEditingQueuedAttachments?.find( + ({ attachment }) => isQueuedFileAttachment(attachment) && attachment.id === fileId, + )?.attachment; + if (queuedFile && isQueuedFileAttachment(queuedFile)) onFileOpen(queuedFile); + }, openMention: (path: string) => useRightPanelStore.getState().openFile(routeThreadRef, path), expandVideo: (fileId: string) => { const file = composerFiles.find((candidate) => candidate.id === fileId); - if (!file || !isVideoAttachment(file)) return; - const localPreview = buildExpandedImagePreview([file], file.id); - if (localPreview) { - onExpandImage(localPreview); + if (file && isVideoAttachment(file)) { + const localPreview = buildExpandedImagePreview([file], file.id); + if (localPreview) { + onExpandImage(localPreview); + return; + } + if (file.uploadedAttachmentId === undefined || file.uploadEnvironmentId !== environmentId) { + return; + } + const persistedPreview = buildAttachmentVideoPreview(environmentId, { + type: "file", + id: file.uploadedAttachmentId, + name: file.name, + mimeType: file.mimeType, + sizeBytes: file.sizeBytes, + }); + if (persistedPreview) onExpandImage(persistedPreview); return; } - if (file.uploadedAttachmentId === undefined || file.uploadEnvironmentId !== environmentId) { + const queuedFile = activeEditingQueuedAttachments?.find( + ({ attachment }) => isQueuedFileAttachment(attachment) && attachment.id === fileId, + )?.attachment; + if (!queuedFile || !isQueuedFileAttachment(queuedFile) || !isVideoAttachment(queuedFile)) { return; } - const persistedPreview = buildAttachmentVideoPreview(environmentId, { - type: "file", - id: file.uploadedAttachmentId, - name: file.name, - mimeType: file.mimeType, - sizeBytes: file.sizeBytes, - }); + const persistedPreview = buildAttachmentVideoPreview(environmentId, queuedFile); if (persistedPreview) onExpandImage(persistedPreview); }, openPullRequest: (event: React.MouseEvent, url: string) => { @@ -798,6 +834,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) environmentContexts: composerEnvironmentContexts, images: composerImages, files: composerFiles, + existingAttachments: activeEditingQueuedAttachments ?? undefined, + environmentId, uploadsByImageId, }); const needsReattachFileCount = composerFiles.filter(composerFileNeedsReattach).length; @@ -1393,12 +1431,20 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) : null); if (!record) return []; if (attachment.file) copiedFiles.set(record.attachmentId, attachment.file); - return [ - record.kind === "image" && attachment.type === "image" && attachment.source - ? { ...record, source: attachment.source } - : record, - ]; + return [record]; }), + ...(activeEditingQueuedAttachments ?? []).flatMap(({ attachment, contextIds }) => { + if (!isQueuedImageAttachment(attachment) && !isQueuedFileAttachment(attachment)) return []; + return (contextIds ?? []) + .filter((contextId) => wanted.has(contextId)) + .map((contextId) => + attachmentContextRecord({ + attachment, + attachmentId: attachment.id, + contextId, + }), + ); + }), ]; if (records.length === 0) return null; const fragment = encodeComposerContextFragment({ @@ -1447,6 +1493,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) promptRef, pendingThreadImportsRef, addComposerFilesToDraft, + removedQueuedAttachments: activeRemovedEditingQueuedAttachments, + onRestoreQueuedAttachment: onRestoreEditingQueuedAttachment, }); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- keeps the shared prompt ref in step with the committed draft prompt for imperative handlers @@ -1652,6 +1700,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) cursorAdjacentToMention: boolean, contextIds: string[], textChanged: boolean, + fromHistory = false, ) => { refreshWorkspaceSnapshotOnTyping(); const trigger = cursorAdjacentToMention @@ -1762,6 +1811,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const attachmentChanges = reconcileAttachmentContextReferences({ referencedContextIds: referenced, files: composerFiles, + queuedAttachments: (activeEditingQueuedAttachments ?? []).map( + ({ attachment, contextIds }) => ({ + attachment, + contextIds: contextIds ?? [], + }), + ), + removedQueuedAttachments: activeRemovedEditingQueuedAttachments ?? [], + fromHistory, images: composerImages, previewAnnotations: composerPreviewAnnotations, retained: retainedContextPayloads, @@ -1781,6 +1838,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) if (attachmentChanges.filesToRestore.length > 0) { addComposerDraftFiles(attachmentDraftTarget, attachmentChanges.filesToRestore); } + for (const attachmentId of attachmentChanges.queuedAttachmentIdsToRemove) { + onRemoveEditingQueuedAttachment(attachmentId); + } + for (const attachment of attachmentChanges.queuedAttachmentsToRestore) { + onRestoreEditingQueuedAttachment?.(attachment); + } setComposerCursor(nextCursor); updateTrigger(trigger); }; @@ -3814,11 +3877,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) )} {!isComposerCollapsedMobile && - pendingUserInputs.length === 0 && - editingQueuedAttachments !== null && - editingQueuedAttachments.length > 0 && ( + activeEditingQueuedAttachments !== null && + activeEditingQueuedAttachments.length > 0 && ( )} diff --git a/apps/web/src/components/chat/composerContextUndo.test.ts b/apps/web/src/components/chat/composerContextUndo.test.ts index a763b47a0d6d7..c493aa2dfc8fd 100644 --- a/apps/web/src/components/chat/composerContextUndo.test.ts +++ b/apps/web/src/components/chat/composerContextUndo.test.ts @@ -1,4 +1,8 @@ -import type { PreviewAnnotationPayload } from "@t3tools/contracts"; +import { + ChatAttachmentId, + ComposerContextId, + type PreviewAnnotationPayload, +} from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; import type { ComposerImageAttachment } from "../../composerDraftStore"; @@ -37,7 +41,7 @@ const annotation = { } satisfies PreviewAnnotationPayload; function retention(): RetainedAttachmentContextPayloads { - return { files: new Map(), previewAnnotations: new Map() }; + return { files: new Map(), previewAnnotations: new Map(), restoredQueuedImageIds: new Set() }; } describe("reconcileAttachmentContextReferences", () => { @@ -88,4 +92,65 @@ describe("reconcileAttachmentContextReferences", () => { }), ]); }); + + it("drops a queued file with its chip, keeps a queued image, and lets undo and redo restore and remove either", () => { + const file = { + attachment: { + type: "file" as const, + id: ChatAttachmentId.make("server-file"), + name: "notes.txt", + mimeType: "text/plain", + sizeBytes: 12, + }, + contextIds: [ComposerContextId.make("file_local")], + }; + const queuedImage = { + attachment: { + type: "image" as const, + id: ChatAttachmentId.make("server-image"), + name: "image.png", + mimeType: "image/png", + sizeBytes: 67, + }, + contextIds: [ComposerContextId.make("image_local")], + }; + const base = { files: [], images: [], previewAnnotations: [], retained: retention() }; + + const deleted = reconcileAttachmentContextReferences({ + ...base, + referencedContextIds: new Set(), + queuedAttachments: [file, queuedImage], + }); + expect(deleted.queuedAttachmentIdsToRemove).toEqual([file.attachment.id]); + + const undone = reconcileAttachmentContextReferences({ + ...base, + referencedContextIds: new Set(["file_local", "image_local"]), + removedQueuedAttachments: [file, queuedImage], + }); + expect(undone.queuedAttachmentsToRestore).toEqual([file.attachment, queuedImage.attachment]); + + const redone = reconcileAttachmentContextReferences({ + ...base, + referencedContextIds: new Set(), + queuedAttachments: [file, queuedImage], + fromHistory: true, + }); + expect(redone.queuedAttachmentIdsToRemove).toEqual([ + file.attachment.id, + queuedImage.attachment.id, + ]); + + reconcileAttachmentContextReferences({ + ...base, + referencedContextIds: new Set(["image_local"]), + removedQueuedAttachments: [queuedImage], + }); + const backspaced = reconcileAttachmentContextReferences({ + ...base, + referencedContextIds: new Set(), + queuedAttachments: [queuedImage], + }); + expect(backspaced.queuedAttachmentIdsToRemove).toEqual([]); + }); }); diff --git a/apps/web/src/components/chat/composerContextUndo.ts b/apps/web/src/components/chat/composerContextUndo.ts index fd2a0cde59341..4c96ec12b70fc 100644 --- a/apps/web/src/components/chat/composerContextUndo.ts +++ b/apps/web/src/components/chat/composerContextUndo.ts @@ -1,4 +1,6 @@ import type { + ChatAttachment, + ComposerContextId, EnvironmentContextRecord, PreviewAnnotationPayload, ThreadContextRecord, @@ -9,15 +11,23 @@ import type { ComposerFileAttachment, ComposerImageAttachment } from "../../comp import { fileContextReference, previewAnnotationContextId } from "../../lib/composerContextRecords"; import type { TerminalContextDraft } from "../../lib/terminalContext"; import type { ReviewCommentContext } from "../../reviewCommentContext"; +import { isQueuedFileAttachment, isQueuedImageAttachment } from "./queuedMessageEdit"; interface RetainedPreviewAnnotation { annotation: PreviewAnnotationPayload; image: ComposerImageAttachment | undefined; } +export interface QueuedAttachmentContextBinding { + readonly attachment: ChatAttachment; + readonly contextIds: ReadonlyArray; +} + export interface RetainedAttachmentContextPayloads { files: Map; previewAnnotations: Map; + /** Queued images brought back because their chip reappeared. */ + restoredQueuedImageIds: Set; } export interface RetainedContextPayloads extends RetainedAttachmentContextPayloads { @@ -35,6 +45,7 @@ function createRetainedContextPayloads(): RetainedContextPayloads { environments: new Map(), files: new Map(), previewAnnotations: new Map(), + restoredQueuedImageIds: new Set(), }; } @@ -61,12 +72,19 @@ export function useRetainedContextPayloads(draftTargetKey: string): RetainedCont export function reconcileAttachmentContextReferences(input: { referencedContextIds: ReadonlySet; files: ReadonlyArray; + /** Attachments of a queued message being edited, and those removed during the edit. */ + queuedAttachments?: ReadonlyArray; + removedQueuedAttachments?: ReadonlyArray; + /** The change came from undo or redo. */ + fromHistory?: boolean; images: ReadonlyArray; previewAnnotations: ReadonlyArray; retained: RetainedAttachmentContextPayloads; }): { filesToRemove: string[]; filesToRestore: ComposerFileAttachment[]; + queuedAttachmentIdsToRemove: string[]; + queuedAttachmentsToRestore: ChatAttachment[]; annotationIdsToRemove: string[]; annotationsToRestore: RetainedPreviewAnnotation[]; } { @@ -86,6 +104,23 @@ export function reconcileAttachmentContextReferences(input: { return file ? [file] : []; }); + const isReferenced = (entry: QueuedAttachmentContextBinding) => + entry.contextIds.some((contextId) => input.referencedContextIds.has(contextId)); + const restoredImageIds = input.retained.restoredQueuedImageIds; + const queuedAttachmentIdsToRemove = (input.queuedAttachments ?? []).flatMap((entry) => { + if (entry.contextIds.length === 0 || isReferenced(entry)) return []; + if (isQueuedFileAttachment(entry.attachment)) return [entry.attachment.id]; + // Like draft images, a queued image outlives its deleted chip, unless undo or redo + // takes away a chip whose return had brought the image back. + const wasRestored = restoredImageIds.delete(entry.attachment.id); + return wasRestored && input.fromHistory ? [entry.attachment.id] : []; + }); + const queuedAttachmentsToRestore = (input.removedQueuedAttachments ?? []).flatMap((entry) => { + if (!isReferenced(entry)) return []; + if (isQueuedImageAttachment(entry.attachment)) restoredImageIds.add(entry.attachment.id); + return [entry.attachment]; + }); + const imagesById = new Map(input.images.map((image) => [image.id, image])); const liveAnnotationContextIds = new Set( input.previewAnnotations.map((annotation) => previewAnnotationContextId(annotation.id)), @@ -106,5 +141,12 @@ export function reconcileAttachmentContextReferences(input: { return retained ? [retained] : []; }); - return { filesToRemove, filesToRestore, annotationIdsToRemove, annotationsToRestore }; + return { + filesToRemove, + filesToRestore, + queuedAttachmentIdsToRemove, + queuedAttachmentsToRestore, + annotationIdsToRemove, + annotationsToRestore, + }; } diff --git a/apps/web/src/components/chat/queuedMessageEdit.test.ts b/apps/web/src/components/chat/queuedMessageEdit.test.ts index 49d22add3a239..0ebfdacdbb607 100644 --- a/apps/web/src/components/chat/queuedMessageEdit.test.ts +++ b/apps/web/src/components/chat/queuedMessageEdit.test.ts @@ -1,4 +1,11 @@ -import { EnvironmentId, MessageId, ThreadId, TurnItemId } from "@t3tools/contracts"; +import { + ChatAttachmentId, + ComposerContextId, + EnvironmentId, + MessageId, + ThreadId, + TurnItemId, +} from "@t3tools/contracts"; import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import { threadContextRecord } from "@t3tools/shared/composerContextReferences"; import { beforeEach, describe, expect, it } from "vite-plus/test"; @@ -10,7 +17,12 @@ import { } from "../../composerDraftStore"; import { readAttachmentUpload, useAttachmentUploadStore } from "../../lib/attachmentUploadQueue"; import { environmentContextRecord, responseContextRecord } from "../../lib/composerContextRecords"; -import { prepareQueuedEditAttachments, recoverQueuedMessageEdit } from "./queuedMessageEdit"; +import { formatInlineContextReference } from "../../lib/composerContextReferences"; +import { + matchRestorableQueuedAttachment, + prepareQueuedEditAttachments, + recoverQueuedMessageEdit, +} from "./queuedMessageEdit"; const environmentId = EnvironmentId.make("remote-environment"); const threadTarget = scopeThreadRef(environmentId, ThreadId.make("thread:edit")); @@ -193,6 +205,85 @@ describe("queued message file edits", () => { expect(store.getComposerDraft(threadTarget)).toBeNull(); }); + it("strips existing queued attachment references when recovering an edit into the thread draft", () => { + const store = useComposerDraftStore.getState(); + const chip = formatInlineContextReference({ + kind: "image", + contextId: "image_queued-1", + label: "image.png", + }); + store.setPrompt(editTarget, `Check ${chip} closely`); + expect( + recoverQueuedMessageEdit({ + ...originalMessage, + originalText: `Check ${chip}`, + existingAttachmentContextIds: ["image_queued-1"], + }), + ).toBe("kept"); + expect(store.getComposerDraft(threadTarget)?.prompt).toBe("Check closely"); + expect(store.getComposerDraft(editTarget)).toBeNull(); + + store.clearComposerContent(threadTarget); + store.setPrompt(editTarget, chip); + expect( + recoverQueuedMessageEdit({ + ...originalMessage, + originalText: `${chip} note`, + existingAttachmentContextIds: ["image_queued-1"], + }), + ).toBe("discarded"); + expect(store.getComposerDraft(threadTarget)).toBeNull(); + }); + + it("matches a removed queued attachment for same-environment paste while rejecting other environments or payloads", () => { + const fileId = ChatAttachmentId.make("server-file-1"); + const contextId = ComposerContextId.make("file_local-1"); + const removedAttachment = { + type: "file" as const, + id: fileId, + name: "notes.txt", + mimeType: "text/plain", + sizeBytes: 12, + }; + const record = { + version: 1 as const, + kind: "file" as const, + contextId, + label: "notes.txt", + attachmentId: fileId, + name: "notes.txt", + mimeType: "text/plain", + sizeBytes: 12, + }; + + expect( + matchRestorableQueuedAttachment({ + environmentId, + sourceEnvironmentId: environmentId, + record, + removedQueuedAttachments: [{ attachment: removedAttachment, contextIds: [contextId] }], + }), + ).toEqual({ attachment: removedAttachment, contextId }); + + expect( + matchRestorableQueuedAttachment({ + environmentId, + sourceEnvironmentId: EnvironmentId.make("other-environment"), + record, + removedQueuedAttachments: [{ attachment: removedAttachment, contextIds: [contextId] }], + }), + ).toBeNull(); + + expect( + matchRestorableQueuedAttachment({ + environmentId, + sourceEnvironmentId: environmentId, + record: { ...record, attachmentId: ChatAttachmentId.make("different-file") }, + removedQueuedAttachments: [{ attachment: removedAttachment, contextIds: [contextId] }], + }), + ).toBeNull(); + }); + it("does not overwrite a separate draft when the queued run leaves", () => { const store = useComposerDraftStore.getState(); store.setPrompt(threadTarget, "Separate draft"); diff --git a/apps/web/src/components/chat/queuedMessageEdit.ts b/apps/web/src/components/chat/queuedMessageEdit.ts index e6b59e3a96b83..ca58777dcb44a 100644 --- a/apps/web/src/components/chat/queuedMessageEdit.ts +++ b/apps/web/src/components/chat/queuedMessageEdit.ts @@ -1,5 +1,14 @@ import { resolveQueuedEditExit } from "@t3tools/client-runtime/queued-run-edit"; -import type { ChatAttachment, ResponseContextRecord } from "@t3tools/contracts"; +import type { + ChatAttachment, + ChatFileAttachment, + ChatImageAttachment, + ComposerContextId, + ComposerContextRecord, + EnvironmentId, + OrchestrationMessageContext, + ResponseContextRecord, +} from "@t3tools/contracts"; import * as Equal from "effect/Equal"; import { composerDraftHasUserContent, @@ -11,6 +20,68 @@ import { import { msg } from "gt-react"; import { m } from "../../i18n/messages"; import { releaseDraftAttachments } from "../../lib/attachmentUploadQueue"; +import { + attachmentContextRecord, + isSameComposerContextPayload, +} from "../../lib/composerContextRecords"; +import { removeInlineContextReference } from "../../lib/composerContextReferences"; + +export function isQueuedImageAttachment( + attachment: ChatAttachment, +): attachment is ChatImageAttachment { + return attachment.type === "image"; +} + +export function isQueuedFileAttachment( + attachment: ChatAttachment, +): attachment is ChatFileAttachment { + return attachment.type === "file"; +} + +export function attachmentContextIdsForRecord( + context: OrchestrationMessageContext | undefined, + attachment: Pick, +): ComposerContextId[] { + return (context?.records ?? []).flatMap((record) => + record.kind === attachment.type && + "attachmentId" in record && + record.attachmentId === attachment.id + ? [record.contextId] + : [], + ); +} + +export function matchRestorableQueuedAttachment(input: { + readonly environmentId: EnvironmentId; + readonly sourceEnvironmentId: EnvironmentId | null; + readonly record: Extract; + readonly removedQueuedAttachments: ReadonlyArray<{ + readonly attachment: ChatAttachment; + readonly contextIds: ReadonlyArray; + }>; +}): { readonly attachment: ChatAttachment; readonly contextId: ComposerContextId } | null { + if (input.sourceEnvironmentId !== input.environmentId) return null; + const match = input.removedQueuedAttachments.find( + ({ attachment, contextIds }) => + (isQueuedImageAttachment(attachment) || isQueuedFileAttachment(attachment)) && + attachment.type === input.record.kind && + contextIds.some((contextId) => + isSameComposerContextPayload( + attachmentContextRecord({ + attachment, + attachmentId: attachment.id, + contextId, + }), + input.record, + ), + ), + ); + if (!match || match.contextIds.length === 0) return null; + const contextId = + match.contextIds.find((candidate) => candidate === input.record.contextId) ?? + match.contextIds[0]!; + return { attachment: match.attachment, contextId }; +} /** Staged attachments upload as soon as they are added, so a dropped edit must release them. */ export function discardQueuedEditDraft(target: ComposerThreadTarget): void { @@ -31,9 +102,21 @@ export function recoverQueuedMessageEdit(input: { readonly originalText: string; readonly originalReplyTo: ResponseContextRecord | null; readonly removedExistingAttachment?: boolean; + readonly existingAttachmentContextIds?: ReadonlyArray; }): "kept" | "discarded" | "clean" { const store = useComposerDraftStore.getState(); const draft = store.getComposerDraft(input.editTarget); + const strippedPrompt = + draft && (input.existingAttachmentContextIds?.length ?? 0) > 0 + ? input.existingAttachmentContextIds!.reduce( + (prompt, contextId) => removeInlineContextReference(prompt, contextId).prompt, + draft.prompt, + ) + : draft?.prompt; + const recoveredDraft = + draft && strippedPrompt !== undefined && strippedPrompt !== draft.prompt + ? { ...draft, prompt: strippedPrompt } + : draft; const recovery = resolveQueuedEditExit({ editChanged: input.removedExistingAttachment === true || @@ -42,10 +125,13 @@ export function recoverQueuedMessageEdit(input: { (draft.prompt !== input.originalText || draft.images.length > 0 || draft.files.length > 0)), // A cleared edit has nothing to put back, so it can only be discarded. threadDraftEmpty: - composerDraftHasUserContent(draft) && + composerDraftHasUserContent(recoveredDraft) && !composerDraftHasUserContent(store.getComposerDraft(input.threadTarget)), }); if (recovery === "kept") { + if (draft && strippedPrompt !== undefined && strippedPrompt !== draft.prompt) { + store.setPrompt(input.editTarget, strippedPrompt); + } store.moveComposerContent(input.editTarget, input.threadTarget); store.clearComposerContent(input.editTarget); } else { diff --git a/apps/web/src/components/chat/useComposerContextImport.ts b/apps/web/src/components/chat/useComposerContextImport.ts index 61d0abd7319a6..458f39dc98638 100644 --- a/apps/web/src/components/chat/useComposerContextImport.ts +++ b/apps/web/src/components/chat/useComposerContextImport.ts @@ -10,6 +10,7 @@ import * as Schema from "effect/Schema"; import type { RefObject } from "react"; import type { ChatComposerProps } from "./ChatComposer"; import { + type ChatAttachment, type ComposerContextClipboardFragment, type ComposerContextRecord, type EnvironmentId, @@ -59,6 +60,8 @@ import { useAtomCommand } from "../../state/use-atom-command"; import { useAtomQueryRunner } from "~/state/use-atom-query-runner"; import { useStableCallback } from "../../hooks/useStableCallback"; import { countPreparingComposerImages } from "./preparingComposerImages"; +import type { QueuedAttachmentContextBinding } from "./composerContextUndo"; +import { matchRestorableQueuedAttachment } from "./queuedMessageEdit"; const isUnreachable = Schema.is( Schema.Union([ConnectionTransientError, ConnectionBlockedError, EnvironmentRpcUnavailableError]), @@ -94,6 +97,8 @@ export function useComposerContextImport(input: { readonly promptRef: RefObject; readonly pendingThreadImportsRef: RefObject>; readonly addComposerFilesToDraft: (files: ComposerFileAttachment[]) => string[]; + readonly removedQueuedAttachments?: ReadonlyArray | undefined; + readonly onRestoreQueuedAttachment?: ((attachment: ChatAttachment) => void) | undefined; }) { const { environmentId, @@ -112,6 +117,8 @@ export function useComposerContextImport(input: { promptRef, pendingThreadImportsRef, addComposerFilesToDraft, + removedQueuedAttachments, + onRestoreQueuedAttachment, } = input; const getComposerDraft = useComposerDraftStore((store) => store.getComposerDraft); const addComposerDraftImages = useComposerDraftStore((store) => store.addImages); @@ -433,6 +440,19 @@ export function useComposerContextImport(input: { case "image": case "file": { if (skippedDependentAttachmentIds.has(record.contextId)) break; + if (questionAttachmentTarget === null && !conflicts) { + const restored = matchRestorableQueuedAttachment({ + environmentId, + sourceEnvironmentId, + record, + removedQueuedAttachments: removedQueuedAttachments ?? [], + }); + if (restored) { + onRestoreQueuedAttachment?.(restored.attachment); + rewritten.set(record.contextId, restored.contextId); + break; + } + } if (sourceEnvironmentId === null && !conflicts) { rewritten.set(record.contextId, record.contextId); break; diff --git a/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx b/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx index a88da51cce16e..5ad406da5ef91 100644 --- a/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx +++ b/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx @@ -2,6 +2,7 @@ import type { ThreadStructure } from "@t3tools/client-runtime/state/shell"; import { EnvironmentId, ChatAttachmentId, + ComposerContextId, MessageId, RunId, ThreadId, @@ -363,22 +364,83 @@ describe("useQueuedRunEdit", () => { expect(draft?.environmentContexts).toEqual([machine]); }); - it("saves only the thread mentions still in the edited message", async () => { + it("saves only the thread mentions and attachments still in the edited message", async () => { const { hook } = setup(); mocks.editQueuedRun.mockResolvedValue({ _tag: "Success" }); const kept = threadContextRecord(THREAD_B, "Kept"); const removed = threadContextRecord(THREAD_A, "Removed"); + const removedImageId = ChatAttachmentId.make("server-image-removed"); + const keptFileId = ChatAttachmentId.make("server-file-kept"); + const removedImageContextId = ComposerContextId.make("image_local-removed"); + const keptFileContextId = ComposerContextId.make("file_local-kept"); + const removedImage = { + type: "image" as const, + id: removedImageId, + name: "image.png", + mimeType: "image/png", + sizeBytes: 67, + }; + const keptFile = { + type: "file" as const, + id: keptFileId, + name: "legacy.pdf", + mimeType: "application/pdf", + sizeBytes: 40, + }; + const removedImageRecord = { + version: 1 as const, + kind: "image" as const, + contextId: removedImageContextId, + label: "image.png", + attachmentId: removedImageId, + name: "image.png", + mimeType: "image/png", + sizeBytes: 67, + }; + const keptFileRecord = { + version: 1 as const, + kind: "file" as const, + contextId: keptFileContextId, + label: "legacy.pdf", + attachmentId: keptFileId, + name: "legacy.pdf", + mimeType: "application/pdf", + sizeBytes: 40, + }; const messageId = MessageId.make("message-1"); - const text = [kept, removed] - .map((record) => formatInlineContextReference(threadContextReference(record))) - .join(" and "); - const messages = [{ id: messageId, text, context: { version: 1, records: [kept, removed] } }]; + const text = [ + formatInlineContextReference(threadContextReference(kept)), + formatInlineContextReference(threadContextReference(removed)), + formatInlineContextReference({ + kind: "image", + contextId: removedImageContextId, + label: "image.png", + }), + ].join(" and "); + const messages = [ + { + id: messageId, + text, + context: { version: 1, records: [kept, removed, removedImageRecord, keptFileRecord] }, + }, + ]; await using _screen = await render(view(THREAD_A, "queued", hook, messages)); - await act(() => requireHook(hook).beginEdit({ runId: RUN, messageId, text, attachments: [] })); + await act(() => + requireHook(hook).beginEdit({ + runId: RUN, + messageId, + text, + attachments: [removedImage, keptFile], + }), + ); const target = requireHook(hook).draftTarget; - await act(() => useComposerDraftStore.getState().setThreadContexts(target, [kept])); + await act(() => { + useComposerDraftStore.getState().setThreadContexts(target, [kept]); + requireHook(hook).removeEditingAttachment(removedImageId); + }); const draft = useComposerDraftStore.getState().getComposerDraft(target); + expect(draft?.prompt).not.toContain(removedImageContextId); await requireHook(hook).saveEdit( { ...savedContent(draft?.prompt ?? ""), threadContexts: draft?.threadContexts ?? [] }, () => {}, @@ -387,7 +449,11 @@ describe("useQueuedRunEdit", () => { expect(mocks.editQueuedRun).toHaveBeenCalledWith( expect.objectContaining({ input: expect.objectContaining({ - edit: expect.objectContaining({ context: { version: 1, records: [kept] } }), + text: draft?.prompt, + edit: expect.objectContaining({ + attachments: [keptFile], + context: { version: 1, records: [keptFileRecord, kept] }, + }), }), }), ); diff --git a/apps/web/src/components/chat/useQueuedRunEdit.ts b/apps/web/src/components/chat/useQueuedRunEdit.ts index 77989f8aebc0d..a33fd9177635c 100644 --- a/apps/web/src/components/chat/useQueuedRunEdit.ts +++ b/apps/web/src/components/chat/useQueuedRunEdit.ts @@ -69,6 +69,7 @@ import type { ChatComposerHandle } from "./ChatComposer"; import { fileAttachmentCapabilityBlockReason } from "./composerAttachmentFiles"; import { composerDraftContentChanged } from "./composerSend.logic"; import { + attachmentContextIdsForRecord, discardQueuedEditDraft, prepareQueuedEditAttachments, recoverQueuedMessageEdit, @@ -80,10 +81,9 @@ interface EditingQueuedRun { readonly runId: RunId; readonly messageId: MessageId; readonly originalText: string; + readonly originalAttachments: ReadonlyArray; readonly existingAttachments: ReadonlyArray; readonly context?: OrchestrationMessageContext | undefined; - /** Removing a server attachment changes the message even when the draft looks untouched. */ - readonly removedExistingAttachment?: true; } // Keyed by the route thread, so an edit survives navigating away and back. @@ -238,13 +238,34 @@ export function useQueuedRunEdit(input: { const urlByAttachmentId = new Map( imageResources.map((resource, index) => [resource.attachmentId, imageUrls[index] ?? null]), ); + const originalReferencedContextIds = + editing === null ? null : new Set(collectInlineContextIds(editing.originalText)); + const attachmentContextIds = (attachment: ChatAttachment) => + editing === null + ? [] + : attachmentContextIdsForRecord(editing.context, attachment).filter((contextId) => + originalReferencedContextIds!.has(contextId), + ); const editingAttachments = editing === null ? null : editing.existingAttachments.map((attachment) => ({ attachment, url: urlByAttachmentId.get(attachment.id) ?? null, + contextIds: attachmentContextIds(attachment), })); + const existingAttachmentIds = new Set( + (editing?.existingAttachments ?? []).map((attachment) => attachment.id), + ); + const removedEditingAttachments = + editing === null + ? [] + : editing.originalAttachments + .filter((attachment) => !existingAttachmentIds.has(attachment.id)) + .map((attachment) => ({ + attachment, + contextIds: attachmentContextIds(attachment), + })); const focusComposerSoon = () => { window.requestAnimationFrame(() => composerRef.current?.focusAtEnd()); @@ -290,6 +311,7 @@ export function useQueuedRunEdit(input: { runId: request.runId, messageId: request.messageId, originalText: text, + originalAttachments: request.attachments, existingAttachments: request.attachments, context, }, @@ -313,7 +335,13 @@ export function useQueuedRunEdit(input: { threadTarget: threadDraftTarget, originalText: edit.originalText, originalReplyTo: reply ?? null, - removedExistingAttachment: edit.removedExistingAttachment === true, + removedExistingAttachment: + edit.existingAttachments.length < edit.originalAttachments.length, + existingAttachmentContextIds: (edit.context?.records ?? []).flatMap((record) => + (record.kind === "image" || record.kind === "file") && "attachmentId" in record + ? [record.contextId] + : [], + ), }); if (recovery === "clean") return; const title = appAtomRegistry.get( @@ -345,13 +373,39 @@ export function useQueuedRunEdit(input: { focusComposerSoon(); }); const removeEditingAttachment = useStableCallback((attachmentId: string) => { + const removed = editing?.existingAttachments.find( + (attachment) => attachment.id === attachmentId, + ); + const contextIds = removed ? attachmentContextIdsForRecord(editing?.context, removed) : []; queuedRunEdits.update(editKey, (current) => ({ ...current, - removedExistingAttachment: true, existingAttachments: current.existingAttachments.filter( (attachment) => attachment.id !== attachmentId, ), })); + if (editing !== null && contextIds.length > 0) { + const target = queuedRunEditDraftId(routeThreadRef, editing.runId); + const store = useComposerDraftStore.getState(); + const currentPrompt = store.getComposerDraft(target)?.prompt ?? ""; + const nextPrompt = contextIds.reduce( + (prompt, contextId) => removeInlineContextReference(prompt, contextId).prompt, + currentPrompt, + ); + if (nextPrompt !== currentPrompt) store.setPrompt(target, nextPrompt); + } + }); + const restoreEditingAttachment = useStableCallback((attachment: ChatAttachment) => { + queuedRunEdits.update(editKey, (current) => { + const keptIds = new Set([ + ...current.existingAttachments.map((entry) => entry.id), + attachment.id, + ]); + // Filtering the originals keeps the restored attachment in its original position. + return { + ...current, + existingAttachments: current.originalAttachments.filter((entry) => keptIds.has(entry.id)), + }; + }); }); // The same move as the queued row's "Send now" while a turn runs. @@ -478,9 +532,11 @@ export function useQueuedRunEdit(input: { isSaving, draftTarget, editingAttachments, + removedEditingAttachments, beginEdit, cancelEdit, removeEditingAttachment, + restoreEditingAttachment, saveEdit, }; } diff --git a/apps/web/src/components/composerContextPresentation.test.ts b/apps/web/src/components/composerContextPresentation.test.ts index 77b0a5fb7815e..641e190ef86a3 100644 --- a/apps/web/src/components/composerContextPresentation.test.ts +++ b/apps/web/src/components/composerContextPresentation.test.ts @@ -1,8 +1,16 @@ -import { ThreadId } from "@t3tools/contracts"; +import { ChatAttachmentId, ComposerContextId, EnvironmentId, ThreadId } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { buildMessageContext } from "~/lib/composerContextRecords"; -import { composerContextRecordsFromDraft } from "./composerContextPresentation"; +import { composerFileNeedsReattach } from "~/composerDraftStore"; +import { + attachmentContextRecord, + buildMessageContext, + isSameComposerContextPayload, +} from "~/lib/composerContextRecords"; +import { + composerContextRecordsFromDraft, + uploadedContextRecordFromDraft, +} from "./composerContextPresentation"; describe("composerContextRecordsFromDraft", () => { it("resolves each wire reference to its own backing draft even when producer ids collide", () => { @@ -53,4 +61,88 @@ describe("composerContextRecordsFromDraft", () => { expect(draftRecords.get(record.contextId)?.kind).toBe(record.kind); } }); + + it("resolves existing queued attachments under their original wire context ids", () => { + const environmentId = EnvironmentId.make("env-1"); + const imageContextId = ComposerContextId.make("image_local-shot"); + const fileContextId = ComposerContextId.make("file_local-notes"); + const imageId = ChatAttachmentId.make("server-shot"); + const fileId = ChatAttachmentId.make("server-notes"); + const source = { + kind: "snap-shot" as const, + capturedAt: "2026-11-22T14:00:00.000Z", + appName: "Safari", + windowTitle: "Example", + }; + const imageAttachment = { + type: "image" as const, + id: imageId, + name: "image.png", + mimeType: "image/png", + sizeBytes: 67, + source, + }; + const draftRecords = composerContextRecordsFromDraft({ + terminalContexts: [], + environmentId, + existingAttachments: [ + { + attachment: imageAttachment, + url: "http://127.0.0.1/assets/server-shot", + contextIds: [imageContextId], + }, + { + attachment: { + type: "file", + id: fileId, + name: "notes.txt", + mimeType: "text/plain", + sizeBytes: 12, + }, + url: null, + contextIds: [fileContextId], + }, + ], + }); + + const imageEntry = draftRecords.get(imageContextId); + expect(imageEntry).toMatchObject({ + kind: "image", + record: { + id: imageId, + name: "image.png", + previewUrl: "http://127.0.0.1/assets/server-shot", + source, + }, + }); + const uploadedImageRecord = uploadedContextRecordFromDraft(imageEntry!); + expect(uploadedImageRecord).toMatchObject({ + kind: "image", + contextId: imageContextId, + attachmentId: imageId, + source, + }); + expect( + isSameComposerContextPayload( + uploadedImageRecord!, + attachmentContextRecord({ + attachment: imageAttachment, + attachmentId: imageId, + contextId: imageContextId, + }), + ), + ).toBe(true); + + const fileEntry = draftRecords.get(fileContextId); + expect(fileEntry?.kind).toBe("file"); + if (fileEntry?.kind === "file") { + expect(composerFileNeedsReattach(fileEntry.record)).toBe(false); + expect(fileEntry.record.uploadEnvironmentId).toBe(environmentId); + } + expect(uploadedContextRecordFromDraft(fileEntry!)).toMatchObject({ + kind: "file", + contextId: fileContextId, + attachmentId: fileId, + }); + }); }); diff --git a/apps/web/src/components/composerContextPresentation.tsx b/apps/web/src/components/composerContextPresentation.tsx index ab7ce9b40186b..0fb3f31e5413e 100644 --- a/apps/web/src/components/composerContextPresentation.tsx +++ b/apps/web/src/components/composerContextPresentation.tsx @@ -2,7 +2,10 @@ import ChatMarkdown from "./ChatMarkdown"; import { isSvgAttachment } from "@t3tools/shared/image"; import { ReadOnlySourcePreview } from "./files/AttachmentFilePreview"; import type { + ChatAttachment, + ComposerContextId, EnvironmentContextRecord, + EnvironmentId, PreviewAnnotationPayload, ThreadContextRecord, } from "@t3tools/contracts"; @@ -40,6 +43,7 @@ import { } from "~/lib/composerContextRecords"; import type { TerminalContextDraft } from "~/lib/terminalContext"; import type { ReviewCommentContext } from "~/reviewCommentContext"; +import { isQueuedFileAttachment, isQueuedImageAttachment } from "./chat/queuedMessageEdit"; import { ComposerPendingTerminalContextChip } from "./chat/ComposerPendingTerminalContexts"; import { EnvironmentContextChip } from "./EnvironmentContextChip"; import { ThreadContextChip } from "./ThreadContextChip"; @@ -60,6 +64,11 @@ import { UnresolvedChip, } from "./contextChipParts"; +export interface ComposerImageContextAttachment extends Omit { + readonly file: File | null; + readonly uploadedAttachmentId?: string | undefined; +} + export type ComposerDraftContextRecord = | { kind: "terminal"; record: TerminalContextDraft } | { kind: "review-comment"; record: ReviewCommentContext } @@ -68,8 +77,18 @@ export type ComposerDraftContextRecord = record: PreviewAnnotationPayload; screenshot?: ComposerImageAttachment | undefined; } - | { kind: "image"; record: ComposerImageAttachment; upload?: AttachmentUploadState | undefined } - | { kind: "file"; record: ComposerFileAttachment; upload?: AttachmentUploadState | undefined } + | { + kind: "image"; + record: ComposerImageContextAttachment; + upload?: AttachmentUploadState | undefined; + contextId?: ComposerContextId | undefined; + } + | { + kind: "file"; + record: ComposerFileAttachment; + upload?: AttachmentUploadState | undefined; + contextId?: ComposerContextId | undefined; + } | { kind: "thread"; record: ThreadContextRecord } | { kind: "environment"; record: EnvironmentContextRecord }; @@ -84,7 +103,7 @@ export const EMPTY_COMPOSER_CONTEXT_RECORDS: ComposerDraftContextRecords = new M export function uploadedContextRecordFromDraft(entry: ComposerDraftContextRecord) { if (entry.kind !== "image" && entry.kind !== "file") return null; - return uploadedAttachmentContextRecord(entry.record, entry.upload); + return uploadedAttachmentContextRecord(entry.record, entry.upload, entry.contextId); } export const ComposerContextRecordsContext = createContext( @@ -99,9 +118,44 @@ export function composerContextRecordsFromDraft(input: { environmentContexts?: ReadonlyArray; images?: ReadonlyArray; files?: ReadonlyArray; + existingAttachments?: + | ReadonlyArray<{ + readonly attachment: ChatAttachment; + readonly url: string | null; + readonly contextIds?: ReadonlyArray | undefined; + }> + | undefined; + environmentId?: EnvironmentId | undefined; uploadsByImageId?: Readonly>; }): ComposerDraftContextRecords { const records = new Map(); + for (const entry of input.existingAttachments ?? []) { + for (const contextId of entry.contextIds ?? []) { + if (isQueuedImageAttachment(entry.attachment)) { + records.set(contextId, { + kind: "image", + contextId, + record: { + ...entry.attachment, + previewUrl: entry.url ?? "", + file: null, + uploadedAttachmentId: entry.attachment.id, + }, + }); + } else if (isQueuedFileAttachment(entry.attachment)) { + records.set(contextId, { + kind: "file", + contextId, + record: { + ...entry.attachment, + file: null, + uploadedAttachmentId: entry.attachment.id, + ...(input.environmentId ? { uploadEnvironmentId: input.environmentId } : {}), + }, + }); + } + } + } for (const record of input.images ?? []) { records.set(imageContextReference(record).contextId, { kind: "image", @@ -183,7 +237,7 @@ function useUploadStatusSuffix( } function attachmentTooltip( - attachment: ComposerImageAttachment | ComposerFileAttachment, + attachment: Pick, upload: AttachmentUploadState | undefined, resolve: MessageResolver, ): string { @@ -193,7 +247,7 @@ function attachmentTooltip( } function ImageContextChip(props: { - record: ComposerImageAttachment; + record: ComposerImageContextAttachment; upload: AttachmentUploadState | undefined; }) { const actions = use(ComposerContextActionsContext); diff --git a/apps/web/src/lib/composerContextRecords.ts b/apps/web/src/lib/composerContextRecords.ts index 31b7239719f1a..6f1c9d3bb8227 100644 --- a/apps/web/src/lib/composerContextRecords.ts +++ b/apps/web/src/lib/composerContextRecords.ts @@ -9,6 +9,8 @@ import { COMPOSER_CONTEXT_TERMINAL_TEXT_MAX_CHARS, } from "@t3tools/contracts"; import type { + ChatFileAttachment, + ChatImageAttachment, ComposerContextId, ComposerContextRecord, EnvironmentContextRecord, @@ -488,39 +490,59 @@ export function fileContextReference(file: ComposerFileAttachment): ComposerCont }; } +export type ComposerContextAttachment = + | ComposerImageAttachment + | ComposerFileAttachment + | (Omit & { + readonly file: File | null; + readonly uploadedAttachmentId?: string | undefined; + }) + | ChatImageAttachment + | ChatFileAttachment; + export interface BoundComposerAttachment { - attachment: ComposerImageAttachment | ComposerFileAttachment; + attachment: ComposerContextAttachment; attachmentId: string; + contextId?: ComposerContextId | undefined; } /** Returns null until the attachment has a server id. */ export function uploadedAttachmentContextRecord( - attachment: ComposerImageAttachment | ComposerFileAttachment, + attachment: ComposerContextAttachment, upload: AttachmentUploadState | undefined, + contextId?: ComposerContextId, ): ImageContextRecord | FileContextRecord | null { const attachmentId = - attachment.type === "file" && attachment.uploadedAttachmentId !== undefined + "uploadedAttachmentId" in attachment && attachment.uploadedAttachmentId !== undefined ? attachment.uploadedAttachmentId : upload?.status === "ready" ? upload.attachmentId : undefined; - return attachmentId === undefined ? null : attachmentContextRecord({ attachment, attachmentId }); + return attachmentId === undefined + ? null + : attachmentContextRecord({ attachment, attachmentId, contextId }); } export function attachmentContextRecord( bound: BoundComposerAttachment, ): ImageContextRecord | FileContextRecord { - const { attachment, attachmentId } = bound; + const { attachment, attachmentId, contextId } = bound; const base = { version: 1 as const, - contextId: toKindScopedComposerContextId(attachment.type, attachment.id), + contextId: contextId ?? toKindScopedComposerContextId(attachment.type, attachment.id), label: sanitizeComposerContextLabel(attachment.name, attachment.type), attachmentId, name: attachment.name, mimeType: attachment.mimeType, sizeBytes: attachment.sizeBytes, }; - return attachment.type === "image" ? { ...base, kind: "image" } : { ...base, kind: "file" }; + return attachment.type === "image" + ? { + ...base, + kind: "image", + ...(attachment.source !== undefined ? { source: attachment.source } : {}), + } + : { ...base, kind: "file" }; } export function buildMessageContext(input: { From 28706aceb6fb3babf2cbae0dc0c3edd93b9b6d5f Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 11:45:51 -0800 Subject: [PATCH 193/324] fix(server): unlinking an environment ends its session on the other machine (#41005) --- apps/server/src/auth/EnvironmentAuth.ts | 23 ++++++++ apps/server/src/auth/McpOAuth.test.ts | 17 ++++++ apps/server/src/auth/McpOAuth.ts | 1 + apps/server/src/auth/mcpOAuthHttp.ts | 13 ++++ apps/server/src/cli/environment.ts | 14 +++-- .../src/mcp/toolkits/orchestrator/handlers.ts | 4 +- .../src/mcp/toolkits/orchestrator/tools.ts | 2 +- apps/server/src/peer/PeerLinks.test.ts | 16 ++++- apps/server/src/peer/PeerLinks.ts | 59 +++++++++++++++++-- .../src/provider/agentContextBudget.json | 2 +- apps/server/src/ws.ts | 3 +- .../settings/LinkedEnvironmentsSettings.tsx | 15 ++++- apps/web/src/i18n/translations/de.json | 4 +- apps/web/src/i18n/translations/en.json | 4 +- apps/web/src/i18n/translations/es.json | 4 +- apps/web/src/i18n/translations/fr.json | 4 +- apps/web/src/i18n/translations/ja.json | 4 +- apps/web/src/i18n/translations/ko.json | 4 +- apps/web/src/i18n/translations/pt-BR.json | 4 +- apps/web/src/i18n/translations/ru.json | 4 +- apps/web/src/i18n/translations/sv.json | 4 +- apps/web/src/i18n/translations/zh.json | 4 +- docs/user/remote-access.md | 6 +- packages/contracts/src/auth.ts | 9 +++ packages/contracts/src/environmentHttp.ts | 7 +++ packages/contracts/src/orchestratorMcp.ts | 1 + packages/contracts/src/peerLink.ts | 6 +- 27 files changed, 206 insertions(+), 32 deletions(-) diff --git a/apps/server/src/auth/EnvironmentAuth.ts b/apps/server/src/auth/EnvironmentAuth.ts index 202ca25310d13..977840617d04c 100644 --- a/apps/server/src/auth/EnvironmentAuth.ts +++ b/apps/server/src/auth/EnvironmentAuth.ts @@ -635,6 +635,10 @@ export class EnvironmentAuth extends Context.Service< readonly authenticateMcpClient: ( request: HttpServerRequest.HttpServerRequest, ) => Effect.Effect; + /** Ends the MCP client session `token` belongs to. False when it is no live MCP client token. */ + readonly revokeMcpClientToken: ( + token: string, + ) => Effect.Effect; readonly issueMcpClientSession: (input: { readonly label: string; readonly access: AuthMcpClientAccess; @@ -1637,6 +1641,24 @@ export const make = Effect.gen(function* () { ); }; + const revokeMcpClientToken: EnvironmentAuth["Service"]["revokeMcpClientToken"] = Effect.fn( + "EnvironmentAuth.revokeMcpClientToken", + )(function* (token) { + const session = yield* sessions.verify(token).pipe( + Effect.asSome, + Effect.catchIf(SessionStore.isSessionCredentialInvalidError, () => Effect.succeedNone), + Effect.mapError((cause) => new ServerAuthSessionCredentialValidationError({ cause })), + ); + if ( + Option.isNone(session) || + session.value.subject !== MCP_CLIENT_SUBJECT || + session.value.method !== "bearer-access-token" + ) { + return false; + } + return yield* revokeSession(session.value.sessionId); + }); + const issueMcpClientSession: EnvironmentAuth["Service"]["issueMcpClientSession"] = (input) => sessions .issue({ @@ -1719,6 +1741,7 @@ export const make = Effect.gen(function* () { issueWebSocketTicket, issueStartupPairingUrl, authenticateMcpClient, + revokeMcpClientToken, issueMcpClientSession, consumeMcpApprovalCode, }); diff --git a/apps/server/src/auth/McpOAuth.test.ts b/apps/server/src/auth/McpOAuth.test.ts index d72a716673e66..f66d0b1c6e81c 100644 --- a/apps/server/src/auth/McpOAuth.test.ts +++ b/apps/server/src/auth/McpOAuth.test.ts @@ -209,6 +209,7 @@ it.effect("derives discovery metadata from the origin the client reached", () => authorization_endpoint: `${ORIGIN}/oauth/mcp/authorize`, token_endpoint: `${ORIGIN}/oauth/mcp/token`, registration_endpoint: `${ORIGIN}/oauth/mcp/register`, + revocation_endpoint: `${ORIGIN}/oauth/mcp/revoke`, code_challenge_methods_supported: ["S256"], }); }), @@ -396,6 +397,22 @@ it.live("signs in with a pairing code and issues a token only /mcp accepts", () }), ); expect(ticket.status).toBe(401); + + // Revocation ends only an MCP client's own session; any other token is answered alike and kept. + const owner = yield* auth.exchangeBootstrapCredentialForAccessToken( + (yield* auth.issuePairingCredential()).credential, + undefined, + { deviceType: "desktop" }, + ); + const bearer = (token: string) => + HttpServerRequest.fromWeb(at("/api", { headers: { authorization: `Bearer ${token}` } })); + for (const other of ["not-a-token", owner.access_token]) { + expect((yield* handler(at("/oauth/mcp/revoke", form({ token: other })))).status).toBe(200); + } + yield* auth.authenticateHttpRequest(bearer(owner.access_token)); + const revoked = yield* handler(at("/oauth/mcp/revoke", form({ token: token.access_token }))); + expect(revoked.status).toBe(200); + yield* auth.authenticateMcpClient(bearer(token.access_token)).pipe(Effect.flip); }), ), ); diff --git a/apps/server/src/auth/McpOAuth.ts b/apps/server/src/auth/McpOAuth.ts index 9ab0bfe1c176a..e63c600ae1b2d 100644 --- a/apps/server/src/auth/McpOAuth.ts +++ b/apps/server/src/auth/McpOAuth.ts @@ -97,6 +97,7 @@ export const authorizationServerMetadata = ( authorization_endpoint: `${urls.issuer}/oauth/mcp/authorize`, token_endpoint: `${urls.issuer}/oauth/mcp/token`, registration_endpoint: `${urls.issuer}/oauth/mcp/register`, + revocation_endpoint: `${urls.issuer}/oauth/mcp/revoke`, response_types_supported: ["code"], grant_types_supported: ["authorization_code"], code_challenge_methods_supported: ["S256"], diff --git a/apps/server/src/auth/mcpOAuthHttp.ts b/apps/server/src/auth/mcpOAuthHttp.ts index 6e10362000adf..c9ffde0ecda99 100644 --- a/apps/server/src/auth/mcpOAuthHttp.ts +++ b/apps/server/src/auth/mcpOAuthHttp.ts @@ -9,6 +9,7 @@ import { } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; +import * as Redacted from "effect/Redacted"; import * as Result from "effect/Result"; import * as Schema from "effect/Schema"; import { HttpServerRequest, HttpServerResponse } from "effect/http"; @@ -20,6 +21,7 @@ import { DEFAULT_HOSTED_APP_URL } from "@t3tools/shared/connectAuth"; import * as CloudLink from "../cloud/CloudLink.ts"; import { agentApprovalAppUrlConfig } from "../cloud/publicConfig.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import * as EnvironmentAuth from "./EnvironmentAuth.ts"; import * as McpOAuth from "./McpOAuth.ts"; import { renderErrorPage } from "./mcpOAuthHtml.ts"; @@ -75,6 +77,7 @@ export const layer = HttpApiBuilder.group( "mcpOAuth", Effect.fnUntraced(function* (handlers) { const oauth = yield* McpOAuth.McpOAuth; + const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth; const cloudLink = yield* CloudLink.CloudLink; const serverEnvironment = yield* ServerEnvironment.ServerEnvironmentIdentity; const hostedAppUrl = yield* agentApprovalAppUrlConfig.pipe( @@ -205,6 +208,16 @@ export const layer = HttpApiBuilder.group( yield* noStore; return yield* oauth.exchangeCode({ request, urls: yield* requestUrls, token: payload }); }), + ) + .handle("revoke", ({ payload }) => + Effect.gen(function* () { + yield* noStore; + // RFC 7009 §2.2: an unknown or already revoked token gets the same 200 as a revoked one. + if (payload.token === undefined) return; + yield* environmentAuth + .revokeMcpClientToken(Redacted.value(payload.token)) + .pipe(Effect.orDie); + }), ); }), ); diff --git a/apps/server/src/cli/environment.ts b/apps/server/src/cli/environment.ts index 8c6d2ab78c041..9243d0340eabf 100644 --- a/apps/server/src/cli/environment.ts +++ b/apps/server/src/cli/environment.ts @@ -293,16 +293,20 @@ const environmentUnlinkCommand = Command.make("unlink", { ), }).pipe( Command.withDescription( - "Forget a linked environment here. Revoke it in that environment's Sharing & access to end its session there too.", + "Forget a linked environment here, and end its session there when that environment answers.", ), Command.withHandler((flags) => runWithPeerLinks(flags, (links) => Effect.gen(function* () { - const removed = yield* links.unlink(EnvironmentId.make(flags.environmentId)); + const { removed, endedThere } = yield* links.unlink( + EnvironmentId.make(flags.environmentId), + ); yield* Console.log( - removed - ? `Forgot ${flags.environmentId}. Revoke it in that environment's Sharing & access to end its session there.\n` - : `No linked environment ${flags.environmentId}.\n`, + !removed + ? `No linked environment ${flags.environmentId}.\n` + : endedThere + ? `Forgot ${flags.environmentId} and ended its session there.\n` + : `Forgot ${flags.environmentId}. It did not answer, so revoke it in that environment's Sharing & access to end its session there.\n`, ); }), ), diff --git a/apps/server/src/mcp/toolkits/orchestrator/handlers.ts b/apps/server/src/mcp/toolkits/orchestrator/handlers.ts index d90a118be468e..57932ac21a619 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/handlers.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/handlers.ts @@ -218,7 +218,7 @@ const handlers = { t3_environment_unlink: McpToolAccess.writesEnvironment(({ environmentId }) => Effect.gen(function* () { const links = yield* PeerLinks.PeerLinks; - const removed = yield* links + const result = yield* links .unlink(environmentId) .pipe( Effect.mapError( @@ -226,7 +226,7 @@ const handlers = { new OrchestratorMcpFailure({ code: "orchestration_error", message: error.message }), ), ); - return { environmentId, removed }; + return { environmentId, ...result }; }), ), t3_thread_interrupt: McpToolAccess.writesThreads( diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.ts index b2866bb0babc5..f617b61fabaa3 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts @@ -350,7 +350,7 @@ const EnvironmentLinkTool = Tool.make("t3_environment_link", { const EnvironmentUnlinkTool = Tool.make("t3_environment_unlink", { description: - "Forget a linked environment. That machine's Connections list its session until revoked there.", + "Forget a linked environment. Its session on that machine ends too when the machine answers.", parameters: OrchestratorMcpEnvironmentUnlinkInput, success: OrchestratorMcpEnvironmentUnlinkResult, failure: OrchestratorMcpFailure, diff --git a/apps/server/src/peer/PeerLinks.test.ts b/apps/server/src/peer/PeerLinks.test.ts index 0b1f4f716474c..8f1d6cc381d63 100644 --- a/apps/server/src/peer/PeerLinks.test.ts +++ b/apps/server/src/peer/PeerLinks.test.ts @@ -157,7 +157,7 @@ it.effect("routes peer reads to readers and sees uncommitted link updates", () = expect((yield* links.list)[0]?.label).toBe("Uncommitted box"); }), ); - expect(yield* links.unlink(box.environmentId)).toBe(true); + expect(yield* links.unlink(box.environmentId)).toEqual({ removed: true, endedThere: false }); expect(yield* links.list).toEqual([]); }), ); @@ -206,6 +206,20 @@ it.effect("links with a pairing code, and the peer holds its agents to the limit // A refusal keeps the peer's reason. const notFound = yield* probe(a, undefined, "refuse").pipe(Effect.flip); expect(notFound).toMatchObject({ code: "thread_not_found", message: "No such thread." }); + + // Unlinking ends the session on B too, instead of leaving a live credential behind. + expect(yield* a.links.unlink(box.environmentId)).toEqual({ removed: true, endedThere: true }); + expect(yield* linkedSessions(b)).toEqual([]); + + // An address that now answers as another environment never receives the token. + const other = yield* serveApart(descriptorOf("environment-other", "Other")); + const relink = yield* b.auth.issuePairingCredential({ access: "auto", purpose: "peer-link" }); + yield* a.links.link({ url: b.url, pairingCode: relink.credential, access: "auto" }); + yield* a.sql`UPDATE peer_environment_links SET urls_json = ${JSON.stringify([other.url])}`; + expect(yield* a.links.unlink(box.environmentId)).toEqual({ + removed: true, + endedThere: false, + }); }), ).pipe(Effect.provide(NodeHttpServer.layerTest)), ); diff --git a/apps/server/src/peer/PeerLinks.ts b/apps/server/src/peer/PeerLinks.ts index 5325e5745c5d7..859266c469c70 100644 --- a/apps/server/src/peer/PeerLinks.ts +++ b/apps/server/src/peer/PeerLinks.ts @@ -116,8 +116,10 @@ export class PeerLinks extends Context.Service< readonly get: ( environmentId: EnvironmentId, ) => Effect.Effect, PeerLinkError>; - /** Forgets the link here. The peer still lists the session until it is revoked there. */ - readonly unlink: (environmentId: EnvironmentId) => Effect.Effect; + /** Forgets the link here, then asks the peer to end the link's session. */ + readonly unlink: ( + environmentId: EnvironmentId, + ) => Effect.Effect<{ readonly removed: boolean; readonly endedThere: boolean }, PeerLinkError>; /** An address that answers as the linked peer, with its token, ready to call. */ readonly resolve: ( environmentId: EnvironmentId, @@ -665,16 +667,63 @@ const make = Effect.gen(function* () { ), ); + /** Best effort: a peer that is gone or too old to revoke lets its session expire instead. */ + const revokeAtPeer = Effect.fn("PeerLinks.revokeAtPeer")( + function* (environmentId: EnvironmentId, urlsJson: string, token: string) { + const urls = yield* decodeUrls(urlsJson); + // A race over no addresses never settles. + if (urls.length === 0) return false; + yield* Effect.raceAll( + urls.map((url) => + // An address can change hands after linking; only the linked peer may see the token. + answersAs(url, environmentId).pipe( + Effect.flatMap(Effect.fromOption), + Effect.andThen(clientFor(url)), + Effect.flatMap((client) => + client.mcpOAuth + .revoke({ payload: { token: Redacted.make(token) } }) + .pipe(Effect.timeout(probeTimeout(url))), + ), + ), + ), + ); + return true; + }, + Effect.catchCause((cause) => + Effect.logDebug("The unlinked peer did not revoke the link's session", { cause }).pipe( + Effect.as(false), + ), + ), + ); + const unlink: PeerLinks["Service"]["unlink"] = Effect.fn("PeerLinks.unlink")( function* (environmentId) { - const deleted = yield* sql<{ secret_name: string }>` + const deleted = yield* sql<{ secret_name: string; urls_json: string }>` DELETE FROM peer_environment_links WHERE environment_id = ${environmentId} - RETURNING secret_name + RETURNING secret_name, urls_json `.pipe(Effect.catch(failStorage)); + let endedThere = false; for (const row of deleted) { + // Unreadable only skips the revocation; the secret is still removed below. + const token = yield* secrets + .get(row.secret_name) + .pipe( + Effect.catch((cause) => + Effect.logWarning("Could not read the unlinked peer's token", { cause }).pipe( + Effect.as(Option.none()), + ), + ), + ); yield* secrets.remove(row.secret_name).pipe(Effect.catch(failStorage)); + if (Option.isSome(token)) { + endedThere = yield* revokeAtPeer( + environmentId, + row.urls_json, + new TextDecoder().decode(token.value), + ); + } } - return deleted.length > 0; + return { removed: deleted.length > 0, endedThere }; }, ); diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 222f23b6b02d9..4d4286111477f 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 6245, "codexAdditionalContextBytes": 7639, - "mcpToolListJsonBytes": 59170 + "mcpToolListJsonBytes": 59168 } diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index d1db4372ab871..b5faaaa16f97c 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -2734,8 +2734,7 @@ export const layerWsRpc = ( [WS_METHODS.peerLinksNames]: (_input) => peerLinks.names.pipe(Effect.map((links) => ({ links }))), [WS_METHODS.peerLinksLink]: (input) => peerLinks.link(input), - [WS_METHODS.peerLinksUnlink]: ({ environmentId }) => - peerLinks.unlink(environmentId).pipe(Effect.map((removed) => ({ removed }))), + [WS_METHODS.peerLinksUnlink]: ({ environmentId }) => peerLinks.unlink(environmentId), [WS_METHODS.peerLinksSubscribeThread]: (input) => peerThreadRelay.subscribe(input), [WS_METHODS.peerLinksThreadHistoryPage]: (input) => Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe( diff --git a/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx b/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx index 954c0e1c4ee3c..5ab6debec7255 100644 --- a/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx +++ b/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx @@ -659,7 +659,7 @@ export function useForgetPeerLink(environmentId: EnvironmentId, link: PeerLinkSu const forget = async () => { const confirmed = await (requestConfirmDialog( gt( - "Forget {label}? Agents here stop working there. Revoke \"T3 Code · …\" in {label}''s Sharing & access to end the session there too.", + "Forget {label}? Agents here stop working there, and their session on {label} ends too if it answers.", { label: link.label }, ), { variant: "destructive" }, @@ -668,7 +668,18 @@ export function useForgetPeerLink(environmentId: EnvironmentId, link: PeerLinkSu setBusy(true); const result = await unlink({ environmentId, input: { environmentId: link.environmentId } }); setBusy(false); - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { + if (result._tag === "Success") { + if (result.value.removed && result.value.endedThere !== true) { + toastManager.add({ + type: "warning", + title: gt("{label} did not answer", { label: link.label }), + description: gt( + "Revoke \"T3 Code · …\" in {label}''s Sharing & access to end the session there too.", + { label: link.label }, + ), + }); + } + } else if (!isAtomCommandInterrupted(result)) { failureToast(gt("Could not forget the link"), String(squashAtomCommandFailure(result))); } }; diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 0db2fb8989ce2..c9aebc46cd49d 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -8928,7 +8928,9 @@ "fb71127e5746a6bc": "Unter „Freigabe & Zugriff“ dort oder mit t3 pair", "1e3fee7084791773": "Auch {target} zurück mit {source} verknüpfen", "ea34a190b0bd804c": "Agenten auf {target} können dann auch auf {source} arbeiten.", - "ad5ed0ce61b966eb": "{label} vergessen? Agenten von hier arbeiten dort nicht mehr. Widerrufe „T3 Code · …“ unter „Freigabe & Zugriff“ auf {label}, um die Sitzung auch dort zu beenden.", + "974f8c65e8b5f492": "{label} vergessen? Agenten hier arbeiten dort nicht mehr, und ihre Sitzung auf {label} endet ebenfalls, wenn es antwortet.", + "6cf9e3083b15614f": "{label} hat nicht geantwortet", + "34ccbdf619b83be3": "Widerrufe „T3 Code · …“ unter „Freigabe & Zugriff“ auf {label}, um die Sitzung auch dort zu beenden.", "81c9796bf61b306a": "Verknüpfung konnte nicht vergessen werden", "130e51beb6cf5aad": "Umgebung verknüpfen", "122c3e355699e69d": "Agenten hier können dort dann Threads starten, ihnen Nachrichten senden und auf sie warten. Sie erscheint unter „Autorisierte Clients“ in „Freigabe & Zugriff“ dieser Umgebung und kann dort widerrufen werden.", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 3aa61a18f6b2b..0808df7eab79b 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -8936,7 +8936,9 @@ "fb71127e5746a6bc": "From Sharing & access there, or t3 pair", "1e3fee7084791773": "Also link {target} back to {source}", "ea34a190b0bd804c": "Agents on {target} can then work on {source} too.", - "ad5ed0ce61b966eb": "Forget {label}? Agents here stop working there. Revoke \"T3 Code · …\" in {label}''s Sharing & access to end the session there too.", + "974f8c65e8b5f492": "Forget {label}? Agents here stop working there, and their session on {label} ends too if it answers.", + "6cf9e3083b15614f": "{label} did not answer", + "34ccbdf619b83be3": "Revoke \"T3 Code · …\" in {label}''s Sharing & access to end the session there too.", "81c9796bf61b306a": "Could not forget the link", "130e51beb6cf5aad": "Link an environment", "122c3e355699e69d": "Agents here can then launch, message and wait on threads there. It appears under Authorized clients in that environment's Sharing & access, where it can be revoked.", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 60ddca69b570f..88f660710fce2 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -8926,7 +8926,9 @@ "fb71127e5746a6bc": "Desde Compartir y acceso allí, o t3 pair", "1e3fee7084791773": "Vincular también {target} de vuelta a {source}", "ea34a190b0bd804c": "Los agentes de {target} podrán trabajar también en {source}.", - "ad5ed0ce61b966eb": "¿Olvidar {label}? Los agentes de aquí dejarán de trabajar allí. Revoca \"T3 Code · …\" en Compartir y acceso de {label} para cerrar también la sesión allí.", + "974f8c65e8b5f492": "¿Olvidar {label}? Los agentes de aquí dejan de trabajar allí, y su sesión en {label} también termina si responde.", + "6cf9e3083b15614f": "{label} no respondió", + "34ccbdf619b83be3": "Revoca \"T3 Code · …\" en Compartir y acceso de {label} para cerrar también la sesión allí.", "81c9796bf61b306a": "No se pudo olvidar el vínculo", "130e51beb6cf5aad": "Vincular un entorno", "122c3e355699e69d": "Así los agentes de aquí podrán iniciar hilos allí, enviarles mensajes y esperarlos. Aparece en Clientes autorizados, en Compartir y acceso de ese entorno, donde se puede revocar.", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index fdcba31a1032f..114dd21e96fd4 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -8928,7 +8928,9 @@ "fb71127e5746a6bc": "Depuis Partage et accès sur cette machine, ou t3 pair", "1e3fee7084791773": "Associer aussi {target} en retour à {source}", "ea34a190b0bd804c": "Les agents de {target} pourront alors aussi travailler sur {source}.", - "ad5ed0ce61b966eb": "Oublier {label} ? Les agents d’ici cessent d’y travailler. Révoquez « T3 Code · … » dans Partage et accès sur {label} pour y fermer aussi la session.", + "974f8c65e8b5f492": "Oublier {label} ? Les agents d’ici cessent d’y travailler, et leur session sur {label} prend fin aussi s’il répond.", + "6cf9e3083b15614f": "{label} n’a pas répondu", + "34ccbdf619b83be3": "Révoquez « T3 Code · … » dans Partage et accès sur {label} pour y fermer aussi la session.", "81c9796bf61b306a": "Impossible d’oublier l’association", "130e51beb6cf5aad": "Associer un environnement", "122c3e355699e69d": "Les agents d’ici pourront alors lancer des fils là-bas, leur envoyer des messages et les attendre. L’association apparaît sous Clients autorisés dans Partage et accès de cet environnement, où elle peut être révoquée.", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 13379225ecf26..e207333046ee3 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -8884,7 +8884,9 @@ "fb71127e5746a6bc": "リンク先の「共有とアクセス」、または t3 pair から", "1e3fee7084791773": "{target} から {source} へも逆方向にリンクする", "ea34a190b0bd804c": "{target} のエージェントも {source} で作業できるようになります。", - "ad5ed0ce61b966eb": "{label} を削除しますか?ここのエージェントはそこで作業できなくなります。そこでのセッションも終了するには、{label} の「共有とアクセス」で \"T3 Code · …\" を取り消してください。", + "974f8c65e8b5f492": "{label} を削除しますか?ここのエージェントはそこで作業できなくなり、{label} が応答すればそこでのセッションも終了します。", + "6cf9e3083b15614f": "{label} が応答しませんでした", + "34ccbdf619b83be3": "そこでのセッションも終了するには、{label} の「共有とアクセス」で \"T3 Code · …\" を取り消してください。", "81c9796bf61b306a": "リンクを削除できませんでした", "130e51beb6cf5aad": "環境をリンク", "122c3e355699e69d": "これで、ここのエージェントがそこでスレッドを起動し、メッセージを送り、完了を待てるようになります。リンクはその環境の「共有とアクセス」の「承認済みクライアント」に表示され、そこで取り消せます。", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index cc8261d7681ff..d0c34a39635f7 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -8887,7 +8887,9 @@ "fb71127e5746a6bc": "그곳의 공유 및 액세스 또는 t3 pair에서", "1e3fee7084791773": "{target}에서 {source}(으)로도 반대 방향 연결", "ea34a190b0bd804c": "그러면 {target}의 에이전트도 {source}에서 작업할 수 있습니다.", - "ad5ed0ce61b966eb": "{label}을(를) 삭제할까요? 이곳의 에이전트가 그곳에서 더 이상 작업하지 않습니다. 그곳의 세션도 끝내려면 {label}의 공유 및 액세스에서 \"T3 Code · …\"를 취소하세요.", + "974f8c65e8b5f492": "{label}을(를) 잊을까요? 여기의 에이전트는 그곳에서 더 이상 작업하지 않으며, {label}이(가) 응답하면 그곳의 세션도 종료됩니다.", + "6cf9e3083b15614f": "{label}이(가) 응답하지 않았습니다", + "34ccbdf619b83be3": "그곳의 세션도 끝내려면 {label}의 공유 및 액세스에서 \"T3 Code · …\"를 취소하세요.", "81c9796bf61b306a": "링크를 삭제할 수 없습니다", "130e51beb6cf5aad": "환경 연결", "122c3e355699e69d": "그러면 이곳의 에이전트가 그곳에서 스레드를 시작하고, 메시지를 보내고, 기다릴 수 있습니다. 해당 환경의 공유 및 액세스에서 승인된 클라이언트에 표시되며 그곳에서 취소할 수 있습니다.", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index a9ce3832a0b9f..d32f4d0a45121 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -8927,7 +8927,9 @@ "fb71127e5746a6bc": "Em Compartilhamento e acesso de lá, ou t3 pair", "1e3fee7084791773": "Vincular também {target} de volta a {source}", "ea34a190b0bd804c": "Os agentes de {target} poderão trabalhar também em {source}.", - "ad5ed0ce61b966eb": "Esquecer {label}? Os agentes daqui deixam de funcionar lá. Revogue \"T3 Code · …\" em Compartilhamento e acesso de {label} para encerrar a sessão lá também.", + "974f8c65e8b5f492": "Esquecer {label}? Os agentes daqui param de trabalhar lá, e a sessão deles em {label} também termina se ele responder.", + "6cf9e3083b15614f": "{label} não respondeu", + "34ccbdf619b83be3": "Revogue \"T3 Code · …\" em Compartilhamento e acesso de {label} para encerrar a sessão lá também.", "81c9796bf61b306a": "Não foi possível esquecer o vínculo", "130e51beb6cf5aad": "Vincular um ambiente", "122c3e355699e69d": "Os agentes daqui poderão então iniciar threads lá, enviar mensagens e aguardá-las. Ele aparece em Clientes autorizados em Compartilhamento e acesso daquele ambiente, onde pode ser revogado.", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index ee0fe30aa4f39..c000355e83081 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -8928,7 +8928,9 @@ "fb71127e5746a6bc": "Из раздела «Общий доступ» там или через t3 pair", "1e3fee7084791773": "Также привязать {target} в ответ к {source}", "ea34a190b0bd804c": "Тогда агенты на {target} смогут работать и на {source}.", - "ad5ed0ce61b966eb": "Забыть {label}? Агенты отсюда перестанут там работать. Чтобы завершить сеанс и там, отзовите «T3 Code · …» в разделе «Общий доступ» на {label}.", + "974f8c65e8b5f492": "Забыть {label}? Агенты отсюда перестанут там работать, а их сеанс на {label} тоже завершится, если он ответит.", + "6cf9e3083b15614f": "{label} не ответил", + "34ccbdf619b83be3": "Чтобы завершить сеанс и там, отзовите «T3 Code · …» в разделе «Общий доступ» на {label}.", "81c9796bf61b306a": "Не удалось забыть привязку", "130e51beb6cf5aad": "Привязать окружение", "122c3e355699e69d": "После этого агенты отсюда смогут запускать треды там, писать в них и ждать их. Связь появится в разделе «Авторизованные клиенты» в «Общем доступе» того окружения, где её можно отозвать.", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index fb02753220b14..a9bfc4cecbe7e 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -8934,7 +8934,9 @@ "fb71127e5746a6bc": "Från Delning och åtkomst där, eller t3 pair", "1e3fee7084791773": "Länka även {target} tillbaka till {source}", "ea34a190b0bd804c": "Agenter på {target} kan då också arbeta på {source}.", - "ad5ed0ce61b966eb": "Glöm {label}? Agenter här slutar arbeta där. Återkalla ”T3 Code · …” under Delning och åtkomst på {label} för att avsluta sessionen där också.", + "974f8c65e8b5f492": "Glöm {label}? Agenter här slutar arbeta där, och deras session på {label} avslutas också om den svarar.", + "6cf9e3083b15614f": "{label} svarade inte", + "34ccbdf619b83be3": "Återkalla ”T3 Code · …” under Delning och åtkomst på {label} för att avsluta sessionen där också.", "81c9796bf61b306a": "Kunde inte glömma länken", "130e51beb6cf5aad": "Länka en miljö", "122c3e355699e69d": "Agenter här kan sedan starta, skicka meddelanden till och vänta på trådar där. Den visas under Auktoriserade klienter i miljöns Delning och åtkomst, där den kan återkallas.", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 04044302284b7..2169040ad1c51 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -8944,7 +8944,9 @@ "fb71127e5746a6bc": "从远端“共享与访问”页面或 t3 pair 获取", "1e3fee7084791773": "同时将 {target} 反向关联到 {source}", "ea34a190b0bd804c": "之后 {target} 上的智能体也能在 {source} 上工作。", - "ad5ed0ce61b966eb": "忘记 {label}?此处的智能体将停止在那里工作。在 {label} 的“共享与访问”中撤销“T3 Code · …”,以同时结束那里的连接。", + "974f8c65e8b5f492": "忘记 {label}?此处的代理将不再在那里工作;如果 {label} 有响应,它们在那里的会话也会结束。", + "6cf9e3083b15614f": "{label} 没有响应", + "34ccbdf619b83be3": "在 {label} 的“共享与访问”中撤销“T3 Code · …”,以同时结束那里的连接。", "81c9796bf61b306a": "无法移除关联", "130e51beb6cf5aad": "关联环境", "122c3e355699e69d": "这里的智能体随后就能在该环境中启动会话、发送消息并等待结果。此连接将显示在该环境“共享与访问”的“已授权客户端”中,可在那里撤销。", diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md index 99255db9ac8cb..051445f03eb07 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -468,8 +468,10 @@ an address you trust: the code is sent there. machine's own threads, projects or settings, and they skip its project setup scripts. - The link shows up in that machine's **Settings → Sharing & access** like any - outside agent. Revoke it there to end it. **Forget** on this machine only - removes it here. + outside agent, and can be revoked there. **Forget** on this machine also ends + it there when that machine confirms it. If it can't, such as when it is + offline or on an older T3 Code, Forget says so; revoke it in that machine's + Sharing & access. - A link stays valid while agents use it. One unused for 30 days expires, as does one to a machine on an older T3 Code after 30 days; link again with a new pairing code. diff --git a/packages/contracts/src/auth.ts b/packages/contracts/src/auth.ts index 826ffeb6b258e..5a630a6b7abe9 100644 --- a/packages/contracts/src/auth.ts +++ b/packages/contracts/src/auth.ts @@ -554,6 +554,8 @@ export const AuthMcpAuthorizationServerMetadata = Schema.Struct({ authorization_endpoint: Schema.String, token_endpoint: Schema.String, registration_endpoint: Schema.String, + // Older environments do not serve one. + revocation_endpoint: Schema.optionalKey(Schema.String), response_types_supported: Schema.Array(Schema.Literal("code")), grant_types_supported: Schema.Array(Schema.Literal("authorization_code")), code_challenge_methods_supported: Schema.Array(Schema.Literal("S256")), @@ -670,6 +672,13 @@ export const AuthMcpTokenRequest = Schema.Struct({ }).pipe(HttpApiSchema.asFormUrlEncoded()); export type AuthMcpTokenRequest = typeof AuthMcpTokenRequest.Type; +/** RFC 7009: the holder of an access token ends its session. */ +export const AuthMcpRevokeRequest = Schema.Struct({ + token: Schema.optionalKey(Schema.RedactedFromValue(Schema.String)), + token_type_hint: Schema.optionalKey(Schema.String), +}).pipe(HttpApiSchema.asFormUrlEncoded()); +export type AuthMcpRevokeRequest = typeof AuthMcpRevokeRequest.Type; + export const AuthMcpTokenResult = Schema.Struct({ access_token: Schema.String, token_type: Schema.Literal("Bearer"), diff --git a/packages/contracts/src/environmentHttp.ts b/packages/contracts/src/environmentHttp.ts index 9b5cd9a0cb5c1..2a6c0dc43d50c 100644 --- a/packages/contracts/src/environmentHttp.ts +++ b/packages/contracts/src/environmentHttp.ts @@ -25,6 +25,7 @@ import { AuthMcpRegisteredClient, AuthMcpRegistrationError, AuthMcpTokenError, + AuthMcpRevokeRequest, AuthMcpTokenRequest, AuthMcpTokenResult, AuthPairingCredentialResult, @@ -725,6 +726,12 @@ class EnvironmentMcpOAuthHttpApi extends HttpApiGroup.make("mcpOAuth") success: AuthMcpTokenResult, error: AuthMcpTokenError, }), + ) + .add( + HttpApiEndpoint.post("revoke", "/oauth/mcp/revoke", { + payload: AuthMcpRevokeRequest, + success: HttpApiSchema.Empty(200), + }), ) {} const EnvironmentOrchestrationThreadSnapshotParams = Schema.Struct({ diff --git a/packages/contracts/src/orchestratorMcp.ts b/packages/contracts/src/orchestratorMcp.ts index f84d003ed12e3..49595364ad786 100644 --- a/packages/contracts/src/orchestratorMcp.ts +++ b/packages/contracts/src/orchestratorMcp.ts @@ -965,6 +965,7 @@ export type OrchestratorMcpEnvironmentUnlinkInput = export const OrchestratorMcpEnvironmentUnlinkResult = Schema.Struct({ environmentId: EnvironmentId, removed: Schema.Boolean, + endedThere: Schema.Boolean, }); export type OrchestratorMcpEnvironmentUnlinkResult = typeof OrchestratorMcpEnvironmentUnlinkResult.Type; diff --git a/packages/contracts/src/peerLink.ts b/packages/contracts/src/peerLink.ts index 6f33686b4b37b..3ff0fe93228d8 100644 --- a/packages/contracts/src/peerLink.ts +++ b/packages/contracts/src/peerLink.ts @@ -63,7 +63,11 @@ export type PeerLinkCreateInput = typeof PeerLinkCreateInput.Type; export const PeerLinkRemoveInput = Schema.Struct({ environmentId: EnvironmentId }); export type PeerLinkRemoveInput = typeof PeerLinkRemoveInput.Type; -export const PeerLinkRemoveResult = Schema.Struct({ removed: Schema.Boolean }); +export const PeerLinkRemoveResult = Schema.Struct({ + removed: Schema.Boolean, + // Whether the peer ended the link's session. Older servers never ask it to. + endedThere: Schema.optionalKey(Schema.Boolean), +}); export type PeerLinkRemoveResult = typeof PeerLinkRemoveResult.Type; /** Why linking or calling a peer failed, in words a user can act on. */ From 7ed41b7c238dc6e61c750d8fad806811e9fd1b6f Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:57:57 +0100 Subject: [PATCH 194/324] fix(mobile): scope Git result banners to their originating thread (#41015) Co-authored-by: Julius Marminge --- .../features/threads/ThreadRouteScreen.tsx | 9 +- .../use-selected-thread-git-actions.test.ts | 7 +- .../state/use-selected-thread-git-actions.ts | 20 ++- .../src/state/use-vcs-action-state.test.ts | 24 ---- .../src/state/use-vcs-action-state.test.tsx | 123 ++++++++++++++++++ apps/mobile/src/state/use-vcs-action-state.ts | 65 +++++---- apps/mobile/vite.config.ts | 1 + 7 files changed, 187 insertions(+), 62 deletions(-) delete mode 100644 apps/mobile/src/state/use-vcs-action-state.test.ts create mode 100644 apps/mobile/src/state/use-vcs-action-state.test.tsx diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx index c4a6ae091a397..8f509de9e674a 100644 --- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx @@ -589,12 +589,11 @@ function ThreadRouteContent( environmentId: selectedThread?.environmentId ?? null, cwd: selectedThreadCwd, }; - const gitActionProgress = useGitActionProgress( - gitActionProgressTarget, + const gitActionThreadRef = selectedThread === null ? null - : { environmentId: selectedThread.environmentId, threadId: selectedThread.id }, - ); + : { environmentId: selectedThread.environmentId, threadId: selectedThread.id }; + const gitActionProgress = useGitActionProgress(gitActionProgressTarget, gitActionThreadRef); const handleOpenGitInspector = () => { navigation.setParams({ inspector: undefined }); @@ -1033,7 +1032,7 @@ function ThreadRouteContent( <> dismissGitActionResult(gitActionThreadRef)} onOpenPullRequest={openPullRequest} /> diff --git a/apps/mobile/src/state/use-selected-thread-git-actions.test.ts b/apps/mobile/src/state/use-selected-thread-git-actions.test.ts index e143c2d032eeb..42953ef7886fe 100644 --- a/apps/mobile/src/state/use-selected-thread-git-actions.test.ts +++ b/apps/mobile/src/state/use-selected-thread-git-actions.test.ts @@ -333,7 +333,12 @@ describe("automatic feature branch refs", () => { ); expect(await useSelectedThreadGitActions().refreshSelectedThreadBranches()).toBeNull(); expect(state.results).toEqual([ - { type: "error", title: "Git action failed", description: "Cannot list refs" }, + { + threadRef: { environmentId: "environment", threadId: "thread" }, + type: "error", + title: "Git action failed", + description: "Cannot list refs", + }, ]); }); }); diff --git a/apps/mobile/src/state/use-selected-thread-git-actions.ts b/apps/mobile/src/state/use-selected-thread-git-actions.ts index 1a40c455ac055..f42b64cf1b3a7 100644 --- a/apps/mobile/src/state/use-selected-thread-git-actions.ts +++ b/apps/mobile/src/state/use-selected-thread-git-actions.ts @@ -36,7 +36,11 @@ import { } from "./use-remote-environment-registry"; import { useAtomCommand } from "./use-atom-command"; import type { GitRepositoryTarget } from "./thread-git-target"; -import { noteRepositoryGitAction, showGitActionResult } from "./use-vcs-action-state"; +import { + noteRepositoryGitAction, + showGitActionResult, + type GitActionResultNotification, +} from "./use-vcs-action-state"; import { useThreadSelection } from "./use-thread-selection"; import { useSelectedThreadWorktree } from "./use-selected-thread-worktree"; @@ -71,6 +75,12 @@ export function useSelectedThreadGitActions(repository?: GitRepositoryTarget) { const createWorktree = useAtomCommand(vcsEnvironment.createWorktree, { reportFailure: false }); const pull = useAtomCommand(vcsEnvironment.pull, { reportFailure: false }); const { selectedThread, selectedThreadProject } = useThreadSelection(); + const threadRef = selectedThread + ? { environmentId: selectedThread.environmentId, threadId: selectedThread.id } + : null; + const reportGitActionResult = (result: GitActionResultNotification) => { + if (threadRef !== null) showGitActionResult({ ...result, threadRef }); + }; const canWriteSourceControl = useEnvironmentScope( selectedThread?.environmentId ?? null, AuthSourceControlWriteScope, @@ -223,7 +233,7 @@ export function useSelectedThreadGitActions(repository?: GitRepositoryTarget) { const error = Cause.squash(result.cause); const message = errorDisplayMessage(error, m) ?? m(msg("Git action failed.")); setPendingConnectionError(message); - showGitActionResult({ + reportGitActionResult({ type: "error", title: m(msg("Git action failed")), description: message, @@ -243,7 +253,7 @@ export function useSelectedThreadGitActions(repository?: GitRepositoryTarget) { const error = Cause.squash(result.cause); const message = errorDisplayMessage(error, m) ?? m(msg("Failed to refresh branches.")); setPendingConnectionError(message); - showGitActionResult({ + reportGitActionResult({ type: "error", title: m(msg("Git action failed")), description: message, @@ -377,7 +387,7 @@ export function useSelectedThreadGitActions(repository?: GitRepositoryTarget) { return result; } await refreshSelectedThreadGitStatus({ quiet: true, cwd }); - showGitActionResult({ + reportGitActionResult({ type: "success", title: result.value.status === "skipped_up_to_date" @@ -424,7 +434,7 @@ export function useSelectedThreadGitActions(repository?: GitRepositoryTarget) { } else { await refreshSelectedThreadGitStatus({ quiet: true, cwd }); } - showGitActionResult({ + reportGitActionResult({ type: "success", title: result.value.toast.title, description: result.value.toast.description, diff --git a/apps/mobile/src/state/use-vcs-action-state.test.ts b/apps/mobile/src/state/use-vcs-action-state.test.ts deleted file mode 100644 index 5d6409bdb1290..0000000000000 --- a/apps/mobile/src/state/use-vcs-action-state.test.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { describe, expect, it, vi } from "vite-plus/test"; - -const mocks = vi.hoisted(() => ({ - notificationAsync: vi.fn(() => Promise.resolve()), -})); - -vi.mock("expo-haptics", () => ({ - NotificationFeedbackType: { Success: "success", Error: "error" }, - notificationAsync: mocks.notificationAsync, -})); - -vi.mock("./vcs", () => ({ vcsActionManager: {} })); - -import { dismissGitActionResult, showGitActionResult } from "./use-vcs-action-state"; - -describe("showGitActionResult", () => { - it("buzzes once per reported result with the matching feedback type", () => { - showGitActionResult({ type: "success", title: "Pushed" }); - showGitActionResult({ type: "error", title: "Git action failed", description: "rejected" }); - dismissGitActionResult(); - - expect(mocks.notificationAsync.mock.calls).toEqual([["success"], ["error"]]); - }); -}); diff --git a/apps/mobile/src/state/use-vcs-action-state.test.tsx b/apps/mobile/src/state/use-vcs-action-state.test.tsx new file mode 100644 index 0000000000000..32bcb84d351fb --- /dev/null +++ b/apps/mobile/src/state/use-vcs-action-state.test.tsx @@ -0,0 +1,123 @@ +import { RegistryContext } from "@effect/atom-react"; +import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts"; +import { act } from "react"; +import { createRoot } from "react-dom/client"; +import { describe, expect, it, vi } from "vite-plus/test"; + +const mocks = vi.hoisted(() => ({ + notificationAsync: vi.fn(() => Promise.resolve()), +})); + +vi.mock("expo-haptics", () => ({ + NotificationFeedbackType: { Success: "success", Error: "error" }, + notificationAsync: mocks.notificationAsync, +})); + +vi.mock("./vcs", async () => { + const { Atom } = await import("effect/reactivity"); + const idle = Atom.make({ isRunning: false }); + return { vcsActionManager: { stateAtom: () => idle } }; +}); + +import { appAtomRegistry } from "./atom-registry"; +import { + dismissGitActionResult, + showGitActionResult, + useGitActionProgress, +} from "./use-vcs-action-state"; + +const owner = { environmentId: EnvironmentId.make("first"), threadId: ThreadId.make("thread-a") }; +const otherThread = { ...owner, threadId: ThreadId.make("thread-b") }; + +function mountGitBanner() { + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + const container = document.createElement("div"); + const root = createRoot(container); + + function Banner({ threadRef }: { readonly threadRef: ScopedThreadRef | null }) { + const progress = useGitActionProgress( + { environmentId: threadRef?.environmentId ?? null, cwd: "/repo" }, + threadRef, + ); + return progress.label; + } + + return { + select(threadRef: ScopedThreadRef | null) { + act(() => { + root.render( + + + , + ); + }); + }, + get text() { + return container.textContent; + }, + [Symbol.dispose]() { + act(() => root.unmount()); + vi.unstubAllGlobals(); + }, + }; +} + +describe("showGitActionResult", () => { + it("buzzes once per reported result with the matching feedback type", () => { + showGitActionResult({ threadRef: owner, type: "success", title: "Pushed" }); + showGitActionResult({ + threadRef: owner, + type: "error", + title: "Git action failed", + description: "rejected", + }); + dismissGitActionResult(owner); + + expect(mocks.notificationAsync.mock.calls).toEqual([["success"], ["error"]]); + }); +}); + +describe("thread Git result banners", () => { + it.each([ + { name: "another thread", resultOwner: owner, viewer: otherThread }, + { + name: "the same thread ID in another environment", + resultOwner: owner, + viewer: { ...owner, environmentId: EnvironmentId.make("second") }, + }, + { + name: "a thread whose IDs join to the same string", + resultOwner: { environmentId: EnvironmentId.make("env"), threadId: ThreadId.make("a:b") }, + viewer: { environmentId: EnvironmentId.make("env:a"), threadId: ThreadId.make("b") }, + }, + { name: "no selected thread", resultOwner: owner, viewer: null }, + ])("hides a thread's result from $name", ({ resultOwner, viewer }) => { + try { + showGitActionResult({ threadRef: resultOwner, type: "success", title: "Pulled" }); + using banner = mountGitBanner(); + banner.select(resultOwner); + expect(banner.text).toBe("Pulled"); + banner.select(viewer); + expect(banner.text).toBe(""); + } finally { + dismissGitActionResult(resultOwner); + } + }); + + it("keeps each thread's result when another thread reports or dismisses", () => { + try { + using banner = mountGitBanner(); + showGitActionResult({ threadRef: otherThread, type: "error", title: "Rejected" }); + banner.select(otherThread); + act(() => showGitActionResult({ threadRef: owner, type: "success", title: "Pulled" })); + expect(banner.text).toBe("Rejected"); + act(() => dismissGitActionResult(otherThread)); + expect(banner.text).toBe(""); + banner.select(owner); + expect(banner.text).toBe("Pulled"); + } finally { + dismissGitActionResult(owner); + dismissGitActionResult(otherThread); + } + }); +}); diff --git a/apps/mobile/src/state/use-vcs-action-state.ts b/apps/mobile/src/state/use-vcs-action-state.ts index 04838ad200219..d09094df84da7 100644 --- a/apps/mobile/src/state/use-vcs-action-state.ts +++ b/apps/mobile/src/state/use-vcs-action-state.ts @@ -43,43 +43,51 @@ export interface GitActionResultNotification { const RESULT_DISMISS_MS = 5_000; -const gitActionResultAtom = Atom.make(null).pipe( +interface PendingGitActionResult { + readonly notification: GitActionResultNotification; + readonly timer: ReturnType; +} + +const gitActionResultsAtom = Atom.make>(new Map()).pipe( Atom.keepAlive, - Atom.withLabel("mobile:git-action-result"), + Atom.withLabel("mobile:git-action-results"), ); -let dismissTimer: ReturnType | null = null; -function broadcast(result: GitActionResultNotification | null): void { - appAtomRegistry.set(gitActionResultAtom, result); +function gitActionResultKey({ environmentId, threadId }: ScopedThreadRef): string { + return JSON.stringify([environmentId, threadId]); } -export function showGitActionResult(result: GitActionResultNotification): void { +export function showGitActionResult({ + threadRef, + ...notification +}: GitActionResultNotification & { readonly threadRef: ScopedThreadRef }): void { // Best effort: devices without a haptics engine reject. Haptics.notificationAsync( - result.type === "success" + notification.type === "success" ? Haptics.NotificationFeedbackType.Success : Haptics.NotificationFeedbackType.Error, ).catch(() => undefined); - if (dismissTimer) clearTimeout(dismissTimer); - broadcast(result); - dismissTimer = setTimeout(() => { - dismissTimer = null; - broadcast(null); - }, RESULT_DISMISS_MS); -} - -export function dismissGitActionResult(): void { - if (dismissTimer) clearTimeout(dismissTimer); - dismissTimer = null; - broadcast(null); + const key = gitActionResultKey(threadRef); + const results = new Map(appAtomRegistry.get(gitActionResultsAtom)); + const previous = results.get(key); + if (previous !== undefined) clearTimeout(previous.timer); + results.set(key, { + notification, + timer: setTimeout(() => dismissGitActionResult(threadRef), RESULT_DISMISS_MS), + }); + appAtomRegistry.set(gitActionResultsAtom, results); } -function useGitActionResultNotification(): { - readonly result: GitActionResultNotification | null; - readonly dismiss: () => void; -} { - const result = useAtomValue(gitActionResultAtom); - return { result, dismiss: dismissGitActionResult }; +export function dismissGitActionResult(threadRef: ScopedThreadRef | null): void { + if (threadRef === null) return; + const key = gitActionResultKey(threadRef); + const results = appAtomRegistry.get(gitActionResultsAtom); + const entry = results.get(key); + if (entry === undefined) return; + clearTimeout(entry.timer); + const next = new Map(results); + next.delete(key); + appAtomRegistry.set(gitActionResultsAtom, next); } export type GitActionProgressPhase = "idle" | "running" | "success" | "error"; @@ -110,7 +118,7 @@ function formatElapsedSeconds( return resolve(msg("Running for {elapsed}s", { elapsed: String(elapsed) })); } -/** Progress in the thread's own folder, or in the repository the thread last acted on. */ +/** Checkout progress and the selected thread's own Git result. */ export function useGitActionProgress( target: VcsActionTarget, threadRef: ScopedThreadRef | null, @@ -129,7 +137,10 @@ export function useGitActionProgress( cwd: repositoryCwd, }); const actionState = repositoryState.isRunning ? repositoryState : threadFolderState; - const { result } = useGitActionResultNotification(); + const resultKey = threadRef === null ? null : gitActionResultKey(threadRef); + const result = useAtomValue(gitActionResultsAtom, (results) => + resultKey === null ? undefined : results.get(resultKey)?.notification, + ); const resolve = useMessages(); // Only a running action shows elapsed time, so only it subscribes to the second tick. diff --git a/apps/mobile/vite.config.ts b/apps/mobile/vite.config.ts index 054f219bfa171..ee001a3a5e3d4 100644 --- a/apps/mobile/vite.config.ts +++ b/apps/mobile/vite.config.ts @@ -47,6 +47,7 @@ const reactTests = [ "src/native/useRetryingImageSource.test.tsx", "src/state/queries.debounce.test.tsx", "src/state/use-selected-thread-git-state.test.tsx", + "src/state/use-vcs-action-state.test.tsx", "src/features/terminal/useTerminalExitNavigation.test.tsx", "src/features/threads/use-thread-list-now.test.tsx", "src/features/threads/use-composer-command-menu.select.test.tsx", From 000ba180beef5c9491970b66c2d640032658696e Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:00:16 +0100 Subject: [PATCH 195/324] fix(web): keep the conversation when a pairing tab closes (#41025) Co-authored-by: Julius Marminge --- apps/web/src/state/linkedThreadView.ts | 16 +- ...-thread-stays-closed-during-pairing.e2e.ts | 139 ++++++++++++++++++ 2 files changed, 152 insertions(+), 3 deletions(-) create mode 100644 scripts/scenarios/closed-linked-thread-stays-closed-during-pairing.e2e.ts diff --git a/apps/web/src/state/linkedThreadView.ts b/apps/web/src/state/linkedThreadView.ts index adeb858c23cab..6f3ec45889a1f 100644 --- a/apps/web/src/state/linkedThreadView.ts +++ b/apps/web/src/state/linkedThreadView.ts @@ -11,7 +11,7 @@ import { useNavigate, useRouter } from "@tanstack/react-router"; import { AsyncResult, Atom } from "effect/reactivity"; import type { TurnItemSource } from "../components/chat/timelineRowContext"; -import { useRightPanelStore } from "../rightPanelStore"; +import { selectThreadRightPanelState, useRightPanelStore } from "../rightPanelStore"; import { connectPairing, reachesEnvironment } from "../connection/onboarding"; import { openLinkedThreadRead } from "../lib/sideChatPane"; import type { LinkedThreadSurface } from "../linkedThreadSurface"; @@ -203,8 +203,17 @@ export function useConnectLinkedEnvironment( const connect = async () => { setState({ phase: "connecting" }); const startedOn = router.state.location.href; + let tabClosed = false; + // A tab can close and reopen with the same ID while pairing is in flight. + const stopWatchingTab = + panelRef === null + ? undefined + : useRightPanelStore.subscribe((state) => { + const { surfaces } = selectThreadRightPanelState(state.byThreadKey, panelRef); + if (!surfaces.some((tab) => tab.id === surface.id)) tabClosed = true; + }); // Pairing takes a moment; a user who has gone elsewhere since is not moved again. - const stayed = () => router.state.location.href === startedOn; + const stayed = () => !tabClosed && router.state.location.href === startedOn; const outcome = await connectLinkedEnvironment({ label: surface.label, requestPairing: async () => { @@ -228,13 +237,14 @@ export function useConnectLinkedEnvironment( }); return result._tag === "Success"; }, - }); + }).finally(stopWatchingTab); if (outcome.type === "unreachable") { setState({ phase: "unreachable", label: outcome.label }); return outcome; } if (outcome.type === "connected") { setState({ phase: "idle" }); + if (tabClosed) return outcome; // The thread opens where every thread on a connected environment does, so its tab is done. if (panelRef !== null) useRightPanelStore.getState().closeSurface(panelRef, surface.id); if (!stayed()) return outcome; diff --git a/scripts/scenarios/closed-linked-thread-stays-closed-during-pairing.e2e.ts b/scripts/scenarios/closed-linked-thread-stays-closed-during-pairing.e2e.ts new file mode 100644 index 0000000000000..dbd90361cfe45 --- /dev/null +++ b/scripts/scenarios/closed-linked-thread-stays-closed-during-pairing.e2e.ts @@ -0,0 +1,139 @@ +/// +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { T3_HOME } from "../e2e.config.ts"; +import { SECOND_HOME, startSecondServer } from "./second-server.ts"; +import { environmentId, makeState, rpcClient, runPromise, test, WEB } from "./t3.ts"; + +const decodeCredential = Schema.decodeUnknownSync(Schema.Struct({ credential: Schema.String })); + +test( + "A closed linked-thread tab does not take over the conversation when pairing finishes", + WEB, + async ({ t3, app, browser, screen }) => { + const project = await t3.project("primary"); + const parent = await t3.thread({ + project, + title: "Current work", + messages: ["Keep this conversation open"], + }); + const origin = app.baseUrl ?? ""; + const server = startSecondServer(origin); + try { + const { host } = await server.ready; + const second = makeState(SECOND_HOME); + const issued = await runPromise(second.cli(["auth", "session", "issue", "--token-only"])); + // @effect-diagnostics-next-line globalFetch:off -- Seeds the real peer link from the scenario's Node fixture. + const pairing = await fetch(`${host}/api/auth/pairing-token`, { + method: "POST", + headers: { + authorization: `Bearer ${issued.stdout.trim()}`, + "content-type": "application/json", + }, + body: JSON.stringify({ purpose: "peer-link", access: "full-access" }), + }); + if (!pairing.ok) throw new Error(`Could not mint a peer-link code: ${pairing.status}`); + const { credential } = decodeCredential(await pairing.json()); + await runPromise( + Effect.gen(function* () { + const primary = yield* rpcClient(T3_HOME, origin); + const remote = yield* rpcClient(SECOND_HOME, host); + for (const client of [primary, remote]) { + yield* client["server.updateSettings"]({ patch: { linkedEnvironmentsEnabled: true } }); + } + yield* primary["peerLinks.link"]({ + url: host, + pairingCode: credential, + access: "full-access", + }); + }).pipe(Effect.scoped), + ); + + const linkedProject = await second.state.project("linked"); + const linkedTitle = "Remote design notes"; + const linkedPrompt = "Read the remote design notes"; + const remoteThread = await second.state.thread({ + project: linkedProject, + title: linkedTitle, + messages: [linkedPrompt], + }); + const via = await runPromise(environmentId(origin)); + const linked = await runPromise(environmentId(host)); + await browser.setViewport({ width: 1440, height: 900 }); + + // Restore the same saved tab that opening the delegated thread in the panel would leave. + await browser.addInitScript( + ({ via, linked, parentId, childId, title }) => { + if (location.pathname !== `/${via}/${parentId}`) return; + const id = `linked-thread:${encodeURIComponent(via)}:${encodeURIComponent(linked)}:${encodeURIComponent(childId)}`; + localStorage.setItem( + "t3code:right-panel-state:v2", + JSON.stringify({ + version: 16, + state: { + byThreadKey: { + [`${via}:${parentId}`]: { + isOpen: true, + activeSurfaceId: id, + surfaces: [ + { + kind: "linked-thread", + id, + viaEnvironmentId: via, + environmentId: linked, + threadId: childId, + label: "Scenario", + title, + }, + ], + }, + }, + threadPanelVisibilityByThreadKey: {}, + }, + }), + ); + }, + { + via, + linked, + parentId: parent.threadId, + childId: remoteThread.threadId, + title: linkedTitle, + }, + ); + + const tokenUrl = `${host}/oauth/token`; + const requested = Promise.withResolvers(); + const release = Promise.withResolvers(); + await browser.route(tokenUrl, async (route) => { + if (route.request.method !== "POST") return route.fallback(); + requested.resolve(); + await release.promise; + await route.continue(); + }); + try { + await t3.open(parent); + await screen.getByText(linkedPrompt, { exact: true }).waitFor(); + const originalUrl = await browser.url(); + await screen.getByRole("button", "Connect to interact", { exact: true }).tap(); + await requested.promise; + await screen.getByRole("button", `Close ${linkedTitle}`, { exact: true }).tap(); + + release.resolve(); + await screen + .getByText("This device is paired with it and can use its threads.", { exact: true }) + .waitFor(); + + await app.screenshot("after-pairing-finishes"); + await expect(browser).toHaveURL(originalUrl); + } finally { + release.resolve(); + await browser.unroute(tokenUrl); + } + } finally { + await server.stop(); + } + }, +); From 5bd0616f0524d312e0ee4471ca96f11bbdcb261c Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:02:35 +0100 Subject: [PATCH 196/324] fix: restart linked thread reads when trying again (#41020) Co-authored-by: Julius Marminge --- apps/web/src/state/linkedThreadView.ts | 19 ++-- .../src/state/peerLinks.test.ts | 31 +++++- .../client-runtime/src/state/peerLinks.ts | 17 +-- .../linked-thread-retry-reads-again.e2e.ts | 105 ++++++++++++++++++ 4 files changed, 153 insertions(+), 19 deletions(-) create mode 100644 scripts/scenarios/linked-thread-retry-reads-again.e2e.ts diff --git a/apps/web/src/state/linkedThreadView.ts b/apps/web/src/state/linkedThreadView.ts index 6f3ec45889a1f..4194e07834811 100644 --- a/apps/web/src/state/linkedThreadView.ts +++ b/apps/web/src/state/linkedThreadView.ts @@ -107,14 +107,17 @@ const tabViewAtom = Atom.family((key: string) => { const view = peerLinkEnvironment.threadView( targetOf({ viaEnvironmentId, environmentId, threadId }), ); - return Atom.make((get) => { - const live = get(view); - const title = AsyncResult.getOrElse(live, () => null)?.thread.projection?.thread.title; - if (title && panelRef !== null) { - useRightPanelStore.getState().setLinkedThreadTitle(panelRef, surfaceId, title); - } - return live; - }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`linked-thread-tab-view:${key}`)); + return Atom.readable( + (get) => { + const live = get(view); + const title = AsyncResult.getOrElse(live, () => null)?.thread.projection?.thread.title; + if (title && panelRef !== null) { + useRightPanelStore.getState().setLinkedThreadTitle(panelRef, surfaceId, title); + } + return live; + }, + (refresh) => refresh(view), + ).pipe(Atom.setIdleTTL(0), Atom.withLabel(`linked-thread-tab-view:${key}`)); }); /** diff --git a/packages/client-runtime/src/state/peerLinks.test.ts b/packages/client-runtime/src/state/peerLinks.test.ts index 75430e340fbff..dd39162df8a4c 100644 --- a/packages/client-runtime/src/state/peerLinks.test.ts +++ b/packages/client-runtime/src/state/peerLinks.test.ts @@ -1,5 +1,6 @@ import { EnvironmentId, + PeerLinkThreadReadError, WS_METHODS, type OrchestrationV2ThreadHistoryPage, type OrchestrationV2ThreadStreamItem, @@ -15,6 +16,7 @@ import * as Queue from "effect/Queue"; import * as Stream from "effect/Stream"; import * as SubscriptionRef from "effect/SubscriptionRef"; import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; +import { TestClock } from "effect/testing"; import { EnvironmentRegistry } from "../connection/registry.ts"; import { EnvironmentSupervisor } from "../connection/supervisor.ts"; @@ -25,7 +27,7 @@ import { createPeerLinkEnvironmentAtoms, linkThroughRoutes } from "./peerLinks.t // regression: #40544 earlier messages vanished when a linked thread's view opened again it.effect( - "keeps loaded messages when a linked thread's view opens again on the same snapshot", + "keeps loaded messages when a linked thread retries and reopens on the same snapshot", () => Effect.gen(function* () { const recent = v2MessageRow("Recent message", 2); @@ -38,7 +40,7 @@ it.effect( hasMoreHistory: true, }); const subscriptions = yield* Queue.unbounded<{ - items: Queue.Queue; + items: Queue.Queue; stopped: Deferred.Deferred; }>(); const requested: string[] = []; @@ -46,7 +48,10 @@ it.effect( [WS_METHODS.peerLinksSubscribeThread]: () => Stream.unwrap( Effect.gen(function* () { - const items = yield* Queue.unbounded(); + const items = yield* Queue.unbounded< + OrchestrationV2ThreadStreamItem, + PeerLinkThreadReadError + >(); const stopped = yield* Deferred.make(); yield* Effect.addFinalizer(() => Deferred.succeed(stopped, undefined)); yield* Queue.offer(subscriptions, { items, stopped }); @@ -102,8 +107,26 @@ it.effect( older.sourceItemId, recent.sourceItemId, ]); + const unreachable = new PeerLinkThreadReadError({ + reason: "unreachable", + label: "Linked", + message: "The linked machine is temporarily unreachable.", + }); + yield* Queue.fail(first.items, unreachable); + expect((yield* Queue.take(views)).error).toBe(unreachable); + + registry.refresh(links.threadView(target)); + yield* TestClock.adjust(0); + const retry = yield* Queue.poll(subscriptions); + if (Option.isNone(retry)) throw new Error("Refresh did not start a new linked thread read"); + yield* Queue.offer(retry.value.items, snapshot("before-recent")); + const recovered = yield* Queue.take(views).pipe( + Effect.repeat({ until: (view) => view.error === null }), + ); + expect(visibleMessages(recovered)).toEqual([older.sourceItemId, recent.sourceItemId]); + unmount(); - yield* Deferred.await(first.stopped); + yield* Deferred.await(retry.value.stopped); open(); const reopened = yield* Queue.take(subscriptions); diff --git a/packages/client-runtime/src/state/peerLinks.ts b/packages/client-runtime/src/state/peerLinks.ts index fd9d269bfd726..a7af1ac15b4c9 100644 --- a/packages/client-runtime/src/state/peerLinks.ts +++ b/packages/client-runtime/src/state/peerLinks.ts @@ -87,13 +87,16 @@ export function createPeerLinkEnvironmentAtoms( ), ) .pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-data:peer-links:thread-stream:${key}`)); - return Atom.make((get) => { - const live = get(stream); - if (AsyncResult.isSuccess(live)) { - get.set(kept, keepLinkedThreadView(get.once(kept), live.value)); - } - return live; - }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-data:peer-links:thread-view:${key}`)); + return Atom.readable( + (get) => { + const live = get(stream); + if (AsyncResult.isSuccess(live)) { + get.set(kept, keepLinkedThreadView(get.once(kept), live.value)); + } + return live; + }, + (refresh) => refresh(stream), + ).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-data:peer-links:thread-view:${key}`)); }); return { list, diff --git a/scripts/scenarios/linked-thread-retry-reads-again.e2e.ts b/scripts/scenarios/linked-thread-retry-reads-again.e2e.ts new file mode 100644 index 0000000000000..fd24c39b74dea --- /dev/null +++ b/scripts/scenarios/linked-thread-retry-reads-again.e2e.ts @@ -0,0 +1,105 @@ +/// +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { T3_HOME } from "../e2e.config.ts"; +import { SECOND_HOME, startSecondServer } from "./second-server.ts"; +import { environmentId, makeState, rpcClient, runPromise, test, WEB } from "./t3.ts"; + +const decodePairing = Schema.decodeEffect( + Schema.fromJsonString(Schema.Struct({ credential: Schema.String })), +); + +test( + "Try again immediately reads a linked thread once it is reachable", + WEB, + async ({ t3, app, browser, screen }) => { + await t3.project("primary"); + const origin = app.baseUrl ?? ""; + const server = startSecondServer(origin); + try { + const { host } = await server.ready; + await runPromise( + Effect.gen(function* () { + const primary = yield* rpcClient(T3_HOME, origin); + const remote = yield* rpcClient(SECOND_HOME, host); + for (const client of [primary, remote]) { + yield* client["server.updateSettings"]({ patch: { linkedEnvironmentsEnabled: true } }); + } + const pairing = yield* makeState(SECOND_HOME).cli([ + "auth", + "pairing", + "create", + "--json", + ]); + const { credential } = yield* decodePairing(pairing.stdout); + yield* primary["peerLinks.link"]({ + url: host, + pairingCode: credential, + access: "approval-required", + }); + }).pipe(Effect.scoped), + ); + + const remote = makeState(SECOND_HOME).state; + const project = await remote.project("linked"); + const prompt = "Read the linked design notes"; + const thread = await remote.thread({ project, title: "Design notes", messages: [prompt] }); + const via = await runPromise(environmentId(origin)); + const linked = await runPromise(environmentId(host)); + + // Drop only the first subscription, as if the linked machine were briefly unreachable. + // Every later request goes to the real server and reads the seeded thread. + await browser.addInitScript(() => { + let failed = false; + const send = WebSocket.prototype.send; + WebSocket.prototype.send = function (data) { + if (failed || typeof data !== "string") return send.call(this, data); + const parsed = JSON.parse(data); + const messages = Array.isArray(parsed) ? parsed : [parsed]; + const request = messages.find( + (message) => message?._tag === "Request" && message.tag === "peerLinks.subscribeThread", + ); + if (!request) return send.call(this, data); + failed = true; + const others = messages.filter((message) => message !== request); + if (others.length > 0) send.call(this, JSON.stringify(others)); + // @effect-diagnostics-next-line globalTimers:off - This callback is injected into the browser. + setTimeout(() => { + this.dispatchEvent( + new MessageEvent("message", { + data: JSON.stringify({ + _tag: "Exit", + requestId: request.id, + exit: { + _tag: "Failure", + cause: [ + { + _tag: "Fail", + error: { + _tag: "PeerLinkThreadReadError", + reason: "unreachable", + label: "Scenario", + message: "The linked machine is temporarily unreachable.", + }, + }, + ], + }, + }), + }), + ); + }, 0); + }; + }); + + await t3.open(`/linked/${via}/${linked}/${thread.threadId}`); + await screen.getByRole("button", "Try again", { exact: true }).tap(); + await app.screenshot("after-trying-again"); + // The automatic retry waits 15 seconds. This checks the user's explicit retry. + await expect(screen.getByText(prompt, { exact: true })).toBeVisible({ timeout: 4_000 }); + } finally { + await server.stop(); + } + }, +); From 55880c41b401469225a63e8128f2119290a7ad32 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:02:47 +0100 Subject: [PATCH 197/324] fix(client-runtime): count ambiguous projects in chat file links (#40986) Co-authored-by: Julius Marminge --- .../src/features/threads/ThreadFeed.tsx | 17 +++++---- apps/web/src/components/ChatMarkdown.tsx | 15 ++++---- apps/web/src/workspaceBasenameLookup.test.ts | 15 ++++++++ .../src/workspaceBasenameLookup.ts | 16 ++++---- ...ation-skips-ambiguous-project-files.e2e.ts | 37 +++++++++++++++++++ ...roject-after-ambiguous-local-search.e2e.ts | 34 +++++++++++++++++ 6 files changed, 110 insertions(+), 24 deletions(-) create mode 100644 scripts/scenarios/citation-skips-ambiguous-project-files.e2e.ts create mode 100644 scripts/scenarios/citation-skips-other-project-after-ambiguous-local-search.e2e.ts diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index 1a6d668d9ce50..106e72c2e1203 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -3330,7 +3330,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { // A v1 link names no environment, so it falls back to this message's. return scopeThreadRef(props.environmentId, link.threadId); }; - // The file a chat link names: in this workspace, else in the one other project that has it. + // Prefer the thread workspace before looking across projects or in agent directories. const findFileLinkTarget = async ( linkPath: string, path: string, @@ -3348,6 +3348,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { return relativePath ?? path; } const workspaceRoot = props.workspaceRoot; + const basenameLookup = needsWorkspaceBasenameLookup(relativePath); const originalPath = resolveWorkspaceFilePath(workspaceRoot, relativePath); const queryOptions = { signal, reportFailure: false, reportDefect: false }; const searchRoot = (root: string) => @@ -3395,13 +3396,13 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { ? [project.workspaceRoot] : [], ); - match = - otherRoots.length === 0 - ? null - : pickProjectLinkMatch(relativePath, await Promise.all(otherRoots.map(searchRoot))); + if (otherRoots.length > 0) { + const projectSearches = await Promise.all(otherRoots.map(searchRoot)); + match = pickProjectLinkMatch(relativePath, [own, ...projectSearches]); + } } if (match === null && reply !== undefined && !signal.aborted) { - // No project has the file, so it opens where the agent last worked, as written. + // An unresolved project lookup falls back to the agent's working directories. const agentRoots = agentWorkingDirectories( appAtomRegistry.get( environmentThreadDetails.quietThreadAtom( @@ -3420,7 +3421,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { (result) => result._tag === "Success" && result.value?.kind === "file", ); const literal = agentPaths[index]; - if (literal !== undefined || !needsWorkspaceBasenameLookup(relativePath)) { + if (literal !== undefined || !basenameLookup) { return literal ?? relativePath; } return ( @@ -3431,7 +3432,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { const metadata = await metadataOf(originalPath); // Another project's file never replaces a thread-local file the search missed. return metadata._tag === "Success" && - (needsWorkspaceBasenameLookup(relativePath) && !otherProject + (basenameLookup && !otherProject ? metadata.value?.kind !== "directory" : metadata.value === null) ? match diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index 979d1858cafc1..2edc4be1febcd 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -880,9 +880,10 @@ function useChatMarkdownState( } const query = workspaceLinkLookupQuery(workspaceRelativePath, cwd); if (query === null) return null; + const basenameLookup = needsWorkspaceBasenameLookup(workspaceRelativePath); // Search can be truncated or still scanning, so it cannot rule out the literal // path. A path with a folder opens as written whenever it exists. - if (!needsWorkspaceBasenameLookup(workspaceRelativePath)) { + if (!basenameLookup) { const metadata = await getFilesystemMetadata({ environmentId, input: { paths: [resolveWorkspaceFilePath(workspaceRelativePath, cwd)] }, @@ -917,26 +918,24 @@ function useChatMarkdownState( const agentRoots = (agentDirectories?.() ?? []).filter((root) => root !== cwd); if (otherRoots.length === 0 && agentRoots.length === 0) return null; // Another project's file never replaces a thread-local file the search missed. - if (needsWorkspaceBasenameLookup(workspaceRelativePath)) { + if (basenameLookup) { const metadata = await getFilesystemMetadata({ environmentId, input: { paths: [resolveWorkspaceFilePath(workspaceRelativePath, cwd)] }, }); if (metadata._tag !== "Success" || metadata.value.entries[0] !== null) return null; } - const projectMatch = pickProjectLinkMatch( - workspaceRelativePath, - await Promise.all(otherRoots.map(searchRoot)), - ); + const projectSearches = await Promise.all(otherRoots.map(searchRoot)); + const projectMatch = pickProjectLinkMatch(workspaceRelativePath, [own, ...projectSearches]); if (projectMatch !== null || agentRoots.length === 0) return projectMatch; - // No project has the file, so it opens where the agent last worked, as written. + // An unresolved project lookup falls back to the agent's working directories. const agentPaths = agentRoots.map((root) => resolveWorkspaceFilePath(workspaceRelativePath, root), ); const metadata = await getFilesystemMetadata({ environmentId, input: { paths: agentPaths } }); if (metadata._tag !== "Success") return null; const literal = agentPaths.find((_, index) => metadata.value.entries[index]?.kind === "file"); - if (literal !== undefined || !needsWorkspaceBasenameLookup(workspaceRelativePath)) { + if (literal !== undefined || !basenameLookup) { return literal ?? null; } return findAgentDirectoryMatch(workspaceRelativePath, agentRoots, searchRoot); diff --git a/apps/web/src/workspaceBasenameLookup.test.ts b/apps/web/src/workspaceBasenameLookup.test.ts index 4e11917a0aeff..7c1d17587813e 100644 --- a/apps/web/src/workspaceBasenameLookup.test.ts +++ b/apps/web/src/workspaceBasenameLookup.test.ts @@ -129,6 +129,21 @@ describe("chat file links into another project", () => { ).toBeNull(); }); + it("opens nothing when a project left ambiguous by case also has the name", () => { + expect( + pickProjectLinkMatch("handoff.txt", [ + { root: "/reports", entries: [{ path: "notes/HANDOFF.txt", kind: "file" }] }, + { + root: "/support", + entries: [ + { path: "current/Handoff.txt", kind: "file" }, + { path: "archive/HANDOFF.txt", kind: "file" }, + ], + }, + ]), + ).toBeNull(); + }); + it("opens nothing when overlapping projects also list a second suffix match", () => { expect( pickProjectLinkMatch("docs/handoff.txt", [ diff --git a/packages/client-runtime/src/workspaceBasenameLookup.ts b/packages/client-runtime/src/workspaceBasenameLookup.ts index 6698aed52fb38..ae55263fb2bd4 100644 --- a/packages/client-runtime/src/workspaceBasenameLookup.ts +++ b/packages/client-runtime/src/workspaceBasenameLookup.ts @@ -118,7 +118,7 @@ function pickStrippedWorkspaceMatch( } /** - * The absolute path of the one file a chat link names across other project roots, or null when + * The absolute path of the one file a chat link names across project roots, or null when * no root has it or roots name different files. Agents cite paths relative to their repo. * Nested project roots list the same file more than once, which still names one file. */ @@ -131,6 +131,9 @@ export function pickProjectLinkMatch( ): string | null { const target = relativePath.trim(); const isBasename = needsWorkspaceBasenameLookup(target); + const folded = target.toLowerCase(); + const isFoldedMatch = (entry: WorkspaceEntryCandidate) => + entry.kind === "file" && basenameOfPath(entry.path).toLowerCase() === folded; const matches = new Map(); let rootHits = 0; const addMatch = (path: string) => { @@ -140,10 +143,10 @@ export function pickProjectLinkMatch( }; for (const { root, entries } of searches) { if (isBasename) { - const match = pickWorkspaceBasenameMatch(target, entries); - if (match === null) continue; + if (!entries.some(isFoldedMatch)) continue; rootHits += 1; - addMatch(resolveWorkspaceFilePath(match, root)); + const match = pickWorkspaceBasenameMatch(target, entries); + if (match !== null) addMatch(resolveWorkspaceFilePath(match, root)); } else { for (const match of workspaceQualifiedPathMatches(target, root, entries)) { addMatch(resolveWorkspaceFilePath(match, root)); @@ -152,12 +155,9 @@ export function pickProjectLinkMatch( } if (isBasename && rootHits > 1) { // A root's pick, or a root left ambiguous by case, can hide another file elsewhere. - const folded = target.toLowerCase(); for (const { root, entries } of searches) { for (const entry of entries) { - if (entry.kind === "file" && basenameOfPath(entry.path).toLowerCase() === folded) { - addMatch(resolveWorkspaceFilePath(entry.path, root)); - } + if (isFoldedMatch(entry)) addMatch(resolveWorkspaceFilePath(entry.path, root)); } } } diff --git a/scripts/scenarios/citation-skips-ambiguous-project-files.e2e.ts b/scripts/scenarios/citation-skips-ambiguous-project-files.e2e.ts new file mode 100644 index 0000000000000..6cfbafc6c49b2 --- /dev/null +++ b/scripts/scenarios/citation-skips-ambiguous-project-files.e2e.ts @@ -0,0 +1,37 @@ +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +const FILE = "handoff.txt"; + +test( + "A bare citation leaves the file unresolved when other projects contain several matches", + WEB, + async ({ t3, app, browser, screen }) => { + const project = await t3.project("planning"); + await t3.project("reports", { "notes/HANDOFF.txt": "Report handoff" }); + await t3.project("support", { + "current/Handoff.txt": "Current support handoff", + "archive/HANDOFF.txt": "Archived support handoff", + }); + const thread = await t3.thread({ + project, + title: "Find the handoff", + messages: [`See :codex-file-citation{path="${FILE}" line_range_start="1"}`], + }); + + await t3.open(thread); + await screen.getByRole("button", /^Agent See/).tap(); + await screen.getByRole("link", /^handoff\.txt/).tap(); + + try { + await expect( + browser + .locator("[data-right-panel-surface-content]") + .getByText("The file could not be accessed or read. It may be missing or inaccessible."), + ).toBeVisible(); + } finally { + await app.screenshot("ambiguous-handoff-citation"); + } + }, +); diff --git a/scripts/scenarios/citation-skips-other-project-after-ambiguous-local-search.e2e.ts b/scripts/scenarios/citation-skips-other-project-after-ambiguous-local-search.e2e.ts new file mode 100644 index 0000000000000..22458e6223fbb --- /dev/null +++ b/scripts/scenarios/citation-skips-other-project-after-ambiguous-local-search.e2e.ts @@ -0,0 +1,34 @@ +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +test( + "A bare citation leaves the file unresolved when the thread project has ambiguous matches", + WEB, + async ({ t3, app, browser, screen }) => { + const project = await t3.project("support", { + "current/Handoff.txt": "Current support handoff", + "archive/HANDOFF.txt": "Archived support handoff", + }); + await t3.project("reports", { "notes/HANDOFF.txt": "Report handoff" }); + const thread = await t3.thread({ + project, + title: "Find the handoff", + messages: ['See :codex-file-citation{path="handoff.txt" line_range_start="1"}'], + }); + + await t3.open(thread); + await screen.getByRole("button", /^Agent See/).tap(); + await screen.getByRole("link", /^handoff\.txt/).tap(); + + try { + await expect( + browser + .locator("[data-right-panel-surface-content]") + .getByText("The file could not be accessed or read. It may be missing or inaccessible."), + ).toBeVisible(); + } finally { + await app.screenshot("ambiguous-local-handoff-citation"); + } + }, +); From 2e62a7189366a3541329479c7b6b4d40cab2916a Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:03:48 +0100 Subject: [PATCH 198/324] fix(mobile): keep media actions on each sent image page (#41018) Co-authored-by: Julius Marminge --- .../src/features/threads/ThreadFeed.tsx | 37 +++-------- .../features/threads/messageImageGallery.ts | 13 +--- apps/mobile/src/lib/composerImageGallery.ts | 13 +--- apps/mobile/src/lib/contextImageGallery.ts | 15 +---- .../mobile/src/lib/filePreviewGallery.test.ts | 63 ++++++++++++++++++- apps/mobile/src/lib/filePreviewGallery.ts | 21 +++++++ 6 files changed, 97 insertions(+), 65 deletions(-) diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index 106e72c2e1203..4337d9619ae2f 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -159,7 +159,10 @@ import { useResolveClassNames } from "uniwind"; import { useReduceMotionEnabled } from "../../lib/appState"; import { useFilePreviewGallery, FilePreviewGallery } from "../../components/ui/FilePreviewGallery"; import { assetImageSource } from "../../lib/assetImageSource"; -import { filePreviewSourceIdentifier } from "../../lib/filePreviewGallery"; +import { + filePreviewSourceIdentifier, + remoteAttachmentImageSource, +} from "../../lib/filePreviewGallery"; import { composerImageGallery } from "../../lib/composerImageGallery"; import { isFileBackedComposerAttachment, @@ -617,17 +620,9 @@ function MessageAttachmentImage(props: { }) { const gt = useGT(); const withGallery = useFilePreviewGallery(); - const resource = { - _tag: "attachment" as const, - attachmentId: props.attachmentId, - fileName: props.name, - mimeType: props.mimeType, - }; - const sourceIdentifier = filePreviewSourceIdentifier({ - kind: "image", - environmentId: props.environmentId, - resource, - }); + const previewSource = remoteAttachmentImageSource(props.environmentId, props.attachmentId, props); + const { resource } = previewSource; + const sourceIdentifier = filePreviewSourceIdentifier(previewSource); const uri = useAssetUrl(props.environmentId, resource); const refreshAssetUrl = useRefreshAssetUrl(props.environmentId, resource); const retriedImage = useRef(false); @@ -666,23 +661,7 @@ function MessageAttachmentImage(props: { height={props.height} accessibilityLabel={gt("Open {name}", { name: props.name })} {...handoffProps(handoff)} - onPress={() => - props.onPressPreview( - withGallery({ - kind: "image", - environmentId: props.environmentId, - resource, - name: props.name, - sourceIdentifier, - actionsSource: { - name: props.name, - mimeType: props.mimeType, - environmentId: props.environmentId, - resource, - }, - }), - ) - } + onPress={() => props.onPressPreview(withGallery({ ...previewSource, sourceIdentifier }))} onLoad={(size) => { retriedImage.current = false; if (handoff) diff --git a/apps/mobile/src/features/threads/messageImageGallery.ts b/apps/mobile/src/features/threads/messageImageGallery.ts index fb8fc3de67b78..c18592c67f43a 100644 --- a/apps/mobile/src/features/threads/messageImageGallery.ts +++ b/apps/mobile/src/features/threads/messageImageGallery.ts @@ -1,6 +1,7 @@ import type { ChatAttachment, EnvironmentId, ThreadId } from "@t3tools/contracts"; import { imageMimeType } from "@t3tools/shared/image"; import type { FilePreviewItem } from "../../components/ui/FilePreviewModal.types"; +import { remoteAttachmentImageSource } from "../../lib/filePreviewGallery"; import { markdownImageSources } from "../../lib/markdownImageSources"; import { resolveMarkdownMediaPreview } from "../../lib/markdownMedia"; @@ -15,17 +16,7 @@ export function messageImageGallery( const images: FilePreviewItem[] = []; for (const attachment of message.attachments ?? []) { if (attachment.type !== "image" && imageMimeType(attachment) === null) continue; - images.push({ - kind: "image", - name: attachment.name, - environmentId: context.environmentId, - resource: { - _tag: "attachment", - attachmentId: attachment.id, - fileName: attachment.name, - mimeType: attachment.mimeType, - }, - }); + images.push(remoteAttachmentImageSource(context.environmentId, attachment.id, attachment)); } for (const href of markdownImageSources(message.text)) { const preview = resolveMarkdownMediaPreview(href, { ...context, imageEmbed: true }); diff --git a/apps/mobile/src/lib/composerImageGallery.ts b/apps/mobile/src/lib/composerImageGallery.ts index ffc6167e8b50d..080ef20f2866c 100644 --- a/apps/mobile/src/lib/composerImageGallery.ts +++ b/apps/mobile/src/lib/composerImageGallery.ts @@ -2,6 +2,7 @@ import { imageMimeType } from "@t3tools/shared/image"; import type { EnvironmentId } from "@t3tools/contracts"; import type { FilePreviewItem } from "../components/ui/FilePreviewModal.types"; import { isFileBackedComposerAttachment, type DraftComposerAttachment } from "./composerImages"; +import { remoteAttachmentImageSource } from "./filePreviewGallery"; export function composerImageGallery( attachments: readonly DraftComposerAttachment[], @@ -11,17 +12,7 @@ export function composerImageGallery( if (attachment.type !== "image" && imageMimeType(attachment) === null) return []; if (environmentId !== undefined && attachment.uploadedAttachmentId) { return [ - { - kind: "image", - name: attachment.name, - environmentId, - resource: { - _tag: "attachment", - attachmentId: attachment.uploadedAttachmentId, - fileName: attachment.name, - mimeType: attachment.mimeType, - }, - }, + remoteAttachmentImageSource(environmentId, attachment.uploadedAttachmentId, attachment), ]; } if (isFileBackedComposerAttachment(attachment)) { diff --git a/apps/mobile/src/lib/contextImageGallery.ts b/apps/mobile/src/lib/contextImageGallery.ts index 335554b0565c5..c119ad856fd91 100644 --- a/apps/mobile/src/lib/contextImageGallery.ts +++ b/apps/mobile/src/lib/contextImageGallery.ts @@ -3,6 +3,7 @@ import { imageMimeType } from "@t3tools/shared/image"; import type { FilePreviewItem } from "../components/ui/FilePreviewModal.types"; import { composerImageGallery } from "./composerImageGallery"; import type { DraftComposerAttachment } from "./composerImages"; +import { remoteAttachmentImageSource } from "./filePreviewGallery"; export function contextImageGallery( records: readonly ComposerContextRecord[], @@ -15,19 +16,7 @@ export function contextImageGallery( const local = attachments.find((item) => item.id === record.attachmentId); if (local) return composerImageGallery([local]); return environmentId - ? [ - { - kind: "image", - name: record.name, - environmentId, - resource: { - _tag: "attachment", - attachmentId: record.attachmentId, - fileName: record.name, - mimeType: record.mimeType, - }, - }, - ] + ? [remoteAttachmentImageSource(environmentId, record.attachmentId, record)] : []; }); } diff --git a/apps/mobile/src/lib/filePreviewGallery.test.ts b/apps/mobile/src/lib/filePreviewGallery.test.ts index f85e33c851f07..d8def9cc125d8 100644 --- a/apps/mobile/src/lib/filePreviewGallery.test.ts +++ b/apps/mobile/src/lib/filePreviewGallery.test.ts @@ -1,8 +1,9 @@ import { describe, expect, it, vi } from "vite-plus/test"; -import { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { ComposerContextId, EnvironmentId, ThreadId } from "@t3tools/contracts"; import type { FilePreviewItem } from "../components/ui/FilePreviewModal.types"; import type { DraftComposerAttachment } from "./composerImages"; import { composerImageGallery } from "./composerImageGallery"; +import { contextImageGallery } from "./contextImageGallery"; import { messageImageGallery } from "../features/threads/messageImageGallery"; import { filePreviewGallery, filePreviewKey } from "./filePreviewGallery"; @@ -67,6 +68,66 @@ describe("image preview groups", () => { }, ); + it("gives every remote image page its own media actions", () => { + const environmentId = EnvironmentId.make("test"); + const ids = ["a", "b"]; + const galleries = [ + messageImageGallery( + { + text: "", + attachments: ids.map((id) => ({ + type: "image" as const, + id: `uploaded-${id}`, + name: `${id}.png`, + mimeType: "image/png", + sizeBytes: 3, + })), + }, + { environmentId, threadId: ThreadId.make("thread"), workspaceRoot: null }, + ), + composerImageGallery( + ids.map((id) => ({ + id, + type: "image", + name: `${id}.png`, + mimeType: "image/png", + sizeBytes: 3, + previewUri: `data:image/png;base64,${id}`, + uploadedAttachmentId: `uploaded-${id}`, + })), + environmentId, + ), + contextImageGallery( + ids.map((id) => ({ + version: 1, + kind: "image", + contextId: ComposerContextId.make(`context-${id}`), + label: `Screenshot ${id}`, + attachmentId: `uploaded-${id}`, + name: `${id}.png`, + mimeType: "image/png", + sizeBytes: 3, + })), + [], + environmentId, + ), + ]; + + for (const gallery of galleries) { + expect(filePreviewGallery(gallery[0]!, gallery)[1]?.actionsSource).toEqual({ + name: "b.png", + mimeType: "image/png", + environmentId, + resource: { + _tag: "attachment", + attachmentId: "uploaded-b", + fileName: "b.png", + mimeType: "image/png", + }, + }); + } + }); + it("matches remote originals despite metadata and property order differences", () => { const environmentId = EnvironmentId.make("test"); const a: FilePreviewItem = { diff --git a/apps/mobile/src/lib/filePreviewGallery.ts b/apps/mobile/src/lib/filePreviewGallery.ts index e8b2f4e19f838..26f16ec03cdc0 100644 --- a/apps/mobile/src/lib/filePreviewGallery.ts +++ b/apps/mobile/src/lib/filePreviewGallery.ts @@ -1,5 +1,26 @@ +import type { EnvironmentId } from "@t3tools/contracts"; import type { FilePreviewItem, FilePreviewSource } from "../components/ui/FilePreviewModal.types"; +export function remoteAttachmentImageSource( + environmentId: EnvironmentId, + attachmentId: string, + { name, mimeType }: { readonly name: string; readonly mimeType: string }, +) { + const resource = { + _tag: "attachment" as const, + attachmentId, + fileName: name, + mimeType, + }; + return { + kind: "image", + name, + environmentId, + resource, + actionsSource: { name, mimeType, environmentId, resource }, + } satisfies FilePreviewItem; +} + export function filePreviewKey(source: FilePreviewItem): string { if ("resource" in source) return JSON.stringify([ From 024dba275d9e5ade1b29a0a240c5f8661cdbdb51 Mon Sep 17 00:00:00 2001 From: Navid Nadali Date: Sun, 22 Nov 2026 20:11:54 +0000 Subject: [PATCH 199/324] perf(server): a run's provider turn lookup is linear, not quadratic (#38791) Co-authored-by: Claude Opus 5.5 Co-authored-by: shivam <91240327+shivamhwp@users.noreply.github.com> --- .../Orchestrator.control-reads.test.ts | 100 ++++++++++++++++++ .../src/orchestration-v2/Orchestrator.ts | 20 ++-- 2 files changed, 111 insertions(+), 9 deletions(-) diff --git a/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts index 027c65011dc94..ac7cb9c714d88 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts @@ -7,6 +7,9 @@ import { EventId, NodeId, type OrchestrationV2DomainEvent, + type OrchestrationV2ProviderTurn, + type OrchestrationV2Run, + type OrchestrationV2RunAttempt, PlanId, ProjectId, ProviderDriverKind, @@ -3184,3 +3187,100 @@ it.effect( assert.equal(yield* captureReads, quietParent); }).pipe(Effect.provide(layerTest)), ); + +/** A copy of `value` whose `id` getter counts its reads. */ +const countingIdReads = ( + value: T, + reads: { count: number }, +): T => + Object.defineProperty({ ...value }, "id", { + enumerable: true, + get: () => { + reads.count += 1; + return value.id; + }, + }); + +// The owner's active attempt is the newest and no provider turn is tagged with it, so the lookup +// falls back to the turn the attempt names. The last two turns are untagged and share one id. +it.each([ + { ownerAttempt: "names no provider turn", providerTurnId: null, findsFirstLegacy: false }, + { + ownerAttempt: "names a provider turn listed twice", + providerTurnId: "legacy", + findsFirstLegacy: true, + }, + { ownerAttempt: "is missing", providerTurnId: null, findsFirstLegacy: false }, +] as const)( + "finds a run's provider turn in at most 2·(T + A) id reads when its attempt $ownerAttempt", + ({ ownerAttempt, providerTurnId, findsFirstLegacy }) => { + const size = 2_000; + const reads = { count: 0 }; + const providerThreadId = ProviderThreadId.make("provider-thread:lookup"); + const attempts = Array.from({ length: size }, (_, index) => + countingIdReads( + { + id: RunAttemptId.make(`attempt:lookup:${index}`), + runId: RunId.make(`run:lookup:${index}`), + attemptOrdinal: 1, + rootNodeId: NodeId.make(`node:lookup:${index}`), + providerInstanceId: instanceId, + providerThreadId, + providerTurnId: + index < size - 1 + ? ProviderTurnId.make(`provider-turn:lookup:${index}`) + : providerTurnId === null + ? null + : ProviderTurnId.make(`provider-turn:lookup:${providerTurnId}`), + reason: "initial", + status: index < size - 1 ? "completed" : "pending", + startedAt: null, + completedAt: null, + }, + reads, + ), + ); + const providerTurns = Array.from({ length: size }, (_, index) => { + const untagged = index >= size - 2; + return countingIdReads( + { + id: ProviderTurnId.make(`provider-turn:lookup:${untagged ? "legacy" : index}`), + providerThreadId, + nodeId: NodeId.make(`node:lookup:${index}`), + runAttemptId: untagged ? null : RunAttemptId.make(`attempt:lookup:${index}`), + nativeTurnRef: null, + ordinal: index + 1, + status: "completed", + startedAt: null, + completedAt: null, + }, + reads, + ); + }); + const owner: OrchestrationV2Run = { + id: RunId.make(`run:lookup:${size - 1}`), + threadId: ThreadId.make("thread:lookup"), + ordinal: size, + providerInstanceId: instanceId, + modelSelection, + providerThreadId, + userMessageId: MessageId.make("message:lookup"), + rootNodeId: NodeId.make(`node:lookup:${size - 1}`), + activeAttemptId: + ownerAttempt === "is missing" + ? RunAttemptId.make("attempt:lookup:missing") + : RunAttemptId.make(`attempt:lookup:${size - 1}`), + status: "starting", + requestedAt: DateTime.makeUnsafe(0), + startedAt: null, + completedAt: null, + checkpointId: null, + contextHandoffId: null, + }; + + const turn = Orchestrator.providerTurnForRun({ attempts, providerTurns }, owner); + + assert.strictEqual(turn, findsFirstLegacy ? providerTurns[size - 2] : undefined); + assert.isAtMost(reads.count, 2 * (size + size)); + }, +); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 5936f57ad5014..e8dfe6df4634d 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -1352,21 +1352,23 @@ function providerThreadForRun( : projection.providerThreads.find((candidate) => candidate.id === run.providerThreadId); } -function providerTurnForRun( +export function providerTurnForRun( projection: Pick, run: OrchestrationV2Run, ): OrchestrationV2ProviderTurn | undefined { if (run.activeAttemptId === null) { return undefined; } - - return ( - latestProviderTurnForAttempt(projection.providerTurns, run.activeAttemptId) ?? - projection.providerTurns.find((turn) => { - const attempt = projection.attempts.find((candidate) => candidate.id === run.activeAttemptId); - return attempt?.providerTurnId === turn.id; - }) - ); + const latest = latestProviderTurnForAttempt(projection.providerTurns, run.activeAttemptId); + if (latest !== undefined) { + return latest; + } + const namedTurnId = projection.attempts.find( + (candidate) => candidate.id === run.activeAttemptId, + )?.providerTurnId; + return namedTurnId === undefined || namedTurnId === null + ? undefined + : projection.providerTurns.find((turn) => turn.id === namedTurnId); } function contextSourcePointForRun( From c7df7004af5e5d086da00d556479efa0de4e8d2c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 12:15:28 -0800 Subject: [PATCH 200/324] fix(web): a photo picked on a phone attaches even when the composer collapses (#41021) --- .../src/components/ChatView.browser.test.tsx | 37 ++++++++ apps/web/src/components/chat/ChatComposer.tsx | 14 ++- .../chat/ComposerAttachmentStrip.tsx | 88 ++++++++++--------- apps/web/test/fakeEnvironment.ts | 7 +- 4 files changed, 100 insertions(+), 46 deletions(-) diff --git a/apps/web/src/components/ChatView.browser.test.tsx b/apps/web/src/components/ChatView.browser.test.tsx index 60c3c24ce5c2d..e721c46d48ec4 100644 --- a/apps/web/src/components/ChatView.browser.test.tsx +++ b/apps/web/src/components/ChatView.browser.test.tsx @@ -547,6 +547,43 @@ it.each(["new", "existing"] as const)( }, ); +it("a file picked after the phone composer collapses still attaches", async () => { + const thread = threadWithHistory("thread-40993", 1); + using _environment = installFakeEnvironment([thread]); + await page.viewport(390, 844); + __setClientSettingsForTests({ + ...DEFAULT_CLIENT_SETTINGS, + onboardingCompletedAt: "2026-01-01T00:00:00.000Z", + }); + const router = getRouter( + createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }), + ); + await router.load(); + await using _app = await render(, { + // AppRoot brings its own router. + router: false, + }); + using _uploads = acceptAttachmentUploads(); + const editor = page.getByTestId("composer-editor"); + await expect.element(page.getByText(`Answer 0 for ${thread.id}.`)).toBeVisible(); + await userEvent.click(editor); + await expect.element(page.getByRole("button", { name: "Attach files" })).toBeVisible(); + const input = document.querySelector( + 'form[data-chat-composer-form] input[type="file"]', + ); + expect(input).not.toBeNull(); + + // Opening the native picker blurs the editor, which collapses the phone composer. + (editor.element() as HTMLElement).blur(); + await expect.element(page.getByRole("button", { name: "Attach files" })).not.toBeInTheDocument(); + const files = new DataTransfer(); + files.items.add(new File([PNG], "picked.png", { type: "image/png" })); + input!.files = files.files; + input!.dispatchEvent(new Event("change", { bubbles: true })); + + await expect.element(page.getByRole("img", { name: "picked.png" })).toBeVisible(); +}); + it("opens the thread actions menu for an older settled thread the shell leaves out", async () => { const thread = { ...threadWithHistory("older-settled", 1), olderSettled: true as const }; using _environment = installFakeEnvironment([thread]); diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 85a7f6173bf96..5b540f48c483e 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -216,6 +216,7 @@ import { } from "./ComposerCommandMenu"; import { ComposerAttachButton, + ComposerAttachInput, ComposerAttachmentFileList, ComposerAttachmentMediaRow, ComposerFilePreviewDialog, @@ -1119,6 +1120,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const composerEditorRef = useRef(null); const pasteAsTextShortcutUntilRef = useRef(0); const composerFormRef = useRef(null); + const composerAttachInputRef = useRef(null); const composerSurfaceRef = useRef(null); const providerInputRejectedRef = useRef(false); const composerSelectLockRef = useRef(false); @@ -3614,10 +3616,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) /> ) : null; const composerAttachButton = showComposerAttachAction ? ( - + composerAttachInputRef.current?.click()} /> ) : null; return ( + {showComposerAttachAction ? ( + + ) : null}
    ; readonly addComposerAttachments: (files: File[]) => Promise; readonly focusComposer: () => void; }) { + return ( + { + const files = Array.from(event.currentTarget.files ?? []); + event.currentTarget.value = ""; + // Inserting a chip refocuses the editor after the draft renders; + // focusing synchronously here would report the editor's stale text + // over the prompt that was just written. + void addComposerAttachments(files).then((inserted) => { + if (!inserted) focusComposer(); + }); + }} + /> + ); +} + +export function ComposerAttachButton({ onOpenPicker }: { readonly onOpenPicker: () => void }) { const gt = useGT(); - const inputRef = useRef(null); return ( - <> - { - const files = Array.from(event.currentTarget.files ?? []); - event.currentTarget.value = ""; - // Inserting a chip refocuses the editor after the draft renders; - // focusing synchronously here would report the editor's stale text - // over the prompt that was just written. - void addComposerAttachments(files).then((inserted) => { - if (!inserted) focusComposer(); - }); - }} - /> - - event.preventDefault()} - onClick={() => inputRef.current?.click()} - aria-label={gt("Attach files")} - /> - } - > - {/* The clip's weight sits in its upper loop; 1px down reads as centered on the row. */} - - - - Attach files - - - + + event.preventDefault()} + onClick={onOpenPicker} + aria-label={gt("Attach files")} + /> + } + > + {/* The clip's weight sits in its upper loop; 1px down reads as centered on the row. */} + + + + Attach files + + ); } diff --git a/apps/web/test/fakeEnvironment.ts b/apps/web/test/fakeEnvironment.ts index 71e8875bb56db..734fe38dad33b 100644 --- a/apps/web/test/fakeEnvironment.ts +++ b/apps/web/test/fakeEnvironment.ts @@ -67,7 +67,12 @@ const descriptor = { // A matching version, since a mismatch adds an update banner a typical user never sees. serverVersion: APP_VERSION, orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION, - capabilities: { repositoryIdentity: true, sideChats: true, freshContext: true }, + capabilities: { + repositoryIdentity: true, + sideChats: true, + freshContext: true, + fileAttachments: { maxUploadBytes: 10_000_000 }, + }, }; const auth = { policy: "loopback-browser", From 02a4c18d644e1b4af2dfa558c95e68e827042215 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:20:42 +0100 Subject: [PATCH 201/324] fix(mobile): cancel pending media actions when swiping gallery pages (#41027) Co-authored-by: Julius Marminge --- .../ui/FilePreviewModal.android.tsx | 32 +++- .../components/ui/FilePreviewSession.test.tsx | 169 +++++++++++++++++- apps/mobile/src/state/mediaActions.ts | 13 +- 3 files changed, 197 insertions(+), 17 deletions(-) diff --git a/apps/mobile/src/components/ui/FilePreviewModal.android.tsx b/apps/mobile/src/components/ui/FilePreviewModal.android.tsx index 017dbdb1456fb..d9f732853dddd 100644 --- a/apps/mobile/src/components/ui/FilePreviewModal.android.tsx +++ b/apps/mobile/src/components/ui/FilePreviewModal.android.tsx @@ -2,7 +2,7 @@ import { T, useGT } from "gt-react-native"; import { Button } from "./Button"; import * as Dialog from "./Dialog"; -import { createContext, useContext, useEffect, useEffectEvent } from "react"; +import { createContext, useContext, useEffect, useEffectEvent, useRef } from "react"; import { Modal, View } from "react-native"; import ImageViewing from "react-native-image-viewing"; import { useSafeAreaInsets } from "react-native-safe-area-context"; @@ -133,14 +133,23 @@ type ImagePreviewProps = { readonly onRequestClose: () => void; }; -const ImagePreviewContext = createContext(null); +const ImagePreviewContext = createContext< + (ImagePreviewProps & { readonly getSaveImageSignal: () => AbortSignal }) | null +>(null); +// Keyed by page so swiping away clears the busy state and aborts pending share preparation. function ImagePreviewHeader(header: { readonly imageIndex: number }) { + return ; +} + +function ImagePreviewPageHeader(header: { readonly imageIndex: number }) { const props = useContext(ImagePreviewContext)!; const source = props.source.images[header.imageIndex]; const gt = useGT(); const insets = useSafeAreaInsets(); - const mediaActions = useMediaActions(source?.actionsSource, props.onRequestClose); + const mediaActions = useMediaActions(source?.actionsSource, props.onRequestClose, { + getSaveImageSignal: props.getSaveImageSignal, + }); return ( (null); + const getSaveImageSignal = () => { + if (saveController.current === null) { + saveController.current = new AbortController(); + } + return saveController.current.signal; + }; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- saves survive a page change but stop when the gallery unmounts + useEffect( + () => () => { + saveController.current?.abort(); + saveController.current = null; + }, + [], + ); return ( - + ({ refreshAssetUrl: vi.fn<(environmentId: string, resource: { url: string }) => Promise>(), alert: vi.fn(), + share: vi.fn(), + download: vi.fn(), previews: [] as unknown[], mounts: 0, presentationFinished: false, })); -vi.mock("../../state/assets", () => ({ refreshAssetUrl: harness.refreshAssetUrl })); +vi.mock("../../state/assets", () => ({ + refreshAssetUrl: harness.refreshAssetUrl, + useRefreshAssetUrl: (environmentId: string, resource: { url: string }) => () => + harness.refreshAssetUrl(environmentId, resource), +})); vi.mock("../../lib/localAttachmentPreview", () => ({ loadLocalAttachmentPreview: vi.fn() })); vi.mock("../../lib/attachmentDownload", () => ({ - downloadAndShareAttachment: vi.fn(), + downloadAndShareAttachment: harness.share, + downloadAttachmentForPreview: harness.download, nativeViewerErrorMessage: () => "", shareLocalAttachment: vi.fn(), })); @@ -30,14 +46,46 @@ vi.mock("./Button", () => ({ Button: () => null })); vi.mock("./SheetHeader", () => ({ SheetHeader: () => null })); vi.mock("./AppText", () => ({ AppText: () => null })); vi.mock("../PdfPreview", () => ({ PdfPreview: () => null })); -vi.mock("../MediaPreviewHeader", () => ({ MediaPreviewHeader: () => null })); -vi.mock("../../state/mediaActions", () => ({ useMediaActions: () => ({ actions: [] }) })); -vi.mock("react-native", () => ({ Modal: () => null, View: () => null })); +vi.mock("../MediaPreviewHeader", () => ({ + MediaPreviewHeader: ({ media }: { media: ReturnType }) => + media.actions + .filter(({ id }) => id === "save" || id === "save-image") + .map(({ id, disabled, run, title }) => ( + + )), +})); +vi.mock("@react-navigation/native", () => ({ useNavigation: () => ({ navigate: vi.fn() }) })); +vi.mock("../../state/session", () => ({ + environmentSession: { sessionStateAtom: (environmentId: string) => environmentId }, +})); +const grant = { authenticated: true, scopes: [AuthFilesystemReadScope] }; +vi.mock("../../state/query", () => ({ + useEnvironmentQuery: () => ({ data: grant, error: null }), +})); +vi.mock("../../state/atom-registry", () => ({ + appAtomRegistry: { get: () => AsyncResult.success(grant) }, +})); +vi.mock("expo", () => ({ requireNativeModule: vi.fn() })); +vi.mock("expo-clipboard", () => ({ setStringAsync: vi.fn() })); +vi.mock("expo-haptics", () => ({ notificationAsync: vi.fn() })); +vi.mock("react-native", () => ({ + Modal: () => null, + Platform: { OS: "android", Version: 35 }, + View: ({ children }: { children: ReactNode }) => children, +})); vi.mock("react-native-safe-area-context", () => ({ useSafeAreaInsets: () => ({ top: 0 }) })); vi.mock("react-native-image-viewing", () => ({ default: function ImageViewing(props: { images: readonly { uri?: string }[]; imageIndex: number; + HeaderComponent?: ComponentType<{ imageIndex: number }>; }) { useState(() => harness.mounts++); harness.previews.push({ @@ -45,7 +93,17 @@ vi.mock("react-native-image-viewing", () => ({ images: props.images, selectedIndex: props.imageIndex, }); - return null; + const [index, setIndex] = useState(props.imageIndex); + const Header = props.HeaderComponent; + if (!Header) return null; + return ( + <> +
    + {props.images.map(({ uri }, imageIndex) => ( +
    - {hasProjects ? ( - <> - {projectScope} - - - - - ) : null} + {hasProjects ? projectScope : null} Date: Sun, 22 Nov 2026 15:44:40 -0500 Subject: [PATCH 205/324] feat(mobile): favorites only is its own model filter, not a provider (#32887) Co-authored-by: Julius Marminge --- .../features/threads/ThreadSettingsSheet.tsx | 45 ++++++++++++------- apps/mobile/src/i18n/translations/de.json | 2 +- apps/mobile/src/i18n/translations/en.json | 2 +- apps/mobile/src/i18n/translations/es.json | 2 +- apps/mobile/src/i18n/translations/fr.json | 2 +- apps/mobile/src/i18n/translations/ja.json | 2 +- apps/mobile/src/i18n/translations/ko.json | 2 +- apps/mobile/src/i18n/translations/pt-BR.json | 2 +- apps/mobile/src/i18n/translations/ru.json | 2 +- apps/mobile/src/i18n/translations/sv.json | 2 +- apps/mobile/src/i18n/translations/zh.json | 2 +- 11 files changed, 38 insertions(+), 27 deletions(-) diff --git a/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx b/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx index f90416a70b8b4..51fe125bf087e 100644 --- a/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx +++ b/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx @@ -146,7 +146,6 @@ const EMPTY_MODEL_FAVORITES: ReadonlyArray<{ readonly provider: ProviderInstanceId; readonly model: string; }> = []; -const FAVORITES_PROVIDER_FILTER = "@favorites"; // Servers that predate `migrateModelPreferences` drop it and keep reporting null favorites. const attemptedMigrationGenerations = new Map(); function ProviderHeader(props: { @@ -333,6 +332,7 @@ type ThreadSettingsSessionValue = { readonly providerExpansionOverrides: ReadonlySet; readonly hasLegacyModels: boolean; readonly pendingModel: ModelOption | null; + readonly favoritesOnly: boolean; readonly providerFilter: string | null; readonly searchQuery: string; readonly showLegacy: boolean; @@ -341,6 +341,7 @@ type ThreadSettingsSessionValue = { readonly isApplied: (option: ModelOption) => boolean; readonly isDisplayed: (option: ModelOption) => boolean; readonly pressModel: (option: ModelOption) => void; + readonly setFavoritesOnly: (favoritesOnly: boolean) => void; readonly setProviderFilter: (providerKey: string | null) => void; readonly setSearchQuery: (query: string) => void; readonly setShowLegacy: (showLegacy: boolean) => void; @@ -507,6 +508,7 @@ function ThreadSettingsSessionProvider( }); }; const [showLegacyToggle, setShowLegacyToggle] = useState(false); + const [favoritesOnly, setFavoritesOnly] = useState(false); const [providerFilter, setProviderFilter] = useState(null); const [searchQuery, setSearchQuery] = useState(""); const [providerExpansionOverrides, setProviderExpansionOverrides] = useState>( @@ -630,9 +632,7 @@ function ThreadSettingsSessionProvider( const environmentId = props.environmentId; // Like the web picker's open tab: scanning every provider would spawn a probe per provider. const scannedInstanceId = - providerFilter !== null && providerFilter !== FAVORITES_PROVIDER_FILTER - ? ProviderInstanceId.make(providerFilter) - : props.providerInstanceId; + providerFilter !== null ? ProviderInstanceId.make(providerFilter) : props.providerInstanceId; const workspaceScan = props.cwd && scannedInstanceId ? { instanceId: scannedInstanceId, cwd: props.cwd } : null; @@ -656,6 +656,7 @@ function ThreadSettingsSessionProvider( providerExpansionOverrides, hasLegacyModels, pendingModel, + favoritesOnly, providerFilter, searchQuery, showLegacy: showLegacyToggle, @@ -664,6 +665,7 @@ function ThreadSettingsSessionProvider( isApplied, isDisplayed, pressModel, + setFavoritesOnly, setProviderFilter, setSearchQuery, setShowLegacy: setShowLegacyToggle, @@ -842,7 +844,7 @@ function subProviderCatalogItems( if ( !group.subProviders?.length || session.searchQuery.trim().length > 0 || - session.providerFilter === FAVORITES_PROVIDER_FILTER + session.favoritesOnly ) { return null; } @@ -887,11 +889,7 @@ function buildThreadSettingsCatalogItems( locale: string, ): ReadonlyArray { return session.providerGroups.flatMap((group) => { - if ( - session.providerFilter !== null && - session.providerFilter !== FAVORITES_PROVIDER_FILTER && - group.providerKey !== session.providerFilter - ) { + if (session.providerFilter !== null && group.providerKey !== session.providerFilter) { return []; } const driver = group.models[0]?.providerDriver ?? group.providerKey; @@ -900,12 +898,12 @@ function buildThreadSettingsCatalogItems( providerLabel: group.providerLabel, query: session.searchQuery, favoriteKeys: session.favoriteKeys, - favoritesOnly: session.providerFilter === FAVORITES_PROVIDER_FILTER, + favoritesOnly: session.favoritesOnly, showLegacy: session.manageHidden || session.showLegacy, isDisplayed: session.isDisplayed, }); const updateRequiredNotice = - group.updateRequired && session.providerFilter !== FAVORITES_PROVIDER_FILTER + group.updateRequired && !session.favoritesOnly ? formatProviderUpdateRequiredNotice( group.updateRequired, session.searchQuery, @@ -918,7 +916,10 @@ function buildThreadSettingsCatalogItems( } const isPrimary = driver !== undefined && PRIMARY_PROVIDER_DRIVERS.has(driver); const containsAppliedSelection = group.models.some(session.isApplied); - const isNarrowed = session.providerFilter !== null || session.searchQuery.trim().length > 0; + const isNarrowed = + session.favoritesOnly || + session.providerFilter !== null || + session.searchQuery.trim().length > 0; const collapsible = !isNarrowed; const collapsed = providerSectionIsCollapsed({ defaultExpanded: isPrimary || containsAppliedSelection, @@ -1111,7 +1112,9 @@ function ThreadSettingsMainContent(props: { const animationsReady = listLoaded && !reducedMotion && !reduceMotionEnabled; const catalogItems = buildThreadSettingsCatalogItems(session, m, locale); const hasActiveCatalogFilter = - session.providerFilter !== null || session.searchQuery.trim().length > 0; + session.favoritesOnly || + session.providerFilter !== null || + session.searchQuery.trim().length > 0; const listItems = [ ...(catalogItems.length === 0 ? ([{ kind: "empty", key: "empty" }] as const) : catalogItems), { kind: "options", key: "options" }, @@ -1138,7 +1141,8 @@ function ThreadSettingsMainContent(props: { content = ( - {session.providerFilter === FAVORITES_PROVIDER_FILTER && + {session.favoritesOnly && + session.providerFilter === null && session.searchQuery.trim().length === 0 ? gt("No favorite models") : hasActiveCatalogFilter @@ -1331,7 +1335,8 @@ function ThreadSettingsModelsScreen() { const session = useThreadSettingsSession(); const presentation = useThreadSettingsPickerPresentation(); const navigation = useNavigation>(); - const hasCustomCatalogFilter = session.providerFilter !== null || session.showLegacy; + const hasCustomCatalogFilter = + session.favoritesOnly || session.providerFilter !== null || session.showLegacy; const commitAndClose = useEffectEvent(() => { if (!session.commitPendingModel()) return; presentation.onClose(); @@ -1347,7 +1352,6 @@ function ThreadSettingsModelsScreen() { const searchToolbarInset = useSearchToolbarInset(search); const providerFilters = [ { id: "all-providers", title: gt("All providers"), value: null }, - { id: "favorites", title: gt("Favorites"), value: FAVORITES_PROVIDER_FILTER }, ...session.providerGroups.map((group) => ({ id: `provider:${group.providerKey}`, title: group.providerLabel, @@ -1369,6 +1373,12 @@ function ThreadSettingsModelsScreen() { ? "line.3.horizontal.decrease.circle.fill" : "line.3.horizontal.decrease", items: [ + { + id: "favorites-only", + title: gt("Favorites only"), + selected: session.favoritesOnly, + onPress: () => session.setFavoritesOnly(!session.favoritesOnly), + }, { id: "provider", title: gt("Provider"), @@ -1393,6 +1403,7 @@ function ThreadSettingsModelsScreen() { }, ]} optionsVersion={[ + session.favoritesOnly, session.providerFilter, session.providerGroups.map((group) => group.providerKey), session.showLegacy, diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index 5adf7cae2b1f0..8b31a8b3c4344 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -4720,7 +4720,7 @@ "c11a66f71057f074": "Dein Prompt enthält „ultrathink“ im Text. Entferne es, um diese Option zu ändern.", "b589c01784b9a88c": "Modell suchen", "9b0277205d8a9b04": "Alle Anbieter", - "4314e052a3524c51": "Favoriten", + "72ae7e7c5ca1c5fc": "Nur Favoriten", "279ab25bdca98778": "Thread-Einstellungen", "0ef86daa831dde67": "Thread-Einstellungen abbrechen", "cb27bc9ea63671c0": "Modellfilter", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 44804860b704d..ca29f2163889b 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -4722,7 +4722,7 @@ "c11a66f71057f074": "Your prompt contains \"ultrathink\" in the text. Remove it to change this option.", "b589c01784b9a88c": "Find a model", "9b0277205d8a9b04": "All providers", - "4314e052a3524c51": "Favorites", + "72ae7e7c5ca1c5fc": "Favorites only", "279ab25bdca98778": "Thread settings", "0ef86daa831dde67": "Cancel thread settings", "cb27bc9ea63671c0": "Model filters", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index b89e4cd636b2e..95c353b708461 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -4713,7 +4713,7 @@ "c11a66f71057f074": "Tu prompt contiene \"ultrathink\" en el texto. Quítalo para cambiar esta opción.", "b589c01784b9a88c": "Buscar un modelo", "9b0277205d8a9b04": "Todos los proveedores", - "4314e052a3524c51": "Favoritos", + "72ae7e7c5ca1c5fc": "Solo favoritos", "279ab25bdca98778": "Ajustes del hilo", "0ef86daa831dde67": "Cancelar ajustes del hilo", "cb27bc9ea63671c0": "Filtros de modelos", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index 75e6c8ed3b83f..606119293ca58 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -4714,7 +4714,7 @@ "c11a66f71057f074": "Votre prompt contient « ultrathink ». Retirez-le pour modifier cette option.", "b589c01784b9a88c": "Trouver un modèle", "9b0277205d8a9b04": "Tous les fournisseurs", - "4314e052a3524c51": "Favoris", + "72ae7e7c5ca1c5fc": "Favoris uniquement", "279ab25bdca98778": "Paramètres du fil", "0ef86daa831dde67": "Annuler les paramètres du fil", "cb27bc9ea63671c0": "Filtres de modèles", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index ade01f9a68ae8..12279cacfe082 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -4694,7 +4694,7 @@ "c11a66f71057f074": "プロンプトのテキストに \"ultrathink\" が含まれています。このオプションを変更するには削除してください。", "b589c01784b9a88c": "モデルを検索", "9b0277205d8a9b04": "すべてのプロバイダー", - "4314e052a3524c51": "お気に入り", + "72ae7e7c5ca1c5fc": "お気に入りのみ", "279ab25bdca98778": "スレッドの設定", "0ef86daa831dde67": "スレッドの設定をキャンセル", "cb27bc9ea63671c0": "モデルのフィルター", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index e55249e7c76d5..6105dbbff9700 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -4699,7 +4699,7 @@ "c11a66f71057f074": "프롬프트 텍스트에 \"ultrathink\"가 포함되어 있습니다. 이 옵션을 변경하려면 제거하세요.", "b589c01784b9a88c": "모델 찾기", "9b0277205d8a9b04": "모든 제공자", - "4314e052a3524c51": "즐겨찾기", + "72ae7e7c5ca1c5fc": "즐겨찾기만", "279ab25bdca98778": "스레드 설정", "0ef86daa831dde67": "스레드 설정 취소", "cb27bc9ea63671c0": "모델 필터", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index e373faf86a051..346d3a17f8d1c 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -4714,7 +4714,7 @@ "c11a66f71057f074": "Seu prompt contém \"ultrathink\" no texto. Remova para mudar esta opção.", "b589c01784b9a88c": "Encontrar um modelo", "9b0277205d8a9b04": "Todos os provedores", - "4314e052a3524c51": "Favoritos", + "72ae7e7c5ca1c5fc": "Somente favoritos", "279ab25bdca98778": "Configurações da thread", "0ef86daa831dde67": "Cancelar configurações da thread", "cb27bc9ea63671c0": "Filtros de modelos", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index c56ae7ca47388..24f1f02d8282c 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -4792,7 +4792,7 @@ "c11a66f71057f074": "В тексте промпта есть «ultrathink». Удалите его, чтобы изменить этот параметр.", "b589c01784b9a88c": "Найти модель", "9b0277205d8a9b04": "Все провайдеры", - "4314e052a3524c51": "Избранное", + "72ae7e7c5ca1c5fc": "Только избранное", "279ab25bdca98778": "Настройки треда", "0ef86daa831dde67": "Отменить настройки треда", "cb27bc9ea63671c0": "Фильтры моделей", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 7887ac576fc11..e9df1ae43bff3 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -4720,7 +4720,7 @@ "c11a66f71057f074": "Din prompt innehåller ”ultrathink” i texten. Ta bort det för att ändra det här alternativet.", "b589c01784b9a88c": "Hitta en modell", "9b0277205d8a9b04": "Alla leverantörer", - "4314e052a3524c51": "Favoriter", + "72ae7e7c5ca1c5fc": "Endast favoriter", "279ab25bdca98778": "Trådinställningar", "0ef86daa831dde67": "Avbryt trådinställningar", "cb27bc9ea63671c0": "Modellfilter", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index 5b3d7f7841bfd..88cb17551721b 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -4703,7 +4703,7 @@ "c11a66f71057f074": "你的提示词中包含“ultrathink”。删除它才能修改这个选项。", "b589c01784b9a88c": "查找模型", "9b0277205d8a9b04": "所有提供方", - "4314e052a3524c51": "收藏", + "72ae7e7c5ca1c5fc": "仅收藏", "279ab25bdca98778": "会话设置", "0ef86daa831dde67": "取消会话设置", "cb27bc9ea63671c0": "模型筛选", From f9fbb004ac0c09ca178279ea84f336d2a8de81a5 Mon Sep 17 00:00:00 2001 From: JoshuaRileyDev <59296334+JoshuaRileyDev@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:45:29 +0000 Subject: [PATCH 206/324] feat(devices): double-tap Home opens the app switcher (#29459) Co-authored-by: Julius Marminge --- .../client-runtime/src/device/stream.test.ts | 29 +++++++++++++++++++ packages/client-runtime/src/device/stream.ts | 10 +++++-- 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/packages/client-runtime/src/device/stream.test.ts b/packages/client-runtime/src/device/stream.test.ts index ad930680fbeb5..9050e6c18504f 100644 --- a/packages/client-runtime/src/device/stream.test.ts +++ b/packages/client-runtime/src/device/stream.test.ts @@ -140,6 +140,35 @@ describe("native device stream transport", () => { }, ); + it.each([ + ["ios", { button: "home" }, { button: "app_switcher" }], + ["android", { type: "home" }, { type: "recents" }], + ] as const)( + "opens the %s app switcher on a double-tapped home button", + async (platform, home, switcher) => { + const { client, opened } = setup(platform); + client.start(); + const socket = await opened; + socket.onopen?.(); + if (platform === "ios") socket.onmessage?.({ data: Uint8Array.of(0x83).buffer }); + socket.send.mockClear(); + + client.pressButton("home"); + client.pressButton("home"); + client.pressButton("home"); + vi.advanceTimersByTime(1000); + client.pressButton("home"); + + const sent = socket.send.mock.calls.map(([payload]) => + JSON.parse( + typeof payload === "string" ? payload : new TextDecoder().decode(payload.subarray(1)), + ), + ); + expect(sent).toEqual([home, switcher, home, home]); + client.stop(); + }, + ); + it.each(["ios", "android"] as const)( "does not renew credentials or reconnect a stopped %s stream", async (platform) => { diff --git a/packages/client-runtime/src/device/stream.ts b/packages/client-runtime/src/device/stream.ts index c570ee107ad55..45824149a8c66 100644 --- a/packages/client-runtime/src/device/stream.ts +++ b/packages/client-runtime/src/device/stream.ts @@ -1,4 +1,4 @@ -// @effect-diagnostics globalFetch:off globalTimers:off - This browser and WebView transport runs without an Effect runtime. +// @effect-diagnostics globalFetch:off globalTimers:off globalDate:off - This browser and WebView transport runs without an Effect runtime. import { createDuoControl, @@ -157,6 +157,7 @@ const SOFT_DECODE_QUEUE = 8; const ANDROID_MAX_TEXT_BYTES = 300; // The pinned hub queue depth is 128; the client does not read queue rejections. const ANDROID_MAX_TEXT_CHUNKS = 64; +const HOME_DOUBLE_TAP_MS = 400; const IOS_MSG_TOUCH = 0x03; const IOS_MSG_BUTTON = 0x04; @@ -428,6 +429,7 @@ export function createDeviceStreamClient( isWebCodecsSupported() && !(platform === "ios" && target.preferMjpeg && !serveSimOnly); let stopped = true; + let lastHomePress = -Infinity; let socket: WebSocket | null = null; let controller: AbortController | null = null; const retryTimers = new Map<"video" | "input", ReturnType>(); @@ -1460,7 +1462,11 @@ export function createDeviceStreamClient( } if (chunk.length > 0) send(JSON.stringify({ type: "text", text: chunk })); }, - pressButton: (button) => { + pressButton: (pressed) => { + const now = Date.now(); + const doubleHome = pressed === "home" && now - lastHomePress < HOME_DOUBLE_TAP_MS; + lastHomePress = pressed === "home" && !doubleHome ? now : -Infinity; + const button = doubleHome ? "appSwitcher" : pressed; if (avcc) { const name = button === "home" From 735c1e74012248f47056953e91c7059949b2c2f6 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 12:48:31 -0800 Subject: [PATCH 207/324] test(desktop): AppImage shim test's fake server ignores a second stop signal (#41062) --- apps/desktop/src/app/DesktopCliShim.test.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/apps/desktop/src/app/DesktopCliShim.test.ts b/apps/desktop/src/app/DesktopCliShim.test.ts index 929148fdbb32f..dda8e058b7179 100644 --- a/apps/desktop/src/app/DesktopCliShim.test.ts +++ b/apps/desktop/src/app/DesktopCliShim.test.ts @@ -66,10 +66,11 @@ const fakeAppImage = (canMount = true, app = REPORTER) => { return { root, image, appImage, shim }; }; -// Stays up after a signal until the test lets it finish, like a server shutting down. +// Stays up after a signal until the test lets it finish, like a server shutting down. A group +// signal and the launcher's forwarded one can both arrive; a re-run trap would read stdin's EOF. const SLOW_SERVER = [ "#!/bin/sh", - "trap 'echo stopping >&3; read go; echo \"stopped $go\" >&3; exit 7' TERM HUP", + 'trap \'trap "" TERM HUP; echo stopping >&3; read go; echo "stopped $go" >&3; exit 7\' TERM HUP', "echo ready", "while :; do sleep 0.05; done", "", From 7e3a9ba1b9b1551d379dddf7d109d8a98121036d Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 12:49:30 -0800 Subject: [PATCH 208/324] fix(server): a task folder creation that loses a branch race no longer deletes the winner's branch (#41061) --- apps/server/src/workspace/TaskFolders.test.ts | 51 +++++++------- apps/server/src/workspace/TaskFolders.ts | 67 +++++++++++++------ 2 files changed, 74 insertions(+), 44 deletions(-) diff --git a/apps/server/src/workspace/TaskFolders.test.ts b/apps/server/src/workspace/TaskFolders.test.ts index c156f190e0049..2be3e39c09817 100644 --- a/apps/server/src/workspace/TaskFolders.test.ts +++ b/apps/server/src/workspace/TaskFolders.test.ts @@ -248,32 +248,35 @@ it.effect("finds no common folder for two Windows drives instead of climbing for }).pipe(Effect.provide(NodePath.layerWin32)), ); -it.live("gives two creations on one branch a folder each", () => - withState((state) => - Effect.gen(function* () { - const { fileSystem, path, tmp, repository } = yield* fixture; - const api = yield* repository("shop/api"); - state.workspaceRoot = path.join(tmp, "shop"); - state.trackedFolders = tracked(api); +it.live.each([{ projectIsRepository: false }, { projectIsRepository: true }])( + "gives two creations on one branch a folder each, project is a repository=$projectIsRepository", + ({ projectIsRepository }) => + withState((state) => + Effect.gen(function* () { + const { fileSystem, path, tmp, repository } = yield* fixture; + const shop = projectIsRepository ? yield* repository("shop") : path.join(tmp, "shop"); + const api = yield* repository("shop/api"); + state.workspaceRoot = shop; + state.trackedFolders = tracked(api); - // Git gives the branch to one of them; the other's rollback must leave that one's folder. - const exits = yield* Effect.all( - [Effect.exit(create("feature")), Effect.exit(create("feature"))], - { - concurrency: 2, - }, - ); + // Git gives the branch to one of them; the other's rollback must leave that one's folder. + const exits = yield* Effect.all( + [Effect.exit(create("feature")), Effect.exit(create("feature"))], + { + concurrency: 2, + }, + ); - const created = exits.flatMap((exit) => - Exit.isSuccess(exit) ? [exit.value.taskFolder] : [], - ); - assert.isAtLeast(created.length, 1); - assert.equal(new Set(created.map((taskFolder) => taskFolder.root)).size, created.length); - for (const taskFolder of created) { - assert.isTrue(yield* fileSystem.exists(path.join(taskFolder.root, "api", "README.md"))); - } - }), - ), + const created = exits.flatMap((exit) => + Exit.isSuccess(exit) ? [exit.value.taskFolder] : [], + ); + assert.isAtLeast(created.length, 1); + assert.equal(new Set(created.map((taskFolder) => taskFolder.root)).size, created.length); + for (const taskFolder of created) { + assert.isTrue(yield* fileSystem.exists(path.join(taskFolder.root, "api", "README.md"))); + } + }), + ), ); it.live.each([{ projectIsRepository: true }, { projectIsRepository: false }])( diff --git a/apps/server/src/workspace/TaskFolders.ts b/apps/server/src/workspace/TaskFolders.ts index 4911065118ce4..75c12d8a7409b 100644 --- a/apps/server/src/workspace/TaskFolders.ts +++ b/apps/server/src/workspace/TaskFolders.ts @@ -1,4 +1,5 @@ import { + GitCommandError, type ProjectId, type ProjectTrackedFolder, TASK_FOLDER_DEFAULT_REPOSITORIES_MAX, @@ -15,6 +16,7 @@ import { flattenTemporaryWorktreeBranchName, isTemporaryWorktreeBranch } from "@ import * as HostProcess from "@t3tools/shared/HostProcess"; import * as KeyedLock from "@t3tools/shared/KeyedLock"; import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile"; +import * as Cause from "effect/Cause"; import * as Context from "effect/Context"; import * as Digest from "effect/crypto/Digest"; import * as Effect from "effect/Effect"; @@ -224,6 +226,8 @@ export const layoutAnchor = ( return { anchor, unreachable }; }; +const isGitCommandError = Schema.is(GitCommandError); + const make = Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -863,6 +867,7 @@ const make = Effect.gen(function* () { branch: string, startFromOrigin: boolean, baseBranch: string | undefined, + recordBranch: (exit: Exit.Exit) => Effect.Effect, ) { const worktreePath = mapped(taskFolder, repository.path); // The project's own checkout (a post-checkout hook, say) already provided this repository. @@ -874,13 +879,15 @@ const make = Effect.gen(function* () { return null; yield* fileSystem.makeDirectory(path.dirname(worktreePath), { recursive: true }); const start = yield* repositoryStart(repository.path, startFromOrigin, baseBranch); - yield* git.createWorktree({ - cwd: repository.path, - refName: start.refName, - newRefName: branch, - baseRefName: start.baseRefName, - path: worktreePath, - }); + yield* git + .createWorktree({ + cwd: repository.path, + refName: start.refName, + newRefName: branch, + baseRefName: start.baseRefName, + path: worktreePath, + }) + .pipe(Effect.onExit(recordBranch)); return { repository: { repositoryPath: repository.path, @@ -933,15 +940,32 @@ const make = Effect.gen(function* () { // A layout command may check out a branch that was already there; a rollback leaves it. const hadBranch = new Set(); let layoutStarted = false; - // Where this attempt makes the branch: a checkout that fails halfway leaves it behind. - let branchMadeIn = [ + // Where this attempt may make the branch: none of them had it when listed. + const branchMissingIn = new Set([ ...taskPlan.repositories .filter((_, index) => !names[index]!.includes(branch)) .map((repository) => repository.path), ...(taskPlan.projectIsRepository && !projectNames.includes(branch) ? [taskPlan.projectRoot] : []), - ]; + ]); + // Where this attempt made the branch: a checkout that fails halfway leaves it behind. Only + // a checkout it ran counts, and not one Git refused because another creation made it first. + let branchMadeIn: string[] = []; + const recordBranch = + (cwd: string) => + (exit: Exit.Exit) => + Effect.sync(() => { + const refused = + Exit.isFailure(exit) && + exit.cause.reasons.some( + (reason) => + Cause.isFailReason(reason) && + isGitCommandError(reason.error) && + reason.error.operation === "GitVcsDriver.createWorktree.createBranch", + ); + if (branchMissingIn.has(cwd) && !refused) branchMadeIn.push(cwd); + }); return yield* Effect.gen(function* () { yield* fileSystem.makeDirectory(root, { recursive: true }); // Recorded before any checkout, so an interrupted creation is still found and removed. @@ -1010,16 +1034,18 @@ const make = Effect.gen(function* () { } if (taskPlan.projectIsRepository) { yield* fileSystem.makeDirectory(path.dirname(empty.projectPath), { recursive: true }); - yield* git.createWorktree( - { - cwd: taskPlan.projectRoot, - refName: input.projectStart.refName, - newRefName: branch, - baseRefName: input.projectStart.baseRefName, - path: empty.projectPath, - }, - input.projectProgress === undefined ? {} : { progress: input.projectProgress }, - ); + yield* git + .createWorktree( + { + cwd: taskPlan.projectRoot, + refName: input.projectStart.refName, + newRefName: branch, + baseRefName: input.projectStart.baseRefName, + path: empty.projectPath, + }, + input.projectProgress === undefined ? {} : { progress: input.projectProgress }, + ) + .pipe(Effect.onExit(recordBranch(taskPlan.projectRoot))); } else { yield* linkFolder(taskPlan.projectRoot, empty.projectPath, taskPlan.trackedRepositories); } @@ -1049,6 +1075,7 @@ const make = Effect.gen(function* () { branch, input.startFromOrigin, input.baseBranch, + recordBranch(repository.path), ) ).pipe( Effect.tap((worktree) => From e213da2a32236cd932687351a0694be8935d92b0 Mon Sep 17 00:00:00 2001 From: Tameem Bin Haider Date: Mon, 23 Nov 2026 02:57:01 +0600 Subject: [PATCH 209/324] fix(client-runtime): refresh stale server clock offset after host sleep (#41037) Co-authored-by: Julius Marminge --- apps/server/src/ws.ts | 3 +- packages/client-runtime/src/clock.test.ts | 28 +++++++++++- packages/client-runtime/src/clock.ts | 23 ++++++++++ .../client-runtime/src/rpc/session.test.ts | 43 +++++++++++++++++++ packages/client-runtime/src/rpc/session.ts | 15 ++++++- packages/client-runtime/src/state/shell.ts | 12 ++++++ .../src/state/threads-sync.test.ts | 12 ++++++ packages/client-runtime/src/state/threads.ts | 28 ++++++++++-- packages/contracts/src/rpc.ts | 6 ++- 9 files changed, 160 insertions(+), 10 deletions(-) diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index b5faaaa16f97c..fc04ad68e46cd 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -2396,7 +2396,8 @@ export const layerWsRpc = ( Effect.annotateCurrentSpan({ "scheduled_task.id": input.id }).pipe( Effect.andThen(scheduledTasks.getWebhookDelivery(input)), ), - [WS_METHODS.serverProbe]: (_input) => Effect.succeed({}), + [WS_METHODS.serverProbe]: (_input) => + Effect.map(DateTime.now, (now) => ({ serverTime: DateTime.formatIso(now) })), [WS_METHODS.serverGetConfig]: (_input) => loadServerConfig({ usageLimitsCommand: false, diff --git a/packages/client-runtime/src/clock.test.ts b/packages/client-runtime/src/clock.test.ts index 1f45860addf7c..f26f830d5b88c 100644 --- a/packages/client-runtime/src/clock.test.ts +++ b/packages/client-runtime/src/clock.test.ts @@ -1,6 +1,12 @@ import { EnvironmentId } from "@t3tools/contracts"; import { afterEach, describe, expect, it, vi } from "vite-plus/test"; -import { deadlineStore, recordServerClock, secondTick, toServerClock } from "./clock.ts"; +import { + deadlineStore, + observeServerTime, + recordServerClock, + secondTick, + toServerClock, +} from "./clock.ts"; describe("deadlineStore", () => { afterEach(() => { @@ -172,4 +178,24 @@ describe("server clock", () => { }); expect(toServerClock(environmentId, 12_345)).toBe(12_345); }); + + it("raises a stale negative offset when a host timestamp arrives ahead of it", () => { + const environmentId = EnvironmentId.make("caught-up"); + recordServerClock(environmentId, { + serverTimeMs: 1_000, + requestedAtMs: 2 * HOUR + 900, + receivedAtMs: 2 * HOUR + 1_050, + }); + expect(toServerClock(environmentId, 2 * HOUR + 10_050)).toBe(10_150); + + observeServerTime(environmentId, 2 * HOUR + 10_000, 2 * HOUR + 10_050); + expect(toServerClock(environmentId, 2 * HOUR + 20_050)).toBe(2 * HOUR + 20_000); + + observeServerTime(environmentId, 5_000, 2 * HOUR + 20_100); + expect(toServerClock(environmentId, 2 * HOUR + 20_050)).toBe(2 * HOUR + 20_000); + + const unrecorded = EnvironmentId.make("unrecorded"); + observeServerTime(unrecorded, HOUR, 1_000); + expect(toServerClock(unrecorded, 1_000)).toBe(1_000); + }); }); diff --git a/packages/client-runtime/src/clock.ts b/packages/client-runtime/src/clock.ts index f8f1290730084..67693220883b8 100644 --- a/packages/client-runtime/src/clock.ts +++ b/packages/client-runtime/src/clock.ts @@ -104,6 +104,29 @@ export function recordServerClock( ); } +/** + * A timestamp stamped by the host is never in its own future, so it gives a + * lower bound on the host's clock. Raises a stale negative offset (for example + * when a VM or WSL clock catches up after host sleep) without shifting a clock + * that already agrees. + */ +export function observeServerTime( + environmentId: EnvironmentId, + serverTimeMs: number, + receivedAtMs: number, +): void { + const currentOffset = serverClockOffsets.get(environmentId); + if ( + currentOffset === undefined || + !Number.isFinite(serverTimeMs) || + !Number.isFinite(receivedAtMs) + ) { + return; + } + if (receivedAtMs + currentOffset >= serverTimeMs) return; + serverClockOffsets.set(environmentId, serverTimeMs - receivedAtMs); +} + /** Converts client epoch milliseconds to the environment's clock. */ export function toServerClock(environmentId: EnvironmentId, clientMs: number): number { return clientMs + (serverClockOffsets.get(environmentId) ?? 0); diff --git a/packages/client-runtime/src/rpc/session.test.ts b/packages/client-runtime/src/rpc/session.test.ts index ebd4780ba5064..27bb60f567e10 100644 --- a/packages/client-runtime/src/rpc/session.test.ts +++ b/packages/client-runtime/src/rpc/session.test.ts @@ -1152,6 +1152,49 @@ describe("RpcSessionFactory", () => { }), ); + it.effect("refreshes the host clock when a liveness probe returns serverTime", () => + Effect.gen(function* () { + const { factory, sockets } = yield* makeFactory(); + const session = yield* factory.connect(PREPARED); + const ready = yield* Effect.forkChild(session.ready); + const socket = yield* awaitSocket(sockets); + socket.open(); + yield* completeInitialConfig(socket, { + ...ENCODED_SERVER_CONFIG, + serverTime: "1970-01-01T01:00:00.000Z", + }); + yield* Fiber.join(ready); + expect(toServerClock(PREPARED.environmentId, 0)).toBe(3_600_000); + + const legacyProbe = yield* Effect.forkChild(session.probe); + const legacyRequest = yield* awaitRequest(socket, 1); + socket.serverMessage( + encodeJson({ + _tag: "Exit", + requestId: legacyRequest.id, + exit: { _tag: "Success", value: {} }, + }), + ); + yield* Fiber.join(legacyProbe); + expect(toServerClock(PREPARED.environmentId, 0)).toBe(3_600_000); + + const probe = yield* Effect.forkChild(session.probe); + const probeRequest = yield* awaitRequest(socket, 2); + socket.serverMessage( + encodeJson({ + _tag: "Exit", + requestId: probeRequest.id, + exit: { + _tag: "Success", + value: { serverTime: "1970-01-01T00:00:00.000Z" }, + }, + }), + ); + yield* Fiber.join(probe); + expect(toServerClock(PREPARED.environmentId, 0)).toBe(0); + }), + ); + it.effect("reaches ready when a newer server sends unknown config members", () => Effect.gen(function* () { const { factory, sockets } = yield* makeFactory(); diff --git a/packages/client-runtime/src/rpc/session.ts b/packages/client-runtime/src/rpc/session.ts index 91160a60941db..148005df2124d 100644 --- a/packages/client-runtime/src/rpc/session.ts +++ b/packages/client-runtime/src/rpc/session.ts @@ -515,9 +515,20 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( ); const probe = initialConfig.pipe( Effect.flatMap(() => - protocolClient[WS_METHODS.serverProbe]({}).pipe(Effect.mapError(mapRpcError)), + Effect.gen(function* () { + const requestedAtMs = yield* Clock.currentTimeMillis; + const result = yield* protocolClient[WS_METHODS.serverProbe]({}).pipe( + Effect.mapError(mapRpcError), + ); + if (result.serverTime !== undefined) { + recordServerClock(connection.environmentId, { + serverTimeMs: Date.parse(result.serverTime), + requestedAtMs, + receivedAtMs: yield* Clock.currentTimeMillis, + }); + } + }), ), - Effect.asVoid, Effect.withSpan("clientRuntime.connection.rpcSession.probe"), ); diff --git a/packages/client-runtime/src/state/shell.ts b/packages/client-runtime/src/state/shell.ts index 9fdd1898cc1cf..24fe257d58285 100644 --- a/packages/client-runtime/src/state/shell.ts +++ b/packages/client-runtime/src/state/shell.ts @@ -13,6 +13,7 @@ import { } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; import * as Clock from "effect/Clock"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; @@ -25,6 +26,7 @@ import * as SubscriptionRef from "effect/SubscriptionRef"; import * as SynchronizedRef from "effect/SynchronizedRef"; import { AsyncResult, Atom } from "effect/reactivity"; +import { observeServerTime } from "../clock.ts"; import * as EnvironmentRegistry from "../connection/registry.ts"; import { connectionProjectionPhase, type PreparedConnection } from "../connection/model.ts"; import * as EnvironmentSupervisor from "../connection/supervisor.ts"; @@ -324,6 +326,7 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make") let receivedAuthoritativeSnapshot = false; let snapshotRequired = false; let deltas: Array = []; + const receivedAtMs = yield* Clock.currentTimeMillis; const flushDeltas = () => { if (deltas.length > 0 && Option.isSome(next.snapshot)) { let sequence = next.snapshot.value.snapshotSequence; @@ -336,6 +339,15 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make") removedAt.set(delta.threadId, delta.sequence); break; case "thread.updated": + // Replayed catch-up deltas may predate a backward host clock correction. + if (!waiting) { + observeServerTime( + environmentId, + DateTime.toEpochMillis(delta.thread.updatedAt), + receivedAtMs, + ); + } + break; case "project.updated": case "project.removed": break; diff --git a/packages/client-runtime/src/state/threads-sync.test.ts b/packages/client-runtime/src/state/threads-sync.test.ts index 9fff726cd6ab8..d14b8a66c40cd 100644 --- a/packages/client-runtime/src/state/threads-sync.test.ts +++ b/packages/client-runtime/src/state/threads-sync.test.ts @@ -39,6 +39,7 @@ import { type PreparedConnection, type SupervisorConnectionState, } from "../connection/model.ts"; +import { recordServerClock, toServerClock } from "../clock.ts"; import * as ConnectionWakeups from "../connection/wakeups.ts"; import * as EnvironmentSupervisor from "../connection/supervisor.ts"; import * as Persistence from "../platform/persistence.ts"; @@ -2546,6 +2547,13 @@ describe("EnvironmentThreads", () => { it.effect("publishes a 20-event catch-up as one state change at its marker", () => Effect.gen(function* () { + // Replayed events can predate a backward host clock correction, so only live ones + // may raise the recorded offset. + recordServerClock(PREPARED.environmentId, { + serverTimeMs: 0, + requestedAtMs: 0, + receivedAtMs: 0, + }); const harness = yield* makeHarness({ cached: BASE_PROJECTION, completionMarker: true }); yield* awaitSubscriptionCount(harness, 1); expect(yield* Ref.get(harness.lastRequestCompletionMarker)).toBe(true); @@ -2564,10 +2572,14 @@ describe("EnvironmentThreads", () => { const live = yield* Queue.take(harness.observed); expect(live.status).toBe("live"); expect(Option.getOrThrow(live.data).thread.title).toBe("Title 20"); + expect(toServerClock(PREPARED.environmentId, 0)).toBe(0); yield* Queue.offer(harness.inputs, titleUpdated("Live title", CACHED_SNAPSHOT_SEQUENCE + 21)); const next = yield* Queue.take(harness.observed); expect(Option.getOrThrow(next.data).thread.title).toBe("Live title"); + expect(toServerClock(PREPARED.environmentId, 0)).toBe( + DateTime.toEpochMillis(Option.getOrThrow(next.data).thread.updatedAt), + ); }), ); diff --git a/packages/client-runtime/src/state/threads.ts b/packages/client-runtime/src/state/threads.ts index 4882df1a6836e..c0921417ba5cf 100644 --- a/packages/client-runtime/src/state/threads.ts +++ b/packages/client-runtime/src/state/threads.ts @@ -13,6 +13,8 @@ import { import { boundedSnapshotProjection } from "@t3tools/shared/orchestrationV2BoundedSnapshot"; import { pendingBackgroundTurnItems } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; import * as Cause from "effect/Cause"; +import * as Clock from "effect/Clock"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as Scope from "effect/Scope"; @@ -26,6 +28,7 @@ import * as SubscriptionRef from "effect/SubscriptionRef"; import { HttpClient } from "effect/http"; import { Atom } from "effect/reactivity"; +import { observeServerTime } from "../clock.ts"; import * as RemoteEnvironmentAuthorization from "../authorization/service.ts"; import * as EnvironmentRegistry from "../connection/registry.ts"; import { connectionProjectionPhase } from "../connection/model.ts"; @@ -541,7 +544,11 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make { kind: "event" | "unknown-event" } >; // Per-batch streaming spans add trace volume without a useful timing boundary. - const applyEventsLocked = Effect.fnUntraced(function* (items: ReadonlyArray) { + const applyEventsLocked = Effect.fnUntraced(function* ( + items: ReadonlyArray, + // Replayed catch-up events may predate a backward host clock correction. + live: boolean, + ) { const appliedSequence = yield* SubscriptionRef.get(lastSequence); let sequence = appliedSequence; const fresh: EventItem[] = []; @@ -565,6 +572,17 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make yield* SubscriptionRef.set(lastSequence, sequence); if (fresh.length === 0) return; + if (live) { + const receivedAtMs = yield* Clock.currentTimeMillis; + for (const item of fresh) { + observeServerTime( + environmentId, + DateTime.toEpochMillis(item.event.occurredAt), + receivedAtMs, + ); + } + } + const waiting = yield* Ref.get(awaitingCompletion); // Apply against the latest projection/history in one update so a concurrent // loadEarlier merge (or history-meta patch) cannot be clobbered by a stale @@ -701,7 +719,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make return; } - yield* applyEventsLocked([item]); + yield* applyEventsLocked([item], false); }); // Items held until the completion marker apply together, so a replay-only resume renders once. @@ -739,6 +757,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make } const items = catchUp; catchUp = []; + let live = !(yield* Ref.get(awaitingCompletion)); let events: SequencedItem[] = []; for (const item of items) { if ( @@ -751,11 +770,12 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make // Clearing the flag first lets the events before the marker publish // "live", so a catch-up ending in the marker is one state change. if (item.kind === "synchronized") yield* Ref.set(awaitingCompletion, false); - yield* applyEventsLocked(events); + yield* applyEventsLocked(events, live); events = []; yield* applyItemLocked(item); + if (item.kind === "synchronized") live = true; } - yield* applyEventsLocked(events); + yield* applyEventsLocked(events, live); yield* remember; }), ); diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index e30bf9af2937c..8a8fe05efb4da 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -45,7 +45,7 @@ import * as Schema from "effect/Schema"; import * as Rpc from "effect/rpc/Rpc"; import * as RpcGroup from "effect/rpc/RpcGroup"; import * as RpcMiddleware from "effect/rpc/RpcMiddleware"; -import { NonNegativeInt, TrimmedNonEmptyString } from "./baseSchemas.ts"; +import { IsoDateTime, NonNegativeInt, TrimmedNonEmptyString } from "./baseSchemas.ts"; import { SecretSourceCheckResult } from "./settingsSecretValue.ts"; import { SecretReference } from "./secretReference.ts"; import { @@ -725,7 +725,9 @@ const WsServerRemoveKeybindingRpc = Rpc.make(WS_METHODS.serverRemoveKeybinding, const WsServerProbeRpc = Rpc.make(WS_METHODS.serverProbe, { payload: Schema.Struct({}), - success: Schema.Struct({}), + success: Schema.Struct({ + serverTime: Schema.optionalKey(IsoDateTime), + }), error: EnvironmentAuthorizationError, }); From 68e81cd1450fac2e150e01cad8c96525316b209c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 13:02:28 -0800 Subject: [PATCH 210/324] fix(server): settled-subagent check reads run status from runs_run_status_idx (#37902) Co-authored-by: shivam <91240327+shivamhwp@users.noreply.github.com> --- .../orchestration-v2/ProjectionStore.test.ts | 19 +++++- .../src/orchestration-v2/ProjectionStore.ts | 67 ++++++++++++------- 2 files changed, 59 insertions(+), 27 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index 8df11001e241a..f13f3f05409ba 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -2520,6 +2520,18 @@ const commandReadsSkipSettledLeafNodes = Effect.gen(function* () { subagents.length, ); // Both reads stay inside their indexes: no scan of the thread's nodes or provider threads. + // A dispatcher's statistics: the mostly NULL owner and session indexes match every row. + yield* sql`ANALYZE orchestration_v2_projection_provider_threads`; + yield* sql`DELETE FROM sqlite_stat1 WHERE tbl = 'orchestration_v2_projection_provider_threads'`; + for (const [index, stat] of [ + ["sqlite_autoindex_orchestration_v2_projection_provider_threads_1", "5531 1"], + ["orchestration_v2_projection_provider_threads_thread_idx", "5531 1"], + ["orchestration_v2_projection_provider_threads_owner_idx", "5531 5531"], + ["orchestration_v2_projection_provider_threads_session_idx", "5531 2766"], + ] as const) { + yield* sql`INSERT INTO sqlite_stat1 VALUES ('orchestration_v2_projection_provider_threads', ${index}, ${stat})`; + } + yield* sql`ANALYZE sqlite_schema`; for (const [table, seeks] of [ [ "nodes", @@ -2528,11 +2540,16 @@ const commandReadsSkipSettledLeafNodes = Effect.gen(function* () { "SEARCH settled USING COVERING INDEX", "SEARCH settled_node USING COVERING INDEX", "subagents_settled_idx (thread_id=?)", + "SEARCH run USING COVERING INDEX orchestration_v2_projection_runs_run_status_idx", ], ], [ "provider_threads", - ["MULTI-INDEX OR", "provider_threads_session_idx (provider_session_id=?)"], + [ + "SEARCH orchestration_v2_projection_provider_threads USING INTEGER PRIMARY KEY", + "provider_threads_session_idx (provider_session_id=?)", + "SEARCH run USING COVERING INDEX orchestration_v2_projection_runs_run_status_idx", + ], ], ] as const) { const query = commandTrace.statements.find((statement) => diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index e930fa67e3836..e10bc5340d646 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -2363,6 +2363,7 @@ export const layer: Layer.Layer = AND COALESCE(${row}.completion_delivery_state, '') IN ('acknowledged', 'delivered', 'disposed') AND NOT EXISTS ( SELECT 1 FROM orchestration_v2_projection_runs AS run + INDEXED BY orchestration_v2_projection_runs_run_status_idx WHERE run.run_id = ${row}.run_id AND run.status IN ('preparing', 'queued', 'starting', 'running', 'waiting') ) @@ -2383,6 +2384,7 @@ export const layer: Layer.Layer = const todoListOfSettledRun = (row: Statement.Fragment) => sql`( ${row}.kind = 'todo_list' AND ${row}.run_id IS NOT NULL AND NOT EXISTS ( SELECT 1 FROM orchestration_v2_projection_runs AS todo_run + INDEXED BY orchestration_v2_projection_runs_run_status_idx WHERE todo_run.run_id = ${row}.run_id AND todo_run.status IN ('queued','preparing','starting','running','waiting') ))`; @@ -4388,37 +4390,50 @@ export const layer: Layer.Layer = ? sql` SELECT payload_json FROM orchestration_v2_projection_provider_threads - WHERE (thread_id = ${threadId} + WHERE ${ + filter?.omitSettledSubagentRecords === true + ? // A dispatcher's settled tasks' provider threads belong to the child threads; + // only a session this thread also uses is probed when it detaches. Most rows + // lack an owner or session, so ANALYZE rates those indexes as matching every + // row and SQLite scans for an OR of them; each union branch seeks instead. + sql`rowid IN ( + SELECT rowid FROM orchestration_v2_projection_provider_threads + WHERE thread_id = ${threadId} + UNION + SELECT rowid FROM orchestration_v2_projection_provider_threads + INDEXED BY orchestration_v2_projection_provider_threads_owner_idx + WHERE owner_node_id IN (${nodesOwningProviderThreads(threadId)}) + UNION + SELECT rowid FROM orchestration_v2_projection_provider_threads + WHERE provider_thread_id IN ( + SELECT provider_thread_id + FROM orchestration_v2_projection_subagents + WHERE rowid IN (${unsettledSubagentRowids(threadId)}) + AND provider_thread_id IS NOT NULL + ) + UNION + SELECT rowid FROM orchestration_v2_projection_provider_threads AS shared + INDEXED BY orchestration_v2_projection_provider_threads_session_idx + WHERE provider_session_id IN ( + SELECT provider_session_id + FROM orchestration_v2_projection_provider_session_bindings + WHERE thread_id = ${threadId} + ) + AND EXISTS ( + SELECT 1 FROM orchestration_v2_projection_subagents AS owner + WHERE owner.provider_thread_id = shared.provider_thread_id + AND owner.thread_id = ${threadId} + ) + )` + : sql`(thread_id = ${threadId} OR owner_node_id IN (${nodesOwningProviderThreads(threadId)}) - OR ${ - filter?.omitSettledSubagentRecords === true - ? // A dispatcher thread holds thousands of settled tasks. Their provider - // threads belong to the child threads; only a session this thread also - // uses is probed for background work when the thread detaches it. - sql`provider_thread_id IN ( - SELECT provider_thread_id - FROM orchestration_v2_projection_subagents - WHERE rowid IN (${unsettledSubagentRowids(threadId)}) - AND provider_thread_id IS NOT NULL - ) - OR (provider_session_id IN ( - SELECT provider_session_id - FROM orchestration_v2_projection_provider_session_bindings - WHERE thread_id = ${threadId} - ) - AND EXISTS ( - SELECT 1 FROM orchestration_v2_projection_subagents AS owner - WHERE owner.provider_thread_id = - orchestration_v2_projection_provider_threads.provider_thread_id - AND owner.thread_id = ${threadId} - ))` - : sql`provider_thread_id IN ( + OR provider_thread_id IN ( SELECT provider_thread_id FROM orchestration_v2_projection_subagents WHERE thread_id = ${threadId} AND provider_thread_id IS NOT NULL - )` - }) + ))` + } ${filter?.providerThreadIds === undefined ? sql`` : sql`AND provider_thread_id IN (SELECT value FROM json_each(${encodeIdList(filter.providerThreadIds)}))`} ORDER BY COALESCE(first_run_ordinal, 0), provider_thread_id ASC ` From 324ac49c5e6bf245778a2e578e075fbbc0525b65 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 13:02:39 -0800 Subject: [PATCH 211/324] fix(server): fresh-session scheduled runs release every idle Codex thread (#41055) --- .../ProviderSessionManager.test.ts | 89 ++++++++++++ .../ProviderSessionManager.ts | 136 +++++++++++------- 2 files changed, 177 insertions(+), 48 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index fcee608e3013f..4f67c42bb6d76 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -5572,6 +5572,95 @@ it.effect.each([ }), ); +it.effect( + "ProviderSessionManagerV2 unloads each idle native thread a fresh session replaced in the same app thread", + () => + Effect.gen(function* () { + const state = yield* Ref.make(emptyState); + const effect = Effect.gen(function* () { + const eventSink = yield* EventSink.EventSinkV2; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; + const projectionStore = yield* ProjectionStore.ProjectionStoreV2; + const now = yield* DateTime.now; + const threadId = ThreadId.make("thread-provider-session-manager-fresh-rounds"); + const providerSessionId = idAllocator.derive.providerSession({ + providerInstanceId: modelSelection.instanceId, + }); + yield* eventSink.write({ + events: [yield* makeThreadCreatedEvent({ idAllocator, threadId, now })], + }); + const runtime = yield* manager.open({ + threadId, + providerSessionId, + modelSelection, + runtimePolicy, + }); + // Each scheduled "fresh session" round opens a new native thread in the same app thread. + for (const round of [1, 2]) { + const runId = idAllocator.derive.run({ threadId, ordinal: round }); + const providerThread = makeProviderThread({ + idAllocator, + threadId, + providerSessionId, + now, + nativeThreadId: `native-round-${round}`, + }); + yield* runtime.startTurn({ + appThread: (yield* projectionStore.getThreadProjection(threadId)).thread, + threadId, + runId, + runOrdinal: round, + providerTurnOrdinal: 1, + attemptId: idAllocator.derive.runAttempt({ runId, attemptOrdinal: 1 }), + rootNodeId: idAllocator.derive.rootNode({ runId }), + providerThread, + message: { + createdBy: "user", + creationSource: "server", + messageId: yield* idAllocator.allocate.message({ threadId, ordinal: round }), + text: "Reply with OK.", + attachments: [], + }, + modelSelection, + runtimePolicy, + }); + const subscription = yield* runtime.subscribeEvents!; + yield* Queue.offer((yield* Ref.get(state)).eventQueues.get(String(providerSessionId))!, { + type: "turn.terminal", + driver: CODEX_DRIVER, + providerThreadId: providerThread.id, + providerTurnId: idAllocator.derive.providerTurn({ + driver: CODEX_DRIVER, + nativeTurnId: `native-turn-${round}`, + }), + runOrdinal: round, + status: "completed", + failure: null, + threadDisposition: "reusable", + }); + yield* subscription.events.pipe(Stream.runHead); + } + + yield* TestClock.adjust("1 second"); + assert.sameMembers( + [...(yield* Ref.get(state)).unloadedNativeThreadIds], + ["native-round-1", "native-round-2"], + ); + }); + + yield* effect.pipe( + Effect.provide( + layerTest({ + state, + idleTimeoutMs: 1000, + // Keep the shared app-server open, as other conversations do. + hasPendingBackgroundWork: Effect.succeed(true), + }), + ), + ); + }), +); it.effect( "ProviderSessionManagerV2 re-attaching a thread waits for its in-flight unload, then reloads it", () => diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index dd573acb1fe17..463bcb5088b2f 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -342,10 +342,12 @@ interface LiveSessionEntry { readonly busyTurns: ReadonlySet; readonly idleFiber: Fiber.Fiber | null; readonly pinnedSinceMs: number | null; - readonly idleThreadUnloads: ReadonlyMap; + /** Keyed by native thread: a fresh session leaves the replaced one to unload on its own timer. */ + readonly idleThreadUnloads: ReadonlyMap; } interface IdleThreadUnload { + readonly threadId: ThreadId; readonly providerThread: OrchestrationV2ProviderThread; readonly generation: number; readonly fiber: Fiber.Fiber | null; @@ -417,6 +419,17 @@ function providerThreadRuntimeKey( : `${nativeThreadRef.driver}:${nativeThreadRef.nativeId}`; } +function isLoadKeyFor( + loadKey: string | undefined, + providerThread: Parameters[0], +): boolean { + return ( + loadKey === undefined || + (JSON.parse(loadKey) as { providerThread: string }).providerThread === + providerThreadRuntimeKey(providerThread) + ); +} + function providerThreadLoadKey(input: { readonly runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime; readonly providerThread: Parameters< @@ -1636,7 +1649,7 @@ export const layerWithOptions = ( )) || // Closing now would skip the archive of a child whose parent has not taken its result. Option.isSome( - yield* Effect.findFirst(entry.idleThreadUnloads.keys(), (threadId) => + yield* Effect.findFirst(entry.idleThreadUnloads.values(), ({ threadId }) => delegatedChildArchive(threadId).pipe( Effect.map((child) => child === "awaiting_delivery"), ), @@ -1679,10 +1692,11 @@ export const layerWithOptions = ( // Closing skips the threads' own idle unloads, so archive delivered children first. yield* Effect.forEach( entry.idleThreadUnloads, - ([threadId, pending]) => + ([providerThreadId, pending]) => unloadIdleThread({ providerSessionId: input.providerSessionId, - threadId, + threadId: pending.threadId, + providerThreadId, generation: pending.generation, archiveOnly: true, }), @@ -2049,18 +2063,18 @@ export const layerWithOptions = ( const updateIdleThreadUnload = ( providerSessionId: ProviderSessionId, - threadId: ThreadId, + providerThreadId: ProviderThreadId, update: (current: IdleThreadUnload | undefined) => IdleThreadUnload | undefined, ) => Ref.modify(sessions, (current) => { const key = sessionKey(providerSessionId); const entry = current.get(key); if (entry === undefined) return [undefined, current] as const; - const previous = entry.idleThreadUnloads.get(threadId); + const previous = entry.idleThreadUnloads.get(providerThreadId); const next = update(previous); const idleThreadUnloads = new Map(entry.idleThreadUnloads); - if (next === undefined) idleThreadUnloads.delete(threadId); - else idleThreadUnloads.set(threadId, next); + if (next === undefined) idleThreadUnloads.delete(providerThreadId); + else idleThreadUnloads.set(providerThreadId, next); const updated = new Map(current); updated.set(key, { ...entry, idleThreadUnloads }); return [previous, updated] as const; @@ -2088,8 +2102,9 @@ export const layerWithOptions = ( } const previous = yield* updateIdleThreadUnload( input.providerSessionId, - input.threadId, + input.providerThread.id, (current) => ({ + threadId: input.threadId, providerThread: input.providerThread, generation: (current?.generation ?? 0) + 1, fiber: null, @@ -2103,20 +2118,27 @@ export const layerWithOptions = ( function* (providerSessionId: ProviderSessionId, providerThreadId: ProviderThreadId) { const entry = (yield* Ref.get(sessions)).get(sessionKey(providerSessionId)); if (entry === undefined || hasBusyTurn(entry, providerThreadId)) return; - const tracked = Array.from(entry.idleThreadUnloads).find( - ([, pending]) => pending.providerThread.id === providerThreadId, - ); - if (tracked === undefined) return; - const [threadId, pending] = tracked; + const pending = entry.idleThreadUnloads.get(providerThreadId); + if (pending === undefined) return; const generation = pending.generation + 1; const fiber = yield* Effect.sleep(Duration.millis(idleTimeoutMs)).pipe( - Effect.andThen(unloadIdleThread({ providerSessionId, threadId, generation })), + Effect.andThen( + unloadIdleThread({ + providerSessionId, + threadId: pending.threadId, + providerThreadId, + generation, + }), + ), Effect.forkIn(layerScope), ); - const previous = yield* updateIdleThreadUnload(providerSessionId, threadId, (current) => - current?.generation === pending.generation - ? { ...current, generation, fiber } - : current, + const previous = yield* updateIdleThreadUnload( + providerSessionId, + providerThreadId, + (current) => + current?.generation === pending.generation + ? { ...current, generation, fiber } + : current, ); yield* cancelIdleFiber( previous?.generation === pending.generation ? previous.fiber : fiber, @@ -2159,6 +2181,7 @@ export const layerWithOptions = ( function* (input: { readonly providerSessionId: ProviderSessionId; readonly threadId: ThreadId; + readonly providerThreadId: ProviderThreadId; readonly generation: number; /** Session release unloads only the threads it would archive, and never waits. */ readonly archiveOnly?: boolean; @@ -2168,7 +2191,7 @@ export const layerWithOptions = ( Effect.gen(function* () { const key = sessionKey(input.providerSessionId); const entry = (yield* Ref.get(sessions)).get(key); - const pending = entry?.idleThreadUnloads.get(input.threadId); + const pending = entry?.idleThreadUnloads.get(input.providerThreadId); const unloadThread = entry?.exposedRuntime.unloadThread; if ( entry === undefined || @@ -2193,29 +2216,39 @@ export const layerWithOptions = ( if (child === "awaiting_delivery") return "deferred" as const; const archive = child === "ready"; if (input.archiveOnly === true && !archive) return "skipped" as const; - const unloading = yield* Ref.modify(sessions, (current) => { - const latest = current.get(key); - if ( - latest?.runtime !== entry.runtime || - latest.idleThreadUnloads.get(input.threadId)?.generation !== input.generation - ) { - return [false, current] as const; - } - const loadedProviderThreadKeyByThread = new Map( - latest.loadedProviderThreadKeyByThread, - ); - loadedProviderThreadKeyByThread.delete(input.threadId); - const idleThreadUnloads = new Map(latest.idleThreadUnloads); - idleThreadUnloads.delete(input.threadId); - const updated = new Map(current); - updated.set(key, { - ...latest, - loadedProviderThreadKeyByThread, - idleThreadUnloads, - }); - return [true, updated] as const; - }); - if (!unloading) return "skipped" as const; + // null when skipped, otherwise whether this native thread is the app thread's loaded one. + const unloadsLoadedThread = yield* Ref.modify( + sessions, + (current): readonly [boolean | null, Map] => { + const latest = current.get(key); + if ( + latest?.runtime !== entry.runtime || + latest.idleThreadUnloads.get(input.providerThreadId)?.generation !== + input.generation + ) { + return [null, current]; + } + const idleThreadUnloads = new Map(latest.idleThreadUnloads); + idleThreadUnloads.delete(input.providerThreadId); + // A native thread a fresh session replaced is not what the app thread has loaded. + const isCurrent = isLoadKeyFor( + latest.loadedProviderThreadKeyByThread.get(input.threadId), + pending.providerThread, + ); + const loadedProviderThreadKeyByThread = new Map( + latest.loadedProviderThreadKeyByThread, + ); + if (isCurrent) loadedProviderThreadKeyByThread.delete(input.threadId); + const updated = new Map(current); + updated.set(key, { + ...latest, + loadedProviderThreadKeyByThread, + idleThreadUnloads, + }); + return [isCurrent, updated]; + }, + ); + if (unloadsLoadedThread === null) return "skipped" as const; const unload = (archiveThread: boolean) => unloadThread({ providerThread: pending.providerThread, @@ -2236,7 +2269,7 @@ export const layerWithOptions = ( Effect.tap(() => Ref.update(sessions, (current) => { const latest = current.get(key); - if (latest?.runtime !== entry.runtime) return current; + if (latest?.runtime !== entry.runtime || !unloadsLoadedThread) return current; const linkedEnvironmentsByThread = new Map(latest.linkedEnvironmentsByThread); linkedEnvironmentsByThread.delete(input.threadId); return new Map(current).set(key, { ...latest, linkedEnvironmentsByThread }); @@ -3502,7 +3535,7 @@ export const layerWithOptions = ( return [ Option.none<{ readonly entry: LiveSessionEntry; - readonly idleUnloadFiber: Fiber.Fiber | null; + readonly idleUnloadFibers: ReadonlyArray>; }>(), current, ] as const; @@ -3524,7 +3557,12 @@ export const layerWithOptions = ( })() : entry.mcpCredentialIdByThread; const idleThreadUnloads = new Map(entry.idleThreadUnloads); - idleThreadUnloads.delete(input.threadId); + const idleUnloadFibers: Array> = []; + for (const [providerThreadId, pending] of entry.idleThreadUnloads) { + if (pending.threadId !== input.threadId) continue; + idleThreadUnloads.delete(providerThreadId); + if (pending.fiber !== null) idleUnloadFibers.push(pending.fiber); + } const updatedEntry = { ...entry, attachedThreadIds, @@ -3538,13 +3576,15 @@ export const layerWithOptions = ( return [ Option.some({ entry: updatedEntry, - idleUnloadFiber: entry.idleThreadUnloads.get(input.threadId)?.fiber ?? null, + idleUnloadFibers, }), updated, ] as const; }); if (Option.isSome(detachResult)) { - yield* cancelIdleFiber(detachResult.value.idleUnloadFiber); + yield* Effect.forEach(detachResult.value.idleUnloadFibers, cancelIdleFiber, { + discard: true, + }); } const detached = Option.map(detachResult, (result) => result.entry); // Plain detaches preserve credentials held by live shared providers across workspace handoffs. From fe9c98c98fce20af75b2e7745554922a2e3714b2 Mon Sep 17 00:00:00 2001 From: Gabriel De Andrade <30420087+gabrielelpidio@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:07:34 -0400 Subject: [PATCH 212/324] feat: agents can report T3 Code problems when you turn feedback on (#35871) Co-authored-by: Claude Opus 5.5 Co-authored-by: maria-rcks --- .../settings/ThreadSettingsSections.tsx | 87 +- .../src/features/settings/settings-search.ts | 1 + .../features/threads/FeedbackRequestCard.tsx | 214 ++++ .../src/features/threads/ThreadFeed.tsx | 12 + apps/mobile/src/i18n/translations/de.json | 45 +- apps/mobile/src/i18n/translations/en.json | 45 +- apps/mobile/src/i18n/translations/es.json | 45 +- apps/mobile/src/i18n/translations/fr.json | 45 +- apps/mobile/src/i18n/translations/ja.json | 45 +- apps/mobile/src/i18n/translations/ko.json | 45 +- apps/mobile/src/i18n/translations/pt-BR.json | 45 +- apps/mobile/src/i18n/translations/ru.json | 45 +- apps/mobile/src/i18n/translations/sv.json | 45 +- apps/mobile/src/i18n/translations/zh.json | 45 +- apps/mobile/src/lib/threadActivity.ts | 14 + apps/server/src/auth/RpcAuthorization.test.ts | 7 + apps/server/src/auth/RpcAuthorization.ts | 1 + apps/server/src/binCli.ts | 2 + apps/server/src/cli/feedback.test.ts | 222 ++++ apps/server/src/cli/feedback.ts | 153 +++ apps/server/src/cli/thread.ts | 44 +- .../src/environment/ServerEnvironment.ts | 1 + apps/server/src/feedback/FeedbackList.ts | 62 + apps/server/src/feedback/FeedbackReport.ts | 222 ++++ .../src/feedback/FeedbackService.test.ts | 1042 +++++++++++++++++ apps/server/src/feedback/FeedbackService.ts | 221 ++++ apps/server/src/feedback/FeedbackStore.ts | 371 ++++++ apps/server/src/feedback/FeedbackTrace.ts | 157 +++ .../server/src/feedback/scrubFeedback.test.ts | 225 ++++ apps/server/src/feedback/scrubFeedback.ts | 130 ++ .../src/guest/GuestShareService.test.ts | 4 +- apps/server/src/mcp/AcpMcpStdioBridge.test.ts | 27 + apps/server/src/mcp/AcpMcpStdioBridge.ts | 13 +- apps/server/src/mcp/McpHttpServer.test.ts | 133 +++ apps/server/src/mcp/McpHttpServer.ts | 44 +- apps/server/src/mcp/McpInvocationContext.ts | 10 + apps/server/src/mcp/OrchestratorMcpService.ts | 2 + apps/server/src/mcp/toolkits/core.test.ts | 6 +- .../mcp/toolkits/environment/handlers.test.ts | 12 + .../src/mcp/toolkits/feedback/handlers.ts | 47 + .../server/src/mcp/toolkits/feedback/tools.ts | 34 + .../src/observability/RpcInstrumentation.ts | 1 + .../Adapters/ClaudeAdapterV2.test.ts | 39 +- .../Adapters/ClaudeAdapterV2.ts | 5 + .../Adapters/CodexAdapterV2.ts | 9 +- .../src/orchestration-v2/Orchestrator.ts | 96 ++ .../ProviderRuntimeRecoveryService.test.ts | 217 ++-- .../ProviderRuntimeRecoveryService.ts | 2 + .../ProviderSessionManager.ts | 14 +- .../SteeringCompletion.integration.test.ts | 36 + .../src/orchestration-v2/runtimeLayer.ts | 6 + apps/server/src/persistence/Migrations.ts | 2 + .../Migrations/108_AgentFeedback.ts | 15 + .../reconcileV2PreviewMigration.test.ts | 2 + .../src/provider/AgentContextBudget.test.ts | 6 + .../src/provider/CodexChatGptAuth.test.ts | 1 + .../provider/CodexDeveloperInstructions.ts | 2 + .../src/provider/agentContextBudget.json | 2 +- .../src/serverRuntimeStartup.autoPull.test.ts | 2 +- apps/server/src/serverSettings.test.ts | 16 + apps/server/src/serverSettings.ts | 86 +- apps/server/src/telemetry/AnalyticsService.ts | 8 +- .../telemetry/ProviderUsageAnalytics.test.ts | 5 +- apps/server/src/ws.test.ts | 2 + apps/server/src/ws.ts | 3 + .../components/chat/FeedbackRequestCard.tsx | 218 ++++ .../components/chat/TimelineV2EventRow.tsx | 10 + .../components/settings/LabsSettingsPanel.tsx | 81 +- .../settings/settingsSearch.test.ts | 1 + .../src/components/settings/settingsSearch.ts | 14 + .../useAvailableSettingsSearchItems.ts | 7 + apps/web/src/i18n/translations/de.json | 45 +- apps/web/src/i18n/translations/en.json | 45 +- apps/web/src/i18n/translations/es.json | 45 +- apps/web/src/i18n/translations/fr.json | 45 +- apps/web/src/i18n/translations/ja.json | 45 +- apps/web/src/i18n/translations/ko.json | 45 +- apps/web/src/i18n/translations/pt-BR.json | 45 +- apps/web/src/i18n/translations/ru.json | 45 +- apps/web/src/i18n/translations/sv.json | 45 +- apps/web/src/i18n/translations/zh.json | 45 +- apps/web/src/routes/_chat.settings.tsx | 31 +- apps/web/src/session-logic.ts | 2 + docs/internals/product-analytics.md | 20 +- docs/user/telemetry.md | 51 +- .../mcp-tool-use/cases/agent-feedback.ndjson | 18 + evals/mcp-tool-use/run.ts | 95 +- packages/client-runtime/package.json | 4 + .../src/feedbackRequest.test.ts | 79 ++ .../client-runtime/src/feedbackRequest.ts | 145 +++ .../src/state/commandPermissions.test.ts | 15 + packages/client-runtime/src/state/server.ts | 9 + packages/contracts/src/agentFeedback.ts | 84 ++ .../contracts/src/clientRpcPermissions.ts | 2 + packages/contracts/src/environment.ts | 2 + packages/contracts/src/index.ts | 1 + packages/contracts/src/orchestrationV2.ts | 38 + packages/contracts/src/rpc.ts | 8 + packages/contracts/src/settings.ts | 8 + packages/provider-acp/src/server/adapter.ts | 1 + .../src/server/ProviderAdapter.ts | 2 + .../src/server/runtimeInstructions.test.ts | 32 + .../src/server/runtimeInstructions.ts | 22 +- .../provider-cursor/src/server/adapter.ts | 3 +- .../provider-muse/src/server/adapter.test.ts | 15 +- packages/provider-muse/src/server/adapter.ts | 3 + .../provider-opencode/src/server/adapter.ts | 5 + .../src/server/v2/adapter.ts | 1 + 108 files changed, 5727 insertions(+), 297 deletions(-) create mode 100644 apps/mobile/src/features/threads/FeedbackRequestCard.tsx create mode 100644 apps/server/src/cli/feedback.test.ts create mode 100644 apps/server/src/cli/feedback.ts create mode 100644 apps/server/src/feedback/FeedbackList.ts create mode 100644 apps/server/src/feedback/FeedbackReport.ts create mode 100644 apps/server/src/feedback/FeedbackService.test.ts create mode 100644 apps/server/src/feedback/FeedbackService.ts create mode 100644 apps/server/src/feedback/FeedbackStore.ts create mode 100644 apps/server/src/feedback/FeedbackTrace.ts create mode 100644 apps/server/src/feedback/scrubFeedback.test.ts create mode 100644 apps/server/src/feedback/scrubFeedback.ts create mode 100644 apps/server/src/mcp/toolkits/feedback/handlers.ts create mode 100644 apps/server/src/mcp/toolkits/feedback/tools.ts create mode 100644 apps/server/src/persistence/Migrations/108_AgentFeedback.ts create mode 100644 apps/web/src/components/chat/FeedbackRequestCard.tsx create mode 100644 evals/mcp-tool-use/cases/agent-feedback.ndjson create mode 100644 packages/client-runtime/src/feedbackRequest.test.ts create mode 100644 packages/client-runtime/src/feedbackRequest.ts create mode 100644 packages/contracts/src/agentFeedback.ts diff --git a/apps/mobile/src/features/settings/ThreadSettingsSections.tsx b/apps/mobile/src/features/settings/ThreadSettingsSections.tsx index 55c45eae31f01..f2ce0ca47cb75 100644 --- a/apps/mobile/src/features/settings/ThreadSettingsSections.tsx +++ b/apps/mobile/src/features/settings/ThreadSettingsSections.tsx @@ -1,6 +1,7 @@ -import { T, useGT } from "gt-react-native"; +import { T, useGT, msg, useMessages } from "gt-react-native"; import { Button } from "../../components/ui/Button"; import { + type AgentFeedbackMode, AuthSettingsWriteScope, isManagedSettingPath, type ServerSettingsPatch, @@ -21,6 +22,7 @@ import { useEnvironments } from "../../state/environments"; import { mobilePreferencesAtom, saveMobilePreferences } from "../../state/preferences"; import { serverEnvironment } from "../../state/server"; import { useAtomCommand } from "../../state/use-atom-command"; +import { ListChoiceRow as SettingsChoiceRow } from "../../components/ui/ListChoiceRow"; import { SettingsSection } from "./components/SettingsSection"; import { SettingsSwitchRow } from "./components/SettingsSwitchRow"; import { SettingsScreen } from "./components/SettingsScreen"; @@ -63,6 +65,7 @@ export function SettingsLabsRouteScreen() { "On a Mac, clone new worktrees from a checkout cached in the T3 home folder instead of writing every file. Uses Git’s normal checkout when it can’t. Turning it off deletes the cache.", )} /> + ); @@ -263,6 +266,88 @@ export function NewThreadSettingsSection() { type MachineBetaSetting = "linkedEnvironmentsEnabled" | "fastWorktreeCheckout"; +const AGENT_FEEDBACK_CHOICES: ReadonlyArray<{ + readonly mode: AgentFeedbackMode; + readonly label: string; + readonly description: string; +}> = [ + { mode: "off", label: msg("Off"), description: msg("Agents send no feedback to the T3 team.") }, + { + mode: "on-request", + label: msg("When I ask"), + description: msg("When you ask, you see a short report and send it if you approve."), + }, + { + mode: "auto", + label: msg("Automatic"), + description: msg("Agents also report T3 Code problems they hit on their own."), + }, +]; + +/** One choice list per connected machine that offers it, since each machine's own setting decides. */ +function AgentFeedbackSection() { + const gt = useGT(); + const m = useMessages(); + const { environments } = useEnvironments(); + const supported = environments.filter( + (environment) => + environment.connection.phase === "connected" && + environment.serverConfig?.environment.capabilities.agentFeedback === true, + ); + const writable = useEnvironmentsWithScope(supported, AuthSettingsWriteScope); + const updateSettings = useAtomCommand(serverEnvironment.updateSettings, { + label: "agentFeedback beta update", + reportFailure: true, + }); + if (supported.length === 0) return null; + return ( + + {supported.map((environment) => { + const policy = environment.serverConfig?.managedPolicy; + const managed = isManagedSettingPath(policy, "agentFeedback"); + const mode = environment.serverConfig?.settings.agentFeedback.mode; + return ( + + {AGENT_FEEDBACK_CHOICES.map((choice, index) => ( + 0} + disabled={managed || !writable.has(environment.environmentId)} + onPress={() => + void updateSettings({ + environmentId: environment.environmentId, + input: { patch: { agentFeedback: { mode: choice.mode } } }, + }) + } + /> + ))} + + ); + })} + + + Reports go to the T3 team. A report you ask for is shown to you first in a card, with an + outline of recent turns. Turn on Include the conversation there to add the messages of the + turns the report is about. + + + + ); +} + /** One switch per connected machine that offers the beta, since each machine's own setting decides. */ function MachineBetaSection({ title, diff --git a/apps/mobile/src/features/settings/settings-search.ts b/apps/mobile/src/features/settings/settings-search.ts index 9b8334641290d..6814475323db0 100644 --- a/apps/mobile/src/features/settings/settings-search.ts +++ b/apps/mobile/src/features/settings/settings-search.ts @@ -159,6 +159,7 @@ const SETTINGS_SEARCH_TERMS = { msg("link machine", { $context: "settings search keyword" }), msg("fast worktree checkout", { $context: "settings search keyword" }), msg("clone cache", { $context: "settings search keyword" }), + msg("agent feedback", { $context: "settings search keyword" }), ], SettingsEnvironmentMaintenance: [ msg("updates", { $context: "settings search keyword" }), diff --git a/apps/mobile/src/features/threads/FeedbackRequestCard.tsx b/apps/mobile/src/features/threads/FeedbackRequestCard.tsx new file mode 100644 index 0000000000000..5475e15d94e34 --- /dev/null +++ b/apps/mobile/src/features/threads/FeedbackRequestCard.tsx @@ -0,0 +1,214 @@ +import { T, msg, useMessages, useGT } from "gt-react-native"; +import { pipe } from "effect/Function"; +import { + feedbackCardPreview, + feedbackConversationHint, + feedbackPreviewFields, + feedbackRequestDisplay, + feedbackRequestFailureMessage, + type FeedbackRequestItem, + feedbackTraceLines, + feedbackTraceSummary, +} from "@t3tools/client-runtime/feedback-request"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; +import type { + AgentFeedbackPreview, + EnvironmentId, + OrchestrationV2ProjectedTurnItem, +} from "@t3tools/contracts"; +import { useAtomValue } from "@effect/atom-react"; +import { useRef, useState } from "react"; +import { Pressable, View, type ColorValue } from "react-native"; + +import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol"; +import { AppText as Text } from "../../components/ui/AppText"; +import { Button } from "../../components/ui/Button"; +import { ThemedSwitch } from "../../components/ui/ThemedSwitch"; +import { serverEnvironment } from "../../state/server"; +import { useAtomCommand } from "../../state/use-atom-command"; + +const TITLE = msg("Feedback for the T3 team"); +const LOCK_SYMBOL: AppSymbolName = { ios: "lock", android: "lock" }; + +export function FeedbackRequestCard(props: { + readonly environmentId: EnvironmentId; + readonly projectedItem: OrchestrationV2ProjectedTurnItem; + readonly iconColor: ColorValue; +}) { + const m = useMessages(); + const { item, visibility } = props.projectedItem; + const [open, setOpen] = useState(false); + if (item.type !== "feedback_request") return null; + const display = feedbackRequestDisplay(item, visibility, m); + if (display.kind === "pending") { + return ; + } + const icon: AppSymbolName = + display.kind === "pending-elsewhere" + ? LOCK_SYMBOL + : display.outcome === "sent" + ? "checkmark" + : "minus"; + return ( + + setOpen((value) => !value)} + className="min-h-9 flex-row items-center gap-2" + > + + + {m(TITLE)} · {display.label} + + + {open ? : null} + + ); +} + +function PendingFeedbackRequest(props: { + readonly environmentId: EnvironmentId; + readonly item: FeedbackRequestItem; +}) { + const m = useMessages(); + const gt = useGT(); + const answer = useAtomCommand(serverEnvironment.answerFeedbackRequest, { + label: "answer feedback request", + reportFailure: false, + }); + const canAnswer = useAtomValue( + serverEnvironment.answerFeedbackRequest.permissionAtom(props.environmentId), + ); + const [submitting, setSubmitting] = useState(false); + const [error, setError] = useState(null); + const [includeConversation, setIncludeConversation] = useState(false); + // Two taps can land before a re-render; this guard is synchronous. + const inFlight = useRef(false); + + const send = async (reply: "send" | "decline") => { + if (inFlight.current) return; + inFlight.current = true; + setSubmitting(true); + setError(null); + const result = await answer({ + environmentId: props.environmentId, + input: { + threadId: props.item.threadId, + turnItemId: props.item.id, + answer: reply, + includeConversation, + }, + }).finally(() => { + inFlight.current = false; + setSubmitting(false); + }); + if (result._tag === "Success" || isAtomCommandInterrupted(result)) return; + pipe( + squashAtomCommandFailure(result), + (failure) => feedbackRequestFailureMessage(failure, m), + setError, + ); + }; + + return ( + + + + Send this report to the T3 team? + + + This is everything that leaves your machine. Nothing is sent unless you tap Send. + + + {props.item.conversationTrace !== undefined ? ( + + + + Include the conversation + + + {feedbackConversationHint(props.item.conversationTrace, m)} + + + + + ) : null} + + {error !== null ? ( + + {error} + + ) : !canAnswer ? ( + + Only someone who can run agents on this machine can send or decline it. + + ) : null} + + +
    + + ); +} + +function FeedbackPreview({ preview }: { readonly preview: AgentFeedbackPreview }) { + const m = useMessages(); + + return ( +
    +
    + {feedbackPreviewFields(preview, m).map((field) => ( +
    +
    {field.label}
    +
    {field.value}
    +
    + ))} +
    + {preview.trace !== null ? ( + + + + {feedbackTraceSummary(preview.trace, m)} + + +
      + {feedbackTraceLines(preview.trace, m).map((entry) => ( +
    1. + {entry.line} + {entry.text !== undefined ? ( +

      + {entry.text} +

      + ) : null} +
    2. + ))} +
    +
    +
    + ) : null} +
    + ); +} diff --git a/apps/web/src/components/chat/TimelineV2EventRow.tsx b/apps/web/src/components/chat/TimelineV2EventRow.tsx index 5ea743025444f..588bcaa3b4266 100644 --- a/apps/web/src/components/chat/TimelineV2EventRow.tsx +++ b/apps/web/src/components/chat/TimelineV2EventRow.tsx @@ -12,6 +12,7 @@ import { ChevronDownIcon } from "lucide-react"; import { cn } from "~/lib/utils"; import { Collapsible, CollapsibleTrigger, CollapsiblePanel } from "../ui/collapsible"; import { EnvironmentSubagentAvatar, SubagentElapsed, V2LifecycleRow } from "./V2LifecycleRow"; +import { FeedbackRequestCard } from "./FeedbackRequestCard"; import { LinkRequestCard } from "./LinkRequestCard"; import { SecretRequestCard } from "./SecretRequestCard"; import { TimelineRowCtx, type TimelineRow } from "./timelineRowContext"; @@ -32,6 +33,15 @@ export function V2EventTimelineRow({ row }: { row: Extract ); } + if (item.type === "feedback_request") { + return ( + + ); + } if (item.type === "link_request") { return ( + ); @@ -291,3 +299,74 @@ function FastWorktreeCheckoutRow() { /> ); } + +/** Shows only when every machine in scope honors it; older servers drop the setting. */ +const AGENT_FEEDBACK_MODES = AgentFeedbackMode.literals; +const AGENT_FEEDBACK_MODE_LABELS: Record = { + off: msg("Off"), + "on-request": msg("When I ask"), + auto: msg("Automatic"), +}; +const AGENT_FEEDBACK_MODE_DESCRIPTIONS: Record = { + off: msg("Agents send no feedback to the T3 team."), + "on-request": msg( + "When you ask, agents show you a short report about T3 Code and send it to the T3 team if you approve.", + ), + auto: msg( + "Agents also report T3 Code problems they hit on their own, such as a T3 tool that failed.", + ), +}; + +function AgentFeedbackRow() { + const searchableSetting = useSearchableSetting(); + const { scope, connectedEnvironments } = useSettingsScope(); + const settings = useScopedSettings(); + const updateSettings = useUpdateScopedSettings(); + const gt = useGT(); + const m = useMessages(); + const mixed = useScopedSettingsMixed(["agentFeedback"]); + if ( + scope.kind === "project" || + scope.kind === "checkout" || + connectedEnvironments.length === 0 || + connectedEnvironments.some( + (environment) => environment.serverConfig?.environment.capabilities.agentFeedback !== true, + ) + ) + return null; + return ( + { + if (mode !== null) updateSettings({ agentFeedback: { mode } }); + }} + > + + + {(mode: AgentFeedbackMode | null) => + mode === null ? gt("Mixed") : m(AGENT_FEEDBACK_MODE_LABELS[mode]) + } + + + + {AGENT_FEEDBACK_MODES.map((mode) => ( + + {m(AGENT_FEEDBACK_MODE_LABELS[mode])} + + ))} + + + } + /> + ); +} diff --git a/apps/web/src/components/settings/settingsSearch.test.ts b/apps/web/src/components/settings/settingsSearch.test.ts index 4bc2c2a6317e5..3249b67624234 100644 --- a/apps/web/src/components/settings/settingsSearch.test.ts +++ b/apps/web/src/components/settings/settingsSearch.test.ts @@ -168,6 +168,7 @@ describe("searchSettings", () => { "auto-settle-merged-threads", "days-before-auto-settle", "linked-environments", + "agent-feedback", ]); expect(available.map((item) => item.id).filter((id) => gatedIds.has(id))).toEqual([]); }); diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index 4252fccc9c7d0..4f57b8d730842 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -72,6 +72,7 @@ export interface SettingsSearchItem { readonly managedTunnelOnly?: boolean; readonly peerLinksOnly?: boolean; readonly fastWorktreeCheckoutOnly?: boolean; + readonly agentFeedbackOnly?: boolean; readonly textGeneratorsOnly?: boolean; readonly secondary?: boolean; readonly requiresThreadAutoSettlement?: boolean; @@ -88,6 +89,7 @@ export interface SettingsSearchAvailability { readonly managedTunnelActive?: boolean; readonly hasPeerLinkHost?: boolean; readonly hasFastWorktreeCheckoutEnvironment?: boolean; + readonly hasAgentFeedbackEnvironment?: boolean; /** An environment without a provider allow-list, which hides text generators. */ readonly hasTextGeneratorsEnvironment?: boolean; readonly hasPrimaryEnvironment?: boolean; @@ -998,6 +1000,16 @@ export const SETTINGS_SEARCH_ITEMS = [ to: "/settings/maintenance", searchTerms: [msg("logs traces processes resource history failures spans cpu memory")], }, + { + id: "agent-feedback", + title: msg("Agent feedback"), + to: "/settings/labs", + scope: "environment-defaults", + agentFeedbackOnly: true, + searchTerms: [ + msg("report bug problem t3 team send feedback agents tools automatic when i ask"), + ], + }, { id: "open-source-licenses", title: msg("Open source licenses"), @@ -1564,6 +1576,7 @@ export function getSettingsSearchTargetScope(targetId: string) { title: item.title, scope: item.scope ?? SETTINGS_CATEGORY_SCOPES[item.to], ...(item.requiresThreadAutoSettlement ? { requiresThreadAutoSettlement: true } : {}), + ...(item.agentFeedbackOnly ? { agentFeedbackOnly: true } : {}), } : null; } @@ -1656,6 +1669,7 @@ export function filterAvailableSettingsSearchItems( (!item.peerLinksOnly || availability.hasPeerLinkHost === true) && (!item.fastWorktreeCheckoutOnly || availability.hasFastWorktreeCheckoutEnvironment === true) && + (!item.agentFeedbackOnly || availability.hasAgentFeedbackEnvironment === true) && (!item.textGeneratorsOnly || availability.hasTextGeneratorsEnvironment === true) && (!item.secretProvidersOnly || availability.hasSecretProvidersEnvironment === true), ); diff --git a/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts b/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts index beb5e3c85c52c..279dbd39d51e3 100644 --- a/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts +++ b/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts @@ -45,6 +45,12 @@ export function useAvailableSettingsSearchItems() { environment.connection.phase === "connected" && environment.serverConfig?.environment.capabilities.fastWorktreeCheckout === true, ) === true; + const hasAgentFeedbackEnvironment = + environments.some( + (environment) => + environment.connection.phase === "connected" && + environment.serverConfig?.environment.capabilities.agentFeedback === true, + ) === true; const hasTextGeneratorsEnvironment = environments.some( (environment) => @@ -83,6 +89,7 @@ export function useAvailableSettingsSearchItems() { managedTunnelActive, hasPeerLinkHost, hasFastWorktreeCheckoutEnvironment, + hasAgentFeedbackEnvironment, hasTextGeneratorsEnvironment, hasPrimaryEnvironment: primaryEnvironmentId !== null, hasSecretProvidersEnvironment, diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 0b3ce24ca4fe3..16f3d83c8b2e6 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -52,6 +52,26 @@ "eb0f60ef4f92ab7d": "Installiere {fj} 0.6 oder neuer von {fjUrl} und führe {fjLogin} aus, oder installiere {tea} 0.16 oder neuer von {teaUrl} und führe {teaLogin} für jeden Forgejo- oder Gitea-Server aus.", "d026a85e2e50e675": "Installiere die GitCafe CLI mit {install} und führe dann {login} aus, speichere ein Token in den Einstellungen oder setze {variable} auf dem Server.", "22d3c0c48a34b5b3": "Installiere die TanStack Source CLI mit {install} und führe dann {login} aus, speichere ein Token in den Einstellungen oder setze {variable} auf dem Server.", + "756c80ad262ef315": "Wartet im ursprünglichen Thread", + "d8df14f9905f38eb": "Gesendet", + "e7c59185f8ab3987": "Nicht gesendet", + "b54ddec9084fa955": "Ohne Senden geschlossen", + "fbaa7ab5da716e50": "Fehler", + "01bac997ea55272e": "Unverständlich", + "0f53bc8f74dfe56a": "Fehlende Funktion", + "055560f307e15e30": "Falsche Dokumentation", + "78344b60f407928e": "Sonstiges", + "f653846a95cd6e8f": "Art", + "f41ea186c275b56e": "Info", + "2f6e4f7cd364da73": "Erwartet", + "9d11c93d4035de3e": "Tatsächlich passiert", + "c87d0595693704f9": "Stattdessen getan", + "d7a4ea6ce5af44e0": "{speaker} · {count} Zeichen", + "f5114fb9c40fd929": "Du", + "cd03eb1b84271c02": "Agent", + "bfe1a60f3f9c60fb": "Runde {turn} · {what}", + "dfdaa6255a416140": "Übersicht über {turns, plural, one {{turns} letzte Runde} other {{turns} letzte Runden}}, {textTurns, plural, =0 {ohne Nachrichtentext} one {mit dem Nachrichtentext der letzten Runde} other {mit den Nachrichtentexten der letzten {textTurns} Runden}}{truncated, select, yes {, passend gekürzt} other {}}", + "afac52a5cc2dc801": "Deine Antwort konnte nicht gesendet werden. Versuche es erneut.", "79d776428f4d0650": "Die Datei konnte nicht geladen werden. Verbinde dich erneut und versuch es noch einmal.", "3ea34cbb1ca5ba9b": "Vorschau abgebrochen.", "7c0af279ecb3da3a": "Streamende Dateivorschauen sind in dieser Laufzeitumgebung nicht verfügbar.", @@ -3582,6 +3602,14 @@ "c53bc5a4b0314342": "Nächstes Medium", "2950b1424a3cddf5": "Verbinde dich erneut mit dieser Umgebung und öffne das Medium noch einmal.", "ef638bf1479a5461": "Die Umgebung hat eine ungültige Medien-URL zurückgegeben.", + "3ccfbf7e86868c35": "Feedback für das T3-Team", + "4e0710d19dfc2e7e": "Diesen Bericht an das T3-Team senden?", + "87d0ae0723ba75d1": "Das ist alles, was deinen Rechner verlässt. Erst wenn du auf Senden klickst, wird etwas gesendet.", + "bf19826f81484328": "Unterhaltung mitsenden", + "260c6b45f52d2f27": "Fügt den Text deiner Nachrichten und der Antworten des Agenten aus {textTurns, plural, one {der letzten Runde} other {den letzten {textTurns} Runden}} hinzu.", + "ddb7e6f8ce99e657": "Nur wer auf diesem Rechner Agenten ausführen kann, kann den Bericht senden oder ablehnen.", + "03c1eb603c112f47": "Nicht senden", + "653405e4ed498d9f": "Senden", "262955d6eb632f9b": "Die Zwischenablage-API ist beim Kopieren des Gast-Links nicht verfügbar.", "f1a4f2b04cdbb4ef": "Der Gast-Link konnte nicht in die Zwischenablage kopiert werden.", "cf3490a604e44d31": "Gastlink konnte nicht erstellt werden.", @@ -3602,7 +3630,6 @@ "abd89e9eefedf11b": "Fertig", "18d166056c1ab6ff": "Freigabe beenden", "7a2d510eac9e4587": "Gastlink abgelaufen", - "653405e4ed498d9f": "Senden", "21888e302219891d": "Vergrößerte Vorschau von {title}", "419719298a7acaea": "Verkleinern", "ed8d5db95359cff4": "Zoom zurücksetzen", @@ -5806,7 +5833,6 @@ "0061fff77e36bd4f": "Der Server ist nicht erreichbar.", "04dfdd46e3dd4a2e": "Etwas ist schiefgelaufen. Versuche es erneut.", "084bb2d8127a508d": "Gesendet", - "e7c59185f8ab3987": "Nicht gesendet", "77c01a15bd36d17c": "Dieser Link ist abgelaufen oder ungültig", "e0e736810f3cbef2": "Bitte den Besitzer um einen neuen Link. Jeder Link funktioniert in einem Browser.", "c3c53aa46f7330e5": "Dieser Link ist abgelaufen", @@ -8831,6 +8857,12 @@ "d3866ead082d14e5": "Tastenkürzel hinzufügen", "d4345c90894a3220": "keybindings.json öffnen", "e56a8d51219efaa0": "Keine Tastenkürzel entsprechen deiner Suche.", + "90a258fff61fd77e": "Aus", + "4060244a7079a0d2": "Wenn ich darum bitte", + "e88c9d8769544731": "Automatisch", + "f29d1dade4dde8aa": "Agenten senden kein Feedback an das T3-Team.", + "93c4c53562d30a98": "Wenn du darum bittest, zeigen Agenten dir einen kurzen Bericht über T3 Code und senden ihn mit deiner Zustimmung an das T3-Team.", + "cd9ee803e8727017": "Agenten melden auch selbstständig Probleme mit T3 Code, auf die sie stoßen, etwa ein fehlgeschlagenes T3-Tool.", "45fa271ea0e1ac8e": "Beta", "3a678332fc7142f7": "Threads in der Seitenleiste in Projektordnern gruppieren. Angeheftete Threads bleiben oben, Zurückgestellte und Erledigte bleiben unter den Ordnern.", "e4e91d155cb6a9b4": "Schlichte Seitenleiste (nach Projekt gruppieren)", @@ -8844,6 +8876,9 @@ "298c7150a7621c80": "Simlock-Geräte-Hosts", "67937aa49179285e": "Auf einem Mac neue Worktrees aus einem im T3-Home-Ordner zwischengespeicherten Checkout klonen, statt jede Datei zu schreiben. Verwendet den normalen Git-Checkout, wenn das nicht geht. Beim Ausschalten wird der Cache gelöscht.", "f9904f78d3003f58": "Schneller Worktree-Checkout", + "9c2f647882522302": "Die ausgewählten Rechner verwenden unterschiedliche Modi für Agenten-Feedback.", + "31bbf7bf8c0a5279": "Agenten-Feedback", + "d52b3d6bf9f2a013": "Gemischt", "ec7623deed751c05": [ "Teile einen Thread mit einem Gast, der ihn live im Browser verfolgt und Nachrichten sendet, die du genehmigst. Erfordert T3 Connect: Melde dich an und verknüpfe diesen Rechner unter", " ", @@ -9158,7 +9193,6 @@ "0b4779a1825c85bc": "Der gemeinsame Name dieser Projektgruppe in der Seitenleiste und in Thread-Listen.", "f68cbda4df83d739": "Projektname auf Standard zurücksetzen", "56e37b85027e8431": "Projektsymbol", - "e88c9d8769544731": "Automatisch", "c99736317da5b1fa": "Projektsymbol auf Standard zurücksetzen", "6afaa3e3739dc570": "Projektsymbol auswählen", "51651ce45d481a20": "Datei für Projektsymbol auswählen", @@ -10133,7 +10167,6 @@ "16bdc70b858c223f": "Proaktive Panels auf Standard zurücksetzen", "c5424f09d77138ff": "Wann ein inaktiver Claude-Thread über 200.000 Tokens komprimiert wird: nach deiner Rückkehr, kurz bevor sein Prompt-Cache abläuft, oder nie. Jeder Claude-Anbieter kann das überschreiben.", "3e99c5c14f4939c8": "Inaktive Threads komprimieren auf Standard zurücksetzen", - "d52b3d6bf9f2a013": "Gemischt", "cd72fe451ba0d6aa": "Neue Projekte", "394c3bd0a1782c8e": "Leer lassen, um „~/“ zu verwenden, wenn sich der Dialog „Projekt hinzufügen“ öffnet.", "f9b912a818bd869d": "Basisverzeichnis für neue Projekte auf Standard zurücksetzen", @@ -11035,7 +11068,6 @@ "4a237f41ce592b7f": "Die Worktrees dieses Projekts behalten, bis du sie manuell löschst.", "00b8ffd8ea6e6a93": "Diese Regeln für dieses Projekt verwenden.", "72c279824d15a999": "Die Worktree-Bereinigungseinstellungen jedes Rechners verwenden.", - "90a258fff61fd77e": "Aus", "b5702d0b64866b08": "Benutzerdefiniert", "c009c901f3eefe78": "Worktrees gelöschter Threads löschen", "431c7cd6d50102b7": "Ungenutzte Worktrees entfernen, wenn aktive oder archivierte Threads gelöscht werden. Worktrees mit lokalen Änderungen bleiben erhalten.", @@ -11732,7 +11764,6 @@ "4c70e3e7b3e6c493": "Geheimnisse", "79b768229c9ef672": "Wartung", "54b188d65247e42f": "Labs", - "f41ea186c275b56e": "Info", "af4b7734da1d5ce7": "Spracheingabe", "4ec62c39ca3192bf": "Versionskontrolle & Issues", "f2bf529f85e05494": "Freigabe & Zugriff", @@ -11858,6 +11889,7 @@ "901a823214edc8c4": "telemetrie analyse nutzungsdaten tracking rechtliches deaktivieren", "82136480255a5106": "OTel OTLP telemetrie export endpunkte logs traces metriken Grafana", "659d081051faf7ff": "logs traces prozesse ressourcenverlauf fehler spans cpu speicher", + "5eaeacfa9f82051a": "bericht fehler problem t3 team senden feedback agenten tools automatisch wenn ich darum bitte", "f537f91e1ee41d47": "tastenkürzel hotkeys befehle tastenzuweisungen json", "1ba01e7ceed64b95": "fenster aufnahme bildschirmfoto", "279b1cceb779ff38": "App-Text einbeziehen", @@ -12327,7 +12359,6 @@ "0bd41ff995d36a66": "Cache-Lesen", "3f0dfe0cb15a3272": "Cache-Schreiben", "1c9d860be42b1c02": "Ausgabe", - "78344b60f407928e": "Sonstiges", "684e516076de81fe": "Standard", "3bbcc1b826fef537": "Schnell", "66796576034c18ea": "Ultraschnell", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 9f369e8bd102e..c4534c680b95f 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -52,6 +52,26 @@ "eb0f60ef4f92ab7d": "Install {fj} 0.6 or later from {fjUrl} and run {fjLogin}, or install {tea} 0.16 or later from {teaUrl} and run {teaLogin} for each Forgejo or Gitea server.", "d026a85e2e50e675": "Install the GitCafe CLI with {install}, then run {login}, save a token in Settings, or set {variable} on the server.", "22d3c0c48a34b5b3": "Install the TanStack Source CLI with {install}, then run {login}, save a token in Settings, or set {variable} on the server.", + "756c80ad262ef315": "Waiting in the original thread", + "d8df14f9905f38eb": "Sent", + "e7c59185f8ab3987": "Not sent", + "b54ddec9084fa955": "Closed without sending", + "fbaa7ab5da716e50": "Bug", + "01bac997ea55272e": "Confusing", + "0f53bc8f74dfe56a": "Missing capability", + "055560f307e15e30": "Wrong docs", + "78344b60f407928e": "Other", + "f653846a95cd6e8f": "Kind", + "f41ea186c275b56e": "About", + "2f6e4f7cd364da73": "Expected", + "9d11c93d4035de3e": "Happened", + "c87d0595693704f9": "Did instead", + "d7a4ea6ce5af44e0": "{speaker} · {count} characters", + "f5114fb9c40fd929": "You", + "cd03eb1b84271c02": "Agent", + "bfe1a60f3f9c60fb": "Turn {turn} · {what}", + "dfdaa6255a416140": "Outline of {turns, plural, one {{turns} recent turn} other {{turns} recent turns}}, {textTurns, plural, =0 {no message text} one {message text of the last turn} other {message text of the last {textTurns} turns}}{truncated, select, yes {, shortened to fit} other {}}", + "afac52a5cc2dc801": "Could not send your answer. Try again.", "79d776428f4d0650": "The file could not be loaded. Reconnect and try again.", "3ea34cbb1ca5ba9b": "Preview cancelled.", "7c0af279ecb3da3a": "Streaming file previews are unavailable in this runtime.", @@ -3581,6 +3601,14 @@ "c53bc5a4b0314342": "Next media", "2950b1424a3cddf5": "Reconnect to this environment and open the media again.", "ef638bf1479a5461": "The environment returned an invalid media URL.", + "3ccfbf7e86868c35": "Feedback for the T3 team", + "4e0710d19dfc2e7e": "Send this report to the T3 team?", + "87d0ae0723ba75d1": "This is everything that leaves your machine. Nothing is sent unless you press Send.", + "bf19826f81484328": "Include the conversation", + "260c6b45f52d2f27": "Adds the text of your messages and the agent's replies in the last {textTurns, plural, one {turn} other {{textTurns} turns}}.", + "ddb7e6f8ce99e657": "Only someone who can run agents on this machine can send or decline it.", + "03c1eb603c112f47": "Don't send", + "653405e4ed498d9f": "Send", "262955d6eb632f9b": "Clipboard API is unavailable while copying guest link.", "f1a4f2b04cdbb4ef": "Failed to copy guest link to the clipboard.", "cf3490a604e44d31": "Could not create a guest link.", @@ -3601,7 +3629,6 @@ "abd89e9eefedf11b": "Done", "18d166056c1ab6ff": "Stop sharing", "7a2d510eac9e4587": "Guest link expired", - "653405e4ed498d9f": "Send", "21888e302219891d": "Expanded {title} preview", "419719298a7acaea": "Zoom out", "ed8d5db95359cff4": "Reset zoom", @@ -5807,7 +5834,6 @@ "0061fff77e36bd4f": "Could not reach the server.", "04dfdd46e3dd4a2e": "Something went wrong. Try again.", "084bb2d8127a508d": "Sent", - "e7c59185f8ab3987": "Not sent", "77c01a15bd36d17c": "This link has ended or is not valid", "e0e736810f3cbef2": "Ask the owner for a new link. Each link works in one browser.", "c3c53aa46f7330e5": "This link has ended", @@ -8839,6 +8865,12 @@ "d3866ead082d14e5": "Add keybinding", "d4345c90894a3220": "Open keybindings.json", "e56a8d51219efaa0": "No keybindings match your search.", + "90a258fff61fd77e": "Off", + "4060244a7079a0d2": "When I ask", + "e88c9d8769544731": "Automatic", + "f29d1dade4dde8aa": "Agents send no feedback to the T3 team.", + "93c4c53562d30a98": "When you ask, agents show you a short report about T3 Code and send it to the T3 team if you approve.", + "cd9ee803e8727017": "Agents also report T3 Code problems they hit on their own, such as a T3 tool that failed.", "45fa271ea0e1ac8e": "Beta", "3a678332fc7142f7": "Group sidebar threads into project folders. Pinned threads stay on top, and Snoozed and Settled stay below the folders.", "e4e91d155cb6a9b4": "Boring sidebar (group by project)", @@ -8852,6 +8884,9 @@ "298c7150a7621c80": "Simlock device hosts", "67937aa49179285e": "On a Mac, clone new worktrees from a checkout cached in the T3 home folder instead of writing every file. Uses Git’s normal checkout when it can’t. Turning it off deletes the cache.", "f9904f78d3003f58": "Fast worktree checkout", + "9c2f647882522302": "The selected machines use different agent feedback modes.", + "31bbf7bf8c0a5279": "Agent feedback", + "d52b3d6bf9f2a013": "Mixed", "ec7623deed751c05": [ "Share a thread with a guest who watches it live in a browser and sends messages you approve. Needs T3 Connect: sign in and link this machine in", " ", @@ -9166,7 +9201,6 @@ "0b4779a1825c85bc": "The shared name for this project group in the sidebar and thread lists.", "f68cbda4df83d739": "Reset project name to default", "56e37b85027e8431": "Project icon", - "e88c9d8769544731": "Automatic", "c99736317da5b1fa": "Reset project icon to default", "6afaa3e3739dc570": "Choose a project icon", "51651ce45d481a20": "Choose a project icon file", @@ -10142,7 +10176,6 @@ "16bdc70b858c223f": "Reset proactive panels to default", "c5424f09d77138ff": "When to compact an idle Claude thread over 200,000 tokens: after you return, just before its prompt cache expires, or never. Each Claude provider can override this.", "3e99c5c14f4939c8": "Reset compact idle threads to default", - "d52b3d6bf9f2a013": "Mixed", "cd72fe451ba0d6aa": "New projects", "394c3bd0a1782c8e": "Leave empty to use \"~/\" when the Add Project browser opens.", "f9b912a818bd869d": "Reset add project base directory to default", @@ -11044,7 +11077,6 @@ "4a237f41ce592b7f": "Keep this project's worktrees until you delete them manually.", "00b8ffd8ea6e6a93": "Use these rules for this project.", "72c279824d15a999": "Use each machine's worktree cleanup settings.", - "90a258fff61fd77e": "Off", "b5702d0b64866b08": "Custom", "c009c901f3eefe78": "Delete worktrees with deleted threads", "431c7cd6d50102b7": "Remove unused worktrees when active or archived threads are deleted. Worktrees with local changes are kept.", @@ -11740,7 +11772,6 @@ "4c70e3e7b3e6c493": "Secrets", "79b768229c9ef672": "Maintenance", "54b188d65247e42f": "Labs", - "f41ea186c275b56e": "About", "af4b7734da1d5ce7": "Voice", "4ec62c39ca3192bf": "Source control & issues", "f2bf529f85e05494": "Sharing & access", @@ -11866,6 +11897,7 @@ "901a823214edc8c4": "telemetry analytics usage data tracking legal opt out", "82136480255a5106": "OTel OTLP telemetry export endpoints logs traces metrics Grafana", "659d081051faf7ff": "logs traces processes resource history failures spans cpu memory", + "5eaeacfa9f82051a": "report bug problem t3 team send feedback agents tools automatic when i ask", "f537f91e1ee41d47": "keyboard shortcuts hotkeys commands bindings json", "1ba01e7ceed64b95": "window capture screenshot", "279b1cceb779ff38": "Include app text", @@ -12335,7 +12367,6 @@ "0bd41ff995d36a66": "Cache read", "3f0dfe0cb15a3272": "Cache write", "1c9d860be42b1c02": "Output", - "78344b60f407928e": "Other", "684e516076de81fe": "Standard", "3bbcc1b826fef537": "Fast", "66796576034c18ea": "Ultrafast", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index bd4ec607512c9..ff83b277dc0d6 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -52,6 +52,26 @@ "eb0f60ef4f92ab7d": "Instala {fj} 0.6 o posterior desde {fjUrl} y ejecuta {fjLogin}, o instala {tea} 0.16 o posterior desde {teaUrl} y ejecuta {teaLogin} para cada servidor de Forgejo o Gitea.", "d026a85e2e50e675": "Instala la CLI de GitCafe con {install} y ejecuta {login}, guarda un token en Ajustes o define {variable} en el servidor.", "22d3c0c48a34b5b3": "Instala la CLI de TanStack Source con {install} y ejecuta {login}, guarda un token en Ajustes o define {variable} en el servidor.", + "756c80ad262ef315": "En espera en el hilo original", + "d8df14f9905f38eb": "Enviado", + "e7c59185f8ab3987": "No enviado", + "b54ddec9084fa955": "Cerrado sin enviar", + "fbaa7ab5da716e50": "Error", + "01bac997ea55272e": "Confuso", + "0f53bc8f74dfe56a": "Función ausente", + "055560f307e15e30": "Documentación incorrecta", + "78344b60f407928e": "Otros", + "f653846a95cd6e8f": "Tipo", + "f41ea186c275b56e": "Acerca de", + "2f6e4f7cd364da73": "Resultado esperado", + "9d11c93d4035de3e": "Lo que ocurrió", + "c87d0595693704f9": "Alternativa utilizada", + "d7a4ea6ce5af44e0": "{speaker} · {count} caracteres", + "f5114fb9c40fd929": "Tú", + "cd03eb1b84271c02": "Agente", + "bfe1a60f3f9c60fb": "Turno {turn} · {what}", + "dfdaa6255a416140": "Resumen de {turns, plural, one {{turns} turno reciente} other {{turns} turnos recientes}}, {textTurns, plural, =0 {sin texto de mensajes} one {con el texto de los mensajes del último turno} other {con el texto de los mensajes de los últimos {textTurns} turnos}}{truncated, select, yes {, acortado para ajustarse} other {}}", + "afac52a5cc2dc801": "No se pudo enviar tu respuesta. Inténtalo de nuevo.", "79d776428f4d0650": "No se pudo cargar el archivo. Vuelve a conectarte e inténtalo de nuevo.", "3ea34cbb1ca5ba9b": "Vista previa cancelada.", "7c0af279ecb3da3a": "Las vistas previas de archivos en streaming no están disponibles en este entorno de ejecución.", @@ -3581,6 +3601,14 @@ "c53bc5a4b0314342": "Elemento siguiente", "2950b1424a3cddf5": "Vuelve a conectarte a este entorno y abre de nuevo el contenido.", "ef638bf1479a5461": "El entorno devolvió una URL de contenido no válida.", + "3ccfbf7e86868c35": "Comentarios para el equipo de T3", + "4e0710d19dfc2e7e": "¿Enviar este informe al equipo de T3?", + "87d0ae0723ba75d1": "Esto es todo lo que sale de tu máquina. No se envía nada hasta que pulses Enviar.", + "bf19826f81484328": "Incluir la conversación", + "260c6b45f52d2f27": "Añade el texto de tus mensajes y de las respuestas del agente en {textTurns, plural, one {el último turno} other {los últimos {textTurns} turnos}}.", + "ddb7e6f8ce99e657": "Solo quien pueda ejecutar agentes en esta máquina puede enviarlo o rechazarlo.", + "03c1eb603c112f47": "No enviar", + "653405e4ed498d9f": "Enviar", "262955d6eb632f9b": "La API del portapapeles no está disponible al copiar el enlace de invitado.", "f1a4f2b04cdbb4ef": "No se pudo copiar el enlace de invitado al portapapeles.", "cf3490a604e44d31": "No se pudo crear un enlace de invitado.", @@ -3601,7 +3629,6 @@ "abd89e9eefedf11b": "Listo", "18d166056c1ab6ff": "Dejar de compartir", "7a2d510eac9e4587": "El enlace de invitado caducó", - "653405e4ed498d9f": "Enviar", "21888e302219891d": "Vista previa ampliada de {title}", "419719298a7acaea": "Alejar", "ed8d5db95359cff4": "Restablecer zoom", @@ -5805,7 +5832,6 @@ "0061fff77e36bd4f": "No se pudo acceder al servidor.", "04dfdd46e3dd4a2e": "Algo salió mal. Vuelve a intentarlo.", "084bb2d8127a508d": "Enviado", - "e7c59185f8ab3987": "No enviado", "77c01a15bd36d17c": "Este enlace terminó o no es válido", "e0e736810f3cbef2": "Pide un enlace nuevo al propietario. Cada enlace funciona en un navegador.", "c3c53aa46f7330e5": "Este enlace terminó", @@ -8829,6 +8855,12 @@ "d3866ead082d14e5": "Añadir atajo de teclado", "d4345c90894a3220": "Abrir keybindings.json", "e56a8d51219efaa0": "Ningún atajo de teclado coincide con tu búsqueda.", + "90a258fff61fd77e": "Desactivado", + "4060244a7079a0d2": "Cuando lo pida", + "e88c9d8769544731": "Automático", + "f29d1dade4dde8aa": "Los agentes no envían comentarios al equipo de T3.", + "93c4c53562d30a98": "Cuando lo pides, los agentes te muestran un breve informe sobre T3 Code y lo envían al equipo de T3 si lo apruebas.", + "cd9ee803e8727017": "Los agentes también informan por su cuenta de los problemas que encuentran en T3 Code, como una herramienta de T3 que falla.", "45fa271ea0e1ac8e": "Beta", "3a678332fc7142f7": "Agrupa los hilos de la barra lateral en carpetas de proyecto. Los hilos fijados quedan arriba, y Pospuestos y Resueltos quedan debajo de las carpetas.", "e4e91d155cb6a9b4": "Barra lateral simple (agrupar por proyecto)", @@ -8842,6 +8874,9 @@ "298c7150a7621c80": "Hosts de dispositivos Simlock", "67937aa49179285e": "En un Mac, clona los nuevos worktrees desde un checkout en caché en la carpeta de inicio de T3 en lugar de escribir cada archivo. Usa el checkout normal de Git cuando no puede. Al desactivarlo se elimina la caché.", "f9904f78d3003f58": "Checkout rápido de worktrees", + "9c2f647882522302": "Las máquinas seleccionadas usan distintos modos de comentarios de agentes.", + "31bbf7bf8c0a5279": "Comentarios de agentes", + "d52b3d6bf9f2a013": "Mixto", "ec7623deed751c05": [ "Comparte un hilo con un invitado que lo ve en directo en un navegador y envía mensajes que tú apruebas. Requiere T3 Connect: inicia sesión y vincula esta máquina en", " ", @@ -9156,7 +9191,6 @@ "0b4779a1825c85bc": "El nombre compartido de este grupo de proyectos en la barra lateral y en las listas de hilos.", "f68cbda4df83d739": "Restablecer el nombre del proyecto al valor predeterminado", "56e37b85027e8431": "Icono del proyecto", - "e88c9d8769544731": "Automático", "c99736317da5b1fa": "Restablecer el icono del proyecto al valor predeterminado", "6afaa3e3739dc570": "Elige un icono para el proyecto", "51651ce45d481a20": "Elige un archivo de icono para el proyecto", @@ -10130,7 +10164,6 @@ "16bdc70b858c223f": "Restablecer los paneles proactivos al valor predeterminado", "c5424f09d77138ff": "Cuándo compactar un hilo inactivo de Claude con más de 200 000 tokens: al volver, justo antes de que caduque su caché de prompts o nunca. Cada proveedor de Claude puede anularlo.", "3e99c5c14f4939c8": "Restablecer la compactación de hilos inactivos al valor predeterminado", - "d52b3d6bf9f2a013": "Mixto", "cd72fe451ba0d6aa": "Proyectos nuevos", "394c3bd0a1782c8e": "Déjalo vacío para usar \"~/\" cuando se abra el explorador de Añadir proyecto.", "f9b912a818bd869d": "Restablecer el directorio base para añadir proyectos al valor predeterminado", @@ -11029,7 +11062,6 @@ "4a237f41ce592b7f": "Conserva los worktrees de este proyecto hasta que los elimines manualmente.", "00b8ffd8ea6e6a93": "Usa estas reglas para este proyecto.", "72c279824d15a999": "Usa los ajustes de limpieza de worktrees de cada máquina.", - "90a258fff61fd77e": "Desactivado", "b5702d0b64866b08": "Personalizado", "c009c901f3eefe78": "Eliminar los worktrees de hilos eliminados", "431c7cd6d50102b7": "Quita los worktrees sin uso cuando se eliminan hilos activos o archivados. Se conservan los worktrees con cambios locales.", @@ -11725,7 +11757,6 @@ "4c70e3e7b3e6c493": "Secretos", "79b768229c9ef672": "Mantenimiento", "54b188d65247e42f": "Experimentos", - "f41ea186c275b56e": "Acerca de", "af4b7734da1d5ce7": "Voz", "4ec62c39ca3192bf": "Versiones e issues", "f2bf529f85e05494": "Compartir y acceso", @@ -11851,6 +11882,7 @@ "901a823214edc8c4": "telemetría analítica datos de uso seguimiento legal desactivar", "82136480255a5106": "OTel OTLP telemetría exportar endpoints registros trazas métricas Grafana", "659d081051faf7ff": "registros trazas procesos historial de recursos fallos spans cpu memoria", + "5eaeacfa9f82051a": "informe error problema t3 equipo enviar comentarios agentes herramientas automático cuando lo pida", "f537f91e1ee41d47": "atajos de teclado teclas rápidas comandos combinaciones json", "1ba01e7ceed64b95": "ventana captura captura de pantalla", "279b1cceb779ff38": "Incluir el texto de la app", @@ -12320,7 +12352,6 @@ "0bd41ff995d36a66": "Lectura de caché", "3f0dfe0cb15a3272": "Escritura de caché", "1c9d860be42b1c02": "Salida", - "78344b60f407928e": "Otros", "684e516076de81fe": "Estándar", "3bbcc1b826fef537": "Rápida", "66796576034c18ea": "Ultrarrápida", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index bf19baf9814e0..939d36465b041 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -52,6 +52,26 @@ "eb0f60ef4f92ab7d": "Installez {fj} 0.6 ou version ultérieure depuis {fjUrl} et exécutez {fjLogin}, ou installez {tea} 0.16 ou version ultérieure depuis {teaUrl} et exécutez {teaLogin} pour chaque serveur Forgejo ou Gitea.", "d026a85e2e50e675": "Installez la CLI GitCafe avec {install}, puis exécutez {login}, enregistrez un jeton dans Paramètres ou définissez {variable} sur le serveur.", "22d3c0c48a34b5b3": "Installez la CLI TanStack Source avec {install}, puis exécutez {login}, enregistrez un jeton dans Paramètres ou définissez {variable} sur le serveur.", + "756c80ad262ef315": "En attente dans le fil d'origine", + "d8df14f9905f38eb": "Envoyé", + "e7c59185f8ab3987": "Non envoyé", + "b54ddec9084fa955": "Fermé sans envoi", + "fbaa7ab5da716e50": "Bug", + "01bac997ea55272e": "Peu clair", + "0f53bc8f74dfe56a": "Fonctionnalité manquante", + "055560f307e15e30": "Documentation incorrecte", + "78344b60f407928e": "Autre", + "f653846a95cd6e8f": "Type", + "f41ea186c275b56e": "À propos", + "2f6e4f7cd364da73": "Résultat attendu", + "9d11c93d4035de3e": "Résultat obtenu", + "c87d0595693704f9": "Solution de repli", + "d7a4ea6ce5af44e0": "{speaker} · {count} caractères", + "f5114fb9c40fd929": "Vous", + "cd03eb1b84271c02": "Agent", + "bfe1a60f3f9c60fb": "Tour {turn} · {what}", + "dfdaa6255a416140": "Résumé de {turns, plural, one {{turns} tour récent} other {{turns} tours récents}}, {textTurns, plural, =0 {sans texte des messages} one {avec le texte des messages du dernier tour} other {avec le texte des messages des {textTurns} derniers tours}}{truncated, select, yes {, raccourci pour tenir dans la limite} other {}}", + "afac52a5cc2dc801": "Impossible d'envoyer votre réponse. Réessayez.", "79d776428f4d0650": "Le fichier n’a pas pu être chargé. Reconnectez-vous et réessayez.", "3ea34cbb1ca5ba9b": "Aperçu annulé.", "7c0af279ecb3da3a": "Les aperçus de fichiers en streaming ne sont pas disponibles dans cet environnement d’exécution.", @@ -3581,6 +3601,14 @@ "c53bc5a4b0314342": "Média suivant", "2950b1424a3cddf5": "Reconnectez-vous à cet environnement et ouvrez à nouveau le média.", "ef638bf1479a5461": "L’environnement a renvoyé une URL de média non valide.", + "3ccfbf7e86868c35": "Retour pour l'équipe T3", + "4e0710d19dfc2e7e": "Envoyer ce rapport à l'équipe T3 ?", + "87d0ae0723ba75d1": "Voici tout ce qui quitte votre machine. Rien n'est envoyé tant que vous ne cliquez pas sur Envoyer.", + "bf19826f81484328": "Inclure la conversation", + "260c6b45f52d2f27": "Ajoute le texte de vos messages et des réponses de l'agent dans {textTurns, plural, one {le dernier tour} other {les {textTurns} derniers tours}}.", + "ddb7e6f8ce99e657": "Seule une personne autorisée à exécuter des agents sur cette machine peut l'envoyer ou le refuser.", + "03c1eb603c112f47": "Ne pas envoyer", + "653405e4ed498d9f": "Envoyer", "262955d6eb632f9b": "L’API Presse-papiers n’est pas disponible pour copier le lien invité.", "f1a4f2b04cdbb4ef": "Impossible de copier le lien invité dans le presse-papiers.", "cf3490a604e44d31": "Impossible de créer un lien invité.", @@ -3601,7 +3629,6 @@ "abd89e9eefedf11b": "Terminé", "18d166056c1ab6ff": "Arrêter le partage", "7a2d510eac9e4587": "Lien invité expiré", - "653405e4ed498d9f": "Envoyer", "21888e302219891d": "Aperçu agrandi de {title}", "419719298a7acaea": "Zoom arrière", "ed8d5db95359cff4": "Réinitialiser le zoom", @@ -5806,7 +5833,6 @@ "0061fff77e36bd4f": "Impossible de joindre le serveur.", "04dfdd46e3dd4a2e": "Une erreur s’est produite. Réessayez.", "084bb2d8127a508d": "Envoyé", - "e7c59185f8ab3987": "Non envoyé", "77c01a15bd36d17c": "Ce lien a expiré ou n’est pas valide", "e0e736810f3cbef2": "Demandez un nouveau lien au propriétaire. Chaque lien fonctionne dans un seul navigateur.", "c3c53aa46f7330e5": "Ce lien a expiré", @@ -8830,6 +8856,12 @@ "d3866ead082d14e5": "Ajouter un raccourci clavier", "d4345c90894a3220": "Ouvrir keybindings.json", "e56a8d51219efaa0": "Aucun raccourci clavier ne correspond à votre recherche.", + "90a258fff61fd77e": "Désactivé", + "4060244a7079a0d2": "À ma demande", + "e88c9d8769544731": "Automatique", + "f29d1dade4dde8aa": "Les agents n'envoient aucun retour à l'équipe T3.", + "93c4c53562d30a98": "À votre demande, les agents vous présentent un court rapport sur T3 Code et l'envoient à l'équipe T3 si vous l'approuvez.", + "cd9ee803e8727017": "Les agents signalent aussi spontanément les problèmes qu'ils rencontrent dans T3 Code, comme un outil T3 qui échoue.", "45fa271ea0e1ac8e": "Bêta", "3a678332fc7142f7": "Regroupe les fils de la barre latérale dans des dossiers de projet. Les fils épinglés restent en haut, les fils reportés et clos restent sous les dossiers.", "e4e91d155cb6a9b4": "Barre latérale classique (regrouper par projet)", @@ -8843,6 +8875,9 @@ "298c7150a7621c80": "Hôtes d’appareils Simlock", "67937aa49179285e": "Sur Mac, clone les nouveaux worktrees depuis une copie en cache dans le dossier T3 home au lieu d’écrire chaque fichier. Utilise le checkout Git normal quand ce n’est pas possible. La désactivation supprime le cache.", "f9904f78d3003f58": "Checkout rapide des worktrees", + "9c2f647882522302": "Les machines sélectionnées utilisent des modes de retour des agents différents.", + "31bbf7bf8c0a5279": "Retours des agents", + "d52b3d6bf9f2a013": "Mixte", "ec7623deed751c05": [ "Partagez un fil avec un invité qui le suit en direct dans un navigateur et envoie des messages que vous approuvez. Nécessite T3 Connect : connectez-vous et associez cette machine dans", " ", @@ -9158,7 +9193,6 @@ "0b4779a1825c85bc": "Le nom commun de ce groupe de projets dans la barre latérale et les listes de fils.", "f68cbda4df83d739": "Réinitialiser le nom du projet à la valeur par défaut", "56e37b85027e8431": "Icône du projet", - "e88c9d8769544731": "Automatique", "c99736317da5b1fa": "Réinitialiser l’icône du projet à la valeur par défaut", "6afaa3e3739dc570": "Choisir une icône de projet", "51651ce45d481a20": "Choisir un fichier d’icône de projet", @@ -10132,7 +10166,6 @@ "16bdc70b858c223f": "Réinitialiser les panneaux proactifs à la valeur par défaut", "c5424f09d77138ff": "Quand compacter un fil Claude inactif de plus de 200 000 tokens : à votre retour, juste avant l’expiration de son cache de prompt, ou jamais. Chaque fournisseur Claude peut remplacer ce paramètre.", "3e99c5c14f4939c8": "Réinitialiser le compactage des fils inactifs à la valeur par défaut", - "d52b3d6bf9f2a013": "Mixte", "cd72fe451ba0d6aa": "Nouveaux projets", "394c3bd0a1782c8e": "Laissez vide pour utiliser « ~/ » à l’ouverture du navigateur Ajouter un projet.", "f9b912a818bd869d": "Réinitialiser le répertoire de base pour l’ajout de projets à la valeur par défaut", @@ -11034,7 +11067,6 @@ "4a237f41ce592b7f": "Conserve les worktrees de ce projet jusqu’à ce que vous les supprimiez manuellement.", "00b8ffd8ea6e6a93": "Utilise ces règles pour ce projet.", "72c279824d15a999": "Utilise les paramètres de nettoyage des worktrees de chaque machine.", - "90a258fff61fd77e": "Désactivé", "b5702d0b64866b08": "Personnalisé", "c009c901f3eefe78": "Supprimer les worktrees des fils supprimés", "431c7cd6d50102b7": "Supprime les worktrees inutilisés quand des fils actifs ou archivés sont supprimés. Les worktrees avec des modifications locales sont conservés.", @@ -11730,7 +11762,6 @@ "4c70e3e7b3e6c493": "Secrets", "79b768229c9ef672": "Maintenance", "54b188d65247e42f": "Labs", - "f41ea186c275b56e": "À propos", "af4b7734da1d5ce7": "Voix", "4ec62c39ca3192bf": "Versions et tickets", "f2bf529f85e05494": "Partage et accès", @@ -11856,6 +11887,7 @@ "901a823214edc8c4": "télémétrie analytique données d’utilisation suivi mentions légales refuser", "82136480255a5106": "OTel OTLP télémétrie export points de terminaison journaux traces métriques Grafana", "659d081051faf7ff": "journaux traces processus historique des ressources échecs spans cpu mémoire", + "5eaeacfa9f82051a": "rapport bug problème t3 équipe envoyer retour agents outils automatique à ma demande", "f537f91e1ee41d47": "raccourcis clavier touches commandes associations json", "1ba01e7ceed64b95": "fenêtre capture capture d’écran", "279b1cceb779ff38": "Inclure le texte de l’app", @@ -12325,7 +12357,6 @@ "0bd41ff995d36a66": "Lecture du cache", "3f0dfe0cb15a3272": "Écriture du cache", "1c9d860be42b1c02": "Sortie", - "78344b60f407928e": "Autre", "684e516076de81fe": "Standard", "3bbcc1b826fef537": "Rapide", "66796576034c18ea": "Ultrarapide", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index b7a4aa42d3750..51fe276edc353 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -52,6 +52,26 @@ "eb0f60ef4f92ab7d": "Forgejo または Gitea のサーバーごとに、{fjUrl} から {fj} 0.6 以降をインストールして {fjLogin} を実行するか、{teaUrl} から {tea} 0.16 以降をインストールして {teaLogin} を実行してください。", "d026a85e2e50e675": "{install} で GitCafe CLI をインストールしてから、{login} を実行するか、設定にトークンを保存するか、サーバーで {variable} を設定してください。", "22d3c0c48a34b5b3": "{install} で TanStack Source CLI をインストールしてから、{login} を実行するか、設定にトークンを保存するか、サーバーで {variable} を設定してください。", + "756c80ad262ef315": "元のスレッドで待機中", + "d8df14f9905f38eb": "送信済み", + "e7c59185f8ab3987": "未送信", + "b54ddec9084fa955": "送信せずに閉じました", + "fbaa7ab5da716e50": "不具合", + "01bac997ea55272e": "分かりにくい", + "0f53bc8f74dfe56a": "機能の不足", + "055560f307e15e30": "ドキュメントの誤り", + "78344b60f407928e": "その他", + "f653846a95cd6e8f": "種類", + "f41ea186c275b56e": "情報", + "2f6e4f7cd364da73": "期待した動作", + "9d11c93d4035de3e": "実際の動作", + "c87d0595693704f9": "代わりに行ったこと", + "d7a4ea6ce5af44e0": "{speaker} · {count} 文字", + "f5114fb9c40fd929": "あなた", + "cd03eb1b84271c02": "エージェント", + "bfe1a60f3f9c60fb": "ターン {turn} · {what}", + "dfdaa6255a416140": "{turns, plural, one {直近 {turns} ターン} other {直近 {turns} ターン}}の概要、{textTurns, plural, =0 {メッセージ本文なし} one {最後のターンのメッセージ本文} other {直近 {textTurns} ターンのメッセージ本文}}{truncated, select, yes {、収まる長さに短縮済み} other {}}", + "afac52a5cc2dc801": "回答を送信できませんでした。もう一度お試しください。", "79d776428f4d0650": "ファイルを読み込めませんでした。再接続してもう一度お試しください。", "3ea34cbb1ca5ba9b": "プレビューをキャンセルしました。", "7c0af279ecb3da3a": "このランタイムではファイルのストリーミングプレビューを利用できません。", @@ -3577,6 +3597,14 @@ "c53bc5a4b0314342": "次のメディア", "2950b1424a3cddf5": "この環境に再接続してから、もう一度メディアを開いてください。", "ef638bf1479a5461": "環境から無効なメディア URL が返されました。", + "3ccfbf7e86868c35": "T3 チームへのフィードバック", + "4e0710d19dfc2e7e": "このレポートを T3 チームに送信しますか?", + "87d0ae0723ba75d1": "この内容だけがこのマシンから送信されます。「送信」を押すまで何も送信されません。", + "bf19826f81484328": "会話を含める", + "260c6b45f52d2f27": "直近 {textTurns} ターンでのあなたのメッセージとエージェントの返信の本文を追加します。", + "ddb7e6f8ce99e657": "このマシンでエージェントを実行できる人だけが、送信または拒否できます。", + "03c1eb603c112f47": "送信しない", + "653405e4ed498d9f": "送信", "262955d6eb632f9b": "ゲストリンクをコピーする際にクリップボード API を利用できませんでした。", "f1a4f2b04cdbb4ef": "ゲストリンクをクリップボードにコピーできませんでした。", "cf3490a604e44d31": "ゲストリンクを作成できませんでした。", @@ -3597,7 +3625,6 @@ "abd89e9eefedf11b": "完了", "18d166056c1ab6ff": "共有を停止", "7a2d510eac9e4587": "ゲストリンクの期限が切れました", - "653405e4ed498d9f": "送信", "21888e302219891d": "拡大した {title} のプレビュー", "419719298a7acaea": "縮小", "ed8d5db95359cff4": "ズームをリセット", @@ -5788,7 +5815,6 @@ "0061fff77e36bd4f": "サーバーに接続できませんでした。", "04dfdd46e3dd4a2e": "問題が発生しました。もう一度お試しください。", "084bb2d8127a508d": "送信済み", - "e7c59185f8ab3987": "未送信", "77c01a15bd36d17c": "このリンクは終了したか、無効です", "e0e736810f3cbef2": "所有者に新しいリンクを依頼してください。各リンクは 1 つのブラウザーでのみ使用できます。", "c3c53aa46f7330e5": "このリンクは終了しました", @@ -8787,6 +8813,12 @@ "d3866ead082d14e5": "キーボードショートカットを追加", "d4345c90894a3220": "keybindings.json を開く", "e56a8d51219efaa0": "検索に一致するキーボードショートカットはありません。", + "90a258fff61fd77e": "オフ", + "4060244a7079a0d2": "依頼したとき", + "e88c9d8769544731": "自動", + "f29d1dade4dde8aa": "エージェントは T3 チームにフィードバックを送信しません。", + "93c4c53562d30a98": "依頼すると、エージェントが T3 Code についての短いレポートを表示し、承認した場合に T3 チームへ送信します。", + "cd9ee803e8727017": "エージェントが自ら遭遇した T3 Code の問題も報告します。たとえば、T3 ツールの失敗などです。", "45fa271ea0e1ac8e": "ベータ", "3a678332fc7142f7": "サイドバーのスレッドをプロジェクトフォルダーにまとめます。ピン留めしたスレッドは上部に残り、スヌーズ中と対応済みはフォルダーの下に表示されます。", "e4e91d155cb6a9b4": "シンプルなサイドバー(プロジェクトでグループ化)", @@ -8800,6 +8832,9 @@ "298c7150a7621c80": "Simlock デバイスホスト", "67937aa49179285e": "Mac では、すべてのファイルを書き込む代わりに、T3 ホームフォルダーにキャッシュしたチェックアウトから新しいワークツリーを複製します。できない場合は Git の通常のチェックアウトを使います。オフにするとキャッシュは削除されます。", "f9904f78d3003f58": "高速ワークツリーチェックアウト", + "9c2f647882522302": "選択したマシンでは、エージェントのフィードバックモードが異なります。", + "31bbf7bf8c0a5279": "エージェントのフィードバック", + "d52b3d6bf9f2a013": "混在", "ec7623deed751c05": [ "スレッドをゲストと共有します。ゲストはブラウザーでライブで閲覧し、あなたが承認したメッセージを送信できます。T3 Connect が必要です。サインインして、", " ", @@ -9115,7 +9150,6 @@ "0b4779a1825c85bc": "サイドバーとスレッド一覧に表示される、このプロジェクトグループの共通の名前です。", "f68cbda4df83d739": "プロジェクト名をデフォルトにリセット", "56e37b85027e8431": "プロジェクトのアイコン", - "e88c9d8769544731": "自動", "c99736317da5b1fa": "プロジェクトのアイコンをデフォルトにリセット", "6afaa3e3739dc570": "プロジェクトのアイコンを選択", "51651ce45d481a20": "プロジェクトのアイコンファイルを選択", @@ -10085,7 +10119,6 @@ "16bdc70b858c223f": "自動で開くパネルをデフォルトにリセット", "c5424f09d77138ff": "200,000 トークンを超えるアイドル状態の Claude スレッドを圧縮するタイミングです。戻ってきた後、プロンプトキャッシュの有効期限の直前、またはしない、から選びます。Claude プロバイダーごとに上書きできます。", "3e99c5c14f4939c8": "「アイドル状態のスレッドを圧縮」をデフォルトにリセット", - "d52b3d6bf9f2a013": "混在", "cd72fe451ba0d6aa": "新しいプロジェクト", "394c3bd0a1782c8e": "空のままにすると、「プロジェクトを追加」のブラウザーを開いたときに \"~/\" を使用します。", "f9b912a818bd869d": "プロジェクト追加のベースディレクトリをデフォルトにリセット", @@ -10985,7 +11018,6 @@ "4a237f41ce592b7f": "このプロジェクトのワークツリーは、手動で削除するまで保持します。", "00b8ffd8ea6e6a93": "このプロジェクトでこれらのルールを使用します。", "72c279824d15a999": "各マシンのワークツリーのクリーンアップ設定を使用します。", - "90a258fff61fd77e": "オフ", "b5702d0b64866b08": "カスタム", "c009c901f3eefe78": "削除したスレッドのワークツリーを削除", "431c7cd6d50102b7": "アクティブまたはアーカイブ済みのスレッドを削除したときに、使われていないワークツリーを削除します。ローカルの変更があるワークツリーは保持されます。", @@ -11681,7 +11713,6 @@ "4c70e3e7b3e6c493": "シークレット", "79b768229c9ef672": "メンテナンス", "54b188d65247e42f": "試験的機能", - "f41ea186c275b56e": "情報", "af4b7734da1d5ce7": "音声", "4ec62c39ca3192bf": "ソース管理と Issue", "f2bf529f85e05494": "共有とアクセス", @@ -11807,6 +11838,7 @@ "901a823214edc8c4": "テレメトリー 分析 使用状況データ トラッキング 法的事項 オプトアウト telemetry", "82136480255a5106": "OTel OTLP テレメトリー エクスポート エンドポイント ログ トレース メトリクス Grafana", "659d081051faf7ff": "ログ トレース プロセス リソース履歴 失敗 スパン CPU メモリ diagnostics", + "5eaeacfa9f82051a": "報告 不具合 問題 t3 チーム 送信 フィードバック エージェント ツール 自動 依頼したとき", "f537f91e1ee41d47": "キーボードショートカット ホットキー コマンド キーバインド JSON keybindings", "1ba01e7ceed64b95": "ウィンドウ キャプチャ スクリーンショット window capture", "279b1cceb779ff38": "アプリのテキストを含める", @@ -12276,7 +12308,6 @@ "0bd41ff995d36a66": "キャッシュの読み取り", "3f0dfe0cb15a3272": "キャッシュの書き込み", "1c9d860be42b1c02": "出力", - "78344b60f407928e": "その他", "684e516076de81fe": "標準", "3bbcc1b826fef537": "高速", "66796576034c18ea": "超高速", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 9a97fd72a773f..51c3b0a06a006 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -52,6 +52,26 @@ "eb0f60ef4f92ab7d": "{fjUrl}에서 {fj} 0.6 이상을 설치하고 {fjLogin}을(를) 실행하거나, {teaUrl}에서 {tea} 0.16 이상을 설치하고 Forgejo 또는 Gitea 서버마다 {teaLogin}을(를) 실행하세요.", "d026a85e2e50e675": "{install}로 GitCafe CLI를 설치한 후 {login}을(를) 실행하거나, 설정에 토큰을 저장하거나, 서버에서 {variable}을(를) 설정하세요.", "22d3c0c48a34b5b3": "{install}로 TanStack Source CLI를 설치한 후 {login}을(를) 실행하거나, 설정에 토큰을 저장하거나, 서버에서 {variable}을(를) 설정하세요.", + "756c80ad262ef315": "원래 스레드에서 대기 중", + "d8df14f9905f38eb": "보냄", + "e7c59185f8ab3987": "보내지 않음", + "b54ddec9084fa955": "보내지 않고 닫음", + "fbaa7ab5da716e50": "버그", + "01bac997ea55272e": "이해하기 어려움", + "0f53bc8f74dfe56a": "기능 부족", + "055560f307e15e30": "잘못된 문서", + "78344b60f407928e": "기타", + "f653846a95cd6e8f": "유형", + "f41ea186c275b56e": "정보", + "2f6e4f7cd364da73": "기대한 동작", + "9d11c93d4035de3e": "실제 동작", + "c87d0595693704f9": "대신 한 일", + "d7a4ea6ce5af44e0": "{speaker} · {count}자", + "f5114fb9c40fd929": "나", + "cd03eb1b84271c02": "에이전트", + "bfe1a60f3f9c60fb": "턴 {turn} · {what}", + "dfdaa6255a416140": "{turns, plural, one {최근 {turns}개 턴} other {최근 {turns}개 턴}}의 개요, {textTurns, plural, =0 {메시지 본문 없음} one {마지막 턴의 메시지 본문} other {최근 {textTurns}개 턴의 메시지 본문}}{truncated, select, yes {, 길이에 맞게 줄임} other {}}", + "afac52a5cc2dc801": "답변을 보내지 못했습니다. 다시 시도하세요.", "79d776428f4d0650": "파일을 불러올 수 없습니다. 다시 연결한 뒤 시도하세요.", "3ea34cbb1ca5ba9b": "미리 보기가 취소되었습니다.", "7c0af279ecb3da3a": "이 런타임에서는 스트리밍 파일 미리 보기를 사용할 수 없습니다.", @@ -3577,6 +3597,14 @@ "c53bc5a4b0314342": "다음 미디어", "2950b1424a3cddf5": "이 환경에 다시 연결한 후 미디어를 다시 여세요.", "ef638bf1479a5461": "환경에서 잘못된 미디어 URL을 반환했습니다.", + "3ccfbf7e86868c35": "T3 팀에 보내는 피드백", + "4e0710d19dfc2e7e": "이 보고서를 T3 팀에 보낼까요?", + "87d0ae0723ba75d1": "이 내용만 이 컴퓨터에서 전송됩니다. 보내기를 누르기 전에는 아무것도 전송되지 않습니다.", + "bf19826f81484328": "대화 포함", + "260c6b45f52d2f27": "최근 {textTurns}개 턴에서 내 메시지와 에이전트 답변의 본문을 추가합니다.", + "ddb7e6f8ce99e657": "이 컴퓨터에서 에이전트를 실행할 수 있는 사람만 보고서를 보내거나 거절할 수 있습니다.", + "03c1eb603c112f47": "보내지 않기", + "653405e4ed498d9f": "보내기", "262955d6eb632f9b": "게스트 링크를 복사하는 중 클립보드 API를 사용할 수 없습니다.", "f1a4f2b04cdbb4ef": "게스트 링크를 클립보드에 복사하지 못했습니다.", "cf3490a604e44d31": "게스트 링크를 만들 수 없습니다.", @@ -3597,7 +3625,6 @@ "abd89e9eefedf11b": "완료", "18d166056c1ab6ff": "공유 중지", "7a2d510eac9e4587": "게스트 링크 만료됨", - "653405e4ed498d9f": "보내기", "21888e302219891d": "확대된 {title} 미리 보기", "419719298a7acaea": "축소", "ed8d5db95359cff4": "확대/축소 초기화", @@ -5786,7 +5813,6 @@ "0061fff77e36bd4f": "서버에 연결할 수 없습니다.", "04dfdd46e3dd4a2e": "문제가 발생했습니다. 다시 시도하세요.", "084bb2d8127a508d": "보냄", - "e7c59185f8ab3987": "보내지 않음", "77c01a15bd36d17c": "이 링크는 종료되었거나 유효하지 않습니다", "e0e736810f3cbef2": "소유자에게 새 링크를 요청하세요. 각 링크는 한 브라우저에서만 작동합니다.", "c3c53aa46f7330e5": "이 링크는 종료되었습니다", @@ -8790,6 +8816,12 @@ "d3866ead082d14e5": "단축키 추가", "d4345c90894a3220": "keybindings.json 열기", "e56a8d51219efaa0": "검색과 일치하는 단축키가 없습니다.", + "90a258fff61fd77e": "끔", + "4060244a7079a0d2": "내가 요청할 때", + "e88c9d8769544731": "자동", + "f29d1dade4dde8aa": "에이전트가 T3 팀에 피드백을 보내지 않습니다.", + "93c4c53562d30a98": "요청하면 에이전트가 T3 Code에 관한 짧은 보고서를 보여주고, 승인하면 T3 팀에 보냅니다.", + "cd9ee803e8727017": "에이전트가 직접 겪은 T3 Code 문제도 보고합니다. 예를 들어 T3 도구가 실패한 경우입니다.", "45fa271ea0e1ac8e": "베타", "3a678332fc7142f7": "사이드바 스레드를 프로젝트 폴더로 묶습니다. 고정된 스레드는 맨 위에, 다시 알림과 정리됨은 폴더 아래에 유지됩니다.", "e4e91d155cb6a9b4": "단순 사이드바(프로젝트별 그룹화)", @@ -8803,6 +8835,9 @@ "298c7150a7621c80": "Simlock 기기 호스트", "67937aa49179285e": "Mac에서 모든 파일을 쓰는 대신 T3 홈 폴더에 캐시된 체크아웃에서 새 워크트리를 복제합니다. 불가능하면 Git의 일반 체크아웃을 사용합니다. 끄면 캐시가 삭제됩니다.", "f9904f78d3003f58": "빠른 워크트리 체크아웃", + "9c2f647882522302": "선택한 컴퓨터의 에이전트 피드백 모드가 서로 다릅니다.", + "31bbf7bf8c0a5279": "에이전트 피드백", + "d52b3d6bf9f2a013": "혼합", "ec7623deed751c05": [ "브라우저에서 실시간으로 지켜보고 승인한 메시지를 보낼 수 있는 게스트와 스레드를 공유합니다. T3 Connect가 필요합니다. 로그인한 뒤", " ", @@ -9117,7 +9152,6 @@ "0b4779a1825c85bc": "사이드바와 스레드 목록에 표시되는 이 프로젝트 그룹의 공유 이름입니다.", "f68cbda4df83d739": "프로젝트 이름 기본값으로 재설정", "56e37b85027e8431": "프로젝트 아이콘", - "e88c9d8769544731": "자동", "c99736317da5b1fa": "프로젝트 아이콘 기본값으로 재설정", "6afaa3e3739dc570": "프로젝트 아이콘 선택", "51651ce45d481a20": "프로젝트 아이콘 파일 선택", @@ -10087,7 +10121,6 @@ "16bdc70b858c223f": "패널 미리 열기 기본값으로 재설정", "c5424f09d77138ff": "200,000 토큰이 넘는 유휴 Claude 스레드를 압축할 시점입니다. 돌아온 뒤, 프롬프트 캐시가 만료되기 직전, 또는 압축 안 함 중에서 선택합니다. 각 Claude 제공자에서 재정의할 수 있습니다.", "3e99c5c14f4939c8": "유휴 스레드 압축 기본값으로 재설정", - "d52b3d6bf9f2a013": "혼합", "cd72fe451ba0d6aa": "새 프로젝트", "394c3bd0a1782c8e": "프로젝트 추가 탐색기가 열릴 때 \"~/\"를 사용하려면 비워 두세요.", "f9b912a818bd869d": "프로젝트 추가 기본 디렉터리 기본값으로 재설정", @@ -10985,7 +11018,6 @@ "4a237f41ce592b7f": "직접 삭제할 때까지 이 프로젝트의 워크트리를 유지합니다.", "00b8ffd8ea6e6a93": "이 프로젝트에 이 규칙을 사용합니다.", "72c279824d15a999": "각 머신의 워크트리 정리 설정을 사용합니다.", - "90a258fff61fd77e": "끔", "b5702d0b64866b08": "사용자 지정", "c009c901f3eefe78": "삭제된 스레드의 워크트리 삭제", "431c7cd6d50102b7": "활성 또는 보관된 스레드가 삭제되면 사용하지 않는 워크트리를 제거합니다. 로컬 변경 사항이 있는 워크트리는 유지됩니다.", @@ -11677,7 +11709,6 @@ "4c70e3e7b3e6c493": "시크릿", "79b768229c9ef672": "유지 관리", "54b188d65247e42f": "실험 기능", - "f41ea186c275b56e": "정보", "af4b7734da1d5ce7": "음성", "4ec62c39ca3192bf": "소스 제어 및 이슈", "f2bf529f85e05494": "공유 및 액세스", @@ -11803,6 +11834,7 @@ "901a823214edc8c4": "원격 분석 분석 사용 데이터 추적 법적 옵트아웃", "82136480255a5106": "OTel OTLP 원격 분석 내보내기 엔드포인트 로그 추적 메트릭 Grafana", "659d081051faf7ff": "로그 추적 프로세스 리소스 기록 실패 스팬 cpu 메모리", + "5eaeacfa9f82051a": "보고 버그 문제 t3 팀 보내기 피드백 에이전트 도구 자동 내가 요청할 때", "f537f91e1ee41d47": "키보드 단축키 핫키 명령 바인딩 json", "1ba01e7ceed64b95": "창 캡처 스크린샷", "279b1cceb779ff38": "앱 텍스트 포함", @@ -12272,7 +12304,6 @@ "0bd41ff995d36a66": "캐시 읽기", "3f0dfe0cb15a3272": "캐시 쓰기", "1c9d860be42b1c02": "출력", - "78344b60f407928e": "기타", "684e516076de81fe": "표준", "3bbcc1b826fef537": "빠름", "66796576034c18ea": "초고속", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 5b3b227205e4b..d17ff0e321ccf 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -52,6 +52,26 @@ "eb0f60ef4f92ab7d": "Instale o {fj} 0.6 ou posterior em {fjUrl} e execute {fjLogin}, ou instale o {tea} 0.16 ou posterior em {teaUrl} e execute {teaLogin} para cada servidor Forgejo ou Gitea.", "d026a85e2e50e675": "Instale a CLI do GitCafe com {install} e execute {login}, salve um token nas Configurações ou defina {variable} no servidor.", "22d3c0c48a34b5b3": "Instale a CLI do TanStack Source com {install} e execute {login}, salve um token nas Configurações ou defina {variable} no servidor.", + "756c80ad262ef315": "Aguardando na thread original", + "d8df14f9905f38eb": "Enviado", + "e7c59185f8ab3987": "Não enviada", + "b54ddec9084fa955": "Fechado sem enviar", + "fbaa7ab5da716e50": "Bug", + "01bac997ea55272e": "Confuso", + "0f53bc8f74dfe56a": "Funcionalidade ausente", + "055560f307e15e30": "Documentação incorreta", + "78344b60f407928e": "Outros", + "f653846a95cd6e8f": "Tipo", + "f41ea186c275b56e": "Sobre", + "2f6e4f7cd364da73": "Resultado esperado", + "9d11c93d4035de3e": "O que aconteceu", + "c87d0595693704f9": "Alternativa utilizada", + "d7a4ea6ce5af44e0": "{speaker} · {count} caracteres", + "f5114fb9c40fd929": "Você", + "cd03eb1b84271c02": "Agente", + "bfe1a60f3f9c60fb": "Turno {turn} · {what}", + "dfdaa6255a416140": "Resumo de {turns, plural, one {{turns} turno recente} other {{turns} turnos recentes}}, {textTurns, plural, =0 {sem texto das mensagens} one {com o texto das mensagens do último turno} other {com o texto das mensagens dos últimos {textTurns} turnos}}{truncated, select, yes {, encurtado para caber} other {}}", + "afac52a5cc2dc801": "Não foi possível enviar sua resposta. Tente novamente.", "79d776428f4d0650": "Não foi possível carregar o arquivo. Reconecte e tente novamente.", "3ea34cbb1ca5ba9b": "Pré-visualização cancelada.", "7c0af279ecb3da3a": "As pré-visualizações de arquivos por streaming não estão disponíveis neste runtime.", @@ -3581,6 +3601,14 @@ "c53bc5a4b0314342": "Próxima mídia", "2950b1424a3cddf5": "Reconecte-se a este ambiente e abra a mídia novamente.", "ef638bf1479a5461": "O ambiente retornou uma URL de mídia inválida.", + "3ccfbf7e86868c35": "Feedback para a equipe do T3", + "4e0710d19dfc2e7e": "Enviar este relatório para a equipe do T3?", + "87d0ae0723ba75d1": "Isto é tudo o que sai da sua máquina. Nada é enviado até você clicar em Enviar.", + "bf19826f81484328": "Incluir a conversa", + "260c6b45f52d2f27": "Adiciona o texto das suas mensagens e das respostas do agente {textTurns, plural, one {no último turno} other {nos últimos {textTurns} turnos}}.", + "ddb7e6f8ce99e657": "Somente quem pode executar agentes nesta máquina pode enviar ou recusar o relatório.", + "03c1eb603c112f47": "Não enviar", + "653405e4ed498d9f": "Enviar", "262955d6eb632f9b": "A API da área de transferência não está disponível ao copiar o link de convidado.", "f1a4f2b04cdbb4ef": "Falha ao copiar o link de convidado para a área de transferência.", "cf3490a604e44d31": "Não foi possível criar um link de convidado.", @@ -3601,7 +3629,6 @@ "abd89e9eefedf11b": "Concluído", "18d166056c1ab6ff": "Parar de compartilhar", "7a2d510eac9e4587": "Link de convidado expirado", - "653405e4ed498d9f": "Enviar", "21888e302219891d": "Pré-visualização expandida de {title}", "419719298a7acaea": "Diminuir zoom", "ed8d5db95359cff4": "Redefinir zoom", @@ -5805,7 +5832,6 @@ "0061fff77e36bd4f": "Não foi possível acessar o servidor.", "04dfdd46e3dd4a2e": "Algo deu errado. Tente novamente.", "084bb2d8127a508d": "Enviada", - "e7c59185f8ab3987": "Não enviada", "77c01a15bd36d17c": "Este link expirou ou não é válido", "e0e736810f3cbef2": "Peça um novo link ao proprietário. Cada link funciona em um navegador.", "c3c53aa46f7330e5": "Este link expirou", @@ -8829,6 +8855,12 @@ "d3866ead082d14e5": "Adicionar atalho de teclado", "d4345c90894a3220": "Abrir keybindings.json", "e56a8d51219efaa0": "Nenhum atalho de teclado corresponde à sua pesquisa.", + "90a258fff61fd77e": "Desativado", + "4060244a7079a0d2": "Quando eu pedir", + "e88c9d8769544731": "Automático", + "f29d1dade4dde8aa": "Os agentes não enviam feedback para a equipe do T3.", + "93c4c53562d30a98": "Quando você pede, os agentes mostram um breve relatório sobre o T3 Code e o enviam para a equipe do T3 se você aprovar.", + "cd9ee803e8727017": "Os agentes também relatam por conta própria os problemas que encontram no T3 Code, como uma ferramenta do T3 que falhou.", "45fa271ea0e1ac8e": "Beta", "3a678332fc7142f7": "Agrupa as threads da barra lateral em pastas de projeto. As threads fixadas ficam no topo, e Adiadas e Concluídas ficam abaixo das pastas.", "e4e91d155cb6a9b4": "Barra lateral sem graça (agrupar por projeto)", @@ -8842,6 +8874,9 @@ "298c7150a7621c80": "Hosts de dispositivos Simlock", "67937aa49179285e": "No Mac, clona novos worktrees a partir de um checkout em cache na pasta T3 home em vez de gravar cada arquivo. Usa o checkout normal do Git quando não consegue. Desativar exclui o cache.", "f9904f78d3003f58": "Checkout rápido de worktree", + "9c2f647882522302": "As máquinas selecionadas usam modos diferentes de feedback dos agentes.", + "31bbf7bf8c0a5279": "Feedback dos agentes", + "d52b3d6bf9f2a013": "Misto", "ec7623deed751c05": [ "Compartilhe uma thread com um convidado que a acompanha ao vivo no navegador e envia mensagens que você aprova. Requer T3 Connect: entre e vincule esta máquina em", " ", @@ -9158,7 +9193,6 @@ "0b4779a1825c85bc": "O nome compartilhado deste grupo de projetos na barra lateral e nas listas de threads.", "f68cbda4df83d739": "Redefinir o nome do projeto para o padrão", "56e37b85027e8431": "Ícone do projeto", - "e88c9d8769544731": "Automático", "c99736317da5b1fa": "Redefinir o ícone do projeto para o padrão", "6afaa3e3739dc570": "Escolha um ícone para o projeto", "51651ce45d481a20": "Escolha um arquivo de ícone para o projeto", @@ -10132,7 +10166,6 @@ "16bdc70b858c223f": "Redefinir os painéis proativos para o padrão", "c5424f09d77138ff": "Quando compactar uma thread do Claude ociosa com mais de 200.000 tokens: depois que você voltar, logo antes de o cache do prompt expirar ou nunca. Cada provedor Claude pode substituir isso.", "3e99c5c14f4939c8": "Redefinir a compactação de threads ociosas para o padrão", - "d52b3d6bf9f2a013": "Misto", "cd72fe451ba0d6aa": "Novos projetos", "394c3bd0a1782c8e": "Deixe vazio para usar \"~/\" quando o navegador de Adicionar projeto abrir.", "f9b912a818bd869d": "Redefinir o diretório base para adicionar projetos para o padrão", @@ -11034,7 +11067,6 @@ "4a237f41ce592b7f": "Mantém os worktrees deste projeto até você excluí-los manualmente.", "00b8ffd8ea6e6a93": "Usa estas regras neste projeto.", "72c279824d15a999": "Usa as configurações de limpeza de worktrees de cada máquina.", - "90a258fff61fd77e": "Desativado", "b5702d0b64866b08": "Personalizado", "c009c901f3eefe78": "Excluir worktrees de threads excluídas", "431c7cd6d50102b7": "Remove worktrees sem uso quando threads ativas ou arquivadas são excluídas. Worktrees com alterações locais são mantidos.", @@ -11730,7 +11762,6 @@ "4c70e3e7b3e6c493": "Segredos", "79b768229c9ef672": "Manutenção", "54b188d65247e42f": "Labs", - "f41ea186c275b56e": "Sobre", "af4b7734da1d5ce7": "Voz", "4ec62c39ca3192bf": "Versões e issues", "f2bf529f85e05494": "Compartilhamento", @@ -11856,6 +11887,7 @@ "901a823214edc8c4": "telemetria analytics dados de uso rastreamento legal desativar", "82136480255a5106": "OTel OTLP telemetria exportar endpoints logs traces métricas Grafana", "659d081051faf7ff": "logs traces processos histórico de recursos falhas spans cpu memória", + "5eaeacfa9f82051a": "relatório bug problema t3 equipe enviar feedback agentes ferramentas automático quando eu pedir", "f537f91e1ee41d47": "atalhos de teclado teclas de atalho comandos bindings json", "1ba01e7ceed64b95": "janela captura captura de tela", "279b1cceb779ff38": "Incluir texto do app", @@ -12325,7 +12357,6 @@ "0bd41ff995d36a66": "Leitura de cache", "3f0dfe0cb15a3272": "Gravação de cache", "1c9d860be42b1c02": "Saída", - "78344b60f407928e": "Outros", "684e516076de81fe": "Padrão", "3bbcc1b826fef537": "Rápido", "66796576034c18ea": "Ultrarrápido", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 9c355b92fa079..88e2323bac363 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -52,6 +52,26 @@ "eb0f60ef4f92ab7d": "Установите {fj} 0.6 или новее с {fjUrl} и выполните {fjLogin} либо установите {tea} 0.16 или новее с {teaUrl} и выполните {teaLogin} для каждого сервера Forgejo или Gitea.", "d026a85e2e50e675": "Установите GitCafe CLI командой {install}, затем выполните {login}, сохраните токен в настройках или задайте {variable} на сервере.", "22d3c0c48a34b5b3": "Установите TanStack Source CLI командой {install}, затем выполните {login}, сохраните токен в настройках или задайте {variable} на сервере.", + "756c80ad262ef315": "Ожидание в исходном треде", + "d8df14f9905f38eb": "Отправлено", + "e7c59185f8ab3987": "Не отправлено", + "b54ddec9084fa955": "Закрыто без отправки", + "fbaa7ab5da716e50": "Ошибка", + "01bac997ea55272e": "Непонятное поведение", + "0f53bc8f74dfe56a": "Не хватает возможности", + "055560f307e15e30": "Ошибка в документации", + "78344b60f407928e": "Другое", + "f653846a95cd6e8f": "Тип", + "f41ea186c275b56e": "О приложении", + "2f6e4f7cd364da73": "Ожидалось", + "9d11c93d4035de3e": "Произошло", + "c87d0595693704f9": "Что сделано вместо этого", + "d7a4ea6ce5af44e0": "{speaker} · {count} симв.", + "f5114fb9c40fd929": "Вы", + "cd03eb1b84271c02": "Агент", + "bfe1a60f3f9c60fb": "Ход {turn} · {what}", + "dfdaa6255a416140": "Обзор {turns, plural, one {{turns} последнего хода} other {{turns} последних ходов}}, {textTurns, plural, =0 {без текста сообщений} =1 {с текстом сообщений последнего хода} one {с текстом сообщений последнего {textTurns} хода} other {с текстом сообщений последних {textTurns} ходов}}{truncated, select, yes {, сокращено до допустимого размера} other {}}", + "afac52a5cc2dc801": "Не удалось отправить ваш ответ. Попробуйте ещё раз.", "79d776428f4d0650": "Не удалось загрузить файл. Переподключитесь и попробуйте ещё раз.", "3ea34cbb1ca5ba9b": "Предпросмотр отменён.", "7c0af279ecb3da3a": "Потоковый предпросмотр файлов недоступен в этой среде выполнения.", @@ -3581,6 +3601,14 @@ "c53bc5a4b0314342": "Следующее медиа", "2950b1424a3cddf5": "Переподключитесь к этому окружению и откройте медиа снова.", "ef638bf1479a5461": "Окружение вернуло некорректный URL медиа.", + "3ccfbf7e86868c35": "Обратная связь для команды T3", + "4e0710d19dfc2e7e": "Отправить этот отчёт команде T3?", + "87d0ae0723ba75d1": "С этого компьютера отправится только это содержимое. Ничего не будет отправлено, пока вы не нажмёте «Отправить».", + "bf19826f81484328": "Включить переписку", + "260c6b45f52d2f27": "Добавляет текст ваших сообщений и ответов агента за {textTurns, plural, =1 {последний ход} one {последний {textTurns} ход} few {последние {textTurns} хода} many {последние {textTurns} ходов} other {последние {textTurns} хода}}.", + "ddb7e6f8ce99e657": "Отправить отчёт или отклонить его может только тот, кто может запускать агентов на этом компьютере.", + "03c1eb603c112f47": "Не отправлять", + "653405e4ed498d9f": "Отправить", "262955d6eb632f9b": "API буфера обмена недоступен при копировании гостевой ссылки.", "f1a4f2b04cdbb4ef": "Не удалось скопировать гостевую ссылку в буфер обмена.", "cf3490a604e44d31": "Не удалось создать гостевую ссылку.", @@ -3601,7 +3629,6 @@ "abd89e9eefedf11b": "Готово", "18d166056c1ab6ff": "Прекратить общий доступ", "7a2d510eac9e4587": "Срок гостевой ссылки истёк", - "653405e4ed498d9f": "Отправить", "21888e302219891d": "Развёрнутый предпросмотр: {title}", "419719298a7acaea": "Уменьшить", "ed8d5db95359cff4": "Сбросить масштаб", @@ -5805,7 +5832,6 @@ "0061fff77e36bd4f": "Не удалось связаться с сервером.", "04dfdd46e3dd4a2e": "Что-то пошло не так. Повторите попытку.", "084bb2d8127a508d": "Отправлено", - "e7c59185f8ab3987": "Не отправлено", "77c01a15bd36d17c": "Срок действия ссылки истёк или она недействительна", "e0e736810f3cbef2": "Попросите владельца прислать новую ссылку. Каждая ссылка работает в одном браузере.", "c3c53aa46f7330e5": "Срок действия ссылки истёк", @@ -8831,6 +8857,12 @@ "d3866ead082d14e5": "Добавить сочетание клавиш", "d4345c90894a3220": "Открыть keybindings.json", "e56a8d51219efaa0": "Нет сочетаний клавиш по вашему запросу.", + "90a258fff61fd77e": "Выкл.", + "4060244a7079a0d2": "По моему запросу", + "e88c9d8769544731": "Автоматически", + "f29d1dade4dde8aa": "Агенты не отправляют обратную связь команде T3.", + "93c4c53562d30a98": "По вашему запросу агенты показывают краткий отчёт о T3 Code и с вашего одобрения отправляют его команде T3.", + "cd9ee803e8727017": "Агенты также сообщают о проблемах T3 Code, с которыми сталкиваются самостоятельно, например о сбое инструмента T3.", "45fa271ea0e1ac8e": "Бета", "3a678332fc7142f7": "Группирует треды боковой панели по папкам проектов. Закреплённые треды остаются наверху, а отложенные и разобранные — под папками.", "e4e91d155cb6a9b4": "Простая боковая панель (группировка по проектам)", @@ -8844,6 +8876,9 @@ "298c7150a7621c80": "Хосты устройств Simlock", "67937aa49179285e": "На Mac клонировать новые рабочие деревья из копии, закешированной в домашней папке T3, вместо записи каждого файла. Если это невозможно, используется обычный checkout Git. При выключении кеш удаляется.", "f9904f78d3003f58": "Быстрый checkout рабочих деревьев", + "9c2f647882522302": "На выбранных компьютерах используются разные режимы обратной связи от агентов.", + "31bbf7bf8c0a5279": "Обратная связь от агентов", + "d52b3d6bf9f2a013": "Разные", "ec7623deed751c05": [ "Поделитесь тредом с гостем: он смотрит его в браузере в реальном времени и отправляет сообщения, которые вы одобряете. Нужен T3 Connect: войдите и привяжите эту машину в разделе", " ", @@ -9159,7 +9194,6 @@ "0b4779a1825c85bc": "Общее название этой группы проектов на боковой панели и в списках тредов.", "f68cbda4df83d739": "Сбросить название проекта к значению по умолчанию", "56e37b85027e8431": "Значок проекта", - "e88c9d8769544731": "Автоматически", "c99736317da5b1fa": "Сбросить значок проекта к значению по умолчанию", "6afaa3e3739dc570": "Выберите значок проекта", "51651ce45d481a20": "Выберите файл значка проекта", @@ -10135,7 +10169,6 @@ "16bdc70b858c223f": "Сбросить заблаговременные панели к значению по умолчанию", "c5424f09d77138ff": "Когда сжимать неактивный тред Claude больше 200 000 токенов: после вашего возвращения, перед самым истечением его кеша промптов или никогда. Каждый провайдер Claude может это переопределить.", "3e99c5c14f4939c8": "Сбросить сжатие простаивающих тредов к значению по умолчанию", - "d52b3d6bf9f2a013": "Разные", "cd72fe451ba0d6aa": "Новые проекты", "394c3bd0a1782c8e": "Оставьте пустым, чтобы при открытии «Добавить проект» использовался «~/».", "f9b912a818bd869d": "Сбросить базовый каталог для добавления проектов к значению по умолчанию", @@ -11035,7 +11068,6 @@ "4a237f41ce592b7f": "Хранить рабочие деревья этого проекта, пока вы не удалите их вручную.", "00b8ffd8ea6e6a93": "Использовать эти правила для этого проекта.", "72c279824d15a999": "Использовать настройки очистки рабочих деревьев каждой машины.", - "90a258fff61fd77e": "Выкл.", "b5702d0b64866b08": "Свои", "c009c901f3eefe78": "Удалять рабочие деревья вместе с удалёнными тредами", "431c7cd6d50102b7": "Удалять неиспользуемые рабочие деревья при удалении активных или архивных тредов. Рабочие деревья с локальными изменениями сохраняются.", @@ -11731,7 +11763,6 @@ "4c70e3e7b3e6c493": "Секреты", "79b768229c9ef672": "Обслуживание", "54b188d65247e42f": "Эксперименты", - "f41ea186c275b56e": "О приложении", "af4b7734da1d5ce7": "Голос", "4ec62c39ca3192bf": "Контроль версий и issue", "f2bf529f85e05494": "Общий доступ", @@ -11857,6 +11888,7 @@ "901a823214edc8c4": "телеметрия аналитика данные об использовании отслеживание юридическое отказ", "82136480255a5106": "OTel OTLP телеметрия экспорт конечные точки логи трассировки метрики Grafana", "659d081051faf7ff": "логи трассировки процессы история ресурсов сбои спаны cpu память", + "5eaeacfa9f82051a": "отчёт ошибка проблема t3 команда отправить обратная связь агенты инструменты автоматически по моему запросу", "f537f91e1ee41d47": "сочетания клавиш горячие клавиши команды привязки json", "1ba01e7ceed64b95": "окно захват снимок экрана", "279b1cceb779ff38": "Включать текст приложения", @@ -12326,7 +12358,6 @@ "0bd41ff995d36a66": "Чтение кеша", "3f0dfe0cb15a3272": "Запись кеша", "1c9d860be42b1c02": "Вывод", - "78344b60f407928e": "Другое", "684e516076de81fe": "Стандартная", "3bbcc1b826fef537": "Быстрая", "66796576034c18ea": "Сверхбыстрая", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index e8ba1b92298fd..055af1f3a6783 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -52,6 +52,26 @@ "eb0f60ef4f92ab7d": "Installera {fj} 0.6 eller senare från {fjUrl} och kör {fjLogin}, eller installera {tea} 0.16 eller senare från {teaUrl} och kör {teaLogin} för varje Forgejo- eller Gitea-server.", "d026a85e2e50e675": "Installera GitCafe CLI med {install} och kör sedan {login}, spara en token i Inställningar eller ange {variable} på servern.", "22d3c0c48a34b5b3": "Installera TanStack Source CLI med {install} och kör sedan {login}, spara en token i Inställningar eller ange {variable} på servern.", + "756c80ad262ef315": "Väntar i den ursprungliga tråden", + "d8df14f9905f38eb": "Skickat", + "e7c59185f8ab3987": "Inte skickat", + "b54ddec9084fa955": "Stängd utan att skickas", + "fbaa7ab5da716e50": "Bugg", + "01bac997ea55272e": "Otydligt", + "0f53bc8f74dfe56a": "Funktion saknas", + "055560f307e15e30": "Fel i dokumentationen", + "78344b60f407928e": "Övrigt", + "f653846a95cd6e8f": "Typ", + "f41ea186c275b56e": "Om", + "2f6e4f7cd364da73": "Förväntat", + "9d11c93d4035de3e": "Vad som hände", + "c87d0595693704f9": "Gjorde i stället", + "d7a4ea6ce5af44e0": "{speaker} · {count} tecken", + "f5114fb9c40fd929": "Du", + "cd03eb1b84271c02": "Agent", + "bfe1a60f3f9c60fb": "Omgång {turn} · {what}", + "dfdaa6255a416140": "Översikt över {turns, plural, one {{turns} senaste omgång} other {{turns} senaste omgångar}}, {textTurns, plural, =0 {ingen meddelandetext} one {meddelandetext från den senaste omgången} other {meddelandetext från de senaste {textTurns} omgångarna}}{truncated, select, yes {, förkortad för att få plats} other {}}", + "afac52a5cc2dc801": "Det gick inte att skicka ditt svar. Försök igen.", "79d776428f4d0650": "Filen kunde inte läsas in. Återanslut och försök igen.", "3ea34cbb1ca5ba9b": "Förhandsvisningen avbröts.", "7c0af279ecb3da3a": "Strömmande förhandsvisning av filer är inte tillgänglig i den här körmiljön.", @@ -3581,6 +3601,14 @@ "c53bc5a4b0314342": "Nästa media", "2950b1424a3cddf5": "Återanslut till den här miljön och öppna mediet igen.", "ef638bf1479a5461": "Miljön returnerade en ogiltig media-URL.", + "3ccfbf7e86868c35": "Återkoppling till T3-teamet", + "4e0710d19dfc2e7e": "Skicka den här rapporten till T3-teamet?", + "87d0ae0723ba75d1": "Det här är allt som lämnar din dator. Inget skickas förrän du trycker på Skicka.", + "bf19826f81484328": "Ta med konversationen", + "260c6b45f52d2f27": "Lägger till texten i dina meddelanden och agentens svar under {textTurns, plural, one {den senaste omgången} other {de senaste {textTurns} omgångarna}}.", + "ddb7e6f8ce99e657": "Bara den som kan köra agenter på den här datorn kan skicka eller avböja rapporten.", + "03c1eb603c112f47": "Skicka inte", + "653405e4ed498d9f": "Skicka", "262955d6eb632f9b": "Urklipps-API:t är inte tillgängligt vid kopiering av gästlänken.", "f1a4f2b04cdbb4ef": "Kunde inte kopiera gästlänken till urklipp.", "cf3490a604e44d31": "Kunde inte skapa en gästlänk.", @@ -3601,7 +3629,6 @@ "abd89e9eefedf11b": "Klar", "18d166056c1ab6ff": "Sluta dela", "7a2d510eac9e4587": "Gästlänken har gått ut", - "653405e4ed498d9f": "Skicka", "21888e302219891d": "Expanderad förhandsvisning av {title}", "419719298a7acaea": "Zooma ut", "ed8d5db95359cff4": "Återställ zoom", @@ -5806,7 +5833,6 @@ "0061fff77e36bd4f": "Kunde inte nå servern.", "04dfdd46e3dd4a2e": "Något gick fel. Försök igen.", "084bb2d8127a508d": "Skickat", - "e7c59185f8ab3987": "Inte skickat", "77c01a15bd36d17c": "Den här länken har upphört eller är ogiltig", "e0e736810f3cbef2": "Be ägaren om en ny länk. Varje länk fungerar i en webbläsare.", "c3c53aa46f7330e5": "Den här länken har upphört", @@ -8837,6 +8863,12 @@ "d3866ead082d14e5": "Lägg till kortkommando", "d4345c90894a3220": "Öppna keybindings.json", "e56a8d51219efaa0": "Inga kortkommandon matchar sökningen.", + "90a258fff61fd77e": "Av", + "4060244a7079a0d2": "När jag ber om det", + "e88c9d8769544731": "Automatisk", + "f29d1dade4dde8aa": "Agenter skickar ingen återkoppling till T3-teamet.", + "93c4c53562d30a98": "När du ber om det visar agenter en kort rapport om T3 Code och skickar den till T3-teamet om du godkänner den.", + "cd9ee803e8727017": "Agenter rapporterar även problem med T3 Code som de själva stöter på, till exempel ett T3-verktyg som misslyckats.", "45fa271ea0e1ac8e": "Beta", "3a678332fc7142f7": "Gruppera trådar i sidofältet i projektmappar. Fästa trådar ligger överst, och Snoozade och Klara ligger under mapparna.", "e4e91d155cb6a9b4": "Enkelt sidofält (gruppera per projekt)", @@ -8850,6 +8882,9 @@ "298c7150a7621c80": "Simlock-enhetsvärdar", "67937aa49179285e": "På en Mac klonas nya worktrees från en utcheckning som cachas i T3-hemmappen i stället för att varje fil skrivs. Använder Gits vanliga utcheckning när det inte går. Om du stänger av det tas cachen bort.", "f9904f78d3003f58": "Snabb utcheckning av worktree", + "9c2f647882522302": "De valda datorerna använder olika lägen för återkoppling från agenter.", + "31bbf7bf8c0a5279": "Återkoppling från agenter", + "d52b3d6bf9f2a013": "Blandat", "ec7623deed751c05": [ "Dela en tråd med en gäst som följer den live i en webbläsare och skickar meddelanden som du godkänner. Kräver T3 Connect: logga in och länka den här datorn under", " ", @@ -9164,7 +9199,6 @@ "0b4779a1825c85bc": "Det gemensamma namnet för projektgruppen i sidofältet och trådlistorna.", "f68cbda4df83d739": "Återställ projektnamn till standard", "56e37b85027e8431": "Projektikon", - "e88c9d8769544731": "Automatisk", "c99736317da5b1fa": "Återställ projektikon till standard", "6afaa3e3739dc570": "Välj en projektikon", "51651ce45d481a20": "Välj en fil för projektikonen", @@ -10140,7 +10174,6 @@ "16bdc70b858c223f": "Återställ proaktiva paneler till standard", "c5424f09d77138ff": "När en inaktiv Claude-tråd på över 200 000 token ska komprimeras: när du kommer tillbaka, precis innan dess promptcache går ut, eller aldrig. Varje Claude-leverantör kan åsidosätta detta.", "3e99c5c14f4939c8": "Återställ komprimering av inaktiva trådar till standard", - "d52b3d6bf9f2a013": "Blandat", "cd72fe451ba0d6aa": "Nya projekt", "394c3bd0a1782c8e": "Lämna tomt för att använda ”~/” när bläddraren Lägg till projekt öppnas.", "f9b912a818bd869d": "Återställ baskatalog för nya projekt till standard", @@ -11042,7 +11075,6 @@ "4a237f41ce592b7f": "Behåll projektets worktrees tills du tar bort dem manuellt.", "00b8ffd8ea6e6a93": "Använd de här reglerna för projektet.", "72c279824d15a999": "Använd varje dators inställningar för rensning av worktrees.", - "90a258fff61fd77e": "Av", "b5702d0b64866b08": "Anpassat", "c009c901f3eefe78": "Ta bort worktrees med borttagna trådar", "431c7cd6d50102b7": "Ta bort oanvända worktrees när aktiva eller arkiverade trådar tas bort. Worktrees med lokala ändringar behålls.", @@ -11738,7 +11770,6 @@ "4c70e3e7b3e6c493": "Hemligheter", "79b768229c9ef672": "Underhåll", "54b188d65247e42f": "Labs", - "f41ea186c275b56e": "Om", "af4b7734da1d5ce7": "Röst", "4ec62c39ca3192bf": "Versioner och ärenden", "f2bf529f85e05494": "Delning och åtkomst", @@ -11864,6 +11895,7 @@ "901a823214edc8c4": "telemetri analys användningsdata spårning juridiskt avböj", "82136480255a5106": "OTel OTLP telemetri export slutpunkter loggar spår mätvärden Grafana", "659d081051faf7ff": "loggar spår processer resurshistorik fel spans cpu minne", + "5eaeacfa9f82051a": "rapport bugg problem t3 team skicka återkoppling agenter verktyg automatiskt när jag ber om det", "f537f91e1ee41d47": "kortkommandon snabbtangenter kommandon tangentbindningar json", "1ba01e7ceed64b95": "fönster fånga skärmbild", "279b1cceb779ff38": "Ta med apptext", @@ -12333,7 +12365,6 @@ "0bd41ff995d36a66": "Cacheläsning", "3f0dfe0cb15a3272": "Cacheskrivning", "1c9d860be42b1c02": "Utdata", - "78344b60f407928e": "Övrigt", "684e516076de81fe": "Standard", "3bbcc1b826fef537": "Snabb", "66796576034c18ea": "Ultrasnabb", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index deced90c1e6a5..998020844cf79 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -52,6 +52,26 @@ "eb0f60ef4f92ab7d": "请从 {fjUrl} 安装 {fj} 0.6 或更高版本并运行 {fjLogin},或从 {teaUrl} 安装 {tea} 0.16 或更高版本,并为每个 Forgejo 或 Gitea 服务器运行 {teaLogin}。", "d026a85e2e50e675": "请使用 {install} 安装 GitCafe CLI,然后运行 {login}、在设置中保存 token,或在服务器上设置 {variable}。", "22d3c0c48a34b5b3": "请使用 {install} 安装 TanStack Source CLI,然后运行 {login}、在设置中保存 token,或在服务器上设置 {variable}。", + "756c80ad262ef315": "正在原始对话中等待", + "d8df14f9905f38eb": "已发送", + "e7c59185f8ab3987": "未发送", + "b54ddec9084fa955": "已关闭,未发送", + "fbaa7ab5da716e50": "错误", + "01bac997ea55272e": "难以理解", + "0f53bc8f74dfe56a": "缺少功能", + "055560f307e15e30": "文档有误", + "78344b60f407928e": "其他", + "f653846a95cd6e8f": "类型", + "f41ea186c275b56e": "关于", + "2f6e4f7cd364da73": "预期行为", + "9d11c93d4035de3e": "实际情况", + "c87d0595693704f9": "替代做法", + "d7a4ea6ce5af44e0": "{speaker} · {count} 个字符", + "f5114fb9c40fd929": "你", + "cd03eb1b84271c02": "智能体", + "bfe1a60f3f9c60fb": "第 {turn} 轮 · {what}", + "dfdaa6255a416140": "{turns, plural, one {最近 {turns} 轮的概要} other {最近 {turns} 轮的概要}},{textTurns, plural, =0 {不含消息文本} one {包含最后一轮的消息文本} other {包含最近 {textTurns} 轮的消息文本}}{truncated, select, yes {,已缩短以符合长度限制} other {}}", + "afac52a5cc2dc801": "无法发送你的回答。请重试。", "79d776428f4d0650": "无法加载文件。请重新连接后重试。", "3ea34cbb1ca5ba9b": "预览已取消。", "7c0af279ecb3da3a": "此运行时不支持流式文件预览。", @@ -3586,6 +3606,14 @@ "c53bc5a4b0314342": "下一个媒体", "2950b1424a3cddf5": "请重新连接这个环境,然后再打开媒体。", "ef638bf1479a5461": "环境返回了无效的媒体 URL。", + "3ccfbf7e86868c35": "给 T3 团队的反馈", + "4e0710d19dfc2e7e": "将这份报告发送给 T3 团队?", + "87d0ae0723ba75d1": "只有这些内容会从你的机器发送出去。点击“发送”前,不会发送任何内容。", + "bf19826f81484328": "包含对话", + "260c6b45f52d2f27": "添加你在最近 {textTurns} 轮中的消息和智能体回复的文本。", + "ddb7e6f8ce99e657": "只有能在这台机器上运行智能体的人,才能发送或拒绝这份报告。", + "03c1eb603c112f47": "不发送", + "653405e4ed498d9f": "发送", "262955d6eb632f9b": "复制访客链接时剪贴板 API 不可用。", "f1a4f2b04cdbb4ef": "无法将访客链接复制到剪贴板。", "cf3490a604e44d31": "无法创建访客链接。", @@ -3606,7 +3634,6 @@ "abd89e9eefedf11b": "完成", "18d166056c1ab6ff": "停止分享", "7a2d510eac9e4587": "访客链接已过期", - "653405e4ed498d9f": "发送", "21888e302219891d": "展开的 {title} 预览", "419719298a7acaea": "缩小", "ed8d5db95359cff4": "重置缩放", @@ -5812,7 +5839,6 @@ "0061fff77e36bd4f": "无法连接到服务器。", "04dfdd46e3dd4a2e": "出了点问题。请重试。", "084bb2d8127a508d": "已发送", - "e7c59185f8ab3987": "未发送", "77c01a15bd36d17c": "此链接已结束或无效", "e0e736810f3cbef2": "请向所有者索取新链接。每个链接只能在一个浏览器中使用。", "c3c53aa46f7330e5": "此链接已结束", @@ -8847,6 +8873,12 @@ "d3866ead082d14e5": "添加快捷键", "d4345c90894a3220": "打开 keybindings.json", "e56a8d51219efaa0": "没有匹配的快捷键。", + "90a258fff61fd77e": "关闭", + "4060244a7079a0d2": "当我要求时", + "e88c9d8769544731": "自动", + "f29d1dade4dde8aa": "智能体不会向 T3 团队发送反馈。", + "93c4c53562d30a98": "当你要求时,智能体会向你展示一份关于 T3 Code 的简短报告,经你批准后发送给 T3 团队。", + "cd9ee803e8727017": "智能体还会主动报告自己遇到的 T3 Code 问题,例如 T3 工具运行失败。", "45fa271ea0e1ac8e": "测试版", "3a678332fc7142f7": "将侧边栏会话按项目文件夹分组。置顶会话保留在顶部,已暂缓和已收尾会话显示在文件夹下方。", "e4e91d155cb6a9b4": "简洁侧边栏(按项目分组)", @@ -8860,6 +8892,9 @@ "298c7150a7621c80": "Simlock 设备主机", "67937aa49179285e": "在 Mac 上,从缓存在 T3 主目录中的工作副本克隆新的工作树,无需逐个写入每个文件。无法使用时改为 Git 的常规检出。关闭后会删除缓存。", "f9904f78d3003f58": "快速创建工作树", + "9c2f647882522302": "所选机器使用的智能体反馈模式不同。", + "31bbf7bf8c0a5279": "智能体反馈", + "d52b3d6bf9f2a013": "各不相同", "ec7623deed751c05": [ "与访客共享会话,访客可在浏览器中实时观看并发送需经你批准的消息。需要 T3 Connect:请登录并在", " ", @@ -9175,7 +9210,6 @@ "0b4779a1825c85bc": "此项目组在侧边栏和会话列表中共用的名称。", "f68cbda4df83d739": "重置项目名称为默认值", "56e37b85027e8431": "项目图标", - "e88c9d8769544731": "自动", "c99736317da5b1fa": "重置项目图标为默认值", "6afaa3e3739dc570": "选择项目图标", "51651ce45d481a20": "选择项目图标文件", @@ -10148,7 +10182,6 @@ "16bdc70b858c223f": "重置主动面板为默认值", "c5424f09d77138ff": "空闲且超过 200,000 token 的 Claude 会话何时压缩:在你回来后、提示缓存即将过期前,或从不压缩。每个 Claude 提供方都可以单独覆盖此设置。", "3e99c5c14f4939c8": "重置压缩空闲会话为默认值", - "d52b3d6bf9f2a013": "各不相同", "cd72fe451ba0d6aa": "新项目", "394c3bd0a1782c8e": "留空时,“添加项目”浏览器从“~/”打开。", "f9b912a818bd869d": "重置添加项目基础目录为默认值", @@ -11056,7 +11089,6 @@ "4a237f41ce592b7f": "保留此项目的工作树,直到你手动删除。", "00b8ffd8ea6e6a93": "此项目使用以下规则。", "72c279824d15a999": "使用各机器的工作树清理设置。", - "90a258fff61fd77e": "关闭", "b5702d0b64866b08": "自定义", "c009c901f3eefe78": "删除会话时删除工作树", "431c7cd6d50102b7": "删除活跃或已归档会话时,移除不再使用的工作树。保留有本地改动的工作树。", @@ -11755,7 +11787,6 @@ "4c70e3e7b3e6c493": "凭据", "79b768229c9ef672": "维护", "54b188d65247e42f": "实验功能", - "f41ea186c275b56e": "关于", "af4b7734da1d5ce7": "语音", "4ec62c39ca3192bf": "版本控制与 issue", "f2bf529f85e05494": "共享与访问", @@ -11881,6 +11912,7 @@ "901a823214edc8c4": "遥测 分析 用量数据 跟踪 法律 退出", "82136480255a5106": "OTel OTLP 遥测 导出 端点 日志 追踪 指标 Grafana", "659d081051faf7ff": "日志 追踪 进程 资源历史 失败 span cpu 内存", + "5eaeacfa9f82051a": "报告 错误 问题 t3 团队 发送 反馈 智能体 工具 自动 当我要求时", "f537f91e1ee41d47": "键盘 快捷键 热键 命令 绑定 json", "1ba01e7ceed64b95": "窗口 捕获 截图", "279b1cceb779ff38": "包含应用文本", @@ -12351,7 +12383,6 @@ "0bd41ff995d36a66": "缓存读取", "3f0dfe0cb15a3272": "缓存写入", "1c9d860be42b1c02": "输出", - "78344b60f407928e": "其他", "684e516076de81fe": "标准", "3bbcc1b826fef537": "快速", "66796576034c18ea": "极速", diff --git a/apps/web/src/routes/_chat.settings.tsx b/apps/web/src/routes/_chat.settings.tsx index c97534939f743..637bf8f9a2236 100644 --- a/apps/web/src/routes/_chat.settings.tsx +++ b/apps/web/src/routes/_chat.settings.tsx @@ -52,22 +52,41 @@ function SettingsScopeBoundary({ pathname, children }: { pathname: string; child const m = useMessages(); const hash = useLocation({ select: (location) => location.hash }); const searchTarget = getSettingsSearchTargetScope(hash); - const autoSettlementAvailability = searchTarget?.requiresThreadAutoSettlement - ? getThreadAutoSettlementSearchAvailability(environments, scope) + const agentFeedbackAvailability = searchTarget?.agentFeedbackOnly + ? { + eligibleEnvironmentIds: environments + .filter( + (environment) => + environment.connection.phase === "connected" && + environment.serverConfig?.environment.capabilities.agentFeedback === true, + ) + .map((environment) => environment.environmentId), + isTargetAvailable: + connectedEnvironments.length > 0 && + connectedEnvironments.every( + (environment) => + environment.serverConfig?.environment.capabilities.agentFeedback === true, + ), + } : null; + const targetAvailability = + agentFeedbackAvailability ?? + (searchTarget?.requiresThreadAutoSettlement + ? getThreadAutoSettlementSearchAvailability(environments, scope) + : null); if ( scope.kind !== "unavailable" && searchTarget && - autoSettlementAvailability && - !autoSettlementAvailability.isTargetAvailable + targetAvailability && + !targetAvailability.isTargetAvailable ) { return ( - {autoSettlementAvailability.eligibleEnvironmentIds.length > 0 + {targetAvailability.eligibleEnvironmentIds.length > 0 ? gt("{title} requires a supporting environment. Choose one to continue.", { title: m(searchTarget.title), }) diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts index 5196ee43458d8..99a1fc62a0bc3 100644 --- a/apps/web/src/session-logic.ts +++ b/apps/web/src/session-logic.ts @@ -245,6 +245,7 @@ const STANDALONE_V2_ITEM_TYPES = new Set Labs**: + +- **Off**, the default: agents do not see the feedback tools, and `t3 feedback` stops with a + message pointing to Labs. +- **When I ask**: agents send a report only when you ask them to, about anything in T3 Code. +- **Automatic**: agents also report T3 Code problems they hit on their own, such as a T3 tool that + failed and made them find another way. These reports carry no outline and no message text, and + go out without asking you. `t3 feedback --kind bug --subject "t3 thread send" --expected "…" --actual "…"` + sends one the same way, so it works only in this mode. + +When you ask your agent for a report, in either mode, T3 Code shows it in the thread as a card +with exactly what would leave your machine, and sends it only if you press **Send**. The agent +carries on without waiting and never learns your answer. The card stays open until you answer it, +even after the turn ends or the server restarts; **Don't send** sends nothing, and the agent is +told not to send it another way. Only someone who can run agents on that machine can answer the +card; people on a guest link cannot. + +Each report has the kind of problem, the T3 tool or command it concerns (or `general`), and up to +300 characters each of expected behavior, actual behavior, and workaround, written by the agent, +which is told not to quote your messages or code. The agent also says how many recent turns the +problem spans. A report you approved carries an outline of those turns, and of at least the last 5, +from when the agent asked: who spoke, how long each message was, and which tools ran, whether they +worked, and how long they took. The outline has no text. Tools from your other MCP servers appear +only as `mcp`. Turn on **Include the conversation** in the card to attach the text of your +messages and the agent's replies in the turns the problem spans, up to 1,000 characters per +message and 16 KB in all, oldest text dropped first; the card shows that text before you send it. +To change a report, such as the turns it covers, ask the agent in the chat: it shows a new card, +and you can decline the old one. Tool inputs and outputs, files, and attachments are never sent. An agent can +show you at most 3 report cards and send 3 reports on its own per turn, and `t3 feedback` can +send at most 10 an hour. + +Before anything is saved, T3 Code removes file paths (when text mentions one, the rest of that line +goes with it), your user name, machine name, project title, branch, and git remote, and anything +that looks like a key, token, email address, or URL with a password. It cannot recognise your code +or a name written in a sentence, so only include the conversation when it holds nothing you would +not send. Reports from agents also name the provider, and the model when it is from the provider's +public model list. No thread IDs or project IDs are sent. + +Reports are saved on your machine first, and a declined one is not saved at all; its card keeps +only what you would have sent without the conversation. When product usage +data is turned off, saved reports stay there and are not sent. `t3 feedback list` shows recent +reports, the thread each came from, and a line for each outline; `t3 feedback list --json` shows +exactly what each one holds. ## Relay connection diagnostics diff --git a/evals/mcp-tool-use/cases/agent-feedback.ndjson b/evals/mcp-tool-use/cases/agent-feedback.ndjson new file mode 100644 index 0000000000000..df85866b2ed91 --- /dev/null +++ b/evals/mcp-tool-use/cases/agent-feedback.ndjson @@ -0,0 +1,18 @@ +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-12"}, "id": "feedback-on-reports-workaround", "kind": "bad", "pattern": "works around a failing T3 tool without reporting it", "experience": "With agent feedback on, t3_thread_read returned no items for a completed thread, the agent fell back to `t3 thread show`, and nobody heard about it.", "rule": "Agent feedback is on and a T3 tool failed, so the agent falls back and reports it with t3_feedback.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "priorTurns": [{"role": "user", "text": "What did the docs audit thread conclude? Its id is 5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30. Summarize it for me."}, {"role": "assistant", "toolCalls": [{"tool": "t3_thread_read", "input": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30"}, "result": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Docs audit", "status": "completed", "items": [], "nextPosition": null}}, {"tool": "t3_thread_read", "input": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "view": "activity", "limit": 20}, "result": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Docs audit", "status": "completed", "items": [], "nextPosition": null}}, {"tool": "Bash", "input": {"command": "t3 thread show 5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30"}, "result": "Docs audit (completed)\n\nassistant: Audit done. docs/user/remote.md has 3 broken links (lines 12, 40, 88). docs/user/mobile.md still shows the old pairing command. I opened no PR."}]}], "world": {"repo": "acme/app", "branch": "main", "agentFeedback": "auto"}}, "prompt": "", "maxSteps": 8, "expect": {"calls": [{"tool": "t3_feedback", "args": {"subject": "~t3_thread_read"}, "success": true}], "callsMustNot": [{"tool": "t3_feedback", "args": {"userRequested": true}}]}, "notes": "Resumes right after the workaround succeeded."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-12"}, "id": "feedback-on-project-failure-guard", "kind": "guard", "pattern": "reports problems outside T3 Code", "experience": "With agent feedback on, a project test failure and a gh auth error are the user's own problems, not T3 Code's.", "rule": "Only T3 Code problems are reported: never the user's code or other tools.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "world": {"repo": "acme/app", "branch": "docs/fix-links", "agentFeedback": "auto"}, "priorTurns": [{"role": "user", "text": "Fix the failing link test and open a PR for this branch."}, {"role": "assistant", "toolCalls": [{"tool": "Bash", "input": {"command": "pnpm test"}, "result": "FAIL src/links.test.ts > resolves relative links\nAssertionError: expected '/docs/a' to be '/docs/a/'\nExit code 1"}, {"tool": "Edit", "input": {"file_path": "/home/user/acme/app/src/links.ts", "old_string": "return path;", "new_string": "return path.endsWith('/') ? path : `${path}/`;"}, "result": "The file /home/user/acme/app/src/links.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "pnpm test"}, "result": "Test Files 12 passed (12)\n Tests 148 passed (148)"}, {"tool": "Bash", "input": {"command": "git commit -am 'fix: keep trailing slash on relative links' && gh pr create --fill"}, "result": "[docs/fix-links 3e1f0a2] fix: keep trailing slash on relative links\n 1 file changed, 1 insertion(+), 1 deletion(-)\nHTTP 401: Bad credentials (https://api.github.com/graphql)\nTry authenticating with: gh auth login\nExit code 1"}, {"tool": "Bash", "input": {"command": "git push -u origin docs/fix-links"}, "result": "remote: Create a pull request for 'docs/fix-links' on GitHub by visiting:\nremote: https://github.com/acme/app/pull/new/docs/fix-links\nbranch 'docs/fix-links' set up to track 'origin/docs/fix-links'."}]}]}, "prompt": "", "maxSteps": 6, "expect": {"callsMustNot": [{"tool": "t3_feedback"}, {"tool": "t3_environment_preferences_update"}]}, "notes": "Resumes after the push. The gh failure and the test failure are not T3 Code's."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-17", "finding": "Two of five agents asked to send T3 feedback declined it in real threads."}, "id": "feedback-on-user-asks-tool-gap", "kind": "bad", "pattern": "declines to send feedback the user asked for", "experience": "Mid-task, the user asked the agent to tell the T3 team about a T3 tool gap, and the agent said it could only report T3 tool failures.", "rule": "When the user asks to send feedback to the T3 team, the agent sends one report marked userRequested.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "world": {"repo": "acme/app", "branch": "main", "agentFeedback": "auto"}, "priorTurns": [{"role": "user", "text": "Find the thread that worked on the docs/fix-links branch."}, {"role": "assistant", "toolCalls": [{"tool": "t3_thread_list", "input": {"titleContains": "links"}, "result": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "status": "completed", "branch": "docs/fix-links"}, {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Link checker CI", "status": "completed", "branch": "ci/link-check"}], "nextCursor": null}}], "text": "t3_thread_list has no branch filter, so I searched titles for \"links\". The thread on docs/fix-links is \"Fix relative links\" (5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30)."}], "mocks": {"t3_thread_read": {"thread": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "link": "", "status": "completed"}, "items": [{"position": 1, "createdBy": "user", "text": "Relative links lose their trailing slash. Fix it."}, {"position": 2, "createdBy": "assistant", "text": "Fixed: relative links now keep their trailing slash. Added a test for it; all tests pass. Committed on docs/fix-links."}], "nextPosition": null, "hasMore": false}, "t3_thread_list": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "status": "completed", "branch": "docs/fix-links"}, {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Link checker CI", "status": "completed", "branch": "ci/link-check"}], "nextCursor": null}}}, "prompt": "Thanks. t3_thread_list really should let you filter by branch. Please tell the T3 team about that, then summarize what that thread changed.", "maxSteps": 8, "expect": {"calls": [{"tool": "t3_feedback", "args": {"subject": "~t3_thread_list", "userRequested": true}, "success": true}], "maxCalls": {"t3_feedback": 1}}, "notes": "The user asks in the same message as more work. The thread tools are mocked so the follow-up finds the thread it expects."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-17", "finding": "Two of five agents asked to send T3 feedback declined it in real threads."}, "id": "feedback-on-user-asks-conversation", "kind": "bad", "pattern": "declines feedback about how the conversation went", "experience": "The user asked the agent to send the T3 team feedback that the session went badly, and the agent said agent feedback only covers T3 tool problems.", "rule": "Feedback the user asks for can be about anything in T3 Code; it uses subject general and leaves out the user's code and paths.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "world": {"repo": "acme/app", "branch": "docs/fix-links", "agentFeedback": "auto"}, "priorTurns": [{"role": "user", "text": "Fix the trailing slash bug in src/links.ts. Don't ask me anything, just make the fix and run the tests."}, {"role": "assistant", "text": "I found the bug in /home/user/acme/app/src/links.ts: relative links drop their trailing slash. Should I change `return path;` to keep it?"}, {"role": "user", "text": "Yes. I said just do it."}, {"role": "assistant", "toolCalls": [{"tool": "Edit", "input": {"file_path": "/home/user/acme/app/src/links.ts", "old_string": "return path;", "new_string": "return path.endsWith('/') ? path : `${path}/`;"}, "result": "The file /home/user/acme/app/src/links.ts has been updated successfully."}], "text": "Edited src/links.ts. Do you want me to run the tests now?"}, {"role": "user", "text": "Yes, run them."}, {"role": "assistant", "toolCalls": [{"tool": "Bash", "input": {"command": "pnpm test"}, "result": "Test Files 12 passed (12)\n Tests 148 passed (148)"}], "text": "All 148 tests pass. Should I commit this?"}]}, "prompt": "Honestly this went badly. I told you up front not to ask me anything and you stopped for confirmation three times. Please send that to the T3 team as feedback.", "maxSteps": 6, "expect": {"calls": [{"tool": "t3_feedback", "args": {"subject": "general", "userRequested": true}, "success": true}], "maxCalls": {"t3_feedback": 1}, "callsMustNot": [{"tool": "t3_feedback", "args": {"expected": "~/home/user"}}, {"tool": "t3_feedback", "args": {"expected": "~links.ts"}}, {"tool": "t3_feedback", "args": {"expected": "~endsWith"}}, {"tool": "t3_feedback", "args": {"actual": "~/home/user"}}, {"tool": "t3_feedback", "args": {"actual": "~links.ts"}}, {"tool": "t3_feedback", "args": {"actual": "~endsWith"}}, {"tool": "t3_feedback", "args": {"workaround": "~/home/user"}}, {"tool": "t3_feedback", "args": {"workaround": "~links.ts"}}, {"tool": "t3_feedback", "args": {"workaround": "~endsWith"}}]}, "notes": "About the agent's conduct in T3 Code, not one tool. The report must not carry the file path or code."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-17", "finding": "In real threads, agents with agent feedback on rarely reported T3 tool problems on their own."}, "id": "feedback-auto-midtask-search", "kind": "bad", "pattern": "a T3 tool fails mid-task and the agent moves on without reporting", "experience": "t3_thread_search failed with an internal error while the agent was gathering context for a refactor; it found the thread another way and went straight on with the refactor.", "rule": "In automatic mode, a T3 tool failure the agent worked around is reported once, even when more work follows.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "world": {"repo": "acme/app", "branch": "main", "agentFeedback": "auto"}, "priorTurns": [{"role": "user", "text": "Check what the auth refactor thread decided about session tokens, then rename getSession to readSession across src/, run the tests, and commit."}, {"role": "assistant", "toolCalls": [{"tool": "t3_thread_search", "input": {"query": "session tokens"}, "result": {"code": "orchestration_error", "message": "Thread search failed: SQLITE_ERROR: no such column: rank"}}, {"tool": "t3_thread_list", "input": {"titleContains": "auth"}, "result": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Auth refactor", "status": "completed", "branch": "refactor/auth"}], "nextCursor": null}}, {"tool": "t3_thread_read", "input": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30"}, "result": {"thread": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Auth refactor", "status": "completed"}, "items": [{"position": 1, "createdBy": "user", "text": "How should we store session tokens?"}, {"position": 2, "createdBy": "assistant", "text": "Decision: session tokens live in an httpOnly cookie, never localStorage. getSession reads the cookie."}], "nextPosition": null, "hasMore": false}}, {"tool": "Bash", "input": {"command": "grep -rn getSession src/"}, "result": "src/auth/session.ts:4:export function getSession(req: Request) {\nsrc/routes/me.ts:2:import { getSession } from '../auth/session';\nsrc/routes/me.ts:7: const session = getSession(req);"}]}], "mocks": {"t3_thread_search": {"code": "orchestration_error", "message": "Thread search failed: SQLITE_ERROR: no such column: rank"}, "t3_thread_list": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Auth refactor", "status": "completed", "branch": "refactor/auth"}], "nextCursor": null}, "t3_thread_read": {"thread": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Auth refactor", "status": "completed"}, "items": [{"position": 1, "createdBy": "user", "text": "How should we store session tokens?"}, {"position": 2, "createdBy": "assistant", "text": "Decision: session tokens live in an httpOnly cookie, never localStorage. getSession reads the cookie."}], "nextPosition": null, "hasMore": false}}}, "prompt": "", "maxSteps": 12, "expect": {"calls": [{"tool": "t3_feedback", "args": {"subject": "~t3_thread_search"}, "success": true}], "maxCalls": {"t3_feedback": 1}, "callsMustNot": [{"tool": "t3_feedback", "args": {"userRequested": true}}]}, "notes": "Resumes after the workaround, with the rename, tests and commit still to do. T3's thread tools answer as they did."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-17", "finding": "In real threads, agents with agent feedback on rarely reported T3 tool problems on their own."}, "id": "feedback-auto-wrong-result", "kind": "bad", "pattern": "a T3 tool returns a wrong result and the agent trusts git instead without reporting", "experience": "t3_worktree_status said the thread had no worktree while git showed the agent working in one; the agent used git's answer and said nothing.", "rule": "In automatic mode, a T3 tool that returns a wrong result, not only an error, is reported once.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "world": {"repo": "acme/app", "branch": "feat/search", "agentFeedback": "auto"}, "priorTurns": [{"role": "user", "text": "Hand this work off to the main checkout so I can test it there."}, {"role": "assistant", "toolCalls": [{"tool": "t3_worktree_status", "input": {}, "result": {"attached": false, "path": null, "branch": null, "projectRoot": "/home/user/acme/app", "startFromOrigin": true}}, {"tool": "Bash", "input": {"command": "pwd && git rev-parse --show-toplevel && git worktree list"}, "result": "/home/user/.t3/worktrees/app/feat-search\n/home/user/.t3/worktrees/app/feat-search\n/home/user/acme/app 3e1f0a2 [main]\n/home/user/.t3/worktrees/app/feat-search 9c4d2b1 [feat/search]"}], "text": "t3_worktree_status says this thread has no worktree, but git shows I'm in /home/user/.t3/worktrees/app/feat-search on feat/search. I'll go by git."}], "mocks": {"t3_worktree_handoff": {"ok": true, "from": "worktree", "to": "local", "branch": "feat/search"}, "t3_worktree_status": {"attached": false, "path": null, "branch": null, "projectRoot": "/home/user/acme/app", "startFromOrigin": true}}}, "prompt": "Ok, go ahead with the handoff.", "maxSteps": 12, "expect": {"calls": [{"tool": "t3_feedback", "args": {"subject": "~t3_worktree_status"}, "success": true}], "maxCalls": {"t3_feedback": 1}, "callsMustNot": [{"tool": "t3_feedback", "args": {"userRequested": true}}]}, "notes": "The user's message is about the handoff, not about feedback."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-17", "finding": "In real threads, agents with agent feedback on rarely reported T3 tool problems on their own."}, "id": "feedback-auto-user-corrects", "kind": "bad", "pattern": "the user corrects the agent about T3 Code and nothing is reported", "experience": "The agent told the user it could not message another thread; the user pointed it at t3_thread_send.", "rule": "In automatic mode, when the user corrects the agent about how T3 Code works, the agent reports it once, without marking it user-requested.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "world": {"repo": "acme/app", "branch": "main", "agentFeedback": "auto"}, "priorTurns": [{"role": "user", "text": "Send this summary to the Release notes thread: search now ranks exact title matches first."}, {"role": "assistant", "text": "I can't post into another T3 thread from here. Here is the text so you can paste it there: \"Search now ranks exact title matches first.\""}], "mocks": {"t3_thread_send": {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "delivery": "started", "link": ""}, "t3_thread_read": {"thread": {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Release notes", "status": "idle"}, "items": [{"position": 1, "createdBy": "user", "text": "Collect release notes for 1.9 here."}], "nextPosition": null, "hasMore": false}, "t3_thread_list": {"threads": [{"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Release notes", "status": "idle"}], "nextCursor": null}, "t3_thread_search": {"matches": [{"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Release notes", "status": "idle"}]}}}, "prompt": "You can, T3 Code has t3_thread_send for that. The Release notes thread id is 8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b. Send it.", "maxSteps": 10, "expect": {"calls": [{"tool": "t3_thread_send", "success": true}, {"tool": "t3_feedback", "success": true}], "maxCalls": {"t3_feedback": 1}, "callsMustNot": [{"tool": "t3_feedback", "args": {"userRequested": true}}]}, "notes": "The user corrects the agent but does not ask for feedback."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-17", "finding": "In real threads, agents with agent feedback on rarely reported T3 tool problems on their own."}, "id": "feedback-auto-missing-capability", "kind": "bad", "pattern": "the agent finds a T3 capability missing and only tells the user", "experience": "Asked for the thread's token usage, the agent found no T3 tool that reports it and told the user so.", "rule": "In automatic mode, a capability the agent looked for in T3 Code and could not find is reported once as missing_capability.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "world": {"repo": "acme/app", "branch": "main", "agentFeedback": "auto"}, "priorTurns": [{"role": "user", "text": "How many tokens has this thread used so far?"}, {"role": "assistant", "toolCalls": [{"tool": "t3_thread_read", "input": {}, "result": {"thread": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Search ranking", "status": "running"}, "items": [{"position": 1, "createdBy": "user", "text": "How many tokens has this thread used so far?"}], "nextPosition": null, "hasMore": false}}, {"tool": "t3_environment_read", "input": {}, "result": {"environmentId": "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee", "label": "Workstation", "version": "1.9.0", "providers": [{"driver": "codex", "status": "ready"}]}}]}], "mocks": {"t3_thread_read": {"thread": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Search ranking", "status": "running"}, "items": [{"position": 1, "createdBy": "user", "text": "How many tokens has this thread used so far?"}], "nextPosition": null, "hasMore": false}, "t3_environment_read": {"environmentId": "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee", "label": "Workstation", "version": "1.9.0", "providers": [{"driver": "codex", "status": "ready"}]}}}, "prompt": "", "maxSteps": 6, "expect": {"calls": [{"tool": "t3_feedback", "args": {"kind": "missing_capability"}, "success": true}], "maxCalls": {"t3_feedback": 1}, "callsMustNot": [{"tool": "t3_feedback", "args": {"userRequested": true}}]}, "notes": "Resumes after both reads came back without usage."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-17", "finding": "In real threads, agents with agent feedback on rarely reported T3 tool problems on their own."}, "id": "feedback-auto-other-mcp-guard", "kind": "guard", "pattern": "reports another MCP server's failure as T3 feedback", "experience": "A Linear MCP tool failed and the agent used the GitHub CLI instead. That is not a T3 Code problem.", "rule": "Only T3 Code problems are reported: never other tools or MCP servers.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "world": {"repo": "acme/app", "branch": "fix/search-ranking", "agentFeedback": "auto"}, "priorTurns": [{"role": "user", "text": "Read issue ENG-142 and open a branch for it."}, {"role": "assistant", "toolCalls": [{"tool": "mcp__linear__get_issue", "input": {"id": "ENG-142"}, "result": {"error": "Linear API error: 502 Bad Gateway"}}, {"tool": "Bash", "input": {"command": "gh issue view 142 --repo acme/app"}, "result": "Search results show stale titles #142\nopen acme/app\nExact title matches should rank above partial ones."}, {"tool": "Bash", "input": {"command": "git switch -c fix/search-ranking"}, "result": "Switched to a new branch 'fix/search-ranking'"}]}], "mocks": {"read_issue": {"url": "https://linear.app/acme/issue/ENG-142/search-results-show-stale-titles", "displayKey": "ENG-142", "title": "Search results show stale titles", "state": "open", "body": "Exact title matches should rank above partial ones."}, "list_issues": {"issues": [{"url": "https://linear.app/acme/issue/ENG-142/search-results-show-stale-titles", "displayKey": "ENG-142", "title": "Search results show stale titles", "state": "open"}], "nextCursors": {}, "errors": []}}}, "prompt": "", "maxSteps": 6, "expect": {"callsMustNot": [{"tool": "t3_feedback"}]}, "notes": "Resumes after the fallback. The Linear failure belongs to another MCP server; T3's own issue tools answer normally."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-17", "finding": "Gabriel: agent feedback gets Off, When I ask, and Automatic modes, and requested reports can carry the conversation."}, "id": "feedback-on-request-no-unprompted", "kind": "guard", "pattern": "reports unprompted while agent feedback only allows requested reports", "experience": "With agent feedback set to When I ask, a T3 tool failed and the agent fell back; nobody asked for a report.", "rule": "In When I ask mode, the agent sends no report the user did not ask for.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "priorTurns": [{"role": "user", "text": "What did the docs audit thread conclude? Its id is 5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30. Summarize it for me."}, {"role": "assistant", "toolCalls": [{"tool": "t3_thread_read", "input": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30"}, "result": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Docs audit", "status": "completed", "items": [], "nextPosition": null}}, {"tool": "t3_thread_read", "input": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "view": "activity", "limit": 20}, "result": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Docs audit", "status": "completed", "items": [], "nextPosition": null}}, {"tool": "Bash", "input": {"command": "t3 thread show 5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30"}, "result": "Docs audit (completed)\n\nassistant: Audit done. docs/user/remote.md has 3 broken links (lines 12, 40, 88). docs/user/mobile.md still shows the old pairing command. I opened no PR."}]}], "world": {"repo": "acme/app", "branch": "main", "agentFeedback": "on-request"}}, "prompt": "", "maxSteps": 8, "expect": {"callsMustNot": [{"tool": "t3_feedback"}]}, "notes": "The workaround case in When I ask mode."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-17", "finding": "Gabriel: agent feedback gets Off, When I ask, and Automatic modes, and requested reports can carry the conversation."}, "id": "feedback-on-request-user-asks", "kind": "bad", "pattern": "declines to send feedback the user asked for", "experience": "Mid-task, the user asked the agent to tell the T3 team about a T3 tool gap, and the agent said it could only report T3 tool failures.", "rule": "In When I ask mode, the agent still sends the report the user asks for, marked userRequested.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "world": {"repo": "acme/app", "branch": "main", "agentFeedback": "on-request"}, "priorTurns": [{"role": "user", "text": "Find the thread that worked on the docs/fix-links branch."}, {"role": "assistant", "toolCalls": [{"tool": "t3_thread_list", "input": {"titleContains": "links"}, "result": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "status": "completed", "branch": "docs/fix-links"}, {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Link checker CI", "status": "completed", "branch": "ci/link-check"}], "nextCursor": null}}], "text": "t3_thread_list has no branch filter, so I searched titles for \"links\". The thread on docs/fix-links is \"Fix relative links\" (5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30)."}], "mocks": {"t3_thread_read": {"thread": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "link": "", "status": "completed"}, "items": [{"position": 1, "createdBy": "user", "text": "Relative links lose their trailing slash. Fix it."}, {"position": 2, "createdBy": "assistant", "text": "Fixed: relative links now keep their trailing slash. Added a test for it; all tests pass. Committed on docs/fix-links."}], "nextPosition": null, "hasMore": false}, "t3_thread_list": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "status": "completed", "branch": "docs/fix-links"}, {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Link checker CI", "status": "completed", "branch": "ci/link-check"}], "nextCursor": null}}}, "prompt": "Thanks. t3_thread_list really should let you filter by branch. Please tell the T3 team about that, then summarize what that thread changed.", "maxSteps": 8, "expect": {"calls": [{"tool": "t3_feedback", "args": {"subject": "~t3_thread_list", "userRequested": true}, "success": true}], "maxCalls": {"t3_feedback": 1}}, "notes": "The tool-gap request in When I ask mode."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-19", "finding": "Julius: the card no longer blocks the turn, and the user, not the agent, chooses in the card whether to include the conversation."}, "id": "feedback-user-asks-include-conversation", "kind": "bad", "pattern": "pastes the conversation into the report, or claims it was included", "experience": "The user asked the agent to send feedback about the session and to include the conversation so the T3 team could see it.", "rule": "When the user asks to include the conversation, the agent sends one report with userRequested, leaves the conversation out of its fields, and leaves the choice to the card.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "world": {"repo": "acme/app", "branch": "docs/fix-links", "agentFeedback": "auto"}, "priorTurns": [{"role": "user", "text": "Fix the trailing slash bug in src/links.ts. Don't ask me anything, just make the fix and run the tests."}, {"role": "assistant", "text": "I found the bug in /home/user/acme/app/src/links.ts: relative links drop their trailing slash. Should I change `return path;` to keep it?"}, {"role": "user", "text": "Yes. I said just do it."}, {"role": "assistant", "toolCalls": [{"tool": "Edit", "input": {"file_path": "/home/user/acme/app/src/links.ts", "old_string": "return path;", "new_string": "return path.endsWith('/') ? path : `${path}/`;"}, "result": "The file /home/user/acme/app/src/links.ts has been updated successfully."}], "text": "Edited src/links.ts. Do you want me to run the tests now?"}, {"role": "user", "text": "Yes, run them."}, {"role": "assistant", "toolCalls": [{"tool": "Bash", "input": {"command": "pnpm test"}, "result": "Test Files 12 passed (12)\n Tests 148 passed (148)"}], "text": "All 148 tests pass. Should I commit this?"}]}, "prompt": "This went badly: I told you not to ask me anything and you stopped for confirmation three times. Send that to the T3 team, and include our conversation so they can see what happened.", "maxSteps": 6, "expect": {"calls": [{"tool": "t3_feedback", "args": {"userRequested": true}, "success": true}], "maxCalls": {"t3_feedback": 1}, "callsMustNot": [{"tool": "t3_feedback", "args": {"expected": "~/home/user"}}, {"tool": "t3_feedback", "args": {"expected": "~links.ts"}}, {"tool": "t3_feedback", "args": {"expected": "~endsWith"}}, {"tool": "t3_feedback", "args": {"actual": "~/home/user"}}, {"tool": "t3_feedback", "args": {"actual": "~links.ts"}}, {"tool": "t3_feedback", "args": {"actual": "~endsWith"}}, {"tool": "t3_feedback", "args": {"workaround": "~/home/user"}}, {"tool": "t3_feedback", "args": {"workaround": "~links.ts"}}, {"tool": "t3_feedback", "args": {"workaround": "~endsWith"}}, {"tool": "t3_feedback", "args": {"expected": "~don't ask me anything"}}, {"tool": "t3_feedback", "args": {"expected": "~I said just do it"}}, {"tool": "t3_feedback", "args": {"actual": "~don't ask me anything"}}, {"tool": "t3_feedback", "args": {"actual": "~I said just do it"}}, {"tool": "t3_feedback", "args": {"workaround": "~don't ask me anything"}}, {"tool": "t3_feedback", "args": {"workaround": "~I said just do it"}}], "textMustNot": ["\\b(?:included|attached|added) (?:the |our |your )?(?:conversation|chat|transcript)\\b", "\\b(?:[Cc]onversation|[Tt]ranscript) (?:is|was|has been) (?:included|attached)\\b", "\\b(?:I've|I have|I) (?:sent|submitted|filed)\\b", "(?", "status": "completed"}, "items": [{"position": 1, "createdBy": "user", "text": "Relative links lose their trailing slash. Fix it."}, {"position": 2, "createdBy": "assistant", "text": "Fixed: relative links now keep their trailing slash. Added a test for it; all tests pass. Committed on docs/fix-links."}], "nextPosition": null, "hasMore": false}, "t3_thread_list": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "status": "completed", "branch": "docs/fix-links"}, {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Link checker CI", "status": "completed", "branch": "ci/link-check"}], "nextCursor": null}}}, "prompt": "t3_thread_list really should let you filter by branch. Please tell the T3 team about that.", "maxSteps": 8, "expect": {"calls": [{"tool": "t3_feedback", "args": {"userRequested": true}, "success": true}], "maxCalls": {"t3_feedback": 1}, "shellMustNot": ["\\bt3\\s+feedback\\b"], "textMustNot": ["\\b(?:I've|I have|I) (?:sent|submitted|filed)\\b", "(?", "status": "completed"}, "items": [{"position": 1, "createdBy": "user", "text": "Relative links lose their trailing slash. Fix it."}, {"position": 2, "createdBy": "assistant", "text": "Fixed: relative links now keep their trailing slash. Added a test for it; all tests pass. Committed on docs/fix-links."}], "nextPosition": null, "hasMore": false}, "t3_thread_list": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "status": "completed", "branch": "docs/fix-links"}, {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Link checker CI", "status": "completed", "branch": "ci/link-check"}], "nextCursor": null}}}, "prompt": "Did the T3 team get it?", "maxSteps": 8, "expect": {"callsMustNot": [{"tool": "t3_feedback"}], "shellMustNot": ["\\bt3\\s+feedback\\b"], "textMustNot": ["\\b(?:I've|I have|I) (?:sent|submitted|filed)\\b", "(?", "status": "completed"}, "items": [{"position": 1, "createdBy": "user", "text": "Relative links lose their trailing slash. Fix it."}, {"position": 2, "createdBy": "assistant", "text": "Fixed: relative links now keep their trailing slash. Added a test for it; all tests pass. Committed on docs/fix-links."}], "nextPosition": null, "hasMore": false}, "t3_thread_list": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "status": "completed", "branch": "docs/fix-links"}, {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Link checker CI", "status": "completed", "branch": "ci/link-check"}], "nextCursor": null}}}, "prompt": "About finding that thread two turns ago: t3_thread_list made you guess from titles. Report that to the T3 team.", "maxSteps": 6, "expect": {"calls": [{"tool": "t3_feedback", "args": {"userRequested": true, "turns": ">=3"}, "success": true}], "maxCalls": {"t3_feedback": 1}, "callsMustNot": [{"tool": "t3_feedback", "args": {"turns": ">=5"}}], "textMustNot": ["\\b(?:I've|I have|I) (?:sent|submitted|filed)\\b", "(?", "status": "completed"}, "items": [{"position": 1, "createdBy": "user", "text": "Relative links lose their trailing slash. Fix it."}, {"position": 2, "createdBy": "assistant", "text": "Fixed: relative links now keep their trailing slash. Added a test for it; all tests pass. Committed on docs/fix-links."}], "nextPosition": null, "hasMore": false}, "t3_thread_list": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "status": "completed", "branch": "docs/fix-links"}, {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Link checker CI", "status": "completed", "branch": "ci/link-check"}], "nextCursor": null}}}, "prompt": "Send the T3 team a feature request: thread search should be able to filter by branch.", "maxSteps": 6, "expect": {"calls": [{"tool": "t3_feedback", "args": {"userRequested": true, "turns": 1}, "success": true}], "maxCalls": {"t3_feedback": 1}, "textMustNot": ["\\b(?:I've|I have|I) (?:sent|submitted|filed)\\b", "(?", "status": "completed"}, "items": [{"position": 1, "createdBy": "user", "text": "Relative links lose their trailing slash. Fix it."}, {"position": 2, "createdBy": "assistant", "text": "Fixed: relative links now keep their trailing slash. Added a test for it; all tests pass. Committed on docs/fix-links."}], "nextPosition": null, "hasMore": false}, "t3_thread_list": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "status": "completed", "branch": "docs/fix-links"}, {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Link checker CI", "status": "completed", "branch": "ci/link-check"}], "nextCursor": null}}}, "prompt": "Make it cover the last four turns instead, so they see the work before it too.", "maxSteps": 6, "expect": {"calls": [{"tool": "t3_feedback", "args": {"userRequested": true, "turns": ">=4"}, "success": true}], "maxCalls": {"t3_feedback": 1}, "callsMustNot": [{"tool": "t3_feedback", "args": {"turns": ">=6"}}], "textMustNot": ["\\b(?:I've|I have|I) (?:sent|submitted|filed)\\b", "(? = [ ProjectToolkit, EnvironmentToolkit, ThemeToolkit, + FeedbackToolkit, PreviewControlsToolkit, WorktreeToolkit, PullRequestsToolkit, @@ -554,6 +567,8 @@ const pastedSecret = (name: string, input: Readonly>) => const hiddenFromSubagents = enabledWhen(McpInvocationContext.hiddenFromSubagents); // The Linked environments beta starts off, and T3 lists its tools only while it is on. const hiddenWhileLinksOff = enabledWhen(McpInvocationContext.hiddenWhileLinksOff); +// Agent feedback starts off, and T3 lists its tools only while it is on. +const hiddenWhileFeedbackOff = enabledWhen(McpInvocationContext.hiddenWhileFeedbackOff); // T3 lists PR and CI tools only to a thread whose project is on a forge it reads. const hiddenWithoutForge = enabledWhen(McpInvocationContext.hiddenWithoutForge); /** @@ -574,12 +589,14 @@ const visibleT3Tools = (options: { readonly subagent?: boolean; readonly links?: boolean; readonly forge?: boolean; + readonly agentFeedback?: Contracts.AgentFeedbackMode; readonly arm?: Arm; }) => t3Tools.filter( (tool) => !(options.arm === "raw" && forgeToolNames.has(tool.name)) && (options.links === true || !hiddenWhileLinksOff.has(tool.name)) && + ((options.agentFeedback ?? "off") !== "off" || !hiddenWhileFeedbackOff.has(tool.name)) && (options.forge !== false || !hiddenWithoutForge.has(tool.name)) && !(options.subagent === true && hiddenFromSubagents.has(tool.name)), ); @@ -589,7 +606,12 @@ const visibleT3Tools = (options: { * `browser` say whether the thread holds the `device` and `preview` capabilities, as agent device * and browser access decide. */ -const claudeQueryOptions = (model: Model, device = true, browser = true) => { +const claudeQueryOptions = ( + model: Model, + device = true, + browser = true, + agentFeedback: Contracts.AgentFeedbackMode = "off", +) => { // Refs whose text follows a capability read its flag; older ones ignore it. const input: Parameters[0] & { readonly deviceToolsAvailable?: boolean; @@ -600,6 +622,7 @@ const claudeQueryOptions = (model: Model, device = true, browser = true) => { resume: false, cwd: null, mcpServers: { "t3-code": { type: "http", url: "http://127.0.0.1/mcp" } }, + agentFeedback, deviceToolsAvailable: device, browserToolsAvailable: browser, }; @@ -607,8 +630,13 @@ const claudeQueryOptions = (model: Model, device = true, browser = true) => { }; /** Text T3 appends to Claude Code's system prompt. Delegated children get the same text. */ -export const t3SystemAppend = (model: Model, device = true, browser = true) => { - const { systemPrompt } = claudeQueryOptions(model, device, browser); +export const t3SystemAppend = ( + model: Model, + device = true, + browser = true, + agentFeedback: Contracts.AgentFeedbackMode = "off", +) => { + const { systemPrompt } = claudeQueryOptions(model, device, browser, agentFeedback); if (isRecord(systemPrompt) && systemPrompt.type === "preset" && systemPrompt.append) { return systemPrompt.append; } @@ -698,6 +726,8 @@ export const buildBase = ( readonly deviceAccess?: boolean; /** false: the thread has no agent browser access, so T3's text leaves the browser out. */ readonly browserAccess?: boolean; + /** The Agent feedback mode: on, T3 lists its tools and its text includes the mode's line. */ + readonly agentFeedback?: Contracts.AgentFeedbackMode; readonly arm?: Arm; }, ) => { @@ -724,7 +754,10 @@ export const buildBase = ( const { model } = options; const append = options.nativeSubagent ? "" - : forArm(t3SystemAppend(model, options.deviceAccess, options.browserAccess), options.arm); + : forArm( + t3SystemAppend(model, options.deviceAccess, options.browserAccess, options.agentFeedback), + options.arm, + ); const modelLine = `You are powered by the model named ${MODELS[model]}. The exact model ID is ${model}.`; const joined = systemTexts.join("\n"); // The capture's home directory names its user. Cases use `/home/user` paths instead. @@ -794,6 +827,8 @@ const buildCodexBase = ( readonly deviceAccess?: boolean; /** false: the thread has no agent browser access, so T3's text leaves the browser out. */ readonly browserAccess?: boolean; + /** The Agent feedback mode: on, T3 lists its tools and its text includes the mode's line. */ + readonly agentFeedback?: Contracts.AgentFeedbackMode; readonly arm?: Arm; }, ): Base => { @@ -829,7 +864,11 @@ const buildCodexBase = ( return [JSON.parse(clean(JSON.stringify(item))) as Block]; }); const context = buildCodexAdditionalContext( - { model: options.model, reasoningEffort: effort }, + { + model: options.model, + reasoningEffort: effort, + agentFeedback: options.agentFeedback ?? "off", + }, { browser: options.browserAccess ?? true, device: options.deviceAccess ?? true }, ); input.push( @@ -2101,6 +2140,8 @@ const savedSecretFile = ( } }; +const decodeFeedbackInput = Schema.decodeUnknownResult(FeedbackInput); + /** The result for one tool call. */ const FORGE_WRITE_TOOLS = new Set([ "pull_request_create", @@ -2257,6 +2298,39 @@ export const answerToolCall = Effect.fn("evaluateMcpToolUse.answerToolCall")(fun const refused = productRefusal(sample, name, input); if (refused !== undefined) return failed(refused); } + if (isT3Name(call.name) && name === "t3_feedback" && (mock === undefined || mock === "default")) { + const decoded = decodeFeedbackInput(input); + if (Result.isFailure(decoded)) return failed(decoded.failure.message); + const report = decoded.success; + // The same refusals as FeedbackService, in its order. + if (sample.testCase.setup.world?.agentFeedback === "on-request" && !report.userRequested) + return failed(new FeedbackNotRequestedError({ source: "mcp" }).message); + const subject = resolveFeedbackSubject( + report.subject, + t3SourceTools.map((tool) => tool.name), + ); + if (subject === undefined) return failed(FEEDBACK_SUBJECT_MESSAGE); + // T3 shows a requested report to the user in a card and answers at once. + if (report.userRequested) { + return toolResult(call.id, { + status: "awaiting_approval", + note: FEEDBACK_AWAITING_APPROVAL_NOTE, + }); + } + return toolResult(call.id, { + ...report, + subject, + trace: null, + expected: scrubFeedback(report.expected, []), + actual: scrubFeedback(report.actual, []), + workaround: scrubFeedback(report.workaround, []), + id: "019a7b3c-0000-7000-8000-000000000001", + threadId: "thread-1", + createdAt: `${base.environment.date ?? "2026-01-01"}T12:00:00.000Z`, + source: "mcp", + sent: true, + }); + } // A pasted secret is saved without a card, so a mocked card outcome does not apply. if (mock !== undefined && mock !== "default" && !pastedSecret(name, input)) { if (name === "request_secret") savedSecretFile(sample, input, mock); @@ -3217,6 +3291,7 @@ const main = Effect.gen(function* () { browserAccess: boolean, links: boolean, forge: boolean, + agentFeedback: Contracts.AgentFeedbackMode = "off", ): Effect.Effect => codex ? decodeCodexCapture(template).pipe( @@ -3230,6 +3305,7 @@ const main = Effect.gen(function* () { forge, deviceAccess, browserAccess, + agentFeedback, arm: flags.arm, }), ), @@ -3245,6 +3321,7 @@ const main = Effect.gen(function* () { forge, deviceAccess, browserAccess, + agentFeedback, arm: flags.arm, }); return role === "native-subagent" @@ -3256,18 +3333,19 @@ const main = Effect.gen(function* () { ); // Codex has no native subagents; its cases with that role run as top-level threads. const baseKey = ({ setup }: McpToolUseCase) => - `${codex && setup.role === "native-subagent" ? "top" : setup.role}:${setup.world?.deviceAgentAccess !== false}:${setup.world?.browserAgentAccess !== false}:${setup.linkedEnvironments === true}:${setup.forge !== false}`; + `${codex && setup.role === "native-subagent" ? "top" : setup.role}:${setup.world?.deviceAgentAccess !== false}:${setup.world?.browserAgentAccess !== false}:${setup.linkedEnvironments === true}:${setup.forge !== false}:${setup.world?.agentFeedback ?? "off"}`; const base = yield* buildFor("top", true, true, false, true); - const bases = new Map([["top:true:true:false:true", base]]); + const bases = new Map([["top:true:true:false:true:off", base]]); for (const testCase of selected) { const key = baseKey(testCase); if (bases.has(key)) continue; - const [role = "top", device, browser, links, forge] = key.split(":") as [ + const [role = "top", device, browser, links, forge, feedback] = key.split(":") as [ McpToolUseCase["setup"]["role"], string, string, string, string, + string, ]; bases.set( key, @@ -3277,6 +3355,7 @@ const main = Effect.gen(function* () { browser === "true", links === "true", forge === "true", + feedback as Contracts.AgentFeedbackMode, ), ); } diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index 92fad6b57ac9d..d20a890bf90da 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -103,6 +103,10 @@ "types": "./src/secretRequest.ts", "default": "./src/secretRequest.ts" }, + "./feedback-request": { + "types": "./src/feedbackRequest.ts", + "default": "./src/feedbackRequest.ts" + }, "./link-batch": { "types": "./src/linkBatch.ts", "default": "./src/linkBatch.ts" diff --git a/packages/client-runtime/src/feedbackRequest.test.ts b/packages/client-runtime/src/feedbackRequest.test.ts new file mode 100644 index 0000000000000..8c1d5b6cae4bd --- /dev/null +++ b/packages/client-runtime/src/feedbackRequest.test.ts @@ -0,0 +1,79 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + feedbackConversationHint, + feedbackPreviewFields, + feedbackRequestDisplay, + feedbackTraceLines, + feedbackTraceSummary, +} from "./feedbackRequest.ts"; + +describe("feedbackRequestDisplay", () => { + it("lets only the thread that asked answer, and names how each card ended", () => { + expect(feedbackRequestDisplay({ feedbackStatus: "pending" }, "local")).toEqual({ + kind: "pending", + }); + expect(feedbackRequestDisplay({ feedbackStatus: "pending" }, "inherited").kind).toBe( + "pending-elsewhere", + ); + expect( + (["sent", "declined", "cancelled"] as const).map((feedbackStatus) => + feedbackRequestDisplay({ feedbackStatus }, "local"), + ), + ).toEqual([ + { kind: "answered", outcome: "sent", label: "Sent" }, + { kind: "answered", outcome: "not-sent", label: "Not sent" }, + { kind: "answered", outcome: "not-sent", label: "Closed without sending" }, + ]); + }); +}); + +describe("feedback preview", () => { + it("shows every field that is sent, and each outline entry with its text", () => { + const trace = { + turns: 1, + textTurns: 1, + truncated: false, + entries: [ + { turn: 1, type: "user" as const, length: 5, text: "Hello" }, + { + turn: 1, + type: "tool" as const, + tool: "t3_thread_read", + outcome: "error" as const, + durationMs: 1_500, + }, + ], + }; + expect( + feedbackPreviewFields({ + kind: "bug", + subject: "t3_thread_read", + expected: "Items.", + actual: "None.", + workaround: "", + trace, + }).map((field) => field.label), + ).toEqual(["Kind", "About", "Expected", "Happened"]); + expect(feedbackTraceLines(trace)).toEqual([ + { key: "0", line: "Turn 1 · You · 5 characters", text: "Hello" }, + { key: "1", line: "Turn 1 · t3_thread_read · error · 1.5 s" }, + ]); + // Text only in turn 4 of 5: the wording reaches back to it, not "the last turn". + const older = { + turns: 5, + textTurns: 1, + truncated: false, + entries: [ + { turn: 4, type: "user" as const, length: 5, text: "Hello" }, + { turn: 5, type: "tool" as const, tool: "shell", outcome: "ok" as const }, + ], + }; + expect(feedbackTraceSummary(older)).toBe( + "Outline of 5 recent turns, message text of the last 2 turns", + ); + expect(feedbackConversationHint(older)).toBe( + "Adds the text of your messages and the agent's replies in the last 2 turns.", + ); + }); +}); diff --git a/packages/client-runtime/src/feedbackRequest.ts b/packages/client-runtime/src/feedbackRequest.ts new file mode 100644 index 0000000000000..f6b0079213ebc --- /dev/null +++ b/packages/client-runtime/src/feedbackRequest.ts @@ -0,0 +1,145 @@ +import { mFallback, msg } from "gt-i18n"; +import type { MFunctionType } from "gt-i18n/types"; +import type { AgentFeedbackPreview, OrchestrationV2TurnItem } from "@t3tools/contracts"; + +export type FeedbackRequestItem = Extract< + OrchestrationV2TurnItem, + { readonly type: "feedback_request" } +>; + +export type FeedbackRequestDisplay = + | { readonly kind: "pending" } + /** Inherited by a fork: only the thread that asked can answer it. */ + | { readonly kind: "pending-elsewhere"; readonly label: string } + | { readonly kind: "answered"; readonly outcome: "sent" | "not-sent"; readonly label: string }; + +export function feedbackRequestDisplay( + item: Pick, + visibility: "local" | "inherited" | "synthetic", + resolve: MFunctionType = mFallback, +): FeedbackRequestDisplay { + switch (item.feedbackStatus) { + case "pending": + return visibility === "local" + ? { kind: "pending" } + : { kind: "pending-elsewhere", label: resolve(msg("Waiting in the original thread")) }; + case "sent": + return { kind: "answered", outcome: "sent", label: resolve(msg("Sent")) }; + case "declined": + return { kind: "answered", outcome: "not-sent", label: resolve(msg("Not sent")) }; + case "cancelled": + return { + kind: "answered", + outcome: "not-sent", + label: resolve(msg("Closed without sending")), + }; + } +} + +/** Exactly what Send sends: the outline, or with the conversation included, its text too. */ +export function feedbackCardPreview( + item: Pick, + includeConversation: boolean, +): AgentFeedbackPreview { + return includeConversation && item.conversationTrace !== undefined + ? { ...item.preview, trace: item.conversationTrace } + : item.preview; +} + +const KIND_LABELS: Record = { + bug: msg("Bug"), + confusing: msg("Confusing"), + missing_capability: msg("Missing capability"), + wrong_docs: msg("Wrong docs"), + other: msg("Other"), +}; + +/** The report's fields in reading order, the empty workaround left out. */ +export function feedbackPreviewFields( + preview: AgentFeedbackPreview, + resolve: MFunctionType = mFallback, +): ReadonlyArray<{ readonly label: string; readonly value: string }> { + return [ + { label: resolve(msg("Kind")), value: resolve(KIND_LABELS[preview.kind]) }, + { label: resolve(msg("About")), value: preview.subject }, + { label: resolve(msg("Expected")), value: preview.expected }, + { label: resolve(msg("Happened")), value: preview.actual }, + { label: resolve(msg("Did instead")), value: preview.workaround }, + ].filter((field) => field.value !== ""); +} + +const seconds = (ms: number) => `${(ms / 1_000).toFixed(ms < 10_000 ? 1 : 0)} s`; + +/** One line per outline entry, plus the message text that goes with it. */ +export function feedbackTraceLines( + trace: NonNullable, + resolve: MFunctionType = mFallback, +): ReadonlyArray<{ readonly key: string; readonly line: string; readonly text?: string }> { + return trace.entries.map((entry, index) => { + const what = + entry.type === "tool" + ? [ + entry.tool ?? "tool", + entry.outcome, + entry.durationMs === undefined ? undefined : seconds(entry.durationMs), + ] + .filter((part) => part !== undefined) + .join(" · ") + : resolve( + msg("{speaker} · {count} characters", { + speaker: resolve(entry.type === "user" ? msg("You") : msg("Agent")), + count: entry.length ?? 0, + }), + ); + return { + key: `${index}`, + line: resolve(msg("Turn {turn} · {what}", { turn: entry.turn, what })), + ...(entry.text === undefined ? {} : { text: entry.text }), + }; + }); +} + +type Trace = NonNullable; + +// Counted back to the oldest turn with text, so a newer turn without any is still inside it. +const textSpan = (trace: Trace) => { + const withText = trace.entries.filter((entry) => entry.text !== undefined); + return withText.length === 0 + ? 0 + : trace.turns - Math.min(...withText.map((entry) => entry.turn)) + 1; +}; + +/** What the outline holds, in one line. */ +export function feedbackTraceSummary(trace: Trace, resolve: MFunctionType = mFallback): string { + return resolve( + msg( + "Outline of {turns, plural, one {{turns} recent turn} other {{turns} recent turns}}, {textTurns, plural, =0 {no message text} one {message text of the last turn} other {message text of the last {textTurns} turns}}{truncated, select, yes {, shortened to fit} other {}}", + { turns: trace.turns, textTurns: textSpan(trace), truncated: trace.truncated ? "yes" : "no" }, + ), + ); +} + +/** What the conversation switch adds: the text of the turns the agent said the problem spans. */ +export function feedbackConversationHint(trace: Trace, resolve: MFunctionType = mFallback): string { + return resolve( + msg( + "Adds the text of your messages and the agent's replies in the last {textTurns, plural, one {turn} other {{textTurns} turns}}.", + { textTurns: textSpan(trace) }, + ), + ); +} + +/** The server's own message for a failed answer, else a generic one. */ +export function feedbackRequestFailureMessage( + failure: unknown, + resolve: MFunctionType = mFallback, +): string { + return typeof failure === "object" && + failure !== null && + "_tag" in failure && + failure._tag === "AgentFeedbackRequestError" && + "message" in failure && + typeof failure.message === "string" + ? failure.message + : resolve(msg("Could not send your answer. Try again.")); +} diff --git a/packages/client-runtime/src/state/commandPermissions.test.ts b/packages/client-runtime/src/state/commandPermissions.test.ts index fcc8cb60e5260..18dee4bd56b41 100644 --- a/packages/client-runtime/src/state/commandPermissions.test.ts +++ b/packages/client-runtime/src/state/commandPermissions.test.ts @@ -541,6 +541,21 @@ it.effect("requires access management to answer a link request", () => }), ); +it.effect("requires thread operation to answer a feedback card", () => + Effect.gen(function* () { + const registry = yield* setup; + registry.set(sessions(env), AsyncResult.success(grant(false))); + const answer = createCommandPermissions(runtime, WS_METHODS.agentFeedbackAnswerRequest); + expect(registry.get(answer.permissionAtom(env))).toBe(false); + expect((yield* answer.authorize(registry, env).pipe(Effect.flip)).requiredPermission).toBe( + AuthOrchestrationOperateScope, + ); + registry.set(sessions(env), AsyncResult.success(grant(true))); + expect(registry.get(answer.permissionAtom(env))).toBe(true); + yield* answer.authorize(registry, env); + }), +); + it.effect("honors exact empty permissions and preserves legacy parent grants", () => Effect.gen(function* () { const registry = yield* setup; diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.ts index 222c12e6ba3e3..6545f377cc632 100644 --- a/packages/client-runtime/src/state/server.ts +++ b/packages/client-runtime/src/state/server.ts @@ -1919,6 +1919,15 @@ export function createServerEnvironmentAtoms( JSON.stringify([environmentId, input.threadId, input.turnItemId]), }, }), + answerFeedbackRequest: createEnvironmentRpcCommand(runtime, { + label: "environment-data:server:agent-feedback:answer-request", + tag: WS_METHODS.agentFeedbackAnswerRequest, + concurrency: { + mode: "singleFlight", + key: ({ environmentId, input }) => + JSON.stringify([environmentId, input.threadId, input.turnItemId]), + }, + }), refreshUsageRates: createEnvironmentRpcCommand(runtime, { label: "environment-data:server:refresh-usage-rates", tag: WS_METHODS.serverRefreshUsageRates, diff --git a/packages/contracts/src/agentFeedback.ts b/packages/contracts/src/agentFeedback.ts new file mode 100644 index 0000000000000..0840c8a4f8994 --- /dev/null +++ b/packages/contracts/src/agentFeedback.ts @@ -0,0 +1,84 @@ +import * as Schema from "effect/Schema"; + +import { ThreadId, TurnItemId } from "./baseSchemas.ts"; + +export const AgentFeedbackKind = Schema.Literals([ + "bug", + "confusing", + "missing_capability", + "wrong_docs", + "other", +]); + +/** Built by the server from the thread's stored items; the agent never writes it. */ +export const AgentFeedbackTrace = Schema.Struct({ + turns: Schema.Int, + textTurns: Schema.Int, + /** A cap dropped an entry or cut or dropped a message text. */ + truncated: Schema.Boolean, + entries: Schema.Array( + Schema.Struct({ + turn: Schema.Int, + type: Schema.Literals(["user", "assistant", "tool"]), + tool: Schema.optionalKey(Schema.String), + outcome: Schema.optionalKey(Schema.Literals(["ok", "error", "unfinished"])), + durationMs: Schema.optionalKey(Schema.Int), + /** A message's length in characters. */ + length: Schema.optionalKey(Schema.Int), + text: Schema.optionalKey(Schema.String), + }), + ), +}); +export type AgentFeedbackTrace = typeof AgentFeedbackTrace.Type; + +/** Exactly what a requested report sends once the user approves it, already scrubbed. */ +export const AgentFeedbackPreview = Schema.Struct({ + kind: AgentFeedbackKind, + subject: Schema.String, + expected: Schema.String, + actual: Schema.String, + workaround: Schema.String, + trace: Schema.NullOr(AgentFeedbackTrace), +}); +export type AgentFeedbackPreview = typeof AgentFeedbackPreview.Type; + +export const AgentFeedbackRequestStatus = Schema.Literals([ + "pending", + "sent", + "declined", + "cancelled", +]); +export type AgentFeedbackRequestStatus = typeof AgentFeedbackRequestStatus.Type; + +export const AgentFeedbackAnswerInput = Schema.Struct({ + threadId: ThreadId, + turnItemId: TurnItemId, + answer: Schema.Literals(["send", "decline"]), + /** Send the card's conversation trace instead of its outline. */ + includeConversation: Schema.optionalKey(Schema.Boolean), +}); +export type AgentFeedbackAnswerInput = typeof AgentFeedbackAnswerInput.Type; + +const AGENT_FEEDBACK_REQUEST_FAILURE_MESSAGES = { + load_failed: "Could not load the feedback report.", + not_found: "This feedback report no longer exists.", + already_answered: "This feedback report was already answered.", + feedback_off: "Agent feedback is off, so this report was not sent.", + record_failed: "Could not record your answer.", +} as const; + +export class AgentFeedbackRequestError extends Schema.TaggedError()( + "AgentFeedbackRequestError", + { + reason: Schema.Literals( + Object.keys(AGENT_FEEDBACK_REQUEST_FAILURE_MESSAGES) as Array< + keyof typeof AGENT_FEEDBACK_REQUEST_FAILURE_MESSAGES + >, + ), + cause: Schema.optionalKey(Schema.Defect()), + }, +) { + override get message(): string { + return AGENT_FEEDBACK_REQUEST_FAILURE_MESSAGES[this.reason]; + } +} diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.ts index b211332c1c8b8..f7825d6364b79 100644 --- a/packages/contracts/src/clientRpcPermissions.ts +++ b/packages/contracts/src/clientRpcPermissions.ts @@ -92,6 +92,8 @@ export const CLIENT_GUARDED_RPC_SCOPES = { [WS_METHODS.peerLinksAnswerRequest]: AuthAccessWriteScope, [WS_METHODS.peerLinksPairClient]: AuthAccessWriteScope, [WS_METHODS.peerLinksPairLink]: AuthAccessWriteScope, + // Send stores and sends a report from a thread's turn: the bar of running that thread. + [WS_METHODS.agentFeedbackAnswerRequest]: AuthOrchestrationOperateScope, } as const; export type ClientGuardedRpcTag = keyof typeof CLIENT_GUARDED_RPC_SCOPES; diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index 34c8688316ae2..ae5bed14b44ba 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -220,6 +220,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({ shellOlderSettled: Schema.optionalKey(Schema.Boolean), /** Publishes a pull request refresh when linked-thread answers change; older servers need polling. */ linkedThreadRefreshes: Schema.optionalKey(Schema.Boolean), + /** Honors the `agentFeedback` setting; older servers drop it, so hide its switch where absent. */ + agentFeedback: Schema.optionalKey(Schema.Boolean), /** Answers `issues.linkedThreads`, the threads an issue is linked to. */ issueLinkedThreads: Schema.optionalKey(Schema.Boolean), }); diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index d7af43291a061..e1b3346386ffc 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -72,6 +72,7 @@ export * from "./resourceTelemetry.ts"; export * from "./rpc.ts"; export * from "./worktreeSetup.ts"; export * from "./secretRequest.ts"; +export * from "./agentFeedback.ts"; export * from "./secretReference.ts"; export * from "./settingsSecretValue.ts"; export * from "./clientRpcPermissions.ts"; diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 8b05c12e17871..6eec84b4dc253 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -7,6 +7,11 @@ import * as SchemaAST from "effect/SchemaAST"; import * as SchemaGetter from "effect/SchemaGetter"; import * as SchemaTransformation from "effect/SchemaTransformation"; +import { + AgentFeedbackPreview, + AgentFeedbackRequestStatus, + AgentFeedbackTrace, +} from "./agentFeedback.ts"; import { CheckpointId, CheckpointRef, @@ -1846,6 +1851,19 @@ const OrchestrationV2LinkRequestFields = { failure: Schema.optional(Schema.String), } as const; +/** + * A report the user asked the agent to send to the T3 team, shown for approval. Send stores and + * sends exactly `preview`, with `conversationTrace` as its trace if the user included the + * conversation. Once answered, the card keeps only what was sent. + */ +const OrchestrationV2FeedbackRequestFields = { + type: Schema.Literal("feedback_request"), + preview: AgentFeedbackPreview, + /** The preview's trace with message text, sent instead if the user includes the conversation. */ + conversationTrace: Schema.optionalKey(AgentFeedbackTrace), + feedbackStatus: AgentFeedbackRequestStatus, +} as const; + export const OrchestrationV2TurnItem = Schema.Union([ Schema.Struct({ ...OrchestrationV2TurnItemBaseFields, @@ -2050,6 +2068,10 @@ export const OrchestrationV2TurnItem = Schema.Union([ ...OrchestrationV2TurnItemBaseFields, ...OrchestrationV2LinkRequestFields, }), + Schema.Struct({ + ...OrchestrationV2TurnItemBaseFields, + ...OrchestrationV2FeedbackRequestFields, + }), Schema.Struct({ ...OrchestrationV2TurnItemBaseFields, type: Schema.Literal("subagent"), @@ -2940,6 +2962,10 @@ export const OrchestrationV2TurnItemJson = Schema.Union([ ...OrchestrationV2TurnItemJsonBaseFields, ...OrchestrationV2LinkRequestFields, }), + Schema.Struct({ + ...OrchestrationV2TurnItemJsonBaseFields, + ...OrchestrationV2FeedbackRequestFields, + }), Schema.Struct({ ...OrchestrationV2TurnItemJsonBaseFields, type: Schema.Literal("subagent"), @@ -3970,6 +3996,18 @@ const OrchestrationV2InternalCommand = Schema.Union([ fields: Schema.optional(Schema.Array(OrchestrationV2SecretRequestField)), secretStatus: OrchestrationV2SecretRequestStatus, }), + /** Internal so no client can mark a report sent without it being stored and sent. */ + Schema.Struct({ + type: Schema.Literal("feedback_request.record"), + commandId: CommandId, + threadId: ThreadId, + runId: RunId, + nodeId: NodeId, + turnItemId: TurnItemId, + preview: AgentFeedbackPreview, + conversationTrace: Schema.optionalKey(AgentFeedbackTrace), + feedbackStatus: AgentFeedbackRequestStatus, + }), /** * Records or updates a link an agent asked the user to make. Internal so no * client can mark a request linked without the link being made. diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index 8a8fe05efb4da..e56009a98fb4e 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -438,6 +438,7 @@ import { ScheduledTaskMutationResult, } from "./scheduledTask.ts"; import { SecretRequestAnswerInput, SecretRequestError } from "./secretRequest.ts"; +import { AgentFeedbackAnswerInput, AgentFeedbackRequestError } from "./agentFeedback.ts"; import { ProjectCloneActionInput, ProjectCloneActionResult, @@ -623,6 +624,7 @@ export const WS_METHODS = { scheduledTasksRunNow: "scheduledTasks.runNow", scheduledTasksRotateWebhookToken: "scheduledTasks.rotateWebhookToken", secretsAnswerRequest: "secrets.answerRequest", + agentFeedbackAnswerRequest: "agentFeedback.answerRequest", guestShareCreate: "guestShare.create", scheduledTasksListWebhookDeliveries: "scheduledTasks.listWebhookDeliveries", scheduledTasksGetWebhookDelivery: "scheduledTasks.getWebhookDelivery", @@ -2335,6 +2337,11 @@ const WsSecretsAnswerRequestRpc = Rpc.make(WS_METHODS.secretsAnswerRequest, { error: Schema.Union([SecretRequestError, EnvironmentAuthorizationError]), }); +const WsAgentFeedbackAnswerRequestRpc = Rpc.make(WS_METHODS.agentFeedbackAnswerRequest, { + payload: AgentFeedbackAnswerInput, + error: Schema.Union([AgentFeedbackRequestError, EnvironmentAuthorizationError]), +}); + const WsScheduledTasksListWebhookDeliveriesRpc = Rpc.make( WS_METHODS.scheduledTasksListWebhookDeliveries, { @@ -2461,6 +2468,7 @@ export const WsRpcGroup = RpcGroup.make( WsScheduledTasksRunNowRpc, WsScheduledTasksRotateWebhookTokenRpc, WsSecretsAnswerRequestRpc, + WsAgentFeedbackAnswerRequestRpc, WsScheduledTasksListWebhookDeliveriesRpc, WsScheduledTasksGetWebhookDeliveryRpc, WsServerReportClientActivityRpc, diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index b0726b07174c9..4538065ee5c50 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -1144,6 +1144,10 @@ export type BackgroundActivitySettings = typeof BackgroundActivitySettings.Type; export const ResponseStreamingMode = Schema.Literals(["turn", "paragraph"]); export type ResponseStreamingMode = typeof ResponseStreamingMode.Type; +/** `on-request`: agents report only when the user asks. `auto`: they also report on their own. */ +export const AgentFeedbackMode = Schema.Literals(["off", "on-request", "auto"]); +export type AgentFeedbackMode = typeof AgentFeedbackMode.Type; + const StorageRetentionDays = Schema.NullOr( Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 3650 })), ); @@ -1394,6 +1398,9 @@ export const ServerSettings = Schema.Struct({ responseStreamingMode: ResponseStreamingMode.pipe( Schema.withDecodingDefault(Effect.succeed("paragraph" as const)), ), + agentFeedback: Schema.Struct({ + mode: AgentFeedbackMode.pipe(Schema.withDecodingDefaultKey(Effect.succeed("off" as const))), + }).pipe(Schema.withDecodingDefault(Effect.succeed({ mode: "off" as const }))), enableProviderUpdateChecks: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), continueThreadsAfterServerUpdate: Schema.Boolean.pipe( Schema.withDecodingDefault(Effect.succeed(true)), @@ -1865,6 +1872,7 @@ export const ServerSettingsPatch = Schema.Struct({ worktreesDirectory: Schema.optionalKey(TrimmedString), fastWorktreeCheckout: Schema.optionalKey(Schema.Boolean), responseStreamingMode: Schema.optionalKey(ResponseStreamingMode), + agentFeedback: Schema.optionalKey(Schema.Struct({ mode: AgentFeedbackMode })), enableProviderUpdateChecks: Schema.optionalKey(Schema.Boolean), continueThreadsAfterServerUpdate: Schema.optionalKey(Schema.Boolean), keepAwakeWhileAgentsWork: Schema.optionalKey(Schema.Boolean), diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 908c99e4eaeb3..997158c78a1ce 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -9092,6 +9092,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }); const sessionSetup = yield* Ref.get(activeSessionSetup); const runtimeInstructions = buildRuntimeInstructions({ + agentFeedback: instructionState.hasT3Mcp ? (turnInput.agentFeedback ?? "off") : "off", harness: flavor.runtimeHarness ?? driver, model: turnInput.modelSelection.model, runtimePolicy: turnInput.runtimePolicy, diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.ts index 796ec9541d295..049198f9a6cb4 100644 --- a/packages/provider-core/src/server/ProviderAdapter.ts +++ b/packages/provider-core/src/server/ProviderAdapter.ts @@ -1,5 +1,6 @@ import type { OrchestrationV2HistoricalMessage } from "@t3tools/contracts"; import { + type AgentFeedbackMode, ChatAttachment, CheckpointId, MessageId, @@ -582,6 +583,7 @@ export interface ProviderAdapterV2EnsureThreadInput { } export interface ProviderAdapterV2TurnInput { + readonly agentFeedback?: AgentFeedbackMode; readonly appThread: OrchestrationV2AppThread; readonly threadId: ThreadId; readonly runId: RunId; diff --git a/packages/provider-core/src/server/runtimeInstructions.test.ts b/packages/provider-core/src/server/runtimeInstructions.test.ts index 2564bedaa9216..5aa9259c49d91 100644 --- a/packages/provider-core/src/server/runtimeInstructions.test.ts +++ b/packages/provider-core/src/server/runtimeInstructions.test.ts @@ -1,6 +1,7 @@ import { assert, describe, it } from "@effect/vitest"; import { + AGENT_FEEDBACK_INSTRUCTIONS, buildRuntimeInstructions, PULL_REQUEST_LINKING_INSTRUCTIONS, } from "./runtimeInstructions.ts"; @@ -57,6 +58,22 @@ describe("buildRuntimeInstructions", () => { assert.include(instructions, "call unwatch_pull_request"); }); + it("carries the feedback line of the agent feedback mode, and none while it is off", () => { + assert.notInclude(buildRuntimeInstructions({ harness: "Codex" }), "t3_feedback"); + assert.notInclude( + buildRuntimeInstructions({ harness: "Codex", agentFeedback: "off" }), + "t3_feedback", + ); + for (const agentFeedback of ["on-request", "auto"] as const) { + for (const pullRequestLinking of [true, false]) { + assert.include( + buildRuntimeInstructions({ harness: "Codex", agentFeedback, pullRequestLinking }), + AGENT_FEEDBACK_INSTRUCTIONS[agentFeedback], + ); + } + } + }); + it("lists a multi-folder thread's folders and leaves single-folder text unchanged", () => { const base = { runtimeMode: "full-access", interactionMode: "default" } as const; const single = buildRuntimeInstructions({ harness: "Codex" }); @@ -86,6 +103,21 @@ describe("buildRuntimeInstructions", () => { }, }); assert.isTrue(listed.startsWith(`${single}\n\n\n`)); + const withFeedback = buildRuntimeInstructions({ harness: "Codex", agentFeedback: "auto" }); + assert.isTrue( + buildRuntimeInstructions({ + harness: "Codex", + agentFeedback: "auto", + runtimePolicy: { + ...base, + cwd: "/work/app", + workspace: { + folders: [{ name: "api", path: "/work/api", isGitRepository: true }], + extraRoots: [], + }, + }, + }).startsWith(`${withFeedback}\n\n\n`), + ); assert.deepEqual( listed .slice(single.length + 2) diff --git a/packages/provider-core/src/server/runtimeInstructions.ts b/packages/provider-core/src/server/runtimeInstructions.ts index 463148500ebb4..ebcf126f982ae 100644 --- a/packages/provider-core/src/server/runtimeInstructions.ts +++ b/packages/provider-core/src/server/runtimeInstructions.ts @@ -1,5 +1,14 @@ +import type { AgentFeedbackMode } from "@t3tools/contracts"; + import type { ProviderAdapterV2RuntimePolicy } from "./ProviderAdapter.ts"; +/** None while agent feedback is off, so users who never opt in pay no context for it. */ +export const AGENT_FEEDBACK_INSTRUCTIONS = { + off: "", + "on-request": "Use `t3_feedback` only when the user asks you to send T3 feedback.", + auto: "`t3_feedback` reports are wanted and cheap. Send one, then continue, when a T3 tool or `t3` command fails or gives a wrong result, the user corrects how you use T3 Code, or a T3 capability you looked for is missing. Once per problem; also when the user asks. Only about T3 Code, never the user's code or other tools.", +} satisfies Record; + /** Session-invariant; harnesses with a native system-prompt append can carry it once per session. */ export const PULL_REQUEST_LINKING_INSTRUCTIONS = ` Link each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch. When pull_request_* tools are listed, use them, not gh or cafe, to read, list, open, edit, review, reply on, close, or merge PRs, and ci_logs and ci_rerun for their checks. pull_request_create links for you. @@ -9,6 +18,7 @@ If available, call link_issue for each issue you take on or file, even via CLI; /** Omit model and effort when the harness manages them dynamically. */ export function buildRuntimeInstructions(runtime: { readonly harness: string; + readonly agentFeedback?: AgentFeedbackMode; readonly model?: string | undefined; readonly modelName?: string | undefined; readonly reasoningEffort?: string | undefined; @@ -26,13 +36,15 @@ export function buildRuntimeInstructions(runtime: { const modelInfo = model && model !== "auto" && model !== "default" ? `, as ${modelLabel}` : ""; const effortInfo = effort ? ` with ${effort} reasoning effort` : ""; const runtimeInfo = `In case you're asked: you are running in T3 Code through the ${harness} harness${modelInfo}${effortInfo}. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.`; + const feedbackLine = AGENT_FEEDBACK_INSTRUCTIONS[runtime.agentFeedback ?? "off"]; + const feedback = feedbackLine ? `\n${feedbackLine}` : ""; const workspace = runtime.runtimePolicy === undefined ? "" : buildWorkspaceInstructions(runtime.runtimePolicy); - return [ - runtimeInfo, - ...(runtime.pullRequestLinking === false ? [] : [PULL_REQUEST_LINKING_INSTRUCTIONS]), - ...(workspace === "" ? [] : [workspace]), - ].join("\n\n"); + const linked = + runtime.pullRequestLinking === false + ? runtimeInfo + : `${runtimeInfo}\n\n${PULL_REQUEST_LINKING_INSTRUCTIONS}`; + return [linked + feedback, ...(workspace === "" ? [] : [workspace])].join("\n\n"); } function toSingleLine(value: string): string { diff --git a/packages/provider-cursor/src/server/adapter.ts b/packages/provider-cursor/src/server/adapter.ts index b4dd1033c2a9f..8fe8fed5917f7 100644 --- a/packages/provider-cursor/src/server/adapter.ts +++ b/packages/provider-cursor/src/server/adapter.ts @@ -2903,11 +2903,12 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( }); } const runtimeInstructions = buildRuntimeInstructions({ + agentFeedback: mcpServers === undefined ? "off" : (turnInput.agentFeedback ?? "off"), harness: "Cursor", model: turnInput.modelSelection.model, runtimePolicy: turnInput.runtimePolicy, }); - // Resend only on a new/compacted/rewound conversation or when the model changes. + // Resend only on a new/compacted/rewound conversation or when the instructions change. const sendRuntimeInstructions = delivered.runtime !== runtimeInstructions; const text = sendRuntimeInstructions ? userText.length === 0 diff --git a/packages/provider-muse/src/server/adapter.test.ts b/packages/provider-muse/src/server/adapter.test.ts index f23f7ca84d7ea..7e0375e99a3ec 100644 --- a/packages/provider-muse/src/server/adapter.test.ts +++ b/packages/provider-muse/src/server/adapter.test.ts @@ -388,7 +388,8 @@ vi.mock("node:fs/promises", { spy: true }); describe("MuseAdapterV2", () => { it.effect("connects the thread's MCP credential on native start and resume", () => Effect.gen(function* () { - yield* (yield* McpProviderSessions.McpProviderSessions).set({ + const sessions = yield* McpProviderSessions.McpProviderSessions; + const config = { environmentId: EnvironmentId.make("test-environment"), threadId: THREAD_ID, providerSessionId: "test-session", @@ -396,11 +397,12 @@ describe("MuseAdapterV2", () => { endpoint: "http://127.0.0.1:43210/mcp", authorizationHeader: "Bearer thread-scoped-test-token", browserToolsAvailable: true, - }); + }; for (const nativeId of [undefined, "saved-native-session"]) { + yield* sessions.set(config); const fake = yield* makeFakeMuse(); fake.host.initializeResult.grantedCapabilities.push("sessionMcp"); - yield* makeHarness(fake, INSTANCE_ID, nativeId); + const harness = yield* makeHarness(fake, INSTANCE_ID, nativeId); const call = yield* fake.takeCall(nativeId ? "session/resume" : "session/start"); assert.deepStrictEqual(call.params.config, { mcpServers: { @@ -412,6 +414,13 @@ describe("MuseAdapterV2", () => { }, }, }); + yield* sessions.clear(THREAD_ID); + yield* harness.runtime.startTurn({ + ...(yield* turnInput(harness.providerThread, 1, harness.policy)), + agentFeedback: "auto", + }); + const turn = yield* fake.takeCall("turn/start"); + assert.match(JSON.stringify(turn.params.input), /t3_feedback/); } }).pipe(Effect.scoped, Effect.provide(testLayer)), ); diff --git a/packages/provider-muse/src/server/adapter.ts b/packages/provider-muse/src/server/adapter.ts index 0b5835e0bad12..66c1fd1a505ff 100644 --- a/packages/provider-muse/src/server/adapter.ts +++ b/packages/provider-muse/src/server/adapter.ts @@ -356,6 +356,7 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( let relaunchable = false; let nativeSessionId: string | undefined; let thread: OrchestrationV2ProviderThread | undefined; + let hasT3Mcp = false; let active: ActiveTurn | undefined; let lastProviderTurn: OrchestrationV2ProviderTurn | undefined; let latestSubscriptionUsage: MuseSubscriptionUsage | undefined; @@ -2013,6 +2014,7 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( createdAt, updatedAt: createdAt, }; + hasT3Mcp = mcpSession !== undefined; session = { ...session, model: result.session.modelId ?? args.modelSelection.model, @@ -2191,6 +2193,7 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( { type: "text", text: buildRuntimeInstructions({ + agentFeedback: hasT3Mcp ? (turnInput.agentFeedback ?? "off") : "off", harness: "Muse Code", model: session.model ?? undefined, reasoningEffort: effort, diff --git a/packages/provider-opencode/src/server/adapter.ts b/packages/provider-opencode/src/server/adapter.ts index d0e1d27cc2a7b..6398e8ec74800 100644 --- a/packages/provider-opencode/src/server/adapter.ts +++ b/packages/provider-opencode/src/server/adapter.ts @@ -13,6 +13,7 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import { getModelSelectionStringOptionValue } from "@t3tools/shared/model"; import { causeErrorTag } from "@t3tools/shared/observability"; import { + type AgentFeedbackMode, defaultInstanceIdForDriver, type ModelSelection, type OrchestrationV2AppThread, @@ -296,6 +297,7 @@ interface ActiveOpenCodeTurn { readonly appThread: OrchestrationV2AppThread; readonly modelSelection: ModelSelection; readonly runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy; + readonly agentFeedback: AgentFeedbackMode; readonly providerTurnId: OrchestrationV2ProviderTurn["id"]; readonly providerThreadId: OrchestrationV2ProviderTurn["providerThreadId"]; readonly runOrdinal: number; @@ -2513,6 +2515,7 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function appThread: state.appThread, modelSelection: state.appThread.modelSelection, runtimePolicy: state.parentSubagent.parentTurn.runtimePolicy, + agentFeedback: state.parentSubagent.parentTurn.agentFeedback, providerTurnId, providerThreadId: providerTurn.providerThreadId, runOrdinal: state.parentSubagent.parentTurn.runOrdinal, @@ -3515,6 +3518,7 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function buildRuntimeInstructions({ harness: "OpenCode", model: turn.modelSelection.model, + agentFeedback: hasT3Mcp ? turn.agentFeedback : "off", runtimePolicy: turn.runtimePolicy, }), ] @@ -3788,6 +3792,7 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function appThread: turnInput.appThread, modelSelection: turnInput.modelSelection, runtimePolicy: turnInput.runtimePolicy, + agentFeedback: turnInput.agentFeedback ?? "off", providerTurnId, providerThreadId: turnInput.providerThread.id, runOrdinal: turnInput.runOrdinal, diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index 5cbc012de984d..9cee26a3fb20d 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -4430,6 +4430,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr } const instructions = [ buildRuntimeInstructions({ + agentFeedback: mcpAvailable ? (turnInput.agentFeedback ?? "off") : "off", harness: "OpenCode", model: turnInput.modelSelection.model, runtimePolicy: turnInput.runtimePolicy, From c89ca0a2f2c1d996d9b461568860991febaca04f Mon Sep 17 00:00:00 2001 From: tiliakoos <73005126+tiliakoos@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:08:25 +0100 Subject: [PATCH 213/324] fix(server): a worktree thread moved to the project checkout no longer holds new messages (#41052) Co-authored-by: MarcoDotIO <20867620+MarcoDotIO@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../src/orchestration-v2/Orchestrator.ts | 70 +++++++++++------- .../ThreadFork.execution.test.ts | 8 +- .../src/orchestration-v2/runtimeLayer.test.ts | 74 ++++++++++++++++++- .../shared/src/orchestrationV2ThreadError.ts | 1 + ...ped-worktree-turn-sends-in-checkout.e2e.ts | 51 +++++++++++++ 5 files changed, 172 insertions(+), 32 deletions(-) create mode 100644 scripts/scenarios/stopped-worktree-turn-sends-in-checkout.e2e.ts diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 4ea2c72d04fde..6920d26d3502f 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -1021,7 +1021,10 @@ function delegatedTaskTerminalStatus( } } -/** Failed worktree setup keeps the queue held so queued messages cannot start in the project checkout. */ +/** + * Failed worktree setup keeps the queue held so queued messages cannot start in the project checkout. + * A run that started had its worktree, so ending it later is not a failed setup. + */ function worktreeSetupPending( projection: Pick, ): boolean { @@ -1030,6 +1033,7 @@ function worktreeSetupPending( projection.runs.some( (run) => (run.status === "failed" || run.status === "interrupted") && + run.startedAt === null && run.workspacePreparation?.type === "worktree", ) ); @@ -2597,7 +2601,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const worktreeMissing = endedRunId !== undefined && failedRun?.id === endedRunId && - failedRun?.workspacePreparation?.type === "worktree" && + failedRun.startedAt === null && + failedRun.workspacePreparation?.type === "worktree" && projection.thread.worktreePath === null; const settings = yield* serverSettings.getSettings.pipe(Effect.orDie); const projectOverride = @@ -3000,30 +3005,42 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ) : null; const activeHandoff = handoff ?? legacyImportRecoveryHandoff; + const mapQueuedStartError = Effect.mapError( + (cause: unknown) => + new OrchestratorDispatchError({ + commandId, + commandType: "message.dispatch", + cause, + }), + ); + const executionCwd = + storedCheckpointScope !== undefined && + storedCheckpointScope.cwd === projection.thread.worktreePath + ? storedCheckpointScope.cwd + : yield* runtimePolicy + .resolve({ thread: projection.thread, modelSelection: queuedRun.modelSelection }) + .pipe( + Effect.map( + (resolvedRuntimePolicy) => + resolvedRuntimePolicy.cwd ?? projection.thread.worktreePath ?? process.cwd(), + ), + mapQueuedStartError, + ); + // The thread may have moved between worktree and checkout while this message waited. + const reusableCheckpointScope = + storedCheckpointScope?.cwd === executionCwd ? storedCheckpointScope : undefined; const checkpointScope = - storedCheckpointScope ?? - (yield* runtimePolicy - .resolve({ thread: projection.thread, modelSelection: queuedRun.modelSelection }) - .pipe( - Effect.flatMap((resolvedRuntimePolicy) => - checkpointService.prepareRootRunScope({ - threadId, - runId: queuedRun.id, - rootNodeId: rootNode.id, - providerThreadId: queuedProviderThread.id, - cwd: resolvedRuntimePolicy.cwd ?? projection.thread.worktreePath ?? process.cwd(), - createdAt: now, - }), - ), - Effect.mapError( - (cause) => - new OrchestratorDispatchError({ - commandId, - commandType: "message.dispatch", - cause, - }), - ), - )); + reusableCheckpointScope ?? + (yield* checkpointService + .prepareRootRunScope({ + threadId, + runId: queuedRun.id, + rootNodeId: rootNode.id, + providerThreadId: queuedProviderThread.id, + cwd: executionCwd, + createdAt: now, + }) + .pipe(mapQueuedStartError)); const providerSessionId = (!canResumeAcrossInstances && queuedProviderThread.providerSessionId !== null && @@ -3179,7 +3196,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio summary: activeHandoff.summaryText, }; const executionIdentityEvents: ReadonlyArray> = - storedCheckpointScope === undefined || + reusableCheckpointScope === undefined || storedProviderThread.id !== queuedProviderThread.id || attempt.providerInstanceId !== queuedRun.providerInstanceId ? [ @@ -7902,6 +7919,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio activeRun === undefined && (dispatchMode.type === "queue_after_active" || dispatchMode.type === "start_immediately") && (latestRun?.status === "failed" || latestRun?.status === "interrupted") && + latestRun.startedAt === null && latestRun.workspacePreparation?.type === "worktree" && projection.thread.worktreePath === null ? latestRun diff --git a/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts b/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts index e60239e88b076..634a842843b93 100644 --- a/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts +++ b/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts @@ -676,6 +676,8 @@ const writeParentRun = (input: { const providerThreadId = input.stable ? ProviderThreadId.make(`${input.runId}:provider-thread`) : null; + const setupUnfinished = + input.status === "preparing" || input.status === "failed" || input.status === "interrupted"; yield* eventSink.write({ events: [ ...(providerThreadId === null @@ -728,7 +730,7 @@ const writeParentRun = (input: { status: input.status, queuePosition: null, requestedAt: now, - startedAt: now, + startedAt: setupUnfinished ? null : now, completedAt: input.status === "preparing" || input.status === "running" || @@ -737,9 +739,7 @@ const writeParentRun = (input: { : now, checkpointId: input.stable ? CheckpointId.make(`${input.runId}:checkpoint`) : null, contextHandoffId: null, - ...(input.status === "preparing" || - input.status === "failed" || - input.status === "interrupted" + ...(setupUnfinished ? { workspacePreparation: { type: "worktree" as const, baseRef: "main" } } : {}), }, diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 843e51da40423..11525ba32170f 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -9326,7 +9326,7 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { nodeId: run.rootNodeId, providerInstanceId: run.providerInstanceId, occurredAt: now, - payload: { ...run, ...patch, status, startedAt: now, completedAt: now }, + payload: { ...run, status, startedAt: now, completedAt: now, ...patch }, }, ], }); @@ -9433,6 +9433,7 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { yield* dispatcher.send("issue", "agent", false); yield* dispatcher.end("setup", "failed", "", { workspacePreparation: { type: "worktree", baseRef: "main" }, + startedAt: null, }); yield* dispatcher.awaitHeld("issue"); assert.isTrue((yield* dispatcher.runFor("issue")).queueHeld); @@ -9471,6 +9472,75 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { }), ); + it.effect.each(["a new message", "the held queue"] as const)( + "starts %s in the project checkout after a failed turn whose worktree was set up", + (next) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const threadId = ThreadId.make(`runtime-layer-worktree-left-for-checkout:${next}`); + const checkoutRoot = `${process.cwd()}/src`; + yield* seedProject({ + projectId: ProjectId.make(`${threadId}:project`), + title: "Checkout", + workspaceRoot: checkoutRoot, + defaultModelSelection: null, + createdAt: "2026-01-01T00:00:00.000Z", + }); + const { send, runFor, end, awaitHeld } = yield* queueTestThread(threadId); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`${threadId}:message:first`), + threadId, + messageId: MessageId.make(`${threadId}:message:first`), + text: "first", + attachments: [], + modelSelection, + dispatchMode: { + type: "defer_start", + workspaceStrategy: { type: "worktree", baseRef: "main" }, + }, + }); + const first = yield* runFor("first"); + yield* orchestrator.dispatch({ + type: "prepared-run.release", + commandId: CommandId.make(`${threadId}:release`), + threadId, + runId: first.id, + }); + yield* send("queued", "user", false); + yield* end("first", "failed"); + yield* awaitHeld("queued"); + // The user switches the thread to the project checkout. + yield* orchestrator.dispatch({ + type: "thread.metadata.update", + commandId: CommandId.make(`${threadId}:checkout`), + threadId, + worktreePath: null, + }); + if (next === "a new message") { + yield* send("second", "user", true); + assert.equal((yield* runFor("second")).status, "starting"); + return; + } + yield* orchestrator.dispatch({ + type: "queue.resume", + commandId: CommandId.make(`${threadId}:resume`), + threadId, + }); + const queued = yield* runFor("queued"); + assert.equal(queued.status, "starting"); + const projection = yield* orchestrator.getThreadProjection(threadId); + const rootNode = projection.nodes.find((node) => node.id === queued.rootNodeId); + assert.equal( + projection.checkpointScopes.find((scope) => scope.id === rootNode?.checkpointScopeId) + ?.cwd, + checkoutRoot, + ); + }), + ); + it.effect("keeps queued user selections and pauses only the limited provider", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; @@ -10876,7 +10946,7 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { ...active, status: "failed", workspacePreparation: { type: "worktree", baseRef: "main" }, - startedAt: now, + startedAt: null, completedAt: now, } : { ...active, status: "completed", startedAt: now, completedAt: now }, diff --git a/packages/shared/src/orchestrationV2ThreadError.ts b/packages/shared/src/orchestrationV2ThreadError.ts index 8987593a0b0a5..1e011eb1c64fd 100644 --- a/packages/shared/src/orchestrationV2ThreadError.ts +++ b/packages/shared/src/orchestrationV2ThreadError.ts @@ -86,6 +86,7 @@ export function orchestrationV2WorktreePending( (latest?.status === "preparing" || latest?.status === "failed" || latest?.status === "interrupted") && + latest.startedAt === null && latest.workspacePreparation?.type === "worktree" ); } diff --git a/scripts/scenarios/stopped-worktree-turn-sends-in-checkout.e2e.ts b/scripts/scenarios/stopped-worktree-turn-sends-in-checkout.e2e.ts new file mode 100644 index 0000000000000..1f93e154b89e2 --- /dev/null +++ b/scripts/scenarios/stopped-worktree-turn-sends-in-checkout.e2e.ts @@ -0,0 +1,51 @@ +import { expect } from "e2e"; + +import { T3_HOME } from "../e2e.config.ts"; +import { makeState, runPromise, test, WEB } from "./t3.ts"; + +test( + "A worktree thread stopped mid-turn and moved to the project checkout runs its next message", + WEB, + async ({ t3, app, browser, screen }) => { + const project = await t3.project("demo"); + // The question recording waits for an answer, so the turn is running in its new worktree. + const started = await runPromise( + makeState(T3_HOME).cli( + [ + "thread", + "start", + project, + "Ask me something", + "--worktree", + "main", + "--provider", + "devReplay", + "--model", + "question", + "--wait", + "--json", + ], + [2], + ), + ); + await t3.open(JSON.parse(started.stdout) as { threadId: string }); + + const stop = screen.getByRole("button", "Stop generation"); + await stop.waitFor({ timeout: 60_000 }); + await stop.tap(); + await stop.waitFor({ state: "hidden" }); + + await browser.locator('[data-slot="combobox-trigger"][aria-label^="Branch:"]:visible').click(); + await screen.getByRole("option", /^main\b/).tap(); + // The server has moved the thread to the project checkout before the send. + await browser + .locator('[aria-label^="Run context:"][aria-label$="Local checkout"]') + .waitFor({ timeout: 60_000 }); + + await screen.getByRole("textbox").fill("Once more"); + await screen.getByRole("textbox").press("Enter"); + await screen.getByText("Once more").first().waitFor(); + await expect(stop).toBeVisible({ timeout: 60_000 }); + await app.screenshot("running-in-checkout"); + }, +); From a3323d4a433a1a4d074e402083df15c63db1a32c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 13:31:41 -0800 Subject: [PATCH 214/324] perf(web): new thread opens its draft without waiting on t3.json (#41070) --- .../src/components/chat/useComposerSend.ts | 17 +- apps/web/src/hooks/useHandleNewThread.test.ts | 194 +++++++++-------- apps/web/src/hooks/useHandleNewThread.ts | 196 ++++++++++-------- apps/web/src/lib/t3ProjectFileDefaults.ts | 41 +++- 4 files changed, 247 insertions(+), 201 deletions(-) diff --git a/apps/web/src/components/chat/useComposerSend.ts b/apps/web/src/components/chat/useComposerSend.ts index bc38e5001dde1..18a9a54715a38 100644 --- a/apps/web/src/components/chat/useComposerSend.ts +++ b/apps/web/src/components/chat/useComposerSend.ts @@ -67,7 +67,7 @@ import { recordPromptSent } from "../GitHubStarPrompt"; import { stackedThreadToast, toastManager } from "../ui/toast"; import { writeTextToClipboard } from "~/hooks/useCopyToClipboard"; import { newMessageId, newThreadId } from "~/lib/utils"; -import { useNewThreadHandler } from "../../hooks/useHandleNewThread"; +import { readPendingWorkspaceDefault, useNewThreadHandler } from "../../hooks/useHandleNewThread"; import { buildThreadRouteParams } from "../../threadRoutes"; import { beginBackgroundDraftSubmissionByRef, @@ -1754,8 +1754,7 @@ export function useComposerSend(input: ComposerSendInput) { }; const onSendLatest = useStableCallback(onSend); - const onSendWithRouting = async (...args: Parameters) => { - args[0]?.preventDefault(); + const sendWithEnvironmentRefresh = async (...args: Parameters) => { const refresh = args[3] || sendInFlightRef.current || readPendingEnvironmentChange() !== null ? null @@ -1767,6 +1766,18 @@ export function useComposerSend(input: ComposerSendInput) { }); if (ready) return onSendLatest(...args); }; + const sendWithEnvironmentRefreshLatest = useStableCallback(sendWithEnvironmentRefresh); + const onSendWithRouting = async (...args: Parameters) => { + args[0]?.preventDefault(); + const workspaceDefault = + draftId && !sendInFlightRef.current ? readPendingWorkspaceDefault(draftId) : null; + if (workspaceDefault === null) return sendWithEnvironmentRefresh(...args); + sendInFlightRef.current = true; + await workspaceDefault.finally(() => { + sendInFlightRef.current = false; + }); + return sendWithEnvironmentRefreshLatest(...args); + }; // No load-balancing refresh: it bails once the draft is no longer displayed, which is the // only time a detached send runs, so the draft keeps the environment it was dictated for. const captureDetachedSend = useStableCallback(() => onSend); diff --git a/apps/web/src/hooks/useHandleNewThread.test.ts b/apps/web/src/hooks/useHandleNewThread.test.ts index 7c64d0077cc2b..07df36fe906a4 100644 --- a/apps/web/src/hooks/useHandleNewThread.test.ts +++ b/apps/web/src/hooks/useHandleNewThread.test.ts @@ -2,9 +2,15 @@ import { describe, expect, it, vi } from "vite-plus/test"; import type { EnvironmentId, ProjectId, RuntimeMode } from "@t3tools/contracts"; const testState = vi.hoisted(() => { - let completeProjectFileRead: (value: null) => void = () => undefined; - let projectFileRead = Promise.resolve(null); - let projectRemoved = false; + type ProjectFile = { readonly defaultThreadEnvMode?: "local" | "worktree" } | null; + let completeProjectFileRead: (value: ProjectFile) => void = () => undefined; + let projectFileRead = Promise.resolve(null); + let draftSession = { + envMode: "local", + worktreePath: null, + branch: null as string | null, + environmentSelection: undefined as "manual" | undefined, + }; let connectedEnvironmentIds = ["environment-primary", "environment-ssh"]; let targetSettings = { defaultThreadEnvMode: "local" as "local" | "worktree" | null, @@ -19,7 +25,6 @@ const testState = vi.hoisted(() => { readonly threadId: string; } | null = null; let openDraftRoute: { readonly kind: "draft"; readonly draftId: string } | null = null; - let draftsWithUserText = new Set(); const router = { state: { location: { href: "/" }, @@ -37,7 +42,7 @@ const testState = vi.hoisted(() => { getDraftSessionByLogicalProjectKey: vi.fn(() => storedDraft), getDraftSession: vi.fn(() => openDraftRoute === null - ? null + ? { ...draftSession, promotedTo: null, startFromOrigin: false } : { logicalProjectKey: "remote-project", promotedTo: null, @@ -56,34 +61,29 @@ const testState = vi.hoisted(() => { }; return { - completeProjectFileRead: (value: null) => completeProjectFileRead(value), + completeProjectFileRead: (value: ProjectFile) => completeProjectFileRead(value), + discoverBranch(branch: string) { + draftSession = { ...draftSession, branch }; + }, + keepEarlierManualChoice() { + draftSession = { ...draftSession, environmentSelection: "manual" }; + }, + pickBranch(branch: string) { + draftSession = { ...draftSession, branch, environmentSelection: "manual" }; + }, draftStore, get projectFileRead() { return projectFileRead; }, - get projectRemoved() { - return projectRemoved; - }, get connectedEnvironmentIds() { return connectedEnvironmentIds; }, disconnect(environmentId: string) { connectedEnvironmentIds = connectedEnvironmentIds.filter((id) => id !== environmentId); }, - removeProject() { - projectRemoved = true; - }, - hasUserText: (draft: { readonly draftId?: string } | null | undefined) => - draft?.draftId !== undefined && draftsWithUserText.has(draft.draftId), - giveUserText(draftId: string) { - draftsWithUserText = new Set([...draftsWithUserText, draftId]); - }, get openDraftRoute() { return openDraftRoute; }, - registerDraft(draft: NonNullable) { - storedDraft = draft; - }, openEmptyDraft(draftId: string) { openDraftRoute = { kind: "draft", draftId }; }, @@ -99,8 +99,12 @@ const testState = vi.hoisted(() => { ) { storedDraft = nextStoredDraft; openDraftRoute = null; - draftsWithUserText = new Set(); - projectRemoved = false; + draftSession = { + envMode: "local", + worktreePath: null, + branch: null, + environmentSelection: undefined, + }; connectedEnvironmentIds = ["environment-primary", "environment-ssh"]; targetSettings = { defaultThreadEnvMode: workspaceDefaults.envMode, @@ -113,7 +117,7 @@ const testState = vi.hoisted(() => { draftStore.setDraftThreadContext.mockClear(); draftStore.setLogicalProjectDraftThreadId.mockClear(); draftStore.setPrompt.mockClear(); - projectFileRead = new Promise((resolve) => { + projectFileRead = new Promise((resolve) => { completeProjectFileRead = resolve; }); }, @@ -186,6 +190,7 @@ vi.mock("@tanstack/react-router", () => ({ useParams: () => null, useRouter: () => testState.router, })); +vi.mock("react-dom", () => ({ flushSync: (update: () => void) => update() })); vi.mock("react", () => ({ useCallback: (callback: T) => callback, useMemo: (factory: () => T) => factory(), @@ -198,8 +203,7 @@ vi.mock("../composerDraftStore", () => { getState: () => testState.draftStore, }); return { - composerDraftHasUserContent: (draft: { readonly draftId?: string } | null | undefined) => - testState.hasUserText(draft), + composerDraftHasUserContent: () => false, markPromotedDraftThreadByRef: vi.fn(), useComposerDraftStore, }; @@ -212,6 +216,7 @@ vi.mock("../lib/chatThreadActions", async (importOriginal) => ({ vi.mock("../providerInstances", () => ({ resolveDefaultProviderModelSelection: () => null })); vi.mock("../lib/t3ProjectFileDefaults", () => ({ readT3ProjectFile: () => testState.projectFileRead, + peekT3ProjectFile: () => undefined, })); vi.mock("../lib/utils", () => ({ newDraftId: () => "draft-delayed", @@ -231,8 +236,7 @@ vi.mock("../state/entities", () => { defaultModelSelection: null, }; return { - readProject: () => (testState.projectRemoved ? null : project), - readProjects: () => (testState.projectRemoved ? [] : [project]), + readProjects: () => [project], readThreadShell: () => null, readThreadShells: () => [], useProjects: () => [], @@ -257,7 +261,11 @@ vi.mock("../uiStateStore", () => ({ })); vi.mock("./useSettings", () => ({ getClientSettings: () => ({}) })); -import { resolveDefaultProjectRef, useNewThreadHandler } from "./useHandleNewThread"; +import { + readPendingWorkspaceDefault, + resolveDefaultProjectRef, + useNewThreadHandler, +} from "./useHandleNewThread"; describe.each([ ["new", null], @@ -271,58 +279,79 @@ describe.each([ }, ], ])("useNewThreadHandler with a %s draft", (_, draft) => { - it("abandons a delayed draft open when the user navigates elsewhere", async () => { - testState.reset(draft); - const openThread = useNewThreadHandler(); - const pendingOpen = openThread( - { environmentId: "environment-ssh", projectId: "project-remote" } as never, - { replace: true }, + it("opens the draft before the project file is read, then applies its workspace default", async () => { + testState.reset(draft, { envMode: null, startFromOrigin: false }); + const opened = await useNewThreadHandler()({ + environmentId: "environment-ssh", + projectId: "project-remote", + } as never); + + expect(testState.router.navigate).toHaveBeenCalledOnce(); + expect(testState.draftStore.setLogicalProjectDraftThreadId).toHaveBeenCalledWith( + "remote-project", + expect.anything(), + opened?.draftId, + expect.objectContaining({ envMode: "local" }), ); + testState.draftStore.setDraftThreadContext.mockClear(); - testState.router.state.location.href = "/usage"; - testState.completeProjectFileRead(null); - await pendingOpen; + testState.discoverBranch("main"); + const pendingDefault = readPendingWorkspaceDefault(opened!.draftId); + expect(pendingDefault).not.toBeNull(); + testState.completeProjectFileRead({ defaultThreadEnvMode: "worktree" }); + await pendingDefault; - expect(testState.router.state.location.href).toBe("/usage"); - expect(testState.router.navigate).not.toHaveBeenCalled(); - expect(testState.draftStore.setLogicalProjectDraftThreadId).not.toHaveBeenCalled(); - }); + expect(readPendingWorkspaceDefault(opened!.draftId)).toBeNull(); - it("resolves to the draft another opener showed for the same project meanwhile", async () => { - testState.reset(draft); - const pendingOpen = useNewThreadHandler()( - { environmentId: "environment-ssh", projectId: "project-remote" } as never, - { replace: true }, - ); + expect(testState.draftStore.setDraftThreadContext).toHaveBeenCalledWith(opened?.draftId, { + envMode: "worktree", + startFromOrigin: false, + }); + }); - // The location moves before the route matches do. - testState.registerDraft({ - draftId: "draft-home", + it("applies the project file's default to a draft chosen manually before it opened", async () => { + testState.reset(draft, { envMode: null, startFromOrigin: false }); + testState.keepEarlierManualChoice(); + const opened = await useNewThreadHandler()({ environmentId: "environment-ssh", - promotedTo: null, - threadId: "thread-home", - }); - testState.router.state.location.href = "/draft/draft-home"; - testState.completeProjectFileRead(null); + projectId: "project-remote", + } as never); + testState.draftStore.setDraftThreadContext.mockClear(); - await expect(pendingOpen).resolves.toEqual({ - draftId: "draft-home", - threadId: "thread-home", + const pendingDefault = readPendingWorkspaceDefault(opened!.draftId); + expect(pendingDefault).not.toBeNull(); + testState.completeProjectFileRead({ defaultThreadEnvMode: "worktree" }); + await pendingDefault; + + expect(testState.draftStore.setDraftThreadContext).toHaveBeenCalledWith(opened?.draftId, { + envMode: "worktree", + startFromOrigin: false, }); - expect(testState.router.navigate).not.toHaveBeenCalled(); - expect(testState.draftStore.setLogicalProjectDraftThreadId).not.toHaveBeenCalled(); + }); + + it("keeps a branch the user picked while the project file loaded", async () => { + testState.reset(draft, { envMode: null, startFromOrigin: false }); + const opened = await useNewThreadHandler()({ + environmentId: "environment-ssh", + projectId: "project-remote", + } as never); + testState.draftStore.setDraftThreadContext.mockClear(); + + testState.pickBranch("feature"); + expect(readPendingWorkspaceDefault(opened!.draftId)).toBeNull(); + testState.completeProjectFileRead({ defaultThreadEnvMode: "worktree" }); + await testState.projectFileRead; + + expect(testState.draftStore.setDraftThreadContext).not.toHaveBeenCalled(); }); it("sets the prompt before the draft shows", async () => { testState.reset(draft); - const pendingOpen = useNewThreadHandler()( + const opened = await useNewThreadHandler()( { environmentId: "environment-ssh", projectId: "project-remote" } as never, { prompt: "Read the playbook. " }, ); - testState.completeProjectFileRead(null); - const opened = await pendingOpen; - expect(testState.draftStore.setPrompt).toHaveBeenCalledWith( opened?.draftId, "Read the playbook. ", @@ -331,46 +360,9 @@ describe.each([ testState.router.navigate.mock.invocationCallOrder[0] ?? 0, ); }); - - it("abandons a delayed draft open when the project is removed meanwhile", async () => { - testState.reset(draft); - const pendingOpen = useNewThreadHandler()( - { environmentId: "environment-ssh", projectId: "project-remote" } as never, - { replace: true }, - ); - - testState.removeProject(); - testState.completeProjectFileRead(null); - - await expect(pendingOpen).resolves.toBeNull(); - expect(testState.router.navigate).not.toHaveBeenCalled(); - expect(testState.draftStore.setLogicalProjectDraftThreadId).not.toHaveBeenCalled(); - }); }); describe("useNewThreadHandler", () => { - it("keeps the text of a draft that gained some while it waited", async () => { - testState.reset(null); - const raced = { - draftId: "draft-raced", - environmentId: "environment-ssh", - promotedTo: null, - threadId: "thread-raced", - }; - testState.draftStore.getDraftSessionByLogicalProjectKey - .mockReturnValueOnce(null) - .mockReturnValueOnce(raced as never); - testState.giveUserText("draft-raced"); - - const opened = await useNewThreadHandler()( - { environmentId: "environment-ssh", projectId: "project-remote" } as never, - { prompt: "Read the playbook. " }, - ); - - expect(opened?.draftId).toBe("draft-raced"); - expect(testState.draftStore.setPrompt).not.toHaveBeenCalled(); - }); - it("seeds the prompt into the empty draft that is already open", async () => { testState.reset(null); testState.openEmptyDraft("draft-open"); diff --git a/apps/web/src/hooks/useHandleNewThread.ts b/apps/web/src/hooks/useHandleNewThread.ts index 1be24bd9a3489..ea9c42b2649b5 100644 --- a/apps/web/src/hooks/useHandleNewThread.ts +++ b/apps/web/src/hooks/useHandleNewThread.ts @@ -3,12 +3,19 @@ import { scopeProjectRef, scopeThreadRef, } from "@t3tools/client-runtime/environment"; -import { DEFAULT_SERVER_SETTINGS, type ScopedProjectRef, type ThreadId } from "@t3tools/contracts"; +import { + DEFAULT_SERVER_SETTINGS, + type ScopedProjectRef, + type T3ProjectFile, + type ThreadId, +} from "@t3tools/contracts"; import { type AnyRouter, useRouter } from "@tanstack/react-router"; +import { flushSync } from "react-dom"; import { composerDraftHasUserContent, markPromotedDraftThreadByRef, type DraftId, + type DraftSessionState, type DraftThreadEnvMode, type DraftThreadState, useComposerDraftStore, @@ -24,7 +31,6 @@ import { } from "@t3tools/client-runtime/state/project-grouping"; import { resolveNewThreadEnvMode, resolveProjectSettings } from "@t3tools/shared/projectSettings"; import { - readProject, readProjects, readThreadShell, readThreadShells, @@ -39,7 +45,7 @@ import { threadHasStarted, } from "../lib/chatThreadActions"; import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; -import { readT3ProjectFile } from "../lib/t3ProjectFileDefaults"; +import { peekT3ProjectFile, readT3ProjectFile } from "../lib/t3ProjectFileDefaults"; import { appAtomRegistry } from "../rpc/atomRegistry"; import { environmentSummaries } from "../state/presentation"; import { environmentServerConfigsAtom } from "../state/server"; @@ -66,6 +72,39 @@ export function readLastUsedProjectKey(): string | null { } } +// Drafts that opened before their project's t3.json was read. A send waits for the file's +// workspace default unless the user has already chosen a workspace. +interface ProvisionalWorkspace { + readonly envMode: DraftThreadEnvMode; + // A reused draft keeps an earlier "manual" marker; only a switch to manual after opening is a choice. + readonly openedManual: boolean; +} + +const pendingWorkspaceDefaults = new Map< + DraftId, + ProvisionalWorkspace & { readonly settled: Promise } +>(); + +function keepsProvisionalWorkspace( + draft: DraftSessionState | null, + provisional: ProvisionalWorkspace, +): draft is DraftSessionState { + return ( + draft !== null && + draft.promotedTo == null && + draft.envMode === provisional.envMode && + draft.worktreePath === null && + (provisional.openedManual || draft.environmentSelection !== "manual") + ); +} + +export function readPendingWorkspaceDefault(draftId: DraftId): Promise | null { + const pending = pendingWorkspaceDefaults.get(draftId); + if (pending === undefined) return null; + const draft = useComposerDraftStore.getState().getDraftSession(draftId); + return keepsProvisionalWorkspace(draft, pending) ? pending.settled : null; +} + interface NewThreadWorkspaceOptions { branch?: string | null; worktreePath?: string | null; @@ -129,8 +168,6 @@ export function createNewThreadHandler(router: AnyRouter) { if (composerDraftHasUserContent(getComposerDraft(draftId))) return; setPrompt(draftId, options.prompt); }; - const requestingRouteHref = router.state.location.href; - const routeChangedSinceRequest = () => router.state.location.href !== requestingRouteHref; const currentRouteTarget = getCurrentRouteTarget(); const carrySourceShell = currentRouteTarget?.kind === "server" ? readThreadShell(currentRouteTarget.threadRef) : null; @@ -163,8 +200,6 @@ export function createNewThreadHandler(router: AnyRouter) { candidate.id === projectRef.projectId && candidate.environmentId === projectRef.environmentId, ); - const abandonedSinceRequest = () => - routeChangedSinceRequest() || (project !== undefined && readProject(projectRef) === null); const projectSettings = resolveProjectSettings( targetServerSettings, project?.id ?? null, @@ -199,19 +234,8 @@ export function createNewThreadHandler(router: AnyRouter) { currentRouteTarget?.kind === "draft" ? currentRouteTarget.draftId : null, destinationDraftId, }); - const resolveDefaultEnvMode = async (): Promise => { - // Environment queries wait for a connection, so reading the project file on an - // offline machine would never settle and the draft would never open. - const consultProjectFile = - project !== undefined && - projectSettings.settings.defaultThreadEnvMode === null && - appAtomRegistry - .get(environmentSummaries.connectedEnvironmentIdsAtom) - .includes(project.environmentId); - const projectFile = consultProjectFile - ? await readT3ProjectFile(project.environmentId, project.workspaceRoot) - : null; - return resolveNewThreadEnvMode({ + const envModeFor = (projectFile: T3ProjectFile | null): DraftThreadEnvMode => + resolveNewThreadEnvMode({ projectSettings: resolveProjectSettings( targetServerSettings, project?.id ?? null, @@ -231,25 +255,60 @@ export function createNewThreadHandler(router: AnyRouter) { [], ) > 0, }); + const startFromOriginFor = (envMode: DraftThreadEnvMode) => + resolveNewDraftStartFromOrigin({ + envMode, + newWorktreesStartFromOrigin: projectSettings.settings.newWorktreesStartFromOrigin, + }); + // The draft opens without waiting on t3.json: a cold read takes seconds on a loaded host. + // Its workspace default lands afterwards unless the user picked a workspace or sent first. + const resolveDefaultEnvMode = () => { + // Environment queries wait for a connection, so an offline machine's file is never read. + const consultProjectFile = + project !== undefined && + projectSettings.settings.defaultThreadEnvMode === null && + appAtomRegistry + .get(environmentSummaries.connectedEnvironmentIdsAtom) + .includes(project.environmentId); + if (!consultProjectFile) return { envMode: envModeFor(null), applyProjectFile: () => {} }; + const projectFileRead = readT3ProjectFile(project.environmentId, project.workspaceRoot); + const cachedProjectFile = peekT3ProjectFile(project.environmentId, project.workspaceRoot); + if (cachedProjectFile !== undefined) { + return { envMode: envModeFor(cachedProjectFile), applyProjectFile: () => {} }; + } + const envMode = envModeFor(null); + const applyProjectFile = (draftId: DraftId) => { + const provisional: ProvisionalWorkspace = { + envMode, + openedManual: getDraftSession(draftId)?.environmentSelection === "manual", + }; + const settled = projectFileRead + .then((projectFile) => { + const fileEnvMode = envModeFor(projectFile); + const draft = getDraftSession(draftId); + if (fileEnvMode === envMode || !keepsProvisionalWorkspace(draft, provisional)) return; + // Commit before a waiting send re-reads the composer's workspace. + flushSync(() => + setDraftThreadContext(draftId, { + envMode: fileEnvMode, + ...(draft.startFromOrigin === startFromOriginFor(envMode) + ? { startFromOrigin: startFromOriginFor(fileEnvMode) } + : {}), + }), + ); + }) + .finally(() => { + if (pendingWorkspaceDefaults.get(draftId)?.settled === settled) { + pendingWorkspaceDefaults.delete(draftId); + } + }); + pendingWorkspaceDefaults.set(draftId, { ...provisional, settled }); + }; + return { envMode, applyProjectFile }; }; const logicalProjectKey = project ? deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings) : scopedProjectKey(projectRef); - // Another opener (home's own first-project draft) may have reached this project's draft first. - // Matches lag the location during a navigation, so compare against the location. - const resultIfAbandoned = () => { - const draft = getDraftSessionByLogicalProjectKey(logicalProjectKey); - if (draft === null || draft.promotedTo != null || readProject(projectRef) === null) { - return null; - } - const draftHref = router.buildLocation({ - to: "/draft/$draftId", - params: { draftId: draft.draftId }, - }).href; - return router.state.location.href === draftHref - ? { draftId: draft.draftId, threadId: draft.threadId } - : null; - }; const hasBranchOption = options?.branch !== undefined; const hasWorktreePathOption = options?.worktreePath !== undefined; const hasEnvModeOption = options?.envMode !== undefined; @@ -286,37 +345,17 @@ export function createNewThreadHandler(router: AnyRouter) { const hasExplicitWorkspaceOption = hasBranchOption || hasWorktreePathOption || hasEnvModeOption || hasStartFromOriginOption; let workspaceContext: NewThreadWorkspaceOptions | null = null; + let applyProjectFile: ((draftId: DraftId) => void) | null = null; if (hasExplicitWorkspaceOption) { workspaceContext = pickExplicitWorkspaceOptions(options); } else if (!isDraftAlreadyOpen) { - const defaultEnvMode = await resolveDefaultEnvMode(); - if (abandonedSinceRequest()) { - return resultIfAbandoned(); - } - // Concurrent calls may change the draft; stale resets, remaps, or navigation could clobber it. - const routeTargetNow = getCurrentRouteTarget(); - const openedMeanwhile = - routeTargetNow?.kind === "draft" && - routeTargetNow.draftId === emptyStoredDraftThread.draftId; - const promotedMeanwhile = - storedDraftThreadRef !== null && readThreadShell(storedDraftThreadRef) !== null; - const remappedMeanwhile = - getDraftSessionByLogicalProjectKey(logicalProjectKey)?.draftId !== - emptyStoredDraftThread.draftId; - const investedMeanwhile = composerDraftHasUserContent( - getComposerDraft(emptyStoredDraftThread.draftId), - ); - if (openedMeanwhile || promotedMeanwhile || remappedMeanwhile || investedMeanwhile) { - return null; - } + const defaultEnvMode = resolveDefaultEnvMode(); + applyProjectFile = defaultEnvMode.applyProjectFile; workspaceContext = { branch: null, worktreePath: null, - envMode: defaultEnvMode, - startFromOrigin: resolveNewDraftStartFromOrigin({ - envMode: defaultEnvMode, - newWorktreesStartFromOrigin: projectSettings.settings.newWorktreesStartFromOrigin, - }), + envMode: defaultEnvMode.envMode, + startFromOrigin: startFromOriginFor(defaultEnvMode.envMode), }; } if (workspaceContext) { @@ -356,6 +395,7 @@ export function createNewThreadHandler(router: AnyRouter) { threadId: emptyStoredDraftThread.threadId, }; seedPrompt(emptyStoredDraftThread.draftId); + applyProjectFile?.(emptyStoredDraftThread.draftId); const routeTargetAfterWrites = getCurrentRouteTarget(); if ( routeTargetAfterWrites?.kind === "draft" && @@ -405,44 +445,15 @@ export function createNewThreadHandler(router: AnyRouter) { const threadId = newThreadId(); const createdAt = new Date().toISOString(); return (async () => { - const initialEnvMode = options?.envMode ?? (await resolveDefaultEnvMode()); - if (abandonedSinceRequest()) { - return resultIfAbandoned(); - } - // Reuse drafts registered while awaiting so their pending navigation cannot lose them. - const racedDraft = getDraftSessionByLogicalProjectKey(logicalProjectKey); - if ( - racedDraft && - racedDraft.draftId !== storedDraftThread?.draftId && - readThreadShell(scopeThreadRef(racedDraft.environmentId, racedDraft.threadId)) === null - ) { - setLogicalProjectDraftThreadId(logicalProjectKey, projectRef, racedDraft.draftId, { - threadId: racedDraft.threadId, - createdAt: racedDraft.createdAt, - runtimeMode: racedDraft.runtimeMode, - interactionMode: racedDraft.interactionMode, - ...pickExplicitWorkspaceOptions(options), - }); - seedPrompt(racedDraft.draftId); - await router.navigate({ - to: "/draft/$draftId", - params: { draftId: racedDraft.draftId }, - replace: options?.replace ?? false, - }); - return { draftId: racedDraft.draftId, threadId: racedDraft.threadId }; - } + const defaultEnvMode = options?.envMode === undefined ? resolveDefaultEnvMode() : null; + const initialEnvMode = options?.envMode ?? defaultEnvMode?.envMode ?? "local"; setLogicalProjectDraftThreadId(logicalProjectKey, projectRef, draftId, { threadId, createdAt, branch: options?.branch ?? null, worktreePath: options?.worktreePath ?? null, envMode: initialEnvMode, - startFromOrigin: - options?.startFromOrigin ?? - resolveNewDraftStartFromOrigin({ - envMode: initialEnvMode, - newWorktreesStartFromOrigin: projectSettings.settings.newWorktreesStartFromOrigin, - }), + startFromOrigin: options?.startFromOrigin ?? startFromOriginFor(initialEnvMode), runtimeMode: defaultRuntimeMode, ...(carryInteractionMode ? { interactionMode: carryInteractionMode } : {}), }); @@ -452,6 +463,7 @@ export function createNewThreadHandler(router: AnyRouter) { setModelSelection(draftId, modelSelectionOverride, { replaceOptions: true }); } seedPrompt(draftId); + defaultEnvMode?.applyProjectFile(draftId); await router.navigate({ to: "/draft/$draftId", params: { draftId }, diff --git a/apps/web/src/lib/t3ProjectFileDefaults.ts b/apps/web/src/lib/t3ProjectFileDefaults.ts index b5000b4ddd92f..a780a1d906cdb 100644 --- a/apps/web/src/lib/t3ProjectFileDefaults.ts +++ b/apps/web/src/lib/t3ProjectFileDefaults.ts @@ -1,6 +1,12 @@ -import { T3_PROJECT_FILE_NAME, type EnvironmentId, type T3ProjectFile } from "@t3tools/contracts"; +import { + T3_PROJECT_FILE_NAME, + type EnvironmentId, + type ProjectReadFileResult, + type T3ProjectFile, +} from "@t3tools/contracts"; import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile"; import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime"; +import { AsyncResult } from "effect/reactivity"; import { getProjectFileQueryAtom, @@ -8,6 +14,21 @@ import { } from "~/components/files/projectFilesQueryState"; import { appAtomRegistry } from "~/rpc/atomRegistry"; +function toT3ProjectFile( + environmentId: EnvironmentId, + workspaceRoot: string, + result: ProjectReadFileResult | null, +): T3ProjectFile | null { + const data = resolveProjectFileQueryData( + environmentId, + workspaceRoot, + T3_PROJECT_FILE_NAME, + result, + ); + if (data === null || data.exists === false || data.truncated) return null; + return parseT3ProjectFile(data.contents); +} + export async function readT3ProjectFile( environmentId: EnvironmentId, workspaceRoot: string, @@ -17,12 +38,22 @@ export async function readT3ProjectFile( getProjectFileQueryAtom(environmentId, workspaceRoot, T3_PROJECT_FILE_NAME), { reportDefect: false, reportFailure: false }, ); - const data = resolveProjectFileQueryData( + return toT3ProjectFile( environmentId, workspaceRoot, - T3_PROJECT_FILE_NAME, result._tag === "Success" ? result.value : null, ); - if (data === null || data.exists === false || data.truncated) return null; - return parseT3ProjectFile(data.contents); +} + +/** The project's t3.json from an earlier read, or `undefined` when none has loaded yet. */ +export function peekT3ProjectFile( + environmentId: EnvironmentId, + workspaceRoot: string, +): T3ProjectFile | null | undefined { + const result = appAtomRegistry.get( + getProjectFileQueryAtom(environmentId, workspaceRoot, T3_PROJECT_FILE_NAME), + ); + return AsyncResult.isSuccess(result) + ? toT3ProjectFile(environmentId, workspaceRoot, result.value) + : undefined; } From dd19bce823d833b5612fd74851d50047e65347fa Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 13:50:41 -0800 Subject: [PATCH 215/324] fix(server): a dropped dictation client frees the speech engine within seconds (#41075) --- apps/server/src/speech/stream.test.ts | 31 ++++++++++++++++++++++++ apps/server/src/speech/stream.ts | 35 +++++++++++++++++++++++---- 2 files changed, 61 insertions(+), 5 deletions(-) diff --git a/apps/server/src/speech/stream.test.ts b/apps/server/src/speech/stream.test.ts index 71d2fdca91310..7ce8b76dd15d2 100644 --- a/apps/server/src/speech/stream.test.ts +++ b/apps/server/src/speech/stream.test.ts @@ -1,9 +1,12 @@ import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer"; import { it } from "@effect/vitest"; import { expect } from "vite-plus/test"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; +import * as Socket from "effect/socket/Socket"; +import * as TestClock from "effect/testing/TestClock"; import { HttpRouter, HttpServer, HttpServerRequest, HttpServerResponse } from "effect/http"; import { SpeechStreamEvent, DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS } from "@t3tools/contracts"; import type { SpeechService, SpeechStream } from "./SpeechService.ts"; @@ -167,3 +170,31 @@ it.live("processes pipelined audio before the finish command", () => { }, ).pipe(Effect.scoped, Effect.provide(NodeHttpServer.layerTest)); }); + +it.effect("releases the stream when a started client goes silent", () => + Effect.gen(function* () { + const released = yield* Deferred.make(); + let pulls = 0; + const socket = Socket.make({ + reader: Effect.succeed({ + pull: Effect.suspend(() => + pulls++ === 0 + ? Effect.succeed([ + JSON.stringify({ type: "start", options: DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS }), + ] as const) + : Effect.never, + ), + upgrade: () => Effect.void, + }), + writer: Effect.succeed({ write: () => Effect.void, writeAll: () => Effect.void }), + }); + const stream: SpeechStream = { feed: () => Effect.never, finish: Effect.never }; + yield* runSpeechSocket(socket, { + startStream: () => + Effect.acquireRelease(Effect.succeed(stream), () => Deferred.succeed(released, undefined)), + }).pipe(Effect.scoped, Effect.forkChild); + + yield* TestClock.adjust("1 minute"); + expect(yield* Deferred.isDone(released)).toBe(true); + }), +); diff --git a/apps/server/src/speech/stream.ts b/apps/server/src/speech/stream.ts index 60d5acb2334e2..8eb9b9626010b 100644 --- a/apps/server/src/speech/stream.ts +++ b/apps/server/src/speech/stream.ts @@ -8,6 +8,7 @@ import { } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; @@ -16,6 +17,10 @@ import * as Socket from "effect/socket/Socket"; import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts"; import * as SpeechService from "./SpeechService.ts"; +// A recording client streams audio continuously; behind a proxy a vanished +// client never closes the server side, so silence is the only sign it is gone. +const SPEECH_SOCKET_IDLE_TIMEOUT = "15 seconds"; + const decodeCommand = Schema.decodeUnknownEffect(Schema.fromJsonString(SpeechStreamCommand)); /** One socket owns one stream. Audio is processed and acknowledged in arrival order. */ @@ -68,18 +73,38 @@ export const runSpeechSocket = Effect.fn("speech.runSocket")(function* ( ); }; const reader = yield* socket.reader; - yield* Effect.gen(function* () { + // Silence only counts while every received frame has been answered. + let unanswered = 0; + const activity = yield* Queue.sliding(1); + const idle = Effect.gen(function* () { + while (true) { + const heard = yield* Queue.take(activity).pipe( + Effect.timeoutOption(SPEECH_SOCKET_IDLE_TIMEOUT), + ); + if (Option.isNone(heard) && unanswered === 0) return; + } + }); + const read = Effect.gen(function* () { const pending = yield* Queue.bounded(2); - yield* Effect.forever(Queue.take(pending).pipe(Effect.flatMap(receive))).pipe( - Effect.forkScoped, - ); + yield* Effect.forever( + Queue.take(pending).pipe( + Effect.flatMap(receive), + Effect.andThen(() => { + unanswered--; + return Queue.offer(activity, undefined); + }), + ), + ).pipe(Effect.forkScoped); while (true) { const frames = yield* reader.pull; + unanswered += frames.length; + yield* Queue.offer(activity, undefined); yield* Effect.forEach(frames, (frame) => Queue.offer(pending, frame), { discard: true, }); } - }).pipe( + }); + yield* Effect.raceFirst(read, idle).pipe( Effect.timeoutOrElse({ duration: "10 minutes", // The socket read loop is already interrupted here; its writer can no longer send. From 0938476b95fa28f6d626144d6a34b0e20d1dd595 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 14:17:38 -0800 Subject: [PATCH 216/324] fix(web): Thinking row no longer shows below a streaming reply (#41060) --- apps/mobile/src/lib/threadActivity.test.ts | 11 +++++++- apps/mobile/src/lib/threadActivity.ts | 6 +++++ .../chat/MessagesTimeline.logic.test.ts | 26 +++++++++++++++++-- .../components/chat/MessagesTimeline.logic.ts | 6 +++++ 4 files changed, 46 insertions(+), 3 deletions(-) diff --git a/apps/mobile/src/lib/threadActivity.test.ts b/apps/mobile/src/lib/threadActivity.test.ts index 3a4f54c59c41b..8d66dfaf5c520 100644 --- a/apps/mobile/src/lib/threadActivity.test.ts +++ b/apps/mobile/src/lib/threadActivity.test.ts @@ -1483,7 +1483,7 @@ describe("buildThreadFeed", () => { expect(presented.some((entry) => entry.type === "thinking")).toBe(false); }); - it("does not show Thinking once the open run's provider turn has ended", () => { + it("does not show Thinking once the provider turn has ended or its reply is streaming", () => { const startedAt = "2026-04-01T00:00:01.000Z"; const run = { runId, status: "running" as const, startedAt, completedAt: null }; expect( @@ -1495,6 +1495,15 @@ describe("buildThreadFeed", () => { startedAt, ).map((row) => row.type), ).toEqual(["run-fold"]); + const streamingReply = buildThreadFeed([ + projected(userMessage(), 0), + projected({ ...assistantMessage(), streaming: true }, 1), + ]); + expect( + deriveThreadFeedPresentation(streamingReply, run, new Set(), new Set(), startedAt).map( + (row) => row.type, + ), + ).toEqual(["message", "run-fold", "message"]); }); it("hides tool calls or everything but the final answer", () => { const at = (second: number) => `2026-06-20T00:00:${String(second).padStart(2, "0")}.000Z`; diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts index 4bff1af9e3750..1760b37b49606 100644 --- a/apps/mobile/src/lib/threadActivity.ts +++ b/apps/mobile/src/lib/threadActivity.ts @@ -1957,10 +1957,16 @@ export function deriveThreadFeedPresentation( } } if (liveFold !== null && !liveFoldPlaced) result.push(liveFold); + const latestRow = result.at(-1); + const replyIsStreaming = + latestRow?.type === "message" && + latestRow.message.role === "assistant" && + latestRow.message.streaming; if ( isWorking && activeWorkStartedAt !== null && latestRun?.turnEnded !== true && + !replyIsStreaming && (activeRunId === null || !compactionCommandRunIds.has(activeRunId)) && !result.some( (row) => diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index 76dc0aa6471bf..f1726cbbb92b2 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -1785,7 +1785,7 @@ describe("deriveMessagesTimelineRows", () => { expect(rows.at(-1)).toMatchObject({ kind: "thinking" }); }); - it("does not show Thinking once the open run's provider turn has ended", () => { + it("does not show Thinking once the provider turn has ended or its reply is streaming", () => { const input = { timelineEntries: [ { @@ -1821,6 +1821,29 @@ describe("deriveMessagesTimelineRows", () => { latestRun: { ...input.latestRun, turnEnded: true }, }); expect(ended.some((row) => row.kind === "thinking")).toBe(false); + + const streamingReply = deriveMessagesTimelineRows({ + ...input, + timelineEntries: [ + ...input.timelineEntries, + { + id: "assistant-entry", + kind: "message" as const, + createdAt: "2026-01-01T00:00:05Z", + message: { + id: "assistant" as never, + role: "assistant" as const, + text: "Here is the first paragraph of the answer", + runId: "turn-1" as never, + createdAt: "2026-01-01T00:00:05Z", + updatedAt: "2026-01-01T00:00:06Z", + streaming: true, + }, + }, + ], + }); + expect(streamingReply.at(-1)?.id).toBe("assistant-entry"); + expect(streamingReply.some((row) => row.kind === "thinking")).toBe(false); }); it("keeps a promptless restart in one active visual response", () => { @@ -4548,7 +4571,6 @@ it("keeps the working header in place across worktree setup handoff", () => { "worktree-setup", "working", "message", - "thinking", ]); const stage = (id: "agent" | "setup-script", status: "done" | "running") => diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index 2d920ad816277..6bd30f1ac3212 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -2383,6 +2383,11 @@ export function deriveMessagesTimelineRows( } } + const latestTimelineEntry = timelineEntries.at(-1); + const replyIsStreaming = + latestTimelineEntry?.kind === "message" && + latestTimelineEntry.message.role === "assistant" && + latestTimelineEntry.message.streaming; const hasWorkingRow = nextRows.some((row) => row.kind === "working"); if (input.isWorking && !hasWorkingRow && activeTurnHeaderIndex === timelineEntries.length) { appendWorkingRow(); @@ -2390,6 +2395,7 @@ export function deriveMessagesTimelineRows( if ( input.isWorking && input.latestRun?.turnEnded !== true && + !replyIsStreaming && !setupOwnsWorkingSlot && !hasActiveCompaction && !compactionOnlyRunFinished && From 7103527dccfaecbd1e1478155297cce9adc937ce Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 14:24:15 -0800 Subject: [PATCH 217/324] fix(web): PR description file links resolve in the PR's repository from a No-project thread (#41073) --- .../components/ChatMarkdown.browser.test.tsx | 33 +++++++++++++++++++ apps/web/src/components/ChatMarkdown.tsx | 18 +++++++++- 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/ChatMarkdown.browser.test.tsx b/apps/web/src/components/ChatMarkdown.browser.test.tsx index faca71b4a101f..b0aa293812d6d 100644 --- a/apps/web/src/components/ChatMarkdown.browser.test.tsx +++ b/apps/web/src/components/ChatMarkdown.browser.test.tsx @@ -90,6 +90,17 @@ vi.mock(import("../state/filesystem"), async (original) => { : actual.useFilesystemReadAccess(environmentId)) as never, }; }); +const threadWorktrees = vi.hoisted(() => new Map()); +vi.mock(import("../state/entities"), async (original) => { + const actual = await original(); + return { + ...actual, + readThreadShell: ((ref: { threadId: string }) => { + const worktreePath = threadWorktrees.get(ref.threadId); + return worktreePath === undefined ? actual.readThreadShell(ref as never) : { worktreePath }; + }) as never, + }; +}); vi.mock(import("../remoteOpen"), async (original) => ({ ...(await original()), useRemoteOpenResolution: () => ({ state: { mode: "local-exec" }, isResolved: true }) as never, @@ -170,6 +181,7 @@ function setup() { parsedSources.length = 0; settingsOverrides.mathRenderingEnabled = false; renderDiagram.mockReset(); + threadWorktrees.clear(); workspaceSearch.mockReset().mockResolvedValue(AsyncResult.success({ entries: [] })); filesystemMetadata.mockReset().mockResolvedValue(AsyncResult.success({ entries: [null] })); } @@ -559,6 +571,27 @@ describe("ChatMarkdown workspace file opens", () => { expect(workspaceSearch).toHaveBeenCalledOnce(); }); + it("opens a path from markdown rendered in another checkout under that checkout", async () => { + setup(); + const scratchThread = { ...threadRef, threadId: ThreadId.make("scratch-thread") }; + threadWorktrees.set(scratchThread.threadId, "/scratch/thread"); + filesystemMetadata.mockResolvedValue(AsyncResult.success({ entries: [{ kind: "file" }] })); + using openFile = vi.spyOn(useRightPanelStore.getState(), "openFile"); + await using screen = await renderText("[State](packages/state/filesystem.ts)", { + cwd: "/repo-a", + threadRef: scratchThread, + }); + await act(async () => screen.container.querySelector("a")!.click()); + + await vi.waitFor(() => + expect(openFile).toHaveBeenCalledExactlyOnceWith( + scratchThread, + "/repo-a/packages/state/filesystem.ts", + undefined, + ), + ); + }); + it.each([ ["its own panel", "thread-own-panel", false], ["its parent's panel from a side chat", "thread-side-chat", true], diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index 2edc4be1febcd..f5f69e063a967 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -942,8 +942,24 @@ function useChatMarkdownState( }; const openFileInPanel = (fileLinkMeta: MarkdownFileLinkMeta, panelPath: string) => { if (!threadRef) return; + // The panel reads relative paths from the thread's folder. A pull request body's `cwd` is the + // checkout of its repository, which can be another folder. + const shell = readThreadShell(threadRef); + const panelRoot = + shell?.worktreePath ?? + projects.find( + (project) => project.environmentId === environmentId && project.id === shell?.projectId, + )?.workspaceRoot; const openAt = (path: string) => - useRightPanelStore.getState().openFile(threadRef, path, fileLinkMeta.line); + useRightPanelStore + .getState() + .openFile( + threadRef, + cwd && panelRoot !== undefined && cwd !== panelRoot + ? resolveWorkspaceFilePath(path, cwd) + : path, + fileLinkMeta.line, + ); if ( fileLinkMeta.workspaceLookupPath === null || !cwd || From 44979a58756544d3d77324ee5eeb2fc1485b3aed Mon Sep 17 00:00:00 2001 From: SSH Date: Sun, 22 Nov 2026 17:38:52 -0500 Subject: [PATCH 218/324] fix(mcp): keep deleted schedules from returning on edit (#41084) Co-authored-by: Julius Marminge --- .../OrchestratorMcpService.schedules.test.ts | 91 +++++++++++++++++++ apps/server/src/mcp/OrchestratorMcpService.ts | 1 + packages/contracts/src/scheduledTask.ts | 3 +- 3 files changed, 94 insertions(+), 1 deletion(-) create mode 100644 apps/server/src/mcp/OrchestratorMcpService.schedules.test.ts diff --git a/apps/server/src/mcp/OrchestratorMcpService.schedules.test.ts b/apps/server/src/mcp/OrchestratorMcpService.schedules.test.ts new file mode 100644 index 0000000000000..a24d8e740d49d --- /dev/null +++ b/apps/server/src/mcp/OrchestratorMcpService.schedules.test.ts @@ -0,0 +1,91 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { expect, it } from "@effect/vitest"; +import { EnvironmentId, ProjectId, ProviderInstanceId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import * as ProviderAdapters from "../orchestration-v2/ProviderAdapterRegistry.ts"; +import * as Launch from "../orchestration-v2/ThreadLaunchService.ts"; +import * as Threads from "../orchestration-v2/ThreadManagementService.ts"; +import * as RemoteDelegation from "../peer/RemoteDelegation.ts"; +import * as Sqlite from "../persistence/Sqlite.ts"; +import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; +import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts"; +import * as Projects from "../project/ProjectService.ts"; +import * as Providers from "../provider/ProviderRegistry.ts"; +import * as Schedules from "../scheduledTasks/ScheduledTaskService.ts"; +import * as Scheduler from "../scheduling/Scheduler.ts"; +import * as Secrets from "../secrets/SecretRequests.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import * as Git from "../vcs/GitVcsDriver.ts"; +import type { McpInvocationScope } from "./McpInvocationContext.ts"; +import * as Mcp from "./OrchestratorMcpService.ts"; + +const dependencies = Layer.mergeAll( + NodeCrypto.layer, + NodeServices.layer, + Sqlite.layerMemory, + ServerSettings.layerTest(), + ManagedPolicy.layerTest(), + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ + namedProjectsRoot: "/projects", + isScratchProject: () => Effect.succeed(false), + }), + Layer.mock(Projects.ProjectService)({}), + Layer.mock(Providers.ProviderRegistry)({}), + Layer.mock(ProviderAdapters.ProviderAdapterRegistryV2)({}), + Layer.mock(Threads.ThreadManagementService)({}), + Layer.mock(Launch.ThreadLaunchService)({}), + Layer.mock(Git.GitVcsDriver)({}), + Layer.mock(Secrets.SecretRequests)({}), + Layer.mock(RemoteDelegation.RemoteDelegation)({}), + Layer.mock(Scheduler.Scheduler)({ register: () => Effect.void }), +); + +const client: McpInvocationScope = { + environmentId: EnvironmentId.make("schedule-test"), + requestNamespace: "client", + thread: undefined, + client: { sessionId: "client", label: "Test", access: "full-access" }, + capabilities: new Set(["orchestration"]), + issuedAt: 1, +}; + +const fixture = Effect.gen(function* () { + const schedules = yield* Schedules.ScheduledTaskService; + const { task } = yield* schedules.upsert({ + title: "Scheduled review", + prompt: "Review", + projectId: ProjectId.make("project"), + schedule: { type: "interval", everyMs: 60_000 }, + enabled: true, + workspaceStrategy: { type: "root" }, + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "test" }, + runtimeMode: "full-access", + interactionMode: "default", + }); + return { schedules, id: task.id }; +}); + +const layer = Schedules.layer.pipe(Layer.provideMerge(dependencies)); + +it.effect("an MCP edit cannot recreate a concurrently deleted schedule", () => + Effect.gen(function* () { + const { schedules, id } = yield* fixture; + const editing = { + ...schedules, + list: () => schedules.list().pipe(Effect.tap(() => schedules.delete({ id }))), + }; + const result = yield* Mcp.OrchestratorMcpService.pipe( + Effect.flatMap((mcp) => + mcp.updateScheduledTask(client, { scheduledTaskId: id, enabled: false }), + ), + Effect.provide(Mcp.layer), + Effect.provideService(Schedules.ScheduledTaskService, editing), + Effect.result, + ); + expect((yield* schedules.list()).tasks).toEqual([]); + expect(result._tag).toBe("Failure"); + }).pipe(Effect.provide(layer)), +); diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index f13623c232838..4278c6bcf95b6 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -2525,6 +2525,7 @@ const make = Effect.gen(function* () { : yield* scheduledTaskWorkspaceStrategy(threadId !== null, existing.projectId); const upsertInput: ScheduledTaskUpsertInput = { id: existing.id, + requireExisting: true, title: input.title ?? existing.title, prompt: input.prompt ?? existing.prompt, enabled: input.enabled ?? existing.enabled, diff --git a/packages/contracts/src/scheduledTask.ts b/packages/contracts/src/scheduledTask.ts index 33b24ed6dfa08..ba1f21c19c25a 100644 --- a/packages/contracts/src/scheduledTask.ts +++ b/packages/contracts/src/scheduledTask.ts @@ -279,7 +279,8 @@ export type ScheduledTaskListResult = typeof ScheduledTaskListResult.Type; export const ScheduledTaskUpsertInput = Schema.Struct({ id: Schema.optional(ScheduledTaskId), requireExisting: Schema.optional(Schema.Boolean).annotate({ - description: "Reject the save if the task no longer exists, for edits from a client form.", + description: + "Reject the save if the task no longer exists, for edits based on an earlier read.", }), commandId: Schema.optional(CommandId), title: TrimmedNonEmptyString, From a09738fb435120d08707db0142ca55b3b7b5c7ec Mon Sep 17 00:00:00 2001 From: SSH Date: Sun, 22 Nov 2026 17:46:37 -0500 Subject: [PATCH 219/324] fix(claude): start the updated Claude Code CLI when a thread changes model (#41086) Co-authored-by: Julius Marminge --- .../Adapters/ClaudeAdapterV2.test.ts | 143 ++++++++++++++++++ .../Adapters/ClaudeAdapterV2.ts | 48 +++++- .../provider/Drivers/ClaudeExecutable.test.ts | 52 ++++++- .../src/provider/Drivers/ClaudeExecutable.ts | 30 ++++ 4 files changed, 264 insertions(+), 9 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 139261b280535..62139c5a91fdc 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -8464,6 +8464,149 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + describe("a model change after a Claude Code update", () => { + /** An install as the Claude installer lays it out: one file per version and a link. */ + const makeInstall = Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "claude-program-" }); + const link = NodePath.join(root, "claude"); + const install = (version: string) => { + const file = NodePath.join(root, version); + NodeFS.writeFileSync(file, "#!/bin/sh\n", { mode: 0o755 }); + NodeFS.rmSync(link, { force: true }); + NodeFS.symlinkSync(file, link); + }; + install("1.0.0"); + return { + settings: { ...DEFAULT_CLAUDE_SETTINGS, binaryPath: link }, + update: () => install("1.0.1"), + }; + }); + const opus = { + instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, + model: "claude-opus-5-5", + } satisfies ModelSelection; + const sonnet = { ...opus, model: "claude-sonnet-4-6" } satisfies ModelSelection; + + it.effect("starts the new version, and only for the model change", () => + Effect.scoped( + Effect.gen(function* () { + const install = yield* makeInstall; + const harness = yield* makeWakeHarnessWithOptions({ + settings: install.settings, + close: (messages) => Queue.shutdown(messages), + freshQueueOnReopen: true, + }); + const now = yield* DateTime.now; + const turn = (ordinal: number, modelSelection: ModelSelection) => + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make(`attempt-updated-cli:${ordinal}`), + text: `Request ${ordinal}`, + attachments: [], + providerTurnOrdinal: ordinal, + modelSelection, + }); + const settle = Effect.gen(function* () { + yield* harness.offerAndWait(turnOneResult); + yield* Queue.take(harness.terminalReceipts); + }); + yield* harness.runtime.startTurn(turn(1, opus)); + yield* settle; + + // The update alone restarts nothing. + install.update(); + yield* harness.runtime.startTurn(turn(2, opus)); + yield* settle; + assert.lengthOf(harness.processQueues, 1); + + yield* harness.runtime.startTurn(turn(3, sonnet)); + assert.lengthOf(harness.processQueues, 2); + assert.equal(harness.getOpenedOptions()?.model, "claude-sonnet-4-6"); + assert.deepEqual(harness.liveSelectionChanges, []); + assert.lengthOf(harness.offeredMessages, 3); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ), + ); + + it.effect("keeps a process that runs background work until that work ends", () => + Effect.scoped( + Effect.gen(function* () { + const install = yield* makeInstall; + const harness = yield* makeWakeHarnessWithOptions({ + settings: install.settings, + close: (messages) => Queue.shutdown(messages), + freshQueueOnReopen: true, + }); + const now = yield* DateTime.now; + const turn = (ordinal: number, modelSelection: ModelSelection) => + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make(`attempt-updated-cli-background:${ordinal}`), + text: `Request ${ordinal}`, + attachments: [], + providerTurnOrdinal: ordinal, + modelSelection, + }); + const settle = Effect.gen(function* () { + yield* harness.offerAndWait(turnOneResult); + yield* Queue.take(harness.terminalReceipts); + }); + yield* harness.runtime.startTurn(turn(1, opus)); + const originalOptions = harness.getOpenedOptions(); + yield* harness.offerAndWait(wakeTaskStarted); + yield* settle; + assert.isTrue(yield* harness.hasPendingBackgroundWork); + + install.update(); + yield* harness.runtime.startTurn(turn(2, sonnet)); + yield* settle; + assert.deepEqual(harness.liveSelectionChanges[0], { model: "claude-sonnet-4-6" }); + assert.strictEqual(harness.getOpenedOptions(), originalOptions); + assert.lengthOf(harness.processQueues, 1); + + // The background shell ended: the next turn starts the new version. + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "system", + subtype: "background_tasks_changed", + tasks: [], + uuid: "00000000-0000-4000-8000-000000000520", + session_id: WAKE_NATIVE_SESSION, + }), + ); + assert.isFalse(yield* harness.hasPendingBackgroundWork); + yield* harness.runtime.startTurn(turn(3, sonnet)); + assert.lengthOf(harness.processQueues, 2); + assert.equal(harness.getOpenedOptions()?.model, "claude-sonnet-4-6"); + assert.lengthOf(harness.offeredMessages, 3); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ), + ); + }); + // regression: #17270 root text_delta frames stream the reply before the block's snapshot it.effect("streams Claude assistant text deltas before the completed snapshot", () => Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 196d82b3aa5c0..30243178fce41 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -167,7 +167,11 @@ import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import { resolveAttachmentPath } from "../../attachmentStore.ts"; import { snapshotMcpApp } from "../../mcpApps/McpAppSnapshot.ts"; -import { resolveClaudeSdkExecutablePath } from "../../provider/Drivers/ClaudeExecutable.ts"; +import { + claudeProgramReader, + claudeProgramWasReplaced, + resolveClaudeSdkExecutablePath, +} from "../../provider/Drivers/ClaudeExecutable.ts"; import * as ProviderInstallationGate from "../../provider/ProviderInstallationGate.ts"; import { planClaudeSkillDispatch, @@ -5322,6 +5326,8 @@ interface ClaudeLiveQueryContext { readonly query: ClaudeAgentSdkQuerySession; readonly queryPolicyKey: string; selection: CompiledClaudeModelSelection; + readonly program: string | undefined; + readonly startedWithApiModelId: string; readonly closed: Deferred.Deferred; lastTurn: ActiveClaudeTurnContext | null; // "early" echoes on the first frame; "acknowledged" confirms uuid acceptance, but resume turns can still precede the prompt. @@ -6032,6 +6038,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( model: input.modelSelection.model, now, }); + const readProgram = yield* claudeProgramReader( + adapterOptions.settings.binaryPath, + adapterOptions.environment, + ); const events = yield* Queue.unbounded(); const activeTurn = yield* Ref.make(null); const taskOutputTails = new Map< @@ -13205,7 +13215,19 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( launchArgSettings, ); let compiledSelection = compileClaudeModelSelection(turnInput.modelSelection, catalog); + // Once an update replaces the running CLI, a model other than the one + // it started with moves to the new CLI unless background work is active. + const startsUpdatedProgram = + !turnInput.resume && + existing !== null && + existing.nativeThreadId === nativeThreadId && + existing.queryPolicyKey === queryPolicyKey && + !existing.stopping && + existing.startedWithApiModelId !== compiledSelection.apiModelId && + claudeProgramWasReplaced(existing.program, yield* readProgram) && + !(yield* liveProcessRunsBackgroundWork(existing)); if ( + !startsUpdatedProgram && !turnInput.resume && existing !== null && existing.nativeThreadId === nativeThreadId && @@ -13219,6 +13241,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( yield* applySelectionLive(existing, compiledSelection); } if ( + !startsUpdatedProgram && !turnInput.resume && existing !== null && existing.nativeThreadId === nativeThreadId && @@ -13352,14 +13375,21 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const resolvedTurnCwd = yield* fileSystem .realPath(turnInput.runtimePolicy.cwd ?? ".") .pipe(Effect.orElseSucceed(() => turnInput.runtimePolicy.cwd)); - const openQueryRuntime = queryRunner.open({ - threadId: turnInput.threadId, - providerSessionId: input.providerSessionId, - options: queryOptions, - ...(turnInput.resume ? { resume: true } : {}), - }); + // Read right before opening so an update during startup counts too. + const openQueryRuntime = readProgram.pipe( + Effect.flatMap((program) => + queryRunner + .open({ + threadId: turnInput.threadId, + providerSessionId: input.providerSessionId, + options: queryOptions, + ...(turnInput.resume ? { resume: true } : {}), + }) + .pipe(Effect.map((querySession) => ({ program, querySession }))), + ), + ); // The SDK spawns the CLI per turn, so only the open waits for a provider update. - const querySession = yield* ( + const { program, querySession } = yield* ( adapterOptions.installationGate === undefined ? openQueryRuntime : adapterOptions.installationGate.execute(adapterOptions.instanceId, openQueryRuntime) @@ -13401,6 +13431,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( query: querySession, queryPolicyKey, selection: compiledSelection, + program, + startedWithApiModelId: compiledSelection.apiModelId, closed, lastTurn: null, promptEchoMode: "unknown", diff --git a/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts b/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts index 36d7e3f3313fc..205f4610759da 100644 --- a/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts +++ b/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts @@ -1,9 +1,20 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeFS from "node:fs"; +import * as NodePath from "node:path"; + +import * as NodeServices from "@effect/platform-node/NodeServices"; import { describe, expect, it } from "@effect/vitest"; +import * as FileSystem from "effect/FileSystem"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { SpawnExecutableResolution } from "@t3tools/shared/shell"; import * as Effect from "effect/Effect"; -import { ClaudeExecutableFileCheck, resolveClaudeSdkExecutablePath } from "./ClaudeExecutable.ts"; +import { + ClaudeExecutableFileCheck, + claudeProgramReader, + claudeProgramWasReplaced, + resolveClaudeSdkExecutablePath, +} from "./ClaudeExecutable.ts"; const NPM_DIR = "C:\\Users\\dev\\AppData\\Roaming\\npm"; const NPM_SHIM = `${NPM_DIR}\\claude.cmd`; @@ -101,3 +112,42 @@ describe("resolveClaudeSdkExecutablePath", () => { }), ); }); + +describe("claudeProgramReader", () => { + /** An install as the Claude installer lays it out: one file per version and a link. */ + const makeInstall = Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "claude-program-" }); + const bin = NodePath.join(root, "bin"); + const link = NodePath.join(bin, "claude"); + const version = (name: string) => { + const file = NodePath.join(root, "versions", name); + NodeFS.mkdirSync(NodePath.dirname(file), { recursive: true }); + NodeFS.writeFileSync(file, "#!/bin/sh\n", { mode: 0o755 }); + return file; + }; + NodeFS.mkdirSync(bin); + NodeFS.symlinkSync(version("1.0.0"), link); + return { + bin, + update: () => { + NodeFS.unlinkSync(link); + NodeFS.symlinkSync(version("1.0.1"), link); + }, + }; + }); + + it.effect("follows a bare command name through PATH", () => + Effect.scoped( + Effect.gen(function* () { + const { bin, update } = yield* makeInstall; + const readProgram = yield* claudeProgramReader("claude", { PATH: bin }); + const startedFrom = yield* readProgram; + expect(startedFrom).toBeDefined(); + expect(claudeProgramWasReplaced(startedFrom, yield* readProgram)).toBe(false); + update(); + expect(claudeProgramWasReplaced(startedFrom, yield* readProgram)).toBe(true); + }), + ).pipe(Effect.provide(NodeServices.layer)), + ); +}); diff --git a/apps/server/src/provider/Drivers/ClaudeExecutable.ts b/apps/server/src/provider/Drivers/ClaudeExecutable.ts index 6f4e85812f0cc..3de63c9372f4e 100644 --- a/apps/server/src/provider/Drivers/ClaudeExecutable.ts +++ b/apps/server/src/provider/Drivers/ClaudeExecutable.ts @@ -73,3 +73,33 @@ export const resolveClaudeSdkExecutablePath = Effect.fn("resolveClaudeSdkExecuta return binaryPath; }, ); + +/** + * Returns an effect reading the real path of the installed Claude binary. + * Updates repoint the installed link to a new version file, so comparing this + * detects when a live CLI process was started from an older version. + */ +export const claudeProgramReader = Effect.fn("claudeProgramReader")(function* ( + binaryPath: string, + environment: NodeJS.ProcessEnv, +): Effect.fn.Return> { + const platform = yield* HostProcess.Platform; + const resolveExecutable = yield* SpawnExecutableResolution; + return Effect.promise(async () => { + try { + const resolved = await resolveExecutable(binaryPath, platform, environment); + return resolved === undefined ? undefined : await NodeFS.promises.realpath(resolved); + } catch { + return undefined; + } + }); +}); + +/** + * Reports whether an update replaced the program a live CLI process started + * from. An unreadable path on either side reports no update. + */ +export const claudeProgramWasReplaced = ( + startedFrom: string | undefined, + now: string | undefined, +): boolean => startedFrom !== undefined && now !== undefined && startedFrom !== now; From fb4558d77d0437a056bdd1604a48b47b3f5db069 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 15:04:00 -0800 Subject: [PATCH 220/324] fix(web,mobile,server): large files load in full without freezing the file preview (#40631) --- .../features/files/FileMarkdownPreview.tsx | 119 ++++--- .../features/files/ThreadFilesRouteScreen.tsx | 74 +++-- .../src/features/files/useFullFileText.ts | 66 ++++ apps/server/src/assets/AssetAccess.test.ts | 33 +- apps/server/src/assets/AssetAccess.ts | 6 +- .../AttachmentFilePreview.browser.test.tsx | 6 + .../src/components/files/ChunkedMarkdown.tsx | 106 +++++++ .../components/files/FileMarkdownPreview.tsx | 3 +- .../files/FilePreviewPanel.browser.test.tsx | 25 +- .../src/components/files/FilePreviewPanel.tsx | 297 +++++++++++------- .../src/components/files/LargeFilePreview.tsx | 125 ++++++++ .../src/components/files/LargeTextViewer.tsx | 116 ++++--- .../files/ReadOnlySourcePreview.tsx | 8 +- .../src/components/files/fullFileText.test.ts | 36 +++ apps/web/src/components/files/fullFileText.ts | 90 ++++++ .../src/components/files/largeTextProtocol.ts | 6 + apps/web/src/i18n/translations/de.json | 4 +- apps/web/src/i18n/translations/en.json | 4 +- apps/web/src/i18n/translations/es.json | 4 +- apps/web/src/i18n/translations/fr.json | 4 +- apps/web/src/i18n/translations/ja.json | 4 +- apps/web/src/i18n/translations/ko.json | 4 +- apps/web/src/i18n/translations/pt-BR.json | 4 +- apps/web/src/i18n/translations/ru.json | 4 +- apps/web/src/i18n/translations/sv.json | 4 +- apps/web/src/i18n/translations/zh.json | 4 +- packages/contracts/src/assets.ts | 1 + packages/shared/package.json | 4 + packages/shared/src/markdownChunks.test.ts | 132 ++++++++ packages/shared/src/markdownChunks.ts | 130 ++++++++ 30 files changed, 1152 insertions(+), 271 deletions(-) create mode 100644 apps/mobile/src/features/files/useFullFileText.ts create mode 100644 apps/web/src/components/files/ChunkedMarkdown.tsx create mode 100644 apps/web/src/components/files/LargeFilePreview.tsx create mode 100644 apps/web/src/components/files/fullFileText.test.ts create mode 100644 apps/web/src/components/files/fullFileText.ts create mode 100644 packages/shared/src/markdownChunks.test.ts create mode 100644 packages/shared/src/markdownChunks.ts diff --git a/apps/mobile/src/features/files/FileMarkdownPreview.tsx b/apps/mobile/src/features/files/FileMarkdownPreview.tsx index 086fb2abec598..23035511a5c2d 100644 --- a/apps/mobile/src/features/files/FileMarkdownPreview.tsx +++ b/apps/mobile/src/features/files/FileMarkdownPreview.tsx @@ -6,7 +6,14 @@ import { maskMarkdownFrontmatter } from "@t3tools/shared/markdownFrontmatter"; import { useGT } from "gt-react-native"; import { useState } from "react"; import { StackActions, useNavigation } from "@react-navigation/native"; -import { ScrollView, View } from "react-native"; +import { View } from "react-native"; +import { LegendList } from "@legendapp/list/react-native"; +import { + LARGE_MARKDOWN_CHUNK_MAX_CHARS, + splitMarkdown, + withMarkdownDefinitions, +} from "@t3tools/shared/markdownChunks"; +import { NativeScrollView } from "../../native/NativeScrollViewMarker"; import { RefreshControl } from "../../components/ui/RefreshControl"; import { tryOpenExternalUrl } from "../../lib/openExternalUrl"; @@ -35,6 +42,7 @@ import { type NativeMarkdownTextStyle, } from "../../native/SelectableMarkdownText"; import { fileRoutePathSegments, resolveWorkspaceFilePath } from "./filePath"; +import { SourceFileSurface } from "./SourceFileSurface"; interface MarkdownPreviewStyles { readonly nativeTextStyle: NativeMarkdownTextStyle; @@ -223,44 +231,77 @@ export function FileMarkdownPreview(props: { if (!openMedia(href)) void tryOpenExternalUrl(href, "markdown-link"); }; - return ( - void handlePullToRefresh()} - /> - ) : undefined + const refreshControl = props.onRefresh ? ( + void handlePullToRefresh()} /> + ) : undefined; + const renderMarkdown = (markdown: string) => ( + + markdownFileEmbedLabel( + href, + { + environmentId: props.environmentId, + threadId: props.threadId ?? undefined, + workspaceRoot: markdownDirectory, + captured: props.captured, + }, + false, + ) } - > - - - markdownFileEmbedLabel( - href, - { - environmentId: props.environmentId, - threadId: props.threadId ?? undefined, - workspaceRoot: markdownDirectory, - captured: props.captured, - }, - false, - ) - } - onLinkPress={onLinkPress} - renderImage={renderImage} - resolveImageSource={resolveImageSource} - onImagePress={onImagePress} - textStyle={styles.nativeTextStyle} - /> - setExpandedFile(null)} /> - setExpandedVideo(null)} /> - - + onLinkPress={onLinkPress} + renderImage={renderImage} + resolveImageSource={resolveImageSource} + onImagePress={onImagePress} + textStyle={styles.nativeTextStyle} + /> + ); + const modals = ( + <> + setExpandedFile(null)} /> + setExpandedVideo(null)} /> + + ); + const markdown = maskMarkdownFrontmatter(props.markdown); + + // Only chunks near the viewport mount, so only they pay for the JS rewrites and native parse. + const { chunks, definitions } = splitMarkdown(markdown); + if (chunks.some((chunk) => chunk.text.length > LARGE_MARKDOWN_CHUNK_MAX_CHARS)) { + return ( + + ); + } + return ( + + String(index)} + estimatedItemSize={ + (styles.nativeTextStyle.lineHeight * + chunks.reduce((lines, chunk) => lines + chunk.lines, 0)) / + chunks.length + } + recycleItems={false} + contentContainerStyle={{ paddingHorizontal: 18, paddingVertical: 18 }} + ItemSeparatorComponent={ChunkSeparator} + renderItem={({ item }) => ( + + {renderMarkdown(withMarkdownDefinitions(item.text, definitions))} + + )} + /> + {modals} + ); } + +function ChunkSeparator() { + return ; +} diff --git a/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx b/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx index 17d7f3e8d17ca..7661a4b547cb8 100644 --- a/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx +++ b/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx @@ -74,6 +74,7 @@ import { needsWorkspaceFileContents, } from "./filePath"; import { useWorkspaceFileAssetUrlState } from "./workspaceFileAssetUrl"; +import { MOBILE_FULL_FILE_MAX_BYTES, useFullFileText } from "./useFullFileText"; function FilesBrowserHeader(props: { readonly projectName: string; @@ -253,6 +254,7 @@ function FileContent(props: { readonly threadId: ThreadId | null; readonly initialLine: number | null; readonly truncated: boolean; + /** Renders Markdown in lazily parsed chunks; set for files past the 1 MB preview. */ readonly selectable: boolean; readonly onRefresh?: () => Promise | void; }) { @@ -703,6 +705,38 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) { : defaultViewMode(relativePath); const resolvedActiveMode = isVideoFile || isAudioFile ? "preview" : canPreview ? activeMode : "source"; + // Metadata is needed only to distinguish directories; file contents can load concurrently. + const needsFileContents = needsWorkspaceFileContents({ + relativePath, + metadataKind: metadata.data?.kind, + activeMode: resolvedActiveMode, + }); + const fileQuery = useEnvironmentQuery( + canReadFiles && + environmentId !== null && + cwd !== null && + relativePath !== null && + needsFileContents + ? projectEnvironment.readFile({ + environmentId, + input: { cwd, relativePath }, + }) + : null, + ); + const fileData = fileQuery.data as ProjectReadFileResult | null; + const [fileRefreshCount, setFileRefreshCount] = useState(0); + const fullText = useFullFileText({ + environmentId, + threadId, + absolutePath: + fileData?.truncated === true && fileData.byteLength <= MOBILE_FULL_FILE_MAX_BYTES + ? targetPath + : null, + revision: `${fileData?.byteLength ?? 0}:${fileRefreshCount}`, + }); + // Until the full text arrives, the 1 MB preview shows with its partial-file notice. + const fileContents = fullText ?? fileData?.contents ?? null; + const fileTruncated = fileData?.truncated === true && fullText === null; const assetPreviewPath = !metadataPending && directoryPath === null && @@ -758,28 +792,13 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) { const handleRetryPreview = () => { void assetPreview.refresh().finally(() => setPreviewRevision((current) => current + 1)); }; - // Metadata is needed only to distinguish directories; file contents can load concurrently. - const needsFileContents = needsWorkspaceFileContents({ - relativePath, - metadataKind: metadata.data?.kind, - activeMode: resolvedActiveMode, - }); - const fileQuery = useEnvironmentQuery( - canReadFiles && - environmentId !== null && - cwd !== null && - relativePath !== null && - needsFileContents - ? projectEnvironment.readFile({ - environmentId, - input: { cwd, relativePath }, - }) - : null, - ); - const fileData = fileQuery.data as ProjectReadFileResult | null; // iOS only: Android lays out a whole-file selectable TextView on the UI thread, which stalls. const canSelectText = - Platform.OS === "ios" && resolvedActiveMode === "source" && fileData?.contents != null; + Platform.OS === "ios" && + resolvedActiveMode === "source" && + fileContents !== null && + // One selectable view lays out the whole text; past the 1 MB preview that stalls. + fileContents.length <= 1024 * 1024; const selectingText = canSelectText && textSelectionPath === relativePath; const handleSelectFile = (path: string) => { @@ -906,13 +925,13 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) { ), } as const, ]), - fileData?.contents != null + fileContents !== null ? ({ id: "copy-contents", - title: fileData.truncated ? gt("Copy preview") : gt("Copy contents"), + title: fileTruncated ? gt("Copy preview") : gt("Copy contents"), icon: "doc.on.doc", inline: false, - onPress: () => copyTextWithHaptic(fileData.contents), + onPress: () => copyTextWithHaptic(fileContents), } as const) : null, isPdfFile({ name: relativePath }) && previewUri !== null @@ -1083,14 +1102,17 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) { videoSource={videoSource} mediaSource={mediaSource} resolveVideoUri={assetPreview.refresh} - fileContents={fileData?.contents ?? null} + fileContents={fileContents} fileError={fileQuery.error} initialLine={targetLine} relativePath={relativePath} threadId={threadId} - truncated={fileData?.truncated ?? false} + truncated={fileTruncated} selectable={selectingText} - onRefresh={() => fileQuery.refresh()} + onRefresh={() => { + setFileRefreshCount((count) => count + 1); + return fileQuery.refresh(); + }} /> { + const [uri] = JSON.parse(key) as [string, string]; + return connectionAtomRuntime + .atom( + HttpClient.get(uri).pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.flatMap((response) => { + // The file can grow after the preview read; never buffer past the cap. React Native's + // fetch buffers the whole body, so a response without a length is refused, not trusted. + const length = Number(response.headers["content-length"] ?? Number.NaN); + return Number.isFinite(length) && length <= MOBILE_FULL_FILE_MAX_BYTES + ? response.text + : Effect.succeed(null); + }), + Effect.provideService(FetchHttpClient.RequestInit, { cache: "no-store" }), + ), + ) + .pipe(Atom.withLabel(`full-file-text:${key}`)); +}); + +const noFullFileTextAtom = Atom.make(AsyncResult.success(null)); + +/** + * Downloads a thread file's full text past the 1 MB RPC preview; null while loading, after a + * failure, or when disabled. A new `revision` downloads it again. + */ +export function useFullFileText(input: { + readonly environmentId: EnvironmentId | null; + readonly threadId: ThreadId | null; + readonly absolutePath: string | null; + readonly revision: string; +}): string | null { + const { threadId, absolutePath } = input; + // Workspace-file URLs serve only previewable types; an attachment download serves any file. + const resource = useMemo( + () => + threadId === null || absolutePath === null + ? null + : { _tag: "media-file", threadId, path: absolutePath, disposition: "attachment" }, + [threadId, absolutePath], + ); + const assetUrl = useAssetUrlState(input.environmentId, resource, input.revision); + const uri = resource !== null && assetUrl._tag === "Success" ? assetUrl.url : null; + const result = useAtomValue( + uri === null ? noFullFileTextAtom : fullFileTextAtom(JSON.stringify([uri, input.revision])), + ); + // The caller keeps showing the 1 MB preview and its partial-file notice. + return AsyncResult.isSuccess(result) ? result.value : null; +} diff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.ts index 990306faae438..64831512a9ef7 100644 --- a/apps/server/src/assets/AssetAccess.test.ts +++ b/apps/server/src/assets/AssetAccess.test.ts @@ -307,15 +307,28 @@ describe("AssetAccess", () => { "archive.zip", "no-extension", ]) { - for (const directory of [root, outside]) { + for (const [directory, draft] of [ + [root, false], + [outside, false], + [root, true], + [outside, true], + ] as const) { const filePath = path.join(directory, name); yield* fs.writeFileString(filePath, "shared file bytes"); - const resource = { - _tag: "media-file" as const, - threadId: ThreadId.make("thread-1"), - path: directory === root ? name : filePath, - disposition: "attachment" as const, - }; + const requested = directory === root ? name : filePath; + const resource = draft + ? { + _tag: "draft-workspace-file" as const, + cwd: root, + path: requested, + disposition: "attachment" as const, + } + : { + _tag: "media-file" as const, + threadId: ThreadId.make("thread-1"), + path: requested, + disposition: "attachment" as const, + }; const result = yield* issueAssetUrl({ resource, workspaceRoot: root }); const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length); const separator = suffix.indexOf("/"); @@ -799,6 +812,12 @@ describe("AssetAccess", () => { }, { _tag: "media-file", threadId, path: config.dbPath }, { _tag: "draft-workspace-file", cwd: config.stateDir, path: "statev2.sqlite" }, + { + _tag: "draft-workspace-file", + cwd: config.stateDir, + path: "statev2.sqlite", + disposition: "attachment", + }, ] as const) { const error = yield* issueAssetUrl({ resource }).pipe(Effect.flip); expect(error._tag).toBe("AssetWorkspaceAssetNotFoundError"); diff --git a/apps/server/src/assets/AssetAccess.ts b/apps/server/src/assets/AssetAccess.ts index 005ce9ebd3f5f..2b8f1029ae3a3 100644 --- a/apps/server/src/assets/AssetAccess.ts +++ b/apps/server/src/assets/AssetAccess.ts @@ -442,7 +442,8 @@ const finalizeAbsoluteMediaFileAsset = Effect.fn("AssetAccess.finalizeAbsoluteMe }); } const download = - input.resource._tag === "media-file" && input.resource.disposition === "attachment"; + (input.resource._tag === "media-file" || input.resource._tag === "draft-workspace-file") && + input.resource.disposition === "attachment"; if (!download && hostPreviewMimeTypeFromExtension(path.extname(canonicalFile)) === null) { return yield* new AssetPreviewTypeValidationError({ resource: input.resource }); } @@ -515,7 +516,8 @@ const finalizeWorkspaceFileAsset = Effect.fn("AssetAccess.finalizeWorkspaceFileA ); const isDraftMedia = input.resource._tag === "draft-workspace-file" && - (isWorkspaceAudioPreviewPath(resolved.relativePath) || + (input.resource.disposition === "attachment" || + isWorkspaceAudioPreviewPath(resolved.relativePath) || isWorkspaceVideoPreviewPath(resolved.relativePath)); if (!isDraftMedia && !isWorkspacePreviewEntryPath(resolved.relativePath)) { return yield* new AssetPreviewTypeValidationError({ diff --git a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx index 70eb4a3490b60..e96b165d5db0e 100644 --- a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx +++ b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx @@ -582,8 +582,14 @@ describe("large text preview recovery", () => { environmentId={EnvironmentId.make("test")} threadRef={{ environmentId: EnvironmentId.make("test"), threadId: ThreadId.make("test") }} absolutePath="/repo/large.txt" + draftCwd={null} name="large.txt" delimiter={null} + markdownCwd={null} + copyContents={{ current: null }} + preview="" + // Past the highlighted-source cap, so the worker-backed viewer under test renders. + sizeBytes={128 * 1024 * 1024} workspaceMutationId={mutation} revealLine={null} revealRequestId={0} diff --git a/apps/web/src/components/files/ChunkedMarkdown.tsx b/apps/web/src/components/files/ChunkedMarkdown.tsx new file mode 100644 index 0000000000000..2564e40389c96 --- /dev/null +++ b/apps/web/src/components/files/ChunkedMarkdown.tsx @@ -0,0 +1,106 @@ +import type { ScopedThreadRef } from "@t3tools/contracts"; +import { LegendList } from "@legendapp/list/react"; +import type { KeyboardEventHandler } from "react"; + +import { Spinner } from "~/components/ui/spinner"; +import { FileMarkdownPreview } from "./FileMarkdownPreview"; +import { + LARGE_MARKDOWN_CHUNK_MAX_CHARS, + type MarkdownChunk, + withMarkdownDefinitions, +} from "@t3tools/shared/markdownChunks"; + +const ESTIMATED_LINE_PX = 24; + +interface ChunkItem { + readonly index: number; + readonly start: number; + readonly chunk: MarkdownChunk; +} + +/** Renders Markdown pieces in a virtualized list; task offsets are file offsets. */ +export function ChunkedMarkdown(props: { + readonly chunks: readonly MarkdownChunk[]; + /** Link definitions from the whole file, so references resolve across pieces. */ + readonly definitions: string; + /** Shows a spinner after the last chunk while more of the file streams in. */ + readonly loading?: boolean; + readonly cwd: string; + readonly relativePath: string; + readonly threadRef: ScopedThreadRef; + readonly workspaceMutationId: string | null; + readonly onKeyDown?: KeyboardEventHandler; + readonly onTaskListChange?: + | ((input: { readonly markerOffset: number; readonly checked: boolean }) => void) + | undefined; +}) { + const { chunks, onTaskListChange } = props; + const items: ChunkItem[] = []; + let start = 0; + let lines = 0; + for (const [index, chunk] of chunks.entries()) { + items.push({ index, start, chunk }); + lines += chunk.lines; + start += chunk.text.length + 1; + } + return ( +
    { + // Select All only reaches rendered pieces; copying all of it copies the whole file. + const list = event.currentTarget.firstElementChild; + if (!list || !window.getSelection()?.containsNode(list)) return; + event.preventDefault(); + event.clipboardData.setData("text/plain", chunks.map((chunk) => chunk.text).join("\n")); + }} + > + + data={items} + extraData={props.definitions} + keyExtractor={(item) => String(item.index)} + estimatedItemSize={(lines / Math.max(items.length, 1)) * ESTIMATED_LINE_PX} + drawDistance={800} + recycleItems={false} + className="h-full scrollbar-gutter-both" + contentContainerClassName="py-5" + ListFooterComponent={ + props.loading ? ( +
    + +
    + ) : null + } + renderItem={({ item }) => ( +
    + {item.chunk.text.length > LARGE_MARKDOWN_CHUNK_MAX_CHARS ? ( + // One block this long (a huge fence or HTML block) is too slow to parse. +
    +                {item.chunk.text}
    +              
    + ) : ( + + onTaskListChange({ + markerOffset: item.start + input.markerOffset, + checked: input.checked, + })) + } + /> + )} +
    + )} + /> +
    + ); +} diff --git a/apps/web/src/components/files/FileMarkdownPreview.tsx b/apps/web/src/components/files/FileMarkdownPreview.tsx index 19df3f6687058..a4b4957201792 100644 --- a/apps/web/src/components/files/FileMarkdownPreview.tsx +++ b/apps/web/src/components/files/FileMarkdownPreview.tsx @@ -10,6 +10,7 @@ export function FileMarkdownPreview(props: { readonly text: string; readonly threadRef: ScopedThreadRef; readonly workspaceMutationId: string | null; + readonly className?: string; readonly onTaskListChange?: | ((input: { readonly markerOffset: number; readonly checked: boolean }) => void) | undefined; @@ -30,7 +31,7 @@ export function FileMarkdownPreview(props: { imageBaseDir={imageBaseDir} threadRef={props.threadRef} workspaceMutationId={props.workspaceMutationId} - className="mx-auto max-w-4xl px-6 py-5" + className={props.className ?? "mx-auto max-w-4xl px-6 py-5"} onTaskListChange={props.onTaskListChange} /> ); diff --git a/apps/web/src/components/files/FilePreviewPanel.browser.test.tsx b/apps/web/src/components/files/FilePreviewPanel.browser.test.tsx index 714e45bac76fb..07e05010baab3 100644 --- a/apps/web/src/components/files/FilePreviewPanel.browser.test.tsx +++ b/apps/web/src/components/files/FilePreviewPanel.browser.test.tsx @@ -562,17 +562,28 @@ describe("source file scroll", () => { }); describe("rendered Markdown task saves", () => { - it("keeps a truncated read read-only without queuing a replacement", async () => { + it("renders the whole file of a truncated read, read-only", async () => { using _settings = setup(); + state.assetUrl = { + _tag: "Success", + url: "/assets/tasks.md", + expiresAt: Number.MAX_SAFE_INTEGER, + }; + const realFetch = globalThis.fetch; + using _fetch = vi + .spyOn(globalThis, "fetch") + .mockImplementation((input, init) => + new URL(String(input), location.href).pathname === "/assets/tasks.md" + ? Promise.resolve( + new Response("- [ ] Keep the rest of this file\n\nPast the first megabyte\n"), + ) + : realFetch(input, init), + ); await using screen = await render(markdownPreview(true)); - using _timers = fakeTimers(); + await expect.element(screen.getByText("Past the first megabyte")).toBeVisible(); const checkbox = screen.container.querySelector('input[type="checkbox"]')!; - expect(checkbox).not.toBeNull(); expect(checkbox.disabled).toBe(true); - expect(checkbox.readOnly).toBe(true); await act(async () => checkbox.click()); - await vi.advanceTimersByTimeAsync(500); - expect(checkbox.checked).toBe(false); expect(state.optimistic).toBeNull(); expect(state.writeFile).not.toHaveBeenCalled(); }); @@ -580,6 +591,8 @@ describe("rendered Markdown task saves", () => { it("still toggles and saves tasks from a complete read", async () => { using _settings = setup(); await using screen = await render(markdownPreview(false)); + // The virtualized list mounts its pieces after measuring the viewport. + await expect.element(screen.getByRole("checkbox")).toBeInTheDocument(); using _timers = fakeTimers(); const checkbox = screen.container.querySelector('input[type="checkbox"]')!; expect(checkbox).not.toBeNull(); diff --git a/apps/web/src/components/files/FilePreviewPanel.tsx b/apps/web/src/components/files/FilePreviewPanel.tsx index 2c27cfb8d80d1..dbb7f6ec0a33a 100644 --- a/apps/web/src/components/files/FilePreviewPanel.tsx +++ b/apps/web/src/components/files/FilePreviewPanel.tsx @@ -58,7 +58,9 @@ import { useEffectEvent, useRef, useState, + type ComponentProps, type KeyboardEvent as ReactKeyboardEvent, + type RefObject, } from "react"; import { isBrowserPreviewFile, openFileInPreview } from "~/browser/openFileInPreview"; @@ -101,7 +103,8 @@ import FileBrowserPanel from "./FileBrowserPanel"; import { FileExplorerPane } from "./FileExplorerPane"; import { FileBreadcrumbs } from "./FileBreadcrumbs"; import { breadcrumbPathOf, retainedBreadcrumbTrail, trailChildOf } from "./filePath"; -import { FileMarkdownPreview } from "./FileMarkdownPreview"; +import { ChunkedMarkdown } from "./ChunkedMarkdown"; +import { splitMarkdown } from "@t3tools/shared/markdownChunks"; import { type FileCommentAnnotationEntry, type FileCommentAnnotationGroup, @@ -122,6 +125,8 @@ import { FileSurfaceLoading, } from "./fileSurfaceChrome"; import SourceFilePreview from "./ReadOnlySourcePreview"; +import LargeFilePreview from "./LargeFilePreview"; +import { FULL_TEXT_MAX_BYTES } from "./largeTextProtocol"; import { resolveCenteredFileLineScrollTop } from "./fileLineReveal"; import { DiffCommentAnnotation } from "../diffs/DiffCommentAnnotation"; import { projectFileCacheKey } from "./fileContentRevision"; @@ -1218,30 +1223,27 @@ function RenderedMarkdownSurface({ }) { const saveTarget = { environmentId, cwd, relativePath }; useFileSaveSession(saveTarget, onPendingChange); + const onTaskListChange = readOnly + ? undefined + : ({ markerOffset, checked }: { readonly markerOffset: number; readonly checked: boolean }) => { + const currentContents = + getOptimisticProjectFileQueryData(environmentId, cwd, relativePath)?.contents ?? contents; + const nextContents = setMarkdownTaskChecked(currentContents, markerOffset, checked); + if (nextContents === currentContents) return; + setProjectFileQueryData(environmentId, cwd, relativePath, nextContents); + changeFileSaveSession(saveTarget, nextContents); + }; return ( - - { - const currentContents = - getOptimisticProjectFileQueryData(environmentId, cwd, relativePath)?.contents ?? - contents; - const nextContents = setMarkdownTaskChecked(currentContents, markerOffset, checked); - if (nextContents === currentContents) return; - setProjectFileQueryData(environmentId, cwd, relativePath, nextContents); - changeFileSaveSession(saveTarget, nextContents); - } - } - /> - + ); } @@ -1394,7 +1396,8 @@ export default function FilePreviewPanel({ const revealHandled = revealLine === null || (handledReveal?.path === relativePath && handledReveal.requestId === revealRequestId); - const renderMarkdown = isMarkdown && renderMarkdownPreferred && revealHandled; + const markdownRenderable = isMarkdown && (file.data?.byteLength ?? 0) <= FULL_TEXT_MAX_BYTES; + const renderMarkdown = markdownRenderable && renderMarkdownPreferred && revealHandled; const renderMermaid = isMermaid && renderMermaidPreferred && revealHandled; const renderBrowserFile = isPdf || (isHtml && renderBrowserFilePreferred && revealHandled); const renderTable = tableDelimiter !== null && renderTablePreferred && revealHandled; @@ -1408,7 +1411,10 @@ export default function FilePreviewPanel({ ? ("html" as const) : null; const canToggleRendered = - previewPath !== null && attachment === undefined && renderedMode !== null; + previewPath !== null && + attachment === undefined && + renderedMode !== null && + (!isMarkdown || markdownRenderable); const showsRawText = previewPath !== null && file.data !== null && @@ -1439,6 +1445,15 @@ export default function FilePreviewPanel({ file.data.contents.length > 0 ? file.data.contents : null; + const showsLargeText = + previewPath !== null && + attachment === undefined && + !isMedia && + !renderBrowserFile && + !isDocument && + !renderMermaid && + file.data?.truncated === true; + const copyLargeText = useRef<(() => Promise) | null>(null); const { copyToClipboard, isCopied } = useCopyToClipboard({ target: namedClipboardTarget(previewPath ?? ""), onError: (error) => @@ -1680,6 +1695,16 @@ export default function FilePreviewPanel({ {isCopied ? : } ) : null} + {showsLargeText && absolutePath && relativePath ? ( + + ) : null} {canOpenInBrowser ? ( {gt( "{count, plural, one {Preview limited to the first 1 MB of a {formatted} byte file.} other {Preview limited to the first 1 MB of a {formatted} byte file.}}", @@ -1789,21 +1814,20 @@ export default function FilePreviewPanel({ title={relativePath} workspaceMutationId={workspaceMutationId} /> - ) : relativePath && - absolutePath && - file.data?.truncated && - !isDocument && - !draft && - !isMarkdown && - !isMermaid && - !isHtml ? ( + ) : relativePath && absolutePath && showsLargeText ? ( import("./LargeTextViewer")); +// A draft has no thread yet, so its download is scoped to the draft's workspace instead. +function largeFileResource( + threadRef: ScopedThreadRef, + absolutePath: string, + draftCwd: string | null, +): AssetResource { + return draftCwd === null + ? { + _tag: "media-file", + threadId: threadRef.threadId, + path: absolutePath, + disposition: "attachment", + } + : { + _tag: "draft-workspace-file", + cwd: draftCwd, + path: absolutePath, + disposition: "attachment", + }; +} + +/** Copy and save for a file past the 1 MB preview, which the panel holds only in its viewer. */ +function LargeFileActions(props: { + environmentId: EnvironmentId; + threadRef: ScopedThreadRef; + absolutePath: string; + draftCwd: string | null; + name: string; + copyContents: RefObject<(() => Promise) | null>; +}) { + const gt = useGT(); + const { copyToClipboard, isCopied } = useCopyToClipboard({ + target: namedClipboardTarget(props.name), + }); + const [saving, setSaving] = useState(false); + const refreshAssetUrl = useAssetUrlRefresh( + props.environmentId, + largeFileResource(props.threadRef, props.absolutePath, props.draftCwd), + ); + const showError = (cause: unknown) => { + toastManager.add({ + type: "error", + title: gt("Could not read file"), + description: thrownErrorMessage(cause, m) ?? gt("Try again."), + }); + }; + return ( + <> + { + const copy = props.copyContents.current; + if (!copy) return; + void copy() + .then((text) => copyToClipboard(text, undefined)) + .catch(showError); + }} + > + {isCopied ? : } + + { + setSaving(true); + void (async () => { + const url = await refreshAssetUrl(); + if (!url) throw new Error(gt("Reconnect to the environment and try again.")); + const response = await fetch(url); + if (!response.ok) throw new Error(gt("The file could not be loaded. Try again.")); + const downloadUrl = URL.createObjectURL(await response.blob()); + setTimeout(() => URL.revokeObjectURL(downloadUrl), 30_000); + const anchor = document.createElement("a"); + anchor.href = downloadUrl; + anchor.download = props.name.split(/[\\/]/).at(-1) || props.name; + anchor.click(); + })() + .catch(showError) + .finally(() => setSaving(false)); + }} + > + + + + ); +} + export function WorkspaceLargeTextPreview(props: { environmentId: EnvironmentId; threadRef: ScopedThreadRef; absolutePath: string; + /** The draft's workspace while the thread does not exist yet. */ + draftCwd: string | null; name: string; delimiter: "," | "\t" | null; + /** Renders the file as Markdown resolving links against this workspace; null shows source. */ + markdownCwd: string | null; + copyContents: RefObject<(() => Promise) | null>; + /** The first megabyte already read, shown until the whole file arrives. */ + preview: string; + sizeBytes: number; + onPostRender?: ComponentProps["onPostRender"]; workspaceMutationId: string | null; revealLine: number | null; revealRequestId: number; wordWrap: boolean; }) { - const resource = { - _tag: "media-file", - threadId: props.threadRef.threadId, - path: props.absolutePath, - disposition: "attachment", - } as const; + const resource = largeFileResource(props.threadRef, props.absolutePath, props.draftCwd); const gt = useGT(); - const copyContents = useRef<(() => Promise) | null>(null); - const { copyToClipboard, isCopied } = useCopyToClipboard({ - target: namedClipboardTarget(props.name), - }); - const [saving, setSaving] = useState(false); const [revision, setRevision] = useState(0); const showError = (cause: unknown) => { toastManager.add({ @@ -2013,78 +2122,30 @@ export function WorkspaceLargeTextPreview(props: { }} /> ); - if (assetUrl._tag !== "Success" || loaded === null) - return ( -
    - Loading… -
    - ); + if (assetUrl._tag !== "Success" || loaded === null) return ; const src = `${loaded.url}${loaded.url.includes("?") ? "&" : "?"}revision=${encodeURIComponent(loaded.revision)}`; + const retry = () => { + void refreshAssetUrl() + .then(() => setRevision((value) => value + 1)) + .catch(showError); + }; return ( - <> -
    - - Full file - - { - const copy = copyContents.current; - if (!copy) return; - void copy() - .then((text) => copyToClipboard(text, undefined)) - .catch(showError); - }} - > - {isCopied ? : } - - { - setSaving(true); - void (async () => { - const url = await refreshAssetUrl(); - if (!url) throw new Error(gt("Reconnect to the environment and try again.")); - const response = await fetch(url); - if (!response.ok) throw new Error(gt("The file could not be loaded. Try again.")); - const downloadUrl = URL.createObjectURL(await response.blob()); - setTimeout(() => URL.revokeObjectURL(downloadUrl), 30_000); - const anchor = document.createElement("a"); - anchor.href = downloadUrl; - anchor.download = props.name.split(/[\\/]/).at(-1) || props.name; - anchor.click(); - })() - .catch(showError) - .finally(() => setSaving(false)); - }} - > - - -
    - - Loading… -
    - } - > - { - void refreshAssetUrl() - .then(() => setRevision((value) => value + 1)) - .catch(showError); - }} - src={src} - delimiter={props.delimiter} - revealLine={props.revealLine} - revealRequestId={props.revealRequestId} - wordWrap={props.wordWrap} - /> - - + ); } diff --git a/apps/web/src/components/files/LargeFilePreview.tsx b/apps/web/src/components/files/LargeFilePreview.tsx new file mode 100644 index 0000000000000..21590a1ea2b11 --- /dev/null +++ b/apps/web/src/components/files/LargeFilePreview.tsx @@ -0,0 +1,125 @@ +import type { ScopedThreadRef } from "@t3tools/contracts"; +import { DEFAULT_TOKENIZE_MAX_LENGTH } from "@pierre/diffs"; +import type { FileOptions } from "@pierre/diffs/react"; +import { useGT } from "gt-react"; +import { lazy, Suspense, useImperativeHandle, type RefObject } from "react"; + +import { ChunkedMarkdown } from "./ChunkedMarkdown"; +import { FileSurfaceLoading } from "./fileSurfaceChrome"; +import { useFullFileMarkdown, useFullFileText } from "./fullFileText"; +import { FULL_TEXT_MAX_BYTES } from "./largeTextProtocol"; +import SourceFilePreview from "./ReadOnlySourcePreview"; + +const LargeTextViewer = lazy(() => import("./LargeTextViewer")); + +/** + * A file past the 1 MB read, shown like any other file once its full text arrives. Tables, and + * files too large to hold or lay out, use the worker-backed plain viewer. + */ +export default function LargeFilePreview(props: { + readonly src: string; + readonly name: string; + /** The first megabyte already read. */ + readonly preview: string; + readonly sizeBytes: number; + readonly delimiter: "," | "\t" | null; + /** Renders the file as Markdown resolving links against this workspace; null shows source. */ + readonly markdownCwd: string | null; + readonly threadRef: ScopedThreadRef; + readonly workspaceMutationId: string | null; + readonly copyContents: RefObject<(() => Promise) | null>; + readonly onRetry: () => void; + readonly onPostRender?: FileOptions["onPostRender"]; + readonly revealLine: number | null; + readonly revealRequestId: number; + readonly wordWrap: boolean; +}) { + const plain = props.delimiter !== null || props.sizeBytes > FULL_TEXT_MAX_BYTES; + return plain ? : ; +} + +// Pierre keeps every token of a highlighted file in memory: a 320k-line log took about 280 MB. +const HIGHLIGHT_MAX_LINES = DEFAULT_TOKENIZE_MAX_LENGTH; + +/** Estimates the whole file's lines from the preview, so highlighting is decided once. */ +function estimatedLines(preview: string, sizeBytes: number): number { + let lines = 1; + for (let index = preview.indexOf("\n"); index !== -1; index = preview.indexOf("\n", index + 1)) + lines += 1; + return (lines / Math.max(1, new TextEncoder().encode(preview).length)) * sizeBytes; +} + +function FullTextPreview(props: Parameters[0]) { + const file = useFullFileText(props.src, props.preview); + // Deciding from the full text would highlight the preview, then drop it once the file arrives. + const highlight = estimatedLines(props.preview, props.sizeBytes) <= HIGHLIGHT_MAX_LINES; + if (file === "too-large" || file === "failed") return ; + return ( + <> + + {props.markdownCwd !== null ? ( + + ) : ( + + )} + + ); +} + +function MarkdownText( + props: Parameters[0] & { + readonly markdownCwd: string; + readonly file: { readonly text: string; readonly done: boolean }; + }, +) { + return ( + + ); +} + +function CopyText(props: { + readonly copyContents: RefObject<(() => Promise) | null>; + readonly text: string | null; +}) { + const gt = useGT(); + const { text } = props; + useImperativeHandle( + props.copyContents, + () => () => + text === null + ? Promise.reject(new Error(gt("The file is still loading. Try again in a moment."))) + : Promise.resolve(text), + [text, gt], + ); + return null; +} + +function PlainViewer(props: Parameters[0]) { + return ( + }> + + + ); +} diff --git a/apps/web/src/components/files/LargeTextViewer.tsx b/apps/web/src/components/files/LargeTextViewer.tsx index 3cfe6b7fafcaa..fc9a890dd9b3e 100644 --- a/apps/web/src/components/files/LargeTextViewer.tsx +++ b/apps/web/src/components/files/LargeTextViewer.tsx @@ -1,6 +1,7 @@ import { msg, T, useGT, useMessages } from "gt-react"; import { useEffect, useImperativeHandle, useRef, useState, type RefObject } from "react"; import { m } from "~/i18n/messages"; +import { Spinner } from "~/components/ui/spinner"; import { parseDelimitedPreview } from "@t3tools/shared/delimitedPreview"; import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments"; import { useClientSettings } from "~/hooks/useSettings"; @@ -29,6 +30,36 @@ function firstScreen(text: string, delimiter: "," | "\t" | null, complete: boole return rows.slice(0, PREVIEW_PAGE_ROWS * 2); } +type Meta = Extract; + +function firstScreenState(text: string, delimiter: "," | "\t" | null, complete: boolean) { + const rows = firstScreen(text, delimiter, complete); + if (!rows.length) return null; + return { + pages: new Map( + [0, PREVIEW_PAGE_ROWS] + .filter((start) => start < rows.length) + .map((start) => [start / PREVIEW_PAGE_ROWS, rows.slice(start, start + PREVIEW_PAGE_ROWS)]), + ), + meta: { + type: "meta", + count: rows.length, + columns: rows.reduce((max, row) => Math.max(max, row.length), 1), + complete: false, + } satisfies Meta as Meta, + }; +} + +// Reopening a recent file paints its first screen at once while the worker indexes it again. +const recentFirstScreens = new Map(); + +function rememberFirstScreen(src: string, text: string, complete: boolean) { + recentFirstScreens.delete(src); + recentFirstScreens.set(src, { text, complete }); + if (recentFirstScreens.size > 32) + recentFirstScreens.delete(recentFirstScreens.keys().next().value!); +} + export default function LargeTextViewer(props: { readonly name: string; readonly src?: string; @@ -44,8 +75,12 @@ export default function LargeTextViewer(props: { }) { const gt = useGT(); const messages = useMessages(); - const [meta, setMeta] = useState | null>(null); - const [pages, setPages] = useState(new Map()); + const [initial] = useState(() => { + const cached = props.src === undefined ? undefined : recentFirstScreens.get(props.src); + return cached ? firstScreenState(cached.text, props.delimiter, cached.complete) : null; + }); + const [meta, setMeta] = useState(initial?.meta ?? null); + const [pages, setPages] = useState(initial?.pages ?? new Map()); const [error, setError] = useState(null); const worker = useRef(null); const copyPending = useRef<{ @@ -66,25 +101,11 @@ export default function LargeTextViewer(props: { let prefetched = false; const paintFirstScreen = (text: string, complete: boolean) => { if (indexed || controller.signal.aborted) return; - const rows = firstScreen(text, props.delimiter, complete); - if (!rows.length) return; + const screen = firstScreenState(text, props.delimiter, complete); + if (!screen) return; prefetched = true; - setPages( - new Map( - [0, PREVIEW_PAGE_ROWS] - .filter((start) => start < rows.length) - .map((start) => [ - start / PREVIEW_PAGE_ROWS, - rows.slice(start, start + PREVIEW_PAGE_ROWS), - ]), - ), - ); - setMeta({ - type: "meta", - count: rows.length, - columns: rows.reduce((max, row) => Math.max(max, row.length), 1), - complete: false, - }); + setPages(screen.pages); + setMeta(screen.meta); }; const startWorker = () => { if (controller.signal.aborted) return; @@ -104,9 +125,14 @@ export default function LargeTextViewer(props: { } else if (result.type === "meta") { indexed = true; if (prefetched) { - setPages(new Map()); - pending.current.clear(); + // Keeps the painted first screen until the worker's own pages replace it. prefetched = false; + pending.current.clear(); + for (const index of [0, 1]) { + if (index * PREVIEW_PAGE_ROWS >= result.count) break; + pending.current.add(index); + engine.postMessage({ type: "page", index }, []); + } } setMeta(result); } else if (result.type === "page") { @@ -152,8 +178,12 @@ export default function LargeTextViewer(props: { }; // Only this bounded prefix is parsed on the main thread. Indexing the full // file and fetching later pages remain in the worker. + const cached = props.src === undefined ? undefined : recentFirstScreens.get(props.src); if (props.sizeBytes === 0) { startWorker(); + } else if (cached) { + paintFirstScreen(cached.text, cached.complete); + scheduleWorker(); } else if (props.text !== undefined) { paintFirstScreen( props.text.slice(0, FIRST_SCREEN_BYTES), @@ -161,7 +191,8 @@ export default function LargeTextViewer(props: { ); scheduleWorker(); } else if (props.src) { - void fetch(props.src, { + const src = props.src; + void fetch(src, { headers: { Range: `bytes=0-${FIRST_SCREEN_BYTES - 1}` }, cache: "no-store", signal: controller.signal, @@ -176,7 +207,9 @@ export default function LargeTextViewer(props: { return; } const total = Number(response.headers.get("content-range")?.split("/")[1]); - paintFirstScreen(await response.text(), total <= FIRST_SCREEN_BYTES); + const text = await response.text(); + rememberFirstScreen(src, text, total <= FIRST_SCREEN_BYTES); + paintFirstScreen(text, total <= FIRST_SCREEN_BYTES); }) .catch(() => { // The worker reports authorization, network and format failures. @@ -223,27 +256,28 @@ export default function LargeTextViewer(props: { className="flex min-h-10 shrink-0 flex-wrap items-center gap-x-1 border-b border-border/60 px-3 py-2 text-xs text-muted-foreground tabular-nums" role="status" > - {props.delimiter - ? `${gt("{count, plural, one {{formatted} row} other {{formatted} rows}}", { - count: rowCount, - formatted: rowCount.toLocaleString(), - })} · ${gt("{count, plural, one {{formatted} column} other {{formatted} columns}}", { - count: columnCount, - formatted: columnCount.toLocaleString(), - })}` - : gt("{count, plural, one {{formatted} line} other {{formatted} lines}}", { - count: meta.count, - formatted: meta.count.toLocaleString(), - })} + {/* Counts appear once indexing ends; the prefix count alone would understate the file. */} + {!meta.complete + ? null + : props.delimiter + ? `${gt("{count, plural, one {{formatted} row} other {{formatted} rows}}", { + count: rowCount, + formatted: rowCount.toLocaleString(), + })} · ${gt("{count, plural, one {{formatted} column} other {{formatted} columns}}", { + count: columnCount, + formatted: columnCount.toLocaleString(), + })}` + : gt("{count, plural, one {{formatted} line} other {{formatted} lines}}", { + count: meta.count, + formatted: meta.count.toLocaleString(), + })} {meta.complete && meta.sizeBytes !== undefined ? ` · ${meta.sizeBytes === 0 ? gt("0 bytes") : formatAttachmentSize(meta.sizeBytes, messages)}` - : ` · ${gt("Indexing…")}`} + : null}
    {!meta.complete ? ( -
    - - Loading the rest of the file… - +
    +
    ) : null} {meta.columns === 1024 ? ( diff --git a/apps/web/src/components/files/ReadOnlySourcePreview.tsx b/apps/web/src/components/files/ReadOnlySourcePreview.tsx index d9236753e98a3..cd1559f46052f 100644 --- a/apps/web/src/components/files/ReadOnlySourcePreview.tsx +++ b/apps/web/src/components/files/ReadOnlySourcePreview.tsx @@ -17,6 +17,8 @@ export default function ReadOnlySourcePreview(props: { readonly onPostRender?: FileOptions["onPostRender"]; /** A preview's own wrap toggle; omitted follows the word wrap setting. */ readonly wordWrap?: boolean; + /** Files with more lines than this render without highlighting; omitted keeps Pierre's limit. */ + readonly tokenizeMaxLength?: number; }) { const resolvedTheme = useRenderedAppearance(); const defaultWordWrap = useClientSettings((settings) => settings.wordWrap); @@ -70,7 +72,8 @@ export default function ReadOnlySourcePreview(props: { }} > @@ -85,6 +88,9 @@ export default function ReadOnlySourcePreview(props: { overflow: wordWrap ? "wrap" : "scroll", theme: resolveDiffThemeName(resolvedTheme), preferredHighlighter: PREFERRED_HIGHLIGHTER, + ...(props.tokenizeMaxLength === undefined + ? {} + : { tokenizeMaxLength: props.tokenizeMaxLength }), themeType: resolvedTheme, unsafeCSS: FILE_LINK_REVEAL_UNSAFE_CSS, onPostRender: drawSelection, diff --git a/apps/web/src/components/files/fullFileText.test.ts b/apps/web/src/components/files/fullFileText.test.ts new file mode 100644 index 0000000000000..80f507c3526cb --- /dev/null +++ b/apps/web/src/components/files/fullFileText.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Stream from "effect/Stream"; +import { FetchHttpClient } from "effect/http"; + +import { downloadText } from "./fullFileText"; +import { RENDERED_MAX_LINES } from "./largeTextProtocol"; + +const encoder = new TextEncoder(); + +const download = (file: Uint8Array) => + downloadText("http://localhost/assets/file.ts").pipe( + Stream.runLast, + Effect.map(Option.getOrThrow), + Effect.provide(FetchHttpClient.layer), + Effect.provideService(FetchHttpClient.Fetch, () => Promise.resolve(new Response(file.slice()))), + ); + +describe("downloadText", () => { + it.effect( + "drops a leading byte order mark as the preview read does, and keeps a later U+FEFF", + () => + Effect.gen(function* () { + const whole = new Uint8Array([0xef, 0xbb, 0xbf, ...encoder.encode("one\ntwo\n")]); + expect((yield* download(whole)).text).toBe("one\ntwo\n"); + }), + ); + + it.effect("stops at the first text past the lines the main thread can lay out", () => + Effect.gen(function* () { + const file = yield* download(encoder.encode("\n".repeat(RENDERED_MAX_LINES + 10))); + expect(file.lines).toBeGreaterThan(RENDERED_MAX_LINES); + }), + ); +}); diff --git a/apps/web/src/components/files/fullFileText.ts b/apps/web/src/components/files/fullFileText.ts new file mode 100644 index 0000000000000..8ff9c557407a1 --- /dev/null +++ b/apps/web/src/components/files/fullFileText.ts @@ -0,0 +1,90 @@ +import { useAtomValue } from "@effect/atom-react"; +import { splitMarkdown, type SplitMarkdown } from "@t3tools/shared/markdownChunks"; +import * as Effect from "effect/Effect"; +import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http"; +import * as Stream from "effect/Stream"; +import { AsyncResult, Atom } from "effect/reactivity"; + +import { connectionAtomRuntime } from "~/connection/runtime"; + +import { FULL_TEXT_MAX_BYTES, RENDERED_MAX_LINES } from "./largeTextProtocol"; + +// A slow download swaps in what has arrived this often, so the reader is not left at 1 MB. +const SWAP_INTERVAL = "1 second"; +// Switching back to a recently closed file reuses its text instead of downloading it again. +const RECENT_FILE_TTL_MS = 60_000; + +interface Downloaded { + readonly text: string; + readonly lines: number; +} + +function countNewlines(text: string): number { + let lines = 0; + for (let index = text.indexOf("\n"); index !== -1; index = text.indexOf("\n", index + 1)) { + lines += 1; + } + return lines; +} + +// Past either cap the main thread cannot hold or lay the text out. +const tooLarge = (file: Downloaded) => + file.lines > RENDERED_MAX_LINES || file.text.length > FULL_TEXT_MAX_BYTES; + +/** A file's text so far, at most once per interval, ending at its whole text or past a cap. */ +export const downloadText = (src: string) => + HttpClient.get(src).pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.map((response) => response.stream), + Effect.provideService(FetchHttpClient.RequestInit, { cache: "no-store" }), + Stream.unwrap, + // Drops a leading BOM, as the 1 MB preview read does. + Stream.decodeText, + Stream.scan( + (): Downloaded => ({ text: "", lines: 1 }), + (file, chunk) => ({ text: file.text + chunk, lines: file.lines + countNewlines(chunk) }), + ), + Stream.takeUntil(tooLarge), + Stream.groupedWithin(Number.MAX_SAFE_INTEGER, SWAP_INTERVAL), + Stream.map((swaps) => swaps[swaps.length - 1]!), + ); + +/** `src` is the asset URL with its revision, so a changed file downloads again. */ +const fullFileTextAtom = Atom.family((src: string) => + connectionAtomRuntime + .atom(downloadText(src)) + .pipe(Atom.setIdleTTL(RECENT_FILE_TTL_MS), Atom.withLabel(`full-file-text:${src}`)), +); + +export type FullFileText = + | { readonly text: string; readonly done: boolean } + | "too-large" + | "failed"; + +/** A file past the 1 MB read: the preview at once, then the full file as it downloads. */ +export function useFullFileText(src: string, preview: string): FullFileText { + const result = useAtomValue(fullFileTextAtom(src)); + if (AsyncResult.isFailure(result)) return "failed"; + if (!AsyncResult.isSuccess(result)) return { text: preview, done: false }; + if (tooLarge(result.value)) return "too-large"; + if (!result.waiting) return { text: result.value.text, done: true }; + // Whole lines only, so the last row does not flicker as it fills in; the first swap can still + // hold less than the preview already shows. + const text = result.value.text.slice(0, result.value.text.lastIndexOf("\n") + 1); + return { text: text.length >= preview.length ? text : preview, done: false }; +} + +/** The finished text's Markdown pieces, kept as long as its text; splitting 12 MB takes 0.5 s. */ +const fullFileMarkdownAtom = Atom.family((src: string) => + Atom.make((get) => { + const result = get(fullFileTextAtom(src)); + return AsyncResult.isSuccess(result) && !result.waiting && !tooLarge(result.value) + ? splitMarkdown(result.value.text) + : null; + }).pipe(Atom.setIdleTTL(RECENT_FILE_TTL_MS), Atom.withLabel(`full-file-markdown:${src}`)), +); + +/** Markdown pieces of the text so far; a finished file's are split once and kept. */ +export function useFullFileMarkdown(src: string, text: string): SplitMarkdown { + return useAtomValue(fullFileMarkdownAtom(src)) ?? splitMarkdown(text); +} diff --git a/apps/web/src/components/files/largeTextProtocol.ts b/apps/web/src/components/files/largeTextProtocol.ts index 8ff6e54946289..661b15c8c8e7d 100644 --- a/apps/web/src/components/files/largeTextProtocol.ts +++ b/apps/web/src/components/files/largeTextProtocol.ts @@ -3,6 +3,12 @@ export const LARGE_TEXT_MAX_BYTES = 256 * 1024 * 1024; export const LARGE_TEXT_MAX_ROWS = 5_000_000; export const LARGE_TEXT_MAX_COLUMNS = 1024; export const PREVIEW_PAGE_ROWS = 32; +// Browsers stop laying out an element near 33.5M px. Rendered Markdown measured about 22 px per +// source line, so files taller than this stay in the scaled plain viewer. +export const RENDERED_MAX_LINES = 1_200_000; +// Rendered Markdown and highlighted source hold the whole file on the main thread; larger files +// use the worker-backed plain viewer. +export const FULL_TEXT_MAX_BYTES = 64 * 1024 * 1024; export type TextPreviewRequest = | { type: "open"; src?: string; text?: string; sizeBytes?: number; delimiter: "," | "\t" | null } | { type: "page"; index: number } diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 16f3d83c8b2e6..8d5cb7d817bb1 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -5628,7 +5628,6 @@ }, ". Prüfe den Pfad des Links oder suche die Datei unter Dateien." ], - "b9b6bbd1e1ea189f": "Ganze Datei", "d715e9494fdbaaf6": "Die Schriftart konnte nicht geladen werden.", "ff17c777a72b4408": "Schriftvorschauen sind auf 10 MB begrenzt.", "6bd41ad699e22f10": "Die Schriftart ist nicht verfügbar.", @@ -5638,6 +5637,7 @@ "a9abaaa4220eae21": "{error} Speichere sie, um sie in einer anderen App zu öffnen.", "c508c9000d9656f8": "Schriftvorschau", "1c416d621d250be8": "Victor jagt zwölf Boxkämpfer quer über den großen Sylter Deich.", + "d7d08260f16b7828": "Die Datei wird noch geladen. Versuche es gleich noch einmal.", "76ebb03de52c92d6": "Der Textbetrachter wurde beendet.", "f48162e8e8c12af7": "Der Textbetrachter konnte nicht geladen werden. Schließe die Datei und versuche es erneut.", "bc4c5b13d38a5da7": "Vorschau geschlossen.", @@ -5645,8 +5645,6 @@ "9450d1827ef336a1": "Ein anderer Kopiervorgang läuft.", "8f48999eb6d9e2e3": "{count, plural, one {{formatted} Zeile} other {{formatted} Zeilen}}", "13b14784f8707ddd": "0 Byte", - "f6e9581cba3467fa": "Wird indiziert…", - "2d1f293ac12463fc": "Der Rest der Datei wird geladen…", "b75105bef8f564a4": "Die ersten 1.024 Spalten werden angezeigt. Quelltext und Speichern behalten alle Spalten.", "2a6e1b1f209c3888": "Diese Datei ist leer.", "192fc79eb3b5b2cb": "Dieses Diagramm enthält Ressourcen-URLs, Markup, Knotenmetadaten oder eine benutzerdefinierte Konfiguration. Zeige den Mermaid-Quelltext an, um es sicher zu prüfen.", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index c4534c680b95f..6c5ef49b77f43 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -5629,7 +5629,6 @@ }, ". Check the link's path or locate the file in Files." ], - "b9b6bbd1e1ea189f": "Full file", "d715e9494fdbaaf6": "The font could not be loaded.", "ff17c777a72b4408": "Font previews are limited to 10 MB.", "6bd41ad699e22f10": "The font is unavailable.", @@ -5639,6 +5638,7 @@ "a9abaaa4220eae21": "{error} Save it to open in another app.", "c508c9000d9656f8": "Font preview", "1c416d621d250be8": "The quick brown fox jumps over the lazy dog.", + "d7d08260f16b7828": "The file is still loading. Try again in a moment.", "76ebb03de52c92d6": "The text viewer stopped.", "f48162e8e8c12af7": "Could not load the text viewer. Close the file and try again.", "bc4c5b13d38a5da7": "Preview closed.", @@ -5646,8 +5646,6 @@ "9450d1827ef336a1": "Another copy is in progress.", "8f48999eb6d9e2e3": "{count, plural, one {{formatted} line} other {{formatted} lines}}", "13b14784f8707ddd": "0 bytes", - "f6e9581cba3467fa": "Indexing…", - "2d1f293ac12463fc": "Loading the rest of the file…", "b75105bef8f564a4": "Showing the first 1,024 columns. Source and Save retain every column.", "2a6e1b1f209c3888": "This file is empty.", "192fc79eb3b5b2cb": "This diagram contains resource URLs, markup, node metadata, or custom configuration. Show Mermaid source to inspect it safely.", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index ff83b277dc0d6..1f4ed2cf548ee 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -5627,7 +5627,6 @@ }, ". Revisa la ruta del enlace o busca el archivo en Archivos." ], - "b9b6bbd1e1ea189f": "Archivo completo", "d715e9494fdbaaf6": "No se pudo cargar la fuente.", "ff17c777a72b4408": "Las vistas previas de fuentes están limitadas a 10 MB.", "6bd41ad699e22f10": "La fuente no está disponible.", @@ -5637,6 +5636,7 @@ "a9abaaa4220eae21": "{error} Guárdala para abrirla en otra app.", "c508c9000d9656f8": "Vista previa de la fuente", "1c416d621d250be8": "El veloz murciélago hindú comía feliz cardillo y kiwi.", + "d7d08260f16b7828": "El archivo aún se está cargando. Inténtalo de nuevo en un momento.", "76ebb03de52c92d6": "El visor de texto se detuvo.", "f48162e8e8c12af7": "No se pudo cargar el visor de texto. Cierra el archivo y vuelve a intentarlo.", "bc4c5b13d38a5da7": "Vista previa cerrada.", @@ -5644,8 +5644,6 @@ "9450d1827ef336a1": "Ya hay otra copia en curso.", "8f48999eb6d9e2e3": "{count, plural, one {{formatted} línea} other {{formatted} líneas}}", "13b14784f8707ddd": "0 bytes", - "f6e9581cba3467fa": "Indexando…", - "2d1f293ac12463fc": "Cargando el resto del archivo…", "b75105bef8f564a4": "Se muestran las primeras 1024 columnas. El código fuente y Guardar conservan todas las columnas.", "2a6e1b1f209c3888": "Este archivo está vacío.", "192fc79eb3b5b2cb": "Este diagrama contiene URL de recursos, marcado, metadatos de nodos o configuración personalizada. Muestra el código fuente de Mermaid para inspeccionarlo de forma segura.", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 939d36465b041..72da8bf8e23b2 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -5628,7 +5628,6 @@ }, ". Vérifiez le chemin du lien ou retrouvez le fichier dans Fichiers." ], - "b9b6bbd1e1ea189f": "Fichier complet", "d715e9494fdbaaf6": "Impossible de charger la police.", "ff17c777a72b4408": "Les aperçus de polices sont limités à 10 Mo.", "6bd41ad699e22f10": "La police est indisponible.", @@ -5638,6 +5637,7 @@ "a9abaaa4220eae21": "{error} Enregistrez-la pour l’ouvrir dans une autre app.", "c508c9000d9656f8": "Aperçu de la police", "1c416d621d250be8": "Portez ce vieux whisky au juge blond qui fume.", + "d7d08260f16b7828": "Le fichier est encore en cours de chargement. Réessaie dans un instant.", "76ebb03de52c92d6": "La visionneuse de texte s’est arrêtée.", "f48162e8e8c12af7": "Impossible de charger la visionneuse de texte. Fermez le fichier et réessayez.", "bc4c5b13d38a5da7": "Aperçu fermé.", @@ -5645,8 +5645,6 @@ "9450d1827ef336a1": "Une autre copie est en cours.", "8f48999eb6d9e2e3": "{count, plural, one {{formatted} ligne} other {{formatted} lignes}}", "13b14784f8707ddd": "0 octet", - "f6e9581cba3467fa": "Indexation…", - "2d1f293ac12463fc": "Chargement du reste du fichier…", "b75105bef8f564a4": "Affichage des 1 024 premières colonnes. Source et Enregistrer conservent toutes les colonnes.", "2a6e1b1f209c3888": "Ce fichier est vide.", "192fc79eb3b5b2cb": "Ce diagramme contient des URL de ressources, du balisage, des métadonnées de nœuds ou une configuration personnalisée. Affichez la source Mermaid pour l’examiner en toute sécurité.", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 51fe276edc353..28945ae29dca3 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -5610,7 +5610,6 @@ }, "。リンクのパスを確認するか、[ファイル] でファイルを探してください。" ], - "b9b6bbd1e1ea189f": "ファイル全体", "d715e9494fdbaaf6": "フォントを読み込めませんでした。", "ff17c777a72b4408": "フォントのプレビューは 10 MB までです。", "6bd41ad699e22f10": "フォントを利用できません。", @@ -5620,6 +5619,7 @@ "a9abaaa4220eae21": "{error} 別のアプリで開くには保存してください。", "c508c9000d9656f8": "フォントのプレビュー", "1c416d621d250be8": "いろはにほへと ちりぬるを わかよたれそ つねならむ", + "d7d08260f16b7828": "ファイルはまだ読み込み中です。少し待ってからもう一度お試しください。", "76ebb03de52c92d6": "テキストビューアーが停止しました。", "f48162e8e8c12af7": "テキストビューアーを読み込めませんでした。ファイルを閉じて、もう一度お試しください。", "bc4c5b13d38a5da7": "プレビューを閉じました。", @@ -5627,8 +5627,6 @@ "9450d1827ef336a1": "別のコピーが進行中です。", "8f48999eb6d9e2e3": "{count, plural, other {{formatted} 行}}", "13b14784f8707ddd": "0 バイト", - "f6e9581cba3467fa": "インデックスを作成しています…", - "2d1f293ac12463fc": "ファイルの残りを読み込んでいます…", "b75105bef8f564a4": "最初の 1,024 列を表示しています。ソースと保存ではすべての列が保持されます。", "2a6e1b1f209c3888": "このファイルは空です。", "192fc79eb3b5b2cb": "この図にはリソース URL、マークアップ、ノードのメタデータ、またはカスタム構成が含まれています。安全に確認するには Mermaid のソースを表示してください。", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 51c3b0a06a006..35f6cc3549436 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -5608,7 +5608,6 @@ }, ". 링크의 경로를 확인하거나 파일에서 해당 파일을 찾으세요." ], - "b9b6bbd1e1ea189f": "전체 파일", "d715e9494fdbaaf6": "글꼴을 불러올 수 없습니다.", "ff17c777a72b4408": "글꼴 미리 보기는 10MB로 제한됩니다.", "6bd41ad699e22f10": "글꼴을 사용할 수 없습니다.", @@ -5618,6 +5617,7 @@ "a9abaaa4220eae21": "{error} 저장한 후 다른 앱에서 여세요.", "c508c9000d9656f8": "글꼴 미리 보기", "1c416d621d250be8": "다람쥐 헌 쳇바퀴에 타고파.", + "d7d08260f16b7828": "파일을 아직 불러오는 중입니다. 잠시 후 다시 시도하세요.", "76ebb03de52c92d6": "텍스트 뷰어가 중지되었습니다.", "f48162e8e8c12af7": "텍스트 뷰어를 불러올 수 없습니다. 파일을 닫고 다시 시도하세요.", "bc4c5b13d38a5da7": "미리 보기가 닫혔습니다.", @@ -5625,8 +5625,6 @@ "9450d1827ef336a1": "다른 복사가 진행 중입니다.", "8f48999eb6d9e2e3": "{count, plural, other {{formatted}줄}}", "13b14784f8707ddd": "0바이트", - "f6e9581cba3467fa": "색인하는 중…", - "2d1f293ac12463fc": "파일의 나머지를 불러오는 중…", "b75105bef8f564a4": "처음 1,024열을 표시합니다. 소스와 저장에는 모든 열이 유지됩니다.", "2a6e1b1f209c3888": "이 파일은 비어 있습니다.", "192fc79eb3b5b2cb": "이 다이어그램에는 리소스 URL, 마크업, 노드 메타데이터 또는 사용자 지정 구성이 포함되어 있습니다. 안전하게 확인하려면 Mermaid 소스를 표시하세요.", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index d17ff0e321ccf..85fefb672d30c 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -5627,7 +5627,6 @@ }, ". Verifique o caminho do link ou localize o arquivo em Arquivos." ], - "b9b6bbd1e1ea189f": "Arquivo completo", "d715e9494fdbaaf6": "Não foi possível carregar a fonte.", "ff17c777a72b4408": "As pré-visualizações de fontes são limitadas a 10 MB.", "6bd41ad699e22f10": "A fonte não está disponível.", @@ -5637,6 +5636,7 @@ "a9abaaa4220eae21": "{error} Salve-a para abrir em outro app.", "c508c9000d9656f8": "Pré-visualização da fonte", "1c416d621d250be8": "Um pequeno jabuti xereta viu dez cegonhas felizes.", + "d7d08260f16b7828": "O arquivo ainda está carregando. Tente novamente em instantes.", "76ebb03de52c92d6": "O visualizador de texto parou.", "f48162e8e8c12af7": "Não foi possível carregar o visualizador de texto. Feche o arquivo e tente novamente.", "bc4c5b13d38a5da7": "Pré-visualização fechada.", @@ -5644,8 +5644,6 @@ "9450d1827ef336a1": "Outra cópia está em andamento.", "8f48999eb6d9e2e3": "{count, plural, one {{formatted} linha} other {{formatted} linhas}}", "13b14784f8707ddd": "0 bytes", - "f6e9581cba3467fa": "Indexando…", - "2d1f293ac12463fc": "Carregando o restante do arquivo…", "b75105bef8f564a4": "Mostrando as primeiras 1.024 colunas. O código-fonte e o arquivo salvo mantêm todas as colunas.", "2a6e1b1f209c3888": "Este arquivo está vazio.", "192fc79eb3b5b2cb": "Este diagrama contém URLs de recursos, markup, metadados de nós ou configuração personalizada. Mostre o código Mermaid para inspecioná-lo com segurança.", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 88e2323bac363..f4d45a79d0b52 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -5627,7 +5627,6 @@ }, ". Проверьте путь в ссылке или найдите файл в «Файлах»." ], - "b9b6bbd1e1ea189f": "Файл целиком", "d715e9494fdbaaf6": "Не удалось загрузить шрифт.", "ff17c777a72b4408": "Предпросмотр шрифтов ограничен 10 МБ.", "6bd41ad699e22f10": "Шрифт недоступен.", @@ -5637,6 +5636,7 @@ "a9abaaa4220eae21": "{error} Сохраните его, чтобы открыть в другом приложении.", "c508c9000d9656f8": "Предпросмотр шрифта", "1c416d621d250be8": "Съешь же ещё этих мягких французских булок, да выпей чаю.", + "d7d08260f16b7828": "Файл ещё загружается. Повторите попытку через мгновение.", "76ebb03de52c92d6": "Просмотрщик текста остановился.", "f48162e8e8c12af7": "Не удалось загрузить просмотрщик текста. Закройте файл и повторите попытку.", "bc4c5b13d38a5da7": "Предпросмотр закрыт.", @@ -5644,8 +5644,6 @@ "9450d1827ef336a1": "Уже идёт другое копирование.", "8f48999eb6d9e2e3": "{count, plural, one {{formatted} строка} few {{formatted} строки} many {{formatted} строк} other {{formatted} строки}}", "13b14784f8707ddd": "0 байт", - "f6e9581cba3467fa": "Индексация…", - "2d1f293ac12463fc": "Загрузка остальной части файла…", "b75105bef8f564a4": "Показаны первые 1 024 столбца. «Исходник» и «Сохранить» сохраняют все столбцы.", "2a6e1b1f209c3888": "Этот файл пуст.", "192fc79eb3b5b2cb": "Эта диаграмма содержит URL ресурсов, разметку, метаданные узлов или собственную конфигурацию. Откройте исходник Mermaid, чтобы безопасно её изучить.", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 055af1f3a6783..99818c1f2ed37 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -5628,7 +5628,6 @@ }, ". Kontrollera länkens sökväg eller leta upp filen i Filer." ], - "b9b6bbd1e1ea189f": "Hela filen", "d715e9494fdbaaf6": "Teckensnittet kunde inte läsas in.", "ff17c777a72b4408": "Förhandsvisningar av teckensnitt är begränsade till 10 MB.", "6bd41ad699e22f10": "Teckensnittet är inte tillgängligt.", @@ -5638,6 +5637,7 @@ "a9abaaa4220eae21": "{error} Spara det för att öppna det i en annan app.", "c508c9000d9656f8": "Förhandsvisning av teckensnitt", "1c416d621d250be8": "Flygande bäckasiner söka hwila på mjuka tuvor.", + "d7d08260f16b7828": "Filen läses fortfarande in. Försök igen om en stund.", "76ebb03de52c92d6": "Textvisaren stoppades.", "f48162e8e8c12af7": "Kunde inte läsa in textvisaren. Stäng filen och försök igen.", "bc4c5b13d38a5da7": "Förhandsvisningen stängdes.", @@ -5645,8 +5645,6 @@ "9450d1827ef336a1": "En annan kopiering pågår.", "8f48999eb6d9e2e3": "{count, plural, one {{formatted} rad} other {{formatted} rader}}", "13b14784f8707ddd": "0 byte", - "f6e9581cba3467fa": "Indexerar…", - "2d1f293ac12463fc": "Läser in resten av filen…", "b75105bef8f564a4": "Visar de första 1 024 kolumnerna. Källa och Spara behåller alla kolumner.", "2a6e1b1f209c3888": "Den här filen är tom.", "192fc79eb3b5b2cb": "Det här diagrammet innehåller resurs-URL:er, markup, nodmetadata eller anpassad konfiguration. Visa Mermaid-källan för att granska det säkert.", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 998020844cf79..09d04201cd2f8 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -5634,7 +5634,6 @@ }, "。请检查链接的路径,或在“文件”中找到该文件。" ], - "b9b6bbd1e1ea189f": "完整文件", "d715e9494fdbaaf6": "无法加载该字体。", "ff17c777a72b4408": "字体预览限制为 10 MB。", "6bd41ad699e22f10": "该字体不可用。", @@ -5644,6 +5643,7 @@ "a9abaaa4220eae21": "{error} 保存后可在其他应用中打开。", "c508c9000d9656f8": "字体预览", "1c416d621d250be8": "敏捷的棕色狐狸跳过了那只懒狗。", + "d7d08260f16b7828": "文件仍在加载中。请稍后重试。", "76ebb03de52c92d6": "文本查看器已停止。", "f48162e8e8c12af7": "无法加载文本查看器。请关闭文件后重试。", "bc4c5b13d38a5da7": "预览已关闭。", @@ -5651,8 +5651,6 @@ "9450d1827ef336a1": "另一个复制操作正在进行。", "8f48999eb6d9e2e3": "{count, plural, other {{formatted} 行}}", "13b14784f8707ddd": "0 字节", - "f6e9581cba3467fa": "正在建立索引…", - "2d1f293ac12463fc": "正在加载文件的其余部分…", "b75105bef8f564a4": "仅显示前 1,024 列。查看源码或保存文件时会保留所有列。", "2a6e1b1f209c3888": "此文件为空。", "192fc79eb3b5b2cb": "此图表包含资源 URL、标记、节点元数据或自定义配置。请显示 Mermaid 源码以安全查看。", diff --git a/packages/contracts/src/assets.ts b/packages/contracts/src/assets.ts index 0cae763748d7a..761cdb8114d9c 100644 --- a/packages/contracts/src/assets.ts +++ b/packages/contracts/src/assets.ts @@ -41,6 +41,7 @@ export const AssetResource = Schema.Union([ Schema.TaggedStruct("draft-workspace-file", { cwd: TrimmedNonEmptyString.check(Schema.isMaxLength(ASSET_PATH_MAX_LENGTH)), path: TrimmedNonEmptyString.check(Schema.isMaxLength(ASSET_PATH_MAX_LENGTH)), + disposition: Schema.optionalKey(Schema.Literal("attachment")), }), Schema.TaggedStruct("attachment", { attachmentId: TrimmedNonEmptyString.check(Schema.isMaxLength(256)), diff --git a/packages/shared/package.json b/packages/shared/package.json index b1ffa038030ef..b727b976fe143 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -519,6 +519,10 @@ "types": "./src/markdownGithubAlerts.ts", "import": "./src/markdownGithubAlerts.ts" }, + "./markdownChunks": { + "types": "./src/markdownChunks.ts", + "import": "./src/markdownChunks.ts" + }, "./markdownHast": { "types": "./src/markdownHast.ts", "import": "./src/markdownHast.ts" diff --git a/packages/shared/src/markdownChunks.test.ts b/packages/shared/src/markdownChunks.test.ts new file mode 100644 index 0000000000000..a5cf2a8017b35 --- /dev/null +++ b/packages/shared/src/markdownChunks.test.ts @@ -0,0 +1,132 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { splitMarkdown } from "./markdownChunks.ts"; + +const splitLargeMarkdown = (text: string, targetChars?: number) => + splitMarkdown(text, targetChars).chunks; + +const starts = (text: string) => + splitLargeMarkdown(text, 1).map((chunk) => chunk.text.split("\n")[0]); + +describe("splitMarkdown", () => { + it("cuts only where a new top-level block starts, and keeps every byte", () => { + const text = [ + "# Title", + "Intro paragraph", + "", + "- item one", + "", + " continued item", + "- item two", + "", + "2. ordered", + "", + "```md", + "# not a heading", + "", + "Not a paragraph", + "```", + "", + "> quote", + "", + "Closing paragraph", + "## Next", + "---", + "", + "| a | b |", + ].join("\n"); + const chunks = splitLargeMarkdown(text, 1); + expect(chunks.map((chunk) => chunk.text).join("\n")).toBe(text); + expect(chunks.reduce((sum, chunk) => sum + chunk.lines, 0)).toBe(text.split("\n").length); + expect(starts(text)).toEqual([ + "# Title", + "```md", + "> quote", + "Closing paragraph", + "## Next", + "| a | b |", + ]); + }); + + it("keeps a fence open until a matching closer", () => { + const text = ["````", "```", "", "# inside", "````", "", "after"].join("\n"); + expect(starts(text)).toEqual(["````", "after"]); + }); + + it("keeps HTML blocks and display math open across blank lines", () => { + const text = [ + "", + "", + "$$", + "", + "Inside math", + "$$", + "", + "
    ",
    +      "",
    +      "Preformatted",
    +      "
    ", + "", + "", + "", + "
    ", + "# literal", + "
    ", + "", + "after", + ].join("\n"); + expect(starts(text)).toEqual(["/], + [/^ {0,3}<\?/, /\?>/], + [/^ {0,3}/], + [/^ {0,3}/], + [/^ {0,3}\$\$/, /\$\$/], +]; + +// A tag name, not an autolink such as . +const HTML_BLOCK_START = /^ {0,3}<\/?[A-Za-z][A-Za-z0-9-]*(?=[\s/>]|$)/; + +/** Returns how to recognize the end of a block that `line` opens, or null for none. */ +function blockCloser(line: string): ((line: string) => boolean) | null { + const fence = FENCE_OPEN.exec(line)?.[1]; + if (fence) { + return (next) => { + const closer = FENCE_OPEN.exec(next)?.[1]; + return ( + closer !== undefined && + closer[0] === fence[0] && + closer.length >= fence.length && + !next.trim().slice(closer.length) + ); + }; + } + for (const [open, close] of SPANNING_BLOCKS) { + const opener = open.exec(line)?.[0]; + if (opener === undefined) continue; + return close.test(line.slice(opener.length)) ? null : (next) => close.test(next); + } + // Other HTML blocks (CommonMark types 6 and 7) run until a blank line. + return HTML_BLOCK_START.test(line) ? (next) => next.trim() === "" : null; +} + +export interface MarkdownChunk { + readonly text: string; + readonly lines: number; +} + +const FRONTMATTER_OPEN = /^\uFEFF?---[ \t]*\r?$/; +const FRONTMATTER_CLOSE = /^(?:---|\.\.\.)[ \t]*\r?$/; +// An opening rule with no closer is a thematic break, not frontmatter; stop waiting for one. +const FRONTMATTER_MAX_LINES = 1000; + +// A one-line link reference definition; footnotes are left alone so each piece does not grow +// a footnote section. +const LINK_DEFINITION = + /^ {0,3}\[(?!\^)(?:[^\]\\]|\\.)+\]:[ \t]*(?:<[^<>\n]*>|[^\s<]\S*)(?:[ \t]+(?:"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|\((?:[^()\\]|\\.)*\)))?[ \t]*\r?$/; +// Definitions past this are not repeated into every piece; their parse cost would outweigh links. +const SHARED_DEFINITIONS_MAX_CHARS = 16 * 1024; + +export interface SplitMarkdown { + readonly chunks: readonly MarkdownChunk[]; + readonly definitions: string; +} + +/** + * Cuts Markdown into pieces of roughly `targetChars`, only at column-0 headings or paragraphs + * that start a new top-level block. Leading frontmatter stays in the first piece. Link + * definitions are collected so every piece can resolve them; footnotes resolve only inside their + * own piece, and duplicate heading slugs restart per piece. + */ +export function splitMarkdown(text: string, targetChars = CHUNK_TARGET_CHARS): SplitMarkdown { + const chunks: MarkdownChunk[] = []; + const definitions: string[] = []; + let lines: string[] = []; + let first = true; + let chars = 0; + let closes: ((line: string) => boolean) | null = null; + let afterBlankLine = false; + let afterDefinition = false; + let afterHeading = false; + let definitionChars = 0; + const flush = () => { + chunks.push({ text: lines.join("\n"), lines: lines.length }); + lines = []; + chars = 0; + }; + for (const line of text.split("\n")) { + if (closes !== null) { + if (closes(line)) closes = null; + } else if (first && FRONTMATTER_OPEN.test(line)) { + let seen = 0; + closes = (next) => FRONTMATTER_CLOSE.test(next) || ++seen >= FRONTMATTER_MAX_LINES; + } else { + const cut = + chars >= targetChars && + (ATX_HEADING.test(line) || + (afterBlankLine && BLOCK_START.test(line) && !ORDERED_ITEM.test(line))); + if (cut) flush(); + closes = blockCloser(line); + // A definition cannot interrupt a paragraph, so it follows a blank line, a heading or + // another definition. + const definition: boolean = + (first || afterBlankLine || afterDefinition || afterHeading) && LINK_DEFINITION.test(line); + afterDefinition = definition; + if (definition && definitionChars + line.length < SHARED_DEFINITIONS_MAX_CHARS) { + definitions.push(line.trim()); + definitionChars += line.length + 1; + } + } + first = false; + lines.push(line); + chars += line.length + 1; + afterBlankLine = line.trim() === ""; + afterHeading = closes === null && (ATX_HEADING.test(line) || THEMATIC_BREAK.test(line)); + } + flush(); + return { chunks, definitions: definitions.join("\n") }; +} + +/** Appends shared link definitions after a piece, leaving its own offsets unchanged. */ +export function withMarkdownDefinitions(text: string, definitions: string): string { + return definitions ? `${text}\n\n${definitions}` : text; +} From ba947e37e1f721fa0b89edc6347a3d8e61e09362 Mon Sep 17 00:00:00 2001 From: bruno Date: Sun, 22 Nov 2026 23:11:55 +0000 Subject: [PATCH 221/324] fix(desktop): show ampersands in native context menu labels (#41097) Co-authored-by: Julius Marminge --- .../desktop/src/electron/ElectronMenu.test.ts | 45 +++++++++++++++++++ apps/desktop/src/electron/ElectronMenu.ts | 3 +- 2 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 apps/desktop/src/electron/ElectronMenu.test.ts diff --git a/apps/desktop/src/electron/ElectronMenu.test.ts b/apps/desktop/src/electron/ElectronMenu.test.ts new file mode 100644 index 0000000000000..df98bdf4e9e85 --- /dev/null +++ b/apps/desktop/src/electron/ElectronMenu.test.ts @@ -0,0 +1,45 @@ +import { assert, describe, it } from "@effect/vitest"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import type * as Electron from "electron"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import { vi } from "vite-plus/test"; + +const { menu } = vi.hoisted(() => ({ + menu: { template: [] as Electron.MenuItemConstructorOptions[] }, +})); + +vi.mock("electron", () => ({ + Menu: { + buildFromTemplate: (template: Electron.MenuItemConstructorOptions[]) => { + menu.template = template; + return { popup: (options: Electron.PopupOptions) => options.callback?.() }; + }, + }, +})); + +import * as ElectronMenu from "./ElectronMenu.ts"; + +describe("ElectronMenu", () => { + it.effect("shows ampersands in labels instead of reading them as mnemonics", () => + Effect.gen(function* () { + const electronMenu = yield* ElectronMenu.make; + yield* electronMenu.showContextMenu({ + window: { webContents: { getZoomFactor: () => 1 } } as Electron.BrowserWindow, + items: [ + { id: "filter", label: "Filter by R&D" }, + { id: "more", label: "A&B", children: [{ id: "child", label: "C && D" }] }, + ], + position: Option.none(), + source: Option.none(), + }); + + assert.deepEqual( + menu.template.map((item) => item.label), + ["Filter by R&&D", "A&&B"], + ); + const submenu = menu.template[1]!.submenu as Electron.MenuItemConstructorOptions[]; + assert.equal(submenu[0]!.label, "C &&&& D"); + }).pipe(Effect.provideService(HostProcess.Platform, "win32")), + ); +}); diff --git a/apps/desktop/src/electron/ElectronMenu.ts b/apps/desktop/src/electron/ElectronMenu.ts index 540326346edf8..873281685054d 100644 --- a/apps/desktop/src/electron/ElectronMenu.ts +++ b/apps/desktop/src/electron/ElectronMenu.ts @@ -168,7 +168,8 @@ export const make = Effect.gen(function* () { } const itemOption: Electron.MenuItemConstructorOptions = { - label: item.label, + // Electron reads a single & as a mnemonic marker and drops it. + label: item.label.replaceAll("&", "&&"), enabled: !item.disabled, ...(typeof item.checked === "boolean" ? { type: "checkbox", checked: item.checked } : {}), }; From 0ee3a92b7e47846e6ec26c5f2bcd52fe4755ec64 Mon Sep 17 00:00:00 2001 From: steven-salinas <71524634+steven-salinas@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:13:38 -0500 Subject: [PATCH 222/324] fix(forgejo): follow Markdown pull request templates (#41095) Co-authored-by: Julius Marminge --- .../server/ForgejoSourceControlProvider.ts | 8 +- .../forgejoChangeRequestTemplate.test.ts | 100 ++++++++++++++++++ .../server/forgejoChangeRequestTemplate.ts | 63 +++++++++++ 3 files changed, 170 insertions(+), 1 deletion(-) create mode 100644 packages/source-control-forgejo/src/server/forgejoChangeRequestTemplate.test.ts create mode 100644 packages/source-control-forgejo/src/server/forgejoChangeRequestTemplate.ts diff --git a/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.ts b/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.ts index 7b6e475f99152..1c088a58e8876 100644 --- a/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.ts +++ b/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.ts @@ -24,6 +24,7 @@ import { unknownRemoteProvider, } from "@t3tools/source-control-core/shared/definition"; import { ForgejoPullRequestSchema, toForgejoChangeRequest } from "./forgejoPullRequests.ts"; +import * as ForgejoChangeRequestTemplate from "./forgejoChangeRequestTemplate.ts"; const isForgejoCliError = Schema.is(ForgejoCli.ForgejoCliError); @@ -303,7 +304,7 @@ interface UnfilteredPulls { export const make = Effect.gen(function* () { const cli = yield* ForgejoCli.ForgejoCli; const fs = yield* FileSystem.FileSystem; - const { process } = yield* SourceControlHost.SourceControlHost; + const { git, process } = yield* SourceControlHost.SourceControlHost; const request = >( input: ForgejoCli.ForgejoApiInput, schema: S, @@ -488,6 +489,11 @@ export const make = Effect.gen(function* () { }, (effect, input) => effect.pipe(mapError("listChangeRequests", input.cwd)), ), + readChangeRequestTemplate: Effect.fn("ForgejoSourceControlProvider.readChangeRequestTemplate")( + function ({ cwd, treeish }) { + return ForgejoChangeRequestTemplate.detect(cwd, treeish, git.execute); + }, + ), getChangeRequest: Effect.fn("ForgejoSourceControlProvider.getChangeRequest")(function (input) { return getPull(input).pipe( Effect.map(toForgejoChangeRequest), diff --git a/packages/source-control-forgejo/src/server/forgejoChangeRequestTemplate.test.ts b/packages/source-control-forgejo/src/server/forgejoChangeRequestTemplate.test.ts new file mode 100644 index 0000000000000..87f27e315406c --- /dev/null +++ b/packages/source-control-forgejo/src/server/forgejoChangeRequestTemplate.test.ts @@ -0,0 +1,100 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost"; +import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; + +import * as ForgejoCli from "./ForgejoCli.ts"; +import * as ForgejoSourceControlProvider from "./ForgejoSourceControlProvider.ts"; + +const templateRepository = Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const { git } = yield* SourceControlHost.SourceControlHost; + const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-forgejo-pr-template-" }); + const runGit = (args: ReadonlyArray) => + git.execute({ operation: "forgejoChangeRequestTemplate.test.git", cwd, args }); + yield* runGit(["init", "--initial-branch=main", "--template="]); + yield* runGit(["config", "user.email", "test@example.com"]); + yield* runGit(["config", "user.name", "Test User"]); + const provider = yield* ForgejoSourceControlProvider.make; + + return { + runGit, + writeTemplate: (relativePath: string, body: string) => + Effect.gen(function* () { + const file = path.join(cwd, relativePath); + yield* fs.makeDirectory(path.dirname(file), { recursive: true }); + yield* fs.writeFileString(file, body); + }), + commit: Effect.gen(function* () { + yield* runGit(["add", "-A"]); + yield* runGit(["commit", "--allow-empty", "-m", "Set pull request template"]); + }), + read: (treeish: string) => + provider.readChangeRequestTemplate?.({ cwd, treeish }) ?? Effect.succeedNone, + }; +}); + +const testLayer = Layer.mergeAll( + TestSourceControlHost.layerWithRealGit(), + Layer.mock(ForgejoCli.ForgejoCli)({}), + NodeServices.layer, +); + +it.live("reads the Gitea template committed to the target branch", () => + Effect.gen(function* () { + const repo = yield* templateRepository; + yield* repo.commit; + yield* repo.runGit(["branch", "feature"]); + yield* repo.writeTemplate(".gitea/pull_request_template.md", "## Expected on the PR"); + yield* repo.commit; + yield* repo.runGit(["checkout", "feature"]); + yield* repo.writeTemplate(".gitea/pull_request_template.md", "## Working tree only"); + + assert.deepStrictEqual(yield* repo.read("main"), Option.some("## Expected on the PR")); + assert.deepStrictEqual(yield* repo.read("HEAD"), Option.none()); + }).pipe(Effect.scoped, Effect.provide(testLayer)), +); + +it.live("uses the first non-empty Markdown template in Forgejo's lookup order", () => + Effect.gen(function* () { + const repo = yield* templateRepository; + yield* repo.writeTemplate("pull_request_template.md", " \n"); + yield* repo.writeTemplate(".forgejo/PULL_REQUEST_TEMPLATE.md", "## Forgejo"); + yield* repo.writeTemplate(".gitea/pull_request_template.md", "## Gitea"); + yield* repo.commit; + assert.deepStrictEqual(yield* repo.read("HEAD"), Option.some("## Forgejo")); + + yield* repo.writeTemplate("pull_request_template.md", "## Root"); + yield* repo.commit; + assert.deepStrictEqual(yield* repo.read("HEAD"), Option.some("## Root")); + }).pipe(Effect.scoped, Effect.provide(testLayer)), +); + +it.live("rejects a committed template symlink and caps the fallback blob", () => + Effect.gen(function* () { + const repo = yield* templateRepository; + const fallback = "x".repeat(9_000); + yield* repo.writeTemplate(".github/pull_request_template.md", fallback); + yield* repo.writeTemplate("link-target", "README.md"); + yield* repo.commit; + const linkBlob = yield* repo.runGit(["rev-parse", "HEAD:link-target"]); + yield* repo.runGit([ + "update-index", + "--add", + "--cacheinfo", + `120000,${linkBlob.stdout.trim()},pull_request_template.md`, + ]); + yield* repo.runGit(["commit", "-m", "Record a template symlink"]); + + assert.deepStrictEqual( + yield* repo.read("HEAD"), + Option.some(`${fallback.slice(0, 8_000)}\n\n[truncated]`), + ); + }).pipe(Effect.scoped, Effect.provide(testLayer)), +); diff --git a/packages/source-control-forgejo/src/server/forgejoChangeRequestTemplate.ts b/packages/source-control-forgejo/src/server/forgejoChangeRequestTemplate.ts new file mode 100644 index 0000000000000..0ffbc33956b7d --- /dev/null +++ b/packages/source-control-forgejo/src/server/forgejoChangeRequestTemplate.ts @@ -0,0 +1,63 @@ +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; + +import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost"; + +// Forgejo's Markdown lookup order also preserves Gitea's root, .gitea, .github order. +const TEMPLATE_PATHS = ["", ".forgejo/", ".gitea/", ".github/", "docs/"].flatMap((directory) => [ + `${directory}PULL_REQUEST_TEMPLATE.md`, + `${directory}pull_request_template.md`, +]); +const TEMPLATE_MAX_BYTES = 8_000; +const TREE_LIST_MAX_BYTES = 100_000; +const TRUNCATION_MARKER = "[truncated]"; + +type ExecuteGit = SourceControlHost.SourceControlHost["Service"]["git"]["execute"]; + +export const detect = Effect.fn("forgejoChangeRequestTemplate.detect")( + function* (cwd: string, treeish: string, executeGit: ExecuteGit) { + const listing = yield* executeGit({ + operation: "forgejoChangeRequestTemplate.listTemplates", + cwd, + args: ["ls-tree", "-z", "--full-tree", treeish, "--", ...TEMPLATE_PATHS], + maxOutputBytes: TREE_LIST_MAX_BYTES, + appendTruncationMarker: true, + }); + if (listing.stdoutTruncated) { + return Option.none(); + } + + // Read only regular blobs from the target tree, including when the worktree has a symlink. + const objectsByPath = new Map(); + for (const record of listing.stdout.split("\0")) { + const entry = /^100(?:644|755) blob ([0-9a-f]{40,64})\t(.+)$/.exec(record); + if (entry?.[1] && entry[2]) { + objectsByPath.set(entry[2], entry[1]); + } + } + + for (const path of TEMPLATE_PATHS) { + const objectId = objectsByPath.get(path); + if (!objectId) { + continue; + } + const blob = yield* executeGit({ + operation: "forgejoChangeRequestTemplate.readTemplate", + cwd, + args: ["cat-file", "blob", objectId], + maxOutputBytes: TEMPLATE_MAX_BYTES, + appendTruncationMarker: true, + }); + const template = blob.stdout.trim(); + if (template.length > 0) { + return Option.some( + blob.stdoutTruncated && !template.endsWith(TRUNCATION_MARKER) + ? `${template}\n\n${TRUNCATION_MARKER}` + : template, + ); + } + } + return Option.none(); + }, + Effect.orElseSucceed(() => Option.none()), +); From 6ba17d97a19021a96bfa648b4534bbc561f4a606 Mon Sep 17 00:00:00 2001 From: SSH Date: Sun, 22 Nov 2026 18:16:31 -0500 Subject: [PATCH 223/324] fix(claude): show steer replies and progress lines written as thinking (#41085) Co-authored-by: Julius Marminge --- .../Adapters/ClaudeAdapterV2.test.ts | 86 +++++++++++++++++++ .../Adapters/ClaudeAdapterV2.ts | 18 ++-- 2 files changed, 95 insertions(+), 9 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 62139c5a91fdc..a4aea2ff1ffa9 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -8464,6 +8464,92 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + // Default display sends the first pre-tool thinking block empty; a blank update is never promoted. + const update = "Found it: the memory file is the cause."; + it.effect.each([ + { + model: "claude-opus-5-5", + texts: ["", update], + expected: ["assistant_message"], + shown: [update], + }, + { model: "claude-opus-5", texts: ["", update], expected: ["reasoning"], shown: [update] }, + { + model: "claude-opus-5-5", + texts: ["Planning the check", " \n "], + expected: ["reasoning", "reasoning"], + }, + ] as ReadonlyArray<{ + readonly model: string; + readonly texts: ReadonlyArray; + readonly expected: ReadonlyArray; + readonly shown?: ReadonlyArray; + }>)( + "shows $model thinking $texts before a tool call as $expected", + ({ model, texts, expected, shown }) => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make(`thinking-before-tool-${model}`), + text: "Check the file", + attachments: [], + }), + ); + const snapshot = (uuid: string, content: ReadonlyArray>) => + claudeSdkFrame({ + type: "assistant", + uuid, + session_id: WAKE_NATIVE_SESSION, + parent_tool_use_id: null, + message: { id: "reply-message", model, content }, + }); + const frames = [ + ...texts.map((thinking, index) => + snapshot(`thinking-snapshot-${index}`, [ + { type: "thinking", thinking, signature: "sig" }, + ]), + ), + snapshot("tool-snapshot", [ + { type: "tool_use", id: "tool-1", name: "Bash", input: { command: "ls" } }, + ]), + makeResultFrame({ uuid: "tool-result", result: "" }), + ]; + for (const frame of frames) yield* Queue.offer(harness.sdkMessages, frame); + yield* Queue.take(harness.terminalReceipts); + const latest = new Map( + harness.events.flatMap((event) => + event.type === "turn_item.updated" && + (event.turnItem.type === "reasoning" || event.turnItem.type === "assistant_message") + ? [[event.turnItem.id, event.turnItem] as const] + : [], + ), + ); + const items = [...latest.values()]; + assert.deepEqual( + items.map((item) => item.type), + [...expected], + ); + assert.deepEqual( + items.map((item) => item.text), + [...(shown ?? texts)], + ); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + describe("a model change after a Claude Code update", () => { /** An install as the Claude installer lays it out: one file per version and a link. */ const makeInstall = Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 30243178fce41..a4dc7c5006a8d 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -2690,7 +2690,7 @@ function textFromClaudeContent(content: SDKAssistantMessage["message"]["content" return content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join(""); } -// Claude 5.1+ emits at most one pre-tool text block as thinking; treat only a second consecutive thinking block as text. +// Claude 5.1+ emits pre-tool text as thinking; treat a second thinking block as text (the first may be empty in default display). function claudeWritesUpdatesAsThinking(model: string): boolean { const match = /claude-[a-z]+-(\d+)(?:-(\d{1,2}))?(?!\d)/u.exec(model); if (match === null) return false; @@ -11225,6 +11225,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( if ( block.type === "tool_use" && update !== null && + update.text.trim() !== "" && update.messageId === message.message.id && update.followsThinking && claudeWritesUpdatesAsThinking(message.message.model) @@ -11249,14 +11250,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( emitEmpty: false, }); const previous = context.reasoning.lastThinking; - context.reasoning.lastThinking = completedText.trim() - ? { - messageId: message.message.id, - itemId, - text: completedText, - followsThinking: previous !== null && previous.messageId === message.message.id, - } - : null; + // Empty thinking from default display still precedes a pre-tool update. + context.reasoning.lastThinking = { + messageId: message.message.id, + itemId, + text: completedText, + followsThinking: previous !== null && previous.messageId === message.message.id, + }; } // A repeated snapshot frame must not re-emit streamed text under its uuid. if (streamedSnapshotReply !== null && unstreamedSnapshotText.join("").length === 0) { From fb23f12f1fb1895c1e14441f797a9da6ae61e75e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 15:17:46 -0800 Subject: [PATCH 224/324] feat(server): outside agents poll and stream milestones as MCP events (#40774) --- apps/server/src/mcp/McpHttpServer.ts | 44 +- apps/server/src/mcp/McpInvocationContext.ts | 7 + .../src/milestones/MilestoneEvents.test.ts | 303 ++ apps/server/src/milestones/MilestoneEvents.ts | 82 + .../src/milestones/MilestoneHub.test.ts | 120 + apps/server/src/milestones/MilestoneHub.ts | 230 ++ .../OrchestrationMilestones.test.ts | 257 ++ .../src/milestones/OrchestrationMilestones.ts | 244 ++ apps/server/src/server.ts | 9 + docs/user/outside-agents.md | 8 + packages/contracts/src/index.ts | 1 + packages/contracts/src/milestones.ts | 120 + patches/effect@4.1.5.patch | 2479 +++++++++++++++++ pnpm-lock.yaml | 517 ++-- pnpm-workspace.yaml | 2 + 15 files changed, 4163 insertions(+), 260 deletions(-) create mode 100644 apps/server/src/milestones/MilestoneEvents.test.ts create mode 100644 apps/server/src/milestones/MilestoneEvents.ts create mode 100644 apps/server/src/milestones/MilestoneHub.test.ts create mode 100644 apps/server/src/milestones/MilestoneHub.ts create mode 100644 apps/server/src/milestones/OrchestrationMilestones.test.ts create mode 100644 apps/server/src/milestones/OrchestrationMilestones.ts create mode 100644 packages/contracts/src/milestones.ts create mode 100644 patches/effect@4.1.5.patch diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index fa04f45d39062..ff55a2ea5459c 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -16,8 +16,9 @@ import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; import type * as Types from "effect/Types"; import { AiError, McpProtocol, McpSchema, McpServer, Tool, Toolkit } from "effect/ai"; -import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http"; +import { HttpBody, HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http"; import { + AuthSessionId, DeviceToolError, OrchestratorMcpFailure, PreviewAutomationError, @@ -30,10 +31,12 @@ import { import packageJson from "../../package.json" with { type: "json" }; import { parseBearerToken } from "../auth/EnvironmentAuth.ts"; +import * as SessionStore from "../auth/SessionStore.ts"; import * as ServerConfig from "../config.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as DeviceService from "../device/DeviceService.ts"; import * as HtmlRender from "../htmlRender/HtmlRender.ts"; +import * as MilestoneEvents from "../milestones/MilestoneEvents.ts"; import * as ThreadCommandExecutor from "../orchestration-v2/ThreadCommandExecutor.ts"; import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; @@ -290,6 +293,27 @@ const makeMcpAuthMiddleware = Effect.gen(function* () { ); const pullRequests = yield* Effect.serviceOption(PullRequestService.PullRequestService); const projections = yield* Effect.serviceOption(ProjectionStore.ProjectionStoreV2); + const sessions = yield* Effect.serviceOption(SessionStore.SessionStore); + // Auth runs once per request, so a response that streams on, such as `events/stream`, ends + // when the outside client's session is revoked or expires. + const endWithSession = ( + response: HttpServerResponse.HttpServerResponse, + client: McpInvocationContext.McpClientCaller | undefined, + ) => { + const body = response.body; + if (client === undefined || Option.isNone(sessions) || body._tag !== "Stream") return response; + const invalidated = sessions.value + .awaitInvalidation(AuthSessionId.make(client.sessionId)) + .pipe(Effect.ignore); + return HttpServerResponse.setBody( + response, + HttpBody.stream( + Stream.interruptWhen(body.stream, invalidated), + body.contentType, + body.contentLength, + ), + ); + }; // Every request reads it, and a remote added mid-thread shows the tools within a minute. const forgeOfThread = yield* Cache.make({ capacity: 1_000, @@ -363,6 +387,7 @@ const makeMcpAuthMiddleware = Effect.gen(function* () { return yield* httpEffect.pipe( Effect.provideService(McpInvocationContext.McpInvocationContext, admitted), Effect.map(normalizeMcpHttpResponse), + Effect.map((response) => endWithSession(response, admitted.client)), Effect.map((response) => linkExpiresAt === undefined ? response @@ -1469,4 +1494,19 @@ export const layerToolSearch = Layer.mergeAll( layerDeferredListing, ).pipe(Layer.provide(layerToolExposure)); -export const layer = layerMcpTransport(Layer.mergeAll(layerTools, layerToolSearch)); +/** + * Milestones as MCP events (SEP-3415) for outside clients to poll or stream. Protocol-level, so no + * thread lists them. + */ +export const layerMilestoneEvents = Layer.effectDiscard( + Effect.gen(function* () { + const annotations = Context.make(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromThreads); + for (const options of yield* MilestoneEvents.make) { + yield* McpServer.registerEvent({ ...options, annotations }); + } + }), +); + +export const layer = layerMcpTransport( + Layer.mergeAll(layerTools, layerToolSearch, layerMilestoneEvents), +); diff --git a/apps/server/src/mcp/McpInvocationContext.ts b/apps/server/src/mcp/McpInvocationContext.ts index bfc35be9baadd..f1a070e86b9e3 100644 --- a/apps/server/src/mcp/McpInvocationContext.ts +++ b/apps/server/src/mcp/McpInvocationContext.ts @@ -216,6 +216,13 @@ export const hiddenWithoutBackgroundWait = (): boolean => { ); }; +/** `McpSchema.EnabledWhen` for tools only a client outside a thread drives, such as the CLI. */ +export const hiddenFromThreads = (): boolean => { + const fiber = Fiber.getCurrent(); + const scope = fiber && Context.getOrUndefined(fiber.context, McpInvocationContext); + return scope?.thread === undefined; +}; + /** `McpSchema.EnabledWhen` for tools that only serve links, hidden while the beta is off. */ export const hiddenWhileLinksOff = (): boolean => { const fiber = Fiber.getCurrent(); diff --git a/apps/server/src/milestones/MilestoneEvents.test.ts b/apps/server/src/milestones/MilestoneEvents.test.ts new file mode 100644 index 0000000000000..bdf102b4dce6f --- /dev/null +++ b/apps/server/src/milestones/MilestoneEvents.test.ts @@ -0,0 +1,303 @@ +import { NodeHttpServer } from "@effect/platform-node"; +import { expect, it } from "@effect/vitest"; +import { + EnvironmentId, + type MilestoneEvent, + MilestoneId, + ProjectId, + ProviderInstanceId, + RunId, + ThreadId, +} from "@t3tools/contracts"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Queue from "effect/Queue"; +import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; +import { HttpBody, HttpClient, HttpRouter } from "effect/http"; + +import * as SessionStore from "../auth/SessionStore.ts"; +import * as McpHttpServer from "../mcp/McpHttpServer.ts"; +import type * as McpInvocationContext from "../mcp/McpInvocationContext.ts"; +import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import * as MilestoneHub from "./MilestoneHub.ts"; + +const environmentId = EnvironmentId.make("environment-milestone-events-test"); +const clientToken = "clientTokenWithoutDots"; +const threadToken = "threadTokenWithoutDots"; +const scopes: Record = { + [clientToken]: { + environmentId, + requestNamespace: "client-session", + thread: undefined, + client: { sessionId: "client-session", label: "Bot", access: "read-only" }, + capabilities: new Set(["orchestration"]), + issuedAt: 1, + }, + [threadToken]: { + environmentId, + requestNamespace: "provider-session", + thread: { + threadId: ThreadId.make("thread-agent"), + providerSessionId: "provider-session", + providerInstanceId: ProviderInstanceId.make("codex"), + }, + client: undefined, + capabilities: new Set(["orchestration"]), + issuedAt: 1, + }, +}; + +const settled = ( + id: string, + options: { readonly project?: string; readonly at?: string } = {}, +): MilestoneEvent => ({ + id: MilestoneId.make(id), + type: "thread.run_settled", + occurredAt: options.at ?? "1970-01-01T00:00:00.000Z", + projectId: ProjectId.make(options.project ?? "project:a"), + threadId: ThreadId.make(`thread:${id}`), + parentThreadId: null, + actor: { type: "agent" }, + isSubagentChild: false, + runId: RunId.make(`run:${id}`), + outcome: "completed", +}); + +type JsonRpcResponse = { + readonly result?: Record; + readonly error?: { readonly code: number; readonly data?: unknown }; +}; + +const serve = Effect.gen(function* () { + const revoked = yield* Deferred.make(); + yield* HttpRouter.serve( + McpHttpServer.layerMcpTransport(McpHttpServer.layerMilestoneEvents).pipe( + Layer.provide(ServerSettings.layerTest()), + Layer.provide( + Layer.mock(SessionStore.SessionStore)({ + cookieName: "t3-session", + legacyCookieName: undefined, + awaitInvalidation: (sessionId) => + sessionId === "client-session" ? Deferred.await(revoked) : Effect.never, + }), + ), + Layer.provide( + Layer.mock(McpSessionRegistry.McpSessionRegistry)({ + resolve: (presented) => + Effect.succeed(scopes[presented] as McpInvocationContext.McpThreadInvocationScope), + }), + ), + ), + { disableListenLog: true, disableLogger: true }, + ).pipe(Layer.build); + const http = yield* HttpClient.HttpClient; + const post = ( + method: string, + params: Record = {}, + options: { readonly token?: string; readonly name?: string | null; readonly id?: number } = {}, + ) => { + const name = options.name === undefined ? params.name : options.name; + return http.post("/mcp", { + headers: { + accept: "application/json, text/event-stream", + authorization: `Bearer ${options.token ?? clientToken}`, + "mcp-method": method, + "mcp-protocol-version": "2026-07-28", + ...(typeof name === "string" ? { "mcp-name": name } : {}), + }, + body: HttpBody.text( + JSON.stringify({ + jsonrpc: "2.0", + id: options.id ?? 1, + method, + params: { + ...params, + _meta: { + "io.modelcontextprotocol/protocolVersion": "2026-07-28", + "io.modelcontextprotocol/clientCapabilities": { + extensions: { "io.modelcontextprotocol/events": {} }, + }, + "io.modelcontextprotocol/clientInfo": { name: "bot", version: "1.0.0" }, + }, + }, + }), + "application/json", + ), + }); + }; + const call = (...args: Parameters) => + post(...args).pipe( + Effect.flatMap((response) => response.json), + Effect.map((body) => body as JsonRpcResponse), + ); + const poll = (args: Record) => + call("events/poll", { name: "thread.run_settled", ...args }).pipe( + Effect.map(({ result }) => ({ + cursor: result!.cursor as string, + truncated: result!.truncated as boolean, + hasMore: result!.hasMore as boolean, + ids: (result!.events as ReadonlyArray<{ eventId: string }>).map((event) => event.eventId), + })), + ); + const stream = (args: Record, id = 7) => + post("events/stream", { name: "thread.run_settled", ...args }, { id }).pipe( + Effect.flatMap((response) => + response.stream.pipe( + Stream.decodeText, + Stream.splitLines, + Stream.filter((line) => line.startsWith("data: ")), + Stream.map( + (line) => + JSON.parse(line.slice("data: ".length)) as { + readonly method: string; + readonly params: Record; + }, + ), + Stream.toQueue({ capacity: "unbounded" }), + ), + ), + ); + return { post, call, poll, stream, revoke: Deferred.succeed(revoked, undefined) }; +}); + +const layerTest = Layer.mergeAll(MilestoneHub.layer, NodeHttpServer.layerTest); + +it.effect("advertises the extension and lists each milestone type to outside clients only", () => + Effect.gen(function* () { + const { call } = yield* serve; + const discovered = yield* call("server/discover"); + expect(discovered.result!.capabilities.extensions).toEqual({ + "io.modelcontextprotocol/events": {}, + }); + + const { events } = (yield* call("events/list")).result!; + expect(events).toHaveLength(6); + const settledType = events.find( + (event: { name: string }) => event.name === "thread.run_settled", + ); + expect(settledType.delivery).toEqual(["poll", "push"]); + expect(Object.keys(settledType.inputSchema.properties)).toEqual([ + "projectIds", + "threadIds", + "includeSubagentChildren", + ]); + expect(settledType.payloadSchema.properties.outcome).toBeDefined(); + expect((yield* call("events/list", {}, { token: threadToken })).result!.events).toEqual([]); + }).pipe(Effect.scoped, Effect.provide(layerTest)), +); + +it.effect("polls from now, then pages forward and says when a cursor fell behind", () => + Effect.gen(function* () { + const hub = yield* MilestoneHub.MilestoneHub; + const { poll } = yield* serve; + yield* hub.publish(settled("before")); + + // A null cursor starts from now: nothing earlier is replayed. + const bootstrap = yield* poll({ cursor: null }); + expect(bootstrap).toMatchObject({ ids: [], truncated: false, hasMore: false }); + + yield* hub.publish(settled("a")); + yield* hub.publish(settled("b", { project: "project:b" })); + yield* hub.publish(settled("c")); + const first = yield* poll({ + cursor: bootstrap.cursor, + arguments: { projectIds: ["project:a"] }, + maxEvents: 1, + }); + expect(first).toMatchObject({ ids: ["a"], hasMore: true, truncated: false }); + const rest = yield* poll({ cursor: first.cursor, arguments: { projectIds: ["project:a"] } }); + expect(rest).toMatchObject({ ids: ["c"], hasMore: false }); + expect(yield* poll({ cursor: rest.cursor })).toMatchObject({ ids: [] }); + + // A cursor from before a restart replays what is kept, and says some may be missing. + expect(yield* poll({ cursor: "previous-boot.3" })).toMatchObject({ + ids: ["before", "a", "b", "c"], + truncated: true, + }); + yield* TestClock.adjust("10 minutes"); + yield* hub.publish(settled("fresh", { at: "1970-01-01T00:10:00.000Z" })); + expect(yield* poll({ cursor: bootstrap.cursor, maxAgeMs: 60_000 })).toMatchObject({ + ids: ["fresh"], + truncated: true, + }); + }).pipe(Effect.scoped, Effect.provide(layerTest)), +); + +it.effect("rejects a mismatched Mcp-Name, an unknown event and webhook delivery", () => + Effect.gen(function* () { + const { post, call } = yield* serve; + const params = { name: "thread.run_settled", cursor: null }; + const missing = yield* post("events/poll", params, { name: null }); + expect(missing.status).toBe(400); + expect(((yield* missing.json) as JsonRpcResponse).error?.code).toBe(-32020); + const mismatched = yield* post("events/poll", params, { name: "thread.needs_input" }); + expect(mismatched.status).toBe(400); + + expect((yield* call("events/poll", { name: "nope", cursor: null })).error).toMatchObject({ + code: -32023, + data: { kind: "event" }, + }); + expect( + (yield* call("events/subscribe", { + name: "thread.run_settled", + delivery: { mode: "webhook", url: "https://example.com/hook", secret: "whsec_x" }, + })).error, + ).toMatchObject({ code: -32026, data: { feature: "deliveryMode", value: "webhook" } }); + }).pipe(Effect.scoped, Effect.provide(layerTest)), +); + +it.effect("streams live milestones after active, replays from a cursor and sends heartbeats", () => + Effect.gen(function* () { + const hub = yield* MilestoneHub.MilestoneHub; + const { stream } = yield* serve; + yield* hub.publish(settled("a")); + + const live = yield* stream({ cursor: null, heartbeatMs: 5_000 }, 7); + const active = yield* Queue.take(live); + expect(active).toMatchObject({ + method: "notifications/events/active", + params: { truncated: false, heartbeatMs: 5_000 }, + }); + expect(active.params._meta["io.modelcontextprotocol/subscriptionId"]).toBe(7); + + yield* hub.publish(settled("b", { project: "project:b" })); + const event = yield* Queue.take(live); + expect(event).toMatchObject({ + method: "notifications/events/event", + params: { + eventId: "b", + name: "thread.run_settled", + data: { id: "b", projectId: "project:b" }, + _meta: { "io.modelcontextprotocol/subscriptionId": 7 }, + }, + }); + + // The heartbeat is due 5 seconds after the last message, however late the loop reads the clock. + yield* TestClock.adjust("5 seconds"); + expect(yield* Queue.take(live)).toMatchObject({ + method: "notifications/events/heartbeat", + params: { cursor: event.params.cursor }, + }); + + const replay = yield* stream({ cursor: "previous-boot.1" }, 8); + expect(yield* Queue.takeN(replay, 3)).toMatchObject([ + { method: "notifications/events/active", params: { truncated: true } }, + { method: "notifications/events/event", params: { eventId: "a" } }, + { method: "notifications/events/event", params: { eventId: "b" } }, + ]); + }).pipe(Effect.scoped, Effect.provide(layerTest)), +); + +it.effect("ends an open stream when the client's session is revoked", () => + Effect.gen(function* () { + const { stream, revoke } = yield* serve; + const live = yield* stream({ cursor: null }); + expect(yield* Queue.take(live)).toMatchObject({ method: "notifications/events/active" }); + + yield* revoke; + expect((yield* Effect.exit(Queue.take(live)))._tag).toBe("Failure"); + }).pipe(Effect.scoped, Effect.provide(layerTest)), +); diff --git a/apps/server/src/milestones/MilestoneEvents.ts b/apps/server/src/milestones/MilestoneEvents.ts new file mode 100644 index 0000000000000..5b07d64b3aa59 --- /dev/null +++ b/apps/server/src/milestones/MilestoneEvents.ts @@ -0,0 +1,82 @@ +import { + type MilestoneEvent as MilestoneEventValue, + MilestoneEvent, + ProjectId, + ThreadId, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; +import type { McpServer } from "effect/ai"; + +import * as MilestoneHub from "./MilestoneHub.ts"; + +// Matches the hub's buffer, so a poll can drain everything it keeps at once. +const MAX_EVENTS = 1_000; +const DEFAULT_EVENTS = 100; + +const Parameters = Schema.Struct({ + projectIds: Schema.optional(Schema.Array(ProjectId)), + threadIds: Schema.optional(Schema.Array(ThreadId)), + includeSubagentChildren: Schema.optional( + Schema.Boolean.annotate({ description: "Also subagent threads." }), + ), +}); + +const DESCRIPTIONS: Record = { + "thread.run_settled": "A thread's turn ended: completed, failed, interrupted or cancelled.", + "thread.needs_input": "An agent waits on a person to answer a question or approve an action.", + "thread.input_resolved": "A question or approval an agent waited on was answered, or lapsed.", + "thread.guest_request": "A guest on a shared thread asked for something.", + "thread.guest_request_resolved": "A guest's request was sent, dismissed, or its link closed.", + "pr.watch_wake": "A watched pull request changed and woke its thread.", +}; + +const occurrence = ({ event }: MilestoneHub.PositionedMilestone) => ({ + eventId: event.id, + timestamp: event.occurredAt, + data: event, +}); + +/** + * Each milestone type as an MCP event type (SEP-3415), for outside clients to poll or stream. + * Cursors are the hub's, so a client that was away catches up on what the hub still keeps. + */ +export const make = Effect.gen(function* () { + const hub = yield* MilestoneHub.MilestoneHub; + return MilestoneEvent.members.map((payload) => { + const type = payload.fields.type.literal; + const filterOf = (args: typeof Parameters.Type) => ({ ...args, types: [type] }); + return { + name: type, + description: DESCRIPTIONS[type], + parameters: Parameters, + payload, + poll: (args, request) => + hub + .read({ + cursor: request.cursor, + maxAgeMs: request.maxAgeMs, + filter: filterOf(args), + limit: Math.min(request.maxEvents ?? DEFAULT_EVENTS, MAX_EVENTS), + }) + .pipe(Effect.map((page) => ({ ...page, events: page.events.map(occurrence) }))), + stream: (args, request) => + hub + .follow({ cursor: request.cursor, maxAgeMs: request.maxAgeMs, filter: filterOf(args) }) + .pipe( + Effect.map(({ cursor, truncated, items }) => ({ + cursor, + truncated, + items: items.pipe( + Stream.map((item): McpServer.EventStreamItem => + item._tag === "Milestone" + ? { _tag: "Event", cursor: item.cursor, ...occurrence(item) } + : item, + ), + ), + })), + ), + } satisfies McpServer.EventOptions; + }); +}); diff --git a/apps/server/src/milestones/MilestoneHub.test.ts b/apps/server/src/milestones/MilestoneHub.test.ts new file mode 100644 index 0000000000000..0361c81f4f7e0 --- /dev/null +++ b/apps/server/src/milestones/MilestoneHub.test.ts @@ -0,0 +1,120 @@ +import { assert, it } from "@effect/vitest"; +import { type MilestoneEvent, MilestoneId, ProjectId, RunId, ThreadId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; + +import * as MilestoneHub from "./MilestoneHub.ts"; + +const settled = ( + id: string, + options: { readonly child?: boolean; readonly project?: string } = {}, +): MilestoneEvent => ({ + id: MilestoneId.make(id), + type: "thread.run_settled", + occurredAt: "2026-11-20T00:00:00.000Z", + projectId: ProjectId.make(options.project ?? "project:a"), + threadId: ThreadId.make(`thread:${id}`), + parentThreadId: options.child === true ? ThreadId.make("thread:parent") : null, + actor: { type: "agent" }, + isSubagentChild: options.child === true, + runId: RunId.make(`run:${id}`), + outcome: "completed", +}); +const ids = (events: Iterable) => [...events].map((event) => event.id); + +it.effect("fans out to every subscriber, muting subagent children unless asked for", () => + Effect.gen(function* () { + const hub = yield* MilestoneHub.MilestoneHub; + const muted = yield* hub.subscribe(); + const everything = yield* hub.subscribe({ includeSubagentChildren: true }); + const projectB = yield* hub.subscribe({ projectIds: [ProjectId.make("project:b")] }); + + yield* hub.publish(settled("a")); + yield* hub.publish(settled("child", { child: true })); + // A repeat of an id is the same milestone. + yield* hub.publish(settled("a")); + yield* hub.publish(settled("b", { project: "project:b" })); + + assert.deepStrictEqual(ids(yield* Stream.runCollect(Stream.take(muted, 2))), ["a", "b"]); + assert.deepStrictEqual(ids(yield* Stream.runCollect(Stream.take(everything, 3))), [ + "a", + "child", + "b", + ]); + assert.deepStrictEqual(ids(yield* Stream.runCollect(Stream.take(projectB, 1))), ["b"]); + assert.deepStrictEqual(ids((yield* hub.recent()).events), ["a", "b"]); + }).pipe(Effect.scoped, Effect.provide(MilestoneHub.layer)), +); + +it.effect("pages forward from a kept id and says when the answer is cut short", () => + Effect.gen(function* () { + const hub = yield* MilestoneHub.MilestoneHub; + for (let index = 0; index < 1_005; index++) yield* hub.publish(settled(`e${index}`)); + + const after = yield* hub.recent({ sinceId: MilestoneId.make("e1000"), limit: 3 }); + assert.deepStrictEqual(ids(after.events), ["e1001", "e1002", "e1003"]); + assert.isTrue(after.truncated); + const rest = yield* hub.recent({ sinceId: MilestoneId.make("e1003") }); + assert.deepStrictEqual([ids(rest.events), rest.truncated], [["e1004"], false]); + + // The oldest fell out of the buffer, so a caller that last saw it missed some. + const gone = yield* hub.recent({ sinceId: MilestoneId.make("e2"), limit: 2 }); + assert.deepStrictEqual([ids(gone.events), gone.truncated], [["e1003", "e1004"], true]); + const newest = yield* hub.recent({ limit: 1_000 }); + assert.deepStrictEqual( + [newest.events.length, newest.events[0]?.id, newest.truncated], + [1_000, "e5", false], + ); + }).pipe(Effect.provide(MilestoneHub.layer)), +); + +it.effect("skips expired milestones even when they arrive after newer ones", () => + Effect.gen(function* () { + const hub = yield* MilestoneHub.MilestoneHub; + yield* TestClock.adjust("10 minutes"); + const { cursor } = yield* hub.read({ cursor: null, limit: 1 }); + yield* hub.publish({ ...settled("fresh"), occurredAt: "1970-01-01T00:10:00.000Z" }); + yield* hub.publish({ ...settled("expired"), occurredAt: "1970-01-01T00:08:59.000Z" }); + yield* hub.publish({ ...settled("at-cutoff"), occurredAt: "1970-01-01T00:09:00.000Z" }); + + const first = yield* hub.read({ cursor, maxAgeMs: 60_000, limit: 1 }); + assert.deepStrictEqual(ids(first.events.map(({ event }) => event)), ["fresh"]); + assert.isTrue(first.hasMore); + assert.isTrue(first.truncated); + const rest = yield* hub.read({ cursor: first.cursor, maxAgeMs: 60_000, limit: 1 }); + assert.deepStrictEqual(ids(rest.events.map(({ event }) => event)), ["at-cutoff"]); + assert.isFalse(rest.hasMore); + }).pipe(Effect.provide(MilestoneHub.layer)), +); + +it.effect("a follower's replay ends at the position it checked, past its last match", () => + Effect.gen(function* () { + const hub = yield* MilestoneHub.MilestoneHub; + const { cursor } = yield* hub.read({ cursor: null, limit: 1 }); + yield* hub.publish(settled("a")); + yield* hub.publish(settled("b", { project: "project:b" })); + + const { items } = yield* hub.follow({ + cursor, + filter: { projectIds: [ProjectId.make("project:a")] }, + }); + const [milestone, position] = yield* Stream.runCollect(Stream.take(items, 2)); + assert.strictEqual(milestone?._tag === "Milestone" ? milestone.event.id : undefined, "a"); + assert.strictEqual(position?._tag, "Position"); + assert.strictEqual((yield* hub.read({ cursor: null, limit: 1 })).cursor, position?.cursor); + }).pipe(Effect.scoped, Effect.provide(MilestoneHub.layer)), +); + +it.effect("tells a follower that fell behind the subscriber backlog where its gap is", () => + Effect.gen(function* () { + const hub = yield* MilestoneHub.MilestoneHub; + const { items } = yield* hub.follow({ cursor: null }); + // Published before the follower reads, so the backlog drops the oldest. + for (let index = 0; index < 300; index++) yield* hub.publish(settled(`e${index}`)); + + const [gap, first] = yield* Stream.runCollect(Stream.take(items, 2)); + assert.strictEqual(gap?._tag, "Gap"); + assert.strictEqual(first?._tag === "Milestone" ? first.event.id : undefined, "e44"); + }).pipe(Effect.scoped, Effect.provide(MilestoneHub.layer)), +); diff --git a/apps/server/src/milestones/MilestoneHub.ts b/apps/server/src/milestones/MilestoneHub.ts new file mode 100644 index 0000000000000..c7649fa38cceb --- /dev/null +++ b/apps/server/src/milestones/MilestoneHub.ts @@ -0,0 +1,230 @@ +import { + type MilestoneEvent, + type MilestoneFilter, + type MilestoneId, + milestoneMatches, +} from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as PubSub from "effect/PubSub"; +import type * as Scope from "effect/Scope"; +import * as Stream from "effect/Stream"; + +// Enough for a client that was away for a while to catch up; older news is in the stores. +const KEPT = 1_000; +// Ids outlive the events they name, so a late repeat of an evicted milestone is still one. +const IDS_KEPT = 4 * KEPT; +// A subscriber this far behind loses its oldest milestones, not the server's memory. +const SUBSCRIBER_BACKLOG = 256; +const RECENT_LIMIT = 200; + +/** A milestone and the cursor that reads on after it. */ +export interface PositionedMilestone { + readonly event: MilestoneEvent; + readonly cursor: string; +} + +/** + * Where a cursor read starts. `null` starts from now. A cursor from before a restart or no longer + * kept starts at the oldest kept milestone; `maxAgeMs` skips those older than that. + */ +export interface MilestoneReadOptions { + readonly cursor: string | null; + readonly maxAgeMs?: number | undefined; + readonly filter?: MilestoneFilter | undefined; +} + +/** What a follower reads after its start: a milestone, a position passed without one, or a gap. */ +export type MilestoneFollowItem = + | ({ readonly _tag: "Milestone" } & PositionedMilestone) + | { readonly _tag: "Position"; readonly cursor: string } + | { readonly _tag: "Gap"; readonly cursor: string }; + +export class MilestoneHub extends Context.Service< + MilestoneHub, + { + /** Publishing an id seen before does nothing, so a feeder may repeat itself. */ + readonly publish: (event: MilestoneEvent) => Effect.Effect; + /** + * Milestones published from now on that match `filter`. Subscribed when this runs, so a caller + * catching up subscribes first, then reads `recent`, and drops ids it already has. + */ + readonly subscribe: ( + filter?: MilestoneFilter, + ) => Effect.Effect, never, Scope.Scope>; + /** + * Kept milestones, oldest first: those after `sinceId`, or the newest. `truncated` says the + * answer is incomplete: `sinceId` is no longer kept, or `limit` cut it short. + */ + readonly recent: (options?: { + readonly sinceId?: MilestoneId | undefined; + readonly limit?: number | undefined; + readonly filter?: MilestoneFilter | undefined; + }) => Effect.Effect<{ + readonly events: ReadonlyArray; + readonly truncated: boolean; + }>; + /** + * Matching milestones after a cursor, at most `limit`. `cursor` reads on from there: after the + * last one returned when `hasMore`, otherwise from now. `truncated` says some were skipped. + */ + readonly read: (options: MilestoneReadOptions & { readonly limit: number }) => Effect.Effect<{ + readonly events: ReadonlyArray; + readonly cursor: string; + readonly truncated: boolean; + readonly hasMore: boolean; + }>; + /** The milestones `read` would return, then live ones, each once. */ + readonly follow: (options: MilestoneReadOptions) => Effect.Effect< + { + readonly cursor: string; + readonly truncated: boolean; + readonly items: Stream.Stream; + }, + never, + Scope.Scope + >; + } +>()("t3/milestones/MilestoneHub") {} + +interface Kept { + readonly event: MilestoneEvent; + readonly seq: number; +} + +const make = Effect.gen(function* () { + const pubsub = yield* PubSub.sliding(SUBSCRIBER_BACKLOG); + const kept: Array = []; + const seen = new Set(); + let seq = 0; + // Sequence numbers restart with the server; the epoch tells an old cursor from a new one. + const epoch = (yield* Clock.currentTimeMillis).toString(36); + const cursorAt = (at: number) => `${epoch}.${at}`; + const seqOf = (cursor: string) => { + const [cursorEpoch, at] = cursor.split("."); + const value = Number(at); + return cursorEpoch === epoch && Number.isSafeInteger(value) && value >= 0 && value <= seq + ? value + : undefined; + }; + + const remember = (event: MilestoneEvent) => { + if (seen.has(event.id)) return undefined; + seen.add(event.id); + if (seen.size > IDS_KEPT) seen.delete(seen.values().next().value!); + const entry = { event, seq: ++seq }; + kept.push(entry); + if (kept.length > KEPT) kept.shift(); + return entry; + }; + + // The kept milestones after the cursor, and whether milestones after it were skipped. + const after = (options: MilestoneReadOptions, now: number) => { + if (options.cursor === null) return { entries: [], truncated: false }; + const from = seqOf(options.cursor); + const oldest = kept[0]?.seq ?? seq + 1; + let entries = from === undefined ? kept : kept.filter((entry) => entry.seq > from); + let truncated = from === undefined || from < oldest - 1; + if (options.maxAgeMs !== undefined) { + // Kept in publication order, which `occurredAt` need not follow, so each one is checked. + const floor = now - options.maxAgeMs; + const young = entries.filter((entry) => Date.parse(entry.event.occurredAt) >= floor); + truncated ||= young.length < entries.length; + entries = young; + } + return { entries, truncated }; + }; + + const positioned = (entry: Kept): PositionedMilestone => ({ + event: entry.event, + cursor: cursorAt(entry.seq), + }); + + const subscribe = Effect.fn("MilestoneHub.subscribe")(function* (filter?: MilestoneFilter) { + const subscription = yield* PubSub.subscribe(pubsub); + return Stream.fromSubscription(subscription).pipe( + Stream.map((entry) => entry.event), + Stream.filter((event) => milestoneMatches(event, filter)), + ); + }); + + const recent: MilestoneHub["Service"]["recent"] = Effect.fn("MilestoneHub.recent")(function* ( + options = {}, + ) { + const limit = Math.max(1, Math.min(options.limit ?? RECENT_LIMIT, KEPT)); + const at = + options.sinceId === undefined + ? -1 + : kept.findIndex((entry) => entry.event.id === options.sinceId); + const gap = options.sinceId !== undefined && at === -1; + const matching = kept + .slice(at + 1) + .map((entry) => entry.event) + .filter((event) => milestoneMatches(event, options.filter)); + // Paging forward from a known id; otherwise the newest, as there is no place to start. + const events = + options.sinceId !== undefined && !gap ? matching.slice(0, limit) : matching.slice(-limit); + return yield* Effect.succeed({ events, truncated: gap || events.length < matching.length }); + }); + + const read: MilestoneHub["Service"]["read"] = Effect.fn("MilestoneHub.read")(function* (options) { + const from = after(options, yield* Clock.currentTimeMillis); + const matching = from.entries.filter((entry) => milestoneMatches(entry.event, options.filter)); + const events = matching.slice(0, Math.max(1, options.limit)); + const hasMore = events.length < matching.length; + return { + events: events.map(positioned), + cursor: hasMore ? cursorAt(events.at(-1)!.seq) : cursorAt(seq), + truncated: from.truncated, + hasMore, + }; + }); + + return MilestoneHub.of({ + publish: Effect.fn("MilestoneHub.publish")(function* (event) { + const entry = remember(event); + if (entry === undefined) return; + yield* PubSub.publish(pubsub, entry); + }), + subscribe, + recent, + read, + follow: Effect.fn("MilestoneHub.follow")(function* (options) { + // Subscribed before reading the buffer, so nothing published in between is lost. + const live = Stream.fromSubscription(yield* PubSub.subscribe(pubsub)); + const caught = yield* read({ ...options, limit: KEPT }); + const first = caught.events[0]; + let last = seqOf(caught.cursor)!; + const items = live.pipe( + Stream.flatMap((entry) => { + if (entry.seq <= last) return Stream.empty; + // A follower that fell behind the subscriber backlog lost the milestones in between. + const gap = entry.seq > last + 1; + last = entry.seq; + const item: MilestoneFollowItem = milestoneMatches(entry.event, options.filter) + ? { _tag: "Milestone", ...positioned(entry) } + : { _tag: "Position", cursor: cursorAt(entry.seq) }; + return Stream.fromIterable( + gap ? [{ _tag: "Gap" as const, cursor: cursorAt(entry.seq - 1) }, item] : [item], + ); + }), + ); + return { + // The position before the first replayed milestone, which each one then advances. + cursor: first === undefined ? caught.cursor : cursorAt(seqOf(first.cursor)! - 1), + truncated: caught.truncated, + items: Stream.fromIterable([ + ...caught.events.map((event): MilestoneFollowItem => ({ _tag: "Milestone", ...event })), + // Replay checked past its last match; told after it, so no client skips a replayed one. + ...(first !== undefined && caught.events.at(-1)!.cursor !== caught.cursor + ? [{ _tag: "Position" as const, cursor: caught.cursor }] + : []), + ]).pipe(Stream.concat(items)), + }; + }), + }); +}); + +export const layer = Layer.effect(MilestoneHub, make); diff --git a/apps/server/src/milestones/OrchestrationMilestones.test.ts b/apps/server/src/milestones/OrchestrationMilestones.test.ts new file mode 100644 index 0000000000000..7930b2ab8097b --- /dev/null +++ b/apps/server/src/milestones/OrchestrationMilestones.test.ts @@ -0,0 +1,257 @@ +import { assert, it } from "@effect/vitest"; +import { + CommandId, + EventId, + GuestMessageId, + GuestShareId, + MessageId, + type OrchestrationV2AppThread, + type OrchestrationV2DomainEvent, + type OrchestrationV2Run, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + RuntimeRequestId, + ThreadId, + type ThreadGuestMessage, +} from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; + +import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import { CodexProviderCapabilitiesV2 } from "../orchestration-v2/Adapters/CodexAdapterV2.ts"; +import * as EffectOutbox from "../orchestration-v2/EffectOutbox.ts"; +import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; +import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; +import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts"; +import * as ProviderReplayHarness from "../orchestration-v2/testkit/ProviderReplayHarness.ts"; +import * as MilestoneHub from "./MilestoneHub.ts"; +import * as OrchestrationMilestones from "./OrchestrationMilestones.ts"; + +const instanceId = ProviderInstanceId.make("codex"); +const modelSelection = { instanceId, model: "gpt-5.1-codex" }; +const adapter = { + instanceId, + driver: ProviderDriverKind.make("codex"), + getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2), + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }), + openSession: () => Effect.die("No provider process needed for milestones"), +} as ProviderAdapter.ProviderAdapterV2["Service"]; +const layerDatabase = SqlitePersistence.layerMemory; +const layerTest = OrchestrationMilestones.layer.pipe( + Layer.provideMerge(MilestoneHub.layer), + Layer.provideMerge( + Layer.mergeAll( + layerDatabase, + ProjectionStore.layer.pipe(Layer.provide(layerDatabase)), + EffectOutbox.layer.pipe(Layer.provide(layerDatabase)), + ProviderReplayHarness.layerWithRegistry( + { name: "milestones" }, + ProviderAdapterRegistry.layerFromAdapters([adapter]), + { databaseLayer: layerDatabase, runEffectWorker: false }, + ), + ), + ), +); + +it.effect("tells each thread transition once, with its lineage", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const feeder = yield* OrchestrationMilestones.OrchestrationMilestones; + const hub = yield* MilestoneHub.MilestoneHub; + const parentThreadId = ThreadId.make("thread:milestone-parent"); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("create-milestone-parent"), + threadId: parentThreadId, + projectId: ProjectId.make("project:milestones"), + title: "Parent", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdBy: "user", + creationSource: "web", + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("start-milestone-parent"), + threadId: parentThreadId, + messageId: MessageId.make("message:milestone-parent"), + text: "Delegate the research", + attachments: [], + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + }); + const parentRun = (yield* projections.getThreadProjection(parentThreadId)).runs[0]!; + yield* orchestrator.dispatch({ + type: "delegated_task.request", + commandId: CommandId.make("delegate-milestone-task"), + parentThreadId, + parentRunId: parentRun.id, + parentNodeId: parentRun.rootNodeId!, + task: "Research the sources", + completionWake: "settled_only", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + createdBy: "agent", + creationSource: "mcp", + }); + const childThreadId = (yield* projections.getThreadProjection(parentThreadId)).subagents[0]! + .childThreadId!; + const childRun = (yield* projections.getThreadRecords(childThreadId, ["runs"])).runs[0]!; + const parent = yield* projections.getThread(parentThreadId); + const now = yield* DateTime.now; + const base = (id: string, threadId: ThreadId) => ({ + id: EventId.make(id), + threadId, + occurredAt: now, + }); + const ended = (id: string, run: OrchestrationV2Run, status: OrchestrationV2Run["status"]) => + ({ + ...base(id, run.threadId), + type: "run.updated", + runId: run.id, + payload: { ...run, status, startedAt: now, completedAt: now }, + }) satisfies OrchestrationV2DomainEvent; + const request = (id: string, status: "pending" | "resolved") => + ({ + ...base(id, parentThreadId), + type: "runtime-request.updated", + payload: { + id: RuntimeRequestId.make("request:milestone"), + nodeId: parentRun.rootNodeId!, + providerTurnId: null, + nativeRequestRef: null, + kind: "command", + status, + responseCapability: { type: "message" }, + createdAt: now, + resolvedAt: status === "pending" ? null : now, + }, + }) satisfies OrchestrationV2DomainEvent; + const shareId = GuestShareId.make("share:milestone"); + const guestMessage = (id: string, status: ThreadGuestMessage["status"]) => ({ + id: GuestMessageId.make(id), + text: "Can you also check the docs?", + status, + submittedAt: DateTime.formatIso(now), + }); + const shared = ( + id: string, + messages: ReadonlyArray | null, + ): OrchestrationV2DomainEvent => { + const payload: OrchestrationV2AppThread = { + ...parent, + guestShare: + messages === null + ? null + : { + id: shareId, + host: "tunnel.example", + createdAt: DateTime.formatIso(now), + expiresAt: DateTime.formatIso(now), + guestName: "Sam", + messages, + }, + }; + return { ...base(id, parentThreadId), type: "thread.guest-share-updated", payload }; + }; + const wake = { + ...base("event:wake", parentThreadId), + type: "message.updated", + payload: { + id: MessageId.make("message:pr-wake"), + threadId: parentThreadId, + runId: null, + nodeId: null, + role: "user", + text: "Checks finished on #7.", + attachments: [], + streaming: false, + createdAt: now, + updatedAt: now, + createdBy: "system", + creationSource: "server", + notification: { + source: { + kind: "monitor", + pullRequest: { + host: "github.com", + repository: "me/app", + number: 7, + watchStartedAt: DateTime.formatIso(now), + headSha: "abc", + watchEnded: true, + }, + }, + outcome: "completed", + summary: "#7: checks passed", + }, + }, + } satisfies OrchestrationV2DomainEvent; + + for (const event of [ + ended("event:parent-done", parentRun, "completed"), + // A later update of a settled run is not a second settlement. + ended("event:parent-done-again", parentRun, "completed"), + ended("event:child-failed", childRun, "failed"), + request("event:asked", "pending"), + request("event:answered", "resolved"), + shared("event:guest-asked", [guestMessage("guest:one", "pending")]), + shared("event:guest-sent", [guestMessage("guest:one", "sent")]), + shared("event:guest-asked-again", [ + guestMessage("guest:one", "sent"), + guestMessage("guest:two", "pending"), + ]), + shared("event:guest-closed", null), + wake, + wake, + ]) { + yield* feeder.handle(event); + } + + const { events } = yield* hub.recent({ filter: { includeSubagentChildren: true } }); + assert.deepStrictEqual( + events.map((event) => [ + event.id, + event.threadId, + event.parentThreadId, + event.isSubagentChild, + ]), + [ + [`thread.run_settled:${parentRun.id}`, parentThreadId, null, false], + [`thread.run_settled:${childRun.id}`, childThreadId, parentThreadId, true], + ["thread.needs_input:request:milestone", parentThreadId, null, false], + ["thread.input_resolved:request:milestone", parentThreadId, null, false], + ["thread.guest_request:guest:one", parentThreadId, null, false], + ["thread.guest_request_resolved:guest:one", parentThreadId, null, false], + ["thread.guest_request:guest:two", parentThreadId, null, false], + ["thread.guest_request_resolved:guest:two", parentThreadId, null, false], + ["pr.watch_wake:message:pr-wake", parentThreadId, null, false], + ], + ); + const [, child, asked, answered, , sent, , closed, woke] = events; + assert.deepInclude(child, { outcome: "failed", projectId: parent.projectId }); + assert.deepInclude(asked, { kind: "approval" }); + assert.deepInclude(answered, { resolution: "resolved", actor: { type: "user" } }); + assert.deepInclude(sent, { resolution: "sent" }); + assert.deepInclude(closed, { resolution: "closed" }); + assert.deepInclude(woke, { + pullRequests: [{ host: "github.com", repository: "me/app", number: 7 }], + watchEnded: true, + summary: "#7: checks passed", + }); + // A subscriber that did not ask for children never hears of the child's run. + assert.notInclude( + (yield* hub.recent()).events.map((event) => event.threadId), + childThreadId, + ); + }).pipe(Effect.provide(layerTest)), +); diff --git a/apps/server/src/milestones/OrchestrationMilestones.ts b/apps/server/src/milestones/OrchestrationMilestones.ts new file mode 100644 index 0000000000000..c50c460ec4814 --- /dev/null +++ b/apps/server/src/milestones/OrchestrationMilestones.ts @@ -0,0 +1,244 @@ +import { + type GuestMessageId, + type GuestShareId, + type MilestoneActor, + type MilestoneEvent, + MilestoneId, + type MilestoneInputKind, + type OrchestrationV2AppThread, + type OrchestrationV2DomainEvent, + type OrchestrationV2RuntimeRequest, + type ThreadId, +} from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import type * as Scope from "effect/Scope"; +import * as Stream from "effect/Stream"; + +import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; +import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; +import { forkParked } from "../serverActivation.ts"; +import * as MilestoneHub from "./MilestoneHub.ts"; + +const inputKind = (kind: OrchestrationV2RuntimeRequest["kind"]): MilestoneInputKind | null => { + switch (kind) { + case "user_input": + case "mcp-elicitation": + return "user_input"; + case "command": + case "file-read": + case "file-change": + case "permission": + return "approval"; + default: + return null; + } +}; + +/** Turns orchestration events into thread, guest and pull request watch milestones. */ +export class OrchestrationMilestones extends Context.Service< + OrchestrationMilestones, + { + readonly start: () => Effect.Effect; + readonly handle: (event: OrchestrationV2DomainEvent) => Effect.Effect; + } +>()("t3/milestones/OrchestrationMilestones") {} + +const make = Effect.gen(function* () { + const engine = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const hub = yield* MilestoneHub.MilestoneHub; + // A record updated again after a restart is not news unless its change is from after it. + const since = yield* DateTime.now; + const isNew = (at: DateTime.Utc | string) => + DateTime.isGreaterThanOrEqualTo(typeof at === "string" ? DateTime.makeUnsafe(at) : at, since); + /** Each thread's waiting guest messages, so a resolution is told once and a closed link is seen. */ + const guestPending = new Map>(); + + const envelope = ( + id: string, + thread: OrchestrationV2AppThread, + occurredAt: DateTime.Utc, + actor: MilestoneActor, + ) => ({ + id: MilestoneId.make(id), + occurredAt: DateTime.formatIso(occurredAt), + projectId: thread.projectId, + threadId: thread.id, + parentThreadId: thread.lineage.parentThreadId, + actor, + isSubagentChild: thread.lineage.relationshipToParent === "subagent", + }); + + const guestMilestones = ( + thread: OrchestrationV2AppThread, + occurredAt: DateTime.Utc, + ): ReadonlyArray => { + const share = thread.guestShare ?? null; + const before = guestPending.get(thread.id) ?? new Map(); + const pending = new Map(); + const out: Array = []; + const resolved = ( + shareId: GuestShareId, + guestMessageId: GuestMessageId, + resolution: "sent" | "dismissed" | "closed", + ) => + out.push({ + ...envelope(`thread.guest_request_resolved:${guestMessageId}`, thread, occurredAt, { + type: "user", + }), + type: "thread.guest_request_resolved", + shareId, + guestMessageId, + resolution, + }); + if (share !== null) { + const guest: MilestoneActor = { + type: "guest", + id: share.id, + ...(share.guestName === null ? {} : { label: share.guestName }), + }; + for (const message of share.messages) { + if (message.status !== "pending") { + if (before.has(message.id)) resolved(share.id, message.id, message.status); + continue; + } + pending.set(message.id, share.id); + if (before.has(message.id) || !isNew(message.submittedAt)) continue; + out.push({ + ...envelope(`thread.guest_request:${message.id}`, thread, occurredAt, guest), + type: "thread.guest_request", + shareId: share.id, + guestMessageId: message.id, + }); + } + } + // Gone from the share without an answer: the link was closed or replaced. + for (const [guestMessageId, shareId] of before) { + if (share?.messages.some((message) => message.id === guestMessageId) !== true) { + resolved(shareId, guestMessageId, "closed"); + } + } + if (pending.size === 0) guestPending.delete(thread.id); + else guestPending.set(thread.id, pending); + return out; + }; + + // Runs for every domain event, token deltas included; most return before reading anything. + const handle: OrchestrationMilestones["Service"]["handle"] = Effect.fnUntraced( + function* (event) { + const out: Array = []; + switch (event.type) { + case "run.updated": { + const run = event.payload; + // A queued run cancelled before it started did no work worth telling of. + if (run.startedAt === null || run.completedAt === null || !isNew(run.completedAt)) return; + if ( + run.status !== "completed" && + run.status !== "failed" && + run.status !== "interrupted" && + run.status !== "cancelled" + ) { + return; + } + const thread = yield* projections.getThread(event.threadId); + out.push({ + ...envelope(`thread.run_settled:${run.id}`, thread, run.completedAt, { + type: "agent", + id: run.providerInstanceId, + }), + type: "thread.run_settled", + runId: run.id, + outcome: run.status, + }); + break; + } + case "runtime-request.updated": { + const request = event.payload; + const kind = inputKind(request.kind); + if (kind === null) return; + if (request.status === "pending") { + if (!isNew(request.createdAt)) return; + const thread = yield* projections.getThread(event.threadId); + out.push({ + ...envelope(`thread.needs_input:${request.id}`, thread, request.createdAt, { + type: "agent", + }), + type: "thread.needs_input", + requestId: request.id, + kind, + }); + } else { + const at = request.resolvedAt ?? event.occurredAt; + if (!isNew(at)) return; + const thread = yield* projections.getThread(event.threadId); + out.push({ + ...envelope(`thread.input_resolved:${request.id}`, thread, at, { + type: request.status === "resolved" ? "user" : "system", + }), + type: "thread.input_resolved", + requestId: request.id, + kind, + resolution: request.status, + }); + } + break; + } + case "thread.guest-share-updated": + out.push(...guestMilestones(event.payload, event.occurredAt)); + break; + case "message.updated": { + const message = event.payload; + const source = message.notification?.source; + if (source?.kind !== "monitor" || source.pullRequest === undefined) return; + if (!isNew(message.createdAt)) return; + const stamps = [source.pullRequest, ...(source.otherPullRequests ?? [])]; + const thread = yield* projections.getThread(event.threadId); + out.push({ + ...envelope(`pr.watch_wake:${message.id}`, thread, message.createdAt, { + type: "system", + label: "pull request watch", + }), + type: "pr.watch_wake", + pullRequests: stamps.map(({ host, repository, number }) => ({ + host, + repository, + number, + })), + outcome: message.notification!.outcome, + summary: message.notification!.summary, + watchEnded: stamps.some((stamp) => stamp.watchEnded === true), + }); + break; + } + default: + return; + } + yield* Effect.forEach(out, hub.publish, { discard: true }); + }, + (effect, event) => + effect.pipe( + Effect.catchCause((cause) => + Effect.logWarning("deriving a milestone failed", { threadId: event.threadId, cause }), + ), + ), + ); + + const start: OrchestrationMilestones["Service"]["start"] = Effect.fn( + "OrchestrationMilestones.start", + )(function* () { + yield* forkParked( + Stream.runForEach(engine.streamDomainEvents, handle).pipe( + Effect.catchCause((cause) => + Effect.logWarning("orchestration milestone stream failed", { cause }), + ), + ), + ); + }); + + return OrchestrationMilestones.of({ start, handle }); +}); + +export const layer = Layer.effect(OrchestrationMilestones, make); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index d06186beb1988..8e0a2ea2f655f 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -9,6 +9,8 @@ import * as StorageCleanup from "./storageCleanup.ts"; import * as PullRequestSyncReactor from "./orchestration-v2/PullRequestSyncReactor.ts"; import * as PullRequestWatchReactor from "./orchestration-v2/PullRequestWatchReactor.ts"; import * as DelegatedTaskQuestionReactor from "./orchestration-v2/DelegatedTaskQuestionReactor.ts"; +import * as MilestoneHub from "./milestones/MilestoneHub.ts"; +import * as OrchestrationMilestones from "./milestones/OrchestrationMilestones.ts"; // Effect wraps this raw Node HTTP server after its startup and write-error guards attach. // @effect-diagnostics nodeBuiltinImport:off import * as NodeHttp from "node:http"; @@ -753,12 +755,19 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll( yield* service.start(); }), ).pipe(Layer.provide(DelegatedTaskQuestionReactor.layer), Layer.provide(ProjectionStoreV2.layer)), + Layer.effectDiscard( + Effect.gen(function* () { + yield* (yield* OrchestrationMilestones.OrchestrationMilestones).start(); + }), + ).pipe(Layer.provide(OrchestrationMilestones.layer), Layer.provide(ProjectionStoreV2.layer)), ProviderUsageLimitsIngestion.layer, layerProviderInstallationRefresh, ProviderInstallation.layer, ReplayMarkers.layer, Layer.effectDiscard(ProjectSettingsOverrideSweep.sweep), ).pipe( + // One hub, which the feeders above publish to and future consumers read. + Layer.provideMerge(MilestoneHub.layer), Layer.provideMerge(layerOrchestrationApplication), Layer.provideMerge(layerTaskFolders), Layer.provideMerge(RuntimeLayer.layerEventInfrastructure), diff --git a/docs/user/outside-agents.md b/docs/user/outside-agents.md index 9c164f91c9962..8bc6b50d24def 100644 --- a/docs/user/outside-agents.md +++ b/docs/user/outside-agents.md @@ -135,6 +135,14 @@ Any agent that supports remote MCP servers over HTTP with OAuth can connect. Giv it the MCP URL and choose OAuth, and the agent finds the sign-in settings itself. Agents without OAuth support cannot connect. +A bot that supports MCP Events (`io.modelcontextprotocol/events`) can learn +when something happens without reading threads over and over: a turn ended, an +agent waits on a person, a guest asked something, a watched pull request woke +its thread. Each of these is an event type it can poll or stream, narrowed to +projects or threads. The environment keeps its latest 1,000 milestones in +memory, so a bot that was away longer, or reconnects after a restart, is told +some may be missing and should reread the threads it cares about. + ## Scripts on the host On the machine that runs the environment, `t3 thread` uses the same tools diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index e1b3346386ffc..7a159c816ef11 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -67,6 +67,7 @@ export * from "./previewAutomation.ts"; export * from "./previewCapture.ts"; export * from "./usage.ts"; export * from "./scheduledTask.ts"; +export * from "./milestones.ts"; export * from "./worktreeMcp.ts"; export * from "./resourceTelemetry.ts"; export * from "./rpc.ts"; diff --git a/packages/contracts/src/milestones.ts b/packages/contracts/src/milestones.ts new file mode 100644 index 0000000000000..56e259b2b9fab --- /dev/null +++ b/packages/contracts/src/milestones.ts @@ -0,0 +1,120 @@ +import * as Schema from "effect/Schema"; + +import { + GuestMessageId, + GuestShareId, + IsoDateTime, + ProjectId, + RunId, + RuntimeRequestId, + ThreadId, + TrimmedNonEmptyString, +} from "./baseSchemas.ts"; +import { ThreadPullRequestKey } from "./threadPullRequest.ts"; + +/** + * Milestones are the coarse state changes worth telling someone about: a turn ended, an agent + * waits on a person, a guest asked something, a watched pull request woke its thread. + * They are derived from the authoritative stores and kept only in memory, so a consumer that + * needs the full state reads it from those stores. + */ +export const MilestoneId = TrimmedNonEmptyString.pipe(Schema.brand("MilestoneId")); +export type MilestoneId = typeof MilestoneId.Type; + +/** Who caused a milestone, as far as the server knows. */ +export const MilestoneActor = Schema.Struct({ + type: Schema.Literals(["user", "agent", "system", "guest"]), + id: Schema.optional(TrimmedNonEmptyString), + label: Schema.optional(TrimmedNonEmptyString), +}); +export type MilestoneActor = typeof MilestoneActor.Type; + +const MilestoneEnvelope = Schema.Struct({ + /** Stable for one transition, so publishing it twice is one milestone. */ + id: MilestoneId, + occurredAt: IsoDateTime, + projectId: Schema.NullOr(ProjectId), + threadId: Schema.NullOr(ThreadId), + parentThreadId: Schema.NullOr(ThreadId), + actor: MilestoneActor, + /** A subagent's thread. Muted unless asked for. */ + isSubagentChild: Schema.Boolean, +}); + +/** `approval` covers command, file and permission prompts; `user_input` covers questions. */ +export const MilestoneInputKind = Schema.Literals(["user_input", "approval"]); +export type MilestoneInputKind = typeof MilestoneInputKind.Type; + +export const MilestoneEvent = Schema.Union([ + Schema.Struct({ + ...MilestoneEnvelope.fields, + type: Schema.Literal("thread.run_settled"), + runId: RunId, + outcome: Schema.Literals(["completed", "failed", "interrupted", "cancelled"]), + }), + Schema.Struct({ + ...MilestoneEnvelope.fields, + type: Schema.Literal("thread.needs_input"), + requestId: RuntimeRequestId, + kind: MilestoneInputKind, + }), + Schema.Struct({ + ...MilestoneEnvelope.fields, + type: Schema.Literal("thread.input_resolved"), + requestId: RuntimeRequestId, + kind: MilestoneInputKind, + resolution: Schema.Literals(["resolved", "expired", "cancelled"]), + }), + Schema.Struct({ + ...MilestoneEnvelope.fields, + type: Schema.Literal("thread.guest_request"), + shareId: GuestShareId, + guestMessageId: GuestMessageId, + }), + Schema.Struct({ + ...MilestoneEnvelope.fields, + type: Schema.Literal("thread.guest_request_resolved"), + shareId: GuestShareId, + guestMessageId: GuestMessageId, + /** `closed` when the link was closed or replaced with the request still waiting. */ + resolution: Schema.Literals(["sent", "dismissed", "closed"]), + }), + Schema.Struct({ + ...MilestoneEnvelope.fields, + type: Schema.Literal("pr.watch_wake"), + pullRequests: Schema.Array(ThreadPullRequestKey), + outcome: Schema.Literals(["completed", "failed", "cancelled", "updated", "unknown"]), + summary: Schema.String, + /** The watch ended with this wake, as a merge, a close or a read failure ends it. */ + watchEnded: Schema.Boolean, + }), +]); +export type MilestoneEvent = typeof MilestoneEvent.Type; + +export const MilestoneEventType = Schema.Literals([ + "thread.run_settled", + "thread.needs_input", + "thread.input_resolved", + "thread.guest_request", + "thread.guest_request_resolved", + "pr.watch_wake", +]); +export type MilestoneEventType = typeof MilestoneEventType.Type; + +export const MilestoneFilter = Schema.Struct({ + types: Schema.optional(Schema.Array(MilestoneEventType)), + projectIds: Schema.optional(Schema.Array(ProjectId)), + threadIds: Schema.optional(Schema.Array(ThreadId)), + /** Absent reads as false: subagent threads churn and are rarely news. */ + includeSubagentChildren: Schema.optional(Schema.Boolean), +}); +export type MilestoneFilter = typeof MilestoneFilter.Type; + +/** Whether `event` is one `filter` asks for. Each given list must contain the event's value. */ +export const milestoneMatches = (event: MilestoneEvent, filter: MilestoneFilter = {}): boolean => + (filter.includeSubagentChildren === true || !event.isSubagentChild) && + (filter.types === undefined || filter.types.includes(event.type)) && + (filter.projectIds === undefined || + (event.projectId !== null && filter.projectIds.includes(event.projectId))) && + (filter.threadIds === undefined || + (event.threadId !== null && filter.threadIds.includes(event.threadId))); diff --git a/patches/effect@4.1.5.patch b/patches/effect@4.1.5.patch new file mode 100644 index 0000000000000..6d1bf0a6a9fa8 --- /dev/null +++ b/patches/effect@4.1.5.patch @@ -0,0 +1,2479 @@ +diff --git a/dist/ai/McpSchema.d.ts b/dist/ai/McpSchema.d.ts +index 8f86c27..aed42ae 100644 +--- a/dist/ai/McpSchema.d.ts ++++ b/dist/ai/McpSchema.d.ts +@@ -941,6 +941,52 @@ export declare const HEADER_MISMATCH_ERROR_CODE: -32020; + * @since 4.0.6 + */ + export declare const UNSUPPORTED_PROTOCOL_VERSION_ERROR_CODE: -32022; ++/** ++ * Represents the MCP error code for a referenced entity that does not exist, ++ * such as an unknown event name. `data.kind` may say which. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export declare const NOT_FOUND_ERROR_CODE: -32023; ++/** ++ * Represents the MCP error code for a principal that is not permitted, or ++ * whose access was revoked. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export declare const FORBIDDEN_ERROR_CODE: -32024; ++/** ++ * Represents the MCP error code for a server-imposed limit or quota. ++ * `data.limit` names it. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export declare const RESOURCE_EXHAUSTED_ERROR_CODE: -32025; ++/** ++ * Represents the MCP error code for a well-formed request that asks for a ++ * capability or option not supported here. `data` identifies it, for example ++ * `{ feature: "deliveryMode", value: "push" }`. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export declare const UNSUPPORTED_ERROR_CODE: -32026; ++/** ++ * Represents the MCP error code for a client-supplied callback endpoint that ++ * failed verification or could not be reached. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export declare const CALLBACK_ENDPOINT_ERROR_CODE: -32027; + declare const ParseError_base: Schema.Class>, Schema.optionalKey, never, never>; ++ readonly _tag: Schema.tag<"NotFound">; ++ readonly code: Schema.tag<-32023>; ++}>, import("../Cause.ts").YieldableError>; ++/** ++ * Represents an MCP error for a referenced entity that does not exist. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export declare class NotFound extends NotFound_base { ++} ++declare const Forbidden_base: Schema.Class>, Schema.optionalKey, never, never>; ++ readonly _tag: Schema.tag<"Forbidden">; ++ readonly code: Schema.tag<-32024>; ++}>, import("../Cause.ts").YieldableError>; ++/** ++ * Represents an MCP error for a principal that is not permitted. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export declare class Forbidden extends Forbidden_base { ++} ++declare const ResourceExhausted_base: Schema.Class>, Schema.optionalKey, never, never>; ++ readonly _tag: Schema.tag<"ResourceExhausted">; ++ readonly code: Schema.tag<-32025>; ++}>, import("../Cause.ts").YieldableError>; ++/** ++ * Represents an MCP error for a server-imposed limit or quota. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export declare class ResourceExhausted extends ResourceExhausted_base { ++} ++declare const Unsupported_base: Schema.Class>, Schema.optionalKey, never, never>; ++ readonly _tag: Schema.tag<"Unsupported">; ++ readonly code: Schema.tag<-32026>; ++}>, import("../Cause.ts").YieldableError>; ++/** ++ * Represents an MCP error for a capability or option not supported here. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export declare class Unsupported extends Unsupported_base { ++} ++declare const CallbackEndpointError_base: Schema.Class>, Schema.optionalKey, never, never>; ++ readonly _tag: Schema.tag<"CallbackEndpointError">; ++ readonly code: Schema.tag<-32027>; ++}>, import("../Cause.ts").YieldableError>; ++/** ++ * Represents an MCP error for a callback endpoint that failed verification or could not be reached. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export declare class CallbackEndpointError extends CallbackEndpointError_base { ++} + /** + * Schema for MCP protocol errors returned in JSON-RPC failure responses, + * including standard protocol errors and custom `McpErrorBase` values. +@@ -1880,6 +2001,66 @@ declare const Skill_base: Schema.Class; ++/** ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventDelivery = typeof EventDelivery.Type; ++/** ++ * An event type listed by `events/list`: its subscription arguments, its ++ * payload, and the delivery modes it supports. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare const EventDescriptor: Schema.Struct<{ ++ readonly name: Schema.String; ++ readonly description: Schema.decodeTo>, Schema.optionalKey, never, never>; ++ readonly delivery: Schema.$Array>; ++ readonly inputSchema: Schema.$Record; ++ readonly payloadSchema: Schema.$Record; ++ readonly _meta: Schema.decodeTo>>, Schema.optionalKey>, never, never>; ++}>; ++/** ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventDescriptor = typeof EventDescriptor.Type; ++/** ++ * One delivered event. `cursor` is the subscription's position after it, on ++ * push and webhook delivery; poll carries the cursor on the result. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare const EventOccurrence: Schema.Struct<{ ++ readonly eventId: Schema.String; ++ readonly name: Schema.String; ++ readonly timestamp: Schema.String; ++ readonly data: Schema.$Record; ++ readonly cursor: Schema.decodeTo>>, Schema.optionalKey>, never, never>; ++ readonly _meta: Schema.decodeTo>>, Schema.optionalKey>, never, never>; ++}>; ++/** ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventOccurrence = typeof EventOccurrence.Type; + declare const PromptArgument_base: Schema.Opaque Effect.Effect Layer.Layer; ++ ++/** ++ * A failure an event handler reports to the client: a JSON-RPC error on a ++ * poll or when a push stream opens, and `notifications/events/terminated` ++ * once it is open. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventError = ++ | InvalidParams ++ | InternalError ++ | McpSchema.NotFound ++ | McpSchema.Forbidden ++ | McpSchema.ResourceExhausted ++ | McpSchema.Unsupported ++ ++/** ++ * Where a poll starts. `cursor` is `null` to start from now, which replays ++ * nothing. With a cursor, replay starts at whichever is later: the cursor, or ++ * `maxAgeMs` before now. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventPollRequest { ++ readonly cursor: string | null ++ readonly maxAgeMs?: number | undefined ++ readonly maxEvents?: number | undefined ++} ++ ++/** ++ * Where a push stream starts, read as for {@link EventPollRequest}. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventStreamRequest { ++ readonly cursor: string | null ++ readonly maxAgeMs?: number | undefined ++} ++ ++/** ++ * One occurrence, with its payload as the event's `payload` schema types it. ++ * `eventId` stays the same however often the occurrence is delivered. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventOccurrence
    { ++ readonly eventId: string ++ readonly timestamp: string ++ readonly data: A ++ readonly _meta?: Readonly> | undefined ++} ++ ++/** ++ * A poll's answer. `truncated` says delivery started later than the cursor, ++ * and `hasMore` that `maxEvents` cut the batch short. `nextPollMs` defaults ++ * to 30 seconds. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventPollResult { ++ readonly events: ReadonlyArray> ++ readonly cursor: string | null ++ readonly truncated?: boolean | undefined ++ readonly hasMore?: boolean | undefined ++ readonly nextPollMs?: number | undefined ++} ++ ++/** ++ * What a push stream carries: an occurrence and the cursor after it; a ++ * position checked without a match, which the next heartbeat reports; a gap, ++ * sent as a fresh `notifications/events/active` with `truncated`; or an error ++ * that leaves the stream open. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventStreamItem = ++ | ({ readonly _tag: "Event"; readonly cursor: string | null } & EventOccurrence) ++ | { readonly _tag: "Position"; readonly cursor: string | null } ++ | { readonly _tag: "Gap"; readonly cursor: string | null } ++ | { readonly _tag: "Error"; readonly error: EventError } ++ ++/** ++ * An accepted push subscription: where it starts, and its items. A failure ++ * of `items` ends it. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventSubscription { ++ readonly cursor: string | null ++ readonly truncated?: boolean | undefined ++ readonly items: Stream.Stream, EventError, R> ++} ++ ++/** ++ * Options for {@link registerEvent} and {@link event}. ++ * ++ * **Details** ++ * ++ * `parameters` types the subscription arguments, an empty object by default, ++ * and `payload` the occurrences' `data`; both are advertised as JSON Schema ++ * by `events/list`. `poll` offers poll delivery and `stream` push delivery, ++ * and at least one is required. Webhook delivery is not supported, so ++ * `events/subscribe` answers `Unsupported`. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventOptions, Payload extends Schema.Codec, R> { ++ readonly name: string ++ readonly description?: string | undefined ++ readonly parameters?: Params | undefined ++ readonly payload: Payload ++ readonly _meta?: Readonly> | undefined ++ readonly annotations?: Context.Context | undefined ++ readonly poll?: ++ | (( ++ args: Params["Type"], ++ request: EventPollRequest ++ ) => Effect.Effect, EventError, R>) ++ | undefined ++ readonly stream?: ++ | (( ++ args: Params["Type"], ++ request: EventStreamRequest ++ ) => Effect.Effect, EventError, R | Scope.Scope>) ++ | undefined ++} ++ ++/** ++ * Registers an event type under the MCP Events extension (SEP-3415). ++ * ++ * **Details** ++ * ++ * The server declares `io.modelcontextprotocol/events` on revision ++ * `2026-07-28` once any event type is registered, and answers `events/list`, ++ * `events/poll` and `events/stream`. A push stream runs `stream` for its ++ * lifetime inside the request's middleware, sends heartbeats carrying the ++ * last cursor, and ends when the client goes away. Services read by `poll` ++ * and `stream` are request-level, as for tools. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare const registerEvent: = Schema.Struct<{}>, Payload extends Schema.Codec = Schema.Codec, R = never>(options: EventOptions) => Effect.Effect>; ++/** ++ * Creates a layer that registers an event type under the MCP Events ++ * extension (SEP-3415). ++ * ++ * @see {@link registerEvent} for the Effect-level event registration API ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare const event: = Schema.Struct<{}>, Payload extends Schema.Codec = Schema.Codec, R = never>(options: EventOptions) => Layer.Layer>; + /** + * Registers an MCP prompt from an Effect program. + * +diff --git a/dist/ai/McpServer.js b/dist/ai/McpServer.js +index 4bf6bca..0973460 100644 +--- a/dist/ai/McpServer.js ++++ b/dist/ai/McpServer.js +@@ -413,6 +413,9 @@ const notFound = (method, target) => { + return new McpCore.SkillNotFound({ + uri: target + }); ++ case "events/poll": ++ case "events/stream": ++ return McpCore.eventNotFound(target); + } + }; + const isHidden = error => error instanceof Hidden; +@@ -2637,6 +2640,96 @@ export const registerSkill = /*#__PURE__*/Effect.fnUntraced(function* (options) + * @since 4.1.1 + */ + export const skill = options => Layer.effectDiscard(registerSkill(options)); ++// ============================================================================= ++// Events ++// ============================================================================= ++const DEFAULT_NEXT_POLL_MS = 30_000; ++/** ++* Registers an event type under the MCP Events extension (SEP-3415). ++* ++* **Details** ++* ++* The server declares `io.modelcontextprotocol/events` on revision ++* `2026-07-28` once any event type is registered, and answers `events/list`, ++* `events/poll` and `events/stream`. A push stream runs `stream` for its ++* lifetime inside the request's middleware, sends heartbeats carrying the ++* last cursor, and ends when the client goes away. Services read by `poll` ++* and `stream` are request-level, as for tools. ++* ++* @stability unstable ++* @category events ++* @since 4.1.4 ++*/ ++export const registerEvent = Effect.fnUntraced(function* (options) { ++ const { name, poll, stream } = options; ++ if (poll === undefined && stream === undefined) { ++ return yield* Effect.die(new Cause.IllegalArgumentError(`Event ${name}: give it poll, stream or both`)); ++ } ++ const registry = yield* McpServer; ++ const { core, globalMiddleware } = internalState.get(registry); ++ const services = yield* Effect.context(); ++ const annotations = options.annotations ?? Context.empty(); ++ const { invoke, visible } = makeInvoke(services, globalMiddleware); ++ const parameters = options.parameters ?? Schema.Struct({}); ++ const decodeArguments = Schema.decodeUnknownEffect(Schema.toCodecJson(parameters)); ++ const encodePayload = Schema.encodeUnknownEffect(Schema.toCodecJson(options.payload)); ++ const argumentsOf = (args) => decodeArguments(args).pipe(Effect.mapError((error) => new InvalidParams({ message: error.message }))); ++ const encodeEvent = (event) => encodePayload(event.data).pipe(Effect.flatMap((data) => Predicate.isReadonlyObject(data) ? Effect.succeed(data) : Effect.fail(data)), Effect.map((data) => ({ ++ eventId: event.eventId, ++ timestamp: event.timestamp, ++ data, ++ ...(event._meta === undefined ? {} : { _meta: event._meta }) ++ })), Effect.mapError(() => new InternalError({ message: `Event '${name}' payload failed to encode` }))); ++ yield* core.events.register({ ++ descriptor: { ++ name, ++ ...(options.description === undefined ? {} : { description: options.description }), ++ delivery: [...(poll === undefined ? [] : ["poll"]), ...(stream === undefined ? [] : ["push"])], ++ inputSchema: toolJsonSchema(parameters, false), ++ payloadSchema: toolJsonSchema(options.payload, false), ++ ...(options._meta === undefined ? {} : { _meta: options._meta }) ++ }, ++ isVisible: isEnabled(annotations), ++ visible: visible("events/list", name), ++ poll: poll === undefined ? undefined : (request, invocation) => invoke(Effect.gen(function* () { ++ const result = yield* poll(yield* argumentsOf(request.arguments), { ++ cursor: request.cursor, ++ maxAgeMs: request.maxAgeMs, ++ maxEvents: request.maxEvents ++ }); ++ return { ++ events: yield* Effect.forEach(result.events, encodeEvent), ++ cursor: result.cursor, ++ truncated: result.truncated ?? false, ++ hasMore: result.hasMore ?? false, ++ nextPollMs: result.nextPollMs ?? DEFAULT_NEXT_POLL_MS ++ }; ++ }), invocation, { method: "events/poll", target: name, payload: request }), ++ stream: stream === undefined ? undefined : (request, invocation, deliver) => invoke(Effect.scoped(Effect.gen(function* () { ++ const subscription = yield* stream(yield* argumentsOf(request.arguments), { ++ cursor: request.cursor, ++ maxAgeMs: request.maxAgeMs ++ }); ++ // The items run on the delivery fiber, so they keep this request's services. ++ const context = yield* Effect.context(); ++ const items = subscription.items.pipe(Stream.mapEffect((item) => item._tag === "Event" ++ ? encodeEvent(item).pipe(Effect.map((event) => ({ ...event, _tag: "Event", cursor: item.cursor })), Effect.catch((error) => Effect.succeed({ _tag: "Error", error }))) ++ : Effect.succeed(item)), Stream.provideContext(context)); ++ yield* deliver({ cursor: subscription.cursor, truncated: subscription.truncated ?? false, items }); ++ })), invocation, { method: "events/stream", target: name, payload: request }) ++ }); ++}); ++/** ++* Creates a layer that registers an event type under the MCP Events ++* extension (SEP-3415). ++* ++* @see {@link registerEvent} for the Effect-level event registration API ++* ++* @stability unstable ++* @category events ++* @since 4.1.4 ++*/ ++export const event = (options) => Layer.effectDiscard(registerEvent(options)); + /** + * Registers an MCP prompt from an Effect program. + * +diff --git a/dist/ai/internal/mcpCore.js b/dist/ai/internal/mcpCore.js +index 4c416a8..50d2d34 100644 +--- a/dist/ai/internal/mcpCore.js ++++ b/dist/ai/internal/mcpCore.js +@@ -75,6 +75,15 @@ export const ClientNotification = /*#__PURE__*/Data.taggedEnum(); + * @internal + */ + export const ServerNotification = /*#__PURE__*/Data.taggedEnum(); ++/** ++ * @internal ++ */ ++export const eventNotFound = name => new McpSchema.NotFound({ ++ message: `Event '${name}' not found`, ++ data: { ++ kind: "event" ++ } ++}); + // Whether one skill directory contains the other, or both are the same. + const skillsOverlap = (a, b) => { + const rootA = a.slice(0, -"/SKILL.md".length); +@@ -90,6 +99,7 @@ export const make = /*#__PURE__*/Effect.sync(() => { + const resourceTemplateRegistrations = []; + const promptRegistrations = new Map(); + const skillRegistrations = new Map(); ++ const eventRegistrations = new Map(); + const skillFiles = new Set(); + const completionRegistrations = new Map(); + const filterList = (registrations, invocation) => Effect.map(Effect.filter(Arr.filter(registrations, entry => entry.isVisible(invocation.protocol)), entry => entry.visible === undefined ? Effect.succeed(true) : entry.visible(invocation)), entries => entries.map(entry => entry.descriptor)); +@@ -234,11 +244,22 @@ export const make = /*#__PURE__*/Effect.sync(() => { + return Array.from(children.values()).sort((a, b) => a.uri < b.uri ? -1 : a.uri > b.uri ? 1 : 0); + }) + }; ++ const events = { ++ register: registration => Effect.sync(() => { ++ eventRegistrations.set(registration.descriptor.name, registration); ++ }), ++ list: invocation => filterList(eventRegistrations.values(), invocation), ++ get: (name, invocation) => Effect.suspend(() => { ++ const registration = eventRegistrations.get(name); ++ return registration !== undefined && registration.isVisible(invocation.protocol) ? Effect.succeed(registration) : Effect.fail(eventNotFound(name)); ++ }) ++ }; + const registrationPresence = Effect.sync(() => ({ + tools: registrations.size > 0, + resources: resourceRegistrations.length > 0 || resourceTemplateRegistrations.length > 0, + prompts: promptRegistrations.size > 0, +- skills: skillRegistrations.size > 0 ++ skills: skillRegistrations.size > 0, ++ events: eventRegistrations.size > 0 + })); + return { + tools, +@@ -246,6 +267,7 @@ export const make = /*#__PURE__*/Effect.sync(() => { + prompts, + completions, + skills, ++ events, + registrationPresence + }; + }); +diff --git a/dist/ai/internal/mcpEvents.d.ts b/dist/ai/internal/mcpEvents.d.ts +new file mode 100644 +index 0000000..cb0ff5c +--- /dev/null ++++ b/dist/ai/internal/mcpEvents.d.ts +@@ -0,0 +1 @@ ++export {}; +diff --git a/dist/ai/internal/mcpEvents.js b/dist/ai/internal/mcpEvents.js +new file mode 100644 +index 0000000..d875046 +--- /dev/null ++++ b/dist/ai/internal/mcpEvents.js +@@ -0,0 +1,265 @@ ++/** ++ * The Events extension (SEP-3415): wire schemas on revision 2026-07-28 and ++ * the delivery loop behind a push stream. ++ */ ++import * as Cause from "../../Cause.js"; ++import * as Clock from "../../Clock.js"; ++import * as Duration from "../../Duration.js"; ++import * as Effect from "../../Effect.js"; ++import * as Option from "../../Option.js"; ++import * as Queue from "../../Queue.js"; ++import * as Result from "../../Result.js"; ++import * as Rpc from "../../rpc/Rpc.js"; ++import * as RpcGroup from "../../rpc/RpcGroup.js"; ++import * as Schema from "../../Schema.js"; ++import * as Stream from "../../Stream.js"; ++import * as PublicMcpSchema from "../McpSchema.js"; ++import * as McpProtocol from "./mcpProtocol.js"; ++import * as Stateless from "./mcpSchema/v2026_07_28.js"; ++/** ++ * @internal ++ */ ++export const EXTENSION_ID = "io.modelcontextprotocol/events"; ++/** ++ * Adds the extension declaration while any event type is registered. The ++ * server sends no `notifications/events/list_changed`, so its settings object ++ * is empty. ++ * ++ * @internal ++ */ ++export const declareExtension = (extensions, servesEvents) => servesEvents ? { ...extensions, [EXTENSION_ID]: {} } : extensions; ++const methodNotFound = (method) => new McpProtocol.ProtocolError({ ++ code: PublicMcpSchema.METHOD_NOT_FOUND_ERROR_CODE, ++ message: `Method not found: ${method}` ++}); ++/** ++ * Fails with `Method not found` while no event type is registered, as a ++ * server that does not declare the extension. ++ * ++ * @internal ++ */ ++export const requireEvents = (core, method) => Effect.flatMap(core.registrationPresence, (presence) => presence.events ? Effect.void : Effect.fail(methodNotFound(method))); ++/** ++ * @internal ++ */ ++export const unsupportedDelivery = (value) => new PublicMcpSchema.Unsupported({ ++ message: `Delivery mode '${value}' is not supported for this event`, ++ data: { feature: "deliveryMode", value } ++}); ++// ============================================================================= ++// Wire schemas ++// ============================================================================= ++const optional = Stateless.optional; ++const Cursor = Schema.NullOr(Schema.String); ++const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)); ++/** ++ * @internal ++ */ ++export const ListEventsResult = Schema.StructWithRest(Schema.Struct({ ...Stateless.PaginatedResult, events: Schema.Array(PublicMcpSchema.EventDescriptor) }), [Stateless.UnknownObject]); ++/** ++ * @internal ++ */ ++export class ListEvents extends Rpc.make("events/list", { ++ success: ListEventsResult, ++ error: Stateless.McpError, ++ payload: Stateless.PaginatedRequestParams ++}) { ++} ++const SubscriptionParams = { ++ ...Stateless.RequestParams.fields, ++ name: Schema.String, ++ arguments: optional(Stateless.UnknownObject), ++ cursor: optional(Cursor), ++ maxAgeMs: optional(NonNegativeInt) ++}; ++/** ++ * @internal ++ */ ++export const PollEventsResult = Schema.StructWithRest(Schema.Struct({ ++ ...Stateless.ResultMeta, ++ events: Schema.Array(PublicMcpSchema.EventOccurrence), ++ cursor: Cursor, ++ truncated: Schema.Boolean, ++ hasMore: Schema.Boolean, ++ nextPollMs: NonNegativeInt ++}), [Stateless.UnknownObject]); ++/** ++ * @internal ++ */ ++export class PollEvents extends Rpc.make("events/poll", { ++ success: PollEventsResult, ++ error: Stateless.McpError, ++ payload: { ...SubscriptionParams, maxEvents: optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(1))) } ++}) { ++} ++/** ++ * @internal ++ */ ++export class StreamEvents extends Rpc.make("events/stream", { ++ success: Stateless.SubscriptionsListenResult, ++ error: Stateless.McpError, ++ payload: { ...SubscriptionParams, heartbeatMs: optional(NonNegativeInt) } ++}) { ++} ++/** ++ * @internal ++ */ ++export class SubscribeEvents extends Rpc.make("events/subscribe", { ++ success: Schema.StructWithRest(Schema.Struct({ ++ ...Stateless.ResultMeta, ++ id: Schema.String, ++ refreshBefore: Schema.NullOr(Schema.String), ++ cursor: Cursor, ++ truncated: Schema.Boolean ++ }), [Stateless.UnknownObject]), ++ error: Stateless.McpError, ++ payload: { ++ ...SubscriptionParams, ++ delivery: Stateless.UnknownObject, ++ ttlMs: optional(Schema.NullOr(NonNegativeInt)) ++ } ++}) { ++} ++/** ++ * @internal ++ */ ++export class UnsubscribeEvents extends Rpc.make("events/unsubscribe", { ++ success: Schema.StructWithRest(Schema.Struct(Stateless.ResultMeta), [Stateless.UnknownObject]), ++ error: Stateless.McpError, ++ payload: { ++ ...Stateless.RequestParams.fields, ++ name: Schema.String, ++ arguments: optional(Stateless.UnknownObject), ++ delivery: Stateless.UnknownObject ++ } ++}) { ++} ++/** ++ * @internal ++ */ ++export class EventsActiveNotification extends Rpc.make("notifications/events/active", { ++ payload: { ...Stateless.NotificationParams.fields, cursor: Cursor, truncated: Schema.Boolean, heartbeatMs: NonNegativeInt } ++}) { ++} ++/** ++ * @internal ++ */ ++export class EventsEventNotification extends Rpc.make("notifications/events/event", { ++ payload: { ...PublicMcpSchema.EventOccurrence.fields, ...Stateless.NotificationParams.fields } ++}) { ++} ++/** ++ * @internal ++ */ ++export class EventsHeartbeatNotification extends Rpc.make("notifications/events/heartbeat", { ++ payload: { ...Stateless.NotificationParams.fields, cursor: Cursor } ++}) { ++} ++/** ++ * @internal ++ */ ++export class EventsErrorNotification extends Rpc.make("notifications/events/error", { ++ payload: { ...Stateless.NotificationParams.fields, error: Stateless.McpError } ++}) { ++} ++/** ++ * @internal ++ */ ++export class EventsTerminatedNotification extends Rpc.make("notifications/events/terminated", { ++ payload: { ...Stateless.NotificationParams.fields, error: Stateless.McpError } ++}) { ++} ++/** ++ * The extension's requests on revision 2026-07-28. ++ * ++ * @internal ++ */ ++export class StatelessRpcs extends RpcGroup.make(ListEvents, PollEvents, StreamEvents, SubscribeEvents, UnsubscribeEvents) { ++} ++/** ++ * The notifications a push stream carries. ++ * ++ * @internal ++ */ ++export class ServerNotificationRpcs extends RpcGroup.make(EventsActiveNotification, EventsEventNotification, EventsHeartbeatNotification, EventsErrorNotification, EventsTerminatedNotification) { ++} ++// ============================================================================= ++// Push delivery ++// ============================================================================= ++const DEFAULT_HEARTBEAT_MS = 30_000; ++const MIN_HEARTBEAT_MS = 1_000; ++const MAX_HEARTBEAT_MS = 300_000; ++// Occurrences the handler may run ahead of a slow client before it waits. ++const PENDING_ITEMS = 16; ++/** ++ * The heartbeat interval granted for a suggested one. ++ * ++ * @internal ++ */ ++export const grantHeartbeat = (suggested) => Math.min(MAX_HEARTBEAT_MS, Math.max(MIN_HEARTBEAT_MS, suggested ?? DEFAULT_HEARTBEAT_MS)); ++const isJson = Schema.is(Schema.Json); ++/** ++ * @internal ++ */ ++export const wireError = (failure) => ({ ++ code: failure.code, ++ message: failure.message, ++ ...(failure.data !== undefined && isJson(failure.data) ? { data: failure.data } : {}) ++}); ++/** ++ * Sends `notifications/events/active`, then each occurrence, and a heartbeat ++ * with the position checked so far whenever `heartbeatMs` passes without ++ * another message. A failure of the subscription's items ends it with ++ * `notifications/events/terminated`. `send` adds the subscription id. ++ * ++ * @internal ++ */ ++export const deliver = Effect.fnUntraced(function* (options) { ++ const { heartbeatMs, name, subscription } = options; ++ let cursor = subscription.cursor; ++ // Measured from the last message sent: a Position changes the cursor but sends nothing. ++ let sentAt = 0; ++ const send = (tag, payload) => ++ options.send(tag, payload).pipe(Effect.andThen(Clock.currentTimeMillis), Effect.map((at) => { ++ sentAt = at; ++ })); ++ const active = (truncated) => send(EventsActiveNotification._tag, { cursor, truncated, heartbeatMs }); ++ yield* active(subscription.truncated); ++ const items = yield* Stream.toQueue(subscription.items, { capacity: PENDING_ITEMS }); ++ while (true) { ++ const wait = Math.max(0, sentAt + heartbeatMs - (yield* Clock.currentTimeMillis)); ++ const next = yield* Queue.take(items).pipe(Effect.timeoutOption(Duration.millis(wait)), Effect.result); ++ if (Result.isFailure(next)) { ++ if (!Cause.isDone(next.failure)) { ++ yield* send(EventsTerminatedNotification._tag, { error: wireError(next.failure) }); ++ } ++ return; ++ } ++ if (Option.isNone(next.success)) { ++ yield* send(EventsHeartbeatNotification._tag, { cursor }); ++ continue; ++ } ++ const item = next.success.value; ++ switch (item._tag) { ++ case "Event": { ++ cursor = item.cursor; ++ const { _meta, _tag, ...occurrence } = item; ++ yield* send(EventsEventNotification._tag, { ...occurrence, name, ...(_meta === undefined ? {} : { _meta }) }); ++ break; ++ } ++ case "Position": { ++ cursor = item.cursor; ++ break; ++ } ++ case "Gap": { ++ cursor = item.cursor; ++ yield* active(true); ++ break; ++ } ++ case "Error": { ++ yield* send(EventsErrorNotification._tag, { error: wireError(item.error) }); ++ break; ++ } ++ } ++ } ++}, Effect.scoped); +diff --git a/dist/ai/internal/mcpProtocol/v2026_07_28.js b/dist/ai/internal/mcpProtocol/v2026_07_28.js +index af1ceed..467dd8a 100644 +--- a/dist/ai/internal/mcpProtocol/v2026_07_28.js ++++ b/dist/ai/internal/mcpProtocol/v2026_07_28.js +@@ -17,6 +17,7 @@ import * as Schema from "../../../Schema.js"; + import * as Scope from "../../../Scope.js"; + import * as PublicMcpSchema from "../../McpSchema.js"; + import * as McpCore from "../mcpCore.js"; ++import * as McpEvents from "../mcpEvents.js"; + import * as McpProtocol from "../mcpProtocol.js"; + import * as McpSchema from "../mcpSchema/v2026_07_28.js"; + import * as McpSkills from "../mcpSkills.js"; +@@ -242,7 +243,7 @@ const unsupported = operation => new PublicMcpSchema.McpReverseOperationUnsuppor + /** + * @internal + */ +-export const handlerRpcs = /*#__PURE__*/McpSchema.ClientRequestRpcs.merge(McpSchema.ClientNotificationRpcs, McpSkills.StatelessRpcs); ++export const handlerRpcs = /*#__PURE__*/McpSchema.ClientRequestRpcs.merge(McpSchema.ClientNotificationRpcs, McpSkills.StatelessRpcs, McpEvents.StatelessRpcs); + /** + * @internal + */ +@@ -260,6 +261,8 @@ export const makeHandlers = (core, _lifecycle, context) => { + const decodeListSkillsResult = Schema.decodeUnknownEffect(McpSkills.ListSkillsResult); + const decodeGetSkillResult = Schema.decodeUnknownEffect(McpSkills.GetSkillResult); + const decodeReadResourceDirectoryResult = Schema.decodeUnknownEffect(McpSkills.ReadResourceDirectoryResult); ++ const decodeListEventsResult = Schema.decodeUnknownEffect(McpEvents.ListEventsResult); ++ const decodePollEventsResult = Schema.decodeUnknownEffect(McpEvents.PollEventsResult); + const sendNotification = context.sendNotification; + const supportsSubscriptions = sendNotification !== undefined; + // Older adapters accept arbitrary JSON; this binding requires extension settings objects. +@@ -277,7 +280,7 @@ export const makeHandlers = (core, _lifecycle, context) => { + completions: {}, + logging: {} + }; +- const declared = McpSkills.declareExtension(extensions, presence.skills); ++ const declared = McpEvents.declareExtension(McpSkills.declareExtension(extensions, presence.skills), presence.events); + if (declared !== undefined) capabilities.extensions = declared; + if (presence.tools) capabilities.tools = { + listChanged: supportsSubscriptions +@@ -297,6 +300,20 @@ export const makeHandlers = (core, _lifecycle, context) => { + serverInfo: context.serverInfo + }; + }); ++ const requireEvents = (method) => McpEvents.requireEvents(core, method).pipe(Effect.catch((error) => failWithHttpStatus(404, error))); ++ // The event type's `x-mcp-header` arguments must match their headers, as a tool's do. ++ const validateEventHeaders = Effect.fnUntraced(function* (registration, args) { ++ const httpRequest = yield* Effect.serviceOption(HttpServerRequest.HttpServerRequest); ++ if (Option.isSome(httpRequest)) { ++ yield* validateParameterHeaders(registration.descriptor.inputSchema, args, httpRequest.value.headers); ++ } ++ }); ++ // Webhook delivery is not implemented, so subscribing refuses every event type. ++ const refuseWebhook = Effect.fnUntraced(function* (method, name) { ++ yield* requireEvents(method); ++ yield* core.events.get(name, yield* getInvocation); ++ return yield* McpEvents.unsupportedDelivery("webhook"); ++ }); + const requireSkills = method => McpSkills.requireSkills(core, method).pipe(Effect.catch(error => failWithHttpStatus(404, error))); + const getInvocation = PublicMcpSchema.McpRequestContext.useSync(McpProtocol.invocationFromRequestContext); + const getInputInvocation = Effect.fnUntraced(function* (request) { +@@ -592,6 +609,77 @@ export const makeHandlers = (core, _lifecycle, context) => { + }, context.serverInfo); + return yield* decodeReadResourceDirectoryResult(result); + }, Effect.mapError(projectError)), ++ "events/list": Effect.fnUntraced(function* (request) { ++ yield* requireEvents("events/list"); ++ yield* McpProtocol.rejectCursor(request.cursor); ++ const events = yield* core.events.list(yield* getInvocation); ++ // Without a notification channel nothing can be pushed. ++ const offered = supportsSubscriptions ? events : events.flatMap((event) => { ++ const delivery = event.delivery.filter((mode) => mode !== "push"); ++ return delivery.length === 0 ? [] : [{ ...event, delivery }]; ++ }); ++ const result = yield* projectCompleteResult({ events: offered }, context.serverInfo); ++ return yield* decodeListEventsResult(result); ++ }, Effect.mapError(projectError)), ++ "events/poll": Effect.fnUntraced(function* (request) { ++ yield* requireEvents("events/poll"); ++ const invocation = yield* getInvocation; ++ const registration = yield* core.events.get(request.name, invocation); ++ if (registration.poll === undefined) { ++ return yield* McpEvents.unsupportedDelivery("poll"); ++ } ++ yield* validateEventHeaders(registration, request.arguments); ++ const outcome = yield* registration.poll({ ++ arguments: request.arguments ?? {}, ++ cursor: request.cursor ?? null, ++ maxAgeMs: request.maxAgeMs, ++ maxEvents: request.maxEvents ++ }, invocation); ++ const result = yield* projectCompleteResult({ ++ events: outcome.events.map((event) => omitUndefined({ ++ eventId: event.eventId, ++ name: request.name, ++ timestamp: event.timestamp, ++ data: event.data, ++ _meta: event._meta ++ })), ++ cursor: outcome.cursor, ++ truncated: outcome.truncated, ++ hasMore: outcome.hasMore, ++ nextPollMs: outcome.nextPollMs ++ }, context.serverInfo); ++ return yield* decodePollEventsResult(result); ++ }, Effect.mapError(projectError)), ++ "events/stream": Effect.fnUntraced(function* (request, { client, requestId }) { ++ yield* requireEvents("events/stream"); ++ const invocation = yield* getInvocation; ++ const registration = yield* core.events.get(request.name, invocation); ++ if (registration.stream === undefined || sendNotification === undefined) { ++ return yield* McpEvents.unsupportedDelivery("push"); ++ } ++ yield* validateEventHeaders(registration, request.arguments); ++ const subscriptionMetadata = { "io.modelcontextprotocol/subscriptionId": requestId }; ++ const send = (tag, payload) => sendNotification(McpSchema.protocolVersion, client.id, { ++ tag, ++ payload: { ++ ...payload, ++ _meta: { ...(Predicate.isReadonlyObject(payload._meta) ? payload._meta : {}), ...subscriptionMetadata } ++ } ++ }); ++ const heartbeatMs = McpEvents.grantHeartbeat(request.heartbeatMs); ++ yield* Effect.raceFirst(registration.stream({ arguments: request.arguments ?? {}, cursor: request.cursor ?? null, maxAgeMs: request.maxAgeMs }, invocation, (subscription) => McpEvents.deliver({ name: request.name, subscription, heartbeatMs, send })), context.awaitClientEnd ?? Effect.never); ++ const encodedServerInfo = yield* encodeImplementation(context.serverInfo); ++ return McpSchema.SubscriptionsListenResult.make({ ++ _meta: { ...subscriptionMetadata, "io.modelcontextprotocol/serverInfo": encodedServerInfo }, ++ resultType: "complete" ++ }); ++ }, Effect.mapError(projectError)), ++ "events/subscribe": Effect.fnUntraced(function* (request) { ++ return yield* refuseWebhook("events/subscribe", request.name); ++ }, Effect.mapError(projectError)), ++ "events/unsubscribe": Effect.fnUntraced(function* (request) { ++ return yield* refuseWebhook("events/unsubscribe", request.name); ++ }, Effect.mapError(projectError)), + "notifications/cancelled": Effect.fnUntraced(function* (_request) { + return yield* Effect.void; + }) +@@ -613,10 +701,10 @@ const runtime = { + export const protocol = /*#__PURE__*/McpProtocol.make({ + protocolVersion: McpSchema.protocolVersion, + runtime, +- clientRpcs: /*#__PURE__*/McpSchema.ClientRpcs.merge(McpSkills.StatelessRpcs), ++ clientRpcs: /*#__PURE__*/McpSchema.ClientRpcs.merge(McpSkills.StatelessRpcs, McpEvents.StatelessRpcs), + clientNotificationRpcs: McpSchema.ClientNotificationRpcs, + serverRequestRpcs: McpSchema.ServerRequestRpcs, +- serverNotificationRpcs: McpSchema.ServerNotificationRpcs, ++ serverNotificationRpcs: /*#__PURE__*/McpSchema.ServerNotificationRpcs.merge(McpEvents.ServerNotificationRpcs), + handlerRpcs, + makeHandlers, + toReverseClient: () => ({ +diff --git a/dist/ai/internal/mcpRuntime.js b/dist/ai/internal/mcpRuntime.js +index 88238ff..274e513 100644 +--- a/dist/ai/internal/mcpRuntime.js ++++ b/dist/ai/internal/mcpRuntime.js +@@ -39,6 +39,10 @@ const routingNameKey = method => { + switch (method) { + case "tools/call": + case "prompts/get": ++ case "events/poll": ++ case "events/stream": ++ case "events/subscribe": ++ case "events/unsubscribe": + return "name"; + case "resources/read": + return "uri"; +@@ -340,7 +344,8 @@ export const make = /*#__PURE__*/Effect.fnUntraced(function* (protocols) { + return { + _tag: "Accepted", + acknowledge: !isRequest || !hasId, +- isSubscription: Predicate.hasProperty(input, "method") && input.method === "subscriptions/listen" ++ // A push subscription stays open until cancelled, so it is never a plain response. ++ isSubscription: Predicate.hasProperty(input, "method") && (input.method === "subscriptions/listen" || input.method === "events/stream") + }; + }, + effectLogLevel: (clientId, headers, fallback) => stateful?.effectLogLevel(clientId, headers, fallback) ?? fallback, +diff --git a/src/ai/McpSchema.ts b/src/ai/McpSchema.ts +index ba6c830..1e58fb9 100644 +--- a/src/ai/McpSchema.ts ++++ b/src/ai/McpSchema.ts +@@ -740,6 +740,57 @@ export const HEADER_MISMATCH_ERROR_CODE = -32020 as const + */ + export const UNSUPPORTED_PROTOCOL_VERSION_ERROR_CODE = -32022 as const + ++/** ++ * Represents the MCP error code for a referenced entity that does not exist, ++ * such as an unknown event name. `data.kind` may say which. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export const NOT_FOUND_ERROR_CODE = -32023 as const ++ ++/** ++ * Represents the MCP error code for a principal that is not permitted, or ++ * whose access was revoked. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export const FORBIDDEN_ERROR_CODE = -32024 as const ++ ++/** ++ * Represents the MCP error code for a server-imposed limit or quota. ++ * `data.limit` names it. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export const RESOURCE_EXHAUSTED_ERROR_CODE = -32025 as const ++ ++/** ++ * Represents the MCP error code for a well-formed request that asks for a ++ * capability or option not supported here. `data` identifies it, for example ++ * `{ feature: "deliveryMode", value: "push" }`. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export const UNSUPPORTED_ERROR_CODE = -32026 as const ++ ++/** ++ * Represents the MCP error code for a client-supplied callback endpoint that ++ * failed verification or could not be reached. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export const CALLBACK_ENDPOINT_ERROR_CODE = -32027 as const ++ + /** + * Represents an MCP/JSON-RPC error for invalid JSON that could not be parsed. + * +@@ -852,6 +903,74 @@ export class InternalError extends Schema.Error("effect/ai/McpSch + static readonly notImplemented = new InternalError({ message: "Not implemented" }) + } + ++/** ++ * Represents an MCP error for a referenced entity that does not exist. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export class NotFound extends Schema.Error("effect/ai/McpSchema/NotFound")({ ++ ...McpErrorBase.fields, ++ _tag: Schema.tag("NotFound"), ++ code: Schema.tag(NOT_FOUND_ERROR_CODE) ++}) {} ++ ++/** ++ * Represents an MCP error for a principal that is not permitted. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export class Forbidden extends Schema.Error("effect/ai/McpSchema/Forbidden")({ ++ ...McpErrorBase.fields, ++ _tag: Schema.tag("Forbidden"), ++ code: Schema.tag(FORBIDDEN_ERROR_CODE) ++}) {} ++ ++/** ++ * Represents an MCP error for a server-imposed limit or quota. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export class ResourceExhausted extends Schema.Error("effect/ai/McpSchema/ResourceExhausted")({ ++ ...McpErrorBase.fields, ++ _tag: Schema.tag("ResourceExhausted"), ++ code: Schema.tag(RESOURCE_EXHAUSTED_ERROR_CODE) ++}) {} ++ ++/** ++ * Represents an MCP error for a capability or option not supported here. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export class Unsupported extends Schema.Error("effect/ai/McpSchema/Unsupported")({ ++ ...McpErrorBase.fields, ++ _tag: Schema.tag("Unsupported"), ++ code: Schema.tag(UNSUPPORTED_ERROR_CODE) ++}) {} ++ ++/** ++ * Represents an MCP error for a callback endpoint that failed verification or ++ * could not be reached. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export class CallbackEndpointError ++ extends Schema.Error("effect/ai/McpSchema/CallbackEndpointError")({ ++ ...McpErrorBase.fields, ++ _tag: Schema.tag("CallbackEndpointError"), ++ code: Schema.tag(CALLBACK_ENDPOINT_ERROR_CODE) ++ }) ++{} ++ + /** + * Schema for MCP protocol errors returned in JSON-RPC failure responses, + * including standard protocol errors and custom `McpErrorBase` values. +@@ -1501,6 +1620,76 @@ export class Skill extends Schema.Class( + _meta: optional(UnknownObject) + }) {} + ++// ============================================================================= ++// Events ++// ============================================================================= ++ ++/** ++ * How a client receives an event type's occurrences under the MCP Events ++ * extension (SEP-3415): by `events/poll`, an `events/stream` push stream, or ++ * a webhook registered with `events/subscribe`. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const EventDelivery = Schema.Literals(["poll", "push", "webhook"]) ++ ++/** ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventDelivery = typeof EventDelivery.Type ++ ++/** ++ * An event type listed by `events/list`: its subscription arguments, its ++ * payload, and the delivery modes it supports. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const EventDescriptor = Schema.Struct({ ++ name: Schema.String, ++ description: optional(Schema.String), ++ delivery: Schema.Array(EventDelivery), ++ inputSchema: UnknownObject, ++ payloadSchema: UnknownObject, ++ _meta: optional(UnknownObject) ++}) ++ ++/** ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventDescriptor = typeof EventDescriptor.Type ++ ++/** ++ * One delivered event. `cursor` is the subscription's position after it, on ++ * push and webhook delivery; poll carries the cursor on the result. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const EventOccurrence = Schema.Struct({ ++ eventId: Schema.String, ++ name: Schema.String, ++ timestamp: Schema.String, ++ data: UnknownObject, ++ cursor: optional(Schema.NullOr(Schema.String)), ++ _meta: optional(UnknownObject) ++}) ++ ++/** ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventOccurrence = typeof EventOccurrence.Type ++ + // ============================================================================= + // Prompts + // ============================================================================= +diff --git a/src/ai/McpServer.ts b/src/ai/McpServer.ts +index 4c2e191..3bf4321 100644 +--- a/src/ai/McpServer.ts ++++ b/src/ai/McpServer.ts +@@ -344,6 +344,9 @@ export type MiddlewareMethod = + | "skills/list" + | "skills/get" + | "resources/directory/read" ++ | "events/list" ++ | "events/poll" ++ | "events/stream" + + /** + * Request metadata passed to MCP middleware. +@@ -819,7 +822,14 @@ const internalError = new InternalError({ message: "Internal error" }) + const rejectWith = (error: McpErrorBase) => + Effect.fail(new McpCore.RequestRejected({ code: error.code, message: error.message, data: error.data, error })) + +-type CallMethod = "tools/call" | "resources/read" | "prompts/get" | "completion/complete" | "skills/get" ++type CallMethod = ++ | "tools/call" ++ | "resources/read" ++ | "prompts/get" ++ | "completion/complete" ++ | "skills/get" ++ | "events/poll" ++ | "events/stream" + + type ListMethod = Exclude + +@@ -829,6 +839,8 @@ interface NotFoundErrors { + readonly "prompts/get": McpCore.PromptNotFound + readonly "completion/complete": InvalidParams + readonly "skills/get": McpCore.SkillNotFound ++ readonly "events/poll": McpSchema.NotFound ++ readonly "events/stream": McpSchema.NotFound + } + + const notFound = (method: CallMethod, target: string): NotFoundErrors[CallMethod] => { +@@ -843,6 +855,9 @@ const notFound = (method: CallMethod, target: string): NotFoundErrors[CallMethod + return new InvalidParams({ message: "Unknown completion reference or argument" }) + case "skills/get": + return new McpCore.SkillNotFound({ uri: target }) ++ case "events/poll": ++ case "events/stream": ++ return McpCore.eventNotFound(target) + } + } + +@@ -4134,6 +4149,276 @@ export const registerSkill: (options: SkillOptions) => Effect.Effect => + Layer.effectDiscard(registerSkill(options)) + ++// ============================================================================= ++// Events ++// ============================================================================= ++ ++/** ++ * A failure an event handler reports to the client: a JSON-RPC error on a ++ * poll or when a push stream opens, and `notifications/events/terminated` ++ * once it is open. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventError = ++ | InvalidParams ++ | InternalError ++ | McpSchema.NotFound ++ | McpSchema.Forbidden ++ | McpSchema.ResourceExhausted ++ | McpSchema.Unsupported ++ ++/** ++ * Where a poll starts. `cursor` is `null` to start from now, which replays ++ * nothing. With a cursor, replay starts at whichever is later: the cursor, or ++ * `maxAgeMs` before now. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventPollRequest { ++ readonly cursor: string | null ++ readonly maxAgeMs?: number | undefined ++ readonly maxEvents?: number | undefined ++} ++ ++/** ++ * Where a push stream starts, read as for {@link EventPollRequest}. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventStreamRequest { ++ readonly cursor: string | null ++ readonly maxAgeMs?: number | undefined ++} ++ ++/** ++ * One occurrence, with its payload as the event's `payload` schema types it. ++ * `eventId` stays the same however often the occurrence is delivered. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventOccurrence { ++ readonly eventId: string ++ readonly timestamp: string ++ readonly data: A ++ readonly _meta?: Readonly> | undefined ++} ++ ++/** ++ * A poll's answer. `truncated` says delivery started later than the cursor, ++ * and `hasMore` that `maxEvents` cut the batch short. `nextPollMs` defaults ++ * to 30 seconds. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventPollResult { ++ readonly events: ReadonlyArray> ++ readonly cursor: string | null ++ readonly truncated?: boolean | undefined ++ readonly hasMore?: boolean | undefined ++ readonly nextPollMs?: number | undefined ++} ++ ++/** ++ * What a push stream carries: an occurrence and the cursor after it; a ++ * position checked without a match, which the next heartbeat reports; a gap, ++ * sent as a fresh `notifications/events/active` with `truncated`; or an error ++ * that leaves the stream open. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventStreamItem = ++ | ({ readonly _tag: "Event"; readonly cursor: string | null } & EventOccurrence) ++ | { readonly _tag: "Position"; readonly cursor: string | null } ++ | { readonly _tag: "Gap"; readonly cursor: string | null } ++ | { readonly _tag: "Error"; readonly error: EventError } ++ ++/** ++ * An accepted push subscription: where it starts, and its items. A failure ++ * of `items` ends it. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventSubscription { ++ readonly cursor: string | null ++ readonly truncated?: boolean | undefined ++ readonly items: Stream.Stream, EventError, R> ++} ++ ++/** ++ * Options for {@link registerEvent} and {@link event}. ++ * ++ * **Details** ++ * ++ * `parameters` types the subscription arguments, an empty object by default, ++ * and `payload` the occurrences' `data`; both are advertised as JSON Schema ++ * by `events/list`. `poll` offers poll delivery and `stream` push delivery, ++ * and at least one is required. Webhook delivery is not supported, so ++ * `events/subscribe` answers `Unsupported`. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventOptions, Payload extends Schema.Codec, R> { ++ readonly name: string ++ readonly description?: string | undefined ++ readonly parameters?: Params | undefined ++ readonly payload: Payload ++ readonly _meta?: Readonly> | undefined ++ readonly annotations?: Context.Context | undefined ++ readonly poll?: ++ | (( ++ args: Params["Type"], ++ request: EventPollRequest ++ ) => Effect.Effect, EventError, R>) ++ | undefined ++ readonly stream?: ++ | (( ++ args: Params["Type"], ++ request: EventStreamRequest ++ ) => Effect.Effect, EventError, R | Scope.Scope>) ++ | undefined ++} ++ ++const DEFAULT_NEXT_POLL_MS = 30_000 ++ ++/** ++ * Registers an event type under the MCP Events extension (SEP-3415). ++ * ++ * **Details** ++ * ++ * The server declares `io.modelcontextprotocol/events` on revision ++ * `2026-07-28` once any event type is registered, and answers `events/list`, ++ * `events/poll` and `events/stream`. A push stream runs `stream` for its ++ * lifetime inside the request's middleware, sends heartbeats carrying the ++ * last cursor, and ends when the client goes away. Services read by `poll` ++ * and `stream` are request-level, as for tools. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const registerEvent: < ++ Params extends Schema.Codec = Schema.Struct<{}>, ++ Payload extends Schema.Codec = Schema.Codec, ++ R = never ++>(options: EventOptions) => Effect.Effect> = ++ Effect.fnUntraced(function*(options: EventOptions, Schema.Codec, any>) { ++ const { name, poll, stream } = options ++ if (poll === undefined && stream === undefined) { ++ return yield* Effect.die(new Cause.IllegalArgumentError(`Event ${name}: give it poll, stream or both`)) ++ } ++ const registry = yield* McpServer ++ const { core, globalMiddleware } = internalState.get(registry)! ++ const services = yield* Effect.context() ++ const annotations = options.annotations ?? Context.empty() ++ const { invoke, visible } = makeInvoke(services, globalMiddleware) ++ const parameters = options.parameters ?? Schema.Struct({}) ++ const decodeArguments = Schema.decodeUnknownEffect(Schema.toCodecJson(parameters)) ++ const encodePayload = Schema.encodeUnknownEffect(Schema.toCodecJson(options.payload)) ++ const argumentsOf = (args: unknown) => ++ decodeArguments(args).pipe(Effect.mapError((error) => new InvalidParams({ message: error.message }))) ++ const encodeEvent = (event: EventOccurrence) => ++ encodePayload(event.data).pipe( ++ Effect.flatMap((data) => Predicate.isReadonlyObject(data) ? Effect.succeed(data) : Effect.fail(data)), ++ Effect.map((data): McpCore.EncodedEvent => ({ ++ eventId: event.eventId, ++ timestamp: event.timestamp, ++ data, ++ ...(event._meta === undefined ? {} : { _meta: event._meta }) ++ })), ++ Effect.mapError(() => new InternalError({ message: `Event '${name}' payload failed to encode` })) ++ ) ++ yield* core.events.register({ ++ descriptor: { ++ name, ++ ...(options.description === undefined ? {} : { description: options.description }), ++ delivery: [...(poll === undefined ? [] : ["poll" as const]), ...(stream === undefined ? [] : ["push" as const])], ++ inputSchema: toolJsonSchema(parameters, false) as Record, ++ payloadSchema: toolJsonSchema(options.payload, false) as Record, ++ ...(options._meta === undefined ? {} : { _meta: options._meta }) ++ }, ++ isVisible: isEnabled(annotations), ++ visible: visible("events/list", name), ++ poll: poll === undefined ? undefined : (request, invocation) => ++ invoke( ++ Effect.gen(function*() { ++ const result = yield* poll(yield* argumentsOf(request.arguments), { ++ cursor: request.cursor, ++ maxAgeMs: request.maxAgeMs, ++ maxEvents: request.maxEvents ++ }) ++ return { ++ events: yield* Effect.forEach(result.events, encodeEvent), ++ cursor: result.cursor, ++ truncated: result.truncated ?? false, ++ hasMore: result.hasMore ?? false, ++ nextPollMs: result.nextPollMs ?? DEFAULT_NEXT_POLL_MS ++ } ++ }), ++ invocation, ++ { method: "events/poll", target: name, payload: request } ++ ), ++ stream: stream === undefined ? undefined : (request, invocation, deliver) => ++ invoke( ++ Effect.scoped(Effect.gen(function*() { ++ const subscription = yield* stream(yield* argumentsOf(request.arguments), { ++ cursor: request.cursor, ++ maxAgeMs: request.maxAgeMs ++ }) ++ // The items run on the delivery fiber, so they keep this request's services. ++ const context = yield* Effect.context() ++ const items = subscription.items.pipe( ++ Stream.mapEffect((item): Effect.Effect => ++ item._tag === "Event" ++ ? encodeEvent(item).pipe( ++ Effect.map((event) => ({ ...event, _tag: "Event" as const, cursor: item.cursor })), ++ Effect.catch((error) => Effect.succeed({ _tag: "Error" as const, error })) ++ ) ++ : Effect.succeed(item) ++ ), ++ Stream.provideContext(context) ++ ) ++ yield* deliver({ cursor: subscription.cursor, truncated: subscription.truncated ?? false, items }) ++ })), ++ invocation, ++ { method: "events/stream", target: name, payload: request } ++ ) ++ }) ++ }) as any ++ ++/** ++ * Creates a layer that registers an event type under the MCP Events ++ * extension (SEP-3415). ++ * ++ * @see {@link registerEvent} for the Effect-level event registration API ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const event = < ++ Params extends Schema.Codec = Schema.Struct<{}>, ++ Payload extends Schema.Codec = Schema.Codec, ++ R = never ++>(options: EventOptions): Layer.Layer> => ++ Layer.effectDiscard(registerEvent(options)) ++ + /** + * Registers an MCP prompt from an Effect program. + * +diff --git a/src/ai/internal/mcpCore.ts b/src/ai/internal/mcpCore.ts +index 643982d..597701f 100644 +--- a/src/ai/internal/mcpCore.ts ++++ b/src/ai/internal/mcpCore.ts +@@ -8,6 +8,7 @@ import * as Data from "../../Data.ts" + import * as Effect from "../../Effect.ts" + import type * as McpProtocol from "../McpProtocol.ts" + import * as McpSchema from "../McpSchema.ts" ++import type * as Stream from "../../Stream.ts" + + /** + * @internal +@@ -330,6 +331,118 @@ export interface SkillRegistration { + readonly directory: (uri: string) => ReadonlyArray | undefined + } + ++/** ++ * A failure an event handler reports to the client as a JSON-RPC error, such ++ * as `McpSchema.Forbidden` or `McpSchema.InvalidParams`. ++ * ++ * @internal ++ */ ++export interface EventFailure { ++ readonly code: number ++ readonly message: string ++ readonly data?: unknown ++} ++ ++/** ++ * @internal ++ */ ++export interface EventPollRequest { ++ readonly arguments: Readonly> ++ readonly cursor: string | null ++ readonly maxAgeMs?: number | undefined ++ readonly maxEvents?: number | undefined ++} ++ ++/** ++ * An occurrence with its payload already encoded for the wire. ++ * ++ * @internal ++ */ ++export interface EncodedEvent { ++ readonly eventId: string ++ readonly timestamp: string ++ readonly data: Readonly> ++ readonly _meta?: Readonly> | undefined ++} ++ ++/** ++ * @internal ++ */ ++export interface EventPollOutcome { ++ readonly events: ReadonlyArray ++ readonly cursor: string | null ++ readonly truncated: boolean ++ readonly hasMore: boolean ++ readonly nextPollMs: number ++} ++ ++/** ++ * @internal ++ */ ++export interface EventStreamRequest { ++ readonly arguments: Readonly> ++ readonly cursor: string | null ++ readonly maxAgeMs?: number | undefined ++} ++ ++/** ++ * What a push stream carries after `notifications/events/active`: occurrences, ++ * a position checked without a match (carried by the next heartbeat), a gap ++ * (a fresh `active` with `truncated`), or a recoverable error. ++ * ++ * @internal ++ */ ++export type EventStreamItem = ++ | ({ readonly _tag: "Event"; readonly cursor: string | null } & EncodedEvent) ++ | { readonly _tag: "Position"; readonly cursor: string | null } ++ | { readonly _tag: "Gap"; readonly cursor: string | null } ++ | { readonly _tag: "Error"; readonly error: EventFailure } ++ ++/** ++ * A push subscription the handler accepted. A failure of `items` ends it with ++ * `notifications/events/terminated`. ++ * ++ * @internal ++ */ ++export interface EventSubscription { ++ readonly cursor: string | null ++ readonly truncated: boolean ++ readonly items: Stream.Stream ++} ++ ++/** ++ * @internal ++ */ ++export interface EventRegistration { ++ readonly descriptor: McpSchema.EventDescriptor ++ readonly isVisible: (profile: NegotiatedProtocolProfile) => boolean ++ readonly visible?: Visible | undefined ++ readonly poll?: ++ | (( ++ request: EventPollRequest, ++ invocation: McpInvocation ++ ) => Effect.Effect) ++ | undefined ++ // Runs for the subscription's lifetime: `deliver` takes over once the ++ // handler accepts it, so a failure before that is the request's error. ++ readonly stream?: ++ | (( ++ request: EventStreamRequest, ++ invocation: McpInvocation, ++ deliver: (subscription: EventSubscription) => Effect.Effect ++ ) => Effect.Effect) ++ | undefined ++} ++ ++/** ++ * @internal ++ */ ++export interface Events { ++ readonly register: (registration: EventRegistration) => Effect.Effect ++ readonly list: (invocation: McpInvocation) => Effect.Effect, RequestRejected> ++ readonly get: (name: string, invocation: McpInvocation) => Effect.Effect ++} ++ + /** + * @internal + */ +@@ -507,11 +620,13 @@ export interface McpCore { + readonly prompts: Prompts + readonly completions: Completions + readonly skills: Skills ++ readonly events: Events + readonly registrationPresence: Effect.Effect<{ + readonly tools: boolean + readonly resources: boolean + readonly prompts: boolean + readonly skills: boolean ++ readonly events: boolean + }> + } + +@@ -523,6 +638,12 @@ export interface McpCore { + */ + export type Visible = (invocation: McpInvocation) => Effect.Effect + ++/** ++ * @internal ++ */ ++export const eventNotFound = (name: string): McpSchema.NotFound => ++ new McpSchema.NotFound({ message: `Event '${name}' not found`, data: { kind: "event" } }) ++ + // Whether one skill directory contains the other, or both are the same. + const skillsOverlap = (a: string, b: string): boolean => { + const rootA = a.slice(0, -"/SKILL.md".length) +@@ -539,6 +660,7 @@ export const make: Effect.Effect = Effect.sync(() => { + const resourceTemplateRegistrations: Array = [] + const promptRegistrations = new Map() + const skillRegistrations = new Map() ++ const eventRegistrations = new Map() + const skillFiles = new Set() + const completionRegistrations = new Map< + string, +@@ -717,12 +839,28 @@ export const make: Effect.Effect = Effect.sync(() => { + }) + } + ++ const events: Events = { ++ register: (registration) => ++ Effect.sync(() => { ++ eventRegistrations.set(registration.descriptor.name, registration) ++ }), ++ list: (invocation) => filterList(eventRegistrations.values(), invocation), ++ get: (name, invocation) => ++ Effect.suspend(() => { ++ const registration = eventRegistrations.get(name) ++ return registration !== undefined && registration.isVisible(invocation.protocol) ++ ? Effect.succeed(registration) ++ : Effect.fail(eventNotFound(name)) ++ }) ++ } ++ + const registrationPresence = Effect.sync(() => ({ + tools: registrations.size > 0, + resources: resourceRegistrations.length > 0 || resourceTemplateRegistrations.length > 0, + prompts: promptRegistrations.size > 0, +- skills: skillRegistrations.size > 0 ++ skills: skillRegistrations.size > 0, ++ events: eventRegistrations.size > 0 + })) + +- return { tools, resources, prompts, completions, skills, registrationPresence } ++ return { tools, resources, prompts, completions, skills, events, registrationPresence } + }) +diff --git a/src/ai/internal/mcpEvents.ts b/src/ai/internal/mcpEvents.ts +new file mode 100644 +index 0000000..54b2ca8 +--- /dev/null ++++ b/src/ai/internal/mcpEvents.ts +@@ -0,0 +1,315 @@ ++/** ++ * The Events extension (SEP-3415): wire schemas on revision 2026-07-28 and ++ * the delivery loop behind a push stream. ++ */ ++import * as Cause from "../../Cause.ts" ++import * as Clock from "../../Clock.ts" ++import * as Duration from "../../Duration.ts" ++import * as Effect from "../../Effect.ts" ++import * as Option from "../../Option.ts" ++import * as Queue from "../../Queue.ts" ++import * as Result from "../../Result.ts" ++import * as Rpc from "../../rpc/Rpc.ts" ++import * as RpcGroup from "../../rpc/RpcGroup.ts" ++import * as Schema from "../../Schema.ts" ++import * as Stream from "../../Stream.ts" ++import * as PublicMcpSchema from "../McpSchema.ts" ++import type * as McpCore from "./mcpCore.ts" ++import * as McpProtocol from "./mcpProtocol.ts" ++import * as Stateless from "./mcpSchema/v2026_07_28.ts" ++ ++/** ++ * @internal ++ */ ++export const EXTENSION_ID = "io.modelcontextprotocol/events" ++ ++/** ++ * Adds the extension declaration while any event type is registered. The ++ * server sends no `notifications/events/list_changed`, so its settings object ++ * is empty. ++ * ++ * @internal ++ */ ++export const declareExtension = ( ++ extensions: Readonly> | undefined, ++ servesEvents: boolean ++): Readonly> | undefined => ++ servesEvents ? { ...extensions, [EXTENSION_ID]: {} } : extensions ++ ++const methodNotFound = (method: string) => ++ new McpProtocol.ProtocolError({ ++ code: PublicMcpSchema.METHOD_NOT_FOUND_ERROR_CODE, ++ message: `Method not found: ${method}` ++ }) ++ ++/** ++ * Fails with `Method not found` while no event type is registered, as a ++ * server that does not declare the extension. ++ * ++ * @internal ++ */ ++export const requireEvents = (core: McpCore.McpCore, method: string) => ++ Effect.flatMap( ++ core.registrationPresence, ++ (presence) => presence.events ? Effect.void : Effect.fail(methodNotFound(method)) ++ ) ++ ++/** ++ * @internal ++ */ ++export const unsupportedDelivery = (value: PublicMcpSchema.EventDelivery) => ++ new PublicMcpSchema.Unsupported({ ++ message: `Delivery mode '${value}' is not supported for this event`, ++ data: { feature: "deliveryMode", value } ++ }) ++ ++// ============================================================================= ++// Wire schemas ++// ============================================================================= ++ ++const optional = Stateless.optional ++const Cursor = Schema.NullOr(Schema.String) ++const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)) ++ ++/** ++ * @internal ++ */ ++export const ListEventsResult = Schema.StructWithRest( ++ Schema.Struct({ ...Stateless.PaginatedResult, events: Schema.Array(PublicMcpSchema.EventDescriptor) }), ++ [Stateless.UnknownObject] ++) ++ ++/** ++ * @internal ++ */ ++export class ListEvents extends Rpc.make("events/list", { ++ success: ListEventsResult, ++ error: Stateless.McpError, ++ payload: Stateless.PaginatedRequestParams ++}) {} ++ ++const SubscriptionParams = { ++ ...Stateless.RequestParams.fields, ++ name: Schema.String, ++ arguments: optional(Stateless.UnknownObject), ++ cursor: optional(Cursor), ++ maxAgeMs: optional(NonNegativeInt) ++} ++ ++/** ++ * @internal ++ */ ++export const PollEventsResult = Schema.StructWithRest( ++ Schema.Struct({ ++ ...Stateless.ResultMeta, ++ events: Schema.Array(PublicMcpSchema.EventOccurrence), ++ cursor: Cursor, ++ truncated: Schema.Boolean, ++ hasMore: Schema.Boolean, ++ nextPollMs: NonNegativeInt ++ }), ++ [Stateless.UnknownObject] ++) ++ ++/** ++ * @internal ++ */ ++export class PollEvents extends Rpc.make("events/poll", { ++ success: PollEventsResult, ++ error: Stateless.McpError, ++ payload: { ...SubscriptionParams, maxEvents: optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(1))) } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class StreamEvents extends Rpc.make("events/stream", { ++ success: Stateless.SubscriptionsListenResult, ++ error: Stateless.McpError, ++ payload: { ...SubscriptionParams, heartbeatMs: optional(NonNegativeInt) } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class SubscribeEvents extends Rpc.make("events/subscribe", { ++ success: Schema.StructWithRest( ++ Schema.Struct({ ++ ...Stateless.ResultMeta, ++ id: Schema.String, ++ refreshBefore: Schema.NullOr(Schema.String), ++ cursor: Cursor, ++ truncated: Schema.Boolean ++ }), ++ [Stateless.UnknownObject] ++ ), ++ error: Stateless.McpError, ++ payload: { ++ ...SubscriptionParams, ++ delivery: Stateless.UnknownObject, ++ ttlMs: optional(Schema.NullOr(NonNegativeInt)) ++ } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class UnsubscribeEvents extends Rpc.make("events/unsubscribe", { ++ success: Schema.StructWithRest(Schema.Struct(Stateless.ResultMeta), [Stateless.UnknownObject]), ++ error: Stateless.McpError, ++ payload: { ++ ...Stateless.RequestParams.fields, ++ name: Schema.String, ++ arguments: optional(Stateless.UnknownObject), ++ delivery: Stateless.UnknownObject ++ } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class EventsActiveNotification extends Rpc.make("notifications/events/active", { ++ payload: { ...Stateless.NotificationParams.fields, cursor: Cursor, truncated: Schema.Boolean, heartbeatMs: NonNegativeInt } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class EventsEventNotification extends Rpc.make("notifications/events/event", { ++ payload: { ...PublicMcpSchema.EventOccurrence.fields, ...Stateless.NotificationParams.fields } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class EventsHeartbeatNotification extends Rpc.make("notifications/events/heartbeat", { ++ payload: { ...Stateless.NotificationParams.fields, cursor: Cursor } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class EventsErrorNotification extends Rpc.make("notifications/events/error", { ++ payload: { ...Stateless.NotificationParams.fields, error: Stateless.McpError } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class EventsTerminatedNotification extends Rpc.make("notifications/events/terminated", { ++ payload: { ...Stateless.NotificationParams.fields, error: Stateless.McpError } ++}) {} ++ ++/** ++ * The extension's requests on revision 2026-07-28. ++ * ++ * @internal ++ */ ++export class StatelessRpcs ++ extends RpcGroup.make(ListEvents, PollEvents, StreamEvents, SubscribeEvents, UnsubscribeEvents) ++{} ++ ++/** ++ * The notifications a push stream carries. ++ * ++ * @internal ++ */ ++export class ServerNotificationRpcs extends RpcGroup.make( ++ EventsActiveNotification, ++ EventsEventNotification, ++ EventsHeartbeatNotification, ++ EventsErrorNotification, ++ EventsTerminatedNotification ++) {} ++ ++// ============================================================================= ++// Push delivery ++// ============================================================================= ++ ++const DEFAULT_HEARTBEAT_MS = 30_000 ++const MIN_HEARTBEAT_MS = 1_000 ++const MAX_HEARTBEAT_MS = 300_000 ++// Occurrences the handler may run ahead of a slow client before it waits. ++const PENDING_ITEMS = 16 ++ ++/** ++ * The heartbeat interval granted for a suggested one. ++ * ++ * @internal ++ */ ++export const grantHeartbeat = (suggested: number | undefined): number => ++ Math.min(MAX_HEARTBEAT_MS, Math.max(MIN_HEARTBEAT_MS, suggested ?? DEFAULT_HEARTBEAT_MS)) ++ ++const isJson = Schema.is(Schema.Json) ++ ++/** ++ * @internal ++ */ ++export const wireError = (failure: McpCore.EventFailure): Stateless.McpError => ({ ++ code: failure.code, ++ message: failure.message, ++ ...(failure.data !== undefined && isJson(failure.data) ? { data: failure.data } : {}) ++}) ++ ++/** ++ * Sends `notifications/events/active`, then each occurrence, and a heartbeat ++ * with the position checked so far whenever `heartbeatMs` passes without ++ * another message. A failure of the subscription's items ends it with ++ * `notifications/events/terminated`. `send` adds the subscription id. ++ * ++ * @internal ++ */ ++export const deliver = Effect.fnUntraced(function*(options: { ++ readonly name: string ++ readonly subscription: McpCore.EventSubscription ++ readonly heartbeatMs: number ++ readonly send: (tag: string, payload: Readonly>) => Effect.Effect ++}) { ++ const { heartbeatMs, name, subscription } = options ++ let cursor = subscription.cursor ++ // Measured from the last message sent: a Position changes the cursor but sends nothing. ++ let sentAt = 0 ++ const send = (tag: string, payload: Readonly>) => ++ options.send(tag, payload).pipe(Effect.andThen(Clock.currentTimeMillis), Effect.map((at) => { ++ sentAt = at ++ })) ++ const active = (truncated: boolean) => send(EventsActiveNotification._tag, { cursor, truncated, heartbeatMs }) ++ yield* active(subscription.truncated) ++ const items = yield* Stream.toQueue(subscription.items, { capacity: PENDING_ITEMS }) ++ while (true) { ++ const wait = Math.max(0, sentAt + heartbeatMs - (yield* Clock.currentTimeMillis)) ++ const next = yield* Queue.take(items).pipe(Effect.timeoutOption(Duration.millis(wait)), Effect.result) ++ if (Result.isFailure(next)) { ++ if (!Cause.isDone(next.failure)) { ++ yield* send(EventsTerminatedNotification._tag, { error: wireError(next.failure) }) ++ } ++ return ++ } ++ if (Option.isNone(next.success)) { ++ yield* send(EventsHeartbeatNotification._tag, { cursor }) ++ continue ++ } ++ const item = next.success.value ++ switch (item._tag) { ++ case "Event": { ++ cursor = item.cursor ++ const { _meta, _tag, ...occurrence } = item ++ yield* send(EventsEventNotification._tag, { ...occurrence, name, ...(_meta === undefined ? {} : { _meta }) }) ++ break ++ } ++ case "Position": { ++ cursor = item.cursor ++ break ++ } ++ case "Gap": { ++ cursor = item.cursor ++ yield* active(true) ++ break ++ } ++ case "Error": { ++ yield* send(EventsErrorNotification._tag, { error: wireError(item.error) }) ++ break ++ } ++ } ++ } ++}, Effect.scoped) +diff --git a/src/ai/internal/mcpProtocol.ts b/src/ai/internal/mcpProtocol.ts +index 5393651..f40915b 100644 +--- a/src/ai/internal/mcpProtocol.ts ++++ b/src/ai/internal/mcpProtocol.ts +@@ -484,6 +484,7 @@ export interface HandlerInstallationContext { + readonly resources: boolean + readonly prompts: boolean + readonly skills: boolean ++ readonly events: boolean + }> + } + +diff --git a/src/ai/internal/mcpProtocol/v2026_07_28.ts b/src/ai/internal/mcpProtocol/v2026_07_28.ts +index a701ec8..9b9a6fd 100644 +--- a/src/ai/internal/mcpProtocol/v2026_07_28.ts ++++ b/src/ai/internal/mcpProtocol/v2026_07_28.ts +@@ -22,6 +22,7 @@ import type * as Types from "../../../Types.ts" + import type * as PublicMcpProtocol from "../../McpProtocol.ts" + import * as PublicMcpSchema from "../../McpSchema.ts" + import * as McpCore from "../mcpCore.ts" ++import * as McpEvents from "../mcpEvents.ts" + import * as McpProtocol from "../mcpProtocol.ts" + import * as McpSchema from "../mcpSchema/v2026_07_28.ts" + import * as McpSkills from "../mcpSkills.ts" +@@ -344,7 +345,11 @@ const unsupported = ( + /** + * @internal + */ +-export const handlerRpcs = McpSchema.ClientRequestRpcs.merge(McpSchema.ClientNotificationRpcs, McpSkills.StatelessRpcs) ++export const handlerRpcs = McpSchema.ClientRequestRpcs.merge( ++ McpSchema.ClientNotificationRpcs, ++ McpSkills.StatelessRpcs, ++ McpEvents.StatelessRpcs ++) + + /** + * @internal +@@ -370,6 +375,8 @@ export const makeHandlers = ( + const decodeListSkillsResult = Schema.decodeUnknownEffect(McpSkills.ListSkillsResult) + const decodeGetSkillResult = Schema.decodeUnknownEffect(McpSkills.GetSkillResult) + const decodeReadResourceDirectoryResult = Schema.decodeUnknownEffect(McpSkills.ReadResourceDirectoryResult) ++ const decodeListEventsResult = Schema.decodeUnknownEffect(McpEvents.ListEventsResult) ++ const decodePollEventsResult = Schema.decodeUnknownEffect(McpEvents.PollEventsResult) + const sendNotification = context.sendNotification + const supportsSubscriptions = sendNotification !== undefined + // Older adapters accept arbitrary JSON; this binding requires extension settings objects. +@@ -384,7 +391,10 @@ export const makeHandlers = ( + } + const getDiscovery = Effect.map(context.registrationPresence, (presence) => { + const capabilities: Types.Mutable = { completions: {}, logging: {} } +- const declared = McpSkills.declareExtension(extensions, presence.skills) ++ const declared = McpEvents.declareExtension( ++ McpSkills.declareExtension(extensions, presence.skills), ++ presence.events ++ ) + if (declared !== undefined) capabilities.extensions = declared + if (presence.tools) capabilities.tools = { listChanged: supportsSubscriptions } + if (presence.resources) { +@@ -393,6 +403,24 @@ export const makeHandlers = ( + if (presence.prompts) capabilities.prompts = { listChanged: supportsSubscriptions } + return { supportedVersions: context.supportedVersions, capabilities, serverInfo: context.serverInfo } + }) ++ const requireEvents = (method: string) => ++ McpEvents.requireEvents(core, method).pipe(Effect.catch((error) => failWithHttpStatus(404, error))) ++ // The event type's `x-mcp-header` arguments must match their headers, as a tool's do. ++ const validateEventHeaders = Effect.fnUntraced(function*( ++ registration: McpCore.EventRegistration, ++ args: unknown ++ ) { ++ const httpRequest = yield* Effect.serviceOption(HttpServerRequest.HttpServerRequest) ++ if (Option.isSome(httpRequest)) { ++ yield* validateParameterHeaders(registration.descriptor.inputSchema, args, httpRequest.value.headers) ++ } ++ }) ++ // Webhook delivery is not implemented, so subscribing refuses every event type. ++ const refuseWebhook = Effect.fnUntraced(function*(method: string, name: string) { ++ yield* requireEvents(method) ++ yield* core.events.get(name, yield* getInvocation) ++ return yield* McpEvents.unsupportedDelivery("webhook") ++ }) + const requireSkills = (method: string) => + McpSkills.requireSkills(core, method).pipe( + Effect.catch((error) => failWithHttpStatus(404, error)) +@@ -728,6 +756,92 @@ export const makeHandlers = ( + const result = yield* projectCompleteResult({ ...cacheHint("skills"), resources }, context.serverInfo) + return yield* decodeReadResourceDirectoryResult(result) + }, Effect.mapError(projectError)), ++ "events/list": Effect.fnUntraced(function*(request: typeof McpEvents.ListEvents.payloadSchema.Type) { ++ yield* requireEvents("events/list") ++ yield* McpProtocol.rejectCursor(request.cursor) ++ const events = yield* core.events.list(yield* getInvocation) ++ // Without a notification channel nothing can be pushed. ++ const offered = supportsSubscriptions ? events : events.flatMap((event) => { ++ const delivery = event.delivery.filter((mode) => mode !== "push") ++ return delivery.length === 0 ? [] : [{ ...event, delivery }] ++ }) ++ const result = yield* projectCompleteResult({ events: offered }, context.serverInfo) ++ return yield* decodeListEventsResult(result) ++ }, Effect.mapError(projectError)), ++ "events/poll": Effect.fnUntraced(function*(request: typeof McpEvents.PollEvents.payloadSchema.Type) { ++ yield* requireEvents("events/poll") ++ const invocation = yield* getInvocation ++ const registration = yield* core.events.get(request.name, invocation) ++ if (registration.poll === undefined) { ++ return yield* McpEvents.unsupportedDelivery("poll") ++ } ++ yield* validateEventHeaders(registration, request.arguments) ++ const outcome = yield* registration.poll({ ++ arguments: request.arguments ?? {}, ++ cursor: request.cursor ?? null, ++ maxAgeMs: request.maxAgeMs, ++ maxEvents: request.maxEvents ++ }, invocation) ++ const result = yield* projectCompleteResult({ ++ events: outcome.events.map((event) => ++ omitUndefined({ ++ eventId: event.eventId, ++ name: request.name, ++ timestamp: event.timestamp, ++ data: event.data, ++ _meta: event._meta ++ }) ++ ), ++ cursor: outcome.cursor, ++ truncated: outcome.truncated, ++ hasMore: outcome.hasMore, ++ nextPollMs: outcome.nextPollMs ++ }, context.serverInfo) ++ return yield* decodePollEventsResult(result) ++ }, Effect.mapError(projectError)), ++ "events/stream": Effect.fnUntraced(function*( ++ request: typeof McpEvents.StreamEvents.payloadSchema.Type, ++ { client, requestId }: { readonly client: Rpc.ServerClient; readonly requestId: RpcMessage.RequestId } ++ ) { ++ yield* requireEvents("events/stream") ++ const invocation = yield* getInvocation ++ const registration = yield* core.events.get(request.name, invocation) ++ if (registration.stream === undefined || sendNotification === undefined) { ++ return yield* McpEvents.unsupportedDelivery("push") ++ } ++ yield* validateEventHeaders(registration, request.arguments) ++ const subscriptionMetadata = { "io.modelcontextprotocol/subscriptionId": requestId } ++ const send = (tag: string, payload: Readonly>) => ++ sendNotification(McpSchema.protocolVersion, client.id, { ++ tag, ++ payload: { ++ ...payload, ++ _meta: { ...(Predicate.isReadonlyObject(payload._meta) ? payload._meta : {}), ...subscriptionMetadata } ++ } ++ }) ++ const heartbeatMs = McpEvents.grantHeartbeat(request.heartbeatMs) ++ yield* Effect.raceFirst( ++ registration.stream( ++ { arguments: request.arguments ?? {}, cursor: request.cursor ?? null, maxAgeMs: request.maxAgeMs }, ++ invocation, ++ (subscription) => McpEvents.deliver({ name: request.name, subscription, heartbeatMs, send }) ++ ), ++ context.awaitClientEnd ?? Effect.never ++ ) ++ const encodedServerInfo = yield* encodeImplementation(context.serverInfo) ++ return McpSchema.SubscriptionsListenResult.make({ ++ _meta: { ...subscriptionMetadata, "io.modelcontextprotocol/serverInfo": encodedServerInfo }, ++ resultType: "complete" ++ }) ++ }, Effect.mapError(projectError)), ++ "events/subscribe": Effect.fnUntraced(function*(request: typeof McpEvents.SubscribeEvents.payloadSchema.Type) { ++ return yield* refuseWebhook("events/subscribe", request.name) ++ }, Effect.mapError(projectError)), ++ "events/unsubscribe": Effect.fnUntraced(function*( ++ request: typeof McpEvents.UnsubscribeEvents.payloadSchema.Type ++ ) { ++ return yield* refuseWebhook("events/unsubscribe", request.name) ++ }, Effect.mapError(projectError)), + "notifications/cancelled": Effect.fnUntraced(function*( + _request: typeof McpSchema.CancelledNotification.payloadSchema.Type + ) { +@@ -751,10 +865,10 @@ const runtime = { + export const protocol = McpProtocol.make({ + protocolVersion: McpSchema.protocolVersion, + runtime, +- clientRpcs: McpSchema.ClientRpcs.merge(McpSkills.StatelessRpcs), ++ clientRpcs: McpSchema.ClientRpcs.merge(McpSkills.StatelessRpcs, McpEvents.StatelessRpcs), + clientNotificationRpcs: McpSchema.ClientNotificationRpcs, + serverRequestRpcs: McpSchema.ServerRequestRpcs, +- serverNotificationRpcs: McpSchema.ServerNotificationRpcs, ++ serverNotificationRpcs: McpSchema.ServerNotificationRpcs.merge(McpEvents.ServerNotificationRpcs), + handlerRpcs, + makeHandlers, + toReverseClient: () => ({ +diff --git a/src/ai/internal/mcpRuntime.ts b/src/ai/internal/mcpRuntime.ts +index 9d4c96e..eb0590c 100644 +--- a/src/ai/internal/mcpRuntime.ts ++++ b/src/ai/internal/mcpRuntime.ts +@@ -53,6 +53,10 @@ const routingNameKey = (method: string): "name" | "uri" | undefined => { + switch (method) { + case "tools/call": + case "prompts/get": ++ case "events/poll": ++ case "events/stream": ++ case "events/subscribe": ++ case "events/unsubscribe": + return "name" + case "resources/read": + return "uri" +@@ -479,7 +483,9 @@ export const make = Effect.fnUntraced(function*( + return { + _tag: "Accepted", + acknowledge: !isRequest || !hasId, +- isSubscription: Predicate.hasProperty(input, "method") && input.method === "subscriptions/listen" ++ // A push subscription stays open until cancelled, so it is never a plain response. ++ isSubscription: Predicate.hasProperty(input, "method") && ++ (input.method === "subscriptions/listen" || input.method === "events/stream") + } + }, + effectLogLevel: (clientId, headers, fallback) => stateful?.effectLogLevel(clientId, headers, fallback) ?? fallback, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 863e897d51b22..471dec4be9987 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -377,6 +377,7 @@ patchedDependencies: alchemy@2.0.0-beta.85: 07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd app-builder-lib@26.16.1: 0fbe9ae51783f5768ebe197d12d1fdb7d477a08c92e5db2f6356bcce62613c53 dbus-next@0.10.2: cfff57561b0ee59b5addb3b2e6c6f20906e967507a530ab67e8db8108e520ba4 + effect@4.1.5: 76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337 electron-updater@6.8.9: 91b5648a7eed42761523ef542ebb7e548b037eda41d66533c8152ac65ac72155 expo-audio@58.0.11: 92414572bf24ffd0c45de44c45f11f6c48bc0af13b8b9a56f77a67bc0e915c1e expo-modules-core@58.0.30: f0b0fd100550ed76e5c25b4d13eb7c9ff62825f8f197c53edf7bf447c50c9fb7 @@ -434,7 +435,7 @@ importers: version: 0.15.4 '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@napi-rs/keyring': specifier: ^1.3.0 version: 1.3.0 @@ -458,7 +459,7 @@ importers: version: 0.10.2(patch_hash=cfff57561b0ee59b5addb3b2e6c6f20906e967507a530ab67e8db8108e520ba4) effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) electron: specifier: 44.10.1 version: 44.10.1(supports-color@8.1.1) @@ -489,7 +490,7 @@ importers: devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -550,7 +551,7 @@ importers: version: 0.4.4(patch_hash=7a808b92da8460750b85818552e13be3fb73d111691c7db76965970351e124e4)(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)(supports-color@8.1.1)(typescript@6.0.3) '@effect/atom-react': specifier: 4.1.5 - version: 4.1.5(effect@4.1.5)(react@19.3.0)(scheduler@0.28.0) + version: 4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react@19.3.0)(scheduler@0.28.0) '@expo-google-fonts/dm-sans': specifier: ^0.4.2 version: 0.4.2 @@ -628,7 +629,7 @@ importers: version: 8.0.3 effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) expo: specifier: 58.0.23 version: 58.0.23(d226faf1ca90e630d8c56a2108dee32d) @@ -815,10 +816,10 @@ importers: version: 7.29.7(supports-color@8.1.1) '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@pierre/trees': specifier: 1.0.0-beta.6 version: 1.0.0-beta.6(@pierre/theme@2.0.0)(@shikijs/themes@4.2.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(shiki@4.2.0) @@ -860,10 +861,10 @@ importers: version: 1.4.2(patch_hash=d9747bbf2d8fa7529b74b690087b70b3b2662fcba0d4d3148afc3b956171b54a)(zod@4.6.7) '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/platform-node-shared': specifier: 4.1.5 - version: 4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6) + version: 4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6) '@ff-labs/fff-node': specifier: 0.11.0 version: 0.11.0(patch_hash=93f62a76399b435a76588b2bef237db0a1e85880c1ac0d0759c416e9cc579252) @@ -944,7 +945,7 @@ importers: version: 8.0.3 effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) ffi-rs: specifier: 1.3.2 version: 1.3.2 @@ -984,10 +985,10 @@ importers: devDependencies: '@effect/graphql-generator': specifier: 'catalog:' - version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5) + version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@handy-computer/models': specifier: 0.2.3 version: 0.2.3 @@ -1092,7 +1093,7 @@ importers: version: 3.2.2(react@19.3.0) '@effect/atom-react': specifier: 4.1.5 - version: 4.1.5(effect@4.1.5)(react@19.3.0)(scheduler@0.28.0) + version: 4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react@19.3.0)(scheduler@0.28.0) '@fontsource-variable/inter': specifier: ^5.3.0 version: 5.3.0 @@ -1197,7 +1198,7 @@ importers: version: 3.4.17 effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) entities: specifier: 8.1.0 version: 8.1.0 @@ -1267,10 +1268,10 @@ importers: devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@tailwindcss/vite': specifier: 4.3.3 version: 4.3.3(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0)) @@ -1336,7 +1337,7 @@ importers: dependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@t3tools/contracts': specifier: workspace:* version: link:../packages/contracts @@ -1348,11 +1349,11 @@ importers: version: link:../packages/shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1364,28 +1365,28 @@ importers: dependencies: '@alchemy.run/axiom': specifier: 'catalog:' - version: 2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5) + version: 2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) '@alchemy.run/cloudflare': specifier: 'catalog:' - version: 2.0.0-beta.85(0a873d1a656f19dfb51d9b33f93f91b1) + version: 2.0.0-beta.85(2402ddc9484fce072797810bc31b583f) '@alchemy.run/drizzle': specifier: 'catalog:' - version: 2.0.0-beta.85(aaf71186a61e3f73fb98ecfca2947754) + version: 2.0.0-beta.85(9d8ed2cd275ad880a7ad7c23a0ac97be) '@alchemy.run/planetscale': specifier: 'catalog:' - version: 2.0.0-beta.85(@effect/sql-pg@4.1.5(effect@4.1.5))(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5)(pg@8.23.0) + version: 2.0.0-beta.85(13cf82a9ea878143588c95fe8a3597d0) '@clerk/backend': specifier: 3.27.0 version: 3.27.0(react-dom@19.3.0(react@19.3.0))(react@19.3.0) '@distilled.cloud/cloudflare': specifier: 'catalog:' - version: 1.0.0-rc.18(effect@4.1.5) + version: 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) '@effect/sql-pg': specifier: 4.1.5 - version: 4.1.5(effect@4.1.5) + version: 4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) '@effect/sql-sqlite-do': specifier: 'catalog:' - version: 4.1.5(effect@4.1.5) + version: 4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) '@noble/curves': specifier: 'catalog:' version: 1.9.1 @@ -1403,26 +1404,26 @@ importers: version: link:../../packages/shared alchemy: specifier: 2.0.0-beta.85 - version: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + version: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) drizzle-orm: specifier: 1.0.0-rc.5 - version: 1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5))(@effect/sql-pg@4.1.5(effect@4.1.5))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5)(expo-sqlite@58.0.15(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7) + version: 1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@effect/sql-pg@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(expo-sqlite@58.0.15(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7) effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@alchemy.run/test': specifier: 'catalog:' - version: 2.0.0-beta.85(patch_hash=29c0539ea71d9cc372f0b16558640599beb9bc609605feb2a493da268d72713e)(adf93af6036c4c597e35df2cca6d42d0) + version: 2.0.0-beta.85(patch_hash=29c0539ea71d9cc372f0b16558640599beb9bc609605feb2a493da268d72713e)(f73ef3f521055a56671f9dfc623ae3a6) '@cloudflare/workers-types': specifier: ^4.20260601.1 version: 4.20260604.1 '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@electric-sql/pglite': specifier: 0.3.15 version: 0.3.15 @@ -1431,7 +1432,7 @@ importers: version: 24.12.4 drizzle-kit: specifier: 1.0.0-rc.5 - version: 1.0.0-rc.5(drizzle-orm@1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5))(@effect/sql-pg@4.1.5(effect@4.1.5))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5)(expo-sqlite@58.0.15(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7)) + version: 1.0.0-rc.5(9451426e25210de8eb160d0749b6dfbf) vite: specifier: npm:@voidzero-dev/vite-plus-core@1.4.0 version: '@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0)' @@ -1443,16 +1444,16 @@ importers: dependencies: '@alchemy.run/axiom': specifier: 'catalog:' - version: 2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5) + version: 2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) '@alchemy.run/cloudflare': specifier: 'catalog:' - version: 2.0.0-beta.85(0a873d1a656f19dfb51d9b33f93f91b1) + version: 2.0.0-beta.85(2402ddc9484fce072797810bc31b583f) alchemy: specifier: 2.0.0-beta.85 - version: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + version: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) jose: specifier: 'catalog:' version: 6.2.2 @@ -1462,10 +1463,10 @@ importers: version: 4.20260604.1 '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1480,14 +1481,14 @@ importers: version: 1.89.0 effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) vite-plus: specifier: 1.4.0 version: 1.4.0(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) @@ -1544,7 +1545,7 @@ importers: version: link:../source-control-definitions effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) gt-i18n: specifier: 1.0.40 version: 1.0.40 @@ -1560,7 +1561,7 @@ importers: devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/mdast': specifier: ^4.0.4 version: 4.0.4 @@ -1584,11 +1585,11 @@ importers: dependencies: effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) vite-plus: specifier: 1.4.0 version: 1.4.0(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) @@ -1597,17 +1598,17 @@ importers: dependencies: effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/openapi-generator': specifier: 'catalog:' - version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5)(encoding@0.1.13) + version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(encoding@0.1.13) '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1619,17 +1620,17 @@ importers: dependencies: effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/openapi-generator': specifier: 'catalog:' - version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5)(encoding@0.1.13) + version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(encoding@0.1.13) '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1647,14 +1648,14 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/graphql-generator': specifier: 'catalog:' - version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5) + version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1678,14 +1679,14 @@ importers: version: 8.0.3 effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1715,14 +1716,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -1746,14 +1747,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1777,7 +1778,7 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) jsonc-parser: specifier: 3.3.1 version: 3.3.1 @@ -1787,10 +1788,10 @@ importers: devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -1817,14 +1818,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -1854,14 +1855,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -1891,14 +1892,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -1928,14 +1929,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -1953,7 +1954,7 @@ importers: version: 1.15.13 '@opencode/client': specifier: 2.0.28 - version: 2.0.28(effect@4.1.5) + version: 2.0.28(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) '@opencode/protocol': specifier: 2.0.28 version: 2.0.28 @@ -1971,14 +1972,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -2002,14 +2003,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -2024,7 +2025,7 @@ importers: dependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@t3tools/contracts': specifier: workspace:* version: link:../contracts @@ -2036,11 +2037,11 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -2055,14 +2056,14 @@ importers: version: link:../contracts effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -2095,14 +2096,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -2123,7 +2124,7 @@ importers: version: link:../contracts effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) ffi-rs: specifier: 1.3.2 version: 1.3.2 @@ -2184,10 +2185,10 @@ importers: devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/hast': specifier: ^3.0.5 version: 3.0.5 @@ -2223,14 +2224,14 @@ importers: version: 8.0.3 effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2257,14 +2258,14 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2285,11 +2286,11 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -2301,7 +2302,7 @@ importers: dependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@t3tools/contracts': specifier: workspace:* version: link:../contracts @@ -2316,11 +2317,11 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -2374,14 +2375,14 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2408,11 +2409,11 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2427,7 +2428,7 @@ importers: dependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@t3tools/contracts': specifier: workspace:* version: link:../contracts @@ -2442,17 +2443,17 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) yaml: specifier: ^2.9.0 version: 2.9.0 devDependencies: '@effect/graphql-generator': specifier: 'catalog:' - version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5) + version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2476,14 +2477,14 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2507,11 +2508,11 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2526,7 +2527,7 @@ importers: dependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@t3tools/contracts': specifier: workspace:* version: link:../contracts @@ -2538,7 +2539,7 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@types/node': specifier: 24.12.4 @@ -2554,14 +2555,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -2579,11 +2580,11 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -2601,7 +2602,7 @@ importers: version: 0.15.5(e2e@0.23.0) '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@electron/asar': specifier: ^4.3.0 version: 4.3.0 @@ -2625,7 +2626,7 @@ importers: version: 0.23.0 effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) playwright-core: specifier: 1.64.1 version: 1.64.1 @@ -2641,7 +2642,7 @@ importers: devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/plist': specifier: 'catalog:' version: 3.0.5 @@ -13167,27 +13168,27 @@ snapshots: dependencies: json-schema: 0.4.0 - '@alchemy.run/acme@2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5)': + '@alchemy.run/acme@2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': dependencies: - '@distilled.cloud/acme': 1.0.0-rc.18(effect@4.1.5) - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - effect: 4.1.5 + '@distilled.cloud/acme': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) - '@alchemy.run/axiom@2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5)': + '@alchemy.run/axiom@2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': dependencies: - '@distilled.cloud/axiom': 1.0.0-rc.18(effect@4.1.5) - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5) - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - effect: 4.1.5 + '@distilled.cloud/axiom': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) - '@alchemy.run/cloudflare-runtime@2.0.0-beta.85(@distilled.cloud/cloudflare@1.0.0-rc.18(effect@4.1.5))(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/node@24.12.4)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(rolldown@1.2.13)(typescript@6.0.3)': + '@alchemy.run/cloudflare-runtime@2.0.0-beta.85(@distilled.cloud/cloudflare@1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/node@24.12.4)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(rolldown@1.2.13)(typescript@6.0.3)': dependencies: '@alchemy.run/node-utils': 2.0.0-beta.85 '@cloudflare/unenv-preset': 2.16.2(unenv@2.0.0-rc.24)(workerd@1.20261026.1) - '@distilled.cloud/cloudflare': 1.0.0-rc.18(effect@4.1.5) + '@distilled.cloud/cloudflare': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) '@puppeteer/browsers': 3.2.6(yauzl@3.4.0) capnp-es: 0.0.16(typescript@6.0.3) - effect: 4.1.5 + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) magic-string: 0.30.21 mime: 4.1.1 sharp: 0.35.5(@types/node@24.12.4) @@ -13195,8 +13196,8 @@ snapshots: workerd: 1.20261026.1 yauzl: 3.4.0 optionalDependencies: - '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6) - '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6) + '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) rolldown: 1.2.13 vite: '@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0)' transitivePeerDependencies: @@ -13204,27 +13205,27 @@ snapshots: - proxy-agent - typescript - '@alchemy.run/cloudflare@2.0.0-beta.85(0a873d1a656f19dfb51d9b33f93f91b1)': - dependencies: - '@alchemy.run/acme': 2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5) - '@alchemy.run/cloudflare-runtime': 2.0.0-beta.85(@distilled.cloud/cloudflare@1.0.0-rc.18(effect@4.1.5))(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/node@24.12.4)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(rolldown@1.2.13)(typescript@6.0.3) - '@alchemy.run/docker': 2.0.0-beta.85(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5) - '@alchemy.run/sql': 2.0.0-beta.85(@effect/sql-pg@4.1.5(effect@4.1.5))(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5)(pg@8.23.0) - '@distilled.cloud/aws': 1.0.0-rc.18(effect@4.1.5) - '@distilled.cloud/aws4signer': 1.0.0-rc.18(effect@4.1.5) - '@distilled.cloud/cloudflare': 1.0.0-rc.18(effect@4.1.5) - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5) - '@distilled.cloud/iceberg': 1.0.0-rc.18(effect@4.1.5) - '@effect/sql-d1': 4.1.1(effect@4.1.5) - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - effect: 4.1.5 + '@alchemy.run/cloudflare@2.0.0-beta.85(2402ddc9484fce072797810bc31b583f)': + dependencies: + '@alchemy.run/acme': 2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + '@alchemy.run/cloudflare-runtime': 2.0.0-beta.85(@distilled.cloud/cloudflare@1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/node@24.12.4)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(rolldown@1.2.13)(typescript@6.0.3) + '@alchemy.run/docker': 2.0.0-beta.85(e480f1b1bda9582dded73d242d5d6dc9) + '@alchemy.run/sql': 2.0.0-beta.85(13cf82a9ea878143588c95fe8a3597d0) + '@distilled.cloud/aws': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + '@distilled.cloud/aws4signer': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + '@distilled.cloud/cloudflare': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + '@distilled.cloud/iceberg': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + '@effect/sql-d1': 4.1.1(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) pathe: 2.0.3 picomatch: 4.0.7 rolldown: 1.2.13 tinyglobby: 0.2.17 optionalDependencies: - '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6) - '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6) + '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) vite: '@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0)' transitivePeerDependencies: - '@effect/sql-libsql' @@ -13236,26 +13237,26 @@ snapshots: - proxy-agent - typescript - '@alchemy.run/docker@2.0.0-beta.85(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5)': + '@alchemy.run/docker@2.0.0-beta.85(e480f1b1bda9582dded73d242d5d6dc9)': dependencies: - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - effect: 4.1.5 + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) rolldown: 1.2.13 optionalDependencies: - '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6) + '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6) - '@alchemy.run/drizzle@2.0.0-beta.85(aaf71186a61e3f73fb98ecfca2947754)': + '@alchemy.run/drizzle@2.0.0-beta.85(9d8ed2cd275ad880a7ad7c23a0ac97be)': dependencies: - '@alchemy.run/sql': 2.0.0-beta.85(@effect/sql-pg@4.1.5(effect@4.1.5))(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5)(pg@8.23.0) - '@effect/sql-d1': 4.1.1(effect@4.1.5) - '@effect/sql-sqlite-do': 4.1.5(effect@4.1.5) - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - drizzle-orm: 1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5))(@effect/sql-pg@4.1.5(effect@4.1.5))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5)(expo-sqlite@58.0.15(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7) - effect: 4.1.5 + '@alchemy.run/sql': 2.0.0-beta.85(13cf82a9ea878143588c95fe8a3597d0) + '@effect/sql-d1': 4.1.1(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + '@effect/sql-sqlite-do': 4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + drizzle-orm: 1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@effect/sql-pg@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(expo-sqlite@58.0.15(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7) + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) optionalDependencies: - '@alchemy.run/cloudflare': 2.0.0-beta.85(0a873d1a656f19dfb51d9b33f93f91b1) - '@effect/sql-pg': 4.1.5(effect@4.1.5) - drizzle-kit: 1.0.0-rc.5(drizzle-orm@1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5))(@effect/sql-pg@4.1.5(effect@4.1.5))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5)(expo-sqlite@58.0.15(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7)) + '@alchemy.run/cloudflare': 2.0.0-beta.85(2402ddc9484fce072797810bc31b583f) + '@effect/sql-pg': 4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + drizzle-kit: 1.0.0-rc.5(9451426e25210de8eb160d0749b6dfbf) transitivePeerDependencies: - mysql2 - pg @@ -13265,13 +13266,13 @@ snapshots: chokidar: 5.0.0 rolldown: 1.2.13 - '@alchemy.run/planetscale@2.0.0-beta.85(@effect/sql-pg@4.1.5(effect@4.1.5))(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5)(pg@8.23.0)': + '@alchemy.run/planetscale@2.0.0-beta.85(13cf82a9ea878143588c95fe8a3597d0)': dependencies: - '@alchemy.run/sql': 2.0.0-beta.85(@effect/sql-pg@4.1.5(effect@4.1.5))(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5)(pg@8.23.0) - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5) - '@distilled.cloud/planetscale': 1.0.0-rc.18(effect@4.1.5) - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - effect: 4.1.5 + '@alchemy.run/sql': 2.0.0-beta.85(13cf82a9ea878143588c95fe8a3597d0) + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + '@distilled.cloud/planetscale': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) optionalDependencies: pg: 8.23.0 transitivePeerDependencies: @@ -13284,21 +13285,21 @@ snapshots: '@types/react': 19.3.0 react-devtools-core: 6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6) - '@alchemy.run/sql@2.0.0-beta.85(@effect/sql-pg@4.1.5(effect@4.1.5))(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5)(pg@8.23.0)': + '@alchemy.run/sql@2.0.0-beta.85(13cf82a9ea878143588c95fe8a3597d0)': dependencies: - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - effect: 4.1.5 + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) optionalDependencies: - '@effect/sql-pg': 4.1.5(effect@4.1.5) + '@effect/sql-pg': 4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) pg: 8.23.0 - '@alchemy.run/test@2.0.0-beta.85(patch_hash=29c0539ea71d9cc372f0b16558640599beb9bc609605feb2a493da268d72713e)(adf93af6036c4c597e35df2cca6d42d0)': + '@alchemy.run/test@2.0.0-beta.85(patch_hash=29c0539ea71d9cc372f0b16558640599beb9bc609605feb2a493da268d72713e)(f73ef3f521055a56671f9dfc623ae3a6)': dependencies: - '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6) - effect: 4.1.5 + '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6) + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) optionalDependencies: - '@effect/vitest': 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + '@effect/vitest': 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) vitest: 5.0.5(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/browser-preview@5.0.5)(@vitest/ui@5.0.5)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0) transitivePeerDependencies: - bufferutil @@ -14277,45 +14278,45 @@ snapshots: '@dimforge/rapier3d-compat@0.12.0': {} - '@distilled.cloud/acme@1.0.0-rc.18(effect@4.1.5)': + '@distilled.cloud/acme@1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': dependencies: - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5) - effect: 4.1.5 + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) - '@distilled.cloud/aws4signer@1.0.0-rc.18(effect@4.1.5)': + '@distilled.cloud/aws4signer@1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': dependencies: - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5) - effect: 4.1.5 + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) - '@distilled.cloud/aws@1.0.0-rc.18(effect@4.1.5)': + '@distilled.cloud/aws@1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': dependencies: - '@distilled.cloud/aws4signer': 1.0.0-rc.18(effect@4.1.5) - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5) - effect: 4.1.5 + '@distilled.cloud/aws4signer': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) - '@distilled.cloud/axiom@1.0.0-rc.18(effect@4.1.5)': + '@distilled.cloud/axiom@1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': dependencies: - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5) - effect: 4.1.5 + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) - '@distilled.cloud/cloudflare@1.0.0-rc.18(effect@4.1.5)': + '@distilled.cloud/cloudflare@1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': dependencies: - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5) - effect: 4.1.5 + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) - '@distilled.cloud/core@1.0.0-rc.18(effect@4.1.5)': + '@distilled.cloud/core@1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': dependencies: - effect: 4.1.5 + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) - '@distilled.cloud/iceberg@1.0.0-rc.18(effect@4.1.5)': + '@distilled.cloud/iceberg@1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': dependencies: - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5) - effect: 4.1.5 + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) - '@distilled.cloud/planetscale@1.0.0-rc.18(effect@4.1.5)': + '@distilled.cloud/planetscale@1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': dependencies: - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5) - effect: 4.1.5 + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) '@dnd-kit/accessibility@3.1.1(react@19.3.0)': dependencies: @@ -14361,64 +14362,64 @@ snapshots: e2e: 0.23.0 playwright-core: 1.64.1 - '@effect/atom-react@4.1.5(effect@4.1.5)(react@19.3.0)(scheduler@0.28.0)': + '@effect/atom-react@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react@19.3.0)(scheduler@0.28.0)': dependencies: - effect: 4.1.5 + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) react: 19.3.0 scheduler: 0.28.0 - '@effect/graphql-generator@4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5)': + '@effect/graphql-generator@4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': dependencies: - '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) - effect: 4.1.5 + '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) - '@effect/openapi-generator@4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5)(encoding@0.1.13)': + '@effect/openapi-generator@4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(encoding@0.1.13)': dependencies: - '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) - effect: 4.1.5 + '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) swagger2openapi: 7.0.8(encoding@0.1.13) transitivePeerDependencies: - encoding - '@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6)': + '@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6)': dependencies: - '@effect/platform-node-shared': 4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6) - effect: 4.1.5 + '@effect/platform-node-shared': 4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6) + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) transitivePeerDependencies: - bufferutil - utf-8-validate - '@effect/platform-node-shared@4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6)': + '@effect/platform-node-shared@4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6)': dependencies: '@types/ws': 8.18.2 - effect: 4.1.5 + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) ws: 8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6) transitivePeerDependencies: - bufferutil - utf-8-validate - '@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6)': + '@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6)': dependencies: - '@effect/platform-node-shared': 4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6) - effect: 4.1.5 + '@effect/platform-node-shared': 4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6) + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) redis: 6.2.1 undici: 8.12.4 transitivePeerDependencies: - bufferutil - utf-8-validate - '@effect/sql-d1@4.1.1(effect@4.1.5)': + '@effect/sql-d1@4.1.1(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': dependencies: '@cloudflare/workers-types': 5.20261026.1 - effect: 4.1.5 + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) - '@effect/sql-pg@4.1.5(effect@4.1.5)': + '@effect/sql-pg@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': dependencies: - effect: 4.1.5 + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) - '@effect/sql-sqlite-do@4.1.5(effect@4.1.5)': + '@effect/sql-sqlite-do@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': dependencies: - effect: 4.1.5 + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) '@effect/tsgo-darwin-arm64@0.67.1': optional: true @@ -14451,9 +14452,9 @@ snapshots: '@effect/tsgo-win32-arm64': 0.67.1 '@effect/tsgo-win32-x64': 0.67.1 - '@effect/vitest@4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0)': + '@effect/vitest@4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0)': dependencies: - effect: 4.1.5 + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) vite-plus: 1.4.0(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) transitivePeerDependencies: - '@arethetypeswrong/core' @@ -15929,22 +15930,22 @@ snapshots: dependencies: cross-spawn: 7.0.6 - '@opencode/client@2.0.28(effect@4.1.5)': + '@opencode/client@2.0.28(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': dependencies: '@opencode/protocol': 2.0.28 '@opencode/schema': 2.0.28 optionalDependencies: - effect: 4.1.5 + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) '@opencode/protocol@2.0.28': dependencies: '@opencode/schema': 2.0.28 - effect: 4.1.5 + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) '@opencode/schema@2.0.28': dependencies: '@standard-schema/spec': 1.1.0 - effect: 4.1.5 + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) '@oslojs/asn1@1.0.0': dependencies: @@ -18033,12 +18034,12 @@ snapshots: json-schema-traverse: 1.0.0 require-from-string: 2.0.2 - alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)): + alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)): dependencies: '@alchemy.run/node-utils': 2.0.0-beta.85 '@alchemy.run/sigil': 0.1.0-alpha.1(@types/react@19.3.0)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6)) capnweb: 0.12.0 - effect: 4.1.5 + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) fflate: 0.8.3 pathe: 2.0.3 picomatch: 4.0.7 @@ -18046,8 +18047,8 @@ snapshots: tinyglobby: 0.2.17 yaml: 2.9.0 optionalDependencies: - '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6) - '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6) + '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) vite: '@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0)' ws: 8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6) transitivePeerDependencies: @@ -19006,21 +19007,21 @@ snapshots: dotenv@16.6.1: {} - drizzle-kit@1.0.0-rc.5(drizzle-orm@1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5))(@effect/sql-pg@4.1.5(effect@4.1.5))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5)(expo-sqlite@58.0.15(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7)): + drizzle-kit@1.0.0-rc.5(9451426e25210de8eb160d0749b6dfbf): optionalDependencies: - drizzle-orm: 1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5))(@effect/sql-pg@4.1.5(effect@4.1.5))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5)(expo-sqlite@58.0.15(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7) + drizzle-orm: 1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@effect/sql-pg@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(expo-sqlite@58.0.15(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7) - drizzle-orm@1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5))(@effect/sql-pg@4.1.5(effect@4.1.5))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5)(expo-sqlite@58.0.15(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7): + drizzle-orm@1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@effect/sql-pg@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(expo-sqlite@58.0.15(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7): optionalDependencies: '@cloudflare/workers-types': 4.20260604.1 - '@effect/sql-d1': 4.1.1(effect@4.1.5) - '@effect/sql-pg': 4.1.5(effect@4.1.5) - '@effect/sql-sqlite-do': 4.1.5(effect@4.1.5) + '@effect/sql-d1': 4.1.1(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + '@effect/sql-pg': 4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + '@effect/sql-sqlite-do': 4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) '@electric-sql/pglite': 0.3.15 '@libsql/client': 0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6) '@types/sql.js': 1.4.11 bun-types: 1.3.14 - effect: 4.1.5 + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) expo-sqlite: 58.0.15(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0) pg: 8.23.0 sql.js: 1.15.0 @@ -19059,7 +19060,7 @@ snapshots: ee-first@1.1.1: {} - effect@4.1.5: {} + effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337): {} ejs@3.1.10: dependencies: diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 7e3c147d69351..fdaafa748a67e 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -285,6 +285,8 @@ patchedDependencies: react-native-svg@15.16.1: patches/react-native-svg@15.16.1.patch # Android: double-tap zoom no longer cancels itself, and taps near a link open it. react-native-pdf-jsi@6.1.0: patches/react-native-pdf-jsi@6.1.0.patch + # The MCP Events extension (SEP-3415) on effect/ai, until Effect ships it. + effect@4.1.5: patches/effect@4.1.5.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. From 9d35540ace7c6b1255a1b29035cab232a79b387e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 15:46:48 -0800 Subject: [PATCH 225/324] fix(mobile): pasted iOS photos keep their encoding and repeats are dropped (#41101) --- .../ios/T3ComposerEditorModule.swift | 1 + .../ios/T3ComposerEditorView.swift | 40 ++++++++++++++++--- .../t3-composer-editor/tests/ios/main.swift | 24 ++++++++++- .../components/ComposerAttachmentStrip.tsx | 21 +++++++++- .../src/features/threads/ThreadComposer.tsx | 12 +++++- apps/mobile/src/i18n/translations/de.json | 1 + apps/mobile/src/i18n/translations/en.json | 1 + apps/mobile/src/i18n/translations/es.json | 1 + apps/mobile/src/i18n/translations/fr.json | 1 + apps/mobile/src/i18n/translations/ja.json | 1 + apps/mobile/src/i18n/translations/ko.json | 1 + apps/mobile/src/i18n/translations/pt-BR.json | 1 + apps/mobile/src/i18n/translations/ru.json | 1 + apps/mobile/src/i18n/translations/sv.json | 1 + apps/mobile/src/i18n/translations/zh.json | 1 + apps/mobile/src/lib/composer-image-schema.ts | 1 + apps/mobile/src/lib/composerImages.test.ts | 6 +++ apps/mobile/src/lib/composerImages.ts | 9 ++++- .../src/native/T3ComposerEditor.ios.tsx | 5 +++ apps/mobile/src/native/T3ComposerEditor.tsx | 1 + .../src/native/T3ComposerEditor.types.ts | 2 + .../src/state/use-composer-drafts.test.ts | 25 +++++++++--- apps/mobile/src/state/use-composer-drafts.ts | 16 ++++---- 23 files changed, 148 insertions(+), 25 deletions(-) diff --git a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorModule.swift b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorModule.swift index c54a1a84e9644..d07908a4b27fa 100644 --- a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorModule.swift +++ b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorModule.swift @@ -117,6 +117,7 @@ public class T3ComposerEditorModule: Module { "onComposerBlur", "onComposerSubmit", "onComposerPasteImages", + "onComposerPasteImagesPending", "onComposerContextPress", "onComposerPasteContext", "onComposerPasteText", diff --git a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift index 253376fe5e4d3..2f24b0d98752c 100644 --- a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift +++ b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift @@ -86,6 +86,8 @@ private final class ComposerTextView: UITextView { ]) var onPasteImages: (([String]) -> Void)? + /// Change in how many pasted images are still loading: +n when a paste is accepted, -n once it settles. + var onPasteImagesPending: ((Int) -> Void)? var onPasteContext: (([String: String]) -> Void)? var onPasteText: ((String, NSRange) -> Void)? var clipboardFragment = "" @@ -308,6 +310,8 @@ private final class ComposerTextView: UITextView { } func loadImages(from providers: [NSItemProvider]) { + guard !providers.isEmpty else { return } + onPasteImagesPending?(providers.count) let group = DispatchGroup() let lock = NSLock() var images = [(data: Data, fileExtension: String)?](repeating: nil, count: providers.count) @@ -325,10 +329,11 @@ private final class ComposerTextView: UITextView { store((object as? UIImage)?.pngData().map { ($0, "png") }) } } - // Decoding a GIF to UIImage keeps only its first frame, so pass its bytes through. - if provider.hasItemConformingToTypeIdentifier(UTType.gif.identifier) { - _ = provider.loadDataRepresentation(forTypeIdentifier: UTType.gif.identifier) { data, _ in - if let data { store((data, "gif")) } else { loadPNG() } + // Re-encoding a photo as PNG inflates it several times and keeps only a GIF's first frame, + // so pass the provider's own encoding through when it is one the attachment path reads. + if let original = Self.passthroughImageType(of: provider) { + _ = provider.loadDataRepresentation(forTypeIdentifier: original.type.identifier) { data, _ in + if let data { store((data, original.fileExtension)) } else { loadPNG() } } } else { loadPNG() @@ -336,7 +341,11 @@ private final class ComposerTextView: UITextView { } group.notify(queue: .main) { [weak self] in - guard let self, !self.isReadOnly else { + guard let self else { + return + } + defer { self.onPasteImagesPending?(-providers.count) } + guard !self.isReadOnly else { return } let urls = images.compactMap { $0 }.compactMap { @@ -418,6 +427,23 @@ private final class ComposerTextView: UITextView { return sourceOffset } + private static let passthroughImageTypes: [(type: UTType, fileExtension: String)] = [ + (.gif, "gif"), (.jpeg, "jpg"), (.heic, "heic"), (.png, "png"), (.webP, "webp"), + ] + + /// Providers list representations best first, so the first supported one is the original. + private static func passthroughImageType( + of provider: NSItemProvider + ) -> (type: UTType, fileExtension: String)? { + for identifier in provider.registeredTypeIdentifiers { + guard let registered = UTType(identifier) else { continue } + if let match = passthroughImageTypes.first(where: { registered.conforms(to: $0.type) }) { + return match + } + } + return nil + } + private static func writeTemporaryImage(_ image: UIImage) -> String? { image.pngData().flatMap { writeTemporaryImage($0, fileExtension: "png") } } @@ -507,6 +533,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro let onComposerBlur = EventDispatcher() let onComposerSubmit = EventDispatcher() let onComposerPasteImages = EventDispatcher() + let onComposerPasteImagesPending = EventDispatcher() let onComposerContextPress = EventDispatcher() let onComposerPasteContext = EventDispatcher() let onComposerPasteText = EventDispatcher() @@ -537,6 +564,9 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro textView.onPasteImages = { [weak self] urls in self?.onComposerPasteImages(["uris": urls]) } + textView.onPasteImagesPending = { [weak self] delta in + self?.onComposerPasteImagesPending(["delta": delta]) + } textView.onPasteContext = { [weak self] context in guard let self else { return } let selection = self.sourceSelection() diff --git a/apps/mobile/modules/t3-composer-editor/tests/ios/main.swift b/apps/mobile/modules/t3-composer-editor/tests/ios/main.swift index 6b69f29d308d5..83c1920bfd133 100644 --- a/apps/mobile/modules/t3-composer-editor/tests/ios/main.swift +++ b/apps/mobile/modules/t3-composer-editor/tests/ios/main.swift @@ -271,6 +271,17 @@ gifEditor.onPasteImages = { urls in exit(0) } +// A provider that finishes on a later main-queue turn, like a full-size photo still loading. +private let deferredPNG = image.pngData()! +private let deferredProvider = NSItemProvider() +deferredProvider.registerDataRepresentation(forTypeIdentifier: UTType.png.identifier, visibility: .all) { completion in + DispatchQueue.main.async { completion(deferredPNG, nil) } + return nil +} +private var pendingDeltas: [Int] = [] +private let deferredEditor = ComposerTextView() +deferredEditor.onPasteImagesPending = { pendingDeltas.append($0) } + // Inline provider completion places the attachment callback before this main-queue check. DispatchQueue.main.async { check(pastedImages.count == 1, "An accepted provider-based paste must emit exactly one attachment batch") @@ -287,7 +298,16 @@ DispatchQueue.main.async { "The attachment must contain the pasted image's pixels") check(pasteEditor.text == "Keep this draft", "Image paste must preserve the draft text") print("Composer provider-paste checks passed") - check(gifProvider.canLoadObject(ofClass: UIImage.self), "A GIF provider must take the image paste path") - gifEditor.paste(itemProviders: [gifProvider, ImmediateImageProvider(image: image)]) + deferredEditor.onPasteImages = { urls in + urls.compactMap(URL.init(string:)).forEach { try? FileManager.default.removeItem(at: $0) } + DispatchQueue.main.async { + check(pendingDeltas == [1, -1], "A finished paste must settle its preparation: \(pendingDeltas)") + print("Composer paste-preparation checks passed") + check(gifProvider.canLoadObject(ofClass: UIImage.self), "A GIF provider must take the image paste path") + gifEditor.paste(itemProviders: [gifProvider, ImmediateImageProvider(image: image)]) + } + } + deferredEditor.paste(itemProviders: [deferredProvider]) + check(pendingDeltas == [1], "Preparation must be reported before the provider finishes: \(pendingDeltas)") } dispatchMain() diff --git a/apps/mobile/src/components/ComposerAttachmentStrip.tsx b/apps/mobile/src/components/ComposerAttachmentStrip.tsx index ba7d9790c4120..95a2d928e4c10 100644 --- a/apps/mobile/src/components/ComposerAttachmentStrip.tsx +++ b/apps/mobile/src/components/ComposerAttachmentStrip.tsx @@ -10,6 +10,7 @@ import { Paths } from "expo-file-system"; import { Image, Pressable, ScrollView, View } from "react-native"; import { AppText as Text } from "./ui/AppText"; +import { AppActivityIndicator } from "./ui/AppActivityIndicator"; import { MaterializedPreviewKey, materializedPreviewAtom } from "../lib/composerImagePreview"; import { PierreEntryIcon } from "./PierreEntryIcon"; import { @@ -44,6 +45,8 @@ export interface ComposerAttachmentStripProps { readonly imageSize?: number; readonly imageBorderRadius?: number; readonly removeButtonPlacement?: "overlay" | "gutter"; + /** Pasted images still being prepared, shown as placeholders after the attachments. */ + readonly pendingImageCount?: number; } type ComposerAttachmentThumbnailProps = { @@ -301,7 +304,8 @@ export function ComposerAttachmentStrip(props: ComposerAttachmentStripProps) { const removeButtonPlacement = props.removeButtonPlacement ?? "overlay"; const removeButtonGutter = removeButtonPlacement === "gutter" ? 10 : 0; - if (props.attachments.length === 0) { + const pendingImageCount = props.pendingImageCount ?? 0; + if (props.attachments.length === 0 && pendingImageCount === 0) { return null; } @@ -353,6 +357,21 @@ export function ComposerAttachmentStrip(props: ComposerAttachmentStripProps) { ))} + {Array.from({ length: pendingImageCount }, (_, index) => ( + + + + ))} diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx index 025b91326762b..b2ebef9a42523 100644 --- a/apps/mobile/src/features/threads/ThreadComposer.tsx +++ b/apps/mobile/src/features/threads/ThreadComposer.tsx @@ -270,6 +270,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps const [isFocused, setIsFocused] = useState(false); const pendingPastedTextAttachmentCountRef = useRef(0); const pendingNativeImagePasteCountRef = useRef(0); + const [pendingNativeImageCount, setPendingNativeImageCount] = useState(0); const [pendingPastedTextAttachmentCount, setPendingPastedTextAttachmentCount] = useState(0); const settingsRoutePresentedRef = useRef(false); const settingsSheetPresentation = useThreadSettingsSheetPresentation({ @@ -478,7 +479,8 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps const isToolbarVisible = isVoiceInputPresented; const hasEditingAttachments = (queuedEdit !== null && queuedEdit.existingAttachments.length > 0) || - stripAttachments.length > 0; + stripAttachments.length > 0 || + pendingNativeImageCount > 0; const attachmentBlockReason = composerAttachmentUploadBlockReason( { environmentId: props.environmentId, @@ -652,7 +654,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps /> ) : null} - {stripAttachments.length > 0 ? ( + {stripAttachments.length > 0 || pendingNativeImageCount > 0 ? ( undefined : props.onRemoveDraftImage} onPressPreview={isSubmissionLocked ? undefined : onPressPreview} onPressVideo={isSubmissionLocked ? undefined : onPressVideo} @@ -903,10 +906,15 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps onPasteImages={(uris) => { if (isSubmissionLocked) return; pendingNativeImagePasteCountRef.current += 1; + setPendingNativeImageCount((count) => count + uris.length); void nativeImageSubmit.pasteImages(uris).finally(() => { pendingNativeImagePasteCountRef.current -= 1; + setPendingNativeImageCount((count) => count - uris.length); }); }} + onPasteImagesPending={(delta) => + setPendingNativeImageCount((count) => count + delta) + } onPasteText={(paste) => { if (isSubmissionLocked) return; const insertPaste = () => { diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index 1fe7fdc60bce9..2073cb88f9e72 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -1360,6 +1360,7 @@ "1c79d42e902ff431": "Wiederholen", "b1687c7b2b91e569": "{name} öffnen", "2ffc366d6a7f88db": "{name} entfernen", + "ff43c1538698d479": "Eingefügtes Bild wird vorbereitet", "c04cd8ec791956cb": "Die lokale Datei ist nicht verfügbar. Hänge sie erneut an.", "68883cb3342998e5": "Verbinde dich erneut mit der Umgebung und versuche es noch einmal.", "43f6af4554b019cf": "Anhang konnte nicht geöffnet werden", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 84c6fd8dfd893..9fc46efb5af54 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -1360,6 +1360,7 @@ "1c79d42e902ff431": "Retry", "b1687c7b2b91e569": "Open {name}", "2ffc366d6a7f88db": "Remove {name}", + "ff43c1538698d479": "Preparing pasted image", "c04cd8ec791956cb": "The local file is unavailable. Attach it again.", "68883cb3342998e5": "Reconnect to the environment and try again.", "43f6af4554b019cf": "Could not open attachment", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index d3fb1c8188ddb..39ca2122a2fe1 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -1360,6 +1360,7 @@ "1c79d42e902ff431": "Reintentar", "b1687c7b2b91e569": "Abrir {name}", "2ffc366d6a7f88db": "Quitar {name}", + "ff43c1538698d479": "Preparando la imagen pegada", "c04cd8ec791956cb": "El archivo local no está disponible. Vuelve a adjuntarlo.", "68883cb3342998e5": "Vuelve a conectarte al entorno e inténtalo de nuevo.", "43f6af4554b019cf": "No se pudo abrir el adjunto", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index 2d4f3cb8084fc..f7110d948813a 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -1360,6 +1360,7 @@ "1c79d42e902ff431": "Réessayer", "b1687c7b2b91e569": "Ouvrir {name}", "2ffc366d6a7f88db": "Retirer {name}", + "ff43c1538698d479": "Préparation de l’image collée", "c04cd8ec791956cb": "Le fichier local n’est pas disponible. Joignez-le à nouveau.", "68883cb3342998e5": "Reconnectez-vous à l’environnement et réessayez.", "43f6af4554b019cf": "Impossible d’ouvrir la pièce jointe", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index 68bcbddda6f02..be00bd9f904d6 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -1360,6 +1360,7 @@ "1c79d42e902ff431": "再試行", "b1687c7b2b91e569": "{name} を開く", "2ffc366d6a7f88db": "{name} を削除", + "ff43c1538698d479": "貼り付けた画像を準備中", "c04cd8ec791956cb": "ローカルファイルを利用できません。もう一度添付してください。", "68883cb3342998e5": "環境に再接続して、もう一度お試しください。", "43f6af4554b019cf": "添付ファイルを開けませんでした", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index ce3e8aba332c7..b991e15bd45a7 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -1360,6 +1360,7 @@ "1c79d42e902ff431": "다시 시도", "b1687c7b2b91e569": "{name} 열기", "2ffc366d6a7f88db": "{name} 제거", + "ff43c1538698d479": "붙여넣은 이미지 준비 중", "c04cd8ec791956cb": "로컬 파일을 사용할 수 없습니다. 다시 첨부하세요.", "68883cb3342998e5": "환경에 다시 연결한 후 다시 시도하세요.", "43f6af4554b019cf": "첨부 파일을 열 수 없습니다", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 8cb5744485eaa..d2ea67494f79f 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -1360,6 +1360,7 @@ "1c79d42e902ff431": "Tentar novamente", "b1687c7b2b91e569": "Abrir {name}", "2ffc366d6a7f88db": "Remover {name}", + "ff43c1538698d479": "Preparando a imagem colada", "c04cd8ec791956cb": "O arquivo local não está disponível. Anexe-o novamente.", "68883cb3342998e5": "Reconecte-se ao ambiente e tente novamente.", "43f6af4554b019cf": "Não foi possível abrir o anexo", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index 7dcacfc04efc6..f3d6056940a69 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -1360,6 +1360,7 @@ "1c79d42e902ff431": "Повторить", "b1687c7b2b91e569": "Открыть {name}", "2ffc366d6a7f88db": "Удалить {name}", + "ff43c1538698d479": "Подготовка вставленного изображения", "c04cd8ec791956cb": "Локальный файл недоступен. Прикрепите его снова.", "68883cb3342998e5": "Переподключитесь к окружению и повторите попытку.", "43f6af4554b019cf": "Не удалось открыть вложение", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 6e18ff09a8318..e6bc78fa18ef7 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -1360,6 +1360,7 @@ "1c79d42e902ff431": "Försök igen", "b1687c7b2b91e569": "Öppna {name}", "2ffc366d6a7f88db": "Ta bort {name}", + "ff43c1538698d479": "Förbereder inklistrad bild", "c04cd8ec791956cb": "Den lokala filen är inte tillgänglig. Bifoga den igen.", "68883cb3342998e5": "Återanslut till miljön och försök igen.", "43f6af4554b019cf": "Kunde inte öppna bilagan", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index 1bea8cf8142f2..937acbb510cbe 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -1360,6 +1360,7 @@ "1c79d42e902ff431": "重试", "b1687c7b2b91e569": "打开 {name}", "2ffc366d6a7f88db": "移除 {name}", + "ff43c1538698d479": "正在准备粘贴的图片", "c04cd8ec791956cb": "本地文件不可用。请重新附加。", "68883cb3342998e5": "请重新连接环境后重试。", "43f6af4554b019cf": "无法打开附件", diff --git a/apps/mobile/src/lib/composer-image-schema.ts b/apps/mobile/src/lib/composer-image-schema.ts index b8ccf9b9055c0..b60e38cf143d9 100644 --- a/apps/mobile/src/lib/composer-image-schema.ts +++ b/apps/mobile/src/lib/composer-image-schema.ts @@ -10,6 +10,7 @@ export const DraftComposerImageAttachmentSchema = Schema.Struct({ sizeBytes: Schema.Number, fileUri: Schema.optional(Schema.String.check(Schema.isNonEmpty())), dataUrl: Schema.optional(Schema.String.check(Schema.isNonEmpty())), + contentDigest: Schema.optional(Schema.String), uploadedAttachmentId: Schema.optional(Schema.String), uploadEnvironmentId: Schema.optional(EnvironmentId), }).check( diff --git a/apps/mobile/src/lib/composerImages.test.ts b/apps/mobile/src/lib/composerImages.test.ts index de05411a8f327..669e24aaf7990 100644 --- a/apps/mobile/src/lib/composerImages.test.ts +++ b/apps/mobile/src/lib/composerImages.test.ts @@ -116,6 +116,11 @@ vi.mock("expo-file-system", () => ({ Paths: { document: "file:///documents" }, })); +vi.mock("expo-crypto", () => ({ + CryptoDigestAlgorithm: { SHA256: "SHA-256" }, + digestStringAsync: async (_algorithm: string, data: string) => `sha256:${data}`, +})); + vi.mock("./uuid", () => ({ uuidv4: () => "attachment-id", })); @@ -154,6 +159,7 @@ describe("native pasted image cleanup", () => { mimeType: "image/jpeg", fileUri: `${STORED}-pasted-image.jpeg`, previewUri: `${STORED}-pasted-image.jpeg`, + contentDigest: "sha256:aGVsbG8=", }), ]); expect(attachments[0]).not.toHaveProperty("dataUrl"); diff --git a/apps/mobile/src/lib/composerImages.ts b/apps/mobile/src/lib/composerImages.ts index a719085189128..fe671928ffdf3 100644 --- a/apps/mobile/src/lib/composerImages.ts +++ b/apps/mobile/src/lib/composerImages.ts @@ -34,6 +34,8 @@ export interface DraftComposerImageAttachment extends Omit { try { const { File } = await import("expo-file-system"); @@ -692,12 +695,16 @@ export async function convertPastedImagesToAttachments(input: { continue; } const name = `pasted-image.${mimeType.split("/")[1] ?? "png"}`; + const { CryptoDigestAlgorithm, digestStringAsync } = await import("expo-crypto"); + const contentDigest = await digestStringAsync(CryptoDigestAlgorithm.SHA256, base64); const fileUri = await persistComposerAttachmentFile( sourceUri, name, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, ); - attachments.push(await ownedComposerImageAttachment({ fileUri, name, mimeType })); + attachments.push( + await ownedComposerImageAttachment({ fileUri, name, mimeType, contentDigest }), + ); } catch (cause) { console.warn("Failed to read pasted image", uri, cause); error = m(msg("Could not read a pasted image.")); diff --git a/apps/mobile/src/native/T3ComposerEditor.ios.tsx b/apps/mobile/src/native/T3ComposerEditor.ios.tsx index 7e8eba1d01b28..0602f4cb308a6 100644 --- a/apps/mobile/src/native/T3ComposerEditor.ios.tsx +++ b/apps/mobile/src/native/T3ComposerEditor.ios.tsx @@ -64,6 +64,8 @@ type NativePasteImagesEvent = NativeSyntheticEvent<{ readonly uris: ReadonlyArray; }>; +type NativePasteImagesPendingEvent = NativeSyntheticEvent<{ readonly delta: number }>; + type NativePasteTextEvent = NativeSyntheticEvent<{ readonly value: string; readonly eventCount: number; @@ -107,6 +109,7 @@ interface NativeComposerEditorProps extends ViewProps { readonly onComposerChange: (event: NativeEditorEvent) => void; readonly onComposerSelectionChange?: (event: NativeSelectionEvent) => void; readonly onComposerPasteImages?: (event: NativePasteImagesEvent) => void; + readonly onComposerPasteImagesPending?: (event: NativePasteImagesPendingEvent) => void; readonly onComposerContextPress?: ( event: NativeSyntheticEvent<{ source: string; start: number; end: number }>, ) => void; @@ -148,6 +151,7 @@ export function ComposerEditor({ onChangeText, onSelectionChange, onPasteImages, + onPasteImagesPending, onPasteText, onFocus, onBlur, @@ -394,6 +398,7 @@ export function ComposerEditor({ forceNativeEventRender((sequence) => sequence + 1); }} onComposerPasteImages={(event) => onPasteImages?.(event.nativeEvent.uris)} + onComposerPasteImagesPending={(event) => onPasteImagesPending?.(event.nativeEvent.delta)} onComposerContextPress={(event) => props.onContextPress?.(event.nativeEvent)} onComposerPasteContext={(event) => { const paste = event.nativeEvent; diff --git a/apps/mobile/src/native/T3ComposerEditor.tsx b/apps/mobile/src/native/T3ComposerEditor.tsx index fa29f3248cabe..91f102238d79d 100644 --- a/apps/mobile/src/native/T3ComposerEditor.tsx +++ b/apps/mobile/src/native/T3ComposerEditor.tsx @@ -12,6 +12,7 @@ export function ComposerEditor({ skills: _skills, selection, onPasteImages, + onPasteImagesPending: _onPasteImagesPending, onPasteText: _onPasteText, style, textStyle, diff --git a/apps/mobile/src/native/T3ComposerEditor.types.ts b/apps/mobile/src/native/T3ComposerEditor.types.ts index f2ffa034cdb11..bc7eda7b2984e 100644 --- a/apps/mobile/src/native/T3ComposerEditor.types.ts +++ b/apps/mobile/src/native/T3ComposerEditor.types.ts @@ -69,6 +69,8 @@ export interface ComposerEditorProps { readonly readResetGeneration?: () => number; readonly onSelectionChange?: (selection: ComposerEditorSelection) => void; readonly onPasteImages?: (uris: ReadonlyArray) => void; + /** iOS: change in pasted images still loading natively, +n on paste and -n once they settle. */ + readonly onPasteImagesPending?: (delta: number) => void; readonly onContextPress?: (reference: { readonly source: string; readonly start: number; diff --git a/apps/mobile/src/state/use-composer-drafts.test.ts b/apps/mobile/src/state/use-composer-drafts.test.ts index 8c1870f76836b..a951c13839ee4 100644 --- a/apps/mobile/src/state/use-composer-drafts.test.ts +++ b/apps/mobile/src/state/use-composer-drafts.test.ts @@ -131,7 +131,7 @@ const composerDraftFileMocks = vi.hoisted(() => { }); const composerAttachmentCleanupMocks = vi.hoisted(() => ({ - remove: vi.fn(async () => undefined), + remove: vi.fn(async (_uri: string) => undefined), releaseUploads: vi.fn(async () => undefined), })); @@ -1222,7 +1222,8 @@ describe("mobile composer drafts", () => { appAtomRegistry.get(composerDraftsAtom)[pasteKey]?.attachments.map(({ id }) => id), ).toEqual(["red", "blue"]); - const makeStoredPaste = (id: string) => ({ + // Each paste is stored under a new file name, so only the content digest catches a repeat. + const makeStoredPaste = (id: string, contentDigest?: string) => ({ id, type: "image" as const, name: "pasted-image.png", @@ -1230,13 +1231,27 @@ describe("mobile composer drafts", () => { sizeBytes: 3, fileUri: `file:///documents/t3-composer-attachments/${id}-pasted-image.png`, previewUri: `file:///documents/t3-composer-attachments/${id}-pasted-image.png`, + ...(contentDigest === undefined ? {} : { contentDigest }), }); const storedKey = "new-task:environment-1:project-stored-pastes"; - appendComposerDraftAttachments(storedKey, [makeStoredPaste("red")]); - appendComposerDraftAttachments(storedKey, [makeStoredPaste("green")]); + appendComposerDraftAttachments(storedKey, [makeStoredPaste("red", "digest-red")]); + const repeatCleanup = Promise.withResolvers(); + onTestFinished(() => { + composerAttachmentCleanupMocks.remove.mockImplementation(async () => undefined); + }); + composerAttachmentCleanupMocks.remove.mockImplementation(async (uri) => { + if (uri === makeStoredPaste("red-2").fileUri) repeatCleanup.resolve(); + return undefined; + }); + appendComposerDraftAttachments(storedKey, [ + makeStoredPaste("green", "digest-green"), + makeStoredPaste("red-2", "digest-red"), + makeStoredPaste("legacy"), + ]); expect( appAtomRegistry.get(composerDraftsAtom)[storedKey]?.attachments.map(({ id }) => id), - ).toEqual(["red", "green"]); + ).toEqual(["red", "green", "legacy"]); + await repeatCleanup.promise; }); it("keeps shared attachment files until every draft releases them", async () => { diff --git a/apps/mobile/src/state/use-composer-drafts.ts b/apps/mobile/src/state/use-composer-drafts.ts index 10d8fd7a4f271..8bf91eaf923d0 100644 --- a/apps/mobile/src/state/use-composer-drafts.ts +++ b/apps/mobile/src/state/use-composer-drafts.ts @@ -1425,16 +1425,14 @@ export function appendComposerDraftText(draftKey: string, value: string): void { }); } -// Pasted images all share one name, so an image's inline bytes decide whether it is a repeat. +// Pasted images all share one name, so an image's bytes decide whether it is a repeat. function isSameAttachment(a: DraftComposerAttachment, b: DraftComposerAttachment): boolean { - return ( - a.mimeType === b.mimeType && - a.sizeBytes === b.sizeBytes && - a.name === b.name && - (a.type !== "image" || - b.type !== "image" || - (a.dataUrl === b.dataUrl && a.fileUri === b.fileUri)) - ); + if (a.mimeType !== b.mimeType || a.sizeBytes !== b.sizeBytes || a.name !== b.name) return false; + if (a.type !== "image" || b.type !== "image") return true; + if (a.contentDigest !== undefined && b.contentDigest !== undefined) { + return a.contentDigest === b.contentDigest; + } + return a.dataUrl === b.dataUrl && a.fileUri === b.fileUri; } /** From 7b47a2173d9fc18a5ccf89be8bde3e3cd96bf9b2 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 16:06:44 -0800 Subject: [PATCH 226/324] fix(server): a Claude resume runs one turn, not a phantom wake after it (#41120) --- .../Adapters/ClaudeAdapterV2.test.ts | 21 +++++++++++++++++++ .../Adapters/ClaudeAdapterV2.ts | 21 ++++++++++++++++--- 2 files changed, 39 insertions(+), 3 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index a4aea2ff1ffa9..3d017de3925fa 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -346,6 +346,27 @@ describe("ClaudeAdapterV2 native resume history", () => { ])("selects the native history head for $name", ({ messages, head }) => { assert.equal(ClaudeAdapterV2.claudeResumeSessionAt(messages), head); }); + + it("recognizes history that ends on a failed request", () => { + const failed = { + uuid: "failed", + type: "assistant", + message: { content: "API Error: Request rejected (429)", model: "" }, + }; + assert.isTrue(ClaudeAdapterV2.claudeHistoryEndsOnFailedRequest([prompt, failed])); + assert.isFalse( + ClaudeAdapterV2.claudeHistoryEndsOnFailedRequest([ + prompt, + entry("stop", "user", "[Request interrupted by user]"), + ]), + ); + assert.isFalse( + ClaudeAdapterV2.claudeHistoryEndsOnFailedRequest([ + prompt, + entry("reply", "assistant", "Done"), + ]), + ); + }); }); describe("ClaudeAdapterV2 runtime query policy", () => { diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index a4dc7c5006a8d..370b6b6c4c3f6 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -1369,12 +1369,23 @@ const decodeClaudeHistoryMessages = Schema.decodeUnknownEffect( Schema.Struct({ type: Schema.String, uuid: Schema.String, - message: Schema.Struct({ content: Schema.Unknown }), + message: Schema.Struct({ content: Schema.Unknown, model: Schema.optional(Schema.Unknown) }), }), ), ), ); +// The placeholder reply the CLI records for a failed request. +export function claudeHistoryEndsOnFailedRequest( + messages: ReadonlyArray<{ + readonly type: string; + readonly message: { readonly content: unknown; readonly model?: unknown }; + }>, +): boolean { + const last = messages.at(-1); + return last?.type === "assistant" && last.message.model === ""; +} + // Claude's interactive reply-on-resume removes native abort rows before querying the saved history. export function claudeResumeSessionAt( messages: ReadonlyArray<{ @@ -1569,6 +1580,7 @@ export const layerQueryRunner: Layer.Layer< const { mcpServers, ...sdkOptions } = input.options; // Jobs the agent starts inherit the thread, so port discovery can attribute their servers. let resumeSessionAt = sdkOptions.resumeSessionAt; + let endsOnFailedRequest = false; if (input.resume && sdkOptions.resume !== undefined) { const messages = yield* runClaudeWorker({ method: "getSessionMessages", @@ -1585,14 +1597,17 @@ export const layerQueryRunner: Layer.Layer< resumeSessionAt === undefined ? messages.length : messages.findIndex((message) => message.uuid === resumeSessionAt) + 1; - resumeSessionAt = claudeResumeSessionAt(messages.slice(0, boundary)) ?? resumeSessionAt; + const history = messages.slice(0, boundary); + endsOnFailedRequest = claudeHistoryEndsOnFailedRequest(history); + resumeSessionAt = claudeResumeSessionAt(history) ?? resumeSessionAt; } const queryOptions = { ...sdkOptions, ...(resumeSessionAt === undefined ? {} : { resumeSessionAt }), env: { ...(sdkOptions.env ?? hostEnvironment), - ...(input.resume + // The CLI would re-run a failed request by itself, then run the resume prompt as a second turn. + ...(input.resume && !endsOnFailedRequest ? { CLAUDE_CODE_RESUME_INTERRUPTED_TURN: "1", CLAUDE_CODE_RESUME_REASON: "user_resume", From 0591d32888dbd2f2f25915c245e6f1fe93dc4755 Mon Sep 17 00:00:00 2001 From: Bilal Bakr <62337003+Bil0000@users.noreply.github.com> Date: Mon, 23 Nov 2026 03:17:48 +0300 Subject: [PATCH 227/324] feat(issues): connect more than one Linear account (#39179) Co-authored-by: Julius Marminge --- ...ettingsSourceControlDetailRouteScreens.tsx | 33 ++- .../components/IssueTrackerSection.tsx | 50 +++-- apps/mobile/src/i18n/translations/de.json | 4 +- apps/mobile/src/i18n/translations/en.json | 4 +- apps/mobile/src/i18n/translations/es.json | 4 +- apps/mobile/src/i18n/translations/fr.json | 4 +- apps/mobile/src/i18n/translations/ja.json | 4 +- apps/mobile/src/i18n/translations/ko.json | 4 +- apps/mobile/src/i18n/translations/pt-BR.json | 4 +- apps/mobile/src/i18n/translations/ru.json | 4 +- apps/mobile/src/i18n/translations/sv.json | 4 +- apps/mobile/src/i18n/translations/zh.json | 4 +- .../src/environment/ServerEnvironment.ts | 1 + apps/server/src/issue/IssueService.test.ts | 121 ++++++++++ apps/server/src/issue/IssueService.ts | 182 ++++++++++----- .../src/issue/IssueTrackerConnections.test.ts | 144 ++++++++++++ .../src/issue/IssueTrackerConnections.ts | 208 +++++++++++++++--- apps/server/src/issue/IssueTrackerHostLive.ts | 19 +- .../src/persistence/IssueTrackerBindings.ts | 102 +++++++-- apps/server/src/persistence/Migrations.ts | 2 + .../Migrations/109_IssueTrackerAccounts.ts | 18 ++ .../reconcileV2PreviewMigration.test.ts | 2 + .../settings/IssueTrackerSettings.tsx | 117 ++++++++-- apps/web/src/i18n/translations/de.json | 6 +- apps/web/src/i18n/translations/en.json | 6 +- apps/web/src/i18n/translations/es.json | 6 +- apps/web/src/i18n/translations/fr.json | 6 +- apps/web/src/i18n/translations/ja.json | 6 +- apps/web/src/i18n/translations/ko.json | 6 +- apps/web/src/i18n/translations/pt-BR.json | 6 +- apps/web/src/i18n/translations/ru.json | 6 +- apps/web/src/i18n/translations/sv.json | 6 +- apps/web/src/i18n/translations/zh.json | 6 +- docs/user/source-control.md | 4 +- .../client-runtime/src/issueLinks.test.ts | 20 ++ packages/client-runtime/src/issueLinks.ts | 25 ++- packages/client-runtime/src/issueList.test.ts | 29 +++ packages/client-runtime/src/issueList.ts | 13 +- .../src/state/issueTrackers.test.ts | 23 +- .../client-runtime/src/state/issueTrackers.ts | 52 ++++- packages/contracts/src/environment.ts | 2 + packages/contracts/src/issue.ts | 34 ++- .../src/server/IssueTrackerHost.ts | 56 ++++- 43 files changed, 1155 insertions(+), 202 deletions(-) create mode 100644 apps/server/src/issue/IssueTrackerConnections.test.ts create mode 100644 apps/server/src/persistence/Migrations/109_IssueTrackerAccounts.ts diff --git a/apps/mobile/src/features/settings/SettingsSourceControlDetailRouteScreens.tsx b/apps/mobile/src/features/settings/SettingsSourceControlDetailRouteScreens.tsx index 957cf17a26178..94c5a682f537f 100644 --- a/apps/mobile/src/features/settings/SettingsSourceControlDetailRouteScreens.tsx +++ b/apps/mobile/src/features/settings/SettingsSourceControlDetailRouteScreens.tsx @@ -2,6 +2,7 @@ import { useAtomValue } from "@effect/atom-react"; import type { StaticScreenProps } from "@react-navigation/native"; import { hasIssueTrackerTeams, + issueTrackerBindings, issueTrackerSummary, } from "@t3tools/client-runtime/state/issue-trackers"; import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; @@ -167,6 +168,7 @@ export function SettingsIssueTrackerRouteScreen({ }: StaticScreenProps<{ readonly environmentId: EnvironmentId; readonly tracker: string; + readonly accountId?: string; }>) { const gt = useGT(); const messages = useMessages(); @@ -176,9 +178,17 @@ export function SettingsIssueTrackerRouteScreen({ issueTrackerEnvironment.connections({ environmentId, input: {} }), ); const canEdit = useAtomValue(issueTrackerEnvironment.connect.permissionAtom(environmentId)); - const tracker = query.data?.trackers.find((entry) => entry.tracker === route.params.tracker); + const tracker = [...(query.data?.trackers ?? []), ...(query.data?.accounts ?? [])].find( + (entry) => entry.tracker === route.params.tracker && entry.accountId === route.params.accountId, + ); const disabled = !canWrite || !canEdit; const usable = tracker?.connected === true && tracker.account !== null; + const canAddAccount = + tracker !== undefined && + route.params.accountId === undefined && + (tracker.connected || + (query.data?.accounts ?? []).some((account) => account.tracker === tracker.tracker)) && + environment?.serverConfig.environment.capabilities.issueTrackerAccounts === true; return ( {!environment || !tracker ? ( @@ -186,7 +196,7 @@ export function SettingsIssueTrackerRouteScreen({ ) : ( <> - {issueTrackerSummary(tracker, query.data?.bindings ?? {}, messages)} + {issueTrackerSummary(tracker, issueTrackerBindings(query.data), messages)} - {usable && hasIssueTrackerTeams(tracker, query.data?.bindings ?? {}) ? ( + {usable && hasIssueTrackerTeams(tracker, issueTrackerBindings(query.data)) ? ( ) : null} + {canAddAccount ? ( + + + + ) : null} )} diff --git a/apps/mobile/src/features/settings/components/IssueTrackerSection.tsx b/apps/mobile/src/features/settings/components/IssueTrackerSection.tsx index 285a9e801ab65..4428096bc7530 100644 --- a/apps/mobile/src/features/settings/components/IssueTrackerSection.tsx +++ b/apps/mobile/src/features/settings/components/IssueTrackerSection.tsx @@ -1,6 +1,8 @@ import { boundIssueTrackerScopes, + issueTrackerBindInput, issueTrackerBindingFor, + issueTrackerBindings, issueTrackerScopeOptions, issueTrackerSummary, } from "@t3tools/client-runtime/state/issue-trackers"; @@ -80,7 +82,11 @@ function EnvironmentTrackers(props: { const query = useEnvironmentQuery( issueTrackerEnvironment.connections({ environmentId, input: {} }), ); - const trackers = query.data?.trackers ?? []; + const firstAccounts = query.data?.trackers ?? []; + const trackers = firstAccounts.flatMap((tracker) => [ + tracker, + ...(query.data?.accounts ?? []).filter((account) => account.tracker === tracker.tracker), + ]); if (trackers.length === 0) { return query.error ? ( @@ -94,16 +100,21 @@ function EnvironmentTrackers(props: { {trackers.map((tracker, index) => ( } - label={tracker.displayName} - description={issueTrackerSummary(tracker, query.data?.bindings ?? {}, messages)} + label={ + tracker.workspace + ? `${tracker.displayName} · ${tracker.workspace}` + : tracker.displayName + } + description={issueTrackerSummary(tracker, issueTrackerBindings(query.data), messages)} ready={tracker.connected && tracker.account !== null} separated={index > 0} onPress={() => navigation.navigate("SettingsIssueTracker", { environmentId, tracker: tracker.tracker, + ...(tracker.accountId === undefined ? {} : { accountId: tracker.accountId }), }) } /> @@ -133,6 +144,8 @@ export function IssueTrackerCredentialForm(props: { readonly environmentId: EnvironmentId; readonly tracker: IssueTrackerConnection; readonly disabled: boolean; + /** Saves the credential as a new account instead of replacing this one's. */ + readonly addAccount?: boolean; }) { const gt = useGT(); const { environmentId, tracker } = props; @@ -143,7 +156,12 @@ export function IssueTrackerCredentialForm(props: { const submit = async (token: string | null) => { setBusy(true); setFailure(null); - const result = await connect({ environmentId, input: { tracker: tracker.tracker, token } }); + const result = await connect({ + environmentId, + input: props.addAccount + ? { tracker: tracker.tracker, token, addAccount: true } + : { tracker: tracker.tracker, accountId: tracker.accountId, token }, + }); setBusy(false); if (!AsyncResult.isFailure(result)) { setDraft(""); @@ -154,14 +172,13 @@ export function IssueTrackerCredentialForm(props: { }; const helpUrl = tracker.credential.helpUrl; const locked = props.disabled || busy; + const replacing = tracker.connected && !props.addAccount; return ( void tryOpenExternalUrl(helpUrl)} /> ) : null} - {tracker.connected ? ( + {replacing ? (
    @@ -275,19 +297,22 @@ function ProjectBindings({ if (held && !saving && !refreshing && !refreshFailed) setPicks({}); const busy = saving || (held && refreshing); const bound = (projectId: ProjectId) => - picks[projectId] ?? boundIssueTrackerScopes(tracker.tracker, bindings[projectId]); + picks[projectId] ?? boundIssueTrackerScopes(tracker, bindings[projectId]); if (projects.length === 0 || !hasIssueTrackerTeams(tracker, bindings)) return null; const change = async (projectId: ProjectId, scopes: ReadonlyArray) => { if (busy) return; - const binding = issueTrackerBindingFor(tracker.tracker, bound(projectId), scopes); + const binding = issueTrackerBindingFor(tracker, bound(projectId), scopes); const before = picks[projectId]; setSaving(true); setPicks((current) => ({ ...current, - [projectId]: boundIssueTrackerScopes(tracker.tracker, binding ?? undefined), + [projectId]: boundIssueTrackerScopes(tracker, binding ?? undefined), })); - const result = await bind({ environmentId, input: { projectId, binding } }); + const result = await bind({ + environmentId, + input: issueTrackerBindInput(projectId, tracker, binding), + }); if (result._tag !== "Success") setPicks((current) => ({ ...current, [projectId]: before })); setSaving(false); }; @@ -302,7 +327,7 @@ function ProjectBindings({ )} /> {projects.map((project) => { - // A project bound to another tracker keeps that binding; this picker shows it unbound. + // A project bound to another tracker or account keeps that binding; this picker shows it unbound. const value = bound(project.id); const options = issueTrackerScopeOptions(tracker, value); return ( @@ -359,3 +384,49 @@ function ProjectBindings({ ); } + +/** A credential for another account of the tracker, kept beside this one. */ +function AddAccountRow({ + tracker, + onAdd, +}: { + readonly tracker: IssueTrackerConnection; + readonly onAdd: (token: string) => Promise; +}) { + const gt = useGT(); + const [adding, setAdding] = useState(false); + const inputId = `issue-tracker-${tracker.tracker}-add-account`; + if (!adding) { + return ( + setAdding(true)}> + + Add account + + } + /> + ); + } + return ( + {tracker.credential.label}} + description={gt("For the new {tracker} account.", { tracker: tracker.displayName })} + control={ + { + if (next.trim()) void onAdd(next.trim()).then((added) => added && setAdding(false)); + }} + /> + } + /> + ); +} diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 8d5cb7d817bb1..ecdb3d4220e67 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -12490,5 +12490,9 @@ "27d76249d09eb69f": "Review-Leitfaden bereit", "faa3bb26abb39c93": "Review-Leitfaden fehlgeschlagen", "b7df38b7d8792d78": "Leitfaden öffnen", - "9e91e9a77b664e4e": "Review-Leitfaden konnte nicht gestartet werden" + "9e91e9a77b664e4e": "Review-Leitfaden konnte nicht gestartet werden", + "99d51127f573296b": "Weiteres Konto", + "8ec2c57414669b79": "Verbinde einen zweiten {tracker}-Workspace oder -Nutzer.", + "99963c0142e17f00": "Für das neue {tracker}-Konto.", + "6d8e4ebc889bace9": "Konto hinzufügen" } diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 6c5ef49b77f43..0cc2d503fd620 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -12499,5 +12499,9 @@ "27d76249d09eb69f": "Review guide ready", "faa3bb26abb39c93": "Review guide failed", "b7df38b7d8792d78": "Open guide", - "9e91e9a77b664e4e": "Could not start a review guide" + "9e91e9a77b664e4e": "Could not start a review guide", + "99d51127f573296b": "Another account", + "8ec2c57414669b79": "Connect a second {tracker} workspace or user.", + "99963c0142e17f00": "For the new {tracker} account.", + "6d8e4ebc889bace9": "Add account" } diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 1f4ed2cf548ee..daf936020ff3a 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -12485,5 +12485,9 @@ "27d76249d09eb69f": "Guía de revisión lista", "faa3bb26abb39c93": "Falló la guía de revisión", "b7df38b7d8792d78": "Abrir guía", - "9e91e9a77b664e4e": "No se pudo iniciar una guía de revisión" + "9e91e9a77b664e4e": "No se pudo iniciar una guía de revisión", + "99d51127f573296b": "Otra cuenta", + "8ec2c57414669b79": "Conecta un segundo espacio de trabajo o usuario de {tracker}.", + "99963c0142e17f00": "Para la nueva cuenta de {tracker}.", + "6d8e4ebc889bace9": "Añadir cuenta" } diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 72da8bf8e23b2..713eca77f3127 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -12490,5 +12490,9 @@ "27d76249d09eb69f": "Guide de revue prêt", "faa3bb26abb39c93": "Échec du guide de revue", "b7df38b7d8792d78": "Ouvrir le guide", - "9e91e9a77b664e4e": "Impossible de démarrer un guide de revue" + "9e91e9a77b664e4e": "Impossible de démarrer un guide de revue", + "99d51127f573296b": "Autre compte", + "8ec2c57414669b79": "Connectez un second espace de travail ou utilisateur {tracker}.", + "99963c0142e17f00": "Pour le nouveau compte {tracker}.", + "6d8e4ebc889bace9": "Ajouter un compte" } diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 28945ae29dca3..2b44f05d584e1 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -12439,5 +12439,9 @@ "27d76249d09eb69f": "レビューガイドの準備ができました", "faa3bb26abb39c93": "レビューガイドの作成に失敗しました", "b7df38b7d8792d78": "ガイドを開く", - "9e91e9a77b664e4e": "レビューガイドを開始できませんでした" + "9e91e9a77b664e4e": "レビューガイドを開始できませんでした", + "99d51127f573296b": "別のアカウント", + "8ec2c57414669b79": "2つ目の {tracker} ワークスペースまたはユーザーを接続します。", + "99963c0142e17f00": "新しい {tracker} アカウント用です。", + "6d8e4ebc889bace9": "アカウントを追加" } diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 35f6cc3549436..48dc094c371ad 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -12434,5 +12434,9 @@ "27d76249d09eb69f": "검토 가이드 준비됨", "faa3bb26abb39c93": "검토 가이드 실패", "b7df38b7d8792d78": "가이드 열기", - "9e91e9a77b664e4e": "검토 가이드를 시작할 수 없습니다" + "9e91e9a77b664e4e": "검토 가이드를 시작할 수 없습니다", + "99d51127f573296b": "다른 계정", + "8ec2c57414669b79": "두 번째 {tracker} 워크스페이스 또는 사용자를 연결합니다.", + "99963c0142e17f00": "새 {tracker} 계정용입니다.", + "6d8e4ebc889bace9": "계정 추가" } diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 85fefb672d30c..9cc052192b4eb 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -12490,5 +12490,9 @@ "27d76249d09eb69f": "Guia de revisão pronto", "faa3bb26abb39c93": "O guia de revisão falhou", "b7df38b7d8792d78": "Abrir guia", - "9e91e9a77b664e4e": "Não foi possível iniciar um guia de revisão" + "9e91e9a77b664e4e": "Não foi possível iniciar um guia de revisão", + "99d51127f573296b": "Outra conta", + "8ec2c57414669b79": "Conecte um segundo espaço de trabalho ou usuário do {tracker}.", + "99963c0142e17f00": "Para a nova conta do {tracker}.", + "6d8e4ebc889bace9": "Adicionar conta" } diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index f4d45a79d0b52..1d8bc14fde51f 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -12490,5 +12490,9 @@ "27d76249d09eb69f": "Гид по ревью готов", "faa3bb26abb39c93": "Не удалось создать гид по ревью", "b7df38b7d8792d78": "Открыть гид", - "9e91e9a77b664e4e": "Не удалось запустить гид по ревью" + "9e91e9a77b664e4e": "Не удалось запустить гид по ревью", + "99d51127f573296b": "Другой аккаунт", + "8ec2c57414669b79": "Подключите второе рабочее пространство или пользователя {tracker}.", + "99963c0142e17f00": "Для нового аккаунта {tracker}.", + "6d8e4ebc889bace9": "Добавить аккаунт" } diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 99818c1f2ed37..234479a1b2558 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -12497,5 +12497,9 @@ "27d76249d09eb69f": "Granskningsguiden är klar", "faa3bb26abb39c93": "Granskningsguiden misslyckades", "b7df38b7d8792d78": "Öppna guiden", - "9e91e9a77b664e4e": "Kunde inte starta en granskningsguide" + "9e91e9a77b664e4e": "Kunde inte starta en granskningsguide", + "99d51127f573296b": "Ett konto till", + "8ec2c57414669b79": "Anslut en andra {tracker}-arbetsyta eller användare.", + "99963c0142e17f00": "För det nya {tracker}-kontot.", + "6d8e4ebc889bace9": "Lägg till konto" } diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 09d04201cd2f8..19eff455a318c 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -12516,5 +12516,9 @@ "27d76249d09eb69f": "审查导览已就绪", "faa3bb26abb39c93": "审查导览生成失败", "b7df38b7d8792d78": "打开导览", - "9e91e9a77b664e4e": "无法开始生成审查导览" + "9e91e9a77b664e4e": "无法开始生成审查导览", + "99d51127f573296b": "其他账号", + "8ec2c57414669b79": "连接第二个 {tracker} 工作区或用户。", + "99963c0142e17f00": "用于新的 {tracker} 账号。", + "6d8e4ebc889bace9": "添加账号" } diff --git a/docs/user/source-control.md b/docs/user/source-control.md index b6702c13de5d9..ba951c3fe9bda 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -416,7 +416,9 @@ To list Linear issues beside a project's, connect Linear with an API key under Settings → Source control & issues, then pick one or more teams for that project there. Pick another team at any time to add it; uncheck every team to unbind the project. Each team's issues appear in the Linear group of the issue list, sorted with the rest by last update, and -each can be loaded further on its own. Agents file new issues in the first team picked unless you name another bound team. +each can be loaded further on its own. Agents file new issues in the first team picked unless you name another bound team. To +connect another Linear workspace or user, add another account in the same place; each project +reads its teams through the account you picked them under. Select an issue to open it beside the list: description, comments, state changes, linked pull requests, labels, assignees, and reactions. Linked pull requests open in the same panel. You can diff --git a/packages/client-runtime/src/issueLinks.test.ts b/packages/client-runtime/src/issueLinks.test.ts index 661dfe1a94cae..1f2683f92cd59 100644 --- a/packages/client-runtime/src/issueLinks.test.ts +++ b/packages/client-runtime/src/issueLinks.test.ts @@ -1,5 +1,6 @@ import { EnvironmentId, + IssueTrackerAccountId, IssueTrackerKind, ProjectId, SourceControlProviderKind, @@ -138,6 +139,25 @@ describe("resolveIssueLinkTarget", () => { expect( resolveIssueLinkTarget({ url: "https://linear.app/acme/issue/WEB-17", projects }), ).toBeNull(); + + // A second account reaches its own workspace, through only the projects bound with it. + const accountId = IssueTrackerAccountId.make("second"); + const [p1, p2] = [ProjectId.make("p1"), ProjectId.make("p2")]; + const both = (url: string) => + resolveIssueLinkTarget({ + url, + projects, + trackers: { + ...trackers, + accounts: [{ ...trackers.trackers[0]!, accountId, workspace: "othercorp" }], + bindings: { [p1]: trackers.bindings[p1]! }, + accountBindings: { [p2]: { ...trackers.bindings[p2]!, accountId } }, + }, + })?.ref.projectId; + expect([ + both("https://linear.app/othercorp/issue/WEB-17"), + both("https://linear.app/acme/issue/WEB-17"), + ]).toEqual(["p2", "p1"]); }); it.each([ diff --git a/packages/client-runtime/src/issueLinks.ts b/packages/client-runtime/src/issueLinks.ts index db06b1b0a218f..a81ac7831396d 100644 --- a/packages/client-runtime/src/issueLinks.ts +++ b/packages/client-runtime/src/issueLinks.ts @@ -82,8 +82,8 @@ export function mayContainStandaloneIssueLink(text: string): boolean { /** * A standalone tracker link resolves through the project bound to its scope, else any bound to - * the tracker, and only when it names the workspace the credential reaches: team keys repeat - * across workspaces, so a link elsewhere stays an ordinary link. + * the tracker, and only through an account whose credential reaches the workspace it names: team + * keys repeat across workspaces, so a link elsewhere stays an ordinary link. */ function resolveStandaloneIssueLink( url: string, @@ -94,14 +94,23 @@ function resolveStandaloneIssueLink( const parsed = trackers === undefined ? null : parseStandaloneIssueLink(url); if (parsed === null || trackers === undefined) return null; const { tracker, link } = parsed; - const workspace = trackers.trackers.find( - (connection) => connection.tracker === tracker && connection.account !== null, - )?.workspace; - if (workspace?.toLowerCase() !== link.workspace.toLowerCase()) return null; - const { bindings } = trackers; + const accounts = new Set( + [...trackers.trackers, ...(trackers.accounts ?? [])] + .filter( + (connection) => + connection.tracker === tracker && + connection.account !== null && + connection.workspace?.toLowerCase() === link.workspace.toLowerCase(), + ) + .map((connection) => connection.accountId ?? null), + ); + if (accounts.size === 0) return null; + const bindings = { ...trackers.bindings, ...trackers.accountBindings }; const onTracker = projects.flatMap((project) => { const binding = bindings[project.id]; - return binding?.tracker === tracker ? [{ project, binding }] : []; + return binding?.tracker === tracker && accounts.has(binding.accountId ?? null) + ? [{ project, binding }] + : []; }); const preferFirst = (candidates: typeof onTracker) => candidates.find((candidate) => candidate.project.id === preferredProjectId) ?? candidates[0]; diff --git a/packages/client-runtime/src/issueList.test.ts b/packages/client-runtime/src/issueList.test.ts index 5085c10e51887..49bab599b4f51 100644 --- a/packages/client-runtime/src/issueList.test.ts +++ b/packages/client-runtime/src/issueList.test.ts @@ -144,6 +144,35 @@ describe("issueFilterScopes", () => { expect(issueFilterScopes(held, [])).toEqual([{ environmentId, input: scope }]); }); + it("offers the same team key of two Linear accounts as two scopes", () => { + const first = { + projectId: api, + tracker: "linear" as IssueTrackerKind, + host: "linear.app", + scope: "ENG", + }; + const second = hold( + answer({ + trackers: [tracker({})], + scopes: [first, { ...first, projectId: "home" as ProjectId }], + }), + ); + const other = hold( + answer({ trackers: [tracker({})], scopes: [{ ...first, projectId: "o" as ProjectId }] }), + ); + // Older servers name no scopes; their rows stand in, once per team on that server. + const older = hold( + answer({ trackers: [tracker({})], entries: [linearRow, { ...linearRow, key: "ENG-2" }] }), + ); + const count = (...pages: ReadonlyArray>) => + issueFilterScopes( + new Map(pages.map((page, index) => [`env-${index}` as EnvironmentId, page])), + [], + ).length; + expect([count(second), count(second, other), count(other, second)]).toEqual([2, 3, 3]); + expect([count(older), count(older, second), count(second, older)]).toEqual([1, 3, 3]); + }); + it("skips a tracker that cannot be read", () => { const held = new Map([ [ diff --git a/packages/client-runtime/src/issueList.ts b/packages/client-runtime/src/issueList.ts index 5e01c4683830d..1a99f54e0f580 100644 --- a/packages/client-runtime/src/issueList.ts +++ b/packages/client-runtime/src/issueList.ts @@ -170,6 +170,9 @@ export function issueFilterScopes( ) { const scopes: Array<{ readonly environmentId: EnvironmentId; readonly input: IssueScopeRef }> = []; + // A repository's scope is the same scope on every server. A bound tracker's scope is not: two + // accounts, or two servers, may both have an ENG team, so those are deduplicated per server only. + const fromRepository = new Set(); for (const [environmentId, page] of held) { for (const project of projects) { if (project.environmentId !== environmentId) continue; @@ -186,10 +189,9 @@ export function issueFilterScopes( ) ) continue; - scopes.push({ - environmentId, - input: { projectId: project.id, tracker: tracker.tracker, host, scope }, - }); + const input = { projectId: project.id, tracker: tracker.tracker, host, scope }; + fromRepository.add(input); + scopes.push({ environmentId, input }); } } // A tracker bound in settings (a Linear team) is no repository's; the answer names its scope, @@ -209,9 +211,12 @@ export function issueFilterScopes( ); if (!tracker?.configured) continue; if (!tracker.capabilities?.labels && !tracker.capabilities?.assignees) continue; + // An answer names each scope once per account; rows standing in for one repeat. if ( scopes.some( (s) => + (fromRepository.has(s.input) || + (page.answer.scopes === undefined && s.environmentId === environmentId)) && s.input.scope.toLowerCase() === input.scope.toLowerCase() && s.input.host?.toLowerCase() === host, ) diff --git a/packages/client-runtime/src/state/issueTrackers.test.ts b/packages/client-runtime/src/state/issueTrackers.test.ts index 32d459bf79ed8..ba2fba0ad1da4 100644 --- a/packages/client-runtime/src/state/issueTrackers.test.ts +++ b/packages/client-runtime/src/state/issueTrackers.test.ts @@ -1,7 +1,15 @@ -import { IssueTrackerKind, MAX_ISSUE_TRACKER_ADDITIONAL_SCOPES } from "@t3tools/contracts"; +import { + IssueTrackerAccountId, + IssueTrackerKind, + MAX_ISSUE_TRACKER_ADDITIONAL_SCOPES, +} from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { issueTrackerScopeOptions } from "./issueTrackers.ts"; +import { + boundIssueTrackerScopes, + issueTrackerBindingFor, + issueTrackerScopeOptions, +} from "./issueTrackers.ts"; describe("issueTrackerScopeOptions", () => { it("offers no new team once the binding is full, and keeps bound ones removable", () => { @@ -34,3 +42,14 @@ describe("issueTrackerScopeOptions", () => { expect(issueTrackerScopeOptions(tracker, ["ENG"]).every((scope) => scope.addable)).toBe(true); }); }); + +describe("boundIssueTrackerScopes", () => { + it("keeps each account's teams apart, and binds new picks with that account", () => { + const tracker = IssueTrackerKind.make("linear"); + const second = { tracker, accountId: IssueTrackerAccountId.make("second") }; + const binding = issueTrackerBindingFor(second, [], ["ENG", "OPS"]) ?? undefined; + expect(binding).toEqual({ ...second, scope: "ENG", additionalScopes: ["OPS"] }); + expect(boundIssueTrackerScopes(second, binding)).toEqual(["ENG", "OPS"]); + expect(boundIssueTrackerScopes({ tracker }, binding)).toEqual([]); + }); +}); diff --git a/packages/client-runtime/src/state/issueTrackers.ts b/packages/client-runtime/src/state/issueTrackers.ts index a4bb5187f8406..74c6bfb0674d8 100644 --- a/packages/client-runtime/src/state/issueTrackers.ts +++ b/packages/client-runtime/src/state/issueTrackers.ts @@ -2,10 +2,11 @@ import { MAX_ISSUE_TRACKER_ADDITIONAL_SCOPES, WS_METHODS, issueTrackerBindingScopes, + type IssueTrackerBindProjectInput, type IssueTrackerConnection, type IssueTrackerConnectionList, - type IssueTrackerKind, type IssueTrackerProjectBinding, + type ProjectId, } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import { Atom } from "effect/reactivity"; @@ -81,6 +82,21 @@ export function issueTrackerDetailText(detail: string, resolve: MFunctionType = return knownTrackerSentence(detail, SERVER_TRACKER_DETAILS, resolve); } +/** Every project's binding, whichever account it was made with. */ +export function issueTrackerBindings( + list: IssueTrackerConnectionList | null | undefined, +): IssueTrackerConnectionList["bindings"] { + return { ...list?.bindings, ...list?.accountBindings }; +} + +/** Whether a project binding reads through this account of the tracker. */ +function issueTrackerBindingIsFor( + binding: IssueTrackerProjectBinding, + tracker: Pick, +): boolean { + return binding.tracker === tracker.tracker && binding.accountId === tracker.accountId; +} + /** * The line under a tracker's name. A connected tracker lists nothing until a project is linked * to one of its scopes, so the line says how many are, and what to do when none is. @@ -98,8 +114,8 @@ export function issueTrackerSummary( ); if (tracker.account === null) return tracker.detail ?? resolve(msg("The saved credential was rejected.")); - const linked = Object.values(bindings).filter( - (binding) => binding.tracker === tracker.tracker, + const linked = Object.values(bindings).filter((binding) => + issueTrackerBindingIsFor(binding, tracker), ).length; return linked === 0 ? knownTrackerSentence( @@ -120,22 +136,42 @@ export function issueTrackerSummary( ); } +type TrackerAccount = Pick; + export function boundIssueTrackerScopes( - tracker: IssueTrackerKind, + tracker: TrackerAccount, binding: IssueTrackerProjectBinding | undefined, ): ReadonlyArray { - return binding?.tracker === tracker ? issueTrackerBindingScopes(binding) : []; + return binding !== undefined && issueTrackerBindingIsFor(binding, tracker) + ? issueTrackerBindingScopes(binding) + : []; } export function issueTrackerBindingFor( - tracker: IssueTrackerKind, + { tracker, accountId }: TrackerAccount, current: ReadonlyArray, scopes: ReadonlyArray, ): IssueTrackerProjectBinding | null { const kept = current.filter((key) => scopes.includes(key)); const [scope, ...additionalScopes] = [...kept, ...scopes.filter((key) => !kept.includes(key))]; if (scope === undefined) return null; - return additionalScopes.length === 0 ? { tracker, scope } : { tracker, scope, additionalScopes }; + return { + tracker, + ...(accountId === undefined ? {} : { accountId }), + scope, + ...(additionalScopes.length === 0 ? {} : { additionalScopes }), + }; +} + +/** The request that saves a project's picks under this account; an unbind names the account. */ +export function issueTrackerBindInput( + projectId: ProjectId, + { accountId }: TrackerAccount, + binding: IssueTrackerProjectBinding | null, +): IssueTrackerBindProjectInput { + return binding === null && accountId !== undefined + ? { projectId, binding, accountId } + : { projectId, binding }; } export function issueTrackerScopeOptions( @@ -156,6 +192,6 @@ export function hasIssueTrackerTeams( ): boolean { return ( tracker.scopes.length > 0 || - Object.values(bindings).some((binding) => binding.tracker === tracker.tracker) + Object.values(bindings).some((binding) => issueTrackerBindingIsFor(binding, tracker)) ); } diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index ae5bed14b44ba..b4f9f9c9d6865 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -224,6 +224,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({ agentFeedback: Schema.optionalKey(Schema.Boolean), /** Answers `issues.linkedThreads`, the threads an issue is linked to. */ issueLinkedThreads: Schema.optionalKey(Schema.Boolean), + /** Keeps more than one account per standalone issue tracker; older servers keep one. */ + issueTrackerAccounts: Schema.optionalKey(Schema.Boolean), }); export type ExecutionEnvironmentCapabilities = typeof ExecutionEnvironmentCapabilities.Type; diff --git a/packages/contracts/src/issue.ts b/packages/contracts/src/issue.ts index 93ed9daf6fba8..48ca2933b4039 100644 --- a/packages/contracts/src/issue.ts +++ b/packages/contracts/src/issue.ts @@ -30,6 +30,16 @@ export const IssueTrackerKind = TrimmedNonEmptyString.check( ).pipe(Schema.brand("IssueTrackerKind")); export type IssueTrackerKind = typeof IssueTrackerKind.Type; +/** + * One saved account of a standalone tracker. A tracker's first account has none: it predates + * accounts, and keeps its credential and bindings unchanged. + */ +export const IssueTrackerAccountId = TrimmedNonEmptyString.check( + Schema.isMaxLength(64), + Schema.isPattern(/^[a-z0-9][a-z0-9-]*$/), +).pipe(Schema.brand("IssueTrackerAccountId")); +export type IssueTrackerAccountId = typeof IssueTrackerAccountId.Type; + export const IssueActor = PullRequestActor; export type IssueActor = typeof IssueActor.Type; @@ -590,6 +600,8 @@ export const MAX_ISSUE_TRACKER_ADDITIONAL_SCOPES = 250; */ export const IssueTrackerProjectBinding = Schema.Struct({ tracker: IssueTrackerKind, + /** The account the scope is read with; absent for the tracker's first account. */ + accountId: Schema.optional(IssueTrackerAccountId), scope: TrimmedNonEmptyString, additionalScopes: Schema.optionalKey( Schema.Array(TrimmedNonEmptyString).check( @@ -617,6 +629,8 @@ export type IssueTrackerScope = typeof IssueTrackerScope.Type; */ export const IssueTrackerConnection = Schema.Struct({ ...StandaloneIssueTrackerDescriptor.fields, + /** Which of the tracker's accounts this is; absent for its first. */ + accountId: Schema.optional(IssueTrackerAccountId), /** A credential is stored. It may still be rejected, which `account` being null reports. */ connected: Schema.Boolean, /** Who the credential signs in as, or null when there is none or it was refused. */ @@ -630,15 +644,29 @@ export const IssueTrackerConnection = Schema.Struct({ export type IssueTrackerConnection = typeof IssueTrackerConnection.Type; export const IssueTrackerConnectionList = Schema.Struct({ + /** Each standalone tracker's first account. */ trackers: Schema.Array(IssueTrackerConnection), - /** Which standalone tracker scopes each bound project reads; a project absent here reads none. */ + /** The accounts added beside a tracker's first, oldest first. Absent from older servers. */ + accounts: Schema.optional(Schema.Array(IssueTrackerConnection)), + /** + * Which standalone tracker scopes each project bound with a tracker's first account reads. A + * project bound with an added account is in `accountBindings` instead, so older clients never + * read another account's team as the first account's. + */ bindings: Schema.Record(ProjectId, IssueTrackerProjectBinding), + /** Projects bound with an added account. Absent from older servers. */ + accountBindings: Schema.optional(Schema.Record(ProjectId, IssueTrackerProjectBinding)), }); export type IssueTrackerConnectionList = typeof IssueTrackerConnectionList.Type; -/** A credential for one standalone tracker; `null` disconnects it and unbinds its projects. */ +/** + * A credential for one standalone tracker account; `null` disconnects it and unbinds its + * projects. `addAccount` saves the credential as a new account beside the existing ones. + */ export const IssueTrackerConnectInput = Schema.Struct({ tracker: IssueTrackerKind, + accountId: Schema.optional(IssueTrackerAccountId), + addAccount: Schema.optional(Schema.Boolean), token: Schema.NullOr(TrimmedNonEmptyString.check(Schema.isMaxLength(4_096))), }); export type IssueTrackerConnectInput = typeof IssueTrackerConnectInput.Type; @@ -647,6 +675,8 @@ export const IssueTrackerBindProjectInput = Schema.Struct({ projectId: ProjectId, /** Null unbinds. */ binding: Schema.NullOr(IssueTrackerProjectBinding), + /** On an unbind, the account the binding was made with; absent for a tracker's first. */ + accountId: Schema.optionalKey(IssueTrackerAccountId), }); export type IssueTrackerBindProjectInput = typeof IssueTrackerBindProjectInput.Type; diff --git a/packages/source-control-core/src/server/IssueTrackerHost.ts b/packages/source-control-core/src/server/IssueTrackerHost.ts index efc51b5046de2..eb85a2f711a5e 100644 --- a/packages/source-control-core/src/server/IssueTrackerHost.ts +++ b/packages/source-control-core/src/server/IssueTrackerHost.ts @@ -2,12 +2,12 @@ * What a standalone tracker package may ask of the server it runs in: the credential the user * saved in Settings. Git-host trackers never need it; their CLIs carry their own credentials. */ -import type { IssueTrackerKind } from "@t3tools/contracts"; +import type { IssueTrackerAccountId, IssueTrackerKind } from "@t3tools/contracts"; import * as Context from "effect/Context"; -import type * as Effect from "effect/Effect"; +import * as Effect from "effect/Effect"; import type * as Option from "effect/Option"; -import type { IssueTrackerError } from "./IssueTracker.ts"; +import type { IssueTrackerApi, IssueTrackerError } from "./IssueTracker.ts"; export class IssueTrackerHost extends Context.Service< IssueTrackerHost, @@ -20,3 +20,53 @@ export class IssueTrackerHost extends Context.Service< }; } >()("@t3tools/source-control-core/server/IssueTrackerHost") {} + +/** + * The account a standalone tracker call is made as, set by the server around each call; null is + * the tracker's first account. A tracker never reads it: `credentials.get` does. + */ +export const IssueTrackerAccount = Context.Reference( + "@t3tools/source-control-core/server/IssueTrackerHost/IssueTrackerAccount", + { defaultValue: () => null }, +); + +/** The tracker with every call made as one account, so no call site can forget to name it. */ +export function asIssueTrackerAccount( + api: IssueTrackerApi, + accountId: IssueTrackerAccountId | null, +): IssueTrackerApi { + if (accountId === null) return api; + const as = (effect: Effect.Effect) => + Effect.provideService(effect, IssueTrackerAccount, accountId); + const { + getIssueLink, + create, + comment, + update, + setState, + setReaction, + listTemplates, + listCandidates, + } = api; + // Every key is required here, so a method added to IssueTrackerApi fails to compile until it + // is wrapped instead of silently running as the first account. + const wrapped: { readonly [K in keyof IssueTrackerApi]-?: IssueTrackerApi[K] | undefined } = { + kind: api.kind, + capabilities: api.capabilities, + getViewer: (input) => as(api.getViewer(input)), + listIssues: (input) => as(api.listIssues(input)), + getIssue: (input) => as(api.getIssue(input)), + getComments: (input) => as(api.getComments(input)), + getIssueLink: getIssueLink && ((input) => as(getIssueLink(input))), + create: create && ((input) => as(create(input))), + comment: comment && ((input) => as(comment(input))), + update: update && ((input) => as(update(input))), + setState: setState && ((input) => as(setState(input))), + setReaction: setReaction && ((input) => as(setReaction(input))), + listTemplates: listTemplates && ((input) => as(listTemplates(input))), + listCandidates: listCandidates && ((input) => as(listCandidates(input))), + }; + return Object.fromEntries( + Object.entries(wrapped).filter(([, value]) => value !== undefined), + ) as unknown as IssueTrackerApi; +} From 43af49bab0c85de2b964f020fbde569a1ef65daf Mon Sep 17 00:00:00 2001 From: Victor Date: Sun, 22 Nov 2026 18:19:38 -0600 Subject: [PATCH 228/324] fix(server): keep inactive threads whose branch has an open PR (#41116) Co-authored-by: Julius Marminge --- .../ThreadSettlementService.test.ts | 62 +++++++++++++++++++ .../ThreadSettlementService.ts | 59 ++++++++++++++---- 2 files changed, 110 insertions(+), 11 deletions(-) diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts index 07bb2d64d80a5..80783a05f57ea 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts @@ -3,6 +3,7 @@ import { assert, describe, expect, it } from "@effect/vitest"; import * as DateTime from "effect/DateTime"; import { DEFAULT_SERVER_SETTINGS, + GitManagerError, ProjectId, EventId, ProviderInstanceId, @@ -959,6 +960,67 @@ describe("ThreadSettlementServiceV2 worker", () => { }), ); + it.effect("keeps idle unlinked branch threads with an open PR under retention", () => + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse(NOW)); + const earlier = "2026-08-19T00:00:00.000Z"; + const openPr = makeThread("idle-open", { + branch: "open", + latestUserMessageAt: DateTime.makeUnsafe(earlier), + }); + const reused = makeThread("idle-reused", { branch: "reused" }); + const link = persistedLink("open", DateTime.makeUnsafe("2026-06-20T00:00:00.000Z")); + const reusedOwner = makeThread("archived-reused-owner", { + branch: "reused", + archivedAt: DateTime.makeUnsafe("2026-07-02T00:00:00.000Z"), + pullRequests: [ + { + ...link, + snapshot: { ...link.snapshot!, state: "merged", mergedAt: "2026-07-01T00:00:00.000Z" }, + }, + ], + }); + const noPr = makeThread("idle-none", { branch: "none" }); + const merged = makeThread("idle-merged", { branch: "merged" }); + const failed = makeThread("idle-failed", { branch: "failed" }); + const fixture = yield* makeHarness({ + snapshot: makeSnapshot([openPr, reused, reusedOwner, noPr, merged, failed]), + settings: { + ...DEFAULT_SERVER_SETTINGS, + sidebarAutoSettleAfterDays: 3, + sidebarAutoSettleKeepPullRequests: true, + }, + branchPullRequest: ({ branch, cwd }, options) => + branch === "open" + ? Effect.succeed(makeBranchPullRequest("open")) + : branch === "reused" + ? Effect.succeed( + options?.freshGitState === true + ? { ...makeBranchPullRequest("open"), number: 43 } + : { ...makeBranchPullRequest("merged"), mergedAt: "2026-07-01T00:00:00.000Z" }, + ) + : branch === "merged" + ? Effect.succeed({ ...makeBranchPullRequest("merged"), mergedAt: earlier }) + : branch === "failed" + ? Effect.fail( + new GitManagerError({ + operation: "branchPullRequest", + cwd, + detail: "failed", + }), + ) + : Effect.succeed(null), + }); + yield* Effect.gen(function* () { + const service = yield* ThreadSettlementService.ThreadSettlementServiceV2; + yield* startHarness(service, fixture.activation, fixture.snapshotReads); + expect( + (yield* Ref.get(fixture.commands)).map((command) => command.threadId).toSorted(), + ).toEqual([failed.id, merged.id, noPr.id]); + }).pipe(Effect.provide(fixture.layer)); + }), + ); + it.effect("does not auto-settle a thread whose terminal has an active subprocess", () => Effect.gen(function* () { yield* TestClock.setTime(Date.parse(NOW)); diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.ts index ef0894f3ecbeb..308ec1795a315 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.ts @@ -442,6 +442,7 @@ export const make = Effect.gen(function* () { ), ); + const deferred = new Set(); const lookupCandidates = (yield* Effect.forEach( candidates, (thread) => { @@ -456,7 +457,17 @@ export const make = Effect.gen(function* () { autoSettleOnMerge: projectSettings.sidebarAutoSettleOnMerge, autoSettleKeepPullRequests: projectSettings.sidebarAutoSettleKeepPullRequests, }); - return settledAt === null ? Effect.succeed(thread) : settleThread(thread, null); + if (settledAt === null) return Effect.succeed(thread); + if ( + projectSettings.sidebarAutoSettleKeepPullRequests && + thread.branch !== null && + visibleThreadPullRequests(thread.pullRequests ?? []).length === 0 + ) { + // Retention needs the branch lookup to see whether an open PR keeps this thread. + deferred.add(thread.id); + return Effect.succeed(thread); + } + return settleThread(thread, null); }, { concurrency: 8 }, )) @@ -636,7 +647,10 @@ export const make = Effect.gen(function* () { } const refresh = group.filter((member) => shellClosedThreads.delete(member.id)).length > 0; const key = lookupKey(thread); - if (scheduledLookups !== null && !refresh && !scheduledLookups.has(key)) return undefined; + const hasDeferred = group.some((member) => deferred.has(member.id)); + if (scheduledLookups !== null && !refresh && !hasDeferred && !scheduledLookups.has(key)) { + return undefined; + } // Remembered git state is enough to rule a thread out; only an answer // that would settle it is confirmed against fresh git state. const remembered = yield* git.branchPullRequest( @@ -644,9 +658,16 @@ export const make = Effect.gen(function* () { { refresh, confirmTerminal: false }, ); noPullRequestRechecks.record(key, nowMs, remembered !== null); - if (ownedByAnotherThread(remembered)) return undefined; - if (refresh || remembered === null || remembered.state === "open") return remembered; - if (!(yield* wouldSettle(group, remembered))) return undefined; + if (refresh || remembered === null || remembered.state === "open") { + return ownedByAnotherThread(remembered) ? undefined : remembered; + } + // A deferred thread confirms first: a reused branch can have a new open PR. + if ( + !hasDeferred && + (ownedByAnotherThread(remembered) || !(yield* wouldSettle(group, remembered))) + ) { + return undefined; + } const fresh = yield* git.branchPullRequest( { cwd, branch: thread.branch }, { freshGitState: true }, @@ -661,13 +682,23 @@ export const make = Effect.gen(function* () { : noPullRequestRechecks.select( nowMs, [...groups] - .filter(([key]) => key.startsWith('["branch",')) + .filter( + ([key, group]) => + key.startsWith('["branch",') && !group.some((member) => deferred.has(member.id)), + ) .map(([key, group]) => ({ key, activityAtMs: Math.max(...group.map(threadActivityAtMs)), })), ); + const settleDeferred = (group: ReadonlyArray<(typeof lookupCandidates)[number]>) => + Effect.forEach( + group.filter((thread) => deferred.has(thread.id)), + (thread) => settleThread(thread, null), + { discard: true }, + ); + yield* Effect.forEach( groups.values(), (group) => @@ -679,10 +710,16 @@ export const make = Effect.gen(function* () { () => Effect.void, ), ); - if (pullRequest === undefined) return; - yield* Effect.forEach(group, (thread) => settleThread(thread, pullRequest), { - discard: true, - }); + if (pullRequest === undefined) return yield* settleDeferred(group); + yield* Effect.forEach( + group, + (thread) => + settleThread( + thread, + deferred.has(thread.id) && pullRequest?.state !== "open" ? null : pullRequest, + ), + { discard: true }, + ); }).pipe( Effect.catchCauseIf( (cause) => !Cause.hasInterruptsOnly(cause), @@ -690,7 +727,7 @@ export const make = Effect.gen(function* () { Effect.logWarning("automatic thread settlement skipped", { threadIds: group.map((thread) => thread.id), cause: Cause.pretty(cause), - }), + }).pipe(Effect.andThen(settleDeferred(group))), ), ), { concurrency: 8, discard: true }, From 1b59af07927ac8eba8efeffdbcaba8b92d645daf Mon Sep 17 00:00:00 2001 From: Ernest0N Date: Mon, 23 Nov 2026 04:38:19 +0400 Subject: [PATCH 229/324] fix(mobile): enlarge PR file Viewed tap target (#39950) Co-authored-by: Julius Marminge Co-authored-by: Claude Opus 5.5 --- .../modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt | 5 +++++ .../expo/modules/t3reviewdiff/T3ReviewDiffView.kt | 2 +- .../t3-review-diff/ios/T3ReviewDiffView.swift | 12 ++++++++++-- .../modules/t3reviewdiff/ReviewDiffGeometryTest.kt | 12 ++++++++++++ 4 files changed, 28 insertions(+), 3 deletions(-) diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt index d86861018c77d..3334efd268bc3 100644 --- a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt +++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt @@ -70,6 +70,11 @@ internal class ReviewDiffCanvasDrawing(context: Context) { ) } + fun fileHeaderCheckboxHitRect(top: Int, bottom: Int, width: Int, style: DiffStyle): RectF { + val checkbox = fileHeaderCheckboxRect(top, bottom, width, style) + return RectF(checkbox.left - 14f * density, top.toFloat(), width.toFloat(), bottom.toFloat()) + } + fun drawDisclosureChevron( canvas: Canvas, rect: RectF, diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt index e2d5a12d76304..2888917a89044 100644 --- a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt +++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt @@ -766,7 +766,7 @@ private class DiffCanvasView(context: Context) : View(context) { rowHitAt(event.y)?.let { hit -> val target = if ( hit.row.kind == "file" && - drawing.fileHeaderCheckboxRect( + drawing.fileHeaderCheckboxHitRect( hit.top, hit.bottom, width, diff --git a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift index 0c65ddf19460a..07d9a58a3553c 100644 --- a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift +++ b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift @@ -1029,6 +1029,7 @@ private struct ReviewDiffFileHeaderInteractiveRects { let chevron: CGRect let icon: CGRect let checkbox: CGRect + let checkboxHitTarget: CGRect } private struct ReviewDiffStickyFileHeaderIndex { @@ -1643,7 +1644,7 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { let interactiveRects = fileHeaderInteractiveRects(for: row, cardRect: rect) let fileId = resolvedFileId(for: row) - if interactiveRects.checkbox.contains(point) { + if interactiveRects.checkboxHitTarget.contains(point) { onToggleViewedFile?(fileId) return } @@ -2349,10 +2350,17 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { let chevronRect = CGRect(x: cardRect.minX + horizontalPadding, y: centerY - 10, width: 20, height: 20) let iconRect = CGRect(x: chevronRect.maxX + 8, y: centerY - 10, width: 20, height: 20) let checkboxRect = CGRect(x: cardRect.maxX - horizontalPadding - 20, y: centerY - 10, width: 20, height: 20) + let checkboxHitMinX = checkboxRect.minX - 14 return ReviewDiffFileHeaderInteractiveRects( chevron: chevronRect, icon: iconRect, - checkbox: checkboxRect + checkbox: checkboxRect, + checkboxHitTarget: CGRect( + x: checkboxHitMinX, + y: cardRect.minY, + width: cardRect.maxX - checkboxHitMinX, + height: cardRect.height + ) ) } diff --git a/apps/mobile/modules/t3-review-diff/tests/android/src/test/kotlin/expo/modules/t3reviewdiff/ReviewDiffGeometryTest.kt b/apps/mobile/modules/t3-review-diff/tests/android/src/test/kotlin/expo/modules/t3reviewdiff/ReviewDiffGeometryTest.kt index f2992979bf522..63e1acece9074 100644 --- a/apps/mobile/modules/t3-review-diff/tests/android/src/test/kotlin/expo/modules/t3reviewdiff/ReviewDiffGeometryTest.kt +++ b/apps/mobile/modules/t3-review-diff/tests/android/src/test/kotlin/expo/modules/t3reviewdiff/ReviewDiffGeometryTest.kt @@ -149,6 +149,18 @@ class ReviewDiffGeometryTest { } } + @Test + fun viewedCheckboxHitTargetSpansTheHeaderHeightAndTrailingEdge() { + val drawing = ReviewDiffCanvasDrawing(RuntimeEnvironment.getApplication()) + val style = DiffStyle.defaults(1f) + val glyph = drawing.fileHeaderCheckboxRect(100, 144, 320, style) + val hit = drawing.fileHeaderCheckboxHitRect(100, 144, 320, style) + assertTrue(hit.contains(glyph)) + assertTrue(hit.contains(glyph.left - 13f, 101f)) + assertTrue(hit.contains(319f, 143f)) + assertTrue(!hit.contains(glyph.left - 15f, 122f)) + } + @Test fun asciiWidthCacheDoesNotRetainPerRowMeasurementObjects() { val drawing = ReviewDiffCanvasDrawing(RuntimeEnvironment.getApplication()) From 05c100fbd893afbc127d29d9ac340d5e1e6412ef Mon Sep 17 00:00:00 2001 From: Victor Date: Sun, 22 Nov 2026 18:38:58 -0600 Subject: [PATCH 230/324] fix(server): skip queued checkpoint restores after thread deletion (#41113) Co-authored-by: Julius Marminge --- .../CheckpointRestoreSafety.test.ts | 1 + .../CheckpointRollbackService.test.ts | 24 +++++++++++++++++++ .../CheckpointRollbackService.ts | 1 + .../src/orchestration-v2/Orchestrator.ts | 7 ++++++ .../src/orchestration-v2/runtimeLayer.test.ts | 21 ++++++++++++++++ 5 files changed, 54 insertions(+) diff --git a/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts b/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts index 69f7661b8931c..95dca7c2b1a15 100644 --- a/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts @@ -80,6 +80,7 @@ it.effect.each([ worktreePath: cwd, activeProviderThreadId: providerThreadId, modelSelection: { instanceId, model: "test" }, + deletedAt: null, }, providerThread, providerSession: undefined, diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts index ff368dccb64d9..fd5d9c34b5bcd 100644 --- a/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts @@ -82,6 +82,7 @@ it.effect.each(["initial", "waiting"])( worktreePath: process.cwd(), activeProviderThreadId: providerThreadId, modelSelection: { instanceId: providerInstanceId, model: "test-model" }, + deletedAt: null, }, providerThread: { id: providerThreadId, providerSessionId, providerInstanceId }, checkpoint: { @@ -217,6 +218,7 @@ it.effect.each([ branch, activeProviderThreadId: providerThreadId, modelSelection: { instanceId: providerInstanceId, model: "test-model" }, + deletedAt: null, }, providerThread, providerSession: undefined, @@ -436,6 +438,7 @@ it.effect.each([ branch: "feature/rollback-reservation", activeProviderThreadId: providerThreadId, modelSelection: { instanceId: providerInstanceId, model: "test-model" }, + deletedAt: null, }, providerThread: { id: providerThreadId, @@ -997,5 +1000,26 @@ it.layer(ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMe ); }), ); + + it.effect("skips a pending rollback once the thread is deleted", () => + Effect.gen(function* () { + const history = yield* seedRollbackHistory; + const thread = yield* history.store.getThread(history.threadId); + yield* history.store.apply({ + id: EventId.make("rollback-history-deleted"), + type: "thread.deleted", + threadId: history.threadId, + providerInstanceId: thread.providerInstanceId, + occurredAt: history.now, + payload: { ...thread, deletedAt: history.now, updatedAt: history.now }, + }); + + yield* history.rollback(2); + + assert.deepEqual(history.rollbackCounts, []); + assert.deepEqual(history.restored, []); + assert.deepEqual(history.committed, []); + }), + ); }, ); diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts index 8d6fd1c09441d..e85175ef2ee33 100644 --- a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts +++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts @@ -156,6 +156,7 @@ export const layer: Layer.Layer< readonly requestId?: CommandId; }) { const context = yield* projections.getCheckpointRollbackContext(input.threadId, input); + if (context.thread.deletedAt !== null) return; const { providerThread, checkpoint, scope, targetAttempt, runsToRollback, staleCheckpoints } = context; const restoreFiles = input.restoreFiles !== false; diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 6920d26d3502f..13fc22a0a051c 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -14572,6 +14572,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ["providerThreads", "checkpoints", "checkpointScopes", "runs", "providerTurns", "attempts"], { turnItemTypes: [], messageRoles: ["user"] }, ); + if (projection.thread.deletedAt !== null) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Thread ${command.threadId} is deleted.`, + }); + } const providerThread = projection.providerThreads.find( (candidate) => candidate.id === projection.thread.activeProviderThreadId, ); diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 11525ba32170f..3d640f61fc398 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -1865,6 +1865,27 @@ it.layer(layerTest)("OrchestrationV2LayerLive", (it) => { conversationOnly.storedEvents.map((stored) => stored.event.type), ["thread.metadata-updated", "checkpoint.rollback-requested"], ); + yield* orchestrator.dispatch({ + type: "thread.delete", + commandId: CommandId.make("runtime-rollback-delete"), + threadId, + }); + const deletedCommandId = CommandId.make("runtime-rollback-deleted"); + const deletedSequence = yield* orchestrator.getThreadEventSequence(threadId); + const deleted = yield* orchestrator + .dispatch({ + type: "checkpoint.rollback", + commandId: deletedCommandId, + threadId, + checkpointId, + scopeId: scope.id, + restoreFiles: false, + }) + .pipe(Effect.flip); + assert.instanceOf(deleted, Orchestrator.OrchestratorDispatchError); + assert.equal(deleted.cause, `Thread ${threadId} is deleted.`); + assert.equal(yield* orchestrator.getThreadEventSequence(threadId), deletedSequence); + assert.deepEqual(yield* outbox.listByCommandId(deletedCommandId), []); } else { const error = yield* rollback.pipe(Effect.flip); assert.instanceOf(error, Orchestrator.OrchestratorDispatchError); From 65b2e6dae66f15caa03abf57ba2fe67da1d769aa Mon Sep 17 00:00:00 2001 From: SSH Date: Sun, 22 Nov 2026 19:39:44 -0500 Subject: [PATCH 231/324] fix(web): stop telemetry refresh spinning after data arrives (#41122) Co-authored-by: Julius Marminge --- .../resourceTelemetryState.browser.test.tsx | 45 +++++++++++++++++++ apps/web/src/lib/resourceTelemetryState.ts | 4 +- 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/apps/web/src/lib/resourceTelemetryState.browser.test.tsx b/apps/web/src/lib/resourceTelemetryState.browser.test.tsx index 981beeafdfd38..f93c53aff89fd 100644 --- a/apps/web/src/lib/resourceTelemetryState.browser.test.tsx +++ b/apps/web/src/lib/resourceTelemetryState.browser.test.tsx @@ -173,6 +173,7 @@ function setup({ retryFails = false, holdRetry = false } = {}) { const registry = AtomRegistry.make(); return { registry, + snapshot, historyQueries, historyReads, releaseRetry, @@ -265,4 +266,48 @@ describe("resource monitor retry", () => { await expect.element(screen.getByText(startError, { exact: true })).toBeVisible(); await expect.element(screen.getByText(historyError, { exact: true })).toBeVisible(); }); + + it("stops showing refresh as pending after the first live snapshot arrives", async () => { + using fixture = setup(); + const liveTelemetry = Atom.make< + AsyncResult.AsyncResult + >(AsyncResult.initial(true)).pipe(Atom.keepAlive); + monitor.telemetry.mockImplementation(() => liveTelemetry); + + await using screen = await render( + + + , + ); + const refreshButton = screen.getByRole("button", { name: "Refresh resource telemetry" }); + await expect.element(refreshButton).toBeDisabled(); + + await act(() => { + fixture.registry.set( + liveTelemetry, + AsyncResult.waiting(AsyncResult.success(fixture.snapshot)), + ); + }); + await expect.element(refreshButton).toBeEnabled(); + }); + + it("stops showing refresh as pending after a live subscription error", async () => { + using fixture = setup(); + const liveTelemetry = Atom.make< + AsyncResult.AsyncResult + >(AsyncResult.waiting(AsyncResult.fail(new MonitorError({ message: startError })))).pipe( + Atom.keepAlive, + ); + monitor.telemetry.mockImplementation(() => liveTelemetry); + + await using screen = await render( + + + , + ); + await expect.element(screen.getByText(startError, { exact: true })).toBeVisible(); + await expect + .element(screen.getByRole("button", { name: "Refresh resource telemetry" })) + .toBeEnabled(); + }); }); diff --git a/apps/web/src/lib/resourceTelemetryState.ts b/apps/web/src/lib/resourceTelemetryState.ts index 5105195d41e28..1fe63398c95b7 100644 --- a/apps/web/src/lib/resourceTelemetryState.ts +++ b/apps/web/src/lib/resourceTelemetryState.ts @@ -60,7 +60,9 @@ export function useResourceTelemetry( return result.value.snapshot; }; - return { ...query, retry }; + // The live subscription keeps waiting for updates after its first snapshot. + const isPending = query.isPending && query.data === null && query.error === null; + return { ...query, isPending, retry }; } export function useResourceTelemetryHistory( From def64e3a54be24a9840edb229619d401568b3b82 Mon Sep 17 00:00:00 2001 From: Mike Ozornin Date: Mon, 23 Nov 2026 04:01:30 +0300 Subject: [PATCH 232/324] fix(web): clicking the selected file in a Files folder view opens it (#41117) Co-authored-by: Julius Marminge --- .../files/FileBrowserPanel.browser.test.tsx | 4 +++ .../src/components/files/FileBrowserPanel.tsx | 26 +++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/apps/web/src/components/files/FileBrowserPanel.browser.test.tsx b/apps/web/src/components/files/FileBrowserPanel.browser.test.tsx index 8d069fc766d38..1924cbb941cf9 100644 --- a/apps/web/src/components/files/FileBrowserPanel.browser.test.tsx +++ b/apps/web/src/components/files/FileBrowserPanel.browser.test.tsx @@ -162,6 +162,10 @@ describe("FileBrowserPanel", () => { row.click(); await vi.waitFor(() => expect(onOpenFile).toHaveBeenCalledTimes(1)); + + // The selection stays put, so reopening the selected file must not depend on a selection change. + row.click(); + await vi.waitFor(() => expect(onOpenFile).toHaveBeenCalledTimes(2)); }); it("keeps an expanded folder open when a very large listing rebuilds the tree", async () => { diff --git a/apps/web/src/components/files/FileBrowserPanel.tsx b/apps/web/src/components/files/FileBrowserPanel.tsx index cd44d99220939..8f0bf626ba034 100644 --- a/apps/web/src/components/files/FileBrowserPanel.tsx +++ b/apps/web/src/components/files/FileBrowserPanel.tsx @@ -649,6 +649,32 @@ export default function FileBrowserPanel({ model={model} aria-label={gt("{projectName} files", { projectName })} className="min-h-0 flex-1 overflow-hidden" + onClickCapture={(event) => { + if ( + event.defaultPrevented || + event.button !== 0 || + event.ctrlKey || + event.metaKey || + event.shiftKey || + event.altKey || + dragMention.isDragInProgress() + ) { + return; + } + // Pierre emits no change for its sole selected row; read before the click to avoid double opens. + const selected = model.getSelectedPaths(); + const path = selected.length === 1 ? selected[0] : undefined; + if (!path || entryKindsRef.current.get(path) !== "file") return; + const clickedSelectedRow = event.nativeEvent + .composedPath() + .some( + (node) => + node instanceof HTMLElement && node.getAttribute("data-item-path") === path, + ); + if (!clickedSelectedRow) return; + treeSelectionPathRef.current = path; + onOpenFile(panelPath(path)); + }} style={pierreTreeStyle(resolvedTheme)} onPointerOver={titleClippedPierreTreeRow} /> From 6b38ec931aab43077760012d0502514e67f7b7ee Mon Sep 17 00:00:00 2001 From: Tyler Bruno Date: Sun, 22 Nov 2026 20:12:29 -0500 Subject: [PATCH 233/324] fix(desktop): remote servers behind origin-checking proxies no longer reject Desktop with 403 (#41092) Co-authored-by: Amp Co-authored-by: Julius Marminge --- apps/desktop/src/electron/ElectronProtocol.ts | 2 +- apps/desktop/src/window/DesktopWindow.test.ts | 6 + apps/desktop/src/window/DesktopWindow.ts | 22 ++- .../src/window/RemoteRequestHeaders.test.ts | 186 ++++++++++++++++++ .../src/window/RemoteRequestHeaders.ts | 129 ++++++++++++ apps/server/src/http.test.ts | 60 ++++++ apps/server/src/http.ts | 55 ++++-- 7 files changed, 446 insertions(+), 14 deletions(-) create mode 100644 apps/desktop/src/window/RemoteRequestHeaders.test.ts create mode 100644 apps/desktop/src/window/RemoteRequestHeaders.ts diff --git a/apps/desktop/src/electron/ElectronProtocol.ts b/apps/desktop/src/electron/ElectronProtocol.ts index 7563898f43efc..43208638f12d8 100644 --- a/apps/desktop/src/electron/ElectronProtocol.ts +++ b/apps/desktop/src/electron/ElectronProtocol.ts @@ -20,7 +20,7 @@ export function getDesktopScheme(isDevelopment: boolean): string { return isDevelopment ? DESKTOP_DEVELOPMENT_SCHEME : DESKTOP_PRODUCTION_SCHEME; } -function getDesktopOrigin(isDevelopment: boolean): string { +export function getDesktopOrigin(isDevelopment: boolean): string { return `${getDesktopScheme(isDevelopment)}://${DESKTOP_HOST}`; } diff --git a/apps/desktop/src/window/DesktopWindow.test.ts b/apps/desktop/src/window/DesktopWindow.test.ts index f2b655b1b69d8..e4e426b1975ae 100644 --- a/apps/desktop/src/window/DesktopWindow.test.ts +++ b/apps/desktop/src/window/DesktopWindow.test.ts @@ -74,6 +74,12 @@ function makeFakeBrowserWindow() { const webContentsListeners = new Map void>(); let zoomLevel = 0; const webContents = { + id: 1, + session: { + webRequest: { + onBeforeSendHeaders: vi.fn(), + }, + }, copyImageAt: vi.fn(), focus: vi.fn(), isDestroyed: vi.fn(() => false), diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts index 880b9dfef4ab9..c99fbb52c49e2 100644 --- a/apps/desktop/src/window/DesktopWindow.ts +++ b/apps/desktop/src/window/DesktopWindow.ts @@ -14,12 +14,13 @@ import { msg } from "gt-i18n"; import { type DesktopSnapShotEvent, DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts"; import * as DesktopAssets from "../app/DesktopAssets.ts"; +import * as DesktopClerk from "../app/DesktopClerk.ts"; import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; import * as DesktopPrimaryPaste from "../app/DesktopPrimaryPaste.ts"; import { makeComponentLogger } from "../app/DesktopObservability.ts"; import * as DesktopState from "../app/DesktopState.ts"; import * as ElectronMenu from "../electron/ElectronMenu.ts"; -import { getDesktopUrl } from "../electron/ElectronProtocol.ts"; +import { getDesktopOrigin, getDesktopUrl } from "../electron/ElectronProtocol.ts"; import * as ElectronShell from "../electron/ElectronShell.ts"; import * as ElectronTheme from "../electron/ElectronTheme.ts"; import * as ElectronWindow from "../electron/ElectronWindow.ts"; @@ -44,6 +45,7 @@ import { m } from "../i18n/messages.ts"; import * as DesktopRendererHistory from "../telemetry/DesktopRendererHistory.ts"; import { makeQuitShortcutHandler } from "./QuitHold.ts"; import { copyContextMenuImage } from "./ContextMenuImage.ts"; +import { installMainWindowRemoteRequestHeaderPolicy } from "./RemoteRequestHeaders.ts"; const TITLEBAR_HEIGHT = 40; @@ -408,6 +410,7 @@ export const make = Effect.gen(function* () { Effect.suspend(() => pendingMainReveals.get(window) ?? electronWindow.reveal(window)), ); let flushMainWindowBounds: Effect.Effect = Effect.void; + let remoteRequestHeaderOwner: Electron.BrowserWindow | null = null; const dismissConnectingSplash = Effect.gen(function* () { const splash = yield* Ref.getAndSet(splashWindowRef, Option.none()); @@ -1036,6 +1039,19 @@ export const make = Effect.gen(function* () { // Desktop IPC only answers the main window, so register it before its renderer can call in. yield* electronWindow.setMain(window); + remoteRequestHeaderOwner = window; + const detachRemoteRequestHeaders = installMainWindowRemoteRequestHeaderPolicy( + window.webContents.session, + { + desktopOrigin: getDesktopOrigin(environment.isDevelopment), + mainWebContentsId: window.webContents.id, + clerkFrontendApiHostname: DesktopClerk.desktopClerkFrontendApiHostname, + devServerOrigin: Option.getOrUndefined( + Option.map(environment.devServerUrl, (url) => url.origin), + ), + isDevelopment: environment.isDevelopment, + }, + ); loadApplication(); if (environment.isDevelopment) { window.webContents.openDevTools({ mode: "detach" }); @@ -1045,6 +1061,10 @@ export const make = Effect.gen(function* () { if (!backendHasStarted) mainClosedDuringStartup = true; clearDevelopmentLoadRetry(); clearBoundsPersist(); + if (remoteRequestHeaderOwner === window) { + remoteRequestHeaderOwner = null; + detachRemoteRequestHeaders(); + } void runPromise(electronWindow.clearMain(Option.some(window))); }); diff --git a/apps/desktop/src/window/RemoteRequestHeaders.test.ts b/apps/desktop/src/window/RemoteRequestHeaders.test.ts new file mode 100644 index 0000000000000..fee9aedb16c63 --- /dev/null +++ b/apps/desktop/src/window/RemoteRequestHeaders.test.ts @@ -0,0 +1,186 @@ +import { assert, describe, it } from "@effect/vitest"; + +import { + stripDesktopOriginHeaders, + type MainWindowRequestHeaderPolicy, +} from "./RemoteRequestHeaders.ts"; + +const packagedPolicy: MainWindowRequestHeaderPolicy = { + desktopOrigin: "t3code://app", + mainWebContentsId: 42, + clerkFrontendApiHostname: "clerk.t3.codes", + isDevelopment: false, +}; + +const devPolicy: MainWindowRequestHeaderPolicy = { + desktopOrigin: "t3code-dev://app", + mainWebContentsId: 42, + clerkFrontendApiHostname: "clerk.t3.codes", + devServerOrigin: "http://devbox.internal:5733", + isDevelopment: true, +}; + +describe("RemoteRequestHeaders", () => { + it.each([ + "https://remote.example.com/.well-known/t3/environment", + "http://127.0.0.1:8080/api/auth/bootstrap", + "ws://127.0.0.1:8080/ws?ticket=abc", + "wss://remote.example.com/ws?ticket=abc", + ])("strips Origin and Sec-Fetch-* on outbound main-window %s requests", (url) => { + const headers = stripDesktopOriginHeaders(packagedPolicy, { + url, + webContentsId: 42, + frame: { parent: null }, + requestHeaders: { + Origin: "t3code://app", + "Sec-Fetch-Site": "cross-site", + "Sec-Fetch-Mode": "cors", + "Sec-Fetch-Dest": "empty", + "sec-fetch-user": "?1", + Authorization: "Bearer secret", + DPoP: "proof-jwt", + }, + }); + + assert.deepEqual(headers, { + Authorization: "Bearer secret", + DPoP: "proof-jwt", + }); + }); + + it("strips lowercase origin headers and allows null frames (WebSocket upgrades and workers)", () => { + const headers = stripDesktopOriginHeaders(packagedPolicy, { + url: "wss://remote.example.com/ws", + webContentsId: 42, + frame: null, + requestHeaders: { + origin: "t3code://app", + "Sec-Fetch-Site": "cross-site", + Upgrade: "websocket", + }, + }); + + assert.deepEqual(headers, { + Upgrade: "websocket", + }); + }); + + it("preserves headers for Clerk frontend API requests", () => { + for (const url of ["https://clerk.t3.codes/v1/client", "https://CLERK.T3.CODES./v1/client"]) { + const headers = stripDesktopOriginHeaders(packagedPolicy, { + url, + webContentsId: 42, + frame: { parent: null }, + requestHeaders: { + Origin: "t3code://app", + "Sec-Fetch-Site": "cross-site", + }, + }); + assert.isUndefined(headers); + } + }); + + it("preserves headers for dev loopback and exact devServerOrigin, while stripping other ports and remote hosts", () => { + for (const url of [ + "http://localhost:3773/api/health", + "http://app.localhost:3773/api/health", + "http://127.0.0.1:3773/api/health", + "http://[::1]:3773/api/health", + "ws://127.0.0.1:3773/ws", + "http://devbox.internal:5733/api/health", + "ws://devbox.internal:5733/ws", + ]) { + assert.isUndefined( + stripDesktopOriginHeaders(devPolicy, { + url, + webContentsId: 42, + frame: { parent: null }, + requestHeaders: { + Origin: "t3code-dev://app", + "Sec-Fetch-Site": "cross-site", + }, + }), + ); + } + + for (const url of [ + "http://devbox.internal:8080/api/auth/bootstrap", + "https://remote.example.com/api/auth/bootstrap", + ]) { + assert.deepEqual( + stripDesktopOriginHeaders(devPolicy, { + url, + webContentsId: 42, + frame: { parent: null }, + requestHeaders: { + Origin: "t3code-dev://app", + "Sec-Fetch-Site": "cross-site", + "Content-Type": "application/json", + }, + }), + { "Content-Type": "application/json" }, + ); + } + }); + + it("never touches sandboxed iframes (Origin: null), subframes, or other webContents", () => { + assert.isUndefined( + stripDesktopOriginHeaders(packagedPolicy, { + url: "https://remote.example.com/api/test", + webContentsId: 42, + frame: { parent: null }, + requestHeaders: { + Origin: "null", + "Sec-Fetch-Site": "cross-site", + }, + }), + ); + + assert.isUndefined( + stripDesktopOriginHeaders(packagedPolicy, { + url: "https://remote.example.com/api/test", + webContentsId: 42, + frame: { parent: {} }, + requestHeaders: { + Origin: "t3code://app", + "Sec-Fetch-Site": "cross-site", + }, + }), + ); + + assert.isUndefined( + stripDesktopOriginHeaders(packagedPolicy, { + url: "https://remote.example.com/api/test", + webContentsId: 99, + frame: { parent: null }, + requestHeaders: { + Origin: "t3code://app", + "Sec-Fetch-Site": "cross-site", + }, + }), + ); + + assert.isUndefined( + stripDesktopOriginHeaders(packagedPolicy, { + url: "https://remote.example.com/api/test", + webContentsId: undefined, + frame: null, + requestHeaders: { + Origin: "t3code://app", + "Sec-Fetch-Site": "cross-site", + }, + }), + ); + + assert.isUndefined( + stripDesktopOriginHeaders(packagedPolicy, { + url: "https://remote.example.com/api/test", + webContentsId: 42, + frame: { parent: null }, + requestHeaders: { + "Sec-Fetch-Site": "cross-site", + }, + }), + ); + }); +}); diff --git a/apps/desktop/src/window/RemoteRequestHeaders.ts b/apps/desktop/src/window/RemoteRequestHeaders.ts new file mode 100644 index 0000000000000..61df4c3535160 --- /dev/null +++ b/apps/desktop/src/window/RemoteRequestHeaders.ts @@ -0,0 +1,129 @@ +import * as NetAddress from "effect/net/NetAddress"; +import * as Result from "effect/Result"; +import type * as Electron from "electron"; + +// `*://` matches only http and https, so WebSocket schemes are listed separately. +const REMOTE_REQUEST_URL_PATTERNS = ["http://*/*", "https://*/*", "ws://*/*", "wss://*/*"]; + +export interface MainWindowRequestHeaderPolicy { + readonly desktopOrigin: string; + readonly mainWebContentsId: number; + readonly clerkFrontendApiHostname?: string | undefined; + readonly devServerOrigin?: string | undefined; + readonly isDevelopment: boolean; +} + +export interface MainWindowRequestHeaderDetails { + readonly url: string; + readonly webContentsId?: number | undefined; + readonly frame?: { readonly parent: unknown } | null | undefined; + readonly requestHeaders: Record; +} + +function normalizeHostname(hostname: string): string { + return hostname + .toLowerCase() + .replace(/^\[(.*)\]$/, "$1") + .replace(/\.$/, ""); +} + +function isLoopbackHostname(hostname: string): boolean { + return ( + hostname === "localhost" || + hostname.endsWith(".localhost") || + Result.match(NetAddress.ipFromString(hostname), { + onSuccess: NetAddress.isLoopback, + onFailure: () => false, + }) + ); +} + +function toHttpOrigin(url: URL): string { + if (url.protocol === "ws:") { + return `http://${url.host}`; + } + if (url.protocol === "wss:") { + return `https://${url.host}`; + } + return url.origin; +} + +function isSubframe(details: MainWindowRequestHeaderDetails): boolean { + try { + return details.frame != null && details.frame.parent !== null; + } catch { + return true; + } +} + +function hasExactDesktopOriginHeader( + requestHeaders: Record, + desktopOrigin: string, +): boolean { + let matched = false; + for (const [name, value] of Object.entries(requestHeaders)) { + if (name.toLowerCase() !== "origin") continue; + if (value !== desktopOrigin) return false; + matched = true; + } + return matched; +} + +function shouldPreserveOriginHeader(policy: MainWindowRequestHeaderPolicy, url: URL): boolean { + const hostname = normalizeHostname(url.hostname); + if ( + policy.clerkFrontendApiHostname !== undefined && + hostname === normalizeHostname(policy.clerkFrontendApiHostname) + ) { + return true; + } + if (!policy.isDevelopment) return false; + if (policy.devServerOrigin !== undefined && toHttpOrigin(url) === policy.devServerOrigin) { + return true; + } + return isLoopbackHostname(hostname); +} + +/** + * Strips Electron's synthetic `Origin` (`t3code://app`) and `Sec-Fetch-*` headers on outbound + * main-window requests so origin-checking reverse proxies treat Desktop like native T3 clients. + */ +export function stripDesktopOriginHeaders( + policy: MainWindowRequestHeaderPolicy, + details: MainWindowRequestHeaderDetails, +): Record | undefined { + if (details.webContentsId !== policy.mainWebContentsId) return undefined; + if (isSubframe(details)) return undefined; + if (!hasExactDesktopOriginHeader(details.requestHeaders, policy.desktopOrigin)) { + return undefined; + } + + const parsedUrl = URL.parse(details.url); + if (parsedUrl === null || shouldPreserveOriginHeader(policy, parsedUrl)) { + return undefined; + } + + const nextHeaders: Record = {}; + for (const [name, value] of Object.entries(details.requestHeaders)) { + const lowerName = name.toLowerCase(); + if (lowerName === "origin" || lowerName.startsWith("sec-fetch-")) continue; + nextHeaders[name] = value; + } + return nextHeaders; +} + +export function installMainWindowRemoteRequestHeaderPolicy( + session: Pick, + policy: MainWindowRequestHeaderPolicy, +): () => void { + session.webRequest.onBeforeSendHeaders( + { urls: REMOTE_REQUEST_URL_PATTERNS }, + (details, callback) => { + const requestHeaders = stripDesktopOriginHeaders(policy, details); + callback(requestHeaders === undefined ? {} : { requestHeaders }); + }, + ); + return () => { + session.webRequest.onBeforeSendHeaders(null); + }; +} diff --git a/apps/server/src/http.test.ts b/apps/server/src/http.test.ts index d0f5b39800319..6e011aef39d26 100644 --- a/apps/server/src/http.test.ts +++ b/apps/server/src/http.test.ts @@ -172,6 +172,66 @@ describe("browser API CORS", () => { await dispose(); } }); + + it("allows originless desktop requests in dev mode while still rejecting disallowed browser origins", async () => { + const layerRoute = Layer.effectDiscard( + Effect.gen(function* () { + const router = yield* HttpRouter.HttpRouter; + yield* router.add( + "GET", + "/api/environment", + HttpServerResponse.empty({ headers: { vary: "Accept-Encoding" } }), + ); + }), + ); + const layerDevConfig = Layer.effect( + ServerConfig.ServerConfig, + Effect.map(ServerConfig.ServerConfig, (config) => ({ + ...config, + devUrl: new URL("http://127.0.0.1:5733"), + })), + ).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "http-dev-cors-test-" }))); + const layerApp = Layer.merge(layerRoute, ServerHttp.layerBrowserApiCors).pipe( + Layer.provide(layerDevConfig), + Layer.provide(NodeServices.layer), + ); + const { handler, dispose } = HttpRouter.toWebHandler(layerApp, { disableLogger: true }); + + try { + const originless = await handler( + new Request("https://dev.example/api/environment", { method: "GET" }), + ); + expect(originless.headers.get("access-control-allow-origin")).toBe("*"); + expect(originless.headers.get("access-control-allow-credentials")).toBeNull(); + expect(originless.headers.get("vary")).toBe("Accept-Encoding, Origin"); + + const originlessPreflight = await handler( + new Request("https://dev.example/api/environment", { method: "OPTIONS" }), + ); + expect(originlessPreflight.status).toBe(204); + expect(originlessPreflight.headers.get("access-control-allow-origin")).toBe("*"); + expect(originlessPreflight.headers.get("vary")).toBe("Origin"); + + const allowed = await handler( + new Request("https://dev.example/api/environment", { + method: "GET", + headers: { origin: "http://127.0.0.1:5733" }, + }), + ); + expect(allowed.headers.get("access-control-allow-origin")).toBe("http://127.0.0.1:5733"); + expect(allowed.headers.get("access-control-allow-credentials")).toBe("true"); + + const disallowed = await handler( + new Request("https://dev.example/api/environment", { + method: "GET", + headers: { origin: "https://evil.example" }, + }), + ); + expect(disallowed.headers.get("access-control-allow-origin")).toBeNull(); + } finally { + await dispose(); + } + }); }); describe("untraced requests", () => { diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts index 47215bef97f7d..acec877a45c55 100644 --- a/apps/server/src/http.ts +++ b/apps/server/src/http.ts @@ -22,6 +22,7 @@ import { cast, pipe } from "effect/Function"; import { HttpClient, HttpClientResponse, + HttpEffect, HttpMiddleware, HttpRouter, HttpServerResponse, @@ -274,28 +275,58 @@ export const layerHttpCompression = HttpRouter.middleware(HttpMiddleware.compres global: true, }); +function withVaryOrigin( + response: HttpServerResponse.HttpServerResponse, +): HttpServerResponse.HttpServerResponse { + const existing = response.headers.vary; + if ( + existing !== undefined && + existing.split(",").some((token) => token.trim().toLowerCase() === "origin") + ) { + return response; + } + return HttpServerResponse.setHeader( + response, + "vary", + existing ? `${existing}, Origin` : "Origin", + ); +} + export const layerBrowserApiCors = Layer.unwrap( Effect.gen(function* () { const config = yield* ServerConfig.ServerConfig; const devOrigin = config.devUrl?.origin; - // Credentialed dev requests need explicit Vite/Electron origins; packaged desktop uses the default wildcard. - const cors = HttpMiddleware.cors({ - ...(devOrigin - ? { - allowedOrigins: [devOrigin, ...DESKTOP_RENDERER_ORIGINS, ...config.devAllowedOrigins], - credentials: true, - } - : {}), + // Credentialed dev requests need explicit Vite/Electron origins; originless desktop/native + // requests and packaged servers use the non-credentialed wildcard. + const wildcardCors = HttpMiddleware.cors({ allowedMethods: browserApiCorsAllowedMethods, allowedHeaders: browserApiCorsAllowedHeaders, maxAge: 600, }); + const devCors = devOrigin + ? HttpMiddleware.cors({ + allowedOrigins: [devOrigin, ...DESKTOP_RENDERER_ORIGINS, ...config.devAllowedOrigins], + credentials: true, + allowedMethods: browserApiCorsAllowedMethods, + allowedHeaders: browserApiCorsAllowedHeaders, + maxAge: 600, + }) + : undefined; return HttpRouter.middleware( (httpEffect) => { - const withCors = cors(httpEffect); - return Effect.flatMap(HttpServerRequest.HttpServerRequest, (request) => - request.url.split("?", 1)[0] === MCP_HTTP_PATH ? httpEffect : withCors, - ); + const withWildcardCors = wildcardCors(httpEffect); + const withDevCors = devCors ? devCors(httpEffect) : undefined; + return Effect.flatMap(HttpServerRequest.HttpServerRequest, (request) => { + if (request.url.split("?", 1)[0] === MCP_HTTP_PATH) return httpEffect; + if (!withDevCors) return withWildcardCors; + if (request.headers.origin !== undefined) return withDevCors; + if (request.method === "OPTIONS") { + return Effect.map(withWildcardCors, withVaryOrigin); + } + return HttpEffect.appendPreResponseHandler((_request, response) => + Effect.succeed(withVaryOrigin(response)), + ).pipe(Effect.andThen(withWildcardCors)); + }); }, { global: true }, ); From 83119ae8bd0507138faa78be56299d073aab2daa Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 17:34:52 -0800 Subject: [PATCH 234/324] fix(server): stopping a delegated child with a queued message no longer ends its task (#41140) --- .../DelegatedChildTerminalRetry.test.ts | 256 ++++++++++++++++++ .../src/orchestration-v2/Orchestrator.ts | 29 +- .../src/server/subagentProjection.ts | 18 +- 3 files changed, 293 insertions(+), 10 deletions(-) diff --git a/apps/server/src/orchestration-v2/DelegatedChildTerminalRetry.test.ts b/apps/server/src/orchestration-v2/DelegatedChildTerminalRetry.test.ts index b9c20c02b5afe..7658acaa9f955 100644 --- a/apps/server/src/orchestration-v2/DelegatedChildTerminalRetry.test.ts +++ b/apps/server/src/orchestration-v2/DelegatedChildTerminalRetry.test.ts @@ -31,6 +31,7 @@ const driver = ProviderDriverKind.make("claudeAgent"); const instanceId = ProviderInstanceId.make("claudeAgent"); const modelSelection = { instanceId, model: "claude-test" }; const parentThreadId = ThreadId.make("thread:delegated-terminal-retry-parent"); +const stopRaceParentId = ThreadId.make("thread:delegated-stop-race-parent"); const childError = "Failed to initialize session: No space left on device"; type ParentRead = { @@ -326,3 +327,258 @@ it.effect("a delegated child reaches its parent after its own delivery read fail failChildRunMessage: true, }), ); + +it.effect("stopping a delegated child with a queued message does not report the task ended", () => + Effect.gen(function* () { + const cwd = yield* checkpointWorkspace("delegated-stop-race"); + const turns: Array<{ + readonly turn: ProviderAdapter.ProviderAdapterV2TurnInput; + readonly events: Queue.Queue; + }> = []; + const terminal = (entry: (typeof turns)[number], status: "completed" | "interrupted") => + Effect.gen(function* () { + const now = yield* DateTime.now; + const providerTurnId = ProviderTurnId.make(`provider-turn:${entry.turn.attemptId}`); + yield* Queue.offer(entry.events, { + type: "provider_turn.updated", + driver, + providerTurn: { + id: providerTurnId, + providerThreadId: entry.turn.providerThread.id, + nodeId: entry.turn.rootNodeId, + runAttemptId: entry.turn.attemptId, + nativeTurnRef: null, + ordinal: entry.turn.providerTurnOrdinal, + status, + startedAt: now, + completedAt: now, + }, + }); + yield* Queue.offer(entry.events, { + type: "turn.terminal", + driver, + providerThreadId: entry.turn.providerThread.id, + providerTurnId, + runOrdinal: entry.turn.runOrdinal, + status, + failure: null, + threadDisposition: "reusable", + }); + }); + const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = { + instanceId, + driver, + getCapabilities: () => Effect.succeed(ClaudeProviderCapabilitiesV2), + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }), + openSession: (session) => + Effect.gen(function* () { + const now = yield* DateTime.now; + const events = yield* Queue.unbounded(); + return { + instanceId, + driver, + providerSessionId: session.providerSessionId, + providerSession: { + id: session.providerSessionId, + driver, + providerInstanceId: instanceId, + status: "ready", + cwd, + model: modelSelection.model, + capabilities: ClaudeProviderCapabilitiesV2, + createdAt: now, + updatedAt: now, + lastError: null, + }, + events: Stream.fromQueue(events), + ensureThread: ({ threadId }) => + Effect.succeed({ + id: ProviderThreadId.make(`provider-thread:${threadId}`), + driver, + providerInstanceId: instanceId, + providerSessionId: session.providerSessionId, + appThreadId: threadId, + ownerNodeId: null, + nativeThreadRef: { driver, nativeId: `native:${threadId}`, strength: "strong" }, + nativeConversationHeadRef: null, + status: "idle", + firstRunOrdinal: null, + lastRunOrdinal: null, + handoffIds: [], + forkedFrom: null, + createdAt: now, + updatedAt: now, + }), + resumeThread: ({ providerThread }) => Effect.succeed(providerThread), + startTurn: (turn) => + Effect.gen(function* () { + turns.push({ turn, events }); + yield* Queue.offer(events, { + type: "provider_turn.updated", + driver, + providerTurn: { + id: ProviderTurnId.make(`provider-turn:${turn.attemptId}`), + providerThreadId: turn.providerThread.id, + nodeId: turn.rootNodeId, + runAttemptId: turn.attemptId, + nativeTurnRef: null, + ordinal: turn.providerTurnOrdinal, + status: "running", + startedAt: now, + completedAt: null, + }, + }); + }), + steerTurn: () => Effect.die("unused"), + interruptTurn: ({ providerTurnId }) => + Effect.gen(function* () { + const entry = turns.find( + (candidate) => + ProviderTurnId.make(`provider-turn:${candidate.turn.attemptId}`) === + providerTurnId, + ); + if (entry !== undefined) yield* terminal(entry, "interrupted"); + }), + respondToRuntimeRequest: () => Effect.die("unused"), + readThreadSnapshot: () => Effect.die("unused"), + rollbackThread: () => Effect.die("unused"), + forkThread: () => Effect.die("unused"), + }; + }), + }; + const layerTest = ProviderReplayHarness.layerWithRegistry( + { name: "delegated-stop-race" }, + ProviderAdapterRegistry.layerSingle(adapter), + { runEffectWorker: false, runContinuationWorker: true }, + ); + + return yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) => + orchestrator.streamDomainEvents.pipe( + Stream.filter(predicate), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + const settle = Effect.gen(function* () { + for (let attempt = 0; attempt < 5; attempt++) { + yield* worker.drain(); + yield* TestClock.adjust("1 second"); + } + }); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("create-parent"), + threadId: stopRaceParentId, + projectId: ProjectId.make("project:delegated-stop-race"), + title: "Parent", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: cwd, + createdBy: "user", + creationSource: "web", + }); + const parentRunning = yield* watch( + (event) => event.type === "provider-turn.updated" && event.payload.status === "running", + ); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("start-parent"), + threadId: stopRaceParentId, + messageId: MessageId.make("message:start-parent"), + text: "Delegate the work", + attachments: [], + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + }); + yield* worker.drain(); + yield* Fiber.join(parentRunning); + const parentRun = (yield* orchestrator.getThreadProjection(stopRaceParentId)).runs[0]!; + + yield* orchestrator.dispatch({ + type: "delegated_task.request", + commandId: CommandId.make("delegate"), + parentThreadId: stopRaceParentId, + parentRunId: parentRun.id, + parentNodeId: parentRun.rootNodeId!, + task: "Do the work", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + completionWake: "always", + createdBy: "agent", + creationSource: "mcp", + }); + const task = (yield* orchestrator.getThreadProjection(stopRaceParentId)).subagents[0]!; + const childThreadId = task.childThreadId!; + + // The parent's own turn ends, so a completion wake would start it again. + yield* terminal( + turns.find((entry) => entry.turn.threadId === stopRaceParentId)!, + "completed", + ); + yield* settle; + const childRun = (yield* orchestrator.getThreadProjection(childThreadId)).runs[0]!; + assert.equal(childRun.status, "running"); + + // The user types a message in the child pane, then presses Stop there. + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("child-follow-up"), + threadId: childThreadId, + messageId: MessageId.make("message:child-follow-up"), + text: "Actually, do it this way", + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "user", + creationSource: "web", + }); + yield* orchestrator.dispatch({ + type: "run.interrupt", + commandId: CommandId.make("child-stop"), + threadId: childThreadId, + runId: childRun.id, + holdQueue: true, + }); + yield* settle; + + const child = yield* orchestrator.getThreadProjection(childThreadId); + assert.deepEqual( + child.runs.map((run) => [run.ordinal, run.status, run.queueHeld ?? false]), + [ + [1, "interrupted", false], + [2, "queued", true], + ], + ); + const parent = yield* orchestrator.getThreadProjection(stopRaceParentId); + const wakes = parent.messages.filter( + (message) => message.delegatedCompletion?.taskIds.includes(task.id) === true, + ); + // The user's message still waits to run in the child's checkout, so the task has not ended. + assert.deepEqual( + wakes.map((message) => message.text), + [], + ); + assert.notInclude( + ["completed", "failed", "cancelled", "interrupted"], + parent.subagents.find((row) => row.id === task.id)?.status, + ); + + // Discarding the held message leaves the stopped run as the task's result. + yield* orchestrator.dispatch({ + type: "queued-run.cancel", + commandId: CommandId.make("child-discard"), + threadId: childThreadId, + runId: child.runs[1]!.id, + }); + yield* settle; + const settled = yield* orchestrator.getThreadProjection(stopRaceParentId); + assert.equal(settled.subagents.find((row) => row.id === task.id)?.status, "interrupted"); + }).pipe(Effect.provide(layerTest)); + }), +); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 13fc22a0a051c..5b1623f8414ec 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -15108,9 +15108,25 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const readDelegatedChildControls = Effect.fn("Orchestrator.readDelegatedChildControls")( function* (childThreadId: ThreadId, taskIds: ReadonlyArray) { - const controls: DelegatedChildControls = yield* projectionStore.getDelegatedChildControls( - childThreadId, - { taskIds, windowSize: DELEGATED_CHILD_RUN_WINDOW }, + // Progress tells a held wake from a held message the user wrote by the run's message. + const withHeldMessages = Effect.fn("Orchestrator.readHeldRunMessages")(function* < + A extends Omit, + >(read: A) { + const heldRunIds = read.runs.flatMap((run) => + run.status === "queued" && run.queueHeld === true ? [run.id] : [], + ); + if (heldRunIds.length === 0) return read; + const { messages } = yield* projectionStore.getThreadRecords(childThreadId, ["messages"], { + messageRoles: ["user"], + messageRunIds: heldRunIds, + }); + return { ...read, messages: [...read.messages, ...messages] }; + }); + const controls: DelegatedChildControls = yield* withHeldMessages( + yield* projectionStore.getDelegatedChildControls(childThreadId, { + taskIds, + windowSize: DELEGATED_CHILD_RUN_WINDOW, + }), ); const progress = delegatedTaskProgress(controls); // The latest result may have ended before the runs read above; then read them all. @@ -15118,7 +15134,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio controls.runsFloor !== undefined && (progress.resultRun === undefined || !ranSince(progress.resultRun, controls.runsFloor)) ) { - const all = yield* readAllDelegatedChildControls(childThreadId); + const all = yield* withHeldMessages(yield* readAllDelegatedChildControls(childThreadId)); return { controls: all, progress: delegatedTaskProgress(all) }; } return { controls, progress }; @@ -15500,12 +15516,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio childThreadId, openTasks.map((task) => task.id), ); + const cancelAwaitsWork = progress.state === "working" && !progress.onlyAwaitsUserRun; for (const task of openTasks) { // A cancelled task does not wait for the work its cancel is stopping. const cancelled = task.cancelledRunId !== undefined; if ( task.id === forkedFrom.nodeId && - (cancelled ? progress.state === "working" : progress.state !== "result_available") + (cancelled ? cancelAwaitsWork : progress.state !== "result_available") ) continue; yield* finalizeAppOwnedSubagentTask(childControls, { @@ -15524,7 +15541,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio resultTask?.cancelledRunId !== undefined && resultTask.cancelledRunId === resultRun?.id; if ( resultRun === undefined || - (taskCancelled ? progress.state === "working" : progress.state !== "result_available") + (taskCancelled ? cancelAwaitsWork : progress.state !== "result_available") ) return; const status = delegatedTaskTerminalStatus(runOutcome(resultRun)); diff --git a/packages/provider-core/src/server/subagentProjection.ts b/packages/provider-core/src/server/subagentProjection.ts index d1638b8022029..df5ea84c4b440 100644 --- a/packages/provider-core/src/server/subagentProjection.ts +++ b/packages/provider-core/src/server/subagentProjection.ts @@ -395,7 +395,7 @@ export function subagentHoldsCompletion( export function delegatedTaskProgress(projection: { readonly runs: OrchestrationV2ThreadProjection["runs"]; readonly messages: ReadonlyArray< - Pick + Pick >; readonly subagents: ReadonlyArray< Pick @@ -410,9 +410,17 @@ export function delegatedTaskProgress(projection: { const workRuns = projection.runs.filter( (run) => !monitorRuns.has(run.id) && run.status !== "rolled_back", ); - const active = workRuns.some( - (run) => !terminal(run.status) && !(run.status === "queued" && run.queueHeld === true), + const held = (run: OrchestrationV2Run) => run.status === "queued" && run.queueHeld === true; + const active = workRuns.some((run) => !terminal(run.status) && !held(run)); + // Held wakes wait on nobody, but a held message the user wrote is the child's next work. + const userRunIds = new Set( + projection.messages.flatMap((message) => + message.createdBy === "user" && message.notification === undefined && message.runId !== null + ? [message.runId] + : [], + ), ); + const awaitsUserRun = workRuns.some((run) => held(run) && userRunIds.has(run.id)); const children = projection.subagents.some(subagentHoldsCompletion) || projection.providerThreads.some((thread) => @@ -423,12 +431,14 @@ export function delegatedTaskProgress(projection: { .toSorted((a, b) => (runRanAfter(a, b) ? -1 : runRanAfter(b, a) ? 1 : 0))[0]; return { state: - active || resultRun === undefined + active || awaitsUserRun || resultRun === undefined ? ("working" as const) : children ? ("waiting_for_children" as const) : ("result_available" as const), resultRun, + /** Working only because of a held message the user wrote, which a cancel does not wait for. */ + onlyAwaitsUserRun: awaitsUserRun && !active && resultRun !== undefined, }; } From e414cfd4bee392e95609a4d31fcbbd3228949849 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 17:50:18 -0800 Subject: [PATCH 235/324] feat(server): durable workflows (#38882) Co-authored-by: Claude Fable 5.2 --- apps/server/src/auth/RpcAuthorization.ts | 4 + apps/server/src/binCli.ts | 2 + apps/server/src/cli/thread.ts | 20 +- apps/server/src/cli/workflow.test.ts | 186 ++ apps/server/src/cli/workflow.ts | 408 +++ apps/server/src/config.ts | 3 + apps/server/src/feedback/FeedbackReport.ts | 13 + apps/server/src/mcp/McpHttpServer.ts | 10 +- .../src/mcp/toolkits/project/handlers.ts | 4 + apps/server/src/mcp/toolkits/project/tools.ts | 3 + .../src/mcp/toolkits/workflow/handlers.ts | 98 + .../server/src/mcp/toolkits/workflow/tools.ts | 69 + .../src/milestones/MilestoneEvents.test.ts | 12 +- apps/server/src/milestones/MilestoneEvents.ts | 117 +- .../src/milestones/MilestoneHub.test.ts | 30 +- .../OrchestrationMilestones.test.ts | 43 + .../src/milestones/OrchestrationMilestones.ts | 1 + .../src/observability/RpcInstrumentation.ts | 9 + .../src/orchestration-v2/Orchestrator.ts | 2 + .../src/orchestration-v2/ProjectionStore.ts | 13 +- .../src/orchestration-v2/ThreadForkService.ts | 7 +- .../ThreadLaunchService.test.ts | 17 +- .../orchestration-v2/ThreadLaunchService.ts | 4 + .../ThreadManagementService.test.ts | 115 + .../ThreadManagementService.ts | 47 +- apps/server/src/orchestration-v2/runOutput.ts | 6 + .../src/orchestration-v2/runtimeLayer.test.ts | 146 +- .../src/orchestration-v2/runtimeLayer.ts | 16 + .../testkit/ProviderReplayHarness.ts | 1 + apps/server/src/persistence/Migrations.ts | 2 + .../persistence/Migrations/110_Workflows.ts | 149 + .../reconcileV2PreviewMigration.test.ts | 2 + .../src/provider/AgentContextBudget.test.ts | 2 + .../src/provider/agentContextBudget.json | 2 +- apps/server/src/scheduledTasks/Schedule.ts | 2 +- .../src/scheduledTasks/webhookRoute.test.ts | 36 + .../server/src/scheduledTasks/webhookRoute.ts | 38 + apps/server/src/server.ts | 12 +- .../src/workflows/WorkflowAgentLinks.test.ts | 292 ++ .../src/workflows/WorkflowAgentLinks.ts | 313 +++ .../src/workflows/WorkflowAgentThreads.ts | 335 +++ apps/server/src/workflows/WorkflowAgents.ts | 117 + apps/server/src/workflows/WorkflowEngine.ts | 1056 +++++++ .../src/workflows/WorkflowForge.test.ts | 113 + apps/server/src/workflows/WorkflowForge.ts | 455 ++++ .../src/workflows/WorkflowRuntime.test.ts | 464 ++++ apps/server/src/workflows/WorkflowRuntime.ts | 978 +++++++ .../src/workflows/WorkflowStore.test.ts | 424 +++ apps/server/src/workflows/WorkflowStore.ts | 1142 ++++++++ apps/server/src/workflows/Workflows.test.ts | 2424 +++++++++++++++++ apps/server/src/workflows/Workflows.ts | 221 ++ apps/server/src/workflows/api.ts | 15 + apps/server/src/workflows/forgeApi.ts | 109 + apps/server/src/workflows/options.ts | 28 + apps/server/src/workflows/runReferences.ts | 90 + apps/server/src/workflows/stepServices.ts | 458 ++++ apps/server/src/workflows/triggers.ts | 156 ++ apps/server/src/workflows/workflow.ts | 897 ++++++ apps/server/src/workflows/workflowAgent.ts | 442 +++ apps/server/src/ws.test.ts | 165 ++ apps/server/src/ws.ts | 27 + docs/internals/workflows.md | 178 ++ .../orchestrator-mcp-server.md | 7 + docs/user/managed-policy.md | 1 + docs/user/outside-agents.md | 6 +- evals/README.md | 15 +- evals/package.json | 1 + evals/workflow-authoring/README.md | 36 + evals/workflow-authoring/cases.ts | 270 ++ .../workflow-authoring/fixtures/globals.d.ts | 11 + .../fixtures/replay-keeps-in-a-module.ts | 19 + .../fixtures/replay-keeps-what-it-read.ts | 20 + .../fixtures/replay-reads-outside-a-step.ts | 17 + .../fixtures/scheduled-agent-then-approval.ts | 34 + .../fixtures/webhook-filter-and-dedupe.ts | 22 + evals/workflow-authoring/grade.ts | 159 ++ evals/workflow-authoring/run.test.ts | 37 + evals/workflow-authoring/run.ts | 179 ++ knip.jsonc | 4 + .../contracts/src/clientRpcPermissions.ts | 7 + packages/contracts/src/index.ts | 1 + packages/contracts/src/milestones.ts | 70 +- packages/contracts/src/orchestrationV2.ts | 27 +- packages/contracts/src/rpc.ts | 88 + packages/contracts/src/settings.ts | 3 + packages/contracts/src/workflow.ts | 223 ++ packages/shared/src/nodeSqliteClient.test.ts | 17 + packages/shared/src/nodeSqliteClient.ts | 6 + packages/shared/src/t3McpToolPresentation.ts | 1 + skills/t3-workflows/SKILL.md | 353 +++ 90 files changed, 14092 insertions(+), 92 deletions(-) create mode 100644 apps/server/src/cli/workflow.test.ts create mode 100644 apps/server/src/cli/workflow.ts create mode 100644 apps/server/src/mcp/toolkits/workflow/handlers.ts create mode 100644 apps/server/src/mcp/toolkits/workflow/tools.ts create mode 100644 apps/server/src/persistence/Migrations/110_Workflows.ts create mode 100644 apps/server/src/workflows/WorkflowAgentLinks.test.ts create mode 100644 apps/server/src/workflows/WorkflowAgentLinks.ts create mode 100644 apps/server/src/workflows/WorkflowAgentThreads.ts create mode 100644 apps/server/src/workflows/WorkflowAgents.ts create mode 100644 apps/server/src/workflows/WorkflowEngine.ts create mode 100644 apps/server/src/workflows/WorkflowForge.test.ts create mode 100644 apps/server/src/workflows/WorkflowForge.ts create mode 100644 apps/server/src/workflows/WorkflowRuntime.test.ts create mode 100644 apps/server/src/workflows/WorkflowRuntime.ts create mode 100644 apps/server/src/workflows/WorkflowStore.test.ts create mode 100644 apps/server/src/workflows/WorkflowStore.ts create mode 100644 apps/server/src/workflows/Workflows.test.ts create mode 100644 apps/server/src/workflows/Workflows.ts create mode 100644 apps/server/src/workflows/api.ts create mode 100644 apps/server/src/workflows/forgeApi.ts create mode 100644 apps/server/src/workflows/options.ts create mode 100644 apps/server/src/workflows/runReferences.ts create mode 100644 apps/server/src/workflows/stepServices.ts create mode 100644 apps/server/src/workflows/triggers.ts create mode 100644 apps/server/src/workflows/workflow.ts create mode 100644 apps/server/src/workflows/workflowAgent.ts create mode 100644 docs/internals/workflows.md create mode 100644 evals/workflow-authoring/README.md create mode 100644 evals/workflow-authoring/cases.ts create mode 100644 evals/workflow-authoring/fixtures/globals.d.ts create mode 100644 evals/workflow-authoring/fixtures/replay-keeps-in-a-module.ts create mode 100644 evals/workflow-authoring/fixtures/replay-keeps-what-it-read.ts create mode 100644 evals/workflow-authoring/fixtures/replay-reads-outside-a-step.ts create mode 100644 evals/workflow-authoring/fixtures/scheduled-agent-then-approval.ts create mode 100644 evals/workflow-authoring/fixtures/webhook-filter-and-dedupe.ts create mode 100644 evals/workflow-authoring/grade.ts create mode 100644 evals/workflow-authoring/run.test.ts create mode 100644 evals/workflow-authoring/run.ts create mode 100644 packages/contracts/src/workflow.ts create mode 100644 skills/t3-workflows/SKILL.md diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index 2cab3d32f1235..b276fafb2723a 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -129,6 +129,10 @@ export const RPC_REQUIRED_SCOPES = { [WS_METHODS.serverSignalProcess]: AuthEnvironmentMaintainScope, [WS_METHODS.serverReportClientActivity]: AuthOrchestrationReadScope, [WS_METHODS.scheduledTasksSubscribe]: AuthOrchestrationReadScope, + [WS_METHODS.workflowsSubscribe]: AuthOrchestrationReadScope, + [WS_METHODS.workflowsCounts]: AuthOrchestrationReadScope, + [WS_METHODS.workflowsGet]: AuthOrchestrationReadScope, + [WS_METHODS.workflowsGetDefinition]: AuthFilesystemReadScope, [WS_METHODS.secretsAnswerRequest]: AuthOrchestrationOperateScope, [WS_METHODS.agentFeedbackAnswerRequest]: AuthOrchestrationOperateScope, // Delivery logs hold request bodies, so they need the same scope as the URL. diff --git a/apps/server/src/binCli.ts b/apps/server/src/binCli.ts index 677336175d723..2ae78f272cd6b 100644 --- a/apps/server/src/binCli.ts +++ b/apps/server/src/binCli.ts @@ -22,6 +22,7 @@ import { sharedServerCommandFlags } from "./cli/config.ts"; import { projectCommand } from "./cli/project.ts"; import { feedbackCommand } from "./cli/feedback.ts"; import { threadCommand } from "./cli/thread.ts"; +import { workflowCommand } from "./cli/workflow.ts"; import { runDefaultServerCommand, serveCommand, startCommand } from "./cli/server.ts"; import { updateCommand } from "./cli/update.ts"; import { @@ -93,6 +94,7 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) => projectCommand, threadCommand, feedbackCommand, + workflowCommand, upCommand, statusCommand, serviceCommand, diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts index bd40b51c8ce4d..1d81dcc6bd7cb 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -197,6 +197,15 @@ const toolFailureDetail = (result: typeof ToolResult.Type) => { }); }; +/** JSON-RPC's invalid params: the arguments failed the tool's schema. */ +const INVALID_PARAMS = -32602; +const rpcErrorDetail = (error: { readonly code: number; readonly message: string }) => { + const message = error.message.replaceAll(/\s*\n\s*/g, " "); + return error.code === INVALID_PARAMS + ? `The server refused the arguments: ${message}` + : `The server refused the request: ${message}`; +}; + const makeThreadTools = (session: McpToolSession, origin: string) => { const unexpected = (tool: string) => new ThreadToolFailedError({ @@ -214,10 +223,13 @@ const makeThreadTools = (session: McpToolSession, origin: string) => { > { const raw = yield* session.call(tool, args).pipe( Effect.mapError((cause) => - // Effect's MCP server words an unknown or hidden tool exactly this way. - cause.rpcError?.code === -32602 && cause.rpcError.message === `Tool '${tool}' not found` - ? new ThreadToolMissingError({ tool }) - : new ThreadServerUnreachableError({ origin, cause }), + cause.rpcError === undefined + ? new ThreadServerUnreachableError({ origin, cause }) + : // Effect's MCP server words an unknown or hidden tool exactly this way. + cause.rpcError.code === -32602 && + cause.rpcError.message === `Tool '${tool}' not found` + ? new ThreadToolMissingError({ tool }) + : new ThreadToolFailedError({ tool, detail: rpcErrorDetail(cause.rpcError) }), ), ); const result = yield* decodeToolResult(raw).pipe(Effect.mapError(() => unexpected(tool))); diff --git a/apps/server/src/cli/workflow.test.ts b/apps/server/src/cli/workflow.test.ts new file mode 100644 index 0000000000000..0c99ca8ee8d21 --- /dev/null +++ b/apps/server/src/cli/workflow.test.ts @@ -0,0 +1,186 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import { AuthSessionId, type WorkflowRun } from "@t3tools/contracts"; +import * as NetService from "@t3tools/shared/Net"; +import * as ConfigProvider from "effect/ConfigProvider"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; +import * as TestConsole from "effect/testing/TestConsole"; +import { Command } from "effect/cli"; +import { vi } from "vite-plus/test"; + +import * as McpBridge from "../mcp/AcpMcpStdioBridge.ts"; +import { + makePersistedServerRuntimeState, + persistServerRuntimeState, +} from "../serverRuntimeState.ts"; +import { workflowCommand } from "./workflow.ts"; + +vi.mock("../auth/EnvironmentAuth.ts", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + layerRuntime: Layer.mock(actual.EnvironmentAuth)({ + issueMcpClientSession: () => + Effect.map(DateTime.now, (expiresAt) => ({ + sessionId: AuthSessionId.make("test-session"), + token: "synthetic-token", + expiresAt, + })), + revokeSession: () => Effect.succeed(true), + }), + }; +}); + +const makeRun = (status: WorkflowRun["status"]): WorkflowRun => ({ + runId: "run-1", + workflow: "review", + version: 1, + title: "review pr-1", + status, + detail: null, + result: null, + pauses: 0, + retired: false, + resumesAt: null, + parentRunId: null, + parentStep: null, + startedAt: "2026-11-20T00:00:00.000Z", + updatedAt: "2026-11-20T00:00:00.000Z", + endedAt: ["running", "waiting", "paused"].includes(status) ? null : "2026-11-20T00:00:00.000Z", +}); + +/** Runs `t3 workflow ` against a live-looking server whose t3_workflow is `call`. */ +const runCli = ( + args: ReadonlyArray, + call: McpBridge.McpToolSession["call"] = () => Effect.die("no tool call expected"), +) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-workflow-cli-" }); + yield* persistServerRuntimeState({ + path: path.join(baseDir, "userdata", "server-runtime.json"), + state: yield* makePersistedServerRuntimeState({ + config: { host: "127.0.0.1", devUrl: undefined }, + port: 3_773, + }), + }); + const calls: Array>> = []; + using _session = vi.spyOn(McpBridge, "mcpToolSession").mockReturnValue( + Effect.succeed({ + call: (tool, input) => { + calls.push(input); + return call(tool, input); + }, + }), + ); + const error = yield* Command.runWith(workflowCommand, { version: "0.0.0" })([ + ...args, + "--base-dir", + baseDir, + ]).pipe( + Effect.flip, + Effect.orElseSucceed(() => undefined), + ); + return { error, calls, errors: yield* TestConsole.errorLines }; + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + NetService.layer, + ConfigProvider.layer(ConfigProvider.fromEnv({ env: { T3CODE_PORT: "3773" } })), + ), + ), + ); + +/** Answers each action with the run in `status`, as the server does. */ +const serving = + (status: WorkflowRun["status"]): McpBridge.McpToolSession["call"] => + () => + Effect.succeed({ structuredContent: { run: makeRun(status), steps: [] } }); + +it.effect("cancel sends --reason, and steers nothing when the run cannot take it", () => + Effect.gen(function* () { + const cancelled = yield* runCli( + ["cancel", "run-1", "--reason", "superseded"], + serving("running"), + ); + assert.deepStrictEqual(cancelled.calls.at(-1), { + action: "cancel", + runId: "run-1", + reason: "superseded", + }); + + for (const [command, status, said] of [ + ["cancel", "completed", "Run run-1 is completed; nothing to cancel."], + ["resume", "waiting", "Run run-1 is waiting; nothing to resume."], + ["resume", "cancelled", "Run run-1 is cancelled; nothing to resume."], + ] as const) { + const { error, calls, errors } = yield* runCli([command, "run-1"], serving(status)); + assert.isUndefined(error, command); + assert.deepStrictEqual( + calls.map((input) => input.action), + ["read"], + ); + assert.include(errors, said); + } + }), +); + +it.effect("reports what the server refused instead of calling it unreachable", () => + Effect.gen(function* () { + // A blank key is refused here, before the server is asked. + const blank = yield* runCli(["start", "review", "--key", " "], () => + Effect.die("the server is not asked"), + ); + assert.strictEqual(blank.error?.message, "--key cannot be blank."); + + const refused = yield* runCli(["start", "review", "--key", "r1"], () => + Effect.fail( + new McpBridge.AcpMcpBridgeError({ + message: "T3 Code MCP tools/call failed.", + rpcError: { + code: -32602, + message: 'Expected a non-blank string\n at ["idempotencyKey"]', + }, + }), + ), + ); + assert.strictEqual(refused.error?._tag, "ThreadToolFailedError"); + assert.strictEqual( + refused.error?.message, + 'The server refused the arguments: Expected a non-blank string at ["idempotencyKey"]', + ); + + const unreachable = yield* runCli(["start", "review", "--key", "pr-1"], () => + Effect.fail(new McpBridge.AcpMcpBridgeError({ message: "fetch failed" })), + ); + assert.strictEqual(unreachable.error?._tag, "ThreadServerUnreachableError"); + }), +); + +it.effect("signal refuses both addresses at once before reaching the server", () => + Effect.gen(function* () { + const { error, calls } = yield* runCli([ + "signal", + "{}", + "--run", + "run-1", + "--wait", + "approve", + "--workflow", + "review", + "--channel", + "pr-1", + ]); + assert.strictEqual(error?._tag, "ThreadUsageError"); + assert.lengthOf(calls, 0); + }), +); diff --git a/apps/server/src/cli/workflow.ts b/apps/server/src/cli/workflow.ts new file mode 100644 index 0000000000000..95a499043c6c6 --- /dev/null +++ b/apps/server/src/cli/workflow.ts @@ -0,0 +1,408 @@ +import { WorkflowHook, WorkflowRunStatus } from "@t3tools/contracts"; +import * as Console from "effect/Console"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import { Argument, Command, Flag } from "effect/cli"; + +import * as Workflows from "../workflows/Workflows.ts"; +import { WorkflowRun, WorkflowStep } from "../workflows/WorkflowStore.ts"; +import { projectLocationFlags } from "./config.ts"; +import { + jsonFlag, + printJson, + reportThreadErrors, + type ThreadTools, + ThreadUsageError, + withThreadTools, +} from "./thread.ts"; + +const RunResult = Schema.Struct({ run: WorkflowRun, steps: Schema.Array(WorkflowStep) }); +const RunsResult = Schema.Struct({ runs: Schema.Array(WorkflowRun) }); +const QuestionsResult = Schema.Struct({ questions: Schema.Array(Workflows.WorkflowQuestion) }); +const HooksResult = Schema.Struct({ hooks: Schema.Array(WorkflowHook) }); +const SignalResult = Schema.Struct({ delivery: Schema.Literals(["delivered", "buffered"]) }); + +const decodeJson = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Json)); +const jsonArgument = (text: string, what: string) => + decodeJson(text).pipe( + Effect.mapError(() => new ThreadUsageError({ detail: `${what} is not valid JSON.` })), + ); + +const runLine = (run: WorkflowRun) => + [run.runId, run.status.padEnd(9), run.workflow, run.title, run.detail ?? ""].join(" ").trimEnd(); + +const printRun = Effect.fn("cli.workflow.printRun")(function* ( + result: typeof RunResult.Type, + json: boolean, +) { + if (json) return yield* printJson(result); + yield* Console.log(runLine(result.run)); + for (const step of result.steps) { + yield* Console.log( + ` ${step.status.padEnd(9)} ${step.kind.padEnd(5)} ${step.name}${ + step.attempts > 1 ? ` (${step.attempts} tries)` : "" + }${step.environmentId === null ? "" : ` in ${step.environmentId}`}${ + step.detail === null ? "" : ` ${step.detail}` + }`, + ); + } + if (result.run.result !== null) yield* printJson(result.run.result); +}); + +const runArgument = Argument.String("run").pipe(Argument.withDescription("Run id.")); +const readRun = (tools: ThreadTools, runId: string) => + tools.call("t3_workflow", { action: "read", runId }, RunResult); + +const startCommand = Command.make("start", { + ...projectLocationFlags, + workflow: Argument.String("workflow").pipe(Argument.withDescription("Workflow name.")), + input: Flag.String("input").pipe( + Flag.withDescription("The run's payload, as JSON. Defaults to {}."), + Flag.withDefault("{}"), + ), + key: Flag.String("key").pipe( + Flag.withDescription( + "Required. Names this run: starting again with the same key is the same run, not a second one.", + ), + ), + json: jsonFlag, +}).pipe( + Command.withDescription("Start a workflow run and print it."), + Command.withHandler((flags) => + Effect.gen(function* () { + const input = yield* jsonArgument(flags.input, "--input"); + if (flags.key.trim() === "") { + return yield* new ThreadUsageError({ detail: "--key cannot be blank." }); + } + yield* withThreadTools( + flags, + Effect.fn("cli.workflow.start")(function* (tools) { + const started = yield* tools.call( + "t3_workflow", + { action: "start", workflow: flags.workflow, input, idempotencyKey: flags.key }, + RunResult, + ); + yield* printRun(started, flags.json); + }), + ); + }).pipe(reportThreadErrors), + ), +); + +const listCommand = Command.make("list", { + ...projectLocationFlags, + status: Flag.Literals("status", WorkflowRunStatus.literals).pipe( + Flag.withDescription( + "Only runs in this state. A skipped run is listed only with `skipped`, unless another run invoked it.", + ), + Flag.optional, + ), + json: jsonFlag, +}).pipe( + Command.withDescription("List workflow runs, newest first."), + Command.withHandler((flags) => + withThreadTools( + flags, + Effect.fn("cli.workflow.list")(function* (tools) { + const { runs } = yield* tools.call( + "t3_workflow", + { + action: "list", + ...(Option.isSome(flags.status) ? { status: flags.status.value } : {}), + }, + RunsResult, + ); + // A workflow skips what was never its to do, and that is most of what a trigger brings. + const listed = Option.isSome(flags.status) + ? runs + : runs.filter((run) => run.status !== "skipped" || run.parentRunId !== null); + if (flags.json) return yield* printJson(listed); + for (const run of listed) yield* Console.log(runLine(run)); + }), + ).pipe(reportThreadErrors), + ), +); + +const showCommand = Command.make("show", { + ...projectLocationFlags, + run: runArgument, + json: jsonFlag, +}).pipe( + Command.withDescription("Show a run and its steps."), + Command.withHandler((flags) => + withThreadTools( + flags, + Effect.fn("cli.workflow.show")(function* (tools) { + yield* printRun(yield* readRun(tools, flags.run), flags.json); + }), + ).pipe(reportThreadErrors), + ), +); + +/** Why `action` would leave the run as it is, or undefined when it would act. */ +const noOpReason = (action: "resume" | "cancel", run: WorkflowRun) => { + if (action === "cancel") { + return run.endedAt === null + ? undefined + : `Run ${run.runId} is ${run.status}; nothing to cancel.`; + } + return run.status === "paused" + ? undefined + : `Run ${run.runId} is ${run.status}; nothing to resume.`; +}; + +const steer = Effect.fn("cli.workflow.steer")(function* ( + tools: ThreadTools, + action: "resume" | "cancel", + flags: { readonly run: string; readonly json: boolean; readonly reason: Option.Option }, +) { + const before = yield* readRun(tools, flags.run); + const skipped = noOpReason(action, before.run); + if (skipped !== undefined) { + // Stderr, so --json output stays the run alone. + yield* Console.error(skipped); + return yield* printRun(before, flags.json); + } + const after = yield* tools.call( + "t3_workflow", + { + action, + runId: flags.run, + ...(Option.isSome(flags.reason) ? { reason: flags.reason.value } : {}), + }, + RunResult, + ); + yield* printRun(after, flags.json); +}); + +const resumeCommand = Command.make("resume", { + ...projectLocationFlags, + run: runArgument, + json: jsonFlag, +}).pipe( + Command.withDescription("Run a paused run's failed step again."), + Command.withHandler((flags) => + withThreadTools(flags, (tools) => + steer(tools, "resume", { ...flags, reason: Option.none() }), + ).pipe(reportThreadErrors), + ), +); + +const cancelCommand = Command.make("cancel", { + ...projectLocationFlags, + run: runArgument, + reason: Flag.String("reason").pipe( + Flag.withDescription("Why, kept as the run's detail."), + Flag.optional, + ), + json: jsonFlag, +}).pipe( + Command.withDescription("Cancel a run."), + Command.withHandler((flags) => + withThreadTools(flags, (tools) => steer(tools, "cancel", flags)).pipe(reportThreadErrors), + ), +); + +const signalCommand = Command.make("signal", { + ...projectLocationFlags, + value: Argument.String("value").pipe( + Argument.withDescription('What the wait receives, as JSON. A question takes {"choice": ...}.'), + ), + run: Flag.String("run").pipe( + Flag.withDescription("Run id. Pass with --wait, not with --workflow and --channel."), + Flag.optional, + ), + wait: Flag.String("wait").pipe( + Flag.withDescription("The wait's or question's name in that run."), + Flag.optional, + ), + workflow: Flag.String("workflow").pipe( + Flag.withDescription("Workflow name. Pass with --channel when the run is not known."), + Flag.optional, + ), + channel: Flag.String("channel").pipe( + Flag.withDescription("The channel the wait opened with."), + Flag.optional, + ), + id: Flag.String("id").pipe( + Flag.withDescription( + "Names this signal: sending it again with the same id is the same signal.", + ), + Flag.optional, + ), +}).pipe( + Command.withDescription("Wake a waiting run, or answer its question."), + Command.withHandler((flags) => + Effect.gen(function* () { + const value = yield* jsonArgument(flags.value, "The value"); + const byRun = Option.isSome(flags.run) || Option.isSome(flags.wait); + const byChannel = Option.isSome(flags.workflow) || Option.isSome(flags.channel); + if (byRun && byChannel) { + return yield* new ThreadUsageError({ + detail: + "Address a signal with --run and --wait, or with --workflow and --channel, not both.", + }); + } + yield* withThreadTools( + { ...flags, json: false }, + Effect.fn("cli.workflow.signal")(function* (tools) { + const { delivery } = yield* tools.call( + "t3_workflow", + { + action: "signal", + value, + ...(Option.isSome(flags.run) ? { runId: flags.run.value } : {}), + ...(Option.isSome(flags.wait) ? { wait: flags.wait.value } : {}), + ...(Option.isSome(flags.workflow) ? { workflow: flags.workflow.value } : {}), + ...(Option.isSome(flags.channel) ? { channel: flags.channel.value } : {}), + ...(Option.isSome(flags.id) ? { signalId: flags.id.value } : {}), + }, + SignalResult, + ); + yield* Console.log( + delivery === "delivered" ? "Delivered." : "Kept until a run waits for it.", + ); + }), + ); + }).pipe(reportThreadErrors), + ), +); + +const questionsCommand = Command.make("questions", { + ...projectLocationFlags, + json: jsonFlag, +}).pipe( + Command.withDescription("List the questions runs are waiting on a person to answer."), + Command.withHandler((flags) => + withThreadTools( + flags, + Effect.fn("cli.workflow.questions")(function* (tools) { + const { questions } = yield* tools.call( + "t3_workflow", + { action: "questions" }, + QuestionsResult, + ); + if (flags.json) return yield* printJson(questions); + for (const question of questions) { + yield* Console.log(`${question.runId} ${question.name}`); + yield* printJson(question.request); + } + }), + ).pipe(reportThreadErrors), + ), +); + +const hooksCommand = Command.make("hooks", { + ...projectLocationFlags, + json: jsonFlag, +}).pipe( + Command.withDescription( + "List the URL paths that start runs. Each holds its hook's secret; add the server's origin.", + ), + Command.withHandler((flags) => + withThreadTools( + flags, + Effect.fn("cli.workflow.hooks")(function* (tools) { + const { hooks } = yield* tools.call("t3_workflow", { action: "hooks" }, HooksResult); + if (flags.json) return yield* printJson(hooks); + for (const hook of hooks) { + yield* Console.log(`${hook.workflow} ${hook.name} ${hook.path}`); + } + }), + ).pipe(reportThreadErrors), + ), +); + +const StoreResult = Schema.Struct({ + entries: Schema.Array(Schema.Struct({ key: Schema.String, value: Schema.Json })), +}); +const keyArgument = Argument.String("key").pipe(Argument.withDescription("The key in the store.")); + +const storeListCommand = Command.make("list", { + ...projectLocationFlags, + prefix: Argument.String("prefix").pipe( + Argument.withDescription("Only keys that start with this."), + Argument.withDefault(""), + ), + json: jsonFlag, +}).pipe( + Command.withDescription("List what workflows keep in the store."), + Command.withHandler((flags) => + withThreadTools( + flags, + Effect.fn("cli.workflow.store.list")(function* (tools) { + const { entries } = yield* tools.call( + "t3_workflow", + { action: "store", ...(flags.prefix === "" ? {} : { key: flags.prefix }) }, + StoreResult, + ); + if (flags.json) return yield* printJson(entries); + for (const entry of entries) { + yield* Console.log(entry.key); + yield* printJson(entry.value); + } + }), + ).pipe(reportThreadErrors), + ), +); + +const storeSetCommand = Command.make("set", { + ...projectLocationFlags, + key: keyArgument, + value: Argument.String("value").pipe(Argument.withDescription("The value, as JSON.")), +}).pipe( + Command.withDescription("Set a key of the store, as a person flipping a switch does."), + Command.withHandler((flags) => + Effect.gen(function* () { + const value = yield* jsonArgument(flags.value, "The value"); + yield* withThreadTools( + { ...flags, json: false }, + Effect.fn("cli.workflow.store.set")(function* (tools) { + yield* tools.call( + "t3_workflow", + { action: "store_set", key: flags.key, value }, + StoreResult, + ); + yield* Console.log(`Set ${flags.key}.`); + }), + ); + }).pipe(reportThreadErrors), + ), +); + +const storeDeleteCommand = Command.make("delete", { + ...projectLocationFlags, + key: keyArgument, +}).pipe( + Command.withDescription("Delete a key of the store."), + Command.withHandler((flags) => + withThreadTools( + { ...flags, json: false }, + Effect.fn("cli.workflow.store.delete")(function* (tools) { + yield* tools.call("t3_workflow", { action: "store_delete", key: flags.key }, StoreResult); + yield* Console.log(`Deleted ${flags.key}.`); + }), + ).pipe(reportThreadErrors), + ), +); + +const storeCommand = Command.make("store").pipe( + Command.withDescription("See and change what workflows keep between runs."), + Command.withSubcommands([storeListCommand, storeSetCommand, storeDeleteCommand]), +); + +export const workflowCommand = Command.make("workflow").pipe( + Command.withDescription("Start, inspect and steer durable workflow runs on the running server."), + Command.withSubcommands([ + startCommand, + listCommand, + showCommand, + resumeCommand, + cancelCommand, + signalCommand, + questionsCommand, + hooksCommand, + storeCommand, + ]), +); diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts index c707c912d672d..9076aadd47381 100644 --- a/apps/server/src/config.ts +++ b/apps/server/src/config.ts @@ -43,6 +43,8 @@ export interface ServerDerivedPaths { readonly environmentThemesDir: string; readonly providerStatusCacheDir: string; readonly worktreesDir: string; + /** Where workflow definition files live. In the home itself: they are the user's own code. */ + readonly workflowsDir: string; readonly worktreeCheckoutCacheDir: string; readonly attachmentsDir: string; readonly browserArtifactsDir: string; @@ -161,6 +163,7 @@ export const deriveServerPaths = Effect.fn(function* ( environmentThemesDir: join(stateDir, "themes"), providerStatusCacheDir, worktreesDir: join(baseDir, "worktrees"), + workflowsDir: join(baseDir, "workflows"), worktreeCheckoutCacheDir: join(providerStatusCacheDir, "worktree-checkouts"), attachmentsDir, browserArtifactsDir: join(stateDir, "browser-artifacts"), diff --git a/apps/server/src/feedback/FeedbackReport.ts b/apps/server/src/feedback/FeedbackReport.ts index ad1fe305ba6db..f7c026700b0e8 100644 --- a/apps/server/src/feedback/FeedbackReport.ts +++ b/apps/server/src/feedback/FeedbackReport.ts @@ -160,6 +160,19 @@ export const T3_CLI_COMMANDS: ReadonlyArray = [ "t3 thread show", "t3 feedback", "t3 feedback list", + "t3 workflow", + "t3 workflow start", + "t3 workflow list", + "t3 workflow show", + "t3 workflow resume", + "t3 workflow cancel", + "t3 workflow signal", + "t3 workflow questions", + "t3 workflow hooks", + "t3 workflow store", + "t3 workflow store list", + "t3 workflow store set", + "t3 workflow store delete", "t3 up", "t3 status", "t3 service", diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index ff55a2ea5459c..5bf97d42a2461 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -71,6 +71,8 @@ import * as ProjectHandlers from "./toolkits/project/handlers.ts"; import { AttachmentToolkit } from "./toolkits/attachment/tools.ts"; import * as AttachmentHandlers from "./toolkits/attachment/handlers.ts"; import { ThreadToolkit } from "./toolkits/thread/tools.ts"; +import { WorkflowToolkit } from "./toolkits/workflow/tools.ts"; +import * as WorkflowHandlers from "./toolkits/workflow/handlers.ts"; import * as ThreadHandlers from "./toolkits/thread/handlers.ts"; import * as ThreadMetadataMcpService from "./ThreadMetadataMcpService.ts"; import * as McpSessionRegistry from "./McpSessionRegistry.ts"; @@ -1336,6 +1338,7 @@ export const layerOrchestratorToolkit = toolkitRegistration( ).pipe(Layer.provide(OrchestratorMcpService.layer), Layer.provide(ThreadMetadataMcpService.layer)); export const layerThreadToolkit = toolkitRegistration(ThreadToolkit, ThreadHandlers.layer); +const layerWorkflowToolkit = toolkitRegistration(WorkflowToolkit, WorkflowHandlers.layer); const layerMessageToolkit = toolkitRegistration(MessageToolkit, MessageHandlers.layer); @@ -1432,6 +1435,7 @@ export const layerTools = Layer.mergeAll( layerPreviewToolkit, layerOrchestratorToolkit, layerThreadToolkit, + layerWorkflowToolkit, layerAttachmentToolkit, layerProjectRegistration, layerFeedbackToolkit, @@ -1501,7 +1505,11 @@ export const layerToolSearch = Layer.mergeAll( export const layerMilestoneEvents = Layer.effectDiscard( Effect.gen(function* () { const annotations = Context.make(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromThreads); - for (const options of yield* MilestoneEvents.make) { + const events = yield* MilestoneEvents.make; + for (const options of events.threads) { + yield* McpServer.registerEvent({ ...options, annotations }); + } + for (const options of events.workflows) { yield* McpServer.registerEvent({ ...options, annotations }); } }), diff --git a/apps/server/src/mcp/toolkits/project/handlers.ts b/apps/server/src/mcp/toolkits/project/handlers.ts index 76f53b43bdfdc..511dcfe26c3df 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.ts @@ -459,6 +459,10 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { ...(linkOrigin === undefined ? {} : { linkOrigin }), // Kept only alongside linkOrigin: thread.create drops it otherwise. ...(input.delegatedFrom === undefined ? {} : { delegatedFrom: input.delegatedFrom }), + // A link's word for it, like `delegatedFrom`: nothing else may name a run. + ...(linkOrigin === undefined || input.workflowRun === undefined + ? {} + : { workflowRun: input.workflowRun }), }).pipe( Effect.mapError((error) => { if (error._tag === "AttachmentClaimError") { diff --git a/apps/server/src/mcp/toolkits/project/tools.ts b/apps/server/src/mcp/toolkits/project/tools.ts index 52e9b77ab3df2..4aff1e4385c8d 100644 --- a/apps/server/src/mcp/toolkits/project/tools.ts +++ b/apps/server/src/mcp/toolkits/project/tools.ts @@ -7,6 +7,7 @@ import { ThreadId, RunId, OrchestrationV2DelegatedFrom, + OrchestrationV2WorkflowOrigin, OrchestrationV2RunStatus, OrchestrationV2ThreadLaunchWorkspaceStrategy, RuntimeMode, @@ -165,6 +166,8 @@ const ThreadLaunchTool = Tool.make("t3_thread_launch", { clientRequestId: Schema.optional(OrchestratorMcpClientRequestId), /** Set by a linked environment launching its agent's delegated task here; ignored otherwise. */ delegatedFrom: Schema.optional(OrchestrationV2DelegatedFrom), + /** Set by a linked environment whose workflow run this thread is a step of; ignored otherwise. */ + workflowRun: Schema.optional(OrchestrationV2WorkflowOrigin), }), success: Schema.Struct({ threadId: ThreadId, diff --git a/apps/server/src/mcp/toolkits/workflow/handlers.ts b/apps/server/src/mcp/toolkits/workflow/handlers.ts new file mode 100644 index 0000000000000..fe19b06108480 --- /dev/null +++ b/apps/server/src/mcp/toolkits/workflow/handlers.ts @@ -0,0 +1,98 @@ +import { OrchestratorMcpFailure } from "@t3tools/contracts"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Effect from "effect/Effect"; + +import * as Workflows from "../../../workflows/Workflows.ts"; +import * as McpToolAccess from "../../McpToolAccess.ts"; +import { WORKFLOW_READ_ACTIONS, WorkflowToolkit } from "./tools.ts"; + +const invalid = (message: string) => + new OrchestratorMcpFailure({ code: "invalid_request", message }); +const required = (value: A | undefined, name: string) => + value === undefined + ? Effect.fail(invalid(`This action needs \`${name}\`.`)) + : Effect.succeed(value); +const refused = (error: Workflows.WorkflowError) => invalid(error.message); +const isRead = (action: string): action is (typeof WORKFLOW_READ_ACTIONS)[number] => + (WORKFLOW_READ_ACTIONS as ReadonlyArray).includes(action); + +export const layer = McpToolAccess.toLayer(WorkflowToolkit, { + t3_workflow: McpToolAccess.either( + (input) => isRead(input.action), + McpToolAccess.reads((input) => + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + if (input.action === "questions") { + return { questions: yield* workflows.questions.pipe(Effect.mapError(refused)) }; + } + if (input.action === "store") { + return { + entries: yield* workflows.stored(input.key ?? "").pipe(Effect.mapError(refused)), + }; + } + if (input.action === "list") { + return { + runs: yield* workflows + .list(input.status === undefined ? {} : { status: input.status }) + .pipe(Effect.mapError(refused)), + }; + } + const runId = yield* required(input.runId, "runId"); + return yield* workflows.get(runId).pipe(Effect.mapError(refused)); + }), + ), + McpToolAccess.writes((input) => + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + // A hook's path holds its secret, and posting to it starts a run. + if (input.action === "hooks") { + return { hooks: yield* workflows.hooks.pipe(Effect.mapError(refused)) }; + } + if (input.action === "start") { + const name = yield* required(input.workflow, "workflow"); + const idempotencyKey = yield* required(input.idempotencyKey, "idempotencyKey"); + const { runId } = yield* workflows + .start(name, input.input ?? {}, { idempotencyKey }) + .pipe(Effect.mapError(refused)); + return yield* workflows.get(runId).pipe(Effect.mapError(refused)); + } + if (input.action === "signal") { + const value = yield* required(input.value, "value"); + const address = + input.runId !== undefined && input.wait !== undefined + ? { runId: input.runId, wait: input.wait } + : input.workflow !== undefined && input.channel !== undefined + ? { workflow: input.workflow, channel: input.channel } + : undefined; + if (address === undefined) { + return yield* invalid( + "Address a signal with `runId` and `wait`, or `workflow` and `channel`.", + ); + } + const random = yield* SecureRandom.SecureRandom; + const id = input.signalId ?? (yield* random.uuidV4()); + const delivery = yield* workflows + .signal(address, value, { id }) + .pipe(Effect.mapError(refused)); + return { delivery }; + } + if (input.action === "store_set" || input.action === "store_delete") { + const key = yield* required(input.key, "key"); + const value = + input.action === "store_set" ? yield* required(input.value, "value") : undefined; + yield* ( + value === undefined ? workflows.storeDelete(key) : workflows.storeSet(key, value) + ).pipe(Effect.mapError(refused)); + return { entries: yield* workflows.stored(key).pipe(Effect.mapError(refused)) }; + } + const runId = yield* required(input.runId, "runId"); + yield* ( + input.action === "resume" + ? workflows.resume(runId) + : workflows.cancel(runId, input.reason) + ).pipe(Effect.mapError(refused)); + return yield* workflows.get(runId).pipe(Effect.mapError(refused)); + }), + ), + ), +}); diff --git a/apps/server/src/mcp/toolkits/workflow/tools.ts b/apps/server/src/mcp/toolkits/workflow/tools.ts new file mode 100644 index 0000000000000..fa01dfb7c5712 --- /dev/null +++ b/apps/server/src/mcp/toolkits/workflow/tools.ts @@ -0,0 +1,69 @@ +import { OrchestratorMcpFailure, TrimmedNonEmptyString, WorkflowHook } from "@t3tools/contracts"; +import * as Schema from "effect/Schema"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import { McpSchema, Tool, Toolkit } from "effect/ai"; + +import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts"; +import * as Workflows from "../../../workflows/Workflows.ts"; +import { WorkflowRun, WorkflowRunStatus, WorkflowStep } from "../../../workflows/WorkflowStore.ts"; +import * as McpInvocationContext from "../../McpInvocationContext.ts"; + +export const WORKFLOW_READ_ACTIONS = ["list", "read", "questions", "store"] as const; + +const WorkflowTool = Tool.make("t3_workflow", { + description: + "Durable workflow runs on this server. start: `workflow`, `input`, `idempotencyKey` (same key, same run). list: runs, by `status`. read: one run and its steps. questions: what runs ask a person. hooks: the URL paths that start runs. store: what workflows keep, under keys starting with `key`; store_set a `key` to `value`; store_delete. signal: wake a wait with `value`, addressed by `runId` and `wait`, or by `workflow` and `channel`; answers a question as `{choice, reason?}`. resume: run a paused run's failed step again. cancel.", + parameters: Schema.Struct({ + action: Schema.Literals([ + ...WORKFLOW_READ_ACTIONS, + "hooks", + "start", + "signal", + "resume", + "cancel", + "store_set", + "store_delete", + ]), + workflow: Schema.optional(TrimmedNonEmptyString), + input: Schema.optional(Schema.Json), + idempotencyKey: Schema.optional(TrimmedNonEmptyString), + runId: Schema.optional(TrimmedNonEmptyString), + status: Schema.optional(WorkflowRunStatus), + wait: Schema.optional(TrimmedNonEmptyString), + key: Schema.optional(TrimmedNonEmptyString), + channel: Schema.optional(TrimmedNonEmptyString), + value: Schema.optional(Schema.Json), + signalId: Schema.optional( + TrimmedNonEmptyString.annotate({ + description: "Reuse it to retry the same signal. A new signal gets a new id.", + }), + ), + reason: Schema.optional(Schema.String), + }), + success: Schema.Struct({ + run: Schema.optional(WorkflowRun), + steps: Schema.optional(Schema.Array(WorkflowStep)), + runs: Schema.optional(Schema.Array(WorkflowRun)), + questions: Schema.optional(Schema.Array(Workflows.WorkflowQuestion)), + hooks: Schema.optional(Schema.Array(WorkflowHook)), + entries: Schema.optional( + Schema.Array(Schema.Struct({ key: Schema.String, value: Schema.Json })), + ), + delivery: Schema.optional(Schema.Literals(["delivered", "buffered"])), + }), + failure: OrchestratorMcpFailure, + failureMode: "return" as const, + dependencies: [ + McpInvocationContext.McpInvocationContext, + Workflows.Workflows, + ThreadManagementService.ThreadManagementService, + SecureRandom.SecureRandom, + ], +}) + .annotate(Tool.Title, "Workflow runs") + .annotate(Tool.Destructive, true) + // Outside clients and the CLI drive workflows. An agent in a thread reaches them through the + // CLI, so the tool costs no thread any context. + .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromThreads); + +export const WorkflowToolkit = Toolkit.make(WorkflowTool); diff --git a/apps/server/src/milestones/MilestoneEvents.test.ts b/apps/server/src/milestones/MilestoneEvents.test.ts index bdf102b4dce6f..44896477fa670 100644 --- a/apps/server/src/milestones/MilestoneEvents.test.ts +++ b/apps/server/src/milestones/MilestoneEvents.test.ts @@ -174,7 +174,7 @@ it.effect("advertises the extension and lists each milestone type to outside cli }); const { events } = (yield* call("events/list")).result!; - expect(events).toHaveLength(6); + expect(events).toHaveLength(12); const settledType = events.find( (event: { name: string }) => event.name === "thread.run_settled", ); @@ -182,9 +182,19 @@ it.effect("advertises the extension and lists each milestone type to outside cli expect(Object.keys(settledType.inputSchema.properties)).toEqual([ "projectIds", "threadIds", + "workflowRunIds", "includeSubagentChildren", ]); expect(settledType.payloadSchema.properties.outcome).toBeDefined(); + const workflowType = events.find( + (event: { name: string }) => event.name === "workflow.run_ended", + ); + // A workflow run belongs to no project or thread, so it is picked by workflow and run. + expect(Object.keys(workflowType.inputSchema.properties)).toEqual([ + "workflows", + "workflowRunIds", + "includeSubagentChildren", + ]); expect((yield* call("events/list", {}, { token: threadToken })).result!.events).toEqual([]); }).pipe(Effect.scoped, Effect.provide(layerTest)), ); diff --git a/apps/server/src/milestones/MilestoneEvents.ts b/apps/server/src/milestones/MilestoneEvents.ts index 5b07d64b3aa59..9c0f2edd0ae55 100644 --- a/apps/server/src/milestones/MilestoneEvents.ts +++ b/apps/server/src/milestones/MilestoneEvents.ts @@ -1,8 +1,10 @@ import { type MilestoneEvent as MilestoneEventValue, MilestoneEvent, + type MilestoneFilter, ProjectId, ThreadId, + TrimmedNonEmptyString, } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; @@ -15,12 +17,30 @@ import * as MilestoneHub from "./MilestoneHub.ts"; const MAX_EVENTS = 1_000; const DEFAULT_EVENTS = 100; +const includeSubagentChildren = Schema.optional( + Schema.Boolean.annotate({ + description: "Also subagent threads and runs another run invoked.", + }), +); +const workflowRunIds = Schema.optional(Schema.Array(TrimmedNonEmptyString)); + const Parameters = Schema.Struct({ projectIds: Schema.optional(Schema.Array(ProjectId)), threadIds: Schema.optional(Schema.Array(ThreadId)), - includeSubagentChildren: Schema.optional( - Schema.Boolean.annotate({ description: "Also subagent threads." }), + workflowRunIds: Schema.optional( + Schema.Array(TrimmedNonEmptyString).annotate({ + description: "Workflow runs, for the threads that are their agent steps.", + }), + ), + includeSubagentChildren, +}); + +const WorkflowParameters = Schema.Struct({ + workflows: Schema.optional( + Schema.Array(TrimmedNonEmptyString).annotate({ description: "Workflow names." }), ), + workflowRunIds, + includeSubagentChildren, }); const DESCRIPTIONS: Record = { @@ -30,6 +50,13 @@ const DESCRIPTIONS: Record = { "thread.guest_request": "A guest on a shared thread asked for something.", "thread.guest_request_resolved": "A guest's request was sent, dismissed, or its link closed.", "pr.watch_wake": "A watched pull request changed and woke its thread.", + "workflow.run_started": "A workflow run started.", + "workflow.needs_input": "A workflow run asks a person a question.", + "workflow.input_resolved": + "A workflow run's question was answered, timed out, or ended with its run.", + "workflow.run_paused": "A workflow run paused: a step failed, or someone paused it.", + "workflow.run_resumed": "A paused workflow run went on again.", + "workflow.run_ended": "A workflow run ended: completed, stopped, skipped or cancelled.", }; const occurrence = ({ event }: MilestoneHub.PositionedMilestone) => ({ @@ -41,42 +68,58 @@ const occurrence = ({ event }: MilestoneHub.PositionedMilestone) => ({ /** * Each milestone type as an MCP event type (SEP-3415), for outside clients to poll or stream. * Cursors are the hub's, so a client that was away catches up on what the hub still keeps. + * Workflow runs have no project or thread, so their types are narrowed by workflow and run. */ export const make = Effect.gen(function* () { const hub = yield* MilestoneHub.MilestoneHub; - return MilestoneEvent.members.map((payload) => { - const type = payload.fields.type.literal; - const filterOf = (args: typeof Parameters.Type) => ({ ...args, types: [type] }); - return { - name: type, - description: DESCRIPTIONS[type], - parameters: Parameters, - payload, - poll: (args, request) => - hub - .read({ - cursor: request.cursor, - maxAgeMs: request.maxAgeMs, - filter: filterOf(args), - limit: Math.min(request.maxEvents ?? DEFAULT_EVENTS, MAX_EVENTS), - }) - .pipe(Effect.map((page) => ({ ...page, events: page.events.map(occurrence) }))), - stream: (args, request) => - hub - .follow({ cursor: request.cursor, maxAgeMs: request.maxAgeMs, filter: filterOf(args) }) - .pipe( - Effect.map(({ cursor, truncated, items }) => ({ - cursor, - truncated, - items: items.pipe( - Stream.map((item): McpServer.EventStreamItem => - item._tag === "Milestone" - ? { _tag: "Event", cursor: item.cursor, ...occurrence(item) } - : item, - ), - ), - })), - ), - } satisfies McpServer.EventOptions; - }); + const isWorkflow = (payload: (typeof MilestoneEvent.members)[number]) => + payload.fields.type.literal.startsWith("workflow."); + return { + threads: MilestoneEvent.members + .filter((payload) => !isWorkflow(payload)) + .map((payload) => eventOf(hub, payload, Parameters)), + workflows: MilestoneEvent.members + .filter(isWorkflow) + .map((payload) => eventOf(hub, payload, WorkflowParameters)), + }; }); + +const eventOf =

    ( + hub: MilestoneHub.MilestoneHub["Service"], + payload: (typeof MilestoneEvent.members)[number], + parameters: P, +) => { + const type = payload.fields.type.literal; + const filterOf = (args: P["Type"]): MilestoneFilter => ({ ...args, types: [type] }); + return { + name: type, + description: DESCRIPTIONS[type], + parameters, + payload, + poll: (args, request) => + hub + .read({ + cursor: request.cursor, + maxAgeMs: request.maxAgeMs, + filter: filterOf(args), + limit: Math.min(request.maxEvents ?? DEFAULT_EVENTS, MAX_EVENTS), + }) + .pipe(Effect.map((page) => ({ ...page, events: page.events.map(occurrence) }))), + stream: (args, request) => + hub + .follow({ cursor: request.cursor, maxAgeMs: request.maxAgeMs, filter: filterOf(args) }) + .pipe( + Effect.map(({ cursor, truncated, items }) => ({ + cursor, + truncated, + items: items.pipe( + Stream.map((item): McpServer.EventStreamItem => + item._tag === "Milestone" + ? { _tag: "Event", cursor: item.cursor, ...occurrence(item) } + : item, + ), + ), + })), + ), + } satisfies McpServer.EventOptions; +}; diff --git a/apps/server/src/milestones/MilestoneHub.test.ts b/apps/server/src/milestones/MilestoneHub.test.ts index 0361c81f4f7e0..40d757a50c3ea 100644 --- a/apps/server/src/milestones/MilestoneHub.test.ts +++ b/apps/server/src/milestones/MilestoneHub.test.ts @@ -21,6 +21,22 @@ const settled = ( runId: RunId.make(`run:${id}`), outcome: "completed", }); +const workflowEnded = (id: string, workflowRunId: string): MilestoneEvent => ({ + id: MilestoneId.make(id), + type: "workflow.run_ended", + occurredAt: "2026-11-20T00:00:00.000Z", + projectId: null, + threadId: null, + parentThreadId: null, + actor: { type: "system" }, + isSubagentChild: false, + workflowRunId, + workflow: "review", + runTitle: "Review", + parentWorkflowRunId: null, + outcome: "completed", + detail: null, +}); const ids = (events: Iterable) => [...events].map((event) => event.id); it.effect("fans out to every subscriber, muting subagent children unless asked for", () => @@ -29,21 +45,31 @@ it.effect("fans out to every subscriber, muting subagent children unless asked f const muted = yield* hub.subscribe(); const everything = yield* hub.subscribe({ includeSubagentChildren: true }); const projectB = yield* hub.subscribe({ projectIds: [ProjectId.make("project:b")] }); + const runR1 = yield* hub.subscribe({ workflowRunIds: ["r1"] }); yield* hub.publish(settled("a")); yield* hub.publish(settled("child", { child: true })); // A repeat of an id is the same milestone. yield* hub.publish(settled("a")); yield* hub.publish(settled("b", { project: "project:b" })); + yield* hub.publish(workflowEnded("w0", "r0")); + yield* hub.publish(workflowEnded("w1", "r1")); - assert.deepStrictEqual(ids(yield* Stream.runCollect(Stream.take(muted, 2))), ["a", "b"]); + assert.deepStrictEqual(ids(yield* Stream.runCollect(Stream.take(muted, 4))), [ + "a", + "b", + "w0", + "w1", + ]); assert.deepStrictEqual(ids(yield* Stream.runCollect(Stream.take(everything, 3))), [ "a", "child", "b", ]); + // A workflow milestone has no project, and a thread milestone no workflow run. assert.deepStrictEqual(ids(yield* Stream.runCollect(Stream.take(projectB, 1))), ["b"]); - assert.deepStrictEqual(ids((yield* hub.recent()).events), ["a", "b"]); + assert.deepStrictEqual(ids(yield* Stream.runCollect(Stream.take(runR1, 1))), ["w1"]); + assert.deepStrictEqual(ids((yield* hub.recent()).events), ["a", "b", "w0", "w1"]); }).pipe(Effect.scoped, Effect.provide(MilestoneHub.layer)), ); diff --git a/apps/server/src/milestones/OrchestrationMilestones.test.ts b/apps/server/src/milestones/OrchestrationMilestones.test.ts index 7930b2ab8097b..bffe7b75fe605 100644 --- a/apps/server/src/milestones/OrchestrationMilestones.test.ts +++ b/apps/server/src/milestones/OrchestrationMilestones.test.ts @@ -1,6 +1,7 @@ import { assert, it } from "@effect/vitest"; import { CommandId, + EnvironmentId, EventId, GuestMessageId, GuestShareId, @@ -106,6 +107,40 @@ it.effect("tells each thread transition once, with its lineage", () => const childThreadId = (yield* projections.getThreadProjection(parentThreadId)).subagents[0]! .childThreadId!; const childRun = (yield* projections.getThreadRecords(childThreadId, ["runs"])).runs[0]!; + // A workflow run's agent step, which a filter on its run picks out. + const stepThreadId = ThreadId.make("thread:milestone-workflow-step"); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("create-milestone-step"), + threadId: stepThreadId, + projectId: ProjectId.make("project:milestones"), + title: "Triage", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdBy: "system", + creationSource: "server", + workflowRun: { + environmentId: EnvironmentId.make("environment:milestones"), + runId: "workflow-run:milestones", + workflow: "review", + step: "triage", + }, + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("start-milestone-step"), + threadId: stepThreadId, + messageId: MessageId.make("message:milestone-step"), + text: "Triage the issue", + attachments: [], + dispatchMode: { type: "start_immediately" }, + createdBy: "system", + creationSource: "server", + }); + const stepRun = (yield* projections.getThreadRecords(stepThreadId, ["runs"])).runs[0]!; const parent = yield* projections.getThread(parentThreadId); const now = yield* DateTime.now; const base = (id: string, threadId: ThreadId) => ({ @@ -213,6 +248,7 @@ it.effect("tells each thread transition once, with its lineage", () => shared("event:guest-closed", null), wake, wake, + ended("event:step-done", stepRun, "completed"), ]) { yield* feeder.handle(event); } @@ -235,8 +271,15 @@ it.effect("tells each thread transition once, with its lineage", () => ["thread.guest_request:guest:two", parentThreadId, null, false], ["thread.guest_request_resolved:guest:two", parentThreadId, null, false], ["pr.watch_wake:message:pr-wake", parentThreadId, null, false], + [`thread.run_settled:${stepRun.id}`, stepThreadId, null, false], ], ); + assert.deepStrictEqual( + (yield* hub.recent({ filter: { workflowRunIds: ["workflow-run:milestones"] } })).events.map( + (event) => event.threadId, + ), + [stepThreadId], + ); const [, child, asked, answered, , sent, , closed, woke] = events; assert.deepInclude(child, { outcome: "failed", projectId: parent.projectId }); assert.deepInclude(asked, { kind: "approval" }); diff --git a/apps/server/src/milestones/OrchestrationMilestones.ts b/apps/server/src/milestones/OrchestrationMilestones.ts index c50c460ec4814..941776771a040 100644 --- a/apps/server/src/milestones/OrchestrationMilestones.ts +++ b/apps/server/src/milestones/OrchestrationMilestones.ts @@ -70,6 +70,7 @@ const make = Effect.gen(function* () { parentThreadId: thread.lineage.parentThreadId, actor, isSubagentChild: thread.lineage.relationshipToParent === "subagent", + ...(thread.workflowRun === undefined ? {} : { workflowRunId: thread.workflowRun.runId }), }); const guestMilestones = ( diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index f8e20da24fbaf..a4a918fe1ddee 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -105,6 +105,15 @@ const RPC_AGGREGATES = { [WS_METHODS.serverRefreshUsageRates]: "server", [WS_METHODS.serverSignalProcess]: "server", [WS_METHODS.serverReportClientActivity]: "server", + [WS_METHODS.workflowsSubscribe]: "workflows", + [WS_METHODS.workflowsCounts]: "workflows", + [WS_METHODS.workflowsGet]: "workflows", + [WS_METHODS.workflowsAnswer]: "workflows", + [WS_METHODS.workflowsResume]: "workflows", + [WS_METHODS.workflowsCancel]: "workflows", + [WS_METHODS.workflowsGetDefinition]: "workflows", + [WS_METHODS.workflowsSaveDefinition]: "workflows", + [WS_METHODS.workflowsDeleteDefinition]: "workflows", [WS_METHODS.scheduledTasksSubscribe]: "scheduledTasks", [WS_METHODS.scheduledTasksUpsert]: "scheduledTasks", [WS_METHODS.scheduledTasksSetEnabled]: "scheduledTasks", diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 5b1623f8414ec..8a546270a0515 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -4077,10 +4077,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ...(command.linkOrigin === undefined || command.delegatedFrom === undefined ? {} : { delegatedFrom: command.delegatedFrom }), + ...(command.workflowRun === undefined ? {} : { workflowRun: command.workflowRun }), lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: command.threadId, + ...(command.workflowRun === undefined ? {} : { workflowStep: true }), }, forkedFrom: null, createdAt: now, diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index e10bc5340d646..2278284d7fde7 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -1960,6 +1960,9 @@ export function threadShellFromProjection( ...(projection.thread.delegatedFrom === undefined ? {} : { delegatedFrom: projection.thread.delegatedFrom }), + ...(projection.thread.workflowRun === undefined + ? {} + : { workflowRun: projection.thread.workflowRun }), latestRunId: latestRun?.id ?? null, latestRunRequestedAt: latestRun?.requestedAt ?? null, latestRunStartedAt: latestRun?.startedAt ?? null, @@ -2274,6 +2277,9 @@ function shellFromState(input: { ...(input.state.thread.delegatedFrom === undefined ? {} : { delegatedFrom: input.state.thread.delegatedFrom }), + ...(input.state.thread.workflowRun === undefined + ? {} + : { workflowRun: input.state.thread.workflowRun }), latestRunId: input.state.latestRunId, latestRunRequestedAt: input.state.latestRunRequestedAt, latestRunStartedAt: input.state.latestRunStartedAt, @@ -9620,6 +9626,7 @@ export const layer: Layer.Layer = readonly parent_thread_id: string | null; readonly root_thread_id: string; readonly side_chat: number | null; + readonly workflow_step: number | null; readonly delegated_from_environment_id: string | null; readonly delegated_from_thread_id: string | null; readonly delegated_from_title: string | null; @@ -9636,6 +9643,7 @@ export const layer: Layer.Layer = json_extract(t.payload_json, '$.lineage.parentThreadId') AS parent_thread_id, json_extract(t.payload_json, '$.lineage.rootThreadId') AS root_thread_id, json_extract(t.payload_json, '$.lineage.sideChat') AS side_chat, + json_extract(t.payload_json, '$.lineage.workflowStep') AS workflow_step, json_extract(t.payload_json, '$.delegatedFrom.environmentId') AS delegated_from_environment_id, json_extract(t.payload_json, '$.delegatedFrom.threadId') AS delegated_from_thread_id, json_extract(t.payload_json, '$.delegatedFrom.title') AS delegated_from_title, @@ -9650,7 +9658,10 @@ export const layer: Layer.Layer = id: ThreadId.make(row.thread_id), projectId: ProjectId.make(row.project_id), title: row.title, - lineage: shellIndexLineage(row), + lineage: { + ...shellIndexLineage(row), + ...(row.workflow_step === 1 ? { workflowStep: true } : {}), + }, ...(row.delegated_from_environment_id === null || row.delegated_from_thread_id === null ? {} : { diff --git a/apps/server/src/orchestration-v2/ThreadForkService.ts b/apps/server/src/orchestration-v2/ThreadForkService.ts index e3e523e372bd0..2981b4ccfb519 100644 --- a/apps/server/src/orchestration-v2/ThreadForkService.ts +++ b/apps/server/src/orchestration-v2/ThreadForkService.ts @@ -100,7 +100,12 @@ export const layer: Layer.Layer = Layer.succeed( }); } // The remote parent delegated the source thread, not its forks. - const { delegatedFrom: _delegatedFrom, ...inherited } = input.sourceProjection.thread; + // Nor is a fork a step of the run its source was one of. + const { + delegatedFrom: _delegatedFrom, + workflowRun: _workflowRun, + ...inherited + } = input.sourceProjection.thread; const targetThread: OrchestrationV2AppThread = { ...inherited, // PR context follows the conversation; watching remains the source thread's responsibility. diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts index 73eaabdde2016..2d5d1c5824dde 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts @@ -503,7 +503,7 @@ it.effect( }, ); -it.effect("leaves a task delegated from a linked environment out of the top-level list", () => { +it.effect("leaves delegated tasks and workflow agent steps out of the top-level list", () => { const harness = makeHarness(); return Effect.gen(function* () { const launches = yield* ThreadLaunch.ThreadLaunchService; @@ -522,15 +522,26 @@ it.effect("leaves a task delegated from a linked environment out of the top-leve title: "Remote parent", }, }); + const workflowStep = yield* launches.launch({ + ...launchInput({ command: "command:workflow-step", thread: "thread:workflow-step" }), + createdBy: "system", + creationSource: "server", + workflowRun: { + environmentId: EnvironmentId.make("environment:local"), + runId: "run:1", + workflow: "review", + step: "agent", + }, + }); const listed = yield* threads.listProjectThreads({ projectId, includeSubagents: false }); assert.deepEqual( listed.map((thread) => thread.id), [ThreadId.make("thread:top-level")], ); const all = yield* threads.listProjectThreads({ projectId, includeSubagents: true }); - assert.include( + assert.includeMembers( all.map((thread) => thread.id), - delegated.threadId, + [delegated.threadId, workflowStep.threadId], ); }).pipe(Effect.provide(harness.layer)); }); diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.ts index 0382415179bfc..ce22ad783e0e6 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.ts @@ -10,6 +10,7 @@ import { type OrchestrationV2Actor, type OrchestrationV2CreationSource, type OrchestrationV2DelegatedFrom, + type OrchestrationV2WorkflowOrigin, type OrchestrationV2LinkOrigin, type OrchestrationV2ProviderThreadNativeMetadata, type OrchestrationV2ThreadProjection, @@ -124,6 +125,8 @@ export interface ThreadLaunchInput { readonly linkOrigin?: OrchestrationV2LinkOrigin; /** The parent there, when that environment's agent delegated this as a task. */ readonly delegatedFrom?: OrchestrationV2DelegatedFrom; + /** The workflow run this thread is an agent step of. */ + readonly workflowRun?: OrchestrationV2WorkflowOrigin; } type PreparationInput = Pick< @@ -1473,6 +1476,7 @@ const make = Effect.gen(function* () { ...(input.delegatedFrom === undefined ? {} : { delegatedFrom: input.delegatedFrom }), + ...(input.workflowRun === undefined ? {} : { workflowRun: input.workflowRun }), createdBy: input.createdBy, creationSource: input.creationSource, ...(initialMessage === undefined diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts index a0b5625af0d2a..eb137e4c50610 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts @@ -74,6 +74,13 @@ it("stamps authoritative provenance on commands that create threads or messages" text: "Forged", attachments: [], }, + // Nor a workflow run it is a step of. + workflowRun: { + environmentId: EnvironmentId.make("environment:elsewhere"), + runId: "run-1", + workflow: "fix", + step: "write", + }, }; const stamped = ThreadManagementService.withCreationProvenance(command, { @@ -87,6 +94,7 @@ it("stamps authoritative provenance on commands that create threads or messages" expect(stamped).not.toHaveProperty("linkOrigin"); expect(stamped).not.toHaveProperty("delegatedFrom"); expect(stamped).not.toHaveProperty("initialMessage"); + expect(stamped).not.toHaveProperty("workflowRun"); }); const layerReceiptsTest = CommandReceiptStore.layer.pipe( @@ -465,6 +473,113 @@ it.effect("waitForThread can wait past an ended run for the thread's delegated w }), ); +it.effect( + "a turn that ended without its result is waited past, and a later turn answers for it", + () => + Effect.gen(function* () { + const projectId = ProjectId.make("project:thread-management:owed"); + const threadId = ThreadId.make("thread:thread-management:owed"); + const runId = RunId.make("run:thread-management:owed"); + const wakeRunId = RunId.make("run:thread-management:owed:wake"); + const subscribed = yield* Deferred.make(); + const events = yield* Queue.unbounded(); + const outputSchema = { type: "object", required: ["head"] }; + const run = (id: RunId, ordinal: number, fields: object) => + ({ id, ordinal, ...fields }) as unknown as OrchestrationV2Run; + // The agent ended its turn to wait for something, without the result it was asked for. + let runs = [run(runId, 1, { status: "completed", outputSchema })]; + const submitted: Array = []; + const stored = (sequence: number, event: object) => + ({ sequence, event: { threadId, ...event } }) as unknown as OrchestrationV2StoredEvent; + const layerTest = ThreadManagementService.layer.pipe( + Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})), + Layer.provide( + Layer.mock(Orchestrator.OrchestratorV2)({ + getThreadEventSequence: () => Effect.succeed(0), + restartContinuationPending: () => Effect.succeed(false), + streamStoredEventsFrom: (input) => + input?.eventType === "run.output-submitted" + ? Stream.fromEffect(Deferred.succeed(subscribed, undefined)).pipe( + Stream.drain, + Stream.concat(Stream.fromQueue(events)), + ) + : Stream.never, + getThreadRecords: () => + Effect.sync( + () => + ({ + thread: { id: threadId, projectId, deletedAt: null }, + runs, + }) as unknown as OrchestrationV2ThreadProjection, + ), + dispatch: (command) => + Effect.sync(() => { + submitted.push(command); + return { sequence: 1 } as never; + }), + }), + ), + Layer.provide(ServerSettings.layerTest()), + Layer.provide(layerReceiptsTest), + ); + const service = yield* ThreadManagementService.ThreadManagementService.pipe( + Effect.provide(layerTest), + ); + const wait = { projectId, threadId, runId, timeoutMs: 60 * 60 * 1_000 }; + // Without the option the ended turn is the answer, as before. + expect(yield* service.waitForThread(wait)).toMatchObject({ timedOut: false }); + // A turn asked for nothing owes nothing, so the option does not hold it. + const plainRunId = RunId.make("run:thread-management:owed:plain"); + runs = [run(plainRunId, 0, { status: "completed" }), ...runs]; + expect( + yield* Effect.raceFirst( + service.waitForThread({ ...wait, runId: plainRunId, untilOutput: true }), + Effect.as(Deferred.await(subscribed), "waited for a result"), + ), + ).toMatchObject({ timedOut: false, run: { id: plainRunId } }); + runs = runs.slice(1); + + const fiber = yield* service + .waitForThread({ ...wait, untilOutput: true }) + .pipe(Effect.forkChild); + yield* Effect.raceFirst(Deferred.await(subscribed), Fiber.await(fiber)); + // Something wakes the thread. The turn it starts was asked for nothing, and submits anyway. + // A request queued behind it asks for a result of its own, and is not the one owed. + const queuedRunId = RunId.make("run:thread-management:owed:queued"); + runs = [ + ...runs, + run(wakeRunId, 2, { status: "running" }), + run(queuedRunId, 3, { status: "queued", outputSchema }), + ]; + const accepted = yield* service.submitRunOutput({ + threadId, + commandId: CommandId.make("command:thread-management:owed"), + json: '{"head":"abc"}', + }); + expect(accepted.runId).toBe(runId); + expect(submitted).toMatchObject([ + { type: "run.output.submit", runId, value: { head: "abc" } }, + ]); + const output = { value: { head: "abc" }, submittedAt: "2026-01-01T00:00:00.000Z" }; + runs = [run(runId, 1, { status: "completed", outputSchema, output }), runs[1]!, runs[2]!]; + yield* Queue.offer(events, stored(1, { type: "run.output-submitted", payload: {} })); + expect(yield* Fiber.join(fiber)).toMatchObject({ + timedOut: false, + run: { id: runId, output }, + }); + + // The result is given once: a later plain turn has nothing to submit to. + const again = yield* service + .submitRunOutput({ + threadId, + commandId: CommandId.make("command:thread-management:owed:again"), + json: '{"head":"def"}', + }) + .pipe(Effect.flip); + expect(again.message).toContain("not asked for a result"); + }), +); + it.effect("waitForThread settles delegated work on a thread rolled back past its only run", () => Effect.gen(function* () { const projectId = ProjectId.make("project:thread-management:wait-rolled-back"); diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index 45b5e9effa8cf..0acb07029f35d 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -70,6 +70,7 @@ import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts"; import { DispatchModeLimit, exceededDispatchModeLimit } from "./DispatchModeLimit.ts"; import { projectTurnItemForDetail } from "./WireProjection.ts"; import { cancelledBeforeStart } from "./RestartBackgroundNote.ts"; +import { contextBoundaryOrdinal } from "./contextBoundary.ts"; import * as LegacyV1ThreadImporter from "./legacy/LegacyV1ThreadImporter.ts"; import * as ServerSettings from "../serverSettings.ts"; import { ThreadWorktreeRestore } from "../workspace/restoreMissingWorktree.ts"; @@ -93,6 +94,7 @@ export function withCreationProvenance( linkOrigin: _linkOrigin, delegatedFrom: _delegatedFrom, initialMessage: _initialMessage, + workflowRun: _workflowRun, ...rest } = command; return { ...rest, ...provenance }; @@ -1035,18 +1037,44 @@ const make = Effect.gen(function* () { "ThreadManagementService.submitRunOutput", )(function* (input) { const records = yield* orchestrator.getThreadRecords(input.threadId, ["runs"]); + // A retry of a submission already taken answers for the run it went to, which a run asked for + // a result since may have followed. Replaying the receipt ignores the command's run and value. + const receipt = yield* receipts + .getByCommandId(input.commandId) + .pipe(Effect.orElseSucceed(() => Option.none())); + const anyRun = records.runs[0]; + if (Option.isSome(receipt) && receipt.value.status === "accepted" && anyRun !== undefined) { + const replayed = yield* orchestrator.dispatch({ + type: "run.output.submit", + commandId: input.commandId, + threadId: input.threadId, + runId: anyRun.id, + value: null, + }); + const runId = replayed.storedEvents.find(({ event }) => event.type === "run.output-submitted") + ?.event.runId; + if (runId !== undefined) return { runId }; + } const active = latestActiveRun(records); // A turn that ended without its result still owes it: the agent may have ended it to wait - // for something, and answer from the turn that woke it. - // Only an ended turn can owe one; a queued or running turn asked for one answers for itself. - const owed = records.runs + // for something, and answer from the turn that woke it. Only the newest started run asked for + // one can owe it, and only while the agent's conversation still reaches it. + const asked = records.runs .filter( (candidate) => candidate.outputSchema !== undefined && - candidate.output === undefined && - candidate.status === "completed", + candidate.status !== "queued" && + !cancelledBeforeStart(candidate), ) .toSorted((left, right) => right.ordinal - left.ordinal)[0]; + const owing = asked?.status === "completed" && asked.output === undefined ? asked : undefined; + const forgotten = + owing !== undefined && + records.runs.some((later) => later.freshContext === true && later.ordinal > owing.ordinal) && + contextBoundaryOrdinal( + yield* orchestrator.getThreadRecords(input.threadId, ["runs", "turnItems"]), + ) > owing.ordinal; + const owed = forgotten ? undefined : owing; const run = active?.outputSchema !== undefined ? active : owed; if (active === undefined || run?.outputSchema === undefined) { return yield* new ThreadManagementRunOutputRejectedError({ @@ -1364,6 +1392,15 @@ const make = Effect.gen(function* () { }, } as const; } + if (explicitRun?.status === "queued") { + const dispatch = yield* orchestrator.dispatch({ + type: "queued-run.cancel", + commandId: input.commandId, + threadId: input.threadId, + runId: explicitRun.id, + }); + return { type: "interrupt_requested", run: explicitRun, dispatch } as const; + } const interruptibleRun = latestActiveRun(target); if (interruptibleRun === undefined) { if (input.runId === undefined) { diff --git a/apps/server/src/orchestration-v2/runOutput.ts b/apps/server/src/orchestration-v2/runOutput.ts index 26df71c0fa2e8..20d76ecff009d 100644 --- a/apps/server/src/orchestration-v2/runOutput.ts +++ b/apps/server/src/orchestration-v2/runOutput.ts @@ -60,6 +60,12 @@ export interface OutputRejection { readonly cause?: unknown; } +/** The rejection as told to whoever wrote the value: the problem, then what in it did not fit. */ +export const rejectionText = (rejection: OutputRejection): string => + rejection.cause instanceof Error + ? `${rejection.problem}\n${rejection.cause.message.slice(0, 2000)}` + : rejection.problem; + /** * Checks what an agent submitted against the schema its run declared. The value is kept as * submitted. A schema that closes its object turns down keys it does not name; an open one keeps diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 3d640f61fc398..d43bd686d6932 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -11953,6 +11953,70 @@ it.layer(layerSharedApplicationDataPlaneTest)("pending provider interruption", ( assert.isFalse(yield* effectWorker.runOnce()); }), ); + + it.effect("cancels a named queued run and leaves the active one running", () => + Effect.gen(function* () { + const projects = yield* ProjectService.ProjectService; + const orchestrator = yield* Orchestrator.OrchestratorV2; + const threadManagement = yield* ThreadManagementService.ThreadManagementService; + const projectId = ProjectId.make("runtime-layer-queued-interrupt-project"); + const threadId = ThreadId.make("runtime-layer-queued-interrupt-thread"); + + yield* projects.create({ + commandId: CommandId.make("runtime-layer-queued-interrupt-project-create"), + projectId, + title: "Queued interrupt project", + workspaceRoot: "/tmp/runtime-layer-queued-interrupt-project", + }); + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("runtime-layer-queued-interrupt-create"), + threadId, + projectId, + title: "Queued interrupt", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + }); + for (const [key, dispatchMode] of [ + ["active", { type: "start_immediately" }], + ["queued", { type: "queue_after_active" }], + ] as const) { + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`runtime-layer-queued-interrupt-${key}`), + threadId, + messageId: MessageId.make(`runtime-layer-queued-interrupt-${key}`), + text: key, + attachments: [], + modelSelection, + dispatchMode, + }); + } + const [active, queued] = (yield* orchestrator.getThreadProjection(threadId)).runs; + assert.equal(queued?.status, "queued"); + + const interrupt = yield* threadManagement.interruptThread({ + projectId, + commandId: CommandId.make("runtime-layer-queued-interrupt-command"), + threadId, + runId: queued!.id, + }); + assert.equal(interrupt.type, "interrupt_requested"); + + const after = yield* orchestrator.getThreadProjection(threadId); + assert.deepEqual( + after.runs.map((run) => run.status), + [active!.status, "cancelled"], + ); + }), + ); }); it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => { @@ -11984,7 +12048,11 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => branch: null, worktreePath: null, }); - const send = (key: string, outputSchema?: { readonly type: "object" }) => + const send = ( + key: string, + outputSchema?: { readonly type: "object" }, + freshContext?: boolean, + ) => orchestrator.dispatch({ type: "message.dispatch", createdBy: "user", @@ -11996,35 +12064,73 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => attachments: [], modelSelection, ...(outputSchema === undefined ? {} : { outputSchema }), + ...(freshContext === undefined ? {} : { freshContext }), dispatchMode: { type: "start_immediately" }, }); - yield* send("asked", { type: "object" }); - const asked = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!; - // The agent ended its turn to wait for something, without the result. - yield* eventSink.write({ - events: [ - { - id: EventId.make(`${threadId}-asked-completed`), - type: "run.updated", - threadId, - runId: asked.id, - occurredAt: asked.requestedAt, - payload: { ...asked, status: "completed", completedAt: asked.requestedAt }, - }, - ], + const runOf = Effect.fn(function* (key: string) { + const runs = (yield* orchestrator.getThreadProjection(threadId)).runs; + return runs.find( + (run) => run.userMessageId === MessageId.make(`runtime-layer-owed-output-${key}`), + )!; + }); + // The agent ends its turn, to wait for something or because it is done. + const complete = Effect.fn(function* (key: string) { + const run = yield* runOf(key); + yield* eventSink.write({ + events: [ + { + id: EventId.make(`${threadId}-${key}-completed`), + type: "run.updated", + threadId, + runId: run.id, + occurredAt: run.requestedAt, + payload: { ...run, status: "completed", completedAt: run.requestedAt }, + }, + ], + }); + }); + const submit = (key: string, json = '{"head":"abc"}') => + threadManagement.submitRunOutput({ + threadId, + commandId: CommandId.make(`runtime-layer-owed-output-submit-${key}`), + json, + }); + const refused = Effect.fn(function* (key: string) { + const rejected = yield* submit(key).pipe(Effect.flip); + assert.include(rejected.message, "not asked for a result"); }); + yield* send("asked", { type: "object" }); + const asked = yield* runOf("asked"); + yield* complete("asked"); yield* send("woken"); - const accepted = yield* threadManagement.submitRunOutput({ - threadId, - commandId: CommandId.make("runtime-layer-owed-output-submit"), - json: '{"head":"abc"}', - }); + const accepted = yield* submit("asked"); assert.equal(accepted.runId, asked.id); const after = yield* orchestrator.getThreadProjection(threadId); assert.deepEqual(after.runs.find((run) => run.id === asked.id)?.output?.value, { head: "abc", }); + + // Its reply was lost, and the retry comes once the next step's turn asked for a result. + yield* complete("woken"); + yield* send("next", { type: "object" }); + assert.equal((yield* submit("asked")).runId, asked.id); + assert.isUndefined((yield* runOf("next")).output); + + // A correction gave the result `next` owed, so a later plain turn owes nothing. + yield* complete("next"); + yield* send("correction", { type: "object" }); + yield* submit("correction"); + yield* complete("correction"); + yield* send("plain"); + yield* refused("plain"); + + // A turn in a fresh conversation cannot answer for one the agent no longer sees. + yield* complete("plain"); + yield* send("before-fresh", { type: "object" }); + yield* complete("before-fresh"); + yield* send("fresh", undefined, true); + yield* refused("fresh"); }), ); diff --git a/apps/server/src/orchestration-v2/runtimeLayer.ts b/apps/server/src/orchestration-v2/runtimeLayer.ts index 1710da5b061d7..c4eed74b274cf 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.ts @@ -56,6 +56,10 @@ import * as ResourceCleanupService from "./ResourceCleanupService.ts"; import * as RuntimePolicy from "./RuntimePolicy.ts"; import * as RuntimeRequestService from "./RuntimeRequestService.ts"; import * as ThreadManagementService from "./ThreadManagementService.ts"; +import * as PeerLinks from "../peer/PeerLinks.ts"; +import * as PeerMcpClient from "../peer/PeerMcpClient.ts"; +import * as WorkflowRuntime from "../workflows/WorkflowRuntime.ts"; +import * as ThreadIssueService from "./ThreadIssueService.ts"; import * as ThreadLaunchService from "./ThreadLaunchService.ts"; import * as ThreadForkService from "./ThreadForkService.ts"; import * as TurnItemPositionStore from "./TurnItemPositionStore.ts"; @@ -312,6 +316,17 @@ const layerThreadLaunchProvided = ThreadLaunchService.layer.pipe( ).pipe(Layer.provideMerge(layerProjectService)), ), ); +const layerWorkflowsProvided = WorkflowRuntime.layer.pipe( + Layer.provide( + Layer.mergeAll( + layerThreadLaunchProvided, + layerThreadManagementProvided, + ThreadIssueService.layer.pipe(Layer.provide(layerOrchestratorProvided)), + ).pipe(Layer.provideMerge(layerProjectService)), + ), + // Layers memoize by reference, so these are the links Settings and agents use. + Layer.provide(PeerMcpClient.layer.pipe(Layer.provideMerge(PeerLinks.layer))), +); const layerSecretRequestsProvided = SecretRequests.layer.pipe( Layer.provide(layerThreadManagementProvided), ); @@ -423,6 +438,7 @@ export const layerProduction = Layer.mergeAll( layerManagedProjectFoldersProvided, layerThreadLaunchProvided, layerScheduledTaskProvided, + layerWorkflowsProvided, layerScratchThreadPromotionProvided, layerSecretRequestsProvided, layerFeedbackStoreProvided, diff --git a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts index bf47bc86109bb..bb336d3179f34 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts @@ -152,6 +152,7 @@ export function makeReplayServerConfig( providerStatusCacheDir, worktreesDir, worktreeCheckoutCacheDir: path.join(providerStatusCacheDir, "worktree-checkouts"), + workflowsDir: path.join(baseDir, "workflows"), attachmentsDir, browserArtifactsDir: path.join(stateDir, "browser-artifacts"), environmentThemesDir, diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index 9b3fc0b4bb472..36762e9059b58 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -117,6 +117,7 @@ import Migration0106 from "./Migrations/106_WorktreePathKeyIndex.ts"; import Migration0107 from "./Migrations/107_DeferredSlashCommandIndex.ts"; import Migration0108 from "./Migrations/108_AgentFeedback.ts"; import Migration0109 from "./Migrations/109_IssueTrackerAccounts.ts"; +import Migration0110 from "./Migrations/110_Workflows.ts"; const migrationEntries = [ [1, "OrchestrationEvents", Migration0001], @@ -229,6 +230,7 @@ const migrationEntries = [ [107, "DeferredSlashCommandIndex", Migration0107], [108, "AgentFeedback", Migration0108], [109, "IssueTrackerAccounts", Migration0109], + [110, "Workflows", Migration0110], ] as const; export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); diff --git a/apps/server/src/persistence/Migrations/110_Workflows.ts b/apps/server/src/persistence/Migrations/110_Workflows.ts new file mode 100644 index 0000000000000..39f588a564057 --- /dev/null +++ b/apps/server/src/persistence/Migrations/110_Workflows.ts @@ -0,0 +1,149 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +// What people and clients look at of a workflow run, and how something outside reaches a sleeping +// one. The engine journals each run in tables of its own, which it creates when it first starts. +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql` + CREATE TABLE workflow_runs ( + run_id TEXT PRIMARY KEY, + workflow TEXT NOT NULL, + version INTEGER NOT NULL, + engine_tag TEXT NOT NULL, + idempotency_key TEXT NOT NULL, + title TEXT NOT NULL, + status TEXT NOT NULL, + detail TEXT, + result_json TEXT, + pauses INTEGER NOT NULL DEFAULT 0, + started_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + ended_at TEXT, + -- What a run was started with, for the cleanup of a cancelled run whose body is gone. + input_json TEXT, + -- The run that invoked this one and the wait it sits in, so it hears how this one ended. + parent_run_id TEXT, + parent_wait TEXT, + -- A run its agent gave up on waits for a person: resuming starts the agent's whole job again. + held INTEGER NOT NULL DEFAULT 0, + -- When an ended run's engine journal was deleted; the run's own rows stay. + engine_pruned_at TEXT + ) + `; + yield* sql`CREATE INDEX workflow_runs_status ON workflow_runs (status, updated_at)`; + yield* sql`CREATE INDEX workflow_runs_parent ON workflow_runs (parent_run_id)`; + // A key names one run of a workflow whatever its version: the row that takes it is that run. + yield* sql`CREATE UNIQUE INDEX workflow_runs_key ON workflow_runs (workflow, idempotency_key)`; + yield* sql` + CREATE INDEX workflow_runs_unpruned ON workflow_runs (ended_at) + WHERE ended_at IS NOT NULL AND engine_pruned_at IS NULL + `; + yield* sql` + CREATE TABLE workflow_steps ( + run_id TEXT NOT NULL, + name TEXT NOT NULL, + kind TEXT NOT NULL, + status TEXT NOT NULL, + attempts INTEGER NOT NULL DEFAULT 0, + detail TEXT, + thread_id TEXT, + started_at TEXT NOT NULL, + ended_at TEXT, + -- The linked environment an agent step's thread is in; null for this one. + environment_id TEXT, + -- What a step produced, for a person reading the run. The engine keeps its own copy to replay. + result_json TEXT, + -- An agent that returns data also says something at the end; a person reads that first. + said TEXT, + -- The agent step's own turn, so cancelling its run stops that turn and not the whole thread. + turn_id TEXT, + PRIMARY KEY (run_id, name) + ) + `; + yield* sql` + CREATE TABLE workflow_waits ( + run_id TEXT NOT NULL, + name TEXT NOT NULL, + workflow TEXT NOT NULL, + token TEXT NOT NULL, + key TEXT, + schema_json TEXT NOT NULL, + request_json TEXT, + deadline TEXT, + opened_at TEXT NOT NULL, + signalled_at TEXT, + -- What the engine itself looks at to end this wait, such as a pull request's checks. + watch_json TEXT, + -- What a wait was woken with, kept until the run is past it, so a wake lost to a crash is redone. + woke_json TEXT, + PRIMARY KEY (run_id, name) + ) + `; + yield* sql`CREATE INDEX workflow_waits_key ON workflow_waits (workflow, key)`; + // A signal that arrived before its wait. `address` is `run::` or `key::`. + yield* sql` + CREATE TABLE workflow_mail ( + signal_id TEXT PRIMARY KEY, + address TEXT NOT NULL, + value_json TEXT NOT NULL, + expires_at TEXT NOT NULL + ) + `; + yield* sql`CREATE INDEX workflow_mail_address ON workflow_mail (address)`; + // How often a run reached a point it must not pass twice without a person or a rest. + yield* sql` + CREATE TABLE workflow_marks ( + run_id TEXT NOT NULL, + name TEXT NOT NULL, + count INTEGER NOT NULL, + PRIMARY KEY (run_id, name) + ) + `; + // Ids of signals that woke a wait, so a sender's retry of one is not a second signal. Kept at + // least as long as any kept copy of the signal, which would otherwise wake a second wait. + yield* sql` + CREATE TABLE workflow_signals ( + signal_id TEXT PRIMARY KEY, + kept_until TEXT NOT NULL + ) + `; + // When each schedule trigger is next due. + yield* sql` + CREATE TABLE workflow_triggers ( + trigger_id TEXT PRIMARY KEY, + next_at TEXT NOT NULL + ) + `; + // The secret half of each workflow hook's URL. + yield* sql` + CREATE TABLE workflow_hooks ( + hook_id TEXT PRIMARY KEY, + token TEXT NOT NULL + ) + `; + // What workflows keep between runs: a cursor, a switch, a queue. + yield* sql` + CREATE TABLE workflow_store ( + key TEXT PRIMARY KEY, + value_json TEXT NOT NULL, + updated_at TEXT NOT NULL + ) + `; + // What a run touched, once per thing: a later touch updates the row and adds its step. + yield* sql` + CREATE TABLE workflow_run_references ( + run_id TEXT NOT NULL, + kind TEXT NOT NULL, + key TEXT NOT NULL, + address_json TEXT NOT NULL, + title TEXT NOT NULL, + url TEXT, + state TEXT, + steps_json TEXT NOT NULL, + origin TEXT NOT NULL, + noted_at TEXT NOT NULL, + PRIMARY KEY (run_id, kind, key) + ) + `; +}); diff --git a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts index 1b57a7d5e57c3..1b8cf040b5fbc 100644 --- a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts +++ b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts @@ -89,6 +89,7 @@ describe("V2 preview upgrade", () => { [107, "DeferredSlashCommandIndex"], [108, "AgentFeedback"], [109, "IssueTrackerAccounts"], + [110, "Workflows"], ]); assert.deepStrictEqual(yield* runMigrations(), []); assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports); @@ -221,6 +222,7 @@ describe("V2 preview upgrade", () => { [107, "DeferredSlashCommandIndex"], [108, "AgentFeedback"], [109, "IssueTrackerAccounts"], + [110, "Workflows"], ]); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); diff --git a/apps/server/src/provider/AgentContextBudget.test.ts b/apps/server/src/provider/AgentContextBudget.test.ts index 1117bf29801f8..ad8593c387528 100644 --- a/apps/server/src/provider/AgentContextBudget.test.ts +++ b/apps/server/src/provider/AgentContextBudget.test.ts @@ -33,6 +33,7 @@ import { PeerLinkRequests } from "../peer/PeerLinkRequests.ts"; import { PeerLinks } from "../peer/PeerLinks.ts"; import { RemoteDelegation } from "../peer/RemoteDelegation.ts"; import { PreviewManager } from "../preview/Manager.ts"; +import { Workflows } from "../workflows/Workflows.ts"; import { PreviewBrowser } from "../preview/PreviewBrowser.ts"; import { ManagedProjectFolders } from "../project/ManagedProjectFolders.ts"; import { ProjectCloneTracker } from "../project/ProjectCloneTracker.ts"; @@ -75,6 +76,7 @@ const toolHandlerServices = Layer.mergeAll( Layer.mock(PreviewAutomationBroker)({}), Layer.mock(PreviewBrowser)({}), Layer.mock(PreviewManager)({}), + Layer.mock(Workflows)({}), Layer.mock(ProjectCloneTracker)({}), Layer.mock(ProjectService)({}), Layer.mock(ProjectSetupScriptRunner)({}), diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 3f204d2e68a8d..169fac6ce2a85 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 6245, "codexAdditionalContextBytes": 7639, - "mcpToolListJsonBytes": 60374 + "mcpToolListJsonBytes": 61724 } diff --git a/apps/server/src/scheduledTasks/Schedule.ts b/apps/server/src/scheduledTasks/Schedule.ts index f8fb648aaaaa9..ec1f3c2adbd97 100644 --- a/apps/server/src/scheduledTasks/Schedule.ts +++ b/apps/server/src/scheduledTasks/Schedule.ts @@ -4,7 +4,7 @@ import * as Option from "effect/Option"; const MINUTE_MS = 60_000; -function parseTimeOfDay(value: string): { hour: number; minute: number } | null { +export function parseTimeOfDay(value: string): { hour: number; minute: number } | null { const match = /^([01]?\d|2[0-3]):([0-5]\d)$/.exec(value.trim()); if (!match) return null; return { hour: Number(match[1]), minute: Number(match[2]) }; diff --git a/apps/server/src/scheduledTasks/webhookRoute.test.ts b/apps/server/src/scheduledTasks/webhookRoute.test.ts index ace3d93b9ac39..7fb2552a56074 100644 --- a/apps/server/src/scheduledTasks/webhookRoute.test.ts +++ b/apps/server/src/scheduledTasks/webhookRoute.test.ts @@ -31,6 +31,8 @@ import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import * as RelayDeliveryProof from "./RelayDeliveryProof.ts"; import { WEBHOOK_MAX_BODY_BYTES } from "./webhookRoute.ts"; import * as WebhookRoute from "./webhookRoute.ts"; +import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; +import * as Workflows from "../workflows/Workflows.ts"; class WebhookTestApi extends HttpApi.make("environment").add(EnvironmentHttpApi.groups.webhooks) {} @@ -70,6 +72,15 @@ const relayProof = Effect.fn("relayProof")(function* (claims: { }).pipe(Effect.provide(PlatformNodeCrypto.layerSignature)); }); +const workflowDeliveries: Array[0]> = []; +const hooks = Layer.mock(Workflows.Workflows)({ + deliver: (delivery) => + Effect.sync(() => { + workflowDeliveries.push(delivery); + return delivery.token === "tok" ? Option.some({ runId: "run-1" }) : Option.none(); + }), +}); + const handlerFor = ( trigger: ( request: WebhookTriggerRequest, @@ -81,6 +92,7 @@ const handlerFor = ( Layer.provide(WebhookRoute.layer), Layer.provide(RelayDeliveryProof.layer), Layer.provide(Layer.mock(ScheduledTaskService)({ triggerWebhook: trigger })), + Layer.provide([hooks, ManagedPolicy.layerTest()]), Layer.provide( Layer.mock(ServerSecretStore.ServerSecretStore)({ get: (name) => @@ -114,6 +126,30 @@ const post = ( ) => new Request(`http://env.local${path}`, { method: "POST", body, headers }); describe("webhook route", () => { + it.live("a workflow's hook starts a run and never reaches the scheduled tasks", () => + Effect.gen(function* () { + let tasks = 0; + const { handler, dispose } = handlerFor(() => { + tasks += 1; + return Effect.succeed({ _tag: "not_found" }); + }); + const send = (token: string) => + Effect.promise(() => + handler(post(`/api/hooks/wf-inbound.push/${token}?a=1`, "hello", { "X-Delivery": "d1" })), + ); + const accepted = yield* send("tok"); + expect(accepted.status).toBe(202); + expect(yield* Effect.promise(() => accepted.json())).toEqual({ runId: "run-1" }); + expect((yield* send("wrong")).status).toBe(404); + expect(tasks).toBe(0); + expect(workflowDeliveries[0]).toMatchObject({ + hookId: "wf-inbound.push", + request: { method: "POST", query: "a=1", body: "hello", headers: { "x-delivery": "d1" } }, + }); + yield* Effect.promise(dispose); + }), + ); + it.live("trusts the relay's delivery id and receive time only with its signed proof", () => Effect.gen(function* () { const received: Array = []; diff --git a/apps/server/src/scheduledTasks/webhookRoute.ts b/apps/server/src/scheduledTasks/webhookRoute.ts index a7e0c512cbe41..e1650219eb598 100644 --- a/apps/server/src/scheduledTasks/webhookRoute.ts +++ b/apps/server/src/scheduledTasks/webhookRoute.ts @@ -2,6 +2,7 @@ import { EnvironmentHttpApi } from "@t3tools/contracts"; import * as ByteSize from "effect/ByteSize"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; +import * as Result from "effect/Result"; import * as Tracer from "effect/Tracer"; import * as HttpIncomingMessage from "effect/http/HttpIncomingMessage"; import type * as HttpServerRequest from "effect/http/HttpServerRequest"; @@ -11,6 +12,8 @@ import { withRelayClientTracing } from "@t3tools/shared/relayTracing"; import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder"; import * as Metrics from "../observability/Metrics.ts"; +import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; +import * as Workflows from "../workflows/Workflows.ts"; import * as RelayDeliveryProof from "./RelayDeliveryProof.ts"; import * as ScheduledTaskService from "./ScheduledTaskService.ts"; @@ -37,6 +40,8 @@ export const layer = HttpApiBuilder.group( Effect.fnUntraced(function* (handlers) { const scheduledTasks = yield* ScheduledTaskService.ScheduledTaskService; const relayDeliveryProof = yield* RelayDeliveryProof.RelayDeliveryProof; + const workflows = yield* Workflows.Workflows; + const managedPolicy = yield* ManagedPolicy.ManagedPolicy; /** * The endpoint is raw so the signature is checked over the exact body * bytes; the service checks the token and signature. @@ -95,6 +100,39 @@ export const layer = HttpApiBuilder.group( const relayParent = Option.isSome(relay) ? HttpTraceContext.fromHeaders(request.headers) : Option.none(); + if (params.hookId.startsWith(Workflows.HOOK_PREFIX)) { + if (ManagedPolicy.deniedBy(managedPolicy, "webhookTasks") !== undefined) { + return json(403, { error: "blocked_by_policy" }, "blocked_by_policy"); + } + // Answered only once the run is stored, so a sender that hears nothing may send again. + const started = yield* workflows + .deliver({ + hookId: params.hookId, + token: params.token, + request: { + method: request.method, + headers, + query: queryIndex === -1 ? "" : request.url.slice(queryIndex + 1), + body: new TextDecoder().decode(body.value), + }, + ...(relayDeliveryId ? { deliveryId: `relay:${relayDeliveryId}` } : {}), + }) + .pipe(Effect.result); + if (Result.isFailure(started)) { + if (started.failure._tag === "WorkflowInputError") { + return json( + 400, + { error: "invalid_request", problem: started.failure.problem }, + "invalid", + ); + } + yield* Effect.logWarning("Workflow hook delivery failed", { hookId: params.hookId }); + return json(500, { error: "internal_error" }, "error"); + } + return Option.isNone(started.success) + ? json(404, { error: "hook_not_found" }, "not_found") + : json(202, { runId: started.success.value.runId }, "accepted"); + } const result = yield* scheduledTasks .triggerWebhook({ hookId: params.hookId, diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 8e0a2ea2f655f..68f32f4ecf0a9 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -227,6 +227,7 @@ import * as UsageService from "./usage/UsageService.ts"; import * as CodexUsageHistory from "./usage/CodexUsageHistory.ts"; import * as RuntimeLayer from "./orchestration-v2/runtimeLayer.ts"; import * as ThreadViewers from "./orchestration-v2/ThreadViewers.ts"; +import * as WorkflowForge from "./workflows/WorkflowForge.ts"; import * as ProjectStore from "./orchestration-v2/ProjectStore.ts"; import * as ThreadSearch from "./orchestration-v2/ThreadSearch.ts"; import * as ThreadSettlementService from "./orchestration-v2/ThreadSettlementService.ts"; @@ -638,6 +639,13 @@ const layerTaskFolders = TaskFolders.layer.pipe( ); const layerOrchestrationV2Runtime = RuntimeLayer.layerProduction.pipe( + Layer.provide( + WorkflowForge.layer.pipe( + Layer.provide(layerIssueService), + Layer.provide(layerPullRequestService), + Layer.provide(RuntimeLayer.layerProjectService), + ), + ), Layer.provide(UsageLimitSources.layerResetFallback), Layer.provide(layerTaskFolders), Layer.provide(layerScheduledTaskWebhookOrigin), @@ -766,9 +774,9 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll( ReplayMarkers.layer, Layer.effectDiscard(ProjectSettingsOverrideSweep.sweep), ).pipe( - // One hub, which the feeders above publish to and future consumers read. - Layer.provideMerge(MilestoneHub.layer), Layer.provideMerge(layerOrchestrationApplication), + // One hub, which the feeders above and the workflow store inside the runtime publish to. + Layer.provideMerge(MilestoneHub.layer), Layer.provideMerge(layerTaskFolders), Layer.provideMerge(RuntimeLayer.layerEventInfrastructure), Layer.provideMerge(Layer.merge(ProjectStore.layer, ThreadSearch.layer)), diff --git a/apps/server/src/workflows/WorkflowAgentLinks.test.ts b/apps/server/src/workflows/WorkflowAgentLinks.test.ts new file mode 100644 index 0000000000000..92b7a4f7b2fff --- /dev/null +++ b/apps/server/src/workflows/WorkflowAgentLinks.test.ts @@ -0,0 +1,292 @@ +import { EnvironmentId, OrchestratorMcpFailure } from "@t3tools/contracts"; +import { assert, it } from "@effect/vitest"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import * as TestClock from "effect/testing/TestClock"; + +import * as PeerLinks from "../peer/PeerLinks.ts"; +import * as PeerMcpClient from "../peer/PeerMcpClient.ts"; +import * as WorkflowAgentLinks from "./WorkflowAgentLinks.ts"; + +const isFailure = Schema.is(OrchestratorMcpFailure); + +interface Call { + readonly environmentId: string; + readonly tool: string; + readonly arguments: Record; + readonly runtimeMode: string; +} + +/** The other environment, played by the test: each tool answers from a list, in order. */ +const peer = (answers: Record>, enabled = true) => { + const calls: Array = []; + const left = new Map(Object.entries(answers).map(([tool, list]) => [tool, [...list]])); + const layer = Layer.merge( + Layer.succeed( + PeerMcpClient.PeerMcpClient, + PeerMcpClient.PeerMcpClient.of({ + call: (input) => + Effect.suspend(() => { + calls.push({ + environmentId: input.environmentId, + tool: input.tool, + arguments: input.arguments, + runtimeMode: input.limits.runtimeMode, + }); + const answer = left.get(input.tool)?.shift(); + return isFailure(answer) ? Effect.fail(answer) : Effect.succeed(answer as never); + }), + }), + ), + Layer.mock(PeerLinks.PeerLinks)({ enabled: Effect.succeed(enabled) }), + ); + return { calls, layer }; +}; + +const input = { + key: "run-1/write/0", + origin: { runId: "run-1", workflow: "fix", step: "write" }, + title: "fix: write", + prompt: "Write the fix.", + outputSchema: { type: "object" }, + model: undefined, + project: "/work/app", + environment: "env-b", + thread: undefined, +}; +const run = (status: string) => ({ recentRuns: [{ runId: "turn-1", status }], items: [] }); +const waited = { threadId: "thread-1", runId: "turn-1", status: "idle" }; + +it.effect("starts a thread there by the project's folder, with the step's key as the request", () => + Effect.gen(function* () { + const there = peer({ + t3_project_list: [ + { projects: [{ id: "p-other", workspaceRoot: "/work/other" }], nextCursor: 1 }, + { projects: [{ id: "p-app", workspaceRoot: "/work/app" }], nextCursor: null }, + ], + t3_thread_launch: [{ threadId: "thread-1", runId: "turn-1" }], + }); + const options = { + workspace: { type: "worktree", baseRef: "origin/main", startFromOrigin: true }, + runtimeMode: "auto-accept-edits", + } as const; + const [turn, continued] = yield* Effect.provide( + Effect.flatMap(WorkflowAgentLinks.make, (links) => + Effect.all([ + links.start( + { ...input, launch: options }, + "env-b", + "workflow:k", + EnvironmentId.make("env-a"), + ), + // A thread keeps how it started. + links + .start( + { ...input, thread: "thread-1", launch: options }, + "env-b", + "workflow:c", + EnvironmentId.make("env-a"), + ) + .pipe(Effect.flip), + ]), + ), + there.layer, + ); + assert.deepStrictEqual(turn, { threadId: "thread-1", turnId: "turn-1", environment: "env-b" }); + assert.include(continued.reason, "A continued `thread` keeps how it started"); + const launch = there.calls.at(-1); + assert.deepStrictEqual(launch?.arguments, { + projectId: "p-app", + title: "fix: write", + runtimeMode: "auto-accept-edits", + workspaceStrategy: { type: "worktree", baseRef: "origin/main", startFromOrigin: true }, + message: "Write the fix.", + outputSchema: { type: "object" }, + clientRequestId: "workflow:k", + workflowRun: { environmentId: "env-a", runId: "run-1", workflow: "fix", step: "write" }, + }); + // The link's own access is the ceiling, not a mode narrower than it. + assert.equal(launch?.runtimeMode, "full-access"); + }), +); + +it.effect("registers a folder that is not a project there yet", () => + Effect.gen(function* () { + const there = peer({ + t3_project_list: [{ projects: [], nextCursor: null }], + t3_project_create: [{ id: "p-new", workspaceRoot: "/work/app" }], + t3_thread_launch: [{ threadId: "thread-1", runId: "turn-1" }], + }); + yield* Effect.provide( + Effect.flatMap(WorkflowAgentLinks.make, (links) => + links.start(input, "env-b", "workflow:k", EnvironmentId.make("env-a")), + ), + there.layer, + ); + assert.deepStrictEqual( + there.calls.map((call) => [call.tool, call.arguments.projectId ?? call.arguments.title]), + [ + ["t3_project_list", undefined], + ["t3_project_create", "app"], + ["t3_thread_launch", "p-new"], + ], + ); + }), +); + +it.effect("does not start anything while linked environments is off", () => + Effect.gen(function* () { + const there = peer({}, false); + const error = yield* Effect.provide( + Effect.flatMap(WorkflowAgentLinks.make, (links) => + links.start(input, "env-b", "workflow:k", EnvironmentId.make("env-a")), + ), + there.layer, + ).pipe(Effect.flip); + assert.match(error.reason, /Linked environments is off/); + assert.deepStrictEqual(there.calls, []); + }), +); + +it.effect("waits in pieces, rides out a dropped route, and returns the output and reply", () => + Effect.gen(function* () { + const there = peer({ + t3_thread_wait: [ + { ...waited, timedOut: true }, + new OrchestratorMcpFailure({ code: "orchestration_error", message: "unreachable" }), + { ...waited, timedOut: false, output: { branch: "fix/1" } }, + ], + t3_thread_read: [ + run("completed"), + { + recentRuns: [], + hasMore: false, + nextPosition: null, + items: [ + { type: "assistant_message", runId: "turn-0", text: "earlier", textTruncated: false }, + { + type: "assistant_message", + runId: "turn-1", + itemId: "item-9", + text: "Done, ", + textTruncated: true, + nextTextOffset: 6, + }, + ], + }, + { recentRuns: [], items: [{ text: "pushed.", textTruncated: false }] }, + ], + }); + const result = yield* Effect.provide( + Effect.flatMap(WorkflowAgentLinks.make, (links) => + links.result({ threadId: "thread-1", turnId: "turn-1" }, "env-b"), + ), + there.layer, + ).pipe(Effect.raceFirst(Effect.forever(TestClock.adjust("1 second")))); + assert.deepStrictEqual(result, { + ending: "completed", + detail: "", + reply: "Done, pushed.", + output: { branch: "fix/1" }, + }); + assert.equal(there.calls.filter((call) => call.tool === "t3_thread_wait").length, 3); + }), +); + +it.effect("a turn someone stopped there is stopped, and a refused link fails at once", () => + Effect.gen(function* () { + const stopped = peer({ + t3_thread_wait: [{ ...waited, timedOut: false }], + t3_thread_read: [run("interrupted")], + t3_thread_interrupt: [{ threadId: "thread-1", runId: "turn-1", status: "interrupted" }], + }); + const result = yield* Effect.provide( + Effect.flatMap(WorkflowAgentLinks.make, (links) => + links.result({ threadId: "thread-1", turnId: "turn-1" }, "env-b"), + ), + stopped.layer, + ); + assert.deepStrictEqual(result, { ending: "stopped", detail: "interrupted", reply: "" }); + // Stopping names the step's turn, so a person's turn on that thread keeps going. + yield* Effect.provide( + Effect.flatMap(WorkflowAgentLinks.make, (links) => + links.interrupt("thread-1", "env-b", "turn-1"), + ), + stopped.layer, + ); + assert.deepInclude(stopped.calls.at(-1)?.arguments, { threadId: "thread-1", runId: "turn-1" }); + + const revoked = peer({ + t3_thread_wait: [ + new OrchestratorMcpFailure({ code: "capability_denied", message: "link revoked" }), + ], + }); + const error = yield* Effect.provide( + Effect.flatMap(WorkflowAgentLinks.make, (links) => + links.result({ threadId: "thread-1", turnId: "turn-1" }, "env-b"), + ), + revoked.layer, + ).pipe(Effect.flip); + assert.match(error.reason, /link revoked/); + assert.equal(revoked.calls.length, 1); + }), +); + +it.effect("a turn that ended without its result is waited past until a later turn gives it", () => + Effect.gen(function* () { + const there = peer({ + t3_thread_wait: [ + // The turn ended. The agent is waiting to be woken, and has submitted nothing. + { ...waited, timedOut: false }, + // Quiet for five minutes, in pieces. A turn that woke in between is under way... + ...Array.from({ length: 6 }, () => ({ ...waited, timedOut: true })), + // ...so the wait starts over, and that turn submits. + { ...waited, timedOut: false, output: { head: "abc" } }, + ], + t3_thread_read: [ + run("completed"), + { recentRuns: [{ runId: "turn-2", status: "running" }], items: [] }, + { recentRuns: [], hasMore: false, nextPosition: null, items: [] }, + ], + }); + const result = yield* Effect.provide( + Effect.flatMap(WorkflowAgentLinks.make, (links) => + links.result({ threadId: "thread-1", turnId: "turn-1" }, "env-b", { + quiet: Duration.minutes(5), + }), + ), + there.layer, + ).pipe(Effect.raceFirst(Effect.forever(TestClock.adjust("1 second")))); + assert.deepStrictEqual(result.output, { head: "abc" }); + const waits = there.calls.filter((call) => call.tool === "t3_thread_wait"); + assert.isTrue(waits.slice(1).every((call) => call.arguments.untilOutput === true)); + }), +); + +it.effect("a thread that stays quiet gives the turn back without a result", () => + Effect.gen(function* () { + const there = peer({ + t3_thread_wait: [ + { ...waited, timedOut: false }, + ...Array.from({ length: 6 }, () => ({ ...waited, timedOut: true })), + ], + t3_thread_read: [ + run("completed"), + // Nothing has run since the turn the step knows. + run("completed"), + { recentRuns: [], hasMore: false, nextPosition: null, items: [] }, + ], + }); + const result = yield* Effect.provide( + Effect.flatMap(WorkflowAgentLinks.make, (links) => + links.result({ threadId: "thread-1", turnId: "turn-1" }, "env-b", { + quiet: Duration.minutes(5), + }), + ), + there.layer, + ).pipe(Effect.raceFirst(Effect.forever(TestClock.adjust("1 second")))); + assert.deepStrictEqual(result, { ending: "completed", detail: "", reply: "" }); + }), +); diff --git a/apps/server/src/workflows/WorkflowAgentLinks.ts b/apps/server/src/workflows/WorkflowAgentLinks.ts new file mode 100644 index 0000000000000..6a0836fc0162c --- /dev/null +++ b/apps/server/src/workflows/WorkflowAgentLinks.ts @@ -0,0 +1,313 @@ +// Agent steps in a linked environment: the same three operations, as that environment's T3 tools. +import { + type EnvironmentId, + OrchestratorMcpFailure, + OrchestratorMcpThreadInterruptResult, + OrchestratorMcpThreadReadResult, + OrchestratorMcpThreadSendResult, + OrchestratorMcpThreadWaitResult, +} from "@t3tools/contracts"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Result from "effect/Result"; +import * as Schedule from "effect/Schedule"; +import type * as Schema from "effect/Schema"; + +import { ProjectToolkit } from "../mcp/toolkits/project/tools.ts"; +import * as PeerLinks from "../peer/PeerLinks.ts"; +import * as PeerMcpClient from "../peer/PeerMcpClient.ts"; +import { + type AgentResult, + type AgentTurn, + isProjectPath, + launchOnContinue, + WorkflowAgentError, + type WorkflowAgents, +} from "./WorkflowAgents.ts"; + +// A run acts for whoever owns this environment, not for an agent with modes of its own, so the +// only ceiling on what it starts there is the access the link was paired with. +const LIMITS = { runtimeMode: "full-access", interactionMode: "default" } as const; + +// T3 Connect's edge drops a request that is idle for about 100 s, so a wait goes out in pieces. +const WAIT_PIECE = Duration.seconds(50); + +/** The link is gone or the thread is: asking again cannot help. */ +const isFinal = (error: OrchestratorMcpFailure) => + error.code === "capability_denied" || + error.code === "thread_not_found" || + error.code === "run_not_found" || + error.code === "invalid_request"; + +// The other machine asleep or a dropped route is worth a few more tries before the run pauses. +const retried = { schedule: Schedule.exponential("2 seconds"), times: 5 }; + +type Service = WorkflowAgents["Service"]; + +export const make = Effect.gen(function* () { + const peers = yield* PeerMcpClient.PeerMcpClient; + const links = yield* PeerLinks.PeerLinks; + + const call = >( + environment: string, + tool: string, + success: S, + args: Record, + ) => + peers + .call({ + environmentId: environment as EnvironmentId, + tool, + arguments: args, + limits: LIMITS, + success, + }) + .pipe( + Effect.retry({ ...retried, while: (error) => !isFinal(error) }), + Effect.mapError( + (error) => + new WorkflowAgentError({ + reason: `Environment ${environment} refused ${tool}: ${error.message}`, + }), + ), + ); + + const listed = Effect.fn("WorkflowAgentLinks.listed")(function* ( + environment: string, + path: string, + ) { + let cursor: number | null = 0; + while (cursor !== null) { + const page: Schema.Schema.Type = + yield* call( + environment, + "t3_project_list", + ProjectToolkit.tools.t3_project_list.successSchema, + { cursor, limit: 100 }, + ); + const found = page.projects.find((project) => project.workspaceRoot === path); + if (found !== undefined) return found.id; + cursor = page.nextCursor; + } + return undefined; + }); + + /** + * The project at a folder there. A machine made for one run has the folder and no project yet, + * so a folder that is not one is registered. Two steps may do that at once; the one that is + * refused finds the other's. + */ + const projectAt = Effect.fn("WorkflowAgentLinks.projectAt")(function* ( + environment: string, + path: string, + ) { + const known = yield* listed(environment, path); + if (known !== undefined) return known; + const title = path.split("/").findLast((part) => part.length > 0) ?? path; + const created = yield* call( + environment, + "t3_project_create", + ProjectToolkit.tools.t3_project_create.successSchema, + { title, workspaceRoot: path }, + ).pipe(Effect.result); + if (Result.isSuccess(created)) return created.success.id; + return (yield* listed(environment, path)) ?? (yield* created.failure); + }); + + /** The whole text of the run's last assistant message. */ + const reply = Effect.fn("WorkflowAgentLinks.reply")(function* ( + turn: AgentTurn, + environment: string, + ) { + let last: OrchestratorMcpThreadReadResult["items"][number] | undefined; + let afterPosition: number | undefined; + while (true) { + const read = yield* call(environment, "t3_thread_read", OrchestratorMcpThreadReadResult, { + threadId: turn.threadId, + view: "messages", + limit: 100, + ...(afterPosition === undefined ? {} : { afterPosition }), + }); + last = + read.items.findLast( + (item) => item.type === "assistant_message" && item.runId === turn.turnId, + ) ?? last; + if (!read.hasMore || read.nextPosition === null) break; + afterPosition = read.nextPosition; + } + if (last === undefined) return ""; + let text = last.text ?? ""; + let textOffset = last.textTruncated ? (last.nextTextOffset ?? null) : null; + while (textOffset !== null) { + const rest = yield* call(environment, "t3_thread_read", OrchestratorMcpThreadReadResult, { + threadId: turn.threadId, + itemId: last.itemId, + textOffset, + maxCharsPerItem: 50_000, + }); + const part = rest.items[0]; + if (part === undefined) break; + text += part.text ?? ""; + textOffset = part.textTruncated ? (part.nextTextOffset ?? null) : null; + } + return text; + }); + + const start = Effect.fn("WorkflowAgentLinks.start")(function* ( + input: Parameters[0], + environment: string, + requestId: string, + here: EnvironmentId, + ) { + if (!(yield* links.enabled)) { + return yield* new WorkflowAgentError({ + reason: + "Linked environments is off on this machine, so an agent step cannot run in another one. Turn it on in Settings → Labs.", + }); + } + const outputSchema = + input.outputSchema === undefined ? {} : { outputSchema: input.outputSchema }; + if (input.thread !== undefined) { + if (input.launch !== undefined) return yield* launchOnContinue; + const sent = yield* call(environment, "t3_thread_send", OrchestratorMcpThreadSendResult, { + threadId: input.thread, + message: input.prompt, + mode: "queue", + ...outputSchema, + clientRequestId: requestId, + }); + return { threadId: sent.threadId, turnId: sent.runId, environment }; + } + if (input.project === undefined) { + return yield* new WorkflowAgentError({ + reason: "An agent step needs a `project` to start in, or a `thread` to continue.", + }); + } + const projectId = isProjectPath(input.project) + ? yield* projectAt(environment, input.project) + : input.project; + const launched = yield* call( + environment, + "t3_thread_launch", + ProjectToolkit.tools.t3_thread_launch.successSchema, + { + projectId, + title: input.title, + ...(input.model === undefined ? {} : { modelSelection: input.model }), + ...(input.launch?.runtimeMode === undefined + ? {} + : { runtimeMode: input.launch.runtimeMode }), + ...(input.launch?.interactionMode === undefined + ? {} + : { interactionMode: input.launch.interactionMode }), + ...(input.launch?.workspace === undefined + ? {} + : { workspaceStrategy: input.launch.workspace }), + message: input.prompt, + ...outputSchema, + clientRequestId: requestId, + // The thread there says which run it is a step of, and where that run lives. + workflowRun: { environmentId: here, ...input.origin }, + }, + ); + if (launched.runId === null) { + return yield* new WorkflowAgentError({ + reason: `Thread ${launched.threadId} in ${environment} started without a turn for its first message.`, + }); + } + return { threadId: launched.threadId, turnId: launched.runId, environment }; + }); + + const result = Effect.fn("WorkflowAgentLinks.result")(function* ( + turn: AgentTurn, + environment: string, + options?: { readonly quiet?: Duration.Duration | undefined }, + ): Effect.fn.Return { + const ended = new Set(["completed", "failed", "interrupted", "cancelled", "rolled_back"]); + /** The result a later turn submits, or nothing once the thread has been quiet. */ + const owed = Effect.fn("WorkflowAgentLinks.owed")(function* (quiet: Duration.Duration) { + let left = Duration.toMillis(quiet); + // The newest turn already seen to end without the result, so quiet is not restarted by it. + let counted = turn.turnId; + while (true) { + const piece = Math.min(left, Duration.toMillis(WAIT_PIECE)); + const waited = yield* call(environment, "t3_thread_wait", OrchestratorMcpThreadWaitResult, { + threadId: turn.threadId, + runId: turn.turnId, + untilOutput: true, + timeoutMs: piece, + }); + if (waited.output !== undefined) return Option.some(waited.output); + // An environment that does not know `untilOutput` answers at once: nothing to wait on. + if (!waited.timedOut) return Option.none(); + left -= piece; + if (left > 0) continue; + const read = yield* call(environment, "t3_thread_read", OrchestratorMcpThreadReadResult, { + threadId: turn.threadId, + limit: 1, + runLimit: 1, + }); + const latest = read.recentRuns[0]; + if (latest === undefined || latest.runId === counted) return Option.none(); + // Quiet is counted from the thread's last turn: one under way, or one not yet counted. + if (ended.has(latest.status)) counted = latest.runId; + left = Duration.toMillis(quiet); + } + }); + while (true) { + const waited = yield* call(environment, "t3_thread_wait", OrchestratorMcpThreadWaitResult, { + threadId: turn.threadId, + runId: turn.turnId, + timeoutMs: Duration.toMillis(WAIT_PIECE), + }); + if (waited.timedOut) continue; + const read = yield* call(environment, "t3_thread_read", OrchestratorMcpThreadReadResult, { + threadId: turn.threadId, + limit: 1, + runLimit: 50, + }); + const status = read.recentRuns.find((run) => run.runId === turn.turnId)?.status; + if (status === undefined) { + return yield* new WorkflowAgentError({ + reason: `Thread ${turn.threadId} in ${environment} no longer lists turn ${turn.turnId}.`, + }); + } + if (status === "completed") { + const output = + waited.output !== undefined || options?.quiet === undefined + ? Option.fromUndefinedOr(waited.output) + : yield* owed(options.quiet); + return { + ending: "completed", + detail: "", + reply: yield* reply(turn, environment), + ...(Option.isNone(output) ? {} : { output: output.value }), + }; + } + if ( + status === "failed" || + status === "interrupted" || + status === "cancelled" || + status === "rolled_back" + ) { + return { ending: status === "failed" ? "failed" : "stopped", detail: status, reply: "" }; + } + // The wait answered for a turn that has not ended. Asking again at once would spin. + yield* Effect.sleep("5 seconds"); + } + }); + + const interrupt = (threadId: string, environment: string, runId?: string) => + Effect.map( + call(environment, "t3_thread_interrupt", OrchestratorMcpThreadInterruptResult, { + threadId, + ...(runId === undefined ? {} : { runId }), + reason: "Its workflow run was cancelled", + }), + (stopped): "stopped" | "ended" => + stopped.status === "interrupt_requested" ? "stopped" : "ended", + ); + + return { start, result, interrupt }; +}); diff --git a/apps/server/src/workflows/WorkflowAgentThreads.ts b/apps/server/src/workflows/WorkflowAgentThreads.ts new file mode 100644 index 0000000000000..ce4a7510b88c0 --- /dev/null +++ b/apps/server/src/workflows/WorkflowAgentThreads.ts @@ -0,0 +1,335 @@ +// Agent steps as threads: a step's turn is an ordinary thread turn that was asked for a result. +import { + CommandId, + MessageId, + type ModelSelection, + ProjectId, + ProviderInstanceId, + type RunId, + ThreadId, +} from "@t3tools/contracts"; +import { subagentResultForRun } from "@t3tools/provider-core/server/subagentProjection"; +import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; +import { resolveNewThreadModelSelection } from "@t3tools/shared/usageLimits"; +import * as Digest from "effect/crypto/Digest"; +import * as Clock from "effect/Clock"; +import * as DateTime from "effect/DateTime"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Hex from "effect/encoding/Hex"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; + +import * as ThreadIssueService from "../orchestration-v2/ThreadIssueService.ts"; +import * as ThreadLaunch from "../orchestration-v2/ThreadLaunchService.ts"; +import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts"; +import * as ProjectService from "../project/ProjectService.ts"; +import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import * as WorkflowAgentLinks from "./WorkflowAgentLinks.ts"; +import { + isProjectPath, + launchOnContinue, + WorkflowAgentError, + WorkflowAgents, +} from "./WorkflowAgents.ts"; +import { noteReference } from "./runReferences.ts"; +import { type IssueAddress, linkedPullRequestReferences, WorkflowForge } from "./WorkflowForge.ts"; + +// A turn can run for hours. Each look is bounded so a wait that lost its event is asked again. +const WAIT_SLICE = Duration.minutes(10); + +const failed = (reason: string) => (cause: unknown) => + new WorkflowAgentError({ + reason: `${reason}: ${cause instanceof Error ? cause.message : String(cause)}`, + }); + +const make = Effect.gen(function* () { + const threads = yield* ThreadManagement.ThreadManagementService; + const launches = yield* ThreadLaunch.ThreadLaunchService; + const projects = yield* ProjectService.ProjectService; + const providers = yield* ProviderRegistry.ProviderRegistry; + const settings = yield* ServerSettings.ServerSettingsService; + const digest = yield* Digest.Digest; + const linked = yield* WorkflowAgentLinks.make; + const forge = yield* WorkflowForge; + const threadIssues = yield* ThreadIssueService.ThreadIssueService; + // A tracker that is down must not cost the step its agent. + const showIssue = (issue: IssueAddress | undefined, threadId: string) => + issue === undefined + ? Effect.void + : forge.issues.read(issue).pipe( + Effect.flatMap((detail) => + threadIssues.link({ + threadId: ThreadId.make(threadId), + ref: { + projectId: detail.projectId, + tracker: detail.tracker, + host: detail.host, + scope: detail.scope, + key: detail.key, + }, + url: detail.url, + displayKey: detail.displayKey, + title: detail.title, + source: "agent", + }), + ), + Effect.catch((error) => + Effect.logWarning("Could not link a workflow agent's thread to its issue", { + threadId, + reason: error.message, + }), + ), + ); + // What the agent opened or linked while it worked is part of what its step touched. + const noteLinked = (threadId: ThreadId, sinceMillis: number | undefined) => + threads.getThreadShell(threadId).pipe( + Effect.flatMap((shell) => + shell === null + ? Effect.void + : Effect.forEach(linkedPullRequestReferences(shell, sinceMillis), noteReference, { + discard: true, + }), + ), + Effect.ignore, + ); + const here = yield* ServerEnvironment.ServerEnvironment.pipe( + Effect.flatMap((environment) => environment.getEnvironmentId), + ); + /** The linked environment a step names, or nothing when it names this one. */ + const elsewhere = (environment: string | undefined) => + environment === here ? undefined : environment; + + // Thread, message and command ids all derive from the step's key, so a start that is asked for + // again after a crash finds the turn it already started. + const idOf = Effect.fn("WorkflowAgentThreads.idOf")(function* (key: string) { + const hash = yield* digest + .digest(Digest.sha256, new TextEncoder().encode(key)) + .pipe(Effect.mapError(failed("Could not derive the turn's id"))); + return `workflow:${Hex.encode(hash)}`; + }); + + const projectDefaults = Effect.fn("WorkflowAgentThreads.projectDefaults")(function* ( + projectId: ProjectId, + ) { + const project = yield* projects + .getById(projectId) + .pipe(Effect.mapError(failed("Could not read the project"))); + if (Option.isNone(project)) { + return yield* new WorkflowAgentError({ reason: `Project ${projectId} was not found.` }); + } + const current = yield* settings.getSettings.pipe( + Effect.mapError(failed("Could not read settings")), + ); + return resolveProjectSettings(current, projectId, project.value).settings; + }); + + const projectIdOf = Effect.fn("WorkflowAgentThreads.projectIdOf")(function* (project: string) { + if (!isProjectPath(project)) return ProjectId.make(project); + const found = yield* projects + .getByWorkspaceRoot(project) + .pipe(Effect.mapError(failed("Could not read the project"))); + if (Option.isNone(found)) { + return yield* new WorkflowAgentError({ + reason: `No project is registered at ${project}.`, + }); + } + return found.value.id; + }); + + return WorkflowAgents.of({ + start: Effect.fn("WorkflowAgentThreads.start")(function* (input) { + const id = yield* idOf(input.key); + const environment = elsewhere(input.environment); + if (environment !== undefined) return yield* linked.start(input, environment, id, here); + const commandId = CommandId.make(id); + const messageId = MessageId.make(id); + const outputSchema = + input.outputSchema === undefined ? {} : { outputSchema: input.outputSchema }; + + if (input.thread !== undefined) { + if (input.launch !== undefined) return yield* launchOnContinue; + const threadId = ThreadId.make(input.thread); + const shell = yield* threads + .getThreadShell(threadId) + .pipe(Effect.mapError(failed("Could not read the thread to continue"))); + if (shell === null || shell.deletedAt !== null) { + return yield* new WorkflowAgentError({ + reason: `Thread ${input.thread} no longer exists, so it cannot be continued.`, + }); + } + const sent = yield* threads + .sendToThread({ + projectId: shell.projectId, + commandId, + threadId, + messageId, + text: input.prompt, + attachments: [], + mode: "queue", + ...outputSchema, + createdBy: "system", + creationSource: "server", + }) + .pipe(Effect.mapError(failed("Could not send to the thread"))); + yield* showIssue(input.issue, threadId); + return { threadId, turnId: sent.run.id }; + } + + if (input.project === undefined) { + return yield* new WorkflowAgentError({ + reason: "An agent step needs a `project` to start in, or a `thread` to continue.", + }); + } + const projectId = yield* projectIdOf(input.project); + const defaults = yield* projectDefaults(projectId); + const modelSelection: ModelSelection | undefined = + input.model === undefined + ? (resolveNewThreadModelSelection({ + defaultSelection: defaults.defaultModelSelection, + fallbackSelection: defaults.fallbackModelSelection, + providers: yield* providers.getProviders, + settings: defaults, + projectId, + now: DateTime.toEpochMillis(yield* DateTime.now), + }).selection ?? undefined) + : { + instanceId: ProviderInstanceId.make(input.model.instanceId), + model: input.model.model, + ...(input.model.options === undefined ? {} : { options: input.model.options }), + }; + if (modelSelection === undefined) { + return yield* new WorkflowAgentError({ + reason: `Project ${input.project} has no default model. Give the agent step a \`model\`.`, + }); + } + const launched = yield* launches + .launch({ + commandId, + threadId: ThreadId.make(id), + projectId, + title: input.title, + modelSelection, + runtimeMode: input.launch?.runtimeMode ?? defaults.defaultRuntimeMode, + interactionMode: input.launch?.interactionMode ?? "default", + workspaceStrategy: input.launch?.workspace ?? { type: "root" }, + initialMessage: { messageId, text: input.prompt, attachments: [], ...outputSchema }, + createdBy: "system", + creationSource: "server", + workflowRun: { environmentId: here, ...input.origin }, + }) + .pipe(Effect.mapError(failed("Could not start the thread"))); + const run = launched.projection.runs.find( + (candidate) => candidate.userMessageId === messageId, + ); + if (run === undefined) { + return yield* new WorkflowAgentError({ + reason: `Thread ${launched.threadId} started without a turn for its first message.`, + }); + } + yield* showIssue(input.issue, launched.threadId); + return { threadId: launched.threadId, turnId: run.id }; + }), + result: Effect.fn("WorkflowAgentThreads.result")(function* (turn, options) { + const environment = elsewhere(turn.environment); + if (environment !== undefined) return yield* linked.result(turn, environment, options); + const threadId = ThreadId.make(turn.threadId); + const shell = yield* threads + .getThreadShell(threadId) + .pipe(Effect.mapError(failed("Could not read the thread"))); + if (shell === null) { + return yield* new WorkflowAgentError({ + reason: `Thread ${turn.threadId} no longer exists.`, + }); + } + // The newest turn already seen to end without the result, so quiet is not restarted by it. + let quietSince = -1; + while (true) { + const waited = yield* threads + .waitForThread({ + projectId: shell.projectId, + threadId, + runId: turn.turnId as RunId, + timeoutMs: Duration.toMillis(WAIT_SLICE), + }) + .pipe(Effect.mapError(failed("Could not wait for the turn"))); + let run = waited.run; + if (waited.timedOut || run === null) continue; + // The agent may have ended its turn to wait for something that will wake it. + const quiet = options?.quiet; + const owes = (candidate: NonNullable) => + candidate.status === "completed" && + candidate.outputSchema !== undefined && + candidate.output === undefined; + while (owes(run)) { + if (quiet === undefined) break; + const owed: ThreadManagement.ThreadManagementWaitResult = yield* threads + .waitForThread({ + projectId: shell.projectId, + threadId, + runId: run.id, + untilOutput: true, + timeoutMs: Duration.toMillis(quiet), + }) + .pipe(Effect.mapError(failed("Could not wait for the turn's result"))); + if (owed.run === null) break; + run = owed.run; + if (!owed.timedOut) continue; + // Quiet is counted from the thread's last turn, so one under way is waited out first. + const latest = yield* threads + .waitForThread({ + projectId: shell.projectId, + threadId, + timeoutMs: Duration.toMillis(WAIT_SLICE), + }) + .pipe(Effect.mapError(failed("Could not wait for the thread"))); + if (latest.run === null || latest.run.id === run.id) break; + if (!latest.timedOut && latest.run.ordinal <= quietSince) break; + quietSince = latest.timedOut ? quietSince : latest.run.ordinal; + } + yield* noteLinked(threadId, turn.startedAt); + if (run.status !== "completed") { + // Interrupted or cancelled is someone stopping it; the rest is the turn dying. + const ending = run.status === "failed" ? ("failed" as const) : ("stopped" as const); + return { ending, detail: run.status, reply: "" }; + } + const records = yield* threads + .getThreadRecords(threadId, ["messages", "turnItems", "providerTurns"]) + .pipe(Effect.mapError(failed("Could not read the turn's reply"))); + return { + ending: "completed" as const, + detail: "", + reply: subagentResultForRun(records, run).text, + ...(run.output === undefined ? {} : { output: run.output.value }), + }; + } + }), + interrupt: Effect.fn("WorkflowAgentThreads.interrupt")(function* (target) { + const environment = elsewhere(target.environment); + if (environment !== undefined) + return yield* linked.interrupt(target.threadId, environment, target.turnId); + const thread = target.threadId; + const threadId = ThreadId.make(thread); + const shell = yield* threads + .getThreadShell(threadId) + .pipe(Effect.mapError(failed("Could not read the thread"))); + if (shell === null) return "ended" as const; + const stopped = yield* threads + .interruptThread({ + projectId: shell.projectId, + threadId, + commandId: CommandId.make( + `workflow:interrupt:${thread}:${target.turnId ?? ""}:${yield* Clock.currentTimeMillis}`, + ), + reason: "Its workflow run was cancelled", + ...(target.turnId === undefined ? {} : { runId: target.turnId as RunId }), + }) + .pipe(Effect.mapError(failed("Could not stop the thread"))); + return stopped.type === "interrupt_requested" ? ("stopped" as const) : ("ended" as const); + }), + }); +}); + +export const layer = Layer.effect(WorkflowAgents, make); diff --git a/apps/server/src/workflows/WorkflowAgents.ts b/apps/server/src/workflows/WorkflowAgents.ts new file mode 100644 index 0000000000000..674b72c69aa3d --- /dev/null +++ b/apps/server/src/workflows/WorkflowAgents.ts @@ -0,0 +1,117 @@ +import type { + ModelSelection, + OrchestrationV2ThreadLaunchWorkspaceStrategy, + ProviderInteractionMode, + RuntimeMode, +} from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import type * as Duration from "effect/Duration"; +import type * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import type { IssueAddress } from "./WorkflowForge.ts"; + +export class WorkflowAgentError extends Schema.TaggedError()( + "WorkflowAgentError", + { reason: Schema.String }, +) { + override get message(): string { + return this.reason; + } +} + +export interface AgentModel { + readonly instanceId: string; + readonly model: string; + /** The model's own options, such as reasoning effort, as `{ id, value }` pairs. */ + readonly options?: ModelSelection["options"]; +} + +/** How a new thread starts, as `t3_thread_launch` takes it. Unset fields follow the project. */ +export interface AgentLaunch { + /** Where its files are: the project's checkout by default, or a worktree of its own. */ + readonly workspace?: OrchestrationV2ThreadLaunchWorkspaceStrategy | undefined; + readonly runtimeMode?: RuntimeMode | undefined; + readonly interactionMode?: ProviderInteractionMode | undefined; +} + +export const AgentTurn = Schema.Struct({ + threadId: Schema.String, + turnId: Schema.String, + /** The linked environment the thread is in. Absent for this one. */ + environment: Schema.optional(Schema.String), + /** When the step's first turn started, which its time limit counts from. */ + startedAt: Schema.optional(Schema.Number), + /** Why no turn was started, for a step that takes that as an answer. The ids are then empty. */ + failed: Schema.optional(Schema.String), +}); +export type AgentTurn = typeof AgentTurn.Type; + +export const AgentResult = Schema.Struct({ + /** + * How the turn ended. `stopped` is someone ending it on purpose, which is not a reason to try + * again; `failed` is the turn dying underneath the agent. + */ + ending: Schema.Literals(["completed", "failed", "stopped"]), + detail: Schema.String, + reply: Schema.String, + /** What the agent submitted against the output schema, when it did. */ + output: Schema.optional(Schema.Json), +}); +export type AgentResult = typeof AgentResult.Type; + +/** What a continued thread says to options that only shape a new one. */ +export const launchOnContinue = new WorkflowAgentError({ + reason: + "`workspace`, `runtimeMode` and `interactionMode` shape a new thread. A continued `thread` keeps how it started.", +}); + +/** A project named by its folder instead of its id. */ +export const isProjectPath = (project: string) => project.startsWith("/"); + +/** Where agent steps run. The server implements it with threads; tests stand in for it. */ +export class WorkflowAgents extends Context.Service< + WorkflowAgents, + { + /** Start a turn. The same `key` is the same turn, however often it is asked for. */ + readonly start: (input: { + readonly key: string; + /** The run and step this turn is for, which a new thread is marked with. */ + readonly origin: { readonly runId: string; readonly workflow: string; readonly step: string }; + readonly title: string; + readonly prompt: string; + readonly outputSchema: Readonly> | undefined; + readonly model: AgentModel | undefined; + /** The project a new thread is made in: its id, or its folder. Not needed to continue `thread`. */ + readonly project: string | undefined; + /** The linked environment to run in. Absent for this one. */ + readonly environment: string | undefined; + /** Continue this thread instead of starting one. */ + readonly thread: string | undefined; + /** An issue the thread is about, which it is linked to. */ + readonly issue?: IssueAddress | undefined; + /** How a new thread starts. Refused with `thread`, which keeps how it started. */ + readonly launch?: AgentLaunch | undefined; + }) => Effect.Effect; + /** + * Wait for the turn to end and return what it produced. With `quiet`, a turn that ended + * without the output it owes is waited past: its agent may be waiting to be woken, and + * submits from a later turn. Only once the thread has done nothing for `quiet` is the turn + * returned without output. + */ + readonly result: ( + turn: AgentTurn, + options?: { readonly quiet?: Duration.Duration | undefined }, + ) => Effect.Effect; + /** + * Stop whatever the thread is doing, when its run is cancelled. `ended` when there was nothing + * to stop: the turn had already ended. + */ + readonly interrupt: (thread: { + readonly threadId: string; + readonly environment?: string | undefined; + /** The step's own turn. With it, a turn of someone else's on the same thread is left alone. */ + readonly turnId?: string | undefined; + }) => Effect.Effect<"stopped" | "ended", WorkflowAgentError>; + } +>()("t3/workflows/WorkflowAgents") {} diff --git a/apps/server/src/workflows/WorkflowEngine.ts b/apps/server/src/workflows/WorkflowEngine.ts new file mode 100644 index 0000000000000..77ff4cf0ada2e --- /dev/null +++ b/apps/server/src/workflows/WorkflowEngine.ts @@ -0,0 +1,1056 @@ +// The workflow service on Effect's workflow engine. Loaded only when workflows are enabled: the +// engine's modules are not worth their load time on a server that registers none. +import * as Cause from "effect/Cause"; +import { + ClusterWorkflowEngine, + EntityAddress, + EntityId, + EntityType, + MessageStorage, + Sharding, + SingleRunner, +} from "effect/cluster"; +import * as Digest from "effect/crypto/Digest"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as DateTime from "effect/DateTime"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as PubSub from "effect/PubSub"; +import * as Result from "effect/Result"; +import * as Schedule from "effect/Schedule"; +import * as Schema from "effect/Schema"; +import * as Scope from "effect/Scope"; +import * as SqlClient from "effect/sql/SqlClient"; +import * as Stream from "effect/Stream"; +import { DurableDeferred, WorkflowEngine } from "effect/workflow"; + +import { checkOutput, rejectionText } from "../orchestration-v2/runOutput.ts"; +import { isMissedFixedTimeRun, nextScheduledRunAt } from "../scheduledTasks/Schedule.ts"; +import { constantTimeEquals } from "../scheduledTasks/webhookVerification.ts"; +import { + END_STEP, + type EngineWorkflow, + engineTag, + engineWorkflow, + layerDefinition, + text, + wakeOf, + type Woke, + type WorkflowDefinition, +} from "./workflow.ts"; +import { issueReference, noteFor, stepReferences } from "./runReferences.ts"; +import { forStep, KeyValues, layerKeyValues, EngineLink, layerEngineLink } from "./stepServices.ts"; +import { WorkflowAgents } from "./WorkflowAgents.ts"; +import { + type Issue, + isSettled, + type PullRequest, + type PullRequestAddress, + type PullRequestWatch, + pullRequestReferenceOf, + standingOf, + unavailable, + WorkflowForge, +} from "./WorkflowForge.ts"; +import { + hookId as hookIdOf, + WorkflowInputError, + WorkflowNotRegisteredError, + WorkflowRunNotFoundError, + Workflows, +} from "./Workflows.ts"; +import * as WorkflowStore from "./WorkflowStore.ts"; + +const SWEEP_EVERY = Duration.seconds(15); +const LOOK_EVERY = Duration.minutes(1); +const LOOK_AT_MOST = 100; +const DEFAULT_SIGNAL_TTL = Duration.days(7); +const RESUME_LOOK_EVERY = Duration.millis(25); +const RESUME_LOOKS = 80; +const WATCH_SETTLE = Duration.millis(100); +const END_TRIES = 5; +// How long a cancelled run's cleanup rests after each failed try before the sweep tries again. +const END_AFTER = ["5 minutes", "20 minutes", "80 minutes", "5 hours"] as const; +// An ended run's engine journal only answers replays that will not come; the run's own rows stay. +const PRUNE_AFTER = Duration.hours(1); +const PRUNE_BATCH = 100; +// Delivery ids that common senders put on a request and keep when they send it again. +const DELIVERY_HEADERS = [ + "x-github-delivery", + "x-gitea-delivery", + "x-gitlab-event-uuid", + "linear-delivery", + "webhook-id", + "idempotency-key", +]; +const CANCEL_WAITS = Duration.seconds(30); +// Times of day are the server's own, as they are for scheduled tasks. +const localNow = DateTime.withCurrentZoneLocal(DateTime.nowInCurrentZone); + +const make = Effect.fn("WorkflowEngine.make")(function* ( + registered: ReadonlyArray, +) { + const store = yield* WorkflowStore.WorkflowStore; + const keyValues = yield* KeyValues; + const link = yield* EngineLink; + const trackers = Option.getOrElse(yield* Effect.serviceOption(WorkflowForge), () => unavailable); + const messages = yield* Effect.serviceOption(MessageStorage.MessageStorage); + const sharding = yield* Effect.serviceOption(Sharding.Sharding); + // The engine reads its own tables as BigInts. The rest of the server's queries must not. + const plain = + , A, E>(call: (...args: Args) => Effect.Effect) => + (...args: Args) => + call(...args).pipe(Effect.provideService(SqlClient.SafeIntegers, false)); + const forge = WorkflowForge.of({ + issues: { + list: plain(trackers.issues.list), + read: plain(trackers.issues.read), + comment: plain(trackers.issues.comment), + setState: plain(trackers.issues.setState), + create: plain(trackers.issues.create), + }, + pullRequests: { + list: plain(trackers.pullRequests.list), + read: plain(trackers.pullRequests.read), + comment: plain(trackers.pullRequests.comment), + act: plain(trackers.pullRequests.act), + }, + }); + const scope = yield* Scope.Scope; + const agents = yield* WorkflowAgents; + const stopTurn = plain(agents.interrupt); + const random = yield* SecureRandom.SecureRandom; + const digest = yield* Digest.Digest; + const context = yield* Effect.context(); + // The engine keeps 64-bit ids, which this SQLite client only reads when asked for BigInts. + const withEngine = (effect: Effect.Effect) => + effect.pipe( + Effect.provideContext(context), + Effect.provideService(SqlClient.SafeIntegers, true), + ); + const byTag = new Map(registered.map(([, engine]) => [engine._tag, engine] as const)); + const definitionByTag = new Map( + registered.map(([definition]) => [engineTag(definition), definition] as const), + ); + const latest = (name: string) => + registered + .filter(([definition]) => definition.name === name) + .toSorted(([left], [right]) => right.version - left.version)[0]; + + /** When the sweep resumes a paused run; undefined once it has used up its tries. */ + const resumesAt = (row: WorkflowStore.RunRow) => { + if (row.status !== "paused" || Number(row.held) === 1) return undefined; + const rest = definitionByTag.get(row.engine_tag)?.resumeAfter[Number(row.pauses) - 1]; + return rest === undefined + ? undefined + : DateTime.addDuration(DateTime.makeUnsafe(row.updated_at), Duration.fromInputUnsafe(rest)); + }; + const toRun = (row: WorkflowStore.RunRow): WorkflowStore.WorkflowRun => { + const resumes = resumesAt(row); + return toRunAt(row, resumes === undefined ? null : DateTime.formatIso(resumes)); + }; + const toRunAt = ( + row: WorkflowStore.RunRow, + resumes: string | null, + ): WorkflowStore.WorkflowRun => ({ + runId: row.run_id, + workflow: row.workflow, + version: Number(row.version), + title: row.title, + status: row.status, + detail: row.detail, + result: row.result_json === null ? null : WorkflowStore.jsonValue(row.result_json), + pauses: Number(row.pauses), + retired: row.ended_at === null && !byTag.has(row.engine_tag), + resumesAt: resumes, + parentRunId: row.parent_run_id, + parentStep: row.parent_wait, + startedAt: row.started_at, + updatedAt: row.updated_at, + endedAt: row.ended_at, + }); + const requireRun = Effect.fn("WorkflowEngine.requireRun")(function* (runId: string) { + const row = yield* store.run(runId); + if (row === undefined) return yield* new WorkflowRunNotFoundError({ runId }); + return row; + }); + const send = (wait: WorkflowStore.WaitRow, value: typeof Woke.Type) => + withEngine( + DurableDeferred.succeed(wakeOf(wait.name), { + token: wait.token as DurableDeferred.Token, + value, + }), + ); + // Runs being resumed now: until the engine has them, the sweep must not take them for paused. + const resuming = new Set(); + // The engine would replay a paused run for the wake and run its failed step again unasked. The + // claim keeps the value, and the resume sends it. + const wake = Effect.fnUntraced(function* (wait: WorkflowStore.WaitRow, value: typeof Woke.Type) { + if (resuming.has(wait.run_id) || (yield* store.run(wait.run_id))?.status === "paused") return; + yield* send(wait, value); + }); + + const start: Workflows["Service"]["start"] = Effect.fn("Workflows.start")( + function* (name, input, options) { + // A parent written against one version of a child must not get another one's payload. + const found = + options.version === undefined + ? latest(name) + : registered.find( + ([candidate]) => candidate.name === name && candidate.version === options.version, + ); + if (found === undefined) { + return yield* new WorkflowNotRegisteredError({ + workflow: name, + ...(options.version === undefined ? {} : { version: options.version }), + }); + } + const [definition, engine] = found; + // A key is one run of the workflow: the engine's own id also counts the version, so a + // start after a new version would otherwise begin the same work again. + const other = Effect.fnUntraced(function* (earlier: WorkflowStore.RunRow) { + if ( + options.parent !== undefined && + (earlier.parent_run_id !== options.parent.runId || + earlier.parent_wait !== options.parent.wait) + ) { + return yield* new WorkflowInputError({ + problem: `Run ${earlier.run_id} of ${name} was started by something else under this key, so it cannot be invoked. Give the invoke a key of its own.`, + }); + } + // A start cut off between its row and the engine left a run nothing executes. Executing + // one the engine has is a no-op. + const its = byTag.get(earlier.engine_tag); + if (earlier.ended_at === null && its !== undefined && earlier.input_json !== null) { + yield* withEngine( + its.execute( + { + idempotencyKey: earlier.idempotency_key, + input: WorkflowStore.jsonValue(earlier.input_json), + }, + { discard: true }, + ), + ); + } + return { runId: earlier.run_id }; + }); + const earlier = yield* store.runByKey(name, options.idempotencyKey); + // An ended run's journal may be pruned, so executing it again would start the work over. + if ( + earlier !== undefined && + (earlier.engine_tag !== engineTag(definition) || earlier.ended_at !== null) + ) { + return yield* other(earlier); + } + const payloadCodec = Schema.toCodecJson(definition.payload); + const encode = Schema.encodeUnknownEffect(payloadCodec); + const encoded = yield* encode(input).pipe( + Effect.mapError( + (error) => + new WorkflowInputError({ + problem: `The payload does not fit workflow ${name}: ${text(error)}`, + }), + ), + ); + const payload = { idempotencyKey: options.idempotencyKey, input: encoded as Schema.Json }; + // The row is written first, with who waits for it: the run's own first step writes the same + // row without that, and whichever write lands first is the one that stays. + const runId = yield* engine.executionId(payload); + yield* store.runStarted({ + runId, + workflow: definition.name, + version: definition.version, + engineTag: engineTag(definition), + idempotencyKey: options.idempotencyKey, + input: payload.input, + parent: options.parent, + }); + // The key is unique, so the row holding it is the run, even one another version started. + const holder = yield* store.runByKey(name, options.idempotencyKey); + if (holder !== undefined && holder.run_id !== runId) return yield* other(holder); + yield* withEngine(engine.execute(payload, { discard: true })); + if (options.parent !== undefined) { + // The key named a run that someone else started: it would never tell this parent. + const row = yield* store.run(runId); + if ( + row?.parent_run_id !== options.parent.runId || + row.parent_wait !== options.parent.wait + ) { + return yield* new WorkflowInputError({ + problem: `Run ${runId} of ${name} was started by something else under this key, so it cannot be invoked. Give the invoke a key of its own.`, + }); + } + } + return { runId }; + }, + ); + + const latestDefinitions = [...new Set(registered.map(([definition]) => definition.name))].map( + (name) => latest(name)![0], + ); + // A schedule taken out and put back is new again: its first run is one interval away. + yield* store.triggersKeep( + latestDefinitions.flatMap((definition) => + definition.triggers.flatMap((trigger) => + trigger.kind === "webhook" ? [] : [`${definition.name}/${trigger.id}`], + ), + ), + ); + /** Start what each schedule is due for, once, however long ago that was. */ + const fireSchedules = Effect.gen(function* () { + const now = yield* localNow; + for (const definition of latestDefinitions) { + for (const trigger of definition.triggers) { + if (trigger.kind !== "schedule") continue; + const id = `${definition.name}/${trigger.id}`; + const due = yield* store.triggerNext(id); + if (due !== undefined) { + const dueAt = DateTime.makeUnsafe(due); + if (DateTime.isLessThan(now, dueAt)) continue; + if (!isMissedFixedTimeRun(trigger.schedule, dueAt, now)) { + // The key is the time it was due, so a crash before the next line starts no second run. + const started = yield* start( + definition.name, + { scheduledAt: due }, + { idempotencyKey: `trigger:${id}:${due}` }, + ).pipe( + Effect.as(true), + Effect.catch((error) => + Effect.as( + Effect.logWarning("A scheduled workflow run did not start", { + trigger: id, + error, + }), + false, + ), + ), + ); + // Not moved past a time it has not started: the next sweep tries that one again. + if (!started) continue; + } + } + const next = nextScheduledRunAt(trigger.schedule, now); + if (next !== null) { + yield* store.triggerSet(id, DateTime.formatIso(DateTime.toUtc(next))); + } + } + } + }).pipe(Effect.withSpan("Workflows.fireSchedules")); + + // Trackers and hosts count requests, and nothing here is in that much of a hurry. + const lookedAt = new Map(); + // Said once per engine: the same item is in every look until newer ones push it out. + const turnedDown = new Set(); + const millisOf = (at: string) => + Option.match(DateTime.make(at), { onNone: () => undefined, onSome: DateTime.toEpochMillis }); + /** + * Start a run for each issue or pull request opened since the trigger last looked. The first + * look only notes the time, so a workflow never starts on everything that was already there. + */ + const fireOpened = Effect.gen(function* () { + const now = yield* DateTime.now; + for (const definition of latestDefinitions) { + for (const trigger of definition.triggers) { + if (trigger.kind !== "issues" && trigger.kind !== "pullRequests") continue; + const id = `${definition.name}/${trigger.id}`; + const since = yield* store.triggerNext(id); + if (since === undefined) { + yield* store.triggerSet(id, DateTime.formatIso(now)); + continue; + } + const last = lookedAt.get(id); + const at = DateTime.toEpochMillis(now); + if (last !== undefined && at - last < Duration.toMillis(LOOK_EVERY)) continue; + lookedAt.set(id, at); + const found = + trigger.kind === "issues" + ? forge.issues.list({ + project: trigger.project, + // Closed ones too: an item can open and close between two looks. + state: "all", + sort: "created", + limit: LOOK_AT_MOST, + labels: trigger.labels, + query: trigger.query, + }) + : forge.pullRequests.list({ + project: trigger.project, + state: "all", + limit: LOOK_AT_MOST, + query: trigger.query, + }); + const sinceMillis = millisOf(since) ?? at; + yield* found.pipe( + Effect.flatMap( + Effect.fnUntraced(function* (entries: ReadonlyArray) { + // From the mark on, not after it: two items can share a moment. As times, since a + // host writes them in its own format and the mark is ours. + const fresh = entries + .flatMap((entry) => { + const created = millisOf(entry.createdAt); + return created === undefined || created < sinceMillis ? [] : [{ entry, created }]; + }) + .toSorted((a, b) => a.created - b.created); + if (entries.length >= LOOK_AT_MOST && fresh.length === entries.length) { + yield* Effect.logWarning( + "More new items than one look reads; older ones among them start no run", + { trigger: id, read: entries.length }, + ); + } + for (const { entry, created } of fresh) { + // The key is the address, so an issue seen twice is still one run. One the + // workflow turns down is passed over, so it does not hold back the ones after it. + const key = `trigger:${id}:${entry.url}`; + if ( + !turnedDown.has(key) && + (yield* store.runByKey(definition.name, key)) === undefined + ) { + yield* start(definition.name, entry, { idempotencyKey: key }).pipe( + // What started the run is the first thing it touched. + Effect.flatMap(({ runId }) => + noteFor( + store, + runId, + null, + "tracker" in entry + ? issueReference(entry, entry) + : pullRequestReferenceOf(entry, entry), + ), + ), + Effect.catchTags({ + WorkflowInputError: (error) => + Effect.andThen( + Effect.sync(() => turnedDown.add(key)), + Effect.logWarning("A workflow turned down an item it was started on", { + trigger: id, + item: entry.url, + error, + }), + ), + }), + ); + } + yield* store.triggerSet(id, DateTime.formatIso(DateTime.makeUnsafe(created))); + } + }), + ), + Effect.catch((error) => + Effect.logWarning("A workflow could not look for new work", { trigger: id, error }), + ), + ); + } + } + }).pipe(Effect.withSpan("Workflows.fireOpened")); + + const noChecksSince = new Map(); + /** End each wait on a pull request that has got where the wait wanted it. */ + const fireWatches = Effect.gen(function* () { + const now = DateTime.toEpochMillis(yield* DateTime.now); + for (const wait of yield* store.watches) { + const id = `watch:${wait.run_id}/${wait.name}`; + const last = lookedAt.get(id); + if (last !== undefined && now - last < Duration.toMillis(LOOK_EVERY)) continue; + lookedAt.set(id, now); + const watch = WorkflowStore.jsonValue( + wait.watch_json ?? "null", + ) as unknown as PullRequestWatch; + yield* forge.pullRequests.read(watch.pullRequest as PullRequestAddress).pipe( + // Each look keeps where the pull request stands on the wait's own step. + Effect.provideContext(stepReferences(store, wait.run_id, wait.name)), + Effect.flatMap( + Effect.fnUntraced(function* (detail) { + const standing = standingOf(detail); + // How long the host has listed no checks, not how long the wait is open: a push can + // clear the list for a moment in the middle of a long wait. + if (standing.checks !== "none") noChecksSince.delete(id); + else if (!noChecksSince.has(id)) noChecksSince.set(id, now); + const without = now - (noChecksSince.get(id) ?? now); + if (!isSettled(watch.until, standing, without)) return; + const woke = { expired: false, value: standing }; + if (!(yield* store.waitSignalled(wait.run_id, wait.name, woke))) return; + lookedAt.delete(id); + noChecksSince.delete(id); + yield* wake(wait, woke); + }), + ), + // The wait's own timeout is what ends a wait on something that cannot be read. + Effect.catch((error) => + Effect.logWarning("A workflow could not look at a pull request", { wait: id, error }), + ), + ); + } + }).pipe(Effect.withSpan("Workflows.fireWatches")); + + const hooks = yield* Effect.forEach( + latestDefinitions.flatMap((definition) => + definition.triggers.flatMap((trigger) => + trigger.kind === "webhook" ? [{ definition, trigger }] : [], + ), + ), + Effect.fnUntraced(function* ({ definition, trigger }) { + const hookId = hookIdOf(definition.name, trigger.name); + const token = yield* store.hookToken(hookId, yield* random.uuidV4()); + return { + hookId, + token, + trigger, + workflow: definition.name, + name: trigger.name, + path: `/api/hooks/${encodeURIComponent(hookId)}/${token}`, + }; + }), + ); + const deliver: Workflows["Service"]["deliver"] = Effect.fn("Workflows.deliver")( + function* (delivery) { + const hook = hooks.find((candidate) => candidate.hookId === delivery.hookId); + // A wrong token reads the same as an unknown hook, so the URL does not say which exist. + const known = + hook !== undefined && + (yield* constantTimeEquals(delivery.token, hook.token).pipe( + Effect.provideService(Digest.Digest, digest), + Effect.orElseSucceed(() => false), + )); + if (!known) return Option.none(); + const authored = yield* Effect.try({ + try: () => hook.trigger.key?.(delivery.request), + catch: (error) => + new WorkflowInputError({ + problem: `The key of hook ${hook.name} could not be read from the request: ${text(error)}`, + }), + }); + // A sender's own delivery id is kept on its retry, so the retry is the same run. + const sent = DELIVERY_HEADERS.find((header) => delivery.request.headers[header]); + const key = + authored ?? + (sent === undefined ? undefined : `${sent}:${delivery.request.headers[sent]}`) ?? + delivery.deliveryId ?? + (yield* random.uuidV4()); + return Option.some( + yield* start(hook.workflow, delivery.request, { + idempotencyKey: `hook:${hook.hookId}:${key}`, + }), + ); + }, + ); + + /** With `pause`, the sweep's own resume, which only resumes that pause and not a later one. */ + const resumeRun = Effect.fn("WorkflowEngine.resumeRun")(function* ( + runId: string, + pause?: WorkflowStore.RunRow, + ) { + const row = yield* requireRun(runId); + const engine = byTag.get(row.engine_tag); + if (engine === undefined) { + return yield* new WorkflowNotRegisteredError({ workflow: row.engine_tag }); + } + if (row.ended_at !== null) return; + resuming.add(runId); + const resumed = yield* Effect.gen(function* () { + // Marked first: once the engine is resumed, the step may fail again and pause the run, and + // that must be the last word. A crash in between leaves `running`, which the sweep corrects. + if (row.status === "paused") { + const unpaused = yield* store.runUnpaused( + runId, + pause === undefined + ? undefined + : { pauses: Number(pause.pauses), updatedAt: pause.updated_at }, + ); + if (!unpaused && pause !== undefined) return false; + } + // The step marks its run paused from inside the engine, a moment before the engine records + // the failure. Resuming in that moment would do nothing, so the record is waited for. + yield* withEngine(engine.poll(runId)).pipe( + Effect.repeat({ + until: (result) => Option.isSome(result) && result.value._tag === "Suspended", + schedule: Schedule.spaced(RESUME_LOOK_EVERY), + times: RESUME_LOOKS, + }), + ); + yield* withEngine(engine.resume(runId)); + yield* store.runUnheld(runId); + return true; + }).pipe(Effect.ensuring(Effect.sync(() => resuming.delete(runId)))); + // Read once `resuming` is clear, so a wake held back meanwhile is among them. + if (!resumed) return; + for (const wait of yield* store.waitsClaimed(runId)) { + yield* send(wait, WorkflowStore.jsonValue(wait.woke_json ?? "null") as typeof Woke.Type); + } + }); + const resume: Workflows["Service"]["resume"] = (runId) => resumeRun(runId); + + /** A run the engine holds as failed while its row says it goes on: paused, after all. */ + const reconcile = Effect.fn("WorkflowEngine.reconcile")(function* (row: WorkflowStore.RunRow) { + if (resuming.has(row.run_id)) return; + const engine = byTag.get(row.engine_tag); + if (engine === undefined) return; + const result = yield* withEngine(engine.poll(row.run_id)); + if (Option.isNone(result) || result.value._tag !== "Suspended") return; + if (result.value.failed !== true) return; + const cause = result.value.cause; + // Held as it was: a run that waited for a person still does. + yield* store.runPaused( + row.run_id, + cause === undefined ? "A step failed." : text(Cause.squash(cause)), + ); + }); + + // A cancelled run's body is gone, so its `onEnd` runs here, outside the engine. The sweep asks + // again after a failure or a restart, and `ending` keeps the two from running it at once. + const ending = new Set(); + const endCancelled = Effect.fn("WorkflowEngine.endCancelled")(function* ( + row: WorkflowStore.RunRow, + ) { + const definition = definitionByTag.get(row.engine_tag); + if (definition?.onEnd === undefined || ending.has(row.run_id)) return; + const onEnd = definition.onEnd; + ending.add(row.run_id); + // A step still running would race the cleanup: a machine deleted before it is made. + yield* link.inFlight.settled(row.run_id); + // The body may have run its own `onEnd` just as the run was cancelled: once is enough. + const steps = yield* store.steps(row.run_id); + if (steps.some((step) => step.name === END_STEP && step.status === "completed")) { + ending.delete(row.run_id); + return; + } + yield* store.stepStarted(row.run_id, END_STEP, "step"); + const payloadCodec = Schema.toCodecJson(definition.payload); + const decode = Schema.decodeEffect(payloadCodec); + yield* decode(row.input_json === null ? null : WorkflowStore.jsonValue(row.input_json)).pipe( + Effect.flatMap((input) => + onEnd(input as never, { + id: row.run_id, + outcome: "cancelled", + reason: row.detail ?? undefined, + }), + ), + Effect.provideContext(forStep(store, keyValues, link, forge, row.run_id, END_STEP)), + // The sweep that runs it reads the engine's BigInts; the cleanup's own code must not. + Effect.provideService(SqlClient.SafeIntegers, false), + Effect.matchCauseEffect({ + onSuccess: () => store.stepEnded(row.run_id, END_STEP, "completed", null), + onFailure: (cause) => + store.stepEnded(row.run_id, END_STEP, "failed", text(Cause.squash(cause))), + }), + Effect.ensuring(Effect.sync(() => ending.delete(row.run_id))), + ); + }); + + const prune = Effect.fn("WorkflowEngine.prune")(function* (at: DateTime.Utc) { + if (Option.isNone(messages) || Option.isNone(sharding)) return; + const before = DateTime.formatIso(DateTime.subtractDuration(at, PRUNE_AFTER)); + for (const row of yield* store.prunable(before, PRUNE_BATCH)) { + const entityId = EntityId.make(row.run_id); + const shardId = sharding.value.getShardId(entityId, "default"); + // Its sleeps are entities of their own under the same id. + yield* Effect.forEach( + [`Workflow/${row.engine_tag}`, "Workflow/-/DurableClock"], + (type) => + messages.value.clearAddress( + EntityAddress.make({ shardId, entityType: EntityType.make(type), entityId }), + ), + { discard: true }, + ).pipe( + Effect.andThen(store.enginePruned(row.run_id)), + // Left unmarked, so the next sweep tries it again. + Effect.catchCause((cause) => + Effect.logWarning("Could not prune a workflow run's engine journal", cause), + ), + ); + } + }); + + const sweep: Workflows["Service"]["sweep"] = Effect.gen(function* () { + for (const wait of yield* store.waitsPastDeadline) { + const woke = { expired: true, value: null }; + if (yield* store.waitSignalled(wait.run_id, wait.name, woke)) yield* wake(wait, woke); + } + // A claim whose wake a crash swallowed: the wake is made again. Waking twice is harmless. + for (const wait of yield* store.waitsToWake) { + if (wait.woke_json === null) continue; + yield* wake(wait, WorkflowStore.jsonValue(wait.woke_json) as typeof Woke.Type); + } + // A cancel that was cut short before it reached what the run had invoked. + for (const child of yield* store.orphans) { + yield* Effect.ignore(cancel(child.run_id, "the run that invoked it was cancelled")); + } + // A cancel cut short after the run was ended: what it had not stopped yet is stopped here. + for (const row of yield* store.cancelsCutShort(END_STEP)) { + if (cancelling.has(row.run_id) || ending.has(row.run_id)) continue; + const engine = byTag.get(row.engine_tag); + if (engine !== undefined) yield* withEngine(engine.interrupt(row.run_id)); + yield* stopSteps(row.run_id, yield* store.runningThreads(row.run_id)); + } + // A run that ended without its parent hearing of it. Telling twice is harmless. + for (const child of yield* store.untold) yield* ended(child.run_id); + yield* store.mailExpire; + yield* fireSchedules; + yield* fireOpened; + yield* fireWatches; + const at = yield* DateTime.now; + // A run with a step still going is ended by its cancel, which waits for that step. + for (const row of yield* store.runsToEnd(END_STEP, END_TRIES)) { + const rest = END_AFTER[Number(row.end_attempts ?? 0) - 1]; + if (row.end_ended_at !== null && rest !== undefined) { + const due = DateTime.addDuration( + DateTime.makeUnsafe(row.end_ended_at), + Duration.fromInputUnsafe(rest), + ); + if (DateTime.isLessThan(at, due)) continue; + } + if (!link.inFlight.busy(row.run_id)) yield* endCancelled(row); + } + for (const row of yield* store.everyRun("running")) yield* reconcile(row); + for (const row of yield* store.everyRun("waiting")) yield* reconcile(row); + for (const row of yield* store.everyRun("paused")) { + const due = resumesAt(row); + if (due === undefined || DateTime.isLessThan(at, due)) continue; + yield* Effect.ignore(resumeRun(row.run_id, row)); + } + yield* prune(at); + }).pipe(Effect.withSpan("Workflows.sweep")); + + // With nothing registered there is nothing to resume, end or start: only history to read. + if (registered.length > 0) { + yield* sweep.pipe( + Effect.catchCause((cause) => Effect.logWarning("Workflow sweep failed", cause)), + Effect.andThen(Effect.sleep(SWEEP_EVERY)), + Effect.forever, + Effect.forkScoped, + ); + } + + const questions = Effect.flatMap(store.requests, (waits) => + Effect.forEach( + waits.filter((wait) => wait.request_json !== null), + (wait) => + Effect.map(store.latestThread(wait.run_id), (thread) => ({ + runId: wait.run_id, + name: wait.name, + request: WorkflowStore.jsonValue(wait.request_json ?? "null"), + askedAt: wait.opened_at, + thread, + })), + ), + ); + const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; + const triggerText = (trigger: WorkflowDefinition["triggers"][number]) => { + if (trigger.kind === "webhook") return `webhook ${trigger.name}`; + if (trigger.kind !== "schedule") { + return `new ${trigger.kind === "issues" ? "issues" : "pull requests"} in ${trigger.project}`; + } + if (trigger.schedule.type === "interval") { + return `every ${Duration.format(Duration.millis(trigger.schedule.everyMs))}`; + } + const days = trigger.schedule.weekdays; + return `daily at ${trigger.schedule.timeOfDay}${ + days === undefined ? "" : ` on ${days.map((day) => WEEKDAYS[day] ?? day).join(", ")}` + }`; + }; + const summaries = [...new Set(registered.map(([definition]) => definition.name))].flatMap( + (name) => { + const found = latest(name); + return found === undefined + ? [] + : [{ name, version: found[0].version, triggers: found[0].triggers.map(triggerText) }]; + }, + ); + const snapshot = Effect.all({ + workflows: Effect.succeed(summaries), + runs: Effect.map(store.runs(undefined), (rows) => rows.map(toRun)), + questions, + }); + const watch: Workflows["Service"]["watch"] = Stream.unwrap( + Effect.gen(function* () { + // Subscribed before the first look, so a change in between is not missed. + const changes = yield* PubSub.subscribe(store.changes); + return Stream.concat( + Stream.fromEffect(snapshot), + // A run writes several rows per step; one list answers a burst of them. + Stream.fromSubscription(changes).pipe( + Stream.debounce(WATCH_SETTLE), + Stream.mapEffect(() => snapshot), + ), + ); + }), + ); + + const counts: Workflows["Service"]["counts"] = Stream.unwrap( + Effect.gen(function* () { + const changes = yield* PubSub.subscribe(store.changes); + return Stream.concat( + Stream.fromEffect(store.counts), + Stream.fromSubscription(changes).pipe( + Stream.debounce(WATCH_SETTLE), + Stream.mapEffect(() => store.counts), + ), + // Most changes move no count, and a badge has no use for hearing of those. + ).pipe(Stream.changesWith((left, right) => JSON.stringify(left) === JSON.stringify(right))); + }), + ); + + const signal: Workflows["Service"]["signal"] = Effect.fn("Workflows.signal")( + function* (address, value, options) { + // A sender's retry of a signal that already woke a wait is not a second signal. + if (yield* store.signalSeen(options.id)) return "delivered" as const; + const valueJson = WorkflowStore.jsonText(value); + const woke = { expired: false, value }; + // One signal per wait: a wait another signal took first sends this one to the next. + while (true) { + const wait = yield* store.waitAt(address); + if (wait === undefined) break; + const schema = WorkflowStore.jsonValue(wait.schema_json) as Record; + const checked = yield* checkOutput(schema, valueJson); + if (Result.isFailure(checked)) { + return yield* new WorkflowInputError({ + problem: `The value does not fit what ${wait.name} waits for. ${rejectionText(checked.failure)}`, + }); + } + if (yield* store.waitSignalled(wait.run_id, wait.name, woke, options.id)) { + yield* wake(wait, woke); + return "delivered" as const; + } + // Refused for its id: the same signal, sent again at once, woke a wait. + if (yield* store.signalSeen(options.id)) return "delivered" as const; + } + const expiresAt = DateTime.formatIso( + DateTime.addDuration( + yield* DateTime.now, + Duration.fromInputUnsafe(options.ttl ?? DEFAULT_SIGNAL_TTL), + ), + ); + if (yield* store.signalSeen(options.id)) return "delivered" as const; + yield* store.mailPut({ signalId: options.id, address, valueJson, expiresAt }); + // The wait may have opened and looked for mail between the look above and this write. + while (true) { + const late = yield* store.waitAt(address); + if (late === undefined) return "buffered" as const; + const schema = WorkflowStore.jsonValue(late.schema_json) as Record; + // Kept for a wait it fits; this one, the oldest on the channel, is not it. + if (Result.isFailure(yield* checkOutput(schema, valueJson))) return "buffered" as const; + const outcome = yield* store.mailDeliver(options.id, late.run_id, late.name, woke); + if (outcome === "delivered") { + yield* wake(late, woke); + return "delivered" as const; + } + // The kept copy went to a wait that opened, or was dropped as already delivered. + if (outcome === "gone") return "delivered" as const; + } + }, + ); + const answer: Workflows["Service"]["answer"] = Effect.fn("Workflows.answer")( + function* (runId, name, value) { + const wait = yield* store.waitAt({ runId, wait: name }); + // Answered already, or never asked: kept, it would answer whatever asks there next. + if (wait === undefined || wait.request_json === null) return; + // Named by this asking of the question, so every answer to it is one signal. + yield* signal({ runId, wait: name }, value, { id: `answer:${wait.token}` }); + }, + ); + const signalAll = Effect.fn("WorkflowEngine.signalAll")(function* ( + address: { readonly channel: string; readonly workflow?: string | undefined }, + value: Schema.Json, + ) { + const valueJson = WorkflowStore.jsonText(value); + let woken = 0; + for (const wait of yield* store.waitsOn(address.channel, address.workflow)) { + const schema = WorkflowStore.jsonValue(wait.schema_json) as Record; + // A wait this value does not fit was not waiting for it; the others are still woken. + if (Result.isFailure(yield* checkOutput(schema, valueJson))) continue; + const woke = { expired: false, value }; + if (!(yield* store.waitSignalled(wait.run_id, wait.name, woke))) continue; + yield* wake(wait, woke); + woken++; + } + return woken; + }); + /** Tell the run that invoked this one, if one did, how it ended. */ + const ended = Effect.fn("WorkflowEngine.ended")(function* (runId: string) { + const row = yield* store.run(runId); + if (row === undefined || row.parent_run_id === null || row.parent_wait === null) return; + if (row.ended_at === null) return; + yield* signal( + { runId: row.parent_run_id, wait: row.parent_wait }, + { + outcome: row.status, + value: row.result_json === null ? null : WorkflowStore.jsonValue(row.result_json), + ...(row.detail === null ? {} : { reason: row.detail }), + }, + { id: `${runId}/ended` }, + ).pipe(Effect.ignore); + }); + + /** A step in flight cannot be interrupted, so the agent it waits on is stopped instead. */ + const stopSteps = Effect.fn("WorkflowEngine.stopSteps")(function* ( + runId: string, + threads: ReadonlyArray[0]>, + ) { + yield* Effect.forEach(threads, (thread) => Effect.ignore(stopTurn(thread)), { + discard: true, + }); + yield* store.stepsCancelled(runId, END_STEP); + }); + + // Cancels under way, whose slow part the sweep must not take for one cut short. + const cancelling = new Set(); + const cancel: Workflows["Service"]["cancel"] = Effect.fn("Workflows.cancel")( + function* (runId, reason) { + const row = yield* requireRun(runId); + if (row.ended_at !== null) return; + const threads = yield* store.runningThreads(runId); + const engine = byTag.get(row.engine_tag); + cancelling.add(runId); + yield* Effect.gen(function* () { + // Ended first, so nothing the run still does can be recorded as its outcome. A run that + // finished in the meantime keeps its own ending, and its cleanup is its own. Not cut off + // midway: the engine would go on with a cancelled run, or its parent wait forever. + const cancelled = yield* Effect.uninterruptible( + Effect.gen(function* () { + if (!(yield* store.runEnded(runId, "cancelled", reason ?? null, null))) return false; + if (engine !== undefined) yield* withEngine(engine.interrupt(runId)); + yield* ended(runId); + return true; + }), + ); + if (!cancelled) return; + yield* stopSteps(runId, threads); + // What this run invoked was part of it. + yield* Effect.forEach( + yield* store.children(runId), + (child) => Effect.ignore(cancel(child.run_id, reason)), + { discard: true }, + ); + // Waited for briefly, so the caller usually hears of a run that is cleaned up. A cleanup + // can take minutes; it goes on by itself, and the sweep finishes one that is cut short. + const cleanup = yield* Effect.forkIn( + endCancelled({ ...row, detail: reason ?? null }), + scope, + ); + yield* Fiber.join(cleanup).pipe(Effect.timeoutOption(CANCEL_WAITS)); + }).pipe(Effect.ensuring(Effect.sync(() => cancelling.delete(runId)))); + }, + ); + + // Steps were registered before this engine existed; now they can reach it. + link.current = { + signal, + signalAll, + start, + ended, + cancel: (runId, reason) => cancel(runId, reason), + list: Effect.fn("WorkflowEngine.list")(function* (filter) { + return (yield* store.runsWhere(filter)).map((row) => ({ + id: row.run_id, + workflow: row.workflow, + key: row.idempotency_key, + title: row.title, + status: row.status, + detail: row.detail, + startedAt: row.started_at, + endedAt: row.ended_at, + })); + }), + }; + + return Workflows.of({ + start, + hooks: Effect.succeed(hooks.map(({ workflow, name, path }) => ({ workflow, name, path }))), + // A cancelled run whose cleanup has not worked yet still needs its version to run it. + unfinished: Effect.map( + Effect.all([store.unfinished, store.runsToEnd(END_STEP, END_TRIES)]), + ([open, ending]) => [ + ...open, + ...ending + .filter((row) => definitionByTag.get(row.engine_tag)?.onEnd !== undefined) + .map((row) => ({ workflow: row.workflow, version: Number(row.version) })), + ], + ), + deliver, + signal, + answer, + resume, + cancel, + get: Effect.fn("Workflows.get")(function* (runId) { + const row = yield* requireRun(runId); + const steps = yield* store.steps(runId); + return { + run: toRun(row), + references: yield* store.references(runId), + steps: steps.map((step) => ({ + name: step.name, + kind: step.kind, + status: step.status, + attempts: Number(step.attempts), + detail: step.detail, + threadId: step.thread_id, + environmentId: step.environment_id, + result: step.result_json === null ? null : WorkflowStore.jsonValue(step.result_json), + said: step.said, + startedAt: step.started_at, + endedAt: step.ended_at, + })), + }; + }), + list: Effect.fn("Workflows.list")(function* (filter) { + return (yield* store.runs(filter?.status)).map(toRun); + }), + waitFor: Effect.fn("Workflows.waitFor")(function* (runId, done) { + // Subscribed before the first look, so a change in between is not missed. + const changes = yield* PubSub.subscribe(store.changes); + while (true) { + const row = yield* store.run(runId); + if (row !== undefined && done(toRun(row))) return toRun(row); + yield* Effect.repeat(PubSub.take(changes), { until: (changed) => changed === runId }); + } + }, Effect.scoped), + questions, + counts, + stored: Effect.fn("Workflows.stored")(function* (prefix) { + return (yield* keyValues.list(prefix)).map((row) => ({ + key: row.key, + value: WorkflowStore.jsonValue(row.valueJson), + })); + }), + storeSet: Effect.fn("Workflows.storeSet")(function* (key, value) { + yield* keyValues.set(key, WorkflowStore.jsonText(value)); + }), + storeDelete: Effect.fn("Workflows.storeDelete")(function* (key) { + yield* keyValues.delete(key); + }), + watch, + sweep, + }); +}); + +/** + * The workflow service with these definitions registered, on the SQLite database provided to it. + * Only one process may run this layer against a database. + */ +export const layer = ( + definitions: ReadonlyArray, + store: typeof WorkflowStore.layer = WorkflowStore.layer, +) => { + const registered = definitions.map( + (definition) => [definition, engineWorkflow(definition)] as const, + ); + const layerDefinitions = Layer.mergeAll( + Layer.empty, + ...registered.map(([definition, engine]) => layerDefinition(definition, engine)), + ); + return Layer.effect(Workflows, make(registered)).pipe( + Layer.provide(layerDefinitions), + Layer.provide(store), + Layer.provide(Layer.merge(layerKeyValues, layerEngineLink)), + Layer.provide( + registered.length === 0 + ? WorkflowEngine.layerMemory + : ClusterWorkflowEngine.layer.pipe( + // Merged so the sweep can prune ended runs' journals from the same storage. + Layer.provideMerge(SingleRunner.layer({ runnerStorage: "sql" })), + ), + ), + Layer.provide(Layer.succeed(SqlClient.SafeIntegers, true)), + ); +}; diff --git a/apps/server/src/workflows/WorkflowForge.test.ts b/apps/server/src/workflows/WorkflowForge.test.ts new file mode 100644 index 0000000000000..58f9626423510 --- /dev/null +++ b/apps/server/src/workflows/WorkflowForge.test.ts @@ -0,0 +1,113 @@ +import { assert, it } from "@effect/vitest"; +import { IssueTrackerKind, ProjectId } from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import * as IssueService from "../issue/IssueService.ts"; +import * as ProjectService from "../project/ProjectService.ts"; +import * as PullRequestService from "../pullRequest/PullRequestService.ts"; +import { StepReferences } from "./runReferences.ts"; +import * as WorkflowForge from "./WorkflowForge.ts"; +import type { ReferenceInput } from "./WorkflowStore.ts"; + +const projectId = ProjectId.make("project-1"); +const forge = WorkflowForge.layer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.mock(IssueService.IssueService)({ comment: () => Effect.void }), + Layer.mock(PullRequestService.PullRequestService)({ + runAction: () => Effect.void as never, + detail: () => + Effect.succeed({ + projectId, + repository: "Me/App", + number: 7, + title: "Minutes wrap at the hour", + url: "https://github.com/Me/App/pull/7", + state: "merged", + } as never), + }), + Layer.mock(ProjectService.ProjectService)({ + getByWorkspaceRoot: () => Effect.succeedSome({ id: projectId } as never), + }), + ), + ), +); + +it.effect("what a step does through the forge is kept against it, one key per thing", () => + Effect.gen(function* () { + const { issues, pullRequests } = yield* WorkflowForge.WorkflowForge; + const noted: Array = []; + const inStep = Context.make(StepReferences, { + note: (reference) => Effect.sync(() => void noted.push(reference)), + }); + const issue = { + projectId, + tracker: IssueTrackerKind.make("github"), + host: "github.com", + scope: "me/app", + key: "3", + }; + yield* Effect.provideContext( + Effect.all([ + // By its address, then as a listing names it: the same pull request either way. + pullRequests.act( + { project: "/home/me/app", url: "https://github.com/Me/App/pull/7" }, + "merge", + ), + pullRequests.read({ projectId, host: "github.com", repository: "me/app", number: 7 }), + issues.comment(issue, "Looking at it."), + ]), + inStep, + ); + // Outside a step nothing is kept. + yield* issues.comment(issue, "Again."); + assert.deepStrictEqual( + noted.map(({ kind, key, title, state }) => ({ kind, key, title, state })), + [ + { kind: "pullRequest", key: noted[1]!.key, title: "", state: undefined }, + { + kind: "pullRequest", + key: '["github.com","me/app",7]', + title: "Minutes wrap at the hour", + state: "merged", + }, + { kind: "issue", key: '["github","github.com","me/app","3"]', title: "", state: undefined }, + ], + ); + assert.deepStrictEqual(noted[1]!.address, { + projectId, + host: "github.com", + repository: "me/app", + number: 7, + }); + }).pipe(Effect.provide(forge)), +); + +it("a step's pull requests are the ones its thread was linked to while it ran", () => { + const link = (number: number, linkedAt: string, source = "agent") => ({ + host: "github.com", + repository: "me/app", + number, + url: `https://github.com/me/app/pull/${number}`, + source, + linkedAt, + snapshot: null, + }); + const references = WorkflowForge.linkedPullRequestReferences( + { + projectId, + pullRequests: [ + link(1, "2026-01-01T00:00:00.000Z"), + link(2, "2026-01-01T00:10:00.000Z"), + link(3, "2026-01-01T00:10:00.000Z", "stack-dismissed"), + ] as never, + }, + Date.parse("2026-01-01T00:05:00.000Z"), + ); + assert.deepStrictEqual( + references.map((reference) => [reference.key, reference.url]), + [['["github.com","me/app",2]', "https://github.com/me/app/pull/2"]], + ); +}); diff --git a/apps/server/src/workflows/WorkflowForge.ts b/apps/server/src/workflows/WorkflowForge.ts new file mode 100644 index 0000000000000..dab867593b4dd --- /dev/null +++ b/apps/server/src/workflows/WorkflowForge.ts @@ -0,0 +1,455 @@ +// Issues and pull requests for workflows: the same trackers and hosts the app's own Issues and +// Pull requests pages read, through the project's credentials. A step names a project the way +// an agent step does, by id or by folder. +import { + IssueDetail, + IssueListEntry, + type IssueCreateResult, + type IssueListState, + type IssueRef, + type PullRequestAction, + type PullRequestDetail, + PullRequestListEntry, + type PullRequestListState, + type PullRequestMergeMethod, + type PullRequestRef, + ProjectId, +} from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; + +import * as IssueService from "../issue/IssueService.ts"; +import * as ProjectService from "../project/ProjectService.ts"; +import * as PullRequestService from "../pullRequest/PullRequestService.ts"; +import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts"; +import { + normalizeThreadPullRequestKey, + threadPullRequestsOf, +} from "../sourceControl/threadPullRequests.ts"; +import { issueReference, noteReference, pullRequestReference } from "./runReferences.ts"; +import { isProjectPath } from "./WorkflowAgents.ts"; + +export class WorkflowForgeError extends Schema.TaggedError()( + "WorkflowForgeError", + { reason: Schema.String }, +) { + override get message(): string { + return this.reason; + } +} + +/** What an issue trigger gives its run, and what `issues.list` returns rows of. */ +export const Issue = IssueListEntry; +export type Issue = typeof Issue.Type; +/** What a pull request trigger gives its run, and what `pullRequests.list` returns rows of. */ +export const PullRequest = PullRequestListEntry; +export type PullRequest = typeof PullRequest.Type; +export { IssueDetail }; + +/** An issue by its web address, or as a trigger or a listing gave it. */ +export type IssueAddress = + | { readonly project: string; readonly url: string } + | Pick; +/** A pull request by its web address, or as a trigger or a listing gave it. */ +export type PullRequestAddress = + | { readonly project: string; readonly url: string } + | Pick; + +/** Where a pull request stands, as a wait on it gives it. */ +export const PullRequestStanding = Schema.Struct({ + state: Schema.Literals(["open", "closed", "merged"]), + /** `none` when the host lists no checks for it. */ + checks: Schema.Literals(["passing", "failing", "pending", "none"]), + mergeability: Schema.Literals(["mergeable", "conflicting", "unknown"]), + url: Schema.String, +}); +export type PullRequestStanding = typeof PullRequestStanding.Type; +export type PullRequestUntil = "checks" | "merged" | "closed"; +/** What a wait on a pull request keeps for the engine to look at. */ +export interface PullRequestWatch { + readonly kind: "pullRequest"; + readonly until: PullRequestUntil; + readonly pullRequest: + | { readonly project: string; readonly url: string } + | { + readonly projectId: string; + readonly host: string; + readonly repository: string; + readonly number: number; + }; +} + +// Checks take a moment to be listed after a push, so "none" only counts once it has stayed none. +const NO_CHECKS_AFTER_MS = 2 * 60_000; + +/** Required checks decide when the host marks any as required; otherwise all of them do. */ +export const standingOf = ( + detail: Pick, +): PullRequestStanding => { + const listed = detail.checks.filter((check) => check.placeholder !== true); + const counted = listed.some((check) => check.required === true) + ? listed.filter((check) => check.required === true) + : listed; + const failing = counted.some( + (check) => + check.status === "failure" || + check.status === "cancelled" || + // Nothing moves it but a person, so a run waiting for it would wait for good. + check.status === "action-required", + ); + const pending = counted.some((check) => check.status === "pending"); + return { + state: detail.state, + // Pending first: the wait is for none of them still running, even once one has failed. + checks: counted.length === 0 ? "none" : pending ? "pending" : failing ? "failing" : "passing", + mergeability: detail.mergeability, + url: detail.url, + }; +}; + +/** Whether a wait `until` this is over, the host having listed no checks for `withoutChecksMs`. */ +export const isSettled = ( + until: PullRequestUntil, + standing: PullRequestStanding, + withoutChecksMs: number, +): boolean => { + if (standing.state !== "open") return true; + if (until !== "checks") return false; + if (standing.checks === "none") return withoutChecksMs >= NO_CHECKS_AFTER_MS; + return standing.checks !== "pending"; +}; + +export interface IssueQuery { + readonly project: string; + /** Defaults to open. */ + readonly state?: IssueListState | undefined; + /** Label names an issue must carry, every one of them. */ + readonly labels?: ReadonlyArray | undefined; + /** Free text the tracker matches itself. */ + readonly query?: string | undefined; + readonly assignee?: string | undefined; + readonly sort?: "updated" | "created" | undefined; + readonly limit?: number | undefined; +} +export interface PullRequestQuery { + readonly project: string; + /** Defaults to open. */ + readonly state?: PullRequestListState | undefined; + readonly query?: string | undefined; + readonly limit?: number | undefined; +} + +type PullRequestSeen = Parameters[1]; +/** A pull request as a run's reference, under the key every way of naming it shares. */ +export const pullRequestReferenceOf = ( + ref: Pick, + seen?: PullRequestSeen, +) => + pullRequestReference( + { + projectId: ref.projectId, + ...normalizeThreadPullRequestKey({ + host: ref.host ?? "", + repository: ref.repository, + number: ref.number, + ...(seen?.url === undefined ? {} : { url: seen.url }), + }), + }, + seen, + ); + +/** The pull requests linked to a thread from `sinceMillis` on, as references of its step. */ +export const linkedPullRequestReferences = ( + thread: Parameters[0] & { readonly projectId: ProjectId }, + sinceMillis: number | undefined, +) => + threadPullRequestsOf(thread) + .filter( + (link) => + link.source !== "stack-dismissed" && + (sinceMillis === undefined || Date.parse(link.linkedAt) >= sinceMillis), + ) + .map((link) => + pullRequestReferenceOf( + { + projectId: thread.projectId, + host: link.host, + repository: link.repository, + number: link.number, + }, + link.snapshot === null + ? { url: link.url } + : { url: link.url, title: link.snapshot.title, state: link.snapshot.state }, + ), + ); + +export class WorkflowForge extends Context.Service< + WorkflowForge, + { + readonly issues: { + readonly list: (query: IssueQuery) => Effect.Effect, WorkflowForgeError>; + readonly read: (issue: IssueAddress) => Effect.Effect; + readonly comment: ( + issue: IssueAddress, + body: string, + ) => Effect.Effect; + readonly setState: ( + issue: IssueAddress, + state: string, + ) => Effect.Effect; + readonly create: (input: { + readonly project: string; + readonly title: string; + readonly body?: string | undefined; + readonly labels?: ReadonlyArray | undefined; + readonly assignees?: ReadonlyArray | undefined; + }) => Effect.Effect; + }; + readonly pullRequests: { + readonly list: ( + query: PullRequestQuery, + ) => Effect.Effect, WorkflowForgeError>; + readonly read: ( + pullRequest: PullRequestAddress, + ) => Effect.Effect; + readonly comment: ( + pullRequest: PullRequestAddress, + body: string, + ) => Effect.Effect; + readonly act: ( + pullRequest: PullRequestAddress, + action: PullRequestAction, + options?: { readonly mergeMethod?: PullRequestMergeMethod | undefined }, + ) => Effect.Effect; + }; + } +>()("t3/workflows/WorkflowForge") {} + +const failed = + (what: string) => + (cause: unknown): WorkflowForgeError => + new WorkflowForgeError({ + reason: `${what}: ${cause instanceof Error ? cause.message : String(cause)}`, + }); + +const missing = (what: string) => () => + Effect.fail( + new WorkflowForgeError({ + reason: `${what} are not available to workflows on this server.`, + }), + ); +/** For an engine with no trackers behind it: every call says so. */ +export const unavailable = WorkflowForge.of({ + issues: { + list: missing("Issues"), + read: missing("Issues"), + comment: missing("Issues"), + setState: missing("Issues"), + create: missing("Issues"), + }, + pullRequests: { + list: missing("Pull requests"), + read: missing("Pull requests"), + comment: missing("Pull requests"), + act: missing("Pull requests"), + }, +}); + +export const layer = Layer.effect( + WorkflowForge, + Effect.gen(function* () { + const issues = yield* IssueService.IssueService; + const pullRequests = yield* PullRequestService.PullRequestService; + const projects = yield* ProjectService.ProjectService; + + const projectIdOf = Effect.fn("WorkflowForge.projectIdOf")(function* (project: string) { + if (!isProjectPath(project)) return ProjectId.make(project); + const found = yield* projects + .getByWorkspaceRoot(project) + .pipe(Effect.mapError(failed("Could not read the project"))); + if (Option.isNone(found)) { + return yield* new WorkflowForgeError({ reason: `No project is registered at ${project}.` }); + } + return found.value.id; + }); + + const issueRef = Effect.fn("WorkflowForge.issueRef")(function* (issue: IssueAddress) { + if (!("project" in issue)) { + return { + projectId: issue.projectId, + tracker: issue.tracker, + host: issue.host, + scope: issue.scope, + key: issue.key, + } satisfies IssueRef; + } + const resolved = yield* issues + .resolveUrl(issue.url, yield* projectIdOf(issue.project)) + .pipe(Effect.mapError(failed(`Could not find the issue at ${issue.url}`))); + return { + projectId: resolved.projectId, + tracker: resolved.tracker, + host: resolved.host, + scope: resolved.scope, + key: resolved.key, + } satisfies IssueRef; + }); + + const pullRequestRef = Effect.fn("WorkflowForge.pullRequestRef")(function* ( + pullRequest: PullRequestAddress, + ) { + if (!("project" in pullRequest)) { + return { + projectId: pullRequest.projectId, + host: pullRequest.host, + repository: pullRequest.repository, + number: pullRequest.number, + } satisfies PullRequestRef; + } + const parsed = sourceControlDefinitions.parseChangeRequestUrl(pullRequest.url)?.link; + if (parsed === undefined) { + return yield* new WorkflowForgeError({ + reason: `${pullRequest.url} is not a pull request address.`, + }); + } + const key = normalizeThreadPullRequestKey(parsed); + return { + projectId: yield* projectIdOf(pullRequest.project), + host: key.host, + repository: key.repository, + number: key.number, + } satisfies PullRequestRef; + }); + + // An address that is a whole listing row already says what the item is called. + const seenOf = (address: object) => ({ + ...("title" in address && typeof address.title === "string" ? { title: address.title } : {}), + ...("url" in address && typeof address.url === "string" ? { url: address.url } : {}), + }); + const issueTouched = (ref: IssueRef, address: IssueAddress) => + noteReference({ ...issueReference(ref), ...seenOf(address) }); + const pullRequestTouched = (ref: PullRequestRef, seen: PullRequestSeen) => + noteReference(pullRequestReferenceOf(ref, seen)); + + return WorkflowForge.of({ + issues: { + list: Effect.fn("WorkflowForge.issues.list")(function* (query) { + const result = yield* issues + .list({ + projectId: yield* projectIdOf(query.project), + state: query.state ?? "open", + ...(query.labels === undefined ? {} : { labels: [...query.labels] }), + ...(query.query === undefined ? {} : { query: query.query }), + ...(query.assignee === undefined ? {} : { assignee: query.assignee }), + ...(query.sort === undefined ? {} : { sort: query.sort }), + ...(query.limit === undefined ? {} : { limit: query.limit }), + }) + .pipe(Effect.mapError(failed("Could not list issues"))); + // A listing answers with what it could read. One that read nothing is a failure. + const problem = result.errors[0]; + if (result.entries.length === 0 && problem !== undefined) { + return yield* new WorkflowForgeError({ + reason: `Could not list issues: ${problem.message}`, + }); + } + return result.entries; + }), + read: Effect.fn("WorkflowForge.issues.read")(function* (issue) { + const ref = yield* issueRef(issue); + const detail = yield* issues + .detail(ref) + .pipe(Effect.mapError(failed("Could not read the issue"))); + yield* noteReference(issueReference(ref, detail)); + return detail; + }), + comment: Effect.fn("WorkflowForge.issues.comment")(function* (issue, body) { + const ref = yield* issueRef(issue); + yield* issues + .comment({ ...ref, body }) + .pipe(Effect.mapError(failed("Could not comment on the issue"))); + yield* issueTouched(ref, issue); + }), + setState: Effect.fn("WorkflowForge.issues.setState")(function* (issue, state) { + const ref = yield* issueRef(issue); + yield* issues + .setState({ ...ref, state }) + .pipe(Effect.mapError(failed("Could not change the issue's state"))); + yield* issueTouched(ref, issue); + }), + create: Effect.fn("WorkflowForge.issues.create")(function* (input) { + const scope = yield* issues + .projectScope(yield* projectIdOf(input.project)) + .pipe(Effect.mapError(failed("Could not find the project's issue tracker"))); + const created = yield* issues + .create({ + projectId: scope.projectId, + tracker: scope.tracker, + host: scope.host, + scope: scope.scope, + title: input.title, + body: input.body ?? "", + labels: [...(input.labels ?? [])], + assignees: [...(input.assignees ?? [])], + }) + .pipe(Effect.mapError(failed("Could not file the issue"))); + yield* noteReference({ + ...issueReference({ ...scope, key: created.key }), + title: input.title, + url: created.url, + state: "open", + }); + return created; + }), + }, + pullRequests: { + list: Effect.fn("WorkflowForge.pullRequests.list")(function* (query) { + const result = yield* pullRequests + .list({ + projectId: yield* projectIdOf(query.project), + state: query.state ?? "open", + ...(query.query === undefined ? {} : { query: query.query }), + ...(query.limit === undefined ? {} : { limit: query.limit }), + }) + .pipe(Effect.mapError(failed("Could not list pull requests"))); + const problem = result.errors[0]; + if (result.entries.length === 0 && problem !== undefined) { + return yield* new WorkflowForgeError({ + reason: `Could not list pull requests: ${problem.message}`, + }); + } + return result.entries; + }), + read: Effect.fn("WorkflowForge.pullRequests.read")(function* (pullRequest) { + const ref = yield* pullRequestRef(pullRequest); + // Fresh, not a held copy: checks that passed before a push must not end a wait after it. + const detail = yield* pullRequests + .detail({ ...ref, allowStale: false }) + .pipe(Effect.mapError(failed("Could not read the pull request"))); + yield* pullRequestTouched(ref, detail); + return detail; + }), + comment: Effect.fn("WorkflowForge.pullRequests.comment")(function* (pullRequest, body) { + const ref = yield* pullRequestRef(pullRequest); + yield* pullRequests + .comment({ ...ref, body }) + .pipe(Effect.mapError(failed("Could not comment on the pull request"))); + yield* pullRequestTouched(ref, seenOf(pullRequest)); + }), + act: Effect.fn("WorkflowForge.pullRequests.act")(function* (pullRequest, action, options) { + const ref = yield* pullRequestRef(pullRequest); + yield* pullRequests + .runAction({ + ...ref, + action, + ...(options?.mergeMethod === undefined ? {} : { mergeMethod: options.mergeMethod }), + }) + .pipe(Effect.mapError(failed(`Could not ${action} the pull request`))); + yield* pullRequestTouched(ref, seenOf(pullRequest)); + }), + }, + }); + }), +); diff --git a/apps/server/src/workflows/WorkflowRuntime.test.ts b/apps/server/src/workflows/WorkflowRuntime.test.ts new file mode 100644 index 0000000000000..344e6d871efd9 --- /dev/null +++ b/apps/server/src/workflows/WorkflowRuntime.test.ts @@ -0,0 +1,464 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Queue from "effect/Queue"; +import * as Path from "effect/Path"; +import * as PlatformError from "effect/PlatformError"; +import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; + +import WorkflowsMigration from "../persistence/Migrations/110_Workflows.ts"; +import { WorkflowAgents } from "./WorkflowAgents.ts"; +import * as WorkflowEngine from "./WorkflowEngine.ts"; +import * as WorkflowRuntime from "./WorkflowRuntime.ts"; +import { engineTag, type WorkflowDefinition } from "./workflow.ts"; +import * as Workflows from "./Workflows.ts"; + +/** Waits to be let go. */ +const hold = `T3.workflow("hold", { version: 1, payload: Schema.Struct({}), returns: Schema.String }, () => + Effect.map(T3.wait("go", { returns: Schema.String }), (said) => Option.getOrElse(said, () => "nobody")), +); +`; +const greet = (says: string) => `const { workflow } = T3; +workflow("greet", { version: 1, payload: Schema.Struct({}), returns: Schema.String }, () => + Effect.succeed(${JSON.stringify(says)}), +); +`; + +/** + * A folder holding `hold.ts`, and the workflow runtime over it on a fresh database. `engine` + * stands in for the real one, which needs the clock to run for as long as it is up. + */ +const setup = Effect.fn("setup")(function* ( + wrap: (fileSystem: FileSystem.FileSystem) => FileSystem.FileSystem = (fileSystem) => fileSystem, + engine?: (definitions: ReadonlyArray) => Layer.Layer, +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-workflow-defs-" }); + const directory = path.join(home, "workflows"); + const at = (name: string) => path.join(directory, name); + yield* fileSystem.makeDirectory(directory); + yield* fileSystem.writeFileString(at("hold.ts"), hold); + const database = NodeSqliteClient.layer({ filename: path.join(home, "state.sqlite") }); + yield* Effect.provide(WorkflowsMigration, database); + const made = WorkflowRuntime.make( + Effect.succeed( + (definitions: ReadonlyArray) => + engine?.(definitions) ?? + WorkflowEngine.layer(definitions).pipe( + Layer.provide(Layer.mock(WorkflowAgents)({})), + Layer.provide(database), + Layer.provide(NodeCrypto.layer), + ), + ), + directory, + Effect.succeed(true), + ).pipe(Effect.provideService(FileSystem.FileSystem, wrap(fileSystem))); + return { fileSystem, at, directory, made, runtime: Layer.effectContext(made) }; +}); + +it.effect( + "every file in the folder defines workflows, and a saved file is verified before it runs", + () => + Effect.gen(function* () { + const { fileSystem, at, runtime } = yield* setup(); + + yield* Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const definitions = yield* WorkflowRuntime.WorkflowDefinitions; + const held = yield* workflows.start("hold", {}, { idempotencyKey: "h" }); + yield* workflows.waitFor(held.runId, (run) => run.status === "waiting"); + + // A file that does not parse is not written, and says where it breaks. + const broken = yield* definitions.save("greet.ts", "T3.workflow(\n 'x',\n];\n"); + assert.isFalse(broken.changed); + assert.deepStrictEqual( + broken.problems.map((problem) => [problem.file, problem.line]), + [["greet.ts", 3]], + ); + // Nor is one that defines what another file already does, or drops what a run needs. + const twice = yield* definitions.save("again.ts", hold); + assert.include( + twice.problems[0]?.message ?? "", + "hold@1 is defined twice, in again.ts and hold.ts", + ); + const dropped = yield* definitions.save("hold.ts", greet("hello")); + assert.include( + dropped.problems[0]?.message ?? "", + "hold@1 is no longer defined, and 1 of its runs", + ); + // Nor one that exports something shaped like a workflow without what the engine walks. + const shaped = yield* definitions.save( + "shaped.ts", + 'export default [{ name: "shaped", version: 1, body: () => Effect.void }];\n', + ); + assert.include(shaped.problems[0]?.message ?? "", "is not a workflow"); + // Nor one with an option nothing reads, or a time a schedule cannot fire at. + const misspelt = yield* definitions.save( + "misspelt.ts", + 'T3.workflow("misspelt", { version: 1, payload: Schema.Struct({}), retries: 2 }, () => Effect.void);\n', + ); + assert.include(misspelt.problems[0]?.message ?? "", "does not take `retries`"); + const late = yield* definitions.save( + "late.ts", + 'T3.workflow("late", { version: 1, payload: T3.Tick, triggers: [T3.daily("9am")] }, () => Effect.void);\n', + ); + assert.include(late.problems[0]?.message ?? "", "24-hour time"); + const banana = yield* definitions.save( + "banana.ts", + 'T3.workflow("banana", { version: 1, payload: T3.Tick, triggers: [T3.every("banana")] }, () => Effect.void);\n', + ); + assert.include(banana.problems[0]?.message ?? "", 'Write one such as "5 minutes"'); + const twoHooks = yield* definitions.save( + "hooks.ts", + 'T3.workflow("hooks", { version: 1, payload: T3.WebhookRequest, triggers: [T3.webhook("in"), T3.webhook("in")] }, () => Effect.void);\n', + ); + assert.include(twoHooks.problems[0]?.message ?? "", 'two hooks named "in"'); + assert.include((yield* definitions.remove("hold.ts")).problems[0]?.message ?? "", "hold@1"); + assert.deepStrictEqual( + (yield* definitions.read).files.map((file) => file.name), + ["hold.ts"], + ); + // The same change made outside the app is refused as a whole: the file still reads as the + // version that runs, until it is put back. + const told = (wanted: boolean) => + workflows.watch.pipe( + Stream.filter((snapshot) => (snapshot.definition?.problem != null) === wanted), + Stream.runHead, + ); + yield* fileSystem.writeFileString(at("hold.ts"), greet("hello")); + yield* told(true); + assert.deepStrictEqual( + (yield* definitions.read).files.map((file) => file.workflows), + [["hold@1"]], + ); + // Only that file is held back: another file's change still runs, and the held one says why. + const other = + 'T3.workflow("other", { version: 1, payload: Schema.Struct({}) }, () => Effect.void);\n'; + // A file the folder's naming leaves out says so, instead of never running without a word. + yield* fileSystem.writeFileString(at("my flow.ts"), other); + assert.deepStrictEqual(yield* definitions.save("other.ts", other), { + changed: true, + problems: [], + }); + yield* workflows.start("other", {}, { idempotencyKey: "o" }); + assert.deepStrictEqual( + (yield* definitions.read).files.map((file) => [file.name, file.problems.length]), + [ + ["hold.ts", 1], + ["other.ts", 0], + ], + ); + assert.deepStrictEqual( + (yield* definitions.read).problems.map((problem) => problem.file), + ["my flow.ts"], + ); + yield* fileSystem.remove(at("my flow.ts")); + assert.deepStrictEqual(yield* definitions.remove("other.ts"), { + changed: true, + problems: [], + }); + yield* fileSystem.writeFileString(at("hold.ts"), hold); + yield* told(false); + + // A new file that passes is there from now on, and what it defines can be started. + const saved = { changed: true, problems: [] }; + assert.deepStrictEqual(yield* definitions.save("greet.ts", greet("hello")), saved); + assert.equal(yield* fileSystem.readFileString(at("greet.ts")), greet("hello")); + const greeted = yield* workflows.start("greet", {}, { idempotencyKey: "g" }); + const done = yield* workflows.waitFor(greeted.runId, (run) => run.status === "completed"); + assert.equal(done.result, "hello"); + // The run that was waiting came through the reload and can still be let go. + yield* workflows.signal({ runId: held.runId, wait: "go" }, "go on", { id: "s1" }); + const freed = yield* workflows.waitFor(held.runId, (run) => run.status === "completed"); + assert.equal(freed.result, "go on"); + + // Someone breaks a file outside the app: its last good version keeps running, and the + // other files go on changing. + const problem = (wanted: boolean) => + workflows.watch.pipe( + Stream.filter((snapshot) => (snapshot.definition?.problem != null) === wanted), + Stream.runHead, + ); + yield* fileSystem.writeFileString(at("greet.ts"), "T3.workflow("); + yield* problem(true); + const read = yield* definitions.read; + assert.deepStrictEqual( + read.files.map((file) => [file.name, file.problems.length]), + [ + ["greet.ts", 1], + ["hold.ts", 0], + ], + ); + const still = yield* workflows.start("greet", {}, { idempotencyKey: "g2" }); + assert.equal( + (yield* workflows.waitFor(still.runId, (run) => run.status === "completed")).result, + "hello", + ); + // And fixes it, saying something else, this time as the file's one default export. + yield* fileSystem.writeFileString( + at("greet.ts"), + greet("hi").replace("\nworkflow(", "\nexport default workflow("), + ); + yield* problem(false); + const fixed = yield* workflows.start("greet", {}, { idempotencyKey: "g3" }); + assert.equal( + (yield* workflows.waitFor(fixed.runId, (run) => run.status === "completed")).result, + "hi", + ); + // A file taken away takes its workflows with it. + assert.deepStrictEqual(yield* definitions.remove("greet.ts"), saved); + const gone = yield* workflows + .start("greet", {}, { idempotencyKey: "g4" }) + .pipe(Effect.flip); + assert.equal(gone._tag, "WorkflowNotRegisteredError"); + // With no file left, nothing runs, and the runs that ended can still be read. + assert.deepStrictEqual(yield* definitions.remove("hold.ts"), saved); + assert.equal((yield* workflows.get(held.runId)).run.status, "completed"); + assert.includeMembers( + (yield* workflows.list()).map((run) => run.runId), + [held.runId, greeted.runId], + ); + }).pipe( + Effect.provide(runtime), + Effect.scoped, + Effect.raceFirst(Effect.forever(TestClock.adjust("1 second"))), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect( + "a folder that cannot be listed keeps its workflows and is looked at again, and an engine that cannot start leaves the last one running", + () => + Effect.gen(function* () { + let refuse = false; + // What each engine was built to run. One that registers `broken` does not come up. + const builds: Array> = []; + // No file events: only the runtime's own retry can pick up what changed. + const { at, fileSystem, runtime } = yield* setup( + (real) => ({ + ...real, + exists: (target) => + refuse + ? Effect.fail( + PlatformError.systemError({ + _tag: "PermissionDenied", + module: "FileSystem", + method: "exists", + pathOrDescriptor: target, + }), + ) + : real.exists(target), + watch: () => Stream.never, + }), + (definitions) => + definitions.some((definition) => definition.name === "broken") + ? Layer.effect(Workflows.Workflows, Effect.die(new Error("broken took it down"))) + : Layer.sync(Workflows.Workflows, () => { + builds.push(definitions.map(engineTag)); + return Workflows.disabled; + }), + ); + + yield* Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const definitions = yield* WorkflowRuntime.WorkflowDefinitions; + const revision = Effect.map( + Stream.runHead(workflows.watch), + (snapshot) => Option.getOrThrow(snapshot).definition?.revision ?? 0, + ); + refuse = true; + // Written, but the folder could not be listed, so it is not said to run. + const unlisted = yield* definitions.save("greet.ts", greet("hi")); + assert.isTrue(unlisted.changed); + assert.include(unlisted.problems[0]?.message ?? "", "could not be read"); + // What was loaded stays, and greet is not taken in yet. + assert.deepStrictEqual(builds, [["hold@1"]]); + const before = yield* revision; + refuse = false; + yield* TestClock.adjust("30 seconds"); + yield* workflows.watch.pipe( + Stream.filter((snapshot) => (snapshot.definition?.revision ?? 0) > before), + Stream.runHead, + ); + assert.deepStrictEqual(builds.at(-1), ["greet@1", "hold@1"]); + + // A definition that passes the checks but takes the engine down at start changes nothing. + yield* fileSystem.writeFileString( + at("broken.ts"), + 'T3.workflow("broken", { version: 1, payload: Schema.Struct({}) }, () => Effect.void);\n', + ); + const fellBack = yield* definitions.save("greet.ts", greet("hello")); + assert.isTrue(fellBack.changed); + assert.include(fellBack.problems[0]?.message ?? "", "did not start"); + assert.deepStrictEqual(builds.slice(1), [ + ["greet@1", "hold@1"], + ["greet@1", "hold@1"], + ]); + assert.include( + (yield* Stream.runHead(workflows.watch)).pipe(Option.getOrThrow).definition?.problem ?? + "", + "did not start", + ); + }).pipe(Effect.provide(runtime), Effect.scoped); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a file that never finishes loading is given up on, and later files still load", () => + Effect.gen(function* () { + const { at, fileSystem } = yield* setup(); + yield* fileSystem.writeFileString(at("stuck.ts"), "await new Promise(() => {});\n"); + yield* fileSystem.writeFileString(at("greet.ts"), greet("hi")); + const stuck = yield* WorkflowRuntime.loadDefinitions(at("stuck.ts"), 0, 50).pipe(Effect.flip); + assert.include(String(stuck.cause), "did not finish loading"); + const loaded = yield* WorkflowRuntime.loadDefinitions(at("greet.ts")); + assert.deepStrictEqual( + loaded.map((definition) => definition.name), + ["greet"], + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a file given up on registers nothing into the file that loads after it", () => + Effect.gen(function* () { + const { at, fileSystem } = yield* setup(); + yield* fileSystem.writeFileString( + at("slow.ts"), + 'await new Promise((resolve) => { globalThis.t3TestResume = resolve; });\nT3.workflow("slow", { version: 1, payload: Schema.Struct({}) }, () => Effect.void);\n', + ); + // The second file goes on loading until the first one's top level has run to its end. + yield* fileSystem.writeFileString( + at("next.ts"), + `${greet("hi")}globalThis.t3TestResume();\nawait new Promise((resolve) => setImmediate(resolve));\n`, + ); + yield* WorkflowRuntime.loadDefinitions(at("slow.ts"), 0, 50).pipe(Effect.flip); + const loaded = yield* WorkflowRuntime.loadDefinitions(at("next.ts")); + assert.deepStrictEqual( + loaded.map((definition) => definition.name), + ["greet"], + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +// Vitest's module runner loads a file its own way; only Node keeps a CommonJS file by its path. +it.live("a file without imports or exports loads again after it changes", () => + Effect.gen(function* () { + const { at, fileSystem } = yield* setup(); + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + yield* fileSystem.writeFileString(at("greet.ts"), greet("hi")); + const twice = ` + import * as NodeFS from "node:fs"; + import * as NodeServices from "@effect/platform-node/NodeServices"; + import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; + import { loadDefinitions } from ${JSON.stringify(new URL("./WorkflowRuntime.ts", import.meta.url).href)}; + const file = process.argv.at(-1); + const program = Effect.gen(function* () { + const first = yield* loadDefinitions(file, 1); + NodeFS.writeFileSync(file, NodeFS.readFileSync(file, "utf8").replace('"hi"', '"hello"')); + const second = yield* loadDefinitions(file, 2); + return [first.length, second.length]; + }); + console.log(JSON.stringify(await Effect.runPromise(Effect.provide(program, NodeServices.layer)))); + `; + const child = yield* spawner.spawn( + ChildProcess.make( + process.execPath, + ["--input-type=module", "--eval", twice, at("greet.ts")], + { cwd: import.meta.dirname }, + ), + ); + const [stdout, stderr] = yield* Effect.all( + [ + child.stdout.pipe(Stream.decodeText(), Stream.mkString), + child.stderr.pipe(Stream.decodeText(), Stream.mkString), + ], + { concurrency: "unbounded" }, + ); + assert.equal(stdout.trim(), "[1,1]", stderr); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a change held back by a run goes in once that run ends, with no further edit", () => + Effect.gen(function* () { + // The folder's changes are told by hand, so the test does not hang on a watcher starting. + const changed = yield* Queue.unbounded(); + const { fileSystem, at, runtime } = yield* setup((fileSystem) => ({ + ...fileSystem, + watch: () => Stream.fromQueue(changed), + })); + yield* Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const definitions = yield* WorkflowRuntime.WorkflowDefinitions; + const held = yield* workflows.start("hold", {}, { idempotencyKey: "h" }); + yield* workflows.waitFor(held.runId, (run) => run.status === "waiting"); + const problem = (wanted: boolean) => + workflows.watch.pipe( + Stream.filter((snapshot) => (snapshot.definition?.problem != null) === wanted), + Stream.runHead, + ); + yield* fileSystem.writeFileString(at("hold.ts"), greet("hello")); + yield* Queue.offer(changed, { _tag: "Update", path: at("hold.ts") }); + yield* problem(true); + yield* workflows.signal({ runId: held.runId, wait: "go" }, "go on", { id: "s1" }); + yield* workflows.waitFor(held.runId, (run) => run.status === "completed"); + // Nothing is told of the folder now: the held change goes in on its own. + yield* problem(false); + assert.deepStrictEqual( + (yield* definitions.read).files.map((file) => file.workflows), + [["greet@1"]], + ); + }).pipe( + Effect.provide(runtime), + Effect.scoped, + Effect.raceFirst(Effect.forever(TestClock.adjust("1 second"))), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect( + "workflows are off until turned on, and a run left waiting when they are turned off goes on once they are on again", + () => + Effect.gen(function* () { + const { fileSystem, at, directory, made } = yield* setup(); + // Its top level counts the times it was loaded. + yield* fileSystem.writeFileString( + at("counted.ts"), + "globalThis.t3GatedLoads = (globalThis.t3GatedLoads ?? 0) + 1;\nexport default [];\n", + ); + const loads = () => (globalThis as { t3GatedLoads?: number }).t3GatedLoads ?? 0; + yield* Effect.gen(function* () { + const { turn, context } = yield* WorkflowRuntime.gate(made, directory); + const workflows = Context.get(context, Workflows.Workflows); + const definitions = Context.get(context, WorkflowRuntime.WorkflowDefinitions); + const start = workflows.start("hold", {}, { idempotencyKey: "h" }); + + assert.equal((yield* Effect.flip(start)).message, Workflows.OFF); + assert.equal((yield* Effect.flip(workflows.list())).message, Workflows.OFF); + assert.deepStrictEqual((yield* definitions.read).files, []); + assert.equal(loads(), 0); + + yield* turn(true); + assert.equal(loads(), 1); + const held = yield* start; + yield* workflows.waitFor(held.runId, (run) => run.status === "waiting"); + + yield* turn(false); + const signal = workflows.signal({ runId: held.runId, wait: "go" }, "go on", { id: "s1" }); + assert.equal((yield* Effect.flip(signal)).message, Workflows.OFF); + + yield* turn(true); + yield* signal; + const freed = yield* workflows.waitFor(held.runId, (run) => run.status === "completed"); + assert.equal(freed.result, "go on"); + }).pipe(Effect.scoped, Effect.raceFirst(Effect.forever(TestClock.adjust("1 second")))); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); diff --git a/apps/server/src/workflows/WorkflowRuntime.ts b/apps/server/src/workflows/WorkflowRuntime.ts new file mode 100644 index 0000000000000..8a7502789189f --- /dev/null +++ b/apps/server/src/workflows/WorkflowRuntime.ts @@ -0,0 +1,978 @@ +// Workflows in the running server: every file in one folder defines some, and the folder can +// change while the server runs. A file that loads replaces what it defined before; one that does +// not keeps its last good version running. With no definitions there is no engine, unless runs +// from before are kept: then one with nothing registered serves their history. +import * as NodeAsyncHooks from "node:async_hooks"; +// @effect-diagnostics-next-line nodeBuiltinImport:off -- the CommonJS cache is cleared in the same tick as the import. +import * as NodeFS from "node:fs"; +import * as NodeModule from "node:module"; +import * as NodeURL from "node:url"; + +import type { + WorkflowDefinitionChangeResult, + WorkflowDefinitionFiles, + WorkflowDefinitionProblem, +} from "@t3tools/contracts"; +import * as Cause from "effect/Cause"; +import * as Config from "effect/Config"; +import * as Context from "effect/Context"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; +import * as Scope from "effect/Scope"; +import * as Semaphore from "effect/Semaphore"; +import * as SqlClient from "effect/sql/SqlClient"; +import * as Stream from "effect/Stream"; +import * as SubscriptionRef from "effect/SubscriptionRef"; + +import * as ServerConfig from "../config.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import { engineTag, text, type WorkflowDefinition } from "./workflow.ts"; +import type * as WorkflowEngine from "./WorkflowEngine.ts"; +import * as WorkflowAgentThreads from "./WorkflowAgentThreads.ts"; +import * as WorkflowForge from "./WorkflowForge.ts"; +import * as Workflows from "./Workflows.ts"; + +/** A folder of definition files, or one file, in place of the folder in the T3 home. */ +const definitionsOverride = Config.String("T3CODE_WORKFLOWS").pipe(Config.option); + +// An editor saves in several writes, and a save from here is followed by its own file event. +const RELOAD_SETTLE = "300 millis"; +// How often a change held back by unfinished runs is tried again, so it goes in once they end. +const HELD_RETRY = "15 seconds"; +// A folder that could not be listed is looked at again, since no file event may follow. +const LIST_RETRY = "30 seconds"; +// A leading dot is how a file is kept out: a draft being checked, an editor's swap file. +// One name in the folder, never a path: the name is also the key a save and a removal go by. +const DEFINITION_FILE = /^[A-Za-z0-9_][\w.-]*\.(ts|mts|js|mjs)$/; +const NAMING = + "Name the file with letters, digits, dashes, underscores and dots, ending in .ts: for example release.ts."; + +export class WorkflowDefinitionsLoadError extends Schema.TaggedError()( + "WorkflowDefinitionsLoadError", + { module: Schema.String, cause: Schema.Defect() }, +) { + override get message(): string { + return `Could not load workflow definitions from ${this.module}.`; + } +} + +/** The definition files of this server, for a person to read and change. */ +export class WorkflowDefinitions extends Context.Service< + WorkflowDefinitions, + { + /** The files as they are on disk now, with what is wrong with them. */ + readonly read: Effect.Effect; + /** + * Verify `source` as the file `name`, and when nothing is wrong write it and run it from now + * on. A file that was written can still fail to run, and then says why. + */ + readonly save: (name: string, source: string) => Effect.Effect; + /** Take a file away, unless runs still need what it defines. */ + readonly remove: (name: string) => Effect.Effect; + } +>()("t3/workflows/WorkflowRuntime/WorkflowDefinitions") {} + +const isDefinition = (value: unknown): value is WorkflowDefinition => + typeof value === "object" && + value !== null && + typeof (value as WorkflowDefinition).name === "string" && + typeof (value as WorkflowDefinition).version === "number" && + typeof (value as WorkflowDefinition).body === "function" && + // The engine walks these at start, and a file can export an object that only looks like one. + Array.isArray((value as WorkflowDefinition).triggers) && + Array.isArray((value as WorkflowDefinition).resumeAfter); + +// The API is handed to a file as globals, which the whole process shares, so files load one at +// a time. A load that was given up on still runs, so `T3.workflow` registers with the load whose +// code calls it, and with none once that load is over. +const loading = Semaphore.makeUnsafe(1); +// A file whose top-level code never settles would otherwise hold every later load. Real time, +// since importing a module is. +const LOAD_DEADLINE_MS = 20_000; + +interface Evaluation { + readonly registered: Array; + open: boolean; +} +const evaluating = new NodeAsyncHooks.AsyncLocalStorage(); +// Counts loads across runtimes: one started again would otherwise get back the modules of the last. +let loads = 0; +const required = NodeModule.createRequire(import.meta.url); + +/** A file with no `import` or `export` loads as CommonJS, which Node keeps by path, not address. */ +const forget = (file: string) => { + delete required.cache[file]; + try { + delete required.cache[NodeFS.realpathSync(file)]; + } catch { + // Gone already, so nothing can be kept under its real path either. + } +}; + +const within = (work: Promise, ms: number): Promise => { + let timer: ReturnType | undefined; + const late = new Promise((resolve) => { + // @effect-diagnostics-next-line globalTimers:off -- an import runs on real time, not a test clock. + timer = setTimeout(resolve, ms, undefined); + }); + return Promise.race([work, late]).finally(() => clearTimeout(timer)); +}; + +const evaluate = async (url: string, evaluation: Evaluation): Promise> => { + const api = await import("./api.ts"); + const { Duration, Effect: effect, Option: option, Schedule, Schema: schema, ...t3 } = api; + const workflow = ((...input: Parameters) => { + const current = evaluating.getStore(); + if (current === undefined || !current.open) { + throw new Error( + "T3.workflow was called after its file finished loading. Call it at the top of the file.", + ); + } + const definition = api.workflow(...input); + current.registered.push(definition); + return definition; + }) as typeof api.workflow; + Object.assign(globalThis, { + T3: { ...t3, workflow }, + Effect: effect, + Schema: schema, + Option: option, + Duration, + Schedule, + }); + const loaded = (await evaluating.run(evaluation, () => import(url))) as { + readonly default?: unknown; + "module.exports"?: unknown; + }; + // A file with no `import` or `export` loads as CommonJS, whose default is its `module.exports`: + // an empty object unless the file set one, which says nothing about what it defines. + const commonJs = "module.exports" in loaded; + const exported = + commonJs && + typeof loaded.default === "object" && + loaded.default !== null && + !Array.isArray(loaded.default) && + Object.keys(loaded.default).length === 0 + ? undefined + : loaded.default; + // One workflow exported by itself is as good as a list of one. + const listed = + exported === undefined + ? [] + : Array.isArray(exported) + ? exported + : isDefinition(exported) + ? [exported] + : undefined; + if (listed === undefined) { + throw new Error( + "The default export is not a workflow or a list of them. Call T3.workflow(…), or export what it returned.", + ); + } + return [...new Set([...evaluation.registered, ...listed])]; +}; + +/** + * The workflows a file defines: every `T3.workflow(…)` it calls, and any list it exports. + * `load` tells one loading of a file from the next: Node keeps a module by its address, so the + * same address would give back the file as it was the first time. + */ +export const loadDefinitions = Effect.fn("WorkflowRuntime.loadDefinitions")(function* ( + module: string, + load = 0, + deadlineMs = LOAD_DEADLINE_MS, +) { + const path = yield* Path.Path; + const file = path.resolve(module); + const url = NodeURL.pathToFileURL(file).href + (load === 0 ? "" : `?${load}`); + const definitions = yield* Effect.tryPromise({ + try: () => { + const evaluation: Evaluation = { registered: [], open: true }; + forget(file); + return within(evaluate(url, evaluation), deadlineMs).finally(() => { + evaluation.open = false; + forget(file); + }); + }, + catch: (cause) => new WorkflowDefinitionsLoadError({ module, cause }), + }).pipe(loading.withPermits(1)); + if (definitions === undefined) { + return yield* new WorkflowDefinitionsLoadError({ + module, + cause: `It did not finish loading within ${deadlineMs / 1000} seconds. Something at the top of the file waits for good.`, + }); + } + if (!definitions.every(isDefinition)) { + return yield* new WorkflowDefinitionsLoadError({ + module, + cause: "Something it exports is not a workflow. Export only what `T3.workflow` returned.", + }); + } + return definitions; +}); + +/** What a load error says, with the line of `file` it points at when it names one. */ +const loadProblem = ( + error: WorkflowDefinitionsLoadError, + loadedFrom: string, + file: string, +): WorkflowDefinitionProblem => { + const cause = error.cause; + const stack = cause instanceof Error ? (cause.stack ?? "") : ""; + const name = loadedFrom.split(/[\\/]/).at(-1) ?? loadedFrom; + // Node names the place as `file:///…/name.ts:12` or `…/name.ts:12:5`, with a `?n` when reloaded. + const at = stack.split(name).find((rest) => /^(\?\d+)?:\d+/.test(rest)); + const line = at === undefined ? undefined : Number(/^(?:\?\d+)?:(\d+)/.exec(at)?.[1]); + return { message: text(cause), file, ...(line === undefined ? {} : { line }) }; +}; + +/** + * What is wrong between files that each loaded, given the runs that have not ended, with the + * files that could each be the cause. + */ +const definitionProblems = ( + files: ReadonlyArray<{ + readonly name: string; + readonly definitions: ReadonlyArray; + }>, + unfinished: ReadonlyArray<{ readonly workflow: string; readonly version: number }>, + before: ReadonlyMap> = new Map(), +): ReadonlyArray<{ + readonly problem: WorkflowDefinitionProblem; + readonly files: ReadonlyArray; + readonly clash: boolean; +}> => { + const where = new Map>(); + for (const file of files) { + for (const definition of file.definitions) { + where.set(engineTag(definition), [...(where.get(engineTag(definition)) ?? []), file.name]); + } + } + const waiting = new Map(); + for (const run of unfinished) { + const tag = engineTag({ name: run.workflow, version: run.version }); + if (!where.has(tag)) waiting.set(tag, (waiting.get(tag) ?? 0) + 1); + } + return [ + ...[...where] + .filter(([, names]) => names.length > 1) + .map(([tag, names]) => ({ + problem: { + message: `${tag} is defined twice, in ${[...new Set(names)].join(" and ")}. A workflow's name and version name one body.`, + }, + files: [...new Set(names)], + clash: true, + })), + ...[...waiting].map(([tag, runs]) => ({ + problem: { + message: `${tag} is no longer defined, and ${runs} of its runs ${runs === 1 ? "has" : "have"} not ended. Keep that version until they end, or cancel them first.`, + }, + files: [...before] + .filter(([, definitions]) => + definitions.some((definition) => engineTag(definition) === tag), + ) + .map(([name]) => name), + clash: false, + })), + ]; +}; + +/** + * `engine` gives the layer that runs a set of definitions. It is asked for only once there is + * something to run or `kept` says there are runs to read, since the engine's modules are not worth + * loading for nothing. `where` is the folder of definition files, or one file. + */ +export const make = Effect.fn("WorkflowRuntime.make")(function* ( + engine: Effect.Effect< + (definitions: ReadonlyArray) => Layer.Layer + >, + where: string, + kept: Effect.Effect, +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const target = path.resolve(where); + const single = DEFINITION_FILE.test(path.basename(target)); + const directory = single ? path.dirname(target) : target; + yield* Effect.ignore(fileSystem.makeDirectory(directory, { recursive: true })); + const outer = yield* Scope.Scope; + const services = yield* Effect.context(); + + // One reload at a time, and callers during one wait for the engine that comes out of it. + const lock = yield* Semaphore.make(1); + let ready = Deferred.makeUnsafe(); + let engineScope: Scope.Closeable | undefined; + let running: ReadonlyArray = []; + let imported = false; + /** Each file as it was last looked at, so one that did not change is not loaded again. */ + const seen = new Map(); + /** The last version of each file that loaded, which runs while a newer one does not. */ + const good = new Map>(); + /** Files that loaded or went away since, kept apart until the change as a whole is taken. */ + const pending = new Map | null>(); + const broken = new Map(); + /** Files whose change clashes with another file or drops what a run needs, and why. */ + const held = new Map>(); + let between: ReadonlyArray = []; + /** Code files in the folder that are not loaded because of their name. */ + let misnamed: ReadonlyArray = []; + let retrying = false; + let unstarted = false; + const state = yield* SubscriptionRef.make<{ revision: number; problem: string | null }>({ + revision: 0, + problem: null, + }); + const told = (problem: WorkflowDefinitionProblem) => + problem.file === undefined ? problem.message : `${problem.file}: ${problem.message}`; + const report = Effect.suspend(() => { + const problems = [...broken.values(), ...[...held.values()].flat(), ...misnamed, ...between]; + return SubscriptionRef.update(state, (current) => ({ + revision: current.revision + 1, + problem: problems.length === 0 ? null : problems.map(told).join("\n"), + })); + }); + + /** Every name in the folder, or the one file. */ + const entries = Effect.gen(function* () { + if (single) { + return (yield* fileSystem.exists(target)) ? [path.basename(target)] : []; + } + // A folder that is not there yet is empty. One that cannot be read just now is not: it + // fails, and what was loaded stays. + if (!(yield* fileSystem.exists(directory))) return []; + return (yield* fileSystem.readDirectory(directory)).toSorted(); + }); + const definitionNames = (all: ReadonlyArray) => + all.filter((entry) => DEFINITION_FILE.test(entry)); + const names = Effect.map(entries, definitionNames); + + /** A fresh engine for these definitions in its own scope, or the failure that stopped it. */ + const build = Effect.fn("WorkflowRuntime.build")(function* ( + definitions: ReadonlyArray, + ) { + const scope = yield* Scope.fork(outer); + const layerEngine = yield* engine; + imported = true; + const built = yield* Effect.suspend(() => + Layer.buildWithScope(layerEngine(definitions), scope), + ).pipe(Effect.provideContext(services), Effect.exit); + if (Exit.isFailure(built)) yield* Scope.close(scope, Exit.void); + else engineScope = scope; + return built; + }); + + const boot = Effect.fn("WorkflowRuntime.boot")( + function* (definitions: ReadonlyArray) { + const next = Deferred.makeUnsafe(); + ready = next; + const previous = running; + if (engineScope !== undefined) yield* Scope.close(engineScope, Exit.void); + engineScope = undefined; + running = []; + if (definitions.length === 0 && !imported && !(yield* kept)) { + yield* Deferred.succeed(next, Workflows.disabled); + return null; + } + const built = yield* build(definitions); + if (Exit.isSuccess(built)) { + running = definitions; + yield* Deferred.succeed(next, Context.get(built.value, Workflows.Workflows)); + if (definitions.length > 0) { + yield* Effect.logInfo("Workflows registered", { + directory, + workflows: definitions.map(engineTag), + }); + } + return null; + } + // What ran before comes back, so definitions that cannot start take nothing down. + const restored = yield* build(previous); + if (Exit.isSuccess(restored)) { + running = previous; + yield* Deferred.succeed(next, Context.get(restored.value, Workflows.Workflows)); + } else { + // Nobody may be left waiting on an engine that never came up. + yield* Deferred.succeed(next, Workflows.disabled); + } + return `The workflow engine did not start: ${text(Cause.squash(built.cause))}`; + }, + // Once `ready` is replaced it must be settled, or every caller waits on it for good. + Effect.uninterruptible, + ); + + const unfinished = Effect.suspend(() => + running.length === 0 + ? Effect.succeed([]) + : Effect.flatMap(Deferred.await(ready), (service) => service.unfinished), + ); + /** The workflows the file at `from` defines, or what is wrong with it as the file `name`. */ + const load = Effect.fn("WorkflowRuntime.load")(function* (from: string, name: string) { + const definitions = yield* loadDefinitions(from, ++loads).pipe( + Effect.provideContext(services), + Effect.result, + ); + return definitions._tag === "Failure" + ? ({ problem: loadProblem(definitions.failure, from, name) } as const) + : ({ definitions: definitions.success } as const); + }); + /** What would run with these files, in the folder's order. */ + const gathered = (files: ReadonlyMap>) => + [...files] + .toSorted(([left], [right]) => left.localeCompare(right)) + .map(([name, definitions]) => ({ name, definitions })); + + // Set once `reload` exists, which it schedules again; the indirection keeps its type inferred. + let retryLater: Effect.Effect = Effect.void; + /** Take in what changed in the folder, and run the result unless something is wrong with it. */ + const reload = Effect.fn("WorkflowRuntime.reload")(function* () { + const listed = yield* Effect.option(entries); + if (Option.isNone(listed)) { + yield* Effect.logWarning( + "The workflows folder could not be read; its workflows stay as they are", + ); + yield* retryLater; + return false; + } + const present = definitionNames(listed.value); + // A leading dot keeps a file out on purpose; any other code file left out is a surprise. + const wasMisnamed = misnamed; + misnamed = listed.value + .filter((entry) => /^[^.].*\.(ts|mts|js|mjs)$/.test(entry) && !DEFINITION_FILE.test(entry)) + .map((entry) => ({ message: `It is not loaded. ${NAMING}`, file: entry })); + const renamed = + misnamed.map((problem) => problem.file).join("/") !== + wasMisnamed.map((problem) => problem.file).join("/"); + let changed = false; + for (const problem of misnamed) { + if (!wasMisnamed.some((known) => known.file === problem.file)) { + yield* Effect.logWarning( + "A file in the workflows folder is not loaded because of its name", + problem, + ); + } + } + for (const name of present) { + const file = path.join(directory, name); + const source = yield* fileSystem.readFileString(file).pipe(Effect.option); + if (Option.isNone(source) || seen.get(name) === source.value) continue; + seen.set(name, source.value); + changed = true; + const loaded = yield* load(file, name); + if (loaded.definitions === undefined) { + broken.set(name, loaded.problem); + pending.delete(name); + yield* Effect.logWarning("A workflow definitions file was not loaded", loaded.problem); + continue; + } + broken.delete(name); + pending.set(name, loaded.definitions); + } + for (const name of [...seen.keys()].filter((known) => !present.includes(known))) { + seen.delete(name); + pending.set(name, null); + broken.delete(name); + changed = true; + } + // Asked again while something stands between files: the runs that held a version may be over. + if (!changed && between.length === 0 && held.size === 0) { + if (renamed) yield* report; + return true; + } + const runs = yield* unfinished; + // A change that clashes is held back like a file that does not load: that file keeps its last + // good version, a new one stays out, and every other change is taken. + held.clear(); + let next = new Map(good); + let problems: ReturnType = []; + let blamed = true; + while (blamed) { + blamed = false; + next = new Map(good); + for (const [name, definitions] of pending) { + if (held.has(name)) continue; + if (definitions === null) next.delete(name); + else next.set(name, definitions); + } + problems = definitionProblems(gathered(next), runs, good); + for (const { problem, files: involved, clash } of problems) { + const changing = involved.filter((name) => pending.has(name) && !held.has(name)); + // Between new files that define the same workflow, the first in the folder's order stays. + const culprits = + clash && changing.length === involved.length ? changing.slice(1) : changing; + for (const name of culprits) { + held.set(name, [...(held.get(name) ?? []), { ...problem, file: name }]); + blamed = true; + } + } + } + if (held.size > 0) { + yield* Effect.logWarning("Some workflow definition changes were not taken", { + problems: [...held.values()].flat(), + }); + } + // What is left was so before any of these changes, so it holds none of them back. + const standing = problems.map((entry) => entry.problem); + if (standing.length > 0) { + yield* Effect.logWarning("Workflow definitions have problems", { problems: standing }); + } + const taking = [...pending.keys()].filter((name) => !held.has(name)); + // An engine that did not start is tried again, as the runs it tripped on may have ended. + if (taking.length === 0 && !unstarted) { + between = standing; + yield* report; + return true; + } + good.clear(); + for (const [name, definitions] of next) good.set(name, definitions); + for (const name of taking) pending.delete(name); + const failed = yield* boot(gathered(next).flatMap((file) => file.definitions)); + unstarted = failed !== null; + between = failed === null ? standing : [...standing, { message: failed }]; + yield* report; + return true; + }); + + retryLater = Effect.suspend(() => { + if (retrying) return Effect.void; + retrying = true; + return Effect.suspend(() => { + retrying = false; + return lock.withPermits(1)(reload()); + }).pipe( + Effect.delay(LIST_RETRY), + Effect.catchCause((cause) => + Effect.logWarning("Reloading workflow definitions failed", Cause.pretty(cause)), + ), + Effect.forkIn(outer), + Effect.asVoid, + ); + }); + + yield* lock.withPermits(1)(reload()); + // No file defines anything yet, though runs kept from before may still be read. + if (!(yield* Deferred.isDone(ready))) yield* boot([]); + + // The folder, not a file: an editor that saves by renaming replaces the file it was watching. + yield* fileSystem.watch(directory).pipe( + Stream.debounce(RELOAD_SETTLE), + Stream.runForEach(() => + lock + .withPermits(1)(reload()) + .pipe( + Effect.catchCause((cause) => + Effect.logWarning("Reloading workflow definitions failed", Cause.pretty(cause)), + ), + ), + ), + Effect.catchCause((cause) => + Effect.logWarning("Workflow definitions are not watched for changes", Cause.pretty(cause)), + ), + Effect.forkIn(outer), + ); + + yield* Effect.sleep(HELD_RETRY).pipe( + Effect.andThen( + Effect.suspend(() => (held.size > 0 ? lock.withPermits(1)(reload()) : Effect.void)), + ), + Effect.catchCause((cause) => + Effect.logWarning("Reloading workflow definitions failed", Cause.pretty(cause)), + ), + Effect.forever, + Effect.forkIn(outer), + ); + + const current = Effect.suspend(() => Deferred.await(ready)); + // A watcher outlives the engine it began on: each reload hands it the next one's stream. + const followed = (pick: (service: Workflows.Workflows["Service"]) => Stream.Stream) => + SubscriptionRef.changes(state).pipe( + Stream.switchMap((at) => + Stream.unwrap(Effect.map(current, pick)).pipe(Stream.map((value) => [value, at] as const)), + ), + ); + const service = Workflows.Workflows.of({ + start: Effect.fn("Workflows.start")(function* (...input) { + return yield* (yield* current).start(...input); + }), + signal: Effect.fn("Workflows.signal")(function* (...input) { + return yield* (yield* current).signal(...input); + }), + answer: Effect.fn("Workflows.answer")(function* (...input) { + return yield* (yield* current).answer(...input); + }), + resume: Effect.fn("Workflows.resume")(function* (...input) { + return yield* (yield* current).resume(...input); + }), + cancel: Effect.fn("Workflows.cancel")(function* (...input) { + return yield* (yield* current).cancel(...input); + }), + get: Effect.fn("Workflows.get")(function* (...input) { + return yield* (yield* current).get(...input); + }), + list: Effect.fn("Workflows.list")(function* (...input) { + return yield* (yield* current).list(...input); + }), + waitFor: Effect.fn("Workflows.waitFor")(function* (...input) { + // A reload replaces the engine, and a wait on the old one would never hear of the run again. + while (true) { + // Noted before the engine is read, so a reload that lands in between is still heard of. + const { revision } = yield* SubscriptionRef.get(state); + const live = yield* current; + const reloaded = SubscriptionRef.changes(state).pipe( + Stream.filter((at) => at.revision !== revision), + Stream.runHead, + ); + const waited = yield* live + .waitFor(...input) + .pipe(Effect.asSome, Effect.raceFirst(Effect.as(reloaded, Option.none()))); + if (Option.isSome(waited)) return waited.value; + } + }), + questions: Effect.flatMap(current, (live) => live.questions), + unfinished: Effect.flatMap(current, (live) => live.unfinished), + hooks: Effect.flatMap(current, (live) => live.hooks), + deliver: Effect.fn("Workflows.deliver")(function* (...input) { + return yield* (yield* current).deliver(...input); + }), + stored: Effect.fn("Workflows.stored")(function* (...input) { + return yield* (yield* current).stored(...input); + }), + storeSet: Effect.fn("Workflows.storeSet")(function* (...input) { + return yield* (yield* current).storeSet(...input); + }), + storeDelete: Effect.fn("Workflows.storeDelete")(function* (...input) { + return yield* (yield* current).storeDelete(...input); + }), + watch: followed((live) => live.watch).pipe( + Stream.map(([snapshot, at]) => ({ ...snapshot, definition: at })), + ), + counts: followed((live) => live.counts).pipe(Stream.map(([counts]) => counts)), + sweep: Effect.flatMap(current, (live) => live.sweep), + }); + + const alone = { message: `This server reads its workflows from ${target} alone.` }; + /** Why `name` cannot be a file here, if it cannot. */ + const refused = (name: string): WorkflowDefinitionProblem | undefined => + single && name !== path.basename(target) + ? alone + : DEFINITION_FILE.test(name) + ? undefined + : { message: NAMING }; + /** What is wrong with the folder once `change` is made to the files that load. */ + const wouldBreak = Effect.fn("WorkflowRuntime.wouldBreak")(function* ( + change: (files: Map>) => void, + ) { + const files = new Map(good); + change(files); + return definitionProblems(gathered(files), yield* unfinished, good).map( + (entry) => entry.problem, + ); + }); + + const refusal = (problems: ReadonlyArray) => ({ + changed: false, + problems, + }); + /** What keeps a change to the file `name` from running, once it is made on disk. */ + const taken = Effect.fn("WorkflowRuntime.taken")(function* (name: string) { + const listed = yield* reload(); + const problem = broken.get(name); + return { + changed: true, + problems: listed + ? [...(problem === undefined ? [] : [problem]), ...(held.get(name) ?? []), ...between] + : [{ message: `${directory} could not be read just now, so the change does not run yet.` }], + }; + }); + + const save = Effect.fn("WorkflowRuntime.save")(function* (name: string, source: string) { + const no = refused(name); + if (no !== undefined) return refusal([no]); + const file = path.join(directory, name); + // Beside the real file, so what it imports resolves the same way. The dot keeps it out. + const draft = path.join(directory, `.${name}.check-${loads + 1}${path.extname(name)}`); + const checked = yield* fileSystem.writeFileString(draft, source).pipe( + Effect.andThen(load(draft, name)), + Effect.ensuring(Effect.ignore(fileSystem.remove(draft))), + Effect.catchTags({ + PlatformError: (error) => + Effect.succeed({ + problem: { message: `Could not write in ${directory}: ${text(error)}` }, + } as const), + }), + ); + if (!("definitions" in checked)) return refusal([checked.problem]); + const definitions = checked.definitions; + const problems = yield* wouldBreak((files) => files.set(name, definitions)); + if (problems.length > 0) return refusal(problems); + const written = yield* fileSystem.writeFileString(file, source).pipe(Effect.result); + if (written._tag === "Failure") { + return refusal([{ message: `Could not write ${file}: ${text(written.failure)}` }]); + } + return yield* taken(name); + }); + + const remove = Effect.fn("WorkflowRuntime.remove")(function* (name: string) { + const no = single ? alone : refused(name); + if (no !== undefined) return refusal([no]); + const problems = yield* wouldBreak((files) => files.delete(name)); + if (problems.length > 0) return refusal(problems); + const removed = yield* fileSystem.remove(path.join(directory, name)).pipe(Effect.result); + if (removed._tag === "Failure") { + return refusal([{ message: `Could not delete ${name}: ${text(removed.failure)}` }]); + } + return yield* taken(name); + }); + + return Context.make(Workflows.Workflows, service).pipe( + Context.add( + WorkflowDefinitions, + WorkflowDefinitions.of({ + read: Effect.gen(function* () { + const files = yield* Effect.forEach( + yield* Effect.orElseSucceed(names, () => []), + (name) => + fileSystem.readFileString(path.join(directory, name)).pipe( + Effect.orElseSucceed(() => ""), + Effect.map((source) => { + const problem = broken.get(name); + return { + name, + source, + workflows: (good.get(name) ?? []).map(engineTag), + problems: [ + ...(problem === undefined ? [] : [problem]), + ...(held.get(name) ?? []), + ], + }; + }), + ), + ); + const at = yield* SubscriptionRef.get(state); + // A file held back after it was deleted has no entry of its own to say so. + const gone = [...held] + .filter(([name]) => !files.some((file) => file.name === name)) + .flatMap(([, problems]) => problems); + return { directory, single, files, problems: [...misnamed, ...between, ...gone], ...at }; + }), + save: Effect.fn("WorkflowDefinitions.save")(function* (name, source) { + return yield* lock.withPermits(1)(save(name, source)); + }), + remove: Effect.fn("WorkflowDefinitions.remove")(function* (name) { + return yield* lock.withPermits(1)(remove(name)); + }), + }), + ), + ); +}); + +/** + * Workflows behind the Labs switch. While off, `runtime` is not run: no definition file loads and + * no engine runs, and every request is refused. Turning on runs it in a scope of its own, which + * turning off closes; runs stay stored and go on once it is on again. `where` is as for `make`. + */ +export const gate = Effect.fn("WorkflowRuntime.gate")(function* ( + runtime: Effect.Effect< + Context.Context, + E, + R | Scope.Scope + >, + where: string, +) { + const path = yield* Path.Path; + const outer = yield* Scope.Scope; + const services = yield* Effect.context(); + const target = path.resolve(where); + const single = DEFINITION_FILE.test(path.basename(target)); + const off = { message: Workflows.OFF }; + const offDefinitions = WorkflowDefinitions.of({ + read: Effect.succeed({ + directory: single ? path.dirname(target) : target, + single, + files: [], + problems: [off], + revision: 0, + problem: null, + }), + save: Effect.fn("WorkflowDefinitions.save")(function* () { + return yield* Effect.succeed({ changed: false, problems: [off] }); + }), + remove: Effect.fn("WorkflowDefinitions.remove")(function* () { + return yield* Effect.succeed({ changed: false, problems: [off] }); + }), + }); + const offContext = Context.make(Workflows.Workflows, Workflows.off).pipe( + Context.add(WorkflowDefinitions, offDefinitions), + ); + + const lock = yield* Semaphore.make(1); + let ready = Deferred.makeUnsafe>(); + Deferred.doneUnsafe(ready, Exit.succeed(offContext)); + let scope: Scope.Closeable | undefined; + const turns = yield* SubscriptionRef.make(0); + + const turn = Effect.fn("WorkflowRuntime.turn")( + function* (on: boolean) { + if (on === (scope !== undefined)) return; + const next = + Deferred.makeUnsafe>(); + ready = next; + if (scope !== undefined) yield* Scope.close(scope, Exit.void); + scope = undefined; + if (on) { + const opened = yield* Scope.fork(outer); + const started = yield* runtime.pipe( + Effect.provideService(Scope.Scope, opened), + Effect.provideContext(services), + Effect.exit, + ); + if (Exit.isSuccess(started)) { + scope = opened; + yield* Deferred.succeed(next, started.value); + } else { + yield* Scope.close(opened, Exit.void); + yield* Effect.logWarning("Workflows did not start", Cause.pretty(started.cause)); + } + } + if (scope === undefined) yield* Deferred.succeed(next, offContext); + yield* SubscriptionRef.update(turns, (count) => count + 1); + yield* Effect.logInfo(scope === undefined ? "Workflows are off" : "Workflows are on"); + }, + // Once `ready` is replaced it must be settled, or every caller waits on it for good. + Effect.uninterruptible, + lock.withPermits(1), + ); + + const live = Effect.suspend(() => Deferred.await(ready)); + const current = Effect.map(live, Context.get(Workflows.Workflows)); + const definitions = Effect.map(live, Context.get(WorkflowDefinitions)); + // A watcher outlives a turn: each one hands it the next service's stream. + const followed = (pick: (service: Workflows.Workflows["Service"]) => Stream.Stream) => + SubscriptionRef.changes(turns).pipe( + Stream.switchMap(() => Stream.unwrap(Effect.map(current, pick))), + ); + const service = Workflows.Workflows.of({ + start: Effect.fn("Workflows.start")(function* (...input) { + return yield* (yield* current).start(...input); + }), + signal: Effect.fn("Workflows.signal")(function* (...input) { + return yield* (yield* current).signal(...input); + }), + answer: Effect.fn("Workflows.answer")(function* (...input) { + return yield* (yield* current).answer(...input); + }), + resume: Effect.fn("Workflows.resume")(function* (...input) { + return yield* (yield* current).resume(...input); + }), + cancel: Effect.fn("Workflows.cancel")(function* (...input) { + return yield* (yield* current).cancel(...input); + }), + get: Effect.fn("Workflows.get")(function* (...input) { + return yield* (yield* current).get(...input); + }), + list: Effect.fn("Workflows.list")(function* (...input) { + return yield* (yield* current).list(...input); + }), + waitFor: Effect.fn("Workflows.waitFor")(function* (...input) { + // Off, nothing changes a run; a wait goes on once workflows are on again. + while (true) { + const turned = yield* SubscriptionRef.get(turns); + const service = yield* current; + const next = SubscriptionRef.changes(turns).pipe( + Stream.filter((count) => count !== turned), + Stream.runHead, + ); + const waited = yield* service + .waitFor(...input) + .pipe(Effect.asSome, Effect.raceFirst(Effect.as(next, Option.none()))); + if (Option.isSome(waited)) return waited.value; + } + }), + questions: Effect.flatMap(current, (service) => service.questions), + unfinished: Effect.flatMap(current, (service) => service.unfinished), + hooks: Effect.flatMap(current, (service) => service.hooks), + deliver: Effect.fn("Workflows.deliver")(function* (...input) { + return yield* (yield* current).deliver(...input); + }), + stored: Effect.fn("Workflows.stored")(function* (...input) { + return yield* (yield* current).stored(...input); + }), + storeSet: Effect.fn("Workflows.storeSet")(function* (...input) { + return yield* (yield* current).storeSet(...input); + }), + storeDelete: Effect.fn("Workflows.storeDelete")(function* (...input) { + return yield* (yield* current).storeDelete(...input); + }), + watch: followed((service) => service.watch), + counts: followed((service) => service.counts), + sweep: Effect.flatMap(current, (service) => service.sweep), + }); + + return { + turn, + context: Context.make(Workflows.Workflows, service).pipe( + Context.add( + WorkflowDefinitions, + WorkflowDefinitions.of({ + read: Effect.flatMap(definitions, (files) => files.read), + save: Effect.fn("WorkflowDefinitions.save")(function* (name, source) { + return yield* (yield* definitions).save(name, source); + }), + remove: Effect.fn("WorkflowDefinitions.remove")(function* (name) { + return yield* (yield* definitions).remove(name); + }), + }), + ), + ), + }; +}); + +/** + * The workflow service for this server, and its definition files: those in the `workflows` + * folder of the T3 home, or wherever `T3CODE_WORKFLOWS` points instead. A file that does not + * load is reported and never stops the server. Nothing runs until `workflowsEnabled` is on. + */ +export const layer = Layer.effectContext( + Effect.gen(function* () { + const override = yield* definitionsOverride; + const config = yield* ServerConfig.ServerConfig; + const forge = Layer.succeed(WorkflowForge.WorkflowForge, yield* WorkflowForge.WorkflowForge); + const sql = yield* SqlClient.SqlClient; + const settings = yield* ServerSettings.ServerSettingsService; + const where = Option.getOrElse(override, () => config.workflowsDir); + const changes = yield* settings.subscribeChanges; + const gated = yield* gate( + make( + Effect.map( + Effect.promise((): Promise => import("./WorkflowEngine.ts")), + (engine) => (definitions) => + engine + .layer(definitions) + .pipe(Layer.provide(WorkflowAgentThreads.layer), Layer.provide(forge)), + ), + where, + sql`SELECT 1 FROM workflow_runs LIMIT 1`.pipe( + Effect.map((rows) => rows.length > 0), + Effect.orElseSucceed(() => true), + ), + ), + where, + ); + const enabled = yield* settings.getSettings.pipe( + Effect.map((current) => current.workflowsEnabled), + Effect.orElseSucceed(() => false), + ); + yield* gated.turn(enabled); + yield* changes.pipe( + Stream.map((current) => current.workflowsEnabled), + Stream.runForEach(gated.turn), + Effect.forkScoped, + ); + return gated.context; + }), +); diff --git a/apps/server/src/workflows/WorkflowStore.test.ts b/apps/server/src/workflows/WorkflowStore.test.ts new file mode 100644 index 0000000000000..7fa6daa8c0208 --- /dev/null +++ b/apps/server/src/workflows/WorkflowStore.test.ts @@ -0,0 +1,424 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import { assert, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; +import * as PubSub from "effect/PubSub"; +import type * as Schema from "effect/Schema"; +import * as TestClock from "effect/testing/TestClock"; + +import WorkflowsMigration from "../persistence/Migrations/110_Workflows.ts"; +import * as MilestoneHub from "../milestones/MilestoneHub.ts"; +import * as WorkflowStore from "./WorkflowStore.ts"; + +const withStore = ( + use: Effect.Effect, +) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-workflow-store-" }); + const database = NodeSqliteClient.layer({ filename: path.join(directory, "state.sqlite") }); + const migrated = Layer.effectDiscard(WorkflowsMigration); + return yield* Effect.provide( + use, + WorkflowStore.layer.pipe( + Layer.provideMerge(Layer.merge(migrated, MilestoneHub.layer)), + Layer.provide(database), + ), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped); + +it.effect("a run still waits while one of the things it started side by side is out", () => + withStore( + Effect.gen(function* () { + const store = yield* WorkflowStore.WorkflowStore; + yield* store.runStarted({ + runId: "r1", + workflow: "duo", + version: 1, + engineTag: "duo@1", + idempotencyKey: "k", + input: {}, + }); + // Started again under its key: nothing changed, so nobody is told. + yield* Effect.scoped( + Effect.gen(function* () { + const told = yield* PubSub.subscribe(store.changes); + yield* store.runStarted({ + runId: "r1", + workflow: "duo", + version: 1, + engineTag: "duo@1", + idempotencyKey: "k", + input: {}, + }); + assert.equal(yield* PubSub.remaining(told), 0); + }), + ); + const now = Effect.map(store.run("r1"), (run) => [run?.status, run?.detail]); + yield* store.stepStarted("r1", "left", "agent"); + yield* store.stepStarted("r1", "right", "agent"); + yield* store.stepStarted("r1", "approve", "ask"); + yield* store.runStatus("r1", "waiting", "agent left"); + + yield* store.stepEnded("r1", "left", "completed", null); + yield* store.runResumed("r1"); + assert.deepStrictEqual(yield* now, ["waiting", "agent right"]); + + yield* store.stepEnded("r1", "right", "completed", null); + yield* store.runResumed("r1"); + assert.deepStrictEqual(yield* now, ["waiting", "approve"]); + + yield* store.stepEnded("r1", "approve", "completed", null); + yield* store.runResumed("r1"); + assert.deepStrictEqual(yield* now, ["running", null]); + + // One of them failed and paused the run: the others ending do not take that back. + yield* store.stepStarted("r1", "again", "agent"); + yield* store.stepStarted("r1", "beside", "agent"); + yield* store.stepStarted("r1", "later", "wait"); + yield* store.runPaused("r1", "again gave up", true); + yield* store.stepEnded("r1", "beside", "completed", null); + yield* store.runResumed("r1"); + yield* store.runStatus("r1", "waiting", "later"); + const paused = yield* store.run("r1"); + assert.deepStrictEqual( + [paused?.status, paused?.detail, Number(paused?.pauses), Number(paused?.held)], + ["paused", "again gave up", 1, 1], + ); + // The sweep's resume is for the pause it read, not for one that came after it. + assert.isTrue(yield* store.runUnpaused("r1")); + yield* store.runPaused("r1", "gave up again"); + assert.isFalse( + yield* store.runUnpaused("r1", { pauses: 1, updatedAt: paused?.updated_at ?? "" }), + ); + assert.equal((yield* store.run("r1"))?.status, "paused"); + }), + ), +); + +it.effect("a key is taken by the first run started under it, whatever its version", () => + withStore( + Effect.gen(function* () { + const store = yield* WorkflowStore.WorkflowStore; + for (const version of [1, 2]) { + yield* store.runStarted({ + runId: `r${version}`, + workflow: "fix", + version, + engineTag: `fix@${version}`, + idempotencyKey: "k", + input: {}, + }); + } + assert.isUndefined(yield* store.run("r2")); + assert.equal((yield* store.runByKey("fix", "k"))?.run_id, "r1"); + }), + ), +); + +it.effect("keeps each thing a run touched once, with what the latest touch knew", () => + withStore( + Effect.gen(function* () { + const store = yield* WorkflowStore.WorkflowStore; + const issue = { kind: "issue", key: "i1", address: { scope: "me/app", key: "1" } }; + yield* store.referenceNoted("r1", null, { + ...issue, + title: "Crash", + url: "https://x/1", + state: "open", + }); + yield* store.referenceNoted("r1", "triage", { ...issue, title: "" }); + // A kind the engine has never heard of comes back as it went in. + const machine = { kind: "machine", key: "m1", address: { id: [1, 2] }, title: "box" }; + yield* store.referenceNoted("r1", "make", machine); + yield* store.referenceNoted("r1", "fix", { + ...issue, + title: "Crash at noon", + state: "closed", + }); + yield* Effect.scoped( + Effect.gen(function* () { + const told = yield* PubSub.subscribe(store.changes); + // Seen again by a step that already touched it, with nothing new: nobody is told. + yield* store.referenceNoted("r1", "triage", { ...issue, title: "" }); + assert.equal(yield* PubSub.remaining(told), 0); + }), + ); + assert.deepStrictEqual(yield* store.references("r1"), [ + { + ...issue, + title: "Crash at noon", + url: "https://x/1", + state: "closed", + steps: ["triage", "fix"], + origin: "trigger", + }, + { ...machine, url: null, state: null, steps: ["make"], origin: "step" }, + ]); + assert.deepStrictEqual(yield* store.references("r2"), []); + }), + ), +); + +it.effect("counts what waits on a person, and finds the run's latest agent thread", () => + withStore( + Effect.gen(function* () { + const store = yield* WorkflowStore.WorkflowStore; + const start = (runId: string) => + store.runStarted({ + runId, + workflow: "fix", + version: 1, + engineTag: "fix@1", + idempotencyKey: runId, + input: {}, + }); + assert.deepStrictEqual(yield* store.counts, { needsYou: 0, active: 0, total: 0 }); + yield* Effect.forEach(["r1", "r2", "r3"], start); + yield* store.runPaused("r1", "the build failed"); + assert.isTrue(yield* store.runEnded("r3", "completed", null, null)); + // A second ending, such as a cancel that lost the race, is not recorded and says so. + assert.isFalse(yield* store.runEnded("r3", "cancelled", "late", null)); + assert.equal((yield* store.run("r3"))?.status, "completed"); + // Every run still going, with no list limit: the guard on dropping a version reads this. + assert.equal((yield* store.unfinished).length, 2); + yield* store.waitOpened({ + runId: "r2", + name: "merge", + workflow: "fix", + key: undefined, + token: "t", + schemaJson: "{}", + requestJson: '{"title":"Merge?"}', + watchJson: null, + deadline: null, + }); + // A paused run and an open question each wait on someone; a plain wait does not. + yield* store.waitOpened({ + runId: "r2", + name: "ci", + workflow: "fix", + key: undefined, + token: "u", + schemaJson: "{}", + requestJson: null, + watchJson: null, + deadline: null, + }); + assert.deepStrictEqual(yield* store.counts, { needsYou: 2, active: 2, total: 3 }); + + assert.isNull(yield* store.latestThread("r2")); + yield* store.stepStarted("r2", "write", "agent"); + yield* store.stepThread("r2", "write", "thread-1", null, "turn-1"); + yield* store.stepStarted("r2", "review", "agent"); + yield* store.stepThread("r2", "review", "thread-2", "env-b", "turn-2"); + assert.deepStrictEqual(yield* store.latestThread("r2"), { + threadId: "thread-2", + environmentId: "env-b", + }); + }), + ), +); + +it.effect("one buffered signal goes to one wait, and a claimed wait keeps what woke it", () => + withStore( + Effect.gen(function* () { + const store = yield* WorkflowStore.WorkflowStore; + const open = (runId: string) => + Effect.andThen( + store.runStarted({ + runId, + workflow: "gate", + version: 1, + engineTag: "gate@1", + idempotencyKey: runId, + input: {}, + }), + store.waitOpened({ + runId, + name: "go", + workflow: "gate", + key: "ready", + token: `token-${runId}`, + schemaJson: "{}", + requestJson: null, + watchJson: null, + deadline: null, + }), + ); + yield* open("r1"); + yield* open("r2"); + // The parts of an address are kept apart: this one is for another workflow's other key. + yield* store.mailPut({ + signalId: "other", + address: { workflow: "gate:ready", channel: "x" }, + valueJson: "1", + expiresAt: "2999-01-01T00:00:00.000Z", + }); + assert.isUndefined(yield* store.mailNext([{ workflow: "gate", channel: "ready:x" }])); + + yield* store.mailPut({ + signalId: "s1", + address: { workflow: "gate", channel: "ready" }, + valueJson: '"yes"', + expiresAt: "2999-01-01T00:00:00.000Z", + }); + const woke = { expired: false, value: "yes" }; + assert.equal(yield* store.mailDeliver("s1", "r1", "go", woke), "delivered"); + // The second wait finds the signal gone and stays open for the next one. + assert.equal(yield* store.mailDeliver("s1", "r2", "go", woke), "gone"); + assert.isDefined(yield* store.waitAt({ runId: "r2", wait: "go" })); + assert.isTrue(yield* store.signalSeen("s1")); + // Nor can the id, sent again straight to that wait, claim it: one id wakes one wait. + assert.isFalse(yield* store.waitSignalled("r2", "go", woke, "s1")); + assert.isDefined(yield* store.waitAt({ runId: "r2", wait: "go" })); + // And a kept copy of an id that already woke a wait straight wakes none: the two sends of a + // retry that overlapped, one buffered and one delivered. + yield* store.mailPut({ + signalId: "s1", + address: { workflow: "gate", channel: "ready" }, + valueJson: '"yes"', + expiresAt: "2999-01-01T00:00:00.000Z", + }); + assert.equal(yield* store.mailDeliver("s1", "r2", "go", woke), "gone"); + assert.isDefined(yield* store.waitAt({ runId: "r2", wait: "go" })); + // It is dropped, so a wait looking through its mail is not handed it again. + assert.isUndefined(yield* store.mailNext([{ workflow: "gate", channel: "ready" }])); + // A wait that is already claimed takes no second wake. + assert.equal(yield* store.mailDeliver("other", "r1", "go", woke), "claimed"); + + // Its wake is redone once the claim has gone unanswered for a while. + assert.deepStrictEqual(yield* store.waitsToWake, []); + yield* TestClock.adjust("1 minute"); + const again = yield* store.waitsToWake; + assert.deepStrictEqual( + again.map((wait) => [wait.run_id, wait.woke_json]), + [["r1", JSON.stringify(woke)]], + ); + + // An id is remembered as long as its signal could have been kept, so a sender's retry + // within a long time to live is still the same signal. + yield* open("r3"); + yield* store.mailPut({ + signalId: "long", + address: { runId: "r3", wait: "go" }, + valueJson: '"yes"', + expiresAt: "1970-01-31T00:00:00.000Z", + }); + assert.equal(yield* store.mailDeliver("long", "r3", "go", woke), "delivered"); + yield* TestClock.adjust("10 days"); + yield* store.mailExpire; + assert.isTrue(yield* store.signalSeen("long")); + }), + ), +); + +it.effect("tells the milestone hub of each run and question transition once", () => + withStore( + Effect.gen(function* () { + const store = yield* WorkflowStore.WorkflowStore; + const hub = yield* MilestoneHub.MilestoneHub; + const start = { + runId: "r1", + workflow: "review", + version: 1, + engineTag: "review@1", + idempotencyKey: "k", + input: {}, + }; + const ask = (name: string, request: Schema.Json) => + store.waitOpened({ + runId: "r1", + name, + workflow: "review", + key: undefined, + token: `token-${name}`, + schemaJson: "{}", + requestJson: WorkflowStore.jsonText(request), + watchJson: null, + deadline: null, + }); + yield* store.runStarted(start); + yield* store.runStarted(start); + yield* ask("approve", { title: "Ship it?" }); + yield* ask("approve", { title: "Ship it?" }); + // A wait nobody is asked is no question. + yield* store.waitOpened({ + runId: "r1", + name: "checks", + workflow: "review", + key: undefined, + token: "token-checks", + schemaJson: "{}", + requestJson: null, + watchJson: null, + deadline: null, + }); + yield* store.waitSignalled("r1", "approve", { expired: false, value: true }); + yield* store.waitSignalled("r1", "approve", { expired: false, value: false }); + yield* store.waitSignalled("r1", "checks", { expired: false, value: null }); + yield* ask("later", {}); + yield* store.waitSignalled("r1", "later", { expired: true, value: null }); + yield* ask("last", { title: "Anything else?" }); + yield* store.runPaused("r1", "agent failed"); + yield* store.runPaused("r1", "agent failed again"); + yield* store.runUnpaused("r1"); + yield* store.runUnpaused("r1"); + // A run another run invoked is muted unless asked for, as a subagent's thread is. + yield* store.runStarted({ + ...start, + runId: "r2", + idempotencyKey: "child", + parent: { runId: "r1", wait: "child" }, + }); + yield* store.runEnded("r1", "cancelled", "stopped by a person", null); + yield* store.runEnded("r1", "completed", null, null); + + assert.notInclude( + (yield* hub.recent()).events.map((event) => event.workflowRunId), + "r2", + ); + const { events } = yield* hub.recent({ filter: { includeSubagentChildren: true } }); + assert.deepStrictEqual( + events.map((event): unknown => { + const { id: _id, occurredAt: _at, ...rest } = event; + return rest; + }), + [ + { type: "workflow.run_started" }, + { type: "workflow.needs_input", step: "approve", question: "Ship it?" }, + { type: "workflow.input_resolved", step: "approve", resolution: "answered" }, + { type: "workflow.needs_input", step: "later", question: "later" }, + { type: "workflow.input_resolved", step: "later", resolution: "expired" }, + { type: "workflow.needs_input", step: "last", question: "Anything else?" }, + { type: "workflow.run_paused", reason: "agent failed" }, + { type: "workflow.run_resumed" }, + { + type: "workflow.run_started", + isSubagentChild: true, + workflowRunId: "r2", + runTitle: "review child", + parentWorkflowRunId: "r1", + }, + { type: "workflow.input_resolved", step: "last", resolution: "cancelled" }, + { type: "workflow.run_ended", outcome: "cancelled", detail: "stopped by a person" }, + ].map((news) => ({ + projectId: null, + threadId: null, + parentThreadId: null, + actor: { type: "system" }, + isSubagentChild: false, + workflowRunId: "r1", + workflow: "review", + runTitle: "review k", + parentWorkflowRunId: null, + ...news, + })), + ); + }), + ), +); diff --git a/apps/server/src/workflows/WorkflowStore.ts b/apps/server/src/workflows/WorkflowStore.ts new file mode 100644 index 0000000000000..17d2b4c4bf358 --- /dev/null +++ b/apps/server/src/workflows/WorkflowStore.ts @@ -0,0 +1,1142 @@ +import { + type MilestoneEvent, + MilestoneId, + type WorkflowCounts, + WorkflowRun, + type WorkflowRunReference, + WorkflowRunStatus, + WorkflowStep, +} from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as PubSub from "effect/PubSub"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; + +import * as MilestoneHub from "../milestones/MilestoneHub.ts"; + +export { WorkflowRun, WorkflowRunStatus, WorkflowStep }; + +/** Where a signal goes: one wait of one run, or whichever run of a workflow waits on a channel. */ +export type SignalAddress = + | { readonly runId: string; readonly wait: string } + | { readonly workflow: string; readonly channel: string }; + +/** The run that invoked another, and the wait in it that hears how the other ended. */ +export interface RunParent { + readonly runId: string; + readonly wait: string; +} + +export interface RunRow { + readonly run_id: string; + readonly workflow: string; + readonly idempotency_key: string; + readonly version: number | bigint; + readonly engine_tag: string; + readonly title: string; + readonly status: WorkflowRunStatus; + readonly detail: string | null; + readonly result_json: string | null; + readonly input_json: string | null; + readonly parent_run_id: string | null; + readonly parent_wait: string | null; + readonly pauses: number | bigint; + /** Paused until a person resumes it, whatever the workflow's `resumeAfter` says. */ + readonly held: number | bigint; + readonly started_at: string; + readonly updated_at: string; + readonly ended_at: string | null; +} +export interface StepRow { + readonly name: string; + readonly kind: WorkflowStep["kind"]; + readonly status: WorkflowStep["status"]; + readonly attempts: number | bigint; + readonly detail: string | null; + readonly thread_id: string | null; + readonly environment_id: string | null; + readonly result_json: string | null; + readonly said: string | null; + readonly started_at: string; + readonly ended_at: string | null; +} +export interface WaitRow { + readonly run_id: string; + readonly name: string; + readonly token: string; + readonly schema_json: string; + readonly request_json: string | null; + readonly watch_json: string | null; + readonly deadline: string | null; + readonly opened_at: string; + /** What it was woken with, once it has been. */ + readonly woke_json: string | null; +} + +/** Something a run touched, as the one that touched it knows it. */ +export interface ReferenceInput { + readonly kind: string; + readonly key: string; + readonly address: Schema.Json; + /** Empty when the toucher does not know it; a title already kept stays. */ + readonly title: string; + readonly url?: string | null | undefined; + readonly state?: string | null | undefined; +} +interface ReferenceRow { + readonly kind: string; + readonly key: string; + readonly address_json: string; + readonly title: string; + readonly url: string | null; + readonly state: string | null; + readonly steps_json: string; + readonly origin: WorkflowRunReference["origin"]; +} + +// Rows keep JSON as text. Everything stored was a JSON value when it was written. +export const jsonText = (value: Schema.Json): string => JSON.stringify(value); +export const jsonValue = (text: string): Schema.Json => JSON.parse(text) as Schema.Json; + +const now = Effect.map(DateTime.now, DateTime.formatIso); + +type WorkflowMilestone = Extract; +/** What a workflow milestone says beyond its envelope and its run. */ +type WorkflowMilestoneNews = WorkflowMilestone extends infer Event + ? Event extends WorkflowMilestone + ? Omit< + Event, + | "id" + | "occurredAt" + | "projectId" + | "threadId" + | "parentThreadId" + | "actor" + | "isSubagentChild" + | "workflowRunId" + | "workflow" + | "runTitle" + | "parentWorkflowRunId" + > + : never + : never; +// A wake is one write away from its claim. A claim this old without its run moving had none. +const WAKE_REDONE_AFTER = Duration.seconds(30); +// Long enough for a sender's retries, short enough that the table stays small. +// Enough to read what a step said; the page that shows it is not a place for a whole report. +const STEP_RESULT_KEPT = 8_000; +const SIGNAL_IDS_KEPT = Duration.days(7); +const REFERENCE_TITLE_KEPT = 300; +const idsKeptUntil = Effect.map(DateTime.now, (at) => + DateTime.formatIso(DateTime.addDuration(at, SIGNAL_IDS_KEPT)), +); +// A tuple, so no name or key can be read as part of the other. +const mailAddress = (address: SignalAddress) => + JSON.stringify( + "runId" in address + ? ["run", address.runId, address.wait] + : ["key", address.workflow, address.channel], + ); + +export class WorkflowStore extends Context.Service< + WorkflowStore, + { + readonly changes: PubSub.PubSub; + readonly runStarted: (run: { + readonly runId: string; + readonly workflow: string; + readonly version: number; + readonly engineTag: string; + readonly idempotencyKey: string; + readonly input: Schema.Json; + readonly parent?: RunParent | undefined; + }) => Effect.Effect; + readonly runStatus: ( + runId: string, + status: "running" | "waiting", + detail: string | null, + ) => Effect.Effect; + /** + * A wait or an agent of the run is over. The run is running again, unless another it started + * side by side is still out, which it then waits on. + */ + readonly runResumed: (runId: string) => Effect.Effect; + /** `held` unsaid keeps what the run had: a run put back to paused is still held. */ + readonly runPaused: (runId: string, detail: string, held?: boolean) => Effect.Effect; + /** + * A paused run is running again. With `current`, only while that is still the pause: the + * sweep's deadline was worked out from it. False when the run was not changed. + */ + readonly runUnpaused: ( + runId: string, + current?: { readonly pauses: number; readonly updatedAt: string }, + ) => Effect.Effect; + /** The person's resume has reached the engine, so the run no longer waits for one. */ + readonly runUnheld: (runId: string) => Effect.Effect; + readonly runEnded: ( + runId: string, + status: "completed" | "stopped" | "skipped" | "cancelled", + detail: string | null, + result: Schema.Json, + ) => Effect.Effect; + readonly runTitle: (runId: string, title: string) => Effect.Effect; + /** Marks the step running and returns how many times it has now been started. */ + readonly stepStarted: ( + runId: string, + name: string, + kind: WorkflowStep["kind"], + ) => Effect.Effect; + readonly stepEnded: ( + runId: string, + name: string, + status: "completed" | "failed", + detail: string | null, + ) => Effect.Effect; + readonly waitOpened: (wait: { + readonly runId: string; + readonly name: string; + readonly workflow: string; + readonly key: string | undefined; + readonly token: string; + readonly schemaJson: string; + /** What a person is asked, when this wait is a question. */ + readonly requestJson: string | null; + /** What the engine looks at to end this wait by itself. */ + readonly watchJson: string | null; + readonly deadline: string | null; + }) => Effect.Effect; + readonly waitClosed: (runId: string, name: string) => Effect.Effect; + /** The wait takes signals again, under a fresh wake: what woke it was not for it. */ + readonly waitReopened: (runId: string, name: string, token: string) => Effect.Effect; + /** Takes the wait for one signal. False when another signal already has it. */ + /** + * Claims an open wait for one wake and keeps what it is woken with. False when something else + * already claimed it. A signal's id is recorded with the claim, so a retry never claims twice. + */ + readonly waitSignalled: ( + runId: string, + name: string, + woke: Schema.Json, + signalId?: string, + ) => Effect.Effect; + /** Waits claimed a while ago whose runs are still not past them: their wake is redone. */ + readonly waitsToWake: Effect.Effect>; + /** The run's waits that were claimed and are still open, whose wakes a resume sends. */ + readonly waitsClaimed: (runId: string) => Effect.Effect>; + /** + * Hands one buffered signal to one wait, or to none: the claim and the removal happen + * together. `gone` when another wait took the signal, `claimed` when the wait was already woken. + */ + readonly mailDeliver: ( + signalId: string, + runId: string, + name: string, + woke: Schema.Json, + ) => Effect.Effect<"delivered" | "gone" | "claimed">; + /** Runs that were not ended while the run that invoked them was cancelled. */ + readonly orphans: Effect.Effect>; + /** Runs ended before `before`, with no step still going, whose engine journal is still kept. */ + readonly prunable: ( + before: string, + limit: number, + ) => Effect.Effect>; + readonly enginePruned: (runId: string) => Effect.Effect; + /** Every run in this state, however many: the sweep must not miss old ones past a page. */ + readonly everyRun: ( + status: "running" | "waiting" | "paused", + ) => Effect.Effect>; + /** What each run that has not ended is a run of, with no limit. */ + readonly unfinished: Effect.Effect< + ReadonlyArray<{ readonly workflow: string; readonly version: number }> + >; + /** Whether a signal with this id already woke a wait. */ + readonly signalSeen: (signalId: string) => Effect.Effect; + /** Counts one more arrival at `name` in this run and returns the count. */ + readonly mark: (runId: string, name: string) => Effect.Effect; + /** The runs this one invoked that have not ended. */ + readonly children: (runId: string) => Effect.Effect>; + /** The steps a cancelled run left in flight are over: nothing will end them. */ + readonly stepsCancelled: (runId: string, except: string) => Effect.Effect; + /** Cancelled runs whose `onEnd` has not completed and may still be tried, with its tries. */ + readonly runsToEnd: ( + step: string, + tries: number, + ) => Effect.Effect< + ReadonlyArray< + RunRow & { + readonly end_attempts: number | bigint | null; + readonly end_ended_at: string | null; + } + > + >; + /** Cancelled runs with a step other than `except` still going: their cancel was cut short. */ + readonly cancelsCutShort: (except: string) => Effect.Effect>; + /** Ended runs whose parent still waits to hear of it. */ + readonly untold: Effect.Effect>; + readonly stepThread: ( + runId: string, + name: string, + threadId: string, + environment: string | null, + turnId: string, + ) => Effect.Effect; + /** The threads of agent steps still running in this run, with each step's own turn. */ + readonly runningThreads: (runId: string) => Effect.Effect< + ReadonlyArray<{ + readonly threadId: string; + readonly environment?: string; + readonly turnId?: string; + }> + >; + readonly waitAt: (address: SignalAddress) => Effect.Effect; + /** Every open wait on `key`, in one workflow or in all of them. */ + readonly waitsOn: ( + key: string, + workflow: string | undefined, + ) => Effect.Effect>; + readonly waitsPastDeadline: Effect.Effect>; + readonly requests: Effect.Effect>; + /** Open waits the engine ends by looking at something. */ + readonly watches: Effect.Effect>; + /** The thread of the run's latest agent step, if it has had one. */ + readonly latestThread: ( + runId: string, + ) => Effect.Effect<{ readonly threadId: string; readonly environmentId: string | null } | null>; + readonly counts: Effect.Effect; + /** Keep what a step produced for a person to read. A large value is kept as its start. */ + readonly stepResult: ( + runId: string, + name: string, + value: Schema.Json, + /** What an agent said in closing, when its result is data and not that reply. */ + said?: string, + ) => Effect.Effect; + /** Say something about a step that is under way, such as when its sleep ends. */ + readonly stepDetail: (runId: string, name: string, detail: string) => Effect.Effect; + readonly mailPut: (mail: { + readonly signalId: string; + readonly address: SignalAddress; + readonly valueJson: string; + readonly expiresAt: string; + }) => Effect.Effect; + /** The oldest signal kept for any of these addresses, but `passed`. It stays until `mailDelete`. */ + readonly mailNext: ( + addresses: ReadonlyArray, + passed?: ReadonlySet, + ) => Effect.Effect< + | { + readonly signalId: string; + readonly valueJson: string; + readonly address: SignalAddress; + } + | undefined + >; + readonly mailDelete: (signalId: string) => Effect.Effect; + readonly mailExpire: Effect.Effect; + readonly run: (runId: string) => Effect.Effect; + /** The run a workflow was started as under `key`, of whichever version. */ + readonly runByKey: (workflow: string, key: string) => Effect.Effect; + readonly runs: (status: WorkflowRunStatus | undefined) => Effect.Effect>; + /** Runs by what they are a run of and what they were started as, newest first. */ + readonly runsWhere: (filter: { + readonly workflow?: string | undefined; + readonly status?: WorkflowRunStatus | undefined; + readonly keyPrefix?: string | undefined; + }) => Effect.Effect>; + readonly triggerNext: (triggerId: string) => Effect.Effect; + readonly triggerSet: (triggerId: string, nextAt: string) => Effect.Effect; + /** Forgets every trigger but these, so one that comes back starts over. */ + readonly triggersKeep: (triggerIds: ReadonlyArray) => Effect.Effect; + /** The hook's token: the one kept for it, or `fresh` from now on. */ + readonly hookToken: (hookId: string, fresh: string) => Effect.Effect; + readonly steps: (runId: string) => Effect.Effect>; + /** + * Keep that the run touched something: from a step, or with no step from what started it. A + * later touch of the same thing keeps what it knows that is new and adds its step. + */ + readonly referenceNoted: ( + runId: string, + step: string | null, + reference: ReferenceInput, + ) => Effect.Effect; + /** What the run touched, in the order it first did. */ + readonly references: (runId: string) => Effect.Effect>; + } +>()("t3/workflows/WorkflowStore") {} + +export const make = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const changes = yield* PubSub.unbounded(); + // A write here is bookkeeping for a run the engine already journaled: failing it would park a + // healthy run, so a database that cannot take it is a defect of the process instead. + const write = (runId: string, effect: Effect.Effect) => + effect.pipe(Effect.orDie, Effect.andThen(PubSub.publish(changes, runId)), Effect.asVoid); + const waitColumns = sql`run_id, name, token, schema_json, request_json, watch_json, deadline, opened_at, woke_json`; + + const hub = yield* Effect.serviceOption(MilestoneHub.MilestoneHub); + /** Tells the milestone hub of a transition this store just wrote, under an id stable for it. */ + const tell = Effect.fn("WorkflowStore.tell")(function* ( + runId: string, + key: string, + at: string, + news: WorkflowMilestoneNews, + ) { + if (Option.isNone(hub)) return; + const [run] = yield* sql>` + SELECT workflow, title, parent_run_id FROM workflow_runs WHERE run_id = ${runId} + `.pipe(Effect.orDie); + if (run === undefined) return; + yield* hub.value.publish({ + id: MilestoneId.make(`${news.type}:${key}`), + occurredAt: at, + projectId: null, + threadId: null, + parentThreadId: null, + actor: { type: "system" }, + isSubagentChild: run.parent_run_id !== null, + workflowRunId: runId, + workflow: run.workflow, + runTitle: run.title, + parentWorkflowRunId: run.parent_run_id, + ...news, + } as WorkflowMilestone); + }); + const questionTitle = (wait: Pick) => { + const request = wait.request_json === null ? null : jsonValue(wait.request_json); + const title = + request !== null && typeof request === "object" && !Array.isArray(request) + ? (request as { readonly title?: unknown }).title + : undefined; + return typeof title === "string" && title.trim() !== "" ? title : wait.name; + }; + /** A question claimed by an answer or its timeout is resolved, whichever claimed it. */ + const questionClaimed = Effect.fn("WorkflowStore.questionClaimed")(function* ( + runId: string, + name: string, + woke: Schema.Json, + at: string, + ) { + if (Option.isNone(hub)) return; + const [wait] = yield* sql>` + SELECT request_json, opened_at FROM workflow_waits WHERE run_id = ${runId} AND name = ${name} + `.pipe(Effect.orDie); + if (wait === undefined || wait.request_json === null) return; + const expired = + woke !== null && + typeof woke === "object" && + (woke as { readonly expired?: unknown }).expired === true; + yield* tell(runId, `${runId}:${name}:${wait.opened_at}`, at, { + type: "workflow.input_resolved", + step: name, + resolution: expired ? "expired" : "answered", + }); + }); + + return WorkflowStore.of({ + changes, + runStarted: Effect.fn("WorkflowStore.runStarted")(function* (run) { + const at = yield* now; + // A start under a key that already has its run changes nothing, and tells nobody. + const inserted = yield* sql` + INSERT INTO workflow_runs ( + run_id, workflow, version, engine_tag, idempotency_key, title, status, input_json, + parent_run_id, parent_wait, started_at, updated_at + ) VALUES ( + ${run.runId}, ${run.workflow}, ${run.version}, ${run.engineTag}, + ${run.idempotencyKey}, ${`${run.workflow} ${run.idempotencyKey}`}, 'running', + ${jsonText(run.input)}, ${run.parent?.runId ?? null}, ${run.parent?.wait ?? null}, + ${at}, ${at} + ) + ON CONFLICT DO NOTHING + RETURNING run_id + `.pipe(Effect.orDie); + if (inserted.length === 0) return; + yield* PubSub.publish(changes, run.runId); + yield* tell(run.runId, run.runId, at, { type: "workflow.run_started" }); + }), + runStatus: Effect.fn("WorkflowStore.runStatus")(function* (runId, status, detail) { + const at = yield* now; + yield* write( + runId, + sql` + UPDATE workflow_runs + SET status = ${status}, detail = ${detail}, updated_at = ${at} + WHERE run_id = ${runId} AND ended_at IS NULL AND status != 'paused' + `, + ); + }), + runResumed: Effect.fn("WorkflowStore.runResumed")(function* (runId) { + const at = yield* now; + // One statement, so two of them ending at once cannot leave the run on one that has ended. + yield* write( + runId, + sql` + WITH out AS ( + SELECT CASE WHEN kind IN ('agent', 'sleep') THEN kind || ' ' || name ELSE name END + AS detail + FROM workflow_steps + WHERE run_id = ${runId} AND status = 'running' + AND kind IN ('wait', 'ask', 'agent', 'sleep') + ORDER BY started_at, rowid LIMIT 1 + ) + UPDATE workflow_runs + SET status = CASE WHEN EXISTS (SELECT 1 FROM out) THEN 'waiting' ELSE 'running' END, + detail = (SELECT detail FROM out), updated_at = ${at} + WHERE run_id = ${runId} AND ended_at IS NULL AND status != 'paused' + `, + ); + }), + runPaused: Effect.fn("WorkflowStore.runPaused")(function* (runId, detail, held) { + const at = yield* now; + const reason = detail.slice(0, 2000); + const paused = yield* sql` + UPDATE workflow_runs + SET status = 'paused', detail = ${reason}, pauses = pauses + 1, + held = ${held === undefined ? sql`held` : held ? 1 : 0}, updated_at = ${at} + WHERE run_id = ${runId} AND ended_at IS NULL AND status != 'paused' + RETURNING run_id + `.pipe(Effect.orDie); + yield* PubSub.publish(changes, runId); + if (paused.length > 0) { + yield* tell(runId, `${runId}:${at}`, at, { type: "workflow.run_paused", reason }); + } + }), + runUnpaused: Effect.fn("WorkflowStore.runUnpaused")(function* (runId, current) { + const at = yield* now; + const rows = yield* sql` + UPDATE workflow_runs SET status = 'running', detail = NULL, updated_at = ${at} + WHERE run_id = ${runId} AND ended_at IS NULL AND status = 'paused' + AND (${current === undefined ? 1 : 0} = 1 + OR (pauses = ${current?.pauses ?? 0} AND updated_at = ${current?.updatedAt ?? ""})) + RETURNING run_id + `.pipe(Effect.orDie); + yield* PubSub.publish(changes, runId); + if (rows.length === 0) return false; + yield* tell(runId, `${runId}:${at}`, at, { type: "workflow.run_resumed" }); + return true; + }), + runUnheld: Effect.fn("WorkflowStore.runUnheld")(function* (runId) { + // A pause since then set its own `held`. + yield* write( + runId, + sql`UPDATE workflow_runs SET held = 0 WHERE run_id = ${runId} AND status != 'paused'`, + ); + }), + runEnded: Effect.fn("WorkflowStore.runEnded")(function* (runId, status, detail, result) { + const at = yield* now; + const resultJson = jsonText(result); + // False when another outcome was recorded first: the run ended some other way. + const ended = yield* sql + .withTransaction( + Effect.gen(function* () { + const rows = yield* sql` + UPDATE workflow_runs + SET status = ${status}, detail = ${detail}, result_json = ${resultJson}, + pauses = 0, updated_at = ${at}, ended_at = ${at} + WHERE run_id = ${runId} AND ended_at IS NULL + RETURNING run_id + `; + const closed = yield* sql>` + DELETE FROM workflow_waits WHERE run_id = ${runId} + RETURNING name, request_json, opened_at + `; + return { ended: rows.length > 0, closed }; + }), + ) + .pipe(Effect.orDie); + yield* PubSub.publish(changes, runId); + if (!ended.ended) return false; + for (const wait of ended.closed) { + if (wait.request_json === null) continue; + yield* tell(runId, `${runId}:${wait.name}:${wait.opened_at}`, at, { + type: "workflow.input_resolved", + step: wait.name, + resolution: "cancelled", + }); + } + yield* tell(runId, runId, at, { type: "workflow.run_ended", outcome: status, detail }); + return true; + }), + runTitle: Effect.fn("WorkflowStore.runTitle")(function* (runId, title) { + yield* write( + runId, + sql`UPDATE workflow_runs SET title = ${title.slice(0, 200)} WHERE run_id = ${runId}`, + ); + }), + stepStarted: Effect.fn("WorkflowStore.stepStarted")(function* (runId, name, kind) { + const at = yield* now; + const rows = yield* sql<{ attempts: number | bigint }>` + INSERT INTO workflow_steps (run_id, name, kind, status, attempts, started_at) + VALUES (${runId}, ${name}, ${kind}, 'running', 1, ${at}) + ON CONFLICT (run_id, name) DO UPDATE + SET status = 'running', attempts = attempts + 1, detail = NULL, ended_at = NULL, + started_at = excluded.started_at + RETURNING attempts + `.pipe(Effect.orDie); + yield* PubSub.publish(changes, runId); + return Number(rows[0]?.attempts ?? 1); + }), + stepEnded: Effect.fn("WorkflowStore.stepEnded")(function* (runId, name, status, detail) { + const at = yield* now; + yield* write( + runId, + sql.withTransaction( + Effect.andThen( + sql` + UPDATE workflow_steps + SET status = ${status}, detail = ${detail === null ? null : detail.slice(0, 2000)}, ended_at = ${at} + WHERE run_id = ${runId} AND name = ${name} + `, + // A step that finished is progress: the next pause is the first in a row again. + status === "completed" + ? // Not while paused: a step beside the one that failed is no progress past it. + sql` + UPDATE workflow_runs SET pauses = 0 + WHERE run_id = ${runId} AND ended_at IS NULL AND status != 'paused' + ` + : Effect.void, + ), + ), + ); + }), + waitOpened: Effect.fn("WorkflowStore.waitOpened")(function* (wait) { + const at = yield* now; + const opened = yield* sql` + INSERT INTO workflow_waits ( + run_id, name, workflow, token, key, schema_json, request_json, watch_json, deadline, + opened_at + ) VALUES ( + ${wait.runId}, ${wait.name}, ${wait.workflow}, ${wait.token}, ${wait.key ?? null}, + ${wait.schemaJson}, ${wait.requestJson}, ${wait.watchJson}, ${wait.deadline}, ${at} + ) + ON CONFLICT (run_id, name) DO NOTHING + RETURNING name + `.pipe(Effect.orDie); + yield* PubSub.publish(changes, wait.runId); + if (opened.length === 0 || wait.requestJson === null) return; + yield* tell(wait.runId, `${wait.runId}:${wait.name}:${at}`, at, { + type: "workflow.needs_input", + step: wait.name, + question: questionTitle({ name: wait.name, request_json: wait.requestJson }), + }); + }), + waitClosed: Effect.fn("WorkflowStore.waitClosed")(function* (runId, name) { + yield* write( + runId, + sql`DELETE FROM workflow_waits WHERE run_id = ${runId} AND name = ${name}`, + ); + }), + waitReopened: Effect.fn("WorkflowStore.waitReopened")(function* (runId, name, token) { + yield* write( + runId, + sql` + UPDATE workflow_waits SET token = ${token}, signalled_at = NULL, woke_json = NULL + WHERE run_id = ${runId} AND name = ${name} + `, + ); + }), + waitSignalled: Effect.fn("WorkflowStore.waitSignalled")( + function* (runId, name, woke, signalId) { + const at = yield* now; + const taken = yield* sql` + UPDATE workflow_waits SET signalled_at = ${at}, woke_json = ${jsonText(woke)} + WHERE run_id = ${runId} AND name = ${name} AND signalled_at IS NULL + RETURNING name + `; + if (taken.length > 0 && signalId !== undefined) { + const receipt = yield* sql` + INSERT INTO workflow_signals (signal_id, kept_until) + VALUES (${signalId}, MAX(${yield* idsKeptUntil}, COALESCE( + (SELECT expires_at FROM workflow_mail WHERE signal_id = ${signalId}), '' + ))) + ON CONFLICT (signal_id) DO NOTHING + RETURNING signal_id + `; + // The id already woke a wait, so this one is not claimed: the transaction undoes it. + if (receipt.length === 0) return yield* Effect.fail("seen" as const); + } + return taken.length > 0; + }, + (effect, runId, name, woke) => + sql.withTransaction(effect).pipe( + Effect.catchIf( + (error) => error === "seen", + () => Effect.succeed(false), + ), + Effect.orDie, + Effect.tap((taken) => + taken + ? Effect.flatMap(now, (at) => questionClaimed(runId, name, woke, at)) + : Effect.void, + ), + ), + ), + waitsToWake: Effect.gen(function* () { + const before = DateTime.formatIso( + DateTime.subtractDuration(yield* DateTime.now, WAKE_REDONE_AFTER), + ); + return yield* sql` + SELECT ${waitColumns} FROM workflow_waits + WHERE woke_json IS NOT NULL AND signalled_at <= ${before} + AND run_id IN (SELECT run_id FROM workflow_runs WHERE ended_at IS NULL) + `.pipe(Effect.orDie); + }), + waitsClaimed: Effect.fn("WorkflowStore.waitsClaimed")(function* (runId) { + return yield* sql` + SELECT ${waitColumns} FROM workflow_waits WHERE run_id = ${runId} AND woke_json IS NOT NULL + `.pipe(Effect.orDie); + }), + mailDeliver: Effect.fn("WorkflowStore.mailDeliver")(function* (signalId, runId, name, woke) { + const at = yield* now; + const outcome = yield* sql + .withTransaction( + Effect.gen(function* () { + // A kept copy of an id that already woke a wait straight is spent: it is dropped, so + // it wakes no second wait and is not offered again. + const seen = yield* sql`SELECT 1 FROM workflow_signals WHERE signal_id = ${signalId}`; + if (seen.length > 0) { + yield* sql`DELETE FROM workflow_mail WHERE signal_id = ${signalId}`; + return "gone" as const; + } + const claimed = yield* sql` + UPDATE workflow_waits SET signalled_at = ${at}, woke_json = ${jsonText(woke)} + WHERE run_id = ${runId} AND name = ${name} AND signalled_at IS NULL + RETURNING name + `; + if (claimed.length === 0) return "claimed" as const; + const taken = yield* sql<{ expires_at: string }>` + DELETE FROM workflow_mail WHERE signal_id = ${signalId} RETURNING expires_at + `; + // Failing undoes the claim: the wait stays open for a signal that is still there. + const copy = taken[0]; + if (copy === undefined) return yield* Effect.fail("gone" as const); + const keep = yield* idsKeptUntil; + const receipt = yield* sql` + INSERT INTO workflow_signals (signal_id, kept_until) + VALUES (${signalId}, ${copy.expires_at > keep ? copy.expires_at : keep}) + ON CONFLICT (signal_id) DO NOTHING + RETURNING signal_id + `; + // Delivered straight in the meantime: undone, and the next look drops the copy above. + if (receipt.length === 0) return yield* Effect.fail("gone" as const); + return "delivered" as const; + }), + ) + .pipe( + Effect.catchIf( + (error) => error === "gone", + () => Effect.succeed("gone" as const), + ), + Effect.orDie, + ); + if (outcome === "delivered") yield* questionClaimed(runId, name, woke, at); + return outcome; + }), + prunable: Effect.fn("WorkflowStore.prunable")(function* (before, limit) { + return yield* sql<{ run_id: string; engine_tag: string }>` + SELECT run_id, engine_tag FROM workflow_runs r + WHERE ended_at IS NOT NULL AND ended_at < ${before} AND engine_pruned_at IS NULL + AND NOT EXISTS ( + SELECT 1 FROM workflow_steps s WHERE s.run_id = r.run_id AND s.status = 'running' + ) + ORDER BY ended_at LIMIT ${limit} + `.pipe(Effect.orDie); + }), + enginePruned: Effect.fn("WorkflowStore.enginePruned")(function* (runId) { + const at = yield* now; + yield* sql` + UPDATE workflow_runs SET engine_pruned_at = ${at} WHERE run_id = ${runId} + `.pipe(Effect.orDie); + }), + orphans: sql` + SELECT c.* FROM workflow_runs c + JOIN workflow_runs p ON p.run_id = c.parent_run_id + WHERE c.ended_at IS NULL AND p.status = 'cancelled' + `.pipe(Effect.orDie), + unfinished: sql<{ workflow: string; version: number | bigint }>` + SELECT workflow, version FROM workflow_runs WHERE ended_at IS NULL + `.pipe( + Effect.map((rows) => + rows.map((row) => ({ workflow: row.workflow, version: Number(row.version) })), + ), + Effect.orDie, + ), + everyRun: Effect.fn("WorkflowStore.everyRun")(function* (status) { + return yield* sql`SELECT * FROM workflow_runs WHERE status = ${status}`.pipe( + Effect.orDie, + ); + }), + signalSeen: Effect.fn("WorkflowStore.signalSeen")(function* (signalId) { + const rows = yield* sql` + SELECT 1 FROM workflow_signals WHERE signal_id = ${signalId} + `.pipe(Effect.orDie); + return rows.length > 0; + }), + mark: Effect.fn("WorkflowStore.mark")(function* (runId, name) { + const rows = yield* sql<{ count: number | bigint }>` + INSERT INTO workflow_marks (run_id, name, count) VALUES (${runId}, ${name}, 1) + ON CONFLICT (run_id, name) DO UPDATE SET count = count + 1 + RETURNING count + `.pipe(Effect.orDie); + return Number(rows[0]?.count ?? 1); + }), + children: Effect.fn("WorkflowStore.children")(function* (runId) { + return yield* sql` + SELECT * FROM workflow_runs WHERE parent_run_id = ${runId} AND ended_at IS NULL + `.pipe(Effect.orDie); + }), + stepsCancelled: Effect.fn("WorkflowStore.stepsCancelled")(function* (runId, except) { + const at = yield* now; + yield* write( + runId, + sql` + UPDATE workflow_steps SET status = 'failed', detail = 'cancelled', ended_at = ${at} + WHERE run_id = ${runId} AND status = 'running' AND name != ${except} + `, + ); + }), + runsToEnd: Effect.fn("WorkflowStore.runsToEnd")(function* (step, tries) { + return yield* sql< + RunRow & { end_attempts: number | bigint | null; end_ended_at: string | null } + >` + SELECT r.*, s.attempts AS end_attempts, s.ended_at AS end_ended_at + FROM workflow_runs r + LEFT JOIN workflow_steps s ON s.run_id = r.run_id AND s.name = ${step} + WHERE r.status = 'cancelled' + AND (s.status IS NULL OR (s.status != 'completed' AND s.attempts < ${tries})) + `.pipe(Effect.orDie); + }), + cancelsCutShort: Effect.fn("WorkflowStore.cancelsCutShort")(function* (except) { + return yield* sql` + SELECT r.* FROM workflow_runs r + WHERE r.status = 'cancelled' AND EXISTS ( + SELECT 1 FROM workflow_steps s + WHERE s.run_id = r.run_id AND s.status = 'running' AND s.name != ${except} + ) + `.pipe(Effect.orDie); + }), + untold: sql` + SELECT c.* FROM workflow_waits w + JOIN workflow_runs c ON c.parent_run_id = w.run_id AND c.parent_wait = w.name + WHERE w.signalled_at IS NULL AND c.ended_at IS NOT NULL + `.pipe(Effect.orDie), + stepThread: Effect.fn("WorkflowStore.stepThread")( + function* (runId, name, threadId, environment, turnId) { + yield* write( + runId, + sql` + UPDATE workflow_steps + SET thread_id = ${threadId}, environment_id = ${environment}, turn_id = ${turnId} + WHERE run_id = ${runId} AND name = ${name} + `, + ); + }, + ), + runningThreads: Effect.fn("WorkflowStore.runningThreads")(function* (runId) { + const rows = yield* sql<{ + thread_id: string; + environment_id: string | null; + turn_id: string | null; + }>` + SELECT thread_id, environment_id, turn_id FROM workflow_steps + WHERE run_id = ${runId} AND status = 'running' AND thread_id IS NOT NULL + `.pipe(Effect.orDie); + return rows.map((row) => ({ + threadId: row.thread_id, + ...(row.environment_id === null ? {} : { environment: row.environment_id }), + ...(row.turn_id === null ? {} : { turnId: row.turn_id }), + })); + }), + waitAt: Effect.fn("WorkflowStore.waitAt")(function* (address) { + const rows = yield* ( + "runId" in address + ? sql` + SELECT ${waitColumns} FROM workflow_waits + WHERE run_id = ${address.runId} AND name = ${address.wait} AND signalled_at IS NULL + ` + : sql` + SELECT ${waitColumns} FROM workflow_waits + WHERE workflow = ${address.workflow} AND key = ${address.channel} AND signalled_at IS NULL + ORDER BY opened_at LIMIT 1 + ` + ).pipe(Effect.orDie); + return rows[0]; + }), + waitsOn: Effect.fn("WorkflowStore.waitsOn")(function* (key, workflow) { + return yield* sql` + SELECT ${waitColumns} FROM workflow_waits + WHERE key = ${key} AND signalled_at IS NULL + AND (${workflow ?? null} IS NULL OR workflow = ${workflow ?? null}) + ORDER BY opened_at + `.pipe(Effect.orDie); + }), + waitsPastDeadline: Effect.flatMap(now, (at) => + sql` + SELECT ${waitColumns} FROM workflow_waits + WHERE deadline IS NOT NULL AND deadline <= ${at} AND signalled_at IS NULL + `.pipe(Effect.orDie), + ), + latestThread: Effect.fn("WorkflowStore.latestThread")(function* (runId) { + const rows = yield* sql<{ thread_id: string; environment_id: string | null }>` + SELECT thread_id, environment_id FROM workflow_steps + WHERE run_id = ${runId} AND thread_id IS NOT NULL + ORDER BY started_at DESC, rowid DESC LIMIT 1 + `.pipe(Effect.orDie); + const row = rows[0]; + return row === undefined + ? null + : { threadId: row.thread_id, environmentId: row.environment_id }; + }), + counts: sql<{ questions: number; paused: number; active: number; total: number }>` + SELECT + (SELECT COUNT(*) FROM workflow_waits + WHERE request_json IS NOT NULL AND signalled_at IS NULL) AS questions, + (SELECT COUNT(*) FROM workflow_runs WHERE status = 'paused') AS paused, + (SELECT COUNT(*) FROM workflow_runs WHERE ended_at IS NULL) AS active, + (SELECT COUNT(*) FROM workflow_runs) AS total + `.pipe( + Effect.orDie, + Effect.map((rows) => ({ + needsYou: Number(rows[0]?.questions ?? 0) + Number(rows[0]?.paused ?? 0), + active: Number(rows[0]?.active ?? 0), + total: Number(rows[0]?.total ?? 0), + })), + ), + stepResult: Effect.fn("WorkflowStore.stepResult")(function* (runId, name, value, said) { + const full = jsonText(value); + const kept = + full.length <= STEP_RESULT_KEPT ? full : jsonText(`${full.slice(0, STEP_RESULT_KEPT)}…`); + const words = said?.trim() ?? ""; + const keptSaid = + words === "" + ? null + : words.length <= STEP_RESULT_KEPT + ? words + : `${words.slice(0, STEP_RESULT_KEPT)}…`; + yield* sql` + UPDATE workflow_steps SET result_json = ${kept}, said = ${keptSaid} + WHERE run_id = ${runId} AND name = ${name} + `.pipe(Effect.orDie); + }), + stepDetail: Effect.fn("WorkflowStore.stepDetail")(function* (runId, name, detail) { + yield* write( + runId, + sql`UPDATE workflow_steps SET detail = ${detail} WHERE run_id = ${runId} AND name = ${name}`, + ); + }), + requests: sql` + SELECT ${waitColumns} FROM workflow_waits + WHERE request_json IS NOT NULL AND signalled_at IS NULL ORDER BY opened_at + `.pipe(Effect.orDie), + watches: sql` + SELECT ${waitColumns} FROM workflow_waits + WHERE watch_json IS NOT NULL AND signalled_at IS NULL ORDER BY opened_at + `.pipe(Effect.orDie), + mailPut: Effect.fn("WorkflowStore.mailPut")(function* (mail) { + yield* sql + .withTransaction( + Effect.andThen( + sql` + INSERT INTO workflow_mail (signal_id, address, value_json, expires_at) + VALUES (${mail.signalId}, ${mailAddress(mail.address)}, ${mail.valueJson}, ${mail.expiresAt}) + ON CONFLICT (signal_id) DO NOTHING + `, + // A copy kept by a retry that raced the first delivery outlives no receipt of it. + sql` + UPDATE workflow_signals SET kept_until = ${mail.expiresAt} + WHERE signal_id = ${mail.signalId} AND kept_until < ${mail.expiresAt} + `, + ), + ) + .pipe(Effect.orDie); + }), + mailNext: Effect.fn("WorkflowStore.mailNext")(function* (addresses, passed = new Set()) { + for (const address of addresses) { + const rows = yield* sql<{ signal_id: string; value_json: string }>` + SELECT signal_id, value_json FROM workflow_mail + WHERE address = ${mailAddress(address)} ORDER BY rowid + `.pipe(Effect.orDie); + const mail = rows.find((row) => !passed.has(row.signal_id)); + if (mail !== undefined) { + return { signalId: mail.signal_id, valueJson: mail.value_json, address }; + } + } + return undefined; + }), + mailDelete: Effect.fn("WorkflowStore.mailDelete")(function* (signalId) { + yield* sql`DELETE FROM workflow_mail WHERE signal_id = ${signalId}`.pipe(Effect.orDie); + }), + mailExpire: Effect.gen(function* () { + const at = yield* DateTime.now; + yield* sql`DELETE FROM workflow_mail WHERE expires_at <= ${DateTime.formatIso(at)}`; + yield* sql`DELETE FROM workflow_signals WHERE kept_until <= ${DateTime.formatIso(at)}`; + }).pipe(Effect.orDie), + run: Effect.fn("WorkflowStore.run")(function* (runId) { + const rows = yield* sql`SELECT * FROM workflow_runs WHERE run_id = ${runId}`.pipe( + Effect.orDie, + ); + return rows[0]; + }), + runByKey: Effect.fn("WorkflowStore.runByKey")(function* (workflow, key) { + const rows = yield* sql` + SELECT * FROM workflow_runs WHERE workflow = ${workflow} AND idempotency_key = ${key} + ORDER BY started_at LIMIT 1 + `.pipe(Effect.orDie); + return rows[0]; + }), + runsWhere: Effect.fn("WorkflowStore.runsWhere")(function* (filter) { + const prefix = filter.keyPrefix ?? null; + // A range, not LIKE, which would read `%` and `_` in a key as patterns. + return yield* sql` + SELECT * FROM workflow_runs + WHERE (${filter.workflow ?? null} IS NULL OR workflow = ${filter.workflow ?? null}) + AND (${filter.status ?? null} IS NULL OR status = ${filter.status ?? null}) + AND (${prefix} IS NULL OR ( + idempotency_key >= ${prefix} AND idempotency_key < ${`${prefix ?? ""}\u{10FFFF}`} + )) + ORDER BY started_at DESC, rowid DESC LIMIT 500 + `.pipe(Effect.orDie); + }), + runs: Effect.fn("WorkflowStore.runs")(function* (status) { + return yield* ( + status === undefined + ? // Skipped runs are counted apart, so a trigger that skips most of what it brings does + // not push the runs that did something out of the list. + sql` + SELECT * FROM ( + SELECT * FROM workflow_runs + WHERE NOT (status = 'skipped' AND parent_run_id IS NULL) + ORDER BY started_at DESC LIMIT 500 + ) + UNION ALL + SELECT * FROM ( + SELECT * FROM workflow_runs + WHERE status = 'skipped' AND parent_run_id IS NULL + ORDER BY started_at DESC LIMIT 500 + ) + ORDER BY started_at DESC + ` + : sql` + SELECT * FROM workflow_runs WHERE status = ${status} + ORDER BY started_at DESC LIMIT 500 + ` + ).pipe(Effect.orDie); + }), + triggerNext: Effect.fn("WorkflowStore.triggerNext")(function* (triggerId) { + const rows = yield* sql<{ next_at: string }>` + SELECT next_at FROM workflow_triggers WHERE trigger_id = ${triggerId} + `.pipe(Effect.orDie); + return rows[0]?.next_at; + }), + triggerSet: Effect.fn("WorkflowStore.triggerSet")(function* (triggerId, nextAt) { + yield* sql` + INSERT INTO workflow_triggers (trigger_id, next_at) VALUES (${triggerId}, ${nextAt}) + ON CONFLICT (trigger_id) DO UPDATE SET next_at = excluded.next_at + `.pipe(Effect.orDie); + }), + triggersKeep: Effect.fn("WorkflowStore.triggersKeep")(function* (triggerIds) { + const kept = yield* sql<{ trigger_id: string }>`SELECT trigger_id FROM workflow_triggers`; + for (const { trigger_id } of kept) { + if (triggerIds.includes(trigger_id)) continue; + yield* sql`DELETE FROM workflow_triggers WHERE trigger_id = ${trigger_id}`; + } + }, Effect.orDie), + hookToken: Effect.fn("WorkflowStore.hookToken")(function* (hookId, fresh) { + yield* sql` + INSERT INTO workflow_hooks (hook_id, token) VALUES (${hookId}, ${fresh}) + ON CONFLICT (hook_id) DO NOTHING + `; + const rows = yield* sql<{ token: string }>` + SELECT token FROM workflow_hooks WHERE hook_id = ${hookId} + `; + return rows[0]?.token ?? fresh; + }, Effect.orDie), + steps: Effect.fn("WorkflowStore.steps")(function* (runId) { + return yield* sql` + SELECT name, kind, status, attempts, detail, thread_id, environment_id, result_json, + said, started_at, ended_at + FROM workflow_steps WHERE run_id = ${runId} ORDER BY started_at, rowid + `.pipe(Effect.orDie); + }), + referenceNoted: Effect.fn("WorkflowStore.referenceNoted")(function* (runId, step, reference) { + const at = yield* now; + const addressJson = jsonText(reference.address); + const title = reference.title.slice(0, REFERENCE_TITLE_KEPT); + const changed = yield* sql + .withTransaction( + Effect.gen(function* () { + const rows = yield* sql` + SELECT kind, key, address_json, title, url, state, steps_json, origin + FROM workflow_run_references + WHERE run_id = ${runId} AND kind = ${reference.kind} AND key = ${reference.key} + `; + const row = rows[0]; + if (row === undefined) { + yield* sql` + INSERT INTO workflow_run_references ( + run_id, kind, key, address_json, title, url, state, steps_json, origin, noted_at + ) VALUES ( + ${runId}, ${reference.kind}, ${reference.key}, ${addressJson}, ${title}, + ${reference.url ?? null}, ${reference.state ?? null}, + ${jsonText(step === null ? [] : [step])}, ${step === null ? "trigger" : "step"}, + ${at} + ) + `; + return true; + } + const steps = jsonValue(row.steps_json) as ReadonlyArray; + const next = { + address_json: addressJson, + title: title === "" ? row.title : title, + url: reference.url ?? row.url, + state: reference.state ?? row.state, + steps_json: + step === null || steps.includes(step) ? row.steps_json : jsonText([...steps, step]), + }; + // A touch that says nothing new is no change, so a look every minute costs no list. + if ( + next.address_json === row.address_json && + next.title === row.title && + next.url === row.url && + next.state === row.state && + next.steps_json === row.steps_json + ) { + return false; + } + yield* sql` + UPDATE workflow_run_references + SET address_json = ${next.address_json}, title = ${next.title}, url = ${next.url}, + state = ${next.state}, steps_json = ${next.steps_json} + WHERE run_id = ${runId} AND kind = ${reference.kind} AND key = ${reference.key} + `; + return true; + }), + ) + .pipe(Effect.orDie); + if (changed) yield* PubSub.publish(changes, runId); + }), + references: Effect.fn("WorkflowStore.references")(function* (runId) { + const rows = yield* sql` + SELECT kind, key, address_json, title, url, state, steps_json, origin + FROM workflow_run_references WHERE run_id = ${runId} ORDER BY rowid + `.pipe(Effect.orDie); + return rows.map((row) => ({ + kind: row.kind, + key: row.key, + address: jsonValue(row.address_json), + title: row.title, + url: row.url, + state: row.state, + steps: jsonValue(row.steps_json) as ReadonlyArray, + origin: row.origin, + })); + }), + }); +}); + +export const layer = Layer.effect(WorkflowStore, make); diff --git a/apps/server/src/workflows/Workflows.test.ts b/apps/server/src/workflows/Workflows.test.ts new file mode 100644 index 0000000000000..cc56f6cd79a8a --- /dev/null +++ b/apps/server/src/workflows/Workflows.test.ts @@ -0,0 +1,2424 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import { assert, it } from "@effect/vitest"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import { ProjectId } from "@t3tools/contracts"; +import * as Cause from "effect/Cause"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Fiber from "effect/Fiber"; +import * as FileSystem from "effect/FileSystem"; +import * as Latch from "effect/Latch"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import * as Ref from "effect/Ref"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; +import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; + +import { daily, every, Tick, webhook, WebhookRequest } from "./triggers.ts"; +import { issues, pullRequests } from "./forgeApi.ts"; +import { cancel, runs, signal, signalAll, start, store } from "./stepServices.ts"; +import { type InRun, invoke, skip, sleep, step, stop, title, wait, workflow } from "./workflow.ts"; +import { type AgentResult, WorkflowAgentError, WorkflowAgents } from "./WorkflowAgents.ts"; +import WorkflowsMigration from "../persistence/Migrations/110_Workflows.ts"; +import * as WorkflowEngine from "./WorkflowEngine.ts"; +import { + Issue, + pullRequestReferenceOf, + unavailable, + WorkflowForge, + WorkflowForgeError, +} from "./WorkflowForge.ts"; +import { issueReference, noteReference } from "./runReferences.ts"; +import { agent, ask } from "./workflowAgent.ts"; +import * as Workflows from "./Workflows.ts"; +import * as WorkflowStore from "./WorkflowStore.ts"; +import type { WorkflowRun, WorkflowRunStatus } from "./WorkflowStore.ts"; + +const once = { retry: { times: 0 } } as const; + +/** Holds the `work` step of an `owned` run in `busy` mode until the test lets it go. */ +interface Latch { + readonly entered: Deferred.Deferred; + readonly release: Deferred.Deferred; + readonly cleaned: Deferred.Deferred; + /** Holds the `bad` step of a `sibling` run until the test lets it go. */ + readonly bad: Deferred.Deferred; +} + +/** A workflow whose `flaky` step fails until `failures` reaches zero, counting every execution. */ +const definitions = ( + counts: Ref.Ref>, + failures: Ref.Ref, + latch: Latch, +) => { + const count = (name: string) => + Ref.updateAndGet(counts, (all) => ({ ...all, [name]: (all[name] ?? 0) + 1 })).pipe( + Effect.map((all) => all[name]!), + ); + return [ + workflow( + "owned", + { + version: 1, + payload: Schema.Struct({ mode: Schema.Literals(["finish", "stop", "hold", "busy"]) }), + // Counted by how the run ended, and failing for as long as `failures` says. + onEnd: (payload, end) => + Effect.gen(function* () { + // The engine's setting for reading integers must not reach a cleanup either. + if (yield* SqlClient.SafeIntegers) return yield* Effect.fail("SafeIntegers leaked"); + if (payload.mode === "busy") { + // Says whether the step it cleans up after had finished. + const all = yield* Ref.get(counts); + yield* count(`end:busy:${all["work"] === 1 ? "after" : "before"} work`); + return yield* Deferred.succeed(latch.cleaned, undefined); + } + const left = yield* Ref.getAndUpdate(failures, (rest) => Math.max(0, rest - 1)); + if (left > 0) return yield* Effect.fail("the machine would not go"); + yield* count(`end:${payload.mode}:${end.outcome}:${end.reason ?? ""}`); + }), + }, + (payload) => + Effect.gen(function* () { + if (payload.mode === "busy") { + yield* step( + "work", + { returns: Schema.Number }, + Effect.andThen( + Effect.andThen( + Deferred.succeed(latch.entered, undefined), + Deferred.await(latch.release), + ), + count("work"), + ), + ); + } + yield* step("take", { returns: Schema.Number, ...once }, count("take")); + if (payload.mode === "stop") return yield* stop("no need"); + if (payload.mode === "hold") yield* wait("go", { returns: Schema.String }); + }), + ), + workflow( + "flaky", + { + version: 1, + payload: Schema.Struct({ id: Schema.String, settle: Schema.optional(Schema.Boolean) }), + returns: Schema.String, + }, + (payload) => + Effect.gen(function* () { + if (payload.settle === true) { + const tried = yield* step.try( + "settled", + { returns: Schema.Number }, + Effect.flatMap( + Ref.getAndUpdate(failures, (left) => Math.max(0, left - 1)), + (left) => (left > 0 ? Effect.fail("the dependency is down") : count("settled")), + ), + ); + return tried.outcome === "done" ? `settled ${tried.value}` : `gave up: ${tried.reason}`; + } + yield* step("before", { returns: Schema.Number, ...once }, count("before")); + const attempt = yield* step( + "flaky", + { returns: Schema.Number, ...once }, + Effect.flatMap( + Ref.getAndUpdate(failures, (left) => Math.max(0, left - 1)), + (left) => (left > 0 ? Effect.fail("the dependency is down") : count("flaky")), + ), + ); + return `done on attempt ${attempt}`; + }), + ), + /** Fails `bad` beside an open wait, as long as `failures` says. */ + workflow("sibling", { version: 1, payload: Schema.Struct({}), returns: Schema.String }, () => + Effect.map( + Effect.all( + [ + step( + "bad", + { returns: Schema.Number, ...once }, + Effect.andThen( + Effect.andThen(Deferred.await(latch.bad), count("bad tries")), + Effect.flatMap( + Ref.getAndUpdate(failures, (left) => Math.max(0, left - 1)), + (left) => (left > 0 ? Effect.fail("the dependency is down") : count("bad")), + ), + ), + ), + wait("sib", { returns: Schema.String }), + ], + { concurrency: 2 }, + ), + ([bad, sib]) => `${bad} ${Option.getOrElse(sib, () => "none")}`, + ), + ), + workflow( + "review", + { + version: 1, + payload: Schema.Struct({ change: Schema.String, timeout: Schema.optional(Schema.String) }), + returns: Schema.String, + }, + (payload) => + Effect.gen(function* () { + yield* title(`review of ${payload.change}`); + yield* sleep("settle", "1 millis"); + const [a, b] = yield* Effect.all( + [ + step("check/a", { returns: Schema.Number, ...once }, count("check/a")), + step("check/b", { returns: Schema.Number, ...once }, count("check/b")), + ], + { concurrency: 2 }, + ); + const verdict = yield* wait("verdict", { + returns: Schema.Struct({ merge: Schema.Boolean }), + channel: payload.change, + ...(payload.timeout === undefined ? {} : { timeout: "0 millis" }), + }); + if (Option.isNone(verdict)) return yield* stop("nobody answered"); + yield* step("after", { returns: Schema.Number, ...once }, count("after")); + return `${a + b} checks, merge: ${verdict.value.merge}`; + }), + ), + /** Reads a number from text, which its JSON Schema cannot say: any string fits that. */ + workflow("reading", { version: 1, payload: Schema.Struct({}), returns: Schema.Number }, () => + Effect.map( + wait("count", { returns: Schema.FiniteFromString }), + Option.getOrElse(() => -1), + ), + ), + workflow( + "broken", + { + version: 1, + payload: Schema.Struct({ + how: Schema.Literals(["dies", "unstorable", "undefined", "nested"]), + }), + }, + (payload): Effect.Effect => { + if (payload.how === "dies") { + return step( + "dies", + { returns: Schema.Void, ...once }, + Effect.die(new Error("null dereference")), + ); + } + if (payload.how === "undefined") { + // No `returns`: read as JSON reads it, without the undefined fields. + return Effect.map( + step.try("void", { returns: Schema.Void, ...once }, Effect.void), + (r) => ({ r, id: undefined, list: [undefined] }), + ); + } + if (payload.how === "nested") { + return step( + "nested", + { returns: Schema.Json, ...once }, + Effect.succeed({ deep: [{ id: undefined }] } as unknown as Schema.Json), + ); + } + return Effect.asVoid( + step("unstorable", { returns: Schema.Int, ...once }, Effect.succeed(1.5)), + ); + }, + ), + workflow("twice", { version: 1, payload: Schema.Struct({}) }, () => + Effect.gen(function* () { + yield* step("same", { returns: Schema.Void, ...once }, Effect.void); + yield* step("same", { returns: Schema.Void, ...once }, Effect.void); + }), + ), + workflow("reserved", { version: 1, payload: Schema.Struct({}) }, () => + step("onEnd", { returns: Schema.Void, ...once }, Effect.void), + ), + ...[1, 2].map((version) => + workflow("versioned", { version, payload: Schema.Struct({}), returns: Schema.Number }, () => + Effect.succeed(version), + ), + ), + ]; +}; + +/** Write a change, ask a person whether to merge it, then land it in the writer's own thread. */ +const tally = store.entry("tally", Schema.Number); +const stored = [ + /** Counts itself in the store, with the first try of the step failing after it counted. */ + workflow( + "tally", + { + version: 1, + payload: Schema.Struct({ wrong: Schema.optional(Schema.Boolean) }), + returns: Schema.Number, + }, + (payload) => + payload.wrong === true + ? step( + "read", + { returns: Schema.Number, ...once }, + Effect.as(store.entry("tally", Schema.String).get, 0), + ) + : step( + "count", + { returns: Schema.Number, ...once }, + tally + .update((current) => Option.getOrElse(current, () => 0) + 1) + .pipe(Effect.map(Option.getOrElse(() => 0))), + ), + ), + /** Waits in line for a door that `opener` opens. */ + workflow( + "door", + { version: 1, payload: Schema.Struct({ door: Schema.String }), returns: Schema.String }, + (payload) => + Effect.map( + wait("open", { returns: Schema.String, channel: payload.door }), + Option.getOrElse(() => "never"), + ), + ), + workflow( + "opener", + { version: 1, payload: Schema.Struct({ door: Schema.String, fail: Schema.Boolean }) }, + (payload) => + step( + "open", + { returns: Schema.Void, retry: { times: 1 } }, + Effect.gen(function* () { + // Written and taken back together when the step fails after writing. + yield* store.transaction( + Effect.gen(function* () { + yield* store.entry(`doors/${payload.door}`, Schema.String).set("open"); + const tries = yield* store + .entry(`tries/${payload.door}`, Schema.Number) + .update((current) => Option.getOrElse(current, () => 0) + 1); + if (payload.fail && Option.contains(tries, 1)) return yield* Effect.fail("slipped"); + }), + ); + yield* signal({ workflow: "door", channel: payload.door }, "came in"); + }), + ), + ), + /** Opens two doors, fails, and on its second try opens the second and a third. */ + workflow( + "relay", + { version: 1, payload: Schema.Struct({ doors: Schema.Array(Schema.String) }) }, + (payload) => + step( + "pass", + { returns: Schema.Void, retry: { times: 1 } }, + Effect.gen(function* () { + const tries = yield* store + .entry("relay-tries", Schema.Number) + .update((current) => Option.getOrElse(current, () => 0) + 1); + const [a, b, c] = payload.doors; + const doors = Option.contains(tries, 1) ? [a!, b!] : [b!, c!]; + for (const door of doors) yield* signal({ workflow: "door", channel: door }, "came in"); + if (Option.contains(tries, 1)) return yield* Effect.fail("slipped"); + }), + ), + ), +]; + +const kid = workflow( + "kid", + { + version: 1, + payload: Schema.Struct({ mode: Schema.Literals(["finish", "stop", "hold"]) }), + returns: Schema.String, + }, + (payload) => + Effect.gen(function* () { + if (payload.mode === "stop") return yield* stop("nothing to do"); + if (payload.mode === "hold") yield* wait("go", { returns: Schema.String }); + return "grown"; + }), +); +const family = [ + kid, + /** Runs a kid as part of itself and reports how the kid ended. */ + workflow( + "parent", + { + version: 1, + payload: Schema.Struct({ mode: Schema.Literals(["finish", "stop", "hold"]) }), + returns: Schema.String, + }, + (payload) => + Effect.map(invoke("kid", kid, payload), (ended) => + ended.outcome === "completed" ? ended.value : `${ended.outcome}: ${ended.reason}`, + ), + ), + /** Invokes under a name a step of its own already has, or by a name and not the definition. */ + workflow( + "clash", + { version: 1, payload: Schema.Struct({ byName: Schema.optional(Schema.Boolean) }) }, + (payload) => + payload.byName === true + ? // Files are not type-checked, so this is what one that passes a name does. + invoke("child", "kid" as unknown as typeof kid, { mode: "finish" }) + : Effect.andThen( + step("kid", { returns: Schema.Void, ...once }, Effect.void), + invoke("kid", kid, { mode: "finish" }), + ), + ), + /** Starts two kids and does not wait for them. */ + workflow( + "spawner", + { version: 1, payload: Schema.Struct({}), returns: Schema.Array(Schema.String) }, + () => + step( + "spawn", + { returns: Schema.Array(Schema.String), ...once }, + Effect.forEach(["one", "two"], (key) => + Effect.map(start(kid, { mode: "finish" }, { key: `spawned/${key}` }), (run) => run.runId), + ), + ), + ), + /** Two agents at once, the second with a minute to finish. */ + workflow("pair", { version: 1, payload: Schema.Struct({}), returns: Schema.String }, () => + Effect.map( + Effect.all( + [ + agent("left", { brief: "Left.", project: "p1" }), + agent("right", { brief: "Right.", project: "p1", timeout: "1 minute" }), + ], + { concurrency: 2 }, + ), + ([left, right]) => `${left.value} ${right.value}`, + ), + ), +]; + +const fix = workflow( + "fix", + { + version: 1, + payload: Schema.Struct({ + project: Schema.String, + environment: Schema.optional(Schema.String), + // Lands with a model of its own, which a continued thread cannot take. + reshape: Schema.optional(Schema.Boolean), + /** The address of the issue the fix is for. */ + issue: Schema.optional(Schema.String), + }), + returns: Schema.String, + }, + (payload) => + Effect.gen(function* () { + const written = yield* agent("write", { + brief: "Write the fix.", + project: payload.project, + ...(payload.environment === undefined ? {} : { environment: payload.environment }), + ...(payload.issue === undefined + ? {} + : { issue: { project: payload.project, url: payload.issue } }), + returns: Schema.Struct({ + branch: Schema.String, + commits: Schema.optional(Schema.Number.check(Schema.isGreaterThan(0))), + }), + }); + const answer = yield* ask("merge", { + title: `Merge ${written.value.branch}?`, + choices: ["Merge", "Leave"], + data: { branch: written.value.branch }, + }); + if (Option.isNone(answer) || answer.value.choice !== "Merge") return yield* stop("left"); + const landed = yield* agent("land", { + brief: "Land it.", + thread: written.thread, + ...(payload.reshape === true ? { model: { instanceId: "codex", model: "gpt" } } : {}), + }); + return `${written.value.branch}: ${landed.value}`; + }), +); + +/** Waits at a gate with others, until whoever keeps it lets everyone through. */ +const gate = workflow( + "gate", + { version: 1, payload: Schema.Struct({ gate: Schema.String }), returns: Schema.String }, + (payload) => + Effect.map( + wait("through", { returns: Schema.String, channel: payload.gate }), + Option.getOrElse(() => "never"), + ), +); +const control = [ + gate, + /** Looks at the runs at the gates, lets one gate's through, or sends one run away. */ + workflow( + "keeper", + { + version: 1, + payload: Schema.Struct({ act: Schema.Literals(["look", "open", "dismiss", "leave"]) }), + returns: Schema.Json, + }, + (payload, run) => + step( + "act", + { returns: Schema.Json, ...once }, + Effect.gen(function* () { + const waiting = yield* runs({ workflow: gate, keyPrefix: "visit/" }); + if (payload.act === "open") return yield* signalAll({ channel: "north" }, "go on"); + if (payload.act === "leave") return yield* Effect.as(cancel(run.id, "done here"), null); + if (payload.act === "dismiss") { + const last = waiting.find((visit) => visit.key === "visit/3"); + return yield* Effect.as(cancel(last?.id ?? "", "the gate is closed"), null); + } + return waiting.map((visit) => `${visit.key} ${visit.status}`).toSorted(); + }), + ), + ), + /** Gives the job to a second agent when the first one fails, and says how it went. */ + workflow( + "fallback", + { + version: 1, + payload: Schema.Struct({ + project: Schema.String, + timeout: Schema.optional(Schema.Literal("1 minute")), + /** Says which thread the first agent's failure came back with. */ + thread: Schema.optional(Schema.Boolean), + }), + returns: Schema.String, + }, + (payload) => + Effect.gen(function* () { + const output = Schema.Struct({ head: Schema.String }); + const first = yield* agent.try("first", { + brief: "Fix it.", + project: payload.project, + returns: output, + ...(payload.timeout === undefined ? {} : { timeout: payload.timeout }), + }); + if (first.outcome === "done") return first.value.head; + const second = yield* agent.try("second", { + brief: "Fix it.", + project: "p1", + returns: output, + }); + if (second.outcome === "failed") return yield* stop(second.reason); + const where = payload.thread === true ? ` in ${first.thread?.threadId ?? "no thread"}` : ""; + return `${second.value.head} after: ${first.reason}${where}`; + }), + ), +]; + +type Started = Parameters[0]; + +/** Agents the test plays: it sees each turn start and decides how that turn ends. */ +const fakeAgents = () => { + const turns = new Map< + string, + { started: Deferred.Deferred; ended: Deferred.Deferred } + >(); + const interrupted: Array<{ + readonly threadId: string; + readonly environment?: string | undefined; + readonly turnId?: string | undefined; + }> = []; + let threads = 0; + let refusals = 0; + const unreadable = new Set(); + const unanswered = new Set(); + const unstartable = new Set(); + const turn = (key: string) => { + const known = turns.get(key); + if (known !== undefined) return known; + const made = { + started: Deferred.makeUnsafe(), + ended: Deferred.makeUnsafe(), + }; + turns.set(key, made); + return made; + }; + return { + service: WorkflowAgents.of({ + start: (input) => + Effect.gen(function* () { + // The engine's own setting for reading integers must not reach what a step calls. + if (yield* SqlClient.SafeIntegers) { + return yield* new WorkflowAgentError({ reason: "SafeIntegers leaked into a step" }); + } + if (input.project === "nowhere" || unstartable.delete(input.key)) { + return yield* new WorkflowAgentError({ reason: "No project is registered there." }); + } + yield* Deferred.succeed(turn(input.key).started, input); + // As the threads do: the issue a thread is linked to is what its step touched. + if (input.issue !== undefined && "url" in input.issue) { + yield* noteReference({ + kind: "issue", + key: input.issue.url, + address: { url: input.issue.url }, + title: "", + }); + } + return { + threadId: input.thread ?? `thread-${++threads}`, + turnId: input.key, + ...(input.environment === undefined ? {} : { environment: input.environment }), + }; + }), + result: (started) => { + const once = (keys: Set) => + [...keys].some((key) => started.turnId.endsWith(`/${key}`) && keys.delete(key)); + if (once(unreadable)) { + return Effect.fail(new WorkflowAgentError({ reason: "the result could not be read" })); + } + return once(unanswered) ? Effect.never : Deferred.await(turn(started.turnId).ended); + }, + // Counted per try, so a retry of the same stop uses up a refusal too. + interrupt: (thread) => + Effect.gen(function* () { + if (yield* SqlClient.SafeIntegers) { + return yield* new WorkflowAgentError({ reason: "SafeIntegers leaked into a stop" }); + } + if (refusals-- > 0) return yield* new WorkflowAgentError({ reason: "the link is down" }); + interrupted.push(thread); + const ended = + thread.turnId !== undefined && turns.has(thread.turnId) + ? yield* Deferred.isDone(turns.get(thread.turnId)!.ended) + : false; + return ended ? ("ended" as const) : ("stopped" as const); + }), + }), + interrupted, + /** The next read of a turn with this key fails. */ + unreadableResult: (key: string) => { + unreadable.add(key); + }, + /** The next read of a turn with this key never answers, as one that is waited past. */ + unansweredResult: (key: string) => { + unanswered.add(key); + }, + /** The turn of `runId` with this key cannot be started. */ + unstartable: (runId: string, key: string) => { + unstartable.add(`${runId}/${key}`); + }, + /** Turns down the next `count` stops. */ + refuseStops: (count: number) => { + refusals = count; + }, + /** The turn of `runId` with this key, once it has been started. */ + started: (runId: string, key: string) => Deferred.await(turn(`${runId}/${key}`).started), + end: (runId: string, key: string, result: Partial) => + Deferred.succeed(turn(`${runId}/${key}`).ended, { + ending: "completed" as const, + detail: "", + reply: "", + ...result, + }), + }; +}; + +/** While set, `nightly` turns down every tick, so its start fails. */ +const ticks = { refused: false }; +const triggered = [ + workflow( + "nightly", + { + version: 1, + payload: Tick.check(Schema.makeFilter(() => !ticks.refused || "not now")), + returns: Schema.String, + triggers: [every("1 hour")], + }, + (tick) => Effect.succeed(tick.scheduledAt), + ), + workflow( + "morning", + { version: 1, payload: Tick, triggers: [daily("09:00", { weekdays: [1, 2, 3, 4, 5] })] }, + () => Effect.void, + ), + workflow( + "inbound", + { + version: 1, + payload: WebhookRequest, + triggers: [ + webhook("push", { + key: (request) => + request.headers["x-delivery"] ?? + (JSON.parse(request.body) as { readonly delivery?: string }).delivery, + }), + ], + }, + (request) => (request.body === "ping" ? skip("only a ping") : Effect.succeed(request.body)), + ), +]; + +const PROJECT = "/home/me/app"; +const triage = workflow( + "triage", + { + version: 1, + payload: Issue, + returns: Schema.String, + triggers: [issues.opened({ project: PROJECT, labels: ["bug"] })], + }, + Effect.fn(function* (issue) { + yield* step( + "thank", + { returns: Schema.Void }, + issues.comment(issue, `Looking at ${issue.title}.`), + ); + return issue.displayKey; + }), +); +const decodeIssue = Schema.decodeSync(Issue); +const land = workflow( + "land", + { version: 1, payload: Schema.Struct({ url: Schema.String }), returns: Schema.String }, + Effect.fn(function* (payload) { + const standing = yield* pullRequests.wait( + "checks", + { project: PROJECT, url: payload.url }, + { until: "checks", timeout: "1 hour" }, + ); + return Option.match(standing, { onNone: () => "gave up", onSome: (at) => at.checks }); + }), +); +const issueAt = (key: string, createdAt: string) => + decodeIssue({ + projectId: "project-1", + projectTitle: "app", + tracker: "github", + host: "github.com", + scope: "me/app", + key, + displayKey: `#${key}`, + title: `Issue ${key}`, + url: `https://github.com/me/app/issues/${key}`, + author: null, + state: { name: "open", category: "open" }, + createdAt, + updatedAt: createdAt, + closedAt: null, + assignees: [], + labels: [], + commentCount: 0, + }); +/** A tracker that lists what the test put in it and remembers what was said. */ +// The real trackers read the server's own tables, which do not decode under the engine's BigInts. +const asTheServerReads = (answer: () => A) => + Effect.flatMap(SqlClient.SafeIntegers, (bigInts) => + bigInts + ? Effect.fail(new WorkflowForgeError({ reason: "called with the engine's BigInts on" })) + : Effect.sync(answer), + ); + +const fakeForge = () => { + const open: Array = []; + const asked: Array[0]> = []; + const comments: Array = []; + const pullRequest = { + state: "open", + mergeability: "mergeable", + url: "https://github.com/me/app/pull/7", + checks: [{ name: "test", status: "pending", description: null, url: null }], + }; + return { + open, + asked, + comments, + pullRequest, + service: WorkflowForge.of({ + ...unavailable, + pullRequests: { + ...unavailable.pullRequests, + // Only what a wait looks at; the rest of a pull request is the host's business. + read: () => + asTheServerReads(() => structuredClone(pullRequest)).pipe( + Effect.tap((read) => + noteReference( + pullRequestReferenceOf( + { + projectId: ProjectId.make("project-1"), + host: "github.com", + repository: "me/app", + number: 7, + }, + { url: read.url, state: read.state }, + ), + ), + ), + Effect.map((read) => read as never), + ), + }, + issues: { + ...unavailable.issues, + list: (query) => + asTheServerReads(() => { + asked.push(query); + return open; + }), + comment: (issue, body) => + asTheServerReads( + () => void comments.push(`${"key" in issue ? issue.key : issue.url}: ${body}`), + ).pipe( + Effect.andThen("key" in issue ? noteReference(issueReference(issue)) : Effect.void), + ), + }, + }), + }; +}; + +const harness = Effect.fnUntraced(function* (store?: typeof WorkflowStore.layer) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-workflows-" }); + const database = NodeSqliteClient.layer({ filename: path.join(directory, "state.sqlite") }); + yield* Effect.provide(WorkflowsMigration, database); + const counts = yield* Ref.make>({}); + const failures = yield* Ref.make(0); + const latch: Latch = { + entered: yield* Deferred.make(), + release: yield* Deferred.make(), + cleaned: yield* Deferred.make(), + bad: yield* Deferred.make(), + }; + // One database file, so a second engine built from it is the server after a restart. + const agents = fakeAgents(); + const forge = fakeForge(); + const all = [ + triage, + land, + ...definitions(counts, failures, latch), + fix, + ...triggered, + ...stored, + ...family, + ...control, + ]; + const engineOf = (registered: typeof all) => + WorkflowEngine.layer(registered, store).pipe( + Layer.provide(Layer.succeed(WorkflowAgents, agents.service)), + Layer.provide(Layer.succeed(WorkflowForge, forge.service)), + Layer.provide(database), + Layer.provide(NodeCrypto.layer), + ); + // The engine polls its message store, backs off between retries and bounds its shutdown, all + // on the clock, so time runs for as long as a server is up, shutdown included. A test closes + // `clock` to hold time still until it has seen what it waits for. + const clock = yield* Latch.make(true); + /** With `registered`, a server whose files define only those. */ + const boot = (use: Effect.Effect, registered = all) => + Effect.raceFirst( + Effect.scoped(Effect.provide(use, engineOf(registered))), + Effect.forever(Effect.andThen(clock.await, TestClock.adjust("1 second"))), + ); + return { counts, failures, latch, boot, agents, forge, clock, database }; +}); + +/** The store the engine writes to, for a test to leave what a crash would have left. */ +const exposedStore = () => { + const made = Deferred.makeUnsafe(); + return { + layer: Layer.effect( + WorkflowStore.WorkflowStore, + Effect.tap(WorkflowStore.make, (store) => Deferred.succeed(made, store)), + ), + store: Deferred.await(made), + }; +}; + +/** The review workflow sleeps first, which is waiting too; this is its wait for a verdict. */ +const atVerdict = (run: WorkflowRun) => run.status === "waiting" && run.detail === "verdict"; +const status = + (...statuses: ReadonlyArray) => + (run: WorkflowRun) => + statuses.includes(run.status); + +it.effect( + "a failing step pauses its run, and resuming runs that step again and nothing before it", + () => + Effect.gen(function* () { + const { counts, failures, boot, database } = yield* harness(); + yield* Ref.set(failures, 2); + const runId = yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const { runId } = yield* workflows.start("flaky", { id: "a" }, { idempotencyKey: "a" }); + const again = yield* workflows.start("flaky", { id: "a" }, { idempotencyKey: "a" }); + assert.equal(again.runId, runId); + + const paused = yield* workflows.waitFor(runId, status("paused")); + assert.include(paused.detail ?? "", "the dependency is down"); + assert.equal(paused.pauses, 1); + // It says when it tries again by itself, which is after it paused. + assert.isTrue(paused.resumesAt !== null && paused.resumesAt > paused.updatedAt); + + yield* workflows.resume(runId); + const pausedAgain = yield* workflows.waitFor(runId, (run) => run.pauses === 2); + assert.equal(pausedAgain.status, "paused"); + return runId; + }), + ); + + // The server restarts while the run is paused. Nothing retries it until it is resumed. + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + assert.equal((yield* workflows.get(runId)).run.status, "paused"); + yield* workflows.resume(runId); + const done = yield* workflows.waitFor(runId, status("completed")); + assert.equal(done.result, "done on attempt 1"); + assert.equal(done.pauses, 0); + const { steps } = yield* workflows.get(runId); + assert.deepStrictEqual( + steps.map((step) => [step.name, step.status, step.attempts]), + [ + ["before", "completed", 1], + ["flaky", "completed", 3], + ], + ); + }), + ); + assert.deepStrictEqual(yield* Ref.get(counts), { before: 1, flaky: 1 }); + + // An hour after it ended its engine journal goes, and starting its key again is still that run. + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const journal = Effect.flatMap( + SqlClient.SqlClient, + (sql) => sql<{ readonly n: number | bigint }>` + SELECT COUNT(*) AS n FROM cluster_messages WHERE entity_id = ${runId} + `, + ).pipe( + Effect.map((rows) => Number(rows[0]?.n ?? 0)), + Effect.provide(database), + ); + assert.isAbove(yield* journal, 0); + yield* TestClock.adjust("2 hours"); + yield* workflows.sweep; + assert.equal(yield* journal, 0); + const again = yield* workflows.start("flaky", { id: "a" }, { idempotencyKey: "a" }); + assert.equal(again.runId, runId); + assert.equal((yield* workflows.get(runId)).run.status, "completed"); + }), + ); + assert.deepStrictEqual(yield* Ref.get(counts), { before: 1, flaky: 1 }); + + // `step.try` hands the failure to the workflow instead of pausing, and runs once by default. + yield* Ref.set(failures, 1); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const { runId } = yield* workflows.start( + "flaky", + { id: "b", settle: true }, + { idempotencyKey: "b" }, + ); + const done = yield* workflows.waitFor(runId, status("completed")); + assert.equal(done.result, "gave up: the dependency is down"); + assert.equal(done.pauses, 0); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a signal to a paused run is kept for the resume and does not run the failed step", () => + Effect.gen(function* () { + const { counts, failures, latch, boot } = yield* harness(); + yield* Ref.set(failures, 2); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const { runId } = yield* workflows.start("sibling", {}, { idempotencyKey: "sib" }); + yield* workflows.waitFor(runId, (run) => run.status === "waiting" && run.detail === "sib"); + yield* Deferred.succeed(latch.bad, undefined); + yield* workflows.waitFor(runId, status("paused")); + assert.equal( + yield* workflows.signal({ runId, wait: "sib" }, "x", { id: "sib-x" }), + "delivered", + ); + yield* workflows.resume(runId); + const again = yield* workflows.waitFor(runId, (run) => run.pauses === 2); + assert.equal(again.status, "paused"); + yield* workflows.resume(runId); + const done = yield* workflows.waitFor(runId, status("completed", "paused")); + assert.deepStrictEqual([done.status, done.result], ["completed", "1 x"]); + const bad = (yield* workflows.get(runId)).steps.find((step) => step.name === "bad"); + assert.equal(bad?.attempts, 3); + }), + ); + assert.deepStrictEqual(yield* Ref.get(counts), { "bad tries": 3, bad: 1 }); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a wait survives a restart, checks what it is signalled with, and steps run once", () => + Effect.gen(function* () { + const { counts, boot } = yield* harness(); + const runId = yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const { runId } = yield* workflows.start( + "review", + { change: "c1" }, + { idempotencyKey: "c1" }, + ); + const waiting = yield* workflows.waitFor(runId, atVerdict); + assert.equal(waiting.title, "review of c1"); + // The sleep before the wait is a step a person can see. + const slept = (yield* workflows.get(runId)).steps.find((step) => step.name === "settle"); + assert.deepStrictEqual([slept?.kind, slept?.status], ["sleep", "completed"]); + const wrong = yield* workflows + .signal({ runId, wait: "verdict" }, { merge: "yes" }, { id: "s0" }) + .pipe(Effect.flip); + assert.include(wrong.message, "merge"); + return runId; + }), + ); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + // Addressed by key: the sender knows the change, not the run. + assert.equal( + yield* workflows.signal( + { workflow: "review", channel: "c1" }, + { merge: true }, + { id: "s1" }, + ), + "delivered", + ); + const done = yield* workflows.waitFor(runId, status("completed")); + assert.equal(done.result, "2 checks, merge: true"); + }), + ); + assert.deepStrictEqual(yield* Ref.get(counts), { "check/a": 1, "check/b": 1, after: 1 }); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a signal its wait cannot read leaves the wait open for one it can", () => + Effect.gen(function* () { + const { boot } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const { runId } = yield* workflows.start("reading", {}, { idempotencyKey: "t1" }); + yield* workflows.waitFor(runId, status("waiting")); + yield* workflows.signal({ runId, wait: "count" }, "many", { id: "t-many" }); + // Delivered straight or kept until the wait opens again: either way it is read. + yield* workflows.signal({ runId, wait: "count" }, "5", { id: "t-5" }); + const done = yield* workflows.waitFor(runId, status("completed", "paused")); + assert.deepStrictEqual([done.status, done.result], ["completed", 5]); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a signal sent before its wait opens is delivered when it does", () => + Effect.gen(function* () { + const { boot } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + assert.equal( + yield* workflows.signal( + { workflow: "review", channel: "c2" }, + { merge: false }, + { id: "s2" }, + ), + "buffered", + ); + const { runId } = yield* workflows.start( + "review", + { change: "c2" }, + { idempotencyKey: "c2" }, + ); + const done = yield* workflows.waitFor(runId, status("completed")); + assert.equal(done.result, "2 checks, merge: false"); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a signal buffered as its wait opens is still delivered to that wait", () => + Effect.gen(function* () { + const looked = yield* Deferred.make(); + const opened = yield* Deferred.make(); + const checked = yield* Deferred.make(); + // Holds the signal between finding no wait and buffering, while the wait opens and finds no mail. + const store = Layer.effect( + WorkflowStore.WorkflowStore, + Effect.gen(function* () { + const real = yield* WorkflowStore.make; + let first = true; + return WorkflowStore.WorkflowStore.of({ + ...real, + waitAt: (address) => + Effect.tap(real.waitAt(address), () => { + if (!("channel" in address) || address.channel !== "c9" || !first) return Effect.void; + first = false; + return Effect.andThen(Deferred.succeed(looked, undefined), Deferred.await(opened)); + }), + mailNext: (addresses, passed) => + Effect.tap(real.mailNext(addresses, passed), (mail) => + mail === undefined && !first ? Deferred.succeed(checked, undefined) : Effect.void, + ), + }); + }), + ); + const { boot } = yield* harness(store); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const sent = yield* Effect.forkChild( + workflows.signal({ workflow: "review", channel: "c9" }, { merge: true }, { id: "s9" }), + ); + yield* Deferred.await(looked); + const { runId } = yield* workflows.start( + "review", + { change: "c9" }, + { idempotencyKey: "c9" }, + ); + // Released once the open wait has looked for mail and found none. + yield* Deferred.await(checked); + yield* Deferred.succeed(opened, undefined); + assert.equal(yield* Fiber.join(sent), "delivered"); + const done = yield* workflows.waitFor(runId, status("completed")); + assert.equal(done.result, "2 checks, merge: true"); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a wait another signal claimed first wakes with that signal's value", () => + Effect.gen(function* () { + // A second signal claims the wait just before the early mail is handed to it. + const store = Layer.effect( + WorkflowStore.WorkflowStore, + Effect.gen(function* () { + const real = yield* WorkflowStore.make; + return WorkflowStore.WorkflowStore.of({ + ...real, + mailDeliver: (signalId, runId, name, woke) => + Effect.andThen( + real.waitSignalled(runId, name, { expired: false, value: { merge: true } }), + real.mailDeliver(signalId, runId, name, woke), + ), + }); + }), + ); + const { boot } = yield* harness(store); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + assert.equal( + yield* workflows.signal( + { workflow: "review", channel: "c8" }, + { merge: false }, + { id: "s8" }, + ), + "buffered", + ); + const { runId } = yield* workflows.start( + "review", + { change: "c8" }, + { idempotencyKey: "c8" }, + ); + const done = yield* workflows.waitFor(runId, status("completed")); + assert.equal(done.result, "2 checks, merge: true"); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a wait past its timeout wakes with nothing, and a workflow may stop on its own", () => + Effect.gen(function* () { + const { boot } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const { runId } = yield* workflows.start( + "review", + { change: "c3", timeout: "now" }, + { idempotencyKey: "c3" }, + ); + yield* workflows.waitFor(runId, atVerdict); + yield* workflows.sweep; + const stopped = yield* workflows.waitFor(runId, status("stopped")); + assert.equal(stopped.detail, "nobody answered"); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a cancelled run ends, and two steps with one name pause their run", () => + Effect.gen(function* () { + // The start of `v3` is cut off once its row is written, before the engine has it. + const cutOff = new Set(["v3"]); + const store = Layer.effect( + WorkflowStore.WorkflowStore, + Effect.map(WorkflowStore.make, (real) => + WorkflowStore.WorkflowStore.of({ + ...real, + runStarted: (run) => + Effect.tap(real.runStarted(run), () => + cutOff.delete(run.idempotencyKey) ? Effect.die("the server stopped") : Effect.void, + ), + }), + ), + ); + const { boot } = yield* harness(store); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const waiting = yield* workflows.start( + "review", + { change: "c4" }, + { idempotencyKey: "c4" }, + ); + yield* workflows.waitFor(waiting.runId, atVerdict); + yield* workflows.cancel(waiting.runId, "not needed"); + const cancelled = (yield* workflows.get(waiting.runId)).run; + assert.equal(cancelled.status, "cancelled"); + assert.equal(cancelled.detail, "not needed"); + // A cancel with no reason gives none, rather than repeating that the run was cancelled. + const unexplained = yield* workflows.start( + "review", + { change: "c5" }, + { idempotencyKey: "c5" }, + ); + yield* workflows.waitFor(unexplained.runId, atVerdict); + yield* workflows.cancel(unexplained.runId); + assert.equal((yield* workflows.get(unexplained.runId)).run.detail, null); + // A signal for the wait it had is kept as mail, not delivered to a run that ended. + assert.equal( + yield* workflows.signal( + { runId: waiting.runId, wait: "verdict" }, + { merge: true }, + { id: "s4" }, + ), + "buffered", + ); + // A file written for the old `title(name, text)` is refused, not titled with the name. + assert.throws( + () => (title as (...args: ReadonlyArray) => unknown)("name", "Release v1"), + /takes only the text/, + ); + + const twice = yield* workflows.start("twice", {}, { idempotencyKey: "t1" }); + const paused = yield* workflows.waitFor(twice.runId, status("paused")); + assert.include(paused.detail ?? "", 'named "same"'); + // The cleanup step's name is taken by nothing else. + const reserved = yield* workflows.start("reserved", {}, { idempotencyKey: "r1" }); + const refusedName = yield* workflows.waitFor(reserved.runId, status("paused")); + assert.include(refusedName.detail ?? "", "cleanup step"); + + const missing = yield* workflows + .start("nothing", {}, { idempotencyKey: "n1" }) + .pipe(Effect.flip); + assert.equal(missing._tag, "WorkflowNotRegisteredError"); + // A version asked for by name is that version or nothing, never the latest instead. + const unknownVersion = yield* workflows + .start("twice", {}, { idempotencyKey: "t2", version: 2 }) + .pipe(Effect.flip); + assert.equal(unknownVersion.message, "Version 2 of workflow twice is not registered."); + const older = yield* workflows.start("versioned", {}, { idempotencyKey: "v1", version: 1 }); + const latest = yield* workflows.start("versioned", {}, { idempotencyKey: "v2" }); + assert.equal((yield* workflows.waitFor(older.runId, status("completed"))).result, 1); + assert.equal((yield* workflows.waitFor(latest.runId, status("completed"))).result, 2); + // A key is one run of the workflow, whichever version starts it again. + assert.deepStrictEqual( + yield* workflows.start("versioned", {}, { idempotencyKey: "v1" }), + older, + ); + // A start cut off between its row and the engine is executed by the next start. + const cut = yield* Effect.exit( + workflows.start("versioned", {}, { idempotencyKey: "v3", version: 1 }), + ); + assert.isTrue(Exit.isFailure(cut)); + const again = yield* workflows.start("versioned", {}, { idempotencyKey: "v3" }); + assert.equal((yield* workflows.waitFor(again.runId, status("completed"))).result, 1); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect( + "an agent returns checked data, a person answers, and a later step continues the thread", + () => + Effect.gen(function* () { + let kept: WorkflowStore.WorkflowStore["Service"] | undefined; + const store = Layer.effect( + WorkflowStore.WorkflowStore, + Effect.tap(WorkflowStore.make, (real) => Effect.sync(() => void (kept = real))), + ); + const { boot, agents } = yield* harness(store); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const { runId } = yield* workflows.start( + "fix", + { project: "p1", issue: "https://github.com/me/app/issues/9" }, + { idempotencyKey: "f1" }, + ); + + const write = yield* agents.started(runId, "write/0"); + assert.equal(write.project, "p1"); + assert.equal(write.thread, undefined); + assert.deepStrictEqual( + [write.outputSchema?.required, write.outputSchema?.additionalProperties], + [["branch"], false], + ); + // The number's own check reaches the agent, without the text JSON spells Infinity in. + assert.deepStrictEqual( + (write.outputSchema?.properties as Record | undefined)?.commits, + { anyOf: [{ type: "number", exclusiveMinimum: 0 }, { type: "null" }] }, + ); + // It ended its turn without a result: the same thread is asked for it, not for the work. + yield* agents.end(runId, "write/0", { reply: "done" }); + const correction = yield* agents.started(runId, "write/0/correct/0"); + assert.equal(correction.thread, "thread-1"); + assert.include(correction.prompt, "without an accepted result"); + // What it then submitted does not fit, and it is told so, not that nothing came. + yield* agents.end(runId, "write/0/correct/0", { output: { branch: 1 } }); + const misfit = yield* agents.started(runId, "write/0/correct/1"); + assert.include(misfit.prompt, "The result you submitted does not fit: Expected string"); + yield* agents.end(runId, "write/0/correct/1", { + output: { branch: "fix/1" }, + reply: "Pushed fix/1.", + }); + + yield* workflows.waitFor(runId, (run) => run.detail === "merge"); + // A person reads what the agent said beside the data it returned. + const detail = yield* workflows.get(runId); + const written = detail.steps.find((step) => step.name === "write"); + assert.deepStrictEqual( + [written?.result, written?.said], + [{ branch: "fix/1" }, "Pushed fix/1."], + ); + // Asked three times on its issue's thread, the step touched the issue once. + assert.deepStrictEqual( + detail.references.map(({ key, steps, origin }) => ({ key, steps, origin })), + [{ key: "https://github.com/me/app/issues/9", steps: ["write"], origin: "step" }], + ); + const [question] = yield* workflows.questions; + // The agent whose work raised the question is one click from it. + assert.deepStrictEqual(question?.thread, { threadId: "thread-1", environmentId: null }); + assert.deepStrictEqual(question?.request, { + title: "Merge fix/1?", + choices: ["Merge", "Leave"], + data: { branch: "fix/1" }, + }); + const refused = yield* workflows + .signal({ runId, wait: "merge" }, { choice: "Maybe" }, { id: "a0" }) + .pipe(Effect.flip); + assert.include(refused.message, "merge waits for"); + // Clicked twice: one answer, and nothing kept to answer it again. + yield* Effect.all( + [ + workflows.answer(runId, "merge", { choice: "Merge" }), + workflows.answer(runId, "merge", { choice: "Merge" }), + ], + { concurrency: "unbounded" }, + ); + yield* workflows.answer(runId, "merge", { choice: "Leave" }); + assert.isUndefined(yield* kept!.mailNext([{ runId, wait: "merge" }])); + + const land = yield* agents.started(runId, "land/0"); + assert.equal(land.thread, "thread-1"); + assert.equal(land.outputSchema, undefined); + yield* agents.end(runId, "land/0", { reply: "merged as abc123" }); + const done = yield* workflows.waitFor(runId, status("completed")); + assert.equal(done.result, "fix/1: merged as abc123"); + assert.deepStrictEqual(yield* workflows.questions, []); + // Each step keeps what it produced, for a person reading the run afterwards. + const { steps } = yield* workflows.get(runId); + assert.deepStrictEqual( + steps.map((step) => [step.name, step.result]), + [ + ["write", { branch: "fix/1" }], + ["merge", { choice: "Merge" }], + ["land", "merged as abc123"], + ], + ); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect( + "an agent whose turn dies is tried on a new thread, then its run pauses until resumed", + () => + Effect.gen(function* () { + const exposed = exposedStore(); + const { boot, agents } = yield* harness(exposed.layer); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const { runId } = yield* workflows.start( + "fix", + { project: "p1" }, + { idempotencyKey: "f2" }, + ); + yield* agents.started(runId, "write/0"); + // Its turn is stopped before the next one starts; a stop that fails pauses the run. + agents.refuseStops(3); + yield* agents.end(runId, "write/0", { ending: "failed", detail: "failed" }); + const refused = yield* workflows.waitFor(runId, status("paused")); + assert.include(refused.detail ?? "", "the link is down"); + // A stop that did not get through is tried again by itself. + assert.isNotNull(refused.resumesAt); + assert.equal(agents.interrupted.length, 0); + yield* agents.started(runId, "write/1"); + assert.equal(agents.interrupted.length, 1); + yield* agents.end(runId, "write/1", { ending: "failed", detail: "provider error" }); + + const paused = yield* workflows.waitFor(runId, status("paused")); + assert.include(paused.detail ?? "", "provider error"); + // An agent that gave up starts its whole job again on resume: a person decides that. + assert.isNull(paused.resumesAt); + // A resume cut off before it reached the engine is put back by the sweep, still held. + yield* (yield* exposed.store).runUnpaused(runId); + const putBack = yield* workflows.waitFor(runId, status("paused")); + assert.deepStrictEqual([putBack.status, putBack.resumesAt], ["paused", null]); + yield* workflows.resume(runId); + yield* agents.started(runId, "write/2"); + yield* agents.end(runId, "write/2", { output: { branch: "fix/2" } }); + yield* workflows.waitFor(runId, (run) => run.detail === "merge"); + yield* workflows.signal({ runId, wait: "merge" }, { choice: "Leave" }, { id: "a2" }); + const stopped = yield* workflows.waitFor(runId, status("stopped")); + assert.equal(stopped.detail, "left"); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect( + "a step that dies, or whose result cannot be stored, pauses its run like any failure", + () => + Effect.gen(function* () { + const { boot } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const dies = yield* workflows.start("broken", { how: "dies" }, { idempotencyKey: "b1" }); + const died = yield* workflows.waitFor(dies.runId, status("paused")); + assert.include(died.detail ?? "", "null dereference"); + const unstorable = yield* workflows.start( + "broken", + { how: "unstorable" }, + { idempotencyKey: "b2" }, + ); + const refused = yield* workflows.waitFor(unstorable.runId, status("paused")); + assert.include(refused.detail ?? "", "unstorable"); + assert.equal((yield* workflows.get(unstorable.runId)).steps[0]?.status, "failed"); + // Never marked done on the way, so each try counts as one more pause. + yield* workflows.waitFor(unstorable.runId, (run) => run.pauses >= 2); + + const loose = yield* workflows.start( + "broken", + { how: "undefined" }, + { idempotencyKey: "b3" }, + ); + const done = yield* workflows.waitFor(loose.runId, status("completed", "paused")); + assert.deepStrictEqual( + [done.status, done.result], + ["completed", { r: { outcome: "done" }, list: [null] }], + ); + const nested = yield* workflows.start( + "broken", + { how: "nested" }, + { idempotencyKey: "b4" }, + ); + const where = yield* workflows.waitFor(nested.runId, status("paused")); + assert.include(where.detail ?? "", "the result.deep[0].id is undefined"); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect( + "signals: one per wait, a retried id is not a second one, and early mail a wait cannot read is kept", + () => + Effect.gen(function* () { + let kept: WorkflowStore.WorkflowStore["Service"] | undefined; + const store = Layer.effect( + WorkflowStore.WorkflowStore, + Effect.tap(WorkflowStore.make, (real) => Effect.sync(() => void (kept = real))), + ); + const { boot } = yield* harness(store); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const key = { workflow: "review", channel: "k1" }; + // Two signals before any run waits: the first is not what the wait expects. + yield* workflows.signal(key, { merge: "x" }, { id: "bad" }); + yield* workflows.signal(key, { merge: true }, { id: "good" }); + const first = yield* workflows.start( + "review", + { change: "k1" }, + { idempotencyKey: "k1a" }, + ); + const done = yield* workflows.waitFor(first.runId, status("completed")); + assert.equal(done.result, "2 checks, merge: true"); + // Left for whichever wait on the channel reads it, another version's perhaps. + assert.equal((yield* kept!.mailNext([key]))?.signalId, "bad"); + // The sender retries the signal that was already delivered from the mail. + assert.equal(yield* workflows.signal(key, { merge: true }, { id: "good" }), "delivered"); + + const second = yield* workflows.start( + "review", + { change: "k1" }, + { idempotencyKey: "k1b" }, + ); + const third = yield* workflows.start( + "review", + { change: "k1" }, + { idempotencyKey: "k1c" }, + ); + yield* workflows.waitFor(second.runId, atVerdict); + yield* workflows.waitFor(third.runId, atVerdict); + // Nothing was left over for them, and each new signal wakes one run. + assert.equal(yield* workflows.signal(key, { merge: false }, { id: "s1" }), "delivered"); + assert.equal(yield* workflows.signal(key, { merge: true }, { id: "s2" }), "delivered"); + const results = [ + (yield* workflows.waitFor(second.runId, status("completed"))).result, + (yield* workflows.waitFor(third.runId, status("completed"))).result, + ]; + // Each new signal woke one of the two runs, whichever opened its wait first. + assert.sameMembers( + results.map((result) => String(result).split(", ")[1]), + ["merge: false", "merge: true"], + ); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("signals that race for the waits on one channel each wake one of them", () => + Effect.gen(function* () { + // All three senders look before any claims, and the two that lose look again together. + const barriers = [ + { at: 3, all: Deferred.makeUnsafe() }, + { at: 5, all: Deferred.makeUnsafe() }, + ]; + let looked = 0; + const store = Layer.effect( + WorkflowStore.WorkflowStore, + Effect.map(WorkflowStore.make, (real) => + WorkflowStore.WorkflowStore.of({ + ...real, + waitAt: (address) => + Effect.tap(real.waitAt(address), () => { + if (!("channel" in address) || address.channel !== "k3") return Effect.void; + const at = ++looked; + const barrier = barriers.find((candidate) => at <= candidate.at); + if (barrier === undefined) return Effect.void; + return at === barrier.at + ? Deferred.succeed(barrier.all, undefined) + : Deferred.await(barrier.all); + }), + }), + ), + ); + const { boot } = yield* harness(store); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const runs = yield* Effect.forEach(["k3a", "k3b", "k3c"], (key) => + workflows.start("review", { change: "k3" }, { idempotencyKey: key }), + ); + yield* Effect.forEach(runs, (run) => workflows.waitFor(run.runId, atVerdict)); + const sent = yield* Effect.forEach( + ["r1", "r2", "r3"], + (id) => workflows.signal({ workflow: "review", channel: "k3" }, { merge: true }, { id }), + { concurrency: "unbounded" }, + ); + assert.deepStrictEqual(sent, ["delivered", "delivered", "delivered"]); + for (const run of runs) yield* workflows.waitFor(run.runId, status("completed")); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect( + "onEnd runs once however the run ends, and a cancelled run's is tried until it works", + () => + Effect.gen(function* () { + const { boot, counts, failures, latch, clock } = yield* harness(); + const ended = (step: { readonly name: string }) => step.name === "onEnd"; + const heldId = yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const finished = yield* workflows.start( + "owned", + { mode: "finish" }, + { idempotencyKey: "f" }, + ); + const stopped = yield* workflows.start( + "owned", + { mode: "stop" }, + { idempotencyKey: "s" }, + ); + yield* workflows.waitFor(finished.runId, status("completed")); + yield* workflows.waitFor(stopped.runId, status("stopped")); + + const held = yield* workflows.start("owned", { mode: "hold" }, { idempotencyKey: "h" }); + yield* workflows.waitFor(held.runId, status("waiting")); + yield* Ref.set(failures, 1); + // Time stands still from here, so no sweep tries again before the first try is read. + yield* clock.close; + yield* workflows.cancel(held.runId, "not needed"); + // The first try failed, which is on the run for a person to see. + const firstTry = (yield* workflows.get(held.runId)).steps.find(ended); + assert.deepStrictEqual( + [firstTry?.status, firstTry?.detail], + ["failed", "the machine would not go"], + ); + // The next try rests a while however often the sweep looks, and needs its version. + yield* workflows.sweep; + const rested = (yield* workflows.get(held.runId)).steps.find(ended); + assert.deepStrictEqual([rested?.status, rested?.attempts], ["failed", 1]); + assert.deepInclude(yield* workflows.unfinished, { workflow: "owned", version: 1 }); + yield* clock.open; + return held.runId; + }), + ); + // Days with the server down do not end the tries. + yield* TestClock.adjust("2 days"); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + // The server's own sweep makes the next try. + const { steps } = Option.getOrThrow( + yield* workflows.watch.pipe( + Stream.mapEffect(() => workflows.get(heldId)), + Stream.filter((run) => + run.steps.some((step) => ended(step) && step.status === "completed"), + ), + Stream.runHead, + ), + ); + assert.deepStrictEqual( + steps.map((step) => [step.name, step.status, step.attempts]), + [ + ["take", "completed", 1], + ["go", "failed", 1], + ["onEnd", "completed", 2], + ], + ); + assert.notDeepInclude(yield* workflows.unfinished, { workflow: "owned", version: 1 }); + // Nothing is left to do, so another look changes nothing. + yield* workflows.sweep; + // A cleanup that works the first time is told why the run was cancelled, too. + const second = yield* workflows.start( + "owned", + { mode: "hold" }, + { idempotencyKey: "h2" }, + ); + yield* workflows.waitFor(second.runId, status("waiting")); + yield* workflows.cancel(second.runId, "changed my mind"); + const all = yield* Ref.get(counts); + assert.deepStrictEqual( + Object.entries(all).filter(([name]) => name.startsWith("end:")), + [ + ["end:finish:completed:", 1], + ["end:stop:stopped:no need", 1], + ["end:hold:cancelled:not needed", 1], + ["end:hold:cancelled:changed my mind", 1], + ], + ); + + // Cancelled with a step still going: the cleanup waits for that step to finish. + const busy = yield* workflows.start("owned", { mode: "busy" }, { idempotencyKey: "b" }); + yield* Deferred.await(latch.entered); + // The cancel itself comes back after a while, the step still going. + yield* workflows.cancel(busy.runId, "not needed"); + yield* Deferred.succeed(latch.release, undefined); + yield* Deferred.await(latch.cleaned); + assert.equal((yield* Ref.get(counts))["end:busy:after work"], 1); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect( + "the store is shared by runs, survives a restart, and a failed transaction writes nothing", + () => + Effect.gen(function* () { + const { boot } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const runs = yield* Effect.forEach(["a", "b", "c"], (key) => + workflows.start("tally", {}, { idempotencyKey: key }), + ); + const counted = yield* Effect.forEach(runs, (run) => + workflows.waitFor(run.runId, status("completed")), + ); + assert.sameMembers( + counted.map((run) => run.result), + [1, 2, 3], + ); + }), + ); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const next = yield* workflows.start("tally", {}, { idempotencyKey: "d" }); + assert.equal((yield* workflows.waitFor(next.runId, status("completed"))).result, 4); + // A key read with another schema is the step's failure, with the key in the reason. + const wrong = yield* workflows.start("tally", { wrong: true }, { idempotencyKey: "w" }); + const paused = yield* workflows.waitFor(wrong.runId, status("paused")); + assert.include(paused.detail ?? "", "The stored value at tally does not fit its schema"); + + // The first try fails inside the transaction, so the door it opened is not there, and + // the try count it raised is 1 again on the second try, which is the one that signals. + const waiting = yield* workflows.start("door", { door: "east" }, { idempotencyKey: "e" }); + yield* workflows.waitFor(waiting.runId, status("waiting")); + const opener = yield* workflows.start( + "opener", + { door: "east", fail: true }, + { idempotencyKey: "o" }, + ); + yield* workflows.waitFor(opener.runId, status("paused")); + assert.equal((yield* workflows.get(waiting.runId)).run.status, "waiting"); + const clean = yield* workflows.start( + "opener", + { door: "east", fail: false }, + { idempotencyKey: "o2" }, + ); + yield* workflows.waitFor(clean.runId, status("completed")); + assert.equal( + (yield* workflows.waitFor(waiting.runId, status("completed"))).result, + "came in", + ); + + // A retry sends again what the first try sent, and what it sends anew is new. + const doors = ["ra", "rb", "rc"]; + const held = yield* Effect.forEach(doors, (door) => + workflows.start("door", { door }, { idempotencyKey: door }), + ); + yield* Effect.forEach(held, (run) => workflows.waitFor(run.runId, status("waiting"))); + const relay = yield* workflows.start("relay", { doors }, { idempotencyKey: "relay" }); + yield* workflows.waitFor(relay.runId, status("completed")); + // Each try is an attempt, though both were one run of the step. + assert.equal((yield* workflows.get(relay.runId)).steps[0]?.attempts, 2); + assert.equal( + yield* workflows.signal({ workflow: "door", channel: "rc" }, "late", { id: "rc-late" }), + "buffered", + ); + const opened = yield* Effect.forEach(held, (run) => + workflows.waitFor(run.runId, status("completed")), + ); + assert.deepStrictEqual( + opened.map((run) => run.result), + ["came in", "came in", "came in"], + ); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("an invoked run reports how it ended, and cancelling the parent cancels it", () => + Effect.gen(function* () { + const { boot } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + // The kid of a parent that waits on it, once the kid itself waits. + const heldKid = Effect.gen(function* () { + const kid = (yield* workflows.list({})).find( + (run) => + run.workflow === "kid" && (run.status === "running" || run.status === "waiting"), + ); + return yield* workflows.waitFor(kid!.runId, status("waiting")); + }); + const finished = yield* workflows.start( + "parent", + { mode: "finish" }, + { idempotencyKey: "f" }, + ); + const stopped = yield* workflows.start("parent", { mode: "stop" }, { idempotencyKey: "s" }); + assert.equal( + (yield* workflows.waitFor(finished.runId, status("completed"))).result, + "grown", + ); + assert.equal( + (yield* workflows.waitFor(stopped.runId, status("completed"))).result, + "stopped: nothing to do", + ); + + const held = yield* workflows.start("parent", { mode: "hold" }, { idempotencyKey: "h" }); + yield* workflows.waitFor(held.runId, (run) => run.detail === "kid"); + const child = yield* heldKid; + yield* workflows.cancel(held.runId, "not needed"); + assert.equal((yield* workflows.get(child.runId)).run.status, "cancelled"); + + // A kid cancelled by itself is an outcome its parent hears, not a failure. + const second = yield* workflows.start("parent", { mode: "hold" }, { idempotencyKey: "h2" }); + yield* workflows.waitFor(second.runId, (run) => run.detail === "kid"); + const lone = yield* heldKid; + yield* workflows.cancel(lone.runId, "changed my mind"); + assert.equal( + (yield* workflows.waitFor(second.runId, status("completed"))).result, + "cancelled: changed my mind", + ); + + const spawner = yield* workflows.start("spawner", {}, { idempotencyKey: "sp" }); + const spawned = (yield* workflows.waitFor(spawner.runId, status("completed"))) + .result as ReadonlyArray; + assert.equal(spawned.length, 2); + for (const runId of spawned) { + assert.equal((yield* workflows.waitFor(runId, status("completed"))).result, "grown"); + } + + // A name taken twice pauses the run before the kid it names is started. + const clash = yield* workflows.start("clash", {}, { idempotencyKey: "c" }); + assert.include( + (yield* workflows.waitFor(clash.runId, status("paused"))).detail ?? "", + 'named "kid"', + ); + assert.deepStrictEqual( + (yield* workflows.list()).filter((run) => run.parentRunId === clash.runId), + [], + ); + const byName = yield* workflows.start("clash", { byName: true }, { idempotencyKey: "n" }); + assert.include( + (yield* workflows.waitFor(byName.runId, status("paused"))).detail ?? "", + "invoke takes the workflow definition, not its name", + ); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a cancel cut off midway still tells the run that invoked it", () => + Effect.gen(function* () { + // The cancel is cut off where it stops the run's steps, as a client that went away would. + const reached = yield* Deferred.make(); + let first = true; + const store = Layer.effect( + WorkflowStore.WorkflowStore, + Effect.map(WorkflowStore.make, (real) => + WorkflowStore.WorkflowStore.of({ + ...real, + stepsCancelled: (runId, except) => { + if (!first) return real.stepsCancelled(runId, except); + first = false; + return Effect.andThen(Deferred.succeed(reached, undefined), Effect.never); + }, + }), + ), + ); + const { boot } = yield* harness(store); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const parent = yield* workflows.start("parent", { mode: "hold" }, { idempotencyKey: "h" }); + yield* workflows.waitFor(parent.runId, (run) => run.detail === "kid"); + const kid = (yield* workflows.list({})).find((run) => run.workflow === "kid"); + yield* workflows.waitFor(kid!.runId, status("waiting")); + const cancelling = yield* Effect.forkChild(workflows.cancel(kid!.runId, "changed my mind")); + yield* Deferred.await(reached); + yield* Fiber.interrupt(cancelling); + assert.equal( + (yield* workflows.waitFor(parent.runId, status("completed"))).result, + "cancelled: changed my mind", + ); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("two agents run side by side, and one past its time limit is stopped", () => + Effect.gen(function* () { + const { boot, agents } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const run = yield* workflows.start("pair", {}, { idempotencyKey: "p" }); + // Both have started before either has ended. + yield* agents.started(run.runId, "left/0"); + yield* agents.started(run.runId, "right/0"); + yield* agents.end(run.runId, "left/0", { reply: "done" }); + // The right one never answers. Its minute passes, and a stop that cannot get through + // pauses the run without giving the turn up, so the next try stops it. + agents.refuseStops(3); + const refused = yield* workflows.waitFor(run.runId, status("paused")); + assert.include(refused.detail ?? "", "the link is down"); + assert.equal(agents.interrupted.length, 0); + const paused = yield* workflows.waitFor( + run.runId, + (current) => current.status === "paused" && current.detail !== refused.detail, + ); + assert.include(paused.detail ?? "", "it was not done after 1m"); + assert.equal(agents.interrupted.length, 1); + const { steps } = yield* workflows.get(run.runId); + assert.deepStrictEqual(steps.map((step) => [step.name, step.status]).toSorted(), [ + ["left", "completed"], + ["right", "failed"], + ]); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a continued thread keeps how it started", () => + Effect.gen(function* () { + const { boot, agents } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const run = yield* workflows.start( + "fix", + { project: "p1", reshape: true }, + { idempotencyKey: "r1" }, + ); + yield* agents.started(run.runId, "write/0"); + yield* agents.end(run.runId, "write/0", { output: { branch: "fix/1" } }); + yield* workflows.waitFor(run.runId, (current) => current.detail === "merge"); + yield* workflows.signal( + { runId: run.runId, wait: "merge" }, + { choice: "Merge" }, + { id: "m" }, + ); + const paused = yield* workflows.waitFor(run.runId, status("paused")); + assert.include(paused.detail ?? "", "Drop `model`"); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("an agent step in a linked environment keeps its thread there", () => + Effect.gen(function* () { + const { boot, agents } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const run = yield* workflows.start( + "fix", + { project: "/work/app", environment: "env-b" }, + { idempotencyKey: "e1" }, + ); + const write = yield* agents.started(run.runId, "write/0"); + assert.equal(write.environment, "env-b"); + yield* agents.end(run.runId, "write/0", { output: { branch: "fix/1" } }); + yield* workflows.waitFor(run.runId, status("waiting")); + yield* workflows.signal( + { runId: run.runId, wait: "merge" }, + { choice: "Merge" }, + { id: "m1" }, + ); + + // The step that continues the thread names no environment: the thread carries it. + const land = yield* agents.started(run.runId, "land/0"); + assert.equal(land.environment, "env-b"); + assert.equal(land.thread, "thread-1"); + yield* workflows.waitFor(run.runId, (current) => current.detail === "agent land"); + const { steps } = yield* workflows.get(run.runId); + assert.deepStrictEqual( + steps.filter((step) => step.kind === "agent").map((step) => step.environmentId), + ["env-b", "env-b"], + ); + yield* workflows.cancel(run.runId, "not needed"); + // Only the step's own turn: someone else's turn on that thread is left alone. + assert.deepStrictEqual(agents.interrupted, [ + { threadId: "thread-1", environment: "env-b", turnId: `${run.runId}/land/0` }, + ]); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("cancelling a run stops its agent, and a turn a person stopped is not tried again", () => + Effect.gen(function* () { + const { boot, agents } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const cancelled = yield* workflows.start( + "fix", + { project: "p1" }, + { idempotencyKey: "x1" }, + ); + yield* agents.started(cancelled.runId, "write/0"); + yield* workflows.waitFor(cancelled.runId, (run) => run.detail === "agent write"); + const { steps } = yield* workflows.get(cancelled.runId); + yield* workflows.cancel(cancelled.runId, "not needed"); + assert.deepStrictEqual(agents.interrupted, [ + { threadId: steps[0]?.threadId ?? "no thread", turnId: `${cancelled.runId}/write/0` }, + ]); + + const stopped = yield* workflows.start("fix", { project: "p1" }, { idempotencyKey: "x2" }); + yield* agents.started(stopped.runId, "write/0"); + yield* agents.end(stopped.runId, "write/0", { ending: "stopped", detail: "interrupted" }); + const paused = yield* workflows.waitFor(stopped.runId, status("paused")); + assert.include(paused.detail ?? "", "stopped"); + // Resuming is the person saying go on: the next round starts. + yield* workflows.resume(stopped.runId); + yield* agents.started(stopped.runId, "write/1"); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a watcher is sent the runs again when one changes", () => + Effect.gen(function* () { + const { boot } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const first = Option.getOrThrow(yield* Stream.runHead(workflows.watch)); + assert.deepStrictEqual([first.runs, first.questions], [[], []]); + // What exists is listed before anything has run, with what starts it. + assert.deepInclude(first.workflows, { + name: "inbound", + version: 1, + triggers: ["webhook push"], + }); + const { runId } = yield* workflows.start( + "review", + { change: "c9", timeout: "1 hour" }, + { idempotencyKey: "c9" }, + ); + const seen = yield* workflows.watch.pipe( + Stream.filter((snapshot) => snapshot.runs.some((run) => run.status === "waiting")), + Stream.runHead, + ); + assert.deepStrictEqual( + Option.getOrThrow(seen).runs.map((run) => run.runId), + [runId], + ); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect( + "a schedule starts one run when it is due, and one for all the times a restart missed", + () => + Effect.gen(function* () { + const { boot } = yield* harness(); + const nightly = (workflows: Workflows.Workflows["Service"]) => + Effect.map(workflows.list(), (runs) => runs.filter((run) => run.workflow === "nightly")); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + // The first look only notes when it is next due. + yield* workflows.sweep; + assert.deepStrictEqual(yield* nightly(workflows), []); + // A start that fails is tried again, not passed over for the next time it is due. + ticks.refused = true; + yield* TestClock.adjust("61 minutes"); + yield* workflows.sweep; + assert.deepStrictEqual(yield* nightly(workflows), []); + ticks.refused = false; + yield* workflows.sweep; + yield* workflows.sweep; + const [run] = yield* nightly(workflows); + assert.equal((yield* nightly(workflows)).length, 1); + const done = yield* workflows.waitFor(run!.runId, status("completed")); + assert.match(String(done.result), /^1970-01-01T01:/); + }), + ); + yield* TestClock.adjust("3 hours"); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + yield* workflows.sweep; + yield* workflows.sweep; + assert.equal((yield* nightly(workflows)).length, 2); + }), + ); + // Taken out of the file and put back long after it was due: due one interval from then. + const others = triggered.filter((definition) => definition.name !== "nightly"); + yield* boot( + Effect.flatMap(Workflows.Workflows, (workflows) => workflows.sweep), + others, + ); + yield* TestClock.adjust("3 hours"); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + yield* workflows.sweep; + yield* workflows.sweep; + assert.equal((yield* nightly(workflows)).length, 2); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("an issue opened after the workflow loaded starts one run, which can comment on it", () => + Effect.gen(function* () { + const starts: Array = []; + const store = Layer.effect( + WorkflowStore.WorkflowStore, + Effect.map(WorkflowStore.make, (real) => + WorkflowStore.WorkflowStore.of({ + ...real, + runStarted: (run) => + Effect.andThen( + Effect.sync(() => starts.push(run.idempotencyKey)), + real.runStarted(run), + ), + }), + ), + ); + const { boot, forge } = yield* harness(store); + const triaged = (workflows: Workflows.Workflows["Service"]) => + Effect.map(workflows.list(), (runs) => runs.filter((run) => run.workflow === "triage")); + forge.open.push(issueAt("1", "1969-12-31T23:00:00.000Z")); + // Before the mark too, written the way some hosts write a time. + forge.open.push(issueAt("3", "1970-01-01T00:30:00+01:00")); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + // The first look only notes the time: what was there already starts nothing. + yield* workflows.sweep; + yield* TestClock.adjust("2 minutes"); + // One the workflow turns down comes first, and does not hold back the one after it. + forge.open.push({ ...issueAt("bad", "1970-01-01T00:00:30.000Z"), title: 5 } as never); + forge.open.push(issueAt("2", "1970-01-01T00:01:00.000Z")); + yield* workflows.sweep; + yield* TestClock.adjust("2 minutes"); + yield* workflows.sweep; + const [run, ...others] = yield* triaged(workflows); + assert.deepStrictEqual(others, []); + const done = yield* workflows.waitFor(run!.runId, status("completed")); + assert.equal(done.result, "#2"); + assert.deepStrictEqual(forge.comments, ["2: Looking at Issue 2."]); + // The issue that started the run is the one its step commented on. + assert.deepStrictEqual( + (yield* workflows.get(run!.runId)).references.map( + ({ kind, title, state, steps, origin }) => ({ kind, title, state, steps, origin }), + ), + [{ kind: "issue", title: "Issue 2", state: "open", steps: ["thank"], origin: "trigger" }], + ); + // A later look still lists it, and leaves the run it has alone. + const before = starts.length; + yield* TestClock.adjust("2 minutes"); + yield* workflows.sweep; + assert.deepStrictEqual(starts.slice(before), []); + assert.deepStrictEqual(forge.asked.at(-1), { + project: PROJECT, + state: "all", + sort: "created", + limit: 100, + labels: ["bug"], + query: undefined, + }); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a wait on a pull request ends when its checks have, and says how", () => + Effect.gen(function* () { + const { boot, forge } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const { runId } = yield* workflows.start( + "land", + { url: forge.pullRequest.url }, + { idempotencyKey: "pr-7" }, + ); + yield* workflows.waitFor(runId, status("waiting")); + yield* workflows.sweep; + assert.equal((yield* workflows.waitFor(runId, () => true)).status, "waiting"); + // Not a question for anyone: nothing waits on a person. + assert.deepStrictEqual(yield* workflows.questions, []); + forge.pullRequest.checks[0]!.status = "success"; + yield* TestClock.adjust("2 minutes"); + yield* workflows.sweep; + const done = yield* workflows.waitFor(runId, status("completed")); + assert.equal(done.result, "passing"); + // Each look kept it on the wait's step, and the replay after the wake added nothing. + assert.deepStrictEqual( + (yield* workflows.get(runId)).references.map(({ kind, steps, state }) => ({ + kind, + steps, + state, + })), + [{ kind: "pullRequest", steps: ["checks"], state: "open" }], + ); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a step or sleep with an option it cannot read says which and what it takes", () => + Effect.gen(function* () { + assert.throws( + () => + step( + "push", + { returns: Schema.Void, retry: { times: 2, shedule: 1 } as never }, + Effect.void, + ), + 'step("push")\'s retry does not take `shedule`', + ); + const slept = yield* Effect.exit(sleep("z", "soon" as never) as unknown as Effect.Effect); + assert.include( + String(Exit.isFailure(slept) ? Cause.squash(slept.cause) : ""), + 'sleep("z") cannot read "soon" as a duration. Write one such as "5 minutes".', + ); + }), +); + +it("hooks of different workflows never share an id", () => { + assert.notEqual(Workflows.hookId("a.b", "c"), Workflows.hookId("a", "b.c")); + assert.equal(Workflows.hookId("inbound", "push"), "wf-inbound.push"); +}); + +it.effect("a request to a hook starts a run, its retry is the same run, and a bad token none", () => + Effect.gen(function* () { + const { boot } = yield* harness(); + const request = (body: string, delivery: string) => ({ + method: "POST", + headers: { "x-delivery": delivery }, + query: "", + body, + }); + const token = yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const [hook] = yield* workflows.hooks; + assert.equal(hook?.workflow, "inbound"); + const [hookId, token] = hook!.path.split("/").slice(-2).map(decodeURIComponent); + const deliver = (body: string, delivery: string, withToken = token!) => + workflows.deliver({ + hookId: hookId!, + token: withToken, + request: request(body, delivery), + }); + + assert.isTrue(Option.isNone(yield* deliver("hello", "d1", "not the token"))); + const first = Option.getOrThrow(yield* deliver("hello", "d1")); + assert.deepStrictEqual(Option.getOrThrow(yield* deliver("hello", "d1")), first); + const done = yield* workflows.waitFor(first.runId, status("completed")); + assert.equal(done.result, "hello"); + + const ping = Option.getOrThrow(yield* deliver("ping", "d2")); + const skipped = yield* workflows.waitFor(ping.runId, status("skipped")); + assert.equal(skipped.detail, "only a ping"); + + const send = (headers: Record, body: string) => + workflows.deliver({ + hookId: hookId!, + token: token!, + request: { method: "POST", headers, query: "", body }, + }); + // With no key from the workflow, the id the sender keeps on its retry makes it one run. + const github = { "x-github-delivery": "g1" }; + const sent = Option.getOrThrow(yield* send(github, "{}")); + assert.deepStrictEqual(Option.getOrThrow(yield* send(github, "{}")), sent); + // A key the workflow cannot read off the request turns the request down. + const unreadable = yield* send({}, "not json").pipe(Effect.flip); + assert.equal(unreadable._tag, "WorkflowInputError"); + return token; + }), + ); + // The URL a sender was given still works after a restart. + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + assert.isTrue((yield* workflows.hooks)[0]?.path.endsWith(`/${token}`)); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a step finds runs by their key, wakes everyone at a key, and cancels another run", () => + Effect.gen(function* () { + const { boot } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const visit = (key: string, at: string) => + workflows.start("gate", { gate: at }, { idempotencyKey: key }); + const keeper = Effect.fn(function* (act: "look" | "open" | "dismiss" | "leave") { + const run = yield* workflows.start("keeper", { act }, { idempotencyKey: act }); + return yield* workflows.waitFor(run.runId, status("completed", "paused")); + }); + const [one, two, three] = yield* Effect.all([ + visit("visit/1", "north"), + visit("visit/2", "north"), + visit("visit/3", "south"), + ]); + // Not at a gate, and not started as a visit: none of the keeper's business. + yield* workflows.start("review", { change: "north" }, { idempotencyKey: "other" }); + for (const run of [one, two, three]) yield* workflows.waitFor(run.runId, status("waiting")); + + assert.deepStrictEqual((yield* keeper("look")).result, [ + "visit/1 waiting", + "visit/2 waiting", + "visit/3 waiting", + ]); + // Both at the north gate go through on one signal; the one at the south gate stays. + assert.equal((yield* keeper("open")).result, 2); + for (const run of [one, two]) { + assert.equal((yield* workflows.waitFor(run.runId, status("completed"))).result, "go on"); + } + assert.equal((yield* workflows.get(three.runId)).run.status, "waiting"); + + yield* keeper("dismiss"); + const dismissed = (yield* workflows.get(three.runId)).run; + assert.deepStrictEqual( + [dismissed.status, dismissed.detail], + ["cancelled", "the gate is closed"], + ); + // A run ends itself with `stop`; cancelling itself would cut the cancel short. + const left = yield* keeper("leave"); + assert.equal(left.status, "paused"); + assert.include(left.detail ?? "", "cannot cancel itself"); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a workflow can take an agent's failure as an answer and go on", () => + Effect.gen(function* () { + const { boot, agents } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + // The first agent's turn dies, and so does the one more try it gets. + const died = yield* workflows.start("fallback", { project: "p1" }, { idempotencyKey: "d" }); + yield* agents.started(died.runId, "first/0"); + yield* agents.end(died.runId, "first/0", { ending: "failed", detail: "failed" }); + yield* agents.started(died.runId, "first/1"); + yield* agents.end(died.runId, "first/1", { ending: "failed", detail: "failed" }); + yield* agents.started(died.runId, "second/0"); + yield* agents.end(died.runId, "second/0", { output: { head: "abc" } }); + const done = yield* workflows.waitFor(died.runId, status("completed", "paused")); + assert.deepStrictEqual( + [done.status, done.pauses, done.result], + ["completed", 0, "abc after: the agent's turn was cut short: failed"], + ); + const { steps } = yield* workflows.get(died.runId); + assert.deepStrictEqual( + steps.map((step) => [step.name, step.status]), + [ + ["first", "failed"], + ["second", "completed"], + ], + ); + + // An agent that cannot be started at all is an answer too. + const lost = yield* workflows.start( + "fallback", + { project: "nowhere" }, + { idempotencyKey: "n" }, + ); + yield* agents.started(lost.runId, "second/0"); + yield* agents.end(lost.runId, "second/0", { output: { head: "def" } }); + const found = yield* workflows.waitFor(lost.runId, status("completed", "paused")); + assert.equal( + found.result, + "def after: the agent could not be started: No project is registered there.", + ); + + // A result that cannot be read leaves the turn maybe running: a stop that fails gives up + // the step, and no second turn starts beside it. + const stopsBefore = agents.interrupted.length; + agents.refuseStops(3); + agents.unreadableResult("first/0"); + const unread = yield* workflows.start( + "fallback", + { project: "p1" }, + { idempotencyKey: "u" }, + ); + yield* agents.started(unread.runId, "second/0"); + assert.equal(agents.interrupted.length, stopsBefore); + yield* agents.end(unread.runId, "second/0", { output: { head: "jkl" } }); + const gaveUp = yield* workflows.waitFor(unread.runId, status("completed", "paused")); + assert.include(gaveUp.result as string, "its turn could not be stopped"); + + // One past its time whose turn cannot be stopped says so, for the workflow to weigh. + agents.refuseStops(3); + const stuck = yield* workflows.start( + "fallback", + { project: "p1", timeout: "1 minute" }, + { idempotencyKey: "s" }, + ); + yield* agents.started(stuck.runId, "second/0"); + yield* agents.end(stuck.runId, "second/0", { output: { head: "ghi" } }); + const weighed = yield* workflows.waitFor(stuck.runId, status("completed", "paused")); + assert.include(weighed.result as string, "its turn could not be stopped"); + + // A stop turned down once gets through on its retry, and the step says it was stopped. + const before = agents.interrupted.length; + agents.refuseStops(1); + const late = yield* workflows.start( + "fallback", + { project: "p1", timeout: "1 minute" }, + { idempotencyKey: "l" }, + ); + yield* agents.started(late.runId, "second/0"); + assert.equal(agents.interrupted.length, before + 1); + yield* agents.end(late.runId, "second/0", { output: { head: "mno" } }); + const retried = yield* workflows.waitFor(late.runId, status("completed", "paused")); + assert.equal(retried.status, "completed"); + assert.notInclude(retried.result as string, "could not be stopped"); + + // A result that arrived as its time ran out, before it was read, is still the answer. + agents.unansweredResult("first/0"); + const lastMinute = yield* workflows.start( + "fallback", + { project: "p1", timeout: "1 minute" }, + { idempotencyKey: "m" }, + ); + yield* agents.started(lastMinute.runId, "first/0"); + yield* agents.end(lastMinute.runId, "first/0", { output: { head: "pqr" } }); + yield* agents.end(lastMinute.runId, "second/0", { output: { head: "not needed" } }); + const answered = yield* workflows.waitFor(lastMinute.runId, status("completed", "paused")); + assert.equal(answered.result, "pqr"); + + // One whose turn had ended without its result is not said to be stopped: the agent may + // answer from a later turn nobody stopped. + agents.unansweredResult("first/0"); + const owing = yield* workflows.start( + "fallback", + { project: "p1", timeout: "1 minute" }, + { idempotencyKey: "o" }, + ); + yield* agents.started(owing.runId, "first/0"); + yield* agents.end(owing.runId, "first/0", {}); + yield* agents.started(owing.runId, "second/0"); + yield* agents.end(owing.runId, "second/0", { output: { head: "stu" } }); + const owed = yield* workflows.waitFor(owing.runId, status("completed", "paused")); + assert.include(owed.result as string, "may still be at work"); + + // One that did the work and never gave its result is not given the job again: it may + // have acted on it already. + const silent = yield* workflows.start( + "fallback", + { project: "p1", thread: true }, + { idempotencyKey: "q" }, + ); + for (const key of ["first/0", "first/0/correct/0", "first/0/correct/1"]) { + yield* agents.started(silent.runId, key); + yield* agents.end(silent.runId, key, {}); + } + yield* agents.end(silent.runId, "first/1", { output: { head: "twice" } }); + yield* agents.end(silent.runId, "second/0", { output: { head: "vwx" } }); + const once = yield* workflows.waitFor(silent.runId, status("completed", "paused")); + assert.match( + once.result as string, + /^vwx after: the agent did not return a result: .* in thread-\d+$/, + ); + + // A correction that cannot be sent leaves the failure with the thread the work is in. + const unasked = yield* workflows.start( + "fallback", + { project: "p1", thread: true }, + { idempotencyKey: "c" }, + ); + agents.unstartable(unasked.runId, "first/0/correct/0"); + yield* agents.started(unasked.runId, "first/0"); + yield* agents.end(unasked.runId, "first/0", {}); + yield* agents.end(unasked.runId, "second/0", { output: { head: "yz" } }); + const kept = yield* workflows.waitFor(unasked.runId, status("completed", "paused")); + assert.match(kept.result as string, /could not be asked again: .* in thread-\d+$/); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); diff --git a/apps/server/src/workflows/Workflows.ts b/apps/server/src/workflows/Workflows.ts new file mode 100644 index 0000000000000..1b26479d6bd7a --- /dev/null +++ b/apps/server/src/workflows/Workflows.ts @@ -0,0 +1,221 @@ +import { + type WorkflowCounts, + type WorkflowHook, + WorkflowQuestion, + type WorkflowRunReference, + type WorkflowRunsSnapshot, +} from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import type * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; + +import type { WebhookRequest } from "./triggers.ts"; +import type * as WorkflowStore from "./WorkflowStore.ts"; + +/** Hook ids of workflows start with this; a scheduled task's hook id never does. */ +export const HOOK_PREFIX = "wf-"; + +// The dot between the two parts is never in either, so no two hooks share an id. +const hookPart = (part: string) => encodeURIComponent(part).replaceAll(".", "%2E"); +/** The id of the hook `name` of `workflow`, which its URL and its secret are kept by. */ +export const hookId = (workflow: string, name: string) => + `${HOOK_PREFIX}${hookPart(workflow)}.${hookPart(name)}`; + +export class WorkflowNotRegisteredError extends Schema.TaggedError()( + "WorkflowNotRegisteredError", + { workflow: Schema.String, version: Schema.optional(Schema.Number) }, +) { + override get message(): string { + return this.version === undefined + ? `No workflow named ${this.workflow} is registered.` + : `Version ${this.version} of workflow ${this.workflow} is not registered.`; + } +} + +export class WorkflowRunNotFoundError extends Schema.TaggedError()( + "WorkflowRunNotFoundError", + { runId: Schema.String }, +) { + override get message(): string { + return `Workflow run ${this.runId} was not found.`; + } +} + +export class WorkflowInputError extends Schema.TaggedError()( + "WorkflowInputError", + { problem: Schema.String }, +) { + override get message(): string { + return this.problem; + } +} + +export { WorkflowQuestion }; + +export type WorkflowError = + | WorkflowNotRegisteredError + | WorkflowRunNotFoundError + | WorkflowInputError; + +export class Workflows extends Context.Service< + Workflows, + { + /** Start a run. A second start with the same key is the same run. */ + readonly start: ( + workflow: string, + input: unknown, + options: { + readonly idempotencyKey: string; + /** The run that waits for this one. A run started with a key has one parent or none. */ + readonly parent?: WorkflowStore.RunParent; + /** The version to run, when the caller holds a definition. Without it, the newest. */ + readonly version?: number; + }, + ) => Effect.Effect<{ readonly runId: string }, WorkflowError>; + /** + * Say that something a run waits on happened. `delivered` woke a wait; `buffered` is kept for + * a wait that has not opened yet, for `ttl` (seven days by default). + */ + readonly signal: ( + address: WorkflowStore.SignalAddress, + value: Schema.Json, + options: { readonly id: string; readonly ttl?: Duration.Input }, + ) => Effect.Effect<"delivered" | "buffered", WorkflowInputError>; + /** + * Answer the question a run asks a person. One answer per time it is asked: a second, a + * double click, wakes nothing and is not kept for later. + */ + readonly answer: ( + runId: string, + name: string, + value: Schema.Json, + ) => Effect.Effect; + /** Run a paused run's failed step again. */ + readonly resume: (runId: string) => Effect.Effect; + readonly cancel: (runId: string, reason?: string) => Effect.Effect; + readonly get: (runId: string) => Effect.Effect< + { + readonly run: WorkflowStore.WorkflowRun; + readonly steps: ReadonlyArray; + readonly references: ReadonlyArray; + }, + WorkflowRunNotFoundError | WorkflowInputError + >; + readonly list: (filter?: { + readonly status?: WorkflowStore.WorkflowRunStatus; + }) => Effect.Effect, WorkflowInputError>; + /** The run once `done` holds for it. Looks now, then on every change to the run. */ + readonly waitFor: ( + runId: string, + done: (run: WorkflowStore.WorkflowRun) => boolean, + ) => Effect.Effect; + /** The questions runs are waiting on a person to answer, oldest first. */ + readonly questions: Effect.Effect, WorkflowInputError>; + /** What each run that has not ended is a run of, however many: no list limit applies. */ + readonly unfinished: Effect.Effect< + ReadonlyArray<{ readonly workflow: string; readonly version: number }> + >; + /** The hook URLs of the registered workflows. */ + readonly hooks: Effect.Effect, WorkflowInputError>; + /** + * Start the run a request to a hook asks for. Nothing, for a hook or token that is not known. + * `deliveryId` names the delivery when its carrier vouches for one, so its retry is one run. + */ + readonly deliver: (delivery: { + readonly hookId: string; + readonly token: string; + readonly request: WebhookRequest; + readonly deliveryId?: string; + }) => Effect.Effect, WorkflowError>; + /** What workflows keep in the store under keys starting with `prefix`, for a person to see. */ + readonly stored: ( + prefix: string, + ) => Effect.Effect< + ReadonlyArray<{ readonly key: string; readonly value: Schema.Json }>, + WorkflowInputError + >; + /** Set a key of the store from outside a run, as a person flipping a switch does. */ + readonly storeSet: (key: string, value: Schema.Json) => Effect.Effect; + readonly storeDelete: (key: string) => Effect.Effect; + /** Recent runs and open questions, now and again after every change. */ + readonly watch: Stream.Stream; + /** How much is going on, now and again whenever a count changes. */ + readonly counts: Stream.Stream; + /** + * Deliver timeouts to waits past their deadline, drop expired mail, and resume paused runs + * whose rest is over. Runs by itself every few seconds. + */ + readonly sweep: Effect.Effect; + } +>()("t3/workflows/Workflows") {} + +const refuse = Effect.fn("Workflows.disabled")(function* () { + return yield* new WorkflowInputError({ + problem: + "This server defines no workflows yet. Add a file to the workflows folder of its T3 home.", + }); +}); + +/** The service with nothing registered and no engine behind it. */ +export const disabled = Workflows.of({ + start: refuse, + signal: refuse, + answer: refuse, + resume: refuse, + cancel: refuse, + get: Effect.fn("Workflows.get")(function* (runId) { + return yield* new WorkflowRunNotFoundError({ runId }); + }), + list: Effect.fn("Workflows.list")(function* () { + return yield* Effect.succeed>([]); + }), + waitFor: Effect.fn("Workflows.waitFor")(function* () { + return yield* Effect.never; + }), + questions: Effect.succeed([]), + unfinished: Effect.succeed([]), + hooks: Effect.succeed([]), + deliver: Effect.fn("Workflows.deliver")(function* () { + return yield* Effect.succeed(Option.none<{ readonly runId: string }>()); + }), + stored: Effect.fn("Workflows.stored")(function* () { + return yield* Effect.succeed>([]); + }), + storeSet: refuse, + storeDelete: refuse, + watch: Stream.concat(Stream.make({ workflows: [], runs: [], questions: [] }), Stream.never), + counts: Stream.concat(Stream.make({ needsYou: 0, active: 0, total: 0 }), Stream.never), + sweep: Effect.void, +}); +export const layerDisabled = Layer.succeed(Workflows, disabled); + +export const OFF = + 'Workflows are off on this server. Turn them on in its Settings → Labs → Workflows, or without a desktop, set "workflowsEnabled": true in userdata/settings.json in its T3 home (~/.t3 by default).'; + +const refuseOff = Effect.fn("Workflows.off")(function* () { + return yield* new WorkflowInputError({ problem: OFF }); +}); + +/** + * The service while workflows are off: every request is refused, and a hook answers as one that + * is not there. + */ +export const off = Workflows.of({ + ...disabled, + start: refuseOff, + signal: refuseOff, + answer: refuseOff, + resume: refuseOff, + cancel: refuseOff, + get: refuseOff, + list: refuseOff, + questions: refuseOff(), + hooks: refuseOff(), + stored: refuseOff, + storeSet: refuseOff, + storeDelete: refuseOff, +}); diff --git a/apps/server/src/workflows/api.ts b/apps/server/src/workflows/api.ts new file mode 100644 index 0000000000000..9f1bfd72b15ca --- /dev/null +++ b/apps/server/src/workflows/api.ts @@ -0,0 +1,15 @@ +// Everything a definitions module is handed. A workflow file imports nothing: an installed server +// is one bundle, with no package for it to import these from, and its own copy of `effect` would +// not be the one the engine runs. +export * as Duration from "effect/Duration"; +export * as Effect from "effect/Effect"; +export * as Option from "effect/Option"; +export * as Schedule from "effect/Schedule"; +export * as Schema from "effect/Schema"; + +export { daily, every, Tick, webhook, WebhookRequest } from "./triggers.ts"; +export { issues, pullRequests } from "./forgeApi.ts"; +export { cancel, runs, signal, signalAll, start, store } from "./stepServices.ts"; +export { Issue, IssueDetail, PullRequest, PullRequestStanding } from "./WorkflowForge.ts"; +export { invoke, skip, sleep, step, stop, title, wait, workflow } from "./workflow.ts"; +export { agent, ask } from "./workflowAgent.ts"; diff --git a/apps/server/src/workflows/forgeApi.ts b/apps/server/src/workflows/forgeApi.ts new file mode 100644 index 0000000000000..a7e0839730201 --- /dev/null +++ b/apps/server/src/workflows/forgeApi.ts @@ -0,0 +1,109 @@ +// Issues and pull requests as a workflow file sees them: triggers, calls for inside a step, and a +// wait on a pull request for the body. +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import type * as Option from "effect/Option"; + +import { checkOptions } from "./options.ts"; +import { issuesOpened, pullRequestsOpened } from "./triggers.ts"; +import type { InRun } from "./workflow.ts"; +import { waitAs } from "./workflow.ts"; +import { + type IssueAddress, + type PullRequestAddress, + PullRequestStanding, + type PullRequestUntil, + type PullRequestWatch, + WorkflowForge, +} from "./WorkflowForge.ts"; + +const forge = (use: (forge: WorkflowForge["Service"]) => Effect.Effect) => + Effect.flatMap(WorkflowForge, use); + +/** + * The project's issues, in whichever tracker it uses. `opened` is a trigger; the rest are for + * inside `step` or `onEnd`. An issue is named by what a trigger or `list` gave, or by + * `{ project, url }`. + */ +export const issues = { + opened: issuesOpened, + list: (query: Parameters[0]) => { + checkOptions("issues.list", query, [ + "project", + "state", + "labels", + "query", + "assignee", + "sort", + "limit", + ]); + return forge((all) => all.issues.list(query)); + }, + read: (issue: IssueAddress) => forge((all) => all.issues.read(issue)), + comment: (issue: IssueAddress, body: string) => forge((all) => all.issues.comment(issue, body)), + /** Move the issue to one of its `states`, as `read` lists them. */ + setState: (issue: IssueAddress, state: string) => + forge((all) => all.issues.setState(issue, state)), + create: (input: Parameters[0]) => { + checkOptions("issues.create", input, ["project", "title", "body", "labels", "assignees"]); + return forge((all) => all.issues.create(input)); + }, +}; + +/** + * The project's pull requests on its git host. `opened` is a trigger; the rest are for inside + * `step` or `onEnd`. A pull request is named by what a trigger or `list` gave, or by + * `{ project, url }`. + */ +export const pullRequests = { + opened: pullRequestsOpened, + list: (query: Parameters[0]) => { + checkOptions("pullRequests.list", query, ["project", "state", "query", "limit"]); + return forge((all) => all.pullRequests.list(query)); + }, + read: (pullRequest: PullRequestAddress) => forge((all) => all.pullRequests.read(pullRequest)), + comment: (pullRequest: PullRequestAddress, body: string) => + forge((all) => all.pullRequests.comment(pullRequest, body)), + /** `merge`, `close`, `ready`, `update-branch` and the host's other actions on a pull request. */ + act: ( + pullRequest: PullRequestAddress, + action: Parameters[1], + options?: Parameters[2], + ) => { + checkOptions("pullRequests.act", options, ["mergeMethod"]); + return forge((all) => all.pullRequests.act(pullRequest, action, options)); + }, + /** + * Wait in the body until the pull request gets somewhere, without holding anything: `checks` + * until none of its checks is still running, `merged` or `closed` until it is no longer open. + * A pull request that is merged or closed ends any of them. Gives where it stands, or nothing + * after `timeout`. The host is asked about once a minute. + */ + wait: ( + name: string, + pullRequest: PullRequestAddress, + options: { readonly until: PullRequestUntil; readonly timeout?: Duration.Input }, + ): Effect.Effect, never, InRun> => { + checkOptions(`pullRequests.wait("${name}")`, options, ["until", "timeout"]); + return Effect.orDie( + waitAs("wait", name, { + returns: PullRequestStanding, + timeout: options.timeout, + watch: { + kind: "pullRequest", + until: options.until, + // Only the address: a listing's row carries far more than a wait needs to keep. + pullRequest: + "url" in pullRequest && "project" in pullRequest + ? { project: pullRequest.project, url: pullRequest.url } + : { + projectId: pullRequest.projectId, + host: pullRequest.host, + repository: pullRequest.repository, + number: pullRequest.number, + }, + } satisfies PullRequestWatch, + }), + ); + }, +}; diff --git a/apps/server/src/workflows/options.ts b/apps/server/src/workflows/options.ts new file mode 100644 index 0000000000000..7ba47abf65f27 --- /dev/null +++ b/apps/server/src/workflows/options.ts @@ -0,0 +1,28 @@ +import * as Duration from "effect/Duration"; +import * as Option from "effect/Option"; + +/** The duration `input` is, or an error that names `what` and shows one that reads. */ +export const durationOf = (what: string, input: Duration.Input): Duration.Duration => + Option.getOrThrowWith( + Duration.fromInput(input), + () => + new Error( + `${what} cannot read ${JSON.stringify(input)} as a duration. Write one such as "5 minutes".`, + ), + ); + +/** + * Refuses an option the call does not take. A workflow file is not type-checked, so a misspelt or + * renamed option would otherwise be dropped without a word. + */ +export const checkOptions = ( + what: string, + options: object | undefined, + allowed: ReadonlyArray, +) => { + if (options === undefined || options === null) return; + const unknown = Object.keys(options).filter((key) => !allowed.includes(key)); + if (unknown.length === 0) return; + const listed = (keys: ReadonlyArray) => keys.map((key) => `\`${key}\``).join(", "); + throw new Error(`${what} does not take ${listed(unknown)}. It takes ${listed(allowed)}.`); +}; diff --git a/apps/server/src/workflows/runReferences.ts b/apps/server/src/workflows/runReferences.ts new file mode 100644 index 0000000000000..8599a3a6cae5b --- /dev/null +++ b/apps/server/src/workflows/runReferences.ts @@ -0,0 +1,90 @@ +// What a run touched, for a person reading the run: the issue that started it, the pull request a +// step merged. Anything that touches something calls `noteReference`; a new kind of thing is a +// new caller, and nothing else changes. +import { + type IssueRef, + type IssueState, + type PullRequestRef, + WorkflowReferenceKind, +} from "@t3tools/contracts"; +import * as Cause from "effect/Cause"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import type * as Schema from "effect/Schema"; + +import type { ReferenceInput, WorkflowStore } from "./WorkflowStore.ts"; + +/** Keeps what the step whose code is running touches, against that step. */ +export class StepReferences extends Context.Service< + StepReferences, + { readonly note: (reference: ReferenceInput) => Effect.Effect } +>()("t3/workflows/runReferences/StepReferences") {} + +/** Keep that `runId` touched `reference`, from `step` or, with none, from what started it. */ +export const noteFor = ( + store: WorkflowStore["Service"], + runId: string, + step: string | null, + reference: ReferenceInput, +): Effect.Effect => + store.referenceNoted(runId, step, reference).pipe( + // Only for a person to read: a step must never fail or wait over it. + Effect.catchCause((cause) => + Effect.logWarning("Could not keep what a workflow run touched", { + runId, + step, + kind: reference.kind, + cause: Cause.pretty(cause), + }), + ), + ); + +/** Keep that the running step touched `reference`. Outside a step it does nothing. */ +export const noteReference = (reference: ReferenceInput): Effect.Effect => + Effect.flatMap(Effect.serviceOption(StepReferences), (current) => + current._tag === "None" ? Effect.void : current.value.note(reference), + ); + +export const stepReferences = ( + store: WorkflowStore["Service"], + runId: string, + step: string, +): Context.Context => + Context.make(StepReferences, { note: (reference) => noteFor(store, runId, step, reference) }); + +/** An issue, with its title and where it stands when the toucher read them. */ +export const issueReference = ( + ref: IssueRef, + seen?: { readonly title: string; readonly url: string; readonly state: IssueState }, +): ReferenceInput => ({ + kind: WorkflowReferenceKind.issue, + key: JSON.stringify([ref.tracker, ref.host ?? "", ref.scope.toLowerCase(), ref.key]), + address: { + projectId: ref.projectId, + tracker: ref.tracker, + ...(ref.host === undefined ? {} : { host: ref.host }), + scope: ref.scope, + key: ref.key, + } satisfies Schema.Json, + title: seen?.title ?? "", + url: seen?.url, + state: seen?.state.category, +}); + +/** A pull request by its normalized host and repository, so every way of naming it is one. */ +export const pullRequestReference = ( + ref: Pick & { readonly host: string }, + seen?: { readonly title?: string; readonly url?: string; readonly state?: string }, +): ReferenceInput => ({ + kind: WorkflowReferenceKind.pullRequest, + key: JSON.stringify([ref.host, ref.repository, ref.number]), + address: { + projectId: ref.projectId, + host: ref.host, + repository: ref.repository, + number: ref.number, + }, + title: seen?.title ?? "", + url: seen?.url, + state: seen?.state, +}); diff --git a/apps/server/src/workflows/stepServices.ts b/apps/server/src/workflows/stepServices.ts new file mode 100644 index 0000000000000..53c6773494c3b --- /dev/null +++ b/apps/server/src/workflows/stepServices.ts @@ -0,0 +1,458 @@ +// What a step's own code may use besides plain Effect: state shared between runs, and a way to +// wake a run that waits. Both touch the world, so they are for inside `step` and `onEnd`. +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Deferred from "effect/Deferred"; +import type * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; + +import { checkOptions } from "./options.ts"; +import { type StepReferences, stepReferences } from "./runReferences.ts"; +import type { WorkflowDefinition } from "./workflow.ts"; +import { WorkflowForge } from "./WorkflowForge.ts"; +import type { WorkflowError, WorkflowInputError } from "./Workflows.ts"; +import type { + RunParent, + SignalAddress, + WorkflowRunStatus, + WorkflowStore, +} from "./WorkflowStore.ts"; + +/** The shared store as rows of JSON text. `store` puts schemas on top. */ +export class KeyValues extends Context.Service< + KeyValues, + { + readonly get: (key: string) => Effect.Effect; + readonly set: (key: string, valueJson: string) => Effect.Effect; + readonly delete: (key: string) => Effect.Effect; + readonly list: ( + prefix: string, + ) => Effect.Effect>; + readonly transaction: (effect: Effect.Effect) => Effect.Effect; + } +>()("t3/workflows/stepServices/KeyValues") {} + +export type SendSignal = ( + address: SignalAddress, + value: Schema.Json, + options: { readonly id: string; readonly ttl?: Duration.Input }, +) => Effect.Effect<"delivered" | "buffered", WorkflowInputError>; + +/** Everyone who waits on a key, in one workflow or in all of them. */ +export interface EveryoneAt { + readonly channel: string; + readonly workflow?: string | undefined; +} +export type SendSignalToAll = (address: EveryoneAt, value: Schema.Json) => Effect.Effect; + +/** A run as a step of another run sees it. `key` is what it was started with. */ +export interface RunSummary { + readonly id: string; + readonly workflow: string; + readonly key: string; + readonly title: string; + readonly status: WorkflowRunStatus; + readonly detail: string | null; + readonly startedAt: string; + readonly endedAt: string | null; +} +export interface RunFilter { + readonly workflow?: string | undefined; + readonly status?: WorkflowRunStatus | undefined; + readonly keyPrefix?: string | undefined; +} + +/** Signals from the step that is running. Its signals are numbered, so a retry sends the same ones. */ +export class Signals extends Context.Service< + Signals, + { + readonly sendAll: SendSignalToAll; + readonly send: ( + address: SignalAddress, + value: Schema.Json, + options?: { readonly id?: string; readonly ttl?: Duration.Input }, + ) => Effect.Effect<"delivered" | "buffered", WorkflowInputError>; + } +>()("t3/workflows/stepServices/Signals") {} + +export type StartRun = ( + workflow: string, + input: unknown, + options: { + readonly idempotencyKey: string; + readonly parent?: RunParent; + /** The version the caller was written against. Without it, the newest registered. */ + readonly version?: number; + }, +) => Effect.Effect<{ readonly runId: string }, WorkflowError>; + +export type CancelRun = (runId: string, reason: string) => Effect.Effect; +export type ListRuns = (filter: RunFilter) => Effect.Effect>; + +/** Other runs, from the step that is running: starting, finding and cancelling them. */ +export class Runs extends Context.Service< + Runs, + { readonly start: StartRun; readonly cancel: CancelRun; readonly list: ListRuns } +>()("t3/workflows/stepServices/Runs") {} + +export type InStep = KeyValues | Signals | Runs | WorkflowForge | StepReferences; + +/** + * What a step needs of the engine, which exists only once the engine does, while the workflows + * that use it are registered before. The engine fills this in when it starts. + */ +export class EngineLink extends Context.Service< + EngineLink, + { + current: + | { + readonly signal: SendSignal; + readonly signalAll: SendSignalToAll; + readonly start: StartRun; + readonly cancel: CancelRun; + readonly list: ListRuns; + /** Tell the run that invoked `runId`, if one did, how it ended. */ + readonly ended: (runId: string) => Effect.Effect; + } + | undefined; + /** The steps of each run that are running in this process right now. */ + readonly inFlight: InFlight; + } +>()("t3/workflows/stepServices/EngineLink") {} +export interface InFlight { + readonly track: ( + runId: string, + effect: Effect.Effect, + ) => Effect.Effect; + /** Whether a step of `runId` is running now. */ + readonly busy: (runId: string) => boolean; + /** Waits until no step of `runId` is running. */ + readonly settled: (runId: string) => Effect.Effect; +} + +// A step cannot be interrupted, so whatever cleans up after a cancelled run waits for it here. +const makeInFlight = (): InFlight => { + const running = new Map }>(); + return { + track: (runId, effect) => + Effect.acquireUseRelease( + Effect.sync(() => { + const entry = running.get(runId) ?? { count: 0, idle: Deferred.makeUnsafe() }; + entry.count++; + running.set(runId, entry); + return entry; + }), + () => effect, + (entry) => + Effect.suspend(() => { + if (--entry.count > 0) return Effect.void; + running.delete(runId); + return Deferred.succeed(entry.idle, undefined); + }), + ), + busy: (runId) => running.has(runId), + settled: (runId) => + Effect.suspend(() => { + const entry = running.get(runId); + return entry === undefined ? Effect.void : Deferred.await(entry.idle); + }), + }; +}; + +export const layerEngineLink = Layer.sync(EngineLink, () => ({ + current: undefined, + inFlight: makeInFlight(), +})); + +const engineOf = (link: EngineLink["Service"]) => + link.current === undefined + ? Effect.die(new Error("The workflow engine is not up.")) + : Effect.succeed(link.current); + +/** + * The services for the step `name` of `runId`. Each signal it sends is the two, where it goes, + * and how many it sent there before, so a retry that sends the same again is not new. What it + * touches through the forge is kept against it. + */ +export const forStep = ( + store: WorkflowStore["Service"], + keyValues: KeyValues["Service"], + link: EngineLink["Service"], + forge: WorkflowForge["Service"], + runId: string, + name: string, +): Context.Context => { + const owner = `${runId}/${name}`; + const sent = new Map(); + return Context.make(KeyValues, keyValues).pipe( + Context.add(WorkflowForge, forge), + Context.merge(stepReferences(store, runId, name)), + Context.add( + Signals, + Signals.of({ + send: Effect.fn("Signals.send")(function* (address, value, options) { + const { signal: send } = yield* engineOf(link); + const to = ( + "runId" in address + ? ["run", address.runId, address.wait] + : ["key", address.workflow, address.channel] + ) + .map(encodeURIComponent) + .join("/"); + const before = sent.get(to) ?? 0; + sent.set(to, before + 1); + return yield* send(address, value, { + id: options?.id ?? `${owner}/signal/${to}/${before}`, + ...(options?.ttl === undefined ? {} : { ttl: options.ttl }), + }); + }), + sendAll: Effect.fn("Signals.sendAll")(function* (address, value) { + const engine = yield* engineOf(link); + return yield* engine.signalAll(address, value); + }), + }), + ), + Context.add( + Runs, + Runs.of({ + start: Effect.fn("Runs.start")(function* (workflow, input, options) { + const engine = yield* engineOf(link); + return yield* engine.start(workflow, input, options); + }), + cancel: Effect.fn("Runs.cancel")(function* (target, reason) { + // Cancelling interrupts the run, and this step is the run: it would cut itself off + // halfway through the cancel. + if (target === runId) { + return yield* Effect.die( + new Error("A run cannot cancel itself. End it from its body with `stop`."), + ); + } + const engine = yield* engineOf(link); + return yield* engine.cancel(target, reason); + }), + list: Effect.fn("Runs.list")(function* (filter) { + const engine = yield* engineOf(link); + return yield* engine.list(filter); + }), + }), + ), + ); +}; + +export const layerKeyValues = Layer.effect( + KeyValues, + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + // LIKE would read `%` and `_` in a prefix as patterns; a range does not. + const after = (prefix: string) => `${prefix}\u{10FFFF}`; + return KeyValues.of({ + get: Effect.fn("KeyValues.get")(function* (key) { + const rows = yield* sql<{ value_json: string }>` + SELECT value_json FROM workflow_store WHERE key = ${key} + `.pipe(Effect.orDie); + return rows[0]?.value_json; + }), + set: Effect.fn("KeyValues.set")(function* (key, valueJson) { + const at = DateTime.formatIso(yield* DateTime.now); + yield* sql` + INSERT INTO workflow_store (key, value_json, updated_at) + VALUES (${key}, ${valueJson}, ${at}) + ON CONFLICT (key) DO UPDATE + SET value_json = excluded.value_json, updated_at = excluded.updated_at + `.pipe(Effect.orDie); + }), + delete: Effect.fn("KeyValues.delete")(function* (key) { + yield* sql`DELETE FROM workflow_store WHERE key = ${key}`.pipe(Effect.orDie); + }), + list: Effect.fn("KeyValues.list")(function* (prefix) { + const rows = yield* sql<{ key: string; value_json: string }>` + SELECT key, value_json FROM workflow_store + WHERE key >= ${prefix} AND key < ${after(prefix)} ORDER BY key + `.pipe(Effect.orDie); + return rows.map((row) => ({ key: row.key, valueJson: row.value_json })); + }), + transaction: Effect.fn("KeyValues.transaction")(function* (effect) { + return yield* sql.withTransaction(effect).pipe(Effect.catchTags({ SqlError: Effect.die })); + }), + }); + }), +); + +/** A value that no longer fits its schema, or never did. */ +export class StoreValueError extends Schema.TaggedError()("StoreValueError", { + key: Schema.String, + problem: Schema.String, +}) { + override get message(): string { + return `The stored value at ${this.key} does not fit its schema: ${this.problem}`; + } +} + +/** + * One key of the store, with the schema of what it holds. `update` reads and writes as one + * action, so two runs counting on the same key never lose a count; returning `undefined` from it + * deletes the key. + */ +const entry = (key: string, schema: Schema.Codec) => { + const codec = Schema.fromJsonString(Schema.toCodecJson(schema)); + const decode = Schema.decodeEffect(codec); + const encode = Schema.encodeEffect(codec); + const invalid = (error: unknown) => new StoreValueError({ key, problem: String(error) }); + const read = (store: KeyValues["Service"]) => + Effect.flatMap(store.get(key), (text) => + text === undefined + ? Effect.succeed(Option.none()) + : Effect.mapBoth(decode(text), { onFailure: invalid, onSuccess: Option.some }), + ); + const write = (store: KeyValues["Service"], value: A) => + encode(value).pipe( + Effect.mapError(invalid), + Effect.flatMap((text) => store.set(key, text)), + ); + return { + key, + get: Effect.flatMap(KeyValues, read), + set: (value: A) => Effect.flatMap(KeyValues, (store) => write(store, value)), + delete: Effect.flatMap(KeyValues, (store) => store.delete(key)), + update: (change: (current: Option.Option) => A | undefined) => + Effect.flatMap(KeyValues, (store) => + store.transaction( + Effect.gen(function* () { + const next = change(yield* read(store)); + if (next === undefined) { + yield* store.delete(key); + return Option.none(); + } + yield* write(store, next); + return Option.some(next); + }), + ), + ), + }; +}; + +/** Every key that starts with `prefix`, in key order, with what it holds. */ +const entries = (prefix: string, schema: Schema.Codec) => { + const codec = Schema.fromJsonString(Schema.toCodecJson(schema)); + const decode = Schema.decodeEffect(codec); + return Effect.flatMap(KeyValues, (store) => + Effect.flatMap(store.list(prefix), (rows) => + Effect.forEach(rows, (row) => + Effect.mapBoth(decode(row.valueJson), { + onFailure: (error) => new StoreValueError({ key: row.key, problem: String(error) }), + onSuccess: (value) => ({ key: row.key, value }), + }), + ), + ), + ); +}; + +/** Several reads and writes as one: all of them happen, or none. */ +const transaction = (effect: Effect.Effect) => + Effect.flatMap(KeyValues, (store) => store.transaction(effect)); + +/** + * State that outlives a run and is shared by every workflow on this server. Use it inside `step` + * or `onEnd`: what it returns changes over time, so the body itself must not read it. + */ +export const store = { entry, entries, transaction }; + +/** A workflow by its name or its definition, wherever one is named. */ +export type WorkflowName = string | Pick; +const nameOf = (workflow: WorkflowName) => + typeof workflow === "string" ? workflow : workflow.name; + +/** + * Wake a run that waits: `{ runId, wait }` for one wait of one run, `{ workflow, channel }` for + * whichever run of a workflow waits on a channel. Inside `step` or `onEnd` only. + */ +export const signal = ( + address: + | { readonly runId: string; readonly wait: string } + | { readonly workflow: WorkflowName; readonly channel: string }, + value: Schema.Json, + options?: { readonly id?: string; readonly ttl?: Duration.Input }, +) => + Effect.flatMap(Signals, (signals) => { + checkOptions( + "signal's address", + address, + "runId" in address ? ["runId", "wait"] : ["workflow", "channel"], + ); + checkOptions("signal", options, ["id", "ttl"]); + return signals.send( + "runId" in address + ? address + : { workflow: nameOf(address.workflow), channel: address.channel }, + value, + options, + ); + }); + +/** + * Start a run of another workflow and go on without it. The same `key` is the same run. Inside + * `step` or `onEnd` only; to wait for the run's result, use `invoke` in the body instead. + */ +export const start =

    ( + workflow: WorkflowDefinition

    , + payload: P, + options: { readonly key: string }, +) => + Effect.flatMap(Runs, (runs) => { + checkOptions("start", options, ["key"]); + return runs.start(workflow.name, payload, { + idempotencyKey: options.key, + version: workflow.version, + }); + }); + +/** + * Wake every run that waits on `channel`, in one workflow or, without `workflow`, in all of them. + * Returns how many it woke. Nothing is kept for a wait that opens later, so a run that waits on + * a condition checks the condition in a step first, and gives its wait a timeout to check again. + * Inside `step` or `onEnd` only. + */ +export const signalAll = ( + address: { readonly channel: string; readonly workflow?: WorkflowName }, + value: Schema.Json, +) => + Effect.flatMap(Signals, (signals) => { + checkOptions("signalAll's address", address, ["channel", "workflow"]); + return signals.sendAll( + { + channel: address.channel, + workflow: address.workflow === undefined ? undefined : nameOf(address.workflow), + }, + value, + ); + }); + +/** + * Cancel another run, as a person would: its agents are stopped, its questions withdrawn, what + * it invoked is cancelled, and its `onEnd` runs. A run that has ended is left alone. Inside + * `step` or `onEnd` only. + */ +export const cancel = (runId: string, reason: string) => + Effect.flatMap(Runs, (runs) => runs.cancel(runId, reason)); + +/** + * Find runs: of one workflow, in one status, or started with a key that begins with `keyPrefix`. + * Newest first, 500 at most. Inside `step` or `onEnd` only: the answer changes over time. + */ +export const runs = (filter?: { + readonly workflow?: WorkflowName; + readonly status?: WorkflowRunStatus; + readonly keyPrefix?: string; +}) => + Effect.flatMap(Runs, (all) => { + checkOptions("runs", filter, ["workflow", "status", "keyPrefix"]); + return all.list({ + workflow: filter?.workflow === undefined ? undefined : nameOf(filter.workflow), + status: filter?.status, + keyPrefix: filter?.keyPrefix, + }); + }); diff --git a/apps/server/src/workflows/triggers.ts b/apps/server/src/workflows/triggers.ts new file mode 100644 index 0000000000000..9e90842ab7fda --- /dev/null +++ b/apps/server/src/workflows/triggers.ts @@ -0,0 +1,156 @@ +// What starts a run by itself. A trigger hands its workflow one value, so a workflow that lists +// a trigger takes that value as its payload: `Tick` for a schedule, `WebhookRequest` for a hook. +import * as Duration from "effect/Duration"; +import * as Schema from "effect/Schema"; + +import { parseTimeOfDay } from "../scheduledTasks/Schedule.ts"; +import { checkOptions, durationOf } from "./options.ts"; +import type { Issue, PullRequest } from "./WorkflowForge.ts"; + +/** The time a scheduled run was due, which is not the time it started. */ +export const Tick = Schema.Struct({ scheduledAt: Schema.String }); +export type Tick = typeof Tick.Type; + +/** A request to a workflow's hook URL, as it arrived. Header names are lower case. */ +export const WebhookRequest = Schema.Struct({ + method: Schema.String, + headers: Schema.Record(Schema.String, Schema.String), + query: Schema.String, + body: Schema.String, +}); +export type WebhookRequest = typeof WebhookRequest.Type; + +export interface ScheduleTrigger { + readonly kind: "schedule"; + /** Stable across restarts: where this trigger's next time is kept. */ + readonly id: string; + readonly schedule: + | { readonly type: "interval"; readonly everyMs: number } + | { + readonly type: "fixed_time"; + readonly timeOfDay: string; + readonly weekdays?: ReadonlyArray; + }; +} +export interface WebhookTrigger { + readonly kind: "webhook"; + readonly name: string; + readonly key: ((request: WebhookRequest) => string | undefined) | undefined; +} +/** New issues or pull requests of a project, which the engine looks for by itself. */ +export interface OpenedTrigger { + readonly kind: "issues" | "pullRequests"; + /** Stable across restarts: where this trigger keeps how far it has looked. */ + readonly id: string; + readonly project: string; + readonly labels?: ReadonlyArray | undefined; + readonly query?: string | undefined; +} +/** `Fires` is what the trigger gives the run it starts. */ +export type Trigger = (ScheduleTrigger | WebhookTrigger | OpenedTrigger) & { + readonly fires?: (value: Fires) => void; +}; + +/** A run every so often, counted from when the last one was started. At least a minute. */ +export const every = (interval: Duration.Input): Trigger => { + const everyMs = Duration.toMillis(durationOf(`every(${JSON.stringify(interval)})`, interval)); + // The sweep would quietly stretch a shorter one to a minute. + if (everyMs < 60_000) { + throw new Error(`every(${JSON.stringify(interval)}) is shorter than the shortest, one minute.`); + } + return { kind: "schedule", id: `every:${everyMs}`, schedule: { type: "interval", everyMs } }; +}; + +/** + * A run at a time of day (`"09:00"`) on the server's clock, on every day or on the given weekdays + * (0 is Sunday). A time missed by more than ten minutes, for a server that was down, is skipped. + */ +export const daily = ( + timeOfDay: string, + options?: { readonly weekdays?: ReadonlyArray }, +): Trigger => { + checkOptions(`daily("${timeOfDay}")`, options, ["weekdays"]); + const weekdays = options?.weekdays; + // Read once here: a time the schedule cannot read would otherwise never fire, without a word. + if (parseTimeOfDay(timeOfDay) === null) { + throw new Error(`daily("${timeOfDay}") needs a 24-hour time such as "09:00".`); + } + if (weekdays?.some((day) => !Number.isInteger(day) || day < 0 || day > 6)) { + throw new Error(`daily's weekdays are 0 (Sunday) to 6 (Saturday), not ${weekdays.join(", ")}.`); + } + return { + kind: "schedule", + id: `daily:${timeOfDay}:${weekdays?.toSorted().join(",") ?? "all"}`, + schedule: { type: "fixed_time", timeOfDay, ...(weekdays === undefined ? {} : { weekdays }) }, + }; +}; + +/** + * A run for each request to this workflow's hook URL (`t3 workflow hooks` prints it). The run + * decides what the request means, `stop` included. Two requests for which `key` gives the same + * text are one run, which is how a sender's retries are told from new deliveries. + */ +export const webhook = ( + name: string, + options?: { readonly key?: (request: WebhookRequest) => string | undefined }, +): Trigger => { + checkOptions(`webhook("${name}")`, options, ["key"]); + return { kind: "webhook", name, key: options?.key }; +}; + +/** Refuses two hooks of one name, or two triggers that would fire on the same thing. */ +export const checkTriggers = ( + workflow: string, + triggers: ReadonlyArray, +) => { + const seen = new Set(); + for (const trigger of triggers) { + const id = trigger.kind === "webhook" ? `webhook:${trigger.name}` : trigger.id; + if (seen.has(id)) { + throw new Error( + trigger.kind === "webhook" + ? `workflow("${workflow}") has two hooks named "${trigger.name}". Give each its own name.` + : `workflow("${workflow}") lists the same ${trigger.kind === "schedule" ? "schedule" : "trigger"} twice. List it once.`, + ); + } + seen.add(id); + } +}; + +const openedId = ( + kind: OpenedTrigger["kind"], + options: { + readonly project: string; + readonly labels?: ReadonlyArray; + readonly query?: string; + }, +) => + // A tuple, so no label or query can be read as part of another. + JSON.stringify([kind, options.project, options.labels?.toSorted() ?? [], options.query ?? ""]); + +/** + * A run for each issue opened in the project's tracker from now on, with the issue as its + * payload (`Issue`). Issues that were already there when the workflow was first loaded start + * nothing. `labels` are ones the issue must carry, all of them; `query` is free text for the + * tracker. The tracker is asked about once a minute. + */ +export const issuesOpened = (options: { + readonly project: string; + readonly labels?: ReadonlyArray; + readonly query?: string; +}): Trigger => { + checkOptions("issues.opened", options, ["project", "labels", "query"]); + return { kind: "issues", id: openedId("issues", options), ...options }; +}; + +/** + * A run for each pull request opened against the project's repository from now on, with the pull + * request as its payload (`PullRequest`). `query` is free text for the host. + */ +export const pullRequestsOpened = (options: { + readonly project: string; + readonly query?: string; +}): Trigger => { + checkOptions("pullRequests.opened", options, ["project", "query"]); + return { kind: "pullRequests", id: openedId("pullRequests", options), ...options }; +}; diff --git a/apps/server/src/workflows/workflow.ts b/apps/server/src/workflows/workflow.ts new file mode 100644 index 0000000000000..3359307875999 --- /dev/null +++ b/apps/server/src/workflows/workflow.ts @@ -0,0 +1,897 @@ +// The author-facing primitives. A workflow body is replayed after a restart, so anything that +// touches the world goes through `step`; these are all a body may use. +import * as Cause from "effect/Cause"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Result from "effect/Result"; +import * as Schedule from "effect/Schedule"; +import * as Schema from "effect/Schema"; +import * as SchemaAST from "effect/SchemaAST"; +import * as SqlClient from "effect/sql/SqlClient"; +import { Activity, DurableClock, DurableDeferred, Workflow, WorkflowEngine } from "effect/workflow"; + +import { checkOptions, durationOf } from "./options.ts"; +import { + EngineLink, + forStep, + type InFlight, + type InStep, + KeyValues, + Runs, +} from "./stepServices.ts"; +import { + checkTriggers, + type OpenedTrigger, + type ScheduleTrigger, + type Trigger, + type WebhookTrigger, +} from "./triggers.ts"; +import type { WorkflowAgents } from "./WorkflowAgents.ts"; +import { unavailable, WorkflowForge } from "./WorkflowForge.ts"; +import * as WorkflowStore from "./WorkflowStore.ts"; + +/** A step that could not be completed. Its run is paused until someone resumes it. */ +export class StepFailed extends Schema.TaggedError()("StepFailed", { + step: Schema.String, + reason: Schema.String, +}) { + override get message(): string { + return `${this.step}: ${this.reason}`; + } +} + +/** The workflow's own decision to end without a result. */ +export class WorkflowStop extends Schema.TaggedError()("WorkflowStop", { + reason: Schema.String, + /** The run was never for this workflow to do, which lists leave out. */ + skipped: Schema.optional(Schema.Boolean), +}) { + override get message(): string { + return this.reason; + } +} + +/** What the primitives need from the run they are called in. */ +export class RunContext extends Context.Service< + RunContext, + { + readonly runId: string; + readonly workflow: string; + readonly store: WorkflowStore.WorkflowStore["Service"]; + /** Names used so far in this pass over the body: two steps with one name would share a result. */ + readonly names: Set; + /** What the code of the step `name` may use. */ + readonly forStep: (name: string) => Context.Context; + /** The steps running now, which a cancelled run's cleanup waits for. */ + readonly inFlight: InFlight; + } +>()("t3/workflows/workflow/RunContext") {} + +/** What a workflow body may require: the run it is in, the engine, and somewhere to run agents. */ +export type InRun = + | RunContext + | WorkflowAgents + | WorkflowEngine.WorkflowEngine + | WorkflowEngine.WorkflowInstance; + +/** Takes `name` for one step of the run. Step results and the step list are both kept by name. */ +export const claim = (name: string, cleanup = false) => + Effect.flatMap(RunContext, (run) => { + // The cleanup step's name is its own, or a body step would take it and cleanup never run. + if (name === END_STEP && !cleanup) { + return Effect.die( + new Error( + `"${END_STEP}" is the name of workflow ${run.workflow}'s cleanup step. Name this step something else.`, + ), + ); + } + if (run.names.has(name)) { + return Effect.die( + new Error( + `Two steps in workflow ${run.workflow} are named "${name}". Names are unique in a run.`, + ), + ); + } + run.names.add(name); + return Effect.succeed(run); + }); + +/** An error as one line for a person, with what caused it when the error only wraps something. */ +export const text = (error: unknown): string => { + if (typeof error === "string") return error.slice(0, 2000); + if (typeof error !== "object" || error === null) return String(error); + // Also an error that came back from the journal, which is its fields and no longer an Error. + const fields = error as { + readonly message?: unknown; + readonly reason?: unknown; + cause?: unknown; + }; + const message = + typeof fields.message === "string" && fields.message !== "" + ? fields.message + : typeof fields.reason === "string" + ? fields.reason + : "Unknown error"; + return (fields.cause === undefined ? message : `${message}: ${text(fields.cause)}`).slice( + 0, + 2000, + ); +}; + +// What a workflow without `returns` returns: any JSON value, or nothing. +const ANY_JSON = Schema.UndefinedOr(Schema.Json); + +/** Where in `value` JSON cannot hold what it finds, with `undefined` counted only when `strict`. */ +const notJson = (value: unknown, at: string, strict: boolean): string | undefined => { + if (value === null || typeof value === "string" || typeof value === "boolean") return undefined; + if (typeof value === "number") return Number.isFinite(value) ? undefined : `${at} is ${value}`; + if (value === undefined) return strict ? `${at} is undefined` : undefined; + if (Array.isArray(value)) { + for (const [index, item] of value.entries()) { + const found = notJson(item, `${at}[${index}]`, strict); + if (found !== undefined) return found; + } + return undefined; + } + const proto = typeof value === "object" ? Object.getPrototypeOf(value) : undefined; + if (proto !== Object.prototype && proto !== null) { + return `${at} is ${typeof value === "object" ? (proto?.constructor?.name ?? "an object") : `a ${typeof value}`}`; + } + for (const [key, field] of Object.entries(value as object)) { + const found = notJson(field, `${at}.${key}`, strict); + if (found !== undefined) return found; + } + return undefined; +}; + +/** A value that did not encode, said with where JSON could not hold it, which `Schema.Json` omits. */ +const encodeFailure = (what: string, error: unknown, value: unknown) => { + const where = notJson(value, what, true); + return where === undefined ? text(error) : `${text(error)}: ${where}`; +}; + +/** A step result the journal cannot store, which fails the step it came from. */ +const unstorable = (error: unknown, value: unknown) => + Effect.die(new Error(encodeFailure("the result", error, value))); + +/** What a run without `returns` returns, read as `JSON.stringify` reads it. */ +const untypedResult = (value: unknown): Effect.Effect => { + const where = notJson(value, "the run's result", false); + if (where !== undefined) return Effect.die(new Error(`The run's result is not JSON: ${where}.`)); + return Effect.succeed( + value === undefined ? null : (JSON.parse(JSON.stringify(value)) as Schema.Json), + ); +}; + +/** + * One journaled action of the step `name`: it happens once, and a replay returns what it stored. + * A failure marks the step failed and pauses the run here; resuming the run executes it again. + */ +export const journaled = ( + run: RunContext["Service"], + name: string, + action: string, + returns: Schema.Codec, + execute: Effect.Effect, + // The run waits for a person after this fails, not for `resumeAfter`. + held = false, +) => { + const codec = Schema.toCodecJson(returns); + const encodable = Schema.encodeEffect(codec); + return Activity.make({ + name: action, + success: returns, + error: StepFailed, + execute: run.inFlight.track(run.runId, execute).pipe( + // A result the journal cannot store is this step's failure, found before it is journaled. + Effect.tap((value) => Effect.catch(encodable(value), (error) => unstorable(error, value))), + // The engine reads its own 64-bit ids as BigInt. What a step calls must not inherit that. + Effect.provideService(SqlClient.SafeIntegers, false), + // Also a step that dies: left as a defect the engine would park the run without a word. + Effect.catchCause((cause) => + Cause.hasInterruptsOnly(cause) + ? Effect.failCause(cause as Cause.Cause) + : Effect.fail(new StepFailed({ step: name, reason: text(Cause.squash(cause)) })), + ), + Effect.tapError((error) => + Effect.andThen( + run.store.stepEnded(run.runId, name, "failed", error.reason), + run.store.runPaused(run.runId, error.message, held), + ), + ), + ), + }); +}; + +/** How an invoked run ended, as its parent's wait receives it. */ +export const ChildEnd = Schema.Struct({ + outcome: Schema.Literals(["completed", "stopped", "skipped", "cancelled"]), + value: Schema.Json, + reason: Schema.optional(Schema.String), +}); + +export interface StepRetry { + /** How many more times to try before the run is paused. */ + readonly times: number; + readonly schedule?: Schedule.Schedule; +} +// Once, unless asked: a step that posts or merges must not do it again after a lost reply. +const DEFAULT_RETRY: StepRetry = { times: 0 }; + +const checkStepOptions = (what: string, options: { readonly retry?: StepRetry | undefined }) => { + checkOptions(what, options, ["returns", "retry"]); + checkOptions(`${what}'s retry`, options?.retry, ["times", "schedule"]); +}; + +/** How `step.try` ended: its value, or why it failed once its retries were used up. */ +export type StepAttempt = + | { readonly outcome: "done"; readonly value: A } + | { readonly outcome: "failed"; readonly reason: string }; + +const attemptOf = (returns: Schema.Codec) => + Schema.Union([ + Schema.Struct({ outcome: Schema.Literal("done"), value: returns }), + Schema.Struct({ outcome: Schema.Literal("failed"), reason: Schema.String }), + ]); + +/** + * Do something once per run. The result is stored, and a replay returns the stored result. + * + * A failure is retried by `retry`, then pauses the run at this step: resuming the run runs the step + * again. Nothing in the body can catch that. For a failure the workflow decides about, use + * `step.try`. + */ +export const step = Object.assign( + ( + name: string, + options: { readonly returns: Schema.Codec; readonly retry?: StepRetry }, + code: Effect.Effect, + ): Effect.Effect => { + checkStepOptions(`step("${name}")`, options); + return Effect.orDie(stepAs(claim(name), name, options, code)); + }, + { + /** As `step`, but a failure left after the retries comes back as `failed` with the reason. */ + try: ( + name: string, + options: { readonly returns: Schema.Codec; readonly retry?: StepRetry }, + code: Effect.Effect, + ): Effect.Effect, never, InRun> => { + checkStepOptions(`step.try("${name}")`, options); + return Effect.orDie( + stepAs( + claim(name), + name, + { returns: attemptOf(options.returns), retry: options.retry }, + code, + (tried) => + tried.pipe( + Effect.map((value): StepAttempt => ({ outcome: "done", value })), + Effect.catchCause((cause) => + Cause.hasInterruptsOnly(cause) + ? Effect.failCause(cause as Cause.Cause) + : Effect.succeed>({ + outcome: "failed", + reason: text(Cause.squash(cause)), + }), + ), + ), + ), + ); + }, + }, +); + +const stepAs = ( + claimed: Effect.Effect, + name: string, + options: { readonly returns: Schema.Codec; readonly retry?: StepRetry | undefined }, + code: Effect.Effect, + // What the step makes of its tries: by default their value, or their failure. + settle: (tried: Effect.Effect) => Effect.Effect = (tried) => + tried as unknown as Effect.Effect, +): Effect.Effect => + Effect.flatMap(claimed, (run) => { + const retry = options.retry ?? DEFAULT_RETRY; + const resultCodec = Schema.toCodecJson(options.returns); + const encodeResult = Schema.encodeEffect(resultCodec); + // Made per try, so a retry numbers its signals from the start again and counts as an attempt. + const execute = Effect.andThen( + run.store.stepStarted(run.runId, name, "step"), + Effect.suspend(() => Effect.provideContext(code, run.forStep(name))), + ); + return journaled( + run, + name, + `step/${name}`, + options.returns, + settle( + retry.times === 0 + ? execute + : Effect.retry(execute, { + times: retry.times, + ...(retry.schedule === undefined ? {} : { schedule: retry.schedule }), + }), + ).pipe( + // A value that does not encode fails the step, so it is never marked done first. + Effect.tap((value) => + Effect.flatMap( + Effect.catch(encodeResult(value), (error) => unstorable(error, value)), + (json) => + Effect.andThen( + run.store.stepEnded(run.runId, name, "completed", null), + // For a person reading the run. + Effect.ignore(run.store.stepResult(run.runId, name, json as Schema.Json)), + ), + ), + ), + ), + ); + }); + +/** A sleep that survives a restart. */ +export const sleep = Effect.fn("workflow.sleep")(function* ( + name: string, + duration: Duration.Input, +): Effect.fn.Return { + const length = durationOf(`sleep("${name}")`, duration); + const run = yield* claim(name); + // Listed like any step, with when it wakes, so a run that sleeps for days says so. + yield* Activity.make({ + name: `sleep/${name}/open`, + execute: Effect.gen(function* () { + const wakes = DateTime.addDuration(yield* DateTime.now, length); + yield* run.store.stepStarted(run.runId, name, "sleep"); + yield* run.store.stepDetail(run.runId, name, DateTime.formatIso(wakes)); + yield* run.store.runStatus(run.runId, "waiting", `sleep ${name}`); + }), + }); + // Effect keeps a short sleep in memory, where a restart would start it over. + yield* DurableClock.sleep({ + name: `sleep/${name}`, + duration: length, + inMemoryThreshold: Duration.zero, + }); + yield* Activity.make({ + name: `sleep/${name}/close`, + execute: Effect.andThen( + run.store.stepEnded(run.runId, name, "completed", null), + run.store.runResumed(run.runId), + ), + }); +}); + +export const Woke = Schema.Struct({ expired: Schema.Boolean, value: Schema.Json }); +export const wakeOf = (name: string) => DurableDeferred.make(`wait/${name}`, { success: Woke }); +const finite = [Schema.isFinite()] as const; +// JSON carries a bare `Schema.Number` as a number or the text "Infinity", "-Infinity" or "NaN", +// and that form drops the number's own checks. Whoever writes the value is told a finite number +// with its checks instead. Transformations and recursion keep their own form. +const finiteNumbers = (ast: SchemaAST.AST): SchemaAST.AST => { + if (ast.encoding !== undefined) return ast; + if (SchemaAST.isNumber(ast)) { + return new SchemaAST.Number( + ast.annotations, + ast.checks === undefined ? finite : [...ast.checks, ...finite], + undefined, + ast.context, + ); + } + if (SchemaAST.isObjects(ast)) { + return new SchemaAST.Objects( + ast.propertySignatures.map( + (field) => new SchemaAST.PropertySignature(field.name, finiteNumbers(field.type)), + ), + ast.indexSignatures.map( + (index) => new SchemaAST.IndexSignature(index.parameter, finiteNumbers(index.type)), + ), + ast.annotations, + ast.checks, + undefined, + ast.context, + ast.encodingChecks, + ); + } + if (SchemaAST.isArrays(ast)) { + return new SchemaAST.Arrays( + ast.isMutable, + ast.elements.map(finiteNumbers), + ast.rest.map(finiteNumbers), + ast.annotations, + ast.checks, + undefined, + ast.context, + ast.encodingChecks, + ); + } + if (SchemaAST.isUnion(ast)) { + return new SchemaAST.Union( + ast.types.map(finiteNumbers), + ast.options, + ast.annotations, + ast.checks, + undefined, + ast.context, + ast.encodingChecks, + ); + } + return ast; +}; + +/** What a value must look like, as JSON Schema; `closed` objects turn down keys they do not name. */ +export const jsonSchemaOf = (schema: Schema.Top, closed = false): Record => { + const document = Schema.toJsonSchemaDocument( + Schema.make(finiteNumbers(schema.ast)), + closed ? { onExcessProperty: "error" } : undefined, + ); + return { ...document.schema, $defs: document.definitions } as Record; +}; + +/** `wait`, also as the question a person answers: `request` is what an inbox shows them. */ +export const waitAs = Effect.fn("workflow.wait")(function* ( + kind: "wait" | "ask", + name: string, + options: WaitOptions, +): Effect.fn.Return, StepFailed, InRun> { + return yield* waitClaimed(yield* claim(name), kind, name, options); +}); + +interface WaitOptions { + readonly returns: Schema.Codec; + readonly timeout?: Duration.Input | undefined; + readonly channel?: string | undefined; + readonly request?: Schema.Json | undefined; + /** What the engine looks at to end the wait by itself. */ + readonly watch?: Schema.Json | undefined; +} + +const sameAddress = (left: WorkflowStore.SignalAddress, right: WorkflowStore.SignalAddress) => + "runId" in left + ? "runId" in right && left.runId === right.runId && left.wait === right.wait + : "channel" in right && left.workflow === right.workflow && left.channel === right.channel; + +const waitClaimed = Effect.fnUntraced(function* ( + run: RunContext["Service"], + kind: "wait" | "ask", + name: string, + options: WaitOptions, +): Effect.fn.Return, StepFailed, InRun> { + const here: WorkflowStore.SignalAddress = { runId: run.runId, wait: name }; + const schema = jsonSchemaOf(options.returns); + const codec = Schema.toCodecJson(options.returns); + const decode = Schema.decodeEffect(codec); + const fits = (value: Schema.Json) => Effect.result(decode(value)); + const addresses: ReadonlyArray = + options.channel === undefined + ? [here] + : [here, { workflow: run.workflow, channel: options.channel }]; + // Whatever arrived early is delivered now, checked as this wait reads it. The mail goes only + // after the wake: waking twice is harmless, and losing the signal is not. + const deliverEarly = Effect.fnUntraced(function* ( + wake: ReturnType, + token: DurableDeferred.Token, + ) { + const passed = new Set(); + while (true) { + const early = yield* run.store.mailNext(addresses, passed); + if (early === undefined) return; + const value = WorkflowStore.jsonValue(early.valueJson); + if (Result.isFailure(yield* fits(value))) { + // Kept when it went to a channel: another run, or another version, may read it. + if (sameAddress(early.address, here)) yield* run.store.mailDelete(early.signalId); + passed.add(early.signalId); + continue; + } + const woke = { expired: false, value }; + const outcome = yield* run.store.mailDeliver(early.signalId, run.runId, name, woke); + // Another wait on the same key took that one; there may be a next. + if (outcome === "gone") continue; + // Another signal claimed this wait first: its wake, or the sweep, carries what it claimed. + if (outcome === "claimed") return; + yield* DurableDeferred.succeed(wake, { token, value: woke }); + return; + } + }); + const first = wakeOf(name); + const firstToken = yield* DurableDeferred.token(first); + yield* Activity.make({ + name: `wait/${name}/open`, + execute: Effect.gen(function* () { + const deadline = + options.timeout === undefined + ? null + : DateTime.formatIso( + DateTime.addDuration(yield* DateTime.now, Duration.fromInputUnsafe(options.timeout)), + ); + yield* run.store.stepStarted(run.runId, name, kind); + yield* run.store.waitOpened({ + runId: run.runId, + name, + workflow: run.workflow, + key: options.channel, + token: firstToken, + schemaJson: WorkflowStore.jsonText(schema), + requestJson: options.request === undefined ? null : WorkflowStore.jsonText(options.request), + watchJson: options.watch === undefined ? null : WorkflowStore.jsonText(options.watch), + deadline, + }); + yield* run.store.runStatus(run.runId, "waiting", name); + yield* deliverEarly(first, firstToken); + }), + }); + // A value that fit the wait's JSON Schema can still fail its codec. It was not for this wait, + // so the wait opens again under a fresh wake instead of breaking the run on every replay. + let wake = first; + for (let again = 1; ; again++) { + const woke = yield* DurableDeferred.await(wake); + const value = woke.expired ? undefined : yield* fits(woke.value); + if (value !== undefined && Result.isFailure(value)) { + const problem = `It was signalled with a value it cannot read, and waits again: ${text(value.failure)}`; + wake = wakeOf(`${name}/again/${again}`); + const token = yield* DurableDeferred.token(wake); + const next = wake; + yield* Activity.make({ + name: `wait/${name}/again/${again}`, + execute: Effect.gen(function* () { + yield* run.store.waitReopened(run.runId, name, token); + yield* run.store.stepDetail(run.runId, name, problem.slice(0, 2000)); + yield* deliverEarly(next, token); + }), + }); + continue; + } + yield* Activity.make({ + name: `wait/${name}/close`, + execute: Effect.gen(function* () { + yield* run.store.waitClosed(run.runId, name); + yield* run.store.stepEnded(run.runId, name, "completed", woke.expired ? "timed out" : null); + if (!woke.expired) yield* run.store.stepResult(run.runId, name, woke.value); + yield* run.store.runResumed(run.runId); + }), + }); + return value === undefined ? Option.none() : Option.some(value.success); + } +}); + +/** + * Sleep until something outside signals this wait; `None` when the timeout passes first. + * Addressed by run and wait name, or by `channel` (scoped to the workflow's name) when the sender + * cannot know the run. A signal sent before the wait opened is delivered when it opens. + */ +export const wait = ( + name: string, + options: { + readonly returns: Schema.Codec; + readonly timeout?: Duration.Input; + readonly channel?: string; + }, +): Effect.Effect, never, InRun> => { + checkOptions(`wait("${name}")`, options, ["returns", "timeout", "channel"]); + return Effect.orDie(waitAs("wait", name, options)); +}; + +/** End the run by the workflow's own decision. It ends as `stopped`, which is not a failure. */ +export const stop = (reason: string): Effect.Effect => + Effect.fail(new WorkflowStop({ reason })); + +/** + * End the run because it was not this workflow's to do: a webhook delivery it ignores, a pull + * request it opened itself. It ends as `skipped`, which lists leave out unless asked. Use `stop` + * for a run that did something and then decided to end. + */ +export const skip = (reason: string): Effect.Effect => + Effect.fail(new WorkflowStop({ reason, skipped: true })); + +/** Name the run in lists. Defaults to the workflow's name and the run's key. */ +export const title = ( + value: string, + ...rest: ReadonlyArray +): Effect.Effect => { + // Files are not type-checked, so `title("name", text)` would title the run "name". + if (typeof value !== "string" || rest.length > 0) { + throw new Error("title takes only the text, as in title(`Release ${name}`), and no step name."); + } + return Effect.flatMap(RunContext, (current) => { + // Numbered by how many came before in the body, which a replay walks the same way. + let n = 0; + while (current.names.has(`title/${n}`)) n++; + const name = `title/${n}`; + return Effect.flatMap(claim(name), (run) => + Activity.make({ name, execute: run.store.runTitle(run.runId, value) }), + ); + }).pipe(Effect.orDie); +}; + +// The defaults are every workflow: a registry holds workflows of every payload and result type. +export interface WorkflowDefinition

    { + /** Types only: what a run is started with and what it returns, for `start` and `invoke`. */ + readonly "~types"?: { readonly payload: (payload: P) => void; readonly returns: A }; + readonly name: string; + readonly version: number; + readonly payload: Schema.Codec; + readonly returns: Schema.Codec; + /** How long a paused run rests before it is resumed by itself, per pause in a row. */ + readonly resumeAfter: ReadonlyArray; + readonly triggers: ReadonlyArray; + /** Fails with the reason as text: by here nothing reads the error but a person. */ + readonly onEnd: + | ((payload: never, end: RunEnd) => Effect.Effect) + | undefined; + // The registry holds workflows of every payload type; `workflow` is where the types are checked. + readonly body: ( + payload: never, + run: { readonly id: string }, + ) => Effect.Effect; +} + +/** How a run ended, as its `onEnd` is told. A paused run has not ended. */ +export interface RunEnd { + readonly id: string; + readonly outcome: "completed" | "stopped" | "skipped" | "cancelled"; + readonly reason: string | undefined; +} + +/** + * Run another workflow as part of this one and wait for how it ends. The other run is a run of + * its own, listed and resumable by itself; cancelling this run cancels it. A run that paused has + * not ended, so this waits on while someone resumes it. + */ +export const invoke = ( + name: string, + workflow: WorkflowDefinition, + payload: P, + options?: { readonly key?: string }, +): Effect.Effect< + | { readonly outcome: "completed"; readonly value: A } + | { readonly outcome: "stopped" | "skipped" | "cancelled"; readonly reason: string }, + never, + InRun +> => { + // Files are not type-checked, and a name would start nothing until its first step failed. + if (typeof workflow !== "object" || workflow === null || typeof workflow.name !== "string") { + return Effect.die( + new Error( + `invoke takes the workflow definition, not its name: invoke("${name}", …) was given ${JSON.stringify(workflow)}. Pass what workflow(…) returned.`, + ), + ); + } + checkOptions(`invoke("${name}")`, options, ["key"]); + return Effect.orDie(invokeAs(name, workflow, payload, options)); +}; + +const invokeAs = Effect.fn("workflow.invoke")(function* ( + name: string, + workflow: WorkflowDefinition, + payload: P, + options?: { readonly key?: string }, +): Effect.fn.Return< + | { readonly outcome: "completed"; readonly value: A } + | { readonly outcome: "stopped" | "skipped" | "cancelled"; readonly reason: string }, + StepFailed, + InRun +> { + // Taken before the child starts: a name already used would refuse the wait after the start. + const run = yield* claim(name); + yield* step( + `${name}/start`, + { returns: Schema.String }, + Effect.flatMap(Runs, (runs) => + runs.start(workflow.name, payload, { + version: workflow.version, + idempotencyKey: options?.key ?? `${run.runId}/${name}`, + parent: { runId: run.runId, wait: name }, + }), + ).pipe(Effect.map((started) => started.runId)), + ); + const ended = yield* waitClaimed(run, "wait", name, { returns: ChildEnd }); + if (Option.isNone(ended)) { + return yield* new StepFailed({ step: name, reason: "the wait ended without an outcome" }); + } + if (ended.value.outcome !== "completed") { + return { outcome: ended.value.outcome, reason: ended.value.reason ?? "" }; + } + const returnsCodec = Schema.toCodecJson(workflow.returns); + const decode = Schema.decodeEffect(returnsCodec); + const value = yield* decode(ended.value.value).pipe( + Effect.mapError((error) => new StepFailed({ step: name, reason: text(error) })), + ); + return { outcome: "completed", value: value as A }; +}); + +/** The step `onEnd` runs as. */ +export const END_STEP = "onEnd"; +const END_RETRY: StepRetry = { times: 3, schedule: Schedule.exponential("2 seconds") }; + +const DEFAULT_RESUME_AFTER: ReadonlyArray = [ + "5 minutes", + "20 minutes", + "80 minutes", +]; + +/** + * A workflow: a name, a version, and a body. + * + * A run keeps the version it started with. To change the order of steps or the shape of a stored + * result, register the new body under a higher version and keep the old one registered until its + * runs have ended. + */ +export const workflow = ( + name: string, + options: { + readonly version: number; + readonly payload: Schema.Codec; + readonly returns?: Schema.Codec; + readonly resumeAfter?: ReadonlyArray; + /** What starts a run by itself. Each must give what `payload` takes. */ + readonly triggers?: ReadonlyArray>; + /** + * Runs once when the run ends, however it ends, to give back what the run took: a machine, a + * lock. It gets the payload and the run's id, not the body's values, so name what the run + * takes after its id. It must be safe to run for a run that took nothing. + */ + readonly onEnd?: (payload: P, end: RunEnd) => Effect.Effect; + }, + body: ( + payload: P, + run: { readonly id: string }, + ) => Effect.Effect, +): WorkflowDefinition => { + checkOptions(`workflow("${name}")`, options, [ + "version", + "payload", + "returns", + "resumeAfter", + "triggers", + "onEnd", + ]); + // Read once now, so a duration that does not parse fails the file and not a paused run later. + for (const rest of options.resumeAfter ?? []) + durationOf(`workflow("${name}")'s resumeAfter`, rest); + checkTriggers(name, options.triggers ?? []); + return definitionOf(name, options, body); +}; + +const definitionOf = ( + name: string, + options: Parameters>[1], + body: Parameters>[2], +): WorkflowDefinition => ({ + name, + version: options.version, + // Erased here, once: the registry holds workflows of every payload and result type. + payload: options.payload as Schema.Codec, + // Without a schema the result is whatever JSON the body returned: dropping it would be a + // surprise, and a value that is not JSON pauses the run with the reason. + returns: (options.returns ?? ANY_JSON) as Schema.Codec, + resumeAfter: options.resumeAfter ?? DEFAULT_RESUME_AFTER, + triggers: options.triggers ?? [], + onEnd: + options.onEnd === undefined + ? undefined + : (payload, end) => options.onEnd!(payload, end).pipe(Effect.asVoid, Effect.mapError(text)), + body, +}); + +export const engineTag = (definition: Pick) => + `${definition.name}@${definition.version}`; + +const Outcome = Schema.Struct({ + outcome: Schema.Literals(["completed", "stopped", "skipped"]), + value: Schema.Json, + reason: Schema.optional(Schema.String), +}); + +export const engineWorkflow = (definition: WorkflowDefinition) => + Workflow.make(engineTag(definition), { + payload: { idempotencyKey: Schema.String, input: Schema.Json }, + idempotencyKey: (payload) => payload.idempotencyKey, + success: Outcome, + error: Schema.Union([StepFailed, WorkflowStop]), + // A failure parks the run instead of ending it; only an explicit resume wakes it. + }).annotate(Workflow.SuspendOnFailure, true); +export type EngineWorkflow = ReturnType; + +export const layerDefinition = (definition: WorkflowDefinition, engine: EngineWorkflow) => { + const payloadCodec = Schema.toCodecJson(definition.payload); + const decodePayload = Schema.decodeEffect(payloadCodec); + const returnsCodec = Schema.toCodecJson(definition.returns); + const encodeResult = Schema.encodeUnknownEffect(returnsCodec); + return engine.toLayer((payload, runId) => + Effect.gen(function* () { + const store = yield* WorkflowStore.WorkflowStore; + const keyValues = yield* KeyValues; + const link = yield* EngineLink; + const forge = Option.getOrElse(yield* Effect.serviceOption(WorkflowForge), () => unavailable); + yield* Activity.make({ + name: "run/begin", + execute: store.runStarted({ + runId, + workflow: definition.name, + version: definition.version, + engineTag: engineTag(definition), + idempotencyKey: payload.idempotencyKey, + input: payload.input, + }), + }); + const input = (yield* Effect.orDie(decodePayload(payload.input))) as never; + const outcome = yield* definition.body(input, { id: runId }).pipe( + Effect.flatMap((value) => + definition.returns === ANY_JSON + ? untypedResult(value) + : encodeResult(value).pipe( + Effect.mapError( + (error) => + new Error( + `The run's result does not fit its returns: ${encodeFailure("the run's result", error, value)}`, + ), + ), + Effect.orDie, + ), + ), + Effect.map((value): typeof Outcome.Type => ({ + outcome: "completed", + value: (value ?? null) as Schema.Json, + })), + Effect.catchTags({ + WorkflowStop: (stopped) => + Effect.succeed({ + outcome: stopped.skipped === true ? "skipped" : "stopped", + value: null, + reason: stopped.reason, + }), + }), + // A step like any other: a cleanup that fails pauses the run, and resuming tries it again. + Effect.tap((ended) => + definition.onEnd === undefined + ? Effect.void + : stepAs( + claim(END_STEP, true), + END_STEP, + // A cleanup is safe to run again, and has nobody else to try it. + { returns: Schema.Void, retry: END_RETRY }, + definition.onEnd(input, { + id: runId, + outcome: ended.outcome, + reason: ended.reason, + }), + ), + ), + Effect.provideService( + RunContext, + RunContext.of({ + runId, + workflow: definition.name, + store, + names: new Set(), + forStep: (name) => forStep(store, keyValues, link, forge, runId, name), + inFlight: link.inFlight, + }), + ), + ); + yield* Activity.make({ + name: "run/end", + execute: Effect.asVoid( + store.runEnded(runId, outcome.outcome, outcome.reason ?? null, outcome.value), + ), + }); + yield* Activity.make({ + name: "run/told", + execute: Effect.suspend(() => link.current?.ended(runId) ?? Effect.void), + }); + return outcome; + }).pipe( + // A failing step marked the run paused itself. What reaches here otherwise is the body + // breaking outside a step: a duplicate name, a payload that no longer decodes. + Effect.tapCause((cause) => + Cause.hasInterruptsOnly(cause) + ? Effect.void + : Effect.flatMap(WorkflowStore.WorkflowStore, (store) => + store.runPaused(runId, text(Cause.squash(cause))), + ), + ), + ), + ); +}; diff --git a/apps/server/src/workflows/workflowAgent.ts b/apps/server/src/workflows/workflowAgent.ts new file mode 100644 index 0000000000000..03956086b03c8 --- /dev/null +++ b/apps/server/src/workflows/workflowAgent.ts @@ -0,0 +1,442 @@ +// The steps that involve someone else: an agent that returns data, and a person who answers. +import * as Clock from "effect/Clock"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import { identity } from "effect/Function"; +import * as Option from "effect/Option"; +import * as Result from "effect/Result"; +import * as Schema from "effect/Schema"; + +import { checkOptions } from "./options.ts"; +import { stepReferences } from "./runReferences.ts"; +import { + claim, + type InRun, + journaled, + jsonSchemaOf, + type StepFailed, + text, + waitAs, +} from "./workflow.ts"; +import type { IssueAddress } from "./WorkflowForge.ts"; +import { + type AgentLaunch, + type AgentModel, + AgentResult, + AgentTurn, + WorkflowAgents, +} from "./WorkflowAgents.ts"; + +/** A thread an agent step ran in, to hand to a later step that should continue it. */ +export interface AgentThread { + readonly threadId: string; + /** The linked environment it is in. Absent for this one. */ + readonly environment?: string | undefined; +} + +const CORRECTIONS = 2; + +export interface AgentOptions extends AgentLaunch { + readonly brief: string; + /** The new thread's title. `: ` by default. */ + readonly title?: string; + readonly returns?: Schema.Codec; + readonly model?: AgentModel; + readonly project?: string; + readonly environment?: string; + readonly thread?: AgentThread; + /** + * The issue this job is about. Its thread shows the issue, and the issue's page lists the + * thread. Only for a thread on this server, not one in a linked `environment`. + */ + readonly issue?: IssueAddress; + /** How long the agent has. Past it the thread is stopped and the step has failed. */ + readonly timeout?: Duration.Input; + /** + * Let the agent end a turn without its `returns` and answer from a later one, as an agent does + * that waits to be woken: by a pull request it watches, by work it left running. Only when + * its thread has done nothing for this long is it asked for the result. Without it, a turn + * that ends without the result is asked at once. + */ + readonly quiet?: Duration.Input; +} + +type Attempt = + | { readonly outcome: "done"; readonly value: A; readonly thread: AgentThread } + | { readonly outcome: "failed"; readonly reason: string; readonly thread?: AgentThread }; + +const AGENT_OPTIONS = [ + "brief", + "returns", + "model", + "project", + "environment", + "thread", + "issue", + "timeout", + "quiet", + "title", + "workspace", + "runtimeMode", + "interactionMode", +]; + +// What only shapes a new thread: a continued one keeps its project, machine, model and modes. +const NEW_THREAD_OPTIONS = [ + "project", + "environment", + "model", + "title", + "workspace", + "runtimeMode", + "interactionMode", +] as const; + +const attempt = Effect.fn("workflow.agent")(function* ( + name: string, + options: AgentOptions, + /** What a failure does: pause the run at this step, or come back as the step's answer. */ + onFailure: "pause" | "return", +): Effect.fn.Return, StepFailed, InRun> { + checkOptions(`agent("${name}")`, options, AGENT_OPTIONS); + if (options.thread !== undefined) { + const shaping = NEW_THREAD_OPTIONS.filter((key) => options[key] !== undefined); + if (shaping.length > 0) { + return yield* Effect.die( + new Error( + `agent("${name}") continues \`thread\`, which keeps how it started. Drop ${shaping.map((key) => `\`${key}\``).join(", ")}.`, + ), + ); + } + } + const run = yield* claim(name); + const agents = yield* WorkflowAgents; + const outputSchema = + options.returns === undefined ? undefined : jsonSchemaOf(options.returns, true); + // Only a turn asked for a result can owe one from a later turn. + const quiet = + options.quiet === undefined || outputSchema === undefined + ? undefined + : Duration.fromInputUnsafe(options.quiet); + const outputCodec = + options.returns === undefined ? undefined : Schema.toCodecJson(options.returns); + const decodeOutput = outputCodec === undefined ? undefined : Schema.decodeEffect(outputCodec); + const threadOf = (turn: AgentTurn): AgentThread => ({ + threadId: turn.threadId, + ...(turn.environment === undefined ? {} : { environment: turn.environment }), + }); + const launch: AgentLaunch | undefined = + options.workspace === undefined && + options.runtimeMode === undefined && + options.interactionMode === undefined + ? undefined + : { + workspace: options.workspace, + runtimeMode: options.runtimeMode, + interactionMode: options.interactionMode, + }; + // What the agent's thread touches, its issue and the pull requests it links, is this step's. + const touches = stepReferences(run.store, run.runId, name); + const start = (key: string, prompt: string, thread: AgentThread | undefined) => + agents + .start({ + key: `${run.runId}/${name}/${key}`, + origin: { runId: run.runId, workflow: run.workflow, step: name }, + title: options.title ?? `${run.workflow}: ${name}`, + // Only the step's own `thread` is refused them; a correction on the thread it made is not. + launch: thread === undefined || thread === options.thread ? launch : undefined, + prompt, + outputSchema, + model: options.model, + project: options.project, + environment: thread === undefined ? options.environment : thread.environment, + thread: thread?.threadId, + issue: options.issue, + }) + .pipe( + Effect.provideContext(touches), + Effect.tap((turn) => + run.store.stepThread( + run.runId, + name, + turn.threadId, + turn.environment ?? null, + turn.turnId, + ), + ), + Effect.flatMap((turn) => + Effect.map(Clock.currentTimeMillis, (startedAt): AgentTurn => ({ ...turn, startedAt })), + ), + // No machine, no project, no link: for a step that takes failure as an answer, that is one. + onFailure === "pause" + ? identity + : Effect.catch((error) => + Effect.succeed({ threadId: "", turnId: "", failed: text(error) }), + ), + ); + const resultOf = (turn: AgentTurn, wait = { quiet }) => + agents + .result(turn, wait) + .pipe( + Effect.provideContext(touches), + onFailure === "pause" + ? identity + : Effect.catch((error) => + Effect.succeed({ ending: "failed", detail: text(error), reply: "" }), + ), + ); + /** The turn's result, or its thread stopped when the step's time is up. */ + const within = Effect.fn("workflow.agent.within")(function* ( + turn: AgentTurn, + startedAt: number | undefined, + ) { + if (options.timeout === undefined || startedAt === undefined) return yield* resultOf(turn); + const limit = Duration.fromInputUnsafe(options.timeout); + const left = startedAt + Duration.toMillis(limit) - (yield* Clock.currentTimeMillis); + const result = yield* resultOf(turn).pipe( + Effect.timeoutOption(Duration.millis(Math.max(0, left))), + ); + if (Option.isSome(result)) return result.value; + // A stop that still fails pauses the run unrecorded, so resuming tries the stop again. A step + // that returns its failure says the turn may still be running. + const stopping = agents + .interrupt({ ...threadOf(turn), turnId: turn.turnId }) + .pipe(Effect.retry({ times: 2 })); + const stop: "stopped" | "ended" | "failed" = yield* onFailure === "pause" + ? stopping + : stopping.pipe(Effect.orElseSucceed(() => "failed" as const)); + const late = `it was not done after ${Duration.format(limit)}`; + if (stop === "ended") { + // The turn ended before it could be stopped, maybe long ago, as a run that resumes late + // finds it. What it left is the answer when it is one. + const ended = yield* resultOf(turn, { quiet: undefined }); + if ( + ended.ending !== "completed" || + outputSchema === undefined || + ended.output !== undefined + ) { + return ended; + } + // Stopping the later turn it may answer from could stop someone else's. + return { + ending: "stopped" as const, + detail: `${late}: its turn ended without its result, and the agent may still be at work on its thread`, + reply: "", + }; + } + return { + ending: "stopped" as const, + detail: `${late}${stop === "stopped" ? "" : ", and its turn could not be stopped"}`, + reply: "", + }; + }); + const done = (round: number, produced: Schema.Json, said?: string) => + journaled( + run, + name, + `agent/${name}/${round}/done`, + Schema.Void, + Effect.all( + [ + run.store.stepEnded(run.runId, name, "completed", null), + run.store.stepResult(run.runId, name, produced, said), + run.store.runResumed(run.runId), + ], + { discard: true }, + ), + ); + + for (let round = 0; ; round++) { + let turn = yield* journaled( + run, + name, + `agent/${name}/${round}/start`, + AgentTurn, + Effect.andThen( + run.store.stepStarted(run.runId, name, "agent"), + start(`${round}`, options.brief, options.thread), + ), + ); + // Counted from the step's first turn, so corrections do not buy more time. + const startedAt = turn.startedAt; + let problem = turn.failed === undefined ? "" : `the agent could not be started: ${turn.failed}`; + let stopped = false; + let died = false; + for (let correction = 0; turn.failed === undefined; correction++) { + const result = yield* journaled( + run, + name, + `agent/${name}/${round}/result/${correction}`, + AgentResult, + Effect.andThen( + run.store.runStatus(run.runId, "waiting", `agent ${name}`), + within(turn, startedAt), + ), + ); + if (result.ending !== "completed") { + stopped = result.ending === "stopped"; + died = result.ending === "failed"; + problem = `the agent's turn was ${stopped ? "stopped" : "cut short"}: ${result.detail}`; + break; + } + if (decodeOutput === undefined) { + yield* done(round, result.reply); + return { outcome: "done", value: result.reply as A, thread: threadOf(turn) }; + } + // What the submitted result got wrong; undefined when nothing was submitted. + let misfit: string | undefined; + if (result.output !== undefined) { + const decoded = yield* Effect.result(decodeOutput(result.output)); + if (Result.isSuccess(decoded)) { + yield* done(round, result.output, result.reply); + return { outcome: "done", value: decoded.success, thread: threadOf(turn) }; + } + misfit = text(decoded.failure); + } + problem = + misfit === undefined + ? "the agent did not return a result: its turn ended with none accepted" + : `the agent's result did not fit: ${misfit}`; + if (correction >= CORRECTIONS) break; + // Back to the same thread: it has the context and only owes the result. + const corrected = yield* journaled( + run, + name, + `agent/${name}/${round}/correct/${correction}`, + AgentTurn, + start( + `${round}/correct/${correction}`, + misfit === undefined + ? "Your turn ended without an accepted result. Do not redo the work: call `t3_submit_output` now with the result of what you did." + : `The result you submitted does not fit: ${misfit}\nDo not redo the work: call \`t3_submit_output\` again with a corrected result.`, + threadOf(turn), + ), + ); + if (corrected.failed !== undefined) { + problem = `${problem}, and it could not be asked again: ${corrected.failed}`; + break; + } + turn = corrected; + } + // The turn may only be out of sight, not dead: it is stopped before another does its work again. + // A stop that does not get through pauses the run unrecorded, or gives up a step that returns. + let lingers = false; + if (died && turn.failed === undefined) { + const lost = turn; + lingers = !(yield* journaled( + run, + name, + `agent/${name}/${round}/stop`, + Schema.Boolean, + agents + .interrupt({ ...threadOf(lost), turnId: lost.turnId }) + .pipe( + Effect.retry({ times: 2 }), + Effect.as(true), + onFailure === "pause" ? identity : Effect.catch(() => Effect.succeed(false)), + ), + )); + if (lingers) problem = `${problem}; its turn could not be stopped`; + } + // A turn that died is not the job's fault the first time: once more, on a thread of its own, + // or on the same thread for a step that continues one, since only that thread has its project. + // Anything else is not tried again behind a person's back: one they stopped, one that never + // started, or one that did its work and would not give its result, which may have acted. + if (round % 2 === 0 && died && !lingers) continue; + if (onFailure === "return") { + yield* journaled( + run, + name, + `agent/${name}/${round}/failed`, + Schema.Void, + Effect.andThen( + run.store.stepEnded(run.runId, name, "failed", problem), + run.store.runResumed(run.runId), + ), + ); + return { + outcome: "failed", + reason: problem, + ...(turn.failed === undefined ? { thread: threadOf(turn) } : {}), + }; + } + // Fails the first time it is reached, which pauses the run here. Resuming the run reaches it + // again, and the next round starts. + yield* journaled( + run, + name, + `agent/${name}/${round}/pause`, + Schema.Void, + Effect.flatMap(run.store.mark(run.runId, `${name}/pause/${round}`), (arrivals) => + arrivals > 1 ? Effect.void : Effect.fail(problem), + ), + // Resuming starts the agent's job again from the top, which is a person's call. + true, + ); + } +}); + +const orPause = ( + name: string, + options: AgentOptions, +): Effect.Effect<{ readonly value: A; readonly thread: AgentThread }, never, InRun> => + Effect.flatMap(Effect.orDie(attempt(name, options, "pause")), (result) => + result.outcome === "done" + ? Effect.succeed({ value: result.value, thread: result.thread }) + : // `pause` never returns a failure: the step fails first, which pauses the run. + Effect.die(new Error(`Agent step ${name} failed without pausing: ${result.reason}`)), + ); + +/** + * An agent doing one job in a thread a person can open. It returns data checked against `returns`, + * or its last message without one. It starts a thread in `project`, in the linked `environment` + * when one is named, or continues `thread` where that is. Past `timeout` it is stopped. A turn + * that dies is tried once more, then the run pauses at this step. + */ +export const agent = Object.assign(orPause, { + /** + * For a workflow that decides for itself what a failed agent means: another model, another + * machine, or stop. An agent that could not be started, died twice, ran out of time or never + * gave its result comes back as `failed` with the reason, and the run goes on. + */ + try: ( + name: string, + options: AgentOptions, + ): Effect.Effect, never, InRun> => Effect.orDie(attempt(name, options, "return")), +}); + +/** + * A question a person answers with one of `choices`; `None` when the timeout passes first. The run + * holds nothing while it waits. `data` is the same facts as the title, for whatever lays the + * question out. + */ +export const ask = >( + name: string, + options: { + readonly title: string; + readonly choices: Choices; + readonly data?: Schema.Json; + readonly timeout?: Parameters[2]["timeout"]; + }, +): Effect.Effect< + Option.Option<{ readonly choice: Choices[number]; readonly reason?: string | undefined }>, + never, + InRun +> => + Effect.suspend(() => { + checkOptions(`ask("${name}")`, options, ["title", "choices", "data", "timeout"]); + return Effect.orDie( + waitAs("ask", name, { + returns: Schema.Struct({ + choice: Schema.Literals(options.choices), + reason: Schema.optional(Schema.String), + }), + timeout: options.timeout, + request: { + title: options.title, + choices: [...options.choices], + ...(options.data === undefined ? {} : { data: options.data }), + }, + }), + ); + }); diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index b0d2fecec2ff4..806a045898ddc 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -8,8 +8,11 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import { AuthAccessReadScope, + type AuthEnvironmentScope, AuthOrchestrationOperateScope, AuthOrchestrationReadScope, + type WorkflowRun, + type WorkflowStep, AuthSessionId, AuthSourceControlWriteScope, ORCHESTRATION_PROTOCOL_VERSION, @@ -130,6 +133,8 @@ import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolve import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts"; import * as ReviewService from "./review/ReviewService.ts"; import * as ScheduledTasks from "./scheduledTasks/ScheduledTaskService.ts"; +import * as Workflows from "./workflows/Workflows.ts"; +import * as WorkflowRuntime from "./workflows/WorkflowRuntime.ts"; import * as SecretRequests from "./secrets/SecretRequests.ts"; import * as FeedbackStore from "./feedback/FeedbackStore.ts"; import * as GuestShareService from "./guest/GuestShareService.ts"; @@ -883,6 +888,8 @@ const layerUnusedConfigRpcServices = Layer.mergeAll( Layer.mock(ResourceTelemetry.ResourceTelemetry)({}), Layer.mock(ReviewService.ReviewService)({}), Layer.mock(ScheduledTasks.ScheduledTaskService)({}), + Workflows.layerDisabled, + Layer.mock(WorkflowRuntime.WorkflowDefinitions)({}), Layer.mock(SecretRequests.SecretRequests)({}), Layer.mock(FeedbackStore.FeedbackStore)({}), Layer.mock(SecretResolver.SecretResolver)({}), @@ -2645,3 +2652,161 @@ it.effect("ACP session RPCs list a thread missing its history and repair it on i ), ), ); + +const workflowTags = [ + WS_METHODS.workflowsGet, + WS_METHODS.workflowsAnswer, + WS_METHODS.workflowsResume, + WS_METHODS.workflowsCancel, +] as const; +const workflowRpcs = WsRpcGroup.omit( + ...[...WsRpcGroup.requests.keys()].filter( + ( + tag, + ): tag is Exclude< + keyof typeof RpcAuthorization.RPC_REQUIRED_SCOPES, + (typeof workflowTags)[number] + > => !(workflowTags as ReadonlyArray).includes(tag), + ), +); +const workflowRun: WorkflowRun = { + runId: "run-1", + workflow: "release", + version: 1, + title: "Release 1.2", + status: "paused", + detail: "build failed: exit 1", + result: null, + pauses: 1, + retired: false, + resumesAt: null, + parentRunId: null, + parentStep: null, + startedAt: "2026-11-01T00:00:00.000Z", + updatedAt: "2026-11-01T00:01:00.000Z", + endedAt: null, +}; +const workflowStep: WorkflowStep = { + name: "build", + kind: "step", + status: "failed", + attempts: 2, + detail: "exit 1", + threadId: null, + environmentId: null, + result: null, + said: null, + startedAt: "2026-11-01T00:00:10.000Z", + endedAt: "2026-11-01T00:01:00.000Z", +}; + +/** A client for the workflow RPCs whose session holds `scopes`; `calls` records what reached the service. */ +const makeWorkflowClient = Effect.fn("test.makeWorkflowClient")(function* ( + scopes: ReadonlyArray, + calls: Array, +) { + const services = Layer.mergeAll( + layerUnusedConfigRpcServices, + Layer.mock(ExternalLauncher.ExternalLauncher)({}), + Layer.mock(ProviderRegistry.ProviderRegistry)({}), + Layer.mock(UsageLimitSources.UsageLimitSources)({}), + Layer.mock(RemoteOpenTargets.RemoteOpenTargets)({}), + Layer.mock(DirectEndpoints.DirectEndpoints)({}), + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/unused" }), + Layer.mock(ScratchThreadPromotion.ScratchThreadPromotion)({}), + Layer.mock(ServerEnvironment.ServerEnvironment)({}), + Layer.mock(EnvironmentAuth.EnvironmentAuth)({}), + Layer.mock(Workflows.Workflows)({ + get: (runId) => + runId === workflowRun.runId + ? Effect.succeed({ run: workflowRun, steps: [workflowStep], references: [] }) + : Effect.fail(new Workflows.WorkflowRunNotFoundError({ runId })), + answer: (runId, name, value) => + Effect.sync(() => calls.push({ answer: [runId, name], value })), + resume: (runId) => Effect.sync(() => calls.push({ resume: runId })), + cancel: (runId, reason) => Effect.sync(() => calls.push({ cancel: runId, reason })), + }), + ); + return yield* RpcTest.makeClient(workflowRpcs).pipe( + Effect.provide( + layerWsRpc( + { + sessionId: AuthSessionId.make("workflow-test"), + subject: "workflow-test", + method: "browser-session-cookie", + scopes: [...scopes], + }, + {}, + yield* ServerBrowser.ServerBrowser, + () => Effect.void, + { secretReferences: true }, + ).pipe(Layer.provide(services), Layer.merge(RpcAuthorization.layer(scopes))), + ), + ); +}); +const layerWorkflowRpcTest = Layer.mergeAll( + Layer.fresh(layerConfigSources), + Layer.mock(PreviewAutomationBroker.PreviewAutomationBroker)({}), + Layer.mock(ServerBrowser.ServerBrowser)({}), +); + +it.effect("workflow RPCs read a run and pass an answer, a resume and a cancel to the service", () => + Effect.gen(function* () { + const calls: Array = []; + const client = yield* makeWorkflowClient( + [AuthOrchestrationReadScope, AuthOrchestrationOperateScope], + calls, + ); + + assert.deepEqual(yield* client[WS_METHODS.workflowsGet]({ runId: "run-1" }), { + run: workflowRun, + steps: [workflowStep], + references: [], + }); + const missing = yield* client[WS_METHODS.workflowsGet]({ runId: "gone" }).pipe(Effect.flip); + assert.deepEqual( + [missing._tag, missing.message], + ["WorkflowRequestError", "Workflow run gone was not found."], + ); + + yield* client[WS_METHODS.workflowsAnswer]({ + runId: "run-1", + name: "approve", + choice: "yes", + reason: "Looks good", + }); + yield* client[WS_METHODS.workflowsAnswer]({ runId: "run-1", name: "approve", choice: "no" }); + yield* client[WS_METHODS.workflowsResume]({ runId: "run-1" }); + yield* client[WS_METHODS.workflowsCancel]({ runId: "run-1" }); + yield* client[WS_METHODS.workflowsCancel]({ runId: "run-1", reason: "Wrong branch" }); + + assert.deepEqual(calls, [ + { answer: ["run-1", "approve"], value: { choice: "yes", reason: "Looks good" } }, + { answer: ["run-1", "approve"], value: { choice: "no" } }, + { resume: "run-1" }, + { cancel: "run-1", reason: undefined }, + { cancel: "run-1", reason: "Wrong branch" }, + ]); + }).pipe(Effect.provide(layerWorkflowRpcTest), Effect.scoped), +); + +it.effect("a session that can only read sees a workflow run but cannot steer it", () => + Effect.gen(function* () { + const calls: Array = []; + const client = yield* makeWorkflowClient([AuthOrchestrationReadScope], calls); + + assert.equal((yield* client[WS_METHODS.workflowsGet]({ runId: "run-1" })).run.runId, "run-1"); + const refused = yield* Effect.all([ + client[WS_METHODS.workflowsAnswer]({ runId: "run-1", name: "approve", choice: "yes" }).pipe( + Effect.flip, + ), + client[WS_METHODS.workflowsResume]({ runId: "run-1" }).pipe(Effect.flip), + client[WS_METHODS.workflowsCancel]({ runId: "run-1" }).pipe(Effect.flip), + ]); + assert.deepEqual( + refused.map((error) => error._tag), + Array.from({ length: 3 }, () => "EnvironmentAuthorizationError"), + ); + assert.deepEqual(calls, []); + }).pipe(Effect.provide(layerWorkflowRpcTest), Effect.scoped), +); diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 051f81c08f70b..ff783eeb57324 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -37,6 +37,7 @@ import { AuthProvidersManageScope, type AuthEnvironmentScope, type ScheduledTaskListResult, + WorkflowRequestError, AuthSessionId, ClientConnectionMethod, ClientDeviceType, @@ -131,6 +132,8 @@ import * as ThreadLaunchService from "./orchestration-v2/ThreadLaunchService.ts" import * as ThreadMessageIntake from "./orchestration-v2/ThreadMessageIntake.ts"; import * as DocumentText from "./provider/DocumentText.ts"; import * as ScheduledTasks from "./scheduledTasks/ScheduledTaskService.ts"; +import * as Workflows from "./workflows/Workflows.ts"; +import * as WorkflowRuntime from "./workflows/WorkflowRuntime.ts"; import * as SecretRequests from "./secrets/SecretRequests.ts"; import * as FeedbackStore from "./feedback/FeedbackStore.ts"; import * as GuestShareService from "./guest/GuestShareService.ts"; @@ -1494,6 +1497,11 @@ export const layerWsRpc = ( const threadViewers = yield* ThreadViewers.ThreadViewers; const providerSessionManager = yield* ProviderSessionManager.ProviderSessionManagerV2; const scheduledTasks = yield* ScheduledTasks.ScheduledTaskService; + const workflows = yield* Workflows.Workflows; + const workflowDefinitions = yield* WorkflowRuntime.WorkflowDefinitions; + // The service's messages are built from its own attributes, so they are safe to send. + const toWorkflowRequestError = (error: Workflows.WorkflowError) => + new WorkflowRequestError({ message: error.message }); const secretRequests = yield* SecretRequests.SecretRequests; const feedbackStore = yield* FeedbackStore.FeedbackStore; const guestShares = yield* GuestShareService.GuestShareService; @@ -2363,6 +2371,25 @@ export const layerWsRpc = ( ), [ORCHESTRATION_V2_WS_METHODS.subscribePromptSuggestion]: (input) => providerSessionManager.subscribePromptSuggestion(input.threadId), + [WS_METHODS.workflowsSubscribe]: (_input) => workflows.watch, + [WS_METHODS.workflowsCounts]: (_input) => workflows.counts, + [WS_METHODS.workflowsGet]: (input) => + workflows.get(input.runId).pipe(Effect.mapError(toWorkflowRequestError)), + [WS_METHODS.workflowsAnswer]: (input) => + workflows + .answer(input.runId, input.name, { + choice: input.choice, + ...(input.reason === undefined ? {} : { reason: input.reason }), + }) + .pipe(Effect.mapError(toWorkflowRequestError)), + [WS_METHODS.workflowsResume]: (input) => + workflows.resume(input.runId).pipe(Effect.mapError(toWorkflowRequestError)), + [WS_METHODS.workflowsCancel]: (input) => + workflows.cancel(input.runId, input.reason).pipe(Effect.mapError(toWorkflowRequestError)), + [WS_METHODS.workflowsGetDefinition]: (_input) => workflowDefinitions.read, + [WS_METHODS.workflowsSaveDefinition]: (input) => + workflowDefinitions.save(input.name, input.source), + [WS_METHODS.workflowsDeleteDefinition]: (input) => workflowDefinitions.remove(input.name), [WS_METHODS.scheduledTasksSubscribe]: (_input) => scheduledTasks.subscribeList().pipe(Stream.map(withVisibleWebhookUrls)), [WS_METHODS.scheduledTasksUpsert]: (input) => scheduledTasks.upsert(input), diff --git a/docs/internals/workflows.md b/docs/internals/workflows.md new file mode 100644 index 0000000000000..5f9b965c082b5 --- /dev/null +++ b/docs/internals/workflows.md @@ -0,0 +1,178 @@ +# Workflows + +A workflow run is a journaled function: a step's result is stored once it succeeds, a restart +replays the run to where it was, and a run sleeps on a wait until something outside signals it. A +step's body can run more than once, after a failure it retries or a crash mid-step, so what it does +outside the run must be safe to repeat. The code is in +[`apps/server/src/workflows`](../../apps/server/src/workflows). This page holds what is not +obvious from it. + +## Why it is shaped this way + +**The engine is Effect's, in the server's database.** `effect/workflow` on one runner journals +runs in tables it creates itself. Runs, steps, waits and kept signals are rows of ours beside them, +not orchestration events: the event store knows projects and threads, a run is neither, and its +journal is the engine's to read. Clients follow runs the way they follow scheduled tasks, by a +list that is sent again when something changes. + +**Off until turned on, then until something is defined.** Workflows are a Labs setting, +`workflowsEnabled`, and the runtime's lifetime follows it: while it is off no file is loaded, no +engine runs, and every request is refused with how to turn it on; turning it off closes the +runtime the way a restart does, so runs wait in the database for it to come back. Once on, the +server registers what the files in the home's `workflows` folder define. While they define +nothing and no runs are kept, the `Workflows` service is the disabled one and the engine's modules +are never imported ([`WorkflowRuntime.ts`](../../apps/server/src/workflows/WorkflowRuntime.ts)). +Keep it that way: anything a light module imports from `effect/workflow` or `effect/cluster` is +paid for by every server and CLI start. + +**A step failure pauses the run.** The alternative, ending the run, loses everything done so far to +a dependency that is back in a minute. Resuming runs the failed step again and nothing before it. +Effect's engine suspends the body when a step fails, so no handler in the body ever sees the +error: the primitives type their error as `never`, and `step.try` and `agent.try` return a failure +as data instead. A step runs once unless it asks for retries, since a lost reply to a post or a +merge would otherwise do it again. A run paused by an agent that gave up waits for a person rather +than `resumeAfter`: resuming starts the agent's whole job again. `stop` is the workflow's own +decision to end, and is not a failure. + +**An agent step is a thread.** It completes when the agent submits a result the server checked +against the step's schema, not when a turn ends, and a person can open the thread and talk to it. +See [typed results](../orchestration-v2/orchestrator-mcp-server.md#t3_submit_output). + +**A run stays where it started; its agents need not.** An agent step that names a linked +environment runs its thread there through that environment's own thread tools, with the step's key +as the request id, so a replay finds the thread it already started. The run is no agent and has no +modes to pass on, so the link's access is the only ceiling on what it starts there. Making and +linking machines is the workflow author's own code in a `step`; nothing here knows how. + +**An agent step's thread says which run it belongs to.** The thread is created with the run, the +workflow and the step it is, and its lineage marks it as a workflow step, so the default lists +of threads leave it out the way they leave out subagents (a list that asks for subagents gets +them too): a run can have dozens, and they are read +through the run. Only the server may set this, as with a link's origin; over a link the launch +tool carries it and it is kept only for a link session. + +**An invoked run is a run of its own.** `invoke` starts it from a step with this run as its +parent and then waits like any `wait`; the engine signals that wait when the child ends, however +it ends, so a child that finished before the parent got to its wait is not missed. A key names +one run with one parent, so invoking under a key something else started is refused instead of +waiting for a signal that would never come. + +**The store is for inside a step.** Its values change between replays, so the body must not read +it; `step` and `onEnd` hand their code the store, a way to signal, and a way to start, find and +cancel runs, and nothing else may use them. A step's signals are numbered from the step's name +and where each goes, so a retried step that sends the same signal again sends no new one, and +one that sends somewhere new is not taken for what an earlier try sent. + +**A run keeps what it touched.** A reference is a `kind`, a `key` naming the thing within its +kind, and an `address` that only that kind's client reads, so a new kind is a new caller of +[`noteReference`](../../apps/server/src/workflows/runReferences.ts) and nothing more. It is called +from inside a step: by the forge helpers, by an agent step's thread for its `issue` and the pull +requests linked to it while the step ran, and by the engine's look at a pull request a wait is +on. An issue or pull request trigger notes its item with no step. There is one row per run, kind +and key, so a retry or replay that touches the same thing adds nothing. It is only for a person +to read: a failure to keep it is logged and never fails a step. Only a run's detail carries +references, not the list that is sent again on every change. + +**A thread owes its result across turns.** An agent that waits for something ends its turn and is +woken later, in a turn nobody asked a result of. A submission from such a turn goes to the newest +turn that was asked and has not answered, so the result lands on the turn the step started, and a +wait with `untilOutput` holds past that turn's end for it. The `quiet` option of an agent step is +that wait with a limit: quiet is counted from the thread's last turn, and when it passes the +step asks for the result as it would have at once without the option. + +**A failed agent is an answer only when the workflow asks for that.** `agent.try` journals the same +turns as `agent` and differs at the end: it marks the step failed and returns, where `agent` +fails the step and pauses the run. A start that failed is journaled as a turn without ids, so a +replay does not try the start again. + +**`onEnd` gets the payload and the run's id, not the body's values.** A cancelled run's body is +gone, so its cleanup runs outside the engine and has only what the run was started with. Inside +the engine `onEnd` is an ordinary last step. + +**Definitions reload by replacing the engine.** The engine is built from a fixed set of +definitions, so a changed folder closes it and builds a new one on the same database, which is +what a restart does; runs come through it as they come through a restart. The service the rest +of the server holds forwards to whichever engine is current, and callers during the swap wait +for the new one. With nothing defined but runs kept, an engine with nothing registered and no +cluster runner serves their history. + +**Each file keeps its last good version.** A file that stops loading does not take its workflows +down, and does not hold back the other files. A change that fails a check across files, a +workflow defined twice or a version dropped under unfinished runs, is held back the same way: +the changed file keeps its last good version (a new one stays out, and of two new files the +first by name wins), and the rest of the change is taken. A held change is tried again on every +reload, since the runs that held it may have ended. + +**The API is globals, so files load one at a time.** `T3.workflow` registers with the load in +progress, and the globals are the process's. A file is loaded under a new address each time, +because Node keeps a module by its address; modules a file imports keep theirs, so they are not +reloaded, and a workflow one of them defines registers only the first time. That is why shared +code belongs in a subfolder and definitions in the files themselves. Saving from a client +verifies a copy beside the real file first, so its imports resolve the same way. + +## Traps + +**A workflow body is replayed.** After a restart or a wait, the body runs again from the top and +each journaled action returns what it stored. Anything that touches the world goes through +a durable activity: `journaled` for `step` and `agent`, and a pair of open and close activities +around a `DurableDeferred` for `wait`, so a fix to one is not a fix to the other. Code between steps must give the same +answer on every pass: no clock, no randomness, no reads. + +**Names are the journal's keys.** A step's result and its row in the step list are both kept by +name, so two steps with one name would share a result. `claim` rejects that, across kinds. A change +to the order of steps, or to the shape a step returns, is a new `version` of the workflow; keep the +old one registered until its runs have ended. A run whose version is gone shows as `retired`. + +**The engine reads integers as BigInt, and nothing else may.** It stores 64-bit ids, which +`node:sqlite` only reads when asked for BigInts, so the engine's fibers and every call into it run +with `SqlClient.SafeIntegers` on. That setting is inherited by whatever those fibers call. +`journaled` turns it off again around a step's own code, and the sweep turns it off around the +turn stops and the `onEnd` it runs for a cancelled run; without that, a step that reads a project +gets rows it cannot decode. + +**The pause is recorded in two places, a moment apart.** A failing step marks its run paused from +inside the engine, just before the engine records the failure. `resume` waits for the engine's +record, or it would resume a run the engine does not yet consider stopped and do nothing. The sweep +puts back a run that still says it goes on while the engine holds it as failed, held for a person if +it was, and leaves alone one a resume is under way for. + +**A paused run is not woken.** The engine replays a run for any wake, and the replay runs the failed +step again as a resume would, though nobody resumed it. A signal, timeout or child's end for a +paused run's other wait is only claimed; the resume sends the wakes its run has claimed. + +**A step in flight cannot be interrupted.** The engine runs a step's body to its end. `cancel` +therefore ends the run's row first, so nothing the step still does is recorded as the outcome, and +stops the step's own turn, which is what makes a long agent step return. Only that turn: someone +else's turn on the same thread is left alone. The cancelled run's `onEnd` waits for the steps still +running in this process, or a cleanup would take away what a step is still making. A version stays +required while a cancelled run's cleanup still has tries left, since only that version can run it; +one that has used them up stays failed on the run for a person to see. + +**A key is one run whatever the version.** The engine's own run id hashes `name@version` with the +key, so after a version bump the same key would be a new run: a trigger that sees its newest issue +again, or a webhook retry, would start the work twice. The key is unique per workflow, so the row +that takes it is the run; a start that finds a row the engine never got executes it. + +**An ended run's journal is deleted.** The engine keeps every request and reply of a run, which +grew one large deployment's database by gigabytes in two weeks, so the sweep clears a run's engine +messages (its sleeps included) an hour after it ends with no step still going. Our rows stay, and +they are all that shows a run. Nothing may hand an ended run to the engine again: with no journal +it would run the body from the start, so a start for an ended run's key returns that run as it is. + +**One signal wakes one wait.** A wait is taken by the first signal for it; a second signal on the +same channel is for the next run that waits on that channel, and is kept until one does or its `ttl` runs +out (seven days by default), after which it is gone. A signal's id is remembered for seven days +once delivered, or until its `ttl` if that is later, so a sender's retry within that time is not a +second signal. + +**A wait checks a signal twice.** The engine checks a value against the wait's JSON Schema before +it wakes the wait, but only the run has the wait's codec, and a codec can refuse what its JSON +Schema allows (a number read from text). A value the codec refuses was not for the wait: the wait +opens again under a fresh wake and says why, rather than failing on every replay. Kept mail on a +channel that a wait cannot read is left for another wait there; mail addressed to that wait is +dropped. + +**`signalAll` keeps nothing.** It wakes the waits open on a channel now and is not kept for one that +opens later: a kept broadcast would wake whichever single run waited next, days on. A run that +holds for a condition therefore reads the condition in a step and waits with a timeout, so one +that began to wait just after the broadcast looks again. diff --git a/docs/orchestration-v2/orchestrator-mcp-server.md b/docs/orchestration-v2/orchestrator-mcp-server.md index 71d8845e74c75..8167049a87817 100644 --- a/docs/orchestration-v2/orchestrator-mcp-server.md +++ b/docs/orchestration-v2/orchestrator-mcp-server.md @@ -479,6 +479,13 @@ status and does not cancel work. `output` carries what the run submitted against its `outputSchema`; with `untilOutput`, a completed run that has not submitted yet is waited on until it has. +### `t3_workflow` + +Starts, lists, reads, signals, resumes and cancels [workflow runs](../internals/workflows.md), and +lists the questions runs ask a person. It is advertised to clients outside a thread only, such as +the `t3 workflow` CLI, so it costs no thread any context; an agent in a thread drives workflows +through that CLI. `start` is idempotent on `idempotencyKey` and `signal` on `signalId`. + ### `t3_thread_interrupt` Interrupts a selected active run through the normal V2 `run.interrupt` command. diff --git a/docs/user/managed-policy.md b/docs/user/managed-policy.md index 32e6f47da4693..a8583b923f3c1 100644 --- a/docs/user/managed-policy.md +++ b/docs/user/managed-policy.md @@ -249,6 +249,7 @@ so restart T3 Code after that. - `webhookTasks: false`: scheduled tasks cannot use webhook triggers. Existing webhook tasks stay but do not run, and cannot be turned back on. Users can still edit or delete them. + Workflow webhooks are refused too. - `browserCookieImport: false`: users cannot import cookies from another browser into T3 Code's browser. - `previewTunnel: false`: other devices cannot load this machine's `localhost` pages themselves. diff --git a/docs/user/outside-agents.md b/docs/user/outside-agents.md index 8bc6b50d24def..8a2f790905f75 100644 --- a/docs/user/outside-agents.md +++ b/docs/user/outside-agents.md @@ -139,7 +139,11 @@ A bot that supports MCP Events (`io.modelcontextprotocol/events`) can learn when something happens without reading threads over and over: a turn ended, an agent waits on a person, a guest asked something, a watched pull request woke its thread. Each of these is an event type it can poll or stream, narrowed to -projects or threads. The environment keeps its latest 1,000 milestones in +projects or threads. [Workflow runs](workflows.md) have their own event types, +narrowed to workflows or runs: a run started, paused, resumed or ended, and a +question it asks was raised or settled. Runs that another run started are left +out unless asked for, as subagent threads are, and narrowing thread events to a +run also picks out the threads that are its agent steps. The environment keeps its latest 1,000 milestones in memory, so a bot that was away longer, or reconnects after a restart, is told some may be missing and should reread the threads it cares about. diff --git a/evals/README.md b/evals/README.md index 8cfb697373c31..d2ecb73dd71be 100644 --- a/evals/README.md +++ b/evals/README.md @@ -4,13 +4,14 @@ An eval runs a real model against T3 Code's real text or code and scores what th Write or run an eval when a change affects what a model sees or does: agent instructions, MCP tool descriptions and schemas, tool results, generated titles, or the guidance an agent gets for a feature such as Device Manager. -| Eval | Measures | -| ------------------------------- | ---------------------------------------------------------------------------------------------------- | -| [mcp-tool-use](mcp-tool-use/) | Whether agents use T3's MCP tools correctly, including device routing and recovery, in fake threads. | -| [thread-titles](thread-titles/) | Whether generated thread titles name the right subject. | -| [pr-content](pr-content/) | Whether PR generation describes the diff when project instructions try to redirect it. | -| [voice-cleanup](voice-cleanup/) | Whether optional dictation cleanup edits only the spoken text and preserves its meaning. | -| [test-signal](test-signal/) | Whether a cheap model running the test-signal check flags low-signal tests. | +| Eval | Measures | +| ----------------------------------------- | ---------------------------------------------------------------------------------------------------- | +| [mcp-tool-use](mcp-tool-use/) | Whether agents use T3's MCP tools correctly, including device routing and recovery, in fake threads. | +| [thread-titles](thread-titles/) | Whether generated thread titles name the right subject. | +| [pr-content](pr-content/) | Whether PR generation describes the diff when project instructions try to redirect it. | +| [voice-cleanup](voice-cleanup/) | Whether optional dictation cleanup edits only the spoken text and preserves its meaning. | +| [test-signal](test-signal/) | Whether a cheap model running the test-signal check flags low-signal tests. | +| [workflow-authoring](workflow-authoring/) | Whether a model writes a working workflow file from the `t3-workflows` skill alone. | ## Run an eval diff --git a/evals/package.json b/evals/package.json index 245448ac4021c..21f022a680466 100644 --- a/evals/package.json +++ b/evals/package.json @@ -11,6 +11,7 @@ "pr-content": "node --env-file-if-exists=../.env pr-content/run.ts", "voice-cleanup": "node --env-file-if-exists=../.env voice-cleanup/run.ts", "test-signal": "node --env-file-if-exists=../.env test-signal/run.ts", + "workflow-authoring": "node --env-file-if-exists=../.env workflow-authoring/run.ts", "typecheck": "effect-tsgo tsrs --noEmit", "test": "vp test run --config ../vite.config.ts --dir ." }, diff --git a/evals/workflow-authoring/README.md b/evals/workflow-authoring/README.md new file mode 100644 index 0000000000000..f93fb582e6933 --- /dev/null +++ b/evals/workflow-authoring/README.md @@ -0,0 +1,36 @@ +# Workflow authoring + +Checks that a model can write a working workflow definitions file from the +[`t3-workflows` skill](../../skills/t3-workflows/SKILL.md) alone. Run it when the skill, the author +API, or the way the server loads a definitions file changes. + +The model gets the skill's body and one task, and replies with a file. The grader loads that file +with the server's loader, registers it in the real engine on a throwaway database, and drives it +with a stand-in for agents: it starts runs, delivers webhooks, answers questions, restarts the +engine, and checks how each run ends. Nothing is judged by reading the code. + +## Run + +```sh +cd evals +pnpm workflow-authoring --out runs/baseline +pnpm workflow-authoring --out runs/shorter --skill /path/to/variant.md --baseline runs/baseline/results.ndjson +``` + +- Models go through the `vibeproxy` CLIProxyAPI provider in `~/.codex/config.toml`. Default models: + `gpt-6.1-terra` and `gpt-6-luna`. Pass `--model` once per model to change them. +- Flags: `--skill ` (a variant of the skill), `--case ` (repeatable), `--samples ` + (default 3), `--reasoning ` (default `low`), `--baseline `. +- Each answer is saved next to the results as `...ts`, and `summary.md` lists + every problem the grader found. +- Cost: proxy quota only, about 5,000 tokens per sample. + +The answers are code the grader runs. They come from a model that saw only the skill and the task, +but run this on a machine where that is acceptable. + +## Add a case + +Add an entry to `cases.ts`: the task as a person would give it, and one or more scenarios. A +scenario says what the stand-in agent answers and returns the problems it finds after driving the +file's workflows; none is a pass. Put a reference answer in `fixtures/.ts`, which +`run.test.ts` requires to pass, and a wrong answer when the case exists to catch one mistake. diff --git a/evals/workflow-authoring/cases.ts b/evals/workflow-authoring/cases.ts new file mode 100644 index 0000000000000..9353dd4d7c12d --- /dev/null +++ b/evals/workflow-authoring/cases.ts @@ -0,0 +1,270 @@ +import * as Clock from "effect/Clock"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; + +import type { Case, World } from "./grade.ts"; + +const defined = (world: World, name: string) => + world.definitions.find((definition) => definition.name === name); +const missing = (name: string) => [`No workflow named ${name} is defined.`]; + +const todos = [ + { file: "src/a.ts", line: 3, text: "handle the empty list" }, + { file: "src/b.ts", line: 9, text: "remove after the migration" }, +]; + +const SUCCEEDED = JSON.stringify({ status: "succeeded", service: "billing" }); +const FAILED = JSON.stringify({ status: "failed", service: "checkout-api" }); + +export const cases: ReadonlyArray = [ + { + id: "scheduled-agent-then-approval", + source: + "The dependency report in the skill: a schedule, typed agent data, a question, a continued thread.", + task: [ + "Write a workflow named `todo-sweep` that runs every weekday (Monday to Friday) at 09:00.", + "An agent in the project with id `proj-1` lists the TODO comments in the repository as data shaped `{ todos: [{ file: string, line: number, text: string }] }`, without changing files.", + "If there are none, the run ends there; that is not a failure.", + "Otherwise a person is asked whether to fix them, with the choices `fix` and `skip`, and the run waits at most one day for the answer.", + "On `fix`, the same agent thread fixes them. On `skip` or no answer, the run ends.", + ].join("\n"), + scenarios: [ + { + name: "nothing to do", + agent: () => ({ output: { todos: [] } }), + check: (world) => + world.server( + Effect.fn(function* (workflows) { + const definition = defined(world, "todo-sweep"); + if (definition === undefined) return missing("todo-sweep"); + const problems: Array = []; + const schedule = definition.triggers.flatMap((trigger) => + trigger.kind === "schedule" && trigger.schedule.type === "fixed_time" + ? [trigger.schedule] + : [], + )[0]; + if (schedule === undefined) { + problems.push("It has no time-of-day trigger."); + } else { + if (!/^0?9:00$/.test(schedule.timeOfDay)) { + problems.push(`It runs at ${schedule.timeOfDay}, not 09:00.`); + } + if ([...(schedule.weekdays ?? [])].toSorted().join() !== "1,2,3,4,5") { + problems.push("It does not run on exactly Monday to Friday."); + } + } + const { runId } = yield* workflows.start( + "todo-sweep", + { scheduledAt: "2026-01-05T09:00:00.000Z" }, + { idempotencyKey: "a" }, + ); + const ended = yield* world.reaches( + workflows, + runId, + "stopped", + "completed", + "paused", + ); + if (Option.isNone(ended)) return [...problems, "The run never ended."]; + if (ended.value.status === "paused") { + problems.push(`The run paused: ${ended.value.detail}`); + } + if (world.turns.length !== 1) { + problems.push(`It asked for ${world.turns.length} agent turns, not 1.`); + } + if (world.turns[0]?.project !== "proj-1") { + problems.push("The agent did not start in proj-1."); + } + if ((yield* workflows.questions).length > 0) { + problems.push("It asked a person although there was nothing to fix."); + } + return problems; + }), + ), + }, + { + name: "approved", + agent: (turn) => + turn.outputSchema === undefined ? { reply: "Fixed." } : { output: { todos } }, + check: (world) => + world.server( + Effect.fn(function* (workflows) { + if (defined(world, "todo-sweep") === undefined) return missing("todo-sweep"); + const { runId } = yield* workflows.start( + "todo-sweep", + { scheduledAt: "2026-01-05T09:00:00.000Z" }, + { idempotencyKey: "b" }, + ); + const question = yield* world.asks(workflows, runId); + if (Option.isNone(question)) return ["It did not ask a person whether to fix them."]; + yield* workflows.signal( + { runId, wait: question.value }, + { choice: "fix" }, + { id: "answer-1" }, + ); + const ended = yield* world.reaches( + workflows, + runId, + "completed", + "paused", + "stopped", + ); + if (Option.isNone(ended) || ended.value.status !== "completed") { + return [ + `After "fix" the run did not complete: ${Option.getOrUndefined(ended)?.status ?? "never ended"}`, + ]; + } + const [first, second] = world.turns; + if (world.turns.length !== 2) { + return [`It asked for ${world.turns.length} agent turns, not 2.`]; + } + return second?.thread === `thread-${first?.key}` + ? [] + : ["The fix did not continue the first agent's thread."]; + }), + ), + }, + ], + }, + { + id: "webhook-filter-and-dedupe", + source: + "Scheduled-task webhooks keep filters and replay keys as settings; a workflow has to write both.", + task: [ + "Write a workflow named `deploy-watch` started by a webhook named `deploys`.", + 'The request body is JSON shaped `{ "status": string, "service": string }`.', + "A sender may deliver the same event more than once; the header `x-delivery-id` identifies an event, and one event must be one run.", + "Anything whose status is not `failed` is ignored: the run ends there, which is not a failure.", + "For a failed deploy, an agent in the project with id `proj-1` investigates. Its brief must name the service.", + ].join("\n"), + scenarios: [ + { + name: "deliveries", + agent: () => ({ reply: "The migration timed out." }), + check: (world) => + world.server( + Effect.fn(function* (workflows) { + if (defined(world, "deploy-watch") === undefined) return missing("deploy-watch"); + const hook = (yield* workflows.hooks).find((entry) => entry.name === "deploys"); + if (hook === undefined) return ["It has no webhook named deploys."]; + const [hookId, token] = hook.path.split("/").slice(-2).map(decodeURIComponent); + const deliver = (delivery: string, body: string) => + workflows + .deliver({ + hookId: hookId!, + token: token!, + request: { + method: "POST", + headers: { "content-type": "application/json", "x-delivery-id": delivery }, + query: "", + body, + }, + }) + .pipe(Effect.map(Option.getOrThrow)); + const problems: Array = []; + + const fine = yield* deliver("d1", SUCCEEDED); + const ignored = yield* world.reaches( + workflows, + fine.runId, + "skipped", + "stopped", + "completed", + "paused", + ); + if (Option.isNone(ignored) || ignored.value.status === "paused") { + problems.push("A deploy that did not fail left its run paused or unfinished."); + } + if (world.turns.length > 0) + problems.push("It started an agent for a deploy that did not fail."); + + const failed = yield* deliver("d2", FAILED); + const again = yield* deliver("d2", FAILED); + if (again.runId !== failed.runId) + problems.push("A redelivered event started a second run."); + const done = yield* world.reaches( + workflows, + failed.runId, + "completed", + "paused", + "stopped", + ); + if (Option.isNone(done) || done.value.status !== "completed") { + problems.push( + `A failed deploy's run did not complete: ${Option.getOrUndefined(done)?.detail ?? "never ended"}`, + ); + } + const turn = world.turns[0]; + if (turn === undefined) + return [...problems, "It started no agent for a failed deploy."]; + if (turn.project !== "proj-1") problems.push("The agent did not start in proj-1."); + if (!turn.prompt.includes("checkout-api")) + problems.push("The brief does not name the service."); + return problems; + }), + ), + }, + ], + }, + { + id: "replay-keeps-what-it-read", + source: + "The replay rule: the body runs again after a wait, so a value read from the world outside a step changes under the run.", + task: [ + "Write a workflow named `stamp`, started by hand with the payload `{ label: string }`, that returns a string.", + "It reads the current time in milliseconds since the epoch, then waits for a signal named `go` whose value is a string.", + "When the signal arrives it returns `( + use: (workflows: Workflows.Workflows["Service"]) => Effect.Effect, + ) => Effect.Effect; + /** The run once it is in one of these states, or nothing after ten seconds. */ + readonly reaches: ( + workflows: Workflows.Workflows["Service"], + runId: string, + ...statuses: ReadonlyArray + ) => Effect.Effect>; + /** The name of the question the run asks a person, or nothing after ten seconds. */ + readonly asks: ( + workflows: Workflows.Workflows["Service"], + runId: string, + ) => Effect.Effect>; +} + +export interface Case { + readonly id: string; + readonly source: string; + /** What the model is asked to write. */ + readonly task: string; + /** What a fake agent answers. Each scenario of the case sets its own. */ + readonly scenarios: ReadonlyArray<{ + readonly name: string; + readonly agent: (turn: AgentTurnInput) => Partial; + /** The problems found. None is a pass. */ + readonly check: (world: World) => Effect.Effect, Workflows.WorkflowError>; + }>; +} + +// Across every grade in the process: a load under an address used before would get that module. +let lifetimes = 0; + +const world = Effect.fn("gradeWorkflow.world")(function* ( + file: string, + definitions: ReadonlyArray, + agent: (turn: AgentTurnInput) => Partial, +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-workflow-eval-" }); + const database = NodeSqliteClient.layer({ filename: path.join(directory, "state.sqlite") }); + yield* Effect.provide(WorkflowsMigration, database); + const turns: Array = []; + const asked = new Map(); + const agents = WorkflowAgents.of({ + start: Effect.fn("gradeWorkflow.agents.start")(function* (input) { + if (!asked.has(input.key)) { + asked.set(input.key, input); + turns.push(input); + } + return yield* Effect.succeed({ + threadId: input.thread ?? `thread-${input.key}`, + turnId: input.key, + }); + }), + result: Effect.fn("gradeWorkflow.agents.result")(function* (turn) { + return yield* Effect.succeed({ + ending: "completed" as const, + detail: "", + reply: "", + ...agent(asked.get(turn.turnId)!), + }); + }), + // Every turn here has already completed, so there is nothing to stop. + interrupt: Effect.fn("gradeWorkflow.agents.interrupt")(function* () { + return yield* Effect.succeed("ended" as const); + }), + }); + const engine = (loaded: ReadonlyArray) => + WorkflowEngine.layer(loaded).pipe( + Layer.provide(Layer.succeed(WorkflowAgents, agents)), + Layer.provide(database), + Layer.provide(NodeCrypto.layer), + Layer.orDie, + ); + return { + definitions, + turns, + server: (use) => + loadDefinitions(file, ++lifetimes).pipe( + Effect.orDie, + Effect.provideService(Path.Path, path), + Effect.flatMap((loaded) => + Effect.scoped(Effect.provide(Effect.flatMap(Workflows.Workflows, use), engine(loaded))), + ), + ), + reaches: (workflows, runId, ...statuses) => + workflows + .waitFor(runId, (run) => statuses.includes(run.status)) + .pipe(Effect.timeoutOption("10 seconds")), + asks: (workflows, runId) => + workflows.watch.pipe( + Stream.filterMap((snapshot) => { + const question = snapshot.questions.find((asked) => asked.runId === runId); + return question === undefined ? Result.failVoid : Result.succeed(question.name); + }), + Stream.runHead, + Effect.timeoutOption("10 seconds"), + Effect.map(Option.flatten), + ), + } satisfies World; +}); + +const problemsWith = Effect.fn("gradeWorkflow.problemsWith")(function* (file: string, entry: Case) { + const loaded = yield* Effect.result(loadDefinitions(file)); + if (loaded._tag === "Failure") { + return [`The file does not load: ${String(loaded.failure.cause)}`]; + } + const problems: Array = []; + for (const scenario of entry.scenarios) { + const found = yield* world(file, loaded.success, scenario.agent).pipe( + Effect.flatMap(scenario.check), + Effect.scoped, + Effect.catch((error) => Effect.succeed([error.message])), + Effect.catchDefect((defect) => Effect.succeed([`It crashed: ${String(defect)}`])), + ); + problems.push(...found.map((problem) => `${scenario.name}: ${problem}`)); + } + return problems; +}); + +/** The problems with the workflow file at `file` as an answer to `entry`. None is a pass. */ +export const grade = (file: string, entry: Case): Promise> => + Effect.runPromise(Effect.provide(problemsWith(file, entry), NodeServices.layer)); diff --git a/evals/workflow-authoring/run.test.ts b/evals/workflow-authoring/run.test.ts new file mode 100644 index 0000000000000..104d56d38d77b --- /dev/null +++ b/evals/workflow-authoring/run.test.ts @@ -0,0 +1,37 @@ +// A test of an eval script, which works on plain file paths. +// @effect-diagnostics nodeBuiltinImport:off +import * as NodePath from "node:path"; + +import { expect, it } from "vite-plus/test"; + +import { cases } from "./cases.ts"; +import { grade } from "./grade.ts"; + +const fixture = (name: string) => NodePath.join(import.meta.dirname, "fixtures", `${name}.ts`); +const entry = (id: string) => cases.find((candidate) => candidate.id === id)!; + +it.each(cases.map((candidate) => candidate.id))("a correct answer to %s passes", async (id) => { + expect(await grade(fixture(id), entry(id))).toEqual([]); +}); + +it("a body that reads the clock outside a step fails the replay case", async () => { + expect( + await grade(fixture("replay-reads-outside-a-step"), entry("replay-keeps-what-it-read")), + ).toEqual([ + "restart while waiting: The time it returned was read again after the restart, not kept from the start.", + ]); +}); + +it("a body that keeps the time in a module variable fails the replay case", async () => { + expect( + await grade(fixture("replay-keeps-in-a-module"), entry("replay-keeps-what-it-read")), + ).toEqual([ + "restart while waiting: The time it returned was read again after the restart, not kept from the start.", + ]); +}); + +it("an answer to another task fails with the reason", async () => { + expect( + await grade(fixture("webhook-filter-and-dedupe"), entry("replay-keeps-what-it-read")), + ).toEqual(["restart while waiting: No workflow named stamp is defined."]); +}); diff --git a/evals/workflow-authoring/run.ts b/evals/workflow-authoring/run.ts new file mode 100644 index 0000000000000..2e2c66f7a5fff --- /dev/null +++ b/evals/workflow-authoring/run.ts @@ -0,0 +1,179 @@ +#!/usr/bin/env node +// An eval script, not server code: it reads and writes files directly. +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeFS from "node:fs"; +import * as NodePath from "node:path"; +import * as NodeUtil from "node:util"; +import * as Effect from "effect/Effect"; +import * as Schedule from "effect/Schedule"; +import * as Schema from "effect/Schema"; +import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http"; + +import { proxyConfig } from "../shared/proxy.ts"; +import { cases } from "./cases.ts"; +import { type Case, grade } from "./grade.ts"; + +const { values } = NodeUtil.parseArgs({ + options: { + out: { type: "string" }, + model: { type: "string", multiple: true }, + skill: { type: "string" }, + case: { type: "string", multiple: true }, + samples: { type: "string", default: "3" }, + reasoning: { type: "string", default: "low" }, + baseline: { type: "string" }, + }, +}); +if (!values.out) throw new Error("Use --out [--model ] [--skill ]."); +const outDirectory = values.out; +const models = values.model ?? ["gpt-6.1-terra", "gpt-6-luna"]; +const skillFile = + values.skill ?? NodePath.resolve(import.meta.dirname, "../../skills/t3-workflows/SKILL.md"); +// An agent is given the skill's body; the front matter only decides when it loads. +const skill = NodeFS.readFileSync(skillFile, "utf8") + .replace(/^---\n[\s\S]*?\n---\n/, "") + .trim(); +const selected = values.case ? cases.filter((entry) => values.case!.includes(entry.id)) : cases; +const proxy = proxyConfig(); + +const Row = Schema.Struct({ + model: Schema.String, + case: Schema.String, + sample: Schema.Number, + problems: Schema.Array(Schema.String), + tokens: Schema.Number, +}); +const encodeRow = Schema.encodeSync(Schema.fromJsonString(Row)); +const decodeRow = Schema.decodeUnknownSync(Schema.fromJsonString(Row)); +const decodeResponse = Schema.decodeUnknownSync( + Schema.fromJsonString( + Schema.Struct({ + output: Schema.Array(Schema.Record(Schema.String, Schema.Unknown)), + usage: Schema.optional(Schema.Struct({ total_tokens: Schema.optional(Schema.Number) })), + }), + ), +); + +const instructions = [ + "You write workflow definitions files for T3 Code. This is everything you know about them:", + "", + "", + skill, + "", + "", + "Reply with the complete definitions file in one ```ts code block and nothing else.", +].join("\n"); + +const sample = Effect.fn("evaluateWorkflowAuthoring.sample")(function* ( + entry: Case, + model: string, + index: number, +) { + const client = (yield* HttpClient.HttpClient).pipe( + HttpClient.retryTransient({ + retryOn: "errors-and-responses", + schedule: Schedule.exponential("2 seconds"), + times: 4, + }), + ); + const response = yield* HttpClientRequest.post(`${proxy.url}/responses`).pipe( + HttpClientRequest.setHeaders(proxy.headers), + HttpClientRequest.bodyJson({ + model, + instructions, + input: [{ role: "user", content: entry.task }], + reasoning: { effort: values.reasoning }, + store: false, + }), + Effect.flatMap(client.execute), + ); + const body = yield* response.text; + if (response.status !== 200) { + return yield* Effect.die(new Error(`Model API ${response.status}: ${body}`)); + } + const decoded = decodeResponse(body); + const reply = decoded.output + .filter((item) => item.type === "message") + .flatMap((item) => (item.content as Array<{ text?: string }>).map((part) => part.text ?? "")) + .join(""); + const code = /```(?:ts|typescript)?\n([\s\S]*?)```/.exec(reply)?.[1] ?? reply; + const file = NodePath.join(outDirectory, `${entry.id}.${model}.${index}.ts`); + NodeFS.writeFileSync(file, code); + const problems = yield* Effect.promise(() => grade(file, entry)); + return { + model, + case: entry.id, + sample: index, + problems, + tokens: decoded.usage?.total_tokens ?? 0, + }; +}); + +/** Half or more of a case's samples failing is the case failing. */ +const passes = (rows: ReadonlyArray, model: string, id: string) => { + const own = rows.filter((row) => row.model === model && row.case === id); + return own.length > 0 && own.filter((row) => row.problems.length > 0).length < own.length / 2; +}; + +NodeFS.mkdirSync(outDirectory, { recursive: true }); +const summary = await Effect.runPromise( + Effect.gen(function* () { + const count = Number(values.samples); + const rows = yield* Effect.forEach( + models.flatMap((model) => + selected.flatMap((entry) => + Array.from({ length: count }, (_, index) => ({ model, entry, index })), + ), + ), + ({ model, entry, index }) => + sample(entry, model, index).pipe( + Effect.catchDefect((defect) => + Effect.succeed({ + model, + case: entry.id, + sample: index, + problems: [`The sample did not run: ${String(defect)}`], + tokens: 0, + }), + ), + ), + // The grader starts an engine per scenario; a few at a time keeps their timings honest. + { concurrency: 3 }, + ); + NodeFS.writeFileSync( + NodePath.join(outDirectory, "results.ndjson"), + rows.map((row) => encodeRow(row)).join("\n") + "\n", + ); + const baseline = values.baseline + ? NodeFS.readFileSync(values.baseline, "utf8") + .trim() + .split("\n") + .map((line) => decodeRow(line)) + : undefined; + const words = skill.split(/\s+/).length; + const lines = [`skill ${skillFile}, ${words} words, ${count} samples per case`, ""]; + lines.push("| model | case | samples passed | verdict | baseline |", "|---|---|---|---|---|"); + for (const model of models) { + for (const entry of selected) { + const own = rows.filter((row) => row.model === model && row.case === entry.id); + const good = own.filter((row) => row.problems.length === 0).length; + const before = + baseline === undefined ? "" : passes(baseline, model, entry.id) ? "pass" : "fail"; + lines.push( + `| ${model} | ${entry.id} | ${good}/${own.length} | ${passes(rows, model, entry.id) ? "pass" : "FAIL"} | ${before} |`, + ); + } + } + const tokens = rows.reduce((sum, row) => sum + row.tokens, 0); + lines.push("", `${tokens} tokens`, "", "## Problems", ""); + for (const row of rows) { + for (const problem of row.problems) { + lines.push(`- ${row.model} ${row.case} #${row.sample}: ${problem}`); + } + } + const report = lines.join("\n") + "\n"; + NodeFS.writeFileSync(NodePath.join(outDirectory, "summary.md"), report); + return report; + }).pipe(Effect.provide(FetchHttpClient.layer)), +); +process.stdout.write(summary); diff --git a/knip.jsonc b/knip.jsonc index 748d6864e2217..bd3228b7ac504 100644 --- a/knip.jsonc +++ b/knip.jsonc @@ -17,6 +17,10 @@ "vite": { "entry": [".github/**/*.test.cjs"] }, "vitest": { "entry": [".github/**/*.test.cjs"] }, }, + "evals": { + // The grader loads these answers by path, as the server loads a definitions file. + "entry": ["workflow-authoring/fixtures/*.ts"], + }, "scripts": { // Knip loads its preprocessor through a CLI option; native verification and // worktree setup (from t3.json) run directly. release-desktop.yml bundles the diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.ts index f7825d6364b79..b23b4650b20a9 100644 --- a/packages/contracts/src/clientRpcPermissions.ts +++ b/packages/contracts/src/clientRpcPermissions.ts @@ -82,6 +82,13 @@ export const CLIENT_GUARDED_RPC_SCOPES = { [WS_METHODS.scheduledTasksRunNow]: AuthOrchestrationOperateScope, [WS_METHODS.scheduledTasksRotateWebhookToken]: AuthOrchestrationOperateScope, [ORCHESTRATION_V2_WS_METHODS.stopWorkflow]: AuthOrchestrationOperateScope, + // An answer, a resume and a cancel each decide what a run's agents do next. + [WS_METHODS.workflowsAnswer]: AuthOrchestrationOperateScope, + [WS_METHODS.workflowsResume]: AuthOrchestrationOperateScope, + [WS_METHODS.workflowsCancel]: AuthOrchestrationOperateScope, + // The server runs this file: saving it is running code there, as a terminal does. + [WS_METHODS.workflowsSaveDefinition]: AuthTerminalOperateScope, + [WS_METHODS.workflowsDeleteDefinition]: AuthTerminalOperateScope, // Force stop kills agent processes, as Stop on a terminal does. [ORCHESTRATION_V2_WS_METHODS.forceStopThread]: AuthOrchestrationOperateScope, // A guest link hands thread access to someone outside, like a pairing link. diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index 7a159c816ef11..58863aaebd5e5 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -68,6 +68,7 @@ export * from "./previewCapture.ts"; export * from "./usage.ts"; export * from "./scheduledTask.ts"; export * from "./milestones.ts"; +export * from "./workflow.ts"; export * from "./worktreeMcp.ts"; export * from "./resourceTelemetry.ts"; export * from "./rpc.ts"; diff --git a/packages/contracts/src/milestones.ts b/packages/contracts/src/milestones.ts index 56e259b2b9fab..5bc08bc403edb 100644 --- a/packages/contracts/src/milestones.ts +++ b/packages/contracts/src/milestones.ts @@ -37,14 +37,25 @@ const MilestoneEnvelope = Schema.Struct({ threadId: Schema.NullOr(ThreadId), parentThreadId: Schema.NullOr(ThreadId), actor: MilestoneActor, - /** A subagent's thread. Muted unless asked for. */ + /** A subagent's thread, or a run another run invoked. Muted unless asked for. */ isSubagentChild: Schema.Boolean, + /** The workflow run a workflow milestone is about, or whose agent step the thread is. */ + workflowRunId: Schema.optional(TrimmedNonEmptyString), }); /** `approval` covers command, file and permission prompts; `user_input` covers questions. */ export const MilestoneInputKind = Schema.Literals(["user_input", "approval"]); export type MilestoneInputKind = typeof MilestoneInputKind.Type; +/** Which workflow run a workflow milestone is about. Its envelope names no project or thread. */ +const WorkflowRunFields = { + workflowRunId: TrimmedNonEmptyString, + workflow: TrimmedNonEmptyString, + runTitle: Schema.String, + /** The run that invoked this one, when one did. */ + parentWorkflowRunId: Schema.NullOr(TrimmedNonEmptyString), +}; + export const MilestoneEvent = Schema.Union([ Schema.Struct({ ...MilestoneEnvelope.fields, @@ -88,6 +99,45 @@ export const MilestoneEvent = Schema.Union([ /** The watch ended with this wake, as a merge, a close or a read failure ends it. */ watchEnded: Schema.Boolean, }), + Schema.Struct({ + ...MilestoneEnvelope.fields, + ...WorkflowRunFields, + type: Schema.Literal("workflow.run_started"), + }), + Schema.Struct({ + ...MilestoneEnvelope.fields, + ...WorkflowRunFields, + type: Schema.Literal("workflow.needs_input"), + /** The step that asks, which answering names. */ + step: TrimmedNonEmptyString, + question: Schema.String, + }), + Schema.Struct({ + ...MilestoneEnvelope.fields, + ...WorkflowRunFields, + type: Schema.Literal("workflow.input_resolved"), + step: TrimmedNonEmptyString, + /** `cancelled` when the run ended with the question still open. */ + resolution: Schema.Literals(["answered", "expired", "cancelled"]), + }), + Schema.Struct({ + ...MilestoneEnvelope.fields, + ...WorkflowRunFields, + type: Schema.Literal("workflow.run_paused"), + reason: Schema.String, + }), + Schema.Struct({ + ...MilestoneEnvelope.fields, + ...WorkflowRunFields, + type: Schema.Literal("workflow.run_resumed"), + }), + Schema.Struct({ + ...MilestoneEnvelope.fields, + ...WorkflowRunFields, + type: Schema.Literal("workflow.run_ended"), + outcome: Schema.Literals(["completed", "stopped", "skipped", "cancelled"]), + detail: Schema.NullOr(Schema.String), + }), ]); export type MilestoneEvent = typeof MilestoneEvent.Type; @@ -98,6 +148,12 @@ export const MilestoneEventType = Schema.Literals([ "thread.guest_request", "thread.guest_request_resolved", "pr.watch_wake", + "workflow.run_started", + "workflow.needs_input", + "workflow.input_resolved", + "workflow.run_paused", + "workflow.run_resumed", + "workflow.run_ended", ]); export type MilestoneEventType = typeof MilestoneEventType.Type; @@ -105,7 +161,11 @@ export const MilestoneFilter = Schema.Struct({ types: Schema.optional(Schema.Array(MilestoneEventType)), projectIds: Schema.optional(Schema.Array(ProjectId)), threadIds: Schema.optional(Schema.Array(ThreadId)), - /** Absent reads as false: subagent threads churn and are rarely news. */ + /** Workflow names. Given, it matches only workflow milestones. */ + workflows: Schema.optional(Schema.Array(TrimmedNonEmptyString)), + /** Workflow runs, with the threads that are their agent steps. */ + workflowRunIds: Schema.optional(Schema.Array(TrimmedNonEmptyString)), + /** Absent reads as false: subagent threads and invoked runs churn and are rarely news. */ includeSubagentChildren: Schema.optional(Schema.Boolean), }); export type MilestoneFilter = typeof MilestoneFilter.Type; @@ -117,4 +177,8 @@ export const milestoneMatches = (event: MilestoneEvent, filter: MilestoneFilter (filter.projectIds === undefined || (event.projectId !== null && filter.projectIds.includes(event.projectId))) && (filter.threadIds === undefined || - (event.threadId !== null && filter.threadIds.includes(event.threadId))); + (event.threadId !== null && filter.threadIds.includes(event.threadId))) && + (filter.workflows === undefined || + ("workflow" in event && filter.workflows.includes(event.workflow))) && + (filter.workflowRunIds === undefined || + (event.workflowRunId !== undefined && filter.workflowRunIds.includes(event.workflowRunId))); diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 6eec84b4dc253..33961fcf8b82b 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -160,6 +160,18 @@ export const OrchestrationV2LinkedSender = Schema.Struct({ }); export type OrchestrationV2LinkedSender = typeof OrchestrationV2LinkedSender.Type; +/** + * The workflow run a thread is an agent step of, with the step's name. `environmentId` is where + * the run lives, which is another environment for a step that runs through a link. + */ +export const OrchestrationV2WorkflowOrigin = Schema.Struct({ + environmentId: EnvironmentId, + runId: TrimmedNonEmptyString, + workflow: TrimmedNonEmptyString, + step: TrimmedNonEmptyString, +}); +export type OrchestrationV2WorkflowOrigin = typeof OrchestrationV2WorkflowOrigin.Type; + export const OrchestrationV2NativeRefStrength = Schema.Literals(["strong", "weak", "none"]); export type OrchestrationV2NativeRefStrength = typeof OrchestrationV2NativeRefStrength.Type; @@ -177,12 +189,19 @@ export const OrchestrationV2AppThreadLineage = Schema.Struct({ relationshipToParent: Schema.NullOr(Schema.Literals(["fork", "subagent"])), rootThreadId: ThreadId, sideChat: Schema.optional(Schema.Boolean), + /** An agent step of a workflow run, which the thread's `workflowRun` names. */ + workflowStep: Schema.optional(Schema.Boolean), }); export type OrchestrationV2AppThreadLineage = typeof OrchestrationV2AppThreadLineage.Type; -/** Subagents and side chats live inside their parent's view, never in thread lists. */ +/** + * Subagents and side chats live inside their parent's view, and a workflow run's agent steps + * inside the run's, never in thread lists. + */ export const isListedThreadLineage = (lineage: OrchestrationV2AppThreadLineage): boolean => - lineage.relationshipToParent !== "subagent" && lineage.sideChat !== true; + lineage.relationshipToParent !== "subagent" && + lineage.sideChat !== true && + lineage.workflowStep !== true; export const OrchestrationV2ContextTransferType = Schema.Literals([ "fork", @@ -497,6 +516,7 @@ export const OrchestrationV2AppThread = Schema.Struct({ historyOrigin: Schema.optional(OrchestrationV2ThreadHistoryOrigin), linkOrigin: Schema.optional(OrchestrationV2LinkOrigin), delegatedFrom: Schema.optional(OrchestrationV2DelegatedFrom), + workflowRun: Schema.optional(OrchestrationV2WorkflowOrigin), lineage: OrchestrationV2AppThreadLineage, forkedFrom: Schema.NullOr( Schema.Union([ @@ -2387,6 +2407,7 @@ export const OrchestrationV2ThreadShell = Schema.Struct({ historyOrigin: Schema.optional(OrchestrationV2ThreadHistoryOrigin), linkOrigin: Schema.optional(OrchestrationV2LinkOrigin), delegatedFrom: Schema.optional(OrchestrationV2DelegatedFrom), + workflowRun: Schema.optional(OrchestrationV2WorkflowOrigin), latestRunId: Schema.NullOr(RunId), latestRunRequestedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)), latestRunStartedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)), @@ -3288,6 +3309,8 @@ export const OrchestrationV2Command = Schema.Union([ linkOrigin: Schema.optional(OrchestrationV2LinkOrigin), /** Only the server sets this, with `linkOrigin`, for a linked environment's delegated task. */ delegatedFrom: Schema.optional(OrchestrationV2DelegatedFrom), + /** Only the server sets this, for a thread that is a workflow run's agent step. */ + workflowRun: Schema.optional(OrchestrationV2WorkflowOrigin), importedNativeThread: Schema.optional( Schema.Struct({ ref: Schema.Struct({ diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index e56009a98fb4e..c7fe990a4be7e 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -420,6 +420,22 @@ import { ListTextGeneratorModelsResult, TextGeneratorError, } from "./settings.ts"; +import { + WorkflowAnswerInput, + WorkflowRequestError, + WorkflowDefinitionChangeResult, + WorkflowDefinitionDeleteInput, + WorkflowDefinitionFiles, + WorkflowDefinitionGetInput, + WorkflowDefinitionSaveInput, + WorkflowRunCancelInput, + WorkflowRunDetail, + WorkflowRunGetInput, + WorkflowRunResumeInput, + WorkflowCounts, + WorkflowRunsSnapshot, + WorkflowRunsSubscribeInput, +} from "./workflow.ts"; import { ScheduledTaskDeleteInput, ScheduledTaskDeleteResult, @@ -617,6 +633,16 @@ export const WS_METHODS = { serverGetUsageSummary: "server.getUsageSummary", serverRefreshUsageRates: "server.refreshUsageRates", + workflowsSubscribe: "workflows.subscribe", + workflowsCounts: "workflows.counts", + workflowsGet: "workflows.get", + workflowsAnswer: "workflows.answer", + workflowsResume: "workflows.resume", + workflowsCancel: "workflows.cancel", + workflowsGetDefinition: "workflows.getDefinition", + workflowsSaveDefinition: "workflows.saveDefinition", + workflowsDeleteDefinition: "workflows.deleteDefinition", + scheduledTasksSubscribe: "scheduledTasks.subscribe", scheduledTasksUpsert: "scheduledTasks.upsert", scheduledTasksSetEnabled: "scheduledTasks.setEnabled", @@ -2286,6 +2312,59 @@ const WsSubscribeServerLifecycleRpc = Rpc.make(WS_METHODS.subscribeServerLifecyc stream: true, }); +const WsWorkflowsSubscribeRpc = Rpc.make(WS_METHODS.workflowsSubscribe, { + payload: WorkflowRunsSubscribeInput, + success: WorkflowRunsSnapshot, + error: EnvironmentAuthorizationError, + stream: true, +}); + +const WsWorkflowsCountsRpc = Rpc.make(WS_METHODS.workflowsCounts, { + payload: WorkflowRunsSubscribeInput, + success: WorkflowCounts, + error: EnvironmentAuthorizationError, + stream: true, +}); + +const WsWorkflowsGetRpc = Rpc.make(WS_METHODS.workflowsGet, { + payload: WorkflowRunGetInput, + success: WorkflowRunDetail, + error: Schema.Union([WorkflowRequestError, EnvironmentAuthorizationError]), +}); + +const WsWorkflowsAnswerRpc = Rpc.make(WS_METHODS.workflowsAnswer, { + payload: WorkflowAnswerInput, + error: Schema.Union([WorkflowRequestError, EnvironmentAuthorizationError]), +}); + +const WsWorkflowsResumeRpc = Rpc.make(WS_METHODS.workflowsResume, { + payload: WorkflowRunResumeInput, + error: Schema.Union([WorkflowRequestError, EnvironmentAuthorizationError]), +}); + +const WsWorkflowsCancelRpc = Rpc.make(WS_METHODS.workflowsCancel, { + payload: WorkflowRunCancelInput, + error: Schema.Union([WorkflowRequestError, EnvironmentAuthorizationError]), +}); + +const WsWorkflowsGetDefinitionRpc = Rpc.make(WS_METHODS.workflowsGetDefinition, { + payload: WorkflowDefinitionGetInput, + success: WorkflowDefinitionFiles, + error: EnvironmentAuthorizationError, +}); + +const WsWorkflowsSaveDefinitionRpc = Rpc.make(WS_METHODS.workflowsSaveDefinition, { + payload: WorkflowDefinitionSaveInput, + success: WorkflowDefinitionChangeResult, + error: EnvironmentAuthorizationError, +}); + +const WsWorkflowsDeleteDefinitionRpc = Rpc.make(WS_METHODS.workflowsDeleteDefinition, { + payload: WorkflowDefinitionDeleteInput, + success: WorkflowDefinitionChangeResult, + error: EnvironmentAuthorizationError, +}); + const WsScheduledTasksSubscribeRpc = Rpc.make(WS_METHODS.scheduledTasksSubscribe, { payload: ScheduledTaskListInput, success: ScheduledTaskListResult, @@ -2461,6 +2540,15 @@ export const WsRpcGroup = RpcGroup.make( WsServerGetUsageSummaryRpc, WsServerRefreshUsageRatesRpc, WsServerSignalProcessRpc, + WsWorkflowsSubscribeRpc, + WsWorkflowsCountsRpc, + WsWorkflowsGetRpc, + WsWorkflowsAnswerRpc, + WsWorkflowsResumeRpc, + WsWorkflowsCancelRpc, + WsWorkflowsGetDefinitionRpc, + WsWorkflowsSaveDefinitionRpc, + WsWorkflowsDeleteDefinitionRpc, WsScheduledTasksSubscribeRpc, WsScheduledTasksUpsertRpc, WsScheduledTasksSetEnabledRpc, diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 4538065ee5c50..e7887f88f0369 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -1501,6 +1501,8 @@ export const ServerSettings = Schema.Struct({ * and tasks on another machine; tasks already running there finish. */ linkedEnvironmentsEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), + /** Beta: durable workflows from the workflows folder of the T3 home. Off runs none of them. */ + workflowsEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), /** Beta: Claude and Codex predict the next prompt after completed turns. Codex follows a change at once; open Claude threads after they restart. */ promptSuggestionsEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), sidebarAutoSettleKeepPullRequests: Schema.Boolean.pipe( @@ -1938,6 +1940,7 @@ export const ServerSettingsPatch = Schema.Struct({ hideTaggedThreads: Schema.optionalKey(Schema.Boolean), guestSharingEnabled: Schema.optionalKey(Schema.Boolean), linkedEnvironmentsEnabled: Schema.optionalKey(Schema.Boolean), + workflowsEnabled: Schema.optionalKey(Schema.Boolean), promptSuggestionsEnabled: Schema.optionalKey(Schema.Boolean), backgroundActivity: Schema.optionalKey( Schema.Struct({ diff --git a/packages/contracts/src/workflow.ts b/packages/contracts/src/workflow.ts new file mode 100644 index 0000000000000..cc0d958d1f9ee --- /dev/null +++ b/packages/contracts/src/workflow.ts @@ -0,0 +1,223 @@ +import * as Schema from "effect/Schema"; + +import { IssueRef } from "./issue.ts"; +import { PullRequestRef } from "./pullRequest.ts"; + +export const WorkflowRunStatus = Schema.Literals([ + "running", + "waiting", + "paused", + "completed", + "stopped", + /** Ended by the workflow as not its to do. Lists leave these out unless asked. */ + "skipped", + "cancelled", +]); +export type WorkflowRunStatus = typeof WorkflowRunStatus.Type; + +export const WorkflowRun = Schema.Struct({ + runId: Schema.String, + workflow: Schema.String, + version: Schema.Number, + title: Schema.String, + status: WorkflowRunStatus, + /** Why it is paused, what it waits on, or how it ended. */ + detail: Schema.NullOr(Schema.String), + result: Schema.NullOr(Schema.Json), + /** How many times in a row it has been paused by a failing step. */ + pauses: Schema.Number, + /** Its version is no longer registered, so it cannot go on until that version is back. */ + retired: Schema.Boolean, + /** When a paused run is resumed without anyone asking; null when it waits for a person. */ + resumesAt: Schema.NullOr(Schema.String), + /** The run that invoked this one and waits for it; null for a run started by itself. */ + parentRunId: Schema.NullOr(Schema.String), + /** The step of that run this one was invoked as. */ + parentStep: Schema.NullOr(Schema.String), + startedAt: Schema.String, + updatedAt: Schema.String, + endedAt: Schema.NullOr(Schema.String), +}); +export type WorkflowRun = typeof WorkflowRun.Type; + +export const WorkflowStep = Schema.Struct({ + name: Schema.String, + // A sleep's `detail` is when it wakes, as an ISO time. + kind: Schema.Literals(["step", "wait", "agent", "ask", "sleep"]), + status: Schema.Literals(["running", "completed", "failed"]), + attempts: Schema.Number, + detail: Schema.NullOr(Schema.String), + /** The thread an agent step ran in. */ + threadId: Schema.NullOr(Schema.String), + /** The linked environment that thread is in; null when it is this one. */ + environmentId: Schema.NullOr(Schema.String), + /** What it produced: a step's value, an agent's data or reply, the answer to a question. */ + result: Schema.NullOr(Schema.Json), + /** What an agent said in closing, when its result is data and not that reply. */ + said: Schema.NullOr(Schema.String), + startedAt: Schema.String, + endedAt: Schema.NullOr(Schema.String), +}); +export type WorkflowStep = typeof WorkflowStep.Type; + +/** A question a run asked. Answer it with a signal to its run and name. */ +export const WorkflowQuestion = Schema.Struct({ + runId: Schema.String, + name: Schema.String, + /** What `ask` was given: a title, the choices, and data to lay out. */ + request: Schema.Json, + askedAt: Schema.String, + /** The run's latest agent thread, for talking it through before answering. */ + thread: Schema.NullOr( + Schema.Struct({ threadId: Schema.String, environmentId: Schema.NullOr(Schema.String) }), + ), +}); +export type WorkflowQuestion = typeof WorkflowQuestion.Type; + +/** Where a workflow takes requests. `path` holds the hook's secret. */ +export const WorkflowHook = Schema.Struct({ + workflow: Schema.String, + name: Schema.String, + path: Schema.String, +}); +export type WorkflowHook = typeof WorkflowHook.Type; + +/** What a client shows of workflows: recent runs, newest first, and the questions still open. */ +/** A workflow this server has registered, at its newest version, and what starts it. */ +export const WorkflowSummary = Schema.Struct({ + name: Schema.String, + version: Schema.Number, + /** In words: "every 1h", "daily at 09:00", "webhook issues". Empty when only started by hand. */ + triggers: Schema.Array(Schema.String), +}); +export type WorkflowSummary = typeof WorkflowSummary.Type; + +/** Something wrong with the definitions: in `file` when it is one file's, at `line` when it names one. */ +export const WorkflowDefinitionProblem = Schema.Struct({ + message: Schema.String, + file: Schema.optional(Schema.String), + line: Schema.optional(Schema.Number), +}); +export type WorkflowDefinitionProblem = typeof WorkflowDefinitionProblem.Type; + +/** Which loading of the definitions file is running, and what is wrong with the file now. */ +export const WorkflowDefinitionState = Schema.Struct({ + /** Goes up whenever the file is loaded or found wrong, so a client knows to read it again. */ + revision: Schema.Number, + /** Why the file on disk is not what runs. The last version that loaded keeps running. */ + problem: Schema.NullOr(Schema.String), +}); + +export const WorkflowDefinitionFile = Schema.Struct({ + name: Schema.String, + /** The file as it is on disk, which is not what runs while it has problems. */ + source: Schema.String, + /** The workflows its last good version defines, each as `name@version`. */ + workflows: Schema.Array(Schema.String), + problems: Schema.Array(WorkflowDefinitionProblem), +}); +export type WorkflowDefinitionFile = typeof WorkflowDefinitionFile.Type; + +/** The files that define this server's workflows. */ +export const WorkflowDefinitionFiles = Schema.Struct({ + /** The folder the files are in. */ + directory: Schema.String, + /** The server was pointed at one file: no file can be added beside it or taken away. */ + single: Schema.Boolean, + files: Schema.Array(WorkflowDefinitionFile), + /** What is wrong between files, such as one workflow defined in two of them. */ + problems: Schema.Array(WorkflowDefinitionProblem), + ...WorkflowDefinitionState.fields, +}); +export type WorkflowDefinitionFiles = typeof WorkflowDefinitionFiles.Type; + +export const WorkflowDefinitionGetInput = Schema.Struct({}); +/** A file by its name in the folder. Saving a name that is not there yet makes the file. */ +export const WorkflowDefinitionSaveInput = Schema.Struct({ + name: Schema.String, + source: Schema.String, +}); +export const WorkflowDefinitionDeleteInput = Schema.Struct({ name: Schema.String }); +export const WorkflowDefinitionChangeResult = Schema.Struct({ + /** The file was written or deleted. */ + changed: Schema.Boolean, + /** Empty when the change is what runs now. With `changed`, why it does not run yet. */ + problems: Schema.Array(WorkflowDefinitionProblem), +}); +export type WorkflowDefinitionChangeResult = typeof WorkflowDefinitionChangeResult.Type; + +export const WorkflowRunsSnapshot = Schema.Struct({ + workflows: Schema.Array(WorkflowSummary), + runs: Schema.Array(WorkflowRun), + questions: Schema.Array(WorkflowQuestion), + definition: Schema.optional(WorkflowDefinitionState), +}); + +/** How much is going on, for a badge that must not cost a list of runs to keep current. */ +export const WorkflowCounts = Schema.Struct({ + /** Open questions and paused runs: what waits on a person. */ + needsYou: Schema.Number, + /** Runs that have not ended. */ + active: Schema.Number, + /** Runs there have ever been, so a client knows whether workflows are in use at all. */ + total: Schema.Number, +}); +export type WorkflowCounts = typeof WorkflowCounts.Type; +export type WorkflowRunsSnapshot = typeof WorkflowRunsSnapshot.Type; + +export const WorkflowRunsSubscribeInput = Schema.Struct({}); + +export const WorkflowRunGetInput = Schema.Struct({ runId: Schema.String }); + +/** + * Something a run touched: an issue, a pull request, or a kind added later. `kind` is open, so a + * client shows a kind it does not know by its title and `url`. `key` is the thing's identity in + * its kind; `address` is whatever that kind needs to open it. + */ +export const WorkflowRunReference = Schema.Struct({ + kind: Schema.String, + key: Schema.String, + address: Schema.Json, + /** Empty until something that touched it knew its title. */ + title: Schema.String, + url: Schema.NullOr(Schema.String), + /** A word for where it stands, such as `open`, `merged` or `closed`. */ + state: Schema.NullOr(Schema.String), + /** The steps that touched it, in the order they first did. */ + steps: Schema.Array(Schema.String), + origin: Schema.Literals(["trigger", "step"]), +}); +export type WorkflowRunReference = typeof WorkflowRunReference.Type; + +/** The kinds of reference runs record today; `address` is an `IssueRef` or a `PullRequestRef`. */ +export const WorkflowReferenceKind = { issue: "issue", pullRequest: "pullRequest" } as const; +export const WorkflowIssueAddress = IssueRef; +export const WorkflowPullRequestAddress = PullRequestRef; + +/** One run with its steps, in the order they started, and what it touched. */ +export const WorkflowRunDetail = Schema.Struct({ + run: WorkflowRun, + steps: Schema.Array(WorkflowStep), + references: Schema.Array(WorkflowRunReference), +}); +export type WorkflowRunDetail = typeof WorkflowRunDetail.Type; + +/** A person's answer to a `WorkflowQuestion`: one of its choices and, if they gave one, why. */ +export const WorkflowAnswerInput = Schema.Struct({ + runId: Schema.String, + name: Schema.String, + choice: Schema.String, + reason: Schema.optional(Schema.String), +}); + +export const WorkflowRunResumeInput = Schema.Struct({ runId: Schema.String }); + +export const WorkflowRunCancelInput = Schema.Struct({ + runId: Schema.String, + reason: Schema.optional(Schema.String), +}); + +export class WorkflowRequestError extends Schema.TaggedError()( + "WorkflowRequestError", + { message: Schema.String }, +) {} diff --git a/packages/shared/src/nodeSqliteClient.test.ts b/packages/shared/src/nodeSqliteClient.test.ts index 24910bc0bf9cf..71a9897b841f3 100644 --- a/packages/shared/src/nodeSqliteClient.test.ts +++ b/packages/shared/src/nodeSqliteClient.test.ts @@ -148,6 +148,23 @@ layer("NodeSqliteClient", (it) => { const largeText = "x".repeat(64 * 1024 + 1); +it.effect("a rowid above 2^53 does not leave a transaction open", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql`CREATE TABLE big (id INTEGER PRIMARY KEY, name TEXT)`; + yield* sql`INSERT INTO big (id, name) VALUES (246166233861328896, 'first')`; + // BEGIN reports the connection's last insert rowid; a failure to convert it must not + // read as a failed BEGIN, or the open transaction is never rolled back. + yield* sql.withTransaction(sql`INSERT INTO big (name) VALUES ('second')`); + yield* sql.withTransaction(sql`UPDATE big SET name = 'third' WHERE name = 'second'`); + const rows = yield* sql<{ name: string }>`SELECT name FROM big ORDER BY id`; + assert.deepStrictEqual( + rows.map((row) => row.name), + ["first", "third"], + ); + }).pipe(Effect.provide(SqliteClient.layer({ filename: ":memory:" }))), +); + it.effect("reads integers on the values path as the caller asked, cached or not", () => Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; diff --git a/packages/shared/src/nodeSqliteClient.ts b/packages/shared/src/nodeSqliteClient.ts index da521a7c6036d..bb00de7459816 100644 --- a/packages/shared/src/nodeSqliteClient.ts +++ b/packages/shared/src/nodeSqliteClient.ts @@ -286,6 +286,8 @@ parentPort.on("message", (request) => { if (pendingBatch) Atomics.wait(received, 0, 0); parentPort.postMessage({ id, rows }); } else { + // A discarded result is read as BigInt: see the same line in the in-process client. + if (!raw) statement.setReadBigInts(true); const result = statement.run(...params); parentPort.postMessage({ id, rows: raw ? result : [] }); } @@ -854,6 +856,10 @@ const make = Effect.fn("makeWithDatabase")(function* ( if (arrays) statement.setReturnArrays(true); result = Exit.succeed(statement.all(...(params as any))); } else { + // `run` reports the connection's last insert rowid even for BEGIN. One above 2^53 + // throws on conversion after the statement already took effect, so a discarded + // result is read as BigInt. + if (mode !== "raw") statement.setReadBigInts(true); const value = statement.run(...(params as any)); result = Exit.succeed( mode === "raw" ? (value as unknown as ReadonlyArray) : [], diff --git a/packages/shared/src/t3McpToolPresentation.ts b/packages/shared/src/t3McpToolPresentation.ts index fc2af2e05cc37..860f28c44f0a1 100644 --- a/packages/shared/src/t3McpToolPresentation.ts +++ b/packages/shared/src/t3McpToolPresentation.ts @@ -359,6 +359,7 @@ const T3_MCP_TOOLS: Readonly> = { ["Handle", "Handling", "Handled", "pending questions"], "question-respond", ), + t3_workflow: tool(["Use", "Using", "Used", "workflow runs"], "thread-send"), t3_submit_output: tool(["Submit", "Submitting", "Submitted", "the result"], "thread-send"), t3_queue_list: tool(["List", "Listing", "Listed", "queued messages"], "queue-list"), t3_queue_read: tool(["Read", "Reading", "Read", "a queued message"], "queue-read"), diff --git a/skills/t3-workflows/SKILL.md b/skills/t3-workflows/SKILL.md new file mode 100644 index 0000000000000..7f600e0b4cee5 --- /dev/null +++ b/skills/t3-workflows/SKILL.md @@ -0,0 +1,353 @@ +--- +name: t3-workflows +description: Author, edit, run, and debug durable T3 Code workflows (`~/.t3/workflows/*.ts`). Use when asked to build or change a multi-step T3 Code automation tying together agent threads, code steps, schedules, webhooks, issue/PR trackers, or human approvals, or to inspect, resume, signal, or cancel workflow runs. +--- + +# T3 Code workflows + +A workflow is a TypeScript function the T3 Code server runs durably on Effect v4 (`effect/workflow`). Every step's result is stored, so restarts replay to where the run left off and a failing step pauses the run instead of losing it. Runs can sleep for days, wait on signals or pull requests, ask a person a question, and launch agents in ordinary threads. + +Use a workflow for multi-stage work that must not be lost or repeated (triage → fix → verify, nightly reports, webhook reactions). For a single prompt on a timer, use a scheduled task instead. + +## Quick start + +Workflows are a Labs feature, off by default. If `t3 workflow` says workflows are off, ask the user to turn them on in Settings → Labs → Workflows; do not edit their settings yourself. + +Put a `.ts` file in `~/.t3/workflows/` (the `workflows` folder of T3 home, or the path in `T3CODE_WORKFLOWS`). Once workflows are on, the server watches the folder and reloads files automatically—nothing to restart. A file name with a space or other unusual character (`fix issue.ts`) is skipped with a warning in the server log: use letters, digits, `-`, `_` and `.`. Files run with Node's type stripping, so only erasable TypeScript works: no `enum`, `namespace` or parameter properties. + +Workflow files import nothing from T3 or Effect. `T3`, `Effect`, `Schema`, `Option`, `Duration`, and `Schedule` are injected as globals. Never `import` from `effect` (that loads a second runtime copy the engine cannot run). Node built-ins (`node:fs`, `node:crypto`) can be imported normally. + +```ts +const { workflow, agent, ask, stop, title, every, Tick } = T3; + +workflow( + "dependency-report", + { version: 1, payload: Tick, triggers: [every("1 day")] }, + Effect.fn(function* (tick) { + yield* title(`Dependencies ${tick.scheduledAt.slice(0, 10)}`); + + const audit = yield* agent("audit", { + project: "/home/me/app", // the project's folder, or its id + brief: "List this repository's outdated dependencies. Do not change any file.", + returns: Schema.Struct({ + outdated: Schema.Array(Schema.Struct({ name: Schema.String, latest: Schema.String })), + }), + }); + if (audit.value.outdated.length === 0) return yield* stop("nothing is outdated"); + + const answer = yield* ask("approve-upgrade", { + title: `Upgrade ${audit.value.outdated.length} dependencies?`, + choices: ["upgrade", "skip"], + data: audit.value, + timeout: "2 days", + }); + if (Option.isNone(answer) || answer.value.choice === "skip") { + return yield* stop("not approved"); + } + + yield* agent("upgrade", { + thread: audit.thread, + brief: "Upgrade the dependencies you listed, run the tests, and say what changed.", + }); + }), +); +``` + +### What `T3` holds + +Only `T3`, `Effect`, `Schema`, `Option`, `Duration` and `Schedule` are globals. Everything below is a +property of `T3`: take what you use at the top of the file, as the quick start does +(`const { workflow, step, daily } = T3;`), or write `T3.step(…)` in full. A bare `daily(…)` or +`step(…)` without that line is a `ReferenceError`. + +- **Definitions & body**: `workflow`, `step`, `agent`, `ask`, `wait`, `sleep`, `title`, `stop`, `skip`, `invoke` +- **Inside `step` / `onEnd` only**: `store`, `signal`, `signalAll`, `start`, `runs`, `cancel` +- **Trackers & hosts**: `issues`, `pullRequests` (triggers, step calls, and `pullRequests.wait` in the body) +- **Triggers**: `every`, `daily`, `webhook` +- **Schemas**: `Tick`, `WebhookRequest`, `Issue`, `IssueDetail`, `PullRequest`, `PullRequestStanding` + +### Effect v4 `Schema` cheatsheet + +```ts +Schema.String; +Schema.Number; +Schema.Boolean; +Schema.Void; +Schema.Null; +Schema.Struct({ name: Schema.String, count: Schema.optional(Schema.Number) }); +Schema.Array(Schema.String); +Schema.Literals(["open", "closed"]); +Schema.NullOr(Schema.String); +Schema.Record(Schema.String, Schema.Number); // two arguments, not an object +``` + +## Defining a workflow + +`workflow(name, options, body)` registers a workflow and returns a handle you can pass to `invoke`, `start`, `runs`, or `signal`. Each `(name, version)` pair must be unique across all files. + +| Option | Required | Meaning | +| ------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `version` | Yes | Integer version. Raise it whenever the body changes (see rules below). | +| `payload` | Yes | `Schema` of the run's input. | +| `returns` | No | `Schema` of the body's return value. If omitted, any JSON value (or `undefined`) is accepted. | +| `triggers` | No | Array of triggers that start runs automatically. | +| `resumeAfter` | No | Durations to wait before auto-resuming a paused run. Defaults to `["5 minutes", "20 minutes", "80 minutes"]`. The server checks about every 15 seconds, so shorter waits act as 15 seconds. | +| `onEnd` | No | `(payload, { id, outcome, reason }) => Effect`: cleanup hook run once when the run ends. | + +The body is `Effect.fn(function* (payload, run) { … })`, where `run.id` is the run's id. Use `yield*` on every primitive. + +### Cleanup with `onEnd` + +`onEnd` runs once when a run completes, stops, is skipped, or is cancelled—not when it pauses. It runs with step services (`store`, `signal`, `issues`, etc.), receives `(payload, { id, outcome, reason })`, and cannot see local variables from the body. Name external resources after `run.id`, and make `onEnd` safe if the run was cancelled before acquiring anything. + +```ts +const { workflow, step, agent, Issue } = T3; + +workflow( + "fix", + { + version: 1, + payload: Issue, + onEnd: (issue, end) => exec("machines.sh", ["delete", `fix-${end.id}`]), + }, + Effect.fn(function* (issue, run) { + const environment = yield* step( + "machine", + { returns: Schema.String }, + exec("machines.sh", ["create-and-link", `fix-${run.id}`]), + ); + yield* agent("fix", { environment, project: "/home/user/app", brief: issue.title }); + }), +); +``` + +(`exec` above is your own Effect helper, not part of `T3`.) On normal end, `onEnd` retries 3 times before pausing at the `onEnd` step; on cancel, it waits for any in-flight step to finish, then tries up to 5 times, 5 minutes, 20 minutes, 80 minutes and 5 hours apart. The workflow version stays required until one try succeeds; after the last failed try the `onEnd` step stays `failed` on the run and nothing retries it, so make cleanup something a person can redo by hand. + +## Body primitives + +Call these directly in the workflow body with `yield*`. Every named primitive stores its result under `name`, which must be unique across all primitives in the run (an `ask("fix", …)` and `agent("fix", …)` collide). + +| Call | Behavior | Returns | +| -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------- | +| `step(name, { returns, retry? }, effect)` | Runs code once per run and journals the result. Failure pauses the run. | `A` | +| `step.try(name, { returns, retry? }, effect)` | Same as `step`, but returns failure as data instead of pausing. | `{ outcome: "done", value }` or `{ outcome: "failed", reason }` | +| `agent(name, { brief, project? \| thread?, returns?, … })` | Runs an agent in a thread. Failure pauses the run for a person. | `{ value, thread }` (`value` matches `returns`, or last reply string) | +| `agent.try(name, { brief, project? \| thread?, returns?, … })` | Same as `agent`, but returns failure as data instead of pausing. | `{ outcome: "done", value, thread }` or `{ outcome: "failed", reason, thread? }` | +| `ask(name, { title, choices, data?, timeout? })` | Puts a multiple-choice question to a person. | `Option<{ choice, reason? }>` (`None` on timeout) | +| `wait(name, { returns, timeout?, channel? })` | Sleeps until signalled by `{ runId, wait }` or `{ workflow, channel }`. | `Option` (`None` on timeout) | +| `pullRequests.wait(name, pr, { until, timeout? })` | Sleeps until PR checks settle, or the PR merges or closes. | `Option` (`None` on timeout) | +| `sleep(name, duration)` | Durable sleep across restarts (e.g. `"1 hour"`, `"2 days"`). | `void` | +| `invoke(name, workflow, payload, { key? })` | Runs another workflow as a child run and waits for it to end. | `{ outcome: "completed", value }` or `{ outcome: "stopped" \| "skipped" \| "cancelled", reason }` | +| `title(text)` | Sets the run's display title in lists (cut to 200 characters). Takes no step name. | `void` | +| `stop(reason)` | Ends the run on purpose as `stopped` (not a failure). Body only: inside a `step` it fails the step and pauses the run, and so does `skip`. | `never` | +| `skip(reason)` | Ends the run as `skipped`, which run lists leave out unless asked (`runs()` includes them). | `never` | + +- **Retries and failures:** A `step` runs once by default. For idempotent work, pass `retry: { times: 3, schedule: Schedule.exponential("2 seconds") }`. Nothing in the body can catch a failed `step` or `agent` because the engine pauses the run—use `step.try` or `agent.try` whenever the workflow should branch on failure. +- **Timeouts are checked about every 15 seconds:** a `wait` or `ask` timeout can end up to 15 seconds late, and a signal that arrives before the check still wins. +- **`Option` results:** `wait`, `ask` and `pullRequests.wait` always give an `Option`, with or without a `timeout`. Check `Option.isNone(result)` first, then read `result.value`. Never put the `Option` itself into a string or a return value. +- **Concurrency:** Run steps or agents in parallel with `Effect.all([agent("a", …), agent("b", …)], { concurrency: 2 })`. +- **Strict options:** Every call refuses an option it does not take, naming the ones it does, since workflow files are not type-checked. So does `every` under a minute and a `daily` time it cannot read. + +## Agents (`agent` and `agent.try`) + +| Option | Applies to | Meaning | +| ----------------- | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | +| `brief` | All | Full task instructions. The agent sees only this brief and its project. | +| `project` | New thread | Project id (from `t3_project_list`) or absolute folder path. | +| `thread` | Continue | `thread` returned by an earlier `agent` step. Continues it as it started, so the New thread options are refused alongside it. | +| `returns` | All | Optional `Schema`. Completes only when the agent submits valid data (up to 2 correction prompts). | +| `model` | New thread | `{ instanceId, model, options? }`; `options` is `[{ id, value }]` (e.g. `[{ id: "reasoningEffort", value: "high" }]`). Defaults to project default. | +| `workspace` | New thread | `{ type: "root" }` (default) or `{ type: "worktree", baseRef: "origin/main", startFromOrigin: true }`. | +| `runtimeMode` | New thread | `"full-access" \| "auto" \| "auto-accept-edits" \| "approval-required"` (waits on thread approvals). Project default if omitted. | +| `interactionMode` | New thread | `"default" \| "plan"`. | +| `title` | New thread | Thread title. Defaults to `: `. | +| `environment` | New thread | Linked environment id (`t3 environment list`). Folder paths not yet registered there are registered automatically. | +| `issue` | Local only | `Issue` or `{ project, url }`. Links the thread to that issue (not applied in linked environments). | +| `timeout` | All | Time limit for each attempt (e.g. `"2 hours"`); an automatic retry or a resume starts a new one. Past it, the turn is stopped and the step fails. | +| `quiet` | All | Idle grace period (e.g. `"45 minutes"`) for agents that wait across turns before submitting `returns`. | + +- **Worktrees:** Use a `worktree` workspace whenever two agents can edit the same repo at once (concurrent runs or parallel `agent` calls). +- **Waiting across turns (`quiet`):** If an agent watches PR checks or background work and ends its turn while waiting to be woken, set `quiet: "45 minutes"` and tell it in `brief` to end waiting turns without submitting. The step prompts for the result only after the thread has been idle for `quiet`. Without `quiet`, it prompts as soon as a turn ends without output. Always set a `timeout` alongside `quiet`. +- **Retries and pauses:** If a turn dies (crashes or is cut off), `agent` automatically tries once more (on a fresh thread, or the same thread if continuing `thread`). An agent that finishes its turn without valid `returns` is asked to correct it twice in the same thread, and then gives up without starting the job again. A timeout or manual stop does not auto-retry. A run paused by an agent that ran and gave up or timed out waits for a person—`resumeAfter` does not auto-resume it (`t3 workflow resume` starts a fresh attempt). An agent that could not be started at all (no project at that folder, linked environment unreachable) pauses like a failed `step` and resumes on its own; `agent.try` returns that failure as data instead. +- **Fallback with `agent.try`:** + +```ts +Effect.fn(function* () { + let fix = yield* agent.try("fix", { project, brief, returns: Fix, timeout: "2 hours" }); + if (fix.outcome === "failed") { + fix = yield* agent.try("fix-again", { project, brief, returns: Fix, model: stronger }); + } + if (fix.outcome === "failed") return yield* stop(`no fix: ${fix.reason}`); +}); +``` + +- **Linked environments:** Enable Settings → Labs → Linked environments. The run stays on this server; only the thread runs remotely, bounded by the link's paired access. For a machine per run, create and link it in a `step` (`t3 auth pairing create --json` on the remote, `t3 environment link --pairing-code --access ` here), return its id, and delete it in `onEnd`. + +## Other workflows + +Define caller and callee in the same file and keep the callee in a variable so its payload and return type flow through: + +```ts +const { workflow, invoke, stop } = T3; + +const review = workflow("review", { version: 1, payload: Change, returns: Verdict }, reviewBody); + +workflow( + "fix", + { version: 1, payload: Issue }, + Effect.fn(function* (issue) { + const ended = yield* invoke("review", review, { branch: `fix/${issue.key}` }); + if (ended.outcome !== "completed") { + return yield* stop(`review ${ended.outcome}: ${ended.reason}`); + } + return ended.value; // Verdict + }), +); +``` + +| Call | Where | Behavior | +| ------------------------------------------- | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `invoke(name, workflow, payload, { key? })` | Body | Starts a child run and waits for it (including while it is paused). Listed and resumed independently; cancelling the parent cancels the child. Pass the definition `workflow(…)` returned, not its name. `key` names the child run; one already started under that key by something else is refused. | +| `start(workflow, payload, { key })` | `step` / `onEnd` | Fire-and-forget. Returns `{ runId }`. Same `key` returns the same run. Use for fan-out. | +| `runs({ workflow?, status?, keyPrefix? })` | `step` / `onEnd` | Lists up to 500 matching runs (skipped runs included), newest first: `{ id, workflow, key, title, status, detail, startedAt, endedAt }`. `workflow` is a definition or its name. | +| `cancel(runId, reason)` | `step` / `onEnd` | Cancels another run (stops agents, withdraws questions, cancels invoked children, runs `onEnd`). Cannot cancel self—use `stop`. | + +End subject keys with a separator (e.g. `issue/412/`), so `runs({ workflow: fix, keyPrefix: "issue/412/" })` does not match `issue/4120`. + +## Store and signals + +`store` holds durable key-value state shared across all workflows on the server (cursors, switches, counters, queues). Call `store`, `signal`, and `signalAll` **only inside `step` or `onEnd`**—never directly in the body. + +| Call | Behavior | +| ------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `store.entry(key, Schema)` | Handle for one key: `.get` (`Option`), `.set(value)`, `.delete`. | +| `entry.update((current) => next)` | Atomic read-modify-write; `current` is `Option`. Return `undefined` to delete. Returns `Option`. | +| `store.entries(prefix, Schema)` | Every `{ key, value }` starting with `prefix`, in key order. Fails if any matching row does not fit `Schema`. | +| `store.transaction(effect)` | Runs all store reads and writes in `effect` atomically (all or nothing). | +| `signal(address, value, { id?, ttl? })` | Wakes one `wait` at `{ runId, wait }` or `{ workflow, channel }`. Buffered until a wait opens or `ttl` (default 7 days) expires. Returns `"delivered" \| "buffered"`. `"buffered"` checks neither the address nor the shape: a wrong workflow or wait name, or a run that has ended, also buffers. A value that does not fit an open wait fails the sending step. | +| `signalAll({ channel, workflow? }, value)` | Wakes every run currently waiting on `channel` (one workflow or all). Returns count woken. Buffers nothing. | + +```ts +const { step, store, Issue } = T3; +const seen = store.entry("issues/seen", Schema.String); + +Effect.fn(function* () { + const fresh = yield* step( + "fetch", + { returns: Schema.Array(Issue) }, + Effect.gen(function* () { + const since = yield* seen.get; + const batch = yield* fetchIssuesAfter(Option.getOrUndefined(since)); + if (batch[0]) yield* seen.set(batch[0].createdAt); + return batch; + }), + ); +}); +``` + +- **Shared gate pattern (`signalAll`):** Because `signalAll` keeps nothing for late arrivals, check the switch in a `step`, then while it is on call `wait` with `{ channel: "main-green", timeout: "10 minutes", returns: Schema.Null }` and re-check in a loop. Number step names per iteration (`switch/1`, `released/1`, `switch/2`, `released/2`). Whoever clears the switch calls `signalAll({ channel: "main-green" }, null)`. +- **Transactions:** Use `entry.update` or `store.transaction` whenever a write depends on a read, or when a step might fail after writing. +- **CLI access:** Inspect or flip keys with `t3 workflow store list [prefix]`, `store set ''`, and `store delete `. + +## Issues and pull requests + +Reads and writes the project's configured tracker (GitHub, GitLab, Linear, etc.) and git host using the project's credentials. Pass an issue/PR object from a trigger or `list`, or `{ project, url }` (useful when an agent returns a URL). + +| Call | Where | Returns | +| ----------------------------------------------------------------------------- | ---------------- | ---------------------------------------------------------------------- | +| `issues.list({ project, state?, labels?, query?, assignee?, sort?, limit? })` | `step` / `onEnd` | `Issue[]` (`state` defaults to `"open"`) | +| `issues.read(issue)` | `step` / `onEnd` | `IssueDetail` (body, comments, valid `states`) | +| `issues.comment(issue, body)` | `step` / `onEnd` | `void` | +| `issues.setState(issue, name)` | `step` / `onEnd` | `void` (`name` from `issues.read(issue).states`) | +| `issues.create({ project, title, body?, labels?, assignees? })` | `step` / `onEnd` | `{ key, displayKey, url }` | +| `pullRequests.list({ project, state?, query?, limit? })` | `step` / `onEnd` | `PullRequest[]` (`state` defaults to `"open"`) | +| `pullRequests.read(pr)` | `step` / `onEnd` | State, checks, reviews, mergeability | +| `pullRequests.comment(pr, body)` | `step` / `onEnd` | `void` | +| `pullRequests.act(pr, action, { mergeMethod? })` | `step` / `onEnd` | `void` (`merge`, `close`, `ready`, `update-branch`, etc.) | +| `pullRequests.wait(name, pr, { until, timeout? })` | **Body** | `Option` (`{ state, checks, mergeability, url }`) | + +Keep one comment or mutation per `step` so a retry does not post twice. + +```ts +const { workflow, title, agent, step, issues, Issue } = T3; + +workflow( + "triage", + { version: 1, payload: Issue, triggers: [issues.opened({ project: "/home/me/app" })] }, + Effect.fn(function* (issue) { + yield* title(`${issue.displayKey} ${issue.title}`); + const found = yield* agent("reproduce", { + project: "/home/me/app", + issue, + brief: `Reproduce this on main. Change nothing.\n\n${issue.url}`, + returns: Schema.Struct({ reproduced: Schema.Boolean, summary: Schema.String }), + }); + yield* step("report", { returns: Schema.Void }, issues.comment(issue, found.value.summary)); + }), +); +``` + +`pullRequests.wait` polls about once a minute. `until` is `"checks"` (no checks still pending), `"merged"`, or `"closed"`. Merging or closing ends any wait, so always check `state` before `checks` (`"passing" | "failing" | "pending" | "none"`): + +```ts +Effect.fn(function* () { + const at = yield* pullRequests.wait( + "checks", + { project, url }, + { until: "checks", timeout: "2 hours" }, + ); + if (Option.isNone(at) || at.value.state !== "open" || at.value.checks !== "passing") { + return yield* stop("not ready to merge"); + } + yield* step("merge", { returns: Schema.Void }, pullRequests.act({ project, url }, "merge")); +}); +``` + +## Triggers + +A workflow's `payload` schema must match what its `triggers` emit. + +| Trigger | Payload | Notes | +| ------------------------------------------------ | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `every("1 hour")` | `Tick` | `{ scheduledAt }`. Minimum 1 minute. The first run comes one interval after the file loads, not at load. Downtime collapses into one run, not one per missed interval. | +| `daily("09:00", { weekdays?: [1, 2, 3, 4, 5] })` | `Tick` | Server local time; `0` is Sunday. Missed by more than 10 minutes is skipped. | +| `webhook("name", { key? })` | `WebhookRequest` | `{ method, headers, query, body }` (lowercase header names, text `query`/`body`). Set `payload: WebhookRequest`, taken from `T3`; never write its shape out yourself. `t3 workflow hooks` prints URL paths (includes secret). A retry that repeats a delivery header (`X-GitHub-Delivery`, `Idempotency-Key`, `webhook-id`, and the Gitea, GitLab and Linear ones) starts no second run; for other senders, `key: (r) => …` names the run from the request. Bodies over 1 MiB are refused. | +| `issues.opened({ project, labels?, query? })` | `Issue` | Polls ~once a minute. Only issues opened after the workflow first loaded. Issue must carry all `labels`. | +| `pullRequests.opened({ project, query? })` | `PullRequest` | Polls ~once a minute. Only pull requests opened after the workflow first loaded. | + +Filter unwanted deliveries in the body with `skip("not a push to main")` so they stay out of run lists. Verify webhook signatures inside a `step`. + +Start any workflow manually with `t3 workflow start --input '' --key `. A `key` identifies one run of that workflow across all versions. + +## Rules you must not break + +1. **The body is replayed from the top.** After every wait or restart, the body runs again and completed primitives return their stored values. Put all side effects, I/O, clock reads, randomness, and `store`/API reads inside `step` or `agent`. Code between calls must be deterministic given `payload` and earlier results. +2. **Names are journal keys.** Every named primitive (`step`, `agent`, `ask`, `wait`, `sleep`, `invoke`, `pullRequests.wait`) must have a unique name within the run, across all kinds. Loops need distinct names (``step(`check-${i}`, …)``). Never name a body step `"onEnd"` (reserved for cleanup). `invoke("x", …)` also takes `x/start`, and `title(…)` takes `title/0`, `title/1`, …. +3. **Bump `version` when changing a live workflow.** Do not reorder, rename, or change the stored schema of steps in a version that still has unfinished runs. Register the updated body under a higher `version` and keep the old version in the file until its runs finish. Runs started by the CLI, a trigger or a webhook use the highest version; `start` and `invoke` run the version of the definition you pass them, so point callers at the new definition when you bump. Keys still deduplicate across versions. +4. **Never import `effect`, and take every `T3` name you use.** The globals are `T3`, `Effect`, `Schema`, `Option`, `Duration` and `Schedule`; `step`, `daily`, `WebhookRequest` and the rest come from `const { … } = T3;` at the top of the file, and one left out of that line is a `ReferenceError`. Shared helpers go in a subfolder (dotfiles and folders are ignored by the loader), and changing an imported helper requires a server restart. +5. **Payloads and step results must fit their `Schema`.** Everything journaled is serialized as JSON; a value that fails encoding fails the step. +6. **Steps can run more than once.** A crash mid-step, a retry, or a manual resume re-runs the step. Make external side effects idempotent (derive idempotency keys from `payload` or `run.id`, keep one comment/post per step, wrap dependent store writes in `store.transaction`). + +## Files, reloading, and CLI + +If an edited file fails to load, its last good version keeps running and the server logs `A workflow definitions file was not loaded` with the reason. A change that defines the same `(name, version)` twice or removes a version with unfinished runs is rejected. The Workflows page shows these errors, and its Definitions view validates files on save. + +```sh +t3 workflow start --input '' --key +t3 workflow list [--status paused] +t3 workflow show [--json] +t3 workflow resume +t3 workflow cancel [--reason ''] +t3 workflow questions +t3 workflow signal '{"choice":"upgrade"}' --run --wait approve-upgrade +t3 workflow signal '' --workflow --channel +t3 workflow hooks +t3 workflow store list [prefix] +t3 workflow store set '' +t3 workflow store delete +``` + +- **Run states:** `running`, `waiting` (agent, signal, question, PR wait, or sleep), `paused` (step failed), `completed`, `stopped`, `skipped`, `cancelled`. +- **Resuming:** Check the failing step and error with `show`, fix the cause, then `resume` (only the failed step re-runs). A paused run also resumes by itself on `resumeAfter` (default 5, 20, 80 minutes), unless it paused because its agent gave up. +- **Retired runs:** A run whose version was removed shows `"retired": true` in `show --json` and cannot continue until that version is restored. +- **Stuck agents:** An agent step's thread is an ordinary thread—open it to inspect or steer the agent. The step finishes as soon as the agent submits its result. From 65d2b4f081694d76a5d335c58132abf28fe6d8c7 Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Mon, 23 Nov 2026 07:28:57 +0530 Subject: [PATCH 236/324] fix(web): center the Connections map zoom controls (#41081) --- apps/web/src/components/settings/EnvironmentsMap.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/settings/EnvironmentsMap.tsx b/apps/web/src/components/settings/EnvironmentsMap.tsx index befa3c5e19b68..5d4b2f96754c8 100644 --- a/apps/web/src/components/settings/EnvironmentsMap.tsx +++ b/apps/web/src/components/settings/EnvironmentsMap.tsx @@ -1044,7 +1044,7 @@ function FleetCanvas({ )}

    {/* Below the canvas, not over it: nothing on the map can end up under the controls. */} -
    +
    0} />
    diff --git a/apps/web/src/components/files/FilePreviewPanel.tsx b/apps/web/src/components/files/FilePreviewPanel.tsx index dbb7f6ec0a33a..2ef4d67095e55 100644 --- a/apps/web/src/components/files/FilePreviewPanel.tsx +++ b/apps/web/src/components/files/FilePreviewPanel.tsx @@ -26,9 +26,7 @@ import { import { useAtomMount, useAtomValue } from "@effect/atom-react"; import { Atom } from "effect/reactivity"; import { - DEFAULT_TOKENIZE_MAX_LENGTH, VirtualizedFile, - getFiletypeFromFileName, type File as FileInstance, type FileContents, type PostRenderPhase, @@ -40,9 +38,9 @@ import { type EditorFactory, type EditorOptions, } from "@pierre/diffs/edit"; -import type { WorkerPoolManager } from "@pierre/diffs/worker"; -import { EditProvider, File, Virtualizer, useWorkerPool } from "@pierre/diffs/react"; +import { EditProvider, File, Virtualizer } from "@pierre/diffs/react"; import { DiffWorkerPoolProvider } from "../DiffWorkerPoolProvider"; +import { useEditableAfterHighlight } from "./useEditableAfterHighlight"; import { useFilesystemReadAccess } from "~/state/filesystem"; import { isAtomCommandInterrupted, @@ -846,43 +844,6 @@ function editableFileContents( }; } -function needsWorkerHighlight(workerPool: WorkerPoolManager | undefined, file: FileContents) { - if (workerPool?.isWorkingPool() !== true) return false; - if ((file.lang ?? getFiletypeFromFileName(file.name)) === "text") return false; - let lines = 1; - for ( - let index = file.contents.indexOf("\n"); - index !== -1; - index = file.contents.indexOf("\n", index + 1) - ) { - lines += 1; - } - return lines <= DEFAULT_TOKENIZE_MAX_LENGTH; -} - -/** Enable editing only after worker highlighting renders; active edit sessions highlight on the main - * thread. */ -function useEditableAfterHighlight(file: FileContents) { - const workerPool = useWorkerPool(); - const [highlightedFile, setHighlightedFile] = useState(null); - const needsHighlight = needsWorkerHighlight(workerPool, file); - const ready = !needsHighlight || highlightedFile === file; - - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- primes the worker pool's highlight cache for this file and falls back to plain text if it fails - useEffect(() => { - if (ready || workerPool === undefined) return; - workerPool.primeFileHighlightCache(file).catch(() => setHighlightedFile(file)); - }, [file, ready, workerPool]); - - const onPostRender = (renderedFile: FileContents | undefined, phase: PostRenderPhase) => { - if (ready || phase === "unmount" || renderedFile?.cacheKey !== file.cacheKey) return; - // Cache results arrive just before instance rendering; seeing the cache during render means rows are - // highlighted. - if (workerPool?.getFileResultCache(file) !== undefined) setHighlightedFile(file); - }; - return { ready, onPostRender }; -} - interface EditableFileSurfaceProps { environmentId: EnvironmentId; projectId?: ProjectId | undefined; diff --git a/apps/web/src/components/files/useEditableAfterHighlight.ts b/apps/web/src/components/files/useEditableAfterHighlight.ts new file mode 100644 index 0000000000000..f91ef979de5c3 --- /dev/null +++ b/apps/web/src/components/files/useEditableAfterHighlight.ts @@ -0,0 +1,46 @@ +import { + DEFAULT_TOKENIZE_MAX_LENGTH, + getFiletypeFromFileName, + type FileContents, + type PostRenderPhase, +} from "@pierre/diffs"; +import { useWorkerPool } from "@pierre/diffs/react"; +import type { WorkerPoolManager } from "@pierre/diffs/worker"; +import { useEffect, useState } from "react"; + +function needsWorkerHighlight(workerPool: WorkerPoolManager | undefined, file: FileContents) { + if (workerPool?.isWorkingPool() !== true) return false; + if ((file.lang ?? getFiletypeFromFileName(file.name)) === "text") return false; + let lines = 1; + for ( + let index = file.contents.indexOf("\n"); + index !== -1; + index = file.contents.indexOf("\n", index + 1) + ) { + lines += 1; + } + return lines <= DEFAULT_TOKENIZE_MAX_LENGTH; +} + +/** Enable editing only after worker highlighting renders; active edit sessions highlight on the main + * thread. */ +export function useEditableAfterHighlight(file: FileContents) { + const workerPool = useWorkerPool(); + const [highlightedFile, setHighlightedFile] = useState(null); + const needsHighlight = needsWorkerHighlight(workerPool, file); + const ready = !needsHighlight || highlightedFile === file; + + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- primes the worker pool's highlight cache for this file and falls back to plain text if it fails + useEffect(() => { + if (ready || workerPool === undefined) return; + workerPool.primeFileHighlightCache(file).catch(() => setHighlightedFile(file)); + }, [file, ready, workerPool]); + + const onPostRender = (renderedFile: FileContents | undefined, phase: PostRenderPhase) => { + if (ready || phase === "unmount" || renderedFile?.cacheKey !== file.cacheKey) return; + // Cache results arrive just before instance rendering; seeing the cache during render means rows are + // highlighted. + if (workerPool?.getFileResultCache(file) !== undefined) setHighlightedFile(file); + }; + return { ready, onPostRender }; +} diff --git a/apps/web/src/components/settings/LabsSettingsPanel.tsx b/apps/web/src/components/settings/LabsSettingsPanel.tsx index e2e33fec8fd75..f6354fb880ea0 100644 --- a/apps/web/src/components/settings/LabsSettingsPanel.tsx +++ b/apps/web/src/components/settings/LabsSettingsPanel.tsx @@ -31,6 +31,7 @@ export function LabsSettingsPanel() { {/* Clerk is only mounted when this build has T3 Connect. */} {hasCloudPublicConfig() ? : } + @@ -194,6 +195,31 @@ function LinkedEnvironmentsRow() { ); } +function WorkflowsRow() { + const searchableSetting = useSearchableSetting(); + const settings = useScopedSettings(); + const updateSettings = useUpdateScopedSettings(); + const gt = useGT(); + return ( + updateSettings({ workflowsEnabled: Boolean(checked) })} + aria-label={gt("Workflows")} + /> + } + /> + ); +} + function PromptSuggestionsRow() { const searchableSetting = useSearchableSetting(); const settings = useScopedSettings(); diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index 4f57b8d730842..1f38ed958d368 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -559,6 +559,13 @@ export const SETTINGS_SEARCH_ITEMS = [ scope: "environment", searchTerms: [msg("beta link another machine vps peer agents work there delegate")], }, + { + id: "workflows-beta", + title: msg("Workflows"), + to: "/settings/labs", + scope: "environment", + searchTerms: [msg("beta workflow durable runs automation steps schedule webhook folder")], + }, { id: "prompt-suggestions-beta", title: msg("Suggest next prompt"), diff --git a/apps/web/src/components/sidebar/mainAppLocation.ts b/apps/web/src/components/sidebar/mainAppLocation.ts index daa18b618a41a..0ef545f76b772 100644 --- a/apps/web/src/components/sidebar/mainAppLocation.ts +++ b/apps/web/src/components/sidebar/mainAppLocation.ts @@ -11,7 +11,10 @@ export function isAppModalPage(pathname: string) { export function isSidebarUtilityPage(pathname: string) { return ( - pathname.startsWith("/projects/") || pathname === "/pull-requests" || pathname === "/issues" + pathname.startsWith("/projects/") || + pathname === "/pull-requests" || + pathname === "/issues" || + pathname === "/workflows" ); } diff --git a/apps/web/src/components/workflows/WorkflowDefinitionEditor.logic.test.ts b/apps/web/src/components/workflows/WorkflowDefinitionEditor.logic.test.ts new file mode 100644 index 0000000000000..736aa4648aaf9 --- /dev/null +++ b/apps/web/src/components/workflows/WorkflowDefinitionEditor.logic.test.ts @@ -0,0 +1,49 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { diskChange, staleAfterSave } from "./WorkflowDefinitionEditor.logic"; + +describe("diskChange", () => { + it.each([ + [ + "a clean editor follows the file", + { source: "B", baseline: "A", dirty: false, saving: null }, + "follow", + ], + [ + "edits over a change are stale", + { source: "B", baseline: "A", dirty: true, saving: null }, + "stale", + ], + [ + "the file it already holds is nothing", + { source: "A", baseline: "A", dirty: true, saving: null }, + "ignore", + ], + [ + "the save's own text is nothing", + { source: "C", baseline: "A", dirty: true, saving: "C" }, + "ignore", + ], + // The disk went A → B → A while C was being saved: back at the baseline, but not what was saved. + [ + "a change back to the baseline during a save is stale", + { source: "A", baseline: "A", dirty: true, saving: "C" }, + "stale", + ], + ] as const)("%s", (_, input, expected) => { + expect(diskChange(input)).toBe(expected); + }); +}); + +describe("staleAfterSave", () => { + it("settles the change the person saved over and keeps a newer one", () => { + const b = { source: "B" }; + expect(staleAfterSave(b, b)).toBeNull(); + const a = { source: "A" }; + expect(staleAfterSave(a, b)).toBe(a); + expect(staleAfterSave(a, null)).toBe(a); + // The disk went B → A → B while the save was out: back at the same text, but a change of its own. + const bAgain = { source: "B" }; + expect(staleAfterSave(bAgain, b)).toBe(bAgain); + }); +}); diff --git a/apps/web/src/components/workflows/WorkflowDefinitionEditor.logic.ts b/apps/web/src/components/workflows/WorkflowDefinitionEditor.logic.ts new file mode 100644 index 0000000000000..c056c6576f061 --- /dev/null +++ b/apps/web/src/components/workflows/WorkflowDefinitionEditor.logic.ts @@ -0,0 +1,23 @@ +/** + * What a new version of the file on disk means for an editor holding `baseline`. A change that + * lands while a save is out is never the save's own unless it is the saved text itself. + */ +export function diskChange(input: { + readonly source: string; + readonly baseline: string; + readonly dirty: boolean; + readonly saving: string | null; +}): "follow" | "stale" | "ignore" { + if (input.saving !== null) return input.source === input.saving ? "ignore" : "stale"; + if (input.source === input.baseline) return "ignore"; + return input.dirty ? "stale" : "follow"; +} + +/** One change on disk the person has not settled. Each change is its own, even with the same text. */ +export interface DiskChange { + readonly source: string; +} + +/** The warning after a save: the change the person saved over is settled, any later one stays. */ +export const staleAfterSave = (now: DiskChange | null, overwrote: DiskChange | null) => + now === overwrote ? null : now; diff --git a/apps/web/src/components/workflows/WorkflowDefinitionEditor.tsx b/apps/web/src/components/workflows/WorkflowDefinitionEditor.tsx new file mode 100644 index 0000000000000..da810dd5c93ac --- /dev/null +++ b/apps/web/src/components/workflows/WorkflowDefinitionEditor.tsx @@ -0,0 +1,575 @@ +import { useAtomValue } from "@effect/atom-react"; +import type { FileContents } from "@pierre/diffs"; +import { Editor, type EditorFactory, type EditorOptions, type Marker } from "@pierre/diffs/edit"; +import { EditProvider, File, Virtualizer } from "@pierre/diffs/react"; +import { type EnvironmentId, type WorkflowDefinitionProblem } from "@t3tools/contracts"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; +import { useBlocker } from "@tanstack/react-router"; +import { T, useGT, Var } from "gt-react"; +import { FileCode2Icon, PlusIcon } from "lucide-react"; +import { useEffect, useRef, useState, type KeyboardEvent } from "react"; +import { createPortal } from "react-dom"; + +import { requestConfirmDialog } from "../../confirmDialog"; +import { useTheme } from "../../hooks/useTheme"; +import { resolveDiffThemeName } from "../../lib/diffRendering"; +import { PREFERRED_HIGHLIGHTER } from "../../lib/syntaxHighlighting"; +import { isMacPlatform } from "../../lib/utils"; +import { useEnvironmentQuery } from "../../state/query"; +import { serverEnvironment } from "../../state/server"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { DiffWorkerPoolProvider } from "../DiffWorkerPoolProvider"; +import { useEditableAfterHighlight } from "../files/useEditableAfterHighlight"; +import { Button } from "../ui/button"; +import { Input } from "../ui/input"; +import { type DiskChange, diskChange, staleAfterSave } from "./WorkflowDefinitionEditor.logic"; +import { WorkflowsEmpty } from "./WorkflowRunsView"; + +type DefinitionEditor = Editor<"file", undefined, undefined>; +const createEditor: EditorFactory = (editorType, options, editStateKey) => + new Editor(editorType, options, editStateKey); + +const fileOf = (path: string, contents: string, revision: number): FileContents => ({ + name: path, + contents, + cacheKey: `workflow-definition:${path}:${revision}:${contents.length}`, +}); + +/** A problem that names a line, as a squiggle under that line. */ +const markersOf = (problems: ReadonlyArray): Array => + problems.flatMap((problem) => + problem.line === undefined + ? [] + : [ + { + start: { line: problem.line - 1, character: 0 }, + end: { line: problem.line - 1, character: Number.MAX_SAFE_INTEGER }, + severity: "error" as const, + message: problem.message, + source: "workflows", + }, + ], + ); + +function ProblemList({ + title, + problems, +}: { + readonly title: string; + readonly problems: ReadonlyArray; +}) { + return ( +
    +

    {title}

    +
      + {problems.map((problem) => ( +
    • + {problem.line === undefined ? null : ( + + + Line {problem.line}: + {" "} + + )} + {problem.message} +
    • + ))} +
    +
    + ); +} + +function Surface({ + environmentId, + name, + path, + source, + revision, + onDisk, + draft, + offline, + onDelete, + onClose, + actions, +}: { + readonly environmentId: EnvironmentId; + readonly name: string; + readonly path: string; + readonly source: string; + readonly revision: number; + /** Why the file on disk is not what runs, when it is not. */ + readonly onDisk: ReadonlyArray; + /** What a file that is not on disk yet starts as. */ + readonly draft?: string; + /** The environment is away: the draft stays, and nothing is sent until it is back. */ + readonly offline: boolean; + /** Take the file away, saying whether it went. Absent where that cannot be done. */ + readonly onDelete?: (() => Promise) | undefined; + /** Leave the file for the list. */ + readonly onClose: () => void; + /** Where in the page's header the file's status and its actions go. */ + readonly actions: HTMLElement | null; +}) { + const { resolvedTheme } = useTheme(); + const gt = useGT(); + const canSave = useAtomValue( + serverEnvironment.saveWorkflowDefinition.permissionAtom(environmentId), + ); + const save = useAtomCommand(serverEnvironment.saveWorkflowDefinition, { + label: "workflow definition save", + }); + // What the draft started from. The file on disk moving past it is someone else's edit. + const [baseline, setBaseline] = useState(source); + // The file as this editor last took note of it, so only a real change on disk is acted on: after + // a save, `source` is still the old text until the server's answer is read again. + const [seen, setSeen] = useState(source); + // The disk text that changed under the person's edits, until they settle it. + const [staleAt, setStaleAt] = useState(null); + const stale = staleAt !== null; + const [shown, setShown] = useState(() => fileOf(path, draft ?? source, revision)); + const [edited, setEdited] = useState(draft ?? null); + const [problems, setProblems] = useState>([]); + // The last save wrote the file, so its problems are why it does not run, not why it was refused. + const [written, setWritten] = useState(false); + const [failure, setFailure] = useState(null); + // The text a save in flight is writing, so its own echo from disk is told from a real change. + const [savingText, setSavingText] = useState(null); + const saving = savingText !== null; + const [savedOnce, setSavedOnce] = useState(false); + const [deleting, setDeleting] = useState(false); + // Set once the file is deleted, so leaving it does not ask about a draft of a file that is gone. + const released = useRef(false); + const [seenRevision, setSeenRevision] = useState(revision); + const editorRef = useRef(null); + const dirty = edited !== null && edited !== baseline; + const adopt = () => { + setBaseline(source); + setShown(fileOf(path, source, revision)); + setEdited(null); + setProblems([]); + setStaleAt(null); + }; + if (source !== seen) { + setSeen(source); + // With nothing of the person's own in the editor, it follows the file. + const change = diskChange({ source, baseline, dirty, saving: savingText }); + if (change === "stale") setStaleAt({ source }); + else if (change === "follow") adopt(); + } + // Why a saved file did not run is old news once the server loads it cleanly. + if (revision !== seenRevision) { + setSeenRevision(revision); + if (written && onDisk.length === 0) setProblems([]); + } + const { ready: editable, onPostRender } = useEditableAfterHighlight(shown); + + const saveNow = async () => { + if (!dirty || saving || deleting || offline || !canSave || edited === null) return; + // Saving over a change on disk that was already shown is a choice. One that lands while this + // save is out is not, and stays shown. + const overwrote = staleAt; + setSavingText(edited); + setFailure(null); + const result = await save({ environmentId, input: { name, source: edited } }); + setSavingText(null); + if (result._tag === "Failure") { + if (!isAtomCommandInterrupted(result)) setFailure(String(squashAtomCommandFailure(result))); + return; + } + setProblems(result.value.problems); + setWritten(result.value.changed); + if (!result.value.changed) return; + setBaseline(edited); + setStaleAt((now) => staleAfterSave(now, overwrote)); + setSavedOnce(true); + }; + const onKeyDown = (event: KeyboardEvent) => { + const mac = isMacPlatform(navigator.platform); + if (event.key.toLowerCase() !== "s" || !(mac ? event.metaKey : event.ctrlKey)) return; + event.preventDefault(); + void saveNow(); + }; + const deleteNow = async () => { + if (onDelete === undefined || deleting || saving) return; + // Busy from the dialog on, so a save cannot slip in while it asks. + setDeleting(true); + const gone = await onDelete(); + setDeleting(false); + if (!gone) return; + released.current = true; + onClose(); + }; + // Leaving with an unsaved draft, by a link in the app or by closing the tab, asks first. + useBlocker({ + shouldBlockFn: async () => + dirty && + !released.current && + !(await (requestConfirmDialog( + gt("Leave without saving? Your changes to this file are lost."), + { + variant: "destructive", + }, + ) ?? Promise.resolve(false))), + enableBeforeUnload: () => dirty && !released.current, + }); + + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- the editor draws markers itself and takes them only through its own method + useEffect(() => { + editorRef.current?.setMarkers(markersOf(problems)); + }, [problems]); + + const editorOptions: EditorOptions<"file", undefined, undefined> = { + onAttach: (editor) => { + editorRef.current = editor; + editor.setMarkers(markersOf(problems)); + }, + onComplete: () => { + editorRef.current = null; + }, + }; + const status = offline + ? gt("Not connected") + : saving + ? gt("Checking…") + : dirty + ? gt("Unsaved changes") + : savedOnce && problems.length === 0 + ? gt("Saved and running") + : null; + + return ( +
    + {actions === null + ? null + : createPortal( + <> + + {canSave || offline ? status : gt("Read-only")} + + {canSave && onDelete !== undefined ? ( + + ) : null} + {canSave ? ( + + ) : null} + , + actions, + )} + {stale ? ( +
    + + The file changed on disk while you were editing. Saving replaces that change. + + +
    + ) : null} + {onDisk.length > 0 && problems.length === 0 ? ( + + ) : null} + {problems.length > 0 ? ( + + ) : null} + {failure === null ? null : ( + + )} + + + setEdited(file.contents)} + options={{ + disableFileHeader: true, + overflow: "scroll", + theme: resolveDiffThemeName(resolvedTheme), + preferredHighlighter: PREFERRED_HIGHLIGHTER, + themeType: resolvedTheme, + onPostRender: (_container, instance, phase) => onPostRender(instance.file, phase), + }} + className="min-h-full" + /> + + +
    + ); +} + +const NEW_FILE = `const { workflow, step, agent, ask, stop } = T3; + +workflow( + "my-workflow", + { version: 1, payload: Schema.Struct({}) }, + Effect.fn(function* () { + // yield* agent("first", { project: "/path/to/project", brief: "What to do." }); + }), +); +`; + +/** + * The files that define this server's workflows: the list of them, or `file` in an editor. A + * `file` the folder does not have yet is a new one, which exists once it is saved. + */ +export default function WorkflowDefinitionEditor({ + environmentId, + file, + away, + onOpen, + actions, +}: { + readonly environmentId: EnvironmentId; + readonly file: string | null; + /** The environment's name while it is not connected. */ + readonly away: string | null; + readonly onOpen: (file: string | null) => void; + readonly actions: HTMLElement | null; +}) { + const query = useEnvironmentQuery( + serverEnvironment.workflowDefinition({ environmentId, input: {} }), + ); + const canChange = useAtomValue( + serverEnvironment.saveWorkflowDefinition.permissionAtom(environmentId), + ); + const remove = useAtomCommand(serverEnvironment.deleteWorkflowDefinition, { + label: "workflow definition delete", + }); + const gt = useGT(); + const [naming, setNaming] = useState(null); + // What the last delete said, on the page it belongs to: the file, or the list once it is gone. + const [refusal, setRefusal] = useState<{ + readonly at: string | null; + readonly problems: ReadonlyArray; + readonly deleted: boolean; + } | null>(null); + // Data already read stays on screen through a failed refresh or a dropped connection. + if (!query.data) { + if (away !== null) { + return ( + + ); + } + if (query.error) { + return ( + + ); + } + return ( +

    + Loading the workflow files… +

    + ); + } + const { directory, single, files, problems, revision } = query.data; + const open = (next: string | null) => { + setRefusal(null); + onOpen(next); + }; + const begin = () => { + const wanted = (naming ?? "").trim(); + if (wanted === "") return; + setNaming(null); + open(/\.(ts|mts|js|mjs)$/.test(wanted) ? wanted : `${wanted}.ts`); + }; + const removeFile = async (target: string) => { + const confirmed = await (requestConfirmDialog( + gt("Delete {file}? The workflows it defines can no longer be started.", { file: target }), + { variant: "destructive" }, + ) ?? Promise.resolve(false)); + if (!confirmed) return false; + const result = await remove({ environmentId, input: { name: target } }); + if (result._tag === "Failure") { + if (!isAtomCommandInterrupted(result)) { + setRefusal({ + at: target, + problems: [{ message: String(squashAtomCommandFailure(result)) }], + deleted: false, + }); + } + return false; + } + const { changed } = result.value; + setRefusal( + result.value.problems.length === 0 + ? null + : { at: changed ? null : target, problems: result.value.problems, deleted: changed }, + ); + return changed; + }; + const refused = refusal !== null && refusal.at === file ? refusal : null; + const between = ( + <> + {away === null ? null : ( +
    + {gt("{name} is not connected. What you write here stays, and saves once it is back.", { + name: away, + })} +
    + )} + {query.error === null || away !== null ? null : ( + + )} + {problems.length === 0 && refused === null ? null : ( + + )} + + ); + + if (file !== null) { + const shown = files.find((candidate) => candidate.name === file) ?? null; + return ( +
    + {between} + + removeFile(file)} + onClose={() => onOpen(null)} + actions={actions} + /> + +
    + ); + } + + return ( +
    + {between} +
    +
    +
    +

    + + Every file in{" "} + + {directory} + {" "} + defines workflows. A change to one is picked up without a restart. + +

    + {single || !canChange ? null : naming === null ? ( + + ) : ( + { + event.preventDefault(); + begin(); + }} + > + setNaming(event.target.value)} + onKeyDown={(event) => { + if (event.key === "Escape") setNaming(null); + }} + /> + + + )} +
    + {files.length === 0 ? ( +

    + + No workflows yet. Make the first file here, or ask an agent to write one in that + folder. + +

    + ) : ( +
      + {files.map((candidate) => ( +
    • + +
    • + ))} +
    + )} +
    +
    +
    + ); +} diff --git a/apps/web/src/components/workflows/WorkflowPane.tsx b/apps/web/src/components/workflows/WorkflowPane.tsx new file mode 100644 index 0000000000000..e23d5de8a50c7 --- /dev/null +++ b/apps/web/src/components/workflows/WorkflowPane.tsx @@ -0,0 +1,179 @@ +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { workflowReferenceLabel } from "@t3tools/client-runtime/workflows"; +import { EnvironmentId, ThreadId, type WorkflowRunReference } from "@t3tools/contracts"; +import { useGT } from "gt-react"; +import { BotIcon, Maximize2Icon, XIcon } from "lucide-react"; + +import { cn } from "../../lib/utils"; +import { useEnvironmentQuery } from "../../state/query"; +import { serverEnvironment } from "../../state/server"; +import { Button } from "../ui/button"; +import { + activeWorkflowPaneIndex, + closeWorkflowPaneTab, + openWorkflowPaneTab, + type WorkflowPaneState, + type WorkflowPaneTab, +} from "./workflowPane.logic"; +import { + useOpenReferencePage, + WorkflowReferenceMark, + WorkflowReferencePanel, +} from "./WorkflowReferences"; +import WorkflowThreadPane, { + useOpenThreadPage, + WorkflowThreadTabLabel, +} from "./WorkflowThreadPane"; + +/** + * The pane beside a run: a tab per transcript or reference opened from it. Only the tab that + * shows is mounted, so a pane with a chat and two pull requests renders one of them. + */ +export default function WorkflowPane({ + environmentId, + runId, + state, + onChange, +}: { + readonly environmentId: EnvironmentId; + readonly runId: string | null; + readonly state: WorkflowPaneState; + readonly onChange: (next: WorkflowPaneState) => void; +}) { + const gt = useGT(); + const detail = useEnvironmentQuery( + runId === null ? null : serverEnvironment.workflowRun({ environmentId, input: { runId } }), + ); + const openThreadPage = useOpenThreadPage(); + const openReferencePage = useOpenReferencePage(environmentId); + const tabs = state.pane ?? []; + const activeIndex = activeWorkflowPaneIndex(state); + const active = tabs[activeIndex]; + const threadOf = (tab: Extract) => + scopeThreadRef( + tab.env === undefined ? environmentId : EnvironmentId.make(tab.env), + ThreadId.make(tab.thread), + ); + const referenceOf = (tab: Extract) => + detail.data?.references.find( + (reference) => reference.kind === tab.kind && reference.key === tab.key, + ) ?? null; + const activeReference = active === undefined || "thread" in active ? null : referenceOf(active); + const openFull = + active === undefined + ? null + : "thread" in active + ? () => openThreadPage(threadOf(active)) + : activeReference === null + ? null + : openReferencePage(activeReference); + + return ( +
    +
    +
    + {tabs.map((tab, index) => ( +
    + + +
    + ))} +
    + {openFull === null ? null : ( + + )} + +
    +
    + {active === undefined ? null : "thread" in active ? ( + + ) : activeReference !== null ? ( + + ) : ( +

    + {detail.data === null ? gt("Loading…") : gt("This run no longer lists it.")} +

    + )} +
    +
    + ); +} + +function ReferenceTabLabel({ + reference, + fallback, +}: { + readonly reference: WorkflowRunReference | null; + readonly fallback: string; +}) { + if (reference === null) return {fallback}; + return ( + <> + + {workflowReferenceLabel(reference)} + + ); +} diff --git a/apps/web/src/components/workflows/WorkflowReferences.tsx b/apps/web/src/components/workflows/WorkflowReferences.tsx new file mode 100644 index 0000000000000..df89ecc7086cf --- /dev/null +++ b/apps/web/src/components/workflows/WorkflowReferences.tsx @@ -0,0 +1,193 @@ +import { + workflowReferenceIssue, + workflowReferenceLabel, + workflowReferencePullRequest, +} from "@t3tools/client-runtime/workflows"; +import type { EnvironmentId, WorkflowRunReference } from "@t3tools/contracts"; +import { useNavigate } from "@tanstack/react-router"; +import { T } from "gt-react"; +import { CircleCheckIcon, CircleDotIcon, ExternalLinkIcon, LinkIcon } from "lucide-react"; + +import { isElectron } from "~/env"; +import { isTerminalFocused } from "../../lib/terminalFocus"; +import { cn } from "../../lib/utils"; +import { ISSUES_PANEL_REF, useRightPanelStore } from "../../rightPanelStore"; +import { IssueDetailPanel } from "../issue/IssueDetailPanel"; +import { readIssueListPreferences } from "../issue/issueListPreferences"; +import { PullRequestDetailPanel } from "../pullRequest/PullRequestDetailPanel"; +import { PULL_REQUEST_STATE_PRESENTATION } from "../pullRequest/pullRequestIcons"; +import { Button } from "../ui/button"; + +/** The mark a reference wears: its kind's icon, in the ink its state has on its own page. */ +function referenceGlyph(reference: WorkflowRunReference) { + if (workflowReferencePullRequest(reference) !== null) { + const state = + reference.state === "closed" || reference.state === "merged" ? reference.state : "open"; + return PULL_REQUEST_STATE_PRESENTATION[state]; + } + if (workflowReferenceIssue(reference) !== null) { + return reference.state === "closed" + ? { + Icon: CircleCheckIcon, + toneClassName: PULL_REQUEST_STATE_PRESENTATION.merged.toneClassName, + } + : { Icon: CircleDotIcon, toneClassName: PULL_REQUEST_STATE_PRESENTATION.open.toneClassName }; + } + return { Icon: LinkIcon, toneClassName: "text-muted-foreground" }; +} + +export function WorkflowReferenceMark({ reference }: { readonly reference: WorkflowRunReference }) { + const glyph = referenceGlyph(reference); + return ; +} + +/** A thing the run touched, as a chip that opens it beside the run. */ +export function WorkflowReferenceChip({ + reference, + open, + small = false, + onOpen, +}: { + readonly reference: WorkflowRunReference; + /** It shows in the pane now, so another click closes it. */ + readonly open: boolean; + /** On a step, where the label is enough. */ + readonly small?: boolean; + readonly onOpen: () => void; +}) { + const label = workflowReferenceLabel(reference); + const title = reference.title === label ? "" : reference.title; + const name = title === "" ? label : `${label} ${title}`; + return ( + + ); +} + +const shortcutContext = () => ({ + terminalFocus: isTerminalFocused(), + terminalOpen: false, + previewFocus: false, + previewOpen: false, + isWeb: !isElectron, + isDesktop: isElectron, +}); + +/** Opens the reference on its own page, where it has the whole window. Null for a kind with none. */ +export function useOpenReferencePage( + environmentId: EnvironmentId, +): (reference: WorkflowRunReference) => (() => void) | null { + const navigate = useNavigate(); + return (reference) => { + const issue = workflowReferenceIssue(reference); + if (issue !== null) { + return () => { + // The Issues page shows the issue its panel has open; the address keeps the list's place. + useRightPanelStore.getState().openIssue(ISSUES_PANEL_REF, { + environmentId, + projectId: issue.projectId, + tracker: issue.tracker, + ...(issue.host === undefined ? {} : { host: issue.host }), + scope: issue.scope, + key: issue.key, + ...(reference.url === null ? {} : { url: reference.url }), + }); + void navigate({ + to: "/issues", + search: { + ...readIssueListPreferences(), + selectedEnvironmentId: environmentId, + selectedProjectId: issue.projectId, + ...(issue.host === undefined ? {} : { selectedHost: issue.host }), + tracker: issue.tracker, + scope: issue.scope, + key: issue.key, + }, + }); + }; + } + const pullRequest = workflowReferencePullRequest(reference); + if (pullRequest !== null) { + return () => + void navigate({ + to: "/pull-requests", + search: { + involvement: "all", + state: "all", + repository: pullRequest.repository, + number: pullRequest.number, + ...(pullRequest.host === undefined ? {} : { selectedHost: pullRequest.host }), + selectedProjectId: pullRequest.projectId, + selectedEnvironmentId: environmentId, + }, + }); + } + return null; + }; +} + +/** A reference opened beside its run: the Issues or Pull requests page's own view of it. */ +export function WorkflowReferencePanel({ + environmentId, + reference, +}: { + readonly environmentId: EnvironmentId; + readonly reference: WorkflowRunReference; +}) { + const issue = workflowReferenceIssue(reference); + if (issue !== null) { + return ; + } + const pullRequest = workflowReferencePullRequest(reference); + if (pullRequest !== null) { + return ( + + ); + } + // A kind this client does not know yet: what the run knows of it, and where it lives. + return ( +
    +

    + {reference.title === "" ? workflowReferenceLabel(reference) : reference.title} +

    +

    + + {reference.kind} + {reference.state === null ? null : ( + <> + · + {reference.state} + + )} +

    + {reference.url === null ? null : ( + + )} +
    + ); +} diff --git a/apps/web/src/components/workflows/WorkflowRunFeed.tsx b/apps/web/src/components/workflows/WorkflowRunFeed.tsx new file mode 100644 index 0000000000000..d77b54d8dcc11 --- /dev/null +++ b/apps/web/src/components/workflows/WorkflowRunFeed.tsx @@ -0,0 +1,1924 @@ +import { useAtomValue } from "@effect/atom-react"; +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, + type AtomCommandResult, +} from "@t3tools/client-runtime/state/runtime"; +import { + EnvironmentId, + ThreadId, + type WorkflowQuestion, + type WorkflowRun, + type WorkflowRunReference, +} from "@t3tools/contracts"; +import { formatModelSlugName } from "@t3tools/shared/model"; +import { formatDuration } from "@t3tools/shared/orchestrationTiming"; +import { msg, T, useGT, useMessages, Var } from "gt-react"; +import { + ArrowLeftIcon, + ArrowUpRightIcon, + ChevronRightIcon, + BotIcon, + CheckIcon, + CircleAlertIcon, + HourglassIcon, + MoonIcon, + SquareIcon, +} from "lucide-react"; +import { secondTick } from "@t3tools/client-runtime/clock"; +import { + createContext, + useContext, + useRef, + useState, + useSyncExternalStore, + type ReactNode, +} from "react"; + +import { requestConfirmDialog } from "../../confirmDialog"; +import { useNowMinute } from "../../hooks/useNowMinute"; +import { cn } from "../../lib/utils"; +import { useQuietThreadShell } from "../../state/entities"; +import { useEnvironment, useEnvironmentProviders } from "../../state/environments"; +import { type MessageResolver } from "../../i18n/messages"; +import { useEnvironmentQuery } from "../../state/query"; +import { serverEnvironment } from "../../state/server"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { formatRelativeTimeLabel } from "../../timestampFormat"; +import ChatMarkdown from "../ChatMarkdown"; +import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon"; +import { Button } from "../ui/button"; +import { Input } from "../ui/input"; +import { stackedThreadToast, toastManager } from "../ui/toast"; +import { + buildWorkflowFeed, + buildWorkflowTimeline, + readWorkflowQuestion, + workflowAgentSummary, + workflowAnswer, + workflowChip, + workflowFlowFocus, + workflowPausedBeat, + workflowResultLines, + workflowRunNow, + workflowRunState, + workflowSaidStart, + workflowStepReferences, + workflowStepTime, + workflowOneLine, + type WorkflowBeat, + type WorkflowFeedRow, + type WorkflowQuickSteps, + type WorkflowRunNode, + type WorkflowRunTone, +} from "@t3tools/client-runtime/workflows"; +import type { WorkflowPaneTab } from "./workflowPane.logic"; +import { WorkflowReferenceChip } from "./WorkflowReferences"; + +/** An agent's thread, as a step names it: the linked environment it is in, or null for this one. */ +export interface WorkflowThreadTarget { + readonly threadId: string; + readonly environmentId: string | null; +} + +// An agent that wrote a page gets a few lines of it; the rest is a click away. +const SAID_SHOWN = 320; + +// What waits on a person is what they came for, so it is in view when the run opens. +const revealOnMount = (element: HTMLElement | null) => { + element?.scrollIntoView({ block: "nearest" }); +}; + +function reportFailure(title: string, result: AtomCommandResult) { + if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return; + toastManager.add( + stackedThreadToast({ + type: "error", + title, + description: String(squashAtomCommandFailure(result)), + }), + ); +} + +// Reads the minute tick because the compiler caches a render-time Date.now() on the timestamp. +function useNowMs(): number { + return Date.parse(`${useNowMinute()}:00.000Z`); +} + +// A time still counting is told to the second: its tenths would only flicker. +const wholeSeconds = (ms: number) => Math.max(1000, Math.round(ms / 1000) * 1000); +const elapsedOf = (beat: WorkflowBeat) => + beat.status === "running" ? wholeSeconds(beat.endMs - beat.startMs) : beat.endMs - beat.startMs; + +const never = () => () => {}; +const noTick = () => 0; + +/** The clock a run is told by: to the second while it is under way, to the minute after. */ +function useRunNowMs(live: boolean): number { + const minute = useNowMs(); + const second = useSyncExternalStore( + live ? secondTick.subscribe : never, + live ? secondTick.getSnapshot : noTick, + live ? secondTick.getSnapshot : noTick, + ); + return live ? second : minute; +} + +export function RelativeLabel({ value }: { readonly value: string }) { + return formatRelativeTimeLabel(value, useNowMs()); +} + +const CHIP_TONES = [ + "bg-sky-500/15 text-sky-700 dark:text-sky-300", + "bg-violet-500/15 text-violet-700 dark:text-violet-300", + "bg-amber-500/15 text-amber-700 dark:text-amber-300", + "bg-emerald-500/15 text-emerald-700 dark:text-emerald-300", + "bg-rose-500/15 text-rose-700 dark:text-rose-300", +] as const; + +/** Which workflow a run is of, at a glance: the same letters and colour wherever it shows. */ +export function WorkflowChip({ name }: { readonly name: string }) { + const chip = workflowChip(name); + return ( + + {chip.letters} + + ); +} + +// The thread list's own colours for the same states, so a run reads like a thread does. +const WORKFLOW_TONE_CLASS: Record = { + input: "text-warning-foreground", + failed: "text-destructive", + working: "text-info-foreground", + quiet: "text-muted-foreground", + done: "text-success-foreground", +}; + +export function WorkflowStateWord({ node }: { readonly node: WorkflowRunNode }) { + const m = useMessages(); + const state = workflowRunState(node, m); + return ( + + {state.tone === "working" ? ( + + ) : state.tone === "done" ? ( + + ) : null} + {state.word} + + ); +} + +const nthTry = (count: number, resolve: MessageResolver) => + resolve( + msg("{count, plural, =1 {1st try} =2 {2nd try} =3 {3rd try} other {{count}th try}}", { + count, + }), + ); + +// The loading view and the timeline each draw a question's card, so a reason typed while the +// steps load is kept here rather than in the card that is about to be replaced. +const AnswerDrafts = createContext<{ + readonly get: (key: string) => string | null; + readonly set: (key: string, reason: string | null) => void; +} | null>(null); + +export function WorkflowRunFeed({ + environmentId, + node, + parent, + shownTab, + onSelect, + onOpenThread, + onOpenReference, +}: { + readonly environmentId: EnvironmentId; + readonly node: WorkflowRunNode; + readonly parent: WorkflowRun | null; + /** What shows beside the run, so the card or chip that opened it can say so. */ + readonly shownTab: WorkflowPaneTab | null; + readonly onSelect: (runId: string | null) => void; + readonly onOpenThread: (thread: WorkflowThreadTarget) => void; + readonly onOpenReference: (reference: WorkflowRunReference) => void; +}) { + const { run } = node; + const gt = useGT(); + const clockMs = useRunNowMs(node.run.endedAt === null); + // An ended run's last step can still read as running for a moment; it ran until the run ended. + const nowMs = node.run.endedAt === null ? clockMs : Date.parse(node.run.endedAt); + const panel = useRef(null); + const [picked, setPicked] = useState(null); + // Steps already there when the run opens are simply shown; only later ones arrive with motion. + const [openedAtMs] = useState(() => Date.now()); + const detail = useEnvironmentQuery( + serverEnvironment.workflowRun({ environmentId, input: { runId: run.runId } }), + ); + const canResume = useAtomValue(serverEnvironment.resumeWorkflowRun.permissionAtom(environmentId)); + const canCancel = useAtomValue(serverEnvironment.cancelWorkflowRun.permissionAtom(environmentId)); + const resume = useAtomCommand(serverEnvironment.resumeWorkflowRun, { label: "workflow resume" }); + const cancel = useAtomCommand(serverEnvironment.cancelWorkflowRun, { label: "workflow cancel" }); + const [busy, setBusy] = useState(false); + const target = { environmentId, input: { runId: run.runId } }; + const [drafts, setDrafts] = useState>(() => new Map()); + const answerDrafts = { + get: (key: string) => drafts.get(key) ?? null, + set: (key: string, reason: string | null) => + setDrafts((current) => { + const next = new Map(current); + if (reason === null) next.delete(key); + else next.set(key, reason); + return next; + }), + }; + const resumeRun = async () => { + if (busy) return; + setBusy(true); + const result = await resume(target); + setBusy(false); + reportFailure(gt("Could not resume the run"), result); + }; + const cancelRun = async () => { + if (busy) return; + // Busy while the dialog is up, so a second click does not open a second one. + setBusy(true); + const confirmed = await (requestConfirmDialog( + gt("Cancel {title}? Its agents stop and the run cannot be resumed.", { title: run.title }), + { variant: "destructive" }, + ) ?? Promise.resolve(false)); + if (!confirmed) return setBusy(false); + const result = await cancel(target); + setBusy(false); + reportFailure(gt("Could not cancel the run"), result); + }; + const ended = run.endedAt !== null; + const ranMs = ended + ? Date.parse(run.endedAt) - Date.parse(run.startedAt) + : wholeSeconds(nowMs - Date.parse(run.startedAt)); + const steps = detail.data?.steps; + const references = detail.data?.references ?? []; + // An open transcript is one thread in one environment; `env` is absent for the run's own. + const openThread = shownTab !== null && "thread" in shownTab ? shownTab : null; + const chip = (reference: WorkflowRunReference, small = false) => ( + onOpenReference(reference)} + /> + ); + const feed = + steps === undefined + ? null + : buildWorkflowFeed( + buildWorkflowTimeline({ + run, + steps, + children: node.children.map((child) => child.run), + nowMs, + }), + ); + const beats = (feed ?? []).flatMap((row) => + row.kind === "quick" ? [] : row.kind === "together" ? row.beats : [row], + ); + // A question is told where it was asked. One whose step is not in the list yet still shows. + const questionOf = (beat: WorkflowBeat) => + beat.kind === "ask" && beat.status === "running" + ? (node.questions.find((question) => question.name === beat.name) ?? null) + : null; + const loose = node.questions.filter( + (question) => !beats.some((beat) => questionOf(beat) === question), + ); + const pausedAt = feed === null ? null : workflowPausedBeat(feed, run.status); + const pause = (name: string | null, attempts: number, reason: string | null) => ( + void resumeRun()} + kept={(steps ?? []).some((step) => step.status === "completed")} + /> + ); + const beatCard = (beat: WorkflowBeat) => { + if (beat === pausedAt) { + // The step's own card stays, so its transcript can be read before resuming. + return ( +
    + {pause(beat.name, beat.attempts, beat.detail ?? run.detail)} + {stepCard(beat)} +
    + ); + } + return stepCard(beat); + }; + const stepCard = (beat: WorkflowBeat) => ( + child.run.runId === beat.childRun?.runId) ?? null} + nowMs={nowMs} + open={ + beat.thread !== null && + openThread !== null && + beat.thread.threadId === openThread.thread && + (beat.thread.environmentId ?? undefined) === openThread.env + } + onSelect={onSelect} + onOpenThread={onOpenThread} + /> + ); + const resultLines = workflowResultLines(run.result); + const pausedApart = run.status === "paused" && pausedAt === null; + const keys = new Set([ + ...(feed ?? []).flatMap((row) => (row.kind === "quick" ? [`quick:${row.steps[0]?.name}`] : [])), + ...beats.map((beat) => `step:${beat.name}`), + ...loose.map((question) => `question:${question.name}`), + ...(pausedApart ? ["pause"] : []), + ...(ended ? ["end"] : []), + ]); + // A run that finished opens on what it came to: its result when that says more than the last + // answer, else the last agent's reply. The header already says it is done. + const lastAnswer = beats.findLast((beat) => beat.kind === "ask" && beat.status === "completed"); + const answered = lastAnswer === undefined ? null : workflowAnswer(lastAnswer.result); + const resultSaysMore = + resultLines.length > 0 && + !(resultLines.length === 1 && answered !== null && resultLines[0]?.value === answered.choice); + const latest = (found: ReadonlyArray) => + found.reduce( + (best, beat) => (best === undefined || beat.endMs >= best.endMs ? beat : best), + undefined, + ); + const lastAgent = latest( + beats.filter((beat) => beat.kind === "agent" && beat.status === "completed"), + ); + const finishedFocus = + run.status !== "completed" || resultSaysMore || lastAgent === undefined + ? "end" + : `step:${lastAgent.name}`; + const focus = + picked !== null && keys.has(picked) + ? picked + : feed === null + ? null + : ended + ? finishedFocus + : workflowFlowFocus({ + rows: feed, + status: run.status, + ended, + questions: node.questions.map((question) => question.name), + }); + const pick = (key: string) => { + const asks = + key.startsWith("question:") || + beats.some((beat) => `step:${beat.name}` === key && questionOf(beat) !== null); + setPicked(asks ? null : key); + // Below the flow on a narrow page, so picking a step brings what it shows into view; a + // question is answered where it is, so the page stays put. + if (!asks) panel.current?.scrollIntoView({ block: "nearest" }); + }; + const endWord = + run.status === "completed" + ? gt("Finished", { $context: "how a workflow run ended" }) + : run.status === "stopped" + ? gt("Stopped", { $context: "how a workflow run ended" }) + : run.status === "skipped" + ? gt("Skipped", { $context: "how a workflow run ended" }) + : gt("Cancelled", { $context: "how a workflow run ended" }); + // A question is answered where it was asked, so beside it is what led up to it. + const asking = + focus !== null && + (focus.startsWith("question:") || + beats.some( + (beat) => + `step:${beat.name}` === focus && + // Answered, its question is gone a moment before the step itself says it is done. + (questionOf(beat) !== null || (beat.kind === "ask" && beat.status === "running")), + )); + // The latest agent's reply is what a person weighs before answering; failing that, the last + // step that left something behind. A sleep or a wait has nothing to say. + const before = asking + ? (latest(beats.filter((beat) => beat.kind === "agent" && beat.status !== "running")) ?? + beats.findLast( + (beat) => + beat.status !== "running" && + beat.kind !== "ask" && + beat.kind !== "sleep" && + beat.kind !== "wait", + ) ?? + null) + : null; + const shown = asking ? (before === null ? null : `step:${before.name}`) : focus; + const shownBeat = beats.find((beat) => `step:${beat.name}` === shown); + const shownQuick = (feed ?? []).find( + (row) => row.kind === "quick" && `quick:${row.steps[0]?.name}` === shown, + ); + + return ( + +
    +
    + + {parent === null ? null : ( + + )} +
    +

    {run.title}

    + + {ended ? null : ( + + )} +
    +

    + + {run.workflow} + · + + + started{" "} + + + + + + {run.status === "paused" ? null : ( + <> + · + + {ended + ? gt("took {duration}", { duration: formatDuration(ranMs) }) + : gt("{duration} so far", { duration: formatDuration(ranMs) })} + + + )} + {run.retired ? ( + <> + · + + its version is no longer registered + + + ) : null} +

    + {references.length === 0 ? null : ( +
      + {references.map((reference) => ( +
    • + {chip(reference, reference.title !== "" && run.title.includes(reference.title))} +
    • + ))} +
    + )} +
    + + {detail.error || + feed === null || + (feed.length === 0 && run.status === "paused" && loose.length === 0) ? ( + <> + {detail.error ? ( +

    {detail.error}

    + ) : feed === null ? ( +

    + Loading steps… +

    + ) : null} + {/* A question the run already asks is answerable without its step history. */} + {run.status === "paused" ? ( +
    +
    {pause(null, run.pauses, run.detail)}
    +
    + ) : null} + {node.questions.map((question) => ( +
    + +
    + ))} + + ) : ( +
    + +
    + {shownBeat !== undefined ? ( + // Keyed by the step: a reason typed for one question must not follow to the next. +
    + {beatCard(shownBeat)} + {(() => { + // With one reference, the header already says it. + const touched = + references.length > 1 + ? workflowStepReferences(references, shownBeat.name) + : []; + return touched.length === 0 ? null : ( +
    + {touched.map((reference) => chip(reference, true))} +
    + ); + })()} +
    + ) : shownQuick !== undefined && shownQuick.kind === "quick" ? ( + + ) : asking ? null : focus === "pause" ? ( + pause(null, run.pauses, run.detail) + ) : focus === "end" ? ( + + + ) : null + } + name={endWord} + sub={} + /> + {run.status !== "completed" && run.detail ? ( +

    {run.detail}

    + ) : null} + +
    + ) : ( +

    + Nothing yet. +

    + )} +
    +
    + )} +
    +
    + ); +} + +type StepTone = "working" | "input" | "quiet" | "done" | "failed" | "ended"; + +// Colour says what is live: blue for work under way, amber for a person's turn. Done is quiet. +const RING: Record = { + working: "stroke-info", + input: "stroke-warning", + quiet: "stroke-muted-foreground/60", + done: "stroke-muted-foreground/45", + failed: "stroke-destructive", + ended: "stroke-muted-foreground/60", +}; + +const VERB_TONE = { + working: "text-info-foreground", + input: "text-warning-foreground", + quiet: "text-muted-foreground", + failed: "text-destructive", +} as const; + +/** + * A step's place on the rail: a ring, filled while it works, ticked when it is done. `pulse` and + * `draw` never change for a step, so each plays once, when its part of the mark first appears. + */ +function StepMark({ + tone, + pulse, + draw, +}: { + readonly tone: StepTone; + /** It started while the run was open here. */ + readonly pulse: boolean; + /** It ended while the run was open here. */ + readonly draw: boolean; +}) { + const live = tone === "working" || tone === "input"; + return ( + + {live && pulse ? ( + + ) : null} + + + {live || tone === "quiet" ? ( + + ) : tone === "done" ? ( + + ) : tone === "failed" ? ( + + ) : ( + + )} + + + ); +} + +/** One line of the run: its mark on the rail, name, what it is doing, a word on how it went, its time. */ +function TimelineRow({ + tone, + enters, + draw, + lead, + name, + note, + verb, + verbTone = "working", + aside, + asideTone, + duration, + selected, + current = false, + onPick, + sub = false, +}: { + readonly tone: StepTone; + /** It started while the run was open here, so it arrives instead of just being there. */ + readonly enters: boolean; + /** It ended while the run was open here. */ + readonly draw: boolean; + /** A small mark before the name, such as the agent's provider. */ + readonly lead?: ReactNode; + readonly name: string; + /** A quieter word after the name, such as the agent's model. */ + readonly note?: string | null; + readonly verb?: string | null; + readonly verbTone?: keyof typeof VERB_TONE; + readonly aside?: string | null; + readonly asideTone?: "failed"; + readonly duration?: string | null; + readonly selected: boolean; + /** The pane beside the timeline shows it. */ + readonly current?: boolean; + readonly onPick: () => void; + /** A step of a fork, hanging off the branch rather than the rail. */ + readonly sub?: boolean; +}) { + const live = tone === "working" || tone === "input"; + return ( + + ); +} + +/** The rail beside a row: from the row above to this mark, and on to the next unless it is last. */ +function Rail({ first, last }: { readonly first: boolean; readonly last: boolean }) { + return ( + + ); +} + +// A fork leaves the rail under its mark, runs through each step's dot, and rejoins the rail. +// The rail's centre is 10px in and a step's dot 39px in; the mark ends 26px down, the first dot +// sits 46px down, and each dot is 14px below its own row's top. +function BranchOut() { + return ( + + + + ); +} + +function BranchBack() { + return ( + <> + + + + + + ); +} + +/** + * The run as it went, one line per step that took time or involved someone. Steps that ran at once + * hang off a branch. It never draws what comes next: a run can branch, so the rail just goes on. + */ +function WorkflowTimeline({ + environmentId, + rows, + node, + nowMs, + focus, + onPick, + loose, + paused, + end, + question, + onOpenThread, + openedAtMs, + current, +}: { + readonly environmentId: EnvironmentId; + readonly rows: ReadonlyArray; + readonly node: WorkflowRunNode; + readonly nowMs: number; + readonly focus: string | null; + readonly onPick: (key: string) => void; + /** Questions whose step is not in the list yet. */ + readonly loose: ReadonlyArray; + /** The run is paused, and not at a step that failed. */ + readonly paused: boolean; + /** How the run ended, once it has. */ + readonly end: string | null; + /** What it ended with, in a few words. */ + /** The question a step waits on a person for, answered right under it. */ + readonly question: (beat: WorkflowBeat) => WorkflowQuestion | null; + readonly onOpenThread: (thread: WorkflowThreadTarget) => void; + /** When this run was opened here: only what changes after that arrives with motion. */ + readonly openedAtMs: number; + /** What the pane beside the timeline shows. */ + readonly current: string | null; +}) { + const gt = useGT(); + const completed = node.run.status === "completed"; + const ask = (asked: WorkflowQuestion) => ( +
    + +
    + ); + const beatRow = (beat: WorkflowBeat, sub = false) => ( + child.run.runId === beat.childRun?.runId) ?? null} + asks={node.questions.some((asked) => asked.name === beat.name)} + nowMs={nowMs} + selected={focus === `step:${beat.name}`} + current={current === `step:${beat.name}`} + onPick={() => onPick(`step:${beat.name}`)} + sub={sub} + openedAtMs={openedAtMs} + /> + ); + const items: Array<{ + readonly key: string; + readonly body: ReactNode; + /** Its steps hang off a branch, which carries the rail past them. */ + readonly branch?: boolean; + }> = []; + for (const row of rows) { + if (row.kind === "quick") { + const key = `quick:${row.steps[0]?.name}`; + // Keyed by its first step, as that step's own row was, so regrouping does not remount it. + const itemKey = row.steps[0]?.name ?? key; + const names = row.steps.map((step) => step.name); + items.push({ + key: itemKey, + body: ( + openedAtMs} + name={ + names.length <= 2 + ? names.join(" · ") + : gt("{names} and {count} more", { + names: names.slice(0, 2).join(" · "), + count: names.length - 2, + }) + } + duration={workflowStepTime(Math.max(0, row.endMs - row.startMs))} + selected={focus === key} + current={current === key} + onPick={() => onPick(key)} + /> + ), + }); + continue; + } + if (row.kind === "together") { + const running = row.beats.filter((beat) => beat.status === "running").length; + // Steps that only sleep or wait are under way without working. + const working = row.beats.some( + (beat) => beat.status === "running" && beat.kind !== "sleep" && beat.kind !== "wait", + ); + const failed = row.beats.some((beat) => beat.status === "failed"); + const asks = row.beats.some( + (beat) => beat.status === "running" && node.questions.some((q) => q.name === beat.name), + ); + const startMs = Math.min(...row.beats.map((beat) => beat.startMs)); + const endMs = Math.max(...row.beats.map((beat) => beat.endMs)); + const first = row.beats[0]; + items.push({ + key: first?.name ?? "together", + branch: true, + body: ( + <> +
    + 0 + ? "quiet" + : failed + ? "failed" + : "done" + } + pulse={startMs > openedAtMs} + draw={running === 0 && endMs > openedAtMs} + /> + 0 ? "font-medium" : "text-muted-foreground", + )} + > + {gt("{count} in parallel", { count: row.beats.length })} + + {working ? ( + + {gt("{count} running", { count: running })} + + ) : null} + + {workflowStepTime(running > 0 ? wholeSeconds(endMs - startMs) : endMs - startMs)} + + +
    + +
      + {row.beats.map((beat, index) => { + const firstBeat = index === 0; + const lastBeat = index === row.beats.length - 1; + const asked = question(beat); + return ( +
    1. + + {lastBeat ? : null} + {beatRow(beat, true)} + {asked === null ? null : ask(asked)} +
    2. + ); + })} +
    + + ), + }); + continue; + } + const asked = question(row); + items.push({ + key: row.name, + body: ( + <> + {beatRow(row)} + {asked === null ? null : ask(asked)} + + ), + }); + } + for (const asked of loose) { + // Keyed like its step's row, which replaces it once the step arrives, so it does not arrive twice. + items.push({ + key: asked.name, + body: ( + <> + openedAtMs} + draw={false} + name={asked.name} + verb={gt("Asks you", { $context: "a workflow step waits on a person's answer" })} + verbTone="input" + selected={focus === `question:${asked.name}`} + current={current === `question:${asked.name}`} + onPick={() => onPick(`question:${asked.name}`)} + /> + {ask(asked)} + + ), + }); + } + if (paused) { + items.push({ + key: "pause", + body: ( + onPick("pause")} + /> + ), + }); + } + // A finished run needs no closing row: the header says so, and the last step is the end. + if (end !== null && !completed) { + const endedMs = Date.parse(node.run.endedAt ?? node.run.updatedAt); + items.push({ + key: "end", + body: ( + openedAtMs} + draw={false} + name={end} + aside={node.run.detail} + selected={focus === "end"} + current={current === "end"} + onPick={() => onPick("end")} + /> + ), + }); + } + const live = end === null; + return ( + + ); +} + +function WorkflowBeatRow({ + environmentId, + beat, + child, + asks, + nowMs, + selected, + onPick, + sub, + openedAtMs, + current, +}: { + readonly environmentId: EnvironmentId; + readonly beat: WorkflowBeat; + readonly child: WorkflowRunNode | null; + /** A person's answer is what it waits for. */ + readonly asks: boolean; + readonly nowMs: number; + readonly selected: boolean; + readonly onPick: () => void; + readonly sub: boolean; + readonly openedAtMs: number; + readonly current: boolean; +}) { + const gt = useGT(); + const m = useMessages(); + const threadEnvironmentId = + beat.thread?.environmentId == null + ? environmentId + : EnvironmentId.make(beat.thread.environmentId); + const shell = useQuietThreadShell( + beat.thread === null + ? null + : scopeThreadRef(threadEnvironmentId, ThreadId.make(beat.thread.threadId)), + ); + const provider = useEnvironmentProviders() + .get(threadEnvironmentId) + ?.find((candidate) => candidate.instanceId === shell?.modelSelection.instanceId); + const under = beat.status === "running"; + const failed = beat.status === "failed"; + const said = workflowAgentSummary(beat).said; + const answer = beat.kind === "ask" ? workflowAnswer(beat.result) : null; + const wakes = beat.detail === null ? Number.NaN : Date.parse(beat.detail); + // An agent's own approval or question needs a person as much as the workflow's does. + const agentAsks = + beat.kind === "agent" && under && shell !== null + ? shell.hasPendingUserInput + ? gt("Asks you", { $context: "a workflow step waits on a person's answer" }) + : shell.hasPendingApprovals + ? gt("waits for your approval") + : null + : null; + // A question waits on a person until its step ends, answered or not; the list of open + // questions drops it a moment before the step reports done. + const needsYou = (under && (asks || beat.kind === "ask")) || agentAsks !== null; + const model = shell === null ? null : formatModelSlugName(shell.modelSelection.model); + const verb = (() => { + if (!under) return null; + if (agentAsks !== null) return agentAsks; + switch (beat.kind) { + case "agent": + return shell?.runtime?.status === "preparing" || shell?.runtime?.status === "starting" + ? gt("starting") + : gt("working"); + case "ask": + // Without its question it was just answered, and the step is about to say so. + return asks + ? gt("Asks you", { $context: "a workflow step waits on a person's answer" }) + : null; + case "sleep": + return Number.isFinite(wakes) && wakes > nowMs + ? gt("wakes in {duration}", { duration: formatDuration(wholeSeconds(wakes - nowMs)) }) + : gt("about to wake"); + case "wait": + return gt("waiting"); + case "run": + return child === null ? gt("running") : workflowRunNow(child, m); + case "step": + return gt("running"); + } + })(); + const aside = (() => { + if (failed) return workflowOneLine(beat.detail ?? gt("failed")); + if (under) return null; + switch (beat.kind) { + case "agent": + return said === null ? null : workflowOneLine(said); + case "ask": + return answer === null + ? gt("nobody answered") + : gt("You said {choice}", { choice: answer.choice }); + case "sleep": + case "wait": + return null; + case "run": + return child === null ? null : workflowRunNow(child, m); + case "step": { + const first = workflowResultLines(beat.result)[0]; + return first === undefined + ? null + : first.label === null + ? first.value + : `${first.label}: ${first.value}`; + } + } + })(); + + return ( + openedAtMs} + draw={!under && beat.endMs > openedAtMs} + lead={ + beat.kind === "agent" && provider !== undefined ? ( + + ) : beat.kind === "run" ? ( + + ) : undefined + } + name={beat.childRun?.title ?? beat.name} + note={beat.kind === "agent" && (under || said === null) ? model : null} + verb={verb} + verbTone={ + needsYou ? "input" : beat.kind === "sleep" || beat.kind === "wait" ? "quiet" : "working" + } + aside={aside} + {...(failed ? { asideTone: "failed" as const } : {})} + duration={workflowStepTime(elapsedOf(beat))} + selected={selected} + current={current} + onPick={onPick} + sub={sub} + /> + ); +} + +// What happened reads as part of the page. A question, answered in the timeline, is the one box; +// a pause says so in its heading and its button. +const CARD_TONE = { + plain: "", + quiet: "", + ask: "rounded-xl border border-warning/30 bg-warning-surface px-3 py-2.5", + failed: "", + done: "", +} as const; + +function FeedCard({ + tone = "plain", + label, + reveal = false, + children, +}: { + readonly tone?: keyof typeof CARD_TONE; + readonly label?: string; + /** Scroll it into view when it first shows. */ + readonly reveal?: boolean; + readonly children: ReactNode; +}) { + return ( +
    + {children} +
    + ); +} + +function CardHead({ + mark, + name, + sub, + action, +}: { + readonly mark: ReactNode; + readonly name: ReactNode; + readonly sub?: ReactNode; + readonly action?: ReactNode; +}) { + return ( +
    +
    + {mark === null || mark === undefined ? null : ( + {mark} + )} +
    {name}
    + {action === undefined || action === null ? null :
    {action}
    } +
    + {sub === undefined || sub === null || sub === "" ? null : ( +
    {sub}
    + )} +
    + ); +} + +function ResultLines({ + lines, +}: { + readonly lines: ReadonlyArray<{ readonly label: string | null; readonly value: string }>; +}) { + if (lines.length === 0) return null; + if (lines.every((line) => line.label === null)) { + return ( +
    + {lines.map((line) => ( +

    + {line.value} +

    + ))} +
    + ); + } + return ({ label: line.label ?? "", value: line.value }))} />; +} + +/** What a step left behind, as a list of names and values. */ +function Facts({ + facts, +}: { + readonly facts: ReadonlyArray<{ readonly label: string; readonly value: string }>; +}) { + return ( +
    + {facts.map((fact) => ( +
    +
    {fact.label}
    +
    {fact.value}
    +
    + ))} +
    + ); +} + +/** A step with nothing to show but that it happened, and what it left behind. */ +function Note({ + label, + children, + detail, +}: { + readonly label: string; + readonly children: ReactNode; + readonly detail?: ReactNode; +}) { + return ( + + + {detail} + + ); +} + +function WorkflowQuickStepsCard({ row }: { readonly row: WorkflowQuickSteps }) { + const gt = useGT(); + return ( + +
      + {row.steps.map((step) => ( +
    • + {step.name} + +
    • + ))} +
    +
    + ); +} + +function WorkflowBeatCard({ + environmentId, + beat, + child, + nowMs, + open, + onSelect, + onOpenThread, +}: { + readonly environmentId: EnvironmentId; + readonly beat: WorkflowBeat; + readonly child: WorkflowRunNode | null; + readonly nowMs: number; + readonly open: boolean; + readonly onSelect: (runId: string | null) => void; + readonly onOpenThread: (thread: WorkflowThreadTarget) => void; +}) { + const gt = useGT(); + const m = useMessages(); + const under = beat.status === "running"; + const length = formatDuration(elapsedOf(beat)); + const tries = beat.attempts > 1 ? ` · ${nthTry(beat.attempts, m)}` : ""; + switch (beat.kind) { + case "agent": + return ( + + ); + case "ask": { + const answer = workflowAnswer(beat.result); + if (answer === null) + return {`${gt("nobody answered")} · ${length}`}; + return ( + + +

    + {answer.reason === null ? ( + + You said{" "} + + {answer.choice} + + . + + ) : ( + + You said{" "} + + {answer.choice} + + : {answer.reason} + + )} +

    +
    + ); + } + case "sleep": { + if (!under) return {`${gt("slept")} · ${length}`}; + const wakes = beat.detail === null ? Number.NaN : Date.parse(beat.detail); + return ( + + } + name={beat.name} + sub={ + Number.isFinite(wakes) && wakes > nowMs + ? gt("wakes in {duration}", { + duration: formatDuration(wholeSeconds(wakes - nowMs)), + }) + : gt("about to wake") + } + /> + + ); + } + case "wait": + if (!under) return {`${gt("waited")} · ${length}`}; + return ( + + } + name={beat.name} + sub={gt("{duration} so far", { duration: length })} + /> + + ); + case "run": { + const title = beat.childRun?.title ?? beat.name; + return ( + + } + name={title} + sub={ + child === null + ? `${beat.childRun?.workflow ?? ""} · ${length}` + : `${child.run.workflow} · ${workflowRunNow(child, m)}` + } + action={ + <> + {child === null ? null : } + + + } + /> + + ); + } + case "step": { + if (under) { + return ( + + } + name={beat.name} + sub={`${gt("running for {duration}", { duration: length })}${tries}`} + /> + + ); + } + const lines = workflowResultLines(beat.result); + return ( + }> + {beat.status === "failed" ? `${gt("failed")} · ${length}` : length} + {tries} + + ); + } + } +} + +function WorkflowAgentCard({ + environmentId, + beat, + open, + onOpenThread, +}: { + readonly environmentId: EnvironmentId; + readonly beat: WorkflowBeat; + readonly open: boolean; + readonly onOpenThread: (thread: WorkflowThreadTarget) => void; +}) { + const gt = useGT(); + const m = useMessages(); + const [all, setAll] = useState(false); + const elsewhere = beat.thread !== null && beat.thread.environmentId !== null; + const threadEnvironmentId = + beat.thread?.environmentId == null + ? environmentId + : EnvironmentId.make(beat.thread.environmentId); + // This client can only show a thread on an environment it is itself connected to. + const threadEnvironment = useEnvironment(threadEnvironmentId); + const shell = useQuietThreadShell( + beat.thread === null + ? null + : scopeThreadRef(threadEnvironmentId, ThreadId.make(beat.thread.threadId)), + ); + const provider = useEnvironmentProviders() + .get(threadEnvironmentId) + ?.find((candidate) => candidate.instanceId === shell?.modelSelection.instanceId); + const under = beat.status === "running"; + const length = formatDuration(elapsedOf(beat)); + const summary = workflowAgentSummary(beat); + const start = summary.said === null ? null : workflowSaidStart(summary.said, SAID_SHOWN); + const liveWord = !under + ? null + : shell?.hasPendingUserInput === true + ? gt("Asks you", { $context: "a workflow step waits on a person's answer" }) + : shell?.hasPendingApprovals === true + ? gt("waits for your approval") + : shell?.runtime?.status === "preparing" || shell?.runtime?.status === "starting" + ? gt("starting") + : gt("working"); + const sub = [ + shell === null ? null : formatModelSlugName(shell.modelSelection.model), + liveWord, + length, + beat.attempts > 1 ? nthTry(beat.attempts, m) : null, + elsewhere + ? gt("on {environment}", { environment: threadEnvironment?.label ?? threadEnvironmentId }) + : null, + ] + .filter((part) => part !== null) + .join(" · "); + return ( + + + ) : ( + + ) + } + name={beat.name} + sub={sub} + action={ + beat.thread === null ? null : threadEnvironment === null ? ( + + + Thread on {threadEnvironmentId} + + + ) : ( + + ) + } + /> + {beat.status === "failed" && beat.detail ? ( +

    + + {beat.detail} +

    + ) : null} + {summary.said === null ? null : ( + // Set off from the head, so headings in the reply read as the agent's, not the page's. +
    + + {start !== null ? ( + + ) : null} +
    + )} + {summary.facts.length === 0 ? null : } +
    + ); +} + +function WorkflowPauseCard({ + run, + name, + attempts, + reason, + nowMs, + disabled, + onResume, + kept, +}: { + readonly run: WorkflowRun; + /** The step it stopped at, when the steps say which. */ + readonly name: string | null; + readonly attempts: number; + readonly reason: string | null; + readonly nowMs: number; + readonly disabled: boolean; + readonly onResume: () => void; + /** Steps before it finished, and resuming keeps them. */ + readonly kept: boolean; +}) { + const gt = useGT(); + const m = useMessages(); + const resumes = run.resumesAt === null ? Number.NaN : Date.parse(run.resumesAt); + const next = run.retired + ? gt("cannot go on until its workflow version is registered again") + : !Number.isFinite(resumes) + ? gt("waits for you to resume it") + : resumes > nowMs + ? gt("tries again by itself in {duration}", { duration: formatDuration(resumes - nowMs) }) + : gt("about to try again by itself"); + return ( + + } + name={ + name === null + ? gt("Paused", { $context: "a workflow run is paused" }) + : gt("Paused at {step}", { step: name }) + } + sub={ + <> + {attempts > 0 ? `${nthTry(attempts, m)} · ` : null} + · {next} + + } + action={ + + } + /> + {reason ?

    {reason}

    : null} + {kept ? ( +

    + Only the failed step runs again; what finished before it is kept. +

    + ) : null} +
    + ); +} + +function WorkflowQuestionCard({ + environmentId, + question, + onOpenThread, + inline = false, +}: { + readonly environmentId: EnvironmentId; + readonly question: WorkflowQuestion; + readonly onOpenThread: (thread: WorkflowThreadTarget) => void; + /** Under its step in the run, which already says that it asks. */ + readonly inline?: boolean; +}) { + const gt = useGT(); + const view = readWorkflowQuestion(question); + const drafts = useContext(AnswerDrafts); + const [ownReason, setOwnReason] = useState(null); + const draftKey = `${question.runId}:${question.name}:${question.askedAt}`; + const reason = drafts === null ? ownReason : drafts.get(draftKey); + const setReason = (next: string | null) => + drafts === null ? setOwnReason(next) : drafts.set(draftKey, next); + const [busy, setBusy] = useState(false); + const canAnswer = useAtomValue( + serverEnvironment.answerWorkflowQuestion.permissionAtom(environmentId), + ); + const answer = useAtomCommand(serverEnvironment.answerWorkflowQuestion, { + label: "workflow answer", + }); + const threadEnvironmentId = + question.thread?.environmentId == null + ? environmentId + : EnvironmentId.make(question.thread.environmentId); + const reachable = useEnvironment(threadEnvironmentId) !== null; + const choose = async (choice: string) => { + if (busy) return; + setBusy(true); + const given = reason?.trim() ?? ""; + const result = await answer({ + environmentId, + input: { + runId: question.runId, + name: question.name, + choice, + ...(given === "" ? {} : { reason: given }), + }, + }); + setBusy(false); + reportFailure(gt("Could not answer the question"), result); + }; + return ( + + {inline ? null : ( +

    + + Needs you + + + + asked{" "} + + + {" "} + · the run waits for you + + +

    + )} +

    + {view.title} +

    + {view.body ? ( + + ) : null} +
    + {view.choices.map((choice, index) => ( + + ))} +
    + {reason === null || (question.thread !== null && reachable) ? ( +
    + {reason === null ? ( + + ) : null} + {question.thread === null || !reachable ? null : ( + + )} +
    + ) : null} + {reason === null ? null : ( +
    + setReason(event.currentTarget.value)} + /> +
    + )} +
    + ); +} diff --git a/apps/web/src/components/workflows/WorkflowRunsView.browser.test.tsx b/apps/web/src/components/workflows/WorkflowRunsView.browser.test.tsx new file mode 100644 index 0000000000000..386ba513e0e5b --- /dev/null +++ b/apps/web/src/components/workflows/WorkflowRunsView.browser.test.tsx @@ -0,0 +1,477 @@ +import { Atom } from "effect/reactivity"; +import { + EnvironmentId, + type WorkflowQuestion, + type WorkflowRun, + type WorkflowRunReference, + type WorkflowRunsSnapshot, + type WorkflowStep, +} from "@t3tools/contracts"; +import { describe, expect, it, vi } from "vite-plus/test"; +import { page as browserPage, userEvent } from "vite-plus/test/browser"; + +import "~/index.css"; +import { render } from "../../../test/render"; +import type { WorkflowPaneTab } from "./workflowPane.logic"; +import { WorkflowRunsView } from "./WorkflowRunsView"; + +const environmentId = EnvironmentId.make("laptop"); +const at = (minute: number) => new Date(Date.UTC(2026, 10, 1, 0, minute)).toISOString(); +const run = (fields: Partial & Pick): WorkflowRun => ({ + workflow: "release", + version: 1, + status: "running", + detail: null, + result: null, + pauses: 0, + retired: false, + resumesAt: null, + parentRunId: null, + parentStep: null, + startedAt: at(0), + updatedAt: at(5), + endedAt: null, + ...fields, +}); +const step = ( + fields: Partial & Pick, +): WorkflowStep => ({ + status: "completed", + attempts: 1, + detail: null, + threadId: null, + environmentId: null, + result: null, + said: null, + startedAt: at(0), + endedAt: at(0), + ...fields, +}); + +const state = vi.hoisted(() => ({ + live: { query: "live" }, + snapshot: { workflows: [], runs: [], questions: [] } as { + workflows: ReadonlyArray; + runs: ReadonlyArray; + questions: ReadonlyArray; + }, + steps: {} as Record>, + references: {} as Record>, + commands: [] as Array, + permitted: true, + detailError: null as string | null, +})); +const canOperate = Atom.make(true); +const cannotOperate = Atom.make(false); + +function setup( + given: Omit & Partial>, + steps: Record> = {}, + references: Record> = {}, +) { + state.snapshot = { workflows: [], ...given }; + state.steps = steps; + state.references = references; + state.commands = []; + state.permitted = true; + state.detailError = null; +} + +const environment = { environmentId, label: "Laptop" }; + +vi.mock(import("../../state/server"), async (original) => { + const actual = await original(); + const permissionAtom = () => (state.permitted ? canOperate : cannotOperate); + return { + ...actual, + serverEnvironment: { + ...actual.serverEnvironment, + workflowsLive: (() => state.live) as never, + workflowRun: ((target: { readonly input: { readonly runId: string } }) => + target.input) as never, + answerWorkflowQuestion: { + ...actual.serverEnvironment.answerWorkflowQuestion, + permissionAtom, + }, + resumeWorkflowRun: { ...actual.serverEnvironment.resumeWorkflowRun, permissionAtom }, + cancelWorkflowRun: { ...actual.serverEnvironment.cancelWorkflowRun, permissionAtom }, + }, + }; +}); +// Stands in for the live list and for one run's detail, which the mocked atoms above name. +vi.mock(import("../../state/query"), async (original) => ({ + ...(await original()), + useEnvironmentQuery: ((request: { readonly runId?: string }) => ({ + data: + request === state.live + ? state.snapshot + : state.detailError !== null + ? null + : { + run: null, + steps: state.steps[request.runId ?? ""] ?? [], + references: state.references[request.runId ?? ""] ?? [], + }, + error: request === state.live ? null : state.detailError, + isPending: false, + refresh: vi.fn(), + })) as never, +})); +vi.mock(import("../../state/use-atom-command"), async (original) => ({ + ...(await original()), + useAtomCommand: ((_command: unknown, options: { readonly label: string }) => + (value: { readonly input: unknown }) => { + state.commands.push([options.label, value.input]); + return Promise.resolve({ _tag: "Success", value: undefined }); + }) as never, +})); +vi.mock(import("../../state/environments"), async (original) => ({ + ...(await original()), + useEnvironment: ((id: EnvironmentId | null) => + id === environmentId ? environment : null) as never, +})); +// The chat's renderer loads its highlighter; a question's body only has to reach the page. +vi.mock("../ChatMarkdown", () => ({ + default: ({ text }: { readonly text: string }) =>
    {text}
    , +})); + +const question: WorkflowQuestion = { + runId: "ship", + name: "approve", + request: { + title: "Ship release 1.2?", + choices: ["Ship", "Hold"], + data: { body: "The diff touches the installer." }, + }, + askedAt: at(4), + thread: { threadId: "thread-9", environmentId: null }, +}; + +const issue101: WorkflowRunReference = { + kind: "issue", + key: "i101", + address: { projectId: "p1", tracker: "github", scope: "me/app", key: "101" }, + title: "Wrong minutes", + url: "https://github.com/me/app/issues/101", + state: "open", + steps: ["triage"], + origin: "trigger", +}; + +/** Wide enough for the list and the run side by side; put back when the test ends. */ +async function desktop() { + const width = window.innerWidth; + const height = window.innerHeight; + await browserPage.viewport(1280, 800); + return { [Symbol.asyncDispose]: () => browserPage.viewport(width, height) }; +} + +const page = ( + selectedRunId: string | null = null, + on: { + readonly select?: (runId: string | null) => void; + readonly thread?: () => void; + readonly reference?: () => void; + } = {}, + shownTab: WorkflowPaneTab | null = null, +) => ( + +); + +describe("WorkflowRunsView", () => { + it("opens on the question that waits, and answers it with the reason given", async () => { + setup( + { + runs: [ + run({ runId: "busy", title: "Nightly sync" }), + run({ runId: "ship", title: "Release 1.2", status: "waiting", detail: "approve" }), + ], + questions: [question], + }, + { ship: [step({ name: "approve", kind: "ask", status: "running", endedAt: null })] }, + ); + const thread = vi.fn(); + await using _desktop = await desktop(); + await using screen = await render(page(null, { thread })); + + // The list opens on what waits on a person, and the run that asks is the one shown. + const runs = screen.getByRole("navigation", { name: "Workflow runs" }); + await expect.element(runs.getByRole("button", { name: /Release 1\.2/ })).toBeVisible(); + await expect + .element(runs.getByRole("button", { name: /Nightly sync/ })) + .not.toBeInTheDocument(); + await expect.element(runs).toMatchTextContent("Asks: Ship release 1.2?"); + await expect.element(screen.getByText("The diff touches the installer.")).toBeVisible(); + + await screen.getByRole("button", { name: "Ask the agent first" }).click(); + expect(thread).toHaveBeenCalledWith("ship", { threadId: "thread-9", environmentId: null }); + + await screen.getByRole("button", { name: "Add a reason" }).click(); + await userEvent.fill( + screen.getByRole("textbox", { name: "Reason for Ship release 1.2?" }), + " Too risky today ", + ); + await screen.getByRole("button", { name: "Hold", exact: true }).click(); + + await vi.waitFor(() => + expect(state.commands).toEqual([ + [ + "workflow answer", + { runId: "ship", name: "approve", choice: "Hold", reason: "Too risky today" }, + ], + ]), + ); + }); + + it("answers a question whose steps did not load, and says a linked run is not here", async () => { + setup({ + runs: [run({ runId: "ship", title: "Release 1.2", status: "waiting", detail: "approve" })], + questions: [question], + }); + state.detailError = "The server did not answer."; + await using _desktop = await desktop(); + { + await using screen = await render(page("ship")); + await expect.element(screen.getByText("The server did not answer.")).toBeVisible(); + await screen.getByRole("button", { name: "Ship", exact: true }).click(); + await vi.waitFor(() => + expect(state.commands).toEqual([ + ["workflow answer", { runId: "ship", name: "approve", choice: "Ship" }], + ]), + ); + } + + // A link to a run this environment does not have never shows another run in its place. + const select = vi.fn(); + await using screen = await render(page("gone", { select })); + await expect.element(screen.getByText("This run is not here")).toBeVisible(); + await expect + .element(screen.getByRole("button", { name: "Ship", exact: true })) + .not.toBeInTheDocument(); + await screen.getByRole("button", { name: "Back to the runs" }).click(); + expect(select).toHaveBeenCalledWith(null); + }); + + it("says a linked run is not here where nothing has run yet", async () => { + setup({ runs: [], questions: [] }); + const select = vi.fn(); + await using screen = await render(page("gone", { select })); + await expect.element(screen.getByText("This run is not here")).toBeVisible(); + await screen.getByRole("button", { name: "Back to the runs" }).click(); + expect(select).toHaveBeenCalledWith(null); + }); + + it("turns the answers off for a session that may not operate", async () => { + setup({ + runs: [run({ runId: "ship", title: "Release 1.2", status: "waiting" })], + questions: [question], + }); + state.permitted = false; + await using _desktop = await desktop(); + await using screen = await render(page()); + + await expect.element(screen.getByRole("button", { name: "Ship", exact: true })).toBeDisabled(); + await expect.element(screen.getByRole("button", { name: "Hold", exact: true })).toBeDisabled(); + }); + + it("says why a run paused at the step that failed, and resumes it", async () => { + setup( + { + runs: [ + run({ + runId: "sync", + title: "Sync labels", + status: "paused", + detail: "apply: 503", + pauses: 1, + }), + ], + questions: [], + }, + { + sync: [ + // A failure the workflow caught and went on from is not where it paused. + step({ name: "lint", kind: "step", status: "failed", endedAt: at(1), detail: "lint" }), + step({ name: "fetch", kind: "step", startedAt: at(1), endedAt: at(1) }), + step({ + name: "apply", + kind: "agent", + status: "failed", + attempts: 3, + detail: "503", + threadId: "thread-apply", + startedAt: at(2), + endedAt: at(3), + }), + ], + }, + ); + await using _desktop = await desktop(); + await using screen = await render(page()); + + const why = screen.getByRole("region", { name: "Why it paused" }); + await expect.element(why).toMatchTextContent(/Paused at apply.*3rd try.*waits for you/); + await expect.element(why).toMatchTextContent("503"); + // The failed agent's transcript is there to read before choosing. + await expect.element(screen.getByRole("button", { name: "Transcript" })).toBeVisible(); + await expect.element(screen.getByText("Paused at lint")).not.toBeInTheDocument(); + await why.getByRole("button", { name: "Resume" }).click(); + + await vi.waitFor(() => + expect(state.commands).toEqual([["workflow resume", { runId: "sync" }]]), + ); + }); + + it("draws a finished run as a flow, and shows the step that is picked", async () => { + setup( + { + runs: [ + run({ + runId: "fix", + title: "#101 Wrong minutes", + status: "completed", + result: "merged as ba6ac7", + endedAt: at(12), + }), + ], + questions: [], + }, + { + fix: [ + step({ name: "load", kind: "step" }), + step({ name: "existing-prs", kind: "step" }), + step({ + name: "triage", + kind: "agent", + endedAt: at(3), + threadId: "thread-1", + said: "Reproduced on main.", + result: { kind: "bug", reproduced: true }, + }), + step({ + name: "implement", + kind: "agent", + startedAt: at(3), + endedAt: at(10), + threadId: "thread-2", + environmentId: "build-box", + }), + step({ + name: "approve", + kind: "ask", + startedAt: at(10), + endedAt: at(11), + result: { choice: "Fix it", reason: "It hits everyone on Windows" }, + }), + ], + }, + { fix: [issue101] }, + ); + const thread = vi.fn(); + const reference = vi.fn(); + await using screen = await render(page("fix", { thread, reference }, { thread: "thread-1" })); + + // A finished run opens on how it ended; the flow has a node for each step that mattered. + const happened = screen.getByRole("region", { name: "What happened" }); + await expect.element(happened).toMatchTextContent(/Finished.*merged as ba6ac7/); + const flow = screen.getByRole("navigation", { name: "Steps so far" }); + await expect + .element(flow) + .toMatchTextContent(/load · existing-prs.*triage.*Reproduced on main\..*implement.*approve/); + + await flow.getByRole("button", { name: /triage/ }).click(); + const triage = screen.getByRole("region", { name: "triage" }); + await expect.element(triage).toMatchTextContent(/3m 0s.*Reproduced on main\..*kind.*bug/); + // Its thread is the one open beside the run, and the button says so. + const transcript = triage.getByRole("button", { name: "Transcript" }); + await expect.element(transcript).toHaveAttribute("aria-pressed", "true"); + await transcript.click(); + expect(thread).toHaveBeenCalledWith("fix", { threadId: "thread-1", environmentId: null }); + // What the run touched is under its title, by number alone when the title already says it. + // It opens beside the run. + const touched = screen.getByRole("list", { name: "What the run touched" }); + const onRun = touched.getByRole("button", { name: "#101 Wrong minutes" }); + await expect.element(onRun).toMatchTextContent(/^#101$/); + await onRun.click(); + expect(reference).toHaveBeenCalledWith("fix", issue101); + // This client is not connected to the linked environment, so there is nothing to open. + await flow.getByRole("button", { name: /implement/ }).click(); + await expect + .element(screen.getByRole("region", { name: "implement" })) + .toMatchTextContent("Thread on build-box"); + await flow.getByRole("button", { name: /approve/ }).click(); + await expect + .element(screen.getByRole("region", { name: "approve" })) + .toMatchTextContent("You said Fix it: It hits everyone on Windows"); + await flow.getByRole("button", { name: /load · existing-prs/ }).click(); + await expect + .element(screen.getByRole("region", { name: "Quick steps" })) + .toMatchTextContent("loadexisting-prs"); + await expect + .element(screen.getByRole("button", { name: "Cancel run" })) + .not.toBeInTheDocument(); + }); + + it("opens an invoked run from its parent's story", async () => { + setup( + { + runs: [ + run({ runId: "rel", title: "Release 1.3", status: "waiting", detail: "check" }), + run({ runId: "chk", title: "Check web", parentRunId: "rel", parentStep: "check" }), + ], + questions: [], + }, + { + rel: [ + step({ name: "check/start", kind: "step" }), + step({ name: "check", kind: "wait", status: "running", endedAt: null }), + ], + }, + ); + const select = vi.fn(); + await using screen = await render(page("rel", { select })); + + const invoked = screen.getByRole("region", { name: "Check web" }); + await invoked.getByRole("button", { name: "Open run" }).click(); + expect(select).toHaveBeenCalledWith("chk"); + }); + + it("switches between what is under way and everything, one workflow at a time", async () => { + setup({ + workflows: [ + { name: "release", version: 1, triggers: ["webhook tags"] }, + { name: "report", version: 1, triggers: ["daily at 09:00"] }, + ], + runs: [ + run({ runId: "rel", title: "Release 1.3" }), + run({ runId: "old", title: "Release 1.2", status: "completed", endedAt: at(3) }), + ], + questions: [], + }); + await using _desktop = await desktop(); + await using screen = await render(page()); + + const runs = screen.getByRole("navigation", { name: "Workflow runs" }); + await expect.element(runs.getByRole("button", { name: /Release 1\.3/ })).toBeVisible(); + await expect + .element(runs.getByRole("button", { name: /Release 1\.2/ })) + .not.toBeInTheDocument(); + await screen.getByRole("button", { name: "All", exact: true }).click(); + await expect.element(runs.getByRole("button", { name: /Release 1\.2/ })).toBeVisible(); + + // A workflow that has not run is still there to be picked, with what starts it. + await screen.getByRole("combobox", { name: "Workflow" }).click(); + await screen.getByRole("option", { name: "report" }).click(); + await expect.element(screen.getByText("Starts on daily at 09:00")).toBeVisible(); + await expect.element(runs).toMatchTextContent("Has not run yet."); + }); +}); diff --git a/apps/web/src/components/workflows/WorkflowRunsView.tsx b/apps/web/src/components/workflows/WorkflowRunsView.tsx new file mode 100644 index 0000000000000..4c43539b1e1e3 --- /dev/null +++ b/apps/web/src/components/workflows/WorkflowRunsView.tsx @@ -0,0 +1,384 @@ +import { type EnvironmentId, type WorkflowRunReference } from "@t3tools/contracts"; +import { msg, T, useGT, useMessages } from "gt-react"; +import { WorkflowIcon } from "lucide-react"; +import { useState, type ReactNode } from "react"; + +import { cn } from "../../lib/utils"; +import { useEnvironmentQuery } from "../../state/query"; +import { serverEnvironment } from "../../state/server"; +import { Button } from "../ui/button"; +import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "../ui/empty"; +import { ScrollArea } from "../ui/scroll-area"; +import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; +import { Toggle, ToggleGroup } from "../ui/toggle-group"; +import { + RelativeLabel, + WorkflowChip, + WorkflowRunFeed, + WorkflowStateWord, + type WorkflowThreadTarget, +} from "./WorkflowRunFeed"; +import type { WorkflowPaneTab } from "./workflowPane.logic"; +import { + allWorkflowRunNodes, + defaultWorkflowListTab, + defaultWorkflowRunId, + groupWorkflowRuns, + listedWorkflowRuns, + workflowRunLists, + workflowRunNow, + workflowTriggerLine, + type WorkflowListTab, + type WorkflowRunNode, + workflowRunInvolves, +} from "@t3tools/client-runtime/workflows"; + +const WORKFLOWS_GUIDE_URL = "https://github.com/pingdotgg/t3code/blob/main/docs/user/workflows.md"; +const EVERY_WORKFLOW = ""; +const TABS: ReadonlyArray<{ readonly value: WorkflowListTab; readonly label: string }> = [ + { + value: "needs-you", + label: msg("Needs you", { $context: "tab: workflow runs that wait on the user" }), + }, + { value: "running", label: msg("Running", { $context: "tab: workflow runs under way" }) }, + { value: "all", label: msg("All", { $context: "tab: every workflow run" }) }, +]; +const NOTHING: Record = { + "needs-you": msg("Nothing waits on you."), + running: msg("Nothing is running."), + all: msg("No runs yet."), +}; + +export function WorkflowsEmpty({ + title, + description, +}: { + readonly title: string; + readonly description: ReactNode; +}) { + return ( +
    + + + + + + {title} + {description} + + +
    + ); +} + +/** One environment's runs: the list to pick from, and the picked run told as a feed. */ +export function WorkflowRunsView({ + environmentId, + selectedRunId, + paneOpen, + shownTab, + onSelect, + onOpenThread, + onOpenReference, + onOpenDefinitions, +}: { + readonly environmentId: EnvironmentId; + readonly selectedRunId: string | null; + /** Something is open beside the run, so the list makes room below `xl`. */ + readonly paneOpen: boolean; + /** What shows beside the run, so what opened it can say so. */ + readonly shownTab: WorkflowPaneTab | null; + readonly onSelect: (runId: string | null) => void; + readonly onOpenThread: (runId: string, thread: WorkflowThreadTarget) => void; + readonly onOpenReference: (runId: string, reference: WorkflowRunReference) => void; + readonly onOpenDefinitions: () => void; +}) { + const live = useEnvironmentQuery(serverEnvironment.workflowsLive({ environmentId, input: {} })); + const [pickedTab, setPickedTab] = useState(null); + const [workflow, setWorkflow] = useState(EVERY_WORKFLOW); + const gt = useGT(); + const m = useMessages(); + const [showSkipped, setShowSkipped] = useState(false); + const snapshot = live.data; + if (live.error) { + return ; + } + if (!snapshot) { + return ( +

    + Loading workflow runs… +

    + ); + } + // A broken file is said even where nothing has run, or its workflows would just seem missing. + const problemAlert = + snapshot.definition?.problem == null ? null : ( +
    + + + + A workflow file has a problem. + {" "} + The last version that did keeps running. + + + +
    + ); + const withProblem = (empty: ReactNode) => + problemAlert === null ? ( + empty + ) : ( +
    + {problemAlert} + {empty} +
    + ); + const notHere = ( + + This environment has no run with that link.{" "} + + + } + /> + ); + // A link to a run says it is not here, even where nothing has run at all. + if (snapshot.runs.length === 0 && snapshot.workflows.length === 0 && selectedRunId !== null) { + return withProblem(notHere); + } + if (snapshot.runs.length === 0 && snapshot.workflows.length === 0) { + return withProblem( + + A workflow ties agents, code, schedules and questions to you into one run that survives + restarts. Write one under{" "} + + , or ask an agent to.{" "} +
    + Read the guide + + + } + />, + ); + } + // A skipped run opened by its link is shown all the same. + const openedSkipped = snapshot.runs.some( + (run) => run.runId === selectedRunId && run.status === "skipped", + ); + const visible = listedWorkflowRuns(snapshot.runs, showSkipped || openedSkipped); + const groups = groupWorkflowRuns(snapshot.workflows, visible.runs, snapshot.questions); + const lists = workflowRunLists(groups); + const all = allWorkflowRunNodes(groups); + const section = groups.workflows.find((candidate) => candidate.name === workflow) ?? null; + // A run the address names is that run or none: another one's buttons would act on the wrong run. + const shownRunId = + selectedRunId === null + ? defaultWorkflowRunId(groups) + : (all.find((node) => node.run.runId === selectedRunId)?.run.runId ?? null); + const shown = all.find((node) => node.run.runId === shownRunId) ?? null; + // A run that another invoked is not in the list itself; the one it is part of stands for it. + const listedFor = (node: WorkflowRunNode | null): string | null => { + if (node === null) return null; + const parent = all.find((candidate) => candidate.run.runId === node.run.parentRunId); + return parent === undefined ? node.run.runId : listedFor(parent); + }; + const currentRunId = listedFor(shown); + // A run opened by its link is shown in a list that has it, so the list never points at nothing. + const opening = defaultWorkflowListTab(groups); + const holds = (candidate: WorkflowListTab) => + lists[candidate].some((node) => node.run.runId === currentRunId); + const tab = + pickedTab ?? + (selectedRunId === null || holds(opening) ? opening : holds("running") ? "running" : "all"); + const listed = lists[tab].filter( + (node) => section === null || workflowRunInvolves(node, section.name), + ); + return ( +
    + {problemAlert} +
    + {/* Below md there is room for one of the two: the list, or the run picked from it. */} +
    +
    + { + const value = TABS.find((candidate) => candidate.value === next[0]); + if (value !== undefined) setPickedTab(value.value); + }} + > + {TABS.map(({ value, label }) => ( + + {m(label)} + + ))} + + {groups.workflows.length > 1 ? ( + + ) : null} + {section === null ? null : ( +

    + {workflowTriggerLine(section, m)} +

    + )} +
    + + + +
    + + {shown === null ? ( + selectedRunId === null ? null : ( + notHere + ) + ) : ( + node.run.runId === shown.run.parentRunId)?.run ?? null} + shownTab={shownTab} + onSelect={onSelect} + onOpenThread={(thread) => onOpenThread(shown.run.runId, thread)} + onOpenReference={(reference) => onOpenReference(shown.run.runId, reference)} + /> + )} + +
    +
    + ); +} + +/** A run in the thread list's own shape: which workflow, its state in a word, and what it is at. */ +function WorkflowRunListItem({ + node, + current, + onSelect, +}: { + readonly node: WorkflowRunNode; + readonly current: boolean; + readonly onSelect: (runId: string | null) => void; +}) { + const { run } = node; + const m = useMessages(); + return ( +
    + {links.length ? ( + + ) : null} ); } @@ -161,6 +246,7 @@ export default function PdfViewer(props: { positionKey?: string; initialView?: PdfViewState; onViewChange?: (view: PdfViewState) => void; + onOpenLink?: (url: string, event: MouseEvent) => void; actions?: ReactNode; }) { const gt = useGT(); @@ -527,6 +613,8 @@ export default function PdfViewer(props: { query={query} onSize={onSize} onError={setError} + onPageLink={showPage} + onOpenLink={props.onOpenLink} />
  • + +
  • + ); +} diff --git a/apps/web/src/components/workflows/WorkflowThreadPane.tsx b/apps/web/src/components/workflows/WorkflowThreadPane.tsx new file mode 100644 index 0000000000000..7e6432eaec393 --- /dev/null +++ b/apps/web/src/components/workflows/WorkflowThreadPane.tsx @@ -0,0 +1,65 @@ +import { type ScopedThreadRef } from "@t3tools/contracts"; +import { useNavigate } from "@tanstack/react-router"; +import { useGT } from "gt-react"; + +import { ComposerHandleContext } from "../../composerHandleContext"; +import type { SideChatParentPanel } from "../../lib/sideChatPane"; +import { useQuietThreadShell } from "../../state/entities"; +import { useEnvironmentShellHasSnapshot } from "../../state/shell"; +import { buildThreadRouteParams } from "../../threadRoutes"; +import ChatView from "../ChatView"; +import { BackgroundThreadContext } from "../chat/backgroundThread"; + +/** Opens the thread as a full thread view. */ +export function useOpenThreadPage(): (threadRef: ScopedThreadRef) => void { + const navigate = useNavigate(); + return (threadRef) => + void navigate({ to: "/$environmentId/$threadId", params: buildThreadRouteParams(threadRef) }); +} + +/** What a transcript's tab is called: the step its agent did, or the thread's own title. */ +export function WorkflowThreadTabLabel({ threadRef }: { readonly threadRef: ScopedThreadRef }) { + const gt = useGT(); + const shell = useQuietThreadShell(threadRef); + const step = shell?.workflowRun?.step; + return step === undefined + ? (shell?.title ?? gt("Agent", { $context: "fallback title of a coding agent's thread" })) + : gt("{step} · transcript", { step, $context: "tab: the agent thread of a workflow step" }); +} + +/** + * An agent step's thread beside its run: the same chat as anywhere, composer included, so a + * person can read what the agent did and talk to it without leaving the run. + */ +export default function WorkflowThreadPane({ threadRef }: { readonly threadRef: ScopedThreadRef }) { + const gt = useGT(); + const openThreadPage = useOpenThreadPage(); + const shell = useQuietThreadShell(threadRef); + const snapshotLoaded = useEnvironmentShellHasSnapshot(threadRef.environmentId); + const openFull = () => openThreadPage(threadRef); + // The diff panel and the terminal drawer belong to the full thread view, so both lead there. + const panel: SideChatParentPanel = { + hostRef: threadRef, + openToolDiff: openFull, + runShellCommand: openFull, + }; + return shell === null ? ( +

    + {snapshotLoaded ? gt("This thread is no longer there.") : gt("Loading the thread…")} +

    + ) : ( + // The attribute is how the embedded chat knows the keyboard is meant for it. +
    + + + + + +
    + ); +} diff --git a/apps/web/src/components/workflows/WorkflowsPage.tsx b/apps/web/src/components/workflows/WorkflowsPage.tsx new file mode 100644 index 0000000000000..7c42a4d00080a --- /dev/null +++ b/apps/web/src/components/workflows/WorkflowsPage.tsx @@ -0,0 +1,328 @@ +import { EnvironmentId, type WorkflowRunReference } from "@t3tools/contracts"; +import { Link, useNavigate, useSearch } from "@tanstack/react-router"; +import { T, useGT } from "gt-react"; +import { FileCode2Icon } from "lucide-react"; +import { lazy, Suspense, useState, type MouseEvent } from "react"; + +import { isElectron } from "~/env"; +import { type FileContextMenuAction, useFileContextMenu } from "../../fileContextMenu"; +import { cn } from "../../lib/utils"; +import { readLocalApi } from "../../localApi"; +import { useEnvironmentQuery } from "../../state/query"; +import { serverEnvironment } from "../../state/server"; +import { + useConnectedEnvironmentIds, + useEnvironments, + usePrimaryEnvironmentId, +} from "../../state/environments"; +import { useWorkflowEnvironmentIds } from "./useWorkflowEnvironmentIds"; +import { Button } from "../ui/button"; +import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; +import { SidebarInset } from "../ui/sidebar"; +import { + WorkspaceBreadcrumb, + WorkspaceBreadcrumbItem, + WorkspaceBreadcrumbSeparator, + WorkspaceBreadcrumbText, +} from "../WorkspaceBreadcrumb"; +import { WorkspacePageHeader } from "../WorkspacePageHeader"; +import { WorkflowRunsView, WorkflowsEmpty } from "./WorkflowRunsView"; +import WorkflowPane from "./WorkflowPane"; +import { + activeWorkflowPaneTab, + toggleWorkflowPaneTab, + type WorkflowPaneState, +} from "./workflowPane.logic"; + +const COPY_PATH = "copy-path"; + +// The editor brings the code view's highlighter with it, which the run list has no use for. +const WorkflowDefinitionEditor = lazy(() => import("./WorkflowDefinitionEditor")); + +export interface WorkflowsSearch extends WorkflowPaneState { + readonly env?: string; + readonly run?: string; + /** Show the definition files instead of the runs: all of them, or `file` in the editor. */ + readonly definitions?: boolean; + readonly file?: string; +} + +export function WorkflowsPage() { + const search = useSearch({ from: "/_chat/workflows" }); + const navigate = useNavigate(); + const gt = useGT(); + const primaryEnvironmentId = usePrimaryEnvironmentId(); + const connectedIds = useConnectedEnvironmentIds(); + const { environments } = useEnvironments(); + const workflowIds = useWorkflowEnvironmentIds(); + // Only servers with workflows on in Labs can be picked; a connected one with them off says so. + const connected = environments.filter((environment) => + workflowIds.includes(environment.environmentId), + ); + const asked = search.env === undefined ? null : EnvironmentId.make(search.env); + const turnedOff = + asked === null + ? workflowIds.length === 0 && connectedIds.length > 0 + : connectedIds.includes(asked) && !workflowIds.includes(asked); + // An environment the address names is kept while it is away: its run and file mean nothing on + // another server. + const environmentId = + asked !== null + ? (connected.find((environment) => environment.environmentId === asked)?.environmentId ?? + null) + : (connected.find((environment) => environment.environmentId === primaryEnvironmentId) + ?.environmentId ?? + connected[0]?.environmentId ?? + null); + const select = (next: WorkflowsSearch) => + void navigate({ to: "/workflows", search: next, replace: true }); + // A level of the page, which the browser's Back should step out of again. + const go = (next: WorkflowsSearch) => void navigate({ to: "/workflows", search: next }); + // Opening a run or file pins the environment it is on, so the same address never means another. + const pinned = environmentId ?? search.env; + const env = pinned === undefined ? {} : { env: pinned }; + const away = + asked !== null && environmentId === null && !turnedOff + ? (environments.find((environment) => environment.environmentId === asked)?.label ?? asked) + : null; + const run = search.run === undefined ? {} : { run: search.run }; + const editing = search.definitions === true || search.file !== undefined; + // An open file stays open while its environment is away, so a draft in it is not lost. + const fileEnvironmentId = + environmentId ?? (search.file === undefined || turnedOff ? null : asked); + const [fileActions, setFileActions] = useState(null); + const definitions = useEnvironmentQuery( + fileEnvironmentId === null || search.file === undefined + ? null + : serverEnvironment.workflowDefinition({ environmentId: fileEnvironmentId, input: {} }), + ); + const fileMenu = useFileContextMenu(fileEnvironmentId); + /** What a right click on the open file's name offers: its path, and the editors on that machine. */ + const showFileMenu = (event: MouseEvent) => { + const api = readLocalApi(); + const directory = definitions.data?.directory; + if (api === undefined || directory === undefined || search.file === undefined) return; + event.preventDefault(); + const path = `${directory}/${search.file}`; + const target = { environmentId: fileEnvironmentId, filePath: path, workspaceRoot: undefined }; + void api.contextMenu + .show([{ id: COPY_PATH, label: gt("Copy path") }, ...fileMenu.buildItems(target)], { + x: event.clientX, + y: event.clientY, + }) + .then((picked) => { + if (picked === null) return; + if (picked === COPY_PATH) return void navigator.clipboard.writeText(path); + return fileMenu.activate(picked as FileContextMenuAction, target); + }); + }; + // The run stays in the address, so the breadcrumb back to the runs reopens it. + const openDefinitions = (file: string | null) => + go({ ...env, ...run, definitions: true, ...(file === null ? {} : { file }) }); + // What is open beside the run, which belongs to the run: picking another one closes it. + const pane: WorkflowPaneState = + environmentId === null || editing || search.pane === undefined + ? {} + : search.tab === undefined + ? { pane: search.pane } + : { pane: search.pane, tab: search.tab }; + const paneOpen = pane.pane !== undefined; + const shownTab = activeWorkflowPaneTab(pane); + // Opening something pins the run it is from, so the address keeps naming the run it belongs to. + const togglePane = (runId: string, tab: Parameters[1]) => + select({ ...env, run: runId, ...toggleWorkflowPaneTab(pane, tab) }); + + return ( + +
    + {/* Below md there is room for one thing, and an open pane is that thing. */} +
    + + + + {editing ? ( + + ) : ( +

    + Workflows +

    + )} +
    + {editing ? ( + <> + + / + + + {search.file === undefined ? ( +

    + Definitions +

    + ) : ( + + )} +
    + + ) : null} + {search.file === undefined ? null : ( + <> + + / + + +

    + + {search.file} + +

    +
    + + )} +
    + {(connected.length > 1 && environmentId !== null) || + ((away !== null || turnedOff) && connected.length > 0) ? ( + + ) : null} + {search.file === undefined ? null : ( +
    + )} + {environmentId === null || editing ? null : ( + + )} + + {editing && fileEnvironmentId !== null ? ( + + Loading the editor… +

    + } + > + +
    + ) : away !== null ? ( + + ) : turnedOff ? ( + + Turn them on for this server in{" "} + + Settings → Labs + + . + + } + /> + ) : environmentId === null ? ( + + ) : ( + openDefinitions(null)} + environmentId={environmentId} + selectedRunId={search.run ?? null} + paneOpen={paneOpen} + shownTab={shownTab} + onSelect={(runId) => select({ ...env, ...(runId === null ? {} : { run: runId }) })} + onOpenThread={(runId, thread) => + togglePane(runId, { + thread: thread.threadId, + ...(thread.environmentId === null ? {} : { env: thread.environmentId }), + }) + } + onOpenReference={(runId, reference: WorkflowRunReference) => + togglePane(runId, { kind: reference.kind, key: reference.key }) + } + /> + )} +
    + {environmentId === null || !paneOpen ? null : ( + + )} +
    + + ); +} diff --git a/apps/web/src/components/workflows/useWorkflowEnvironmentIds.ts b/apps/web/src/components/workflows/useWorkflowEnvironmentIds.ts new file mode 100644 index 0000000000000..9a8bd4a583b71 --- /dev/null +++ b/apps/web/src/components/workflows/useWorkflowEnvironmentIds.ts @@ -0,0 +1,11 @@ +import type { EnvironmentId } from "@t3tools/contracts"; + +import { useServerConfigs } from "../../state/entities"; +import { useConnectedEnvironmentIds } from "../../state/environments"; + +/** The connected environments whose server has workflows turned on in Labs. */ +export function useWorkflowEnvironmentIds(): ReadonlyArray { + const connectedIds = useConnectedEnvironmentIds(); + const configs = useServerConfigs(); + return connectedIds.filter((id) => configs.get(id)?.settings.workflowsEnabled === true); +} diff --git a/apps/web/src/components/workflows/workflowPane.logic.test.ts b/apps/web/src/components/workflows/workflowPane.logic.test.ts new file mode 100644 index 0000000000000..f9c9b54f926a2 --- /dev/null +++ b/apps/web/src/components/workflows/workflowPane.logic.test.ts @@ -0,0 +1,50 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + activeWorkflowPaneTab, + closeWorkflowPaneTab, + openWorkflowPaneTab, + readWorkflowPane, + toggleWorkflowPaneTab, + type WorkflowPaneState, +} from "./workflowPane.logic"; + +const issue = { kind: "issue", key: "i412" }; +const pullRequest = { kind: "pullRequest", key: "p418" }; +const transcript = { thread: "workflow:ab", env: "env-2" }; + +describe("the pane beside a run", () => { + it("reads back from the address only what it can, once", () => { + expect( + readWorkflowPane( + [issue, { kind: "issue" }, issue, transcript, { thread: "t1", env: 3 }, "x"], + "0", + ), + ).toEqual({ pane: [issue, transcript, { thread: "t1" }], tab: 0 }); + // The last tab shows unless the address says another; one it cannot have shows the last. + expect(readWorkflowPane([issue, pullRequest], 7)).toEqual({ pane: [issue, pullRequest] }); + expect(readWorkflowPane("nope", 0)).toEqual({}); + }); + + it("opens a tab once, shows it, and closing one shows the tab beside it", () => { + let state: WorkflowPaneState = {}; + state = openWorkflowPaneTab(state, issue); + state = openWorkflowPaneTab(state, pullRequest); + state = openWorkflowPaneTab(state, transcript); + expect(state).toEqual({ pane: [issue, pullRequest, transcript] }); + state = openWorkflowPaneTab(state, { ...issue }); + expect(state).toEqual({ pane: [issue, pullRequest, transcript], tab: 0 }); + state = closeWorkflowPaneTab(state, 0); + expect(activeWorkflowPaneTab(state)).toEqual(pullRequest); + // Closing one that does not show leaves the one that does. + state = closeWorkflowPaneTab(state, 1); + expect(state).toEqual({ pane: [pullRequest] }); + expect(closeWorkflowPaneTab(state, 0)).toEqual({}); + }); + + it("asking for the tab that shows closes it, and any other shows it", () => { + const open = { pane: [issue, transcript] }; + expect(toggleWorkflowPaneTab(open, transcript)).toEqual({ pane: [issue] }); + expect(toggleWorkflowPaneTab(open, issue)).toEqual({ pane: [issue, transcript], tab: 0 }); + }); +}); diff --git a/apps/web/src/components/workflows/workflowPane.logic.ts b/apps/web/src/components/workflows/workflowPane.logic.ts new file mode 100644 index 0000000000000..9cdbc4963423d --- /dev/null +++ b/apps/web/src/components/workflows/workflowPane.logic.ts @@ -0,0 +1,103 @@ +/** + * What is open beside a run: agent transcripts and the things the run touched, one tab each. It + * lives in the address, so a reload or a shared link opens the same tabs. + */ +export type WorkflowPaneTab = + /** An agent's thread, and the linked environment it is in when not the run's own. */ + | { readonly thread: string; readonly env?: string } + /** One of the run's references, by its kind and key. */ + | { readonly kind: string; readonly key: string }; + +export interface WorkflowPaneState { + readonly pane?: ReadonlyArray; + /** Which tab shows; the last one when it names none. */ + readonly tab?: number; +} + +// A link is typed into an address bar: what it holds is capped like the rest of the address. +const MOST_TABS = 12; +const LONGEST = 400; + +const text = (value: unknown): value is string => + typeof value === "string" && value !== "" && value.length <= LONGEST; + +function readTab(raw: unknown): WorkflowPaneTab | null { + if (typeof raw !== "object" || raw === null) return null; + const fields = raw as Readonly>; + if (text(fields.thread)) { + return text(fields.env) + ? { thread: fields.thread, env: fields.env } + : { thread: fields.thread }; + } + return text(fields.kind) && text(fields.key) ? { kind: fields.kind, key: fields.key } : null; +} + +const sameWorkflowPaneTab = (left: WorkflowPaneTab, right: WorkflowPaneTab) => + "thread" in left + ? "thread" in right && left.thread === right.thread && left.env === right.env + : "kind" in right && left.kind === right.kind && left.key === right.key; + +/** The pane an address names, without what it cannot read or holds twice. */ +export function readWorkflowPane(rawPane: unknown, rawTab: unknown): WorkflowPaneState { + const tabs: Array = []; + for (const raw of Array.isArray(rawPane) ? rawPane : []) { + const tab = readTab(raw); + if (tab === null || tabs.some((open) => sameWorkflowPaneTab(open, tab))) continue; + tabs.push(tab); + if (tabs.length === MOST_TABS) break; + } + if (tabs.length === 0) return {}; + const tab = typeof rawTab === "number" ? rawTab : Number(rawTab); + return Number.isInteger(tab) && tab >= 0 && tab < tabs.length - 1 + ? { pane: tabs, tab } + : { pane: tabs }; +} + +/** The index of the tab that shows, or -1 when nothing is open. */ +export function activeWorkflowPaneIndex(state: WorkflowPaneState): number { + const count = state.pane?.length ?? 0; + return state.tab !== undefined && state.tab < count ? state.tab : count - 1; +} + +export function activeWorkflowPaneTab(state: WorkflowPaneState): WorkflowPaneTab | null { + return state.pane?.[activeWorkflowPaneIndex(state)] ?? null; +} + +const stateOf = (tabs: ReadonlyArray, active: number): WorkflowPaneState => + tabs.length === 0 + ? {} + : active === tabs.length - 1 + ? { pane: tabs } + : { pane: tabs, tab: active }; + +/** Shows `tab`, opening it after the others when it is not open yet. */ +export function openWorkflowPaneTab( + state: WorkflowPaneState, + tab: WorkflowPaneTab, +): WorkflowPaneState { + const tabs = state.pane ?? []; + const at = tabs.findIndex((open) => sameWorkflowPaneTab(open, tab)); + if (at !== -1) return stateOf(tabs, at); + const next = [...tabs, tab].slice(-MOST_TABS); + return stateOf(next, next.length - 1); +} + +/** Closes the tab at `index`. The one beside it shows if it was showing. */ +export function closeWorkflowPaneTab(state: WorkflowPaneState, index: number): WorkflowPaneState { + const tabs = state.pane ?? []; + if (index < 0 || index >= tabs.length) return state; + const active = activeWorkflowPaneIndex(state); + const rest = tabs.filter((_, at) => at !== index); + return stateOf(rest, active > index ? active - 1 : Math.min(active, rest.length - 1)); +} + +/** Asking for the tab that shows closes it, as the pressed control that asked says it will. */ +export function toggleWorkflowPaneTab( + state: WorkflowPaneState, + tab: WorkflowPaneTab, +): WorkflowPaneState { + const active = activeWorkflowPaneTab(state); + return active !== null && sameWorkflowPaneTab(active, tab) + ? closeWorkflowPaneTab(state, activeWorkflowPaneIndex(state)) + : openWorkflowPaneTab(state, tab); +} diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index ecdb3d4220e67..f63b5ce4f5841 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -396,6 +396,31 @@ "476ca970255eaea4": "Verknüpfe diese Umgebung mit T3 Connect, um eine öffentliche URL zu erhalten.", "6b80f5b38a8f9950": "Nur dieser Computer kann diese Adresse aufrufen. Verknüpfe T3 Connect für eine öffentliche URL.", "c5a7b1d3891dd0b8": "Funktioniert überall, wo die Adresse dieser Umgebung erreichbar ist, zum Beispiel über Tailscale oder deinen eigenen Proxy. Verknüpfe T3 Connect für eine öffentliche URL.", + "3669395daf36fd33": "Auf diesem Server nicht mehr registriert", + "fe513cf316e796e3": "Läuft als Teil anderer Workflows", + "ccf00b97925efab3": "Wird von Hand gestartet", + "421e585eb092b07b": "Startet bei {triggers}", + "7bd7c58592671384": "Braucht dich", + "834ca879c14c167b": "Arbeitet", + "582d6df7dfab86fb": "Pausiert", + "ea6583ce92507ee3": "Schläft", + "7ea8cb8af281ce93": "Wartet", + "1347868f2523140e": "Fertig", + "57d76c4614054271": "Gestoppt", + "5c7344bd51d0b966": "Übersprungen", + "b2074e9bd23049a6": "Abgebrochen", + "5bb7401807ee2fb5": "Fragt: {question} und {more} weitere", + "9e4286183d5f9e34": "Fragt: {question}", + "474c18d001bd6717": "Ein Schritt ist fehlgeschlagen", + "d3890f4eb1508781": "Führt eigene Schritte aus", + "3e7ced10c9482af0": "{step} arbeitet", + "237e1bcb1cf1bdec": "Schläft bei {step}", + "3f7b17ac5a20c8d2": "Führt {run} aus", + "0306f5f324b8aaa5": "{count} Ausführungen laufen", + "e8fd779b84a202a2": "Wartet", + "b6d55657e1a027b8": "Wartet auf {step}", + "e942562a42aede34": "Abgeschlossen", + "26b2b9727fe11289": "Vorzeitig beendet", "1bb995dcec481554": "Genehmige dieses Gerät auf {host}. Dort wird der Code {verificationCode} angezeigt.", "8696a33219944832": "Der Autorisierungsnachweis für die WebSocket-Verbindung konnte nicht erstellt werden.", "5678f133a8631f7d": "Deine Cloud-Anmeldung hat sich geändert. Melde dich erneut an, um die Umgebung zu autorisieren.", @@ -1743,6 +1768,8 @@ "2e995206e087c3fc": "Versuche zu antworten, sobald die Verbindung oder ausstehende Eingabe geklärt ist.", "604ec3067171a0d7": "Unterhaltung", "d6182a057ea12624": "Übergeordneter Thread", + "f2d8537c33cc55a5": "Schritt der Workflow-Ausführung", + "ba8337dca3232880": "Ausführung öffnen", "30fa4a764d11ae42": "{name} konnte nicht heruntergeladen werden", "4952f87dc98191a7": "Der Anhang ist nicht verfügbar.", "2fd6d178493fb407": "Die aktuelle Runde konnte nicht unterbrochen werden.", @@ -1828,6 +1855,7 @@ "04fd71efaa2c3b92": "Pull Requests öffnen", "57e875b79b98ab82": "Issues öffnen", "f1db0a234c777a1d": "T3 Code in einer anderen App verwenden (MCP)", + "6050f22f63e2bcb5": "Workflows öffnen", "a0cc19e60dd99851": "Nutzung öffnen", "46694969044eee98": "Nächsten Arbeitsbereich fokussieren", "0a1011328ba42eef": "Vorherigen Arbeitsbereich fokussieren", @@ -8869,6 +8897,8 @@ "9ae293971d93c819": "Teile einen Thread mit einem Gast, der ihn live im Browser verfolgt und Nachrichten sendet, die du genehmigst. Melde dich bei T3 Connect an, um Gastlinks zu nutzen.", "0aa5406ac4d7f7c7": "Gastlinks", "f0e853acd2006d53": "Verknüpfte Umgebungen", + "ef10c2dff987f3ea": "Führe mehrstufige Workflows aus Dateien im Ordner workflows des T3-Home dieses Servers aus. Öffne sie über die Befehlspalette. Solange es aus ist, läuft nichts aus diesem Ordner; Läufe warten, bis es wieder an ist.", + "2dadb2359422121c": "Workflows", "13e86eb5d8287a71": "Nach einer Claude- oder Codex-Runde eine vorhergesagte nächste Nachricht im leeren Eingabefeld anzeigen. Tab übernimmt sie. Jede ist eine zusätzliche gecachte Anfrage in deinem Tarif. Erfordert Codex 0.165+. Claude-Threads werden nach einem Neustart aktualisiert.", "d4b2a2ec812aafb0": "Nächsten Prompt vorschlagen", "298c7150a7621c80": "Simlock-Geräte-Hosts", @@ -11816,6 +11846,7 @@ "d443390c4d2dcfd4": "barrierefreiheit a11y screenreader nvda jaws voiceover orca sprachausgabe fenstertitel tab-titel alt tab taskleiste thread status reihenfolge arbeitet genehmigung", "6826fa9579c22035": "beta teilen gast einladen link teammitglied zuschauen t3 connect tunnel", "f10c06cba0cdf7fe": "beta anderen rechner verknüpfen vps peer agenten dort arbeiten delegieren", + "bc0b409d89ce086e": "beta workflow dauerhafte läufe automatisierung schritte zeitplan webhook ordner", "4a21cf825a2045b0": "beta tab autovervollständigung nächste nachricht vorhersagen claude codex ghost text", "fea2dc36585c4a20": "Simlock-Geräte-Hosts (Alpha)", "9d834d178130180e": "beta alpha simlock callstack simulator emulator ios android pool lease gateway", @@ -12372,6 +12403,262 @@ "2cddd6095abc734a": "7 Tage", "53493056306708cf": "30 Tage", "c719359d18d37ad3": "90 Tage", + "0bd950151ddc6407": "Ohne Speichern verlassen? Deine Änderungen an dieser Datei gehen verloren.", + "c0ba3f6756b09f30": "Ungespeicherte Änderungen", + "6914e22d357f0ad6": "Gespeichert und aktiv", + "aff389354a031d6f": "Die Datei auf der Festplatte lässt sich nicht laden. Die letzte funktionierende Version läuft weiter.", + "858effde748ab563": "Gespeichert, läuft aber noch nicht.", + "ddb37138df660942": "Nicht gespeichert. Auf dem Server hat sich nichts geändert.", + "6ef4db489e40e39e": "Speichern fehlgeschlagen", + "c89624a2e9af1793": "{name} ist nicht verbunden", + "b5a352a43adb4c17": "Ihre Workflows erscheinen wieder, sobald sie sich neu verbindet. Wähle eine andere Umgebung, um deren Läufe zu sehen.", + "3dcedb736d20aae5": "Die Workflow-Dateien konnten nicht gelesen werden", + "b09f4df8d76ae8ea": "{file} löschen? Die darin definierten Workflows können dann nicht mehr gestartet werden.", + "b4535f5a03689d27": "{name} ist nicht verbunden. Was du hier schreibst, bleibt erhalten und lässt sich speichern, sobald die Verbindung wieder da ist.", + "b54c78d85fd942ea": "Gelöscht, aber was läuft, ist noch nicht nachgezogen.", + "407c228d7da0b7df": "Nicht gelöscht. Auf dem Server hat sich nichts geändert.", + "1a6aa10f3cc14fff": "Diese Dateien passen nicht zusammen. Was bisher lief, läuft weiter.", + "259312516a1dbe6f": "Dateiname", + "2f48ab2aa0586853": "Definiert keine Workflows", + "ba5adfa37b55b8c5": [ + "Zeile ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ":" + ], + "d94eb9ab3201b641": "Löschen", + "84c900d1ae72adc6": "Speichern", + "5912d817be03247a": "Die Datei wurde auf der Festplatte geändert, während du sie bearbeitet hast. Speichern ersetzt diese Änderung.", + "0b1e6f5608826387": "Datei laden und meine Änderungen verwerfen", + "f47b4c06aeb77c1c": "Workflow-Dateien werden geladen…", + "4353bfd401d58f87": [ + "Jede Datei in", + " ", + { + "t": "code", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " ", + "definiert Workflows. Änderungen werden ohne Neustart übernommen." + ], + "0c165251a06f10f1": "Neue Datei", + "8e97cf734b4463e7": "Erstellen", + "2ec0d5108fd6cebe": "Noch keine Workflows. Erstelle hier die erste Datei oder bitte einen Agenten, eine in diesem Ordner zu schreiben.", + "5601350626e8cfe9": "Lässt sich nicht laden", + "21d778a1b9a0c234": "Neben der Ausführung geöffnet", + "62dc4d3a19ff7ca0": "Tab schließen", + "1e25265f2758fce3": "Als vollständigen Thread öffnen", + "672a3dae06b39402": "Auf eigener Seite öffnen", + "7755500a4cde5066": "Bereich schließen", + "b8dcbc93a2ca1861": "Diese Ausführung führt es nicht mehr auf.", + "115c69de3202f664": "Öffnen", + "644eafa9048b62df": "{count, plural, =1 {1. Versuch} =2 {2. Versuch} =3 {3. Versuch} other {{count}. Versuch}}", + "e39f89c909df4db0": "Die Ausführung konnte nicht fortgesetzt werden", + "865f034346b82f47": "{title} abbrechen? Die Agenten stoppen und die Ausführung kann nicht fortgesetzt werden.", + "6bc75632fd9c9136": "Die Ausführung konnte nicht abgebrochen werden", + "64e50329dcfdd5b0": "Abgeschlossen", + "350162e7cc1ebea4": "Gestoppt", + "0875cf506f4c6810": "Übersprungen", + "3cc43f1dbf3f8e0c": "Abgebrochen", + "ded70e75de6404ba": "Zurück zur Liste der Ausführungen", + "2f4ed7dbd22be30d": "Ausführung abbrechen", + "614e5ad58a795fb5": "Stop", + "04b050b0329f0ac8": "dauerte {duration}", + "aff78e1774818ff4": "bisher {duration}", + "38eddd466439afc9": "Was die Ausführung berührt hat", + "156ec271d49ddd70": "Was passiert ist", + "34f59bbbead0b97f": "{names} und {count} weitere", + "ac1556f6ce89a5ea": "{count} parallel", + "e197c4963bacc746": "{count} laufen", + "f5319ed9e18c0df1": "Fragt dich", + "882a25e9084ae1b2": "Pausiert", + "9a03d8a9afc60387": "Bisherige Schritte", + "2f2ae791afe01674": "wartet auf deine Freigabe", + "24f8060c4ccdf928": "startet", + "30a5be40eb956663": "arbeitet", + "dd7a1e58c2553933": "wacht in {duration} auf", + "95cc952724dd7310": "wacht gleich auf", + "3cc34921c0128593": "läuft", + "e777db2880f53a46": "niemand hat geantwortet", + "dc90739d391a5e67": "Du hast {choice} gesagt", + "389f2563b5b763fd": "Kurze Schritte", + "a41c8d758121ad81": "hat geschlafen", + "9db248b770096984": "hat gewartet", + "c76124517af28686": "läuft seit {duration}", + "89102905bf09b0e8": "Live ansehen", + "bdf338cdff4118f0": "Transkript", + "811e7e992f9ff820": "kann erst weitergehen, wenn ihre Workflow-Version wieder registriert ist", + "4d4cdf035e98dd57": "wartet darauf, dass du sie fortsetzt", + "eb5b21dd224a5941": "versucht es in {duration} von selbst erneut", + "6ab3dfa749fde477": "versucht es gleich von selbst erneut", + "44b6463aa70aa14c": "Grund der Pause", + "cf25e7169ab0eb7a": "Pausiert bei {step}", + "56c48c1f220f2754": "Die Frage konnte nicht beantwortet werden", + "a3c43735e1a81498": "Begründung für {title}", + "bfad234f016cfa3f": "Warum, in einem Satz. Gilt für die Antwort, die du wählst.", + "004c41aff9c97873": "Ausführungen", + "4dc0c244a2419f6c": [ + "Teil von ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8c303e8335acb135": [ + "gestartet", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8bffb377e2a6a7de": "ihre Version ist nicht mehr registriert", + "f92d9132f7b85d1a": "Schritte werden geladen…", + "6ebc59f64c761a49": "Noch nichts.", + "a759dccd157d7dae": [ + "Du hast", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " gesagt." + ], + "593b425188346781": [ + "Du hast", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " gesagt: ", + { + "i": 3, + "k": "_gt_value_3", + "v": "v" + } + ], + "c98009be9a273b31": "Ausführung öffnen", + "c8eb9be36d4d51ad": [ + "Thread auf ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "3d9761e81798fcd8": "Fortsetzen", + "8cebd63fc4c967d5": "Nur der fehlgeschlagene Schritt läuft erneut; zuvor Abgeschlossenes bleibt erhalten.", + "bc1e0a2a0f1e9552": "Braucht dich", + "a812f51e970740f1": [ + "gefragt", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " ", + "· die Ausführung wartet auf dich" + ], + "02dfe6c63fd0b8a1": "Begründung hinzufügen", + "19abd94828a3bdbc": "Erst den Agenten fragen", + "a18721fa8f328361": "Braucht dich", + "bbf24e7920c1e86b": "Läuft", + "8d6e18d2ad832db6": "Alle", + "f25af5332ffc3734": "Nichts wartet auf dich.", + "c3f0119b8d6231f8": "Es läuft nichts.", + "33028dfc1229eaa6": "Noch keine Ausführungen.", + "5459bf696a187c26": "Workflow-Ausführungen konnten nicht geladen werden", + "d57c35d43b0f163a": "Diesen Lauf gibt es hier nicht", + "b9aae2f7cdb1a379": "Noch keine Workflow-Ausführungen", + "8f15f66e545af7c0": "Welche Ausführungen", + "b6409289e0c9a4dd": "Workflow", + "035cb02ca1ae4952": "Alle {count} Workflows", + "46d614fa7b4bf1e5": "Workflow-Ausführungen", + "1c635faa2fb45b8b": "Noch nie gelaufen.", + "156ff7b625287a1e": "Übersprungene ausblenden", + "69b985b97ab45e6b": "{count} übersprungene anzeigen", + "2400254d362de84d": "Workflow-Ausführungen werden geladen…", + "145e1f7503ba3b2c": [ + "Diese Umgebung hat keinen Lauf mit diesem Link.", + " ", + { + "t": "button", + "i": 1, + "c": "Zurück zu den Läufen" + } + ], + "783e616cb0476c17": [ + "Ein Workflow verbindet Agenten, Code, Zeitpläne und Fragen an dich zu einer Ausführung, die Neustarts übersteht. Schreib einen unter", + " ", + { + "t": "button", + "i": 1, + "c": "Definitionen" + }, + ", oder bitte einen Agenten darum.", + " ", + { + "t": "a", + "i": 2, + "c": "Anleitung lesen" + } + ], + "cae5c3205c01d062": [ + { + "t": "span", + "i": 1, + "c": "Eine Workflow-Datei hat ein Problem." + }, + " ", + "Die letzte funktionierende Version läuft weiter." + ], + "ed8ce6ebc73dc12d": "Datei öffnen", + "5d8d278ff828102d": "Alle Workflows", + "39459da07479f482": "Agent", + "7741243632056b81": "{step} · Transkript", + "c512071143a5ba32": "Diesen Thread gibt es nicht mehr.", + "ed169d23683fb6ac": "Thread wird geladen…", + "290e0ab40b87dc17": "Workflows-Breadcrumb", + "683dd9831e54edc0": "Umgebung", + "34ad53646f06ed80": "Workflows sind aus", + "8f6589c9e0ac5d4e": "Keine Umgebung verbunden", + "744127f8dfad7d22": "Verbinde eine Umgebung, um ihre Workflow-Ausführungen zu sehen.", + "036182ec7e2ee4d4": "Neben der Ausführung", + "2d6107cb78382d08": "Workflows", + "16f7df687349b399": "Definitionen", + "f0a212aadfe1257b": "Editor wird geladen…", + "20f194e003885e95": [ + "Aktiviere sie für diesen Server in den", + " ", + { + "t": "Link", + "i": 1, + "c": "Einstellungen → Labs" + }, + "." + ], "8367779e149f723b": "Anfrage an die primäre Umgebung während {operation} fehlgeschlagen (HTTP {status}).", "c5cd027743a2b5a6": "Ungültiges Kopplungstoken. Prüfe das Token und versuch es erneut.", "0e4b49c8203aae81": "Zeitüberschreitung beim Warten auf eine authentifizierte Sitzung nach dem Bootstrap.", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 0cc2d503fd620..e3e810fe437bc 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -396,6 +396,31 @@ "476ca970255eaea4": "Link this environment to T3 Connect for a public URL.", "6b80f5b38a8f9950": "Only this computer can call this address. Link T3 Connect for a public URL.", "c5a7b1d3891dd0b8": "Works wherever this environment's address is reachable, for example over Tailscale or your own proxy. Link T3 Connect for a public URL.", + "3669395daf36fd33": "No longer registered on this server", + "fe513cf316e796e3": "Runs as part of other workflows", + "ccf00b97925efab3": "Started by hand", + "421e585eb092b07b": "Starts on {triggers}", + "7bd7c58592671384": "Needs you", + "834ca879c14c167b": "Working", + "582d6df7dfab86fb": "Paused", + "ea6583ce92507ee3": "Sleeping", + "7ea8cb8af281ce93": "Waiting", + "1347868f2523140e": "Done", + "57d76c4614054271": "Stopped", + "5c7344bd51d0b966": "Skipped", + "b2074e9bd23049a6": "Cancelled", + "5bb7401807ee2fb5": "Asks: {question} and {more} more", + "9e4286183d5f9e34": "Asks: {question}", + "474c18d001bd6717": "A step failed", + "d3890f4eb1508781": "Running its own steps", + "3e7ced10c9482af0": "{step} is working", + "237e1bcb1cf1bdec": "Sleeping at {step}", + "3f7b17ac5a20c8d2": "Runs {run}", + "0306f5f324b8aaa5": "{count} runs under way", + "e8fd779b84a202a2": "Waiting", + "b6d55657e1a027b8": "Waiting for {step}", + "e942562a42aede34": "Finished", + "26b2b9727fe11289": "Ended early", "1bb995dcec481554": "Approve this device on {host}. It shows code {verificationCode}.", "8696a33219944832": "Could not create the websocket authorization proof.", "5678f133a8631f7d": "Your cloud sign-in changed. Sign in again to authorize the environment.", @@ -1744,6 +1769,8 @@ "2e995206e087c3fc": "Try replying after the connection or pending input is resolved.", "604ec3067171a0d7": "Conversation", "d6182a057ea12624": "Parent thread", + "f2d8537c33cc55a5": "Step of the workflow run", + "ba8337dca3232880": "Open run", "30fa4a764d11ae42": "Could not download {name}", "4952f87dc98191a7": "The attachment is unavailable.", "2fd6d178493fb407": "Failed to interrupt the current turn.", @@ -1829,6 +1856,7 @@ "04fd71efaa2c3b92": "Open pull requests", "57e875b79b98ab82": "Open issues", "f1db0a234c777a1d": "Use T3 Code in another app (MCP)", + "6050f22f63e2bcb5": "Open workflows", "a0cc19e60dd99851": "Open usage", "46694969044eee98": "Focus Next Workspace Area", "0a1011328ba42eef": "Focus Previous Workspace Area", @@ -8877,6 +8905,8 @@ "9ae293971d93c819": "Share a thread with a guest who watches it live in a browser and sends messages you approve. Sign in to T3 Connect to use guest links.", "0aa5406ac4d7f7c7": "Guest links", "f0e853acd2006d53": "Linked environments", + "ef10c2dff987f3ea": "Run multi-step workflows from files in the workflows folder of this server's T3 home. Open them from the command palette. While off, nothing in that folder runs; runs wait until it is on again.", + "2dadb2359422121c": "Workflows", "13e86eb5d8287a71": "Show a predicted next message in the empty composer after a Claude or Codex turn. Tab uses it. Each is an extra cached request on your plan. Needs Codex 0.165+. Claude threads update on restart.", "d4b2a2ec812aafb0": "Suggest next prompt", "298c7150a7621c80": "Simlock device hosts", @@ -11824,6 +11854,7 @@ "d443390c4d2dcfd4": "accessibility a11y screen reader nvda jaws voiceover orca narrator window title tab title alt tab taskbar thread status order working approval", "6826fa9579c22035": "beta share guest invite link teammate watch t3 connect tunnel", "f10c06cba0cdf7fe": "beta link another machine vps peer agents work there delegate", + "bc0b409d89ce086e": "beta workflow durable runs automation steps schedule webhook folder", "4a21cf825a2045b0": "beta tab autocomplete predict next message claude codex ghost text", "fea2dc36585c4a20": "Simlock device hosts (alpha)", "9d834d178130180e": "beta alpha simlock callstack simulator emulator ios android pool lease gateway", @@ -12380,6 +12411,262 @@ "2cddd6095abc734a": "7 days", "53493056306708cf": "30 days", "c719359d18d37ad3": "90 days", + "0bd950151ddc6407": "Leave without saving? Your changes to this file are lost.", + "c0ba3f6756b09f30": "Unsaved changes", + "6914e22d357f0ad6": "Saved and running", + "aff389354a031d6f": "The file on disk does not load. The last version that did keeps running.", + "858effde748ab563": "Saved, but it does not run yet.", + "ddb37138df660942": "Not saved. Nothing changed on the server.", + "6ef4db489e40e39e": "Could not save", + "c89624a2e9af1793": "{name} is not connected", + "b5a352a43adb4c17": "Its workflows show again when it reconnects. Pick another environment to see its runs.", + "3dcedb736d20aae5": "Could not read the workflow files", + "b09f4df8d76ae8ea": "Delete {file}? The workflows it defines can no longer be started.", + "b4535f5a03689d27": "{name} is not connected. What you write here stays, and saves once it is back.", + "b54c78d85fd942ea": "Deleted, but what runs has not caught up yet.", + "407c228d7da0b7df": "Not deleted. Nothing changed on the server.", + "1a6aa10f3cc14fff": "These files do not fit together. What ran before keeps running.", + "259312516a1dbe6f": "File name", + "2f48ab2aa0586853": "Defines no workflows", + "ba5adfa37b55b8c5": [ + "Line ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ":" + ], + "d94eb9ab3201b641": "Delete", + "84c900d1ae72adc6": "Save", + "5912d817be03247a": "The file changed on disk while you were editing. Saving replaces that change.", + "0b1e6f5608826387": "Load the file and drop my changes", + "f47b4c06aeb77c1c": "Loading the workflow files…", + "4353bfd401d58f87": [ + "Every file in", + " ", + { + "t": "code", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " ", + "defines workflows. A change to one is picked up without a restart." + ], + "0c165251a06f10f1": "New file", + "8e97cf734b4463e7": "Create", + "2ec0d5108fd6cebe": "No workflows yet. Make the first file here, or ask an agent to write one in that folder.", + "5601350626e8cfe9": "Does not load", + "21d778a1b9a0c234": "Open beside the run", + "62dc4d3a19ff7ca0": "Close tab", + "1e25265f2758fce3": "Open as a full thread", + "672a3dae06b39402": "Open on its own page", + "7755500a4cde5066": "Close the pane", + "b8dcbc93a2ca1861": "This run no longer lists it.", + "115c69de3202f664": "Open", + "644eafa9048b62df": "{count, plural, =1 {1st try} =2 {2nd try} =3 {3rd try} other {{count}th try}}", + "e39f89c909df4db0": "Could not resume the run", + "865f034346b82f47": "Cancel {title}? Its agents stop and the run cannot be resumed.", + "6bc75632fd9c9136": "Could not cancel the run", + "64e50329dcfdd5b0": "Finished", + "350162e7cc1ebea4": "Stopped", + "0875cf506f4c6810": "Skipped", + "3cc43f1dbf3f8e0c": "Cancelled", + "ded70e75de6404ba": "Back to the list of runs", + "2f4ed7dbd22be30d": "Cancel run", + "614e5ad58a795fb5": "Stop", + "04b050b0329f0ac8": "took {duration}", + "aff78e1774818ff4": "{duration} so far", + "38eddd466439afc9": "What the run touched", + "156ec271d49ddd70": "What happened", + "34f59bbbead0b97f": "{names} and {count} more", + "ac1556f6ce89a5ea": "{count} in parallel", + "e197c4963bacc746": "{count} running", + "f5319ed9e18c0df1": "Asks you", + "882a25e9084ae1b2": "Paused", + "9a03d8a9afc60387": "Steps so far", + "2f2ae791afe01674": "waits for your approval", + "24f8060c4ccdf928": "starting", + "30a5be40eb956663": "working", + "dd7a1e58c2553933": "wakes in {duration}", + "95cc952724dd7310": "about to wake", + "3cc34921c0128593": "running", + "e777db2880f53a46": "nobody answered", + "dc90739d391a5e67": "You said {choice}", + "389f2563b5b763fd": "Quick steps", + "a41c8d758121ad81": "slept", + "9db248b770096984": "waited", + "c76124517af28686": "running for {duration}", + "89102905bf09b0e8": "Watch live", + "bdf338cdff4118f0": "Transcript", + "811e7e992f9ff820": "cannot go on until its workflow version is registered again", + "4d4cdf035e98dd57": "waits for you to resume it", + "eb5b21dd224a5941": "tries again by itself in {duration}", + "6ab3dfa749fde477": "about to try again by itself", + "44b6463aa70aa14c": "Why it paused", + "cf25e7169ab0eb7a": "Paused at {step}", + "56c48c1f220f2754": "Could not answer the question", + "a3c43735e1a81498": "Reason for {title}", + "bfad234f016cfa3f": "Why, in a sentence. It goes with whichever answer you pick.", + "004c41aff9c97873": "Runs", + "4dc0c244a2419f6c": [ + "Part of ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8c303e8335acb135": [ + "started", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8bffb377e2a6a7de": "its version is no longer registered", + "f92d9132f7b85d1a": "Loading steps…", + "6ebc59f64c761a49": "Nothing yet.", + "a759dccd157d7dae": [ + "You said", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + "." + ], + "593b425188346781": [ + "You said", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + ": ", + { + "i": 3, + "k": "_gt_value_3", + "v": "v" + } + ], + "c98009be9a273b31": "Open run", + "c8eb9be36d4d51ad": [ + "Thread on ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "3d9761e81798fcd8": "Resume", + "8cebd63fc4c967d5": "Only the failed step runs again; what finished before it is kept.", + "bc1e0a2a0f1e9552": "Needs you", + "a812f51e970740f1": [ + "asked", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " ", + "· the run waits for you" + ], + "02dfe6c63fd0b8a1": "Add a reason", + "19abd94828a3bdbc": "Ask the agent first", + "a18721fa8f328361": "Needs you", + "bbf24e7920c1e86b": "Running", + "8d6e18d2ad832db6": "All", + "f25af5332ffc3734": "Nothing waits on you.", + "c3f0119b8d6231f8": "Nothing is running.", + "33028dfc1229eaa6": "No runs yet.", + "5459bf696a187c26": "Could not load workflow runs", + "d57c35d43b0f163a": "This run is not here", + "b9aae2f7cdb1a379": "No workflow runs yet", + "8f15f66e545af7c0": "Which runs", + "b6409289e0c9a4dd": "Workflow", + "035cb02ca1ae4952": "All {count} workflows", + "46d614fa7b4bf1e5": "Workflow runs", + "1c635faa2fb45b8b": "Has not run yet.", + "156ff7b625287a1e": "Hide skipped", + "69b985b97ab45e6b": "Show {count} skipped", + "2400254d362de84d": "Loading workflow runs…", + "145e1f7503ba3b2c": [ + "This environment has no run with that link.", + " ", + { + "t": "button", + "i": 1, + "c": "Back to the runs" + } + ], + "783e616cb0476c17": [ + "A workflow ties agents, code, schedules and questions to you into one run that survives restarts. Write one under", + " ", + { + "t": "button", + "i": 1, + "c": "Definitions" + }, + ", or ask an agent to.", + " ", + { + "t": "a", + "i": 2, + "c": "Read the guide" + } + ], + "cae5c3205c01d062": [ + { + "t": "span", + "i": 1, + "c": "A workflow file has a problem." + }, + " ", + "The last version that did keeps running." + ], + "ed8ce6ebc73dc12d": "Open the file", + "5d8d278ff828102d": "All workflows", + "39459da07479f482": "Agent", + "7741243632056b81": "{step} · transcript", + "c512071143a5ba32": "This thread is no longer there.", + "ed169d23683fb6ac": "Loading the thread…", + "290e0ab40b87dc17": "Workflows breadcrumb", + "683dd9831e54edc0": "Environment", + "34ad53646f06ed80": "Workflows are off", + "8f6589c9e0ac5d4e": "No environment connected", + "744127f8dfad7d22": "Connect an environment to see its workflow runs.", + "036182ec7e2ee4d4": "Beside the run", + "2d6107cb78382d08": "Workflows", + "16f7df687349b399": "Definitions", + "f0a212aadfe1257b": "Loading the editor…", + "20f194e003885e95": [ + "Turn them on for this server in", + " ", + { + "t": "Link", + "i": 1, + "c": "Settings → Labs" + }, + "." + ], "8367779e149f723b": "Primary environment request failed during {operation} (HTTP {status}).", "c5cd027743a2b5a6": "Invalid pairing token. Check the token and try again.", "0e4b49c8203aae81": "Timed out waiting for authenticated session after bootstrap.", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index daf936020ff3a..b15af98ce01ba 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -396,6 +396,31 @@ "476ca970255eaea4": "Vincula este entorno a T3 Connect para tener una URL pública.", "6b80f5b38a8f9950": "Solo este equipo puede llamar a esta dirección. Vincula T3 Connect para tener una URL pública.", "c5a7b1d3891dd0b8": "Funciona donde se pueda acceder a la dirección de este entorno, por ejemplo a través de Tailscale o de tu propio proxy. Vincula T3 Connect para tener una URL pública.", + "3669395daf36fd33": "Ya no está registrado en este servidor", + "fe513cf316e796e3": "Se ejecuta como parte de otros flujos de trabajo", + "ccf00b97925efab3": "Se inicia a mano", + "421e585eb092b07b": "Se inicia con {triggers}", + "7bd7c58592671384": "Te necesitan", + "834ca879c14c167b": "Trabajando", + "582d6df7dfab86fb": "En pausa", + "ea6583ce92507ee3": "Durmiendo", + "7ea8cb8af281ce93": "Esperando", + "1347868f2523140e": "Terminada", + "57d76c4614054271": "Detenida", + "5c7344bd51d0b966": "Omitida", + "b2074e9bd23049a6": "Cancelada", + "5bb7401807ee2fb5": "Pregunta: {question} y {more} más", + "9e4286183d5f9e34": "Pregunta: {question}", + "474c18d001bd6717": "Falló un paso", + "d3890f4eb1508781": "Ejecuta sus propios pasos", + "3e7ced10c9482af0": "{step} está trabajando", + "237e1bcb1cf1bdec": "Durmiendo en {step}", + "3f7b17ac5a20c8d2": "Ejecuta {run}", + "0306f5f324b8aaa5": "{count} ejecuciones en curso", + "e8fd779b84a202a2": "Esperando", + "b6d55657e1a027b8": "Esperando a {step}", + "e942562a42aede34": "Finalizada", + "26b2b9727fe11289": "Terminó antes de tiempo", "1bb995dcec481554": "Aprueba este dispositivo en {host}. Muestra el código {verificationCode}.", "8696a33219944832": "No se pudo crear la prueba de autorización del websocket.", "5678f133a8631f7d": "Tu inicio de sesión en la nube cambió. Vuelve a iniciar sesión para autorizar el entorno.", @@ -1744,6 +1769,8 @@ "2e995206e087c3fc": "Prueba a responder cuando se resuelva la conexión o la entrada pendiente.", "604ec3067171a0d7": "Conversación", "d6182a057ea12624": "Hilo principal", + "f2d8537c33cc55a5": "Paso de la ejecución del flujo de trabajo", + "ba8337dca3232880": "Abrir ejecución", "30fa4a764d11ae42": "No se pudo descargar {name}", "4952f87dc98191a7": "El adjunto no está disponible.", "2fd6d178493fb407": "No se pudo interrumpir el turno actual.", @@ -1829,6 +1856,7 @@ "04fd71efaa2c3b92": "Abrir pull requests", "57e875b79b98ab82": "Abrir issues", "f1db0a234c777a1d": "Usar T3 Code en otra app (MCP)", + "6050f22f63e2bcb5": "Abrir flujos de trabajo", "a0cc19e60dd99851": "Abrir uso", "46694969044eee98": "Enfocar la siguiente área de trabajo", "0a1011328ba42eef": "Enfocar el área de trabajo anterior", @@ -8867,6 +8895,8 @@ "9ae293971d93c819": "Comparte un hilo con un invitado que lo ve en directo en un navegador y envía mensajes que tú apruebas. Inicia sesión en T3 Connect para usar enlaces de invitado.", "0aa5406ac4d7f7c7": "Enlaces de invitado", "f0e853acd2006d53": "Entornos vinculados", + "ef10c2dff987f3ea": "Ejecuta flujos de trabajo de varios pasos a partir de archivos en la carpeta workflows del directorio T3 de este servidor. Ábrelos desde la paleta de comandos. Mientras está desactivado, no se ejecuta nada de esa carpeta; las ejecuciones esperan hasta que se vuelva a activar.", + "2dadb2359422121c": "Flujos de trabajo", "13e86eb5d8287a71": "Muestra un mensaje siguiente previsto en el cuadro de mensaje vacío tras un turno de Claude o Codex. Tab lo usa. Cada uno es una solicitud extra en caché de tu plan. Requiere Codex 0.165+. Los hilos de Claude se actualizan al reiniciar.", "d4b2a2ec812aafb0": "Sugerir el siguiente prompt", "298c7150a7621c80": "Hosts de dispositivos Simlock", @@ -11809,6 +11839,7 @@ "d443390c4d2dcfd4": "accesibilidad a11y lector de pantalla nvda jaws voiceover orca narrador título de ventana título de pestaña alt tab barra de tareas estado del hilo orden en curso aprobación", "6826fa9579c22035": "beta compartir invitado invitar enlace compañero ver t3 connect túnel", "f10c06cba0cdf7fe": "beta vincular otra máquina vps agentes pares trabajar allí delegar", + "bc0b409d89ce086e": "beta flujo de trabajo workflow ejecuciones duraderas automatización pasos programación webhook carpeta", "4a21cf825a2045b0": "beta tab autocompletar predecir siguiente mensaje claude codex texto fantasma", "fea2dc36585c4a20": "Hosts de dispositivos Simlock (alfa)", "9d834d178130180e": "beta alfa simlock callstack simulador emulador ios android grupo préstamo gateway", @@ -12365,6 +12396,262 @@ "2cddd6095abc734a": "7 días", "53493056306708cf": "30 días", "c719359d18d37ad3": "90 días", + "0bd950151ddc6407": "¿Salir sin guardar? Se perderán tus cambios en este archivo.", + "c0ba3f6756b09f30": "Cambios sin guardar", + "6914e22d357f0ad6": "Guardado y en ejecución", + "aff389354a031d6f": "El archivo en disco no se carga. Sigue en ejecución la última versión que sí cargó.", + "858effde748ab563": "Guardado, pero todavía no se ejecuta.", + "ddb37138df660942": "No se guardó. No cambió nada en el servidor.", + "6ef4db489e40e39e": "No se pudo guardar", + "c89624a2e9af1793": "{name} no está conectado", + "b5a352a43adb4c17": "Sus flujos de trabajo vuelven a mostrarse cuando se reconecta. Elige otro entorno para ver sus ejecuciones.", + "3dcedb736d20aae5": "No se pudieron leer los archivos de flujos de trabajo", + "b09f4df8d76ae8ea": "¿Eliminar {file}? Los flujos de trabajo que define ya no se podrán iniciar.", + "b4535f5a03689d27": "{name} no está conectado. Lo que escribas aquí se conserva y se puede guardar en cuanto vuelva.", + "b54c78d85fd942ea": "Eliminado, pero lo que se ejecuta aún no se ha actualizado.", + "407c228d7da0b7df": "No se eliminó. No cambió nada en el servidor.", + "1a6aa10f3cc14fff": "Estos archivos no encajan entre sí. Lo que se ejecutaba antes sigue en ejecución.", + "259312516a1dbe6f": "Nombre del archivo", + "2f48ab2aa0586853": "No define ningún flujo de trabajo", + "ba5adfa37b55b8c5": [ + "Línea ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ":" + ], + "d94eb9ab3201b641": "Eliminar", + "84c900d1ae72adc6": "Guardar", + "5912d817be03247a": "El archivo cambió en disco mientras lo editabas. Al guardar se reemplaza ese cambio.", + "0b1e6f5608826387": "Cargar el archivo y descartar mis cambios", + "f47b4c06aeb77c1c": "Cargando los archivos de flujos de trabajo…", + "4353bfd401d58f87": [ + "Cada archivo de", + " ", + { + "t": "code", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " ", + "define flujos de trabajo. Los cambios se aplican sin reiniciar." + ], + "0c165251a06f10f1": "Nuevo archivo", + "8e97cf734b4463e7": "Crear", + "2ec0d5108fd6cebe": "Aún no hay flujos de trabajo. Crea aquí el primer archivo o pide a un agente que escriba uno en esa carpeta.", + "5601350626e8cfe9": "No se carga", + "21d778a1b9a0c234": "Abierto junto a la ejecución", + "62dc4d3a19ff7ca0": "Cerrar pestaña", + "1e25265f2758fce3": "Abrir como hilo completo", + "672a3dae06b39402": "Abrir en su propia página", + "7755500a4cde5066": "Cerrar el panel", + "b8dcbc93a2ca1861": "Esta ejecución ya no lo incluye.", + "115c69de3202f664": "Abrir", + "644eafa9048b62df": "{count, plural, =1 {1.er intento} =2 {2.º intento} =3 {3.er intento} other {{count}.º intento}}", + "e39f89c909df4db0": "No se pudo reanudar la ejecución", + "865f034346b82f47": "¿Cancelar {title}? Sus agentes se detienen y la ejecución no se podrá reanudar.", + "6bc75632fd9c9136": "No se pudo cancelar la ejecución", + "64e50329dcfdd5b0": "Finalizada", + "350162e7cc1ebea4": "Detenida", + "0875cf506f4c6810": "Omitida", + "3cc43f1dbf3f8e0c": "Cancelada", + "ded70e75de6404ba": "Volver a la lista de ejecuciones", + "2f4ed7dbd22be30d": "Cancelar ejecución", + "614e5ad58a795fb5": "Stop", + "04b050b0329f0ac8": "tardó {duration}", + "aff78e1774818ff4": "{duration} hasta ahora", + "38eddd466439afc9": "Lo que tocó la ejecución", + "156ec271d49ddd70": "Qué ocurrió", + "34f59bbbead0b97f": "{names} y {count} más", + "ac1556f6ce89a5ea": "{count} en paralelo", + "e197c4963bacc746": "{count} en curso", + "f5319ed9e18c0df1": "Te pregunta", + "882a25e9084ae1b2": "En pausa", + "9a03d8a9afc60387": "Pasos hasta ahora", + "2f2ae791afe01674": "espera tu aprobación", + "24f8060c4ccdf928": "empezando", + "30a5be40eb956663": "trabajando", + "dd7a1e58c2553933": "despierta en {duration}", + "95cc952724dd7310": "a punto de despertar", + "3cc34921c0128593": "en curso", + "e777db2880f53a46": "nadie respondió", + "dc90739d391a5e67": "Dijiste {choice}", + "389f2563b5b763fd": "Pasos rápidos", + "a41c8d758121ad81": "en espera", + "9db248b770096984": "esperó", + "c76124517af28686": "en ejecución desde hace {duration}", + "89102905bf09b0e8": "Ver en directo", + "bdf338cdff4118f0": "Transcripción", + "811e7e992f9ff820": "no puede continuar hasta que su versión del flujo de trabajo vuelva a registrarse", + "4d4cdf035e98dd57": "espera a que la reanudes", + "eb5b21dd224a5941": "lo reintenta sola en {duration}", + "6ab3dfa749fde477": "a punto de reintentarlo sola", + "44b6463aa70aa14c": "Por qué se pausó", + "cf25e7169ab0eb7a": "En pausa en {step}", + "56c48c1f220f2754": "No se pudo responder a la pregunta", + "a3c43735e1a81498": "Motivo de {title}", + "bfad234f016cfa3f": "El porqué, en una frase. Acompaña a la respuesta que elijas.", + "004c41aff9c97873": "Ejecuciones", + "4dc0c244a2419f6c": [ + "Parte de ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8c303e8335acb135": [ + "iniciada", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8bffb377e2a6a7de": "su versión ya no está registrada", + "f92d9132f7b85d1a": "Cargando pasos…", + "6ebc59f64c761a49": "Nada todavía.", + "a759dccd157d7dae": [ + "Dijiste", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + "." + ], + "593b425188346781": [ + "Dijiste", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + ": ", + { + "i": 3, + "k": "_gt_value_3", + "v": "v" + } + ], + "c98009be9a273b31": "Abrir ejecución", + "c8eb9be36d4d51ad": [ + "Hilo en ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "3d9761e81798fcd8": "Reanudar", + "8cebd63fc4c967d5": "Solo se vuelve a ejecutar el paso que falló; lo que terminó antes se conserva.", + "bc1e0a2a0f1e9552": "Te necesitan", + "a812f51e970740f1": [ + "preguntó", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " ", + "· la ejecución te espera" + ], + "02dfe6c63fd0b8a1": "Añadir un motivo", + "19abd94828a3bdbc": "Preguntar antes al agente", + "a18721fa8f328361": "Te necesitan", + "bbf24e7920c1e86b": "En ejecución", + "8d6e18d2ad832db6": "Todas", + "f25af5332ffc3734": "Nada espera tu respuesta.", + "c3f0119b8d6231f8": "No hay nada en ejecución.", + "33028dfc1229eaa6": "Aún no hay ejecuciones.", + "5459bf696a187c26": "No se pudieron cargar las ejecuciones de flujos de trabajo", + "d57c35d43b0f163a": "Esta ejecución no está aquí", + "b9aae2f7cdb1a379": "Aún no hay ejecuciones de flujos de trabajo", + "8f15f66e545af7c0": "Qué ejecuciones", + "b6409289e0c9a4dd": "Flujo de trabajo", + "035cb02ca1ae4952": "Los {count} flujos de trabajo", + "46d614fa7b4bf1e5": "Ejecuciones de flujos de trabajo", + "1c635faa2fb45b8b": "Aún no se ha ejecutado.", + "156ff7b625287a1e": "Ocultar omitidos", + "69b985b97ab45e6b": "Mostrar {count} omitidos", + "2400254d362de84d": "Cargando ejecuciones de flujos de trabajo…", + "145e1f7503ba3b2c": [ + "Este entorno no tiene ninguna ejecución con ese enlace.", + " ", + { + "t": "button", + "i": 1, + "c": "Volver a las ejecuciones" + } + ], + "783e616cb0476c17": [ + "Un flujo de trabajo une agentes, código, programaciones y preguntas para ti en una sola ejecución que sobrevive a los reinicios. Escribe uno en", + " ", + { + "t": "button", + "i": 1, + "c": "Definiciones" + }, + ", o pídeselo a un agente.", + " ", + { + "t": "a", + "i": 2, + "c": "Leer la guía" + } + ], + "cae5c3205c01d062": [ + { + "t": "span", + "i": 1, + "c": "Un archivo de flujo de trabajo tiene un problema." + }, + " ", + "Sigue en ejecución la última versión que sí cargó." + ], + "ed8ce6ebc73dc12d": "Abrir el archivo", + "5d8d278ff828102d": "Todos los flujos de trabajo", + "39459da07479f482": "Agente", + "7741243632056b81": "{step} · transcripción", + "c512071143a5ba32": "Este hilo ya no existe.", + "ed169d23683fb6ac": "Cargando el hilo…", + "290e0ab40b87dc17": "Ruta de navegación de flujos de trabajo", + "683dd9831e54edc0": "Entorno", + "34ad53646f06ed80": "Los flujos de trabajo están desactivados", + "8f6589c9e0ac5d4e": "Ningún entorno conectado", + "744127f8dfad7d22": "Conecta un entorno para ver sus ejecuciones de flujos de trabajo.", + "036182ec7e2ee4d4": "Junto a la ejecución", + "2d6107cb78382d08": "Flujos de trabajo", + "16f7df687349b399": "Definiciones", + "f0a212aadfe1257b": "Cargando el editor…", + "20f194e003885e95": [ + "Actívalos para este servidor en", + " ", + { + "t": "Link", + "i": 1, + "c": "Ajustes → Labs" + }, + "." + ], "8367779e149f723b": "Falló una solicitud al entorno principal durante {operation} (HTTP {status}).", "c5cd027743a2b5a6": "El token de emparejamiento no es válido. Revísalo e inténtalo de nuevo.", "0e4b49c8203aae81": "Se agotó el tiempo de espera de la sesión autenticada tras el arranque.", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 713eca77f3127..f2f519b25ae0b 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -396,6 +396,31 @@ "476ca970255eaea4": "Associez cet environnement à T3 Connect pour obtenir une URL publique.", "6b80f5b38a8f9950": "Seul cet ordinateur peut appeler cette adresse. Associez T3 Connect pour obtenir une URL publique.", "c5a7b1d3891dd0b8": "Fonctionne partout où l’adresse de cet environnement est joignable, par exemple via Tailscale ou votre propre proxy. Associez T3 Connect pour obtenir une URL publique.", + "3669395daf36fd33": "N’est plus enregistré sur ce serveur", + "fe513cf316e796e3": "S’exécute dans le cadre d’autres workflows", + "ccf00b97925efab3": "Démarré à la main", + "421e585eb092b07b": "Démarre sur {triggers}", + "7bd7c58592671384": "Vous attendent", + "834ca879c14c167b": "En cours", + "582d6df7dfab86fb": "En pause", + "ea6583ce92507ee3": "En veille", + "7ea8cb8af281ce93": "En attente", + "1347868f2523140e": "Terminée", + "57d76c4614054271": "Arrêtée", + "5c7344bd51d0b966": "Ignorée", + "b2074e9bd23049a6": "Annulée", + "5bb7401807ee2fb5": "Demande : {question} et {more} de plus", + "9e4286183d5f9e34": "Demande : {question}", + "474c18d001bd6717": "Une étape a échoué", + "d3890f4eb1508781": "Exécute ses propres étapes", + "3e7ced10c9482af0": "{step} est en cours", + "237e1bcb1cf1bdec": "En veille à {step}", + "3f7b17ac5a20c8d2": "Exécute {run}", + "0306f5f324b8aaa5": "{count} exécutions en cours", + "e8fd779b84a202a2": "En attente", + "b6d55657e1a027b8": "En attente de {step}", + "e942562a42aede34": "Terminée", + "26b2b9727fe11289": "Terminée prématurément", "1bb995dcec481554": "Approuvez cet appareil sur {host}. Il affiche le code {verificationCode}.", "8696a33219944832": "Impossible de créer la preuve d’autorisation WebSocket.", "5678f133a8631f7d": "Votre connexion cloud a changé. Reconnectez-vous pour autoriser l’environnement.", @@ -1744,6 +1769,8 @@ "2e995206e087c3fc": "Réessayez de répondre une fois la connexion ou la saisie en attente résolue.", "604ec3067171a0d7": "Conversation", "d6182a057ea12624": "Fil parent", + "f2d8537c33cc55a5": "Étape de l’exécution du workflow", + "ba8337dca3232880": "Ouvrir l’exécution", "30fa4a764d11ae42": "Impossible de télécharger {name}", "4952f87dc98191a7": "La pièce jointe est indisponible.", "2fd6d178493fb407": "Échec de l’interruption du tour en cours.", @@ -1829,6 +1856,7 @@ "04fd71efaa2c3b92": "Ouvrir les pull requests", "57e875b79b98ab82": "Ouvrir les tickets", "f1db0a234c777a1d": "Utiliser T3 Code dans une autre app (MCP)", + "6050f22f63e2bcb5": "Ouvrir les workflows", "a0cc19e60dd99851": "Ouvrir l’utilisation", "46694969044eee98": "Activer la zone de travail suivante", "0a1011328ba42eef": "Activer la zone de travail précédente", @@ -8868,6 +8896,8 @@ "9ae293971d93c819": "Partagez un fil avec un invité qui le suit en direct dans un navigateur et envoie des messages que vous approuvez. Connectez-vous à T3 Connect pour utiliser les liens invités.", "0aa5406ac4d7f7c7": "Liens invités", "f0e853acd2006d53": "Environnements associés", + "ef10c2dff987f3ea": "Exécutez des workflows en plusieurs étapes à partir des fichiers du dossier workflows du répertoire T3 de ce serveur. Ouvrez-les depuis la palette de commandes. Tant que c'est désactivé, rien dans ce dossier ne s'exécute ; les exécutions attendent sa réactivation.", + "2dadb2359422121c": "Workflows", "13e86eb5d8287a71": "Affiche un prochain message suggéré dans la zone de saisie vide après un tour Claude ou Codex. Tab l’utilise. Chaque suggestion est une requête en cache supplémentaire sur votre forfait. Nécessite Codex 0.165+. Les fils Claude se mettent à jour au redémarrage.", "d4b2a2ec812aafb0": "Suggérer le prochain prompt", "298c7150a7621c80": "Hôtes d’appareils Simlock", @@ -11814,6 +11844,7 @@ "d443390c4d2dcfd4": "accessibilité a11y lecteur d’écran nvda jaws voiceover orca narrateur titre de fenêtre titre d’onglet alt tab barre des tâches statut du fil ordre en cours approbation", "6826fa9579c22035": "bêta partager invité invitation lien coéquipier regarder t3 connect tunnel", "f10c06cba0cdf7fe": "bêta associer une autre machine vps pair agents y travaillent déléguer", + "bc0b409d89ce086e": "bêta workflow exécutions durables automatisation étapes planification webhook dossier", "4a21cf825a2045b0": "bêta tab autocomplétion prédire prochain message claude codex texte fantôme", "fea2dc36585c4a20": "Hôtes d’appareils Simlock (alpha)", "9d834d178130180e": "bêta alpha simlock callstack simulateur émulateur ios android pool bail passerelle", @@ -12370,6 +12401,262 @@ "2cddd6095abc734a": "7 jours", "53493056306708cf": "30 jours", "c719359d18d37ad3": "90 jours", + "0bd950151ddc6407": "Quitter sans enregistrer ? Vos modifications de ce fichier seront perdues.", + "c0ba3f6756b09f30": "Modifications non enregistrées", + "6914e22d357f0ad6": "Enregistré et en service", + "aff389354a031d6f": "Le fichier sur le disque ne se charge pas. La dernière version valide continue de s’exécuter.", + "858effde748ab563": "Enregistré, mais il ne s’exécute pas encore.", + "ddb37138df660942": "Non enregistré. Rien n’a changé sur le serveur.", + "6ef4db489e40e39e": "Impossible d’enregistrer", + "c89624a2e9af1793": "{name} n’est pas connecté", + "b5a352a43adb4c17": "Ses workflows réapparaissent quand il se reconnecte. Choisis un autre environnement pour voir ses exécutions.", + "3dcedb736d20aae5": "Impossible de lire les fichiers de workflow", + "b09f4df8d76ae8ea": "Supprimer {file} ? Les workflows qu’il définit ne pourront plus être démarrés.", + "b4535f5a03689d27": "{name} n’est pas connecté. Ce que vous écrivez ici est conservé et pourra être enregistré dès son retour.", + "b54c78d85fd942ea": "Supprimé, mais ce qui s’exécute n’a pas encore suivi.", + "407c228d7da0b7df": "Non supprimé. Rien n’a changé sur le serveur.", + "1a6aa10f3cc14fff": "Ces fichiers ne sont pas cohérents entre eux. Ce qui s’exécutait avant continue de s’exécuter.", + "259312516a1dbe6f": "Nom du fichier", + "2f48ab2aa0586853": "Ne définit aucun workflow", + "ba5adfa37b55b8c5": [ + "Ligne ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " :" + ], + "d94eb9ab3201b641": "Supprimer", + "84c900d1ae72adc6": "Enregistrer", + "5912d817be03247a": "Le fichier a changé sur le disque pendant votre modification. L’enregistrement remplace ce changement.", + "0b1e6f5608826387": "Charger le fichier et abandonner mes modifications", + "f47b4c06aeb77c1c": "Chargement des fichiers de workflow…", + "4353bfd401d58f87": [ + "Chaque fichier de", + " ", + { + "t": "code", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " ", + "définit des workflows. Toute modification est prise en compte sans redémarrage." + ], + "0c165251a06f10f1": "Nouveau fichier", + "8e97cf734b4463e7": "Créer", + "2ec0d5108fd6cebe": "Aucun workflow pour l’instant. Créez le premier fichier ici ou demandez à un agent d’en écrire un dans ce dossier.", + "5601350626e8cfe9": "Ne se charge pas", + "21d778a1b9a0c234": "Ouvert à côté de l’exécution", + "62dc4d3a19ff7ca0": "Fermer l’onglet", + "1e25265f2758fce3": "Ouvrir comme fil complet", + "672a3dae06b39402": "Ouvrir sur sa propre page", + "7755500a4cde5066": "Fermer le panneau", + "b8dcbc93a2ca1861": "Cette exécution ne le mentionne plus.", + "115c69de3202f664": "Ouvrir", + "644eafa9048b62df": "{count, plural, =1 {1er essai} =2 {2e essai} =3 {3e essai} other {{count}e essai}}", + "e39f89c909df4db0": "Impossible de reprendre l’exécution", + "865f034346b82f47": "Annuler {title} ? Ses agents s’arrêtent et l’exécution ne pourra pas être reprise.", + "6bc75632fd9c9136": "Impossible d’annuler l’exécution", + "64e50329dcfdd5b0": "Terminée", + "350162e7cc1ebea4": "Arrêtée", + "0875cf506f4c6810": "Ignorée", + "3cc43f1dbf3f8e0c": "Annulée", + "ded70e75de6404ba": "Retour à la liste des exécutions", + "2f4ed7dbd22be30d": "Annuler l’exécution", + "614e5ad58a795fb5": "Stop", + "04b050b0329f0ac8": "a duré {duration}", + "aff78e1774818ff4": "{duration} jusqu’ici", + "38eddd466439afc9": "Ce que l’exécution a touché", + "156ec271d49ddd70": "Ce qui s’est passé", + "34f59bbbead0b97f": "{names} et {count} de plus", + "ac1556f6ce89a5ea": "{count} en parallèle", + "e197c4963bacc746": "{count} en cours", + "f5319ed9e18c0df1": "Vous pose une question", + "882a25e9084ae1b2": "En pause", + "9a03d8a9afc60387": "Étapes jusqu’ici", + "2f2ae791afe01674": "attend ton approbation", + "24f8060c4ccdf928": "démarre", + "30a5be40eb956663": "en cours", + "dd7a1e58c2553933": "réveil dans {duration}", + "95cc952724dd7310": "réveil imminent", + "3cc34921c0128593": "en cours", + "e777db2880f53a46": "personne n’a répondu", + "dc90739d391a5e67": "Vous avez répondu {choice}", + "389f2563b5b763fd": "Étapes rapides", + "a41c8d758121ad81": "en veille", + "9db248b770096984": "a attendu", + "c76124517af28686": "en cours depuis {duration}", + "89102905bf09b0e8": "Suivre en direct", + "bdf338cdff4118f0": "Transcription", + "811e7e992f9ff820": "ne peut pas continuer tant que sa version du workflow n’est pas de nouveau enregistrée", + "4d4cdf035e98dd57": "attend que vous la repreniez", + "eb5b21dd224a5941": "réessaie d’elle-même dans {duration}", + "6ab3dfa749fde477": "va réessayer d’elle-même", + "44b6463aa70aa14c": "Raison de la pause", + "cf25e7169ab0eb7a": "En pause à {step}", + "56c48c1f220f2754": "Impossible de répondre à la question", + "a3c43735e1a81498": "Raison pour {title}", + "bfad234f016cfa3f": "Pourquoi, en une phrase. Elle accompagne la réponse que vous choisissez.", + "004c41aff9c97873": "Exécutions", + "4dc0c244a2419f6c": [ + "Fait partie de ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8c303e8335acb135": [ + "démarrée", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8bffb377e2a6a7de": "sa version n’est plus enregistrée", + "f92d9132f7b85d1a": "Chargement des étapes…", + "6ebc59f64c761a49": "Rien pour l’instant.", + "a759dccd157d7dae": [ + "Vous avez répondu", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + "." + ], + "593b425188346781": [ + "Vous avez répondu", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " : ", + { + "i": 3, + "k": "_gt_value_3", + "v": "v" + } + ], + "c98009be9a273b31": "Ouvrir l’exécution", + "c8eb9be36d4d51ad": [ + "Fil sur ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "3d9761e81798fcd8": "Reprendre", + "8cebd63fc4c967d5": "Seule l’étape en échec est relancée ; ce qui s’est terminé avant est conservé.", + "bc1e0a2a0f1e9552": "Vous attendent", + "a812f51e970740f1": [ + "question posée", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " ", + "· l’exécution vous attend" + ], + "02dfe6c63fd0b8a1": "Ajouter une raison", + "19abd94828a3bdbc": "Demander d’abord à l’agent", + "a18721fa8f328361": "Vous attendent", + "bbf24e7920c1e86b": "En cours", + "8d6e18d2ad832db6": "Toutes", + "f25af5332ffc3734": "Rien n’attend votre réponse.", + "c3f0119b8d6231f8": "Rien n’est en cours.", + "33028dfc1229eaa6": "Aucune exécution pour l’instant.", + "5459bf696a187c26": "Impossible de charger les exécutions de workflow", + "d57c35d43b0f163a": "Cette exécution n’est pas ici", + "b9aae2f7cdb1a379": "Aucune exécution de workflow pour l’instant", + "8f15f66e545af7c0": "Quelles exécutions", + "b6409289e0c9a4dd": "Workflow", + "035cb02ca1ae4952": "Les {count} workflows", + "46d614fa7b4bf1e5": "Exécutions de workflow", + "1c635faa2fb45b8b": "Pas encore exécuté.", + "156ff7b625287a1e": "Masquer les éléments ignorés", + "69b985b97ab45e6b": "Afficher {count} ignorés", + "2400254d362de84d": "Chargement des exécutions de workflow…", + "145e1f7503ba3b2c": [ + "Cet environnement n’a aucune exécution avec ce lien.", + " ", + { + "t": "button", + "i": 1, + "c": "Retour aux exécutions" + } + ], + "783e616cb0476c17": [ + "Un workflow réunit agents, code, planifications et questions qui vous sont posées en une seule exécution qui survit aux redémarrages. Écrivez-en un dans", + " ", + { + "t": "button", + "i": 1, + "c": "Définitions" + }, + ", ou demandez-le à un agent.", + " ", + { + "t": "a", + "i": 2, + "c": "Lire le guide" + } + ], + "cae5c3205c01d062": [ + { + "t": "span", + "i": 1, + "c": "Un fichier de workflow présente un problème." + }, + " ", + "La dernière version valide continue de s’exécuter." + ], + "ed8ce6ebc73dc12d": "Ouvrir le fichier", + "5d8d278ff828102d": "Tous les workflows", + "39459da07479f482": "Agent", + "7741243632056b81": "{step} · transcription", + "c512071143a5ba32": "Ce fil n’existe plus.", + "ed169d23683fb6ac": "Chargement du fil…", + "290e0ab40b87dc17": "Fil d’Ariane des workflows", + "683dd9831e54edc0": "Environnement", + "34ad53646f06ed80": "Les workflows sont désactivés", + "8f6589c9e0ac5d4e": "Aucun environnement connecté", + "744127f8dfad7d22": "Connectez un environnement pour voir ses exécutions de workflow.", + "036182ec7e2ee4d4": "À côté de l’exécution", + "2d6107cb78382d08": "Workflows", + "16f7df687349b399": "Définitions", + "f0a212aadfe1257b": "Chargement de l’éditeur…", + "20f194e003885e95": [ + "Activez-les pour ce serveur dans", + " ", + { + "t": "Link", + "i": 1, + "c": "Paramètres → Labs" + }, + "." + ], "8367779e149f723b": "La requête vers l’environnement principal a échoué pendant {operation} (HTTP {status}).", "c5cd027743a2b5a6": "Jeton d’appairage non valide. Vérifiez le jeton et réessayez.", "0e4b49c8203aae81": "Délai dépassé en attendant la session authentifiée après l’amorçage.", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 2b44f05d584e1..e665b9445f6f9 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -396,6 +396,31 @@ "476ca970255eaea4": "公開 URL を使うには、この環境を T3 Connect にリンクしてください。", "6b80f5b38a8f9950": "このアドレスを呼び出せるのはこのコンピューターだけです。公開 URL を使うには T3 Connect をリンクしてください。", "c5a7b1d3891dd0b8": "この環境のアドレスに到達できる場所ならどこでも動作します (Tailscale や独自のプロキシ経由など)。公開 URL を使うには T3 Connect をリンクしてください。", + "3669395daf36fd33": "このサーバーにはもう登録されていません", + "fe513cf316e796e3": "他のワークフローの一部として実行", + "ccf00b97925efab3": "手動で開始", + "421e585eb092b07b": "{triggers} で開始", + "7bd7c58592671384": "要対応", + "834ca879c14c167b": "作業中", + "582d6df7dfab86fb": "一時停止中", + "ea6583ce92507ee3": "スリープ中", + "7ea8cb8af281ce93": "待機中", + "1347868f2523140e": "完了", + "57d76c4614054271": "停止", + "5c7344bd51d0b966": "スキップ", + "b2074e9bd23049a6": "キャンセル済み", + "5bb7401807ee2fb5": "質問: {question} ほか {more} 件", + "9e4286183d5f9e34": "質問: {question}", + "474c18d001bd6717": "ステップが失敗しました", + "d3890f4eb1508781": "自身のステップを実行中", + "3e7ced10c9482af0": "{step} が作業中", + "237e1bcb1cf1bdec": "{step} でスリープ中", + "3f7b17ac5a20c8d2": "{run} を実行", + "0306f5f324b8aaa5": "{count} 件の実行が進行中", + "e8fd779b84a202a2": "待機中", + "b6d55657e1a027b8": "{step} を待機中", + "e942562a42aede34": "完了", + "26b2b9727fe11289": "早期終了", "1bb995dcec481554": "{host} でこのデバイスを承認してください。コード {verificationCode} が表示されています。", "8696a33219944832": "WebSocket の認可証明を作成できませんでした。", "5678f133a8631f7d": "クラウドのサインインが変更されました。環境を認可するには、もう一度サインインしてください。", @@ -1743,6 +1768,8 @@ "2e995206e087c3fc": "接続または保留中の入力が解決してから、返信してください。", "604ec3067171a0d7": "会話", "d6182a057ea12624": "親スレッド", + "f2d8537c33cc55a5": "ワークフロー実行のステップ", + "ba8337dca3232880": "実行を開く", "30fa4a764d11ae42": "{name} をダウンロードできませんでした", "4952f87dc98191a7": "添付ファイルを利用できません。", "2fd6d178493fb407": "現在のターンを中断できませんでした。", @@ -1828,6 +1855,7 @@ "04fd71efaa2c3b92": "プルリクエストを開く", "57e875b79b98ab82": "Issue を開く", "f1db0a234c777a1d": "他のアプリで T3 Code を使用 (MCP)", + "6050f22f63e2bcb5": "ワークフローを開く", "a0cc19e60dd99851": "使用量を開く", "46694969044eee98": "次のワークスペース領域にフォーカス", "0a1011328ba42eef": "前のワークスペース領域にフォーカス", @@ -8825,6 +8853,8 @@ "9ae293971d93c819": "スレッドをゲストと共有します。ゲストはブラウザーでライブで閲覧し、あなたが承認したメッセージを送信できます。ゲストリンクを使うには T3 Connect にサインインしてください。", "0aa5406ac4d7f7c7": "ゲストリンク", "f0e853acd2006d53": "リンクされた環境", + "ef10c2dff987f3ea": "このサーバーの T3 ホームにある workflows フォルダーのファイルから、複数ステップのワークフローを実行します。コマンドパレットから開けます。オフの間はそのフォルダーの内容は実行されず、実行はオンに戻るまで待機します。", + "2dadb2359422121c": "ワークフロー", "13e86eb5d8287a71": "Claude または Codex のターンの後、空の入力欄に次のメッセージの予測を表示します。Tab で使用します。毎回、プランでキャッシュされたリクエストが 1 つ追加されます。Codex 0.165 以降が必要です。Claude のスレッドは再起動時に更新されます。", "d4b2a2ec812aafb0": "次のプロンプトを提案", "298c7150a7621c80": "Simlock デバイスホスト", @@ -11765,6 +11795,7 @@ "d443390c4d2dcfd4": "アクセシビリティ a11y スクリーンリーダー NVDA JAWS VoiceOver Orca ナレーター ウィンドウタイトル タブタイトル Alt+Tab タスクバー スレッド ステータス 順序 作業中 承認 accessibility", "6826fa9579c22035": "ベータ 共有 ゲスト 招待 リンク チームメイト 閲覧 T3 Connect トンネル beta share guest", "f10c06cba0cdf7fe": "ベータ リンク 別のマシン VPS ピア エージェント そこで作業 委任 beta link machine", + "bc0b409d89ce086e": "ベータ ワークフロー 永続 実行 自動化 ステップ スケジュール webhook フォルダー beta workflow", "4a21cf825a2045b0": "ベータ Tab 補完 次のメッセージを予測 Claude Codex ゴーストテキスト autocomplete", "fea2dc36585c4a20": "Simlock デバイスホスト (アルファ版)", "9d834d178130180e": "ベータ アルファ simlock callstack シミュレーター エミュレーター iOS Android プール リース ゲートウェイ simulator", @@ -12321,6 +12352,254 @@ "2cddd6095abc734a": "7 日間", "53493056306708cf": "30 日間", "c719359d18d37ad3": "90 日間", + "0bd950151ddc6407": "保存せずに移動しますか?このファイルへの変更は失われます。", + "c0ba3f6756b09f30": "未保存の変更", + "6914e22d357f0ad6": "保存済み、実行中", + "aff389354a031d6f": "ディスク上のファイルを読み込めません。正常に読み込めた最後のバージョンが引き続き実行されます。", + "858effde748ab563": "保存しましたが、まだ実行されていません。", + "ddb37138df660942": "保存されませんでした。サーバー上では何も変更されていません。", + "6ef4db489e40e39e": "保存できませんでした", + "c89624a2e9af1793": "{name} は接続されていません", + "b5a352a43adb4c17": "再接続するとワークフローがまた表示されます。別の環境を選ぶと、その実行を確認できます。", + "3dcedb736d20aae5": "ワークフローファイルを読み取れませんでした", + "b09f4df8d76ae8ea": "{file} を削除しますか?このファイルで定義されたワークフローは開始できなくなります。", + "b4535f5a03689d27": "{name} は接続されていません。ここに書いた内容は残り、再接続後に保存できます。", + "b54c78d85fd942ea": "削除しましたが、実行中の内容はまだ反映されていません。", + "407c228d7da0b7df": "削除されませんでした。サーバー上では何も変更されていません。", + "1a6aa10f3cc14fff": "これらのファイルは互いに整合しません。以前のものが引き続き実行されます。", + "259312516a1dbe6f": "ファイル名", + "2f48ab2aa0586853": "ワークフローの定義なし", + "ba5adfa37b55b8c5": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " 行目:" + ], + "d94eb9ab3201b641": "削除", + "84c900d1ae72adc6": "保存", + "5912d817be03247a": "編集中にディスク上のファイルが変更されました。保存するとその変更が上書きされます。", + "0b1e6f5608826387": "ファイルを読み込んで自分の変更を破棄", + "f47b4c06aeb77c1c": "ワークフローファイルを読み込んでいます…", + "4353bfd401d58f87": [ + { + "t": "code", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " ", + "内のすべてのファイルがワークフローを定義します。変更は再起動なしで反映されます。" + ], + "0c165251a06f10f1": "新しいファイル", + "8e97cf734b4463e7": "作成", + "2ec0d5108fd6cebe": "ワークフローはまだありません。ここで最初のファイルを作成するか、エージェントにそのフォルダーへ作成するよう依頼してください。", + "5601350626e8cfe9": "読み込めません", + "21d778a1b9a0c234": "実行の横で開いているもの", + "62dc4d3a19ff7ca0": "タブを閉じる", + "1e25265f2758fce3": "通常のスレッドとして開く", + "672a3dae06b39402": "専用のページで開く", + "7755500a4cde5066": "ペインを閉じる", + "b8dcbc93a2ca1861": "この実行には含まれなくなりました。", + "115c69de3202f664": "開く", + "644eafa9048b62df": "{count, plural, =1 {1 回目の試行} =2 {2 回目の試行} =3 {3 回目の試行} other {{count} 回目の試行}}", + "e39f89c909df4db0": "実行を再開できませんでした", + "865f034346b82f47": "{title} をキャンセルしますか?エージェントは停止し、この実行は再開できなくなります。", + "6bc75632fd9c9136": "実行をキャンセルできませんでした", + "64e50329dcfdd5b0": "完了", + "350162e7cc1ebea4": "停止", + "0875cf506f4c6810": "スキップ", + "3cc43f1dbf3f8e0c": "キャンセル済み", + "ded70e75de6404ba": "実行一覧に戻る", + "2f4ed7dbd22be30d": "実行をキャンセル", + "614e5ad58a795fb5": "Stop", + "04b050b0329f0ac8": "所要時間 {duration}", + "aff78e1774818ff4": "{duration} 経過", + "38eddd466439afc9": "この実行が扱ったもの", + "156ec271d49ddd70": "経過", + "34f59bbbead0b97f": "{names} ほか {count} 件", + "ac1556f6ce89a5ea": "{count} 件を並行", + "e197c4963bacc746": "{count} 件実行中", + "f5319ed9e18c0df1": "あなたへの質問", + "882a25e9084ae1b2": "一時停止中", + "9a03d8a9afc60387": "これまでのステップ", + "2f2ae791afe01674": "承認待ち", + "24f8060c4ccdf928": "開始中", + "30a5be40eb956663": "作業中", + "dd7a1e58c2553933": "{duration} 後にスリープ解除", + "95cc952724dd7310": "まもなくスリープ解除", + "3cc34921c0128593": "実行中", + "e777db2880f53a46": "回答なし", + "dc90739d391a5e67": "あなたの回答: {choice}", + "389f2563b5b763fd": "短いステップ", + "a41c8d758121ad81": "スリープ", + "9db248b770096984": "待機", + "c76124517af28686": "{duration} 実行中", + "89102905bf09b0e8": "ライブで見る", + "bdf338cdff4118f0": "トランスクリプト", + "811e7e992f9ff820": "ワークフローのバージョンが再登録されるまで続行できません", + "4d4cdf035e98dd57": "手動での再開待ち", + "eb5b21dd224a5941": "{duration} 後に自動で再試行", + "6ab3dfa749fde477": "まもなく自動で再試行", + "44b6463aa70aa14c": "一時停止の理由", + "cf25e7169ab0eb7a": "{step} で一時停止中", + "56c48c1f220f2754": "質問に回答できませんでした", + "a3c43735e1a81498": "{title} の理由", + "bfad234f016cfa3f": "理由を一文で。どの回答を選んでも一緒に送信されます。", + "004c41aff9c97873": "実行", + "4dc0c244a2419f6c": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " の一部" + ], + "8c303e8335acb135": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "に開始" + ], + "8bffb377e2a6a7de": "そのバージョンはもう登録されていません", + "f92d9132f7b85d1a": "ステップを読み込んでいます…", + "6ebc59f64c761a49": "まだ何もありません。", + "a759dccd157d7dae": [ + "あなたの回答: ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + } + ], + "593b425188346781": [ + "あなたの回答: ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + ": ", + { + "i": 3, + "k": "_gt_value_3", + "v": "v" + } + ], + "c98009be9a273b31": "実行を開く", + "c8eb9be36d4d51ad": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " 上のスレッド" + ], + "3d9761e81798fcd8": "再開", + "8cebd63fc4c967d5": "失敗したステップだけが再実行されます。それより前に完了したものは保持されます。", + "bc1e0a2a0f1e9552": "要対応", + "a812f51e970740f1": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "に質問", + " ", + "· 実行はあなたの回答を待っています" + ], + "02dfe6c63fd0b8a1": "理由を追加", + "19abd94828a3bdbc": "先にエージェントに質問", + "a18721fa8f328361": "要対応", + "bbf24e7920c1e86b": "実行中", + "8d6e18d2ad832db6": "すべて", + "f25af5332ffc3734": "対応待ちのものはありません。", + "c3f0119b8d6231f8": "実行中のものはありません。", + "33028dfc1229eaa6": "実行はまだありません。", + "5459bf696a187c26": "ワークフローの実行を読み込めませんでした", + "d57c35d43b0f163a": "この実行はここにありません", + "b9aae2f7cdb1a379": "ワークフローの実行はまだありません", + "8f15f66e545af7c0": "表示する実行", + "b6409289e0c9a4dd": "ワークフロー", + "035cb02ca1ae4952": "すべてのワークフロー ({count} 件)", + "46d614fa7b4bf1e5": "ワークフローの実行", + "1c635faa2fb45b8b": "まだ実行されていません。", + "156ff7b625287a1e": "スキップ済みを非表示", + "69b985b97ab45e6b": "スキップ済み {count} 件を表示", + "2400254d362de84d": "ワークフローの実行を読み込んでいます…", + "145e1f7503ba3b2c": [ + "この環境には、そのリンクの実行はありません。", + " ", + { + "t": "button", + "i": 1, + "c": "実行一覧に戻る" + } + ], + "783e616cb0476c17": [ + "ワークフローは、エージェント、コード、スケジュール、あなたへの質問を、再起動後も継続する 1 つの実行にまとめます。", + { + "t": "button", + "i": 1, + "c": "定義" + }, + " ", + "で作成するか、エージェントに依頼してください。", + " ", + { + "t": "a", + "i": 2, + "c": "ガイドを読む" + } + ], + "cae5c3205c01d062": [ + { + "t": "span", + "i": 1, + "c": "ワークフローファイルに問題があります。" + }, + " ", + "正常に読み込めた最後のバージョンが引き続き実行されます。" + ], + "ed8ce6ebc73dc12d": "ファイルを開く", + "5d8d278ff828102d": "すべてのワークフロー", + "39459da07479f482": "エージェント", + "7741243632056b81": "{step} · トランスクリプト", + "c512071143a5ba32": "このスレッドはもう存在しません。", + "ed169d23683fb6ac": "スレッドを読み込んでいます…", + "290e0ab40b87dc17": "ワークフローのパンくずリスト", + "683dd9831e54edc0": "環境", + "34ad53646f06ed80": "ワークフローはオフです", + "8f6589c9e0ac5d4e": "接続されている環境がありません", + "744127f8dfad7d22": "環境を接続すると、そのワークフローの実行が表示されます。", + "036182ec7e2ee4d4": "実行の横", + "2d6107cb78382d08": "ワークフロー", + "16f7df687349b399": "定義", + "f0a212aadfe1257b": "エディターを読み込んでいます…", + "20f194e003885e95": [ + "このサーバーの", + " ", + { + "t": "Link", + "i": 1, + "c": "設定 → Labs" + }, + " でオンにしてください。" + ], "8367779e149f723b": "プライマリ環境へのリクエストが {operation} 中に失敗しました (HTTP {status})。", "c5cd027743a2b5a6": "ペアリングトークンが無効です。トークンを確認して、もう一度お試しください。", "0e4b49c8203aae81": "ブートストラップ後、認証済みセッションの待機がタイムアウトしました。", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 48dc094c371ad..90614ef54230d 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -396,6 +396,31 @@ "476ca970255eaea4": "공개 URL을 사용하려면 이 환경을 T3 Connect에 연결하세요.", "6b80f5b38a8f9950": "이 컴퓨터에서만 이 주소를 호출할 수 있습니다. 공개 URL을 사용하려면 T3 Connect를 연결하세요.", "c5a7b1d3891dd0b8": "Tailscale이나 자체 프록시처럼 이 환경의 주소에 접근할 수 있는 곳이면 어디서든 작동합니다. 공개 URL을 사용하려면 T3 Connect를 연결하세요.", + "3669395daf36fd33": "이 서버에 더 이상 등록되어 있지 않음", + "fe513cf316e796e3": "다른 워크플로의 일부로 실행", + "ccf00b97925efab3": "수동으로 시작", + "421e585eb092b07b": "{triggers}에서 시작", + "7bd7c58592671384": "확인 필요", + "834ca879c14c167b": "작업 중", + "582d6df7dfab86fb": "일시 중지됨", + "ea6583ce92507ee3": "슬립 중", + "7ea8cb8af281ce93": "대기 중", + "1347868f2523140e": "완료", + "57d76c4614054271": "중지됨", + "5c7344bd51d0b966": "건너뜀", + "b2074e9bd23049a6": "취소됨", + "5bb7401807ee2fb5": "질문: {question} 외 {more}개", + "9e4286183d5f9e34": "질문: {question}", + "474c18d001bd6717": "단계 실패", + "d3890f4eb1508781": "자체 단계 실행 중", + "3e7ced10c9482af0": "{step} 작업 중", + "237e1bcb1cf1bdec": "{step}에서 슬립 중", + "3f7b17ac5a20c8d2": "{run} 실행", + "0306f5f324b8aaa5": "실행 {count}개 진행 중", + "e8fd779b84a202a2": "대기 중", + "b6d55657e1a027b8": "{step} 대기 중", + "e942562a42aede34": "완료", + "26b2b9727fe11289": "조기 종료", "1bb995dcec481554": "{host}에서 이 기기를 승인하세요. 코드 {verificationCode}이(가) 표시됩니다.", "8696a33219944832": "WebSocket 인증 증명을 만들 수 없습니다.", "5678f133a8631f7d": "클라우드 로그인이 변경되었습니다. 환경을 인증하려면 다시 로그인하세요.", @@ -1743,6 +1768,8 @@ "2e995206e087c3fc": "연결 또는 대기 중인 입력이 해결된 후 답장해 보세요.", "604ec3067171a0d7": "대화", "d6182a057ea12624": "상위 스레드", + "f2d8537c33cc55a5": "워크플로 실행의 단계", + "ba8337dca3232880": "실행 열기", "30fa4a764d11ae42": "{name}을(를) 다운로드할 수 없습니다", "4952f87dc98191a7": "첨부 파일을 사용할 수 없습니다.", "2fd6d178493fb407": "현재 턴을 중단하지 못했습니다.", @@ -1828,6 +1855,7 @@ "04fd71efaa2c3b92": "풀 리퀘스트 열기", "57e875b79b98ab82": "이슈 열기", "f1db0a234c777a1d": "다른 앱에서 T3 Code 사용(MCP)", + "6050f22f63e2bcb5": "워크플로 열기", "a0cc19e60dd99851": "사용량 열기", "46694969044eee98": "다음 작업 영역으로 포커스 이동", "0a1011328ba42eef": "이전 작업 영역으로 포커스 이동", @@ -8828,6 +8856,8 @@ "9ae293971d93c819": "브라우저에서 실시간으로 지켜보고 승인한 메시지를 보낼 수 있는 게스트와 스레드를 공유합니다. 게스트 링크를 사용하려면 T3 Connect에 로그인하세요.", "0aa5406ac4d7f7c7": "게스트 링크", "f0e853acd2006d53": "연결된 환경", + "ef10c2dff987f3ea": "이 서버 T3 홈의 workflows 폴더에 있는 파일로 여러 단계의 워크플로를 실행합니다. 명령 팔레트에서 엽니다. 꺼져 있는 동안에는 그 폴더의 어떤 것도 실행되지 않으며, 실행은 다시 켤 때까지 기다립니다.", + "2dadb2359422121c": "워크플로", "13e86eb5d8287a71": "Claude 또는 Codex 턴이 끝난 뒤 빈 입력창에 예상되는 다음 메시지를 표시합니다. Tab을 누르면 사용합니다. 제안마다 요금제에서 캐시된 요청이 하나 더 발생합니다. Codex 0.165 이상이 필요합니다. Claude 스레드는 다시 시작하면 업데이트됩니다.", "d4b2a2ec812aafb0": "다음 프롬프트 제안", "298c7150a7621c80": "Simlock 기기 호스트", @@ -11761,6 +11791,7 @@ "d443390c4d2dcfd4": "접근성 a11y 화면 낭독기 nvda jaws voiceover orca 내레이터 창 제목 탭 제목 alt tab 작업 표시줄 스레드 상태 순서 작업 중 승인", "6826fa9579c22035": "베타 공유 게스트 초대 링크 팀원 지켜보기 T3 Connect 터널", "f10c06cba0cdf7fe": "베타 다른 머신 연결 vps 피어 에이전트 원격 작업 위임", + "bc0b409d89ce086e": "베타 워크플로 workflow 지속 실행 자동화 단계 일정 webhook 폴더", "4a21cf825a2045b0": "베타 탭 자동 완성 다음 메시지 예측 Claude Codex 고스트 텍스트", "fea2dc36585c4a20": "Simlock 기기 호스트(알파)", "9d834d178130180e": "베타 알파 simlock callstack 시뮬레이터 에뮬레이터 iOS Android 풀 임대 게이트웨이", @@ -12317,6 +12348,255 @@ "2cddd6095abc734a": "7일", "53493056306708cf": "30일", "c719359d18d37ad3": "90일", + "0bd950151ddc6407": "저장하지 않고 나갈까요? 이 파일의 변경 사항이 사라집니다.", + "c0ba3f6756b09f30": "저장되지 않은 변경 사항", + "6914e22d357f0ad6": "저장되어 실행 중", + "aff389354a031d6f": "디스크의 파일을 불러올 수 없습니다. 마지막으로 불러온 버전이 계속 실행됩니다.", + "858effde748ab563": "저장했지만 아직 실행되지 않습니다.", + "ddb37138df660942": "저장되지 않았습니다. 서버에서 변경된 것은 없습니다.", + "6ef4db489e40e39e": "저장할 수 없습니다", + "c89624a2e9af1793": "{name}이(가) 연결되어 있지 않습니다", + "b5a352a43adb4c17": "다시 연결되면 워크플로가 다시 표시됩니다. 다른 환경을 선택하면 그 환경의 실행을 볼 수 있습니다.", + "3dcedb736d20aae5": "워크플로 파일을 읽을 수 없습니다", + "b09f4df8d76ae8ea": "{file}을(를) 삭제할까요? 이 파일에 정의된 워크플로는 더 이상 시작할 수 없습니다.", + "b4535f5a03689d27": "{name}이(가) 연결되어 있지 않습니다. 여기에 작성한 내용은 유지되며, 다시 연결되면 저장할 수 있습니다.", + "b54c78d85fd942ea": "삭제했지만 실행 중인 내용에 아직 반영되지 않았습니다.", + "407c228d7da0b7df": "삭제되지 않았습니다. 서버에서 변경된 것은 없습니다.", + "1a6aa10f3cc14fff": "이 파일들은 서로 맞지 않습니다. 이전에 실행되던 것이 계속 실행됩니다.", + "259312516a1dbe6f": "파일 이름", + "2f48ab2aa0586853": "정의된 워크플로 없음", + "ba5adfa37b55b8c5": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "번째 줄:" + ], + "d94eb9ab3201b641": "삭제", + "84c900d1ae72adc6": "저장", + "5912d817be03247a": "편집하는 동안 디스크의 파일이 변경되었습니다. 저장하면 해당 변경 사항을 덮어씁니다.", + "0b1e6f5608826387": "파일을 불러오고 내 변경 사항 버리기", + "f47b4c06aeb77c1c": "워크플로 파일을 불러오는 중…", + "4353bfd401d58f87": [ + { + "t": "code", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + "의 모든 파일이 워크플로를 정의합니다. 파일을 변경하면 다시 시작하지 않아도 반영됩니다." + ], + "0c165251a06f10f1": "새 파일", + "8e97cf734b4463e7": "만들기", + "2ec0d5108fd6cebe": "아직 워크플로가 없습니다. 여기에서 첫 파일을 만들거나 에이전트에게 해당 폴더에 작성해 달라고 요청하세요.", + "5601350626e8cfe9": "불러올 수 없음", + "21d778a1b9a0c234": "실행 옆에 열린 항목", + "62dc4d3a19ff7ca0": "탭 닫기", + "1e25265f2758fce3": "전체 스레드로 열기", + "672a3dae06b39402": "전용 페이지에서 열기", + "7755500a4cde5066": "창 닫기", + "b8dcbc93a2ca1861": "이 실행에 더 이상 포함되지 않습니다.", + "115c69de3202f664": "열기", + "644eafa9048b62df": "{count, plural, =1 {1번째 시도} =2 {2번째 시도} =3 {3번째 시도} other {{count}번째 시도}}", + "e39f89c909df4db0": "실행을 재개할 수 없습니다", + "865f034346b82f47": "{title}을(를) 취소할까요? 에이전트가 중지되며 이 실행은 재개할 수 없습니다.", + "6bc75632fd9c9136": "실행을 취소할 수 없습니다", + "64e50329dcfdd5b0": "완료", + "350162e7cc1ebea4": "중지됨", + "0875cf506f4c6810": "건너뜀", + "3cc43f1dbf3f8e0c": "취소됨", + "ded70e75de6404ba": "실행 목록으로 돌아가기", + "2f4ed7dbd22be30d": "실행 취소", + "614e5ad58a795fb5": "Stop", + "04b050b0329f0ac8": "{duration} 소요", + "aff78e1774818ff4": "현재까지 {duration}", + "38eddd466439afc9": "이 실행이 다룬 항목", + "156ec271d49ddd70": "진행 내역", + "34f59bbbead0b97f": "{names} 외 {count}개", + "ac1556f6ce89a5ea": "{count}개 병렬", + "e197c4963bacc746": "{count}개 실행 중", + "f5319ed9e18c0df1": "사용자에게 질문", + "882a25e9084ae1b2": "일시 중지됨", + "9a03d8a9afc60387": "지금까지의 단계", + "2f2ae791afe01674": "승인을 기다리는 중", + "24f8060c4ccdf928": "시작하는 중", + "30a5be40eb956663": "작업 중", + "dd7a1e58c2553933": "{duration} 후 깨어남", + "95cc952724dd7310": "곧 깨어남", + "3cc34921c0128593": "실행 중", + "e777db2880f53a46": "응답 없음", + "dc90739d391a5e67": "내 답변: {choice}", + "389f2563b5b763fd": "빠른 단계", + "a41c8d758121ad81": "슬립", + "9db248b770096984": "대기", + "c76124517af28686": "{duration}째 실행 중", + "89102905bf09b0e8": "실시간 보기", + "bdf338cdff4118f0": "대화 기록", + "811e7e992f9ff820": "워크플로 버전이 다시 등록될 때까지 계속할 수 없음", + "4d4cdf035e98dd57": "사용자가 재개하기를 기다리는 중", + "eb5b21dd224a5941": "{duration} 후 자동으로 다시 시도", + "6ab3dfa749fde477": "곧 자동으로 다시 시도", + "44b6463aa70aa14c": "일시 중지된 이유", + "cf25e7169ab0eb7a": "{step}에서 일시 중지됨", + "56c48c1f220f2754": "질문에 답변할 수 없습니다", + "a3c43735e1a81498": "{title}의 이유", + "bfad234f016cfa3f": "이유를 한 문장으로 적어 주세요. 어떤 답변을 고르든 함께 전달됩니다.", + "004c41aff9c97873": "실행", + "4dc0c244a2419f6c": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "의 일부" + ], + "8c303e8335acb135": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " ", + "시작" + ], + "8bffb377e2a6a7de": "해당 버전이 더 이상 등록되어 있지 않음", + "f92d9132f7b85d1a": "단계를 불러오는 중…", + "6ebc59f64c761a49": "아직 아무것도 없습니다.", + "a759dccd157d7dae": [ + "내 답변: ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + } + ], + "593b425188346781": [ + "내 답변: ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + ": ", + { + "i": 3, + "k": "_gt_value_3", + "v": "v" + } + ], + "c98009be9a273b31": "실행 열기", + "c8eb9be36d4d51ad": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "의 스레드" + ], + "3d9761e81798fcd8": "재개", + "8cebd63fc4c967d5": "실패한 단계만 다시 실행되며, 그 전에 완료된 내용은 유지됩니다.", + "bc1e0a2a0f1e9552": "확인 필요", + "a812f51e970740f1": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " ", + "질문", + " ", + "· 실행이 답변을 기다리는 중" + ], + "02dfe6c63fd0b8a1": "이유 추가", + "19abd94828a3bdbc": "먼저 에이전트에게 묻기", + "a18721fa8f328361": "확인 필요", + "bbf24e7920c1e86b": "실행 중", + "8d6e18d2ad832db6": "전체", + "f25af5332ffc3734": "확인이 필요한 항목이 없습니다.", + "c3f0119b8d6231f8": "실행 중인 항목이 없습니다.", + "33028dfc1229eaa6": "아직 실행이 없습니다.", + "5459bf696a187c26": "워크플로 실행을 불러올 수 없습니다", + "d57c35d43b0f163a": "이 실행은 여기에 없습니다", + "b9aae2f7cdb1a379": "아직 워크플로 실행이 없습니다", + "8f15f66e545af7c0": "표시할 실행", + "b6409289e0c9a4dd": "워크플로", + "035cb02ca1ae4952": "워크플로 {count}개 전체", + "46d614fa7b4bf1e5": "워크플로 실행", + "1c635faa2fb45b8b": "아직 실행된 적이 없습니다.", + "156ff7b625287a1e": "건너뛴 항목 숨기기", + "69b985b97ab45e6b": "건너뛴 항목 {count}개 표시", + "2400254d362de84d": "워크플로 실행을 불러오는 중…", + "145e1f7503ba3b2c": [ + "이 환경에는 해당 링크의 실행이 없습니다.", + " ", + { + "t": "button", + "i": 1, + "c": "실행 목록으로 돌아가기" + } + ], + "783e616cb0476c17": [ + "워크플로는 에이전트, 코드, 일정, 사용자에게 묻는 질문을 다시 시작해도 유지되는 하나의 실행으로 묶습니다.", + " ", + { + "t": "button", + "i": 1, + "c": "정의" + }, + "에서 직접 작성하거나 에이전트에게 요청하세요.", + " ", + { + "t": "a", + "i": 2, + "c": "가이드 읽기" + } + ], + "cae5c3205c01d062": [ + { + "t": "span", + "i": 1, + "c": "워크플로 파일에 문제가 있습니다." + }, + " ", + "마지막으로 불러온 버전이 계속 실행됩니다." + ], + "ed8ce6ebc73dc12d": "파일 열기", + "5d8d278ff828102d": "모든 워크플로", + "39459da07479f482": "에이전트", + "7741243632056b81": "{step} · 기록", + "c512071143a5ba32": "이 스레드는 더 이상 존재하지 않습니다.", + "ed169d23683fb6ac": "스레드를 불러오는 중…", + "290e0ab40b87dc17": "워크플로 탐색 경로", + "683dd9831e54edc0": "환경", + "34ad53646f06ed80": "워크플로가 꺼져 있습니다", + "8f6589c9e0ac5d4e": "연결된 환경 없음", + "744127f8dfad7d22": "환경을 연결하면 해당 환경의 워크플로 실행을 볼 수 있습니다.", + "036182ec7e2ee4d4": "실행 옆", + "2d6107cb78382d08": "워크플로", + "16f7df687349b399": "정의", + "f0a212aadfe1257b": "편집기를 불러오는 중…", + "20f194e003885e95": [ + "이 서버의", + " ", + { + "t": "Link", + "i": 1, + "c": "설정 → Labs" + }, + "에서 켜세요." + ], "8367779e149f723b": "{operation} 중 기본 환경 요청에 실패했습니다(HTTP {status}).", "c5cd027743a2b5a6": "잘못된 페어링 토큰입니다. 토큰을 확인하고 다시 시도하세요.", "0e4b49c8203aae81": "부트스트랩 후 인증된 세션을 기다리다 시간이 초과되었습니다.", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 9cc052192b4eb..e8d50d83a5f44 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -396,6 +396,31 @@ "476ca970255eaea4": "Vincule este ambiente ao T3 Connect para ter uma URL pública.", "6b80f5b38a8f9950": "Só este computador pode acessar este endereço. Vincule o T3 Connect para ter uma URL pública.", "c5a7b1d3891dd0b8": "Funciona onde o endereço deste ambiente for acessível, por exemplo pelo Tailscale ou pelo seu próprio proxy. Vincule o T3 Connect para ter uma URL pública.", + "3669395daf36fd33": "Não está mais registrado neste servidor", + "fe513cf316e796e3": "Executa como parte de outros workflows", + "ccf00b97925efab3": "Iniciado manualmente", + "421e585eb092b07b": "Inicia com {triggers}", + "7bd7c58592671384": "Precisam de você", + "834ca879c14c167b": "Trabalhando", + "582d6df7dfab86fb": "Pausada", + "ea6583ce92507ee3": "Dormindo", + "7ea8cb8af281ce93": "Aguardando", + "1347868f2523140e": "Concluída", + "57d76c4614054271": "Parada", + "5c7344bd51d0b966": "Pulada", + "b2074e9bd23049a6": "Cancelada", + "5bb7401807ee2fb5": "Pergunta: {question} e mais {more}", + "9e4286183d5f9e34": "Pergunta: {question}", + "474c18d001bd6717": "Uma etapa falhou", + "d3890f4eb1508781": "Executando as próprias etapas", + "3e7ced10c9482af0": "{step} está trabalhando", + "237e1bcb1cf1bdec": "Dormindo em {step}", + "3f7b17ac5a20c8d2": "Executa {run}", + "0306f5f324b8aaa5": "{count} execuções em andamento", + "e8fd779b84a202a2": "Aguardando", + "b6d55657e1a027b8": "Aguardando {step}", + "e942562a42aede34": "Concluída", + "26b2b9727fe11289": "Encerrada antes do fim", "1bb995dcec481554": "Aprove este dispositivo em {host}. Ele mostra o código {verificationCode}.", "8696a33219944832": "Não foi possível criar a prova de autorização do websocket.", "5678f133a8631f7d": "Seu login na nuvem mudou. Entre novamente para autorizar o ambiente.", @@ -1744,6 +1769,8 @@ "2e995206e087c3fc": "Tente responder depois que a conexão ou a resposta pendente for resolvida.", "604ec3067171a0d7": "Conversa", "d6182a057ea12624": "Thread principal", + "f2d8537c33cc55a5": "Etapa da execução do workflow", + "ba8337dca3232880": "Abrir execução", "30fa4a764d11ae42": "Não foi possível baixar {name}", "4952f87dc98191a7": "O anexo não está disponível.", "2fd6d178493fb407": "Falha ao interromper o turno atual.", @@ -1829,6 +1856,7 @@ "04fd71efaa2c3b92": "Abrir pull requests", "57e875b79b98ab82": "Abrir issues", "f1db0a234c777a1d": "Usar o T3 Code em outro app (MCP)", + "6050f22f63e2bcb5": "Abrir workflows", "a0cc19e60dd99851": "Abrir uso", "46694969044eee98": "Focar a próxima área do workspace", "0a1011328ba42eef": "Focar a área anterior do workspace", @@ -8867,6 +8895,8 @@ "9ae293971d93c819": "Compartilhe uma thread com um convidado que a acompanha ao vivo no navegador e envia mensagens que você aprova. Entre no T3 Connect para usar links de convidado.", "0aa5406ac4d7f7c7": "Links de convidado", "f0e853acd2006d53": "Ambientes vinculados", + "ef10c2dff987f3ea": "Execute workflows de várias etapas a partir de arquivos na pasta workflows da pasta T3 deste servidor. Abra-os pela paleta de comandos. Enquanto estiver desativado, nada dessa pasta é executado; as execuções aguardam até que seja ativado novamente.", + "2dadb2359422121c": "Workflows", "13e86eb5d8287a71": "Mostra uma próxima mensagem prevista no editor vazio após um turno do Claude ou do Codex. Tab a usa. Cada uma é uma requisição extra em cache no seu plano. Requer Codex 0.165+. As threads do Claude são atualizadas ao reiniciar.", "d4b2a2ec812aafb0": "Sugerir próximo prompt", "298c7150a7621c80": "Hosts de dispositivos Simlock", @@ -11814,6 +11844,7 @@ "d443390c4d2dcfd4": "acessibilidade a11y leitor de tela nvda jaws voiceover orca narrador título da janela título da aba alt tab barra de tarefas status da thread ordem trabalhando aprovação", "6826fa9579c22035": "beta compartilhar convidado convite link colega acompanhar t3 connect túnel", "f10c06cba0cdf7fe": "beta vincular outra máquina vps par agentes trabalham lá delegar", + "bc0b409d89ce086e": "beta workflow execuções duráveis automação etapas agendamento webhook pasta", "4a21cf825a2045b0": "beta tab autocompletar prever próxima mensagem claude codex texto fantasma", "fea2dc36585c4a20": "Hosts de dispositivos Simlock (alfa)", "9d834d178130180e": "beta alpha simlock callstack simulador emulador ios android pool lease gateway", @@ -12370,6 +12401,262 @@ "2cddd6095abc734a": "7 dias", "53493056306708cf": "30 dias", "c719359d18d37ad3": "90 dias", + "0bd950151ddc6407": "Sair sem salvar? Suas alterações neste arquivo serão perdidas.", + "c0ba3f6756b09f30": "Alterações não salvas", + "6914e22d357f0ad6": "Salvo e em execução", + "aff389354a031d6f": "O arquivo no disco não carrega. A última versão que carregou continua em execução.", + "858effde748ab563": "Salvo, mas ainda não está em execução.", + "ddb37138df660942": "Não salvo. Nada mudou no servidor.", + "6ef4db489e40e39e": "Não foi possível salvar", + "c89624a2e9af1793": "{name} não está conectado", + "b5a352a43adb4c17": "Os fluxos de trabalho dele voltam a aparecer quando ele se reconectar. Escolha outro ambiente para ver as execuções dele.", + "3dcedb736d20aae5": "Não foi possível ler os arquivos de workflow", + "b09f4df8d76ae8ea": "Excluir {file}? Os workflows que ele define não poderão mais ser iniciados.", + "b4535f5a03689d27": "{name} não está conectado. O que você escrever aqui fica guardado e pode ser salvo assim que ele voltar.", + "b54c78d85fd942ea": "Excluído, mas o que está em execução ainda não foi atualizado.", + "407c228d7da0b7df": "Não excluído. Nada mudou no servidor.", + "1a6aa10f3cc14fff": "Estes arquivos não são compatíveis entre si. O que rodava antes continua em execução.", + "259312516a1dbe6f": "Nome do arquivo", + "2f48ab2aa0586853": "Não define nenhum workflow", + "ba5adfa37b55b8c5": [ + "Linha ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ":" + ], + "d94eb9ab3201b641": "Excluir", + "84c900d1ae72adc6": "Salvar", + "5912d817be03247a": "O arquivo mudou no disco enquanto você editava. Salvar substitui essa alteração.", + "0b1e6f5608826387": "Carregar o arquivo e descartar minhas alterações", + "f47b4c06aeb77c1c": "Carregando os arquivos de workflow…", + "4353bfd401d58f87": [ + "Cada arquivo em", + " ", + { + "t": "code", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " ", + "define workflows. Uma alteração em qualquer um deles é aplicada sem reiniciar." + ], + "0c165251a06f10f1": "Novo arquivo", + "8e97cf734b4463e7": "Criar", + "2ec0d5108fd6cebe": "Nenhum workflow ainda. Crie o primeiro arquivo aqui ou peça a um agente para escrever um nessa pasta.", + "5601350626e8cfe9": "Não carrega", + "21d778a1b9a0c234": "Aberto ao lado da execução", + "62dc4d3a19ff7ca0": "Fechar aba", + "1e25265f2758fce3": "Abrir como thread completa", + "672a3dae06b39402": "Abrir na própria página", + "7755500a4cde5066": "Fechar o painel", + "b8dcbc93a2ca1861": "Esta execução não o lista mais.", + "115c69de3202f664": "Abrir", + "644eafa9048b62df": "{count, plural, =1 {1ª tentativa} =2 {2ª tentativa} =3 {3ª tentativa} other {{count}ª tentativa}}", + "e39f89c909df4db0": "Não foi possível retomar a execução", + "865f034346b82f47": "Cancelar {title}? Os agentes param e a execução não pode ser retomada.", + "6bc75632fd9c9136": "Não foi possível cancelar a execução", + "64e50329dcfdd5b0": "Concluída", + "350162e7cc1ebea4": "Parada", + "0875cf506f4c6810": "Pulada", + "3cc43f1dbf3f8e0c": "Cancelada", + "ded70e75de6404ba": "Voltar à lista de execuções", + "2f4ed7dbd22be30d": "Cancelar execução", + "614e5ad58a795fb5": "Stop", + "04b050b0329f0ac8": "levou {duration}", + "aff78e1774818ff4": "{duration} até agora", + "38eddd466439afc9": "O que a execução tocou", + "156ec271d49ddd70": "O que aconteceu", + "34f59bbbead0b97f": "{names} e mais {count}", + "ac1556f6ce89a5ea": "{count} em paralelo", + "e197c4963bacc746": "{count} em execução", + "f5319ed9e18c0df1": "Pergunta a você", + "882a25e9084ae1b2": "Pausada", + "9a03d8a9afc60387": "Etapas até agora", + "2f2ae791afe01674": "aguarda sua aprovação", + "24f8060c4ccdf928": "iniciando", + "30a5be40eb956663": "trabalhando", + "dd7a1e58c2553933": "acorda em {duration}", + "95cc952724dd7310": "prestes a acordar", + "3cc34921c0128593": "em execução", + "e777db2880f53a46": "ninguém respondeu", + "dc90739d391a5e67": "Você disse {choice}", + "389f2563b5b763fd": "Etapas rápidas", + "a41c8d758121ad81": "em espera", + "9db248b770096984": "aguardou", + "c76124517af28686": "em execução há {duration}", + "89102905bf09b0e8": "Assistir ao vivo", + "bdf338cdff4118f0": "Transcrição", + "811e7e992f9ff820": "não pode continuar até que a versão do workflow seja registrada novamente", + "4d4cdf035e98dd57": "aguarda você retomá-la", + "eb5b21dd224a5941": "tenta de novo sozinha em {duration}", + "6ab3dfa749fde477": "prestes a tentar de novo sozinha", + "44b6463aa70aa14c": "Por que pausou", + "cf25e7169ab0eb7a": "Pausada em {step}", + "56c48c1f220f2754": "Não foi possível responder à pergunta", + "a3c43735e1a81498": "Motivo para {title}", + "bfad234f016cfa3f": "O motivo, em uma frase. Ele acompanha a resposta que você escolher.", + "004c41aff9c97873": "Execuções", + "4dc0c244a2419f6c": [ + "Parte de ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8c303e8335acb135": [ + "iniciada", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8bffb377e2a6a7de": "sua versão não está mais registrada", + "f92d9132f7b85d1a": "Carregando etapas…", + "6ebc59f64c761a49": "Nada ainda.", + "a759dccd157d7dae": [ + "Você disse", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + "." + ], + "593b425188346781": [ + "Você disse", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + ": ", + { + "i": 3, + "k": "_gt_value_3", + "v": "v" + } + ], + "c98009be9a273b31": "Abrir execução", + "c8eb9be36d4d51ad": [ + "Thread em ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "3d9761e81798fcd8": "Retomar", + "8cebd63fc4c967d5": "Só a etapa que falhou é executada de novo; o que terminou antes dela é mantido.", + "bc1e0a2a0f1e9552": "Precisam de você", + "a812f51e970740f1": [ + "perguntou", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " ", + "· a execução aguarda você" + ], + "02dfe6c63fd0b8a1": "Adicionar um motivo", + "19abd94828a3bdbc": "Perguntar ao agente primeiro", + "a18721fa8f328361": "Precisam de você", + "bbf24e7920c1e86b": "Em execução", + "8d6e18d2ad832db6": "Todas", + "f25af5332ffc3734": "Nada aguarda você.", + "c3f0119b8d6231f8": "Nada em execução.", + "33028dfc1229eaa6": "Nenhuma execução ainda.", + "5459bf696a187c26": "Não foi possível carregar as execuções de workflow", + "d57c35d43b0f163a": "Esta execução não está aqui", + "b9aae2f7cdb1a379": "Nenhuma execução de workflow ainda", + "8f15f66e545af7c0": "Quais execuções", + "b6409289e0c9a4dd": "Workflow", + "035cb02ca1ae4952": "Todos os workflows ({count})", + "46d614fa7b4bf1e5": "Execuções de workflow", + "1c635faa2fb45b8b": "Ainda não foi executado.", + "156ff7b625287a1e": "Ocultar puladas", + "69b985b97ab45e6b": "Mostrar puladas ({count})", + "2400254d362de84d": "Carregando execuções de workflow…", + "145e1f7503ba3b2c": [ + "Este ambiente não tem nenhuma execução com esse link.", + " ", + { + "t": "button", + "i": 1, + "c": "Voltar às execuções" + } + ], + "783e616cb0476c17": [ + "Um workflow reúne agentes, código, agendamentos e perguntas para você em uma única execução que sobrevive a reinicializações. Escreva um em", + " ", + { + "t": "button", + "i": 1, + "c": "Definições" + }, + ", ou peça a um agente.", + " ", + { + "t": "a", + "i": 2, + "c": "Leia o guia" + } + ], + "cae5c3205c01d062": [ + { + "t": "span", + "i": 1, + "c": "Um arquivo de workflow tem um problema." + }, + " ", + "A última versão que carregou continua em execução." + ], + "ed8ce6ebc73dc12d": "Abrir o arquivo", + "5d8d278ff828102d": "Todos os workflows", + "39459da07479f482": "Agente", + "7741243632056b81": "{step} · transcrição", + "c512071143a5ba32": "Esta thread não existe mais.", + "ed169d23683fb6ac": "Carregando a thread…", + "290e0ab40b87dc17": "Trilha de navegação de workflows", + "683dd9831e54edc0": "Ambiente", + "34ad53646f06ed80": "Os workflows estão desativados", + "8f6589c9e0ac5d4e": "Nenhum ambiente conectado", + "744127f8dfad7d22": "Conecte um ambiente para ver as execuções de workflow dele.", + "036182ec7e2ee4d4": "Ao lado da execução", + "2d6107cb78382d08": "Workflows", + "16f7df687349b399": "Definições", + "f0a212aadfe1257b": "Carregando o editor…", + "20f194e003885e95": [ + "Ative-os para este servidor em", + " ", + { + "t": "Link", + "i": 1, + "c": "Configurações → Labs" + }, + "." + ], "8367779e149f723b": "A requisição ao ambiente principal falhou durante {operation} (HTTP {status}).", "c5cd027743a2b5a6": "Token de pareamento inválido. Verifique o token e tente novamente.", "0e4b49c8203aae81": "Tempo esgotado aguardando a sessão autenticada após a inicialização.", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 1d8bc14fde51f..f15a9f71b21f2 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -396,6 +396,31 @@ "476ca970255eaea4": "Привяжите это окружение к T3 Connect, чтобы получить публичный URL.", "6b80f5b38a8f9950": "Обращаться к этому адресу может только этот компьютер. Привяжите T3 Connect, чтобы получить публичный URL.", "c5a7b1d3891dd0b8": "Работает везде, где доступен адрес этого окружения, например через Tailscale или ваш прокси. Привяжите T3 Connect, чтобы получить публичный URL.", + "3669395daf36fd33": "Больше не зарегистрирован на этом сервере", + "fe513cf316e796e3": "Запускается в составе других воркфлоу", + "ccf00b97925efab3": "Запускается вручную", + "421e585eb092b07b": "Запускается по: {triggers}", + "7bd7c58592671384": "Ждут вас", + "834ca879c14c167b": "Работает", + "582d6df7dfab86fb": "Приостановлен", + "ea6583ce92507ee3": "Спит", + "7ea8cb8af281ce93": "Ожидает", + "1347868f2523140e": "Готово", + "57d76c4614054271": "Остановлен", + "5c7344bd51d0b966": "Пропущен", + "b2074e9bd23049a6": "Отменён", + "5bb7401807ee2fb5": "Спрашивает: {question} и ещё {more}", + "9e4286183d5f9e34": "Спрашивает: {question}", + "474c18d001bd6717": "Шаг завершился ошибкой", + "d3890f4eb1508781": "Выполняет свои шаги", + "3e7ced10c9482af0": "{step} работает", + "237e1bcb1cf1bdec": "Спит на шаге {step}", + "3f7b17ac5a20c8d2": "Запускает {run}", + "0306f5f324b8aaa5": "Запусков в работе: {count}", + "e8fd779b84a202a2": "Ожидает", + "b6d55657e1a027b8": "Ожидает шага {step}", + "e942562a42aede34": "Завершён", + "26b2b9727fe11289": "Завершён досрочно", "1bb995dcec481554": "Подтвердите это устройство на {host}. Там отображается код {verificationCode}.", "8696a33219944832": "Не удалось создать подтверждение авторизации WebSocket.", "5678f133a8631f7d": "Ваш облачный вход изменился. Войдите снова, чтобы авторизовать окружение.", @@ -1744,6 +1769,8 @@ "2e995206e087c3fc": "Попробуйте ответить после восстановления подключения или завершения ожидающего ввода.", "604ec3067171a0d7": "Беседа", "d6182a057ea12624": "Родительский тред", + "f2d8537c33cc55a5": "Шаг запуска воркфлоу", + "ba8337dca3232880": "Открыть запуск", "30fa4a764d11ae42": "Не удалось скачать {name}", "4952f87dc98191a7": "Вложение недоступно.", "2fd6d178493fb407": "Не удалось прервать текущий ход.", @@ -1829,6 +1856,7 @@ "04fd71efaa2c3b92": "Открыть пул-реквесты", "57e875b79b98ab82": "Открыть issue", "f1db0a234c777a1d": "Использовать T3 Code в другом приложении (MCP)", + "6050f22f63e2bcb5": "Открыть воркфлоу", "a0cc19e60dd99851": "Открыть использование", "46694969044eee98": "Фокус на следующую панель рабочей области", "0a1011328ba42eef": "Фокус на предыдущую панель рабочей области", @@ -8869,6 +8897,8 @@ "9ae293971d93c819": "Поделитесь тредом с гостем: он смотрит его в браузере в реальном времени и отправляет сообщения, которые вы одобряете. Войдите в T3 Connect, чтобы использовать гостевые ссылки.", "0aa5406ac4d7f7c7": "Гостевые ссылки", "f0e853acd2006d53": "Привязанные окружения", + "ef10c2dff987f3ea": "Запускайте многошаговые воркфлоу из файлов в папке workflows домашней папки T3 этого сервера. Открывайте их из палитры команд. Пока функция выключена, ничего из этой папки не выполняется; запуски ждут, пока её снова не включат.", + "2dadb2359422121c": "Воркфлоу", "13e86eb5d8287a71": "Показывать предполагаемое следующее сообщение в пустом поле ввода после хода Claude или Codex. Tab вставляет его. Каждое — дополнительный кешированный запрос в рамках вашего плана. Нужен Codex 0.165+. Треды Claude обновятся после перезапуска.", "d4b2a2ec812aafb0": "Предлагать следующий промпт", "298c7150a7621c80": "Хосты устройств Simlock", @@ -11815,6 +11845,7 @@ "d443390c4d2dcfd4": "доступность a11y экранный диктор nvda jaws voiceover orca экранный диктор заголовок окна заголовок вкладки alt tab панель задач статус треда порядок в работе подтверждение", "6826fa9579c22035": "бета поделиться гость приглашение ссылка коллега наблюдать t3 connect туннель", "f10c06cba0cdf7fe": "бета привязать другой компьютер vps агенты работают там делегировать", + "bc0b409d89ce086e": "бета воркфлоу workflow надёжные запуски автоматизация шаги расписание webhook папка", "4a21cf825a2045b0": "бета tab автодополнение предсказать следующее сообщение claude codex подсказка", "fea2dc36585c4a20": "Хосты устройств Simlock (альфа)", "9d834d178130180e": "бета альфа simlock callstack симулятор эмулятор ios android пул аренда шлюз", @@ -12371,6 +12402,262 @@ "2cddd6095abc734a": "7 дней", "53493056306708cf": "30 дней", "c719359d18d37ad3": "90 дней", + "0bd950151ddc6407": "Уйти без сохранения? Изменения в этом файле будут потеряны.", + "c0ba3f6756b09f30": "Несохранённые изменения", + "6914e22d357f0ad6": "Сохранено и работает", + "aff389354a031d6f": "Файл на диске не загружается. Продолжает работать последняя версия, которая загрузилась.", + "858effde748ab563": "Сохранено, но пока не запускается.", + "ddb37138df660942": "Не сохранено. На сервере ничего не изменилось.", + "6ef4db489e40e39e": "Не удалось сохранить", + "c89624a2e9af1793": "{name} не подключено", + "b5a352a43adb4c17": "Его рабочие процессы снова появятся после переподключения. Выберите другое окружение, чтобы увидеть его запуски.", + "3dcedb736d20aae5": "Не удалось прочитать файлы воркфлоу", + "b09f4df8d76ae8ea": "Удалить {file}? Воркфлоу, которые он определяет, больше нельзя будет запустить.", + "b4535f5a03689d27": "{name} не подключено. Написанное здесь сохранится, и его можно будет сохранить, когда подключение вернётся.", + "b54c78d85fd942ea": "Удалено, но то, что запущено, ещё не обновилось.", + "407c228d7da0b7df": "Не удалено. На сервере ничего не изменилось.", + "1a6aa10f3cc14fff": "Эти файлы не согласуются между собой. Продолжает работать то, что работало раньше.", + "259312516a1dbe6f": "Имя файла", + "2f48ab2aa0586853": "Не определяет ни одного воркфлоу", + "ba5adfa37b55b8c5": [ + "Строка ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ":" + ], + "d94eb9ab3201b641": "Удалить", + "84c900d1ae72adc6": "Сохранить", + "5912d817be03247a": "Файл изменился на диске, пока вы его редактировали. Сохранение заменит это изменение.", + "0b1e6f5608826387": "Загрузить файл и сбросить мои изменения", + "f47b4c06aeb77c1c": "Загрузка файлов воркфлоу…", + "4353bfd401d58f87": [ + "Каждый файл в", + " ", + { + "t": "code", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " ", + "определяет воркфлоу. Изменения в любом из них подхватываются без перезапуска." + ], + "0c165251a06f10f1": "Новый файл", + "8e97cf734b4463e7": "Создать", + "2ec0d5108fd6cebe": "Воркфлоу пока нет. Создайте первый файл здесь или попросите агента написать его в этой папке.", + "5601350626e8cfe9": "Не загружается", + "21d778a1b9a0c234": "Открыто рядом с запуском", + "62dc4d3a19ff7ca0": "Закрыть вкладку", + "1e25265f2758fce3": "Открыть как полноценный тред", + "672a3dae06b39402": "Открыть на отдельной странице", + "7755500a4cde5066": "Закрыть панель", + "b8dcbc93a2ca1861": "Этого больше нет в запуске.", + "115c69de3202f664": "Открыть", + "644eafa9048b62df": "{count, plural, =1 {1-я попытка} =2 {2-я попытка} =3 {3-я попытка} one {{count}-я попытка} few {{count}-я попытка} many {{count}-я попытка} other {{count}-я попытка}}", + "e39f89c909df4db0": "Не удалось возобновить запуск", + "865f034346b82f47": "Отменить {title}? Его агенты остановятся, и запуск нельзя будет возобновить.", + "6bc75632fd9c9136": "Не удалось отменить запуск", + "64e50329dcfdd5b0": "Завершён", + "350162e7cc1ebea4": "Остановлен", + "0875cf506f4c6810": "Пропущен", + "3cc43f1dbf3f8e0c": "Отменён", + "ded70e75de6404ba": "Назад к списку запусков", + "2f4ed7dbd22be30d": "Отменить запуск", + "614e5ad58a795fb5": "Stop", + "04b050b0329f0ac8": "занял {duration}", + "aff78e1774818ff4": "пока {duration}", + "38eddd466439afc9": "Что затронул запуск", + "156ec271d49ddd70": "Что произошло", + "34f59bbbead0b97f": "{names} и ещё {count}", + "ac1556f6ce89a5ea": "параллельно: {count}", + "e197c4963bacc746": "выполняется: {count}", + "f5319ed9e18c0df1": "Спрашивает вас", + "882a25e9084ae1b2": "Приостановлен", + "9a03d8a9afc60387": "Шаги на данный момент", + "2f2ae791afe01674": "ждёт вашего одобрения", + "24f8060c4ccdf928": "запускается", + "30a5be40eb956663": "работает", + "dd7a1e58c2553933": "проснётся через {duration}", + "95cc952724dd7310": "вот-вот проснётся", + "3cc34921c0128593": "выполняется", + "e777db2880f53a46": "никто не ответил", + "dc90739d391a5e67": "Вы ответили: {choice}", + "389f2563b5b763fd": "Быстрые шаги", + "a41c8d758121ad81": "спал", + "9db248b770096984": "ждал", + "c76124517af28686": "выполняется {duration}", + "89102905bf09b0e8": "Смотреть вживую", + "bdf338cdff4118f0": "Транскрипт", + "811e7e992f9ff820": "не может продолжиться, пока версия его воркфлоу не будет снова зарегистрирована", + "4d4cdf035e98dd57": "ждёт, пока вы его возобновите", + "eb5b21dd224a5941": "повторит попытку сам через {duration}", + "6ab3dfa749fde477": "вот-вот повторит попытку сам", + "44b6463aa70aa14c": "Почему приостановлен", + "cf25e7169ab0eb7a": "Приостановлен на шаге {step}", + "56c48c1f220f2754": "Не удалось ответить на вопрос", + "a3c43735e1a81498": "Причина: {title}", + "bfad234f016cfa3f": "Причина в одном предложении. Она прикладывается к любому выбранному ответу.", + "004c41aff9c97873": "Запуски", + "4dc0c244a2419f6c": [ + "В составе: ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8c303e8335acb135": [ + "запущен", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8bffb377e2a6a7de": "его версия больше не зарегистрирована", + "f92d9132f7b85d1a": "Загрузка шагов…", + "6ebc59f64c761a49": "Пока ничего.", + "a759dccd157d7dae": [ + "Вы ответили:", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + "." + ], + "593b425188346781": [ + "Вы ответили:", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " — ", + { + "i": 3, + "k": "_gt_value_3", + "v": "v" + } + ], + "c98009be9a273b31": "Открыть запуск", + "c8eb9be36d4d51ad": [ + "Тред на ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "3d9761e81798fcd8": "Возобновить", + "8cebd63fc4c967d5": "Заново выполняется только упавший шаг; всё, что завершилось до него, сохраняется.", + "bc1e0a2a0f1e9552": "Ждут вас", + "a812f51e970740f1": [ + "спросил", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " ", + "· запуск ждёт вас" + ], + "02dfe6c63fd0b8a1": "Добавить причину", + "19abd94828a3bdbc": "Сначала спросить агента", + "a18721fa8f328361": "Ждут вас", + "bbf24e7920c1e86b": "Выполняются", + "8d6e18d2ad832db6": "Все", + "f25af5332ffc3734": "Вас ничего не ждёт.", + "c3f0119b8d6231f8": "Ничего не выполняется.", + "33028dfc1229eaa6": "Запусков пока нет.", + "5459bf696a187c26": "Не удалось загрузить запуски воркфлоу", + "d57c35d43b0f163a": "Этого запуска здесь нет", + "b9aae2f7cdb1a379": "Запусков воркфлоу пока нет", + "8f15f66e545af7c0": "Какие запуски", + "b6409289e0c9a4dd": "Воркфлоу", + "035cb02ca1ae4952": "Все воркфлоу ({count})", + "46d614fa7b4bf1e5": "Запуски воркфлоу", + "1c635faa2fb45b8b": "Ещё не запускался.", + "156ff7b625287a1e": "Скрыть пропущенные", + "69b985b97ab45e6b": "Показать пропущенные ({count})", + "2400254d362de84d": "Загрузка запусков воркфлоу…", + "145e1f7503ba3b2c": [ + "В этом окружении нет запуска по этой ссылке.", + " ", + { + "t": "button", + "i": 1, + "c": "Вернуться к запускам" + } + ], + "783e616cb0476c17": [ + "Воркфлоу объединяет агентов, код, расписания и вопросы к вам в один запуск, который переживает перезапуски. Напишите его в разделе", + " ", + { + "t": "button", + "i": 1, + "c": "Определения" + }, + " или попросите об этом агента.", + " ", + { + "t": "a", + "i": 2, + "c": "Читать руководство" + } + ], + "cae5c3205c01d062": [ + { + "t": "span", + "i": 1, + "c": "В файле воркфлоу есть ошибка." + }, + " ", + "Продолжает работать последняя версия, которая загрузилась." + ], + "ed8ce6ebc73dc12d": "Открыть файл", + "5d8d278ff828102d": "Все воркфлоу", + "39459da07479f482": "Агент", + "7741243632056b81": "{step} · расшифровка", + "c512071143a5ba32": "Этого треда больше нет.", + "ed169d23683fb6ac": "Загрузка треда…", + "290e0ab40b87dc17": "Навигационная цепочка воркфлоу", + "683dd9831e54edc0": "Окружение", + "34ad53646f06ed80": "Воркфлоу выключены", + "8f6589c9e0ac5d4e": "Нет подключённых окружений", + "744127f8dfad7d22": "Подключите окружение, чтобы увидеть его запуски воркфлоу.", + "036182ec7e2ee4d4": "Рядом с запуском", + "2d6107cb78382d08": "Воркфлоу", + "16f7df687349b399": "Определения", + "f0a212aadfe1257b": "Загрузка редактора…", + "20f194e003885e95": [ + "Включите их для этого сервера в разделе", + " ", + { + "t": "Link", + "i": 1, + "c": "«Настройки → Labs»" + }, + "." + ], "8367779e149f723b": "Запрос к основному окружению не удался во время {operation} (HTTP {status}).", "c5cd027743a2b5a6": "Недействительный токен сопряжения. Проверьте токен и попробуйте ещё раз.", "0e4b49c8203aae81": "Истекло время ожидания аутентифицированного сеанса после начальной загрузки.", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 234479a1b2558..6d53cb0b38d73 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -396,6 +396,31 @@ "476ca970255eaea4": "Länka den här miljön till T3 Connect för en publik URL.", "6b80f5b38a8f9950": "Bara den här datorn kan anropa den här adressen. Länka T3 Connect för en publik URL.", "c5a7b1d3891dd0b8": "Fungerar där den här miljöns adress kan nås, till exempel via Tailscale eller din egen proxy. Länka T3 Connect för en publik URL.", + "3669395daf36fd33": "Inte längre registrerat på den här servern", + "fe513cf316e796e3": "Körs som en del av andra arbetsflöden", + "ccf00b97925efab3": "Startas manuellt", + "421e585eb092b07b": "Startar vid {triggers}", + "7bd7c58592671384": "Behöver dig", + "834ca879c14c167b": "Arbetar", + "582d6df7dfab86fb": "Pausad", + "ea6583ce92507ee3": "Sover", + "7ea8cb8af281ce93": "Väntar", + "1347868f2523140e": "Klar", + "57d76c4614054271": "Stoppad", + "5c7344bd51d0b966": "Överhoppad", + "b2074e9bd23049a6": "Avbruten", + "5bb7401807ee2fb5": "Frågar: {question} och {more} till", + "9e4286183d5f9e34": "Frågar: {question}", + "474c18d001bd6717": "Ett steg misslyckades", + "d3890f4eb1508781": "Kör sina egna steg", + "3e7ced10c9482af0": "{step} arbetar", + "237e1bcb1cf1bdec": "Sover vid {step}", + "3f7b17ac5a20c8d2": "Kör {run}", + "0306f5f324b8aaa5": "{count} körningar pågår", + "e8fd779b84a202a2": "Väntar", + "b6d55657e1a027b8": "Väntar på {step}", + "e942562a42aede34": "Klar", + "26b2b9727fe11289": "Avslutad i förtid", "1bb995dcec481554": "Godkänn den här enheten på {host}. Den visar koden {verificationCode}.", "8696a33219944832": "Kunde inte skapa auktoriseringsbeviset för websocket.", "5678f133a8631f7d": "Din molninloggning har ändrats. Logga in igen för att auktorisera miljön.", @@ -1744,6 +1769,8 @@ "2e995206e087c3fc": "Försök svara när anslutningen eller den väntande inmatningen är löst.", "604ec3067171a0d7": "Konversation", "d6182a057ea12624": "Överordnad tråd", + "f2d8537c33cc55a5": "Steg i arbetsflödeskörningen", + "ba8337dca3232880": "Öppna körning", "30fa4a764d11ae42": "Kunde inte ladda ned {name}", "4952f87dc98191a7": "Bilagan är inte tillgänglig.", "2fd6d178493fb407": "Det gick inte att avbryta den aktuella omgången.", @@ -1829,6 +1856,7 @@ "04fd71efaa2c3b92": "Öppna pull requests", "57e875b79b98ab82": "Öppna ärenden", "f1db0a234c777a1d": "Använd T3 Code i en annan app (MCP)", + "6050f22f63e2bcb5": "Öppna arbetsflöden", "a0cc19e60dd99851": "Öppna användning", "46694969044eee98": "Fokusera nästa område i arbetsytan", "0a1011328ba42eef": "Fokusera föregående område i arbetsytan", @@ -8875,6 +8903,8 @@ "9ae293971d93c819": "Dela en tråd med en gäst som följer den live i en webbläsare och skickar meddelanden som du godkänner. Logga in på T3 Connect för att använda gästlänkar.", "0aa5406ac4d7f7c7": "Gästlänkar", "f0e853acd2006d53": "Länkade miljöer", + "ef10c2dff987f3ea": "Kör arbetsflöden i flera steg från filer i mappen workflows i serverns T3-hemkatalog. Öppna dem från kommandopaletten. När det är av körs inget i mappen; körningar väntar tills det slås på igen.", + "2dadb2359422121c": "Arbetsflöden", "13e86eb5d8287a71": "Visa ett förutsagt nästa meddelande i det tomma inmatningsfältet efter en omgång med Claude eller Codex. Tab använder det. Varje förslag är en extra cachad begäran i ditt abonnemang. Kräver Codex 0.165+. Claude-trådar uppdateras vid omstart.", "d4b2a2ec812aafb0": "Föreslå nästa prompt", "298c7150a7621c80": "Simlock-enhetsvärdar", @@ -11822,6 +11852,7 @@ "d443390c4d2dcfd4": "tillgänglighet a11y skärmläsare nvda jaws voiceover orca skärmläsaren fönstertitel fliktitel alt tab aktivitetsfält trådstatus ordning arbetar godkännande", "6826fa9579c22035": "beta dela gäst bjud in länk kollega titta t3 connect tunnel", "f10c06cba0cdf7fe": "beta länka en annan dator vps peer agenter arbetar där delegera", + "bc0b409d89ce086e": "beta arbetsflöde workflow beständiga körningar automatisering steg schema webhook mapp", "4a21cf825a2045b0": "beta tabb autokomplettering förutsäg nästa meddelande claude codex spöktext", "fea2dc36585c4a20": "Simlock-enhetsvärdar (alfa)", "9d834d178130180e": "beta alpha simlock callstack simulator emulator ios android pool lån gateway", @@ -12378,6 +12409,262 @@ "2cddd6095abc734a": "7 dagar", "53493056306708cf": "30 dagar", "c719359d18d37ad3": "90 dagar", + "0bd950151ddc6407": "Lämna utan att spara? Dina ändringar i filen går förlorade.", + "c0ba3f6756b09f30": "Osparade ändringar", + "6914e22d357f0ad6": "Sparad och körs", + "aff389354a031d6f": "Filen på disken går inte att läsa in. Den senaste versionen som gick att läsa in körs vidare.", + "858effde748ab563": "Sparad, men den körs inte än.", + "ddb37138df660942": "Inte sparad. Inget ändrades på servern.", + "6ef4db489e40e39e": "Kunde inte spara", + "c89624a2e9af1793": "{name} är inte ansluten", + "b5a352a43adb4c17": "Dess arbetsflöden visas igen när den ansluter igen. Välj en annan miljö för att se dess körningar.", + "3dcedb736d20aae5": "Kunde inte läsa arbetsflödesfilerna", + "b09f4df8d76ae8ea": "Ta bort {file}? Arbetsflödena som den definierar kan inte längre startas.", + "b4535f5a03689d27": "{name} är inte ansluten. Det du skriver här finns kvar och kan sparas när den är tillbaka.", + "b54c78d85fd942ea": "Borttagen, men det som körs har inte hunnit ikapp än.", + "407c228d7da0b7df": "Inte borttagen. Inget ändrades på servern.", + "1a6aa10f3cc14fff": "De här filerna passar inte ihop. Det som kördes förut körs vidare.", + "259312516a1dbe6f": "Filnamn", + "2f48ab2aa0586853": "Definierar inga arbetsflöden", + "ba5adfa37b55b8c5": [ + "Rad ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ":" + ], + "d94eb9ab3201b641": "Ta bort", + "84c900d1ae72adc6": "Spara", + "5912d817be03247a": "Filen ändrades på disken medan du redigerade. Om du sparar ersätts den ändringen.", + "0b1e6f5608826387": "Läs in filen och släng mina ändringar", + "f47b4c06aeb77c1c": "Läser in arbetsflödesfilerna…", + "4353bfd401d58f87": [ + "Varje fil i", + " ", + { + "t": "code", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " ", + "definierar arbetsflöden. En ändring i någon av dem plockas upp utan omstart." + ], + "0c165251a06f10f1": "Ny fil", + "8e97cf734b4463e7": "Skapa", + "2ec0d5108fd6cebe": "Inga arbetsflöden än. Skapa den första filen här, eller be en agent skriva en i den mappen.", + "5601350626e8cfe9": "Går inte att läsa in", + "21d778a1b9a0c234": "Öppet bredvid körningen", + "62dc4d3a19ff7ca0": "Stäng flik", + "1e25265f2758fce3": "Öppna som en hel tråd", + "672a3dae06b39402": "Öppna på en egen sida", + "7755500a4cde5066": "Stäng panelen", + "b8dcbc93a2ca1861": "Körningen listar det inte längre.", + "115c69de3202f664": "Öppna", + "644eafa9048b62df": "{count, plural, =1 {1:a försöket} =2 {2:a försöket} =3 {3:e försöket} other {försök {count}}}", + "e39f89c909df4db0": "Kunde inte återuppta körningen", + "865f034346b82f47": "Avbryta {title}? Dess agenter stoppas och körningen kan inte återupptas.", + "6bc75632fd9c9136": "Kunde inte avbryta körningen", + "64e50329dcfdd5b0": "Klar", + "350162e7cc1ebea4": "Stoppad", + "0875cf506f4c6810": "Överhoppad", + "3cc43f1dbf3f8e0c": "Avbruten", + "ded70e75de6404ba": "Tillbaka till listan över körningar", + "2f4ed7dbd22be30d": "Avbryt körningen", + "614e5ad58a795fb5": "Stop", + "04b050b0329f0ac8": "tog {duration}", + "aff78e1774818ff4": "{duration} hittills", + "38eddd466439afc9": "Vad körningen rörde", + "156ec271d49ddd70": "Vad som hände", + "34f59bbbead0b97f": "{names} och {count} till", + "ac1556f6ce89a5ea": "{count} parallellt", + "e197c4963bacc746": "{count} körs", + "f5319ed9e18c0df1": "Frågar dig", + "882a25e9084ae1b2": "Pausad", + "9a03d8a9afc60387": "Steg hittills", + "2f2ae791afe01674": "väntar på ditt godkännande", + "24f8060c4ccdf928": "startar", + "30a5be40eb956663": "arbetar", + "dd7a1e58c2553933": "vaknar om {duration}", + "95cc952724dd7310": "vaknar strax", + "3cc34921c0128593": "körs", + "e777db2880f53a46": "ingen svarade", + "dc90739d391a5e67": "Du svarade {choice}", + "389f2563b5b763fd": "Snabba steg", + "a41c8d758121ad81": "sov", + "9db248b770096984": "väntade", + "c76124517af28686": "har körts i {duration}", + "89102905bf09b0e8": "Följ live", + "bdf338cdff4118f0": "Transkript", + "811e7e992f9ff820": "kan inte fortsätta förrän dess arbetsflödesversion registreras igen", + "4d4cdf035e98dd57": "väntar på att du återupptar den", + "eb5b21dd224a5941": "försöker igen själv om {duration}", + "6ab3dfa749fde477": "försöker strax igen själv", + "44b6463aa70aa14c": "Varför den pausades", + "cf25e7169ab0eb7a": "Pausad vid {step}", + "56c48c1f220f2754": "Kunde inte svara på frågan", + "a3c43735e1a81498": "Skäl för {title}", + "bfad234f016cfa3f": "Varför, i en mening. Det följer med vilket svar du än väljer.", + "004c41aff9c97873": "Körningar", + "4dc0c244a2419f6c": [ + "Del av ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8c303e8335acb135": [ + "startade", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8bffb377e2a6a7de": "dess version är inte längre registrerad", + "f92d9132f7b85d1a": "Läser in steg…", + "6ebc59f64c761a49": "Inget än.", + "a759dccd157d7dae": [ + "Du svarade", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + "." + ], + "593b425188346781": [ + "Du svarade", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + ": ", + { + "i": 3, + "k": "_gt_value_3", + "v": "v" + } + ], + "c98009be9a273b31": "Öppna körning", + "c8eb9be36d4d51ad": [ + "Tråd på ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "3d9761e81798fcd8": "Återuppta", + "8cebd63fc4c967d5": "Bara det misslyckade steget körs igen; det som blev klart före det behålls.", + "bc1e0a2a0f1e9552": "Behöver dig", + "a812f51e970740f1": [ + "frågade", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " ", + "· körningen väntar på dig" + ], + "02dfe6c63fd0b8a1": "Lägg till ett skäl", + "19abd94828a3bdbc": "Fråga agenten först", + "a18721fa8f328361": "Behöver dig", + "bbf24e7920c1e86b": "Körs", + "8d6e18d2ad832db6": "Alla", + "f25af5332ffc3734": "Inget väntar på dig.", + "c3f0119b8d6231f8": "Inget körs.", + "33028dfc1229eaa6": "Inga körningar än.", + "5459bf696a187c26": "Kunde inte läsa in arbetsflödeskörningarna", + "d57c35d43b0f163a": "Den här körningen finns inte här", + "b9aae2f7cdb1a379": "Inga arbetsflödeskörningar än", + "8f15f66e545af7c0": "Vilka körningar", + "b6409289e0c9a4dd": "Arbetsflöde", + "035cb02ca1ae4952": "Alla arbetsflöden ({count})", + "46d614fa7b4bf1e5": "Arbetsflödeskörningar", + "1c635faa2fb45b8b": "Har inte körts än.", + "156ff7b625287a1e": "Dölj överhoppade", + "69b985b97ab45e6b": "Visa överhoppade ({count})", + "2400254d362de84d": "Läser in arbetsflödeskörningar…", + "145e1f7503ba3b2c": [ + "Den här miljön har ingen körning med den länken.", + " ", + { + "t": "button", + "i": 1, + "c": "Tillbaka till körningarna" + } + ], + "783e616cb0476c17": [ + "Ett arbetsflöde knyter ihop agenter, kod, scheman och frågor till dig i en enda körning som överlever omstarter. Skriv ett under", + " ", + { + "t": "button", + "i": 1, + "c": "Definitioner" + }, + ", eller be en agent göra det.", + " ", + { + "t": "a", + "i": 2, + "c": "Läs guiden" + } + ], + "cae5c3205c01d062": [ + { + "t": "span", + "i": 1, + "c": "En arbetsflödesfil har ett problem." + }, + " ", + "Den senaste versionen som gick att läsa in körs vidare." + ], + "ed8ce6ebc73dc12d": "Öppna filen", + "5d8d278ff828102d": "Alla arbetsflöden", + "39459da07479f482": "Agent", + "7741243632056b81": "{step} · transkript", + "c512071143a5ba32": "Den här tråden finns inte längre.", + "ed169d23683fb6ac": "Läser in tråden…", + "290e0ab40b87dc17": "Brödsmulor för arbetsflöden", + "683dd9831e54edc0": "Miljö", + "34ad53646f06ed80": "Arbetsflöden är avstängda", + "8f6589c9e0ac5d4e": "Ingen miljö ansluten", + "744127f8dfad7d22": "Anslut en miljö för att se dess arbetsflödeskörningar.", + "036182ec7e2ee4d4": "Bredvid körningen", + "2d6107cb78382d08": "Arbetsflöden", + "16f7df687349b399": "Definitioner", + "f0a212aadfe1257b": "Läser in redigeraren…", + "20f194e003885e95": [ + "Slå på dem för den här servern i", + " ", + { + "t": "Link", + "i": 1, + "c": "Inställningar → Labs" + }, + "." + ], "8367779e149f723b": "Begäran till den primära miljön misslyckades under {operation} (HTTP {status}).", "c5cd027743a2b5a6": "Ogiltig parkopplingstoken. Kontrollera token och försök igen.", "0e4b49c8203aae81": "Tidsgränsen överskreds i väntan på en autentiserad session efter uppstart.", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 19eff455a318c..deaa65edcc1ec 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -396,6 +396,31 @@ "476ca970255eaea4": "将此环境关联到 T3 Connect,获取公网 URL。", "6b80f5b38a8f9950": "只有本机可以访问此地址。关联 T3 Connect 可获取公网 URL。", "c5a7b1d3891dd0b8": "只要能连接此环境的地址(例如通过 Tailscale 或你自己的代理)即可使用。关联 T3 Connect 可获取公网 URL。", + "3669395daf36fd33": "已不再注册到此服务器", + "fe513cf316e796e3": "作为其他工作流的一部分运行", + "ccf00b97925efab3": "手动启动", + "421e585eb092b07b": "由 {triggers} 触发启动", + "7bd7c58592671384": "等你处理", + "834ca879c14c167b": "运行中", + "582d6df7dfab86fb": "已暂停", + "ea6583ce92507ee3": "休眠中", + "7ea8cb8af281ce93": "等待中", + "1347868f2523140e": "完成", + "57d76c4614054271": "已停止", + "5c7344bd51d0b966": "已跳过", + "b2074e9bd23049a6": "已取消", + "5bb7401807ee2fb5": "提问:{question},另有 {more} 个", + "9e4286183d5f9e34": "提问:{question}", + "474c18d001bd6717": "有步骤失败", + "d3890f4eb1508781": "正在运行自身的步骤", + "3e7ced10c9482af0": "{step} 正在运行", + "237e1bcb1cf1bdec": "在 {step} 休眠中", + "3f7b17ac5a20c8d2": "运行 {run}", + "0306f5f324b8aaa5": "{count} 个运行进行中", + "e8fd779b84a202a2": "等待中", + "b6d55657e1a027b8": "正在等待 {step}", + "e942562a42aede34": "已完成", + "26b2b9727fe11289": "提前结束", "1bb995dcec481554": "请在 {host} 上批准此设备。它会显示代码 {verificationCode}。", "8696a33219944832": "无法创建 WebSocket 授权证明。", "5678f133a8631f7d": "你的云端登录已变化。请重新登录以授权环境。", @@ -1744,6 +1769,8 @@ "2e995206e087c3fc": "请在连接恢复或待处理的输入完成后重试回复。", "604ec3067171a0d7": "对话", "d6182a057ea12624": "父会话", + "f2d8537c33cc55a5": "工作流运行的步骤", + "ba8337dca3232880": "打开运行", "30fa4a764d11ae42": "无法下载 {name}", "4952f87dc98191a7": "附件不可用。", "2fd6d178493fb407": "无法中断当前这一轮。", @@ -1829,6 +1856,7 @@ "04fd71efaa2c3b92": "打开 PR", "57e875b79b98ab82": "打开 issue", "f1db0a234c777a1d": "在其他应用中使用 T3 Code(MCP)", + "6050f22f63e2bcb5": "打开工作流", "a0cc19e60dd99851": "打开用量", "46694969044eee98": "聚焦下一个工作区区域", "0a1011328ba42eef": "聚焦上一个工作区区域", @@ -8885,6 +8913,8 @@ "9ae293971d93c819": "与访客共享会话,访客可在浏览器中实时查看,并发送需要你批准的消息。登录 T3 Connect 后即可使用访客链接。", "0aa5406ac4d7f7c7": "访客链接", "f0e853acd2006d53": "关联环境", + "ef10c2dff987f3ea": "从此服务器 T3 主目录下 workflows 文件夹中的文件运行多步骤工作流。可从命令面板打开。关闭期间,该文件夹中的内容都不会运行;运行会等到重新开启后继续。", + "2dadb2359422121c": "工作流", "13e86eb5d8287a71": "Claude 或 Codex 完成一轮回复后,在空输入框中预测下一条消息。按 Tab 使用它。每次预测都会在你的套餐上产生一次额外的缓存请求。需要 Codex 0.165+。Claude 会话在重启后更新。", "d4b2a2ec812aafb0": "建议下一条提示词", "298c7150a7621c80": "Simlock 设备主机", @@ -11839,6 +11869,7 @@ "d443390c4d2dcfd4": "无障碍 a11y 屏幕阅读器 nvda jaws voiceover orca 讲述人 窗口标题 标签页标题 alt tab 任务栏 会话状态 顺序 运行中 批准", "6826fa9579c22035": "测试版 共享 访客 邀请 链接 队友 观看 t3 connect 隧道", "f10c06cba0cdf7fe": "测试版 关联 另一台机器 vps 对等 智能体 在那里工作 委派", + "bc0b409d89ce086e": "测试版 工作流 workflow 持久 运行 自动化 步骤 计划 webhook 文件夹", "4a21cf825a2045b0": "测试版 tab 自动补全 预测 下一条消息 claude codex 幽灵文本", "fea2dc36585c4a20": "Simlock 设备主机(早期测试)", "9d834d178130180e": "测试版 alpha simlock callstack 模拟器 ios android 池 租用 网关", @@ -12396,6 +12427,255 @@ "2cddd6095abc734a": "7 天", "53493056306708cf": "30 天", "c719359d18d37ad3": "90 天", + "0bd950151ddc6407": "不保存就离开?对此文件的更改将丢失。", + "c0ba3f6756b09f30": "未保存的更改", + "6914e22d357f0ad6": "已保存并生效", + "aff389354a031d6f": "磁盘上的文件无法加载。上一个可加载的版本会继续运行。", + "858effde748ab563": "已保存,但尚未运行。", + "ddb37138df660942": "未保存。服务器上没有任何更改。", + "6ef4db489e40e39e": "无法保存", + "c89624a2e9af1793": "{name} 未连接", + "b5a352a43adb4c17": "重新连接后,它的工作流会再次显示。选择其他环境可查看其运行。", + "3dcedb736d20aae5": "无法读取工作流文件", + "b09f4df8d76ae8ea": "要删除 {file} 吗?它定义的工作流将无法再启动。", + "b4535f5a03689d27": "{name} 未连接。你在这里写的内容会保留,重新连接后即可保存。", + "b54c78d85fd942ea": "已删除,但正在运行的内容尚未更新。", + "407c228d7da0b7df": "未删除。服务器上没有任何更改。", + "1a6aa10f3cc14fff": "这些文件彼此不匹配。之前的版本会继续运行。", + "259312516a1dbe6f": "文件名", + "2f48ab2aa0586853": "未定义任何工作流", + "ba5adfa37b55b8c5": [ + "第 ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " 行:" + ], + "d94eb9ab3201b641": "删除", + "84c900d1ae72adc6": "保存", + "5912d817be03247a": "编辑期间磁盘上的文件发生了变化。保存会覆盖该变化。", + "0b1e6f5608826387": "加载该文件并放弃我的更改", + "f47b4c06aeb77c1c": "正在加载工作流文件…", + "4353bfd401d58f87": [ + { + "t": "code", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " ", + "中的每个文件都定义工作流。修改后无需重启即可生效。" + ], + "0c165251a06f10f1": "新建文件", + "8e97cf734b4463e7": "创建", + "2ec0d5108fd6cebe": "还没有工作流。在这里创建第一个文件,或让智能体在该文件夹中编写一个。", + "5601350626e8cfe9": "无法加载", + "21d778a1b9a0c234": "在运行旁打开的内容", + "62dc4d3a19ff7ca0": "关闭标签页", + "1e25265f2758fce3": "作为完整会话打开", + "672a3dae06b39402": "在单独的页面打开", + "7755500a4cde5066": "关闭面板", + "b8dcbc93a2ca1861": "此运行不再列出它。", + "115c69de3202f664": "打开", + "644eafa9048b62df": "{count, plural, =1 {第 1 次尝试} =2 {第 2 次尝试} =3 {第 3 次尝试} other {第 {count} 次尝试}}", + "e39f89c909df4db0": "无法继续此运行", + "865f034346b82f47": "要取消 {title} 吗?其智能体将停止,且此运行无法再继续。", + "6bc75632fd9c9136": "无法取消此运行", + "64e50329dcfdd5b0": "已完成", + "350162e7cc1ebea4": "已停止", + "0875cf506f4c6810": "已跳过", + "3cc43f1dbf3f8e0c": "已取消", + "ded70e75de6404ba": "返回运行列表", + "2f4ed7dbd22be30d": "取消运行", + "614e5ad58a795fb5": "Stop", + "04b050b0329f0ac8": "用时 {duration}", + "aff78e1774818ff4": "已用时 {duration}", + "38eddd466439afc9": "此运行涉及的内容", + "156ec271d49ddd70": "经过", + "34f59bbbead0b97f": "{names} 等另外 {count} 个", + "ac1556f6ce89a5ea": "{count} 个并行", + "e197c4963bacc746": "{count} 个运行中", + "f5319ed9e18c0df1": "向你提问", + "882a25e9084ae1b2": "已暂停", + "9a03d8a9afc60387": "目前的步骤", + "2f2ae791afe01674": "等待你的批准", + "24f8060c4ccdf928": "正在启动", + "30a5be40eb956663": "工作中", + "dd7a1e58c2553933": "{duration} 后唤醒", + "95cc952724dd7310": "即将唤醒", + "3cc34921c0128593": "运行中", + "e777db2880f53a46": "无人回答", + "dc90739d391a5e67": "你的回答:{choice}", + "389f2563b5b763fd": "快速步骤", + "a41c8d758121ad81": "已休眠", + "9db248b770096984": "已等待", + "c76124517af28686": "已运行 {duration}", + "89102905bf09b0e8": "实时查看", + "bdf338cdff4118f0": "对话记录", + "811e7e992f9ff820": "需重新注册其工作流版本后才能继续", + "4d4cdf035e98dd57": "等你手动继续", + "eb5b21dd224a5941": "{duration} 后自动重试", + "6ab3dfa749fde477": "即将自动重试", + "44b6463aa70aa14c": "暂停原因", + "cf25e7169ab0eb7a": "暂停于 {step}", + "56c48c1f220f2754": "无法回答此问题", + "a3c43735e1a81498": "{title} 的理由", + "bfad234f016cfa3f": "用一句话说明理由。无论你选哪个回答,它都会一并附上。", + "004c41aff9c97873": "运行", + "4dc0c244a2419f6c": [ + "属于 ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8c303e8335acb135": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "开始" + ], + "8bffb377e2a6a7de": "其版本已不再注册", + "f92d9132f7b85d1a": "正在加载步骤…", + "6ebc59f64c761a49": "暂无内容。", + "a759dccd157d7dae": [ + "你的回答:", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + } + ], + "593b425188346781": [ + "你的回答:", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + ":", + { + "i": 3, + "k": "_gt_value_3", + "v": "v" + } + ], + "c98009be9a273b31": "打开运行", + "c8eb9be36d4d51ad": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " 上的会话" + ], + "3d9761e81798fcd8": "继续", + "8cebd63fc4c967d5": "只会重新运行失败的步骤;此前已完成的内容会保留。", + "bc1e0a2a0f1e9552": "等你处理", + "a812f51e970740f1": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "提问", + " ", + "· 运行正在等你回答" + ], + "02dfe6c63fd0b8a1": "添加理由", + "19abd94828a3bdbc": "先问问智能体", + "a18721fa8f328361": "等你处理", + "bbf24e7920c1e86b": "运行中", + "8d6e18d2ad832db6": "全部", + "f25af5332ffc3734": "没有等你处理的内容。", + "c3f0119b8d6231f8": "没有正在运行的内容。", + "33028dfc1229eaa6": "还没有运行。", + "5459bf696a187c26": "无法加载工作流运行", + "d57c35d43b0f163a": "此运行不在这里", + "b9aae2f7cdb1a379": "还没有工作流运行", + "8f15f66e545af7c0": "显示哪些运行", + "b6409289e0c9a4dd": "工作流", + "035cb02ca1ae4952": "全部 {count} 个工作流", + "46d614fa7b4bf1e5": "工作流运行", + "1c635faa2fb45b8b": "尚未运行过。", + "156ff7b625287a1e": "隐藏已跳过", + "69b985b97ab45e6b": "显示 {count} 个已跳过", + "2400254d362de84d": "正在加载工作流运行…", + "145e1f7503ba3b2c": [ + "此环境中没有该链接对应的运行。", + " ", + { + "t": "button", + "i": 1, + "c": "返回运行列表" + } + ], + "783e616cb0476c17": [ + "工作流将智能体、代码、定时计划和向你提出的问题串联成一次重启后仍会继续的运行。可在", + " ", + { + "t": "button", + "i": 1, + "c": "定义" + }, + " ", + "中编写,或让智能体代写。", + " ", + { + "t": "a", + "i": 2, + "c": "阅读指南" + } + ], + "cae5c3205c01d062": [ + { + "t": "span", + "i": 1, + "c": "有工作流文件存在问题。" + }, + "上一个可加载的版本会继续运行。" + ], + "ed8ce6ebc73dc12d": "打开文件", + "5d8d278ff828102d": "全部工作流", + "39459da07479f482": "智能体", + "7741243632056b81": "{step} · 记录", + "c512071143a5ba32": "此会话已不存在。", + "ed169d23683fb6ac": "正在加载会话…", + "290e0ab40b87dc17": "工作流面包屑导航", + "683dd9831e54edc0": "环境", + "34ad53646f06ed80": "工作流已关闭", + "8f6589c9e0ac5d4e": "未连接任何环境", + "744127f8dfad7d22": "连接一个环境以查看其工作流运行。", + "036182ec7e2ee4d4": "运行旁", + "2d6107cb78382d08": "工作流", + "16f7df687349b399": "定义", + "f0a212aadfe1257b": "正在加载编辑器…", + "20f194e003885e95": [ + "在此服务器的", + " ", + { + "t": "Link", + "i": 1, + "c": "设置 → Labs" + }, + " 中开启。" + ], "8367779e149f723b": "主环境请求在 {operation} 期间失败(HTTP {status})。", "c5cd027743a2b5a6": "配对 token 无效。请检查后重试。", "0e4b49c8203aae81": "引导完成后等待登录状态超时。", diff --git a/apps/web/src/index.css b/apps/web/src/index.css index 2b19b90cc28e3..15380512f4060 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -231,6 +231,10 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil --animate-stash-pulse-row: stash-pulse-row 1400ms; --animate-stash-pulse-row-alt: stash-pulse-row-alt 1400ms; --animate-stash-pulse-count: stash-pulse-count 1400ms step-start; + /* One-off arrivals in a workflow run's timeline; nothing here loops. */ + --animate-step-in: step-in 180ms ease-out; + --animate-step-ping: step-ping 520ms ease-out; + --animate-check-draw: check-draw 200ms ease-out; --color-warning-foreground: var(--warning-foreground); --color-warning: var(--warning); --color-warning-surface: var(--warning-surface); @@ -345,6 +349,27 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil opacity: 1; } } + @keyframes step-in { + from { + opacity: 0; + translate: 0 4px; + } + } + @keyframes step-ping { + from { + opacity: 0.55; + scale: 0.7; + } + to { + opacity: 0; + scale: 1.45; + } + } + @keyframes check-draw { + from { + stroke-dashoffset: 12; + } + } @keyframes status-ping { /* Burst first (immediate feedback for click ripples), then hold invisible for the rest of the cycle. Mirrors animate-ping's diff --git a/apps/web/src/routeTree.gen.ts b/apps/web/src/routeTree.gen.ts index 2d2e74ab58ef2..b1cc1b86c29ba 100644 --- a/apps/web/src/routeTree.gen.ts +++ b/apps/web/src/routeTree.gen.ts @@ -18,6 +18,7 @@ import { Route as ApproveAgentRouteImport } from './routes/approve-agent' import { Route as ChatRouteImport } from './routes/_chat' import { Route as ChatIndexRouteImport } from './routes/_chat.index' import { Route as ProjectsProjectKeyRouteImport } from './routes/projects.$projectKey' +import { Route as ChatWorkflowsRouteImport } from './routes/_chat.workflows' import { Route as ChatUsageRouteImport } from './routes/_chat.usage' import { Route as ChatSettingsRouteImport } from './routes/_chat.settings' import { Route as ChatPullRequestsRouteImport } from './routes/_chat.pull-requests' @@ -99,6 +100,11 @@ const ProjectsProjectKeyRoute = ProjectsProjectKeyRouteImport.update({ path: '/projects/$projectKey', getParentRoute: () => rootRouteImport, } as any) +const ChatWorkflowsRoute = ChatWorkflowsRouteImport.update({ + id: '/workflows', + path: '/workflows', + getParentRoute: () => ChatRoute, +} as any) const ChatUsageRoute = ChatUsageRouteImport.update({ id: '/usage', path: '/usage', @@ -302,6 +308,7 @@ export interface FileRoutesByFullPath { '/pull-requests': typeof ChatPullRequestsRoute '/settings': typeof ChatSettingsRouteWithChildren '/usage': typeof ChatUsageRoute + '/workflows': typeof ChatWorkflowsRoute '/projects/$projectKey': typeof ProjectsProjectKeyRoute '/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute '/draft/$draftId': typeof ChatDraftDraftIdRoute @@ -347,6 +354,7 @@ export interface FileRoutesByTo { '/pull-requests': typeof ChatPullRequestsRoute '/settings': typeof ChatSettingsRouteWithChildren '/usage': typeof ChatUsageRoute + '/workflows': typeof ChatWorkflowsRoute '/projects/$projectKey': typeof ProjectsProjectKeyRoute '/': typeof ChatIndexRoute '/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute @@ -395,6 +403,7 @@ export interface FileRoutesById { '/_chat/pull-requests': typeof ChatPullRequestsRoute '/_chat/settings': typeof ChatSettingsRouteWithChildren '/_chat/usage': typeof ChatUsageRoute + '/_chat/workflows': typeof ChatWorkflowsRoute '/projects/$projectKey': typeof ProjectsProjectKeyRoute '/_chat/': typeof ChatIndexRoute '/_chat/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute @@ -444,6 +453,7 @@ export interface FileRouteTypes { | '/pull-requests' | '/settings' | '/usage' + | '/workflows' | '/projects/$projectKey' | '/$environmentId/$threadId' | '/draft/$draftId' @@ -489,6 +499,7 @@ export interface FileRouteTypes { | '/pull-requests' | '/settings' | '/usage' + | '/workflows' | '/projects/$projectKey' | '/' | '/$environmentId/$threadId' @@ -536,6 +547,7 @@ export interface FileRouteTypes { | '/_chat/pull-requests' | '/_chat/settings' | '/_chat/usage' + | '/_chat/workflows' | '/projects/$projectKey' | '/_chat/' | '/_chat/$environmentId/$threadId' @@ -648,6 +660,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ProjectsProjectKeyRouteImport parentRoute: typeof rootRouteImport } + '/_chat/workflows': { + id: '/_chat/workflows' + path: '/workflows' + fullPath: '/workflows' + preLoaderRoute: typeof ChatWorkflowsRouteImport + parentRoute: typeof ChatRoute + } '/_chat/usage': { id: '/_chat/usage' path: '/usage' @@ -973,6 +992,7 @@ interface ChatRouteChildren { ChatPullRequestsRoute: typeof ChatPullRequestsRoute ChatSettingsRoute: typeof ChatSettingsRouteWithChildren ChatUsageRoute: typeof ChatUsageRoute + ChatWorkflowsRoute: typeof ChatWorkflowsRoute ChatIndexRoute: typeof ChatIndexRoute ChatEnvironmentIdThreadIdRoute: typeof ChatEnvironmentIdThreadIdRoute ChatDraftDraftIdRoute: typeof ChatDraftDraftIdRoute @@ -985,6 +1005,7 @@ const ChatRouteChildren: ChatRouteChildren = { ChatPullRequestsRoute: ChatPullRequestsRoute, ChatSettingsRoute: ChatSettingsRouteWithChildren, ChatUsageRoute: ChatUsageRoute, + ChatWorkflowsRoute: ChatWorkflowsRoute, ChatIndexRoute: ChatIndexRoute, ChatEnvironmentIdThreadIdRoute: ChatEnvironmentIdThreadIdRoute, ChatDraftDraftIdRoute: ChatDraftDraftIdRoute, diff --git a/apps/web/src/routes/_chat.workflows.tsx b/apps/web/src/routes/_chat.workflows.tsx new file mode 100644 index 0000000000000..c755da76d5b38 --- /dev/null +++ b/apps/web/src/routes/_chat.workflows.tsx @@ -0,0 +1,15 @@ +import { createFileRoute } from "@tanstack/react-router"; + +import { readWorkflowPane } from "../components/workflows/workflowPane.logic"; +import { WorkflowsPage, type WorkflowsSearch } from "../components/workflows/WorkflowsPage"; + +export const Route = createFileRoute("/_chat/workflows")({ + validateSearch: (raw: Record): WorkflowsSearch => ({ + ...(typeof raw.env === "string" && raw.env ? { env: raw.env.slice(0, 200) } : {}), + ...(typeof raw.run === "string" && raw.run ? { run: raw.run.slice(0, 200) } : {}), + ...readWorkflowPane(raw.pane, raw.tab), + ...(raw.definitions === true || raw.definitions === "true" ? { definitions: true } : {}), + ...(typeof raw.file === "string" && raw.file ? { file: raw.file.slice(0, 200) } : {}), + }), + component: WorkflowsPage, +}); diff --git a/docs/user/workflows.md b/docs/user/workflows.md new file mode 100644 index 0000000000000..3327d28062bf9 --- /dev/null +++ b/docs/user/workflows.md @@ -0,0 +1,92 @@ +# Workflows + +A workflow is a TypeScript script that chains agents, plain code, schedules, webhooks, issue and pull request events, and questions to you into one durable run that survives server restarts. Each step's result is saved when it succeeds, so restarts pick up where the run left off and failures do not lose earlier work. Workflows are an early feature: start runs from the `t3` CLI or a trigger, and follow them in the app. + +For one prompt on a timer or webhook, use a scheduled task. Use a workflow when work has stages — such as triage, a fix, your approval, and a release. + +## Turn on workflows + +Workflows are a Labs feature, off by default. Turn on **Settings → Labs → Workflows** for the server that runs them. On a server without a desktop, set `"workflowsEnabled": true` in `userdata/settings.json` in its T3 home (`~/.t3` by default). While off, nothing in the workflows folder runs and `t3 workflow` says how to turn it on; runs are kept and continue once it is on again. + +## Create a workflow + +Workflow files live in `~/.t3/workflows/` (or wherever `T3CODE_WORKFLOWS` points — a folder or a single file). The server watches the folder and reloads changes without a restart. + +- **Ask an agent (recommended):** copy the [`t3-workflows` skill](https://github.com/pingdotgg/t3code/blob/main/skills/t3-workflows/SKILL.md) into your agent's skills folder (such as `~/.claude/skills/` or `~/.agents/skills/`) and describe what you want. +- **Edit directly:** edit files in `~/.t3/workflows/`, or use **Definitions** on the Workflows page (saving and deleting in the app require terminal access). Before anything has run, open the page with **Open workflows** in the command palette. + +A small workflow, saved as `~/.t3/workflows/release.ts`: + +```ts +const { workflow, step, ask, stop, title } = T3; + +export default workflow( + "release", + { version: 1, payload: Schema.Struct({ name: Schema.String }) }, + Effect.fn(function* (payload) { + yield* title(`Release ${payload.name}`); + const notes = yield* step("notes", { returns: Schema.String }, Effect.succeed("3 fixes")); + const answer = yield* ask("ship", { + title: `Ship ${payload.name}? ${notes}`, + choices: ["Ship", "Hold"], + }); + if (Option.isNone(answer) || answer.value.choice !== "Ship") return yield* stop("held back"); + return { shipped: payload.name }; + }), +); +``` + +Start it with `t3 workflow start release --input '{"name":"v1.4"}' --key v1.4`, then answer its question in the app. `T3`, `Effect`, `Schema` and `Option` are provided; a workflow file imports nothing from T3 or Effect. Name files with letters, digits, `-`, `_` and `.`; other names are skipped with a warning. + +Saving checks that the file loads, does not duplicate a workflow name and version, and does not remove a version with unfinished runs. A file that fails these checks keeps its last working version while the Workflows page (and the server log) shows why; other files are not affected. A change held back by unfinished runs goes in by itself once those runs end or are cancelled. Mistakes inside a workflow body surface when a run hits them and pauses. To change steps while runs are unfinished, add the new body under a higher `version` and keep the old one until those runs end. + +Dot-files and subfolders are ignored. Keep shared helpers in a subfolder and restart the server after editing an imported file. + +## Start and steer + +```sh +t3 workflow start --input '' --key +t3 workflow list [--status paused] +t3 workflow show +t3 workflow resume +t3 workflow cancel [--reason ''] +t3 workflow questions +t3 workflow signal '{"choice":"yes"}' --run --wait +t3 workflow signal '' --workflow --channel +t3 workflow hooks +t3 workflow store list +t3 workflow store set '' +``` + +Every start needs a `--key`: starting twice with the same key returns the same run — even after a version bump — so retries do not duplicate work. Use `signal` with `--run` and `--wait` to answer a question or wake a run, or with `--workflow` and `--channel` to wake whichever run waits on that channel. A signal for a question that is no longer open is kept for a later wait rather than refused, so check `t3 workflow questions` first. Use `store` to read or change state kept between runs. + +## Triggers + +- **Schedules:** `every` runs on an interval, starting one interval after the workflow loads; `daily` runs at a local time of day (a time missed by more than 10 minutes while the server is down is skipped). +- **Webhooks:** `t3 workflow hooks` prints each hook's path; prepend your server's address. The path contains the hook's secret, so share it only with the sender. A sender's retry that repeats its delivery header (such as GitHub's `X-GitHub-Delivery`) starts no second run, and bodies over 1 MiB are refused. Organization policies blocking webhook tasks block workflow webhooks too. +- **Issues and pull requests:** workflows can start on new issues or pull requests and read, comment on, or update them via **Settings → Source control & issues** — no webhook needed. T3 Code checks roughly once a minute, and only items opened after the workflow was first loaded start runs. + +## Follow runs in the app + +Open the Workflows page with **Open workflows** in the command palette of the web or desktop app; the entry shows once a connected server has workflows on. Filter by **Needs you**, **Running**, or **All** (skipped runs stay hidden unless toggled on), open child runs from their parent, and answer questions, resume paused runs, or cancel active runs (requires permission to operate threads). The issues and pull requests a run touched show as chips under its title and on the steps that touched them; a chip opens the item beside the run, in a tab next to any agent transcripts you opened. + +### Agent threads + +Each `agent` step runs in an ordinary thread, left out of thread lists (including `t3 thread list`). Open it from the run to watch it live, read its transcript, or send follow-up messages; the thread links back to the run. + +An `agent` step can launch a new thread with its own `workspace` (such as a worktree), `runtimeMode`, `interactionMode`, `title`, and typed `returns`, or continue an earlier step's thread. Runs can set their display name with `title(text)`. An `agent` step can also target a project on a [linked environment](remote-access.md#link-another-environment) (requires **Settings → Labs → Linked environments**); the run itself stays on the server that started it. + +### Failures, pause, and cancel + +A plain code step runs once unless it asks for retries. When a step fails, the run pauses there instead of losing earlier work: + +- **Code step failures** retry automatically after 5, 20, and 80 minutes by default, or immediately when you resume; only that step runs again. +- **Agent failures** — when an agent ran and gave up or timed out — pause and wait for you to resume rather than retrying automatically. An agent that could not be started at all, for example because its environment was offline, retries on its own like a failed step. + +Cancelling a run stops its active agent turns and cancels child runs it invoked. A cancelled run cannot be resumed. + +## Limits + +- Runs live on the server that started them and only advance while it is running; use an always-on machine for schedules or webhooks you cannot miss. +- Keep older workflow versions defined until their unfinished runs end or are cancelled. +- Signals sent to a `channel` before a run waits on it are kept for 7 days by default. diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index d20a890bf90da..0ff07506e941d 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -47,6 +47,10 @@ "types": "./src/contractLabels.ts", "default": "./src/contractLabels.ts" }, + "./workflows": { + "types": "./src/workflows.ts", + "default": "./src/workflows.ts" + }, "./locales": { "types": "./src/locales.ts", "default": "./src/locales.ts" diff --git a/packages/client-runtime/src/rpc/client.ts b/packages/client-runtime/src/rpc/client.ts index 0947b1c046085..d86da6082dc29 100644 --- a/packages/client-runtime/src/rpc/client.ts +++ b/packages/client-runtime/src/rpc/client.ts @@ -71,6 +71,8 @@ export type EnvironmentSubscriptionRpcTag = | typeof WS_METHODS.subscribeServerConfig | typeof WS_METHODS.subscribeServerLifecycle | typeof WS_METHODS.scheduledTasksSubscribe + | typeof WS_METHODS.workflowsSubscribe + | typeof WS_METHODS.workflowsCounts | typeof WS_METHODS.serverGetStorageCleanupReport | typeof WS_METHODS.serverGetDatabaseStorage | typeof WS_METHODS.subscribeTerminalMetadata diff --git a/packages/client-runtime/src/state/commandPermissions.test.ts b/packages/client-runtime/src/state/commandPermissions.test.ts index 18dee4bd56b41..a3b1861ca0351 100644 --- a/packages/client-runtime/src/state/commandPermissions.test.ts +++ b/packages/client-runtime/src/state/commandPermissions.test.ts @@ -11,6 +11,7 @@ import { AuthAccessWriteScope, AuthEnvironmentMaintainScope, AuthOrchestrationOperateScope, + AuthTerminalOperateScope, AuthOrchestrationReadScope, AuthPreviewOperateScope, AuthProvidersManageScope, @@ -224,21 +225,43 @@ describe("command permissions", () => { ), ); - it.effect.each([WS_METHODS.scheduledTasksDelete, ORCHESTRATION_V2_WS_METHODS.stopWorkflow])( - "uses the target grant for both availability and execution of %s", - (method) => - Effect.gen(function* () { - const registry = yield* setup; - const permissions = createCommandPermissions(runtime, method); - registry.set(sessions(env), AsyncResult.success(grant(true))); - expect(registry.get(permissions.permissionAtom(env))).toBe(true); - expect(permissions.permissionAtom(env)).toBe(permissions.permissionAtom(env)); - yield* permissions.authorize(registry, env); - registry.set(sessions(other), AsyncResult.success(grant(false))); - expect(registry.get(permissions.permissionAtom(other))).toBe(false); - const denied = yield* permissions.authorize(registry, other).pipe(Effect.flip); - expect(denied._tag).toBe("EnvironmentAuthorizationError"); - }), + it.effect.each([ + WS_METHODS.scheduledTasksDelete, + ORCHESTRATION_V2_WS_METHODS.stopWorkflow, + WS_METHODS.workflowsAnswer, + WS_METHODS.workflowsResume, + WS_METHODS.workflowsCancel, + ])("uses the target grant for both availability and execution of %s", (method) => + Effect.gen(function* () { + const registry = yield* setup; + const permissions = createCommandPermissions(runtime, method); + registry.set(sessions(env), AsyncResult.success(grant(true))); + expect(registry.get(permissions.permissionAtom(env))).toBe(true); + expect(permissions.permissionAtom(env)).toBe(permissions.permissionAtom(env)); + yield* permissions.authorize(registry, env); + registry.set(sessions(other), AsyncResult.success(grant(false))); + expect(registry.get(permissions.permissionAtom(other))).toBe(false); + const denied = yield* permissions.authorize(registry, other).pipe(Effect.flip); + expect(denied._tag).toBe("EnvironmentAuthorizationError"); + }), + ); + it.effect("saving workflow definitions takes more than operating threads", () => + Effect.gen(function* () { + const registry = yield* setup; + const saving = createCommandPermissions(runtime, WS_METHODS.workflowsSaveDefinition); + // The server runs that file, so the grant that answers a question does not cover it. + registry.set(sessions(env), AsyncResult.success(grant(true))); + expect(registry.get(saving.permissionAtom(env))).toBe(false); + registry.set( + sessions(env), + AsyncResult.success({ + ...grant(true), + scopes: [AuthTerminalOperateScope], + permissions: [AuthTerminalOperateScope], + }), + ); + expect(registry.get(saving.permissionAtom(env))).toBe(true); + }), ); it.effect("waits for an initial grant", () => Effect.gen(function* () { diff --git a/packages/client-runtime/src/state/models.ts b/packages/client-runtime/src/state/models.ts index 4401f90e898c3..4b708662839b2 100644 --- a/packages/client-runtime/src/state/models.ts +++ b/packages/client-runtime/src/state/models.ts @@ -162,6 +162,8 @@ export interface EnvironmentThreadShell { readonly linkOrigin: OrchestrationV2ThreadShell["linkOrigin"] | null; /** The thread in a linked environment that delegated this one, if one did. */ readonly delegatedFrom: OrchestrationV2ThreadShell["delegatedFrom"] | null; + /** The workflow run this thread is an agent step of, if it is one. */ + readonly workflowRun: OrchestrationV2ThreadShell["workflowRun"] | null; readonly activeProviderThreadId: OrchestrationV2ThreadShell["activeProviderThreadId"]; readonly latestRun: ThreadRunSummary | null; readonly runtime: ThreadRuntimeSummary | null; @@ -314,6 +316,7 @@ export function presentThreadShell( forkedFrom: thread.forkedFrom, linkOrigin: thread.linkOrigin ?? null, delegatedFrom: thread.delegatedFrom ?? null, + workflowRun: thread.workflowRun ?? null, activeProviderThreadId: thread.activeProviderThreadId, latestRun, runtime, diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.ts index 6545f377cc632..61bcd4bcac53a 100644 --- a/packages/client-runtime/src/state/server.ts +++ b/packages/client-runtime/src/state/server.ts @@ -53,6 +53,7 @@ import * as EnvironmentSupervisor from "../connection/supervisor.ts"; import { safeErrorLogAttributes } from "../errors/safeLog.ts"; import * as Persistence from "../platform/persistence.ts"; import { runCachePersistence } from "./cachePersistence.ts"; +import { workflowRunRefreshKey } from "../workflows.ts"; import { currentSession, isRpcClientError, @@ -1461,6 +1462,36 @@ export function createServerEnvironmentAtoms( ), ); }); + const workflowsLive = createEnvironmentRpcSubscriptionAtomFamily(runtime, { + label: "environment-data:server:workflows:live", + tag: WS_METHODS.workflowsSubscribe, + }); + const liveWorkflowSnapshot = (environmentId: EnvironmentId) => { + const live = workflowsLive({ environmentId, input: {} }); + return (get: Atom.AtomContext) => Option.getOrUndefined(AsyncResult.value(get(live))); + }; + // Keyed by a JSON array of environment ids, like the compaction notice, to read them as one. + const workflowsLiveAcross = Atom.family((environmentIdsKey: string) => { + const sources = (JSON.parse(environmentIdsKey) as EnvironmentId[]).map((environmentId) => ({ + environmentId, + atom: workflowsLive({ environmentId, input: {} }), + })); + return Atom.make((get) => + sources.map(({ environmentId, atom }) => ({ environmentId, result: get(atom) })), + ).pipe(Atom.withLabel(`environment-data:server:workflows:live-across:${environmentIdsKey}`)); + }); + // One change of a run or file at a time per target, so a double click does not act twice. + const workflowRunConcurrency = { + mode: "singleFlight" as const, + key: ({ environmentId, input }: { environmentId: EnvironmentId; input: { runId: string } }) => + JSON.stringify([environmentId, input.runId]), + }; + const workflowDefinitionScheduler = createAtomCommandScheduler(); + const workflowDefinitionConcurrency = { + mode: "serial" as const, + key: ({ environmentId, input }: { environmentId: EnvironmentId; input: { name: string } }) => + JSON.stringify([environmentId, input.name]), + }; const welcome = (target: { readonly environmentId: EnvironmentId; readonly input: EnvironmentRpcInput; @@ -1607,6 +1638,26 @@ export function createServerEnvironmentAtoms( label: "environment-data:server:scheduled-task:webhook-delivery", tag: WS_METHODS.scheduledTasksGetWebhookDelivery, }), + workflowsLive, + workflowsLiveAcross, + workflowRun: createEnvironmentRpcQueryAtomFamily(runtime, { + label: "environment-data:server:workflows:run", + tag: WS_METHODS.workflowsGet, + refreshTrigger: ({ environmentId, input }) => { + const snapshot = liveWorkflowSnapshot(environmentId); + return Atom.make((get) => workflowRunRefreshKey(snapshot(get), input.runId)); + }, + isFinal: (detail) => detail.run.endedAt !== null, + }), + // Read again whenever the server loads the files or finds them wrong, which `revision` says. + workflowDefinition: createEnvironmentRpcQueryAtomFamily(runtime, { + label: "environment-data:server:workflows:definition", + tag: WS_METHODS.workflowsGetDefinition, + refreshTrigger: ({ environmentId }) => { + const snapshot = liveWorkflowSnapshot(environmentId); + return Atom.make((get) => snapshot(get)?.definition?.revision); + }, + }), scheduledTasksLive: createEnvironmentRpcSubscriptionAtomFamily(runtime, { label: "environment-data:server:scheduled-tasks:live", tag: WS_METHODS.scheduledTasksSubscribe, @@ -1904,6 +1955,37 @@ export function createServerEnvironmentAtoms( scheduler: configScheduler, concurrency: configConcurrency, }), + answerWorkflowQuestion: createEnvironmentRpcCommand(runtime, { + label: "environment-data:server:workflows:answer", + tag: WS_METHODS.workflowsAnswer, + concurrency: { + mode: "singleFlight", + key: ({ environmentId, input }) => JSON.stringify([environmentId, input.runId, input.name]), + }, + }), + resumeWorkflowRun: createEnvironmentRpcCommand(runtime, { + label: "environment-data:server:workflows:resume", + tag: WS_METHODS.workflowsResume, + concurrency: workflowRunConcurrency, + }), + cancelWorkflowRun: createEnvironmentRpcCommand(runtime, { + label: "environment-data:server:workflows:cancel", + tag: WS_METHODS.workflowsCancel, + concurrency: workflowRunConcurrency, + }), + // Saves and deletes of one file go one after another: each carries its own text. + saveWorkflowDefinition: createEnvironmentRpcCommand(runtime, { + label: "environment-data:server:workflows:save-definition", + tag: WS_METHODS.workflowsSaveDefinition, + scheduler: workflowDefinitionScheduler, + concurrency: workflowDefinitionConcurrency, + }), + deleteWorkflowDefinition: createEnvironmentRpcCommand(runtime, { + label: "environment-data:server:workflows:delete-definition", + tag: WS_METHODS.workflowsDeleteDefinition, + scheduler: workflowDefinitionScheduler, + concurrency: workflowDefinitionConcurrency, + }), createGuestShare: createEnvironmentRpcCommand(runtime, { label: "environment-data:server:guest-share:create", tag: WS_METHODS.guestShareCreate, diff --git a/packages/client-runtime/src/workflows.test.ts b/packages/client-runtime/src/workflows.test.ts new file mode 100644 index 0000000000000..9fce777fd5642 --- /dev/null +++ b/packages/client-runtime/src/workflows.test.ts @@ -0,0 +1,521 @@ +import type { + WorkflowQuestion, + WorkflowRun, + WorkflowRunReference, + WorkflowStep, +} from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { + allWorkflowRunNodes, + buildWorkflowFeed, + buildWorkflowTimeline, + defaultWorkflowListTab, + defaultWorkflowRunId, + groupWorkflowRuns, + listedWorkflowRuns, + readWorkflowQuestion, + workflowAgentSummary, + workflowAnswer, + workflowChip, + workflowFlowFocus, + workflowPausedBeat, + workflowResultLines, + workflowRunInvolves, + workflowRunLists, + workflowRunNow, + workflowRunRefreshKey, + workflowReferenceIssue, + workflowReferenceLabel, + workflowReferencePullRequest, + workflowRunState, + workflowSaidStart, + workflowStepReferences, + workflowStepTime, + workflowOneLine, + workflowTriggerLine, +} from "./workflows.ts"; + +const two = (value: number) => String(value).padStart(2, "0"); +const at = (minute: number, second = 0) => `2026-11-01T00:${two(minute)}:${two(second)}.000Z`; + +const run = (runId: string, fields: Partial = {}): WorkflowRun => ({ + runId, + workflow: "release", + version: 1, + title: runId, + status: "running", + detail: null, + result: null, + pauses: 0, + retired: false, + resumesAt: null, + parentRunId: null, + parentStep: null, + startedAt: at(0), + updatedAt: at(0), + endedAt: null, + ...fields, +}); +const step = ( + name: string, + kind: WorkflowStep["kind"], + from: string, + to: string | null, + fields: Partial = {}, +): WorkflowStep => ({ + name, + kind, + status: to === null ? "running" : "completed", + attempts: 1, + detail: null, + threadId: null, + environmentId: null, + result: null, + said: null, + startedAt: from, + endedAt: to, + ...fields, +}); +const question = (runId: string, request: unknown = { title: "Ship?" }): WorkflowQuestion => ({ + runId, + name: "approve", + request: request as never, + askedAt: at(1), + thread: null, +}); + +describe("groupWorkflowRuns", () => { + const registered = [ + { name: "release", version: 1, triggers: ["webhook tags"] }, + { name: "check", version: 1, triggers: [] }, + { name: "report", version: 2, triggers: ["daily at 09:00"] }, + ]; + + it("puts what waits on a person first, then each workflow with its own runs", () => { + const groups = groupWorkflowRuns( + registered, + [ + run("done", { status: "completed", endedAt: at(9) }), + run("busy"), + run("parent", { status: "waiting", detail: "check" }), + // The child is what is paused, so its parent is the entry that needs someone. + run("child", { + workflow: "check", + status: "paused", + parentRunId: "parent", + parentStep: "check", + }), + run("asks", { workflow: "old", status: "waiting", detail: "approve" }), + run("orphan", { workflow: "old", status: "completed", endedAt: at(8), parentRunId: "x" }), + ], + [question("asks")], + ); + expect(groups.needsYou.map((node) => node.run.runId)).toEqual(["parent", "asks"]); + expect(groups.needsYou[0]?.children.map((node) => node.run.runId)).toEqual(["child"]); + expect( + groups.workflows.map((section) => [ + section.name, + workflowTriggerLine(section), + [...section.active, ...section.finished].map((node) => node.run.runId), + ]), + ).toEqual([ + // What is under way comes first, then what has run, then what only exists. + ["release", "Starts on webhook tags", ["busy", "done"]], + ["old", "No longer registered on this server", ["orphan"]], + ["check", "Runs as part of other workflows", []], + ["report", "Starts on daily at 09:00", []], + ]); + expect(allWorkflowRunNodes(groups).map((node) => node.run.runId)).toEqual([ + "parent", + "child", + "asks", + "busy", + "done", + "orphan", + ]); + // Opening the page lands on the first thing to act on, not on its untroubled parent. + expect(defaultWorkflowRunId(groups)).toBe("child"); + }); + + it("opens a run that is under way when nothing waits on anyone, else the newest", () => { + const quiet = groupWorkflowRuns( + registered, + [run("old", { endedAt: at(2), updatedAt: at(2) }), run("live", { workflow: "report" })], + [], + ); + expect(defaultWorkflowRunId(quiet)).toBe("live"); + const over = groupWorkflowRuns( + registered, + [ + run("first", { endedAt: at(2), updatedAt: at(2) }), + run("last", { workflow: "report", endedAt: at(5), updatedAt: at(5) }), + ], + [], + ); + expect(defaultWorkflowRunId(over)).toBe("last"); + expect(defaultWorkflowRunId(groupWorkflowRuns(registered, [], []))).toBeNull(); + }); +}); + +describe("the list of runs", () => { + const only = (fields: Partial, questions: ReadonlyArray = []) => + allWorkflowRunNodes(groupWorkflowRuns([], [run("a", fields)], questions))[0]!; + + it("gives a run the word the thread list would, and says what it is at", () => { + const told = (fields: Partial, questions?: ReadonlyArray) => { + const node = only(fields, questions); + return `${workflowRunState(node).word}: ${workflowRunNow(node)}`; + }; + expect(told({ status: "waiting", detail: "agent review" })).toBe("Working: review is working"); + expect(told({ status: "waiting", detail: "sleep night" })).toBe("Sleeping: Sleeping at night"); + expect(told({ status: "waiting", detail: "ci" })).toBe("Waiting: Waiting for ci"); + expect(told({ status: "waiting", detail: "approve" }, [question("a")])).toBe( + "Needs you: Asks: Ship?", + ); + expect(told({ status: "paused", detail: "build: exit 1\n at build.ts" })).toBe( + "Paused: build: exit 1", + ); + expect(told({ status: "completed", endedAt: at(1), result: { merged: "ba6ac73" } })).toBe( + "Done: merged: ba6ac73", + ); + expect(told({ status: "cancelled", endedAt: at(1), detail: "superseded" })).toBe( + "Cancelled: superseded", + ); + }); + + it("says of a run that waits on one it invoked what that one waits on", () => { + const groups = groupWorkflowRuns( + [], + [ + run("child", { parentRunId: "parent", status: "waiting", title: "Check web" }), + run("parent", { status: "waiting", detail: "check" }), + ], + [question("child")], + ); + const parent = allWorkflowRunNodes(groups)[0]!; + expect(workflowRunState(parent).word).toBe("Needs you"); + expect(workflowRunNow(parent)).toBe("Check web: Asks: Ship?"); + }); + + it("sorts runs into what waits on a person, what is under way, and everything", () => { + const groups = groupWorkflowRuns( + [], + [ + run("old", { status: "completed", endedAt: at(1), updatedAt: at(1) }), + run("busy", { updatedAt: at(2) }), + run("stuck", { status: "paused", updatedAt: at(3) }), + run("new", { status: "completed", endedAt: at(4), updatedAt: at(4) }), + ], + [], + ); + const lists = workflowRunLists(groups); + const ids = (nodes: ReadonlyArray<{ readonly run: WorkflowRun }>) => + nodes.map((node) => node.run.runId); + expect(ids(lists["needs-you"])).toEqual(["stuck"]); + expect(ids(lists.running)).toEqual(["busy"]); + expect(ids(lists.all)).toEqual(["stuck", "busy", "new", "old"]); + expect(defaultWorkflowListTab(groups)).toBe("needs-you"); + expect(defaultWorkflowListTab(groupWorkflowRuns([], [run("busy")], []))).toBe("running"); + expect( + defaultWorkflowListTab( + groupWorkflowRuns([], [run("old", { status: "completed", endedAt: at(1) })], []), + ), + ).toBe("all"); + const invoked = workflowRunLists( + groupWorkflowRuns( + [], + [run("parent"), run("child", { workflow: "check", parentRunId: "parent" }), run("other")], + [], + ), + ).all; + expect(ids(invoked.filter((node) => workflowRunInvolves(node, "check")))).toEqual(["parent"]); + }); + + it("leaves out what a workflow skipped, but not a skipped step of another run", () => { + const runs = [ + run("ignored", { status: "skipped", endedAt: at(1) }), + run("parent"), + run("child", { status: "skipped", endedAt: at(1), parentRunId: "parent" }), + ]; + expect(listedWorkflowRuns(runs, false)).toEqual({ runs: [runs[1], runs[2]], skipped: 1 }); + expect(listedWorkflowRuns(runs, true)).toEqual({ runs, skipped: 1 }); + }); + + it("marks a workflow with the same letters and colour every time", () => { + expect(workflowChip("nightly-report").letters).toBe("NR"); + expect(workflowChip("issue").letters).toBe("IS"); + expect(workflowChip("issue")).toEqual(workflowChip("issue")); + }); +}); + +describe("workflowRunRefreshKey", () => { + it("reads an ended run again only when it changes, and one under way on any change", () => { + const snapshot = (runs: ReadonlyArray) => ({ workflows: [], runs, questions: [] }); + const ended = run("old", { endedAt: at(5), updatedAt: at(5) }); + const before = snapshot([ended, run("busy", { updatedAt: at(6) })]); + const after = snapshot([ended, run("busy", { updatedAt: at(7) })]); + expect(workflowRunRefreshKey(before, "old")).toBe(workflowRunRefreshKey(after, "old")); + expect(workflowRunRefreshKey(before, "busy")).not.toBe(workflowRunRefreshKey(after, "busy")); + }); +}); + +describe("workflowAgentSummary", () => { + it("tells an agent's words apart from the facts of its result", () => { + expect(workflowAgentSummary({ result: "Fixed in one line.", said: null })).toEqual({ + said: "Fixed in one line.", + facts: [], + }); + expect( + workflowAgentSummary({ + said: "Reproduced on main.", + result: { kind: "bug", reproduced: true, surfaces: ["web", "desktop"], prUrl: null }, + }), + ).toEqual({ + said: "Reproduced on main.", + facts: [ + { label: "kind", value: "bug" }, + { label: "reproduced", value: "yes" }, + { label: "surfaces", value: "web, desktop" }, + ], + }); + }); + + it("lets the longest prose of a result speak when no closing words were kept", () => { + const summary = + "The draft is stored per thread id, and a reload before the thread exists drops it for good."; + expect(workflowAgentSummary({ said: null, result: { verdict: "merge", summary } })).toEqual({ + said: summary, + facts: [{ label: "verdict", value: "merge" }], + }); + }); +}); + +describe("workflowSaidStart", () => { + it("cuts a long reply where a paragraph ends", () => { + const said = + "It is a real bug.\n\n**Where:** line 5.\n\n**Reproduced:** yes, with 3660 seconds."; + expect(workflowSaidStart(said, 200)).toBeNull(); + expect(workflowSaidStart(said, 40)).toBe("It is a real bug.\n\n**Where:** line 5."); + expect(workflowSaidStart(said, 10)).toBe("It is a real bug."); + }); +}); + +describe("buildWorkflowTimeline", () => { + it("keeps the beats of a run and folds the bookkeeping between them", () => { + const parent = run("r", { startedAt: at(0), endedAt: at(10) }); + const child = run("c", { parentRunId: "r", parentStep: "check", title: "Check web" }); + const timeline = buildWorkflowTimeline({ + run: parent, + children: [child], + nowMs: Date.parse(at(10)), + steps: [ + step("load", "step", at(0), at(0)), + step("switch", "step", at(0), at(0)), + step("triage", "agent", at(0), at(3), { threadId: "t1" }), + // Two reviews at once. + step("review-a", "agent", at(3), at(5)), + step("review-b", "agent", at(3), at(6)), + step("record", "step", at(6), at(6)), + step("check/start", "step", at(6), at(6)), + step("check", "wait", at(6), at(8)), + step("build", "step", at(8), at(9)), + step("publish", "step", at(9), at(9), { status: "failed", detail: "503" }), + ], + }); + expect( + timeline.rows.map((row) => + row.kind === "quick" + ? `quick:${row.steps.map((quick) => quick.name).join(",")}` + : `${row.kind}:${row.name}${row.parallel ? ":parallel" : ""}`, + ), + ).toEqual([ + "quick:load,switch", + "agent:triage", + "agent:review-a:parallel", + "agent:review-b:parallel", + "quick:record", + // The step that started the invoked run is told by the wait for it. + "run:check", + // A plain step that took a minute is a beat; so is one that failed in no time. + "step:build", + "step:publish", + ]); + const invoked = timeline.rows.find((row) => row.kind === "run"); + expect(invoked?.kind === "run" ? invoked.childRun?.title : null).toBe("Check web"); + // Read as a feed, the two reviews are one row, and the path has a stop per row that matters. + const feed = buildWorkflowFeed(timeline); + expect( + feed.map((row) => + row.kind === "together" + ? row.beats.map((beat) => beat.name).join("+") + : row.kind === "quick" + ? "quick" + : row.name, + ), + ).toEqual(["quick", "triage", "review-a+review-b", "quick", "check", "build", "publish"]); + // The flow opens where the run needs someone, then where it failed, then on how it ended. + const focus = (status: WorkflowRun["status"], questions: ReadonlyArray = []) => + workflowFlowFocus({ rows: feed, status, ended: status === "completed", questions }); + expect(focus("waiting", ["approve"])).toBe("question:approve"); + expect(focus("paused")).toBe("step:publish"); + expect(focus("completed")).toBe("end"); + expect(focus("running")).toBe("step:publish"); + expect(workflowPausedBeat(feed, "paused")?.name).toBe("publish"); + // A failure the workflow caught, with the run going on after it, is not where it paused. + const caught = buildWorkflowFeed( + buildWorkflowTimeline({ + run: run("r", { startedAt: at(0) }), + children: [], + nowMs: Date.parse(at(10)), + steps: [ + step("lint", "agent", at(0), at(2), { status: "failed", detail: "timed out" }), + step("build", "agent", at(2), at(4)), + ], + }), + ); + expect(workflowPausedBeat(caught, "paused")).toBeNull(); + expect(workflowFlowFocus({ rows: caught, status: "paused", ended: false, questions: [] })).toBe( + "pause", + ); + }); + + it("measures a step that is under way up to now", () => { + const timeline = buildWorkflowTimeline({ + run: run("r", { startedAt: at(0) }), + children: [], + nowMs: Date.parse(at(4)), + steps: [step("fix", "agent", at(1), null)], + }); + const [fix] = timeline.rows; + expect(fix?.kind === "agent" ? [fix.endMs - fix.startMs, timeline.endMs] : null).toEqual([ + 180_000, + Date.parse(at(4)), + ]); + // Six started at once and a clock a minute behind: still one row, and no time runs backwards. + const wide = buildWorkflowTimeline({ + run: run("r", { startedAt: at(1) }), + children: [], + nowMs: Date.parse(at(0)), + steps: [ + step("a", "sleep", at(1), at(2)), + ...["b", "c", "d", "e", "f"].map((name) => step(name, "sleep", at(1), null)), + ], + }); + expect( + buildWorkflowFeed(wide).map((row) => (row.kind === "together" ? row.beats.length : 1)), + ).toEqual([6]); + expect(wide.rows.every((row) => row.endMs >= row.startMs)).toBe(true); + }); +}); + +describe("workflowResultLines", () => { + it("reads a result as a sentence or as its fields", () => { + expect(workflowResultLines("merged as ba6ac7")).toEqual([ + { label: null, value: "merged as ba6ac7" }, + ]); + expect(workflowResultLines({ sent: true, to: "everyone" })).toEqual([ + { label: "sent", value: "true" }, + { label: "to", value: "everyone" }, + ]); + expect(workflowResultLines(null)).toEqual([]); + }); +}); + +describe("readWorkflowQuestion", () => { + it("reads the title, the choices and the body, and drops parts of another shape", () => { + expect( + readWorkflowQuestion( + question("r", { title: "Ship it?", choices: ["yes", 2], data: { body: "Diff is small." } }), + ), + ).toEqual({ title: "Ship it?", choices: ["yes"], body: "Diff is small." }); + expect(readWorkflowQuestion(question("r", null))).toEqual({ + title: "approve", + choices: [], + body: null, + }); + }); +}); + +describe("workflowAnswer", () => { + it("reads a person's answer off a question's result", () => { + expect(workflowAnswer({ choice: "Ship", reason: " " })).toEqual({ + choice: "Ship", + reason: null, + }); + expect(workflowAnswer({ choice: "Hold", reason: "Too risky" })).toEqual({ + choice: "Hold", + reason: "Too risky", + }); + expect(workflowAnswer("done")).toBeNull(); + expect(workflowAnswer(null)).toBeNull(); + }); +}); + +describe("workflow references", () => { + const reference = (fields: Partial): WorkflowRunReference => ({ + kind: "issue", + key: "k", + address: {}, + title: "", + url: null, + state: null, + steps: [], + origin: "step", + ...fields, + }); + const issue = (key: string) => + reference({ + key, + address: { projectId: "p1", tracker: "github", scope: "me/app", key }, + steps: ["triage"], + }); + const pullRequest = reference({ + kind: "pullRequest", + key: "pr", + address: { projectId: "p1", host: "github.com", repository: "me/app", number: 418 }, + steps: ["fix", "checks"], + }); + const machine = reference({ kind: "machine", address: { id: 1 }, title: "box-1" }); + + it("names each by what its kind calls it, and a kind it does not know by its title", () => { + expect( + [issue("412"), issue("ENG-12"), pullRequest, machine].map(workflowReferenceLabel), + ).toEqual(["#412", "ENG-12", "#418", "box-1"]); + expect(workflowReferenceLabel(reference({ kind: "machine" }))).toBe("machine"); + }); + + it("opens an issue or pull request only when its address reads as one", () => { + expect(workflowReferencePullRequest(pullRequest)?.number).toBe(418); + expect(workflowReferenceIssue(pullRequest)).toBeNull(); + expect(workflowReferenceIssue(reference({ address: { key: 1 } }))).toBeNull(); + expect(workflowReferenceIssue(machine)).toBeNull(); + }); + + it("gives a step the things it touched", () => { + const all = [issue("412"), pullRequest, machine]; + expect(workflowStepReferences(all, "checks")).toEqual([pullRequest]); + expect(workflowStepReferences(all, "merge")).toEqual([]); + }); +}); + +describe("workflowStepTime", () => { + it("keeps one shape down the column", () => { + expect(workflowStepTime(9)).toBe("0.1s"); + expect(workflowStepTime(342)).toBe("0.3s"); + expect(workflowStepTime(9_700)).toBe("9.7s"); + expect(workflowStepTime(4_000)).toBe("4s"); + expect(workflowStepTime(12_400)).toBe("12s"); + }); +}); + +describe("workflowOneLine", () => { + it("reads a reply's first sentence as plain words", () => { + expect(workflowOneLine("## Done\n\nI added `clamp` next to **sum**. Tests pass.")).toBe( + "I added clamp next to sum.", + ); + expect(workflowOneLine("- See [the issue](https://x.test/2) first")).toBe( + "See the issue first", + ); + }); +}); diff --git a/packages/client-runtime/src/workflows.ts b/packages/client-runtime/src/workflows.ts new file mode 100644 index 0000000000000..3808f94703237 --- /dev/null +++ b/packages/client-runtime/src/workflows.ts @@ -0,0 +1,770 @@ +import { mFallback, msg } from "gt-i18n"; +import type { MFunctionType } from "gt-i18n/types"; +import { + type IssueRef, + type PullRequestRef, + WorkflowIssueAddress, + WorkflowPullRequestAddress, + WorkflowReferenceKind, + type WorkflowQuestion, + type WorkflowRun, + type WorkflowRunReference, + type WorkflowRunsSnapshot, + type WorkflowStep, + type WorkflowSummary, +} from "@t3tools/contracts"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import { formatDuration } from "@t3tools/shared/orchestrationTiming"; + +export interface WorkflowQuestionView { + readonly title: string; + readonly choices: ReadonlyArray; + readonly body: string | null; +} + +function field(value: unknown, key: string): unknown { + return typeof value === "object" && value !== null && !Array.isArray(value) + ? (value as Readonly>)[key] + : undefined; +} + +/** + * What a question shows. `request` is whatever the workflow handed `ask`, so a part that is + * missing or of another shape is left out instead of failing the whole list. + */ +export function readWorkflowQuestion(question: WorkflowQuestion): WorkflowQuestionView { + const title = field(question.request, "title"); + const choices = field(question.request, "choices"); + const body = field(field(question.request, "data"), "body"); + return { + title: typeof title === "string" && title.trim() !== "" ? title : question.name, + choices: Array.isArray(choices) + ? choices.filter((choice): choice is string => typeof choice === "string") + : [], + body: typeof body === "string" && body.trim() !== "" ? body : null, + }; +} + +/** + * What a run's detail is read again on, out of the live list: the run's last change once it has + * ended. Steps do not move a run's `updatedAt`, so one under way is read again on any change. + */ +export function workflowRunRefreshKey( + snapshot: WorkflowRunsSnapshot | undefined, + runId: string, +): unknown { + const run = snapshot?.runs.find((candidate) => candidate.runId === runId); + return run === undefined || run.endedAt === null ? snapshot : run.updatedAt; +} + +export interface WorkflowRunNode { + readonly run: WorkflowRun; + /** The runs it invoked, in the order they started. */ + readonly children: ReadonlyArray; + /** Questions open on this run. */ + readonly questions: ReadonlyArray; +} + +/** One workflow and the runs of it that nobody has to act on. */ +export interface WorkflowSection { + readonly name: string; + /** What starts it, in words. Null for a workflow this server no longer has registered. */ + readonly triggers: ReadonlyArray | null; + readonly active: ReadonlyArray; + readonly finished: ReadonlyArray; + /** It has runs, and every one was invoked by a run of another workflow. */ + readonly invokedOnly: boolean; + /** It has never run here, as far as the list goes back. */ + readonly neverRan: boolean; +} + +export interface WorkflowRunGroups { + /** Runs a person has to act on: one has a question open or is paused, itself or below it. */ + readonly needsYou: ReadonlyArray; + /** Every workflow there is, busiest first, each with its other runs. */ + readonly workflows: ReadonlyArray; +} + +const needsPerson = (node: WorkflowRunNode): boolean => + node.questions.length > 0 || node.run.status === "paused" || node.children.some(needsPerson); + +/** + * The list a person reads: what waits on them first, then each workflow with its runs. A run + * that another invoked sits under that one, so a piece of work is one entry, and a workflow that + * has not run yet is still listed, since the list is also how one learns what exists. `runs` is + * newest first and that order is kept. + */ +/** + * The runs a list shows: without those a workflow skipped as not its to do, unless asked for + * them. A skipped run that another run invoked stays, as a step of that one. + */ +export function listedWorkflowRuns( + runs: ReadonlyArray, + showSkipped: boolean, +): { readonly runs: ReadonlyArray; readonly skipped: number } { + const hidden = (run: WorkflowRun) => run.status === "skipped" && run.parentRunId === null; + const skipped = runs.filter(hidden).length; + return { runs: showSkipped ? runs : runs.filter((run) => !hidden(run)), skipped }; +} + +export function groupWorkflowRuns( + workflows: ReadonlyArray, + runs: ReadonlyArray, + questions: ReadonlyArray, +): WorkflowRunGroups { + const listed = new Set(runs.map((run) => run.runId)); + const childrenOf = new Map(); + const roots: WorkflowRun[] = []; + for (const run of runs) { + if (run.parentRunId === null || !listed.has(run.parentRunId)) { + roots.push(run); + continue; + } + const siblings = childrenOf.get(run.parentRunId); + if (siblings) siblings.push(run); + else childrenOf.set(run.parentRunId, [run]); + } + const node = (run: WorkflowRun): WorkflowRunNode => ({ + run, + questions: questions.filter((question) => question.runId === run.runId), + children: (childrenOf.get(run.runId) ?? []) + .slice() + .sort((left, right) => left.startedAt.localeCompare(right.startedAt)) + .map(node), + }); + const needsYou: WorkflowRunNode[] = []; + const sections = new Map(); + const sectionOf = (name: string) => { + const known = sections.get(name); + if (known) return known; + const made = { active: [], finished: [] }; + sections.set(name, made); + return made; + }; + for (const root of roots.map(node)) { + if (needsPerson(root)) needsYou.push(root); + else if (root.run.endedAt === null) sectionOf(root.run.workflow).active.push(root); + else sectionOf(root.run.workflow).finished.push(root); + } + const registered = new Map(workflows.map((workflow) => [workflow.name, workflow] as const)); + const hasRuns = new Set(runs.map((run) => run.workflow)); + const hasRootRuns = new Set(roots.map((run) => run.workflow)); + const names = [...new Set([...sections.keys(), ...registered.keys(), ...hasRuns])]; + const rank = (name: string) => { + const section = sections.get(name); + if (section !== undefined && section.active.length > 0) return 0; + return section !== undefined && section.finished.length > 0 ? 1 : 2; + }; + return { + needsYou, + workflows: names + .map((name) => ({ + name, + triggers: registered.get(name)?.triggers ?? null, + active: sections.get(name)?.active ?? [], + finished: sections.get(name)?.finished ?? [], + invokedOnly: hasRuns.has(name) && !hasRootRuns.has(name), + neverRan: !hasRuns.has(name), + })) + .slice() + .sort( + (left, right) => rank(left.name) - rank(right.name) || left.name.localeCompare(right.name), + ), + }; +} + +/** Every run of these, parents before the runs they invoked. */ +function flattenWorkflowRunNodes( + nodes: ReadonlyArray, +): ReadonlyArray { + return nodes.flatMap((node) => [node, ...flattenWorkflowRunNodes(node.children)]); +} + +/** Every run in the list, in the order it is listed. */ +export function allWorkflowRunNodes(groups: WorkflowRunGroups): ReadonlyArray { + return flattenWorkflowRunNodes([ + ...groups.needsYou, + ...groups.workflows.flatMap((section) => [...section.active, ...section.finished]), + ]); +} + +/** The run to show when none was picked: the first that waits on a person, else one under way. */ +export function defaultWorkflowRunId(groups: WorkflowRunGroups): string | null { + const waiting = flattenWorkflowRunNodes(groups.needsYou).find( + (node) => node.questions.length > 0 || node.run.status === "paused", + ); + const rest = groups.workflows; + return ( + waiting?.run.runId ?? + rest.find((section) => section.active.length > 0)?.active[0]?.run.runId ?? + rest + .flatMap((section) => section.finished) + .slice() + .sort((left, right) => right.run.updatedAt.localeCompare(left.run.updatedAt))[0]?.run.runId ?? + null + ); +} + +/** What starts a workflow, in words. */ +export function workflowTriggerLine( + section: WorkflowSection, + resolve: MFunctionType = mFallback, +): string { + if (section.triggers === null) return resolve(msg("No longer registered on this server")); + if (section.invokedOnly) return resolve(msg("Runs as part of other workflows")); + return section.triggers.length === 0 + ? resolve(msg("Started by hand")) + : resolve(msg("Starts on {triggers}", { triggers: section.triggers.join(", ") })); +} + +export type WorkflowListTab = "needs-you" | "running" | "all"; + +/** + * The three lists a person switches between. Each is whole pieces of work, newest change first: a + * run that another invoked is reached through that one. + */ +export function workflowRunLists( + groups: WorkflowRunGroups, +): Readonly>> { + const byChange = (nodes: ReadonlyArray) => + [...nodes].sort((left, right) => right.run.updatedAt.localeCompare(left.run.updatedAt)); + const running = groups.workflows.flatMap((section) => section.active); + const finished = groups.workflows.flatMap((section) => section.finished); + return { + "needs-you": byChange(groups.needsYou), + running: byChange(running), + all: [...byChange(groups.needsYou), ...byChange(running), ...byChange(finished)], + }; +} + +/** Whether a run is of this workflow or invoked one, so a workflow that only runs inside others is found. */ +export function workflowRunInvolves(node: WorkflowRunNode, workflow: string): boolean { + return ( + node.run.workflow === workflow || + node.children.some((child) => workflowRunInvolves(child, workflow)) + ); +} + +/** The list to open on: what waits on a person, else what is under way, else everything. */ +export function defaultWorkflowListTab(groups: WorkflowRunGroups): WorkflowListTab { + if (groups.needsYou.length > 0) return "needs-you"; + return groups.workflows.some((section) => section.active.length > 0) ? "running" : "all"; +} + +const CHIP_TONES = 5; + +/** A workflow's mark in the list: two letters and one of a few colours, the same every time. */ +export function workflowChip(name: string): { readonly letters: string; readonly tone: number } { + const parts = name.split(/[^\p{L}\p{N}]+/u).filter((part) => part !== ""); + const letters = + parts.length > 1 ? `${parts[0]![0]}${parts[1]![0]}` : (parts[0] ?? name).slice(0, 2); + let hash = 0; + for (const char of name) hash = (hash * 31 + char.codePointAt(0)!) % 9973; + return { letters: letters.toUpperCase(), tone: hash % CHIP_TONES }; +} + +export type WorkflowRunTone = "input" | "failed" | "working" | "quiet" | "done"; + +/** A run's state as the one word the thread list would use for it. */ +export function workflowRunState( + node: WorkflowRunNode, + resolve: MFunctionType = mFallback, +): { + readonly word: string; + readonly tone: WorkflowRunTone; +} { + const { run } = node; + const input = { + word: resolve(msg("Needs you", { $context: "workflow run status: it waits on a person" })), + tone: "input", + } as const; + const working = { + word: resolve(msg("Working", { $context: "workflow run status" })), + tone: "working", + } as const; + if (node.questions.length > 0) return input; + switch (run.status) { + case "paused": + return { + word: resolve(msg("Paused", { $context: "workflow run status" })), + tone: "failed", + }; + case "running": + return working; + case "waiting": { + const detail = run.detail ?? ""; + if (detail.startsWith("agent ")) return working; + if (detail.startsWith("sleep ")) { + return { + word: resolve(msg("Sleeping", { $context: "workflow run status" })), + tone: "quiet", + }; + } + // Something below it holds it up; say that, not that it idles. + if (node.children.some(needsPerson)) return input; + return { word: resolve(msg("Waiting", { $context: "workflow run status" })), tone: "quiet" }; + } + case "completed": + return { word: resolve(msg("Done", { $context: "workflow run status" })), tone: "done" }; + case "stopped": + return { word: resolve(msg("Stopped", { $context: "workflow run status" })), tone: "quiet" }; + case "skipped": + return { word: resolve(msg("Skipped", { $context: "workflow run status" })), tone: "quiet" }; + case "cancelled": + return { + word: resolve(msg("Cancelled", { $context: "workflow run status" })), + tone: "quiet", + }; + } +} + +const firstLine = (text: string) => text.trim().split("\n", 1)[0]!.trim(); + +/** What a run is at right now, as the line under its title. */ +export function workflowRunNow(node: WorkflowRunNode, resolve: MFunctionType = mFallback): string { + const { run } = node; + const detail = run.detail?.trim() ?? ""; + const asked = node.questions[0]; + if (asked !== undefined) { + const more = node.questions.length - 1; + const question = readWorkflowQuestion(asked).title; + return more > 0 + ? resolve(msg("Asks: {question} and {more} more", { question, more })) + : resolve(msg("Asks: {question}", { question })); + } + const below = flattenWorkflowRunNodes(node.children); + const holding = below.find( + (child) => child.questions.length > 0 || child.run.status === "paused", + ); + switch (run.status) { + case "paused": + return detail === "" ? resolve(msg("A step failed")) : firstLine(detail); + case "running": + return resolve(msg("Running its own steps")); + case "waiting": + if (holding !== undefined) { + return `${holding.run.title}: ${workflowRunNow(holding, resolve)}`; + } + if (detail.startsWith("agent ")) { + return resolve(msg("{step} is working", { step: detail.slice(6) })); + } + if (detail.startsWith("sleep ")) { + return resolve(msg("Sleeping at {step}", { step: detail.slice(6) })); + } + if (below.some((child) => child.run.endedAt === null)) { + const open = below.filter((child) => child.run.endedAt === null); + return open.length === 1 + ? resolve(msg("Runs {run}", { run: open[0]!.run.title })) + : resolve(msg("{count} runs under way", { count: open.length })); + } + return detail === "" + ? resolve(msg("Waiting", { $context: "what a workflow run is doing now" })) + : resolve(msg("Waiting for {step}", { step: detail })); + case "completed": { + const line = workflowResultLines(run.result)[0]; + if (line === undefined) { + return resolve(msg("Finished", { $context: "what a workflow run is doing now" })); + } + return firstLine(line.label === null ? line.value : `${line.label}: ${line.value}`); + } + case "stopped": + case "skipped": + case "cancelled": + return detail === "" ? resolve(msg("Ended early")) : firstLine(detail); + } +} + +/** A run's result as lines a person can read: a sentence, or the fields of an object. */ +export function workflowResultLines( + result: WorkflowRun["result"], +): ReadonlyArray<{ readonly label: string | null; readonly value: string }> { + if (result === null) return []; + if (typeof result !== "object") return [{ label: null, value: String(result) }]; + if (Array.isArray(result)) return [{ label: null, value: JSON.stringify(result) }]; + return Object.entries(result).map(([label, value]) => ({ + label, + value: typeof value === "string" ? value : JSON.stringify(value), + })); +} + +// A step this short is bookkeeping between the parts of a run that take time. +const QUICK_STEP_MS = 1_000; + +export interface WorkflowBeat { + readonly kind: WorkflowStep["kind"] | "run"; + readonly name: string; + readonly status: WorkflowStep["status"]; + readonly attempts: number; + /** A failure's reason, or when a sleep wakes. */ + readonly detail: string | null; + /** What it produced: a value, an agent's data or reply, the answer to a question. */ + readonly result: WorkflowStep["result"]; + /** What an agent said in closing, when its result is data. */ + readonly said: string | null; + readonly startMs: number; + /** When it ended, or `nowMs` while it is under way. */ + readonly endMs: number; + readonly thread: { readonly threadId: string; readonly environmentId: string | null } | null; + /** The run this step invoked and waited for. */ + readonly childRun: WorkflowRun | null; + /** Another beat was under way at the same time. */ + readonly parallel: boolean; +} + +export interface WorkflowQuickSteps { + readonly kind: "quick"; + readonly steps: ReadonlyArray; + readonly startMs: number; + readonly endMs: number; +} + +export type WorkflowTimelineRow = WorkflowBeat | WorkflowQuickSteps; + +export interface WorkflowTimeline { + readonly rows: ReadonlyArray; + readonly startMs: number; + readonly endMs: number; +} + +/** + * A run's steps as the story of the run: what took time or involved someone is a beat, and the + * quick steps between two beats fold into one row, since a journal of them hides where the run + * is. An invoked run takes the place of the two steps that started and awaited it. + */ +export function buildWorkflowTimeline(input: { + readonly run: Pick; + readonly steps: ReadonlyArray; + readonly children: ReadonlyArray; + readonly nowMs: number; +}): WorkflowTimeline { + const childByStep = new Map( + input.children + .filter((child) => child.parentRunId === input.run.runId && child.parentStep !== null) + .map((child) => [child.parentStep, child] as const), + ); + const startMs = Date.parse(input.run.startedAt); + // A caller's clock can be a minute old. Now is never before anything the run has done. + const nowMs = Math.max( + input.nowMs, + startMs, + ...input.steps.map((step) => Date.parse(step.endedAt ?? step.startedAt)), + ); + const endMs = input.run.endedAt === null ? nowMs : Date.parse(input.run.endedAt); + const rows: WorkflowTimelineRow[] = []; + const beats: WorkflowBeat[] = []; + let quick: WorkflowStep[] = []; + const flush = () => { + if (quick.length === 0) return; + rows.push({ + kind: "quick", + steps: quick, + startMs: Date.parse(quick[0]!.startedAt), + endMs: Date.parse(quick.at(-1)!.endedAt ?? quick.at(-1)!.startedAt), + }); + quick = []; + }; + for (const step of input.steps) { + // The step that started an invoked run is told by the wait that follows it. + if (step.kind === "step" && step.name.endsWith("/start")) { + if (childByStep.has(step.name.slice(0, -"/start".length))) continue; + } + const stepStart = Date.parse(step.startedAt); + const stepEnd = step.endedAt === null ? nowMs : Date.parse(step.endedAt); + const childRun = step.kind === "wait" ? (childByStep.get(step.name) ?? null) : null; + const isBeat = + step.kind !== "step" || + step.status !== "completed" || + step.attempts > 1 || + stepEnd - stepStart >= QUICK_STEP_MS; + if (!isBeat) { + quick.push(step); + continue; + } + flush(); + const beat: WorkflowBeat = { + kind: childRun === null ? step.kind : "run", + name: step.name, + status: step.status, + attempts: step.attempts, + detail: step.detail, + result: step.result, + said: step.said, + startMs: stepStart, + endMs: Math.max(stepStart, stepEnd), + thread: + step.threadId === null + ? null + : { threadId: step.threadId, environmentId: step.environmentId }, + childRun, + parallel: false, + }; + beats.push(beat); + rows.push(beat); + } + flush(); + const overlaps = (left: WorkflowBeat, right: WorkflowBeat) => + left !== right && left.startMs < openEnd(right) && right.startMs < openEnd(left); + return { + rows: rows.map((row) => + row.kind === "quick" + ? row + : { ...row, parallel: beats.some((other) => overlaps(row, other)) }, + ), + startMs, + endMs: Math.max(endMs, ...beats.map((beat) => beat.endMs), startMs + 1), + }; +} + +/** When a beat stops overlapping what starts after it: one still under way never does. */ +const openEnd = (beat: WorkflowBeat) => + beat.status === "running" ? Number.POSITIVE_INFINITY : beat.endMs; + +/** What a person answered a question with, when a step's result is such an answer. */ +export function workflowAnswer( + result: WorkflowStep["result"], +): { readonly choice: string; readonly reason: string | null } | null { + const choice = field(result, "choice"); + const reason = field(result, "reason"); + return typeof choice === "string" + ? { choice, reason: typeof reason === "string" && reason.trim() !== "" ? reason : null } + : null; +} + +/** Steps that were under way at the same time, shown side by side. */ +export interface WorkflowTogether { + readonly kind: "together"; + readonly beats: ReadonlyArray; +} + +export type WorkflowFeedRow = WorkflowTimelineRow | WorkflowTogether; + +/** + * The timeline as it is read: beats that overlapped become one row, so two reviewers at once look + * like two reviewers at once and not like one after the other. + */ +export function buildWorkflowFeed(timeline: WorkflowTimeline): ReadonlyArray { + const rows: WorkflowFeedRow[] = []; + let together: WorkflowBeat[] = []; + let until = 0; + const flush = () => { + if (together.length === 1) rows.push(together[0]!); + else if (together.length > 1) rows.push({ kind: "together", beats: together }); + together = []; + }; + for (const row of timeline.rows) { + if (row.kind === "quick") { + flush(); + rows.push(row); + continue; + } + if (together.length > 0 && row.parallel && row.startMs < until) { + together.push(row); + until = Math.max(until, openEnd(row)); + continue; + } + flush(); + together = [row]; + until = openEnd(row); + } + flush(); + return rows; +} + +/** The steps of a feed that take a place in the run's flow: every beat, in order. */ +const beatsOf = (rows: ReadonlyArray) => + rows.flatMap((row) => (row.kind === "quick" ? [] : row.kind === "together" ? row.beats : [row])); + +/** + * The step a paused run stopped at: the last that failed, unless the run went on after it, since + * then the workflow caught that failure. Null when the run is not paused at a step. + */ +export function workflowPausedBeat( + rows: ReadonlyArray, + status: WorkflowRun["status"], +): WorkflowBeat | null { + if (status !== "paused") return null; + const failed = beatsOf(rows).findLast((beat) => beat.status === "failed"); + if (failed === undefined) return null; + const wentOn = rows.some((row) => + row.kind === "together" + ? row.beats.some((beat) => beat !== failed && beat.startMs >= failed.endMs) + : row !== failed && row.startMs >= failed.endMs, + ); + return wentOn ? null : failed; +} + +/** + * Which part of a run's flow to open on: what waits on a person, then where it failed, then how + * it ended, then what is under way. Keys are `step:`, `question:`, `pause` and `end`. + */ +export function workflowFlowFocus(input: { + readonly rows: ReadonlyArray; + readonly status: WorkflowRun["status"]; + readonly ended: boolean; + /** The names of the questions that wait on a person. */ + readonly questions: ReadonlyArray; +}): string | null { + const beats = beatsOf(input.rows); + const asked = input.questions[0]; + if (asked !== undefined) { + const at = beats.find( + (beat) => + beat.kind === "ask" && beat.status === "running" && input.questions.includes(beat.name), + ); + return at === undefined ? `question:${asked}` : `step:${at.name}`; + } + if (input.status === "paused") { + const failed = workflowPausedBeat(input.rows, input.status); + return failed === null ? "pause" : `step:${failed.name}`; + } + if (input.ended) return "end"; + const last = beats.findLast((beat) => beat.status === "running") ?? beats.at(-1); + return last === undefined ? null : `step:${last.name}`; +} + +const FACT_LENGTH = 48; +const FACTS_SHOWN = 6; +// A string this long is the agent talking, not a fact about its work. +const PROSE_LENGTH = 80; + +const words = (key: string) => + key + .replace(/([a-z0-9])([A-Z])/g, "$1 $2") + .replace(/[_-]+/g, " ") + .toLowerCase(); + +function factValue(value: unknown): string | null { + if (typeof value === "boolean") return value ? "yes" : "no"; + if (typeof value === "number") return String(value); + if (typeof value === "string") { + const text = value.trim(); + return text !== "" && text.length <= FACT_LENGTH && !text.includes("\n") ? text : null; + } + if (Array.isArray(value) && value.length > 0 && value.length <= 4) { + const parts = value.map(factValue); + const joined = parts.join(", "); + return parts.every((part) => part !== null) && joined.length <= FACT_LENGTH ? joined : null; + } + return null; +} + +/** + * What an agent step has to say for itself: its words, and the short facts of its result. With no + * closing words kept, the longest piece of prose in the result stands in for them. + */ +export function workflowAgentSummary(beat: Pick): { + readonly said: string | null; + readonly facts: ReadonlyArray<{ readonly label: string; readonly value: string }>; +} { + const { result } = beat; + const kept = beat.said?.trim() ?? ""; + if (typeof result === "string") { + return { said: kept !== "" ? kept : result.trim() === "" ? null : result.trim(), facts: [] }; + } + if (result === null || typeof result !== "object" || Array.isArray(result)) { + return { said: kept === "" ? null : kept, facts: [] }; + } + const entries = Object.entries(result); + const prose = + kept !== "" + ? null + : (entries + .filter( + (entry): entry is [string, string] => + typeof entry[1] === "string" && entry[1].trim().length >= PROSE_LENGTH, + ) + .slice() + .sort((left, right) => right[1].length - left[1].length)[0] ?? null); + return { + said: kept !== "" ? kept : (prose?.[1].trim() ?? null), + facts: entries + .flatMap(([key, value]) => { + const text = factValue(value); + return text === null ? [] : [{ label: words(key), value: text }]; + }) + .slice(0, FACTS_SHOWN), + }; +} + +/** + * The start of what an agent said, cut where a paragraph ends so no markup is left half open. + * Null when all of it fits. + */ +export function workflowSaidStart(said: string, limit: number): string | null { + if (said.length <= limit) return null; + const paragraphs = said.split(/\n{2,}/); + let kept = paragraphs[0]!; + for (const paragraph of paragraphs.slice(1)) { + if (kept.length + paragraph.length + 2 > limit) break; + kept = `${kept}\n\n${paragraph}`; + } + // One paragraph that runs on is cut at a word, which can still split markup but not a word. + if (kept.length > limit * 2) kept = `${kept.slice(0, kept.lastIndexOf(" ", limit))}…`; + return kept === said ? null : kept; +} + +const decodeIssueAddress = Schema.decodeUnknownOption(WorkflowIssueAddress); +const decodePullRequestAddress = Schema.decodeUnknownOption(WorkflowPullRequestAddress); + +/** A reference's issue, when it is one and its address reads as one. */ +export function workflowReferenceIssue(reference: WorkflowRunReference): IssueRef | null { + return reference.kind === WorkflowReferenceKind.issue + ? Option.getOrNull(decodeIssueAddress(reference.address)) + : null; +} + +/** A reference's pull request, when it is one and its address reads as one. */ +export function workflowReferencePullRequest( + reference: WorkflowRunReference, +): PullRequestRef | null { + return reference.kind === WorkflowReferenceKind.pullRequest + ? Option.getOrNull(decodePullRequestAddress(reference.address)) + : null; +} + +/** + * What a reference is called in a chip: `#412` for an issue or pull request on a git host, a + * tracker's own key such as `ENG-12`, and the title for a kind this client does not know. + */ +export function workflowReferenceLabel(reference: WorkflowRunReference): string { + const pullRequest = workflowReferencePullRequest(reference); + if (pullRequest !== null) return `#${pullRequest.number}`; + const issue = workflowReferenceIssue(reference); + if (issue !== null) return /^\d+$/.test(issue.key) ? `#${issue.key}` : issue.key; + return reference.title === "" ? reference.kind : reference.title; +} + +/** The references a step touched, in the order the run first touched them. */ +export function workflowStepReferences( + references: ReadonlyArray, + step: string, +): ReadonlyArray { + return references.filter((reference) => reference.steps.includes(step)); +} + +/** A step's time in one shape down a column: 0.3s, 9.7s, 12s, then minutes. */ +export function workflowStepTime(ms: number): string { + if (ms < 10_000 && ms % 1000 !== 0) return `${(Math.max(ms, 100) / 1000).toFixed(1)}s`; + if (ms < 60_000) return `${Math.round(ms / 1000)}s`; + return formatDuration(ms); +} + +/** + * The first sentence of a reply, as one line of plain text: a heading, list mark, inline code, + * emphasis or link reads as its words. + */ +export function workflowOneLine(text: string): string { + const line = + text + .split("\n") + .map((candidate) => candidate.trim()) + .find((candidate) => candidate !== "" && !/^(#|```|\|)/.test(candidate)) + ?.replace(/^([-*>]|\d+\.)\s+/, "") ?? ""; + const plain = line + .replace(/\[([^\]]*)\]\([^)]*\)/g, "$1") + .replace(/`([^`]*)`/g, "$1") + .replace(/(\*\*|__|\*|_)(\S(?:.*?\S)?)\1/g, "$2"); + const end = plain.search(/[.!?](\s|$)/); + return end === -1 ? plain : plain.slice(0, end + 1); +} From f29c824614c424327ea50abcf945f734db8c130f Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 18:07:10 -0800 Subject: [PATCH 239/324] fix(server): Full access Codex no longer asks before dangerous commands (#40773) --- .../Adapters/CodexAdapterV2.test.ts | 90 +++++++++++++++++++ .../Adapters/CodexAdapterV2.ts | 13 +++ docs/user/permission-modes.md | 4 + 3 files changed, 107 insertions(+) diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index d30748a0df77c..330524c99ad3b 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -2010,6 +2010,96 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); + it.effect.each([ + { name: "dangerous command", networkApprovalContext: undefined, asks: false }, + { + name: "managed-network command", + networkApprovalContext: { host: "example.com", protocol: "https" }, + asks: true, + }, + ] as const)("full access asks about a $name: $asks", ({ networkApprovalContext, asks }) => + Effect.gen(function* () { + const nativeThreadId = "command-approval-thread"; + const nativeTurnId = "command-approval-turn"; + const prompt = "Clean node_modules."; + const pending = yield* Queue.unbounded(); + const harness = yield* makeCodexReplayHarness( + makeCodexReplayTranscript({ + scenario: "full-access-command-approval", + entries: [ + ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt }), + { + type: "emit_inbound", + frame: { + id: 0, + method: "item/commandExecution/requestApproval", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + itemId: "exec-rm", + command: "/bin/bash -lc 'rm -rf ./node_modules'", + startedAtMs: 0, + ...(networkApprovalContext === undefined ? {} : { networkApprovalContext }), + }, + }, + }, + ...(asks + ? [] + : ([ + { type: "expect_outbound", frame: { id: 0, result: { decision: "accept" } } }, + { + type: "emit_inbound", + frame: { + method: "turn/completed", + params: { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }), + }, + }, + }, + ] as const)), + ], + }), + (event) => + event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending" + ? Queue.offer(pending, event.runtimeRequest) + : Effect.void, + ); + const turnInput = makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("command-approval-attempt"), + text: prompt, + }); + yield* harness.runtime.startTurn({ + ...turnInput, + runtimePolicy: { ...turnInput.runtimePolicy, runtimeMode: "full-access" }, + }); + const request = yield* Effect.raceFirst( + harness.firstTerminal.pipe(Effect.as(undefined)), + Queue.take(pending), + ); + assert.equal(request?.kind, asks ? "command" : undefined); + if (!asks) { + assert.deepEqual( + harness.terminalEvents().map((event) => event.status), + ["completed"], + ); + } + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + it.effect.each(["native", "ordinary"] as const)( "resumes Codex without a prompt only for an existing conversation (%s)", (mode) => diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 49c153f30be09..1c38aaebffc80 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -6062,6 +6062,19 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( payload, ); } + // T3's Full access policy is granular, under which Codex still asks before commands it + // deems dangerous. Managed-network asks enforce the user's allowlist, so they still ask. + if ( + context.input.runtimePolicy.runtimeMode === "full-access" && + context.input.runtimePolicy.approvalPolicy === undefined && + context.input.runtimePolicy.sandboxPolicy === undefined && + payload.networkApprovalContext == null && + (payload.proposedNetworkPolicyAmendments ?? []).length === 0 + ) { + return { + decision: "accept", + } satisfies CodexSchema.CommandExecutionRequestApprovalResponse; + } const allowance = sessionAllowance(payload.threadId, context); if (allowance.has("command")) { return { diff --git a/docs/user/permission-modes.md b/docs/user/permission-modes.md index a8f1cf8391221..60c403e31979b 100644 --- a/docs/user/permission-modes.md +++ b/docs/user/permission-modes.md @@ -48,6 +48,10 @@ session-wide choice, because Grok would remember that command for the whole proj ACP Registry agents run their own tools in their own mode; T3 Code answers their approval requests by the permission mode. See [ACP Registry permissions](./providers-acp.md#permissions-and-terminals). +In **Full access**, commands that Codex's dangerous-command check would ask about run without +asking. Codex still asks before network access its managed network settings don't allow, unless +you already allowed commands for the session. + Claude can still ask in **Full access** when its settings disable bypass permissions or require approval for an action. Dangerous-removal safety checks in bypass mode reject the command with the original warning. Claude can use a safe rewrite when the warning supplies one; otherwise it From 2808e878de91aacc7fb82887f18414976be7ae34 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Sun, 22 Nov 2026 20:16:09 -0600 Subject: [PATCH 240/324] fix(usage): skipped-record warnings only count the selected dates (#41157) Co-authored-by: Cursor Co-authored-by: Julius Marminge Co-authored-by: Claude Opus 5.5 --- .../src/provider/Drivers/codexUsage.test.ts | 48 +++++----- .../server/src/provider/Drivers/codexUsage.ts | 21 +++-- apps/server/src/usage/UsageService.test.ts | 94 ++++++++++++++++++- apps/server/src/usage/UsageService.ts | 39 +++++--- apps/server/src/usage/usageAggregation.ts | 16 ++++ apps/server/src/usage/usageScanCache.test.ts | 38 +++++--- apps/server/src/usage/usageScanCache.ts | 30 ++++-- .../src/usage/usageTranscriptReader.test.ts | 20 ++-- .../server/src/usage/usageTranscriptReader.ts | 6 +- packages/provider-core/src/server/usage.ts | 4 +- 10 files changed, 239 insertions(+), 77 deletions(-) diff --git a/apps/server/src/provider/Drivers/codexUsage.test.ts b/apps/server/src/provider/Drivers/codexUsage.test.ts index 1cdbe05d07669..2326b6749f4a6 100644 --- a/apps/server/src/provider/Drivers/codexUsage.test.ts +++ b/apps/server/src/provider/Drivers/codexUsage.test.ts @@ -98,7 +98,7 @@ describe("parseCodexLine", () => { parseCodexLine(line.replace("2026-08-01T05:17:49.919Z", "invalid"), cumulativeState), ).toBeNull(); expect(parseCodexLine(line, cumulativeState)?.totals.outputTokens).toBe(20); - expect(codexUsageFormat.readMalformedRecords?.(cumulativeState)).toBe(0); + expect(codexUsageFormat.readMalformedRecords?.(cumulativeState).length).toBe(0); }); it("ignores stale changed requests but counts equal requests when totals advance across contexts", () => { @@ -141,7 +141,7 @@ describe("parseCodexLine", () => { totals: { uncachedInputTokens: 100, outputTokens: 20 }, }); } - expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0); + expect(codexUsageFormat.readMalformedRecords?.(state).length).toBe(0); }); it.each([false, true])( @@ -160,7 +160,7 @@ describe("parseCodexLine", () => { expect( parseCodexLine(counted(counters(10, 2), counters(130, 27)), state)?.totals.outputTokens, ).toBe(2); - expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0); + expect(codexUsageFormat.readMalformedRecords?.(state).length).toBe(0); }, ); @@ -187,10 +187,10 @@ describe("parseCodexLine", () => { total[field] += 1; if (field === "input_tokens" || field === "output_tokens") total.total_tokens += 1; expect(parseCodexLine(counted(request, total), state), field).toBeNull(); - expect(codexUsageFormat.readMalformedRecords?.(state), field).toBe(1); + expect(codexUsageFormat.readMalformedRecords?.(state).length, field).toBe(1); for (const key of fields) total[key] += request[key]; expect(parseCodexLine(counted(request, total), state)?.totals.outputTokens, field).toBe(20); - expect(codexUsageFormat.readMalformedRecords?.(state), field).toBe(1); + expect(codexUsageFormat.readMalformedRecords?.(state).length, field).toBe(1); } }); @@ -250,7 +250,7 @@ describe("parseCodexLine", () => { state, )?.totals.outputTokens, ).toBe(2); - expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0); + expect(codexUsageFormat.readMalformedRecords?.(state).length).toBe(0); }, ); @@ -307,7 +307,7 @@ describe("parseCodexLine", () => { reasoning_output_tokens: 5, }; expect(parseCodexLine(counted(request, cumulative), state)).toBeNull(); - expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(1); + expect(codexUsageFormat.readMalformedRecords?.(state).length).toBe(1); expect(state.lastCumulativeUsage).toEqual(cumulative); }); @@ -327,14 +327,14 @@ describe("parseCodexLine", () => { state, ), ).toBeNull(); - expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(1); + expect(codexUsageFormat.readMalformedRecords?.(state).length).toBe(1); expect( parseCodexLine( counted(request, malformed === "request" ? counters(300, 60) : counters(200, 40)), state, )?.totals.outputTokens, ).toBe(20); - expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(1); + expect(codexUsageFormat.readMalformedRecords?.(state).length).toBe(1); }); it("bills only the reported request when usage records sit between reconciling snapshots", () => { @@ -520,7 +520,7 @@ describe("parseCodexLine", () => { parseCodexLine(counted(counters(10, 2), { ...counters(10, 2), total_tokens: 1012 }), state) ?.totals.outputTokens, ).toBe(2); - expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0); + expect(codexUsageFormat.readMalformedRecords?.(state).length).toBe(0); }); it.each([false, true])( @@ -536,7 +536,7 @@ describe("parseCodexLine", () => { expect( parseCodexLine(counted(counters(30, 5), counters(30, 5)), state)?.totals.outputTokens, ).toBe(5); - expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0); + expect(codexUsageFormat.readMalformedRecords?.(state).length).toBe(0); }, ); @@ -550,7 +550,7 @@ describe("parseCodexLine", () => { expect( parseCodexLine(counted(counters(10, 2), counters(40, 7)), state)?.totals.outputTokens, ).toBe(2); - expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0); + expect(codexUsageFormat.readMalformedRecords?.(state).length).toBe(0); }); const later = (line: string) => line.replace("05:17:49.919Z", "07:17:49.919Z"); @@ -583,7 +583,10 @@ describe("parseCodexLine", () => { return record === null ? 0 : totalTokens(record.totals); }); - expect({ processed: billed, skipped: codexUsageFormat.readMalformedRecords?.(state) }).toEqual({ + expect({ + processed: billed, + skipped: codexUsageFormat.readMalformedRecords?.(state).length, + }).toEqual({ processed, skipped, }); @@ -675,7 +678,10 @@ describe("parseCodexLine", () => { return record === null ? 0 : totalTokens(record.totals); }); - expect({ processed: billed, skipped: codexUsageFormat.readMalformedRecords?.(state) }).toEqual({ + expect({ + processed: billed, + skipped: codexUsageFormat.readMalformedRecords?.(state).length, + }).toEqual({ processed, skipped, }); @@ -697,7 +703,7 @@ describe("parseCodexLine", () => { expect({ processed, - skipped: codexUsageFormat.readMalformedRecords?.(state), + skipped: codexUsageFormat.readMalformedRecords?.(state).length, }).toEqual({ processed: [120, 120, 0, 120], skipped: 0 }); }); @@ -715,7 +721,7 @@ describe("parseCodexLine", () => { const record = parseCodexLine(line, state); return record === null ? 0 : totalTokens(record.totals); }); - expect({ processed, skipped: codexUsageFormat.readMalformedRecords?.(state) }).toEqual({ + expect({ processed, skipped: codexUsageFormat.readMalformedRecords?.(state).length }).toEqual({ processed: [120, 120, 120, 35], skipped: 0, }); @@ -756,7 +762,7 @@ describe("parseCodexLine", () => { expect({ processed: billed, - skipped: codexUsageFormat.readMalformedRecords?.(state), + skipped: codexUsageFormat.readMalformedRecords?.(state).length, }).toEqual({ processed, skipped: 0 }); }, ); @@ -777,7 +783,7 @@ describe("parseCodexLine", () => { expect({ processed, - skipped: codexUsageFormat.readMalformedRecords?.(state), + skipped: codexUsageFormat.readMalformedRecords?.(state).length, }).toEqual({ processed: [120, 0, 120, 35], skipped: 1 }); }); @@ -917,7 +923,7 @@ describe("parseCodexLine", () => { state, ); expect(next).not.toBeNull(); - expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0); + expect(codexUsageFormat.readMalformedRecords?.(state).length).toBe(0); }); it("recognizes subagent spawns without forked_from_id", () => { @@ -968,7 +974,7 @@ describe("parseCodexLine", () => { expect({ processed: [first, copied, afterBurst, next], - skipped: codexUsageFormat.readMalformedRecords?.(state), + skipped: codexUsageFormat.readMalformedRecords?.(state).length, }).toEqual({ processed: [120, 0, 120, 35], skipped: 0 }); }); @@ -989,7 +995,7 @@ describe("parseCodexLine", () => { expect({ processed: billed.map((record) => totalTokens(record.totals)), - skipped: codexUsageFormat.readMalformedRecords?.(state), + skipped: codexUsageFormat.readMalformedRecords?.(state).length, }).toEqual({ processed: [160, 230], skipped: 0 }); }); }); diff --git a/apps/server/src/provider/Drivers/codexUsage.ts b/apps/server/src/provider/Drivers/codexUsage.ts index a2977d3080fee..7fafc555aac56 100644 --- a/apps/server/src/provider/Drivers/codexUsage.ts +++ b/apps/server/src/provider/Drivers/codexUsage.ts @@ -148,6 +148,9 @@ export const CodexScanState = Schema.Struct({ ), requestLedgerActive: Schema.mutableKey(Schema.optionalKey(Schema.Boolean)), malformedRecords: Schema.mutableKey(TokenCount), + malformedRecordTimestamps: Schema.mutableKey( + Schema.optionalKey(Schema.mutable(Schema.Array(Schema.Finite))), + ), sawSessionMeta: Schema.mutableKey(Schema.Boolean), modelProvider: Schema.mutableKey(Schema.String), turnId: Schema.mutableKey(Schema.String), @@ -331,7 +334,7 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): readonly Usag // A valid snapshot remains the next baseline even when its paired request is malformed. if (cumulative !== null) rebaseCodexUsage(state, cumulative, timestampMs); if (last === null || (hasCumulative && cumulative === null)) { - state.malformedRecords += 1; + noteMalformedRecord(state, timestampMs); return []; } @@ -351,7 +354,7 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): readonly Usag } if (last.total_tokens !== last.input_tokens + last.output_tokens) { - state.malformedRecords += 1; + noteMalformedRecord(state, timestampMs); return []; } @@ -397,12 +400,12 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): readonly Usag state.lastCumulativeUsage = previous; if (pending !== undefined) state.unreportedRequests = pending; } - state.malformedRecords += 1; + noteMalformedRecord(state, timestampMs); return []; } unreported = bridged; } else if (!restarted && rewound) { - state.malformedRecords += discardedRequests(pending, last); + noteMalformedRecord(state, timestampMs, discardedRequests(pending, last)); } if (restarted) state.sequenceStartSignature = sequenceStart; } else { @@ -410,7 +413,7 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): readonly Usag // Advance expected totals for billed legacy requests so a cumulative re-emission is stale. const advanced = advanceCodexUsage(previous, last); if (advanced === null) { - state.malformedRecords += 1; + noteMalformedRecord(state, timestampMs); return []; } state.lastCumulativeUsage = advanced; @@ -424,6 +427,12 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): readonly Usag ]; } +function noteMalformedRecord(state: CodexScanState, timestampMs: number, count = 1) { + state.malformedRecords += count; + const timestamps = (state.malformedRecordTimestamps ??= []); + for (let index = 0; index < count; index++) timestamps.push(timestampMs); +} + function codexAttribution(state: CodexScanState, timestampMs: number): CodexRequestAttribution { return { timestampMs, @@ -509,7 +518,7 @@ export const codexUsageFormat: TranscriptUsageFormat = { parseLine: parseCodexLine, parseProjected: parseCodexRecord, state: { initial: initialCodexScanState, schema: CodexScanState }, - readMalformedRecords: (state) => state.malformedRecords, + readMalformedRecords: (state) => state.malformedRecordTimestamps ?? [], // A rollout that moved after it was read leaves a copy in both places. sharedSessionsAcrossFiles: true, }; diff --git a/apps/server/src/usage/UsageService.test.ts b/apps/server/src/usage/UsageService.test.ts index 237f0740c7d19..d2bc0c296fbc1 100644 --- a/apps/server/src/usage/UsageService.test.ts +++ b/apps/server/src/usage/UsageService.test.ts @@ -3298,6 +3298,72 @@ describe("UsageService", () => { }), ); + it.effect("limits cached transcript work and diagnostics to the requested dates", () => + Effect.gen(function* () { + const { home, settings } = yield* setup; + const dir = NodePath.join(home, "codex", "sessions"); + const transcript = NodePath.join(dir, "rollout.jsonl"); + const line = (timestamp: string, input: number, total: number) => + JSON.stringify({ + type: "event_msg", + timestamp, + payload: { + type: "token_count", + info: { + last_token_usage: { input_tokens: input, output_tokens: 1 }, + total_token_usage: { input_tokens: total, output_tokens: total / 10 }, + }, + }, + }); + yield* Effect.promise(async () => { + await NodeFSP.mkdir(dir, { recursive: true }); + await NodeFSP.writeFile( + transcript, + [ + JSON.stringify({ type: "turn_context", payload: { model: "gpt-6-astra" } }), + line("2026-08-01T10:00:00Z", 10, 10), + line("2026-08-01T11:00:00Z", 10, 40), + ].join("\n") + "\n", + ); + }); + yield* Effect.gen(function* () { + const first = yield* UsageService.make; + const source = (summary: UsageSummary) => + summary.sources.find((s) => s.fingerprint.provider === "codex")!; + assert.strictEqual(source(yield* first.readSummary(WINDOW)).malformedRecords, 1); + const hour = { + ...WINDOW, + resolution: "hour" as const, + sinceTime: "2026-08-01T10:00:00Z", + untilTime: "2026-08-01T11:00:00Z", + }; + assert.strictEqual(source(yield* first.readSummary(hour)).malformedRecords, 0); + + yield* first.awaitPersisted; + const restarted = yield* UsageService.make; + const nextDay = { + ...WINDOW, + sinceDay: UsageDay.make("2026-08-02"), + untilDay: UsageDay.make("2026-08-02"), + }; + const outside = source(yield* restarted.readSummary(nextDay)); + assert.strictEqual(outside.malformedRecords, 0); + assert.strictEqual(outside.scannedFiles, 0); + assert.strictEqual(outside.message, null); + yield* Effect.promise(() => + NodeFSP.appendFile(transcript, line("2026-08-02T10:00:00Z", 10, 10)), + ); + const mixed = yield* restarted.readSummary(nextDay); + assert.strictEqual(totalOutputTokens(mixed), 1); + assert.strictEqual(source(mixed).malformedRecords, 0); + yield* restarted.awaitPersisted; + const saved = yield* UsageService.make; + assert.strictEqual(source(yield* saved.readSummary(nextDay)).malformedRecords, 0); + assert.strictEqual(source(yield* saved.readSummary(WINDOW)).malformedRecords, 1); + }).pipe(Effect.provide(layerService({ prefix: "usage-window-diagnostics", home, settings }))); + }), + ); + it.effect( "merges partial Claude copies through tail replacement, newline completion and restart", () => @@ -3892,6 +3958,32 @@ describe("UsageService", () => { }), ); + it.effect("leaves a duplicate uncounted when its first copy is before the window", () => + Effect.gen(function* () { + const { transcript, settings, home } = yield* setup; + const dir = NodePath.dirname(transcript); + yield* Effect.promise(async () => { + await NodeFSP.writeFile(NodePath.join(dir, "a.jsonl"), ""); + await NodeFSP.writeFile(NodePath.join(dir, "b.jsonl"), ""); + const [first = "", second = ""] = (await NodeFSP.readdir(dir)).map((name) => + NodePath.join(dir, name), + ); + const nextDay = (line: string) => line.replace("2026-08-01", "2026-08-02"); + await NodeFSP.writeFile(first, claudeLine(1, 5)); + await NodeFSP.writeFile(second, nextDay(claudeLine(1, 5)) + nextDay(claudeLine(2, 7))); + }); + yield* Effect.gen(function* () { + const summary = yield* (yield* UsageService.make).readSummary({ + ...WINDOW, + sinceDay: UsageDay.make("2026-08-02"), + }); + assert.strictEqual(totalOutputTokens(summary), 7); + }).pipe( + Effect.provide(layerService({ prefix: "usage-service-early-copy-test", home, settings })), + ); + }), + ); + it.effect("credits the same copy of a duplicate from the last scan as an exact read does", () => Effect.gen(function* () { yield* TestClock.setTime(Date.parse("2026-08-15T00:00:00Z")); @@ -4002,7 +4094,7 @@ describe("UsageService", () => { provider: "claude" as const, records: [], tailRecords: [], - malformedRecords: 2, + malformedRecords: [mtimeMs, mtimeMs], position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }, }, ], diff --git a/apps/server/src/usage/UsageService.ts b/apps/server/src/usage/UsageService.ts index 30edc903a580f..3ff2004266651 100644 --- a/apps/server/src/usage/UsageService.ts +++ b/apps/server/src/usage/UsageService.ts @@ -39,7 +39,12 @@ import type { TranscriptUsageFormat, UsageRecord, } from "@t3tools/provider-core/server/usage"; -import { canonicalModelFilter, resolveModelAliases, UsageAggregator } from "./usageAggregation.ts"; +import { + canonicalModelFilter, + resolveModelAliases, + usageTimestampFilter, + UsageAggregator, +} from "./usageAggregation.ts"; import { createOverrideRateTable, isUnlistedModel, @@ -419,7 +424,8 @@ export const make = Effect.gen(function* () { ([filePath, entry]) => entry.provider === provider && entry.mtimeMs >= retentionCutoffMs && - (entry.records.length + entry.tailRecords.length > 0 || entry.malformedRecords > 0) && + (entry.records.length + entry.tailRecords.length > 0 || + entry.malformedRecords.length > 0) && isWithinDirectory(filePath, dir), ); const volumeId = @@ -564,7 +570,7 @@ export const make = Effect.gen(function* () { format: TranscriptUsageFormat, ): Effect.fn.Return<{ readonly records: readonly UsageRecord[]; - readonly malformedRecords: number; + readonly malformedRecords: readonly number[]; readonly failed?: true; readonly update?: { readonly entry: CachedFile; readonly replaces: CachedFile | undefined }; }> { @@ -599,7 +605,7 @@ export const make = Effect.gen(function* () { if (parsed === null) return { records: cached?.provider === provider ? [...cached.records, ...cached.tailRecords] : [], - malformedRecords: cached?.provider === provider ? cached.malformedRecords : 0, + malformedRecords: cached?.provider === provider ? cached.malformedRecords : [], failed: true, }; @@ -687,7 +693,7 @@ export const make = Effect.gen(function* () { | readonly { readonly path: string; readonly records: readonly UsageRecord[]; - readonly malformedRecords: number; + readonly malformedRecords: readonly number[]; }[] | null; /** Every transcript path the walk listed, in walk order, whatever its mtime. */ @@ -800,7 +806,7 @@ export const make = Effect.gen(function* () { : Effect.succeed<[string, string | undefined]>([volumeId, undefined]), ([resolved, sourceId]): ScannedDir => ({ ...source, - files: source.files?.map((file) => ({ ...file, malformedRecords: 0 })) ?? null, + files: source.files?.map((file) => ({ ...file, malformedRecords: [] })) ?? null, provider: reader.provider, volumeId: resolved, ...(sourceId === undefined ? {} : { physicalSourceId: sourceId }), @@ -876,6 +882,11 @@ export const make = Effect.gen(function* () { ? 0 : Math.max(0, startedAtMs - settings.usageHistoryRetentionDays * 24 * 60 * 60 * 1000); + const inWindow = usageTimestampFilter({ ...input, ...hourlyWindow }); + const windowEndMs = + hourlyWindow?.untilTimeMs ?? + Date.parse(`${input.untilDay}T00:00:00Z`) + 86400000 + MTIME_SLACK_MS; + const awaitRefresh = input.awaitRefresh === true; const collect = Effect.gen(function* () { const resolved = yield* resolveTranscriptDirs(settings, retentionCutoffMs, awaitRefresh).pipe( @@ -951,7 +962,16 @@ export const make = Effect.gen(function* () { malformedRecords: entry.malformedRecords, }); } - return retainedFiles; + return retainedFiles.flatMap((file) => { + // A keyed copy outside the window still claims its key, so a later copy is not counted. + const records = file.records.filter( + (record) => record.dedupeKey !== null || inWindow(record.timestampMs), + ); + const malformedRecords = file.malformedRecords.filter(inWindow); + return records.length === 0 && malformedRecords.length === 0 + ? [] + : [{ ...file, records, malformedRecords }]; + }); }); // Usage two transcripts share counts in the first one, so saved files take the order an exact // scan reads them in: walked files in walk order, then the directory's deleted files. @@ -1009,9 +1029,6 @@ export const make = Effect.gen(function* () { ...(input.modelFilter === undefined ? {} : { modelFilter: input.modelFilter }), }); - const windowEndMs = - hourlyWindow?.untilTimeMs ?? - Date.parse(`${input.untilDay}T00:00:00Z`) + 86400000 + MTIME_SLACK_MS; let resolvedAny = false; for (const { reader } of transcriptReaders) { if (reader.resolveServiceTiers === undefined || fromMemory) continue; @@ -1077,7 +1094,7 @@ export const make = Effect.gen(function* () { let counted = false; for (const file of filesByDir[index] ?? []) { - malformedRecords += file.malformedRecords; + malformedRecords += file.malformedRecords.length; if (file.records.length === 0) { skippedFiles += 1; continue; diff --git a/apps/server/src/usage/usageAggregation.ts b/apps/server/src/usage/usageAggregation.ts index f4c39753548fd..9ba0a22fd7a32 100644 --- a/apps/server/src/usage/usageAggregation.ts +++ b/apps/server/src/usage/usageAggregation.ts @@ -77,6 +77,22 @@ export interface AggregateOptions { readonly untilTimeMs?: number; } +export function usageTimestampFilter( + options: Pick< + AggregateOptions, + "timeZone" | "sinceDay" | "untilDay" | "sinceTimeMs" | "untilTimeMs" + >, +) { + const toDay = makeDayFormatter(options.timeZone); + return (timestampMs: number) => { + if (options.sinceTimeMs !== undefined && options.untilTimeMs !== undefined) { + return timestampMs >= options.sinceTimeMs && timestampMs < options.untilTimeMs; + } + const day = toDay(timestampMs); + return day >= options.sinceDay && day <= options.untilDay; + }; +} + export function resolveModelAliases( aliases: Readonly>, ): ReadonlyMap { diff --git a/apps/server/src/usage/usageScanCache.test.ts b/apps/server/src/usage/usageScanCache.test.ts index 36864768eb525..6acc49e0657cf 100644 --- a/apps/server/src/usage/usageScanCache.test.ts +++ b/apps/server/src/usage/usageScanCache.test.ts @@ -52,7 +52,7 @@ function cacheWith(entries: readonly [string, number, readonly UsageRecord[]][]) provider: "claude", records, tailRecords: [], - malformedRecords: 0, + malformedRecords: [], position: position(), }); } @@ -95,7 +95,7 @@ describe("scan cache round trip", () => { ]); original.set("/grok.jsonl", { size: 40, - malformedRecords: 2, + malformedRecords: [1, 2], mtimeMs: 300, provider: "grok", records: [ @@ -131,7 +131,7 @@ describe("scan cache round trip", () => { const pendingTail = { ...pending, unresolvedServiceTierTurnId: "native-tail" }; original.set("/codex.jsonl", { size: 80, - malformedRecords: 3, + malformedRecords: [1, 2, 3], mtimeMs: 400, provider: "codex", records: [ @@ -166,6 +166,16 @@ describe("scan cache round trip", () => { expect(restored.size).toBe(4); expect(restored).toEqual(original); + const encoded = parse(makeScanCacheWriter()(original, {})); + const { mt: _dates, ...undated } = encoded.files["/codex.jsonl"]!; + const reparsed = decodeScanCache( + { ...encoded, files: { ...encoded.files, "/codex.jsonl": undated } }, + TEST_FORMAT_MAP, + ).get("/codex.jsonl")!; + expect(reparsed.size).toBe(-1); + expect(reparsed.position.resumeOffset).toBe(0); + expect(reparsed.records).toEqual(original.get("/codex.jsonl")!.records); + expect(reparsed.malformedRecords).toEqual([]); }); it.each([5, 6, 7, 8, 10, 11, 12, 13])( @@ -175,7 +185,7 @@ describe("scan cache round trip", () => { original.set("/gone-codex.jsonl", { ...original.get("/gone.jsonl")!, provider: "codex", - malformedRecords: 1, + malformedRecords: [1], records: [record({ provider: "codex", speed: "fast", dedupeKey: null })], position: position({ state: { @@ -195,12 +205,12 @@ describe("scan cache round trip", () => { size: 256, provider: "pi", records: [record({ provider: "pi", model: "anthropic/claude-fable-5" })], - malformedRecords: 3, + malformedRecords: [1, 2, 3], position: position({ state: { sessionId: "session-a" } }), }); const cleanCodex = { ...original.get("/gone-codex.jsonl")!, - malformedRecords: 0, + malformedRecords: [], }; original.set("/clean-codex.jsonl", cleanCodex); const encoded = parse(makeScanCacheWriter()(original, {})); @@ -257,7 +267,7 @@ describe("scan cache round trip", () => { ); it("re-parses a v14 Codex entry that skipped records and restarts a clean one when it grows", () => { - const codex = (malformedRecords: number): CachedFile => ({ + const codex = (malformedRecords: readonly number[]): CachedFile => ({ size: 10, mtimeMs: 100, provider: "codex", @@ -269,20 +279,20 @@ describe("scan cache round trip", () => { }), }); const original: ScanCache = new Map([ - ["/skipped-codex.jsonl", codex(1)], - ["/clean-codex.jsonl", codex(0)], + ["/skipped-codex.jsonl", codex([1])], + ["/clean-codex.jsonl", codex([])], ]); const v14 = { ...parse(makeScanCacheWriter()(original, {})), version: 14 }; const restored = decodeScanCache(JSON.parse(JSON.stringify(v14)), TEST_FORMAT_MAP); expect(restored.get("/skipped-codex.jsonl")).toEqual({ - ...codex(1), + ...codex([1]), size: -1, position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }, }); // Served while unchanged, but its state predates the latest snapshot time, so it cannot resume. expect(restored.get("/clean-codex.jsonl")).toEqual({ - ...codex(0), + ...codex([]), position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }, }); // The migrated entries persist without a state and load again under the current version. @@ -306,7 +316,7 @@ describe("scan cache round trip", () => { provider: "codex", records: [record({ provider: "codex", model: "gpt-6-astra", dedupeKey: null })], tailRecords: [], - malformedRecords: 0, + malformedRecords: [], position: position({ state: { ...initialCodexScanState(), @@ -368,14 +378,14 @@ describe("scan cache round trip", () => { ["/a.jsonl", 100, [record()]], ["/b.jsonl", 200, [record({ sessionId: "session-b" })]], ]); - cache.set("/b.jsonl", { ...cache.get("/b.jsonl")!, malformedRecords: 2 }); + cache.set("/b.jsonl", { ...cache.get("/b.jsonl")!, malformedRecords: [1, 2] }); const sources = { "claude\u0000/projects": { dir: "/projects", volumeId: "1:2" } }; expect(decodeScanCache(parse(write(cache, { sources })), TEST_FORMAT_MAP)).toEqual(cache); cache.set("/b.jsonl", { ...cache.get("/b.jsonl")!, size: 30, - malformedRecords: 4, + malformedRecords: [1, 2, 3, 4], records: [record({ sessionId: "session-c", model: "claude-opus-5-5", dedupeKey: "msg_3:" })], }); const document = parse(write(cache, { sources })); diff --git a/apps/server/src/usage/usageScanCache.ts b/apps/server/src/usage/usageScanCache.ts index 843b414b97f32..cc6068b72f164 100644 --- a/apps/server/src/usage/usageScanCache.ts +++ b/apps/server/src/usage/usageScanCache.ts @@ -44,8 +44,8 @@ export interface CachedFile { readonly records: readonly UsageRecord[]; /** Unterminated tail records stay separate because incremental parsing rereads them. */ readonly tailRecords: readonly UsageRecord[]; - /** Whole-file count, including diagnostics from the tentative tail. */ - readonly malformedRecords: number; + /** Whole-file timestamps, including diagnostics from the tentative tail. */ + readonly malformedRecords: readonly number[]; readonly position: TranscriptParsePosition; } @@ -75,6 +75,7 @@ interface SerializedFile { readonly r: readonly SerializedRecord[]; readonly t: readonly SerializedRecord[]; readonly mr: number; + readonly mt?: readonly number[]; readonly o: number; readonly gl: number; readonly gh: number; @@ -136,7 +137,8 @@ function serializeFile(entry: CachedFile, tables: InternTables): SerializedFile p: entry.provider, r: entry.records.map(serializeRecord), t: entry.tailRecords.map(serializeRecord), - mr: entry.malformedRecords, + mr: entry.malformedRecords.length, + ...(entry.malformedRecords.length === 0 ? {} : { mt: entry.malformedRecords }), o: entry.position.resumeOffset, gl: entry.position.guardLength, gh: entry.position.guardHash, @@ -288,8 +290,18 @@ export function decodeScanCache( const format = formats.get(entry.p); if (format === undefined) continue; if (!isRecordArray(entry.r) || !isRecordArray(entry.t)) continue; - const malformedRecords = entry.mr === undefined ? 0 : entry.mr; - if (!Number.isSafeInteger(malformedRecords) || malformedRecords < 0) continue; + const malformedCount = entry.mr === undefined ? 0 : entry.mr; + if (!Number.isSafeInteger(malformedCount) || malformedCount < 0) continue; + const malformedRecords = entry.mt ?? (malformedCount === 0 ? [] : undefined); + if ( + malformedRecords !== undefined && + (!Array.isArray(malformedRecords) || + malformedRecords.length !== malformedCount || + !malformedRecords.every(Number.isFinite)) + ) + continue; + // A count saved without dates cannot be limited to a window, so the file re-parses whole. + const undated = malformedRecords === undefined; // Position fields feed byte offsets and a Buffer allocation in the reader, // so anything outside their real ranges must reject the entry: a bogus // guard length would otherwise fail every parse of the file, silently @@ -317,14 +329,14 @@ export function decodeScanCache( (entry.p === "grok" && version < 17) || (format.state !== undefined && (version < 6 || - (entry.p === "codex" && (version < 14 || (version < 15 && malformedRecords > 0))))); + (entry.p === "codex" && (version < 14 || (version < 15 && malformedCount > 0))))); // A corrupt state disqualifies the entry: resuming with it would attach // appended usage to the wrong model or replay fork-copied history. if (!legacy && !isValidState.get(entry.p)?.(entry.cs)) continue; // Before v16 a Codex baseline can lack the time of its latest move, or carry an older one, // and that time keeps a re-emitted older snapshot from billing twice. A grown file re-parses // whole instead of resuming. - const resumable = !legacy && !(entry.p === "codex" && version < 16); + const resumable = !legacy && !undated && !(entry.p === "codex" && version < 16); const provider = entry.p; const records = decodeRecords(entry.r, provider); @@ -332,12 +344,12 @@ export function decodeScanCache( if (records === null || tailRecords === null) continue; cache.set(path, { - size: legacy ? -1 : entry.s, + size: legacy || undated ? -1 : entry.s, mtimeMs: entry.m, provider, records, tailRecords, - malformedRecords, + malformedRecords: malformedRecords ?? [], position: resumable ? { resumeOffset: entry.o, diff --git a/apps/server/src/usage/usageTranscriptReader.test.ts b/apps/server/src/usage/usageTranscriptReader.test.ts index ca994dd3ac5b2..1896991a9b835 100644 --- a/apps/server/src/usage/usageTranscriptReader.test.ts +++ b/apps/server/src/usage/usageTranscriptReader.test.ts @@ -162,8 +162,8 @@ describe("compressed transcripts", () => { assert.strictEqual(expected.tailRecords.length, 1); assert.deepStrictEqual(actual.records, expected.records); assert.deepStrictEqual(actual.tailRecords, expected.tailRecords); - assert.strictEqual(expected.malformedRecords, 1); - assert.strictEqual(actual.malformedRecords, expected.malformedRecords); + assert.strictEqual(expected.malformedRecords.length, 1); + assert.deepStrictEqual(actual.malformedRecords, expected.malformedRecords); assert.strictEqual(actual.records[0]?.speed, "ultrafast"); assert.isFalse(actual.resumed); assert.strictEqual(actual.position.resumeOffset, 0); @@ -226,7 +226,7 @@ describe("readTranscriptRecords resume", () => { } return TEST_FORMATS.claude.parseProjected(value, undefined); }, - readMalformedRecords: (state: { errors: number }) => state.errors, + readMalformedRecords: (state: { errors: number }) => Array(state.errors).fill(0), }; const path = NodePath.join(dir, "diagnostics.jsonl"); const malformed = JSON.stringify({ usage: "malformed" }); @@ -243,7 +243,7 @@ describe("readTranscriptRecords resume", () => { assert.deepStrictEqual(first.tailRecords, []); assert.strictEqual(first.position.resumeOffset, Buffer.byteLength(committed)); assert.deepStrictEqual(first.position.state, { errors: 1 }); - assert.strictEqual(first.malformedRecords, 2); + assert.strictEqual(first.malformedRecords.length, 2); const savedPosition = JSON.parse(JSON.stringify(first.position)); await NodeFSP.appendFile(path, `\n${claudeLine(2, 7)}${malformed}\n`); @@ -255,14 +255,14 @@ describe("readTranscriptRecords resume", () => { [7], ); assert.deepStrictEqual(resumed.position.state, { errors: 3 }); - assert.strictEqual(resumed.malformedRecords, 3); + assert.strictEqual(resumed.malformedRecords.length, 3); const full = await readTranscriptRecords(path, format, undefined, options); assert.isNotNull(full); assert.deepStrictEqual([...first.records, ...resumed.records], full.records); assert.deepStrictEqual(resumed.tailRecords, full.tailRecords); assert.deepStrictEqual(resumed.position, full.position); - assert.strictEqual(resumed.malformedRecords, full.malformedRecords); + assert.deepStrictEqual(resumed.malformedRecords, full.malformedRecords); }); it("parses only appended lines when resuming a grown file", async () => { @@ -272,7 +272,7 @@ describe("readTranscriptRecords resume", () => { assert.isNotNull(first); assert.strictEqual(first.records.length, 2); assert.isFalse(first.resumed); - assert.strictEqual(first.malformedRecords, 0); + assert.deepStrictEqual(first.malformedRecords, []); await NodeFSP.appendFile(path, claudeLine(3, 11)); const second = await readTranscriptRecords(path, TEST_FORMATS.claude, first.position); @@ -380,7 +380,7 @@ describe("readTranscriptRecords resume", () => { first.tailRecords.map((r) => [r.totals.outputTokens, r.speed]), [[20, "ultrafast"]], ); - assert.strictEqual(first.malformedRecords, 0); + assert.deepStrictEqual(first.malformedRecords, []); await NodeFSP.appendFile(path, `\n${firstLine}\n${event(usage(10, 2), usage(510, 62))}\n`); const resumed = await readTranscriptRecords( @@ -402,7 +402,7 @@ describe("readTranscriptRecords resume", () => { ], ); assert.deepStrictEqual(resumed.tailRecords, []); - assert.strictEqual(resumed.malformedRecords, 0); + assert.deepStrictEqual(resumed.malformedRecords, []); assert.deepStrictEqual(resumed.position, full.position); }, ); @@ -476,7 +476,7 @@ describe("readTranscriptRecords resume", () => { { billedTokens: requests.reduce((sum, tokens) => sum + tokens, 0), requests, - malformedRecords: result.malformedRecords, + malformedRecords: result.malformedRecords.length, }, { billedTokens: 510, requests: [120, 160, 230], malformedRecords: 0 }, ); diff --git a/apps/server/src/usage/usageTranscriptReader.ts b/apps/server/src/usage/usageTranscriptReader.ts index 43597513e5240..263f6701a47c0 100644 --- a/apps/server/src/usage/usageTranscriptReader.ts +++ b/apps/server/src/usage/usageTranscriptReader.ts @@ -36,8 +36,8 @@ export interface TranscriptParseResult { readonly records: readonly UsageRecord[]; /** Unterminated tail records stay outside records/position so the next scan rereads them. */ readonly tailRecords: readonly UsageRecord[]; - /** Includes tentative tail diagnostics; position.state only includes committed lines. */ - readonly malformedRecords: number; + /** Timestamps, including tentative tail diagnostics; position.state only includes committed lines. */ + readonly malformedRecords: readonly number[]; readonly position: TranscriptParsePosition; readonly resumed: boolean; } @@ -464,7 +464,7 @@ export async function readTranscriptRecords( return { records, tailRecords, - malformedRecords: format.readMalformedRecords?.(tailState) ?? 0, + malformedRecords: format.readMalformedRecords?.(tailState) ?? [], position: { resumeOffset: compressed ? 0 : resumeOffset, guardLength, diff --git a/packages/provider-core/src/server/usage.ts b/packages/provider-core/src/server/usage.ts index ff4c14dfefe00..260f160421f33 100644 --- a/packages/provider-core/src/server/usage.ts +++ b/packages/provider-core/src/server/usage.ts @@ -62,8 +62,8 @@ export interface TranscriptUsageFormat { readonly usageMarkers: readonly [string, ...string[]]; parseLine(line: string, state: State): readonly UsageRecord[]; parseProjected(projected: unknown, state: State): readonly UsageRecord[]; - /** Cumulative malformed or inconsistent usage records, including skipped records. */ - readMalformedRecords?(state: State): number; + /** Timestamps of malformed or inconsistent usage records, including skipped records. */ + readMalformedRecords?(state: State): readonly number[]; /** * Present for formats whose records depend on earlier lines. The state at a * resume point is persisted in the scan cache through `schema`, so a grown From 8cc8bcbf6b4041cadffb54f627a6476ee87ef819 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 18:55:40 -0800 Subject: [PATCH 241/324] feat(server): outside agents receive milestones by MCP Events webhooks (#41141) --- apps/server/src/mcp/McpHttpServer.ts | 53 +- .../src/mcp/McpWebhookTransport.test.ts | 66 + apps/server/src/mcp/McpWebhookTransport.ts | 127 ++ .../src/milestones/MilestoneEvents.test.ts | 501 ++++- apps/server/src/milestones/MilestoneEvents.ts | 116 +- docs/user/outside-agents.md | 21 +- patches/effect@4.1.5.patch | 1723 ++++++++++++++++- pnpm-lock.yaml | 518 ++--- 8 files changed, 2752 insertions(+), 373 deletions(-) create mode 100644 apps/server/src/mcp/McpWebhookTransport.test.ts create mode 100644 apps/server/src/mcp/McpWebhookTransport.ts diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index 5bf97d42a2461..ab1f7b003c566 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -55,6 +55,7 @@ import { advertisedJsonSchema } from "./advertisedJsonSchema.ts"; import * as McpInvocationContext from "./McpInvocationContext.ts"; import * as McpToolAccess from "./McpToolAccess.ts"; import * as McpToolExposure from "./McpToolExposure.ts"; +import * as McpWebhookTransport from "./McpWebhookTransport.ts"; import { MCP_TOOL_EXPOSURE_HEADER } from "@t3tools/provider-core/server/mcpSession"; import * as OrchestratorMcpService from "./OrchestratorMcpService.ts"; import { PreviewControlsToolkit } from "./toolkits/previewControls/tools.ts"; @@ -296,14 +297,17 @@ const makeMcpAuthMiddleware = Effect.gen(function* () { const pullRequests = yield* Effect.serviceOption(PullRequestService.PullRequestService); const projections = yield* Effect.serviceOption(ProjectionStore.ProjectionStoreV2); const sessions = yield* Effect.serviceOption(SessionStore.SessionStore); - // Auth runs once per request, so a response that streams on, such as `events/stream`, ends - // when the outside client's session is revoked or expires. + // Auth runs once per request, so a response that streams on ends when the outside client's + // session is revoked or expires. `events/stream` ends itself first with + // `notifications/events/terminated`, which cutting the body here would lose. const endWithSession = ( response: HttpServerResponse.HttpServerResponse, + request: HttpServerRequest.HttpServerRequest, client: McpInvocationContext.McpClientCaller | undefined, ) => { const body = response.body; if (client === undefined || Option.isNone(sessions) || body._tag !== "Stream") return response; + if (request.headers["mcp-method"] === "events/stream") return response; const invalidated = sessions.value .awaitInvalidation(AuthSessionId.make(client.sessionId)) .pipe(Effect.ignore); @@ -389,7 +393,7 @@ const makeMcpAuthMiddleware = Effect.gen(function* () { return yield* httpEffect.pipe( Effect.provideService(McpInvocationContext.McpInvocationContext, admitted), Effect.map(normalizeMcpHttpResponse), - Effect.map((response) => endWithSession(response, admitted.client)), + Effect.map((response) => endWithSession(response, request, admitted.client)), Effect.map((response) => linkExpiresAt === undefined ? response @@ -1499,8 +1503,44 @@ export const layerToolSearch = Layer.mergeAll( ).pipe(Layer.provide(layerToolExposure)); /** - * Milestones as MCP events (SEP-3415) for outside clients to poll or stream. Protocol-level, so no - * thread lists them. + * A webhook subscription belongs to the outside client's session. Its id is the same for the + * session's whole life, and a client signs in again rather than refreshing a token, so a new + * sign-in is a new principal whose subscriptions the old session's end does not touch. + */ +const webhookPrincipal = Effect.serviceOption(McpInvocationContext.McpInvocationContext).pipe( + Effect.flatMap((scope) => { + const client = Option.getOrUndefined(scope)?.client; + return client === undefined + ? Effect.fail( + new McpSchema.Forbidden({ + message: "Webhook delivery needs an outside client's sign-in", + }), + ) + : Effect.succeed(client.sessionId); + }), +); + +/** Webhooks reach public addresses only, through a client pinned to the address it checked. */ +const layerWebhookTransport = Layer.unwrap( + Effect.gen(function* () { + const transport = McpWebhookTransport.make(yield* McpWebhookTransport.allowedHosts); + return Layer.merge( + Layer.succeed(McpServer.CallbackGuard, { + allowsPlaintext: transport.allowsPlaintext, + check: Effect.fn("McpHttpServer.webhookCallbackCheck")(function* (url: URL) { + return yield* transport + .check(url) + .pipe(Effect.mapError((error) => new McpServer.CallbackRejected(error))); + }), + }), + transport.layerClient, + ); + }).pipe(Effect.orDie), +); + +/** + * Milestones as MCP events (SEP-3415) for outside clients to poll, stream or receive by webhook. + * Protocol-level, so no thread lists them. */ export const layerMilestoneEvents = Layer.effectDiscard( Effect.gen(function* () { @@ -1513,6 +1553,9 @@ export const layerMilestoneEvents = Layer.effectDiscard( yield* McpServer.registerEvent({ ...options, annotations }); } }), +).pipe( + Layer.provide(McpServer.layerEventWebhooks({ principal: webhookPrincipal })), + Layer.provide(layerWebhookTransport), ); export const layer = layerMcpTransport( diff --git a/apps/server/src/mcp/McpWebhookTransport.test.ts b/apps/server/src/mcp/McpWebhookTransport.test.ts new file mode 100644 index 0000000000000..0afbfa0b8c5c7 --- /dev/null +++ b/apps/server/src/mcp/McpWebhookTransport.test.ts @@ -0,0 +1,66 @@ +import { NodeHttpServer } from "@effect/platform-node"; +import { expect, it } from "@effect/vitest"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import { HttpClient, HttpRouter, HttpServer, HttpServerResponse } from "effect/http"; + +import * as McpWebhookTransport from "./McpWebhookTransport.ts"; + +it.each([ + ["127.0.0.1", false], + ["10.1.2.3", false], + ["172.16.0.1", false], + ["192.168.1.1", false], + ["169.254.169.254", false], + ["100.64.0.1", false], + ["0.0.0.0", false], + ["::1", false], + ["fc00::1", false], + ["fe80::1", false], + ["::ffff:127.0.0.1", false], + ["fec0::1", false], + ["5f00::1", false], + ["::ffff:0:102:304", false], + ["8.8.8.8", true], + ["2606:4700:4700::1111", true], +])("treats %s as globally routable: %s", (address, routable) => { + expect(McpWebhookTransport.isGloballyRoutable(address)).toBe(routable); +}); + +it.effect("refuses private callbacks unless allowlisted, and the client never reaches them", () => + Effect.gen(function* () { + yield* HttpRouter.serve( + Layer.mergeAll( + HttpRouter.add("POST", "/redirect", HttpServerResponse.redirect("/target")), + HttpRouter.add("POST", "/target", HttpServerResponse.text("reached")), + ), + { disableListenLog: true, disableLogger: true }, + ).pipe(Layer.build); + const port = new URL(HttpServer.formatAddress((yield* HttpServer.HttpServer).address)).port; + const guard = McpWebhookTransport.make(["127.0.0.1"]); + const client = Context.get(yield* Layer.build(guard.layerClient), HttpClient.HttpClient); + + const refused = (url: string) => + guard.check(new URL(url)).pipe( + Effect.flip, + Effect.map((error) => error._tag), + ); + expect(yield* refused("https://10.0.0.1/hook")).toBe("WebhookAddressRejected"); + expect(yield* refused("https://[::1]/hook")).toBe("WebhookAddressRejected"); + expect(yield* refused("https://localhost/hook")).toBe("WebhookAddressRejected"); + yield* guard.check(new URL(`http://127.0.0.1:${port}/hook`)); + expect(guard.allowsPlaintext(new URL("http://127.0.0.1/hook"))).toBe(true); + expect(guard.allowsPlaintext(new URL("http://localhost/hook"))).toBe(false); + + // A redirect comes back as it is, never followed. + const redirected = yield* client.post(`http://127.0.0.1:${port}/redirect`); + expect(redirected.status).toBe(302); + // The client resolves again when it connects, so a name for a private address fails there. + const pinned = yield* Effect.flip(client.post(`http://localhost:${port}/target`)); + expect(pinned.reason._tag).toBe("TransportError"); + expect(String((pinned.reason as { readonly cause?: unknown }).cause)).toContain( + "localhost is not a public address", + ); + }).pipe(Effect.scoped, Effect.provide(NodeHttpServer.layerTest)), +); diff --git a/apps/server/src/mcp/McpWebhookTransport.ts b/apps/server/src/mcp/McpWebhookTransport.ts new file mode 100644 index 0000000000000..8bdde7b1184da --- /dev/null +++ b/apps/server/src/mcp/McpWebhookTransport.ts @@ -0,0 +1,127 @@ +import * as NodeDns from "node:dns"; +import * as NodeNet from "node:net"; + +import { NodeHttpClient } from "@effect/platform-node"; +import * as Config from "effect/Config"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +/** + * Hosts that may receive webhooks although they are private or plain `http:`, for testing + * against a local receiver. Comma-separated host names or addresses; unset denies them all. + */ +export const ALLOWED_HOSTS_ENV = "T3CODE_MCP_WEBHOOK_ALLOWED_HOSTS"; + +export const allowedHosts = Config.String(ALLOWED_HOSTS_ENV).pipe( + Config.withDefault(""), + Config.map((value) => value.split(",").filter((host) => host.trim() !== "")), +); + +export class WebhookAddressRejected extends Schema.TaggedError()( + "WebhookAddressRejected", + { message: Schema.String }, +) {} + +// The IANA special-purpose ranges that are not globally reachable. An IPv6 address must also be +// in global unicast (2000::/3), which leaves out every form that embeds an IPv4 address. Two +// lists, because a list checks an IPv4 address against its IPv4-mapped IPv6 rules too. +const notGlobalV4 = new NodeNet.BlockList(); +for (const [network, prefix] of [ + ["0.0.0.0", 8], + ["10.0.0.0", 8], + ["100.64.0.0", 10], + ["127.0.0.0", 8], + ["169.254.0.0", 16], + ["172.16.0.0", 12], + ["192.0.0.0", 24], + ["192.0.2.0", 24], + ["192.88.99.0", 24], + ["192.168.0.0", 16], + ["198.18.0.0", 15], + ["198.51.100.0", 24], + ["203.0.113.0", 24], + ["224.0.0.0", 4], + ["240.0.0.0", 4], +] as const) { + notGlobalV4.addSubnet(network, prefix, "ipv4"); +} +const globalUnicastV6 = new NodeNet.BlockList(); +globalUnicastV6.addSubnet("2000::", 3, "ipv6"); +const notGlobalV6 = new NodeNet.BlockList(); +for (const [network, prefix] of [ + ["2001::", 23], + ["2001:db8::", 32], + ["2002::", 16], + ["3fff::", 20], +] as const) { + notGlobalV6.addSubnet(network, prefix, "ipv6"); +} + +export const isGloballyRoutable = (address: string): boolean => { + const family = NodeNet.isIP(address); + if (family === 4) return !notGlobalV4.check(address, "ipv4"); + return ( + family === 6 && globalUnicastV6.check(address, "ipv6") && !notGlobalV6.check(address, "ipv6") + ); +}; + +const hostOf = (url: URL) => url.hostname.replace(/^\[(.*)\]$/, "$1").toLowerCase(); + +const resolveAll = (host: string) => + Effect.callback, Error>((resume) => { + NodeDns.lookup(host, { all: true }, (error, addresses) => + resume(error === null ? Effect.succeed(addresses) : Effect.fail(error)), + ); + }); + +/** + * The webhook address check and the client deliveries go through. The client resolves again + * as it connects, to the address it checks, so DNS rebinding cannot reach a private address; + * TLS still sees the host name. Undici's dispatcher never follows redirects. + */ +export const make = (hosts: ReadonlyArray) => { + const allowed = new Set(hosts.map((host) => host.trim().toLowerCase())); + const check = Effect.fn("McpWebhookTransport.check")(function* (url: URL) { + const host = hostOf(url); + if (allowed.has(host)) return; + const addresses = + NodeNet.isIP(host) !== 0 + ? [host] + : (yield* resolveAll(host).pipe( + // A subscribe holds its slot while this runs, and a delivery's request timeout + // does not cover it, so a slow resolver counts as no answer. + Effect.timeout("5 seconds"), + Effect.mapError( + () => new WebhookAddressRejected({ message: `${host} could not be resolved` }), + ), + )).map((resolved) => resolved.address); + if (addresses.length === 0 || !addresses.every(isGloballyRoutable)) { + return yield* new WebhookAddressRejected({ message: `${host} is not a public address` }); + } + }); + const lookup: NodeNet.LookupFunction = (hostname, lookupOptions, callback) => { + NodeDns.lookup(hostname, { ...lookupOptions, all: true }, (error, addresses) => { + if (error !== null) return callback(error, ""); + if ( + !allowed.has(hostname.toLowerCase()) && + (addresses.length === 0 || + addresses.some((address) => !isGloballyRoutable(address.address))) + ) { + return callback( + Object.assign(new Error(`${hostname} is not a public address`), { + code: "ECONNREFUSED", + }), + "", + ); + } + if (lookupOptions.all === true) return callback(null, addresses); + const [first] = addresses; + return callback(null, first!.address, first!.family); + }); + }; + return { + check, + allowsPlaintext: (url: URL) => allowed.has(hostOf(url)), + layerClient: NodeHttpClient.layerUndiciOptions({ connect: { lookup } }), + }; +}; diff --git a/apps/server/src/milestones/MilestoneEvents.test.ts b/apps/server/src/milestones/MilestoneEvents.test.ts index 44896477fa670..06e7763023841 100644 --- a/apps/server/src/milestones/MilestoneEvents.test.ts +++ b/apps/server/src/milestones/MilestoneEvents.test.ts @@ -9,24 +9,38 @@ import { RunId, ThreadId, } from "@t3tools/contracts"; +import * as ConfigProvider from "effect/ConfigProvider"; +import * as Mac from "effect/crypto/Mac"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Base64 from "effect/encoding/Base64"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Queue from "effect/Queue"; import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; -import { HttpBody, HttpClient, HttpRouter } from "effect/http"; +import { + HttpBody, + HttpClient, + HttpRouter, + HttpServer, + type HttpServerRequest, + HttpServerResponse, +} from "effect/http"; import * as SessionStore from "../auth/SessionStore.ts"; import * as McpHttpServer from "../mcp/McpHttpServer.ts"; import type * as McpInvocationContext from "../mcp/McpInvocationContext.ts"; import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts"; +import * as McpWebhookTransport from "../mcp/McpWebhookTransport.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as MilestoneHub from "./MilestoneHub.ts"; const environmentId = EnvironmentId.make("environment-milestone-events-test"); const clientToken = "clientTokenWithoutDots"; const threadToken = "threadTokenWithoutDots"; +const hostToken = "hostTokenWithoutDots"; const scopes: Record = { [clientToken]: { environmentId, @@ -48,8 +62,51 @@ const scopes: Record = { capabilities: new Set(["orchestration"]), issuedAt: 1, }, + // A script on the host: signed in as no outside client. + [hostToken]: { + environmentId, + requestNamespace: "host", + thread: undefined, + client: undefined, + capabilities: new Set(["orchestration"]), + issuedAt: 1, + }, }; +// The Standard Webhooks example secret: base64 of 24 bytes. +const secret = "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw"; + +/** The Standard Webhooks check a receiver runs: any `v1,` signature over id, timestamp and body. */ +const signedBy = Effect.fnUntraced(function* ( + secretValue: string, + headers: Readonly>, + body: string, +) { + const mac = yield* Mac.Mac; + const bytes = Base64.decode(secretValue.slice("whsec_".length)); + if (bytes._tag === "Failure") return false; + const key = yield* Mac.key(Mac.hmacSha256, bytes.success); + const tag = yield* mac.sign( + key, + new TextEncoder().encode(`${headers["webhook-id"]}.${headers["webhook-timestamp"]}.${body}`), + ); + return (headers["webhook-signature"] ?? "").split(" ").includes(`v1,${Base64.encode(tag)}`); +}, Effect.orDie); + +interface Delivery { + readonly headers: Readonly>; + readonly raw: string; + readonly body: Record; + readonly reply: Deferred.Deferred; +} + +/** `open` sends the body and never ends it. */ +interface Answer { + readonly status: number; + readonly body?: string; + readonly open?: boolean; +} + const settled = ( id: string, options: { readonly project?: string; readonly at?: string } = {}, @@ -73,8 +130,40 @@ type JsonRpcResponse = { const serve = Effect.gen(function* () { const revoked = yield* Deferred.make(); + const deliveries = yield* Queue.unbounded(); + const replies = new Set(); + // The webhook receiver: each POST waits for the test to answer it. + const receiver = HttpRouter.add( + "POST", + "/hook", + Effect.fnUntraced(function* (request: HttpServerRequest.HttpServerRequest) { + const raw = yield* request.text; + const reply = yield* Deferred.make(); + replies.add(reply); + yield* Queue.offer(deliveries, { + headers: request.headers, + raw, + body: JSON.parse(raw), + reply, + }); + const answer = yield* Deferred.await(reply); + return answer.open === true + ? HttpServerResponse.stream( + Stream.make(new TextEncoder().encode(answer.body)).pipe(Stream.concat(Stream.never)), + { status: answer.status, contentType: "application/json" }, + ) + : HttpServerResponse.text(answer.body ?? "", { status: answer.status }); + }, Effect.orDie), + ); yield* HttpRouter.serve( - McpHttpServer.layerMcpTransport(McpHttpServer.layerMilestoneEvents).pipe( + Layer.merge(McpHttpServer.layerMcpTransport(McpHttpServer.layerMilestoneEvents), receiver).pipe( + Layer.provide( + ConfigProvider.layer( + ConfigProvider.fromEnv({ + env: { [McpWebhookTransport.ALLOWED_HOSTS_ENV]: "127.0.0.1" }, + }), + ), + ), Layer.provide(ServerSettings.layerTest()), Layer.provide( Layer.mock(SessionStore.SessionStore)({ @@ -139,7 +228,9 @@ const serve = Effect.gen(function* () { cursor: result!.cursor as string, truncated: result!.truncated as boolean, hasMore: result!.hasMore as boolean, - ids: (result!.events as ReadonlyArray<{ eventId: string }>).map((event) => event.eventId), + ids: (result!.events as ReadonlyArray<{ data: { id: string } }>).map( + (event) => event.data.id, + ), })), ); const stream = (args: Record, id = 7) => @@ -160,10 +251,46 @@ const serve = Effect.gen(function* () { ), ), ); - return { post, call, poll, stream, revoke: Deferred.succeed(revoked, undefined) }; + // Shutting the server down waits for open requests, so a test that stops early answers them. + yield* Effect.addFinalizer(() => + Effect.forEach(replies, (reply) => Deferred.succeed(reply, { status: 503 }), { discard: true }), + ); + const hookUrl = `${HttpServer.formatAddress((yield* HttpServer.HttpServer).address)}/hook`; + const answer = (delivery: Delivery, status: number, body?: string, open = false) => + Deferred.succeed(delivery.reply, body === undefined ? { status } : { status, body, open }); + const subscribeParams = (params: Record = {}) => ({ + name: "thread.run_settled", + delivery: { mode: "webhook", url: hookUrl, secret }, + cursor: null, + ...params, + }); + // Subscribes; a first subscription to the URL is verified, so this echoes the challenge. + const subscribe = Effect.fnUntraced(function* (params: Record = {}) { + const pending = yield* Effect.forkChild(call("events/subscribe", subscribeParams(params))); + const verification = yield* Queue.take(deliveries); + expect(verification.body.type).toBe("verification"); + expect(yield* signedBy(secret, verification.headers, verification.raw)).toBe(true); + yield* answer(verification, 200, JSON.stringify({ challenge: verification.body.challenge })); + return { verification, response: yield* Fiber.join(pending) }; + }); + return { + post, + call, + poll, + stream, + revoke: Deferred.succeed(revoked, undefined), + deliveries, + answer, + subscribeParams, + subscribe, + }; }); -const layerTest = Layer.mergeAll(MilestoneHub.layer, NodeHttpServer.layerTest); +const layerTest = Layer.mergeAll( + MilestoneHub.layer, + NodeHttpServer.layerTest, + Mac.layerWebCrypto.pipe(Layer.provide(SecureRandom.layerWebCrypto)), +); it.effect("advertises the extension and lists each milestone type to outside clients only", () => Effect.gen(function* () { @@ -172,13 +299,17 @@ it.effect("advertises the extension and lists each milestone type to outside cli expect(discovered.result!.capabilities.extensions).toEqual({ "io.modelcontextprotocol/events": {}, }); + // TODO(#41158): drop with the bridge for clients predating SEP-3415. + expect(discovered.result!.capabilities.events).toEqual({}); const { events } = (yield* call("events/list")).result!; expect(events).toHaveLength(12); const settledType = events.find( (event: { name: string }) => event.name === "thread.run_settled", ); - expect(settledType.delivery).toEqual(["poll", "push"]); + for (const event of events) { + expect(event.delivery).toEqual(["poll", "push", "webhook"]); + } expect(Object.keys(settledType.inputSchema.properties)).toEqual([ "projectIds", "threadIds", @@ -236,26 +367,69 @@ it.effect("polls from now, then pages forward and says when a cursor fell behind }).pipe(Effect.scoped, Effect.provide(layerTest)), ); -it.effect("rejects a mismatched Mcp-Name, an unknown event and webhook delivery", () => +it.effect("rejects a mismatched Mcp-Name, an unknown event and a bad webhook callback", () => Effect.gen(function* () { - const { post, call } = yield* serve; + const { post, call, deliveries, answer, subscribeParams } = yield* serve; const params = { name: "thread.run_settled", cursor: null }; const missing = yield* post("events/poll", params, { name: null }); expect(missing.status).toBe(400); expect(((yield* missing.json) as JsonRpcResponse).error?.code).toBe(-32020); const mismatched = yield* post("events/poll", params, { name: "thread.needs_input" }); expect(mismatched.status).toBe(400); + // TODO(#41158): drop with the bridge for clients predating SEP-3415. Subscribing needs no Mcp-Name, + // but one that is sent must match. + const wrongName = yield* post("events/subscribe", subscribeParams(), { + name: "thread.needs_input", + }); + expect(((yield* wrongName.json) as JsonRpcResponse).error?.code).toBe(-32020); + // Arguments are checked before the endpoint hears anything. + const badArguments = yield* call( + "events/subscribe", + subscribeParams({ arguments: { projectIds: "project:a" } }), + ).pipe(Effect.forkChild); + expect( + yield* Effect.raceFirst( + Effect.map(Fiber.join(badArguments), (response) => ({ answered: response.error })), + Effect.map(Queue.take(deliveries), (delivery) => ({ posted: delivery.body })), + ), + ).toMatchObject({ answered: { code: -32602 } }); + const unnamed = yield* post("events/subscribe", subscribeParams(), { name: null }).pipe( + Effect.flatMap((response) => response.json), + Effect.forkChild, + ); + const verification = yield* Queue.take(deliveries); + yield* answer(verification, 200, JSON.stringify({ challenge: verification.body.challenge })); + expect(((yield* Fiber.join(unnamed)) as JsonRpcResponse).result?.id).toMatch(/^sub_/); expect((yield* call("events/poll", { name: "nope", cursor: null })).error).toMatchObject({ code: -32023, data: { kind: "event" }, }); + + const subscribe = (delivery: Record, token = clientToken) => + call("events/subscribe", { name: "thread.run_settled", delivery }, { token }).pipe( + Effect.map((response) => response.error), + ); + const valid = { mode: "webhook", url: "https://example.com/hook", secret }; + // Webhooks need an outside client's sign-in; threads cannot see events at all. + expect(yield* subscribe(valid, hostToken)).toMatchObject({ code: -32024 }); + expect(yield* subscribe(valid, threadToken)).toMatchObject({ code: -32023 }); + expect(yield* subscribe({ ...valid, secret: "whsec_c2hvcnQ=" })).toMatchObject({ + code: -32602, + }); + expect(yield* subscribe({ ...valid, secret: { toString: 1 } })).toMatchObject({ + code: -32602, + }); + // Plain http and private addresses are refused unless allowlisted. + expect(yield* subscribe({ ...valid, url: "http://example.com/hook" })).toMatchObject({ + code: -32602, + }); + expect(yield* subscribe({ ...valid, url: "https://10.0.0.1/hook" })).toMatchObject({ + code: -32602, + }); expect( - (yield* call("events/subscribe", { - name: "thread.run_settled", - delivery: { mode: "webhook", url: "https://example.com/hook", secret: "whsec_x" }, - })).error, - ).toMatchObject({ code: -32026, data: { feature: "deliveryMode", value: "webhook" } }); + (yield* call("events/unsubscribe", { name: "thread.run_settled", delivery: valid })).error, + ).toMatchObject({ code: -32023, data: { kind: "subscription" } }); }).pipe(Effect.scoped, Effect.provide(layerTest)), ); @@ -278,7 +452,7 @@ it.effect("streams live milestones after active, replays from a cursor and sends expect(event).toMatchObject({ method: "notifications/events/event", params: { - eventId: "b", + eventId: expect.stringMatching(/^evt_[\w-]{22}$/), name: "thread.run_settled", data: { id: "b", projectId: "project:b" }, _meta: { "io.modelcontextprotocol/subscriptionId": 7 }, @@ -295,8 +469,8 @@ it.effect("streams live milestones after active, replays from a cursor and sends const replay = yield* stream({ cursor: "previous-boot.1" }, 8); expect(yield* Queue.takeN(replay, 3)).toMatchObject([ { method: "notifications/events/active", params: { truncated: true } }, - { method: "notifications/events/event", params: { eventId: "a" } }, - { method: "notifications/events/event", params: { eventId: "b" } }, + { method: "notifications/events/event", params: { data: { id: "a" } } }, + { method: "notifications/events/event", params: { data: { id: "b" } } }, ]); }).pipe(Effect.scoped, Effect.provide(layerTest)), ); @@ -308,6 +482,299 @@ it.effect("ends an open stream when the client's session is revoked", () => expect(yield* Queue.take(live)).toMatchObject({ method: "notifications/events/active" }); yield* revoke; - expect((yield* Effect.exit(Queue.take(live)))._tag).toBe("Failure"); + // It says why, then closes. + expect(yield* Queue.take(live)).toMatchObject({ + method: "notifications/events/terminated", + params: { error: { code: -32024 } }, + }); + while ((yield* Effect.exit(Queue.take(live)))._tag === "Success") { + // The request's own response follows the notice. + } + }).pipe(Effect.scoped, Effect.provide(layerTest)), +); + +it.effect("signs like the Standard Webhooks reference", () => + Effect.gen(function* () { + expect( + yield* signedBy( + secret, + { + "webhook-id": "msg_p5jXN8AQM9LWM0D4loKWxJek", + "webhook-timestamp": "1614265330", + "webhook-signature": "v1,g0hM9SsE+OTPJTGt/tmIKtSyZlE3uFJELVlNIOLJ1OE=", + }, + '{"test": 2432232314}', + ), + ).toBe(true); + }).pipe(Effect.provide(layerTest)), +); + +it.effect("verifies a webhook endpoint and refuses one that does not echo the challenge", () => + Effect.gen(function* () { + const { call, deliveries, answer, subscribe, subscribeParams } = yield* serve; + const at = (url: string) => + call( + "events/subscribe", + subscribeParams({ delivery: { mode: "webhook", url, secret } }), + ).pipe(Effect.forkChild); + const wrongUrl = `${subscribeParams().delivery.url}?wrong`; + const failing = yield* at(wrongUrl); + const wrong = yield* Queue.take(deliveries); + yield* answer(wrong, 200, JSON.stringify({ challenge: "not-it" })); + expect((yield* Fiber.join(failing)).error).toMatchObject({ + code: -32027, + data: { reason: "challenge_failed" }, + }); + // A failure is remembered, so subscribing again answers without another POST. + const again = yield* at(wrongUrl); + const repeated = yield* Effect.raceFirst( + Effect.map(Fiber.join(again), (response) => ({ cached: response.error })), + Effect.map(Queue.take(deliveries), (delivery) => ({ posted: delivery.body })), + ); + expect(repeated).toMatchObject({ + cached: { code: -32027, data: { reason: "challenge_failed" } }, + }); + + // At most 8 KiB of the answer is read: exactly that passes, and one byte more fails at + // once, even from an endpoint that never ends its answer. + const echoOfLength = (challenge: string, length: number) => { + const bare = JSON.stringify({ challenge, padding: "" }); + return JSON.stringify({ challenge, padding: "x".repeat(length - bare.length) }); + }; + const exact = yield* at(`${subscribeParams().delivery.url}?exact`); + const fits = yield* Queue.take(deliveries); + yield* answer(fits, 200, echoOfLength(fits.body.challenge, 8_192)); + expect((yield* Fiber.join(exact)).error).toBeUndefined(); + const long = yield* at(`${subscribeParams().delivery.url}?long`); + const padded = yield* Queue.take(deliveries); + yield* answer(padded, 200, echoOfLength(padded.body.challenge, 8_193), true); + expect((yield* Fiber.join(long)).error).toMatchObject({ + code: -32027, + data: { reason: "challenge_failed" }, + }); + + const { verification, response } = yield* subscribe(); + expect(verification.headers["webhook-id"]).toMatch(/^msg_verification_[\w-]+$/); + expect(verification.headers["x-mcp-subscription-id"]).toBe(response.result!.id); + expect(response.result).toMatchObject({ + id: expect.stringMatching(/^sub_[0-9a-f]{32}$/), + truncated: false, + }); + }).pipe(Effect.scoped, Effect.provide(layerTest)), +); + +it.effect("delivers one signed event at a time and advances the cursor once each resolves", () => + Effect.gen(function* () { + const hub = yield* MilestoneHub.MilestoneHub; + const { call, deliveries, answer, subscribe, subscribeParams } = yield* serve; + const { response } = yield* subscribe({ ttlMs: 600_000 }); + const subscribed = response.result!; + const refresh = (params: Record = {}) => + call("events/subscribe", subscribeParams({ ttlMs: 600_000, ...params })).pipe( + Effect.map((refreshed) => refreshed.result!), + ); + + yield* hub.publish(settled("a")); + yield* hub.publish(settled("b")); + const first = yield* Queue.take(deliveries); + expect(first.body).toMatchObject({ data: { id: "a" }, name: "thread.run_settled" }); + // TODO(#41158): drop with the bridge for clients predating SEP-3415. An event's webhook-id is its eventId. + expect(first.body.eventId).toMatch(/^[A-Za-z0-9_-]+$/); + expect(first.headers["webhook-id"]).toBe(first.body.eventId); + expect(first.headers["x-mcp-subscription-id"]).toBe(subscribed.id); + expect(yield* signedBy(secret, first.headers, first.raw)).toBe(true); + yield* answer(first, 500); + // Unresolved, so the refresh still reports where the subscription started. + expect(yield* refresh()).toMatchObject({ + id: subscribed.id, + cursor: subscribed.cursor, + deliveryStatus: { active: true, lastError: "http_5xx" }, + }); + + // "b" waits for "a": the next POST is its retry, which keeps its webhook-id with a fresh + // timestamp and signature. + yield* TestClock.adjust("30 seconds"); + const retry = yield* Queue.take(deliveries); + expect(retry.body.data.id).toBe("a"); + expect(retry.headers["webhook-id"]).toBe(first.headers["webhook-id"]); + expect(retry.headers["webhook-timestamp"]).not.toBe(first.headers["webhook-timestamp"]); + expect(yield* signedBy(secret, retry.headers, retry.raw)).toBe(true); + yield* answer(retry, 200); + + // Only after "a" resolved does "b" go out; a 410 gives it up without a retry. + const second = yield* Queue.take(deliveries); + expect(second.body.data.id).toBe("b"); + expect(yield* refresh()).toMatchObject({ + cursor: first.body.cursor, + deliveryStatus: { lastError: null, lastDeliveryAt: expect.any(String) }, + }); + yield* answer(second, 410); + // A new secret signs alongside the old one for a grace period. + const rotated = "whsec_" + Buffer.alloc(32, 7).toString("base64"); + yield* refresh({ + delivery: { mode: "webhook", url: subscribeParams().delivery.url, secret: rotated }, + }); + yield* hub.publish(settled("c")); + const third = yield* Queue.take(deliveries); + expect(third.body.data.id).toBe("c"); + expect(yield* signedBy(secret, third.headers, third.raw)).toBe(true); + expect(yield* signedBy(rotated, third.headers, third.raw)).toBe(true); + expect( + (yield* refresh({ + delivery: { mode: "webhook", url: subscribeParams().delivery.url, secret: rotated }, + })).cursor, + ).toBe(second.body.cursor); + yield* answer(third, 200); + }).pipe(Effect.scoped, Effect.provide(layerTest)), +); + +it.effect("reports a gap the endpoint never took on the next refresh", () => + Effect.gen(function* () { + const hub = yield* MilestoneHub.MilestoneHub; + const { call, deliveries, answer, subscribe, subscribeParams } = yield* serve; + const filter = { arguments: { projectIds: ["project:a"] } }; + yield* subscribe(filter); + yield* hub.publish(settled("a")); + const first = yield* Queue.take(deliveries); + // While "a" is out, more milestones than the subscription's backlog go by elsewhere. + for (let index = 0; index < 300; index++) { + yield* hub.publish(settled(`elsewhere-${index}`, { project: "project:b" })); + } + yield* answer(first, 200); + const gap = yield* Queue.take(deliveries); + expect(gap.body).toMatchObject({ type: "gap" }); + yield* answer(gap, 410); + // "c" goes out only after the gap was given up on. + yield* hub.publish(settled("c")); + const next = yield* Queue.take(deliveries); + expect(next.body.data.id).toBe("c"); + const refresh = (cursor: string) => + call("events/subscribe", subscribeParams({ ...filter, cursor })).pipe( + Effect.map(({ result }) => result!), + ); + // Until the client shows a cursor from past the gap, as if each answer were lost. + const refreshed = yield* refresh(first.body.cursor); + expect(refreshed.truncated).toBe(true); + expect(refreshed.cursor).not.toBe(first.body.cursor); + expect((yield* refresh(first.body.cursor)).truncated).toBe(true); + expect((yield* refresh(refreshed.cursor)).truncated).toBe(false); + yield* answer(next, 200); + }).pipe(Effect.scoped, Effect.provide(layerTest)), +); + +it.effect("gives each subscription to one URL its own delivery id for an event", () => + Effect.gen(function* () { + const hub = yield* MilestoneHub.MilestoneHub; + const { call, deliveries, answer, subscribe, subscribeParams } = yield* serve; + yield* subscribe(); + yield* call("events/subscribe", subscribeParams({ arguments: { projectIds: ["project:a"] } })); + yield* hub.publish(settled("a")); + const both = [yield* Queue.take(deliveries), yield* Queue.take(deliveries)]; + for (const delivery of both) { + expect(delivery.body.data.id).toBe("a"); + expect(delivery.headers["webhook-id"]).toBe(delivery.body.eventId); + yield* answer(delivery, 200); + } + expect(both[0]!.headers["webhook-id"]).not.toBe(both[1]!.headers["webhook-id"]); + }).pipe(Effect.scoped, Effect.provide(layerTest)), +); + +it.effect("gives an event up after five attempts", () => + Effect.gen(function* () { + const hub = yield* MilestoneHub.MilestoneHub; + const { deliveries, answer, subscribe } = yield* serve; + yield* subscribe(); + yield* hub.publish(settled("a")); + for (const wait of ["30 seconds", "1 minute", "2 minutes", "4 minutes"] as const) { + yield* answer(yield* Queue.take(deliveries), 503); + yield* TestClock.adjust(wait); + } + const last = yield* Queue.take(deliveries); + expect(last.body.data.id).toBe("a"); + yield* answer(last, 503); + yield* hub.publish(settled("b")); + const next = yield* Queue.take(deliveries); + expect(next.body.data.id).toBe("b"); + yield* answer(next, 200); + }).pipe(Effect.scoped, Effect.provide(layerTest)), +); + +it.effect("grants a finite TTL and keeps one id for the same subscription", () => + Effect.gen(function* () { + const { call, subscribe, subscribeParams } = yield* serve; + const { response } = yield* subscribe({ ttlMs: 1_000 }); + // The test clock starts at the epoch; a grant is clamped to between a minute and an hour. + const hour = "1970-01-01T01:00:00.000Z"; + expect(response.result!.refreshBefore).toBe("1970-01-01T00:01:00.000Z"); + const grant = (params: Record) => + call("events/subscribe", subscribeParams(params)).pipe(Effect.map(({ result }) => result!)); + expect((yield* grant({ ttlMs: null })).refreshBefore).toBe(hour); + expect((yield* grant({ ttlMs: 86_400_000 })).refreshBefore).toBe(hour); + expect((yield* grant({})).refreshBefore).toBe("1970-01-01T00:15:00.000Z"); + + // Arguments compare as canonical JSON; a different filter is another subscription. + const ordered = yield* grant({ + arguments: { projectIds: ["project:a"], includeSubagentChildren: true }, + }); + const reordered = yield* grant({ + arguments: { includeSubagentChildren: true, projectIds: ["project:a"] }, + }); + expect(reordered.id).toBe(ordered.id); + expect(reordered.deliveryStatus).toBeDefined(); + expect(ordered.id).not.toBe(response.result!.id); + }).pipe(Effect.scoped, Effect.provide(layerTest)), +); + +it.effect("ends a subscription at a deadline a refresh brought forward", () => + Effect.gen(function* () { + const { call, subscribe, subscribeParams } = yield* serve; + yield* subscribe({ ttlMs: 3_600_000 }); + const grant = (ttlMs: number) => + call("events/subscribe", subscribeParams({ ttlMs })).pipe( + Effect.map(({ result }) => result!), + ); + expect(yield* grant(60_000)).toMatchObject({ + refreshBefore: "1970-01-01T00:01:00.000Z", + deliveryStatus: { active: true }, + }); + yield* TestClock.adjust("1 minute"); + // Gone, so subscribing again starts a new subscription rather than refreshing a live one. + expect((yield* grant(3_600_000)).deliveryStatus).toBeUndefined(); + }).pipe(Effect.scoped, Effect.provide(layerTest)), +); + +it.effect("refuses subscribes past the per-client cap even when they arrive together", () => + Effect.gen(function* () { + const { call, deliveries, answer, subscribeParams } = yield* serve; + const fibers = yield* Effect.forEach( + Array.from({ length: 101 }, (_, index) => index), + (index) => + call( + "events/subscribe", + subscribeParams({ arguments: { threadIds: [`thread:${index}`] } }), + ).pipe(Effect.forkChild), + ); + // They share one verification; while it is pending each holds a slot, so one is refused now. + const verification = yield* Queue.take(deliveries); + const refused = yield* Effect.raceAll(fibers.map(Fiber.join)); + expect(refused.error).toMatchObject({ + code: -32025, + data: { limit: "subscriptions", max: 100 }, + }); + yield* answer(verification, 200, JSON.stringify({ challenge: verification.body.challenge })); + const responses = yield* Effect.forEach(fibers, Fiber.join); + expect(responses.filter((response) => response.result !== undefined)).toHaveLength(100); + }).pipe(Effect.scoped, Effect.provide(layerTest)), +); + +it.effect("ends a webhook subscription with terminated when the client's session is revoked", () => + Effect.gen(function* () { + const { deliveries, answer, subscribe, revoke } = yield* serve; + yield* subscribe(); + yield* revoke; + const terminated = yield* Queue.take(deliveries); + expect(terminated.headers["webhook-id"]).toMatch(/^msg_terminated_/); + expect(terminated.body).toMatchObject({ type: "terminated", error: { code: -32024 } }); + yield* answer(terminated, 200); }).pipe(Effect.scoped, Effect.provide(layerTest)), ); diff --git a/apps/server/src/milestones/MilestoneEvents.ts b/apps/server/src/milestones/MilestoneEvents.ts index 9c0f2edd0ae55..51d04b2fa1e83 100644 --- a/apps/server/src/milestones/MilestoneEvents.ts +++ b/apps/server/src/milestones/MilestoneEvents.ts @@ -1,4 +1,5 @@ import { + AuthSessionId, type MilestoneEvent as MilestoneEventValue, MilestoneEvent, type MilestoneFilter, @@ -6,11 +7,16 @@ import { ThreadId, TrimmedNonEmptyString, } from "@t3tools/contracts"; +import * as Digest from "effect/crypto/Digest"; import * as Effect from "effect/Effect"; +import * as Base64Url from "effect/encoding/Base64Url"; +import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; -import type { McpServer } from "effect/ai"; +import { McpSchema, type McpServer } from "effect/ai"; +import * as SessionStore from "../auth/SessionStore.ts"; +import * as McpInvocationContext from "../mcp/McpInvocationContext.ts"; import * as MilestoneHub from "./MilestoneHub.ts"; // Matches the hub's buffer, so a poll can drain everything it keeps at once. @@ -59,33 +65,72 @@ const DESCRIPTIONS: Record = { "workflow.run_ended": "A workflow run ended: completed, stopped, skipped or cancelled.", }; -const occurrence = ({ event }: MilestoneHub.PositionedMilestone) => ({ - eventId: event.id, - timestamp: event.occurredAt, - data: event, -}); - /** - * Each milestone type as an MCP event type (SEP-3415), for outside clients to poll or stream. - * Cursors are the hub's, so a client that was away catches up on what the hub still keeps. - * Workflow runs have no project or thread, so their types are narrowed by workflow and run. + * Each milestone type as an MCP event type (SEP-3415), for outside clients to poll, stream or + * receive by webhook. Cursors are the hub's, so a client that was away catches up on what the + * hub still keeps. Workflow runs have no project or thread, so their types are narrowed by + * workflow and run. */ export const make = Effect.gen(function* () { const hub = yield* MilestoneHub.MilestoneHub; + const sessions = yield* Effect.serviceOption(SessionStore.SessionStore); + // A webhook subscription outlives its request, so it ends itself when the client's session does. + const untilRevoked = Effect.fnUntraced(function* (items: Stream.Stream) { + const scope = yield* Effect.serviceOption(McpInvocationContext.McpInvocationContext); + const sessionId = Option.getOrUndefined(scope)?.client?.sessionId; + if (sessionId === undefined || Option.isNone(sessions)) return items; + const revoked = sessions.value.awaitInvalidation(AuthSessionId.make(sessionId)).pipe( + Effect.ignore, + Effect.andThen( + Effect.fail( + new McpSchema.Forbidden({ + message: "Access revoked", + data: { reason: "Access revoked" }, + }), + ), + ), + ); + return items.pipe(Stream.interruptWhen(revoked)); + }); + const digest = yield* Effect.service(Digest.Digest).pipe(Effect.provide(Digest.layerWebCrypto)); + // TODO(#41158): drop this bridge for clients predating SEP-3415 (ChatGPT, @ai-sdk/mcp). + // They take an event's eventId as its webhook-id, which allows only [A-Za-z0-9_-], so the + // eventId is a hash of the milestone id, the same in every delivery mode. + const occurrence = ({ event }: MilestoneHub.PositionedMilestone) => + Effect.map(digest.digest(Digest.sha256, new TextEncoder().encode(event.id)), (hash) => ({ + eventId: `evt_${Base64Url.encode(hash).slice(0, 22)}`, + timestamp: event.occurredAt, + data: event, + })); + const context = { hub, untilRevoked, occurrence }; const isWorkflow = (payload: (typeof MilestoneEvent.members)[number]) => payload.fields.type.literal.startsWith("workflow."); return { threads: MilestoneEvent.members .filter((payload) => !isWorkflow(payload)) - .map((payload) => eventOf(hub, payload, Parameters)), + .map((payload) => eventOf(context, payload, Parameters)), workflows: MilestoneEvent.members .filter(isWorkflow) - .map((payload) => eventOf(hub, payload, WorkflowParameters)), + .map((payload) => eventOf(context, payload, WorkflowParameters)), }; }); const eventOf =

    ( - hub: MilestoneHub.MilestoneHub["Service"], + { + hub, + untilRevoked, + occurrence, + }: { + readonly hub: MilestoneHub.MilestoneHub["Service"]; + readonly occurrence: (milestone: MilestoneHub.PositionedMilestone) => Effect.Effect<{ + readonly eventId: string; + readonly timestamp: string; + readonly data: MilestoneEventValue; + }>; + readonly untilRevoked: ( + items: Stream.Stream, + ) => Effect.Effect>; + }, payload: (typeof MilestoneEvent.members)[number], parameters: P, ) => { @@ -104,22 +149,41 @@ const eventOf =

    ( filter: filterOf(args), limit: Math.min(request.maxEvents ?? DEFAULT_EVENTS, MAX_EVENTS), }) - .pipe(Effect.map((page) => ({ ...page, events: page.events.map(occurrence) }))), - stream: (args, request) => - hub - .follow({ cursor: request.cursor, maxAgeMs: request.maxAgeMs, filter: filterOf(args) }) .pipe( - Effect.map(({ cursor, truncated, items }) => ({ - cursor, - truncated, - items: items.pipe( - Stream.map((item): McpServer.EventStreamItem => + Effect.flatMap((page) => + Effect.map(Effect.forEach(page.events, occurrence), (events) => ({ + ...page, + events, + })), + ), + ), + stream: Effect.fn("MilestoneEvents.stream")(function* ( + args: P["Type"], + request: McpServer.EventStreamRequest, + ) { + const { cursor, truncated, items } = yield* hub.follow({ + cursor: request.cursor, + maxAgeMs: request.maxAgeMs, + filter: filterOf(args), + }); + return { + cursor, + truncated, + items: yield* untilRevoked( + items.pipe( + Stream.mapEffect( + (item): Effect.Effect> => item._tag === "Milestone" - ? { _tag: "Event", cursor: item.cursor, ...occurrence(item) } - : item, - ), + ? Effect.map(occurrence(item), (event) => ({ + _tag: "Event" as const, + cursor: item.cursor, + ...event, + })) + : Effect.succeed(item), ), - })), + ), ), + }; + }), } satisfies McpServer.EventOptions; }; diff --git a/docs/user/outside-agents.md b/docs/user/outside-agents.md index 8a2f790905f75..30c8aba13ffb1 100644 --- a/docs/user/outside-agents.md +++ b/docs/user/outside-agents.md @@ -138,14 +138,19 @@ Agents without OAuth support cannot connect. A bot that supports MCP Events (`io.modelcontextprotocol/events`) can learn when something happens without reading threads over and over: a turn ended, an agent waits on a person, a guest asked something, a watched pull request woke -its thread. Each of these is an event type it can poll or stream, narrowed to -projects or threads. [Workflow runs](workflows.md) have their own event types, -narrowed to workflows or runs: a run started, paused, resumed or ended, and a -question it asks was raised or settled. Runs that another run started are left -out unless asked for, as subagent threads are, and narrowing thread events to a -run also picks out the threads that are its agent steps. The environment keeps its latest 1,000 milestones in -memory, so a bot that was away longer, or reconnects after a restart, is told -some may be missing and should reread the threads it cares about. +its thread. [Workflow runs](workflows.md) are events too: a run started, paused, +resumed or ended, or waits on a person. A bot can poll, stream, or receive each +event type by webhook, narrowed to projects and threads or to workflows and +runs; runs another run started are left out unless asked for, as subagent +threads are, and narrowing thread events to a run picks out its agent steps. +The environment keeps its latest 1,000 milestones in memory, so a bot that was +away longer, or reconnects after a restart, is told some may be missing and +should reread what it cares about. Webhooks go only to public `https` addresses, +a subscription lasts at most an hour before the bot must renew it, and signing +the bot out ends its subscriptions. To test with a receiver on your own machine +or network, start the environment with `T3CODE_MCP_WEBHOOK_ALLOWED_HOSTS` set to +its host names, for example `localhost,127.0.0.1`; those hosts may also use +plain `http`. ## Scripts on the host diff --git a/patches/effect@4.1.5.patch b/patches/effect@4.1.5.patch index 6d1bf0a6a9fa8..91026f0d15bd7 100644 --- a/patches/effect@4.1.5.patch +++ b/patches/effect@4.1.5.patch @@ -381,10 +381,18 @@ index bff6370..0a6962c 100644 // ============================================================================= /** diff --git a/dist/ai/McpServer.d.ts b/dist/ai/McpServer.d.ts -index fe6f18e..b641e20 100644 +index fe6f18e..c67169e 100644 --- a/dist/ai/McpServer.d.ts +++ b/dist/ai/McpServer.d.ts -@@ -26,6 +26,7 @@ import * as RpcServer from "../rpc/RpcServer.ts"; +@@ -17,6 +17,7 @@ import * as Context from "../Context.ts"; + import * as Duration from "../Duration.ts"; + import * as Effect from "../Effect.ts"; + import * as Headers from "../http/Headers.ts"; ++import * as HttpClient from "../http/HttpClient.ts"; + import * as HttpRouter from "../http/HttpRouter.ts"; + import * as HttpServerRequest from "../http/HttpServerRequest.ts"; + import * as Layer from "../Layer.ts"; +@@ -26,6 +27,7 @@ import * as RpcServer from "../rpc/RpcServer.ts"; import * as Schema from "../Schema.ts"; import * as Scope from "../Scope.ts"; import type { Stdio } from "../Stdio.ts"; @@ -392,7 +400,7 @@ index fe6f18e..b641e20 100644 import type * as Types from "../Types.ts"; import type * as McpProtocol from "./McpProtocol.ts"; import * as McpSchema from "./McpSchema.ts"; -@@ -113,7 +114,7 @@ export interface MiddlewareSuccess { +@@ -113,7 +115,7 @@ export interface MiddlewareSuccess { * @category middleware * @since 4.0.0 */ @@ -401,7 +409,7 @@ index fe6f18e..b641e20 100644 /** * Request metadata passed to MCP middleware. * -@@ -1276,6 +1277,177 @@ export declare const registerSkill: (options: SkillOptions) => Effect.Effect Effect.Effect Layer.Layer; @@ -520,8 +528,8 @@ index fe6f18e..b641e20 100644 + * `parameters` types the subscription arguments, an empty object by default, + * and `payload` the occurrences' `data`; both are advertised as JSON Schema + * by `events/list`. `poll` offers poll delivery and `stream` push delivery, -+ * and at least one is required. Webhook delivery is not supported, so -+ * `events/subscribe` answers `Unsupported`. ++ * and at least one is required. With {@link EventWebhooks} provided where the ++ * event is registered, `stream` also backs webhook delivery. + * + * @stability unstable + * @category events @@ -576,14 +584,128 @@ index fe6f18e..b641e20 100644 + * @since 4.1.4 + */ +export declare const event: = Schema.Struct<{}>, Payload extends Schema.Codec = Schema.Codec, R = never>(options: EventOptions) => Layer.Layer>; ++declare const CallbackRejected_base: new = {}>(args: import("../Types.ts").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("../Cause.ts").YieldableError & { ++ readonly _tag: "CallbackRejected"; ++} & Readonly; ++/** ++ * The reason a {@link CallbackGuard} refuses a callback URL. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare class CallbackRejected extends CallbackRejected_base<{ ++ readonly message: string; ++}> { ++} ++/** ++ * Decides which webhook callback URLs may be reached. ++ * ++ * **Details** ++ * ++ * `check` runs when a subscription is created and again before every POST. ++ * Resolving a host name needs the platform, so the default refuses every URL: ++ * a server that offers webhooks provides a guard that resolves the host and ++ * refuses addresses that are not globally routable. That check alone cannot ++ * stop DNS rebinding, so the `HttpClient` given to {@link layerEventWebhooks} ++ * must connect only to the address it validated, sending the original host ++ * name in `Host` and TLS SNI, and must not follow redirects. `allowsPlaintext` ++ * admits an `http:` URL, which only a local test setup should do. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare const CallbackGuard: Context.Reference<{ ++ readonly check: (url: URL) => Effect.Effect; ++ readonly allowsPlaintext?: ((url: URL) => boolean) | undefined; ++}>; ++declare const EventWebhooks_base: Context.ServiceClass; ++}>; ++/** ++ * Webhook delivery for event types under the MCP Events extension (SEP-3415). ++ * ++ * **Details** ++ * ++ * Event types registered with a `stream` where this service is present also ++ * offer webhook delivery. `events/subscribe` validates the callback, verifies ++ * the endpoint with a challenge, and runs the event's `stream` for the ++ * subscription's lifetime, POSTing each occurrence with Standard Webhooks ++ * signatures, one at a time, retrying with backoff. Subscriptions live in ++ * memory: every grant is finite, between a minute and an hour, so a client ++ * refreshing from its cursor recreates what a restart lost. A failure of the ++ * stream, such as `Forbidden` when access is revoked, ends the subscription ++ * with a `terminated` envelope. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare class EventWebhooks extends EventWebhooks_base { ++} ++/** ++ * Options for {@link layerEventWebhooks}. ++ * ++ * **Details** ++ * ++ * `principal` names the authenticated subject of an `events/subscribe` or ++ * `events/unsubscribe` request, read from the request's services. It fails ++ * with `Forbidden` for a caller that may not subscribe; webhook delivery ++ * requires an authenticated principal. A subscription's identity is its ++ * principal, callback URL, event name and arguments, so the principal must ++ * stay the same across token refreshes. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventWebhooksOptions { ++ readonly principal: Effect.Effect; ++} ++/** ++ * Provides {@link EventWebhooks}, delivering through the given `HttpClient` ++ * and admitting callbacks through the current {@link CallbackGuard}. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare const layerEventWebhooks: (options: EventWebhooksOptions) => Layer.Layer; /** * Registers an MCP prompt from an Effect program. * diff --git a/dist/ai/McpServer.js b/dist/ai/McpServer.js -index 4bf6bca..0973460 100644 +index 4bf6bca..5ad258e 100644 --- a/dist/ai/McpServer.js +++ b/dist/ai/McpServer.js -@@ -413,6 +413,9 @@ const notFound = (method, target) => { +@@ -16,6 +16,8 @@ import * as Cause from "../Cause.js"; + import * as Clock from "../Clock.js"; + import * as Context from "../Context.js"; + import * as Digest from "../crypto/Digest.js"; ++import * as Mac from "../crypto/Mac.js"; ++import * as SecureRandom from "../crypto/SecureRandom.js"; + import * as Data from "../Data.js"; + import * as Deferred from "../Deferred.js"; + import * as Duration from "../Duration.js"; +@@ -26,6 +28,7 @@ import * as Exit from "../Exit.js"; + import * as Fiber from "../Fiber.js"; + import * as FindMyWay from "../http/FindMyWay.js"; + import * as Headers from "../http/Headers.js"; ++import * as HttpClient from "../http/HttpClient.js"; + import { appendPreResponseHandlerUnsafe } from "../http/HttpEffect.js"; + import * as HttpRouter from "../http/HttpRouter.js"; + import * as HttpServerRequest from "../http/HttpServerRequest.js"; +@@ -55,6 +58,7 @@ import * as McpCore from "./internal/mcpCore.js"; + import * as McpProtocolInternal from "./internal/mcpProtocol.js"; + import * as McpRuntime from "./internal/mcpRuntime.js"; + import * as McpSkills from "./internal/mcpSkills.js"; ++import * as McpWebhooks from "./internal/mcpWebhooks.js"; + import * as InternalStructuredOutput from "./internal/structured-output.js"; + import * as McpSchema from "./McpSchema.js"; + import { CallToolResult, ElicitationDeclined, EnabledWhen, GetPromptResult, InternalError, InvalidParams, InvalidRequest, isParam, McpRequestContext, McpServerClient, McpServerClientMiddleware, MethodNotFound, Prompt, Resource, ResourceTemplate, ServerNotificationRpcs, TextContent, Tool as McpTool, ToolJson } from "./McpSchema.js"; +@@ -413,6 +417,9 @@ const notFound = (method, target) => { return new McpCore.SkillNotFound({ uri: target }); @@ -593,7 +715,7 @@ index 4bf6bca..0973460 100644 } }; const isHidden = error => error instanceof Hidden; -@@ -2637,6 +2640,96 @@ export const registerSkill = /*#__PURE__*/Effect.fnUntraced(function* (options) +@@ -2637,6 +2644,155 @@ export const registerSkill = /*#__PURE__*/Effect.fnUntraced(function* (options) * @since 4.1.1 */ export const skill = options => Layer.effectDiscard(registerSkill(options)); @@ -608,7 +730,8 @@ index 4bf6bca..0973460 100644 +* +* The server declares `io.modelcontextprotocol/events` on revision +* `2026-07-28` once any event type is registered, and answers `events/list`, -+* `events/poll` and `events/stream`. A push stream runs `stream` for its ++* `events/poll`, `events/stream`, and with {@link EventWebhooks} ++* `events/subscribe` and `events/unsubscribe`. A push stream runs `stream` for its +* lifetime inside the request's middleware, sends heartbeats carrying the +* last cursor, and ends when the client goes away. Services read by `poll` +* and `stream` are request-level, as for tools. @@ -627,6 +750,9 @@ index 4bf6bca..0973460 100644 + const services = yield* Effect.context(); + const annotations = options.annotations ?? Context.empty(); + const { invoke, visible } = makeInvoke(services, globalMiddleware); ++ const webhooks = stream === undefined ++ ? undefined ++ : Option.getOrUndefined(Option.map(Context.getOption(services, EventWebhooks), (service) => webhooksState.get(service))); + const parameters = options.parameters ?? Schema.Struct({}); + const decodeArguments = Schema.decodeUnknownEffect(Schema.toCodecJson(parameters)); + const encodePayload = Schema.encodeUnknownEffect(Schema.toCodecJson(options.payload)); @@ -641,13 +767,19 @@ index 4bf6bca..0973460 100644 + descriptor: { + name, + ...(options.description === undefined ? {} : { description: options.description }), -+ delivery: [...(poll === undefined ? [] : ["poll"]), ...(stream === undefined ? [] : ["push"])], ++ delivery: [ ++ ...(poll === undefined ? [] : ["poll"]), ++ ...(stream === undefined ? [] : ["push"]), ++ ...(webhooks === undefined ? [] : ["webhook"]) ++ ], + inputSchema: toolJsonSchema(parameters, false), + payloadSchema: toolJsonSchema(options.payload, false), + ...(options._meta === undefined ? {} : { _meta: options._meta }) + }, + isVisible: isEnabled(annotations), + visible: visible("events/list", name), ++ webhooks, ++ decodeArguments: argumentsOf, + poll: poll === undefined ? undefined : (request, invocation) => invoke(Effect.gen(function* () { + const result = yield* poll(yield* argumentsOf(request.arguments), { + cursor: request.cursor, @@ -663,7 +795,8 @@ index 4bf6bca..0973460 100644 + }; + }), invocation, { method: "events/poll", target: name, payload: request }), + stream: stream === undefined ? undefined : (request, invocation, deliver) => invoke(Effect.scoped(Effect.gen(function* () { -+ const subscription = yield* stream(yield* argumentsOf(request.arguments), { ++ const args = request.decoded !== undefined ? request.decoded.value : yield* argumentsOf(request.arguments); ++ const subscription = yield* stream(args, { + cursor: request.cursor, + maxAgeMs: request.maxAgeMs + }); @@ -687,6 +820,54 @@ index 4bf6bca..0973460 100644 +* @since 4.1.4 +*/ +export const event = (options) => Layer.effectDiscard(registerEvent(options)); ++/** ++ * The reason a {@link CallbackGuard} refuses a callback URL. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export class CallbackRejected extends /*#__PURE__*/Data.TaggedError("CallbackRejected") {} ++/** ++ * Decides which webhook callback URLs may be reached. The default refuses ++ * every URL; see the source for the contract a platform guard keeps. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const CallbackGuard = /*#__PURE__*/Context.Reference("effect/ai/McpServer/CallbackGuard", { ++ defaultValue: () => ({ ++ check: (url) => Effect.fail(new CallbackRejected({ message: `No callback guard admits ${url.host}` })) ++ }) ++}); ++/** ++ * Webhook delivery for event types under the MCP Events extension (SEP-3415). ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export class EventWebhooks extends /*#__PURE__*/Context.Service()("effect/ai/McpServer/EventWebhooks") {} ++const webhooksState = /*#__PURE__*/new WeakMap(); ++/** ++ * Provides {@link EventWebhooks}, delivering through the given `HttpClient` ++ * and admitting callbacks through the current {@link CallbackGuard}. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const layerEventWebhooks = (options) => Layer.effect(EventWebhooks, Effect.gen(function* () { ++ const webhooks = yield* McpWebhooks.make({ ++ principal: options.principal, ++ guard: yield* CallbackGuard, ++ client: yield* HttpClient.HttpClient ++ }); ++ const service = EventWebhooks.of({ size: webhooks.size }); ++ webhooksState.set(service, webhooks); ++ return service; ++}).pipe(Effect.provide(Layer.mergeAll(Mac.layerWebCrypto, Digest.layerWebCrypto).pipe(Layer.provideMerge(SecureRandom.layerWebCrypto))))); /** * Registers an MCP prompt from an Effect program. * @@ -1029,7 +1210,7 @@ index 0000000..d875046 + } +}, Effect.scoped); diff --git a/dist/ai/internal/mcpProtocol/v2026_07_28.js b/dist/ai/internal/mcpProtocol/v2026_07_28.js -index af1ceed..467dd8a 100644 +index af1ceed..ea29279 100644 --- a/dist/ai/internal/mcpProtocol/v2026_07_28.js +++ b/dist/ai/internal/mcpProtocol/v2026_07_28.js @@ -17,6 +17,7 @@ import * as Schema from "../../../Schema.js"; @@ -1049,25 +1230,31 @@ index af1ceed..467dd8a 100644 /** * @internal */ -@@ -260,6 +261,8 @@ export const makeHandlers = (core, _lifecycle, context) => { +@@ -260,6 +261,10 @@ export const makeHandlers = (core, _lifecycle, context) => { const decodeListSkillsResult = Schema.decodeUnknownEffect(McpSkills.ListSkillsResult); const decodeGetSkillResult = Schema.decodeUnknownEffect(McpSkills.GetSkillResult); const decodeReadResourceDirectoryResult = Schema.decodeUnknownEffect(McpSkills.ReadResourceDirectoryResult); + const decodeListEventsResult = Schema.decodeUnknownEffect(McpEvents.ListEventsResult); + const decodePollEventsResult = Schema.decodeUnknownEffect(McpEvents.PollEventsResult); ++ const decodeSubscribeEventsResult = Schema.decodeUnknownEffect(McpEvents.SubscribeEvents.successSchema); ++ const decodeUnsubscribeEventsResult = Schema.decodeUnknownEffect(McpEvents.UnsubscribeEvents.successSchema); const sendNotification = context.sendNotification; const supportsSubscriptions = sendNotification !== undefined; // Older adapters accept arbitrary JSON; this binding requires extension settings objects. -@@ -277,7 +280,7 @@ export const makeHandlers = (core, _lifecycle, context) => { +@@ -277,8 +282,11 @@ export const makeHandlers = (core, _lifecycle, context) => { completions: {}, logging: {} }; - const declared = McpSkills.declareExtension(extensions, presence.skills); + const declared = McpEvents.declareExtension(McpSkills.declareExtension(extensions, presence.skills), presence.events); if (declared !== undefined) capabilities.extensions = declared; ++ // Bridge for clients predating SEP-3415 (ChatGPT, @ai-sdk/mcp); drop per #41158. ++ // They look for a top-level `events` capability instead of the extension. ++ if (presence.events) capabilities.events = {}; if (presence.tools) capabilities.tools = { listChanged: supportsSubscriptions -@@ -297,6 +300,20 @@ export const makeHandlers = (core, _lifecycle, context) => { + }; +@@ -297,6 +305,26 @@ export const makeHandlers = (core, _lifecycle, context) => { serverInfo: context.serverInfo }; }); @@ -1079,16 +1266,22 @@ index af1ceed..467dd8a 100644 + yield* validateParameterHeaders(registration.descriptor.inputSchema, args, httpRequest.value.headers); + } + }); -+ // Webhook delivery is not implemented, so subscribing refuses every event type. -+ const refuseWebhook = Effect.fnUntraced(function* (method, name) { ++ // Webhook delivery runs the event's push stream, so it needs both. ++ const webhookRegistration = Effect.fnUntraced(function* (method, name, args) { + yield* requireEvents(method); -+ yield* core.events.get(name, yield* getInvocation); -+ return yield* McpEvents.unsupportedDelivery("webhook"); ++ const invocation = yield* getInvocation; ++ const registration = yield* core.events.get(name, invocation); ++ const { stream, webhooks } = registration; ++ if (webhooks === undefined || stream === undefined) { ++ return yield* McpEvents.unsupportedDelivery("webhook"); ++ } ++ yield* validateEventHeaders(registration, args); ++ return { invocation, stream, webhooks, decodeArguments: registration.decodeArguments }; + }); const requireSkills = method => McpSkills.requireSkills(core, method).pipe(Effect.catch(error => failWithHttpStatus(404, error))); const getInvocation = PublicMcpSchema.McpRequestContext.useSync(McpProtocol.invocationFromRequestContext); const getInputInvocation = Effect.fnUntraced(function* (request) { -@@ -592,6 +609,77 @@ export const makeHandlers = (core, _lifecycle, context) => { +@@ -592,6 +620,97 @@ export const makeHandlers = (core, _lifecycle, context) => { }, context.serverInfo); return yield* decodeReadResourceDirectoryResult(result); }, Effect.mapError(projectError)), @@ -1158,15 +1351,35 @@ index af1ceed..467dd8a 100644 + }); + }, Effect.mapError(projectError)), + "events/subscribe": Effect.fnUntraced(function* (request) { -+ return yield* refuseWebhook("events/subscribe", request.name); ++ const { decodeArguments, invocation, stream, webhooks } = yield* webhookRegistration("events/subscribe", request.name, request.arguments); ++ const args = request.arguments ?? {}; ++ const cursor = request.cursor ?? null; ++ const subscribed = yield* webhooks.subscribe({ ++ name: request.name, ++ arguments: args, ++ delivery: request.delivery, ++ cursor, ++ ttlMs: request.ttlMs, ++ decode: decodeArguments(args), ++ open: (decoded, deliver) => stream({ arguments: args, decoded: { value: decoded }, cursor, maxAgeMs: request.maxAgeMs }, invocation, deliver) ++ }); ++ const result = yield* projectCompleteResult(omitUndefined({ ...subscribed }), context.serverInfo); ++ return yield* decodeSubscribeEventsResult(result); + }, Effect.mapError(projectError)), + "events/unsubscribe": Effect.fnUntraced(function* (request) { -+ return yield* refuseWebhook("events/unsubscribe", request.name); ++ const { webhooks } = yield* webhookRegistration("events/unsubscribe", request.name, request.arguments); ++ yield* webhooks.unsubscribe({ ++ name: request.name, ++ arguments: request.arguments ?? {}, ++ delivery: request.delivery ++ }); ++ const result = yield* projectCompleteResult({}, context.serverInfo); ++ return yield* decodeUnsubscribeEventsResult(result); + }, Effect.mapError(projectError)), "notifications/cancelled": Effect.fnUntraced(function* (_request) { return yield* Effect.void; }) -@@ -613,10 +701,10 @@ const runtime = { +@@ -613,10 +732,10 @@ const runtime = { export const protocol = /*#__PURE__*/McpProtocol.make({ protocolVersion: McpSchema.protocolVersion, runtime, @@ -1180,7 +1393,7 @@ index af1ceed..467dd8a 100644 makeHandlers, toReverseClient: () => ({ diff --git a/dist/ai/internal/mcpRuntime.js b/dist/ai/internal/mcpRuntime.js -index 88238ff..274e513 100644 +index 88238ff..721ff28 100644 --- a/dist/ai/internal/mcpRuntime.js +++ b/dist/ai/internal/mcpRuntime.js @@ -39,6 +39,10 @@ const routingNameKey = method => { @@ -1194,7 +1407,19 @@ index 88238ff..274e513 100644 return "name"; case "resources/read": return "uri"; -@@ -340,7 +344,8 @@ export const make = /*#__PURE__*/Effect.fnUntraced(function* (protocols) { +@@ -178,7 +182,10 @@ export const make = /*#__PURE__*/Effect.fnUntraced(function* (protocols) { + if (nameKey !== undefined) { + const name = asRecord(inputRecord?.params)?.[nameKey]; + const header = headers[MCP_NAME_HEADER]; +- if (typeof name !== "string" || header === undefined || McpProtocol.decodeRoutingHeader(header) !== name) { ++ // Bridge for clients predating SEP-3415 (ChatGPT, @ai-sdk/mcp); drop per #41158. ++ // They send no Mcp-Name on these; one they do send must still match. ++ const optional = header === undefined && (method === "events/subscribe" || method === "events/unsubscribe"); ++ if (!optional && (typeof name !== "string" || header === undefined || McpProtocol.decodeRoutingHeader(header) !== name)) { + return headerMismatch("Mcp-Name header does not match request parameters"); + } + } +@@ -340,7 +347,8 @@ export const make = /*#__PURE__*/Effect.fnUntraced(function* (protocols) { return { _tag: "Accepted", acknowledge: !isRequest || !hasId, @@ -1204,6 +1429,475 @@ index 88238ff..274e513 100644 }; }, effectLogLevel: (clientId, headers, fallback) => stateful?.effectLogLevel(clientId, headers, fallback) ?? fallback, +diff --git a/dist/ai/internal/mcpWebhooks.d.ts b/dist/ai/internal/mcpWebhooks.d.ts +new file mode 100644 +index 0000000..cb0ff5c +--- /dev/null ++++ b/dist/ai/internal/mcpWebhooks.d.ts +@@ -0,0 +1 @@ ++export {}; +diff --git a/dist/ai/internal/mcpWebhooks.js b/dist/ai/internal/mcpWebhooks.js +new file mode 100644 +index 0000000..4e2871a +--- /dev/null ++++ b/dist/ai/internal/mcpWebhooks.js +@@ -0,0 +1,456 @@ ++import * as Clock from "../../Clock.js"; ++import * as Digest from "../../crypto/Digest.js"; ++import * as Mac from "../../crypto/Mac.js"; ++import * as SecureRandom from "../../crypto/SecureRandom.js"; ++import * as Deferred from "../../Deferred.js"; ++import * as Duration from "../../Duration.js"; ++import * as Effect from "../../Effect.js"; ++import * as Base64 from "../../encoding/Base64.js"; ++import * as Base64Url from "../../encoding/Base64Url.js"; ++import * as Fiber from "../../Fiber.js"; ++import * as FetchHttpClient from "../../http/FetchHttpClient.js"; ++import * as HttpClient from "../../http/HttpClient.js"; ++import * as HttpClientRequest from "../../http/HttpClientRequest.js"; ++import * as Option from "../../Option.js"; ++import * as Result from "../../Result.js"; ++import * as Stream from "../../Stream.js"; ++import * as PublicMcpSchema from "../McpSchema.js"; ++import { wireError } from "./mcpEvents.js"; ++const MINUTE_MS = 6e4; ++const MIN_TTL_MS = MINUTE_MS; ++const MAX_TTL_MS = 60 * MINUTE_MS; ++const DEFAULT_TTL_MS = 15 * MINUTE_MS; ++const MAX_ATTEMPTS = 5; ++const FIRST_RETRY_MS = 3e4; ++const REQUEST_TIMEOUT_MS = 1e4; ++const ROTATION_GRACE_MS = 5 * MINUTE_MS; ++const VERIFIED_FOR_MS = MAX_TTL_MS; ++const FAILED_FOR_MS = 5 * MINUTE_MS; ++const VERIFICATIONS_PER_HOST_PER_MINUTE = 10; ++const MAX_SUBSCRIPTIONS_PER_PRINCIPAL = 100; ++const MAX_CHALLENGE_RESPONSE_BYTES = 8192; ++const SECRET_PREFIX = "whsec_"; ++const invalid = (message) => new PublicMcpSchema.InvalidParams({ message }); ++const grantTtl = (suggested) => suggested === void 0 ? DEFAULT_TTL_MS : suggested === null ? MAX_TTL_MS : Math.min(MAX_TTL_MS, Math.max(MIN_TTL_MS, suggested)); ++const canonicalJson = (value) => { ++ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`; ++ if (typeof value === "object" && value !== null) { ++ const entries = Object.entries(value).filter(([, entry]) => entry !== void 0); ++ entries.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0); ++ return `{${entries.map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`).join(",")}}`; ++ } ++ return JSON.stringify(value) ?? "null"; ++}; ++const encoder = new TextEncoder(); ++const parseUrl = (value, guard) => { ++ if (typeof value !== "string") return Effect.fail(invalid("delivery.url is required")); ++ let url; ++ try { ++ url = new URL(value); ++ } catch { ++ return Effect.fail(invalid("delivery.url is not a valid URL")); ++ } ++ if (url.protocol !== "https:" && !(url.protocol === "http:" && guard.allowsPlaintext?.(url) === true)) { ++ return Effect.fail(invalid("delivery.url must use https")); ++ } ++ if (url.username !== "" || url.password !== "") { ++ return Effect.fail(invalid("delivery.url must not carry credentials")); ++ } ++ url.hash = ""; ++ return Effect.succeed(url); ++}; ++const parseSecret = (value) => { ++ const fail = Effect.fail(invalid("delivery.secret must be whsec_ and the base64 of 24 to 64 random bytes")); ++ if (typeof value !== "string" || !value.startsWith(SECRET_PREFIX)) return fail; ++ const bytes = Base64.decode(value.slice(SECRET_PREFIX.length)); ++ if (Result.isFailure(bytes) || bytes.success.length < 24 || bytes.success.length > 64) return fail; ++ return Mac.key(Mac.hmacSha256, bytes.success).pipe(Effect.orDie, Effect.map((key) => ({ text: value, key }))); ++}; ++const statusCategory = (status) => status >= 500 ? "http_5xx" : "http_4xx"; ++const transportCategory = (error) => { ++ let current = error; ++ for (let depth = 0; depth < 8 && typeof current === "object" && current !== null; depth++) { ++ const code = current.code; ++ if (typeof code === "string" && /CERT|TLS|SSL/.test(code)) return "tls_error"; ++ current = current.cause ?? current.reason; ++ } ++ return "connection_refused"; ++}; ++const readCapped = (response) => Effect.suspend(() => { ++ const chunks = []; ++ let total = 0; ++ let oversized = false; ++ return response.stream.pipe( ++ Stream.takeWhile((chunk) => { ++ if (total + chunk.length > MAX_CHALLENGE_RESPONSE_BYTES) { ++ oversized = true; ++ return false; ++ } ++ total += chunk.length; ++ chunks.push(chunk); ++ return true; ++ }), ++ Stream.runDrain, ++ Effect.map(() => { ++ if (oversized) return void 0; ++ const bytes = new Uint8Array(total); ++ let offset = 0; ++ for (const chunk of chunks) { ++ bytes.set(chunk, offset); ++ offset += chunk.length; ++ } ++ return new TextDecoder().decode(bytes); ++ }) ++ ); ++}); ++const echoedChallenge = (body) => { ++ try { ++ const parsed = JSON.parse(body); ++ const challenge = typeof parsed === "object" && parsed !== null ? parsed.challenge : void 0; ++ return typeof challenge === "string" ? challenge : void 0; ++ } catch { ++ return void 0; ++ } ++}; ++const callbackError = (category) => new PublicMcpSchema.CallbackEndpointError({ ++ message: `The callback endpoint failed verification: ${category}`, ++ data: { reason: category } ++}); ++const iso = (millis) => new Date(millis).toISOString(); ++const make = Effect.fnUntraced(function* (options) { ++ const scope = yield* Effect.scope; ++ const mac = yield* Mac.Mac; ++ const digest = yield* Digest.Digest; ++ const random = yield* SecureRandom.SecureRandom; ++ const { guard } = options; ++ const client = HttpClient.withScope(options.client); ++ const subscriptions = /* @__PURE__ */ new Map(); ++ const pending = /* @__PURE__ */ new Map(); ++ const verified = /* @__PURE__ */ new Map(); ++ const failedVerifications = /* @__PURE__ */ new Map(); ++ const verifying = /* @__PURE__ */ new Map(); ++ const verificationsByHost = /* @__PURE__ */ new Map(); ++ const forget = (subscription) => { ++ if (subscriptions.get(subscription.id) === subscription) subscriptions.delete(subscription.id); ++ }; ++ const subscriptionId = (principal, url, name, args) => digest.digestHex(Digest.sha256, encoder.encode(canonicalJson([principal, url.href, name, args]))).pipe( ++ Effect.map((hex) => `sub_${hex.slice(0, 32)}`) ++ ); ++ const messageId = (prefix) => Effect.map(random.randomBytes(18), (bytes) => `${prefix}_${Base64Url.encode(bytes)}`); ++ const deliveryId = (subscription, eventId) => Effect.map( ++ digest.digest(Digest.sha256, encoder.encode(`${subscription.id}\0${eventId}`)), ++ (hash) => `evt_${Base64Url.encode(hash).slice(0, 22)}` ++ ); ++ const MAX_CURSORS_SINCE_GAP = 1024; ++ const advance = (subscription, cursor) => { ++ subscription.watermark = cursor; ++ const since = subscription.cursorsSinceGap; ++ if (since === void 0) return; ++ since.add(cursor); ++ if (since.size > MAX_CURSORS_SINCE_GAP) since.delete(since.values().next().value); ++ }; ++ const sign = (keys, webhookId, timestamp, body) => Effect.forEach(keys, (key) => mac.sign(key, encoder.encode(`${webhookId}.${timestamp}.${body}`))).pipe( ++ Effect.orDie, ++ Effect.map((tags) => tags.map((tag) => `v1,${Base64.encode(tag)}`).join(" ")) ++ ); ++ const send = Effect.fnUntraced(function* (subscription, body, webhookId, readBody) { ++ const admitted = yield* Effect.result(guard.check(subscription.url)); ++ if (Result.isFailure(admitted)) { ++ return { _tag: "Failed", category: "connection_refused", retryable: true }; ++ } ++ const now = yield* Clock.currentTimeMillis; ++ const timestamp = Math.floor(now / 1e3); ++ const previous = subscription.previous; ++ const keys = previous !== void 0 && now < previous.until ? [subscription.key, previous.key] : [subscription.key]; ++ const request = HttpClientRequest.post(subscription.url).pipe( ++ HttpClientRequest.setHeaders({ ++ "webhook-id": webhookId, ++ "webhook-timestamp": String(timestamp), ++ "webhook-signature": yield* sign(keys, webhookId, timestamp, body), ++ "x-mcp-subscription-id": subscription.id ++ }), ++ HttpClientRequest.bodyText(body, "application/json") ++ ); ++ const outcome = yield* client.execute(request).pipe( ++ Effect.flatMap((response) => { ++ if (response.status < 200 || response.status >= 300) { ++ return Effect.succeed({ ++ _tag: "Failed", ++ category: statusCategory(response.status), ++ retryable: response.status !== 410 && response.status !== 413 ++ }); ++ } ++ return readBody ? Effect.map(readCapped(response), (text) => ({ _tag: "Delivered", body: text })) : Effect.succeed({ _tag: "Delivered", body: void 0 }); ++ }), ++ Effect.timeoutOption(Duration.millis(REQUEST_TIMEOUT_MS)), ++ Effect.scoped, ++ // `fetch` would follow a redirect itself; webhook delivery never does. ++ Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }), ++ // Trace ids stay inside: the endpoint belongs to someone else. ++ Effect.provideService(HttpClient.TracerPropagationEnabled, false), ++ Effect.catch( ++ (error) => Effect.succeed(Option.some({ _tag: "Failed", category: transportCategory(error), retryable: true })) ++ ) ++ ); ++ return Option.getOrElse(outcome, () => ({ _tag: "Failed", category: "timeout", retryable: true })); ++ }); ++ const deliver = Effect.fnUntraced(function* (subscription, body, webhookId) { ++ for (let attempt = 1; ; attempt++) { ++ const current = subscriptions.get(subscription.id); ++ if (current !== void 0 && current !== subscription) return false; ++ const startedAt = yield* Clock.currentTimeMillis; ++ const outcome = yield* send(subscription, body, webhookId, false); ++ if (outcome._tag === "Delivered") { ++ subscription.lastDeliveryAt = yield* Clock.currentTimeMillis; ++ subscription.lastError = void 0; ++ return true; ++ } ++ subscription.lastError = outcome.category; ++ if (!outcome.retryable || attempt >= MAX_ATTEMPTS) return false; ++ const wait = startedAt + FIRST_RETRY_MS * 2 ** (attempt - 1) - (yield* Clock.currentTimeMillis); ++ if (wait > 0) yield* Effect.sleep(Duration.millis(wait)); ++ } ++ }); ++ const control = (subscription, type, fields) => Effect.flatMap( ++ messageId(`msg_${type}`), ++ (webhookId) => deliver(subscription, JSON.stringify({ type, ...fields }), webhookId) ++ ); ++ const run = (subscription, name, events) => events.items.pipe( ++ Stream.runForEach((item) => { ++ switch (item._tag) { ++ case "Event": ++ return Effect.flatMap(deliveryId(subscription, item.eventId), (webhookId) => { ++ const body = JSON.stringify({ ++ eventId: webhookId, ++ name, ++ timestamp: item.timestamp, ++ data: item.data, ++ cursor: item.cursor, ++ ...item._meta === void 0 ? {} : { _meta: item._meta } ++ }); ++ return deliver(subscription, body, webhookId); ++ }).pipe(Effect.andThen(Effect.sync(() => advance(subscription, item.cursor)))); ++ case "Position": ++ return Effect.sync(() => advance(subscription, item.cursor)); ++ case "Gap": ++ return control(subscription, "gap", { cursor: item.cursor }).pipe( ++ Effect.map((delivered) => { ++ if (!delivered) subscription.cursorsSinceGap = /* @__PURE__ */ new Set(); ++ advance(subscription, item.cursor); ++ }) ++ ); ++ case "Error": ++ return Effect.void; ++ } ++ }), ++ // Ended before it says so, so a refresh meanwhile starts afresh instead of reporting it live. ++ Effect.catch( ++ (failure) => Effect.suspend(() => { ++ forget(subscription); ++ return control(subscription, "terminated", { error: wireError(failure) }); ++ }) ++ ) ++ ); ++ const expiry = (subscription) => Effect.gen(function* () { ++ while (true) { ++ const left = subscription.expiresAt - (yield* Clock.currentTimeMillis); ++ if (left <= 0) return forget(subscription); ++ yield* Effect.raceFirst(Effect.sleep(Duration.millis(left)), Deferred.await(subscription.deadlineMoved)); ++ } ++ }); ++ const handshake = Effect.fnUntraced(function* (subscription) { ++ const challenge = Base64Url.encode(yield* random.randomBytes(32)); ++ const outcome = yield* send( ++ subscription, ++ JSON.stringify({ type: "verification", challenge }), ++ yield* messageId("msg_verification"), ++ true ++ ); ++ if (outcome._tag === "Failed") return yield* Effect.fail(outcome.category); ++ const echoed = outcome.body === void 0 ? void 0 : echoedChallenge(outcome.body); ++ if (echoed === void 0 || !Mac.timingSafeEqual(encoder.encode(echoed), encoder.encode(challenge))) { ++ return yield* Effect.fail("challenge_failed"); ++ } ++ }); ++ const verify = Effect.fnUntraced(function* (subscription) { ++ const key = JSON.stringify([subscription.principal, subscription.url.href]); ++ const now = yield* Clock.currentTimeMillis; ++ for (const [entry, until] of verified) if (until <= now) verified.delete(entry); ++ for (const [entry, failure2] of failedVerifications) if (failure2.until <= now) failedVerifications.delete(entry); ++ if (verified.has(key)) return; ++ const failure = failedVerifications.get(key); ++ if (failure !== void 0) return yield* callbackError(failure.category); ++ const inFlight = verifying.get(key); ++ if (inFlight !== void 0) return yield* Deferred.await(inFlight); ++ const host = subscription.url.hostname; ++ const recent = (verificationsByHost.get(host) ?? []).filter((at) => at > now - MINUTE_MS); ++ if (recent.length >= VERIFICATIONS_PER_HOST_PER_MINUTE) { ++ verificationsByHost.set(host, recent); ++ return yield* new PublicMcpSchema.ResourceExhausted({ ++ message: "Too many callback verifications for this host", ++ data: { limit: "verifications", max: VERIFICATIONS_PER_HOST_PER_MINUTE } ++ }); ++ } ++ for (const [entry, times] of verificationsByHost) { ++ if (times.every((at) => at <= now - MINUTE_MS)) verificationsByHost.delete(entry); ++ } ++ verificationsByHost.set(host, [...recent, now]); ++ const done = Deferred.makeUnsafe(); ++ verifying.set(key, done); ++ return yield* handshake(subscription).pipe( ++ Effect.tap( ++ () => Effect.map(Clock.currentTimeMillis, (at) => { ++ verified.set(key, at + VERIFIED_FOR_MS); ++ }) ++ ), ++ Effect.tapError( ++ (category) => Effect.map(Clock.currentTimeMillis, (at) => { ++ failedVerifications.set(key, { until: at + FAILED_FOR_MS, category }); ++ }) ++ ), ++ Effect.mapError(callbackError), ++ Effect.onExit( ++ (exit) => Effect.sync(() => { ++ verifying.delete(key); ++ Deferred.doneUnsafe(done, exit); ++ }) ++ ) ++ ); ++ }); ++ const refresh = Effect.fnUntraced(function* (request, subscription, secret, expiresAt, now) { ++ const opening = !Deferred.isDoneUnsafe(subscription.accepted); ++ const start = yield* Deferred.await(subscription.accepted); ++ if (subscriptions.get(subscription.id) !== subscription) return yield* subscribe(request); ++ if (subscription.secret !== secret.text) { ++ subscription.previous = { key: subscription.key, until: now + ROTATION_GRACE_MS }; ++ subscription.secret = secret.text; ++ subscription.key = secret.key; ++ } ++ subscription.expiresAt = expiresAt; ++ const moved = subscription.deadlineMoved; ++ subscription.deadlineMoved = Deferred.makeUnsafe(); ++ Deferred.doneUnsafe(moved, Effect.void); ++ if (opening) return { id: subscription.id, refreshBefore: iso(expiresAt), ...start }; ++ const since = subscription.cursorsSinceGap; ++ if (since !== void 0 && since.has(request.cursor)) subscription.cursorsSinceGap = void 0; ++ const truncated = subscription.cursorsSinceGap !== void 0; ++ return { ++ id: subscription.id, ++ refreshBefore: iso(expiresAt), ++ cursor: subscription.watermark, ++ truncated, ++ deliveryStatus: { ++ active: true, ++ lastDeliveryAt: subscription.lastDeliveryAt === void 0 ? null : iso(subscription.lastDeliveryAt), ++ lastError: subscription.lastError ?? null ++ } ++ }; ++ }); ++ const subscribe = Effect.fnUntraced(function* (request) { ++ const principal = yield* options.principal; ++ const mode = request.delivery.mode; ++ if (mode !== void 0 && mode !== "webhook") return yield* invalid("delivery.mode must be 'webhook'"); ++ const url = yield* parseUrl(request.delivery.url, guard); ++ const secret = yield* parseSecret(request.delivery.secret); ++ const id = yield* subscriptionId(principal, url, request.name, request.arguments); ++ const now = yield* Clock.currentTimeMillis; ++ const expiresAt = now + grantTtl(request.ttlMs); ++ const live = subscriptions.get(id); ++ if (live !== void 0) return yield* refresh(request, live, secret, expiresAt, now); ++ let held = pending.get(principal) ?? 0; ++ for (const subscription of subscriptions.values()) if (subscription.principal === principal) held++; ++ if (held >= MAX_SUBSCRIPTIONS_PER_PRINCIPAL) { ++ return yield* new PublicMcpSchema.ResourceExhausted({ ++ message: "Too many webhook subscriptions", ++ data: { limit: "subscriptions", max: MAX_SUBSCRIPTIONS_PER_PRINCIPAL } ++ }); ++ } ++ pending.set(principal, (pending.get(principal) ?? 0) + 1); ++ let reserved = true; ++ const release = () => { ++ if (!reserved) return; ++ reserved = false; ++ const left = (pending.get(principal) ?? 1) - 1; ++ if (left === 0) pending.delete(principal); ++ else pending.set(principal, left); ++ }; ++ return yield* create(request, { principal, url, secret, id, expiresAt, now, release }).pipe( ++ Effect.ensuring(Effect.sync(release)) ++ ); ++ }); ++ const create = Effect.fnUntraced(function* (request, { expiresAt, id, now, principal, release, secret, url }) { ++ yield* Effect.mapError(guard.check(url), () => invalid("delivery.url is not allowed")); ++ const subscription = { ++ id, ++ principal, ++ url, ++ secret: secret.text, ++ key: secret.key, ++ previous: void 0, ++ expiresAt, ++ watermark: request.cursor, ++ lastDeliveryAt: void 0, ++ lastError: void 0, ++ fiber: void 0, ++ deadlineMoved: Deferred.makeUnsafe(), ++ accepted: Deferred.makeUnsafe(), ++ cursorsSinceGap: void 0 ++ }; ++ const decoded = yield* request.decode; ++ yield* verify(subscription); ++ const raced = subscriptions.get(id); ++ if (raced !== void 0) { ++ release(); ++ return yield* refresh(request, raced, secret, expiresAt, now); ++ } ++ release(); ++ subscriptions.set(id, subscription); ++ const { accepted } = subscription; ++ const lifetime = request.open( ++ decoded, ++ (events) => Effect.suspend(() => { ++ subscription.watermark = events.cursor; ++ return Deferred.succeed(accepted, { cursor: events.cursor, truncated: events.truncated }); ++ }).pipe(Effect.andThen(run(subscription, request.name, events))) ++ ).pipe( ++ Effect.tapError((failure) => Deferred.fail(accepted, failure)), ++ Effect.raceFirst(expiry(subscription)), ++ Effect.ignore, ++ Effect.ensuring(Effect.suspend(() => { ++ forget(subscription); ++ return Deferred.fail(accepted, new PublicMcpSchema.InternalError({ message: "The subscription ended" })); ++ })) ++ ); ++ subscription.fiber = yield* Effect.forkIn(lifetime, scope); ++ const start = yield* Deferred.await(accepted); ++ return { id, refreshBefore: iso(expiresAt), cursor: start.cursor, truncated: start.truncated }; ++ }); ++ const unsubscribe = Effect.fnUntraced(function* (request) { ++ const principal = yield* options.principal; ++ const url = yield* parseUrl(request.delivery.url, guard); ++ const id = yield* subscriptionId(principal, url, request.name, request.arguments); ++ const subscription = subscriptions.get(id); ++ if (subscription === void 0) { ++ return yield* new PublicMcpSchema.NotFound({ ++ message: "No webhook subscription matches", ++ data: { kind: "subscription" } ++ }); ++ } ++ subscriptions.delete(id); ++ if (subscription.fiber !== void 0) yield* Fiber.interrupt(subscription.fiber); ++ }); ++ return { ++ subscribe, ++ unsubscribe, ++ size: Effect.sync(() => subscriptions.size) ++ }; ++}); ++export { ++ DEFAULT_TTL_MS, ++ MAX_ATTEMPTS, ++ MAX_TTL_MS, ++ MIN_TTL_MS, ++ canonicalJson, ++ grantTtl, ++ make ++}; diff --git a/src/ai/McpSchema.ts b/src/ai/McpSchema.ts index ba6c830..1e58fb9 100644 --- a/src/ai/McpSchema.ts @@ -1419,10 +2113,35 @@ index ba6c830..1e58fb9 100644 // Prompts // ============================================================================= diff --git a/src/ai/McpServer.ts b/src/ai/McpServer.ts -index 4c2e191..3bf4321 100644 +index 4c2e191..bedd064 100644 --- a/src/ai/McpServer.ts +++ b/src/ai/McpServer.ts -@@ -344,6 +344,9 @@ export type MiddlewareMethod = +@@ -16,6 +16,8 @@ import * as Cause from "../Cause.ts" + import * as Clock from "../Clock.ts" + import * as Context from "../Context.ts" + import * as Digest from "../crypto/Digest.ts" ++import * as Mac from "../crypto/Mac.ts" ++import * as SecureRandom from "../crypto/SecureRandom.ts" + import * as Data from "../Data.ts" + import * as Deferred from "../Deferred.ts" + import * as Duration from "../Duration.ts" +@@ -26,6 +28,7 @@ import * as Exit from "../Exit.ts" + import * as Fiber from "../Fiber.ts" + import * as FindMyWay from "../http/FindMyWay.ts" + import * as Headers from "../http/Headers.ts" ++import * as HttpClient from "../http/HttpClient.ts" + import { appendPreResponseHandlerUnsafe } from "../http/HttpEffect.ts" + import * as HttpRouter from "../http/HttpRouter.ts" + import * as HttpServerRequest from "../http/HttpServerRequest.ts" +@@ -59,6 +62,7 @@ import * as McpCore from "./internal/mcpCore.ts" + import * as McpProtocolInternal from "./internal/mcpProtocol.ts" + import * as McpRuntime from "./internal/mcpRuntime.ts" + import * as McpSkills from "./internal/mcpSkills.ts" ++import * as McpWebhooks from "./internal/mcpWebhooks.ts" + import * as InternalStructuredOutput from "./internal/structured-output.ts" + import type * as McpProtocol from "./McpProtocol.ts" + import * as McpSchema from "./McpSchema.ts" +@@ -344,6 +348,9 @@ export type MiddlewareMethod = | "skills/list" | "skills/get" | "resources/directory/read" @@ -1432,7 +2151,7 @@ index 4c2e191..3bf4321 100644 /** * Request metadata passed to MCP middleware. -@@ -819,7 +822,14 @@ const internalError = new InternalError({ message: "Internal error" }) +@@ -819,7 +826,14 @@ const internalError = new InternalError({ message: "Internal error" }) const rejectWith = (error: McpErrorBase) => Effect.fail(new McpCore.RequestRejected({ code: error.code, message: error.message, data: error.data, error })) @@ -1448,7 +2167,7 @@ index 4c2e191..3bf4321 100644 type ListMethod = Exclude -@@ -829,6 +839,8 @@ interface NotFoundErrors { +@@ -829,6 +843,8 @@ interface NotFoundErrors { readonly "prompts/get": McpCore.PromptNotFound readonly "completion/complete": InvalidParams readonly "skills/get": McpCore.SkillNotFound @@ -1457,7 +2176,7 @@ index 4c2e191..3bf4321 100644 } const notFound = (method: CallMethod, target: string): NotFoundErrors[CallMethod] => { -@@ -843,6 +855,9 @@ const notFound = (method: CallMethod, target: string): NotFoundErrors[CallMethod +@@ -843,6 +859,9 @@ const notFound = (method: CallMethod, target: string): NotFoundErrors[CallMethod return new InvalidParams({ message: "Unknown completion reference or argument" }) case "skills/get": return new McpCore.SkillNotFound({ uri: target }) @@ -1467,7 +2186,7 @@ index 4c2e191..3bf4321 100644 } } -@@ -4134,6 +4149,276 @@ export const registerSkill: (options: SkillOptions) => Effect.Effect Effect.Effect => Layer.effectDiscard(registerSkill(options)) @@ -1589,8 +2308,8 @@ index 4c2e191..3bf4321 100644 + * `parameters` types the subscription arguments, an empty object by default, + * and `payload` the occurrences' `data`; both are advertised as JSON Schema + * by `events/list`. `poll` offers poll delivery and `stream` push delivery, -+ * and at least one is required. Webhook delivery is not supported, so -+ * `events/subscribe` answers `Unsupported`. ++ * and at least one is required. With {@link EventWebhooks} provided where the ++ * event is registered, `stream` also backs webhook delivery. + * + * @stability unstable + * @category events @@ -1626,7 +2345,8 @@ index 4c2e191..3bf4321 100644 + * + * The server declares `io.modelcontextprotocol/events` on revision + * `2026-07-28` once any event type is registered, and answers `events/list`, -+ * `events/poll` and `events/stream`. A push stream runs `stream` for its ++ * `events/poll`, `events/stream`, and with {@link EventWebhooks} ++ * `events/subscribe` and `events/unsubscribe`. A push stream runs `stream` for its + * lifetime inside the request's middleware, sends heartbeats carrying the + * last cursor, and ends when the client goes away. Services read by `poll` + * and `stream` are request-level, as for tools. @@ -1650,6 +2370,9 @@ index 4c2e191..3bf4321 100644 + const services = yield* Effect.context() + const annotations = options.annotations ?? Context.empty() + const { invoke, visible } = makeInvoke(services, globalMiddleware) ++ const webhooks = stream === undefined ++ ? undefined ++ : Option.getOrUndefined(Option.map(Context.getOption(services, EventWebhooks), (service) => webhooksState.get(service))) + const parameters = options.parameters ?? Schema.Struct({}) + const decodeArguments = Schema.decodeUnknownEffect(Schema.toCodecJson(parameters)) + const encodePayload = Schema.encodeUnknownEffect(Schema.toCodecJson(options.payload)) @@ -1670,13 +2393,19 @@ index 4c2e191..3bf4321 100644 + descriptor: { + name, + ...(options.description === undefined ? {} : { description: options.description }), -+ delivery: [...(poll === undefined ? [] : ["poll" as const]), ...(stream === undefined ? [] : ["push" as const])], ++ delivery: [ ++ ...(poll === undefined ? [] : ["poll" as const]), ++ ...(stream === undefined ? [] : ["push" as const]), ++ ...(webhooks === undefined ? [] : ["webhook" as const]) ++ ], + inputSchema: toolJsonSchema(parameters, false) as Record, + payloadSchema: toolJsonSchema(options.payload, false) as Record, + ...(options._meta === undefined ? {} : { _meta: options._meta }) + }, + isVisible: isEnabled(annotations), + visible: visible("events/list", name), ++ webhooks, ++ decodeArguments: argumentsOf, + poll: poll === undefined ? undefined : (request, invocation) => + invoke( + Effect.gen(function*() { @@ -1699,7 +2428,10 @@ index 4c2e191..3bf4321 100644 + stream: stream === undefined ? undefined : (request, invocation, deliver) => + invoke( + Effect.scoped(Effect.gen(function*() { -+ const subscription = yield* stream(yield* argumentsOf(request.arguments), { ++ const args = request.decoded !== undefined ++ ? request.decoded.value ++ : yield* argumentsOf(request.arguments) ++ const subscription = yield* stream(args, { + cursor: request.cursor, + maxAgeMs: request.maxAgeMs + }) @@ -1740,23 +2472,139 @@ index 4c2e191..3bf4321 100644 + R = never +>(options: EventOptions): Layer.Layer> => + Layer.effectDiscard(registerEvent(options)) ++ ++/** ++ * The reason a {@link CallbackGuard} refuses a callback URL. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export class CallbackRejected extends Data.TaggedError("CallbackRejected")<{ ++ readonly message: string ++}> {} ++ ++/** ++ * Decides which webhook callback URLs may be reached. ++ * ++ * **Details** ++ * ++ * `check` runs when a subscription is created and again before every POST. ++ * Resolving a host name needs the platform, so the default refuses every URL: ++ * a server that offers webhooks provides a guard that resolves the host and ++ * refuses addresses that are not globally routable. That check alone cannot ++ * stop DNS rebinding, so the `HttpClient` given to {@link layerEventWebhooks} ++ * must connect only to the address it validated, sending the original host ++ * name in `Host` and TLS SNI, and must not follow redirects. `allowsPlaintext` ++ * admits an `http:` URL, which only a local test setup should do. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const CallbackGuard = Context.Reference<{ ++ readonly check: (url: URL) => Effect.Effect ++ readonly allowsPlaintext?: ((url: URL) => boolean) | undefined ++}>("effect/ai/McpServer/CallbackGuard", { ++ defaultValue: () => ({ ++ check: (url) => Effect.fail(new CallbackRejected({ message: `No callback guard admits ${url.host}` })) ++ }) ++}) ++ ++/** ++ * Webhook delivery for event types under the MCP Events extension (SEP-3415). ++ * ++ * **Details** ++ * ++ * Event types registered with a `stream` where this service is present also ++ * offer webhook delivery. `events/subscribe` validates the callback, verifies ++ * the endpoint with a challenge, and runs the event's `stream` for the ++ * subscription's lifetime, POSTing each occurrence with Standard Webhooks ++ * signatures, one at a time, retrying with backoff. Subscriptions live in ++ * memory: every grant is finite, between a minute and an hour, so a client ++ * refreshing from its cursor recreates what a restart lost. A failure of the ++ * stream, such as `Forbidden` when access is revoked, ends the subscription ++ * with a `terminated` envelope. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export class EventWebhooks extends Context.Service ++}>()("effect/ai/McpServer/EventWebhooks") {} ++ ++const webhooksState = new WeakMap() ++ ++/** ++ * Options for {@link layerEventWebhooks}. ++ * ++ * **Details** ++ * ++ * `principal` names the authenticated subject of an `events/subscribe` or ++ * `events/unsubscribe` request, read from the request's services. It fails ++ * with `Forbidden` for a caller that may not subscribe; webhook delivery ++ * requires an authenticated principal. A subscription's identity is its ++ * principal, callback URL, event name and arguments, so the principal must ++ * stay the same across token refreshes. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventWebhooksOptions { ++ readonly principal: Effect.Effect ++} ++ ++/** ++ * Provides {@link EventWebhooks}, delivering through the given `HttpClient` ++ * and admitting callbacks through the current {@link CallbackGuard}. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const layerEventWebhooks = ( ++ options: EventWebhooksOptions ++): Layer.Layer => ++ Layer.effect( ++ EventWebhooks, ++ Effect.gen(function*() { ++ const webhooks = yield* McpWebhooks.make({ ++ principal: options.principal, ++ guard: yield* CallbackGuard, ++ client: yield* HttpClient.HttpClient ++ }) ++ const service = EventWebhooks.of({ size: webhooks.size }) ++ webhooksState.set(service, webhooks) ++ return service ++ }).pipe( ++ Effect.provide( ++ Layer.mergeAll(Mac.layerWebCrypto, Digest.layerWebCrypto).pipe( ++ Layer.provideMerge(SecureRandom.layerWebCrypto) ++ ) ++ ) ++ ) ++ ) + /** * Registers an MCP prompt from an Effect program. * diff --git a/src/ai/internal/mcpCore.ts b/src/ai/internal/mcpCore.ts -index 643982d..597701f 100644 +index 643982d..d705160 100644 --- a/src/ai/internal/mcpCore.ts +++ b/src/ai/internal/mcpCore.ts -@@ -8,6 +8,7 @@ import * as Data from "../../Data.ts" +@@ -8,6 +8,8 @@ import * as Data from "../../Data.ts" import * as Effect from "../../Effect.ts" import type * as McpProtocol from "../McpProtocol.ts" import * as McpSchema from "../McpSchema.ts" +import type * as Stream from "../../Stream.ts" ++import type * as McpWebhooks from "./mcpWebhooks.ts" /** * @internal -@@ -330,6 +331,118 @@ export interface SkillRegistration { +@@ -330,6 +332,123 @@ export interface SkillRegistration { readonly directory: (uri: string) => ReadonlyArray | undefined } @@ -1810,6 +2658,8 @@ index 643982d..597701f 100644 + */ +export interface EventStreamRequest { + readonly arguments: Readonly> ++ // Set when the arguments were already decoded, as a webhook subscribe does first. ++ readonly decoded?: { readonly value: unknown } | undefined + readonly cursor: string | null + readonly maxAgeMs?: number | undefined +} @@ -1846,6 +2696,9 @@ index 643982d..597701f 100644 + readonly descriptor: McpSchema.EventDescriptor + readonly isVisible: (profile: NegotiatedProtocolProfile) => boolean + readonly visible?: Visible | undefined ++ // Set when webhook delivery is offered, which runs `stream`. ++ readonly webhooks?: McpWebhooks.Webhooks | undefined ++ readonly decodeArguments: (args: unknown) => Effect.Effect + readonly poll?: + | (( + request: EventPollRequest, @@ -1875,7 +2728,7 @@ index 643982d..597701f 100644 /** * @internal */ -@@ -507,11 +620,13 @@ export interface McpCore { +@@ -507,11 +626,13 @@ export interface McpCore { readonly prompts: Prompts readonly completions: Completions readonly skills: Skills @@ -1889,7 +2742,7 @@ index 643982d..597701f 100644 }> } -@@ -523,6 +638,12 @@ export interface McpCore { +@@ -523,6 +644,12 @@ export interface McpCore { */ export type Visible = (invocation: McpInvocation) => Effect.Effect @@ -1902,7 +2755,7 @@ index 643982d..597701f 100644 // Whether one skill directory contains the other, or both are the same. const skillsOverlap = (a: string, b: string): boolean => { const rootA = a.slice(0, -"/SKILL.md".length) -@@ -539,6 +660,7 @@ export const make: Effect.Effect = Effect.sync(() => { +@@ -539,6 +666,7 @@ export const make: Effect.Effect = Effect.sync(() => { const resourceTemplateRegistrations: Array = [] const promptRegistrations = new Map() const skillRegistrations = new Map() @@ -1910,7 +2763,7 @@ index 643982d..597701f 100644 const skillFiles = new Set() const completionRegistrations = new Map< string, -@@ -717,12 +839,28 @@ export const make: Effect.Effect = Effect.sync(() => { +@@ -717,12 +845,28 @@ export const make: Effect.Effect = Effect.sync(() => { }) } @@ -2275,7 +3128,7 @@ index 5393651..f40915b 100644 } diff --git a/src/ai/internal/mcpProtocol/v2026_07_28.ts b/src/ai/internal/mcpProtocol/v2026_07_28.ts -index a701ec8..9b9a6fd 100644 +index a701ec8..8e4b36a 100644 --- a/src/ai/internal/mcpProtocol/v2026_07_28.ts +++ b/src/ai/internal/mcpProtocol/v2026_07_28.ts @@ -22,6 +22,7 @@ import type * as Types from "../../../Types.ts" @@ -2299,16 +3152,18 @@ index a701ec8..9b9a6fd 100644 /** * @internal -@@ -370,6 +375,8 @@ export const makeHandlers = ( +@@ -370,6 +375,10 @@ export const makeHandlers = ( const decodeListSkillsResult = Schema.decodeUnknownEffect(McpSkills.ListSkillsResult) const decodeGetSkillResult = Schema.decodeUnknownEffect(McpSkills.GetSkillResult) const decodeReadResourceDirectoryResult = Schema.decodeUnknownEffect(McpSkills.ReadResourceDirectoryResult) + const decodeListEventsResult = Schema.decodeUnknownEffect(McpEvents.ListEventsResult) + const decodePollEventsResult = Schema.decodeUnknownEffect(McpEvents.PollEventsResult) ++ const decodeSubscribeEventsResult = Schema.decodeUnknownEffect(McpEvents.SubscribeEvents.successSchema) ++ const decodeUnsubscribeEventsResult = Schema.decodeUnknownEffect(McpEvents.UnsubscribeEvents.successSchema) const sendNotification = context.sendNotification const supportsSubscriptions = sendNotification !== undefined // Older adapters accept arbitrary JSON; this binding requires extension settings objects. -@@ -384,7 +391,10 @@ export const makeHandlers = ( +@@ -384,8 +393,14 @@ export const makeHandlers = ( } const getDiscovery = Effect.map(context.registrationPresence, (presence) => { const capabilities: Types.Mutable = { completions: {}, logging: {} } @@ -2318,9 +3173,13 @@ index a701ec8..9b9a6fd 100644 + presence.events + ) if (declared !== undefined) capabilities.extensions = declared ++ // Bridge for clients predating SEP-3415 (ChatGPT, @ai-sdk/mcp); drop per #41158. ++ // They look for a top-level `events` capability instead of the extension. ++ if (presence.events) capabilities.events = {} if (presence.tools) capabilities.tools = { listChanged: supportsSubscriptions } if (presence.resources) { -@@ -393,6 +403,24 @@ export const makeHandlers = ( + capabilities.resources = { listChanged: supportsSubscriptions, subscribe: supportsSubscriptions } +@@ -393,6 +408,30 @@ export const makeHandlers = ( if (presence.prompts) capabilities.prompts = { listChanged: supportsSubscriptions } return { supportedVersions: context.supportedVersions, capabilities, serverInfo: context.serverInfo } }) @@ -2336,16 +3195,22 @@ index a701ec8..9b9a6fd 100644 + yield* validateParameterHeaders(registration.descriptor.inputSchema, args, httpRequest.value.headers) + } + }) -+ // Webhook delivery is not implemented, so subscribing refuses every event type. -+ const refuseWebhook = Effect.fnUntraced(function*(method: string, name: string) { ++ // Webhook delivery runs the event's push stream, so it needs both. ++ const webhookRegistration = Effect.fnUntraced(function*(method: string, name: string, args: unknown) { + yield* requireEvents(method) -+ yield* core.events.get(name, yield* getInvocation) -+ return yield* McpEvents.unsupportedDelivery("webhook") ++ const invocation = yield* getInvocation ++ const registration = yield* core.events.get(name, invocation) ++ const { stream, webhooks } = registration ++ if (webhooks === undefined || stream === undefined) { ++ return yield* McpEvents.unsupportedDelivery("webhook") ++ } ++ yield* validateEventHeaders(registration, args) ++ return { invocation, stream, webhooks, decodeArguments: registration.decodeArguments } + }) const requireSkills = (method: string) => McpSkills.requireSkills(core, method).pipe( Effect.catch((error) => failWithHttpStatus(404, error)) -@@ -728,6 +756,92 @@ export const makeHandlers = ( +@@ -728,6 +767,121 @@ export const makeHandlers = ( const result = yield* projectCompleteResult({ ...cacheHint("skills"), resources }, context.serverInfo) return yield* decodeReadResourceDirectoryResult(result) }, Effect.mapError(projectError)), @@ -2428,17 +3293,46 @@ index a701ec8..9b9a6fd 100644 + }) + }, Effect.mapError(projectError)), + "events/subscribe": Effect.fnUntraced(function*(request: typeof McpEvents.SubscribeEvents.payloadSchema.Type) { -+ return yield* refuseWebhook("events/subscribe", request.name) ++ const { decodeArguments, invocation, stream, webhooks } = yield* webhookRegistration( ++ "events/subscribe", ++ request.name, ++ request.arguments ++ ) ++ const args = request.arguments ?? {} ++ const cursor = request.cursor ?? null ++ const subscribed = yield* webhooks.subscribe({ ++ name: request.name, ++ arguments: args, ++ delivery: request.delivery, ++ cursor, ++ ttlMs: request.ttlMs, ++ decode: decodeArguments(args), ++ open: (decoded, deliver) => ++ stream( ++ { arguments: args, decoded: { value: decoded }, cursor, maxAgeMs: request.maxAgeMs }, ++ invocation, ++ deliver ++ ) ++ }) ++ const result = yield* projectCompleteResult(omitUndefined({ ...subscribed }), context.serverInfo) ++ return yield* decodeSubscribeEventsResult(result) + }, Effect.mapError(projectError)), + "events/unsubscribe": Effect.fnUntraced(function*( + request: typeof McpEvents.UnsubscribeEvents.payloadSchema.Type + ) { -+ return yield* refuseWebhook("events/unsubscribe", request.name) ++ const { webhooks } = yield* webhookRegistration("events/unsubscribe", request.name, request.arguments) ++ yield* webhooks.unsubscribe({ ++ name: request.name, ++ arguments: request.arguments ?? {}, ++ delivery: request.delivery ++ }) ++ const result = yield* projectCompleteResult({}, context.serverInfo) ++ return yield* decodeUnsubscribeEventsResult(result) + }, Effect.mapError(projectError)), "notifications/cancelled": Effect.fnUntraced(function*( _request: typeof McpSchema.CancelledNotification.payloadSchema.Type ) { -@@ -751,10 +865,10 @@ const runtime = { +@@ -751,10 +905,10 @@ const runtime = { export const protocol = McpProtocol.make({ protocolVersion: McpSchema.protocolVersion, runtime, @@ -2452,7 +3346,7 @@ index a701ec8..9b9a6fd 100644 makeHandlers, toReverseClient: () => ({ diff --git a/src/ai/internal/mcpRuntime.ts b/src/ai/internal/mcpRuntime.ts -index 9d4c96e..eb0590c 100644 +index 9d4c96e..0afe3ed 100644 --- a/src/ai/internal/mcpRuntime.ts +++ b/src/ai/internal/mcpRuntime.ts @@ -53,6 +53,10 @@ const routingNameKey = (method: string): "name" | "uri" | undefined => { @@ -2466,7 +3360,22 @@ index 9d4c96e..eb0590c 100644 return "name" case "resources/read": return "uri" -@@ -479,7 +483,9 @@ export const make = Effect.fnUntraced(function*( +@@ -319,7 +323,13 @@ export const make = Effect.fnUntraced(function*( + if (nameKey !== undefined) { + const name = asRecord(inputRecord?.params)?.[nameKey] + const header = headers[MCP_NAME_HEADER] +- if (typeof name !== "string" || header === undefined || McpProtocol.decodeRoutingHeader(header) !== name) { ++ // Bridge for clients predating SEP-3415 (ChatGPT, @ai-sdk/mcp); drop per #41158. ++ // They send no Mcp-Name on these; one they do send must still match. ++ const optional = header === undefined && (method === "events/subscribe" || method === "events/unsubscribe") ++ if ( ++ !optional && ++ (typeof name !== "string" || header === undefined || McpProtocol.decodeRoutingHeader(header) !== name) ++ ) { + return headerMismatch("Mcp-Name header does not match request parameters") + } + } +@@ -479,7 +489,9 @@ export const make = Effect.fnUntraced(function*( return { _tag: "Accepted", acknowledge: !isRequest || !hasId, @@ -2477,3 +3386,701 @@ index 9d4c96e..eb0590c 100644 } }, effectLogLevel: (clientId, headers, fallback) => stateful?.effectLogLevel(clientId, headers, fallback) ?? fallback, +diff --git a/src/ai/internal/mcpWebhooks.ts b/src/ai/internal/mcpWebhooks.ts +new file mode 100644 +index 0000000..5b53d08 +--- /dev/null ++++ b/src/ai/internal/mcpWebhooks.ts +@@ -0,0 +1,692 @@ ++/** ++ * Webhook delivery for the Events extension (SEP-3415): `events/subscribe` ++ * validation, subscription identity, Standard Webhooks signing, the endpoint ++ * verification handshake and the delivery loop. ++ * ++ * Subscriptions live in memory. Every grant is finite, so a subscription lost ++ * in a restart comes back on the client's next refresh, from its cursor. ++ */ ++import * as Clock from "../../Clock.ts" ++import * as Digest from "../../crypto/Digest.ts" ++import * as Mac from "../../crypto/Mac.ts" ++import * as SecureRandom from "../../crypto/SecureRandom.ts" ++import * as Deferred from "../../Deferred.ts" ++import * as Duration from "../../Duration.ts" ++import * as Effect from "../../Effect.ts" ++import * as Base64 from "../../encoding/Base64.ts" ++import * as Base64Url from "../../encoding/Base64Url.ts" ++import * as Fiber from "../../Fiber.ts" ++import * as FetchHttpClient from "../../http/FetchHttpClient.ts" ++import * as HttpClient from "../../http/HttpClient.ts" ++import * as HttpClientRequest from "../../http/HttpClientRequest.ts" ++import type * as HttpClientResponse from "../../http/HttpClientResponse.ts" ++import * as Option from "../../Option.ts" ++import * as Result from "../../Result.ts" ++import * as Stream from "../../Stream.ts" ++import * as PublicMcpSchema from "../McpSchema.ts" ++import type * as McpCore from "./mcpCore.ts" ++import { wireError } from "./mcpEvents.ts" ++ ++const MINUTE_MS = 60_000 ++/** @internal */ ++export const MIN_TTL_MS = MINUTE_MS ++// Short grants because subscriptions live in memory: a restart loses them until the next refresh. ++/** @internal */ ++export const MAX_TTL_MS = 60 * MINUTE_MS ++/** @internal */ ++export const DEFAULT_TTL_MS = 15 * MINUTE_MS ++/** @internal */ ++export const MAX_ATTEMPTS = 5 ++// Retries wait 30 s, 1, 2 and 4 minutes: about 7.5 minutes in all. ++const FIRST_RETRY_MS = 30_000 ++const REQUEST_TIMEOUT_MS = 10_000 ++// Deliveries signed with the old secret before a rotation still verify for this long. ++const ROTATION_GRACE_MS = 5 * MINUTE_MS ++const VERIFIED_FOR_MS = MAX_TTL_MS ++// A failed challenge is answered from here, so repeated subscribes cannot flood the endpoint. ++const FAILED_FOR_MS = 5 * MINUTE_MS ++// Verification POSTs one destination host receives per minute, across all principals. ++const VERIFICATIONS_PER_HOST_PER_MINUTE = 10 ++const MAX_SUBSCRIPTIONS_PER_PRINCIPAL = 100 ++// A verification reads this many bytes of the response at most; a delivery reads none. ++const MAX_CHALLENGE_RESPONSE_BYTES = 8_192 ++const SECRET_PREFIX = "whsec_" ++ ++/** ++ * The fixed categories `deliveryStatus.lastError` and `CallbackEndpointError` ++ * report; never the endpoint's own response. ++ * ++ * @internal ++ */ ++export type FailureCategory = ++ | "connection_refused" ++ | "timeout" ++ | "tls_error" ++ | "http_4xx" ++ | "http_5xx" ++ | "challenge_failed" ++ ++/** ++ * @internal ++ */ ++export interface Guard { ++ readonly check: (url: URL) => Effect.Effect ++ readonly allowsPlaintext?: ((url: URL) => boolean) | undefined ++} ++ ++/** ++ * @internal ++ */ ++export interface Options { ++ readonly principal: Effect.Effect ++ readonly guard: Guard ++ readonly client: HttpClient.HttpClient ++} ++ ++/** ++ * @internal ++ */ ++export interface SubscribeRequest { ++ readonly name: string ++ readonly arguments: Readonly> ++ readonly delivery: Readonly> ++ readonly cursor: string | null ++ readonly ttlMs?: number | null | undefined ++ // The event's argument decoder, run before the endpoint is contacted. ++ readonly decode: Effect.Effect ++ // Runs the event's stream for the subscription's lifetime, as push delivery does. ++ readonly open: ( ++ decoded: unknown, ++ deliver: (subscription: McpCore.EventSubscription) => Effect.Effect ++ ) => Effect.Effect ++} ++ ++/** ++ * @internal ++ */ ++export interface SubscribeResult { ++ readonly id: string ++ readonly refreshBefore: string ++ readonly cursor: string | null ++ readonly truncated: boolean ++ readonly deliveryStatus?: { ++ readonly active: boolean ++ readonly lastDeliveryAt: string | null ++ readonly lastError: FailureCategory | null ++ } | undefined ++} ++ ++/** ++ * @internal ++ */ ++export interface UnsubscribeRequest { ++ readonly name: string ++ readonly arguments: Readonly> ++ readonly delivery: Readonly> ++} ++ ++/** ++ * @internal ++ */ ++export interface Webhooks { ++ readonly subscribe: ( ++ request: SubscribeRequest ++ ) => Effect.Effect ++ readonly unsubscribe: (request: UnsubscribeRequest) => Effect.Effect ++ readonly size: Effect.Effect ++} ++ ++interface Subscription { ++ readonly id: string ++ readonly principal: string ++ readonly url: URL ++ secret: string ++ key: Mac.Key ++ previous: { readonly key: Mac.Key; readonly until: number } | undefined ++ expiresAt: number ++ // Everything at or before it was acknowledged or given up on. ++ watermark: string | null ++ lastDeliveryAt: number | undefined ++ lastError: FailureCategory | undefined ++ fiber: Fiber.Fiber | undefined ++ // Completed when a refresh moves the deadline, so the expiry recomputes it. ++ deadlineMoved: Deferred.Deferred ++ // Where the event's stream started, or why it could not; a same-key refresh waits for it. ++ readonly accepted: Deferred.Deferred< ++ { readonly cursor: string | null; readonly truncated: boolean }, ++ McpCore.EventFailure | McpCore.RequestRejected ++ > ++ // After a gap whose envelope the endpoint never took: the cursors handed out since, any of ++ // which a refresh presents to say it saw past the gap. Until then every refresh is truncated. ++ cursorsSinceGap: Set | undefined ++} ++ ++type Outcome = ++ // `body` is read only for a verification, and is undefined when it was too long. ++ | { readonly _tag: "Delivered"; readonly body: string | undefined } ++ | { readonly _tag: "Failed"; readonly category: FailureCategory; readonly retryable: boolean } ++ ++const invalid = (message: string) => new PublicMcpSchema.InvalidParams({ message }) ++ ++/** ++ * The TTL granted for a suggested one: the default when none is suggested, and ++ * never unbounded, since subscriptions are not kept across restarts. ++ * ++ * @internal ++ */ ++export const grantTtl = (suggested: number | null | undefined): number => ++ suggested === undefined ++ ? DEFAULT_TTL_MS ++ : suggested === null ++ ? MAX_TTL_MS ++ : Math.min(MAX_TTL_MS, Math.max(MIN_TTL_MS, suggested)) ++ ++/** ++ * JSON with object keys sorted, so equal arguments serialize equally. ++ * ++ * @internal ++ */ ++export const canonicalJson = (value: unknown): string => { ++ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]` ++ if (typeof value === "object" && value !== null) { ++ const entries = Object.entries(value).filter(([, entry]) => entry !== undefined) ++ entries.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) ++ return `{${entries.map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`).join(",")}}` ++ } ++ return JSON.stringify(value) ?? "null" ++} ++ ++const encoder = new TextEncoder() ++ ++const parseUrl = (value: unknown, guard: Guard) => { ++ if (typeof value !== "string") return Effect.fail(invalid("delivery.url is required")) ++ let url: URL ++ try { ++ url = new URL(value) ++ } catch { ++ return Effect.fail(invalid("delivery.url is not a valid URL")) ++ } ++ if (url.protocol !== "https:" && !(url.protocol === "http:" && guard.allowsPlaintext?.(url) === true)) { ++ return Effect.fail(invalid("delivery.url must use https")) ++ } ++ if (url.username !== "" || url.password !== "") { ++ return Effect.fail(invalid("delivery.url must not carry credentials")) ++ } ++ url.hash = "" ++ return Effect.succeed(url) ++} ++ ++const parseSecret = (value: unknown) => { ++ const fail = Effect.fail(invalid("delivery.secret must be whsec_ and the base64 of 24 to 64 random bytes")) ++ if (typeof value !== "string" || !value.startsWith(SECRET_PREFIX)) return fail ++ const bytes = Base64.decode(value.slice(SECRET_PREFIX.length)) ++ if (Result.isFailure(bytes) || bytes.success.length < 24 || bytes.success.length > 64) return fail ++ return Mac.key(Mac.hmacSha256, bytes.success).pipe(Effect.orDie, Effect.map((key) => ({ text: value, key }))) ++} ++ ++const statusCategory = (status: number): FailureCategory => (status >= 500 ? "http_5xx" : "http_4xx") ++ ++// Only codes and names are read, never what the endpoint sent. ++const transportCategory = (error: unknown): FailureCategory => { ++ let current: unknown = error ++ for (let depth = 0; depth < 8 && typeof current === "object" && current !== null; depth++) { ++ const code = (current as { readonly code?: unknown }).code ++ if (typeof code === "string" && /CERT|TLS|SSL/.test(code)) return "tls_error" ++ current = (current as { readonly cause?: unknown }).cause ?? ++ (current as { readonly reason?: unknown }).reason ++ } ++ return "connection_refused" ++} ++ ++// Stops pulling past the cap; closing the request's scope then aborts the rest. ++const readCapped = (response: HttpClientResponse.HttpClientResponse) => ++ Effect.suspend(() => { ++ const chunks: Array = [] ++ let total = 0 ++ let oversized = false ++ return response.stream.pipe( ++ Stream.takeWhile((chunk) => { ++ if (total + chunk.length > MAX_CHALLENGE_RESPONSE_BYTES) { ++ oversized = true ++ return false ++ } ++ total += chunk.length ++ chunks.push(chunk) ++ return true ++ }), ++ Stream.runDrain, ++ Effect.map(() => { ++ if (oversized) return undefined ++ const bytes = new Uint8Array(total) ++ let offset = 0 ++ for (const chunk of chunks) { ++ bytes.set(chunk, offset) ++ offset += chunk.length ++ } ++ return new TextDecoder().decode(bytes) ++ }) ++ ) ++ }) ++ ++const echoedChallenge = (body: string): string | undefined => { ++ try { ++ const parsed: unknown = JSON.parse(body) ++ const challenge = typeof parsed === "object" && parsed !== null ++ ? (parsed as { readonly challenge?: unknown }).challenge ++ : undefined ++ return typeof challenge === "string" ? challenge : undefined ++ } catch { ++ return undefined ++ } ++} ++ ++const callbackError = (category: FailureCategory) => ++ new PublicMcpSchema.CallbackEndpointError({ ++ message: `The callback endpoint failed verification: ${category}`, ++ data: { reason: category } ++ }) ++ ++const iso = (millis: number) => new Date(millis).toISOString() ++ ++/** ++ * @internal ++ */ ++export const make = Effect.fnUntraced(function*(options: Options) { ++ const scope = yield* Effect.scope ++ const mac = yield* Mac.Mac ++ const digest = yield* Digest.Digest ++ const random = yield* SecureRandom.SecureRandom ++ const { guard } = options ++ // Closing a request's scope aborts its body, so a delivery never downloads what the endpoint sends. ++ const client = HttpClient.withScope(options.client) ++ const subscriptions = new Map() ++ // Subscribes past the principal check that have not created their subscription yet. ++ const pending = new Map() ++ const verified = new Map() ++ const failedVerifications = new Map() ++ const verifying = new Map>() ++ const verificationsByHost = new Map>() ++ ++ const forget = (subscription: Subscription) => { ++ if (subscriptions.get(subscription.id) === subscription) subscriptions.delete(subscription.id) ++ } ++ ++ const subscriptionId = (principal: string, url: URL, name: string, args: unknown) => ++ digest.digestHex(Digest.sha256, encoder.encode(canonicalJson([principal, url.href, name, args]))).pipe( ++ Effect.map((hex) => `sub_${hex.slice(0, 32)}`) ++ ) ++ ++ // High entropy and unrelated to the eventId; a retry reuses it. ++ const messageId = (prefix: string) => ++ Effect.map(random.randomBytes(18), (bytes) => `${prefix}_${Base64Url.encode(bytes)}`) ++ ++ // Bridge for clients predating SEP-3415 (ChatGPT, @ai-sdk/mcp); drop per #41158. ++ // They require an event's webhook-id to equal its eventId. Both become this id, derived per ++ // subscription so two subscriptions to one URL never share it; poll and push keep the eventId. ++ const deliveryId = (subscription: Subscription, eventId: string) => ++ Effect.map( ++ digest.digest(Digest.sha256, encoder.encode(`${subscription.id}\0${eventId}`)), ++ (hash) => `evt_${Base64Url.encode(hash).slice(0, 22)}` ++ ) ++ ++ const MAX_CURSORS_SINCE_GAP = 1_024 ++ const advance = (subscription: Subscription, cursor: string | null) => { ++ subscription.watermark = cursor ++ const since = subscription.cursorsSinceGap ++ if (since === undefined) return ++ since.add(cursor) ++ if (since.size > MAX_CURSORS_SINCE_GAP) since.delete(since.values().next().value!) ++ } ++ ++ const sign = (keys: ReadonlyArray, webhookId: string, timestamp: number, body: string) => ++ Effect.forEach(keys, (key) => mac.sign(key, encoder.encode(`${webhookId}.${timestamp}.${body}`))).pipe( ++ Effect.orDie, ++ Effect.map((tags) => tags.map((tag) => `v1,${Base64.encode(tag)}`).join(" ")) ++ ) ++ ++ // One POST. The timestamp and signature are fresh on every attempt. ++ const send = Effect.fnUntraced(function*( ++ subscription: Subscription, ++ body: string, ++ webhookId: string, ++ readBody: boolean ++ ) { ++ const admitted = yield* Effect.result(guard.check(subscription.url)) ++ if (Result.isFailure(admitted)) { ++ return { _tag: "Failed", category: "connection_refused", retryable: true } satisfies Outcome ++ } ++ const now = yield* Clock.currentTimeMillis ++ const timestamp = Math.floor(now / 1000) ++ const previous = subscription.previous ++ const keys = previous !== undefined && now < previous.until ++ ? [subscription.key, previous.key] ++ : [subscription.key] ++ const request = HttpClientRequest.post(subscription.url).pipe( ++ HttpClientRequest.setHeaders({ ++ "webhook-id": webhookId, ++ "webhook-timestamp": String(timestamp), ++ "webhook-signature": yield* sign(keys, webhookId, timestamp, body), ++ "x-mcp-subscription-id": subscription.id ++ }), ++ HttpClientRequest.bodyText(body, "application/json") ++ ) ++ const outcome = yield* client.execute(request).pipe( ++ Effect.flatMap((response): Effect.Effect => { ++ if (response.status < 200 || response.status >= 300) { ++ return Effect.succeed({ ++ _tag: "Failed", ++ category: statusCategory(response.status), ++ retryable: response.status !== 410 && response.status !== 413 ++ }) ++ } ++ return readBody ++ ? Effect.map(readCapped(response), (text) => ({ _tag: "Delivered", body: text })) ++ : Effect.succeed({ _tag: "Delivered", body: undefined }) ++ }), ++ Effect.timeoutOption(Duration.millis(REQUEST_TIMEOUT_MS)), ++ Effect.scoped, ++ // `fetch` would follow a redirect itself; webhook delivery never does. ++ Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }), ++ // Trace ids stay inside: the endpoint belongs to someone else. ++ Effect.provideService(HttpClient.TracerPropagationEnabled, false), ++ Effect.catch((error) => ++ Effect.succeed(Option.some({ _tag: "Failed", category: transportCategory(error), retryable: true })) ++ ) ++ ) ++ return Option.getOrElse(outcome, (): Outcome => ({ _tag: "Failed", category: "timeout", retryable: true })) ++ }) ++ ++ // Retries with backoff; gives up after a 410, a 413 or the last attempt. True once delivered. ++ const deliver = Effect.fnUntraced(function*(subscription: Subscription, body: string, webhookId: string) { ++ for (let attempt = 1;; attempt++) { ++ // A subscription that ended may have been replaced under its id; this one speaks no longer. ++ const current = subscriptions.get(subscription.id) ++ if (current !== undefined && current !== subscription) return false ++ const startedAt = yield* Clock.currentTimeMillis ++ const outcome = yield* send(subscription, body, webhookId, false) ++ if (outcome._tag === "Delivered") { ++ subscription.lastDeliveryAt = yield* Clock.currentTimeMillis ++ subscription.lastError = undefined ++ return true ++ } ++ subscription.lastError = outcome.category ++ if (!outcome.retryable || attempt >= MAX_ATTEMPTS) return false ++ // Counted from the attempt's start, so a slow endpoint does not stretch the window. ++ const wait = startedAt + FIRST_RETRY_MS * 2 ** (attempt - 1) - (yield* Clock.currentTimeMillis) ++ if (wait > 0) yield* Effect.sleep(Duration.millis(wait)) ++ } ++ }) ++ ++ const control = (subscription: Subscription, type: string, fields: Readonly>) => ++ Effect.flatMap( ++ messageId(`msg_${type}`), ++ (webhookId) => deliver(subscription, JSON.stringify({ type, ...fields }), webhookId) ++ ) ++ ++ // One delivery in flight per subscription, so the watermark only moves forward ++ // once everything before it is resolved. ++ const run = (subscription: Subscription, name: string, events: McpCore.EventSubscription) => ++ events.items.pipe( ++ Stream.runForEach((item): Effect.Effect => { ++ switch (item._tag) { ++ case "Event": ++ return Effect.flatMap(deliveryId(subscription, item.eventId), (webhookId) => { ++ const body = JSON.stringify({ ++ eventId: webhookId, ++ name, ++ timestamp: item.timestamp, ++ data: item.data, ++ cursor: item.cursor, ++ ...(item._meta === undefined ? {} : { _meta: item._meta }) ++ }) ++ return deliver(subscription, body, webhookId) ++ }).pipe(Effect.andThen(Effect.sync(() => advance(subscription, item.cursor)))) ++ case "Position": ++ return Effect.sync(() => advance(subscription, item.cursor)) ++ case "Gap": ++ return control(subscription, "gap", { cursor: item.cursor }).pipe( ++ Effect.map((delivered) => { ++ if (!delivered) subscription.cursorsSinceGap = new Set() ++ advance(subscription, item.cursor) ++ }) ++ ) ++ case "Error": ++ // A webhook has no envelope for an error that leaves the subscription open. ++ return Effect.void ++ } ++ }), ++ // Ended before it says so, so a refresh meanwhile starts afresh instead of reporting it live. ++ Effect.catch((failure) => ++ Effect.suspend(() => { ++ forget(subscription) ++ return control(subscription, "terminated", { error: wireError(failure) }) ++ }) ++ ) ++ ) ++ ++ const expiry = (subscription: Subscription) => ++ Effect.gen(function*() { ++ while (true) { ++ const left = subscription.expiresAt - (yield* Clock.currentTimeMillis) ++ if (left <= 0) return forget(subscription) ++ yield* Effect.raceFirst(Effect.sleep(Duration.millis(left)), Deferred.await(subscription.deadlineMoved)) ++ } ++ }) ++ ++ const handshake = Effect.fnUntraced(function*(subscription: Subscription) { ++ const challenge = Base64Url.encode(yield* random.randomBytes(32)) ++ const outcome = yield* send( ++ subscription, ++ JSON.stringify({ type: "verification", challenge }), ++ yield* messageId("msg_verification"), ++ true ++ ) ++ if (outcome._tag === "Failed") return yield* Effect.fail(outcome.category) ++ const echoed = outcome.body === undefined ? undefined : echoedChallenge(outcome.body) ++ if (echoed === undefined || !Mac.timingSafeEqual(encoder.encode(echoed), encoder.encode(challenge))) { ++ return yield* Effect.fail("challenge_failed") ++ } ++ }) ++ ++ // Cached per (principal, url) either way; concurrent subscribes share one handshake. ++ const verify = Effect.fnUntraced(function*(subscription: Subscription) { ++ const key = JSON.stringify([subscription.principal, subscription.url.href]) ++ const now = yield* Clock.currentTimeMillis ++ for (const [entry, until] of verified) if (until <= now) verified.delete(entry) ++ for (const [entry, failure] of failedVerifications) if (failure.until <= now) failedVerifications.delete(entry) ++ if (verified.has(key)) return ++ const failure = failedVerifications.get(key) ++ if (failure !== undefined) return yield* callbackError(failure.category) ++ const inFlight = verifying.get(key) ++ if (inFlight !== undefined) return yield* Deferred.await(inFlight) ++ const host = subscription.url.hostname ++ const recent = (verificationsByHost.get(host) ?? []).filter((at) => at > now - MINUTE_MS) ++ if (recent.length >= VERIFICATIONS_PER_HOST_PER_MINUTE) { ++ verificationsByHost.set(host, recent) ++ return yield* new PublicMcpSchema.ResourceExhausted({ ++ message: "Too many callback verifications for this host", ++ data: { limit: "verifications", max: VERIFICATIONS_PER_HOST_PER_MINUTE } ++ }) ++ } ++ for (const [entry, times] of verificationsByHost) { ++ if (times.every((at) => at <= now - MINUTE_MS)) verificationsByHost.delete(entry) ++ } ++ verificationsByHost.set(host, [...recent, now]) ++ const done = Deferred.makeUnsafe() ++ verifying.set(key, done) ++ return yield* handshake(subscription).pipe( ++ Effect.tap(() => ++ Effect.map(Clock.currentTimeMillis, (at) => { ++ verified.set(key, at + VERIFIED_FOR_MS) ++ }) ++ ), ++ Effect.tapError((category) => ++ Effect.map(Clock.currentTimeMillis, (at) => { ++ failedVerifications.set(key, { until: at + FAILED_FOR_MS, category }) ++ }) ++ ), ++ Effect.mapError(callbackError), ++ Effect.onExit((exit) => ++ Effect.sync(() => { ++ verifying.delete(key) ++ Deferred.doneUnsafe(done, exit) ++ }) ++ ) ++ ) ++ }) ++ ++ // A caller that joins while the first subscribe's stream is opening waits for it and gets ++ // where it started; one whose subscription went away meanwhile subscribes afresh. ++ const refresh = Effect.fnUntraced(function*( ++ request: SubscribeRequest, ++ subscription: Subscription, ++ secret: { readonly text: string; readonly key: Mac.Key }, ++ expiresAt: number, ++ now: number ++ ): Effect.fn.Return { ++ const opening = !Deferred.isDoneUnsafe(subscription.accepted) ++ const start = yield* Deferred.await(subscription.accepted) ++ if (subscriptions.get(subscription.id) !== subscription) return yield* subscribe(request) ++ if (subscription.secret !== secret.text) { ++ subscription.previous = { key: subscription.key, until: now + ROTATION_GRACE_MS } ++ subscription.secret = secret.text ++ subscription.key = secret.key ++ } ++ subscription.expiresAt = expiresAt ++ const moved = subscription.deadlineMoved ++ subscription.deadlineMoved = Deferred.makeUnsafe() ++ Deferred.doneUnsafe(moved, Effect.void) ++ if (opening) return { id: subscription.id, refreshBefore: iso(expiresAt), ...start } ++ // Kept until the client shows a cursor from past the gap, so a lost response hides nothing. ++ const since = subscription.cursorsSinceGap ++ if (since !== undefined && since.has(request.cursor)) subscription.cursorsSinceGap = undefined ++ const truncated = subscription.cursorsSinceGap !== undefined ++ return { ++ id: subscription.id, ++ refreshBefore: iso(expiresAt), ++ cursor: subscription.watermark, ++ truncated, ++ deliveryStatus: { ++ active: true, ++ lastDeliveryAt: subscription.lastDeliveryAt === undefined ? null : iso(subscription.lastDeliveryAt), ++ lastError: subscription.lastError ?? null ++ } ++ } satisfies SubscribeResult ++ }) ++ ++ const subscribe: Webhooks["subscribe"] = Effect.fnUntraced(function*(request) { ++ const principal = yield* options.principal ++ const mode = request.delivery.mode ++ if (mode !== undefined && mode !== "webhook") return yield* invalid("delivery.mode must be 'webhook'") ++ const url = yield* parseUrl(request.delivery.url, guard) ++ const secret = yield* parseSecret(request.delivery.secret) ++ const id = yield* subscriptionId(principal, url, request.name, request.arguments) ++ const now = yield* Clock.currentTimeMillis ++ const expiresAt = now + grantTtl(request.ttlMs) ++ const live = subscriptions.get(id) ++ if (live !== undefined) return yield* refresh(request, live, secret, expiresAt, now) ++ // The slot is taken before anything asynchronous, so concurrent subscribes cannot pass the cap. ++ let held = pending.get(principal) ?? 0 ++ for (const subscription of subscriptions.values()) if (subscription.principal === principal) held++ ++ if (held >= MAX_SUBSCRIPTIONS_PER_PRINCIPAL) { ++ return yield* new PublicMcpSchema.ResourceExhausted({ ++ message: "Too many webhook subscriptions", ++ data: { limit: "subscriptions", max: MAX_SUBSCRIPTIONS_PER_PRINCIPAL } ++ }) ++ } ++ pending.set(principal, (pending.get(principal) ?? 0) + 1) ++ let reserved = true ++ const release = () => { ++ if (!reserved) return ++ reserved = false ++ const left = (pending.get(principal) ?? 1) - 1 ++ if (left === 0) pending.delete(principal) ++ else pending.set(principal, left) ++ } ++ return yield* create(request, { principal, url, secret, id, expiresAt, now, release }).pipe( ++ Effect.ensuring(Effect.sync(release)) ++ ) ++ }) ++ ++ const create = Effect.fnUntraced(function*( ++ request: SubscribeRequest, ++ { expiresAt, id, now, principal, release, secret, url }: { ++ readonly principal: string ++ readonly url: URL ++ readonly secret: { readonly text: string; readonly key: Mac.Key } ++ readonly id: string ++ readonly expiresAt: number ++ readonly now: number ++ readonly release: () => void ++ } ++ ) { ++ // One answer whether the host is private or does not resolve, so it reveals neither. ++ yield* Effect.mapError(guard.check(url), () => invalid("delivery.url is not allowed")) ++ const subscription: Subscription = { ++ id, ++ principal, ++ url, ++ secret: secret.text, ++ key: secret.key, ++ previous: undefined, ++ expiresAt, ++ watermark: request.cursor, ++ lastDeliveryAt: undefined, ++ lastError: undefined, ++ fiber: undefined, ++ deadlineMoved: Deferred.makeUnsafe(), ++ accepted: Deferred.makeUnsafe(), ++ cursorsSinceGap: undefined ++ } ++ const decoded = yield* request.decode ++ yield* verify(subscription) ++ // A concurrent subscribe for the same key may have finished while this one verified. ++ const raced = subscriptions.get(id) ++ if (raced !== undefined) { ++ release() ++ return yield* refresh(request, raced, secret, expiresAt, now) ++ } ++ release() ++ subscriptions.set(id, subscription) ++ const { accepted } = subscription ++ const lifetime = request.open(decoded, (events) => ++ Effect.suspend(() => { ++ subscription.watermark = events.cursor ++ return Deferred.succeed(accepted, { cursor: events.cursor, truncated: events.truncated }) ++ }).pipe(Effect.andThen(run(subscription, request.name, events))) ++ ).pipe( ++ Effect.tapError((failure) => Deferred.fail(accepted, failure)), ++ Effect.raceFirst(expiry(subscription)), ++ Effect.ignore, ++ Effect.ensuring(Effect.suspend(() => { ++ forget(subscription) ++ return Deferred.fail(accepted, new PublicMcpSchema.InternalError({ message: "The subscription ended" })) ++ })) ++ ) ++ // Forked from the request, so the event's stream keeps the request's services. ++ subscription.fiber = yield* Effect.forkIn(lifetime, scope) ++ const start = yield* Deferred.await(accepted) ++ return { id, refreshBefore: iso(expiresAt), cursor: start.cursor, truncated: start.truncated } ++ }) ++ ++ const unsubscribe: Webhooks["unsubscribe"] = Effect.fnUntraced(function*(request) { ++ const principal = yield* options.principal ++ const url = yield* parseUrl(request.delivery.url, guard) ++ const id = yield* subscriptionId(principal, url, request.name, request.arguments) ++ const subscription = subscriptions.get(id) ++ if (subscription === undefined) { ++ return yield* new PublicMcpSchema.NotFound({ ++ message: "No webhook subscription matches", ++ data: { kind: "subscription" } ++ }) ++ } ++ subscriptions.delete(id) ++ if (subscription.fiber !== undefined) yield* Fiber.interrupt(subscription.fiber) ++ }) ++ ++ return { ++ subscribe, ++ unsubscribe, ++ size: Effect.sync(() => subscriptions.size) ++ } satisfies Webhooks ++}) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 471dec4be9987..e53019e0f39bd 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -377,7 +377,7 @@ patchedDependencies: alchemy@2.0.0-beta.85: 07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd app-builder-lib@26.16.1: 0fbe9ae51783f5768ebe197d12d1fdb7d477a08c92e5db2f6356bcce62613c53 dbus-next@0.10.2: cfff57561b0ee59b5addb3b2e6c6f20906e967507a530ab67e8db8108e520ba4 - effect@4.1.5: 76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337 + effect@4.1.5: 24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28 electron-updater@6.8.9: 91b5648a7eed42761523ef542ebb7e548b037eda41d66533c8152ac65ac72155 expo-audio@58.0.11: 92414572bf24ffd0c45de44c45f11f6c48bc0af13b8b9a56f77a67bc0e915c1e expo-modules-core@58.0.30: f0b0fd100550ed76e5c25b4d13eb7c9ff62825f8f197c53edf7bf447c50c9fb7 @@ -435,7 +435,7 @@ importers: version: 0.15.4 '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@napi-rs/keyring': specifier: ^1.3.0 version: 1.3.0 @@ -459,7 +459,7 @@ importers: version: 0.10.2(patch_hash=cfff57561b0ee59b5addb3b2e6c6f20906e967507a530ab67e8db8108e520ba4) effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) electron: specifier: 44.10.1 version: 44.10.1(supports-color@8.1.1) @@ -490,7 +490,7 @@ importers: devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -551,7 +551,7 @@ importers: version: 0.4.4(patch_hash=7a808b92da8460750b85818552e13be3fb73d111691c7db76965970351e124e4)(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)(supports-color@8.1.1)(typescript@6.0.3) '@effect/atom-react': specifier: 4.1.5 - version: 4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react@19.3.0)(scheduler@0.28.0) + version: 4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react@19.3.0)(scheduler@0.28.0) '@expo-google-fonts/dm-sans': specifier: ^0.4.2 version: 0.4.2 @@ -629,7 +629,7 @@ importers: version: 8.0.3 effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) expo: specifier: 58.0.23 version: 58.0.23(d226faf1ca90e630d8c56a2108dee32d) @@ -816,10 +816,10 @@ importers: version: 7.29.7(supports-color@8.1.1) '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@pierre/trees': specifier: 1.0.0-beta.6 version: 1.0.0-beta.6(@pierre/theme@2.0.0)(@shikijs/themes@4.2.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(shiki@4.2.0) @@ -861,10 +861,10 @@ importers: version: 1.4.2(patch_hash=d9747bbf2d8fa7529b74b690087b70b3b2662fcba0d4d3148afc3b956171b54a)(zod@4.6.7) '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/platform-node-shared': specifier: 4.1.5 - version: 4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6) + version: 4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6) '@ff-labs/fff-node': specifier: 0.11.0 version: 0.11.0(patch_hash=93f62a76399b435a76588b2bef237db0a1e85880c1ac0d0759c416e9cc579252) @@ -945,7 +945,7 @@ importers: version: 8.0.3 effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) ffi-rs: specifier: 1.3.2 version: 1.3.2 @@ -985,10 +985,10 @@ importers: devDependencies: '@effect/graphql-generator': specifier: 'catalog:' - version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@handy-computer/models': specifier: 0.2.3 version: 0.2.3 @@ -1093,7 +1093,7 @@ importers: version: 3.2.2(react@19.3.0) '@effect/atom-react': specifier: 4.1.5 - version: 4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react@19.3.0)(scheduler@0.28.0) + version: 4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react@19.3.0)(scheduler@0.28.0) '@fontsource-variable/inter': specifier: ^5.3.0 version: 5.3.0 @@ -1198,7 +1198,7 @@ importers: version: 3.4.17 effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) entities: specifier: 8.1.0 version: 8.1.0 @@ -1268,10 +1268,10 @@ importers: devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@tailwindcss/vite': specifier: 4.3.3 version: 4.3.3(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0)) @@ -1337,7 +1337,7 @@ importers: dependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@t3tools/contracts': specifier: workspace:* version: link:../packages/contracts @@ -1349,11 +1349,11 @@ importers: version: link:../packages/shared effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1365,28 +1365,28 @@ importers: dependencies: '@alchemy.run/axiom': specifier: 'catalog:' - version: 2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + version: 2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@alchemy.run/cloudflare': specifier: 'catalog:' - version: 2.0.0-beta.85(2402ddc9484fce072797810bc31b583f) + version: 2.0.0-beta.85(0416d8b0ccd24e78c5b3f43641d5aa3e) '@alchemy.run/drizzle': specifier: 'catalog:' - version: 2.0.0-beta.85(9d8ed2cd275ad880a7ad7c23a0ac97be) + version: 2.0.0-beta.85(5cde798e96ab6d44cdc28240628f10b1) '@alchemy.run/planetscale': specifier: 'catalog:' - version: 2.0.0-beta.85(13cf82a9ea878143588c95fe8a3597d0) + version: 2.0.0-beta.85(da21ec6b7d14801bed2312314736ccf5) '@clerk/backend': specifier: 3.27.0 version: 3.27.0(react-dom@19.3.0(react@19.3.0))(react@19.3.0) '@distilled.cloud/cloudflare': specifier: 'catalog:' - version: 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + version: 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@effect/sql-pg': specifier: 4.1.5 - version: 4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + version: 4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@effect/sql-sqlite-do': specifier: 'catalog:' - version: 4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + version: 4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@noble/curves': specifier: 'catalog:' version: 1.9.1 @@ -1404,26 +1404,26 @@ importers: version: link:../../packages/shared alchemy: specifier: 2.0.0-beta.85 - version: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + version: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) drizzle-orm: specifier: 1.0.0-rc.5 - version: 1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@effect/sql-pg@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(expo-sqlite@58.0.15(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7) + version: 1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@effect/sql-pg@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(expo-sqlite@58.0.15(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7) effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@alchemy.run/test': specifier: 'catalog:' - version: 2.0.0-beta.85(patch_hash=29c0539ea71d9cc372f0b16558640599beb9bc609605feb2a493da268d72713e)(f73ef3f521055a56671f9dfc623ae3a6) + version: 2.0.0-beta.85(patch_hash=29c0539ea71d9cc372f0b16558640599beb9bc609605feb2a493da268d72713e)(a619c060a1b8ed45ad4914f1f8e44c19) '@cloudflare/workers-types': specifier: ^4.20260601.1 version: 4.20260604.1 '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@electric-sql/pglite': specifier: 0.3.15 version: 0.3.15 @@ -1432,7 +1432,7 @@ importers: version: 24.12.4 drizzle-kit: specifier: 1.0.0-rc.5 - version: 1.0.0-rc.5(9451426e25210de8eb160d0749b6dfbf) + version: 1.0.0-rc.5(73cc0b8bb5cef1afe1d24404a4fb8809) vite: specifier: npm:@voidzero-dev/vite-plus-core@1.4.0 version: '@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0)' @@ -1444,16 +1444,16 @@ importers: dependencies: '@alchemy.run/axiom': specifier: 'catalog:' - version: 2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + version: 2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@alchemy.run/cloudflare': specifier: 'catalog:' - version: 2.0.0-beta.85(2402ddc9484fce072797810bc31b583f) + version: 2.0.0-beta.85(0416d8b0ccd24e78c5b3f43641d5aa3e) alchemy: specifier: 2.0.0-beta.85 - version: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + version: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) jose: specifier: 'catalog:' version: 6.2.2 @@ -1463,10 +1463,10 @@ importers: version: 4.20260604.1 '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1481,14 +1481,14 @@ importers: version: 1.89.0 effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) vite-plus: specifier: 1.4.0 version: 1.4.0(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) @@ -1545,7 +1545,7 @@ importers: version: link:../source-control-definitions effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) gt-i18n: specifier: 1.0.40 version: 1.0.40 @@ -1561,7 +1561,7 @@ importers: devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/mdast': specifier: ^4.0.4 version: 4.0.4 @@ -1585,11 +1585,11 @@ importers: dependencies: effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) vite-plus: specifier: 1.4.0 version: 1.4.0(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) @@ -1598,17 +1598,17 @@ importers: dependencies: effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/openapi-generator': specifier: 'catalog:' - version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(encoding@0.1.13) + version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(encoding@0.1.13) '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1620,17 +1620,17 @@ importers: dependencies: effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/openapi-generator': specifier: 'catalog:' - version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(encoding@0.1.13) + version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(encoding@0.1.13) '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1648,14 +1648,14 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/graphql-generator': specifier: 'catalog:' - version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1679,14 +1679,14 @@ importers: version: 8.0.3 effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1716,14 +1716,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -1747,14 +1747,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1778,7 +1778,7 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) jsonc-parser: specifier: 3.3.1 version: 3.3.1 @@ -1788,10 +1788,10 @@ importers: devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -1818,14 +1818,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -1855,14 +1855,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -1892,14 +1892,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -1929,14 +1929,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -1954,7 +1954,7 @@ importers: version: 1.15.13 '@opencode/client': specifier: 2.0.28 - version: 2.0.28(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + version: 2.0.28(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@opencode/protocol': specifier: 2.0.28 version: 2.0.28 @@ -1972,14 +1972,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -2003,14 +2003,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -2025,7 +2025,7 @@ importers: dependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@t3tools/contracts': specifier: workspace:* version: link:../contracts @@ -2037,11 +2037,11 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -2056,14 +2056,14 @@ importers: version: link:../contracts effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -2096,14 +2096,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -2124,7 +2124,7 @@ importers: version: link:../contracts effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) ffi-rs: specifier: 1.3.2 version: 1.3.2 @@ -2185,10 +2185,10 @@ importers: devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/hast': specifier: ^3.0.5 version: 3.0.5 @@ -2224,14 +2224,14 @@ importers: version: 8.0.3 effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2258,14 +2258,14 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2286,11 +2286,11 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -2302,7 +2302,7 @@ importers: dependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@t3tools/contracts': specifier: workspace:* version: link:../contracts @@ -2317,11 +2317,11 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -2375,14 +2375,14 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2409,11 +2409,11 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2428,7 +2428,7 @@ importers: dependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@t3tools/contracts': specifier: workspace:* version: link:../contracts @@ -2443,17 +2443,17 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) yaml: specifier: ^2.9.0 version: 2.9.0 devDependencies: '@effect/graphql-generator': specifier: 'catalog:' - version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2477,14 +2477,14 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2508,11 +2508,11 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2527,7 +2527,7 @@ importers: dependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@t3tools/contracts': specifier: workspace:* version: link:../contracts @@ -2539,7 +2539,7 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@types/node': specifier: 24.12.4 @@ -2555,14 +2555,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -2580,11 +2580,11 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -2602,7 +2602,7 @@ importers: version: 0.15.5(e2e@0.23.0) '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@electron/asar': specifier: ^4.3.0 version: 4.3.0 @@ -2626,7 +2626,7 @@ importers: version: 0.23.0 effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) playwright-core: specifier: 1.64.1 version: 1.64.1 @@ -2642,7 +2642,7 @@ importers: devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/plist': specifier: 'catalog:' version: 3.0.5 @@ -13168,27 +13168,27 @@ snapshots: dependencies: json-schema: 0.4.0 - '@alchemy.run/acme@2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': + '@alchemy.run/acme@2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - '@distilled.cloud/acme': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + '@distilled.cloud/acme': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@alchemy.run/axiom@2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': + '@alchemy.run/axiom@2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - '@distilled.cloud/axiom': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + '@distilled.cloud/axiom': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@alchemy.run/cloudflare-runtime@2.0.0-beta.85(@distilled.cloud/cloudflare@1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/node@24.12.4)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(rolldown@1.2.13)(typescript@6.0.3)': + '@alchemy.run/cloudflare-runtime@2.0.0-beta.85(@distilled.cloud/cloudflare@1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/node@24.12.4)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(rolldown@1.2.13)(typescript@6.0.3)': dependencies: '@alchemy.run/node-utils': 2.0.0-beta.85 '@cloudflare/unenv-preset': 2.16.2(unenv@2.0.0-rc.24)(workerd@1.20261026.1) - '@distilled.cloud/cloudflare': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + '@distilled.cloud/cloudflare': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@puppeteer/browsers': 3.2.6(yauzl@3.4.0) capnp-es: 0.0.16(typescript@6.0.3) - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) magic-string: 0.30.21 mime: 4.1.1 sharp: 0.35.5(@types/node@24.12.4) @@ -13196,8 +13196,8 @@ snapshots: workerd: 1.20261026.1 yauzl: 3.4.0 optionalDependencies: - '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6) - '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6) + '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) rolldown: 1.2.13 vite: '@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0)' transitivePeerDependencies: @@ -13205,27 +13205,27 @@ snapshots: - proxy-agent - typescript - '@alchemy.run/cloudflare@2.0.0-beta.85(2402ddc9484fce072797810bc31b583f)': - dependencies: - '@alchemy.run/acme': 2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - '@alchemy.run/cloudflare-runtime': 2.0.0-beta.85(@distilled.cloud/cloudflare@1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/node@24.12.4)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(rolldown@1.2.13)(typescript@6.0.3) - '@alchemy.run/docker': 2.0.0-beta.85(e480f1b1bda9582dded73d242d5d6dc9) - '@alchemy.run/sql': 2.0.0-beta.85(13cf82a9ea878143588c95fe8a3597d0) - '@distilled.cloud/aws': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - '@distilled.cloud/aws4signer': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - '@distilled.cloud/cloudflare': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - '@distilled.cloud/iceberg': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - '@effect/sql-d1': 4.1.1(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + '@alchemy.run/cloudflare@2.0.0-beta.85(0416d8b0ccd24e78c5b3f43641d5aa3e)': + dependencies: + '@alchemy.run/acme': 2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@alchemy.run/cloudflare-runtime': 2.0.0-beta.85(@distilled.cloud/cloudflare@1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/node@24.12.4)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(rolldown@1.2.13)(typescript@6.0.3) + '@alchemy.run/docker': 2.0.0-beta.85(b7b9d9a38fe35faf72b0a492112f9365) + '@alchemy.run/sql': 2.0.0-beta.85(da21ec6b7d14801bed2312314736ccf5) + '@distilled.cloud/aws': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@distilled.cloud/aws4signer': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@distilled.cloud/cloudflare': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@distilled.cloud/iceberg': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@effect/sql-d1': 4.1.1(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) pathe: 2.0.3 picomatch: 4.0.7 rolldown: 1.2.13 tinyglobby: 0.2.17 optionalDependencies: - '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6) - '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6) + '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) vite: '@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0)' transitivePeerDependencies: - '@effect/sql-libsql' @@ -13237,26 +13237,26 @@ snapshots: - proxy-agent - typescript - '@alchemy.run/docker@2.0.0-beta.85(e480f1b1bda9582dded73d242d5d6dc9)': + '@alchemy.run/docker@2.0.0-beta.85(b7b9d9a38fe35faf72b0a492112f9365)': dependencies: - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) rolldown: 1.2.13 optionalDependencies: - '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6) + '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6) - '@alchemy.run/drizzle@2.0.0-beta.85(9d8ed2cd275ad880a7ad7c23a0ac97be)': + '@alchemy.run/drizzle@2.0.0-beta.85(5cde798e96ab6d44cdc28240628f10b1)': dependencies: - '@alchemy.run/sql': 2.0.0-beta.85(13cf82a9ea878143588c95fe8a3597d0) - '@effect/sql-d1': 4.1.1(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - '@effect/sql-sqlite-do': 4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - drizzle-orm: 1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@effect/sql-pg@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(expo-sqlite@58.0.15(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7) - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + '@alchemy.run/sql': 2.0.0-beta.85(da21ec6b7d14801bed2312314736ccf5) + '@effect/sql-d1': 4.1.1(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@effect/sql-sqlite-do': 4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + drizzle-orm: 1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@effect/sql-pg@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(expo-sqlite@58.0.15(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) optionalDependencies: - '@alchemy.run/cloudflare': 2.0.0-beta.85(2402ddc9484fce072797810bc31b583f) - '@effect/sql-pg': 4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - drizzle-kit: 1.0.0-rc.5(9451426e25210de8eb160d0749b6dfbf) + '@alchemy.run/cloudflare': 2.0.0-beta.85(0416d8b0ccd24e78c5b3f43641d5aa3e) + '@effect/sql-pg': 4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + drizzle-kit: 1.0.0-rc.5(73cc0b8bb5cef1afe1d24404a4fb8809) transitivePeerDependencies: - mysql2 - pg @@ -13266,13 +13266,13 @@ snapshots: chokidar: 5.0.0 rolldown: 1.2.13 - '@alchemy.run/planetscale@2.0.0-beta.85(13cf82a9ea878143588c95fe8a3597d0)': + '@alchemy.run/planetscale@2.0.0-beta.85(da21ec6b7d14801bed2312314736ccf5)': dependencies: - '@alchemy.run/sql': 2.0.0-beta.85(13cf82a9ea878143588c95fe8a3597d0) - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - '@distilled.cloud/planetscale': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + '@alchemy.run/sql': 2.0.0-beta.85(da21ec6b7d14801bed2312314736ccf5) + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@distilled.cloud/planetscale': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) optionalDependencies: pg: 8.23.0 transitivePeerDependencies: @@ -13285,21 +13285,21 @@ snapshots: '@types/react': 19.3.0 react-devtools-core: 6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6) - '@alchemy.run/sql@2.0.0-beta.85(13cf82a9ea878143588c95fe8a3597d0)': + '@alchemy.run/sql@2.0.0-beta.85(da21ec6b7d14801bed2312314736ccf5)': dependencies: - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) optionalDependencies: - '@effect/sql-pg': 4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + '@effect/sql-pg': 4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) pg: 8.23.0 - '@alchemy.run/test@2.0.0-beta.85(patch_hash=29c0539ea71d9cc372f0b16558640599beb9bc609605feb2a493da268d72713e)(f73ef3f521055a56671f9dfc623ae3a6)': + '@alchemy.run/test@2.0.0-beta.85(patch_hash=29c0539ea71d9cc372f0b16558640599beb9bc609605feb2a493da268d72713e)(a619c060a1b8ed45ad4914f1f8e44c19)': dependencies: - '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6) - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) optionalDependencies: - '@effect/vitest': 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + '@effect/vitest': 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) vitest: 5.0.5(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/browser-preview@5.0.5)(@vitest/ui@5.0.5)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0) transitivePeerDependencies: - bufferutil @@ -14278,45 +14278,45 @@ snapshots: '@dimforge/rapier3d-compat@0.12.0': {} - '@distilled.cloud/acme@1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': + '@distilled.cloud/acme@1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@distilled.cloud/aws4signer@1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': + '@distilled.cloud/aws4signer@1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@distilled.cloud/aws@1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': + '@distilled.cloud/aws@1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - '@distilled.cloud/aws4signer': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + '@distilled.cloud/aws4signer': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@distilled.cloud/axiom@1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': + '@distilled.cloud/axiom@1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@distilled.cloud/cloudflare@1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': + '@distilled.cloud/cloudflare@1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@distilled.cloud/core@1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': + '@distilled.cloud/core@1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@distilled.cloud/iceberg@1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': + '@distilled.cloud/iceberg@1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@distilled.cloud/planetscale@1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': + '@distilled.cloud/planetscale@1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) '@dnd-kit/accessibility@3.1.1(react@19.3.0)': dependencies: @@ -14362,64 +14362,64 @@ snapshots: e2e: 0.23.0 playwright-core: 1.64.1 - '@effect/atom-react@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react@19.3.0)(scheduler@0.28.0)': + '@effect/atom-react@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react@19.3.0)(scheduler@0.28.0)': dependencies: - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) react: 19.3.0 scheduler: 0.28.0 - '@effect/graphql-generator@4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': + '@effect/graphql-generator@4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@effect/openapi-generator@4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(encoding@0.1.13)': + '@effect/openapi-generator@4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(encoding@0.1.13)': dependencies: - '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) swagger2openapi: 7.0.8(encoding@0.1.13) transitivePeerDependencies: - encoding - '@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6)': + '@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6)': dependencies: - '@effect/platform-node-shared': 4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6) - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + '@effect/platform-node-shared': 4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) transitivePeerDependencies: - bufferutil - utf-8-validate - '@effect/platform-node-shared@4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6)': + '@effect/platform-node-shared@4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6)': dependencies: '@types/ws': 8.18.2 - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) ws: 8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6) transitivePeerDependencies: - bufferutil - utf-8-validate - '@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6)': + '@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6)': dependencies: - '@effect/platform-node-shared': 4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6) - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + '@effect/platform-node-shared': 4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) redis: 6.2.1 undici: 8.12.4 transitivePeerDependencies: - bufferutil - utf-8-validate - '@effect/sql-d1@4.1.1(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': + '@effect/sql-d1@4.1.1(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: '@cloudflare/workers-types': 5.20261026.1 - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@effect/sql-pg@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': + '@effect/sql-pg@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@effect/sql-sqlite-do@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': + '@effect/sql-sqlite-do@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) '@effect/tsgo-darwin-arm64@0.67.1': optional: true @@ -14452,9 +14452,9 @@ snapshots: '@effect/tsgo-win32-arm64': 0.67.1 '@effect/tsgo-win32-x64': 0.67.1 - '@effect/vitest@4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0)': + '@effect/vitest@4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0)': dependencies: - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) vite-plus: 1.4.0(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) transitivePeerDependencies: - '@arethetypeswrong/core' @@ -15930,22 +15930,22 @@ snapshots: dependencies: cross-spawn: 7.0.6 - '@opencode/client@2.0.28(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': + '@opencode/client@2.0.28(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: '@opencode/protocol': 2.0.28 '@opencode/schema': 2.0.28 optionalDependencies: - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) '@opencode/protocol@2.0.28': dependencies: '@opencode/schema': 2.0.28 - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) '@opencode/schema@2.0.28': dependencies: '@standard-schema/spec': 1.1.0 - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) '@oslojs/asn1@1.0.0': dependencies: @@ -18034,12 +18034,12 @@ snapshots: json-schema-traverse: 1.0.0 require-from-string: 2.0.2 - alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)): + alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)): dependencies: '@alchemy.run/node-utils': 2.0.0-beta.85 '@alchemy.run/sigil': 0.1.0-alpha.1(@types/react@19.3.0)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6)) capnweb: 0.12.0 - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) fflate: 0.8.3 pathe: 2.0.3 picomatch: 4.0.7 @@ -18047,8 +18047,8 @@ snapshots: tinyglobby: 0.2.17 yaml: 2.9.0 optionalDependencies: - '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6) - '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6) + '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) vite: '@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0)' ws: 8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6) transitivePeerDependencies: @@ -19007,21 +19007,21 @@ snapshots: dotenv@16.6.1: {} - drizzle-kit@1.0.0-rc.5(9451426e25210de8eb160d0749b6dfbf): + drizzle-kit@1.0.0-rc.5(73cc0b8bb5cef1afe1d24404a4fb8809): optionalDependencies: - drizzle-orm: 1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@effect/sql-pg@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(expo-sqlite@58.0.15(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7) + drizzle-orm: 1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@effect/sql-pg@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(expo-sqlite@58.0.15(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7) - drizzle-orm@1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@effect/sql-pg@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(expo-sqlite@58.0.15(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7): + drizzle-orm@1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@effect/sql-pg@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(expo-sqlite@58.0.15(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7): optionalDependencies: '@cloudflare/workers-types': 4.20260604.1 - '@effect/sql-d1': 4.1.1(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - '@effect/sql-pg': 4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - '@effect/sql-sqlite-do': 4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + '@effect/sql-d1': 4.1.1(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@effect/sql-pg': 4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@effect/sql-sqlite-do': 4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@electric-sql/pglite': 0.3.15 '@libsql/client': 0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6) '@types/sql.js': 1.4.11 bun-types: 1.3.14 - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) expo-sqlite: 58.0.15(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0) pg: 8.23.0 sql.js: 1.15.0 @@ -19060,7 +19060,7 @@ snapshots: ee-first@1.1.1: {} - effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337): {} + effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28): {} ejs@3.1.10: dependencies: From 29a33f8827ae4bbc14a315cc56938b5fbabbade5 Mon Sep 17 00:00:00 2001 From: Simone Date: Mon, 23 Nov 2026 03:56:35 +0100 Subject: [PATCH 242/324] fix(antigravity): recognize attachments with MIME parameters (#39097) Co-authored-by: Simone <185146821+Lucenx9@users.noreply.github.com> --- .../acp/AntigravityAcpSupport.test.ts | 46 ++++++++++--------- .../src/provider/acp/AntigravityAcpSupport.ts | 2 +- 2 files changed, 25 insertions(+), 23 deletions(-) diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts index 7201d1edc0ba0..a68c1334c473f 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts @@ -508,29 +508,31 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => { }), ); - it.effect("sends supported audio files as native audio content", () => - Effect.gen(function* () { - const fixture = yield* makeAttachmentFixture(); - const audioAttachment = { - ...textAttachment, - id: "recording-1", - name: "recording.wav", - mimeType: "audio/wav", - } satisfies ChatAttachment; - const bytes = Buffer.from("RIFF....WAVEfmt ", "latin1"); - yield* fixture.write(audioAttachment, bytes); - const prompt = yield* buildAntigravityPrompt({ - input: "Transcribe this.", - attachments: [audioAttachment], - resolveAttachmentPath: fixture.resolve, - promptCapabilities: { image: true, audio: true, embeddedContext: true }, - }); + it.effect.each(["audio/wav", "audio/wav;codecs=1", "Audio/WAV \t; codecs=1"])( + "sends supported audio files as native audio content (%s)", + (mimeType) => + Effect.gen(function* () { + const fixture = yield* makeAttachmentFixture(); + const audioAttachment = { + ...textAttachment, + id: "recording-1", + name: "recording.wav", + mimeType, + } satisfies ChatAttachment; + const bytes = Buffer.from("RIFF....WAVEfmt ", "latin1"); + yield* fixture.write(audioAttachment, bytes); + const prompt = yield* buildAntigravityPrompt({ + input: "Transcribe this.", + attachments: [audioAttachment], + resolveAttachmentPath: fixture.resolve, + promptCapabilities: { image: true, audio: true, embeddedContext: true }, + }); - expect(prompt).toEqual([ - { type: "text", text: "Transcribe this." }, - { type: "audio", data: bytes.toString("base64"), mimeType: "audio/wav" }, - ]); - }), + expect(prompt).toEqual([ + { type: "text", text: "Transcribe this." }, + { type: "audio", data: bytes.toString("base64"), mimeType: "audio/wav" }, + ]); + }), ); it.effect.each([{ image: true }])( diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.ts index 4d57305f7e0ec..f16c143cc278c 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.ts @@ -428,7 +428,7 @@ export const buildAntigravityPrompt = Effect.fn("buildAntigravityPrompt")(functi "source" in attachment && attachment.source?._tag === "pasted-text"; // The text already carries the path; keep folded pastes lazy so agents can search without embedding the whole file. - const mimeType = attachment.mimeType.toLowerCase().split(";", 1)[0] ?? ""; + const mimeType = attachment.mimeType.split(";", 1)[0]?.trim().toLowerCase() ?? ""; const image = attachment.type === "image" && IMAGE_MIME_TYPES.has(mimeType); const audio = attachment.type === "file" && AUDIO_MIME_TYPES.has(mimeType); const pdf = attachment.type === "file" && mimeType === "application/pdf"; From 27ab8d49eba9bd5f0910e71891bcdb719e0850a0 Mon Sep 17 00:00:00 2001 From: Simone Date: Mon, 23 Nov 2026 03:56:43 +0100 Subject: [PATCH 243/324] fix(antigravity): keep shortened question text valid Unicode (#39478) Co-authored-by: Simone <185146821+Lucenx9@users.noreply.github.com> --- .../src/provider/acp/AntigravityProtocol.test.ts | 16 +++++++++++----- .../src/provider/acp/AntigravityProtocol.ts | 16 ++++++++-------- 2 files changed, 19 insertions(+), 13 deletions(-) diff --git a/apps/server/src/provider/acp/AntigravityProtocol.test.ts b/apps/server/src/provider/acp/AntigravityProtocol.test.ts index 93f7d1fc377c8..d86ca3ead0f3c 100644 --- a/apps/server/src/provider/acp/AntigravityProtocol.test.ts +++ b/apps/server/src/provider/acp/AntigravityProtocol.test.ts @@ -253,17 +253,23 @@ describe("Antigravity permissions and questions", () => { }); it("bounds question text without changing choice IDs", () => { + const title = "Q".repeat(7_994) + "🧪"; + const label = "O".repeat(506) + "🧪"; const request = { ...questionRequest, - toolCall: { ...questionRequest.toolCall, title: "Question ".repeat(2_000) }, + toolCall: { ...questionRequest.toolCall, title: title + "🚀 continued" }, options: [ - { optionId: "stable-choice", name: "Choice ".repeat(2_000), kind: "allow_once" as const }, + { optionId: "stable-choice", name: label + "🚀 continued", kind: "allow_once" as const }, ], }; const question = extractAntigravityUserInputQuestion(request); - expect(question?.question.length).toBeLessThanOrEqual(8_000); - expect(question?.options[0]?.label.length).toBeLessThanOrEqual(512); - expect(question?.options[0]?.value).toBe("stable-choice"); + expect(question?.question).toBe(title + "..."); + expect(question?.options).toEqual([ + { value: "stable-choice", label: label + "...", description: label + "..." }, + ]); + expect( + makeAntigravityUserInputResponse(request, { interaction_9960062f: label + "..." }), + ).toEqual({ outcome: { outcome: "selected", optionId: "stable-choice" } }); }); }); diff --git a/apps/server/src/provider/acp/AntigravityProtocol.ts b/apps/server/src/provider/acp/AntigravityProtocol.ts index 2e59a78e376b4..008579d087f05 100644 --- a/apps/server/src/provider/acp/AntigravityProtocol.ts +++ b/apps/server/src/provider/acp/AntigravityProtocol.ts @@ -125,11 +125,14 @@ function copyBoundedText(text: string): string { return Buffer.from(text, "utf16le").toString("utf16le"); } +function boundQuestionText(text: string, limit: number): string { + if (text.length <= limit) return text; + const prefix = text.slice(0, limit - 3).replace(/[\uD800-\uDBFF]$/u, ""); + return copyBoundedText(`${prefix}...`); +} + function questionLabel(option: EffectAcpSchema.PermissionOption): string { - const label = option.name.trim() || option.optionId; - return label.length > QUESTION_LABEL_LIMIT - ? copyBoundedText(`${label.slice(0, QUESTION_LABEL_LIMIT - 3)}...`) - : label; + return boundQuestionText(option.name.trim() || option.optionId, QUESTION_LABEL_LIMIT); } export function extractAntigravityUserInputQuestion( @@ -149,10 +152,7 @@ export function extractAntigravityUserInputQuestion( return { id: request.toolCall.toolCallId, header: "Question", - question: - question.length > TOOL_TEXT_LIMIT - ? copyBoundedText(`${question.slice(0, TOOL_TEXT_LIMIT - 3)}...`) - : question, + question: boundQuestionText(question, TOOL_TEXT_LIMIT), multiSelect: false, allowCustomAnswer: false, options: request.options.map((option) => ({ From b9c310971001a4b0ca3010ddb13af4d028c60acc Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Sun, 22 Nov 2026 20:58:19 -0600 Subject: [PATCH 244/324] fix(cursor): preserve ended turns when connection retries exhaust (#41176) --- .../src/server/adapter.test.ts | 48 +++++++++++++++++++ .../provider-cursor/src/server/adapter.ts | 10 ++-- 2 files changed, 54 insertions(+), 4 deletions(-) diff --git a/packages/provider-cursor/src/server/adapter.test.ts b/packages/provider-cursor/src/server/adapter.test.ts index dfa1ac4865269..85cc2535960b8 100644 --- a/packages/provider-cursor/src/server/adapter.test.ts +++ b/packages/provider-cursor/src/server/adapter.test.ts @@ -445,6 +445,54 @@ describe("CursorAdapterV2", () => { failure: null, answers: [], }, + { + reason: "no failure when the connection fails after the turn ended", + updates: [ + { type: "text-delta", text: "Done." }, + { type: "turn-ended" }, + ] satisfies ReadonlyArray, + wait: Effect.succeed({ + id: "native-cursor-run", + requestId: "native-request", + status: "error" as const, + error: { message: "Connection failed repeatedly" }, + model: { id: "claude-fable-5" }, + durationMs: 1, + }), + failure: null, + }, + { + reason: "a connection failure before the turn ends", + updates: [ + { type: "text-delta", text: "Working." }, + ] satisfies ReadonlyArray, + wait: Effect.succeed({ + id: "native-cursor-run", + requestId: "native-request", + status: "error" as const, + error: { message: "Connection failed repeatedly" }, + model: { id: "claude-fable-5" }, + durationMs: 1, + }), + failure: { class: "provider_error", message: "Connection failed repeatedly" }, + }, + { + reason: "a connection failure during a continuation after the turn ended", + updates: [ + { type: "text-delta", text: "Done." }, + { type: "turn-ended" }, + { type: "step-started", stepId: 2 }, + ] satisfies ReadonlyArray, + wait: Effect.succeed({ + id: "native-cursor-run", + requestId: "native-request", + status: "error" as const, + error: { message: "Connection failed repeatedly" }, + model: { id: "claude-fable-5" }, + durationMs: 1, + }), + failure: { class: "provider_error", message: "Connection failed repeatedly" }, + }, { reason: "the token usage Cursor reported", // Cursor's inputTokens already include cache reads and writes. diff --git a/packages/provider-cursor/src/server/adapter.ts b/packages/provider-cursor/src/server/adapter.ts index 8fe8fed5917f7..6b04e17c120a1 100644 --- a/packages/provider-cursor/src/server/adapter.ts +++ b/packages/provider-cursor/src/server/adapter.ts @@ -928,9 +928,11 @@ interface CursorProjectionTarget { const MAX_CURSOR_STREAMED_OUTPUT_CHARS = 256 * 1024; // After a turn ends, a retryable stream error can make Cursor's SDK resume from // an older checkpoint inside the same run. When those resumes save nothing, it -// ends the run with this error even though the answer was already delivered. -const CURSOR_RESUME_NO_PROGRESS_MESSAGE = - "Agent turn stopped after repeated resume attempts made no progress"; +// ends with either retry limit even though the answer was already delivered. +const CURSOR_POST_TURN_RETRY_ERRORS = new Set([ + "Agent turn stopped after repeated resume attempts made no progress", + "Connection failed repeatedly", +]); interface ActiveCursorToolCall { readonly callId: string; @@ -2690,7 +2692,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( const isResumeFailureAfterTurnEnded = (context: ActiveCursorTurn, result: RunResult) => context.turnEnded && result.status === "error" && - result.error?.message === CURSOR_RESUME_NO_PROGRESS_MESSAGE; + CURSOR_POST_TURN_RETRY_ERRORS.has(result.error?.message ?? ""); const terminalStatus = ( context: ActiveCursorTurn, From 074a0d35be9ff1e55355bbc2e12715b12d7b56d3 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 19:05:07 -0800 Subject: [PATCH 245/324] fix(server): startup PR backfill looks up each repository branch once (#41175) --- .../ThreadPullRequestService.test.ts | 99 +++++++++++++++++++ .../ThreadPullRequestService.ts | 55 ++++++++--- 2 files changed, 138 insertions(+), 16 deletions(-) diff --git a/apps/server/src/orchestration-v2/ThreadPullRequestService.test.ts b/apps/server/src/orchestration-v2/ThreadPullRequestService.test.ts index e80faac5c1902..11710743816f9 100644 --- a/apps/server/src/orchestration-v2/ThreadPullRequestService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadPullRequestService.test.ts @@ -800,6 +800,105 @@ describe("ThreadPullRequestServiceV2 reads", () => { }), ); + it.effect("startup backfill looks up a branch once for threads whose worktrees are gone", () => + Effect.gen(function* () { + // Removed worktree folders all fall back to the project root, so they share one lookup. + const shared = ["a", "b", "c", "d"].map((suffix) => ({ + ...threadShell(`gone-worktree-${suffix}`), + branch: "feature/shared", + worktreePath: `/workspace/worktrees/gone-${suffix}`, + settledAt: NOW, + })); + // Every start repeats the backfill, so it reads only the most recently updated threads. + const older = Array.from({ length: 100 }, (_, index) => ({ + ...threadShell(`old-${index}`), + branch: `t3/old-${index}`, + worktreePath: `/workspace/worktrees/old-${index}`, + settledAt: NOW, + updatedAt: DateTime.subtract(NOW, { minutes: index + 1 }), + })); + const threads = [...older.toReversed(), ...shared]; + const project: OrchestrationProjectShell = { + id: threads[0]!.projectId, + title: "Project", + workspaceRoot: "/workspace/project", + defaultModelSelection: null, + scripts: [], + createdAt: "2026-08-01T00:00:00.000Z", + updatedAt: "2026-08-01T00:00:00.000Z", + }; + const activation = yield* Deferred.make(); + const sweeps = yield* Queue.unbounded(); + const lookups: Array<{ readonly cwd: string; readonly branch: string }> = []; + const dependencies = Layer.mergeAll( + Layer.mock(Orchestrator.OrchestratorV2)({ + streamDomainEvents: Stream.never, + getPullRequestSnapshot: () => + Queue.offer(sweeps, undefined).pipe( + Effect.as({ + schemaVersion: 2, + snapshotSequence: 1, + threads, + archivedThreads: [], + }), + ), + }), + Layer.mock(ProjectStore.ProjectStoreV2)({ + listShells: () => Effect.succeed([project]), + getShell: () => Effect.succeedSome(project), + }), + Layer.mock(GitManager.GitManager)({ + branchPullRequest: (input) => + Effect.sync(() => { + lookups.push({ cwd: input.cwd, branch: input.branch }); + return null; + }), + }), + Layer.mock(PullRequestService.PullRequestService)({ + notifyLinkedThreadsChanged: Effect.void, + }), + Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({ + resolve: () => + Effect.succeed({ + canonicalKey: "github.com/acme/project", + locator: { + source: "git-remote" as const, + remoteName: "origin", + remoteUrl: "git@github.com:acme/project.git", + }, + provider: SourceControlProviderKind.make("github"), + owner: "acme", + name: "project", + }), + }), + Layer.mock(BackgroundPolicy.BackgroundPolicy)({ + shouldRunScopeWork: () => Effect.succeed(true), + shouldRunOpportunisticWork: Effect.succeed(true), + }), + Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)), + Layer.succeed( + SecureRandom.SecureRandom, + SecureRandom.make((size) => new Uint8Array(size).fill(1)), + ), + FileSystem.layerNoop({}), + Path.layer, + ); + yield* Effect.gen(function* () { + const service = yield* ThreadPullRequestService.make; + yield* service.start(); + yield* Deferred.succeed(activation, undefined); + + yield* Queue.take(sweeps); + yield* service.drain; + + expect(lookups.map((lookup) => lookup.branch).toSorted()).toEqual( + ["feature/shared", ...older.slice(0, 60).map((thread) => thread.branch)].toSorted(), + ); + expect(lookups.every((lookup) => lookup.cwd === project.workspaceRoot)).toBe(true); + }).pipe(Effect.provide(dependencies)); + }), + ); + it.effect.each([ { state: "open", checkedOut: false }, { state: "merged", checkedOut: false }, diff --git a/apps/server/src/orchestration-v2/ThreadPullRequestService.ts b/apps/server/src/orchestration-v2/ThreadPullRequestService.ts index 5c32dda1d183c..762c2f71c6d33 100644 --- a/apps/server/src/orchestration-v2/ThreadPullRequestService.ts +++ b/apps/server/src/orchestration-v2/ThreadPullRequestService.ts @@ -110,6 +110,7 @@ export function projectWorkspaceMatchesSnapshot( } const BACKFILL_ATTEMPTS = 5; +const BACKFILL_THREADS = 64; const REPOSITORY_LOOKUP_CONCURRENCY = 4; interface RefreshRequest { @@ -237,13 +238,23 @@ export const make = Effect.gen(function* () { const projects = new Map(projectShells.map((project) => [project.id, project])); const nowMs = DateTime.toEpochMillis(yield* DateTime.now); if (request.backfill) { - for (const thread of snapshotThreads) { - if ( + // Nothing records a lookup that found no pull request, so every start repeats this. + // Only the most recently updated threads are read; older ones wait for their own events. + const candidates = snapshotThreads.filter( + (thread) => + thread.archivedAt === null && + thread.branch !== null && (thread.settledOverride === "settled" || thread.settledAt !== null) && - thread.branchPullRequest == null - ) { - pendingBackfill.set(thread.id, BACKFILL_ATTEMPTS); - } + thread.branchPullRequest == null, + ); + const recent = candidates + .toSorted( + (left, right) => + DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt), + ) + .slice(0, BACKFILL_THREADS); + for (const thread of recent) { + pendingBackfill.set(thread.id, BACKFILL_ATTEMPTS); } } const visibleThreadIds = new Set( @@ -261,8 +272,28 @@ export const make = Effect.gen(function* () { pendingBackfill.has(thread.id)) && (thread.branch !== null || thread.branchPullRequest != null), ); + // Threads whose worktree is gone fall back to the project root, so they share its lookup. + // A worktree folder can outlive its .git, and git there fails with not_a_repository. + // An unreadable .git keeps the worktree rather than failing the whole group. + const lookupCwds = new Map(); + yield* Effect.forEach( + threads, + (thread) => + Effect.gen(function* () { + const project = projects.get(thread.projectId); + const cwd = + thread.worktreePath !== null && + (yield* fileSystem + .exists(path.join(thread.worktreePath, ".git")) + .pipe(Effect.orElseSucceed(() => true))) + ? thread.worktreePath + : (project?.workspaceRoot ?? null); + lookupCwds.set(thread.id, cwd); + }), + { concurrency: 32, discard: true }, + ); const groups = Map.groupBy(threads, (thread) => - JSON.stringify([thread.projectId, thread.worktreePath, thread.branch]), + JSON.stringify([thread.projectId, lookupCwds.get(thread.id), thread.branch]), ); // A thread's own events and a backfill read at once; only scheduled sweeps wait. @@ -298,15 +329,7 @@ export const make = Effect.gen(function* () { refresh: request.refresh, }); if (first.branch !== null && repository === null) return finishBackfill(group); - // A worktree folder can outlive its .git, and git there fails with not_a_repository. - // An unreadable .git keeps the worktree rather than failing the whole group. - const cwd = - first.worktreePath !== null && - (yield* fileSystem - .exists(path.join(first.worktreePath, ".git")) - .pipe(Effect.orElseSucceed(() => true))) - ? first.worktreePath - : project.workspaceRoot; + const cwd = lookupCwds.get(first.id) ?? project.workspaceRoot; // A detected PR is confirmed against fresh git state before it is saved. const detected = first.branch === null From 8a17857870487f7a475a306d8dadfc264039f5d6 Mon Sep 17 00:00:00 2001 From: Isaac-b-ux Date: Sun, 22 Nov 2026 22:13:10 -0500 Subject: [PATCH 246/324] perf(mobile): avoid re-rendering on shell updates in useSidebarRowThreadKey (#41143) Co-authored-by: Isaac-b-ux <264455269+Isaac-b-ux@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../threads/useSidebarRowThreadKey.test.tsx | 94 +++++++++++++++++++ .../threads/useSidebarRowThreadKey.ts | 24 ++++- apps/mobile/vite.config.ts | 1 + 3 files changed, 114 insertions(+), 5 deletions(-) create mode 100644 apps/mobile/src/features/threads/useSidebarRowThreadKey.test.tsx diff --git a/apps/mobile/src/features/threads/useSidebarRowThreadKey.test.tsx b/apps/mobile/src/features/threads/useSidebarRowThreadKey.test.tsx new file mode 100644 index 0000000000000..ef58c0571ce0c --- /dev/null +++ b/apps/mobile/src/features/threads/useSidebarRowThreadKey.test.tsx @@ -0,0 +1,94 @@ +import { act, useLayoutEffect } from "react"; +import { createRoot } from "react-dom/client"; +import { RegistryContext } from "@effect/atom-react"; +import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { type Atom, AtomRegistry } from "effect/reactivity"; +import { describe, expect, it, vi } from "vite-plus/test"; + +import { scopedThreadKey } from "../../lib/scopedEntities"; +import { environmentThreadShells } from "../../state/threads"; +import { makeThreadShellFixture } from "../../test-fixtures"; +import { useSidebarRowThreadKey } from "./useSidebarRowThreadKey"; + +vi.mock("../../state/threads", async () => { + const { Atom: ReactivityAtom } = await import("effect/reactivity"); + return { + environmentThreadShells: { + quietThreadShellsAtom: ReactivityAtom.make([]).pipe( + ReactivityAtom.keepAlive, + ), + }, + }; +}); + +const quietThreadShellsAtom = environmentThreadShells.quietThreadShellsAtom as Atom.Writable< + readonly EnvironmentThreadShell[] +>; + +describe("useSidebarRowThreadKey", () => { + it("re-renders only when the resolved row key changes", async () => { + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + using _globals = { [Symbol.dispose]: () => vi.unstubAllGlobals() }; + const registry = AtomRegistry.make(); + using _registry = { [Symbol.dispose]: () => registry.dispose() }; + + const envId = EnvironmentId.make("env-1"); + const parentId = ThreadId.make("thread-parent"); + const childId = ThreadId.make("thread-child"); + const parentKey = scopedThreadKey(envId, parentId); + const childKey = scopedThreadKey(envId, childId); + const parentThread = makeThreadShellFixture({ + environmentId: envId, + id: parentId, + title: "Parent", + }); + const childThread = makeThreadShellFixture({ + environmentId: envId, + id: childId, + title: "Delegated child", + delegatedFrom: { environmentId: envId, threadId: parentId, title: "Parent" }, + }); + const otherThread = (title: string) => + makeThreadShellFixture({ environmentId: envId, id: ThreadId.make("thread-other"), title }); + + registry.set(quietThreadShellsAtom, [parentThread, childThread, otherThread("v1")]); + + const seen: Array = []; + function Probe(props: { openThreadKey: string | null }) { + const value = useSidebarRowThreadKey(props.openThreadKey); + useLayoutEffect(() => { + seen.push(value); + }); + return null; + } + + const root = createRoot(document.createElement("div")); + using _root = { [Symbol.dispose]: () => act(() => root.unmount()) }; + const renderKey = (openThreadKey: string | null) => + act(async () => + root.render( + + + , + ), + ); + const setShells = (shells: readonly EnvironmentThreadShell[]) => + act(async () => registry.set(quietThreadShellsAtom, shells)); + + await renderKey(null); + await setShells([parentThread, childThread, otherThread("v2")]); + expect(seen).toEqual([null]); + + await renderKey(childKey); + await setShells([parentThread, childThread, otherThread("v3")]); + expect(seen).toEqual([null, parentKey]); + + await setShells([ + { ...parentThread, archivedAt: "2026-01-02T00:00:00.000Z" }, + childThread, + otherThread("v3"), + ]); + expect(seen).toEqual([null, parentKey, childKey]); + }); +}); diff --git a/apps/mobile/src/features/threads/useSidebarRowThreadKey.ts b/apps/mobile/src/features/threads/useSidebarRowThreadKey.ts index 0e72dad60ca0d..a08efc2a0886a 100644 --- a/apps/mobile/src/features/threads/useSidebarRowThreadKey.ts +++ b/apps/mobile/src/features/threads/useSidebarRowThreadKey.ts @@ -1,15 +1,29 @@ import { useAtomValue } from "@effect/atom-react"; import { parseScopedThreadKey } from "@t3tools/client-runtime/environment"; import { resolveListedAncestorThreadRef } from "@t3tools/client-runtime/state/threads"; +import { Atom } from "effect/reactivity"; import { scopedThreadKey } from "../../lib/scopedEntities"; import { environmentThreadShells } from "../../state/threads"; +const NULL_ROW_KEY_ATOM = Atom.make(null); + +// Deriving the resolved key inside an atom family avoids subscribing to the full shell list when +// no row is selected (phone portrait) and avoids re-rendering on shell frames that do not change +// the open thread's listed ancestor row. +const sidebarRowThreadKeyAtom = Atom.family((openThreadKey: string) => + Atom.make((get): string | null => { + const openThreadRef = parseScopedThreadKey(openThreadKey); + if (openThreadRef === null) return openThreadKey; + const threads = get(environmentThreadShells.quietThreadShellsAtom); + const rowRef = resolveListedAncestorThreadRef(openThreadRef, threads); + return scopedThreadKey(rowRef.environmentId, rowRef.threadId); + }), +); + /** An open subagent, side chat or delegated task has no row; its listed ancestor's row is selected. */ export function useSidebarRowThreadKey(openThreadKey: string | null): string | null { - const threads = useAtomValue(environmentThreadShells.quietThreadShellsAtom); - const openThreadRef = openThreadKey === null ? null : parseScopedThreadKey(openThreadKey); - if (openThreadRef === null) return openThreadKey; - const rowRef = resolveListedAncestorThreadRef(openThreadRef, threads); - return scopedThreadKey(rowRef.environmentId, rowRef.threadId); + return useAtomValue( + openThreadKey === null ? NULL_ROW_KEY_ATOM : sidebarRowThreadKeyAtom(openThreadKey), + ); } diff --git a/apps/mobile/vite.config.ts b/apps/mobile/vite.config.ts index ee001a3a5e3d4..436cea63f4f28 100644 --- a/apps/mobile/vite.config.ts +++ b/apps/mobile/vite.config.ts @@ -51,6 +51,7 @@ const reactTests = [ "src/features/terminal/useTerminalExitNavigation.test.tsx", "src/features/threads/use-thread-list-now.test.tsx", "src/features/threads/use-composer-command-menu.select.test.tsx", + "src/features/threads/useSidebarRowThreadKey.test.tsx", "src/features/threads/useThreadListV2.test.tsx", "src/features/home/home-list-options.test.tsx", "src/features/home/home-route-visibility.test.tsx", From 1a4932efd06eff5efce4c19072cd598a9d393d42 Mon Sep 17 00:00:00 2001 From: Alex Southwell Date: Mon, 23 Nov 2026 14:15:05 +1100 Subject: [PATCH 247/324] perf(client): skip child indexing when no child needs input (#25537) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: SAPHID Co-authored-by: shivam <91240327+shivamhwp@users.noreply.github.com> Co-authored-by: Claude Fable 5.2 --- .../src/state/threadShell.test.ts | 31 +++++++++++++++++++ .../client-runtime/src/state/threadShell.ts | 16 +++++++++- 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/packages/client-runtime/src/state/threadShell.test.ts b/packages/client-runtime/src/state/threadShell.test.ts index de1bc04aeda8a..9210949afb737 100644 --- a/packages/client-runtime/src/state/threadShell.test.ts +++ b/packages/client-runtime/src/state/threadShell.test.ts @@ -61,6 +61,35 @@ function makeHarness(environmentIds: ReadonlyArray = [environment } describe("v2 thread shell lists", () => { + it("builds no child index while no child asks for input", () => { + const { registry, threads, snapshotAtom } = makeHarness(); + let parentIdReads = 0; + const child = { + ...v2ThreadShell, + id: ThreadId.make("child"), + creationSource: "mcp" as const, + lineage: { + rootThreadId: v2ThreadShell.id, + relationshipToParent: "subagent" as const, + // Nothing is pending, so only the child index would read parent ids. + get parentThreadId() { + parentIdReads++; + return v2ThreadShell.id; + }, + }, + }; + const inputs = threads.childThreadInputsAtom({ environmentId, threadId: v2ThreadShell.id }); + const dispose = registry.mount(inputs); + registry.set(snapshotAtom(environmentId), { + ...v2ShellSnapshot, + threads: [v2ThreadShell, child], + }); + expect(registry.get(inputs)).toEqual([]); + expect(parentIdReads).toBe(0); + dispose(); + registry.dispose(); + }); + it("preserves ordered reference arrays when a middle thread changes", () => { const { registry, threads, snapshotAtom } = makeHarness(); const snapshot = { @@ -160,6 +189,8 @@ describe("v2 thread shell lists", () => { threads: [root, { ...legacyChild, status: "completed" as const }], }); expect(registry.get(inputs)).toEqual([]); + registry.set(snapshotAtom(environmentId), { ...v2ShellSnapshot, threads: [root, child] }); + expect(registry.get(inputs).map((thread) => thread.id)).toEqual([child.id]); dispose(); registry.dispose(); }); diff --git a/packages/client-runtime/src/state/threadShell.ts b/packages/client-runtime/src/state/threadShell.ts index d5c60570b0a18..3325346d5d153 100644 --- a/packages/client-runtime/src/state/threadShell.ts +++ b/packages/client-runtime/src/state/threadShell.ts @@ -147,6 +147,9 @@ function sideChatRequest(thread: OrchestrationV2ThreadShell): PendingSubagentReq return kind === "user_input" ? "user_input" : "approval"; } +const asksParent = (thread: OrchestrationV2ThreadShell) => + subagentRequest(thread) !== null || sideChatRequest(thread) !== null; + /** * The threads to flag for a subagent's live approval, up its * subagent chain and through a side chat to its parent. `delegated` are tasks this @@ -496,12 +499,23 @@ export function createEnvironmentThreadShellAtoms(input: { }).pipe(Atom.withLabel(`environment-quiet-thread-shell:${key}`)); }); + const hasChildThreadInputsAtom = Atom.make((get) => { + for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) { + if (get(environmentThreadsAtom(environmentId)).some(asksParent)) return true; + } + return false; + }).pipe(Atom.withLabel("environment-has-child-thread-inputs")); + // Child approvals and questions are hidden with their sidebar rows. Read their // shell summaries, without subscribing to every child transcript. A task // delegated to a linked environment is a child too, with its own subagents. const childThreadInputsAtomFamily = Atom.family((key: string) => { let previous: ReadonlyArray = []; return Atom.make((get) => { + if (!get(hasChildThreadInputsAtom)) { + if (previous.length !== 0) previous = []; + return previous; + } const children = new Map< string, Array<{ environmentId: EnvironmentId; thread: OrchestrationV2ThreadShell }> @@ -537,7 +551,7 @@ export function createEnvironmentThreadShellAtoms(input: { if (seen.has(childKey)) continue; seen.add(childKey); pending.push(childKey); - if (subagentRequest(thread) !== null || sideChatRequest(thread) !== null) { + if (asksParent(thread)) { next.push( scopedThread(environmentId, thread, get(pendingSubagentRequestsAtom(environmentId))), ); From 86349553c5aeb24196905368bcf5d25c70da626a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bazyli=20Brz=C3=B3ska?= Date: Sun, 22 Nov 2026 19:17:25 -0800 Subject: [PATCH 248/324] fix(server): app links no longer leave the preview stuck loading (#41168) Co-authored-by: Julius Marminge --- apps/server/src/preview/ServerBrowser.test.ts | 35 ++++++++++++ apps/server/src/preview/ServerBrowser.ts | 19 ++++++- packages/shared/package.json | 4 ++ packages/shared/src/appLinks.test.ts | 32 +++++++++++ packages/shared/src/appLinks.ts | 22 ++++++++ ...rver-preview-app-link-stops-loading.e2e.ts | 53 +++++++++++++++++++ 6 files changed, 164 insertions(+), 1 deletion(-) create mode 100644 packages/shared/src/appLinks.test.ts create mode 100644 packages/shared/src/appLinks.ts create mode 100644 scripts/scenarios/server-preview-app-link-stops-loading.e2e.ts diff --git a/apps/server/src/preview/ServerBrowser.test.ts b/apps/server/src/preview/ServerBrowser.test.ts index a15378ec3039c..d8e5f0622241c 100644 --- a/apps/server/src/preview/ServerBrowser.test.ts +++ b/apps/server/src/preview/ServerBrowser.test.ts @@ -2144,6 +2144,41 @@ it.effect("a request whose frame is not available yet is not a main navigation", ).pipe(Effect.provide(layer)), ); +it.effect("an app link's aborted request leaves the page it was clicked on", () => + Effect.scoped( + Effect.gen(function* () { + const { broker, tabId } = yield* ready; + const page = contexts[0]!.page; + const navigation = (url: string, redirectedFrom: unknown = null) => ({ + url: () => url, + method: () => "GET", + isNavigationRequest: () => true, + redirectedFrom: () => redirectedFrom, + frame: () => page, + failure: () => ({ errorText: "net::ERR_ABORTED" }), + }); + const loading = Effect.map( + broker.invoke({ scope, tabId, operation: "status", input: {} }), + (status) => status.loading, + ); + // Chromium hands the link to the OS, aborts the request and keeps the current page. + const direct = navigation("obsidian://open?vault=notes"); + page.emit("request", direct); + page.emit("requestfailed", direct); + expect(yield* loading).toBe(false); + + // A page that redirects to an app link ends its navigation there; the redirect itself finished. + const open = navigation("https://example.com/open"); + page.emit("request", open); + expect(yield* loading).toBe(true); + const redirected = navigation("obsidian://open?vault=notes", open); + page.emit("request", redirected); + page.emit("requestfailed", redirected); + expect(yield* loading).toBe(false); + }), + ).pipe(Effect.provide(layer)), +); + it.effect.each(["before", "during"] as const)( "a navigation that fails while a load reads its title keeps its failure (request %s read)", (requestTiming) => diff --git a/apps/server/src/preview/ServerBrowser.ts b/apps/server/src/preview/ServerBrowser.ts index 26203fc1a63c8..9fd94232a5e23 100644 --- a/apps/server/src/preview/ServerBrowser.ts +++ b/apps/server/src/preview/ServerBrowser.ts @@ -51,6 +51,7 @@ import { import { AgentScope, agentScopeLauncherScript } from "@t3tools/shared/AgentScope"; import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { appLinkUrl } from "@t3tools/shared/appLinks"; import { normalizePreviewUrl } from "@t3tools/shared/preview"; import { resolvePreviewViewport } from "@t3tools/shared/previewViewport"; import * as NodeCrypto from "node:crypto"; @@ -1245,15 +1246,31 @@ const make = Effect.gen(function* () { } // Playwright's `request.frame()` throws for a request issued before its frame exists, and a // throw from a page listener is uncaught, so such a request is not a main-frame navigation. - const isMainNavigation = (request: { isNavigationRequest(): boolean; frame(): unknown }) => { + const isMainFrameNavigation = (request: { + isNavigationRequest(): boolean; + frame(): unknown; + }) => { try { return request.isNavigationRequest() && request.frame() === page.mainFrame(); } catch { return false; } }; + // Chromium aborts an app link's request and keeps the page, so it is no navigation. + const isMainNavigation = (request: { + isNavigationRequest(): boolean; + url(): string; + frame(): unknown; + }) => appLinkUrl(request.url()) === null && isMainFrameNavigation(request); const navigationGenerations = new WeakMap(); page.on("request", (request) => { + if (appLinkUrl(request.url()) !== null && isMainFrameNavigation(request)) { + // A redirect into an app link ends the navigation that led there. + const redirectedFrom = request.redirectedFrom(); + const generation = redirectedFrom && navigationGenerations.get(redirectedFrom); + if (generation) settleAbortedNavigation(tab, generation, request.url(), undefined); + return; + } if (!isMainNavigation(request)) return; // Playwright can deliver the first request after Stop has already settled its navigation. const stoppedInitialRequest = diff --git a/packages/shared/package.json b/packages/shared/package.json index b727b976fe143..d12cd9b003982 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -151,6 +151,10 @@ "types": "./src/toolOutput.ts", "import": "./src/toolOutput.ts" }, + "./appLinks": { + "types": "./src/appLinks.ts", + "import": "./src/appLinks.ts" + }, "./htmlRender": { "types": "./src/htmlRender.ts", "import": "./src/htmlRender.ts" diff --git a/packages/shared/src/appLinks.test.ts b/packages/shared/src/appLinks.test.ts new file mode 100644 index 0000000000000..2e3556803208f --- /dev/null +++ b/packages/shared/src/appLinks.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { appLinkUrl } from "./appLinks.ts"; + +describe("appLinkUrl", () => { + it("accepts schemes another app opens", () => { + expect(appLinkUrl("obsidian://open?vault=vault&file=Note")).toBe( + "obsidian://open?vault=vault&file=Note", + ); + expect(appLinkUrl("t3-thread://v2/env/thread")).toBe("t3-thread://v2/env/thread"); + expect(appLinkUrl("mailto:a@example.com")).toBe("mailto:a@example.com"); + }); + + it("rejects schemes the browser loads itself, and non-URLs", () => { + for (const url of [ + "https://example.com", + "http://example.com", + "javascript:alert(1)", + "JavaScript:alert(1)", + "data:text/html,x", + "file:///etc/passwd", + "blob:https://example.com/id", + "about:blank", + "view-source:https://example.com", + "chrome://settings", + "filesystem:https://example.com/temporary/a", + "not a url", + ]) { + expect(appLinkUrl(url), url).toBeNull(); + } + }); +}); diff --git a/packages/shared/src/appLinks.ts b/packages/shared/src/appLinks.ts new file mode 100644 index 0000000000000..85ebe6a6922f7 --- /dev/null +++ b/packages/shared/src/appLinks.ts @@ -0,0 +1,22 @@ +/** Schemes the browser engine loads itself; every other scheme names an app the OS opens. */ +const BROWSER_PROTOCOLS = [ + "about:", + "blob:", + "chrome:", + "data:", + "devtools:", + "file:", + "filesystem:", + "http:", + "https:", + "javascript:", + "view-source:", +]; + +const browserProtocols: ReadonlySet = new Set(BROWSER_PROTOCOLS); + +/** The normalized URL when it is an app link, such as `obsidian:` or `mailto:`, otherwise null. */ +export function appLinkUrl(rawUrl: string): string | null { + const url = URL.parse(rawUrl); + return url === null || browserProtocols.has(url.protocol) ? null : url.href; +} diff --git a/scripts/scenarios/server-preview-app-link-stops-loading.e2e.ts b/scripts/scenarios/server-preview-app-link-stops-loading.e2e.ts new file mode 100644 index 0000000000000..2aa4c70a1fa12 --- /dev/null +++ b/scripts/scenarios/server-preview-app-link-stops-loading.e2e.ts @@ -0,0 +1,53 @@ +// @effect-diagnostics-next-line nodeBuiltinImport:off - one fixture page for the server's browser to load +import * as NodeHttp from "node:http"; + +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +// One app link that fills the page. Its click renames the page a moment later, after the server +// has seen the link's request. +const PAGE = ` +Note link +Open the note`; + +test( + "An app link clicked in the Browser leaves the page shown and loaded", + WEB, + async ({ t3, app, browser, screen }) => { + const server = NodeHttp.createServer((_request, response) => { + response.writeHead(200, { "content-type": "text/html" }); + response.end(PAGE); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + try { + const address = server.address(); + if (address === null || typeof address === "string") throw new Error("No page port."); + const url = `http://127.0.0.1:${address.port}/`; + const project = await t3.project("demo"); + const thread = await t3.thread({ project, title: "Note check", messages: ["first"] }); + await t3.open(thread); + + await screen.getByRole("button", "Toggle right panel").tap(); + await screen.getByRole("button", "Browser B").tap(); + const addressBar = screen.getByRole("textbox", "Search or enter URL"); + await addressBar.fill(url); + await browser.keyboard.press("Enter"); + await expect(screen.getByText("Note link")).toBeVisible(); + + // The page draws on the canvas beside its input proxy. + await browser.locator('canvas:has(~ textarea[aria-label="Browser page"])').tap(); + try { + // Chromium hands the link to the OS and keeps the page, which goes on renaming itself. + await expect(screen.getByText("Link clicked")).toBeVisible({ timeout: 2_000 }); + await expect(addressBar).toHaveValue(url); + await expect(screen.getByRole("button", "Refresh", { exact: true })).toBeVisible(); + } finally { + await app.screenshot("after-click"); + } + } finally { + await new Promise((resolve) => server.close(resolve)); + } + }, +); From 047a86f5ab43d6330b6b50607049c991624ab1eb Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 19:34:22 -0800 Subject: [PATCH 249/324] fix(server): open Claude sessions on macOS share one process-table poll (#37585) Co-authored-by: Claude Opus 5.5 --- .../Adapters/ClaudeAdapterV2.ts | 120 ++++++++++++------ .../ClaudeAgentSdkQueryRunner.test.ts | 77 +++++++++-- 2 files changed, 147 insertions(+), 50 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 370b6b6c4c3f6..f6d84df4dcda9 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -534,40 +534,75 @@ function claudeDescendants( return found; } -/** What a CLI started, by pid and start time, recorded from each process table read while it runs. */ -export function makeClaudeDescendantTracker( - cliPid: number, +const processIdentity = (row: ClaudeProcessRow) => `${row.pid} ${row.started}`; + +/** What one CLI started, by pid and start time, recorded from each process table read while it runs. */ +function makeClaudeDescendantTracker(cliPid: number) { + const tracked = new Map(); + // After exit the CLI's pid may belong to an unrelated process, so only tracked jobs are roots. + const record = (rows: ReadonlyArray, cliRunning: boolean) => { + const running = new Set(rows.map(processIdentity)); + // `ps -A` lists itself, so no rows is a failed read. + if (rows.length === 0) return running; + const roots = cliRunning ? [cliPid] : []; + for (const [key, row] of tracked) { + if (running.has(key)) roots.push(row.pid); + else tracked.delete(key); + } + for (const row of claudeDescendants(rows, roots)) tracked.set(processIdentity(row), row); + return running; + }; + return { tracked: tracked as ReadonlyMap, record }; +} + +/** + * Process table reads for every running CLI. A poll reads the table once for all of them, so the + * `ps` cost does not grow with open sessions. + */ +export function makeClaudeDescendantPoll( readProcessTable: Effect.Effect>, ) { - const tracked = new Map(); - const identity = (row: ClaudeProcessRow) => `${row.pid} ${row.started}`; - // The poll, a session close and the exit read one at a time, so each table is newer than all - // recorded here, and a pid and start time it no longer lists never run again. + const live = new Set>(); + // Polls, session closes and exits read one at a time, so each table is newer than all recorded, + // and a pid and start time it no longer lists never run again. const reading = Semaphore.makeUnsafe(1); - // After exit the CLI's pid may belong to an unrelated process, so only tracked jobs are roots. - const refresh = Effect.fn("ClaudeAgentSdkQueryRunner.trackDescendants")( - function* (cliRunning: boolean) { - const rows = yield* readProcessTable; - const running = new Set(rows.map(identity)); - // `ps -A` lists itself, so no rows is a failed read. - if (rows.length === 0) return running; - const roots = cliRunning ? [cliPid] : []; - for (const [key, row] of tracked) { - if (running.has(key)) roots.push(row.pid); - else tracked.delete(key); - } - for (const row of claudeDescendants(rows, roots)) tracked.set(identity(row), row); - return running; - }, - (effect) => reading.withPermits(1)(effect), - ); + const read = (apply: (rows: ReadonlyArray) => A) => + reading.withPermits(1)(readProcessTable.pipe(Effect.map(apply))); return { - tracked: tracked as ReadonlyMap, - refresh: refresh(true).pipe(Effect.asVoid), - /** Reads the table after the CLI exited: what it left that is still the same process. */ - leftovers: refresh(false).pipe( - Effect.map((running) => [...tracked.values()].filter((row) => running.has(identity(row)))), - ), + // A table read before a CLI started may list an older process under its pid, so a poll records + // only into the CLIs tracked when its read began. + poll: reading + .withPermits(1)( + Effect.suspend(() => { + const tracked = [...live]; + return readProcessTable.pipe( + Effect.map((rows) => { + for (const tracker of tracked) if (live.has(tracker)) tracker.record(rows, true); + }), + ); + }), + ) + .pipe(Effect.withSpan("ClaudeAgentSdkQueryRunner.trackDescendants")), + track: (cliPid: number) => { + const tracker = makeClaudeDescendantTracker(cliPid); + live.add(tracker); + return { + tracked: tracker.tracked, + refresh: read((rows) => void tracker.record(rows, true)), + /** Reads the table after the CLI exited: what it left that is still the same process. */ + leftovers: Effect.sync(() => live.delete(tracker)).pipe( + Effect.andThen( + read((rows) => { + const running = tracker.record(rows, false); + return [...tracker.tracked.values()].filter((row) => + running.has(processIdentity(row)), + ); + }), + ), + ), + }; + }, + hasLive: () => live.size > 0, }; } @@ -1549,8 +1584,24 @@ export const layerQueryRunner: Layer.Layer< // Without an agent scope, a job that left the CLI's group escapes the group kill and is // re-parented once the CLI exits. So the CLI's tree is recorded while it runs, and what is // still the same process (pid and start time) is stopped after it exits. + const descendantPoll = makeClaudeDescendantPoll(readProcessTable); + // One poll serves every CLI. The first tracked CLI starts it; it stops once none is left. + let polling: Fiber.Fiber | undefined; const trackDescendants = (cliPid: number) => { - const tracker = makeClaudeDescendantTracker(cliPid, readProcessTable); + const tracker = descendantPoll.track(cliPid); + polling ??= runFork( + descendantPoll.poll.pipe( + Effect.repeat({ + schedule: Schedule.spaced(CLAUDE_DESCENDANT_POLL), + // Cleared in the same step that ends the poll, so the next tracked CLI starts a new one. + while: () => { + if (descendantPoll.hasLive()) return true; + polling = undefined; + return false; + }, + }), + ), + ); const stop = tracker.leftovers.pipe( Effect.map((rows) => { for (const row of rows) killClaudeDescendant(row); @@ -1666,12 +1717,7 @@ export const layerQueryRunner: Layer.Layer< ); if (unit === undefined && child.pid !== undefined) { const tracker = trackDescendants(child.pid); - const polling = runFork( - tracker.refresh.pipe(Effect.repeat(Schedule.spaced(CLAUDE_DESCENDANT_POLL))), - ); - child.once("exit", () => - runFork(Fiber.interrupt(polling).pipe(Effect.andThen(tracker.stop))), - ); + child.once("exit", () => runFork(tracker.stop)); refreshDescendants = tracker.refresh; } return child; diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts index 2bf2763c58c66..431ee35e27187 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts @@ -31,7 +31,7 @@ import { ClaudeAgentSdkQueryRunner, type ClaudeAgentSdkQueryOpenInput, layerQueryRunner, - makeClaudeDescendantTracker, + makeClaudeDescendantPoll, spawnClaudeProcessGroup, } from "./ClaudeAdapterV2.ts"; @@ -734,10 +734,7 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro "keeps only the descendants the CLI still has running, however many jobs it ran", () => { let table: ReadonlyArray> = []; - const tracker = makeClaudeDescendantTracker( - 1000, - Effect.sync(() => table), - ); + const tracker = makeClaudeDescendantPoll(Effect.sync(() => table)).track(1000); const jobs = (poll: number) => [0, 1, 2, 3].map((job) => 1100 + poll * 4 + job); return Effect.gen(function* () { for (let poll = 0; poll < 50; poll++) { @@ -781,10 +778,7 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro [processRow(1000, 10, 0), ...unrelated, orphan], [...unrelated, orphan], ]; - const tracker = makeClaudeDescendantTracker( - 1000, - Effect.sync(() => tables.shift() ?? []), - ); + const tracker = makeClaudeDescendantPoll(Effect.sync(() => tables.shift() ?? [])).track(1000); return Effect.gen(function* () { yield* tracker.refresh; yield* tracker.refresh; @@ -811,10 +805,7 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro processRow(1001, 1000, 0), processRow(1100, 1001, 1), ]); - const tracker = makeClaudeDescendantTracker( - 1000, - Effect.suspend(() => read), - ); + const tracker = makeClaudeDescendantPoll(Effect.suspend(() => read)).track(1000); return Effect.gen(function* () { yield* tracker.refresh; read = Deferred.succeed(olderReadStarted, undefined).pipe( @@ -840,6 +831,66 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro }, ); + it.effect("reads the process table once per poll for every running CLI", () => { + let reads = 0; + const descendantPoll = makeClaudeDescendantPoll( + Effect.sync(() => { + reads++; + return [ + processRow(1000, 10, 0), + processRow(1100, 1000, 1), + processRow(2000, 10, 0), + processRow(2100, 2000, 1), + ]; + }), + ); + const first = descendantPoll.track(1000); + const second = descendantPoll.track(2000); + return Effect.gen(function* () { + yield* descendantPoll.poll; + assert.strictEqual(reads, 1); + assert.deepStrictEqual( + [...first.tracked.values()].map((row) => row.pid), + [1100], + ); + assert.deepStrictEqual( + [...second.tracked.values()].map((row) => row.pid), + [2100], + ); + yield* first.leftovers; + assert.isTrue(descendantPoll.hasLive()); + yield* second.leftovers; + assert.isFalse(descendantPoll.hasLive()); + }); + }); + + it.effect("does not record a poll's table into a CLI tracked after the read began", () => { + const readStarted = Deferred.makeUnsafe(); + const table = Deferred.makeUnsafe>>(); + const descendantPoll = makeClaudeDescendantPoll( + Deferred.succeed(readStarted, undefined).pipe(Effect.andThen(Deferred.await(table))), + ); + return Effect.gen(function* () { + const first = descendantPoll.track(1000); + const polling = yield* descendantPoll.poll.pipe(Effect.forkChild); + yield* Deferred.await(readStarted); + // The earlier process at pid 2000 exited and the pid went to a newly tracked CLI. + const late = descendantPoll.track(2000); + yield* Deferred.succeed(table, [ + processRow(1000, 10, 0), + processRow(1100, 1000, 1), + processRow(2000, 10, 0), + processRow(2100, 2000, 1), + ]); + yield* Fiber.join(polling); + assert.deepStrictEqual( + [...first.tracked.values()].map((row) => row.pid), + [1100], + ); + assert.strictEqual(late.tracked.size, 0); + }); + }); + const rootRefusal = "--dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons"; From 18850a5eeb388148fc2b8fa3499bf8e624a1154c Mon Sep 17 00:00:00 2001 From: tiliakoos <73005126+tiliakoos@users.noreply.github.com> Date: Mon, 23 Nov 2026 04:34:29 +0100 Subject: [PATCH 250/324] fix(mobile): screen readers hear when a terminal Ctrl, Alt or Cmd key is latched (#41173) Co-authored-by: MarcoDotIO <20867620+MarcoDotIO@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../mobile/src/components/ComposerToolbar.tsx | 1 + ...nal-latched-modifier-reads-selected.e2e.ts | 41 +++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 scripts/scenarios/terminal-latched-modifier-reads-selected.e2e.ts diff --git a/apps/mobile/src/components/ComposerToolbar.tsx b/apps/mobile/src/components/ComposerToolbar.tsx index 36ed505d27cd0..a901d6fa60b50 100644 --- a/apps/mobile/src/components/ComposerToolbar.tsx +++ b/apps/mobile/src/components/ComposerToolbar.tsx @@ -376,6 +376,7 @@ export function ComposerToolbarButton(props: { { + const project = await t3.project("demo"); + const { threadId } = await t3.thread({ project, title: "Latched keys", messages: ["hello"] }); + await t3.open(); + await screen.getByText("Latched keys", { exact: false }).first().waitFor({ timeout: 120_000 }); + + const environment = await runPromise( + environmentId(`http://${MOBILE.host}:${MOBILE.serverPort}`), + ); + await device.openLink(`t3code-dev://threads/${environment}/${threadId}/terminal`, { + app: "com.t3tools.t3code.dev", + }); + await device.alert("accept").catch(() => {}); + + // The keyboard toolbar shows with the software keyboard; ctrl starts past its right edge. + const esc = screen.getByRole("button", "esc"); + await esc.waitFor({ timeout: 60_000 }); + const box = await esc.boundingBox(); + const x = (box?.x ?? 0) + (box?.width ?? 0); + const y = (box?.y ?? 0) + (box?.height ?? 0) / 2; + // A slow drag, so the scroller stops with ctrl in view instead of flinging to its end. + await screen.swipe({ from: { x, y }, to: { x: x - 150, y }, duration: 1_500 }); + const ctrl = screen.getByRole("button", "ctrl"); + await ctrl.waitFor(); + await ctrl.tap(); + await app.screenshot("ctrl-latched"); + await expect(ctrl).toBeSelected(); + + await ctrl.tap(); + await expect(ctrl).not.toBeSelected(); + }, +); From 372fbabe5fa6196a32ac0f926aaff402fbf60a09 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 19:36:25 -0800 Subject: [PATCH 251/324] fix(server): renaming a provider instance no longer stops its sessions (#41189) --- .../provider/ProviderInstanceRegistry.test.ts | 35 +++++++++ .../src/provider/ProviderInstanceRegistry.ts | 70 +++++++++++++++-- .../src/provider/ProviderRegistry.test.ts | 76 +++++++++++++++++++ apps/server/src/provider/ProviderRegistry.ts | 21 +++++ 4 files changed, 194 insertions(+), 8 deletions(-) diff --git a/apps/server/src/provider/ProviderInstanceRegistry.test.ts b/apps/server/src/provider/ProviderInstanceRegistry.test.ts index ce6416332bae0..94c5f3f8c3cfd 100644 --- a/apps/server/src/provider/ProviderInstanceRegistry.test.ts +++ b/apps/server/src/provider/ProviderInstanceRegistry.test.ts @@ -347,6 +347,41 @@ describe("ProviderInstanceRegistry — multi-instance codex slice", () => { }).pipe(Effect.provide(layerTest)), ); + it.effect.each([{ displayName: "Renamed" }, { accentColor: "#ff0000" }])( + "keeps the live instance when only %o changes", + (presentation) => + Effect.gen(function* () { + let closed = 0; + const driver: typeof CodexDriver = { + ...CodexDriver, + create: (input) => + Effect.gen(function* () { + const instance = yield* CodexDriver.create(input); + yield* Effect.addFinalizer(() => Effect.sync(() => closed++)); + return instance; + }), + }; + const instanceId = ProviderInstanceId.make("account-a"); + const entry = { + driver: CodexDriver.driverKind, + enabled: false, + displayName: "Account A", + config: makeCodexConfig({}), + }; + const { registry, mutator } = yield* makeProviderInstanceRegistry({ + drivers: [driver], + configMap: { [instanceId]: entry }, + }); + const instance = yield* registry.getInstance(instanceId); + const changes = yield* registry.subscribeChanges; + yield* mutator.reconcile({ [instanceId]: { ...entry, ...presentation } }); + expect(closed).toBe(0); + expect(yield* registry.getInstance(instanceId)).toBe(instance); + yield* PubSub.take(changes); + expect(yield* instance!.snapshot.getSnapshot).toMatchObject(presentation); + }).pipe(Effect.provide(layerTest)), + ); + it.effect("treats an explicit in-config enabled:false as disabling despite the envelope", () => Effect.gen(function* () { const staleId = ProviderInstanceId.make("codex_stale"); diff --git a/apps/server/src/provider/ProviderInstanceRegistry.ts b/apps/server/src/provider/ProviderInstanceRegistry.ts index 9ab3f56aedcd5..f343093d7c9ef 100644 --- a/apps/server/src/provider/ProviderInstanceRegistry.ts +++ b/apps/server/src/provider/ProviderInstanceRegistry.ts @@ -55,6 +55,7 @@ interface LiveEntry { readonly scope: Scope.Closeable; readonly entry: ProviderInstanceConfig; readonly secrets: InstanceSecrets; + readonly setPresentation: (entry: ProviderInstanceConfig) => void; } interface RegistryState { @@ -69,6 +70,55 @@ interface RegistryState { const entryEqual = (a: ProviderInstanceConfig, b: ProviderInstanceConfig): boolean => Equal.equals(a, b); +const withoutPresentation = ({ + displayName: _displayName, + accentColor: _accentColor, + ...runtime +}: ProviderInstanceConfig) => runtime; + +// Display name and accent colour are only labels; changing them must not stop the instance's sessions. +const runtimeEqual = (a: ProviderInstanceConfig, b: ProviderInstanceConfig): boolean => + Equal.equals(withoutPresentation(a), withoutPresentation(b)); + +// Drivers stamp the presentation they were created with into every snapshot, so a renamed +// instance kept live restamps what it reports. +const withLivePresentation = (instance: ProviderInstance, created: ProviderInstanceConfig) => { + let current = created; + const restamp = (snapshot: S): S => { + const next: { -readonly [K in keyof S]: S[K] } = { ...snapshot }; + for (const key of ["displayName", "accentColor"] as const) { + const value = current[key]; + if (value === created[key]) continue; + if (value) next[key] = value; + else delete next[key]; + } + return next; + }; + const { snapshot, snapshotForCwd } = instance; + const wrapped: ProviderInstance = { + ...instance, + get displayName() { + return current.displayName; + }, + get accentColor() { + return current.accentColor; + }, + snapshot: { + ...snapshot, + getSnapshot: Effect.suspend(() => snapshot.getSnapshot).pipe(Effect.map(restamp)), + refresh: Effect.suspend(() => snapshot.refresh).pipe(Effect.map(restamp)), + streamChanges: Stream.suspend(() => snapshot.streamChanges).pipe(Stream.map(restamp)), + }, + ...(snapshotForCwd + ? { snapshotForCwd: (cwd: string) => snapshotForCwd(cwd).pipe(Effect.map(restamp)) } + : {}), + }; + const setPresentation = (entry: ProviderInstanceConfig) => { + current = entry; + }; + return { instance: wrapped, setPresentation }; +}; + const secretReferencesIn = (environment: ProviderInstanceEnvironment): Array => environment.flatMap((variable) => (typeof variable.value === "string" ? [] : [variable.value])); @@ -350,14 +400,10 @@ const buildEntry = Effect.fn("ProviderInstanceRegistry.buildEntry")(function* (input: { const nextEntry = configMap[instanceId]; if ( rebuild.has(instanceId) || - (nextEntry !== undefined && !entryEqual(live.entry, nextEntry)) + (nextEntry !== undefined && !runtimeEqual(live.entry, nextEntry)) ) { replacedIds.add(instanceId); } @@ -440,6 +486,7 @@ const makeReconcile = (input: { const builtUnavailable = new Map(); const builtSecretsUnreadable = new Map(); let orderChanged = false; + let presentationChanged = false; const previousOrder = [...previousEntries.keys()]; const nextOrder: Array = []; @@ -449,7 +496,13 @@ const makeReconcile = (input: { const existing = previousEntries.get(instanceId); if (existing !== undefined && !replacedIds.has(instanceId)) { - builtEntries.set(instanceId, existing); + if (entryEqual(existing.entry, entry)) { + builtEntries.set(instanceId, existing); + } else { + existing.setPresentation(entry); + builtEntries.set(instanceId, { ...existing, entry }); + presentationChanged = true; + } continue; } const parked = parkedSnapshot(instanceId, entry); @@ -489,6 +542,7 @@ const makeReconcile = (input: { } const entriesChanged = + presentationChanged || orderChanged || removedIds.length > 0 || replacedIds.size > 0 || diff --git a/apps/server/src/provider/ProviderRegistry.test.ts b/apps/server/src/provider/ProviderRegistry.test.ts index 69b7bd9eb2c1d..4fe6da7f791a9 100644 --- a/apps/server/src/provider/ProviderRegistry.test.ts +++ b/apps/server/src/provider/ProviderRegistry.test.ts @@ -20,6 +20,7 @@ import * as PubSub from "effect/PubSub"; import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; +import * as Option from "effect/Option"; import * as Scope from "effect/Scope"; import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; @@ -2682,6 +2683,81 @@ it.layer( }), ); + it.effect("publishes a new label for an instance the registry kept live", () => + Effect.gen(function* () { + const driver = ProviderDriverKind.make("antigravity"); + const instanceId = ProviderInstanceId.make("account-a"); + let displayName = "Account A"; + const instance: ProviderInstance = { + instanceId, + driverKind: driver, + continuationIdentity: { driverKind: driver, continuationKey: "antigravity:account-a" }, + get displayName() { + return displayName; + }, + enabled: true, + snapshot: { + resolveMaintenance: () => + Effect.succeed( + makeManualOnlyProviderMaintenanceCapabilities({ + provider: driver, + packageName: null, + }), + ), + getSnapshot: Effect.sync(() => ({ + instanceId, + driver, + displayName, + status: "ready" as const, + enabled: true, + installed: true, + auth: { status: "authenticated" as const }, + checkedAt: "1970-01-01T00:00:00.000Z", + version: "1.0.0", + models: [], + slashCommands: [], + skills: [], + })), + refresh: Effect.die("unused"), + streamChanges: Stream.empty, + applyUsageLimits: () => Effect.void, + }, + orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"], + textGeneration: {} as ProviderInstance["textGeneration"], + }; + const changes = yield* PubSub.unbounded(); + const scope = yield* Scope.make(); + yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); + const services = yield* Layer.build( + ProviderRegistry.layer.pipe( + Layer.provide(layerUnusedMutator), + Layer.provideMerge( + Layer.succeed(ProviderInstanceRegistry.ProviderInstanceRegistry, { + getInstance: () => Effect.succeed(instance), + listInstances: Effect.succeed([instance]), + listUnavailable: Effect.succeed([]), + streamChanges: Stream.fromPubSub(changes), + subscribeChanges: PubSub.subscribe(changes), + }), + ), + Layer.provideMerge( + ServerConfig.layerTest(process.cwd(), { prefix: "t3-provider-registry-label-" }), + ), + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + ).pipe(Scope.provide(scope)); + const registry = yield* ProviderRegistry.ProviderRegistry.pipe(Effect.provide(services)); + const relabelled = yield* registry.streamChanges.pipe( + Stream.filter((providers) => providers[0]?.displayName === "Account B"), + Stream.runHead, + Effect.forkChild({ startImmediately: true }), + ); + displayName = "Account B"; + yield* PubSub.publish(changes, undefined); + assert.isTrue(Option.isSome(yield* Fiber.join(relabelled))); + }), + ); + it.effect("rescans a requested cwd whose snapshot is still current", () => Effect.gen(function* () { const h = yield* makeWorkspaceRescanHarness; diff --git a/apps/server/src/provider/ProviderRegistry.ts b/apps/server/src/provider/ProviderRegistry.ts index 43d66cd1ca049..172599fd29c88 100644 --- a/apps/server/src/provider/ProviderRegistry.ts +++ b/apps/server/src/provider/ProviderRegistry.ts @@ -1050,6 +1050,27 @@ export const layer = Layer.effect( }).pipe(Effect.ignoreCause({ log: true })), { concurrency: "unbounded", discard: true }, ); + // A rename keeps the instance live, so its new label only arrives from a fresh read. + const published = new Map( + (yield* Ref.get(providersRef)).map((provider) => [provider.instanceId, provider]), + ); + yield* Effect.forEach( + carriedOver.values(), + (instance) => + Effect.gen(function* () { + // Its first check publishes the new label anyway; the placeholder must not replace the cache. + if (yield* instance.snapshot.isAwaitingFirstCheck ?? Effect.succeed(false)) return; + const provider = yield* instance.snapshot.getSnapshot; + const previous = published.get(instance.instanceId); + if ( + previous?.displayName !== provider.displayName || + previous?.accentColor !== provider.accentColor + ) { + yield* syncProvider(provider); + } + }).pipe(Effect.ignoreCause({ log: true })), + { concurrency: "unbounded", discard: true }, + ); yield* upsertProviders(unavailableProviders, { persist: false, replace: true, From 1d61429c02c1b880e55ef436588b1627edc4d381 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 19:38:40 -0800 Subject: [PATCH 252/324] perf(server): idle agent sessions free their memory after 2 minutes (#41174) Co-authored-by: Claude Opus 5.5 --- .../Adapters/ClaudeAdapterV2.ts | 94 ++++++++---- .../ClaudeAgentSdkQueryRunner.test.ts | 141 ++++++++++++++---- .../ProviderSessionManager.test.ts | 39 ++++- .../ProviderSessionManager.ts | 29 ++-- 4 files changed, 239 insertions(+), 64 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index f6d84df4dcda9..9ff0c8fc16511 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -402,7 +402,7 @@ const CLAUDE_STOP_CONFIRM_TIMEOUT_MS = 10_000; const CLAUDE_STDERR_TAIL_LENGTH = 2_048; // The process group is killed on exit, so its stderr closes promptly. const CLAUDE_STDERR_DRAIN_TIMEOUT = Duration.seconds(1); -// How often the CLI's process tree is recorded when no agent scope will stop what it leaves. +// How often a working CLI's process tree is recorded when no agent scope will stop what it leaves. const CLAUDE_DESCENDANT_POLL = "1 second"; // Claude Code's refusal of bypassPermissions as root, which it explains only on stderr. const CLAUDE_ROOT_REFUSAL = @@ -556,8 +556,9 @@ function makeClaudeDescendantTracker(cliPid: number) { } /** - * Process table reads for every running CLI. A poll reads the table once for all of them, so the - * `ps` cost does not grow with open sessions. + * Process table reads for every working CLI. A poll reads the table once for all of them, so the + * `ps` cost does not grow with open sessions. Jobs start only while a CLI works, so an idle CLI is + * left out of polls; its turn ends with one last read. */ export function makeClaudeDescendantPoll( readProcessTable: Effect.Effect>, @@ -570,27 +571,44 @@ export function makeClaudeDescendantPoll( reading.withPermits(1)(readProcessTable.pipe(Effect.map(apply))); return { // A table read before a CLI started may list an older process under its pid, so a poll records - // only into the CLIs tracked when its read began. - poll: reading - .withPermits(1)( - Effect.suspend(() => { - const tracked = [...live]; - return readProcessTable.pipe( - Effect.map((rows) => { - for (const tracker of tracked) if (live.has(tracker)) tracker.record(rows, true); - }), - ); - }), - ) - .pipe(Effect.withSpan("ClaudeAgentSdkQueryRunner.trackDescendants")), + // only into the CLIs working when its read began. + poll: Effect.suspend(() => + live.size === 0 + ? Effect.void + : reading + .withPermits(1)( + Effect.suspend(() => { + const working = [...live]; + return readProcessTable.pipe( + Effect.map((rows) => { + for (const tracker of working) + if (live.has(tracker)) tracker.record(rows, true); + }), + ); + }), + ) + .pipe(Effect.withSpan("ClaudeAgentSdkQueryRunner.trackDescendants")), + ), track: (cliPid: number) => { const tracker = makeClaudeDescendantTracker(cliPid); - live.add(tracker); + let exited = false; + const refresh = read((rows) => void tracker.record(rows, true)); return { tracked: tracker.tracked, - refresh: read((rows) => void tracker.record(rows, true)), + refresh, + /** Polls this CLI from now until its turn settles. */ + work: () => { + if (!exited) live.add(tracker); + }, + settle: Effect.suspend(() => { + live.delete(tracker); + return exited ? Effect.void : refresh; + }), /** Reads the table after the CLI exited: what it left that is still the same process. */ - leftovers: Effect.sync(() => live.delete(tracker)).pipe( + leftovers: Effect.sync(() => { + exited = true; + live.delete(tracker); + }).pipe( Effect.andThen( read((rows) => { const running = tracker.record(rows, false); @@ -1587,8 +1605,7 @@ export const layerQueryRunner: Layer.Layer< const descendantPoll = makeClaudeDescendantPoll(readProcessTable); // One poll serves every CLI. The first tracked CLI starts it; it stops once none is left. let polling: Fiber.Fiber | undefined; - const trackDescendants = (cliPid: number) => { - const tracker = descendantPoll.track(cliPid); + const startPolling = () => { polling ??= runFork( descendantPoll.poll.pipe( Effect.repeat({ @@ -1602,12 +1619,20 @@ export const layerQueryRunner: Layer.Layer< }), ), ); + }; + const trackDescendants = (cliPid: number) => { + const tracker = descendantPoll.track(cliPid); + const work = () => { + tracker.work(); + startPolling(); + }; + work(); const stop = tracker.leftovers.pipe( Effect.map((rows) => { for (const row of rows) killClaudeDescendant(row); }), ); - return { refresh: tracker.refresh, stop }; + return { refresh: tracker.refresh, work, settle: tracker.settle, stop }; }; // The open span below is the tracing boundary for both attempts. @@ -1700,7 +1725,7 @@ export const layerQueryRunner: Layer.Layer< if (answered) return; stderrTail = (stderrTail + text).slice(-CLAUDE_STDERR_TAIL_LENGTH); }; - let refreshDescendants: Effect.Effect = Effect.void; + let descendants: ReturnType | undefined; const spawnProcess = options.spawnClaudeCodeProcess ?? ((spawnOptions: ClaudeSpawnOptions) => { @@ -1718,7 +1743,7 @@ export const layerQueryRunner: Layer.Layer< if (unit === undefined && child.pid !== undefined) { const tracker = trackDescendants(child.pid); child.once("exit", () => runFork(tracker.stop)); - refreshDescendants = tracker.refresh; + descendants = tracker; } return child; } @@ -1899,6 +1924,16 @@ export const layerQueryRunner: Layer.Layer< } }), ), + // The result waits for the turn's last tree read, so a session closed on it keeps that job. + Stream.tap((message) => + descendants === undefined + ? Effect.void + : message.type === "result" + ? descendants.settle + : message.type === "assistant" + ? Effect.sync(descendants.work) + : Effect.void, + ), Stream.tap((message) => logProtocolEvent({ direction: "incoming", @@ -1910,7 +1945,12 @@ export const layerQueryRunner: Layer.Layer< offer: (message, onQueued) => Effect.uninterruptibleMask((restore) => restore(Queue.offer(promptQueue, message)).pipe( - Effect.tap(() => Effect.sync(() => onQueued?.())), + Effect.tap(() => + Effect.sync(() => { + descendants?.work(); + onQueued?.(); + }), + ), ), ).pipe( Effect.asVoid, @@ -2101,7 +2141,9 @@ export const layerQueryRunner: Layer.Layer< ), ), // A job started since the last poll is recorded before the CLI is told to exit. - close: Effect.suspend(() => (processExited ? Effect.void : refreshDescendants)).pipe( + close: Effect.suspend(() => + processExited || descendants === undefined ? Effect.void : descendants.refresh, + ).pipe( Effect.andThen(Queue.shutdown(promptQueue)), Effect.andThen(closeClaudeQuery(queryRuntime)), Effect.tap(() => diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts index 431ee35e27187..76439d76924b5 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts @@ -18,6 +18,7 @@ import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import * as Stream from "effect/Stream"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import * as TestClock from "effect/testing/TestClock"; import { vi } from "vite-plus/test"; @@ -831,7 +832,7 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro }, ); - it.effect("reads the process table once per poll for every running CLI", () => { + it.effect("reads the process table once per poll for every working CLI", () => { let reads = 0; const descendantPoll = makeClaudeDescendantPoll( Effect.sync(() => { @@ -847,6 +848,8 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro const first = descendantPoll.track(1000); const second = descendantPoll.track(2000); return Effect.gen(function* () { + first.work(); + second.work(); yield* descendantPoll.poll; assert.strictEqual(reads, 1); assert.deepStrictEqual( @@ -859,37 +862,121 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro ); yield* first.leftovers; assert.isTrue(descendantPoll.hasLive()); - yield* second.leftovers; + // A settled turn reads the table once more, then idles out of polls. + yield* second.settle; + assert.strictEqual(reads, 3); assert.isFalse(descendantPoll.hasLive()); + yield* descendantPoll.poll; + assert.strictEqual(reads, 3); }); }); - it.effect("does not record a poll's table into a CLI tracked after the read began", () => { - const readStarted = Deferred.makeUnsafe(); - const table = Deferred.makeUnsafe>>(); - const descendantPoll = makeClaudeDescendantPoll( - Deferred.succeed(readStarted, undefined).pipe(Effect.andThen(Deferred.await(table))), - ); - return Effect.gen(function* () { - const first = descendantPoll.track(1000); - const polling = yield* descendantPoll.poll.pipe(Effect.forkChild); - yield* Deferred.await(readStarted); - // The earlier process at pid 2000 exited and the pid went to a newly tracked CLI. - const late = descendantPoll.track(2000); - yield* Deferred.succeed(table, [ - processRow(1000, 10, 0), - processRow(1100, 1000, 1), - processRow(2000, 10, 0), - processRow(2100, 2000, 1), - ]); - yield* Fiber.join(polling); - assert.deepStrictEqual( - [...first.tracked.values()].map((row) => row.pid), - [1100], + it.effect( + "does not record a poll's table into a CLI that started working after the read began", + () => { + const readStarted = Deferred.makeUnsafe(); + const table = Deferred.makeUnsafe>>(); + const descendantPoll = makeClaudeDescendantPoll( + Deferred.succeed(readStarted, undefined).pipe(Effect.andThen(Deferred.await(table))), ); - assert.strictEqual(late.tracked.size, 0); - }); - }); + return Effect.gen(function* () { + const first = descendantPoll.track(1000); + first.work(); + const polling = yield* descendantPoll.poll.pipe(Effect.forkChild); + yield* Deferred.await(readStarted); + // The earlier process at pid 2000 exited and the pid went to a newly tracked CLI. + const late = descendantPoll.track(2000); + late.work(); + yield* Deferred.succeed(table, [ + processRow(1000, 10, 0), + processRow(1100, 1000, 1), + processRow(2000, 10, 0), + processRow(2100, 2000, 1), + ]); + yield* Fiber.join(polling); + assert.deepStrictEqual( + [...first.tracked.values()].map((row) => row.pid), + [1100], + ); + assert.strictEqual(late.tracked.size, 0); + }); + }, + ); + + it.effect("reads the CLI's process tree once when its turn ends and not while it is idle", () => + Effect.gen(function* () { + const cli = fakeClaudeCli( + [ + 'dir=$(dirname "$0")', + `while read -r line; do case "$line" in *'"type":"user"'*) break;; esac; done`, + `perl -e 'setpgrp(0, 0); exec @ARGV' sleep 600 > "$dir/alive" &`, + 'echo $! > "$dir/leftover.pid"', + `echo '{"type":"result","subtype":"success","is_error":false,"result":"done","session_id":"native-session-fake-cli"}'`, + 'read -r _ < "$dir/exit"', + ].join("\n"), + ); + const dir = NodePath.dirname(cli); + NodeChildProcess.execFileSync("mkfifo", [NodePath.join(dir, "alive")]); + NodeChildProcess.execFileSync("mkfifo", [NodePath.join(dir, "exit")]); + yield* Effect.addFinalizer(() => + Effect.sync(() => { + try { + process.kill(Number(NodeFS.readFileSync(NodePath.join(dir, "leftover.pid"), "utf8"))); + } catch {} + NodeFS.rmSync(dir, { recursive: true, force: true }); + }), + ); + const alive = NodeFS.createReadStream(NodePath.join(dir, "alive")); + const leftoverStopped = new Promise((resolve) => alive.once("close", () => resolve())); + alive.resume(); + let listings = 0; + const countingSpawner = Layer.effect( + ChildProcessSpawner.ChildProcessSpawner, + Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + return ChildProcessSpawner.make((command) => { + if (command._tag === "StandardCommand" && command.command === "ps") listings += 1; + return spawner.spawn(command); + }); + }), + ).pipe(Layer.provide(NodeServices.layer)); + + const session = yield* openFakeCli(cli).pipe( + Effect.provide( + layerQueryRunner.pipe( + Layer.provide(countingSpawner), + Layer.provide(PortScanner.layerTest), + Layer.provide( + Layer.succeed(ProviderEventLoggers, { native: undefined, canonical: undefined }), + ), + Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + ), + ); + const turnEnded = yield* Deferred.make(); + yield* session.messages.pipe( + Stream.tap((message) => + message.type === "result" ? Deferred.succeed(turnEnded, undefined) : Effect.void, + ), + Stream.runDrain, + Effect.ignore, + Effect.forkScoped, + ); + yield* session.offer({ + type: "user", + message: { role: "user", content: "Start a job." }, + parent_tool_use_id: null, + session_id: "native-session-fake-cli", + }); + yield* Deferred.await(turnEnded); + const listingsAtTurnEnd = listings; + yield* TestClock.adjust("1 minute"); + // The CLI exits on its own, so only the turn-end read can have recorded the job. + yield* Effect.promise(() => NodeFS.promises.writeFile(NodePath.join(dir, "exit"), "\n")); + yield* Effect.promise(() => leftoverStopped); + assert.equal(listings, listingsAtTurnEnd + 1); + }), + ); const rootRefusal = "--dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons"; diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index 4f67c42bb6d76..14d17371983b5 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -649,7 +649,7 @@ const makeProviderAdapter = Effect.fnUntraced(function* ( function layerTest(input: { readonly state: Ref.Ref; - readonly idleTimeoutMs: number; + readonly idleTimeoutMs?: number; readonly maxIdlePinMs?: number; readonly failEventStream?: boolean; readonly normalizeThreadLoadModelSelection?: (selection: ModelSelection) => ModelSelection; @@ -769,7 +769,7 @@ function layerTest(input: { layerConfiguredMcpRegistry, McpProviderSessions.layer, ProviderSessionManager.layerWithOptions({ - idleTimeoutMs: input.idleTimeoutMs, + ...(input.idleTimeoutMs === undefined ? {} : { idleTimeoutMs: input.idleTimeoutMs }), ...(input.maxIdlePinMs === undefined ? {} : { maxIdlePinMs: input.maxIdlePinMs }), }).pipe( Layer.provide( @@ -2102,6 +2102,41 @@ it.effect( }), ); +it.effect.each([ + { resume: "native resume", supportsNativeResume: true, minutes: 2 }, + { resume: "no native resume", supportsNativeResume: false, minutes: 30 }, +])( + "ProviderSessionManagerV2 releases an idle session with $resume after $minutes minutes", + ({ supportsNativeResume, minutes }) => + Effect.gen(function* () { + const state = yield* Ref.make(emptyState); + const capabilities = { + ...CodexCapabilities, + turns: { ...CodexCapabilities.turns, supportsNativeResume }, + }; + yield* Effect.gen(function* () { + const eventSink = yield* EventSink.EventSinkV2; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; + const threadId = ThreadId.make("thread-default-idle-timeout"); + const providerSessionId = yield* idAllocator.allocate.providerSession({ + providerInstanceId: modelSelection.instanceId, + threadId, + }); + yield* eventSink.write({ + events: [ + yield* makeThreadCreatedEvent({ idAllocator, threadId, now: yield* DateTime.now }), + ], + }); + yield* manager.open({ threadId, providerSessionId, modelSelection, runtimePolicy }); + yield* TestClock.adjust(minutes * 60_000 - 1_000); + assert.isTrue(yield* manager.isLive(providerSessionId)); + yield* TestClock.adjust("1 second"); + assert.isFalse(yield* manager.isLive(providerSessionId)); + }).pipe(Effect.provide(layerTest({ state, capabilities }))); + }), +); + it.effect.each(["session metadata", "session status changes", "provider work"] as const)( "ProviderSessionManagerV2 expires idle sessions according to %s", (activity) => diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index b840379ae5b54..6d445f5b0bdf7 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -78,7 +78,9 @@ import { import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; -const DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1000; +const DEFAULT_IDLE_TIMEOUT_MS = 2 * 60 * 1000; +// Without native resume, a released session comes back as a summary of the thread, so it stays longer. +const NO_NATIVE_RESUME_IDLE_TIMEOUT_MS = 30 * 60 * 1000; const DEFAULT_MAX_IDLE_PIN_MS = 4 * 60 * 60 * 1000; const RELEASE_SCOPE_CLOSE_TIMEOUT_MS = 30 * 1000; /** Past adapters' own 10 s stop fallbacks, so they settle first when the provider answers at all. */ @@ -576,7 +578,14 @@ export const layerWithOptions = ( readonly providerSessionId: ProviderSessionId; readonly threadId: ThreadId; }) => `${input.providerSessionId}\u0000${input.threadId}`; - const idleTimeoutMs = Math.max(1, options.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS); + const idleTimeoutFor = (runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime) => + Math.max( + 1, + options.idleTimeoutMs ?? + (runtime.providerSession.capabilities.turns.supportsNativeResume === true + ? DEFAULT_IDLE_TIMEOUT_MS + : NO_NATIVE_RESUME_IDLE_TIMEOUT_MS), + ); const maxIdlePinMs = Math.max(0, options.maxIdlePinMs ?? DEFAULT_MAX_IDLE_PIN_MS); interface PreparedMcpCredential { readonly mcpCredentialId: string | undefined; @@ -1688,7 +1697,7 @@ export const layerWithOptions = ( pinnedForMs: now - pinnedSinceMs, }); // Recheck on this fiber; scheduleIdleReleaseInternal would interrupt it and self-deadlock. - yield* Effect.sleep(Duration.millis(idleTimeoutMs)); + yield* Effect.sleep(Duration.millis(idleTimeoutFor(probedRuntime))); return yield* releaseIfStillIdle(input); } yield* Effect.logWarning("orchestration-v2.driver-session.idle-release-pin-expired", { @@ -1758,7 +1767,7 @@ export const layerWithOptions = ( yield* cancelIdleFiber(entry.idleFiber); const generation = entry.idleGeneration + 1; - const idleFiber = yield* Effect.sleep(Duration.millis(idleTimeoutMs)).pipe( + const idleFiber = yield* Effect.sleep(Duration.millis(idleTimeoutFor(entry.runtime))).pipe( Effect.andThen(releaseIfStillIdle({ providerSessionId, generation })), Effect.forkIn(layerScope), ); @@ -2128,7 +2137,7 @@ export const layerWithOptions = ( const pending = entry.idleThreadUnloads.get(providerThreadId); if (pending === undefined) return; const generation = pending.generation + 1; - const fiber = yield* Effect.sleep(Duration.millis(idleTimeoutMs)).pipe( + const fiber = yield* Effect.sleep(Duration.millis(idleTimeoutFor(entry.runtime))).pipe( Effect.andThen( unloadIdleThread({ providerSessionId, @@ -2217,10 +2226,12 @@ export const layerWithOptions = ( : yield* entry.runtime .hasPendingBackgroundWorkForThread(pending.providerThread) .pipe(Effect.catchCause(() => Effect.succeed(false))); - if (hasPendingWork) return "deferred" as const; + if (hasPendingWork) return { retryAfterMs: idleTimeoutFor(entry.runtime) }; const child = yield* delegatedChildArchive(input.threadId); // Unloading now would miss the archive once the parent takes the result. - if (child === "awaiting_delivery") return "deferred" as const; + if (child === "awaiting_delivery") { + return { retryAfterMs: idleTimeoutFor(entry.runtime) }; + } const archive = child === "ready"; if (input.archiveOnly === true && !archive) return "skipped" as const; // null when skipped, otherwise whether this native thread is the app thread's loaded one. @@ -2295,8 +2306,8 @@ export const layerWithOptions = ( }), ); // Wait outside the lock so the next attach is not blocked. - if (outcome === "deferred" && input.archiveOnly !== true) { - yield* Effect.sleep(Duration.millis(idleTimeoutMs)); + if (typeof outcome === "object" && input.archiveOnly !== true) { + yield* Effect.sleep(Duration.millis(outcome.retryAfterMs)); return yield* unloadIdleThread(input); } }, From 8708a29a0b9017133cdfc08c4ad3841fdd50f021 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 19:39:05 -0800 Subject: [PATCH 253/324] perf(server): checkpoint capture no longer walks every reflog in the repository (#41177) Co-authored-by: Claude Opus 5.5 --- apps/server/src/vcs/GitVcsDriver.test.ts | 135 ++++++++++++++++++++++- apps/server/src/vcs/GitVcsDriver.ts | 125 ++++++++++++++++----- 2 files changed, 227 insertions(+), 33 deletions(-) diff --git a/apps/server/src/vcs/GitVcsDriver.test.ts b/apps/server/src/vcs/GitVcsDriver.test.ts index 21b4d23a37bda..882469b57a5c0 100644 --- a/apps/server/src/vcs/GitVcsDriver.test.ts +++ b/apps/server/src/vcs/GitVcsDriver.test.ts @@ -1427,7 +1427,7 @@ it.effect.each([1_700_000_000, 1_700_000_000.9999])( }).pipe(Effect.scoped, Effect.provide(layerGitContract)), ); -it.effect.each(["local", "mixed", "exit"] as const)( +it.effect.each(["local", "mixed", "exit", "non-UTF-8 refs", "pruned ref"] as const)( "checkpoint authorship uses local evidence or full fallback ($0)", (mode) => Effect.gen(function* () { @@ -1441,7 +1441,7 @@ it.effect.each(["local", "mixed", "exit"] as const)( const fromCheckpointRef = CheckpointRef.make("refs/t3/checkpoints/authorship/from"); const toCheckpointRef = CheckpointRef.make("refs/t3/checkpoints/authorship/to"); yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef: fromCheckpointRef }); - if (mode === "mixed") { + if (mode !== "local" && mode !== "exit") { yield* fs.writeFileString(path.join(cwd, "imported.txt"), "upstream\n"); yield* git(["add", "."]); const tree = (yield* git(["write-tree"])).stdout.trim(); @@ -1476,10 +1476,30 @@ it.effect.each(["local", "mixed", "exit"] as const)( const queryDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe( Effect.provideService(VcsProcess.VcsProcess, { run: (input) => { + if (mode === "non-UTF-8 refs" && input.args.includes("for-each-ref")) { + return liveProcess + .run(input) + .pipe(Effect.map((result) => ({ ...result, stdoutInvalidUtf8: true }))); + } + // Pruned between listing the refs and walking their reflogs. + if (mode === "pruned ref" && input.args.includes("for-each-ref")) { + return liveProcess.run(input).pipe( + Effect.map((result) => ({ + ...result, + stdout: `refs/remotes/origin/pruned\n${result.stdout}`, + })), + ); + } if (!input.args.includes("--walk-reflogs")) return liveProcess.run(input); - const scope = input.args.includes("--all") ? "--all" : "HEAD"; + const scope = input.args.includes("--all") + ? `worktree HEADs${input.args.includes("--branches") ? " and --branches" : ""}` + : input.args.includes("--remotes") + ? "--remotes" + : input.args.includes("--stdin") + ? "refs" + : "HEAD"; reflogScopes.push(scope); - if (scope === "--all" || mode !== "exit") return liveProcess.run(input); + if (scope !== "HEAD" || mode !== "exit") return liveProcess.run(input); return Effect.fail( new VcsProcessExitError({ operation: input.operation, @@ -1500,10 +1520,115 @@ it.effect.each(["local", "mixed", "exit"] as const)( }), new Set(["local.txt"]), ); - assert.deepEqual(reflogScopes, mode === "local" ? ["HEAD"] : ["HEAD", "--all"]); + assert.deepEqual( + reflogScopes, + { + local: ["HEAD"], + mixed: ["HEAD", "refs", "worktree HEADs"], + // Without an import no remote-tracking ref holds the turn's commits, so none is read. + exit: ["HEAD"], + "non-UTF-8 refs": ["HEAD", "--remotes", "worktree HEADs and --branches"], + "pruned ref": ["HEAD", "refs", "worktree HEADs"], + }[mode], + ); }).pipe(Effect.scoped, Effect.provide(layerGitContract)), ); +it.effect("checkpoint authorship reads only reflogs of refs holding the turn's commits", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const driver = yield* GitVcsDriver.makeVcsDriverShape(); + const liveProcess = yield* VcsProcess.VcsProcess; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-imports-" }); + const upstream = path.join(root, "upstream"); + const primary = path.join(root, "primary"); + const cwd = path.join(root, "turn"); + const git = (repo: string, args: ReadonlyArray, stdin?: string) => + driver.execute({ + operation: "checkpoint-test", + cwd: repo, + args: ["-c", "user.name=Test", "-c", "user.email=test@test.com", ...args], + ...(stdin === undefined ? {} : { stdin }), + }); + const commitFile = (repo: string, file: string) => + Effect.gen(function* () { + yield* fs.writeFileString(path.join(repo, file), `${file}\n`); + yield* git(repo, ["add", "."]); + yield* git(repo, ["commit", "-m", file]); + }); + yield* fs.makeDirectory(upstream); + yield* git(upstream, ["init"]); + yield* commitFile(upstream, "base.txt"); + yield* git(root, ["clone", upstream, primary]); + yield* git(primary, ["worktree", "add", cwd, "-b", "turn"]); + const fromCheckpointRef = CheckpointRef.make("refs/t3/checkpoints/imports/from"); + const toCheckpointRef = CheckpointRef.make("refs/t3/checkpoints/imports/to"); + yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef: fromCheckpointRef }); + + // Refs updated during the turn that hold none of its commits. + const base = (yield* git(cwd, ["rev-parse", "HEAD"])).stdout.trim(); + const unrelated = Array.from({ length: 200 }, (_, index) => [ + `create refs/remotes/origin/unrelated-${index} ${base}`, + `create refs/heads/unrelated-${index} ${base}`, + `create refs/t3/checkpoints/unrelated-${index} ${base}`, + ]).flat(); + yield* git( + cwd, + ["update-ref", "--create-reflog", "-m", "fetch origin: storing head", "--stdin"], + `${unrelated.join("\n")}\n`, + ); + + // Fetched and fast-forwarded: imported. + yield* git(upstream, ["checkout", "-b", "release"]); + yield* commitFile(upstream, "fetched.txt"); + // Made in another worktree that then moved on, pushed, and fetched back: local. + yield* git(primary, ["checkout", "--detach"]); + yield* commitFile(primary, "own.txt"); + yield* git(primary, ["push", "origin", "HEAD:refs/heads/pushed"]); + yield* git(primary, ["checkout", "-"]); + yield* git(upstream, ["merge", "pushed", "--no-edit"]); + yield* git(upstream, ["checkout", "-b", "feature"]); + yield* commitFile(upstream, "picked.txt"); + yield* git(cwd, ["fetch", "origin"]); + yield* git(cwd, ["merge", "--ff-only", "origin/release"]); + // Cherry-picked from a fetched branch: a new local commit. + yield* git(cwd, ["cherry-pick", "origin/feature"]); + yield* commitFile(cwd, "local.txt"); + // Pushing imported commits elsewhere must not make them look local. + yield* git(cwd, ["push", "origin", "HEAD:refs/heads/mirror"]); + yield* driver.checkpoints.captureCheckpoint({ + cwd, + checkpointRef: toCheckpointRef, + previousCheckpointRef: fromCheckpointRef, + }); + + const reflogWalks: Array<{ args: ReadonlyArray; refs: ReadonlyArray }> = []; + const queryDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe( + Effect.provideService(VcsProcess.VcsProcess, { + run: (input) => { + if (input.args.includes("--walk-reflogs")) { + reflogWalks.push({ args: input.args, refs: (input.stdin ?? "").split("\n") }); + } + return liveProcess.run(input); + }, + }), + ); + assert.deepEqual( + yield* queryDriver.checkpoints.listAuthoredPaths({ cwd, fromCheckpointRef, toCheckpointRef }), + new Set(["own.txt", "picked.txt", "local.txt"]), + ); + assert.isNotEmpty(reflogWalks); + for (const { args, refs } of reflogWalks) { + // Refs come only from the explicit list; --all is limited to worktree HEADs. + const selectors = args.filter((arg) => /^--(?:all|branches|remotes|glob|tags)\b/.test(arg)); + assert.deepEqual(selectors, args.includes("--all") ? ["--all"] : []); + if (args.includes("--all")) assert.include(args, "--exclude=refs/*"); + for (const ref of refs) assert.notInclude(ref, "unrelated"); + } + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + it.effect("checkpoint authorship works with git that rejects --diff-merges=remerge", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index 3a4dd7cedf10a..3ba545caf97a8 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -1,5 +1,6 @@ import * as NodeBuffer from "node:buffer"; +import * as Arr from "effect/Array"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as SecureRandom from "effect/crypto/SecureRandom"; @@ -2368,36 +2369,102 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( outputMode: "error", }).pipe(Effect.map((result) => result.stdout.split("\0"))); - // A commit is an import when a fetch delivered it since the previous checkpoint and no - // reflog in any worktree shows this repository creating it. --all covers every worktree's - // HEAD, and with --walk-reflogs --max-age compares each entry's own time. --since would - // guess at a date, and reads a timestamp before 1973 as the current time. - const listImportedCommits = Effect.gen(function* () { - const entries = (yield* listLines([ - "log", - "--walk-reflogs", - "--all", - `--max-age=${capturedAt}`, - "--format=%H %gD %gs", - ])).map(parseCheckpointReflogEntry); - // A push records commits this repository already had. - const fetchedTips = new Set( - entries - .filter((entry) => entry.fetched && entry.subject !== "update by push") - .map((entry) => entry.commit), - ); - if (fetchedTips.size === 0) return fetchedTips; - // Fetching another branch can deliver a commit that was made here and pushed. - const createdHere = new Set( - entries.filter(isLocalReflogCreation).map((entry) => entry.commit), - ); - const fetched = yield* listLines( - ["rev-list", `--max-age=${capturedAt}`, "--stdin"], - `${[...fetchedTips, `^${startHead}`].join("\n")}\n`, + // Refs under `namespace` that contain any of `commits`. Only the oldest commits of the set + // are passed on, since a ref containing a descendant also contains its ancestors. + const listRefsContaining = Effect.fn("GitVcsDriver.checkpoints.listRefsContaining")( + function* (commits: ReadonlySet, namespace: "refs/remotes" | "refs/heads") { + const roots = (yield* listLines( + ["rev-list", "--no-walk=unsorted", "--parents", "--stdin"], + `${[...commits].join("\n")}\n`, + )).flatMap((line) => { + const [commit = "", ...parents] = line.split(" "); + return parents.some((parent) => commits.has(parent)) ? [] : [commit]; + }); + const outputs = yield* Effect.forEach(Arr.chunksOf(roots, 256), (chunk) => + execute({ + operation, + cwd: input.cwd, + args: [ + "for-each-ref", + "--format=%(refname)", + ...chunk.flatMap((commit) => ["--contains", commit]), + namespace, + ], + maxOutputBytes: VcsDriver.CHECKPOINT_DIFF_MAX_OUTPUT_BYTES, + outputMode: "error", + }), + ); + // A ref name that is not UTF-8 would not survive the round trip, so Git lists them. + if (outputs.some((output) => output.stdoutInvalidUtf8)) { + return { + revisionArgs: [namespace === "refs/heads" ? "--branches" : "--remotes"], + refs: [], + }; + } + const refs = outputs.flatMap((output) => output.stdout.split("\n")); + return { revisionArgs: [], refs: [...new Set(refs.filter((ref) => ref !== ""))] }; + }, + ); + // With --walk-reflogs, --max-age compares each entry's own time; --since would guess at a + // date and reads a timestamp before 1973 as now. Walking many reflogs at once slows down + // quadratically with the refs passed: --all took 40 s in a repository with 29k refs. + const walkReflogs = Effect.fn("GitVcsDriver.checkpoints.walkReflogs")(function* ( + revisionArgs: ReadonlyArray, + refs: ReadonlyArray, + ) { + const lines = yield* listLines( + [ + "log", + "--walk-reflogs", + ...revisionArgs, + `--max-age=${capturedAt}`, + "--format=%H %gD %gs", + // A listed ref may be pruned before this walk reads it. + "--ignore-missing", + "--stdin", + ], + `${refs.join("\n")}\n`, ); - return new Set(fetched.filter((commit) => !createdHere.has(commit))); + return lines.map(parseCheckpointReflogEntry); }); + // A commit is an import when a fetch delivered it since the previous checkpoint and no + // reflog shows this repository creating it. Only refs containing a turn commit are read; + // a remote-tracking ref force-moved off one after the fetch is missed, which keeps that + // commit attributed to the turn. + const listImportedCommits = Effect.fn("GitVcsDriver.checkpoints.listImportedCommits")( + function* (candidates: ReadonlySet) { + const remote = yield* listRefsContaining(candidates, "refs/remotes"); + if (remote.revisionArgs.length === 0 && remote.refs.length === 0) { + return new Set(); + } + // A push records commits this repository already had. + const fetchedTips = new Set( + (yield* walkReflogs(remote.revisionArgs, remote.refs)) + .filter((entry) => entry.fetched && entry.subject !== "update by push") + .map((entry) => entry.commit), + ); + if (fetchedTips.size === 0) return fetchedTips; + const fetched = new Set( + (yield* listLines( + ["rev-list", `--max-age=${capturedAt}`, "--stdin"], + `${[...fetchedTips, `^${startHead}`].join("\n")}\n`, + )).filter((commit) => candidates.has(commit)), + ); + if (fetched.size === 0) return fetched; + // Fetching another branch can deliver a commit that was made here and pushed. Every + // worktree's HEAD reflog is read, since a detached HEAD may have moved off the commit + // it made; --all with refs/* excluded yields exactly those HEADs. + const local = yield* listRefsContaining(fetched, "refs/heads"); + const createdHere = new Set( + (yield* walkReflogs(["--exclude=refs/*", "--all", ...local.revisionArgs], local.refs)) + .filter(isLocalReflogCreation) + .map((entry) => entry.commit), + ); + return new Set([...fetched].filter((commit) => !createdHere.has(commit))); + }, + ); + // Remerge diffs retain merge conflict fixes while excluding clean upstream changes. // Older Git gets dense combined diffs, which miss a conflict resolved to one side's // version, so it also keeps every path more than one parent changed since the merge base. @@ -2483,7 +2550,9 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( const importedCommits = unprovenCommits.size === 0 ? new Set() - : yield* listImportedCommits.pipe(Effect.orElseSucceed(() => new Set())); + : yield* listImportedCommits(unprovenCommits).pipe( + Effect.orElseSucceed(() => new Set()), + ); const ownCommits = recentCommits.filter((commit) => !importedCommits.has(commit)); const ownCommitPaths = ownCommits.length === 0 From a679987c0b15b3be5a105062b7b47c9889ca4752 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 19:44:39 -0800 Subject: [PATCH 254/324] test(server): replay scenarios no longer run checkpoints against the real checkout (#41192) Co-authored-by: Claude Opus 5.5 --- .../src/orchestration-v2/RuntimePolicy.ts | 10 -------- .../ThreadFork.execution.test.ts | 1 + .../testkit/ProviderReplayHarness.ts | 23 +++++++++++++++++-- 3 files changed, 22 insertions(+), 12 deletions(-) diff --git a/apps/server/src/orchestration-v2/RuntimePolicy.ts b/apps/server/src/orchestration-v2/RuntimePolicy.ts index aac7a859423fb..3ba0baa24dd5d 100644 --- a/apps/server/src/orchestration-v2/RuntimePolicy.ts +++ b/apps/server/src/orchestration-v2/RuntimePolicy.ts @@ -79,16 +79,6 @@ export class RuntimePolicyV2 extends Context.Service = Layer.succeed(RuntimePolicyV2, { - resolve: Effect.fn("RuntimePolicyV2.resolve")(function (input) { - return Effect.succeed({ - runtimeMode: input.thread.runtimeMode, - interactionMode: input.thread.interactionMode, - cwd: input.thread.worktreePath, - }); - }), -}); - export function providerRuntimeMode( runtimeMode: RuntimeMode, supportedRuntimeModes: ReadonlyArray | undefined, diff --git a/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts b/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts index 634a842843b93..3466fed79f502 100644 --- a/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts +++ b/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts @@ -1938,6 +1938,7 @@ const runForkWithFailingNativeSource = (forkFailures: number) => { ProviderReplayHarness.layerWithRegistry( { name: "fork-missing-native-source" }, ProviderAdapterRegistry.layerFromAdapters([adapter]), + { runEffectWorker: false }, ), ), ); diff --git a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts index bb336d3179f34..ccd4c69710d81 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts @@ -17,6 +17,7 @@ import type * as SqlClient from "effect/sql/SqlClient"; import type { MigrationError } from "effect/sql/Migrator"; import type { SqlError } from "effect/sql/SqlError"; +import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace"; import * as CheckpointStore from "../../checkpointing/CheckpointStore.ts"; import * as ServerConfig from "../../config.ts"; import * as SqlitePersistence from "../../persistence/Sqlite.ts"; @@ -317,11 +318,29 @@ export function layerWithRegistry( ServerConfig.ServerConfig, makeReplayServerConfig(scenario.name).pipe(Effect.orDie), ).pipe(Layer.provide(NodeServices.layer)); + // A thread without a worktree would otherwise fall back to process.cwd(), so checkpoints + // would run git against the checkout running the tests and race its other users. + const layerScenarioWorkspacePolicy = Layer.effect( + RuntimePolicy.RuntimePolicyV2, + Effect.gen(function* () { + const workspace = yield* checkpointWorkspace( + scenario.name.replace(/[^a-z0-9_-]+/gi, "-"), + ).pipe(Effect.orDie); + return { + resolve: (input) => + Effect.succeed({ + runtimeMode: input.thread.runtimeMode, + interactionMode: input.thread.interactionMode, + cwd: input.thread.worktreePath ?? workspace, + }), + }; + }), + ); const layerRuntimeBase = scenario.runtimePolicyOverride === undefined - ? RuntimePolicy.layer + ? layerScenarioWorkspacePolicy : RuntimePolicy.layerWithOverride(scenario.runtimePolicyOverride).pipe( - Layer.provide(RuntimePolicy.layer), + Layer.provide(layerScenarioWorkspacePolicy), ); const layerDatabase = options.databaseLayer ?? SqlitePersistence.layerMemory; // Share one continuation queue across adapters, orchestrator, and worker through layer memoization. From 9a87dbb99a9d672957de4ebe45df92aea5283647 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 19:45:33 -0800 Subject: [PATCH 255/324] fix(web): chat file tooltips open beside the link instead of sliding in from the corner (#41194) --- apps/web/src/components/ui/shared-tooltip.tsx | 3 +++ .../components/ui/tooltip.browser.test.tsx | 22 +++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/apps/web/src/components/ui/shared-tooltip.tsx b/apps/web/src/components/ui/shared-tooltip.tsx index 0858fa656e6bb..cca4d8a43fd61 100644 --- a/apps/web/src/components/ui/shared-tooltip.tsx +++ b/apps/web/src/components/ui/shared-tooltip.tsx @@ -11,6 +11,7 @@ import { type ReactElement, type ReactNode, } from "react"; +import { flushSync } from "react-dom"; import { Tooltip, TooltipPopup, TooltipTrigger, useTooltipScrollTracker } from "./tooltip"; @@ -79,6 +80,8 @@ export function SharedTooltipProvider({ children }: { children: ReactNode }) { const [api] = useState(() => ({ show(anchor, content, immediate) { clearTimer(); + // A Root that mounts open skips Base UI's mount transition, so the popup would slide in from (0,0). + if (!current.current) flushSync(() => commit({ ...content, anchor, open: false })); const open = current.current?.open === true; const reopen = performance.now() - lastClosedAt.current < REOPEN_WINDOW_MS; if (immediate || open || reopen) { diff --git a/apps/web/src/components/ui/tooltip.browser.test.tsx b/apps/web/src/components/ui/tooltip.browser.test.tsx index bcb62ee2fdaf0..344ddcea7f0f1 100644 --- a/apps/web/src/components/ui/tooltip.browser.test.tsx +++ b/apps/web/src/components/ui/tooltip.browser.test.tsx @@ -114,3 +114,25 @@ it("refreshes a pending shared tooltip if its label changes during the open dela await expect.element(page.getByText("Copy code")).toBeVisible(); expect(page.getByText("Copied").query()).toBeNull(); }); + +it("opens a shared tooltip in place the first time", async () => { + await using _screen = await render( + // Away from the corner the unpositioned popup sits in, so a slide from there is a real move. +

    , + ); + // Focus opens it at once, while a position transition would still be running. + await userEvent.keyboard("{Tab}"); + await expect.element(page.getByText("Description")).toBeVisible(); + const moving = document + .getAnimations() + .filter((animation) => animation instanceof CSSTransition) + .map((transition) => transition.transitionProperty) + .filter((property) => ["top", "left", "right", "bottom", "transform"].includes(property)); + expect(moving).toEqual([]); +}); From c18f82c4bd9f7fa27df6c7edded2442f48c5538b Mon Sep 17 00:00:00 2001 From: Victor Date: Sun, 22 Nov 2026 21:46:57 -0600 Subject: [PATCH 256/324] fix(server): RTF attachments leave hidden text out of what agents read (#41191) Co-authored-by: Julius Marminge --- apps/server/src/provider/documentTextWorker.ts | 5 ++++- apps/server/src/provider/userInputAttachments.test.ts | 10 ++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index ec1f1f694c2f4..0acffd168c07d 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -459,6 +459,7 @@ function* rtf(source: string): Generator { let state = { skip: false, deleted: false, + hiddenText: false, uc: 1, font: 0, fontTable: false, @@ -469,7 +470,7 @@ function* rtf(source: string): Generator { const fonts = new Map(); let defaultFont = 0; const decoder = () => fonts.get(state.font) ?? state.decoder; - const hidden = () => state.skip || state.deleted; + const hidden = () => state.skip || state.deleted || state.hiddenText; const symbols = new Map([ ["endash", "–"], ["emdash", characterEntities.mdash], @@ -548,8 +549,10 @@ function* rtf(source: string): Generator { if (codePage) fonts.set(state.font, new TextDecoder(codePage)); } if (control === "deleted") state.deleted = value !== 0; + else if (control === "v") state.hiddenText = value !== 0; else if (control === "plain") { state.deleted = false; + state.hiddenText = false; state.font = defaultFont; } if (control === "mac" || (control === "ansicpg" && value === 10000)) diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index 55c3468f3dce9..8c8be7bf30534 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -329,6 +329,16 @@ describe("question answer paths", () => { String.raw`{\rtf1\ansi\trowd\cellx1000\cellx2000\intbl A\deleted\cell\deleted0 B\cell\deleted\row\deleted0 C\cell}`, "A\tB\t\nC", ], + [ + "hidden text", + String.raw`{\rtf1\ansi A {\v B{\v0 C}D} E\v F\v0 G\v1 H\plain I}`, + "A C E G I", + ], + [ + "hidden text table and escapes", + String.raw`{\rtf1\ansi\trowd\cellx1000\cellx2000\intbl A\v B\u945?\'e9\cell\v0 C\cell\v\row\v0 D\cell}`, + "A\tC\t\nD", + ], [ "document breaks", String.raw`{\rtf1\ansi\sectd\cols2\pard North quota: 120\column South quota: 240\page East quota: 360\sect\sectd\pard West quota: 480\par}`, From 1d4d9be3ff925d5d5ecc90859bdcbd20ecb04b15 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 19:47:09 -0800 Subject: [PATCH 257/324] fix(server): Antigravity 502s fail the turn with the real error (#33596) --- .../Adapters/AcpAdapterV2.test.ts | 46 +++++++++++++++++ .../acp/AntigravityTurnOutcome.test.ts | 47 +++++++++++++++++- .../provider/acp/AntigravityTurnOutcome.ts | 16 ++++-- packages/provider-acp/src/server/adapter.ts | 49 +++++++++++++++---- 4 files changed, 142 insertions(+), 16 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 7815f8d959a2f..43db1b82b63a2 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -626,6 +626,7 @@ const isProviderAdapterProtocolError = Schema.is(ProviderAdapter.ProviderAdapter const makePromptInactivityHarness = Effect.fnUntraced(function* (input: { readonly environment: (runtimeOrdinal: number) => Readonly>; readonly runtimeMode?: "full-access" | "approval-required"; + readonly watchPromptOutcome?: AcpAdapterV2Flavor["watchPromptOutcome"]; readonly wrapPrompt?: ( prompt: AcpSessionRuntime.AcpSessionRuntime["Service"]["prompt"], ) => AcpSessionRuntime.AcpSessionRuntime["Service"]["prompt"]; @@ -642,6 +643,9 @@ const makePromptInactivityHarness = Effect.fnUntraced(function* (input: { driver: ACP_TEST_DRIVER, capabilities: AcpProviderCapabilitiesV2, promptInactivityTimeout: "15 minutes", + ...(input.watchPromptOutcome === undefined + ? {} + : { watchPromptOutcome: input.watchPromptOutcome }), ...(input.followAgentWorkState === true ? { followAgentWorkState: true } : {}), makeRuntime: makeMockRuntime({ childProcessSpawner, @@ -5845,6 +5849,48 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(layerTest)), ); + it.effect("fails a silent prompt with the failure its outcome check recorded", () => + Effect.gen(function* () { + const badGateway = { + class: "provider_error", + message: "Bad Gateway: Failed to connect to backend API", + code: "502 Bad Gateway", + retryable: true, + } as const; + // The agent logs the upstream error and leaves session/prompt open. + const harness = yield* makePromptInactivityHarness({ + environment: () => ({ T3_ACP_HANG_PROMPT_FOREVER: "1" }), + watchPromptOutcome: () => + Effect.succeed((_result, options) => + Effect.succeed( + options?.retired === true + ? { failure: badGateway, threadDisposition: "reusable" as const } + : undefined, + ), + ), + }); + yield* harness.startTurn(1); + yield* TestClock.adjust("15 minutes"); + const [silent] = yield* harness.terminals(1); + assert.equal(silent?.status, "failed"); + assert.deepEqual(silent?.failure, badGateway); + }).pipe(Effect.provide(layerTest), Effect.scoped), + ); + + it.effect("retires a silent prompt whose outcome check dies", () => + Effect.gen(function* () { + const harness = yield* makePromptInactivityHarness({ + environment: () => ({ T3_ACP_HANG_PROMPT_FOREVER: "1" }), + watchPromptOutcome: () => Effect.succeed(() => Effect.die("session log unreadable")), + }); + yield* harness.startTurn(1); + yield* TestClock.adjust("15 minutes"); + const [silent] = yield* harness.terminals(1); + assert.equal(silent?.status, "failed"); + assert.include(silent?.failure?.message, "15 minutes"); + }).pipe(Effect.provide(layerTest), Effect.scoped), + ); + // regression: #34160 a turn failed as silent right after the computer woke from sleep it.effect.each([ { label: "a timer due during sleep fires on wake", timerCountsSleep: true, asleep: "2 hours" }, diff --git a/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts b/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts index b6094e638285d..962da73bfc2bd 100644 --- a/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts +++ b/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts @@ -30,9 +30,19 @@ const QUOTA_ERROR = errorPayload( const RATE_LIMIT_ERROR = errorPayload( "Error 429, Message: Resource has been exhausted (e.g. check quota)., Status: RESOURCE_EXHAUSTED, Details: [map[@type:type.googleapis.com/google.rpc.ErrorInfo domain:cloudcode-pa.googleapis.com reason:RATE_LIMIT_EXCEEDED] map[@type:type.googleapis.com/google.rpc.RetryInfo retryDelay:42s]]", ); +const RETIRED_QUOTA_ERROR = errorPayload( + "Error 429, Message: Quota exhausted for test model., Status: RESOURCE_EXHAUSTED, Details: [map[@type:type.googleapis.com/google.rpc.ErrorInfo domain:googleapis.com metadata:map[quotaResetDelay:3600s quotaResetTimeStamp:2026-11-09T01:05:00Z] reason:QUOTA_EXHAUSTED]]", +); const INVALID_ARGUMENT_ERROR = errorPayload( "Error 400, Message: Request contains an invalid argument., Status: INVALID_ARGUMENT, Details: []", ); +// The harness renders a gateway failure with its HTTP status line in place of a gRPC status. +const BAD_GATEWAY_ERROR = Buffer.concat([ + errorPayload( + "Error 502, Message: Bad Gateway: Failed to connect to backend API, Status: 502 Bad Gateway, Details: []", + ), + Buffer.from("\nThe model is currently unreachable."), +]); // Vertex Claude rejects a resumed history whose saved thinking block lost its signature. const MISSING_SIGNATURE_ERROR = errorPayload( 'Error 400, Message: {"type":"error","error":{"type":"invalid_request_error","message":"messages.1.content.0.thinking.signature: Field required"},"request_id":"req_vrtx_test"}, Status: INVALID_ARGUMENT, Details: []', @@ -82,11 +92,12 @@ describe("watchAntigravityPromptOutcome", () => { const turn = ( steps: ReadonlyArray, result: EffectAcpSchema.PromptResponse = { stopReason: "end_turn" }, + options?: { readonly retired?: boolean }, ) => Effect.gen(function* () { const check = yield* watchAntigravityPromptOutcome(profileDirectory, sessionId); appendSteps(steps); - return yield* check(result); + return yield* check(result, options); }); const input = Buffer.from("Run the fixture."); const reply = Buffer.from("FIXTURE_OK"); @@ -149,6 +160,40 @@ describe("watchAntigravityPromptOutcome", () => { retryable: false, }), ); + assert.deepInclude( + (yield* turn([ + [USER_INPUT, input], + [ERROR_MESSAGE, BAD_GATEWAY_ERROR], + ]))?.failure, + { + class: "provider_error", + message: "Bad Gateway: Failed to connect to backend API", + retryable: true, + }, + ); + // A prompt the watchdog retired keeps an absolute reset time but drops a relative one. + assert.deepEqual( + (yield* turn( + [ + [USER_INPUT, input], + [ERROR_MESSAGE, RATE_LIMIT_ERROR], + ], + undefined, + { retired: true }, + ))?.failure.resetAt, + undefined, + ); + assert.equal( + (yield* turn( + [ + [USER_INPUT, input], + [ERROR_MESSAGE, RETIRED_QUOTA_ERROR], + ], + undefined, + { retired: true }, + ))?.failure.resetAt, + "2026-11-09T01:05:00.000Z", + ); // A 404 after the turn already reached the model is a transient edge error, not a bad model. for (const error of [NOT_FOUND_ERROR, STATUS_NOT_FOUND_ERROR]) { assert.deepEqual( diff --git a/apps/server/src/provider/acp/AntigravityTurnOutcome.ts b/apps/server/src/provider/acp/AntigravityTurnOutcome.ts index 32eee40f008ae..35ed2f347df1d 100644 --- a/apps/server/src/provider/acp/AntigravityTurnOutcome.ts +++ b/apps/server/src/provider/acp/AntigravityTurnOutcome.ts @@ -20,7 +20,10 @@ const PLANNER_RESPONSE_STEP_TYPE = 15; // The harness error text leads the payload; a Go stack trace follows it. const MAX_ERROR_PAYLOAD_BYTES = 16_384; // The Go harness's rendering of a Google API error, as the agent's api_errors.py reads it. -const API_ERROR = /Error (\d{3}), Message: (.+?), Status: ([A-Z_]+)/s; +// Status is a gRPC code, or an HTTP status line such as "502 Bad Gateway". A message +// stops at the next error, so each start scans its own span and the match stays linear. +const API_ERROR = + /Error (\d{3}), Message: ((?:(?!, Status: |Error \d{3}, Message: ).)+), Status: ([A-Z_]+|\d{3}[^,\n]*)/s; // Antigravity 1.5 with a Google account writes "STATUS (code NNN): message". const STATUS_ERROR = /(? undefined), ) : undefined; - return turnFailure(result.stopReason, step, yield* DateTime.now); + // A retired prompt's check runs long after the error, so a relative delay has no anchor. + const now = options?.retired === true ? undefined : yield* DateTime.now; + return turnFailure(result.stopReason, step, now); }); }); diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 997158c78a1ce..d4af4aa10ddd5 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -389,15 +389,17 @@ export interface AcpAdapterV2Flavor { /** The flavor's runtime refuses a version the policy rates broken when it starts. */ readonly checksVersionAtHandshake?: boolean; /** - * Runs before `session/prompt`. The returned check sees a prompt the agent ended - * without an error or cancel, and reports a failure its stop reason hid. A reported - * failure restarts the runtime before the next turn. A `broken` thread's native - * history is unusable, so the next turn falls back to a fresh session. + * Runs before `session/prompt`. The check reports a failure hidden by a clean stop, or + * by silence when the inactivity watchdog retires the prompt (`retired`). A failure + * restarts the runtime; a `broken` thread's next turn starts a fresh session. */ readonly watchPromptOutcome?: ( sessionId: string, ) => Effect.Effect< - (result: EffectAcpSchema.PromptResponse) => Effect.Effect + ( + result: EffectAcpSchema.PromptResponse, + options?: { readonly retired?: boolean }, + ) => Effect.Effect >; readonly requiresSignIn?: (cause: unknown) => boolean; /** @@ -1746,6 +1748,12 @@ interface ActiveAcpTurn { inactivityWatchdog: Fiber.Fiber | undefined; } +const PROMPT_OUTCOME_CHECK_TIMEOUT = Duration.seconds(5); + +type PromptOutcomeCheck = Effect.Success< + ReturnType> +>; + type AcpRuntimeTeardownState = | { readonly _tag: "Idle" } | { @@ -8909,6 +8917,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( context: ActiveAcpTurn, generation: number, timeoutMillis: number, + checkPromptOutcome: PromptOutcomeCheck | undefined, ) { const retired = yield* runRuntimeCallbackAtGeneration( generation, @@ -8929,14 +8938,31 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.set(runtimeRestartRequired, true); yield* cancelPendingRuntimeRequests(); yield* terminalizeOpenForegroundTools(context, "failed"); + // Bounded: it runs under the transition permit that Stop and the next turn wait on. + const recorded = + checkPromptOutcome === undefined + ? undefined + : yield* checkPromptOutcome({ stopReason: "end_turn" }, { retired: true }).pipe( + Effect.timeout(PROMPT_OUTCOME_CHECK_TIMEOUT), + Effect.catchCause((cause) => + Effect.logError("failed to check a silent ACP prompt's outcome", { + driver, + cause, + }).pipe(Effect.as(undefined)), + ), + ); const minutes = Math.max(1, Math.round(timeoutMillis / 60_000)); yield* finalizeTurn( context, "failed", - makeProviderFailure({ - class: "provider_error", - message: `${flavor.runtimeHarness ?? driver} sent nothing for ${minutes} ${minutes === 1 ? "minute" : "minutes"}, so T3 Code stopped the turn and restarted the agent. Send a message to continue.`, - }), + recorded?.failure ?? + makeProviderFailure({ + class: "provider_error", + message: `${flavor.runtimeHarness ?? driver} sent nothing for ${minutes} ${minutes === 1 ? "minute" : "minutes"}, so T3 Code stopped the turn and restarted the agent. Send a message to continue.`, + }), + recorded === undefined + ? undefined + : { threadDisposition: recorded.threadDisposition }, ); return "retired" as const; }), @@ -8960,6 +8986,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( context: ActiveAcpTurn, generation: number, timeoutMillis: number, + checkPromptOutcome: PromptOutcomeCheck | undefined, ) { yield* Deferred.await(context.promptDispatched); context.lastProgressAt = yield* Clock.currentTimeMillis; @@ -8978,7 +9005,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( continue; } const outcome = yield* runtimeTransitionPermit.withPermit( - retireInactivePrompt(context, generation, timeoutMillis), + retireInactivePrompt(context, generation, timeoutMillis, checkPromptOutcome), ); if (outcome !== "rearm") return; } @@ -9742,6 +9769,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( context, promptGeneration, promptInactivityTimeoutMillis, + checkPromptOutcome, ).pipe(Effect.forkIn(sessionScope)); } const compactSession = isCompactionMessage(turnInput.message) @@ -9844,6 +9872,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( context, generation, promptInactivityTimeoutMillis, + checkPromptOutcome, ).pipe(Effect.forkIn(sessionScope)); } const releasedForSteer = context.foregroundIdle; From 9dc36169b4a2018ac6c2ca3e32263874475437a3 Mon Sep 17 00:00:00 2001 From: SeniorZhai Date: Mon, 23 Nov 2026 11:55:41 +0800 Subject: [PATCH 258/324] fix(web,mobile): translate remaining untranslated workflow, git, and link strings (#41193) Co-authored-by: Julius Marminge --- apps/mobile/src/i18n/translations/pt-BR.json | 2 +- apps/web/src/i18n/translations/de.json | 2 +- apps/web/src/i18n/translations/es.json | 2 +- apps/web/src/i18n/translations/fr.json | 2 +- apps/web/src/i18n/translations/ja.json | 2 +- apps/web/src/i18n/translations/ko.json | 2 +- apps/web/src/i18n/translations/pt-BR.json | 4 ++-- apps/web/src/i18n/translations/ru.json | 2 +- apps/web/src/i18n/translations/sv.json | 6 +++--- apps/web/src/i18n/translations/zh.json | 2 +- 10 files changed, 13 insertions(+), 13 deletions(-) diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index d8d29e5cd0641..037e9559e0aa3 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -1555,7 +1555,7 @@ "49a888ab323521ae": "Thread ramificada", "5d865442753ef6c2": "Thread criada", "3ccfbf7e86868c35": "Feedback para a equipe do T3", - "3604d2f52be9539e": "Link {target}", + "3604d2f52be9539e": "Vincular {target}", "646de37e0bec85f8": "Chamada de ferramenta", "5469bba2f5569925": "Plano proposto", "c3a88348c14f8258": "Plano atualizado", diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index f63b5ce4f5841..aeb4e4497d43e 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -12470,7 +12470,7 @@ "3cc43f1dbf3f8e0c": "Abgebrochen", "ded70e75de6404ba": "Zurück zur Liste der Ausführungen", "2f4ed7dbd22be30d": "Ausführung abbrechen", - "614e5ad58a795fb5": "Stop", + "614e5ad58a795fb5": "Stoppen", "04b050b0329f0ac8": "dauerte {duration}", "aff78e1774818ff4": "bisher {duration}", "38eddd466439afc9": "Was die Ausführung berührt hat", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index b15af98ce01ba..113f1c5d4cafe 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -12463,7 +12463,7 @@ "3cc43f1dbf3f8e0c": "Cancelada", "ded70e75de6404ba": "Volver a la lista de ejecuciones", "2f4ed7dbd22be30d": "Cancelar ejecución", - "614e5ad58a795fb5": "Stop", + "614e5ad58a795fb5": "Detener", "04b050b0329f0ac8": "tardó {duration}", "aff78e1774818ff4": "{duration} hasta ahora", "38eddd466439afc9": "Lo que tocó la ejecución", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index f2f519b25ae0b..17c01696429a9 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -12468,7 +12468,7 @@ "3cc43f1dbf3f8e0c": "Annulée", "ded70e75de6404ba": "Retour à la liste des exécutions", "2f4ed7dbd22be30d": "Annuler l’exécution", - "614e5ad58a795fb5": "Stop", + "614e5ad58a795fb5": "Arrêter", "04b050b0329f0ac8": "a duré {duration}", "aff78e1774818ff4": "{duration} jusqu’ici", "38eddd466439afc9": "Ce que l’exécution a touché", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index e665b9445f6f9..a13377564e7fe 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -12416,7 +12416,7 @@ "3cc43f1dbf3f8e0c": "キャンセル済み", "ded70e75de6404ba": "実行一覧に戻る", "2f4ed7dbd22be30d": "実行をキャンセル", - "614e5ad58a795fb5": "Stop", + "614e5ad58a795fb5": "停止", "04b050b0329f0ac8": "所要時間 {duration}", "aff78e1774818ff4": "{duration} 経過", "38eddd466439afc9": "この実行が扱ったもの", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 90614ef54230d..da68956e5a4d2 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -12411,7 +12411,7 @@ "3cc43f1dbf3f8e0c": "취소됨", "ded70e75de6404ba": "실행 목록으로 돌아가기", "2f4ed7dbd22be30d": "실행 취소", - "614e5ad58a795fb5": "Stop", + "614e5ad58a795fb5": "중지", "04b050b0329f0ac8": "{duration} 소요", "aff78e1774818ff4": "현재까지 {duration}", "38eddd466439afc9": "이 실행이 다룬 항목", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index e8d50d83a5f44..a0e88601de24c 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -2122,7 +2122,7 @@ "cd80122422577239": "Publicar repositório", "c85db9ac99efa605": "Push e criar {term, select, mr {MR} cr {solicitação de alteração} other {PR}}", "dbccf81ad4a03f48": "Sincronizar ref", - "4350ab8128b18105": "Pull", + "4350ab8128b18105": "Fazer pull", "dca2ca8303bfc14e": "Fazer commit e push na ref padrão?", "e196fda632e279d0": "Esta ação vai fazer commit e push das alterações em \"{branch}\". Você pode continuar nesta ref ou criar uma ref de feature e executar a mesma ação nela.", "87e714255e8be7f2": "Fazer push na ref padrão?", @@ -12468,7 +12468,7 @@ "3cc43f1dbf3f8e0c": "Cancelada", "ded70e75de6404ba": "Voltar à lista de execuções", "2f4ed7dbd22be30d": "Cancelar execução", - "614e5ad58a795fb5": "Stop", + "614e5ad58a795fb5": "Parar", "04b050b0329f0ac8": "levou {duration}", "aff78e1774818ff4": "{duration} até agora", "38eddd466439afc9": "O que a execução tocou", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index f15a9f71b21f2..890e0b9d7506b 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -12469,7 +12469,7 @@ "3cc43f1dbf3f8e0c": "Отменён", "ded70e75de6404ba": "Назад к списку запусков", "2f4ed7dbd22be30d": "Отменить запуск", - "614e5ad58a795fb5": "Stop", + "614e5ad58a795fb5": "Остановить", "04b050b0329f0ac8": "занял {duration}", "aff78e1774818ff4": "пока {duration}", "38eddd466439afc9": "Что затронул запуск", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 6d53cb0b38d73..967d0c7eededd 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -9576,9 +9576,9 @@ "d2b0987f8c907e13": "Samplar var {ms} ms", "4a3d538e12caed70": "{count, plural, one {Samplar var {seconds} sekund} other {Samplar var {seconds}:e sekund}}", "32c787e014d8f2ec": "Underprocess i backend", - "ca84041dbbfb9e45": "Electron main", + "ca84041dbbfb9e45": "Electrons huvudprocess", "0693ca29c961e19b": "Renderare", - "fb4e08f7e0f78d3b": "Electron utility", + "fb4e08f7e0f78d3b": "Electrons hjälpprocess", "7f206abc2cb38ab2": "Övervakare", "7cdfa8c2f4106d6a": "T3-process", "9bc60e1d0ef816cf": "Lagringsbyte", @@ -12476,7 +12476,7 @@ "3cc43f1dbf3f8e0c": "Avbruten", "ded70e75de6404ba": "Tillbaka till listan över körningar", "2f4ed7dbd22be30d": "Avbryt körningen", - "614e5ad58a795fb5": "Stop", + "614e5ad58a795fb5": "Stoppa", "04b050b0329f0ac8": "tog {duration}", "aff78e1774818ff4": "{duration} hittills", "38eddd466439afc9": "Vad körningen rörde", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index deaa65edcc1ec..5a5128c0a7c8d 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -12492,7 +12492,7 @@ "3cc43f1dbf3f8e0c": "已取消", "ded70e75de6404ba": "返回运行列表", "2f4ed7dbd22be30d": "取消运行", - "614e5ad58a795fb5": "Stop", + "614e5ad58a795fb5": "停止", "04b050b0329f0ac8": "用时 {duration}", "aff78e1774818ff4": "已用时 {duration}", "38eddd466439afc9": "此运行涉及的内容", From e6ae5810a330ee755b5a8bbe9181703dad25aae2 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 20:03:28 -0800 Subject: [PATCH 259/324] fix(web): preserve reading position when side panels resize (#41184) Co-authored-by: 137 <113233555+caezium@users.noreply.github.com> --- ...rPromptEditorTiptap.input.browser.test.tsx | 48 +++++++ .../components/ComposerPromptEditorTiptap.tsx | 6 + .../chat/MessagesTimeline.browser.test.tsx | 42 ++++++ .../src/components/chat/MessagesTimeline.tsx | 13 ++ apps/web/src/lib/preserveReadingPosition.ts | 115 ++++++++++++++++ ...de-panel-preserves-reading-position.e2e.ts | 124 ++++++++++++++++++ 6 files changed, 348 insertions(+) create mode 100644 apps/web/src/lib/preserveReadingPosition.ts create mode 100644 scripts/scenarios/side-panel-preserves-reading-position.e2e.ts diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx index ff5b426c0bf3f..230603dfe46dd 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx @@ -682,6 +682,54 @@ it("reopens a long draft scrolled to its caret without taking focus", async () = expect(caret.bottom).toBeLessThanOrEqual(scroller.getBoundingClientRect().bottom - 48 + 1); }); +it.each(["none", "caret", "selection"] as const)( + "keeps the reading position when a draft rewraps (focus: %s)", + async (focus) => { + const focused = focus !== "none"; + const value = "A long wrapped paragraph should keep the sentence being read in view. ".repeat( + 100, + ); + const style = document.head.appendChild(document.createElement("style")); + style.textContent = ".composer-tiptap { width: 700px; max-height: 160px; overflow-y: auto; }"; + using _style = { [Symbol.dispose]: () => style.remove() }; + await using screen = await mountEditor(value); + const { editor } = screen; + const scroller = editor.view.dom; + await vi.waitFor(() => expect(scroller.scrollTop).toBeGreaterThan(500)); + if (focused) await focusAt(editor, 2000); + scroller.scrollTop = 300; + scroller.dispatchEvent(new Event("scroll")); + const box = scroller.getBoundingClientRect(); + const position = editor.view.posAtCoords({ + left: box.left + box.width / 2, + top: box.top + 25, + })!; + const before = editor.view.coordsAtPos(position.pos).top - box.top; + if (focused) await focusAt(editor, position.pos); + if (focus === "selection") { + editor.commands.setTextSelection({ from: position.pos, to: position.pos + 20 }); + } + document.dispatchEvent(new Event("selectionchange")); + const selection = editor.state.selection.toJSON(); + for (const width of [420, 700]) { + // The panel toggle shortcut reaches the focused editor before the width changes. + if (focused) { + scroller.dispatchEvent( + new KeyboardEvent("keydown", { key: "b", ctrlKey: true, altKey: true, bubbles: true }), + ); + } + scroller.style.width = `${width}px`; + await vi.waitFor(() => { + const after = + editor.view.coordsAtPos(position.pos).top - scroller.getBoundingClientRect().top; + expect(Math.abs(after - before)).toBeLessThan(25); + }); + expect(editor.state.selection.toJSON()).toEqual(selection); + expect(editor.view.hasFocus()).toBe(focused); + } + }, +); + it("does not outline the line under a click made with the node-select modifier held", async () => { await using screen = await mountEditor("ship it"); const { editor } = screen; diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index 634b7a9389e93..8ce568c117dce 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -64,6 +64,7 @@ import { pastedPathQueryLength, } from "~/composer-logic"; import { useStableCallback } from "~/hooks/useStableCallback"; +import { preserveReadingPosition } from "~/lib/preserveReadingPosition"; import { caretLineDirection, ComposerTextDirectionExtension } from "~/composer-text-direction"; import { collapseShownMarkdownSource, @@ -1765,6 +1766,11 @@ function ComposerPromptEditorTiptapInner( if (replacements.length > 0) replaceSkillChips(editor, replacements); }, [editor, literalText, modelKeys, skills]); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- keeps the mounted editor's visible text anchored while its DOM width changes + useLayoutEffect(() => { + if (editor) return preserveReadingPosition(editor.view.dom); + }, [editor]); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- restores ProseMirror focus and caret scroll when the keyed editor remounts, capturing focus on teardown useLayoutEffect(() => { if (!editor) return; diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index d15a26ca43db0..bce13bb454379 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -626,6 +626,48 @@ describe("MessagesTimeline messages", () => { await vi.waitFor(() => expect(viewport.scrollTop).toBeLessThan(atEnd)); }); + it("keeps the visible sentence in a long message when the chat width changes", async () => { + setup(); + const size = { width: window.innerWidth, height: window.innerHeight }; + onTestFinished(() => page.viewport(size.width, size.height)); + await page.viewport(1200, 1400); + const props = { ...baseProps(), liveFollowEnabled: false }; + const paragraphs = Array.from( + { length: 30 }, + (_, index) => + `Paragraph ${index + 1}. ${"A side panel should not move the sentence being read out of view. ".repeat(5)}`, + ); + await using screen = await renderTimeline( + [message(paragraphs.join("\n\n"), { role: "assistant" })], + props, + ); + screen.container.style.width = "900px"; + const viewport = props.listRef.current!.getScrollableNode()!; + const target = page.getByText(paragraphs[15]!.trim(), { exact: true }).element(); + await vi.waitFor(() => { + expect(viewport.scrollHeight).toBeGreaterThan(1000); + expect(viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop).toBeLessThan(2); + }); + await props.listRef.current!.scrollToOffset({ + offset: + viewport.scrollTop + + target.getBoundingClientRect().top - + viewport.getBoundingClientRect().top - + 24, + animated: false, + }); + viewport.dispatchEvent(new Event("scroll")); + const before = target.getBoundingClientRect().top - viewport.getBoundingClientRect().top; + expect(Math.abs(before - 24)).toBeLessThan(2); + for (const width of [500, 900]) { + screen.container.style.width = `${width}px`; + await vi.waitFor(() => { + const after = target.getBoundingClientRect().top - viewport.getBoundingClientRect().top; + expect(Math.abs(after - before)).toBeLessThan(30); + }); + } + }); + it("disables the minimap's next turn button at the bottom of the thread", async () => { setup(); const props = baseProps(); diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 207f719c8e6e9..42409464aca7a 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -26,6 +26,7 @@ import { parseScopedThreadKey } from "@t3tools/client-runtime/environment"; import { resolveWorkGroupScrollAnchor } from "@t3tools/client-runtime/work-log/scroll-anchor"; import type { WorkflowOpening } from "@t3tools/client-runtime/state/subagentRuntime"; import { observeResize } from "~/lib/observeResize"; +import { preserveReadingPosition } from "~/lib/preserveReadingPosition"; import { useStableCallback } from "~/hooks/useStableCallback"; const NOOP_USE_ARTIFACT_TEMPLATE = () => {}; @@ -1261,6 +1262,14 @@ const ConversationTimeline = memo(function ConversationTimeline({ const canvas = useChatCanvas(); const registerTimeline = canvas?.registerTimeline; + const shouldPreserveReadingPosition = useStableCallback( + () => + !liveFollowEnabled && + !anchoredEndSpace && + !findActive && + !citationPositioning && + !restoringThreadPosition, + ); // Stable so the list attaches once per mount, not on every render. const setTimelineList = useStableCallback((list: LegendListRef | null) => { listRef.current = list; @@ -1276,6 +1285,9 @@ const ConversationTimeline = memo(function ConversationTimeline({ }) : null; viewportRef.current = viewport; + const stopPreservingReadingPosition = scrollNode + ? preserveReadingPosition(scrollNode, shouldPreserveReadingPosition) + : undefined; const detachViewport = viewport ? onViewportAttach?.(viewport) : undefined; const stopRememberingRelease = viewport?.onFollowReleased(rememberReleasedPosition); const stopDisclosureReveal = viewport?.subscribe(() => { @@ -1304,6 +1316,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ scheduleContentSizeChanged(); return () => { stopListeningToContentSize?.(); + stopPreservingReadingPosition?.(); stopRememberingRelease?.(); stopDisclosureReveal?.(); if (contentSizeFrame !== null) cancelAnimationFrame(contentSizeFrame); diff --git a/apps/web/src/lib/preserveReadingPosition.ts b/apps/web/src/lib/preserveReadingPosition.ts new file mode 100644 index 0000000000000..2c6f576519911 --- /dev/null +++ b/apps/web/src/lib/preserveReadingPosition.ts @@ -0,0 +1,115 @@ +import { observeResize } from "./observeResize"; + +/** Native anchoring keeps a paragraph's start fixed, losing the visible line in a long paragraph. */ +export function preserveReadingPosition( + scroller: HTMLElement, + enabled: () => boolean = () => true, +): () => void { + let width = scroller.clientWidth; + let anchor: { range: Range; top: number } | null = null; + let frame: number | null = null; + + const capture = () => { + if (frame !== null || scroller.clientWidth !== width) return; + anchor = null; + if (!enabled() || scroller.scrollTop === 0) return; + const box = scroller.getBoundingClientRect(); + const selection = + scroller.isContentEditable && document.activeElement === scroller + ? document.getSelection() + : null; + if (selection?.isCollapsed && selection.rangeCount > 0) { + const range = selection.getRangeAt(0).cloneRange(); + const rect = range.getBoundingClientRect(); + if ( + scroller.contains(range.startContainer) && + rect.top >= box.top && + rect.bottom <= box.bottom + ) { + anchor = { range, top: rect.top - box.top }; + return; + } + } + // A point near the top captures text rather than the paragraph's bounding box. + const x = box.left + box.width / 2; + // The first point can land in paragraph spacing. Look only within the first few lines. + for (let inset = Math.min(24, box.height / 2); inset < Math.min(64, box.height); inset += 8) { + const y = box.top + inset; + const position = document.caretPositionFromPoint?.(x, y); + const range = document.createRange(); + if (position) { + range.setStart(position.offsetNode, position.offset); + } else { + const fallback = document.caretRangeFromPoint?.(x, y); + if (!fallback) continue; + range.setStart(fallback.startContainer, fallback.startOffset); + } + range.collapse(true); + if ( + !scroller.contains(range.startContainer) || + range.startContainer.nodeType !== Node.TEXT_NODE + ) + continue; + const top = range.getBoundingClientRect().top - box.top; + if (top >= 0 && top < scroller.clientHeight) { + anchor = { range, top }; + break; + } + } + }; + const restore = () => { + if ( + !enabled() || + !anchor || + anchor.range.startContainer.nodeType !== Node.TEXT_NODE || + !scroller.contains(anchor.range.startContainer) + ) + return; + const delta = + anchor.range.getBoundingClientRect().top - scroller.getBoundingClientRect().top - anchor.top; + if (Math.abs(delta) > 0.5) scroller.scrollTop += delta; + }; + const stop = observeResize(scroller, () => { + const nextWidth = scroller.clientWidth; + if (nextWidth === width) { + capture(); + return; + } + width = nextWidth; + restore(); + if (frame !== null) cancelAnimationFrame(frame); + // Virtualized rows can finish measuring in the next frame. Keep the same text anchor then. + frame = requestAnimationFrame(() => { + restore(); + frame = null; + capture(); + }); + }); + scroller.addEventListener("scroll", capture, { passive: true }); + scroller.addEventListener("input", capture); + const captureSelection = () => { + if (document.activeElement === scroller) capture(); + }; + if (scroller.isContentEditable) document.addEventListener("selectionchange", captureSelection); + const interrupt = () => { + if (frame !== null) cancelAnimationFrame(frame); + anchor = null; + // Scrolling wins over a pending resize correction; the next frame captures the reader's new place. + frame = requestAnimationFrame(() => { + frame = null; + width = scroller.clientWidth; + capture(); + }); + }; + scroller.addEventListener("wheel", interrupt, { passive: true }); + scroller.addEventListener("touchmove", interrupt, { passive: true }); + return () => { + stop(); + if (frame !== null) cancelAnimationFrame(frame); + scroller.removeEventListener("scroll", capture); + scroller.removeEventListener("input", capture); + document.removeEventListener("selectionchange", captureSelection); + scroller.removeEventListener("wheel", interrupt); + scroller.removeEventListener("touchmove", interrupt); + }; +} diff --git a/scripts/scenarios/side-panel-preserves-reading-position.e2e.ts b/scripts/scenarios/side-panel-preserves-reading-position.e2e.ts new file mode 100644 index 0000000000000..5a86da06aae41 --- /dev/null +++ b/scripts/scenarios/side-panel-preserves-reading-position.e2e.ts @@ -0,0 +1,124 @@ +/// +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +const text = Array.from( + { length: 70 }, + (_, index) => + `Sentence ${index + 1}. Opening a side panel should keep the sentence being read visible while the text wraps to the available width. `, +).join(""); + +test( + "Opening a side panel preserves the visible text in the conversation and draft", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo"); + const thread = await t3.thread({ + project, + title: "Reading position", + messages: ["Start"], + model: "multi-turn", + }); + await browser.setViewport({ width: 1440, height: 1000 }); + await t3.open(thread); + await screen.getByRole("button", "Toggle thread details panel").tap(); + await screen.getByRole("textbox").fill(text); + await screen.getByRole("textbox").press("Enter"); + await screen.getByText("second fixture turn complete", { exact: false }).waitFor(); + await screen.getByRole("button", "Show full message").tap(); + + const position = (draft: boolean, place: boolean) => + browser.evaluate( + async ({ draft, place }) => { + const scroller = document.querySelector( + draft ? ".composer-tiptap" : ".messages-timeline-scroll", + )!; + const content = draft + ? scroller + : Array.from(scroller.querySelectorAll("[data-user-message-body]")).find( + (body) => (body.textContent?.length ?? 0) >= 3000, + ); + if (!content) throw new Error("The long message is not rendered"); + const walker = document.createTreeWalker(content, NodeFilter.SHOW_TEXT); + let node = walker.nextNode(); + while (node && (node.textContent?.length ?? 0) < 3000) node = walker.nextNode(); + if (!node) throw new Error("The long paragraph is not rendered"); + const range = document.createRange(); + range.setStart(node, 2500); + range.collapse(true); + if (place) { + scroller.blur(); + scroller.scrollTop += + range.getBoundingClientRect().top - scroller.getBoundingClientRect().top - 48; + } + await new Promise((resolve) => + requestAnimationFrame(() => + requestAnimationFrame(() => requestAnimationFrame(() => resolve())), + ), + ); + return range.getBoundingClientRect().top - scroller.getBoundingClientRect().top; + }, + { draft, place }, + ); + + const point = await browser.evaluate(() => { + const box = document.querySelector(".messages-timeline-scroll")!.getBoundingClientRect(); + return { x: box.left + box.width / 2, y: box.top + 150 }; + }); + await browser.mouse.move(point.x, point.y); + await browser.mouse.wheel(0, -800); + // The wheel's native scroll completes asynchronously before positioning the fixture text. + await browser.evaluate( + () => + new Promise((resolve) => + requestAnimationFrame(() => requestAnimationFrame(() => resolve(null))), + ), + ); + let timelineBefore = await position(false, true); + if (Math.abs(timelineBefore - 48) > 2) timelineBefore = await position(false, true); + if (Math.abs(timelineBefore - 48) > 2) + throw new Error(`The conversation did not settle at the reading position: ${timelineBefore}`); + await app.screenshot("conversation-panel-closed"); + await screen.getByRole("button", "Toggle right panel").tap(); + const timelineAfter = await position(false, false); + await app.screenshot("conversation-panel-open"); + await screen.getByRole("button", "Toggle right panel").tap(); + + await screen.getByRole("textbox").fill(text); + const draftBefore = await position(true, true); + if (Math.abs(draftBefore - 48) > 2) + throw new Error("The draft did not settle at the reading position"); + await app.screenshot("draft-panel-closed"); + await screen.getByRole("button", "Toggle right panel").tap(); + const draftAfter = await position(true, false); + await app.screenshot("draft-panel-open"); + + // The panel shortcut is pressed inside the focused draft, with a caret and then a selection. + const shortcutShifts: number[] = []; + for (const length of [0, 20]) { + const shortcutBefore = await browser.evaluate((length) => { + const scroller = document.querySelector(".composer-tiptap")!; + scroller.focus(); + const node = document.createTreeWalker(scroller, NodeFilter.SHOW_TEXT).nextNode()!; + document.getSelection()!.setBaseAndExtent(node, 2500, node, 2500 + length); + const range = document.createRange(); + range.setStart(node, 2500); + scroller.scrollTop += + range.getBoundingClientRect().top - scroller.getBoundingClientRect().top - 48; + return range.getBoundingClientRect().top - scroller.getBoundingClientRect().top; + }, length); + await browser.keyboard.press("Control+Alt+B"); + shortcutShifts.push(Math.abs((await position(true, false)) - shortcutBefore)); + await app.screenshot(length === 0 ? "draft-caret-shortcut" : "draft-selection-shortcut"); + } + + expect( + Math.max( + Math.abs(timelineAfter - timelineBefore), + Math.abs(draftAfter - draftBefore), + ...shortcutShifts, + ), + ).toBeLessThan(30); + }, +); From 192ef9b7b204c09f1ec1e78255e4d2429d27b682 Mon Sep 17 00:00:00 2001 From: Victor Date: Sun, 22 Nov 2026 22:07:23 -0600 Subject: [PATCH 260/324] fix(web): preserve alpha channel when previewing WhiteIsZero TIFF images (#41196) Co-authored-by: Julius Marminge --- .../AttachmentFilePreview.browser.test.tsx | 89 ++++++++++--------- .../components/files/imageDecode.worker.ts | 6 +- 2 files changed, 53 insertions(+), 42 deletions(-) diff --git a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx index e96b165d5db0e..076f2c7ee32df 100644 --- a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx +++ b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx @@ -499,48 +499,55 @@ describe("bounded binary previews", () => { } }); - it("keeps WhiteIsZero TIFF brightness and rejects oversized metadata before decoding", async () => { - const tags = [ - [256, 2], - [257, 1], - [258, 8], - [259, 1], - [262, 0], - [273, 134], - [277, 1], - [278, 1], - [279, 2], - [284, 1], - ]; - const bytes = new ArrayBuffer(136); - const view = new DataView(bytes); - view.setUint16(0, 0x4949); - view.setUint16(2, 42, true); - view.setUint32(4, 8, true); - view.setUint16(8, tags.length, true); - tags.forEach(([tag, value], index) => { - const offset = 10 + index * 12; - view.setUint16(offset, tag!, true); - view.setUint16(offset + 2, 4, true); - view.setUint32(offset + 4, 1, true); - view.setUint32(offset + 8, value!, true); - }); - view.setUint8(135, 255); - const src = URL.createObjectURL(new Blob([bytes])); - try { - const blob = await decodeImagePreview(src, false, new AbortController().signal); - const bitmap = await createImageBitmap(blob); - const canvas = new OffscreenCanvas(2, 1); - const context = canvas.getContext("2d")!; - context.drawImage(bitmap, 0, 0); - expect([...context.getImageData(0, 0, 2, 1).data]).toEqual([ - 255, 255, 255, 255, 0, 0, 0, 255, - ]); - bitmap.close(); - } finally { - URL.revokeObjectURL(src); + it("keeps WhiteIsZero TIFF brightness and alpha and rejects oversized metadata before decoding", async () => { + let bytes = new ArrayBuffer(0); + for (const { pixels, expected } of [ + { pixels: [0, 255], expected: [255, 255, 255, 255, 0, 0, 0, 255] }, + { pixels: [0, 255, 255, 0], expected: [255, 255, 255, 255, 0, 0, 0, 0] }, + ]) { + const samples = pixels.length / 2; + const start = samples === 2 ? 146 : 134; + const tags = [ + [256, 2], + [257, 1], + [258, 8], + [259, 1], + [262, 0], + [273, start], + [277, samples], + [278, 1], + [279, pixels.length], + [284, 1], + ...(samples === 2 ? [[338, 2]] : []), + ]; + bytes = new ArrayBuffer(start + pixels.length); + const view = new DataView(bytes); + view.setUint16(0, 0x4949); + view.setUint16(2, 42, true); + view.setUint32(4, 8, true); + view.setUint16(8, tags.length, true); + tags.forEach(([tag, value], index) => { + const offset = 10 + index * 12; + view.setUint16(offset, tag!, true); + view.setUint16(offset + 2, 4, true); + view.setUint32(offset + 4, 1, true); + view.setUint32(offset + 8, value!, true); + }); + new Uint8Array(bytes, start).set(pixels); + const src = URL.createObjectURL(new Blob([bytes])); + try { + const blob = await decodeImagePreview(src, false, new AbortController().signal); + const bitmap = await createImageBitmap(blob); + const canvas = new OffscreenCanvas(2, 1); + const context = canvas.getContext("2d")!; + context.drawImage(bitmap, 0, 0); + expect([...context.getImageData(0, 0, 2, 1).data]).toEqual(expected); + bitmap.close(); + } finally { + URL.revokeObjectURL(src); + } } - view.setUint32(14, 1_000_000, true); + new DataView(bytes).setUint32(14, 1_000_000, true); const invalid = URL.createObjectURL(new Blob([bytes])); try { await expect( diff --git a/apps/web/src/components/files/imageDecode.worker.ts b/apps/web/src/components/files/imageDecode.worker.ts index f19174b62af35..9ddcfdbfb3e98 100644 --- a/apps/web/src/components/files/imageDecode.worker.ts +++ b/apps/web/src/components/files/imageDecode.worker.ts @@ -190,6 +190,9 @@ async function decode(bytes: ArrayBuffer, heif: boolean) { const rgba = new Uint8ClampedArray(image.width * image.height * 4); const scale = image.bitsPerSample === 16 ? 257 : 1; const palette = image.palette; + const alpha = image.alpha; + // The tiff decoder inverts every WhiteIsZero sample, alpha included. + const invertAlpha = alpha && image.type === 0; for (let pixel = 0; pixel < image.width * image.height; pixel++) { const index = pixel * image.components; if (palette) { @@ -203,7 +206,8 @@ async function decode(bytes: ArrayBuffer, heif: boolean) { const gray = image.data[index]! / scale; rgba.fill(gray, pixel * 4, pixel * 4 + 3); } - rgba[pixel * 4 + 3] = image.alpha ? image.data[index + image.components - 1]! / scale : 255; + const value = alpha ? image.data[index + image.components - 1]! / scale : 255; + rgba[pixel * 4 + 3] = invertAlpha ? 255 - value : value; } const canvas = new OffscreenCanvas(image.width, image.height); const context = canvas.getContext("2d"); From b50e76981188cf82965fdaa547b4f737c3f27836 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 20:08:24 -0800 Subject: [PATCH 261/324] fix(server): workflow event types appear only while Workflows is on (#41202) --- apps/server/src/mcp/McpHttpServer.ts | 17 ++++++++++++++--- apps/server/src/mcp/McpInvocationContext.ts | 9 +++++++++ .../src/milestones/MilestoneEvents.test.ts | 17 +++++++++++++++-- 3 files changed, 38 insertions(+), 5 deletions(-) diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index ab1f7b003c566..be41f8630b7dd 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -291,8 +291,13 @@ const makeMcpAuthMiddleware = Effect.gen(function* () { Effect.map((settings) => ({ linkedEnvironments: settings.linkedEnvironmentsEnabled, agentFeedback: settings.agentFeedback.mode, + workflows: settings.workflowsEnabled, + })), + Effect.orElseSucceed(() => ({ + linkedEnvironments: false, + agentFeedback: "off" as const, + workflows: false, })), - Effect.orElseSucceed(() => ({ linkedEnvironments: false, agentFeedback: "off" as const })), ); const pullRequests = yield* Effect.serviceOption(PullRequestService.PullRequestService); const projections = yield* Effect.serviceOption(ProjectionStore.ProjectionStoreV2); @@ -366,7 +371,7 @@ const makeMcpAuthMiddleware = Effect.gen(function* () { const asked = withModeLimit(withSenderThread(invocation, request), request); if (asked === undefined) return invalidModeLimit; const limited = McpInvocationContext.withRuntimeModeCeiling(asked, runtimeModeCeiling); - const { linkedEnvironments, agentFeedback } = yield* settingsFlags; + const { linkedEnvironments, agentFeedback, workflows } = yield* settingsFlags; if (limited.client?.linked === true && !linkedEnvironments) return linkedEnvironmentsOff; const origin = Option.getOrUndefined(Option.map(requestUrl(request), (url) => url.origin)); const forge = @@ -377,6 +382,7 @@ const makeMcpAuthMiddleware = Effect.gen(function* () { ...limited, linkedEnvironments, agentFeedback, + workflows, origin, ...(forge === undefined ? {} : { forge }), }; @@ -1549,8 +1555,13 @@ export const layerMilestoneEvents = Layer.effectDiscard( for (const options of events.threads) { yield* McpServer.registerEvent({ ...options, annotations }); } + // Listed only while Labs → Workflows is on, since no run can reach them otherwise. + const workflowAnnotations = Context.make( + McpSchema.EnabledWhen, + McpInvocationContext.hiddenUnlessWorkflowEvents, + ); for (const options of events.workflows) { - yield* McpServer.registerEvent({ ...options, annotations }); + yield* McpServer.registerEvent({ ...options, annotations: workflowAnnotations }); } }), ).pipe( diff --git a/apps/server/src/mcp/McpInvocationContext.ts b/apps/server/src/mcp/McpInvocationContext.ts index f1a070e86b9e3..0ba10af2d8c45 100644 --- a/apps/server/src/mcp/McpInvocationContext.ts +++ b/apps/server/src/mcp/McpInvocationContext.ts @@ -155,6 +155,8 @@ export interface McpInvocationScope { readonly linkedEnvironments?: boolean; /** The Agent feedback mode here; `/mcp` reads it per request. Unset is off. */ readonly agentFeedback?: AgentFeedbackMode; + /** True while Labs → Workflows is on here; `/mcp` reads it per request. Unset is off. */ + readonly workflows?: boolean; /** * The origin this `/mcp` request reached, e.g. a T3 Connect tunnel. Hosted clients cannot * see the URL they were configured with, so links they must fetch carry it. Unset in-process. @@ -237,6 +239,13 @@ export const hiddenWhileFeedbackOff = (): boolean => { return scope?.agentFeedback !== undefined && scope.agentFeedback !== "off"; }; +/** `McpSchema.EnabledWhen` for workflow event types: outside clients only, while Workflows is on. */ +export const hiddenUnlessWorkflowEvents = (): boolean => { + const fiber = Fiber.getCurrent(); + const scope = fiber && Context.getOrUndefined(fiber.context, McpInvocationContext); + return scope !== undefined && scope.thread === undefined && scope.workflows === true; +}; + /** `McpSchema.EnabledWhen` for tools that act on the thread's forge, hidden where it has none. */ export const hiddenWithoutForge = (): boolean => { const fiber = Fiber.getCurrent(); diff --git a/apps/server/src/milestones/MilestoneEvents.test.ts b/apps/server/src/milestones/MilestoneEvents.test.ts index 06e7763023841..49f6c1c5c6b5a 100644 --- a/apps/server/src/milestones/MilestoneEvents.test.ts +++ b/apps/server/src/milestones/MilestoneEvents.test.ts @@ -128,7 +128,7 @@ type JsonRpcResponse = { readonly error?: { readonly code: number; readonly data?: unknown }; }; -const serve = Effect.gen(function* () { +const serveWith = Effect.fnUntraced(function* (settings: { readonly workflowsEnabled: boolean }) { const revoked = yield* Deferred.make(); const deliveries = yield* Queue.unbounded(); const replies = new Set(); @@ -164,7 +164,7 @@ const serve = Effect.gen(function* () { }), ), ), - Layer.provide(ServerSettings.layerTest()), + Layer.provide(ServerSettings.layerTest(settings)), Layer.provide( Layer.mock(SessionStore.SessionStore)({ cookieName: "t3-session", @@ -285,6 +285,7 @@ const serve = Effect.gen(function* () { subscribe, }; }); +const serve = serveWith({ workflowsEnabled: true }); const layerTest = Layer.mergeAll( MilestoneHub.layer, @@ -330,6 +331,18 @@ it.effect("advertises the extension and lists each milestone type to outside cli }).pipe(Effect.scoped, Effect.provide(layerTest)), ); +it.effect("lists workflow event types only while Labs → Workflows is on", () => + Effect.gen(function* () { + const { call } = yield* serveWith({ workflowsEnabled: false }); + const { events } = (yield* call("events/list")).result!; + const names = (events as ReadonlyArray<{ name: string }>).map((event) => event.name); + expect(names).toHaveLength(6); + expect(names.some((name) => name.startsWith("workflow."))).toBe(false); + const poll = yield* call("events/poll", { name: "workflow.run_ended", cursor: null }); + expect(poll.error).toBeDefined(); + }).pipe(Effect.scoped, Effect.provide(layerTest)), +); + it.effect("polls from now, then pages forward and says when a cursor fell behind", () => Effect.gen(function* () { const hub = yield* MilestoneHub.MilestoneHub; From dc2f73af48dbb5f5983c2fca2bd520b70a56f5da Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 20:09:00 -0800 Subject: [PATCH 262/324] fix(server): worktree launches name their branch while the worktree is created (#36904) Co-authored-by: Claude Opus 5.5 --- .../ThreadLaunchService.test.ts | 37 +++++++++++++++++++ .../orchestration-v2/ThreadLaunchService.ts | 25 ++++++++++++- 2 files changed, 61 insertions(+), 1 deletion(-) diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts index 2d5d1c5824dde..9bc617e48823b 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts @@ -3233,6 +3233,43 @@ it.effect("starts the agent of a new worktree thread only after its branch is re }), ); +it.effect("names a new worktree thread's branch while its worktree is being created", () => + Effect.gen(function* () { + const branchNameStarted = yield* Deferred.make(); + const renamedTo = yield* Deferred.make(); + const harness = makeHarness({ + generateBranchName: () => + Deferred.succeed(branchNameStarted, undefined).pipe( + Effect.as({ branch: "generated-branch" }), + ), + createWorktree: (input) => + Deferred.await(branchNameStarted).pipe( + Effect.as({ + worktree: { + path: "/repo-worktrees/feature", + refName: input.newRefName, + headSha: "abc", + }, + } as never), + ), + renameBranch: (input) => + Deferred.succeed(renamedTo, input.newBranch).pipe(Effect.as({ branch: input.newBranch })), + }); + yield* Effect.gen(function* () { + const launches = yield* ThreadLaunch.ThreadLaunchService; + yield* launches.launch( + launchInput({ + command: "launch:name-during-checkout", + thread: "thread:name-during-checkout", + message: "Start", + workspace: { type: "worktree", baseRef: "main" }, + }), + ); + assert.equal(yield* Deferred.await(renamedTo), "generated-branch"); + }).pipe(Effect.provide(harness.layer)); + }), +); + it.effect("tells the thread when its worktree branch could not be renamed", () => Effect.gen(function* () { const harness = makeHarness({ diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.ts index ce22ad783e0e6..9262695987cbf 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.ts @@ -571,6 +571,7 @@ const make = Effect.gen(function* () { let runReleased = false; // Stop background renames before forgetting worktrees; completed renames record them again. let branchRename: Fiber.Fiber | null = null; + let stopBranchName: Effect.Effect = Effect.void; if (input.workspaceStrategy.type === "worktree") { yield* setupTracker.begin({ threadId, @@ -662,6 +663,19 @@ const make = Effect.gen(function* () { input.workspaceStrategy.type === "existing_worktree" ? input.workspaceStrategy.worktreePath : null; + // The agent waits for this LLM call; start it now so it overlaps fetch, checkout and setup. + const branchName = + reused === undefined && + initialMessage !== undefined && + (input.workspaceStrategy.type === "worktree" || worktreePath !== null) && + branch !== null && + (generatedTemporaryBranch || isTemporaryWorktreeBranch(branch)) + ? yield* generateBranchNameFor( + worktreePath ?? project.workspaceRoot, + initialMessage, + ).pipe(Effect.forkIn(preparationScope)) + : null; + if (branchName !== null) stopBranchName = Fiber.interrupt(branchName); if (input.workspaceStrategy.type === "worktree") { const taskPlan = yield* taskFolders .plan({ projectId: project.id, repositories: input.workspaceStrategy.repositories }) @@ -898,7 +912,11 @@ const make = Effect.gen(function* () { ) { const oldBranch = branch; const worktreeCwd = worktreePath; - branchRename = yield* generateBranchNameFor(worktreeCwd, initialMessage).pipe( + const generatedName = + branchName === null + ? generateBranchNameFor(worktreeCwd, initialMessage) + : Fiber.join(branchName); + branchRename = yield* generatedName.pipe( Effect.flatMap(({ branch: newBranch, exactName }) => Effect.suspend( (): Effect.Effect< @@ -995,6 +1013,8 @@ const make = Effect.gen(function* () { ), Effect.forkIn(preparationScope), ); + } else { + yield* stopBranchName; } if (runId !== null && worktreePath !== null) { @@ -1113,6 +1133,8 @@ const make = Effect.gen(function* () { Effect.onError((cause) => Effect.gen(function* () { const cancelled = Cause.hasInterruptsOnly(cause); + // Not yet handed to a rename, so nothing will use the name. + if (branchRename === null) yield* stopBranchName; yield* setupTracker.finish( threadId, cancelled ? "cancelled" : "failed", @@ -1128,6 +1150,7 @@ const make = Effect.gen(function* () { ((cancelled && !runReleased) || !workspaceRecorded) ) { if (branchRename !== null) yield* Fiber.interrupt(branchRename); + yield* stopBranchName; const removedPath = createdWorktreePath; const removedBranch = createdBranch; const removedTaskFolder = createdTaskFolder; From 9d3054a7bbc0ab02330a03d5735f4adf72a4e887 Mon Sep 17 00:00:00 2001 From: Victor Date: Sun, 22 Nov 2026 22:22:28 -0600 Subject: [PATCH 263/324] fix(cli): expand ~ paths passed to t3 project add --track (#41199) Co-authored-by: Julius Marminge --- apps/server/src/cli/project.test.ts | 7 ++++++- apps/server/src/cli/project.ts | 5 ++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/apps/server/src/cli/project.test.ts b/apps/server/src/cli/project.test.ts index 21c3e1caa1943..6dfd723e7084a 100644 --- a/apps/server/src/cli/project.test.ts +++ b/apps/server/src/cli/project.test.ts @@ -16,6 +16,7 @@ import { type OrchestrationV2AppThread, type ProjectId, } from "@t3tools/contracts"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import * as NetService from "@t3tools/shared/Net"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -139,6 +140,7 @@ it.effect( // Repositories inside the folder are found; `--track` adds one from outside it. const shared = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-v2-project-shared-")); + const homeShared = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-v2-project-home-")); NodeFS.mkdirSync(NodePath.join(workspaceRoot, "api", ".git"), { recursive: true }); NodeFS.mkdirSync(NodePath.join(workspaceRoot, "notes")); yield* runCli([ @@ -147,12 +149,15 @@ it.effect( workspaceRoot, "--track", `${shared}${NodePath.sep}`, + "--track", + `~/${NodePath.basename(homeShared)}`, "--base-dir", baseDir, - ]); + ]).pipe(Effect.provideService(HostProcess.HomeDirectory, NodeOS.tmpdir())); assert.deepEqual((yield* readProjects(baseDir)).projects[0]?.trackedFolders, [ { path: NodePath.join(workspaceRoot, "api"), name: "api", discovered: true }, { path: shared, name: NodePath.basename(shared) }, + { path: homeShared, name: NodePath.basename(homeShared) }, ]); }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); diff --git a/apps/server/src/cli/project.ts b/apps/server/src/cli/project.ts index d2e84e0d4f4f5..1fa7cc0f3f264 100644 --- a/apps/server/src/cli/project.ts +++ b/apps/server/src/cli/project.ts @@ -7,6 +7,8 @@ import { type ProjectSnapshot, ProjectId, } from "@t3tools/contracts"; +import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Console from "effect/Console"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; @@ -395,9 +397,10 @@ const projectAddCommand = Command.make("add", { (project) => project.deletedAt === null && project.workspaceRoot === workspaceRoot, ); const path = yield* Path.Path; + const home = yield* HostProcess.HomeDirectory; const named = flags.track .map((folder) => { - const resolved = path.resolve(folder); + const resolved = path.resolve(expandHomePath(folder, home)); return { path: resolved, name: (path.basename(resolved) || resolved).slice(0, 128).trim(), From 4aed1194fe32a11e4f40bc805ae606abadedf43e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 20:35:32 -0800 Subject: [PATCH 264/324] fix(server): html_preview as root names the sandbox opt-out (#41206) --- apps/server/src/htmlRender/HtmlRender.test.ts | 27 +++++++++++++++++++ apps/server/src/preview/PreviewBrowserHost.ts | 3 +++ 2 files changed, 30 insertions(+) diff --git a/apps/server/src/htmlRender/HtmlRender.test.ts b/apps/server/src/htmlRender/HtmlRender.test.ts index 4ef5d1d1db58e..e1ba0742f3c90 100644 --- a/apps/server/src/htmlRender/HtmlRender.test.ts +++ b/apps/server/src/htmlRender/HtmlRender.test.ts @@ -522,6 +522,33 @@ fs.createReadStream(null, { fd: 3 }).on("end", quit).on("data", (chunk) => { expect(error.message).toContain(`browser setup --base-dir ${baseDir}`); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); + + it.live("reports a root server's sandbox refusal as a root error", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-fake-browser-", + }); + const executable = path.join(directory, "chrome-headless-shell"); + const refusal = + "[1123/040735.447156:ERROR:content/browser/zygote_host/zygote_host_impl_linux.cc:103] Running as root without --no-sandbox is not supported. See https://crbug.com/638180.\n"; + yield* fileSystem.writeFileString( + executable, + `#!${process.execPath}\nprocess.stderr.write(${JSON.stringify(refusal)});\nprocess.exit(1);\n`, + { mode: 0o755 }, + ); + + const error = yield* HtmlRender.HtmlRender.use((htmlRender) => + htmlRender.preview({ html: "

    hello

    " }), + ).pipe( + Effect.flip, + Effect.provide(layerHtmlRender(executable)), + Effect.provideService(HostProcess.UserId, 0), + ); + expect(error).toBeInstanceOf(PreviewBrowserHost.PreviewBrowserRootError); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); }, ); diff --git a/apps/server/src/preview/PreviewBrowserHost.ts b/apps/server/src/preview/PreviewBrowserHost.ts index 0952dbaf944cd..6241ef9060238 100644 --- a/apps/server/src/preview/PreviewBrowserHost.ts +++ b/apps/server/src/preview/PreviewBrowserHost.ts @@ -8,6 +8,8 @@ import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; export const SETUP_SUBCOMMAND = "browser setup"; export const NO_SANDBOX_SIGNATURE = "No usable sandbox"; +/** What chrome-headless-shell prints itself when started sandboxed as root. */ +const ROOT_SANDBOX_SIGNATURE = "Running as root without --no-sandbox"; export const sandboxDisabled = (env: Readonly>) => env.T3CODE_SERVER_BROWSER_SANDBOX === "0"; @@ -92,6 +94,7 @@ export const diagnoseLaunchFailure = Effect.fn("PreviewBrowserHost.diagnoseLaunc readonly setupCommand: string; }) { const { setupCommand } = input; + if (input.output.includes(ROOT_SANDBOX_SIGNATURE)) return new PreviewBrowserRootError(); if (input.output.includes(NO_SANDBOX_SIGNATURE)) { // Playwright reports Chrome's refusal to sandbox as root as a sandbox failure too. return (yield* HostProcess.UserId) === 0 From d775f66a1578e25e95366346da576a6bdf7a3147 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Sun, 22 Nov 2026 20:36:22 -0800 Subject: [PATCH 265/324] chore: vouch jschachter (#41215) --- .github/VOUCHED.td | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/VOUCHED.td b/.github/VOUCHED.td index 5c0f9e1f74a2a..a2981329cda25 100644 --- a/.github/VOUCHED.td +++ b/.github/VOUCHED.td @@ -46,6 +46,7 @@ github:jamesx0416 github:jappyjan github:jasonLaster github:JoeEverest +github:jschachter github:justsomelegs github:kridaydave github:lgwacker From 7e5a4398f58df267ac4ca983bdf7fb2366081f85 Mon Sep 17 00:00:00 2001 From: Victor Date: Sun, 22 Nov 2026 22:40:39 -0600 Subject: [PATCH 266/324] fix(server): parse unordered HTML favicon rel tokens (#41203) Co-authored-by: Julius Marminge --- .../src/project/ProjectFaviconResolver.test.ts | 14 +++++++++++++- apps/server/src/project/ProjectFaviconResolver.ts | 6 ++++-- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/apps/server/src/project/ProjectFaviconResolver.test.ts b/apps/server/src/project/ProjectFaviconResolver.test.ts index d00147991cf5d..d4cc22efd220a 100644 --- a/apps/server/src/project/ProjectFaviconResolver.test.ts +++ b/apps/server/src/project/ProjectFaviconResolver.test.ts @@ -219,6 +219,18 @@ it.layer(layerTest)("ProjectFaviconResolverLive", (it) => { expect(yield* resolver.resolvePath(paddedCwd)).toBe( (yield* Path.Path).join(paddedCwd, "brand", "custom.svg"), ); + + const tokenListCwd = yield* makeTempDir; + yield* writeTextFile( + tokenListCwd, + "index.html", + ``, + ); + yield* writeTextFile(tokenListCwd, "touch.svg", "touch"); + yield* writeTextFile(tokenListCwd, "brand.svg", "brand"); + expect(yield* resolver.resolvePath(tokenListCwd)).toBe( + (yield* Path.Path).join(tokenListCwd, "brand.svg"), + ); }), ); @@ -248,7 +260,7 @@ it.layer(layerTest)("ProjectFaviconResolverLive", (it) => { head: () => ({ links: [ { rel: "stylesheet", href: "/app.css" }, - { rel: "icon", href: "/brand/logo.svg" }, + { rel: "icon shortcut", href: "/brand/logo.svg" }, ], }), });`, diff --git a/apps/server/src/project/ProjectFaviconResolver.ts b/apps/server/src/project/ProjectFaviconResolver.ts index 4554c308b4c19..497538634ae73 100644 --- a/apps/server/src/project/ProjectFaviconResolver.ts +++ b/apps/server/src/project/ProjectFaviconResolver.ts @@ -77,9 +77,11 @@ const ICON_SOURCE_FILES = [ ] as const; const HTML_LINK_RE = /]*>/gi; -const HTML_ICON_REL_RE = /\brel=["'](?:icon|shortcut icon)["']/i; +// `rel` is an unordered, whitespace-separated token list; any `icon` token marks an icon link. +const ICON_REL_VALUE = String.raw`(?:"(?:[^"]*[\t\n\f\r ])?icon(?=[\t\n\f\r "])|'(?:[^']*[\t\n\f\r ])?icon(?=[\t\n\f\r ']))`; +const HTML_ICON_REL_RE = new RegExp(String.raw`\brel=${ICON_REL_VALUE}`, "i"); const HTML_ICON_HREF_RE = /\bhref=["']([^"'?]+)/i; -const ICON_REL_RE = /\brel\s*:\s*["'](?:icon|shortcut icon)["']/i; +const ICON_REL_RE = new RegExp(String.raw`\brel\s*:\s*${ICON_REL_VALUE}`, "i"); const ICON_HREF_RE = /\bhref\s*:\s*["']([^"'?]+)/i; export class ProjectFaviconResolutionError extends Schema.TaggedError()( From 71d1830e52d8e4bcb2b81dead36ce449ef8db5c3 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Sun, 22 Nov 2026 21:02:49 -0800 Subject: [PATCH 267/324] fix(server): token analytics label new models from Codex and Claude catalogs (#41214) Co-authored-by: Claude Opus 5.5 --- .../src/feedback/FeedbackService.test.ts | 1 + .../src/telemetry/ProviderDimensions.test.ts | 19 +++++- .../src/telemetry/ProviderDimensions.ts | 67 ++++++++++--------- .../telemetry/ProviderUsageAnalytics.test.ts | 52 ++++++++++++-- 4 files changed, 100 insertions(+), 39 deletions(-) diff --git a/apps/server/src/feedback/FeedbackService.test.ts b/apps/server/src/feedback/FeedbackService.test.ts index cdc7a7984e6f7..be632b62c5fc2 100644 --- a/apps/server/src/feedback/FeedbackService.test.ts +++ b/apps/server/src/feedback/FeedbackService.test.ts @@ -314,6 +314,7 @@ const harness = Effect.gen(function* () { { instanceId, driver: "codex", + auth: { status: "authenticated" }, models: [{ slug: "gpt-5.5", isCustom: false }], } as unknown as ServerProvider, ]), diff --git a/apps/server/src/telemetry/ProviderDimensions.test.ts b/apps/server/src/telemetry/ProviderDimensions.test.ts index 00e59c11228cb..3959d7dc78e4b 100644 --- a/apps/server/src/telemetry/ProviderDimensions.test.ts +++ b/apps/server/src/telemetry/ProviderDimensions.test.ts @@ -7,15 +7,20 @@ const provider = ( instanceId: string, driver: string, models: ReadonlyArray<{ slug: string; isCustom: boolean }>, + auth: Record = {}, ) => ({ instanceId: ProviderInstanceId.make(instanceId), driver, + auth: { status: "authenticated", ...auth }, models, }) as unknown as ServerProvider; const providers = [ provider("work-codex", "codex", [{ slug: "gpt-5.5", isCustom: false }]), + provider("azure-codex", "codex", [{ slug: "gpt-acme-finetune", isCustom: false }], { + endpoint: "https://acme.example.com", + }), provider("claudeAgent", "claudeAgent", [ { slug: "claude-opus-5-5", isCustom: false }, { slug: "my-private-finetune", isCustom: true }, @@ -37,13 +42,17 @@ const thread = ( ...overrides, }); -it("omits custom, user-configured, and unknown models and instance names", () => { +it("omits custom, user-configured, endpoint-served, and unknown models and instance names", () => { expect( agentToolProperties({ tool: "t3_thread_send", providers, caller: thread("claudeAgent", "my-private-finetune"), - targets: [thread("opencode", "ollama/acme-internal"), thread("removed-instance", "gpt-5.5")], + targets: [ + thread("opencode", "ollama/acme-internal"), + thread("removed-instance", "gpt-5.5"), + thread("azure-codex", "gpt-acme-finetune"), + ], outcome: { outcome: "ok" }, }).map(({ callerProvider, callerModel, targetProvider, targetModel }) => ({ callerProvider, @@ -64,6 +73,12 @@ it("omits custom, user-configured, and unknown models and instance names", () => targetProvider: "unknown", targetModel: undefined, }, + { + callerProvider: "claudeAgent", + callerModel: undefined, + targetProvider: "codex", + targetModel: undefined, + }, ]); }); diff --git a/apps/server/src/telemetry/ProviderDimensions.ts b/apps/server/src/telemetry/ProviderDimensions.ts index 49faea7e688c0..497f1e660131b 100644 --- a/apps/server/src/telemetry/ProviderDimensions.ts +++ b/apps/server/src/telemetry/ProviderDimensions.ts @@ -6,19 +6,6 @@ import type { import { BUNDLED_MODEL_MANIFEST } from "../provider/ModelManifest.ts"; -/** - * Drivers whose model catalogs are published by the vendor. Other drivers - * (OpenCode, Pi, ACP agents) list models from the user's own configuration, - * such as local Ollama tags, so their model names stay out of analytics. - */ -const VENDOR_CATALOG_DRIVERS: ReadonlySet = new Set([ - "codex", - "claudeAgent", - "cursor", - "grok", - "antigravity", -]); - export interface ProviderDimensions { readonly provider: string; readonly model?: string; @@ -27,7 +14,7 @@ export interface ProviderDimensions { /** * Anonymous provider and model for a model selection. Instance ids are * user-defined, so only the driver kind is reported. The model is reported - * only when it comes from a vendor catalog and is not a user-added custom model. + * only when the selected instance's vendor catalog lists it. */ export function providerDimensions( providers: ReadonlyArray, @@ -35,17 +22,15 @@ export function providerDimensions( ): ProviderDimensions { const provider = providers.find((candidate) => candidate.instanceId === selection.instanceId); if (provider === undefined) return { provider: "unknown" }; - const model = provider.models.find((candidate) => candidate.slug === selection.model); - return VENDOR_CATALOG_DRIVERS.has(provider.driver) && model !== undefined && !model.isCustom - ? { provider: provider.driver, model: model.slug } - : { provider: provider.driver }; + const model = vendorCatalogEntry(provider, [selection.model]); + return model === undefined + ? { provider: provider.driver } + : { provider: provider.driver, model: model.slug }; } const DATED_SNAPSHOT = /-\d{8}$/u; -// The bundled manifest is reviewed in this repo. Codex lists whatever its configured -// model provider serves, so only the manifest vouches for Codex and Claude. Cursor, Grok, -// and Antigravity list their vendor's catalog, which ships models before the manifest does. +// The bundled manifest is reviewed in this repo. Vendor catalogs ship models before it does. const MANIFEST_LABELS: ReadonlyMap = new Map( Object.values(BUNDLED_MODEL_MANIFEST.providers ?? {}).flatMap((catalog) => catalog.models.flatMap((model) => @@ -53,13 +38,39 @@ const MANIFEST_LABELS: ReadonlyMap = new Map( ), ), ); -const REGISTRY_LABEL_DRIVERS: ReadonlySet = new Set(["cursor", "grok", "antigravity"]); + +// Drivers whose model lists come from the vendor. OpenCode, Pi, and ACP agents list the +// user's own configuration, such as local Ollama tags. Codex and Claude also list +// early-access code names, so only slugs in the vendor's public family vouch for them. +const VENDOR_CATALOGS: ReadonlyMap = new Map([ + ["cursor", undefined], + ["grok", undefined], + ["antigravity", undefined], + ["codex", /^gpt-/u], + ["claudeAgent", /^claude-/u], +]); + +// A custom endpoint or gateway serves whatever names its owner chose. +const isVendorRouted = (auth: ServerProvider["auth"]) => + auth.endpoint === undefined && auth.type !== "customEndpoint" && auth.type !== "bedrock"; + +function vendorCatalogEntry(provider: ServerProvider, candidates: ReadonlyArray) { + if (!VENDOR_CATALOGS.has(provider.driver) || !isVendorRouted(provider.auth)) return undefined; + const family = VENDOR_CATALOGS.get(provider.driver); + return provider.models.find( + (entry) => + !entry.isCustom && + (family === undefined || family.test(entry.slug)) && + (candidates.includes(entry.slug) || + entry.aliases?.some((alias) => candidates.includes(alias)) === true), + ); +} /** * The vendor catalog slug that a native or routed model id names, such as * `anthropic/claude-opus-5-5` or a dated snapshot. Models outside the bundled - * manifest and the Cursor, Grok, and Antigravity catalogs, including user-added ones, - * return undefined. + * manifest and vendor-routed provider catalogs, including user-added ones and + * names a custom endpoint serves, return undefined. */ export function catalogModelLabel( providers: ReadonlyArray, @@ -72,13 +83,7 @@ export function catalogModelLabel( if (label !== undefined) return label; } for (const provider of providers) { - if (!REGISTRY_LABEL_DRIVERS.has(provider.driver)) continue; - const match = provider.models.find( - (entry) => - !entry.isCustom && - (candidates.includes(entry.slug) || - entry.aliases?.some((alias) => candidates.includes(alias)) === true), - ); + const match = vendorCatalogEntry(provider, candidates); if (match !== undefined) return match.slug; } return undefined; diff --git a/apps/server/src/telemetry/ProviderUsageAnalytics.test.ts b/apps/server/src/telemetry/ProviderUsageAnalytics.test.ts index 249ec86f3724c..0ce417e9a2c8b 100644 --- a/apps/server/src/telemetry/ProviderUsageAnalytics.test.ts +++ b/apps/server/src/telemetry/ProviderUsageAnalytics.test.ts @@ -26,9 +26,28 @@ import { } from "./ProviderUsageAnalytics.ts"; const providers = [ - // Codex lists whatever its configured model provider serves, including private deployments. - { driver: "codex", models: [{ slug: "gpt-6-sol" }, { slug: "acme-azure-deployment" }] }, - { driver: "claudeAgent", models: [{ slug: "claude-opus-5-5" }, { slug: "claude-haiku-4-5" }] }, + // Vendor-routed Codex lists OpenAI's catalog, including early-access code names. + { + driver: "codex", + models: [{ slug: "gpt-6-sol" }, { slug: "gpt-6.2-sol" }, { slug: "nova-alpha" }], + }, + // A custom endpoint serves whatever its owner chose, including private deployments. + { + instanceId: "azure-codex", + driver: "codex", + auth: { endpoint: "https://acme.example.com" }, + models: [{ slug: "acme-azure-deployment" }, { slug: "gpt-acme-finetune" }], + }, + { + driver: "claudeAgent", + models: [{ slug: "claude-opus-5-5" }, { slug: "claude-haiku-4-5" }, { slug: "claude-opus-6" }], + }, + { + instanceId: "claude-gateway", + driver: "claudeAgent", + auth: { type: "customEndpoint" }, + models: [{ slug: "claude-ops-internal" }], + }, { driver: "opencode", models: [{ slug: "ollama/acme-internal" }] }, // Antigravity ships models before the bundled manifest lists them. { @@ -39,10 +58,21 @@ const providers = [ ], }, ].map( - ({ driver, models }) => + ({ + instanceId, + driver, + auth, + models, + }: { + instanceId?: string; + driver: string; + auth?: Record; + models: ReadonlyArray<{ slug: string; aliases?: ReadonlyArray }>; + }) => ({ - instanceId: ProviderInstanceId.make(driver), + instanceId: ProviderInstanceId.make(instanceId ?? driver), driver, + auth: { status: "authenticated", ...auth }, models: models.map((model) => ({ ...model, isCustom: false })), }) as unknown as ServerProvider, ); @@ -336,10 +366,20 @@ describe("provider usage reporting", () => { expect(routed("ollama/acme-internal", "secret-variant")).not.toHaveProperty("effort"); }); - it("reports Antigravity catalog models the bundled manifest does not list", () => { + it("reports vendor catalog models the bundled manifest does not list", () => { expect(label("gemini-4-hydrogen")).toBe("gemini-4-hydrogen"); expect(label("antigravity-default")).toBe("gemini-4-neon"); expect(label("gemini-4-unlisted")).toBeUndefined(); + expect(label("gpt-6.2-sol")).toBe("gpt-6.2-sol"); + expect(label("claude-opus-6")).toBe("claude-opus-6"); + for (const hidden of [ + "nova-alpha", + "acme-azure-deployment", + "gpt-acme-finetune", + "claude-ops-internal", + ]) { + expect(label(hidden)).toBeUndefined(); + } }); it("reports closed service tiers from a tier option or a fast mode toggle", () => { From 887e3a569ff3b72328c47efd7b17271bfcb44789 Mon Sep 17 00:00:00 2001 From: Victor Date: Sun, 22 Nov 2026 23:02:52 -0600 Subject: [PATCH 268/324] =?UTF-8?q?fix(web):=20file=20picker=20highlights?= =?UTF-8?q?=20stay=20on=20the=20typed=20letters=20after=20=C4=B0=20(#41216?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Julius Marminge --- .../files/ProjectFilePicker.logic.test.ts | 14 ++++++++++++++ .../components/files/ProjectFilePicker.logic.ts | 13 ++++++++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/files/ProjectFilePicker.logic.test.ts b/apps/web/src/components/files/ProjectFilePicker.logic.test.ts index f112ba97ab5d6..47efe8f58c44f 100644 --- a/apps/web/src/components/files/ProjectFilePicker.logic.test.ts +++ b/apps/web/src/components/files/ProjectFilePicker.logic.test.ts @@ -37,4 +37,18 @@ describe("getProjectFilePickerMatches", () => { [0, 1, 2], ); }); + + it("maps highlights back to original characters when lowercasing expands them", () => { + const entries = [{ kind: "file", path: "icons/İ-logo.svg" }] as const; + const indices = (query: string) => { + const match = getProjectFilePickerMatches(entries, query)[0]; + return [match?.nameMatchIndices, match?.pathMatchIndices]; + }; + + assert.deepEqual(indices("logo"), [ + [2, 3, 4, 5], + [8, 9, 10, 11], + ]); + assert.deepEqual(indices("İ"), [[0], [0, 6]]); + }); }); diff --git a/apps/web/src/components/files/ProjectFilePicker.logic.ts b/apps/web/src/components/files/ProjectFilePicker.logic.ts index 87fa4212eb384..a19e8b4a1e8d5 100644 --- a/apps/web/src/components/files/ProjectFilePicker.logic.ts +++ b/apps/web/src/components/files/ProjectFilePicker.logic.ts @@ -19,12 +19,23 @@ function findMatchIndices(value: string, query: string): number[] | null { if (!query) return []; const normalizedValue = value.toLowerCase(); + // Lowercasing lengthens İ (to i̇) and shortens nothing, so only a longer result needs mapping back. + const sourceSpans: Array = []; + if (normalizedValue.length !== value.length) { + let sourceOffset = 0; + for (const char of value) { + const span = [sourceOffset, sourceOffset + char.length] as const; + for (let n = char.toLowerCase().length; n > 0; n -= 1) sourceSpans.push(span); + sourceOffset = span[1]; + } + } const indices: number[] = []; let queryIndex = 0; for (let valueIndex = 0; valueIndex < normalizedValue.length; valueIndex += 1) { if (normalizedValue[valueIndex] !== query[queryIndex]) continue; - indices.push(valueIndex); + const [start, end] = sourceSpans[valueIndex] ?? [valueIndex, valueIndex + 1]; + for (let i = Math.max(start, (indices.at(-1) ?? -1) + 1); i < end; i += 1) indices.push(i); queryIndex += 1; if (queryIndex === query.length) return indices; } From 58aa80dcdf98594a2f98ee04b331ae23ca461fa3 Mon Sep 17 00:00:00 2001 From: miley Date: Mon, 23 Nov 2026 07:05:59 +0200 Subject: [PATCH 269/324] fix(server): T3's own git commands no longer start Git's auto maintenance (#41200) Co-authored-by: Julius Marminge --- apps/server/src/vcs/GitVcsDriverCore.test.ts | 5 ++++- apps/server/src/vcs/GitVcsDriverCore.ts | 17 +++-------------- apps/server/src/vcs/VcsProcess.ts | 18 +++++++++++++++++- 3 files changed, 24 insertions(+), 16 deletions(-) diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index b3ad640db4c7a..d64c0ec5cbb5b 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -6053,7 +6053,9 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { { fetch: "statusDetailsRemote" }, // Storage cleanup's merge check fetches the default branch on every sweep. { fetch: "fetchRemoteTrackingBranch" }, - ] as const)("does not start Git auto-maintenance from background $fetch fetches", ({ fetch }) => + // Startup pulls each project's default branch. + { fetch: "pullCurrentBranch" }, + ] as const)("does not start Git auto-maintenance from $fetch", ({ fetch }) => Effect.gen(function* () { const cwd = yield* makeTmpDir(); const remote = yield* makeTmpDir("git-vcs-driver-remote-"); @@ -6079,6 +6081,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { const driver = yield* GitVcsDriver.GitVcsDriver; if (fetch === "statusDetailsRemote") yield* driver.statusDetailsRemote(cwd); + else if (fetch === "pullCurrentBranch") yield* driver.pullCurrentBranch(cwd); else yield* driver.fetchRemoteTrackingBranch({ cwd, diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index f863f01bdb40a..9ee53e4e90ac3 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -47,11 +47,7 @@ import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../observabil import * as GitVcsDriver from "./GitVcsDriver.ts"; import { removeEmptyDirectory, type RemoveEmptyDirectoryError } from "./removeEmptyDirectory.ts"; import { VcsAutomaticFetchInterval } from "./VcsAutomaticFetchInterval.ts"; -import { - explicitBareRepositoryEnv, - gitConfigEnv, - unsetInheritedRepositoryEnv, -} from "./VcsProcess.ts"; +import { gitConfigEnv, serverGitConfigEnv, unsetInheritedRepositoryEnv } from "./VcsProcess.ts"; import { makeWorktreeCheckoutCache } from "./worktreeCheckoutCache.ts"; import { removeLinkedWorktree } from "./worktreeRemoval.ts"; import { resolveWorktreesDirectory } from "../worktreesDirectory.ts"; @@ -1095,7 +1091,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ...input.env, ...trace2Monitor.env, }; - const env = { ...baseEnv, ...explicitBareRepositoryEnv(baseEnv, hostPlatform) }; + const env = { ...baseEnv, ...serverGitConfigEnv(baseEnv, hostPlatform) }; const spawnEnv = { ...env, ...windowsLongPathConfigEnv(hostPlatform, env) }; const resolved = yield* resolveSpawnCommand("git", [], { env: spawnEnv }); const spawnError = (cause: unknown) => @@ -1558,17 +1554,12 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ) { const fetchCwd = path.basename(gitCommonDir) === ".git" ? path.dirname(gitCommonDir) : gitCommonDir; - // `--no-auto-gc` (a synonym of `--no-auto-maintenance` that older Git also knows) keeps - // this poll from starting `git gc --auto`. When that gc fails, for example on a repository - // with missing objects, Git retries it on every fetch and leaves a full-size `tmp_pack_*` - // behind each time, so a background poll could fill the disk. const fetchArgs = (mode: "--dry-run" | "--quiet") => [ "--git-dir", gitCommonDir, "fetch", mode, "--no-tags", - "--no-auto-gc", // FETCH_HEAD is written without a lock; overlapping a user's `git pull` makes that pull fail. "--no-write-fetch-head", "--", @@ -6531,13 +6522,11 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const fetchRemoteTrackingBranch: GitVcsDriver.GitVcsDriver["Service"]["fetchRemoteTrackingBranch"] = Effect.fn("fetchRemoteTrackingBranch")(function* (input) { - // Storage cleanup runs this every sweep: like the status fetch, a killed fetch strands a - // `tmp_pack_*` and a failing `gc --auto` repeats each time, so allow time and skip gc. + // Storage cleanup runs this every sweep, and a killed fetch strands a `tmp_pack_*`. const args = [ "fetch", "--quiet", "--no-tags", - "--no-auto-gc", "--", input.remoteName, `+refs/heads/${input.remoteBranch}:refs/remotes/${input.remoteName}/${input.remoteBranch}`, diff --git a/apps/server/src/vcs/VcsProcess.ts b/apps/server/src/vcs/VcsProcess.ts index 91e21e8f07a97..28b46c8c5482a 100644 --- a/apps/server/src/vcs/VcsProcess.ts +++ b/apps/server/src/vcs/VcsProcess.ts @@ -140,6 +140,22 @@ export const gitConfigEnv = ( export const explicitBareRepositoryEnv = (env: NodeJS.ProcessEnv, platform: NodeJS.Platform) => gitConfigEnv(env, "safe.bareRepository", "explicit", platform); +// A failing `gc --auto` (say, missing objects) reruns after every fetch and strands a full-size +// `tmp_pack_*` each time, so T3's frequent background Git calls could fill the disk. +const SERVER_GIT_CONFIG = [ + ["safe.bareRepository", "explicit"], + ["maintenance.auto", "false"], + ["gc.auto", "0"], +] as const; + +export const serverGitConfigEnv = (env: NodeJS.ProcessEnv, platform: NodeJS.Platform) => { + const added: NodeJS.ProcessEnv = {}; + for (const [key, value] of SERVER_GIT_CONFIG) { + Object.assign(added, gitConfigEnv({ ...env, ...added }, key, value, platform)); + } + return added; +}; + const REPOSITORY_SELECTORS = new Set([ "GIT_DIR", "GIT_WORK_TREE", @@ -248,7 +264,7 @@ export const make = Effect.gen(function* () { // LANGUAGE leaves LC_CTYPE, which hooks inherit, alone. ...(input.command === "git" ? { LANGUAGE: "C" } : {}), ...input.env, - ...explicitBareRepositoryEnv({ ...process.env, ...input.env }, hostPlatform), + ...serverGitConfigEnv({ ...process.env, ...input.env }, hostPlatform), }, timeout: input.timeoutMs ?? DEFAULT_TIMEOUT_MS, maxOutputBytes: input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES, From 73bb8ece1fd03501327fe20412e13a0b73e374f8 Mon Sep 17 00:00:00 2001 From: Victor Date: Sun, 22 Nov 2026 23:08:16 -0600 Subject: [PATCH 270/324] fix(web): accept TIFF files containing standard IFD tag type 13 (SubIFDs) (#41228) Co-authored-by: Julius Marminge --- .../files/AttachmentFilePreview.browser.test.tsx | 9 +++++---- apps/web/src/components/files/imageDecode.worker.ts | 2 +- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx index 076f2c7ee32df..9316935ba2df0 100644 --- a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx +++ b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx @@ -499,14 +499,14 @@ describe("bounded binary previews", () => { } }); - it("keeps WhiteIsZero TIFF brightness and alpha and rejects oversized metadata before decoding", async () => { + it("keeps WhiteIsZero TIFF brightness and alpha with SubIFDs tags and rejects oversized metadata before decoding", async () => { let bytes = new ArrayBuffer(0); for (const { pixels, expected } of [ { pixels: [0, 255], expected: [255, 255, 255, 255, 0, 0, 0, 255] }, { pixels: [0, 255, 255, 0], expected: [255, 255, 255, 255, 0, 0, 0, 0] }, ]) { const samples = pixels.length / 2; - const start = samples === 2 ? 146 : 134; + const start = samples === 2 ? 158 : 146; const tags = [ [256, 2], [257, 1], @@ -518,6 +518,7 @@ describe("bounded binary previews", () => { [278, 1], [279, pixels.length], [284, 1], + [330, 0, 13], ...(samples === 2 ? [[338, 2]] : []), ]; bytes = new ArrayBuffer(start + pixels.length); @@ -526,10 +527,10 @@ describe("bounded binary previews", () => { view.setUint16(2, 42, true); view.setUint32(4, 8, true); view.setUint16(8, tags.length, true); - tags.forEach(([tag, value], index) => { + tags.forEach(([tag, value, type = 4], index) => { const offset = 10 + index * 12; view.setUint16(offset, tag!, true); - view.setUint16(offset + 2, 4, true); + view.setUint16(offset + 2, type, true); view.setUint32(offset + 4, 1, true); view.setUint32(offset + 8, value!, true); }); diff --git a/apps/web/src/components/files/imageDecode.worker.ts b/apps/web/src/components/files/imageDecode.worker.ts index 9ddcfdbfb3e98..9cd3140308612 100644 --- a/apps/web/src/components/files/imageDecode.worker.ts +++ b/apps/web/src/components/files/imageDecode.worker.ts @@ -25,7 +25,7 @@ function validateTiffMetadata(bytes: ArrayBuffer) { const tag = view.getUint16(entry, littleEndian); const type = view.getUint16(entry + 2, littleEndian); const values = view.getUint32(entry + 4, littleEndian); - const width = [0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8][type]; + const width = [0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8, 4][type]; if (!width) throw new PreviewError({ code: "tiff-metadata-type" }); const length = values * width; const start = length > 4 ? view.getUint32(entry + 8, littleEndian) : entry + 8; From 6cfc3bf0d55819c4395aebce96df4e9c28575795 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 21:11:12 -0800 Subject: [PATCH 271/324] fix(shared): reject keybindings with a dangling or extra '+' (#41231) --- apps/server/src/keybindings.test.ts | 12 ++++++++++++ packages/shared/src/keybindings.ts | 4 +++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/apps/server/src/keybindings.test.ts b/apps/server/src/keybindings.test.ts index 7e846811e1440..44048330c3ae2 100644 --- a/apps/server/src/keybindings.test.ts +++ b/apps/server/src/keybindings.test.ts @@ -182,6 +182,8 @@ it.layer(NodeServices.layer)("keybindings", (it) => { { key: "mod+j", command: "terminal.toggle" }, { key: "mod+shift+d+o", command: "terminal.new" }, { key: "mod+x", command: "invalid.command" }, + { key: "mod+", command: "sidebar.toggle" }, + { key: "mod+a+++", command: "sidebar.toggle" }, ]), ); @@ -205,6 +207,16 @@ it.layer(NodeServices.layer)("keybindings", (it) => { index: 2, message: configState.issues[1]?.message ?? "", }, + { + kind: "keybindings.invalid-entry", + index: 3, + message: configState.issues[2]?.message ?? "", + }, + { + kind: "keybindings.invalid-entry", + index: 4, + message: configState.issues[3]?.message ?? "", + }, ]); }).pipe(Effect.provide(layerKeybindings())), ); diff --git a/packages/shared/src/keybindings.ts b/packages/shared/src/keybindings.ts index 9a67264d8bd1f..29bb71d5f6f1a 100644 --- a/packages/shared/src/keybindings.ts +++ b/packages/shared/src/keybindings.ts @@ -167,8 +167,10 @@ export function parseKeybindingShortcut(value: string): KeybindingShortcut | nul trailingEmptyCount += 1; tokens.pop(); } - if (trailingEmptyCount > 0) { + if (trailingEmptyCount === 2) { tokens.push("+"); + } else if (trailingEmptyCount !== 0) { + return null; } if (tokens.some((token) => token.length === 0)) { return null; From 12f19b83c0653f2ede65c39ef3367d2704be4230 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 21:12:23 -0800 Subject: [PATCH 272/324] fix(github): a remote host URL rejects no longer breaks GitHub resolution (#41232) --- .../server/gitHubRepositoryResolution.test.ts | 24 +++++++++++++++++++ .../src/server/gitHubRepositoryResolution.ts | 4 +++- 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/packages/source-control-github/src/server/gitHubRepositoryResolution.test.ts b/packages/source-control-github/src/server/gitHubRepositoryResolution.test.ts index 3447c3a1be2ab..2fd05d1dd0719 100644 --- a/packages/source-control-github/src/server/gitHubRepositoryResolution.test.ts +++ b/packages/source-control-github/src/server/gitHubRepositoryResolution.test.ts @@ -168,6 +168,30 @@ describe("gitHubApiHostForRemote", () => { ); assert.strictEqual(gitHubApiHostForRemote("git@gitlab.com:a/b.git"), null); }); + + it("ignores a secondary remote whose host is not a valid URL host", () => { + for (const url of [ + "git@nas.08:team/repo.git", + "git@08:team/repo.git", + "git@node.256:team/repo.git", + "git@[2001:db8::1]:team/repo.git", + ]) { + const remotes = [ + "origin\tgit@github.com:pingdotgg/t3code.git (fetch)", + `backup\t${url} (fetch)`, + ].join("\n"); + assert.deepStrictEqual( + resolveGitHubRepository({ + remotes, + resolved: "", + hostHint: undefined, + defaultHost: "github.com", + }), + { host: "github.com", locator: { host: "github.com", owner: "pingdotgg", name: "t3code" } }, + url, + ); + } + }); }); describe("github.com- SSH aliases", () => { diff --git a/packages/source-control-github/src/server/gitHubRepositoryResolution.ts b/packages/source-control-github/src/server/gitHubRepositoryResolution.ts index e42e428d9d997..cfd36b6c02765 100644 --- a/packages/source-control-github/src/server/gitHubRepositoryResolution.ts +++ b/packages/source-control-github/src/server/gitHubRepositoryResolution.ts @@ -166,7 +166,9 @@ function apiHostForSshAlias(host: string): string | null | undefined { export function gitHubApiHostForRemote(remoteUrl: string): string | null { const remote = parseGitRemoteHost(remoteUrl); if (remote === null) return null; - const host = new URL(`https://${remote.host}`).host.toLowerCase(); + const parsed = URL.parse(`https://${remote.host}`); + if (parsed === null) return null; + const host = parsed.host.toLowerCase(); if (isSshRemoteUrl(remoteUrl)) { const aliased = apiHostForSshAlias(host); if (aliased !== undefined) return aliased; From 21e7fc1545068b9cc95ed646f080b793b15f27d8 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 21:12:51 -0800 Subject: [PATCH 273/324] feat(scripts): a server metrics run catches CPU, memory and first-request regressions (#41159) Co-authored-by: Claude Opus 5.5 --- docs/internals/performance-regressions.md | 23 + package.json | 1 + scripts/scenarios/shell.ts | 2 +- scripts/server-metrics-report.ts | 339 ++++++ scripts/server-metrics.test.ts | 158 +++ scripts/server-metrics.ts | 1137 +++++++++++++++++++++ 6 files changed, 1659 insertions(+), 1 deletion(-) create mode 100644 scripts/server-metrics-report.ts create mode 100644 scripts/server-metrics.test.ts create mode 100644 scripts/server-metrics.ts diff --git a/docs/internals/performance-regressions.md b/docs/internals/performance-regressions.md index 25ecabd80c5a4..e67ff30a85e6a 100644 --- a/docs/internals/performance-regressions.md +++ b/docs/internals/performance-regressions.md @@ -97,6 +97,29 @@ catalog digests and status deltas gets the provider list of its first config in provider with 250 slash commands and 200 skills. The lists load with the first cwd snapshot, and a machine refresh sends back an empty provider list. +## Server process metrics + +`node scripts/server-metrics.ts run --out ` starts a checkout's server against throwaway +state, a fake Anthropic API and the real `claude` CLI, and records server CPU, wakeups, RSS and +heap at rest, with quiet Claude threads and with 5 streaming, plus how long a new thread takes to +reach the API. Only the server process is measured. + +- Compare refs with `ab `, not with two files from different times. It + alternates the two on one machine, and `compare` flags a metric only when the bootstrap interval + of the median difference clears both the threshold and the noise floor. Single runs on a busy + machine differ by more than most regressions. +- Read per-thread cost from `scaling`, a fit over 5 to 20 open threads. It separates what each + open thread costs from the fixed cost of the server, which the absolute numbers mix. +- `--soak ` reports heap and RSS slopes in MB per hour and the constructors that grew. + A rising heap floor is a leak; a high but flat one is not. +- The quiet and streaming windows save a CPU and an allocation profile, so a regression comes with + the functions that cost it. + +Run it on macOS and Windows too, and on Linux with `--no-agent-scope`. Only Linux has agent +scopes, so other platforms take per-process paths a Linux server with a systemd user manager never +runs. A one-second `ps -A` poll per Claude session cost 0.1.11 about 18% of a core with 20 open +threads on macOS and went unnoticed on Linux. + ## Event store and startup Sequence cursors must seek an index rather than scan retained history. The application sequence diff --git a/package.json b/package.json index 9f1d2bee11b58..190d7e25cc3ec 100644 --- a/package.json +++ b/package.json @@ -31,6 +31,7 @@ "tc": "vp run -r --cache --concurrency-limit 4 typecheck", "check:changed": "node scripts/check-changed.ts", "report:renders": "node scripts/render-metrics.ts", + "report:server": "node scripts/server-metrics.ts", "lint": "vp lint --report-unused-disable-directives", "i18n:untranslated": "node scripts/i18n-untranslated.ts", "knip": "knip --preprocessor ./scripts/knip-schemas.ts", diff --git a/scripts/scenarios/shell.ts b/scripts/scenarios/shell.ts index 40e3b224fa694..32adbe1920a8c 100644 --- a/scripts/scenarios/shell.ts +++ b/scripts/scenarios/shell.ts @@ -52,7 +52,7 @@ export const run = Effect.fn("scenario.run")( ); if (!(options.allowExit ?? [0]).includes(exitCode)) { return yield* new ScenarioError({ - message: `${program} ${args.slice(0, 3).join(" ")} exited with ${exitCode}: ${stderr.trim().slice(-600)}`, + message: `${program} ${args.slice(0, 3).join(" ")} exited with ${exitCode}: ${(stderr.trim() || stdout.trim()).slice(-600)}`, }); } return { stdout, stderr, exitCode: Number(exitCode) }; diff --git a/scripts/server-metrics-report.ts b/scripts/server-metrics-report.ts new file mode 100644 index 0000000000000..c024e9737ef46 --- /dev/null +++ b/scripts/server-metrics-report.ts @@ -0,0 +1,339 @@ +// The pure half of scripts/server-metrics.ts: the JSON it writes, and how two of them compare. +import * as Schema from "effect/Schema"; + +const Window = Schema.Struct({ + cpuPct: Schema.Number, + wakeupsPerSec: Schema.NullOr(Schema.Number), + rssPeakMB: Schema.Number, + rssMB: Schema.Number, + heapAfterGcMB: Schema.Number, +}); +export type Window = typeof Window.Type; +const Spread = Schema.Struct({ median: Schema.Number, p90: Schema.Number }); +const FirstWord = Schema.Struct({ toRequestMs: Spread, toDoneMs: Spread }); +export type FirstWord = typeof FirstWord.Type; +const Scaling = Schema.Struct({ + heapMBPerThread: Schema.Number, + rssMBPerThread: Schema.Number, + cpuPctPerThread: Schema.Number, + wakeupsPerThread: Schema.NullOr(Schema.Number), + /** Each measured point as [threads, cpuPct, wakeupsPerSec, rssMB, heapAfterGcMB]; not compared. */ + points: Schema.Array(Schema.Array(Schema.NullOr(Schema.Number))), +}); +const Soak = Schema.Struct({ + minutes: Schema.Number, + heapMBPerHour: Schema.Number, + rssMBPerHour: Schema.Number, +}); + +/** One pass over the scenarios. */ +export const Measured = Schema.Struct({ + startup: Schema.optional(Schema.Struct({ readyMs: Schema.Number })), + rest: Schema.optional(Window), + firstWord: Schema.optional(Schema.Struct({ inPlace: FirstWord, worktree: FirstWord })), + quiet: Schema.optional(Window), + scaling: Schema.optional(Scaling), + streaming: Schema.optional(Window), + soak: Schema.optional(Soak), +}); +export type Measured = typeof Measured.Type; + +const Hotspot = Schema.Struct({ frame: Schema.String, value: Schema.Number }); +export type Hotspot = typeof Hotspot.Type; +const ProfileSummary = Schema.Struct({ + cpuMs: Schema.Array(Hotspot), + allocatedMB: Schema.Array(Hotspot), +}); +export type ProfileSummary = typeof ProfileSummary.Type; +export const HeapGrowth = Schema.Struct({ + constructor: Schema.String, + count: Schema.Number, + MB: Schema.Number, +}); + +export const ServerMetrics = Schema.Struct({ + meta: Schema.Record( + Schema.String, + Schema.Union([Schema.String, Schema.Number, Schema.Boolean, Schema.Null]), + ), + runs: Schema.Array(Measured), + /** Top CPU self time (ms) and allocated MB by function, from the last run. */ + profiles: Schema.optional(Schema.Record(Schema.String, ProfileSummary)), + soakHeapGrowth: Schema.optional(Schema.Array(HeapGrowth)), +}); +export type ServerMetrics = typeof ServerMetrics.Type; + +export const round = (value: number, digits = 1) => Math.round(value * 10 ** digits) / 10 ** digits; + +/** `ps -o time=` CPU time, `[[dd-]hh:]mm:ss[.ss]`, in seconds; NaN for anything else. */ +export function parsePsCpuTime(text: string) { + const match = /^(?:(?:(\d+)-)?(\d+):)?(\d+):(\d+(?:\.\d+)?)$/.exec(text.trim()); + if (match === null) return Number.NaN; + const [, days = "0", hours = "0", minutes = "0", seconds = "0"] = match; + return ((Number(days) * 24 + Number(hours)) * 60 + Number(minutes)) * 60 + Number(seconds); +} + +/** + * `--only`, `--threads` and `--soak` as run options. Thread counts must ascend because threads stay + * open, so a lower count after a higher one would mislabel its window. A soak alone runs nothing else. + */ +export function parseRunSelection(input: { + readonly only: string; + readonly threads: string; + readonly soak: number; + readonly scenarios: ReadonlyArray; +}): + | { readonly only: ReadonlyArray; readonly threads: ReadonlyArray } + | { readonly error: string } { + const only = input.only.split(",").filter(Boolean); + const unknown = only.filter((name) => !input.scenarios.includes(name)); + if (unknown.length > 0) return { error: `unknown scenario: ${unknown.join(", ")}` }; + const threads = input.threads + .split(",") + .map((count) => (count.trim() === "" ? Number.NaN : Number(count))); + if ( + threads.some( + (count, index) => !Number.isInteger(count) || count < 0 || count < (threads[index - 1] ?? 0), + ) + ) { + return { error: "--threads takes ascending counts such as 0,5,10,20" }; + } + if (!Number.isInteger(input.soak) || input.soak < 0) + return { error: "--soak takes minutes, 0 for none" }; + return { only: input.soak > 0 && only.length === 0 ? ["none"] : only, threads }; +} + +export function spread(values: ReadonlyArray) { + const sorted = values.toSorted((a, b) => a - b); + const at = (q: number) => sorted[Math.min(sorted.length - 1, Math.ceil(q * sorted.length) - 1)]; + return { median: Math.round(at(0.5) ?? 0), p90: Math.round(at(0.9) ?? 0) }; +} + +/** Least-squares slope of y over x. */ +export function slope(points: ReadonlyArray) { + const n = points.length; + if (n < 2) return 0; + const mx = points.reduce((sum, [x]) => sum + x, 0) / n; + const my = points.reduce((sum, [, y]) => sum + y, 0) / n; + let numerator = 0; + let denominator = 0; + for (const [x, y] of points) { + numerator += (x - mx) * (y - my); + denominator += (x - mx) ** 2; + } + return denominator === 0 ? 0 : numerator / denominator; +} + +/** Numeric leaves by dotted path, such as `quiet.cpuPct` or `firstWord.worktree.toRequestMs.p90`. */ +export function flatten(measured: Measured): Map { + const values = new Map(); + const visit = (value: unknown, path: string) => { + if (typeof value === "number") values.set(path, value); + else if (value && typeof value === "object") { + for (const [key, child] of Object.entries(value)) visit(child, path ? `${path}.${key}` : key); + } + }; + visit(measured, ""); + return values; +} + +function noiseFloor(metric: string) { + if (metric.startsWith("scaling.")) return metric.endsWith("cpuPctPerThread") ? 0.2 : 2; + if (metric.startsWith("soak.")) return 20; + if (metric.endsWith("cpuPct")) return 1; + if (metric.endsWith("wakeupsPerSec")) return 20; + if (metric.endsWith("MB")) return 15; + return 300; +} + +const median = (values: ReadonlyArray) => { + const sorted = values.toSorted((a, b) => a - b); + const middle = Math.floor(sorted.length / 2); + return sorted.length % 2 ? sorted[middle]! : (sorted[middle - 1]! + sorted[middle]!) / 2; +}; + +/** 95% bootstrap interval of median(b) - median(a), with a fixed seed so reruns agree. */ +export function bootstrapMedianDifference(a: ReadonlyArray, b: ReadonlyArray) { + let seed = 0x5eed; + const random = () => { + seed = (seed + 0x6d2b79f5) | 0; + let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296; + }; + const resample = (values: ReadonlyArray) => + median(Array.from(values, () => values[Math.floor(random() * values.length)]!)); + const differences = Array.from({ length: 2_000 }, () => resample(b) - resample(a)).toSorted( + (x, y) => x - y, + ); + return [differences[49]!, differences[1_949]!] as const; +} + +export function compareMetrics(before: ServerMetrics, after: ServerMetrics, threshold = 10) { + const collect = (metrics: ServerMetrics) => { + const values = new Map(); + for (const run of metrics.runs) { + for (const [metric, value] of flatten(run)) { + values.set(metric, [...(values.get(metric) ?? []), value]); + } + } + return values; + }; + const a = collect(before); + const b = collect(after); + const lines = [ + "### Server metrics (lower is better)", + "", + `before \`${before.meta.commit}\` (${before.runs.length} runs), after \`${after.meta.commit}\` (${after.runs.length} runs), ${after.meta.platform}${after.meta.noAgentScope ? ", no agent scope" : ""}`, + "", + "| metric | before | after | change | 95% interval | |", + "| :-- | --: | --: | --: | --: | :-- |", + ]; + const regressed: string[] = []; + const improved: string[] = []; + let compared = 0; + for (const metric of new Set([...a.keys(), ...b.keys()])) { + if (metric === "soak.minutes" || metric.startsWith("scaling.points")) continue; + const x = a.get(metric); + const y = b.get(metric); + if (!x || !y) { + lines.push(`| ${metric} | ${x ? median(x) : "–"} | ${y ? median(y) : "–"} | n/a | | |`); + continue; + } + compared++; + const mx = median(x); + const my = median(y); + // A change counts only past both the relative threshold and the absolute noise floor. + const limit = Math.max(noiseFloor(metric), (Math.abs(mx) * threshold) / 100); + const repeated = x.length > 1 && y.length > 1; + const [low, high] = repeated ? bootstrapMedianDifference(x, y) : [my - mx, my - mx]; + const verdict = low > limit ? "worse" : high < -limit ? "better" : ""; + if (verdict === "worse") regressed.push(metric); + if (verdict === "better") improved.push(metric); + const percent = mx === 0 ? (my === 0 ? 0 : Infinity) : ((my - mx) / Math.abs(mx)) * 100; + const shown = Number.isFinite(percent) + ? `${percent > 0 ? "+" : ""}${Math.round(percent)}%` + : "new"; + const interval = repeated ? `${round(low, 2)} to ${round(high, 2)}` : ""; + lines.push( + `| ${metric} | ${round(mx, 2)} | ${round(my, 2)} | ${shown} | ${interval} | ${verdict} |`, + ); + } + return { table: lines.join("\n"), regressed, improved, compared }; +} + +const CallFrame = Schema.Struct({ + functionName: Schema.String, + url: Schema.String, + lineNumber: Schema.Number, +}); +type CallFrame = typeof CallFrame.Type; +export const CpuProfile = Schema.Struct({ + nodes: Schema.Array( + Schema.Struct({ callFrame: CallFrame, hitCount: Schema.optional(Schema.Number) }), + ), + samples: Schema.optional(Schema.Array(Schema.Number)), + startTime: Schema.Number, + endTime: Schema.Number, +}); +interface HeapProfileNode { + readonly callFrame: CallFrame; + readonly selfSize: number; + readonly children: ReadonlyArray; +} +const HeapProfileNode: Schema.Codec = Schema.Struct({ + callFrame: CallFrame, + selfSize: Schema.Number, + children: Schema.Array(Schema.suspend(() => HeapProfileNode)), +}); +export const HeapProfile = Schema.Struct({ head: HeapProfileNode }); + +const shortUrl = (url: string) => + url + .replace(/^file:\/\//, "") + .split(/[\\/]/) + .slice(-3) + .join("/"); +const frameName = (frame: CallFrame) => + `${frame.functionName || "(anonymous)"} ${frame.url ? `${shortUrl(frame.url)}:${frame.lineNumber + 1}` : ""}`.trim(); +const top = (totals: Map, digits: number): Hotspot[] => + [...totals] + .toSorted((a, b) => b[1] - a[1]) + .slice(0, 10) + .map(([frame, value]) => ({ frame, value: round(value, digits) })); + +/** Top CPU self time in ms and allocated MB, by function. */ +export function summarizeProfiles( + cpu: typeof CpuProfile.Type, + heap: typeof HeapProfile.Type, +): ProfileSummary { + const perSampleMs = (cpu.endTime - cpu.startTime) / 1_000 / Math.max(1, cpu.samples?.length ?? 1); + const cpuTotals = new Map(); + for (const node of cpu.nodes) { + if (!node.hitCount || node.callFrame.functionName === "(idle)") continue; + const name = frameName(node.callFrame); + cpuTotals.set(name, (cpuTotals.get(name) ?? 0) + node.hitCount * perSampleMs); + } + const allocations = new Map(); + const visit = (node: HeapProfileNode) => { + const name = frameName(node.callFrame); + allocations.set(name, (allocations.get(name) ?? 0) + node.selfSize / 1e6); + for (const child of node.children) visit(child); + }; + visit(heap.head); + return { cpuMs: top(cpuTotals, 0), allocatedMB: top(allocations, 1) }; +} + +export const HeapSnapshot = Schema.Struct({ + snapshot: Schema.Struct({ + meta: Schema.Struct({ + node_fields: Schema.Array(Schema.String), + node_types: Schema.Array(Schema.Union([Schema.Array(Schema.String), Schema.String])), + }), + }), + nodes: Schema.Array(Schema.Number), + strings: Schema.Array(Schema.String), +}); + +/** Self size by constructor from a V8 heap snapshot. */ +export function heapByConstructor(snapshot: typeof HeapSnapshot.Type) { + const fields = snapshot.snapshot.meta.node_fields; + const typeNames = snapshot.snapshot.meta.node_types[0]; + const types = Array.isArray(typeNames) ? typeNames : []; + const typeAt = fields.indexOf("type"); + const nameAt = fields.indexOf("name"); + const sizeAt = fields.indexOf("self_size"); + const totals = new Map(); + for (let index = 0; index < snapshot.nodes.length; index += fields.length) { + const type = types[snapshot.nodes[index + typeAt]!] ?? "?"; + const label = snapshot.strings[snapshot.nodes[index + nameAt]!] ?? ""; + const name = + type === "object" + ? label.slice(0, 80) + : type === "closure" + ? `(closure) ${label.slice(0, 60)}` + : `(${type.replace(/^(concatenated|sliced) /, "")})`; + const entry = totals.get(name) ?? { count: 0, bytes: 0 }; + entry.count++; + entry.bytes += snapshot.nodes[index + sizeAt]!; + totals.set(name, entry); + } + return totals; +} + +/** The constructors whose heap grew most from one snapshot to the next. */ +export function heapGrowth( + before: ReturnType, + after: ReturnType, +) { + return [...after] + .map(([name, { count, bytes }]) => ({ + constructor: name, + count: count - (before.get(name)?.count ?? 0), + bytes: bytes - (before.get(name)?.bytes ?? 0), + })) + .filter((entry) => entry.bytes > 0) + .toSorted((a, b) => b.bytes - a.bytes) + .slice(0, 25) + .map(({ bytes, ...entry }) => ({ ...entry, MB: round(bytes / 1e6, 2) })); +} diff --git a/scripts/server-metrics.test.ts b/scripts/server-metrics.test.ts new file mode 100644 index 0000000000000..fe87cbbd39c68 --- /dev/null +++ b/scripts/server-metrics.test.ts @@ -0,0 +1,158 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + compareMetrics, + heapGrowth, + parsePsCpuTime, + parseRunSelection, + slope, + type ServerMetrics, +} from "./server-metrics-report.ts"; + +type Quiet = { cpuPct: number; wakeupsPerSec: number | null; rssPeakMB: number }; +const meta = { commit: "abc", platform: "linux-x64", noAgentScope: true }; +const quietRuns = (...runs: Quiet[]) => + ({ + meta, + runs: runs.map((quiet) => ({ quiet: { ...quiet, rssMB: 500, heapAfterGcMB: 200 } })), + }) satisfies ServerMetrics; +const base: Quiet = { cpuPct: 0.3, wakeupsPerSec: 7, rssPeakMB: 500 }; +const cpuRuns = (...values: number[]) => + quietRuns(...values.map((cpuPct) => ({ ...base, cpuPct }))); + +describe("compareMetrics", () => { + it.each([ + ["a CPU jump past both the percentage and the floor", { cpuPct: 18.6 }, ["quiet.cpuPct"], []], + ["a large relative change under the 1 point CPU floor", { cpuPct: 0.9 }, [], []], + ["RSS growth under the 15 MB floor", { rssPeakMB: 512 }, [], []], + ["RSS growth past it", { rssPeakMB: 585 }, ["quiet.rssPeakMB"], []], + [ + "an improvement past the floors", + { cpuPct: 0.1, wakeupsPerSec: 7, rssPeakMB: 400 }, + [], + ["quiet.rssPeakMB"], + ], + ])("one run each: %s", (_name, change, regressed, improved) => { + const result = compareMetrics(quietRuns(base), quietRuns({ ...base, ...change })); + expect(result.regressed).toEqual(regressed); + expect(result.improved).toEqual(improved); + }); + + it("shows a metric missing on one side as n/a, not as a change", () => { + const before = quietRuns({ ...base, wakeupsPerSec: null }); + const result = compareMetrics(before, quietRuns({ ...base, wakeupsPerSec: 50 })); + expect(result.regressed).toEqual([]); + expect(result.table).toContain("| quiet.wakeupsPerSec | – | 50 | n/a | | |"); + }); + + it("flags repeated runs only when the whole interval clears the limit", () => { + const steady = cpuRuns(26.1, 27.4, 25.8); + const fixed = cpuRuns(2.2, 2.5, 2.1); + expect(compareMetrics(steady, fixed).improved).toContain("quiet.cpuPct"); + expect(compareMetrics(fixed, steady).regressed).toContain("quiet.cpuPct"); + // The medians differ by 2.8 points, past the floor, but a resampled median can match. + expect(compareMetrics(fixed, cpuRuns(2.2, 5, 9)).regressed).toEqual([]); + }); + + it("counts how many metrics both sides share", () => { + const startupOnly: ServerMetrics = { meta, runs: [{ startup: { readyMs: 9_000 } }] }; + expect(compareMetrics(startupOnly, quietRuns(base)).compared).toBe(0); + expect(compareMetrics(quietRuns(base), quietRuns(base)).compared).toBe(5); + }); +}); + +describe("heapGrowth", () => { + it("lists only constructors that grew, small growth included", () => { + const before = new Map([ + ["Shrank", { count: 10, bytes: 5_000_000 }], + ["Flat", { count: 3, bytes: 1_000 }], + ["Grew", { count: 1, bytes: 1_000 }], + ]); + const after = new Map([ + ["Shrank", { count: 5, bytes: 1_000_000 }], + ["Flat", { count: 3, bytes: 1_000 }], + ["Grew", { count: 2, bytes: 1_500 }], + ["New", { count: 4, bytes: 3_000_000 }], + ]); + expect(heapGrowth(before, after)).toEqual([ + { constructor: "New", count: 4, MB: 3 }, + { constructor: "Grew", count: 1, MB: 0 }, + ]); + }); +}); + +describe("slope", () => { + it("fits the cost per thread", () => { + const points: Array = [ + [0, 175], + [5, 180], + [10, 185], + [20, 195], + ]; + expect(slope(points)).toBeCloseTo(1); + }); +}); + +describe("parsePsCpuTime", () => { + it.each([ + ["0:00.00", 0], + ["1:02.50", 62.5], + ["1:00:00.00", 3600], + ["2-01:00:00", 2 * 86_400 + 3600], + ["1-02:03", Number.NaN], + ["::", Number.NaN], + ["", Number.NaN], + ["1:2:3:4", Number.NaN], + ])("%s", (text, seconds) => { + expect(parsePsCpuTime(text)).toBe(seconds); + }); +}); + +describe("parseRunSelection", () => { + const scenarios = ["rest", "quiet", "streaming"]; + it.each([ + [ + "the default thread counts", + { only: "", threads: "0,5,10,20", soak: 0 }, + { only: [], threads: [0, 5, 10, 20] }, + ], + [ + "descending thread counts", + { only: "", threads: "5,20,10", soak: 0 }, + { error: "--threads takes ascending counts such as 0,5,10,20" }, + ], + [ + "an empty thread count", + { only: "", threads: "0,,10", soak: 0 }, + { error: "--threads takes ascending counts such as 0,5,10,20" }, + ], + [ + "named scenarios", + { only: "rest,quiet", threads: "0", soak: 0 }, + { only: ["rest", "quiet"], threads: [0] }, + ], + [ + "an unknown scenario", + { only: "rest,idle", threads: "0", soak: 0 }, + { error: "unknown scenario: idle" }, + ], + ["a soak alone", { only: "", threads: "0", soak: 10 }, { only: ["none"], threads: [0] }], + [ + "a soak with scenarios", + { only: "rest", threads: "0", soak: 10 }, + { only: ["rest"], threads: [0] }, + ], + [ + "a negative soak", + { only: "", threads: "0", soak: -1 }, + { error: "--soak takes minutes, 0 for none" }, + ], + [ + "an infinite soak", + { only: "", threads: "0", soak: Number.POSITIVE_INFINITY }, + { error: "--soak takes minutes, 0 for none" }, + ], + ])("%s", (_name, input, expected) => { + expect(parseRunSelection({ ...input, scenarios })).toEqual(expected); + }); +}); diff --git a/scripts/server-metrics.ts b/scripts/server-metrics.ts new file mode 100644 index 0000000000000..3a9887f40f5fb --- /dev/null +++ b/scripts/server-metrics.ts @@ -0,0 +1,1137 @@ +#!/usr/bin/env node +// Measures a checkout's server process (CPU, wakeups, memory, time to the API) against a fake +// Anthropic API and the real `claude` CLI. See docs/internals/performance-regressions.md. +// @effect-diagnostics nodeBuiltinImport:off - NodeHttpServer takes a node:http server. +import * as NodeHttp from "node:http"; + +import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient"; +import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer"; +import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as NodeSocket from "@effect/platform-node/NodeSocket"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { fromJsonStringPretty } from "@t3tools/shared/schemaJson"; +import * as Clock from "effect/Clock"; +import * as Console from "effect/Console"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Deferred from "effect/Deferred"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import * as Random from "effect/Random"; +import * as Ref from "effect/Ref"; +import * as Schedule from "effect/Schedule"; +import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; +import { Argument, Command, Flag } from "effect/cli"; +import { HttpClient, HttpServer, HttpServerRequest, HttpServerResponse } from "effect/http"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; +import * as Socket from "effect/socket/Socket"; + +import { run } from "./scenarios/shell.ts"; +import { + compareMetrics, + CpuProfile, + HeapProfile, + HeapSnapshot, + heapByConstructor, + heapGrowth, + round, + ServerMetrics, + slope, + spread, + parsePsCpuTime, + parseRunSelection, + summarizeProfiles, + type FirstWord, + type Measured, + type ProfileSummary, + type Window, +} from "./server-metrics-report.ts"; + +const PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)); +const MODEL = "claude-haiku-4-5"; +const SLOW_MARKER = "[[stream-slowly]]"; + +export class MetricsError extends Schema.TaggedError()("MetricsError", { + message: Schema.String, +}) {} + +const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); +const decodeJson = (schema: S) => + Schema.decodeUnknownEffect(Schema.fromJsonString(schema)); +const encodeMetrics = Schema.encodeEffect(fromJsonStringPretty(ServerMetrics)); + +/** What a command printed, or none when it is missing or failed. */ +const output = (program: string, args: ReadonlyArray, cwd?: string) => + run(program, args, cwd === undefined ? {} : { cwd }).pipe( + Effect.map(({ stdout }) => stdout.trim()), + Effect.option, + ); +const powershell = (script: string) => + output("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script]); + +/** Milliseconds on a monotonic clock, for intervals only. */ +const nowMs = Effect.map(Clock.monotonicTimeNanos, (nanos) => Number(nanos) / 1e6); + +const httpServerOn = (port: number) => + NodeHttpServer.layer(() => NodeHttp.createServer(), { port, host: "127.0.0.1" }); + +interface ApiRequest { + readonly at: number; + readonly agent: boolean; + readonly stream: boolean; + readonly marker: string | undefined; +} + +const MessagesRequest = Schema.Struct({ + stream: Schema.optional(Schema.Boolean), + model: Schema.optional(Schema.String), + tools: Schema.optional(Schema.Array(Schema.Unknown)), +}); + +/** Streams a canned reply to every Messages request; a prompt holding SLOW_MARKER streams slowly. */ +const serveFakeAnthropic = Effect.fn("serverMetrics.serveFakeAnthropic")(function* () { + const requests: ApiRequest[] = []; + const app = Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + if (request.url.includes("count_tokens")) { + return HttpServerResponse.jsonUnsafe({ input_tokens: 100 }); + } + if (!request.url.startsWith("/v1/messages")) { + return HttpServerResponse.jsonUnsafe( + { type: "error", error: { type: "not_found_error" } }, + { status: 404 }, + ); + } + const raw = yield* request.text.pipe(Effect.orElseSucceed(() => "")); + const body = yield* decodeJson(MessagesRequest)(raw).pipe( + Effect.orElseSucceed((): typeof MessagesRequest.Type => ({})), + ); + const streamed = body.stream === true; + requests.push({ + at: yield* nowMs, + stream: streamed, + // Title and branch-name jobs carry only their structured-output tool; the agent carries many. + agent: streamed && (body.tools?.length ?? 0) > 1, + marker: /bench-run-(\d+)/.exec(raw)?.[0], + }); + const model = body.model ?? MODEL; + const id = `msg_bench_${requests.length}`; + if (!streamed) { + return HttpServerResponse.jsonUnsafe({ + id, + type: "message", + role: "assistant", + model, + content: [{ type: "text", text: "Bench reply" }], + stop_reason: "end_turn", + stop_sequence: null, + usage: { input_tokens: 10, output_tokens: 2 }, + }); + } + const event = (name: string, data: object) => + `event: ${name}\ndata: ${encodeJson({ type: name, ...data })}\n\n`; + const slow = raw.includes(SLOW_MARKER); + const words = slow ? 2_000 : 40; + const deltas = Stream.range(0, words - 1).pipe( + Stream.mapEffect((word) => + Effect.sleep(Duration.millis(slow ? 50 : 5)).pipe( + Effect.as( + event("content_block_delta", { + index: 0, + delta: { type: "text_delta", text: `${word ? " " : ""}word${word}` }, + }), + ), + ), + ), + ); + const events = Stream.make( + event("message_start", { + message: { + id, + type: "message", + role: "assistant", + model, + content: [], + stop_reason: null, + stop_sequence: null, + usage: { input_tokens: 100, output_tokens: 1 }, + }, + }), + event("content_block_start", { index: 0, content_block: { type: "text", text: "" } }), + ).pipe( + Stream.concat(deltas), + Stream.concat( + Stream.make( + event("content_block_stop", { index: 0 }), + event("message_delta", { + delta: { stop_reason: "end_turn", stop_sequence: null }, + usage: { output_tokens: words }, + }), + event("message_stop", {}), + ), + ), + Stream.encodeText, + ); + return HttpServerResponse.stream(events, { + contentType: "text/event-stream", + headers: { "cache-control": "no-cache" }, + }); + }); + // Each run gets its own listener, closed with the run's scope. + const context = yield* Layer.build(httpServerOn(0)); + return yield* Effect.gen(function* () { + yield* HttpServer.serveEffect(Effect.interruptible(app)); + const { address } = yield* HttpServer.HttpServer; + if (address._tag === "UnixPathAddress") { + return yield* new MetricsError({ message: "the fake API has no TCP address" }); + } + return { port: address.port, requests }; + }).pipe(Effect.provide(context)); +}); + +/** A Chrome DevTools Protocol session on the server's inspector. */ +const inspect = Effect.fn("serverMetrics.inspect")(function* (url: string) { + const socket = yield* Socket.makeWebSocket(url); + const reader = yield* socket.reader; + const writer = yield* socket.writer; + const pending = new Map< + number, + { method: string; answer: Deferred.Deferred } + >(); + const chunks: string[] = []; + let nextId = 0; + let closed = false; + const decodeMessage = decodeJson( + Schema.Struct({ + id: Schema.optional(Schema.Number), + result: Schema.optional(Schema.Unknown), + error: Schema.optional(Schema.Struct({ message: Schema.String })), + method: Schema.optional(Schema.String), + params: Schema.optional(Schema.Struct({ chunk: Schema.optional(Schema.String) })), + }), + ); + const text = new TextDecoder(); + yield* reader.pull.pipe( + Effect.flatMap((frames) => + Effect.forEach(frames, (frame) => + decodeMessage(typeof frame === "string" ? frame : text.decode(frame)).pipe( + Effect.flatMap((message) => { + if (message.id !== undefined) { + const waiting = pending.get(message.id); + pending.delete(message.id); + if (!waiting) return Effect.void; + return message.error + ? Deferred.fail( + waiting.answer, + new MetricsError({ message: `${waiting.method}: ${message.error.message}` }), + ) + : Deferred.succeed(waiting.answer, message.result); + } + if (message.method === "HeapProfiler.addHeapSnapshotChunk") { + chunks.push(message.params?.chunk ?? ""); + } + return Effect.void; + }), + Effect.ignore, + ), + ), + ), + Effect.forever, + Effect.ignore, + // A closed connection answers nothing, so every waiting call fails instead of hanging. + Effect.ensuring( + Effect.suspend(() => { + closed = true; + const waiting = [...pending.values()]; + pending.clear(); + return Effect.forEach(waiting, ({ method, answer }) => + Deferred.fail(answer, new MetricsError({ message: `${method}: the inspector closed` })), + ); + }), + ), + Effect.forkScoped, + ); + const send = Effect.fn("serverMetrics.cdp")(function* (method: string, params: object = {}) { + if (closed) return yield* new MetricsError({ message: `${method}: the inspector closed` }); + const id = ++nextId; + const answer = yield* Deferred.make(); + pending.set(id, { method, answer }); + yield* writer.write(encodeJson({ id, method, params })); + return yield* Deferred.await(answer); + }); + const decodeHeapUsage = Schema.decodeUnknownEffect(Schema.Struct({ usedSize: Schema.Number })); + const decodeEvaluated = Schema.decodeUnknownEffect( + Schema.Struct({ result: Schema.Struct({ value: Schema.Number }) }), + ); + const decodeHeapProfile = Schema.decodeUnknownEffect(Schema.Struct({ profile: HeapProfile })); + const decodeCpuProfile = Schema.decodeUnknownEffect(Schema.Struct({ profile: CpuProfile })); + return { + // getrusage keeps the switches of threads that already exited, unlike per-thread counters. + contextSwitches: send("Runtime.evaluate", { + expression: + "(() => { const u = process.resourceUsage(); return u.voluntaryContextSwitches + u.involuntaryContextSwitches; })()", + returnByValue: true, + }).pipe( + Effect.flatMap(decodeEvaluated), + Effect.map(({ result }) => result.value), + ), + heapAfterGc: Effect.gen(function* () { + yield* send("HeapProfiler.collectGarbage"); + yield* send("HeapProfiler.collectGarbage"); + return (yield* decodeHeapUsage(yield* send("Runtime.getHeapUsage"))).usedSize; + }), + profile: Effect.fn("serverMetrics.profile")(function* (seconds: number) { + yield* send("Profiler.enable"); + yield* send("Profiler.setSamplingInterval", { interval: 1_000 }); + yield* send("Profiler.start"); + yield* send("HeapProfiler.startSampling", { + samplingInterval: 32_768, + includeObjectsCollectedByMajorGC: true, + includeObjectsCollectedByMinorGC: true, + }); + yield* Effect.sleep(Duration.seconds(seconds)); + const heap = yield* send("HeapProfiler.stopSampling"); + const cpu = yield* send("Profiler.stop"); + yield* send("Profiler.disable"); + return { + summary: summarizeProfiles( + (yield* decodeCpuProfile(cpu)).profile, + (yield* decodeHeapProfile(heap)).profile, + ), + raw: { cpu, heap }, + }; + }), + snapshot: Effect.gen(function* () { + chunks.length = 0; + yield* send("HeapProfiler.takeHeapSnapshot", { reportProgress: false }); + const json = chunks.join(""); + chunks.length = 0; + return heapByConstructor(yield* decodeJson(HeapSnapshot)(json)); + }), + }; +}); + +/** CPU seconds and RSS bytes of one process; a failed or unreadable probe fails the window. */ +const sample = Effect.fn("serverMetrics.sample")(function* (pid: number) { + const platform = yield* HostProcess.Platform; + const checked = (cpuSeconds: number, rss: number, probe: string) => + Number.isFinite(cpuSeconds) && Number.isFinite(rss) + ? Effect.succeed({ cpuSeconds, rss }) + : Effect.fail(new MetricsError({ message: `could not read process ${pid}: ${probe}` })); + if (platform === "linux") { + const fs = yield* FileSystem.FileSystem; + const stat = (yield* fs.readFileString(`/proc/${pid}/stat`)).split(") ")[1]?.split(" ") ?? []; + const status = yield* fs.readFileString(`/proc/${pid}/status`); + const rss = /VmRSS:\s+(\d+)/.exec(status)?.[1]; + return yield* checked( + (Number(stat[11]) + Number(stat[12])) / 100, + rss === undefined ? Number.NaN : Number(rss) * 1024, + "/proc", + ); + } + if (platform === "win32") { + const line = yield* powershell( + `$p = Get-Process -Id ${pid}; "$($p.TotalProcessorTime.TotalSeconds) $($p.WorkingSet64)"`, + ); + const [cpu = "", rss = ""] = Option.getOrElse(line, () => "").split(/\s+/); + return yield* checked( + cpu ? Number(cpu) : Number.NaN, + rss ? Number(rss) : Number.NaN, + "Get-Process", + ); + } + const line = yield* output("ps", ["-o", "rss=,time=", "-p", `${pid}`]); + const [rss = "", time = ""] = Option.getOrElse(line, () => "") + .split(/\s+/) + .filter(Boolean); + return yield* checked(parsePsCpuTime(time), rss ? Number(rss) * 1024 : Number.NaN, "ps"); +}); + +/** Every process below `pid`. Windows needs none: taskkill /T stops the tree. */ +const descendantsOf = Effect.fn("serverMetrics.descendantsOf")(function* (pid: number) { + const platform = yield* HostProcess.Platform; + const children = new Map(); + const add = (child: number, parent: number) => + children.set(parent, [...(children.get(parent) ?? []), child]); + if (platform === "linux") { + const fs = yield* FileSystem.FileSystem; + for (const entry of yield* fs.readDirectory("/proc")) { + if (!/^\d+$/.test(entry)) continue; + const stat = yield* fs + .readFileString(`/proc/${entry}/stat`) + .pipe(Effect.orElseSucceed(() => "")); + const parent = Number(stat.split(") ")[1]?.split(" ")[1]); + if (parent) add(Number(entry), parent); + } + } else if (platform === "darwin") { + const table = yield* output("ps", ["-A", "-o", "pid=,ppid="]); + for (const line of Option.getOrElse(table, () => "").split("\n")) { + const [child, parent] = line.trim().split(/\s+/).map(Number); + if (child && parent) add(child, parent); + } + } else return []; + const found: number[] = []; + const pending = [pid]; + for (let next = pending.pop(); next !== undefined; next = pending.pop()) { + for (const child of children.get(next) ?? []) { + found.push(child); + pending.push(child); + } + } + return found; +}); + +interface Environment { + readonly home: string; + readonly apiPort: number; + readonly requests: ReadonlyArray; + readonly noAgentScope: boolean; + readonly serverDir: string; +} + +/** A free loopback port: bind 0, read it, let it go. */ +const freePort = Effect.scoped( + Effect.gen(function* () { + const context = yield* Layer.build(httpServerOn(0)); + const { address } = Context.get(context, HttpServer.HttpServer); + return address._tag === "UnixPathAddress" ? 0 : address.port; + }), +); + +/** A fresh server with its own base dir and git project, stopped when the scope closes. */ +const startServer = Effect.fn("serverMetrics.startServer")(function* ( + environment: Environment, + name: string, +) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const http = yield* HttpClient.HttpClient; + const platform = yield* HostProcess.Platform; + const node = yield* HostProcess.ExecutablePath; + const hostEnvironment = yield* HostProcess.Environment; + const directory = yield* fs.makeTempDirectory({ + directory: environment.home, + prefix: `${name}-`, + }); + const project = path.join(directory, "project"); + yield* fs.makeDirectory(project); + yield* fs.writeFileString(path.join(project, "README.md"), "# bench\n"); + for (const args of [ + ["init", "-q", "-b", "main"], + ["add", "."], + ["-c", "user.email=bench@t3.codes", "-c", "user.name=bench", "commit", "-qm", "init"], + ]) { + yield* run("git", args, { cwd: project }); + } + const baseDir = path.join(directory, "base"); + // Branch names come from Claude too, so a worktree launch's naming call reaches the fake API. + yield* fs.makeDirectory(path.join(baseDir, "userdata"), { recursive: true }); + yield* fs.writeFileString( + path.join(baseDir, "userdata/settings.json"), + encodeJson({ textGenerationModelSelection: { instanceId: "claudeAgent", model: MODEL } }), + ); + const dropped = new Set([ + "ANTHROPIC_AUTH_TOKEN", + "T3CODE_HOME", + "CLAUDE_CONFIG_DIR", + ...(environment.noAgentScope ? ["XDG_RUNTIME_DIR"] : []), + ]); + const env: Record = { + ...Object.fromEntries( + Object.entries(hostEnvironment).filter( + (entry): entry is [string, string] => entry[1] !== undefined && !dropped.has(entry[0]), + ), + ), + HOME: environment.home, + USERPROFILE: environment.home, + ANTHROPIC_BASE_URL: `http://127.0.0.1:${environment.apiPort}`, + ANTHROPIC_API_KEY: "sk-bench", + CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", + OTEL_SDK_DISABLED: "true", + T3CODE_DEV_SEED: "0", + }; + const port = yield* freePort; + const started = yield* nowMs; + const child = yield* spawner.spawn( + ChildProcess.make( + node, + [ + "--inspect=127.0.0.1:0", + "src/bin.ts", + "serve", + "--base-dir", + baseDir, + "--port", + `${port}`, + "--host", + "127.0.0.1", + project, + ], + { + cwd: environment.serverDir, + env, + extendEnv: false, + // A server that ignores SIGTERM still stops, so cleanup always reaches the temp dir. + forceKillAfter: Duration.seconds(10), + stdin: "ignore", + stdout: "ignore", + stderr: "pipe", + }, + ), + ); + const pid = Number(child.pid); + const stderr = yield* Ref.make(""); + yield* child.stderr.pipe( + Stream.decodeText(), + Stream.runForEach((chunk) => Ref.update(stderr, (text) => (text + chunk).slice(-8_000))), + Effect.ignore, + Effect.forkScoped, + ); + + yield* Effect.addFinalizer(() => + Effect.gen(function* () { + const spawned = yield* descendantsOf(pid).pipe(Effect.orElseSucceed(() => [])); + if (platform === "win32") yield* output("taskkill", ["/PID", `${pid}`, "/T", "/F"]); + else + yield* child + .kill({ killSignal: "SIGTERM", forceKillAfter: Duration.seconds(10) }) + .pipe(Effect.timeout(Duration.seconds(15)), Effect.ignore); + yield* child.exitCode.pipe(Effect.timeout(Duration.seconds(10)), Effect.ignore); + if (spawned.length > 0) yield* output("kill", ["-9", ...spawned.map(String)]); + // Windows keeps a file locked for a moment after its process exits. + yield* fs + .remove(directory, { recursive: true }) + .pipe(Effect.retry({ schedule: Schedule.spaced(Duration.millis(500)), times: 20 })); + }).pipe(Effect.ignore), + ); + + const readyMs = yield* http.get(`http://127.0.0.1:${port}/`).pipe( + Effect.timeout(Duration.seconds(1)), + Effect.retry({ schedule: Schedule.spaced(Duration.millis(100)), times: 600 }), + Effect.andThen(nowMs), + Effect.map((now) => Math.round(now - started)), + Effect.catch(() => + Effect.flatMap( + Ref.get(stderr), + (text) => new MetricsError({ message: `server never answered:\n${text}` }), + ), + ), + ); + const inspectorUrl = /ws:\/\/127\.0\.0\.1:\d+\/[\w-]+/.exec(yield* Ref.get(stderr))?.[0]; + if (!inspectorUrl) return yield* new MetricsError({ message: "no inspector URL on stderr" }); + const devtools = yield* inspect(inspectorUrl); + + const cli = (args: ReadonlyArray) => + run(node, ["src/bin.ts", ...args, "--base-dir", baseDir], { + cwd: environment.serverDir, + env, + allowExit: [0, 1, 2], + }); + const added = yield* cli(["project", "add", project]); + if (added.exitCode !== 0) { + return yield* new MetricsError({ + message: `project add failed: ${added.stderr.trim() || added.stdout.trim()}`, + }); + } + + // Spawning PowerShell for each sample costs a few hundred ms of the machine's CPU. + const sampleEvery = Duration.millis(platform === "win32" ? 5_000 : 1_000); + const measure = Effect.fn("serverMetrics.measure")(function* (seconds: number) { + // Each counter is divided by the time between its own two reads; a CIM probe can take seconds. + // Windows reports no context switches through getrusage, so wakeups are unknown there. + const countSwitches = platform === "win32" ? Effect.succeed(null) : devtools.contextSwitches; + // A probe can take seconds (CIM on Windows), so each read is timed at its midpoint. + const timed = Effect.fn("serverMetrics.timedRead")(function* ( + read: Effect.Effect, + ) { + const before = yield* nowMs; + const value = yield* read; + return { value, at: (before + (yield* nowMs)) / 2 }; + }); + const firstSwitches = yield* timed(countSwitches); + const firstSample = yield* timed(sample(pid)); + const first = firstSample.value; + const start = firstSample.at; + let rssPeak = first.rss; + while ((yield* nowMs) - start < seconds * 1_000) { + yield* Effect.sleep(sampleEvery); + rssPeak = Math.max(rssPeak, (yield* sample(pid)).rss); + } + const lastSample = yield* timed(sample(pid)); + const last = lastSample.value; + const cpuElapsed = (lastSample.at - start) / 1_000; + const lastSwitches = yield* timed(countSwitches); + const switchesElapsed = (lastSwitches.at - firstSwitches.at) / 1_000; + const switches = + firstSwitches.value === null || lastSwitches.value === null + ? null + : lastSwitches.value - firstSwitches.value; + const heap = yield* devtools.heapAfterGc; + const window: Window = { + cpuPct: round(((last.cpuSeconds - first.cpuSeconds) / cpuElapsed) * 100), + wakeupsPerSec: switches === null ? null : round(switches / switchesElapsed), + rssPeakMB: Math.round(Math.max(rssPeak, last.rss) / 1e6), + rssMB: Math.round((yield* sample(pid)).rss / 1e6), + heapAfterGcMB: round(heap / 1e6), + }; + return window; + }); + + return { + readyMs, + measure, + profile: devtools.profile, + snapshot: devtools.snapshot, + threadStart: (message: string, extra: ReadonlyArray = []) => + cli([ + "thread", + "start", + "--provider", + "claudeAgent", + "--model", + MODEL, + ...extra, + project, + message, + ]), + threadSend: (threadId: string, message: string) => + cli(["thread", "send", "--wait", threadId, message]), + }; +}); + +type Server = Effect.Success>; + +const firstWord = Effect.fn("serverMetrics.firstWord")(function* ( + environment: Environment, + server: Server, + runs: number, + worktree: boolean, +) { + const toRequest: number[] = []; + const toDone: number[] = []; + for (let index = 0; index < runs; index++) { + const marker = `bench-run-${worktree ? 1000 + index : index}`; + const started = yield* nowMs; + const result = yield* server.threadStart(`Say hello. ${marker}`, [ + "--wait", + ...(worktree ? ["--worktree", "main"] : []), + ]); + const done = (yield* nowMs) - started; + if (result.exitCode !== 0) { + return yield* new MetricsError({ + message: `thread start failed: ${result.stderr.trim() || result.stdout.trim()}`, + }); + } + const request = environment.requests.find( + (entry) => entry.agent && entry.marker === marker && entry.at >= started, + ); + if (!request) { + return yield* new MetricsError({ message: `the agent request for ${marker} never arrived` }); + } + toRequest.push(request.at - started); + toDone.push(done); + } + const result: FirstWord = { toRequestMs: spread(toRequest), toDoneMs: spread(toDone) }; + return result; +}); + +/** Starts threads that each answer once, and returns their ids. */ +const openThreads = Effect.fn("serverMetrics.openThreads")(function* ( + server: Server, + from: number, + count: number, +) { + const answers = yield* Effect.forEach( + Array.from({ length: count }, (_, index) => from + index), + (index) => server.threadStart(`Say hello ${index}.`, ["--wait"]), + { concurrency: "unbounded" }, + ); + const failed = answers.find((answer) => answer.exitCode !== 0); + if (failed) { + return yield* new MetricsError({ + message: `a thread failed to answer: ${failed.stderr.trim() || failed.stdout.trim()}`, + }); + } + // Without --json, `thread start` prints the new thread's id to stderr, older releases too. + const ids = answers.map((answer) => /^Thread (\S+)$/m.exec(answer.stderr)?.[1]); + if (ids.some((id) => id === undefined)) { + return yield* new MetricsError({ message: "thread start printed no thread id" }); + } + return ids.filter((id) => id !== undefined); +}); + +const SCENARIOS = ["startup", "rest", "firstWord", "quiet", "streaming"] as const; + +interface RunOptions { + readonly checkout: string; + readonly noAgentScope: boolean; + readonly runs: number; + readonly threads: ReadonlyArray; + readonly only: ReadonlyArray; + readonly soakMinutes: number; + /** Where full CPU and allocation profiles go; none are written without it. */ + readonly profileDir: string | undefined; +} + +/** One pass: startup, rest and firstWord share a server; quiet, streaming and soak get their own. */ +const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOptions) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-server-metrics-" }); + const api = yield* serveFakeAnthropic(); + const environment: Environment = { + home, + apiPort: api.port, + requests: api.requests, + noAgentScope: options.noAgentScope, + serverDir: path.join(options.checkout, "apps/server"), + }; + const wanted = (scenario: string) => options.only.length === 0 || options.only.includes(scenario); + const measured: { -readonly [K in keyof Measured]: Measured[K] } = {}; + const profiles: Record = {}; + let soakHeapGrowth: ReturnType | undefined; + const withServer = (name: string, body: (server: Server) => Effect.Effect) => + Effect.scoped(Effect.flatMap(startServer(environment, name), body)); + const profile = Effect.fn("serverMetrics.saveProfile")(function* (server: Server, name: string) { + const { summary, raw } = yield* server.profile(20); + profiles[name] = summary; + if (options.profileDir === undefined) return; + yield* fs.makeDirectory(options.profileDir, { recursive: true }); + yield* fs.writeFileString( + path.join(options.profileDir, `${name}.cpuprofile`), + encodeJson(raw.cpu), + ); + yield* fs.writeFileString( + path.join(options.profileDir, `${name}.heapprofile`), + encodeJson(raw.heap), + ); + }); + + if (wanted("startup") || wanted("rest") || wanted("firstWord")) { + yield* withServer("rest", (server) => + Effect.gen(function* () { + measured.startup = { readyMs: server.readyMs }; + if (wanted("rest")) { + yield* Effect.sleep(Duration.seconds(15)); + measured.rest = yield* server.measure(30); + } + if (wanted("firstWord")) { + measured.firstWord = { + inPlace: yield* firstWord(environment, server, options.runs, false), + worktree: yield* firstWord(environment, server, options.runs, true), + }; + } + }), + ); + } + if (wanted("quiet")) { + yield* withServer("quiet", (server) => + Effect.gen(function* () { + const points: Array<{ threads: number; window: Window }> = []; + let open = 0; + for (const threads of options.threads) { + if (threads > open) yield* openThreads(server, open, threads - open); + open = Math.max(open, threads); + yield* Effect.sleep(Duration.seconds(15)); + points.push({ threads, window: yield* server.measure(30) }); + } + const last = points.at(-1); + if (last) measured.quiet = last.window; + // The first thread also loads the provider's modules once, so the fit leaves out 0 threads. + const withThreads = points.filter(({ threads }) => threads > 0); + const fitted = withThreads.length >= 2 ? withThreads : points; + const fit = (pick: (window: Window) => number) => + round(slope(fitted.map(({ threads, window }) => [threads, pick(window)])), 3); + measured.scaling = { + heapMBPerThread: fit((window) => window.heapAfterGcMB), + rssMBPerThread: fit((window) => window.rssMB), + cpuPctPerThread: fit((window) => window.cpuPct), + wakeupsPerThread: points.every(({ window }) => window.wakeupsPerSec !== null) + ? fit((window) => window.wakeupsPerSec ?? 0) + : null, + points: points.map(({ threads, window }) => [ + threads, + window.cpuPct, + window.wakeupsPerSec, + window.rssMB, + window.heapAfterGcMB, + ]), + }; + yield* profile(server, "quiet"); + }), + ); + } + if (wanted("streaming")) { + yield* withServer("streaming", (server) => + Effect.gen(function* () { + // Earlier scenarios share the fake API, so only this launch's requests count. + const markers = [0, 1, 2, 3, 4].map((index) => `bench-run-${9_000 + index}`); + const launchedAt = yield* nowMs; + const started = yield* Effect.forEach( + markers, + (marker) => server.threadStart(`Write a long answer. ${SLOW_MARKER} ${marker}`), + { concurrency: "unbounded" }, + ); + if (started.some((answer) => answer.exitCode !== 0)) { + return yield* new MetricsError({ message: "streaming start failed" }); + } + const streaming = () => + new Set( + api.requests + .filter((request) => request.agent && request.stream && request.at >= launchedAt) + .map((request) => request.marker), + ); + for (let attempt = 0; attempt < 300; attempt++) { + if (markers.every((marker) => streaming().has(marker))) break; + yield* Effect.sleep(Duration.millis(100)); + } + if (!markers.every((marker) => streaming().has(marker))) { + return yield* new MetricsError({ message: "fewer than 5 replies started streaming" }); + } + yield* Effect.sleep(Duration.seconds(5)); + measured.streaming = yield* server.measure(60); + yield* profile(server, "streaming"); + }), + ); + } + if (options.soakMinutes > 0) { + yield* withServer("soak", (server) => + Effect.gen(function* () { + const threads = yield* openThreads(server, 0, 10); + yield* Effect.sleep(Duration.seconds(60)); + // The snapshot inflates RSS once, so the slopes start after it. + const before = yield* server.snapshot; + const samples: Array<{ hours: number; window: Window }> = []; + const start = yield* nowMs; + const elapsed = Effect.map(nowMs, (now) => now - start); + const takeSample = Effect.gen(function* () { + samples.push({ hours: (yield* elapsed) / 3_600_000, window: yield* server.measure(5) }); + }); + let nextSample = 0; + for (let turn = 0; (yield* elapsed) < options.soakMinutes * 60_000; turn++) { + if ((yield* elapsed) >= nextSample) { + yield* takeSample; + nextSample += 120_000; + } + const threadId = + threads[yield* Random.nextIntBetween(0, threads.length, { halfOpen: true })]; + if (threadId === undefined) + return yield* new MetricsError({ message: "no soak threads" }); + const sent = yield* server.threadSend(threadId, `Short reply ${turn}.`); + if (sent.exitCode !== 0) { + return yield* new MetricsError({ + message: `soak turn ${turn} on ${threadId} failed: ${sent.stderr.trim() || sent.stdout.trim()}`, + }); + } + yield* Effect.sleep(Duration.millis(Math.max(0, (turn + 1) * 30_000 - (yield* elapsed)))); + } + yield* takeSample; + const perHour = (pick: (window: Window) => number) => + round(slope(samples.map(({ hours, window }) => [hours, pick(window)]))); + measured.soak = { + minutes: options.soakMinutes, + heapMBPerHour: perHour((window) => window.heapAfterGcMB), + rssMBPerHour: perHour((window) => window.rssMB), + }; + soakHeapGrowth = heapGrowth(before, yield* server.snapshot); + }), + ); + } + return { measured: measured as Measured, profiles, soakHeapGrowth }; +}, Effect.scoped); + +const machineLoad = Effect.gen(function* () { + const platform = yield* HostProcess.Platform; + if (platform === "win32") { + return yield* powershell( + "(Get-CimInstance Win32_Processor | Measure-Object LoadPercentage -Average).Average", + ); + } + if (platform === "linux") { + const fs = yield* FileSystem.FileSystem; + const load = yield* fs.readFileString("/proc/loadavg").pipe(Effect.option); + return Option.map(load, (text) => text.split(" ").slice(0, 3).join(" ")); + } + return yield* output("sysctl", ["-n", "vm.loadavg"]); +}).pipe( + Effect.map((load) => + Option.getOrNull(Option.map(load, (text) => text.replace(/[{}]/g, "").trim())), + ), +); + +const metaFor = Effect.fn("serverMetrics.metaFor")(function* (options: RunOptions) { + const platform = yield* HostProcess.Platform; + const architecture = yield* HostProcess.Architecture; + const environment = yield* HostProcess.Environment; + const node = yield* HostProcess.ExecutablePath; + const claude = yield* output("claude", ["--version"]); + if (Option.isNone(claude)) { + return yield* new MetricsError({ message: "The real `claude` CLI must be on PATH." }); + } + if (options.noAgentScope && platform !== "linux") { + return yield* new MetricsError({ + message: "--no-agent-scope is Linux only; other platforms never have an agent scope.", + }); + } + const cpus = + platform === "win32" + ? Option.fromNullishOr(environment.NUMBER_OF_PROCESSORS) + : yield* output("getconf", ["_NPROCESSORS_ONLN"]); + return { + platform: `${platform}-${architecture}`, + cpus: Option.getOrNull(Option.map(cpus, Number)), + node: Option.getOrNull(yield* output(node, ["--version"])), + claude: claude.value, + commit: Option.getOrNull( + yield* output("git", ["rev-parse", "--short=12", "HEAD"], options.checkout), + ), + noAgentScope: options.noAgentScope, + agentScope: + platform === "linux" && + !options.noAgentScope && + !!environment.XDG_RUNTIME_DIR && + Option.isSome(yield* output("sh", ["-c", "command -v systemd-run"])), + loadBefore: yield* machineLoad, + measuredAt: DateTime.formatIso(yield* DateTime.now), + }; +}); + +const writeMetrics = Effect.fn("serverMetrics.writeMetrics")(function* ( + out: Option.Option, + metrics: ServerMetrics, +) { + const fs = yield* FileSystem.FileSystem; + const json = yield* encodeMetrics(metrics); + if (Option.isSome(out)) yield* fs.writeFileString(out.value, `${json}\n`); + else yield* Console.log(json); +}); + +/** Prints the comparison and sets exit code 1 when a metric got worse. */ +const report = Effect.fn("serverMetrics.report")(function* ( + before: ServerMetrics, + after: ServerMetrics, + threshold: number, +) { + const { table, regressed, improved, compared } = compareMetrics(before, after, threshold); + yield* Console.log(table); + if (compared === 0) { + return yield* new MetricsError({ + message: "the two files share no metric, so nothing was compared", + }); + } + if (improved.length) yield* Console.error(`Better: ${improved.join(", ")}`); + if (regressed.length === 0) return; + yield* Console.error(`Worse: ${regressed.join(", ")}`); + yield* Effect.sync(() => { + process.exitCode = 1; + }); +}); + +const thresholdFlag = Flag.Int("threshold").pipe( + Flag.withDescription("Percent a metric must move, past its noise floor, to count."), + Flag.withDefault(10), +); +const runFlags = { + noAgentScope: Flag.Boolean("no-agent-scope").pipe( + Flag.withAlias("mac-path"), + Flag.withDefault(false), + Flag.withDescription( + "Linux only: start the server without XDG_RUNTIME_DIR, so it takes the no-agent-scope path macOS and Windows always take.", + ), + ), + runs: Flag.Int("runs").pipe( + Flag.withSchema(PositiveInt), + Flag.withDescription("firstWord runs in each variant."), + Flag.withDefault(5), + ), + threads: Flag.String("threads").pipe( + Flag.withDescription("Open thread counts the quiet scenario measures."), + Flag.withDefault("0,5,10,20"), + ), + only: Flag.String("only").pipe( + Flag.withDescription(`Scenarios to run, comma separated: ${SCENARIOS.join(", ")}.`), + Flag.optional, + ), + soak: Flag.Int("soak").pipe( + Flag.withSchema(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))), + Flag.withDescription( + "Minutes of soak: 10 threads, a short turn every 30 s; heap and RSS slopes per hour and the constructors that grew. Runs alone unless --only names more.", + ), + Flag.withDefault(0), + ), +}; +interface RunFlags { + readonly noAgentScope: boolean; + readonly runs: number; + readonly threads: string; + readonly only: Option.Option; + readonly soak: number; +} + +const toRunOptions = Effect.fn("serverMetrics.toRunOptions")(function* ( + flags: RunFlags, + checkout: string, + profileDir: string | undefined, +) { + const path = yield* Path.Path; + const selection = parseRunSelection({ + only: Option.getOrElse(flags.only, () => ""), + threads: flags.threads, + soak: flags.soak, + scenarios: SCENARIOS, + }); + if ("error" in selection) return yield* new MetricsError({ message: selection.error }); + const { only, threads } = selection; + const options: RunOptions = { + checkout: path.resolve(checkout), + noAgentScope: flags.noAgentScope, + runs: flags.runs, + threads, + only, + soakMinutes: flags.soak, + profileDir, + }; + return options; +}); + +const runCommand = Command.make( + "run", + { + ...runFlags, + out: Flag.String("out").pipe(Flag.withDescription("JSON file to write."), Flag.optional), + checkout: Flag.String("checkout").pipe( + Flag.withDescription("Checkout whose server to measure, with dependencies installed."), + Flag.optional, + ), + repeat: Flag.Int("repeat").pipe( + Flag.withSchema(PositiveInt), + Flag.withDescription("Runs to record in one file."), + Flag.withDefault(1), + ), + }, + Effect.fn("serverMetrics.run")(function* (input) { + const path = yield* Path.Path; + const checkout = Option.getOrElse(input.checkout, () => + path.resolve(import.meta.dirname, ".."), + ); + const profileDir = Option.getOrUndefined( + Option.map(input.out, (out) => `${out.replace(/\.json$/, "")}-profiles`), + ); + if (input.repeat < 1) + return yield* new MetricsError({ message: "--repeat must be at least 1" }); + const options = yield* toRunOptions(input, checkout, profileDir); + const meta = yield* metaFor(options); + const runs: Measured[] = []; + let last: Effect.Success> | undefined; + for (let index = 0; index < input.repeat; index++) { + last = yield* runOnce(options); + runs.push(last.measured); + } + yield* writeMetrics(input.out, { + meta: { ...meta, loadAfter: yield* machineLoad }, + runs, + ...(last ? { profiles: last.profiles } : {}), + ...(last?.soakHeapGrowth ? { soakHeapGrowth: last.soakHeapGrowth } : {}), + }); + }), +).pipe( + Command.withDescription( + "Measure a checkout's server: startup, rest and first word on one server, then quiet threads (with their cost per thread), streaming and an optional soak on servers of their own. Needs the real claude CLI on PATH; on Windows the native claude.exe from claude.ai/install.ps1, since an npm claude.cmd shim cannot be started without a shell.", + ), +); + +const abCommand = Command.make( + "ab", + { + ...runFlags, + checkoutA: Argument.String("checkout-a").pipe(Argument.withDescription("Baseline checkout.")), + checkoutB: Argument.String("checkout-b").pipe(Argument.withDescription("Candidate checkout.")), + rounds: Flag.Int("rounds").pipe( + Flag.withSchema(PositiveInt), + Flag.withDescription("Rounds; each runs A and B once, alternating which goes first."), + Flag.withDefault(3), + ), + outDir: Flag.String("out-dir").pipe( + Flag.withDescription("Directory for a.json and b.json."), + Flag.withDefault("server-metrics-ab"), + ), + threshold: thresholdFlag, + }, + Effect.fn("serverMetrics.ab")(function* (input) { + if (input.rounds < 1) + return yield* new MetricsError({ message: "--rounds must be at least 1" }); + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const outDir = path.resolve(input.outDir); + yield* fs.makeDirectory(outDir, { recursive: true }); + const sides = [ + yield* toRunOptions(input, input.checkoutA, undefined), + yield* toRunOptions(input, input.checkoutB, undefined), + ] as const; + const metas = [yield* metaFor(sides[0]), yield* metaFor(sides[1])] as const; + const runs: [Measured[], Measured[]] = [[], []]; + for (let round = 0; round < input.rounds; round++) { + // A B, then B A, so a drift in machine load lands on both sides. + for (const side of round % 2 === 0 ? ([0, 1] as const) : ([1, 0] as const)) { + yield* Console.error(`round ${round + 1}/${input.rounds}: ${side === 0 ? "A" : "B"}`); + runs[side].push((yield* runOnce(sides[side])).measured); + } + } + const loadAfter = yield* machineLoad; + const before: ServerMetrics = { meta: { ...metas[0], loadAfter }, runs: runs[0] }; + const after: ServerMetrics = { meta: { ...metas[1], loadAfter }, runs: runs[1] }; + yield* writeMetrics(Option.some(path.join(outDir, "a.json")), before); + yield* writeMetrics(Option.some(path.join(outDir, "b.json")), after); + yield* report(before, after, input.threshold); + }), +).pipe( + Command.withDescription( + "Run two checkouts alternately on this machine and compare them. Each needs its dependencies installed; the harness comes from this script, so an old release works too.", + ), +); + +const compareCommand = Command.make( + "compare", + { + before: Argument.String("before").pipe(Argument.withDescription("Baseline JSON.")), + after: Argument.String("after").pipe(Argument.withDescription("Candidate JSON.")), + threshold: thresholdFlag, + }, + Effect.fn("serverMetrics.compare")(function* (input) { + const fs = yield* FileSystem.FileSystem; + const read = (file: string) => + fs.readFileString(file).pipe(Effect.flatMap(decodeJson(ServerMetrics))); + yield* report(yield* read(input.before), yield* read(input.after), input.threshold); + }), +).pipe( + Command.withDescription( + "Markdown table of two result files, lower is better. With 2+ runs a side, a metric counts only when the 95% bootstrap interval of the median difference clears the threshold and its noise floor (1 CPU point, 20 wakeups/s, 15 MB, 300 ms; per thread 2 MB or 0.2 CPU points). Exits 1 on a regression.", + ), +); + +const serverMetricsCommand = Command.make("server-metrics").pipe( + Command.withDescription( + "Measure the server process against a fake Anthropic API and the real claude CLI, on Linux, macOS and Windows.", + ), + Command.withSubcommands([runCommand, abCommand, compareCommand]), +); + +if (import.meta.main) { + Command.run(serverMetricsCommand, { version: "0.0.0" }).pipe( + Effect.provide( + Layer.mergeAll( + NodeServices.layer, + NodeHttpClient.layerUndici, + NodeSocket.layerWebSocketConstructor, + ), + ), + NodeRuntime.runMain, + ); +} From 3c84f4b1c4f2fff49f731b9bc863e9b14bae2e0e Mon Sep 17 00:00:00 2001 From: Pulsar Programmer Date: Mon, 23 Nov 2026 00:17:29 -0500 Subject: [PATCH 274/324] fix(ssh): accept Node versions with build metadata (#41171) --- packages/shared/src/semver.test.ts | 3 +++ packages/shared/src/semver.ts | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/shared/src/semver.test.ts b/packages/shared/src/semver.test.ts index 0dac4f2ab9e0d..b5a3935ebc208 100644 --- a/packages/shared/src/semver.test.ts +++ b/packages/shared/src/semver.test.ts @@ -94,6 +94,9 @@ describe("semver helpers", () => { expect(recreated("0.5.0", "^0")).toBe(true); expect(recreated("0.0.4", "^0.0")).toBe(true); expect(recreated("24.10.0", ">=24.10")).toBe(true); + expect(recreated("24.10.0+vendor.1", ">=24.10")).toBe(true); + expect(recreated("24.10.0+vendor..1", ">=24.10")).toBe(false); + expect(recreated("24.9.9+vendor.1", ">=24.10")).toBe(false); expect(recreated("24.9.9", ">=24.10")).toBe(false); }); }); diff --git a/packages/shared/src/semver.ts b/packages/shared/src/semver.ts index 0a982b9465566..4b6166f40c403 100644 --- a/packages/shared/src/semver.ts +++ b/packages/shared/src/semver.ts @@ -145,7 +145,7 @@ export const satisfiesSemverRange: (rawVersion: string, range: string) => boolea function satisfiesSemverRange(rawVersion, range) { const normalizedVersion = String(rawVersion).trim().replace(/^v/, ""); const versionMatch = normalizedVersion.match( - /^(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:-[0-9A-Za-z.-]+)?$/, + /^(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/, ); if (!versionMatch) { return false; From ad621cc20e9f1712b0e68905ae1949ca36828bf1 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 21:19:15 -0800 Subject: [PATCH 275/324] fix(server): merge-back refuses an archived or deleted parent (#41229) --- .../src/orchestration-v2/Orchestrator.ts | 14 ++++++++++ .../ThreadFork.execution.test.ts | 28 +++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 8a546270a0515..ae06077992d0a 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -6170,6 +6170,20 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio cause: `Thread ${command.sourceThreadId} is not a fork of ${command.targetThreadId}.`, }); } + if (sourceProjection.thread.deletedAt !== null) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Thread ${command.sourceThreadId} was deleted.`, + }); + } + if (targetProjection.thread.deletedAt !== null || targetProjection.thread.archivedAt !== null) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Thread ${command.targetThreadId} is archived or deleted.`, + }); + } // Queued runs cannot consume merge-back context. Refuse under the target's // command lock before a pending transfer can block its ordinary messages. if (targetProjection.runs.some((run) => isActiveRun(run) || run.status === "queued")) { diff --git a/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts b/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts index 3466fed79f502..457a98487c69d 100644 --- a/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts +++ b/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts @@ -1724,6 +1724,34 @@ it.effect("merge-back rejects a second fork's context until the first is consume [first.threadId, "pending"], ], ); + + // Archiving or deleting a parent cascades only to side chats, so the full fork can still merge back. + const mergeNestedInto = (commandId: string) => + orchestrator + .dispatch({ + type: "thread.merge_back", + commandId: CommandId.make(commandId), + sourceThreadId: nested.threadId, + targetThreadId: first.threadId, + sourcePoint: { type: "run", runId: nestedRunId }, + createdBy: "user", + creationSource: "web", + }) + .pipe(Effect.flip); + yield* orchestrator.dispatch({ + type: "thread.archive", + commandId: CommandId.make("merge-back-guard-archive-first"), + threadId: first.threadId, + }); + const intoArchived = yield* mergeNestedInto("merge-back-guard-into-archived"); + assert.equal(intoArchived._tag, "OrchestratorDispatchError"); + yield* orchestrator.dispatch({ + type: "thread.delete", + commandId: CommandId.make("merge-back-guard-delete-first"), + threadId: first.threadId, + }); + const intoDeleted = yield* mergeNestedInto("merge-back-guard-into-deleted"); + assert.equal(intoDeleted._tag, "OrchestratorDispatchError"); }).pipe(Effect.provide(forkCases[0]!.layer)), ); From df93cabbcc20148aef4565e9b18adef942f39eb3 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 21:20:20 -0800 Subject: [PATCH 276/324] fix(contracts): ForwardCompatibleOptional drops the key for values it cannot read (#41236) --- packages/contracts/src/baseSchemas.test.ts | 10 ++++++++++ packages/contracts/src/baseSchemas.ts | 21 +++++++++++---------- 2 files changed, 21 insertions(+), 10 deletions(-) diff --git a/packages/contracts/src/baseSchemas.test.ts b/packages/contracts/src/baseSchemas.test.ts index beae3731400bc..e6940cc85a76d 100644 --- a/packages/contracts/src/baseSchemas.test.ts +++ b/packages/contracts/src/baseSchemas.test.ts @@ -5,6 +5,7 @@ import * as Schema from "effect/Schema"; import { ForwardCompatibleArray, + ForwardCompatibleOptional, ForwardCompatibleUnion, ForwardCompatibleUnionArray, isUnknownUnionMember, @@ -62,6 +63,15 @@ describe("ForwardCompatibleArray", () => { }); }); +describe("ForwardCompatibleOptional", () => { + const Settings = Schema.Struct({ mode: ForwardCompatibleOptional(Schema.Literals(["a", "b"])) }); + const encodeSettings = Schema.encodeUnknownSync(Schema.toCodecJson(Settings)); + + it("encodes back to JSON after dropping a value it cannot read", () => { + expect(encodeSettings(fromWire(Settings)({ mode: "future" }))).toEqual({}); + }); +}); + describe("ForwardCompatibleUnion", () => { const decode = fromWire(ForwardCompatibleUnion(members, "kind")); diff --git a/packages/contracts/src/baseSchemas.ts b/packages/contracts/src/baseSchemas.ts index 30df0d53c537f..d8137fc8ca9ec 100644 --- a/packages/contracts/src/baseSchemas.ts +++ b/packages/contracts/src/baseSchemas.ts @@ -47,16 +47,17 @@ export type IsoDateTime = typeof IsoDateTime.Type; export const ForwardCompatibleOptional = (value: Value) => { const decodeValue = Schema.decodeUnknownOption(value as never); - return Schema.optionalKey( - Schema.Unknown.pipe( - Schema.decodeTo( - Schema.UndefinedOr(value), - SchemaTransformation.transform({ - decode: (raw) => - Option.isSome(decodeValue(raw)) ? (raw as Value["Encoded"]) : undefined, - encode: (raw) => raw, - }), - ), + // Unreadable values drop the key: an own undefined property is not JSON and fails RPC encoding. + return Schema.optionalKey(Schema.Unknown).pipe( + Schema.decodeTo( + Schema.optionalKey(Schema.UndefinedOr(value)), + SchemaTransformation.transformOptional({ + decode: (raw) => + Option.isSome(raw) && Option.isSome(decodeValue(raw.value)) + ? Option.some(raw.value as Value["Encoded"]) + : Option.none(), + encode: (raw) => (Option.isSome(raw) && raw.value !== undefined ? raw : Option.none()), + }), ), ); }; From 91c6ecce42cfd8bd04f4ba87b1b9caaaa05b488c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 21:24:54 -0800 Subject: [PATCH 277/324] fix(acp): agent terminals keep 1.25 MiB of output, not 16 MiB (#41243) Co-authored-by: Claude Opus 5.5 --- packages/provider-acp/src/server/adapter.ts | 4 +-- .../src/server/runtimeModel.test.ts | 26 ++++++++++++++++--- .../provider-acp/src/server/runtimeModel.ts | 9 ++++--- 3 files changed, 29 insertions(+), 10 deletions(-) diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index d4af4aa10ddd5..8905317d20f5f 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -80,6 +80,7 @@ import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderS import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession"; import { applyAcpAgentTerminalUpdate, + MAX_AGENT_TERMINAL_OUTPUT_CHARS, acpContentBlockDisplayText, embeddedTerminalIdsFromSessionUpdate, extractMcpToolCallIdentity, @@ -2008,9 +2009,6 @@ const emptySnapshotState = (): SnapshotMessageState => ({ const ACP_STOP_CONFIRM_TIMEOUT_MS = 10_000; const TOOL_UPDATE_PERSIST_EVERY = 10; -// CommandOutputHub reads the last 256 KiB; retain more so its display cut stays unchanged. -const MAX_AGENT_TERMINAL_OUTPUT_CHARS = 320 * 1024; - // Agents can resend whole calls while streaming arguments. function shouldPersistToolUpdate( context: Pick, diff --git a/packages/provider-acp/src/server/runtimeModel.test.ts b/packages/provider-acp/src/server/runtimeModel.test.ts index ee4a9ca2aa57a..a4fe10a11efe2 100644 --- a/packages/provider-acp/src/server/runtimeModel.test.ts +++ b/packages/provider-acp/src/server/runtimeModel.test.ts @@ -1207,9 +1207,27 @@ describe("AcpRuntimeModel", () => { expect(second.pendingOutputBytes).toBeUndefined(); }); - it("trims full ACP terminal output by a further 1 MiB at a UTF-8 boundary", () => { - const cap = 16 * 1024 * 1024; - const step = 1024 * 1024; + it("retains only the terminal output tail the projection reads", () => { + const projectedChars = 320 * 1024; + let state: ReturnType | undefined; + let full = ""; + for (let index = 0; index < 64; index += 1) { + const text = `${index % 10}`.repeat(64 * 1024 - 1) + "é"; + full += text; + state = applyAcpAgentTerminalUpdate(state, { + sessionUpdate: "terminal_output_chunk", + terminalId: "terminal-tail", + data: Buffer.from(text).toString("base64"), + }); + } + expect(state!.outputBytes).toBeLessThanOrEqual(4 * projectedChars); + expect(state!.outputBytes).toBe(Buffer.byteLength(state!.output)); + expect(state!.output.slice(-projectedChars)).toBe(full.slice(-projectedChars)); + }); + + it("trims full ACP terminal output by a further 256 KiB at a UTF-8 boundary", () => { + const cap = 1280 * 1024; + const step = 256 * 1024; const chunk = (text: string | Uint8Array) => ({ sessionUpdate: "terminal_output_chunk" as const, terminalId: "terminal-cap", @@ -1228,7 +1246,7 @@ describe("AcpRuntimeModel", () => { expect(full.outputBytes).toBe(cap); expect(full.output.length).toBe(cap - 1); - // The cut at one byte past the cap plus 1 MiB falls inside "é", so the whole character goes. + // The cut at one byte past the cap plus 256 KiB falls inside "é", so the whole character goes. const trimmed = applyAcpAgentTerminalUpdate(full, chunk("c")); expect(trimmed.outputBytes).toBe(cap - step - 1); expect(trimmed.output.length).toBe(cap - step - 1); diff --git a/packages/provider-acp/src/server/runtimeModel.ts b/packages/provider-acp/src/server/runtimeModel.ts index e01ca47772f9e..1306d0a12cf44 100644 --- a/packages/provider-acp/src/server/runtimeModel.ts +++ b/packages/provider-acp/src/server/runtimeModel.ts @@ -61,9 +61,12 @@ type AcpAgentTerminalUpdate = Extract< { readonly sessionUpdate: "terminal_update" | "terminal_output_chunk" } >; -const MAX_ACP_TERMINAL_OUTPUT_BYTES = 16 * 1024 * 1024; -const ACP_TERMINAL_OUTPUT_TRIM_BYTES = 1024 * 1024; -const MAX_ACP_TERMINAL_FRAME_BYTES = MAX_ACP_TERMINAL_OUTPUT_BYTES; +// CommandOutputHub reads the last 256 KiB; retain more so its display cut stays unchanged. +export const MAX_AGENT_TERMINAL_OUTPUT_CHARS = 320 * 1024; +// A UTF-16 code unit is at most 3 UTF-8 bytes, so the post-trim floor still holds the projected tail. +const MAX_ACP_TERMINAL_OUTPUT_BYTES = 4 * MAX_AGENT_TERMINAL_OUTPUT_CHARS; +const ACP_TERMINAL_OUTPUT_TRIM_BYTES = 256 * 1024; +const MAX_ACP_TERMINAL_FRAME_BYTES = 16 * 1024 * 1024; function isBase64DataCode(code: number): boolean { return ( From 611410683b3571a6cd2c8f711a6b1cfc01de5a9f Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Sun, 22 Nov 2026 23:26:30 -0600 Subject: [PATCH 278/324] feat(cursor): show which step Cursor is in while a turn starts (#41242) Co-authored-by: Claude Opus 5.5 --- .../src/features/threads/ThreadFeed.tsx | 1 + .../src/features/threads/thread-work-log.tsx | 19 +++++- apps/mobile/src/i18n/translations/de.json | 7 +- apps/mobile/src/i18n/translations/en.json | 7 +- apps/mobile/src/i18n/translations/es.json | 7 +- apps/mobile/src/i18n/translations/fr.json | 7 +- apps/mobile/src/i18n/translations/ja.json | 7 +- apps/mobile/src/i18n/translations/ko.json | 7 +- apps/mobile/src/i18n/translations/pt-BR.json | 7 +- apps/mobile/src/i18n/translations/ru.json | 7 +- apps/mobile/src/i18n/translations/sv.json | 7 +- apps/mobile/src/i18n/translations/zh.json | 7 +- apps/mobile/src/lib/threadActivity.ts | 14 +++- apps/web/src/components/ChatView.tsx | 5 ++ .../src/components/chat/MessagesTimeline.tsx | 4 ++ .../components/chat/ProviderStartingIcon.tsx | 67 +++++++++++++++++++ .../components/chat/TimelineWorkGroupRows.tsx | 49 +++++++++++--- .../src/components/chat/timelineRowContext.ts | 2 + apps/web/src/i18n/translations/de.json | 7 +- apps/web/src/i18n/translations/en.json | 7 +- apps/web/src/i18n/translations/es.json | 7 +- apps/web/src/i18n/translations/fr.json | 7 +- apps/web/src/i18n/translations/ja.json | 7 +- apps/web/src/i18n/translations/ko.json | 7 +- apps/web/src/i18n/translations/pt-BR.json | 7 +- apps/web/src/i18n/translations/ru.json | 7 +- apps/web/src/i18n/translations/sv.json | 7 +- apps/web/src/i18n/translations/zh.json | 7 +- packages/client-runtime/src/state/models.ts | 6 ++ .../src/state/threadExecution.test.ts | 16 +++++ .../src/state/threadExecution.ts | 39 +++++++++-- packages/contracts/src/orchestrationV2.ts | 5 ++ .../src/server/CursorAgentSdk.test.ts | 34 ++++++++++ .../src/server/CursorAgentSdk.ts | 59 +++++++++++----- .../CursorAgentSdkProcessRunner.test.ts | 4 ++ .../src/server/CursorAgentSdkProcessRunner.ts | 29 ++++++-- .../src/server/CursorAgentSdkWorker.ts | 6 ++ .../server/CursorAgentSdkWorkerProtocol.ts | 5 ++ .../src/server/adapter.test.ts | 11 +++ .../provider-cursor/src/server/adapter.ts | 29 +++++++- patches/@cursor__sdk@1.4.2.patch | 14 ++-- pnpm-lock.yaml | 8 +-- 42 files changed, 494 insertions(+), 72 deletions(-) create mode 100644 apps/web/src/components/chat/ProviderStartingIcon.tsx diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index a809dc8ea8f3e..005a6fb8f30c1 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -2096,6 +2096,7 @@ function renderFeedEntry( iconSubtleColor={iconSubtleColor} label={entry.label} providerStartingLabel={entry.providerStartingLabel} + providerStartingDriver={entry.providerStartingDriver} /> ); } diff --git a/apps/mobile/src/features/threads/thread-work-log.tsx b/apps/mobile/src/features/threads/thread-work-log.tsx index f0bc00e11385e..a774bf9519c29 100644 --- a/apps/mobile/src/features/threads/thread-work-log.tsx +++ b/apps/mobile/src/features/threads/thread-work-log.tsx @@ -1,3 +1,4 @@ +import { ProviderIcon } from "../../components/ProviderIcon"; import { Button } from "../../components/ui/Button"; import { ThreadSubagentGroup } from "./thread-subagent-group"; import { ProposedPlanCard } from "./ProposedPlanCard"; @@ -214,6 +215,7 @@ function ShimmerWorkContent(props: { readonly environmentId?: EnvironmentId; readonly highlighted: boolean; readonly icon: WorkContentIcon; + readonly iconNode?: ReactNode; readonly iconSubtleColor: ColorValue; readonly label: string; readonly onTextLayout?: ComponentProps["onTextLayout"]; @@ -225,7 +227,9 @@ function ShimmerWorkContent(props: { {props.showIcon ? ( - {props.toolIcon && props.environmentId ? ( + {props.iconNode !== undefined ? ( + props.iconNode + ) : props.toolIcon && props.environmentId ? ( + + + ) + } iconSubtleColor={props.iconSubtleColor} label={label} showIcon diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index 10ed053228b10..1116dd8895c6e 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "Fertig", "d4d89c139de812a8": "Fehlgeschlagen", "c1e03a860c856245": "Gestoppt", - "f1d27d127ab27ac6": "Wird gestartet", + "7e5abc299ead1d09": "{provider}-Plugins werden geladen", + "21872f69ccbc711d": "{provider}-MCP-Server werden gestartet", + "fedaa29ff8815a77": "{provider}-Hooks werden geladen", + "57025ae4de5beb57": "{provider}-Regeln und -Skills werden geladen", + "4729a188600f1501": "Verbindung zu {provider} wird hergestellt", "8c8977097681630f": "{provider} wird gestartet", + "f1d27d127ab27ac6": "Wird gestartet", "86d60d42f6cb4a40": "Inaktiv", "0e8eab930d79d8b4": "Wartet", "54002bf654ddbab1": "Abgeschlossen", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 312e7e4c60bbd..d9c7d08df765b 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "Done", "d4d89c139de812a8": "Failed", "c1e03a860c856245": "Stopped", - "f1d27d127ab27ac6": "Starting", + "7e5abc299ead1d09": "Loading {provider} plugins", + "21872f69ccbc711d": "Starting {provider} MCP servers", + "fedaa29ff8815a77": "Loading {provider} hooks", + "57025ae4de5beb57": "Loading {provider} rules and skills", + "4729a188600f1501": "Connecting to {provider}", "8c8977097681630f": "Starting {provider}", + "f1d27d127ab27ac6": "Starting", "86d60d42f6cb4a40": "Idle", "0e8eab930d79d8b4": "Waiting", "54002bf654ddbab1": "Completed", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index 9124637171066..8ceac2b26a722 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "Terminado", "d4d89c139de812a8": "Falló", "c1e03a860c856245": "Detenido", - "f1d27d127ab27ac6": "Iniciando", + "7e5abc299ead1d09": "Cargando plugins de {provider}", + "21872f69ccbc711d": "Iniciando servidores MCP de {provider}", + "fedaa29ff8815a77": "Cargando hooks de {provider}", + "57025ae4de5beb57": "Cargando reglas y skills de {provider}", + "4729a188600f1501": "Conectando con {provider}", "8c8977097681630f": "Iniciando {provider}", + "f1d27d127ab27ac6": "Iniciando", "86d60d42f6cb4a40": "Inactivo", "0e8eab930d79d8b4": "Esperando", "54002bf654ddbab1": "Completado", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index ad9d49d83c52c..a6904b69d7f73 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "Terminé", "d4d89c139de812a8": "Échec", "c1e03a860c856245": "Arrêté", - "f1d27d127ab27ac6": "Démarrage", + "7e5abc299ead1d09": "Chargement des plugins de {provider}", + "21872f69ccbc711d": "Démarrage des serveurs MCP de {provider}", + "fedaa29ff8815a77": "Chargement des hooks de {provider}", + "57025ae4de5beb57": "Chargement des règles et des skills de {provider}", + "4729a188600f1501": "Connexion à {provider}", "8c8977097681630f": "Démarrage de {provider}", + "f1d27d127ab27ac6": "Démarrage", "86d60d42f6cb4a40": "Inactif", "0e8eab930d79d8b4": "En attente", "54002bf654ddbab1": "Terminé", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index b80aeaddbb35a..3ce3515fae73b 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "完了", "d4d89c139de812a8": "失敗", "c1e03a860c856245": "停止", - "f1d27d127ab27ac6": "起動中", + "7e5abc299ead1d09": "{provider} のプラグインを読み込み中", + "21872f69ccbc711d": "{provider} の MCP サーバーを起動中", + "fedaa29ff8815a77": "{provider} のフックを読み込み中", + "57025ae4de5beb57": "{provider} のルールとスキルを読み込み中", + "4729a188600f1501": "{provider} に接続中", "8c8977097681630f": "{provider} を起動中", + "f1d27d127ab27ac6": "起動中", "86d60d42f6cb4a40": "アイドル", "0e8eab930d79d8b4": "待機中", "54002bf654ddbab1": "完了", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index b35b6391337f1..484ab67231b2e 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "완료", "d4d89c139de812a8": "실패", "c1e03a860c856245": "중지됨", - "f1d27d127ab27ac6": "시작 중", + "7e5abc299ead1d09": "{provider} 플러그인 불러오는 중", + "21872f69ccbc711d": "{provider} MCP 서버 시작 중", + "fedaa29ff8815a77": "{provider} 훅 불러오는 중", + "57025ae4de5beb57": "{provider} 규칙 및 스킬 불러오는 중", + "4729a188600f1501": "{provider}에 연결 중", "8c8977097681630f": "{provider} 시작 중", + "f1d27d127ab27ac6": "시작 중", "86d60d42f6cb4a40": "유휴", "0e8eab930d79d8b4": "대기 중", "54002bf654ddbab1": "완료됨", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 037e9559e0aa3..4959be9c365b1 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "Concluído", "d4d89c139de812a8": "Falhou", "c1e03a860c856245": "Parado", - "f1d27d127ab27ac6": "Iniciando", + "7e5abc299ead1d09": "Carregando plugins do {provider}", + "21872f69ccbc711d": "Iniciando servidores MCP do {provider}", + "fedaa29ff8815a77": "Carregando hooks do {provider}", + "57025ae4de5beb57": "Carregando regras e skills do {provider}", + "4729a188600f1501": "Conectando ao {provider}", "8c8977097681630f": "Iniciando {provider}", + "f1d27d127ab27ac6": "Iniciando", "86d60d42f6cb4a40": "Ocioso", "0e8eab930d79d8b4": "Aguardando", "54002bf654ddbab1": "Concluído", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index a36a2f6e8716b..7987d3d16485a 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "Готово", "d4d89c139de812a8": "Ошибка", "c1e03a860c856245": "Остановлено", - "f1d27d127ab27ac6": "Запуск", + "7e5abc299ead1d09": "Загрузка плагинов {provider}", + "21872f69ccbc711d": "Запуск MCP-серверов {provider}", + "fedaa29ff8815a77": "Загрузка хуков {provider}", + "57025ae4de5beb57": "Загрузка правил и навыков {provider}", + "4729a188600f1501": "Подключение к {provider}", "8c8977097681630f": "Запуск {provider}", + "f1d27d127ab27ac6": "Запуск", "86d60d42f6cb4a40": "Простаивает", "0e8eab930d79d8b4": "Ожидание", "54002bf654ddbab1": "Завершено", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 6c1040e3eb0b0..38f2f3c80172c 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "Klar", "d4d89c139de812a8": "Misslyckades", "c1e03a860c856245": "Stoppad", - "f1d27d127ab27ac6": "Startar", + "7e5abc299ead1d09": "Läser in plugins för {provider}", + "21872f69ccbc711d": "Startar MCP-servrar för {provider}", + "fedaa29ff8815a77": "Läser in hooks för {provider}", + "57025ae4de5beb57": "Läser in regler och färdigheter för {provider}", + "4729a188600f1501": "Ansluter till {provider}", "8c8977097681630f": "Startar {provider}", + "f1d27d127ab27ac6": "Startar", "86d60d42f6cb4a40": "Inaktiv", "0e8eab930d79d8b4": "Väntar", "54002bf654ddbab1": "Slutförd", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index 7f0cdbac92e7d..e673d0e56ba1b 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "完成", "d4d89c139de812a8": "失败", "c1e03a860c856245": "已停止", - "f1d27d127ab27ac6": "正在启动", + "7e5abc299ead1d09": "正在加载 {provider} 插件", + "21872f69ccbc711d": "正在启动 {provider} MCP 服务器", + "fedaa29ff8815a77": "正在加载 {provider} 钩子", + "57025ae4de5beb57": "正在加载 {provider} 规则和技能", + "4729a188600f1501": "正在连接 {provider}", "8c8977097681630f": "正在启动 {provider}", + "f1d27d127ab27ac6": "正在启动", "86d60d42f6cb4a40": "闲置", "0e8eab930d79d8b4": "等待中", "54002bf654ddbab1": "已完成", diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts index 1760b37b49606..e180927aa3c90 100644 --- a/apps/mobile/src/lib/threadActivity.ts +++ b/apps/mobile/src/lib/threadActivity.ts @@ -270,6 +270,8 @@ type ThreadFeedEntryContent = readonly label?: string; /** Shown instead of "Thinking" while the provider has not started a turn. */ readonly providerStartingLabel?: string; + /** The starting provider's driver, whose logo replaces the thinking icon. */ + readonly providerStartingDriver?: string; }; export interface ThreadFeedLatestRun { @@ -280,6 +282,7 @@ export interface ThreadFeedLatestRun { readonly turnEnded?: boolean; readonly providerStartingLabel?: string; readonly providerStartingLabelMsg?: string; + readonly providerStarting?: { readonly driver: string }; } /** Long Android headers can ANR despite one-line display; cap labels only, preserving expanded and copied text. */ @@ -1498,7 +1501,8 @@ function latestRunsEqual(left: ThreadFeedLatestRun | null, right: ThreadFeedLate left.completedAt === right.completedAt && left.turnEnded === right.turnEnded && left.providerStartingLabel === right.providerStartingLabel && - left.providerStartingLabelMsg === right.providerStartingLabelMsg) + left.providerStartingLabelMsg === right.providerStartingLabelMsg && + left.providerStarting?.driver === right.providerStarting?.driver) ); } @@ -1990,6 +1994,7 @@ export function deriveThreadFeedPresentation( latestRun?.providerStartingLabelMsg === undefined ? latestRun?.providerStartingLabel : resolve(latestRun.providerStartingLabelMsg), + latestRun?.providerStarting?.driver, ), ); } @@ -2136,12 +2141,14 @@ function thinkingRow( runId: RunId | null, label: string | null, providerStartingLabel: string | undefined, + providerStartingDriver: string | undefined, ) { if ( cachedThinkingRow?.createdAt !== createdAt || cachedThinkingRow.runId !== runId || (cachedThinkingRow.label ?? null) !== label || - cachedThinkingRow.providerStartingLabel !== providerStartingLabel + cachedThinkingRow.providerStartingLabel !== providerStartingLabel || + cachedThinkingRow.providerStartingDriver !== providerStartingDriver ) { cachedThinkingRow = { type: "thinking", @@ -2150,6 +2157,9 @@ function thinkingRow( runId, ...(label === null ? {} : { label }), ...(providerStartingLabel === undefined ? {} : { providerStartingLabel }), + ...(providerStartingLabel === undefined || providerStartingDriver === undefined + ? {} + : { providerStartingDriver }), }; } return cachedThinkingRow; diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 840c337156343..e3b4e9e5f7682 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -3650,6 +3650,11 @@ export default function ChatView(props: ChatViewProps) { ? messages(activeActivityRun.providerStartingLabelMsg) : null } + providerStarting={ + activeActivityRun?.providerStartingLabelMsg + ? (activeActivityRun.providerStarting ?? null) + : null + } worktreeSetup={worktreeSetup} onCancelWorktreeSetup={onCancelWorktreeSetupStable} retryableWorkspacePreparationRunIds={retryableWorkspacePreparationRunIds} diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 42409464aca7a..aaaba1d4bc921 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -1,5 +1,6 @@ import { T, useGT, useMessages, Var } from "gt-react"; import type { SideThreadOpenIntent } from "@t3tools/client-runtime/side-thread"; +import type { ThreadRunSummary } from "@t3tools/client-runtime/state/models"; import { threadErrorText } from "@t3tools/client-runtime/state/threads"; import { threadEnvironment } from "../../state/threads"; import { useAtomCommand } from "../../state/use-atom-command"; @@ -242,6 +243,7 @@ interface MessagesTimelineProps { activeTurnStartedAt?: string | null; /** Replaces "Thinking" while the active run's provider has not started a turn. */ providerStartingLabel?: string | null; + providerStarting?: NonNullable | null; worktreeSetup?: WorktreeSetupSnapshot | null; onCancelWorktreeSetup?: () => void; retryableWorkspacePreparationRunIds?: ReadonlySet; @@ -366,6 +368,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ runlessWorkActive = false, activeTurnStartedAt = null, providerStartingLabel = null, + providerStarting = null, worktreeSetup = null, footer = null, onCancelWorktreeSetup, @@ -1193,6 +1196,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ awaitingUser: awaitingUser !== null, isPreparingWorktree, providerStartingLabel, + providerStarting, latestRunId: latestRun?.runId ?? null, liveAnswerPreview: isWorking && toolCallVisibility === "zen" ? liveAnswerPreview(timelineEntries) : null, diff --git a/apps/web/src/components/chat/ProviderStartingIcon.tsx b/apps/web/src/components/chat/ProviderStartingIcon.tsx new file mode 100644 index 0000000000000..634f1f742f1d6 --- /dev/null +++ b/apps/web/src/components/chat/ProviderStartingIcon.tsx @@ -0,0 +1,67 @@ +import { useAtomValue } from "@effect/atom-react"; +import { + type EnvironmentId, + PROVIDER_DISPLAY_NAMES, + type ProviderDriverKind, + type ProviderInstanceId, +} from "@t3tools/contracts"; +import * as Option from "effect/Option"; +import { Atom } from "effect/reactivity"; + +import { brandProviderInstanceEntries, deriveProviderInstanceEntries } from "~/providerInstances"; +import { serverEnvironment } from "~/state/server"; +import { ProviderInstanceIcon } from "./ProviderInstanceIcon"; + +interface ProviderStartingPresentation { + readonly displayName: string; + readonly acpRegistryAgentId: string | undefined; + readonly acpRegistryIconUrl: string | undefined; +} + +// Keyed per instance so provider status pushes don't rerender the live row. +const providerStartingPresentationAtom = Atom.family((key: string) => + Atom.make((get): ProviderStartingPresentation | null => { + const [environmentId, instanceId] = key.split("\u0000") as [string, string]; + const config = get(serverEnvironment.configValueAtom(environmentId as EnvironmentId)); + const provider = config?.providers.find((candidate) => candidate.instanceId === instanceId); + if (!config || !provider) return null; + const [entry] = brandProviderInstanceEntries( + deriveProviderInstanceEntries([provider]), + config.settings, + ); + if (!entry) return null; + const next = { + displayName: entry.displayName, + acpRegistryAgentId: entry.acpRegistryAgentId, + acpRegistryIconUrl: entry.acpRegistryIconUrl, + }; + const previous = Option.getOrNull(get.self()); + return previous && + previous.displayName === next.displayName && + previous.acpRegistryAgentId === next.acpRegistryAgentId && + previous.acpRegistryIconUrl === next.acpRegistryIconUrl + ? previous + : next; + }).pipe(Atom.withLabel("provider-starting-presentation")), +); + +/** The logo of the provider a run is waiting on, shown in place of the thinking icon. */ +export function ProviderStartingIcon(props: { + readonly environmentId: EnvironmentId | null; + readonly instanceId: ProviderInstanceId; + readonly driver: ProviderDriverKind; +}) { + const presentation = useAtomValue( + providerStartingPresentationAtom(`${props.environmentId ?? ""}\u0000${props.instanceId}`), + ); + return ( + + ); +} diff --git a/apps/web/src/components/chat/TimelineWorkGroupRows.tsx b/apps/web/src/components/chat/TimelineWorkGroupRows.tsx index c67c76bf4cca3..253d72fd2649e 100644 --- a/apps/web/src/components/chat/TimelineWorkGroupRows.tsx +++ b/apps/web/src/components/chat/TimelineWorkGroupRows.tsx @@ -41,6 +41,7 @@ import { type TimelineWorkEntry, type TimelineRow, } from "./timelineRowContext"; +import { ProviderStartingIcon } from "./ProviderStartingIcon"; import { TimelineRowTimestamp, ActivityShimmerOverlay } from "./TimelineRowParts"; import { failedToolIconClassName, @@ -443,8 +444,13 @@ export function ThinkingTimelineRow({ row }: { row: Extract; // A failed group keeps this disclosure while an approval waits, but nothing is thinking then. const live = ctx.pendingApprovals.size === 0; @@ -457,6 +463,15 @@ export function ThinkingTimelineRow({ row }: { row: Extract + ) + } active={live} shimmer={live} /> @@ -478,6 +493,7 @@ export function ThinkingTimelineRow({ row }: { row: Extract {showShimmer ? ( - + ) : null}
    @@ -517,6 +542,7 @@ function LiveActivityRow({ function LiveActivityContent({ label, iconName, + iconNode, toolIcon, failed = false, announceFailure = false, @@ -525,6 +551,7 @@ function LiveActivityContent({ }: { label: ReactNode; iconName: WorkEntryIconName | undefined; + iconNode?: ReactNode; toolIcon?: ToolActivityIcon | undefined; failed?: boolean; announceFailure?: boolean; @@ -551,12 +578,16 @@ function LiveActivityContent({ role={announceFailure ? "img" : undefined} aria-label={announceFailure ? gt("Tool call failed") : undefined} > - + {iconNode ? ( + {iconNode} + ) : ( + + )} ) : null } diff --git a/apps/web/src/components/chat/timelineRowContext.ts b/apps/web/src/components/chat/timelineRowContext.ts index 5ff5c032db981..139379fbeefda 100644 --- a/apps/web/src/components/chat/timelineRowContext.ts +++ b/apps/web/src/components/chat/timelineRowContext.ts @@ -1,5 +1,6 @@ import type { ToolCallDiffTarget } from "../../diffPanelStore"; import type { SideThreadOpenIntent } from "@t3tools/client-runtime/side-thread"; +import type { ThreadRunSummary } from "@t3tools/client-runtime/state/models"; import type { ProviderApprovalDecision, ResponseContextRecord, @@ -117,6 +118,7 @@ export interface TimelineRowActivityState { awaitingUser: boolean; isPreparingWorktree: boolean; providerStartingLabel: string | null; + providerStarting: NonNullable | null; latestRunId: RunId | null; backgroundWorktreeSetup: WorktreeSetupSnapshot | null; liveAnswerPreview: string | null; diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index aeb4e4497d43e..7900e73186091 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "Fertig", "d4d89c139de812a8": "Fehlgeschlagen", "c1e03a860c856245": "Gestoppt", - "f1d27d127ab27ac6": "Wird gestartet", + "7e5abc299ead1d09": "{provider}-Plugins werden geladen", + "21872f69ccbc711d": "{provider}-MCP-Server werden gestartet", + "fedaa29ff8815a77": "{provider}-Hooks werden geladen", + "57025ae4de5beb57": "{provider}-Regeln und -Skills werden geladen", + "4729a188600f1501": "Verbindung zu {provider} wird hergestellt", "8c8977097681630f": "{provider} wird gestartet", + "f1d27d127ab27ac6": "Wird gestartet", "86d60d42f6cb4a40": "Inaktiv", "0e8eab930d79d8b4": "Wartet", "54002bf654ddbab1": "Abgeschlossen", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index e3e810fe437bc..5bdd7c383d319 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "Done", "d4d89c139de812a8": "Failed", "c1e03a860c856245": "Stopped", - "f1d27d127ab27ac6": "Starting", + "7e5abc299ead1d09": "Loading {provider} plugins", + "21872f69ccbc711d": "Starting {provider} MCP servers", + "fedaa29ff8815a77": "Loading {provider} hooks", + "57025ae4de5beb57": "Loading {provider} rules and skills", + "4729a188600f1501": "Connecting to {provider}", "8c8977097681630f": "Starting {provider}", + "f1d27d127ab27ac6": "Starting", "86d60d42f6cb4a40": "Idle", "0e8eab930d79d8b4": "Waiting", "54002bf654ddbab1": "Completed", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 113f1c5d4cafe..91dbb2b07f50f 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "Terminado", "d4d89c139de812a8": "Falló", "c1e03a860c856245": "Detenido", - "f1d27d127ab27ac6": "Iniciando", + "7e5abc299ead1d09": "Cargando plugins de {provider}", + "21872f69ccbc711d": "Iniciando servidores MCP de {provider}", + "fedaa29ff8815a77": "Cargando hooks de {provider}", + "57025ae4de5beb57": "Cargando reglas y skills de {provider}", + "4729a188600f1501": "Conectando con {provider}", "8c8977097681630f": "Iniciando {provider}", + "f1d27d127ab27ac6": "Iniciando", "86d60d42f6cb4a40": "Inactivo", "0e8eab930d79d8b4": "Esperando", "54002bf654ddbab1": "Completado", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 17c01696429a9..f5cf7e62a4744 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "Terminé", "d4d89c139de812a8": "Échec", "c1e03a860c856245": "Arrêté", - "f1d27d127ab27ac6": "Démarrage", + "7e5abc299ead1d09": "Chargement des plugins de {provider}", + "21872f69ccbc711d": "Démarrage des serveurs MCP de {provider}", + "fedaa29ff8815a77": "Chargement des hooks de {provider}", + "57025ae4de5beb57": "Chargement des règles et des skills de {provider}", + "4729a188600f1501": "Connexion à {provider}", "8c8977097681630f": "Démarrage de {provider}", + "f1d27d127ab27ac6": "Démarrage", "86d60d42f6cb4a40": "Inactif", "0e8eab930d79d8b4": "En attente", "54002bf654ddbab1": "Terminé", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index a13377564e7fe..7e3be343b068b 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "完了", "d4d89c139de812a8": "失敗", "c1e03a860c856245": "停止", - "f1d27d127ab27ac6": "起動中", + "7e5abc299ead1d09": "{provider} のプラグインを読み込み中", + "21872f69ccbc711d": "{provider} の MCP サーバーを起動中", + "fedaa29ff8815a77": "{provider} のフックを読み込み中", + "57025ae4de5beb57": "{provider} のルールとスキルを読み込み中", + "4729a188600f1501": "{provider} に接続中", "8c8977097681630f": "{provider} を起動中", + "f1d27d127ab27ac6": "起動中", "86d60d42f6cb4a40": "アイドル", "0e8eab930d79d8b4": "待機中", "54002bf654ddbab1": "完了", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index da68956e5a4d2..ef69858aead11 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "완료", "d4d89c139de812a8": "실패", "c1e03a860c856245": "중지됨", - "f1d27d127ab27ac6": "시작 중", + "7e5abc299ead1d09": "{provider} 플러그인 불러오는 중", + "21872f69ccbc711d": "{provider} MCP 서버 시작 중", + "fedaa29ff8815a77": "{provider} 훅 불러오는 중", + "57025ae4de5beb57": "{provider} 규칙 및 스킬 불러오는 중", + "4729a188600f1501": "{provider}에 연결 중", "8c8977097681630f": "{provider} 시작 중", + "f1d27d127ab27ac6": "시작 중", "86d60d42f6cb4a40": "유휴", "0e8eab930d79d8b4": "대기 중", "54002bf654ddbab1": "완료됨", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index a0e88601de24c..5b2f82a27a416 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "Concluído", "d4d89c139de812a8": "Falhou", "c1e03a860c856245": "Parado", - "f1d27d127ab27ac6": "Iniciando", + "7e5abc299ead1d09": "Carregando plugins do {provider}", + "21872f69ccbc711d": "Iniciando servidores MCP do {provider}", + "fedaa29ff8815a77": "Carregando hooks do {provider}", + "57025ae4de5beb57": "Carregando regras e skills do {provider}", + "4729a188600f1501": "Conectando ao {provider}", "8c8977097681630f": "Iniciando {provider}", + "f1d27d127ab27ac6": "Iniciando", "86d60d42f6cb4a40": "Ocioso", "0e8eab930d79d8b4": "Aguardando", "54002bf654ddbab1": "Concluído", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 890e0b9d7506b..2891cb8165d7c 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "Готово", "d4d89c139de812a8": "Ошибка", "c1e03a860c856245": "Остановлено", - "f1d27d127ab27ac6": "Запуск", + "7e5abc299ead1d09": "Загрузка плагинов {provider}", + "21872f69ccbc711d": "Запуск MCP-серверов {provider}", + "fedaa29ff8815a77": "Загрузка хуков {provider}", + "57025ae4de5beb57": "Загрузка правил и навыков {provider}", + "4729a188600f1501": "Подключение к {provider}", "8c8977097681630f": "Запуск {provider}", + "f1d27d127ab27ac6": "Запуск", "86d60d42f6cb4a40": "Простаивает", "0e8eab930d79d8b4": "Ожидание", "54002bf654ddbab1": "Завершено", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 967d0c7eededd..c792d6fb4a981 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "Klar", "d4d89c139de812a8": "Misslyckades", "c1e03a860c856245": "Stoppad", - "f1d27d127ab27ac6": "Startar", + "7e5abc299ead1d09": "Läser in plugins för {provider}", + "21872f69ccbc711d": "Startar MCP-servrar för {provider}", + "fedaa29ff8815a77": "Läser in hooks för {provider}", + "57025ae4de5beb57": "Läser in regler och färdigheter för {provider}", + "4729a188600f1501": "Ansluter till {provider}", "8c8977097681630f": "Startar {provider}", + "f1d27d127ab27ac6": "Startar", "86d60d42f6cb4a40": "Inaktiv", "0e8eab930d79d8b4": "Väntar", "54002bf654ddbab1": "Slutförd", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 5a5128c0a7c8d..cd80e9a35102a 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -813,8 +813,13 @@ "166661f94b300f5b": "完成", "d4d89c139de812a8": "失败", "c1e03a860c856245": "已停止", - "f1d27d127ab27ac6": "正在启动", + "7e5abc299ead1d09": "正在加载 {provider} 插件", + "21872f69ccbc711d": "正在启动 {provider} MCP 服务器", + "fedaa29ff8815a77": "正在加载 {provider} 钩子", + "57025ae4de5beb57": "正在加载 {provider} 规则和技能", + "4729a188600f1501": "正在连接 {provider}", "8c8977097681630f": "正在启动 {provider}", + "f1d27d127ab27ac6": "正在启动", "86d60d42f6cb4a40": "闲置", "0e8eab930d79d8b4": "等待中", "54002bf654ddbab1": "已完成", diff --git a/packages/client-runtime/src/state/models.ts b/packages/client-runtime/src/state/models.ts index 4b708662839b2..a57483fdd95c5 100644 --- a/packages/client-runtime/src/state/models.ts +++ b/packages/client-runtime/src/state/models.ts @@ -12,6 +12,7 @@ import type { OrchestrationV2ThreadShell, PlanId, ProjectId, + ProviderDriverKind, ProviderInstanceId, RunId, ThreadId, @@ -99,6 +100,11 @@ export interface ThreadRunSummary { readonly providerStartingLabel?: string; /** `providerStartingLabel` as a `msg()` string; display sites resolve this one. */ readonly providerStartingLabelMsg?: string; + /** The starting provider, so clients can show its logo beside the label. */ + readonly providerStarting?: { + readonly instanceId: ProviderInstanceId; + readonly driver: ProviderDriverKind; + }; readonly sourcePlanRef?: { readonly threadId: ThreadId; readonly planId: PlanId; diff --git a/packages/client-runtime/src/state/threadExecution.test.ts b/packages/client-runtime/src/state/threadExecution.test.ts index d932e2c0395b3..5e7b0b1b8c675 100644 --- a/packages/client-runtime/src/state/threadExecution.test.ts +++ b/packages/client-runtime/src/state/threadExecution.test.ts @@ -415,6 +415,22 @@ describe("thread execution presentation", () => { const starting = { ...v2Projection, runs: [openRun], providerSessions: [session] }; expect(deriveThreadActivityRun(starting)?.providerStartingLabel).toBe("Starting Claude"); + expect(deriveThreadActivityRun(starting)?.providerStarting).toEqual({ + instanceId: openRun.providerInstanceId, + driver: session.driver, + }); + expect( + deriveThreadActivityRun({ + ...starting, + providerSessions: [{ ...session, startupPhase: "plugins" }], + })?.providerStartingLabel, + ).toBe("Loading Claude plugins"); + expect( + deriveThreadActivityRun({ + ...starting, + providerSessions: [{ ...session, startupPhase: "a-later-server's-phase" }], + })?.providerStartingLabel, + ).toBe("Starting Claude"); expect( deriveThreadActivityRun({ ...starting, providerSessions: [] })?.providerStartingLabel, ).toBe("Starting"); diff --git a/packages/client-runtime/src/state/threadExecution.ts b/packages/client-runtime/src/state/threadExecution.ts index 7e5ad55dc53b2..7a47960e7b3f3 100644 --- a/packages/client-runtime/src/state/threadExecution.ts +++ b/packages/client-runtime/src/state/threadExecution.ts @@ -113,19 +113,46 @@ function latestMatchingRun( ); } +// Phases a provider can report while it prepares a turn; an unknown one keeps the plain label. +function providerStartingPhase(phase: string | undefined, provider: string) { + switch (phase) { + case "plugins": + return msg("Loading {provider} plugins", { provider }); + case "mcp": + return msg("Starting {provider} MCP servers", { provider }); + case "hooks": + return msg("Loading {provider} hooks", { provider }); + case "skills": + return msg("Loading {provider} rules and skills", { provider }); + case "connecting": + return msg("Connecting to {provider}", { provider }); + default: + return msg("Starting {provider}", { provider }); + } +} + function providerStarting( projection: ThreadStructure, run: OrchestrationV2ThreadProjection["runs"][number], -): Pick { - const driver = projection.providerSessions.findLast( +): Pick< + ThreadRunSummary, + "providerStartingLabel" | "providerStartingLabelMsg" | "providerStarting" +> { + const session = projection.providerSessions.findLast( (session) => session.providerInstanceId === run.providerInstanceId, - )?.driver; - const name = driver === undefined ? undefined : PROVIDER_DISPLAY_NAMES[driver]; + ); + const name = session === undefined ? undefined : PROVIDER_DISPLAY_NAMES[session.driver]; const label = name === undefined ? msg("Starting", { $context: "a provider is launching" }) - : msg("Starting {provider}", { provider: name }); - return { providerStartingLabel: markedTextEnglish([label]), providerStartingLabelMsg: label }; + : providerStartingPhase(session?.startupPhase, name); + return { + providerStartingLabel: markedTextEnglish([label]), + providerStartingLabelMsg: label, + ...(session === undefined + ? {} + : { providerStarting: { instanceId: run.providerInstanceId, driver: session.driver } }), + }; } function summarizeThreadRun( diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 33961fcf8b82b..c9c8eea937e94 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -1114,6 +1114,11 @@ export const OrchestrationV2ProviderSession = Schema.Struct({ }), ).check(Schema.isMaxLength(32)), ).pipe(Schema.withDecodingDefault(Effect.succeed([]))), + /** + * The slow step a provider is in while it starts a turn, such as `plugins`. A string, because + * clients already released reject a literal they do not know; they show the ones they do. + */ + startupPhase: Schema.optionalKey(TrimmedNonEmptyString.check(Schema.isMaxLength(64))), createdAt: Schema.DateTimeUtc, updatedAt: Schema.DateTimeUtc, lastError: Schema.NullOr(Schema.String), diff --git a/packages/provider-cursor/src/server/CursorAgentSdk.test.ts b/packages/provider-cursor/src/server/CursorAgentSdk.test.ts index 94ae5205131e7..3b637b350ffc3 100644 --- a/packages/provider-cursor/src/server/CursorAgentSdk.test.ts +++ b/packages/provider-cursor/src/server/CursorAgentSdk.test.ts @@ -404,6 +404,40 @@ describe("CursorAgentSdkRunner", () => { }).pipe(Effect.provide(layerTest)), ); + it.effect("reports the SDK's startup phases only to the send that is starting", () => + Effect.gen(function* () { + const publish = (phase: string) => + (Reflect.get(globalThis, Symbol.for("@cursor/sdk.startupPhase")) as Function)(phase); + const startSend = cursorSdkMock.send.getMockImplementation()!; + cursorSdkMock.send.mockImplementationOnce(async (message, options) => { + await Promise.resolve(); + publish("plugins"); + return startSend(message, options); + }); + const phases: Array = []; + const reported = yield* Deferred.make(); + const runner = yield* CursorAgentSdk.CursorAgentSdkRunner; + const session = yield* runner.open({ + operation: "create", + options: {}, + threadId: ThreadId.make("thread-cursor-agent-sdk-phase"), + providerSessionId: ProviderSessionId.make("provider-session-cursor-agent-sdk-phase"), + }); + const run = yield* session.send({ + message: "start", + onStartupPhase: (phase) => + Effect.sync(() => phases.push(phase)).pipe( + Effect.andThen(Deferred.succeed(reported, undefined)), + ), + }); + yield* Deferred.await(reported); + publish("mcp"); + yield* run.wait; + + assert.deepStrictEqual(phases, ["plugins"]); + }).pipe(Effect.provide(layerTest)), + ); + it.effect("keeps an agent's background shells and reports each start and end in order", () => Effect.gen(function* () { const start = (conversationId: string, id: number) => { diff --git a/packages/provider-cursor/src/server/CursorAgentSdk.ts b/packages/provider-cursor/src/server/CursorAgentSdk.ts index 81b8208a5dda8..3c05771bfaf05 100644 --- a/packages/provider-cursor/src/server/CursorAgentSdk.ts +++ b/packages/provider-cursor/src/server/CursorAgentSdk.ts @@ -9,6 +9,7 @@ import type { SendOptions, SteerAckOutcome, } from "@cursor/sdk"; +import * as NodeAsyncHooks from "node:async_hooks"; import { NonNegativeInt, type OrchestrationV2ProviderSession, @@ -106,6 +107,8 @@ export interface CursorAgentSdkSendInput { * ends, which is often long after the run. */ readonly onBackgroundShell?: (event: CursorBackgroundShellEvent) => Effect.Effect; + /** Runs as the SDK enters each slow step of preparing the run, before the run starts. */ + readonly onStartupPhase?: (phase: string) => Effect.Effect; } interface CursorBackgroundShellRef { @@ -550,6 +553,19 @@ interface CursorBackgroundShell { }; } +// The SDK names no step while it prepares a run, which can take minutes, so the @cursor/sdk patch +// calls this hook as it enters each one. The hook is global: async context finds the send. +const STARTUP_PHASE_HOOK = Symbol.for("@cursor/sdk.startupPhase"); +const startupPhaseListener = new NodeAsyncHooks.AsyncLocalStorage<(phase: string) => void>(); + +function listeningForStartupPhases(listener: (phase: string) => void, start: () => A): A { + const hooks = globalThis as Record; + hooks[STARTUP_PHASE_HOOK] ??= (phase: unknown) => { + if (typeof phase === "string") startupPhaseListener.getStore()?.(phase); + }; + return startupPhaseListener.run(listener, start); +} + // The SDK kills an agent's background shells when its run ends and reports their exit to no one. // The @cursor/sdk patch offers each new one to this hook; true keeps it past the run. const BACKGROUND_SHELL_HOOK = Symbol.for("@cursor/sdk.backgroundShell"); @@ -833,26 +849,33 @@ export const makeCursorAgentSdkRunner = Effect.fn("makeCursorAgentSdkRunner")(fu return callbackChain; }; - const startRun = () => - Effect.tryPromise({ - try: () => { - if (sendInput.summarize === true) return agent.summarize(); - const options: SendOptions = { - ...sendInput.options, - onDelta: async ({ update }) => { - if (!callbacksReady) { - pendingUpdates.push(update); - return; - } - await dispatchUpdate(update); - }, - }; - if (sendInput.resume !== true) return agent.send(sendInput.message, options); - if (agent.resume === undefined) { - throw new Error("This Cursor SDK agent cannot resume."); + const startSdkRun = () => { + if (sendInput.summarize === true) return agent.summarize(); + const options: SendOptions = { + ...sendInput.options, + onDelta: async ({ update }) => { + if (!callbacksReady) { + pendingUpdates.push(update); + return; } - return agent.resume(options); + await dispatchUpdate(update); }, + }; + if (sendInput.resume !== true) return agent.send(sendInput.message, options); + if (agent.resume === undefined) { + throw new Error("This Cursor SDK agent cannot resume."); + } + return agent.resume(options); + }; + const onStartupPhase = sendInput.onStartupPhase; + const startRun = () => + Effect.tryPromise({ + try: () => + onStartupPhase === undefined + ? startSdkRun() + : listeningForStartupPhases((phase) => { + void Effect.runPromiseWith(context)(onStartupPhase(phase)); + }, startSdkRun), catch: (cause) => runnerError(cause, sendInput.resume === true ? "run.resume" : "run.start"), }); diff --git a/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.test.ts b/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.test.ts index 430907b101097..f52a11fb25a87 100644 --- a/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.test.ts +++ b/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.test.ts @@ -64,6 +64,7 @@ rl.on("line", (line) => { return; } // Emit an early delta before the send response to verify parent buffering/ordering. + send({ type: "startupPhase", sendId: req.id, phase: "plugins" }); send({ type: "delta", sendId: req.id, update: { type: "text-delta", text: "early-" } }); send({ type: "response", id: req.id, ok: true, result: { runId: "run-worker-1", agentId: "agent-worker-1" } }); if (mode === "cancel") { @@ -308,8 +309,10 @@ describe("CursorAgentSdkProcessRunner", () => { const receivedDeltas: Array = []; const firstDeltaGate = yield* Deferred.make(); + const startupPhases: Array = []; const run = yield* session.send({ message: "hi", + onStartupPhase: (phase) => Effect.sync(() => startupPhases.push(phase)), onDelta: (update) => Effect.gen(function* () { const text = (update as { readonly text?: string }).text ?? ""; @@ -320,6 +323,7 @@ describe("CursorAgentSdkProcessRunner", () => { }), }); assert.equal(run.runId, "run-worker-1"); + assert.deepEqual(startupPhases, ["plugins"]); yield* Deferred.await(firstDeltaGate); const steerOutcome = yield* run.steer!("change course"); diff --git a/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.ts b/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.ts index ed97c62288829..ec40415dd932a 100644 --- a/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.ts +++ b/packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.ts @@ -55,6 +55,7 @@ interface ActiveWorkerRun { readonly sessionId: number; readonly queue: Queue.Queue; readonly waitDeferred: Deferred.Deferred; + readonly onStartupPhase: ((phase: string) => Effect.Effect) | undefined; doneEnqueued: boolean; } @@ -104,7 +105,11 @@ interface SpawnedCursorWorker { build: (id: number) => CursorWorkerRequest, method: string, ) => Effect.Effect; - readonly registerRun: (sessionId: number, sendId: number) => Effect.Effect; + readonly registerRun: ( + sessionId: number, + sendId: number, + onStartupPhase: ActiveWorkerRun["onStartupPhase"], + ) => Effect.Effect; readonly unregisterRun: (sendId: number) => Effect.Effect; readonly failSessionRuns: (sessionId: number) => Effect.Effect; readonly setBackgroundShellListener: ( @@ -358,6 +363,8 @@ export const makeCursorAgentSdkProcessRunner = Effect.fn("makeCursorAgentSdkProc } return Effect.void; } + case "startupPhase": + return activeRuns.get(parsed.sendId)?.onStartupPhase?.(parsed.phase) ?? Effect.void; case "runDone": { const run = activeRuns.get(parsed.sendId); if (run !== undefined && !run.doneEnqueued) { @@ -599,13 +606,23 @@ export const makeCursorAgentSdkProcessRunner = Effect.fn("makeCursorAgentSdkProc activeCleanups.add(activeCleanup); // Untraced: per-send registration inside CursorAgentSdkSession.send. - const registerRun = Effect.fnUntraced(function* (sessionId: number, sendId: number) { + const registerRun = Effect.fnUntraced(function* ( + sessionId: number, + sendId: number, + onStartupPhase: ActiveWorkerRun["onStartupPhase"], + ) { const queue = yield* Queue.unbounded(); const waitDeferred = yield* Deferred.make< RunResult, CursorAgentSdk.CursorAgentSdkRunnerError >(); - const state: ActiveWorkerRun = { sessionId, queue, waitDeferred, doneEnqueued: false }; + const state: ActiveWorkerRun = { + sessionId, + queue, + waitDeferred, + onStartupPhase, + doneEnqueued: false, + }; activeRuns.set(sendId, state); return state; }); @@ -863,7 +880,11 @@ export const makeCursorAgentSdkProcessRunner = Effect.fn("makeCursorAgentSdkProc if (sendInput.onBackgroundShell !== undefined) { yield* worker.setBackgroundShellListener(sessionId, sendInput.onBackgroundShell); } - const runState = yield* worker.registerRun(sessionId, sendId); + const runState = yield* worker.registerRun( + sessionId, + sendId, + sendInput.onStartupPhase, + ); let transmitted = false; let acknowledged = false; let rejectedByWorker = false; diff --git a/packages/provider-cursor/src/server/CursorAgentSdkWorker.ts b/packages/provider-cursor/src/server/CursorAgentSdkWorker.ts index 1481795f4ad6a..cdd0fb0136806 100644 --- a/packages/provider-cursor/src/server/CursorAgentSdkWorker.ts +++ b/packages/provider-cursor/src/server/CursorAgentSdkWorker.ts @@ -225,6 +225,12 @@ const runCursorSdkWorkerWithStdio = Effect.fn("CursorAgentSdkWorker.run")(functi writeMessage({ type: "delta", sendId: req.id, update }); } }), + onStartupPhase: (phase) => + Effect.sync(() => { + if (startingSendIds.has(req.id)) { + writeMessage({ type: "startupPhase", sendId: req.id, phase }); + } + }), ...(req.listenBackgroundShells === true ? { onBackgroundShell: (event: CursorAgentSdk.CursorBackgroundShellEvent) => diff --git a/packages/provider-cursor/src/server/CursorAgentSdkWorkerProtocol.ts b/packages/provider-cursor/src/server/CursorAgentSdkWorkerProtocol.ts index e39323ef67925..7f33fde74d0ee 100644 --- a/packages/provider-cursor/src/server/CursorAgentSdkWorkerProtocol.ts +++ b/packages/provider-cursor/src/server/CursorAgentSdkWorkerProtocol.ts @@ -161,6 +161,11 @@ export type CursorWorkerMessage = readonly sendId: number; readonly update: InteractionUpdate; } + | { + readonly type: "startupPhase"; + readonly sendId: number; + readonly phase: string; + } | { readonly type: "runDone"; readonly sendId: number; diff --git a/packages/provider-cursor/src/server/adapter.test.ts b/packages/provider-cursor/src/server/adapter.test.ts index 85cc2535960b8..4e687ed2b9c9e 100644 --- a/packages/provider-cursor/src/server/adapter.test.ts +++ b/packages/provider-cursor/src/server/adapter.test.ts @@ -2581,6 +2581,8 @@ describe("CursorAdapterV2", () => { send: (input) => Effect.gen(function* () { report = input.onBackgroundShell!; + yield* input.onStartupPhase!("plugins"); + yield* input.onStartupPhase!("plugins"); for (const id of ["6", "7", "8"]) { yield* report({ ...shell(id), @@ -2676,6 +2678,15 @@ describe("CursorAdapterV2", () => { Stream.takeUntil((event) => event.type === "turn.terminal"), Stream.runCollect, ); + // The phase the SDK reported while starting is published once and cleared when the run starts. + assert.deepEqual( + events.flatMap((event) => + event.type === "provider_session.updated" + ? [event.providerSession.startupPhase ?? null] + : [], + ), + ["plugins", null], + ); const listed = ( update: ReadonlyArray, ): ReadonlyArray => diff --git a/packages/provider-cursor/src/server/adapter.ts b/packages/provider-cursor/src/server/adapter.ts index 6b04e17c120a1..426bc8b60a264 100644 --- a/packages/provider-cursor/src/server/adapter.ts +++ b/packages/provider-cursor/src/server/adapter.ts @@ -1153,6 +1153,23 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( ), }); + let startupPhase: string | undefined; + const emitStartupPhase = Effect.fn("CursorAdapterV2.emitStartupPhase")(function* ( + phase: string | undefined, + ) { + if (phase === startupPhase) return; + startupPhase = phase; + yield* emitProviderEvent({ + type: "provider_session.updated", + driver: CursorAgentSdk.CURSOR_PROVIDER, + providerSession: { + ...session, + ...(phase === undefined ? {} : { startupPhase: phase }), + updatedAt: yield* DateTime.now, + }, + }); + }); + const emitProviderThread = Effect.fn("CursorAdapterV2.emitProviderThread")(function* ( providerThread: OrchestrationV2ProviderThread, sessionScoped = false, @@ -3016,6 +3033,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( ...(yield* resolveWorkspaceMcpServers(turnInput.runtimePolicy.cwd)), ...mcpServers, }; + let starting = true; const sdkRun = yield* agent.session .send({ message, @@ -3041,8 +3059,17 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( return handleInteractionUpdate(context, update); }, onBackgroundShell: (shell) => onBackgroundShell(turnInput, shell), + onStartupPhase: (phase) => (starting ? emitStartupPhase(phase) : Effect.void), }) - .pipe(Effect.mapError(classifyCursorModelRejection(turnInput.modelSelection))); + .pipe( + Effect.ensuring( + Effect.suspend(() => { + starting = false; + return emitStartupPhase(undefined); + }), + ), + Effect.mapError(classifyCursorModelRejection(turnInput.modelSelection)), + ); // A resume sends no new instructions, and a native one still continues the stopped request. if (resume === undefined) { yield* Ref.set(told, { diff --git a/patches/@cursor__sdk@1.4.2.patch b/patches/@cursor__sdk@1.4.2.patch index 6aadf1b246e56..048f41a7b281d 100644 --- a/patches/@cursor__sdk@1.4.2.patch +++ b/patches/@cursor__sdk@1.4.2.patch @@ -1,5 +1,5 @@ diff --git a/dist/bundled/index.js b/dist/bundled/index.js -index 4d813759e7075c0fe8c881d52200d94c657b5988..d107ac8d650a17aa1cadcef5994c086a9493f0ff 100644 +index 4d813759e7075c0fe8c881d52200d94c657b5988..b9d56b14bac4b3505679a83cfc4cc50cf34318e7 100644 --- a/dist/bundled/index.js +++ b/dist/bundled/index.js @@ -173,7 +173,7 @@ ${X} @@ -25,7 +25,7 @@ index 4d813759e7075c0fe8c881d52200d94c657b5988..d107ac8d650a17aa1cadcef5994c086a ${WP8}`}function zP8($){return $ instanceof Y71}function Q71($){return QP8($)||zP8($)}var T30,Y71,WP8="To view or modify configured hooks, go to Cursor Settings > Hooks.";var bb0=P(()=>{q9();T30=class T30 extends Error{reason;failureType="permission_denied";constructor($){super(`Hook denied: ${$}`);this.name="HookDeniedError",this.reason=$}};Y71=class Y71 extends Error{reason;failureType="error";cause;constructor($,Z){super(`Hook failed (fail-closed): ${$}`);this.name="FailClosedError",this.reason=$,this.cause=Z}}});import{randomUUID as wr6}from"crypto";import{performance as fb0}from"perf_hooks";function HP8($,Z,J,X){try{return rq({hookEventName:J,additionalContext:X})}catch(Y){if(Y instanceof uQ)return P30.warn($,`${J} additional_context exceeded max size; dropping carrier`,{toolName:Z,hookEventName:J,actualLength:Y.actualLength,maxLength:Y.maxLength}),[];throw Y}}function jr6($,Z,J,X){let{toolInput:Y,extraHookFields:Q,hookContextCollector:W}=X,{baseHookRequest:K,toolUseId:H}=X;return{fireFailureAsync:async(V,O,F,N=!1)=>{try{let L=await Yu0($.signal,()=>Z.executeHookForStep(i0.postToolUseFailure,{...K,tool_name:J,tool_input:Y,error_message:O,failure_type:F,duration:V,tool_use_id:H,is_interrupt:N,...Q}));HW(W,HP8($,J,i0.postToolUseFailure,L?.additional_context))}catch(L){P30.warn($,"postToolUseFailure hook error",{toolName:J,error:L instanceof Error?L.message:String(L)})}},fireSuccessAsync:async(V,O)=>{try{let F=await Yu0($.signal,()=>Z.executeHookForStep(i0.postToolUse,{...K,tool_name:J,tool_input:Y,tool_output:O,duration:V,tool_use_id:H,...Q}));HW(W,HP8($,J,i0.postToolUse,F?.additional_context))}catch(F){P30.warn($,"postToolUse hook error",{toolName:J,error:F instanceof Error?F.message:String(F)})}},getToolInput:()=>Y,setToolInput:(V)=>{Y=V},setExtraHookFields:(V)=>{Q=V,X.extraHookFields=V}}}function GP8($,Z,J,X,Y,Q){let W=X($),K=Y.getToolCallId?.(Z)??wr6(),H=Y.getExtraHookFields?.(Z)??{},G={baseHookRequest:W,toolUseId:K,toolInput:Y.createToolInput(Z),extraHookFields:H,hookContextCollector:Q?.hookContextCollector??Y.getHookContextCollector?.(Z)??[]},q=jr6($,J,Y.toolName,G);return{hookContext:G,helpers:q}}async function qP8($,Z,J,X,Y,Q,W,K){let{baseHookRequest:H,toolUseId:G,extraHookFields:q}=X;try{let V=await Yu0($.signal,()=>J.executeHookForStep(i0.preToolUse,{...H,tool_name:Q.toolName,tool_input:Y.getToolInput(),tool_use_id:G,...q}));if(V?.permission==="deny"){let O=V.user_message||`${Q.toolName} blocked by preToolUse hook`,F=Em0(O);try{HW(X.hookContextCollector,rq({hookEventName:i0.preToolUse,additionalContext:V.additional_context}))}catch(N){if(N instanceof uQ)P30.warn($,"preToolUse deny additional_context exceeded max size; dropping carrier",{toolName:Q.toolName,actualLength:N.actualLength,maxLength:N.maxLength});else throw N}return await Y.fireFailureAsync(0,O,"permission_denied"),{type:"rejected",result:W(Z,F),reason:F}}if(V?.updated_input&&Q.applyUpdatedInput){if(Q.applyUpdatedInput(Z,V.updated_input),Y.setToolInput(Q.createToolInput(Z)),Q.getExtraHookFields)Y.setExtraHookFields(Q.getExtraHookFields(Z))}HW(X.hookContextCollector,rq({hookEventName:i0.preToolUse,additionalContext:V?.additional_context}))}catch(V){let O=J.hasFailClosedHooksForStep?.(i0.preToolUse,Q.toolName)??!1,F=V instanceof uQ,N=F?"preToolUse additional_context exceeded max size":"preToolUse hook failed";if(O){let L=V instanceof Error?V.message:"preToolUse hook error",U=A2(`${N}: ${L}`);return await Y.fireFailureAsync(0,U,"error"),{type:"rejected",result:W(Z,U),reason:U}}P30.warn($,F?"preToolUse additional_context exceeded max size; dropping carrier":"preToolUse hook error",{toolName:Q.toolName,error:V instanceof Error?V.message:String(V),...F?{actualLength:V.actualLength,maxLength:V.maxLength}:{}})}if(K)try{let V=await K({ctx:$,args:Z,baseHookRequest:H,hookExecutor:J,toolInput:Y.getToolInput(),toolUseId:G,extraHookFields:X.extraHookFields});if(V!==void 0)return await Y.fireFailureAsync(0,"Pre-execution hook returned rejection","permission_denied"),{type:"rejected",result:V,reason:"Pre-execution hook returned rejection"}}catch(V){if(Q71(V))return await Y.fireFailureAsync(0,V.reason,V.failureType),{type:"rejected",result:W(Z,V.reason),reason:V.reason};throw V}return{type:"continue"}}function T5($){return $.toolCallId}function l6($,Z,J,X){return{async execute(Y,Q,W){let K=W71(Y,Z),{hookContext:H,helpers:G}=GP8(Y,Q,K,J,X,W),q;try{q=await qP8(Y,Q,K,H,G,X,X.createRejectedResult,X.runPreExecutionHooks)}catch(O){throw X.runCleanup?.(H.toolUseId),O}if(q.type==="rejected")return X.runCleanup?.(H.toolUseId),q.result;let V=fb0.now();try{let O=await $.execute(Y,Q,W),F=oU(fb0.now()-V);if(X.runPostExecutionHooks)try{let N=await X.runPostExecutionHooks({ctx:Y,args:Q,result:O,baseHookRequest:H.baseHookRequest,hookExecutor:K,toolInput:G.getToolInput(),toolUseId:H.toolUseId,executionDurationMs:F,extraHookFields:H.extraHookFields});if(N!==void 0)return await G.fireSuccessAsync(F,JSON.stringify(X.createSuccessOutput(Q,N))),X.runCleanup?.(H.toolUseId),N}catch(N){if(Q71(N))return await G.fireFailureAsync(F,N.reason,N.failureType),X.runCleanup?.(H.toolUseId),X.createRejectedResult(Q,N.reason);P30.warn(Y,"postExecutionHooks error",{toolName:X.toolName,error:N instanceof Error?N.message:String(N)})}if(X.isSuccess(O))await G.fireSuccessAsync(F,JSON.stringify(X.createSuccessOutput(Q,O)));else await G.fireFailureAsync(F,X.getErrorMessage(O),X.getFailureType?.(O)??"error",X.isInterrupt?.(O)??!1);return X.runCleanup?.(H.toolUseId),O}catch(O){let F=oU(fb0.now()-V);throw await G.fireFailureAsync(F,O instanceof Error?O.message:String(O),"error"),X.runCleanup?.(H.toolUseId),O}}}}function XI1($,Z,J,X){return{async*execute(Y,Q,W){let K=W71(Y,Z),{hookContext:H,helpers:G}=GP8(Y,Q,K,J,X,W),q=X.runPreExecutionHooks?async(L)=>{await X.runPreExecutionHooks(L);return}:void 0,V=await qP8(Y,Q,K,H,G,X,(L,U)=>X.createRejectedEvent(L,U),q);if(V.type==="rejected"){yield V.result;for(let L of JI1(X,H))yield L;return}let O=fb0.now(),F=X.createResultCollector();try{for await(let L of $.execute(Y,Q,W))F.onEvent(L),yield L}catch(L){let U=oU(fb0.now()-O),D=L instanceof Error?L.message:String(L);await G.fireFailureAsync(U,D,"error");for(let j of JI1(X,H))yield j;throw L}let N=oU(fb0.now()-O);if(X.runPostExecutionHooks)try{await X.runPostExecutionHooks({ctx:Y,args:Q,baseHookRequest:H.baseHookRequest,hookExecutor:K,toolInput:G.getToolInput(),toolUseId:H.toolUseId,extraHookFields:H.extraHookFields,collector:F,executionDurationMs:N})}catch(L){P30.warn(Y,"postExecutionHooks error",{toolName:X.toolName,error:L instanceof Error?L.message:String(L)})}if(F.isAborted())await G.fireFailureAsync(N,"Command was aborted","error",!0);else if(X.isStreamSuccess?.(F)??!0)await G.fireSuccessAsync(N,JSON.stringify(X.createSuccessOutput(Q,F)));else{let L=X.getStreamErrorMessage?.(Q,F)??`Command failed with exit code ${F.getExitCode()}`;await G.fireFailureAsync(N,L,"error")}for(let L of JI1(X,H))yield L}}}function*JI1($,Z){let J=Z.hookContextCollector;if(!$.createHookContextEvent||J===void 0||J.length===0)return;yield $.createHookContextEvent(J)}function W71($,Z){let J=L20($),X=$.get(YW1);if(J&&X===void 0)return Z;let Y=(Q)=>X?.during(Q)??Q;return{executeHookForStep:async(Q,W)=>{if(!J&&m21(Q)){await Y(Z.whenConfigReady());return}return Y(Z.executeHookForStep(Q,W))},hasFailClosedHooksForStep:(Q,W)=>Z.hasFailClosedHooksForStep?.(Q,W)??!1,hasHooksForStep:(Q)=>Z.hasHooksForStep?.(Q)??!0,whenConfigReady:()=>Y(Z.whenConfigReady())}}var P30,oU=($)=>Math.round($*1000)/1000;var OZ=P(()=>{J6();Qu0();F1();q9();$I1();bb0();P30=G1("generic-hooks")});var VP8=()=>{};import{lstat as Mr6}from"fs/promises";import E30 from"path";function Ir6($,Z){let J=E30.resolve($),X=E30.resolve(Z),Y=E30.relative(X,J);if(Y.length===0||Y===".."||Y.startsWith(`..${E30.sep}`)||E30.isAbsolute(Y))return"unsafe";let Q=Y.split(E30.sep).filter((H)=>H.length>0),W=[],K=X;for(let H of Q)K=E30.join(K,H),W.push(K);return W}function Tr6($){if(typeof $!=="object"||$===null||!("code"in $))return!1;let Z=$.code;return Z==="ENOENT"||Z==="ENOTDIR"}async function YI1($,Z){let J=Ir6($,Z);if(J==="unsafe")return!0;for(let X of J)try{if((await Mr6(X)).isSymbolicLink())return!0}catch(Y){if(Tr6(Y))return!0;throw Y}return!1}var QI1=()=>{};import*as K71 from"fs/promises";class z71{async readFile($){try{return await K71.readFile($,"utf-8")}catch(Z){if(Z?.code==="ENOENT")return;throw Z}}async exists($){try{return await K71.access($),!0}catch{return!1}}async pathContainsSymlink($,Z){return YI1($,Z)}}var BP8=P(()=>{QI1()});class H71{innerExecutor;hooksAdditionalContextPromise;teamHooksReadyPromise;hooksConfigLease;constructor($,Z,J,X){this.innerExecutor=$;this.hooksAdditionalContextPromise=Z;this.teamHooksReadyPromise=J;this.hooksConfigLease=X}async execute($,Z,J){if(this.teamHooksReadyPromise)await this.teamHooksReadyPromise;let X=await this.innerExecutor.execute($,Z,J),Y=await this.hooksAdditionalContextPromise,Q=this.hooksConfigLease?new yB({configuredSteps:Array.from(this.hooksConfigLease.getConfiguredSteps())}):void 0;if(X.result.case==="success"&&(Y||Q)){let K=X.result.value.requestContext?.clone()??new S5;if(Y)K.hooksAdditionalContext=Y;if(Q)K.hooksConfig=Q;return new b9({result:{case:"success",value:new Y3({requestContext:K,servedFromDiskCache:X.result.value.servedFromDiskCache})}})}return X}}var WI1=P(()=>{c4()});function tU($){if(!$)return!1;return $.type!==GJ.INSECURE_NONE&&$.type!==GJ.UNSPECIFIED}var G71=P(()=>{OV()});async function hb0({hookExecutor:$,baseHookRequest:Z,toolUseId:J,command:X,cwd:Y,sandbox:Q}){let W=await $.executeHookForStep(i0.beforeShellExecution,{...Z,command:X,cwd:Y,sandbox:Q,tool_use_id:J});if(W?.permission==="deny"){let K=sq("Command execution",W.user_message);throw new T30(K)}if(W?.permission==="ask")return JW1(W.user_message);return}var q71=P(()=>{J6();q9();bb0()});class Vl0{wrappedExecutor;constructor($,Z,J){this.wrappedExecutor=l6($,Z,J,Pr6)}execute($,Z,J){return this.wrappedExecutor.execute($,Z,J)}}class Bl0{wrappedExecutor;constructor($,Z,J){this.wrappedExecutor=l6($,Z,J,Er6)}execute($,Z,J){return this.wrappedExecutor.execute($,Z,J)}}var Pr6,Er6;var OP8=P(()=>{J6();q9();MV();q$();OZ();G71();BZ();q71();Pr6={toolName:i8.Shell,getToolCallId:T5,createToolInput:($)=>{let Z=$.workingDirectory||"";return{command:$.command,cwd:Z}},applyUpdatedInput:($,Z)=>{if(typeof Z.command==="string")$.command=Z.command;if(typeof Z.cwd==="string")$.workingDirectory=Z.cwd},createRejectedResult:($,Z)=>new s7({result:{case:"rejected",value:new f6({command:$.command,workingDirectory:$.workingDirectory,reason:Z})}}),isSuccess:($)=>$.result.case==="success",getErrorMessage:($)=>{switch($.result.case){case"error":return $.result.value.error||"BackgroundShell error";case"rejected":return $.result.value.reason||"BackgroundShell rejected";case"permissionDenied":return"Permission denied";case"sandboxUnsupported":return`Sandbox policy unsupported on this host: ${$.result.value.reason}`;default:return"Unknown error"}},createSuccessOutput:($,Z)=>{if(Z.result.case==="success")return{shell_id:Z.result.value.shellId,pid:Z.result.value.pid};return{success:!0}},getExtraHookFields:($)=>{return{cwd:$.workingDirectory||""}},runPreExecutionHooks:async($)=>{let{ctx:Z,args:J,baseHookRequest:X,hookExecutor:Y,toolUseId:Q}=$,W=J.workingDirectory||"",K=tU(J.sandboxPolicy);if(hG(Z,i0.beforeShellExecution))F20(J,await hb0({hookExecutor:Y,baseHookRequest:X,toolUseId:Q,command:J.command,cwd:W,sandbox:K}));return}};Er6={toolName:i8.WriteShellStdin,createToolInput:($)=>({shell_id:$.shellId,chars_length:$.chars.length}),createRejectedResult:($,Z)=>new M7({result:{case:"error",value:new DY({error:Z})}}),isSuccess:($)=>$.result.case==="success",getErrorMessage:($)=>{if($.result.case==="error")return $.result.value.error||"WriteShellStdin error";return"Unknown error"},createSuccessOutput:($)=>({shell_id:$.shellId,success:!0})}});class Ol0{wrappedExecutor;constructor($,Z,J){this.wrappedExecutor=l6($,Z,J,kr6)}execute($,Z,J){return this.wrappedExecutor.execute($,Z,J)}}var kr6;var FP8=P(()=>{q4();OZ();BZ();kr6={toolName:i8.ComputerUse,getToolCallId:T5,createToolInput:($)=>({actions_count:$.actions.length}),createRejectedResult:($,Z)=>new T7({result:{case:"error",value:new $9({error:Z})}}),isSuccess:($)=>$.result.case==="success",getErrorMessage:($)=>{if($.result.case==="error")return $.result.value.error||"ComputerUse error";return"Unknown error"},createSuccessOutput:($,Z)=>{if(Z.result.case==="success")return{action_count:Z.result.value.actionCount,duration_ms:Z.result.value.durationMs};return{success:!0}}}});class Fl0{wrappedExecutor;constructor($,Z,J){this.wrappedExecutor=l6($,Z,J,Rr6)}execute($,Z,J){return this.wrappedExecutor.execute($,Z,J)}}var Rr6;var NP8=P(()=>{lV();OZ();BZ();Rr6={toolName:i8.Delete,getToolCallId:T5,createToolInput:($)=>({file_path:$.path}),applyUpdatedInput:($,Z)=>{if(typeof Z.file_path==="string")$.path=Z.file_path},createRejectedResult:($,Z)=>new C6({result:{case:"rejected",value:new UX({path:$.path,reason:Z})}}),isSuccess:($)=>$.result.case==="success",getErrorMessage:($)=>{switch($.result.case){case"fileNotFound":return`File not found: ${$.result.value.path}`;case"notFile":return`Not a file: ${$.result.value.path}`;case"permissionDenied":return`Permission denied: ${$.result.value.path}`;case"fileBusy":return`File busy: ${$.result.value.path}`;case"rejected":return $.result.value.reason||"Delete rejected";case"error":return $.result.value.error||"Delete error";default:return"Unknown error"}},createSuccessOutput:($)=>({file_path:$.path,deleted:!0})}});class Nl0{wrappedExecutor;constructor($,Z,J){this.wrappedExecutor=l6($,Z,J,Cr6)}execute($,Z,J){return this.wrappedExecutor.execute($,Z,J)}}var Cr6;var LP8=P(()=>{sV();OZ();BZ();Cr6={toolName:i8.ReadLints,getToolCallId:T5,createToolInput:($)=>({file_path:$.path}),applyUpdatedInput:($,Z)=>{if(typeof Z.file_path==="string")$.path=Z.file_path},createRejectedResult:($,Z)=>new S9({result:{case:"rejected",value:new aV({path:$.path,reason:Z})}}),isSuccess:($)=>$.result.case==="success",getErrorMessage:($)=>{switch($.result.case){case"error":return $.result.value.error||"Diagnostics error";case"rejected":return $.result.value.reason||"Diagnostics rejected";case"fileNotFound":return`File not found: ${$.result.value.path}`;case"permissionDenied":return`Permission denied: ${$.result.value.path}`;default:return"Unknown error"}},createSuccessOutput:($,Z)=>{if(Z.result.case==="success")return{file_path:$.path,diagnostics_count:Z.result.value.totalDiagnostics};return{file_path:$.path,success:!0}}}});class Ll0{wrappedExecutor;constructor($,Z,J){this.wrappedExecutor=l6($,Z,J,_r6)}execute($,Z,J){return this.wrappedExecutor.execute($,Z,J)}}var _r6;var UP8=P(()=>{wf0();OZ();BZ();_r6={toolName:i8.Fetch,getToolCallId:T5,createToolInput:($)=>({url:$.url}),applyUpdatedInput:($,Z)=>{if(typeof Z.url==="string")$.url=Z.url},createRejectedResult:($,Z)=>new wJ({result:{case:"error",value:new sW({url:$.url,error:Z})}}),isSuccess:($)=>$.result.case==="success",getErrorMessage:($)=>{if($.result.case==="error")return $.result.value.error||"Fetch error";return"Unknown error"},createSuccessOutput:($,Z)=>{if(Z.result.case==="success")return{url:$.url,status_code:Z.result.value.statusCode,content_length:Z.result.value.content.length};return{url:$.url,success:!0}}}});class Ul0{wrappedExecutor;constructor($,Z,J){this.wrappedExecutor=l6($,Z,J,Sr6)}execute($,Z,J){return this.wrappedExecutor.execute($,Z,J)}}var Sr6;var DP8=P(()=>{iV();OZ();BZ();Sr6={toolName:i8.Grep,getToolCallId:T5,createToolInput:($)=>({pattern:$.pattern,file_path:$.path,glob:$.glob,output_mode:$.outputMode}),applyUpdatedInput:($,Z)=>{if(typeof Z.pattern==="string")$.pattern=Z.pattern;if(typeof Z.file_path==="string")$.path=Z.file_path},createRejectedResult:($,Z)=>new v$({result:{case:"error",value:new P7({error:Z})}}),isSuccess:($)=>$.result.case==="success",getErrorMessage:($)=>{if($.result.case==="error")return $.result.value.error||"Grep error";return"Unknown error"},createSuccessOutput:($)=>({pattern:$.pattern,success:!0})}});class Dl0{wrappedExecutor;constructor($,Z,J){this.wrappedExecutor=l6($,Z,J,vr6)}execute($,Z,J){return this.wrappedExecutor.execute($,Z,J)}}var vr6;var AP8=P(()=>{H4();OZ();BZ();vr6={toolName:i8.LS,getToolCallId:T5,createToolInput:($)=>({file_path:$.path,ignore:$.ignore}),applyUpdatedInput:($,Z)=>{if(typeof Z.file_path==="string")$.path=Z.file_path},createRejectedResult:($,Z)=>new s$({result:{case:"rejected",value:new yV({path:$.path,reason:Z})}}),isSuccess:($)=>$.result.case==="success",getErrorMessage:($)=>{switch($.result.case){case"error":return $.result.value.error||"Ls error";case"rejected":return $.result.value.reason||"Ls rejected";case"timeout":return"Ls operation timed out";default:return"Unknown error"}},getFailureType:($)=>$.result.case==="timeout"?"timeout":"error",createSuccessOutput:($)=>({file_path:$.path,success:!0})}});import{randomUUID as yr6}from"crypto";import{performance as KI1}from"perf_hooks";import{Value as xr6}from"@bufbuild/protobuf";function zI1($){if($===null||typeof $==="string"||typeof $==="boolean"||typeof $==="number"&&Number.isFinite($))return!0;if(Array.isArray($))return $.every(zI1);if(typeof $==="object")return Object.values($).every((Z)=>Z!==void 0&&zI1(Z));return!1}function wP8($,Z,J,X){try{return rq({hookEventName:J,additionalContext:X})}catch(Y){if(Y instanceof uQ)return eU.warn($,`${J} additional_context exceeded max size; dropping carrier`,{toolName:Z,hookEventName:J,actualLength:Y.actualLength,maxLength:Y.maxLength}),[];throw Y}}class Al0{innerExecutor;hookExecutor;baseHookRequestExtractor;mcpLease;hooksConfigLease;constructor($,Z,J,X,Y){this.innerExecutor=$;this.hookExecutor=Z;this.baseHookRequestExtractor=J;this.mcpLease=X;this.hooksConfigLease=Y}async execute($,Z,J){if(Z.smartModeApprovalOnly)return this.innerExecutor.execute($,Z,J);if(Z.symbolicPathArguments.length>0&&(this.hooksConfigLease?.hasHookForStep(i0.preToolUse)===!0||this.hooksConfigLease?.hasHookForStep(i0.beforeMCPExecution)===!0))return new e8({result:{case:"error",value:new k7({error:`"${HQ}" arguments can't be used on this computer: hooks that inspect MCP calls are configured here, and they would not see the file's contents. Read the file and pass its contents instead.`})}});let X=W71($,this.hookExecutor),Y=this.baseHookRequestExtractor($),Q=yr6(),W=J?.hookContextCollector??[],K=Object.fromEntries(Object.entries(Z.args).map(([D,j])=>[D,j?.toJson()])),H=`MCP:${Z.toolName}`;try{let D=await X.executeHookForStep(i0.preToolUse,{...Y,tool_name:H,tool_input:K,tool_use_id:Q});if(D?.permission==="deny"){let j=D.user_message||"MCP tool blocked by preToolUse hook";try{HW(W,rq({hookEventName:i0.preToolUse,additionalContext:D.additional_context}))}catch(w){if(w instanceof uQ)eU.warn($,"preToolUse deny additional_context exceeded max size; dropping carrier",{toolName:H,actualLength:w.actualLength,maxLength:w.maxLength});else throw w}return await this.firePostToolUseFailureAsync($,X,Y,H,K,j,"permission_denied",0,Q,!1,W),new e8({result:{case:"permissionDenied",value:new v9({error:sq("MCP tool execution",j),isReadonly:!1})}})}if(D?.updated_input)try{for(let[j,w]of Object.entries(D.updated_input)){if(w===void 0)continue;if(!zI1(w))throw TypeError("updated_input value is not JSON");Z.args[j]=xr6.fromJson(w)}K=Object.fromEntries(Object.entries(Z.args).map(([j,w])=>[j,w?.toJson()]))}catch(j){eU.warn($,"Failed to merge updated_input for MCP",{error:j instanceof Error?j.message:String(j)})}HW(W,rq({hookEventName:i0.preToolUse,additionalContext:D?.additional_context}))}catch(D){let j=X.hasFailClosedHooksForStep?.(i0.preToolUse,H)??!1,w=D instanceof uQ,k=w?"preToolUse additional_context exceeded max size":"preToolUse hook failed";if(j){let T=D instanceof Error?D.message:"preToolUse hook error",I=A2(`${k}: ${T}`);return await this.firePostToolUseFailureAsync($,X,Y,H,K,I,"error",0,Q,!1,W),new e8({result:{case:"permissionDenied",value:new v9({error:sq("MCP tool execution",I),isReadonly:!1})}})}eU.warn($,w?"preToolUse additional_context exceeded max size; dropping carrier":"preToolUse hook error in MCP executor",{toolName:H,error:D instanceof Error?D.message:String(D),...w?{actualLength:D.actualLength,maxLength:D.maxLength}:{}})}let q=(await this.mcpLease?.getClient($,Z.providerIdentifier))?.config,V,O=q&&"url"in q&&q.url?q.url:void 0;if(O!==void 0)V={url:O};else if(q&&"command"in q)V={command:[q.command,...q.args??[]].filter(Boolean).join(" ")};else V={command:Z.providerIdentifier};let F={mcp_server_name:Z.providerIdentifier,...O!==void 0?{mcp_server_url:O}:{}},N={...Y,tool_name:Z.toolName,tool_input:JSON.stringify(K),tool_use_id:Q,...F,...V},L=hG($,i0.beforeMCPExecution)?await X.executeHookForStep(i0.beforeMCPExecution,N):void 0;if(L?.permission==="deny"){let D=sq("MCP tool execution",L.user_message);return await this.firePostToolUseFailureAsync($,X,Y,H,K,D,"permission_denied",0,Q,!1,W),new e8({result:{case:"permissionDenied",value:new v9({error:D,isReadonly:!1})}})}let U=KI1.now();try{let D=await this.innerExecutor.execute($,Z,J),j=oU(KI1.now()-U),w="{}";if(D.result.case==="success")try{let I=D.result.value.content.map((M)=>{if(M.content.case==="text")return{type:"text",text:M.content.value.text};else if(M.content.case==="image")return{type:"image",data:Buffer.from(M.content.value.data).toString("base64"),mimeType:M.content.value.mimeType};return{type:"unknown"}});w=JSON.stringify({content:I,isError:D.result.value.isError})}catch(I){eU.warn($,"Failed to serialize MCP result",{error:I instanceof Error?I.message:String(I)}),w=JSON.stringify({error:"Failed to serialize result"})}else if(D.result.case==="error")w=JSON.stringify({error:D.result.value.error});else if(D.result.case==="rejected")w=JSON.stringify({rejected:!0,reason:D.result.value.reason});else if(D.result.case==="permissionDenied")w=JSON.stringify({permissionDenied:!0,error:D.result.value.error});let k={...Y,tool_name:Z.toolName,tool_input:JSON.stringify(K),result_json:w,duration:j,tool_use_id:Q,...F};await X.executeHookForStep(i0.afterMCPExecution,k);let T=await this.firePostToolUse($,X,Y,H,K,w,j,Q,W);if(T?.updated_mcp_tool_output!==void 0)try{let I=T.updated_mcp_tool_output,M=[];if(typeof I==="string")M.push(new H5({content:{case:"text",value:new $7({text:I})}}));else if(typeof I==="object"&&I!==null&&"content"in I&&Array.isArray(I.content)){let v=I.content;for(let R of v)if(typeof R==="object"&&R!==null&&"type"in R&&R.type==="text"&&"text"in R)M.push(new H5({content:{case:"text",value:new $7({text:String(R.text)})}}));else M.push(new H5({content:{case:"text",value:new $7({text:JSON.stringify(R)})}}))}else M.push(new H5({content:{case:"text",value:new $7({text:JSON.stringify(I)})}}));let C=typeof I==="object"&&I!==null&&"isError"in I?Boolean(I.isError):!1;return new e8({result:{case:"success",value:new AJ({content:M,isError:C})}})}catch(I){return eU.warn($,"Failed to process updated_mcp_tool_output",{error:I instanceof Error?I.message:String(I)}),D}return D}catch(D){let j=oU(KI1.now()-U),w=D instanceof Error?D.message:String(D);throw await this.firePostToolUseFailureAsync($,X,Y,H,K,w,"error",j,Q,!1,W),D}}async firePostToolUse($,Z,J,X,Y,Q,W,K,H){try{let G=await Z.executeHookForStep(i0.postToolUse,{...J,tool_name:X,tool_input:Y,tool_output:Q,duration:W,tool_use_id:K});return HW(H,wP8($,X,i0.postToolUse,G?.additional_context)),G}catch(G){eU.warn($,"postToolUse hook error in MCP executor",{error:G instanceof Error?G.message:String(G)});return}}async firePostToolUseFailureAsync($,Z,J,X,Y,Q,W,K,H,G,q){try{let V=await Z.executeHookForStep(i0.postToolUseFailure,{...J,tool_name:X,tool_input:Y,error_message:Q,failure_type:W,duration:K,tool_use_id:H,is_interrupt:G});HW(q,wP8($,X,i0.postToolUseFailure,V?.additional_context))}catch(V){eU.warn($,"postToolUseFailure hook error in MCP executor",{error:V instanceof Error?V.message:String(V)})}}}var eU;var jP8=P(()=>{J6();F1();q9();$I1();bb0();wZ();OZ();eU=G1("hooks-exec:mcp")});class wl0{wrappedExecutor;constructor($,Z,J){this.wrappedExecutor=l6($,Z,J,br6)}execute($,Z,J){return this.wrappedExecutor.execute($,Z,J)}}class jl0{wrappedExecutor;constructor($,Z,J){this.wrappedExecutor=l6($,Z,J,fr6)}execute($,Z,J){return this.wrappedExecutor.execute($,Z,J)}}var br6,fr6;var MP8=P(()=>{wZ();OZ();BZ();br6={toolName:i8.ListMcpResources,createToolInput:($)=>({server:$.server}),applyUpdatedInput:($,Z)=>{if(typeof Z.server==="string")$.server=Z.server},createRejectedResult:($,Z)=>new y9({result:{case:"error",value:new j4({error:Z})}}),isSuccess:($)=>$.result.case==="success",getErrorMessage:($)=>{switch($.result.case){case"error":return $.result.value.error||"ListMcpResources error";case"rejected":return $.result.value.reason||"ListMcpResources rejected";default:return"Unknown error"}},createSuccessOutput:($,Z)=>{if(Z.result.case==="success")return{resources_count:Z.result.value.resources.length};return{success:!0}}};fr6={toolName:i8.FetchMcpResource,createToolInput:($)=>({server:$.server,uri:$.uri,download_path:$.downloadPath}),applyUpdatedInput:($,Z)=>{if(typeof Z.server==="string")$.server=Z.server;if(typeof Z.uri==="string")$.uri=Z.uri;if(typeof Z.download_path==="string")$.downloadPath=Z.download_path},createRejectedResult:($,Z)=>new F$({result:{case:"error",value:new AZ({error:Z})}}),isSuccess:($)=>$.result.case==="success",getErrorMessage:($)=>{switch($.result.case){case"error":return $.result.value.error||"ReadMcpResource error";case"rejected":return $.result.value.reason||"ReadMcpResource rejected";case"notFound":return"Resource not found";default:return"Unknown error"}},createSuccessOutput:($,Z)=>{if(Z.result.case==="success"){let J=Z.result.value;return{uri:$.uri,name:J.name,mime_type:J.mimeType,download_path:J.downloadPath,content_type:J.content.case,content_length:J.content.case==="text"?J.content.value.length:J.content.case==="blob"?J.content.value.length:void 0}}return{uri:$.uri,success:!0}}}});class mb0{wrappedExecutor;constructor($,Z,J){this.wrappedExecutor=new oS0(l6($,Z,J,hr6))}execute($,Z,J){return this.wrappedExecutor.execute($,Z,J)}}var hr6;var IP8=P(()=>{J6();q9();jN();OZ();bb0();BZ();hr6={toolName:i8.Read,getToolCallId:T5,createToolInput:($)=>({file_path:$.path}),applyUpdatedInput:($,Z)=>{if(typeof Z.file_path==="string")$.path=Z.file_path},createRejectedResult:($,Z)=>new N6({result:{case:"rejected",value:new S3({path:$.path,reason:Z})}}),isSuccess:($)=>$.result.case==="success",getErrorMessage:($)=>{switch($.result.case){case"error":return $.result.value.error||"Read error";case"rejected":return $.result.value.reason||"Read rejected";case"fileNotFound":return`File not found: ${$.result.value.path}`;case"permissionDenied":return`Permission denied: ${$.result.value.path}`;case"invalidFile":return`Invalid file: ${$.result.value.path}`;default:return"Unknown error"}},createSuccessOutput:($,Z)=>{if(Z.result.case==="success"){let J=Z.result.value.output.case==="content"?Z.result.value.output.value:"";return{file_path:$.path,content_length:J.length}}return{file_path:$.path,success:!0}},runPostExecutionHooks:async($)=>{let{args:Z,result:J,baseHookRequest:X,hookExecutor:Y,toolUseId:Q}=$;if(J.result.case!=="success"||Y.hasHooksForStep?.(i0.beforeReadFile)===!1)return;let W=J.result.value.output.case==="content"?J.result.value.output.value:"",K=await ZI1(()=>Y.executeHookForStep(i0.beforeReadFile,{...X,content:W,file_path:Z.path,attachments:[],tool_use_id:Q}),"File read");if(K?.permission==="deny"){let H=sq("File read",K.user_message);throw new T30(H)}return}}});class Ml0{wrappedExecutor;constructor($,Z,J){this.wrappedExecutor=l6($,Z,J,mr6)}execute($,Z,J){return this.wrappedExecutor.execute($,Z,J)}}var mr6;var TP8=P(()=>{kD();OZ();BZ();mr6={toolName:i8.RecordScreen,getToolCallId:T5,createToolInput:($)=>({mode:$.mode,save_as_filename:$.saveAsFilename}),createRejectedResult:($,Z)=>new I7({result:{case:"failure",value:new _W({error:Z,kind:R6.HOOK_REJECTED})}}),isSuccess:($)=>$.result.case!=="failure",getErrorMessage:($)=>{if($.result.case==="failure")return $.result.value.error||"RecordScreen failed";return"Unknown error"},createSuccessOutput:($,Z)=>({result_type:Z.result.case})}});function PP8($){if($.result.case==="success")return $.result.value.stdout+$.result.value.stderr;else if($.result.case==="failure")return $.result.value.stdout+$.result.value.stderr;return""}class Il0{wrappedExecutor;constructor($,Z,J){this.wrappedExecutor=l6($,Z,J,gr6)}execute($,Z,J){return this.wrappedExecutor.execute($,Z,J)}}var gr6;var EP8=P(()=>{J6();q9();q$();OZ();G71();BZ();q71();gr6={toolName:i8.Shell,createToolInput:($)=>{let Z=$.workingDirectory||"",J=$.timeout;return{command:$.command,cwd:Z,...typeof J==="number"&&J>0&&{timeout:J}}},applyUpdatedInput:($,Z)=>{if(typeof Z.command==="string")$.command=Z.command;if(typeof Z.cwd==="string")$.workingDirectory=Z.cwd;if(typeof Z.timeout==="number"&&Z.timeout>=0)$.timeout=Z.timeout},createRejectedResult:($,Z)=>new G6({result:{case:"rejected",value:new f6({command:$.command,workingDirectory:$.workingDirectory,reason:Z})}}),isSuccess:($)=>{if($.result.case==="success")return!0;if($.result.case==="failure"&&!$.result.value.aborted)return!0;return!1},getErrorMessage:($)=>{switch($.result.case){case"timeout":return`Command timed out after ${$.result.value.timeoutMs}ms`;case"spawnError":return $.result.value.error||"Failed to spawn command";case"failure":if($.result.value.aborted)return"Command was aborted";return"Command failed";case"rejected":return $.result.value.reason||"Command rejected";default:return"Unknown error"}},getFailureType:($)=>{if($.result.case==="timeout")return"timeout";return"error"},isInterrupt:($)=>{return $.result.case==="failure"&&$.result.value.aborted},createSuccessOutput:($,Z)=>{let J=PP8(Z),X=Z.result.case==="success"?0:1;return{output:J,exitCode:X}},getExtraHookFields:($)=>{return{cwd:$.workingDirectory||""}},runPreExecutionHooks:async($)=>{let{ctx:Z,args:J,baseHookRequest:X,hookExecutor:Y,toolUseId:Q}=$,W=J.workingDirectory||"";if(hG(Z,i0.beforeShellExecution))F20(J,await hb0({hookExecutor:Y,baseHookRequest:X,toolUseId:Q,command:J.command,cwd:W,sandbox:tU(J.requestedSandboxPolicy)}));return},runPostExecutionHooks:async($)=>{let{args:Z,result:J,baseHookRequest:X,hookExecutor:Y,executionDurationMs:Q,toolUseId:W}=$,K=PP8(J);await Y.executeHookForStep(i0.afterShellExecution,{...X,command:Z.command,output:K,duration:Q,sandbox:tU(Z.requestedSandboxPolicy),tool_use_id:W});return}}});class kP8{output="";exitEvent;onEvent($){if($.event.case==="stdout")this.output+=$.event.value.data;else if($.event.case==="stderr")this.output+=$.event.value.data;else if($.event.case==="exit")this.exitEvent=$.event.value}getOutput(){return this.output}isAborted(){return this.exitEvent?.aborted??!1}getExitCode(){return this.exitEvent?.code??0}}class Tl0{wrappedExecutor;constructor($,Z,J){this.wrappedExecutor=XI1($,Z,J,ur6)}execute($,Z,J){return this.wrappedExecutor.execute($,Z,J)}}var ur6;var RP8=P(()=>{J6();q9();q$();OZ();G71();BZ();q71();ur6={toolName:i8.Shell,createToolInput:($)=>{let Z=$.workingDirectory||"",J=$.timeout;return{command:$.command,cwd:Z,...typeof J==="number"&&J>0&&{timeout:J}}},applyUpdatedInput:($,Z)=>{if(typeof Z.command==="string")$.command=Z.command;if(typeof Z.cwd==="string")$.workingDirectory=Z.cwd;if(typeof Z.timeout==="number"&&Z.timeout>=0)$.timeout=Z.timeout},createRejectedEvent:($,Z)=>new b6({event:{case:"rejected",value:new f6({command:$.command,workingDirectory:$.workingDirectory,reason:Z})}}),createHookContextEvent:($)=>new b6({event:{case:"hookContext",value:new RW({hookAdditionalContexts:[...$]})}}),getExtraHookFields:($)=>{return{cwd:$.workingDirectory||""}},createResultCollector:()=>new kP8,createSuccessOutput:($,Z)=>({output:Z.getOutput(),exitCode:Z.getExitCode()}),isStreamSuccess:($)=>$.getExitCode()===0,getStreamErrorMessage:($,Z)=>{return Z.getOutput().trim()||`Command failed with exit code ${Z.getExitCode()}`},runPreExecutionHooks:async($)=>{let{ctx:Z,args:J,baseHookRequest:X,hookExecutor:Y,toolUseId:Q}=$,W=J.workingDirectory||"",K=tU(J.requestedSandboxPolicy);if(hG(Z,i0.beforeShellExecution))F20(J,await hb0({hookExecutor:Y,baseHookRequest:X,toolUseId:Q,command:J.command,cwd:W,sandbox:K}))},runPostExecutionHooks:async($)=>{let{args:Z,baseHookRequest:J,hookExecutor:X,collector:Y,executionDurationMs:Q,toolUseId:W}=$,K=tU(Z.requestedSandboxPolicy);await X.executeHookForStep(i0.afterShellExecution,{...J,command:Z.command,output:Y.getOutput(),duration:Q,sandbox:K,tool_use_id:W})}}});import{stat as cr6}from"fs/promises";function GI1($,Z){let J=sd0("","",$,Z,"","",{context:0,timeout:dr6});if(J===void 0)return[{old_string:"",new_string:Z}];if(J.hunks.length===0)return[];return J.hunks.map((X)=>{let Y=[],Q=[];for(let W of X.lines)if(W.startsWith("-"))Y.push(W.slice(1));else if(W.startsWith("+"))Q.push(W.slice(1));return{old_string:Y.join(` `),new_string:Q.join(` -`)}})}function pr6($){return{toolName:i8.Write,getToolCallId:T5,createToolInput:(Z)=>({file_path:Z.path,content:Z.fileText}),applyUpdatedInput:(Z,J)=>{if(typeof J.file_path==="string")Z.path=J.file_path},createRejectedResult:(Z,J)=>new z6({result:{case:"error",value:new L5({path:Z.path,error:J})}}),isSuccess:(Z)=>Z.result.case==="success",getErrorMessage:(Z)=>{if(Z.result.case==="error")return Z.result.value.error||"Write error";return"Unknown error"},createSuccessOutput:(Z)=>({file_path:Z.path,success:!0}),runPreExecutionHooks:async(Z)=>{let{args:J,hookExecutor:X,toolUseId:Y}=Z;if(X.hasHooksForStep?.(i0.afterFileEdit)===!1)return;let Q,W=!1;try{if((await cr6(J.path)).size>HI1)W=!0;else Q=await K$(J.path)}catch(K){}$.set(Y,{contentBeforeWrite:Q,fileTooLarge:W});return},runCleanup:(Z)=>{$.delete(Z)},runPostExecutionHooks:async(Z)=>{let{args:J,result:X,baseHookRequest:Y,hookExecutor:Q,toolUseId:W}=Z,K=$.get(W);if(X.result.case!=="success"||Q.hasHooksForStep?.(i0.afterFileEdit)===!1)return;let{contentBeforeWrite:H,fileTooLarge:G}=K??{fileTooLarge:!1},q;if(G)q=[{old_string:"",new_string:J.fileText}];else if(H===void 0)q=[{old_string:"",new_string:J.fileText}];else if(H===J.fileText)q=[];else q=GI1(H,J.fileText);let V={...Y,file_path:J.path,edits:q},O=await Q.executeHookForStep(i0.afterFileEdit,V);if(J.returnFileContentAfterWrite&&O!==void 0){let F=X.result.value.path;try{let N=await K$(F),L=SJ(N),U=Buffer.byteLength(N,"utf8");return new z6({result:{case:"success",value:new $Q({path:X.result.value.path,linesCreated:L,fileSize:U,fileContentAfterWrite:N})}})}catch(N){return}}return}}}class Pl0{wrappedExecutor;constructor($,Z,J){let X=new Map;this.wrappedExecutor=l6($,Z,J,pr6(X))}execute($,Z,J){return this.wrappedExecutor.execute($,Z,J)}}var HI1=262144,dr6=50;var CP8=P(()=>{q9();ZG();o9();$U1();OZ();BZ()});var qI1=P(()=>{OP8();FP8();NP8();LP8();UP8();DP8();AP8();jP8();MP8();IP8();TP8();EP8();RP8();CP8()});function l7($,Z,J){return Z===$.symbol}function _P8($,Z,J){if(l7(mG,$,Z))return new Il0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(a9,$,Z))return new Tl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(D20,$,Z))return new Pl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(a3,$,Z))return new Al0(Z,J.hookExecutor,J.baseHookRequestExtractor,J.mcpLease,J.hooksConfigLease);if(l7(tS0,$,Z))return new mb0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(xm0,$,Z))return new mb0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(_m0,$,Z))return new Dl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(Mm0,$,Z))return new Ul0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(wm0,$,Z))return new Ll0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(V20,$,Z))return new Fl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(B20,$,Z))return new Nl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(vm0,$,Z))return new wl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(ym0,$,Z))return new jl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(xG,$,Z))return new Vl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(bG,$,Z))return new Bl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(Am0,$,Z))return new Ol0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(mm0,$,Z))return new Ml0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(r9,$,Z)&&(J.hooksAdditionalContextPromise||J.hooksConfigLease))return new H71(Z,J.hooksAdditionalContextPromise??Promise.resolve(void 0),J.teamHooksReadyPromise,J.hooksConfigLease);return}function lr6($,Z){if($.symbol!==qs0.symbol)return;return new Cm0(Z)}function ir6($,Z,J){let X=_P8($.symbol,Z,J);if(X!==void 0)return X;return Z}class V71{innerAccessor;hookExecutor;baseHookRequestExtractor;mcpLease;hooksAdditionalContextPromise;teamHooksReadyPromise;hooksConfigLease;constructor($,Z,J,X,Y,Q,W){this.innerAccessor=$;this.hookExecutor=Z;this.baseHookRequestExtractor=J;this.mcpLease=X;this.hooksAdditionalContextPromise=Y;this.teamHooksReadyPromise=Q;this.hooksConfigLease=W}get($){let Z=lr6($,this.hookExecutor);if(Z!==void 0)return Z;return ir6($,this.innerAccessor.get($),{hookExecutor:this.hookExecutor,baseHookRequestExtractor:this.baseHookRequestExtractor,mcpLease:this.mcpLease,hooksAdditionalContextPromise:this.hooksAdditionalContextPromise,teamHooksReadyPromise:this.teamHooksReadyPromise,hooksConfigLease:this.hooksConfigLease})}*entries(){for(let[Z,J]of this.innerAccessor.entries()){let X=_P8(Z.symbol,J,{hookExecutor:this.hookExecutor,baseHookRequestExtractor:this.baseHookRequestExtractor,mcpLease:this.mcpLease,hooksAdditionalContextPromise:this.hooksAdditionalContextPromise,teamHooksReadyPromise:this.teamHooksReadyPromise,hooksConfigLease:this.hooksConfigLease});yield[Z,X??J]}yield[qs0,new Cm0(this.hookExecutor)]}}var SP8=P(()=>{J6();WI1();qI1()});var vP8=P(()=>{X2()});var yP8=P(()=>{nI8();AT8();eT8();Gl0();$P8();OZ();VP8();bb0();BP8();sM1();WI1();SP8();QI1();qI1();BZ();vP8()});import{spawn as nr6}from"child_process";import{homedir as xP8}from"os";import{join as El0}from"path";function rr6($){if(process.platform==="win32")return{executable:FQ(),args:[...Pl1,"-Command",$]};return{executable:process.env.SHELL||"/bin/sh",args:["-lc",$]}}function bP8($=process.cwd()){let Z=$;return{async getCwd(){return Z},clone(X){return bP8(X??Z)},async*execute(X,Y,Q={}){let W=Q.workingDirectory??Z;Z=W;let K=rr6(Y),H=nr6(K.executable,[...K.args],{cwd:W,env:{...process.env,...Q.env??{}},signal:Q.signal,stdio:[Q.pipeStdin===!0?"pipe":"ignore","pipe","pipe"]}),G=[],q,V,O=!1,F=()=>{q?.(),q=void 0},N=(L)=>{G.push(L),F()};H.on("spawn",()=>{if(Q.pipeStdin===!0)N({type:"stdin_ready",stdin:H.stdin??void 0})}),H.stdout?.setEncoding("utf8"),H.stdout?.on("data",(L)=>{N({type:"stdout",data:String(L)})}),H.stderr?.setEncoding("utf8"),H.stderr?.on("data",(L)=>{N({type:"stderr",data:String(L)})}),H.on("error",(L)=>{V=L,O=!0,F()}),H.on("close",(L)=>{N({type:"exit",code:L}),O=!0});while(!O||G.length>0){if(G.length===0){await new Promise((L)=>{q=L});continue}yield G.shift()}if(V!==void 0)throw V}}}function sr6($){return $.projectRoot??$.workingDirectory??$.workspaceRoots[0]??process.cwd()}function or6($,Z){let J=$.projectRoot??$.workingDirectory??$.workspaceRoots[0],X=Z.includeProjectHooks??!0,Y=Z.includeUserHooks??!0;return{enterpriseConfigPath:Z.includeEnterpriseHooks??!0?nM1():void 0,userConfigPath:Y?El0(xP8(),".cursor","hooks.json"):void 0,claudeUserConfigPath:Y?El0(xP8(),".claude","settings.json"):void 0,projectConfigPath:X&&J!==void 0?El0(J,".cursor","hooks.json"):void 0,claudeProjectConfigPath:X&&J!==void 0?El0(J,".claude","settings.json"):void 0,claudeProjectLocalConfigPath:X&&J!==void 0?El0(J,".claude","settings.local.json"):void 0}}function tr6($){return Object.freeze({...ar6,...$.globalContext??{}})}function kl0($,Z,...J){for(let X of J){let Y=Z($[X]);if(Y!==void 0)return Y}return}function B71($){return typeof $==="string"&&$.length>0?$:void 0}function er6($){return typeof $==="object"&&$!==null&&typeof $.id==="string"&&typeof $.value==="string"}function $s6($){if(!Array.isArray($))return;if(!$.every(er6))return;return $.map((Z)=>({id:Z.id,value:Z.value}))}function Zs6($,Z){let J=kl0(Z,B71,"conversationId","conversation_id")??$.sessionId??"",X=kl0(Z,B71,"generationId","generation_id")??J,Y=kl0(Z,B71,"model")??"unknown",Q=kl0(Z,B71,"modelId","model_id"),W=kl0(Z,$s6,"modelParams","model_params");return{conversation_id:J,generation_id:X,model:Y,...g5({modelId:Q,modelParams:W})}}function Js6($){return typeof $==="object"&&$!==null&&"get"in $&&typeof $.get==="function"&&"entries"in $&&typeof $.entries==="function"}function Xs6($){return typeof $==="object"&&$!==null&&"hooksConfigLease"in $&&"createSessionRuntime"in $&&typeof $.createSessionRuntime==="function"}class fP8{innerAccessor;sessionHooksRuntime;constructor($,Z){this.innerAccessor=$;this.sessionHooksRuntime=Z}get($){return this.innerAccessor.get($)}entries(){return this.innerAccessor.entries()}async dispose(){await this.sessionHooksRuntime.dispose()}}async function Ys6($,Z={}){let J=await new I30(new z71,or6($,Z)).load(),X=new X71(J),Y=sr6($),Q=tr6(Z);return{projectDir:$.projectRoot,workspacePath:Y,hooksConfig:J,hooksConfigLease:X,globalContext:Q,createSessionRuntime(){let W=new J71(J,Y,Q,(Z.createTerminalExecutor??bP8)(),Z.promptHookClient,void 0,void 0,{enableClaudeNestedHookSpecificOutputCompatibility:!0,commandHookPayloadTransport:Tl1(Z.useCommandHookStdinTransport)});return{hookExecutor:W,hooksConfigLease:X,async dispose(){W.clearSessionEnvironment()}}},async dispose(){}}}function hP8($={}){return{createHooksRuntime(Z){return Ys6(Z.workspaceState,$)}}}function mP8(){return{wrapResources($){let Z=$.workspaceServices.hooksRuntime;if($.options.excludeHooks===!0||!Xs6(Z)||!Js6($.resources))return $.resources;let J=Z.createSessionRuntime({sessionState:$.sessionState,metadata:$.metadata});return new fP8(new V71($.resources,J.hookExecutor,()=>Zs6($.sessionState,$.metadata),$.workspaceServices.mcpLease,void 0,void 0,Z.hooksConfigLease),J)}}}var ar6;var gP8=P(()=>{q9();yP8();K7();ar6={cursor_version:process.env.AGENT_CLI_STATIC_VERSION??"1.0.0",user_email:null}});function Qs6($){return typeof $==="object"&&$!==null&&"dispose"in $&&typeof $.dispose==="function"}async function GW($){if(Qs6($))await $.dispose()}import{realpath as pP8}from"fs/promises";import{homedir as Ws6}from"os";import{createClient as Ks6}from"@connectrpc/connect";function zs6($){if($.workspaceRoots.length>0)return[...$.workspaceRoots];let Z=$.projectRoot??$.workingDirectory;return Z!==void 0?[Z]:[]}function lP8($={}){let Z=$.getThirdPartyExtensibilityEnabled??(()=>!0),J=$.importThirdPartyPlugins??!1,X=$.includeProjectExtensibility??!0,Y=$.includeUserExtensibility??!0,Q=$.includeManagedSkills??!0,W=$.includePluginExtensibility??!0,K=new _K,H=Ws6(),G=AK(H).dirPath,q,V=!0;return{async prepareLocalExtensibility(){V=Q&&await Bs6($.dashboardTransport)},async loadLocalExtensibility(O){let F=O.workspaceState,N=zs6(F);if(N.length===0)return q=void 0,{cursorRulesService:dP8(),getAgentSkills:async(l)=>[]};let L=k1(),U=$.loadNestedRules??!0,D=X?N.map((y)=>new zU(L,K,y,U,Z,void 0)):[],j=D.length===0?dP8():D.length===1?D[0]:new Gx0(D,()=>Kx0),w=Hs6(j,{allowedRoots:X?N:[],excludedRoots:[]}),k=new E11(L,X?N:[],H,K,U,void 0,Z,Promise.resolve(),"sdk"),T=Gs6(k,{allowedRoots:[...X?N:[],...Y?[H]:[],...V?[G]:[]],excludedRoots:V?[]:[G]}),I=X?N.map((y)=>new R11(y,Z)):[],M=I.length===0?new HU:I.length===1?I[0]:new kW0(I),C=a51(O.services.pluginBootstrapOutputs),v=C&&W?new k11(L,()=>({importThirdPartyPlugins:J}),void 0,C.pluginsService):void 0,R=C&&W?new C11(()=>({importThirdPartyPlugins:J}),C.pluginsService):void 0,S=new Gx0([w,T,...v?[v]:[]],()=>Kx0),h=new op0([T,...v?[v]:[]],()=>[],()=>({workspacePaths:X?N:[],userHomeDirectory:H,agentStoreSkillsDirs:[]})),b=new kW0([M,...R?[R]:[]]);return q={localRulesService:w,localSkillsService:T,localSubagentsService:M,pluginSkillsService:v,pluginSubagentsService:R,mergedCursorRulesService:S,mergedAgentSkillsService:h,mergedSubagentsService:b},{cursorRulesService:S,getAgentSkills:(y)=>h.getAllAgentSkills(y),subagentsService:b}},async disposeLocalExtensibility(){if(!q)return;let O=q;q=void 0,await Vs6(O)}}}function Hs6($,Z){let J=iP8(Z);return{async getAllCursorRules(X){return VI1(await $.getAllCursorRules(X),J)},reload(X){$.reload(X)},onDidChangeRules(X){return $.onDidChangeRules(X)},dispose(){$.dispose()}}}function Gs6($,Z){let J=iP8(Z);return{async getAllCursorRules(X){return VI1(await $.getAllCursorRules(X),J)},async getAllAgentSkills(X){return VI1(await $.getAllAgentSkills(X),J)},reload(X){$.reload(X)},onDidChangeRules(X){return $.onDidChangeRules(X)},onDidChangeSkills(X){return $.onDidChangeSkills(X)},dispose(){$.dispose()}}}function iP8($){let Z=Promise.all($.allowedRoots.map(cP8)),J=Promise.all($.excludedRoots.map(cP8));return async(Y)=>{let[Q,W,K]=await Promise.all([qs6(Y.fullPath),Z,J]);if(Q===void 0)return!1;if(K.some((H)=>uP8(Q,H)))return!1;return W.some((H)=>uP8(Q,H))}}async function VI1($,Z){let J=await Promise.all($.map(Z));return $.filter((X,Y)=>J[Y])}function uP8($,Z){if($===Z)return!0;let J=`${Z}/`;return $.startsWith(J)}function BI1($){return $.replace(/\\/g,"/").replace(/\/+$/,"")}async function cP8($){try{return BI1(await pP8($))}catch{return BI1($)}}async function qs6($){try{return BI1(await pP8($))}catch{return}}function dP8(){return{async getAllCursorRules(){return[]},reload(){},onDidChangeRules(){return()=>{}},dispose(){}}}async function Vs6($){let Z,J=[$.mergedSubagentsService,$.mergedAgentSkillsService,$.mergedCursorRulesService,$.pluginSubagentsService,$.pluginSkillsService,$.localSubagentsService,$.localSkillsService,$.localRulesService];for(let X of J)try{await GW(X)}catch(Y){Z??=Y}if(Z!==void 0)throw Z}async function Bs6($){if(!$)return!1;let Z=Ks6(P3,$);return(await IM1(k1(),{getManagedSkills:async()=>{return(await Z.getManagedSkills(new TH({}))).skills??[]}})).status==="synced"}var nP8=P(()=>{F1();nq();VC0();X2()});import{homedir as Os6}from"os";import{join as Fs6}from"path";import{createClient as Ns6}from"@connectrpc/connect";function Ls6(){return{log($,Z,J){switch($){case"warn":Z6.warn("[local-plugins-bootstrap]",Z,J??{});break;case"error":Z6.error("[local-plugins-bootstrap]",Z,J??{});break;default:break}},increment(){},distribution(){},captureException($,Z){Z6.error("[local-plugins-bootstrap] Unexpected plugin exception:",$,Z??{})}}}function sP8($={}){let Z=$.userHomeDirectory??Os6(),J=$.importThirdPartyPlugins??!1,X=$.pluginLogger??Ls6(),Y=rP8($.marketplaceOptions),Q=$.dashboardTransport!==void 0,W=$.loadCursorFirstParty??(Y||Q);return{async loadPluginBootstrapOutputs(K){let H=Us6(K.workspaceState),{discoveredEntries:G,failures:q}=await As6(H),V=$.marketplaceOptions??($.dashboardTransport?Ds6({dashboardTransport:$.dashboardTransport,workspacePath:H,userHomeDirectory:Z}):void 0),O=rP8(V),F=new h51(H!==void 0?[H]:[],Z,()=>({importThirdPartyPlugins:J,loadCursorFirstParty:W}),V,X),N=[],L=[...q];try{N=await F.getAllEnabledPlugins()}catch(D){L.push({stage:"resolution",source:"plugin-loader",message:D instanceof Error?`Failed to load plugins: ${D.message}`:`Failed to load plugins: ${String(D)}`,detail:D})}if(G.length>0&&!O)L.push({stage:"resolution",source:"plugin-loader",message:"Project plugin entries were discovered, but no marketplace-backed project plugin source was configured. Those entries remain available through discoveredEntries only.",detail:{workspacePath:H,discoveredEntryCount:G.length}});let U={kind:gI8,discoveredEntries:G,loadedPlugins:N,loadFailures:F.getLoadFailures(),bootstrapFailures:L,pluginsService:F,async dispose(){}};for(let D of L)Z6.warn("[local-plugins-bootstrap] Plugin bootstrap failure:",{workspacePath:H,stage:D.stage,source:D.source,message:D.message,detail:D.detail});for(let D of U.loadFailures)Z6.warn("[local-plugins-bootstrap] Plugin load failure:",{workspacePath:H,pluginName:D.pluginName,pluginId:D.pluginId,marketplaceName:D.marketplaceName,errorType:D.errorType,errorMessage:D.errorMessage});return[U]}}}function Us6($){return $.projectRoot??$.workspaceRoots[0]??$.workingDirectory}function rP8($){if($===void 0)return!1;return Array.isArray($)?$.length>0:!0}function Ds6($){let Z=Fs6($.userHomeDirectory,".cursor","plugins","marketplaces"),J=Ns6(P3,$.dashboardTransport),X=(H,{signal:G})=>J.downloadPluginContent(H,{signal:G}),Y=new oy0,Q=$11(async()=>{try{return await J.getEffectiveUserPlugins(new jH(aP8))}catch{return{plugins:[]}}},{marketplaceCacheRoot:Z,listOptions:{allowedMarketplaceNames:["cursor-public"]},downloadPluginContent:X,contentRetries:Y.forListing("account")}),W=$.workspacePath,K=$11(async()=>{if(W===void 0)return{plugins:[]};try{let H=await O11(W);if(H.length===0)return{plugins:[]};let G=H.filter((N)=>N.entry.gitUrl),q=H.filter((N)=>!N.entry.gitUrl),O=G.filter(({entry:N})=>{let L=N.gitUrl;return!L||B11(L)}).map(({key:N,entry:L})=>{let U=F11(N),D=L.gitUrl;return{plugin:{name:U.name,gitUrl:D,gitRef:L.gitRef,gitPath:L.gitPath,marketplace:{name:U.marketplaceName,gitUrl:D,gitRef:L.gitRef}},isEnabled:!0}}),F=[];if(q.length>0)try{let N=q.map((U)=>{let D=F11(U.key);return new hF({name:D.name,marketplaceName:D.marketplaceName})});F=(await J.resolvePluginsByRef(new MH({refs:N,...aP8}))).plugins?.map((U)=>({plugin:U,isEnabled:!0}))??[]}catch{}return{plugins:[...O,...F]}}catch{return{plugins:[]}}},{marketplaceCacheRoot:Z,listOptions:{allowedMarketplaceNames:["cursor-public"]},downloadPluginContent:X,contentRetries:Y.forListing("project")});return[{client:Q,userId:"",cacheManager:new wW0($.userHomeDirectory),pruneOldVersions:!0},{client:K,userId:"",cacheManager:new wW0($.userHomeDirectory),pruneOldVersions:!0}]}async function As6($){if($===void 0)return{discoveredEntries:[],failures:[]};try{return{discoveredEntries:(await O11($)).map(({key:J,entry:X})=>({source:"project-settings",workspacePath:$,key:J,entry:X})),failures:[]}}catch(Z){return{discoveredEntries:[],failures:[{stage:"discovery",source:"project-settings",message:Z instanceof Error?`Failed to read project plugin settings: ${Z.message}`:`Failed to read project plugin settings: ${String(Z)}`,detail:Z}]}}}var aP8;var oP8=P(()=>{TW0();nq();VC0();X2();l3();aP8={supportsBackendContent:!0}});class ZE8{async getAllCursorRules($){return[]}reload($){}dispose(){}onDidChangeRules($){return()=>{}}}function js6($){return $==="/"||$==="\\"}function OI1($){if($.length<=1)return $;let Z=$.length;while(Z>1&&js6($[Z-1])){if(Z===3&&$[1]===":")break;Z-=1}return $.slice(0,Z)}function O71($){let Z=OI1($).replaceAll("\\","/");if(/^[A-Za-z]:\/$/.test(Z))return Z.slice(0,-1);return Z}function tP8($){let Z=OI1($.reportedWorkspacePath);if($.suffix==="")return Z;let J=Z.replaceAll("\\","/"),X=J==="/"?$.suffix:`${J}${$.suffix}`;return Z.includes("\\")?X.replaceAll("/","\\"):X}function eP8($){let Z=O71($.value),J=$.roots.filter((X)=>X.host.length>0).sort((X,Y)=>O71(Y.host).length-O71(X.host).length);for(let X of J){let Y=O71(X.host);if(Z===Y)return tP8({reportedWorkspacePath:X.reported,suffix:""});let Q=Y==="/"?"/":`${Y}/`;if(Z.startsWith(Q)){let W=Y==="/"?Z:Z.slice(Y.length);return tP8({reportedWorkspacePath:X.reported,suffix:W})}}return}function Ms6($,Z){if($.result.case!=="success"||$.result.value.requestContext?.env===void 0)return $;let J=$.clone();if(J.result.case!=="success")return $;let X=J.result.value.requestContext?.env;if(X===void 0)return J;let{roots:Y,reportedWorkspacePath:Q}=Z;X.workspacePaths=X.workspacePaths.map((W)=>eP8({value:W,roots:Y})??W);for(let W of ws6){let K=X[W];if(K===void 0||K==="")continue;let H=eP8({value:K,roots:Y});X[W]=W==="processWorkingDirectory"&&Q!==void 0?H??OI1(Q):H??K}return J}function Is6($,Z){let J=$.get(r9);if(J===void 0)return;let{reportedWorkspacePath:X,reportedProjectFolder:Y}=Z,Q=X===void 0?[]:Z.workspacePaths.map((K)=>({host:K,reported:X})),W=Y??X;if(W!==void 0)Q.push({host:Z.projectDir,reported:W});$.register(r9,{execute:async(K,H,G)=>{let q=await J.execute(K,H,G);return Ms6(q,{roots:Q,reportedWorkspacePath:X})}})}async function Ts6($){if($===void 0)return $E8;try{let Z=await $();return{powershellUtf8Console:Z.powershellUtf8Console,powershellUtf8ChildEnv:Z.powershellUtf8ChildEnv}}catch{return $E8}}async function Ps6($,Z){if($===void 0)return{};if(typeof $==="function")return await $({sessionId:Z.sessionState.sessionId,metadata:Z.metadata});return $}function XE8($){let Z=new _K;return{async createResources(J){let X=$.createSessionDependencies?.(J)??{pendingDecisionStore:$.pendingDecisionStore,fileChangeTracker:$.fileChangeTracker,permissionsService:$.permissionsService};if(!X.pendingDecisionStore||!X.fileChangeTracker||!X.permissionsService)throw Error("Local resource provider factory requires either shared dependencies or a per-session dependency factory.");let Y=J.workspaceServices.cursorRulesService??new ZE8,Q=J.workspaceServices.subagentsService??new HU,W=J.workspaceServices.mcpLease??new uU,K=J.options.excludeProjectMcp===!0,H=J.options.mcpServersOverride===void 0&&!K?void 0:$.createSessionMcpLease!==void 0?await $.createSessionMcpLease(J,J.options.mcpServersOverride):K?new uU:void 0,q=DL1(H??W,J.options.extraMcpTools??[]);try{let V=await Ps6(J.options.localResourceProviderOptions,J),O=await Ts6($.getPowershellUtf8Options),F={pendingDecisionStore:X.pendingDecisionStore,fileChangeTracker:X.fileChangeTracker,gitExecutor:Z,ignoreService:$.ignoreService,grepProvider:$.grepProvider,permissionsService:X.permissionsService,workspacePaths:$.workspacePaths,diagnosticsProvider:$.diagnosticsProvider,mcpLease:q,mcpStateAccessor:$.createMcpStateAccessor?.(q,J.options),cursorRulesService:Y,subagentsService:Q,repositoryProvider:$.repositoryProvider,projectDir:$.projectDir,shellManager:$.shellManager,_defaultSandboxPolicy:$.defaultSandboxPolicy??{type:"insecure_none"},_defaultSandboxPolicySources:$.defaultSandboxPolicySources,getSandboxEnabled:$.getSandboxEnabled,getSandboxSupported:$.getSandboxSupported,getNetworkAllowlistInfo:$.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:$.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:$.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:$.getMockPromptTime,mcpFileOutputThresholdBytes:$.mcpFileOutputThresholdBytes,mcpMetaToolEnabled:$.mcpMetaToolEnabled,getAgentSkills:J.workspaceServices.getAgentSkills,powershellUtf8Console:O.powershellUtf8Console,powershellUtf8ChildEnv:O.powershellUtf8ChildEnv,...V},N=H===void 0?new j30(F):new JE8(F,H);if(J.options.reportedWorkspacePath!==void 0||J.options.reportedProjectFolder!==void 0)Is6(N,{reportedWorkspacePath:J.options.reportedWorkspacePath,reportedProjectFolder:J.options.reportedProjectFolder,workspacePaths:F.workspacePaths,projectDir:F.projectDir});return N}catch(V){throw await GW(H),V}}}}var ws6,$E8,JE8;var YE8=P(()=>{J6();nq();pU();ws6=["projectFolder","terminalsFolder","agentSharedNotesFolder","agentConversationNotesFolder","agentTranscriptsFolder","processWorkingDirectory","artifactsFolder"];$E8={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1};JE8=class JE8 extends j30{sessionMcpLease;constructor($,Z){super($);this.sessionMcpLease=Z}async dispose(){try{await super.dispose()}finally{await GW(this.sessionMcpLease)}}}});function QE8($){if(typeof $==="object"&&$!==null||typeof $==="function")KE8.add($)}function WE8($){return(typeof $==="object"&&$!==null||typeof $==="function")&&KE8.has($)}function Es6($,Z){return AggregateError([Z],"Workspace service loading failed and resource cleanup also failed.",{cause:$})}function ks6($,Z){let J=Object.keys(Z).filter((X)=>!FI1.includes(X));if(J.length>0)throw Error(`Workspace service contributors may only provide ${FI1.join(", ")}. Received unsupported service keys: ${J.join(", ")}.`);for(let X of FI1)if(Object.hasOwn(Z,X))$[X]=Z[X]}async function Rs6($){let Z;for(let J=$.length-1;J>=0;J-=1)try{await GW($[J])}catch(X){Z??=X}if(Z!==void 0)throw Z}async function NI1($,Z,J){let X={config:void 0,plugins:[],pluginBootstrapOutputs:[],cursorRulesService:void 0,getAgentSkills:void 0,subagentsService:void 0,mcpLease:void 0,hooksRuntime:void 0};try{X.config=$.config?await $.config.loadConfig(Z):void 0,X.plugins=$.plugins?await $.plugins.loadPlugins(Z):[];let Y=()=>({workspaceState:Z,policy:J,services:X});if(X.pluginBootstrapOutputs=$.pluginBootstrap?await $.pluginBootstrap.loadPluginBootstrapOutputs(Y()):X.pluginBootstrapOutputs,X.mcpLease=$.mcp?await $.mcp.createLease(Y()):void 0,X.hooksRuntime=$.hooks?await $.hooks.createHooksRuntime(Y()):void 0,$.localExtensibility?.prepareLocalExtensibility)await $.localExtensibility.prepareLocalExtensibility(Y());let Q=$.localExtensibility?await $.localExtensibility.loadLocalExtensibility(Y()):void 0;if(Q!==void 0)QE8(Q.cursorRulesService),QE8(Q.subagentsService),Object.assign(X,Q);for(let W of $.workspaceServicesContributors??[]){let K=await W.contributeServices(Y());if(K!==void 0)ks6(X,K)}return X}catch(Y){try{await Rl0(X,{disposeLocalExtensibility:$.localExtensibility===void 0?void 0:()=>$.localExtensibility?.disposeLocalExtensibility?.()})}catch(Q){throw Es6(Y,Q)}throw Y}}async function Rl0($,Z){let J=Z?.preserveSharedContributorsFrom,X,Y=async(Q)=>{try{await GW(Q)}catch(W){X??=W}};if($.subagentsService!==J?.subagentsService&&!WE8($.subagentsService))await Y($.subagentsService);if($.cursorRulesService!==J?.cursorRulesService&&!WE8($.cursorRulesService))await Y($.cursorRulesService);if(Z?.disposeLocalExtensibility)try{await Z.disposeLocalExtensibility()}catch(Q){X??=Q}await Y($.hooksRuntime),await Y($.mcpLease);try{await Rs6($.pluginBootstrapOutputs)}catch(Q){X??=Q}if(X!==void 0)throw X}var FI1,KE8;var LI1=P(()=>{FI1=["cursorRulesService","getAgentSkills","subagentsService"],KE8=new WeakSet});function Cs6($,Z){return AggregateError([Z],"Session creation failed and resource cleanup also failed.",{cause:$})}async function zE8($){let Z=new Set,J;for(let X=$.length-1;X>=0;X-=1){let Y=$[X];if(Z.has(Y))continue;Z.add(Y);try{await GW(Y)}catch(Q){J??=Q}}if(J!==void 0)throw J}async function HE8($){let Z={sessionId:$.options?.sessionId??L6(),createdAt:new Date},J=Object.freeze({...$.options?.metadata??{}}),X={options:$.options??{},workspaceState:$.workspaceState,workspaceServices:$.workspaceServices,policy:$.policy,sessionState:Z,metadata:J,getAgentSkills:$.workspaceServices.getAgentSkills},Y=void 0,Q=void 0,W=[];try{Y=$.adapters.resourceFactory?await $.adapters.resourceFactory.createResources(X):void 0,Q=Y,W.push(Y);for(let G of $.adapters.resourceWrappers??[])Q=await G.wrapResources({...X,baseResources:Y,resources:Q}),W.push(Q);await $.adapters.lifecycle?.onSessionCreated?.(Z)}catch(G){try{await zE8(W)}catch(q){throw Cs6(G,q)}throw G}let K={base:Y,wrapped:Q},H=!1;return{state:Z,resources:K,metadata:J,workspaceServices:$.workspaceServices,policy:$.policy,async dispose(){if(H)return;H=!0;try{await zE8(W)}finally{await $.adapters.lifecycle?.onSessionDisposed?.(Z)}}}}var UI1=P(()=>{B1()});function F71($){if($===void 0||$.length===0)return DI1([]);for(let J of $)if(!_s6.has(J))throw Error(`Unsupported setting source "${J}"`);if($.includes("all")){if($.length>1)throw Error('settingSources cannot mix "all" with individual setting sources');return{...DI1(GE8),all:!0}}let Z=$.filter((J)=>J!=="all");return DI1(Z)}function N7($,Z){return $[Z]}function DI1($){let Z=new Set($);return{project:Z.has("project"),user:Z.has("user"),team:Z.has("team"),mdm:Z.has("mdm"),plugins:Z.has("plugins"),all:!1}}var GE8,_s6;var qE8=P(()=>{GE8=["project","user","team","mdm","plugins"],_s6=new Set([...GE8,"all"])});function BE8($={}){let Z=Object.freeze({...VE8.metadata,...$.metadata}),J={...VE8,...$,metadata:Z};return{name:"permissive-sdk-local",resolvePolicy(){return J}}}async function OE8($,Z){return $.resolvePolicy(Z)}var Ss6,VE8;var FE8=P(()=>{Ss6=Object.freeze({}),VE8=Object.freeze({allowMcpServers:!0,allowPlugins:!0,allowBackgroundSessions:!0,requireMcpApproval:!1,maxParallelSessions:void 0,sandboxMode:void 0,metadata:Ss6})});var AI1=P(()=>{FE8()});async function NE8($={}){let Z=RI8($.adapters),J=await Z.workspace.resolveWorkspaceState({workingDirectory:$.workingDirectory,projectRoot:$.projectRoot,projectDirectory:$.projectDirectory,workspaceRoots:$.workspaceRoots}),X=await OE8($.policyAdapter??BE8(),{workspaceState:J}),Y=await NI1(Z,J,X),Q=!1,W=Promise.resolve(),K=(q)=>{let V=W.then(q);return W=V.catch(()=>{}),V},H=Z.localExtensibility,G=H===void 0?void 0:()=>H.disposeLocalExtensibility?.();return{state:J,get services(){return Y},policy:X,async createSessionRuntime(q={}){if(Q)throw Error("Cannot create a session runtime after the workspace runtime has been disposed.");return HE8({options:q,workspaceState:J,workspaceServices:Y,policy:X,adapters:Z})},async reload(){if(Q)return;await K(async()=>{if(Q)return;let q=Y,V=await NI1(Z,J,X);if(Q){await Rl0(V,{disposeLocalExtensibility:G});return}Y=V,await Rl0(q,{preserveSharedContributorsFrom:V,disposeLocalExtensibility:G}),await Z.lifecycle?.onWorkspaceReload?.(J)})},async dispose(){if(Q)return;Q=!0,await K(async()=>{try{await Rl0(Y,{disposeLocalExtensibility:G})}finally{await Z.lifecycle?.dispose()}})}}}var wI1=P(()=>{yM1();AI1();LI1();UI1()});var jI1=P(()=>{iI8();gP8();nP8();oP8();YE8();LI1();UI1();qE8();wI1()});import{resolve as vs6}from"path";class LE8{async requestApproval($){return{approved:!0}}}class UE8{approvalMode;userConfiguredPolicy;teamSettingsService;respectAdminControls;constructor($,Z,J,X){this.approvalMode=$;this.userConfiguredPolicy=Z;this.teamSettingsService=J;this.respectAdminControls=X}async getPermissions(){let $=this.respectAdminControls&&this.userConfiguredPolicy.type!=="insecure_none"?(await this.teamSettingsService.getSandboxingControls()).sandboxingDisabled:!1;return{allow:[],deny:[],approvalMode:this.approvalMode,userConfiguredPolicy:$?{type:"insecure_none"}:this.userConfiguredPolicy}}async updatePermissions(){}}class DE8{async open($,Z){}async getDiagnostics($,Z){return[]}}class AE8{async getCodebaseReference($,Z){return}}class wE8{inner;allowlistReports;constructor($,Z){this.inner=$;this.allowlistReports=Z}async getState($){let Z=await this.inner.getState($);return await this.reportAllowlists($),{...Z,servers:Z.servers.filter((J)=>J.status!=="needsAuth")}}async reportAllowlists($){if(this.allowlistReports===void 0)return;let{mcpLease:Z,onMcpAllowlistInUse:J,onMcpServerBlockedByAllowlist:X}=this.allowlistReports,Y;try{Y=await Z.getClients($)}catch(Q){Z6.warn("[sdk-mcp-state] Could not read the MCP allowlist in use:",Q);return}for(let[Q,W]of Object.entries(Y))try{if(J!==void 0){let K=await W.getAllowlistInUse?.();if(K!==void 0)J({serverName:Q,allowlist:K})}if(X!==void 0){let K=await W.getAllowlistRefusal?.();if(K!==void 0)X({serverName:Q,refusal:K})}}catch(K){Z6.warn("[sdk-mcp-state] Could not read the MCP allowlist in use:",K)}}}class N71{subagents;constructor($){this.subagents=$.map((Z)=>new NX({fullPath:`sdk-inline://${Z.name}`,name:Z.name,description:Z.description,tools:[],model:Z.model,prompt:Z.prompt,permissionMode:W4.DEFAULT,isBackground:!1,source:"sdk"}))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents}}function ys6($,Z){let J=[],X=new Set;for(let Y of[$,...Z??[]]){let Q=vs6(Y);if(X.has(Q))continue;X.add(Q),J.push(Y)}return J}async function jE8($){let{workingDirectory:Z,projectDir:J}=$,X=ys6(Z,$.dirs),Y=X.length>1?X:void 0,Q=F71($.settingSources),W=$.teamSettingsService??Zl0(),K=$.defaultSandboxPolicy??{type:"insecure_none"},H=$.getSandboxSupported??(()=>S20(K,{ctx:$.initializationCtx})),G=$.getSandboxEnabled??(()=>K.type!=="insecure_none"&&H()),q=new _K,V=new Xy0(q,W,X),O=new DE8,F=new AE8,N=$.getSmartModeClassifierAutoModeEnabled?.(),L=new UE8(N?"allowlist":$.approvalMode??"unrestricted",K,W,$.respectAdminControls??!1),U=$.pendingDecisionProvider,D={executeIndexedGrep:void 0},j=()=>!0,w=N7(Q,"plugins"),k=$.importThirdPartyPlugins??!1,T=$.mcpMetaToolEnabled??!0,I=$.mcpServers!==void 0&&Object.keys($.mcpServers).length>0,M=$.customSubagents!==void 0&&$.customSubagents.length>0,C=I||N7(Q,"project")||N7(Q,"user")||w,v=N7(Q,"project")||N7(Q,"user")||N7(Q,"mdm"),R=N7(Q,"team"),S=R&&$.dashboardTransport!==void 0,h=N7(Q,"project")||N7(Q,"user")||R||S||w,b={teamSettingsService:W,initializationCtx:$.initializationCtx,importThirdPartyPlugins:k,ignoreApprovals:!0,includeProjectMcp:N7(Q,"project"),includeUserMcp:N7(Q,"user"),includePluginMcp:w,isLinkSharedPaymentTokenLogRedactionEnabled:$.isLinkSharedPaymentTokenLogRedactionEnabled,restMcpCursorAuthTokenSupplier:$.restMcpCursorAuthTokenSupplier},_=(y)=>NE8({workingDirectory:Z,...Y!==void 0?{workspaceRoots:Y}:{},adapters:{...y.includeMcp?{mcp:bM1({...b,inlineMcpServers:$.mcpServers})}:{},...w?{pluginBootstrap:sP8({importThirdPartyPlugins:k,dashboardTransport:$.dashboardTransport})}:{},...v?{hooks:hP8({includeProjectHooks:N7(Q,"project"),includeUserHooks:N7(Q,"user"),includeEnterpriseHooks:N7(Q,"mdm"),useCommandHookStdinTransport:$.useCommandHookStdinTransport})}:{},...h?{localExtensibility:lP8({includeProjectExtensibility:N7(Q,"project"),includeUserExtensibility:N7(Q,"user"),includeManagedSkills:S,includeTeamExtensibility:R,includePluginExtensibility:w,teamSettingsService:W,getThirdPartyExtensibilityEnabled:j,dashboardTransport:$.dashboardTransport,importThirdPartyPlugins:k})}:{},resourceFactory:XE8({ignoreService:V,grepProvider:D,workspacePaths:X,diagnosticsProvider:O,repositoryProvider:F,projectDir:J??Z,shellManager:void 0,defaultSandboxPolicy:K,defaultSandboxPolicySources:$.defaultSandboxPolicySources,getSandboxEnabled:G,getSandboxSupported:H,getNetworkAllowlistInfo:$.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:$.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:$.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:$.getMockPromptTime,getPowershellUtf8Options:$.getPowershellUtf8Options,mcpFileOutputThresholdBytes:void 0,mcpMetaToolEnabled:T,createMcpStateAccessor:(m,l)=>new wE8(new _b0(m),l?.onMcpAllowlistInUse===void 0&&l?.onMcpServerBlockedByAllowlist===void 0?void 0:{mcpLease:m,onMcpAllowlistInUse:l.onMcpAllowlistInUse,onMcpServerBlockedByAllowlist:l.onMcpServerBlockedByAllowlist}),createSessionMcpLease:(m,l)=>bM1({...b,includeProjectMcp:b.includeProjectMcp&&m.options.excludeProjectMcp!==!0,inlineMcpServers:l??$.mcpServers}).createLease({workspaceState:m.workspaceState,services:m.workspaceServices,policy:m.policy}),createSessionDependencies:(m)=>{let l=U??new LE8,i=new R81(Z),e=new D61(V,l,L,W,Z,$.respectAdminControls??!1,{enforceMcpAdminToolLimits:$.isMcpAdminToolLimitEnforced,onMcpAdminToolLimitCheck:m.options.onMcpAdminToolLimitCheck});return{pendingDecisionStore:l,fileChangeTracker:i,permissionsService:e}}}),resourceWrappers:v?[mP8()]:[],...M?{workspaceServicesContributors:[{contributeServices:(m)=>{let l=new N71($.customSubagents??[]),i=m.services.subagentsService;return{subagentsService:i===void 0?l:new kW0([l,i])}}}]}:{}}});if(!C)return _({includeMcp:!1});try{return await _({includeMcp:!0})}catch(y){return Z6.warn("[default-local-workspace-runtime] Failed to initialize MCP-enabled runtime, retrying without MCP:",{error:y,workingDirectory:Z,projectDir:J,enablePlugins:w,importThirdPartyPlugins:k}),_({includeMcp:!1})}}var ME8=P(()=>{nq();sK();K7();jI1();wI1();l3()});var IE8=()=>{};function TE8($){let{workspaceRuntime:Z}=$;if(!(Z.hooksConfigLease.hasHookForStep(i0.sessionStart)||Z.hooksConfigLease.hasHookForStep(i0.sessionEnd)||Z.hooksConfigLease.hasHookForStep(i0.stop)||Z.hooksConfigLease.hasHookForStep(i0.beforeSubmitPrompt)))return{};let X=Z.createSessionRuntime({sessionState:$.sessionState,metadata:$.metadata}),{hookExecutor:Y}=X,Q;return{async onSessionStart(W){if(Q=W,!Y.hasHooksForStep(i0.sessionStart))return;try{let K={conversation_id:W.conversationId,generation_id:W.generationId,model:W.model,...g5(W),is_background_agent:!1},H=await Y.executeHookForStep(i0.sessionStart,K);if(H){if(H.env)Y.setSessionEnvironment(H.env);return{env:H.env,additionalContext:H.additional_context,blocked:H.continue===!1,blockedReason:H.user_message}}}catch(K){Z6.warn("[hooks-adapter] sessionStart hook failed:",K)}return},async onSessionEnd(W,K){if(!Y.hasHooksForStep(i0.sessionEnd)){Y.clearSessionEnvironment();return}try{let H={conversation_id:Q?.conversationId??"",generation_id:Q?.generationId??"",model:Q?.model??"unknown",...Q?g5(Q):{},reason:W,duration_ms:K,is_background_agent:!1,final_status:W};await Y.executeHookForStep(i0.sessionEnd,H)}catch(H){Z6.warn("[hooks-adapter] sessionEnd hook failed:",H)}finally{Y.clearSessionEnvironment()}},async onBeforeSubmitPrompt(W){if(!Y.hasHooksForStep(i0.beforeSubmitPrompt))return;try{let K={conversation_id:W.conversationId,generation_id:W.generationId,model:W.model,...g5(W),prompt:W.promptText??"",attachments:[]};await Y.executeHookForStep(i0.beforeSubmitPrompt,K)}catch(K){Z6.warn("[hooks-adapter] beforeSubmitPrompt hook failed:",K)}},async onTurnCompleted(W){if(!Y.hasHooksForStep(i0.stop))return;let K={conversation_id:W.conversationId,generation_id:W.generationId,model:W.model,...g5(W),status:"completed",loop_count:W.loopCount},H=await Y.executeHookForStep(i0.stop,K),G=typeof H?.followup_message==="string"?H.followup_message.trim():"";return G.length>0?G:void 0},async onTurnError(W){if(!Y.hasHooksForStep(i0.stop))return;try{let K={conversation_id:W.conversationId,generation_id:W.generationId,model:W.model,...g5(W),status:"error",loop_count:W.loopCount};await Y.executeHookForStep(i0.stop,K)}catch(K){Z6.warn("[hooks-adapter] onTurnError stop hook failed:",K)}},async onTurnAborted(W){if(!Y.hasHooksForStep(i0.stop))return;try{let K={conversation_id:W.conversationId,generation_id:W.generationId,model:W.model,...g5(W),status:"aborted",loop_count:W.loopCount};await Y.executeHookForStep(i0.stop,K)}catch(K){Z6.warn("[hooks-adapter] onTurnAborted stop hook failed:",K)}},async dispose(){await X.dispose()}}}var PE8=P(()=>{q9();l3()});import{accessSync as xs6,constants as bs6,mkdtempSync as fs6,statSync as hs6}from"fs";import{homedir as ms6,tmpdir as gs6}from"os";import{join as L71}from"path";function us6($){if($.trim()==="")return!1;try{if(!hs6($).isDirectory())return!1;return xs6($,bs6.W_OK),!0}catch{return!1}}function cs6($){return fs6(L71($,"cursor-transcripts-"))}function ds6($){let Z=$.cursorDataDir?.trim();if(Z)return L71(Z,"projects",XQ($.workspacePath));if($.homeDir!==void 0&&us6($.homeDir))return L71($.homeDir,".cursor","projects",XQ($.workspacePath));return L71($.ensureFallbackRoot($.tempDir),XQ($.workspacePath))}function II1($){if(process.env.CURSOR_DATA_DIR?.trim())return tp0($);let J;try{J=ms6()}catch{J=void 0}return ds6({workspacePath:$,homeDir:J,tempDir:gs6(),ensureFallbackRoot:(X)=>{if(MI1===void 0)MI1=cs6(X);return MI1}})}var MI1;var EE8=P(()=>{l51();B1()});import{mkdir as ps6,writeFile as ls6}from"fs/promises";import{dirname as is6,join as U71}from"path";function ns6($,Z){let J=hK({conversationId:Z,ext:"jsonl",kind:"primary"});return U71(II1($),J)}async function kE8($,Z){let J=is6($);await ps6(J,{recursive:!0}),await ls6($,Z,"utf-8")}class Cl0{transcriptStore;nestedSubagentTranscriptStore;projectDir;conversationId;workspacePath;parentConversationId;blobStore;writeChain=Promise.resolve();constructor($){this.workspacePath=$.workspacePath,this.conversationId=$.conversationId,this.parentConversationId=$.parentConversationId,this.blobStore=$.blobStore,this.projectDir=II1(this.workspacePath);let Z=this.parentConversationId?(X,Y)=>{let Q=hK({conversationId:X,ext:Y,kind:"subagent",parentConversationId:this.parentConversationId});return U71(this.projectDir,Q)}:void 0;this.transcriptStore=new e51(this.projectDir,$.blobStore,kE8,{writeText:!1,writeJsonl:!0,...Z?{pathResolver:Z}:{}});let J=(X,Y)=>{let Q=hK({conversationId:X,ext:Y,kind:"subagent",parentConversationId:this.conversationId});return U71(this.projectDir,Q)};this.nestedSubagentTranscriptStore=new e51(this.projectDir,$.blobStore,kE8,{writeText:!1,writeJsonl:!0,pathResolver:J})}enqueueWrite($,Z){let J=this.writeChain;return this.writeChain=J.then(async()=>{try{await $()}catch(X){Z6.warn(`${Z} ${X instanceof Error?X.message:String(X)}`)}}),this.writeChain}async writeFromState($,Z){return this.enqueueWrite(async()=>{await this.transcriptStore.writeFromStateFull($,Z,this.conversationId);let J=await ch0($,Z,this.blobStore);for(let[X,Y]of Object.entries(J)){if(!Y?.conversationState)continue;await this.nestedSubagentTranscriptStore.writeFromStateFull($,Y.conversationState,X)}},"[LocalTranscriptWriter] Failed to write transcript:")}async writeTurnEndedFromState($,Z,J){return this.enqueueWrite(async()=>{await this.transcriptStore.writeFromStateFull($,Z,this.conversationId,{turnEnded:J})},"[LocalTranscriptWriter] Failed to write turn-ended transcript:")}waitForPendingWrites(){return this.writeChain}getTranscriptPath(){if(this.parentConversationId){let $=hK({conversationId:this.conversationId,ext:"jsonl",kind:"subagent",parentConversationId:this.parentConversationId});return U71(this.projectDir,$)}return ns6(this.workspacePath,this.conversationId)}getProjectDir(){return this.projectDir}}var TI1=P(()=>{hJ();o51();l3();EE8()});function rs6($){if(!as6.test($))throw Error(`Invalid resumeAgentId format: ${$}`)}function ss6($){let Z=new aC0,J=YQ($),X=new xN(new nC0,Z);return X.setMetadata("agentId",J.agentId),X.setMetadata("latestRootBlobId",J.latestRootBlobId),X.setMetadata("name",J.name),X.setMetadata("createdAt",J.createdAt),X.setMetadata("mode",J.mode),X.setMetadata("isRunEverything",J.isRunEverything),X.setMetadata("lastUsedModel",J.lastUsedModel),X.setMetadata("lastDebugServerPort",J.lastDebugServerPort),X.setMetadata("currentPlanUri",J.currentPlanUri),X.setMetadata("subagentInfo",J.subagentInfo),X.setMetadata("blobEncryptionKey",J.blobEncryptionKey),X}function os6($){let Z=$.query.case;switch(Z){case"webSearchRequestQuery":return H6.webSearchRejected($.id,"Web search is not supported in local subagent");case"webFetchRequestQuery":return H6.webFetchRejected($.id,"Web fetch is not supported in local subagent");case"switchModeRequestQuery":return H6.switchModeRejected($.id,"Subagent mode switches are not supported in local subagent");case"askQuestionInteractionQuery":{let J=new jZ({result:{case:"rejected",value:new yY({reason:"Interactive questions are not supported in local subagent mode"})}});return H6.askQuestion($.id,J)}default:throw Error(`Unhandled interaction query type in local subagent: ${String(Z)}`)}}class EI1{sessions=new Map;backgroundRuns=new Map;activeForegroundExecutions=new Map;backgroundPromises=new Set;pendingReleaseSessions=new Set;childParentIds=new Map;parentChildIds=new Map;queuedChildCompletions=new Map;childCompletionWaiters=new Map;childLineageRequestIds=new Map;untrackedParentRequestIds=new Map;rootLineageRequestId;lifecycleStore;agentClient;getResources;mcpTools;workspacePath;parentConversationId;headers;endlessRetries;onSessionCreated;onInteractionUpdate;onSessionCompleted;onSessionReleased;onSubagentTokenDelta;constructor($){this.agentClient=$.agentClient,this.getResources=$.getResources,this.mcpTools=$.mcpTools??[],this.workspacePath=$.workspacePath,this.parentConversationId=$.parentConversationId;let Z=$.rootRequestId?.trim();this.rootLineageRequestId=Z!==void 0&&Z.length>0?Z:L6(),this.headers=$.headers,this.endlessRetries=$.endlessRetries,this.onSessionCreated=$.onSessionCreated,this.onInteractionUpdate=$.onInteractionUpdate,this.onSessionCompleted=$.onSessionCompleted,this.onSessionReleased=$.onSessionReleased,this.onSubagentTokenDelta=$.onSubagentTokenDelta,this.lifecycleStore=new js0}async createOrResumeSession($,Z){if(Z.forkAgentId)throw Error("forkAgentId is not supported in local subagents.");let J=Z.resumeAgentId;if(J)rs6(J);if(J&&!Z.prompt)return J;if(J&&Ms0(Z.prompt)&&this.isBackgroundRunBusy(J))throw Error(gW1);if(J){if(this.sessions.get(J))return J}let X=J??L6(),Y=ss6(X),Q=new Cl0({workspacePath:this.workspacePath,conversationId:X,parentConversationId:this.parentConversationId,blobStore:Y.getBlobStore()});return this.sessions.set(X,{agentStore:Y,transcriptWriter:Q,toolCallId:Z.toolCallId}),this.onSessionCreated?.({agentId:X,toolCallId:Z.toolCallId,subagentType:Z.subagentType,parentAgentId:Z.parentConversationId}),X}async runSession($,Z,J,X){if(this.isAwaitBackgroundMode(J))return this.awaitBackgroundRun(J.resumeAgentId,$.signal);let Y=this.sessions.get(Z);if(!Y)return{status:"error",error:`Subagent session not found: ${Z}`};if(J.runInBackground){let[O,F]=$.withDetached().withCancel();return this.registerBackgroundRun(Z,this.executeSubagent(O,Z,J,Y),J.parentConversationId,F),{status:"background",backgroundReason:NZ.AGENT_REQUEST,toolCallCount:0}}let[Q,W]=$.withDetached().withCancel(),K=!1,H=()=>{if(!K)W()};if($.signal.addEventListener("abort",H,{once:!0}),$.signal.aborted)H();let G=()=>{},q=new Promise((O)=>{G=O}),V={requestBackground:()=>{if(K)return!0;if(Q.signal.aborted)return!1;return K=!0,$.signal.removeEventListener("abort",H),G(),!0}};this.activeForegroundExecutions.set(J.toolCallId,V),this.activeForegroundExecutions.set(Z,V);try{let O=this.executeSubagent(Q,Z,J,Y),F=await Promise.race([O.then((N)=>({handedOff:!1,outcome:N})),q.then(()=>({handedOff:!0}))]);if(F.handedOff)return this.registerBackgroundRun(Z,O,J.parentConversationId,W),{status:"background",backgroundReason:NZ.USER_REQUEST,toolCallCount:0};return this.onSessionCompleted?.(Z,F.outcome),F.outcome}finally{if(this.clearForegroundExecution(J.toolCallId,V),this.clearForegroundExecution(Z,V),!K)$.signal.removeEventListener("abort",H)}}forceBackgroundByToolCallId($){if(!this.activeForegroundExecutions.get($)?.requestBackground())return new m3({status:dh0.NOT_FOUND});return new m3({status:dh0.ACCEPTED})}clearForegroundExecution($,Z){if(this.activeForegroundExecutions.get($)===Z)this.activeForegroundExecutions.delete($)}releaseSession($){if(this.lifecycleStore.release($),this.isBackgroundRunBusy($)){this.pendingReleaseSessions.add($);return}this.cleanupSession($)}async awaitBackgroundWorkers(){while(this.backgroundPromises.size>0)await Promise.allSettled([...this.backgroundPromises])}async waitForBackgroundCompletions($,Z){return this.collectAvailableChildCompletions($,Z)}isBackgroundRunBusy($){return this.lifecycleStore.isBusy($)||this.backgroundRuns.has($)}registerBackgroundRun($,Z,J,X){this.registerParentChildLink($,J);let Y=this.lifecycleStore.startRun($,{abort:X}),Q=Z.catch((K)=>{return{status:"error",error:K instanceof Error?K.message:String(K)}}),W={runId:Y,promise:Q};this.backgroundRuns.set($,W),this.backgroundPromises.add(Q),Q.then((K)=>{if(this.lifecycleStore.finishRun($,Y),this.backgroundRuns.get($)?.runId===Y){this.backgroundRuns.delete($),this.enqueueChildCompletion($,Y,K),this.maybeCleanupReleasedSession($);try{this.onSessionCompleted?.($,K)}catch(G){Z6.error("[LocalSubagentHostAdapter] onSessionCompleted threw after background run",{agentId:$,error:G instanceof Error?G.message:String(G)})}}return K}).finally(()=>this.backgroundPromises.delete(Q))}maybeCleanupReleasedSession($){if(this.pendingReleaseSessions.has($)&&!this.isBackgroundRunBusy($))this.cleanupSession($)}cleanupSession($){this.pendingReleaseSessions.delete($);let Z=this.sessions.get($);if(!Z)return;let J=this.parentChildIds.get($);if(J)for(let X of J)this.childParentIds.delete(X);this.removeParentChildLink($),this.parentChildIds.delete($),this.queuedChildCompletions.delete($),this.childCompletionWaiters.delete($),Z.transcriptWriter.waitForPendingWrites().catch(()=>{}),this.sessions.delete($),this.onSessionReleased?.($)}async executeSubagent($,Z,J,X){if(J.continuationConfig)return this.executeSubagentWithContinuation($,Z,J,X,J.continuationConfig);return this.executeSubagentOnce($,Z,J,X)}async executeSubagentWithContinuation($,Z,J,X,Y){let Q=Y.maxLoops>0?Y.maxLoops:Number.POSITIVE_INFINITY,W=await this.runContinuationLoop($,Z,J,X,Y,Q);if(!Y.collectBackgroundChildren||W.status!=="completed")return W;let K=500;for(let H=0;H0){W=0,K=void 0;continue}W+=1,K=W>=Y.idleThreshold?`DONE_${L6().replace(/-/g,"").slice(0,8)}`:void 0}return H??{status:"error",error:"Subagent continuation exited unexpectedly"}}computeContinuationNudge($,Z,J){if(Z>=$.idleThreshold&&J!==void 0)return $.escapeMessageTemplate.replace("{idle_count}",String(Z)).replace("{escape_token}",J);return $.nudgeMessage}lineageForChildRun($){if(!this.childLineageRequestIds.has($.agentId))this.childLineageRequestIds.set($.agentId,L6());let Z=$.parentConversationId?.trim()??"",J=$.toolCallId.trim();return{parentRequestId:Z===""||Z===this.parentConversationId?this.rootLineageRequestId:this.childLineageRequestIds.get(Z)??this.untrackedParentRequestId(Z),rootParentRequestId:this.rootLineageRequestId,...J.length>0?{parentAgentToolCallId:J}:{}}}untrackedParentRequestId($){let Z=this.untrackedParentRequestIds.get($);if(Z===void 0)Z=L6(),this.untrackedParentRequestIds.set($,Z);return Z}async executeSubagentOnce($,Z,J,X){let Y=this.lineageForChildRun({agentId:Z,parentConversationId:J.parentConversationId,toolCallId:J.toolCallId}),Q,W=0,K=new N$({action:{case:"userMessageAction",value:new f9({userMessage:new v5({text:J.prompt})})}}),H=new mY({modelId:J.modelId,displayModelId:J.modelId,displayName:J.modelId});if(J.credentials.case!==void 0)H.credentials=J.credentials;let G=new um0,q={sendUpdate:async(O,F)=>{if(F.message.case==="tokenDelta")this.onSubagentTokenDelta?.(Z,F.message.value.tokens);if(F.message.case==="toolCallStarted"||F.message.case==="toolCallCompleted"||F.message.case==="partialToolCall")this.onInteractionUpdate?.(Z,F);if(F.message.case==="toolCallCompleted")W++;if(F.message.case==="textDelta")Q=(Q??"")+F.message.value.text},query:async(O,F)=>{return os6(F)}},V={handleCheckpoint:async(O,F)=>{await X.agentStore.handleCheckpoint(O,F),X.transcriptWriter.writeFromState(O,F)},getLatestCheckpoint:()=>{return X.agentStore.getLatestCheckpoint()}};try{let O=J.rootParentConversationId?.trim(),F=J.parentConversationId?.trim(),N=O!==void 0&&O!==""?O:F!==void 0&&F!==""?F:Z,L=await this.getResources({agentId:Z,parentAgentId:J.parentConversationId}),U=J.readonly?EW1(L):L;return await this.agentClient.run($,X.agentStore.getConversationStateStructure(),K,H,q,U,X.agentStore.getBlobStore(),G,V,[...this.mcpTools],{conversationGroupId:N,conversationId:Z,...X.transcriptWriter.parentConversationId?{transcriptParentConversationId:X.transcriptWriter.parentConversationId}:{},subagentTypeName:J.subagentType||void 0,...Y,headers:i51(X.agentStore.getMetadata("blobEncryptionKey"),this.headers),endlessRetries:this.endlessRetries,subagentModelOverrides:[]}),await X.transcriptWriter.writeTurnEndedFromState($,X.agentStore.getConversationStateStructure(),$.signal.aborted?{status:"aborted",error:PI1}:{status:"success"}),{status:"completed",finalMessage:Q,toolCallCount:W}}catch(O){let F=O instanceof Error?O.message:String(O);if(Z6.error("[LocalSubagentHostAdapter] Subagent session failed",{agentId:Z,error:F}),await X.transcriptWriter.writeTurnEndedFromState($,X.agentStore.getLatestCheckpoint()??X.agentStore.getConversationStateStructure(),this.getTurnEndedFromError($,F)),$.signal.aborted)return{status:"aborted",error:PI1};return{status:"error",error:F}}}getTurnEndedFromError($,Z){return $.signal.aborted?{status:"aborted",error:PI1}:{status:"error",error:Z}}isAwaitBackgroundMode($){if(!Boolean($.resumeAgentId&&!Ms0($.prompt)&&$.readonly&&$.runInBackground!==!0))return!1;if(($.parentConversationId??"").trim().length===0)throw Error(`Missing parentConversationId for subagent await/status check (subagentId: ${$.resumeAgentId})`);return!0}async awaitBackgroundRun($,Z){let J=this.backgroundRuns.get($);if(!J){if(this.isBackgroundRunBusy($))return this.awaitBusyLifecycleRun($,Z);return{status:"error",error:`No background subagent found for id: ${$}`}}return this.awaitBackgroundEntry(J,Z)}async awaitBackgroundRunBounded($,Z){let J=Z.agentId;if($.signal.aborted)return new p9({result:{case:"stillRunning",value:new f3({agentId:J})}});let X=this.backgroundRuns.get(J);if(X===void 0){let K=this.takeQueuedChildCompletion(J);if(K!==void 0){if(K.status==="success")return new p9({result:{case:"complete",value:new VG({agentId:J,finalMessage:K.finalMessage,toolCallCount:K.toolCallCount??0})}});return new p9({result:{case:"error",value:new BG({agentId:J,error:K.finalMessage||"Subagent was aborted"})}})}if(this.isBackgroundRunBusy(J))return new p9({result:{case:"stillRunning",value:new f3({agentId:J})}});return new p9({result:{case:"notFound",value:new bN({agentId:J})}})}let[Y,Q]=$.withTimeoutAndCancel(Math.max(0,Z.timeoutMs)),W=await new Promise((K)=>{let H=()=>K(void 0);Y.signal.addEventListener("abort",H,{once:!0}),X.promise.then(K).finally(()=>{Y.signal.removeEventListener("abort",H),Q()})});if(W===void 0||W.status==="background"||$.signal.aborted)return new p9({result:{case:"stillRunning",value:new f3({agentId:J})}});if(this.takeQueuedChildCompletion(J,X.runId),W.status==="completed")return new p9({result:{case:"complete",value:new VG({agentId:J,finalMessage:W.finalMessage,toolCallCount:W.toolCallCount??0})}});return new p9({result:{case:"error",value:new BG({agentId:J,error:W.error??"Subagent was aborted"})}})}takeQueuedChildCompletion($,Z){for(let[J,X]of this.queuedChildCompletions){let Y=X.findIndex((W)=>W.agentId===$&&(Z===void 0||W.runId===Z));if(Y===-1)continue;let[Q]=X.splice(Y,1);if(X.length===0)this.queuedChildCompletions.delete(J);return Q}return}async awaitBusyLifecycleRun($,Z){while(this.isBackgroundRunBusy($)){if(Z.aborted)return{status:"error",error:"Await timed out while task is still running"};let J=this.backgroundRuns.get($);if(J)return this.awaitBackgroundEntry(J,Z);await new Promise((X)=>setTimeout(X,50))}return{status:"completed",toolCallCount:0}}async awaitBackgroundEntry($,Z){if(Z.aborted)return{status:"error",error:"Await timed out while task is still running"};let J={status:"error",error:"Await timed out while task is still running"};return new Promise((X)=>{let Y=()=>{X(J)};Z.addEventListener("abort",Y,{once:!0}),$.promise.then(X).finally(()=>Z.removeEventListener("abort",Y))})}registerParentChildLink($,Z){let J=Z?.trim();if(!J||J===$||!this.sessions.has(J)&&J!==this.parentConversationId)return;let X=this.childParentIds.get($);if(X===J)return;if(X){if(this.parentChildIds.get(X)?.delete($),(this.parentChildIds.get(X)?.size??0)===0)this.parentChildIds.delete(X)}this.childParentIds.set($,J);let Y=this.parentChildIds.get(J)??new Set;Y.add($),this.parentChildIds.set(J,Y)}removeParentChildLink($){let Z=this.childParentIds.get($);if(!Z)return;this.childParentIds.delete($);let J=this.parentChildIds.get(Z);if(J?.delete($),(J?.size??0)===0)this.parentChildIds.delete(Z)}enqueueChildCompletion($,Z,J){let X=this.childParentIds.get($);if(!X)return;let Y=this.queuedChildCompletions.get(X)??[];Y.push({agentId:$,runId:Z,status:J.status==="completed"?"success":J.status==="error"?"error":"aborted",finalMessage:J.status==="completed"?J.finalMessage??"":J.status==="error"?J.error:"Subagent was aborted by the user",...J.status==="completed"&&J.toolCallCount!==void 0?{toolCallCount:J.toolCallCount}:{}}),this.queuedChildCompletions.set(X,Y),this.removeParentChildLink($);let Q=this.childCompletionWaiters.get(X);if(!Q)return;this.childCompletionWaiters.delete(X);for(let W of Q)W()}async collectAvailableChildCompletions($,Z){let J=this.drainChildCompletions($);if(J.length>0)return J;if(!this.hasPendingChildSubagents($))return[];return await this.waitForChildCompletion($,Z),this.drainChildCompletions($)}hasPendingChildSubagents($){return(this.parentChildIds.get($)?.size??0)>0}drainChildCompletions($){let Z=this.queuedChildCompletions.get($)??[];return this.queuedChildCompletions.delete($),Z}async waitForChildCompletion($,Z){if(Z.aborted)throw Error("aborted");await new Promise((J,X)=>{let Y=this.childCompletionWaiters.get($)??new Set,Q=()=>{K(),J()},W=()=>{K(),X(Error("aborted"))},K=()=>{if(Y.delete(Q),Y.size===0)this.childCompletionWaiters.delete($);Z.removeEventListener("abort",W)};Y.add(Q),this.childCompletionWaiters.set($,Y),Z.addEventListener("abort",W,{once:!0})})}buildChildrenCompletedMessage($,Z){let J=$.map((X)=>{let Y=X.status==="success"?"SUCCESS":"FAILED";return`## Agent ${X.agentId} -- ${Y} -+`)}})}function pr6($){return{toolName:i8.Write,getToolCallId:T5,createToolInput:(Z)=>({file_path:Z.path,content:Z.fileText}),applyUpdatedInput:(Z,J)=>{if(typeof J.file_path==="string")Z.path=J.file_path},createRejectedResult:(Z,J)=>new z6({result:{case:"error",value:new L5({path:Z.path,error:J})}}),isSuccess:(Z)=>Z.result.case==="success",getErrorMessage:(Z)=>{if(Z.result.case==="error")return Z.result.value.error||"Write error";return"Unknown error"},createSuccessOutput:(Z)=>({file_path:Z.path,success:!0}),runPreExecutionHooks:async(Z)=>{let{args:J,hookExecutor:X,toolUseId:Y}=Z;if(X.hasHooksForStep?.(i0.afterFileEdit)===!1)return;let Q,W=!1;try{if((await cr6(J.path)).size>HI1)W=!0;else Q=await K$(J.path)}catch(K){}$.set(Y,{contentBeforeWrite:Q,fileTooLarge:W});return},runCleanup:(Z)=>{$.delete(Z)},runPostExecutionHooks:async(Z)=>{let{args:J,result:X,baseHookRequest:Y,hookExecutor:Q,toolUseId:W}=Z,K=$.get(W);if(X.result.case!=="success"||Q.hasHooksForStep?.(i0.afterFileEdit)===!1)return;let{contentBeforeWrite:H,fileTooLarge:G}=K??{fileTooLarge:!1},q;if(G)q=[{old_string:"",new_string:J.fileText}];else if(H===void 0)q=[{old_string:"",new_string:J.fileText}];else if(H===J.fileText)q=[];else q=GI1(H,J.fileText);let V={...Y,file_path:J.path,edits:q},O=await Q.executeHookForStep(i0.afterFileEdit,V);if(J.returnFileContentAfterWrite&&O!==void 0){let F=X.result.value.path;try{let N=await K$(F),L=SJ(N),U=Buffer.byteLength(N,"utf8");return new z6({result:{case:"success",value:new $Q({path:X.result.value.path,linesCreated:L,fileSize:U,fileContentAfterWrite:N})}})}catch(N){return}}return}}}class Pl0{wrappedExecutor;constructor($,Z,J){let X=new Map;this.wrappedExecutor=l6($,Z,J,pr6(X))}execute($,Z,J){return this.wrappedExecutor.execute($,Z,J)}}var HI1=262144,dr6=50;var CP8=P(()=>{q9();ZG();o9();$U1();OZ();BZ()});var qI1=P(()=>{OP8();FP8();NP8();LP8();UP8();DP8();AP8();jP8();MP8();IP8();TP8();EP8();RP8();CP8()});function l7($,Z,J){return Z===$.symbol}function _P8($,Z,J){if(l7(mG,$,Z))return new Il0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(a9,$,Z))return new Tl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(D20,$,Z))return new Pl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(a3,$,Z))return new Al0(Z,J.hookExecutor,J.baseHookRequestExtractor,J.mcpLease,J.hooksConfigLease);if(l7(tS0,$,Z))return new mb0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(xm0,$,Z))return new mb0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(_m0,$,Z))return new Dl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(Mm0,$,Z))return new Ul0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(wm0,$,Z))return new Ll0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(V20,$,Z))return new Fl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(B20,$,Z))return new Nl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(vm0,$,Z))return new wl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(ym0,$,Z))return new jl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(xG,$,Z))return new Vl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(bG,$,Z))return new Bl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(Am0,$,Z))return new Ol0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(mm0,$,Z))return new Ml0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(r9,$,Z)&&(J.hooksAdditionalContextPromise||J.hooksConfigLease))return new H71(Z,J.hooksAdditionalContextPromise??Promise.resolve(void 0),J.teamHooksReadyPromise,J.hooksConfigLease);return}function lr6($,Z){if($.symbol!==qs0.symbol)return;return new Cm0(Z)}function ir6($,Z,J){let X=_P8($.symbol,Z,J);if(X!==void 0)return X;return Z}class V71{innerAccessor;hookExecutor;baseHookRequestExtractor;mcpLease;hooksAdditionalContextPromise;teamHooksReadyPromise;hooksConfigLease;constructor($,Z,J,X,Y,Q,W){this.innerAccessor=$;this.hookExecutor=Z;this.baseHookRequestExtractor=J;this.mcpLease=X;this.hooksAdditionalContextPromise=Y;this.teamHooksReadyPromise=Q;this.hooksConfigLease=W}get($){let Z=lr6($,this.hookExecutor);if(Z!==void 0)return Z;return ir6($,this.innerAccessor.get($),{hookExecutor:this.hookExecutor,baseHookRequestExtractor:this.baseHookRequestExtractor,mcpLease:this.mcpLease,hooksAdditionalContextPromise:this.hooksAdditionalContextPromise,teamHooksReadyPromise:this.teamHooksReadyPromise,hooksConfigLease:this.hooksConfigLease})}*entries(){for(let[Z,J]of this.innerAccessor.entries()){let X=_P8(Z.symbol,J,{hookExecutor:this.hookExecutor,baseHookRequestExtractor:this.baseHookRequestExtractor,mcpLease:this.mcpLease,hooksAdditionalContextPromise:this.hooksAdditionalContextPromise,teamHooksReadyPromise:this.teamHooksReadyPromise,hooksConfigLease:this.hooksConfigLease});yield[Z,X??J]}yield[qs0,new Cm0(this.hookExecutor)]}}var SP8=P(()=>{J6();WI1();qI1()});var vP8=P(()=>{X2()});var yP8=P(()=>{nI8();AT8();eT8();Gl0();$P8();OZ();VP8();bb0();BP8();sM1();WI1();SP8();QI1();qI1();BZ();vP8()});import{spawn as nr6}from"child_process";import{homedir as xP8}from"os";import{join as El0}from"path";function rr6($){if(process.platform==="win32")return{executable:FQ(),args:[...Pl1,"-Command",$]};return{executable:process.env.SHELL||"/bin/sh",args:["-lc",$]}}function bP8($=process.cwd()){let Z=$;return{async getCwd(){return Z},clone(X){return bP8(X??Z)},async*execute(X,Y,Q={}){let W=Q.workingDirectory??Z;Z=W;let K=rr6(Y),H=nr6(K.executable,[...K.args],{cwd:W,env:{...process.env,...Q.env??{}},signal:Q.signal,stdio:[Q.pipeStdin===!0?"pipe":"ignore","pipe","pipe"]}),G=[],q,V,O=!1,F=()=>{q?.(),q=void 0},N=(L)=>{G.push(L),F()};H.on("spawn",()=>{if(Q.pipeStdin===!0)N({type:"stdin_ready",stdin:H.stdin??void 0})}),H.stdout?.setEncoding("utf8"),H.stdout?.on("data",(L)=>{N({type:"stdout",data:String(L)})}),H.stderr?.setEncoding("utf8"),H.stderr?.on("data",(L)=>{N({type:"stderr",data:String(L)})}),H.on("error",(L)=>{V=L,O=!0,F()}),H.on("close",(L)=>{N({type:"exit",code:L}),O=!0});while(!O||G.length>0){if(G.length===0){await new Promise((L)=>{q=L});continue}yield G.shift()}if(V!==void 0)throw V}}}function sr6($){return $.projectRoot??$.workingDirectory??$.workspaceRoots[0]??process.cwd()}function or6($,Z){let J=$.projectRoot??$.workingDirectory??$.workspaceRoots[0],X=Z.includeProjectHooks??!0,Y=Z.includeUserHooks??!0;return{enterpriseConfigPath:Z.includeEnterpriseHooks??!0?nM1():void 0,userConfigPath:Y?El0(xP8(),".cursor","hooks.json"):void 0,claudeUserConfigPath:Y?El0(xP8(),".claude","settings.json"):void 0,projectConfigPath:X&&J!==void 0?El0(J,".cursor","hooks.json"):void 0,claudeProjectConfigPath:X&&J!==void 0?El0(J,".claude","settings.json"):void 0,claudeProjectLocalConfigPath:X&&J!==void 0?El0(J,".claude","settings.local.json"):void 0}}function tr6($){return Object.freeze({...ar6,...$.globalContext??{}})}function kl0($,Z,...J){for(let X of J){let Y=Z($[X]);if(Y!==void 0)return Y}return}function B71($){return typeof $==="string"&&$.length>0?$:void 0}function er6($){return typeof $==="object"&&$!==null&&typeof $.id==="string"&&typeof $.value==="string"}function $s6($){if(!Array.isArray($))return;if(!$.every(er6))return;return $.map((Z)=>({id:Z.id,value:Z.value}))}function Zs6($,Z){let J=kl0(Z,B71,"conversationId","conversation_id")??$.sessionId??"",X=kl0(Z,B71,"generationId","generation_id")??J,Y=kl0(Z,B71,"model")??"unknown",Q=kl0(Z,B71,"modelId","model_id"),W=kl0(Z,$s6,"modelParams","model_params");return{conversation_id:J,generation_id:X,model:Y,...g5({modelId:Q,modelParams:W})}}function Js6($){return typeof $==="object"&&$!==null&&"get"in $&&typeof $.get==="function"&&"entries"in $&&typeof $.entries==="function"}function Xs6($){return typeof $==="object"&&$!==null&&"hooksConfigLease"in $&&"createSessionRuntime"in $&&typeof $.createSessionRuntime==="function"}class fP8{innerAccessor;sessionHooksRuntime;constructor($,Z){this.innerAccessor=$;this.sessionHooksRuntime=Z}get($){return this.innerAccessor.get($)}entries(){return this.innerAccessor.entries()}async dispose(){await this.sessionHooksRuntime.dispose()}}async function Ys6($,Z={}){let J=await new I30(new z71,or6($,Z)).load(),X=new X71(J),Y=sr6($),Q=tr6(Z);return{projectDir:$.projectRoot,workspacePath:Y,hooksConfig:J,hooksConfigLease:X,globalContext:Q,createSessionRuntime(){let W=new J71(J,Y,Q,(Z.createTerminalExecutor??bP8)(),Z.promptHookClient,void 0,void 0,{enableClaudeNestedHookSpecificOutputCompatibility:!0,commandHookPayloadTransport:Tl1(Z.useCommandHookStdinTransport)});return{hookExecutor:W,hooksConfigLease:X,async dispose(){W.clearSessionEnvironment()}}},async dispose(){}}}function hP8($={}){return{createHooksRuntime(Z){return Ys6(Z.workspaceState,$)}}}function mP8(){return{wrapResources($){let Z=$.workspaceServices.hooksRuntime;if($.options.excludeHooks===!0||!Xs6(Z)||!Js6($.resources))return $.resources;let J=Z.createSessionRuntime({sessionState:$.sessionState,metadata:$.metadata});return new fP8(new V71($.resources,J.hookExecutor,()=>Zs6($.sessionState,$.metadata),$.workspaceServices.mcpLease,void 0,void 0,Z.hooksConfigLease),J)}}}var ar6;var gP8=P(()=>{q9();yP8();K7();ar6={cursor_version:process.env.AGENT_CLI_STATIC_VERSION??"1.0.0",user_email:null}});function Qs6($){return typeof $==="object"&&$!==null&&"dispose"in $&&typeof $.dispose==="function"}async function GW($){if(Qs6($))await $.dispose()}import{realpath as pP8}from"fs/promises";import{homedir as Ws6}from"os";import{createClient as Ks6}from"@connectrpc/connect";function zs6($){if($.workspaceRoots.length>0)return[...$.workspaceRoots];let Z=$.projectRoot??$.workingDirectory;return Z!==void 0?[Z]:[]}function lP8($={}){let Z=$.getThirdPartyExtensibilityEnabled??(()=>!0),J=$.importThirdPartyPlugins??!1,X=$.includeProjectExtensibility??!0,Y=$.includeUserExtensibility??!0,Q=$.includeManagedSkills??!0,W=$.includePluginExtensibility??!0,K=new _K,H=Ws6(),G=AK(H).dirPath,q,V=!0;return{async prepareLocalExtensibility(){V=Q&&await Bs6($.dashboardTransport)},async loadLocalExtensibility(O){let F=O.workspaceState,N=zs6(F);if(N.length===0)return q=void 0,{cursorRulesService:dP8(),getAgentSkills:async(l)=>[]};let L=k1(),U=$.loadNestedRules??!0,D=X?N.map((y)=>new zU(L,K,y,U,Z,void 0)):[],j=D.length===0?dP8():D.length===1?D[0]:new Gx0(D,()=>Kx0),w=Hs6(j,{allowedRoots:X?N:[],excludedRoots:[]}),k=new E11(L,X?N:[],H,K,U,void 0,Z,Promise.resolve(),"sdk"),T=Gs6(k,{allowedRoots:[...X?N:[],...Y?[H]:[],...V?[G]:[]],excludedRoots:V?[]:[G]}),I=X?N.map((y)=>new R11(y,Z)):[],M=I.length===0?new HU:I.length===1?I[0]:new kW0(I),C=a51(O.services.pluginBootstrapOutputs),v=C&&W?new k11(L,()=>({importThirdPartyPlugins:J}),void 0,C.pluginsService):void 0,R=C&&W?new C11(()=>({importThirdPartyPlugins:J}),C.pluginsService):void 0,S=new Gx0([w,T,...v?[v]:[]],()=>Kx0),h=new op0([T,...v?[v]:[]],()=>[],()=>({workspacePaths:X?N:[],userHomeDirectory:H,agentStoreSkillsDirs:[]})),b=new kW0([M,...R?[R]:[]]);return q={localRulesService:w,localSkillsService:T,localSubagentsService:M,pluginSkillsService:v,pluginSubagentsService:R,mergedCursorRulesService:S,mergedAgentSkillsService:h,mergedSubagentsService:b},{cursorRulesService:S,getAgentSkills:(y)=>h.getAllAgentSkills(y),subagentsService:b}},async disposeLocalExtensibility(){if(!q)return;let O=q;q=void 0,await Vs6(O)}}}function Hs6($,Z){let J=iP8(Z);return{async getAllCursorRules(X){return VI1(await $.getAllCursorRules(X),J)},reload(X){$.reload(X)},onDidChangeRules(X){return $.onDidChangeRules(X)},dispose(){$.dispose()}}}function Gs6($,Z){let J=iP8(Z);return{async getAllCursorRules(X){return VI1(await $.getAllCursorRules(X),J)},async getAllAgentSkills(X){return VI1(await $.getAllAgentSkills(X),J)},reload(X){$.reload(X)},onDidChangeRules(X){return $.onDidChangeRules(X)},onDidChangeSkills(X){return $.onDidChangeSkills(X)},dispose(){$.dispose()}}}function iP8($){let Z=Promise.all($.allowedRoots.map(cP8)),J=Promise.all($.excludedRoots.map(cP8));return async(Y)=>{let[Q,W,K]=await Promise.all([qs6(Y.fullPath),Z,J]);if(Q===void 0)return!1;if(K.some((H)=>uP8(Q,H)))return!1;return W.some((H)=>uP8(Q,H))}}async function VI1($,Z){let J=await Promise.all($.map(Z));return $.filter((X,Y)=>J[Y])}function uP8($,Z){if($===Z)return!0;let J=`${Z}/`;return $.startsWith(J)}function BI1($){return $.replace(/\\/g,"/").replace(/\/+$/,"")}async function cP8($){try{return BI1(await pP8($))}catch{return BI1($)}}async function qs6($){try{return BI1(await pP8($))}catch{return}}function dP8(){return{async getAllCursorRules(){return[]},reload(){},onDidChangeRules(){return()=>{}},dispose(){}}}async function Vs6($){let Z,J=[$.mergedSubagentsService,$.mergedAgentSkillsService,$.mergedCursorRulesService,$.pluginSubagentsService,$.pluginSkillsService,$.localSubagentsService,$.localSkillsService,$.localRulesService];for(let X of J)try{await GW(X)}catch(Y){Z??=Y}if(Z!==void 0)throw Z}async function Bs6($){if(!$)return!1;let Z=Ks6(P3,$);return(await IM1(k1(),{getManagedSkills:async()=>{return(await Z.getManagedSkills(new TH({}))).skills??[]}})).status==="synced"}var nP8=P(()=>{F1();nq();VC0();X2()});import{homedir as Os6}from"os";import{join as Fs6}from"path";import{createClient as Ns6}from"@connectrpc/connect";function Ls6(){return{log($,Z,J){switch($){case"warn":Z6.warn("[local-plugins-bootstrap]",Z,J??{});break;case"error":Z6.error("[local-plugins-bootstrap]",Z,J??{});break;default:break}},increment(){},distribution(){},captureException($,Z){Z6.error("[local-plugins-bootstrap] Unexpected plugin exception:",$,Z??{})}}}function sP8($={}){let Z=$.userHomeDirectory??Os6(),J=$.importThirdPartyPlugins??!1,X=$.pluginLogger??Ls6(),Y=rP8($.marketplaceOptions),Q=$.dashboardTransport!==void 0,W=$.loadCursorFirstParty??(Y||Q);return{async loadPluginBootstrapOutputs(K){let H=Us6(K.workspaceState),{discoveredEntries:G,failures:q}=await As6(H),V=$.marketplaceOptions??($.dashboardTransport?Ds6({dashboardTransport:$.dashboardTransport,workspacePath:H,userHomeDirectory:Z}):void 0),O=rP8(V),F=new h51(H!==void 0?[H]:[],Z,()=>({importThirdPartyPlugins:J,loadCursorFirstParty:W}),V,X),N=[],L=[...q];try{N=await F.getAllEnabledPlugins()}catch(D){L.push({stage:"resolution",source:"plugin-loader",message:D instanceof Error?`Failed to load plugins: ${D.message}`:`Failed to load plugins: ${String(D)}`,detail:D})}if(G.length>0&&!O)L.push({stage:"resolution",source:"plugin-loader",message:"Project plugin entries were discovered, but no marketplace-backed project plugin source was configured. Those entries remain available through discoveredEntries only.",detail:{workspacePath:H,discoveredEntryCount:G.length}});let U={kind:gI8,discoveredEntries:G,loadedPlugins:N,loadFailures:F.getLoadFailures(),bootstrapFailures:L,pluginsService:F,async dispose(){}};for(let D of L)Z6.warn("[local-plugins-bootstrap] Plugin bootstrap failure:",{workspacePath:H,stage:D.stage,source:D.source,message:D.message,detail:D.detail});for(let D of U.loadFailures)Z6.warn("[local-plugins-bootstrap] Plugin load failure:",{workspacePath:H,pluginName:D.pluginName,pluginId:D.pluginId,marketplaceName:D.marketplaceName,errorType:D.errorType,errorMessage:D.errorMessage});return[U]}}}function Us6($){return $.projectRoot??$.workspaceRoots[0]??$.workingDirectory}function rP8($){if($===void 0)return!1;return Array.isArray($)?$.length>0:!0}function Ds6($){let Z=Fs6($.userHomeDirectory,".cursor","plugins","marketplaces"),J=Ns6(P3,$.dashboardTransport),X=(H,{signal:G})=>J.downloadPluginContent(H,{signal:G}),Y=new oy0,Q=$11(async()=>{try{return await J.getEffectiveUserPlugins(new jH(aP8))}catch{return{plugins:[]}}},{marketplaceCacheRoot:Z,listOptions:{allowedMarketplaceNames:["cursor-public"]},downloadPluginContent:X,contentRetries:Y.forListing("account")}),W=$.workspacePath,K=$11(async()=>{if(W===void 0)return{plugins:[]};try{let H=await O11(W);if(H.length===0)return{plugins:[]};let G=H.filter((N)=>N.entry.gitUrl),q=H.filter((N)=>!N.entry.gitUrl),O=G.filter(({entry:N})=>{let L=N.gitUrl;return!L||B11(L)}).map(({key:N,entry:L})=>{let U=F11(N),D=L.gitUrl;return{plugin:{name:U.name,gitUrl:D,gitRef:L.gitRef,gitPath:L.gitPath,marketplace:{name:U.marketplaceName,gitUrl:D,gitRef:L.gitRef}},isEnabled:!0}}),F=[];if(q.length>0)try{let N=q.map((U)=>{let D=F11(U.key);return new hF({name:D.name,marketplaceName:D.marketplaceName})});F=(await J.resolvePluginsByRef(new MH({refs:N,...aP8}))).plugins?.map((U)=>({plugin:U,isEnabled:!0}))??[]}catch{}return{plugins:[...O,...F]}}catch{return{plugins:[]}}},{marketplaceCacheRoot:Z,listOptions:{allowedMarketplaceNames:["cursor-public"]},downloadPluginContent:X,contentRetries:Y.forListing("project")});return[{client:Q,userId:"",cacheManager:new wW0($.userHomeDirectory),pruneOldVersions:!0},{client:K,userId:"",cacheManager:new wW0($.userHomeDirectory),pruneOldVersions:!0}]}async function As6($){if($===void 0)return{discoveredEntries:[],failures:[]};try{return{discoveredEntries:(await O11($)).map(({key:J,entry:X})=>({source:"project-settings",workspacePath:$,key:J,entry:X})),failures:[]}}catch(Z){return{discoveredEntries:[],failures:[{stage:"discovery",source:"project-settings",message:Z instanceof Error?`Failed to read project plugin settings: ${Z.message}`:`Failed to read project plugin settings: ${String(Z)}`,detail:Z}]}}}var aP8;var oP8=P(()=>{TW0();nq();VC0();X2();l3();aP8={supportsBackendContent:!0}});class ZE8{async getAllCursorRules($){return[]}reload($){}dispose(){}onDidChangeRules($){return()=>{}}}function js6($){return $==="/"||$==="\\"}function OI1($){if($.length<=1)return $;let Z=$.length;while(Z>1&&js6($[Z-1])){if(Z===3&&$[1]===":")break;Z-=1}return $.slice(0,Z)}function O71($){let Z=OI1($).replaceAll("\\","/");if(/^[A-Za-z]:\/$/.test(Z))return Z.slice(0,-1);return Z}function tP8($){let Z=OI1($.reportedWorkspacePath);if($.suffix==="")return Z;let J=Z.replaceAll("\\","/"),X=J==="/"?$.suffix:`${J}${$.suffix}`;return Z.includes("\\")?X.replaceAll("/","\\"):X}function eP8($){let Z=O71($.value),J=$.roots.filter((X)=>X.host.length>0).sort((X,Y)=>O71(Y.host).length-O71(X.host).length);for(let X of J){let Y=O71(X.host);if(Z===Y)return tP8({reportedWorkspacePath:X.reported,suffix:""});let Q=Y==="/"?"/":`${Y}/`;if(Z.startsWith(Q)){let W=Y==="/"?Z:Z.slice(Y.length);return tP8({reportedWorkspacePath:X.reported,suffix:W})}}return}function Ms6($,Z){if($.result.case!=="success"||$.result.value.requestContext?.env===void 0)return $;let J=$.clone();if(J.result.case!=="success")return $;let X=J.result.value.requestContext?.env;if(X===void 0)return J;let{roots:Y,reportedWorkspacePath:Q}=Z;X.workspacePaths=X.workspacePaths.map((W)=>eP8({value:W,roots:Y})??W);for(let W of ws6){let K=X[W];if(K===void 0||K==="")continue;let H=eP8({value:K,roots:Y});X[W]=W==="processWorkingDirectory"&&Q!==void 0?H??OI1(Q):H??K}return J}function Is6($,Z){let J=$.get(r9);if(J===void 0)return;let{reportedWorkspacePath:X,reportedProjectFolder:Y}=Z,Q=X===void 0?[]:Z.workspacePaths.map((K)=>({host:K,reported:X})),W=Y??X;if(W!==void 0)Q.push({host:Z.projectDir,reported:W});$.register(r9,{execute:async(K,H,G)=>{let q=await J.execute(K,H,G);return Ms6(q,{roots:Q,reportedWorkspacePath:X})}})}async function Ts6($){if($===void 0)return $E8;try{let Z=await $();return{powershellUtf8Console:Z.powershellUtf8Console,powershellUtf8ChildEnv:Z.powershellUtf8ChildEnv}}catch{return $E8}}async function Ps6($,Z){if($===void 0)return{};if(typeof $==="function")return await $({sessionId:Z.sessionState.sessionId,metadata:Z.metadata});return $}function XE8($){let Z=new _K;return{async createResources(J){let X=$.createSessionDependencies?.(J)??{pendingDecisionStore:$.pendingDecisionStore,fileChangeTracker:$.fileChangeTracker,permissionsService:$.permissionsService};if(!X.pendingDecisionStore||!X.fileChangeTracker||!X.permissionsService)throw Error("Local resource provider factory requires either shared dependencies or a per-session dependency factory.");let Y=J.workspaceServices.cursorRulesService??new ZE8,Q=J.workspaceServices.subagentsService??new HU,W=J.workspaceServices.mcpLease??new uU,K=J.options.excludeProjectMcp===!0,H=J.options.mcpServersOverride===void 0&&!K?void 0:$.createSessionMcpLease!==void 0?await $.createSessionMcpLease(J,J.options.mcpServersOverride):K?new uU:void 0,q=DL1(H??W,J.options.extraMcpTools??[]);try{let V=await Ps6(J.options.localResourceProviderOptions,J),O=await Ts6($.getPowershellUtf8Options),F={pendingDecisionStore:X.pendingDecisionStore,fileChangeTracker:X.fileChangeTracker,gitExecutor:Z,ignoreService:$.ignoreService,grepProvider:$.grepProvider,permissionsService:X.permissionsService,workspacePaths:$.workspacePaths,diagnosticsProvider:$.diagnosticsProvider,mcpLease:q,mcpStateAccessor:$.createMcpStateAccessor?.(q,J.options),cursorRulesService:Y,subagentsService:Q,repositoryProvider:$.repositoryProvider,projectDir:$.projectDir,shellManager:$.shellManager,_defaultSandboxPolicy:$.defaultSandboxPolicy??{type:"insecure_none"},_defaultSandboxPolicySources:$.defaultSandboxPolicySources,getSandboxEnabled:$.getSandboxEnabled,getSandboxSupported:$.getSandboxSupported,getNetworkAllowlistInfo:$.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:$.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:$.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:$.getMockPromptTime,mcpFileOutputThresholdBytes:$.mcpFileOutputThresholdBytes,mcpMetaToolEnabled:$.mcpMetaToolEnabled,attributionConfigProvider:$.attributionConfigProvider,getAgentSkills:J.workspaceServices.getAgentSkills,powershellUtf8Console:O.powershellUtf8Console,powershellUtf8ChildEnv:O.powershellUtf8ChildEnv,...V},N=H===void 0?new j30(F):new JE8(F,H);if(J.options.reportedWorkspacePath!==void 0||J.options.reportedProjectFolder!==void 0)Is6(N,{reportedWorkspacePath:J.options.reportedWorkspacePath,reportedProjectFolder:J.options.reportedProjectFolder,workspacePaths:F.workspacePaths,projectDir:F.projectDir});return N}catch(V){throw await GW(H),V}}}}var ws6,$E8,JE8;var YE8=P(()=>{J6();nq();pU();ws6=["projectFolder","terminalsFolder","agentSharedNotesFolder","agentConversationNotesFolder","agentTranscriptsFolder","processWorkingDirectory","artifactsFolder"];$E8={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1};JE8=class JE8 extends j30{sessionMcpLease;constructor($,Z){super($);this.sessionMcpLease=Z}async dispose(){try{await super.dispose()}finally{await GW(this.sessionMcpLease)}}}});function QE8($){if(typeof $==="object"&&$!==null||typeof $==="function")KE8.add($)}function WE8($){return(typeof $==="object"&&$!==null||typeof $==="function")&&KE8.has($)}function Es6($,Z){return AggregateError([Z],"Workspace service loading failed and resource cleanup also failed.",{cause:$})}function ks6($,Z){let J=Object.keys(Z).filter((X)=>!FI1.includes(X));if(J.length>0)throw Error(`Workspace service contributors may only provide ${FI1.join(", ")}. Received unsupported service keys: ${J.join(", ")}.`);for(let X of FI1)if(Object.hasOwn(Z,X))$[X]=Z[X]}async function Rs6($){let Z;for(let J=$.length-1;J>=0;J-=1)try{await GW($[J])}catch(X){Z??=X}if(Z!==void 0)throw Z}async function NI1($,Z,J){let X={config:void 0,plugins:[],pluginBootstrapOutputs:[],cursorRulesService:void 0,getAgentSkills:void 0,subagentsService:void 0,mcpLease:void 0,hooksRuntime:void 0};try{X.config=$.config?await $.config.loadConfig(Z):void 0,X.plugins=$.plugins?await $.plugins.loadPlugins(Z):[];let Y=()=>({workspaceState:Z,policy:J,services:X});if(X.pluginBootstrapOutputs=$.pluginBootstrap?await $.pluginBootstrap.loadPluginBootstrapOutputs(Y()):X.pluginBootstrapOutputs,X.mcpLease=$.mcp?await $.mcp.createLease(Y()):void 0,X.hooksRuntime=$.hooks?await $.hooks.createHooksRuntime(Y()):void 0,$.localExtensibility?.prepareLocalExtensibility)await $.localExtensibility.prepareLocalExtensibility(Y());let Q=$.localExtensibility?await $.localExtensibility.loadLocalExtensibility(Y()):void 0;if(Q!==void 0)QE8(Q.cursorRulesService),QE8(Q.subagentsService),Object.assign(X,Q);for(let W of $.workspaceServicesContributors??[]){let K=await W.contributeServices(Y());if(K!==void 0)ks6(X,K)}return X}catch(Y){try{await Rl0(X,{disposeLocalExtensibility:$.localExtensibility===void 0?void 0:()=>$.localExtensibility?.disposeLocalExtensibility?.()})}catch(Q){throw Es6(Y,Q)}throw Y}}async function Rl0($,Z){let J=Z?.preserveSharedContributorsFrom,X,Y=async(Q)=>{try{await GW(Q)}catch(W){X??=W}};if($.subagentsService!==J?.subagentsService&&!WE8($.subagentsService))await Y($.subagentsService);if($.cursorRulesService!==J?.cursorRulesService&&!WE8($.cursorRulesService))await Y($.cursorRulesService);if(Z?.disposeLocalExtensibility)try{await Z.disposeLocalExtensibility()}catch(Q){X??=Q}await Y($.hooksRuntime),await Y($.mcpLease);try{await Rs6($.pluginBootstrapOutputs)}catch(Q){X??=Q}if(X!==void 0)throw X}var FI1,KE8;var LI1=P(()=>{FI1=["cursorRulesService","getAgentSkills","subagentsService"],KE8=new WeakSet});function Cs6($,Z){return AggregateError([Z],"Session creation failed and resource cleanup also failed.",{cause:$})}async function zE8($){let Z=new Set,J;for(let X=$.length-1;X>=0;X-=1){let Y=$[X];if(Z.has(Y))continue;Z.add(Y);try{await GW(Y)}catch(Q){J??=Q}}if(J!==void 0)throw J}async function HE8($){let Z={sessionId:$.options?.sessionId??L6(),createdAt:new Date},J=Object.freeze({...$.options?.metadata??{}}),X={options:$.options??{},workspaceState:$.workspaceState,workspaceServices:$.workspaceServices,policy:$.policy,sessionState:Z,metadata:J,getAgentSkills:$.workspaceServices.getAgentSkills},Y=void 0,Q=void 0,W=[];try{Y=$.adapters.resourceFactory?await $.adapters.resourceFactory.createResources(X):void 0,Q=Y,W.push(Y);for(let G of $.adapters.resourceWrappers??[])Q=await G.wrapResources({...X,baseResources:Y,resources:Q}),W.push(Q);await $.adapters.lifecycle?.onSessionCreated?.(Z)}catch(G){try{await zE8(W)}catch(q){throw Cs6(G,q)}throw G}let K={base:Y,wrapped:Q},H=!1;return{state:Z,resources:K,metadata:J,workspaceServices:$.workspaceServices,policy:$.policy,async dispose(){if(H)return;H=!0;try{await zE8(W)}finally{await $.adapters.lifecycle?.onSessionDisposed?.(Z)}}}}var UI1=P(()=>{B1()});function F71($){if($===void 0||$.length===0)return DI1([]);for(let J of $)if(!_s6.has(J))throw Error(`Unsupported setting source "${J}"`);if($.includes("all")){if($.length>1)throw Error('settingSources cannot mix "all" with individual setting sources');return{...DI1(GE8),all:!0}}let Z=$.filter((J)=>J!=="all");return DI1(Z)}function N7($,Z){return $[Z]}function DI1($){let Z=new Set($);return{project:Z.has("project"),user:Z.has("user"),team:Z.has("team"),mdm:Z.has("mdm"),plugins:Z.has("plugins"),all:!1}}var GE8,_s6;var qE8=P(()=>{GE8=["project","user","team","mdm","plugins"],_s6=new Set([...GE8,"all"])});function BE8($={}){let Z=Object.freeze({...VE8.metadata,...$.metadata}),J={...VE8,...$,metadata:Z};return{name:"permissive-sdk-local",resolvePolicy(){return J}}}async function OE8($,Z){return $.resolvePolicy(Z)}var Ss6,VE8;var FE8=P(()=>{Ss6=Object.freeze({}),VE8=Object.freeze({allowMcpServers:!0,allowPlugins:!0,allowBackgroundSessions:!0,requireMcpApproval:!1,maxParallelSessions:void 0,sandboxMode:void 0,metadata:Ss6})});var AI1=P(()=>{FE8()});async function NE8($={}){let Z=RI8($.adapters),J=await Z.workspace.resolveWorkspaceState({workingDirectory:$.workingDirectory,projectRoot:$.projectRoot,projectDirectory:$.projectDirectory,workspaceRoots:$.workspaceRoots}),X=await OE8($.policyAdapter??BE8(),{workspaceState:J}),Y=await NI1(Z,J,X),Q=!1,W=Promise.resolve(),K=(q)=>{let V=W.then(q);return W=V.catch(()=>{}),V},H=Z.localExtensibility,G=H===void 0?void 0:()=>H.disposeLocalExtensibility?.();return{state:J,get services(){return Y},policy:X,async createSessionRuntime(q={}){if(Q)throw Error("Cannot create a session runtime after the workspace runtime has been disposed.");return HE8({options:q,workspaceState:J,workspaceServices:Y,policy:X,adapters:Z})},async reload(){if(Q)return;await K(async()=>{if(Q)return;let q=Y,V=await NI1(Z,J,X);if(Q){await Rl0(V,{disposeLocalExtensibility:G});return}Y=V,await Rl0(q,{preserveSharedContributorsFrom:V,disposeLocalExtensibility:G}),await Z.lifecycle?.onWorkspaceReload?.(J)})},async dispose(){if(Q)return;Q=!0,await K(async()=>{try{await Rl0(Y,{disposeLocalExtensibility:G})}finally{await Z.lifecycle?.dispose()}})}}}var wI1=P(()=>{yM1();AI1();LI1();UI1()});var jI1=P(()=>{iI8();gP8();nP8();oP8();YE8();LI1();UI1();qE8();wI1()});import{resolve as vs6}from"path";class LE8{async requestApproval($){return{approved:!0}}}class UE8{approvalMode;userConfiguredPolicy;teamSettingsService;respectAdminControls;constructor($,Z,J,X){this.approvalMode=$;this.userConfiguredPolicy=Z;this.teamSettingsService=J;this.respectAdminControls=X}async getPermissions(){let $=this.respectAdminControls&&this.userConfiguredPolicy.type!=="insecure_none"?(await this.teamSettingsService.getSandboxingControls()).sandboxingDisabled:!1;return{allow:[],deny:[],approvalMode:this.approvalMode,userConfiguredPolicy:$?{type:"insecure_none"}:this.userConfiguredPolicy}}async updatePermissions(){}}class DE8{async open($,Z){}async getDiagnostics($,Z){return[]}}class AE8{async getCodebaseReference($,Z){return}}class wE8{inner;allowlistReports;constructor($,Z){this.inner=$;this.allowlistReports=Z}async getState($){let Z=await this.inner.getState($);return await this.reportAllowlists($),{...Z,servers:Z.servers.filter((J)=>J.status!=="needsAuth")}}async reportAllowlists($){if(this.allowlistReports===void 0)return;let{mcpLease:Z,onMcpAllowlistInUse:J,onMcpServerBlockedByAllowlist:X}=this.allowlistReports,Y;try{Y=await Z.getClients($)}catch(Q){Z6.warn("[sdk-mcp-state] Could not read the MCP allowlist in use:",Q);return}for(let[Q,W]of Object.entries(Y))try{if(J!==void 0){let K=await W.getAllowlistInUse?.();if(K!==void 0)J({serverName:Q,allowlist:K})}if(X!==void 0){let K=await W.getAllowlistRefusal?.();if(K!==void 0)X({serverName:Q,refusal:K})}}catch(K){Z6.warn("[sdk-mcp-state] Could not read the MCP allowlist in use:",K)}}}class N71{subagents;constructor($){this.subagents=$.map((Z)=>new NX({fullPath:`sdk-inline://${Z.name}`,name:Z.name,description:Z.description,tools:[],model:Z.model,prompt:Z.prompt,permissionMode:W4.DEFAULT,isBackground:!1,source:"sdk"}))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents}}function ys6($,Z){let J=[],X=new Set;for(let Y of[$,...Z??[]]){let Q=vs6(Y);if(X.has(Q))continue;X.add(Q),J.push(Y)}return J}async function jE8($){let{workingDirectory:Z,projectDir:J}=$,X=ys6(Z,$.dirs),Y=X.length>1?X:void 0,Q=F71($.settingSources),W=$.teamSettingsService??Zl0(),K=$.defaultSandboxPolicy??{type:"insecure_none"},H=$.getSandboxSupported??(()=>S20(K,{ctx:$.initializationCtx})),G=$.getSandboxEnabled??(()=>K.type!=="insecure_none"&&H()),q=new _K,V=new Xy0(q,W,X),O=new DE8,F=new AE8,N=$.getSmartModeClassifierAutoModeEnabled?.(),L=new UE8(N?"allowlist":$.approvalMode??"unrestricted",K,W,$.respectAdminControls??!1),U=$.pendingDecisionProvider,D={executeIndexedGrep:void 0},j=()=>!0,w=N7(Q,"plugins"),k=$.importThirdPartyPlugins??!1,T=$.mcpMetaToolEnabled??!0,I=$.mcpServers!==void 0&&Object.keys($.mcpServers).length>0,M=$.customSubagents!==void 0&&$.customSubagents.length>0,C=I||N7(Q,"project")||N7(Q,"user")||w,v=N7(Q,"project")||N7(Q,"user")||N7(Q,"mdm"),R=N7(Q,"team"),S=R&&$.dashboardTransport!==void 0,h=N7(Q,"project")||N7(Q,"user")||R||S||w,b={teamSettingsService:W,initializationCtx:$.initializationCtx,importThirdPartyPlugins:k,ignoreApprovals:!0,includeProjectMcp:N7(Q,"project"),includeUserMcp:N7(Q,"user"),includePluginMcp:w,isLinkSharedPaymentTokenLogRedactionEnabled:$.isLinkSharedPaymentTokenLogRedactionEnabled,restMcpCursorAuthTokenSupplier:$.restMcpCursorAuthTokenSupplier},_=(y)=>NE8({workingDirectory:Z,...Y!==void 0?{workspaceRoots:Y}:{},adapters:{...y.includeMcp?{mcp:bM1({...b,inlineMcpServers:$.mcpServers})}:{},...w?{pluginBootstrap:sP8({importThirdPartyPlugins:k,dashboardTransport:$.dashboardTransport})}:{},...v?{hooks:hP8({includeProjectHooks:N7(Q,"project"),includeUserHooks:N7(Q,"user"),includeEnterpriseHooks:N7(Q,"mdm"),useCommandHookStdinTransport:$.useCommandHookStdinTransport})}:{},...h?{localExtensibility:lP8({includeProjectExtensibility:N7(Q,"project"),includeUserExtensibility:N7(Q,"user"),includeManagedSkills:S,includeTeamExtensibility:R,includePluginExtensibility:w,teamSettingsService:W,getThirdPartyExtensibilityEnabled:j,dashboardTransport:$.dashboardTransport,importThirdPartyPlugins:k})}:{},resourceFactory:XE8({attributionConfigProvider:N7(Q,"user")?{get(){try{const{readFileSync:r}=process.getBuiltinModule("node:fs"),{join:j}=process.getBuiltinModule("node:path"),{homedir:h}=process.getBuiltinModule("node:os"),x=process.env.XDG_CONFIG_HOME,d=process.env.CURSOR_CONFIG_DIR||(x&&process.platform!=="darwin"&&process.platform!=="win32"?j(x,"cursor"):j(h(),".cursor"));return JSON.parse(r(j(d,"cli-config.json"),"utf8"))}catch{return}}}:void 0,ignoreService:V,grepProvider:D,workspacePaths:X,diagnosticsProvider:O,repositoryProvider:F,projectDir:J??Z,shellManager:void 0,defaultSandboxPolicy:K,defaultSandboxPolicySources:$.defaultSandboxPolicySources,getSandboxEnabled:G,getSandboxSupported:H,getNetworkAllowlistInfo:$.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:$.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:$.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:$.getMockPromptTime,getPowershellUtf8Options:$.getPowershellUtf8Options,mcpFileOutputThresholdBytes:void 0,mcpMetaToolEnabled:T,createMcpStateAccessor:(m,l)=>new wE8(new _b0(m),l?.onMcpAllowlistInUse===void 0&&l?.onMcpServerBlockedByAllowlist===void 0?void 0:{mcpLease:m,onMcpAllowlistInUse:l.onMcpAllowlistInUse,onMcpServerBlockedByAllowlist:l.onMcpServerBlockedByAllowlist}),createSessionMcpLease:(m,l)=>bM1({...b,includeProjectMcp:b.includeProjectMcp&&m.options.excludeProjectMcp!==!0,inlineMcpServers:l??$.mcpServers}).createLease({workspaceState:m.workspaceState,services:m.workspaceServices,policy:m.policy}),createSessionDependencies:(m)=>{let l=U??new LE8,i=new R81(Z),e=new D61(V,l,L,W,Z,$.respectAdminControls??!1,{enforceMcpAdminToolLimits:$.isMcpAdminToolLimitEnforced,onMcpAdminToolLimitCheck:m.options.onMcpAdminToolLimitCheck});return{pendingDecisionStore:l,fileChangeTracker:i,permissionsService:e}}}),resourceWrappers:v?[mP8()]:[],...M?{workspaceServicesContributors:[{contributeServices:(m)=>{let l=new N71($.customSubagents??[]),i=m.services.subagentsService;return{subagentsService:i===void 0?l:new kW0([l,i])}}}]}:{}}});if(!C)return _({includeMcp:!1});try{return await _({includeMcp:!0})}catch(y){return Z6.warn("[default-local-workspace-runtime] Failed to initialize MCP-enabled runtime, retrying without MCP:",{error:y,workingDirectory:Z,projectDir:J,enablePlugins:w,importThirdPartyPlugins:k}),_({includeMcp:!1})}}var ME8=P(()=>{nq();sK();K7();jI1();wI1();l3()});var IE8=()=>{};function TE8($){let{workspaceRuntime:Z}=$;if(!(Z.hooksConfigLease.hasHookForStep(i0.sessionStart)||Z.hooksConfigLease.hasHookForStep(i0.sessionEnd)||Z.hooksConfigLease.hasHookForStep(i0.stop)||Z.hooksConfigLease.hasHookForStep(i0.beforeSubmitPrompt)))return{};let X=Z.createSessionRuntime({sessionState:$.sessionState,metadata:$.metadata}),{hookExecutor:Y}=X,Q;return{async onSessionStart(W){if(Q=W,!Y.hasHooksForStep(i0.sessionStart))return;try{let K={conversation_id:W.conversationId,generation_id:W.generationId,model:W.model,...g5(W),is_background_agent:!1},H=await Y.executeHookForStep(i0.sessionStart,K);if(H){if(H.env)Y.setSessionEnvironment(H.env);return{env:H.env,additionalContext:H.additional_context,blocked:H.continue===!1,blockedReason:H.user_message}}}catch(K){Z6.warn("[hooks-adapter] sessionStart hook failed:",K)}return},async onSessionEnd(W,K){if(!Y.hasHooksForStep(i0.sessionEnd)){Y.clearSessionEnvironment();return}try{let H={conversation_id:Q?.conversationId??"",generation_id:Q?.generationId??"",model:Q?.model??"unknown",...Q?g5(Q):{},reason:W,duration_ms:K,is_background_agent:!1,final_status:W};await Y.executeHookForStep(i0.sessionEnd,H)}catch(H){Z6.warn("[hooks-adapter] sessionEnd hook failed:",H)}finally{Y.clearSessionEnvironment()}},async onBeforeSubmitPrompt(W){if(!Y.hasHooksForStep(i0.beforeSubmitPrompt))return;try{let K={conversation_id:W.conversationId,generation_id:W.generationId,model:W.model,...g5(W),prompt:W.promptText??"",attachments:[]};await Y.executeHookForStep(i0.beforeSubmitPrompt,K)}catch(K){Z6.warn("[hooks-adapter] beforeSubmitPrompt hook failed:",K)}},async onTurnCompleted(W){if(!Y.hasHooksForStep(i0.stop))return;let K={conversation_id:W.conversationId,generation_id:W.generationId,model:W.model,...g5(W),status:"completed",loop_count:W.loopCount},H=await Y.executeHookForStep(i0.stop,K),G=typeof H?.followup_message==="string"?H.followup_message.trim():"";return G.length>0?G:void 0},async onTurnError(W){if(!Y.hasHooksForStep(i0.stop))return;try{let K={conversation_id:W.conversationId,generation_id:W.generationId,model:W.model,...g5(W),status:"error",loop_count:W.loopCount};await Y.executeHookForStep(i0.stop,K)}catch(K){Z6.warn("[hooks-adapter] onTurnError stop hook failed:",K)}},async onTurnAborted(W){if(!Y.hasHooksForStep(i0.stop))return;try{let K={conversation_id:W.conversationId,generation_id:W.generationId,model:W.model,...g5(W),status:"aborted",loop_count:W.loopCount};await Y.executeHookForStep(i0.stop,K)}catch(K){Z6.warn("[hooks-adapter] onTurnAborted stop hook failed:",K)}},async dispose(){await X.dispose()}}}var PE8=P(()=>{q9();l3()});import{accessSync as xs6,constants as bs6,mkdtempSync as fs6,statSync as hs6}from"fs";import{homedir as ms6,tmpdir as gs6}from"os";import{join as L71}from"path";function us6($){if($.trim()==="")return!1;try{if(!hs6($).isDirectory())return!1;return xs6($,bs6.W_OK),!0}catch{return!1}}function cs6($){return fs6(L71($,"cursor-transcripts-"))}function ds6($){let Z=$.cursorDataDir?.trim();if(Z)return L71(Z,"projects",XQ($.workspacePath));if($.homeDir!==void 0&&us6($.homeDir))return L71($.homeDir,".cursor","projects",XQ($.workspacePath));return L71($.ensureFallbackRoot($.tempDir),XQ($.workspacePath))}function II1($){if(process.env.CURSOR_DATA_DIR?.trim())return tp0($);let J;try{J=ms6()}catch{J=void 0}return ds6({workspacePath:$,homeDir:J,tempDir:gs6(),ensureFallbackRoot:(X)=>{if(MI1===void 0)MI1=cs6(X);return MI1}})}var MI1;var EE8=P(()=>{l51();B1()});import{mkdir as ps6,writeFile as ls6}from"fs/promises";import{dirname as is6,join as U71}from"path";function ns6($,Z){let J=hK({conversationId:Z,ext:"jsonl",kind:"primary"});return U71(II1($),J)}async function kE8($,Z){let J=is6($);await ps6(J,{recursive:!0}),await ls6($,Z,"utf-8")}class Cl0{transcriptStore;nestedSubagentTranscriptStore;projectDir;conversationId;workspacePath;parentConversationId;blobStore;writeChain=Promise.resolve();constructor($){this.workspacePath=$.workspacePath,this.conversationId=$.conversationId,this.parentConversationId=$.parentConversationId,this.blobStore=$.blobStore,this.projectDir=II1(this.workspacePath);let Z=this.parentConversationId?(X,Y)=>{let Q=hK({conversationId:X,ext:Y,kind:"subagent",parentConversationId:this.parentConversationId});return U71(this.projectDir,Q)}:void 0;this.transcriptStore=new e51(this.projectDir,$.blobStore,kE8,{writeText:!1,writeJsonl:!0,...Z?{pathResolver:Z}:{}});let J=(X,Y)=>{let Q=hK({conversationId:X,ext:Y,kind:"subagent",parentConversationId:this.conversationId});return U71(this.projectDir,Q)};this.nestedSubagentTranscriptStore=new e51(this.projectDir,$.blobStore,kE8,{writeText:!1,writeJsonl:!0,pathResolver:J})}enqueueWrite($,Z){let J=this.writeChain;return this.writeChain=J.then(async()=>{try{await $()}catch(X){Z6.warn(`${Z} ${X instanceof Error?X.message:String(X)}`)}}),this.writeChain}async writeFromState($,Z){return this.enqueueWrite(async()=>{await this.transcriptStore.writeFromStateFull($,Z,this.conversationId);let J=await ch0($,Z,this.blobStore);for(let[X,Y]of Object.entries(J)){if(!Y?.conversationState)continue;await this.nestedSubagentTranscriptStore.writeFromStateFull($,Y.conversationState,X)}},"[LocalTranscriptWriter] Failed to write transcript:")}async writeTurnEndedFromState($,Z,J){return this.enqueueWrite(async()=>{await this.transcriptStore.writeFromStateFull($,Z,this.conversationId,{turnEnded:J})},"[LocalTranscriptWriter] Failed to write turn-ended transcript:")}waitForPendingWrites(){return this.writeChain}getTranscriptPath(){if(this.parentConversationId){let $=hK({conversationId:this.conversationId,ext:"jsonl",kind:"subagent",parentConversationId:this.parentConversationId});return U71(this.projectDir,$)}return ns6(this.workspacePath,this.conversationId)}getProjectDir(){return this.projectDir}}var TI1=P(()=>{hJ();o51();l3();EE8()});function rs6($){if(!as6.test($))throw Error(`Invalid resumeAgentId format: ${$}`)}function ss6($){let Z=new aC0,J=YQ($),X=new xN(new nC0,Z);return X.setMetadata("agentId",J.agentId),X.setMetadata("latestRootBlobId",J.latestRootBlobId),X.setMetadata("name",J.name),X.setMetadata("createdAt",J.createdAt),X.setMetadata("mode",J.mode),X.setMetadata("isRunEverything",J.isRunEverything),X.setMetadata("lastUsedModel",J.lastUsedModel),X.setMetadata("lastDebugServerPort",J.lastDebugServerPort),X.setMetadata("currentPlanUri",J.currentPlanUri),X.setMetadata("subagentInfo",J.subagentInfo),X.setMetadata("blobEncryptionKey",J.blobEncryptionKey),X}function os6($){let Z=$.query.case;switch(Z){case"webSearchRequestQuery":return H6.webSearchRejected($.id,"Web search is not supported in local subagent");case"webFetchRequestQuery":return H6.webFetchRejected($.id,"Web fetch is not supported in local subagent");case"switchModeRequestQuery":return H6.switchModeRejected($.id,"Subagent mode switches are not supported in local subagent");case"askQuestionInteractionQuery":{let J=new jZ({result:{case:"rejected",value:new yY({reason:"Interactive questions are not supported in local subagent mode"})}});return H6.askQuestion($.id,J)}default:throw Error(`Unhandled interaction query type in local subagent: ${String(Z)}`)}}class EI1{sessions=new Map;backgroundRuns=new Map;activeForegroundExecutions=new Map;backgroundPromises=new Set;pendingReleaseSessions=new Set;childParentIds=new Map;parentChildIds=new Map;queuedChildCompletions=new Map;childCompletionWaiters=new Map;childLineageRequestIds=new Map;untrackedParentRequestIds=new Map;rootLineageRequestId;lifecycleStore;agentClient;getResources;mcpTools;workspacePath;parentConversationId;headers;endlessRetries;onSessionCreated;onInteractionUpdate;onSessionCompleted;onSessionReleased;onSubagentTokenDelta;constructor($){this.agentClient=$.agentClient,this.getResources=$.getResources,this.mcpTools=$.mcpTools??[],this.workspacePath=$.workspacePath,this.parentConversationId=$.parentConversationId;let Z=$.rootRequestId?.trim();this.rootLineageRequestId=Z!==void 0&&Z.length>0?Z:L6(),this.headers=$.headers,this.endlessRetries=$.endlessRetries,this.onSessionCreated=$.onSessionCreated,this.onInteractionUpdate=$.onInteractionUpdate,this.onSessionCompleted=$.onSessionCompleted,this.onSessionReleased=$.onSessionReleased,this.onSubagentTokenDelta=$.onSubagentTokenDelta,this.lifecycleStore=new js0}async createOrResumeSession($,Z){if(Z.forkAgentId)throw Error("forkAgentId is not supported in local subagents.");let J=Z.resumeAgentId;if(J)rs6(J);if(J&&!Z.prompt)return J;if(J&&Ms0(Z.prompt)&&this.isBackgroundRunBusy(J))throw Error(gW1);if(J){if(this.sessions.get(J))return J}let X=J??L6(),Y=ss6(X),Q=new Cl0({workspacePath:this.workspacePath,conversationId:X,parentConversationId:this.parentConversationId,blobStore:Y.getBlobStore()});return this.sessions.set(X,{agentStore:Y,transcriptWriter:Q,toolCallId:Z.toolCallId}),this.onSessionCreated?.({agentId:X,toolCallId:Z.toolCallId,subagentType:Z.subagentType,parentAgentId:Z.parentConversationId}),X}async runSession($,Z,J,X){if(this.isAwaitBackgroundMode(J))return this.awaitBackgroundRun(J.resumeAgentId,$.signal);let Y=this.sessions.get(Z);if(!Y)return{status:"error",error:`Subagent session not found: ${Z}`};if(J.runInBackground){let[O,F]=$.withDetached().withCancel();return this.registerBackgroundRun(Z,this.executeSubagent(O,Z,J,Y),J.parentConversationId,F),{status:"background",backgroundReason:NZ.AGENT_REQUEST,toolCallCount:0}}let[Q,W]=$.withDetached().withCancel(),K=!1,H=()=>{if(!K)W()};if($.signal.addEventListener("abort",H,{once:!0}),$.signal.aborted)H();let G=()=>{},q=new Promise((O)=>{G=O}),V={requestBackground:()=>{if(K)return!0;if(Q.signal.aborted)return!1;return K=!0,$.signal.removeEventListener("abort",H),G(),!0}};this.activeForegroundExecutions.set(J.toolCallId,V),this.activeForegroundExecutions.set(Z,V);try{let O=this.executeSubagent(Q,Z,J,Y),F=await Promise.race([O.then((N)=>({handedOff:!1,outcome:N})),q.then(()=>({handedOff:!0}))]);if(F.handedOff)return this.registerBackgroundRun(Z,O,J.parentConversationId,W),{status:"background",backgroundReason:NZ.USER_REQUEST,toolCallCount:0};return this.onSessionCompleted?.(Z,F.outcome),F.outcome}finally{if(this.clearForegroundExecution(J.toolCallId,V),this.clearForegroundExecution(Z,V),!K)$.signal.removeEventListener("abort",H)}}forceBackgroundByToolCallId($){if(!this.activeForegroundExecutions.get($)?.requestBackground())return new m3({status:dh0.NOT_FOUND});return new m3({status:dh0.ACCEPTED})}clearForegroundExecution($,Z){if(this.activeForegroundExecutions.get($)===Z)this.activeForegroundExecutions.delete($)}releaseSession($){if(this.lifecycleStore.release($),this.isBackgroundRunBusy($)){this.pendingReleaseSessions.add($);return}this.cleanupSession($)}async awaitBackgroundWorkers(){while(this.backgroundPromises.size>0)await Promise.allSettled([...this.backgroundPromises])}async waitForBackgroundCompletions($,Z){return this.collectAvailableChildCompletions($,Z)}isBackgroundRunBusy($){return this.lifecycleStore.isBusy($)||this.backgroundRuns.has($)}registerBackgroundRun($,Z,J,X){this.registerParentChildLink($,J);let Y=this.lifecycleStore.startRun($,{abort:X}),Q=Z.catch((K)=>{return{status:"error",error:K instanceof Error?K.message:String(K)}}),W={runId:Y,promise:Q};this.backgroundRuns.set($,W),this.backgroundPromises.add(Q),Q.then((K)=>{if(this.lifecycleStore.finishRun($,Y),this.backgroundRuns.get($)?.runId===Y){this.backgroundRuns.delete($),this.enqueueChildCompletion($,Y,K),this.maybeCleanupReleasedSession($);try{this.onSessionCompleted?.($,K)}catch(G){Z6.error("[LocalSubagentHostAdapter] onSessionCompleted threw after background run",{agentId:$,error:G instanceof Error?G.message:String(G)})}}return K}).finally(()=>this.backgroundPromises.delete(Q))}maybeCleanupReleasedSession($){if(this.pendingReleaseSessions.has($)&&!this.isBackgroundRunBusy($))this.cleanupSession($)}cleanupSession($){this.pendingReleaseSessions.delete($);let Z=this.sessions.get($);if(!Z)return;let J=this.parentChildIds.get($);if(J)for(let X of J)this.childParentIds.delete(X);this.removeParentChildLink($),this.parentChildIds.delete($),this.queuedChildCompletions.delete($),this.childCompletionWaiters.delete($),Z.transcriptWriter.waitForPendingWrites().catch(()=>{}),this.sessions.delete($),this.onSessionReleased?.($)}async executeSubagent($,Z,J,X){if(J.continuationConfig)return this.executeSubagentWithContinuation($,Z,J,X,J.continuationConfig);return this.executeSubagentOnce($,Z,J,X)}async executeSubagentWithContinuation($,Z,J,X,Y){let Q=Y.maxLoops>0?Y.maxLoops:Number.POSITIVE_INFINITY,W=await this.runContinuationLoop($,Z,J,X,Y,Q);if(!Y.collectBackgroundChildren||W.status!=="completed")return W;let K=500;for(let H=0;H0){W=0,K=void 0;continue}W+=1,K=W>=Y.idleThreshold?`DONE_${L6().replace(/-/g,"").slice(0,8)}`:void 0}return H??{status:"error",error:"Subagent continuation exited unexpectedly"}}computeContinuationNudge($,Z,J){if(Z>=$.idleThreshold&&J!==void 0)return $.escapeMessageTemplate.replace("{idle_count}",String(Z)).replace("{escape_token}",J);return $.nudgeMessage}lineageForChildRun($){if(!this.childLineageRequestIds.has($.agentId))this.childLineageRequestIds.set($.agentId,L6());let Z=$.parentConversationId?.trim()??"",J=$.toolCallId.trim();return{parentRequestId:Z===""||Z===this.parentConversationId?this.rootLineageRequestId:this.childLineageRequestIds.get(Z)??this.untrackedParentRequestId(Z),rootParentRequestId:this.rootLineageRequestId,...J.length>0?{parentAgentToolCallId:J}:{}}}untrackedParentRequestId($){let Z=this.untrackedParentRequestIds.get($);if(Z===void 0)Z=L6(),this.untrackedParentRequestIds.set($,Z);return Z}async executeSubagentOnce($,Z,J,X){let Y=this.lineageForChildRun({agentId:Z,parentConversationId:J.parentConversationId,toolCallId:J.toolCallId}),Q,W=0,K=new N$({action:{case:"userMessageAction",value:new f9({userMessage:new v5({text:J.prompt})})}}),H=new mY({modelId:J.modelId,displayModelId:J.modelId,displayName:J.modelId});if(J.credentials.case!==void 0)H.credentials=J.credentials;let G=new um0,q={sendUpdate:async(O,F)=>{if(F.message.case==="tokenDelta")this.onSubagentTokenDelta?.(Z,F.message.value.tokens);if(F.message.case==="toolCallStarted"||F.message.case==="toolCallCompleted"||F.message.case==="partialToolCall")this.onInteractionUpdate?.(Z,F);if(F.message.case==="toolCallCompleted")W++;if(F.message.case==="textDelta")Q=(Q??"")+F.message.value.text},query:async(O,F)=>{return os6(F)}},V={handleCheckpoint:async(O,F)=>{await X.agentStore.handleCheckpoint(O,F),X.transcriptWriter.writeFromState(O,F)},getLatestCheckpoint:()=>{return X.agentStore.getLatestCheckpoint()}};try{let O=J.rootParentConversationId?.trim(),F=J.parentConversationId?.trim(),N=O!==void 0&&O!==""?O:F!==void 0&&F!==""?F:Z,L=await this.getResources({agentId:Z,parentAgentId:J.parentConversationId}),U=J.readonly?EW1(L):L;return await this.agentClient.run($,X.agentStore.getConversationStateStructure(),K,H,q,U,X.agentStore.getBlobStore(),G,V,[...this.mcpTools],{conversationGroupId:N,conversationId:Z,...X.transcriptWriter.parentConversationId?{transcriptParentConversationId:X.transcriptWriter.parentConversationId}:{},subagentTypeName:J.subagentType||void 0,...Y,headers:i51(X.agentStore.getMetadata("blobEncryptionKey"),this.headers),endlessRetries:this.endlessRetries,subagentModelOverrides:[]}),await X.transcriptWriter.writeTurnEndedFromState($,X.agentStore.getConversationStateStructure(),$.signal.aborted?{status:"aborted",error:PI1}:{status:"success"}),{status:"completed",finalMessage:Q,toolCallCount:W}}catch(O){let F=O instanceof Error?O.message:String(O);if(Z6.error("[LocalSubagentHostAdapter] Subagent session failed",{agentId:Z,error:F}),await X.transcriptWriter.writeTurnEndedFromState($,X.agentStore.getLatestCheckpoint()??X.agentStore.getConversationStateStructure(),this.getTurnEndedFromError($,F)),$.signal.aborted)return{status:"aborted",error:PI1};return{status:"error",error:F}}}getTurnEndedFromError($,Z){return $.signal.aborted?{status:"aborted",error:PI1}:{status:"error",error:Z}}isAwaitBackgroundMode($){if(!Boolean($.resumeAgentId&&!Ms0($.prompt)&&$.readonly&&$.runInBackground!==!0))return!1;if(($.parentConversationId??"").trim().length===0)throw Error(`Missing parentConversationId for subagent await/status check (subagentId: ${$.resumeAgentId})`);return!0}async awaitBackgroundRun($,Z){let J=this.backgroundRuns.get($);if(!J){if(this.isBackgroundRunBusy($))return this.awaitBusyLifecycleRun($,Z);return{status:"error",error:`No background subagent found for id: ${$}`}}return this.awaitBackgroundEntry(J,Z)}async awaitBackgroundRunBounded($,Z){let J=Z.agentId;if($.signal.aborted)return new p9({result:{case:"stillRunning",value:new f3({agentId:J})}});let X=this.backgroundRuns.get(J);if(X===void 0){let K=this.takeQueuedChildCompletion(J);if(K!==void 0){if(K.status==="success")return new p9({result:{case:"complete",value:new VG({agentId:J,finalMessage:K.finalMessage,toolCallCount:K.toolCallCount??0})}});return new p9({result:{case:"error",value:new BG({agentId:J,error:K.finalMessage||"Subagent was aborted"})}})}if(this.isBackgroundRunBusy(J))return new p9({result:{case:"stillRunning",value:new f3({agentId:J})}});return new p9({result:{case:"notFound",value:new bN({agentId:J})}})}let[Y,Q]=$.withTimeoutAndCancel(Math.max(0,Z.timeoutMs)),W=await new Promise((K)=>{let H=()=>K(void 0);Y.signal.addEventListener("abort",H,{once:!0}),X.promise.then(K).finally(()=>{Y.signal.removeEventListener("abort",H),Q()})});if(W===void 0||W.status==="background"||$.signal.aborted)return new p9({result:{case:"stillRunning",value:new f3({agentId:J})}});if(this.takeQueuedChildCompletion(J,X.runId),W.status==="completed")return new p9({result:{case:"complete",value:new VG({agentId:J,finalMessage:W.finalMessage,toolCallCount:W.toolCallCount??0})}});return new p9({result:{case:"error",value:new BG({agentId:J,error:W.error??"Subagent was aborted"})}})}takeQueuedChildCompletion($,Z){for(let[J,X]of this.queuedChildCompletions){let Y=X.findIndex((W)=>W.agentId===$&&(Z===void 0||W.runId===Z));if(Y===-1)continue;let[Q]=X.splice(Y,1);if(X.length===0)this.queuedChildCompletions.delete(J);return Q}return}async awaitBusyLifecycleRun($,Z){while(this.isBackgroundRunBusy($)){if(Z.aborted)return{status:"error",error:"Await timed out while task is still running"};let J=this.backgroundRuns.get($);if(J)return this.awaitBackgroundEntry(J,Z);await new Promise((X)=>setTimeout(X,50))}return{status:"completed",toolCallCount:0}}async awaitBackgroundEntry($,Z){if(Z.aborted)return{status:"error",error:"Await timed out while task is still running"};let J={status:"error",error:"Await timed out while task is still running"};return new Promise((X)=>{let Y=()=>{X(J)};Z.addEventListener("abort",Y,{once:!0}),$.promise.then(X).finally(()=>Z.removeEventListener("abort",Y))})}registerParentChildLink($,Z){let J=Z?.trim();if(!J||J===$||!this.sessions.has(J)&&J!==this.parentConversationId)return;let X=this.childParentIds.get($);if(X===J)return;if(X){if(this.parentChildIds.get(X)?.delete($),(this.parentChildIds.get(X)?.size??0)===0)this.parentChildIds.delete(X)}this.childParentIds.set($,J);let Y=this.parentChildIds.get(J)??new Set;Y.add($),this.parentChildIds.set(J,Y)}removeParentChildLink($){let Z=this.childParentIds.get($);if(!Z)return;this.childParentIds.delete($);let J=this.parentChildIds.get(Z);if(J?.delete($),(J?.size??0)===0)this.parentChildIds.delete(Z)}enqueueChildCompletion($,Z,J){let X=this.childParentIds.get($);if(!X)return;let Y=this.queuedChildCompletions.get(X)??[];Y.push({agentId:$,runId:Z,status:J.status==="completed"?"success":J.status==="error"?"error":"aborted",finalMessage:J.status==="completed"?J.finalMessage??"":J.status==="error"?J.error:"Subagent was aborted by the user",...J.status==="completed"&&J.toolCallCount!==void 0?{toolCallCount:J.toolCallCount}:{}}),this.queuedChildCompletions.set(X,Y),this.removeParentChildLink($);let Q=this.childCompletionWaiters.get(X);if(!Q)return;this.childCompletionWaiters.delete(X);for(let W of Q)W()}async collectAvailableChildCompletions($,Z){let J=this.drainChildCompletions($);if(J.length>0)return J;if(!this.hasPendingChildSubagents($))return[];return await this.waitForChildCompletion($,Z),this.drainChildCompletions($)}hasPendingChildSubagents($){return(this.parentChildIds.get($)?.size??0)>0}drainChildCompletions($){let Z=this.queuedChildCompletions.get($)??[];return this.queuedChildCompletions.delete($),Z}async waitForChildCompletion($,Z){if(Z.aborted)throw Error("aborted");await new Promise((J,X)=>{let Y=this.childCompletionWaiters.get($)??new Set,Q=()=>{K(),J()},W=()=>{K(),X(Error("aborted"))},K=()=>{if(Y.delete(Q),Y.size===0)this.childCompletionWaiters.delete($);Z.removeEventListener("abort",W)};Y.add(Q),this.childCompletionWaiters.set($,Y),Z.addEventListener("abort",W,{once:!0})})}buildChildrenCompletedMessage($,Z){let J=$.map((X)=>{let Y=X.status==="success"?"SUCCESS":"FAILED";return`## Agent ${X.agentId} -- ${Y} ++`)}})}function pr6($){return{toolName:i8.Write,getToolCallId:T5,createToolInput:(Z)=>({file_path:Z.path,content:Z.fileText}),applyUpdatedInput:(Z,J)=>{if(typeof J.file_path==="string")Z.path=J.file_path},createRejectedResult:(Z,J)=>new z6({result:{case:"error",value:new L5({path:Z.path,error:J})}}),isSuccess:(Z)=>Z.result.case==="success",getErrorMessage:(Z)=>{if(Z.result.case==="error")return Z.result.value.error||"Write error";return"Unknown error"},createSuccessOutput:(Z)=>({file_path:Z.path,success:!0}),runPreExecutionHooks:async(Z)=>{let{args:J,hookExecutor:X,toolUseId:Y}=Z;if(X.hasHooksForStep?.(i0.afterFileEdit)===!1)return;let Q,W=!1;try{if((await cr6(J.path)).size>HI1)W=!0;else Q=await K$(J.path)}catch(K){}$.set(Y,{contentBeforeWrite:Q,fileTooLarge:W});return},runCleanup:(Z)=>{$.delete(Z)},runPostExecutionHooks:async(Z)=>{let{args:J,result:X,baseHookRequest:Y,hookExecutor:Q,toolUseId:W}=Z,K=$.get(W);if(X.result.case!=="success"||Q.hasHooksForStep?.(i0.afterFileEdit)===!1)return;let{contentBeforeWrite:H,fileTooLarge:G}=K??{fileTooLarge:!1},q;if(G)q=[{old_string:"",new_string:J.fileText}];else if(H===void 0)q=[{old_string:"",new_string:J.fileText}];else if(H===J.fileText)q=[];else q=GI1(H,J.fileText);let V={...Y,file_path:J.path,edits:q},O=await Q.executeHookForStep(i0.afterFileEdit,V);if(J.returnFileContentAfterWrite&&O!==void 0){let F=X.result.value.path;try{let N=await K$(F),L=SJ(N),U=Buffer.byteLength(N,"utf8");return new z6({result:{case:"success",value:new $Q({path:X.result.value.path,linesCreated:L,fileSize:U,fileContentAfterWrite:N})}})}catch(N){return}}return}}}class Pl0{wrappedExecutor;constructor($,Z,J){let X=new Map;this.wrappedExecutor=l6($,Z,J,pr6(X))}execute($,Z,J){return this.wrappedExecutor.execute($,Z,J)}}var HI1=262144,dr6=50;var CP8=P(()=>{q9();ZG();o9();$U1();OZ();BZ()});var qI1=P(()=>{OP8();FP8();NP8();LP8();UP8();DP8();AP8();jP8();MP8();IP8();TP8();EP8();RP8();CP8()});function l7($,Z,J){return Z===$.symbol}function _P8($,Z,J){if(l7(mG,$,Z))return new Il0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(a9,$,Z))return new Tl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(D20,$,Z))return new Pl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(a3,$,Z))return new Al0(Z,J.hookExecutor,J.baseHookRequestExtractor,J.mcpLease,J.hooksConfigLease);if(l7(tS0,$,Z))return new mb0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(xm0,$,Z))return new mb0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(_m0,$,Z))return new Dl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(Mm0,$,Z))return new Ul0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(wm0,$,Z))return new Ll0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(V20,$,Z))return new Fl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(B20,$,Z))return new Nl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(vm0,$,Z))return new wl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(ym0,$,Z))return new jl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(xG,$,Z))return new Vl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(bG,$,Z))return new Bl0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(Am0,$,Z))return new Ol0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(mm0,$,Z))return new Ml0(Z,J.hookExecutor,J.baseHookRequestExtractor);if(l7(r9,$,Z)&&(J.hooksAdditionalContextPromise||J.hooksConfigLease))return new H71(Z,J.hooksAdditionalContextPromise??Promise.resolve(void 0),J.teamHooksReadyPromise,J.hooksConfigLease);return}function lr6($,Z){if($.symbol!==qs0.symbol)return;return new Cm0(Z)}function ir6($,Z,J){let X=_P8($.symbol,Z,J);if(X!==void 0)return X;return Z}class V71{innerAccessor;hookExecutor;baseHookRequestExtractor;mcpLease;hooksAdditionalContextPromise;teamHooksReadyPromise;hooksConfigLease;constructor($,Z,J,X,Y,Q,W){this.innerAccessor=$;this.hookExecutor=Z;this.baseHookRequestExtractor=J;this.mcpLease=X;this.hooksAdditionalContextPromise=Y;this.teamHooksReadyPromise=Q;this.hooksConfigLease=W}get($){let Z=lr6($,this.hookExecutor);if(Z!==void 0)return Z;return ir6($,this.innerAccessor.get($),{hookExecutor:this.hookExecutor,baseHookRequestExtractor:this.baseHookRequestExtractor,mcpLease:this.mcpLease,hooksAdditionalContextPromise:this.hooksAdditionalContextPromise,teamHooksReadyPromise:this.teamHooksReadyPromise,hooksConfigLease:this.hooksConfigLease})}*entries(){for(let[Z,J]of this.innerAccessor.entries()){let X=_P8(Z.symbol,J,{hookExecutor:this.hookExecutor,baseHookRequestExtractor:this.baseHookRequestExtractor,mcpLease:this.mcpLease,hooksAdditionalContextPromise:this.hooksAdditionalContextPromise,teamHooksReadyPromise:this.teamHooksReadyPromise,hooksConfigLease:this.hooksConfigLease});yield[Z,X??J]}yield[qs0,new Cm0(this.hookExecutor)]}}var SP8=P(()=>{J6();WI1();qI1()});var vP8=P(()=>{X2()});var yP8=P(()=>{nI8();AT8();eT8();Gl0();$P8();OZ();VP8();bb0();BP8();sM1();WI1();SP8();QI1();qI1();BZ();vP8()});import{spawn as nr6}from"child_process";import{homedir as xP8}from"os";import{join as El0}from"path";function rr6($){if(process.platform==="win32")return{executable:FQ(),args:[...Pl1,"-Command",$]};return{executable:process.env.SHELL||"/bin/sh",args:["-lc",$]}}function bP8($=process.cwd()){let Z=$;return{async getCwd(){return Z},clone(X){return bP8(X??Z)},async*execute(X,Y,Q={}){let W=Q.workingDirectory??Z;Z=W;let K=rr6(Y),H=nr6(K.executable,[...K.args],{cwd:W,env:{...process.env,...Q.env??{}},signal:Q.signal,stdio:[Q.pipeStdin===!0?"pipe":"ignore","pipe","pipe"]}),G=[],q,V,O=!1,F=()=>{q?.(),q=void 0},N=(L)=>{G.push(L),F()};H.on("spawn",()=>{if(Q.pipeStdin===!0)N({type:"stdin_ready",stdin:H.stdin??void 0})}),H.stdout?.setEncoding("utf8"),H.stdout?.on("data",(L)=>{N({type:"stdout",data:String(L)})}),H.stderr?.setEncoding("utf8"),H.stderr?.on("data",(L)=>{N({type:"stderr",data:String(L)})}),H.on("error",(L)=>{V=L,O=!0,F()}),H.on("close",(L)=>{N({type:"exit",code:L}),O=!0});while(!O||G.length>0){if(G.length===0){await new Promise((L)=>{q=L});continue}yield G.shift()}if(V!==void 0)throw V}}}function sr6($){return $.projectRoot??$.workingDirectory??$.workspaceRoots[0]??process.cwd()}function or6($,Z){let J=$.projectRoot??$.workingDirectory??$.workspaceRoots[0],X=Z.includeProjectHooks??!0,Y=Z.includeUserHooks??!0;return{enterpriseConfigPath:Z.includeEnterpriseHooks??!0?nM1():void 0,userConfigPath:Y?El0(xP8(),".cursor","hooks.json"):void 0,claudeUserConfigPath:Y?El0(xP8(),".claude","settings.json"):void 0,projectConfigPath:X&&J!==void 0?El0(J,".cursor","hooks.json"):void 0,claudeProjectConfigPath:X&&J!==void 0?El0(J,".claude","settings.json"):void 0,claudeProjectLocalConfigPath:X&&J!==void 0?El0(J,".claude","settings.local.json"):void 0}}function tr6($){return Object.freeze({...ar6,...$.globalContext??{}})}function kl0($,Z,...J){for(let X of J){let Y=Z($[X]);if(Y!==void 0)return Y}return}function B71($){return typeof $==="string"&&$.length>0?$:void 0}function er6($){return typeof $==="object"&&$!==null&&typeof $.id==="string"&&typeof $.value==="string"}function $s6($){if(!Array.isArray($))return;if(!$.every(er6))return;return $.map((Z)=>({id:Z.id,value:Z.value}))}function Zs6($,Z){let J=kl0(Z,B71,"conversationId","conversation_id")??$.sessionId??"",X=kl0(Z,B71,"generationId","generation_id")??J,Y=kl0(Z,B71,"model")??"unknown",Q=kl0(Z,B71,"modelId","model_id"),W=kl0(Z,$s6,"modelParams","model_params");return{conversation_id:J,generation_id:X,model:Y,...g5({modelId:Q,modelParams:W})}}function Js6($){return typeof $==="object"&&$!==null&&"get"in $&&typeof $.get==="function"&&"entries"in $&&typeof $.entries==="function"}function Xs6($){return typeof $==="object"&&$!==null&&"hooksConfigLease"in $&&"createSessionRuntime"in $&&typeof $.createSessionRuntime==="function"}class fP8{innerAccessor;sessionHooksRuntime;constructor($,Z){this.innerAccessor=$;this.sessionHooksRuntime=Z}get($){return this.innerAccessor.get($)}entries(){return this.innerAccessor.entries()}async dispose(){await this.sessionHooksRuntime.dispose()}}async function Ys6($,Z={}){let J=await new I30(new z71,or6($,Z)).load(),X=new X71(J),Y=sr6($),Q=tr6(Z);return{projectDir:$.projectRoot,workspacePath:Y,hooksConfig:J,hooksConfigLease:X,globalContext:Q,createSessionRuntime(){let W=new J71(J,Y,Q,(Z.createTerminalExecutor??bP8)(),Z.promptHookClient,void 0,void 0,{enableClaudeNestedHookSpecificOutputCompatibility:!0,commandHookPayloadTransport:Tl1(Z.useCommandHookStdinTransport)});return{hookExecutor:W,hooksConfigLease:X,async dispose(){W.clearSessionEnvironment()}}},async dispose(){}}}function hP8($={}){return{createHooksRuntime(Z){return Ys6(Z.workspaceState,$)}}}function mP8(){return{wrapResources($){let Z=$.workspaceServices.hooksRuntime;if($.options.excludeHooks===!0||!Xs6(Z)||!Js6($.resources))return $.resources;let J=Z.createSessionRuntime({sessionState:$.sessionState,metadata:$.metadata});return new fP8(new V71($.resources,J.hookExecutor,()=>Zs6($.sessionState,$.metadata),$.workspaceServices.mcpLease,void 0,void 0,Z.hooksConfigLease),J)}}}var ar6;var gP8=P(()=>{q9();yP8();K7();ar6={cursor_version:process.env.AGENT_CLI_STATIC_VERSION??"1.0.0",user_email:null}});function Qs6($){return typeof $==="object"&&$!==null&&"dispose"in $&&typeof $.dispose==="function"}async function GW($){if(Qs6($))await $.dispose()}import{realpath as pP8}from"fs/promises";import{homedir as Ws6}from"os";import{createClient as Ks6}from"@connectrpc/connect";function zs6($){if($.workspaceRoots.length>0)return[...$.workspaceRoots];let Z=$.projectRoot??$.workingDirectory;return Z!==void 0?[Z]:[]}function lP8($={}){let Z=$.getThirdPartyExtensibilityEnabled??(()=>!0),J=$.importThirdPartyPlugins??!1,X=$.includeProjectExtensibility??!0,Y=$.includeUserExtensibility??!0,Q=$.includeManagedSkills??!0,W=$.includePluginExtensibility??!0,K=new _K,H=Ws6(),G=AK(H).dirPath,q,V=!0;return{async prepareLocalExtensibility(){V=Q&&await Bs6($.dashboardTransport)},async loadLocalExtensibility(O){let F=O.workspaceState,N=zs6(F);if(N.length===0)return q=void 0,{cursorRulesService:dP8(),getAgentSkills:async(l)=>[]};let L=k1(),U=$.loadNestedRules??!0,D=X?N.map((y)=>new zU(L,K,y,U,Z,void 0)):[],j=D.length===0?dP8():D.length===1?D[0]:new Gx0(D,()=>Kx0),w=Hs6(j,{allowedRoots:X?N:[],excludedRoots:[]}),k=new E11(L,X?N:[],H,K,U,void 0,Z,Promise.resolve(),"sdk"),T=Gs6(k,{allowedRoots:[...X?N:[],...Y?[H]:[],...V?[G]:[]],excludedRoots:V?[]:[G]}),I=X?N.map((y)=>new R11(y,Z)):[],M=I.length===0?new HU:I.length===1?I[0]:new kW0(I),C=a51(O.services.pluginBootstrapOutputs),v=C&&W?new k11(L,()=>({importThirdPartyPlugins:J}),void 0,C.pluginsService):void 0,R=C&&W?new C11(()=>({importThirdPartyPlugins:J}),C.pluginsService):void 0,S=new Gx0([w,T,...v?[v]:[]],()=>Kx0),h=new op0([T,...v?[v]:[]],()=>[],()=>({workspacePaths:X?N:[],userHomeDirectory:H,agentStoreSkillsDirs:[]})),b=new kW0([M,...R?[R]:[]]);return q={localRulesService:w,localSkillsService:T,localSubagentsService:M,pluginSkillsService:v,pluginSubagentsService:R,mergedCursorRulesService:S,mergedAgentSkillsService:h,mergedSubagentsService:b},{cursorRulesService:S,getAgentSkills:(y)=>h.getAllAgentSkills(y),subagentsService:b}},async disposeLocalExtensibility(){if(!q)return;let O=q;q=void 0,await Vs6(O)}}}function Hs6($,Z){let J=iP8(Z);return{async getAllCursorRules(X){return VI1(await $.getAllCursorRules(X),J)},reload(X){$.reload(X)},onDidChangeRules(X){return $.onDidChangeRules(X)},dispose(){$.dispose()}}}function Gs6($,Z){let J=iP8(Z);return{async getAllCursorRules(X){return VI1(await $.getAllCursorRules(X),J)},async getAllAgentSkills(X){return VI1(await $.getAllAgentSkills(X),J)},reload(X){$.reload(X)},onDidChangeRules(X){return $.onDidChangeRules(X)},onDidChangeSkills(X){return $.onDidChangeSkills(X)},dispose(){$.dispose()}}}function iP8($){let Z=Promise.all($.allowedRoots.map(cP8)),J=Promise.all($.excludedRoots.map(cP8));return async(Y)=>{let[Q,W,K]=await Promise.all([qs6(Y.fullPath),Z,J]);if(Q===void 0)return!1;if(K.some((H)=>uP8(Q,H)))return!1;return W.some((H)=>uP8(Q,H))}}async function VI1($,Z){let J=await Promise.all($.map(Z));return $.filter((X,Y)=>J[Y])}function uP8($,Z){if($===Z)return!0;let J=`${Z}/`;return $.startsWith(J)}function BI1($){return $.replace(/\\/g,"/").replace(/\/+$/,"")}async function cP8($){try{return BI1(await pP8($))}catch{return BI1($)}}async function qs6($){try{return BI1(await pP8($))}catch{return}}function dP8(){return{async getAllCursorRules(){return[]},reload(){},onDidChangeRules(){return()=>{}},dispose(){}}}async function Vs6($){let Z,J=[$.mergedSubagentsService,$.mergedAgentSkillsService,$.mergedCursorRulesService,$.pluginSubagentsService,$.pluginSkillsService,$.localSubagentsService,$.localSkillsService,$.localRulesService];for(let X of J)try{await GW(X)}catch(Y){Z??=Y}if(Z!==void 0)throw Z}async function Bs6($){if(!$)return!1;let Z=Ks6(P3,$);return(await IM1(k1(),{getManagedSkills:async()=>{return(await Z.getManagedSkills(new TH({}))).skills??[]}})).status==="synced"}var nP8=P(()=>{F1();nq();VC0();X2()});import{homedir as Os6}from"os";import{join as Fs6}from"path";import{createClient as Ns6}from"@connectrpc/connect";function Ls6(){return{log($,Z,J){switch($){case"warn":Z6.warn("[local-plugins-bootstrap]",Z,J??{});break;case"error":Z6.error("[local-plugins-bootstrap]",Z,J??{});break;default:break}},increment(){},distribution(){},captureException($,Z){Z6.error("[local-plugins-bootstrap] Unexpected plugin exception:",$,Z??{})}}}function sP8($={}){let Z=$.userHomeDirectory??Os6(),J=$.importThirdPartyPlugins??!1,X=$.pluginLogger??Ls6(),Y=rP8($.marketplaceOptions),Q=$.dashboardTransport!==void 0,W=$.loadCursorFirstParty??(Y||Q);return{async loadPluginBootstrapOutputs(K){let H=Us6(K.workspaceState),{discoveredEntries:G,failures:q}=await As6(H),V=$.marketplaceOptions??($.dashboardTransport?Ds6({dashboardTransport:$.dashboardTransport,workspacePath:H,userHomeDirectory:Z}):void 0),O=rP8(V),F=new h51(H!==void 0?[H]:[],Z,()=>({importThirdPartyPlugins:J,loadCursorFirstParty:W}),V,X),N=[],L=[...q];try{N=await F.getAllEnabledPlugins()}catch(D){L.push({stage:"resolution",source:"plugin-loader",message:D instanceof Error?`Failed to load plugins: ${D.message}`:`Failed to load plugins: ${String(D)}`,detail:D})}if(G.length>0&&!O)L.push({stage:"resolution",source:"plugin-loader",message:"Project plugin entries were discovered, but no marketplace-backed project plugin source was configured. Those entries remain available through discoveredEntries only.",detail:{workspacePath:H,discoveredEntryCount:G.length}});let U={kind:gI8,discoveredEntries:G,loadedPlugins:N,loadFailures:F.getLoadFailures(),bootstrapFailures:L,pluginsService:F,async dispose(){}};for(let D of L)Z6.warn("[local-plugins-bootstrap] Plugin bootstrap failure:",{workspacePath:H,stage:D.stage,source:D.source,message:D.message,detail:D.detail});for(let D of U.loadFailures)Z6.warn("[local-plugins-bootstrap] Plugin load failure:",{workspacePath:H,pluginName:D.pluginName,pluginId:D.pluginId,marketplaceName:D.marketplaceName,errorType:D.errorType,errorMessage:D.errorMessage});return[U]}}}function Us6($){return $.projectRoot??$.workspaceRoots[0]??$.workingDirectory}function rP8($){if($===void 0)return!1;return Array.isArray($)?$.length>0:!0}function Ds6($){let Z=Fs6($.userHomeDirectory,".cursor","plugins","marketplaces"),J=Ns6(P3,$.dashboardTransport),X=(H,{signal:G})=>J.downloadPluginContent(H,{signal:G}),Y=new oy0,Q=$11(async()=>{try{return await J.getEffectiveUserPlugins(new jH(aP8))}catch{return{plugins:[]}}},{marketplaceCacheRoot:Z,listOptions:{allowedMarketplaceNames:["cursor-public"]},downloadPluginContent:X,contentRetries:Y.forListing("account")}),W=$.workspacePath,K=$11(async()=>{if(W===void 0)return{plugins:[]};try{let H=await O11(W);if(H.length===0)return{plugins:[]};let G=H.filter((N)=>N.entry.gitUrl),q=H.filter((N)=>!N.entry.gitUrl),O=G.filter(({entry:N})=>{let L=N.gitUrl;return!L||B11(L)}).map(({key:N,entry:L})=>{let U=F11(N),D=L.gitUrl;return{plugin:{name:U.name,gitUrl:D,gitRef:L.gitRef,gitPath:L.gitPath,marketplace:{name:U.marketplaceName,gitUrl:D,gitRef:L.gitRef}},isEnabled:!0}}),F=[];if(q.length>0)try{let N=q.map((U)=>{let D=F11(U.key);return new hF({name:D.name,marketplaceName:D.marketplaceName})});F=(await J.resolvePluginsByRef(new MH({refs:N,...aP8}))).plugins?.map((U)=>({plugin:U,isEnabled:!0}))??[]}catch{}return{plugins:[...O,...F]}}catch{return{plugins:[]}}},{marketplaceCacheRoot:Z,listOptions:{allowedMarketplaceNames:["cursor-public"]},downloadPluginContent:X,contentRetries:Y.forListing("project")});return[{client:Q,userId:"",cacheManager:new wW0($.userHomeDirectory),pruneOldVersions:!0},{client:K,userId:"",cacheManager:new wW0($.userHomeDirectory),pruneOldVersions:!0}]}async function As6($){if($===void 0)return{discoveredEntries:[],failures:[]};try{return{discoveredEntries:(await O11($)).map(({key:J,entry:X})=>({source:"project-settings",workspacePath:$,key:J,entry:X})),failures:[]}}catch(Z){return{discoveredEntries:[],failures:[{stage:"discovery",source:"project-settings",message:Z instanceof Error?`Failed to read project plugin settings: ${Z.message}`:`Failed to read project plugin settings: ${String(Z)}`,detail:Z}]}}}var aP8;var oP8=P(()=>{TW0();nq();VC0();X2();l3();aP8={supportsBackendContent:!0}});class ZE8{async getAllCursorRules($){return[]}reload($){}dispose(){}onDidChangeRules($){return()=>{}}}function js6($){return $==="/"||$==="\\"}function OI1($){if($.length<=1)return $;let Z=$.length;while(Z>1&&js6($[Z-1])){if(Z===3&&$[1]===":")break;Z-=1}return $.slice(0,Z)}function O71($){let Z=OI1($).replaceAll("\\","/");if(/^[A-Za-z]:\/$/.test(Z))return Z.slice(0,-1);return Z}function tP8($){let Z=OI1($.reportedWorkspacePath);if($.suffix==="")return Z;let J=Z.replaceAll("\\","/"),X=J==="/"?$.suffix:`${J}${$.suffix}`;return Z.includes("\\")?X.replaceAll("/","\\"):X}function eP8($){let Z=O71($.value),J=$.roots.filter((X)=>X.host.length>0).sort((X,Y)=>O71(Y.host).length-O71(X.host).length);for(let X of J){let Y=O71(X.host);if(Z===Y)return tP8({reportedWorkspacePath:X.reported,suffix:""});let Q=Y==="/"?"/":`${Y}/`;if(Z.startsWith(Q)){let W=Y==="/"?Z:Z.slice(Y.length);return tP8({reportedWorkspacePath:X.reported,suffix:W})}}return}function Ms6($,Z){if($.result.case!=="success"||$.result.value.requestContext?.env===void 0)return $;let J=$.clone();if(J.result.case!=="success")return $;let X=J.result.value.requestContext?.env;if(X===void 0)return J;let{roots:Y,reportedWorkspacePath:Q}=Z;X.workspacePaths=X.workspacePaths.map((W)=>eP8({value:W,roots:Y})??W);for(let W of ws6){let K=X[W];if(K===void 0||K==="")continue;let H=eP8({value:K,roots:Y});X[W]=W==="processWorkingDirectory"&&Q!==void 0?H??OI1(Q):H??K}return J}function Is6($,Z){let J=$.get(r9);if(J===void 0)return;let{reportedWorkspacePath:X,reportedProjectFolder:Y}=Z,Q=X===void 0?[]:Z.workspacePaths.map((K)=>({host:K,reported:X})),W=Y??X;if(W!==void 0)Q.push({host:Z.projectDir,reported:W});$.register(r9,{execute:async(K,H,G)=>{let q=await J.execute(K,H,G);return Ms6(q,{roots:Q,reportedWorkspacePath:X})}})}async function Ts6($){if($===void 0)return $E8;try{let Z=await $();return{powershellUtf8Console:Z.powershellUtf8Console,powershellUtf8ChildEnv:Z.powershellUtf8ChildEnv}}catch{return $E8}}async function Ps6($,Z){if($===void 0)return{};if(typeof $==="function")return await $({sessionId:Z.sessionState.sessionId,metadata:Z.metadata});return $}function XE8($){let Z=new _K;return{async createResources(J){let X=$.createSessionDependencies?.(J)??{pendingDecisionStore:$.pendingDecisionStore,fileChangeTracker:$.fileChangeTracker,permissionsService:$.permissionsService};if(!X.pendingDecisionStore||!X.fileChangeTracker||!X.permissionsService)throw Error("Local resource provider factory requires either shared dependencies or a per-session dependency factory.");let Y=J.workspaceServices.cursorRulesService??new ZE8,Q=J.workspaceServices.subagentsService??new HU,W=J.workspaceServices.mcpLease??new uU,K=J.options.excludeProjectMcp===!0,H=J.options.mcpServersOverride===void 0&&!K?void 0:$.createSessionMcpLease!==void 0?await $.createSessionMcpLease(J,J.options.mcpServersOverride):K?new uU:void 0,q=DL1(H??W,J.options.extraMcpTools??[]);try{let V=await Ps6(J.options.localResourceProviderOptions,J),O=await Ts6($.getPowershellUtf8Options),F={pendingDecisionStore:X.pendingDecisionStore,fileChangeTracker:X.fileChangeTracker,gitExecutor:Z,ignoreService:$.ignoreService,grepProvider:$.grepProvider,permissionsService:X.permissionsService,workspacePaths:$.workspacePaths,diagnosticsProvider:$.diagnosticsProvider,mcpLease:q,mcpStateAccessor:$.createMcpStateAccessor?.(q,J.options),cursorRulesService:Y,subagentsService:Q,repositoryProvider:$.repositoryProvider,projectDir:$.projectDir,shellManager:$.shellManager,_defaultSandboxPolicy:$.defaultSandboxPolicy??{type:"insecure_none"},_defaultSandboxPolicySources:$.defaultSandboxPolicySources,getSandboxEnabled:$.getSandboxEnabled,getSandboxSupported:$.getSandboxSupported,getNetworkAllowlistInfo:$.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:$.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:$.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:$.getMockPromptTime,mcpFileOutputThresholdBytes:$.mcpFileOutputThresholdBytes,mcpMetaToolEnabled:$.mcpMetaToolEnabled,attributionConfigProvider:$.attributionConfigProvider,getAgentSkills:J.workspaceServices.getAgentSkills,powershellUtf8Console:O.powershellUtf8Console,powershellUtf8ChildEnv:O.powershellUtf8ChildEnv,...V},N=H===void 0?new j30(F):new JE8(F,H);if(J.options.reportedWorkspacePath!==void 0||J.options.reportedProjectFolder!==void 0)Is6(N,{reportedWorkspacePath:J.options.reportedWorkspacePath,reportedProjectFolder:J.options.reportedProjectFolder,workspacePaths:F.workspacePaths,projectDir:F.projectDir});return N}catch(V){throw await GW(H),V}}}}var ws6,$E8,JE8;var YE8=P(()=>{J6();nq();pU();ws6=["projectFolder","terminalsFolder","agentSharedNotesFolder","agentConversationNotesFolder","agentTranscriptsFolder","processWorkingDirectory","artifactsFolder"];$E8={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1};JE8=class JE8 extends j30{sessionMcpLease;constructor($,Z){super($);this.sessionMcpLease=Z}async dispose(){try{await super.dispose()}finally{await GW(this.sessionMcpLease)}}}});function QE8($){if(typeof $==="object"&&$!==null||typeof $==="function")KE8.add($)}function WE8($){return(typeof $==="object"&&$!==null||typeof $==="function")&&KE8.has($)}function Es6($,Z){return AggregateError([Z],"Workspace service loading failed and resource cleanup also failed.",{cause:$})}function ks6($,Z){let J=Object.keys(Z).filter((X)=>!FI1.includes(X));if(J.length>0)throw Error(`Workspace service contributors may only provide ${FI1.join(", ")}. Received unsupported service keys: ${J.join(", ")}.`);for(let X of FI1)if(Object.hasOwn(Z,X))$[X]=Z[X]}async function Rs6($){let Z;for(let J=$.length-1;J>=0;J-=1)try{await GW($[J])}catch(X){Z??=X}if(Z!==void 0)throw Z}async function NI1($,Z,J){const __p=e=>{try{globalThis[Symbol.for("@cursor/sdk.startupPhase")]?.(e)}catch{}};let X={config:void 0,plugins:[],pluginBootstrapOutputs:[],cursorRulesService:void 0,getAgentSkills:void 0,subagentsService:void 0,mcpLease:void 0,hooksRuntime:void 0};try{X.config=$.config?await $.config.loadConfig(Z):void 0,($.plugins||$.pluginBootstrap)&&__p("plugins"),X.plugins=$.plugins?await $.plugins.loadPlugins(Z):[];let Y=()=>({workspaceState:Z,policy:J,services:X});if(X.pluginBootstrapOutputs=$.pluginBootstrap?await $.pluginBootstrap.loadPluginBootstrapOutputs(Y()):X.pluginBootstrapOutputs,$.mcp&&__p("mcp"),X.mcpLease=$.mcp?await $.mcp.createLease(Y()):void 0,$.hooks&&__p("hooks"),X.hooksRuntime=$.hooks?await $.hooks.createHooksRuntime(Y()):void 0,$.localExtensibility&&__p("skills"),$.localExtensibility?.prepareLocalExtensibility)await $.localExtensibility.prepareLocalExtensibility(Y());let Q=$.localExtensibility?await $.localExtensibility.loadLocalExtensibility(Y()):void 0;if(Q!==void 0)QE8(Q.cursorRulesService),QE8(Q.subagentsService),Object.assign(X,Q);for(let W of $.workspaceServicesContributors??[]){let K=await W.contributeServices(Y());if(K!==void 0)ks6(X,K)}return __p("connecting"),X}catch(Y){try{await Rl0(X,{disposeLocalExtensibility:$.localExtensibility===void 0?void 0:()=>$.localExtensibility?.disposeLocalExtensibility?.()})}catch(Q){throw Es6(Y,Q)}throw Y}}async function Rl0($,Z){let J=Z?.preserveSharedContributorsFrom,X,Y=async(Q)=>{try{await GW(Q)}catch(W){X??=W}};if($.subagentsService!==J?.subagentsService&&!WE8($.subagentsService))await Y($.subagentsService);if($.cursorRulesService!==J?.cursorRulesService&&!WE8($.cursorRulesService))await Y($.cursorRulesService);if(Z?.disposeLocalExtensibility)try{await Z.disposeLocalExtensibility()}catch(Q){X??=Q}await Y($.hooksRuntime),await Y($.mcpLease);try{await Rs6($.pluginBootstrapOutputs)}catch(Q){X??=Q}if(X!==void 0)throw X}var FI1,KE8;var LI1=P(()=>{FI1=["cursorRulesService","getAgentSkills","subagentsService"],KE8=new WeakSet});function Cs6($,Z){return AggregateError([Z],"Session creation failed and resource cleanup also failed.",{cause:$})}async function zE8($){let Z=new Set,J;for(let X=$.length-1;X>=0;X-=1){let Y=$[X];if(Z.has(Y))continue;Z.add(Y);try{await GW(Y)}catch(Q){J??=Q}}if(J!==void 0)throw J}async function HE8($){let Z={sessionId:$.options?.sessionId??L6(),createdAt:new Date},J=Object.freeze({...$.options?.metadata??{}}),X={options:$.options??{},workspaceState:$.workspaceState,workspaceServices:$.workspaceServices,policy:$.policy,sessionState:Z,metadata:J,getAgentSkills:$.workspaceServices.getAgentSkills},Y=void 0,Q=void 0,W=[];try{Y=$.adapters.resourceFactory?await $.adapters.resourceFactory.createResources(X):void 0,Q=Y,W.push(Y);for(let G of $.adapters.resourceWrappers??[])Q=await G.wrapResources({...X,baseResources:Y,resources:Q}),W.push(Q);await $.adapters.lifecycle?.onSessionCreated?.(Z)}catch(G){try{await zE8(W)}catch(q){throw Cs6(G,q)}throw G}let K={base:Y,wrapped:Q},H=!1;return{state:Z,resources:K,metadata:J,workspaceServices:$.workspaceServices,policy:$.policy,async dispose(){if(H)return;H=!0;try{await zE8(W)}finally{await $.adapters.lifecycle?.onSessionDisposed?.(Z)}}}}var UI1=P(()=>{B1()});function F71($){if($===void 0||$.length===0)return DI1([]);for(let J of $)if(!_s6.has(J))throw Error(`Unsupported setting source "${J}"`);if($.includes("all")){if($.length>1)throw Error('settingSources cannot mix "all" with individual setting sources');return{...DI1(GE8),all:!0}}let Z=$.filter((J)=>J!=="all");return DI1(Z)}function N7($,Z){return $[Z]}function DI1($){let Z=new Set($);return{project:Z.has("project"),user:Z.has("user"),team:Z.has("team"),mdm:Z.has("mdm"),plugins:Z.has("plugins"),all:!1}}var GE8,_s6;var qE8=P(()=>{GE8=["project","user","team","mdm","plugins"],_s6=new Set([...GE8,"all"])});function BE8($={}){let Z=Object.freeze({...VE8.metadata,...$.metadata}),J={...VE8,...$,metadata:Z};return{name:"permissive-sdk-local",resolvePolicy(){return J}}}async function OE8($,Z){return $.resolvePolicy(Z)}var Ss6,VE8;var FE8=P(()=>{Ss6=Object.freeze({}),VE8=Object.freeze({allowMcpServers:!0,allowPlugins:!0,allowBackgroundSessions:!0,requireMcpApproval:!1,maxParallelSessions:void 0,sandboxMode:void 0,metadata:Ss6})});var AI1=P(()=>{FE8()});async function NE8($={}){let Z=RI8($.adapters),J=await Z.workspace.resolveWorkspaceState({workingDirectory:$.workingDirectory,projectRoot:$.projectRoot,projectDirectory:$.projectDirectory,workspaceRoots:$.workspaceRoots}),X=await OE8($.policyAdapter??BE8(),{workspaceState:J}),Y=await NI1(Z,J,X),Q=!1,W=Promise.resolve(),K=(q)=>{let V=W.then(q);return W=V.catch(()=>{}),V},H=Z.localExtensibility,G=H===void 0?void 0:()=>H.disposeLocalExtensibility?.();return{state:J,get services(){return Y},policy:X,async createSessionRuntime(q={}){if(Q)throw Error("Cannot create a session runtime after the workspace runtime has been disposed.");return HE8({options:q,workspaceState:J,workspaceServices:Y,policy:X,adapters:Z})},async reload(){if(Q)return;await K(async()=>{if(Q)return;let q=Y,V=await NI1(Z,J,X);if(Q){await Rl0(V,{disposeLocalExtensibility:G});return}Y=V,await Rl0(q,{preserveSharedContributorsFrom:V,disposeLocalExtensibility:G}),await Z.lifecycle?.onWorkspaceReload?.(J)})},async dispose(){if(Q)return;Q=!0,await K(async()=>{try{await Rl0(Y,{disposeLocalExtensibility:G})}finally{await Z.lifecycle?.dispose()}})}}}var wI1=P(()=>{yM1();AI1();LI1();UI1()});var jI1=P(()=>{iI8();gP8();nP8();oP8();YE8();LI1();UI1();qE8();wI1()});import{resolve as vs6}from"path";class LE8{async requestApproval($){return{approved:!0}}}class UE8{approvalMode;userConfiguredPolicy;teamSettingsService;respectAdminControls;constructor($,Z,J,X){this.approvalMode=$;this.userConfiguredPolicy=Z;this.teamSettingsService=J;this.respectAdminControls=X}async getPermissions(){let $=this.respectAdminControls&&this.userConfiguredPolicy.type!=="insecure_none"?(await this.teamSettingsService.getSandboxingControls()).sandboxingDisabled:!1;return{allow:[],deny:[],approvalMode:this.approvalMode,userConfiguredPolicy:$?{type:"insecure_none"}:this.userConfiguredPolicy}}async updatePermissions(){}}class DE8{async open($,Z){}async getDiagnostics($,Z){return[]}}class AE8{async getCodebaseReference($,Z){return}}class wE8{inner;allowlistReports;constructor($,Z){this.inner=$;this.allowlistReports=Z}async getState($){let Z=await this.inner.getState($);return await this.reportAllowlists($),{...Z,servers:Z.servers.filter((J)=>J.status!=="needsAuth")}}async reportAllowlists($){if(this.allowlistReports===void 0)return;let{mcpLease:Z,onMcpAllowlistInUse:J,onMcpServerBlockedByAllowlist:X}=this.allowlistReports,Y;try{Y=await Z.getClients($)}catch(Q){Z6.warn("[sdk-mcp-state] Could not read the MCP allowlist in use:",Q);return}for(let[Q,W]of Object.entries(Y))try{if(J!==void 0){let K=await W.getAllowlistInUse?.();if(K!==void 0)J({serverName:Q,allowlist:K})}if(X!==void 0){let K=await W.getAllowlistRefusal?.();if(K!==void 0)X({serverName:Q,refusal:K})}}catch(K){Z6.warn("[sdk-mcp-state] Could not read the MCP allowlist in use:",K)}}}class N71{subagents;constructor($){this.subagents=$.map((Z)=>new NX({fullPath:`sdk-inline://${Z.name}`,name:Z.name,description:Z.description,tools:[],model:Z.model,prompt:Z.prompt,permissionMode:W4.DEFAULT,isBackground:!1,source:"sdk"}))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents}}function ys6($,Z){let J=[],X=new Set;for(let Y of[$,...Z??[]]){let Q=vs6(Y);if(X.has(Q))continue;X.add(Q),J.push(Y)}return J}async function jE8($){let{workingDirectory:Z,projectDir:J}=$,X=ys6(Z,$.dirs),Y=X.length>1?X:void 0,Q=F71($.settingSources),W=$.teamSettingsService??Zl0(),K=$.defaultSandboxPolicy??{type:"insecure_none"},H=$.getSandboxSupported??(()=>S20(K,{ctx:$.initializationCtx})),G=$.getSandboxEnabled??(()=>K.type!=="insecure_none"&&H()),q=new _K,V=new Xy0(q,W,X),O=new DE8,F=new AE8,N=$.getSmartModeClassifierAutoModeEnabled?.(),L=new UE8(N?"allowlist":$.approvalMode??"unrestricted",K,W,$.respectAdminControls??!1),U=$.pendingDecisionProvider,D={executeIndexedGrep:void 0},j=()=>!0,w=N7(Q,"plugins"),k=$.importThirdPartyPlugins??!1,T=$.mcpMetaToolEnabled??!0,I=$.mcpServers!==void 0&&Object.keys($.mcpServers).length>0,M=$.customSubagents!==void 0&&$.customSubagents.length>0,C=I||N7(Q,"project")||N7(Q,"user")||w,v=N7(Q,"project")||N7(Q,"user")||N7(Q,"mdm"),R=N7(Q,"team"),S=R&&$.dashboardTransport!==void 0,h=N7(Q,"project")||N7(Q,"user")||R||S||w,b={teamSettingsService:W,initializationCtx:$.initializationCtx,importThirdPartyPlugins:k,ignoreApprovals:!0,includeProjectMcp:N7(Q,"project"),includeUserMcp:N7(Q,"user"),includePluginMcp:w,isLinkSharedPaymentTokenLogRedactionEnabled:$.isLinkSharedPaymentTokenLogRedactionEnabled,restMcpCursorAuthTokenSupplier:$.restMcpCursorAuthTokenSupplier},_=(y)=>NE8({workingDirectory:Z,...Y!==void 0?{workspaceRoots:Y}:{},adapters:{...y.includeMcp?{mcp:bM1({...b,inlineMcpServers:$.mcpServers})}:{},...w?{pluginBootstrap:sP8({importThirdPartyPlugins:k,dashboardTransport:$.dashboardTransport})}:{},...v?{hooks:hP8({includeProjectHooks:N7(Q,"project"),includeUserHooks:N7(Q,"user"),includeEnterpriseHooks:N7(Q,"mdm"),useCommandHookStdinTransport:$.useCommandHookStdinTransport})}:{},...h?{localExtensibility:lP8({includeProjectExtensibility:N7(Q,"project"),includeUserExtensibility:N7(Q,"user"),includeManagedSkills:S,includeTeamExtensibility:R,includePluginExtensibility:w,teamSettingsService:W,getThirdPartyExtensibilityEnabled:j,dashboardTransport:$.dashboardTransport,importThirdPartyPlugins:k})}:{},resourceFactory:XE8({attributionConfigProvider:N7(Q,"user")?{get(){try{const{readFileSync:r}=process.getBuiltinModule("node:fs"),{join:j}=process.getBuiltinModule("node:path"),{homedir:h}=process.getBuiltinModule("node:os"),x=process.env.XDG_CONFIG_HOME,d=process.env.CURSOR_CONFIG_DIR||(x&&process.platform!=="darwin"&&process.platform!=="win32"?j(x,"cursor"):j(h(),".cursor"));return JSON.parse(r(j(d,"cli-config.json"),"utf8"))}catch{return}}}:void 0,ignoreService:V,grepProvider:D,workspacePaths:X,diagnosticsProvider:O,repositoryProvider:F,projectDir:J??Z,shellManager:void 0,defaultSandboxPolicy:K,defaultSandboxPolicySources:$.defaultSandboxPolicySources,getSandboxEnabled:G,getSandboxSupported:H,getNetworkAllowlistInfo:$.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:$.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:$.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:$.getMockPromptTime,getPowershellUtf8Options:$.getPowershellUtf8Options,mcpFileOutputThresholdBytes:void 0,mcpMetaToolEnabled:T,createMcpStateAccessor:(m,l)=>new wE8(new _b0(m),l?.onMcpAllowlistInUse===void 0&&l?.onMcpServerBlockedByAllowlist===void 0?void 0:{mcpLease:m,onMcpAllowlistInUse:l.onMcpAllowlistInUse,onMcpServerBlockedByAllowlist:l.onMcpServerBlockedByAllowlist}),createSessionMcpLease:(m,l)=>bM1({...b,includeProjectMcp:b.includeProjectMcp&&m.options.excludeProjectMcp!==!0,inlineMcpServers:l??$.mcpServers}).createLease({workspaceState:m.workspaceState,services:m.workspaceServices,policy:m.policy}),createSessionDependencies:(m)=>{let l=U??new LE8,i=new R81(Z),e=new D61(V,l,L,W,Z,$.respectAdminControls??!1,{enforceMcpAdminToolLimits:$.isMcpAdminToolLimitEnforced,onMcpAdminToolLimitCheck:m.options.onMcpAdminToolLimitCheck});return{pendingDecisionStore:l,fileChangeTracker:i,permissionsService:e}}}),resourceWrappers:v?[mP8()]:[],...M?{workspaceServicesContributors:[{contributeServices:(m)=>{let l=new N71($.customSubagents??[]),i=m.services.subagentsService;return{subagentsService:i===void 0?l:new kW0([l,i])}}}]}:{}}});if(!C)return _({includeMcp:!1});try{return await _({includeMcp:!0})}catch(y){return Z6.warn("[default-local-workspace-runtime] Failed to initialize MCP-enabled runtime, retrying without MCP:",{error:y,workingDirectory:Z,projectDir:J,enablePlugins:w,importThirdPartyPlugins:k}),_({includeMcp:!1})}}var ME8=P(()=>{nq();sK();K7();jI1();wI1();l3()});var IE8=()=>{};function TE8($){let{workspaceRuntime:Z}=$;if(!(Z.hooksConfigLease.hasHookForStep(i0.sessionStart)||Z.hooksConfigLease.hasHookForStep(i0.sessionEnd)||Z.hooksConfigLease.hasHookForStep(i0.stop)||Z.hooksConfigLease.hasHookForStep(i0.beforeSubmitPrompt)))return{};let X=Z.createSessionRuntime({sessionState:$.sessionState,metadata:$.metadata}),{hookExecutor:Y}=X,Q;return{async onSessionStart(W){if(Q=W,!Y.hasHooksForStep(i0.sessionStart))return;try{let K={conversation_id:W.conversationId,generation_id:W.generationId,model:W.model,...g5(W),is_background_agent:!1},H=await Y.executeHookForStep(i0.sessionStart,K);if(H){if(H.env)Y.setSessionEnvironment(H.env);return{env:H.env,additionalContext:H.additional_context,blocked:H.continue===!1,blockedReason:H.user_message}}}catch(K){Z6.warn("[hooks-adapter] sessionStart hook failed:",K)}return},async onSessionEnd(W,K){if(!Y.hasHooksForStep(i0.sessionEnd)){Y.clearSessionEnvironment();return}try{let H={conversation_id:Q?.conversationId??"",generation_id:Q?.generationId??"",model:Q?.model??"unknown",...Q?g5(Q):{},reason:W,duration_ms:K,is_background_agent:!1,final_status:W};await Y.executeHookForStep(i0.sessionEnd,H)}catch(H){Z6.warn("[hooks-adapter] sessionEnd hook failed:",H)}finally{Y.clearSessionEnvironment()}},async onBeforeSubmitPrompt(W){if(!Y.hasHooksForStep(i0.beforeSubmitPrompt))return;try{let K={conversation_id:W.conversationId,generation_id:W.generationId,model:W.model,...g5(W),prompt:W.promptText??"",attachments:[]};await Y.executeHookForStep(i0.beforeSubmitPrompt,K)}catch(K){Z6.warn("[hooks-adapter] beforeSubmitPrompt hook failed:",K)}},async onTurnCompleted(W){if(!Y.hasHooksForStep(i0.stop))return;let K={conversation_id:W.conversationId,generation_id:W.generationId,model:W.model,...g5(W),status:"completed",loop_count:W.loopCount},H=await Y.executeHookForStep(i0.stop,K),G=typeof H?.followup_message==="string"?H.followup_message.trim():"";return G.length>0?G:void 0},async onTurnError(W){if(!Y.hasHooksForStep(i0.stop))return;try{let K={conversation_id:W.conversationId,generation_id:W.generationId,model:W.model,...g5(W),status:"error",loop_count:W.loopCount};await Y.executeHookForStep(i0.stop,K)}catch(K){Z6.warn("[hooks-adapter] onTurnError stop hook failed:",K)}},async onTurnAborted(W){if(!Y.hasHooksForStep(i0.stop))return;try{let K={conversation_id:W.conversationId,generation_id:W.generationId,model:W.model,...g5(W),status:"aborted",loop_count:W.loopCount};await Y.executeHookForStep(i0.stop,K)}catch(K){Z6.warn("[hooks-adapter] onTurnAborted stop hook failed:",K)}},async dispose(){await X.dispose()}}}var PE8=P(()=>{q9();l3()});import{accessSync as xs6,constants as bs6,mkdtempSync as fs6,statSync as hs6}from"fs";import{homedir as ms6,tmpdir as gs6}from"os";import{join as L71}from"path";function us6($){if($.trim()==="")return!1;try{if(!hs6($).isDirectory())return!1;return xs6($,bs6.W_OK),!0}catch{return!1}}function cs6($){return fs6(L71($,"cursor-transcripts-"))}function ds6($){let Z=$.cursorDataDir?.trim();if(Z)return L71(Z,"projects",XQ($.workspacePath));if($.homeDir!==void 0&&us6($.homeDir))return L71($.homeDir,".cursor","projects",XQ($.workspacePath));return L71($.ensureFallbackRoot($.tempDir),XQ($.workspacePath))}function II1($){if(process.env.CURSOR_DATA_DIR?.trim())return tp0($);let J;try{J=ms6()}catch{J=void 0}return ds6({workspacePath:$,homeDir:J,tempDir:gs6(),ensureFallbackRoot:(X)=>{if(MI1===void 0)MI1=cs6(X);return MI1}})}var MI1;var EE8=P(()=>{l51();B1()});import{mkdir as ps6,writeFile as ls6}from"fs/promises";import{dirname as is6,join as U71}from"path";function ns6($,Z){let J=hK({conversationId:Z,ext:"jsonl",kind:"primary"});return U71(II1($),J)}async function kE8($,Z){let J=is6($);await ps6(J,{recursive:!0}),await ls6($,Z,"utf-8")}class Cl0{transcriptStore;nestedSubagentTranscriptStore;projectDir;conversationId;workspacePath;parentConversationId;blobStore;writeChain=Promise.resolve();constructor($){this.workspacePath=$.workspacePath,this.conversationId=$.conversationId,this.parentConversationId=$.parentConversationId,this.blobStore=$.blobStore,this.projectDir=II1(this.workspacePath);let Z=this.parentConversationId?(X,Y)=>{let Q=hK({conversationId:X,ext:Y,kind:"subagent",parentConversationId:this.parentConversationId});return U71(this.projectDir,Q)}:void 0;this.transcriptStore=new e51(this.projectDir,$.blobStore,kE8,{writeText:!1,writeJsonl:!0,...Z?{pathResolver:Z}:{}});let J=(X,Y)=>{let Q=hK({conversationId:X,ext:Y,kind:"subagent",parentConversationId:this.conversationId});return U71(this.projectDir,Q)};this.nestedSubagentTranscriptStore=new e51(this.projectDir,$.blobStore,kE8,{writeText:!1,writeJsonl:!0,pathResolver:J})}enqueueWrite($,Z){let J=this.writeChain;return this.writeChain=J.then(async()=>{try{await $()}catch(X){Z6.warn(`${Z} ${X instanceof Error?X.message:String(X)}`)}}),this.writeChain}async writeFromState($,Z){return this.enqueueWrite(async()=>{await this.transcriptStore.writeFromStateFull($,Z,this.conversationId);let J=await ch0($,Z,this.blobStore);for(let[X,Y]of Object.entries(J)){if(!Y?.conversationState)continue;await this.nestedSubagentTranscriptStore.writeFromStateFull($,Y.conversationState,X)}},"[LocalTranscriptWriter] Failed to write transcript:")}async writeTurnEndedFromState($,Z,J){return this.enqueueWrite(async()=>{await this.transcriptStore.writeFromStateFull($,Z,this.conversationId,{turnEnded:J})},"[LocalTranscriptWriter] Failed to write turn-ended transcript:")}waitForPendingWrites(){return this.writeChain}getTranscriptPath(){if(this.parentConversationId){let $=hK({conversationId:this.conversationId,ext:"jsonl",kind:"subagent",parentConversationId:this.parentConversationId});return U71(this.projectDir,$)}return ns6(this.workspacePath,this.conversationId)}getProjectDir(){return this.projectDir}}var TI1=P(()=>{hJ();o51();l3();EE8()});function rs6($){if(!as6.test($))throw Error(`Invalid resumeAgentId format: ${$}`)}function ss6($){let Z=new aC0,J=YQ($),X=new xN(new nC0,Z);return X.setMetadata("agentId",J.agentId),X.setMetadata("latestRootBlobId",J.latestRootBlobId),X.setMetadata("name",J.name),X.setMetadata("createdAt",J.createdAt),X.setMetadata("mode",J.mode),X.setMetadata("isRunEverything",J.isRunEverything),X.setMetadata("lastUsedModel",J.lastUsedModel),X.setMetadata("lastDebugServerPort",J.lastDebugServerPort),X.setMetadata("currentPlanUri",J.currentPlanUri),X.setMetadata("subagentInfo",J.subagentInfo),X.setMetadata("blobEncryptionKey",J.blobEncryptionKey),X}function os6($){let Z=$.query.case;switch(Z){case"webSearchRequestQuery":return H6.webSearchRejected($.id,"Web search is not supported in local subagent");case"webFetchRequestQuery":return H6.webFetchRejected($.id,"Web fetch is not supported in local subagent");case"switchModeRequestQuery":return H6.switchModeRejected($.id,"Subagent mode switches are not supported in local subagent");case"askQuestionInteractionQuery":{let J=new jZ({result:{case:"rejected",value:new yY({reason:"Interactive questions are not supported in local subagent mode"})}});return H6.askQuestion($.id,J)}default:throw Error(`Unhandled interaction query type in local subagent: ${String(Z)}`)}}class EI1{sessions=new Map;backgroundRuns=new Map;activeForegroundExecutions=new Map;backgroundPromises=new Set;pendingReleaseSessions=new Set;childParentIds=new Map;parentChildIds=new Map;queuedChildCompletions=new Map;childCompletionWaiters=new Map;childLineageRequestIds=new Map;untrackedParentRequestIds=new Map;rootLineageRequestId;lifecycleStore;agentClient;getResources;mcpTools;workspacePath;parentConversationId;headers;endlessRetries;onSessionCreated;onInteractionUpdate;onSessionCompleted;onSessionReleased;onSubagentTokenDelta;constructor($){this.agentClient=$.agentClient,this.getResources=$.getResources,this.mcpTools=$.mcpTools??[],this.workspacePath=$.workspacePath,this.parentConversationId=$.parentConversationId;let Z=$.rootRequestId?.trim();this.rootLineageRequestId=Z!==void 0&&Z.length>0?Z:L6(),this.headers=$.headers,this.endlessRetries=$.endlessRetries,this.onSessionCreated=$.onSessionCreated,this.onInteractionUpdate=$.onInteractionUpdate,this.onSessionCompleted=$.onSessionCompleted,this.onSessionReleased=$.onSessionReleased,this.onSubagentTokenDelta=$.onSubagentTokenDelta,this.lifecycleStore=new js0}async createOrResumeSession($,Z){if(Z.forkAgentId)throw Error("forkAgentId is not supported in local subagents.");let J=Z.resumeAgentId;if(J)rs6(J);if(J&&!Z.prompt)return J;if(J&&Ms0(Z.prompt)&&this.isBackgroundRunBusy(J))throw Error(gW1);if(J){if(this.sessions.get(J))return J}let X=J??L6(),Y=ss6(X),Q=new Cl0({workspacePath:this.workspacePath,conversationId:X,parentConversationId:this.parentConversationId,blobStore:Y.getBlobStore()});return this.sessions.set(X,{agentStore:Y,transcriptWriter:Q,toolCallId:Z.toolCallId}),this.onSessionCreated?.({agentId:X,toolCallId:Z.toolCallId,subagentType:Z.subagentType,parentAgentId:Z.parentConversationId}),X}async runSession($,Z,J,X){if(this.isAwaitBackgroundMode(J))return this.awaitBackgroundRun(J.resumeAgentId,$.signal);let Y=this.sessions.get(Z);if(!Y)return{status:"error",error:`Subagent session not found: ${Z}`};if(J.runInBackground){let[O,F]=$.withDetached().withCancel();return this.registerBackgroundRun(Z,this.executeSubagent(O,Z,J,Y),J.parentConversationId,F),{status:"background",backgroundReason:NZ.AGENT_REQUEST,toolCallCount:0}}let[Q,W]=$.withDetached().withCancel(),K=!1,H=()=>{if(!K)W()};if($.signal.addEventListener("abort",H,{once:!0}),$.signal.aborted)H();let G=()=>{},q=new Promise((O)=>{G=O}),V={requestBackground:()=>{if(K)return!0;if(Q.signal.aborted)return!1;return K=!0,$.signal.removeEventListener("abort",H),G(),!0}};this.activeForegroundExecutions.set(J.toolCallId,V),this.activeForegroundExecutions.set(Z,V);try{let O=this.executeSubagent(Q,Z,J,Y),F=await Promise.race([O.then((N)=>({handedOff:!1,outcome:N})),q.then(()=>({handedOff:!0}))]);if(F.handedOff)return this.registerBackgroundRun(Z,O,J.parentConversationId,W),{status:"background",backgroundReason:NZ.USER_REQUEST,toolCallCount:0};return this.onSessionCompleted?.(Z,F.outcome),F.outcome}finally{if(this.clearForegroundExecution(J.toolCallId,V),this.clearForegroundExecution(Z,V),!K)$.signal.removeEventListener("abort",H)}}forceBackgroundByToolCallId($){if(!this.activeForegroundExecutions.get($)?.requestBackground())return new m3({status:dh0.NOT_FOUND});return new m3({status:dh0.ACCEPTED})}clearForegroundExecution($,Z){if(this.activeForegroundExecutions.get($)===Z)this.activeForegroundExecutions.delete($)}releaseSession($){if(this.lifecycleStore.release($),this.isBackgroundRunBusy($)){this.pendingReleaseSessions.add($);return}this.cleanupSession($)}async awaitBackgroundWorkers(){while(this.backgroundPromises.size>0)await Promise.allSettled([...this.backgroundPromises])}async waitForBackgroundCompletions($,Z){return this.collectAvailableChildCompletions($,Z)}isBackgroundRunBusy($){return this.lifecycleStore.isBusy($)||this.backgroundRuns.has($)}registerBackgroundRun($,Z,J,X){this.registerParentChildLink($,J);let Y=this.lifecycleStore.startRun($,{abort:X}),Q=Z.catch((K)=>{return{status:"error",error:K instanceof Error?K.message:String(K)}}),W={runId:Y,promise:Q};this.backgroundRuns.set($,W),this.backgroundPromises.add(Q),Q.then((K)=>{if(this.lifecycleStore.finishRun($,Y),this.backgroundRuns.get($)?.runId===Y){this.backgroundRuns.delete($),this.enqueueChildCompletion($,Y,K),this.maybeCleanupReleasedSession($);try{this.onSessionCompleted?.($,K)}catch(G){Z6.error("[LocalSubagentHostAdapter] onSessionCompleted threw after background run",{agentId:$,error:G instanceof Error?G.message:String(G)})}}return K}).finally(()=>this.backgroundPromises.delete(Q))}maybeCleanupReleasedSession($){if(this.pendingReleaseSessions.has($)&&!this.isBackgroundRunBusy($))this.cleanupSession($)}cleanupSession($){this.pendingReleaseSessions.delete($);let Z=this.sessions.get($);if(!Z)return;let J=this.parentChildIds.get($);if(J)for(let X of J)this.childParentIds.delete(X);this.removeParentChildLink($),this.parentChildIds.delete($),this.queuedChildCompletions.delete($),this.childCompletionWaiters.delete($),Z.transcriptWriter.waitForPendingWrites().catch(()=>{}),this.sessions.delete($),this.onSessionReleased?.($)}async executeSubagent($,Z,J,X){if(J.continuationConfig)return this.executeSubagentWithContinuation($,Z,J,X,J.continuationConfig);return this.executeSubagentOnce($,Z,J,X)}async executeSubagentWithContinuation($,Z,J,X,Y){let Q=Y.maxLoops>0?Y.maxLoops:Number.POSITIVE_INFINITY,W=await this.runContinuationLoop($,Z,J,X,Y,Q);if(!Y.collectBackgroundChildren||W.status!=="completed")return W;let K=500;for(let H=0;H0){W=0,K=void 0;continue}W+=1,K=W>=Y.idleThreshold?`DONE_${L6().replace(/-/g,"").slice(0,8)}`:void 0}return H??{status:"error",error:"Subagent continuation exited unexpectedly"}}computeContinuationNudge($,Z,J){if(Z>=$.idleThreshold&&J!==void 0)return $.escapeMessageTemplate.replace("{idle_count}",String(Z)).replace("{escape_token}",J);return $.nudgeMessage}lineageForChildRun($){if(!this.childLineageRequestIds.has($.agentId))this.childLineageRequestIds.set($.agentId,L6());let Z=$.parentConversationId?.trim()??"",J=$.toolCallId.trim();return{parentRequestId:Z===""||Z===this.parentConversationId?this.rootLineageRequestId:this.childLineageRequestIds.get(Z)??this.untrackedParentRequestId(Z),rootParentRequestId:this.rootLineageRequestId,...J.length>0?{parentAgentToolCallId:J}:{}}}untrackedParentRequestId($){let Z=this.untrackedParentRequestIds.get($);if(Z===void 0)Z=L6(),this.untrackedParentRequestIds.set($,Z);return Z}async executeSubagentOnce($,Z,J,X){let Y=this.lineageForChildRun({agentId:Z,parentConversationId:J.parentConversationId,toolCallId:J.toolCallId}),Q,W=0,K=new N$({action:{case:"userMessageAction",value:new f9({userMessage:new v5({text:J.prompt})})}}),H=new mY({modelId:J.modelId,displayModelId:J.modelId,displayName:J.modelId});if(J.credentials.case!==void 0)H.credentials=J.credentials;let G=new um0,q={sendUpdate:async(O,F)=>{if(F.message.case==="tokenDelta")this.onSubagentTokenDelta?.(Z,F.message.value.tokens);if(F.message.case==="toolCallStarted"||F.message.case==="toolCallCompleted"||F.message.case==="partialToolCall")this.onInteractionUpdate?.(Z,F);if(F.message.case==="toolCallCompleted")W++;if(F.message.case==="textDelta")Q=(Q??"")+F.message.value.text},query:async(O,F)=>{return os6(F)}},V={handleCheckpoint:async(O,F)=>{await X.agentStore.handleCheckpoint(O,F),X.transcriptWriter.writeFromState(O,F)},getLatestCheckpoint:()=>{return X.agentStore.getLatestCheckpoint()}};try{let O=J.rootParentConversationId?.trim(),F=J.parentConversationId?.trim(),N=O!==void 0&&O!==""?O:F!==void 0&&F!==""?F:Z,L=await this.getResources({agentId:Z,parentAgentId:J.parentConversationId}),U=J.readonly?EW1(L):L;return await this.agentClient.run($,X.agentStore.getConversationStateStructure(),K,H,q,U,X.agentStore.getBlobStore(),G,V,[...this.mcpTools],{conversationGroupId:N,conversationId:Z,...X.transcriptWriter.parentConversationId?{transcriptParentConversationId:X.transcriptWriter.parentConversationId}:{},subagentTypeName:J.subagentType||void 0,...Y,headers:i51(X.agentStore.getMetadata("blobEncryptionKey"),this.headers),endlessRetries:this.endlessRetries,subagentModelOverrides:[]}),await X.transcriptWriter.writeTurnEndedFromState($,X.agentStore.getConversationStateStructure(),$.signal.aborted?{status:"aborted",error:PI1}:{status:"success"}),{status:"completed",finalMessage:Q,toolCallCount:W}}catch(O){let F=O instanceof Error?O.message:String(O);if(Z6.error("[LocalSubagentHostAdapter] Subagent session failed",{agentId:Z,error:F}),await X.transcriptWriter.writeTurnEndedFromState($,X.agentStore.getLatestCheckpoint()??X.agentStore.getConversationStateStructure(),this.getTurnEndedFromError($,F)),$.signal.aborted)return{status:"aborted",error:PI1};return{status:"error",error:F}}}getTurnEndedFromError($,Z){return $.signal.aborted?{status:"aborted",error:PI1}:{status:"error",error:Z}}isAwaitBackgroundMode($){if(!Boolean($.resumeAgentId&&!Ms0($.prompt)&&$.readonly&&$.runInBackground!==!0))return!1;if(($.parentConversationId??"").trim().length===0)throw Error(`Missing parentConversationId for subagent await/status check (subagentId: ${$.resumeAgentId})`);return!0}async awaitBackgroundRun($,Z){let J=this.backgroundRuns.get($);if(!J){if(this.isBackgroundRunBusy($))return this.awaitBusyLifecycleRun($,Z);return{status:"error",error:`No background subagent found for id: ${$}`}}return this.awaitBackgroundEntry(J,Z)}async awaitBackgroundRunBounded($,Z){let J=Z.agentId;if($.signal.aborted)return new p9({result:{case:"stillRunning",value:new f3({agentId:J})}});let X=this.backgroundRuns.get(J);if(X===void 0){let K=this.takeQueuedChildCompletion(J);if(K!==void 0){if(K.status==="success")return new p9({result:{case:"complete",value:new VG({agentId:J,finalMessage:K.finalMessage,toolCallCount:K.toolCallCount??0})}});return new p9({result:{case:"error",value:new BG({agentId:J,error:K.finalMessage||"Subagent was aborted"})}})}if(this.isBackgroundRunBusy(J))return new p9({result:{case:"stillRunning",value:new f3({agentId:J})}});return new p9({result:{case:"notFound",value:new bN({agentId:J})}})}let[Y,Q]=$.withTimeoutAndCancel(Math.max(0,Z.timeoutMs)),W=await new Promise((K)=>{let H=()=>K(void 0);Y.signal.addEventListener("abort",H,{once:!0}),X.promise.then(K).finally(()=>{Y.signal.removeEventListener("abort",H),Q()})});if(W===void 0||W.status==="background"||$.signal.aborted)return new p9({result:{case:"stillRunning",value:new f3({agentId:J})}});if(this.takeQueuedChildCompletion(J,X.runId),W.status==="completed")return new p9({result:{case:"complete",value:new VG({agentId:J,finalMessage:W.finalMessage,toolCallCount:W.toolCallCount??0})}});return new p9({result:{case:"error",value:new BG({agentId:J,error:W.error??"Subagent was aborted"})}})}takeQueuedChildCompletion($,Z){for(let[J,X]of this.queuedChildCompletions){let Y=X.findIndex((W)=>W.agentId===$&&(Z===void 0||W.runId===Z));if(Y===-1)continue;let[Q]=X.splice(Y,1);if(X.length===0)this.queuedChildCompletions.delete(J);return Q}return}async awaitBusyLifecycleRun($,Z){while(this.isBackgroundRunBusy($)){if(Z.aborted)return{status:"error",error:"Await timed out while task is still running"};let J=this.backgroundRuns.get($);if(J)return this.awaitBackgroundEntry(J,Z);await new Promise((X)=>setTimeout(X,50))}return{status:"completed",toolCallCount:0}}async awaitBackgroundEntry($,Z){if(Z.aborted)return{status:"error",error:"Await timed out while task is still running"};let J={status:"error",error:"Await timed out while task is still running"};return new Promise((X)=>{let Y=()=>{X(J)};Z.addEventListener("abort",Y,{once:!0}),$.promise.then(X).finally(()=>Z.removeEventListener("abort",Y))})}registerParentChildLink($,Z){let J=Z?.trim();if(!J||J===$||!this.sessions.has(J)&&J!==this.parentConversationId)return;let X=this.childParentIds.get($);if(X===J)return;if(X){if(this.parentChildIds.get(X)?.delete($),(this.parentChildIds.get(X)?.size??0)===0)this.parentChildIds.delete(X)}this.childParentIds.set($,J);let Y=this.parentChildIds.get(J)??new Set;Y.add($),this.parentChildIds.set(J,Y)}removeParentChildLink($){let Z=this.childParentIds.get($);if(!Z)return;this.childParentIds.delete($);let J=this.parentChildIds.get(Z);if(J?.delete($),(J?.size??0)===0)this.parentChildIds.delete(Z)}enqueueChildCompletion($,Z,J){let X=this.childParentIds.get($);if(!X)return;let Y=this.queuedChildCompletions.get(X)??[];Y.push({agentId:$,runId:Z,status:J.status==="completed"?"success":J.status==="error"?"error":"aborted",finalMessage:J.status==="completed"?J.finalMessage??"":J.status==="error"?J.error:"Subagent was aborted by the user",...J.status==="completed"&&J.toolCallCount!==void 0?{toolCallCount:J.toolCallCount}:{}}),this.queuedChildCompletions.set(X,Y),this.removeParentChildLink($);let Q=this.childCompletionWaiters.get(X);if(!Q)return;this.childCompletionWaiters.delete(X);for(let W of Q)W()}async collectAvailableChildCompletions($,Z){let J=this.drainChildCompletions($);if(J.length>0)return J;if(!this.hasPendingChildSubagents($))return[];return await this.waitForChildCompletion($,Z),this.drainChildCompletions($)}hasPendingChildSubagents($){return(this.parentChildIds.get($)?.size??0)>0}drainChildCompletions($){let Z=this.queuedChildCompletions.get($)??[];return this.queuedChildCompletions.delete($),Z}async waitForChildCompletion($,Z){if(Z.aborted)throw Error("aborted");await new Promise((J,X)=>{let Y=this.childCompletionWaiters.get($)??new Set,Q=()=>{K(),J()},W=()=>{K(),X(Error("aborted"))},K=()=>{if(Y.delete(Q),Y.size===0)this.childCompletionWaiters.delete($);Z.removeEventListener("abort",W)};Y.add(Q),this.childCompletionWaiters.set($,Y),Z.addEventListener("abort",W,{once:!0})})}buildChildrenCompletedMessage($,Z){let J=$.map((X)=>{let Y=X.status==="success"?"SUCCESS":"FAILED";return`## Agent ${X.agentId} -- ${Y} ${X.finalMessage}`}).join(` @@ -46,12 +46,12 @@ index 4d813759e7075c0fe8c881d52200d94c657b5988..d107ac8d650a17aa1cadcef5994c086a `);await iS8($,J.length>0?`${J} `:"")}function ZP1($){return{...$,createdAt:new Date($.createdAt).getTime()}}Vm0();br0();s71();n$();Zm0();async function L7($,Z){try{return await Z()}catch(J){throw F6(J,{operation:$})}}class K91{constructor(){}static async create($){return L7("Agent.create",async()=>{if($.agentId===void 0&&$.cloud?.envVars!==void 0)return iT1($);let Z=$.agentId??($.cloud?gS0():mS0()),J={...$,agentId:Z};return iT1(J)})}static async resume($,Z){return L7("Agent.resume",()=>FS8($,Z))}static async prompt($,Z){return L7("Agent.prompt",async()=>{let J=await K91.create(Z??{});try{return await(await J.send($)).wait()}finally{await J[Symbol.asyncDispose]()}})}static async list($){return L7("Agent.list",()=>LS8($))}static async listRuns($,Z){return L7("Agent.listRuns",()=>US8($,Z))}static async getRun($,Z){return L7("Agent.getRun",()=>DS8($,Z))}static async cancelRun($,Z){return L7("Agent.cancelRun",()=>AS8($,Z))}static async get($,Z){return L7("Agent.get",()=>IS8($,Z))}static async archive($,Z){return L7("Agent.archive",()=>TS8($,Z))}static async unarchive($,Z){return L7("Agent.unarchive",()=>PS8($,Z))}static async delete($,Z){return L7("Agent.delete",()=>ES8($,Z))}static async getUsage($,Z){return L7("Agent.getUsage",()=>RS8($,Z))}static messages={list($,Z){return L7("Agent.messages.list",()=>wS8($,Z))}}}class XP1{constructor(){}static configure($){Ur0($)}static async me($){return L7("Cursor.me",()=>CS8($))}static models={list($){return L7("Cursor.models.list",()=>_S8($))}};static repositories={list($){return L7("Cursor.repositories.list",()=>SS8($))}};static auth={login($){return L7("Cursor.auth.login",()=>Py1($))},logout($){return L7("Cursor.auth.logout",()=>Ey1($))},status($){return L7("Cursor.auth.status",()=>ky1($))}}}import*as t8 from"zod/v3";RT1();var zv8=t8.object({text:t8.string()}),Hv8=t8.object({text:t8.string(),thinkingDurationMs:t8.number().optional()}),Gv8=t8.object({text:t8.string()}),qv8=t8.object({command:t8.string(),workingDirectory:t8.string().optional()}),Vv8=t8.object({stdout:t8.string(),stderr:t8.string(),exitCode:t8.number()}),Bv8=t8.discriminatedUnion("type",[t8.object({type:t8.literal("assistantMessage"),message:zv8}),t8.object({type:t8.literal("toolCall"),message:Jf0}),t8.object({type:t8.literal("thinkingMessage"),message:Hv8})]),Ov8=t8.object({userMessage:Gv8.optional(),steps:t8.array(Bv8)}),Fv8=t8.object({shellCommand:qv8.optional(),shellOutput:Vv8.optional()}),l5$=t8.discriminatedUnion("type",[t8.object({type:t8.literal("agentConversationTurn"),turn:Ov8}),t8.object({type:t8.literal("shellConversationTurn"),turn:Fv8})]);fT1();function i5$($){return $.type}kT1();export{F6 as wrapSdkError,Qh0 as unionFs,KQ0 as tempFs,Zh0 as strReplaceOnFileSystem,gS8 as startLocalRunEventNotifierServer,DC0 as remapPathError,mJ1 as readOnlyFs,vG as paginateRunDocuments,eN as paginateCheckpointBlobIds,$L as paginateAgentDocuments,en0 as overlayFs,_C0 as localRunStreamEventToSdkMessage,D8$ as isUserMessage,Ah0 as isTerminalLocalRunStreamEvent,w8$ as isMessage,QQ0 as isInvalidGrepPatternError,_3 as isFileNotFoundError,A8$ as isAssistantMessage,i5$ as getTurnType,K20 as getDefaultSdkStateRoot,Qf0 as getDefaultSdkAuthPath,hJ1 as emptyFs,yh1 as decodeSdkMessageRunStreamEvent,Dh0 as decodeLocalRunStreamEvent,Ua0 as createSdkMessageRunStreamEvent,mS8 as createLocalRunEventNotifier,uS8 as createInMemoryRunEventNotifier,XY1 as createFileSystemTools,WY as createAgentPlatform,hv8 as convertError,HV as convertConnectError,Ur0 as configureCursorSdk,m41 as composeLocalAgentStore,dJ1 as childOverlayFs,XQ0 as WriteFailedError,al0 as UserMessageSchema,b_8 as UserMessageAppendedUpdateSchema,W20 as UnsupportedRunOperationError,zJ as UnknownAgentError,c_8 as TurnEndedUpdateSchema,_T1 as ToolCallStartedUpdateSchema,a_8 as ToolCallDeltaUpdateSchema,ST1 as ToolCallCompletedUpdateSchema,f_8 as TokenDeltaUpdateSchema,vT1 as ThinkingDeltaUpdateSchema,yT1 as ThinkingCompletedUpdateSchema,CT1 as TextDeltaUpdateSchema,h_8 as SummaryUpdateSchema,m_8 as SummaryStartedUpdateSchema,g_8 as SummaryCompletedUpdateSchema,Vv8 as ShellOutputSchema,u_8 as ShellOutputDeltaUpdateSchema,Fv8 as ShellConversationTurnSchema,qv8 as ShellCommandSchema,Gv8 as SdkUserMessageSchema,Hv8 as SdkThinkingMessageSchema,zv8 as SdkAssistantMessageSchema,J7 as ReadOnlyMountError,wW as RateLimitError,g9 as PathError,xT1 as PartialToolCallUpdateSchema,JQ0 as NoMountError,A7 as NetworkError,n_8 as NestedTaskUpdateSchema,d_8 as ModelCallCompletedUpdateSchema,__8 as MessageSchema,tl0 as LocalRunEventNotifierServer,Z91 as LocalRunEventNotifier,OQ0 as LOCAL_RUN_STREAM_SCHEMA_VERSION,Na0 as LOCAL_RUN_STREAM_EVENT_TYPE,Q91 as JsonlLocalAgentStore,JP1 as JSONL_LOCAL_AGENT_STORE_FILES,NN as InvalidGrepPatternError,bT1 as InteractionUpdateSchema,Ki0 as IntegrationNotConnectedError,J91 as InMemoryRunEventNotifier,A91 as InMemoryCredentialStore,C_8 as ImageSchema,kJ as FileNotFoundError,Wf0 as FileCredentialStore,zi0 as FeatureUnavailableError,JG as FILE_SYSTEM_SCAN_LIMIT,G2 as EditError,YQ0 as DeleteNotSupportedError,LJ1 as DEFAULT_LOGIN_API_KEY_TTL_MS,BX as CursorSdkError,x30 as CursorAgentPlatform,jW as CursorAgentError,XP1 as Cursor,l5$ as ConversationTurnSchema,Bv8 as ConversationStepSchema,L1 as ConfigurationError,E5 as AuthenticationError,ET1 as AssistantMessageSchema,ND as AgentNotFoundError,Ov8 as AgentConversationTurnSchema,Wi0 as AgentBusyError,K91 as Agent}; diff --git a/dist/cjs/977.js b/dist/cjs/977.js -index 9b48bdf0d6ff3c60e525736752d11daeebb96fef..bbba4a6c1adee197776114ecccc4f7cd6b5b8d5d 100644 +index 9b48bdf0d6ff3c60e525736752d11daeebb96fef..559fc3999ab224e405b959b47548819a2aa634b1 100644 --- a/dist/cjs/977.js +++ b/dist/cjs/977.js @@ -1,4 +1,4 @@ -exports.id=977,exports.ids=[977],exports.modules={"./src/agent/local-executor.ts"(e,t,r){"use strict";r.d(t,{createLocalExecutor:()=>IH});var n=r("node:buffer"),o=r("node:os"),s=r("node:path"),i=r.t(s,2),a=r.n(s),c=r("../proto/dist/generated/agent/v1/agent_pb.js");const l={textDelta:(e,t)=>new c.Uq({messageStartedAtMs:t,message:{case:"textDelta",value:new c.PtE({text:e})}}),toolCallStarted:(e,t,r)=>new c.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"toolCallStarted",value:new c.xuG({callId:e,toolCall:t,modelCallId:r})}}),toolCallCompleted:(e,t,r)=>new c.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"toolCallCompleted",value:new c.LLS({callId:e,toolCall:t,modelCallId:r})}}),toolCallDelta:(e,t,r,n)=>new c.Uq({messageStartedAtMs:n,message:{case:"toolCallDelta",value:new c.I0n({callId:e,toolCallDelta:t,modelCallId:r})}}),thinkingDelta:(e,t,r)=>new c.Uq({messageStartedAtMs:r,message:{case:"thinkingDelta",value:new c.cHB({text:e,thinkingStyle:t})}}),thinkingCompleted:(e,t,r)=>new c.Uq({messageStartedAtMs:t,message:{case:"thinkingCompleted",value:new c.tr3({thinkingDurationMs:e,...!0===r?{narration:!0}:{}})}}),thinkingNote:e=>new c.Uq({message:{case:"thinkingNote",value:new c.Y$k({text:e})}}),taskChild:(e,t,r)=>"thinkingNote"===t.message.case?t:l.toolCallDelta(e,new c.V1v({delta:{case:"taskToolCallDelta",value:new c.aon({interactionUpdate:t})}}),r),userMessageAppended:e=>new c.Uq({messageStartedAtMs:e.startedAtMs,message:{case:"userMessageAppended",value:new c.v$T({userMessage:e})}}),partialToolCall:(e,t,r)=>new c.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"partialToolCall",value:new c.fxF({callId:e,toolCall:t,modelCallId:r})}}),tokenDelta:e=>new c.Uq({message:{case:"tokenDelta",value:new c.Fyz({tokens:e})}}),summary:e=>new c.Uq({message:{case:"summary",value:new c.ECk({summary:e})}}),summaryStarted:()=>new c.Uq({message:{case:"summaryStarted",value:new c.lWT}}),heartbeat:()=>new c.Uq({message:{case:"heartbeat",value:new c.ih1}}),summaryCompleted:(e,t,r)=>new c.Uq({message:{case:"summaryCompleted",value:new c.ZM9({hookMessage:e,failed:t,fallback:r})}}),shellOutputDelta:e=>new c.Uq({message:{case:"shellOutputDelta",value:new c.Nn_({event:e})}}),modelCallCompleted:(e,t)=>new c.Uq({message:{case:"modelCallCompleted",value:new c.c2D({modelCallId:e,inputTokens:BigInt(t.inputTokens),outputTokens:BigInt(t.outputTokens),cacheReadTokens:BigInt(t.cacheReadTokens),cacheWriteTokens:BigInt(t.cacheWriteTokens),...void 0!==t.reasoningTokens?{reasoningTokens:BigInt(t.reasoningTokens)}:{}})}}),turnEnded(e,t){const r=e?.catalogCostCents;return new c.Uq({message:{case:"turnEnded",value:new c.lJj({...e?{inputTokens:BigInt(e.inputTokens),outputTokens:BigInt(e.outputTokens),cacheReadTokens:BigInt(e.cacheReadTokens),cacheWriteTokens:BigInt(e.cacheWriteTokens),reasoningTokens:BigInt(e.reasoningTokens??0)}:{},...void 0!==t?{endedAtMs:t}:{},...void 0!==r&&Number.isFinite(r)?{estimatedCost:new c.QVp({rawCostCents:r,chargedCents:r,source:c.nnk.CATALOG})}:{}})}})},stepStarted:e=>new c.Uq({message:{case:"stepStarted",value:new c.dwJ({stepId:BigInt(e)})}}),toolRequestsListed:e=>new c.Uq({message:{case:"toolRequestsListed",value:new c.BU$({callCount:Math.max(0,e)})}}),voiceCallUtterance:e=>new c.Uq({message:{case:"voiceCallUtterance",value:e}}),stepCompleted:(e,t)=>new c.Uq({message:{case:"stepCompleted",value:new c.Lrv({stepId:BigInt(e),stepDurationMs:BigInt(t)})}}),activeBranchChange:(e,t)=>new c.Uq({message:{case:"activeBranchChange",value:new c.PSN({path:e,branchName:t})}}),feedbackRequest:(e,t,r,n=[],o={})=>new c.Uq({message:{case:"feedbackRequest",value:new c.apn({requestId:e,canonicalModelName:t,categories:[...r],categoryGroups:[...n],title:o.title,negativeTitle:o.negativeTitle,commentPlaceholder:o.commentPlaceholder})}})};class u{constructor(e=0){this.nextId=e}next(){return this.nextId++}peekNext(){return this.nextId}observe(e){Number.isSafeInteger(e)&&e>=this.nextId&&(this.nextId=e+1)}}var d=r("../context/dist/logger.js"),h=r("../metrics/dist/index.js"),p=r("../proto/dist/generated/agent/v1/exec_pb.js"),f=r("../utils/dist/writable-iterable.js");const m=/https?:\/\/\S+/gi,g=/[)"'<>,.;:\]}]$/;function w(e){const{url:t,wrappers:r}=function(e){let t=e.length;for(;t>0&&g.test(e.slice(t-1,t));)t-=1;return{url:e.slice(0,t),wrappers:e.slice(t)}}(e),n=t.search(/[?#]/),o=-1===n?t:t.slice(0,n),s=o.indexOf("//")+2,i=o.slice(s).search(/[/?#]/),a=-1===i?o.length:s+i,c=o.lastIndexOf("@",a-1);return c0&&o.push(`gitErrorCode=${n.gitErrorCode}`),"number"==typeof n.exitCode&&Number.isFinite(n.exitCode)&&o.push(`exitCode=${n.exitCode}`),0===o.length)return e;let s=`${e} [git: ${o.join(" ")}]`;var i,a;return!0===r?.includeStderr&&"string"==typeof n.stderr&&n.stderr.length>0&&(s+=`\n--- git stderr ---\n${a=n.stderr,i=a.replace(m,w),i.length<=2048?i:`${i.slice(0,2048)}… [truncated to 2048 chars]`}`),s}var b=r("../context/dist/core.js");const S=(0,b.cF)(Symbol("machineProfile"),void 0),k=(0,d.h)("SimpleControlledExecManager"),_=(0,h.v5)("agent_exec.controlled.exec.duration_ms",{description:"Duration of controlled exec operations in milliseconds",labelNames:["exec_case"]}),C=(0,h.v5)("agent_exec.controlled.exec.machine_duration_ms",{description:"Duration of grep, shell and hook execs by coarse machine profile",labelNames:["exec_case","cpu_cores","ram_gb","defender_rt"]}),E=new Set(["grepArgs","shellStreamArgs","executeHookArgs"]),x=(0,h.Pu)("agent_exec.controlled.exec.success",{description:"Count of successful controlled exec operations",labelNames:["exec_case"]}),P=(0,h.Pu)("agent_exec.controlled.exec.error",{description:"Count of failed controlled exec operations",labelNames:["exec_case"]}),R={computerUseArgs:"Computer use is not enabled for this environment, so the Computer tool and the computerUse subagent cannot run here. Do not retry computer actions; verify with non-GUI methods (automated tests, shell commands) instead. (No computer-use handler is registered on this exec daemon.)",recordScreenArgs:"Screen recording is not enabled for this environment, so recordings cannot be captured here. Do not retry; skip the recording and present other evidence instead. (No record-screen handler is registered on this exec daemon.)"};class I extends Error{constructor(e){super(e),this.name="ControlledExecDisposedError"}}function T(e){return e instanceof I?"EXEC_BACKEND_UNAVAILABLE":e instanceof Error&&"AgentExecStreamStartTimeoutError"===e.name?"AGENT_EXEC_STREAM_START_TIMEOUT":void 0}class A{constructor(e,t,r){this.exec=e,this.deserializeArgs=t,this.serializeResult=r}handle(e,t){const r=this.deserializeArgs(t);if(void 0===r)return;const{id:n,args:o}=r;return async function*(r){const s=performance.now(),i=[],a=await r.exec.execute(e,o,{execId:t.execId,hookContextCollector:i,deliverAgentStoreConflictNotices:!0===t.acceptHookAdditionalContexts,recordAgentView:!0===t.recordAgentView,refuseUnreadChanges:!0===t.refuseUnreadChanges}),c=r.serializeResult(n,a);c.localExecutionTimeMs=Math.round(Math.max(0,performance.now()-s)),i.length>0&&(c.hookAdditionalContexts=i),yield c}(this)}}class ${constructor(e,t,r){this.exec=e,this.deserializeArgs=t,this.serializeStream=r}handle(e,t){const r=this.deserializeArgs(t);if(void 0===r)return;const{id:n,args:o}=r;return async function*(r){const s=performance.now(),i=[],a=r.exec.execute(e,o,{execId:t.execId,hookContextCollector:i,deliverAgentStoreConflictNotices:!0===t.acceptHookAdditionalContexts});try{for await(const e of a){const t=r.serializeStream(n,e);t.localExecutionTimeMs=Math.round(Math.max(0,performance.now()-s)),yield t}}finally{const e=i.filter((e=>"agentStoreConflict"===e.hookEventName));e.length>0&&(yield new p.yT({id:n,hookAdditionalContexts:e}))}}(this)}}class M{constructor(e){this.handlers=[],this.runningExecs=new Map;const t=e?.includeGitStderrInThrows??!1;this.includeGitStderrInThrows="function"==typeof t?t:()=>t,this.observeResults=e?.observeResults}startResultObserver(e,t,r){if(void 0!==this.observeResults)try{return this.observeResults(e,t,r)}catch{return}}register(e){this.handlers.push(e)}handleControlMessage(e){if("abort"===e.message.case){const t=e.message.value.id,r=this.runningExecs.get(t);r&&r()}}handle(e,t){const[r,n]=e.withCancel();this.runningExecs.set(t.id,n);const o=t.message.case??"unknown";for(const e of this.handlers){const s=e.handle(r,t);if(void 0===s)continue;const i=s,a=(0,f.Jt)();let c;const l=()=>{c=setTimeout((()=>{a.write(new p.$Y({message:{case:"heartbeat",value:new p.VA({id:t.id})}})).then(l).catch((()=>{}))}),3e3)};l();const u=performance.now(),d=this.startResultObserver(r,o,t);return(async()=>{try{for await(const e of i){if(void 0!==d&&e instanceof p.yT)try{d.message(e)}catch{}await a.write(e)}await a.write(new p.$Y({message:{case:"streamClose",value:new p.D9({id:t.id})}})),x.increment(r,1,{exec_case:o})}catch(e){if(e instanceof f.W2)return;P.increment(r,1,{exec_case:o}),await a.write(new p.$Y({message:{case:"throw",value:new p.Fu({id:t.id,error:e instanceof Error?v(e.message,e,{includeStderr:this.includeGitStderrInThrows()}):"Unknown error",stackTrace:e instanceof Error?e.stack:void 0,errorCode:T(e)})}}))}finally{if(void 0!==d)try{d.done()}catch{}const e=performance.now()-u;if(_.histogram(r,e,{exec_case:o}),E.has(o)){const t=r.get(S)?.();void 0!==t&&C.histogram(r,e,{exec_case:o,...t})}clearTimeout(c),a.close(),this.runningExecs.delete(t.id),n()}})(),a}this.runningExecs.delete(t.id),n();const s=t.message.case,i=(void 0===s?void 0:R[s])??`No handler found for server message of type ${s}`;return k.error(e,i,{messageCase:s}),P.increment(e,1,{exec_case:o}),async function*(){yield new p.$Y({message:{case:"throw",value:new p.Fu({id:t.id,error:i})}}),yield new p.$Y({message:{case:"streamClose",value:new p.D9({id:t.id})}})}()}static fromResources(e,t){const r=new M(t);for(const[t,n]of e.entries())t.registerControlledImplementation(n,r);return r}}var D=r("../context/dist/otel.js");async function O(e){const t=e[Symbol.asyncIterator](),r=await t.next();if(r.done)return;const n={async*[Symbol.asyncIterator](){for(;;){const e=await t.next();if(e.done)return;yield e.value}}};return{firstItem:r.value,rest:n}}const F=(0,b.cF)(Symbol("agentExec.remoteExecResultObserverFactory"),void 0),N={message(){},[Symbol.dispose](){}};function L(e){const t=e.get(F);if(void 0===t)return N;let r;try{r=t(e)}catch{return N}return void 0===r?N:{message(e){try{r?.message(e)}catch{r=void 0}},[Symbol.dispose](){const e=r;r=void 0;try{e?.end()}catch{}}}}var j=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},U=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const B=(0,d.h)("ExecutorResource"),W=(0,h.Pu)("agent_exec.hook_additional_context.delivered",{description:"Hook additional_context carriers drained into the caller collector",labelNames:["hook_event_name"]});class H{constructor(e,t,r){this.execManager=e,this.serializeArgs=t,this.deserializeResult=r}async execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=j(n,(0,D.VI)(e.withName("ExecutorResource.execute")),!1),s=o.ctx;void 0!==r?.execId&&o.span.setAttribute("exec.id",r.execId);const i=(0,D.mJ)(s),a=i?new p.Kg(i):void 0,c=this.execManager.createExecInstance(s,(e=>{const n=this.serializeArgs(e,t);return new p.Ye({id:n.id,message:n.message,execId:r?.execId,machineId:r?.machineId,spanContext:a,acceptHookAdditionalContexts:void 0!==r?.hookContextCollector,recordAgentView:r?.recordAgentView,refuseUnreadChanges:r?.refuseUnreadChanges})})),l=await O(c);if(void 0===l)throw new Error("No exec result");let{firstItem:u,rest:d}=l;const h=j(n,L(s),!1),f=e=>{if(h.message(e),void 0!==r?.hookContextCollector&&e.hookAdditionalContexts.length>0){r.hookContextCollector.push(...e.hookAdditionalContexts);for(const t of e.hookAdditionalContexts)W.increment(s,1,{hook_event_name:t.hookEventName})}};f(u);let m=this.deserializeResult(u);for(;void 0===m;){const e=await O(d);if(void 0===e)throw new Error("No result value");u=e.firstItem,d=e.rest,f(u),m=this.deserializeResult(u)}return(async()=>{try{for await(const e of d)f(e)}catch(e){B.info(s,"Ignoring exec stream shutdown during detached drain",{error:e})}})().catch((()=>{})),m}catch(e){n.error=e,n.hasError=!0}finally{U(n)}}}class q{constructor(e,t,r){this.execManager=e,this.serializeArgs=t,this.deserializeStream=r}async*execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=j(n,(0,D.VI)(e.withName("StreamExecutorResource.execute")),!1).ctx,s=(0,D.mJ)(o),i=s?new p.Kg(s):void 0,a=this.execManager.createExecInstance(o,(e=>{const n=this.serializeArgs(e,t);return new p.Ye({id:n.id,message:n.message,execId:r?.execId,machineId:r?.machineId,spanContext:i,acceptHookAdditionalContexts:void 0!==r?.hookContextCollector||!0===r?.deliverAgentStoreConflictNotices})})),c=j(n,L(o),!1);for await(const e of a){c.message(e),void 0!==r?.hookContextCollector&&e.hookAdditionalContexts.length>0&&r.hookContextCollector.push(...e.hookAdditionalContexts);const t=this.deserializeStream(e);void 0!==t&&(yield t)}}catch(e){n.error=e,n.hasError=!0}finally{U(n)}}}function z(e){return Symbol.for(`@anysphere/agent-exec/resource/${e}`)}function G(e,t,r){return{name:e,symbol:z(e),remoteImplementation:t,registerControlledImplementation:r}}class V{constructor(e,t){this.resource=e,this.value=t}}function K(e,t){return[e,t]}function J(e,t){return t}class Z{constructor(){this.resources=new Map}register(e,t){this.resources.set(e.symbol,new V(e,t))}get(e){return J(0,this.resources.get(e.symbol)?.value)}entries(){return Array.from(this.resources.values()).map((e=>[e.resource,e.value]))}}class X{constructor(e,t){this.remoteAccessor=e,this.localResources=new Map;for(const[e,r]of t)this.localResources.set(e.symbol,{resource:e,implementation:r})}get(e){const t=this.localResources.get(e.symbol);return t?J(0,t.implementation):this.remoteAccessor.get(e)}*entries(){for(const{resource:e,implementation:t}of this.localResources.values())yield[e,t];for(const e of this.remoteAccessor.entries())this.localResources.has(e[0].symbol)||(yield e)}}function Q(e){return function(t,r){return new p.Ye({id:t,message:{case:e,value:r}})}}function Y(e){return t=>{if(t.message.case===e)return t.message.value}}function ee(e){return function(t,r){const n={case:e,value:r};return new p.yT({id:t,message:n})}}function te(e){return function(t){if(t.message.case===e)return{id:t.id,args:t.message.value}}}const re=G("shell-stream-executor",(e=>new q(e,Q("shellStreamArgs"),Y("shellStream"))),((e,t)=>{t.register(new $(e,te("shellStreamArgs"),ee("shellStream")))}));var ne=r("../proto/dist/generated/agent/v1/kv_pb.js"),oe=r("../agent-kv/dist/blob-store.js"),se=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const ie=(0,d.h)("ControlledKvManager");function ae(e,t,r){return e?(0,D.F)({traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags??1},t,r):r}function ce(e,t,r,n,o){o<=r||(0,D.xd)(e.withName(`${t}.slow`),{startTime:n,attributes:{durationMs:o,slowThresholdMs:r}},n+o)}const le=(0,h.v5)("agent_kv.controlled.get_blob.duration_ms",{description:"Duration of ControlledKvManager getBlob operations in milliseconds"}),ue=(0,h.v5)("agent_kv.controlled.set_blob.duration_ms",{description:"Duration of ControlledKvManager setBlob operations in milliseconds"});class de{constructor(e,t,r,n={}){this.serverStream=e,this.clientStream=t,this.blobStore=r,this.options=n}async run(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,D.VI)(e.withName("ControlledKvManager.run")),!1).ctx,n=new Set,o=e=>{n.add(e),e.finally((()=>{n.delete(e)}))};try{for await(const e of this.serverStream){const t=performance.now(),n=Date.now();switch(e.message.case){case"getBlobArgs":{const s=e.message.value.blobId;o((async()=>{const o=ae(e.spanContext,"ControlledKvManager.getBlob",r);try{await(this.options.beforeGetBlob?.(o,s));const t=await this.blobStore.getBlob(o,s);await this.clientStream.write(new ne.gm({id:e.id,message:{case:"getBlobResult",value:{blobData:t?(0,oe.Fo)(t):void 0}}}))}catch(t){ie.error(o,"Error handling getBlob",t);const r=t instanceof Error?t.message:String(t);try{await this.clientStream.write(new ne.gm({id:e.id,message:{case:"getBlobResult",value:{blobData:void 0,error:{message:r}}}}))}catch(e){ie.error(o,"Error writing failed getBlobResult",e)}}finally{const e=performance.now()-t;le.histogram(o,e),ce(o,"ControlledKvManager.getBlob",50,n,e)}})());break}case"setBlobArgs":{const s=e.message.value.blobId,i=e.message.value.blobData;o((async()=>{const o=ae(e.spanContext,"ControlledKvManager.setBlob",r);try{await this.blobStore.setBlob(o,s,i),await this.clientStream.write(new ne.gm({id:e.id,message:{case:"setBlobResult",value:{error:void 0}}}))}catch(t){const r=t instanceof Error?t.message:String(t);try{await this.clientStream.write(new ne.gm({id:e.id,message:{case:"setBlobResult",value:{error:{message:r}}}}))}catch(e){ie.error(o,"Error writing setBlobResult",e)}}finally{const e=performance.now()-t;ue.histogram(o,e),ce(o,"ControlledKvManager.setBlob",100,n,e)}})());break}}}}finally{await Promise.allSettled(n)}}catch(e){t.error=e,t.hasError=!0}finally{se(t)}}}function he(e){return e instanceof Error?{abortReasonType:"error",abortReasonName:e.name,abortReasonMessage:e.message}:"string"==typeof e?{abortReasonType:"string",abortReasonMessage:e}:void 0===e?{abortReasonType:"undefined"}:{abortReasonType:typeof e}}var pe=r("../proto/dist/generated/agent/v1/agent_service_pb.js"),fe=r("../proto/dist/generated/agent/v1/shell_exec_pb.js");Error;const me={stateRestoreMs:"client_prep_state_restore_ms",rootPromptRestoreMs:"client_prep_root_prompt_restore_ms",requestContextMs:"client_prep_request_context_ms",systemPromptMs:"client_prep_system_prompt_ms",preTurnSnapshotMs:"client_prep_pre_turn_snapshot_ms",preTurnSnapshotWaitMs:"client_prep_pre_turn_snapshot_wait_ms",preTurnSnapshotBlobWritesMs:"client_prep_pre_turn_snapshot_blob_writes_ms",preTurnSnapshotSerializeMs:"client_prep_pre_turn_snapshot_serialize_ms",firstStepToFirstInvocationMs:"client_prep_first_step_to_first_invocation_ms",promptMessageCount:"client_prep_prompt_message_count",turnCount:"client_prep_turn_count"},ge=Object.keys(me).filter((e=>e in me));function we(e){const t={};for(const r of ge){const n=e[r];void 0!==n&&(t[r]=n)}return t}new WeakMap;var ye=r("../utils/dist/fresh-uuid.js"),ve=r("@bufbuild/protobuf"),be=r("@connectrpc/connect"),Se=r("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/protocol/async-iterable.js"),ke=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class _e{constructor(e,t,r){this.checkpointStream=e,this.checkpointHandler=t,this.ctx=r}async run(){const e={stack:[],error:void 0,hasError:!1};try{const t=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(e,(0,D.VI)(this.ctx.withName("CheckpointController.run")),!1).ctx,r=[];for await(const e of this.checkpointStream){let n;try{n=this.checkpointHandler.handleCheckpoint(t,e.checkpoint,e.metadata)}catch(t){throw e.onSettled?.(),t}r.push(n),void 0!==e.onSettled&&n.then(e.onSettled,e.onSettled)}await Promise.all(r)}catch(t){e.error=t,e.hasError=!0}finally{ke(e)}}}const Ce=(0,d.h)("@anysphere/agent-client:checkpoint-store-waits");class Ee{constructor(e={}){this.options=e,this.inFlight=new Map}noteRouted(e){const t=Pe(e.pendingToolCalls);if(0===t.size)return xe;let r;const n=new Promise((e=>{r=e}));for(const e of t){let t=this.inFlight.get(e);void 0===t&&(t=new Set,this.inFlight.set(e,t)),t.add(n)}return()=>{for(const e of t){const t=this.inFlight.get(e);t?.delete(n),0===t?.size&&this.inFlight.delete(e)}r()}}storedBefore(e,t){const r=this.inFlight.get(t);if(void 0!==r){try{this.options.onExecHeld?.(t)}catch(t){Ce.warn(e,"onExecHeldForCheckpointStore callback failed",{error:String(t)})}return Promise.all(r).then(xe)}}}function xe(){}function Pe(e){const t=new Set;for(const r of e){let e;try{e=JSON.parse(r)}catch{continue}const n=Ie(e)?e.content:void 0;if(!Array.isArray(n))continue;const o=n;for(const e of o)Ie(e)&&"tool-call"===e.type&&"string"==typeof e.toolCallId&&t.add(e.toolCallId)}return t}function Re(e){if("executeHookArgs"===e.message.case)return function(e){const t=e.request?.request;switch(t?.case){case"preToolUse":case"postToolUse":case"postToolUseFailure":return""===t.value.toolUseId?void 0:t.value.toolUseId;case"subagentStart":return""===t.value.toolCallId?void 0:t.value.toolCallId;default:return}}(e.message.value);const t=e.message.value;return Ie(t)&&"string"==typeof t.toolCallId&&""!==t.toolCallId?t.toolCallId:void 0}function Ie(e){return"object"==typeof e&&null!==e}const Te=(0,d.h)("@anysphere/agent-client:exec-checkpoint-gate"),Ae=new Set(["shellArgs","shellStreamArgs","backgroundShellSpawnArgs","forceBackgroundShellArgs","miniSweAgentBashArgs","writeArgs","deleteArgs","mcpArgs","readMcpResourceExecArgs","computerUseArgs","recordScreenArgs","subagentArgs","forceBackgroundSubagentArgs","executeHookArgs"]),$e=new Set(["userMessageAction","resumeAction","backgroundTaskCompletionAction","goalContinuationAction","subscriptionNotificationAction","executePlanAction","asyncAskQuestionCompletionAction"]);function Me(e){const t=e.message.case;return void 0!==t&&Ae.has(t)?Re(e):void 0}const De=e=>e.replace(/[\r\n]/g,"");function Oe(e){return{...void 0!==e.parentRequestId?{"x-parent-request-id":De(e.parentRequestId)}:{},...void 0!==e.rootParentRequestId?{"x-root-parent-request-id":De(e.rootParentRequestId)}:{},...void 0!==e.parentAgentToolCallId?{"x-parent-agent-tool-call-id":De(e.parentAgentToolCallId)}:{},...!0===e.directMetaParentChildSubagent?{"x-direct-meta-parent-child-subagent":"true"}:{}}}const Fe="x-inference-authentication-jwt";function Ne(){const e=globalThis.process?.env,t=e?.INFERENCE_PROXY_JWT?.trim();return void 0===t||""===t||t.startsWith("$")?{}:{[Fe]:t}}class Le extends Error{constructor(e,t){super(`This conversation's data is missing and can't be restored. Start a new chat to continue.${function(e){if(0===e.length)return"";const t=e.slice(0,3).map((e=>e.slice(0,12)));return` (${1===e.length?`missing blob ${t[0]}`:`${e.length} missing blobs: ${t.join(", ")}${e.length>t.length?", …":""}`})`}(e)}`,void 0!==t?.cause?{cause:t.cause}:void 0),this.isUsageError=!0,this.isBlobNotFound=!0,this.name="BlobNotFoundError",this.blobIdHexes=[...e]}}function je(e){return e instanceof Error&&(e instanceof Le||"isBlobNotFound"in e&&!0===e.isBlobNotFound||"BlobNotFoundError"===e.name)}var Ue=r("../proto/dist/generated/aiserver/v1/utils_pb.js"),Be=r("zod/v4");const We="relayedAttemptFailure",He=Be.object({transport:Be.boolean(),stallAborted:Be.boolean(),errorName:Be.string(),connectCode:Be.number().optional(),connectCodeName:Be.string().optional(),connectCause:Be.object({code:Be.union([Be.string(),Be.number()]).optional(),name:Be.string().optional()}).optional(),transportFailureKind:Be.string().optional(),loop:Be.string().optional(),transportMode:Be.string().optional()});function qe(e){const t=e?.details?.additionalInfo[We];if(void 0!==t)try{const e=He.safeParse(JSON.parse(t));return e.success?e.data:void 0}catch{return}}class ze extends Error{constructor(e,t={}){super(e),Object.setPrototypeOf(this,new.target.prototype),this.cause=t.cause,this.requestId=t.requestId,this.displayInfo=t.displayInfo,this.isTransport=t.isTransport}get name(){return this.kind}}class Ge extends ze{get kind(){return"RetriableError"}}class Ve extends ze{constructor(e,t,r={}){super(e,r),this.action=t}get kind(){return"ActionRequiredError"}}class Ke extends ze{get kind(){return"NonRetriableError"}}class Je extends Ke{constructor(e){const t=`This turn's step limit (${e}) needs an in-process agent loop; the network client cannot send it.`;super(t,{displayInfo:{title:"Step limit not supported",detail:t,isRetryable:!1}}),this.maxSteps=e}}class Ze extends ze{get kind(){return"CancelledError"}}const Xe=new Set([Ue.yM.NOT_LOGGED_IN,Ue.yM.AGENT_REQUIRES_LOGIN,Ue.yM.AUTH_TOKEN_NOT_FOUND,Ue.yM.AUTH_TOKEN_EXPIRED,Ue.yM.INVALID_AUTH_ID,Ue.yM.UNAUTHORIZED,Ue.yM.GITHUB_NO_USER_CREDENTIALS,Ue.yM.GITHUB_USER_NO_ACCESS]),Qe=new Set([Ue.yM.FREE_USER_USAGE_LIMIT,Ue.yM.FREE_USER_RATE_LIMIT_EXCEEDED,Ue.yM.PRO_USER_ONLY,Ue.yM.PRO_USER_USAGE_LIMIT,Ue.yM.PRO_USER_RATE_LIMIT_EXCEEDED,Ue.yM.RATE_LIMITED,Ue.yM.RATE_LIMITED_CHANGEABLE,Ue.yM.GENERIC_RATE_LIMIT_EXCEEDED]),Ye=new Set([Ue.yM.USAGE_PRICING_REQUIRED,Ue.yM.USAGE_PRICING_REQUIRED_CHANGEABLE]),et=new Set([Ue.yM.BAD_API_KEY,Ue.yM.BAD_USER_API_KEY,Ue.yM.OUTDATED_CLIENT]),tt=new Set([Ue.yM.USER_ABORTED_REQUEST,Ue.yM.DEBOUNCED]),rt=new Set([Ue.yM.CUSTOM_MESSAGE]),nt=new Map([[be.Code.PermissionDenied,"Permission Denied"]]),ot=["NGHTTP2","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE","socket hang up","Premature close","UND_ERR_SOCKET","ERR_STREAM","protocol error","http/2 stream","ERR_HTTP2_SESSION_ERROR","Session closed with error code","connection aborted","PING timed out","HTTP/2 session not established","HTTP/2 peer not answering","refused to tunnel to","HTTP CONNECT through proxy","Could not connect to proxy"],st=new Set(["ENOTFOUND","EAI_AGAIN","EAI_FAIL","ENODATA","ESERVFAIL","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ECONNABORTED"]),it=new RegExp(`\\b(${[...st].join("|")})\\b`),at=["IMAGE_TOO_LARGE","MAX_TOKENS","CONVERSATION_TOO_LONG","CONTENT_POLICY","DEPRECATED","MAX_MODE_REQUIRED","MODEL_NO_LONGER_SUPPORTED","UNSUPPORTED_REGION","OUTDATED_CLIENT"],ct="x-cursor-inference-request-error-type",lt="AgentWebSocketDeliveryAmbiguousError";function ut(e,t={}){const{requestId:r}=t;if(e instanceof ze)return e;if(dt(e))return function(e,t){const r=pt(e),n=r.code,o=ft(e),s=void 0===o?void 0:function(e){if(void 0===e.details?.additionalInfo[We])return e;const t=e.clone();return void 0!==t.details&&(delete t.details.additionalInfo[We],t.details.equals(new Ue.ej)&&(t.details=void 0)),t}(o),i={title:s?.details?.title,detail:s?.details?.detail,isRetryable:s?.details?.isRetryable,connectCode:n,errorCode:s?.error,inferenceRequestErrorType:mt(r,ct)??mt(e,ct),errorDetails:s},a={cause:e,requestId:t,displayInfo:i,...!0===qe(o)?.transport?{isTransport:!0}:{}};if(n===be.Code.Canceled||n===be.Code.Aborted)return kt(e)?new Ge(e.message,a):new Ze(e.message,a);if(void 0!==s?.error){const t=s.error;if(tt.has(t))return new Ze(vt(e,s),a);const r=s.details?.analyticsMetadata?.actionRequired;if(void 0!==r&&""!==r)return new Ve(vt(e,s),r,a);if(void 0!==Mt(s))return new Ge(vt(e,s),a);if(Xe.has(t))return new Ve(vt(e,s),"login",a);if(Qe.has(t))return new Ve(vt(e,s),"upgrade",a);if(Ye.has(t))return new Ve(vt(e,s),"payment",a);if(et.has(t))return new Ve(vt(e,s),"config",a);if(rt.has(t)&&!0!==s.details?.isRetryable)return new Ke(vt(e,s),a);if(!1===s.details?.isRetryable)return new Ke(vt(e,s),a)}if(n===be.Code.Unauthenticated)return new Ve(e.message,"login",{...a,displayInfo:ht(i,"Sign in required",r)});const c=yt(r);if(Tt.test(c))return new Ve(e.message,"proxy_sign_in",{...a,displayInfo:{...i,title:"Proxy sign-in required",detail:`${c}. Please check your sign-in for this proxy and try again.`,isRetryable:!0}});if(At.test(c))return new Ve(e.message,"proxy_blocked",{...a,displayInfo:{...i,title:"Connection blocked by proxy",detail:`${c}. Your proxy doesn't allow this connection. Please ask your network administrator to allow it and try again.`,isRetryable:!0}});const l=nt.get(n);return void 0===l||!0===s?.details?.isRetryable||kt(e)?new Ge(e.message,a):new Ke(vt(e,s),{...a,displayInfo:ht(i,l,r)})}(e,r);const n=function(e){let t=e;for(let e=0;e<10;e++){if(null==t)return;if(je(t))return t;if("object"!=typeof t||!("cause"in t))return;t=t.cause}}(e);if(void 0!==n)return new Ke(n.message,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Conversation data missing",detail:n.message,isRetryable:!1}});const o=function(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){if(r.name===bt)return r;t.add(r),r=r.cause}}(e);if(void 0!==o)return new Ke(o.message,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Context summarization failed",detail:o.message,isRetryable:!1}});if(function(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){const e="code"in r?r.code:void 0,n="errcode"in r?r.errcode:void 0;if("ENOSPC"===e||"ERR_SQLITE_ERROR"===e&&"number"==typeof n&&13==(255&n))return!0;t.add(r),r=r.cause}return!1}(e))return new Ke(St,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Out of disk space",detail:St,isRetryable:!1}});if(e instanceof Error){if("AbortError"===e.name)return new Ze(e.message,{cause:e,requestId:r});if(e.name===lt)return new Ge(e.message,{cause:e,requestId:r,isTransport:!0});if(kt(e))return new Ge(e.message,{cause:e,requestId:r})}const s=e instanceof Error?e.message:String(e);return new Ge(s,{cause:e instanceof Error?e:void 0,requestId:r})}function dt(e){return null!==e&&"object"==typeof e&&"code"in e&&"name"in e&&("ConnectError"===e.name||"rawMessage"in e&&"string"==typeof e.rawMessage&&"details"in e&&Array.isArray(e.details)&&"findDetails"in e&&"function"==typeof e.findDetails)}function ht(e,t,r){return{...e,title:e.title||t,detail:e.detail||yt(r),isRetryable:e.isRetryable??!1}}function pt(e){let t=e;for(let e=0;e<10&&t.code===be.Code.Unknown;e++){const e=t.cause;if(!dt(e))break;t=e}return t}function ft(e){let t=e;for(let e=0;e<10&&dt(t);e++){try{const e=t.findDetails?.(Ue.vj);if(void 0!==e&&e.length>0)return e[0]}catch{}t=t.cause}}function mt(e,t){const r=e.metadata;if(null===r||"object"!=typeof r||!("get"in r)||"function"!=typeof r.get)return;const n=r.get(t);return"string"==typeof n?n:void 0}function gt(e){let t=e;for(let e=0;e<10&&"object"==typeof t&&null!==t;e++){if(dt(t))return t;t="cause"in t?t.cause:void 0}}function wt(e){const t=gt(e);return void 0===t?void 0:pt(t)}function yt(e){const t=e.rawMessage;return"string"==typeof t?t:e.message.replace(/^\[[a-z_]+\] /,"")}function vt(e,t){if(t?.details){const{title:r,detail:n}=t.details;return r&&n?`${r} ${n}`:r||n||e.message}return e.message}const bt="SummaryPlaceholderRejectedError",St="Out of disk space. Free some space and try again.";function kt(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){t.add(r);const e=`${r.name}: ${r.message}`;if(ot.some((t=>e.includes(t)))||it.test(e))return!0;const n=r.code;if("string"==typeof n&&(ot.some((e=>n.includes(e)))||st.has(n)))return!0;r=r.cause}return!1}function _t(e){return ot.some((t=>e.includes(t)))||it.test(e)}function Ct(e){return e instanceof ze&&e.cause instanceof Error?kt(e.cause):e instanceof Error?kt(e):"string"==typeof e&&_t(e)}function Et(e){return void 0!==e&&e>0}function xt(e){return e+1}function Pt(e){return Object.defineProperty(e,"code",{value:"connection_stalled",enumerable:!0,configurable:!0}),e}function Rt(e){const{cause:t,requestId:r,transportErrorRetries:n,connectCode:o}=e;return Et(n)?Pt(new Ge("Connection stalled repeatedly",{cause:t,requestId:r,displayInfo:{title:"Connection stalled",detail:`The connection stalled ${xt(n)} times. Please check your network connection and try again.`,isRetryable:!0,connectCode:o}})):Pt(new Ge("Connection stalled",{cause:t,requestId:r,displayInfo:{title:"Connection stalled",detail:"The connection stalled. Please try again.",isRetryable:!0,connectCode:o}}))}const It=/^(?:Proxy \S+ refused to tunnel to |HTTP CONNECT through proxy \S+ failed: |Could not connect to proxy \S+: )/,Tt=/^Proxy \S+ refused to tunnel to \S+: 407\b/,At=/^Proxy \S+ refused to tunnel to \S+: 403\b/;function $t(e){let t=e.cause;for(let e=0;e<10&&void 0!==t;e++){if(t instanceof Error&&"AbortError"===t.name)return!0;if(dt(t)&&(t.code===be.Code.Canceled||t.code===be.Code.Aborted))return!0;t=null!==t&&"object"==typeof t&&"cause"in t?t.cause:void 0}return!1}function Mt(e){const t=e?.details?.additionalInfo;if(e?.error!==Ue.yM.RATE_LIMITED||"run_inference_novel_tokens"!==t?.kind||void 0===t.retryAfterMs)return;const r=Number(t.retryAfterMs);return Number.isFinite(r)&&r>=0?r:void 0}var Dt=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Ot=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Ft=(0,d.h)("@anysphere/agent-client:exec-controller");class Nt extends Error{constructor(e){super(e),this.name="LostConnection"}}class Lt{constructor(e,t,r,n){this.serverStream=e,this.clientStream=t,this.controlledExecManager=r,this.checkpointStoreWaits=n}async run(e){const t={stack:[],error:void 0,hasError:!1};try{Dt(t,(0,D.VI)(e.withName("ClientExecController.run")),!1);const r=[],n=t=>{if((0,ve.isMessage)(t,p.Nv))this.controlledExecManager.handleControlMessage(t);else{const n=this.execute(e,t);n.catch((()=>{})),r.push(n)}};let o,s,i=!1;try{try{for await(const t of this.serverStream){const r=(0,ve.isMessage)(t,p.Nv)?void 0:Re(t),a=void 0===r?void 0:this.checkpointStoreWaits?.storedBefore(e,r);if(void 0===o&&void 0===a){n(t);continue}const c=(o??Promise.resolve()).then((async()=>{await a,(0,ve.isMessage)(t,p.Nv)||!i&&!e.canceled?n(t):Ft.info(e,"Dropped an exec queued behind a checkpoint's store",{toolCallId:r})})).catch((e=>{s??={error:e}}));o=c,c.then((()=>{o===c&&(o=void 0)}))}}finally{i=!0}if(await o,void 0!==s)throw s.error;await Promise.all(r)}catch(e){if(e instanceof be.ConnectError&&"protocol error: missing EndStreamResponse"===e.rawMessage)throw new Nt(e.message);if(e instanceof be.ConnectError&&e.code===be.Code.Aborted){const t=e.cause;if(t instanceof Error&&"code"in t&&"string"==typeof t.code&&t.code.includes("ERR_STREAM_WRITE_AFTER_END"))throw new Nt(e.message)}else{if(e instanceof f.W2)throw new Nt(e.message);if(e instanceof be.ConnectError&&e.code===be.Code.Internal){const t=e.cause;if(t instanceof Error&&t.message.includes("NGHTTP2_PROTOCOL_ERROR"))throw new Nt(e.message)}}throw e}}catch(e){t.error=e,t.hasError=!0}finally{Ot(t)}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{let n,o;if(t.spanContext){const r=t.spanContext;n=(0,D.V5)({traceId:r.traceId,spanId:r.spanId,traceFlags:r.traceFlags??1},"exec.handle",e),o=(0,D.fU)(n)}else n=e;Dt(r,o?new D.r2(n,o):void 0,!1);const s=this.controlledExecManager.handle(n,t);for await(const e of s)await this.clientStream.write(e)}catch(e){r.error=e,r.hasError=!0}finally{Ot(r)}}}const jt=(0,d.h)("@anysphere/agent-client:stall-detector"),Ut=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,Bt={nal:"[NAL client stall detector]",local_loop:"[local-loop client stall detector]",module:"[module client stall detector]"},Wt=new Set(["http2","http1_sse","http1_poll","websocket"]);function Ht(e){return void 0===e?"unknown":Wt.has(e)?e:"other"}const qt=(0,h.Pu)("agent_client.stream.stall.count",{description:"Number of bidirectional stream stalls detected",labelNames:["activity_type","message_type","loop","transport_mode"]}),zt=(0,h.v5)("agent_client.stream.stall.duration_ms",{description:"Duration of stream stalls in milliseconds",labelNames:["activity_type","loop","transport_mode"]}),Gt=(0,h.Pu)("agent_client.stream.did_stall",{description:"Number of streams that experienced at least one stall",labelNames:["loop","transport_mode"]}),Vt=(0,h.Pu)("agent_client.stream.total",{description:"Total number of streams monitored",labelNames:["loop","transport_mode"]});class Kt{constructor(){this.handlers=new Map}track(e,t){return this.handlers.set(e,{name:e,state:"started",startedAt:Date.now()}),t.then((t=>{const r=this.handlers.get(e);return r&&(r.state="completed",r.endedAt=Date.now()),t})).catch((t=>{const r=this.handlers.get(e);throw r&&(r.state="errored",r.endedAt=Date.now(),r.error=t instanceof Error?t.message:String(t)),t}))}getHandlerStates(){const e=Date.now(),t={};for(const[r,n]of this.handlers)t[r]={state:n.state,durationMs:(n.endedAt??e)-n.startedAt,error:n.error};return t}}class Jt{constructor(e,t,r){this.lastActivityTime=performance.now(),this.lastMeaningfulActivityTime=performance.now(),this.hasLogged=!1,this.hasLoggedAdvisory=!1,this.hasLoggedHeartbeatOnly=!1,this.hasEverStalled=!1,this.paused=!1,this.disposed=!1,this.activityHistory=[],this.ctx=e,"number"==typeof t?(this.thresholdMs=t,this.advisoryThresholdMs=void 0,this.heartbeatOnlyThresholdMs=3*t,this.onStall=r,this.onStallCallback=void 0,this.handlerTracker=void 0,this.loop="nal",this.readTransportMode=void 0):(this.thresholdMs=t.thresholdMs,this.advisoryThresholdMs=t.advisoryThresholdMs,this.heartbeatOnlyThresholdMs=t.heartbeatOnlyThresholdMs??3*t.thresholdMs,this.onStall=t.onStall,this.onStallCallback=t.onStallCallback,this.handlerTracker=t.handlerTracker,this.loop=t.loop??"nal",this.readTransportMode=t.transportMode),this.logPrefix=Bt[this.loop],this.startTimer(),this.startAdvisoryTimer(),this.startHeartbeatOnlyTimer(),this.onCtxSignalAbort=()=>{this.trackActivity("ctx.signal","abort"),this.abortedAt=performance.now(),this.emitLifecycleLog(`${this.logPrefix} Stream aborted while stall detector active`,"aborted")},e.signal.addEventListener("abort",this.onCtxSignalAbort)}metricLabels(){return{loop:this.loop,transport_mode:Ht(this.readTransportMode?.())}}trackActivity(e,t){const r={type:e,messageType:t};this.lastActivity=r,"inbound_message"===e?this.lastInboundMessage=r:"outbound_write"===e&&(this.lastOutboundMessage=r);const n=this.activityHistory.at(-1);n?.type===e&&n.messageType===t?n.repeat=(n.repeat??1)+1:(this.activityHistory.push(r),this.activityHistory.length>10&&this.activityHistory.shift())}reset(e="inbound_message",t,r=!0){if(this.trackActivity(e,t),"inbound_message"===e){const e=this.hasLogged,t=this.hasLoggedAdvisory,n=this.hasLoggedHeartbeatOnly;e&&(this.hasLogged=!1,this.emitLogAndMetric()),n&&r&&(this.hasLoggedHeartbeatOnly=!1),t&&(this.hasLoggedAdvisory=!1),this.lastActivityTime=performance.now(),r&&(this.lastMeaningfulActivityTime=performance.now()),void 0===this.timer&&this.startTimer(),void 0===this.advisoryTimer&&this.startAdvisoryTimer(),r&&void 0===this.heartbeatOnlyTimer&&this.startHeartbeatOnlyTimer()}}onStreamEnded(){this.trackActivity("stream","ended"),this.streamEndedAt=performance.now()}onClientSentHeartbeat(){this.lastClientSentHeartbeatAt=performance.now()}onServerSentHeartbeat(){this.lastServerSentHeartbeatAt=performance.now()}setPaused(e){if(!this.disposed&&e!==this.paused&&(this.paused=e,!e)){const e=performance.now();this.lastActivityTime=e,this.lastMeaningfulActivityTime=e,void 0===this.timer&&this.startTimer(),void 0===this.advisoryTimer&&this.startAdvisoryTimer(),void 0===this.heartbeatOnlyTimer&&this.startHeartbeatOnlyTimer()}}restartedAfterLoopGap(e,t){const r=performance.now(),n=r-e;return!(n<5e3||t>=e||(this.reportLoopGap(n,r-t),this.lastActivityTime=r,this.lastMeaningfulActivityTime=r,0))}reportLoopGap(e,t){try{jt.info(this.ctx,`${this.logPrefix} Stall check ran late - the process was not running, its windows restart`,this.buildLogMetadata({late_ms:e,window_ms:t,stall_type:"loop_gap"}))}catch(e){console.error("Error in stall detection:",e)}}startTimer(){if(this.disposed||this.thresholdMs<=0||void 0!==this.timer)return;let e=0;const t=t=>{e=performance.now()+t,this.timer=setTimeout(r,t)},r=()=>{if(this.paused||this.restartedAfterLoopGap(e,this.lastActivityTime))return void t(this.thresholdMs);const r=this.thresholdMs-(performance.now()-this.lastActivityTime);if(r<=0)return this.timer=void 0,void this.onStallDetected("no_activity");t(r)};t(this.thresholdMs)}startAdvisoryTimer(){if(this.disposed||void 0===this.advisoryThresholdMs||this.advisoryThresholdMs<=0||void 0!==this.advisoryTimer)return;const e=this.advisoryThresholdMs;let t=0;const r=e=>{t=performance.now()+e,this.advisoryTimer=setTimeout(n,e)},n=()=>{if(this.paused||this.restartedAfterLoopGap(t,this.lastActivityTime))return void r(e);const n=e-(performance.now()-this.lastActivityTime);if(n<=0)return this.advisoryTimer=void 0,void this.onAdvisoryDetected();r(n)};r(e)}startHeartbeatOnlyTimer(){if(this.disposed||this.thresholdMs<=0||this.heartbeatOnlyThresholdMs<=0||void 0!==this.heartbeatOnlyTimer)return;let e=0;const t=t=>{e=performance.now()+t,this.heartbeatOnlyTimer=setTimeout(r,t)},r=()=>{if(this.paused||this.restartedAfterLoopGap(e,this.lastMeaningfulActivityTime))return void t(this.heartbeatOnlyThresholdMs);const r=this.heartbeatOnlyThresholdMs-(performance.now()-this.lastMeaningfulActivityTime);if(r<=0)return this.heartbeatOnlyTimer=void 0,void this.onStallDetected("heartbeat_only");t(r)};t(this.heartbeatOnlyThresholdMs)}buildLogMetadata(e){const t=this.ctx.get(On),r={...e};t?.modelDetails?.displayName&&(r.model_name=t.modelDetails.displayName);const n=performance.now();void 0!==this.abortedAt&&(r.aborted_ago_ms=n-this.abortedAt),void 0!==this.disposedAt&&(r.disposed_ago_ms=n-this.disposedAt),void 0!==this.lastClientSentHeartbeatAt&&(r.last_client_sent_heartbeat_ago_ms=n-this.lastClientSentHeartbeatAt),void 0!==this.lastServerSentHeartbeatAt&&(r.last_server_sent_heartbeat_ago_ms=n-this.lastServerSentHeartbeatAt),void 0!==this.streamEndedAt&&(r.stream_ended_ago_ms=n-this.streamEndedAt),this.lastInboundMessage&&(r.last_inbound_message_type=this.lastInboundMessage.messageType),this.lastOutboundMessage&&(r.last_outbound_message_type=this.lastOutboundMessage.messageType);const o=[];let s;for(let e=this.activityHistory.length-1;e>=0;e--){const{type:t,messageType:r,repeat:n}=this.activityHistory[e];s!==t&&(s?o.push(`[${t}]`):o.push(`[${t}] (MOST RECENT)`),s=t),o.push(`${r}${n?` (x${n})`:""}`)}return r.activities=o.join("\n"),{reqId:t?.requestId,loop:this.loop,stall:r}}onAdvisoryDetected(){if(this.hasLogged||this.hasLoggedAdvisory)return;if(void 0===this.advisoryThresholdMs||this.advisoryThresholdMs<=0)return;const e=performance.now()-this.lastActivityTime;e=this.heartbeatOnlyThresholdMs){if(this.hasLoggedHeartbeatOnly)return;this.hasLoggedHeartbeatOnly=!0,this.reportStall(e,n)}return}if(this.hasLogged)return;this.hasLogged=!0,this.hasLoggedAdvisory=!0;const t=performance.now()-this.lastActivityTime;this.reportStall(e,t)}reportStall(e,t){const r=this.lastActivity,n=this.lastInboundMessage,o=this.lastOutboundMessage,s=this.ctx.get(On);try{const i=this.buildLogMetadata({duration_ms:t,threshold_ms:"heartbeat_only"===e?this.heartbeatOnlyThresholdMs:this.thresholdMs,stall_type:e}),a="heartbeat_only"===e?`${this.logPrefix} Stream receiving heartbeats only - no meaningful data for threshold period`:`${this.logPrefix} Bidirectional stream stall detected - no activity for threshold period`;if(jt.warn(this.ctx,a,i),qt.increment(this.ctx,1,{activity_type:r?.type??"unknown",message_type:r?.messageType??"unknown",...this.metricLabels()}),this.hasEverStalled||(this.hasEverStalled=!0,Gt.increment(this.ctx,1,this.metricLabels())),this.onStallCallback){const t=performance.now(),i={type:e,lastActivityAgoMs:t-this.lastActivityTime,lastMeaningfulActivityAgoMs:t-this.lastMeaningfulActivityTime,lastActivityType:r?.messageType,lastInboundMessageType:n?.messageType,lastOutboundMessageType:o?.messageType,requestId:s?.requestId,modelName:s?.modelDetails?.displayName,streamEnded:void 0!==this.streamEndedAt,aborted:void 0!==this.abortedAt,lastServerHeartbeatAgoMs:void 0!==this.lastServerSentHeartbeatAt?t-this.lastServerSentHeartbeatAt:void 0,lastClientHeartbeatAgoMs:void 0!==this.lastClientSentHeartbeatAt?t-this.lastClientSentHeartbeatAt:void 0,thresholdMs:"heartbeat_only"===e?this.heartbeatOnlyThresholdMs:this.thresholdMs,handlers:this.handlerTracker?.getHandlerStates(),loop:this.loop};try{this.onStallCallback(i)}catch(e){console.error("Error in stall callback:",e)}}}catch(e){console.error("Error in stall detection:",e)}try{this.onStall?.(function(e){const t=new DOMException(`the stall detector cut the stream: ${e}`,"AbortError");return Object.defineProperty(t,"cursorStallCut",{value:!0}),t}("heartbeat_only"===e?`heartbeats alone for ${this.heartbeatOnlyThresholdMs} ms`:`no activity for ${this.thresholdMs} ms`))}catch(e){console.error("Error in onStall callback:",e)}}emitLifecycleLog(e,t){const r=performance.now()-this.lastActivityTime;try{const n=this.buildLogMetadata({duration_ms:r,event_type:t});jt.info(this.ctx,e,n)}catch(e){console.error("Error logging stream lifecycle:",e)}}emitLogAndMetric(){const e=performance.now()-this.lastActivityTime;this.emitLifecycleLog(`${this.logPrefix} Stream activity resumed after stall`,"recovered"),zt.histogram(this.ctx,e,{activity_type:this.lastActivity?.type??"unknown",...this.metricLabels()})}[Symbol.dispose](){this.disposed||Vt.increment(this.ctx,1,this.metricLabels()),this.disposed=!0,this.paused=!1,void 0!==this.timer&&(clearTimeout(this.timer),this.timer=void 0),void 0!==this.advisoryTimer&&(clearTimeout(this.advisoryTimer),this.advisoryTimer=void 0),void 0!==this.heartbeatOnlyTimer&&(clearTimeout(this.heartbeatOnlyTimer),this.heartbeatOnlyTimer=void 0),this.ctx.signal.removeEventListener("abort",this.onCtxSignalAbort),this.trackActivity("disposed","disposed"),this.disposedAt=performance.now(),this.emitLifecycleLog(`${this.logPrefix} Stream stall detector disposed`,"disposed")}}const Zt={now:()=>performance.now(),setTimeout(e,t){const r=setTimeout(e,t);return r.unref?.(),r},clearTimeout(e){clearTimeout(e)}},Xt=(0,h.v5)("agent_client.first_message.event_loop_max_lag_ms",{description:"Longest event-loop block between the network phase start and the first server message of a run's first attempt",labelNames:["loop","transport_mode","first_message_slow"]}),Qt=(0,h.v5)("agent_client.first_message.event_loop_total_lag_ms",{description:"Summed event-loop blocking between the network phase start and the first server message of a run's first attempt",labelNames:["loop","transport_mode","first_message_slow"]}),Yt=(0,h.v5)("agent_client.first_message.network_ms",{description:"Time from the network phase start to the first server message of a run's first attempt, on attempts that sampled event-loop lag",labelNames:["loop","transport_mode","first_message_slow"]});var er=r("../proto/dist/generated/agent/v1/ask_question_tool_pb.js"),tr=r("../proto/dist/generated/agent/v1/create_plan_tool_pb.js"),rr=r("../proto/dist/generated/agent/v1/pr_management_tool_pb.js"),nr=r("../proto/dist/generated/agent/v1/replace_env_tool_pb.js"),or=r("../proto/dist/generated/agent/v1/setup_vm_environment_tool_pb.js"),sr=r("../proto/dist/generated/agent/v1/connect_scm_tool_pb.js"),ir=r("../proto/dist/generated/agent/v1/generate_image_tool_pb.js"),ar=r("../proto/dist/generated/agent/v1/mcp_auth_tool_pb.js"),cr=r("../proto/dist/generated/agent/v1/switch_mode_tool_pb.js"),lr=r("../proto/dist/generated/agent/v1/web_fetch_tool_pb.js"),ur=r("../proto/dist/generated/agent/v1/web_search_tool_pb.js");class dr extends Error{constructor(e){super(`Deferred interaction response requested for query ${e.id} (${e.query.case??"unknown"})`),this.query=e,this.name="DeferredInteractionResponseError",Object.setPrototypeOf(this,new.target.prototype)}}const hr=e=>new c.Y5({id:e,result:{case:"webSearchRequestResponse",value:new ur.lI({result:{case:"approved",value:new ur.XJ}})}}),pr=(e,t)=>new c.Y5({id:e,result:{case:"webSearchRequestResponse",value:new ur.lI({result:{case:"rejected",value:new ur.yc({reason:t??""})}})}}),fr=e=>new c.Y5({id:e,result:{case:"webFetchRequestResponse",value:new lr.fS({result:{case:"approved",value:new lr.Hs}})}}),mr=(e,t)=>new c.Y5({id:e,result:{case:"webFetchRequestResponse",value:new lr.fS({result:{case:"rejected",value:new lr.m$({reason:t??""})}})}}),gr=(e,t)=>new c.Y5({id:e,result:{case:"askQuestionInteractionResponse",value:new c.zT({result:t})}}),wr=e=>new c.Y5({id:e,result:{case:"switchModeRequestResponse",value:new cr.w$({result:{case:"approved",value:new cr.q5}})}}),yr=(e,t)=>new c.Y5({id:e,result:{case:"switchModeRequestResponse",value:new cr.w$({result:{case:"rejected",value:new cr.rA({reason:t??""})}})}}),vr=(e,t)=>new c.Y5({id:e,result:{case:"createPlanRequestResponse",value:new tr.gz({result:t})}}),br=(e,t)=>new c.Y5({id:e,result:{case:"setupVmEnvironmentResult",value:t}}),Sr=(e,t)=>new c.Y5({id:e,result:{case:"replaceEnvResult",value:t}}),kr=(e,t)=>new c.Y5({id:e,result:{case:"prManagementResult",value:t}}),_r=e=>new c.Y5({id:e,result:{case:"mcpAuthRequestResponse",value:new ar.h({result:{case:"approved",value:new ar.D5}})}}),Cr=(e,t)=>new c.Y5({id:e,result:{case:"mcpAuthRequestResponse",value:new ar.h({result:{case:"rejected",value:new ar.OI({reason:t??"Authentication was rejected"})}})}}),Er=(e,t)=>new c.Y5({id:e,result:{case:"connectScmRequestResponse",value:new sr.qG({result:{case:"rejected",value:new sr.lB({reason:t??"Connecting GitHub was skipped"})}})}}),xr=(e,t)=>new c.Y5({id:e,result:{case:"generateImageRequestResponse",value:new ir.vW({result:{case:"approved",value:new ir.l3({description:t??""})}})}}),Pr=(e,t)=>new c.Y5({id:e,result:{case:"generateImageRequestResponse",value:new ir.vW({result:{case:"rejected",value:new ir.Uq({reason:t??""})}})}});class Rr extends Error{constructor(e,t={}){super(e),this.name="InteractionListenerStreamClosedError",this.cause=t.cause,Object.setPrototypeOf(this,new.target.prototype)}}Rr.telemetryName="InteractionListenerStreamClosedError";var Ir=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Tr=(0,d.h)("ClientInteractionController"),Ar=new Set(["askQuestionInteractionQuery","switchModeRequestQuery","mcpAuthRequestQuery","connectScmRequestQuery"]);class $r{constructor(e,t,r,n){this.interactionStream=e,this.interactionListener=t,this.queryResponseStream=r,this.stallSuspender=n,this.pendingHumanQueries=0}async run(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,D.VI)(e.withName("ClientInteractionController.run")),!1);e=r.ctx;let n,o=Promise.resolve();for await(const t of this.interactionStream){const r=()=>"interactionQuery"===t.case?this.handleInteractionQuery(e,t.value):this.handleInteractionUpdate(e,t.value);o=o.then(r).catch((r=>{Tr.error(e,"Error handling interaction message",r,{messageCase:t.case}),n??=r}))}if(await o,void 0!==n)throw n}catch(e){t.error=e,t.hasError=!0}finally{Ir(t)}}async handleInteractionUpdate(e,t){await this.interactionListener.sendUpdate(e,t)}handleInteractionQuery(e,t){const r=void 0!==t.query.case&&Ar.has(t.query.case);let n=!1;const o=()=>{r&&!n&&(n=!0,this.pendingHumanQueries--,0===this.pendingHumanQueries&&this.stallSuspender?.setPaused(!1))};r&&(this.pendingHumanQueries++,1===this.pendingHumanQueries&&this.stallSuspender?.setPaused(!0)),(async()=>this.interactionListener.query(e,t))().catch((r=>{const n=function(e,t){switch(e.query.case){case"webSearchRequestQuery":return pr(e.id,t);case"webFetchRequestQuery":return mr(e.id,t);case"askQuestionInteractionQuery":return gr(e.id,new er.tz({result:{case:"rejected",value:new er.ox({reason:t})}}));case"switchModeRequestQuery":return yr(e.id,t);case"createPlanRequestQuery":return vr(e.id,new tr.bK({result:{case:"error",value:new tr.iY({error:t})}}));case"setupVmEnvironmentArgs":return br(e.id,new or.r$({result:{case:"success",value:new or.JH({})}}));case"replaceEnvArgs":return Sr(e.id,new nr.dV({result:{case:"failure",value:new nr.uq({errorMessage:t,setupLogs:""})}}));case"prManagementRequestQuery":return kr(e.id,new rr.HL({result:{case:"error",value:new rr.K$({error:t})}}));case"mcpAuthRequestQuery":return Cr(e.id,t);case"connectScmRequestQuery":return Er(e.id,t);case"generateImageRequestQuery":return Pr(e.id,t);case void 0:return;default:return e.query}}(t,"The client could not show this request to the user");if(!(n instanceof c.Y5))throw r;return Tr.error(e,"Error handling interaction query; answering with a fail-closed response",{queryCase:t.query.case,error:r}),n})).then((e=>(o(),this.queryResponseStream.write(e)))).catch((t=>{Tr.error(e,"Error handling interaction query",t)})).finally(o)}}async function Mr(e,t){let r;try{r=await e(t.signal)}catch(e){if(t.isCanceled())throw new Ze("User aborted request");throw new Ke("Failed to mint LLM Gateway credential",{cause:e instanceof Error?e:void 0,requestId:t.requestId})}if(void 0===r)throw new Ke("LLM Gateway credential minter returned no credential",{requestId:t.requestId});if(""===r.bearerToken.trim())throw new Ke("LLM Gateway credential minter returned an empty bearer token",{requestId:t.requestId});return new c.Ibo({bearerToken:r.bearerToken})}const Dr=G("request-context-executor",(e=>new H(e,Q("requestContextArgs"),Y("requestContextResult"))),((e,t)=>{t.register(new A(e,te("requestContextArgs"),ee("requestContextResult")))}));var Or=r("../agent-kv/dist/serde.js"),Fr=r("../proto/dist/generated/agent/v1/request_context_exec_pb.js"),Nr=r("../utils/dist/promise-extras.js");const Lr=15728640,jr=(0,h.Pu)("agent_client.request_context_blob.prepared",{description:"Prepared RequestContext blob references"}),Ur=(0,h.v5)("agent_client.request_context_blob.bytes",{description:"Serialized RequestContext bytes staged by the client"}),Br=(0,h.v5)("agent_client.request_context_blob.preparation_ms",{description:"Time to hydrate, serialize, and hash RequestContext"});function Wr(e){switch(e.action.case){case"userMessageAction":case"subscriptionNotificationAction":case"resumeAction":case"executePlanAction":return e.action.value;default:return}}class Hr{constructor(e,t=62914560){this.parent=e,this.maxTransientBytes=t,this.transientBlobs=new Map,this.persistedBlobIds=new Set,this.transientBytes=0}seed(e,t){return this.seedAll([{blobId:e,blobData:t}])}seedAll(e){const t=new Map;for(const{blobId:r,blobData:n}of e)t.set((0,Or.nj)(r),n.byteLength);let r=this.transientBytes;for(const[e,n]of t)r-=this.transientBlobs.get(e)?.byteLength??0,r+=n;if(r>this.maxTransientBytes)return!1;for(const{blobId:t,blobData:r}of e)this.transientBlobs.set((0,Or.nj)(t),r);return this.transientBytes=r,!0}has(e){return this.transientBlobs.has((0,Or.nj)(e))}hasAll(e){return e.every((e=>this.has(e)))}async getBlob(e,t){const r=(0,Or.nj)(t),n=this.transientBlobs.get(r);return void 0===n?await this.parent.getBlob(e,t):n}async persistForRemoteRead(e,t){const r=(0,Or.nj)(t),n=this.transientBlobs.get(r);void 0===n||this.persistedBlobIds.has(r)||(await(0,Nr.O$)((()=>this.parent.setBlob(e,t,n)),2),this.persistedBlobIds.add(r))}async setBlob(e,t,r){await this.parent.setBlob(e,t,r)}async setBlobLocallyOnly(e,t,r){await this.parent.setBlobLocallyOnly(e,t,r)}async flush(e){await this.parent.flush(e)}}async function qr({ctx:e,action:t,resources:r,blobStore:n,mode:o,maxBlobBytes:s,maxInlineDynamicBytes:i=1048576,notesSessionId:a}){const c=performance.now(),l=Wr(t);if(void 0===l)return{kind:"not_applicable"};if("legacy"===o)return t.requestContextParts=void 0,{kind:"legacy"};if(void 0!==t.requestContextParts){const e=void 0===(u=t.requestContextParts)?[]:[u.rulesBlobId,u.skillsBlobId,u.subagentsBlobId,u.mcpsBlobId],r=void 0!==l.requestContext,s=e.length>0&&n.hasAll(e);if(r||s){const e=t.requestContextParts;return"ref_only"===o&&r&&s&&void 0!==e?.dynamicContext&&(l.requestContext=void 0),{kind:"already_prepared"}}}var u;t.requestContextParts=void 0;const d=void 0===l.requestContext,h=l.requestContext??await async function({ctx:e,resources:t,notesSessionId:r}){const n=t.get(Dr),o=await n.execute(e,new Fr._K({notesSessionId:r})),s="success"===o.result.case?o.result.value.requestContext:void 0;if(void 0===s)throw new Error(`Failed to compute request context: ${o.result.case}`);return s}({ctx:e,resources:r,notesSessionId:a}),p=Math.min(Math.max(0,s),Lr),f=await async function({requestContext:e,mode:t,maxBlobBytes:r,maxInlineDynamicBytes:n}){const o=function(e){const t=e.clone();return t.rules=[],t.nonFileRules=[],t.cloudRule=void 0,t.agentSkills=[],t.skillOptions=void 0,t.customSubagents=[],t.tools=[],t.mcpInstructions=[],t.mcpFileSystemOptions=void 0,t.mcpMetaToolOptions=void 0,{dynamicContext:t,rules:new Fr.T3({rules:e.rules.map((e=>e.clone())),nonFileRules:e.nonFileRules.map((e=>e.clone())),cloudRule:e.cloudRule}),skills:new Fr.CB({agentSkills:e.agentSkills.map((e=>e.clone())),skillOptions:e.skillOptions?.clone()}),subagents:new Fr.yb({customSubagents:e.customSubagents.map((e=>e.clone()))}),mcps:new Fr.vB({tools:e.tools.map((e=>e.clone())),mcpInstructions:e.mcpInstructions.map((e=>e.clone())),mcpFileSystemOptions:e.mcpFileSystemOptions?.clone(),mcpMetaToolOptions:e.mcpMetaToolOptions?.clone()})}}(e),s="ref_only"===t?o.dynamicContext.toBinary().byteLength:void 0;if(void 0!==s&&s>n)return;const i=o.rules.toBinary(),a=o.skills.toBinary(),c=o.subagents.toBinary(),l=o.mcps.toBinary(),u=i.byteLength+a.byteLength+c.byteLength+l.byteLength;if(u>r)return;const[d,h,p,f]=await Promise.all([(0,oe.Bk)(i),(0,oe.Bk)(a),(0,oe.Bk)(c),(0,oe.Bk)(l)]),m=[{blobId:d,blobData:i},{blobId:h,blobData:a},{blobId:p,blobData:c},{blobId:f,blobData:l}],g=new Fr.sG({rulesBlobId:d,rulesByteLength:i.byteLength,skillsBlobId:h,skillsByteLength:a.byteLength,subagentsBlobId:p,subagentsByteLength:c.byteLength,mcpsBlobId:f,mcpsByteLength:l.byteLength,dynamicContext:"ref_only"===t?o.dynamicContext:void 0});if("dual"===t)return{kind:"dual",inlineContext:e,byteLength:u,parts:g};if(void 0===s)throw new Error("ref_only request context did not measure dynamic bytes");return{kind:"ref_only",stagedBlobs:m,byteLength:u,parts:g,dynamicByteLength:s}}({requestContext:h,mode:o,maxBlobBytes:p,maxInlineDynamicBytes:Math.min(Math.max(0,i),p)});if(void 0===f)return l.requestContext=h,t.requestContextParts=void 0,jr.increment(e,1,{mode:o,outcome:"oversized"}),{kind:"oversized"};if("ref_only"===f.kind&&!n.seedAll(f.stagedBlobs))return l.requestContext=h,t.requestContextParts=void 0,jr.increment(e,1,{mode:o,outcome:"transient_budget_exceeded"}),{kind:"transient_budget_exceeded"};l.requestContext="dual"===f.kind?f.inlineContext:void 0,t.requestContextParts=f.parts;const m=f.byteLength;return jr.increment(e,1,{mode:o,outcome:d?"hydrated":"inline"}),Ur.histogram(e,m,{mode:o}),Br.histogram(e,performance.now()-c,{mode:o}),{kind:"prepared",byteLength:m,hydrated:d,rulesByteLength:f.parts.rulesByteLength,skillsByteLength:f.parts.skillsByteLength,subagentsByteLength:f.parts.subagentsByteLength,mcpsByteLength:f.parts.mcpsByteLength,dynamicByteLength:"ref_only"===f.kind?f.dynamicByteLength:void 0}}function zr(e){return Object.keys(e.fileContents).length>0}function Gr(e,t){return Object.assign(new(e.getType()),e,t)}function Vr(e){return Gr(e,{fileContents:{}})}function Kr(e){for(const[t]of e.entries())if(t.symbol===Dr.symbol)return e.get(Dr)}var Jr=r("../proto/dist/generated/agent/v1/cursor_rules_pb.js");const Zr=102400;function Xr(e){return"AGENTS.md"===e||"CLAUDE.md"===e||"CLAUDE.local.md"===e}function Qr({content:e,filename:t}){return Buffer.byteLength(e,"utf8")>Zr?function({content:e,filename:t}){const r=Buffer.from(e,"utf8");let n=Zr;for(;128==(192&r.readUInt8(n));)n--;const o=`[truncated: ${t} is ${Math.round(r.length/1024)} KB; only the first 100 KB is included]`;return`${r.subarray(0,n).toString("utf8")}\n\n${o}`}({content:e,filename:t}):e}function Yr(e){const t=/^\s*("(?:[^"\\]|\\.)*"|'(?:[^']|'')*')\s+#/.exec(e);return null!==t?t[1]:/^\s*["']/.test(e)?e.trim():e.replace(/\s#.*$/,"").trim()}function en(e,t){return"description"===e?t.trim():Yr(t)}function tn(e){const t=e.trim();return"true"===t||"false"!==t&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t)}function rn(e){const t=e.trimStart();if(!t.startsWith("---"))return null;const r=t.split("---").filter(Boolean);if(r.length<2)return null;const n=r[0].trim(),o=r.slice(1).join("---").trim(),s={};let i=null,a=null;for(const e of n.split("\n")){const t=e.replace(/\r$/,"");if(/^\s*#/.test(t))continue;const r=t.match(/^\s+-\s+(.*)$/);if(r&&a){let e=Yr(r[1]);(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1));const t=s[a];Array.isArray(t)&&t.push(e);continue}const n=t.startsWith(" ")||t.startsWith("\t");if(i&&n){const e=t.trim(),r=e.indexOf(":");if(-1===r)continue;const n=e.slice(0,r).trim(),o=Yr(e.slice(r+1)),c=tn(o),l=`${i}.${n}`;""===o?(s[l]=[],a=l):"metadata.environments"===l||"metadata.disabledEnvironments"===l||"metadata.scopedTo"===l?(s[l]=String(c).split(",").map((e=>e.trim())).filter(Boolean),a=null):(s[l]=c,a=null);continue}i=null,a=null;const o=t.indexOf(":");if(-1===o)continue;const c=t.slice(0,o).trim(),l=en(c,t.slice(o+1));if(""===l&&"metadata"===c){i=c;continue}if("globs"===c&&""===l){s.globs=[],a="globs";continue}const u=tn(l);s[c]="metadata.environments"!==c&&"metadata.disabledEnvironments"!==c&&"metadata.scopedTo"!==c?u:String(u).split(",").map((e=>e.trim())).filter(Boolean)}return{frontmatter:s,rawFrontmatter:`---\n${n}\n---`,body:o}}function nn(e){const t=e.replace(/\\/g,"/").replace(/^[A-Za-z]:/,(e=>e.toLowerCase())),r=[];for(const e of t.split("/"))""!==e&&"."!==e&&(".."!==e?r.push(e):r.pop());return`${t.startsWith("/")?"/":""}${r.join("/")}`}function on(e,t){return"/"===t?e.length>1:e.startsWith(`${t}/`)}const sn=[[".cursor","skills"],[".cursor","skills-cursor"],[".claude","skills"],[".claude","plugins"],[".codex","skills"],[".grok","skills"],[".agents","skills"],[".cursor","plugins"]];class an{constructor(){this.allowed=!1}observeHeaders(e){this.allowed="1"===e.get("x-cursor-lazy-rule-bodies")}isAllowed(){return this.allowed}}function cn(e){if("success"!==e.result.case)return e;const t=e.result.value,r=t.requestContext;if(void 0===r)return e;const n=function(e){const t=e.env?.workspacePaths??[];let r=!1;const n=e.rules.map((e=>{if(!function(e,t){if(!0===e.bodyOmitted||0===e.content.length||void 0!==e.parseError||e.source!==Jr.gv.UNSPECIFIED||void 0!==e.plugin||void 0!==e.marketplace||void 0!==e.pluginId||void 0!==e.marketplaceId)return!1;if(0===e.scopedTo.length&&0===e.frontmatter.length&&e.content.trimStart().startsWith("---"))return!1;const r=nn(e.fullPath),n=r.startsWith("/"),o=r.split("/").filter((e=>e.length>0)),s=o.at(-1);if(void 0===s||function(e){return"SKILL.md"===e.at(-1)||e.some(((t,r)=>sn.some((([n,o])=>t===n&&e[r+1]===o))))}(o))return!1;const i=t.map(nn);if(!i.some((e=>on(r,e))))return!1;const a=function(e,t){let r=e.length-1;for(let t=e.length-2;t>=0;t--)if(".cursor"===e[t]&&"rules"===e[t+1]){r=t;break}return`${t?"/":""}${e.slice(0,r).join("/")}`}(o,n),c=a!==`${n?"/":""}${o.slice(0,-1).join("/")}`,l=e.type?.type.case;return"fileGlobbed"===l?s.endsWith(".mdc")&&c:"global"===l&&!!(Xr(s)||s.endsWith(".mdc")&&c)&&!i.includes(a)&&i.some((e=>on(a,e)))}(e,t))return e;r=!0;const n=Object.assign(new(e.getType()),e);return n.content=e.content.split("\n").find((e=>e.trim().length>0))??"",n.bodyOmitted=!0,n}));return r?Object.assign(new(e.getType()),e,{rules:n}):e}(r);return n===r?e:new Fr._G({result:{case:"success",value:Object.assign(new(t.getType()),t,{requestContext:n})}})}function ln(e){return void 0!==e&&Number.isFinite(e)&&Number.isInteger(e)}function un(e,t){const{rulesByteLength:r,skillsByteLength:n}=e,{subagentsByteLength:o,mcpsByteLength:s}=e;if(!(ln(r)&&ln(n)&&ln(o)&&ln(s)))return;const i=t?.dynamicByteLength;return{bytes:r+n+o+s+(i??0),bytesSource:"blob_parts",rulesBytes:r,skillsBytes:n,mcpBytes:s,subagentsBytes:o,...ln(i)?{dynamicBytes:i}:{}}}const dn=["alpn_failure","poll_seqno_gap","append_fatal","http_464","http_404_unimplemented","socket_reset","stream_closed_early","idle_deadline","stall","other"],hn=/\bHTTP (\d{3})\b/;function pn(e){const t=e.message;return"string"==typeof t?t:""}function fn(e){return e instanceof Error&&("AbortError"===e.name||e.name===lt)}const mn={serverCap:3,transportCap:10},gn={alpn_failure:"server",poll_seqno_gap:"server",append_fatal:"by_signature",http_464:"server",http_404_unimplemented:"server",socket_reset:"transport",stream_closed_early:"server",idle_deadline:"server",stall:"transport",other:"server"};function wn(e){return{action:"retry",countAsServerError:!0,countAsTransportError:!1,transportFailureKind:e}}function yn(e,t,r){const n=r.attemptRequestId,o=!0===t.endless,s=r.retriesEnabled||o,i=(e,n)=>!o&&(e>=n||void 0!==t.sharedCap&&r.serverErrorRetries+r.transportErrorRetries>=t.sharedCap);let a=e instanceof ze?e:ut(e,{requestId:n});const c=a instanceof Ze&&("owner"===r.abortOrigin||function(e){const t=e.displayInfo?.errorCode;return void 0!==t&&tt.has(t)}(a)),l="stall_detector"===r.abortOrigin&&!c&&(a instanceof Ze||a instanceof Ge),u="owner"===r.abortOrigin&&a instanceof Ge&&$t(a),d=function(e,t,r){return t.stalled?"stall":t.userStop?"other":function(e,t={}){const r=function(e){const t=[],r=new Set;let n=e;for(;"object"==typeof n&&null!==n&&!r.has(n);)r.add(n),t.push(n),n="cause"in n?n.cause:void 0;return t}(e);if(r.some((e=>"cursorBidiAppendFatal"in e)))return"append_fatal";const n=r.map(pn),o=e=>n.some((t=>t.includes(e))),s=function(e){return wt(e)?.code}(e),i=void 0===t.transportMode;if(i&&s===be.Code.Unavailable&&o("ALPN protocol failed to negotiate"))return"alpn_failure";if((i||"http1_poll"===t.transportMode)&&s===be.Code.Unavailable&&o("Unexpected seqno"))return"poll_seqno_gap";const a=n.map((e=>hn.exec(e)?.[1])).find((e=>void 0!==e));return i&&s===be.Code.Unknown&&"464"===a?"http_464":i&&s===be.Code.Unimplemented&&"404"===a?"http_404_unimplemented":s===be.Code.DeadlineExceeded&&function(e){const t=gt(e);return void 0===t?void 0:ft(t)?.error}(e)===Ue.yM.TIMEOUT?"idle_deadline":i&&s===be.Code.Unknown&&o("unsupported content type null")?"stream_closed_early":Ct(e)||function(e){return e instanceof Error&&"isTransport"in e&&!0===e.isTransport}(e)||r.some(fn)?"socket_reset":"other"}(e,r)}(e,{stalled:l,userStop:c||u},{transportMode:r.attemptTransportMode}),h=(e,t={})=>({action:"throw",error:e,...t,transportFailureKind:d}),p=(e,n,{immediateFirstRetry:o})=>s?i(r.transportErrorRetries,t.transportCap)?h(e(),{countAsTransportError:!0}):function(e,t){return{action:"retry",countAsServerError:!1,countAsTransportError:!0,transportFailureKind:e,...t?{noBackoff:!0}:{}}}(d,o&&0===r.transportErrorRetries):h(n(),{countAsTransportError:!0}),f=()=>({cause:a.cause,requestId:n,transportErrorRetries:r.transportErrorRetries,connectCode:a.displayInfo?.connectCode});if(l){if(s&&void 0!==r.stallRetryElapsedMs&&r.stallRetryElapsedMs>=18e4)return h(Rt(f()),{countAsTransportError:!0});const e=p((()=>Rt(f())),(()=>Rt({...f(),transportErrorRetries:void 0})),{immediateFirstRetry:!1});return"retry"===e.action?{...e,stall:!0}:e}if(a instanceof Ze&&!c&&$t(a)&&(a=new Ge(a.message,{cause:a.cause,requestId:n,displayInfo:a.displayInfo,isTransport:!0})),u)return h(new Ze(a.message,{cause:a.cause,requestId:n,displayInfo:a.displayInfo}));if(!0===t.retryAllInference&&(a instanceof Ve||a instanceof Ke)&&function(e){const t=e.displayInfo?.inferenceRequestErrorType;return void 0!==t&&!at.some((e=>e===t))}(a))return i(r.serverErrorRetries,t.serverCap)?h(a):wn(d);if(a instanceof Ze||a instanceof Ve||a instanceof Ke)return h(a);const m=function(e){return Mt(e.displayInfo?.errorDetails)}(a);if(a instanceof Ge&&void 0!==m){const e=(r.rateLimitRetryElapsedMs??0)+m;return!s||!o&&e>3e5?h(a):{action:"retry",countAsServerError:!1,countAsTransportError:!1,transportFailureKind:d,retryAfterMs:m,rateLimit:!0}}if(a instanceof Ge&&(!0===a.isTransport||function(e,t){const r=gn[e];return"by_signature"===r?Ct(t):"transport"===r}(d,a)||"owner"!==r.abortOrigin&&$t(a))){const e=function(e){const t=e.displayInfo,r=t?.title,n=t?.detail;return r&&n?{...t,title:r,detail:n}:void 0}(a);return p((()=>function(e){const{cause:t,requestId:r,transportErrorRetries:n,connectCode:o,ownCopy:s}=e;if(void 0!==s)return new Ge(Et(n)?"Connection failed repeatedly":"Connection failed",{cause:t,requestId:r,displayInfo:{...s,isRetryable:!0,connectCode:o??s.connectCode}});const i=function(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){t.add(r);const e=dt(r)?yt(r):r.message;if(It.test(e))return e;r=r.cause}}(t),a=void 0===i?"Please check your network connection and try again.":"Please check your proxy settings and try again.";return Et(n)?new Ge("Connection failed repeatedly",{cause:t,requestId:r,displayInfo:{title:"Connection failed",detail:`${void 0===i?"":`${i}. `}The connection failed ${xt(n)} times. ${a}`,isRetryable:!0,connectCode:o}}):new Ge("Connection failed",{cause:t,requestId:r,displayInfo:{title:"Connection failed",detail:`${i??"The connection was interrupted"}. ${a}`,isRetryable:!0,connectCode:o}})}({...f(),...void 0===e?{}:{ownCopy:e}})),(()=>a),{immediateFirstRetry:!0})}return s?i(r.serverErrorRetries,t.serverCap)?h(function(e){const{classified:t,requestId:r,serverErrorRetries:n}=e,o=t.displayInfo;return new Ge(t.message,{cause:t.cause,requestId:r,displayInfo:{...o,title:o?.title||"Server error",detail:o?.detail||`The server failed ${xt(n)} times. Please try again, or contact support if the issue persists.`,isRetryable:!0}})}({classified:a,requestId:n,serverErrorRetries:r.serverErrorRetries})):wn(d):h(a)}var vn=r("../proto/dist/generated/agent/v1/mcp_pb.js");const bn=(0,b.cF)(Symbol("agentTransportTimingRecorder"),void 0),Sn=(0,d.h)("@anysphere/agent-client:turn-runner"),kn=1e3,_n=6e4,Cn=(0,h.Pu)("agent_client.turn.retry",{description:"Turn attempts retried by the turn runner",labelNames:["attempt","reason","loop"]});function En(e){return e<=1?"1":2===e?"2":e<=5?"3_5":"gt5"}function xn(e){return!0===e.stall?"stall":!0===e.rateLimit?"rate_limit":e.countAsTransportError?"transport":e.countAsServerError?"server":!0===e.immediate?"speculative":"other"}const Pn=new Set(["textDelta","thinkingDelta","thinkingCompleted","partialToolCall","toolCallDelta","toolCallStarted","toolCallCompleted","tokenDelta"]);function Rn(e){const{message:t}=e;return("textDelta"!==t.case||void 0===t.value||!("isServerNotice"in t.value)||!0!==t.value.isServerNotice)&&Pn.has(t.case??"")}async function In(e,t,r){await new Promise(((n,o)=>{if(t?.aborted)return void o(new Ze("Cancelled during backoff"));const s=new AbortController,i=setTimeout(a,e);function a(){clearTimeout(i),t?.removeEventListener("abort",c),s.abort(),n()}function c(){clearTimeout(i),s.abort(),o(new Ze("Cancelled during backoff"))}t?.addEventListener("abort",c,{once:!0});try{r?.(s.signal)?.then(a,(()=>{}))}catch{}}))}function Tn(e,t){return e.length===t.length&&e.every(((e,r)=>{const n=t[r];return void 0!==n&&e.byteLength===n.byteLength&&e.every(((e,t)=>e===n[t]))}))}function An(e){const{connectCode:t,connectCodeName:r,...n}=e;return void 0===r?n:{...n,connectCode:r}}async function $n(e){const{ctx:t,checkpointHandler:r,runOptions:n,requestId:o,hooks:s,cancellation:i}=e,a=e.originalRequestId??o;let l=kn;const u=async(r,o,s,i,a)=>{if(s||(l=kn),void 0!==e.backoff)return void await e.backoff(r,o,i.retryAfterMs);if(!0===i.rateLimit&&void 0!==i.retryAfterMs){const n=i.retryAfterMs+1e3*Math.random();return e.logging&&Sn.info(t,`[${e.logging.tag}] Waiting out a rate limit`,{attempt:r,retryAfterMs:i.retryAfterMs,selectedDelayMs:n}),void await In(n,o)}const c=s?function(e,t){const r=Math.min(3e5,3*e);return t??kn+(r-kn)*Math.random()}(l,n.fixedRetryDelayMs):function(e,t,r){const n=t?100:kn,o=r??Math.min(n*2**e,_n);return o+(void 0===r?.2*o*Math.random():0)}(r,n.isRunningInTest,n.fixedRetryDelayMs),u=function(e,t){if(void 0===t||t<=e)return e;const r=Math.min(t,_n),n=Math.min(r+.2*r*Math.random(),_n);return Math.max(e,n)}(c,i.retryAfterMs);u!==c&&e.logging&&Sn.info(t,`[${e.logging.tag}] Waiting for Retry-After`,{attempt:r,retryAfterMs:i.retryAfterMs,computedDelayMs:c,selectedDelayMs:u,endlessRetries:s}),s&&(l=c,e.logging&&Sn.info(t,`[${e.logging.tag}] Endless retry delay selected`,{selectedDelayMs:u,attempt:r,retryCategory:i.countAsServerError?"server":"transport",endlessRetries:s}));const{retryWake:d}=n;await In(u,o,void 0===d?void 0:e=>d({error:a,delayMs:u,waitEnded:e}))};let d,h,p,f,m,g,w=e.state,y=e.action,v=0,b=o,S=0,k=0,_=!1,C=0;const E=()=>{_&&(n.onConnectionStateChange?.({state:"connected"}),_=!1)},x=(e,t)=>()=>{e===v&&("progress"===t?m=!0:g=!0,E())},P=e=>({handleCheckpoint:async(t,n,o)=>{e===v&&(m=!0),await r.handleCheckpoint(t,n,o),e===v&&(d=n,h=o?.resumeEligibility??"eligible",E())},getLatestCheckpoint:()=>r.getLatestCheckpoint()});for(;;){if(t.canceled)throw i.toCancelledError(void 0,b);if(d=void 0,h=void 0,m=!1,g=!1,s.beginAttempt?.({attempt:v,originalRequestId:a}),v>0?(b=(0,ye.C)(),await(n.onRetryStarting?.(v,{actionCase:y.action.case,conversationState:w,isResume:"resumeAction"===y.action.case,attemptRequestId:b})),e.logging&&Sn.info(t,`[${e.logging.tag}] Retrying attempt ${v}`,{attempt:v,actionCase:y.action.case,requestId:b,originalRequestId:a}),"resumeAction"===y.action.case&&(await(n.onRetryResuming?.({checkpointState:w,nextAttempt:v,reason:"resume_action"})),e.logging&&Sn.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:v,reason:"resume_action"}))):(e.logging&&Sn.info(t,`[${e.logging.tag}] Initial request`,{attempt:v,actionCase:y.action.case,requestId:b}),!0===e.notifyInitialResume&&"resumeAction"===y.action.case&&(await(n.onRetryResuming?.({checkpointState:w,nextAttempt:v,reason:"resume_action"})),e.logging&&Sn.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:v,reason:"resume_action"}))),t.canceled)throw i.toCancelledError(void 0,b);try{return await s.runAttempt({state:w,action:y,checkpointHandler:P(v),attempt:v,attemptRequestId:b,notifyConnected:E,notifyApplicationProgress:x(v,"progress"),notifyApplicationActivity:x(v,"activity")}),E(),void(e.logging&&Sn.info(t,`[${e.logging.tag}] Request successful`,{attempt:v,actionCase:y.action.case,requestId:b,originalRequestId:a}))}catch(r){if(!0===i.shortCircuit?.(r))throw i.toCancelledError(r,b);const o=!0===n.endlessRetries?.(),E=e.nowMs?.()??Date.now();(m||g)&&(p=void 0,f=void 0);const x=void 0===p?void 0:E-p,P=void 0===f?void 0:E-f;let T=s.classify(r,{attempt:v,attemptRequestId:b,originalRequestId:a,serverErrorRetries:S,transportErrorRetries:k,stallRetryElapsedMs:x,rateLimitRetryElapsedMs:P,endlessRetries:o});if("retry"===T.action){const n=!("resumeAction"===y.action.case&&w.pendingToolCalls.length>0)&&("resumeAction"===y.action.case||!0===e.noProgressGuardCountsReplays&&v>0);void 0!==d?C=0:n&&m&&(C++,C>=2&&(e.logging&&Sn.warn(t,`[${e.logging.tag}] Resume attempts are streaming but not producing checkpoints; stopping automatic resume`,{noProgressResumeFailures:C,attempt:v,requestId:b,originalRequestId:a,errorName:r instanceof Error?r.name:typeof r}),T={action:"throw",error:new Ge("Agent turn stopped after repeated resume attempts made no progress",{cause:r instanceof Error?r:void 0,requestId:b,displayInfo:{title:"Agent stopped retrying",detail:"The connection was interrupted repeatedly without saving progress, so the agent stopped to avoid repeating the same work. Retry to continue from the last saved state.",isRetryable:!0}}),transportFailureKind:T.transportFailureKind}))}const A={...void 0===T.transportFailureKind?{}:{transportFailureKind:T.transportFailureKind},...void 0===e.loop?{}:{loop:e.loop}},$=e.logging?.diagnostics?.(r);if(e.logging){const e="retry"===T.action?`RETRY (countAsServerError=${T.countAsServerError}, countAsTransportError=${T.countAsTransportError})`:`THROW ${T.error.kind}`;Sn.warn(t,`[AGENT_ERROR_DIAGNOSTICS] requestId=${b} originalRequestId=${a} decision=${e}`,{decision:e,willRetry:"retry"===T.action,enableAgentRetries:n.enableAgentRetries??!1,endlessRetries:o,isRunningInTest:n.isRunningInTest??!1,serverErrorRetries:S,transportErrorRetries:k,attempt:v,requestId:b,originalRequestId:a,...A,...$})}if("throw"===T.action){if(0===v){const r={attempt:0,actionCase:y.action.case,error:T.error,requestId:b,originalRequestId:a,enableAgentRetries:!0===n.enableAgentRetries,endlessRetries:o,stallAborted:!1,abortSources:[]};try{await(n.onErrorNotRetried?.(s.buildNonRetriedErrorInfo?.(r)??r))}catch(r){e.logging&&Sn.warn(t,`[${e.logging.tag}] onErrorNotRetried callback failed`,{error:String(r),requestId:b,originalRequestId:a})}}throw e.logging&&Sn.warn(t,`[${e.logging.tag}] Error not retryable`,{...A,...$,attempt:v,actionCase:y.action.case,requestId:b,originalRequestId:a,errorName:T.error.name,...!0===e.logging.includeErrorObjects?{error:T.error}:{},serverErrorRetries:S,transportErrorRetries:k}),T.error}const M=v+1;if("ineligible_terminal_turn"===h)return void(e.logging&&Sn.warn(t,`[${e.logging.tag}] Terminal checkpoint received before retryable error; completing without automatic resume`,{errorName:r instanceof Error?r.name:typeof r,errorMessage:r instanceof Error?r.message:String(r)}));!0!==T.immediate&&(n.onConnectionStateChange?.({state:"reconnecting",attempt:M,trigger:{...A,...s.reconnectTrigger?.(r,T,{originalRequestId:a,failedAttemptRequestId:b,nextAttempt:M})??{originatingRequestId:a,attemptRequestId:b}}}),_=!0),T.countAsServerError&&S++,T.countAsTransportError&&k++,!0===T.stall?p??=E:p=void 0,!0===T.rateLimit?f??=E:f=void 0,v=M;try{Cn.increment(t,1,{attempt:En(M),reason:xn(T),loop:e.loop??"nal"})}catch{}void 0!==d&&(I=d,Tn((R=w).turns,I.turns)&&Tn(R.rootPromptMessagesJson,I.rootPromptMessagesJson)||(l=kn),w=d,y=new c.QFf({action:{case:"resumeAction",value:new c.qKo}})),s.onRetryCommitted?.(),!0===T.immediate||!0===T.noBackoff&&void 0===T.retryAfterMs||await u(v,t.signal,o,T,r)}}var R,I}var Mn=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Dn=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const On=(0,b.cF)(Symbol("agentStreamMetadata"),void 0),Fn=(0,d.h)("@anysphere/agent-client:abort"),Nn=(0,d.h)("@anysphere/agent-client:retry"),Ln=(0,d.h)("@anysphere/agent-client:request-context-blob");async function jn({ctx:e,action:t,resources:r,blobStore:n,options:o,source:s,transportMode:i,notifyBytes:a}){!0===o.omitRequestContextFileContents&&function(e){const t=Wr(e);if(void 0===t)return;const r=t.requestContext;void 0!==r&&zr(r)&&(t.requestContext=Vr(r));const n=e.requestContextParts,o=n?.dynamicContext;void 0!==n&&void 0!==o&&zr(o)&&(e.requestContextParts=Gr(n,{dynamicContext:Vr(o)}))}(t);try{const s=await qr({ctx:e,action:t,resources:r,blobStore:n,mode:i??o.requestContextBlobTransportMode??"legacy",maxBlobBytes:o.requestContextBlobMaxBytes??Lr,maxInlineDynamicBytes:o.requestContextDynamicInlineMaxBytes??1048576,notesSessionId:o.conversationId});if(!0===a){const e=function({prepared:e,parts:t}){return"prepared"===e.kind?un(e,{dynamicByteLength:e.dynamicByteLength}):"already_prepared"===e.kind&&void 0!==t?un(t):void 0}({prepared:s,parts:t.requestContextParts});void 0!==e&&o.onRequestContextBytes?.(e)}}catch(r){t.requestContextParts=void 0,Ln.warn(e,"Failed to prepare request context blob; using legacy fallback",{actionCase:t.action.case,errorName:r instanceof Error?r.name:typeof r,source:s})}}const Un=e=>{const t=[];switch(t.push(e.message.case),e.message.case){case"conversationAction":t.push(e.message.value.action.case);break;case"execClientMessage":case"execClientControlMessage":case"kvClientMessage":case"execServerMessage":case"execServerControlMessage":t.push(e.message.value.message.case);break;case"interactionResponse":t.push(e.message.value.result.case);break;case"interactionUpdate":switch(t.push(e.message.value.message.case),e.message.value.message.case){case"partialToolCall":case"toolCallCompleted":case"toolCallStarted":t.push(e.message.value.message.value.toolCall?.tool.case);break;case"toolCallDelta":t.push(e.message.value.message.value.toolCallDelta?.delta.case)}break;case"interactionQuery":t.push(e.message.value.query.case)}return t.filter((e=>void 0!==e)).join(":")};function Bn(e){if(e instanceof Error)return`${e.name}: ${e.message}`;if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e||"bigint"==typeof e)return String(e);if(null==e)return String(e);try{const t=JSON.stringify(e);return"string"==typeof t?t:"unserializable error"}catch{return"unserializable error"}}async function Wn(e,t,r){for await(const n of t)switch(n.event.case){case"stdout":await r.sendUpdate(e,l.shellOutputDelta({case:"stdout",value:new fe.o0({data:n.event.value.data})}));break;case"stderr":await r.sendUpdate(e,l.shellOutputDelta({case:"stderr",value:new fe.Db({data:n.event.value.data})}));break;case"exit":await r.sendUpdate(e,l.shellOutputDelta({case:"exit",value:new fe.vb({code:n.event.value.code,aborted:n.event.value.aborted})}))}}function Hn(e){return e instanceof Error?e.name:void 0}class qn{constructor(e,t,r={}){this.client=e,this.endpointUrl=t,this.options=r,this.hasStartedStream=!1}async run(e,t,r,n,o,s,i,a,c,l,d){const h={stack:[],error:void 0,hasError:!1};try{if(void 0!==d.maxSteps)throw new Je(d.maxSteps);const g=!0===d.omitRequestContextFileContents?function(e){const t=Kr(e);return void 0===t?e:new X(e,[K(Dr,{execute:async(e,r,n)=>function(e){if("success"!==e.result.case)return e;const t=e.result.value,r=t.requestContext;return void 0!==r&&zr(r)?new Fr._G({result:{case:"success",value:Gr(t,{requestContext:Vr(r)})}}):e}(await t.execute(e,r,n))})])}(s):s,w=!0===d.lazyFileScopedRuleBodies?new an:void 0,y=void 0===w?g:function(e,t){const r=Kr(e);return void 0===r?e:new X(e,[K(Dr,{execute:async(e,n,o)=>{const s=await r.execute(e,n,o);return void 0!==o?.execId&&t.isAllowed()?cn(s):s}})])}(g,w),v=void 0===w?d:{...d,onHeader:e=>{w.observeHeaders(e),d.onHeader?.(e)}},b=new Hr(i),S=d.generationUUID??(0,ye.C)(),k=new u,_=(m=k,p=o,f=e=>{m.observe(e.id)},{sendUpdate:(e,t)=>p.sendUpdate(e,t),query:(e,t)=>(f(t),p.query(e,t)),enqueuePostTurnEndedWork:p.enqueuePostTurnEndedWork?.bind(p),flushPostTurnEndedWork:p.flushPostTurnEndedWork?.bind(p)}),C={sources:[],abortReasonName:void 0,abortReasonMessage:void 0},E=e=>{const t=function(e){const t=gt(e);return void 0===t?void 0:qe(ft(t))}(e),r=C.sources.includes("stall_detector")||!0===t?.stallAborted,n=(o=C.sources).some((e=>"stall_detector"!==e))?"owner":o.includes("stall_detector")?"stall_detector":"none";var o;const s=function(e){const t={errorName:Hn(e)},r=wt(e);if(void 0===r)return t;const n=function(e){if(null!==e&&"object"==typeof e&&"cause"in e)return e.cause}(r),o=function(e){if(null===e||"object"!=typeof e||!("code"in e))return;const t=e.code;return"string"==typeof t||"number"==typeof t?t:void 0}(n),s=Hn(n);return{...t,underlyingConnectError:{code:r.code,codeName:be.Code[r.code],cause:void 0!==o||void 0!==s?{code:o,name:s}:void 0}}}(e),i=s.underlyingConnectError;return{relayed:t,stallAborted:r,abortOrigin:"none"===n&&r?"stall_detector":n,reading:void 0===t?{errorName:s.errorName,connectCode:i?.code,connectCodeName:i?.codeName,connectCause:i?.cause,abortSources:[...C.sources],abortReasonName:C.abortReasonName,...void 0===i?{}:{underlyingConnectError:i}}:{errorName:t.errorName,connectCode:t.connectCode,connectCodeName:t.connectCodeName,connectCause:t.connectCause,...(a=t.loop,"nal"===a||"local_loop"===a||"module"===a?{loop:t.loop}:{}),...void 0===t.transportMode?{}:{transportMode:t.transportMode}}};var a};let x=0,P=0;const R={networkPhaseStartedAt:performance.now()};try{d.onNetworkPhaseStart?.()}catch(t){Nn.warn(e,"onNetworkPhaseStart callback failed",{error:String(t)})}const I=Mn(h,(0,D.VI)(e.withName("networkPhase")),!1);e=I.ctx,await(0,D.MG)(I.span,(()=>$n({ctx:e,state:t,action:r,checkpointHandler:c,runOptions:d,requestId:S,loop:this.options.loop??"nal",notifyInitialResume:!0,logging:{...this.options.retryLogging??{tag:"nal_agent_retries",includeErrorObjects:!0},diagnostics:e=>{const{stallAborted:t,abortOrigin:r,reading:n}=E(e);return{stallAborted:t,abortOrigin:r,...An(n)}}},cancellation:{toCancelledError:()=>new Ze("Request cancelled")},hooks:{beginAttempt:()=>{C.sources=[],C.abortReasonName=void 0,C.abortReasonMessage=void 0,P=++x},runAttempt:async({state:t,action:r,checkpointHandler:o,attempt:s,attemptRequestId:i,notifyConnected:c,notifyApplicationProgress:u,notifyApplicationActivity:d})=>{const h=function(e,t,r){return{sendUpdate:async(n,o)=>{if(t===r())return e.sendUpdate(n,o);"toolCallCompleted"===o.message?.case&&Nn.warn(n,"nal.await_stall.stale_completion_dropped",{attemptGen:t,currentGen:r()})},query:async(n,o)=>{if(t!==r())throw new Ze("Stale query from previous attempt");return e.query(n,o)},enqueuePostTurnEndedWork:e.enqueuePostTurnEndedWork?t=>e.enqueuePostTurnEndedWork(t):void 0,flushPostTurnEndedWork:e.flushPostTurnEndedWork?t=>e.flushPostTurnEndedWork(t):void 0}}(_,P,(()=>x));await this.runInternal(e,t,r,n,h,y,b,a,o,l,v,i,S,k,C,c,u,d,s,R)},classify:(e,t)=>{const{abortOrigin:r,relayed:n}=E(e),o=yn(e,function(e,t,r=mn){const n=function(e){if(void 0!==e&&Number.isFinite(e))return Math.min(Math.max(Math.floor(e),1),100)-1}(e.maxRetries),o=void 0===n?r:{serverCap:n,transportCap:n};return{serverCap:o.serverCap,transportCap:!0===e.isRunningInTest?Math.min(o.transportCap,2):o.transportCap,...void 0===n?{}:{sharedCap:n},endless:t.endlessRetries,retryAllInference:!0===e.retryAllInferenceErrors}}(d,t),{...t,retriesEnabled:d.enableAgentRetries??!1,abortOrigin:r}),s=n?.transportFailureKind;return"string"==typeof(i=s)&&dn.includes(i)?{...o,transportFailureKind:s}:o;var i},buildNonRetriedErrorInfo:e=>({...e,enableAgentRetries:d.enableAgentRetries??!1,stallAborted:E(e.error).stallAborted,abortSources:[...C.sources],abortReasonName:C.abortReasonName,abortReasonMessage:C.abortReasonMessage}),reconnectTrigger:(e,t,r)=>{const{relayed:n,stallAborted:o,reading:s}=E(e),i=e instanceof ze?e:ut(e,{requestId:r.failedAttemptRequestId});return{errorClass:n?.errorName??i.name,connectCode:s.connectCode,connectCodeName:s.connectCodeName,errorCode:i.displayInfo?.errorCode,countAsServerError:t.countAsServerError,countAsTransportError:t.countAsTransportError,stallAborted:o,originatingRequestId:r.originalRequestId,attemptRequestId:r.failedAttemptRequestId,...void 0===s.transportMode?{}:{transportMode:s.transportMode},endpointUrl:this.endpointUrl}},onRetryCommitted:()=>a.reopen()}})))}catch(e){h.error=e,h.hasError=!0}finally{Dn(h)}var p,f,m}async runInternal(e,t,r,n,o,s,i,a,l,u,d,h,m,g,w,y,v,b,S,k,_="agent.request.attempt"){const C={stack:[],error:void 0,hasError:!1};try{const P=e;e=this.options.prepareAttemptContext?.(e,{attempt:S,attemptRequestId:h,originalRequestId:m,runOptions:d})??e;const R=Mn(C,(0,D.VI)(e.withName(_)),!1);R.span.setAttribute("agent.attempt",S),R.span.setAttribute("agent.request_id",h),R.span.setAttribute("agent.original_request_id",m),e=R.ctx,e=(0,D.Mf)(e,"agent.request_id",h),e=(e=(0,D.Mf)(e,"agent.original_request_id",m)).with(On,{requestId:h,rootParentRequestId:d.rootParentRequestId,modelDetails:n});const I=new Set(w.sources);let T=void 0!==w.abortReasonName||void 0!==w.abortReasonMessage;const A=(t,r)=>{if(I.has(t))return;I.add(t),w.sources=[...I];const n=(e=>{const t="string"==typeof e?.abortReasonName?e.abortReasonName:void 0,r="string"==typeof e?.abortReasonMessage?e.abortReasonMessage:void 0;if(void 0!==t||void 0!==r)return{abortReasonName:t,abortReasonMessage:r}})(r);T||void 0===n||(T=!0,w.abortReasonName=n.abortReasonName,w.abortReasonMessage=n.abortReasonMessage),Fn.error(e,"Agent client stream abort",new Error(t),{abortSource:t,requestId:h,conversationId:d.conversationId,...r??{}})};if(e.signal.aborted){const t=e.signal.reason;A("ctx_signal_abort",he(t))}else e.signal.addEventListener("abort",(()=>{const t=e.signal.reason;A("ctx_signal_abort",he(t))}),{once:!0});const[$,O]=e.withCancel();if(a.signal?.aborted){const e=a.signal?.reason;A("conversation_action_abort",he(e)),O()}else a.signal?.addEventListener("abort",(()=>{const e=a.signal?.reason;A("conversation_action_abort",he(e)),O()}),{once:!0});if(e.canceled||$.canceled){const t={ctxCanceled:e.canceled,softCancel:$.canceled};throw A("pre_run_cancel",t),new Ze("User aborted request")}const F=(0,D.VI)(e.withName("createControlledExecManager")),N=M.fromResources(s);F[Symbol.dispose]();const[L,j]=e.withCancel(),U=new Kt,{failThresholdMs:B,advisoryThresholdMs:W}=function(e,t){const r=Ut(e?.failTimeoutMs)??3e4,n=r>0&&!0!==t?.isRunningInTest?Math.max(r,2e4):r,o=Ut(e?.advisoryTimeoutMs);return{failThresholdMs:n,advisoryThresholdMs:void 0!==o&&o>0&&(n<=0||oH,onStall:e=>{A("stall_detector",{thresholdMs:B,advisoryThresholdMs:W}),j(e)},onStallCallback:d.onStall,handlerTracker:U}),!1);let z,G,V;const K=(0,Se.Jt)(),J=new f.F8(K,(e=>(q.reset("outbound_write",Un(e)),e))),Z=Mn(C,(0,D.VI)(e.withName("writeInitialRequest")),!1);let X;const Q=function(e){return new vn.Or({mcpTools:e.map((e=>({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?ve.Value.fromJson(e.inputSchema):void 0,outputSchemaJson:void 0!==e.outputSchema?JSON.stringify(e.outputSchema):void 0})))})}(u),Y=d.requestContextBlobTransportMode??"legacy",ee=0===S&&"userMessageAction"===r.action.case&&0===t.turns.length,te="ref_only"===Y&&ee?"dual":Y,[,ne]=await Promise.all([jn({ctx:e,action:r,resources:s,blobStore:i,options:d,source:"run_request",transportMode:te,notifyBytes:0===S}),void 0===d.mintLlmGatewayCredential?Promise.resolve(void 0):Mr(d.mintLlmGatewayCredential,{signal:$.signal,isCanceled:()=>$.canceled,requestId:h})]),oe={action:r,headers:d.headers??{}},se=this.options.decorateAttempt?.(oe,d)??oe,ie=new c.Mpn({conversationState:t,action:se.action,modelDetails:n,requestedModel:d.requestedModel,clientLlmGatewayCredential:ne,mcpTools:Q,conversationGroupId:d.conversationGroupId,conversationId:d.conversationId,agentSessionId:d.agentSessionId,mcpFileSystemOptions:d.mcpFileSystemOptions,customSystemPrompt:d.customSystemPrompt,systemPromptSpec:d.systemPromptSpec,harness:d.harness,computerUseCoordinateMode:d.computerUseCoordinateMode,subagentTypeName:d.subagentTypeName,excludeWorkspaceContext:d.excludeWorkspaceContext,devRawModelSlug:d.devRawModelSlug,selectedSubagentModels:d.selectedSubagentModels,subagentModelOverrides:d.subagentModelOverrides??[],selectedSubagentModelDetails:d.selectedSubagentModelsLegacy,clientSupportsInlineImages:d.clientSupportsInlineImages,clientSupportsPreviewCard:d.clientSupportsPreviewCard,startedAsNewProject:d.startedAsNewProject,firstProjectOnboarding:d.firstProjectOnboarding,clientSupportsSendToUser:d.clientSupportsSendToUser,clientSupportsRoutedModelUpdate:d.clientSupportsRoutedModelUpdate,emitModelCallUsage:d.emitModelCallUsage,canCreateCloudSubagents:d.canCreateCloudSubagents,suppressSubagentProgressUpdateTool:d.suppressSubagentProgressUpdateTool,transcriptParentConversationId:d.transcriptParentConversationId,runId:m,nextInteractionQueryId:g.peekNext(),voiceCallNotes:d.voiceCallNotes});if(X=J.write(new pe.KS({message:{case:"runRequest",value:ie}})),$.canceled){const t={ctxCanceled:e.canceled,softCancel:$.canceled};throw A("post_write_cancel",t),Z[Symbol.dispose](),new Ze("User aborted request")}const ae={...se.headers,"x-request-id":h,"x-original-request-id":m,...Oe(d),...Ne()};z=(0,D.VI)(e.withName("handshakeEstablishment")),z.span.setAttribute("handshake.firstStreamOnClient",!this.hasStartedStream),this.hasStartedStream=!0;const ce=function(e){return e?.get(bn)}(e)?.startTransportRun(),le=void 0===ce?z.ctx:function(e,t){return e.with(bn,t)}(z.ctx,ce),ue=0===S&&void 0!==d.onTtftBreakdown?k?.networkPhaseStartedAt:void 0;let me;const ge=void 0===ce&&void 0===ue?K:(E=K,x=()=>{me=performance.now(),ce?.markFirstRequestSent(me)},{[Symbol.asyncIterator](){const e=E[Symbol.asyncIterator]();let t=!1;const r={next:()=>(t||(t=!0,x()),e.next())};return void 0!==e.return&&(r.return=t=>e.return(t)),void 0!==e.throw&&(r.throw=t=>e.throw(t)),r}}),ye=this.client.run(le,ge,{signal:L.signal,headers:ae,onHeader:e=>{H=e.get("x-cursor-agent-transport-mode")??void 0,d.onHeader?.(e)},onNetworkStarted:()=>{void 0===G&&(G=performance.now(),0===S&&(V=function(e=Zt,t=25){let r,n=0,o=0,s=e.now()+t;const i=e=>{e<=0||(o+=e,e>n&&(n=e))},a=()=>{const r=e.now();i(r-s),s=r+t,c=e.setTimeout(a,t)};let c=e.setTimeout(a,t);return{stop:()=>(void 0===r&&(e.clearTimeout(c),i(e.now()-s),r={maxLagMs:n,totalLagMs:o}),r)}}()))}}),be=performance.now();let ke;const Ce=t=>{z&&(z.span.setAttribute("handshake.firstMessageHeartbeat",t),void 0!==G&&z.span.setAttribute("handshake.preNetworkMs",G-be),z[Symbol.dispose](),z=void 0),y();const r=performance.now();ke=r,d.onFirstMessage?.(r-be),void 0!==G&&(d.onFirstMessageNetwork?.(r-G),void 0!==V&&(function(e,t){const r={loop:t.loop??"nal",transport_mode:Ht(t.transportMode),first_message_slow:t.firstMessageNetworkMs>=1e3?"true":"false"};Xt.histogram(e,t.reading.maxLagMs,r),Qt.histogram(e,t.reading.totalLagMs,r),Yt.histogram(e,t.firstMessageNetworkMs,r)}(e,{loop:this.options.loop,transportMode:H,firstMessageNetworkMs:r-G,reading:V.stop()}),V=void 0))},xe=()=>{b(),d.onFirstNonHeartbeatResponse?.(performance.now()-be,S)},Re=d.onTtftBreakdown?e=>{const t=performance.now(),r=void 0===ue||void 0===me||"server"!==e.clock?void 0:function(e){const t=Math.min(e.firstRequestTakenAt,e.firstMessageAt);return{requestBuildMs:Math.max(0,e.transportRunCalledAt-e.networkPhaseStartedAt),connectMs:Math.max(0,t-e.transportRunCalledAt),roundTripMs:Math.max(0,e.firstMessageAt-t),firstByteToOutputMs:Math.max(0,e.firstOutputAt-e.firstMessageAt),firstOutputReceivedAtEpochMs:e.firstOutputAtEpochMs}}({networkPhaseStartedAt:ue,transportRunCalledAt:be,firstRequestTakenAt:me,firstMessageAt:ke??t,firstOutputAt:t,firstOutputAtEpochMs:Date.now()});d.onTtftBreakdown(void 0===r?e:{...e,transit:r},S)}:void 0,Ie=!0===this.options.execCheckpointGate?function(e,t,r,n={}){return $e.has(r.action.action.case)?async function*(e,t,r,n){const o=[];let s=0;const i=()=>o.flatMap((e=>void 0===e.toolCallId?[]:[e.toolCallId])),a=e=>{const t=[];for(;o.length>0;){const n=o[0];if(!e&&void 0!==n.toolCallId&&!r.has(n.toolCallId))break;t.push(n.message),o.shift()}return t.length>0&&o.length>0&&(s=n.now()),t},c=()=>{const e=o.filter((e=>"execServerControlMessage"===e.message.message.case)),t=o.filter((e=>"execServerControlMessage"!==e.message.message.case));return o.splice(0,o.length,...t),e.map((e=>e.message))},l=t[Symbol.asyncIterator]();let u=!0;try{for(;;){let t;try{t=await l.next()}catch(e){throw u=!1,yield*c(),e}if(!0===t.done)return u=!1,void(yield*c());const d=t.value,h=d.message;if("execServerMessage"!==h.case&&"execServerControlMessage"!==h.case)if("conversationCheckpointUpdate"!==h.case){if(yield d,o.length>0&&n.now()-s>=n.holdMs){Te.info(e,"No checkpoint named held tool calls on a stream still delivering: handed on as they came",{toolCallIds:i().join(", "),waitedMs:Math.round(n.now()-s)});for(const e of i())r.add(e);yield*a(!0)}}else{for(const e of Pe(h.value.pendingToolCalls))r.add(e);if(yield d,o.length>0){const t=Math.round(n.now()-s),r=a(!1);r.length>0&&Te.debug(e,"Handed held execs on after their checkpoint",{count:r.length,waitedMs:t}),yield*r}}else{const t="execServerMessage"===h.case?Me(h.value):void 0,i=void 0!==t&&!r.has(t);if(0===o.length&&!i){yield d;continue}if(0===o.length&&(s=n.now()),o.push({message:d,toolCallId:i?t:void 0}),i){Te.debug(e,"Held a tool call's exec for the checkpoint that names it",{toolCallId:t});try{n.onHeld?.(t)}catch(t){Te.warn(e,"onExecHeldForCheckpoint callback failed",{error:String(t)})}}}}}catch(e){if(u){u=!1;try{await(l.return?.())}catch{}}throw e}finally{o.length>0&&Te.info(e,"The stream ended before a checkpoint named held tool calls: dropped, never run",{toolCallIds:i().join(", ")}),u&&await(l.return?.())}}(e,t,Pe(r.state.pendingToolCalls),{holdMs:n.holdMs??5e3,now:n.now??(()=>performance.now()),onHeld:n.onHeld}):t}(e,ye,{action:se.action,state:t},void 0===this.options.onExecHeldForCheckpoint?{}:{onHeld:this.options.onExecHeldForCheckpoint}):ye,Ae=!0===this.options.execAfterCheckpointStored||!0===this.options.execCheckpointGate?new Ee(void 0===this.options.onExecHeldForCheckpointStore?{}:{onExecHeld:this.options.onExecHeldForCheckpointStore}):void 0,{interactionStream:De,execStream:Fe,checkpointStream:Le,kvStream:je,done:Ue}=function(e,t,r,n,o,s,i,a,c,l){const u=(0,Se.Jt)(),d=(0,Se.Jt)(),h=(0,Se.Jt)(),p=(0,Se.Jt)();let f=!1,m=!1,g=!1;return{interactionStream:u,execStream:d,checkpointStream:h,kvStream:p,done:async function(){let w,y,v=!1,b=!1;try{for await(const o of t){if(void 0!==o.ttftBreakdown){const t=o.ttftBreakdown;try{a?.({serverFirstTokenMs:t.serverFirstTokenMs,preStreamSetupMs:t.preStreamSetupMs,waitForFirstEventMs:t.waitForFirstEventMs,providerTtftMs:t.providerTtftMs,slowPoolWaitMs:t.slowPoolWaitMs,...void 0===t.clientPrepMs?{}:{clientPrepMs:t.clientPrepMs},...void 0===t.clientPrepLegs?{}:{clientPrepLegs:we(t.clientPrepLegs)},...void 0===t.preHandlerMs?{}:{preHandlerMs:t.preHandlerMs},clock:t.clientClock?"client":"server"})}catch(t){Nn.warn(e,"onTtftBreakdown callback failed",{error:String(t)})}}const t="interactionUpdate"===o.message.case&&"heartbeat"===o.message.value.message.case;if(f||(f=!0,n(t)),t)r.onServerSentHeartbeat(),r.reset("inbound_message","heartbeat");else{if(!m){m=!0;try{i?.()}catch(t){Nn.warn(e,"onFirstNonHeartbeatMessage callback failed",{error:String(t)})}}if(!g&&"interactionUpdate"===o.message.case&&Rn(o.message.value)){g=!0;try{l?.()}catch(t){Nn.warn(e,"onFirstModelOutput callback failed",{error:String(t)})}}r.reset("inbound_message",Un(o))}if("interactionUpdate"===o.message.case&&"turnEnded"===o.message.value.message.case&&(v=!0),"interactionUpdate"!==o.message.case&&"interactionQuery"!==o.message.case||await u.write(o.message).catch((()=>{})),"execServerMessage"!==o.message.case&&"execServerControlMessage"!==o.message.case||await d.write(o.message.value),"conversationCheckpointUpdate"===o.message.case){const e=v?"ineligible_terminal_turn":"eligible";"ineligible_terminal_turn"===e&&(b=!0);const t=c?.noteRouted(o.message.value);try{await h.write({checkpoint:o.message.value,metadata:{resumeEligibility:e},...void 0===t?{}:{onSettled:t}})}catch(e){throw t?.(),e}}"kvServerMessage"===o.message.case&&await p.write(o.message.value)}r.onStreamEnded()}catch(e){w=e}finally{if(y=w,v&&b&&void 0!==w&&!o?.aborted&&!s?.aborted&&function(e){const t=e instanceof ze?e:ut(e);return t instanceof Ge&&function(e){return!0===e.isTransport||(e.cause instanceof Error?kt(e.cause):_t(e.message))}(t)}(w)&&(Nn.debug(e,"Ignoring transport close after terminal agent stream",{caughtError:w instanceof Error?`${w.name}: ${w.message}`:String(w)}),r.onStreamEnded(),y=void 0),v||o?.aborted||s?.aborted){if(!v&&!o?.aborted){const t=`Stream ended without turnEnded, abort signals: signal.aborted=${o?.aborted}, parentSignal.aborted=${s?.aborted}; firstMessageFired=${f}`;Nn.warn(e,t)}}else{const t="Stream ended without turnEnded — connection likely dropped mid-stream";void 0===w?(Nn.warn(e,t),y=new Ge(t,{isTransport:!0})):w instanceof Error&&"[aborted] aborted"===w.message?(Nn.warn(e,`${t}; retrying caught [aborted] aborted error`),y=new Ge(t,{cause:w,isTransport:!0})):Nn.warn(e,`${t}; caught non-retriable stream error, rethrowing as-is`,{caughtError:Bn(w)})}u.close(),d.close(),h.close(),p.close()}if(void 0!==y)throw y}()}}(e,Ie,q,Ce,$.signal,e.signal,xe,Re,Ae,v);let Be;const We={handleCheckpoint:async(e,t,r)=>{await l.handleCheckpoint(e,t,r),Be=r?.resumeEligibility??"eligible"},getLatestCheckpoint:()=>l.getLatestCheckpoint()};Z[Symbol.dispose]();const He=5e3;let qe;const Ve=()=>{qe=setTimeout((()=>{J.write(new pe.KS({message:{case:"clientHeartbeat",value:new pe.kA}})).then((()=>q.onClientSentHeartbeat()),(()=>{})),Ve()}),He)},Je=()=>{void 0!==qe&&(clearTimeout(qe),qe=void 0)};Ve();try{let t;if("shellCommandAction"===r.action.case&&r.action.value.execId){const n=r.action.value,i=new fe.a({command:n.shellCommand?.command||"",parsingResult:new fe.HO,skipApproval:!0}),a=s.get(re).execute(e,i,{execId:n.execId}),c=new $r(De,o,new f.F8(J,(e=>new pe.KS({message:{case:"interactionResponse",value:e}}))),q);t={run:async e=>{await Promise.all([U.track("handleShellStream",Wn(e,a,o)),U.track("interactionController",c.run(e))])}}}else{const e=new $r(De,o,new f.F8(J,(e=>new pe.KS({message:{case:"interactionResponse",value:e}}))),q);t={run:async t=>{await U.track("interactionController",e.run(t))}}}void 0!==X&&await Promise.race([X,Ue.catch((()=>{}))]);const c=new f.F8(J,(e=>{if((0,ve.isMessage)(e,p.yT))return new pe.KS({message:{case:"execClientMessage",value:e}});if((0,ve.isMessage)(e,p.$Y))return new pe.KS({message:{case:"execClientControlMessage",value:e}});throw new Error(`Unknown exec message (type: ${(0,ve.isMessage)(e)?e.getType().typeName:typeof e})`)})),l=new Lt(Fe,c,N,Ae),S=new de(je,new f.F8(J,(e=>new pe.KS({message:{case:"kvClientMessage",value:e}}))),i,{beforeGetBlob:async(e,t)=>i.persistForRemoteRead(e,t)}),k=new _e(Le,We,e);let _,C;const E={promise:new Promise(((e,t)=>{_=e,C=t})),resolve:_,reject:C};$.canceled?(E.resolve(),De.close()):$.signal.addEventListener("abort",(()=>{E.resolve(),De.close()}),{once:!0}),l.run($).then(E.resolve).catch(E.reject);const x=Promise.allSettled([U.track("streamSplitter",Ue.finally((()=>{Je(),a.close(),c.close()}))),U.track("execHandler",E.promise),t.run(e),U.track("checkpointController",k.run()),U.track("kvHandler",S.run(e)),U.track("conversationActionManager",a.run(e,{write:async t=>{await jn({ctx:e,action:t,resources:s,blobStore:i,options:d,source:"queued_action"}),await J.write(new pe.KS({message:{case:"conversationAction",value:t}}))}}))]);let R,I;const T={promise:new Promise(((e,t)=>{R=e,I=t})),resolve:R,reject:I};x.then(T.resolve).catch(T.reject),e.canceled?T.reject(new Ze("User aborted request")):e.signal.addEventListener("abort",(()=>T.reject(new Ze("User aborted request"))),{once:!0});const A=()=>{e.signal.aborted?j():function(e){const t=e.lingerMs??6e3;return new Promise((r=>{let n=!1;const o=e=>{n||(n=!0,clearTimeout(s),r(e))},s=setTimeout((()=>o("linger_timed_out")),t);e.done.then((()=>o("stream_ended")),(()=>o("stream_ended")))}))}({done:Ue,lingerMs:d.softCancelLingerMs}).then((t=>{Nn.info(e,"Soft-cancel transport linger finished",{outcome:t,requestId:h}),j()}))};$.canceled?(A(),T.reject(new Ze("User aborted request"))):$.signal.addEventListener("abort",(()=>{A(),T.reject(new Ze("User aborted request"))}),{once:!0});const M=await T.promise,D=M[0],O=M[1],F=M[3],L=e=>e.reason instanceof Error?`${e.reason.name}: ${e.reason.message}`:String(e.reason);if("rejected"===F.status)throw new Ke("Checkpoint persistence failed",{cause:F.reason instanceof Error?F.reason:void 0,requestId:h,displayInfo:{title:"Checkpoint persistence failed",detail:L(F),isRetryable:!1}});const B="ineligible_terminal_turn"===Be;if(B){const t={..."rejected"===D.status?{streamSplitter:L(D)}:{},..."rejected"===O.status?{execHandler:L(O)}:{}};Object.keys(t).length>0&&Nn.debug(e,"Ignoring handler errors after terminal checkpoint",t)}if("rejected"===D.status&&!B)throw D.reason;if("rejected"===O.status&&!B)throw O.reason;$.canceled||await this.processUnprocessedMessages(P,a,We,n,o,s,i,u,d,h,m,g,w,q,y,v,b)}finally{Je(),V?.stop(),V=void 0,z&&(z[Symbol.dispose](),z=void 0)}}catch(e){C.error=e,C.hasError=!0}finally{Dn(C)}var E,x}async processUnprocessedMessages(e,t,r,n,o,s,i,a,l,u,d,h,p,f,m,g,w){if(!t.hasUnprocessedMessages())return;const y=t.getUnprocessedUserMessages(),v=r.getLatestCheckpoint();if(!v||0===y.length)return;const b=y[0];t.markMessageAsProcessed(b),t.resetStream(),f[Symbol.dispose]();const S=r.getLatestCheckpoint();try{await this.runInternal(e,v,new c.QFf({action:{case:"userMessageAction",value:new c.Vtf({userMessage:b})}}),n,o,s,i,t,r,a,l,u,d,h,p,m,g,w,0,void 0,"agent.request.queuedMessage")}catch(e){throw S===r.getLatestCheckpoint()&&t.requeueMessage(b),e}}}const zn="cursor-ide-browser",Gn="cursor-dev-control",Vn="custom-user-tools",Kn=new Set(["cursor-app-control","cursor-backend-control","cursor-browser-extension",zn,Gn,Vn,"fsd","cursor-subscriptions","cursor-cloud","suggestions","Cursor Slack Tools","Cursor Automation Tools"]);function Jn(e){return!Kn.has(e)}const Zn=new Set([Gn,zn]);function Xn(e){if(void 0!==e&&0!==Object.keys(e).length)try{return JSON.stringify(e)}catch{return}}function Qn(e){return{name:e.toolName,description:e.description,arguments:e.inputSchema,outputSchema:e.outputSchema,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId}}var Yn;function eo(e){return void 0===e||void 0===e.serverIdentifiers}function to(e){switch(e.kind){case"ready":return void 0===e.toolListError?"connected":"error";case"requires_authentication":return"needsAuth";case"error":return"error";default:return"loading"}}(0,b.cF)(Symbol("mcpHostFilledArguments"),[]),function(e){e.Snapshots="cursor_mcp_lease_snapshot_store",e.Status="cursor_mcp_lease_server_status",e.Settings="cursor_mcp_lease_settings",e.Providers="cursor_mcp_lease_providers",e.Unknown="cursor_mcp_lease_unknown"}(Yn||(Yn={}));const ro=G("mcp-executor",(e=>new H(e,Q("mcpArgs"),Y("mcpResult"))),((e,t)=>{t.register(new A(e,te("mcpArgs"),ee("mcpResult")))})),no=G("list-mcp-resources-executor",(e=>new H(e,Q("listMcpResourcesExecArgs"),Y("listMcpResourcesExecResult"))),((e,t)=>{t.register(new A(e,te("listMcpResourcesExecArgs"),ee("listMcpResourcesExecResult")))})),oo=G("read-mcp-resource-executor",(e=>new H(e,Q("readMcpResourceExecArgs"),Y("readMcpResourceExecResult"))),((e,t)=>{t.register(new A(e,te("readMcpResourceExecArgs"),ee("readMcpResourceExecResult")))})),so=G("mcp-state-executor",(e=>new H(e,Q("mcpStateExecArgs"),Y("mcpStateExecResult"))),((e,t)=>{t.register(new A(e,te("mcpStateExecArgs"),ee("mcpStateExecResult")))}));var io=r("../proto/dist/generated/agent/v1/subagent_exec_pb.js");(0,b.cF)(Symbol("pendingSubagentReplay"),void 0);class ao extends Error{constructor(e,t){super(e),this.name="SubagentHostError",this.agentId=t?.agentId,this.cause=t?.cause}}const co=G("subagent-executor",(e=>new H(e,Q("subagentArgs"),Y("subagentResult"))),((e,t)=>{t.register(new A(e,te("subagentArgs"),ee("subagentResult")))})),lo=G("subagent-await-executor",(e=>new H(e,Q("subagentAwaitArgs"),Y("subagentAwaitResult"))),((e,t)=>{t.register(new A(e,te("subagentAwaitArgs"),ee("subagentAwaitResult")))})),uo=G("force-background-subagent-executor",(e=>new H(e,Q("forceBackgroundSubagentArgs"),Y("forceBackgroundSubagentResult"))),((e,t)=>{t.register(new A(e,te("forceBackgroundSubagentArgs"),ee("forceBackgroundSubagentResult")))}));var ho=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/status.js"),po=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js");const fo=(0,be.createContextKey)(void 0,{description:"anysphere.callerContext"}),mo=(0,b.cF)(Symbol("context-rpc.expected_error"),void 0);function go(e,t,r){!0===t.get(mo)?.(r)?e?.setAttribute("rpc.expected_error",!0):(e?.recordException(yo(r)),e?.setStatus({code:ho.s.ERROR,message:r instanceof Error?r.message:"RPC call failed"})),e?.end()}function wo(e){return null!==e&&"object"==typeof e&&Symbol.asyncIterator in e}function yo(e){return e instanceof Error?e:new Error(String(e))}function vo(e,t,r){return{[Symbol.asyncIterator](){const n=e[Symbol.asyncIterator]();let o=!1;const s=e=>{o||(o=!0,e?(t?.recordException(yo(e)),t?.setStatus({code:ho.s.ERROR,message:e instanceof Error?e.message:"Stream failed"})):t?.setStatus({code:ho.s.OK}),t?.end(),r?.())};return{async next(){try{const e=await n.next();return e.done&&s(),e}catch(e){throw s(e),e}},return:async e=>(s(),n.return?n.return(e):{done:!0,value:void 0}),async throw(e){if(s(e),n.throw)return n.throw(e);throw e}}}}}function bo(...e){const t=new Headers;for(const r of e)r&&(r instanceof Headers?r:new Headers(r)).forEach(((e,r)=>{t.set(r,e)}));return t}function So(e,t){const{injectTraceHeaders:r=!0,extractHeaders:n}=t;return new Proxy(e,{get(e,o){const s=e[o];return"function"!=typeof s?s:(i,a,c={})=>{const l=(0,D.fR)(i.withName(`rpc.${String(o)}`),{kind:po.v.CLIENT,attributes:{"rpc.method":String(o),"rpc.system":"connect"}}),u=(0,D.fU)(l);let d;try{let o;if(r&&(o=function(e){const t=new Headers;try{const r=(0,D.fU)(e),n=r?.spanContext?.();if(n?.traceId&&n.spanId){const e=n.traceFlags??0,r=`00-${n.traceId}-${n.spanId}-${e.toString(16).padStart(2,"0")}`;t.set("traceparent",r),t.set("backend-traceparent",r),n.traceState&&t.set("tracestate",n.traceState.serialize())}}catch{}return t}(l)),n){const e=n(l);e&&(o=bo(o,e))}const i=bo(c.headers,o),{signal:p,cleanup:f}=!0===t.enableAbortSignal?function(e,t){if(void 0===t||t===e)return{signal:e};const r=new AbortController,n=()=>{r.abort(e.reason)},o=()=>{r.abort(t.reason)};e.addEventListener("abort",n,{once:!0}),t.addEventListener("abort",o,{once:!0}),e.aborted?n():t.aborted&&o();return{signal:r.signal,cleanup:()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",o)}}}(l.signal,c.signal):{signal:c.signal,cleanup:void 0};d=f;const m=(c.contextValues??(0,be.createContextValues)()).set(fo,l),g={...c,headers:i,signal:p,contextValues:m},w=s.call(e,a,g);return wo(w)?vo(w,u,d):null!==(h=w)&&"object"==typeof h&&"then"in h&&"function"==typeof h.then?Promise.resolve(w).then((e=>wo(e)?vo(e,u,d):(u?.setStatus({code:ho.s.OK}),u?.end(),d?.(),e))).catch((e=>{throw go(u,l,e),d?.(),e})):(u?.setStatus({code:ho.s.OK}),u?.end(),d?.(),w)}catch(e){throw go(u,l,e),d?.(),e}var h}}})}var ko=r("node:crypto"),_o=r("../utils/dist/workspace-paths.js");function Co(){return(0,s.join)(function(){const e=process.env.CURSOR_DATA_DIR;return e?.trim()?e:(0,s.join)((0,o.homedir)(),".cursor")}(),"projects")}function Eo(e){return(0,s.join)(Co(),(0,_o.r_)(e))}var xo=r("node:fs/promises"),Po=r("../../node_modules/.pnpm/lru-cache@11.2.5/node_modules/lru-cache/dist/esm/index.js"),Ro=r("node:fs");const Io="local";function To(e,t){return`${e}:task_progress:${t}`}function Ao(e){const t={};return"string"==typeof e.title&&e.title.trim().length>0&&(t.title=e.title),"string"==typeof e.cwd&&e.cwd.trim().length>0&&(t.cwd=e.cwd),"number"==typeof e.startTimeMs&&Number.isFinite(e.startTimeMs)&&e.startTimeMs>0&&(t.startTimeMs=String(Math.floor(e.startTimeMs))),Object.keys(t).length>0?t:void 0}function $o(e,t){e.hookApprovalRequirement=void 0!==t?new fe.In(t):void 0}function Mo(e){return e.hookApprovalRequirement}function Do(e){return e?.kind===fe.b.FORCE_PROMPT}function Oo(e){return!(!e.skipApproval||e.smartModeClassifierAllowed&&Do(e.hookApprovalRequirement))}var Fo=r("../proto/dist/generated/agent/v1/background_shell_exec_pb.js"),No=r("../shell-exec/dist/api/index.js"),Lo=r("./src/agent/native/tree-sitter.webpack.cjs"),jo=r("./src/agent/native/tree-sitter-bash.webpack.cjs");const Uo=function(e,t=console.warn){let r;return()=>{if(void 0!==r)return r;try{const t=e();t.setLanguage(jo),r=t}catch(e){if(!function(e){return"object"==typeof e&&null!==e&&"CURSOR_TREE_SITTER_STUBBED"===e.code}(e))throw e;r=null,t("shell-parser: tree-sitter natives are unavailable in this artifact; shell command analysis degrades to parsingFailed")}return r}}((()=>new Lo)),Bo=new Set(["file_redirect","heredoc_redirect","herestring_redirect","heredoc","here_string","redirect","redirection"]),Wo=new Set(["<",">",">>",">|","<>","<&",">&","&>","&>>"]);function Ho(e,t){if(null===e)return{legacy:{simpleCommands:[],hasInputRedirect:!1,hasOutputRedirect:!1},structured:{parsingFailed:!0,executableCommands:[],hasRedirects:!1,hasCommandSubstitution:!1,redirects:[]}};const r=e.parse(t),n=new WeakSet;let o=!1,s=!0;const i={simpleCommands:[],hasInputRedirect:!1,hasOutputRedirect:!1},a={parsingFailed:!1,executableCommands:[],hasRedirects:!1,hasCommandSubstitution:!1,redirects:[]},c=e=>{o=!0,a.hasRedirects=!0,s=s&&e},l=e=>{if(e&&/^\d+$/.test(e.text))return Number.parseInt(e.text,10)},u=()=>({fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}),d=(e,t)=>{const r=(e=>{const t=e.children,r=t.findIndex((e=>Wo.has(e.type)));if(-1!==r)return{operator:t[r]?.type??"",target:t.slice(r+1).find((e=>"comment"!==e.type))}})(e);if(!r)return!1;const{operator:n,target:o}=r,s=((e,t)=>{if("&>"===t||"&>>"===t)return[1,2];const r=(e=>l(e.children.find((e=>"file_descriptor"===e.type))))(e);return void 0!==r?[r]:t.startsWith("<")?[0]:[1]})(e,n),i=(e=>{if(e){if("word"===e.type)return 0===e.namedChildren.length?e.text:void 0;if("number"===e.type)return e.text;if("raw_string"===e.type){if(e.text.length<2)return;return e.text.slice(1,-1)}if("string"===e.type){const t=e.namedChildren;if(0===t.length||t.some((e=>"string_content"!==e.type)))return;return t.map((e=>e.text)).join("")}}})(o),c={operator:n,destinationFds:s,targetNodeType:o?.type??""};if(void 0!==i&&(c.targetText=i),a.redirects.push(c),">&"===n){const e=l(o),r=void 0===e?void 0:t.fdTargets.get(e);if(!(e=>"original-stdout"===e||"original-stderr"===e||"dev-null"===e)(r)){for(const e of s)t.fdTargets.set(e,"unsafe");return!1}for(const e of s)t.fdTargets.set(e,r);return!0}if("<&"===n){const e=l(o),r=void 0===e?void 0:t.fdTargets.get(e);if("dev-null"!==r){for(const e of s)t.fdTargets.set(e,"unsafe");return!1}for(const e of s)t.fdTargets.set(e,r);return!0}if(!(e=>{if(!e)return!1;if("word"===e.type)return"/dev/null"===e.text;if("raw_string"===e.type)return"'/dev/null'"===e.text;if("string"===e.type){const t=e.namedChildren;return 1===t.length&&"string_content"===t[0]?.type&&"/dev/null"===t[0].text}return!1})(o)){for(const e of s)t.fdTargets.set(e,"unsafe");return!1}for(const e of s)t.fdTargets.set(e,"dev-null");return!0},h=(e,t)=>{if(!n.has(e)){if(n.add(e),(e=>{var t;t=e.text,/(^|\s)[0-9]*<>/.test(t)||/(^|\s)[0-9]*>(\||&)?/.test(t)||/(^|\s)&>/.test(t)||/(^|\s)[0-9]+>&[0-9]+/.test(t))&&(i.hasOutputRedirect=!0),"heredoc_redirect"!==e.type&&"herestring_redirect"!==e.type||(i.hasInputRedirect=!0)})(e),"heredoc_redirect"===e.type){const{redirect:t,isAllowlistSafe:r}=(e=>{const t=(e=>{const t=e.parent;if("redirected_statement"!==t?.type)return;const r=t.children.find((e=>"command"===e.type)),n=r?.childForFieldName("name");return n?.text})(e),r=void 0!==t&&!(e=>{let t=e.parent;for(;t;){if("command_substitution"===t.type&&"string"!==t.parent?.type)return!0;t=t.parent}return!1})(e),n={operator:r?"<<":"",destinationFds:r?[0]:[],targetNodeType:e.type};return r&&(n.targetText=t),{redirect:n,isAllowlistSafe:r}})(e);return a.redirects.push(t),void c(r)}if("file_redirect"!==e.type)return a.redirects.push({operator:"",destinationFds:[],targetNodeType:e.type}),void c(!1);c(d(e,t))}};return function e(t){const r=t.type;if((e=>{const t=u();for(const r of e.children)Bo.has(r.type)&&h(r,t)})(t),Bo.has(r)&&!n.has(t)&&h(t,u()),"command"===r){const e=t.childForFieldName("name");if(null===e)a.parsingFailed=!0;else{i.simpleCommands.push(e.text);let r=e.text;const n=[];for(const e of function(e){const t=[],r=e.walk();if(r.gotoFirstChild())do{"argument"===r.currentFieldName&&t.push(r.currentNode)}while(r.gotoNextSibling());return t}(t))n.push({type:e.type,value:e.text}),r+=` ${e.text}`;a.executableCommands.push({name:e.text,args:n,fullText:r})}}if("command_name"===r||"simple_command"===r)if("command_name"!==r||i.simpleCommands.includes(t.text)){if("simple_command"===r){const e=t.firstNamedChild;e&&"command_name"===e.type?i.simpleCommands.includes(e.text)||i.simpleCommands.push(e.text):i.simpleCommands.push(t.text)}}else i.simpleCommands.push(t.text);"command_substitution"!==r&&"process_substitution"!==r||(a.hasCommandSubstitution=!0);for(const r of t.children)e(r)}(r.rootNode),o&&(a.allRedirectsAreDevNull=s),{legacy:i,structured:a}}function qo(e){return Ho(Uo(),e)}function zo(e,t){return t>0&&t=55296&&r<=56319)&&function(e){return e>=56320&&e<=57343}(e.charCodeAt(t));var r}function Go(e,t){return t>0?t>=e.length?e.length:Math.trunc(t):0}function Vo(e,t){const r=Go(e,t);return zo(e,r)?r-1:r}function Ko(e,t){const r=Go(e,t);return zo(e,r)?r+1:r}function Jo(e,t){return t>0?e.length<=t?e:e.slice(0,Vo(e,t)):""}function Zo(e,t){return t>0?e.length<=t?e:e.slice(Ko(e,e.length-Math.trunc(t))):""}let Xo,Qo;function Yo(e,t){Xo??=new TextEncoder,Qo??=new Uint8Array(65536);let r=0,n=0;for(;r{const t=(0,ts.o1)(e);try{return await(0,xo.realpath)(t)}catch{return t}},os=1048576,ss=52428800;var is=r("../proto/dist/generated/agent/v1/sandbox_pb.js");function as(e){if(!e)return;let t;return"allow"===e.default?t=is.h1.ALLOW:"deny"===e.default&&(t=is.h1.DENY),new is.RB({version:e.version,defaultAction:t,deny:e.deny??[],allow:e.allow??[],logging:e.logging?(r=e.logging,new is.Qq({decisionLogPath:r.decisionLogPath,logFormat:r.logFormat})):void 0});var r}function cs(e){const t=function(e){if(!e)return;const t={};if(1===e.version&&(t.version=1),void 0!==e.defaultAction)switch(e.defaultAction){case is.h1.ALLOW:t.default="allow";break;case is.h1.DENY:t.default="deny"}return e.deny&&e.deny.length>0&&(t.deny=e.deny),e.allow&&e.allow.length>0&&(t.allow=e.allow),e.logging&&(t.logging=function(e){const t={};return e.decisionLogPath&&(t.decisionLogPath=e.decisionLogPath),"jsonl"===e.logFormat&&(t.logFormat="jsonl"),t}(e.logging)),t}(e.networkPolicy);return t||(e.networkAccess?(0,No.T6)():(0,No.Po)())}function ls(e){switch(e){case"system":return is.Sz.SYSTEM;case"workspace":return is.Sz.WORKSPACE;default:return is.Sz.UNSPECIFIED}}function us(e){const t=function(e){switch(e){case is.Sz.SYSTEM:return"system";case is.Sz.WORKSPACE:return"workspace";case is.Sz.UNSPECIFIED:default:return}}(e.readBoundary),r=e.additionalReadPaths??[];return{readBoundary:t,additionalReadPaths:"workspace"===t&&r.length>0?r:void 0,privateTmp:e.privateTmp}}function ds(e){if(!e)return{type:"insecure_none"};switch(e.type){case is.vc.INSECURE_NONE:case is.vc.UNSPECIFIED:return{type:"insecure_none",allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies};case is.vc.WORKSPACE_READWRITE:return{type:"workspace_readwrite",networkPolicy:cs(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadwritePaths:e.additionalReadwritePaths,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict,...us(e)};case is.vc.WORKSPACE_READONLY:return{type:"workspace_readonly",networkPolicy:cs(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict,...us(e)};default:return{type:"insecure_none"}}}function hs(e){if(e)return"insecure_none"===e.type?new is.Mw({type:is.vc.INSECURE_NONE,allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies}):"workspace_readwrite"===e.type?new is.Mw({type:is.vc.WORKSPACE_READWRITE,networkAccess:(0,No.$b)(e.networkPolicy),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadwritePaths:e.additionalReadwritePaths??[],additionalReadonlyPaths:e.additionalReadonlyPaths??[],disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicy:as(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:ls(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[],privateTmp:e.privateTmp}):"workspace_readonly"===e.type?new is.Mw({type:is.vc.WORKSPACE_READONLY,networkAccess:(0,No.$b)(e.networkPolicy),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths??[],disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicy:as(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:ls(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[],privateTmp:e.privateTmp}):new is.Mw({type:is.vc.INSECURE_NONE})}function ps(e){return" "===e||"\t"===e||"\n"===e||"\r"===e||" "===e||"​"===e||"‌"===e||"‍"===e||"\ufeff"===e}function fs(e){let t="",r=!1;for(const n of e)ps(n)?r=!0:(r&&t.length>0&&(t+=" "),r=!1,t+=n);return t}function ms(e){if(0===e.length)return!1;for(let t=0;te.fullText))])]}const vs={a:"",b:"\b",e:"",E:"",f:"\f",n:"\n",r:"\r",t:"\t",v:"\v","\\":"\\","'":"'",'"':'"',"?":"?"};function bs(e){let t="",r="plain",n=0;for(;n=e.length){t+=o,n++;continue}const s=e[n+1],i=vs[s];if(void 0!==i){t+=i,n+=2;continue}const a="x"===s?e.slice(n+2).match(/^[0-9a-fA-F]{1,2}/)?.[0]:"u"===s?e.slice(n+2).match(/^[0-9a-fA-F]{1,4}/)?.[0]:"U"===s?e.slice(n+2).match(/^[0-9a-fA-F]{1,8}/)?.[0]:e.slice(n+1).match(/^[0-7]{1,3}/)?.[0],c="u"===s||"U"===s,l="x"===s||c?16:8;if(void 0!==a){const e=Number.parseInt(a,l);if(!c||e<=1114111){t+=c?String.fromCodePoint(e):String.fromCharCode(e),n+=a.length+(16===l?2:1);continue}}t+=s,n+=2}return fs(t)}function Ss({rule:e,command:t}){const r=fs(e).trim();return 0!==r.length&&(null!==function(e){const t=fs(e).trim();if(0===t.length)return"Rule cannot be empty";if(t.length>512)return"Rule cannot exceed 512 characters";if(ms(t))return"Rule cannot match every command; be more specific than wildcards alone";if(t.startsWith(":"))return"Colon rules need an executable before `:` (e.g. `aws:*s3 rm*`)";const r=gs(t);if(void 0!==r){const{executablePattern:e,argsPattern:t}=r;if(ms(e)&&(0===t.length||ms(t)))return"Rule cannot match every command; narrow the executable or argument pattern"}return null}(r)||[t.trim(),fs(t).trim(),bs(t).trim()].some((e=>function(e,t){const r=gs(e);if(void 0!==r){const{executablePattern:e,argsPattern:n}=r,o=t.indexOf(" "),s=-1===o?t:t.slice(0,o),i=-1===o?"":t.slice(o+1).trim();if((0,ws.T)(e,s)&&(0,ws.T)(n,i))return!0}return e.includes("*")?(0,ws.T)(e,t):t===e||t.startsWith(`${e} `)}(r,e))))}function ks({matchForms:e,blockedCommands:t}){const r=t.map((e=>e.trim())).filter((e=>e.length>0));if(0===r.length)return;const n=e.map((e=>e.trim())).filter((e=>e.length>0)),o=n.length>0?n:[""];for(const e of r)if(o.some((t=>Ss({rule:e,command:t}))))return e}function _s(e){return`Denied: this command was blocked by administrator policy (denylist rule: ${e}) and was not executed. It cannot be approved from this conversation; only a user can run it manually outside the agent. You may continue working on the task.`}function Cs({command:e,parsingResult:t,blockedCommands:r}){if(0===r.length)return;if(t.parsingFailed||0===t.executableCommands.length)return"Denied: this command could not be conclusively analyzed against your team's administrator command denylist, so it was blocked (fail-closed) and was not executed. It cannot be approved from this conversation; only a user can run it manually outside the agent. You may continue working on the task.";const n=ks({matchForms:ys({command:e,parsingResult:t}),blockedCommands:r});return void 0===n?void 0:_s(n)}var Es=r("../utils/dist/test-resets.js");const xs="CURSOR_FORCED_SHELL_EGRESS_NETWORK_DEFAULT",Ps="CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_DENY_DOMAINS",Rs=/\$\(|`|<\(|>\(/,Is=/[;&|]/;let Ts,As,$s,Ms;function Ds(){if(void 0===Ts){const e=(process.env.CURSOR_FORCED_SHELL_EGRESS??"").trim().toLowerCase();Ts=""!==e&&"0"!==e&&"false"!==e&&"off"!==e}return Ts}function Os(e){const t=(process.env[e]??"").trim();if(t)try{return new RegExp(t,"i"),t}catch(t){throw new Error(`[forced-egress] invalid regex in ${e}: ${String(t)}`)}}function Fs(e){return(process.env[e]??"").split(",").map((e=>e.trim())).filter((e=>e.length>0))}function Ns(e){const t=(process.env[e]??"").split(":").map((e=>e.trim())).filter((e=>e.length>0)),r=t.filter((e=>e.startsWith("/"))),n=t.length-r.length;return n>0&&console.error(`[forced-egress] ignoring ${n} non-absolute path(s) in ${e}.`),r}function Ls(){if(void 0===Ms){const e=(process.env[xs]??"").trim().toLowerCase();let t="deny";"allow"===e||"deny"===e?t=e:""!==e&&console.error(`[forced-egress] ignoring invalid value in ${xs} (expected "allow" or "deny"); using "deny".`);const r=Fs("CURSOR_FORCED_SHELL_EGRESS_DENY_DOMAINS"),n=(process.env[Ps]??"").trim();let o=r;"none"===n.toLowerCase()?o=[]:""!==n&&(o=Fs(Ps)),Ms={networkDefault:t,denyDomains:r,dependencyDenyDomains:o,allowDomains:Fs("CURSOR_FORCED_SHELL_EGRESS_ALLOW_DOMAINS"),writablePaths:Ns("CURSOR_FORCED_SHELL_EGRESS_WRITABLE_PATHS")}}return Ms}function js(e,t,r={}){const n=[Os(e),Os(t)].filter((e=>void 0!==e)).map((e=>`(?:${e})`));if(0===n.length)return null;const o=n.join("|"),s=r.anchorToExecutable?`^\\s*(?:[A-Za-z_][A-Za-z0-9_]*=[^\\s]*\\s+)*(?:${o})`:o;return new RegExp(s,"i")}function Us(e,t){const r=function(){const e=Ls();return{type:"workspace_readwrite",...e.writablePaths.length>0?{additionalReadwritePaths:e.writablePaths}:{},networkPolicy:{version:1,default:e.networkDefault,allow:["127.0.0.0/8","::1/128","localhost",...e.allowDomains],...e.denyDomains.length>0?{deny:e.denyDomains}:{}},networkPolicyStrict:!0,skipStatsigDefaults:!0,enableSharedBuildCache:!0}}(),n=(void 0===As&&(As=js("CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_DEPENDENCY_REGEX",{anchorToExecutable:!0})),As);if(null===n)return r;const o=t?.executableCommands??[];if(t?.parsingFailed||0===o.length)return r;if(Rs.test(e))return r;const s=(void 0===$s&&($s=js("CURSOR_FORCED_SHELL_EGRESS_SOURCE_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_SOURCE_REGEX")),$s);for(const e of o){const t=e.fullText?.trim()||e.name?.trim()||"";if(!t||s?.test(t)||Is.test(t))return r}return o.every((e=>n.test(e.fullText?.trim()||e.name?.trim()||"")))?function(){const e=Ls();return{type:"workspace_readwrite",...e.writablePaths.length>0?{additionalReadwritePaths:e.writablePaths}:{},networkPolicy:{version:1,default:"allow",...e.dependencyDenyDomains.length>0?{deny:e.dependencyDenyDomains}:{}},skipStatsigDefaults:!0,enableSharedBuildCache:!0}}():r}(0,Es.J)((function(){Ts=void 0,As=void 0,$s=void 0,Ms=void 0}));var Bs=r("../utils/dist/lru-cache.js");const Ws=["Desktop","Documents","Downloads","Music","Movies","Pictures","Library",".Trash"],Hs="/Volumes";function qs(e){const t=e.replace(/\/{2,}/g,"/");return t.length>1&&t.endsWith("/")?t.slice(0,-1):t}function zs(e,t){if("darwin"!==t.platform)return[];const r=qs(e),n=r.toLowerCase(),o=qs(t.homeDirectory),s="/"===r?1:r.split("/").length;return[...Ws.map((e=>`${o}/${e}`)),Hs].filter((e=>function(e,t){return e!==t&&e.startsWith(t.endsWith("/")?t:`${t}/`)}(e.toLowerCase(),n))).map((e=>{const t=e.split("/").slice(s).join("/");return`${"/"===r?"":r}/${t}`}))}var Gs=r("../utils/dist/safe-spawn-cwd.js"),Vs=r("node:util");const Ks=8388608;var Js=r("../../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/lib/index.js"),Zs=r("../../node_modules/.pnpm/jschardet@3.1.4/node_modules/jschardet/index.js");function Xs(e){let t=1,r=0;for(;;){const n=e.indexOf("\n",r);if(-1===n)return t;t++,r=n+1}}const Qs="utf8",Ys="utf8bom",ei="latin1",ti={"windows-1250":"cp1250","windows-1251":"cp1251","windows-1252":"cp1252","windows-1253":"cp1253","windows-1254":"cp1254","windows-1255":"cp1255","windows-1256":"cp1256","windows-1257":"cp1257","windows-1258":"cp1258","iso-8859-1":"iso88591","iso-8859-2":"iso88592","iso-8859-5":"iso88595","iso-8859-6":"iso88596","iso-8859-7":"iso88597","iso-8859-8":"iso88598","iso-8859-9":"iso88599","iso-8859-15":"iso885915","iso-8859-16":"iso885916",shift_jis:"shiftjis","euc-jp":"eucjp","euc-kr":"euckr","iso-2022-jp":"iso2022jp","iso-2022-kr":"iso2022kr",gb2312:"gb2312",gbk:"gbk",gb18030:"gb18030",big5:"big5","big5-hkscs":"big5hkscs","koi8-r":"koi8r","koi8-u":"koi8u",ibm855:"cp855",ibm866:"cp866",maccyrillic:"maccyrillic","x-mac-cyrillic":"maccyrillic","utf-16le":"utf16le","utf-16be":"utf16be","utf-32le":"utf32le","utf-32be":"utf32be",johab:"johab",cp949:"cp949",cp932:"cp932"};function ri(e){return ti[e]||e}function ni(e){return e.startsWith("\ufeff")?e.slice(1):e}function oi(e){const t=e.toLowerCase();return"latin-1"===t?ei:"utf-8"===t?Qs:"utf-8-bom"===t||"utf-8 bom"===t?Ys:t}function si(e){const t=[],r=[];let n=0;for(let o=e.indexOf("\n");-1!==o;o=e.indexOf("\n",n)){const s=13===e.charCodeAt(o-1);t.push(e.slice(n,s?o-1:o)),r.push(s?"\r\n":"\n"),n=o+1}return t.push(e.slice(n)),r.push(""),{lines:t,ends:r}}const ii=new Vs.TextDecoder("utf-8",{fatal:!1}),ai=new Vs.TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),ci="�";function li(e){return ii.decode(e)}function ui(e){let t=0,r=0,n=0,o=0;for(let s=0;s0?o--:n++}return r+=n,r>t}function di(e,t=1/0){let r=0,n=0;for(;r=194&&r<=223)n=2;else if(r>=224&&r<=239)n=3,224===r&&(o=160),237===r&&(s=159);else{if(!(r>=240&&r<=244))return 1;n=4,240===r&&(o=144),244===r&&(s=143)}let i=1;for(;i(1===i?s:191))break;i++}return i===n?void 0:i}function pi(e){return e<128?1:e<2048?2:e<65536?3:4}var fi;!function(e){e.CRLF="CRLF",e.LF="LF"}(fi||(fi={}));const mi=[".mp4",".webm",".mov",".avi",".mkv",".wmv",".flv",".m4v"],gi=new Set(mi),wi=new Vs.TextDecoder("utf-8",{fatal:!0}),yi=new Vs.TextDecoder("latin1"),vi=Buffer.from([239,187,191]),bi={utf16le:Buffer.from([255,254]),utf16be:Buffer.from([254,255]),utf32le:Buffer.from([255,254,0,0]),utf32be:Buffer.from([0,0,254,255])},Si=8192,ki="UTF-8",_i="windows-1252",Ci=/[^\u0000-\u007f\ufffd]/u,Ei=/(?:\p{Script=Cyrillic}\p{M}*){3,}/gu,xi=/(?:\p{Script=Greek}\p{M}*){3,}/gu,Pi=/(?:\p{Script=Hebrew}\p{M}*){3,}/gu,Ri=new Map([["windows-1251",Ei],["ISO-8859-5",Ei],["KOI8-R",Ei],["x-mac-cyrillic",Ei],["IBM866",Ei],["IBM855",Ei],["ISO-8859-7",xi],["windows-1253",xi],["windows-1255",Pi],["ISO-8859-8",Pi],["TIS-620",/(?:\p{Script=Thai}\p{M}*){3,}/gu]]),Ii=/\p{Script=Latin}\p{M}*[\p{Script=Cyrillic}\p{Script=Greek}\p{Script=Hebrew}\p{Script=Thai}]|[\p{Script=Cyrillic}\p{Script=Greek}\p{Script=Hebrew}\p{Script=Thai}]\p{M}*\p{Script=Latin}/u,Ti=/[\p{L}\p{M}]+/gu,Ai=String.raw`[\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF\u0152\u0153\u0160\u0161\u017D\u017E\u0178]`,$i=new RegExp(`[A-Za-z]${Ai}{1,2}(?!${Ai})|^${Ai}{1,2}[A-Za-z]`,"u"),Mi=new Map,Di=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".pdf",".zip",".tar",".gz",".exe",".dll",".so",".dylib",".bin",...mi]),Oi=/\.(png|jpg|jpeg|gif|webp|ico|bmp)$/i,Fi=new Set([".ps1",".psm1",".psd1"]),Ni=/[^\u0000-\u007f]/u;function Li(e){const t=e.toLowerCase(),r=t.lastIndexOf(".");return-1===r?"":t.substring(r)}function ji(e){const t=Li(e);return gi.has(t)}function Ui(e){const t=Li(e);return{encoding:"binary",lineEnding:fi.LF,isBinaryFile:!0,isImageFile:Oi.test(t),isVideoFile:gi.has(t)}}async function Bi(e,t){return(await Wi(e,t)).text}async function Wi(e,t){const{stamp:r,buf:n}=await async function(e){const t=await(0,xo.open)(e,"r");try{return{stamp:await t.stat(),buf:await t.readFile()}}finally{await t.close()}}(e),o=Gi(n);if(o.isBinaryFile)throw new Error("Binary file cannot be decoded as text");const s=ea(e,r);let i;i=t||s||o.encoding;const{text:a,encoding:c}=na(n,i),l=ni(a),u=c===Qs&&oa(n)?Ys:c;ta(e,r,u);const d=function(e,t){if(t===Ys)return oa(e);const r=bi[ri(oi(t))];return void 0!==r&&e.subarray(0,r.length).equals(r)}(n,u);if(o.lineEnding===fi.CRLF){const e=l.match(/\r\n/g)?.length??0,t=(l.match(/\n/g)?.length??0)-e;return{text:l.replaceAll("\r\n","\n"),encoding:u,bom:d,lineEnding:e>t?"CRLF":"LF"}}return{text:l,encoding:u,bom:d,lineEnding:"LF"}}async function Hi(e,t){if("binary"===t.encoding)return void Yi(e);let r;try{r=await(0,xo.stat)(e)}catch{return void Yi(e)}r.size===t.buffer.byteLength?ta(e,r,t.encoding):Yi(e)}async function qi(e,t,r,o){let s,i;try{s=r?await async function(e,t){try{return await zi(e)}catch{}const r=Li(e);if(Di.has(r))return Ui(e);try{return await async function(e){const t=new Map;let r=0;for await(const n of Xi(e)){if(r>=100)break;try{const e=await zi(n);if(!e.isBinaryFile){const r=`${e.encoding}:${e.lineEnding}`,n=t.get(r);if(n){if(n.count++,n.count>=3)return n.format}else t.set(r,{format:e,count:1})}r++}catch(e){}}let n;for(const e of t.values())(!n||e.count>n.count)&&(n=e);return n?n.format:Qi()}(t)}catch{return Qi()}}(e,r):await zi(e)}catch{const t=Li(e);s=Di.has(t)?Ui(e):Qi()}const a=()=>i??=async function(e){try{const t=await(0,xo.stat)(e);if(!t.isFile()||t.size>Ks)return;return await(0,xo.readFile)(e)}catch{return}}(e),c=ea(e,await async function(e){try{return await(0,xo.stat)(e)}catch{return}}(e));let l;if(!s.isBinaryFile){let r;o?r=oi(o):c?r=oi(c):(r=oi(s.encoding),r===Ys||Js.encodingExists(ri(r))||(r=Qs),r!==Qs&&r!==Ys||(r=await async function(e,t){const r=await t();return void 0===r||(0,n.isUtf8)(r)?e:ra(r).encoding===ei?ei:e}(r,a))),r===Qs&&!o&&function(e,t){return"win32"===process.platform&&Fi.has(Li(e))&&Ni.test(t)&&!t.startsWith("#!")}(e,t)&&(await async function(e){try{return await(0,xo.stat)(e),!1}catch(e){return e instanceof Error&&"code"in e&&"ENOENT"===e.code}}(e)||await async function(e){const t=await e();return void 0!==t&&(0,n.isAscii)(t)}(a))&&(r=Ys);const i=r===Ys||r===Qs&&!o&&await sa(e,vi),u=bi[ri(r)];i?l=vi:u&&await sa(e,u)&&(l=u),s={...s,encoding:i?Ys:r}}const u=Xs(t),d=t.includes("\r\n")?void 0:await async function(e,t){if(t.isBinaryFile)return;const r=await e();if(void 0===r||!r.includes(13))return;const n=ni(na(r,t.encoding).text);return function(e){let t=!1,r=!1;for(let n=e.indexOf("\n");-1!==n;n=e.indexOf("\n",n+1))if(13===e.charCodeAt(n-1)?t=!0:r=!0,t&&r)return!0;return!1}(n)?n:void 0}(a,s);if(void 0!==d?t=function({content:e,existing:t,defaultEnding:r}){const n=si(t),o=si(e),s=function({before:e,after:t}){const r=new Int32Array(t.length).fill(-1);let n=0;for(;n0&&i>0&&(s+1)*(i+1)<=4e6){const o=i+1,a=new Uint16Array((s+1)*o);for(let r=s-1;r>=0;r--)for(let s=i-1;s>=0;s--)a[r*o+s]=e[n+r]===t[n+s]?a[(r+1)*o+s+1]+1:Math.max(a[(r+1)*o+s],a[r*o+s+1]);for(let c=0,l=0;c=a[c*o+l+1]?c++:l++}let a=-1,c=-1;for(let n=0;n<=t.length;n++){const o=n===t.length?e.length:r[n];if(-1!==o){if(o-a==n-c)for(let e=1;e50&&/^[A-Za-z0-9+/]*={0,2}$/.test(t))try{const e=Buffer.from(t,"base64");if(e.length>0){const r=Math.floor(.5*t.length);if(e.length>=r)return e}}catch{}return Buffer.from(e,"latin1")}(t);return{lines:u,buffer:e,format:s}}const h=l?ni(t):t,p=s.encoding===Ys?Qs:s.encoding,f=p===Qs?await async function(e,t){if(!t.includes(ci))return;const r=await e();return void 0===r?void 0:function(e,t){if(!e.includes(ci)||(0,n.isUtf8)(t))return;const r=function(e){const t=[];let r=0;for(const n of ai.decode(e)){const o=n.codePointAt(0)??0;if(65533!==o){r+=pi(o);continue}const s=hi(e,r);void 0===s?(t.push(void 0),r+=3):(t.push(e.subarray(r,r+s)),r+=s)}return r===e.length?t:void 0}(t),o=e.split(ci);if(void 0===r||o.length-1!==r.length)return;const s=[];for(let e=0;e=Math.max(0,e.length-3);t--){const r=e[t];if(r<128)return e;if(r>=192){const n=r>=240?4:r>=224?3:2;return e.length-t=e.length);o+=2){if(0===e[o+1]){const r=e[o];(r>=32&&r<=126||9===r||10===r||13===r)&&t++}if(0===e[o]){const t=e[o+1];(t>=32&&t<=126||9===t||10===t||13===t)&&r++}}return t>.8*n?"UTF-16LE":r>.8*n?"UTF-16BE":null}(e)??function(e){if(e.length<8)return null;if(0===e[0]&&0===e[1]&&254===e[2]&&255===e[3])return"UTF-32BE";if(255===e[0]&&254===e[1]&&0===e[2]&&0===e[3])return"UTF-32LE";let t=0,r=0;const n=Math.min(50,Math.floor(e.length/4));for(let o=0;o<4*n&&!(o+3>=e.length);o+=4){if(0===e[o]&&0===e[o+1]&&0===e[o+2]){const r=e[o+3];(r>=32&&r<=126||9===r||10===r||13===r)&&t++}if(0===e[o+1]&&0===e[o+2]&&0===e[o+3]){const t=e[o];(t>=32&&t<=126||9===t||10===t||13===t)&&r++}}return t>.8*n?"UTF-32BE":r>.8*n?"UTF-32LE":null}(e);if(t)return{encoding:t,lineEnding:Ki(Js.decode(e.subarray(0,Si),ri(oi(t)))),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};if(!function(e){const t=Math.min(Si,e.length);if(0===t)return!0;for(let r=0;r=8&&137===r[0]&&80===r[1]&&78===r[2]&&71===r[3]&&13===r[4]&&10===r[5]&&26===r[6]&&10===r[7]||255===r[0]&&216===r[1]&&255===r[2]||r.length>=12&&82===r[0]&&73===r[1]&&70===r[2]&&70===r[3]&&87===r[8]&&69===r[9]&&66===r[10]&&80===r[11]||r.length>=6&&71===r[0]&&73===r[1]&&70===r[2]&&56===r[3]&&(55===r[4]||57===r[4])&&97===r[5])),isVideoFile:!1};var r,o,s;if((0,n.isUtf8)(e)&&(!e.includes(27)||!(0,n.isAscii)(e)))return{encoding:ki,lineEnding:Vi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};if(!(0,n.isUtf8)(e)&&(o=li(e),s=e.length,ui(o)||1024*di(o)<=s&&!Ci.test(o)))return{encoding:ki,lineEnding:Vi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};const i=Zs.detect(e);let a=i.confidence>.7?i.encoding:"utf-8";"ascii"===a&&(a="utf-8");const c=Ri.get(a);return void 0!==c&&(a=function(e,t,r){const n=ri(oi(t));if(!Js.encodingExists(n))return t;const o=Js.decode(e,n);return Ii.test(o)&&function(e,t,r){const n=t.match(r)?.length??0;let o=0;for(const[t]of Js.decode(e,_i).matchAll(Ti))$i.test(t)&&o++;return o>n}(e,o,r)?_i:t}(e,a,c)),a!==_i||function(e,t){const r=ri(oi(t));return!Js.getDecoder(r).write(e).includes(ci)}(e,a)||(a="utf-8"),{encoding:a??"utf-8",lineEnding:Vi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function Vi(e){let t=0,r=0;for(let n=0;n0&&13===e[n-1]?t++:r++);return Ji(t,r)}function Ki(e){const t=e.match(/\n/g)?.length??0,r=e.match(/\r\n/g)?.length??0;return Ji(r,t-r)}function Ji(e,t){return 0===e&&0===t?fi.LF:e/(e+t)*100>=5?fi.CRLF:fi.LF}async function Zi(e){const t=await(0,xo.open)(e,"r");try{const e=Buffer.allocUnsafe(Si),{bytesRead:r}=await t.read(e,0,Si,0);return e.subarray(0,r)}finally{await t.close()}}async function*Xi(e){const t=new Set(["node_modules",".git",".svn",".hg","dist","build","out",".next",".cache","coverage","__pycache__",".venv","venv",".turbo"]);try{const r=await(0,xo.readdir)(e,{withFileTypes:!0});for(const n of r){if(n.name.startsWith(".")&&".gitignore"!==n.name)continue;const r=(0,s.join)(e,n.name);n.isDirectory()?t.has(n.name)||(yield*Xi(r)):n.isFile()&&(yield r)}}catch(e){return}}function Qi(){return{encoding:Qs,lineEnding:"win32"===process.platform?fi.CRLF:fi.LF,isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function Yi(e){Mi.delete(e)}function ea(e,t){const r=Mi.get(e);if(void 0!==r)return void 0!==t&&r.size===t.size&&r.mtimeMs===t.mtimeMs?r.encoding:void Mi.delete(e)}function ta(e,t,r){if(Mi.has(e)&&Mi.delete(e),Mi.set(e,{encoding:r,size:t.size,mtimeMs:t.mtimeMs}),Mi.size<=100)return;const n=Mi.keys().next().value;void 0!==n&&Mi.delete(n)}function ra(e){try{return{text:wi.decode(e),encoding:Qs}}catch{const t=li(e);return ui(t)?{text:t,encoding:Qs}:{text:yi.decode(e),encoding:ei}}}function na(e,t){const r=oi(t);if(r===Qs||r===Ys||"ascii"===r){const t=ra(e);return r===Ys&&t.encoding===Qs?{text:t.text,encoding:Ys}:t}if(r===ei)return{text:yi.decode(e),encoding:ei};try{const t=ri(r);if(Js.encodingExists(t))return{text:Js.decode(e,t),encoding:r}}catch{}return ra(e)}function oa(e){return e.length>=vi.length&&e[0]===vi[0]&&e[1]===vi[1]&&e[2]===vi[2]}async function sa(e,t){try{return(await Zi(e)).subarray(0,t.length).equals(t)}catch{return!1}}var ia=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js");class aa{constructor({ttlMs:e,now:t=Date.now}){this.entries=new Map,this.nextSweepAtMs=0,this.ttlMs="function"==typeof e?e:aa.validated(e),this.now=t}static validated(e){if(!Number.isFinite(e)||e<=0)throw new Error(`TTL cache requires a positive ttlMs, got ${e}`);return()=>e}get(e){const t=this.entries.get(e);if(void 0!==t){if(!(t.expiresAtMs<=this.now()))return t.value;this.entries.delete(e)}}has(e){const t=this.entries.get(e);return!(void 0===t||t.expiresAtMs<=this.now()&&(this.entries.delete(e),1))}get size(){return this.entries.size}set(e,t){const r=this.now(),n=this.ttlMs();if(this.entries.set(e,{value:t,expiresAtMs:r+n}),!(r1048576?e:await async function(e,t){const r=function(e){const t=Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=Gi(t);return r.isBinaryFile?li(t):ni(na(t,r.encoding).text)}(t);return function(e,t){if(!(0,n.isUtf8)(e))return!1;const r=e.toString("utf8");return(r.startsWith("\ufeff")?r.slice(1):r)===t}(t,r)?e:async function(e,t){const r=await(da??=(0,xo.mkdtemp)((0,s.join)((0,o.tmpdir)(),"cursorignore-utf8-")).then((e=>(process.once("exit",(()=>{try{(0,Ro.rmSync)(e,{recursive:!0,force:!0})}catch{}})),e))),da),n=(0,s.join)(r,`cursorignore-${ha(e)}-${ha(t)}.txt`);if(await pa(n))return n;const i=`${n}.${process.pid}.${Date.now()}.tmp`;return await(0,xo.writeFile)(i,t,"utf8"),await(0,xo.rename)(i,n),n}(e,r)}(e,await(0,xo.readFile)(e));return la.set(e,{mtimeMs:t.mtimeMs,size:t.size,ripgrepPath:i}),i}function ma(e){return Promise.all(e.map((e=>async function(e){const t=ua.get(e);if(void 0!==t)return t;const r=fa(e).catch((()=>e)).finally((()=>{ua.delete(e)}));return ua.set(e,r),r}(e))))}(0,Es.J)((function(){la.clear(),ua.clear()}));var ga=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function wa(e){if(e.aborted)return{aborted:Promise.resolve("aborted"),[Symbol.dispose](){}};let t=()=>{};const r=new Promise((e=>{t=()=>e("aborted")}));return e.addEventListener("abort",t,{once:!0}),{aborted:r,[Symbol.dispose](){e.removeEventListener("abort",t)}}}function ya(e,{root:t,searchPaths:r=[],includeGlobs:n=[],excludeGlobs:s=[],caseSensitive:i=!1,cursorIgnoreFiles:a=[],sandboxPolicy:c={type:"insecure_none"},noIgnoreVcs:l=!1,followSymlinks:u=!1,source:d="ripwalk"}){const h=["--files","--hidden","--no-require-git","--no-config","--color=never"],p=function(e=process.env){const t=e.CURSOR_RIPWALK_THREADS?.trim();if(void 0!==t&&""!==t){const e=Number(t);if(Number.isInteger(e)&&e>=0)return 0===e?void 0:e}return Math.min(2,(0,o.availableParallelism)())}();void 0!==p&&h.push("--threads",String(p)),u&&h.push("--follow"),l&&h.push("--no-ignore-vcs"),i&&h.push("--case-sensitive");for(const e of n)h.push("--iglob",e);for(const e of s)h.push("--iglob",`!${e}`);const f=r.length>0?["--",...r]:[];let m,g=!1;const w=new Promise((e=>{m=e}));return{lines:async function*(){const r={stack:[],error:void 0,hasError:!1};try{const n=[];for(const e of await ma(a))n.push("--cursor-ignore",e);const o=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,function(e,t,r,n){const o=(0,No.spawnInSandbox)((0,No.Ko)(),t,{cwd:r},n),s=[];o.stderr?.on("data",(e=>{s.push(e)}));const i=new Promise(((e,t)=>{o.on("error",t),o.on("close",(t=>e(t??0)))}));if(i.catch((()=>{})),!o.stdout)throw new Error("No stdout from ripgrep process");const a=wa(e.signal);return{stdout:o.stdout,processExit:i,stderr:()=>Buffer.concat(s).toString(),aborted:a.aborted,[Symbol.dispose](){a[Symbol.dispose](),o.kill()}}}(e,[...h,...n,...f],t,c),!1);let s=0;const i=async function*(e){const t=new ca.StringDecoder("utf8");let r="";for await(const n of e){r+=t.write(n);const e=r.split("\n");r=e.pop()??"",e.length>0&&(yield e)}r+=t.end(),r&&(yield[r])}(o.stdout)[Symbol.asyncIterator]();e:for(;;){const t=await Promise.race([i.next(),o.aborted]);if("aborted"===t){g=!0,m(!0);break}if(t.done)break;for(const r of t.value){if(e.signal.aborted){g=!0,m(!0);break e}s++,yield r}}if(s>0);else if(!g){const e=await o.processExit;if(0!==e&&1!==e){const t=o.stderr();throw new Error(`Ripgrep failed (exit ${e}) with no results${t?`: ${t}`:""}`)}}g||m(!1)}catch(e){r.error=e,r.hasError=!0}finally{ga(r)}}(),didTimeout:w}}var va=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});let ba;function Sa(e=process.env){if(void 0!==ba)return ba;const t=e.CURSOR_RIPWALK_CACHE_TTL_MS?.trim();if(void 0!==t&&""!==t){const e=Number(t);if(Number.isFinite(e)&&e>0)return e}return 2e4}function ka({root:e,searchPaths:t=[],includeGlobs:r=[],excludeGlobs:n=[],caseSensitive:o=!1,cursorIgnoreFiles:s=[],sandboxPolicy:i={type:"insecure_none"},noIgnoreVcs:a=!1,followSymlinks:c=!1}){return JSON.stringify({root:e,searchPaths:t,includeGlobs:r,excludeGlobs:n,caseSensitive:o,cursorIgnoreFiles:s,sandboxPolicy:i,noIgnoreVcs:a,followSymlinks:c})}class _a{constructor(e=()=>Sa()){this.cache=new aa({ttlMs:e})}get size(){return this.cache.size}clear(){this.cache.clear()}delete(e){this.cache.delete(ka(e))}walk(e,t){const r=ka(t);let n,o=!1,s=!1;const i=new Promise((e=>{n=e})),a=e=>{s||(s=!0,n(e))};return{lines:async function*(){const n=this.cache.get(r);if(void 0!==n){const t={stack:[],error:void 0,hasError:!1};try{const s=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,wa(e.signal),!1),i=await Promise.race([n.linesPromise.then((e=>({type:"lines",lines:e})),(e=>({type:"error",error:e}))),s.aborted.then((()=>({type:"aborted"})))]);if("aborted"===i.type)return o=!0,void a(!0);if("lines"===i.type)return a(!1),void(yield*i.lines);this.cache.get(r)===n&&this.cache.delete(r)}catch(e){t.error=e,t.hasError=!0}finally{va(t)}}let s,i;const c={linesPromise:new Promise(((e,t)=>{s=e,i=t}))};c.linesPromise.catch((()=>{})),this.cache.set(r,c);const l=[];let u,d=!1;try{const r=ya(e,t);for await(const e of r.lines)l.push(e),yield e;if(await r.didTimeout)return o=!0,u=new Error("Ripwalk aborted before cacheable result was available"),void a(!0);d=!0}catch(e){throw u=e,e}finally{d?s?.(l):(this.cache.get(r)===c&&this.cache.delete(r),i?.(u??new Error("Ripwalk terminated before cacheable result was available"))),o||a(!1)}}.bind(this)(),didTimeout:i}}}const Ca=16777216,Ea=new Set([32,9,10,13]),xa="a path through /proc or /dev/fd",Pa={kind:"none"},Ra={kind:"stop"};function Ia(e,t){return{kind:"refused",refused:{name:e,reason:t}}}async function Ta(e){const t=await async function(e){if(void 0===await(0,xo.lstat)(e).catch((()=>{})))return Pa;if(await Ma(Buffer.from(e)))return Ia(".git",xa);const t=await(0,xo.stat)(e).catch((()=>{}));if(void 0===t)return Pa;if(!t.isFile())return Aa(e);const r=await Na(e,{whole:1048576});if("not-regular"===r.kind)return Ia(".git","not a regular file");if("bytes"!==r.kind)return Ra;const n=Buffer.from("gitdir: "),o=Ba(r.bytes);if(!o.subarray(0,n.length).equals(n)||o.length<=n.length)return Ra;const i=Ua({dir:(0,s.dirname)(e),target:Wa(o.subarray(n.length))});if(await Ma(i))return Ia(".git",xa);const a=await Aa(i);return"none"===a.kind?Ra:a}(ja(e,".git").toString());return"none"!==t.kind?t:Aa(e)}async function Aa(e){const t=await async function(e){const t=await(0,xo.lstat)(e).catch((()=>{}));if(void 0===t||t.isDirectory())return Pa;if(t.isSymbolicLink()){const t=await(0,xo.readlink)(e,{encoding:"buffer"}).catch((()=>{}));return"refs/"===t?.subarray(0,5).toString("latin1")?"valid":Pa}if(!t.isFile())return Ia("HEAD","not a regular file");const r=await Na(e,{prefix:255});if("not-regular"===r.kind)return Ia("HEAD","not a regular file");if("bytes"!==r.kind)return Pa;const n=Wa(r.bytes.subarray(0,255)).toString("latin1");if(n.startsWith("ref:")){let e=4;for(;e{}))){if(await Ma(n))return Ia("commondir",xa);const t=await Na(n,{whole:Ca});switch(t.kind){case"bytes":{if(0===t.bytes.length)return Ra;const n=Ua({dir:e,target:Wa(Ba(t.bytes))});if(await Ma(n))return Ia("commondir",xa);const o=await(0,xo.realpath)(n,{encoding:"buffer"}).catch((()=>{}));if(void 0===o)return Pa;r=o;break}case"too-large":return Ia("commondir","over the size cap");case"not-regular":return Ia("commondir","not a regular file");case"directory":case"unreadable":return Ra;default:throw new Error(`unhandled read ${String(t)}`)}}for(const e of["objects","refs"]){const t=ja(r,e);if(await Ma(t))return Ia(e,xa);if(!await La(t))return Pa}return{kind:"repository",gitDir:e,commonDir:r}}async function $a({gitDir:e,commonDir:t}){const r=[["HEAD",ja(e,"HEAD")],["config.worktree",ja(e,"config.worktree")],["config",ja(t,"config")],["info/exclude",ja(ja(t,"info"),"exclude")]];for(const[e,t]of r){if(await Ma(t))return{name:e,reason:xa};const r=await(0,xo.stat)(t).catch((()=>{}));if(void 0!==r&&!r.isDirectory()&&!await Fa(r)){if(!r.isFile())return{name:e,reason:"not a regular file"};if(r.size>Ca)return{name:e,reason:"over the size cap"}}}}async function Ma(e){if("win32"===process.platform)return!1;const t=Da(e.toString("latin1")).reverse();let r="/",n=0;for(let e=t.pop();void 0!==e;e=t.pop()){if(".."===e){r=(0,s.dirname)(r);continue}const o=(0,s.join)(r,e),i="darwin"===process.platform?o.toLowerCase():o;if(["/proc","/dev/fd"].some((e=>i===e||i.startsWith(`${e}/`))))return!0;const a=await(0,xo.readlink)(Buffer.from(o,"latin1"),{encoding:"buffer"}).catch((()=>{}));if(void 0===a){r=o;continue}if(++n>40)return!1;const c=a.toString("latin1");(0,s.isAbsolute)(c)&&(r="/"),t.push(...Da(c).reverse())}return!1}function Da(e){return e.split("/").filter((e=>""!==e&&"."!==e))}let Oa;async function Fa(e){if(!e.isCharacterDevice())return!1;Oa??=(0,xo.stat)("/dev/null").catch((()=>{}));const t=await Oa;return void 0!==t&&e.dev===t.dev&&e.ino===t.ino}async function Na(e,t){const r=Ro.constants.O_RDONLY|(Ro.constants.O_NONBLOCK??0)|(Ro.constants.O_NOCTTY??0),n=await(0,xo.open)(e,r).catch((()=>{}));if(void 0===n)return{kind:"unreadable"};try{const e=await n.stat();if(e.isDirectory())return{kind:"directory"};if(!e.isFile())return{kind:"not-regular"};if("whole"in t&&e.size>t.whole)return{kind:"too-large"};const r="whole"in t?t.whole:t.prefix,o=Buffer.alloc(Math.min(r+1,e.size+1));let s=0;for(;st.whole?{kind:"too-large"}:{kind:"bytes",bytes:o.subarray(0,s)}}catch{return{kind:"unreadable"}}finally{await n.close().catch((()=>{}))}}function La(e){return(0,xo.access)(e,Ro.constants.X_OK).then((()=>!0),(()=>!1))}function ja(e,t){const r=Buffer.isBuffer(e)?e:Buffer.from(e),n=r.toString("latin1").endsWith(s.sep)?"":s.sep;return Buffer.concat([r,Buffer.from(`${n}${t}`)])}function Ua({dir:e,target:t}){return(0,s.isAbsolute)(t.toString("latin1"))?t:Buffer.concat([ja(e,""),t])}function Ba(e){let t=e.length;for(;t>0&&(10===e[t-1]||13===e[t-1]);)t--;return e.subarray(0,t)}function Wa(e){const t=e.indexOf(0);return-1===t?e:e.subarray(0,t)}const Ha=[{stage:"prod",gitHost:"origin.cursor.com",gitCdnHost:"gitcdn.origin.cursor.com",cloneKitS3Host:"git-forge-prod-bundles.s3.us-east-1.amazonaws.com",rawUserContentHost:"raw.cursorusercontent.com",apiHost:"api.origin.cursor.com",internalHost:"origin-prod.internal.cursor.com"},{stage:"staging",gitHost:"origin-staging.cursor.com",gitCdnHost:"gitcdn.origin-staging.cursor.com",cloneKitS3Host:"git-forge-staging-bundles.s3.us-east-1.amazonaws.com",rawUserContentHost:"raw.staging.cursorusercontent.com",apiHost:"api.origin-staging.cursor.com",internalHost:"origin-staging.internal.cursor.com"},{stage:"test",gitHost:"origin-test.cursor.com",gitCdnHost:"gitcdn.origin-test.cursor.com",cloneKitS3Host:"git-forge-test-bundles.s3.us-east-1.amazonaws.com",rawUserContentHost:"raw.test.cursorusercontent.com",apiHost:"api.origin-test.cursor.com",internalHost:"origin-test.internal.cursor.com"}];function qa(e){let t=e.length;for(;t>0&&47===e.charCodeAt(t-1);)t--;const r=e.slice(0,t).replace(/\.git$/i,"");return r&&"/"!==r?r.startsWith("/")?r:`/${r}`:""}function za(e,t){const r=qa(t);return r?`${e}${r}`.toLowerCase():""}new Map(Ha.map((e=>[e.gitHost,e.apiHost]))),new Map(Ha.map((e=>[e.gitHost,e.gitCdnHost]))),new Map(Ha.map((e=>[e.gitHost,e.cloneKitS3Host]))),new Map(Ha.map((e=>[e.gitHost,e.rawUserContentHost]))),new Map(Ha.map((e=>[e.apiHost,e.gitHost]))),new Map(Ha.map((e=>[e.apiHost,e.internalHost])));const Ga=new Map;function Va(e){const t=Ga.get(e);if(void 0!==t)return t;const r=function(e){const t=e.trim();if(!t)return"";try{const e=function(e){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(e))return e;const t=`https://${e}`;try{return new URL(t),t}catch{const r=e.match(/^([^@/\s]+@)?([^:/\s]+):(.+)$/);return r?`ssh://${r[1]??""}${r[2]}/${r[3]}`:t}}(t),r=new URL(e);return za(r.hostname,r.pathname)}catch{const e=t.replace(/^(?:https?|ssh|git):\/\//i,""),r=e.indexOf("/"),n=-1===r?e:e.slice(0,r),o=-1===r?"":e.slice(r);return za(n.includes("@")?n.slice(n.lastIndexOf("@")+1):n,o)}}(e);return Ga.size>=16384&&Ga.clear(),Ga.set(e,r),r}function Ka(e){return/^origin(-[a-z0-9]+)?\.cursor\.com$/i.test(e)}(function(e){const t=Ha.find((t=>t.stage===e));if(void 0===t)throw new Error(`unknown Origin stage: ${e}`);return t})("prod").gitHost;const Ja=new Map;function Za(e){if(void 0===e)return;if(Ja.has(e))return Ja.get(e);const t=function(e){const t=e?function(e){let t=e.trim();if(""!==t){t.startsWith("git@")?t=`https://${t.slice(4).replace(":","/")}`:/^[a-z][a-z0-9+.-]*:\/\//i.test(t)&&!/^https?:\/\//i.test(t)?t=t.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"https://"):/^https?:\/\//i.test(t)||(t=`https://${t}`);try{return new URL(t)}catch{return}}}(e):void 0;if(void 0===t||!Ka(t.hostname))return;const r=qa(t.pathname).split("/").filter(Boolean),n=3===r.length&&"git"===r[0]?.toLowerCase(),o=2===r.length&&"git"!==r[0]?.toLowerCase();if(!n&&!o)return;const s=n?r[1]:r[0],i=n?r[2]:r[1];return s&&i?Object.freeze({hostname:t.hostname,owner:s,name:i}):void 0}(e);return Ja.size>=16384&&Ja.clear(),Ja.set(e,t),t}function Xa(e){return void 0!==function(e){const t=Za(e);return void 0===t?void 0:{owner:t.owner,name:t.name}}(e)}new Set(["github.com","www.github.com"]),new RegExp("^tmp-[0-9a-f]{16}$");const Qa=(0,d.h)("local-exec:git-root"),Ya=new WeakMap,ec=new Map;function tc(e,t,r){return rc(e,t,r).then((e=>"repository"===e.kind?e.root:null))}function rc(e,t,r){const n=performance.now();let o=Ya.get(t);void 0===o&&(o=new Map,Ya.set(t,o));const s=o.get(r);if(void 0!==s&&nc(s,n))return s.result;for(const[e,t]of o)nc(t,n)||o.delete(e);const i=t.guardedRootLookup,a=void 0===i?{result:ic(e,t,r,void 0),windowStart:n}:{result:oc(e,t,r,i.timeoutMs),windowStart:void 0};return void 0===a.windowStart&&a.result.then((()=>{a.windowStart=performance.now()})),o.set(r,a),a.result}function nc(e,t){return void 0===e.windowStart||t-e.windowStart<5e3}async function oc(e,t,r,n){const o=new AbortController,i=performance.now()+n,a=await(0,Nr.wj)(async function({ctx:e,gitExecutor:t,startPath:r,deadline:n,settled:o}){const i=await function(e){let t=ec.get(e);if(void 0===t){t=async function(e){const t=await(0,xo.realpath)(e).catch((()=>{}));if(void 0===t)return;const r=function(){const e=(process.env.GIT_DISCOVERY_ACROSS_FILESYSTEM??"").toLowerCase();return!["","0","false","no","off"].includes(e)}()?void 0:(await(0,xo.stat)(t).catch((()=>{})))?.dev;for(let e=t;;){const t=await Ta(e);switch(t.kind){case"refused":return t.refused;case"stop":return;case"repository":return $a(t);case"none":break;default:throw new Error(`unhandled probe ${String(t)}`)}const n=(0,s.dirname)(e);if(n===e||void 0!==r&&(await(0,xo.stat)(n).catch((()=>{})))?.dev!==r)return;e=n}}(e),ec.set(e,t);const r=()=>{ec.delete(e)};t.then(r,r)}return t}(r);if(o.aborted)return{kind:"unknown",reason:"timed-out"};if(void 0!==i)return Qa.warn(e,"findGitRoot: not starting git; its answer is unknown",{adminFile:i.name,reason:i.reason}),{kind:"unknown",reason:"refused"};const a=Math.ceil(n-performance.now());return a<=0?{kind:"unknown",reason:"timed-out"}:ic(e,t,r,a)}({ctx:e,gitExecutor:t,startPath:r,deadline:i,settled:o.signal}),n).catch((t=>t instanceof Nr.MU?{kind:"unknown",reason:"timed-out"}:(Qa.warn(e,"findGitRoot: the admin file check failed; not starting git",{code:sc(t)}),{kind:"unknown",reason:"refused"}))).finally((()=>{o.abort()}));return"unknown"===a.kind&&"timed-out"===a.reason&&Qa.warn(e,"findGitRoot: the lookup ran past its bound; its answer is unknown",{timeoutMs:n}),a}function sc(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:void 0}async function ic(e,t,r,n){try{return{kind:"repository",root:(await t.exec(e,r,["rev-parse","--show-toplevel"],{...void 0===n?{}:{timeout:n},caller:"findGitRoot"})).stdout.trim()}}catch(e){return void 0!==n&&function(e){return"object"==typeof e&&null!==e&&"killed"in e&&!0===e.killed}(e)?{kind:"unknown",reason:"timed-out"}:{kind:"none"}}}async function ac(e,t,r){try{return(await t.exec(e,r,["config","--get","remote.origin.url"],{caller:"getGitRemoteUrl"})).stdout.trim()}catch{return}}function cc(e){const t=e.trim();if(""===t)return t;try{const e=new URL(t);return""===e.host?uc(t)??e.toString():(e.username="",e.password="",e.toString())}catch{return function(e){const t=e.replace(/^[\u0000-\u0020]+|[\u0000-\u0020]+$/g,"").replace(/[\t\n\r]/g,""),r=t.indexOf(":"),n=t.slice(0,r);if(r<0||!/^[A-Za-z][A-Za-z0-9+.-]*$/.test(n))return;const o=t.slice(r+1),s=lc.has(n.toLowerCase());let i;if(s)i=o.replace(/^[/\\]+/,"");else{if(!o.startsWith("//"))return;i=o.slice(2)}const a=i.search(s?/[/?#\\]/:/[/?#]/),c=a<0?i.length:a,l=i.slice(0,c),u=l.lastIndexOf("@");return u<0?void 0:`${t.slice(0,t.length-i.length)}${l.slice(u+1)}${i.slice(c)}`}(t)??uc(t)??t}}const lc=new Set(["ftp","file","http","https","ws","wss"]);function uc(e){const t=e.indexOf("/"),r=t<0?e:e.slice(0,t),n=r.indexOf(":"),o=r.lastIndexOf("@",r.lastIndexOf(":"));if(!(n<0||o<0||r.indexOf("@")`/${s.posix.relative(e,t)}`))}var pc=r("../../node_modules/.pnpm/picomatch@4.0.5/node_modules/picomatch/index.js");function fc(e,t){return e.some((e=>{return"*"===e.url.trim()?(e.patterns??[]).some((e=>wc(e.pattern,t))):!((r=e.url).includes("://")||r.includes("github.com")||r.includes("gitlab.com")||r.includes("bitbucket.org")||r.includes("@"))&&wc(e.url,t);var r}))}function mc(e,t,r){return gc(e.url,t)&&(e.patterns??[]).some((e=>wc(e.pattern,r)))}function gc(e,t){return e.includes("*")?"*"===e.trim()||function(e,t){const r=e.trim();return!!wc(r,t)||!!r.startsWith("*/")&&wc(`**/${r.slice(2)}`,t)}(kc(e),kc(t)):kc(e)===kc(t)}function wc(e,t){const r=e.trim();return!("."!==t&&""!==t||"**"!==r&&"**/*"!==r)||function(e){const t=bc.get(e);if(void 0!==t)return t;let r;try{const t=pc(e,{dot:!0});r=r=>{try{return t(r)}catch{return e===r}}}catch{r=t=>e===t}return Sc(bc,yc,e,r)}(r)(t)}const yc=2048,vc=new Map,bc=new Map;function Sc(e,t,r,n){if(e.set(r,n),e.size>t){const t=e.keys().next().value;void 0!==t&&e.delete(t)}return n}function kc(e){const t=vc.get(e);if(void 0!==t)return t;const r=(function(e){const t=Za(e);if(void 0!==t)return`${t.hostname}/git/${t.owner}/${t.name}`.toLowerCase()}(n=e)??Va(n))||function(e){let t=e.trim();t.startsWith("git@")&&(t=`https://${t.slice(4).replace(":","/")}`),/^[a-z][a-z0-9+.-]*:\/\//i.test(t)&&!/^https?:\/\//i.test(t)&&(t=t.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"https://")),/^https?:\/\//i.test(t)||(t=`https://${t}`);try{const e=new URL(t),r=e.pathname.replace(/\/+$/,"").replace(/\.git$/i,"").replace(/\/+$/,"");return e.hostname+r}catch{return t=t.replace(/^https?:\/\//i,""),t=t.replace(/[?#].*$/,""),t=t.replace(/\/+$/,""),t=t.replace(/\.git$/i,""),t=t.replace(/\/+$/,""),t}}(e).toLowerCase();var n;return Sc(vc,2048,e,r)}function _c(e){if("object"==typeof e&&null!==e&&"code"in e){const t=e.code;if("string"==typeof t)return t}}function Cc(e){if(e instanceof Error)return e.message;if("object"==typeof e&&null!==e&&"message"in e){const t=e.message;if("string"==typeof t)return t}return""}(0,Es.J)((function(){vc.clear(),bc.clear()}));const Ec=[".gitignore",".cursorignore"];async function xc(e){if(!(0,s.isAbsolute)(e))return null;const t=await(0,ts.DN)(e);return null===t?null:t}function Pc(e,t){if(!e||0===e.length)return[...t];const r=new Set(e);for(const e of t)r.has(e)&&r.delete(e),r.add(e);return[...r]}class Rc{constructor(e,t,r,n={}){this.disposeRequested=!1,this.initIgnoreService=()=>Ac.init((0,b.q6)(),e,r??[process.cwd()],t),!0!==n.deferInit&&this.ensureStarted()}ensureStarted(){if(void 0===this.ignoreServicePromise){if(this.disposeRequested)return Promise.reject(new Error("LazyIgnoreService was disposed before its ignore-file scan started"));this.ignoreServicePromise=this.initIgnoreService()}return this.ignoreServicePromise}isIgnoredByAny(e){return this.ensureStarted().then((t=>t.isIgnoredByAny(e)))}isGitIgnored(e){return this.ensureStarted().then((t=>t.isGitIgnored(e)))}isCursorIgnored(e,t){return this.ensureStarted().then((r=>r.isCursorIgnored(e,t)))}isRepoBlocked(e){return this.ensureStarted().then((t=>t.isRepoBlocked(e)))}listCursorIgnoreFilesByRoot(e){return this.ensureStarted().then((t=>t.listCursorIgnoreFilesByRoot(e)))}getCursorIgnoreMapping(){return this.ensureStarted().then((e=>e.getCursorIgnoreMapping()))}getShellSandboxIgnoreMapping(e){return this.ensureStarted().then((t=>t.getShellSandboxIgnoreMapping(e)))}getGitIgnoreMapping(){return this.ensureStarted().then((e=>e.getGitIgnoreMapping()))}getRepoBlockExcludeGlobs(e){return this.ensureStarted().then((t=>t.getRepoBlockExcludeGlobs(e)))}handleCursorIgnoreCreated(e){return this.ensureStarted().then((t=>t.handleCursorIgnoreCreated(e)))}handleCursorIgnoreChanged(e){return this.ensureStarted().then((t=>t.handleCursorIgnoreChanged(e)))}handleCursorIgnoreDeleted(e){return this.ensureStarted().then((t=>t.handleCursorIgnoreDeleted(e)))}dispose(){this.disposeRequested||(this.disposeRequested=!0,this.ignoreServicePromise?.then((e=>{e.dispose()})).catch((()=>{})))}}const Ic=Math.min(8,Math.max(1,Math.floor(o.availableParallelism()/2)));class Tc{constructor(e){this.maxLookups=e,this.instances=new Map,this.lookups=0}get(e,t){this.lookups>=this.maxLookups&&this.clear(),this.lookups++;let r=this.instances.get(e);return void 0===r&&(r=ia().add(t),this.instances.set(e,r)),r}delete(e){this.instances.delete(e)}clear(){this.instances.clear(),this.lookups=0}}class Ac{constructor(e,t,r,n,o,s){this.gitExecutor=e,this.gitIgnoreMapping=t,this.cursorIgnoreMapping=r,this.teamSettingsService=n,this.rootDirectories=o,this.scanEnvironment=s,this.gitIgnoreCache=new Bs.q({max:2e3}),this.cursorIgnoreCache=new Bs.q({max:2e3}),this.gitRootCache=new Bs.q({max:1e4}),this.gitRemoteUrlCache=new Bs.q({max:200}),this.hasGitDirCache=new Bs.q({max:1e3}),this.gitParsedIgnoreCache=new Tc(1e4),this.cursorParsedIgnoreCache=new Tc(1e4),this.ignoreMappingsHaveEntries=!1,this.directoryWalkPlacementCache=new Bs.q({max:1e4}),this.extraRootCursorIgnoreCache=new Bs.q({max:32}),this.extraGitRepoMappingCache=new Bs.q({max:32}),this.unwalkedFolders=o.flatMap((e=>zs(e,s)))}static getRipwalkCache(){return Ac.ripwalkCache??=new _a,Ac.ripwalkCache}hasNoWorkspaceFolders(){return!this.ignoreMappingsHaveEntries&&(this.ignoreMappingsHaveEntries=Object.keys(this.gitIgnoreMapping).length>0||Object.keys(this.cursorIgnoreMapping).length>0,!this.ignoreMappingsHaveEntries)}async resolveLookupRoot(e){return await(0,ts.DN)(e)??(0,ts.o1)(e)}static async init(e,t,r,n,s={platform:process.platform,homeDirectory:o.homedir()}){const i={...s,homeDirectory:await(0,ts.DN)(s.homeDirectory)??s.homeDirectory},a=await(0,Nr.PH)(r,(async e=>{const t=await(0,ts.DN)(e);return null===t?(console.warn(`[IgnoreService] Cannot resolve workspace root, using as-is: ${e}`),e):t})),c={},l={},u=await(0,Nr.PH)(a,(async r=>({root:r,lookup:await rc(e,t,r)}))),d=u.map((({root:e,lookup:t})=>"none"===t.kind?null:"unknown"===t.kind||zs(t.root,i).length>0?e:t.root)).filter((e=>null!==e)),h=u.filter((({lookup:e})=>"unknown"===e.kind)).map((({root:e})=>(0,ts.o1)(e)));return d.length>0&&await Promise.all([Ac.initializeIgnoreMapping({rootDirectories:d,ignoreFileName:".gitignore",mapping:c,scanEnvironment:i,unknownRoots:h}),Ac.initializeIgnoreMapping({rootDirectories:a,ignoreFileName:".cursorignore",mapping:l,scanEnvironment:i,unknownRoots:h})]),new Ac(t,c,l,n,a,i)}static async preloadHierarchy(e,t,r,n){let o=(0,ts.o1)(e);const i=(0,s.parse)(o).root;for(;o!==i;){if(n?.has(o)){const e=(0,s.dirname)(o);if(e===o)break;o=e;continue}void 0===r[o]&&await Ac.handleHierarchyIgnore(o,t,r),n?.add(o);const e=(0,s.dirname)(o);if(e===o)break;o=e}}static async handleHierarchyIgnore(e,t,r){const n=(0,s.join)(e,t);try{await(0,xo.access)(n,xo.constants.F_OK);const t=await Bi(n),o=Ac.parseIgnoreRules(t);r[e]=o}catch(o){"ENOENT"===_c(o)||console.error(`Error reading ${t} file at ${n}:`,o),r[e]=[]}}static async initializeIgnoreMapping({rootDirectories:e,ignoreFileName:t,mapping:r,scanEnvironment:n,unknownRoots:o}){try{const i=Ac.deduplicateRootDirectories(e),a=await Ac.promiseQueue.enqueueList(i,(e=>Ac.findFilesWithRipgrep({rootDirectory:e,fileName:t,scanEnvironment:n,noIgnoreVcs:o.some((t=>(0,ts.ZU)({basePath:e,targetPath:t})))}))),c=Array.from(a.values()).flat();await Promise.all(c.map((async e=>{try{const t=await Bi(e),n=Ac.parseIgnoreRules(t),o=(0,s.dirname)(e);r[o]=n}catch(r){console.error(`Error processing ${t} file at ${e}:`,r)}})));const l=new Set;for(const e of i)await Ac.preloadHierarchy(e,t,r,l)}catch(e){console.error(`Error initializing ignore mapping for ${t}:`,e)}}static async findFilesWithRipgrep({rootDirectory:e,fileName:t,scanEnvironment:r,noIgnoreVcs:n}){const o=(0,b.q6)(),i=[],a={root:e,includeGlobs:Ec.map((e=>`**/${e}`)),excludeGlobs:[...dc,...hc(e,r)],noIgnoreVcs:n,source:"ignore_scan"},c=Ac.getRipwalkCache().walk(o,a);for await(const r of c.lines)(0,s.basename)(r)===t&&i.push((0,s.join)(e,r));return i}async handleManualLookupWhenNoWorkspaceDirs(e,t,r){const n={};let o=(0,s.dirname)(e);const i=(0,s.parse)(o).root;for(;;){let e=r?.get(o);if(void 0===e){try{e=Ac.parseIgnoreRules(await Bi((0,s.join)(o,t)))}catch{e=[]}r?.set(o,e)}if(e.length>0&&(n[o]=e),o===i)break;o=(0,s.dirname)(o)}return this.testIgnored(e,n,((e,t)=>ia().add(t)))}async isIgnoredByAny(e){const[t,r,n]=await Promise.all([this.checkGitIgnored(e),this.checkCursorIgnored(e),this.checkRepoBlocked(e)]);return t||r||n}async isGitIgnored(e){return this.checkGitIgnored(e)}async isCursorIgnored(e,t){return this.checkCursorIgnored(e,t)}async checkGitIgnored(e){if(this.hasNoWorkspaceFolders())return this.handleManualLookupWhenNoWorkspaceDirs(e,".gitignore");const t=this.gitIgnoreCache.get(e);if(void 0!==t)return t;await this.populateHierarchyIfNeeded(e,".gitignore",this.gitIgnoreMapping);const r=this.checkIgnored(e,this.gitIgnoreMapping,this.gitParsedIgnoreCache);return this.gitIgnoreCache.set(e,r),r}async checkCursorIgnored(e,t){if(this.hasNoWorkspaceFolders())return this.handleManualLookupWhenNoWorkspaceDirs(e,".cursorignore",t);const r=this.cursorIgnoreCache.get(e);if(void 0!==r)return r;await this.populateHierarchyIfNeeded(e,".cursorignore",this.cursorIgnoreMapping);const n=this.checkIgnored(e,this.cursorIgnoreMapping,this.cursorParsedIgnoreCache);return this.cursorIgnoreCache.set(e,n),n}isInUnwalkedFolder(e){const t="darwin"===this.scanEnvironment.platform,r=t?e.toLowerCase():e;return this.unwalkedFolders.some((e=>(0,ts.ZU)({basePath:t?e.toLowerCase():e,targetPath:r})))}directoryWalkPlacement(e){const t=this.directoryWalkPlacementCache.get(e);if(void 0!==t)return t;let r;return r=this.isInUnwalkedFolder(e)?"unwalked":this.rootDirectories.some((t=>(0,ts.ZU)({basePath:t,targetPath:e})))?"walked":"outside",this.directoryWalkPlacementCache.set(e,r),r}async populateHierarchyIfNeeded(e,t,r){let n=(0,s.dirname)((0,ts.o1)(e));const o=[],i=(0,s.parse)(n).root;for(;n!==i;){const e=this.directoryWalkPlacement(n),t="unwalked"===e;if("walked"===e){n=(0,s.dirname)(n);continue}if(void 0===r[n])o.push(n);else if(!t)break;const i=(0,s.dirname)(n);if(i===n)break;n=i}o.length>0&&(await Ac.promiseQueue.enqueueList(o,(e=>Ac.handleHierarchyIgnore(e,t,r))),".gitignore"===t?this.gitIgnoreCache.clear():this.cursorIgnoreCache.clear())}testIgnored(e,t,r){for(const[n,o]of Object.entries(t)){if(0===o.length)continue;if(!(0,ts.ZU)({basePath:n,targetPath:e}))continue;const t=(0,s.relative)(n,e);if(""===t)continue;const i=r(n,o),a=(0,ts.oL)(t),c=i.test(a);if(c.ignored&&!c.unignored)return!0;const l=i.test(`${a}/`);if(l.ignored&&!l.unignored)return!0}return!1}checkIgnored(e,t,r){return this.testIgnored(e,t,((e,t)=>r.get(e,t)))}async listCursorIgnoreFilesByRoot(e){const t=await this.resolveLookupRoot(e),r=[];for(const[e,n]of Object.entries(this.cursorIgnoreMapping)){if(0===n.length)continue;if(!(0,ts.ZU)({basePath:t,targetPath:e}))continue;const o=(0,s.join)(e,".cursorignore");try{await(0,xo.access)(o),r.push(o)}catch{}}return r}async getCursorIgnoreMapping(){return{...this.cursorIgnoreMapping}}async getShellSandboxIgnoreMapping(e=[]){const t={...this.cursorIgnoreMapping},r=[];for(const t of e){if((0,Gs.$f)(t))continue;const e=await(0,ts.DN)(t);if(null===e||".git"===(0,s.basename)(e)||this.rootDirectories.some((t=>(0,ts.ZU)({basePath:t,targetPath:e})))||r.includes(e))continue;const n=await xo.stat(e).catch((e=>{if(void 0===_c(e))throw e}));n?.isDirectory()&&r.push(e)}const n=Date.now();for(const e of r){let r=this.extraRootCursorIgnoreCache.get(e);if(void 0===r||r.expiresAt<=n){const t={},o=void 0===this.gitExecutor.guardedRootLookup?void 0:await rc((0,b.q6)(),this.gitExecutor,e);await Ac.initializeIgnoreMapping({rootDirectories:[e],ignoreFileName:".cursorignore",mapping:t,scanEnvironment:this.scanEnvironment,unknownRoots:"unknown"===o?.kind?[e]:[]}),r={mapping:t,expiresAt:n+Sa()},this.extraRootCursorIgnoreCache.set(e,r)}for(const[e,n]of Object.entries(r.mapping))t[e]=Pc(t[e],n)}for(const e of[...this.rootDirectories,...r]){const r=await this.getRepoBlockExcludeGlobs(e);0!==r.length&&(t[e]=Pc(t[e],r))}return t}async getGitIgnoreMapping(){return{...this.gitIgnoreMapping}}static deduplicateRootDirectories(e){const t=[...e.map((e=>(0,ts.o1)(e)))].sort(((e,t)=>e.length-t.length)),r=[];for(const e of t)r.some((t=>e.startsWith(`${t}/`)||e.startsWith(`${t}\\`)))||r.push(e);return r}static parseIgnoreRules(e){return e.split("\n").map((e=>e.replace(/\r$/,"").trimStart())).filter((e=>""!==e&&!e.startsWith("#")))}clearCaches(){this.gitIgnoreCache.clear(),this.cursorIgnoreCache.clear(),this.gitRootCache.clear(),this.gitRemoteUrlCache.clear(),this.hasGitDirCache.clear(),this.gitParsedIgnoreCache.clear(),this.cursorParsedIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear(),this.extraGitRepoMappingCache.clear()}dispose(){this.gitIgnoreCache=new Bs.q({max:1}),this.cursorIgnoreCache=new Bs.q({max:1}),this.gitRootCache=new Bs.q({max:1}),this.gitRemoteUrlCache=new Bs.q({max:1}),this.hasGitDirCache=new Bs.q({max:1}),this.directoryWalkPlacementCache=new Bs.q({max:1}),this.extraRootCursorIgnoreCache=new Bs.q({max:1}),this.extraGitRepoMappingCache=new Bs.q({max:1}),this.gitParsedIgnoreCache.clear(),this.cursorParsedIgnoreCache.clear(),this.gitRepoMappingPromise=void 0}async handleCursorIgnoreCreated(e){const t=(0,s.dirname)(e),r=await Bi(e),n=Ac.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear()}async handleCursorIgnoreChanged(e){const t=(0,s.dirname)(e),r=await Bi(e),n=Ac.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear()}handleCursorIgnoreDeleted(e){const t=(0,s.dirname)(e);this.cursorIgnoreMapping[t]=[],this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear()}async findGitRootsForFile(e){const t=(0,ts.o1)(e),r=this.gitRootCache.get(t);if(void 0!==r)return r;const n=[],o=[],i=[];let a=t;const c=(0,s.parse)(a).root;for(;a!==c;){o.push(a),void 0===this.hasGitDirCache.get(a)&&i.push(a);const e=(0,s.dirname)(a);if(e===a)break;a=e}if(i.length>0){const e=i.map((e=>(0,xo.access)((0,s.join)(e,".git"),xo.constants.F_OK).then((()=>[e,!0])).catch((()=>[e,!1])))),t=await Promise.all(e);for(const[e,r]of t)this.hasGitDirCache.set(e,r)}for(const e of o)!0===this.hasGitDirCache.get(e)&&n.push(e);return this.gitRootCache.set(t,n),n}async isRepoBlocked(e){return this.checkRepoBlocked(e)}async checkRepoBlocked(e){const t=function(e){if(void 0===e)return;const t=e.repos??[],r=e.disableLocalExecAllowlistEnforcement?[]:e.allowedRepos??[];return 0===t.length&&0===r.length?void 0:{blocked:t,allowed:r}}(await(this.teamSettingsService?.getTeamRepos()));if(void 0===t)return!1;const r=await this.findGitRootsForFile(e);if(0===r.length)return 0!==t.allowed.length&&!(0,ts.ZU)({basePath:await this.getCursorDataDir(),targetPath:e})&&function(e,t){return 0!==e.allowed.length&&!fc(e.allowed,t)}(t,this.getWorkspaceRelativePath(e));const n=[];for(const t of r)n.push({url:await this.remoteUrlOf(t),relativePath:(0,s.relative)(t,e)||"."});return function(e,t){let r=0===e.allowed.length,n=!1;for(const{url:o,relativePath:s}of t)if(void 0!==o){if(e.blocked.some((e=>mc(e,o,s))))return!0;e.allowed.length>0&&!n&&(n=!0,r=e.allowed.some((e=>mc(e,o,s))))}else 0;return!r}(t,n)}async remoteUrlOf(e){if(this.gitRemoteUrlCache.has(e))return this.gitRemoteUrlCache.get(e);const t=await ac((0,b.q6)(),this.gitExecutor,e);return void 0!==t&&this.gitRemoteUrlCache.set(e,t),t}getWorkspaceRelativePath(e){let t;for(const r of this.rootDirectories)(0,ts.ZU)({basePath:r,targetPath:e})&&(void 0===t||r.length>t.length)&&(t=r);return void 0!==t?(0,ts.oL)((0,s.relative)(t,e)):(0,ts.oL)(e)}getCursorDataDir(){return this.cursorDataDirPromise??=(async()=>{const e=(0,s.join)(o.homedir(),".cursor");return await(0,ts.DN)(e)??e})(),this.cursorDataDirPromise}async getRepoBlockExcludeGlobs(e){const t=await(this.teamSettingsService?.getTeamRepos());if(!t?.repos?.length)return[];const r=await this.resolveLookupRoot(e);let n;if(this.rootDirectories.some((e=>(0,ts.ZU)({basePath:e,targetPath:r}))))n=await this.getGitRepoMapping();else{const e=this.extraGitRepoMappingCache.get(r);void 0!==e?n=e:(n=await this.initializeGitRepoMapping([r]),this.extraGitRepoMappingCache.set(r,n))}if(0===n.size)return[];const o=[];for(const[e,i]of n){if(void 0===i)continue;const n=this.normalizePathForComparison(e),a=this.normalizePathForComparison(r);let c=!1,l="";if(a.startsWith(n)?(c=!0,l=""):n.startsWith(a)&&(c=!0,l=(0,s.relative)(r,e)),!c)continue;const u=t.repos.filter((e=>gc(e.url,i)));if(0!==u.length)for(const e of u)for(const t of e.patterns||[]){const e=t.pattern.trim();if(!e)continue;let r;r=l?(0,s.join)(l,e).replace(/\\/g,"/"):e,o.push(r),r.endsWith("/**")||o.push(`${r}/**`)}}return o}normalizePathForComparison(e){let t=e.replace(/\\/g,"/");return t.startsWith("/")&&t.length>2&&":"===t[2]&&(t=t.substring(1)),"win32"===process.platform&&(t=t.toLowerCase()),t}getGitRepoMapping(){return this.gitRepoMappingPromise||(this.gitRepoMappingPromise=this.initializeGitRepoMapping()),this.gitRepoMappingPromise}async initializeGitRepoMapping(e=this.rootDirectories){const t=new Map,r=[],n=["**/node_modules/**","**/.turbo/**","**/.next/**","**/.cache/**","**/.pnpm/**","**/.yarn/**","**/dist/**","**/build/**","**/out/**","**/target/**","**/.vscode/**","**/.idea/**","**/venv/**","**/__pycache__/**","**/logs/**","**/tmp/**","**/temp/**"],o=(0,b.q6)();for(const t of e){const e=(0,ts.o1)(t);try{await(0,xo.access)((0,s.join)(e,".git"),xo.constants.F_OK),r.includes(e)||r.push(e)}catch{}let i=(0,s.dirname)(e);const a=(0,s.parse)(i).root;for(;i!==a&&""!==i;){try{await(0,xo.access)((0,s.join)(i,".git"),xo.constants.F_OK),r.includes(i)||r.push(i)}catch{}const e=(0,s.dirname)(i);if(e===i)break;i=e}try{const t={root:e,includeGlobs:["**/.git/config"],excludeGlobs:[...n,...hc(e,this.scanEnvironment)],noIgnoreVcs:!0,source:"ignore_scan"},i=Ac.getRipwalkCache().walk(o,t);for await(const t of i.lines){const n=(0,s.join)(e,t),o=(0,s.dirname)(n),i=(0,s.dirname)(o);r.includes(i)||r.push(i)}}catch{}}return await Promise.all(r.map((async e=>{try{const r=await ac(o,this.gitExecutor,e);t.set(e,r)}catch{t.set(e,void 0)}}))),t}}async function $c(e,t){let r=e;if(Ds()&&(r=Us(t.command,t.parsingResult)),!r||"insecure_none"===r.type)return r;const n="workspace_readwrite"===r.type&&t.permissionsService.resolveLinkedWorktreeSandboxGrants?await t.permissionsService.resolveLinkedWorktreeSandboxGrants(r,{command:t.command,workingDirectory:t.workingDirectory}):void 0,o=function(e,t){if(!e)return t;const r={...e};for(const[e,n]of Object.entries(t))r[e]=Pc(r[e],n);return r}(r.ignoreMapping,await async function(e,t){return e.getShellSandboxIgnoreMapping?e.getShellSandboxIgnoreMapping(t):e.getCursorIgnoreMapping()}(t.ignoreService,n?.roots));if("workspace_readwrite"===r.type&&void 0!==n){const e=(0,No.s9)(r.additionalReadwritePaths,[...n.roots,...n.commonDirs]);return{...r,additionalReadwritePaths:e.length>0?e:void 0,ignoreMapping:o}}return{...r,ignoreMapping:o}}Ac.promiseQueue=new Nr.TJ({max:Ic});var Mc=r("../proto/dist/generated/agent/v1/mcp_exec_pb.js");const Dc="agent-tools",Oc=51380224;var Fc=r("../proto/dist/generated/agent/v1/utils_pb.js");const Nc=/^v?(\d{1,9})\.(\d{1,9})(?:\.\d{1,9})?(?:[-+][0-9A-Za-z.+-]*)?$/,Lc=["unknown","other","older","3.24","3.25","3.26","3.27","3.28","3.29","3.30","3.31","3.32","3.33","3.34","3.35","3.36","3.37","3.38","3.39","3.40","newer"].flatMap((e=>{const t=/^(\d+)\.(\d+)$/.exec(e);return null===t?[]:[{major:Number(t[1]),minor:Number(t[2]),bucket:e}]})),jc=Lc[0].major,Uc=Lc[0].minor;function Bc(e){if(null==e)return"unknown";const t=e.trim();if(0===t.length||t.length>128)return"unknown";const r=Nc.exec(t);if(null===r)return"unknown";const n=Number(r[1]),o=Number(r[2]);if(n!==jc)return"other";const s=Lc.find((e=>e.minor===o));return void 0!==s?s.bucket:o=128&&t<=191?t:Jc.get(e)}function ol(e,t){const r=e.charCodeAt(t),n=function(e){return e>=194&&e<=222?201===e?0:2:e>=224&&e<=239?3:240===e?4:0}(r);if(0===n||t+n>e.length)return;const o=new Uint8Array(n);o[0]=r;for(let r=1;r0&&Xc.test(e[t-1]))return}else{if(Qc.has(s))return;if(!0===el.get(r)?.has(s))return;if(3===n&&tl.has(s)&&Qc.has(e[t+2]))return}let i;try{i=Kc.decode(o)}catch{return}return rl.test(i)?void 0:{index:t,text:e.slice(t,t+n),repaired:i}}function sl(e,t=Number.POSITIVE_INFINITY){const r=[];let n=0;for(;n240){n++;continue}const o=ol(e,n);void 0!==o?(r.push(o),n+=o.text.length):n++}return r}const il=`[\\u00c2-\\u00f0][\\u0080-\\u00bf${[...Jc.keys()].join("")}]`,al=new RegExp(il),cl=/\p{L}/u;function ll(e,t){const r=e.charCodeAt(t);let n;if(r>=194&&r<=223)n=2;else if(r>=224&&r<=239)n=3;else{if(!(r>=240&&r<=244))return 0;n=4}if(t+n>e.length)return 0;for(let r=1;r=128&&n<=191)&&(n<128||!Jc.has(e[t+r])))return 0}return n}function ul(e,t){if(t.text.length>2)return!0;const r=t.text.charCodeAt(1);if(r>=128&&r<=159)return!0;if(0===t.index||!Xc.test(e[t.index-1]))return!0;const n=t.index+t.text.length;return n0)return"damaged";const n=bl(r);return"utf8"!==n&&"utf8_bom"!==n?"other_encoding":"intact"}function ml(e,t){return e<=t?"existing_only":"new_damage"}function gl(e,t){const r=new Set(t.map((e=>e.text))),n=e.filter((e=>!r.has(e.text))),o=n.length>0?n:e;if(function(e){let t="",r=-1;for(const n of e){if(n.index!==r){if(sl(t,1).length>0)return!0;t=""}t+=n.repaired,r=n.index+n.text.length}return sl(t,1).length>0}(o))return"double";if(1!==new Set(o.map((e=>e.text.length))).size)return"mixed";switch(o[0].text.length){case 2:return"two_byte";case 3:return"three_byte";default:return"four_byte"}}function wl(e){return{detector:e,outcome:"clean",afterCount:0,beforeCount:0}}function yl(e,t,r){const n=sl(r,1e3);if(0===n.length)return wl("mojibake");const o=void 0===e?[]:sl(e,Math.max(n.length,6));return{detector:"mojibake",outcome:ml(n.length,o.length),file:fl(e,o.length,t),afterCount:n.length,beforeCount:o.length,pattern:gl(n,o)}}function vl(e,t,r){const n=di(r);if(0===n)return wl("replacement_chars");const o=void 0===e?0:di(e);return{detector:"replacement_chars",outcome:ml(n,o),file:fl(e,o,t),afterCount:n,beforeCount:o}}function bl(e){if(void 0===e)return"none";const t=e.toLowerCase().replace(/[^a-z0-9]/g,"");return"utf8"===t||"ascii"===t?"utf8":"utf8bom"===t?"utf8_bom":t.startsWith("utf16")?"utf16":"latin1"===t||"iso88591"===t?"latin1":"windows1252"===t||"cp1252"===t?"windows_1252":"gbk"===t||"gb2312"===t||"gb18030"===t||"cp936"===t?"gbk":"shiftjis"===t||"sjis"===t||"cp932"===t||"windows31j"===t?"shift_jis":"euckr"===t||"cp949"===t?"euc_kr":"big5"===t||"big5hkscs"===t||"cp950"===t?"big5":"other"}const Sl=new Map([["md",["md","mdx","markdown"]],["txt",["txt","text","log","rst","adoc","asciidoc","tex"]],["js_ts",["js","jsx","mjs","cjs","ts","tsx","mts","cts"]],["web",["html","htm","xhtml","css","scss","sass","less","vue","svelte","astro"]],["py",["py","pyi","pyw","ipynb"]],["jvm",["java","kt","kts","scala","groovy","gradle"]],["dotnet",["cs","csx","vb","fs","fsx","razor","cshtml","xaml"]],["c_cpp",["c","h","cc","cpp","cxx","c++","hpp","hh","hxx","h++","m","mm"]],["other_code",["go","rs","rb","erb","php","swift","dart","lua","pl","pm","r","ex","exs","erl","hs","clj","cljs","zig","nim","jl","sol","elm","ml","mli","pas","bas"]],["shell",["sh","bash","zsh","fish","ps1","psm1","psd1","bat","cmd"]],["sql",["sql","psql","ddl","dml"]],["config",["json","jsonc","json5","yaml","yml","toml","ini","cfg","conf","env","properties","editorconfig"]],["xml",["xml","xsl","xslt","xsd","svg","csproj","vbproj","fsproj","props","targets","nuspec","plist","storyboard","xib"]],["i18n",["po","pot","strings","stringsdict","arb","xlf","xliff","ftl","resx"]],["csv",["csv","tsv"]]].flatMap((([e,t])=>t.map((t=>[t,e])))));function kl(e){const t=(0,s.extname)(e).slice(1).toLowerCase();return""===t?"none":Sl.get(t)??"other"}const _l=new Map([[1252,"1252"],[1250,"1250"],[1251,"1251"],[874,"874"],[932,"932"],[936,"936"],[949,"949"],[950,"950"],[65001,"65001"]]);function Cl(e){if("string"==typeof e)return e;const t=void 0===e.acp?void 0:_l.get(e.acp);return void 0===t?"other":e.oemcp===e.acp?t:`${t}_split`}function El(e,t){if("clean"===e.outcome)return{detector:e.detector,outcome:"clean",file:"unclassified"};const r={outcome:e.outcome,file:e.file,ext:kl(t.path),encoding:bl(t.encoding),code_page:Cl(t.pages),run_count:hl(e.afterCount),delta:(n=e.afterCount-e.beforeCount,n<0?"neg":pl(n)),before_count:pl(e.beforeCount)};var n;return"mojibake"===e.detector?{detector:"mojibake",pattern:e.pattern,...r}:{detector:"replacement_chars",...r}}class xl{constructor(){this.counts={stdout:0,stderr:0},this.produced={stdout:!1,stderr:!1}}note(e,t){if(0===t.length)return;this.produced[e]=!0;const r=this.counts[e];r>=6||(this.counts[e]=r+di(t,6-r))}labels(e,t){const r=Cl(t),n=[];for(const t of["stdout","stderr"]){if(!this.produced[t])continue;const o=this.counts[t];n.push({detector:"replacement_chars",outcome:o>0?"damaged":"clean",run_count:pl(o),branch:e[t],stream:t,code_page:r})}return n}}const Pl=/[\ud800-\udbff](?![\udc00-\udfff])|(?=e.length||e.startsWith(Ml,r))&&e.startsWith(Ml,r+Ll(e,r)))return!0}return!1}(e)}(e,o))return"utf16";if(r)return"clean";if(!$l.test(e))return"clean";const s=function(e){if(!al.test(e))return;let t=0,r=!1,n=!0,o=0;for(;o=194&&s<=240?ol(e,o):void 0;if(void 0!==i){if(t++,r=ul(e,i),o+=i.text.length,!n||!r&&t>=256)return"medium";continue}const a=n?ll(e,o):0;if(0===a){if(n=!1,t>0)return"medium";o++}else o+=a}return 0!==t?r&&n?"high":"medium":void 0}(e);return void 0!==s?"high"===s?"mojibake_high":"mojibake_medium":Al.test(e)?"c1":"clean"}const Ul=(0,d.h)("local-exec:encoding-slices");function Bl(e,t){if(void 0===e)return!1;try{return"function"==typeof e?e(t):e}catch{return!1}}function Wl(e,t){return Bl(e?.enabled,t)}function Hl(e,t,r=!1){if("clean"===e)return"clean";switch(t){case"utf8_valid":return"lone_surrogate"===e?"new_damage_cut":"existing_only";case"utf8_invalid":return"lone_surrogate"===e?"new_damage_cut":"replacement"!==e?"existing_only":r?"unknown":"not_text";case"utf8_cut":return"lone_surrogate"===e?"new_damage_cut":"replacement"!==e?"existing_only":r?"unknown":"new_damage_cut";case"utf8_as_other":return"new_damage_decode";case"declared_other":return"replacement"!==e||r?"unknown":"new_damage_decode";case"other_encoding":case"unseen":return"unknown";default:return t}}function ql(e){for(let t=1;t<=Math.min(3,e.length);t++){const r=e[e.length-t]??0;if(128!=(192&r))return(r>=240?4:r>=224?3:r>=192?2:1)>t?t:0}return 0}class zl{constructor(){this.seen=!1,this.invalid=!1,this.carry=new Uint8Array(0)}write(e){if(0===e.length)return;if(this.seen=!0,this.invalid)return;const t=this.carry.length>0?Buffer.concat([this.carry,e]):e,r=ql(t);if(!(0,n.isUtf8)(t.subarray(0,t.length-r)))return this.invalid=!0,void(this.carry=new Uint8Array(0));this.carry=r>0?Uint8Array.from(t.subarray(t.length-r)):t.subarray(0,0)}evidence(){return this.seen?this.invalid?"utf8_invalid":this.carry.length>0?"utf8_cut":"utf8_valid":"unseen"}}const Gl=new Map(Object.entries({zsh:"zsh",zsh_light:"zsh_light",bash:"bash",pwsh:"pwsh",powershell51:"powershell51",naive_pwsh:"naive_pwsh",naive_powershell51:"naive_powershell51",naive_bash:"naive_bash",naive_zsh:"naive_zsh",naive_other:"naive_other"})),Vl=(0,h.Pu)("local_exec.encoding_slice",{description:"Results a local executor returned, and results about to be encoded for the wire, by the boundary they were counted at, the kind of encoding damage their text holds (one kind per result, clean included), whose the damage is as far as the bytes at that boundary say, which executor the result came from, the client's version bucket, for a shell result counted on Windows how the code page lookup stood, and for a shell result which shell ran the command",labelNames:["layer","kind","origin","source","version_bucket","code_page_lookup","shell_kind"]}),Kl=Il[0],Jl=new Map(Il.map(((e,t)=>[e,t])));function Zl(e){return Jl.get(e)??Il.length}class Xl{constructor(){this.worst="clean",this.remaining=262144}note(e){this.walk(e,0)}kind(){return this.worst}capped(){return this.remaining<=0}settled(){return this.remaining<=0||this.worst===Kl}noteText(e){if(0===e.length)return;const t=e.length>this.remaining?Jo(e,this.remaining):e;this.remaining-=Math.max(t.length,1);const r=jl(t);Zl(r)=16)return;if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer)return;if(Array.isArray(e)){for(const r of e)if(this.walk(r,t+1),this.settled())return;return}const r=Object.values(e);for(const e of r)if(this.walk(e,t+1),this.settled())return}}class Ql{constructor(e=1024){this.capacity=e,this.counted=new Set}firstRead(e,t){if(""===e)return!0;const r=`${e}\n${t}`,n=this.counted.delete(r);if(this.counted.add(r),this.counted.size>this.capacity)for(const e of this.counted){this.counted.delete(e);break}return!n}}function Yl(e,t,r,n){const o={layer:r.layer,kind:n,origin:Hl(n,r.evidence??"unseen",!0===r.partial),source:r.source??r.layer,version_bucket:Bc(e.clientVersion)};void 0!==r.codePageLookup&&(o.code_page_lookup=r.codePageLookup),void 0!==r.shellKind&&(o.shell_kind=r.shellKind),Vl.increment(t,1,o)}function eu(e,t){Ul.warn(e,"encoding slice was not counted (result unaffected)",{error:t instanceof Error?t.name:"unknown"})}function tu(e,t,r,n){if(void 0!==e&&Wl(e,t))try{const o=new Xl;o.note(n),Yl(e,t,r,o.kind())}catch(e){eu(t,e)}}function ru(e,t,r,n){if(void 0!==e&&Wl(e,t))try{Yl(e,t,r,n)}catch(e){eu(t,e)}}class nu{constructor(){this.seen=!1,this.invalid=!1}note(e){this.seen=!0,this.invalid||(0,n.isUtf8)(e)||(this.invalid=!0)}evidence(){return this.seen?this.invalid?"utf8_invalid":"utf8_valid":"unseen"}}function ou(e,t,r,n){return void 0===t?e:{execute:async(o,s,i)=>{const a=await e.execute(o,s,i);if(Wl(t,o))try{n(a)&&tu(t,o,{layer:r},a)}catch(e){eu(o,e)}return a}}}new Map([["readArgs","exec_read"],["redactedReadArgs","exec_read"],["grepArgs","exec_grep"],["mcpArgs","exec_mcp"],["readMcpResourceExecArgs","exec_mcp"],["executeHookArgs","exec_hooks"],["fetchArgs","exec_web_fetch"],["shellArgs","exec_shell"],["shellStreamArgs","exec_shell"],["backgroundShellSpawnArgs","exec_shell"],["miniSweAgentBashArgs","exec_shell"],["writeArgs","exec_write"]]);class su{constructor(){this.text={stdout:new Xl,stderr:new Xl},this.bytes={stdout:new zl,stderr:new zl},this.produced={stdout:!1,stderr:!1},this.dropped={stdout:!1,stderr:!1},this.shellKind="unknown"}noteBytes(e,t){this.bytes[e].write(t)}noteText(e,t){0!==t.length&&(this.produced[e]=!0,this.text[e].note(t))}noteDropped(e){this.dropped[e]=!0}noteShell(e){this.shellKind=function(e){return"string"!=typeof e?"unknown":Gl.get(e)??"unknown"}(e)}record(e,t,r,n){for(const o of["stdout","stderr"])this.produced[o]&&ru(e,t,{layer:"exec_shell",evidence:this.evidence(o,r[o]),partial:this.dropped[o]||this.text[o].capped(),codePageLookup:n,shellKind:this.shellKind},this.text[o].kind())}evidence(e,t){if("utf8"!==t)return"other_encoding";const r=this.bytes[e].evidence();return"utf8_cut"===r?"utf8_invalid":r}}var iu=r("node:child_process"),au=r("../utils/dist/workload-spawn.js");const cu=(0,d.h)("local-exec:shell-output-encoding"),lu=(0,Vs.promisify)(iu.execFile),uu=/^\s*OEMCP\s+REG_\w+\s+(\d+)\s*$/m,du=/^\s*ACP\s+REG_\w+\s+(\d+)\s*$/m;function hu(e,t){const r=t.exec(e);return null===r?void 0:Number(r[1])}const pu="㐀-䶿一-鿿豈-﫿",fu=" -〿㈀-㏿︰-﹯＀-￯",mu="‐-※←-⇿─-◿★☆",gu="぀-ヿ",wu=new Map([["cp932",{script:new RegExp(`[${pu}${fu}${mu}${gu}]`),doubleByte:!0}],["cp936",{script:new RegExp(`[${pu}${fu}${mu}${gu}㄀-ㄯ]`),doubleByte:!0}],["cp949",{script:new RegExp(`[${pu}${fu}${mu}${gu}㄰-㆏가-힯]`),doubleByte:!0}],["cp950",{script:new RegExp(`[${pu}${fu}${mu}㄀-ㄯ]`),doubleByte:!0}],["cp874",{script:new RegExp("[฀-๿]"),doubleByte:!1}]]);const yu=function(e){let t,r,n,o,s=!1,i=0;const a=()=>{i+=1;const e=i;n=async function(){const{stdout:e}=await(0,au.D9)(lu,"\\\\.\\GLOBALROOT\\SystemRoot\\System32\\reg.exe",["query","HKLM\\SYSTEM\\CurrentControlSet\\Control\\Nls\\CodePage"],{encoding:"buffer",timeout:3e3,windowsHide:!0});return e}().then((e=>{const i=function(e){const t=Buffer.isBuffer(e)?function(e){return e.length>=2&&255===e[0]&&254===e[1]?e.subarray(2).toString("utf16le"):e.includes(0)?e.toString("utf16le"):e.toString("latin1")}(e):e,r={},n=hu(t,uu),o=hu(t,du);return void 0!==n&&(r.oemcp=n),void 0!==o&&(r.acp=o),r}(e);t=function(e){const{oemcp:t,acp:r}=e;if(void 0===t||void 0===r||t!==r)return;const n=function(e){if(65001===e)return;const t=`cp${e}`;return Js.encodingExists(t)?t:void 0}(t);return void 0!==n&&wu.has(n)?n:void 0}(i),r=i,s=!0,n=void 0,o=void 0===i.oemcp&&void 0===i.acp?"unparsed":"answered",cu.info((0,b.q6)(),"Resolved the fallback encoding for shell output",{encoding:t??"none",oemcp:i.oemcp??"none",acp:i.acp??"none"})}),(t=>{n=void 0,o=function(e){try{if("object"!=typeof e||null===e)return"spawn_error";const t="code"in e?e.code:void 0;return"killed"in e&&!0===e.killed&&"string"!=typeof t?"timeout":"number"==typeof t?"nonzero_exit":"spawn_error"}catch{return"spawn_error"}}(t),cu.warn((0,b.q6)(),"Could not read the Windows code pages; shell output stays UTF-8 only",{error:t instanceof Error?t.message:String(t),attempt:e})}))};return"win32"===e&&a(),{current:()=>("win32"===e&&!s&&void 0===n&&i<3&&a(),t),pages:()=>void 0!==r?r:"win32"!==e?"none":i>=3&&void 0===n?"failed":"pending",lastOutcome:()=>"win32"===e?o??"pending":void 0,settled:()=>n??Promise.resolve()}}(process.platform),vu=Buffer.alloc(0),bu=/[\u0080-\uffff]/;function Su(e){const t=Math.max(0,e.length-3);for(let r=e.length-1;r>=t;r--){const t=e[r];if(128==(192&t))continue;const n=t>=248?1:t>=240?4:t>=224?3:t>=192?2:1,o=e.length-r;return n>o?o:0}return 0}function ku(){const e=new ca.StringDecoder("utf8");return{write:t=>e.write(t),end:()=>e.end()}}function _u(e,t){return Js.decode(t,e,{stripBOM:!1})}const Cu=/[\xe0-\xef][\x80-\xbf]\?/;const Eu=10,xu=Buffer.alloc(0),Pu=new Set([7,8,9,10,11,12,13,27]);function Ru(e,t,r){for(let n=0;n+1(r=void 0,t.end())}}const Au={encoding:"utf8",skip:0};function $u(e){const t=e();let r="utf8";const n={};let o=!1;const s=()=>"utf8"===r?t:n[r]??=Tu(r),i=e=>("utf8"!==r&&e.length>0&&(o=!0),e);let a,c=!0,l=xu,u=!1,d=0;const h=(e,t)=>{const n=function(e){if(!(e.length<2))return 255===e[0]&&254===e[1]?"utf16le":254===e[0]&&255===e[1]?"utf16be":void 0}(e);if(void 0!==n)return{encoding:n,skip:2};if("utf8"===r){if(e.length<2)return t?Au:void 0;const r=0===e[0]?"utf16be":0===e[1]?"utf16le":void 0;if(void 0===r)return Au;const n=Iu(e,r);if(-1!==n)return Ru(e,r,n)?{encoding:r,skip:0}:Au;if(!t)return;const o=e.length-e.length%2;return function(e,t){const r="utf16le"===t?1:0;for(let t=0;te.length?t?o:void 0:Ru(e,r,n)?o:Au}if(-1===i)return t?Au:void 0;if("utf16le"===r&&i%2==0){if(i+1>=e.length)return t?Au:void 0;if(0===e[i+1])return o}return Au},p=e=>{if(e===r)return"";const t=i(s().end());return r=e,t},f=e=>"utf8"===r&&0!==e&&e<128,m=(e,n)=>{let o="",m=e;for(;;){if(c){const e=Math.min(m.length,512-l.length);let r;if(r=l.length>0?Buffer.concat([l,m.subarray(0,e)]):e===m.length?m:m.subarray(0,e),0===r.length)return o;const s=h(r,n||r.length>=512);if(void 0===s)return 1===r.length&&f(r[0])&&(o+=t.write(r),u=!0),l=Buffer.from(r),o;let i=s.skip,g=!1;if(u&&(i="utf8"===s.encoding?1:2,g=r[0]===Eu,u=!1),0===l.length)i>0&&(m=m.subarray(i));else{const t=r.subarray(i);m=m.subarray(e),m=0===m.length?t:0===t.length?m:Buffer.concat([t,m]),l=xu}if(c=g,d=0,a=void 0,o+=p(s.encoding),g)continue}if(0===m.length)return o;if("utf8"===r&&!m.includes(0)&&!m.includes(254)&&!m.includes(255)){const e=m.lastIndexOf(Eu),r=-1===e?-1:m.length-e-1;if(-1===r||r>=2)return o+t.write(m);if(c=!0,0===r)return e>0&&m[e-1]===Eu&&(l=Buffer.of(Eu),u=!0),o+t.write(m);const n=m[m.length-1];return l=Buffer.of(n),u=f(n),o+t.write(u?m:m.subarray(0,e+1))}const e=Iu(m,r,d,a);if(-1===e)return d+=m.length,a=m[m.length-1],o+i(s().write(m));o+=i(s().write(m.subarray(0,e))),m=m.subarray(e),c=!0}};return{write:e=>0===e.length?s().write(e):m(e,!1),peek(){if(!c||0===l.length)return"";const t=h(l,!0);if(void 0===t)return"";const r=u?"utf8"===t.encoding?1:2:t.skip,n=l.subarray(r);return 0===n.length?"":"utf8"===t.encoding?e().write(n):Tu(t.encoding).write(n)},end(){const e=m(xu,!0)+i(s().end());return c=!0,l=xu,u=!1,d=0,a=void 0,e},branch:()=>!0===t.usedCodePage?.()?"code_page":o?"utf16":"utf8"}}var Mu=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Du=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Ou=(0,d.h)("local-exec:shell-core"),Fu=(0,h.Pu)("local_exec.shell.encoding_check",{description:"Shell command output streams that produced text, per encoding detector (U+FFFD): whether the decoded text holds the pattern and how much, which decode path (UTF-8, Windows code page, UTF-16) produced it, which stream, and the machine's Windows code page",labelNames:["detector","outcome","run_count","branch","stream","code_page"]}),Nu="win32"===process.platform,Lu=["CURSOR_CONVERSATION_ID","CURSOR_REQUEST_ID","CURSOR_AGENT_STORE_FILES_DIR","CURSOR_AGENT_STORE_SHARED_PATHS"];function ju(e){return`'${e.replace(/'/g,"'\\''")}'`}async function Uu(e){try{return(await(0,xo.stat)(e)).isDirectory()}catch(e){const t=_c(e);if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}const Bu=["eval-cursorbench","cursorbench","sand-eval","eval-harness"];function Wu(e){return Bu.some((t=>e.includes(t)))?(0,ko.createHash)("sha256").update(e).digest("hex"):e}function Hu(e,t){return e[t]??process.env[t]}const qu=/^[A-Za-z_][A-Za-z0-9_]*$/,zu=/CURSOR_SANDBOX/i;function Gu(e){return qu.test(e)&&!zu.test(e)}function Vu(e){return"function"==typeof e?e():e}function Ku(e,t){const r=void 0===e?[]:[...e];return r.includes(t)||r.push(t),r}function Ju(e){let t=0,r=0;const n=e.length;for(;r"insecure_none"===e?.type?void 0:e?.privateTmp)).find((e=>void 0!==e));if("linux"!==process.platform||!0!==n||void 0===r||!(0,ts.ZU)({basePath:"/tmp",targetPath:e}))return!1;const o=(0,No.W1)(r);return void 0!==o&&await Uu(s.join(o,"tmp",s.relative("/tmp",e)))}(c,t.sandboxPolicy,this.workspacePath))){if(c!==(0,ts.o1)(await i.getCwd(),this.workspacePath))throw new Zu(c);return yield{type:"stderr",data:`The shell's working directory no longer exists: ${c}. The command did not run. Re-run it with working_directory set to an existing directory.\n`},void(yield{type:"exit",code:1,aborted:!1,localExecutionTimeMs:Math.round(performance.now()-o)})}let l,u,d=0,h=0,p=!1,f=!1,m=!1;t.fileOutputThresholdBytes&&this.projectDir&&(l={buffer:"",lineCount:0,size:0,threshold:Number(t.fileOutputThresholdBytes)});const g=t.signal,w={CURSOR_AGENT:"1"};t.conversationId&&(w.CURSOR_CONVERSATION_ID=(0,_o.sh)(t.conversationId)),t.requestId&&(w.CURSOR_REQUEST_ID=t.requestId),this.projectDir&&(w.AGENT_TRANSCRIPTS=s.join(this.projectDir,_o.O2));const y=this.options.extraEnvProvider?.(e,t);void 0!==y&&Object.assign(w,y);const v=t.requestScopedEnv??{};for(const[e,t]of Object.entries(v))void 0!==t&&Gu(e)&&(w[e]=t);const b=w.CURSOR_REQUEST_ID;void 0!==b&&(w.CURSOR_REQUEST_ID=Wu(b)),function(e,t){const r=Lu,n=Object.keys(t).filter((e=>Gu(e)&&!r.includes(e))),o=`builtin unset ${[...Lu,...n].join(" ")} 2>/dev/null || true`,s=[];for(const t of Lu){const r=Hu(e,t);void 0!==r&&s.push(`builtin export ${t}=${ju(r)}`)}for(const e of n){const r=t[e];void 0!==r&&s.push(`builtin export ${e}=${ju(r)}`)}const i=e.__CURSOR_SANDBOX_ENV_RESTORE?.trim(),a=process.env.__CURSOR_SANDBOX_ENV_RESTORE?.trim();e.__CURSOR_SANDBOX_ENV_RESTORE=[o,a,i,...s].filter((e=>void 0!==e&&""!==e)).join("; ")}(w,v),void 0!==w.__CURSOR_SANDBOX_ENV_RESTORE&&(w.__CURSOR_SANDBOX_ENV_RESTORE=function(e,t){let r=e;for(const e of t){if(null==e||0===e.length)continue;const t=Wu(e);t!==e&&(r=r.split(e).join(t))}return r}(w.__CURSOR_SANDBOX_ENV_RESTORE,[t.requestId,b,v.CURSOR_REQUEST_ID,process.env.CURSOR_REQUEST_ID]));const S=function(e,t){const r=Hu(t,"CURSOR_AGENT_STORE_FILES_DIR"),n=function(e){if(void 0===e)return[];try{const t=JSON.parse(e);if("object"!=typeof t||null===t)return[];const r=[];for(const e of Object.values(t))"object"==typeof e&&null!==e&&"path"in e&&"readOnly"in e&&"string"==typeof e.path&&"boolean"==typeof e.readOnly&&r.push({path:e.path,readOnly:e.readOnly});return r}catch{return[]}}(Hu(t,"CURSOR_AGENT_STORE_SHARED_PATHS"));if(void 0===r&&0===n.length)return e;const o=e?.perUser,s=e?.perRepo??e?.perUser??e?.teamAdmin;if("workspace_readwrite"!==s?.type&&"workspace_readonly"!==s?.type)return e;const i=o?.type===s.type?{...o}:{type:s.type};var a;void 0!==r&&(a=r,"workspace_readwrite"!==i.type?i.additionalReadonlyPaths=Ku(i.additionalReadonlyPaths,a):i.additionalReadwritePaths=Ku(i.additionalReadwritePaths,a));for(const e of n)e.readOnly||"workspace_readwrite"!==i.type?i.additionalReadonlyPaths=Ku(i.additionalReadonlyPaths,e.path):i.additionalReadwritePaths=Ku(i.additionalReadwritePaths,e.path);return{...e,perUser:i}}(t.sandboxPolicy,w),k=(0,No.CG)(S??No.BM);let _,C,E,x;S&&(yield{type:"start",sandboxed:"workspace_readonly"===k||"workspace_readwrite"===k}),t.askpassConfig&&!Nu&&(w.SUDO_ASKPASS=t.askpassConfig.helperPath,w.CURSOR_ASKPASS_SOCKET=t.askpassConfig.socketPath,w.CURSOR_ASKPASS_SECRET=t.askpassConfig.secret);const P=this.options.codePageLookup??yu,R=(this.options.outputFallbackEncoding??(()=>P.current()))(),I=()=>function(e){if(void 0===e)return ku();const t=wu.get(e);return void 0!==t&&Js.encodingExists(e)?function(e,t){const{script:r}=t,o=function(e){const{script:t}=e,r=new RegExp(`${t.source}{2}`);let n=!1,o=!1,s=!1;return{note(i,a){if(!s&&0!==i.length){if(!n){const e=bu.exec(i);null!==e&&(n=!0,s=t.test(e[0]))}s||=o&&t.test(i[0])||r.test(i)||e.doubleByte&&void 0!==a&&Cu.test(a.toString("latin1")),o=t.test(i[i.length-1])}},isUtf8Text:()=>s,reset(){n=!1,o=!1,s=!1}}}(t);let s=vu,i=0,a="utf8",c=!1;const l=()=>{a="utf8",o.reset(),i=0},u=(t,n)=>{const s=n?Su(t):0,l=t.subarray(0,t.length-s),u=l.toString("utf8");if("replacement"!==a){const t=l.subarray(i);if(i=0,o.note(t.toString("utf8"),t),o.isUtf8Text())a="replacement";else{const t=0===u.length?"":u[u.length-1],o=n&&r.test(t)?Buffer.byteLength(t):0,d=function(e,t,r){let n=_u(e,t);if(!r)return{text:n,keep:0};const o=Math.min(3,t.length);let s=0;for(;s0&&(c=!0),{text:d.text,keep:i+s}}}return{text:u,keep:s}};return{write:e=>{const t=0===s.length?e:Buffer.concat([s,e]);if(s=vu,"utf8"===a){const e=t.subarray(0,t.length-Su(t));if((0,n.isUtf8)(e)){e.length{const t=e.lastIndexOf("\n");-1===t?o.note(e):(l(),o.note(e.slice(t+1)))})(r),r}}let r="",i=0;for(;i0&&(s=Buffer.from(d.subarray(u.length))),-1===e?o.note(n):l(),i=c;continue}a="undecided"}const{text:h,keep:p}=u(d,-1===e);r+=h,p>0&&(s=Buffer.from(d.subarray(d.length-p))),-1!==e&&l(),i=c}return r},end:()=>{const e=s;s=vu;const t=0===e.length?"":"utf8"===a?e.toString("utf8"):u(e,!1).text;return l(),t},usedCodePage:()=>c}}(e,t):ku()}(R),T={stdout:$u(I),stderr:$u(I)},A=new xl,$=Wl(this.options.encodingSlices,e)?new su:void 0,M=void 0===$?void 0:function(e,t,r){return n=>{try{const o=function(e,t,r){if(!(Object.hasOwn(Hc,e.shell)&&Object.hasOwn(qc,e.parse)&&Object.hasOwn(zc,e.stateFile)&&Object.hasOwn(Gc,e.exit)))return;let n="withheld";if(r){if("function"!=typeof e.callsExit)return;n=!0===e.callsExit()?"yes":"no"}return{shell_kind:e.shell,parse:e.parse,calls_exit:n,state_file:e.stateFile,exit:e.exit,version_bucket:Bc(t)}}(n,t,r);if(void 0===o)return;Vc.increment(e,1,{...o})}catch(t){Wc.warn(e,"PowerShell run was not counted (command unaffected)",{error:t instanceof Error?t.name:"unknown"})}}}(e,this.options.encodingSlices?.clientVersion,function(e,t){return!0===Bl(e?.commandTextReadable,t)}(this.options.encodingSlices,e));let O=!1;const F=()=>{if(!O){O=!0;try{const t={stdout:T.stdout.branch(),stderr:T.stderr.branch()};for(const r of A.labels(t,P.pages()))Fu.increment(e,1,r);$?.record(this.options.encodingSlices,e,t,P.lastOutcome())}catch(t){Ou.warn(e,"shell output encoding check failed (command result unaffected)",{error:t instanceof Error?t.message:String(t)})}}},N=e=>{void 0!==l&&0!==e.length&&(l.file?l.file.write(e):l.buffer+=e)},L=function*(){const e={stdout:p,stderr:f};for(const t of["stdout","stderr"]){const r=T[t].end();if(0===r.length)continue;const n=void 0!==l&&!0!==l.truncated;n&&N(r),!n&&e[t]||(A.note(t,r),$?.noteText(t,r)),e[t]||(yield{type:t,data:r})}F()};try{for await(const r of i.execute(e,t.command,{signal:g,workingDirectory:c,env:w,sandboxPolicy:S,sandboxWorkspaceRoot:this.workspacePath,pipeStdin:t.pipeStdin??!1,keepBackgroundJobs:this.options.keepBackgroundJobs??!1,bufferOutputEvents:this.options.shellOutputBackpressureOptions?.bufferOutputEvents,outputLimiterOptions:this.options.shellOutputBackpressureOptions?.outputLimiterOptions,powershellUtf8Console:Vu(this.options.powershellUtf8Console),powershellUtf8ChildEnv:Vu(this.options.powershellUtf8ChildEnv),powershellParseAfterUtf8Switch:Vu(this.options.powershellParseAfterUtf8Switch),powershellWebRequestUtf8:Vu(this.options.powershellWebRequestUtf8),powershellPerLineStateDump:Vu(this.options.powershellPerLineStateDump),...void 0===M?{}:{powershellRunObserver:M}})){_=0,C="",E="",x="";let e=!1,t=!1;if("stdout"===r.type||"stderr"===r.type){const n=T[r.type],o="stdout"===r.type?p:f,i=void 0===l||!0===l.truncated;let a=!1;if(!o||!i){_=r.data.length;const c="stdout"===r.type?d:h,p=!o&&c+_<=os,f=void 0!==l&&!0!==l.truncated&&l.size+_<=Oc;"stdout"===r.type?e=p:t=p;const m=!o&&!p,g=!i&&!f;if((m||g)&&(x=n.peek(),g&&N(x),m&&(E=x)),(p||f)&&(C=n.write(r.data),a=!0,A.note(r.type,C),$?.noteBytes(r.type,r.data),$?.noteText(r.type,C)),void 0!==l&&l.size+_>Oc)l.truncated=!0;else if(f&&void 0!==l)if(l.size+=_,l.lineCount+=Ju(r.data),l.file)l.file.write(C);else if(l.buffer+=C,l.size>l.threshold){const e=s.join(this.projectDir,Dc);l.path=s.join(e,`${(0,ko.randomUUID)()}.txt`);try{await(0,xo.mkdir)(e,{recursive:!0}),l.file=(0,Ro.createWriteStream)(l.path),l.file.on("error",(e=>{u??=e})),l.file.write(l.buffer)}catch(e){u??=e instanceof Error?e:new Error(String(e)),l.truncated=!0}l.buffer=""}}a||(n.end(),A.note(r.type,x),$?.noteDropped(r.type),$?.noteText(r.type,x))}switch(r.type){case"stdout":e?(d+=_,C&&(yield{type:"stdout",data:C})):p||(E&&(yield{type:"stdout",data:E}),p=!0,yield{type:"stdout_trimmed"});break;case"suppressed_output":m||(m=!0,yield{type:"stdout",data:No.Ls});break;case"stderr":t?(h+=_,C&&(yield{type:"stderr",data:C})):f||(E&&(yield{type:"stderr",data:E}),f=!0,yield{type:"stderr_trimmed"});break;case"exit":{yield*L();const e=Math.max(0,Math.round(performance.now()-o));let t;if(l?.file){if(l.truncated){const e=`\n... (output truncated at ${l.size} bytes) ...\n`;l.file.write(e),l.size+=e.length,l.lineCount+=Xs(e)-1}const e=await new Promise((e=>l.file.end(e)));u??=e??void 0,u?await(0,xo.rm)(l.path,{force:!0}):t=new Fc.pV({filePath:l.path,sizeBytes:BigInt(l.size),lineCount:BigInt(l.lineCount)})}u&&void 0!==l?.path&&(yield{type:"stderr",data:`\nThe full output could not be saved to ${l.path}: ${u.message}\n`}),yield{type:"exit",code:r.code,signal:r.signal,aborted:r.aborted,outputLocation:t,localExecutionTimeMs:e};break}case"stdin_ready":$?.noteShell(r.shell),yield{type:"stdin_ready",stdin:r.stdin,pid:r.pid};break;case"sandbox_denies":yield{type:"sandbox_denies",events:r.events}}}yield*L()}catch(t){if("ENOENT"===_c(t)&&(0,Gs.$f)(c))try{Ou.warn(e,"shell failed with ENOENT in an agent store working directory",{...await(0,Gs.KZ)(c)})}catch{}throw t}finally{F()}}catch(e){r.error=e,r.hasError=!0}finally{Du(r)}}async getCwd(e){return this.executorFor(e).getCwd()}getWorkspacePath(){if(!this.workspacePath)throw new Error("Workspace path is not configured");return this.workspacePath}}class Qu{constructor(e,t){this.innerExecutor=e,this.shellManager=t}async*execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{Mu(r,(0,D.VI)(e.withName("ManagedShellCoreExecutor.execute")),!1),Ou.info(e,"Executing shell command",{command:t.command,workingDirectory:t.workingDirectory,toolCallId:t.toolCallId});let n=null;t.toolCallId&&(n=this.shellManager.getOrCreateShellEmitter(t.toolCallId));for await(const r of this.innerExecutor.execute(e,t)){if(n)switch(r.type){case"stdin_ready":n.emit({type:"stdin_ready",stdin:r.stdin,pid:r.pid});break;case"start":n.emit({type:"start",sandboxed:r.sandboxed});break;case"stdout":n.emit({type:"stdout",data:r.data});break;case"stderr":n.emit({type:"stderr",data:r.data});break;case"exit":n.emit({type:"exit",code:r.code??-1,aborted:r.aborted})}yield r}}catch(e){r.error=e,r.hasError=!0}finally{Du(r)}}async getCwd(e){return this.innerExecutor.getCwd(e)}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}class Yu{constructor(e,t){this.innerExecutor=e,this.askpassConfig=t}async*execute(e,t){const r={...t,askpassConfig:t.askpassConfig??this.askpassConfig};yield*this.innerExecutor.execute(e,r)}async getCwd(e){return this.innerExecutor.getCwd(e)}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}async function ed(e,t){switch(e.type){case"needsApproval":return t.onNeedsApproval(e.approvalReason,e.approvalDetails);case"userRejected":return t.onUserRejected(e.reason);case"cursorIgnore":return t.onPermissionDenied("Blocked by cursor ignore");case"permissionsConfig":return t.onPermissionDenied("Blocked by permissions configuration",{isReadonly:e.isReadonly});case"cursorFiles":return t.onPermissionDenied("Blocked by cursor files protection");case"adminBlock":return t.onPermissionDenied("Blocked by admin repository block");case"adminCommandDenylist":return t.onPermissionDenied(_s(e.pattern));case"unsafeResolution":return t.onPermissionDenied(e.message);default:{const t=e;throw new Error(`Unhandled block reason type: ${JSON.stringify(t)}`)}}}function td(e){switch(e.type){case"userRejected":return e.reason;case"unsafeResolution":return e.message;case"adminCommandDenylist":return _s(e.pattern);case"needsApproval":case"cursorIgnore":case"adminBlock":case"permissionsConfig":case"cursorFiles":return"Command is not allowed";default:{const t=e;return`Command is not allowed (${JSON.stringify(t)})`}}}function rd(e,t,r){return"permissionsConfig"===r.type?{case:"permissionDenied",value:new fe.jn({command:e,workingDirectory:t,error:"Command blocked by permissions configuration",isReadonly:r.isReadonly??!1})}:{case:"rejected",value:new fe.pZ({command:e,workingDirectory:t,reason:td(r)})}}var nd=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const od=(0,d.h)("local-exec:background-shell");function sd(e,t,r){return new Fo.Lt({result:rd(e,t,r)})}class id{constructor(e,t){this.id=e,this.abortController=t,this.disposed=!1,this.completed=!1,this.completionListeners=[]}abort(){this.abortController.abort()}dispose(){this.disposed||(this.disposed=!0,this.abortController.signal.aborted||this.abortController.abort())}get signal(){return this.abortController.signal}isDisposed(){return this.disposed}onComplete(e){this.completed&&this.completion?e(this.completion):this.completionListeners.push(e)}markCompleted(e){if(this.completed)return;this.completed=!0,this.completion=e;const t=[...this.completionListeners];this.completionListeners=[];for(const r of t)r(e)}}async function ad(e,t){let r;try{for(let n=await t.next();!n.done;n=await t.next())"stdin_ready"===n.value.type?(e.stdin=n.value.stdin,e.pid=n.value.pid):"exit"===n.value.type&&(r={code:n.value.code,signal:n.value.signal,aborted:n.value.aborted,outputPath:n.value.outputLocation?.filePath})}catch(e){}finally{e.markCompleted(r??{code:null,aborted:e.signal.aborted})}}function cd(e){e().catch((()=>{}))}class ld{constructor(e){if(this.args=e,this.carryover="",this.matchedOccurrences=0,this.emittedNotifications=0,this.finished=!1,this.monotonicStartMs=performance.now(),this.limit=e.config.notificationLimit??100,e.config.pattern.length>500)throw new Error("Output notification pattern exceeds 500 characters");this.regex=es.L3.compile(e.config.pattern,es.L3.MULTILINE)}observe(e){if(this.finished||this.matchedOccurrences>=this.limit||0===e.length)return;if(e.length>65536){for(const t of function(e){if(0===e.length)return[];const t=Math.max(1,Math.trunc(65536)||1),r=[];let n=0;for(;n=this.limit)break;this.observe(t)}return}const t=this.carryover.length,r=`${this.carryover}${e}`,n=this.regex.matcher(r);for(;this.matchedOccurrencest&&this.queueMatch(e)}this.carryover=Zo(r,1024)}finish(){this.finished||(this.finished=!0,this.flushPendingBatch("finish"),this.clearFlushTimer(),0===this.matchedOccurrences&&this.recordWatchOutcome("silent",{silent_ms:hd(this.monotonicStartMs)}))}queueMatch(e){if(this.matchedOccurrences>=this.limit)return;this.matchedOccurrences+=1;const t=this.matchedOccurrences,r=function(e,t){return e.length<=5e3?`${t}: ${e}`:`${t} is ${e.length} characters; omitted from notification detail.`}(e,1===t?"Matched text":"Latest match");return 1===t?(this.emitNotification({startOccurrence:t,endOccurrence:t,count:1,matchedTextDetail:r}),this.recordWatchOutcome("matched",{first_match_ms:hd(this.monotonicStartMs)}),void(t===this.limit&&this.emitLimitReachedNotification())):(this.pendingBatch?(this.pendingBatch.endOccurrence=t,this.pendingBatch.count+=1,this.pendingBatch.matchedTextDetail=r):this.pendingBatch={startOccurrence:t,endOccurrence:t,count:1,matchedTextDetail:r},t===this.limit?(this.flushPendingBatch("limit"),void this.emitLimitReachedNotification()):void this.scheduleFlush())}scheduleFlush(){if(void 0!==this.flushTimer)return;const e=this.getDebounceMs();this.flushTimer=setTimeout((()=>{this.flushPendingBatch("debounce")}),e)}getDebounceMs(){const e=this.args.debounceMs??function(e){const t=e.debounce;if(void 0!==t&&Number.isFinite(t))return Math.ceil(1e3*t)}(this.args.config)??5e3;return Math.max(e,5e3)}clearFlushTimer(){void 0!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0)}flushPendingBatch(e){const t=this.pendingBatch;t&&(this.pendingBatch=void 0,this.clearFlushTimer(),this.emitNotification(t))}emitNotification(e){this.emittedNotifications+=1;const t=this.args.config.reason.trim()||`Shell output contains /${this.args.config.pattern}/`,r=this.args.config.pattern,n=void 0!==e.matchedTextDetail?` ${e.matchedTextDetail}.`:"",o=1===e.count?`Shell output has pattern /${r}/. This is occurrence number ${e.startOccurrence}.${n} The title message is being displayed to the user.`:`Shell output matched /${r}/ ${e.count} more times since the previous notification. The title message is being displayed to the user.${n}`,s=To(String(this.args.shellId),this.emittedNotifications);var i;this.args.registry.enqueue({conversationId:this.args.conversationId,id:s,source:"shell",payload:{taskId:s,...void 0!==this.args.toolCallId?{toolCallId:this.args.toolCallId}:{},kind:"shell",status:"success",title:(i=t,i.length<=500?i:`${Jo(i,500)}...`),detail:o,outputPath:this.args.outputPath,reason:"task_progress"}})}emitLimitReachedNotification(){this.emittedNotifications+=1;const e=this.args.config.pattern,t=To(String(this.args.shellId),this.emittedNotifications);this.args.registry.enqueue({conversationId:this.args.conversationId,id:t,source:"shell",payload:{taskId:t,...void 0!==this.args.toolCallId?{toolCallId:this.args.toolCallId}:{},kind:"shell",status:"success",title:`Notification limit reached (${this.limit})`,detail:`Shell output matched /${e}/ ${this.limit} times and has reached the notification limit. No further notifications will be sent for this pattern. To continue monitoring, read the output file directly at the output path.`,outputPath:this.args.outputPath,reason:"task_progress"}}),this.recordWatchOutcome("limit_reached")}recordWatchOutcome(e,t){void 0!==this.args.ctx&&od.info(this.args.ctx,"agent.shell_output_notification_match",{event:"agent.shell_output_notification_match",outcome:e,shell_id:this.args.shellId,conversation_id:this.args.conversationId,tool_call_id:this.args.toolCallId,limit:this.limit,...t})}}class ud{constructor(e,t,r){this.innerFactory=e,this.projectDir=t,this.backgroundWorkRegistry=r}async spawn(e,t){const r=this.createObserver(e.ctx,e.shellId,e.conversationId,e.toolCallId,e.outputNotification);if(!r)return this.innerFactory.spawn(e,t);try{return await this.innerFactory.spawn(e,this.createObservingExecutor(t,r))}catch(e){throw r.finish(),e}}async adopt(e){const t=this.createObserver(e.ctx,e.shellId,void 0,e.toolCallId,e.outputNotification);if(!t)return this.innerFactory.adopt(e);e.initialOutput.length>0&&t.observe(e.initialOutput);try{return await this.innerFactory.adopt({...e,eventIterator:this.createObservingIterator(e.eventIterator,t)})}catch(e){throw t.finish(),e}}createObserver(e,t,r,n,o){if(!this.backgroundWorkRegistry||!o)return;if(0===o.pattern.trim().length)return;const i=s.join(this.projectDir,"terminals",`${t}.txt`);try{return new ld({shellId:t,outputPath:i,config:o,conversationId:r??Io,toolCallId:n,registry:this.backgroundWorkRegistry,ctx:e})}catch(r){return void(void 0!==e&&od.warn(e,"Invalid shell output notification pattern",{shellId:t,error:r instanceof Error?r.message:String(r)}))}}createObservingExecutor(e,t){const r=e.execute.bind(e);return{...e,execute:async function*(e,n){try{for await(const o of r(e,n))"stdout"===o.type||"stderr"===o.type?t.observe(o.data):"exit"===o.type&&t.finish(),yield o}finally{t.finish()}}}}createObservingIterator(e,t){const r=e.return?.bind(e);return{next:async()=>{try{const r=await e.next();if(r.done)t.finish();else{const e=r.value;"stdout"===e.type||"stderr"===e.type?t.observe(e.data):"exit"===e.type&&t.finish()}return r}catch(e){throw t.finish(),e}},return:async e=>(t.finish(),r?r(e):{done:!0,value:void 0})}}}class dd{async spawn(e,t){const r=new AbortController,n=new id(e.shellId,r),o=t.execute(e.ctx,{command:e.command,workingDirectory:e.workingDirectory,signal:r.signal,toolCallId:e.toolCallId,conversationId:e.conversationId,requestId:e.requestId,secretScopeId:e.secretScopeId,sandboxPolicy:e.sandboxPolicy,pipeStdin:e.enableWriteShellStdinTool,showElapsedTime:!0})[Symbol.asyncIterator]();try{for(let e=await o.next();!e.done;e=await o.next())if("stdin_ready"===e.value.type){n.stdin=e.value.stdin,n.pid=e.value.pid;break}}catch(e){if(e instanceof No.SandboxUnsupportedError||e instanceof Zu)throw e}return cd((()=>ad(n,o))),n}async adopt(e){const t=new id(e.shellId,e.abortController);return t.stdin=e.stdin,t.pid=e.pid,cd((()=>ad(t,e.eventIterator))),t}}function hd(e){return Math.round(performance.now()-e)}function pd(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}function fd(e){const t=String(e.runningForMs).padEnd(9," "),r=e.status.padEnd(9," ");let n="---\n";return void 0!==e.pid&&0!==e.pid&&(n+=`pid: ${e.pid}\n`),n+=`cwd: ${pd(e.cwd)}\n`,n+=`command: ${pd(e.command)}\n`,void 0!==e.title&&e.title.trim().length>0&&(n+=`title: ${pd(e.title)}\n`),n+=`status: ${r}\n`,n+=`started_at: ${e.startedAt}\n`,n+=`running_for_ms: ${t}\n`,n+="---\n",n}function md(e){return`\n[${e} truncated by cursor: the command wrote more than 1048576 characters to ${e}; only the first 1048576 were captured and the rest was dropped from this file]\n`}class gd{constructor(e,t){this.innerFactory=e,this.projectDir=t}async spawn(e,t){const r=s.join(this.projectDir,"terminals");await(0,xo.mkdir)(r,{recursive:!0});const n=this.createLoggingExecutor(t,e,r);return this.innerFactory.spawn(e,n)}createLoggingExecutor(e,t,r){const o=e.execute.bind(e);return{...e,execute:async function*(e,i){let a,c,l,u=!1,d=!1,h=!1,p=!1;const f=Date.now(),m=new Date(f).toISOString(),g=performance.now();let w,y="running",v=!1,b=Promise.resolve();const S=async e=>{if(c)try{await c.write(e)}catch(e){}},k=t.shellId,_=s.join(r,`${k}.txt`),C=async()=>{if(!a)return;const e=hd(g),r=fd({pid:w,cwd:t.workingDirectory,command:t.command,title:t.description,status:y,startedAt:m,runningForMs:e});try{await a.write(r,0,"utf8")}catch(e){}},E=()=>(b=b.then(C).catch((()=>{})),b),x=()=>{void 0!==l&&(clearInterval(l),l=void 0)},P=async e=>{if(p)return;p=!0,w=e;const r=hd(g),n=fd({pid:e,cwd:t.workingDirectory,command:t.command,title:t.description,status:y,startedAt:m,runningForMs:r});await(0,xo.writeFile)(_,n,"utf8"),l=setInterval((()=>{E()}),5e3)},R=async()=>{a||(a=await Ro.promises.open(_,"r+")),c||(c=await Ro.promises.open(_,"a"))},I=async(e,t)=>{if(!v){if(v=!0,x(),p||await P(),await R(),void 0!==t){const e=hd(g),r=`\n---\n${t}\n`+(i.showElapsedTime?`elapsed_ms: ${e}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await S(r)}y=e,await E()}};try{for await(const r of o(e,i)){if("stdout"===r.type)p||(await P(),await R()),await S(r.data);else if("stderr"===r.type)p||(await P(),await R()),await S(r.data);else if("stdout_trimmed"!==r.type||d)if("stderr_trimmed"!==r.type||h)if("stdin_ready"!==r.type||u)"exit"===r.type&&await I(r.aborted?"aborted":0===r.code?"succeeded":"failed",`exit_code: ${r.code??"unknown"}`);else{u=!0,p||(await P(r.pid),await R());const e=r.stdin;if(e&&!0!==t.suppressStdinLogging){const t=e=>{if(null==e)return;const t="string"==typeof e?e:n.Buffer.isBuffer(e)||e instanceof Uint8Array?n.Buffer.from(e).toString():"";if(!t)return;const r=t.endsWith("\n")?t:`${t}\n`;S(`[stdin] ${r}`)},r=e.write.bind(e);if(e.write=(e,n,o)=>(t(e),r(e,n,o)),"function"==typeof e.end){const r=e.end.bind(e);e.end=(e,n,o)=>(void 0!==e&&t(e),r(e,n,o))}}}else h=!0,p||await P(),await R(),await S(md("stderr"));else d=!0,p||await P(),await R(),await S(md("stdout"));yield r}if(!v){const e=i.signal?.aborted??!1;await I(e?"aborted":"failed")}}catch(e){const t=i.signal?.aborted??!1,r=pd(e instanceof Error?e.message:"Unknown error");if(await I(t?"aborted":"failed",t?void 0:`error: ${r}`),!t)throw e}finally{if(x(),await b,a)try{await a.close()}catch{}if(c)try{await c.close()}catch{}}}}}async adopt(e){const t=s.join(this.projectDir,"terminals");await(0,xo.mkdir)(t,{recursive:!0});const r=s.join(t,`${e.shellId}.txt`),n=e.startTime,o=new Date(n).toISOString(),i=e.monotonicStartMs;let a="running";const c=hd(i),l=fd({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:a,startedAt:o,runningForMs:c})+(e.initialOutput??"");await(0,xo.writeFile)(r,l,"utf8");const u=await Ro.promises.open(r,"r+");let d;try{d=await Ro.promises.open(r,"a")}catch(e){throw await u.close(),e}let h=!1,p=!1,f=!1,m=!1,g=Promise.resolve();const w=async()=>{const t=hd(i),r=fd({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:a,startedAt:o,runningForMs:t});try{await u.write(r,0,"utf8")}catch{}},y=()=>(g=g.then(w).catch((()=>{})),g);let v=setInterval((()=>{y()}),5e3);const b=()=>{void 0!==v&&(clearInterval(v),v=void 0)},S=async()=>{if(!h){h=!0,b(),await g;try{await u.close()}catch{}try{await d.close()}catch{}}},k=async e=>{try{await d.write(e)}catch(e){}},_=async(t,r)=>{if(!p){if(p=!0,b(),void 0!==r){const t=hd(i),n=`\n---\n${r}\n`+(e.showElapsedTime?`elapsed_ms: ${t}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await k(n)}a=t,await y()}},C={next:async()=>{try{const t=await e.eventIterator.next();if(t.done){if(!p){const t=e.abortController.signal.aborted;await _(t?"aborted":"failed")}}else{const e=t.value;"stdout"===e.type||"stderr"===e.type?await k(e.data):"stdout_trimmed"!==e.type||f?"stderr_trimmed"!==e.type||m?"exit"===e.type&&(await _(e.aborted?"aborted":0===e.code?"succeeded":"failed",`exit_code: ${e.code??"unknown"}`),await S()):(m=!0,await k(md("stderr"))):(f=!0,await k(md("stdout")))}return t.done&&await S(),t}catch(t){const r=e.abortController.signal.aborted;throw await _(r?"aborted":"failed"),await S(),t}},return:async()=>{if(!p){const t=e.abortController.signal.aborted;await _(t?"aborted":"failed")}return await S(),e.eventIterator.return?e.eventIterator.return():{done:!0,value:void 0}}};return this.innerFactory.adopt({...e,eventIterator:C})}}class wd{constructor(e,t){this.factory=e,this.backgroundWorkRegistry=t,this.runningShells=new Map,this.nextShellId=1e3+Math.floor(999e3*Math.random())}registerShellWork(e,t){const r=String(e.id);this.backgroundWorkRegistry?.upsertWork({id:r,kind:"shell",state:"running",metadata:Ao(t),abort:()=>{this.abort(e.id)}})}clearShellWork(e){this.backgroundWorkRegistry?.clearWork(String(e))}cleanupShell(e){this.runningShells.has(e)&&(this.runningShells.delete(e),this.clearShellWork(e))}enqueueShellCompletion(e,t,r,n,o,s){if(!this.backgroundWorkRegistry)return;const i=s.aborted?"aborted":0===s.code?"success":"error",a=function(e){if(!e.aborted)return void 0!==e.signal?`signal=${e.signal}`:null!==e.code&&0!==e.code?`exit_code=${e.code}`:void 0}(s),c=function(e){if(!e.aborted)return void 0!==e.signal?{kind:"signal",signal:e.signal}:null!==e.code?{kind:"exit",code:e.code}:void 0}(s),l=n.description?.trim()?n.description:void 0,u=String(e);this.backgroundWorkRegistry.enqueue({conversationId:r??Io,id:u,source:"shell",payload:{taskId:u,...void 0!==t?{toolCallId:t}:{},kind:"shell",status:i,title:n.description||n.command,...a?{detail:a}:{},...s.outputPath?{outputPath:s.outputPath}:{},reason:"task_finished",durationMs:hd(o),...c?{shellEnd:c}:{},...l?{description:l}:{}}})}async spawn(e,t){const r=await this.factory.spawn(e,t),n=Date.now(),o=performance.now();return this.runningShells.set(r.id,r),this.registerShellWork(r,{title:e.description||e.command,cwd:e.workingDirectory,startTimeMs:n}),r.signal.addEventListener("abort",(()=>{this.cleanupShell(r.id)})),r.onComplete?.((t=>{this.enqueueShellCompletion(r.id,e.toolCallId,e.conversationId,{command:e.command,description:e.description},o,t),this.cleanupShell(r.id)})),{shellId:r.id,pid:r.pid}}async adopt(e){const t=await this.factory.adopt(e);return this.runningShells.set(t.id,t),this.registerShellWork(t,{title:e.description||e.command,cwd:e.workingDirectory,startTimeMs:e.startTime}),t.signal.addEventListener("abort",(()=>{this.cleanupShell(t.id),e.onCleanup?.()})),t.onComplete?.((r=>{this.enqueueShellCompletion(t.id,e.toolCallId,void 0,{command:e.command,description:e.description},e.monotonicStartMs,r),this.cleanupShell(t.id),e.onCleanup?.()})),{shellId:t.id,pid:e.pid}}generateShellId(){for(let e=0;e<=998999;e++){this.nextShellId>999999&&(this.nextShellId=1e3);const e=this.nextShellId;if(this.nextShellId+=1,!this.runningShells.has(e))return e}throw new Error("No available background shell id in range")}abort(e){const t=this.runningShells.get(e);return!!t&&(t.abort(),this.runningShells.delete(e),this.clearShellWork(e),!0)}isRunning(e){return this.runningShells.has(e)}dispose(){for(const[e,t]of this.runningShells)t.dispose(),this.clearShellWork(e);this.runningShells.clear()}async writeStdin(e,t){const r=this.runningShells.get(e);if(!r)throw new Error("Shell not found");if(!r.stdin)throw new Error("Shell stdin not available");const n=t.indexOf(""),o=-1!==n?n:t.indexOf("\\u0004");if(-1!==o){const e=t.substring(0,o);e.length>0&&await new Promise(((t,n)=>{r.stdin.write(e,(e=>{e?n(e):t(void 0)}))})),r.stdin.end()}else await new Promise(((e,n)=>{r.stdin.write(t,(t=>{t?n(t):e(void 0)}))}))}}new WeakMap;class yd{constructor(e,t){this.inner=e,this.ownerConversationId=t}enqueue(e){this.inner.enqueue({...e,conversationId:this.ownerConversationId})}enqueueCompletion(e){this.enqueue({conversationId:this.ownerConversationId,id:e.taskId,source:e.kind,payload:e})}pull(e){return this.inner.pull(e)}ack(e){return this.inner.ack(e)}nack(e,t){this.inner.nack(e,t)}suppress(e,t){this.inner.suppress(e,t)}upsertWork(e){this.inner.upsertWork(e)}clearWork(e){return this.inner.clearWork(e)}abortWork(e){return this.inner.abortWork(e)}hasRunningWork(e){return this.inner.hasRunningWork(e)}abortAllWork(e){return this.inner.abortAllWork(e)}listWork(e){return this.inner.listWork(e)}drainCompletions(){return this.inner.drainCompletions()}hasPendingCompletions(e){return this.inner.hasPendingCompletions(e)}markAwaitedCompletion(e){this.inner.suppress(this.ownerConversationId,e)}}class vd{constructor(e,t,r,n,o,s,i,a){if(this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r,void 0!==a)return this.backgroundShellManager=a,void(this.ownsBackgroundShellManager=!1);const c=s&&void 0!==i?new yd(s,i):s,l=o??function(e){const t=new dd;return new gd(t,e)}(n),u=new ud(l,n,c);this.backgroundShellManager=new wd(u,c),this.ownsBackgroundShellManager=!0}getManager(){return this.backgroundShellManager}dispose(){this.ownsBackgroundShellManager&&this.backgroundShellManager.dispose()}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,D.VI)(e.withName("LocalBackgroundShellExecutor.execute")),!1);const n=t.command,o=t.sandboxPolicy?ds(t.sandboxPolicy):void 0,s=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),i=(0,ts.o1)(s),a=new fe.HO(qo(n).structured),c=Cs({command:n,parsingResult:a,blockedCommands:t.adminCommandDenylist});if(void 0!==c)return new Fo.Lt({result:{case:"rejected",value:new fe.pZ({command:n,workingDirectory:i,reason:c})}});let l;if(od.info(e,"Background shell: approval gate reached",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,hasSmartModeApproval:void 0!==t.smartModeApproval,hasSmartModeApprovalReason:void 0!==t.smartModeApproval?.reason,hasSmartModeApprovalRequestId:void 0!==t.smartModeApproval?.requestId,requestedPolicyType:o?.type??"undefined",parserCommandCount:a.executableCommands.length,classifierCommandCount:t.classifierResult?.commands.length??0,commandLength:n.length}),Oo(t)){const r=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:i,skipUnsafeWorkingDirectoryBlock:!0,command:n,parsingResult:a,toolCallId:t.toolCallId,resolveSkippedApprovalPolicy:!0},o);if("block"===r.kind)return od.info(e,"Background shell: invariant blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,skipApproval:t.skipApproval}),sd(n,i,r.reason);l=r.policy??o,od.info(e,"Background shell: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:o?.type??"undefined",effectivePolicyType:l?.type??"undefined"})}else{const r=await this.permissionsService.shouldBlockShellCommand(e,n,{workingDirectory:i,timeout:0,parsingResult:a,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Mo(t)},o);if("block"===r.kind)return od.info(e,"Background shell: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),sd(n,i,r.reason);l=r.policy,od.info(e,"Background shell: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:l.type})}l=await $c(l,{command:n,workingDirectory:i,parsingResult:a,permissionsService:this.permissionsService,ignoreService:this.ignoreService});try{const r=this.backgroundShellManager.generateShellId(),o=l?{perUser:l}:void 0,s={ctx:e,command:n,workingDirectory:i,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:o,shellId:r,enableWriteShellStdinTool:t.enableWriteShellStdinTool,suppressStdinLogging:t.suppressStdinLogging,description:t.description,outputNotification:t.outputNotification},a=await this.backgroundShellManager.spawn(s,this.coreExecutor);return new Fo.Lt({result:{case:"success",value:new Fo.Po({shellId:r,command:n,workingDirectory:i,pid:a.pid})}})}catch(r){if(r instanceof No.SandboxUnsupportedError){const o=l?.type??"unknown";return od.debug(e,"Background shell: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:o,reason:r.reason}),new Fo.Lt({result:{case:"sandboxUnsupported",value:new fe.rI({command:n,workingDirectory:i,sandboxPolicyType:o,reason:r.reason??r.message,isReadonly:"workspace_readonly"===o})}})}return new Fo.Lt({result:{case:"error",value:new Fo.Of({command:n,workingDirectory:i,error:r instanceof Error?r.message:"Unknown error"})}})}}catch(e){r.error=e,r.hasError=!0}finally{nd(r)}}writeStdin(e,t){return this.backgroundShellManager.writeStdin(e,t)}}var bd=r("node:async_hooks");r("../../node_modules/.pnpm/minimatch@10.2.5/node_modules/minimatch/dist/esm/index.js");function Sd(e){return e instanceof Error?e.message:String(e)}function kd(e){return"Failed to read skill file: "+Sd(e)}function _d(e){return"Invalid skill frontmatter: "+Sd(e)}function Cd(e,t){return e||t?void 0:"Description is required"}new Set(["EACCES","EPERM","ENOENT","ENOTDIR","EISDIR","ELOOP","ENAMETOOLONG"]);const Ed=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function xd(e){return e.toLocaleString("en-US")}var Pd=r("node:url");const Rd={beforeShellExecution:"beforeShellExecution",beforeMCPExecution:"beforeMCPExecution",afterShellExecution:"afterShellExecution",afterMCPExecution:"afterMCPExecution",beforeReadFile:"beforeReadFile",afterFileEdit:"afterFileEdit",beforeTabFileRead:"beforeTabFileRead",afterTabFileEdit:"afterTabFileEdit",stop:"stop",beforeSubmitPrompt:"beforeSubmitPrompt",afterAgentResponse:"afterAgentResponse",afterAgentThought:"afterAgentThought",sessionStart:"sessionStart",sessionEnd:"sessionEnd",preCompact:"preCompact",subagentStart:"subagentStart",subagentStop:"subagentStop",preToolUse:"preToolUse",postToolUse:"postToolUse",postToolUseFailure:"postToolUseFailure",workspaceOpen:"workspaceOpen"},Id=e=>"string"==typeof e,Td=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),Ad=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),$d=(e,t=[])=>({isValid:e,errors:t});function Md(e,t,r){void 0===e||Id(e)||r.push(`${t} must be a string if provided`)}const Dd=e=>{const t=[];if(!Td(e))return t.push("Hook script must be an object with either a 'command' property (command hook) or 'type: \"prompt\"' with a 'prompt' property (prompt hook)"),$d(!1,t);const r=e.type;return"prompt"===r?((e,t)=>{Id(e.prompt)?""===e.prompt.trim()&&t.push("Prompt hook 'prompt' property cannot be empty"):t.push("Prompt hook must have a 'prompt' property (string)"),void 0!==e.model&&(Id(e.model)?""===e.model.trim()&&t.push("Prompt hook 'model' cannot be an empty string"):t.push("Prompt hook 'model' must be a string if provided"))})(e,t):"command"===r||void 0===r?((e,t)=>{Id(e.command)||t.push("Hook script command must be a string")})(e,t):t.push(`Invalid hook type: "${r}". Must be "command", "prompt", or omitted (defaults to "command")`),((e,t)=>{if(void 0!==e.matcher)if(Id(e.matcher)){if(""!==e.matcher&&"*"!==e.matcher)try{new RegExp(e.matcher)}catch(r){t.push(`Hook script matcher "${e.matcher}" is not a valid regex: ${r?.message??String(r)}`)}}else t.push("Hook script matcher must be a string if provided");if(void 0!==e.timeout&&("number"!=typeof e.timeout?t.push("Hook script timeout must be a number (seconds)"):e.timeout<=0?t.push("Hook script timeout must be a positive number"):e.timeout>3600&&console.warn(`[hooks] Hook timeout of ${e.timeout}s is very long (>1 hour)`)),void 0!==e.loop_limit){const r=e.loop_limit;null!==r&&("number"!=typeof r?t.push("Hook script loop_limit must be a positive integer or null"):Number.isInteger(r)?r<=0&&t.push("Hook script loop_limit must be a positive integer (use null for no limit)"):t.push("Hook script loop_limit must be an integer"))}void 0!==e.failClosed&&"boolean"!=typeof e.failClosed&&t.push("Hook script failClosed must be a boolean")})(e,t),$d(0===t.length,t)},Od=(e,t)=>{const r=[];if(!Array.isArray(e))return r.push(`${t} must be an array of hook scripts`),$d(!1,r);for(let n=0;n{const t=[];if(!Td(e))return t.push("Hooks config must be an object"),$d(!1,t);if("number"!=typeof e.version?t.push("Config version must be a number"):(!Number.isInteger(e.version)||e.version<1)&&t.push("Config version must be a positive integer"),!Td(e.hooks))return t.push("Config hooks must be an object"),$d(!1,t);void 0!==e.stop_hook_loop_limit&&console.warn("[hooks] DEPRECATION WARNING: 'stop_hook_loop_limit' is deprecated. Use 'loop_limit' on individual hook scripts instead. The configured value is being ignored.");const r=Object.values(Rd),n=e.hooks;for(const[e,o]of Object.entries(n))if(r.includes(e)){if(void 0!==o){const r=Od(o,e);r.isValid||t.push(...r.errors)}}else t.push(`Unknown hook type: ${e}. Valid types are: ${r.join(", ")}`);return $d(0===t.length,t)},Nd={PreToolUse:Rd.preToolUse,PermissionRequest:null,PostToolUse:Rd.postToolUse,UserPromptSubmit:Rd.beforeSubmitPrompt,Stop:Rd.stop,SubagentStop:Rd.subagentStop,SessionStart:Rd.sessionStart,SessionEnd:Rd.sessionEnd,PreCompact:Rd.preCompact,Notification:null},Ld=Object.fromEntries(Object.entries(Nd).filter((e=>jd(e[0])&&null!==e[1])).map((([e,t])=>[t,e])));function jd(e){return Object.prototype.hasOwnProperty.call(Nd,e)}const Ud={Bash:"Shell",Read:"Read",Write:"Write",Edit:"Write",Glob:null,Grep:"Grep",WebFetch:"WebFetch",WebSearch:"WebSearch",Task:"Task"},Bd=["Glob"],Wd=["Notification","PermissionRequest"],Hd=/^[A-Za-z0-9_./:=+-]+$/,qd=/^=|^-.*\./,zd=/\$\{(?:CLAUDE_PROJECT_DIR|CURSOR_PROJECT_DIR|CLAUDE_PLUGIN_ROOT|CURSOR_PLUGIN_ROOT)\}/g,Gd=/^[^\p{Cc}$`"]*$/u,Vd=/\\(?:[$`"\\]|$)/;function Kd(e){return`'${e.replace(/'/g,"'\\''")}'`}function Jd(e){if(Hd.test(e)&&!qd.test(e))return e;const t=e.replace(zd,"");if((t!==e||e.includes("'"))&&Gd.test(t)&&!Vd.test(e))return`"${e}"`;const r=[];let n=0;for(const t of e.matchAll(zd))t.index>n&&r.push(Kd(e.slice(n,t.index))),r.push(`"${t[0]}"`),n=t.index+t[0].length;return(n{},info:()=>{}};function Xd(e,t,r=Zd){const n={loop_limit:null,failClosed:!1};if(t&&"*"!==t&&(n.matcher=t),void 0!==e.timeout&&(n.timeout=e.timeout),"prompt"===e.type)return e.prompt?{type:"prompt",prompt:e.prompt,...n}:null;const o=function(e,t){const r=e.command;if(!r)return null;const n=e.args;return null==n?(void 0!==e.shell&&t.warn(`Hook "${r}" sets shell "${e.shell}", which Cursor does not support; the platform default shell will be used`),r):(o=n,Array.isArray(o)&&o.every((e=>"string"==typeof e))?function(e,t){return[e,...t].map(Jd).join(" ")}(r,n):(t.warn(`Hook "${r}" has invalid "args" (expected an array of strings), skipping`),null));var o}(e,r);return null===o?null:{type:"command",command:o,...n}}function Qd(e,t,r=Zd){const n=[];let o;if("PreToolUse"===t||"PostToolUse"===t){const t=function(e,t=Zd){if(!e||"*"===e)return"*";const r=e.split("|"),n=[],o=[];for(const e of r){const t=e.trim();if(t.startsWith("mcp__")){const e=t.split("__");if(e.length>=3){const t=e.slice(2).join("__");n.push(`MCP:${t}`);continue}}const r=Ud[t];null!==r?void 0!==r?n.includes(r)||n.push(r):n.push(t):Bd.includes(t)&&o.push(`Tool "${t}" is not supported in Cursor and will be ignored`)}for(const e of o)t.warn(e);return 0===n.length?null:n.join("|")}(e.matcher,r);if(null===t)return r.warn(`All tools in matcher "${e.matcher}" are unsupported, skipping hooks`),[];o="*"===t?void 0:t}else"SessionStart"===t||"PreCompact"===t?(e.matcher&&"*"!==e.matcher&&""!==e.matcher&&("SessionStart"===t?["startup","resume","clear","compact"].includes(e.matcher):["manual","auto"].includes(e.matcher))&&r.warn(`${t} trigger matcher "${e.matcher}" is not supported in Cursor, hooks will fire for all triggers`),o=void 0):o=void 0;for(const t of e.hooks){const e=Xd(t,o,r);e&&n.push(e)}return n}function Yd(e,t=Zd){const r={};for(const[n,o]of Object.entries(e)){if(!jd(n)){t.warn(`Unknown Claude Code event "${n}", skipping`);continue}if(Wd.includes(n)){t.warn(`Claude Code event "${n}" is not supported in Cursor and will be ignored`);continue}const e=Nd[n];if(!e){t.warn(`Unknown Claude Code event "${n}", skipping`);continue}const s=[];if(Array.isArray(o))for(const e of o){const r=Qd(e,n,t);s.push(...r)}else void 0!==o&&t.warn(`Claude Code event "${n}" has invalid value (expected array), skipping`);if(s.length>0){const t=r[e]||[];r[e]=[...t,...s]}}return{version:1,hooks:r}}var eh=r("../../node_modules/.pnpm/gray-matter@4.0.3/node_modules/gray-matter/index.js");const th=()=>({});function rh(e,t){return eh(e,{...t,engines:{...t?.engines,js:th,javascript:th}})}function nh(e,t,r){return eh.stringify({content:e,data:{}},t,r)}var oh=r("node:zlib");function sh(e,t){const r=function(e){return e.split(/[/\\]/).filter((e=>e))}(e);for(let e=0;ee.isDirectory())).map((e=>e.name))}catch{return[]}}async removeVersion(e){const t=this.getCacheDir(e);try{await(0,xo.rm)(t,{recursive:!0,force:!0})}catch{}}async removeAllVersions(e){const t=ph(this.cacheRoot,e);await(0,xo.rm)(t,{recursive:!0,force:!0})}async pruneOldVersions(e){const t=await this.listCachedVersions({marketplaceSlug:e.marketplaceSlug,pluginId:e.pluginId}),r=new Set(e.keepVersions.map((e=>dh(e))));for(const n of t)r.has(n)||await this.removeVersion({marketplaceSlug:e.marketplaceSlug,pluginId:e.pluginId,version:n})}async markCacheComplete(e){const t=this.getCacheDir(e);await(0,xo.writeFile)(hh({parent:t,name:uh}),"")}}class mh extends Error{constructor(e,t){super(t),this.reason=e,this.name="PluginContentInstallError"}}const gh=(0,Vs.promisify)(oh.gunzip),wh=/^[A-Za-z0-9._-]{1,128}$/,yh=/^[0-9a-f]{64}$/,vh=/^[1-9]\d{0,18}$/,bh="backend-content://",Sh="backend-content/",kh=new Map([[3,"request_refused"],[5,"not_found"],[9,"account_not_connected"],[10,"revision_superseded"],[12,"unsupported_server"],[14,"unavailable"]]),_h=new Set(["unavailable","revision_superseded","timeout","download_failed","integrity"]);function Ch(e){return e instanceof mh&&_h.has(e.reason)}class Eh{constructor(){this.awaited=new Map}forListing(e){return{startLoad:()=>{for(const[t,r]of this.awaited)r.listing===e&&(r.attemptedThisLoad?r.attemptedThisLoad=!1:this.awaited.delete(t))},heldFailure:({pluginDbId:e,revision:t})=>{const r=this.awaited.get(e);if(void 0!==r&&r.revision===t)return r.attemptedThisLoad=!0,Date.now(){Ch(n)?this.awaited.set(t,{revision:r,reason:n.reason,retryAtMs:Date.now()+6e4,listing:e,attemptedThisLoad:!0}):this.awaited.delete(t)},isRetryDue:()=>this.isRetryDue(),allowImmediateRetry:()=>this.allowImmediateRetry()}}isRetryDue(){const e=Date.now();return[...this.awaited.values()].some((t=>e>=t.retryAtMs))}allowImmediateRetry(){for(const e of this.awaited.values())e.retryAtMs=0}}function xh(e){if("bigint"!=typeof e&&"number"!=typeof e&&"string"!=typeof e)return;const t=String(e);return vh.test(t)?t:void 0}function Ph(e){return e.startsWith(bh)}function Rh(e){return`${Sh}${e}`}function Ih(e,t){return new mh(e,function(e,t){const r=JSON.stringify(t);switch(e){case"unsupported_client":return`Plugin ${r} could not be downloaded: this client cannot install plugins whose files the server provides.`;case"not_found":return`Plugin ${r} could not be downloaded: it no longer exists or you no longer have access to it.`;case"account_not_connected":return`Plugin ${r} could not be downloaded: connect your account on the host of its source repository first.`;case"revision_superseded":return`Plugin ${r} changed while it was downloading. The new version installs on the next plugin refresh.`;case"unavailable":return`Plugin ${r} could not be downloaded: its files cannot be served right now. It installs on a later plugin refresh.`;case"unsupported_server":return`Plugin ${r} could not be downloaded: this server does not provide plugin files.`;case"request_refused":return`Plugin ${r} could not be downloaded: the server refused the request.`;case"download_failed":return`Plugin ${r} could not be downloaded.`;case"timeout":return`Downloading plugin ${r} timed out.`;case"integrity":return`The download of plugin ${r} did not match the size or hash the server gave for it, so it was discarded.`;case"too_large":return`Plugin ${r} could not be downloaded: its files are larger than this client accepts.`;case"unsafe_archive":return`The download of plugin ${r} could not be unpacked safely, so it was discarded.`;case"unpack_failed":return`The download of plugin ${r} could not be written to the plugin cache.`;default:return e}}(e,t))}function Th(e){if("File"!==e.type&&"OldFile"!==e.type&&"Directory"!==e.type)return!0;const t=e.path;return!(0!==t.length&&!t.includes("\0")&&!/^([/\\]|[A-Za-z]:)/.test(t))||t.split(/[/\\]/).includes("..")}async function Ah(e){const{download:t,pluginName:r,content:n,targetDir:o}=e;if(void 0===t)throw Ih("unsupported_client",r);const s=new AbortController;let i;try{i=await async function(e){const t=e[Symbol.asyncIterator](),r=()=>(0,Nr.wj)(t.next(),12e4);try{const e=await r();if(!0===e.done||"header"!==e.value.part.case)return"integrity";const{sha256:t}=e.value.part.value,n=function(e){let t;if("bigint"==typeof e||"number"==typeof e)t=Number(e);else{if("string"!=typeof e||!/^\d{1,15}$/.test(e))return;t=Number(e)}return Number.isSafeInteger(t)&&t>0?t:void 0}(e.value.part.value.sizeBytes);if(void 0===n||"string"!=typeof t||!yh.test(t))return"integrity";if(n>16777216)return"too_large";const o=[];let s=0;for(;;){const e=await r();if(!0===e.done)break;const{part:t}=e.value;if(void 0!==t.case){if("data"!==t.case||0===t.value.byteLength)return"integrity";if(s+=t.value.byteLength,s>n)return"integrity";o.push(t.value)}}const i=Buffer.concat(o,s);return s===n&&(0,ko.createHash)("sha256").update(i).digest("hex")===t?i:"integrity"}finally{Promise.resolve(t.return?.()).catch((()=>{}))}}(t({pluginId:BigInt(e.pluginDbId),revision:n.revision},{signal:s.signal}))}catch(e){throw Ih(function(e){return e instanceof Nr.MU?"timeout":"object"==typeof e&&null!==e&&"code"in e?"number"!=typeof e.code?"download_failed":kh.get(e.code)??"download_failed":"download_failed"}(e),r)}finally{s.abort()}if("string"==typeof i)throw Ih(i,r);const a=await async function(e){let t;try{t=await gh(e,{maxOutputLength:268435456})}catch{return}const r=t.byteLength>=512,n=r&&31===t[0]&&139===t[1],o=r&&682962941===t.readUInt32BE(0);if(r&&!n&&!o)return t}(i);if(void 0===a||!await function(e){return new Promise((t=>{let r=0;const n=(0,ah.p_)({strict:!0,onReadEntry:e=>{r+=1,(r>5e4||Th(e))&&(t(!1),n.abort(new Error("unsafe entry")))}});n.once("end",(()=>t(r>0))),n.once("error",(()=>t(!1))),n.end(e)}))}(a))throw Ih("unsafe_archive",r);try{await async function(e,t){const r=(0,ah.o6)({cwd:t,strict:!0,preserveOwner:!1,filter:(e,t)=>{if(!("type"in t)||Th(t))return!1;const r=!!(64&(t.mode??0));return t.mode="Directory"===t.type||r?493:420,!0}});await new Promise(((t,n)=>{r.once("close",t),r.once("error",n),r.end(e)}))}(a,o)}catch{throw Ih("unpack_failed",r)}}function $h(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")||"/"}function Mh(e,t){if(Object.hasOwn(e,t))return e[t]}function Dh(e,t,r,n){const o=e?.plugins;if(!o||"object"!=typeof o)return[];const s=t?.enabledPlugins??{},i={};r?.enabledPlugins&&Object.assign(i,r.enabledPlugins);const a=void 0!==n?$h(n):void 0,c=new Set,l=[];for(const[e,t]of Object.entries(o)){if(!Array.isArray(t)||0===t.length)continue;if(void 0!==a&&!1===Mh(i,e))continue;let r;void 0!==a&&(r=t.find((t=>!("project"!==t.scope&&"local"!==t.scope||!t.projectPath)&&($h(t.projectPath)===a&&!0===Mh(i,e))))),r||!0!==Mh(s,e)||(r=t.find((e=>"user"===e.scope))),r?.installPath&&!c.has(e)&&(l.push({pluginId:e,installPath:r.installPath}),c.add(e))}return l}var Oh=r("../../node_modules/.pnpm/js-yaml@4.3.1/node_modules/js-yaml/dist/js-yaml.mjs");const Fh=Be.enum(["canvas"]),Nh=Be.array(Fh).transform((e=>[...new Set(e)].sort())),Lh=new Set(["https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","https://agent-plugins.org/schemas/1.0.0/mcp.schema.json"]),jh=/^v?(\d+\.\d+(?:\.\d+)?)$/;function Uh(e){if("object"!=typeof(t=e)||null===t||Array.isArray(t))return;var t;const r=e.$schema;return"string"==typeof r&&r.length>0?r:void 0}function Bh(e){let t;try{t=new URL(e).pathname.split("/")}catch{t=e.split("/")}for(const e of t){const t=jh.exec(e);if(null!==t)return t[1]}}function Wh(e){return void 0===e?{kind:"absent"}:Lh.has(e)?{kind:"supported",id:e,version:Bh(e)??e}:{kind:"unsupported",id:e}}const Hh=10485760,qh=/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/,zh=[".cursor-plugin/plugin.json",".claude-plugin/plugin.json","plugin.json"],Gh=[".cursor-plugin",".claude-plugin"],Vh=[".cursor-plugin/marketplace.json",".claude-plugin/marketplace.json"],Kh=Be.object({source:Be.literal("github"),repo:Be.string().regex(/^[^/]+\/[^/]+$/,"Must be in owner/repo format"),ref:Be.string().optional(),sha:Be.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Jh=Be.object({source:Be.literal("url"),url:Be.string().url().endsWith(".git","URL must end with .git"),ref:Be.string().optional(),sha:Be.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Zh=Be.object({source:Be.literal("git-subdir"),url:Be.string().url().endsWith(".git","URL must end with .git"),path:Be.string().min(1),ref:Be.string().optional(),sha:Be.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Xh=Be.union([Be.string(),Kh,Jh,Zh]),Qh=/^(\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?|never)$/,Yh='Must be a semver version (X.Y.Z) or "never"',ep=Be.object({cursor:Be.string().regex(Qh,Yh).optional(),sand:Be.string().regex(Qh,Yh).optional(),sandMobile:Be.string().regex(Qh,Yh).optional()}),tp=Be.object({name:Be.string().min(1,"Author name is required"),email:Be.string().email().optional()}),rp=Be.enum(["string","number","integer","boolean","object","array","null"]),np=Be.union([rp,Be.array(rp).nonempty().superRefine(((e,t)=>{new Set(e).size!==e.length&&t.addIssue({code:Be.ZodIssueCode.custom,message:"Schema type arrays must not contain duplicates"})}))]);function op(e,t){if(void 0!==e.required)if(void 0===e.properties)for(const r of e.required)t.addIssue({code:Be.ZodIssueCode.custom,message:`Required property "${r}" must be declared in properties`,path:["required"]});else for(const r of e.required)r in e.properties||t.addIssue({code:Be.ZodIssueCode.custom,message:`Required property "${r}" must be declared in properties`,path:["required"]});void 0!==e.minLength&&void 0!==e.maxLength&&e.minLength>e.maxLength&&t.addIssue({code:Be.ZodIssueCode.custom,message:"minLength must be less than or equal to maxLength",path:["minLength"]}),void 0!==e.minimum&&void 0!==e.maximum&&e.minimum>e.maximum&&t.addIssue({code:Be.ZodIssueCode.custom,message:"minimum must be less than or equal to maximum",path:["minimum"]}),void 0!==e.exclusiveMinimum&&void 0!==e.exclusiveMaximum&&e.exclusiveMinimum>=e.exclusiveMaximum&&t.addIssue({code:Be.ZodIssueCode.custom,message:"exclusiveMinimum must be less than exclusiveMaximum",path:["exclusiveMinimum"]}),void 0!==e.minItems&&void 0!==e.maxItems&&e.minItems>e.maxItems&&t.addIssue({code:Be.ZodIssueCode.custom,message:"minItems must be less than or equal to maxItems",path:["minItems"]}),void 0!==e.minProperties&&void 0!==e.maxProperties&&e.minProperties>e.maxProperties&&t.addIssue({code:Be.ZodIssueCode.custom,message:"minProperties must be less than or equal to maxProperties",path:["minProperties"]})}const sp=Be.lazy((()=>Be.object({type:np.optional(),title:Be.string().optional(),description:Be.string().optional(),format:Be.string().optional(),writeOnly:Be.boolean().optional(),placeholder:Be.string().optional(),default:Be.unknown().optional(),enum:Be.array(Be.any()).nonempty().optional(),const:Be.unknown().optional(),properties:Be.record(Be.string(),sp).optional(),required:Be.array(Be.string()).optional(),additionalProperties:Be.union([Be.boolean(),sp]).optional(),items:Be.union([sp,Be.array(sp)]).optional(),minLength:Be.number().int().nonnegative().optional(),maxLength:Be.number().int().nonnegative().optional(),minimum:Be.number().optional(),maximum:Be.number().optional(),exclusiveMinimum:Be.number().optional(),exclusiveMaximum:Be.number().optional(),multipleOf:Be.number().positive().optional(),minItems:Be.number().int().nonnegative().optional(),maxItems:Be.number().int().nonnegative().optional(),uniqueItems:Be.boolean().optional(),minProperties:Be.number().int().nonnegative().optional(),maxProperties:Be.number().int().nonnegative().optional()}).strict().superRefine(op)));function ip(e){const t=sp.superRefine(((e,t)=>{lp(e)&&"object"===e.type||t.addIssue({code:Be.ZodIssueCode.custom,message:'Plugin variable schemas must declare type "object"',path:["type"]})})).safeParse(e);return t.success?up(t.data)?{success:!0,data:t.data}:{success:!1,error:new Be.ZodError([{code:"custom",path:["type"],message:'Plugin variable schemas must declare type "object"'}])}:{success:!1,error:t.error}}const ap=Be.unknown().superRefine(((e,t)=>{const r=ip(e);if(!r.success)for(const e of r.error.issues)t.addIssue({code:"custom",message:e.message,path:e.path})})).transform((e=>{if(!up(e))throw new Error('Plugin variable schema must declare type "object"');return e})),cp=(Be.object({name:Be.string().min(1).transform((e=>e.toLowerCase())).refine((e=>qh.test(e)),"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:Be.string().optional(),source:Xh,description:Be.string().optional(),version:Be.string().optional(),author:tp.optional(),publisher:Be.string().min(1).optional(),homepage:Be.string().url().optional(),repository:Be.string().url().optional(),license:Be.string().optional(),keywords:Be.array(Be.string()).optional(),capabilities:Nh.optional(),logo:Be.string().optional(),category:Be.string().optional(),tags:Be.array(Be.string()).optional(),minClientVersions:ep.optional(),strict:Be.boolean().default(!0),commands:Be.union([Be.string(),Be.array(Be.string())]).optional(),agents:Be.union([Be.string(),Be.array(Be.string())]).optional(),skills:Be.union([Be.string(),Be.array(Be.string())]).optional(),rules:Be.union([Be.string(),Be.array(Be.string())]).optional(),hooks:Be.union([Be.string(),Be.record(Be.string(),Be.unknown())]).optional(),variables:ap.optional(),mcpServers:Be.union([Be.string(),Be.record(Be.string(),Be.unknown()),Be.array(Be.union([Be.string(),Be.record(Be.string(),Be.unknown())]))]).optional()}),Be.object({description:Be.string().optional(),version:Be.string().optional(),pluginRoot:Be.string().optional()}),Be.object({name:Be.string().min(1).regex(qh,"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:Be.string().optional(),description:Be.string().optional(),version:Be.string().optional(),author:tp.optional(),publisher:Be.string().min(1).optional(),homepage:Be.string().url().optional(),repository:Be.string().url().optional(),license:Be.string().optional(),logo:Be.string().optional(),keywords:Be.array(Be.string()).optional(),capabilities:Nh.optional(),minClientVersions:ep.optional(),commands:Be.union([Be.string(),Be.array(Be.string())]).optional(),agents:Be.union([Be.string(),Be.array(Be.string())]).optional(),skills:Be.union([Be.string(),Be.array(Be.string())]).optional(),rules:Be.union([Be.string(),Be.array(Be.string())]).optional(),hooks:Be.union([Be.string(),Be.record(Be.string(),Be.unknown())]).optional(),variables:ap.optional(),mcpServers:Be.union([Be.string(),Be.record(Be.string(),Be.unknown()),Be.array(Be.union([Be.string(),Be.record(Be.string(),Be.unknown())]))]).optional()}));function lp(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function up(e){return lp(e)&&"object"===e.type}function dp(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function hp(e,t){if(lp(e)&&"string"==typeof e.name){const t=dp(e.name);if(t.length>0)return t}return function(e){const t=void 0!==e.repoName?dp(e.repoName):"";return t.length>0?t:`cursor-marketplace-${e.fallbackId??(0,ko.randomUUID)()}`}(t)}function pp(e){if(lp(e)&&lp(e.owner)){const t="string"==typeof e.owner.name&&e.owner.name.trim().length>0?e.owner.name:"Unknown",r="string"==typeof e.owner.email&&e.owner.email.trim().length>0?e.owner.email:void 0;return{name:t,...void 0!==r?{email:r}:{}}}return{name:"Unknown"}}function fp(e){return"string"==typeof e?e:void 0}function mp(e){if(!Array.isArray(e))return;const t=e.filter((e=>"string"==typeof e));return t.length>0?t:void 0}function gp(e){return"string"==typeof e?e:mp(e)}function wp(e){if(!lp(e)||!lp(e.metadata))return;const t={description:fp(e.metadata.description),version:fp(e.metadata.version),pluginRoot:fp(e.metadata.pluginRoot)};return void 0!==t.description||void 0!==t.version||void 0!==t.pluginRoot?t:void 0}function yp(e){if(!lp(e))return;const t=fp(e.name);if(void 0===t||0===t.length)return;const r=fp(e.email);return{name:t,...void 0!==r?{email:r}:{}}}function vp(e){if("string"==typeof e||lp(e))return e;if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e||lp(e)));return t.length>0?t:void 0}}function bp(e){if("string"==typeof e||lp(e))return e}function Sp(e){if(void 0===e)return;const t=ip(e);return t.success?t.data:void 0}function kp(e,t={}){if(e.length>Hh)return{success:!1,error:"Manifest exceeds maximum size of 10485760 bytes"};let r;try{r=JSON.parse(e)}catch(e){return{success:!1,error:`Invalid JSON: ${e instanceof Error?e.message:"Unknown error"}`}}if(!lp(r))return{success:!1,error:"Invalid marketplace manifest: expected a JSON object"};const n=[],o=[],i=new Set;return(Array.isArray(r.plugins)?r.plugins:[]).forEach(((e,t)=>{const r=function(e,t){if(!lp(e))return{skippedEntry:{index:t,error:`Plugin entry at index ${t} is not an object`}};const r="string"==typeof(n=e.source)?n:lp(n)?"github"===n.source&&"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:fp(n.ref),sha:fp(n.sha)}:("url"===n.source||void 0===n.source)&&"string"==typeof n.url&&n.url.length>0?{source:"url",url:n.url,ref:fp(n.ref),sha:fp(n.sha)}:"git-subdir"===n.source&&"string"==typeof n.url&&n.url.length>0&&"string"==typeof n.path&&n.path.length>0?{source:"git-subdir",url:n.url,path:n.path,ref:fp(n.ref),sha:fp(n.sha)}:"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:fp(n.ref),sha:fp(n.sha)}:void 0:void 0;var n;if(void 0===r){const r=fp(e.name);return{skippedEntry:{index:t,...void 0!==r&&r.length>0?{name:r}:{},error:`Plugin entry at index ${t} has no usable source`}}}const o=("string"==typeof e.name?dp(e.name):"")||function(e){if("string"==typeof e){const t=dp((0,s.basename)(e));return t.length>0?t:void 0}if("github"===e.source){const t=dp(e.repo.split("/").at(-1)??"");return t.length>0?t:void 0}if("git-subdir"===e.source){const t=dp((0,s.basename)(e.path));return t.length>0?t:void 0}let t=e.url;try{t=new URL(e.url).pathname}catch{}for(;t.endsWith("/");)t=t.slice(0,-1);t.toLowerCase().endsWith(".git")&&(t=t.slice(0,-4));const r=dp((0,s.basename)(t));return r.length>0?r:void 0}(r);if(void 0===o)return{skippedEntry:{index:t,error:`Plugin entry at index ${t} has no usable name`}};const i=Nh.safeParse(e.capabilities);if(void 0!==e.capabilities&&!i.success)return{skippedEntry:{index:t,name:o,error:`Plugin entry at index ${t} has invalid capabilities: ${i.error.issues.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`}};const a=i.success?i.data:void 0,c=function(e){const t=ep.safeParse(e);if(t.success&&(void 0!==t.data.cursor||void 0!==t.data.sand||void 0!==t.data.sandMobile))return t.data}(e.minClientVersions);return{entry:{name:o,displayName:fp(e.displayName),source:r,description:fp(e.description),version:fp(e.version),author:yp(e.author),publisher:fp(e.publisher),homepage:fp(e.homepage),repository:fp(e.repository),license:fp(e.license),keywords:mp(e.keywords),logo:fp(e.logo),category:fp(e.category),tags:mp(e.tags),strict:"boolean"!=typeof e.strict||e.strict,commands:gp(e.commands),agents:gp(e.agents),skills:gp(e.skills),rules:gp(e.rules),hooks:bp(e.hooks),variables:Sp(e.variables),mcpServers:vp(e.mcpServers),...void 0!==a&&{capabilities:a},...void 0!==c&&{minClientVersions:c}}}}(e,t);"skippedEntry"in r?o.push(r.skippedEntry):i.has(r.entry.name)?o.push({index:t,name:r.entry.name,error:`Duplicate plugin name "${r.entry.name}" at index ${t}`}):(i.add(r.entry.name),n.push(r.entry))})),{success:!0,data:{name:hp(r,t),owner:pp(r),description:fp(r.description),plugins:n,metadata:wp(r),skippedPluginEntries:o}}}function _p(e){if(e.length>Hh)return{success:!1,error:"Manifest exceeds maximum size of 10485760 bytes"};let t;try{t=JSON.parse(e)}catch(e){return{success:!1,error:`Invalid JSON: ${e instanceof Error?e.message:"Unknown error"}`}}const r=Wh(Uh(t)),n=cp.safeParse(t);return n.success?{success:!0,data:n.data,..."unsupported"===r.kind&&{unrecognizedSchemaId:r.id}}:{success:!1,error:`Invalid plugin manifest: ${n.error.issues.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`,details:n.error}}function Cp(e,t){if("string"!=typeof e)return null;let r=e;if(r.startsWith("./")&&(r=r.slice(2)),void 0!==t){let e=t;e.startsWith("./")&&(e=e.slice(2)),e.endsWith("/")&&(e=e.slice(0,-1)),r=`${e}/${r}`}return r||"."}function Ep(e){return!e.includes("..")&&!(0,s.isAbsolute)(e)&&!e.includes("://")}var xp=r("../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js");const Pp=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g,Rp=/\$%7B([^%/?#]+?)%7D/gi;function Ip(e,t){return Tp(e,"function"==typeof t?t:function(e){const t=new Map(Object.entries(e).map((([e,t])=>[e.toLowerCase(),t])));return r=>e[r]??t.get(r.toLowerCase())}(t))}function Tp(e,t){if("string"==typeof e)return function(e,t){return e.replace(Rp,"${$1}").replace(Pp,((e,r,n,o)=>{if(void 0!==r)return t(r)??e;if(void 0===n)return e;const s=t(n);return void 0!==s?s:void 0!==o?o:e}))}(e,t);if(Array.isArray(e))return e.map((e=>Tp(e,t)));if(function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e)){const r={};for(const[n,o]of Object.entries(e))r[n]=Tp(o,t);return r}return e}function Ap(e,t){return e.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g,(()=>t)).replace(/\$\{CURSOR_PLUGIN_ROOT\}/g,(()=>t))}const $p={log:()=>{},increment:()=>{},distribution:()=>{},captureException:()=>{}},Mp=Be.object({command:Be.string().optional(),args:Be.array(Be.string()).optional(),env:Be.record(Be.string(),Be.string()).optional(),url:Be.string().optional(),headers:Be.record(Be.string(),Be.string()).optional(),cwd:Be.string().optional(),envFile:Be.string().optional(),auth:Be.object({CLIENT_ID:Be.string(),CLIENT_SECRET:Be.string().optional(),scopes:Be.array(Be.string()).optional()}).optional(),enabledTools:Be.array(Be.string()).optional(),placement:Be.enum(["server","client"]).optional(),tls:Be.object({caBundle:Be.string().trim().min(1).max(131072)}).optional()}),Dp=Be.object({mcpServers:Be.record(Be.string(),Mp).optional()}),Op=[".mcp.json","mcp.json"],Fp=new Set(["author","owner","source","metadata"].map((e=>e.toLowerCase())));function Np(e,t){if(!function(e){return Fp.has(e.toLowerCase())}(e))return!1;if(!function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(t))return!1;const r=t;switch(e.toLowerCase()){case"author":case"owner":return"string"==typeof r.name;case"source":return"string"==typeof r.source||"string"==typeof r.repo||"string"==typeof r.path||"string"==typeof r.ref||"string"==typeof r.sha;case"metadata":return"string"==typeof r.description||"string"==typeof r.version||"string"==typeof r.pluginRoot;default:return!1}}function Lp(e){return"object"==typeof e&&null!==e&&("command"in e||"url"in e)}function jp(e){const t=void 0!==e&&e.length>0?e.replace(/\/+$/,""):void 0;return Op.map((e=>void 0!==t?`${t}/${e}`:e))}function Up(e,t,r){if(!e.mcpServers)return e;const n={};for(const[r,o]of Object.entries(e.mcpServers)){const e={...o};if("string"==typeof o.command&&(e.command=Ap(o.command,t)),Array.isArray(o.args)&&(e.args=o.args.map((e=>"string"==typeof e?Ap(e,t):e))),o.env&&"object"==typeof o.env){const r={};for(const[e,n]of Object.entries(o.env))r[e]="string"==typeof n?Ap(n,t):n;e.env=r}"string"==typeof o.cwd&&(e.cwd=Ap(o.cwd,t)),n[r]=e}return function(e,t){const r=t?.cloudAgentEnvLookup,n=t?.configuredVariables;if(void 0!==r)return Ip(e,r);const o=new Map(Object.keys(n??{}).map((e=>[e.toLowerCase(),e])));return Ip(e,(e=>{const t=process.env[e];if(void 0!==t)return t;const r=void 0!==n&&Object.hasOwn(n,e)?e:o.get(e.toLowerCase()),s=void 0!==r?n?.[r]:void 0;return null!=s?"string"==typeof s?s:"number"==typeof s||"boolean"==typeof s||"bigint"==typeof s?String(s):JSON.stringify(s):void 0}))}({...e,mcpServers:n},r)}function Bp(e,t,r){try{const n=(0,xp.qg)(e),o=Uh(n);if(void 0!==o){const e=r?.log??$p;"unsupported"===Wh(o).kind?e.log("debug",`mcp.json declares an unrecognized $schema, loading anyway: ${o}`):function(e,t){if(void 0===e||void 0===t)return!1;const r=Bh(e),n=Bh(t);return void 0!==r&&void 0!==n&&r!==n}(r?.pluginSchemaId,o)&&e.log("debug",`mcp.json $schema ${o} disagrees with plugin.json $schema ${r?.pluginSchemaId}, loading anyway`)}const s=Dp.safeParse(n),i=!0===r?.skipExpansion;if(s.success&&s.data.mcpServers&&Object.keys(s.data.mcpServers).length>0)return i?s.data:Up(s.data,t,r);const a={};for(const[e,t]of Object.entries(n))"mcpServers"!==e&&!Np(e,t)&&Lp(t)&&(a[e]=t);if(Object.keys(a).length>0){const e=Dp.safeParse({mcpServers:a});if(e.success)return i?e.data:Up(e.data,t,r)}return null}catch{return null}}function Wp(e,t,r){for(const[n,o]of Object.entries(t))e.mcpServers[n]=o,e.mcpServerSourcePaths[n]=r}async function Hp(e,t,r,n={}){const o=n.toSourcePath??(e=>e),s=n.installPathForExpansion??"",i=n.fallbackFileNames??Op,a=n.manifestPrecedence??"override",c={},l={};for(const t of i){const r=await e(t);if(null===r)continue;const i=Bp(r,s,n.parserOptions);if(i?.mcpServers)for(const[e,r]of Object.entries(i.mcpServers))void 0===c[e]&&(c[e]=r,l[e]=o(t))}if(void 0!==t){const i=await async function(e,t,r={}){const n=r.toSourcePath??(e=>e),o=r.installPathForExpansion??"",s={mcpServers:{},mcpServerSourcePaths:{}},i=async e=>{const i=e.replace(/^\.\//,"");if(!Ep(i))return;const a=await t(i);if(null===a)return;const c=Bp(a,o,r.parserOptions);c?.mcpServers&&Object.keys(c.mcpServers).length>0&&Wp(s,c.mcpServers,n(i))},a=e=>{const t=Bp(JSON.stringify(e),o,r.parserOptions);t?.mcpServers&&Object.keys(t.mcpServers).length>0&&Wp(s,t.mcpServers,r.manifestSourcePath??"manifest")};if("string"==typeof e)await i(e);else if(Array.isArray(e))for(const t of e)"string"==typeof t?await i(t):"object"==typeof t&&null!==t&&a(t);else"object"==typeof e&&null!==e&&a(e);return s}(t,e,{toSourcePath:o,manifestSourcePath:r,installPathForExpansion:s,parserOptions:n.parserOptions});for(const[e,t]of Object.entries(i.mcpServers))"fill"===a&&void 0!==c[e]||(c[e]=t,l[e]=i.mcpServerSourcePaths[e])}return 0===Object.keys(c).length?null:{mcpServers:c,...Object.keys(l).length>0&&{mcpServerSourcePaths:l}}}const qp=new Set(["CREDENTIAL","CREDENTIALS","KEY","PASSPHRASE","PASSWORD","SECRET","TOKEN"]);function zp(e){return function(e){return e.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/[^a-z\d]+/gi,"_").toUpperCase().split("_").filter((e=>e.length>0))}(e).some((e=>qp.has(e)))}const Gp=/\$\{(?:env:([A-Z][A-Z0-9_]*)|([A-Z][A-Z0-9_]*)(?::-([^}]*))?)\}/g,Vp=new Set(["CURSOR_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT"]),Kp=new Set(["api","aws","db","dd","gcp","http","https","id","mcp","ssl","tls","uri","url"]);function Jp(e){return e.split("_").filter((e=>e.length>0)).map((e=>{const t=e.toLowerCase();return Kp.has(t)?e.toUpperCase():e.charAt(0).toUpperCase()+t.slice(1)})).join(" ")}function Zp(e,t){if("string"!=typeof e){if(Array.isArray(e))for(const r of e)Zp(r,t);else if(null!==e&&"object"==typeof e)for(const r of Object.values(e))Zp(r,t)}else for(const[,r,n,o]of e.matchAll(Gp)){const e=r??n;if(void 0===e||Vp.has(e)||t.has(e))continue;const s=void 0===r?`\${${e}}`:`\${env:${e}}`;t.set(e,{reference:s,defaultValue:o})}}function Xp(e){if(void 0===e?.mcpServers)return;const t=new Map;if(Zp(e.mcpServers,t),0===t.size)return;const r={};for(const e of[...t.keys()].sort()){const n=t.get(e);if(void 0===n)continue;const{reference:o,defaultValue:s}=n;r[e]={type:"string",title:Jp(e),description:void 0===s||0===s.length?`Referenced as \`${o}\` in this plugin's MCP configuration.`:`Referenced as \`${o}\` in this plugin's MCP configuration. Defaults to \`${s}\` when left blank.`,...zp(e)?{writeOnly:!0}:{}}}return{type:"object",properties:r}}const Qp=[".md",".mdc",".markdown"],Yp=[...Qp,".txt"],ef=/^---\s*\n([\s\S]*?)\n---/;function tf(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function rf(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9.-]/g,"")}function nf(e){const t=e.match(ef);if(!t)return{};try{const e=Oh.Ay.load(t[1],{schema:Oh.Ay.JSON_SCHEMA});if(!tf(e))return{};const r=tf(e.metadata)?e.metadata:void 0,n=of(e.environments??r?.environments);return{disabledEnvironments:of(e["disabled-environments"]??r?.disabledEnvironments),environments:n,name:"string"==typeof e.name?e.name:void 0,description:"string"==typeof e.description?e.description:void 0}}catch{const e=t[1],r=e.match(/^name:\s*(.+)$/m),n=e.match(/^description:\s*(.+)$/m);return r||n?{name:r?r[1].trim():void 0,description:n?n[1].trim():void 0}:{}}}function of(e){if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e&&e.length>0));return 0===t.length?void 0:t}if("string"==typeof e){const t=e.split(",").map((e=>e.trim())).filter((e=>e.length>0));return 0===t.length?void 0:t}}function sf(e){return rf((0,s.basename)(e).replace(/\.(md|mdc|markdown|txt)$/i,""))}function af(e){const t=new Set,r=[];for(const n of e)t.has(n.name)||(t.add(n.name),r.push(n));return r}class cf{constructor(e){this.fetcher=e}async discoverComponents(e={}){const t=e.basePath??"",r=t?`${t}/`:"",n=e.manifest;let o;try{o=await this.fetcher.listDirectory(t)}catch{o=[]}const s=new Set(o.filter((e=>"dir"===e.type)).map((e=>e.name.toLowerCase()))),i=Op.filter((e=>o.some((t=>"file"===t.type&&t.name===e)))),a=o.some((e=>"file"===e.type&&"SKILL.md"===e.name)),[c,l,u,d,h,p,f]=await Promise.all([a&&void 0===n?.skills?this.discoverRootSkill(r):Promise.resolve(null),void 0!==n?.skills?this.discoverFromManifestPaths(r,n.skills,!0,Qp):s.has("skills")?this.discoverSkills(`${r}skills`):Promise.resolve([]),void 0!==n?.agents?this.discoverFromManifestPaths(r,n.agents,!1,Qp):s.has("agents")?this.discoverMarkdownComponents(`${r}agents`,Qp):Promise.resolve([]),void 0!==n?.hooks?this.discoverHooksFromManifest(r,n.hooks):s.has("hooks")?this.discoverHooksFromJson(`${r}hooks/hooks.json`):Promise.resolve([]),void 0!==n?.commands?this.discoverFromManifestPaths(r,n.commands,!1,Yp):s.has("commands")?this.discoverMarkdownComponents(`${r}commands`,Yp):Promise.resolve([]),void 0!==n?.rules?this.discoverFromManifestPaths(r,n.rules,!1,Qp):s.has("rules")?this.discoverMarkdownComponents(`${r}rules`,Qp):Promise.resolve([]),this.discoverMcpServers(r,n?.mcpServers,i)]);return{skills:af(c?[c,...l]:l),agents:af(u),hooks:d,commands:af(h),rules:af(p),mcpServers:f.servers,mcpVariables:f.variables,mcpConfigs:f.configs}}async discoverHooksFromJson(e){try{if(!await this.fetcher.fileExists(e))return[];const{content:t}=await this.fetcher.fetchFile(e),r=JSON.parse(t);return tf(r)&&tf(r.hooks)?Object.keys(r.hooks).map((t=>({name:rf(t),path:e,description:`Hook: ${t}`}))):[]}catch{return[]}}async discoverHooksFromManifest(e,t){if("string"==typeof t){if(!Ep(t))return[];const r=`${e}${t.replace(/^\.\//,"")}`;return r.endsWith(".json")?this.discoverHooksFromJson(r):this.discoverHooksFromJson(`${r}/hooks.json`)}const r=t.hooks??t;return!r||"object"!=typeof r||Array.isArray(r)?[]:Object.keys(r).map((e=>({name:rf(e),path:"manifest",description:`Hook: ${e}`})))}async discoverFromManifestPaths(e,t,r=!1,n=Qp){if("string"==typeof t){if(!Ep(t))return[];const o=`${e}${t.replace(/^\.\//,"")}`.replace(/\/$/,"");return r?this.discoverSkills(o):this.discoverMarkdownComponents(o,n)}const o=[];for(const n of t)try{if(!Ep(n))continue;const t=`${e}${n.replace(/^\.\//,"")}`;if(r){const e=t.endsWith("SKILL.md")?t:`${t.replace(/\/$/,"")}/SKILL.md`;if(!await this.fetcher.fileExists(e)){const e=t.replace(/\/$/,""),r=await this.discoverSkills(e);o.push(...r);continue}let r=sf(t.endsWith("SKILL.md")?t.slice(0,-8).replace(/\/$/,""):t);const{content:n}=await this.fetcher.fetchFile(e),s=nf(n);if(r=s.name??r,r){const t={disabledEnvironments:s.disabledEnvironments,environments:s.environments,name:rf(r),path:e};void 0!==s.description&&(t.description=s.description),o.push(t)}}else{if(!await this.fetcher.fileExists(t))continue;let e=sf(t);const{content:r}=await this.fetcher.fetchFile(t),n=nf(r);e=n.name??e;const s=n.description;if(e){const r={name:rf(e),path:t};void 0!==s&&(r.description=s),o.push(r)}}}catch{}return o}async discoverMarkdownComponents(e,t=Qp,r=new Set){let n;try{n=await this.fetcher.listDirectory(e,r)}catch{return[]}const o=n.filter((e=>"file"===e.type&&t.some((t=>e.name.endsWith(t))))),s=n.filter((e=>"dir"===e.type)),[i,a]=await Promise.all([Promise.all(o.map((async e=>{try{let t=sf(e.name);const{content:r}=await this.fetcher.fetchFile(e.path),n=nf(r);t=n.name?rf(n.name):t;const o=n.description;if(!t)return null;const s={name:t,path:e.path};return void 0!==o&&(s.description=o),s}catch{return null}}))),Promise.all(s.map((e=>this.discoverMarkdownComponents(e.path,t,r))))]);return[...i.filter((e=>null!==e)),...a.flat()]}async discoverRootSkill(e){try{const t=`${e}SKILL.md`;let r=rf((0,s.basename)(e.replace(/[\\/]+$/,"")));const{content:n}=await this.fetcher.fetchFile(t),o=nf(n);if(r=o.name?rf(o.name):r,!r)return null;const i={disabledEnvironments:o.disabledEnvironments,environments:o.environments,name:r,path:t};return void 0!==o.description&&(i.description=o.description),i}catch{return null}}async discoverSkills(e){let t;try{t=await this.fetcher.listDirectory(e)}catch{return[]}const r=t.filter((e=>"dir"===e.type));return(await Promise.all(r.map((async e=>{try{const t=`${e.path}/SKILL.md`;if(!await this.fetcher.fileExists(t))return null;const{content:r}=await this.fetcher.fetchFile(t),n=nf(r),o=n.name?rf(n.name):rf(e.name);if(!o)return null;const s={disabledEnvironments:n.disabledEnvironments,environments:n.environments,name:o,path:t};return void 0!==n.description&&(s.description=n.description),s}catch{return null}})))).filter((e=>null!==e))}async discoverMcpServers(e,t,r){const n=new Map,o=async t=>{const r=n.get(t);if(void 0!==r)return r;const o=this.fetcher.fetchFile(`${e}${t}`).then((({content:e})=>e)).catch((()=>null));return n.set(t,o),o},s=async n=>Hp(o,t,void 0!==t?"manifest":void 0,{fallbackFileNames:r,manifestPrecedence:n,toSourcePath:t=>`${e}${t}`,parserOptions:{skipExpansion:!0}}),i=await s("fill");if(void 0===i?.mcpServers)return{servers:[],variables:void 0,configs:void 0};const a=void 0===t?i:await s("override"),c=a?.mcpServers??i.mcpServers,l={};for(const[e,t]of Object.entries(c))l[e]=t;return{servers:Object.keys(i.mcpServers).map((e=>({name:rf(e),path:i.mcpServerSourcePaths?.[e]??"manifest"}))),variables:Xp(a??i),configs:l}}}class lf extends Error{constructor(e,t){super(`Invalid Claude Code plugin identifier "${t}": ${e}`),this.raw=t,this.name="CCPluginIdentifierError"}}function uf(e){const t=e.trim();if(!t)throw new lf("Empty identifier",e);const r=/^[a-zA-Z0-9_-]+$/,n=t.indexOf("@");if(n!==t.lastIndexOf("@"))throw new lf("Plugin identifier cannot contain multiple @ symbols",e);if(-1===n){if(!r.test(t))throw new lf("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(t.length>100)throw new lf("Plugin name must be 100 characters or less",e);return{name:t,sourceType:"marketplace",marketplace:"claude-plugins-official",raw:e}}const o=t.slice(0,n).trim(),s=t.slice(n+1).trim();if(!o)throw new lf("Missing plugin name before @",e);if(!s)throw new lf("Missing source after @",e);if(!r.test(o))throw new lf("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(o.length>100)throw new lf("Plugin name must be 100 characters or less",e);if(s.startsWith("github:")){const t=s.slice(7).trim();if(!t||!/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(t))throw new lf("Invalid GitHub repo format, expected 'org/repo' (e.g., 'anthropics/claude-plugins')",e);return{name:o,sourceType:"github",githubRepo:t,raw:e}}if(s.startsWith("local:")){const t=s.slice(6).trim();if(!t)throw new lf("Missing path after 'local:'",e);return{name:o,sourceType:"local",localPath:t,raw:e}}if(s.startsWith("url:")){const t=s.slice(4).trim();if(!t)throw new lf("Missing Git URL after 'url:'",e);try{new URL(t)}catch{throw new lf("Invalid Git URL format",e)}return{name:o,sourceType:"url",gitUrl:t,raw:e}}const i=s.indexOf("#");let a,c;if(-1!==i?(a=s.slice(0,i).trim(),c=s.slice(i+1).trim()):a=s,!a)throw new lf("Missing marketplace name",e);if(!r.test(a))throw new lf("Marketplace name must contain only alphanumeric characters, dashes, and underscores",e);return{name:o,sourceType:"marketplace",marketplace:a,version:c,raw:e}}function df(e){if("claude-plugin"===e.source)return e.sourceInfo.raw;if("user-local"===e.source)return`user-local:${e.sourceInfo.name}`;if("extension"===e.source){const t=e.sourceInfo;return`extension:${t.extensionId}:${t.localPath}`}const t=e.sourceInfo;return`${t.name}-${t.version}`}function hf(e){return e.sourceInfo.name}function pf(e){switch(e.source){case"claude-plugin":case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplace;default:return}}function ff(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.pluginDbId;default:return}}function mf(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplaceDbId;default:return}}function gf(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function wf(e){return!!gf(e)&&(void 0===e.enabledPlugins||gf(e.enabledPlugins))}function yf(e){return JSON.parse(e)}function vf(e){const t=e??process.env.HOME??"";return(0,s.join)(t,".claude")}async function bf(e){const t={enabledPlugins:{}};let r=!1;const n=(0,s.join)(e,".claude","settings.json");try{const e=yf(await(0,xo.readFile)(n,"utf-8"));wf(e)&&e.enabledPlugins&&(Object.assign(t.enabledPlugins,e.enabledPlugins),r=!0)}catch{}const o=(0,s.join)(e,".claude","settings.local.json");try{const e=yf(await(0,xo.readFile)(o,"utf-8"));wf(e)&&e.enabledPlugins&&(Object.assign(t.enabledPlugins,e.enabledPlugins),r=!0)}catch{}return r?t:null}function Sf(e,t){const r=(0,s.resolve)(e),n=(0,s.resolve)(e,t),o=(0,s.relative)(r,n);if(o.startsWith("..")||(0,s.isAbsolute)(o))throw new Error(`Invalid subPath: path traversal not allowed (${JSON.stringify(t)})`);return n}async function kf(e){try{return(await(0,xo.lstat)(e)).isSymbolicLink()}catch{return!1}}async function _f(e){if(await kf(e))throw new Error(`Refusing to read symlink: ${e}`);return(0,xo.readFile)(e,"utf-8")}async function Cf(e){if((await(0,xo.stat)(e)).size>10485760)throw new Error(`File ${e} exceeds maximum size of 10485760 bytes`)}function Ef(e){const t=e instanceof Error?e.message:String(e);return/timed?\s*out/i.test(t)?"timeout":/clone|fetch|git/i.test(t)?"clone":/manifest|marketplace\.json/i.test(t)?"manifest":/parse|invalid|malformed/i.test(t)?"parse":/install|download|copy/i.test(t)?"install":"unknown"}async function xf({installPath:e,logo:t}){const r=t?.trim();if(r&&!(0,s.isAbsolute)(r)&&!r.includes("://"))try{const t=await(0,xo.realpath)(e),n=Sf(t,r),o=await(0,xo.realpath)(n);if(Sf(t,o),!(await(0,xo.stat)(o)).isFile())return;return await Cf(o),(0,Pd.pathToFileURL)(o).href}catch{return}}function Pf(e){const t={};return void 0!==e.version&&(t.version=e.version),void 0!==e.homepage&&(t.homepage=e.homepage),void 0!==e.repository&&(t.repository=e.repository),t}function Rf(e){return void 0!==e.version||void 0!==e.homepage||void 0!==e.repository}function If(e,t){return Pf({version:e.version??t?.version,homepage:e.homepage??t?.homepage,repository:e.repository??t?.repository})}async function Tf(e,t,r){let n;for(const o of zh){const i=(0,s.join)(e,o);let a;try{if(await kf(i))continue;if(!(await(0,xo.stat)(i)).isFile())continue;await Cf(i),a=await _f(i)}catch{continue}const c=_p(a);if(!c.success)continue;const l=c.data,u=l.commands,d=l.agents,h=l.skills,p=l.rules,f=l.hooks,m=l.mcpServers,g=void 0!==u||void 0!==d||void 0!==h||void 0!==p||void 0!==f||void 0!==m,w="string"==typeof l.displayName?l.displayName:void 0,y="string"==typeof l.description?l.description:void 0,v=l.author?.name,b=await xf({installPath:e,logo:l.logo}),S=Pf(l),k=l.variables,_=l.capabilities,C=void 0!==w||void 0!==y||void 0!==v||void 0!==b||void 0!==k||void 0!==_;if(!g&&!C&&!Rf(S))continue;if(!g&&!C){n=n?{...n,fields:If(n.fields,S)}:{fields:S,path:i,relPath:o,unrecognizedSchemaId:c.unrecognizedSchemaId};continue}void 0!==c.unrecognizedSchemaId&&r.log("debug",`${t}: ${o} declares an unrecognized $schema, loading anyway: ${c.unrecognizedSchemaId}`);const E=If(S,n?.fields);return{manifestFilePath:i,...g&&{manifestOptions:{commands:u,agents:d,skills:h,rules:p,hooks:f,mcpServers:m}},...(C||Rf(E))&&{metadata:{displayName:w,description:y,authorName:v,logoUrl:b,...E,variables:k,capabilities:_}}}}if(void 0!==n)return void 0!==n.unrecognizedSchemaId&&r.log("debug",`${t}: ${n.relPath} declares an unrecognized $schema, loading anyway: ${n.unrecognizedSchemaId}`),{manifestFilePath:n.path,metadata:n.fields}}async function Af(e,t){const r=function(e,t){const r=new Map,n=(0,s.resolve)(e),o=(0,s.resolve)(t?.symlinkTargetRoot??n),i=(0,xo.realpath)(o).catch((()=>o));function a(e){const t=(0,s.resolve)(e);try{return Sf(n,t)}catch{throw new Error(`Path escapes plugin directory: ${e}`)}}async function c(e){const t=a(e),r=await i,n=await(0,xo.realpath)(t);try{return Sf(r,n)}catch{throw new Error(`Path escapes plugin directory via symlink: ${e}`)}}return{async listDirectory(t,r){const n=a(t?(0,s.join)(e,t):e);try{const e=await c(n);if(r?.has(e))return[];r?.add(e);const o=await(0,xo.readdir)(e,{withFileTypes:!0}),i=[];for(const e of o){const r=(0,s.join)(n,e.name);let o=e.isDirectory()?"dir":"file";if(e.isSymbolicLink())try{const e=await c(r);o=(await(0,xo.stat)(e)).isDirectory()?"dir":"file"}catch{continue}i.push({name:e.name,type:o,path:t?`${t}/${e.name}`:e.name})}return i}catch{return[]}},async fetchFile(t){const n=r.get(t);if(void 0!==n)return{content:n};const o=a((0,s.join)(e,t)),i=await c(o);await Cf(i);const l=await(0,xo.readFile)(i,"utf-8");return r.set(t,l),{content:l}},async fileExists(t){try{const r=a((0,s.join)(e,t)),n=await c(r);return(await(0,xo.stat)(n)).isFile()}catch{return!1}}}}(e),n=new cf(r),o=await n.discoverComponents({manifest:t}),[i,a,c,l]=await Promise.all([$f(r,o.skills,e),Df(r,o.agents,e),Of(r,o.commands,e),Mf(r,o.rules,e)]);return{skills:i,agents:a,commands:c,rules:l}}async function $f(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Nf({content:Ap(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}async function Mf(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Nf({content:Ap(t,r),relativePath:o.path});s&&n.push({...s,name:o.name})}catch{}return n}async function Df(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Lf({content:Ap(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}async function Of(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=jf({content:Ap(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}function Ff(e){if("string"==typeof e){const t=function(e){const t=[];let r=0,n=0;for(let o=0;o0)n--;else if(","===s&&0===n){const n=e.slice(r,o).trim();n&&t.push(n),r=o+1}}if(n>0){for(const n of e.slice(r).split(",")){const e=n.trim();e&&t.push(e)}return t}const o=e.slice(r).trim();return o&&t.push(o),t}(e);return t.length>0?t:void 0}if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e)).map((e=>e.trim())).filter(Boolean);return t.length>0?t:void 0}}function Nf({content:e,relativePath:t}){try{const r=rh(e),n=t.replace(/\\/g,"/"),o=n.split("/").filter((e=>e.length>0)),s=o.length>=2?o[o.length-2]:void 0,i=o[o.length-1]??n,a=s??i.replace(/\.md$/i,""),c="string"==typeof r.data.name?r.data.name.trim():void 0,l=of(r.data.environments??r.data.metadata?.environments),u=of(r.data["disabled-environments"]??r.data.metadata?.disabledEnvironments);return{path:t,name:c&&c.length>0?c:a,description:"string"==typeof r.data.description?r.data.description:void 0,globs:Ff(r.data.globs),alwaysApply:!0===r.data.alwaysApply,content:e,environments:l,disabledEnvironments:u}}catch{return null}}function Lf({content:e,relativePath:t}){try{const n=rh(e),o=n.content.trim();if(!o)return null;let i;"string"==typeof n.data.tools?i=n.data.tools.split(",").map((e=>e.trim())).filter(Boolean):Array.isArray(n.data.tools)&&(i=n.data.tools.map((e=>"string"==typeof e?e.trim():String(e))).filter(Boolean));const a=n.data.permissionMode??n.data.permissionmode,c=(0,s.basename)(t);return{path:t,name:"string"==typeof n.data.name?n.data.name:(0,s.basename)(c,(0,s.extname)(c)).replace(/[\s_]+/g,"-"),description:"string"==typeof n.data.description?n.data.description:void 0,tools:i,model:"string"==typeof n.data.model?n.data.model:"inherit",prompt:o,permissionMode:(r=a,"readonly"===(r??"").trim().toLowerCase()?"readonly":"default")}}catch{return null}var r}function jf({content:e,relativePath:t}){try{const r=rh(e);let n;const o=r.data["argument-hint"];"string"==typeof o?n=o:Array.isArray(o)&&(n=`[${o.join(" ")}]`);const i=(0,s.basename)(t);return{path:t,name:"string"==typeof r.data.name?r.data.name:(0,s.basename)(i,(0,s.extname)(i)),description:"string"==typeof r.data.description?r.data.description:void 0,argumentHint:n,content:r.content.trim()}}catch{return null}}function Uf(e){if(void 0!==e)return{configuredVariables:e.configuredVariables}}async function Bf(e,t,r){const n=r??Uf(t);return async function(e,t={}){const r=t.toSourcePath??(e=>e);let n,o,s;for(const t of zh){const i=await e(t);if(null===i)continue;let a;try{a=JSON.parse(i)}catch{continue}s=Uh(a);const c=_p(i);if(c.success){void 0!==c.data.mcpServers&&(n=c.data.mcpServers,o=r(t));break}}return Hp(e,n,o,void 0===s?t:{...t,parserOptions:{...t.parserOptions,pluginSchemaId:s}})}(function(e){return async t=>{if(!Ep(t))return null;const r=(0,s.join)(e,t);try{return await kf(r)?null:(await(0,xo.stat)(r)).isFile()?(await Cf(r),await _f(r)):null}catch{return null}}}(e),{fallbackFileNames:jp(),manifestPrecedence:"override",toSourcePath:t=>(0,s.join)(e,t),installPathForExpansion:e,parserOptions:n})}async function Wf(e,t,r){const n=await Bf(e,void 0,{log:r});if(n)return n;for(const n of Vh){const o=(0,s.join)(e,n);try{if(!(await(0,xo.stat)(o)).isFile())continue;const n=await(0,xo.readFile)(o,"utf-8"),i=JSON.parse(n);if(!zf(i)||!Array.isArray(i.plugins))continue;const a=i.plugins.filter(Gf),c=t.name,l=a.find((e=>e.name===c));if(!l?.mcpServers?.length)continue;for(const t of l.mcpServers){const n=t.replace(/^\.\//,"");if(!Ep(n))continue;const o=(0,s.join)(e,n);try{await Cf(o);const t=Bp(await _f(o),e,{log:r});if(t?.mcpServers&&Object.keys(t.mcpServers).length>0){const e=Object.fromEntries(Object.keys(t.mcpServers).map((e=>[e,o])));return{...t,mcpServerSourcePaths:e}}}catch{}}return null}catch{}}return null}Error;const Hf=new Set(Object.values(Rd));function qf(e){return Hf.has(e)}function zf(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Gf(e){return!(!zf(e)||"string"!=typeof e.name)&&(void 0===e.mcpServers||Array.isArray(e.mcpServers)&&e.mcpServers.every((e=>"string"==typeof e)))}function Vf(e,t){const r={};for(const[n,o]of Object.entries(e.hooks))Array.isArray(o)&&qf(n)&&(r[n]=o.map((e=>"command"in e&&"string"==typeof e.command?{...e,command:Ap(e.command,t)}:"prompt"in e&&"string"==typeof e.prompt?{...e,prompt:Ap(e.prompt,t)}:e)));return{...e,hooks:r}}async function Kf(e,t,r,n,o){if("object"==typeof n){const s=Jf(n,t,r);return s&&"config"in s?{config:Vf(s.config,e),...void 0!==o&&{sourcePath:o}}:s}let i,a,c;if("string"==typeof n){const t=n.replace(/^\.\//,"");if(!Ep(t))return;i=t.endsWith(".json")?(0,s.join)(e,t):(0,s.join)(e,t,"hooks.json")}else i=(0,s.join)(e,"hooks","hooks.json");try{if(await kf(i))return;if(!(await(0,xo.stat)(i)).isFile())return}catch{return}try{await Cf(i),a=await(0,xo.readFile)(i,"utf-8")}catch{return}try{c=JSON.parse(a)}catch{return{error:{source:"claude-plugin",message:`Plugin ${t} ${i}: invalid JSON`}}}const l=Jf(c,t,r);return l&&"config"in l?{config:Vf(l.config,e),sourcePath:i}:l}function Jf(e,t,r){const n=function(e){if(!Ad(e))return"unknown";const t=e,r="object"==typeof t.hooks&&null!==t.hooks?t.hooks:null;if(!r)return"unknown";for(const e of Object.values(r)){if(!Array.isArray(e)||0===e.length)continue;const t=e[0];if(Ad(t)){if("hooks"in t&&Array.isArray(t.hooks))return"claude-code";if("command"in t||"prompt"in t||"type"in t)return"cursor"}}return"unknown"}(e);if("cursor"===n){const r=Fd(e);return r.isValid&&Fd(e).isValid?{config:e}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${r.errors.join("; ")}`}}}if("claude-code"===n){if(!(zf(o=e)&&zf(o.hooks)&&Object.keys(o.hooks).length>0))return;const n=Yd(e.hooks,{warn:e=>r.log("warn",`Plugin ${t} hooks: ${e}`),info:e=>r.log("info",`Plugin ${t} hooks: ${e}`)}),s=Fd(n);return s.isValid?{config:n}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${s.errors.join("; ")}`}}}var o}async function Zf(e,t,r,n){const o=n?.log??$p,s=await Tf(e,t,o),i={...Uf(r)??(n?.configuredVariables?{configuredVariables:n.configuredVariables}:void 0),log:o},[a,c,l]=await Promise.all([Af(e,s?.manifestOptions),Bf(e,r,i),Kf(e,t,o,s?.manifestOptions?.hooks,s?.manifestFilePath)]);return{...a,...void 0!==s?.metadata?.displayName&&{displayName:s.metadata.displayName},...void 0!==s?.metadata?.description&&{description:s.metadata.description},...void 0!==s?.metadata?.authorName&&{authorName:s.metadata.authorName},...void 0!==s?.metadata?.logoUrl&&{logoUrl:s.metadata.logoUrl},...void 0!==s?.metadata?.version&&{version:s.metadata.version},...void 0!==s?.metadata?.homepage&&{homepage:s.metadata.homepage},...void 0!==s?.metadata?.repository&&{repository:s.metadata.repository},variablesSchema:s?.metadata?.variables,mcpConfig:c,capabilities:s?.metadata?.capabilities??[],hooks:l}}async function Xf(e,t,r){const n=r?.log??$p,o=await Tf(e,t.raw,n),[s,i,a]=await Promise.all([Af(e,o?.manifestOptions),Wf(e,t,n),Kf(e,t.raw,n,o?.manifestOptions?.hooks,o?.manifestFilePath)]);return{identifier:{source:"claude-plugin",sourceInfo:t},installPath:e,...void 0!==o?.metadata?.displayName&&{displayName:o.metadata.displayName},...void 0!==o?.metadata?.description&&{description:o.metadata.description},...void 0!==o?.metadata?.authorName&&{authorName:o.metadata.authorName},...void 0!==o?.metadata?.logoUrl&&{logoUrl:o.metadata.logoUrl},...void 0!==o?.metadata?.version&&{version:o.metadata.version},...void 0!==o?.metadata?.homepage&&{homepage:o.metadata.homepage},...void 0!==o?.metadata?.repository&&{repository:o.metadata.repository},...s,mcpConfig:i??void 0,capabilities:o?.metadata?.capabilities??[],hooks:a}}async function Qf(e,t,r,n){const o=`${r.name}@${r.version}`,{displayName:s,description:i,authorName:a,logoUrl:c,version:l,homepage:u,repository:d,variablesSchema:h,skills:p,rules:f,agents:m,commands:g,mcpConfig:w,capabilities:y,hooks:v}=await Zf(e,o,r,{log:n?.log});return{identifier:{source:t,sourceInfo:r},installPath:e,...void 0!==s&&{displayName:s},...void 0!==i&&{description:i},...void 0!==a&&{authorName:a},...void 0!==c&&{logoUrl:c},...void 0!==l&&{version:l},...void 0!==u&&{homepage:u},...void 0!==d&&{repository:d},variablesSchema:h,skills:p,rules:f,agents:m,commands:g,mcpConfig:w??void 0,capabilities:y,hooks:v}}async function Yf(e,t,r={}){const n=r.log??$p,o=performance.now(),i=await async function(e){const t=vf(e),r=(0,s.join)(t,"plugins","installed_plugins.json");try{const e=yf(await(0,xo.readFile)(r,"utf-8"));return gf(n=e)&&gf(n.plugins)?e:null}catch{return null}var n}(r.userHomeDir);if(!i?.plugins)return n.log("info",`loadAllEnabledPlugins: no installed plugins metadata found (${(performance.now()-o).toFixed(1)}ms)`),[];const a=await async function(e){const t=vf(e),r=(0,s.join)(t,"settings.json");try{const e=yf(await(0,xo.readFile)(r,"utf-8"));return wf(e)?e:null}catch{return null}}(r.userHomeDir),c=function(e){if(void 0===e)return[];const t="string"==typeof e?[e]:e,r=new Set,n=[];for(const e of t){if(!e)continue;const t=(0,s.resolve)(e);r.has(t)||(r.add(t),n.push(t))}return n}(e),l=function(e,t,r){if(0===r.length)return Dh(e,t,null,void 0);const n=new Set;for(const{settings:e}of r)for(const[t,r]of Object.entries(e?.enabledPlugins??{}))!1===r&&n.add(t);const o=new Set,s=[];for(const{workspacePath:i,settings:a}of r){const r=Dh(e,t,a,i);for(const e of r)o.has(e.pluginId)||n.has(e.pluginId)||(o.add(e.pluginId),s.push(e))}return s}(i,a,await(0,Nr.PH)(c,(async e=>({workspacePath:e,settings:await bf(e)})),{max:8})),u=[],d=r.onError;for(const{pluginId:e,installPath:t}of l)try{const r=performance.now(),o=uf(e),s=await Xf(t,o,{log:n});u.push(s),n.log("info",`loadClaudePlugin ${e} loaded in ${(performance.now()-r).toFixed(1)}ms`)}catch(t){const r=t instanceof Error?t:new Error(String(t));if(d)try{d(uf(e),r)}catch{d({name:e.split("@")[0]??e,sourceType:"marketplace",marketplace:"unknown",raw:e},r)}}return n.log("info",`loadAllEnabledPlugins completed in ${(performance.now()-o).toFixed(1)}ms (${l.length} resolved, ${u.length} loaded)`),u}const em=new Map;async function tm(e){const{entry:t,slug:r,cacheManager:n}=e;if(void 0===t.backendContent&&!Ph(t.downloadUrl))return rm(e);const o=n.getCacheDir({marketplaceSlug:r,pluginId:t.pluginId,version:t.version}),s=em.get(o);if(void 0!==s)return s;const i=rm(e).finally((()=>{em.delete(o)}));return em.set(o,i),i}async function rm(e){const{entry:t,slug:r,client:n,cacheManager:o,pluginLogger:s}=e;if(await o.isCached({marketplaceSlug:r,pluginId:t.pluginId,version:t.version})){const e=o.getCacheDir({marketplaceSlug:r,pluginId:t.pluginId,version:t.version});return s.log("info",`loadFromMarketplaceSource: Found cached plugin: ${t.pluginId} at ${e}`,{marketplaceSlug:r,pluginId:t.pluginId,gitRef:t.version,marketplaceId:t.marketplace?.id}),e}const i=o.getCacheDir({marketplaceSlug:r,pluginId:t.pluginId,version:t.version});s.log("info",`loadFromMarketplaceSource: Plugin missing from cache, installing: ${t.pluginId} at ${i}`,{marketplaceSlug:r,pluginId:t.pluginId,gitRef:t.version,marketplaceId:t.marketplace?.id}),await(0,xo.mkdir)(i,{recursive:!0});try{await n.installPlugin(t,i),await o.markCacheComplete({marketplaceSlug:r,pluginId:t.pluginId,version:t.version})}catch(e){try{await(0,xo.rm)(i,{recursive:!0,force:!0})}catch{}throw e}return i}async function nm(e){const{error:t,entry:r,slug:n,client:o,cacheManager:s,pluginLogger:i}=e;if(!Ch(t))return;if("revision_superseded"===t.reason){const t=await(o.relistPlugin?.(r).catch((()=>{})));if(void 0!==t)try{return{entry:t,installPath:await tm({...e,entry:t})}}catch(e){if(!Ch(e))throw e}}const a=await async function(e){const{cacheManager:t,marketplaceSlug:r,pluginId:n,exceptVersion:o}=e,s=ih(Sh),i=await t.listCachedVersions({marketplaceSlug:r,pluginId:n});let a;for(const e of i){if(!e.startsWith(s))continue;const i=Rh(e.slice(s.length));if(i===o)continue;const c=hh({parent:t.getCacheDir({marketplaceSlug:r,pluginId:n,version:i}),name:uh}),l=await(0,xo.stat)(c).then((e=>e.mtimeMs),(()=>{}));void 0!==l&&(void 0===a||l>a.installedAtMs)&&(a={version:i,installedAtMs:l})}return a?.version}({cacheManager:s,marketplaceSlug:n,pluginId:r.pluginId,exceptVersion:r.version});return void 0!==a?(i.log("warn",`Plugin ${r.pluginId} keeps its installed version until the listed one can be downloaded`,{pluginId:r.pluginId,reason:t.reason}),{entry:{...r,version:a},installPath:s.getCacheDir({marketplaceSlug:n,pluginId:r.pluginId,version:a})}):void 0}async function om(e){const t=e.log??$p,r=performance.now(),{client:n,userId:o,teamId:s,onCursorError:i,pruneOldVersions:a,pluginFilter:c,onPluginsListed:l}=e,u=[],d=e.cacheManager??new fh(e.userHomeDir),h=performance.now();let p;try{p=await n.listEnabledPlugins(o,s)}catch(e){return t.captureException(e,{error_type:"list_enabled_plugins"}),t.increment("marketplace.source_unavailable",1),t.log("error",`marketplace listEnabledPlugins failed after ${(performance.now()-h).toFixed(1)}ms; treating source as unavailable: ${e instanceof Error?e.message:String(e)}`),{plugins:[],failures:[],sourceUnavailable:!0}}t.log("info",`marketplace listEnabledPlugins completed in ${(performance.now()-h).toFixed(1)}ms (${p.plugins.length} plugins)`),l&&await l(p.plugins);const f=[];if(p.listFailures){u.push(...p.listFailures);for(const e of p.listFailures)f.push({identifier:{source:e.marketplaceName&&"cursor-public"!==e.marketplaceName?"cursor-third-party":"cursor-first-party",sourceInfo:{name:e.pluginName,version:"",...void 0!==e.pluginDbId&&{pluginDbId:e.pluginDbId},marketplace:e.marketplaceName}},installPath:"",loadError:e.errorMessage,skills:[],rules:[],agents:[],commands:[],capabilities:[]})}const m=new Map;for(const e of p.plugins){if(c&&!c(e))continue;let r=e;try{const e=r.marketplace?.name;if(!e){const e=new Error(`Plugin ${r.name} has no marketplace metadata — cannot determine cache path`);u.push({pluginName:r.name,pluginId:r.pluginId,marketplaceName:void 0,errorMessage:e.message,errorType:"manifest"}),i&&i(r,e);continue}const o=`${e}/${r.pluginId}`;let s,a=m.get(o);a||(a={slug:e,pluginId:r.pluginId,versions:[]},m.set(o,a)),a.versions.push(r.version);try{s=await tm({entry:r,slug:e,client:n,cacheManager:d,pluginLogger:t})}catch(o){const i=await nm({error:o,entry:r,slug:e,client:n,cacheManager:d,pluginLogger:t});if(void 0===i)throw o;({entry:r,installPath:s}=i),a.versions.push(r.version)}const c=r.marketplace?.name,l=void 0!==c&&"cursor-public"!==c&&c.length>0?"cursor-third-party":"cursor-first-party",h={name:r.name,version:r.version,pluginDbId:r.pluginDbId,configuredVariables:r.configuredVariables,marketplace:c,marketplaceDbId:r.marketplaceDbId,isTeamRequired:r.isTeamRequired},p=await Qf(s,l,h,{log:t});f.push(p);try{await d.pruneOldVersions({marketplaceSlug:e,pluginId:r.pluginId,keepVersions:[r.version]})}catch{}}catch(e){t.captureException(e,{error_type:"load_plugin_from_marketplace"});const n=e instanceof Error?e:new Error(String(e));u.push({pluginName:r.name,pluginId:r.pluginId,marketplaceName:r.marketplace?.name,errorMessage:n.message,errorType:Ef(n)});const o=r.marketplace?.name,s=void 0!==o&&"cursor-public"!==o&&o.length>0;f.push({identifier:{source:s?"cursor-third-party":"cursor-first-party",sourceInfo:{name:r.name,version:r.version,pluginDbId:r.pluginDbId,marketplace:o,marketplaceDbId:r.marketplaceDbId,isTeamRequired:r.isTeamRequired}},installPath:"",loadError:n.message||"Plugin load failed",skills:[],rules:[],agents:[],commands:[],capabilities:[]}),i&&i(r,n)}}if(a)for(const{slug:e,pluginId:t,versions:r}of m.values())try{await d.pruneOldVersions({marketplaceSlug:e,pluginId:t,keepVersions:r})}catch{}return t.log("info",`loadFromMarketplaceSource completed in ${(performance.now()-r).toFixed(1)}ms (${f.length} plugins loaded, ${u.length} failures)`),{plugins:f,failures:u,sourceUnavailable:!1}}function sm(e){const{identifier:t}=e;switch(t.source){case"claude-plugin":return"marketplace"===t.sourceInfo.sourceType&&t.sourceInfo.marketplace?`${t.sourceInfo.marketplace}/${t.sourceInfo.name}`:void 0;case"cursor-first-party":case"cursor-third-party":return t.sourceInfo.marketplace?`${t.sourceInfo.marketplace}/${t.sourceInfo.name}`:void 0;default:return}}function im(e){return sm(e)??`path:${e.installPath}`}function am(e,t={}){return{...e,model:t.stripModel?void 0:e.model,tools:t.stripTools?void 0:e.tools}}function cm(e,t){const r=[];for(const o of e){const e=df(o.identifier),i=`plugin:${e}`,a=hf(o.identifier),c=pf(o.identifier),l=ff(o.identifier),u=mf(o.identifier);for(const d of t(o)){const t=(0,s.join)(o.installPath,d.path),{type:h,globs:p,description:f}=(n=d).alwaysApply?{type:"global"}:n.globs&&n.globs.length>0?{type:"fileGlobbed",globs:n.globs}:n.description?{type:"agentFetched",description:n.description}:{type:"manuallyAttached"};r.push({fullPath:t,content:d.content,type:h,globs:p,description:f,pluginIdentifier:e,gitRemoteOrigin:i,plugin:a,marketplace:c,pluginId:l,marketplaceId:u,environments:d.environments,disabledEnvironments:d.disabledEnvironments})}}var n;return r}var lm=r("../proto/dist/generated/agent/v1/agent_skills_pb.js");const um=(0,Vs.debuglog)("agent-skills-catalog-cache");function dm(e){return(0,ko.createHash)("sha256").update(JSON.stringify({v:1,...e})).digest("hex")}async function hm(e){try{return(await(0,xo.stat)(e)).mtimeMs}catch{return}}function pm(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const fm=[".kits","cursor-pages"],mm={configDir:".cursor",subdir:"skills-cursor",thirdParty:!1,builtin:!0},gm=[{configDir:".cursor",subdir:"skills",thirdParty:!1,builtin:!1},{configDir:".claude",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".codex",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".grok",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".agents",subdir:"skills",thirdParty:!1,builtin:!1},mm],wm=(new Set(gm.map((e=>e.configDir))),new Set(["imagegen","openai-docs","opneai-docs","plugin-creator","skill-creator","skill-installer"]));function ym(e){return e.replace(/\\/g,"/").split("/").filter(Boolean)}function vm(e){const t=ym(e);if(function(e){const t=e.findIndex(((t,r)=>function(e,t){return gm.some((r=>r.configDir===e&&r.subdir===t))}(t,e[r+1])));return-1!==t&&e.slice(t+2).some((e=>e.startsWith(".")))}(t))return!0;const r=t.lastIndexOf(".codex");if(-1===r||"skills"!==t[r+1])return!1;const n=t.at(-1),o="SKILL.md"===n?t.at(-2):n;return void 0!==o&&wm.has(o)}function bm(e){return{dirPath:(0,s.join)(e,mm.configDir,mm.subdir),scope:"builtin",source:"builtin"}}const Sm="canvas";function km(e,t){return{dirPath:(0,s.join)(bm(e).dirPath,...fm),scope:"builtin",source:"builtin"}}function _m(e,t){const r=e.replace(/\\/g,"/"),n=t.replace(/\\/g,"/").replace(/\/+$/,"");if(r.startsWith(`${n}/`))return ym(r.slice(n.length+1))}function Cm(e,t){const r=_m(e,t);return void 0!==r&&!r.some((e=>e.startsWith(".")))}function Em(e){return gm.filter((t=>!t.builtin&&(e||!t.thirdParty)))}function xm(e,t){return Em(t).map((t=>({dirPath:(0,s.join)(e,t.configDir,t.subdir),scope:"project",source:"workspace"})))}function Pm(e,t){return Em(t).map((t=>({dirPath:(0,s.join)(e,t.configDir,t.subdir),scope:"user",source:"user"})))}var Rm=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function Im(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const Tm=gm.map((({configDir:e,subdir:t,thirdParty:r})=>({pattern:new RegExp(`[/\\\\]${Im(e)}[/\\\\]${Im(t)}[/\\\\]`,"i"),requiresThirdParty:r}))),Am=/[/\\]\.cursor[/\\]rules[/\\]/i,$m=[{pattern:/[/\\]\.cursor[/\\]agents[/\\]/i,requiresThirdParty:!1},{pattern:/[/\\]\.claude[/\\]agents[/\\]/i,requiresThirdParty:!0}],Mm=new Set(["AGENTS.md","CLAUDE.md","CLAUDE.local.md"]);function Dm(e,t){const r=e.replace(/\\/g,"/"),n=(0,s.basename)(r);if(Mm.has(n))return"AGENTS.md"===n||t&&("CLAUDE.md"===n||"CLAUDE.local.md"===n)?"markdown":void 0;if(Am.test(r)&&n.endsWith(".mdc"))return"rules";if("SKILL.md"===n)for(const{pattern:e,requiresThirdParty:n}of Tm)if(e.test(r)){if(n&&!t)continue;return"skills"}if(n.endsWith(".md"))for(const{pattern:e,requiresThirdParty:n}of $m)if(e.test(r)){if(n&&!t)continue;return"agents"}}class Om{constructor(e,t,r,n){this.root=e,this.gitExecutor=t,this.userHomeDirectory=r,this.getThirdPartyExtensibilityEnabled=n}static getRipwalkCache(){return Om.ripwalkCache??=new _a,Om.ripwalkCache}async discover(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,D.VI)(e.withName("NestedExtensibilityService.discover")),!1),n={rules:[],skills:[],markdown:[],agents:[]},o=(0,s.resolve)(this.root),i=(0,s.resolve)(this.userHomeDirectory);if(o===i||zs(o,{platform:process.platform,homeDirectory:i}).length>0)return r.span.setAttribute("nested_extensibility.rules",0),r.span.setAttribute("nested_extensibility.skills",0),r.span.setAttribute("nested_extensibility.markdown",0),r.span.setAttribute("nested_extensibility.agents",0),n;if(!await tc(e,this.gitExecutor,(0,s.resolve)(this.root)))return r.span.setAttribute("nested_extensibility.rules",0),r.span.setAttribute("nested_extensibility.skills",0),r.span.setAttribute("nested_extensibility.markdown",0),r.span.setAttribute("nested_extensibility.agents",0),n;const a=this.getThirdPartyExtensibilityEnabled(),c=this.buildIncludeGlobs(a),l={root:this.root,includeGlobs:c,excludeGlobs:dc,followSymlinks:!0,source:"nested_extensibility"},u={rules:[],skills:[],markdown:[],agents:[]},d=Om.getRipwalkCache();try{const e=d.walk(r.ctx,l);try{for await(const t of e.lines){const e=Dm(t,a);e&&u[e].push((0,s.resolve)(this.root,t))}}finally{d.delete(l)}}catch{}return r.span.setAttribute("nested_extensibility.rules",u.rules.length),r.span.setAttribute("nested_extensibility.skills",u.skills.length),r.span.setAttribute("nested_extensibility.markdown",u.markdown.length),r.span.setAttribute("nested_extensibility.agents",u.agents.length),u}catch(e){t.error=e,t.hasError=!0}finally{Rm(t)}}buildIncludeGlobs(e){const t=["*/**/.cursor/**","*/**/.agents/**","*/**/AGENTS.md"];return e&&t.push("*/**/.claude/**","*/**/.codex/**","*/**/.grok/**","*/**/CLAUDE.md","*/**/CLAUDE.local.md"),t}}const Fm=new Set(["node_modules","__pycache__","dist","build"]);async function Nm({rootDir:e,includeFile:t,maxDepth:r=10,containmentRootDir:n}){const o=[],i=[{dir:e,depth:0}],a=new Set,c=void 0!==n?await(0,xo.realpath)(n):null,l=e=>{if(null===c)return!0;const t=(0,s.relative)(c,e);return""===t||!t.startsWith("..")&&!(0,s.isAbsolute)(t)};for(;i.length>0;){const e=i.pop();if(void 0===e)continue;const{dir:n,depth:c}=e;if(c>r)continue;try{const e=await(0,xo.realpath)(n);if(!l(e))continue;if(a.has(e))continue;a.add(e)}catch{continue}const d=await(0,xo.readdir)(n,{withFileTypes:!0,encoding:"utf8"}).catch((()=>null));if(null!==d)for(const e of d){const r=(0,s.join)(n,e.name);let a=e.isDirectory(),l=e.isFile();if(e.isSymbolicLink())try{const e=await(0,xo.stat)(r);a=e.isDirectory(),l=e.isFile()}catch{continue}if(a){if((u=e.name).startsWith(".")||Fm.has(u))continue;i.push({dir:r,depth:c+1})}else l&&t(e.name)&&o.push(r)}}var u;return o.sort(((e,t)=>e.localeCompare(t))),o}const Lm={agentStoreSkillsDirs:[],userHomeDirectory:""};function jm(e){const t=e.replace(/\\/g,"/");return t.endsWith("/")?t.slice(0,-1):t}function Um(e,t){const r=jm(t.userHomeDirectory),n=e.replace(/\\/g,"/");if(r.length>0)for(const e of t.agentStoreSkillsDirs){const t=jm(e);if(t.length>0&&n.startsWith(`${t}/`))return{key:`${r}::skills/${n.slice(t.length+1)}`,inAgentStore:!0}}return{key:Bm(e),inAgentStore:!1}}function Bm(e){const t=e.replace(/\\/g,"/"),r=t.toLowerCase(),n=r.indexOf("/.cursor/"),o=r.indexOf("/.claude/"),s=r.indexOf("/.codex/"),i=r.indexOf("/.grok/"),a=r.indexOf("/.agents/");return-1!==n?`${t.slice(0,n)}::${t.slice(n+9)}`:-1!==o?`${t.slice(0,o)}::${t.slice(o+9)}`:-1!==s?`${t.slice(0,s)}::${t.slice(s+8)}`:-1!==i?`${t.slice(0,i)}::${t.slice(i+7)}`:-1!==a?`${t.slice(0,a)}::${t.slice(a+9)}`:e}function Wm(e,t){const r=new Map,n=[];for(const o of e){const{key:e,inAgentStore:s}=Um(o.fullPath,t),i=r.get(e);void 0!==i?s&&!n[i].inAgentStore&&(n[i]={item:o,inAgentStore:s}):(r.set(e,n.length),n.push({item:o,inAgentStore:s}))}return n.map((e=>e.item))}var Hm=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},qm=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const zm=(0,d.h)("local-exec:cursor-rules");function Gm(e){return"/"===e||"\\"===e}function Vm(e){return e.split(/[\\/]+/).filter((e=>e.length>0)).length}async function Km(e){return await Nm({rootDir:e,includeFile:e=>"SKILL.md"===e})}async function Jm(e){let t;try{t=await Bi(e)}catch(t){return{skillFilePath:e,error:kd(t)}}try{return{skillFilePath:e,content:t,parsed:rh(t)}}catch(t){return{skillFilePath:e,error:_d(t)}}}async function Zm(e){const t=await ns(e);return{...await Jm(e),realSkillFilePath:t}}function Xm(e){return eg(e.data?.environments??e.data?.metadata?.environments)??[]}function Qm(e){return eg(e.data?.["disabled-environments"]??e.data?.metadata?.disabledEnvironments)??[]}function Ym(e){return eg(e.data?.metadata?.scopedTo??e.data?.["metadata.scopedTo"])??[]}function eg(e){if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e&&e.length>0));return 0===t.length?void 0:t}if("string"==typeof e){const t=e.split(",").map((e=>e.trim())).filter((e=>e.length>0));return 0===t.length?void 0:t}}function tg(e,t,r){const n=function(e){const t=e.data?.metadata?.surfaces;return Array.isArray(t)?t:"string"==typeof t?t.split(",").map((e=>e.trim())).filter(Boolean):[]}(e);return n.length>0&&!n.includes(t)&&!r.includes(e.data?.name)}function rg(e){return Jo(e,1536)}function ng(e){return!0===e.data?.alwaysApply}function og(e){return!0===e.data?.["disable-model-invocation"]}function sg({skillFilePath:e,content:t,parsed:r}){const n=function(e){return function(e){const t=(e.matter??"").trim(),r=e.language?.toLowerCase();return t.length>0&&"js"!==r&&"javascript"!==r?`---\n${t}\n---`:nh("",e.data??{}).trim()}(e)}(r),o=function({fullPath:e,name:t,description:r,body:n}){const o=[],s=function(e){const t=e.replace(/\\/g,"/").split("/"),r=t[t.length-1]??"";return"SKILL.md"===r&&t.length>=2?t[t.length-2]??"":r}(e);s.length>64&&o.push(`Name is ${xd(s.length)} characters; the limit is 64. Rename the skill's folder.`),Ed.test(s)||o.push('Name should be lowercase letters and numbers joined by single hyphens, like "pdf-helper". Rename the skill\'s folder.'),void 0!==t&&t!==s&&o.push(`Frontmatter name ${JSON.stringify(t)} doesn't match the folder name ${JSON.stringify(s)}, which is the name the skill goes by. Make them the same.`);const i=r?.trim().length??0;i>1024&&o.push(`Description is ${xd(i)} characters; the limit is ${xd(1024)}.`);const a=Math.round(n.length/4);return a>5e3&&o.push(`Body is about ${xd(a)} tokens; the recommended limit is ${xd(5e3)}. Move details into reference files that SKILL.md links to.`),o}({fullPath:e,name:"string"==typeof r.data?.name?r.data.name:void 0,description:"string"==typeof r.data?.description?r.data.description:void 0,body:r.content});if(ng(r))return new Jr.DX({fullPath:e,content:t,frontmatter:n,type:new Jr.f5({type:{case:"global",value:new Jr.i9}}),environments:Xm(r),disabledEnvironments:Qm(r),scopedTo:Ym(r),warnings:o});const s="string"==typeof r.data?.description?rg(r.data.description):void 0,i=Cd(s,og(r));return i?new Jr.DX({fullPath:e,parseError:i,frontmatter:n,scopedTo:Ym(r),type:new Jr.f5({type:{case:"agentFetched",value:new Jr.Xo}})}):new Jr.DX({fullPath:e,content:t,frontmatter:n,type:new Jr.f5({type:{case:"agentFetched",value:new Jr.Xo({description:s})}}),environments:Xm(r),disabledEnvironments:Qm(r),scopedTo:Ym(r),warnings:o})}function ig({skillFilePath:e,content:t,parsed:r}){const n="string"==typeof r.data?.description?rg(r.data.description):"",o=Ff(r.data?.paths??r.data?.globs),s=og(r);return new lm.N({fullPath:e,content:t,description:n,globs:o??[],parseError:Cd(n,s),environments:Xm(r),disabledEnvironments:Qm(r),scopedTo:Ym(r),disableModelInvocation:s})}function ag({rules:e,agentSkills:t,skillFilePath:r,errorMessage:n}){e.push(function({skillFilePath:e,errorMessage:t}){return new Jr.DX({fullPath:e,parseError:t,type:new Jr.f5({type:{case:"agentFetched",value:new Jr.Xo}})})}({skillFilePath:r,errorMessage:n})),t.push(function({skillFilePath:e,errorMessage:t}){return new lm.N({fullPath:e,parseError:t})}({skillFilePath:r,errorMessage:n}))}function cg(e,t,r,n){if("error"in t)return e.realSkillFilePathsByFullPath.set(t.skillFilePath,t.realSkillFilePath),void ag({rules:e.rules,agentSkills:e.agentSkills,skillFilePath:t.skillFilePath,errorMessage:t.error});tg(t.parsed,r,n)||(e.realSkillFilePathsByFullPath.set(t.skillFilePath,t.realSkillFilePath),e.rules.push(sg(t)),ng(t.parsed)||e.agentSkills.push(ig(t)))}const lg=(0,Vs.debuglog)("cursor-rules-service");function ug(){return{rules:[],agentSkills:[],realSkillFilePathsByFullPath:new Map}}function dg(e){return t=>(lg("%s: %O",e,t),ug())}function hg(e,t){return dm({kind:"agent-store",surface:e,roots:[...t].sort()})}function pg(e,t){const r=t.replace(/\\/g,"/").replace(/\/+$/,"");return""!==r&&e.replace(/\\/g,"/").startsWith(`${r}/`)}function fg(e){let t;if(!0===e.frontmatter.alwaysApply)t={case:"global",value:new Jr.i9};else{const r=Ff(e.frontmatter.globs);t=r&&r.length>0?{case:"fileGlobbed",value:new Jr.uT({globs:r})}:"string"==typeof e.frontmatter.description&&e.frontmatter.description.trim().length>0?{case:"agentFetched",value:new Jr.Xo({description:rg(e.frontmatter.description)})}:{case:"manuallyAttached",value:new Jr._u}}const r=e.frontmatter["metadata.environments"],n=Array.isArray(r)?r:[],o=e.frontmatter["metadata.disabledEnvironments"],s=Array.isArray(o)?o:[],i=e.frontmatter["metadata.scopedTo"],a=Array.isArray(i)?i:[];return new Jr.DX({fullPath:e.path,content:e.body,type:new Jr.f5({type:t}),environments:n,disabledEnvironments:s,scopedTo:a,frontmatter:e.rawFrontmatter??""})}class mg{constructor(e,t){this.cursorRulesServices=e,this.getAgentStoreSkillsContext=t,this.onChangeCallbacks=new Set}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Hm(t,(0,D.VI)(e.withName("MergedCursorRulesService.getAllCursorRules")),!1),n=this.cursorRulesServices.map((e=>e.getAllCursorRules(r.ctx).catch((e=>((0,Vs.debuglog)("Failed to load cursor rules from service:",e),[])))));return Wm((await Promise.all(n)).flat(),this.getAgentStoreSkillsContext())}catch(e){t.error=e,t.hasError=!0}finally{qm(t)}}reload(e){for(const t of this.cursorRulesServices)t.reload(e)}scheduleDidChangeRules(){void 0===this.changeTimer&&(this.changeTimer=setTimeout((()=>{this.changeTimer=void 0;for(const e of Array.from(this.onChangeCallbacks))e()}),mg.CHANGE_COALESCE_MS))}ensureChangeListenersRegistered(){void 0===this.disposeChangeListeners&&(this.disposeChangeListeners=this.cursorRulesServices.map((e=>e.onDidChangeRules((()=>this.scheduleDidChangeRules())))))}disposeChangeListenersIfUnused(){if(!(this.onChangeCallbacks.size>0||void 0===this.disposeChangeListeners)){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0,void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0)}}onDidChangeRules(e){return this.onChangeCallbacks.add(e),this.ensureChangeListenersRegistered(),()=>{this.onChangeCallbacks.delete(e),this.disposeChangeListenersIfUnused()}}dispose(){if(void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0),this.onChangeCallbacks.clear(),void 0!==this.disposeChangeListeners){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0}for(const e of this.cursorRulesServices)e.dispose&&e.dispose()}}mg.CHANGE_COALESCE_MS=1e3;class gg{constructor(e,t,r,n,i,a,c,l){this.gitExecutor=t,this.rootDirectory=r,this.loadNestedRules=n,this.getThirdPartyExtensibilityEnabled=i,this.loadTraceId=void 0,this.onChangeCallbacks=new Set,this.nestedExtensibilityService=new Om(r,t,(0,o.homedir)(),i),this.ignoreService=c??new Rc(t,void 0,[this.rootDirectory]);const u=performance.now();if(this._rules=this.load(e,l).then((t=>{try{zm.info(e,"LocalCursorRulesService load completed",{durationMs:Math.round(performance.now()-u),ruleCount:t.length})}catch{}return t})).catch((e=>((0,Vs.debuglog)("Failed to load cursor rules:",e),[]))),a){const e=[".cursor/rules/**/*.mdc","AGENTS.md","CLAUDE.md","CLAUDE.local.md",".cursorrules",".cursorignore"];this.unsubscribeWatcher=a.subscribe(this.rootDirectory,e,(e=>{const t={stack:[],error:void 0,hasError:!1};try{const r=(0,b.q6)(),n=Hm(t,(0,D.VI)(r.withName("LocalCursorRulesService.fileWatcher.subscribe")),!1);if(".cursorignore"===(0,s.basename)(e))return gg.getRipwalkCache().clear(),void this.reload(n.ctx);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{qm(t)}}))}}reload(e){this._rules=this.load(e).catch((e=>((0,Vs.debuglog)("Failed to load cursor rules:",e),[])));for(const e of this.onChangeCallbacks)e()}static getRipwalkCache(){return gg.ripwalkCache??=new _a,gg.ripwalkCache}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.reloadAtPath")),!1);if(Xr((0,s.basename)(t)))return void this.reload(n.ctx);const o=this._rules;this._rules=(async()=>{const e=(await o).filter((e=>e.fullPath!==t));const r=(await this.readRulesAtPath(n.ctx,t)).map((e=>this.toCursorRule(e)));return[...e,...r]})().catch((e=>((0,Vs.debuglog)("Failed to load cursor rules at path:",e),[])));for(const e of this.onChangeCallbacks)e()}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}isRuleMarkdownFile(e){return Xr(e)}async readRulesAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.readRulesAtPath")),!1),o=(0,s.basename)(t);if(".cursorrules"===o){const e=(0,s.resolve)(this.rootDirectory),t=await tc(n.ctx,this.gitExecutor,e)||e,r=await this.loadCursorRulesRule(n.ctx,t);return r?[r]:[]}if(o.endsWith(".mdc"))return await wg(t);if(this.isRuleMarkdownFile(o))try{return await this.loadRulesFromMarkdownFile(n.ctx,(0,s.dirname)(t),o)}catch{}return[]}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}dispose(){this.unsubscribeWatcher&&(this.unsubscribeWatcher(),this.unsubscribeWatcher=void 0)}async load(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.load")),!1);this.loadTraceId=n.span.spanContext().traceId;const o=(0,s.resolve)(this.rootDirectory),i=await tc(n.ctx,this.gitExecutor,o)||o,a=this.loadCursorRulesRule(n.ctx,i).then((e=>e?[e]:[])),c=this.loadRulesFromDirAndAncestors(n.ctx,o);let l,u;if(this.loadNestedRules){const e=t??this.nestedExtensibilityService.discover(n.ctx);l=e.then((e=>this.parseNestedRuleFiles(n.ctx,e.rules))),u=e.then((e=>this.parseNestedMarkdownFiles(n.ctx,e.markdown)))}else l=[],u=[];const d=(await Promise.all([a,c,l,u])).flat(),h=new Map;for(const e of d)h.set(e.path,e);const p=[...h.values()];return(await async function(e){const t=e.filter((e=>Xr((0,s.basename)(e.fullPath))));if(t.length<=1)return[...e];const r=await(0,Nr.PH)(t,(e=>async function(e){try{const t=await(0,xo.stat)(e,{bigint:!0});if(0n!==t.ino)return`ino:${String(t.dev)}:${String(t.ino)}`}catch{}return await ns(e)}(e.fullPath)),{max:16}),n=t.map(((e,t)=>({item:e,identity:r[t],dir:(0,s.dirname)(e.fullPath),content:e.content.trim()}))).sort(((e,t)=>{const r=Vm(e.dir)-Vm(t.dir);if(0!==r)return r;const n="AGENTS.md"===(0,s.basename)(e.item.fullPath);return n===("AGENTS.md"===(0,s.basename)(t.item.fullPath))?0:n?-1:1})),o=[];for(const e of n)o.some((t=>{return((r=t.dir)===(n=e.dir)||!!n.startsWith(r)&&(Gm(r.at(-1))||Gm(n[r.length])))&&(t.identity===e.identity||t.content===e.content);var r,n}))||o.push(e);const i=new Set(o.map((e=>e.item)));return e.filter((e=>!Xr((0,s.basename)(e.fullPath))||i.has(e)))}(p.map((e=>({fullPath:e.path,content:e.body,rule:e}))))).map((e=>this.toCursorRule(e.rule)))}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}async loadCursorRulesRule(e,t){const r={stack:[],error:void 0,hasError:!1};try{Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.loadCursorrules")),!1);try{const e=(0,s.join)(t,".cursorrules");if((await(0,xo.stat)(e)).isFile())return{filename:".cursorrules",path:e,frontmatter:{alwaysApply:!0},body:await Bi(e)}}catch{}return null}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{return Hm(t,(0,D.VI)(e.withName("LocalCursorRulesService.getAllCursorRules")),!1).span.setAttribute("cacheTraceId",this.loadTraceId??"undefined"),await this._rules}catch(e){t.error=e,t.hasError=!0}finally{qm(t)}}toCursorRule(e){return fg({path:e.path,body:e.body,frontmatter:e.frontmatter,rawFrontmatter:e.rawFrontmatter})}async loadRulesFromDirAndAncestors(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirAndAncestors")),!1),o=[];let i=t;const a=this.getThirdPartyExtensibilityEnabled();for(;;){const e=(0,s.join)(i,".cursor","rules"),t=i;o.push((async()=>await this.dirIsDirectory(n.ctx,e)?this.loadRulesFromDirectory(n.ctx,t):[])());const r=[];a&&r.push("CLAUDE.md","CLAUDE.local.md"),r.push("AGENTS.md");for(const e of r)o.push(this.loadRulesFromMarkdownFile(n.ctx,i,e));const c=(0,s.dirname)(i);if(c===i)break;i=c}const c=(await Promise.all(o)).flat();return n.span.setAttribute("rules",c.length),c}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}async loadRulesFromMarkdownFile(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{Hm(n,(0,D.VI)(e.withName("LocalCursorRulesService.loadRulesFromMarkdownFile")),!1).span.setAttribute("filename",r);try{const e=(0,s.join)(t,r);if(await this.isCursorIgnored(e))return[];if((await(0,xo.stat)(e)).isFile()){const t=Qr({content:await Bi(e),filename:r});return[{filename:(0,s.basename)(e,".md"),path:e,frontmatter:{alwaysApply:!0},body:t}]}}catch{}return[]}catch(e){n.error=e,n.hasError=!0}finally{qm(n)}}async isCursorIgnored(e){try{const t=await xc((0,s.resolve)(this.rootDirectory,e));return null===t||await this.ignoreService.isCursorIgnored(t)}catch{return!1}}async parseNestedRuleFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.parseNestedRuleFiles")),!1),o=(await Promise.all(t.map((async e=>{try{const t=rn(await Bi(e));if(t)return{filename:(0,s.basename)(e,".mdc"),path:e,frontmatter:t.frontmatter,rawFrontmatter:t.rawFrontmatter,body:t.body}}catch{}})))).filter((e=>void 0!==e));return n.span.setAttribute("ruleFiles",o.length),o}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}async parseNestedMarkdownFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.parseNestedMarkdownFiles")),!1),o=(await Promise.all(t.map((async e=>{try{const t=(0,s.basename)(e);if(!this.isRuleMarkdownFile(t))return[];const r=(0,s.dirname)(e);return await this.loadRulesFromMarkdownFile(n.ctx,r,t)}catch{}return[]})))).flat();return n.span.setAttribute("markdownFiles",o.length),o}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}async loadRulesFromDirectory(e,t){return await async function(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=Hm(n,(0,D.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirectory")),!1),i=[];try{(0,s.join)(t,".cursorignore");const e={root:(0,s.join)(t,".cursor","rules"),includeGlobs:["**/*.mdc"],followSymlinks:!0,source:"cursor_rules"},n=r.walk(o.ctx,e);for await(const t of n.lines){const r=(0,s.join)(e.root,t);i.push(...await wg(r))}}catch{}return o.span.setAttribute("rules",i.length),i}catch(e){n.error=e,n.hasError=!0}finally{qm(n)}}(e,t,gg.getRipwalkCache())}async dirIsDirectory(e,t){const r={stack:[],error:void 0,hasError:!1};try{Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.dirIsDirectory")),!1);try{return(await(0,xo.stat)(t)).isDirectory()}catch{return!1}}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}}async function wg(e){try{const t=rn(await Bi(e));if(t)return[{filename:(0,s.basename)(e,".mdc"),path:e,frontmatter:t.frontmatter,rawFrontmatter:t.rawFrontmatter,body:t.body}]}catch{}return[]}class yg{constructor(e,t,r,n,o,s,i=()=>!0,a=Promise.resolve(),c="ide",l,u=()=>[],d,h,p=()=>[],f){if(this.workspacePaths=t,this.userHomeDirectory=r,this.gitExecutor=n,this.getEnabledSkills=p,this.ignoreService=f,this.agentStoreLoadRequestedWhileInFlight=!1,this.agentStoreLoadGeneration=0,this.watchersByFolder=new Map,this.onChangeCallbacks=new Set,this.reloadRequestedDuringSeed=!1,this.surface=c,this.waitBeforeSkillLoad="function"==typeof a?a:()=>a,this.getAgentStoreSkillRoots=u,this.fileWatcher=s,this.getThirdPartyExtensibilityEnabled=i,this.catalogCache=d,this.builtinSkillRootDir=bm(r).dirPath,this.canvasKitSkillRootDir=void 0===h?void 0:km(r).dirPath,this.workspaceCatalogKey=dm({kind:"workspace",surface:c,loadNestedSkills:o,thirdPartyExtensibility:i(),workspacePaths:[...t].sort(),userHomeDirectory:r,...void 0===h?{}:{canvasKit:h}}),void 0!==l&&l.length!==t.length)throw new Error(`initialNestedExtensibilityResults length (${l.length}) must match workspacePaths length (${t.length})`);this.nestedExtensibilityEntries=o?t.map((e=>new Om(e,n,r,i))):[],this.foldersToWatch=this.computeFoldersToWatch();const m=performance.now();let g=!1,w=!1,y=!1;const v=this.loadAll(e,l).then((t=>{try{zm.info(e,"AgentSkillsCursorRulesService load completed",{durationMs:Math.round(performance.now()-m),ruleCount:t.rules.length,skillCount:t.agentSkills.length,servedFromCache:g})}catch{}return t})).catch((e=>(w=!0,dg("Failed to load Agent Skills")(e))));if(void 0===this.catalogCache)this._loaded=v;else{const t=this.readCatalog(this.workspaceCatalogKey).then((r=>(y=!0,this._loaded!==t?this._loaded:(w&&this.closeSeedWindow(e),void 0===r?v:(g=!0,r)))));this.seededLoaded=t,this._loaded=t,v.then((r=>{this._loaded===t?w?y&&this.closeSeedWindow(e):(this._loaded=v,g&&this.notifyChanged(),this.persistCatalog(this.workspaceCatalogKey,r),this.closeSeedWindow(e)):this.seededLoaded=void 0}))}this.refreshAgentStoreSkills(),this.setupWatchers(this.foldersToWatch)}closeSeedWindow(e){this.seededLoaded=void 0,this.reloadRequestedDuringSeed&&(this.reloadRequestedDuringSeed=!1,this.reload(e))}async readCatalog(e){if(void 0!==this.catalogCache)try{const t=await this.catalogCache.read(e);return void 0===t?void 0:await async function(e){if(!function(e){if(!pm(e))return!1;const t=e.fileMtimesMs;return 1===e.version&&Array.isArray(e.rules)&&Array.isArray(e.agentSkills)&&Array.isArray(e.realSkillFilePathsByFullPath)&&e.realSkillFilePathsByFullPath.every((e=>Array.isArray(e)&&2===e.length&&"string"==typeof e[0]&&"string"==typeof e[1]))&&pm(t)&&Object.values(t).every((e=>"number"==typeof e&&Number.isFinite(e)))}(e))return;const t=new Map;if(await Promise.all(e.realSkillFilePathsByFullPath.map((async([r,n])=>{const o=e.fileMtimesMs[n];void 0!==o&&await hm(r)===o&&t.set(r,n)}))),0===t.size)return;const r=e=>void 0!==e&&t.has(e);try{return{rules:e.rules.map((e=>Jr.DX.fromJson(e,{ignoreUnknownFields:!0}))).filter((e=>r(e.fullPath))),agentSkills:e.agentSkills.map((e=>lm.N.fromJson(e,{ignoreUnknownFields:!0}))).filter((e=>r(e.fullPath))),realSkillFilePathsByFullPath:t}}catch(e){return void um("snapshot failed to decode: %O",e)}}(t)}catch(e){return void lg("Failed to read the skills catalog cache: %O",e)}}persistCatalog(e,t){const r=this.catalogCache;void 0!==r&&async function(e){const t=new Set(e.realSkillFilePathsByFullPath.values()),r={};return await Promise.all(Array.from(t,(async e=>{const t=await hm(e);void 0!==t&&(r[e]=t)}))),{version:1,rules:e.rules.map((e=>e.toJson())),agentSkills:e.agentSkills.map((e=>e.toJson())),realSkillFilePathsByFullPath:Array.from(e.realSkillFilePathsByFullPath),fileMtimesMs:r}}(t).then((t=>r.write(e,t))).catch((e=>{lg("Failed to persist the skills catalog cache: %O",e)}))}computeFoldersToWatch(){const e=this.getThirdPartyExtensibilityEnabled(),t=new Set;for(const r of this.workspacePaths){t.add((0,s.join)(r,".cursor","rules"));for(const n of xm(r,e))t.add(n.dirPath)}for(const r of Pm(this.userHomeDirectory,e))t.add(r.dirPath);for(const e of this.getAgentStoreSkillRoots())t.add(e);return t.add(this.builtinSkillRootDir),void 0!==this.canvasKitSkillRootDir&&t.add(this.canvasKitSkillRootDir),Array.from(t)}isIgnoredSkillPath(e){if(void 0!==this.canvasKitSkillRootDir){if(Cm(e,this.canvasKitSkillRootDir))return!1;if(function(e,t){const r=_m(e,t);return void 0!==r&&2===r.length&&r[0]===Sm&&"SKILL.md"===r[1]}(e,this.builtinSkillRootDir))return!0}return vm(e)}setupWatchers(e){if(!this.fileWatcher)return;const t=["**"];for(const r of e){if(this.watchersByFolder.has(r))continue;const e=this.fileWatcher.subscribe(r,t,(e=>{const t={stack:[],error:void 0,hasError:!1};try{const r=(0,b.q6)(),n=Hm(t,(0,D.VI)(r.withName("AgentSkillsCursorRulesService.fileWatcher.subscribe")),!1);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{qm(t)}}));this.watchersByFolder.set(r,e)}}removeWatchers(e){for(const t of e){const e=this.watchersByFolder.get(t);e&&(e(),this.watchersByFolder.delete(t))}}async getAllCursorRules(e){const[t]=await Promise.all([this._loaded,this.awaitAgentStoreSeed()]);return this.withAgentStoreSkills(t).rules}async awaitAgentStoreSeed(){void 0!==this.agentStoreSeedInFlight&&await(0,Nr.wj)(this.agentStoreSeedInFlight,250,"Agent Store skills cache read timed out").catch((()=>{}))}reload(e){this.syncWatchers(),this.seededLoaded=void 0,this.reloadRequestedDuringSeed=!1;const t=this.loadAll(e),r=t.catch(dg("Failed to load Agent Skills"));this._loaded=r,t.then((e=>{this._loaded===r&&this.persistCatalog(this.workspaceCatalogKey,e)}),(()=>{})),this.refreshAgentStoreSkills(),this.notifyChanged()}reloadSkillRoots(){try{this.syncWatchers()}finally{this.refreshAgentStoreSkills()}}async agentStoreSkillsSettled(){for(let e=this.agentStoreWalk;void 0!==e;e=this.agentStoreWalk)await e}syncWatchers(){const e=this.computeFoldersToWatch(),t=new Set(this.foldersToWatch),r=new Set(e);this.removeWatchers(this.foldersToWatch.filter((e=>!r.has(e)))),this.setupWatchers(e.filter((e=>!t.has(e)))),this.foldersToWatch=e}isPrunedByExtensibilityScan(e){if(void 0!==this.canvasKitSkillRootDir&&Cm(e,this.canvasKitSkillRootDir))return!1;const t=e.replace(/\\/g,"/");for(const e of this.foldersToWatch){const r=e.replace(/\\/g,"/");if(t.startsWith(`${r}/`))return t.slice(r.length+1).split("/").slice(0,-1).some((e=>e.startsWith(".")))}return!1}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("AgentSkillsCursorRulesService.reloadAtPath")),!1),o=function(e,t,r=i){for(const n of t){const t=r.relative(n,e);if(""!==t&&".."!==t&&!t.startsWith(`..${r.sep}`)&&!r.isAbsolute(t))return r.join(n,t)}return e}(t,this.foldersToWatch),a=o.endsWith("SKILL.md")?o:(0,s.join)(o,"SKILL.md");if(void 0!==this.seededLoaded&&this._loaded===this.seededLoaded&&!this.getAgentStoreSkillRoots().some((e=>pg(a,e))))return void(this.reloadRequestedDuringSeed=!0);if(this.getAgentStoreSkillRoots().some((e=>pg(a,e))))return void this.refreshAgentStoreSkills();if(this.foldersToWatch.some((e=>""===(0,s.relative)(e,o))))return void this.reload(n.ctx);const c=this._loaded,l=(async()=>{const e=await c,{realSkillFilePathsByFullPath:t}=e,r=function(e,t){const r=new Map(e.realSkillFilePathsByFullPath);for(const e of t)r.delete(e);return{rules:e.rules.filter((e=>!t.has(e.fullPath))),agentSkills:e.agentSkills.filter((e=>!t.has(e.fullPath))),realSkillFilePathsByFullPath:r}}(e,new Set([a]));if(this.isIgnoredSkillPath(a)||this.isPrunedByExtensibilityScan(a))return r;const o=t.get(a);if(void 0===o){try{await(0,xo.stat)(a)}catch{return r}return await this.loadAll(n.ctx)}let s;try{s=await(0,xo.realpath)(a)}catch{return await this.loadAll(n.ctx)}if(s!==o)return await this.loadAll(n.ctx);try{return cg(r,{...await async function(e){const t=await Bi(e);return{skillFilePath:e,content:t,parsed:rh(t)}}(a),realSkillFilePath:s},this.surface,this.getEnabledSkills()),r}catch{return await this.loadAll(n.ctx)}})().catch(dg("Failed to load Agent Skills at path"));this._loaded=l,this.notifyChanged()}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}async getAllAgentSkills(e){const[t]=await Promise.all([this._loaded,this.awaitAgentStoreSeed()]);return this.withAgentStoreSkills(t).agentSkills}withAgentStoreSkills(e){const t=this.settledAgentStoreSkills?.loaded;if(void 0===t||0===t.realSkillFilePathsByFullPath.size)return e;const r=new Set(e.realSkillFilePathsByFullPath.values()),n={rules:[...e.rules],agentSkills:[...e.agentSkills],realSkillFilePathsByFullPath:new Map(e.realSkillFilePathsByFullPath)},o=new Set;for(const[e,s]of t.realSkillFilePathsByFullPath)n.realSkillFilePathsByFullPath.has(e)||r.has(s)?o.add(e):n.realSkillFilePathsByFullPath.set(e,s);for(const e of t.rules)o.has(e.fullPath)||n.rules.push(e);for(const e of t.agentSkills)o.has(e.fullPath)||n.agentSkills.push(e);return n}refreshAgentStoreSkills(){const e=this.getAgentStoreSkillRoots().filter((e=>""!==e.trim())),t=++this.agentStoreLoadGeneration;var r,n;if(void 0===this.settledAgentStoreSkills||(r=this.settledAgentStoreSkills.roots,n=e,r.length===n.length&&r.every(((e,t)=>e===n[t])))||(this.settledAgentStoreSkills=void 0,this.notifyChanged()),0!==e.length){if(void 0===this.settledAgentStoreSkills){const r=this.seedAgentStoreSkills(e,t).finally((()=>{this.agentStoreSeedInFlight===r&&(this.agentStoreSeedInFlight=void 0)}));this.agentStoreSeedInFlight=r}void 0===this.agentStoreWalk?this.agentStoreWalk=(0,Nr.wj)(this.loadAgentStoreSkills(e),3e4,"Agent Store skills walk timed out").then((r=>{t===this.agentStoreLoadGeneration&&(this.settledAgentStoreSkills={roots:e,loaded:r},this.notifyChanged(),(r.rules.length>0||r.agentSkills.length>0)&&this.persistCatalog(hg(this.surface,e),r))}),(e=>{lg("Failed to load Agent Store skills: %O",e)})).finally((()=>{this.agentStoreWalk=void 0,this.agentStoreLoadRequestedWhileInFlight&&(this.agentStoreLoadRequestedWhileInFlight=!1,this.refreshAgentStoreSkills())})):this.agentStoreLoadRequestedWhileInFlight=!0}}async seedAgentStoreSkills(e,t){const r=await this.readCatalog(hg(this.surface,e));void 0!==r&&t===this.agentStoreLoadGeneration&&void 0===this.settledAgentStoreSkills&&(this.settledAgentStoreSkills={roots:e,loaded:r},this.notifyChanged())}async loadAgentStoreSkills(e){const t=ug(),r=(await Promise.all(e.map((e=>Km(e))))).flat().filter((e=>!vm(e))),n=await Promise.all(r.map((e=>Zm(e)))),o=new Set;for(const e of n)o.has(e.realSkillFilePath)||(o.add(e.realSkillFilePath),cg(t,e,this.surface,this.getEnabledSkills()));return t}notifyChanged(){for(const e of Array.from(this.onChangeCallbacks))e()}onDidChangeSkills(e){return this.onDidChangeRules(e)}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}dispose(){for(const e of this.watchersByFolder.values())e();this.watchersByFolder.clear()}async loadAll(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("AgentSkillsCursorRulesService.loadAll")),!1);await this.waitBeforeSkillLoad();const o=[],s=[],i=new Map,a=Promise.all(this.nestedExtensibilityEntries.map(((e,r)=>(t?.[r]??e.discover(n.ctx)).catch((e=>{lg("Failed to discover nested agent skills: %O",e)}))))),c=new Set(this.getAgentStoreSkillRoots()),l=await Promise.all(this.foldersToWatch.filter((e=>!c.has(e))).map((async e=>{const t=(await Km(e)).filter((e=>!this.isIgnoredSkillPath(e)));return Promise.all(t.map((e=>Zm(e))))}))),u=new Set;for(const e of l)for(const t of e)if(!u.has(t.realSkillFilePath))if(u.add(t.realSkillFilePath),"error"in t)i.set(t.skillFilePath,t.realSkillFilePath),ag({rules:o,agentSkills:s,skillFilePath:t.skillFilePath,errorMessage:t.error});else{if(tg(t.parsed,this.surface,this.getEnabledSkills()))continue;i.set(t.skillFilePath,t.realSkillFilePath),o.push(sg(t)),ng(t.parsed)||s.push(ig(t))}const d=(await a).flatMap((e=>e?.skills??[])).filter((e=>!vm(e))),h=await Promise.all(d.map((e=>ns(e)))),p=[];for(const[e,t]of d.entries()){const r=h[e];u.has(r)||(u.add(r),p.push(t))}const f=await Promise.all(p.map((e=>Zm(e))));for(const e of f)if("error"in e)i.set(e.skillFilePath,e.realSkillFilePath),ag({rules:o,agentSkills:s,skillFilePath:e.skillFilePath,errorMessage:e.error});else{if(tg(e.parsed,this.surface,this.getEnabledSkills()))continue;i.set(e.skillFilePath,e.realSkillFilePath),o.push(sg(e)),ng(e.parsed)||s.push(ig(e))}return n.span.setAttribute("agent_skills.total",o.length),n.span.setAttribute("agent_skills_proto.total",s.length),{rules:o,agentSkills:s,realSkillFilePathsByFullPath:i}}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}}function vg(e){let t;switch(e.type){case"global":t=new Jr.f5({type:{case:"global",value:new Jr.i9}});break;case"fileGlobbed":t=new Jr.f5({type:{case:"fileGlobbed",value:new Jr.uT({globs:e.globs??[]})}});break;case"agentFetched":t=new Jr.f5({type:{case:"agentFetched",value:new Jr.Xo({description:rg(e.description??"")})}});break;case"manuallyAttached":t=new Jr.f5({type:{case:"manuallyAttached",value:new Jr._u}});break;default:e.type,t=new Jr.f5({type:{case:"manuallyAttached",value:new Jr._u}})}return new Jr.DX({fullPath:e.fullPath,content:e.content,type:t,gitRemoteOrigin:e.gitRemoteOrigin,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,environments:e.environments??[],disabledEnvironments:e.disabledEnvironments??[],scopedTo:[]})}class bg{constructor(e,t,r,n){this.getImportSettings=t,this.pluginsService=n,this._rules=Promise.resolve([]),this._agentSkills=Promise.resolve([]),this._lastLoaded={rules:[],agentSkills:[]},this._loadGeneration=0,this.onChangeCallbacks=new Set,this.currentImportSettings=this.getImportSettings();const o=performance.now();this.startLoad(e,!1,(t=>{try{zm.info(e,"CursorPluginsAgentSkillsService load completed",{durationMs:Math.round(performance.now()-o),ruleCount:t.rules.length,skillCount:t.agentSkills.length})}catch{}}))}startLoad(e,t,r){const n=++this._loadGeneration,o=this.loadAll(e,t).catch((e=>((0,Vs.debuglog)("cursor-plugins-agent-skills")("Failed to load Cursor Plugins Agent Skills: %s",e instanceof Error?e.message:String(e)),{rules:[],agentSkills:[]}))).then((e=>(n===this._loadGeneration&&(this._lastLoaded=e,r?.(e)),e))),s=()=>(o.then((e=>{n===this._loadGeneration&&(this._rules=Promise.resolve(e.rules),this._agentSkills=Promise.resolve(e.agentSkills),this.notifyChange())})),this._lastLoaded),i=void 0!==this._overBudgetLoad?Promise.resolve(s()):(0,Nr.wj)(o,5e3,"Cursor plugin load did not finish within the rules wait budget").catch((t=>(zm.warn(e,"Serving rules without plugin primitives while plugins load",{error:t instanceof Error?t.message:String(t),waitMs:5e3}),this._overBudgetLoad=o,o.then((()=>{this._overBudgetLoad===o&&(this._overBudgetLoad=void 0)})),s())));this._rules=i.then((e=>e.rules)),this._agentSkills=i.then((e=>e.agentSkills))}notifyChange(){for(const e of Array.from(this.onChangeCallbacks))e()}async getAllCursorRules(e){return await this._rules}async getAllAgentSkills(e){return await this._agentSkills}reload(e){const t=this.getImportSettings();this.currentImportSettings=t,this.startLoad(e,!0),this.notifyChange()}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}onDidChangeSkills(e){return this.onDidChangeRules(e)}dispose(){this.onChangeCallbacks.clear()}async loadAll(e,t=!1){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("CursorPluginsAgentSkillsService.loadAll")),!1),o=[],i=[];try{let e=t?await this.pluginsService.reload():await this.pluginsService.getAllEnabledPlugins();this.currentImportSettings.importThirdPartyPlugins||(e=e.filter((e=>"claude-plugin"!==e.identifier.source))),n.span.setAttribute("cursor_plugins.loaded",e.length);const r=function(e){return cm(e,(e=>e.skills))}(e),a=function(e){return cm(e,(e=>e.rules))}(e);for(const e of[...r,...a])o.push(vg(e));for(const t of e){const e=`plugin:${df(t.identifier)}`,r=hf(t.identifier),n=pf(t.identifier),o=ff(t.identifier),a=mf(t.identifier);for(const c of t.skills){if(!0===c.alwaysApply)continue;let l=!1;if(c.content?.includes("disable-model-invocation"))try{l=!0===rh(c.content).data?.["disable-model-invocation"]}catch{}i.push(new lm.N({fullPath:(0,s.join)(t.installPath,c.path),content:c.content,description:rg(c.description??""),environments:c.environments??[],disabledEnvironments:c.disabledEnvironments??[],gitRemoteOrigin:e,plugin:r,marketplace:n,pluginId:o,marketplaceId:a,disableModelInvocation:l}))}}}catch(e){n.span.setAttribute("cursor_plugins.error",String(e))}return n.span.setAttribute("cursor_plugins.total",o.length),n.span.setAttribute("cursor_plugins_proto.total",i.length),{rules:o,agentSkills:i}}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}}var Sg=r("../proto/dist/generated/agent/v1/subagents_pb.js");const kg=(0,Vs.debuglog)("local-subagents");class _g{async getAllSubagents(){return[]}async reload(){return[]}}function Cg(e){return"true"===(e??"").trim().toLowerCase()}function Eg(e){const t=e.match(/^---\s*\n([\s\S]*?)\n---\s*\n?([\s\S]*)$/m);if(!t)return null;const r=t[1]??"",n=(t[2]??"").trim();if(0===n.length)return null;const o={};for(const e of r.split("\n")){const t=e.trim();if(0===t.length||t.startsWith("#"))continue;const r=t.indexOf(":");if(-1===r)continue;const n=t.slice(0,r).trim().toLowerCase(),s=t.slice(r+1).trim();0!==n.length&&(o[n]=s)}const s=o.name??"",i=o.description,a=o.model,c=Cg(o["force-default-model"]),l="true"===(o.readonly??"").trim().toLowerCase()?Sg.b$.READONLY:Sg.b$.DEFAULT,u=Cg(o.background??o.is_background),d=o.tools;return{name:s,description:i,tools:void 0!==d&&d.length>0?d.split(",").map((e=>e.trim())).filter((e=>e.length>0)):[],model:a,forceDefaultModel:c,prompt:n,permissionMode:l,isBackground:u}}function xg(e){const t=(0,s.extname)(e).toLowerCase();return".md"===t||".mdc"===t||".markdown"===t}function Pg(e){return(0,s.basename)(e,(0,s.extname)(e)).replace(/[\s_]+/g,"-")}async function Rg(e,t){return await Nm({rootDir:e,includeFile:xg,containmentRootDir:t})}class Ig{constructor(e,t,r="workspace",n=!1,o){this.workspacePath=e,this.cursorAgentsSource=r,this.allowExternalAgentSymlinks=n,this.ignoreService=o,this.getThirdPartyExtensibilityEnabled=t??(()=>!0),this.subagents=this.load().catch((e=>(kg("Failed to load subagents: %o",e),[])))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents=this.load().catch((e=>(kg("Failed to load subagents: %o",e),[]))),await this.subagents}computeAgentsDirs(){const e=(0,s.resolve)(this.workspacePath),t=[{dirPath:(0,s.join)(e,".cursor","agents"),source:this.cursorAgentsSource}];return this.getThirdPartyExtensibilityEnabled()&&(t.push({dirPath:(0,s.join)(e,".claude","agents"),source:"claude"}),t.push({dirPath:(0,s.join)(e,".grok","agents"),source:"grok"})),t}async load(){const e=this.computeAgentsDirs(),t=[];for(const{dirPath:r,source:n}of e){const e=await Rg(r,this.allowExternalAgentSymlinks?void 0:this.workspacePath);for(const r of e){const e=(0,s.basename)(r);try{if(!(await(0,xo.stat)(r)).isFile())continue}catch(e){kg("Skipping subagent file %s due to stat error: %o",r,e);continue}try{const o=Eg(await Bi(r));if(!o)continue;t.push(new Sg.zz({fullPath:r,name:o.name||Pg(e),description:o.description??"",tools:o.tools,model:o.model??"inherit",forceDefaultModel:o.forceDefaultModel,prompt:o.prompt,permissionMode:o.permissionMode,isBackground:o.isBackground,source:n}))}catch(e){kg("Failed to parse subagent file %s: %o",r,e)}}}return t}}const Tg=new Set(["claude-code-tutor"]);class Ag{constructor(e){this.subagentsServices=e}async getAllSubagents(){const e=await Promise.all(this.subagentsServices.map((e=>e.getAllSubagents().catch((e=>(kg("Failed to load subagents from merged service: %o",e),[])))))),t=new Map;for(const r of e)for(const e of r)Tg.has(e.name)||t.has(e.name)||t.set(e.name,e);return Array.from(t.values())}async reload(){return await Promise.all(this.subagentsServices.map((e=>e.reload()))),this.getAllSubagents()}}class $g{constructor(e,t){this.getSettings=e,this.pluginsService=t,this._subagentsCache=[],this._loadId=0,this._loadPromise=null,this._loadedOnce=!1,this.runLoadInBackground()}async getAllSubagents(){return this._loadPromise&&await this._loadPromise,this._loadedOnce||await this.reload(),[...this._subagentsCache]}async reload(){return this.runLoadInBackground(!0),this._loadPromise&&await this._loadPromise,this._subagentsCache}runLoadInBackground(e=!1){const t=++this._loadId;this._loadPromise=this.load(e).then((e=>{t===this._loadId&&(this._subagentsCache=e,this._loadedOnce=!0)})).catch((e=>{t===this._loadId&&(kg("Failed to load Cursor plugin subagents: %o",e),this._subagentsCache=[],this._loadedOnce=!0)})).finally((()=>{t===this._loadId&&(this._loadPromise=null)}))}dispose(){}async load(e){const t=[];try{let r=e?await this.pluginsService.reload():await this.pluginsService.getAllEnabledPlugins();this.getSettings().importThirdPartyPlugins||(r=r.filter((e=>"claude-plugin"!==e.identifier.source)));const n=function(e,t={stripModel:!0,stripTools:!0}){const r=[];for(const n of e){const e=hf(n.identifier),o=pf(n.identifier),i=ff(n.identifier),a=mf(n.identifier);for(const c of n.agents){const l=am(c,t),u=(0,s.join)(n.installPath,l.path);r.push({name:l.name,description:l.description??"",prompt:l.prompt,fullPath:u,permissionMode:"readonly"===l.permissionMode?"readonly":"default",plugin:e,marketplace:o,pluginId:i,marketplaceId:a})}}return r}(r,{stripModel:!0,stripTools:!0});for(const e of n){const r="readonly"===e.permissionMode?Sg.b$.READONLY:Sg.b$.DEFAULT;t.push(new Sg.zz({name:e.name,description:e.description,tools:[],model:"inherit",prompt:e.prompt,fullPath:e.fullPath,permissionMode:r,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,source:"plugin"}))}}catch{}return t}}class Mg{constructor(e){this.pastElements=[],this.closed=!1,this.forks=new Set,this.consume(e)}async consume(e){try{for await(const t of e){this.pastElements.push(t);const e=[];for(const r of this.forks)e.push(r.write(t).catch((()=>{})));await Promise.allSettled(e)}}catch(e){this.error=e instanceof Error?e:new Error(String(e))}finally{this.closed=!0;for(const e of this.forks)this.error?e.throw(this.error):e.close();this.forks.clear()}}fork(){if(this.closed){const e=this.pastElements,t=this.error;return async function*(){for(const t of e)yield t;if(t)throw t}()}const e=(0,f.Jt)(),t=this.pastElements.slice();this.forks.add(e);const r=this;return async function*(){for(const e of t)yield e;try{for await(const t of e)yield t}finally{r.forks.delete(e)}}()}}function Dg(e,t){return`${e}:${(0,ko.createHash)("sha256").update(t.toBinary()).digest("hex")}`}function Og(e){return new Po.q({max:e?.max??10,ttl:e?.ttl})}function Fg(e,t,r=Og(t)){return{async execute(t,n,o){if(!o?.execId)return e.execute(t,n,o);const s=Dg(o.execId,n),i=r.get(s);if(void 0!==i)return i;const a=await e.execute(t,n,o);return r.set(s,a),a}}}var Ng=r("../proto/dist/generated/agent/v1/computer_use_tool_pb.js");r("node:readline"),Error;var Lg=r("node:timers/promises");const jg=iu.execFile;function Ug(e,t,r){return new Promise(((n,o)=>{r?.signal?.throwIfAborted();const s={timeout:r?.timeoutMs??3e4,env:r?.env?{...process.env,...r.env}:void 0,signal:r?.signal};(0,au.D9)(jg,e,t.map(String),{...s,encoding:"utf8"},((e,t)=>{e?o(e):n(t)}))}))}Ng.w3.UNSPECIFIED,Ng.w3.LEFT,Ng.w3.MIDDLE,Ng.w3.RIGHT,Ng.w3.BACK,Ng.w3.FORWARD,Ng.Dh.UNSPECIFIED,Ng.Dh.UP,Ng.Dh.DOWN,Ng.Dh.LEFT,Ng.Dh.RIGHT;const Bg=(0,Vs.promisify)(iu.execFile);function Wg(e){const t=e.lastIndexOf(":");if(-1===t)throw new Error(`Invalid X11 display string: ${e} (missing ':')`);const r=e.slice(t+1).split(".")[0],n=parseInt(r,10);if(!Number.isFinite(n)||n<0)throw new Error(`Invalid X11 display number in: ${e} (parsed: ${r})`);return n}function Hg(e,t,r,n){const o=function(e={}){const t=e.displayWidth??1920,r=e.displayHeight??1200,n=e.apiWidth??1280;return{width:n,height:Math.round(n*r/t)}}({displayWidth:e,displayHeight:t,apiWidth:r});return{display:{width:e,height:t},api:{width:o.width,height:n??o.height}}}async function qg(e){const{stdout:t}=await(0,au.D9)(Bg,"xrandr",["--display",e],{timeout:5e3,encoding:"utf8"}),r=function(e){let t,r,n;for(const o of e.split("\n"))if(o.includes("*")){const e=o.trim().match(/^(\d+)x(\d+)/);e&&(t=parseInt(e[1],10),r=parseInt(e[2],10));const s=o.match(/(\d+(?:\.\d+)?)\*(?:\+)?/);if(s){const e=parseFloat(s[1]);e>0&&e<=500&&(n=Math.round(e))}if(t&&r)break}if(!t||!r){const n=e.match(/current\s+(\d+)\s*x\s*(\d+)/i);n&&(t=parseInt(n[1],10),r=parseInt(n[2],10))}if(!t||!r)throw new Error(`Could not detect display resolution from xrandr output.\nExpected a line with '*' indicating active mode, or 'current WxH'.\nxrandr output:\n${e}`);return n||(n=60),{width:t,height:r,refreshRate:n}}(t);return{display:r,resolution:Hg(r.width,r.height),resolutionString:`${r.width}x${r.height}`}}Ng.w3.UNSPECIFIED,Ng.w3.LEFT,Ng.w3.MIDDLE,Ng.w3.RIGHT,Ng.w3.BACK,Ng.w3.FORWARD,Ng.Dh.UNSPECIFIED,Ng.Dh.UP,Ng.Dh.DOWN,Ng.Dh.LEFT,Ng.Dh.RIGHT;const zg={pattern:"[\\w-]{1,64}",next:e=>e},Gg={pattern:"[0-9a-f-]{36}",next:()=>ko.randomUUID()},Vg={pattern:"webp",next:()=>"webp"},Kg={native:[Gg,Vg],agent:[zg,Gg,Vg],legacyNative:[Gg,{pattern:"png",next:()=>"png"}]};new RegExp(`^(?:${Object.values(Kg).map((e=>e.map((e=>e.pattern)).join("\\."))).join("|")})$`),new RegExp(`^${zg.pattern}$`),Ng.Z8.NATIVE_X11,Ng.Z8.XDOTOOL,(0,h.v5)("computer_use.session.duration_ms",{description:"Duration of computer-use session in milliseconds"}),(0,h.v5)("computer_use.session.action_count",{description:"Number of actions executed in a computer-use session"}),(0,h.Pu)("computer_use.session.result",{description:"Result status of computer-use session",labelNames:["outcome"]}),(0,h.Pu)("computer_use.session.action_kind",{description:"Requested computer-use actions by bounded kind",labelNames:["kind"]}),(0,d.h)("computer-use"),Math.floor(35927136),["Skip changes that cannot affect what runs in any deployed environment:","- documentation-only changes (Markdown, docs sites, code comments, changelogs)","- formatting, lint, or typo fixes with no behavior change","- test-only changes (test files, fixtures, snapshots)","Monitor everything else, including dependency bumps, configuration, and infrastructure changes."].join("\n"),Error,(0,h.Pu)("computer_use.desktop_lease.check",{description:"Desktop lease action-gate outcomes",labelNames:["outcome","reason"]});var Jg=r("../proto/dist/runtime/compact.js");Jg.HL;var Zg=(0,Jg.QT)(ve.proto3,"agent.v1.","CursorType",[[0,"UNSPECIFIED"],[1,"ARROW"],[2,"POINTER"],[3,"TEXT"],[4,"WAIT"],[5,"CROSSHAIR"],[6,"MOVE"],[7,"RESIZE_NS"],[8,"RESIZE_EW"],[9,"RESIZE_NWSE"],[10,"RESIZE_NESW"],[11,"NOT_ALLOWED"],[12,"GRAB"],[13,"GRABBING"]],1);ve.proto3,ve.proto3,ve.proto3,ve.proto3;class Xg{constructor(e){this.config=e;const t=e.display.width/e.display.height,r=e.api.width/e.api.height;if(Math.abs(t-r)>.02)throw new Error(`Aspect ratio mismatch: display=${t.toFixed(3)}, api=${r.toFixed(3)}`);this.xScaleUp=e.display.width/e.api.width,this.yScaleUp=e.display.height/e.api.height,this.xScaleDown=e.api.width/e.display.width,this.yScaleDown=e.api.height/e.display.height}apiToDisplay(e,t){return{x:Math.round(e*this.xScaleUp),y:Math.round(t*this.yScaleUp)}}displayToApi(e,t){return{x:Math.round(e*this.xScaleDown),y:Math.round(t*this.yScaleDown)}}get apiWidth(){return this.config.api.width}get apiHeight(){return this.config.api.height}get displayWidth(){return this.config.display.width}get displayHeight(){return this.config.display.height}}const Qg={left_ptr:Zg.ARROW,arrow:Zg.ARROW,default:Zg.ARROW,top_left_arrow:Zg.ARROW,hand:Zg.POINTER,hand1:Zg.POINTER,hand2:Zg.POINTER,pointer:Zg.POINTER,pointing_hand:Zg.POINTER,xterm:Zg.TEXT,ibeam:Zg.TEXT,text:Zg.TEXT,watch:Zg.WAIT,wait:Zg.WAIT,progress:Zg.WAIT,left_ptr_watch:Zg.WAIT,crosshair:Zg.CROSSHAIR,cross:Zg.CROSSHAIR,tcross:Zg.CROSSHAIR,move:Zg.MOVE,fleur:Zg.MOVE,size_all:Zg.MOVE,sb_v_double_arrow:Zg.RESIZE_NS,v_double_arrow:Zg.RESIZE_NS,ns_resize:Zg.RESIZE_NS,row_resize:Zg.RESIZE_NS,top_side:Zg.RESIZE_NS,bottom_side:Zg.RESIZE_NS,sb_h_double_arrow:Zg.RESIZE_EW,h_double_arrow:Zg.RESIZE_EW,ew_resize:Zg.RESIZE_EW,col_resize:Zg.RESIZE_EW,left_side:Zg.RESIZE_EW,right_side:Zg.RESIZE_EW,top_left_corner:Zg.RESIZE_NWSE,bottom_right_corner:Zg.RESIZE_NWSE,nwse_resize:Zg.RESIZE_NWSE,size_fdiag:Zg.RESIZE_NWSE,top_right_corner:Zg.RESIZE_NESW,bottom_left_corner:Zg.RESIZE_NESW,nesw_resize:Zg.RESIZE_NESW,size_bdiag:Zg.RESIZE_NESW,not_allowed:Zg.NOT_ALLOWED,no_drop:Zg.NOT_ALLOWED,forbidden:Zg.NOT_ALLOWED,circle:Zg.NOT_ALLOWED,grab:Zg.GRAB,openhand:Zg.GRAB,grabbing:Zg.GRABBING,closedhand:Zg.GRABBING};class Yg{constructor(e){this.events=[],this.recordingStartTime=0,this.lastKnownPosition={x:0,y:0},this.isRunning=!1,this.pending=Promise.resolve();const t=e.displayNum??1;this.env={DISPLAY:`:${t}`},this.scaler=new Xg(e.resolution)}async start(){this.events=[],this.recordingStartTime=Date.now(),this.isRunning=!0,this.pending=Promise.resolve();try{this.lastKnownPosition=await this.captureCurrentPosition()}catch{this.lastKnownPosition={x:Math.floor(this.scaler.apiWidth/2),y:Math.floor(this.scaler.apiHeight/2)}}}logEvent(e,t,r){if(!this.isRunning)return;const n={...this.lastKnownPosition},o=this.getExpectedPositionAfterAction(e,n);this.lastKnownPosition=o;const s=async()=>{let s,i;try{[s,i]=await Promise.all([this.captureCurrentPosition(),this.detectCursorType()]),this.lastKnownPosition=s}catch{s=o,i=Zg.ARROW}const a={executionTimestampMs:r-this.recordingStartTime,action:e,commandDurationMs:r-t,positionBefore:n,positionAfter:s,cursorTypeAfter:i};this.events.push(a)};this.pending=this.pending.then((()=>s())).catch((()=>{}))}async stop(){return this.isRunning=!1,await this.pending,[...this.events]}getEvents(){return[...this.events]}getRecordingStartTime(){return this.recordingStartTime}getIsRunning(){return this.isRunning}async captureCurrentPosition(){const e=await Ug("xdotool",["getmouselocation","--shell"],{env:this.env}),t=e.match(/X=(\d+)/),r=e.match(/Y=(\d+)/);if(!t||!r)throw new Error(`Failed to parse cursor position: ${e}`);const n=parseInt(t[1],10),o=parseInt(r[1],10);return this.scaler.displayToApi(n,o)}async detectCursorType(){try{const e=(await Ug("xdotool",["getmouselocation","--shell"],{env:this.env})).match(/CURSOR=(\S+)/i);if(e){const t=e[1].toLowerCase();return Qg[t]??Zg.ARROW}try{const e=await Ug("xprop",["-root","_XSERVER_CURSOR"],{env:this.env,timeoutMs:500});for(const[t,r]of Object.entries(Qg))if(e.toLowerCase().includes(t))return r}catch{}return Zg.ARROW}catch{return Zg.ARROW}}getExpectedPositionAfterAction(e,t){const r=e.action;if(!r)return t;switch(r.case){case"mouseMove":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}case"click":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}case"drag":{const e=r.value.path;if(e.length>0){const t=e[e.length-1];return{x:t.x,y:t.y}}break}case"scroll":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}}return t}}(0,d.h)("computer-use-lazy");var ew=r("node:net");function tw(e){return!!e.includes(o.homedir())||e.includes("node_modules")||e.includes("Application Support")||/\.wasm\b/.test(e)||/(?:^|[\s'`"(=])(?:\/|\.{1,2}\/)/.test(e)||/(?:^|[\s'`"(=:])(?:[A-Za-z]:[\\/]|\\\\)/.test(e)||/\bS-1-5-21(?:-\d+){3,}/i.test(e)}class rw extends Error{constructor(e){super(e),this.name="MacRPCProtocolError"}}const nw=Be.object({rpcSocketPath:Be.string().min(1).optional(),appControlSocketPath:Be.string().min(1).optional(),pid:Be.number().int().positive().optional().catch(void 0),protocolMajor:Be.number().int().positive().optional().catch(void 0)}).passthrough(),ow=Be.object({data:Be.string(),mimeType:Be.string().min(1)}).strip(),sw=Be.object({message:Be.string(),screenshot:ow.optional(),screenshotBefore:ow.optional(),structuredContent:Be.unknown().optional(),isError:Be.boolean()}).strip(),iw=Be.object({accessibilityTrusted:Be.boolean(),screenRecordingGranted:Be.boolean()}).strip(),aw=Be.union([Be.object({id:Be.number().int(),result:sw,ok:Be.never().optional(),error:Be.never().optional(),errorCode:Be.never().optional(),permissionStatus:Be.never().optional(),sessionId:Be.never().optional()}).strip(),Be.object({id:Be.number().int(),sessionId:Be.string().min(1),ok:Be.literal(!0).optional(),result:Be.never().optional(),error:Be.never().optional(),errorCode:Be.never().optional(),permissionStatus:Be.never().optional()}).strip(),Be.object({id:Be.number().int(),ok:Be.literal(!0),result:Be.never().optional(),error:Be.never().optional(),errorCode:Be.never().optional(),permissionStatus:Be.never().optional(),sessionId:Be.never().optional()}).strip(),Be.object({id:Be.number().int().nullable().optional(),error:Be.string().min(1),errorCode:Be.string().min(1).optional(),result:Be.never().optional(),ok:Be.never().optional(),permissionStatus:Be.never().optional(),sessionId:Be.never().optional()}).strip(),Be.object({id:Be.number().int(),permissionStatus:iw,result:Be.never().optional(),ok:Be.never().optional(),error:Be.never().optional(),errorCode:Be.never().optional(),sessionId:Be.never().optional()}).strip()]);function cw(e,t){try{return JSON.parse(e)}catch{throw new rw(`local-cua ${t} is not valid JSON`)}}const lw={responseMaxBytes:33554432,parseServiceState(e){const t=nw.safeParse(cw(e,"service state")),r=t.success?t.data.rpcSocketPath??t.data.appControlSocketPath:void 0;if(!t.success||void 0===r)throw new rw("local-cua service state is malformed");return{...t.data,rpcSocketPath:r}},parseResponse({line:e,expectedID:t}){const r=aw.safeParse(cw(e.toString("utf8"),"RPC response"));if(!r.success)throw new rw("local-cua RPC response is malformed");if(void 0!==r.data.id&&null!==r.data.id&&r.data.id!==t)throw new rw("local-cua RPC response ID did not match");return r.data}};class uw extends Error{constructor(e,t){super(e),this.name="MacComputerUseRPCError",this.code=t?.code,this.userFacing=!0===t?.userFacing,this.tool=t?.tool}}function dw(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:e instanceof Error?tw(e.message)?e.name:e.message.length>0?`${e.name}: ${e.message}`:e.name:"unknown"}const hw=new Map([["co.anysphere.cursor-computer-use","cursor-computer-use"],["co.anysphere.cursor-computer-use.dev","cursor-computer-use-dev"]]),pw=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;class fw{constructor(e){this.mode=e}static isInstalled(){if((0,Ro.existsSync)(fw.serviceExecutablePath()))return!0;let e;try{e=lw.parseServiceState((0,Ro.readFileSync)(fw.serviceStatePath(),"utf8"))}catch{return!1}return void 0===e.pid||fw.isProcessAlive(e.pid)}static async runningHelperPid(){const e=await fw.readServiceState(),t=e?.pid;return void 0!==t&&fw.isProcessAlive(t)?t:void 0}static isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}static isExitedIncompatibleHelper(e){return void 0!==e.protocolMajor&&e.protocolMajor!==fw.protocolMajor&&void 0!==e.pid&&!fw.isProcessAlive(e.pid)}screenshot(e){return this.callTool(e,"computer_use_screenshot",{})}click(e,t){return this.callTool(e,"computer_use_click",{method:"coordinate",...void 0!==t.coordinate&&{x:t.coordinate.x,y:t.coordinate.y},button:t.button,count:t.count,modifier_keys:t.modifierKeys})}scroll(e,t){return this.callTool(e,"computer_use_scroll",{x:t.coordinate?.x,y:t.coordinate?.y,direction:t.direction,amount:t.amount,modifier_keys:t.modifierKeys})}move(e,t){return this.callTool(e,"computer_use_mouse_move",{x:t.x,y:t.y})}mouseButton(e,t){return this.callTool(e,"computer_use_mouse_button",{button:t.button,action:t.action})}drag(e,t){return this.callTool(e,"computer_use_drag",{button:t.button,path:t.path,modifier_keys:t.modifierKeys})}typeText(e,t){return this.callTool(e,"computer_use_typing",{value:t})}pressKey(e,t){return this.callTool(e,"computer_use_press_key",{key:t.key,hold_duration_ms:t.holdDurationMs})}checkPermissions(e){return this.callTool(e,"computer_use_check_permissions",{})}async startControl(e){if("remote"!==this.mode||void 0!==this.activeSessionId)return;fw.throwIfAborted(e.signal);const t=(0,ko.randomUUID)(),r=await this.sendWithRelaunchRetry(e,(()=>({id:fw.requestID,method:"control/start",requestID:t,mode:this.mode})),"control/start");if(void 0!==r.error)throw fw.rpcError(r);if(void 0===r.sessionId)throw new uw("local-cua control/start returned no session");this.activeSessionId=r.sessionId}async releaseControl(e){const t=this.activeSessionId;if(void 0!==t){this.activeSessionId=void 0;try{const e=await fw.readServiceState();if(void 0===e)return;const r=await fw.sendOnce(fw.socketPathFrom(e),{id:fw.requestID,method:"control/release",requestID:(0,ko.randomUUID)(),mode:this.mode,sessionId:t},fw.defaultCallTimeoutMs);if(void 0!==r.error)throw fw.rpcError(r)}catch(t){fw.logger.warn(e,"local-cua control release failed",{error:dw(t)})}}}async callTool(e,t,r){fw.throwIfAborted(e.signal);const n=fw.defaultCallTimeoutMs,o=await this.sendWithRelaunchRetry(e,(()=>{const e=Date.now()/1e3,o=this.activeSessionId;return{id:fw.requestID,method:"tools/call",requestID:(0,ko.randomUUID)(),name:t,arguments:r,timeoutSeconds:n/1e3,startedAtEpochSeconds:e,deadlineEpochSeconds:e+n/1e3,mode:this.mode,...void 0!==o&&{sessionId:o}}}),t);if(void 0!==o.error)throw fw.rpcError(o,t);const s=o.result;if(void 0===s)throw new uw(`local-cua tool ${t} returned no result`,{tool:t});if(s.isError){const e=s.message.trim();throw new uw(e.length>0?e:`local-cua tool ${t} reported an error`,{tool:t,userFacing:e.length>0})}return s}async sendWithRelaunchRetry(e,t,r){const n=fw.defaultCallTimeoutMs,o=await this.ensureSocketPath(e);fw.throwIfAborted(e.signal);try{return await fw.sendOnce(o,t(),n,e.signal)}catch(o){if(!fw.isPreDeliveryConnectionError(o))throw o;fw.logger.warn(e,"local-cua callTool failed; relaunching and retrying",{tool:r,error:fw.spawnErrorCode(o)});const s=await this.ensureSocketPath(e,!0);return fw.throwIfAborted(e.signal),void 0!==this.activeSessionId&&(this.activeSessionId=void 0,await this.startControl(e)),await fw.sendOnce(s,t(),n,e.signal)}}static rpcError(e,t){return new uw(e.error,{code:e.errorCode,userFacing:!0,tool:t})}async ensureSocketPath(e,t=!1){if(fw.throwIfAborted(e.signal),!t){const e=await fw.readServiceState();if(e&&!fw.isExitedIncompatibleHelper(e))return fw.socketPathFrom(e)}await this.launchAndWait(e);const r=await fw.readServiceState();if(!r)throw new uw("local-cua sidecar did not publish service.json after launch");return fw.socketPathFrom(r)}static setLaunchGuard(e){fw.launchGuard=e}async launchAndWait(e){const t=fw.serviceAppPath(),r=fw.launchGuard,n=()=>this.launchAppAndWait(e,t);await(void 0===r?n():r(t,n,e.signal))}async launchAppAndWait(e,t){fw.logger.info(e,"launching local-cua sidecar",fw.sidecarLaunchLogFields(t)),"1"===process.env[fw.directLaunchEnv]?await fw.spawnSidecarProcess(e,fw.serviceExecutablePath(),[],{detached:!0}):await fw.spawnSidecarProcess(e,"/usr/bin/open",["-g",t]);const r=Date.now()+fw.launchReadyTimeoutMs;for(;Date.now()0?e:s.join(o.homedir(),...fw.sharedInstallRelativePath,`${fw.serviceAppBundleName}.app`)}static helperIdentity(){const e=fw.serviceAppPath(),t=process.env[fw.appSupportOverrideEnv],r=`${e}\0${t??""}`,n=fw.identityCache;if(n?.key===r)return n.identity;const i=function(e){let t;try{t=(0,Ro.readFileSync)(s.join(e,"Contents","Info.plist"),"utf8")}catch{return{}}const r=e=>{const r=new RegExp(`${e}\\s*([^<]*)`).exec(t)?.[1];return void 0!==r&&pw.test(r.trim())?r.trim():void 0};return{executableName:r("CFBundleExecutable"),bundleIdentifier:r("CFBundleIdentifier")}}(e),a=s.join(e,"Contents","MacOS",i.executableName??fw.productionExecutableName),c={appPath:e,executablePath:a,appSupportDirectory:void 0!==t&&t.length>0?t:s.join(o.homedir(),"Library","Application Support",(void 0===i.bundleIdentifier?void 0:hw.get(i.bundleIdentifier))??fw.appSupportFolder)};return(0,Ro.existsSync)(a)&&(fw.identityCache={key:r,identity:c}),c}static sidecarLaunchLogFields(e){const t=`${fw.serviceAppBundleName}.app`;return{appName:s.basename(e)===t?t:"custom",appPathHash:(0,ko.createHash)("sha256").update(e).digest("hex"),usingOverride:Boolean(process.env[fw.serviceAppOverrideEnv])}}static spawnErrorCode(e){return dw(e)}static socketError(e){const t=dw(e);return new uw(`local-cua RPC connection failed: ${t}`,{code:t})}static serviceExecutablePath(){return fw.helperIdentity().executablePath}static spawnSidecarProcess(e,t,r,n){return new Promise(((o,s)=>{const i=(0,iu.spawn)(t,[...r],{detached:!0===n?.detached,stdio:"ignore"}),a=e=>{s(new uw(`local-cua sidecar launch failed: ${fw.spawnErrorCode(e)}`))};i.once("error",a),i.once("spawn",(()=>{i.removeListener("error",a),i.on("error",(t=>{fw.logger.warn(e,"local-cua sidecar process error after launch",{error:fw.spawnErrorCode(t)})})),i.unref(),o()}))}))}static async readServiceState(){try{const e=await(0,xo.readFile)(fw.serviceStatePath(),"utf8");return lw.parseServiceState(e)}catch(e){if(e instanceof Error&&"code"in e&&"ENOENT"===e.code)return;if(e instanceof rw)return;throw new uw("local-cua service state could not be read")}}static socketPathFrom(e){if(void 0!==e.protocolMajor&&e.protocolMajor!==fw.protocolMajor)throw new uw(`The running Cursor Computer Use speaks protocol ${e.protocolMajor}, and this Cursor CLI speaks protocol ${fw.protocolMajor}. Update the Cursor CLI.`,{userFacing:!0});return e.rpcSocketPath}static abortError(e){return e.reason instanceof Error?e.reason:new uw("local-cua RPC aborted")}static throwIfAborted(e){if(e.aborted)throw fw.abortError(e)}static sendOnce(e,t,r,n){return n?.aborted?Promise.reject(fw.abortError(n)):new Promise(((o,s)=>{let i=!1,a=[],c=0,l=!1;const u=(0,ew.createConnection)({path:e}),d=e=>{i||(i=!0,clearTimeout(p),n?.removeEventListener("abort",h),u.destroy(),e())},h=()=>{d((()=>s(void 0===n?new uw("local-cua RPC aborted"):fw.abortError(n))))},p=setTimeout((()=>{d((()=>s(new uw(`local-cua RPC timed out after ${r}ms`))))}),r);n?.addEventListener("abort",h,{once:!0}),n?.aborted?h():(u.on("connect",(()=>{u.write(`${JSON.stringify(t)}\n`,(e=>{null==e?l=!0:d((()=>s(fw.socketError(e))))}))})),u.on("data",(e=>{const t=e.indexOf(10),r=c+(t<0?e.length:t);if(r>lw.responseMaxBytes)return void d((()=>s(new uw("local-cua RPC response exceeded the size limit"))));if(t<0)return a.push(e),void(c+=e.length);a.push(e.subarray(0,t));const n=Buffer.concat(a,r);a=[],c=0;try{const e=lw.parseResponse({line:n,expectedID:fw.requestID});d((()=>o(e)))}catch(e){d((()=>s(e)))}})),u.on("error",(e=>{d(l?()=>s(new uw("local-cua RPC connection failed after request delivery")):()=>s(fw.socketError(e)))})),u.on("close",(()=>{const e=c>0?"local-cua RPC response ended without a newline":l?"local-cua RPC connection closed after request delivery":"local-cua RPC connection closed";d((()=>s(new uw(e))))})))}))}}let mw;function gw(){if(void 0===mw){const e=async function(){const[{createJimp:e},{default:t},{default:n},{default:o,msBmp:s},{default:i},{default:a},{methods:c}]=await Promise.all([Promise.all([r.e(731),r.e(250)]).then(r.bind(r,"../../node_modules/.pnpm/@jimp+core@1.6.0/node_modules/@jimp/core/dist/esm/index.js")),r.e(690).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-png@1.6.0/node_modules/@jimp/js-png/dist/esm/index.js")),r.e(831).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-jpeg@1.6.0/node_modules/@jimp/js-jpeg/dist/esm/index.js")),Promise.all([r.e(731),r.e(284)]).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-bmp@1.6.0/node_modules/@jimp/js-bmp/dist/esm/index.js")),r.e(295).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-gif@1.6.0/node_modules/@jimp/js-gif/dist/esm/index.js")),r.e(181).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-tiff@1.6.0/node_modules/@jimp/js-tiff/dist/esm/index.js")),r.e(162).then(r.bind(r,"../../node_modules/.pnpm/@jimp+plugin-resize@1.6.0/node_modules/@jimp/plugin-resize/dist/esm/index.js"))]);return e({formats:[t,n,o,s,i,a],plugins:[c]})}().catch((t=>{throw mw===e&&(mw=void 0),t}));mw=e}return mw}fw.logger=(0,d.h)("local-cua:rpc"),fw.serviceAppBundleName="Cursor Computer Use",fw.appSupportFolder="cursor-computer-use",fw.productionExecutableName="CUCursorService",fw.sharedInstallRelativePath=[".cursor","computer-use-sidecar"],fw.appSupportOverrideEnv="CUA_APP_SUPPORT_DIR",fw.serviceAppOverrideEnv="CUA_SERVICE_APP",fw.directLaunchEnv="CUA_DIRECT_LAUNCH",fw.protocolMajor=1,fw.defaultCallTimeoutMs=45e3,fw.launchReadyTimeoutMs=8e3,fw.launchPollIntervalMs=200,fw.requestID=1;var ww=r("node:module"),yw=r.t(ww,2);const vw="mac-webp-runtime.cjs";function bw(e){return"function"==typeof e}function Sw(e){return"object"==typeof e&&null!==e&&"getFileName"in e&&"function"==typeof e.getFileName}function kw(){const e=(new Error).stack;return Array.isArray(e)?e.filter(Sw):[]}let _w,Cw;function Ew(){return _w??=(()=>{const e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;const e=kw()[0]?.getFileName();return function(){const e=yw;if("createRequire"in e&&bw(e.createRequire))return e.createRequire;if("default"in e&&"object"==typeof e.default&&null!==e.default&&"createRequire"in e.default&&bw(e.default.createRequire))return e.default.createRequire;throw new Error("node:module createRequire is unavailable")}()("string"==typeof e&&e.length>0?e:(0,s.join)(process.cwd(),"package.json"))}finally{Error.prepareStackTrace=e}})(),_w}function xw(){const e=globalThis.__MAC_WEBP_IMPORT__;return"function"==typeof e?t=>Promise.resolve(e(t)):(Cw??=function(){const e=[],t=new Set,r=r=>{t.has(r)||(t.add(r),e.push(r))};for(const e of function(){const e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;const e=[];for(const t of kw()){const r=t.getFileName();"string"==typeof r&&r.length>0&&e.push(r)}return e}finally{Error.prepareStackTrace=e}}()){const t=(0,s.dirname)((n=e).startsWith("file:")?(0,Pd.fileURLToPath)(n):n);r((0,s.join)(t,vw)),r((0,s.join)(t,"..","..","src","computer-use",vw))}var n;"string"==typeof process.argv[1]&&process.argv[1].length>0&&r((0,s.join)((0,s.dirname)(process.argv[1]),vw)),r((0,s.join)(process.cwd(),"src","computer-use",vw)),r((0,s.join)(process.cwd(),"computer-use",vw));try{const e=(0,s.dirname)(Ew().resolve("@anysphere/local-exec/package.json"));r((0,s.join)(e,"src","computer-use",vw)),r((0,s.join)(e,"dist","computer-use",vw))}catch{}for(const t of e)try{const e=Ew()(t);if("object"==typeof e&&null!==e&&"importFile"in e&&"function"==typeof e.importFile)return e.importFile.bind(e)}catch{}throw new Error("mac-webp runtime importer was not found next to the bundle")}(),Cw)}function Pw(...e){return t=["@jsquash","webp",...e].join("/"),Ew().resolve(t);var t}async function Rw(...e){var t;return await(t=(0,Pd.pathToFileURL)(Pw(...e)).href,xw()(t))}const Iw=e=>{let t;return()=>{if(void 0===t){const r=e();r.catch((()=>{t===r&&(t=void 0)})),t=r}return t}},Tw=(Iw((async()=>{const e=await Rw("decode.js");return await e.init({wasmBinary:await Ro.promises.readFile(Pw("codec","dec","webp_dec.wasm"))}),e})),Iw((async()=>{const[e,t,r]=await Promise.all([Rw("utils.js"),Rw("meta.js"),Rw("codec","enc","webp_enc.js")]);return{module:await e.initEmscriptenModule(r.default,void 0,{wasmBinary:await Ro.promises.readFile(Pw("codec","enc","webp_enc.wasm"))}),defaultOptions:t.defaultOptions}}))),Aw="image/png",$w={async normalize(e){if(e.mimeType!==Aw)throw new Error(`Mac screenshot must be ${Aw}, received ${e.mimeType}`);const t=await gw(),r=await t.read(Buffer.from(e.data,"base64"));return(await(n={data:r.bitmap.data,width:r.bitmap.width,height:r.bitmap.height},(async e=>{const{module:t,defaultOptions:r}=await Tw(),n=new Uint8ClampedArray(e.data.buffer,e.data.byteOffset,e.data.byteLength);return Buffer.from(t.encode(n,e.width,e.height,{...r,lossless:1,exact:1}))})(n))).toString("base64");var n}},Mw={userFacing:function(e){if(e instanceof uw&&e.userFacing&&e.message.trim().length>0&&!tw(e.message))return e.message.trim()},isCaptureBlocked:function(e){return e instanceof uw&&("computer_use_screenshot"===e.tool||"permission_required"===e.code)}},Dw=new Set(["keys"]),Ow=new Set(["matched","mismatch","unchecked"]),Fw=new Set(["no_text","password","control_keys","too_long","unreadable","moved","chromium","gecko"]),Nw=new Set(["matched"]),Lw=new Set(["too_long"]),jw=new Set(["watched","fell_back","unavailable","over_budget"]);class Uw{constructor({ctx:e,actions:t,sidecar:r,errors:n,reportTyping:o}){this.startTime=Date.now(),this.typingNotes=[],this.typing=[],this.geometryPrimed=!1,this.actionCount=0,this.hasCompletedActuation=!1,this.staleAfterWait=!1,this.ctx=e,this.actions=t,this.sidecar=r,this.errors=n??Mw,this.reportTyping=!0===o}async execute(){const e=this.actions.some((e=>Uw.isInputAction(e.action.case)));try{this.throwIfAborted(),e&&await this.sidecar.startControl(this.ctx);for(const e of this.actions){this.throwIfAborted();const t=e.action;if(void 0===t.case)throw new Error("Computer use action case is undefined");switch(this.actionCount+=1,t.case){case"screenshot":case"cursorPosition":await this.captureScreen();break;case"click":void 0!==t.value.coordinate&&await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.click(this.ctx,{coordinate:t.value.coordinate,button:Uw.mouseButtonName(t.value.button),count:t.value.count>0?t.value.count:1,modifierKeys:t.value.modifierKeys}),t.value.coordinate);break;case"scroll":void 0!==t.value.coordinate&&await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.scroll(this.ctx,{coordinate:t.value.coordinate,direction:Uw.scrollDirectionName(t.value.direction),amount:t.value.amount>0?t.value.amount:3,modifierKeys:t.value.modifierKeys}),t.value.coordinate);break;case"mouseMove":if(void 0===t.value.coordinate)throw new Error("MouseMoveAction requires coordinate");await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.move(this.ctx,{x:t.value.coordinate.x,y:t.value.coordinate.y}),t.value.coordinate);break;case"mouseDown":this.recordActuation(await this.sidecar.mouseButton(this.ctx,{button:Uw.mouseButtonName(t.value.button),action:"down"}));break;case"mouseUp":this.recordActuation(await this.sidecar.mouseButton(this.ctx,{button:Uw.mouseButtonName(t.value.button),action:"up"}));break;case"drag":{const e=t.value.path.map((e=>({x:e.x,y:e.y})));await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.drag(this.ctx,{button:Uw.mouseButtonName(t.value.button),path:e,modifierKeys:t.value.modifierKeys}),e.at(-1));break}case"type":{const e=await this.sidecar.typeText(this.ctx,t.value.text);this.recordActuation(e),this.recordTyping(e);break}case"key":if(t.value.stroke===Ng.EB.DOWN||t.value.stroke===Ng.EB.UP)throw new Error("Held keys (KeyAction.stroke DOWN/UP) are not supported by the computer-use sidecar; use hold_duration_ms");this.recordActuation(await this.sidecar.pressKey(this.ctx,{key:t.value.key,holdDurationMs:t.value.holdDurationMs}));break;case"wait":await this.delay(Math.max(0,t.value.durationMs)),this.staleAfterWait=!0;break;default:{const e=t;throw new Error(`Unknown computer use action: ${JSON.stringify(e)}`)}}}this.throwIfAborted(),(void 0===this.screenshot||this.staleAfterWait)&&await this.captureScreen(),this.throwIfAborted();const t=await this.normalizeRetainedScreenshots();return t.screenshotFailed&&!this.hasCompletedActuation?this.screenshotUnavailableResult(t.failureReason):(this.throwIfAborted(),new Ng.ks({result:{case:"success",value:new Ng.Wd({actionCount:this.actionCount,durationMs:Date.now()-this.startTime,screenshot:t.screenshot,cursorPosition:this.cursor,log:this.log(t.screenshotFailed?"Screenshot unavailable":void 0),typing:this.typing})}}))}catch(e){return this.ctx.signal.aborted?this.abortedResult():this.errorResult(e)}finally{e&&await this.sidecar.releaseControl(this.ctx)}}static isInputAction(e){switch(e){case"click":case"scroll":case"mouseMove":case"mouseDown":case"mouseUp":case"drag":case"type":case"key":return!0;default:return!1}}async captureScreen(){const e=await this.sidecar.screenshot(this.ctx);this.screenshot=e.screenshot,this.cursor=Uw.cursorFromResult(e)??this.cursor,this.geometryPrimed=!0,this.staleAfterWait=!1}async ensureGeometryCached(){this.geometryPrimed||await this.captureScreen()}recordActuation(e,t){this.screenshot=e.screenshot,this.hasCompletedActuation=!0,this.staleAfterWait=!1,void 0!==e.screenshot&&(this.geometryPrimed=!0),this.cursor=Uw.cursorFromResult(e)??Uw.coordinateFromPoint(t)??this.cursor}recordTyping(e){if(!this.reportTyping)return;const t=e.message.trim();""!==t&&this.typingNotes.push(t);const r=Uw.typingFromResult(e);void 0!==r&&this.typing.push(r)}log(e){const t=void 0===e?this.typingNotes:[...this.typingNotes,e];return 0===t.length?void 0:t.join("\n")}static typingFromResult(e){const t=e.structuredContent;if("object"!=typeof t||null===t||!("type"in t))return;const r=t.type;if("object"!=typeof r||null===r)return;const n=new Map(Object.entries(r)),o=(e,t)=>{const r=n.get(e);return"string"==typeof r&&t.has(r)?r:void 0},s=e=>{const t=n.get(e);return"number"==typeof t&&Number.isInteger(t)&&t>=0?t:void 0},i=o("check",Ow),a=o("unchecked",Fw),c=void 0!==n.get("unchecked")&&null!==n.get("unchecked"),l=void 0!==i&&Nw.has(i)&&!c||"unchecked"===i&&void 0!==a&&Lw.has(a);return new Ng.qA({method:o("method",Dw)??"",chars:l?s("chars")??0:0,atoms:l?s("atoms")??0:0,typedAtoms:l?s("typedAtoms")??0:0,aborted:!0===n.get("aborted"),check:i,verified:l?s("verified"):void 0,unchecked:a,landing:o("landing",jw)})}async errorResult(e){let t;if(Uw.logger.error(this.ctx,"local-cua execute failed",void 0,{error:dw(e)}),!this.errors.isCaptureBlocked(e))try{const e=await this.sidecar.screenshot(this.ctx);t=(await this.normalizeScreenshot(e.screenshot,"error")).data}catch(e){Uw.logger.warn(this.ctx,"local-cua error screenshot capture failed",{error:dw(e)})}const r=this.errors.userFacing(e);return new Ng.ks({result:{case:"error",value:new Ng.Jb({error:void 0===r?"Computer use failed":`Computer use failed: ${r}`,actionCount:this.actionCount,durationMs:Date.now()-this.startTime,screenshot:t,log:this.log(),typing:this.typing})}})}screenshotUnavailableResult(e){return new Ng.ks({result:{case:"error",value:new Ng.Jb({error:"Screenshot unavailable",actionCount:this.actionCount,durationMs:Date.now()-this.startTime,log:e})}})}abortedResult(){return new Ng.ks({result:{case:"error",value:new Ng.Jb({error:"Computer use aborted",actionCount:this.actionCount,durationMs:Date.now()-this.startTime,log:this.log(),typing:this.typing})}})}static mouseButtonName(e){return Uw.mouseButtonNames[e]??"left"}static scrollDirectionName(e){return Uw.scrollDirectionNames[e]??"down"}async normalizeRetainedScreenshots(){const e=await this.normalizeScreenshot(this.screenshot,"post-action");return{screenshot:e.data,screenshotFailed:void 0===this.screenshot||e.failed,failureReason:void 0===this.screenshot?"sidecar returned no image":e.reason}}async normalizeScreenshot(e,t){if(void 0===e)return{failed:!1};try{return{data:await $w.normalize(e),failed:!1}}catch(r){const n=dw(r);return Uw.logger.error(this.ctx,"local-cua screenshot conversion failed",void 0,{frame:t,error:n}),"image/png"===e.mimeType&&e.data.length>0?{data:e.data,failed:!1}:{failed:!0,reason:n}}}static coordinateFromPoint(e){if(void 0!==e&&Number.isFinite(e.x)&&Number.isFinite(e.y))return new Ng.xp({x:Math.round(e.x),y:Math.round(e.y)})}static cursorFromResult(e){const t=e.structuredContent;if("object"!=typeof t||null===t||!("cursor"in t))return;const r=t.cursor;return"object"==typeof r&&null!==r&&"x"in r&&"y"in r&&"number"==typeof r.x&&"number"==typeof r.y&&Number.isFinite(r.x)&&Number.isFinite(r.y)?new Ng.xp({x:Math.round(r.x),y:Math.round(r.y)}):void 0}throwIfAborted(){if(this.ctx.signal.aborted)throw this.ctx.signal.reason??new Error("Computer use aborted")}delay(e){return this.throwIfAborted(),new Promise(((t,r)=>{const n=()=>{clearTimeout(o),r(this.ctx.signal.reason??new Error("Computer use aborted"))},o=setTimeout((()=>{this.ctx.signal.removeEventListener("abort",n),t()}),e);this.ctx.signal.addEventListener("abort",n,{once:!0}),this.ctx.signal.aborted&&n()}))}}Uw.logger=(0,d.h)("local-cua:actions"),Uw.mouseButtonNames={[Ng.w3.UNSPECIFIED]:"left",[Ng.w3.LEFT]:"left",[Ng.w3.RIGHT]:"right",[Ng.w3.MIDDLE]:"middle",[Ng.w3.BACK]:"left",[Ng.w3.FORWARD]:"left"},Uw.scrollDirectionNames={[Ng.Dh.UNSPECIFIED]:"down",[Ng.Dh.UP]:"up",[Ng.Dh.DOWN]:"down",[Ng.Dh.LEFT]:"left",[Ng.Dh.RIGHT]:"right"},s.join(o.tmpdir(),"computer-use"),(0,d.h)("local-cua:windows");Error,Buffer.from([137,80,78,71,13,10,26,10]),new Set(["capture_failed","secure_desktop","input_desktop_unavailable","sidecar_unavailable","user_aborted","session_busy","canvas_mismatch"]);var Bw,Ww=r("../proto/dist/generated/agent/v1/delete_exec_pb.js");function Hw({encoding:e,bom:t,lineEnding:r}){return{encoding:e,bom:t,lineEnding:r}}class qw{constructor(e){this.workspacePath=e,this.changes=new Map,this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){for(const t of this.listeners)t(e)}async trackChange(e,t,r,n,o){const s=this.changes.get(e);if(s){const t=s.before,o=n||s.metadata;if(t===r||void 0===t&&void 0===r)this.changes.delete(e),this.notify();else{const n={path:e,before:t,after:r,metadata:o,...void 0===s.beforeFormat?{}:{beforeFormat:s.beforeFormat}};this.changes.set(e,n),this.notify(n)}}else{const s={path:e,before:t,after:r,metadata:n,...void 0===o?{}:{beforeFormat:o}};this.changes.set(e,s),this.notify(s)}}getChanges(){return Array.from(this.changes.values())}getChange(e){return this.changes.get(e)}hasChange(e){return this.changes.has(e)}accept(e){const t=this.changes.get(e);this.changes.delete(e),this.notify(t)}acceptAll(){this.changes.clear(),this.notify()}async reject(e){const t=this.changes.get(e);if(t)try{void 0===t.before&&void 0!==t.after?await(0,xo.unlink)(e):(void 0!==t.before&&void 0===t.after||void 0!==t.before&&void 0!==t.after)&&await async function(e,t,r,n){const{buffer:o,format:s}=await qi(e,t,r,n);await(0,xo.writeFile)(e,o),await Hi(e,{buffer:o,encoding:s.encoding})}(e,t.before,this.workspacePath)}catch{}finally{this.changes.delete(e),this.notify(t)}}async rejectAll(){const e=Array.from(this.changes.keys());await Promise.all(e.map((e=>this.reject(e))))}clear(){const e=this.changes.values().next().value;this.changes.clear(),this.notify(e)}get size(){return this.changes.size}dispose(){this.changes.clear(),this.listeners.clear()}}!function(e){e.Write="write",e.Read="read",e.Shell="shell",e.Delete="delete",e.Mcp="mcp"}(Bw||(Bw={}));var zw=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class Gw{constructor(e,t,r,n,o,s){this.pendingDecisionProvider=e,this.fileChangeTracker=t,this.permissionsService=r,this.workspacePath=n,this.onDeleteForAiTracking=o,this.agentFileViews=s}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,D.VI)(e.withName("LocalDeleteExecutor.execute")),!1);const n=t.path;if(""===n.trim())return new Ww.Pi({result:{case:"error",value:new Ww.GU({path:n,error:rs})}});const o=(0,ts.o1)(n,this.workspacePath),i=await this.permissionsService.shouldBlockWrite(e,o,"");if(i){const e=await ed(i,{onNeedsApproval:async(e,t)=>null,onUserRejected:e=>new Ww.Pi({result:{case:"rejected",value:new Ww.iq({path:o,reason:e||""})}}),onPermissionDenied:(e,t)=>new Ww.Pi({result:{case:"permissionDenied",value:new Ww.QG({path:o,clientVisibleError:e,isReadonly:t?.isReadonly??!1})}})});if(null!==e)return e}const a=await async function(e,t){const r=await(0,xo.realpath)((0,s.dirname)(e)).catch((()=>{}));if(void 0===r)return e;if(void 0!==t){const n=await(0,xo.realpath)(t).catch((()=>{}));if(void 0!==n&&(0,ts.BJ)(r,n))return(0,s.resolve)(t,(0,s.relative)(n,r),(0,s.basename)(e))}return(0,s.join)(r,(0,s.basename)(e))}(o,this.workspacePath),c=await this.pendingDecisionProvider.requestApproval({type:Bw.Delete,details:{path:a},toolCallId:t.toolCallId});if(!c.approved)return new Ww.Pi({result:{case:"rejected",value:new Ww.iq({path:o,reason:c.reason||""})}});let l;try{l=await(0,xo.stat)(o)}catch(e){return"ENOENT"===_c(e)?new Ww.Pi({result:{case:"fileNotFound",value:new Ww.n0({path:o})}}):new Ww.Pi({result:{case:"error",value:new Ww.GU({path:o,error:Cc(e)})}})}if(!l.isFile()){const e=l.isDirectory()?"directory":"other";return new Ww.Pi({result:{case:"notFile",value:new Ww.LX({path:o,actualType:e})}})}const u=l.size;let d,h;if(u<=ss)try{const e=await Wi(o);d=e.text,h=Hw(e)}catch{}const p=d??"",f=await(0,xo.realpath)(o).catch((()=>o)),m=await(0,xo.stat)(o).catch((()=>{}));if(m?.dev!==l.dev||m.ino!==l.ino)return new Ww.Pi({result:{case:"error",value:new Ww.GU({path:o,error:"File changed while deleting; nothing was removed"})}});e.signal.throwIfAborted();try{await(0,xo.unlink)(o),this.agentFileViews?.recordDelete(o)}catch(e){return"EACCES"===_c(e)?new Ww.Pi({result:{case:"permissionDenied",value:new Ww.QG({path:o,clientVisibleError:"Permission denied"})}}):"EBUSY"===_c(e)?new Ww.Pi({result:{case:"fileBusy",value:new Ww.vX({path:o})}}):new Ww.Pi({result:{case:"error",value:new Ww.GU({path:o,error:Cc(e)})}})}if(this.fileChangeTracker&&void 0!==d){const e={...t.toolCallId?{toolCallId:t.toolCallId}:{},...f===o?{}:{writtenPath:f},beforeMode:511&l.mode};await this.fileChangeTracker.trackChange(o,d,void 0,e,h)}return this.onDeleteForAiTracking&&this.onDeleteForAiTracking({path:o}).catch((()=>{})),new Ww.Pi({result:{case:"success",value:new Ww.fl({path:o,deletedFile:o,fileSize:BigInt(u),prevContent:p})}})}catch(e){r.error=e,r.hasError=!0}finally{zw(r)}}}class Vw{constructor(e,t){this.inner=e,this.extraTools=t}async getTools(e){return[...await this.inner.getTools(e).catch((()=>[])),...this.extraTools]}async getToolsForServers(e,t){const r=await this.inner.getToolsForServers(e,t).catch((()=>[])),n=new Set(t);return[...r,...this.extraTools.filter((e=>n.has(e.clientKey)||n.has(e.providerIdentifier)))]}async getClients(e){return this.inner.getClients(e)}async getClient(e,t){return this.inner.getClient(e,t)}async getInstructions(e){const t=await this.inner.getInstructions(e).catch((()=>[])),r=this.extraTools.filter((e=>e.providerIdentifier===Vn));if(0===r.length)return t;const n=r.map((e=>{const t="string"==typeof e.description&&e.description.length>0?e.description:"(no description provided)";return`- ${e.toolName}: ${t}`})).join("\n");return[...t,new vn.I0({serverIdentifier:Vn,serverName:Vn,instructions:`User-defined tools for this session (server "${Vn}"). Discover schemas via MCP meta-tool discovery for that server, then invoke via the MCP invocation meta-tool.\n\nAvailable tools:\n${n}`})]}async getToolSet(e){return this.inner.getToolSet(e)}}class Kw extends Vw{constructor(e,t){super(e,t),this.observableInner=e}onDidChange(e){return this.observableInner.onDidChange(e)}}var Jw=r("../proto/dist/generated/agent/v1/fetch_exec_pb.js"),Zw=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Xw=/;\s*charset\s*=\s*"?([^";\s]+)/i;class Qw{constructor(e){this.encodingSlices=e?.encodingSlices}async readText(e,t){if(!Wl(this.encodingSlices,e))return await t.text();const r=async function(e,t){if(void 0===e)return"unseen";try{return(0,n.isUtf8)(await e.arrayBuffer())?"utf8_valid":t?"declared_other":"utf8_invalid"}catch{return"unseen"}}(function(e){try{return e.clone()}catch{return}}(t),function(e){const t=Xw.exec(e.headers.get("content-type")??"")?.[1];return void 0!==t&&!/^utf-?8$/i.test(t)}(t)),o=await t.text();return this.recordFetched(e,o,r),o}async recordFetched(e,t,r){try{tu(this.encodingSlices,e,{layer:"exec_web_fetch",evidence:await r},t)}catch{}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,D.VI)(e.withName("LocalFetchExecutor.execute")),!1);const n=t.url;try{const t=await fetch(n),r=await this.readText(e,t),o=t.headers.get("content-type")||"text/plain";return new Jw.uN({result:{case:"success",value:new Jw.Uk({url:n,content:r,statusCode:t.status,contentType:o})}})}catch(e){return new Jw.uN({result:{case:"error",value:new Jw.fk({url:n,error:Cc(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{Zw(r)}}}const Yw=[["safe.bareRepository","explicit"]],ey=[["core.fsmonitor","false"],["core.hooksPath",o.devNull],["core.attributesFile",o.devNull]],ty=[["core.quotePath","false"]];function ry(e){const t="allow-hooks"===e?ey.filter((([e])=>"core.hooksPath"!==e)):ey;return[...Yw,...t]}const ny=(0,Vs.promisify)(iu.execFile),oy=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env","--attr-source"]),sy=new Set(["diff","show","blame","log","whatchanged"]);function iy(e){for(let t=0;t["-c",`${e}=${t}`]))}const vy=yy([...ry("block"),["submodule.recurse","false"],["fetch.recurseSubmodules","false"],["diff.submodule","short"],["status.submoduleSummary","false"],["log.showSignature","false"],["log.diffMerges","separate"],["gpg.openpgp.program",o.devNull],["gpg.x509.program",o.devNull],["gpg.ssh.program",o.devNull]]);function by(e){const t=e?.timeout??0,r=Number.isFinite(t)&&t>0?Math.min(t,2147483647):6e4;return performance.now()+r}function Sy(e,t=2147483647){return Math.max(1,Math.ceil(Math.min(t,e-performance.now())))}function ky(){const e=new Map;return{async exec(t,r,n){const o=by(n);return uy("git",await _y(e,t,r,o),{cwd:t,env:wy,windowsHide:!0,killSignal:"SIGTERM",timeout:Sy(o)})},async run(t,r,n){const o=by(n);return function(e,t,r,n){return new Promise(((o,s)=>{const i=function(e,t,r){const{env:n,...o}=r??{},s=cy(t);return(0,iu.spawn)("git",s,{...o,env:ly(s,n)})}(0,t,{cwd:e,env:wy,windowsHide:!0,stdio:[void 0===n?"ignore":"pipe","pipe","pipe"]}),a=[],c=[];let l=!1;const u=()=>{const e=!l;return l=!0,clearTimeout(d),e},d=setTimeout((()=>{u()&&(i.kill("SIGTERM"),i.stdin?.destroy(),i.stdout?.destroy(),i.stderr?.destroy(),s(Object.assign(new Error("git timed out"),{code:null,killed:!0,signal:"SIGTERM"})))}),Sy(r));i.stdout?.on("data",(e=>{a.push(e)})),i.stderr?.on("data",(e=>{c.push(e)}));for(const e of[i.stdout,i.stderr])e?.on("error",(e=>{u()&&(i.kill("SIGTERM"),s(e))}));i.on("error",(e=>{u()&&s(e)})),i.on("close",((e,t)=>{u()&&(null!==e?o({exitCode:e,stdout:Buffer.concat(a).toString("utf8"),stderr:Buffer.concat(c).toString("utf8")}):s(Object.assign(new Error(`git was killed by ${String(t)}`),{code:e,killed:!1,signal:t})))})),void 0!==n&&null!==i.stdin&&(i.stdin.on("error",(()=>{})),i.stdin.end(n))}))}(t,await _y(e,t,r,o),o,n?.input)}}}async function _y(e,t,r,n){const{prefix:o,tail:s,readsConfig:i}=function(e){const t=cy(e),r=iy(t),n=t.findIndex(((e,t)=>t>r&&("--"===e||"--end-of-options"===e))),o=t.slice(0,-1===n?t.length:n);if(o.includes("--help")||o.includes("-h"))throw new TypeError("git help is refused: it starts the repository's man viewer");if(-1===r)return{prefix:[],tail:t,readsConfig:!1};const s=t[r],i=hy.get(s);if(void 0===i)throw new TypeError(`git ${s} is refused: the pins cover only a fixed set of verbs`);const[a,c]=i,l=o.find((e=>function(e,t,r){const n=r.startsWith("--")?r.slice(2).split("=",1)[0]:"",o=[...py,..."status"===e?["verbose"]:[],..."worktree"===e?["checkout","no-force"]:[],...t?["ignore-submodules","no-ignore-submodules"]:[]];return""!==n&&o.some((e=>e.startsWith(n)))||"status"===e&&/^-[^-]*v/.test(r)}(s,c,e)));if(void 0!==l)throw new TypeError(`git ${s} ${l} is refused: it can start a program the pins miss`);const u=t.slice(r+1),d="worktree"===s?u.find((e=>!e.startsWith("-"))):void 0;if("remove"===d&&!o.includes("--force")&&!o.includes("-f"))throw new TypeError("git worktree remove is refused without --force");if("add"===d&&"--no-checkout"!==u[u.indexOf("add")+1])throw new TypeError("git worktree add is refused unless --no-checkout follows add");return{prefix:[...t.slice(0,r),...vy],tail:[s,...c?["--ignore-submodules=dirty"]:[],...u],readsConfig:a}}(r),a=i?await function(e,t,r,n){const o=`${t}\0${r.join("\0")}`,s=e.get(o);if(void 0!==s)return s;const i=async function(e,t,r){let n;try{n=(await uy("git",[...t,"config","--list","--show-scope","--includes","-z"],{cwd:e,env:wy,windowsHide:!0,killSignal:"SIGTERM",timeout:Sy(r,1e4),maxBuffer:16777216})).stdout}catch(e){throw function(e){if(!(e instanceof Error))return new dy("read-failed");if("syscall"in e&&"string"==typeof e.syscall&&e.syscall.startsWith("spawn"))return e;if("killed"in e&&!0===e.killed)return new dy("timed-out");const t="code"in e&&"number"==typeof e.code?e.code:void 0;return new dy("read-failed",t)}(e)}if(performance.now()>=r)throw new dy("timed-out");return function(e){if(""===e)return[];const t=e.split("\0");if(""!==t.pop()||t.length%2!=0)throw new dy("read-failed");const r=new Set;for(let e=0;eyy([[`filter.${e}.clean`,""],[`filter.${e}.smudge`,""],[`filter.${e}.process`,""],[`filter.${e}.required`,"false"]])))}(n)}(t,r,n);return e.set(o,i),i}(e,t,o,n):[];return[...o,...a,...s]}function Cy(e,t,r){return ky().exec(e,t,r)}var Ey=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class xy{constructor(e={}){void 0!==e.guardedRootLookup&&(this.guardedRootLookup=e.guardedRootLookup)}async exec(e,t,r,n){return Py(e,t,r,n,Cy)}forRequest(){const e=ky();return{exec:(t,r,n,o)=>Py(t,r,n,o,((t,r,n)=>e.exec(t,r,n))),...void 0===this.guardedRootLookup?{}:{guardedRootLookup:this.guardedRootLookup}}}}async function Py(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(s,(0,D.VI)(e.withName("LocalGitExecutor.exec"),{attributes:{"git.cwd":t,"git.args":r,"git.caller":n?.caller}}),!1);const{stdout:i,stderr:a}=await o(t,r,{timeout:n?.timeout});return{exitCode:0,stdout:i,stderr:a}}catch(e){s.error=e,s.hasError=!0}finally{Ey(s)}}var Ry=r("../proto/dist/generated/agent/v1/grep_exec_pb.js");class Iy{constructor(){this.lineEnd=0,this.nextStart=0}}function Ty(e,t,r){const n=e.length;if(t>=n)return!1;const o=e.indexOf("\n",t);if(-1!==o){const n=o>t&&13===e.charCodeAt(o-1);return r.lineEnd=n?o-1:o,r.nextStart=o+1,!0}return r.lineEnd=n,r.nextStart=n,!0}function Ay(e,t,r,n,o,s){const i=e.indexOf("\0",t);if(-1===i||i>=r)return;let a=i+1;for(;a=48&&e.charCodeAt(a)<=57;)a++;if(a===i+1||a>=r)return;const c=e.charCodeAt(a);if(58!==c&&45!==c)return;const l=n.indexOf(0,o);if(-1===l||l>=s)return;const u=l+(a-i);return u>=s||n.toString("latin1",l+1,u+1)!==e.slice(i+1,a+1)?void 0:{file:e.slice(t,i),contentStart:a+1,contentEnd:r,contentBytesStart:u+1,contentBytesEnd:s}}const $y=-(2**31),My=2**31-1;function Dy(e){return Number.isNaN(e)?0:e<$y?$y:e>My?My:e}function Oy(e){if("number"==typeof e&&Number.isFinite(e)&&!(e<0))return Dy(Math.trunc(e))}function Fy(e){const t=e.replace(/\s/g,"_").replace(/[^a-zA-Z0-9_.-]/g,"").replace(/\.+/g,".");return"."===t||".."===t?t.replace(/\./g,"_"):0===t.length?"_":t}async function Ny(e,t){const r=Fy(t),n=(0,s.join)(e,"mcps",r,"tools");let o;try{o=await(0,xo.readdir)(n)}catch(e){if("ENOENT"===_c(e))return{toolNames:[],toolsDirExists:!1};throw e}const i=await Promise.all(o.map((async e=>{if(e.endsWith(".json"))try{return function(e){try{const t=JSON.parse(e);return"string"==typeof t.name&&t.name.length>0?t.name:"string"==typeof t.toolName&&t.toolName.length>0?t.toolName:void 0}catch{return}}(await(0,xo.readFile)((0,s.join)(n,e),"utf8"))}catch{return}}))),a=new Set;for(const e of i)e&&a.add(e);return{toolNames:Array.from(a).sort(((e,t)=>e.localeCompare(t))),toolsDirExists:!0}}const Ly=(0,d.h)("local-exec:mcp-disk-freshness-on-access"),jy="/mcps/",Uy=(0,h.Pu)("mcp.discovery_freshness.check",{description:"MCP discovery surface freshness comparison outcome against canonical live tools",labelNames:["surface","outcome"]}),By=(0,h.v5)("mcp.discovery_freshness.missing_tools",{description:"Number of tools present in canonical live state but missing from the observed discovery surface",labelNames:["surface"]}),Wy=(0,h.v5)("mcp.discovery_freshness.extra_tools",{description:"Number of tools present on the observed discovery surface but absent from canonical live state",labelNames:["surface"]}),Hy=(0,h.v5)("mcp.discovery_freshness.symmetric_difference",{description:"Total symmetric difference between canonical live tools and the observed discovery surface",labelNames:["surface"]}),qy=new Map;function zy(e){const t=e.replace(/\\/g,"/");return t.endsWith("/mcps")?`${t}/`:t}async function Gy({ctx:e,mcpStateAccessor:t,projectDir:r,sanitizedServerFolder:n,readDiskCatalog:o,state:s}){let i=s;if(void 0===i)try{i=await t.getState(e)}catch(t){return void Ly.warn(e,"mcp_disk_state_read_failed",{error_type:t instanceof Error?t.name:typeof t})}const a=i.servers.find((e=>Fy(e.serverIdentifier)===n));if(void 0===a)return;let c;try{c=await o(r,a.serverIdentifier)}catch(t){return void Ly.warn(e,"mcp_disk_catalog_read_failed",{error_type:t instanceof Error?t.name:typeof t})}if(!c.toolsDirExists)return;const l=a.tools.map((e=>e.toolName)).filter((e=>e.length>0)).sort(((e,t)=>e.localeCompare(t)));!function({ctx:e,serverIdentifier:t,canonicalToolNames:r,observedToolNames:n}){const o=new Set(n),s=new Set(r),i=r.filter((e=>!o.has(e))),a=n.filter((e=>!s.has(e))),c=0===i.length&&0===a.length?"match":"mismatch",l={surface:"disk"};Uy.increment(e,1,{...l,outcome:c}),By.histogram(e,i.length,l),Wy.histogram(e,a.length,l),Hy.histogram(e,i.length+a.length,l),"mismatch"===c&&Ly.warn(e,"mcp_disk_discovery_freshness_mismatch",{server_identifier:t,missing_tool_count:i.length,extra_tool_count:a.length})}({ctx:e,serverIdentifier:a.serverIdentifier,canonicalToolNames:l,observedToolNames:c.toolNames})}function Vy(e,t,r,n=Ny){if(void 0===r||(void 0===(o=r)||!zy(o).includes(jy)))return;var o;const s=function(e){const t=zy(e),r=t.indexOf(jy);if(-1===r)return;const n=t.slice(0,r),o=t.slice(r+6).split("/").filter(Boolean);return 0!==n.length?0===o.length?{projectDir:n,kind:"mcps_root"}:{projectDir:n,kind:"server",sanitizedServerFolder:o[0]}:void 0}(r);if(void 0===s)return;let i,a;const c="mcps_root"===s.kind;"mcps_root"===s.kind?(i=`${s.projectDir}\0__mcps_root__`,a=void 0):(i=`${s.projectDir}\0${s.sanitizedServerFolder}`,a=s.sanitizedServerFolder);const l=qy.get(i);void 0!==l&&clearTimeout(l);const u=e,d=setTimeout((()=>{qy.delete(i),(async()=>{if(c){const e=await t.getState(u);for(const r of e.servers){const o=Fy(r.serverIdentifier);await Gy({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:o,readDiskCatalog:n,state:e})}}else void 0!==a&&await Gy({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:a,readDiskCatalog:n})})().catch((e=>{Ly.warn(u,"mcp_disk_discovery_freshness_schedule_failed",{error_type:e instanceof Error?e.name:typeof e})}))}),2e3);qy.set(i,d)}async function Ky(e){try{return(await(0,xo.stat)(e,{bigint:!0})).mtimeNs}catch{return}}function Jy(e,t,r){const n=e.map(((e,n)=>({file:e,mtime:t[n],segments:e.path.split(r)})));return n.sort(((e,t)=>e.mtime!==t.mtime?void 0===e.mtime?1:void 0===t.mtime||e.mtime>t.mtime?-1:1:function({left:e,right:t}){const r=Math.min(e.length,t.length);for(let n=0;ne.file))}async function Zy(e,t,r=Ky){const n=e.map((e=>({item:e,path:t(e)})));let o;try{o=await(0,Nr.wj)(Promise.all(n.map((({path:e})=>r(e)))),2e3,"stat timed out")}catch(t){if(t instanceof Nr.MU)return{items:[...e],statTimedOut:!0};throw t}return{items:Jy(n,o,s.sep).map((({item:e})=>e)),statTimedOut:!1}}var Xy=r("../proto/dist/generated/agent/v1/read_exec_pb.js");const Qy=Buffer.from([137,80,78,71,13,10,26,10]),Yy=Buffer.from([0,0,0,0,73,69,78,68,174,66,96,130]),ev=e=>{if(e.lengthe.subarray(e.length-Yy.length).equals(Yy)||(e=>{let t=Qy.length+25;for(;t+Yy.length<=e.length;){const r=e.readUInt32BE(t);if(r>e.length-t-Yy.length)return!1;if("IEND"===e.toString("ascii",t+4,t+8))return e.subarray(t,t+Yy.length).equals(Yy);t+=Yy.length+r}return!1})(e))(e))return;const t=e.readUInt32BE(16),r=e.readUInt32BE(20);return t<1||r<1?void 0:{width:t,height:r,colorType:e.readUInt8(25)}},tv=e=>1===e||e>=208&&e<=216,rv=e=>192===e||193===e||194===e,nv=e=>e>=195&&e<=207&&196!==e&&200!==e&&204!==e,ov=e=>0===e||e>=208&&e<=215,sv=(e,t)=>{let r=e.indexOf(255,t);for(;-1!==r&&r+1(e=>{const t=ev(e);if(void 0!==t)return{mimeType:"image/png",width:t.width,height:t.height}})(e)??(e=>{if(e.length<4||255!==e[0]||216!==e[1]||!(e=>255===e[e.length-2]&&217===e[e.length-1]||(e=>{let t=2;for(;t+2<=e.length;){if(255!==e[t])return!1;const r=e[t+1];if(255===r){t+=1;continue}if(217===r)return!0;if(tv(r)){t+=2;continue}if(t+4>e.length)return!1;const n=e.readUInt16BE(t+2);if(n<2)return!1;const o=t+2+n;if(218!==r){t=o;continue}const s=sv(e,o);if(void 0===s)return!1;t=s}return!1})(e))(e))return;let t=2;for(;t+4<=e.length;){if(255!==e[t])return;const r=e[t+1];if(255===r){t+=1;continue}if(tv(r)){t+=2;continue}if(218===r||217===r||nv(r))return;const n=e.readUInt16BE(t+2);if(n<2)return;if(rv(r)){if(n<8||t+9>e.length)return;const r=e.readUInt16BE(t+5),o=e.readUInt16BE(t+7);if(o<1||r<1)return;return{mimeType:"image/jpeg",width:o,height:r}}t+=2+n}})(e),av=(e,t)=>({width:Math.max(e?.width??0,t.width),height:Math.max(e?.height??0,t.height)}),cv=(e,t)=>{for(;t{const t=e.toString("latin1",0,6);return e.subarray(0,Qy.length).equals(Qy)?"png":t.startsWith("ÿØÿ")?"jpeg":"GIF87a"===t||"GIF89a"===t?"gif":t.startsWith("BM")?"bmp":t.startsWith("II*\0")||t.startsWith("MM\0*")?"tiff":t.startsWith("ID3")?"id3":void 0},uv={0:1,2:3,4:2,6:4},dv=async({data:e,width:t,height:r})=>{const n=hv(e);if(void 0===n||t>n.width||r>n.height)return;const o=n.width*n.channels,s=new Uint32Array(n.width);for(let e=0;e{let t;const r=[];let n=8;for(;n+12<=e.length;){const o=e.readUInt32BE(n),s=e.toString("ascii",n+4,n+8),i=e.subarray(n+8,n+8+o);if(i.length!==o)return;if("IHDR"===s){const e=uv[i[9]];if(void 0!==t||13!==o||8!==i[8]||0!==i[12]||void 0===e)return;t={width:i.readUInt32BE(0),height:i.readUInt32BE(4),channels:e}}else if("IDAT"===s)r.push(i);else{if("tRNS"===s)return;if("IEND"===s)break}n+=o+12}return void 0===t||0===r.length?void 0:{...t,idat:r}},pv=({filter:e,row:t,previous:r,bytesPerPixel:n})=>{if(0!==e)for(let o=0;o=n?t[o-n]:0,i=r[o];switch(e){case 1:t[o]+=s;break;case 2:t[o]+=i;break;case 3:t[o]+=s+i>>1;break;case 4:{const e=o>=n?r[o-n]:0,a=s+i-e,c=Math.abs(a-s),l=Math.abs(a-i),u=Math.abs(a-e);t[o]+=c<=l&&c<=u?s:l<=u?i:e;break}default:throw new Error(`unknown PNG filter type ${e}`)}}},fv=({row:e,channels:t,columnOf:r,sums:n,counts:o})=>{const s=t<3;for(let i=0,a=0;i{for(let s=0;s0&&(e[c]=Math.round(n[i]/a),e[c+1]=Math.round(n[i+1]/a),e[c+2]=Math.round(n[i+2]/a),e[c+3]=Math.round(a/o[s]))}n.fill(0),o.fill(0)},gv={0:1,2:3,3:1,4:2,6:4},wv=[1,2,4,8,16],yv=[[0,0,8,8],[4,0,8,8],[0,4,4,8],[2,0,4,4],[0,2,2,4],[1,0,2,2],[0,1,1,2]],vv=async e=>{const t=bv(e);if(void 0===t)return;const r=Sv(t);let n=0;const o=ch.Readable.from(t.idat).pipe((0,oh.createInflate)());for await(const e of o)if(n+=e.length,n>=r)return void o.destroy();throw new Error(`PNG pixel data ends after ${n} of ${r} bytes`)},bv=e=>{let t;const r=[];let n=8;for(;n+12<=e.length;){const o=e.readUInt32BE(n),s=e.toString("ascii",n+4,n+8),i=e.subarray(n+8,n+8+o);if("IHDR"===s&&void 0===t&&13===i.length){const e=gv[i[9]];if(void 0===e||!wv.includes(i[8])||i[12]>1)return;t={width:i.readUInt32BE(0),height:i.readUInt32BE(4),bitsPerPixel:e*i[8],interlaced:1===i[12]}}else if("IDAT"===s)r.push(i);else if("IEND"===s)break;n+=o+12}return void 0===t||0===r.length?void 0:{...t,idat:r}},Sv=({width:e,height:t,bitsPerPixel:r,interlaced:n})=>{const o=(e,t)=>e<=0||t<=0?0:t*(1+Math.ceil(e*r/8));return n?yv.reduce(((r,[n,s,i,a])=>r+o(Math.ceil((e-n)/i),Math.ceil((t-s)/a))),0):o(e,t)};const kv=()=>{throw new Error("webp codec not registered: registerWebpCodec() must be called by a Node server before decoding/encoding webp")},_v=e=>e.length>=12&&"RIFF"===e.toString("ascii",0,4)&&"WEBP"===e.toString("ascii",8,12),Cv=e=>{if(!_v(e)||e.length<16)return;const t=e.toString("ascii",12,16);if("VP8 "===t){if(e.length<30||157!==e[23]||1!==e[24]||42!==e[25])return;return{width:16383&(e[26]|e[27]<<8),height:16383&(e[28]|e[29]<<8)}}if("VP8L"===t){if(e.length<25||47!==e[20])return;const t=(e[21]|e[22]<<8|e[23]<<16|e[24]<<24)>>>0;return{width:1+(16383&t),height:1+(t>>14&16383)}}if("VP8X"===t){if(e.length<30)return;return{width:1+(e[24]|e[25]<<8|e[26]<<16),height:1+(e[27]|e[28]<<8|e[29]<<16)}}},Ev=e=>kv().decode(e);async function xv(e){((e,t)=>{if(!Number.isSafeInteger(e)||e<1||e>t)throw new Error("pngByteBudgetBytes must be a positive integer at most MAX_IMAGE_SIZE_BYTES")})(e.budgetBytes,e.maxImageBytes);iv(e.data);return e.resizeWithoutBudget(e.data)}const Pv=[{width:1280,height:800},{width:1456,height:840}],Rv=e=>void 0!==e&&Pv.some((t=>t.width===e.width&&t.height===e.height)),Iv=1048576,Tv=e=>{const t=e.buffer;return t instanceof ArrayBuffer?new Uint8Array(t,e.byteOffset,e.byteLength):Uint8Array.from(e)};function Av(e,t,r=1024){if(e<1||t<1)return{width:e,height:t,needsResize:!1};const n=Math.max(e,t);if(n<=r)return{width:e,height:t,needsResize:!1};const o=Math.min(e,t);if(o<8)return{width:e,height:t,needsResize:!1};let s=r/n,i=Math.max(1,Math.round(e*s)),a=Math.max(1,Math.round(t*s));return(i<8||a<8)&&(s=8/o,i=Math.max(8,Math.round(e*s)),a=Math.max(8,Math.round(t*s))),{width:i,height:a,needsResize:i!==e||a!==t}}const $v=(e,t,r=1024)=>Av(e,t,r),Mv=(e,t)=>Rv({width:e,height:t})?{width:e,height:t,needsResize:!1}:Av(e,t),Dv=(e,t,r)=>{e.resize({w:t,h:r})};function Ov(e){if(void 0===e)throw new Error("image dimensions could not be read before decoding");const{width:t,height:r}=e;if(!(t*r<=178956970))throw new Error(`image dimensions ${t}x${r} exceed the 178956970 pixel decode limit`);if(!(Math.max(t,r)<=1e6))throw new Error(`image dimensions ${t}x${r} exceed the 1000000 pixel side limit`)}const Fv=(e,t)=>{switch(t){case"tiff":throw new Error("TIFF images are not supported; convert the image to PNG or JPEG");case"id3":throw new Error("images that start with an ID3 tag are not supported");case"jpeg":return;default:Ov(((e,t)=>{switch(t){case"png":return(e=>{let t,r=Qy.length;for(;r+16<=e.length;)"IHDR"===e.toString("ascii",r+4,r+8)&&(t=av(t,{width:e.readUInt32BE(r+8),height:e.readUInt32BE(r+12)})),r+=12+e.readUInt32BE(r);return t})(e);case"gif":return(e=>{if(e.length<13)return;const t={width:e.readUInt16LE(6),height:e.readUInt16LE(8)};let r=13+(128&(n=e[10])?3<<1+(7&n):0);for(var n;re.length<26?void 0:{width:e.readUInt32LE(18),height:Math.abs(e.readInt32LE(22))})(e)}})(e,t))}},Nv=e=>{const{width:t,height:r}=$v(e.width,e.height,1280);return{width:t,height:r}},Lv=async(e,t)=>{let{width:r,height:n}=e,o=await t({width:r,height:n});for(;o.length>Iv&&r>8&&n>8;)r=Math.max(8,Math.round(.8*r)),n=Math.max(8,Math.round(.8*n)),o=await t({width:r,height:n});return{data:Tv(o),mimeType:"image/webp",reencoded:!0}},jv=async(e,t)=>{const r=(await gw()).fromBitmap({data:Buffer.from(e.data),width:e.width,height:e.height});return Lv(t,(async e=>(r.bitmap.width===e.width&&r.bitmap.height===e.height||Dv(r,e.width,e.height),(e=>kv().encode(e))({data:r.bitmap.data,width:r.bitmap.width,height:r.bitmap.height}))))};let Uv;const Bv=async(e,t)=>{if(void 0!==t?.pngByteBudgetBytes){const{pngByteBudgetBytes:r,...n}=t,o=iv(e);return"image/png"===o?.mimeType&&Rv(o)&&await vv(e),xv({data:e,budgetBytes:r,maxImageBytes:Iv,fitImage:Mv,resizeWithoutBudget:e=>Bv(e,n)})}const r=await(async(e,t)=>{const r=_v(e);if(r&&!0===t?.preserveWebpDimensions)return;const n=r?void 0:iv(e),o=r?Cv(e):n;if(void 0===o||!Rv(o))return;const s=Uv;if(void 0!==n&&void 0!==s&&!Rv(await s.readOrientedDimensions(e)))return;const i="image/png"===n?.mimeType;if(i&&await vv(e),e.length<=Iv)return{data:Tv(e),mimeType:n?.mimeType??"image/webp"};const a=s?.resizeWebp;if(void 0!==a)return Lv(o,(t=>a({data:e,...t})))})(e,t);if(void 0!==r)return r;if(_v(e))return(async(e,t)=>{const r=Cv(e);if(!0===t?.preserveWebpDimensions&&void 0!==r)return{data:Tv(e),mimeType:"image/webp"};if(void 0!==r&&!$v(r.width,r.height,1280).needsResize&&e.length<=Iv)return{data:Tv(e),mimeType:"image/webp"};if("passthrough"===t?.webpWithoutCodec)return{data:Tv(e),mimeType:"image/webp"};Ov(r);const n=undefined;if(void 0!==n)return Lv(Nv(r),(t=>n({data:e,...t})));const o=await Ev(e);return jv(o,Nv(o))})(e,t);const n=iv(e);if(void 0!==n&&e.length<=Iv&&!$v(n.width,n.height).needsResize)return{data:Tv(e),mimeType:n.mimeType};const o=lv(e);void 0!==o&&Fv(e,o);const s=void 0===n?void 0:$v(n.width,n.height),i="image/png"===n?.mimeType&&!0===s?.needsResize?await dv({data:e,width:s.width,height:s.height}).catch((()=>{})):void 0;void 0===i&&"png"===o&&await vv(e);const a=await gw(),c=void 0===i?await a.read(e):a.fromBitmap(i),l=(e=>{switch(e.mime){case"image/png":default:return"image/png";case"image/bmp":return"image/bmp";case"image/tiff":return"image/tiff";case"image/x-ms-bmp":return"image/x-ms-bmp";case"image/gif":return"image/gif";case"image/jpeg":return"image/jpeg"}})(c),u=!0===t?.convertUnsupportedModelFormatsToPng&&"image/png"!==l&&"image/jpeg"!==l?"image/png":l,{width:d,height:h,needsResize:p}=$v(c.width,c.height);if(void 0===i&&!p&&e.length<=Iv&&u===l)return{data:Tv(e),mimeType:l};let f=d,m=h;p&&Dv(c,f,m);let g=await c.getBuffer(u);for(;g.length>Iv&&f>8&&m>8;)f=Math.max(8,Math.round(.8*f)),m=Math.max(8,Math.round(.8*m)),Dv(c,f,m),g=await c.getBuffer(u);return{data:Tv(g),mimeType:u,reencoded:!0}},Wv=async e=>{const t=Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=lv(t);let n;if(_v(t))return{kind:"unchecked"};if(void 0===r)return{kind:"unchecked"};{Fv(t,r);const e=await gw();n=async()=>("png"===r&&await vv(t),e.read(t))}try{return await n(),{kind:"decodes"}}catch(e){return{kind:"undecodable",reason:e instanceof Error?e.message:String(e)}}},Hv=BigInt(0),qv=BigInt(8),zv=BigInt(16),Gv=BigInt(65535);function Vv(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function Kv(e){const t=e.split(".");if(4!==t.length)return;let r=Hv;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<>zv&Gv)),t.push(Number(o.value&Gv))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function Zv(e){return Kv(e)??function(e){const t=Vv(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=Jv(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<7?void 0:{version:6,value:[...s,...new Array(8-a).fill(0),...i].reduce(((e,t)=>e<i)return!1;const a=BigInt(i-s);return o.value>>a==n.value>>a}(r,n);if(n.startsWith("*.")){const e=n.slice(2);return r===e||r.endsWith(`.${e}`)}return r===n}function Qv(e,t){const r=function(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch{return}}(e);return!!r&&function(e,t){return t.some((t=>Xv(e,t)))}(r.hostname,t)}var Yv=r("../constants/dist/commercial-cursor-hosts.js");new Set([1,2]);const eb="cursor/requiresConfirmation",tb="https://grok.com/connectors-oauth-exchange-code/",rb="https://x.com/i/connectors/oauth_callback",nb="https://chat.x.com/connectors/oauth_callback",ob="https://lite.x.com/i/connectors/oauth_callback",sb={provider:"google-workspace",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0,authorizationParams:{access_type:"offline",prompt:"select_account consent"}},ib={provider:"x-money",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,registeredAppRedirectUris:[tb,rb]},ab="x-cursor-auth";function cb(e,t){return function({serverUrl:e,restMcpHost:t}){if(void 0===e)return;let r;try{r=new URL(e)}catch{return}return"https:"===r.protocol&&r.hostname.toLowerCase()===t.toLowerCase()&&""===r.port?lb(e):void 0}({serverUrl:e,restMcpHost:t})}function lb(e){if(void 0===e)return;let t;try{t=new URL(e)}catch{return}const r=/^\/rest-mcp\/([^/]+)\/mcp\/?$/.exec(t.pathname);return r?.[1]}new Set(Object.values({notConnected:"scm_not_connected",tokenUnavailable:"scm_token_unavailable",tokenRejected:"scm_token_rejected",repoNotAccessible:"scm_repo_not_accessible",orgBlocked:"scm_org_blocked"})),new Set(Object.values({originNotEnabled:"origin_not_enabled",teamDisabled:"team_disabled",admissionRejected:"admission_rejected"}));const ub="https://mcp.shop.com",db={provider:"grok-connectors",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,scopes:["grok-plugins:access","offline_access"]},hb=new Map([["mcp.slack.com",{displayName:"Slack",baseScopes:["canvases:read","canvases:write","channels:history","channels:read","channels:write","chat:write","emoji:read","files:read","files:write","groups:history","groups:read","im:history","im:read","im:write","lists:read","lists:write","mpim:history","mpim:read","mpim:write","reactions:read","reactions:write","search:read.files","search:read.im","search:read.mpim","search:read.private","search:read.public","search:read.users","users:read","users:read.email"],stepUpScopes:{"groups:write":{action:"create private channels",tools:[{name:"slack_create_conversation",args:{is_private:!0}}]}},missingScopeAnswer:/\bmissing_scope\b/}]]),pb=new Map([["gmailmcp.googleapis.com",{...sb,scopes:["https://www.googleapis.com/auth/gmail.readonly","https://www.googleapis.com/auth/gmail.compose","https://www.googleapis.com/auth/gmail.modify"]}],["drivemcp.googleapis.com",{...sb,scopes:["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/drive.file"]}],["calendarmcp.googleapis.com",{...sb,scopes:["https://www.googleapis.com/auth/calendar.events","https://www.googleapis.com/auth/calendar.calendarlist.readonly","https://www.googleapis.com/auth/calendar.events.readonly","https://www.googleapis.com/auth/calendar.events.freebusy"]}],["docsmcp.googleapis.com",{...sb,scopes:["https://www.googleapis.com/auth/documents"]}],["sheetsmcp.googleapis.com",{...sb,scopes:["https://www.googleapis.com/auth/spreadsheets"]}],["slidesmcp.googleapis.com",{...sb,scopes:["https://www.googleapis.com/auth/presentations"]}],["bigquery.googleapis.com",{...sb,scopes:["https://www.googleapis.com/auth/bigquery"]}],["api.x.com",{provider:"x",clientRegistration:"static",unauthenticatedConnect:!1,rejectsCustomSchemeRedirects:!1,pinsScopesOverConfiguredScopes:!0}],["mcp.money-dev.x.com",ib],["mcp.money-staging.x.com",ib],["mcp.money.x.com",ib],["connectors-gateway.grok.gcp.mouseion.dev",db],["connectors-gateway.grok.com",db],["mcp.hubspot.com",{provider:"hubspot",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0}],["mcp.box.com",{provider:"box",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0}],["mcp.asana.com",{provider:"asana",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,configuredSecretStaysOnBackend:!0}],["mcp.strava.com",{provider:"strava",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,scopes:["read","activity:read_all","profile:read_all"]}],["mcp.quickbooks.intuit.com",{provider:"quickbooks-online",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,unauthenticatedEndpointBlocked:!0,backendOnlyTokenExchange:!0,scopes:["com.intuit.quickbooks.accounting","foundations.tools.businessreports.read","foundations.tools.bi-dashboard","foundations.tools.transactions.write","foundations.tools.companyprofile.read","foundations.tools.companyprofile.write","payroll.tools.tax.read","payroll.tools.employer.read","payroll.tools.employer.manage","payroll.tools.run.read","payroll.tools.run.manage","payroll.tools.employee.read","payroll.tools.employee.manage","worker-mgmt.tools.employee.read","worker-mgmt.tools.employee.manage","time-tracking.tools.timeentry.read","sales.tools.invoice.read","sales.tools.invoice","sales.tools.estimate.read","sales.tools.estimate","sales.tools.payment-link.read","sales.tools.payment-link","sales.tools.settings.read","sales.tools.settings","sales.tools.salesorder.read","sales.tools.salesorder","contact.tools.customer.read","contact.tools.customer","catalog.tools.item.read","catalog.tools.item","lending.tools.servicing.read","money-onboarding.tools.application"]}],["setup.shopify.com",{provider:"shopify",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!1}],["mcp.cloudflare.com",{provider:"cloudflare",clientRegistration:"dynamic",unauthenticatedConnect:!1,rejectsCustomSchemeRedirects:!1,scopes:["user:read","account:read","offline_access","d1.metadata_read","d1.read","d1.write","workers-scripts.read","workers-scripts.write","workers-routes.read","workers-routes.write","workers-tail.read","workers-kv-storage.metadata_read","workers-kv-storage.read","workers-kv-storage.write","workers-r2.metadata_read","workers-r2.read","workers-r2.write","workers-r2-bucket-item.read","workers-r2-bucket-item.write","workers-observability.read","workers-observability.write","dns.read","dns.write","zone.read","zone.write"],pinsScopesOverConfiguredScopes:!0,scopesPinGate:"mcp_cloudflare_api_oauth_scopes"}],["mcp.shop.com",{provider:"shop",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,backendOnlyTokenExchange:!0,scopes:["openid","personal_agent"],pinsScopesOverConfiguredScopes:!0,authorizationParams:{resource:ub}}],["api.elections.kalshi.com",{provider:"kalshi",clientRegistration:"dynamic",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0}],["mcp.squarespace.com",{provider:"squarespace",clientRegistration:"dynamic",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0}]]),fb=[".databricks.com",".azuredatabricks.net"];const mb=/^\/sncapps\/mcp-server\/mcp\/[^/]+$/,gb={provider:"databricks",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,scopes:["ai-gateway","offline_access"],pinsScopesOverConfiguredScopes:!0},wb={provider:"servicenow",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,unauthenticatedEndpointBlocked:!0,backendOnlyTokenExchange:!0,ownMcpJsonClientMayExchange:!0};function yb(e){if(void 0===e)return;let t;try{t=new URL(e)}catch{return}return function(e){return"https:"===e.protocol&&""===e.port&&""===e.username&&""===e.password&&function(e){const t=e.toLowerCase();return!(!/^[a-z0-9.-]+$/.test(t)||t.includes("..")||t.startsWith("."))&&fb.some((e=>t.endsWith(e)&&t.length>e.length))}(e.hostname)&&"/ai-gateway/mcp-services/system.ai.genie_one_mcp"===e.pathname.replace(/\/+$/,"")}(t)?gb:function(e){return"https:"===e.protocol&&""===e.port&&""===e.username&&""===e.password&&mb.test(e.pathname.replace(/\/+$/,""))}(t)?wb:(r=t.hostname,pb.get(r.toLowerCase()));var r}function vb(e){return e.endsWith("/")?e:`${e}/`}async function bb(e,t){if(void 0===t)return;const r=new URL(e),n=new URL(t);if(r.origin!==n.origin||!vb(r.pathname).startsWith(vb(n.pathname)))throw new Error(`Protected resource ${t} does not match expected ${r.href} (or origin)`);return n}const Sb=/^\/shops\/[A-Za-z0-9-]+\/mcp$/;function kb(e){if(void 0!==e)try{return new URL(e)}catch{return}}async function _b(e,t){if(void 0===t)return;const r=new URL(e),n=kb(t);if(void 0===n||n.origin!==r.origin||n.pathname!==r.pathname&&!Sb.test(n.pathname))throw new Error(`Protected resource ${t} does not match expected ${r.href} (or origin)`);return n}function Cb(e){const t=kb(e);return void 0===t?void 0:hb.get(t.hostname.toLowerCase())}const Eb=new Set([...pb].filter((([,e])=>"google-workspace"===e.provider)).map((([e])=>e))),xb="https://www.cursor.com/bot/mcp/oauth/callback",Pb={portal:"https://www.cursor.com/agents/mcp/oauth/callback",grokBotBounce:xb},Rb="tailnet_";new Set([`${Rb}waiting_for_approval`,`${Rb}tailnet_locked`,`${Rb}joining`]);const Ib="grokbot://mcp/oauth/callback",Tb="http://localhost:8787/callback",Ab="gb";function $b(e){const t=new URL(Tb);return t.port=String(e),t.toString()}function Mb(e){try{const t=new URL(e);if("http:"!==t.protocol)return!1;const r=t.hostname;return"localhost"===r||"127.0.0.1"===r||"[::1]"===r}catch{return!1}}function Db(e){const t=e.redirectUrl??Tb;if(!0!==e.loopbackIpv4||!Mb(t))return t;const r=new URL(t);return r.hostname="127.0.0.1",r.toString()}function Ob(e,t=Pb){const r=new Set,n=void 0!==e&&Mb(e);return e&&!n&&r.add(e),r.add(t.portal),e===Ib&&r.add(t.grokBotBounce),r.add(Tb),e&&n&&r.add(e),Array.from(r)}function Fb(e){var t;if(void 0!==e&&0!==e.length)try{const r=JSON.parse(e);if("object"==typeof(t=r)&&null!==t&&!Array.isArray(t))return r}catch{}}function Nb(e){if(void 0===e)return{};const t={};"string"==typeof e.title&&e.title.length>0&&(t.title=Jo(e.title,256));for(const r of["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"])"boolean"==typeof e[r]&&(t[r]=e[r]);return function(e){return!0===e?.[eb]}(e)&&(t[eb]=!0),0===Object.keys(t).length?{}:{annotationsJson:JSON.stringify(t)}}new Map([[Ab,Ib],["gw",tb],["gd",Tb],["xa",rb],["xc",nb],["xl",ob],...[18787,28787,31787].map((e=>[`gd${e}`,$b(e)]))]),new Map([[Ib,Ab],[xb,Ab],[tb,"gw"],[rb,"xa"],[nb,"xc"],[ob,"xl"]]),Db({loopbackIpv4:!0});var Lb=r("../mcp-core/dist/transport/mcp-url-utils.js");function jb(e){return e.trim().toLowerCase()}const Ub="";function Bb({mode:e,tools:t}){const r=(t??[]).map(jb).filter((e=>e.length>0)),n=void 0===e?void 0:jb(e);return"all"===n?{mode:"all"}:"reads"===n?{mode:"reads"}:r.length>0?{mode:"custom",tools:r}:{mode:"all"}}function Wb(e,t){switch(e.mode){case"all":return!0;case"custom":return function(e,t){const r=jb(e);return 0!==r.length&&r!==Ub&&t.some((e=>jb(e)===r))}(t.name,e.tools);case"reads":return void 0!==(r=t.annotations)&&!0!==r.destructiveHint&&!0===r.readOnlyHint;default:return e}var r}function Hb(e,t){switch(t.mode){case"all":return[`${e}:*`];case"custom":return t.tools.filter((e=>jb(e)!==Ub)).map((t=>`${e}:${t}`));case"reads":return[];default:return t}}const qb=new Set(["ash","bash","csh","dash","fish","ksh","powershell","pwsh","sh","tcsh","zsh","cmd"]);function zb(e){return e.trim().split(/\s+/).filter(Boolean)}function Gb(e){const t=function(e){const t=e.trim(),r=t[0];if('"'===r||"'"===r){const e=t.indexOf(r,1);if(-1!==e)return t.slice(0,e+1)}return zb(t)[0]}(e);if(!t)return!1;const r=t.replace(/^["']|["']$/g,"").replaceAll("\\","/").split("/"),n=(r[r.length-1]??"").replace(/\.exe$/i,"").toLowerCase();return qb.has(n)}function Vb(e,t){if(e.length>t.length)return!1;for(let r=0;r=t.tokenCount)continue;let a=!0;for(const t of e.tokens)if(!n.has(t)){a=!1;break}if(!a)continue;const c=Vb(e.tokens,t.tokens);void 0!==o?e.tokenCount>o.tokenCount?(o=e,s=c):e.tokenCount===o.tokenCount&&c&&!s&&(o=e,s=!0):(o=e,s=c)}void 0!==o&&(t.indentLevel=o.indentLevel+1,t.ancestorIds=[...o.ancestorIds,t.id])}const n=r.filter((e=>!r.some((t=>t.id!==e.id&&t.tokenCounte.id));return{options:r,defaultSelectedOptionIds:n}}(e),n=[...r.defaultSelectedOptionIds];if(!t||0===t.length)return{defaultSelectedOptionIds:n,hasClassifierSuggestions:!1};const o=[],s=new Set;for(const e of t){const t=r.options.find((t=>t.id===e));if(t){o.push(t.id),s.add(Jb(t.id));continue}const n=r.options.filter((t=>t.id.startsWith(`${e} `)||t.id===e)),i=r.options.filter((t=>e.startsWith(`${t.id} `)||e===t.id));if(i.length>0){const e=i.reduce(((e,t)=>e.id.length>t.id.length?e:t));o.push(e.id),s.add(Jb(e.id))}else if(n.length>0){const e=n.reduce(((e,t)=>e.id.length!s.has(Jb(e))));return{defaultSelectedOptionIds:[...new Set([...i,...o])],hasClassifierSuggestions:!0}}(e,t).defaultSelectedOptionIds}const Xb=["com.todesktop.230313mzl4w4u92","co.anysphere.cursor","com.anysphere.molten-glass"],Qb=["cursor","molten glass"];function Yb(e){return Xb.some((t=>e===t||e.startsWith(`${t}.`)))}const eS=[{bundleId:"com.apple.scripteditor2",name:"Script Editor"},{bundleId:"com.apple.automator",name:"Automator"},{bundleId:"com.apple.shortcuts",name:"Shortcuts"}],tS=[{bundleId:"com.apple.terminal",name:"Terminal"},{bundleId:"com.googlecode.iterm2",name:"iTerm",aliases:["iTerm2"]},{bundleId:"dev.warp.warp-stable",name:"Warp"},{bundleId:"dev.warp.warp-preview",name:"WarpPreview",aliases:["Warp Preview"]},{bundleId:"com.mitchellh.ghostty",name:"Ghostty"},{bundleId:"org.alacritty",name:"Alacritty"},{bundleId:"net.kovidgoyal.kitty",name:"kitty"},{bundleId:"com.github.wez.wezterm",name:"WezTerm"},{bundleId:"co.zeit.hyper",name:"Hyper"},{bundleId:"org.tabby",name:"Tabby"},...eS,{bundleId:Xb[0],name:"Cursor"}];function rS(e){const t=e.toLowerCase(),r=(0,s.basename)(e,".app").toLowerCase(),n=tS.find((({bundleId:e,name:n,aliases:o=[]})=>e===t||[n,...o].some((e=>{const n=e.toLowerCase();return n===t||n===r}))));return void 0!==n?{bundleId:n.bundleId,name:n.name}:Yb(t)?{bundleId:t,name:"Cursor"}:[t,r].some((e=>Qb.some((t=>e===t||e.startsWith(`${t} `)))))?{bundleId:Xb[0],name:"Cursor"}:void 0}const nS=new Set(["com.apple.systempreferences","com.apple.keychainaccess","com.apple.passwords","com.1password.1password","com.agilebits.onepassword7","com.bitwarden.desktop","com.lastpass.lastpass","org.keepassxc.keepassxc"]);function oS(e){return nS.has(e.toLowerCase())}function sS(e){return`app/${e}`}function iS(e){return"object"==typeof e&&null!==e}function aS(e){return lS.includes(e)}function cS(e){if(!iS(e))return;const{appArg:t,appSelectorArgs:r,capturesScreen:n}=e;if("boolean"==typeof n){if(void 0!==r){if(void 0!==t||!iS(r))return;const e={};for(const[t,n]of Object.entries(r)){if(!aS(t)||"string"!=typeof n||0===n.length)return;e[t]=n}if(0===Object.keys(e).length)return;return{appSelectorArgs:e,capturesScreen:n}}return void 0===t?{capturesScreen:n}:"string"==typeof t&&t.length>0?{appArg:t,capturesScreen:n}:void 0}}const lS=["pid","bundleId","path","appName"],uS=/^[+-]?\d+$/;var dS=r("../../node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/create.js");const hS=".cursor/worktrees",pS=".grok/build-desktop/worktrees",fS="win32"===process.platform||"darwin"===process.platform,mS=new Map;function gS(e,t){if(!(0,ts.BJ)(t,e))return;const r=(fS?(0,s.relative)(e.toLowerCase(),t.toLowerCase()):(0,s.relative)(e,t)).split(s.sep).filter(Boolean);return r.length>0?r:void 0}function wS(e,t){const r=gS(e,t);if(void 0!==r)return r;const n=function(e){if(mS.has(e))return mS.get(e);const t=[];let r,n=e;for(;;)try{const e=Ro.realpathSync.native(n);r=0===t.length?e:(0,s.join)(e,...t);break}catch(e){const r=_c(e);if("ENOENT"!==r&&"ENOTDIR"!==r)break;const o=(0,s.dirname)(n);if(o===n)break;t.unshift((0,s.basename)(n)),n=o}return mS.size>=64&&mS.clear(),mS.set(e,r),r}(e);var o,i;return void 0!==n&&(o=n,i=e,fS?o.toLowerCase()!==i.toLowerCase():o!==i)?gS(n,t):void 0}function yS(e){const t=e?.trim();return t&&".cursor"!==t?[".cursor",t]:[".cursor"]}function vS(e,t){const r=(0,o.homedir)();return yS(t?.dataFolderName).some((t=>void 0!==wS((0,s.join)(r,t,"projects"),e)))}function bS(e){const t=(0,o.homedir)();return[hS,pS].some((r=>void 0!==wS((0,s.join)(t,...r.split("/")),e)))}function SS(e,t,r){const n=function(e,t){const r=(0,o.homedir)();for(const n of yS(t?.dataFolderName)){const t=wS((0,s.join)(r,n,"projects"),e);if(void 0!==t&&t.length>=2)return t[1]}}(e,r);return void 0!==n&&(fS?t.some((e=>e.toLowerCase()===n.toLowerCase())):t.includes(n))}function kS(e,t,r){const n=wS(e,t);if(void 0===n)return!1;const o=n[0];return fS?r.some((e=>e.toLowerCase()===o.toLowerCase())):r.includes(o)}const _S=/[\s"'`=/\\:;()[\]{},&|<>]/,CS="win32"===process.platform||"darwin"===process.platform;async function ES(e,t,r,n){const o=AS(await TS((0,s.join)(e,"gitdir")),"");if(void 0===o)return;const i=(0,s.resolve)(e,o);if(".git"!==(0,s.basename)(i)||(0,Gs.$f)(i))return;const a=(0,s.dirname)(i);if(r&&bS(a))return;const c=await $S(i);if(void 0===c)return;const l=(0,s.dirname)(c);if(r&&bS(l))return;if(void 0!==n&&(u=DS(a,l)?[l]:[a,l],d=n.command,!(void 0!==(h=n.realWorkingDirectory)&&u.some((e=>(0,ts.BJ)(h,e)))||void 0!==d&&u.some((e=>{const t=(0,s.basename)(e);return t.length>0&&function(e,t){const r=CS?e.toLowerCase():e,n=CS?t.toLowerCase():t;let o=0;for(;;){const e=r.indexOf(n,o);if(-1===e)return!1;const t=0===e||_S.test(r[e-1]),s=e+n.length,i=s===r.length||_S.test(r[s]);if(t&&i)return!0;o=e+1}}(d,t)})))))return;var u,d,h;const p=await IS(i,c);return void 0!==p&&DS(p.commonDir,t)?l:void 0}async function xS(e,t){const r=await(0,xo.readdir)(e).catch(MS);return void 0===r?[]:r.sort().slice(0,t)}function PS(e,t){return t.some((t=>(0,ts.BJ)(t,e)))}async function RS(e){for(let t=e;;t=(0,s.dirname)(t)){if((0,Gs.$f)(t))return;const e=(0,s.join)(t,".git"),r=await(0,xo.lstat)(e).catch(MS);if(r?.isFile())return(await IS(e))?.commonDir;if(r?.isDirectory())return e;if(void 0!==r||(0,s.dirname)(t)===t)return}}async function IS(e,t){const r=AS(await TS(e),"gitdir: ");if(void 0===r)return;const n=await $S((0,s.resolve)((0,s.dirname)(e),r));if(void 0===n||"worktrees"!==(0,s.basename)((0,s.dirname)(n)))return;const o=(0,s.dirname)((0,s.dirname)(n));if(".git"!==(0,s.basename)(o))return;const i=AS(await TS((0,s.join)(n,"commondir")),"");if(void 0===i)return;const a=await $S((0,s.resolve)(n,i));if(void 0===a||!DS(a,o))return;const c=AS(await TS((0,s.join)(n,"gitdir")),"");if(void 0===c)return;const[l,u]=await Promise.all([$S((0,s.resolve)(n,c)),t??$S(e)]);return void 0!==l&&void 0!==u&&DS(l,u)?{commonDir:o,realDotGit:u}:void 0}async function TS(e){const t=await(0,xo.lstat)(e).catch(MS);if(void 0!==t&&t.isFile()&&!(t.size>4096))return(0,xo.readFile)(e,"utf8").catch(MS)}function AS(e,t){const r=e?.split("\n",1)[0]?.replace(/\r$/,"");if(void 0===r||!r.startsWith(t))return;const n=r.slice(t.length);return n.length>0&&!n.includes("\0")?n:void 0}async function $S(e){if(!(0,Gs.$f)(e))return(0,xo.realpath)(e).catch(MS)}function MS(e){const t=_c(e);if(void 0===t||t.startsWith("ERR_"))throw e}function DS(e,t){return CS?e.toLowerCase()===t.toLowerCase():e===t}function OS(e,t,r){return{resolvedPath:e,originalPath:t,resolution:r}}function FS(e){const t=_c(e);switch(t){case"ENOENT":return{status:"newFile"};case"EACCES":case"EPERM":return{status:"permissionDenied",errno:t};case"ELOOP":return{status:"symlinkLoop",errno:t};default:return{status:"unknownError",errno:t??"UNKNOWN",message:Cc(e)}}}async function NS(e,t){const r=(0,ts.o1)(e,t);try{return OS(await(0,xo.realpath)(r),r,{status:"resolved"})}catch(e){if("ENOENT"!==_c(e))return OS(r,r,FS(e));try{if((await(0,xo.lstat)(r)).isSymbolicLink()){let e=null;try{e=await(0,xo.readlink)(r)}catch{}return OS(r,r,{status:"danglingSymlink",symlinkTarget:e})}try{return OS(await(0,xo.realpath)(r),r,{status:"resolved"})}catch(e){if("ENOENT"!==_c(e))return OS(r,r,FS(e))}return OS(r,r,{status:"unknownError",errno:"ENOENT",message:"realpath returned ENOENT but lstat found a non-symlink entry"})}catch(e){return"ENOENT"===_c(e)?async function(e){let t=(0,s.dirname)(e);const r=[(0,s.basename)(e)];for(;(0,s.dirname)(t)!==t;){try{const n=await(0,xo.realpath)(t);return OS((0,s.join)(n,...r),e,{status:"newFile"})}catch(t){if("ENOENT"!==_c(t))return OS(e,e,FS(t))}r.unshift((0,s.basename)(t)),t=(0,s.dirname)(t)}return OS(e,e,{status:"newFile"})}(r):OS(r,r,FS(e))}}}function LS(e){return"resolved"===e.status||"newFile"===e.status}function jS(e,t){switch(t.status){case"resolved":case"newFile":return"";case"danglingSymlink":return`Write blocked: \`${e}\` is a dangling symlink${t.symlinkTarget?` (target: ${t.symlinkTarget})`:""}. Cannot verify it does not point to a protected file.`;case"permissionDenied":return`Write blocked: cannot verify \`${e}\` -- permission denied resolving symlinks (${t.errno}).`;case"symlinkLoop":return`Write blocked: \`${e}\` has a symlink loop (${t.errno}). Cannot verify target.`;case"unknownError":return`Write blocked: cannot verify \`${e}\` -- ${t.errno}: ${t.message}.`;default:return`Write blocked: unknown resolution status for \`${e}\`.`}}function US({realAbsolutePath:e,setting:t,resolvedWorkspaceRoots:r,resolvedAllowFolders:n,resolvedAllowGlobs:o}){return!("workspace"!==t.boundary||BS(e,r)||BS(e,n)||HS(e,t.allowPaths)||HS(e,o))}function BS(e,t){return t.some((t=>(0,ts.BJ)(e,t)))}function WS(e){return e.flatMap((e=>{const t=(0,ts.jl)(e.trim());return!t.includes("*")&&(0,s.isAbsolute)(t)?[(0,s.resolve)(t)]:[]}))}function HS(e,t){const r="win32"===process.platform?ts.oL:e=>e,n=r(e);return t.some((e=>{const t=(0,ts.jl)(e.trim());return!(!t.includes("*")&&(0,s.isAbsolute)(t))&&(0,ws.T)(r(t),n)}))}const qS={caffeinate:{flags:["-d","-i","-m","-s","-u"],valueOptions:["-t","-w"]},command:{flags:["-p"],valueOptions:[],lookupFlags:["-v","-V"]},env:{flags:["-","-i","-0","-v","--ignore-environment","--null","--debug"],valueOptions:["-u","-C","--unset","--chdir"],assignments:!0,directoryOptions:["-C","--chdir"]},nice:{flags:[],valueOptions:["-n","--adjustment"],numericOption:!0},nohup:{flags:[],valueOptions:[]},stdbuf:{flags:[],valueOptions:["-i","-o","-e","--input","--output","--error"]},time:{flags:["-p"],valueOptions:[]},timeout:{flags:["-f","-p","-v","--foreground","--preserve-status","--verbose"],valueOptions:["-k","-s","--kill-after","--signal"],operands:1},xargs:{flags:["-0","-o","-p","-r","-t","-x","--null","--open-tty","--interactive","--no-run-if-empty","--verbose","--exit","--show-limits"],valueOptions:["-a","-d","-E","-I","-J","-L","-n","-P","-R","-S","-s","--arg-file","--delimiter","--max-args","--max-procs","--max-chars","--process-slot-var"],attachedValueOptions:["-e","-i","-l","--eof","--replace","--max-lines"],readsArguments:!0}};function zS(e){const t=[];let r=!0,n=!1,o=e;for(;;){const e=qS[s.posix.basename(o.name)];if(void 0===e)return{command:o,wrapperForms:t,allowlistable:r,readsArguments:n};const i=GS(o.args,e);if("unreadable"===i)return{command:o,wrapperForms:t,allowlistable:!1,readsArguments:n};if("none"===i)return{command:o,wrapperForms:t,allowlistable:r,readsArguments:n};const[a,...c]=o.args.slice(i);if(void 0===a||!XS(a))return{command:o,wrapperForms:t,allowlistable:!1,readsArguments:n};(o.name.includes("/")||o.args.slice(0,i).some((t=>VS(t,e)||KS(t.value,e))))&&(r=!1),n||=!0===e.readsArguments,t.push(o.fullText.trim()),o=new fe.Pv({name:a.value,args:c,fullText:[a.value,...c.map((e=>e.value))].join(" ")})}}function GS(e,t){let r=0;for(;rt.startsWith("--")?e===t||e.startsWith(`${t}=`):/^-[^-]/.test(e)&&e.includes(t.slice(1))))}function JS(e,t,r){const n=e=>!0===r.attachedValueOptions?.includes(e);if(r.flags.includes(e)||n(e))return 1;if(e.startsWith("--")){const o=e.indexOf("=");if(-1!==o){const t=e.slice(0,o);return r.valueOptions.includes(t)||n(t)?1:void 0}if(!r.valueOptions.includes(e))return;return void 0===t?void 0:2}for(let o=1;o{const t=await NS(e);return LS(t.resolution)?t.resolvedPath:(0,ts.o1)(e)})))}function pk(e,t,r){return`${e} blocked: cannot verify ${t} \`${r}\` while resolving symlinks. This can happen when access is denied or the path contains a symlink loop.`}function fk(e){return[...new Set(e)]}function mk(){return{fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}}function gk({basePath:e,targetPath:t,pathModule:r}){const n=r.resolve(e),o=r.resolve(t),s=r.relative(n,o);return""===s||".."!==s&&!s.startsWith(`..${r.sep}`)&&!r.isAbsolute(s)}function wk(e){return">"===e||">>"===e||">|"===e||"&>"===e||"&>>"===e}function yk(e){return"<"!==e.operator&&"<&"!==e.operator}function vk(e){if(void 0===e||e.trim()!==e)return;const t=Number(e);return Number.isInteger(t)&&t>=0?t:void 0}function bk(e){return"<<"===e.operator&&"heredoc_redirect"===e.targetNodeType&&1===e.destinationFds.length&&0===Number(e.destinationFds[0])&&void 0!==e.targetText}function Sk(e,t){return!(/^=|[~*?[{(#^`]/.test(e)||"\\"!==t.sep&&e.includes("\\"))}function kk(e){return"word"===e.type||"number"===e.type?Sk(e.value,i)?e.value:void 0:"raw_string"===e.type||"string"===e.type&&!/[$`\\]/.test(e.value)?e.value.slice(1,-1):void 0}function _k({command:e,readsArguments:t}){if(!function(e){const t=e.replace(/["']/g,"");return[t,t.replace(/\\/g,"")].some((e=>/^tee(?:-object)?(?:\.exe)?$/i.test(e.slice(Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"))+1))))}(e.name))return[];const r=e.args.map(kk);return t?[...r,void 0]:r}const Ck=new Set(["cd","chdir","pushd"]),Ek=new Set(["popd","eval","source",".","trap","set-location","sl","push-location","pop-location"]);function xk(e){const t=e.replace(/["'\\]/g,"");return t.slice(t.lastIndexOf("/")+1).toLowerCase()}function Pk(e,t){return new fe.Pv({name:e,args:t,fullText:[e,...t.map((e=>e.value))].join(" ")})}function Rk(e){let t=e;for(;;){const e=xk(t.name);if("command"===e){const e=Pk("command",t.args),r=zS(e).command;if(r!==e){t=r;continue}const n=t.args[0]?.value;return void 0===n||"-v"===n||"-V"===n?t:"unreadable"}if("builtin"!==e)return t;const r="--"===t.args[0]?.value?t.args.slice(1):t.args,[n,...o]=r;if(void 0===n)return t;const s=kk(n);if(void 0===s||s.startsWith("-"))return"unreadable";t=Pk(s,o)}}function Ik(e,t){return!(!t.isAbsolute(e)||"/"!==t.sep&&/^[\\/]$/.test(t.parse(e).root))}async function Tk({parsingResult:e,workingDirectory:t,resolvePathForPermissions:r,pathModule:n}){const o=[t];for(const t of e.executableCommands.map(zS)){const e=Rk(t.command);if("unreadable"===e)return;const i=xk(e.name),a=e.args;if(Ek.has(i)||/^cd\.\./.test(s=i)||/^[a-z]:$/.test(s))return;if(!Ck.has(i))continue;const c=1===a.length&&void 0!==a[0]?kk(a[0]):void 0;if(void 0===c||!Ik(c,n))return;const l=await r(c);if(!LS(l.resolution))return;o.push(l.resolvedPath)}var s;return o}async function Ak({targetText:e,workingDirectory:t,workingDirectories:r,...n}){const o=Ik(e,n.pathModule)?[t]:r;if(void 0===o)return;let s;for(const t of o)if(s=await $k({...n,targetText:e,workingDirectory:t}),void 0===s)return;return s}async function $k({targetText:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:o,pathModule:s,tempPathOptions:i}){if(""!==s.parse(e).root&&!s.isAbsolute(e))return;const a=await o(e,t);if(!LS(a.resolution))return;const c=[];for(const e of r){const t=await o(e);LS(t.resolution)&&c.push(t.resolvedPath)}return await async function({targetPath:e,rootPaths:t,pathModule:r}){if(e.split(r.sep).some((e=>".git"===e.toLowerCase())))return!0;for(const r of t)if(await(0,No.OK)(e,r).catch((()=>!0)))return!0;return!1}({targetPath:a.resolvedPath,rootPaths:c,pathModule:s})?void 0:c.some((e=>gk({basePath:e,targetPath:a.resolvedPath,pathModule:s})))?"workspace-file":n&&!(0,No.dA)(a.originalPath)&&zk(a.resolvedPath,i)?"tmp-file":void 0}async function Mk({parsingResult:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n}){const s=await Tk({parsingResult:e,workingDirectory:t,resolvePathForPermissions:NS,pathModule:i});for(const a of e.executableCommands.map(zS).flatMap(_k))if("/dev/null"!==a&&(void 0===a||!await Ak({targetText:a,workingDirectory:t,workingDirectories:s,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:NS,pathModule:i,tempPathOptions:{platform:process.platform,env:process.env,pathModule:i,homeDirectory:(0,o.homedir)()}})))return!1;return!0}function Dk(e){return fk(e.map((e=>e.trim())).filter(Boolean))}function Ok(e){const t=e.name.trim();if(!t)return[];const r=e.arguments.map((e=>e.trim())).filter(Boolean),n=r.length>0?`${t} ${r.join(" ")}`:t,o=e.subcommandTokens.map((e=>e.trim())).filter(Boolean);if(0===o.length)return[n];const s=`${t} ${o.join(" ")}`;return s===n?[n]:[n,s]}function Fk(e,t){const r=t.trim();return!!r&&e.some((e=>e===r||e.startsWith(`${r} `)))}function Nk(e){const t=e.name.trim(),r=e.arguments.map((e=>e.trim())).filter(Boolean).map((e=>new fe.r6({type:"word",value:e})));return new fe.Pv({name:t,args:r,fullText:[t,...r.map((e=>e.value))].join(" ").trim()})}function Lk(e,t={}){return{type:e,...t}}function jk(e){return void 0!==e&&("deny"===e.default||void 0!==e.allow&&e.allow.length>0||void 0!==e.deny&&e.deny.length>0)}function Uk(...e){return e.filter((e=>void 0!==e)).join(" • ")}function Bk(e){const t=[];for(const r of e){const e=r.match(/^\s*Read\s*\((.*)\)\s*$/);e&&t.push((e[1]??"").trim())}return t}function Wk(e,t){if("workspace"===e&&void 0!==t)return t}const Hk={workspace:0,system:1};function qk(e){const t=e.match(/^\s*(Shell|Bash)\s*\((.*)\)\s*$/);if(!t)return null;const r=t[1];if("Shell"!==r&&"Bash"!==r)return null;const n=t[2]?.trim()??"",o=n.indexOf(":");return-1!==o?{shellType:r,fullPattern:n,commandPattern:n.slice(0,o).trim(),argsPattern:n.slice(o+1).trim()}:{shellType:r,fullPattern:n,commandPattern:n,argsPattern:null}}function zk(e,{platform:t,env:r,pathModule:n,homeDirectory:o}){if((0,No.dA)(e))return!1;if("win32"===t){const t=r.TEMP??r.TMP;if(t){const r=n.normalize(t).toLowerCase(),o=n.normalize(e).toLowerCase(),s=r.endsWith(n.sep)?r:r+n.sep;return o===r||o.startsWith(s)}return!1}const s=e=>{const r=n.normalize(e);return"darwin"!==t?r:"/tmp"===r||r.startsWith("/tmp/")||"/var"===r||r.startsWith("/var/")?`/private${r}`:r},i=s(e);return(void 0===o||!gk({basePath:s(o),targetPath:i,pathModule:n}))&&("darwin"===t?["/private/tmp/","/private/var/folders/"].some((e=>i.startsWith(e))):["/tmp/","/private/tmp/","/var/folders/","/private/var/folders/","/var/tmp/"].some((e=>i.startsWith(e))))}function Gk(e,t){if("insecure_none"===t.type)return!0;if("insecure_none"===e.type)return!1;const r=(0,No.$b)(e.networkPolicy),n=(0,No.$b)(t.networkPolicy);if(r&&!n)return!1;const o=(0,No._B)(e.networkPolicy),s=(0,No._B)(t.networkPolicy);if(o&&n&&!s)return!1;if("workspace_readonly"===e.type&&"workspace_readwrite"===t.type)return!0;if("workspace_readwrite"===e.type&&"workspace_readonly"===t.type)return!1;const i=e.readBoundary??"system",a=t.readBoundary??"system";return!(Hk[i]>Hk[a])}function Vk(e){return{wrapperForms:e.flatMap((e=>e.wrapperForms)),allowlistable:e.every((e=>e.allowlistable)),readsArguments:e.some((e=>e.readsArguments))}}function Kk(e){return[...e.wrapperForms,e.command.fullText.trim()].filter(Boolean)}class Jk{constructor(e,t,r,n,o){this.command=e,this.requestedPolicy=t,this.wrapperForms=o?.wrapperForms??[],this.allowlistable=o?.allowlistable??!0,this.readsArguments=o?.readsArguments??!1;const s=void 0!==r&&Gk(t,r);this.state=s?"preapproved":"approvable";const i=[e.fullText.trim()].filter(Boolean);this.matchForms=n&&n.length>0?[...n]:i}approveWithPolicy(e){"approvable"!==this.state&&"preapproved"!==this.state||!Gk(this.requestedPolicy,e)||(this.state="allowlisted")}deny(){this.state="denied"}isRunnable(){return"preapproved"===this.state||"allowlisted"===this.state}}function Zk(e){return e?.type??"undefined"}const Xk=["skills","skills-cursor","rules","plugins"],Qk=["assets","agent-notes","agent-tools","swarm-agents"];async function Yk(e,t,r){return e.shouldBlockFileRead?.(t,r)??e.shouldBlockRead(t,r)}function e_(e){const t=e.lastIndexOf("::mcpScope:");return-1===t?e:e.slice(0,t)}function t_({server:e,tool:t}){const r=e=>e.length>0&&e.length<=256&&!/[:*]/.test(e),n=e.trim().toLowerCase(),o=t.trim().toLowerCase();return r(n)&&r(o)?`${n}:${o}`:void 0}const r_=/^\s*Read\s*\((.*)\)\s*$/,n_=/^\s*Write\s*\((.*)\)\s*$/;class o_{constructor(e,t,r,n,i,a=!1,c){this.ignoreService=e,this.pendingDecisionStore=t,this.permissionsProvider=r,this.teamSettingsService=n,this.adminNetworkControlsEnabled=a,this.computerUseAppsAllowedForSession=[],this.rootDirectories=Array.isArray(i)?i:[i??process.cwd()],this.projectDir=c?.projectDir,this.perUserSandboxConfigPath=c?.perUserSandboxConfigPath??(0,s.join)((0,o.homedir)(),".cursor","sandbox.json"),this.mcpAllowlistLog=c?.mcpAllowlistLog,this.computerUse=c?.computerUse,this.computerUseAdminPolicy=c?.computerUseAdminPolicy,this.enforceMcpAdminToolLimits=c?.enforceMcpAdminToolLimits,this.onMcpAdminToolLimitCheck=c?.onMcpAdminToolLimitCheck}async shouldBlockRead(e,t={}){return this.shouldBlockReadInternal(e,t,!1)}async shouldBlockFileRead(e,t={}){return this.shouldBlockReadInternal(e,t,!0)}async getFileReadBoundaryBlocker(){const{perms:e,setting:t}=await this.readControlSetting(),r=e.deny.filter((e=>this.isPathEntry("Read",e))),n="workspace"===t.boundary&&"unrestricted"!==e.approvalMode;if(!n&&0===r.length)return;const[o,s,i]=n?await Promise.all([this.resolveWorkspaceReadRoots(e.userSandboxDataFolderName),this.resolvedReadAllowFolders(t.allowPaths),this.resolvedReadAllowGlobs(t.allowPaths)]):[[],[],[]],a=r.map((e=>this.compileReadDenyMatcher(e))),c=e=>a.some((t=>t(e)));return async(e,r)=>c(e)||c(r)||n&&US({realAbsolutePath:r,setting:t,resolvedWorkspaceRoots:o,resolvedAllowFolders:s,resolvedAllowGlobs:i})}async readControlSetting(){const e=await this.getPermissions(),{enabled:t,...r}=await this.adminReadControls(e);return{perms:e,setting:function(e){if(!e.enabled)return{boundary:"system",allowPaths:[],enforcedByAdmin:!1};const t="workspace"===e.admin.boundary,r=t||"workspace"===e.local.boundary?"workspace":"system",n=t?e.admin.allowPaths:[];return{boundary:r,allowPaths:t&&!1===e.admin.allowUserOverride?[...n]:[...new Set([...n,...e.local.allowPaths])],enforcedByAdmin:t}}({enabled:t,admin:r,local:{boundary:e.readBoundary,allowPaths:Bk(e.allow)}})}}async adminReadControls(e){const t=e.teamAdminPolicy,r=this.teamSettingsService.isReadControlEnabled?.()??!0;if(void 0!==t&&"unavailable"!==t){const e=await r;return"workspace"!==t.readBoundary?{enabled:e,boundary:void 0,allowPaths:[],allowUserOverride:void 0}:{enabled:e,boundary:"workspace",allowPaths:t.additionalReadPaths??[],allowUserOverride:t.allowUserOverrideReadPaths}}const[n,o]=await Promise.all([r,this.teamSettingsService.getSandboxingControls()]);return{enabled:n,boundary:o.readBoundary,allowPaths:o.readAllowlistPaths??[],allowUserOverride:o.allowUserOverrideReadAllowlist}}resolvedReadAllowFolders(e){return hk([...WS(e),...(0,No.r5)()])}async resolvedReadAllowGlobs(e){const t=function(e){return e.flatMap((e=>{const t=(0,ts.jl)(e.trim()),r=t.indexOf("*");if(r<0||!(0,s.isAbsolute)(t))return[];const n="win32"===process.platform?Math.max(t.lastIndexOf("/",r),t.lastIndexOf("\\",r)):t.lastIndexOf("/",r);return n>=(0,s.parse)(t).root.length?[{folder:t.slice(0,n),rest:t.slice(n)}]:[]}))}(e),r=await hk(t.map((({folder:e})=>e)));return t.map((({rest:e},t)=>function(e,t,r={parse:s.parse}){return r.parse(e).root===e&&/[\\/]$/.test(e)?`${e}${t.slice(1)}`:`${e}${t}`}(r[t],e)))}async resolveWorkspaceReadRoots(e){const t=(0,s.join)((0,o.homedir)(),void 0!==e&&e.length>0?e:".cursor"),r=[...this.rootDirectories.map((e=>(0,s.join)(t,"projects",(0,_o.r_)(e)))),...Xk.map((e=>(0,s.join)(t,e)))],n=this.rootDirectories.flatMap((e=>(0,No.W1)(e)??[]));return hk([...this.rootDirectories,...r,...n,...void 0===this.projectDir?[]:[this.projectDir]])}async shouldBlockReadInternal(e,{cursorIgnoreChecked:t=!1},r){const n=(0,ts.o1)(e),o=await xc(n);if(null===o)return{type:"unsafeResolution",message:pk("Read","path",n)};if(await this.ignoreService.isRepoBlocked(o))return{type:"adminBlock",source:"Team repo blocklist"};if(await this.isPathExplicitlyDenied("Read",n))return{type:"permissionsConfig"};if(!t&&!bS(o)&&!vS(o,{dataFolderName:(await this.getPermissions()).userSandboxDataFolderName})&&await this.ignoreService.isCursorIgnored(o))return{type:"cursorIgnore"};if(r){const e=await this.shouldBlockReadForBoundary(o);if(e)return e}return!1}async shouldBlockReadForBoundary(e){const{perms:t,setting:r}=await this.readControlSetting();if("workspace"!==r.boundary||"unrestricted"===t.approvalMode)return!1;const n=await this.resolveWorkspaceReadRoots(t.userSandboxDataFolderName);if(BS(e,n))return!1;const[o,s]=await Promise.all([this.resolvedReadAllowFolders(r.allowPaths),this.resolvedReadAllowGlobs(r.allowPaths)]);return!!US({realAbsolutePath:e,setting:r,resolvedWorkspaceRoots:n,resolvedAllowFolders:o,resolvedAllowGlobs:s})&&{type:"needsApproval",approvalReason:r.enforcedByAdmin?"This reads a file outside your workspace and requires approval under your team's read policy.":"This reads a file outside your workspace.",approvalDetails:{type:"fileRead",path:e}}}async isProjectDirInternalPath(e,t){if(void 0===this.projectDir)return!1;const r=await NS(this.projectDir);return!!LS(r.resolution)&&kS(r.resolvedPath,e,t)}async isFreelyWritableOutsideWorkspace(e,t){return function(e){return zk(e,{platform:process.platform,env:process.env,pathModule:i,homeDirectory:(0,o.homedir)()})}(e)||SS(e,Qk,{dataFolderName:t})||await this.isProjectDirInternalPath(e,Qk)}async shouldBlockWrite(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{tk(n,(0,D.VI)(e.withName("InteractivePermissionsService.shouldBlockWrite")),!1).ctx;const i=await NS(t);if(!LS(i.resolution))return{type:"unsafeResolution",message:jS(i.originalPath,i.resolution)};const a=i.resolvedPath,c=a;if(await this.ignoreService.isRepoBlocked(c))return{type:"adminBlock",source:"Team repo blocklist"};if(await this.isPathExplicitlyDenied("Write",a))return{type:"permissionsConfig"};const l=i.originalPath.split(s.sep).pop()?.toLowerCase()??"",u=a.split(s.sep).pop()?.toLowerCase()??"";if(".cursorignore"===l||".cursorignore"===u)return{type:"permissionsConfig"};if((0,No.dA)(i.originalPath)||(0,No.dA)(a))return{type:"permissionsConfig"};const d=await this.getPermissions();if(!bS(c)&&!vS(c,{dataFolderName:d.userSandboxDataFolderName})&&await this.ignoreService.isCursorIgnored(c))return{type:"cursorIgnore"};if("workspace_readonly"===d.userConfiguredPolicy.type)return{type:"permissionsConfig",isReadonly:!0};if(await this.isPathExplicitlyAllowed("Write",a))return!1;if("unrestricted"===d.approvalMode)return!1;const h=async()=>{let e,t,n="";try{n=await Bi(a),e=!1}catch{e=!0}if(e)t=r;else{const e=e=>e.endsWith("\n")?e:`${e}\n`,{hunks:o}=(0,dS.YB)("a","b",e(n),e(r),"","",{context:2});t=o.map((e=>e.lines.map((e=>e.length>0?`${e[0]} ${e.slice(1)}`:e)).join("\n"))).join("\n...\n")}return{isNewFile:e,diffString:t}};let p;const f=[];for(const e of this.rootDirectories){const t=await NS(e);if(LS(t.resolution)){if((0,ts.BJ)(a,t.resolvedPath)){p=t.resolvedPath;break}f.push(t.resolvedPath)}}const m=void 0===p?await async function(e,t,r={}){if(0===t.length)return;let n;for(let o=(0,s.dirname)(e);;o=(0,s.dirname)(o)){if((0,Gs.$f)(o))return;const e=(0,s.join)(o,".git"),i=await(0,xo.lstat)(e).catch(MS);if(i?.isFile()){const s=await IS(e);if(void 0!==s){const{commonDir:e}=s;if(PS(o,t))return;if(t.some((t=>(0,ts.BJ)(e,t))))return{root:o,commonDir:e};if(!await(r.isUntrustedExternalGitDir?.(e))&&(await(n??=Promise.all(t.map((e=>RS(e)))),n)).some((t=>void 0!==t&&DS(t,e))))return{root:o,commonDir:e}}}if((0,s.dirname)(o)===o)return}}(a,f,{isUntrustedExternalGitDir:e=>this.isFreelyWritableOutsideWorkspace(e,d.userSandboxDataFolderName)}):void 0;let g=!1;const w=p??m?.root;if(void 0!==w){const e=(0,s.relative)(w,a),t=e.split(s.sep).map((e=>"win32"===process.platform&&e.includes(":")?e.split(":")[0]:e));if(g=function(e){const t=e.replace(/\\/g,"/");return/(^|\/)\.cursor\/debug(?:-[a-zA-Z0-9-]+)?\.log$/i.test(t)}(e),!g){const e=await this.checkCursorFileProtection(t);if(e)return e}if("win32"===process.platform&&t.some((e=>e.includes("~")))){const{isNewFile:e,diffString:r}=await h();return{type:"needsApproval",approvalReason:`Protected config file: ${t[t.length-1]??""}`,approvalDetails:{type:"fileEdit",isNewFile:e,diffString:r,blockReason:"protectedConfig"}}}if(await(0,No.OK)(a,w)){const e=t[t.length-1]?.toLowerCase()??"",{isNewFile:r,diffString:n}=await h();return{type:"needsApproval",approvalReason:`Protected config file: ${e}`,approvalDetails:{type:"fileEdit",isNewFile:r,diffString:n,blockReason:"protectedConfig"}}}}if(void 0===p&&(void 0===m||"workspace"===(await this.readControlSetting()).setting.boundary)){if(await this.isFreelyWritableOutsideWorkspace(a,d.userSandboxDataFolderName))return!1;const e=`${(0,o.homedir)()}${s.sep}.cursor${s.sep}`;if(a.startsWith(e)){const e=a.split(s.sep).pop()?.toLowerCase()??"";if(e.endsWith(".md")||e.endsWith(".mdc")||".cursorrules"===e)return!1}const{isNewFile:t,diffString:r}=await h();return{type:"needsApproval",approvalReason:"Out of workspace",approvalDetails:{type:"fileEdit",isNewFile:t,diffString:r,blockReason:"outOfWorkspace"}}}if(g)return!1;if(!0===d.promptWorkspaceWrites){const{isNewFile:e,diffString:t}=await h();return{type:"needsApproval",approvalReason:"Workspace write",approvalDetails:{type:"fileEdit",isNewFile:e,diffString:t,blockReason:"workspaceWrite"}}}return!1}catch(e){n.error=e,n.hasError=!0}finally{rk(n)}}async shouldEnforceShellInvariantBlocks(e,t,r){const n=await this.getAdminCommandDenylistBlock(e,{command:t.command,parsingResult:t.parsingResult,toolCallId:t.toolCallId});if(void 0!==n)return{kind:"block",reason:n};const o=await xc(t.workingDirectory);if(null===o){if(!0!==t.skipUnsafeWorkingDirectoryBlock)return{kind:"block",reason:{type:"unsafeResolution",message:pk("Command","working directory",t.workingDirectory)}}}else if(await this.ignoreService.isRepoBlocked(o))return{kind:"block",reason:{type:"adminBlock",source:"Team repo blocklist"}};const s=(await this.getPermissions()).userConfiguredPolicy,i=r??s;return"workspace_readonly"===s.type&&"workspace_readonly"!==i.type?{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}}:void 0!==r?{kind:"allow",policy:r}:!0!==t.resolveSkippedApprovalPolicy||"workspace_readonly"!==s.type?{kind:"allow",policy:void 0}:{kind:"allow",policy:await this.applyServerAndAdminPolicies({...s,skipStatsigDefaults:s.skipStatsigDefaults??!0})}}async shouldBlockShellCommand(e,t,r,n){const o="insecure_none"===n?.type,s=await this.shouldEnforceShellInvariantBlocks(e,{workingDirectory:r.workingDirectory,command:t,parsingResult:r.parsingResult,toolCallId:r.toolCallId},n);if("block"===s.kind)return s;const i=await this.getPermissions(),a=i.approvalMode,c="unrestricted"===a,l=i.userConfiguredPolicy,u=!i.dashboardTerminalAllowlistOverriddenByPermissionsFile;if(nk.info(e,"Shell permissions: evaluating shell command",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:Zk(l),requestedPolicyType:Zk(n),effectiveRequestedPolicyType:Zk(n??l),smartAllowlistEnabled:!0===i.smartAllowlistEnabled,hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId,hookForcesPrompt:Do(r.hookApprovalRequirement),classifierClassificationFailed:!0===r.classifierResult?.classificationFailed,classifierCommandCount:r.classifierResult?.commands.length??0,parserCommandCount:r.parsingResult.executableCommands.length,parsingFailed:r.parsingResult.parsingFailed,hasRedirects:r.parsingResult.hasRedirects,commandLength:t.length}),await this.shouldPromptForEmptyPlainShellAllowlist(t,i))return nk.info(e,"Shell permissions: prompting for empty allowlist",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:Zk(l),requestedPolicyType:Zk(n),hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId}),await this.requestApprovalForEmptyShellAllowlist(t,r,n??l);const d=r.parsingResult.executableCommands,h=r.parsingResult.parsingFailed,p=r.classifierResult,f=r.smartModeApprovalReason,m=r.smartModeApprovalRequestId,g=void 0!==p&&!p.classificationFailed&&p.commands.length>0?p:void 0,w="allowlist"===a&&i.smartAllowlistEnabled?g?.commands:void 0,y=void 0!==w,v=d.map(zS),b=w?w.map(Nk):v.map((e=>e.command)),S=void 0!==w?w.map(Ok):b.map((e=>[e.fullText.trim()].filter(Boolean))),k=void 0!==g?g.commands.map(Ok):v.map(Kk);if(n||(n=i.userConfiguredPolicy),"insecure_none"!==n.type&&void 0===n.skipStatsigDefaults&&"insecure_none"!==l.type&&(n={...n,skipStatsigDefaults:l.skipStatsigDefaults??!0}),"insecure_none"!==l.type&&(0,No.$b)(l.networkPolicy)&&"insecure_none"!==n.type&&!(0,No._B)(n.networkPolicy)){const e=l.networkPolicy,t=n.networkPolicy?.allow;if(void 0!==t&&t.length>0&&e){const r=[...new Set([...e.allow??[],...t])];n={...n,networkPolicy:{...e,allow:r}}}else n={...n,networkPolicy:e}}let _;n=function({requestedPolicy:e,userConfiguredPolicy:t}){if("insecure_none"===e.type||"insecure_none"===t.type)return e;const r=(0,No.XX)(e.readBoundary,t.readBoundary),n="workspace"===r?(0,No.wG)(Wk(e.readBoundary,e.additionalReadPaths),Wk(t.readBoundary,t.additionalReadPaths)):void 0;return{...e,readBoundary:r,additionalReadPaths:n}}({requestedPolicy:n,userConfiguredPolicy:l}),p&&nk.info(e,"Smart allowlist: classifier result received",{classificationFailed:p.classificationFailed,suggestedSandboxMode:p.suggestedSandboxMode,commandCount:p.commands.length,suggestedAllowlistEntryCount:p.commands.filter((e=>e.suggestedAllowlistEntry)).length});const C=[],E=[];let x=[],P=[],R=[];const I=Dk(i.smartAllowlistDenylist??[]);if(I.length>0){P=[];const t=k.map((e=>e[0]??""));for(let e=0;eFk(r,e)))){const r=t[e];r&&P.push(r)}}P.length>0&&(nk.info(e,"Command blocklist: commands require approval",{count:P.length}),C.push(`In blocklist: ${P.join(", ")}`))}if(y&&p){const t=S.map((e=>e[0]??"")),r=i.allow.filter((e=>this.isShellEntry(e)));nk.info(e,"Smart allowlist: checking commands against lists",{commandCount:t.length,allowlistCount:r.length,commandBlocklistCount:I.length});const n=S.map((e=>r.some((t=>e.some((e=>this.matchesShell(t,e))))))),o=n.every(Boolean),s=[];for(let e=0;efunction(e){const t=e.name.trim();if(!t)return[];if(Gb(t))return[];const r=e.subcommandTokens.map((e=>e.trim())).filter(Boolean),n=e.arguments.map((e=>e.trim())).filter(Boolean),o=[t],s=[t];for(const e of r)s.push(e),o.push(s.join(" "));const i=[t,...n].join(" ");return o.includes(i)||o.push(i),Dk(o)}(e)))),R=s.map((e=>e.suggestedAllowlistEntry)).filter((e=>"string"==typeof e)).filter((e=>x.includes(e))),x.length>0){const e=Zb(x,R),t=e.length>0?e.join(", "):x.join(", ");E.push(`Not in allowlist: ${t}`)}_=o&&0===P.length,_&&nk.info(e,"Smart allowlist: all commands in allowlist, will check security",{commandCount:t.length})}const T="ask-every-time"===a||"insecure_none"===n.type&&"allowlist"===a?void 0:l,A=Vk(v),$=b.map(((e,t)=>new Jk(e,n,T,S[t],y?A:v[t])));if((0===b.length||h&&!y)&&!c){nk.info(e,"Shell permissions: prompting after parser miss",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:Zk(n),userConfiguredPolicyType:Zk(l),isSmartAllowlistActive:y,parsingFailed:h,parserCommandCount:b.length,hasSmartModeApprovalReason:void 0!==f,hasSmartModeApprovalRequestId:void 0!==m});const o={type:Bw.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:Uk(f??(h?"Parser failed to parse command (possible bypass)":"Parser found no commands (possible bypass)"),await this.adminNetworkLimitReason(n)),isSandboxAvailable:!1,isSandboxEnabled:!1,canAllowlist:!1,notAllowedCommands:[],smartModeApprovalReason:f,smartModeApprovalRequestId:m}};r.onApprovalRequested?.();const s=await this.pendingDecisionStore.requestApproval(o);return s.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(n)}:{kind:"block",reason:{type:"userRejected",reason:s.reason}}}if(await this.hasHardDeny(e,$))return{kind:"block",reason:{type:"permissionsConfig",..."workspace_readonly"===l.type?{isReadonly:!0}:{}}};const{allowlistOfferSafe:M,redirectsAllowlistSafe:D}=await this.computeRedirectAllowlistSafety(r.parsingResult,r.workingDirectory,"insecure_none"===l.type||"workspace"!==l.readBoundary),O=await this.teamSettingsService.getAutoRunControls(),F={type:"insecure_none"};for(const e of $)await this.cmdIsAllowedByAllowlist(e,{redirectsAllowlistSafe:D,autoRunControls:O,applyTeamAllowlist:u})&&e.approveWithPolicy(F);for(const e of $)O&&this.isInTeamBlocklist(O,e)&&e.deny();const N=await this.teamSettingsService.getDeleteFileProtection();if(N)for(const e of $)"rm"===e.command.name&&e.deny();const L=this.buildShellApprovalDecisionFacts({commands:$,autoRunControls:O,shouldApplyTeamShellAllowlist:u,deleteProtectionEnabled:N,softDenylistedCommands:P});if("workspace_readonly"===l.type&&"workspace_readonly"!==n.type)return nk.info(e,"Shell permissions: blocked by readonly mode"),{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}};const j=Do(r.hookApprovalRequirement),U=r.hookApprovalRequirement?.reason,B=o&&"insecure_none"!==l.type&&function(e){if(/\brimraf\b/i.test(e))return!0;for(const t of e.replace(/[\\`^]\r?\n/g," ").split(/(?|])&|\|\||[;\n]/)){let e=!1;for(const r of t.split("|")){if(e&&QS.test(r)||ek(r,QS,YS)||ek(r,/(?0&&(L.hasSecurityDenies||L.hasSoftDenies||!L.allCommandsRunnable);if(void 0!==f&&G.push(f),j&&(V||G.push(U?`Hook requested approval: ${U}`:"Hook requested approval"),z=!1),B&&(V||G.push("Recursive delete outside the sandbox"),z=!1),C.length>0&&(V||G.push(...C),z=!1),!V)if(y&&E.length>0)G.push(...E);else if(L.unapprovedCommands.length>0){const e=Zb(this.generateAllowlistPatterns(L.unapprovedCommands)),t=e.length>0?e.join(", "):L.unapprovedCommands.map((e=>e.command.fullText)).join(", ");G.push(`Not in allowlist: ${t}`)}if(L.hasSecurityDenies&&(V||(L.rmDeniedByDeleteProtection.length>0&&G.push("Delete protection is enabled"),L.teamBlocklistedCommands.length>0&&G.push(`In team blocklist: ${L.teamBlocklistedCommands.map((e=>e.command.name)).join(", ")}`)),z=!1),K){const t=L.notInTeamAllowlist.map((e=>e.command.fullText)).join(", ");nk.info(e,"Shell permissions: commands not in team allowlist",{commandCount:L.notInTeamAllowlist.length}),V||G.push(`Not in team allowlist: ${t}`),z=!1}const J="unrestricted"===a&&"workspace_readonly"===n.type,Z="unrestricted"!==a||J?n:{type:"insecure_none"},X=Uk(...G,await this.adminNetworkLimitReason(Z)),Q=[];if(z){const e=void 0!==f?$.filter((e=>"allowlisted"!==e.state)):L.unapprovedCommands;Q.push(...this.generateAllowlistPatterns(e))}const Y=y&&E.length>0,ee=Y?x:Q,te=Y&&R.length>0?R:void 0,re="insecure_none"!==n.type&&"insecure_none"!==l.type,ne="insecure_none"!==n.type,oe=[void 0!==f?"smart_mode_approval":void 0,j?"hook_forces_prompt":void 0,B?"unsandboxed_recursive_delete":void 0,C.length>0?"command_blocklist":void 0,y&&E.length>0?"smart_allowlist_miss":void 0,L.unapprovedCommands.length>0?"unapproved_commands":void 0,L.hasSecurityDenies?"security_denies":void 0,K?"team_allowlist_miss":void 0].filter((e=>void 0!==e));nk.info(e,"Shell permissions: requesting shell approval",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:Zk(n),userConfiguredPolicyType:Zk(l),isSandboxAvailable:re,isSandboxEnabled:ne,canAllowlist:z,isSmartAllowlistActive:y,hasSmartModeApprovalReason:void 0!==f,hasSmartModeApprovalRequestId:void 0!==m,hookForcesPrompt:j,approvalReasonTypes:oe,commandCount:$.length,unapprovedCommandCount:L.unapprovedCommands.length,deniedCommandCount:L.deniedCommands.length,notInTeamAllowlistCount:L.notInTeamAllowlist.length,notAllowedCommandCount:ee.length,suggestedAllowlistEntryCount:te?.length??0,allCommandsRunnable:L.allCommandsRunnable,allCommandsAllowlisted:L.allCommandsAllowlisted,allCommandsPreapproved:L.allCommandsPreapproved,hasSecurityDenies:L.hasSecurityDenies,hasSoftDenies:L.hasSoftDenies});const se={type:Bw.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:X,isSandboxAvailable:"allowlist"===a&&re,isSandboxEnabled:!("allowlist"!==a&&!J)&&ne,canAllowlist:z,notAllowedCommands:ee,suggestedAllowlistEntries:te,smartModeApprovalReason:f,smartModeApprovalRequestId:m}};r.onApprovalRequested?.();const ie=await this.pendingDecisionStore.requestApproval(se);return ie.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(Z)}:{kind:"block",reason:{type:"userRejected",reason:ie.reason}}}async isShellCommandFullyAllowlisted(e,t,r){const n=e.withName("InteractivePermissionsService.isShellCommandFullyAllowlisted"),o=await this.getPermissions(),s=!o.dashboardTerminalAllowlistOverriddenByPermissionsFile;if("allowlist"!==o.approvalMode)return!1;if("workspace_readonly"===o.userConfiguredPolicy.type)return!1;const{redirectsAllowlistSafe:i}=await this.computeRedirectAllowlistSafety(r.parsingResult,r.workingDirectory,"insecure_none"===o.userConfiguredPolicy.type||"workspace"!==o.userConfiguredPolicy.readBoundary);if(!i)return!1;const a=r.classifierResult,c=void 0!==a&&!a.classificationFailed&&a.commands.length>0?a:void 0,l=(o.smartAllowlistEnabled??!1)&&void 0!==c;if(r.parsingResult.parsingFailed&&!l)return!1;const u=r.parsingResult.executableCommands.map(zS),d=l?c.commands.map(Nk):u.map((e=>e.command));if(0===d.length)return!1;const h=l?c.commands.map(Ok):d.map((e=>[e.fullText.trim()].filter(Boolean))),p=void 0!==c?c.commands.map(Ok):u.map(Kk),f={type:"insecure_none"},m=Vk(u),g=d.map(((e,t)=>new Jk(e,f,void 0,h[t],l?m:u[t])));if(await this.hasHardDeny(n,g))return!1;const w=Dk(o.smartAllowlistDenylist??[]);if(w.length>0)for(const e of p)if(e&&0!==e.length&&w.some((t=>Fk(e,t))))return!1;if(await this.teamSettingsService.getDeleteFileProtection()&&g.some((e=>"rm"===e.command.name)))return!1;const y=await this.teamSettingsService.getAutoRunControls();if(void 0!==y&&g.some((e=>this.isInTeamBlocklist(y,e))))return!1;for(const e of g)if(!await this.cmdIsAllowedByAllowlist(e,{redirectsAllowlistSafe:i,autoRunControls:y,applyTeamAllowlist:s}))return!1;return!0}async applyServerAndAdminPolicies(e){if("insecure_none"===e.type)return e;const t=this.rootDirectories.at(0)??(0,o.homedir)(),{userSandboxDataFolderName:r,teamAdminPolicy:n}=await this.getPermissions(),i=void 0!==r&&r.length>0?(0,s.join)((0,o.homedir)(),r,"sandbox.json"):this.perUserSandboxConfigPath,a=await this.foldPerUserFilePolicy(e,i),c=a.skipStatsigDefaults?a:await this.applyStatsigDefaults(a),l=await this.loadPerRepoFilePolicy(c,t),u=await this.resolveTeamAdminLayer(n);if("unavailable"===u){const{policy:e}=await(0,No.resolveSandboxPolicyForWorkspace)(t,{perUser:c,perRepo:l});return function(e){return"insecure_none"===e.type?e:{...e,networkPolicy:(0,No.Po)(),readBoundary:"workspace",additionalReadPaths:[]}}(e)}const d=void 0===u?void 0:Lk(c.type,u),h=(0,No._B)(e.networkPolicy)&&!jk(d?.networkPolicy),{policy:p}=await(0,No.resolveSandboxPolicyForWorkspace)(t,{perUser:c,perRepo:l,teamAdmin:d});return h?{...p,networkPolicy:(0,No.T6)()}:p}async resolveLinkedWorktreeSandboxGrants(e,t){if("workspace_readwrite"!==e.type||"workspace"===e.readBoundary)return;const{perms:r,setting:n}=await this.readControlSetting();if("workspace"===n.boundary||"unavailable"===r.teamAdminPolicy)return;const i=r.userSandboxDataFolderName;if(void 0===e.readBoundary){const t=this.rootDirectories.at(0)??(0,o.homedir)(),n=void 0!==i&&i.length>0?(0,s.join)((0,o.homedir)(),i,"sandbox.json"):this.perUserSandboxConfigPath,a="readBoundary"in r.userConfiguredPolicy&&void 0!==r.userConfiguredPolicy.readBoundary?{...e,readBoundary:r.userConfiguredPolicy.readBoundary}:e,c=await this.foldPerUserFilePolicy(a,n),l=await this.loadPerRepoFilePolicy(c,t);if("workspace"===(l?.readBoundary??c.readBoundary))return}const a=[];for(const e of this.rootDirectories){if((0,Gs.$f)(e))continue;const t=await NS(e);LS(t.resolution)&&!bS(t.resolvedPath)&&a.push(t.resolvedPath)}if(0===a.length)return;let c;if(!(0,Gs.$f)(t.workingDirectory)){const e=await NS(t.workingDirectory);LS(e.resolution)&&(c=e.resolvedPath)}return async function(e,t={}){if(0===e.length)return;const r=await Promise.all(e.map((e=>RS(e)))),n=[];for(const o of r)void 0===o||n.some((e=>DS(e,o)))||!e.some((e=>(0,ts.BJ)(o,e)))&&await(t.isUntrustedExternalGitDir?.(o))||n.push(o);if(0===n.length)return;const o=[],i=[],a=void 0!==t.command||void 0!==t.realWorkingDirectory;for(const r of n){const n=await xS((0,s.join)(r,"worktrees"),256),c=await(0,Nr.PH)(n,(e=>ES((0,s.join)(r,"worktrees",e),r,!0===t.excludeAgentWorktrees,a?{command:t.command,realWorkingDirectory:t.realWorkingDirectory}:void 0)),{max:16});let l=!1;for(const r of c){if(o.length>=16)break;void 0===r||o.some((e=>DS(e,r)))||e.some((e=>(0,ts.BJ)(r,e)))||PS(r,e)||await(t.isExcludedWorktreeRoot?.(r))||(o.push(r),l=!0)}l&&i.push(r)}return 0===o.length?void 0:{roots:o,commonDirs:i}}(a,{command:t.command,realWorkingDirectory:c,excludeAgentWorktrees:!0,isUntrustedExternalGitDir:e=>this.isFreelyWritableOutsideWorkspace(e,i),isExcludedWorktreeRoot:async e=>await this.isFreelyWritableOutsideWorkspace(e,i)||await this.ignoreService.isRepoBlocked(e)})}async foldPerUserFilePolicy(e,t=this.perUserSandboxConfigPath){const r=await(0,No.tv)(t,(0,o.homedir)());if(!r||"insecure_none"===r.type)return e;let n=(0,No.fZ)(r.networkPolicy,e.networkPolicy);n&&void 0!==e.networkPolicy?.default&&(n={...n,default:e.networkPolicy.default});const s=(0,No.s9)(r.additionalReadonlyPaths,e.additionalReadonlyPaths),i={...e,networkPolicy:n,additionalReadonlyPaths:s.length>0?s:void 0,readBoundary:r.readBoundary??e.readBoundary,additionalReadPaths:void 0!==r.additionalReadPaths?r.additionalReadPaths:e.additionalReadPaths,privateTmp:r.privateTmp??e.privateTmp};if("workspace_readwrite"===e.type&&"workspace_readwrite"===r.type){const t=(0,No.s9)(r.additionalReadwritePaths,e.additionalReadwritePaths);return{...i,additionalReadwritePaths:t.length>0?t:void 0}}return i}async applyStatsigDefaults(e){const t=await this.teamSettingsService.getDefaultNetworkAllowlist();if(!t.available||0===t.allowlist.length)return e;if((0,No._B)(e.networkPolicy))return e;const r={default:"deny",allow:fk(t.allowlist)};return{...e,networkPolicy:(0,No.fZ)(e.networkPolicy,r)}}async loadPerRepoFilePolicy(e,t){const r=await(0,No.tv)((0,s.join)(t,".cursor","sandbox.json"),t);if(r){if("1"===process.env[Yv.K4]){const n=(0,No.fB)({perUser:e,perRepo:r},t).perRepo;return"insecure_none"===n?.type?void 0:n}if("insecure_none"!==r.type)return r.type!==e.type?Lk(e.type,{networkPolicy:r.networkPolicy,additionalReadonlyPaths:r.additionalReadonlyPaths,..."additionalReadwritePaths"in r?{additionalReadwritePaths:r.additionalReadwritePaths}:{},disableTmpWrite:r.disableTmpWrite,networkPolicyStrict:r.networkPolicyStrict,readBoundary:r.readBoundary,additionalReadPaths:r.additionalReadPaths,privateTmp:r.privateTmp}):r}}async resolveTeamAdminLayer(e){return void 0!==e?"unavailable"===e?"unavailable":"workspace"===(t=e).readBoundary?t:void 0===t.networkPolicy?{}:{networkPolicy:t.networkPolicy}:async function(e){const{teamSettings:t}=e,r=e.adminNetworkControlsEnabled?(i=await t.getNetworkAccessControls()).available?0!==i.allowlist.length||0!==i.denylist.length?{...i.allowlist.length>0?{default:"deny",allow:fk(i.allowlist)}:{},...i.denylist.length>0?{deny:fk(i.denylist)}:{}}:void 0:(0,No.Po)():void 0,[n,o]=await Promise.all([t.isReadControlEnabled?.()??!0,t.getSandboxingControls()]),s=void 0===r?{}:{networkPolicy:r};var i;return n&&"workspace"===o.readBoundary?{...s,readBoundary:"workspace",additionalReadPaths:o.readAllowlistPaths??[],allowUserOverrideReadPaths:o.allowUserOverrideReadAllowlist}:void 0===r?void 0:s}({teamSettings:this.teamSettingsService,adminNetworkControlsEnabled:this.adminNetworkControlsEnabled});var t}async adminNetworkLimitReason(e){if("insecure_none"===e.type||!(0,No._B)(e.networkPolicy))return;const{teamAdminPolicy:t}=await this.getPermissions(),r=await this.resolveTeamAdminLayer(t);return function(e){if(jk(e))return void 0!==e.allow&&e.allow.length>0?"Network access limited to your admin's allowlist":"deny"===e.default?"Network access limited by your admin":"Network access excludes domains your admin blocks"}("unavailable"===r?(0,No.Po)():r?.networkPolicy)}async getAdminReadSandboxing(){const e=await this.getPermissions();if("unavailable"===e.teamAdminPolicy)return{readBoundary:"workspace"};const{enabled:t,boundary:r}=await this.adminReadControls(e);return{readBoundary:t&&"workspace"===r?"workspace":void 0}}async isInShellAllowlist(e){if(!e.allowlistable)return!1;const t=await this.getPermissions(),r=e.readsArguments?e.matchForms.map((e=>`${e} \0`)):e.matchForms;return t.allow.some((e=>this.isShellEntry(e)&&r.some((t=>this.matchesShell(e,t)))))}isInTeamBlocklist(e,t){const r=[...t.wrapperForms,t.command.fullText];return e.blocked.some((e=>r.some((t=>this.matchesAutoRunCommand(t,e)))))}isInTeamAllowlist(e,t){return!!t.allowlistable&&e.allowed.some((e=>this.matchesAutoRunCommand(t.command.fullText,e)))}async computeRedirectAllowlistSafety(e,t,r){const n=e.hasRedirects,s=e.parsingFailed,a=!0===e.allRedirectsAreDevNull,c=!(!n||a||s)&&await async function({parsingResult:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n=!0,resolvePathForPermissions:s=NS,pathModule:a=i,tempPathOptions:c={platform:process.platform,env:process.env,pathModule:a,homeDirectory:(0,o.homedir)()}}){if(!e.hasRedirects)return!0;const l=e.redirects;if(0===l.length)return!1;const u=e.executableCommands.length>1,d=await Tk({parsingResult:e,workingDirectory:t,resolvePathForPermissions:s,pathModule:a}),h=mk();for(const e of l){if(bk(e))continue;const o=u?mk():h,{operator:i,targetText:l}=e,f=e.destinationFds;if(">&"===i){const e=vk(l),t=void 0===e?void 0:o.fdTargets.get(e);if("original-stdout"!==(p=t)&&"original-stderr"!==p&&"dev-null"!==p&&"workspace-file"!==p&&"tmp-file"!==p){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}for(const e of f)o.fdTargets.set(e,t);continue}if("<&"===i){const e=vk(l),t=void 0===e?void 0:o.fdTargets.get(e);if("dev-null"!==t){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}for(const e of f)o.fdTargets.set(e,t);continue}if("/dev/null"===l){for(const e of f)o.fdTargets.set(e,"dev-null");continue}if(!wk(i)||void 0===l||"word"===e.targetNodeType&&!Sk(l,a)){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}const m=await Ak({targetText:l,workingDirectory:t,workingDirectories:d,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:s,pathModule:a,tempPathOptions:c});if(!m){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}for(const e of f)o.fdTargets.set(e,m)}var p;return!0}({parsingResult:e,workingDirectory:t,rootDirectories:this.rootDirectories,allowTmpRedirects:r}),l=await Mk({parsingResult:e,workingDirectory:t,rootDirectories:this.rootDirectories,allowTmpRedirects:r}),u=!function({parsingResult:e,hasRedirects:t,parsingFailed:r,allRedirectsAreAllowlistSafe:n,allRedirectsAreWorkspaceFileSafe:o}){return!(!t||r||n||o)&&(0===e.redirects.length||e.redirects.some(yk))}({parsingResult:e,hasRedirects:n,parsingFailed:s,allRedirectsAreAllowlistSafe:a,allRedirectsAreWorkspaceFileSafe:c})&&l;return{allowlistOfferSafe:(!n||a||c)&&l&&!s,redirectsAllowlistSafe:u}}async cmdIsAllowedByAllowlist(e,t){return!!t.redirectsAllowlistSafe&&(!!await this.isInShellAllowlist(e)||t.applyTeamAllowlist&&void 0!==t.autoRunControls&&this.isInTeamAllowlist(t.autoRunControls,e))}buildShellApprovalDecisionFacts({commands:e,softDenylistedCommands:t,autoRunControls:r,shouldApplyTeamShellAllowlist:n,deleteProtectionEnabled:o}){const s=e.filter((e=>"denied"===e.state)),i=e.filter((e=>"approvable"===e.state)),a=n&&r?.enabled?e.filter((e=>!this.isInTeamAllowlist(r,e))):[],c=s.filter((e=>void 0!==r&&this.isInTeamBlocklist(r,e))),l=o?s.filter((e=>"rm"===e.command.name)):[];return{hasSecurityDenies:s.length>0,hasSoftDenies:t.length>0,hasTeamAllowlistMisses:a.length>0,allCommandsRunnable:e.every((e=>e.isRunnable())),allCommandsAllowlisted:e.every((e=>"allowlisted"===e.state)),allCommandsPreapproved:e.every((e=>"preapproved"===e.state)),canAllowlistInPrompt:0===s.length&&0===a.length,unapprovedCommands:i,deniedCommands:s,notInTeamAllowlist:a,teamBlocklistedCommands:c,rmDeniedByDeleteProtection:l}}getShellAutoApprovalPolicy({approvalMode:e,isUnrestricted:t,requestedPolicy:r,facts:n,preserveRequestedPolicyForAllowlistedCommands:o}){if(!n.hasSecurityDenies&&!n.hasSoftDenies&&n.allCommandsRunnable){if(t)return"workspace_readonly"===r.type?r:{type:"insecure_none"};if("allowlist"===e)return n.allCommandsAllowlisted&&!o&&"workspace_readonly"!==r.type?{type:"insecure_none",allowlistEscalated:!0}:r}}async getPermissions(){return await this.permissionsProvider.getPermissions()}hasLocalShellControls(e){return e.allow.some((e=>this.isShellEntry(e)))||e.deny.some((e=>this.isShellEntry(e)))||(e.smartAllowlistDenylist?.length??0)>0}hasTeamShellControls(e,t=!0){return void 0!==e&&(t&&(e.enabled||e.allowed.length>0)||e.blocked.length>0)}async shouldPromptForEmptyPlainShellAllowlist(e,t){if("allowlist"!==t.approvalMode||"insecure_none"!==t.userConfiguredPolicy.type||0===e.trim().length||this.hasLocalShellControls(t))return!1;const[r,n]=await Promise.all([this.teamSettingsService.getAutoRunControls(),this.teamSettingsService.getDeleteFileProtection()]);return!this.hasTeamShellControls(r,!t.dashboardTerminalAllowlistOverriddenByPermissionsFile)&&!n}async requestApprovalForEmptyShellAllowlist(e,t,r){const n=await this.getEmptyShellAllowlistCandidates(t);t.onApprovalRequested?.();const o=await this.pendingDecisionStore.requestApproval({type:Bw.Shell,toolCallId:t.toolCallId,details:{command:e,workingDirectory:t.workingDirectory,timeout:t.timeout,reason:Uk(t.smartModeApprovalReason??"Shell allowlist is empty",await this.adminNetworkLimitReason(r)),isSandboxAvailable:!1,isSandboxEnabled:!1,canAllowlist:n.length>0,notAllowedCommands:n,smartModeApprovalReason:t.smartModeApprovalReason,smartModeApprovalRequestId:t.smartModeApprovalRequestId}});return o.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(r)}:{kind:"block",reason:{type:"userRejected",reason:o.reason}}}async getEmptyShellAllowlistCandidates(e){const t=e.parsingResult;return t.parsingFailed||0===t.executableCommands.length||t.hasRedirects&&!0!==t.allRedirectsAreDevNull||!await Mk({parsingResult:t,workingDirectory:e.workingDirectory,rootDirectories:this.rootDirectories,allowTmpRedirects:!0})?[]:this.generateAllowlistPatterns(t.executableCommands.map(zS))}async getAdminCommandDenylistBlock(e,t){const r=(await this.teamSettingsService.getAdminCommandDenylist()).rules;if(0===r.length)return;const n=ks({matchForms:t.parsingResult?ys({command:t.command,parsingResult:t.parsingResult}):[t.command],blockedCommands:r});return void 0!==n?(nk.info(e,"Admin command denylist hard-blocked shell at execution time",{toolCallId:t.toolCallId,parsingFailed:t.parsingResult?.parsingFailed??!0,parserCommandCount:t.parsingResult?.executableCommands.length??0}),{type:"adminCommandDenylist",pattern:n}):void 0}async hasHardDeny(e,t){const r=await this.getPermissions();return t.some((e=>r.deny.some((t=>this.isShellEntry(t)&&[...e.wrapperForms,...e.matchForms].some((e=>this.matchesShell(t,e)))))))}isShellEntry(e){return null!==qk(e)}isPathEntry(e,t){return new RegExp(`^\\s*${e}\\s*\\(`).test(t)}matchesShell(e,t){const r=qk(e);if(!r)return!1;const n=t.trim(),o=this.extractBaseCommand(n);if(null!==r.argsPattern){const e=n.includes(" ")?n.slice(n.indexOf(" ")+1).trim():"",t=this.matchGlob(r.commandPattern,o)||this.matchGlob(r.commandPattern,n),s=this.matchGlob(r.argsPattern,e);if(t&&s)return!0}return!!this.matchGlob(r.fullPattern,n)||!!n.startsWith(`${r.fullPattern} `)||!!this.matchGlob(r.fullPattern,o)||o===r.fullPattern}async checkCursorFileProtection(e){if(!e.some((e=>".cursor"===e.toLowerCase()||".vscode"===e.toLowerCase())))return null;const t=e[e.length-1]?.toLowerCase()??"";return t.endsWith(".md")||t.endsWith(".mdc")||".cursorrules"===t?null:await this.teamSettingsService.getDotCursorProtection()?{type:"permissionsConfig"}:null}extractBaseCommand(e){const t=e.trim(),r=t.indexOf(" ");return-1===r?t:t.substring(0,r)}generateAllowlistPatterns(e){const t=[],r=["git","npm","yarn","pnpm","docker","pip","systemctl","uv","cargo","bun","npx"];for(const{command:n,allowlistable:o}of e)o&&!Gb(n.name)&&(r.includes(n.name)&&n.args.length>0&&"word"===n.args[0].type?t.push(`${n.name} ${n.args[0].value}`):t.push(n.name));return[...new Set(t)]}pathEntryRawPattern(e,t){const r=t.match(function(e){return"Read"===e?r_:n_}(e));if(r)return(r[1]??"").trim()}compileReadDenyMatcher(e){try{const t=this.pathEntryRawPattern("Read",e);if(void 0===t)return()=>!1;const r=(0,ws.b)((0,ts.jl)(t));return e=>r(e)}catch(e){return()=>{throw e}}}matchesPathEntry(e,t,r){const n=this.pathEntryRawPattern(e,t);return void 0!==n&&this.matchGlob((0,ts.jl)(n),r)}async isPathExplicitlyDenied(e,t){return(await this.getPermissions()).deny.some((r=>this.isPathEntry(e,r)&&this.matchesPathEntry(e,r,t)))}async isPathExplicitlyAllowed(e,t){return(await this.getPermissions()).allow.some((r=>this.isPathEntry(e,r)&&this.matchesPathEntry(e,r,t)))}matchGlob(e,t){return(0,ws.T)(e,t)}async addToAllowList(e,t,r){const n=`${t}(${r})`;await this.permissionsProvider.updatePermissions((e=>{const t=e.allow.includes(n)?e.allow:[...e.allow,n];return{...e,allow:t}}))}async addToDenyList(e,t,r){const n=`${t}(${r})`;await this.permissionsProvider.updatePermissions((e=>{const t=e.deny.includes(n)?e.deny:[...e.deny,n];return{...e,deny:t}}))}async shouldBlockMcp(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{tk(o,(0,D.VI)(e.withName("InteractivePermissionsService.shouldBlockMcp")),!1);const{name:s,toolName:i,providerIdentifier:a,args:c}=t,l=function(e,t){if(void 0!==t)return t;const r=e;return void 0!==r.annotations?r.annotations:Fb(r.annotationsJson)}(t,r?.annotations),u=e=>{this.mcpAllowlistLog?.(e)};if(u(`[permissions-service] shouldBlockMcp: toolName="${i}", providerIdentifier="${a}"`),await this.isComputerUseDisabledByAdminFor(a))return u(`[permissions-service] shouldBlockMcp: BLOCKED (Computer Use off for team) toolName="${i}", providerIdentifier="${a}"`),{type:"unsafeResolution",message:"Computer Use is turned off by your team admin. Ask the user to do it instead."};const d=await this.mcpAdminToolLimitRefusal(e,{resolvedTool:n?.resolvedTool,toolName:i});if(void 0!==d)return u(`[permissions-service] shouldBlockMcp: BLOCKED (team tool limit) toolName="${i}", providerIdentifier="${a}"`),{type:"unsafeResolution",message:d};const h=await this.computerUseDecision(t,r);if(await this.isMcpExplicitlyDenied(e,a,i))return u(`[permissions-service] shouldBlockMcp: BLOCKED (explicitly denied) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig"};const p=await this.getPermissions(),f="workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode;if(!0===n?.alreadyApproved&&!f&&"block"!==h.kind&&"askEachCall"!==h.kind)return!1;const m=await this.teamSettingsService.getMcpToolControls(),g=!0===m?.enabled&&!(void 0!==n?.client&&!0===await(this.teamSettingsService.isHostMcpBridgeClient?.(n.client))),w=g&&"block"!==h.kind?{kind:"notComputerUse"}:h,y=void 0!==t.smartModeApproval?.reason&&f,v=t_({server:e_(a),tool:i});let b,S,k;switch(w.kind){case"block":return u(`[permissions-service] shouldBlockMcp: BLOCKED (Computer Use app) toolName="${i}", providerIdentifier="${a}"`),{type:"unsafeResolution",message:w.message};case"noAccess":if(!f&&!await this.teamSettingsService.getShouldBlockMcp())return u(`[permissions-service] shouldBlockMcp: ALLOWED (Computer Use no access) toolName="${i}", providerIdentifier="${a}"`),!1;b=v,k=!0;break;case"app":if(!y&&(this.computerUseAppsAllowedForSession.includes(w.entry)||await this.isComputerUseAppSaved(w.entry)))return u(`[permissions-service] shouldBlockMcp: ALLOWED (Computer Use app grant) toolName="${i}", providerIdentifier="${a}"`),!1;b=w.entry,S=w.app,k=!1;break;case"askEachCall":b=void 0,S=w.app&&{...w.app,allowOnce:!0},k=!1;break;case"notComputerUse":b=v,k=!0}const _=k||void 0!==b,C=t.smartModeApproval?.reason;if(void 0!==C)return"workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode?(u(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode, Smart Mode forced approval) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig",isReadonly:!0}):(u(`[permissions-service] shouldBlockMcp: needsApproval (Smart Mode) toolName="${i}", providerIdentifier="${a}"`),!(g?this.isMcpInTeamAllowlist(m,{providerIdentifier:a,toolName:i,annotations:l}):k&&await this.isMcpExplicitlyAllowed(e,a,i))&&!("unrestricted"===p.approvalMode&&!await this.teamSettingsService.getShouldBlockMcp())&&{type:"needsApproval",approvalReason:C,approvalDetails:{type:"mcp",name:s,toolName:i,...dk(r,l),providerIdentifier:a,args:c,reason:"smartMode",canAllowlist:_&&!this.isComputerUseServer(a),smartModeApprovalReason:C,smartModeApprovalRequestId:t.smartModeApproval?.requestId,allowlistEntry:b,computerUseApp:S}});if(g){const t=this.isMcpInTeamAllowlist(m,{providerIdentifier:a,toolName:i,annotations:l});if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"team",outcome:t?"pass":"fail"}),t)return u(`[permissions-service] shouldBlockMcp: ALLOWED (in admin MCP allowlist) toolName="${i}", providerIdentifier="${a}"`),!1}else if(k){const t=await this.isMcpExplicitlyAllowed(e,a,i);if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"user",outcome:t?"pass":"fail"}),t)return u(`[permissions-service] shouldBlockMcp: ALLOWED (explicitly in allowlist) toolName="${i}", providerIdentifier="${a}"`),!1}if("workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode)return u(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig",isReadonly:!0};if("unrestricted"===p.approvalMode){if(!await this.teamSettingsService.getShouldBlockMcp())return u(`[permissions-service] shouldBlockMcp: ALLOWED (auto-run, no team block) toolName="${i}", providerIdentifier="${a}"`),!1;u(`[permissions-service] shouldBlockMcp: needsApproval (auto-run but team blocks MCP) toolName="${i}", providerIdentifier="${a}"`)}return u(`[permissions-service] shouldBlockMcp: needsApproval (not in allowlist) toolName="${i}", providerIdentifier="${a}", approvalMode="${p.approvalMode}"`),{type:"needsApproval",approvalReason:`MCP tool: ${i}`,approvalDetails:{type:"mcp",name:s,toolName:i,...dk(r,l),providerIdentifier:a,args:c,canAllowlist:_,allowlistEntry:b,computerUseApp:S}}}catch(e){o.error=e,o.hasError=!0}finally{rk(o)}}async mcpAdminToolLimitRefusal(e,{resolvedTool:t,toolName:r}){if(void 0===t||void 0===this.enforceMcpAdminToolLimits)return;if(!await this.enforcesMcpAdminToolLimits())return void(void 0!==this.onMcpAdminToolLimitCheck&&this.judgeMcpAdminToolLimit(t,r).then((e=>this.reportMcpAdminToolLimitCheck("shadow",e)),(()=>{})));const n=await this.judgeMcpAdminToolLimit(t,r);this.reportMcpAdminToolLimitCheck("enforce",n);const o=n?.outcome;switch(o){case void 0:case"within_limit":return;case"outside_limit":return sk.increment(e,1,{reason:"outside_limit"}),"Your team's admin limits this MCP tool";case"settings_unavailable":if(!0===n?.ranWithoutLimit)return;return sk.increment(e,1,{reason:"settings_unavailable"}),"Your team's MCP settings could not be read, so this MCP tool can't run right now";case"unknown_server":return sk.increment(e,1,{reason:"unknown_server"}),ik;default:return o}}async judgeMcpAdminToolLimit(e,t){if("unresolved"===e)return{outcome:"unknown_server"};const r=await(this.teamSettingsService.getMcpAdminToolLimit?.(e.client));if(void 0!==r)switch(r.kind){case"none":return;case"settings_unavailable":return{outcome:"settings_unavailable",...void 0===r.failure?{}:{settingsFailure:r.failure},...!0===r.noLimitApplies?{ranWithoutLimit:!0}:{}};case"unknown_server":return{outcome:"unknown_server"};case"limit":return{outcome:Wb(r.policy,{name:t,annotations:e.annotations})?"within_limit":"outside_limit"};default:return r}}reportMcpAdminToolLimitCheck(e,t){if(void 0!==t)try{this.onMcpAdminToolLimitCheck?.({mode:e,...t})}catch{}}async enforcesMcpAdminToolLimits(){if(void 0===this.enforceMcpAdminToolLimits)return!1;try{return await this.enforceMcpAdminToolLimits()}catch{return!1}}async computerUseDecision(e,t){const r=this.computerUse;if(void 0===r||!this.isComputerUseServer(e.providerIdentifier))return{kind:"notComputerUse"};const n=await r.isOwnServer(e_(e.serverIdentifier||e.providerIdentifier),t);if(!1===n)return{kind:"notComputerUse"};const o=await async function(e,t){const r=cS(e.meta?.["cursor/computerUseScope"])??cS(t.toolScopes?.[e.toolName]);if(void 0===r)return{kind:"screen"};let n;if(void 0!==r.appSelectorArgs){const t=Object.entries(r.appSelectorArgs).flatMap((([t,r])=>aS(t)&&void 0!==r&&void 0!==e.args[r]&&null!==e.args[r]?[{selector:t,value:e.args[r]}]:[]));if(0===t.length){const t=new Intl.ListFormat("en",{type:"disjunction"}).format(Object.values(r.appSelectorArgs).filter((e=>void 0!==e)));return{kind:"noAppSelector",message:`${e.toolName} needs exactly one of ${t} to name the app. Call it again with one of them.`}}const o=t.filter((({selector:e,value:t})=>function(e,t){return"pid"===e?"number"==typeof t&&Number.isInteger(t)||"string"==typeof t&&uS.test(t):"string"==typeof t&&t.length>0}(e,t)));if(1!==o.length){for(const{value:e}of t){const t="string"==typeof e?rS(e.trim()):void 0;if(void 0!==t)return{kind:"app",app:t}}return{kind:"unknownApp"}}n=function(e,t){if("pid"===e){const e="string"==typeof t&&uS.test(t)?Number(t):t;return"number"==typeof e&&Number.isSafeInteger(e)&&e>0?{pid:e}:void 0}const r="string"==typeof t?t.trim():"";if(0!==r.length)return"bundleId"===e?{bundleId:r}:"path"===e?{path:r}:{appName:r}}(o[0].selector,o[0].value)}else{if(void 0===r.appArg)return r.capturesScreen?{kind:"screen"}:{kind:"none"};{const t=e.args[r.appArg];if(null==t||function(e){return"object"==typeof e&&null!==e&&"screen"===e.scope}(t))return{kind:"screen"};n=function(e){if("string"==typeof e){const t=e.trim();return t.length>0?{name:t}:void 0}if("object"!=typeof e||null===e)return;const{scope:t,pid:r}=e;return"app"===t&&"number"==typeof r&&Number.isInteger(r)&&r>0?{pid:r}:void 0}(t)}}if(void 0===n)return{kind:"unknownApp"};const o=function(e){return"pid"in e?void 0:"name"in e?e.name:"bundleId"in e?e.bundleId:"path"in e?e.path:e.appName}(n),s=await t.describeApp(n)??(void 0===o?void 0:rS(o));return void 0===s?{kind:"unknownApp"}:{kind:"app",app:s}}({toolName:e.toolName,args:Object.fromEntries(Object.entries(e.args).map((([e,t])=>[e,t.toJson()]))),meta:t?._meta},r);if(void 0===n&&"app"!==o.kind)return{kind:"askEachCall"};switch(o.kind){case"none":return{kind:"noAccess"};case"screen":return{kind:"notComputerUse"};case"unknownApp":return{kind:"askEachCall"};case"noAppSelector":return{kind:"block",message:o.message};case"app":{const e=function(e){const t=e.toLowerCase();return Yb(t)?"Computer Use doesn't control Cursor itself, including its approval cards. Ask the user to do it instead.":eS.some((e=>e.bundleId===t))?"Computer Use doesn't control apps that run scripts, such as Script Editor, Automator and Shortcuts. Ask the user to do it instead.":tS.some((e=>e.bundleId===t))?"Computer Use doesn't control terminal apps. Use your shell tool to run commands instead.":void 0}(o.app.bundleId);if(void 0!==e)return{kind:"block",message:e};if(void 0===n)return{kind:"askEachCall"};const t=oS(o.app.bundleId)?void 0:t_({server:r.serverId,tool:sS(o.app.bundleId)});return void 0===t?{kind:"askEachCall",app:o.app}:{kind:"app",app:o.app,entry:t}}}throw new Error("unreachable computer-use subject")}isComputerUseServer(e){const t=e_(e);return!0===this.computerUse?.providerIdentifiers.has(t)}async isComputerUseDisabledByAdminFor(e){const t=this.computerUseAdminPolicy;return t?.providerIdentifiers.has(e_(e))?await t.isDisabledByAdmin():!!this.isComputerUseServer(e)&&!0===await(this.teamSettingsService.isComputerUseDisabledByAdmin?.())}allowComputerUseAppForSession({bundleId:e}){const t=void 0===this.computerUse||oS(e)?void 0:t_({server:this.computerUse.serverId,tool:sS(e)});void 0!==t&&this.computerUseAppsAllowedForSession.push(t)}async isMcpFullyAllowlisted(e,t){const r=e.withName("InteractivePermissionsService.isMcpFullyAllowlisted"),{providerIdentifier:n,toolName:o}=t,s=t.annotations??Fb(t.annotationsJson);if(await this.isMcpExplicitlyDenied(r,n,o)||await this.isComputerUseDisabledByAdminFor(n))return!1;const i=await this.teamSettingsService.getMcpToolControls();return!0===i?.enabled?!!this.isMcpInTeamAllowlist(i,{providerIdentifier:n,toolName:o,annotations:s}):!this.isComputerUseServer(n)&&await this.isMcpExplicitlyAllowed(r,n,o)}async isWebFetchFullyAllowlisted(e,t){const r=await this.getPermissions();if("allowlist"!==r.approvalMode)return!1;let n;try{n=new URL(t.url)}catch{return!1}const o=n.hostname;return!r.deny.some((e=>this.matchesWebFetchEntry(e,o)))&&r.allow.some((e=>this.matchesWebFetchEntry(e,o)))}matchesAutoRunCommand(e,t){const r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^${r}(\\s|$)`).test(e.trim())}matchesMcpPattern({pattern:e,providerIdentifier:t,toolName:r,logLabel:n}){const o=e.indexOf(":");if(-1===o)return!1;const s=e.slice(0,o).trim().toLowerCase(),i=e.slice(o+1).trim().toLowerCase(),a=e_(t).toLowerCase().trim(),c=r.toLowerCase().trim(),l="*"===s||this.matchGlob(s,a),u="*"===i||this.matchGlob(i,c),d=l&&u,h=`[permissions-service] ${n}: serverPattern="${s}", toolPattern="${i}", normalizedProviderIdentifier="${a}", normalizedToolName="${c}", serverMatches=${l}, toolMatches=${u}, result=${d}`;return this.mcpAllowlistLog?.(h),d}recordMcpAllowlistCheckResult(e,{allowlistScope:t,outcome:r}){ok.increment(e,1,{allowlist_scope:t,outcome:r})}matchesMcpEntry(e,t,r){const n=e.match(/^\s*Mcp\s*\((.*)\)\s*$/);if(!n)return!1;const o=n[1]?.trim()??"";return this.matchesMcpPattern({pattern:o,providerIdentifier:t,toolName:r,logLabel:"matchesMcpEntry"})}matchesWebFetchEntry(e,t){const r=e.match(/^\s*WebFetch\s*\((.*)\)\s*$/);return!!r&&Xv(t,r[1]?.trim()??"")}matchesMcpEntryBare({pattern:e,providerIdentifier:t,toolName:r}){return this.matchesMcpPattern({pattern:e,providerIdentifier:t,toolName:r,logLabel:"matchesMcpEntryBare"})}isMcpInTeamAllowlist(e,{providerIdentifier:t,toolName:r,annotations:n}){if(e.mcpToolAllowlist.some((e=>this.matchesMcpEntryBare({pattern:e,providerIdentifier:t,toolName:r}))))return!0;const o=this.findTeamMcpServerPolicy(e,t);return void 0!==o&&"reads"===o.mode&&Wb(o,{name:r,annotations:n})}findTeamMcpServerPolicy(e,t){for(const r of e.serverPolicies??[])if(this.matchesMcpEntryBare({pattern:`${r.name}:*`,providerIdentifier:t,toolName:""}))return r.policy}async isMcpExplicitlyDenied(e,t,r){return(await this.getPermissions()).deny.some((e=>this.matchesMcpEntry(e,t,r)))}async isComputerUseAppSaved(e){return(await this.getPermissions()).allow.some((t=>t.match(/^\s*Mcp\s*\((.*)\)\s*$/)?.[1]?.trim().toLowerCase()===e))}async isMcpExplicitlyAllowed(e,t,r){return(await this.getPermissions()).allow.some((e=>this.matchesMcpEntry(e,t,r)))}}var s_=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const i_=65536,a_=1048576,c_=(0,d.h)("LocalReadExecutor"),l_=async(e,t,r,n)=>{const o=setTimeout((()=>{c_.warn(e,`[watchdog, LocalReadExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function u_(e){return BigInt(Math.min(e,4294967295))}async function d_(e,t){if(0===t)return(0,xo.readFile)(e);if(t>2147483647)throw new RangeError(`File size (${t}) is greater than 2 GiB`);const r=await(0,xo.open)(e,"r");try{const e=Buffer.allocUnsafe(t);let n=0;for(;n=32&&e<=126||9===e||10===e||13===e}function f_(e){if(e.length>=2){if(255===e[0]&&254===e[1])return"utf-16le";if(254===e[0]&&255===e[1])return"utf-16be"}const t=Math.min(4096,e.length);if(t<16)return"utf-8";let r=0,n=0;for(let o=0;o+1=8&&r>=4*Math.max(1,n)?"utf-16le":n>=8&&n>=4*Math.max(1,r)?"utf-16be":"utf-8"}const m_=Buffer.from("\n---\n");function g_(e,t){const r=e.length;if(r<2*m_.length)return r;if(10!==e[r-1]||45!==e[r-2]||45!==e[r-3]||45!==e[r-4]||10!==e[r-5])return r;const n=Math.max(t,r-4096),o=e.lastIndexOf(m_,r-m_.length-1);return-1===o||o126))return!1}const t=e.split("\n").filter((e=>e.length>0));if(t.length<2||t.length>3)return!1;const r=t[0],n=t[t.length-1];return!(!/^(exit_code: (?:-?\d+|unknown)|error: .+)$/.test(r)||!n.startsWith("ended_at: ")||3===t.length&&!/^elapsed_ms: \d+$/.test(t[1]))}(e.subarray(o+m_.length,r-4).toString("utf-8"))?o:r}const w_=[Buffer.from("%PDF-","ascii"),Buffer.from([208,207,17,224,161,177,26,225]),Buffer.from([80,75,3,4]),Buffer.from([80,75,5,6]),Buffer.from([80,75,7,8]),Buffer.from([127,69,76,70]),Buffer.from([254,237,250,206]),Buffer.from([254,237,250,207]),Buffer.from([206,250,237,254]),Buffer.from([207,250,237,254]),Buffer.from([77,90,144]),Buffer.from([0,97,115,109]),Buffer.from([137,80,78,71,13,10,26,10]),Buffer.from([255,216,255]),Buffer.from("GIF87a","ascii"),Buffer.from("GIF89a","ascii"),Buffer.from("SQLite format 3\0","ascii"),Buffer.from([31,139]),Buffer.from("BZh","ascii"),Buffer.from([253,55,122,88,90,0]),Buffer.from([40,181,47,253]),Buffer.from([55,122,188,175,39,28]),Buffer.from([82,97,114,33,26,7,0]),Buffer.from([82,97,114,33,26,7,1,0])];function y_(e){return new Xy.sV({result:{case:"invalidFile",value:new Xy.cW({path:e,reason:"File content is binary data, not text"})}})}function v_(e,t,r){if(void 0===r.offset&&void 0===r.limit)return{applied:!1};if(t)return{applied:!1};const n=r.offset??1,o=r.limit??(n<0?Math.abs(n):e),s=n<0?Math.max(0,e+n):Math.max(0,n-1);if(s>=e)return{applied:!1};const i=Math.min(e,s+o),a=b_(s,e),c=b_(i,e);return{applied:!0,start:a,end:Math.max(a,c)}}function b_(e,t){if(Number.isNaN(e)||0===e)return 0;if(e===Number.POSITIVE_INFINITY)return t;if(e===Number.NEGATIVE_INFINITY)return 0;const r=Math.trunc(e);return r<0?Math.max(t+r,0):Math.min(r,t)}function S_(e){return-1===e.indexOf("\r\n")?e:e.replaceAll("\r\n","\n")}function k_(e,t,r,n,o,s){if(n>=o)return{from:0,to:0};let i=0,a=0,c=0===n,l=0;for(;ia&&13===r(t)?t-1:t};l=t+1}return c?{from:a,to:t}:{from:t,to:t}}function __(e,t,r){const n=k_((t=>e.indexOf("\n",t)),e.length,(t=>e.charCodeAt(t-1)),t,r,!1);return 0===n.from&&n.to===e.length?e:n.from>=n.to?"":e.slice(n.from,n.to)}function C_(e,t,r,n,o){if(t>=r)return{text:"",truncated:!1};const s=n>=0?n+3:-1;let i=t;if(n>=0&&i>=n&&i=r)return{text:"",truncated:!1};const a=function(e,t,r,n){if(r>=n)return n;if(r<=t)return t;const o=Math.max(t,r-3);let s=r;for(;s>o;){if(128!=(192&(e[s]??0)))return s;s--}return 192&~(e[s]??0)?r:s}(e,i,Math.min(r,i+3*(o+1)+3),r);let c=S_(function(e,t,r,n){if(t>=r)return"";if(n<0)return e.toString("utf8",t,r);const o=n+3;return r<=n||t>=o?e.toString("utf8",t,r):t>=n&&r<=o?"":(to?e.toString("utf8",Math.max(t,o),r):"")}(e,i,a,n));const l=c.length>o||ao&&(c=Jo(c,o)),{text:c,truncated:l}}function E_(e,t,r,n){if(t>=r)return{text:"",truncated:!1};const o=Math.min(r,t+2*n+1);let s=S_(e.slice(t,o));const i=s.length>n||on&&(s=Jo(s,n)),s.lengthn?{text:e.text+Jo(t,n),truncated:!0}:{text:e.text+t,truncated:e.truncated}}function P_(e,t){if(e.truncated)return e;const r=x_(e,t);return{text:r.text,truncated:r.truncated}}function R_(e,t,r){let n=e;return t.forEach(((e,t)=>{const o=function(e,t){const{line:r,hasNewline:n}=e;return t&&n&&r.text.endsWith("\r")?{...r,text:r.text.slice(0,-1)}:r}(e,r);t>0&&(n=x_(n,"\n")),n=x_(n,o.text),o.truncated&&(n={text:n.text,truncated:!0})})),n}function I_(e){const t=e.toLowerCase();return"utf-8"===t?"utf8":"utf-8-bom"===t||"utf-8 bom"===t?"utf8bom":"latin-1"===t?"latin1":t}function T_(e){return void 0===e.maxChars||void 0!==e.offset||void 0!==e.limit?Ks:Math.min(Ks,e.maxChars+2)}function A_(e,t,r){if(!t||void 0===r.maxChars||e.length-1<=r.maxChars)return e;const n=e.charCodeAt(e.length-1);return n>=55296&&n<=56319?e.slice(0,-1):e}class $_ extends Error{constructor(){super("Invalid UTF-8 while streaming read"),this.name="InvalidUtf8Error"}}function M_(e){for(let t=1;t<=Math.min(3,e.length);t++){const r=e[e.length-t]??0;if(128!=(192&r))return D_(r)>t?t:0}return 0}function D_(e){return e>=240?4:e>=224?3:e>=192?2:1}class O_{constructor(e,t,r){this.previousEndsWithCr=e,this.carry=t,this.strict=r,this.lines=0,this.crlfCount=0,this.lfOnlyCount=0,this.continuesLine=t.length>0}count(e){this.strict&&this.validate(e),0===this.lines&&e.length>0&&10!==e[0]&&(this.continuesLine=!0);for(let t=e.indexOf(10);-1!==t;t=e.indexOf(10,t+1))(t>0?13===e[t-1]:this.previousEndsWithCr)?this.crlfCount++:this.lfOnlyCount++,this.lines++;e.length>0&&(this.previousEndsWithCr=13===e[e.length-1])}finish(){if(this.strict&&this.carry.length>0)throw new $_}validate(e){let t=e;if(this.carry.length>0){const r=D_(this.carry[0]??0)-this.carry.length;if(e.length0&&(0,n.isUtf8)(e.subarray(0,e.length-t))?"utf8_cut":"utf8_invalid"}(e)}async function L_(e,t){const r=t>0?Math.min(t,a_):a_,o=await d_(e,r);return o.length===t&&(0,n.isUtf8)(o)||ui(new Vs.TextDecoder("utf-8",{fatal:!1}).decode(o,{stream:o.length===a_&&o.length!==t}))?{kind:"lossyUtf8",cacheEncoding:"utf8"}:{kind:"iconv",decoderEncoding:"latin1",cacheEncoding:"latin1"}}async function j_(e){const t=await(0,xo.stat)(e),r=await zi(e);if(r.isBinaryFile)return;const n=F_({file:e,stats:t,format:r},void 0);if("iconv"===n.kind)return n.decoderEncoding;const o=await L_(e,t.size);return"iconv"===o.kind?o.decoderEncoding:void 0}async function U_(e,{file:t,stats:r},n,o,s){const i=r.size,a=void 0!==n.offset||void 0!==n.limit,c=(n.offset??1)<0,l=n.offset??1,u=Math.max(0,l-1),d=void 0===n.limit?void 0:u+n.limit,h=c?Math.abs(l):0,p=a?1/0:n.maxChars??1/0,f=a&&!c?n.maxChars??1/0:1/0;let m=[],g=0,w=!1,y=0,v=!1,b=!(c||a&&u<=0),S=!1;const k=[];let _,C=0,E=!1,x=0,P=!1,R=[],I=0,T=0,A=0,$=!1,M={text:"",truncated:!1},D=!1,O=!1,F=0,N=0,L=0,j=!1,U=!1;const B=e=>{let t=e;return!j&&t.length>0&&(j=!0,65279===t.charCodeAt(0)&&(U=!0,t=t.slice(1))),t},W=(e,t)=>t&&13===e.text.charCodeAt(e.text.length-1),H=()=>P||E&&C>=Ks,q=()=>v||w&&g>=Ks,z=(e,t)=>{if(H())return;const r=k.length>0?1:0;let n=Ks-C;if(r>0){if(n<=0)return void(E=!0);n--}const o=e.text.length>n?{line:{text:Jo(e.text,n),truncated:!0},hasNewline:t}:{line:e,hasNewline:t};k.push(o),C+=r+(o.line.truncated?n:o.line.text.length),e.truncated&&(E=!0),o.line.truncated&&(E=!0),W(o.line,t)&&x++,C-x>f&&(P=!0,_=F)},G=(e,t)=>{if(q())return;const r=m.length>0?1:0;let n=Ks-g;if(r>0){if(n<=0)return void(w=!0);n--}const o=e.text.length>n?{line:{text:Jo(e.text,n),truncated:!0},hasNewline:t}:{line:e,hasNewline:t};m.push(o),g+=r+(o.line.truncated?n:o.line.text.length),(e.truncated||o.line.truncated)&&(w=!0),W(o.line,t)&&y++,g-y>p&&(v=!0,_=F)},V=(e,t)=>{e&&(t?N++:L++),F++},K=()=>{const e=R[I];void 0!==e&&(A-=e.line.text.length+1),R[I]=void 0,I=(I+1)%R.length,T--},J=(e,t,r)=>{const n=F;if(0===n&&(S=0===e.text.length),!c&&a&&b&&n>=u&&(b=!1,m=[]),b&&G(e,t),c){if(h>0)for(T===h&&K(),(e=>{if(T===R.length){const e=new Array(Math.min(h,Math.max(16,2*R.length)));for(let t=0;t1&&A>Ks;)K(),$=!0}else a&&n>=u&&(void 0===d||n!(D||(!b||q())&&(!a||0!==F)&&!(c?h>0:!(!a||H())&&F>=u&&F<(d??1/0))),X=()=>{const e=M.text.length-1;if(a){const t=!c&&F>=u&&F<(d??1/0),r=k.length>0?1:0;if(!t||C-x+r+e<=f)return;z(M,!1)}else{const t=m.length>0?1:0;if(g-y+t+e<=p)return;G(M,!1)}M={text:"",truncated:!1},D=!0};let Q;const Y=e=>{if(void 0===n.maxChars||c)return;if(!(a?H()||F>=(d??1/0):q()))return;const t=e.subarray(e.length-M_(e));return Q=new O_(ee,Buffer.from(t),"strictUtf8"===o.kind),Q};let ee=!1;for await(const r of async function*(e,t,r,n,o){const s=function(e){return e>0?{start:0,end:e-1}:{}}(n);if("strictUtf8"===r.kind||"lossyUtf8"===r.kind){const n=new Vs.TextDecoder("utf-8",{fatal:"strictUtf8"===r.kind,ignoreBOM:!0}),i=(0,Ro.createReadStream)(t,{highWaterMark:i_,signal:e.signal,...s});let a;try{for await(const e of i){if(void 0!==a){a.count(e);continue}const t=n.decode(e,{stream:!0});t.length>0&&(yield t),e.length>=4&&(a=o?.(e))}if(void 0!==a)return void a.finish();const e=n.decode();e.length>0&&(yield e)}catch(e){if(e instanceof TypeError)throw new $_;throw e}return}const i=(0,Ro.createReadStream)(t,{highWaterMark:i_,signal:e.signal,...s}).pipe(Js.decodeStream(r.decoderEncoding));for await(const e of i)yield"string"==typeof e?e:String(e)}(e,t,o,i,Y)){const e=B(r);let t=0,n=e.indexOf("\n",t);for(;-1!==n;){const r=n>t?13===e.charCodeAt(n-1):ee;Z()?(M=P_(M,e.slice(t,n)),J(M,!0,r)):(D&&n>t&&(O=!0),V(!0,r)),M={text:"",truncated:!1},D=!1,ee=!1,t=n+1,n=e.indexOf("\n",t)}t0&&N/te*100>=5,ne="utf8"===o.cacheEncoding&&U?"utf8bom":o.cacheEncoding;s&&ta(t,r,ne);const oe=Math.min(F,a?d??1/0:1/0),se=void 0!==_&&(O||oe>_+1),ie=(n.maxChars??1/0)+i_,ae=e=>e.text.length>ie?{text:Jo(e.text,ie),truncated:!0}:e,ce=()=>R_({text:"",truncated:w||se},m,re);if(!a){const e=ae(ce());return{content:e.text,totalLines:F,truncated:e.truncated,rangeApplied:!1}}if(F<=1&&S)return{content:"",totalLines:F,truncated:!1,rangeApplied:!1};if(c){const e=n.limit??h,t=[];for(let e=0;e=F){const e=ce();return{content:e.text,totalLines:F,truncated:e.truncated,rangeApplied:!1}}const le=ae(R_({text:"",truncated:E||se},k,re));return{content:le.text,totalLines:F,truncated:le.truncated,rangeApplied:!0}}class B_{constructor(e,t,r){this.permissionsService=e,this.workspacePath=t,this.terminalReads=new Ql,this.mcpStateAccessor=r?.mcpStateAccessor,this.useStreamingRead=r?.useStreamingRead,this.pendingDecisionProvider=r?.pendingDecisionProvider,this.encodingSlices=r?.encodingSlices}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,D.VI)(e.withName("LocalReadExecutor.execute")),!1);const o=t.path;if(""===o.trim())return new Xy.sV({result:{case:"error",value:new Xy.F_({path:o,error:rs})}});const i=(0,ts.o1)(o,this.workspacePath),a=await l_(e,"permissionsService.shouldBlockFileRead",3e3,(()=>Yk(this.permissionsService,i)));if(a){const r=await l_(e,"resolveFileReadBlock",3e3,(()=>async function(e,t){return await ed(e,{onNeedsApproval:async(e,r)=>{const n=t.pendingDecisionProvider?.requestReadApproval?.bind(t.pendingDecisionProvider);if("fileRead"!==r.type||!n)return{kind:"denied",message:"Blocked by permissions configuration"};const o=await n({type:Bw.Read,details:{path:r.path,reason:e},toolCallId:t.toolCallId});return o.approved?null:{kind:"rejected",reason:o.reason}},onUserRejected:e=>({kind:"rejected",reason:e}),onPermissionDenied:e=>({kind:"denied",message:e})})??{kind:"proceed"}}(a,{pendingDecisionProvider:this.pendingDecisionProvider,toolCallId:t.toolCallId})));if("rejected"===r.kind)return new Xy.sV({result:{case:"rejected",value:new Xy.f4({path:i,reason:r.reason??""})}});if("denied"===r.kind)return new Xy.sV({result:{case:"permissionDenied",value:new Xy.lW({path:i})}})}void 0!==this.mcpStateAccessor&&Vy(e,this.mcpStateAccessor,i);try{const r=await l_(e,"stat",3e3,(()=>(0,xo.stat)(i)));if(r.isDirectory())return new Xy.sV({result:{case:"invalidFile",value:new Xy.cW({path:i,reason:"Path is a directory, not a file"})}});if(!r.isFile())return new Xy.sV({result:{case:"invalidFile",value:new Xy.cW({path:i,reason:"Path is neither a file nor a directory"})}});const o=function(e){return null!==function(e){const t=sh(e,"terminals");if(!t||1!==t.remainingPath.length)return null;const r=t.remainingPath[0],n=/^(\d+)\.txt$/.exec(r);if(!n)return null;const o=Number.parseInt(n[1],10);return Number.isNaN(o)?null:{id:o}}(e)}(i),a=function(e){const t=sh(e,"agent-tools");return null!==t&&1===t.remainingPath.length&&t.remainingPath[0].endsWith(".txt")}(i);if(o||a)return await this.readTerminalFile(e,i,r,t,a&&!o);const c=await l_(e,"getFormatForFile",3e3,(()=>zi(i))),l=c.isImageFile,u=function(e){return".pdf"===(0,s.extname)(e).toLowerCase()}(i),d=ji(i);if(l){const t=await l_(e,"prepareImageForModel",3e3,(async()=>(async e=>{let t;try{t=await Bv(e)}catch(t){const r=await Wv(e);if("undecodable"===r.kind)return r;throw t}if(!0===t.reencoded)return{kind:"image",image:t};const r=await Wv(t.data);return"undecodable"===r.kind?r:{kind:"image",image:t}})(await(0,xo.readFile)(i))));return"undecodable"===t.kind?new Xy.sV({result:{case:"invalidFile",value:new Xy.cW({path:i,reason:(n=t.reason,`File is not a valid image: its data could not be decoded (${n}). A truncated or hand-copied file does this; write it again from the original bytes with code.`)})}}):new Xy.sV({result:{case:"success",value:new Xy.mE({path:i,output:{case:"data",value:t.image.data},totalLines:0,fileSize:u_(r.size),truncated:!1})}})}if(u){const t=await l_(e,"readPdfBinary",3e3,(()=>(0,xo.readFile)(i)));return new Xy.sV({result:{case:"success",value:new Xy.mE({path:i,output:{case:"data",value:t},totalLines:0,fileSize:u_(r.size),truncated:!1})}})}if(c.isBinaryFile&&d){if(void 0!==t.maxVideoBytes&&r.size>t.maxVideoBytes)return new Xy.sV({result:{case:"success",value:new Xy.mE({path:i,totalLines:0,fileSize:u_(r.size),truncated:!0})}});const n=await l_(e,"readBinaryFile",3e3,(()=>(0,xo.readFile)(i)));return new Xy.sV({result:{case:"success",value:new Xy.mE({path:i,output:{case:"data",value:n},totalLines:0,fileSize:u_(r.size),truncated:!1})}})}if(c.isBinaryFile)return y_(i);{const n=this.useStreamingRead,o=!n||await l_(e,"useStreamingRead",3e3,(()=>n()));if(o||r.size>Ks){const n=await l_(e,"readTextStreaming",7e3,(()=>async function(e,t,r,n){const o=F_(t,r.encodingHint);try{return{...await U_(e,t,r,o,n),decoder:o.kind}}catch(o){if(o instanceof $_){const o=await L_(t.file,t.stats.size);return{...await U_(e,t,r,o,n),decoder:o.kind}}throw o}}(e,{file:i,stats:r,format:c},t,o))),s=A_(n.content,n.truncated,t);return Wl(this.encodingSlices,e)&&this.recordStreamedRead(e,i,r.size,n,s),new Xy.sV({result:{case:"success",value:new Xy.mE({path:i,output:{case:"content",value:s},totalLines:n.totalLines,fileSize:u_(r.size),truncated:n.truncated,rangeApplied:n.rangeApplied})}})}const s=await l_(e,"readText",3e3,(()=>Bi(i,t.encodingHint))),a=await l_(e,"countLines",3e3,(()=>Xs(s))),l=function(e,t,r){const n=v_(t,""===e,r);return n.applied?n.start>=n.end?{content:"",rangeApplied:!0}:{content:__(e,n.start,n.end),rangeApplied:!0}:{content:e,rangeApplied:!1}}(s,a,t);let u=l.content,d=!1;const h=T_(t);return u.length>h&&(u=A_(u.substring(0,h),!0,t),d=!0),u.length16777216)return"other_encoding";try{return r=await d_(e,t),!(0,n.isAscii)(r)&&(0,n.isUtf8)(r)?"utf8_as_other":"other_encoding"}catch{return"other_encoding"}var r}(t,r)),ru(this.encodingSlices,e,{layer:"exec_read",evidence:a,partial:o.rangeApplied||o.truncated},i)}catch{}}async readTerminalFile(e,t,r,n,o){const s=await l_(e,"readTerminalFile",3e3,(()=>d_(t,r.size)));if(o&&(i=s,w_.some((e=>function(e,t){return e.length>=t.length&&e.subarray(0,t.length).equals(t)}(i,e)))))return y_(t);var i;const a=function(e,t,r=8388608){if(0===e.length)return{content:"",totalLines:1,rangeApplied:!1,truncated:!1};const n=h_(e),o=g_(e,n);if("utf-8"!==f_(e.subarray(n,o)))return function(e,t,r){const n=0===e.length,o=function(e){let t=0,r=0;const n=e.length;for(;r=s.end)return{content:"",totalLines:o,rangeApplied:!0,truncated:!1};const i=k_((t=>e.indexOf("\n",t)),e.length,(t=>e.charCodeAt(t-1)),s.start,s.end,!0),a=E_(e,i.from,i.to,r);return{content:a.text,totalLines:o,rangeApplied:!0,truncated:a.truncated}}(function(e){const t=h_(e),r=t>0?e.subarray(0,t).toString("utf-8"):"",n=g_(e,t),o=nr?-1:239===e[t]&&187===e[t+1]&&191===e[t+2]?t:-1}(e,n,o);return function(e,t,r,n){const o=e.length-(t>=0?3:0)==0,s=function(e){let t=0,r=0;const n=e.length;for(;r=i.end)return{content:"",totalLines:s,rangeApplied:!0,truncated:!1};const a=k_((t=>e.indexOf(10,t)),e.length,(t=>e[t-1]??0),i.start,i.end,!0),c=C_(e,a.from,a.to,t,n);return{content:c.text,totalLines:s,rangeApplied:!0,truncated:c.truncated}}(e,s,t,r)}(s,n,T_(n)),c=A_(a.content,a.truncated,n);return Wl(this.encodingSlices,e)&&(o||this.terminalReads.firstRead(n.toolCallId,t))&&tu(this.encodingSlices,e,{layer:o?"exec_read":"exec_terminal_context",evidence:N_(s),partial:a.rangeApplied||a.truncated},c),new Xy.sV({result:{case:"success",value:new Xy.mE({path:t,output:{case:"content",value:c},totalLines:a.totalLines,fileSize:u_(r.size),truncated:a.truncated,rangeApplied:a.rangeApplied})}})}}function W_(e){return Buffer.from(e,"utf16le").toString("utf16le")}var H_=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},q_=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function z_(e){return`Path '${e}' could not be verified while resolving symlinks. This can happen when access is denied or the path contains a symlink loop.`}function G_(e){return`Path '${e}' is neither a file nor a directory`}async function V_(e){const t=await(0,xo.stat)(e).catch((()=>{}));return void 0!==t&&!t.isFile()&&!t.isDirectory()}function K_(e,t,r){const n=function(e,t){let r;for(const n of t)(0,ts.ZU)({basePath:n,targetPath:e})&&(void 0===r||n.length>r.length)&&(r=n);return r}((0,s.resolve)(e,t),r);return void 0===n||n===e}class J_ extends Error{}function Z_(e){const t=new AbortController,r=setTimeout((()=>t.abort()),e);return{signal:t.signal,clear:()=>clearTimeout(r)}}function X_(e){switch(e.result.case){case"content":return e.result.value.matches.length>0;case"files":return e.result.value.files.length>0;case"count":return e.result.value.counts.length>0;case void 0:return!1;default:{const t=e.result;throw new Error(`Unknown grep result: ${String(t)}`)}}}function Q_(e){switch(e){case"content":return new Ry.vD({result:{case:"content",value:new Ry.Zp({ripgrepTruncated:!0})}});case"files_with_matches":return new Ry.vD({result:{case:"files",value:new Ry.T7({ripgrepTruncated:!0})}});case"count":return new Ry.vD({result:{case:"count",value:new Ry.xA({ripgrepTruncated:!0})}});default:throw new Error(`Unknown output mode: ${String(e)}`)}}function Y_(e){return"success"===e.result.case&&Object.values(e.result.value.workspaceResults).some((e=>!0===e.result.value?.clientTruncated))}function eC(e,t,r){let n=Buffer.concat(e);t&&(n=n.subarray(0,n.lastIndexOf(10)+1)),r?.note(n);const o=n.toString("utf8");return o.includes("�")?{stdout:o,stdoutBytes:n}:{stdout:o}}function tC(e){return/^(utf-?16|ucs-?2)/i.test(e)}const rC=(0,d.h)("local-exec/grep"),nC=(0,h.Pu)("local_exec.grep.deadline_reached",{description:"Grep and Glob searches the search deadline stopped, by whether they kept what was found",labelNames:["output_mode","outcome","streaming"]}),oC=(0,h.Pu)("local_exec.grep.newest_first_stat_fallback",{description:"Grep and Glob results left in ripgrep's order because stat was too slow to sort them",labelNames:["output_mode"]}),sC=(0,h.v5)("local_exec.grep.rg.spawn_ms",{description:"Time to start the ripgrep process for one Grep or Glob search",labelNames:["sandboxed"]}),iC=(0,h.v5)("local_exec.grep.rg.search_ms",{description:"Time ripgrep took to search and exit after it started, for runs it finished",labelNames:["output_mode","sandboxed"]});function aC(e){return e instanceof Error&&e.message.includes("ENOENT")&&e.message.includes("spawn")}function cC(e){try{return(0,Ro.existsSync)(e)}catch{return"check_failed"}}function lC(e){if("object"==typeof e&&null!==e&&"errno"in e){const t=e.errno;if("number"==typeof t)return t}}function uC(e,t){if("object"==typeof e&&null!==e)return"syscall"===t&&"syscall"in e&&"string"==typeof e.syscall?e.syscall:"path"===t&&"path"in e&&"string"==typeof e.path?e.path:void 0}function dC(e,t,r,n){return{...pC(e),...n,cwd:t,cwdExists:cC(t),errorMessage:Cc(r),errorCode:_c(r),errno:lC(r),syscall:uC(r,"syscall"),errorPath:uC(r,"path")}}function hC(e){return new Error(`Path does not exist: ${e}`)}function pC(e){const t={rgPath:e,platform:process.platform,arch:process.arch,pid:process.pid,uptimeSeconds:Math.round(process.uptime()),execPath:process.execPath};try{t.rgPathExists=(0,Ro.existsSync)(e)}catch(e){t.rgPathExists=!1,t.rgPathExistsError=e instanceof Error?e.message:String(e)}try{const r=(0,Ro.lstatSync)(e);t.rgIsSymlink=r.isSymbolicLink(),r.isSymbolicLink()&&!t.rgPathExists&&(t.rgBrokenSymlink=!0)}catch{t.rgLstatFailed=!0}const r=(0,s.dirname)(e);try{t.parentDirExists=(0,Ro.existsSync)(r),t.parentDirExists&&(t.parentDirContents=(0,Ro.readdirSync)(r).slice(0,50))}catch(e){t.parentDirError=e instanceof Error?e.message:String(e)}const n=(0,s.dirname)(r);try{t.grandparentDirExists=(0,Ro.existsSync)(n),t.grandparentDirExists&&(t.grandparentDirContents=(0,Ro.readdirSync)(n).slice(0,50))}catch(e){t.grandparentDirError=e instanceof Error?e.message:String(e)}if(t.rgPathExists)try{const r=(0,Ro.statSync)(e);t.rgFileSize=r.size,t.rgFileMode=r.mode.toString(8),t.rgIsFile=r.isFile(),t.rgModifiedMs=r.mtimeMs}catch(e){t.rgStatError=e instanceof Error?e.message:String(e)}const o="node_modules.asar.unpacked";if(e.includes(o)){const r=e.split(o)[0];if(r){const n=r.concat("node_modules.asar");try{t.asarExists=(0,Ro.existsSync)(n)}catch{t.asarExists="check_failed"}const i=r.concat(o);try{if(t.asarUnpackedDirExists=(0,Ro.existsSync)(i),t.asarUnpackedDirExists){const r=(0,s.dirname)((0,s.dirname)(e));t.ripgrepPkgDirExists=(0,Ro.existsSync)(r)}}catch{t.asarUnpackedDirExists="check_failed"}}}return t}class fC{constructor(e,t,r,n){this.ignoreService=e,this.grepProvider=t,this.workspacePath=r,this.stdoutDecodes=new WeakMap;const o=Array.isArray(this.workspacePath)?this.workspacePath[0]:this.workspacePath;this.singleWorkspacePath=Array.isArray(this.workspacePath)&&this.workspacePath.length>1?void 0:o,this.mcpStateAccessor=n?.mcpStateAccessor,this.permissionsService=n?.permissionsService,this.useStreamingGrep=n?.useStreamingGrep,this.encodingSlices=n?.encodingSlices}computeRelativeTarget(e,t){const r=(0,ts.o1)(e,this.singleWorkspacePath??t);return r===t?".":(0,s.relative)(t,r)}isRootIndependentSearchPath(e){return(0,s.isAbsolute)(e)||/^~(?=$|[/\\])/.test(e)||e.startsWith("file://")}resolveSearchTargets(e,t){const r=this.isRootIndependentSearchPath(e);return t.map((t=>{const n=(0,s.resolve)(t);return{root:t,resolvedRoot:n,target:(0,ts.o1)(e,r?void 0:n)}}))}findOutsideTargets(e,t){if(void 0===e||""===e)return;const r=this.resolveSearchTargets(e,t);return r.some((({resolvedRoot:e,target:t})=>(0,ts.BJ)(t,e)))?void 0:[...new Set(r.map((({target:e})=>e)))]}searchTarget(e,t){if(!t.path)return".";const r=(0,ts.o1)(t.path,this.singleWorkspacePath??e);return(0,ts.BJ)(r,(0,s.resolve)(e))?this.computeRelativeTarget(t.path,e):r}sortsAfterRipgrep(e,t,r){return void 0===t.sort&&(r?!0!==t.sortAscending:(0,s.isAbsolute)(this.searchTarget(e,t)))}async buildArgs(e,t,r,n){const o=[],s=function(e,t){return"files_with_matches"===t&&""===e.pattern&&Boolean(e.glob)}(t,r),i=await ma(await this.ignoreService.listCursorIgnoreFilesByRoot(e));for(const e of i)o.push("--cursor-ignore",e);if("content"===r)o.push("--line-number","--with-filename","--no-heading","-0"),void 0!==t.contextBefore&&o.push("--before-context",String(t.contextBefore)),void 0!==t.contextAfter&&o.push("--after-context",String(t.contextAfter)),o.push("--max-columns",String(1e3),"--max-columns-preview"),void 0!==t.context&&void 0===t.contextBefore&&void 0===t.contextAfter&&o.push("--before-context",String(t.context),"--after-context",String(t.context));else if("files_with_matches"===r)o.push(s?"--files":"-l");else{if("count"!==r)throw new Error(`Unknown output mode: ${String(r)}`);o.push("-c","--with-filename")}!0===t.caseInsensitive?o.push("--ignore-case"):o.push("--case-sensitive"),t.type&&o.push("--type",t.type),t.glob&&(o.push("--iglob",t.glob),s&&o.push("--iglob","!**/.git")),t.multiline&&o.push("--multiline","--multiline-dotall");const a=n?"none":t.sort??"modified";if(n&&o.push("--line-buffered"),"none"!==a){const e=!0===t.sortAscending?"--sort":"--sortr";o.push(e,a)}o.push("--no-config","--color=never"),o.push("--hidden"),o.push("--follow");const c=this.searchTarget(e,t);if(t.path){const t=await async function(e){try{if(!(await(0,xo.stat)(e)).isFile())return;const{encoding:t}=await zi(e);return tC(t)?t.toLowerCase():void 0}catch{return}}((0,ts.o1)(c,e));void 0!==t&&o.push("--encoding",t)}return s||o.push("--regexp",t.pattern),o.push("--"),o.push(c),o}async filterBlockedFiles(e,t){const r=new Map,n=await(this.permissionsService?.getFileReadBoundaryBlocker?.()),o=[];for(const s of e){const e=(0,ts.o1)(s.file,t),i=await xc(e);null===i||await this.isPostRipgrepBlocked(i,r)||void 0!==n&&await n(e,i)||o.push(s)}return o}async isPostRipgrepBlocked(e,t){const[r,n]=await Promise.all([this.ignoreService.isCursorIgnored(e,t),this.ignoreService.isRepoBlocked(e)]);return r||n}throwOnRipgrepFailure(e,t,r){if((""!==e.stderr||2===e.exitCode)&&""===e.stdout.trim()&&!function({stderr:e,target:t}){return e.trim().split(/\r?\n/).every((e=>{if(/^rg: .+: line \d+: /.test(e))return!0;const r=/^rg: (.+?): .*\(os error (?:13|5|2|1)\)$/.exec(e)?.[1]??/^rg: File system loop found: (.+) points to an ancestor /.exec(e)?.[1];return void 0!==r&&r!==t}))}({stderr:e.stderr,target:this.searchTarget(t,r)}))throw new Error(e.stderr||`ripgrep exited with code ${e.exitCode}`)}async orderNewestFirst(e,t,r,n,o){const s=await Zy(t,(e=>(0,ts.o1)(n(e),r)));return s.statTimedOut&&(rC.info(e,"newest_first.stat_timeout_fallback",{toolCallId:o.toolCallId,execId:o.execId,outputMode:o.outputMode,fileCount:t.length}),oC.increment(e,1,{output_mode:o.outputMode})),s.items}async keepNewestPage(e,t,r,n,o){return(await this.orderNewestFirst(e,t,r,n,o)).slice(0,fC.CLIENT_LIMIT_LINES)}async runFilesMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const d=H_(a,(0,D.VI)(e.withName("LocalGrepExecutor.runFilesMode")),!1),h=await this.buildArgs(t,r,"files_with_matches",n),p=await this.executeRg(d.ctx,t,h,void 0,o,s,i);this.throwOnRipgrepFailure(p,t,r);const f=(c=p.stdout,l=n?fC.HARD_MAX_OUTPUT_LINES:fC.CLIENT_LIMIT_LINES,u=fC.HARD_MAX_OUTPUT_LINES,function(e,t,r){const n=e.trim();if(""===n)return{files:[],totalFiles:0,clientTruncated:!1,ripgrepTruncated:!1};const o=new Iy;let s=0,i=0,a=0;for(;Ty(n,a,o);)a=o.nextStart,st?Buffer.from(n.slice(0,i)).toString():n,l=[];for(a=0;l.lengtht,ripgrepTruncated:s>=r}}(c,l,u)),m=f.totalFiles>fC.CLIENT_LIMIT_LINES;let g=f.files;n&&(g=await this.keepNewestPage(d.ctx,g,t,(e=>e),i),m&&(g=g.join("\0").split("\0")));const w=(await this.filterBlockedFiles(g.map((e=>({file:e}))),t)).map((({file:e})=>e)),y=g.length-w.length,v=new Ry.T7({files:w,totalFiles:Dy(f.totalFiles-y),clientTruncated:m,ripgrepTruncated:f.ripgrepTruncated||p.timedOut||p.stdoutByteCapped});return{result:new Ry.vD({result:{case:"files",value:v}}),timedOut:p.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{q_(a)}var c,l,u}async runCountMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const d=H_(a,(0,D.VI)(e.withName("LocalGrepExecutor.runCountMode")),!1),h=await this.buildArgs(t,r,"count",n),p=await this.executeRg(d.ctx,t,h,void 0,o,s,i);this.throwOnRipgrepFailure(p,t,r);const f=(c=p.stdout,l=n?fC.HARD_MAX_OUTPUT_LINES:fC.CLIENT_LIMIT_LINES,u=fC.HARD_MAX_OUTPUT_LINES,function(e,t,r){const n=e.trim();if(""===n)return{counts:[],totalFiles:0,totalMatches:0,clientTruncated:!1,ripgrepTruncated:!1};const o=[],s=new Iy;let i=0;for(;Ty(n,i,s);){const e=i,t=s.lineEnd;if(i=s.nextStart,t===e)continue;const r=n.lastIndexOf(":",t-1);if(rt,ripgrepTruncated:a>=r}}(c,l,u)),m=n?await this.keepNewestPage(d.ctx,f.counts,t,(e=>e.file),i):f.counts,g=await this.filterBlockedFiles(m,t),w=g.reduce(((e,t)=>e+t.count),0),y=m.length-g.length,v=m.reduce(((e,t)=>e+t.count),0)-w,b=new Ry.xA({counts:g.map((e=>new Ry.sS({file:e.file,count:Dy(e.count)}))),totalFiles:Dy(f.totalFiles-y),totalMatches:Dy(f.totalMatches-v),clientTruncated:f.totalFiles>fC.CLIENT_LIMIT_LINES,ripgrepTruncated:f.ripgrepTruncated||p.timedOut||p.stdoutByteCapped});return{result:new Ry.vD({result:{case:"count",value:b}}),timedOut:p.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{q_(a)}var c,l,u}async runContentMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const c=H_(a,(0,D.VI)(e.withName("LocalGrepExecutor.runContentMode")),!1),l=await this.buildArgs(t,r,"content",n),u=void 0!==r.context||void 0!==r.contextBefore||void 0!==r.contextAfter,d=fC.CLIENT_LIMIT_LINES*(u?2:1),h=await this.executeRg(c.ctx,t,l,d,o,s,i);this.throwOnRipgrepFailure(h,t,r);const p=await this.decodeLinesAsRead(c.ctx,h,t,i),{byFile:f,totalLines:m,totalMatchedLines:g,clientTruncated:w,ripgrepTruncated:y}=function(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{return H_(o,(0,D.VI)(n.withName("parseContentOutput")),!1),function(e,t,r){const n={byFile:new Map,totalLines:0,totalMatchedLines:0,totalFiles:0,clientTruncated:!1,ripgrepTruncated:!1};if(""===e.trim())return n;const o=new Map,s=new Set,i=new Iy;let a=0,c=0,l=0,u=0;for(;Ty(e,u,i);){const r=u,n=i.lineEnd;if(u=i.nextStart,l++,d=e,n-(h=r)==2&&45===d.charCodeAt(h)&&45===d.charCodeAt(h+1))continue;let p=-1;for(let t=r;t=n)continue;let m=0,g=0;for(;f57)break;m=10*m+(t-48),g++,f++}if(0===g||f>=n||!Number.isFinite(m))continue;const w=e.charCodeAt(f);if(58!==w&&45!==w)continue;const y=45===w;y||a++;const v=e.slice(r,p);if(s.has(v)||s.add(v),c>=t)continue;const b=e.slice(f+1,n);let S=o.get(v);void 0===S&&(S={file:v,matches:[]},o.set(v,S)),S.matches.push({lineNumber:m,content:b,isContextLine:y}),c++}var d,h;return{byFile:o,totalLines:Dy(l),totalMatchedLines:Dy(a),totalFiles:Dy(s.size),clientTruncated:c>=t,ripgrepTruncated:l>=r}}(e,t,r)}catch(e){o.error=e,o.hasError=!0}finally{q_(o)}}(p,fC.CLIENT_LIMIT_LINES,d,c.ctx),v=Array.from(f.values()),b=await this.filterBlockedFiles(v,t),S=v.filter((e=>!b.includes(e))),k=S.reduce(((e,t)=>e+t.matches.length),0),_=S.reduce(((e,t)=>e+t.matches.filter((e=>!e.isContextLine)).length),0),C=n?await this.orderNewestFirst(c.ctx,b,t,(e=>e.file),i):b,E=new Ry.Zp({matches:C.map((e=>new Ry.uI({file:e.file,matches:e.matches.map((e=>new Ry.dx({lineNumber:e.lineNumber,content:e.content,isContextLine:e.isContextLine})))}))),totalLines:Dy(m-k),totalMatchedLines:Dy(g-_),clientTruncated:w,ripgrepTruncated:y||h.timedOut||h.stdoutByteCapped});return{result:new Ry.vD({result:{case:"content",value:E}}),timedOut:h.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{q_(a)}}async decodeLinesAsRead(e,t,r,o){const s={stack:[],error:void 0,hasError:!1};try{const i=t.stdoutBytes;if(void 0===i)return t.stdout;const a=H_(s,(0,D.VI)(e.withName("LocalGrepExecutor.decodeLinesAsRead")),!1),c=function(e,t){const r=[],o=new Iy;let s=0,i=0,a=e.indexOf("�");for(;-1!==a&&Ty(e,s,o);){const{lineEnd:c,nextStart:l}=o,u=t.indexOf(10,i),d=-1===u?t.length:u+1;let h=-1===u?t.length:u;if(h>i&&-1!==u&&13===t[h-1]&&h--,ae.file)))],u=new Map,d=performance.now()+fC.LINE_ENCODING_TIMEOUT_MS;let h=0;for(;h{let d=!1,h=!1;const p=()=>{h||(h=!0,a.span.end())};if(e.signal.aborted)return p(),void u(new Error("Grep was cancelled"));if(o.aborted)return p(),void u(fC.ripgrepTimeoutError());let f;const m="insecure_none"===s.type?"false":"true",g=performance.now();let w=g;try{const e=s;f=(0,No.spawnInSandbox)((0,No.Ko)(),r,{cwd:t},e),w=performance.now(),0}catch(r){if(p(),aC(r)){const n=(0,No.Ko)();if(rC.error(e,"rg_diagnostics.spawn_throw",void 0,dC(n,t,r,i)),!1===cC(t))return u(hC(t))}return u(r)}const y=[],v=[];let b=0,S=0,k=0,_=!1,C=!1,E=!1;const x=()=>{if(!d)try{p(),E=!0;const e=eC(y,!0,this.stdoutDecodes.get(i));""===e.stdout?u(fC.ripgrepTimeoutError()):l({...e,stderr:"",exitCode:0,timedOut:!0,stdoutByteCapped:C}),f.kill()}catch{}};o.addEventListener("abort",x,{once:!0});const P=()=>{o.removeEventListener("abort",x),p(),u(new Error("Grep was cancelled"));try{f.kill()}catch{}};e.signal.addEventListener("abort",P,{once:!0}),f.stdout?.on("data",(e=>{if(!C&&!_)if(b+=e.length,b>c){C=!0;try{f.kill()}catch{}}else if(void 0!==n){let t=-1,r=0;for(let o=0;o=n)){t=o+1,_=!0;try{f.kill()}catch{}break}k+=r;const o=t>=0?e.subarray(0,t):e;y.push(o)}else y.push(e)})),f.stderr?.on("data",(e=>{S+=e.length,S<=c&&v.push(e)})),f.on("error",(r=>{if(o.removeEventListener("abort",x),e.signal.removeEventListener("abort",P),p(),aC(r)){const n=(0,No.Ko)();if(rC.error(e,"rg_diagnostics.spawn_enoent",void 0,dC(n,t,r,i)),!1===cC(t))return void u(hC(t))}u(r)})),f.on("close",(t=>{const r=performance.now()-w;d=!0,o.removeEventListener("abort",x),e.signal.removeEventListener("abort",P);const n=eC(y,C,E?void 0:this.stdoutDecodes.get(i)),s=Buffer.concat(v).toString("utf8");p(),l({...n,stderr:s,exitCode:t??0,timedOut:!1,stdoutByteCapped:C}),sC.histogram(e,w-g,{sandboxed:m}),C||_||o.aborted||e.signal.aborted||0!==t&&1!==t||iC.histogram(e,r,{output_mode:i.outputMode,sandboxed:m})}))}))}async checkOutsideTarget(e,t){if(1!==t.length||void 0===t[0])return{error:`Path '${e}' points to a different folder from each workspace root; use an absolute path`};const r=await xc(t[0]);return null===r?{error:z_(e)}:await this.ignoreService.isCursorIgnored(r)?{error:`Path '${e}' is filtered out by .cursorignore`}:await V_(t[0])?{error:G_(e)}:{resolvedTarget:r}}async execute(e,t,r){if(!Wl(this.encodingSlices,e))return this.search(e,t,r,void 0);const n=new nu,o=await this.search(e,t,r,n);return"success"===o.result.case&&tu(this.encodingSlices,e,{layer:"exec_grep",evidence:n.evidence(),partial:Y_(o)},o),o}async search(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{const a=H_(o,(0,D.VI)(e.withName("LocalGrepExecutor.execute")),!1),c=Array.isArray(this.workspacePath)?this.workspacePath:[this.workspacePath??process.cwd()],l=t.outputMode??"content";if("content"!==(i=l)&&"files_with_matches"!==i&&"count"!==i)throw new Error(`Unknown output mode: ${l}`);const u=l,d={toolCallId:t.toolCallId,execId:r?.execId,outputMode:u,targetPath:t.path,workspacePaths:c};void 0!==n&&this.stdoutDecodes.set(d,n);const h=ds(t.sandboxPolicy),p=this.grepProvider.getWorktreeGuardInfo?.(c);if((0,ts.fl)({targetPath:t.path,workspacePaths:c,mainWorktreePath:p?.mainWorktreePath}))return new Ry.Ud({result:{case:"error",value:new Ry.ts({error:ts.PS})}});const f=this.findOutsideTargets(t.path,c);let m=t,g=c;try{if(t.path&&void 0!==f){const r=await this.checkOutsideTarget(t.path,f);if("error"in r)return new Ry.Ud({result:{case:"error",value:new Ry.ts({error:r.error})}});void 0!==this.mcpStateAccessor&&Vy(e,this.mcpStateAccessor,r.resolvedTarget),g=c.slice(0,1),m=t.clone(),m.path=f[0]}else if(m.path){const t=[];let r=!1;for(const{root:n,resolvedRoot:o,target:s}of this.resolveSearchTargets(m.path,c)){if(!(0,ts.BJ)(s,o))continue;const i=await xc(s);if(null!==i)if(await this.ignoreService.isCursorIgnored(i))r=!0;else{if(await V_(s))return new Ry.Ud({result:{case:"error",value:new Ry.ts({error:G_(m.path)})}});t.push(n),void 0!==this.mcpStateAccessor&&Vy(e,this.mcpStateAccessor,i)}}if(0===t.length){const e=r?`Path '${m.path}' is filtered out by .cursorignore`:z_(m.path);return new Ry.Ud({result:{case:"error",value:new Ry.ts({error:e})}})}g=t}let r={};const n=void 0===f?await this.executeIndexedGrepWithTimeout(a.ctx,g,m,d):void 0;if(void 0!==n){r=n;for(const[e,t]of Object.entries(r)){const r=t.result;switch(r.case){case"content":r.value.matches=await this.filterBlockedFiles(r.value.matches,e);break;case"files":r.value.files=(await this.filterBlockedFiles(r.value.files.map((e=>({file:e}))),e)).map((({file:e})=>e));break;case"count":r.value.counts=await this.filterBlockedFiles(r.value.counts,e)}}}else{const e=await this.streamingEnabled(a.ctx,d),t=e?Z_(fC.MAIN_TIMEOUT_MS):void 0;let n=0,o=!1;try{for(const s of g){if(!0===t?.signal.aborted){r[s]=Q_(u),n++,o=!0;continue}if(!1===cC(s))return new Ry.Ud({result:{case:"error",value:new Ry.ts({error:`Path does not exist: ${s}`})}});const i=t??Z_(fC.MAIN_TIMEOUT_MS);try{const t=await this.runMode(a.ctx,u,s,m,e,i.signal,h,d);r[s]=t.result,t.timedOut&&n++}catch(t){if(!(t instanceof J_))throw t;if(r[s]=Q_(u),n++,o=!0,!e)break}finally{i!==t&&i.clear()}}}finally{t?.clear()}if(n>0){const t=o&&(!e||!Object.values(r).some(X_));if(this.reportDeadlineReached(a.ctx,d,{streaming:e,folderCount:g.length,stoppedFolderCount:n,outcome:t?"failed":"partial"}),t)throw fC.ripgrepTimeoutError()}}const o=function(e,t){if(t.length<=1)return e;const r=[...new Set(t.map((e=>(0,s.resolve)(e))))],n={};for(const[t,o]of Object.entries(e)){const e=(0,s.resolve)(t),i=t=>K_(e,t,r),a=o.result;switch(a.case){case"content":{const e=a.value,r=[];let o=0,s=0;for(const t of e.matches)i(t.file)?r.push(t):(o+=t.matches.length,s+=t.matches.filter((e=>!e.isContextLine)).length);const c=e.clone();c.matches=r,c.totalLines=Math.max(0,e.totalLines-o),c.totalMatchedLines=Math.max(0,e.totalMatchedLines-s),n[t]=new Ry.vD({result:{case:"content",value:c}});break}case"files":{const e=a.value,r=e.files.filter((e=>i(e))),o=e.clone();o.files=r,o.totalFiles=Math.max(0,e.totalFiles-(e.files.length-r.length)),n[t]=new Ry.vD({result:{case:"files",value:o}});break}case"count":{const e=a.value,r=[];let o=0;for(const t of e.counts)i(t.file)?r.push(t):o+=t.count;const s=e.clone();s.counts=r,s.totalFiles=Math.max(0,e.totalFiles-(e.counts.length-r.length)),s.totalMatches=Math.max(0,e.totalMatches-o),n[t]=new Ry.vD({result:{case:"count",value:s}});break}default:n[t]=o}}return n}(r,g),i=new Ry._0({pattern:m.pattern,path:void 0!==m.path&&this.isRootIndependentSearchPath(m.path)?(0,ts.o1)(m.path):m.path,outputMode:u,workspaceResults:o});return new Ry.Ud({result:{case:"success",value:i}})}catch(e){if(m.path){const e=(0,ts.o1)(m.path,this.singleWorkspacePath);try{await(0,xo.stat)(e)}catch(t){return new Ry.Ud({result:{case:"error",value:new Ry.ts({error:`Path does not exist: ${e}`})}})}}return new Ry.Ud({result:{case:"error",value:new Ry.ts({error:e instanceof Error?e.message:String(e)})}})}}catch(e){o.error=e,o.hasError=!0}finally{q_(o)}var i}}fC.MAIN_TIMEOUT_MS=25e3,fC.INDEXED_GREP_TIMEOUT_MS=25e3,fC.INDEXED_GREP_CONTEXT_TIMEOUT_MS=fC.INDEXED_GREP_TIMEOUT_MS+100,fC.HARD_MAX_OUTPUT_LINES=1e4,fC.CLIENT_LIMIT_LINES=2e3,fC.LINE_ENCODING_TIMEOUT_MS=2e3,Be.object({record_v:Be.number().int().nullish(),pid:Be.number().int().nonnegative().nullish(),version:Be.string().nullish(),started_at:Be.number().nullish(),control_sock:Be.string().nullish(),runtime_dir:Be.string().nullish(),data_dir:Be.string().nullish(),config_path:Be.string().nullish(),log_path:Be.string().nullish(),metrics_addr:Be.string().nullish(),exe:Be.string().nullish()}),Be.object({mountpoint:Be.string().nullish(),capabilities:Be.array(Be.string()).nullish(),nfs_transport:Be.string().nullish(),bind_ignored:Be.object({active:Be.array(Be.string()).nullish()}).passthrough().nullish()});const mC=Be.object({daemon_alive:Be.boolean().nullish(),mounts:Be.array(Be.unknown()).nullish(),data_plane:Be.object({enabled:Be.boolean().nullish()}).passthrough().nullish()});Be.object({daemon_alive:Be.boolean().nullish(),daemon_version:Be.string().nullish(),capabilities:Be.array(Be.string()).nullish()}),mC.extend({memory:Be.object({anon_bytes:Be.number()}).nullish().catch(null)});const gC=Be.number().int().nonnegative(),wC=Be.object({line_no:Be.number().int().positive(),kind:Be.enum(["match","before","after"]),text:Be.string().optional(),bytes:Be.string().regex(/^(?:[0-9a-fA-F]{2})*$/).optional(),truncated:Be.boolean().default(!1)}).refine((e=>void 0!==e.text||void 0!==e.bytes));Be.object({type:Be.literal("file"),path:Be.string(),lines:Be.array(wC)}),Be.object({type:Be.literal("summary"),files_searched:gC,more:Be.boolean(),stop_reason:Be.string().nullable(),skipped:Be.object({over_size:gC,size_unknown:gC,budget_exhausted:gC,fetch_failed:gC,unreadable:gC})}),Be.object({type:Be.string()}),(0,d.h)("local-exec/grove-grep"),(0,h.Pu)("local_exec.grep.grove",{description:"Grep searches Grove served, or declined to ripgrep, by decline reason",labelNames:["outcome","reason"]}),(0,h.v5)("local_exec.grep.grove.served_ms",{description:"Time Grove took to answer a Grep search it served"});var yC=r("../proto/dist/generated/agent/v1/ls_exec_pb.js"),vC=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},bC=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class SC{constructor(e,t,r){this.permissionsService=e,this.ignoreService=t,this.workspacePath=r}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{vC(r,(0,D.VI)(e.withName("LocalLsExecutor.execute")),!1).ctx;const n=(0,ts.o1)(t.path,this.workspacePath);try{let r;try{r=await(0,xo.stat)(n)}catch(e){return"ENOENT"===_c(e)?function(e){const t=sh(e,"terminals");return null!==t&&0===t.remainingPath.length}(n)?new yC.fv({result:{case:"error",value:new yC.uj({path:n,error:"No active terminals."})}}):new yC.fv({result:{case:"error",value:new yC.uj({path:n,error:`Path does not exist: ${n}`})}}):new yC.fv({result:{case:"error",value:new yC.uj({path:n,error:Cc(e)})}})}if(!r.isDirectory())return new yC.fv({result:{case:"error",value:new yC.uj({path:n,error:`Path is not a directory: ${n}`})}});const o=ds(t.sandboxPolicy),s=t.timeoutMs??5e3,i=e.withTimeout(s),{tree:a,didTimeout:c}=await this.getDirectoryTree(i,n,t.ignore,o);return c?new yC.fv({result:{case:"timeout",value:new yC.ze({directoryTreeRoot:a})}}):new yC.fv({result:{case:"success",value:new yC.PC({directoryTreeRoot:a})}})}catch(e){return new yC.fv({result:{case:"error",value:new yC.uj({path:n,error:e instanceof Error?e.message:"Unknown error occurred"})}})}}catch(e){r.error=e,r.hasError=!0}finally{bC(r)}}async getDirectoryTree(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{return vC(o,(0,D.VI)(e.withName("LocalLsExecutor.getDirectoryTree")),!1),await this.buildTreeFromRipgrepStream(e,t,r,n,2500)}catch(e){o.error=e,o.hasError=!0}finally{bC(o)}}async buildTreeFromRipgrepStream(e,t,r,n,o){const i={stack:[],error:void 0,hasError:!1};try{vC(i,(0,D.VI)(e.withName("LocalLsExecutor.buildTreeFromRipgrepStream")),!1);const a=(0,s.resolve)(t),c=new yC.vq({absPath:a,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!0,fullSubtreeExtensionCounts:{}}),l=new Map;l.set(a,c);const u={charactersUsed:a.length,budgetExceeded:!1},[d,h]=await Promise.all([this.ignoreService.listCursorIgnoreFilesByRoot(t),this.ignoreService.getRepoBlockExcludeGlobs(t)]),p=[...r,...h],{lines:f,didTimeout:m}=ya(e,{root:t,excludeGlobs:p,caseSensitive:!0,cursorIgnoreFiles:d,sandboxPolicy:n,source:"ls"});for await(const e of f){if(!e)continue;const r=(0,s.resolve)(t,e),n=await xc(r);null===n||await this.ignoreService.isCursorIgnored(n)||await this.ignoreService.isRepoBlocked(n)||this.addPathToTree(r,a,l,u,o)}return this.sortTreeChildren(c),{tree:c,didTimeout:await m}}catch(e){i.error=e,i.hasError=!0}finally{bC(i)}}addPathToTree(e,t,r,n,o){const i=(0,s.basename)(e),a=(0,s.dirname)(e);this.ensureDirectoryPath(a,t,r,n.budgetExceeded);const c=r.get(a);if(!c)return;const l=i.length;if(!n.budgetExceeded&&n.charactersUsed+l<=o){const e=new yC.ur({name:i});c.childrenFiles.push(e),n.charactersUsed+=l}else{if(!n.budgetExceeded){n.budgetExceeded=!0;let e=a;for(;e.startsWith(t);){const t=r.get(e);t&&(t.childrenWereProcessed=!1);const n=(0,s.dirname)(e);if(n===e)break;e=n}}let o=n.overflowChain;if(n.overflowDir!==a||void 0===o){o=[];let e=a;for(;e.startsWith(t);){const t=r.get(e);t&&o.push(t);const n=(0,s.dirname)(e);if(n===e)break;e=n}n.overflowDir=a,n.overflowChain=o}const i=(0,s.extname)(e);for(const e of o)e.fullSubtreeExtensionCounts[i]??=0,e.fullSubtreeExtensionCounts[i]=Dy(e.fullSubtreeExtensionCounts[i]+1),e.numFiles??=0,e.numFiles=Dy(e.numFiles+1)}}ensureDirectoryPath(e,t,r,n){if(r.has(e)||e===t)return;const o=(0,s.dirname)(e);o!==e&&o.startsWith(t)&&this.ensureDirectoryPath(o,t,r,n);const i=new yC.vq({absPath:e,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!n,fullSubtreeExtensionCounts:{}});r.set(e,i);const a=r.get(o);a&&a.childrenDirs.push(i)}sortTreeChildren(e){e.childrenDirs.sort(((e,t)=>(0,s.basename)(e.absPath).localeCompare((0,s.basename)(t.absPath)))),e.childrenFiles.sort(((e,t)=>e.name.localeCompare(t.name)));for(const t of e.childrenDirs)this.sortTreeChildren(t)}}class kC extends Error{constructor(e,t){super(`Tool ${e} not found, available tools: ${t.join(", ")}`),this.toolName=e,this.availableTools=t,this.name="McpToolNotFoundError"}}function _C(e){if(e instanceof kC)return!0;if(!(e instanceof Error)||"McpToolNotFoundError"!==e.name)return!1;const t=e;return"string"==typeof t.toolName&&Array.isArray(t.availableTools)}function CC(e){return!0===e.url?.startsWith("mcp-provider://")}function EC(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function xC(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function PC(e,t){return(t??[]).some((t=>{const r=EC(t.command),n=xC(t.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==e.command&&(0,Lb.mD)(r,e.command),s=void 0===n||void 0!==e.url&&(0,Lb.eA)(n,e.url);return o&&s}))}function RC(e,t){if(CC(e))return!1;const r=t?.rules??[];if(0===r.length)return!1;if(PC(e,r))return!0;const n=function(e){return e.flatMap((e=>{if(void 0===e.serverUrl)return[];const t=function(e){if(e.includes("*"))return e;const t=e.search(/[?#]/);return-1===t?e:e.slice(0,t)}(e.serverUrl);return t===e.serverUrl?[]:[{...e,serverUrl:t}]}))}(r);return n.length>0&&PC(e,n)}function IC(e,t){const{command:r,url:n}=e;return void 0!==r&&t.commandPatterns.some((e=>(0,Lb.mD)(e.trim(),r)))||void 0!==n&&t.serverUrlPatterns.some((e=>(0,Lb.eA)(e.trim(),n)))}var TC=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class AC extends Error{constructor(e){super(`MCP server "${e}" is disabled`),this.name="McpServerDisabledError"}}class $C extends Error{constructor(e){super(`MCP server "${e}" has not been approved`),this.serverName=e,this.name="McpServerNotApprovedError"}}class MC extends Error{constructor(e,t){super(`MCP server "${e}" is overridden by ${t}`),this.serverName=e,this.overridingConfigPath=t,this.name="McpServerOverriddenError"}}class DC{constructor(e){this.disabledService=e}async load(e,t,r,n,o){if(await this.disabledService.isServerDisabled(t))throw new AC(t);return await o(e,r)}}class OC{constructor(e){this.approvalService=e}async load(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{if(function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(s,(0,D.VI)(e.withName("ServerApprovalMiddleware.load")),!1),!await this.approvalService.isServerApproved(t,r,n))throw new $C(t);return await o(e,r)}catch(e){s.error=e,s.hasError=!0}finally{TC(s)}}}class FC{constructor(e,t){this.approvalsPath=e,this.cwd=t,this.approvalsPromise=this.loadApprovals()}async isServerApproved(e,t,r){const n=function(e,t,r){const n={path:r,server:t};return`${e}-${(0,ko.createHash)("sha256").update(JSON.stringify(n)).digest("hex").substring(0,16)}`}(e,t,this.cwd);return(await this.getApprovals()).includes(n)}async loadApprovals(){try{const e=await(0,xo.readFile)(this.approvalsPath,"utf8"),t=JSON.parse(e);return Array.isArray(t)?t:(await this.saveApprovalsToFile([]),[])}catch(e){if(e instanceof Error&&e.message.includes("ENOENT"))return[];throw e}}async getApprovals(){return this.approvalsPromise}async addApproval(e){const t=await this.approvalsPromise;t.includes(e)||(t.push(e),await this.saveApprovals(t))}async addApprovals(e){const t=await this.approvalsPromise,r=e.filter((e=>!t.includes(e)));r.length>0&&(t.push(...r),await this.saveApprovals(t))}async removeApproval(e){const t=await this.approvalsPromise,r=t.filter((t=>t!==e));r.length!==t.length&&await this.saveApprovals(r)}async clearApprovals(e){const t=await this.approvalsPromise,r=e?t.filter((t=>!e(t))):[];r.length!==t.length&&await this.saveApprovals(r)}async saveApprovalsToFile(e){await(0,xo.mkdir)(s.dirname(this.approvalsPath),{recursive:!0}),await(0,xo.writeFile)(this.approvalsPath,JSON.stringify(e,null,2))}async saveApprovals(e){await this.saveApprovalsToFile(e),this.approvalsPromise=Promise.resolve(e)}}const NC=["https://api.cursor.com","https://api2.cursor.sh"],LC=["CURSOR_API_BASE_URL","CURSOR_BACKEND_URL"],jC=/^MCP server ".+" is blocked by \S/u;function UC(e){if(void 0!==e&&""!==e)try{return new URL(e).origin}catch{return}}function BC(e,t=process.env){if(void 0===e)return!1;let r;try{r=new URL(e)}catch{return!1}if("/v1/agent/mcp"!==r.pathname.replace(/\/+$/,"")&&!r.pathname.startsWith("/internal/agent-serve/agent-sdk-mcp-relay/"))return!1;const n=new Set(NC);for(const e of LC){const r=UC(t[e]);void 0!==r&&n.add(r)}return n.has(r.origin)}function WC(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function HC(e,t){if("string"!=typeof e)return;const r=e.trim();return""===r||r.length>t||/\p{Cc}/u.test(r)?void 0:r}function qC(e){if(!Array.isArray(e))return;const t=[];for(const r of e.slice(0,200)){const e=HC(r,200);void 0!==e&&t.push(e)}return t}function zC(e,t){const r=t.slice(0,20).join(", "),n=t.length-20;return n>0?` ${e}: ${r}, and ${n} more.`:` ${e}: ${r}.`}var GC=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},VC=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class KC{async load(e,t,r,n,o){const s=o(e,r);return new ZC(e,t,s,r)}}function JC(e){let t;return e.then((e=>{t=e})).catch((()=>{})),t}class ZC{constructor(e,t,r,n){this.serverName=t,this.clientPromise=r,this.config=n,this.clientPromiseTraceId=(0,D.fU)(e)?.spanContext()?.traceId,this.toolsPromise=this.clientPromise.then((async t=>null===t?[]:await t.getTools(e))),this.resourcesPromise=this.clientPromise.then((async t=>null===t?[]:(await t.listResources(e)).resources)),this.promptsPromise=this.clientPromise.then((async t=>null===t?[]:await t.listPrompts(e))),this.toolsPromise.catch((()=>{})),this.resourcesPromise.catch((()=>{})),this.promptsPromise.catch((()=>{}))}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=GC(t,(0,D.VI)(e.withName("CachedMcpClient.getTools")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=JC(this.toolsPromise);return void 0!==n?n:await this.toolsPromise}catch(e){t.error=e,t.hasError=!0}finally{VC(t)}}async callTool(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{const i=GC(s,(0,D.VI)(e.withName("CachedMcpClient.callTool")),!1),a=await this.getClient(i.ctx);if(null===a)throw new Error("Client is not ready");return a.callTool(i.ctx,t,r,n,o)}catch(e){s.error=e,s.hasError=!0}finally{VC(s)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=GC(t,(0,D.VI)(e.withName("CachedMcpClient.getInstructions")),!1),n=await this.getClient(r.ctx);if(null===n)return;return await n.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{VC(t)}}async getClient(e){const t={stack:[],error:void 0,hasError:!1};try{const r=GC(t,(0,D.VI)(e.withName("CachedMcpClient.getClient")),!1);return r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined"),await this.clientPromise}catch(e){t.error=e,t.hasError=!0}finally{VC(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{const r=GC(t,(0,D.VI)(e.withName("CachedMcpClient.listResources")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=JC(this.resourcesPromise);return void 0!==n?{resources:n}:{resources:await this.resourcesPromise}}catch(e){t.error=e,t.hasError=!0}finally{VC(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=GC(r,(0,D.VI)(e.withName("CachedMcpClient.readResource")),!1),o=await this.getClient(n.ctx);return null===o?{contents:[]}:o.readResource(n.ctx,t)}catch(e){r.error=e,r.hasError=!0}finally{VC(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{const r=GC(t,(0,D.VI)(e.withName("CachedMcpClient.listPrompts")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=JC(this.promptsPromise);return void 0!==n?n:await this.promptsPromise}catch(e){t.error=e,t.hasError=!0}finally{VC(t)}}async getPrompt(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=GC(n,(0,D.VI)(e.withName("CachedMcpClient.getPrompt")),!1),s=await this.getClient(o.ctx);return null===s?{messages:[]}:s.getPrompt(o.ctx,t,r)}catch(e){n.error=e,n.hasError=!0}finally{VC(n)}}async getState(e){const t={stack:[],error:void 0,hasError:!1};try{const r=GC(t,(0,D.VI)(e.withName("CachedMcpClient.getState")),!1);r.span.setAttribute("serverName",this.serverName);const n=await this.getClient(r.ctx);if(null===n)throw new Error("Client is not ready");return await n.getState(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{VC(t)}}async getAllowlistInUse(){try{await this.toolsPromise;const e=await this.clientPromise;return await(e?.getAllowlistInUse?.())}catch{return}}async getAllowlistRefusal(){if(void 0!==this.config&&"url"in this.config&&BC(this.config.url))try{return void await this.toolsPromise}catch(e){return function(e){const t=e instanceof Error?e.message:"string"==typeof e?e:void 0;if(void 0===t)return;const r=t.indexOf("{");if(-1===r)return;let n;try{n=JSON.parse(t.slice(r))}catch{return}if(!WC(n))return;const o=HC(n.error,700);return void 0!==o&&jC.test(o)?o:void 0}(e)}}async close(){try{const e=await this.clientPromise;await(e?.close?.())}catch{}}}function XC(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function QC(e,t){if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e||"bigint"==typeof e)return String(e);if(null==e)return t;try{const r=JSON.stringify(e);return"string"==typeof r?r:t}catch{return t}}function YC(e){return e?` (${QC(e,"")})`:""}function eE(e){if(null===e||"string"==typeof e||"boolean"==typeof e)return e;if("number"==typeof e)return Number.isFinite(e)?e:void 0;if(Array.isArray(e)){const t=[];for(const r of e){if(void 0===r){t.push(null);continue}const e=eE(r);if(void 0===e)return;t.push(e)}return t}if("object"!=typeof e)return;const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&null!==t)return;const r={};for(const[t,n]of Object.entries(e)){if(void 0===n)continue;const e=eE(n);if(void 0===e)return;r[t]=e}return r}function tE(e){const t=eE(e);if(null!=t&&"object"==typeof t&&!Array.isArray(t))return t}const rE=new TextDecoder("utf-8",{fatal:!0});function nE(e){return"string"==typeof e?e.split(";")[0]?.trim().toLowerCase()??"":""}function oE(e,t){const r=Buffer.from(t,"base64"),n=function(e){try{const t=rE.decode(e);return t.includes("\0")?void 0:t}catch{return}}(r)??(function(e){const t=nE(e);return t.startsWith("text/")||"application/xml"===t||t.endsWith("+xml")}(e.mimeType)?r.toString("utf8").replace(/^\uFEFF/,""):void 0);if(void 0!==n)return{text:n,binary:!1};const o="string"==typeof e.mimeType&&e.mimeType.length>0?e.mimeType:"unknown type";return{text:`[Binary resource: ${QC(e.uri,"unknown")} (${o}, ${r.byteLength} bytes). The file is not text, so its contents are not included.]`,binary:!0}}const sE=new Set(["image/png","image/jpeg","image/jpg","image/gif","image/webp"]);function iE(e){return"string"==typeof e.text&&e.text.length>0?e.text:void 0}function aE(e){if(!XC(e))return;const t=e.resource;return XC(t)&&void 0===iE(t)&&"string"==typeof t.blob&&sE.has(nE(t.mimeType))?t.blob:void 0}function cE(e){const t=e,r=t.resource;if(XC(r)){const e=iE(r);return void 0!==e?e:"string"==typeof r.blob?oE(r,r.blob).text:`Resource: ${QC(r.uri,"unknown")}${YC(r.name)}`}return t.uri?`Resource: ${QC(t.uri,"unknown")}${YC(t.name)}`:`Unsupported content type "${e.type}": ${JSON.stringify(e)}`}function lE(e){const t=tE(e);if(void 0!==t&&0!==Object.keys(t).length)try{return Buffer.byteLength(JSON.stringify(t))<=262144?t:void 0}catch{return}}var uE=r("zod/v4-mini");const dE=uE.object({CLIENT_ID:uE.string(),CLIENT_SECRET:uE.optional(uE.string()),scopes:uE.optional(uE.array(uE.string()))}),hE=uE.strictObject({caBundle:uE.string().check(uE.trim(),uE.minLength(1),uE.maxLength(131072))}),pE=uE.object({type:uE.optional(uE.literal("stdio")),command:uE.string(),args:uE.optional(uE.array(uE.string())),env:uE.optional(uE.record(uE.string(),uE.string())),envFile:uE.optional(uE.string()),cwd:uE.optional(uE.string()),enabledTools:uE.optional(uE.array(uE.string())),startupTimeoutSec:uE.catch(uE.optional(uE.number().check(uE.positive())),void 0)}),fE=uE.object({type:uE.optional(uE.enum(["http","sse"])),url:uE.string(),headers:uE.optional(uE.record(uE.string(),uE.string())),auth:uE.optional(dE),tls:uE.optional(hE),placement:uE.optional(uE.enum(["server","client"])),enabledTools:uE.optional(uE.array(uE.string()))}),mE=uE.union([pE,fE]),gE=uE.object({mcpServers:uE.record(uE.string(),mE)});Error;const wE=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g;function yE(e,t){if("string"==typeof e)return function(e,t){return e.replace(wE,((e,r,n,o)=>{if(void 0!==r){const n=t(r);return void 0!==n?n:e}if(void 0===n)return e;const s=t(n);return void 0!==s?s:void 0!==o?o:e}))}(e,t);if(Array.isArray(e))return e.map((e=>yE(e,t)));if(null!==e&&"object"==typeof e){const r={};for(const[n,o]of Object.entries(e))r[n]=yE(o,t);return r}return e}r("../../node_modules/.pnpm/smol-toml@1.9.0/node_modules/smol-toml/dist/index.js");Symbol("invalid");function vE(e){const t=Object.entries(e);return{jsonKeyOf:new Map(t.map((([e,t])=>[t,e]))),tomlKeyOf:new Map(t)}}const bE=vE({CLIENT_ID:"client_id",CLIENT_SECRET:"client_secret",scopes:"scopes"}),SE=vE({caBundle:"ca_bundle"}),kE=vE({type:"type",command:"command",args:"args",env:"env",envFile:"env_file",cwd:"cwd",enabledTools:"enabled_tools",startupTimeoutSec:"startup_timeout_sec"}),_E=vE({type:"type",url:"url",headers:"http_headers",auth:"auth",tls:"tls",placement:"placement",enabledTools:"enabled_tools"}),CE=(new Map([["auth",{keys:bE,unknownKeyIsError:!1}],["tls",{keys:SE,unknownKeyIsError:!0}]]),"enabled");new Set([...kE.jsonKeyOf.keys(),..._E.jsonKeyOf.keys(),CE]);Symbol("disabled");const EE=(0,d.h)("McpConfig");async function xE(e,t=e=>process.env[e]){try{const r=await(0,xo.readFile)(e,"utf8"),n=yE((0,xp.qg)(r),t);return gE.parse(n)}catch{return{mcpServers:{}}}}async function PE(e,t=e=>process.env[e]){const r={config:{mcpServers:{}},diagnostics:[]};return r}async function RE(e,t=e=>process.env[e]){const{config:r,diagnostics:n}=await PE(0,t);return n.length>0&&EE.warn((0,b.q6)(),"[mcp config] problems in MCP config; `agent mcp list` shows them",{errorCount:n.filter((e=>"error"===e.severity)).length,warningCount:n.filter((e=>"warning"===e.severity)).length,fileNames:[...new Set(n.map((e=>s.basename(e.file))))]}),r}const IE=["enterprise","project","user","env"];function TE(e){return"project"===e||"env"===e}const AE=["0.0.0.0/0","::/0"];function $E(e){const t=(e??[]).filter((e=>e.trim().length>0)),r=t.flatMap((e=>{const t=(0,Lb.bi)(e);return void 0===t?[]:[t]}));return{hasInvalidEntries:r.length!==t.length,entries:r}}function ME(e){const t=!0===e.enabled,r=$E(e.mcpNetworkDenylist),n="deny_all"===e.mcpNetworkMode||r.entries.includes("*")||r.hasInvalidEntries,o=t?function(e){if("allow_all"===e.mcpNetworkMode)return[...AE];const t=$E(e.mcpNetworkAllowlist);if("allowlist"===e.mcpNetworkMode)return t.entries.includes("*")?[...AE]:t.entries;if(!function(e){return(e.mcpNetworkAllowlist??[]).some((e=>e.trim().length>0))}(e))return[...AE];const r=(0,Lb.b6)(e);return r.includes("*")?[...AE]:r}(e):[],s=t?n?["*"]:r.entries:[];return JSON.stringify({enabled:t,mode:e.mcpNetworkMode,allow:n?[]:o,deny:s})}class DE extends Error{constructor(e,t){super(`MCP server "${e}" wasn't started: your team's MCP settings require it to run in a sandbox, and the sandbox isn't supported on this machine. Ask a team admin to review the team's MCP settings for this server.`),this.serverName=e,this.name="McpSandboxUnavailableError",void 0!==t&&(this.cause=t)}}const OE=new Set(["invalid_auth","not_authed","account_inactive","token_revoked","token_expired"]);class FE extends Error{constructor(){super("Your organization admin only allows Slack workspaces your company manages. Connect your company Slack workspace instead."),this.name="SlackWorkspaceNotManagedError"}}class NE extends Error{constructor(){super("Slack couldn't confirm which workspace this connection is for, and your organization admin only allows the Slack workspaces your company manages. Try again in a moment."),this.name="SlackWorkspaceUnconfirmedError"}}function LE(e){return URL.canParse(e)&&"mcp.slack.com"===new URL(e).hostname.toLowerCase()}function jE(e,t){const r=new Map,n=t.lookUpWorkspace??(t=>async function(e,t){let r;try{const n=await e("https://slack.com/api/auth.test",{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/x-www-form-urlencoded"},signal:AbortSignal.timeout(5e3)});r=await n.json()}catch{return{kind:"unavailable"}}if("object"!=typeof r||null===r)return{kind:"unavailable"};if("object"!=typeof(n=r)||null===n||Array.isArray(n))return{kind:"unavailable"};var n;const o=r;return!0!==o.ok?"string"==typeof o.error&&OE.has(o.error)?{kind:"dead"}:{kind:"unavailable"}:"string"!=typeof o.team_id||0===o.team_id.length?{kind:"unavailable"}:"string"==typeof o.enterprise_id&&o.enterprise_id.length>0?{kind:"found",slackTeamId:o.team_id,slackEnterpriseId:o.enterprise_id}:{kind:"found",slackTeamId:o.team_id}}(e,t));let o,s=[];return async(i,a)=>{if(!LE(function(e){return"string"==typeof e?e:e instanceof URL?e.href:e.url}(i)))return e(i,a);const c=function(e,t){const r=new Headers(t?.headers??(e instanceof Request?e.headers:void 0)),n=/^Bearer\s+(.+)$/i.exec(r.get("authorization")??"");return n?.[1]?.trim()||void 0}(i,a);if(void 0===c)return e(i,a);const l=await((void 0===o||Date.now()-o.atMs>=3e4)&&(o={atMs:Date.now(),lists:t.managedSlackWorkspaceLists().then((e=>"unconfirmed"===e?e:(s=e.filter((e=>e.length>0)).map((e=>e.map((e=>e.toUpperCase())))),s)),(()=>s))}),o.lists);if("unconfirmed"===l)throw new NE;if(0===l.length)return e(i,a);let u=r.get(c);if(void 0===u){const t=await n(c);if("dead"===t.kind)return e(i,a);if("unavailable"===t.kind)throw new NE;r.size>=64&&r.clear(),r.set(c,t),u=t}const d=[u.slackTeamId,u.slackEnterpriseId].flatMap((e=>void 0===e?[]:[e.toUpperCase()]));if(!l.every((e=>d.some((t=>e.includes(t))))))throw new FE;return e(i,a)}}function UE(e,t,r){if("string"==typeof e)return t(e);if(!(e instanceof Error))return e;if(r.results.has(e))return r.results.get(e)===e&&r.cycled.add(e),r.results.get(e);r.results.set(e,e);const n=Object.isFrozen(e)&&JE(e,t)?new Error:void 0;void 0!==n&&r.results.set(e,n);const o=t(e.message),s="string"==typeof e.stack?t(e.stack):void 0,i=Object.keys(e).flatMap((n=>{if("cause"===n)return[];const o=HE(e,n),s=VE(o,t,r);return Object.is(s,o)?[]:[[n,s]]})),a=Object.getOwnPropertyDescriptor(e,"cause"),c=void 0===a?void 0:HE(e,"cause"),l=VE(c,t,r),u=e instanceof AggregateError?HE(e,"errors"):void 0,d=function(e,t,r){if(!Array.isArray(e))return e;const n=e.map((e=>VE(e,t,r)));if(n.every(((t,r)=>Object.is(t,e[r]))))return e;try{return n.forEach(((t,r)=>{e[r]=t})),e}catch{return n}}(u,t,r),h=[...i,...Object.is(l,c)?[]:[["cause",l]],...Object.is(d,u)?[]:[["errors",d]]];let p=!1;if(void 0===n)try{o!==e.message&&(e.message=o),void 0!==s&&s!==e.stack&&(e.stack=s),p=e.message===o&&(void 0===s||e.stack===s)&&h.every((([t,r])=>WE(e,t,r)))}catch{}if(p)return e;const f=Object.defineProperties(n??new Error,{message:{value:o,writable:!0,enumerable:!1,configurable:!0},...Object.getOwnPropertyDescriptors(zE(e,new Map(i)))});Array.isArray(d)&&Object.defineProperty(f,"errors",{value:d,writable:!0,enumerable:!1,configurable:!0}),void 0!==a&&Object.defineProperty(f,"cause",{value:l,writable:!0,enumerable:!0===a.enumerable,configurable:!0});const m=Object.getPrototypeOf(e);null!==m&&"object"==typeof m&&m!==Error.prototype&&(Object.setPrototypeOf(f,m),function(e){try{let t=Object.getPrototypeOf(e);for(let r=0;r<8&&null!==t&&"object"==typeof t&&t!==Error.prototype&&t!==Object.prototype;r++){for(const r of Reflect.ownKeys(t)){const n=Object.getOwnPropertyDescriptor(t,r)?.get;void 0!==n&&Reflect.apply(n,e,[])}t=Object.getPrototypeOf(t)}String(e);const r=e;"function"==typeof r.toJSON&&Reflect.apply(r.toJSON,e,[""]);const n=r[qE];return"function"==typeof n&&Reflect.apply(n,e,[0,{depth:0,stylize:String},String]),!0}catch{return!1}}(f)||Object.setPrototypeOf(f,Error.prototype));const g=QE(e);return void 0!==g&&QE(f)!==g&&Object.defineProperty(f,"name",{value:g,writable:!0,configurable:!0,enumerable:!1}),void 0!==s&&(f.stack=s),r.results.set(e,f),f}function BE(e,t){if(e instanceof Error)return t.get(e)??e;if(!Array.isArray(e)||!Object.isFrozen(e))return e;const r=e.map((e=>e instanceof Error?t.get(e)??e:e));return r.every(((t,r)=>Object.is(t,e[r])))?e:r}function WE(e,t,r){const n=Object.getOwnPropertyDescriptor(e,t);return!0===n?.writable&&Reflect.defineProperty(e,t,{...n,value:r})}function HE(e,t){try{const r=Object.getOwnPropertyDescriptor(e,t);return void 0===r?.get?r?.value:r.get.call(e)}catch{return}}const qE=Symbol.for("nodejs.util.inspect.custom");function zE(e,t){const r={};for(const n of Object.keys(e))try{const o=Object.getOwnPropertyDescriptor(e,n),s=void 0===o?.get?o?.value:o.get.call(e);Object.defineProperty(r,n,{value:t.has(n)?t.get(n):s,writable:!0,enumerable:!0,configurable:!0})}catch{}return r}function GE(e,t,r,n){if("string"==typeof e)return t(e);if("object"!=typeof e||null===e)return e;if(e instanceof Error)return UE(e,t,n);if(Array.isArray(e)){if(r>=4)return;return e.slice(0,64).map((e=>GE(e,t,r+1,n)))}const o=Object.getPrototypeOf(e);return o!==Object.prototype&&null!==o?e:r>=4?void 0:function(e,t,r,n){const o={};for(const s of Object.keys(e).slice(0,64))try{const i=Object.getOwnPropertyDescriptor(e,s),a=void 0===i?.get?i?.value:i.get.call(e);Object.defineProperty(o,s,{value:GE(a,t,r,n),writable:!0,enumerable:!0,configurable:!0})}catch{}return o}(e,t,r+1,n)}function VE(e,t,r){if(e instanceof Error)return UE(e,t,r);try{return JE(e,t)?GE(e,t,1,r):e}catch{return}}const KE=4096;function JE(e,t){const r=new Set,n=[e];for(let o=0;n.length>0;o++){if(o>=KE||n.length>KE)return ZE(e,t);const s=n.pop();if("string"==typeof s){if(t(s)!==s)return!0}else if((XE(s)||s instanceof Error)&&!r.has(s)){r.add(s),s instanceof Error&&(n.push(HE(s,"message"),HE(s,"stack"),HE(s,"cause")),s instanceof AggregateError&&n.push(HE(s,"errors")));for(const e of Object.keys(s))n.push(HE(s,e))}}return!1}function ZE(e,t){const r=new Set;let n;try{n=JSON.stringify(e,((e,t)=>{return"bigint"==typeof t?t.toString():"object"!=typeof t||null===t?t:r.has(t)?void 0:(r.add(t),t instanceof Error?(n=t,{...Object.fromEntries(Object.keys(n).map((e=>[e,HE(n,e)]))),message:HE(n,"message"),stack:HE(n,"stack"),cause:HE(n,"cause"),...n instanceof AggregateError?{errors:HE(n,"errors")}:{}}):t);var n}))}catch{return!0}return void 0!==n&&t(n)!==n}function XE(e){if(Array.isArray(e))return!0;if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function QE(e){try{return"string"==typeof e.name?e.name:void 0}catch{return}}const YE=/spt_[A-Za-z0-9_]{6,}/g,ex=/[A-Z0-9]/;function tx(e){return function(e){return e.replace(YE,(e=>function(e){return e.slice(4).split("_").some((e=>e.length>=8&&ex.test(e)))}(e)?"[redacted Link shared payment token]":e))}(e)}var rx=r("../../node_modules/.pnpm/string-argv@0.3.2/node_modules/string-argv/index.js");new Set(["EAI_AGAIN","ECONNABORTED","ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ENOTFOUND","EPIPE","ETIMEDOUT","EADDRNOTAVAIL","UND_ERR_CONNECT_TIMEOUT"]),new Set(["ECONNRESET","EPIPE"]);const nx=new Set([429,502,503,504]);function ox(e){return"object"==typeof e&&null!==e}function sx(e){const t=ox(e)?e.code:void 0,r=(e instanceof Error||ox(e)&&"string"==typeof e.message?e.message:"").match(/\(HTTP (\d+)\)|Non-200 status code \((\d+)\)|\bHTTP\s+(\d{3})\b/i),n=r?.[1]??r?.[2]??r?.[3],o=void 0!==n?parseInt(n,10):void 0;if("number"==typeof t&&t>=100)return void 0!==o&&nx.has(o)&&!nx.has(t)?o:t;if("string"==typeof t&&/^\d{3}$/.test(t)){const e=Number.parseInt(t,10);return e>=100&&e<=599?e:o}return o}new Set(["UND_ERR_SOCKET","UND_ERR_CLOSED","ECONNRESET"]);const ix=8192;function ax(e){return void 0===e?"unknown":"url"in e&&e.url.length>0?void 0!==lb(e.url)?"rest_mcp":"streamable_http":"command"in e?"stdio":"unknown"}new Set(["ENOENT","EACCES","ENOTDIR","EPERM"]);const cx=/\$\{[^}]*\}/;function lx(e){if(void 0!==function(e){if(void 0===e)return;const t=e.trim();return 0!==t.length&&cx.test(t)?t:void 0}(e))return;const t=e?.trim();return t&&t.length>0?t:void 0}const ux=new Map;async function dx(e,t=fetch){if(void 0===lb(e))return;const r=new URL(e),n=`${r.origin}/.well-known/oauth-protected-resource${r.pathname.replace(/\/+$/,"")}`,o=ux.get(n);if(void 0!==o&&o.expiresAtMs>Date.now())return o.metadata;let s;try{const e=await t(n);if(!e.ok)return;s=function(e){if("object"!=typeof(t=e)||null===t)return{};var t;const r=e,n="string"==typeof r.cursor_client_id&&r.cursor_client_id.length>0?r.cursor_client_id:void 0;let o;if("object"==typeof r.cursor_authorization_params&&null!==r.cursor_authorization_params){const e=Object.entries(r.cursor_authorization_params).filter((e=>"string"==typeof e[1]));e.length>0&&(o=Object.fromEntries(e))}return{...void 0!==n?{clientId:n}:{},...!0===r.cursor_omit_resource_indicator?{omitResourceIndicator:!0}:{},...!0===r.cursor_omit_consent_prompt?{omitConsentPrompt:!0}:{},...void 0!==o?{authorizationParams:o}:{},...!0===r.cursor_rejects_custom_scheme_redirects?{rejectsCustomSchemeRedirects:!0}:{},...!0===r.cursor_unauthenticated_connect?{unauthenticatedConnect:!0}:{},...!0===r.cursor_loopback_ipv4?{loopbackIpv4:!0}:{},...!0===r.cursor_backend_only_token_exchange?{backendOnlyTokenExchange:!0}:{}}}(await e.json())}catch{return}return ux.set(n,{metadata:s,expiresAtMs:Date.now()+3e5}),s}(0,Es.J)((function(){ux.clear()}));const hx={info:()=>{},warn:()=>{},error:()=>{},debug:()=>{}};function px(e){return hx}const fx=/^[\x21\x23-\x5B\x5D-\x7E]+$/,mx=["invalid_request","invalid_token","insufficient_scope"];function gx(e){return mx.some((t=>t===e))}function wx(e){const t=new Set;for(const r of e)r.length<=200&&fx.test(r)&&t.add(r);return[...t]}const yx=/[!#$%&'*+.^_`|~0-9A-Za-z-]+/y,vx=/"((?:[^"\\]|\\.)*)"?/y,bx=/[^\s,]*/y;function Sx(e,t){let r,n=0;const o=t=>{t.lastIndex=n;const r=t.exec(e);return null!==r&&(n=t.lastIndex),r};for(;n"string"==typeof e&&e.length>0)):void 0}function Cx(e){if("object"!=typeof e||null===e||Array.isArray(e))return kx;const t=_x("grantedScopes"in e?e.grantedScopes:void 0),r=_x("requestedScopes"in e?e.requestedScopes:void 0);return{...void 0!==t?{grantedScopes:t}:{},stepUpScopes:_x("stepUpScopes"in e?e.stepUpScopes:void 0)??[],signInMissing:_x("signInMissing"in e?e.signInMissing:void 0)??[],...void 0!==r?{requestedScopes:r}:{}}}function Ex(e){return(e??"").split(/\s+/).filter((e=>e.length>0))}function xx(e,t){return e.filter((e=>!t.has(e)))}function Px(e){const t=Cb(e.serverUrl),r=e.connectorName??t?.displayName??e.accountKey,n=px(e.accountKey);let o;const s=async()=>Cx(await e.readRecord()),i=async t=>{if(void 0!==t.grantedScopes)return t.grantedScopes;const r=Ex(await e.readTokenScope());return r.length>0?r:void 0},a=(e,t)=>{n.info(`MCP OAuth scope step-up: ${e}`,{event:`mcp_oauth_scope_step_up_${e}`,...t})};return{accountKey:e.accountKey,connectorName:r,async decide(r){if(401!==r.status&&403!==r.status)return;const n=function(e){const t=e??"",r=Sx(t,"error")?.toLowerCase(),n=Sx(t,"resource_metadata");return{error:void 0===r||""===r?"none":gx(r)?r:"other",scopes:wx((Sx(t,"scope")??"").split(/\s+/)),resourceMetadata:void 0===n||""===n?void 0:n}}(r.wwwAuthenticate);if("insufficient_scope"!==n.error||0===n.scopes.length)return;if(function(e){try{return Eb.has(new URL(e).hostname.toLowerCase())}catch{return!1}}(e.serverUrl))return;const o=function(e,t){if(void 0!==t)try{return new URL(t).origin===new URL(e).origin?t:void 0}catch{return}}(e.serverUrl,n.resourceMetadata),c=void 0===t?await e.readScopesSupported(o).catch((()=>{})):void 0,l=await s(),u=await i(l),{accepted:d,dropped:h}=function(e){const t=new Set(e.granted??[]),r=[],n=[];for(const o of wx(e.named))e.allowlist.has(o)?t.has(o)||r.push(o):n.push(o);return{accepted:r,dropped:n}}({named:n.scopes,allowlist:(p={policy:t,scopesSupported:c,configuredScopes:e.configuredScopes},void 0!==p.policy?new Set([...p.policy.baseScopes,...Object.keys(p.policy.stepUpScopes)]):new Set([...p.scopesSupported??[],...p.configuredScopes??[]])),granted:u});var p;if(0===d.length)return void a("none_accepted",{status:r.status,namedCount:n.scopes.length,droppedCount:h.length});const f=new Set(l.signInMissing),m=d.every((e=>f.has(e)))?"blocked":"offer";return"offer"===m&&await e.writeRecord({...l,...void 0!==u?{grantedScopes:u}:{},stepUpScopes:[...new Set([...l.stepUpScopes,...d])]}),a(m,{status:r.status,acceptedCount:d.length,droppedCount:h.length}),{kind:m,status:r.status,scopes:d,dropped:h,toolName:r.toolName,resourceMetadataUrl:o}},signIn:async e=>(void 0===o&&(o=Promise.resolve().then(e).finally((()=>{o=void 0}))),o),get isSigningIn(){return void 0!==o},tokensForSdk(e){if(void 0===o||void 0===e?.refresh_token)return e;const{refresh_token:t,...r}=e;return r},async prepareAuthorization(){const t=await s();return{stepUpScopes:t.stepUpScopes.length>0?[...new Set([...await i(t)??[],...t.stepUpScopes])]:[],recordRequestedScopes:async t=>{await e.writeRecord({...await s(),requestedScopes:Ex(t.searchParams.get("scope"))})}}},async recordTokens(t,{isRefresh:r}){const n=await e.readRecord();if(void 0===n)return;const o=Cx(n),s=Ex(t.scope);if(r)return void(s.length>0&&await e.writeRecord({...o,grantedScopes:s}));if(void 0===o.requestedScopes)return;const i=s.length>0?s:o.requestedScopes,c=new Set(i),l=xx(o.requestedScopes,c);await e.writeRecord({grantedScopes:i,stepUpScopes:xx(o.stepUpScopes,c),signInMissing:l}),a("sign_in_recorded",{grantedCount:i.length,signInMissingCount:l.length,scopeReported:s.length>0})},async clear(t){await e.writeRecord(!0===t?.keepPendingScopes?function(e){const{stepUpScopes:t}=Cx(e);return t.length>0?{stepUpScopes:t,signInMissing:[]}:void 0}(await e.readRecord()):void 0)}}}function Rx(e){const t=Cb(e.serverUrl);for(const r of e.scopes){const e=t?.stepUpScopes[r]?.action;if(void 0!==e)return e}return e.toolTitle}function Ix(e){const t=function(e){return void 0===e.action?`${e.connectorName} needs a permission its sign-in did not grant.`:`${e.connectorName} needs one more permission to ${e.action}.`}({connectorName:e.connectorName,action:Rx(e)}),r="offer"===e.kind?`Authorize ${e.connectorName} again to approve it; the turn can continue once it's granted.`:`Its last sign-in did not grant ${1===e.scopes.length?"it":"them"}, so an admin or your consent is blocking this. Reconnect ${e.connectorName} from its MCP settings to ask again.`,n=function(e){if(0===e.length)return;const t=e.slice(0,3).join(", "),r=e.length-3;return`${1===e.length?"Permission":"Permissions"}: ${t}${r>0?` and ${r} more`:""}`}(e.scopes);return void 0===n?`${t} ${r}`:`${t} ${r}\n${n}`}class Tx extends Error{constructor(e,t,r){super(Ix({kind:e.kind,serverUrl:t,connectorName:r,scopes:e.scopes,toolTitle:e.toolName})),this.decision=e,this.serverUrl=t,this.connectorName=r,this.name="McpOAuthScopeStepUpError"}answerWithToolTitle(e){return Ix({kind:this.decision.kind,serverUrl:this.serverUrl,connectorName:this.connectorName,scopes:this.decision.scopes,toolTitle:e??this.decision.toolName})}}function Ax(e){if("string"!=typeof e)return;let t;try{t=JSON.parse(e)}catch{return}const r=Array.isArray(t)?t:[t];for(const e of r){if("object"!=typeof e||null===e||!("method"in e)||"tools/call"!==e.method)continue;const t="params"in e?e.params:void 0,r="object"==typeof t&&null!==t&&"name"in t?t.name:void 0;return"string"==typeof r?r:void 0}}function $x(e){return e instanceof Error&&/does not support dynamic client registration/i.test(e.message)}Error,Error;const Mx=new Set(["UnauthorizedError","InvalidGrantError","InvalidTokenError","InvalidClientError","UnauthorizedClientError"]),Dx=new Set(["invalid_grant","invalid_token","invalid_client","unauthorized_client"]),Ox=[/\btoken (?:has |is )?expired\b/i,/\btoken (?:was|is) invalid\b/i,/\binvalid (?:refresh[ _]?)?token\b/i,/\btoken (?:has been |was )?revoked\b/i];var Fx=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js");const Nx="2026-07-28",Lx=-32022,jx="io.modelcontextprotocol/protocolVersion",Ux="io.modelcontextprotocol/clientCapabilities",Bx="io.modelcontextprotocol/clientInfo",Wx="io.modelcontextprotocol/serverInfo",Hx={name:"cursor",version:"1.0.0"},qx=new Map;function zx(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Gx(e){const t=new URL(String(e));return t.hash="",t.href}function Vx(e,t){const r=qx.get(e);return!(void 0===r||r<=t()&&(qx.delete(e),1))}function Kx(e,t){try{return Gx(e)===t}catch{return!1}}function Jx(e){return(e.headers.get("content-type")??"").toLowerCase().includes("application/json")}const Zx=new Set(["events/subscribe","events/unsubscribe","events/poll","events/stream"]);function Xx(e,t,r,n,o=t.message){const s=new Headers(e?.headers);if(s.set("mcp-protocol-version",Nx),s.set("mcp-method",r),s.delete("mcp-session-id"),!t.isRequest&&o===t.message)return{...e,headers:s};const i=zx(o.params)?o.params:{},a=zx(i._meta)?i._meta:{},c=function(e,t){const r="tools/call"===e||"prompts/get"===e||Zx.has(e)?"name":"resources/read"===e?"uri":void 0,n=void 0===r?void 0:t[r];return"string"==typeof n?n:void 0}(r,i);void 0!==c&&s.set("mcp-name",c);const l=JSON.stringify({...o,params:{...i,_meta:{...a,[jx]:Nx,[Ux]:n.capabilities,[Bx]:n.clientInfo}}});return{...e,headers:s,body:l}}function Qx(e){return new Response(JSON.stringify({jsonrpc:"2.0",...e}),{status:200,headers:{"content-type":"application/json"}})}function Yx(e,t){const r=Gx(t.serverUrl),n=t.now??Date.now;let o={capabilities:{},clientInfo:{...Hx}},s=!1;const i=()=>s||Vx(r,n),a=async(t,i,a)=>{const{method:c,message:l}=t;if(void 0===c)return e(i,a);if("notifications/initialized"===c)return new Response(null,{status:202});if(t.isRequest&&"initialize"===c){const c={jsonrpc:"2.0",id:l.id,method:"server/discover",params:{}},u=await e(i,Xx(a,t,"server/discover",o,c)),d=await async function(e,t,r){if(!e.ok||!Jx(e))return e;let n;try{n=await e.clone().json()}catch{return e}if(!zx(n)||!zx(n.result))return e;const o=n.result,s=o.supportedVersions;if(!Array.isArray(s)||!s.includes(Nx))return Qx({id:t,error:{code:Lx,message:"Unsupported protocol version",data:{requested:Nx,supported:s??[]}}});const i=zx(o._meta)?o._meta:{},a=zx(i[Wx])?i[Wx]:{name:new URL(r).hostname,version:"unknown"};return Qx({id:t,result:{protocolVersion:Fx.aE,capabilities:zx(o.capabilities)?o.capabilities:{},serverInfo:a,..."string"==typeof o.instructions?{instructions:o.instructions}:{}}})}(u,l.id,r);return d!==u&&(s=!0,function(e,t){qx.set(e,t()+6e5)}(r,n)),d}return e(i,Xx(a,t,c,o))};return async(t,c)=>{const l=function(e,t,r){if("POST"!==(t?.method??"GET").toUpperCase()||"string"!=typeof t?.body||!Kx(e,r))return;let n;try{n=JSON.parse(t.body)}catch{return}if(!zx(n)||"2.0"!==n.jsonrpc)return;const o="string"==typeof n.method?n.method:void 0;return{message:n,method:o,isRequest:void 0!==o&&"id"in n}}(t,c,r);if(void 0===l)return function(e,t,r){return"GET"===(t?.method??"GET").toUpperCase()&&Kx(e,r)}(t,c,r)&&i()?new Response(null,{status:405}):e(t,c);if(l.isRequest&&"initialize"===l.method){const e=zx(l.message.params)?l.message.params:{};o={capabilities:zx(e.capabilities)?e.capabilities:{},clientInfo:zx(e.clientInfo)?e.clientInfo:o.clientInfo}}const u=l.isRequest&&"initialize"===l.method;if(u?Vx(r,n):i())return a(l,t,c);if(u&&(s=!1),!l.isRequest)return e(t,c);const d=await e(t,c);if(u&&await async function(e){if(e.status>=500||!Jx(e))return!1;const t=Number(e.headers.get("content-length"));if(Number.isFinite(t)&&t>4096)return!1;let r;try{r=await e.clone().json()}catch{return!1}if(!zx(r)||!zx(r.error))return!1;const n=r.error;if(n.code!==Lx||!zx(n.data))return!1;const o=n.data.supported;return Array.isArray(o)&&o.includes(Nx)}(d)){const e=await a(l,t,c);return s?e:d}return d}}function eP(e,t){if(void 0===t)return{headers:t,cursorAuthHeaderValue:void 0,cursorAuthOrigin:void 0};const r=Object.entries(t),n=r.find((([e])=>e.toLowerCase()===ab));if(void 0===n)return{headers:t,cursorAuthHeaderValue:void 0,cursorAuthOrigin:void 0};let o;try{o=new URL(e).origin}catch{o=void 0}return{headers:Object.fromEntries(r.filter((([e])=>e.toLowerCase()!==ab))),cursorAuthHeaderValue:n[1],cursorAuthOrigin:o}}function tP(e,t,r){return async(n,o)=>{let s;try{s=new URL("string"==typeof n?n:n.toString()).origin}catch{return r(n,o)}if(s!==t)return r(n,o);const i=await e();if(void 0===i||0===i.length)return r(n,o);const a=new Headers(o?.headers);return a.set(ab,i),r(n,{...o,headers:a,redirect:"manual"})}}class rP{constructor(e=864e5){this.ttl=e,this.staleDirty=!1,this.refreshGeneration=0}async get(e){const t=performance.now();if(this.state&&this.state.expiresAt>t&&!this.staleDirty)return this.state.value;if(this.staleDirty&&this.state){const t=this.state.value;if(!this.refreshInFlight){const t=this.refreshGeneration;let r;r=(async()=>{try{const r=await e();if(t!==this.refreshGeneration)return;this.state={expiresAt:performance.now()+this.ttl,value:r},this.staleDirty=!1}catch{}finally{r&&this.refreshInFlight===r&&(this.refreshInFlight=void 0)}})(),this.refreshInFlight=r}return t}const r=this.refreshGeneration,n=await e();return r!==this.refreshGeneration||(this.state={expiresAt:performance.now()+this.ttl,value:n},this.staleDirty=!1),n}invalidate(){this.refreshGeneration++,this.state=void 0,this.staleDirty=!1,this.refreshInFlight=void 0}invalidateKeepingStale(){this.state&&(this.staleDirty=!0)}}var nP=r("crypto");function oP(e){const t={};for(const[r,n]of Object.entries(e))void 0!==n&&(t[r]=n);return t}function sP(e,t){const r=function(e){try{const t=new URL(e);return{host:t.host,origin:t.origin,pathname:t.pathname}}catch{return{host:null,origin:null,pathname:null}}}(e),n=!1!==t?.includePath;return{host:r.host,origin:r.origin,path:n?r.pathname:null}}function iP(e,t){return sP(e,t)}function aP(e){if(e)return(0,nP.createHash)("sha256").update(e).digest("hex").slice(0,12)}function cP(e){if(e&&0!==e.length)return aP(JSON.stringify([...e].sort()))}function lP(e){return{clientIdHash:aP(e?.client_id),hasClientSecret:(e?.client_secret??"").length>0,redirectUrisHash:cP(e?.redirect_uris),redirectUriCount:e?.redirect_uris?.length??0}}function uP(e){return"object"==typeof e&&null!==e}function dP(e,t){let r=e;for(const e of t){if(!uP(r)||!(e in r))return;r=r[e]}return r}function hP(e,t){for(const r of t){const t=dP(e,r.split("."));if("string"==typeof t)return t}}function pP(e){if(!e||"object"!=typeof e)return;const t=e.errorCode;return"string"==typeof t?t:void 0}function fP(e){if(!e)return;const t=e.match(/\(HTTP (\d+)\)|Non-200 status code \((\d+)\)|\bHTTP\s+(\d{3})\b/i),r=t?.[1]??t?.[2]??t?.[3];if(!r)return;const n=Number.parseInt(r,10);return Number.isNaN(n)?void 0:n}const mP=e=>e;function gP(e,t){if(e instanceof Error){const r=e.message;return r&&r!==e.name?_P(t(r)):void 0}if("string"==typeof e||"number"==typeof e||"boolean"==typeof e){const r=String(e);return r?_P(t(r)):void 0}}function wP(e){if(e&&"object"==typeof e)return uP(e)?e.cause:void 0}function yP(e,t,r=4){const n=[];let o=e;for(let e=0;e1?n.join(" > "):void 0}const vP="[REDACTED]",bP=/(^|_|-)(token|secret|password|assertion|authorization|verifier|challenge|code)(_|-|$)/i;function SP(e){return e.replace(/(authorization[^:=\r\n]{0,32}[:=]\s*["']?)(?:[A-Za-z][\w.~+/-]*[ \t]+)?[^"',\s&}]+/gi,`$1${vP}`).replace(/((?:access_token|refresh_token|id_token|client_secret|code|password|assertion|token|secret)[^:=\r\n]{0,32}[:=]\s*["']?)([^"',\s&}]+)/gi,`$1${vP}`).replace(/(\bBearer\s+)([A-Za-z0-9\-._~+/]+=*)/gi,`$1${vP}`)}function kP(e,t=256){return e.length>t?`${e.slice(0,Math.max(0,t-3))}...`:e}function _P(e,t){return kP(SP(e),t?.maxLength)}function CP(e,t=mP){if("string"==typeof e)return kP(SP(t(e)));if(void 0!==e)try{const r=JSON.stringify(e,((e,r)=>e&&function(e){const t=e.toLowerCase();return"code"===t||"authorization"===t||t.includes("token")||t.includes("secret")||t.includes("password")||t.includes("assertion")||t.includes("verifier")||t.includes("challenge")||bP.test(t)}(e)?vP:"string"==typeof r?SP(t(r)):r));if(!r)return;return kP(r)}catch{return}}function EP(e,t=mP){const r=wP(e),n=e instanceof Error?e.name:null!=e?typeof e:void 0,o=r instanceof Error?r.name:void 0,s=gP(r,t),i=gP(e,t)??s,a=hP(e,["code","cause.code"]),c=pP(e)??pP(r)??hP(e,["errorCode","error","cause.errorCode","cause.error","body.error","response.body.error"]),l=void 0===c?void 0:_P(t(c)),u=function(e){for(const t of["status","statusCode","response.status","response.statusCode","cause.status","cause.statusCode","cause.response.status","cause.response.statusCode"]){const r=dP(e,t.split("."));if("number"==typeof r&&Number.isFinite(r))return r}}(e)??fP(i)??fP(s),d=CP(dP(e,["response","body"])??dP(e,["body"])??dP(e,["data"])??dP(e,["cause","body"])??dP(e,["cause","response","body"]),t),h=function(e){const t=e.message?.toLowerCase(),r=e.code?.toLowerCase();return t?.includes("timed out")||t?.includes("timeout")||t?.includes("etimedout")||"etimedout"===r?"timeout":t?.includes("enotfound")||t?.includes("eai_again")||t?.includes("dns")||"enotfound"===r||"eai_again"===r?"dns":t?.includes("certificate")||t?.includes("tls")||t?.includes("ssl")?"tls":t?.includes("econnreset")||t?.includes("connection reset")||"econnreset"===r?"connection_reset":t?.includes("econnrefused")||t?.includes("connection refused")||"econnrefused"===r?"connection_refused":void 0}({message:i,code:a}),p=l?"oauth_error":h?"auth_transport_error":i?"generic_error":void 0;return oP({errorName:n,errorMessage:i,errorType:null!=e?typeof e:void 0,httpStatus:u,oauthErrorCode:l,errorResponseSummary:d,networkClassification:h,causeName:o,causeMessage:s,causeChain:yP(e,t),sdkErrorKind:p})}const xP={mcp_oauth_provider_initialized:"MCP OAuth provider initialized",mcp_oauth_tokens_loaded:"MCP OAuth tokens loaded",mcp_oauth_tokens_saved:"MCP OAuth tokens saved",mcp_oauth_callback_completion:"MCP OAuth callback exchange completed",mcp_oauth_client_info_loaded:"MCP OAuth client information loaded",mcp_oauth_client_info_saved:"MCP OAuth client information saved",mcp_oauth_refresh_prepare:"MCP OAuth refresh prepared",mcp_oauth_refresh_error_release:"MCP OAuth refresh error released",mcp_oauth_state_transition:"MCP OAuth state transition",mcp_oauth_credentials_invalidated:"MCP OAuth credentials invalidated"};function PP(e){const t=e.message??xP[e.event],r={event:e.event,cursorMcp:{oauth:oP({...e.metadata})}},n=e.level??"info";"error"!==n?"warn"!==n?"debug"!==n?e.logger.info?.(t,r):e.logger.debug?.(t,r):e.logger.warn?.(t,r):e.logger.error?.(t,e.error,r)}const RP=new Map(["AWS4-HMAC-SHA256","Api-Key","ApiKey","Basic","Bearer","Bot","DPoP","Digest","GNAP","HOBA","Key","Mutual","NTLM","Negotiate","OAuth","PrivateToken","SCRAM-SHA-1","SCRAM-SHA-256","Token","vapid"].map((e=>[e.toLowerCase(),e]))),IP=4096;function TP(e){return"object"==typeof e&&null!==e&&"url"in e&&"string"==typeof e.url}function AP(e){return"string"==typeof e?e:e instanceof URL?e.toString():e.url}function $P(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function MP(e){if(e instanceof Headers)return e;if(Array.isArray(e)){const t=[];for(const r of e){if(!Array.isArray(r)||"string"!=typeof r[0]||"string"!=typeof r[1])return;t.push([r[0],r[1]])}return t}if($P(e)){const t={};for(const[r,n]of Object.entries(e)){if("string"!=typeof n)return;t[r]=n}return t}}function DP(e,t){const r=new Headers(MP(TP(e)?e.headers:void 0));return new Headers(MP(t?.headers)).forEach(((e,t)=>{r.set(t,e)})),r}function OP(e){const t=[];return e.forEach(((e,r)=>{t.push(r)})),t.sort()}function FP(e){if(null===e)return null;const t=Number.parseInt(e,10);return Number.isNaN(t)?null:t}function NP(e,t){if(null==e)return{kind:"none",bytes:0,contentLength:FP(t.get("content-length"))};if("string"==typeof e){const r=(new TextEncoder).encode(e).length;return{kind:"text",bytes:r,contentLength:FP(t.get("content-length"))??r}}if(e instanceof URLSearchParams){const r=e.toString(),n=(new TextEncoder).encode(r).length;return{kind:"text",bytes:n,contentLength:FP(t.get("content-length"))??n}}return e instanceof Blob?{kind:"blob",bytes:e.size,contentLength:FP(t.get("content-length"))??e.size}:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?{kind:"binary",bytes:e.byteLength,contentLength:FP(t.get("content-length"))??e.byteLength}:"object"==typeof e&&null!==e&&("getReader"in e||Symbol.asyncIterator in e)?{kind:"stream",bytes:null,contentLength:FP(t.get("content-length"))}:{kind:"unknown",bytes:null,contentLength:FP(t.get("content-length"))}}function LP(e,t){if(null===e||!e.toLowerCase().startsWith("application/x-www-form-urlencoded"))return;const r="string"==typeof t?function(e){for(const t of e.split("&")){const e=t.indexOf("="),r=e>=0?t.slice(0,e):t;let n;try{n=decodeURIComponent(r.replaceAll("+"," "))}catch{return}if("grant_type"!==n)continue;const o=e>=0?t.slice(e+1):"";try{return decodeURIComponent(o.replaceAll("+"," "))}catch{return}}}(t):t instanceof URLSearchParams?t.get("grant_type")??void 0:void 0;return r?function(e){switch(e){case"authorization_code":case"refresh_token":case"client_credentials":case"urn:ietf:params:oauth:grant-type:jwt-bearer":case"urn:ietf:params:oauth:grant-type:token-exchange":return e;default:return"other"}}(r):void 0}function jP(e){const{input:t,init:r}=e,n=sP(AP(t)),o=DP(t,r),s=OP(o),i=o.get("content-type"),a=aP(o.get("mcp-session-id")??void 0),c=function(e){if(!e)return null;const t=e.trim().split(/\s+/,1)[0]??"";return RP.get(t.toLowerCase())??"unrecognized"}(o.get("authorization"));return{method:(r?.method??(TP(t)?t.method:void 0)??"GET").toUpperCase(),url:n,headers:{names:s,count:s.length},contentType:i,body:NP(r?.body,o),sessionIdHash:a??null,authorizationScheme:c}}function UP(e,t){const r=OP(e.headers),n=FP(e.headers.get("content-length"));return{status:e.status,ok:e.ok,headers:{names:r,count:r.length},contentType:e.headers.get("content-type"),body:{kind:null===e.body?"none":"stream",bytes:null===e.body?0:n,contentLength:n,...void 0!==t?{errorSummary:t}:{}},sessionIdHash:aP(e.headers.get("mcp-session-id")??void 0)??null,wwwAuthenticateHash:aP(e.headers.get("www-authenticate")??void 0)??null,mcpProtocolVersion:e.headers.get("mcp-protocol-version")??null,requestId:e.headers.get("x-request-id")??null,retryAfter:BP(e.headers,"retry-after"),slackRateLimitType:BP(e.headers,"x-slack-ratelimit-type")}}function BP(e,t){return e.get(t)?.slice(0,64)??null}function WP(e){const t={};return void 0!==e.errorName&&(t.name=e.errorName),void 0!==e.errorMessage&&(t.message=e.errorMessage),void 0!==e.errorType&&(t.type=e.errorType),void 0!==e.oauthErrorCode&&(t.oauthErrorCode=e.oauthErrorCode),void 0!==e.errorResponseSummary&&(t.responseSummary=e.errorResponseSummary),void 0!==e.networkClassification&&(t.networkClassification=e.networkClassification),void 0!==e.sdkErrorKind&&(t.sdkErrorKind=e.sdkErrorKind),t}function HP(e,t){const r=jP({input:e,init:t});if(void 0!==LP(r.contentType,t?.body))return!0;const n=r.url.path?.toLowerCase()??"";return n.endsWith("/token")||n.includes("/oauth/token")||n.includes("/connect/token")}const qP=e=>e,zP="REDACTED_SESSION_ID",GP=/\b00D[A-Za-z0-9]{12,15}![A-Za-z0-9._]{20,512}/g;async function VP(e,t,r){try{const n=r(await e.clone().text());return n.length>t?n.slice(0,t):n}catch{return}}async function KP(e){if(!HP(e.input,e.init))return;const t=await VP(e.response,IP,e.redact);if(void 0!==t)try{return CP(JSON.parse(t))}catch{return _P(t,{maxLength:IP})}}async function JP(e){const t=await async function(e,t,r){try{if(t.ok)return;const n=t.headers.get("content-type")?.toLowerCase()??"";if(!n.includes("json")&&!n.includes("text"))return;const o=await VP(t,IP,r);if(void 0===o)return;return function(e){if("/mcp"!==(t=sP(AP(e.input)).path)&&!0!==t?.endsWith("/mcp"))return _P(e.rawText,{maxLength:IP});var t;try{const t=JSON.parse(e.rawText);return $P(t)?function(e){const t=e.error;if("string"==typeof t)return JSON.stringify({error:t});if("object"!=typeof t||null===t)return;if(!$P(t))return;const r=t,n="number"==typeof r.code||"string"==typeof r.code?r.code:void 0,o="string"==typeof r.message?_P(r.message,{maxLength:IP}):void 0;return void 0!==n||void 0!==o?JSON.stringify({...void 0!==n?{code:n}:{},...void 0!==o?{message:o}:{}}):void 0}(t):void 0}catch{return}}({input:e,rawText:o})}catch{return}}(e.input,e.response,e.redact);return{responseErrorSummary:t,oauthTokenErrorBodySummary:void 0===t?await KP({input:e.input,response:e.response,init:e.init,redact:e.redact}):void 0}}function ZP(e,t,r){try{e()}catch{t.warn?.("MCP HTTP exchange logging failed",{event:"mcp_http_exchange_logging_failure",phase:r})}}function XP(e,t,r){if("string"==typeof e)return t(e);if("object"!=typeof e||null===e||r>12)return e;if(Array.isArray(e))return e.map((e=>XP(e,t,r+1)));const n=Object.getPrototypeOf(e);return n!==Object.prototype&&null!==n?e:Object.fromEntries(Object.entries(e).map((([e,n])=>[e,XP(n,t,r+1)])))}function QP(e,t){const r=e=>{const r=XP(e,t,0);return $P(r)?r:void 0};return{debug:(t,n)=>e.debug?.(t,r(n)),info:(t,n)=>e.info?.(t,r(n)),warn:(t,n)=>e.warn?.(t,r(n))}}function YP(e){const{fetch:t,logSuccessfulExchanges:r=!0,redactLogText:n}=e,o=void 0===n?e.logger:QP(e.logger,n);return async(s,i)=>{const a=Date.now(),c="function"==typeof e.metadata?e.metadata(s):e.metadata,l=!0===e.redactEchoedSessionId?function(e,t,r){const n=DP(e,t).get("mcp-session-id")?.trim()??"";return e=>{const t=n.length>=8?e.split(n).join(zP):e;return r(t.replace(GP,zP))}}(s,i,n??qP):n??qP;try{const e=await t(s,i),{responseErrorSummary:n,oauthTokenErrorBodySummary:u}=e.ok?{}:await JP({input:s,init:i,response:e,redact:l});return!r&&e.ok||ZP((()=>{!function(e){const{logger:t,response:r}=e,n=function(e){const{input:t,init:r,response:n,durationMs:o,metadata:s,responseErrorSummary:i,oauthTokenErrorBodySummary:a}=e,c=jP({input:t,init:r}),l=LP(c.contentType,r?.body);return{event:"mcp_http_exchange",outcome:n.ok?"success":"http_error",durationMs:o,cursorMcp:{transport:{...s,request:c,response:UP(n,i),...void 0!==l?{oauth:{grantType:l}}:{},...void 0!==a?{oauthTokenErrorBodySummary:a}:{}}}}}(e);r.ok?t.info?.("MCP HTTP exchange completed",n):function(e){return 401===e.response.status&&null===e.request.authorizationScheme&&e.response.headers.has("www-authenticate")&&!HP(e.input,e.init)}({response:r,request:n.cursorMcp.transport.request,input:e.input,init:e.init})?t.debug?.("MCP HTTP exchange completed",n):t.warn?.("MCP HTTP exchange completed",n)}({logger:o,input:s,init:i,response:e,durationMs:Date.now()-a,metadata:c,responseErrorSummary:n,oauthTokenErrorBodySummary:u})}),o,"success"),e}catch(t){const r=function(e){if(!uP(e))return;const t=uP(e.cause)?e.cause:void 0,r=[e.response,t?.response];for(const e of r)if("object"==typeof(n=e)&&null!==n&&"status"in n&&"number"==typeof n.status&&"headers"in n&&"object"==typeof n.headers&&null!==n.headers&&"get"in n.headers&&"function"==typeof n.headers.get)return e;var n}(t),{responseErrorSummary:u,oauthTokenErrorBodySummary:d}=r?await JP({input:s,init:i,response:r,redact:l}):{};throw ZP((()=>{!function(e){const{logger:t}=e;t.warn?.("MCP HTTP exchange failed",function(e){const{input:t,init:r,error:n,durationMs:o,metadata:s,responseFromError:i,responseErrorSummary:a,oauthTokenErrorBodySummary:c}=e,l=EP(n,e.redactLogText),u=jP({input:t,init:r}),d=LP(u.contentType,r?.body);return{event:"mcp_http_exchange",outcome:"error",durationMs:o,cursorMcp:{transport:{...s,request:u,response:void 0!==i?UP(i,a):{status:l.httpStatus??null,ok:null,headers:{names:[],count:0},contentType:null,body:{kind:"none",bytes:null,contentLength:null,...void 0!==a?{errorSummary:a}:{}},requestId:null,sessionIdHash:null,wwwAuthenticateHash:null,mcpProtocolVersion:null,retryAfter:null,slackRateLimitType:null},...void 0!==d?{oauth:{grantType:d}}:{},...void 0!==c?{oauthTokenErrorBodySummary:c}:{},error:WP(l)}}}}(e))}({logger:o,input:s,init:i,error:t,durationMs:Date.now()-a,metadata:c,responseFromError:r,responseErrorSummary:u,oauthTokenErrorBodySummary:d,redactLogText:!0===e.redactEchoedSessionId?l:n})}),o,"failure"),t}}}function eR(e,t){const r=e?.access_token,n="string"==typeof r?r.length:0,o=Boolean(e?.refresh_token),s="number"==typeof e?.expires_in&&Number.isFinite(e.expires_in)?e.expires_in:null;return{accessTokenLen:n,refreshTokenPresent:o,expiresAtTimestamp:t?.expiresInIsFresh&&null!==s?Date.now()+Math.round(1e3*s):null,grantedScope:"string"==typeof e?.scope&&e.scope.length>0?e.scope:null}}function tR(e){const t=function(e){if(!e||"object"!=typeof e)return;const t=e.code;if("number"==typeof t&&t>=100&&t<=599)return t;if("string"==typeof t&&/^\d{3}$/.test(t)&&Number(t)>=100&&Number(t)<=599)return Number(t);const r=e instanceof Error||"object"==typeof e&&null!==e&&"message"in e&&"string"==typeof e.message?e.message:void 0;if(!r)return;const n=r.match(/\bHTTP\s+(\d{3})\b/i);if(!n?.[1])return;const o=Number.parseInt(n[1],10);return Number.isNaN(o)?void 0:o}(e);return void 0!==t?400===t||404===t||405===t:!!(e instanceof Error&&e.message.toLowerCase().includes("sessionid must be provided"))||function(e){if(!(e instanceof Error))return!1;const t="code"in e&&"string"==typeof e.code?e.code:void 0,r="cause"in e&&"object"==typeof e.cause&&null!==e.cause&&"code"in e.cause&&"string"==typeof e.cause.code?e.cause.code:void 0;return"ECONNREFUSED"===t||"ECONNREFUSED"===r||e.message.includes("ECONNREFUSED")}(e)}function rR(e,t=process.env){const r=t.TMPDIR,n={...void 0===r?{}:{TMPDIR:r},...e},{NODE_COMPILE_CACHE:o,...s}=n;return{...s,NODE_DISABLE_COMPILE_CACHE:"1"}}const nR=["PYTHONIOENCODING","PYTHONUTF8","PYTHONLEGACYWINDOWSSTDIO"],oR=[".exe",".cmd",".bat"],sR=/^pythonw?(?:\d+(?:\.\d+)*t?)?$/,iR=new Set(["py","pyw"]),aR=new Set(["--cache-dir","--color","--allow-insecure-host","--directory","--project","--config-file"]),cR=new Set;function lR(e){return nR.some((t=>function(e,t){const r=t.toUpperCase();return Object.entries(e).some((([e,t])=>void 0!==t&&e.toUpperCase()===r))}(e,t)))}function uR(e,t){for(let r=0;r=2&&e.endsWith(t)?e.slice(1,-1):e}(e.trim())).toLowerCase();for(const e of oR)if(t.endsWith(e))return t.slice(0,-e.length);return t}(e);if(sR.test(r)||iR.has(r)||"uvx"===r)return!0;if("uv"===r){const e=uR(t,aR);return"run"===e?.value||"tool"===e?.value&&"run"===uR(e.rest,aR)?.value}return"pipx"===r&&"run"===uR(t,cR)?.value}(n,o)?lR(i)||lR(r)?i:{...i,PYTHONIOENCODING:"utf-8:surrogateescape"}:i}async function hR(e){const t=[],r=new Set;let n;for(let o=1;;o++){const s=await e.fetchPage(n),i=e.itemsOf(s);t.push(...i);const a=e.nextCursorOf(s);if(!a||r.has(a))return t;if(o>=1e3)throw new Error("MCP list did not end after 1000 pages; refusing to keep paging");r.add(a),n=a}}var pR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"),fR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js"),mR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js"),gR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js");var wR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js");function yR(e){return`${typeof e}:${String(e)}`}function vR(e){const t=new Map,r=new Set,n=new Set,o=e=>{for(const t of n)t(e)},s=e=>{t.delete(e),r.delete(e)},i=e.send.bind(e);e.send=(e,n)=>((e=>{if("method"in e)if("tools/call"===e.method&&"id"in e){const r=e.params?.name;"string"==typeof r&&t.set(yR(e.id),r)}else if("notifications/cancelled"===e.method){const n=e.params?.requestId;if("string"!=typeof n&&"number"!=typeof n)return;const o=yR(n);if(!t.has(o))return;if(r.add(o),r.size>64){const e=r.values().next().value;void 0!==e&&s(e)}}})(e),i(e,n));const a=e.onmessage;return e.onmessage=(e,n)=>{(e=>{if("method"in e)return void("notifications/tools/list_changed"===e.method&&o({kind:"tools_list_changed"}));if(!("id"in e))return;const n=e.id;if("string"!=typeof n&&"number"!=typeof n)return;const i=yR(n),a=t.get(i);if(void 0===a)return;const c=r.has(i);if(s(i),!c)return;const l="error"in e||"object"==typeof e.result&&null!==e.result&&"isError"in e.result&&!0===e.result.isError;o({kind:"late_tool_result",toolName:a,isError:l})})(e),a?.(e,n)},{subscribe:e=>(n.add(e),()=>{n.delete(e)})}}function bR(e){const t=Object.entries(e.headers??{}).map((([e,t])=>[e.toLowerCase(),t])).sort((([e],[t])=>et?1:0));return(0,ko.createHash)("sha256").update(JSON.stringify([e.url,t,e.accessToken??null])).digest("hex")}class SR{constructor(e,t){this.inner=e,this.initializeResult=t,e.onclose=()=>this.onclose?.(),e.onerror=e=>this.onerror?.(e),e.onmessage=e=>this.onmessage?.(e)}get sessionId(){return this.inner.sessionId}setProtocolVersion(e){this.inner.setProtocolVersion(e)}start(){return this.inner.start()}close(){return this.inner.close()}async send(e,t){if((0,Fx.vo)(e)&&(0,Fx.eK)(e)){const t={jsonrpc:"2.0",id:e.id,result:this.initializeResult};queueMicrotask((()=>this.onmessage?.(t)))}else(0,Fx.wU)(e)||await this.inner.send(e,t)}}const kR=Be.object({tools:Be.array(Be.unknown()),nextCursor:Be.unknown().optional(),_meta:Be.unknown().optional()}),_R={typeFilled:0,toolDropped:0,outputStripped:0};function CR(e){if(TR(e))return"string"==typeof e.name?e.name:void 0}function ER(e){return xR(e.issues.filter((e=>"outputSchema"===e.path[0])))}function xR(e){return e.map((e=>`${e.path.map(String).join(".")}: ${e.message}`))}function PR(e){if(!TR(e))return e;const t={...e};return delete t.outputSchema,t}function RR(e){return TR(e)&&!("type"in e)}function IR(e,t){return{...e,inputSchema:{type:"object",...t}}}function TR(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var AR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js");const $R=new class{constructor({maxSchemasPerCompiler:e=2048,createCompiler:t=()=>new AR.p}={}){this.compiled=new Map,this.maxSchemasPerCompiler=e,this.createCompiler=t,this.compiler=t()}get compiledSchemaCount(){return this.compiled.size}getValidator(e){let t;return r=>(t??=this.compile(e),t(r))}compile(e){const t=JSON.stringify(e),r=(0,ko.createHash)("sha256").update(t).digest("base64url"),n=this.compiled.get(r);if(void 0!==n)return n;this.compiled.size>=this.maxSchemasPerCompiler&&(this.compiler=this.createCompiler(),this.compiled.clear());const o=(t.includes('"$id"')?this.createCompiler():this.compiler).getValidator(e);return this.compiled.set(r,o),o}};class MR{constructor(){this.decoder=new TextDecoder("utf-8"),this.captured="",this.capturedBytes=0}push(e){const t="string"==typeof e?e:this.decoder.decode(e,{stream:!0});return this.append(t),t}end(){const e=this.decoder.decode();return this.append(e),e}get text(){return this.captured}get full(){return this.capturedBytes>=ix}append(e){const t=ix-this.capturedBytes;if(t<=0||0===e.length)return;const r=function(e,t){if(!(t>0))return"";if(3*e.length<=t)return e;const{read:r}=Yo(e,Math.trunc(t));return r>=e.length?e:e.slice(0,r)}(e,t);this.captured+=r,this.capturedBytes=r.length=100&&t<=599?{error_class:"http",error_code:String(t),transport:e.transport}:void 0!==e.error||!0===e.failed?{error_class:"other",error_code:"exception",transport:e.transport}:!0===e.isError?{error_class:"payload",error_code:"is_error",transport:e.transport}:{error_class:"none",error_code:"none",transport:e.transport}}({transport:ax(t),...r}))}catch{}}const UR=(0,h.Pu)("mcp_tool.oauth_scope_step_up",{description:"A tools/call refused for a missing OAuth scope, by step-up decision",labelNames:["decision","dropped"]});function BR(e){return void 0===e?"unknown":"url"in e?"http":"stdio"}const WR=["authorization_code","refresh_token"],HR=["code"];class qR{constructor(e){this._refreshInProgress=!1,this._identifier=e.identifier,this._redirectUrl=e.redirectUrl,this._serverUrl=e.serverUrl,this._restMcpProviderMetadata=e.restMcpProviderMetadata,this.validateResourceURL=!0===e.restMcpProviderMetadata?.omitResourceIndicator?async()=>{}:function(e,t){if(function(e,t){const r=t.gtmApiOrigin;if(void 0===e||void 0===r)return!1;let n,o;try{n=new URL(e),o=new URL(r)}catch{return!1}return n.protocol===o.protocol&&n.hostname===o.hostname&&""===n.port&&"/mcp"===n.pathname}(e,t))return async()=>{};const r=kb(e);return void 0!==r&&function(e){return"https:"===e.protocol&&e.hostname===new URL(ub).hostname}(r)?async()=>{}:void 0!==r&&function(e){return"https:"===e.protocol&&"setup.shopify.com"===e.hostname&&""===e.port&&"/mcp"===e.pathname}(r)?_b:bb}(e.serverUrl,e.gtmMcpMatch),this._clientMetadata=e.clientMetadata,this._scopes=e.scopes,this._isScopePinGateEnabled=e.isScopePinGateEnabled,this.scopeStepUp=e.scopeStepUp,this._tokens=e.tokens,this._clientInformation=e.clientInformation,this._saveTokens=e.saveTokens,this._prepareForRefresh=e.prepareForRefresh,this._releaseRefreshLeaseOnError=e.releaseRefreshLeaseOnError,this._invalidateCredentials=e.invalidateCredentials,this._saveClientInformation=e.saveClientInformation,this.addClientAuthentication=e.addClientAuthentication}get redirectUrl(){return this._redirectUrl}get clientMetadata(){return this._clientMetadata}state(){return this._oauthAttemptId=(0,ko.randomUUID)(),this._oauthState=function(e,t,r){const n={id:e,owner:t,...r?{attemptId:r}:{}};return Buffer.from(JSON.stringify(n),"utf8").toString("base64url")}(this._identifier,{workspaceId:this._redirectUrl},this._oauthAttemptId),this._oauthState}clientInformation(){return this._clientInformation}hasClientInformation(){return void 0!==this._clientInformation}async saveClientInformation(e){this._clientInformation=e,await this._saveClientInformation(e)}tokens(){return this.scopeStepUp?.tokensForSdk(this._tokens)??this._tokens}async saveTokens(e){const t=this._refreshInProgress;this._refreshInProgress=!1,this._tokens=e,await this._saveTokens(e),await(this.scopeStepUp?.recordTokens(e,{isRefresh:t}))}async prepareForRefresh(){await(this._prepareForRefresh?.()),this._refreshInProgress=!0}async releaseRefreshLeaseOnError(e){this._refreshInProgress=!1,await(this._releaseRefreshLeaseOnError?.(e))}async invalidateCredentials(e){switch(this._refreshInProgress=!1,e){case"tokens":this._tokens=void 0;break;case"client":this._clientInformation=void 0;break;case"verifier":this._codeVerifier=void 0,this._oauthState=void 0,this._oauthAttemptId=void 0;break;case"all":this._tokens=void 0,this._clientInformation=void 0,this._codeVerifier=void 0,this._oauthState=void 0,this._oauthAttemptId=void 0,this._lastRedirectUrl=void 0,await(this.scopeStepUp?.clear({keepPendingScopes:!0}));break;default:return e}await(this._invalidateCredentials?.(e))}async redirectToAuthorization(e){const t=await(this.scopeStepUp?.prepareAuthorization());(function(e,t,r={}){const n=r.stepUpScopes??[],o=void 0!==t&&t.length>0?t:n.length>0?(e.searchParams.get("scope")??"").split(" ").filter((e=>e.length>0)):void 0;var s;void 0!==o&&e.searchParams.set("scope",(s={scopes:o,stepUpScopes:n},[...new Set([...s.scopes,...s.stepUpScopes])]).join(" "))})(e,function(e,t,r){const n=yb(e);return!0!==n?.pinsScopesOverConfiguredScopes?void 0!==t&&t.length>0||void 0===r?t:Cb(e)?.baseScopes??t:void 0!==n.scopesPinGate&&!0!==r?.(n.scopesPinGate)?t:n.scopes??t}(this._serverUrl??"",this._scopes,this._isScopePinGateEnabled),{stepUpScopes:t?.stepUpScopes}),void 0!==this._serverUrl&&function(e,t){const r=yb(t)?.authorizationParams;if(void 0!==r)for(const[t,n]of Object.entries(r))e.searchParams.set(t,n)}(e,this._serverUrl);for(const[t,r]of Object.entries(this._restMcpProviderMetadata?.authorizationParams??{}))e.searchParams.set(t,r);(!0===this._restMcpProviderMetadata?.omitConsentPrompt||function(e){return"login.microsoftonline.com"===e.hostname}(e))&&function(e){const t=new Set(e.searchParams.getAll("prompt").flatMap((e=>e.split(" "))).filter((e=>""!==e&&"consent"!==e)));e.searchParams.delete("prompt"),t.size>0&&e.searchParams.set("prompt",[...t].join(" "))}(e),await(t?.recordRequestedScopes(e)),this._lastRedirectUrl=e}get lastRedirectUrl(){return this._lastRedirectUrl}async saveCodeVerifier(e){this._codeVerifier=e}codeVerifier(){if(!this._codeVerifier)throw new Error("No code verifier saved");return this._codeVerifier}}async function zR(e){const{serverName:t,config:n,tokenStorage:o}=e,s=await dx(n.url,e.fetchImpl),i=Db({loopbackIpv4:s?.loopbackIpv4,redirectUrl:e.authRedirectUrl}),a=function(e,t){const r=lx(e?.CLIENT_ID);if(void 0!==r)return{client_id:r,...e?.CLIENT_SECRET?{client_secret:e.CLIENT_SECRET}:{},redirect_uris:Ob(t),grant_types:[...WR],response_types:[...HR],token_endpoint_auth_method:"none"}}(n.auth,i),c=function({storedClientInformation:e,staticClientInformation:t}){return t?e&&e.client_id===t.client_id?{...t,...e,client_secret:t.client_secret??e.client_secret,redirect_uris:t.redirect_uris,grant_types:e.grant_types??t.grant_types,response_types:e.response_types??t.response_types,token_endpoint_auth_method:e.token_endpoint_auth_method??t.token_endpoint_auth_method}:t:e}({storedClientInformation:await o.loadClientInformation(),staticClientInformation:a});return new qR({identifier:t,redirectUrl:i,serverUrl:n.url,restMcpProviderMetadata:s,gtmMcpMatch:e.gtmMcpMatch??{gtmApiOrigin:void 0},clientMetadata:{redirect_uris:Ob(i),token_endpoint_auth_method:"none",grant_types:[...WR],response_types:[...HR],client_name:"Cursor",logo_uri:"https://ptht05hbb1ssoooe.public.blob.vercel-storage.com/assets/uploads/cursorlogomcpv3.svg"},scopes:n.auth?.scopes,isScopePinGateEnabled:e.isScopePinGateEnabled,...!0===e.scopeChallengeStepUp&&void 0!==o.loadScopeStepUpRecord&&void 0!==o.saveScopeStepUpRecord?{scopeStepUp:Px({serverUrl:n.url,accountKey:t,configuredScopes:n.auth?.scopes,readTokenScope:async()=>void 0!==o.loadGrantedScope?o.loadGrantedScope():(await o.loadTokens())?.scope,readRecord:async()=>o.loadScopeStepUpRecord?.(),writeRecord:async e=>o.saveScopeStepUpRecord?.(e),readScopesSupported:t=>async function(e){try{const{discoverAuthorizationServerMetadata:t,discoverOAuthProtectedResourceMetadata:n}=await Promise.resolve().then(r.bind(r,"../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js")),o=await n(e.serverUrl,void 0!==e.resourceMetadataUrl?{resourceMetadataUrl:new URL(e.resourceMetadataUrl)}:void 0,e.fetch),s=await t(o.authorization_servers?.[0]??new URL("/",e.serverUrl),{fetchFn:e.fetch}).catch((()=>{}));if(void 0===s&&!0===e.requireAuthorizationServerMetadata)return;const i=new Set([...o.scopes_supported??[],...s?.scopes_supported??[]]);return i.size>0?[...i]:void 0}catch{return}}({serverUrl:n.url,resourceMetadataUrl:t,fetch:e.fetchImpl})})}:{},tokens:await o.loadTokens(),clientInformation:c,saveTokens:e=>o.saveTokens(e),prepareForRefresh:()=>o.prepareForRefresh?.()??Promise.resolve(),releaseRefreshLeaseOnError:e=>o.releaseRefreshLeaseOnError?.(e)??Promise.resolve(),invalidateCredentials:o.invalidateCredentials?e=>o.invalidateCredentials(e):void 0,saveClientInformation:e=>o.saveClientInformation(e),addClientAuthentication:o.tokenEndpointAuth?.({clientId:c?.client_id})})}const GR=new Set;let VR=!1;function KR(){for(const e of GR)try{process.kill(e,"SIGKILL")}catch{}}function JR(e){return $x(e)?new pR.D_:e}function ZR(e,t){return Yx(e??globalThis.fetch.bind(globalThis),{serverUrl:t})}function XR(e,t,r){const n=eP(e,t),o=r??(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),s=void 0!==n.cursorAuthHeaderValue&&void 0!==n.cursorAuthOrigin&&void 0!==o?tP((()=>n.cursorAuthHeaderValue),n.cursorAuthOrigin,o):o;return{transportHeaders:n.headers,baseFetch:s}}class QR{constructor(e,t,r){this._toolListGeneration=0,this._toolListSuccessGeneration=0,this._toolListStateGeneration=0,this._callToolLock=Promise.resolve(),this._callToolQueueDepth=0,this._stateEnteredAtMs=Date.now(),this._terminatingSession=!1,this._closeRequested=!1,this.serverName=e,this.client=t,this.tools=new rP,this.stateValue=r.initialState,this._authProvider=r.authProvider,this._authCodeExchange=r.authCodeExchange,this._sessionId=r.sessionId,this._protocolVersion=r.protocolVersion,this._resumedInstructions=r.resumedInstructions,this._sessionlessInitialize=r.sessionlessInitialize,this.config=r.config,this._oauthLifecycleLogger=r.oauthLifecycleLogger,this._serverSignals=r.serverSignals,this._redactLogText=r.redactLogText,this.setupElicitationHandler(),!0===r.stdioServer&&(t.onclose=()=>{this._closeRequested||(this.updateState({kind:"error",message:"MCP server exited"},"stdio_exited"),this.tools.invalidate())})}_stateKindLabel(e){return"requires_authentication"===e.kind?"needsAuth":e.kind}_logStateTransition(e,t,r,n){if(!this._oauthLifecycleLogger)return;const o=this._stateKindLabel(e),s=this._stateKindLabel(t);if(o===s)return;const i=Date.now()-this._stateEnteredAtMs,a=(()=>{try{const e=this.config&&"url"in this.config?this.config.url:void 0;return e?new URL(e).host:void 0}catch{return}})();PP({logger:this._oauthLifecycleLogger,event:"mcp_oauth_state_transition",metadata:{identifier:this.serverName,from:o,to:s,cause:r,serverUrlHost:a,previousStateDurationMs:i,...n}})}static createClient(e={}){const t={elicitation:{form:{}},...!1===e.mcpAppsUi?{}:{extensions:{"io.modelcontextprotocol/ui":{mimeTypes:["text/html;profile=mcp-app"]}}}};return new wR.K({name:"Cursor",version:"1.0.0"},{capabilities:t,jsonSchemaValidator:$R})}setupElicitationHandler(){this.client.setRequestHandler(Fx.$9,(async e=>{if(!this._currentElicitationProvider)return{action:"decline"};if(!("requestedSchema"in e.params))return{action:"decline"};try{const t=e.params.requestedSchema,r=await this._currentElicitationProvider.elicit({message:e.params.message,requestedSchema:t});return{action:r.action,content:r.content}}catch(e){return{action:"decline"}}}))}static async fromStreamableHttp(e,t,r,n,o,s,i,a,c,l,u,d=!1,h={}){const p=new URL(t.url);o=o??Tb;const f=await zR({serverName:e,config:t,tokenStorage:r,authRedirectUrl:o,fetchImpl:s,gtmMcpMatch:c,isScopePinGateEnabled:l,scopeChallengeStepUp:u}),m=f.tokens(),g=eP(t.url,n),w=g.headers,y=d&&function(e){return Object.entries(e??{}).some((([e,t])=>"authorization"===e.toLowerCase()&&t.trim().length>0))}(w)?void 0:f,v=s??(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),b=void 0!==g.cursorAuthHeaderValue&&void 0!==g.cursorAuthOrigin&&void 0!==v?tP((()=>g.cursorAuthHeaderValue),g.cursorAuthOrigin,v):v,S=e=>void 0===b||void 0===i?b:YP({fetch:b,logger:i.logger,metadata:{...i.metadata,transportType:e},redactLogText:i.redactLogText});let k;const _=e=>{const r=f.scopeStepUp,n=e??v;return void 0===r||void 0===n?e:(o={fetch:n,scopeStepUp:r,serverUrl:t.url,startSignIn:async e=>{const t=void 0!==e.resourceMetadataUrl&&URL.canParse(e.resourceMetadataUrl)?new URL(e.resourceMetadataUrl):void 0;await(0,pR.j2)(f,{serverUrl:p.toString(),...void 0!==t?{resourceMetadataUrl:t}:{},...void 0!==b?{fetchFn:b}:{}});const r=f.lastRedirectUrl;k=void 0!==r&&void 0!==t?{redirectUrl:r,resourceMetadataUrl:t}:void 0}},async(e,t)=>{const r=await o.fetch(e,t);if(401!==r.status&&403!==r.status||!function(e){if("string"!=typeof e)return!1;let t;try{t=JSON.parse(e)}catch{return!1}return(Array.isArray(t)?t:[t]).some((e=>"object"==typeof e&&null!==e&&"method"in e&&"tools/call"===e.method))}(t?.body))return r;const n=await o.scopeStepUp.decide({status:r.status,wwwAuthenticate:r.headers.get("www-authenticate"),toolName:Ax(t?.body)});if(void 0===n)return r;if(o.onDecision?.(n),await(r.body?.cancel().catch((()=>{}))),"offer"===n.kind)try{await o.scopeStepUp.signIn((()=>o.startSignIn(n)))}catch(e){px(o.scopeStepUp.accountKey).warn("MCP OAuth scope step-up: could not start the sign-in",{event:"mcp_oauth_scope_step_up_sign_in_failed",errorName:e instanceof Error?e.name:typeof e})}throw new Tx(n,o.serverUrl,o.scopeStepUp.connectorName)});var o},C=QR.createClient(h),E=e=>e instanceof pR.D_||function(e){if(null===e||"object"!=typeof e)return!1;const t=e.name;if("string"==typeof t&&Mx.has(t))return!0;const r=e.errorCode;return!("string"!=typeof r||!Dx.has(r.toLowerCase()))||function(e){if(null===e||"object"!=typeof e)return!1;const t=e.name,r=e.errorCode;if("InvalidRequestError"!==t&&("string"!=typeof r||"invalid_request"!==r.toLowerCase()))return!1;const n=e.message;return"string"==typeof n&&Ox.some((e=>e.test(n)))}(e)}(e)||$x(e),x=async t=>{if(!f.hasClientInformation())throw new Error("OAuth client registration has not completed. The MCP server may not support dynamic client registration or the registration failed.");const r=void 0!==k&&k.redirectUrl===f.lastRedirectUrl?k.resourceMetadataUrl:void 0;await(0,pR.j2)(f,{serverUrl:p.toString(),authorizationCode:t,...void 0!==r?{resourceMetadataUrl:r}:{},...void 0!==b?{fetchFn:b}:{}}),a&&PP({logger:a,event:"mcp_oauth_callback_completion",metadata:{identifier:e,...iP(p.toString()),...eR(f.tokens(),{expiresInIsFresh:!0})}})},P=r=>{const n=f.lastRedirectUrl?.toString?.()??"",o=new QR(e,C,{oauthLifecycleLogger:a,redactLogText:i?.redactLogText,initialState:{kind:"requires_authentication",url:n,callback:async e=>{try{await x(e),o.updateState({kind:"ready"})}catch(e){const t=e instanceof Error?e.message:"Authentication failed";throw new Error(`Authentication callback failed: ${t}`)}}},authProvider:f,authCodeExchange:x,sessionId:r,config:t});return o},R=async r=>{const n=new fR.A(p,{authProvider:y,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...w??{}}},fetch:_(S("sse"))});try{return await C.connect(n),new QR(e,C,{initialState:{kind:"ready"},authProvider:f,authCodeExchange:x,config:t,oauthLifecycleLogger:a,redactLogText:i?.redactLogText})}catch(t){if(await n.close().catch((()=>{})),E(t))return a&&PP({logger:a,event:"mcp_oauth_state_transition",metadata:{identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"sse",refreshTokenPresent:Boolean(m?.refresh_token),...iP(p.toString()),...EP(t,i?.redactLogText)}}),P();if(void 0!==r&&tR(t)&&t instanceof fR._)throw function(e,t){let r=e;for(let e=0;e<8&&r instanceof Error&&r.cause instanceof Error;e++)r=r.cause;return r instanceof Error&&void 0===r.cause&&Reflect.defineProperty(r,"cause",{value:t,writable:!0,configurable:!0,enumerable:!1}),e}(r,t);throw t}};if("sse"===t.type)return R();const I=new gR.j(p,{authProvider:y,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...w??{}}},fetch:_(ZR(S("streamableHttp"),p))});try{await C.connect(I);const r=function(e,t=Date.now){return Vx(Gx(e),t)}(t.url)?void 0:function(e,r){const o=r.protocolVersion;if(void 0!==r.sessionId||void 0===o)return;const s=e.getServerCapabilities(),i=e.getServerVersion();if(void 0===s||void 0===i)return;const a=e.getInstructions();return{result:{protocolVersion:o,capabilities:s,serverInfo:i,...void 0===a?{}:{instructions:a}},credentialFingerprint:bR({url:t.url,headers:n,accessToken:f.tokens()?.access_token})}}(C,I);return new QR(e,C,{initialState:{kind:"ready"},authProvider:f,authCodeExchange:x,sessionId:I.sessionId,protocolVersion:I.protocolVersion,...void 0===r?{}:{sessionlessInitialize:r},config:t,oauthLifecycleLogger:a,redactLogText:i?.redactLogText})}catch(t){if(E(t))return a&&PP({logger:a,event:"mcp_oauth_state_transition",metadata:{identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"streamableHttp",refreshTokenPresent:Boolean(m?.refresh_token),...iP(p.toString()),...EP(t,i?.redactLogText)}}),P(I.sessionId);if(tR(t))return R(t);throw t}}static async fromStreamableHttpWithoutOAuth(e,t,r){const n=QR.createClient(),o=new gR.j(new URL(t.url),{requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...t.headers}},fetch:r});return await n.connect(o),new QR(e,n,{initialState:{kind:"ready"},sessionId:o.sessionId,protocolVersion:o.protocolVersion,config:t})}static async fromCachedSession(e,t,r,n,o,s=Tb,i,a,c,l,u){const d=new URL(t.url),h=await zR({serverName:e,config:t,tokenStorage:n,authRedirectUrl:s,fetchImpl:i,gtmMcpMatch:l,isScopePinGateEnabled:u}),{transportHeaders:p,baseFetch:f}=XR(t.url,o,i),m=new gR.j(d,{authProvider:h,sessionId:r.sessionId,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...p??{}}},fetch:void 0!==f&&void 0!==a?YP({fetch:f,logger:a.logger,metadata:{...a.metadata,transportType:"streamableHttp"},redactLogText:a.redactLogText}):f});m.setProtocolVersion(r.protocolVersion);const g=function(e){return e._requestMessageId=(0,ko.randomInt)(1048576,2146435072),e}(QR.createClient());return await g.connect(m),new QR(e,g,{initialState:{kind:"ready"},authProvider:h,sessionId:m.sessionId,protocolVersion:r.protocolVersion,...void 0===r.instructions?{}:{resumedInstructions:r.instructions},config:t,oauthLifecycleLogger:c,redactLogText:a?.redactLogText})}static async fromSessionlessInitialize(e,t,r,n,o,s=Tb,i,a,c,l){const u=await zR({serverName:e,config:t,tokenStorage:n,authRedirectUrl:s,fetchImpl:i,gtmMcpMatch:a,isScopePinGateEnabled:c});if(bR({url:t.url,headers:o,accessToken:u.tokens()?.access_token})!==r.credentialFingerprint)return;const{transportHeaders:d,baseFetch:h}=XR(t.url,o,i),p=new gR.j(new URL(t.url),{authProvider:u,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...d??{}}},fetch:h}),f=QR.createClient();return await f.connect(new SR(p,r.result)),new QR(e,f,{initialState:{kind:"ready"},authProvider:u,sessionlessInitialize:r,config:t,redactLogText:l})}get sessionId(){return this._sessionId}get protocolVersion(){return this._protocolVersion}get sessionlessInitialize(){return this._sessionlessInitialize}get holdsOAuthAccessToken(){return Boolean(this._authProvider?.tokens()?.access_token)}async openStandaloneStream(){const e=this.client.transport;e instanceof gR.j&&await e.resumeStream("")}static async fromCommand(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{OR(s,(0,D.VI)(e.withName("McpSdkClient.fromCommand")),!1);const l=(c=o?.spawn,void 0!==c||"linux"!==process.platform?c:(e,t,r)=>(0,au.D9)(iu.spawn,e,t,r)),u=r.args??[],d=new mR.oQ({command:r.command,args:u,env:rR(dR({command:r.command,args:u,env:n})),cwd:r.cwd,stderr:"pipe",...l&&{spawn:l}}),h=function(e){const t=new MR;let r=null===e;return null!==e&&(e.on("data",(e=>{t.full||t.push(e)})),e.once("end",(()=>{t.end(),r=!0}))),{read:()=>_P(t.text.replace(/\s+/g," ").trim(),{maxLength:ix}),waitForFlush:async()=>{r||null===e||await new Promise((t=>{let r;const n=()=>{void 0!==r&&clearTimeout(r),e.off("end",n),t()};r=setTimeout(n,250),r.unref(),e.once("end",n)}))}}}(d.stderr),p=QR.createClient({mcpAppsUi:o?.mcpAppsUi}),f=o?.connectTimeoutMs??(void 0!==(a=r.startupTimeoutSec)&&Number.isFinite(a)&&a>0?Math.min(1e3*a,3e5):6e4);let m;d.onclose=()=>{var e;void 0!==m&&(e=m,GR.delete(e))};let g=0,w=!0;d.onerror=e=>{w&&function(e){return e instanceof SyntaxError||"ZodError"===e.name}(e)&&(g+=1)};const y=new AbortController,v=p.connect(d,{timeout:f,signal:y.signal});let b;m=d.pid??void 0,void 0!==m&&(i=m,GR.add(i),VR||(VR=!0,process.on("exit",KR)));const S=new Promise(((e,r)=>{b=setTimeout((()=>r(new Error(`MCP server connection timed out after ${f}ms: ${t}`))),f)}));try{await Promise.race([v,S])}catch(e){throw y.abort(),v.catch((()=>{})),await d.close().catch((()=>{})),await h.waitForFlush(),g>0&&e instanceof Error&&(e.message=`${e.message}; non-JSON-RPC output on stdout before initialize (${String(g)} line${1===g?"":"s"})`),function(e,t){if(""===t)return e;const r=e instanceof Error?e:new Error(String(e));return r.message=`${r.message}; stderr: ${t}`,DR.set(r,t),r}(e,h.read())}finally{w=!1,void 0!==b&&clearTimeout(b)}return new QR(t,p,{initialState:{kind:"ready"},config:r,stdioServer:void 0!==m,serverSignals:vR(d)})}catch(e){s.error=e,s.hasError=!0}finally{FR(s)}var i,a,c}terminateSessionOnClose(e){this._sessionTermination=e}setToolCallRequestOptions(e){this._toolCallRequestOptions=e}failToolCallInFlight(e){const t=this._toolCallInFlight;return void 0!==t&&!t.signal.aborted&&(t.abort(e),!0)}onServerSignal(e){return this._serverSignals?.subscribe(e)??(()=>{})}setToolCallOutputSchemaPassthrough(e){this._toolCallOutputSchemaPassthrough=e}async close(){if(this._closeRequested=!0,this._terminatingSession)return;const e=this._sessionTermination,t=this.client.transport;if(void 0!==e&&t instanceof gR.j)return this._terminatingSession=!0,void(async()=>{await async function(e,t){const r=await async function(e,t){if(void 0===e.sessionId)return{outcome:"no_session",durationMs:0};const r=Date.now(),n=e.terminateSession();n.catch((()=>{}));try{await(0,Nr.wj)(n,t.timeoutMs)}catch(e){const t=Date.now()-r;return e instanceof Nr.MU?{outcome:"timeout",durationMs:t}:e instanceof gR.b&&void 0!==e.code&&e.code>0?{outcome:"rejected",durationMs:t,httpStatus:e.code,error:e.message}:{outcome:"failed",durationMs:t,error:String(e)}}const o=t.deleteObserver?.lastDeleteStatus;return{outcome:405===o?"unsupported":"terminated",durationMs:Date.now()-r,...void 0!==o?{httpStatus:o}:{}}}(e,t);try{t.onResult?.(r)}catch{}return r}(t,e),await this.client.close()})().catch((()=>{}));await this.client.close()}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=OR(t,(0,D.VI)(e.withName("McpSdkClient.getTools")),!1);if(r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("mcp.transport",BR(this.config)),"requires_authentication"===this.stateValue.kind)return r.span.setAttribute("mcp.tools.requires_authentication",!0),[];if("error"===this.stateValue.kind)return[];const n=++this._toolListGeneration;let o=0,s=0;try{const e=await this.tools.get((async()=>{let e;const t=await hR({fetchPage:async t=>{o++;const n=await async function(e,t,r){try{const r=await e.listTools({cursor:t});return{tools:r.tools,nextCursor:r.nextCursor,meta:r._meta,..._R}}catch(c){if(!(c instanceof Error&&"issues"in c&&Array.isArray(c.issues)))throw c}const n=await e.request({method:"tools/list",params:{cursor:t}},kR),o=[];let s=0,i=0,a=0;for(const e of n.tools){let t=e;if(TR(e)){const r=e.inputSchema;RR(r)&&(t=IR(e,r),s++)}let n=Fx.Dn.safeParse(t);if(!n.success&&(c=n.error).issues.some((e=>"outputSchema"===e.path[0]))){const o=Fx.Dn.safeParse(PR(t));o.success&&(a++,r(CR(e),ER(n.error),"output_stripped"),n=o)}n.success?o.push(n.data):(i++,r(CR(e),xR(n.error.issues),"dropped"))}var c;return{tools:o,nextCursor:"string"==typeof n.nextCursor?n.nextCursor:void 0,meta:n._meta,typeFilled:s,toolDropped:i,outputStripped:a}}(this.client,t,((e,t,n)=>{(function(e,t,r){const n=JSON.stringify([e,t,r]);if(eI.has(n))return eI.delete(n),eI.add(n),!1;if(eI.add(n),eI.size>256){const e=eI.keys().next().value;void 0!==e&&eI.delete(e)}return!0})(n,this.serverName,e??"")&&NR.warn(r.ctx,"output_stripped"===n?"Removed an MCP tool output schema the client rejected":"Left out an MCP tool whose definition is invalid",{serverName:this.serverName,..."string"==typeof e?{toolName:e}:{},issues:t})}));return s+=n.typeFilled,tI(r.ctx,"type_filled",n.typeFilled),tI(r.ctx,"tool_dropped",n.toolDropped),tI(r.ctx,"output_stripped",n.outputStripped),e??=function(e){if(!WC(e))return;const t=e.mcpAllowlist;if(!WC(t)||"string"!=typeof t.list)return;const r=HC(t.name,200),n=HC(t.reason,200);if(void 0===r||void 0===n)return;const o={list:"local"===t.list||"cloud"===t.list?t.list:"other",name:r,reason:n},s=qC(t.allowedServerNames)??qC(t.allowedServers);void 0!==s&&(o.allowedServers=s);const i=qC(t.blockedServers);return void 0!==i&&(o.blockedServers=i),o}(n.meta),n},itemsOf:e=>e.tools,nextCursorOf:e=>e.nextCursor});return this._allowlistInUse=this.reportsCursorMcpAllowlist()?e:void 0,t.map((e=>({...e,inputSchema:eE(e.inputSchema),outputSchema:void 0===e.outputSchema?void 0:eE(e.outputSchema)})))}));return this.noteToolListSuccess(),r.span.setAttribute("mcp.tools.fetched",o>0),r.span.setAttribute("mcp.tools.pages",o),o>0&&r.span.setAttribute("mcp.tools.type_filled",s),r.span.setAttribute("mcp.tools.count",e.length),e}catch(e){const t=JR(e);if(r.span.setAttribute("mcp.tools.fetched",o>0),r.span.setAttribute("mcp.tools.pages",o),o>0&&r.span.setAttribute("mcp.tools.type_filled",s),this.noteToolListFailure(r.ctx,t,n),t instanceof pR.D_&&n===this._toolListGeneration&&n>this._toolListStateGeneration&&"ready"===this.stateValue.kind){const e=this.stateValue,r=this._authProvider?.lastRedirectUrl?.toString()??"";this.stateValue={kind:"requires_authentication",url:r,callback:e=>this.completeRuntimeAuthorization(e)},this.discardToolListError(),this._logStateTransition(e,this.stateValue,"runtime_unauthorized",{...EP(t,this._redactLogText)}),this._stateEnteredAtMs=Date.now()}throw t}}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async getAllowlistInUse(){return this._allowlistInUse}reportsCursorMcpAllowlist(){return void 0!==this.config&&"url"in this.config&&BC(this.config.url)}toolListAttemptIsCurrent(e){return e>this._toolListSuccessGeneration&&e>this._toolListStateGeneration}noteToolListSuccess(){this._toolListError=void 0,this._toolListSuccessGeneration=this._toolListGeneration}discardToolListError(){this._toolListError=void 0,this._toolListStateGeneration=this._toolListGeneration}noteToolListFailure(e,t,r){const n=Fx.O4.MethodNotFound;if(t instanceof Fx.Nh&&t.code===n&&void 0===this.client.getServerCapabilities()?.tools)return void this.noteToolListSuccess();if(t instanceof pR.D_||!this.toolListAttemptIsCurrent(r))return;const o=function(e){if(e instanceof Fx.Nh)return{descriptor:`McpError ${e.code}`,errorClass:"McpError",jsonRpcCode:e.code};if(e instanceof gR.b||e instanceof fR._){const t=e instanceof gR.b?"StreamableHTTPError":"SseError",r="number"==typeof e.code?e.code:void 0;return{descriptor:void 0===r?t:`${t} ${r}`,errorClass:t,...void 0===r?{}:{httpStatus:r}}}return e instanceof Error?{descriptor:"Error",errorClass:"Error"}:{descriptor:"unknown",errorClass:"unknown"}}(t);o.descriptor!==this._toolListError&&NR.warn(e,"MCP server failed to list its tools",{serverName:this.serverName,errorClass:o.errorClass,...void 0!==o.jsonRpcCode?{jsonRpcCode:o.jsonRpcCode}:{},...void 0!==o.httpStatus?{httpStatus:o.httpStatus}:{}}),this._toolListError=o.descriptor}async callTool(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{const a=OR(s,(0,D.VI)(e.withName("McpSdkClient.callTool")),!1);a.span.setAttribute("toolName",t),a.span.setAttribute("serverName",this.serverName),a.span.setAttribute("mcp.transport",BR(this.config));const c=this._callToolLock,l=this._callToolQueueDepth;let u;this._callToolQueueDepth++,this._callToolLock=new Promise((e=>{u=e}));try{{const e={stack:[],error:void 0,hasError:!1};try{const t=OR(e,(0,D.VI)(a.ctx.withName("McpSdkClient.callTool.lockWait")),!1);t.span.setAttribute("serverName",this.serverName),t.span.setAttribute("mcp.call_tool.queued_ahead",l);const r=performance.now();await c;const n=performance.now()-r;t.span.setAttribute("mcp.call_tool.lock_wait_ms",n),a.span.setAttribute("mcp.call_tool.lock_wait_ms",n),a.span.setAttribute("mcp.call_tool.queued_ahead",l)}catch(t){e.error=t,e.hasError=!0}finally{FR(e)}}if("requires_authentication"===this.stateValue.kind)throw new pR.D_(`MCP server "${this.serverName}" requires authentication`);this._currentToolCallId=n,this._currentToolName=t,this._currentElicitationProvider=o;const s=new AbortController;this._toolCallInFlight=s;const u=this._authProvider?.lastRedirectUrl;try{const n={stack:[],error:void 0,hasError:!1};try{const o=OR(n,(0,D.VI)(a.ctx.withName("McpSdkClient.callTool.sdk")),!1);o.span.setAttribute("toolName",t),o.span.setAttribute("serverName",this.serverName);const c=await this.sendToolCall({name:t,arguments:r},s.signal);return o.span.setAttribute("mcp.call_tool.is_error",!0===c.isError),jR(e,this.config,{isError:!0===c.isError}),{content:c.content,isError:!0===c.isError,structuredContent:(i=c.structuredContent,tE(i)),_meta:lE(c._meta)}}catch(e){n.error=e,n.hasError=!0}finally{FR(n)}}catch(t){const r=JR(t);r instanceof Tx?(jR(e,this.config,{error:r,httpStatus:r.decision.status}),function(e,t){try{UR.increment(e,1,{decision:t.decision.kind,dropped:String(t.decision.dropped.length>0)})}catch{}}(e,r)):jR(e,this.config,{error:r});const n=r instanceof Tx&&"offer"===r.decision.kind&&void 0!==this._authProvider?.lastRedirectUrl&&this._authProvider.lastRedirectUrl!==u;if((r instanceof pR.D_||n)&&"ready"===this.stateValue.kind){const e=this.stateValue,t=this._authProvider?.lastRedirectUrl?.toString()??"";this.stateValue={kind:"requires_authentication",url:t,callback:e=>this.completeRuntimeAuthorization(e)},this.discardToolListError(),this._logStateTransition(e,this.stateValue,n?"scope_step_up":"runtime_unauthorized",{...EP(r,this._redactLogText)}),this._stateEnteredAtMs=Date.now()}throw r}finally{this._toolCallInFlight=void 0,this._currentElicitationProvider=void 0,this._currentToolCallId=void 0,this._currentToolName=void 0}}finally{this._callToolQueueDepth--,c.then(u)}}catch(e){s.error=e,s.hasError=!0}finally{FR(s)}var i}sendToolCall(e,t){const r=this._toolCallRequestOptions?.(e.name),n={...r,signal:void 0===r?.signal?t:AbortSignal.any([r.signal,t])};return!0===this._toolCallOutputSchemaPassthrough?.()?this.client.request({method:"tools/call",params:e},Fx.TF,n):this.client.callTool(e,void 0,n)}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{if(OR(t,(0,D.VI)(e.withName("McpSdkClient.getInstructions")),!1).span.setAttribute("serverName",this.serverName),"requires_authentication"===this.stateValue.kind)return;return this.client.getInstructions()??this._resumedInstructions}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{if(OR(t,(0,D.VI)(e.withName("McpSdkClient.listResources")),!1),"requires_authentication"===this.stateValue.kind||"error"===this.stateValue.kind)return{resources:[]};const r=this.client.getServerCapabilities();return r?.resources?{resources:await hR({fetchPage:e=>this.client.listResources({cursor:e}),itemsOf:e=>e.resources,nextCursorOf:e=>e.nextCursor})}:{resources:[]}}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{return OR(r,(0,D.VI)(e.withName("McpSdkClient.readResource")),!1),"requires_authentication"===this.stateValue.kind?{contents:[]}:{contents:(await this.client.readResource({uri:t.uri})).contents}}catch(e){r.error=e,r.hasError=!0}finally{FR(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{return OR(t,(0,D.VI)(e.withName("McpSdkClient.listPrompts")),!1),"requires_authentication"===this.stateValue.kind||"error"===this.stateValue.kind?[]:(this.client.getServerCapabilities()??{prompts:!1}).prompts?(await hR({fetchPage:e=>this.client.listPrompts({cursor:e}),itemsOf:e=>e.prompts,nextCursorOf:e=>e.nextCursor})).map((e=>({name:e.name,description:e.description,arguments:e.arguments?.map((e=>({name:e.name,description:e.description,required:e.required})))}))):[]}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async getPrompt(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{return OR(n,(0,D.VI)(e.withName("McpSdkClient.getPrompt")),!1),"requires_authentication"===this.stateValue.kind?{messages:[]}:{messages:(await this.client.getPrompt({name:t,arguments:r})).messages.map((e=>({role:e.role,content:Array.isArray(e.content)?e.content.map((e=>"text"===e.type?{type:"text",text:e.text}:"image"===e.type?{type:"image",data:e.data,mimeType:e.mimeType}:{type:"text",text:JSON.stringify(e)})):[{type:"text",text:"string"==typeof e.content?e.content:JSON.stringify(e.content)}]})))}}catch(e){n.error=e,n.hasError=!0}finally{FR(n)}}getCurrentToolCallContext(){if(this._currentToolName)return{toolName:this._currentToolName,toolCallId:this._currentToolCallId}}async getState(e){return"ready"===this.stateValue.kind&&void 0!==this._toolListError?{kind:"ready",toolListError:this._toolListError}:this.stateValue}async completeRuntimeAuthorization(e){if(!this._authCodeExchange)throw new Error(`MCP server "${this.serverName}" cannot complete authorization: no code exchange is configured for this client.`);try{await this._authCodeExchange(e)}catch(e){const t=e instanceof Error?e.message:"Authentication failed";throw new Error(`Authentication callback failed: ${t}`)}this.updateState({kind:"ready"},"runtime_authorization_completed")}updateState(e,t){const r=this.stateValue;this.discardToolListError(),this.stateValue=e,this._logStateTransition(r,e,t??"explicit_update"),this._stateEnteredAtMs=Date.now()}}const YR=(0,h.Pu)("mcp_tool.schema",{description:"One MCP tool definition a tools/list repair touched",labelNames:["outcome"]}),eI=new Set;function tI(e,t,r){if(0!==r)try{YR.increment(e,r,{outcome:t})}catch{}}class rI extends Error{constructor(e,t){super(`MCP server ${e} not found, available servers: ${t.join(", ")}`),this.serverName=e,this.availableServers=t,this.name="McpServerNotFoundError"}}Error,Error;class nI{constructor(e){this.tools=e}async execute(e,t,r,n){const o=this.tools[e];if(!o)throw new kC(e,Object.keys(this.tools));return o.execute(t,r,n)}async executeOn(e,t,r,n,o){const s=this.tools[t];if(!s)throw new kC(t,Object.keys(this.tools));if(s.client===e)return s.execute(r,n,o)}getTools(){return Object.entries(this.tools).map((([e,t])=>({...t.definition,name:e})))}}class oI{async getClients(e){return{}}async getClient(e,t){}async getInstructions(e){return[]}async getToolSet(e){return new nI({})}async getTools(e){return[]}async getToolsForServers(e,t){return[]}}class sI{constructor(e){this.manager=e}async getClients(e){return this.manager.getClients()}async getClient(e,t){return this.manager.getClient(t)}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=OR(t,(0,D.VI)(e.withName("ManagerMcpLease.getInstructions")),!1);return await this.manager.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async getToolSet(e){const t={stack:[],error:void 0,hasError:!1};try{const r=OR(t,(0,D.VI)(e.withName("ManagerMcpLease.getToolSet")),!1);return await this.manager.getToolSet(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=OR(t,(0,D.VI)(e.withName("ManagerMcpLease.getTools")),!1);return(await this.getToolSet(r.ctx)).getTools()}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async getToolsForServers(e,t){const r=new Set(t);return(await this.getTools(e)).filter((e=>r.has(e.clientKey)))}onDidChange(e){return{dispose:this.manager.onDidChange((()=>e(void 0)))}}async reconcileSelection(e,t,r){for(const e of t.removed){const t=this.manager.getClient(e);this.manager.deleteClient(e);try{await(t?.close?.())}catch{}}for(const n of t.added){if(this.manager.getClient(n))continue;const t=await r(e,n);this.manager.setClient(n,t)}}}class iI{constructor(e,t){this.clients=e,this.elicitationFactory=t,this.changeListeners=new Set,this.warnedToolNameCollisions=new Set}onDidChange(e){return this.changeListeners.add(e),()=>{this.changeListeners.delete(e)}}fireDidChange(){for(const e of this.changeListeners)try{e()}catch(e){console.error("Error in McpManager change listener:",e)}}getClients(){return this.clients}getClient(e){return this.clients[e]}setClient(e,t){this.clients[e]=t,this.fireDidChange()}deleteClient(e){delete this.clients[e],this.fireDidChange()}setListingDeadline(e){this.listingDeadlineAt=void 0===e?void 0:performance.now()+e}async closeAllClients(){const e=Object.values(this.clients);await Promise.all(e.map((async e=>{try{await(e.close?.())}catch{}})))}async getToolSet(e){const t={stack:[],error:void 0,hasError:!1};try{const r=OR(t,(0,D.VI)(e.withName("McpManager.getToolSet")),!1),n=OR(t,aI(this.listingDeadlineAt),!1),o=await(0,Nr.PH)(Object.entries(this.clients),(([e,t])=>n.within(t,r.ctx,(()=>t.getTools(r.ctx))).then((r=>(r??[]).map((r=>({...r,clientKey:e,clientName:t.serverName,client:t}))))).catch((()=>[]))),{max:n.concurrency}),s=Array.from(o.values()).flat(),i=new Map;for(const e of s){const t=`${e.clientName}-${e.name}`,r=i.get(t);void 0===r?i.set(t,[e]):r.push(e)}const a={};for(const[e,t]of i){const n=t[0];if(void 0===n)continue;if(t.some((e=>e.clientName!==n.clientName||e.name!==n.name))){if(!this.warnedToolNameCollisions.has(e)){this.warnedToolNameCollisions.add(e);const r=t.map((e=>`${e.clientName}/${e.name}`)).join(", ");console.warn("Colliding MCP tool name; exposing neither:",`${e} (${r})`)}continue}const o=t[t.length-1]?.clientKey,s=t.filter((e=>e.clientKey===o)),i=s[0]??n;s.length>1&&!this.warnedToolNameCollisions.has(e)&&(this.warnedToolNameCollisions.add(e),console.warn("MCP server lists a tool name more than once; using the first:",`${i.clientName}/${i.name}`)),a[e]={definition:{...i,clientKey:i.clientKey,providerIdentifier:i.clientName,toolName:i.name},client:i.client,execute:async(e,t,n)=>{const o=n?.createProvider(i.clientName,i.name,t);return await i.client.callTool(r.ctx,i.name,e,t,o)}}}return new nI(a)}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=OR(t,(0,D.VI)(e.withName("McpManager.getInstructions")),!1),n=OR(t,aI(this.listingDeadlineAt),!1),o=await(0,Nr.PH)(Object.entries(this.clients),(([e,t])=>n.within(t,r.ctx,(()=>t.getInstructions(r.ctx))).then((e=>e&&0!==e.trim().length?new vn.I0({serverName:t.serverName,instructions:e.trim()}):null)).catch((()=>null))),{max:n.concurrency});return Array.from(o.values()).filter((e=>null!==e))}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}}function aI(e){if(void 0===e)return{concurrency:4,within:(e,t,r)=>r(),[Symbol.dispose]:()=>{}};let t;const r=new Promise((r=>{t=setTimeout((()=>r(void 0)),Math.max(0,e-performance.now()))}));return{concurrency:Number.POSITIVE_INFINITY,within:async(t,n,o)=>{const s=await Promise.race([t.getState(n).catch((()=>{})),r]);if("ready"!==s?.kind)return Promise.race([o(),r]);let i;try{return await Promise.race([o(),new Promise((t=>{i=setTimeout((()=>t(void 0)),Math.max(2e3,e-performance.now()))}))])}finally{clearTimeout(i)}},[Symbol.dispose]:()=>clearTimeout(t)}}function cI(e,t){return function(e){const{logger:t,ctx:r}=e;return{debug:(e,n)=>t.debug(r,e,n),info:(e,n)=>t.info(r,e,n),warn:(e,n)=>t.warn(r,e,n),error:(e,n,o)=>t.error(r,e,n,o)}}({ctx:e,logger:t})}Error;class lI{constructor(e){this.options=e,PP({logger:e.logger,event:"mcp_oauth_provider_initialized",metadata:this.baseMetadata})}get baseMetadata(){return{identifier:this.options.identifier,...this.options.serverUrl?{serverUrl:iP(this.options.serverUrl)}:{}}}async loadTokens(){const e=await this.options.inner.loadTokens();return PP({logger:this.options.logger,event:"mcp_oauth_tokens_loaded",level:"debug",metadata:{...this.baseMetadata,...eR(e)}}),e}async saveTokens(e){await this.options.inner.saveTokens(e),PP({logger:this.options.logger,event:"mcp_oauth_tokens_saved",metadata:{...this.baseMetadata,...eR(e,{expiresInIsFresh:!0})}})}async prepareForRefresh(){PP({logger:this.options.logger,event:"mcp_oauth_refresh_prepare",metadata:this.baseMetadata}),await(this.options.inner.prepareForRefresh?.())}async releaseRefreshLeaseOnError(e){PP({logger:this.options.logger,event:"mcp_oauth_refresh_error_release",level:"warn",error:e,metadata:{...this.baseMetadata,...EP(e,this.options.redactLogText)}}),await(this.options.inner.releaseRefreshLeaseOnError?.(e))}async loadClientInformation(){const e=await this.options.inner.loadClientInformation();return PP({logger:this.options.logger,event:"mcp_oauth_client_info_loaded",level:"debug",metadata:{...this.baseMetadata,...lP(e)}}),e}async saveClientInformation(e){await this.options.inner.saveClientInformation(e),PP({logger:this.options.logger,event:"mcp_oauth_client_info_saved",metadata:{...this.baseMetadata,...lP(e)}})}async invalidateCredentials(e){void 0!==this.options.inner.invalidateCredentials&&(PP({logger:this.options.logger,event:"mcp_oauth_credentials_invalidated",level:"warn",metadata:{...this.baseMetadata,scope:e}}),await this.options.inner.invalidateCredentials(e))}tokenEndpointAuth(e){return this.options.inner.tokenEndpointAuth?.(e)}get loadScopeStepUpRecord(){return this.options.inner.loadScopeStepUpRecord?.bind(this.options.inner)}get saveScopeStepUpRecord(){return this.options.inner.saveScopeStepUpRecord?.bind(this.options.inner)}}class uI{constructor(e,t){this.storage=e,this.identifier=t}async loadTokens(){return this.storage.loadTokens(this.identifier)}async saveTokens(e){return this.storage.saveTokens(this.identifier,e)}async loadClientInformation(){return this.storage.loadClientInformation(this.identifier)}async saveClientInformation(e){return this.storage.saveClientInformation(this.identifier,e)}get loadScopeStepUpRecord(){const{storage:e,identifier:t}=this;return void 0===e.loadScopeStepUpRecord?void 0:()=>e.loadScopeStepUpRecord(t)}get saveScopeStepUpRecord(){const{storage:e,identifier:t}=this;return void 0===e.saveScopeStepUpRecord?void 0:r=>e.saveScopeStepUpRecord(t,r)}}class dI{constructor(e){this.inner=e}async loadTokens(){}async loadClientInformation(){}async saveTokens(e){return this.inner.saveTokens(e)}async saveClientInformation(e){return this.inner.saveClientInformation(e)}async invalidateCredentials(e){await(this.inner.invalidateCredentials?.(e))}get loadScopeStepUpRecord(){return this.inner.loadScopeStepUpRecord?.bind(this.inner)}get saveScopeStepUpRecord(){return this.inner.saveScopeStepUpRecord?.bind(this.inner)}async loadGrantedScope(){return void 0!==this.inner.loadGrantedScope?this.inner.loadGrantedScope():(await this.inner.loadTokens())?.scope}}var hI=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},pI=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const fI=(0,d.h)("DefinitionMcpLoader"),mI=(0,h.Pu)("connector_policy.blocked",{description:"MCP servers a team or org policy refused to load, once per loader and server.",labelNames:["surface","stage","reason"]});function gI(e){const{filePath:t,baseDir:r}=e;return"~"===t||t.startsWith("~/")?s.join(o.homedir(),t.slice(1)):t.startsWith("./")||"."===t?s.resolve(r??process.cwd(),t):t}function wI(e){return"getManagedSlackWorkspaceLists"in e&&"function"==typeof e.getManagedSlackWorkspaceLists}function yI(e){return"getMcpNetworkControlsConfig"in e&&"function"==typeof e.getMcpNetworkControlsConfig}function vI(e){return e?.length??0}function bI(e){if(void 0!==e)return(0,ko.createHash)("sha256").update(ME(e)).digest("hex")}function SI(e){if(void 0===e)return;let t;return r=>(void 0===t&&(t=e(),queueMicrotask((()=>{t=void 0}))),t?tx(r):r)}async function kI(e,t,n,o,s={middlewares:[],configPath:""},i,a,c={},l={}){const u={stack:[],error:void 0,hasError:!1};try{const{middlewares:d,configPath:h}=s,p=hI(u,(0,D.VI)(e.withName("mcp-agent-exec.loadServer")),!1);p.span.setAttribute("serverName",t);const f=!1!==l.mcpAppsUi;p.span.setAttribute("mcpAppsUi",f),fI.info(p.ctx,`Loading MCP server "${t}" ${f?"declaring":"without declaring"} the MCP Apps UI extension`,{event:"mcp_apps_ui_capability",serverName:t,mcpAppsUi:f,transport:"command"in n?"stdio":"http"});let m=async(e,n)=>{const s={stack:[],error:void 0,hasError:!1};try{const u=hI(s,(0,D.VI)(e.withName("loadServer.next")),!1);u.span.setAttribute("serverName",t);const h=u.ctx;if("command"in n){u.span.setAttribute("kind","command");const e=d.find(yI);return await async function(e,t,n,o,s={}){const i=n.cwd?gI({filePath:n.cwd}):void 0;let a,c;if(n.args&&n.args.length>0)a=gI({filePath:n.command,baseDir:i}),c=n.args.map((e=>gI({filePath:e,baseDir:i})));else{const e=(0,rx.A)(n.command);a=gI({filePath:e[0],baseDir:i}),c=e.slice(1).map((e=>gI({filePath:e,baseDir:i})))}const l=n.env??{},{startupTimeoutSec:u}=n,d=await(o?.getMcpNetworkControlsConfig?.({command:[n.command,...n.args??[]].join(" ")})),h=(0,Lb.$H)(d);if(void 0!==h){const{buildMcpSandboxPolicy:n}=await r.e(449).then(r.bind(r,"../mcp-agent-exec/dist/mcp-sandbox-policy.js")),{SandboxUnsupportedError:o,spawnInSandbox:p}=await Promise.resolve().then(r.bind(r,"../shell-exec/dist/api/index.js")),f=i??process.cwd(),m=await n(h,f);fI.info(e,function(e){return`Sandboxing local MCP server "${e.serverName}" with network controls: networkControlsEnabled=${String(!0===e.networkControlsConfig?.enabled)}, mcpNetworkMode=${e.networkControlsConfig?.mcpNetworkMode??"unset"}, mcpNetworkAllowlistCount=${vI(e.networkControlsConfig?.mcpNetworkAllowlist)}, mcpNetworkDenylistCount=${vI(e.networkControlsConfig?.mcpNetworkDenylist)}, localAgentNetworkAllowlistCount=${vI(e.networkControlsConfig?.localAgentNetworkAllowlist)}, sandboxPolicyHash=${bI(e.sandboxNetworkControlsConfig)??"none"}`}({serverName:t,networkControlsConfig:d,sandboxNetworkControlsConfig:h}),function(e){return{event:"mcp_stdio_sandbox_policy",serverName:e.serverName,networkControlsEnabled:!0===e.networkControlsConfig?.enabled,mcpNetworkMode:e.networkControlsConfig?.mcpNetworkMode,mcpNetworkAllowlistCount:vI(e.networkControlsConfig?.mcpNetworkAllowlist),mcpNetworkDenylistCount:vI(e.networkControlsConfig?.mcpNetworkDenylist),localAgentNetworkAllowlistCount:vI(e.networkControlsConfig?.localAgentNetworkAllowlist),sandboxPolicyHash:bI(e.sandboxNetworkControlsConfig)}}({serverName:t,networkControlsConfig:d,sandboxNetworkControlsConfig:h}));try{return await QR.fromCommand(e,t,{command:a,args:c,cwd:i,startupTimeoutSec:u},l,{...s,spawn:(e,t,r)=>p(e,t,r,m)})}catch(e){if(e instanceof o)throw new DE(t,e);throw e}}return!0===d?.enabled&&"no_sandbox"===d.mcpNetworkMode&&(!0===d.win32UserExtensionUnsandbox?fI.info(e,`Starting local MCP server "${t}" without MCP sandboxing`,{event:"mcp_stdio_win32_user_extension_unsandbox",serverName:t}):fI.info(e,`Starting local MCP server "${t}" without MCP sandboxing`)),QR.fromCommand(e,t,{command:a,args:c,cwd:i,startupTimeoutSec:u},l,s)}(h,t,n,e,l)}if("url"in n){u.span.setAttribute("kind","url");const e=i?.(t);return await async function(e,t,r,n,o,s,i,a,c={}){const l=cI(e,fI),u=function(e,t,r){return{logger:{debug:(t,r)=>fI.debug(e,t,r),info:(t,r)=>fI.info(e,t,r),warn:(t,r)=>fI.warn(e,t,r),error:(t,r,n)=>fI.error(e,t,r,n)},metadata:{identifier:t,source:"mcp-agent-exec"},redactLogText:SI(r)}}(e,t,a),d=void 0!==s&&LE(r.url)?jE(globalThis.fetch.bind(globalThis),{managedSlackWorkspaceLists:()=>s.getManagedSlackWorkspaceLists()}):void 0;return QR.fromStreamableHttp(t,r,n,r.headers,o,d,u,l,void 0,void 0,i,!1,c)}(h,t,n,o,e,d.find(wI),a,c.isLinkSharedPaymentTokenLogRedactionEnabled,l)}throw new Error(`Invalid server: ${JSON.stringify(n)}`)}catch(e){s.error=e,s.hasError=!0}finally{pI(s)}};for(const e of d){const r=m;m=async(n,o)=>await e.load(n,t,o,h,r)}try{return await m(p.ctx,n)}catch(e){throw function(e,t){if(void 0===t)return e;!function(e,t){if("object"!=typeof e||null===e)return;const r=DR.get(e);void 0!==r&&DR.set(e,t(r))}(e,t);const r=function(e,t){if(void 0===t)return e;const r={results:new Map,cycled:new Set},n=UE(e,t,r),o=new Map([...r.cycled].flatMap((e=>{const t=r.results.get(e);return t===e?[]:[[e,t]]})));return o.size>0&&function(e,t){const r=new Set,n=[e];for(let e=0;n.length>0&&e({identifier:e,serverConfig:t,configPath:this.configPath})))}}class CI{constructor(e,t,r=[],n={}){this.source=e,this.tokenStorage=t,this.middlewares=r,this.options=n,this.clientCache=new Map}async load(e,t=!0){const r={stack:[],error:void 0,hasError:!1};try{hI(r,(0,D.VI)(e.withName("DefinitionMcpLoader.load")),!1),t||(await this.closeAllCachedClients(),this.source.clearCache?.());const n=await this.source.getDefinitions(e,t);await this.evictClientsOnSandboxPolicyChange(e,n);const o={};return await(0,Nr.PH)([...n],(async r=>{try{const n=t?this.clientCache.get(r.identifier):void 0,s=n??await this.loadDefinitionClient(e,r);n||this.clientCache.set(r.identifier,s),o[r.identifier]=s}catch(t){if(this.handleDefinitionLoadError(e,r,t))return;!function(e,t,r,n){const o=SI(n)??(e=>e),s=function(e){if("object"==typeof e&&null!==e)return DR.get(e)}(r);fI.warn(e,"Failed to load MCP server",{identifier:t.identifier,source:t.source,configPath:t.configPath,metadata:t.metadata,errorMessage:o(r instanceof Error?r.message:String(r)),stderrTail:void 0===s?void 0:o(s)})}(e,r,t,this.options.isLinkSharedPaymentTokenLogRedactionEnabled)}}),{max:this.options.maxConcurrency??Math.max(n.length,1)}),new iI(o,this.options.elicitationFactory)}catch(e){r.error=e,r.hasError=!0}finally{pI(r)}}clearClient(e){this.clientCache.delete(e)}clearAllMcpCaches(){this.clientCache.clear()}async evictClientsOnSandboxPolicyChange(e,t){const r=this.middlewares.find(yI);if(!r)return;let n;try{n=JSON.stringify(await Promise.all([...t].sort(((e,t)=>e.identifier.localeCompare(t.identifier))).map((async e=>{const t=await(r.getMcpNetworkControlsConfig?.((n=e.serverConfig,"url"in n?{url:n.url}:{command:[n.command,...n.args??[]].join(" ")})))??{};var n;return[e.identifier,ME(t)]}))))}catch{return}const o=this.sandboxPolicyFingerprint;this.sandboxPolicyFingerprint=n,void 0!==o&&o!==n&&(fI.info(e,"MCP network-controls policy changed; reloading MCP clients to apply the new egress policy"),await this.closeAllCachedClients())}async closeAllCachedClients(){const e=[...this.clientCache.values()];this.clientCache.clear(),await(0,Nr.PH)(e,(async e=>{try{await(e.close?.())}catch{}}),{max:Math.max(e.length,1)})}async loadClient(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{hI(n,(0,D.VI)(e.withName("DefinitionMcpLoader.loadClient")),!1);const o=await this.source.getDefinitions(e);if(await this.evictClientsOnSandboxPolicyChange(e,o),!r){const e=this.clientCache.get(t);if(e)return e}const s=o.find((e=>e.identifier===t));if(!s)throw new Error(`MCP server "${t}" not found in config`);let i;try{i=await this.loadDefinitionClient(e,s,r)}catch(t){throw this.handleDefinitionLoadError(e,s,t),t}return r||this.clientCache.set(t,i),i}catch(e){n.error=e,n.hasError=!0}finally{pI(n)}}async loadDefinitionClient(e,t,r){const n=t.authStorageKey??t.identifier,o=new uI(this.tokenStorage,n),s=cI(e,fI),i=new lI({inner:o,logger:s,redactLogText:SI(this.options.isLinkSharedPaymentTokenLogRedactionEnabled),identifier:n,serverUrl:"url"in t.serverConfig?t.serverConfig.url:void 0}),a=r?new dI(i):i;return kI(e,t.identifier,t.serverConfig,a,{middlewares:this.middlewares,configPath:t.configPath??""},this.options.authRedirectUrlGenerator,this.options.scopeChallengeStepUp,{isLinkSharedPaymentTokenLogRedactionEnabled:this.options.isLinkSharedPaymentTokenLogRedactionEnabled})}handleDefinitionLoadError(e,t,r){let n=!1;try{n="handled"===this.options.onDefinitionLoadError?.(e,t,r)}catch(r){fI.warn(e,"MCP definition load error hook failed",{identifier:t.identifier,source:t.source,configPath:t.configPath,metadata:t.metadata,errorMessage:r instanceof Error?r.message:String(r)})}return n||function(e){return e instanceof AC||e instanceof $C||e instanceof MC||e instanceof EI}(r)}}class EI extends Error{constructor(e,t,r){super(r??("teamNetworkAllowlist"===t?`MCP server "${e}" is not on the team network allowlist`:`MCP server "${e}" is blocked by team policy`)),this.serverName=e,this.reason=t,this.name="McpServerBlockedError"}}const xI=[1e3,3e3];class PI{constructor(e){this.blockingService=e,this.countedPolicyBlocks=new Set}async getMcpNetworkControlsConfig(e){return await(this.blockingService.getMcpNetworkControlsConfig?.(e))??{}}async getManagedSlackWorkspaceLists(){return await(this.blockingService.getManagedSlackWorkspaceLists?.())??[]}async load(e,t,r,n,o){const s=function(e){return{command:"command"in e?[e.command,...e.args??[]].join(" "):void 0,url:"url"in e?e.url:void 0}}(r),i=await(this.blockingService.getMcpServerBlockInfo?.(s))??{blocked:await this.blockingService.isServerBlocked(s)};if(i.blocked){const r=i.reason??"teamPolicy";throw"teamPolicy"!==r||this.countedPolicyBlocks.has(t)||(this.countedPolicyBlocks.add(t),mI.increment(e,1,{surface:"desktop",stage:"tool_call",reason:"server_not_allowed"})),new EI(t,r,i.message)}for(let n=0;;n++)try{const t=await o(e,r);return!0===i.hostMcpBridge&&this.blockingService.recordHostMcpBridgeClient?.(t),this.blockingService.recordMcpServerClient?.(t,s),t}catch(e){if(e instanceof FE)throw new EI(t,"teamPolicy",e.message);const r=e instanceof NE?xI[n]:void 0;if(void 0===r)throw e;await(0,Nr.cb)(r)}}}class RI extends CI{constructor(e,t,r=[],n={}){super(new _I(e),t,r,n),this.configPath=e}static init(e,t,r=[]){return new RI(t,e,r)}}function II(e){return"stdio"===e.type&&e.command?{command:e.command,args:e.args??[],env:e.env,cwd:e.cwd}:"streamableHttp"===e.type&&e.url?{url:e.url,headers:e.headers,auth:e.auth,...void 0!==e.tls?{tls:e.tls}:{},...void 0!==e.placement?{placement:e.placement}:{}}:void 0}var TI=r("../utils/dist/private-file.js"),AI=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js");function $I(e){const t=AI.VE.safeParse(e);return t.success?t.data:void 0}function MI(e){const t=AI.H5.safeParse(e);return t.success?t.data:void 0}class DI{constructor(e){this.mcpAuthPath=e;const t=DI.mcpAuthPromises.get(e);if(t)this.mcpAuthPromise=t;else{const t=this.loadMcpAuth();this.mcpAuthPromise=t,DI.mcpAuthPromises.set(e,t),t.catch((()=>{DI.mcpAuthPromises.get(e)===t&&DI.mcpAuthPromises.delete(e)}))}DI.saveLocks.has(e)||DI.saveLocks.set(e,Promise.resolve())}async loadMcpAuth(){try{await(0,TI.rV)(this.mcpAuthPath);const e=await(0,xo.readFile)(this.mcpAuthPath,"utf8"),t=JSON.parse(e);if(t&&"object"==typeof t){if(Object.values(t).some((e=>e&&"object"==typeof e&&null!==e&&("access_token"in e||"refresh_token"in e)&&!("tokens"in e)&&!("clientInfo"in e)))){const e={};for(const[r,n]of Object.entries(t)){const t=$I(n);void 0!==t&&(e[r]={tokens:t})}return e}const e={};for(const[r,n]of Object.entries(t))n&&"object"==typeof n&&null!==n&&(e[r]={tokens:"tokens"in n?$I(n.tokens):void 0,clientInfo:"clientInfo"in n?MI(n.clientInfo):void 0,..."scopeStepUp"in n?{scopeStepUp:n.scopeStepUp}:{}});return e}return{}}catch(e){if(e instanceof Error&&e.message.includes("ENOENT"))return{};throw e}}async loadTokens(e){const t=await this.mcpAuthPromise;return t[e]?.tokens}async saveTokens(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),r[e].tokens=t,await this.saveMcpAuth(r)}))}async loadClientInformation(e){const t=await this.mcpAuthPromise;return t[e]?.clientInfo}async withSaveLock(e){const t=DI.saveLocks.get(this.mcpAuthPath)??Promise.resolve();let r;DI.saveLocks.set(this.mcpAuthPath,new Promise((e=>{r=e})));try{return await t,await e()}finally{r()}}async saveClientInformation(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),r[e].clientInfo=t,await this.saveMcpAuth(r)}))}async loadScopeStepUpRecord(e){const t=await this.mcpAuthPromise;return t[e]?.scopeStepUp}async saveScopeStepUpRecord(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),void 0===t?delete r[e].scopeStepUp:r[e].scopeStepUp=t,await this.saveMcpAuth(r)}))}async deleteCredentials(e){await this.withSaveLock((async()=>{const t=await this.mcpAuthPromise;e in t&&(delete t[e],await this.saveMcpAuth(t))}))}async saveMcpAuth(e){await(0,TI.Pl)(this.mcpAuthPath,JSON.stringify(e,null,2))}}DI.mcpAuthPromises=new Map,DI.saveLocks=new Map,(0,b.cF)(Symbol("execHookConversationId"),void 0),(0,b.cF)(Symbol("execHookGenerationId"),void 0),(0,b.cF)(Symbol("execHookModel"),void 0);const OI=(0,b.cF)(Symbol("execHookWorkspaceRoots"),void 0);var FI=r("../proto/dist/generated/agent/v1/write_exec_pb.js"),NI=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},LI=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const jI=(0,h.Pu)("mcp.filesystem.divergence",{description:"Divergence detected between MCP lease state and filesystem state",labelNames:["divergence_type","mcp_source","configured_servers","mcp_version"]}),UI=(0,h.Pu)("mcp.filesystem.sync_check",{description:"MCP filesystem sync check executed",labelNames:["synced","mcp_source","configured_servers","mcp_version"]}),BI=(0,h.wt)("mcp.filesystem.sync_check.expected_servers",{description:"Number of expected MCP servers at last sync check",labelNames:["mcp_source","mcp_version"]}),WI=(0,h.wt)("mcp.filesystem.sync_check.actual_servers",{description:"Number of actual MCP servers on disk at last sync check",labelNames:["mcp_source","mcp_version"]}),HI=(0,h.wt)("mcp.filesystem.sync_check.servers_missing",{description:"Number of expected MCP servers missing from disk at last sync check",labelNames:["mcp_source","mcp_version"]}),qI=(0,h.wt)("mcp.filesystem.sync_check.tool_mismatches",{description:"Number of MCP servers with tool count mismatches at last sync check",labelNames:["mcp_source","mcp_version"]}),zI=(0,d.h)("McpFileSystemWriter"),GI="mcpFsStructuredLogOptIn";function VI(e,t){return t?.includeStructuredLogs?{...e??{},[GI]:!0}:e}const KI={debug(e,t,r,n){zI.debug(e,t,VI(r,n))},info(e,t,r,n){zI.info(e,t,VI(r,n))},warn(e,t,r,n){zI.warn(e,t,VI(r,n))},error(e,t,r,n,o){zI.error(e,t,r,VI(n,o))}},JI="mcps",ZI="tools",XI="~staging",QI="~prev",YI=[25,50,100,200],eT=new Set(["EPERM","EBUSY","EACCES"]),tT=new Map;function rT(e){return e.slice(0,e.indexOf("~"))}function nT(e,t){return`${e}~${Date.now()}-${process.pid}-${(0,ko.randomBytes)(4).toString("hex")}${t}`}const oT=/~(\d+)-\d+-[0-9a-f]+~(?:staging|prev)$/;async function sT(e,t){const r=oT.exec(t),n=r?Number(r[1]):0;try{const{mtimeMs:r}=await(0,xo.stat)((0,s.join)(e,t));return Date.now()-Math.max(n,r)>6e4}catch{return!1}}const iT="mcp_auth",aT="Authenticate this MCP server so its tools can be used. Call this tool through your MCP tool-calling interface when STATUS.md indicates this server needs authentication.",cT="# >>> CURSOR MANAGED BLOCK >>>",lT="# <<< CURSOR MANAGED BLOCK <<<",uT=["# Ignore everything in .cursor","*","# Un-ignore projects so we can descend to allowlisted subdirs","!projects/","projects/*","!projects/*/","projects/*/*","# MCP tool descriptors, resources, prompts","!projects/*/mcps/","!projects/*/mcps/**","# Agent transcripts for citation","!projects/*/agent-transcripts/","!projects/*/agent-transcripts/**","# Terminal output files","!projects/*/terminals/","!projects/*/terminals/**","# Conversation notes (shared scratchpad)","!projects/*/agent-notes/","!projects/*/agent-notes/**","# Large tool output files","!projects/*/agent-tools/","!projects/*/agent-tools/**","# Plugin cache (rules, skills, agents)","!plugins/","!plugins/**","# Built-in Cursor skills","!skills-cursor/","!skills-cursor/**","# User's personal skills","!skills/","!skills/**","# User's personal slash commands","!commands/","!commands/**","# User's plan files","!plans/","!plans/**","# Subagent state/transcripts","!subagents/","!subagents/**","# User-level cursor rules","!rules/","!rules/**"].join("\n");function dT(e,t,r=15e3){let n;return Promise.race([e.catch((()=>t)),new Promise((e=>{n=setTimeout((()=>e(t)),r)}))]).finally((()=>clearTimeout(n)))}function hT(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function pT(e){if(void 0===e)return;const t=e.trim();return t.length>0?t:void 0}function fT(e){switch(e.kind){case"loading":return"initializing";case"requires_authentication":return"needsAuth";case"ready":return"connected";case"error":return"error";default:return"disconnected"}}function mT(e){if(Array.isArray(e))return e.map((e=>mT(e)));if(function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e)){const t=Object.entries(e).filter((([,e])=>void 0!==e)).sort((([e],[t])=>et?1:0)).map((([e,t])=>[e,mT(t)]));return Object.fromEntries(t)}return e}function gT(e){return JSON.stringify(mT(e))}function wT(e){const t=e.map((e=>({value:e,key:gT(e)})));return t.sort(((e,t)=>e.keyt.key?1:0)),t.map((e=>e.value))}function yT(e){const t=wT(e.tools.map((e=>({name:e.toolName,description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema})))),r=wT(e.resources.map((e=>({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType})))),n=wT(e.prompts.map((e=>({name:e.name,description:e.description,arguments:e.arguments}))));return gT({id:e.serverIdentifier,name:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,tools:t,resources:r,prompts:n,instructions:e.instructions,status:e.status})}class vT{constructor(e,t,r){this.cachedFingerprints=new Map,this.disposed=!1,this.hasPendingLeaseChangeEvent=!1,this.lastDivergenceCheckMs=0,this.mcpLease=e,this.projectDir=t,this.debounceMs=r?.debounceMs??100,this.mcpAuthCopyOverrides=r?.mcpAuthCopyOverrides,this.exposeVirtualMcpAuthTool=r?.exposeVirtualMcpAuthTool??!0,this.alwaysExposeVirtualMcpAuthTool=r?.alwaysExposeVirtualMcpAuthTool??!1,this.snapshotProvider=r?.snapshotProvider,this.mcpVersion=r?.mcpVersion??(this.snapshotProvider?"snapshots":"v1"),this.onDidWrite=r?.onDidWrite,this.ctx=this.getContext(r?.loggerBackend),this.startupCleanupPromise=this.cleanupStaleStagingDirs(this.ctx),this.leaseChangeDisposable=this.mcpLease.onDidChange((e=>{KI.info(this.ctx,"Lease change event received",{serverIdentifiers:e?.serverIdentifiers,reason:e?.reason}),this.onLeaseChanged(this.ctx,e)})),KI.info(this.ctx,"Constructor: scheduling initial write"),this.scheduleWrite(this.ctx),this.ensureCursorDirGitignore()}ensureCursorDirGitignore(){(async function(e){const t=(0,s.join)(e,".gitignore"),r=`${cT}\n${uT}\n${lT}\n`;let n;await(0,xo.mkdir)(e,{recursive:!0});try{n=await(0,xo.readFile)(t,"utf-8")}catch(e){if("ENOENT"!==_c(e))throw e}if(void 0===n)return void await(0,xo.writeFile)(t,r);const o=n.indexOf(cT),i=n.indexOf(lT,o+30);if(-1===o||-1===i)await(0,xo.writeFile)(t,r);else{const e=`${n.slice(0,o)}${r}${n.slice(i+30).replace(/^\n/,"")}`;e!==n&&await(0,xo.writeFile)(t,e)}})((0,s.join)((0,o.homedir)(),".cursor")).catch((e=>{KI.warn(this.ctx,"Failed to ensure ~/.cursor/.gitignore",e)}))}async cleanupStaleStagingDirs(e){const t=this.getLogContext(e),r=(0,s.join)(this.projectDir,JI);try{const e=await(0,xo.readdir)(r);await Promise.allSettled(e.filter((e=>e.endsWith(XI))).map((async e=>{await sT(r,e)&&await(0,xo.rm)((0,s.join)(r,e),{recursive:!0,force:!0})})))}catch(e){"ENOENT"!==_c(e)&&KI.error(t,"Error clearing stale mcps staging dirs",e)}}onLeaseChanged(e,t){if(this.disposed)return;const r=t??{serverIdentifiers:void 0};this.hasPendingLeaseChangeEvent?this.pendingLeaseChangeEvent=function(...e){const[t,r]=e;return e.length<2?t:eo(r)?{serverIdentifiers:void 0,reason:t?.reason??r?.reason}:void 0===t?r:eo(t)?{serverIdentifiers:void 0,reason:t.reason??r?.reason}:{serverIdentifiers:[...new Set([...t.serverIdentifiers??[],...r?.serverIdentifiers??[]])],reason:t.reason??r?.reason}}(this.pendingLeaseChangeEvent??{serverIdentifiers:void 0},r):(this.pendingLeaseChangeEvent=r,this.hasPendingLeaseChangeEvent=!0),void 0!==this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout((()=>{this.debounceTimer=void 0;const t=this.takePendingLeaseChangeEvent();this.scheduleWrite(e,t)}),this.debounceMs)}takePendingLeaseChangeEvent(){if(!this.hasPendingLeaseChangeEvent)return;const e=this.pendingLeaseChangeEvent??{serverIdentifiers:void 0};return this.pendingLeaseChangeEvent=void 0,this.hasPendingLeaseChangeEvent=!1,e}scheduleWrite(e,t){const r=this.getLogContext(e);if(this.disposed)return;const n=this.writePromise;this.writePromise=(async()=>{if(n)try{await n}catch(e){KI.error(r,"Error waiting for previous write",e)}this.disposed||(await this.startupCleanupPromise,this.disposed||await this.fetchAndWrite(e,t))})()}getContext(e){let t=(0,b.q6)();return e&&(t=t.with(d._O,e)),t}getLogContext(e){return e.with(d._O,this.ctx.get(d._O))}getMetricTags(e){return{...e,mcp_version:this.mcpVersion}}getMcpAuthToolDescription(){return pT(this.mcpAuthCopyOverrides?.authToolDescription)??aT}shouldExposeVirtualMcpAuthToolForStatus(e,t){return this.exposeVirtualMcpAuthTool&&Jn(e)&&(this.alwaysExposeVirtualMcpAuthTool||"needsAuth"===t)}getErrorStatusMessage(){return pT(this.mcpAuthCopyOverrides?.errorStatusMessage)??"The MCP server errored. If this server is important for completing the task, concisely inform the user and ask them to check the MCP status in Cursor's Customize page > MCPs; otherwise continue with a different approach."}getNeedsAuthStatusMessage(e){return t=pT(this.mcpAuthCopyOverrides?.needsAuthStatusMessageWithAuthTool)??'The MCP server needs authentication. Authenticate it by calling the `{authToolName}` tool for server "{serverIdentifier}" through your MCP tool-calling interface using an empty arguments object. If this server is important for completing the task, authenticate it first; otherwise continue with a different approach.',r={serverIdentifier:e,authToolName:iT},t.replace(/\{serverIdentifier\}/g,r.serverIdentifier).replace(/\{authToolName\}/g,r.authToolName);var t,r}getNeedsAuthStatusMessageForWrite(e){return this.exposeVirtualMcpAuthTool&&Jn(e)?this.getNeedsAuthStatusMessage(e):pT(this.mcpAuthCopyOverrides?.needsAuthStatusMessageWithoutVirtualTool)??"This MCP server requires authentication before its tools can be used. Open Cursor's Customize page > MCPs, select this server, and use Authenticate/Reopen, or refresh credentials in your MCP configuration (for example mcp.json), then restart this environment. If this server is not required for the task, continue without it."}async getToolsForServers(e,t){if(0===t.length)return[];const r=this.getLogContext(e);try{return await this.mcpLease.getToolsForServers(e,t)}catch(n){KI.warn(r,`getToolsForServers() threw, falling back to filtered getTools(): ${Cc(n)}`);const o=await this.mcpLease.getTools(e).catch((e=>(KI.warn(r,`getTools() threw during scoped-tool fallback, defaulting to []: ${e}`),[]))),s=new Set(t);return o.filter((e=>s.has(e.clientKey)))}}async fetchClientDataForServer(e,t,r,n){const o=await dT(r.getState(e),{kind:"error"}).then((r=>("error"!==r.kind||"message"in r||KI.warn(e,`getState() timed out for "${t}", defaulting to error`),r))),s="ready"===o.kind||"requires_authentication"===o.kind,[i,a,c]=await Promise.all([s?dT(r.listResources(e),{resources:[]}):Promise.resolve({resources:[]}),s?dT(r.listPrompts(e),[]):Promise.resolve([]),s&&n?.fetchInstructions?dT(r.getInstructions(e),void 0):Promise.resolve(void 0)]);return{clientKey:t,serverName:r.serverName,plugin:r.plugin,marketplace:r.marketplace,pluginId:r.pluginId,marketplaceId:r.marketplaceId,resources:i.resources.map((e=>({...e,serverIdentifier:t,serverName:r.serverName}))),prompts:a.map((e=>({...e,serverIdentifier:t,serverName:r.serverName}))),instructions:c,status:fT(o)}}buildServerDataMap(e,t,r){const n=new Map;for(const e of t){const t=Fy(e.clientKey);n.set(e.clientKey,{serverIdentifier:e.clientKey,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,sanitizedId:t,folderPath:(0,s.join)(this.projectDir,JI,t),tools:[],resources:e.resources,prompts:e.prompts,instructions:e.instructions,status:e.status})}for(const t of e){let e=n.get(t.clientKey);if(!e){const r=Fy(t.clientKey);e={serverIdentifier:t.clientKey,serverName:t.providerIdentifier,plugin:t.plugin,marketplace:t.marketplace,pluginId:t.pluginId,marketplaceId:t.marketplaceId,sanitizedId:r,folderPath:(0,s.join)(this.projectDir,JI,r),tools:[],resources:[],prompts:[],instructions:void 0,status:void 0},n.set(t.clientKey,e)}e.tools.push(t)}if(void 0!==r)for(const e of r){const t=e.serverIdentifier?.trim();let r=t?Array.from(n.values()).find((e=>e.serverIdentifier===t)):void 0;if(!r){const t=e.serverName?.trim();r=t?Array.from(n.values()).find((e=>e.serverName===t)):void 0}r&&e.instructions&&(r.instructions=e.instructions)}if(this.exposeVirtualMcpAuthTool)for(const e of n.values())this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&(e.tools.some((e=>e.toolName===iT))||e.tools.push({clientKey:(o={serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,authToolDescription:this.getMcpAuthToolDescription()}).serverIdentifier,providerIdentifier:o.serverName,plugin:o.plugin,marketplace:o.marketplace,pluginId:o.pluginId,marketplaceId:o.marketplaceId,toolName:iT,name:iT,description:o.authToolDescription,inputSchema:{type:"object",properties:{},additionalProperties:!1}}));var o;return n}buildServersToWrite(e,t){const r=[],n=new Set;for(const o of t.values()){const t=o.tools.length>0||o.resources.length>0||o.prompts.length>0||o.instructions,s="error"===o.status||"needsAuth"===o.status||"initializing"===o.status;t||s?n.has(o.sanitizedId)?KI.warn(e,`Skipping server "${o.serverIdentifier}" — sanitizedId "${o.sanitizedId}" collides with another server`):(n.add(o.sanitizedId),r.push(o)):KI.info(e,`Server "${o.serverIdentifier}" excluded from write: tools=${o.tools.length}, resources=${o.resources.length}, prompts=${o.prompts.length}, hasInstructions=${!!o.instructions}, status=${o.status}`)}return r}mergeScopedRefreshWithCachedServerData(e,t){const r=[...t.tools];if(this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&!r.some((e=>e.toolName===iT))){const t=e.tools.find((e=>e.toolName===iT));void 0!==t&&r.push(t)}return{...e,...t,tools:r,resources:e.resources,prompts:e.prompts,instructions:e.instructions,status:e.status,plugin:t.plugin??e.plugin,marketplace:t.marketplace??e.marketplace,pluginId:t.pluginId??e.pluginId,marketplaceId:t.marketplaceId??e.marketplaceId}}async refreshServersFromLease(e,t){const r=this.getLogContext(e),n=[...new Set(t.serverIdentifiers??[])];KI.info(r,`fetchAndWrite: refreshing ${n.length} targeted servers`,{serverIdentifiers:n});const o=await this.getToolsForServers(e,n),s=await this.mcpLease.getInstructions(e).catch((e=>(KI.warn(r,`getInstructions() threw during scoped refresh, defaulting to []: ${e}`),[]))),i=await Promise.all(n.map((async t=>{try{const r=await this.mcpLease.getClient(e,t);return void 0===r?{serverIdentifier:t,kind:"missing"}:{serverIdentifier:t,kind:"client",client:r}}catch(e){return KI.warn(r,`getClient("${t}") threw during scoped refresh, preserving cached data: ${Cc(e)}`),{serverIdentifier:t,kind:"error",error:e}}}))),a=i.filter((e=>"missing"===e.kind)).map((e=>e.serverIdentifier));let c=new Set;if(a.length>0){const t=await this.mcpLease.getClients(e).catch((e=>{KI.warn(r,`getClients() threw while confirming targeted server removal, preserving cached data: ${e}`)}));void 0!==t&&(c=new Set(a.filter((e=>void 0===t[e]))))}const l=await Promise.all(i.filter((e=>"client"===e.kind)).map((({serverIdentifier:t,client:r})=>this.fetchClientDataForServer(e,t,r,{fetchInstructions:!0})))),u=new Map((this.cachedServerData??[]).map((e=>[e.serverIdentifier,e]))),d=this.buildServerDataMap(o,l,s),h=new Set(n),p=new Set(i.filter((e=>"error"===e.kind||"missing"===e.kind&&!c.has(e.serverIdentifier))).map((e=>e.serverIdentifier)));for(const e of n){const t=u.get(e),n=d.get(e);if(void 0===n)c.has(e)?u.delete(e):KI.warn(r,`refreshServersFromLease: preserving cached data for "${e}" because targeted refresh returned no replacement`);else{if(p.has(e)&&void 0!==t){u.set(e,this.mergeScopedRefreshWithCachedServerData(t,n)),KI.warn(r,`refreshServersFromLease: preserving cached metadata for "${e}" because the client was unavailable during targeted refresh`);continue}u.set(e,n)}}const f=new Map(Array.from(u.values()).map((e=>[e.sanitizedId,e.serverIdentifier])));for(const[e,t]of this.cachedFingerprints)if(!h.has(e)&&!u.has(e)){const t=Fy(e);f.set(t,e)}const m=this.buildServersToWrite(e,u);await this.writeServerData(e,m,f),this.cachedServerData=m,this.fireOnDidWrite(m)}async fetchAndWrite(e,t){const r={stack:[],error:void 0,hasError:!1};try{NI(r,(0,D.VI)(e.withName("McpFileSystemWriter.fetchAndWrite")),!1);const n=this.getLogContext(e);try{if(void 0!==this.cachedServerData&&void 0!==t&&!eo(t)&&[...new Set(t.serverIdentifiers??[])].length>0)return void await this.refreshServersFromLease(e,t);const[r,o,s]=await Promise.all([this.mcpLease.getTools(e).catch((e=>(KI.warn(n,`getTools() threw, defaulting to []: ${e}`),[]))),this.mcpLease.getInstructions(e).catch((()=>[])),this.mcpLease.getClients(e).catch((e=>(KI.warn(n,`getClients() threw, defaulting to {}: ${e}`),{})))]),i=Object.keys(s);KI.info(n,`fetchAndWrite: lease returned ${r.length} tools across ${i.length} clients`);const a=Object.entries(s).map((([t,r])=>this.fetchClientDataForServer(e,t,r))),c=await Promise.all(a),l=this.buildServerDataMap(r,c,o),u=this.buildServersToWrite(e,l),d=new Map(Array.from(l.values()).map((e=>[e.sanitizedId,e.serverIdentifier])));await this.writeServerData(e,u,d),this.cachedServerData=u,this.fireOnDidWrite(u)}catch(e){KI.error(n,"Error fetching/writing MCP state",e)}}catch(e){r.error=e,r.hasError=!0}finally{LI(r)}}fireOnDidWrite(e){if(this.onDidWrite)try{const t=e.map((e=>({serverIdentifier:e.serverIdentifier,folderPath:e.folderPath,tools:e.tools.map((t=>({toolName:t.toolName,definitionPath:(0,s.join)(e.folderPath,ZI,`${hT(t.toolName)}.json`)})))})));this.onDidWrite(t)}catch{}}async writeServerData(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{NI(n,(0,D.VI)(e.withName("McpFileSystemWriter.writeServerData")),!1);const o=this.getLogContext(e),i=(0,s.join)(this.projectDir,JI);await(0,xo.mkdir)(i,{recursive:!0});const a=new Map;for(const e of t)try{a.set(e.serverIdentifier,yT(e))}catch(t){KI.error(o,"Error computing server fingerprint, will force write",t,{serverIdentifier:e.serverIdentifier}),a.set(e.serverIdentifier,`__error_${Date.now()}_${Math.random()}`)}const c=[];for(const e of t){const t=this.cachedFingerprints.get(e.serverIdentifier);t!==a.get(e.serverIdentifier)&&(c.push(e),void 0!==t&&KI.info(o,`Server "${e.serverIdentifier}" fingerprint changed: tools=${e.tools.length}, status=${e.status}`))}for(const e of t)if(!c.includes(e))try{await(0,xo.stat)((0,s.join)(i,e.sanitizedId))}catch{KI.info(o,`Server "${e.serverIdentifier}" directory missing on disk, forcing write`),c.push(e)}const l=new Set;for(const[e]of this.cachedFingerprints)if(!a.has(e)){const t=this.cachedServerData?.find((t=>t.serverIdentifier===e)),n=t?.sanitizedId??Fy(e);r.has(n)?(KI.info(o,`Server "${e}" (sanitized="${n}") still in lease but excluded from write, preserving directory`),a.set(e,this.cachedFingerprints.get(e))):(KI.info(o,`Server "${e}" (sanitized="${n}") left the lease, scheduling directory removal`),l.add(n))}const u=void 0===this.cachedServerData;if(u)try{const e=await(0,xo.readdir)(i),t=new Set(e.filter((e=>!e.endsWith(XI)&&!e.endsWith(QI))));for(const r of e){const e=r.endsWith(XI),n=r.endsWith(QI);if((e||n)&&await sT(i,r))if(e)await(0,xo.rm)((0,s.join)(i,r),{recursive:!0,force:!0});else{const e=rT(r);if(t.has(e))await(0,xo.rm)((0,s.join)(i,r),{recursive:!0,force:!0});else try{await(0,xo.rename)((0,s.join)(i,r),(0,s.join)(i,e)),t.add(e)}catch{await(0,xo.rm)((0,s.join)(i,r),{recursive:!0,force:!0}).catch((()=>{}))}}}for(const e of t)if(r.has(e)){const t=r.get(e);a.has(t)||a.set(t,`__preserved_${e}`)}else l.add(e)}catch(e){KI.error(o,"Error clearing mcps directory",e)}const d=Array.from(l);if(c.length>0||l.size>0){const e=c.map((e=>({serverIdentifier:e.serverIdentifier,sanitizedId:e.sanitizedId,toolCount:e.tools.length})));KI.info(o,`Incremental write: ${c.length} changed, ${l.size} removed, ${t.length-c.length} unchanged`,{changedServerCount:c.length,changedServers:e,removedServerCount:l.size,removedServerSanitizedIds:d,unchangedServerCount:t.length-c.length,totalServerCount:t.length,leaseServerCount:r.size,coldStartReconcile:u,projectDirHash:(0,ko.createHash)("sha256").update(this.projectDir).digest("hex")},{includeStructuredLogs:!0})}const h=await Promise.allSettled(c.map((t=>this.writeServerAtomic(e,t,i))));for(let t=0;t(0,xo.rm)((0,s.join)(i,e),{recursive:!0,force:!0}))));for(let r=0;r{await(i?.catch((()=>{}))),await this.swapServerDirectory(e,t,r)})();tT.set(o,a);try{await a}finally{tT.get(o)===a&&tT.delete(o)}}catch(e){n.error=e,n.hasError=!0}finally{LI(n)}}async swapServerDirectory(e,t,r){const n=nT(t.sanitizedId,XI),o=(0,s.join)(r,n),i=(0,s.join)(r,t.sanitizedId);try{await this.writeServerDirectory(e,t,{basePath:r,dirName:n})}catch(e){throw await(0,xo.rm)(o,{recursive:!0,force:!0}).catch((()=>{})),e}const a=(0,s.join)(r,nT(t.sanitizedId,QI));let c=!1;try{try{await this.renameWithRetry(i,a),c=!0}catch(e){if("ENOENT"!==_c(e))throw e}await this.renameWithRetry(o,i)}catch(r){if(KI.error(e,"Per-server swap failed",r,{serverIdentifier:t.serverIdentifier,sanitizedId:t.sanitizedId},{includeStructuredLogs:!0}),c)try{await this.renameWithRetry(a,i)}catch{await(0,xo.stat)(i).then((()=>!0),(()=>!1))&&await(0,xo.rm)(a,{recursive:!0,force:!0}).catch((()=>{}))}throw await(0,xo.rm)(o,{recursive:!0,force:!0}).catch((()=>{})),r}await(0,xo.rm)(a,{recursive:!0,force:!0}).catch((()=>{}))}async renameWithRetry(e,t){for(let r=0;;r++)try{return void await(0,xo.rename)(e,t)}catch(e){const t=_c(e);if(r>=YI.length||void 0===t||!eT.has(t))throw e;await(0,Nr.cb)(YI[r])}}async writeServerDirectory(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{NI(n,(0,D.VI)(e.withName("McpFileSystemWriter.writeServerDirectory")),!1);const o=(0,s.join)(r.basePath,r.dirName??t.sanitizedId);await(0,xo.mkdir)(o,{recursive:!0});const i=[];if(t.tools.length>0){const e=(0,s.join)(o,ZI);await(0,xo.mkdir)(e,{recursive:!0});for(const r of t.tools){const t=hT(r.toolName);i.push({path:(0,s.join)(e,`${t}.json`),content:JSON.stringify(Qn(r),null,2)})}}if(t.resources.length>0){const e=(0,s.join)(o,"resources");await(0,xo.mkdir)(e,{recursive:!0});for(const r of t.resources){const t=hT(r.name||r.uri.replace(/[^a-zA-Z0-9_-]/g,"_")),n={uri:r.uri,name:r.name,description:r.description,mimeType:r.mimeType};i.push({path:(0,s.join)(e,`${t}.json`),content:JSON.stringify(n,null,2)})}}if(t.prompts.length>0){const e=(0,s.join)(o,"prompts");await(0,xo.mkdir)(e,{recursive:!0});for(const r of t.prompts){const t=hT(r.name),n={name:r.name,description:r.description,arguments:r.arguments};i.push({path:(0,s.join)(e,`${t}.json`),content:JSON.stringify(n,null,2)})}}t.instructions&&t.instructions.trim().length>0&&i.push({path:(0,s.join)(o,"INSTRUCTIONS.md"),content:t.instructions.trim()}),"error"!==t.status&&"needsAuth"!==t.status||i.push({path:(0,s.join)(o,"STATUS.md"),content:"error"===t.status?this.getErrorStatusMessage():this.getNeedsAuthStatusMessageForWrite(t.serverIdentifier)});const a={serverIdentifier:t.serverIdentifier,serverName:t.serverName};i.push({path:(0,s.join)(o,"SERVER_METADATA.json"),content:JSON.stringify(a,null,2)});if(new Set(i.map((e=>e.path.toLowerCase()))).size!==i.length){for(const e of i)await(0,xo.writeFile)(e.path,e.content);return}const c=(await(0,Nr.up)(i,(e=>(0,xo.writeFile)(e.path,e.content)),{max:8})).find((e=>"rejected"===e.status));if(c)throw c.reason}catch(e){n.error=e,n.hasError=!0}finally{LI(n)}}async getMcpFileSystemOptions(e,t){const r={stack:[],error:void 0,hasError:!1};try{if(this.disposed)return;NI(r,(0,D.VI)(e.withName("McpFileSystemWriter.getMcpFileSystemOptions")),!1);const n=this.getLogContext(e),o=await this.ensureWritesSettled(e,t?.timeoutMs);if(this.snapshotProvider&&!o)return this.buildOptionsFromSnapshots(e);this.snapshotProvider&&o&&KI.warn(n,"Snapshot mode write barrier timed out; falling back to cached descriptors",{timeoutMs:t?.timeoutMs},{includeStructuredLogs:!0});const i=(this.cachedServerData??[]).map((e=>{const t=e.tools.map((t=>{const r=hT(t.toolName),n=(0,s.join)(e.folderPath,ZI,`${r}.json`);return new vn.E$({toolName:t.toolName,definitionPath:n,...Nb(t.annotations)})}));return new vn.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,folderPath:e.folderPath,serverUseInstructions:e.instructions,tools:t})}));return this.checkDescriptorsVsFilesystem(e,i,"workbench_lease"),new vn.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:i})}catch(e){r.error=e,r.hasError=!0}finally{LI(r)}}async ensureWritesSettled(e,t){const r=this.getLogContext(e),n=void 0!==this.debounceTimer;if(void 0!==this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0,this.scheduleWrite(e,this.takePendingLeaseChangeEvent())),n&&KI.info(r,"getMcpFileSystemOptions force-fired pending debounce"),!this.writePromise)return!1;if(void 0!==t){let e,n=!1;try{await Promise.race([this.writePromise,new Promise((r=>{e=setTimeout((()=>{n=!0,r()}),t)}))])}catch(e){KI.error(r,"Error waiting for pending write to complete",e)}finally{clearTimeout(e)}return n&&KI.warn(r,`getMcpFileSystemOptions timed out after ${t}ms waiting for write; returning stale cache`),n}try{await this.writePromise}catch(e){KI.error(r,"Error waiting for pending write to complete",e)}return!1}async buildOptionsFromSnapshots(e){const t={stack:[],error:void 0,hasError:!1};try{NI(t,(0,D.VI)(e.withName("McpFileSystemWriter.buildOptionsFromSnapshots")),!1);const r=this.getLogContext(e),n=Date.now(),o=await this.snapshotProvider.getAllSnapshots(e),i=(0,s.join)(this.projectDir,JI),a=o.filter((e=>e.tools.length>0||e.resources.length>0||e.prompts.length>0||void 0!==e.instructions||this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)||"needsAuth"===e.status||"error"===e.status)).map((e=>{const t=Fy(e.serverIdentifier),r=(0,s.join)(i,t),n=e.tools.map((e=>{const t=hT(e.name);return new vn.E$({toolName:e.name,definitionPath:(0,s.join)(r,ZI,`${t}.json`),...Nb(e.annotations)})}));if(this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&!e.tools.some((e=>e.name===iT))){const e=hT(iT);n.push(new vn.E$({toolName:iT,definitionPath:(0,s.join)(r,ZI,`${e}.json`)}))}return new vn.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,folderPath:r,serverUseInstructions:e.instructions,tools:n})})),c=a.reduce(((e,t)=>e+t.tools.length),0);return KI.info(r,`buildOptionsFromSnapshots completed in ${Date.now()-n}ms: ${o.length} snapshots, ${a.length} descriptors, ${c} tools`),this.checkDescriptorsVsFilesystem(e,a,"snapshot"),new vn.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:a})}catch(e){t.error=e,t.hasError=!0}finally{LI(t)}}async waitForPendingWrites(){if(void 0!==this.debounceTimer&&await new Promise((e=>{const t=()=>{void 0===this.debounceTimer?e():setTimeout(t,10)};t()})),this.writePromise)try{await this.writePromise}catch{}}getCachedServerData(){return this.cachedServerData}checkDescriptorsVsFilesystem(e,t,r){const n=this.getLogContext(e),o=Date.now();o-this.lastDivergenceCheckMs{KI.warn(n,"Divergence check failed",e)})))}async _checkDescriptorsVsFilesystemAsync(e,t,r){const n=this.getLogContext(e),o=(0,s.join)(this.projectDir,JI),i=new Set,a=new Map;for(const e of t){const t=Fy(e.serverIdentifier);i.add(t),a.set(t,e.tools.length)}let c=[];try{c=await(0,xo.readdir)(o),c=c.filter((e=>!e.endsWith(XI)&&!e.endsWith(QI)))}catch(e){if("ENOENT"!==_c(e))throw e}const l=new Set(c);let u=!0,d=0,h=0,p=0;const f=function(e){return 0===e?"0":e<=3?"1-3":e<=6?"4-6":e<=10?"7-10":"11+"}(i.size);for(const t of i)l.has(t)||(u=!1,d++,jI.increment(e,1,this.getMetricTags({divergence_type:"server_missing",mcp_source:r,configured_servers:f})),KI.warn(n,"Divergence detected: server missing from filesystem",{mcpFileSystemMeta:{divergenceType:"server_missing",serverId:t,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}));for(const t of l)i.has(t)||(u=!1,h++,jI.increment(e,1,this.getMetricTags({divergence_type:"server_stale",mcp_source:r,configured_servers:f})));for(const t of i){if(!l.has(t))continue;const c=a.get(t)??0,d=(0,s.join)(o,t,ZI);let h=0;try{h=(await(0,xo.readdir)(d)).filter((e=>e.endsWith(".json"))).length}catch{}h!==c&&(u=!1,p++,jI.increment(e,1,this.getMetricTags({divergence_type:"tool_count_mismatch",mcp_source:r,configured_servers:f})),KI.warn(n,"Divergence detected: tool count mismatch",{mcpFileSystemMeta:{divergenceType:"tool_count_mismatch",serverId:t,expected:c,actual:h,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}))}UI.increment(e,1,this.getMetricTags({synced:String(u),mcp_source:r,configured_servers:f})),BI.gauge(e,i.size,this.getMetricTags({mcp_source:r})),WI.gauge(e,l.size,this.getMetricTags({mcp_source:r})),HI.gauge(e,d,this.getMetricTags({mcp_source:r})),qI.gauge(e,p,this.getMetricTags({mcp_source:r})),KI.info(n,"MCP filesystem sync check",{mcpFileSystemMeta:{synced:u,expectedServers:i.size,actualServers:l.size,serversMissing:d,serversStale:h,toolMismatches:p,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}),u||KI.warn(n,"MCP filesystem divergence summary",{mcpFileSystemMeta:{synced:u,expectedServers:i.size,actualServers:l.size,serversMissing:d,serversStale:h,toolMismatches:p,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0})}dispose(){this.disposed||(this.disposed=!0,void 0!==this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.leaseChangeDisposable&&(this.leaseChangeDisposable.dispose(),this.leaseChangeDisposable=void 0),this.cachedServerData=void 0,this.cachedFingerprints.clear())}}vT.DIVERGENCE_CHECK_COOLDOWN_MS=1e4;var bT=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},ST=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function kT(e){if("object"!=typeof e||null===e||Array.isArray(e))return;const t={};for(const[r,n]of Object.entries(e))"string"==typeof n&&(t[r]=n);return t}const _T=(0,d.h)("local-exec:mcp");function CT(e,t){const r=s.relative(e,t);return""===r||!s.isAbsolute(r)&&".."!==r&&!r.startsWith(`..${s.sep}`)}function ET(e){return e instanceof Error&&"code"in e&&"string"==typeof e.code?e.code:void 0}function xT(e){return new Mc._Z({content:{case:"image",value:new Mc.do({data:e.data,mimeType:e.mimeType})}})}function PT(e){return new Mc._Z({content:{case:"text",value:new Mc.zN({text:e})}})}async function RT(e,t,r){const n=await r.permissionsService.shouldBlockMcp(e,t,r.toolDef,{alreadyApproved:t.skipApproval,...void 0===r.client?{}:{client:r.client},...void 0===r.resolvedTool?{}:{resolvedTool:r.resolvedTool}});if(!n)return;const o=await ed(n,{onNeedsApproval:async(e,n)=>{if("mcp"!==n.type)return new Mc.iz({result:{case:"error",value:new Mc.Nh({error:"Invalid approval details type for MCP execution"})}});const o=await r.pendingDecisionProvider.requestApproval({type:Bw.Mcp,details:{name:n.name,toolName:n.toolName,toolTitle:n.toolTitle,destructiveHint:n.destructiveHint,providerIdentifier:n.providerIdentifier,source:r.toolDef?.source,args:n.args,reason:n.reason??e,canAllowlist:n.canAllowlist,smartModeApprovalReason:n.smartModeApprovalReason,smartModeApprovalRequestId:n.smartModeApprovalRequestId,allowlistEntry:n.allowlistEntry,computerUseApp:n.computerUseApp},toolCallId:t.toolCallId});return o.approved&&void 0!==n.computerUseApp&&!0!==n.computerUseApp.allowOnce&&r.permissionsService.allowComputerUseAppForSession?.({bundleId:n.computerUseApp.bundleId}),o.approved?t.smartModeApprovalOnly?new Mc.iz({result:{case:"approved",value:new Mc.Ke}}):null:new Mc.iz({result:{case:"rejected",value:new Mc.xo({reason:`User rejected MCP: ${t.name}${o.reason?` - ${o.reason}`:""}`})}})},onUserRejected:e=>new Mc.iz({result:{case:"error",value:new Mc.Nh({error:`User rejected MCP: ${t.name}${e?` - ${e}`:""}`})}}),onPermissionDenied:(e,r)=>IT({name:t.name,reason:e,isReadonly:r?.isReadonly??!1})});return o??void 0}function IT({name:e,reason:t,isReadonly:r}){return new Mc.iz({result:{case:"permissionDenied",value:new Mc.HQ({error:`MCP tool execution blocked: ${e} - ${t}`,isReadonly:r})}})}class TT{constructor(e,t,r,n,o=4e4,s,i,a={}){this.toolSet=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.projectDir=n,this.fileOutputThresholdBytes=o,this.elicitationFactory=s,this.ensureMcpServersLoaded=i,this.spillOptions=a}async describeDisconnectedServer(e,t){const r=new Set(t.filter((e=>""!==e)));if(0===r.size)return;let n;try{n=await this.toolSet.getClients(e)}catch{return}const o=Object.entries(n).find((([e,t])=>r.has(e)||r.has(t.serverName)));if(void 0===o)return;const[s,i]=o;let a;try{a=await i.getState(e)}catch{return}if("ready"===a.kind&&void 0===a.toolListError)return;const c=function(e){switch(e){case"needsAuth":return"This MCP server requires authentication before its tools can be used.";case"error":return"This MCP server failed during live tool discovery. Its tools are unavailable until the connection is fixed.";case"loading":return"This MCP server is still loading; tools may not be available yet.";default:return}}(to(a));return void 0!==c?`MCP server "${s}" has no callable tools right now. ${c}${"error"===a.kind&&a.message?` (${a.message})`:""}`:void 0}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=bT(r,(0,D.VI)(e.withName("LocalMcpToolExecutor.execute")),!1).ctx,i=t.serverIdentifier||t.providerIdentifier;await(this.ensureMcpServersLoaded?.(o,[i]));const a=await this.toolSet.getTools(o),c=Array.from(new Set(a.map((e=>e.clientKey)))).sort(),l=a.find((e=>e.clientKey===i&&e.toolName===t.toolName)),u=a.find((e=>e.name===t.name));if(void 0!==u&&(void 0!==l?u!==l:u.toolName!==t.toolName||u.clientKey!==i&&u.providerIdentifier!==i))return new Mc.iz({result:{case:"error",value:new Mc.Nh({error:`MCP tool "${t.name}" is not the tool "${t.toolName}" on server "${i}" that the call names.`})}});const d=void 0===l?void 0:await this.toolSet.getClient(o,l.clientKey).catch((()=>{})),h=l??u,p=void 0===h?void 0:h===l?d:await this.toolSet.getClient(o,h.clientKey).catch((()=>{})),f=await RT(o,t,{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionProvider,toolDef:l,...void 0===d?{}:{client:d},...void 0===h?{}:{resolvedTool:void 0===p?"unresolved":{client:p,annotations:h.annotations}}});if(void 0!==f)return f;const m=await this.toolSet.getToolSet(o),g=!0===await(this.permissionsService.enforcesMcpAdminToolLimits?.());let w;try{if(g&&void 0===h)throw new kC(t.name,a.map((e=>e.name)));const e=l?.name??t.name,r=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()])));if(g){const n=void 0===p?void 0:await(m.executeOn?.(p,e,r,t.toolCallId,this.elicitationFactory));if(void 0===n)return _T.warn(o,"Refusing an MCP tool whose client was not judged",{toolName:t.toolName,toolSetNamesClients:void 0!==m.executeOn}),IT({name:t.name,reason:ik,isReadonly:!1});w=n}else w=await m.execute(e,r,t.toolCallId,this.elicitationFactory)}catch(e){let r=e;if(_C(r)&&t.providerIdentifier.length>0&&!a.some((e=>e.clientKey===t.providerIdentifier||e.providerIdentifier===t.providerIdentifier))&&(r=new rI(t.providerIdentifier,c)),r instanceof rI){const e=await this.describeDisconnectedServer(o,[i,t.providerIdentifier]);return void 0!==e?new Mc.iz({result:{case:"error",value:new Mc.Nh({error:e})}}):new Mc.iz({result:{case:"serverNotFound",value:new Mc.JL({name:r.serverName,availableServers:r.availableServers})}})}if(_C(r))return new Mc.iz({result:{case:"toolNotFound",value:new Mc.WV({name:r.toolName,availableTools:r.availableTools})}});throw r}const y=[];for(const e of w.content){const r=e.type;if("text"===r&&"object"==typeof e&&null!==e&&"text"in e&&"string"==typeof e.text)y.push(PT(e.text));else if("resource"===r){const r=aE(e),n=void 0===r?void 0:Buffer.from(r,"base64"),s=void 0===n?void 0:await Bv(n).then(xT,(e=>{_T.warn(o,"Describing an undecodable MCP resource image",{toolName:t.toolName,bytes:n.byteLength,error:e instanceof Error?e.message:String(e)})}));y.push(s??PT(cE(e)))}else if("image"===r){const r=e,s="string"==typeof r.data?Buffer.from(r.data,"base64"):Buffer.alloc(0);let i;try{i=await Bv(s)}catch(e){_T.warn(o,"Omitting undecodable MCP tool image",{toolName:t.toolName,mimeType:"string"==typeof r.mimeType?r.mimeType.slice(0,100):typeof r.mimeType,bytes:s.byteLength,error:e instanceof Error?e.message:String(e)}),y.push(PT(`[Image omitted: the tool returned ${n=r.mimeType,"string"==typeof n&&/^image\/[\w.+-]{1,40}$/.test(n)?n:"image"} data (${s.byteLength} bytes) that could not be decoded.]`));continue}y.push(xT(i))}else if("image"!==r){const t=cE(e);y.push(PT(t))}}const v=await async function({contentItems:e,thresholdBytes:t,write:r}){const n=e.filter((e=>"text"===e.content.case&&void 0===e.content.value.outputLocation)).map((e=>"text"===e.content.case?e.content.value.text:"")).join("\n\n");if(t<=0||Buffer.byteLength(n,"utf8")<=t)return e;const o=await r(n);if(void 0===o)return;const s=[];let i=!1;for(const t of e)"text"===t.content.case&&void 0===t.content.value.outputLocation?i||(s.push(new Mc._Z({content:{case:"text",value:new Mc.zN({text:"",outputLocation:o})}})),i=!0):s.push(t);return s}({contentItems:y,thresholdBytes:this.fileOutputThresholdBytes,write:e=>async function(e,t,r){const n=s.join(t,Dc),o=s.join(n,`${(0,ko.randomUUID)()}.txt`);await(0,xo.mkdir)(s.dirname(o),{recursive:!0});const i=Jo(!0===r.blankSharedPaymentTokens?tx(e):e,Oc),a=Xs(i),c=Buffer.byteLength(i,"utf8");return await(0,xo.writeFile)(o,i,"utf8"),new Fc.pV({filePath:o,sizeBytes:BigInt(c),lineCount:BigInt(a)})}(e,this.projectDir,this.spillOptions)});if(void 0===v)throw new Error("Failed to materialize MCP text output");const b=w.structuredContent&&"object"==typeof w.structuredContent&&!Array.isArray(w.structuredContent)?ve.Struct.fromJson(w.structuredContent):void 0,S=new Mc.QW({content:v,isError:w.isError,structuredContent:b,resultMeta:void 0===w._meta?void 0:ve.Struct.fromJson(w._meta)});return new Mc.iz({result:{case:"success",value:S}})}catch(e){r.error=e,r.hasError=!0}finally{ST(r)}var n}}class AT{constructor(e,t){this.mcpLease=e,this.ensureMcpServersLoaded=t}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=bT(r,(0,D.VI)(e.withName("LocalListMcpResourcesExecutor.execute")),!1).ctx;try{if(t.server){await(this.ensureMcpServersLoaded?.(n,[t.server]));const e=await this.mcpLease.getClients(n),r=e[t.server]??Object.values(e).find((e=>e.serverName===t.server));if(!r)return new Mc.kP({result:{case:"error",value:new Mc.w2({error:`Server "${t.server}" not found`})}});const o=await this.listResourcesFromClient(n,r,t.server,!0);return new Mc.kP({result:{case:"success",value:new Mc.T2({resources:o})}})}const e=await this.mcpLease.getClients(n),r=new Set,o=await this.mcpLease.getTools(n);for(const e of o)r.add(e.providerIdentifier),r.add(`user-${e.providerIdentifier}`);const s=[];for(const[t,o]of Object.entries(e)){if(r.size>0&&!r.has(t))continue;const e=await this.listResourcesFromClient(n,o,t);s.push(...e)}return new Mc.kP({result:{case:"success",value:new Mc.T2({resources:s})}})}catch(e){const t=e instanceof Error?e.message:String(e);return new Mc.kP({result:{case:"error",value:new Mc.w2({error:`Failed to list MCP resources: ${t}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{ST(r)}}async listResourcesFromClient(e,t,r,n=!1){const o=await t.getState(e);if("ready"!==o.kind&&(!n||"loading"!==o.kind))return[];const s=await t.listResources(e);return s&&s.resources?s.resources.map((e=>new Mc.X2({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType,server:r,annotations:kT(e.annotations)}))):[]}}class $T{constructor(e,t=".",r,n=[],o,s,i){this.mcpLease=e,this.projectDir=t,this.pendingDecisionProvider=o,this.ensureMcpServersLoaded=s,this.writeExecutor=i,this.workspacePaths=n.filter((e=>e.length>0))}resolveProjectDir(e){const t=e.get(OI),r=t?.find((e=>"string"==typeof e&&e.length>0));return r||(this.workspacePaths.length>0?this.workspacePaths[0]:this.projectDir)}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=bT(r,(0,D.VI)(e.withName("LocalReadMcpResourceExecutor.execute")),!1).ctx,o=t.smartModeApproval?.reason;if(void 0!==o){if(void 0===this.pendingDecisionProvider)return new Mc.ZD({result:{case:"error",value:new Mc.Jx({uri:t.uri,error:"Auto-review approval provider is not configured"})}});const e=await this.pendingDecisionProvider.requestApproval({type:Bw.Mcp,details:{name:"FetchMcpResource",toolName:"FetchMcpResource",providerIdentifier:t.server,args:{server:ve.Value.fromJson(t.server),uri:ve.Value.fromJson(t.uri),...void 0!==t.downloadPath?{downloadPath:ve.Value.fromJson(t.downloadPath)}:{}},reason:"smartMode",canAllowlist:!1,smartModeApprovalReason:o,smartModeApprovalRequestId:t.smartModeApproval?.requestId},toolCallId:t.toolCallId});if(!e.approved)return new Mc.ZD({result:{case:"rejected",value:new Mc.Dh({reason:"User rejected MCP resource fetch"+(e.reason?` - ${e.reason}`:"")})}})}await(this.ensureMcpServersLoaded?.(n,[t.server]));const i=await this.mcpLease.getClients(n),a=i[t.server]??Object.values(i).find((e=>e.serverName===t.server));if(!a)return new Mc.ZD({result:{case:"error",value:new Mc.Jx({uri:t.uri,error:`Server "${t.server}" not found`})}});try{if("ready"!==(await a.getState(n)).kind)return new Mc.ZD({result:{case:"error",value:new Mc.Jx({uri:t.uri,error:`Server "${t.server}" is not ready`})}});const e=await a.readResource(n,{uri:t.uri});if(!e||!e.contents||0===e.contents.length)return new Mc.ZD({result:{case:"notFound",value:new Mc.ov({uri:t.uri})}});const r=e.contents[0];if(t.downloadPath){const e=await async function(e,t){const r=s.resolve(e),n=await(0,xo.realpath)(r),o=s.isAbsolute(t)?s.resolve(t):s.resolve(r,t),i=CT(r,o),a=s.isAbsolute(t)&&CT(n,o);if(!i&&!a)throw new Error("downloadPath must stay within the workspace");let c=s.dirname(o);for(;;)try{if(!CT(n,await(0,xo.realpath)(c)))throw new Error("downloadPath must stay within the workspace");break}catch(e){if("ENOENT"!==ET(e))throw e;const t=s.dirname(c);if(t===c)throw e;c=t}try{if((await(0,xo.lstat)(o)).isSymbolicLink())throw new Error("downloadPath must stay within the workspace")}catch(e){if("ENOENT"!==ET(e))throw e}return o}(this.resolveProjectDir(n),t.downloadPath);let o=e;if(r.text||r.blob){if(void 0===this.writeExecutor)throw new Error("File-write executor is not configured");const s=await this.writeExecutor.execute(n,new FI.hY({path:e,fileText:r.text??"",fileBytes:r.text||void 0===r.blob?new Uint8Array:new Uint8Array(Buffer.from(r.blob,"base64")),toolCallId:t.toolCallId,confineToWorkspace:!0}));if("rejected"===s.result.case)return new Mc.ZD({result:{case:"rejected",value:new Mc.Dh({uri:t.uri,reason:s.result.value.reason})}});if("success"!==s.result.case)return new Mc.ZD({result:{case:"error",value:new Mc.Jx({uri:t.uri,error:MT(s)})}});o=s.result.value.path}return new Mc.ZD({result:{case:"success",value:new Mc.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,downloadPath:o})}})}if(r.text)return new Mc.ZD({result:{case:"success",value:new Mc.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:kT(r.annotations),metaJson:Xn(r._meta),content:{case:"text",value:r.text}})}});if(r.blob){const e=Buffer.from(r.blob,"base64");return new Mc.ZD({result:{case:"success",value:new Mc.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:kT(r.annotations),metaJson:Xn(r._meta),content:{case:"blob",value:e}})}})}return new Mc.ZD({result:{case:"error",value:new Mc.Jx({uri:t.uri,error:"Failed to read resource"})}})}catch(e){const r=e instanceof Error?e.message:String(e);return _T.warn(n,"LocalReadMcpResourceExecutor.execute failed",{server:t.server,hasDownloadPath:Boolean(t.downloadPath),errorName:e instanceof Error?e.name:typeof e,errorMessage:r}),new Mc.ZD({result:{case:"error",value:new Mc.Jx({uri:t.uri,error:`Failed to read MCP resource: ${r}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{ST(r)}}}function MT(e){switch(e.result.case){case"error":return e.result.value.error;case"permissionDenied":return e.result.value.error||"Permission denied";case"noSpace":return"No space left on device";case"rejected":return e.result.value.reason||"Write rejected";case"success":return"";case void 0:return"Write executor returned result without case";default:{const t=e.result;return String(t)}}}var DT=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const OT=1e4,FT=5e3,NT={PAGER:"cat",MANPAGER:"cat",LESS:"-R",PIP_PROGRESS_BAR:"off",TQDM_DISABLE:"1"};class LT{constructor(){this.fullOutput="",this.outputHead="",this.outputTail="",this.totalChars=0}append(e){if(0===e.length)return;const t=this.totalChars;if(this.totalChars+=e.length,tOT&&(this.fullOutput="")}getOutput(){return this.totalChars<=OT?this.fullOutput:void 0}getTruncation(){if(!(this.totalChars<=OT))return{outputHead:this.outputHead,outputTail:this.outputTail,elidedChars:this.totalChars-this.outputHead.length-this.outputTail.length}}}class jT{constructor(){this.kept="",this.full=!1}append(e){if(this.full)return;const t=os-this.kept.length;this.full=e.length>=t,this.kept+=Jo(e,t)}get text(){return this.kept}}function UT(e,t){return null!==e?e:null===t?-1:-o.constants.signals[t]}class BT{constructor(e,t,r){this.permissionsService=e,this.ignoreService=t,this.defaultCwd=r}buildResult({args:e,workingDirectory:t,processResult:r,sandboxPolicy:n}){const o={command:e.command,workingDirectory:t,exitCode:r.returncode,signal:r.signal,stdout:r.stdout,stderr:r.exceptionInfo||r.stderr,interleavedOutput:r.output,outputHead:r.outputTruncation?.outputHead,outputTail:r.outputTruncation?.outputTail,elidedChars:r.outputTruncation?.elidedChars,executionTime:r.localExecutionTimeMs??0,localExecutionTimeMs:r.localExecutionTimeMs},s=r.exceptionInfo.length>0,i=0!==r.returncode||s?{case:"failure",value:new fe.xC({...o,aborted:s,abortReason:r.abortReason})}:{case:"success",value:new fe.QR(o)};return new fe.W4({result:i,sandboxPolicy:hs(n)})}async runProcess({ctx:e,args:t,workingDirectory:r,sandboxPolicy:n,timeoutMs:o}){const s=performance.now(),i=this.defaultCwd,a=(await(0,No.resolveSandboxPolicyForWorkspace)(i,n?{perUser:n}:void 0)).policy,c="insecure_none"!==a.type?{...a,sandboxWorkspaceRoot:i}:a;return await new Promise((n=>{const i=new LT,a=new jT,l=new jT;let u,d,h=!1,p=!1,f="",m=()=>{};const g=(0,No.Qw)((0,No.ue)((0,No.Xw)({...process.env,...NT,CURSOR_AGENT:"1"}))),w={cwd:r,env:g,stdio:["pipe","pipe","pipe"],detached:"win32"!==process.platform,windowsVerbatimArguments:"win32"===process.platform},y="win32"===process.platform?{executable:process.env.ComSpec??"cmd.exe",args:(v=t.command,["/d","/s","/c",`"${v}"`])}:{executable:"/bin/sh",args:["-c",t.command]};var v;const b="insecure_none"===c.type?(0,au.D9)(iu.spawn,y.executable,y.args,w):(0,No.spawnInSandbox)(y.executable,y.args,w,c);b.stdin?.end();const S=e=>{h||(h=!0,clearTimeout(d),m(),n({...e,output:i.getOutput(),outputTruncation:i.getTruncation(),localExecutionTimeMs:Oy(performance.now()-s)}))};d=setTimeout((()=>{if(p=!0,void 0===u&&(f=`An error occurred while executing the command: Command timed out after ${o}ms`,u=fe.Lv.TIMEOUT,m()),void 0!==b.pid&&"win32"!==process.platform)try{return void process.kill(-b.pid,"SIGKILL")}catch{}b.kill("SIGKILL")}),o);const k=()=>{if(void 0===u){if(f="An error occurred while executing the command: Command aborted",u=fe.Lv.USER_ABORT,void 0!==b.pid&&"win32"!==process.platform)try{return void process.kill(-b.pid,"SIGTERM")}catch{}b.kill("SIGTERM")}};e.signal.aborted?k():(e.signal.addEventListener("abort",k,{once:!0}),m=()=>{e.signal.removeEventListener("abort",k)}),b.stdout?.setEncoding("utf8"),b.stdout?.on("data",(e=>{a.append(e),i.append(e)})),b.stderr?.setEncoding("utf8"),b.stderr?.on("data",(e=>{l.append(e),i.append(e)})),b.on("error",(e=>{S({stdout:a.text,stderr:l.text,returncode:-1,signal:"",exceptionInfo:`An error occurred while executing the command: ${e.message}`})})),b.on("close",((e,t)=>{S({stdout:a.text,stderr:l.text,returncode:f.length>0?-1:UT(e,t),signal:t??(p?"SIGKILL":""),exceptionInfo:f,abortReason:u})}))}))}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,D.VI)(e.withName("LocalMiniSweAgentBashExecutor.execute")),!1).ctx;(0,D.HF)(n,"LocalMiniSweAgentBashExecutor.execute");const o=t.command,s=(0,ts.o1)(t.workingDirectory||this.defaultCwd),i=t.timeout>0?t.timeout:3e4;if(!t.parsingResult)return new fe.W4({result:{case:"spawnError",value:new fe.mJ({command:o,workingDirectory:s,error:"Parsing result is required"})}});let a=t.requestedSandboxPolicy?ds(t.requestedSandboxPolicy):void 0;const c=await this.permissionsService.shouldBlockShellCommand(n,o,{workingDirectory:s,timeout:i,parsingResult:t.parsingResult,toolCallId:t.toolCallId},a);if("block"===c.kind)return"permissionsConfig"===c.reason.type&&c.reason.isReadonly?new fe.W4({result:{case:"permissionDenied",value:new fe.jn({command:o,workingDirectory:s,error:"Command blocked by permissions configuration",isReadonly:!0})}}):new fe.W4({result:{case:"rejected",value:new fe.pZ({command:o,workingDirectory:s,reason:td(c.reason)})}});a=c.policy,Ds()&&(a=Us(o,t.parsingResult)),a&&"insecure_none"!==a.type&&(a={...a,ignoreMapping:await this.ignoreService.getCursorIgnoreMapping()});const l=await this.runProcess({ctx:n,args:t,workingDirectory:s,sandboxPolicy:a,timeoutMs:i});return this.buildResult({args:t,workingDirectory:s,processResult:l,sandboxPolicy:a})}catch(e){r.error=e,r.hasError=!0}finally{DT(r)}}}const WT=G("shell-executor",(e=>new H(e,Q("shellArgs"),Y("shellResult"))),((e,t)=>{t.register(new A(e,te("shellArgs"),ee("shellResult")))})),HT=G("mini-swe-agent-bash-executor",(e=>new H(e,Q("miniSweAgentBashArgs"),Y("miniSweAgentBashResult"))),((e,t)=>{t.register(new A(e,te("miniSweAgentBashArgs"),ee("miniSweAgentBashResult")))}));function qT(e){return`${e} changed on disk after this tool call read it. Nothing was written. Read the file again and retry.`}function zT(e){return`${e} changed on disk after you last read or wrote it. Nothing was written. Read the file again and retry.`}(0,b.cF)(Symbol("optionalPendingPodWrite"),!1);const GT=G("write-executor",(e=>new H(e,Q("writeArgs"),Y("writeResult"))),((e,t)=>{t.register(new A(e,te("writeArgs"),ee("writeResult")))})),VT=G("delete-executor",(e=>new H(e,Q("deleteArgs"),Y("deleteResult"))),((e,t)=>{t.register(new A(e,te("deleteArgs"),ee("deleteResult")))})),KT=G("fetch-executor",(e=>new H(e,Q("fetchArgs"),Y("fetchResult"))),((e,t)=>{t.register(new A(e,te("fetchArgs"),ee("fetchResult")))})),JT=G("git-diff-executor",(e=>new H(e,Q("gitDiffRequest"),Y("gitDiffResponse"))),((e,t)=>{t.register(new A(e,te("gitDiffRequest"),ee("gitDiffResponse")))})),ZT=G("grep-executor",(e=>new H(e,Q("grepArgs"),Y("grepResult"))),((e,t)=>{t.register(new A(e,te("grepArgs"),ee("grepResult")))})),XT="[REDACTED]",QT=new TextEncoder;async function YT(e){const t=QT.encode(e),r=await crypto.subtle.digest("SHA-256",t);return{sha256:[...new Uint8Array(r)].map((e=>e.toString(16).padStart(2,"0"))).join(""),bytes:t.byteLength}}class eA{constructor(e){this.inner=e}async execute(e,t,r){if(!0!==t.digestOnly)return this.inner.execute(e,t,r);const n=t.clone();return n.digestOnly=void 0,n.maxChars=void 0,async function(e){if("success"!==e.result.case)return e;const t=e.result.value;if("content"!==t.output.case)return e;const{sha256:r,bytes:n}=await YT(t.output.value),o=t.clone();return o.output={case:void 0},o.outputBlobId=void 0,o.sha256=r,o.sizeBytes=BigInt(n),new Xy.sV({result:{case:"success",value:o}})}(await this.inner.execute(e,n,r))}}const tA=G("read-executor",(e=>new H(e,Q("readArgs"),Y("readResult"))),((e,t)=>{t.register(new A(e,te("readArgs"),ee("readResult")))})),rA=G("redacted-read-executor",(e=>new H(e,Q("redactedReadArgs"),Y("redactedReadResult"))),((e,t)=>{t.register(new A(e,te("redactedReadArgs"),ee("redactedReadResult")))})),nA=G("ls-executor",(e=>new H(e,Q("lsArgs"),Y("lsResult"))),((e,t)=>{t.register(new A(e,te("lsArgs"),ee("lsResult")))})),oA=G("diagnostics-executor",(e=>new H(e,Q("diagnosticsArgs"),Y("diagnosticsResult"))),((e,t)=>{t.register(new A(e,te("diagnosticsArgs"),ee("diagnosticsResult")))})),sA=G("canvas-diagnostics-executor",(e=>new H(e,Q("canvasDiagnosticsArgs"),Y("canvasDiagnosticsResult"))),((e,t)=>{t.register(new A(e,te("canvasDiagnosticsArgs"),ee("canvasDiagnosticsResult")))})),iA="$file:";const aA=(0,h.Pu)("mcp.symbolic_args.expansion",{description:"Outcome of late-binding $file:/abs/path MCP argument expansion at the executor boundary. The call is refused rather than carrying a placeholder to the server when the read reports having replaced a saved secret (`redacted`), or, from a read executor too old to report that, when its text still carries the redaction marker (`redacted_marker`)",labelNames:["route","outcome"]}),cA=(0,h.v5)("mcp.symbolic_args.bytes",{description:"Total bytes substituted into one MCP tool call by $file:/abs/path arguments",labelNames:["route"]}),lA=(0,h.Pu)("mcp.symbolic_args.describe",{description:"Per-file $file:/abs/path describe reads: `vm_digest` when the read executor hashed the file where it lives, `outdated_executor` when it returned the text instead (it predates $file: expansion, so the call is refused)",labelNames:["source"]}),uA=(0,h.v5)("mcp.symbolic_args.paths",{description:"Number of distinct $file:/abs/path arguments expanded in one MCP tool call",labelNames:["route"]});function dA(e,t,r){return{kind:e,message:`Could not resolve the symbolic argument "${iA}${t}": ${r} A string argument of the form "${iA}/absolute/path" is replaced with that file's contents before the tool runs; pass the literal text instead if you did not intend that.`}}const hA={redacted:e=>`${e} contains a saved secret, and a saved secret is never sent through a "${iA}/absolute/path" argument, so this call was not made. Do not retry it, and do not read the file to pass the value yourself. Tell the user that this file holds a saved secret and that they have to enter it in the tool's service themselves.`,redacted_marker:e=>`${e} may contain a saved secret: its text includes the placeholder "${XT}", and the computer that read it is too old to say whether a saved secret stood there, so this call was not made. Do not retry it, and do not read the file to pass the value yourself. Tell the user that this file may hold a saved secret and that they have to enter it in the tool's service themselves.`};function pA(e,t){return{kind:e,message:`Could not resolve the symbolic argument "${iA}${t}": ${hA[e](t)}`}}class fA extends Error{constructor(e){super(e.message),this.failure=e}}let mA;async function gA(e,t,r,n,o,{maxFileBytes:s=8388608,maxTotalBytes:i=16777216,refuseSavedSecrets:a=!1}){if(t.length>4)throw new fA(dA("too_many",t[4]??"",`at most 4 symbolic arguments may be used in one call (${t.length} given). Split the call or pass paths to tools that accept them.`));const c=r();if(void 0===c)throw new fA(dA("no_read_executor",t[0]??"","this environment cannot read files on behalf of a tool call."));const l=await(0,Nr.xb)(t,(t=>async function(e,t,r,n,o){const s=await t.execute(e,new Xy.a2({path:r,toolCallId:n,...o.digestOnly?{digestOnly:!0}:{}}));if("success"!==s.result.case)throw new fA(function(e,t,r){switch(e.result.case){case"fileNotFound":return dA("not_found",t,"the file does not exist.");case"permissionDenied":return dA("permission_denied",t,"reading it was not permitted.");case"rejected":return dA("rejected",t,`${e.result.value.reason||"the read was rejected"}. Only files the Read tool can read without approval can be substituted; read it with Read instead.`);case"invalidFile":return dA("not_text",t,"the file cannot be read as text.");case"error":return r?{kind:"read_error",message:`Could not resolve the symbolic argument "${iA}${t}": ${e.result.value.error}`}:dA("read_error",t,e.result.value.error);default:return dA("read_error",t,"the read returned no result.")}}(s,r,o.refuseSavedSecrets));return await async function(e,t,r,{maxFileBytes:n,digestOnly:o,refuseSavedSecrets:s}){const i=function(e,t,r,n){const o=n&&void 0!==t.sha256&&void 0!==t.sizeBytes?{sha256:t.sha256,bytes:Number(t.sizeBytes)}:void 0;if(void 0===o&&"content"!==t.output.case)throw new fA(dA("not_text",r,"the file is not a text file."));if(n){if(lA.increment(e,1,{source:void 0!==o?"vm_digest":"outdated_executor"}),void 0===o)throw new fA(dA("outdated_executor",r,"the computer that would run this tool has an older tool runner that cannot substitute files. Read the file and pass its contents instead."));return o}}(e,t,r,o),a="content"===t.output.case?t.output.value:void 0,{sha256:c,bytes:l}=i??await YT(a??""),u={content:a,bytes:l,sha256:c};if(t.truncated||l>n)throw new fA(dA("too_large",r,`the file is too large to inline (${Number(t.fileSize)||l} bytes; at most ${n} bytes per file may be substituted). Pass the path to a tool that accepts one, or read a range of it.`));return await async function(e,t,r,n){if(n){if(!0===e.redacted)throw new fA(pA("redacted",r));if(void 0===e.redacted&&await async function(e){return void 0!==e.content?e.content.includes(XT):(await(mA??=Promise.all([XT,`${XT}\n`,`${XT}\r\n`].map((async e=>(await YT(e)).sha256))).then((e=>new Set(e))),mA)).has(e.sha256)}(t))throw new fA(pA("redacted_marker",r))}}(t,u,r,s),u}(e,s.result.value,r,o)}(e,c,t,n,{maxFileBytes:s,digestOnly:o,refuseSavedSecrets:a})),{max:4});let u=0;for(const[e,r]of l)if(u+=r.bytes,u>i)throw new fA(dA("over_budget",e,`together the ${t.length} symbolic arguments exceed the ${i} bytes that may be substituted per call. Pass paths to tools that accept them instead.`));return l}async function wA(e,t,{route:r,getReadExecutor:n,...o}){if(0===t.symbolicPathArguments.length)return{kind:"none"};const s=new Map(t.symbolicPathArguments.map((e=>[e.path,e]))),i=[...s.keys()],a=t=>(aA.increment(e,1,{route:r,outcome:t.kind}),{kind:"failed",failure:t,result:new Mc.iz({result:{case:"error",value:new Mc.Nh({error:t.message})}})});let c;try{c=await gA(e,i,n,t.toolCallId,!1,o)}catch(e){return a(function(e,t){return e instanceof fA?e.failure:dA("read_error",t,e instanceof Error?e.message:String(e))}(e,i[0]??""))}let l=0;for(const[e,t]of c){l+=t.bytes;const r=s.get(e);if(r?.sha256!==t.sha256)return a(dA("content_changed",e,`the file changed after the call was reviewed (${r?.sizeBytes??0} bytes then, ${t.bytes} bytes now), so its new contents were not sent. Re-run the call to review the current contents.`))}const u=new Map([...c].map((([e,t])=>[e,t.content??""]))),d=function(e,t){const r=e=>{const n=function(e){if("string"!=typeof e||!e.startsWith(iA))return;const t=e.slice(6);return(r=t).startsWith("/")||/^[a-zA-Z]:[\\/]/.test(r)||r.startsWith("\\\\")?t:void 0;var r}(e);return void 0!==n?t.get(n)??e:Array.isArray(e)?e.map(r):null!==e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map((([e,t])=>[e,r(t)]))):e};return Object.fromEntries(Object.entries(e).map((([e,t])=>[e,r(t)])))}(Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()]))),u),h=t.clone();return h.args=Object.fromEntries(Object.entries(d).map((([e,t])=>[e,ve.Value.fromJson(t)]))),h.symbolicPathArguments=[],h.argumentsRepaired=!1,aA.increment(e,1,{route:r,outcome:"expanded"}),cA.record(e,l,{route:r}),uA.record(e,i.length,{route:r}),{kind:"expanded",expansion:{args:h,files:[...c].map((([e,t])=>({path:e,bytes:t.bytes}))),paths:i.length,bytes:l}}}const yA=/\b413\b|payload too large|request entity too large|body.*too large|too large.*body|ECONNRESET|EPIPE|socket hang up|max(?:imum)? (?:body|payload|request|content) (?:size|length)/i;function vA(e,t,r,n){return yA.test(t)?(aA.increment(e,1,{route:n,outcome:"server_rejected_body"}),`${t}\n\nThe request carried ${r.bytes} bytes of file contents substituted from ${r.paths} "${iA}/abs/path" argument(s), and the server appears to have rejected the request body as too large. Do not retry the same call: pass a smaller file or a range of it, or use a tool that accepts a path or upload instead.`):t}function bA(e){return e.files.map((e=>`"${iA}${e.path}" was replaced with the contents of ${e.path} (${e.bytes} bytes) before the call.`)).join("\n")}class SA{constructor(e,t,r={}){this.inner=e,this.getReadExecutor=t,this.options=r}isBackendRouted(e){return this.inner.isBackendRouted?.(e)??!1}async execute(e,t,r){if(0===t.symbolicPathArguments.length)return this.inner.execute(e,t,r);const n=await wA(e,t,{route:"local",getReadExecutor:this.getReadExecutor,refuseSavedSecrets:!0===this.options.refuseSavedSecrets&&t.refuseSavedSecrets});if("none"===n.kind)return this.inner.execute(e,t,r);if("failed"===n.kind)return n.result;let o;try{o=await this.inner.execute(e,n.expansion.args,r)}catch(t){throw t instanceof Error&&(t.message=vA(e,t.message,n.expansion,"local")),t}return function(e,t,r){const n=t.clone();return"success"===n.result.case?n.result.value.content.push(new Mc._Z({content:{case:"text",value:new Mc.zN({text:bA(r)})}})):"error"===n.result.case&&(n.result.value.error=vA(e,n.result.value.error,r,"local")),n}(e,o,n.expansion)}}const kA=G("background-shell-executor",(e=>new H(e,Q("backgroundShellSpawnArgs"),Y("backgroundShellSpawnResult"))),((e,t)=>{t.register(new A(e,te("backgroundShellSpawnArgs"),ee("backgroundShellSpawnResult")))})),_A=G("write-background-shell-input-executor",(e=>new H(e,Q("writeShellStdinArgs"),Y("writeShellStdinResult"))),((e,t)=>{t.register(new A(e,te("writeShellStdinArgs"),ee("writeShellStdinResult")))})),CA=G("agent-store-conflict-executor",(e=>new H(e,Q("agentStoreConflictArgs"),Y("agentStoreConflictResult"))),((e,t)=>{t.register(new A(e,te("agentStoreConflictArgs"),ee("agentStoreConflictResult")))})),EA=G("shell-allowlist-precheck-executor",(e=>new H(e,Q("shellAllowlistPrecheckArgs"),Y("shellAllowlistPrecheckResult"))),((e,t)=>{t.register(new A(e,te("shellAllowlistPrecheckArgs"),ee("shellAllowlistPrecheckResult")))})),xA=G("mcp-allowlist-precheck-executor",(e=>new H(e,Q("mcpAllowlistPrecheckArgs"),Y("mcpAllowlistPrecheckResult"))),((e,t)=>{t.register(new A(e,te("mcpAllowlistPrecheckArgs"),ee("mcpAllowlistPrecheckResult")))})),PA=G("web-fetch-allowlist-precheck-executor",(e=>new H(e,Q("webFetchAllowlistPrecheckArgs"),Y("webFetchAllowlistPrecheckResult"))),((e,t)=>{t.register(new A(e,te("webFetchAllowlistPrecheckArgs"),ee("webFetchAllowlistPrecheckResult")))})),RA=G("force-background-shell-executor",(e=>new H(e,Q("forceBackgroundShellArgs"),Y("forceBackgroundShellResult"))),((e,t)=>{t.register(new A(e,te("forceBackgroundShellArgs"),ee("forceBackgroundShellResult")))})),IA=G("computer-use-executor",(e=>new H(e,Q("computerUseArgs"),Y("computerUseResult"))),((e,t)=>{t.register(new A(e,te("computerUseArgs"),ee("computerUseResult")))})),TA=G("computer-use-end-turn-executor",(e=>new H(function(e){return{createExecInstance:(t,r)=>e.createExecInstance(t,(e=>{if(t.signal.aborted)throw new Error("computer-use turn end not sent: its caller stopped waiting");return r(e)}))}}(e),Q("computerUseEndTurnArgs"),Y("computerUseEndTurnResult"))),((e,t)=>{t.register(new A(e,te("computerUseEndTurnArgs"),ee("computerUseEndTurnResult")))})),AA=G("record-screen-executor",(e=>new H(e,Q("recordScreenArgs"),Y("recordScreenResult"))),((e,t)=>{t.register(new A(e,te("recordScreenArgs"),ee("recordScreenResult")))}));var $A=r("../proto/dist/generated/agent/v1/agent_store_conflict_exec_pb.js");function MA(e){if(void 0!==e)return{journalEpoch:e.journalEpoch,seq:Number(e.seq),lastEventId:e.lastEventId}}class DA{constructor(e){this.drainer=e}async execute(e,t){try{void 0!==t.includeQuotaNotices&&this.drainer.setIncludeQuotaNoticesOverride(t.includeQuotaNotices);const e=await this.drainer.drain({cursor:MA(t.cursor),advance:!1!==t.advance});return new $A.Ev({result:{case:"success",value:new $A.iS({events:e.events.map((e=>new $A.RZ({v:e.v,eventId:e.event_id,journalEpoch:e.journal_epoch,seq:BigInt(e.seq),tsMs:BigInt(e.ts_ms),kind:e.kind,storeId:e.store_id,originalRelPath:e.original_rel_path,conflictRelPath:e.conflict_rel_path,originalAbsPath:e.original_abs_path,conflictAbsPath:e.conflict_abs_path,preservedBytes:void 0===e.preserved_bytes?void 0:BigInt(e.preserved_bytes),scopeKind:e.scope_kind,limitBytes:void 0===e.limit_bytes?void 0:BigInt(e.limit_bytes),usageBytes:void 0===e.usage_bytes?void 0:BigInt(e.usage_bytes)}))),nextCursor:(r=e.nextCursor,new $A.LK({journalEpoch:r.journalEpoch,seq:BigInt(r.seq),lastEventId:r.lastEventId})),gap:e.gap})}})}catch(e){return new $A.Ev({result:{case:"error",value:new $A.h6({error:e instanceof Error?e.message:String(e)})}})}var r}}class OA{constructor(e){this.shellStdinWriter=e}async execute(e,t){const r=t.shellId;try{await this.shellStdinWriter(r,t.chars)}catch(e){return new Fo.nt({result:{case:"error",value:new Fo.Gv({error:`Failed to write to shell ${r} stdin: ${e instanceof Error?e.message:"Unknown error"}`})}})}return new Fo.nt({result:{case:"success",value:new Fo.tR({shellId:r,terminalFileLengthBeforeInputWritten:0})}})}}var FA=r("../proto/dist/generated/agent/v1/canvas_diagnostics_exec_pb.js"),NA=r("../proto/dist/generated/agent/v1/diagnostics_exec_pb.js");class LA{constructor(e,t){this.getCanvasDiagnostics=e,this.beginCanvasSave=t}async execute(e,t){let r=()=>{};const n=new Promise((e=>{r=e}));let o;if(void 0===this.beginCanvasSave)o=Promise.resolve(void 0);else try{o=this.beginCanvasSave(t.path,{typecheckOutcome:n}).catch((()=>{}))}catch{o=Promise.resolve(void 0)}try{const e=await this.getCanvasDiagnostics(t.path);return void 0===e?(r("unavailable"),jA(UA(t.path,"diagnostics unavailable"),await o)):(r(e.some((e=>1===e.severity))?"failed":"passed"),jA(new FA.GL({result:{case:"success",value:new FA.uX({path:t.path,diagnostics:e.map(BA)})}}),await o))}catch(e){return r("unavailable"),jA(UA(t.path,e instanceof Error?e.message:String(e)),await o)}}}function jA(e,t){return void 0===t||(e.saveState=t.saveState,e.canvasId=t.canvasId,e.title=t.title,e.saveDetail=t.saveDetail),e}function UA(e,t){return new FA.GL({result:{case:"error",value:new FA.HW({path:e,error:t})}})}function BA(e){return new NA.oQ({severity:WA(e.severity),range:new Fc.Q6({start:new Fc.yX({line:e.range.start.line+1,column:e.range.start.character+1}),end:new Fc.yX({line:e.range.end.line+1,column:e.range.end.character+1})}),message:e.message,source:"ts",code:e.code??""})}function WA(e){switch(e){case 1:return NA.h_.ERROR;case 2:return NA.h_.WARNING;case 3:return NA.h_.INFORMATION;case 4:return NA.h_.HINT;default:return NA.h_.UNSPECIFIED}}class HA{constructor(e){if(e.startsWith("file://")){if(!this.isValidFileUrl(e))throw new Error(`Invalid file URL: ${e}`);this.urlString=e}else{const t=this.resolvePath(e);this.urlString=this.pathToFileUrl(t)}}isValidFileUrl(e){try{return"file:"===new URL(e).protocol}catch{return!1}}resolvePath(e){if(e.includes("\\")&&(e=e.replace(/\\/g,"/")),/^[a-zA-Z]:\//.test(e)||/^\//.test(e))return e;const t=e.split("/"),r=[];for(let e=0;ethis.convertDiagnostic(e)));return new NA.Ek({result:{case:"success",value:new NA.a1({path:t.path,diagnostics:s,totalDiagnostics:s.length})}})}catch(r){return e.canceled?new NA.Ek({result:{case:"error",value:new NA.Ho({path:t.path,error:"Request timed out after 10 seconds"})}}):new NA.Ek({result:{case:"error",value:new NA.Ho({path:t.path,error:r instanceof Error?r.message:String(r)})}})}finally{n()}}catch(e){r.error=e,r.hasError=!0}finally{qA(r)}}convertDiagnostic(e){const t=e.message,r="string"==typeof t?t:t&&"object"==typeof t&&"value"in t&&"string"==typeof t.value?t.value:"";return new NA.oQ({severity:this.convertSeverity(e.severity),range:e.range?new Fc.Q6({start:new Fc.yX({line:e.range.start.line,column:e.range.start.character}),end:new Fc.yX({line:e.range.end.line,column:e.range.end.character})}):void 0,message:r,source:e.source,code:e.code?String(e.code):void 0})}convertSeverity(e){switch(e){case 1:return NA.h_.ERROR;case 2:return NA.h_.WARNING;case 3:return NA.h_.INFORMATION;case 4:return NA.h_.HINT;default:return NA.h_.UNSPECIFIED}}}async function GA(e){const{repoRoot:t,filePaths:r,getContent:n}=e,o=new Map;if(0===r.length)return o;const s=await async function(e,t){const r=new Map;if(0===t.length)return r;try{const{stdout:n}=await ky().run(e,["check-attr","linguist-generated","--stdin"],{input:`${t.join("\n")}\n`});for(const e of n.trim().split("\n")){const t=e.match(/^(.+): linguist-generated: (.+)$/);if(t){const e=t[1],n=t[2];"true"===n||"set"===n?r.set(e,!0):"false"!==n&&"unset"!==n||r.set(e,!1)}}}catch{}return r}(t,r);return await Promise.all(r.map((async e=>{const t=s.get(e);if(!0!==t)if(!1!==t)if(function(e){return new VA(e).isGeneratedByPath()}(e))o.set(e,{isGenerated:!0,source:"path-heuristic"});else{if(n){const t=await n(e);if(void 0!==t&&function(e,t){return new VA(e,(()=>t)).isGeneratedByContent()}(e,t))return void o.set(e,{isGenerated:!0,source:"content-heuristic"})}o.set(e,{isGenerated:!1,source:"none"})}else o.set(e,{isGenerated:!1,source:"gitattributes"});else o.set(e,{isGenerated:!0,source:"gitattributes"})}))),o}class VA{constructor(e,t){this.name=e,this.extname=s.extname(e).toLowerCase(),this.getContent=t}get lines(){if(void 0===this.cachedLines){const e=this.getContent?.();this.cachedLines=e?e.split("\n"):[]}return this.cachedLines}get data(){return this.getContent?.()}isGeneratedByPath(){return this.xcodeFile()||this.intellijFile()||this.cocoapods()||this.carthageBuild()||this.generatedGraphqlRelay()||this.generatedNetDesignerFile()||this.generatedNetSpecflowFeatureFile()||this.composerLock()||this.cargoLock()||this.cargoOrig()||this.denoLock()||this.flakeLock()||this.bazelLock()||this.nodeModules()||this.goVendor()||this.goLock()||this.packageResolved()||this.poetryLock()||this.pdmLock()||this.uvLock()||this.pixiLock()||this.esyLock()||this.npmShrinkwrapOrPackageLock()||this.pnpmLock()||this.bunLock()||this.terraformLock()||this.generatedYarnPlugnplay()||this.godeps()||this.generatedByZephir()||this.htmlcov()||this.gradleWrapper()||this.mavenWrapper()||this.pipenvLock()||this.generatedPascalTlb()||this.generatedSqlxQuery()||this.sourceMapByName()}isGeneratedByContent(){return!!this.getContent&&(this.minifiedFiles()||this.hasSourceMap()||this.sourceMap()||this.compiledCoffeescript()||this.generatedParser()||this.generatedNetDocfile()||this.generatedPostscript()||this.compiledCythonFile()||this.generatedGo()||this.generatedProtocolBufferFromGo()||this.generatedProtocolBuffer()||this.generatedJavascriptProtocolBuffer()||this.generatedTypescriptProtocolBuffer()||this.generatedApacheThrift()||this.generatedJniHeader()||this.vcrCassette()||this.generatedAntlr()||this.generatedModule()||this.generatedUnity3dMeta()||this.generatedRacc()||this.generatedJflex()||this.generatedGrammarkit()||this.generatedRoxygen2()||this.generatedHtml()||this.generatedJison()||this.generatedGrpcCpp()||this.generatedDart()||this.generatedPerlPpportHeader()||this.generatedGamemakerstudio()||this.generatedGimp()||this.generatedVisualstudio6()||this.generatedHaxe()||this.generatedJooq()||this.generatedSorbetRbi()||this.generatedMysqlViewDefinitionFormat())}xcodeFile(){return[".nib",".xcworkspacedata",".xcuserstate"].includes(this.extname)}intellijFile(){return/(?:^|\/)\.idea\//.test(this.name)}cocoapods(){return/(^Pods|\/Pods)\//.test(this.name)}carthageBuild(){return/(^|\/)Carthage\/Build\//.test(this.name)}generatedGraphqlRelay(){return/__generated__\//.test(this.name)}generatedNetDesignerFile(){return/\.designer\.(cs|vb)$/i.test(this.name)}generatedNetSpecflowFeatureFile(){return/\.feature\.cs$/i.test(this.name)}composerLock(){return/composer\.lock/.test(this.name)}cargoLock(){return/Cargo\.lock/.test(this.name)}cargoOrig(){return/Cargo\.toml\.orig/.test(this.name)}denoLock(){return/deno\.lock/.test(this.name)}flakeLock(){return/(^|\/)flake\.lock$/.test(this.name)}bazelLock(){return/(^|\/)MODULE\.bazel\.lock$/.test(this.name)}nodeModules(){return/node_modules\//.test(this.name)}goVendor(){return/vendor\/((?!-)[-0-9A-Za-z]+(?e+t.length),0)/this.lines.length>110}hasSourceMap(){return!!this.maybeMinified()&&this.lines.slice(-2).some((e=>/^\/[*/][#@] source(?:Mapping)?URL|sourceURL=/.test(e)))}sourceMap(){if(".map"!==this.extname)return!1;if(/\.(css|js)\.map$/i.test(this.name))return!0;const e=this.lines[0]||"";return/^{"version":\d+,/.test(e)||/^\/\*\* Begin line maps\. \*\*\/{/.test(e)}compiledCoffeescript(){if(".js"!==this.extname)return!1;const e=this.lines[0]||"";if(/^\/\/ Generated by /.test(e))return!0;if("(function() {"===e&&"}).call(this);"===(this.lines[this.lines.length-2]||"")&&""===(this.lines[this.lines.length-1]||"")){let e=0;for(const t of this.lines)if(/var /.test(t)){const r=t.match(/_fn|_i|_len|_ref|_results/g);e+=1*(r?.length||0);const n=t.match(/__bind|__extends|__hasProp|__indexOf|__slice/g);e+=3*(n?.length||0)}return e>=3}return!1}generatedNetDocfile(){return".xml"===this.extname&&!(this.lines.length<=3)&&(this.lines[1]||"").includes("")&&(this.lines[2]||"").includes("")&&(this.lines[this.lines.length-2]||"").includes("")}generatedParser(){if(".js"!==this.extname)return!1;const e=this.lines.slice(0,5).join("");return/^(?:[^/]|\/[^*])*\/\*(?:[^*]|\*[^/])*Generated by PEG\.js/.test(e)}generatedPostscript(){if(![".ps",".eps",".pfa"].includes(this.extname))return!1;const e=this.data;if(!e)return!1;if(/^\s*(?:currentfile eexec\s+|\/sfnts\s+\[\s<)/.test(e))return!0;const t=this.lines.slice(0,10).find((e=>/^%%Creator: /.test(e)));return!!t&&(!(!/[0-9]|draw|mpage|ImageMagick|inkscape|MATLAB/.test(t)&&!/PCBNEW|pnmtops|\(Unknown\)|Serif Affinity|Filterimage -tops/.test(t))||!!t.includes("EAGLE")&&this.lines.slice(0,5).some((e=>/^%%Title: EAGLE Drawing /.test(e))))}generatedGo(){return".go"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,40).some((e=>/^\/\/ Code generated .*/.test(e)))}generatedProtocolBufferFromGo(){return".proto"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,20).some((e=>e.includes("This file was autogenerated by go-to-protobuf")))}generatedProtocolBuffer(){return!![".py",".java",".h",".cc",".cpp",".m",".rb",".php"].includes(this.extname)&&!(this.lines.length<=1)&&this.lines.slice(0,3).some((e=>e.includes("Generated by the protocol buffer compiler. DO NOT EDIT!")))}generatedJavascriptProtocolBuffer(){return".js"===this.extname&&!(this.lines.length<=6)&&(this.lines[5]||"").includes("GENERATED CODE -- DO NOT EDIT!")}generatedTypescriptProtocolBuffer(){return".ts"===this.extname&&!(this.lines.length<=4)&&(this.lines[0]||"").includes("Code generated by protoc-gen-ts_proto. DO NOT EDIT.")}generatedApacheThrift(){return!![".rb",".py",".go",".js",".m",".java",".h",".cc",".cpp",".php"].includes(this.extname)&&this.lines.slice(0,6).some((e=>e.includes("Autogenerated by Thrift Compiler")))}generatedJniHeader(){return".h"===this.extname&&!(this.lines.length<=2)&&(this.lines[0]||"").includes("/* DO NOT EDIT THIS FILE - it is machine generated */")&&(this.lines[1]||"").includes("#include ")}vcrCassette(){return".yml"===this.extname&&!(this.lines.length<=2)&&(this.lines[this.lines.length-2]||"").includes("recorded_with: VCR")}generatedAntlr(){return".g"===this.extname&&!(this.lines.length<=2)&&(this.lines[1]||"").includes("generated by Xtest")}compiledCythonFile(){return!![".c",".cpp"].includes(this.extname)&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("Generated by Cython")}generatedModule(){if(".mod"!==this.extname)return!1;if(this.lines.length<=1)return!1;const e=this.lines[0]||"";return e.includes("PCBNEW-LibModule-V")||e.includes("GFORTRAN module version '")}generatedUnity3dMeta(){return".meta"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("fileFormatVersion: ")}generatedRacc(){return".rb"===this.extname&&!(this.lines.length<=2)&&(this.lines[2]||"").startsWith("# This file is automatically generated by Racc")}generatedJflex(){return".java"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("/* The following code was generated by JFlex ")}generatedGrammarkit(){return".java"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("// This is a generated file. Not intended for manual editing.")}generatedRoxygen2(){return".rd"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("% Generated by roxygen2: do not edit by hand")}generatedHtml(){if(![".html",".htm",".xhtml"].includes(this.extname))return!1;if(this.lines.length<=1)return!1;if(this.lines.slice(0,2).some((e=>//.test(e))))return!0;if(this.lines.length>2&&(this.lines[2]||"").startsWith("\x3c!-- This is an automatically generated file."))return!0;if(this.lines.slice(0,31).some((e=>//i.test(e))))return!0;const e=this.lines.slice(0,31).join(" ").match(/]+)>/gi);if(!e)return!1;for(const t of e){const e=this.extractHtmlMeta(t);if("generator"===e.name?.toLowerCase()&&(e.content||e.value)){const t=e.content||e.value||"";if(/^(org\s+mode|j?latex2html|groff|makeinfo|texi2html|ronn)\b/i.test(t))return!0}}return!1}extractHtmlMeta(e){const t={},r=e.matchAll(/(?<=^|\s)(name|content|value)\s*=\s*("[^"]+"|'[^']+'|[^\s"']+)/gi);for(const e of r){const r=e[1].toLowerCase();let n=e[2];(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'"))&&(n=n.slice(1,-1)),t[r]=n}return t}generatedJison(){if(".js"!==this.extname)return!1;if(this.lines.length<=1)return!1;const e=this.lines[0]||"";return e.startsWith("/* parser generated by jison ")||e.startsWith("/* generated by jison-lex ")}generatedGrpcCpp(){return!![".cpp",".hpp",".h",".cc"].includes(this.extname)&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("// Generated by the gRPC")}generatedDart(){return".dart"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,3).some((e=>/generated code\W{2,3}do not modify/i.test(e)))}generatedPerlPpportHeader(){return!!/ppport\.h$/.test(this.name)&&!(this.lines.length<=10)&&(this.lines[8]||"").includes("Automatically created by Devel::PPPort")}generatedGamemakerstudio(){if(![".yy",".yyp"].includes(this.extname))return!1;if(this.lines.length<=3)return!1;const e=this.lines.slice(0,3).join("");return/^\s*[{[]/.test(e)||/^\d\.\d\.\d.+\|\{/.test(this.lines[0]||"")}generatedGimp(){if(![".c",".h"].includes(this.extname))return!1;if(0===this.lines.length)return!1;const e=this.lines[0]||"";return/^\/\* GIMP [a-zA-Z0-9- ]+ C-Source image dump \(.+?\.c\) \*\//.test(e)||/^\/\* {2}GIMP header image file format \([a-zA-Z0-9- ]+\): .+?\.h {2}\*\//.test(e)}generatedVisualstudio6(){return".dsp"===this.extname&&this.lines.slice(0,3).some((e=>e.includes("# Microsoft Developer Studio Generated Build File")))}generatedHaxe(){return!![".js",".py",".lua",".cpp",".h",".java",".cs",".php"].includes(this.extname)&&this.lines.slice(0,3).some((e=>e.includes("Generated by Haxe")))}generatedJooq(){return".java"===this.extname&&this.lines.slice(0,2).some((e=>e.includes("This file is generated by jOOQ.")))}generatedSorbetRbi(){return".rbi"===this.extname&&!(this.lines.length<5)&&/^# typed:/.test(this.lines[0]||"")&&(this.lines[2]||"").includes("DO NOT EDIT MANUALLY")&&/^# Please (run|instead update this file by running) `bin\/tapioca/.test(this.lines[4]||"")}generatedMysqlViewDefinitionFormat(){return".frm"===this.extname&&(this.lines[0]||"").includes("TYPE=VIEW")}}const KA=e=>{if(!e)return[];if("string"!=typeof e||e.match(/^\s+$/))return[];const t=e.split("\n");if(0===t.length)return[];const r=[];let n=null,o=null,s=0,i=0,a=null;const c=e=>{o?.changes.push({type:"normal",normal:!0,ln1:s++,ln2:i++,content:e}),a.oldLines--,a.newLines--},l=e=>{const[t,o]=XA(e)??[];n={chunks:[],deletions:0,additions:0,from:t,to:o},r.push(n)},u=()=>{n&&!n.chunks.length||l()},d=e=>+(e||1),h=e=>{o&&(o.changes.push({type:"del",del:!0,ln:s++,content:e}),n.deletions++,a.oldLines--)},p=e=>{o&&(o.changes.push({type:"add",add:!0,ln:i++,content:e}),n.additions++,a.newLines--)},f=e=>{if(!o)return;const[t]=o.changes.slice(-1);o.changes.push({type:t.type,[t.type]:!0,ln1:t.ln1,ln2:t.ln2,ln:t.ln,content:e})},m=[[/^diff\s/,l],[/^new file mode (\d+)$/,(e,t)=>{u(),n.new=!0,n.newMode=t[1],n.from="/dev/null"}],[/^deleted file mode (\d+)$/,(e,t)=>{u(),n.deleted=!0,n.oldMode=t[1],n.to="/dev/null"}],[/^old mode (\d+)$/,(e,t)=>{u(),n.oldMode=t[1]}],[/^new mode (\d+)$/,(e,t)=>{u(),n.newMode=t[1]}],[/^index\s[\da-zA-Z]+\.\.[\da-zA-Z]+(\s(\d+))?$/,(e,t)=>{u(),n.index=e.split(" ").slice(1),t[1]&&(n.oldMode=n.newMode=t[1].trim())}],[/^---\s/,e=>{u(),n.from=YA(e)}],[/^\+\+\+\s/,e=>{u(),n.to=YA(e)}],[/^@@\s+-(\d+),?(\d+)?\s+\+(\d+),?(\d+)?\s@@/,(e,t)=>{n||l(e);const[r,c,u,h]=t.slice(1);s=+r,i=+u,o={content:e,changes:[],oldStart:+r,oldLines:d(c),newStart:+u,newLines:d(h)},a={oldLines:d(c),newLines:d(h)},n.chunks.push(o)}],[/^\\ No newline at end of file$/,f]],g=[[/^\\ No newline at end of file$/,f],[/^-/,h],[/^\+/,p],[/^\s+/,c]],w=e=>{a?(e=>{const t=e.charCodeAt(0);if(43===t)p(e);else if(45===t)h(e);else if(32===t)c(e);else if(92===t&&/^\\ No newline at end of file$/.test(e))f(e);else for(const[t,r]of g){const n=e.match(t);if(n){r(e,n);break}}0===a.oldLines&&0===a.newLines&&(a=null)})(e):(e=>{for(const[t,r]of m){const n=e.match(t);if(n){r(e,n);break}}})(e)};for(const e of t)w(e);return r},JA=/(a|i|w|c|o|1|2)\/.*(?=["']? ["']?(b|i|w|c|o|1|2)\/)|(b|i|w|c|o|1|2)\/.*$/g,ZA=/^(a|b|i|w|c|o|1|2)\//,XA=e=>{const t=e?.match(JA);return t?.map((e=>e.replace(ZA,"").replace(/("|')$/,"")))},QA=/^\\?['"]|\\?['"]$/g,YA=e=>{let t=e$(e,"-+").trim();return t=r$(t),t.replace(QA,"").replace(ZA,"")},e$=(e,t)=>{if(e=o$(e),!t&&String.prototype.trimLeft)return e.trimLeft();const r=n$(t);return e.replace(new RegExp(`^${r}+`),"")},t$=/\t.*|\d{4}-\d\d-\d\d\s\d\d:\d\d:\d\d(.\d+)?\s(\+|-)\d\d\d\d/,r$=e=>{const t=t$.exec(e);return t&&(e=e.substring(0,t.index).trim()),e},n$=e=>null==e?"\\s":e instanceof RegExp?e.source:`[${o$(e).replace(/([.*+?^=!:${}()|[\]/\\])/g,"\\$1")}]`,o$=e=>`${e??""}`,s$=(0,d.h)("local-mercurial-diff"),i$=5242880,a$="0000000000000000000000000000000000000000";let c$,l$;async function u$(e,t,r={}){const n=await async function(){if(void 0===c$&&(c$=await async function(e){const t="win32"===process.platform?["hg.com","hg.exe"]:["hg"];for(const r of e.split(s.delimiter))if(s.isAbsolute(r))for(const e of t){const t=s.join(r,e);try{if(!(await xo.stat(t)).isFile())continue;return"win32"!==process.platform&&await xo.access(t,Ro.constants.X_OK),t}catch{}}}(process.env.PATH??"")??null),null===c$){const e=new Error("hg executable not found");throw e.code="ENOENT",e}return c$}(),o=await new Promise(((o,s)=>{const i=(0,iu.spawn)(n,t,{cwd:e,env:{...process.env,HGPLAIN:"+strictflags",HGRCPATH:"",HGRCSKIPREPO:"1"},shell:!1}),a=new ca.StringDecoder("utf8");let c="";i.stdout.on("data",(e=>{c+=a.write(e)})),i.stderr.on("data",(()=>{})),i.on("error",(e=>{!0===r.allowFailure?o(""):s(e)})),i.on("close",(e=>{if(0===e||!0===r.allowFailure)o(c+a.end());else{const r=t.find((e=>!e.startsWith("-")))??"hg";s(new Error(`MercurialDiffFailed: hg ${r} exited ${e??"unknown"}`))}}))}));return o}async function d$(e){const t=await async function(e){let t=s.resolve(e);for(;;){try{if((await xo.stat(s.join(t,".hg"))).isDirectory())return!0}catch{}const e=s.dirname(t);if(e===t)return!1;t=e}}(e);if(!t)return;const r=function(e,t){return e&&"absent"!==t?"skips-repo-config"!==t?"unsafe":"proceed":"not-mercurial"}(t,await async function(){if(void 0!==l$)return l$;const e=await xo.mkdtemp(s.join((0,o.tmpdir)(),"hg-probe-"));try{const t=await u$(e,["help","environment"]);l$=/\bHGRCSKIPREPO\b/.test(t)?"skips-repo-config":"reads-repo-config"}catch(e){l$=function(e){return"object"==typeof e&&null!==e&&"code"in e&&"ENOENT"===e.code}(e)?"absent":"reads-repo-config"}finally{await xo.rm(e,{recursive:!0,force:!0})}return l$}());if("not-mercurial"===r)return;if("unsafe"===r)throw new Error("MercurialClientUnsafe: hg would read repository config");let n;try{n=(await u$(e,["root"])).trim()}catch{return}if(0!==n.length)try{return(await xo.stat(s.join(n,".hg"))).isDirectory()?n:void 0}catch{return}}function h$(e,t){return"win32"===process.platform?s.win32.normalize(e).toLowerCase()===s.win32.normalize(t).toLowerCase():s.resolve(e)===s.resolve(t)}function p$(e,t){const r=s.relative(s.resolve(t),s.resolve(e));return 0===r.length||!s.isAbsolute(r)&&!r.split(s.sep).includes("..")}async function f$(e){const t=s.resolve(e);try{return await xo.realpath(t)}catch{return t}}function m$(e){if(0===e.length)return[];const t=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),r=t.split("\n");return t.endsWith("\n")&&r.pop(),r}function g$(e){if(e.includes("\0")||/[\r\n]/.test(e))throw new Error("MercurialDiffFailed: base ref contains a newline")}async function w$({repositoryRoot:e,rev:t,filePath:r}){const n=await async function({repositoryRoot:e,rev:t,filePath:r}){let n;try{n=await u$(e,["files","-r",t,"-T","{size}","--",r])}catch{return}const o=n.trim();if(!/^\d+$/.test(o))return;const s=Number(o);return Number.isFinite(s)?s:void 0}({repositoryRoot:e,rev:t,filePath:r});return void 0===n||n>i$?"":u$(e,["cat","-r",t,"--",r])}async function y$(e,t,r){const n=function(e){switch(e){case Ue.ek.NAME_STATUS:return Ue.ek.NAME_STATUS;case Ue.ek.NAME_STATUS_AND_NUMSTAT:return Ue.ek.NAME_STATUS_AND_NUMSTAT;case Ue.ek.FILE_DIFFS:return Ue.ek.FILE_DIFFS;case Ue.ek.DIFFS_WITH_BEFORE_AND_AFTER:return Ue.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return Ue.ek.FILE_DIFFS}}(r.outputFormat),o=["root"],i=(await u$(t,["root"])).trim();if(0===i.length)throw new Error("MercurialDiffFailed: hg root did not resolve");let a,c;if(0!==r.ref.length||"HEAD"!==r.baseRef&&(r.mergeBase||0!==r.baseRef.length)){if(r.mergeBase||0===r.baseRef.length)a=await async function({cwd:e,baseRef:t,commands:r}){if(t.length>0&&"HEAD"!==t){g$(t),r.push("log");const n=(await u$(e,["log","-r",`ancestor(., (${t}))`,"-T","{node}"])).trim();if(0===n.length||n===a$)throw new Error("MercurialDiffFailed: base ref did not resolve");return n}r.push("log");const n=(await u$(e,["log","-r","max(::. and public())","-T","{node}"],{allowFailure:!0})).trim();if(n.length>0&&n!==a$)return n;const o=(await u$(e,["log","-r","ancestor(., default)","-T","{node}"],{allowFailure:!0})).trim();if(o.length>0&&o!==a$)return o;const s=(await u$(e,["log","-r",".","-T","{node}"],{allowFailure:!0})).trim();return s.length>0?s:a$}({cwd:t,baseRef:r.baseRef,commands:o});else if(g$(r.baseRef),o.push("log"),a=(await u$(t,["log","-r",r.baseRef,"-T","{node}"])).trim(),0===a.length)throw new Error("MercurialDiffFailed: base ref did not resolve");r.ref.length>0&&(g$(r.ref),o.push("log"),c=(await u$(t,["log","-r",r.ref,"-T","{node}"])).trim())}const l=["diff","--git"];r.includeSpaceChanges||l.push("-b"),void 0!==r.unifiedContextLines&&l.push(`-U${r.unifiedContextLines}`),void 0!==a&&l.push("-r",a),void 0!==c&&l.push("-r",c),r.targetPaths.length>0&&l.push("--",...r.targetPaths),o.push("diff");const u=await u$(t,l),d=function(e){const t=e.replace(/\r\n/g,"\n");return new Ue.o$({diffs:KA(t).map((e=>function(e){const t=new Ue.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new Ue.Ei({content:e.content,lines:e.changes.map((e=>e.content)),oldStart:e.oldStart,oldLines:e.oldLines,newStart:e.newStart,newLines:e.newLines})))});return t.added=e.additions,t.removed=e.deletions,t}(e))),diffType:Ue.Wf.UNSPECIFIED})}(u);let h=[];if(r.maxUntrackedFiles>0&&(o.push("status"),h=await async function({cwd:e,repositoryRoot:t,maxUnknownFiles:r}){let n=(await u$(e,["status","-un0"])).split("\0").filter((e=>e.length>0));return n.length>r&&(n=n.slice(0,r)),(await Promise.all(n.map((async e=>{try{const r=s.join(t,e),n=await xo.stat(r);if(n.size>i$){const t=await async function(e){const t=(0,ko.createHash)("sha256"),r=await xo.open(e,"r");try{const e=Buffer.alloc(65536);let n=0;for(;;){const{bytesRead:o}=await r.read(e,0,e.length,n);if(0===o)break;t.update(e.subarray(0,o)),n+=o}}finally{await r.close()}return t.digest("hex")}(r);return{contents:"",path:e,omittedDueToSize:!0,byteSize:n.size,contentHash:t}}return{contents:await xo.readFile(r,"utf8"),path:e}}catch{return}})))).filter((e=>void 0!==e))}({cwd:t,repositoryRoot:i,maxUnknownFiles:r.maxUntrackedFiles}),d.diffs.push(...h.map((e=>function(e){if(!0===e.omittedDueToSize)return new Ue.QP({from:"/dev/null",to:e.path,chunks:[],added:0,removed:0});const t=m$(e.contents);if(0===t.length)return new Ue.QP({from:"/dev/null",to:e.path,chunks:[],added:0,removed:0});const r=t.length;return new Ue.QP({from:"/dev/null",to:e.path,chunks:[new Ue.Ei({content:`@@ -0,0 +1${1===r?"":`,${r}`} @@`,lines:t.map((e=>`+${e}`)),oldStart:0,oldLines:0,newStart:1,newLines:r})],added:r,removed:0})}(e))))),n!==Ue.ek.FILE_DIFFS)for(const e of d.diffs)e.chunks=[];if(n===Ue.ek.DIFFS_WITH_BEFORE_AND_AFTER){const e=a??".";await Promise.all(d.diffs.map((async t=>{if("/dev/null"!==t.from)try{t.beforeFileContents=await w$({repositoryRoot:i,rev:e,filePath:t.from})}catch{t.beforeFileContents=""}else t.beforeFileContents="";if("/dev/null"!==t.to)if(void 0===c)try{const e=s.join(i,t.to),r=await xo.stat(e);t.afterFileContents=r.size>i$?"":await xo.readFile(e,"utf8")}catch{t.afterFileContents=""}else try{t.afterFileContents=await w$({repositoryRoot:i,rev:c,filePath:t.to})}catch{t.afterFileContents=""}else t.afterFileContents=""})))}const p=[u,function(e){const t=[];for(const r of e){const e=m$(r.contents);if(t.push(`diff --git a/${r.path} b/${r.path}`),t.push("new file mode 100644"),t.push("--- /dev/null"),t.push(`+++ b/${r.path}`),0===e.length)continue;const n=e.length;t.push(`@@ -0,0 +1${1===n?"":`,${n}`} @@`),t.push(...e.map((e=>`+${e}`)))}return t.join("\n")}(h.filter((e=>!0!==e.omittedDueToSize))),h.filter((e=>!0===e.omittedDueToSize)).map((e=>`omitted-untracked ${e.byteSize??0} ${e.contentHash??""} ${JSON.stringify(e.path)}`)).join("\n")].filter((e=>e.length>0)).join("\n"),f=r.computePatchId?function(e){if(0!==e.length)return`hg:${(0,ko.createHash)("sha256").update(e).digest("hex")}`}(p.length>0?`${p}\n`:""):void 0;let m,g;if(!0===r.returnHeadSha){o.push("log","status");const e=(await u$(t,["log","-r",".","-T","{node}"],{allowFailure:!0})).trim();m=e.length>0?e:a$,g=(await u$(t,["status","-0"])).length>0}s$.info(e,"Local mercurial diff commands",{sourceControl:"mercurial",commands:o});const w=new Ue.df({diff:d,submoduleDiffs:[],patchId:f,headSha:m,hasUncommittedChanges:g}),y=r.maxResponseBytes??0;if(y>0){const t=w.toBinary().byteLength;if(t>y)throw s$.info(e,"Local diff outcome",{sourceControl:"mercurial",outcome:"too_large"}),new Error(`GetDiffResponseTooLarge: ${t} bytes exceeds the ${y} byte limit`)}return s$.info(e,"Local diff outcome",{sourceControl:"mercurial",outcome:"ok",fileCount:d.diffs.length,patchIdPrefixed:!0===f?.startsWith("hg:")}),w}const v$=(0,d.h)("local-git-diff");function b$({exitCode:e,stderr:t}){return new Error(`Git command failed with code ${e}: ${t}`)}async function S$(e,t,r={}){let n;try{n=await e(t)}catch(e){if(!0===r.ignoreErrors)return"";throw e}if(0!==n.exitCode&&!0!==r.ignoreErrors)throw b$(n);return!0===r.shouldNotTrimOutput?n.stdout:n.stdout.trim()}function k$(e){const t=KA(e);return new Ue.o$({diffs:t.map((e=>function(e){const t=new Ue.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new Ue.Ei({content:e.content,lines:e.changes.map((e=>e.content)),oldStart:e.oldStart,oldLines:e.oldLines,newStart:e.newStart,newLines:e.newLines})))});return t.added=e.additions,t.removed=e.deletions,t}(e))),diffType:Ue.Wf.UNSPECIFIED})}function _$(e){const t=[];for(const n of e){const e={body:`+${(r=n.contents).replaceAll("\n","\n+")}`,numLines:Xs(r)},o=1===e.numLines?"@@ -0,0 +1 @@":`@@ -0,0 +1,${e.numLines} @@`;t.push(`diff --git a/${n.path} b/${n.path}\n--- /dev/null\n+++ b/${n.path}\n${o}\n${e.body}`)}var r;return t.join("\n")}const C$=["main","master","develop"];async function E$(e,t){const r=s.join(e,t),n=await xo.lstat(r);if(n.isSymbolicLink())return{contents:await xo.readlink(r),path:t,isSymlink:!0};if(!n.isFile())throw new Error("Not a regular file or symlink");return{contents:await xo.readFile(r,"utf8"),path:t,isSymlink:!1}}async function x$(e,t,r){const n=ky(),o=(e,r)=>n.run(t,e,r),i=await async function(e,t){let r;try{const e=(await S$(t,["rev-parse","--show-toplevel"])).trim();e.length>0&&(r=e)}catch{}if(void 0!==r){const t=await async function({cwd:e,gitRoot:t}){const r=await f$(t);let n=await f$(e);if(h$(n,r))return;let o=!1;for(;p$(n,r)&&!h$(n,r);){try{if((await xo.stat(s.join(n,".hg"))).isDirectory()){o=!0;break}}catch{}const e=s.dirname(n);if(e===n)break;n=e}return o?d$(e):void 0}({cwd:e,gitRoot:r});return void 0!==t?"mercurial":"git"}return void 0===await d$(e)?"none":"mercurial"}(t,o);if(v$.info(e,"Local diff source control",{sourceControl:i}),"none"===i)throw v$.info(e,"Local diff outcome",{sourceControl:i,outcome:"no_version_control"}),new Error("NoVersionControl: no git or mercurial repository");if("mercurial"===i)return y$(e,t,r);const a=function(e){switch(e){case Ue.ek.NAME_STATUS:return Ue.ek.NAME_STATUS;case Ue.ek.NAME_STATUS_AND_NUMSTAT:return Ue.ek.NAME_STATUS_AND_NUMSTAT;case Ue.ek.FILE_DIFFS:return Ue.ek.FILE_DIFFS;case Ue.ek.DIFFS_WITH_BEFORE_AND_AFTER:return Ue.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return Ue.ek.FILE_DIFFS}}(r.outputFormat),c=await(async()=>{let e=r.baseRef.length>0?r.baseRef:await async function(e){try{const t=await S$(e,["symbolic-ref","--short","refs/remotes/origin/HEAD"]);if(t)return t.trim()}catch{}for(const t of C$){const r=`origin/${t}`;try{return await S$(e,["rev-parse","--verify",r]),r}catch{}}try{const t=(await S$(e,["branch","-r"])).split("\n").map((e=>e.trim())).find((e=>e.startsWith("origin/")));if(t)return t}catch{}try{const t=await S$(e,["config","--get","init.defaultBranch"]);if(t)return t.trim()}catch{}throw new Error("Could not determine default branch")}(o);if(r.mergeBase){const t=r.ref.length>0?r.ref:"HEAD";e=(await S$(o,["merge-base","--end-of-options",e,t])).trim()}return e})(),l=["diff","--no-color"];r.includeSpaceChanges||l.push("--ignore-space-change"),void 0!==r.unifiedContextLines&&l.push(`-U${r.unifiedContextLines}`);const u=["--end-of-options",c];r.ref.length>0&&u.push(r.ref),r.targetPaths.length>0&&u.push("--",...r.targetPaths);const d=await o([...l,...u]);let h,p;if(0===d.exitCode)h=d.stdout,p=k$(h);else{const t=b$(d);if(r.computePatchId||!await async function(e){return(await S$(e,["config","--get-regexp","^(extensions\\.partialclone|remote\\..+\\.promisor)$"],{ignoreErrors:!0})).split("\n").some((e=>/^(extensions\.partialclone \S|remote\..+\.promisor( (true|yes|on|1))?$)/i.test(e)))}(o))throw t;p=await async function(e,t){const r=(await S$(e,["diff","--name-status","--no-renames","-z",...t])).split("\0"),n=[];for(let e=1;e{throw t})),v$.info(e,"Local diff outcome",{sourceControl:i,outcome:"partial_clone_names_only"})}let f=[];if(r.maxUntrackedFiles>0){f=await async function(e,t,r){let n=(await S$(t,["ls-files","--others","--exclude-standard"])).split("\n").map((e=>e.trim())).filter((e=>e.length>0));return n.length>r&&(n=n.slice(0,r)),(await Promise.all(n.map((async t=>{try{return await E$(e,t)}catch{return}})))).filter((e=>void 0!==e))}(t,o,r.maxUntrackedFiles);for(const e of f){const t=e.isSymlink?`${_$([e])}\n\\ No newline at end of file`:await S$(o,["diff","--no-color","--no-index","--","/dev/null",e.path],{ignoreErrors:!0,shouldNotTrimOutput:!0});p.diffs.push(...k$(t).diffs)}}if(a!==Ue.ek.FILE_DIFFS||!0===p.fileContentsOmitted)for(const e of p.diffs)e.chunks=[];if(a===Ue.ek.DIFFS_WITH_BEFORE_AND_AFTER&&!0!==p.fileContentsOmitted){const n=r.ref.length>0?r.ref:"HEAD";await Promise.all(p.diffs.map((async s=>{try{if("/dev/null"!==s.from)try{s.beforeFileContents=await S$(o,["show","--end-of-options",`${c}:${s.from}`],{shouldNotTrimOutput:!0})}catch{s.beforeFileContents=""}else s.beforeFileContents="";if("/dev/null"!==s.to)if(r.ref.length>0)try{s.afterFileContents=await S$(o,["show","--end-of-options",`${n}:${s.to}`],{shouldNotTrimOutput:!0})}catch{s.afterFileContents=""}else try{s.afterFileContents=(await E$(t,s.to)).contents}catch{try{s.afterFileContents=await S$(o,["show","--end-of-options",`${n}:${s.to}`],{shouldNotTrimOutput:!0})}catch{s.afterFileContents=""}}else s.afterFileContents=""}catch(t){v$.error(e,"Error fetching file contents for diff",t)}})))}const m=new Map;for(const e of p.diffs){const t="/dev/null"!==e.to?e.to:e.from;t&&m.set(t,e)}const g=[...m.keys()],w=r.ref.length>0?r.ref:"HEAD";try{const e=await GA({repoRoot:t,filePaths:g,getContent:async e=>{const t=m.get(e);if(t){if(void 0!==t.afterFileContents)return t.afterFileContents;try{if(t.to&&"/dev/null"!==t.to)return await S$(o,["show","--end-of-options",`${w}:${t.to}`],{shouldNotTrimOutput:!0})}catch{}}}});for(const[t,r]of e){const e=m.get(t);e&&(e.isGenerated=r.isGenerated)}}catch(t){v$.warn(e,"Generated-file detection failed; continuing without it",{error:t instanceof Error?t.message:String(t)})}const y=r.computePatchId&&void 0!==h?await async function(e,t){if(0===t.length)return;const{exitCode:r,stdout:n,stderr:o}=await e(["patch-id","--stable"],{input:t});if(0!==r)throw new Error(`git patch-id failed with code ${r}: ${o}`);return n.trim().split(/\s+/)[0]||void 0}(o,function(...e){const t=e.filter((e=>e.length>0));return 0===t.length?"":`${t.join("\n")}\n`}(h,_$(f))):void 0,v=!0===r.returnHeadSha?(await S$(o,["rev-parse","HEAD"])).trim():void 0,b=!0===r.returnHeadSha?(await S$(o,["status","--porcelain=v1","--untracked-files=all"])).trim().length>0:void 0,S=new Ue.df({diff:p,submoduleDiffs:[],patchId:y,headSha:v,hasUncommittedChanges:b}),k=r.maxResponseBytes??0;if(k>0){const e=S.toBinary().byteLength;if(e>k)throw new Error(`GetDiffResponseTooLarge: ${e} bytes exceeds the ${k} byte limit`)}return S}class P${async execute(e,t){return x$(e,t.cwd,t)}}var R$=r("../proto/dist/generated/agent/v1/mcp_allowlist_precheck_exec_pb.js");class I${constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isMcpFullyAllowlisted(e,{providerIdentifier:t.providerIdentifier,toolName:t.toolName,annotationsJson:t.annotationsJson});return new R$.M({allowlisted:r})}}var T$=r("../proto/dist/generated/agent/v1/record_screen_exec_pb.js"),A$=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function $$(e){return null!==e.exitCode||null!==e.signalCode||e.killed}function M$(e,t){return"object"==typeof e&&null!==e&&"code"in e&&e.code===t}function D$(e){return e instanceof Error?e.message:String(e)}function O$(e,t){return new T$.Tj({result:{case:"failure",value:new T$.yH({error:t,kind:e})}})}function F$(e){return e instanceof Error?e.message.startsWith("Failed to load polished-renderer native binding")?"binding_load_failed":"code"in e&&"string"==typeof e.code?e.code:e.name:typeof e}function N$(e,t,r,n){const o=[],s=function(e,t){const r=e.ffmpegExitCode??e.childProcess.exitCode,n=e.ffmpegExitSignal??e.childProcess.signalCode;if(e.ffmpegDiedEarly||null!==e.ffmpegDiedTime||null!==r||null!==n)return`ffmpeg exited code=${r} signal=${n}${null!==e.ffmpegDiedTime?` ${Math.max(0,Math.round((t-e.ffmpegDiedTime)/1e3))}s before SAVE`:""}`}(t,n);return void 0!==s&&o.push(s),void 0!==r&&o.push(`stop failed: ${D$(r)}`),o.length>0?`${e} (${o.join("; ")})`:e}const L$=(0,Vs.promisify)(iu.execFile);class j${constructor(e){if(this.activeRecording=null,this.inFlightSaves=[],this.onRecordingStartedCallback=null,this.onRecordingStoppedCallback=null,this.recordingStoppedCallbackInvoked=!1,this.artifactsDir=e.artifactsDir,this.stagingDir=e.stagingDir??"/opt/cursor/recording-staging/",this.display=e.display,this.disablePolishedRendering=e.disablePolishedRendering??!1,this.polishedRenderer=e.polishedRenderer,!this.disablePolishedRendering){if(!this.polishedRenderer)throw new Error("record_screen requires a polished recording renderer when polished rendering is enabled. This tool should run via exec-daemon where that dependency is bundled.");this.polishedRenderer.assertAvailable()}}setOnRecordingStarted(e){this.onRecordingStartedCallback=e}setOnRecordingStopped(e){this.onRecordingStoppedCallback=e}invokeStoppedCallbackOnce(){!this.recordingStoppedCallbackInvoked&&this.onRecordingStoppedCallback&&(this.recordingStoppedCallbackInvoked=!0,this.onRecordingStoppedCallback())}async cleanupRecording(e){try{await(e.inputEventLogger?.stop())}catch{}if(!$$(e.childProcess)&&e.childProcess.pid)try{await this.stopFfmpegRecording(e)}catch{try{process.kill(e.childProcess.pid,"SIGKILL")}catch{}}}getActiveInputEventLogger(){return this.activeRecording?.inputEventLogger??null}async dispose(){const e=this.inFlightSaves.map((e=>e.promise));if(e.length>0)try{await(0,Nr.wj)(Promise.all(e),j$.IN_FLIGHT_SAVE_DISPOSE_TIMEOUT_MS,"Timed out waiting for in-flight recording save")}catch{}if(this.activeRecording){await this.cleanupRecording(this.activeRecording),this.invokeStoppedCallbackOnce();try{await xo.rm(this.activeRecording.sessionDir,{force:!0,recursive:!0})}catch{}this.activeRecording=null}}findInFlightSave(e){return this.inFlightSaves.find((t=>t.state===e))}clearActiveRecordingIfCurrent(e){this.activeRecording===e&&(this.activeRecording=null)}invokeStoppedCallbackIfCurrent(e){this.activeRecording===e&&this.invokeStoppedCallbackOnce()}sanitizeToolCallId(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}async ensureRecordingDirectoryExists(){await xo.mkdir(this.stagingDir,{recursive:!0}),await xo.mkdir(this.artifactsDir,{recursive:!0})}buildSessionDir(e){const t=this.sanitizeToolCallId(e),r=`session-${(new Date).toISOString().replace(/[:.]/g,"-")}-${t}`;return s.join(this.stagingDir,r)}validateAndNormalizeSaveAsFilename(e){let t=e.trim();return t.startsWith(this.artifactsDir)&&(t=t.slice(this.artifactsDir.length),t.startsWith("/")&&(t=t.slice(1))),t=t.trim(),0===t.length?{success:!1,reason:T$.y.UNSPECIFIED}:t.includes("/")||t.includes("\\")?{success:!1,reason:T$.y.SLASHES_NOT_ALLOWED}:(t=t.replace(/[^a-zA-Z0-9 ._-]/g,"_"),t=t.trim(),0===t.length?{success:!1,reason:T$.y.UNSPECIFIED}:(t.length>128&&(t=t.slice(0,128).trim()),t.toLowerCase().endsWith(".mp4")||(t=`${t}.mp4`),{success:!0,filename:t}))}async movePolishedVideo(e,t){try{return void await xo.rename(e,t)}catch(e){if(!M$(e,"EXDEV"))throw e}try{await xo.copyFile(e,t)}catch(e){throw await xo.rm(t,{force:!0}).catch((()=>{})),e}try{await xo.unlink(e)}catch(e){throw await xo.rm(t,{force:!0}).catch((()=>{})),e}}async getUniqueArtifactVideoPath(e){const t=s.parse(e),r=t.name||"recording",n=t.ext||".mp4";let o=`${r}${n}`,i=2;for(;;){const e=s.join(this.artifactsDir,o);try{const t=await xo.open(e,"wx");return await t.close(),e}catch(e){if(!M$(e,"EEXIST"))throw e;o=`${r}-${i}${n}`,i++}}}async resolveArtifactVideoPath(e){const{saveAsFilename:t,stagingSessionDir:r}=e;let n,o;if(t){const e=this.validateAndNormalizeSaveAsFilename(t);e.success?o=e.filename:(n=e.reason,o=`${s.basename(r)}.mp4`)}else o=`${s.basename(r)}.mp4`;return{finalVideoPath:await this.getUniqueArtifactVideoPath(o),requestedFilePathRejectedReason:n}}async getVideoDurationMs(e){const{stdout:t}=await(0,au.D9)(L$,"ffprobe",["-v","error","-show_entries","format=duration","-of","default=noprint_wrappers=1:nokey=1",e],{encoding:"utf8"}),r=parseFloat(t.trim());if(!Number.isFinite(r)||r<0)throw new Error(`Invalid video duration from ffprobe: ${t.trim()}`);return Math.floor(1e3*r)}async getVideoDimensions(e){const{stdout:t}=await(0,au.D9)(L$,"ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=width,height","-of","csv=p=0:s=x",e],{encoding:"utf8"}),[r,n]=t.trim().split("x"),o=Number.parseInt(r,10),s=Number.parseInt(n,10);if(!Number.isFinite(o)||!Number.isFinite(s))throw new Error(`Invalid video dimensions from ffprobe: ${t.trim()}`);if(o<=0||s<=0)throw new Error(`Invalid non-positive video dimensions from ffprobe: ${t.trim()}`);return{width:o,height:s}}async renderPolished(e,t){const r=s.join(t,"recording"),n=s.join(r,"recording_full.mp4");try{await this.polishedRenderer.renderRecordingSession({stagingSessionDir:t,outputVideoPath:n,fps:j$.PROXY_TARGET_FPS,includeBrandTag:!0}),await xo.access(n,xo.constants.R_OK)}catch(t){const r=(0,D.fU)(e);throw r?.setAttribute("error.type",F$(t)),r?.setStatus({code:2}),t}return n}async getVideoFramerate(e){try{const{stdout:t}=await(0,au.D9)(L$,"ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=r_frame_rate","-of","default=noprint_wrappers=1:nokey=1",e],{encoding:"utf8"}),r=t.trim();if(r.includes("/")){const[e,t]=r.split("/"),n=Number.parseFloat(e),o=Number.parseFloat(t);if(Number.isFinite(n)&&Number.isFinite(o)&&0!==o){const e=n/o;if(e>0&&e<500)return Math.round(e)}}else{const e=Number.parseFloat(r);if(Number.isFinite(e)&&e>0&&e<500)return Math.round(e)}console.warn(`[record-screen] Unexpected ffprobe r_frame_rate output "${r}", defaulting to ${j$.PROXY_TARGET_FPS}fps`)}catch(e){console.warn(`[record-screen] Failed to read video framerate: ${e instanceof Error?e.message:String(e)}, defaulting to ${j$.PROXY_TARGET_FPS}fps`)}return j$.PROXY_TARGET_FPS}async startFfmpegRecording(e,t){const r=s.join(t,"recording");await xo.mkdir(r,{recursive:!0});const n=s.join(r,"recording_render_proxy_1080p.mp4"),o="windowsDesktop"===e.kind?["-f","gdigrab","-i","desktop"]:["-video_size",e.resolution,"-framerate",String(await this.detectRefreshRate(e.display)),"-draw_mouse","0","-f","x11grab","-i",e.display],i=["-vf",`scale=${j$.PROXY_TARGET_WIDTH}:-2:flags=lanczos,fps=${j$.PROXY_TARGET_FPS}`,"-c:v","libx264","-preset",j$.PROXY_PRESET,"-crf",String(j$.PROXY_CRF),"-pix_fmt","yuv420p","-profile:v","high","-x264-params","keyint=1:min-keyint=1:scenecut=0:bframes=0","-movflags","+faststart","-tune","fastdecode"],a=["-vf",`scale=${j$.PROXY_TARGET_WIDTH}:-2:flags=lanczos`,"-c:v","libx264","-preset",j$.PROXY_PRESET,"-pix_fmt","yuv420p","-movflags","+faststart"],c=this.disablePolishedRendering?a:i,l=(0,au.D9)(iu.spawn,"ffmpeg",[...o,...c,"-y",n],{stdio:["win32"===process.platform?"pipe":"ignore","pipe","pipe"],detached:"win32"!==process.platform,windowsHide:!0}),u=new Promise(((e,t)=>{let r="",n=!1;l.stderr?.on("data",(t=>{r+=t.toString(),!n&&r.includes("frame=")&&(n=!0,e(Date.now()))}));const o=setTimeout((()=>{n||t(new Error("ffmpeg did not start encoding within 5 seconds"))}),5e3);l.once("exit",((e,r)=>{clearTimeout(o),n||t(new Error(`ffmpeg exited before starting: code=${e} signal=${r}`))})),l.once("error",(e=>{clearTimeout(o),n||t(new Error(`ffmpeg failed to start: ${e.message}`))}))}));return await new Promise(((e,t)=>{const r=setTimeout(e,300);l.once("error",(e=>{clearTimeout(r),t(new Error(`Failed to start ffmpeg: ${e.message}`))})),l.once("exit",((e,n)=>{clearTimeout(r),t(null!==e&&0!==e?new Error(`ffmpeg exited with code ${e}`):null!==n?new Error(`ffmpeg killed by signal ${n}`):new Error("ffmpeg exited unexpectedly during startup"))}))})),{process:l,videoStartedPromise:u}}async detectRefreshRate(e){try{return(await qg(e)).display.refreshRate}catch(e){return console.warn(`[record-screen] Failed to detect refresh rate: ${e instanceof Error?e.message:String(e)}, using default ${j$.DEFAULT_REFRESH_RATE}Hz`),j$.DEFAULT_REFRESH_RATE}}async runFfmpegCommand(e,t){return await new Promise(((r,n)=>{const o=(0,au.D9)(iu.spawn,"ffmpeg",t,{stdio:["ignore","ignore","pipe"]});let s="";o.stderr?.on("data",(e=>{s.length<2e4&&(s+=e.toString())})),o.once("error",(t=>{n(new Error(`ffmpeg ${e} failed to start: ${t instanceof Error?t.message:String(t)}`))})),o.once("close",(t=>{0===t?r():n(new Error(`ffmpeg ${e} exited with code ${t}: ${s.trim()}`))}))}))}async saveRecordingDataPackage(e){const{sessionDir:t,durationMs:r,recordingStartEpochMs:n,ffmpegStartedEpochMs:o,inputEvents:i,resolution:a,renderProxies:c}=e,l=s.join(t,"recording"),u=s.join(l,"recording-data.json"),d=o-n,h=i.map((e=>({executionTimestampMs:e.executionTimestampMs,commandDurationMs:e.commandDurationMs,positionBefore:e.positionBefore,positionAfter:e.positionAfter,cursorTypeAfter:e.cursorTypeAfter,action:{action:this.serializeAction(e.action)}}))),p={version:3,durationMs:r,recordingStartEpochMs:n,ffmpegStartedEpochMs:o,eventToVideoOffsetMs:d,displayWidth:a.display.width,displayHeight:a.display.height,apiWidth:a.api.width,apiHeight:a.api.height,inputEvents:h,renderProxies:c??null};await xo.writeFile(u,JSON.stringify(p,null,2))}serializeAction(e){const{action:t}=e,r={case:t.case};switch(t.case){case"click":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null,button:t.value.button,count:t.value.count,modifierKeys:t.value.modifierKeys};break;case"mouseMove":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null};break;case"type":r.value={text:t.value.text};break;case"key":r.value={key:t.value.key,holdDurationMs:t.value.holdDurationMs};break;case"scroll":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null,direction:t.value.direction,amount:t.value.amount,modifierKeys:t.value.modifierKeys};break;case"drag":r.value={path:t.value.path.map((e=>({x:e.x,y:e.y}))),button:t.value.button};break;case"wait":r.value={durationMs:t.value.durationMs};break;case"screenshot":case"cursorPosition":case"mouseDown":case"mouseUp":r.value=t.value;break;default:r.value={}}return r}async stopFfmpegRecording(e){const{childProcess:t}=e;if($$(t)||!t.pid)return;const r=t.pid;return new Promise(((e,n)=>{const o=setTimeout((()=>{try{try{process.kill(-r,"SIGKILL")}catch{process.kill(r,"SIGKILL")}}catch{}n(new Error("Timeout waiting for ffmpeg to stop"))}),2e4);t.once("exit",(()=>{clearTimeout(o),e()})),t.once("error",(e=>{clearTimeout(o),n(new Error(`Error stopping ffmpeg: ${e.message}`))}));try{if(t.stdin)return t.stdin.on("error",(()=>{})),void t.stdin.end("q");try{process.kill(-r,"SIGTERM")}catch{process.kill(r,"SIGTERM")}}catch(t){if(clearTimeout(o),M$(t,"ESRCH"))return void e();n(new Error(`Failed to send SIGTERM: ${t instanceof Error?t.message:String(t)}`))}}))}async performSave(e,t,r){const n=Date.now();let o=T$.Wg.INTERNAL;try{const i=await(r.inputEventLogger?.stop())??[],a=r.inputEventLogger?.getRecordingStartTime()??r.startTime;let c;this.invokeStoppedCallbackIfCurrent(r);try{!$$(r.childProcess)&&r.childProcess.pid&&await this.stopFfmpegRecording(r)}catch(e){c=e,console.warn(`[record-screen] Failed to stop ffmpeg: ${D$(e)}`)}const l=r.ffmpegStartedEpochMs??a,u=r.sessionDir,d=s.join(u,"recording"),h=s.join(d,"recording_render_proxy_1080p.mp4");let p,f,m;try{await xo.access(h,xo.constants.R_OK)}catch(e){await this.cleanupRecording(r),this.clearActiveRecordingIfCurrent(r);const t=M$(e,"ENOENT"),o=t?`Recording proxy not found at ${h}`:`Recording proxy at ${h} could not be validated: ${D$(e)}`;return O$(t?T$.Wg.PROXY_MISSING:T$.Wg.STAGING_IO,N$(o,r,c,n))}try{if([p,f,m]=await Promise.all([this.getVideoDurationMs(h),this.getVideoDimensions(h),this.getVideoFramerate(h)]),p<=0)throw new Error(`Recording proxy has zero duration at ${h}`)}catch(e){await this.cleanupRecording(r);const t=D$(e),o=t.includes(h)?t:`Recording proxy at ${h} could not be validated: ${t}`;return O$(T$.Wg.PROXY_INVALID,N$(o,r,c,n))}const g={profileVersion:j$.PROXY_PROFILE_VERSION,generatedAtEpochMs:Date.now(),source:{width:f.width,height:f.height,durationMs:p,fps:m},artifacts:[{name:"render_proxy_1080p",path:"recording_render_proxy_1080p.mp4",width:f.width,height:f.height,fps:j$.PROXY_TARGET_FPS,codec:"h264",profile:j$.PROXY_PROFILE_VERSION,keyint:1,status:"success",elapsedMs:0}]};o=T$.Wg.STAGING_IO,void 0!==r.resolution&&await this.saveRecordingDataPackage({sessionDir:u,durationMs:p,recordingStartEpochMs:a,ffmpegStartedEpochMs:l,inputEvents:i,resolution:r.resolution,renderProxies:g}),o=T$.Wg.ARTIFACT_WRITE_FAILED;const{finalVideoPath:w,requestedFilePathRejectedReason:y}=await this.resolveArtifactVideoPath({saveAsFilename:t.saveAsFilename,stagingSessionDir:u});try{if(this.disablePolishedRendering)await xo.copyFile(h,w);else{o=T$.Wg.RENDER_FAILED;const t=await this.renderPolished(e,u);o=T$.Wg.ARTIFACT_WRITE_FAILED,await this.movePolishedVideo(t,w)}}catch(e){throw await xo.rm(w,{force:!0}).catch((()=>{})),e}try{await xo.rm(u,{force:!0,recursive:!0})}catch(e){console.warn(`[record-screen] Failed to remove staging session ${u}: ${D$(e)}`)}return this.clearActiveRecordingIfCurrent(r),new T$.Tj({result:{case:"saveSuccess",value:new T$.ol({path:w,recordingDurationMs:ve.protoInt64.parse(p.toString()),requestedFilePathRejectedReason:y})}})}catch(e){return await this.cleanupRecording(r),this.invokeStoppedCallbackIfCurrent(r),O$("binding_load_failed"===F$(e)?T$.Wg.RENDERER_UNAVAILABLE:o,D$(e))}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,D.VI)(e.withName("LocalRecordScreenExecutor.execute")),!1);try{await this.ensureRecordingDirectoryExists()}catch(e){return O$(T$.Wg.STAGING_IO,`Failed to create recording directory: ${e instanceof Error?e.message:String(e)}. Ensure the parent directory exists and has write permissions, or run: sudo mkdir -p ${this.stagingDir} ${this.artifactsDir} && sudo chmod 777 ${this.stagingDir} ${this.artifactsDir}`)}if(t.mode===T$.$u.UNSPECIFIED)return O$(T$.Wg.INVALID_MODE,"Mode must be one of START_RECORDING, SAVE_RECORDING, DISCARD_RECORDING");switch(t.mode){case T$.$u.START_RECORDING:{this.recordingStoppedCallbackInvoked=!1;let e=!1;if(this.activeRecording){const t=this.activeRecording;if(!this.inFlightSaves.some((e=>e.state===t))){e=!0;try{await this.cleanupRecording(t),await xo.rm(t.sessionDir,{force:!0,recursive:!0}).catch((()=>{}))}catch{}}this.activeRecording=null}let r,n=null,o=null,s=T$.Wg.STAGING_IO;try{o=this.buildSessionDir(t.toolCallId||"recording"),await xo.mkdir(o,{recursive:!0}),s=T$.Wg.DISPLAY_UNAVAILABLE;const i="win32"===process.platform?void 0:await qg(this.display),a=void 0===i?{kind:"windowsDesktop"}:{kind:"x11",display:this.display,resolution:i.resolutionString};s=T$.Wg.FFMPEG_START_FAILED;const{process:c,videoStartedPromise:l}=await this.startFfmpegRecording(a,o);n=c;const u=this.disablePolishedRendering?void 0:i?.resolution;void 0!==u&&(s=T$.Wg.INTERNAL,r=new Yg({displayNum:Wg(this.display),resolution:u}),await r.start());const d=r?.getRecordingStartTime()??Date.now();let h;s=T$.Wg.FFMPEG_START_FAILED;try{h=await l}catch(e){throw new Error(`ffmpeg failed to start encoding: ${e instanceof Error?e.message:String(e)}`)}const p={childProcess:n,sessionDir:o,startTime:d,inputEventLogger:r,resolution:u,ffmpegStartedEpochMs:h,ffmpegDiedEarly:!1,ffmpegDiedTime:null,ffmpegExitCode:null,ffmpegExitSignal:null};this.activeRecording=p,this.onRecordingStartedCallback&&r&&this.onRecordingStartedCallback(r),n.once("exit",((e,t)=>{p.ffmpegDiedEarly=!0,p.ffmpegDiedTime=Date.now(),p.ffmpegExitCode=e,p.ffmpegExitSignal=t}));const f=!!t.saveAsFilename;return new T$.Tj({result:{case:"startSuccess",value:new T$.T4({wasPriorRecordingCancelled:e,wasSaveAsFilenameIgnored:f})}})}catch(e){if(r)try{await r.stop()}catch{}if(n&&!n.killed&&n.pid)try{process.kill(n.pid,"SIGKILL")}catch{}return o&&await xo.rm(o,{force:!0,recursive:!0}).catch((()=>{})),this.activeRecording=null,O$(s,D$(e))}}case T$.$u.SAVE_RECORDING:{if(!this.activeRecording)return 1===this.inFlightSaves.length?await this.inFlightSaves[0].promise:O$(T$.Wg.NO_ACTIVE_RECORDING,"No active recording to save");const e=this.activeRecording,r=this.findInFlightSave(e);if(r)return await r.promise;const o=Promise.resolve().then((()=>this.performSave(n.ctx,t,e))),s={state:e,promise:o};this.inFlightSaves.push(s);try{return await o}finally{this.inFlightSaves=this.inFlightSaves.filter((e=>e!==s))}}case T$.$u.DISCARD_RECORDING:{if(!this.activeRecording)return O$(T$.Wg.NO_ACTIVE_RECORDING,"No active recording to discard");const e=this.activeRecording;if(this.findInFlightSave(e))return O$(T$.Wg.SAVE_IN_PROGRESS,"Save in progress for this recording; wait for it or start a new recording");let t=T$.Wg.INTERNAL;try{return await(e.inputEventLogger?.stop()),this.invokeStoppedCallbackOnce(),!$$(e.childProcess)&&e.childProcess.pid&&(t=T$.Wg.FFMPEG_STOP_FAILED,await this.stopFfmpegRecording(e)),t=T$.Wg.STAGING_IO,await xo.rm(e.sessionDir,{force:!0,recursive:!0}),this.activeRecording=null,new T$.Tj({result:{case:"discardSuccess",value:new T$.N8}})}catch(r){await this.cleanupRecording(e),this.invokeStoppedCallbackOnce();const n=e.sessionDir;let o=!1;try{await xo.rm(n,{force:!0,recursive:!0}),o=!0}catch{}this.activeRecording=null;return O$(t,`Failed to discard recording: ${r instanceof Error?r.message:String(r)}${o?"":`. Session may remain at: ${n}`}`)}}default:{const e=t.mode;return O$(T$.Wg.INVALID_MODE,`Unhandled recording mode: ${String(e)}`)}}}catch(e){r.error=e,r.hasError=!0}finally{A$(r)}}}async function U$(e){const t=await(0,xo.readdir)(e,{withFileTypes:!0}).catch((()=>[])),r=[];for(const n of t){const t=s.join(e,n.name),o={name:n.name,path:t,isDirectory:n.isDirectory()};n.isDirectory()&&(o.children=await U$(t)),r.push(o)}return r.sort(((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)))}function B$(e,t="",r=!0){const n=[`${t}${r?"└── ":"├── "}${e.isDirectory?`${e.name}/`:e.name}`],o=e.children;if(o?.length){const e=t+(r?" ":"│ ");o.forEach(((t,r)=>{const s=r===o.length-1;n.push(...B$(t,e,s))}))}return n}async function W$(e){if(!await(0,xo.access)(e,xo.constants.R_OK).then((()=>!0),(()=>!1)))return"(No notes directory yet - will be created when you write your first note)";const t=await U$(e);return 0===t.length?"(Notes directory is empty)":t.flatMap(((e,r)=>B$(e,"",r===t.length-1))).join("\n")}async function H$(e,t){return W$(s.join(e,"agent-notes",t))}async function q$(e){return W$(s.join(e,"agent-notes","shared"))}j$.IN_FLIGHT_SAVE_DISPOSE_TIMEOUT_MS=3e4,j$.PROXY_TARGET_WIDTH=1920,j$.PROXY_TARGET_FPS=60,j$.PROXY_CRF=17,j$.PROXY_PRESET="veryfast",j$.PROXY_PROFILE_VERSION="render-proxy-h264-all-i-v1",j$.DEFAULT_REFRESH_RATE=60;var z$=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},G$=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const V$=3e3,K$=(0,d.h)("local-exec:request-context"),J$=Symbol("sectionLoadTimedOut");function Z$(e,t){if(void 0===t)return e;let r;const n=new Promise((e=>{r=setTimeout((()=>e(J$)),t)}));return e.catch((()=>{})),Promise.race([e,n]).finally((()=>{clearTimeout(r)}))}class X${async read(e,t){const r=this.inFlight??this.begin(e),n=this.last;if(void 0===n)return r;const o=await Z$(r,t).catch((()=>J$));return o===J$?n.value:o}prefetch(e){void 0===this.inFlight&&this.begin(e).catch((()=>{}))}begin(e){const t=e();this.inFlight=t;const r=()=>{this.inFlight===t&&(this.inFlight=void 0)};return t.then((e=>{this.last={value:e},r()}),r),t}}async function Q$(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{z$(o,(0,D.VI)(e.withName("LocalRequestContextExecutor.getGitStatusForRepoPath")),!1);try{return(await t.exec(e,r,["--no-optional-locks","status","--short","--branch"],{timeout:n,caller:"getGitStatusForRepoPath"})).stdout}catch{return}}catch(e){o.error=e,o.hasError=!0}finally{G$(o)}}async function Y$(e,t,r,n){try{const o=(await t.exec(e,r,["rev-parse","--abbrev-ref","HEAD"],{timeout:n,caller:"getGitBranchForRepoPath"})).stdout.trim();if("HEAD"===o||0===o.length)return;return o}catch{return}}async function eM(e,t,r,n){const o=e=>{let t;const r=new Promise((e=>{t=setTimeout((()=>{e(void 0)}),n)}));return Promise.race([e.catch((()=>{})),r]).finally((()=>{void 0!==t&&clearTimeout(t)}))},[s,i]=await Promise.all([o(Q$(e,t,r,n)),o(Y$(e,t,r,n))]);return{status:s,branchName:i}}async function tM(e,t,r={}){const{projectDir:n,notesSessionId:s,agentNotesEnabled:i,reportProcessWorkingDirectory:a,getSmartModeClassifierAutoModeEnabled:c,devForceNextSmartModeClassifierBlockToken:l,isWorkingDirHomeDir:u,getSandboxEnabled:d,getSandboxSupported:h,getNetworkAllowlistInfo:p,userTerminalHint:f,artifactsFolder:m,secretRedactionEnabled:g,getComputerUseSupported:w,getComputerUseDesktop:y,getMockPromptTime:v}=r,b=y?.(),S=`${o.platform()} ${o.release()}`,k=(0,No.G6)(f),_=v?.(),C=(()=>{try{return(new Intl.DateTimeFormat).resolvedOptions().timeZone??void 0}catch{return}})(),E=n,x=n?`${n}/terminals`:void 0,P=n&&!1!==i?`${n}/agent-notes/shared`:void 0,R=n&&s&&!1!==i?`${n}/agent-notes/${s}`:void 0,I=n?`${n}/agent-transcripts`:void 0,T=!!d&&d(),A=h?.(),$=c?.();let M;if(p)try{const e=await Z$(p(),3e3);e!==J$&&(M=e)}catch{M=void 0}return new Fr.GE({osVersion:S,workspacePaths:t,shell:k,sandboxEnabled:T,projectFolder:E,terminalsFolder:x,agentSharedNotesFolder:P,agentConversationNotesFolder:R,agentTranscriptsFolder:I,timeZone:C,...!1!==a&&{processWorkingDirectory:process.cwd()},artifactsFolder:m,...void 0!==$&&{smartModeClassifierAutoModeEnabled:$},...void 0!==l&&{devForceNextSmartModeClassifierBlockToken:l},...void 0!==_&&{devMockPromptTime:ve.Timestamp.fromDate(_)},...void 0!==g&&{secretRedactionEnabled:g},...void 0!==A&&{sandboxSupported:A},...void 0!==M?.hasDefaults&&{sandboxNetworkHasDefaults:M.hasDefaults},...M?.explicitEntries&&M.explicitEntries.length>0&&{sandboxNetworkExplicitAllowlist:M.explicitEntries},...void 0!==w&&{computerUseSupported:w()},...void 0!==b&&{computerUseDesktop:b},...void 0!==u&&{isWorkingDirHomeDir:u}})}const rM={type:"object",properties:{},additionalProperties:!1};function nM(e,t){return{tools:(!0===t?.internalBrowserProvidersOnly?e.servers.filter((e=>Zn.has(e.serverIdentifier))):e.servers).flatMap((e=>e.tools)).map((e=>new vn.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,...!0===t?.inputSchemaJson?{inputSchemaJson:void 0===e.inputSchema?void 0:JSON.stringify(e.inputSchema)}:{inputSchema:e.inputSchema?ve.Value.fromJson(e.inputSchema):void 0}}))),mcpInstructions:e.servers.flatMap((e=>e.instructions))}}function oM(e,t){const r=!0===t?.slimDescriptors,n=e.servers.map((e=>{const n=e.instructions.map((e=>e.instructions)).filter(Boolean).join("\n"),o=e.tools.map((e=>new vn.E$({toolName:e.toolName,...Nb(e.annotations),...r?{}:{description:e.description,...!0===t?.inputSchemaJson?{inputSchemaJson:void 0===e.inputSchema?void 0:JSON.stringify(e.inputSchema)}:{inputSchema:void 0!==e.inputSchema?ve.Value.fromJson(e.inputSchema):void 0}}})));return!Jn(e.serverIdentifier)||!0!==t?.alwaysExposeVirtualMcpAuthTool&&"needsAuth"!==e.status||o.some((e=>e.toolName===iT))||o.push(new vn.E$({toolName:iT,...r?{}:{description:aT,...!0===t?.inputSchemaJson?{inputSchemaJson:JSON.stringify(rM)}:{inputSchema:ve.Value.fromJson(rM)}}})),new vn.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,serverUseInstructions:n||void 0,tools:o})}));return new vn.U_({enabled:!0,mcpDescriptors:n})}function sM(e){const t=e?.trim();return t||void 0}function iM(e,t){const r=function(e){return sM(e.serverIdentifier)}(e);if(r)return r;const n=sM(e.serverName);return n?t.get(n)??n:void 0}class aM{constructor(e){this.mcpLease=e}async getState(e){const[t,r]=await Promise.all([this.mcpLease.getTools(e).catch((t=>(K$.warn(e,"Error fetching MCP tools",{error:t}),[]))),this.mcpLease.getInstructions(e).catch((t=>(K$.warn(e,"Error fetching MCP instructions",{error:t}),[])))]);return function(e,t,r,n=!1){const o=new Map;for(const t of e)o.has(t.providerIdentifier)||o.set(t.providerIdentifier,t.clientKey);const s=t.map((e=>iM(e,o))).filter((e=>Boolean(e))),i=[...new Set([...e.map((e=>e.clientKey)),...s,...Array.from(r?.entries()??[]).filter((([,e])=>"connected"!==e.status)).map((([e])=>e))])];if(n&&void 0!==r){const e=new Map(Array.from(r.keys(),((e,t)=>[e,t])));i.sort(((t,r)=>(e.get(t)??e.size)-(e.get(r)??e.size)))}return{servers:i.map((n=>{const s=e.filter((e=>e.clientKey===n));return{serverName:s[0]?.providerIdentifier??n,serverIdentifier:n,plugin:s[0]?.plugin,marketplace:s[0]?.marketplace,tools:s,instructions:t.filter((e=>iM(e,o)===n)),status:r?.get(n)?.status,errorMessage:r?.get(n)?.errorMessage}}))}}(t,r,await async function(e,t){const r=await t.getClients(e).catch((t=>(K$.warn(e,"Error fetching MCP clients",{error:t}),{}))),n=await Promise.all(Object.entries(r).map((async([t,r])=>{const n=await r.getState(e).catch((()=>({kind:"error",message:"Failed to fetch MCP client state"})));return[t,{status:to(n),errorMessage:"error"===n.kind&&void 0!==n.message?n.message:void 0}]})));return new Map(n)}(e,this.mcpLease))}}function cM(e){return new Mc._W({result:{case:"success",value:new Mc.pv({servers:e.servers.map((e=>new Mc.XE({serverName:e.serverName,serverIdentifier:e.serverIdentifier,plugin:e.plugin,marketplace:e.marketplace,tools:e.tools.map((e=>new vn.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?ve.Value.fromJson(e.inputSchema):void 0,metaJson:Xn(e._meta),...Nb(e.annotations)}))),instructions:e.instructions,status:e.status,errorMessage:e.errorMessage})))})}})}class lM{constructor(e,t,r){this.mcpStateAccessor=e,this.ensureMcpServersLoaded=t,this.options=r}async execute(e,t){if(void 0!==t.ruleSubjects&&void 0!==this.options?.serverRuleSubjects)return function(e,t){const r={commandPatterns:t.commandPatterns,serverUrlPatterns:t.serverUrlPatterns},n=[];for(const[t,o]of e){const e=void 0!==o.command?{transport:Mc.zj.STDIO,value:o.command,matched:{command:o.command}}:void 0!==o.url?{transport:Mc.zj.HTTP,value:o.url,matched:{url:o.url}}:void 0;void 0!==e&&n.push(new Mc.XE({serverName:t,serverIdentifier:t,ruleSubject:new Mc.D0({transport:e.transport,...IC(e.matched,r)?{value:e.value}:{}})}))}return new Mc._W({result:{case:"success",value:new Mc.pv({servers:n})}})}(this.options.serverRuleSubjects(),t.ruleSubjects);try{await(this.ensureMcpServersLoaded?.(e,t.serverIdentifiers,{wait:!t.kickOnly}))}catch{}t.refreshPolicy!==Mc.ew.FORCE_IF_MISSING&&t.refreshPolicy!==Mc.ew.FORCE||await(this.mcpStateAccessor.refreshNow?.(e));const r=await this.mcpStateAccessor.getState(e);if(!0===this.options?.filterToRequestedServers&&t.serverIdentifiers.length>0){const e=new Set(t.serverIdentifiers),n=r.servers.filter((t=>e.has(t.serverIdentifier)));if(n.length>0)return cM({...r,servers:n})}return cM(r)}}class uM{constructor(e,t,r,n,o,s,i,a,c={}){this.cursorRulesService=e,this.cloudRulesService=t,this.subagentsService=r,this.repositoryProvider=n,this.grepProvider=o,this.mcpStateAccessor=s,this.gitExecutor=i,this.workspacePaths=a,this.reusedGitInfo=new Map,this.reusedMcpState=new X$,this.reusedAgentSkills=new X$,this.reusedAdminCommandDenylist=new X$,this.cachedWorkspaces=new Map,this.inFlightWorkspaceWarms=new Map;const{projectDir:l,getSmartModeClassifierAutoModeEnabled:u,getAdminCommandDenylist:d,devForceNextSmartModeClassifierBlockToken:h,isWorkingDirHomeDir:p,agentNotesEnabled:f,reportProcessWorkingDirectory:m,createFileWatcher:g,getSandboxEnabled:w,getSandboxSupported:y,getNetworkAllowlistInfo:v,userTerminalHint:b,getMcpFileSystemOptions:S,mcpMetaToolEnabled:k,mcpMetaToolSlimDescriptors:_,mcpInputSchemaJson:C,alwaysExposeVirtualMcpAuthTool:E,getArtifactsFolder:x,secretRedactionEnabled:P,attributionConfigProvider:R,isAttributionDisabledByAdmin:I,getAgentSkills:T,additionalRules:A,getComputerUseSupported:$,getComputerUseDesktop:M,getMockPromptTime:D}=c;this.projectDir=l,this.isWorkingDirHomeDir=p,this.agentNotesEnabled=f??!0,this.reportProcessWorkingDirectory=m??!0,this.getSandboxEnabled=w,this.getSandboxSupported=y,this.getNetworkAllowlistInfo=v,this.getSmartModeClassifierAutoModeEnabled=u,this.getAdminCommandDenylist=d,this.devForceNextSmartModeClassifierBlockToken=h,this.getMockPromptTime=D,this.userTerminalHint=b,this.getMcpFileSystemOptions=S,this.mcpMetaToolEnabled=k??!1,this.mcpMetaToolSlimDescriptors=_??!1,this.mcpInputSchemaJson=C??!1,this.alwaysExposeVirtualMcpAuthTool=E??!1,this.getArtifactsFolder=x,this.secretRedactionEnabled=P,this.attributionConfigProvider=R,this.isAttributionDisabledByAdmin=I,this.getAgentSkills=T,this.additionalRules=A??[],this.getComputerUseSupported=$,this.getComputerUseDesktop=M,this.reduceContextHotPath=c.reduceContextHotPath??!1,this.sectionLoadTimeoutMs=c.sectionLoadTimeoutMs,this.reportSectionCompleteness=c.reportSectionCompleteness??!1,this.freshSectionWaitMs=c.freshSectionWaitMs,this.onRequestContext=c.onRequestContext,this.mcpFieldsFromCaller=c.mcpFieldsFromCaller??!1,!0!==c.deferWarmup&&this.warm(),void 0!==g&&(this.fileWatcher=g(),this.fileWatcher.onDidChange((e=>{this.onWorkspacePathChanged(e)})),this.fileWatcher.onDidCreate((e=>{this.onWorkspacePathChanged(e)})),this.fileWatcher.onDidDelete((e=>{this.onWorkspacePathChanged(e)})))}warm(){this.warmWorkspaceCaches(),void 0===this.globalCache&&this.rebuildGlobalCache()}onWorkspacePathChanged(e){this.rebuildAllCaches()}getWorkspaceCache(e){return this.cachedWorkspaces.get(e)}warmWorkspaceCaches(){const e=(0,b.q6)();Promise.all(this.workspacePaths.map((t=>this.ensureWorkspaceCacheWarm(e,t))))}ensureWorkspaceCacheWarm(e,t){if(this.cachedWorkspaces.has(t))return Promise.resolve();const r=this.inFlightWorkspaceWarms.get(t);if(void 0!==r)return r;const n=this.warmWorkspaceCache(e,t).finally((()=>{this.inFlightWorkspaceWarms.delete(t)}));return this.inFlightWorkspaceWarms.set(t,n),n}async warmWorkspaceCache(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=z$(r,(0,D.VI)(e.withName("LocalRequestContextExecutor.warmWorkspaceCache")),!1),o=await tc(n.ctx,this.gitExecutor,t),s=o?await ac(n.ctx,this.gitExecutor,o):void 0,i={repoPath:o??void 0,remoteUrl:void 0!==s?cc(s):void 0};if(this.cachedWorkspaces.set(t,i),void 0!==this.freshSectionWaitMs&&void 0!==i.repoPath){const e=i.repoPath;this.gitInfoSection(e).prefetch((()=>eM((0,b.q6)(),this.gitExecutor,e,V$)))}}catch(e){r.error=e,r.hasError=!0}finally{G$(r)}}gitInfoSection(e){let t=this.reusedGitInfo.get(e);return void 0===t&&(t=new X$,this.reusedGitInfo.set(e,t)),t}rebuildAllCaches(){this.cacheDebounceTimeout&&clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=setTimeout((()=>{this.cacheDebounceTimeout=void 0,this.rebuildGlobalCache()}),5e3)}invalidateGlobalCache(){this.globalCache=void 0,this.lastGoodGlobalCache=void 0,this.globalCacheTraceId=void 0}refreshGlobalCache(){this.cacheDebounceTimeout&&(clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=void 0),this.rebuildGlobalCache()}rebuildGlobalCache(){const e={stack:[],error:void 0,hasError:!1};try{const t=(0,b.q6)(),r=z$(e,(0,D.VI)(t.withName("LocalRequestContextExecutor.rebuildGlobalCache")),!1);this.globalCacheTraceId=r.span.spanContext().traceId;const n=this.computeGlobalCache(r.ctx);return this.globalCache=n,(this.reduceContextHotPath||void 0!==this.sectionLoadTimeoutMs||void 0!==this.freshSectionWaitMs)&&n.then((e=>{this.globalCache===n&&(this.lastGoodGlobalCache=e)}),(()=>{this.globalCache===n&&(this.globalCache=void 0)})),n}catch(t){e.error=t,e.hasError=!0}finally{G$(e)}}async computeGlobalCache(e){const t={stack:[],error:void 0,hasError:!1};try{const r=z$(t,(0,D.VI)(e.withName("LocalRequestContextExecutor.computeGlobalCache")),!1),n=AbortSignal.timeout(1e3),o=performance.now(),s={},i=(e,t)=>{const r=performance.now();return t.finally((()=>{s[e]=Math.round(performance.now()-r)}))},[a,c,l,u]=await Promise.all([i("cursorRules",this.cursorRulesService.getAllCursorRules(r.ctx)),i("cloudRule",this.cloudRulesService?this.cloudRulesService.getCloudRule(r.ctx):Promise.resolve(null)),i("codebaseRef",this.repositoryProvider.getCodebaseReference(r.ctx,n).catch((()=>{}))),i("subagents",this.subagentsService?this.subagentsService.getAllSubagents().catch((()=>[])):Promise.resolve([]))]),d=Math.round(performance.now()-o);return d>1e3&&K$.warn(r.ctx,"computeGlobalCache: slow",{totalMs:d,...s,ruleCount:a.length}),{rules:[...this.additionalRules,...a],cloudRule:c,codebaseReference:l,customSubagents:u}}catch(e){t.error=e,t.hasError=!0}finally{G$(t)}}dispose(){this.cacheDebounceTimeout&&(clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=void 0),this.fileWatcher&&(this.fileWatcher.dispose(),this.fileWatcher=void 0),this.globalCache=void 0,this.lastGoodGlobalCache=void 0}async collectWorkspaceCaches(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=z$(r,(0,D.VI)(e.withName("LocalRequestContextExecutor.collectWorkspaceCaches")),!1);let o;if(this.grepProvider.getTrackedState)try{o=await this.grepProvider.getTrackedState(this.workspacePaths)}catch{o=void 0}let s=!0,i=!0;return{gitRepos:(await Promise.all(this.workspacePaths.map((async e=>{let r=this.getWorkspaceCache(e);if(void 0===r){if(!t.waitForWorkspaceCache)return s=!1,void this.ensureWorkspaceCacheWarm(n.ctx,e);if(await this.ensureWorkspaceCacheWarm(n.ctx,e),r=this.getWorkspaceCache(e),void 0===r)return void(s=!1)}const a=o?.[e];if(void 0!==a)return void 0!==r.repoPath&&void 0===a.gitStatus&&(i=!1),new Fr.DS({path:r.repoPath,status:a.gitStatus,branchName:a.gitBranchName,remoteUrl:r.remoteUrl,isOriginBacked:Xa(r.remoteUrl)});if(void 0===r.repoPath)return;const c=r.repoPath,{status:l,branchName:u}=void 0===this.freshSectionWaitMs?await eM(n.ctx,t.gitExecutor,c,V$):await this.gitInfoSection(c).read((()=>eM((0,b.q6)(),t.gitExecutor,c,V$)),this.freshSectionWaitMs);return void 0===l&&(i=!1),new Fr.DS({path:r.repoPath,status:l,branchName:u,remoteUrl:r.remoteUrl,isOriginBacked:Xa(r.remoteUrl)})})))).filter((e=>void 0!==e)),gitRepoInfoComplete:s,gitStatusInfoComplete:s&&i}}catch(e){r.error=e,r.hasError=!0}finally{G$(r)}}shareBoundedSectionLoad(e,t,r){if(void 0===this.sectionLoadTimeoutMs)return r();const n=e();if(void 0!==n)return n;const o=r();t(o);const s=()=>{e()===o&&t(void 0)};return o.then(s,s),o}async computeCachedRequestContext(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=z$(n,(0,D.VI)(e.withName("LocalRequestContextExecutor.computeCachedRequestContext")),!1),s=this.projectDir,i=async()=>{const e={stack:[],error:void 0,hasError:!1};try{const t=z$(e,(0,D.VI)(o.ctx.withName("LocalRequestContextExecutor.computeCachedRequestContext.getGlobalData")),!1);if(this.globalCacheTraceId&&t.span.setAttribute("cacheTraceId",this.globalCacheTraceId),!this.reduceContextHotPath&&void 0===this.freshSectionWaitMs){if(void 0===this.globalCache){const e=this.computeGlobalCache(o.ctx);this.globalCache=e,e.catch((()=>{this.globalCache===e&&(this.globalCache=void 0)})),void 0!==this.sectionLoadTimeoutMs&&e.then((t=>{this.globalCache===e&&(this.lastGoodGlobalCache=t)}),(()=>{}))}return this.globalCache}return void 0!==this.lastGoodGlobalCache?this.lastGoodGlobalCache:this.globalCache??this.rebuildGlobalCache()}catch(t){e.error=t,e.hasError=!0}finally{G$(e)}},a=performance.now(),c={},l=(e,t)=>{const r=performance.now();return t.finally((()=>{c[e]=Math.round(performance.now()-r)}))},u=e=>Z$(e,this.sectionLoadTimeoutMs),d=(e,t,r)=>this.shareBoundedSectionLoad(e,t,r),h=this.freshSectionWaitMs,p=(e,t)=>void 0===h?t():e.read(t,h),f=void 0===h?o.ctx:(0,b.q6)(),[m,g,w,{gitRepos:y,gitRepoInfoComplete:v,gitStatusInfoComplete:S},k,_,C,E,x,P]=await Promise.all([l("globalCache",u(i())),l("mcpState",this.mcpFieldsFromCaller?Promise.resolve({servers:[]}):u(p(this.reusedMcpState,(()=>d((()=>this.inFlightMcpState),(e=>{this.inFlightMcpState=e}),(()=>this.mcpStateAccessor.getState(f))))))),l("env",tM(o.ctx,this.workspacePaths,{projectDir:s,notesSessionId:t.notesSessionId,agentNotesEnabled:this.agentNotesEnabled,reportProcessWorkingDirectory:this.reportProcessWorkingDirectory,getSmartModeClassifierAutoModeEnabled:this.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:this.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:this.getMockPromptTime,isWorkingDirHomeDir:this.isWorkingDirHomeDir,getSandboxEnabled:this.getSandboxEnabled,getSandboxSupported:this.getSandboxSupported,getNetworkAllowlistInfo:this.getNetworkAllowlistInfo,userTerminalHint:this.userTerminalHint,artifactsFolder:this.getArtifactsFolder?.(o.ctx),secretRedactionEnabled:this.secretRedactionEnabled,getComputerUseSupported:this.getComputerUseSupported,getComputerUseDesktop:this.getComputerUseDesktop})),l("git",this.collectWorkspaceCaches(o.ctx,{waitForWorkspaceCache:!0===t.waitForWorkspaceCache,gitExecutor:r})),l("conversationNotes",this.agentNotesEnabled&&s&&t.notesSessionId?H$(s,t.notesSessionId):Promise.resolve(void 0)),l("sharedNotes",this.agentNotesEnabled&&s?q$(s):Promise.resolve(void 0)),l("mcpFileSystemOptions",this.getMcpFileSystemOptions?this.getMcpFileSystemOptions(o.ctx,{timeoutMs:3e3}):Promise.resolve(void 0)),l("attribution",this.isAttributionDisabledByAdmin?this.isAttributionDisabledByAdmin().catch((()=>!0)):Promise.resolve(!1)),l("agentSkills",u(p(this.reusedAgentSkills,(()=>d((()=>this.inFlightAgentSkills),(e=>{this.inFlightAgentSkills=e}),(()=>this.getAgentSkills?this.getAgentSkills(f):Promise.resolve([]))))))),l("adminCommandDenylist",u(p(this.reusedAdminCommandDenylist,(()=>d((()=>this.inFlightAdminCommandDenylist),(e=>{this.inFlightAdminCommandDenylist=e}),(()=>this.getAdminCommandDenylist?this.getAdminCommandDenylist():Promise.resolve(void 0)))))))]),R=m===J$,I=g===J$,T=x===J$,A=P===J$,$=R?this.lastGoodGlobalCache??{rules:[...this.additionalRules],cloudRule:null,codebaseReference:void 0,customSubagents:[]}:m,M=I?{servers:[]}:g,O=T?[]:x,F=A?void 0:P;(R||I||T||A)&&K$.warn(o.ctx,"computeCachedRequestContext: section load timed out",{timeoutMs:this.sectionLoadTimeoutMs,rulesAndSubagents:R,mcpState:I,agentSkills:T,adminCommandDenylist:A});const N=performance.now()-a;for(const[e,t]of Object.entries(c))o.span.setAttribute(`requestContext.timing.${e}Ms`,t);o.span.setAttribute("requestContext.timing.totalMs",Math.round(N)),N>1e3&&K$.warn(o.ctx,"computeCachedRequestContext: slow parallel data collection",{durationMs:Math.round(N),...c});const L=this.mcpMetaToolEnabled?oM(M,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,slimDescriptors:this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}):void 0,j=this.attributionConfigProvider?.get(),U=!E&&(j?.attribution?.attributeCommitsToAgent??!0),B=!E&&(j?.attribution?.attributePRsToAgent??!0),W=new Fr.bb({rules:$.rules,env:w,gitRepos:y,gitRepoInfoComplete:v,repositoryInfo:$.codebaseReference?[{relativeWorkspacePath:$.codebaseReference.relativeWorkspacePath,repoName:$.codebaseReference.repoName,repoOwner:$.codebaseReference.repoOwner,isTracked:$.codebaseReference.isTracked,isLocal:$.codebaseReference.isLocal,orthogonalTransformSeed:$.codebaseReference.orthogonalTransformSeed,pathEncryptionKey:$.codebaseReference.pathEncryptionKey}]:[],...nM(M,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}),conversationNotesListing:k,sharedNotesListing:_,customSubagents:$.customSubagents,mcpFileSystemOptions:C,mcpMetaToolOptions:L,supportsMcpAuth:!0,commitAttributionMessage:U?"enabled":void 0,prAttributionMessage:B?"enabled":void 0,agentSkills:O,adminCommandDenylist:F?.rules??[]});return null!==$.cloudRule&&void 0!==$.cloudRule&&(W.cloudRule=$.cloudRule),this.reportSectionCompleteness&&(W.rulesInfoComplete=!R,W.customSubagentsInfoComplete=!R,W.agentSkillsInfoComplete=!T,W.mcpInfoComplete=!I,W.mcpFileSystemInfoComplete=this.mcpMetaToolEnabled||void 0!==C,W.envInfoComplete=!0,W.gitStatusInfoComplete=S),W}catch(e){n.error=e,n.hasError=!0}finally{G$(n)}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{this.onRequestContext?.();const n=z$(r,(0,D.VI)(e.withName("LocalRequestContextExecutor.execute")),!1);n.span.setAttribute("enableCaching",void 0!==this.fileWatcher),n.span.setAttribute("hasGlobalCache",!!this.globalCache);try{const e=this.gitExecutor.forRequest?.()??this.gitExecutor,r=await this.computeCachedRequestContext(n.ctx,t,e);return new Fr._G({result:{case:"success",value:new Fr.yW({requestContext:r})}})}catch(e){return e instanceof Error||"string"==typeof e?n.span.recordException(e):n.span.recordException(Cc(e)),new Fr._G({result:{case:"error",value:new Fr.nf({error:e instanceof Error?e.message:String(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{G$(r)}}}function dM(e){return 0!==e.timeout?e.timeout:e.isBackground||e.timeoutBehavior===fe._d.BACKGROUND||void 0!==e.hardTimeout&&e.hardTimeout>0?0:3e4}var hM=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class pM{constructor(e,t,r,n){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r}buildResultFromExit(e){return 0===(e.exitCode??-1)?new fe.W4({result:{case:"success",value:new fe.QR({...e,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:hs(e.sandboxPolicy)}):new fe.W4({result:{case:"failure",value:new fe.xC({...e,aborted:void 0!==e.abortReason,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:hs(e.sandboxPolicy)})}async executeWithPolicy(e,t,r,n,o){const s=Date.now(),i=new AbortController,a=e.signal?AbortSignal.any([e.signal,i.signal]):i.signal,c=setTimeout((()=>{i.abort()}),n);try{let n,l,u,d="",h="",p=null;const f=o?{perUser:o}:void 0;for await(const o of this.coreExecutor.execute(e,{command:t.command,workingDirectory:r,signal:a,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:f,fileOutputThresholdBytes:t.fileOutputThresholdBytes,pipeStdin:!1}))"stdout"===o.type?d+=o.data:"stderr"===o.type?h+=o.data:"exit"===o.type&&(p=null!=o.code?0|o.code:null,l=o.outputLocation,n=o.aborted?a.aborted?i.signal.aborted&&a.reason===i.signal.reason?fe.Lv.TIMEOUT:fe.Lv.USER_ABORT:fe.Lv.UNSPECIFIED:void 0,u=Oy(o.localExecutionTimeMs));clearTimeout(c);const m=Date.now()-s,g={command:t.command,workingDirectory:r,exitCode:void 0!==n?-1:p??-1,signal:void 0!==n?"SIGTERM":"",abortReason:n,stdout:d,stderr:h,executionTime:m,localExecutionTimeMs:u,sandboxPolicy:o,outputLocation:l};return this.buildResultFromExit(g)}catch(s){return clearTimeout(c),i.signal.aborted&&!e.signal.aborted?new fe.W4({result:{case:"timeout",value:new fe.eG({command:t.command,workingDirectory:r,timeoutMs:n})},sandboxPolicy:hs(o)}):e.signal.aborted?new fe.W4({result:{case:"rejected",value:new fe.pZ({command:t.command,workingDirectory:r,reason:"Command aborted"})},sandboxPolicy:hs(o)}):new fe.W4({result:{case:"spawnError",value:new fe.mJ({command:t.command,workingDirectory:r,error:s instanceof Error?s.message:"Unknown error"})},sandboxPolicy:hs(o)})}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,D.VI)(e.withName("LocalShellExecutor.execute")),!1).ctx;(0,D.HF)(n,"LocalShellExecutor.execute");const o=t.command,s=t.requestedSandboxPolicy?ds(t.requestedSandboxPolicy):void 0,i=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),a=dM(t),c=(0,ts.o1)(i);if(!t.parsingResult)return new fe.W4({result:{case:"spawnError",value:new fe.mJ({command:o,workingDirectory:c,error:"Parsing result is required"})}});let l;if(Oo(t)){const e=await this.permissionsService.shouldEnforceShellInvariantBlocks(n,{workingDirectory:c,skipUnsafeWorkingDirectoryBlock:!0,command:o,parsingResult:t.parsingResult,toolCallId:t.toolCallId,resolveSkippedApprovalPolicy:!0},s);if("block"===e.kind)return new fe.W4({result:rd(o,c,e.reason)});l=e.policy??s}else{const e=await this.permissionsService.shouldBlockShellCommand(n,o,{workingDirectory:c,timeout:a,parsingResult:t.parsingResult,toolCallId:t.toolCallId,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Mo(t)},s);if("block"===e.kind)return new fe.W4({result:rd(o,c,e.reason)});l=e.policy}return l=await $c(l,{command:o,workingDirectory:c,parsingResult:t.parsingResult,permissionsService:this.permissionsService,ignoreService:this.ignoreService}),this.executeWithPolicy(n,t,i,a,l)}catch(e){r.error=e,r.hasError=!0}finally{hM(r)}}}var fM=r("../proto/dist/generated/agent/v1/shell_allowlist_precheck_exec_pb.js");class mM{constructor(e){this.permissionsService=e}async execute(e,t){const r=t.parsingResult??new fe.HO,n=await this.permissionsService.isShellCommandFullyAllowlisted(e,t.command,{workingDirectory:t.workingDirectory,parsingResult:r,classifierResult:t.classifierResult,toolCallId:t.toolCallId});return new fM.e({allowlisted:n})}}class gM{constructor(e){this.shellStreamExecutor=e}async execute(e,t,r){return""===t.toolCallId.trim()?new fe.jK({status:fe.iA.NOT_FOUND}):this.shellStreamExecutor.forceBackgroundByToolCallId(e,t.toolCallId)}}var wM=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const yM=(0,d.h)("local-exec:shell-stream");class vM{constructor(e,t){this.iterator=e,this.timeoutMs=t,this.pendingPromise=null,this.stopPromise=new Promise((e=>{this.stopResolve=e}))}stop(e){return void 0===this.stopReason&&(this.stopReason=e,this.stopResolve?.(),!0)}get timedOut(){return"background"===this.stopReason?.kind&&this.stopReason.reason===fe.Jg.TIMEOUT}get backgroundRequested(){return"background"===this.stopReason?.kind}get backgroundReasonValue(){return"background"===this.stopReason?.kind?this.stopReason.reason:void 0}get stopReasonValue(){return this.stopReason}async*iterate(){this.timer=setTimeout((()=>{this.stop({kind:"background",reason:fe.Jg.TIMEOUT})}),this.timeoutMs);try{for(;;){if(void 0!==this.stopReason)return;this.pendingPromise=this.iterator.next();const e=await Promise.race([this.pendingPromise.then((e=>({kind:"result",result:e}))),this.stopPromise.then((()=>({kind:"stopped"})))]);if("stopped"===e.kind)return;if(this.pendingPromise=null,e.result.done)return;yield e.result.value}}finally{clearTimeout(this.timer)}}requestBackground(){return this.stop({kind:"background",reason:fe.Jg.USER_REQUEST})}abort(){this.stop({kind:"abort"})}getHandoffIterator(){if(this.pendingPromise){const e=this.pendingPromise;this.pendingPromise=null;let t=!1;return{next:async()=>t?this.iterator.next():(t=!0,e)}}return this.iterator}}function bM(){let e=()=>{};return{promise:new Promise((t=>{e=t})),resolve:e}}class SM{constructor(e,t,r,n){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r,this.backgroundShellManager=n,this.activeForegroundExecutions=new Map,this.pendingShells=new Map}hasForegroundWork(){return this.activeForegroundExecutions.size>0||this.pendingShells.size>0}async forceBackgroundByToolCallId(e,t){const r=this.pendingShells.get(t),n=void 0===r||r.awaitingApproval?this.activeForegroundExecutions.get(t):await async function(e,t){const[r,n]=e.withCancel();try{return await Promise.race([t.registered.promise,(0,b.uk)(r).then((()=>{}))])}finally{n()}}(e,r),o=n?.requestBackground();return o?new fe.jK({status:fe.iA.ACCEPTED,shellResult:o}):new fe.jK({status:fe.iA.NOT_FOUND})}pendingFrom(e){return{execute:(t,r,n)=>this.whilePending(r,(()=>e.get(re).execute(t,r,n)))}}execute(e,t){return this.whilePending(t,(r=>this.run(e,t,r)))}async*whilePending(e,t){let r=this.pendingShells.get(e.toolCallId);void 0===r&&(r={awaitingApproval:!1,registered:bM()},""!==e.toolCallId&&e.timeoutBehavior===fe._d.BACKGROUND&&this.pendingShells.set(e.toolCallId,r));try{yield*t(r)}finally{this.settle(e.toolCallId,r,void 0)}}settle(e,t,r){this.pendingShells.get(e)===t&&this.pendingShells.delete(e),t.registered.resolve(r)}async*run(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{e.signal?.throwIfAborted(),function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(n,(0,D.VI)(e.withName("LocalShellStreamExecutor.execute")),!1);const o=t.command;let s=t.requestedSandboxPolicy?ds(t.requestedSandboxPolicy):void 0;const i=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),a=dM(t),c=(0,ts.o1)(i),l=Date.now(),u=performance.now(),d=new fe.HO(qo(o).structured),h=Cs({command:o,parsingResult:d,blockedCommands:t.adminCommandDenylist});if(void 0!==h)return void(yield new fe.FI({event:{case:"rejected",value:new fe.pZ({command:o,workingDirectory:c,reason:h})}}));const p=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:c,skipUnsafeWorkingDirectoryBlock:!0,command:o,parsingResult:d,toolCallId:t.toolCallId,resolveSkippedApprovalPolicy:Oo(t)},s);if("block"===p.kind)return"permissionsConfig"===p.reason.type?void(yield new fe.FI({event:{case:"permissionDenied",value:new fe.jn({command:o,workingDirectory:c,error:"Command blocked by permissions configuration",isReadonly:p.reason.isReadonly??!1})}})):void(yield new fe.FI({event:{case:"rejected",value:new fe.pZ({command:o,workingDirectory:c,reason:td(p.reason)})}}));if(yM.info(e,"Shell stream: approval gate reached",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,hasSmartModeApproval:void 0!==t.smartModeApproval,hasSmartModeApprovalReason:void 0!==t.smartModeApproval?.reason,hasSmartModeApprovalRequestId:void 0!==t.smartModeApproval?.requestId,requestedPolicyType:s?.type??"undefined",parserCommandCount:d.executableCommands.length,classifierCommandCount:t.classifierResult?.commands.length??0,commandLength:o.length}),Oo(t)){const r=p.policy??s;yM.info(e,"Shell stream: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:s?.type??"undefined",effectivePolicyType:r?.type??"undefined"}),s=r}else{r.awaitingApproval=!0;const n=await this.permissionsService.shouldBlockShellCommand(e,o,{workingDirectory:c,timeout:a,parsingResult:d,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Mo(t),onApprovalRequested:()=>{r.registered.resolve(void 0),r.registered=bM()}},s);if(r.awaitingApproval=!1,"block"===n.kind){if(yM.info(e,"Shell stream: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:n.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),"permissionsConfig"===n.reason.type)return void(yield new fe.FI({event:{case:"permissionDenied",value:new fe.jn({command:o,workingDirectory:c,error:"Command blocked by permissions configuration",isReadonly:n.reason.isReadonly??!1})}}));const r=td(n.reason);return void(yield new fe.FI({event:{case:"rejected",value:new fe.pZ({command:o,workingDirectory:c,reason:r})}}))}s=n.policy,yM.info(e,"Shell stream: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:s.type})}s=await $c(s,{command:o,workingDirectory:c,parsingResult:d,permissionsService:this.permissionsService,ignoreService:this.ignoreService}),yield new fe.FI({event:{case:"start",value:new fe.tD({sandboxPolicy:hs(s)})}});const f=t.timeoutBehavior===fe._d.BACKGROUND,m=f&&!t.closeStdin&&void 0===t.smartModeApproval,g=new AbortController,w=f?g.signal:e.signal?AbortSignal.any([e.signal,g.signal]):g.signal,y=!0,v=s?{perUser:s}:void 0,b=this.coreExecutor.execute(e,{command:o,workingDirectory:i,signal:w,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:v,fileOutputThresholdBytes:t.fileOutputThresholdBytes,pipeStdin:m,showElapsedTime:y});let S;f||(S=setTimeout((()=>g.abort()),a));const k=f?new vM(b[Symbol.asyncIterator](),a):null;let _,C,E,x="",P=!1,R=!1;const I=t.toolCallId&&k?{requestBackground:()=>{if(k.requestBackground())return E=E??this.backgroundShellManager.generateShellId(),new fe.W4({result:{case:"success",value:new fe.QR({shellId:E,pid:C,command:o,workingDirectory:c,msToWait:Oy(performance.now()-u),backgroundReason:fe.Jg.USER_REQUEST,interleavedOutput:x})}})}}:void 0;t.toolCallId&&I&&this.activeForegroundExecutions.set(t.toolCallId,I),this.settle(t.toolCallId,r,I);const T=()=>{t.toolCallId&&this.activeForegroundExecutions.get(t.toolCallId)===I&&this.activeForegroundExecutions.delete(t.toolCallId)},A=()=>{k&&!k.backgroundRequested&&(g.abort(),k.abort())};let $;k&&e.signal&&(e.signal.aborted?A():e.signal.addEventListener("abort",A,{once:!0}));const M=t.hardTimeout;void 0!==M&&M>0&&($=setTimeout((()=>{void 0!==E?this.backgroundShellManager.abort(E)||g.abort():(P=!0,g.abort(),k?.abort())}),M));const O=k?.iterate()??b;try{for await(const r of O)if("stdout"===r.type)x+=r.data,yield new fe.FI({event:{case:"stdout",value:new fe.o0({data:r.data})}});else if("stderr"===r.type)x+=r.data,yield new fe.FI({event:{case:"stderr",value:new fe.Db({data:r.data})}});else if("stdin_ready"===r.type)_=r.stdin,C=r.pid;else if("exit"===r.type){let n;R=!0,r.aborted&&(n=e.signal?.aborted?fe.Lv.USER_ABORT:k?.timedOut||g.signal.aborted?fe.Lv.TIMEOUT:fe.Lv.USER_ABORT),yield new fe.FI({event:{case:"exit",value:new fe.vb({code:(r.code??-1)>>>0,cwd:await this.coreExecutor.getCwd(t.conversationId),outputLocation:r.outputLocation,aborted:r.aborted,abortReason:n,localExecutionTimeMs:Oy(r.localExecutionTimeMs)})}})}}catch(r){if(!(r instanceof No.SandboxUnsupportedError))throw r;const n=s?.type??"unknown";return yM.debug(e,"Shell stream: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:n,reason:r.reason}),void(yield new fe.FI({event:{case:"sandboxUnsupported",value:new fe.rI({command:o,workingDirectory:c,sandboxPolicyType:n,reason:r.reason??r.message,isReadonly:"workspace_readonly"===n})}}))}finally{clearTimeout(S),k?.backgroundRequested||clearTimeout($),T(),!k||k.backgroundRequested||R||g.abort(),e.signal?.removeEventListener("abort",A)}if(k?.backgroundRequested&&!P){const r=E??this.backgroundShellManager.generateShellId();E=r;const n=k.backgroundReasonValue===fe.Jg.USER_REQUEST?fe.Jg.USER_REQUEST:fe.Jg.TIMEOUT,s=n===fe.Jg.USER_REQUEST?Math.round(performance.now()-u):a;await this.backgroundShellManager.adopt({ctx:e,shellId:r,command:o,workingDirectory:c,toolCallId:t.toolCallId,sandboxPolicy:v,initialOutput:x,stdin:_,pid:C,abortController:g,eventIterator:k.getHandoffIterator(),startTime:l,monotonicStartMs:u,showElapsedTime:y,description:t.description,outputNotification:t.outputNotification,onCleanup:()=>clearTimeout($)}),yield new fe.FI({event:{case:"backgrounded",value:new fe.Y9({shellId:r,command:o,workingDirectory:c,pid:C,msToWait:y?s:void 0,reason:n})}})}else e.signal?.aborted&&void 0!==k?.stopReasonValue?(clearTimeout($),yield new fe.FI({event:{case:"exit",value:new fe.vb({code:4294967295,cwd:await this.coreExecutor.getCwd(t.conversationId),aborted:!0,abortReason:fe.Lv.USER_ABORT})}})):clearTimeout($)}catch(e){n.error=e,n.hasError=!0}finally{wM(n)}}}const kM={kind:"absent"};class _M{constructor(e){this.cells=new Map,this.takenCells=new WeakMap,this.collectedCells=new FinalizationRegistry((e=>{void 0===this.cells.get(e)?.deref()&&this.cells.delete(e)})),this.claims=new Map,this.nextGeneration=0,this.entries=new Po.q({max:1e3,ttl:6e4,ttlResolution:0,perf:e})}begin(e){this.entries.purgeStale();const t=++this.nextGeneration;return this.claims.set(TM(e),t),t}record(e,t,r){if(!this.claim(e,r))return;const n=TM(e);this.entries.set(n,{recorded:t,generation:r}),this.commitGeneration(n,r)}forget(e,t){if(!this.claim(e,t))return;const r=TM(e);this.entries.delete(r),this.commitGeneration(r,t)}end(e,t){this.claim(e,t)}take(e){const t=TM(e),r=this.entries.get(t);if(void 0===r)return;const n=this.entries.getRemainingTTL(t);this.entries.delete(t);let o=this.cells.get(t)?.deref();void 0===o&&(o={committed:r.generation},this.cells.set(t,new WeakRef(o)),this.collectedCells.register(o,t));const s={read:e,recorded:r.recorded,remainingTtlMs:n,generation:r.generation};return this.takenCells.set(s,o),s}restore(e){const t=this.takenCells.get(e);if(void 0===t||t.committed!==e.generation)return;const r=TM(e.read);this.entries.has(r)||!Number.isFinite(e.remainingTtlMs)||e.remainingTtlMs<=0||this.entries.set(r,{recorded:e.recorded,generation:e.generation},{ttl:e.remainingTtlMs})}commitGeneration(e,t){const r=this.cells.get(e)?.deref();void 0!==r&&(r.committed=t)}claim(e,t){const r=TM(e);return this.claims.get(r)===t&&(this.claims.delete(r),!0)}}class CM{constructor(){this.views=new Po.q({max:1e3})}get(e){return this.views.get(e)}set(e,t){this.views.set(e,t)}forget(e){this.views.delete(e)}recordWrite(e,t){if(t.length>Ks)return void this.views.delete(e);const r=(0,ko.createHash)("sha256").update(t).digest("hex");this.views.set(e,{kind:"fingerprint",byteLength:t.length,sha256:r})}recordDelete(e){this.views.set(e,kM)}}async function EM(e,t){if(void 0===e)return!1;try{if("absent"===e.kind)return await IM(t);const r=await RM(t);return void 0===r||r.byteLength!==e.byteLength||r.sha256!==e.sha256}catch{return!1}}async function xM(e,t){if("fingerprint"!==e?.kind)return!1;try{return!await IM(t)}catch{return!1}}class PM{constructor(e,t,r,n,o){this.inner=e,this.reads=t,this.permissionsService=r,this.workspacePath=n,this.views=o}async execute(e,t,r){const n=!0===r?.recordAgentView?(0,ts.o1)(t.path,this.workspacePath):void 0,o=function(e,t){if(""!==e.toolCallId&&void 0===e.offset&&void 0===e.limit)return{toolCallId:e.toolCallId,resolvedPath:(0,ts.o1)(e.path,t)}}(t,this.workspacePath);if(void 0===o){const o=await this.inner.execute(e,t,r);return this.forgetViewReadPast(n,o),o}const s=this.reads.begin(o);try{let i,a;try{i=await Yk(this.permissionsService,o.resolvedPath)}catch{return await this.readAndForget(e,t,r,o,s,n)}if(!1!==i&&"needsApproval"!==i.type)return await this.readAndForget(e,t,r,o,s,n);if(!1!==i){const i=await this.inner.execute(e,t,r),a=await async function(e,t){if("success"===e.result.case&&"content"===e.result.value.output.case)try{return await RM(t)}catch{return}}(i,o.resolvedPath);return this.commit(o,s,i,a,n),i}try{a=await RM(o.resolvedPath)}catch{return await this.readAndForget(e,t,r,o,s,n)}const c=await this.inner.execute(e,t,r);return this.commit(o,s,c,a,n),c}finally{this.reads.end(o,s)}}commit(e,t,r,n,o){let s;if("fileNotFound"===r.result.case?s=kM:void 0!==n&&"success"===r.result.case&&"content"===r.result.value.output.case&&(s={kind:"fingerprint",...n}),void 0===s)return this.reads.forget(e,t),void this.forgetViewReadPast(o,r);this.reads.record(e,s,t),void 0!==o&&this.views?.set(o,s)}async readAndForget(e,t,r,n,o,s){const i=await this.inner.execute(e,t,r);return this.reads.forget(n,o),this.forgetViewReadPast(s,i),i}forgetViewReadPast(e,t){void 0===e||"success"!==t.result.case&&"fileNotFound"!==t.result.case||this.views?.forget(e)}}async function RM(e){try{const t=await(0,xo.stat)(e);if(!t.isFile()||t.size>Ks)return}catch(e){return AM(e)}let t;try{t=await(0,xo.open)(e,function(){const e=Ro.constants;return e.O_RDONLY|(e.O_NONBLOCK??0)}());const r=await t.stat();if(!r.isFile()||r.size>Ks)return;const n=(0,ko.createHash)("sha256");let o=0;const s=Buffer.alloc(65536);for(;o<=Ks;){const{bytesRead:e}=await t.read(s,0,s.length,o);if(0===e)break;o+=e,n.update(s.subarray(0,e))}if(o>Ks)return;return{byteLength:o,sha256:n.digest("hex")}}catch(e){return AM(e)}finally{await(t?.close())}}async function IM(e){try{return await(0,xo.stat)(e),!0}catch(e){if($M(e))return!1;throw e}}function TM({toolCallId:e,resolvedPath:t}){return`${e}\0${t}`}function AM(e){if(!$M(e))throw e}function $M(e){const t=_c(e);return"ENOENT"===t||"ENOTDIR"===t}var MM=r("../proto/dist/generated/agent/v1/web_fetch_allowlist_precheck_exec_pb.js");class DM{constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isWebFetchFullyAllowlisted(e,{url:t.url});return new MM.M({allowlisted:r})}}var OM=r("node:constants");const FM=[".md",".markdown",".mdown",".mkd",".mkdn",".mdx"];function NM(e){const t=e.trim().toLowerCase();return FM.some((e=>t.endsWith(e)))}function LM(e,t){const r=e.trim().toLowerCase().split("win32"===t?/[\\/]/:"/");if(r.some((e=>"."===e||".."===e)))return!1;const[n,o,s,i,a]=r.slice(-5);return r.length>=5&&".cursor"===n&&"projects"===o&&void 0!==s&&""!==s&&"canvases"===i&&void 0!==a&&a.length>11&&a.endsWith(".canvas.tsx")}const jM="win32"===process.platform;process.platform;const UM="\\"===s.sep?"win32":"posix",BM={allowed:!1};class WM extends Error{constructor(e,t){super(t),this.name="SymlinkRefusedError",this.path=e}}function HM(e,{nonBlocking:t}){const r=Ro.constants;let n=e;return"number"==typeof r.O_NOFOLLOW&&(n|=r.O_NOFOLLOW),t&&"number"==typeof r.O_NONBLOCK&&(n|=r.O_NONBLOCK),"number"==typeof r.O_CLOEXEC&&(n|=r.O_CLOEXEC),n}const qM=[20,40,80],zM=new Set(["UNKNOWN","EBUSY"]);async function GM(e,t){try{const[r,n]=await Promise.all([t.stat({bigint:!0}),(0,xo.lstat)(e,{bigint:!0})]);r.dev===n.dev&&r.ino===n.ino&&await(0,xo.unlink)(e)}catch{}}async function VM(e,t,r,{removeOnRefusal:n=!1}={}){let o;try{o=await async function(e,t){try{return await(0,xo.open)(e,HM(t,{nonBlocking:!0}),438)}catch(r){const n=_c(r);if(("EAGAIN"===n||"EWOULDBLOCK"===n)&&await async function(e){try{return(await(0,xo.lstat)(e)).isFile()}catch{return!1}}(e))return await(0,xo.open)(e,HM(t,{nonBlocking:!1}),438);throw r}}(e,t)}catch(t){if(function(e){const t=_c(e);return"ELOOP"===t||"EMLINK"===t||"EPERM"===t&&"number"==typeof Ro.constants.O_NOFOLLOW}(t))throw new WM(e,`Refusing to ${r} through a symlink at ${e}`);throw t}try{let t;try{t=(0,Ro.realpathSync)(e)}catch{throw new WM(e,`Cannot verify canonical path before ${r}: ${e}`)}if(t!==e)throw new WM(e,`Refusing ${r}: ${e} now resolves through a symlinked parent to ${t}`);const n=await o.stat();if(!n.isFile())throw new WM(e,`Refusing to ${r} non-regular file at ${e}`);return{fd:o,stats:n}}catch(t){throw n&&await GM(e,o),await o.close(),t}}var KM=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const JM=(0,d.h)("LocalWriteExecutor"),ZM=(0,h.Pu)("local_exec.write.encoding_check",{description:"Text writes that landed, per encoding detector (mojibake, U+FFFD): whether the written text holds the pattern and holds more of it than the file did, and for a detection what the file held, its extension family, encoding and the machine's Windows code page",labelNames:["detector","outcome","file","ext","encoding","code_page","run_count","delta","before_count","pattern"]}),XM=async(e,t,r,n)=>{const o=setTimeout((()=>{JM.warn(e,`[watchdog, LocalWriteExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function QM(e){return new Error(`Could not create ${e}: directory creation exceeded the path depth and was stopped.`)}async function YM(e){try{return(await(0,xo.stat)(e)).isDirectory()?"directory":"present"}catch(e){if("ENOENT"===_c(e))return"missing";throw e}}async function eD(e,t){const r=[];let n=e;for(let o=0;o<=t;o+=1){const t=await YM(n);if("directory"===t)return r.reverse(),r;if("present"===t)return await(0,xo.mkdir)(n,{recursive:!1}),r.reverse(),r;r.push(n);const o=(0,s.dirname)(n);if(o===n){const t=new Error(`ENOENT: no such file or directory, mkdir '${e}'`);throw t.code="ENOENT",t.syscall="mkdir",t.path=e,t}n=o}throw QM(e)}class tD{constructor(e,t,r,{workspacePaths:n,workspacePath:o,worktreeMainPath:s,projectDir:i,onWriteForAiTracking:a,writeFileMutationGuard:c,toolCallReads:l,agentFileViews:u}){this.fileChangeTracker=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.workspacePaths=n,this.workspacePath=o,this.worktreeMainPath=s,this.projectDir=i,this.onWriteForAiTracking=a,this.writeFileMutationGuard=c,this.toolCallReads=l,this.agentFileViews=u}async execute(e,t,r){if(function(e){if(!e.startsWith("file://"))return!1;try{return(0,Pd.fileURLToPath)(e),!1}catch{return!0}}(t.path))return new FI.v3({result:{case:"error",value:new FI.QM({path:t.path,error:`${t.path} is not a valid file URL. Use an absolute path instead.`})}});const n=(0,ts.o1)(t.path,this.workspacePath),o=this.toolCallReads,s=void 0!==o&&""!==t.toolCallId?o.take({toolCallId:t.toolCallId,resolvedPath:n}):void 0,i=!0===r?.refuseUnreadChanges?this.agentFileViews?.get(n):void 0,a={writeStarted:!1},c=()=>{void 0===s||a.writeStarted||o?.restore(s)};try{const r=await this.executeWithRecord(e,t,n,s?.recorded,i,a);return oD(r)&&c(),r}catch(e){throw c(),e}}async executeWithRecord(e,t,r,n,o,i){const a={stack:[],error:void 0,hasError:!1};try{const c=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(a,(0,D.VI)(e.withName("LocalWriteExecutor.execute")),!1).ctx,l=(t.path,t.fileText),u=t.fileBytes.length>0?t.fileBytes:void 0,d=["assets","agent-tools","swarm-agents"],h=SS(r,d)||void 0!==this.projectDir&&!this.workspacePaths.some((e=>{return t=e,n=r,jM&&(t=t.toLowerCase(),n=n.toLowerCase()),t===n||(t.charAt(t.length-1)!==s.sep&&(t+=s.sep),n.startsWith(t));var t,n}))&&kS(this.projectDir,r,d);if((0,ts.fl)({targetPath:r,workspacePaths:this.workspacePaths,mainWorktreePath:this.worktreeMainPath}))return new FI.v3({result:{case:"error",value:new FI.QM({path:r,error:ts.PS})}});let p,f,m,g,w=!1;try{const e=await(0,xo.stat)(r);if(g=511&e.mode,e.size<=ss){const e=await XM(c,"readText before write",3e3,(()=>Wi(r,t.encodingHint)));p=e.text,f=e.encoding,m=Hw(e)}else w=!0}catch(e){w="ENOENT"!==_c(e)}const y=await NS(r),v=y.resolvedPath;if(t.confineToWorkspace){let e=(await Promise.all(this.workspacePaths.map((e=>(0,xo.realpath)(e).catch((()=>{})))))).filter((e=>void 0!==e));if(0===e.length&&void 0!==this.projectDir){const t=await(0,xo.realpath)(this.projectDir).catch((()=>{}));void 0!==t&&(e=[t])}if(!e.some((e=>(0,ts.BJ)(v,e))))return new FI.v3({result:{case:"error",value:new FI.QM({path:r,error:"downloadPath must stay within the workspace"})}})}const b=async()=>{return await EM(n,v)?qT(r):(t=n,void 0!==(e=o)&&void 0!==t&&e.kind===t.kind&&("absent"===e.kind||"fingerprint"===t.kind&&e.byteLength===t.byteLength&&e.sha256===t.sha256)||!await EM(o,v)?void 0:zT(r));var e,t},S=t.planMode?await XM(c,"checkPlanModeWriteTarget",3e3,(()=>async function(e,t){switch(t.resolution.status){case"resolved":case"newFile":return NM(t.resolvedPath)?{allowed:!0}:await async function(e,t){if(!(LM(t.resolvedPath,UM)||LM(e,UM)&&t.resolvedPath===await async function(e){const t=(0,s.dirname)((0,s.dirname)((0,s.dirname)((0,s.dirname)(e)))),r=await NS(t);if(LS(r.resolution))return(0,s.join)(r.resolvedPath,(0,s.relative)(t,e))}(e)))return BM;if("newFile"===t.resolution.status)return{allowed:!0,singleLink:{kind:"create"}};const r=await async function(e){try{const t=await(0,xo.lstat)(e,{bigint:!0});return t.isFile()&&1n===t.nlink?{kind:"existing",dev:t.dev,ino:t.ino}:void 0}catch{return}}(t.resolvedPath);return void 0===r?BM:{allowed:!0,singleLink:r}}(e,t);case"danglingSymlink":{const e=await async function(e){let t=e;for(let e=0;e<40;e++){let e;try{e=await(0,xo.readlink)(t)}catch(e){const r=_c(e);return"ENOENT"===r||"EINVAL"===r?t:void 0}t=(0,s.resolve)((0,s.dirname)(t),e)}}(t.resolvedPath);return void 0!==e&&NM(e)?{allowed:!0}:BM}case"permissionDenied":case"symlinkLoop":case"unknownError":return BM;default:return t.resolution,BM}}(r,y))):void 0;if(void 0!==S&&!S.allowed)return new FI.v3({result:{case:"rejected",value:new FI.en({path:r,reason:"Cannot edit non markdown files in plan mode"})}});const k=(".cursorignore"===(r.split(s.sep).pop()?.toLowerCase()??"")?{type:"permissionsConfig"}:void 0)??await XM(c,"permissionsService.shouldBlockWrite",3e3,(()=>this.permissionsService.shouldBlockWrite(c,v,l)));if(k){const e=await XM(c,"handleBlockReason",3e3,(()=>ed(k,{onNeedsApproval:async(e,n)=>{const o="fileEdit"!==n?.type||n.isNewFile,s="fileEdit"===n?.type?n.diffString:l,i="fileEdit"===n?.type?n.blockReason:void 0,a=await b();if(void 0!==a)return rD(r,a);const c=await this.pendingDecisionProvider.requestApproval({type:Bw.Write,details:{path:r,reason:e,isNewFile:o,diffString:s,before:p,after:l,blockReason:i},toolCallId:t.toolCallId});return c.approved?null:new FI.v3({result:{case:"rejected",value:new FI.en({path:r,reason:c.reason||""})}})},onUserRejected:e=>new FI.v3({result:{case:"rejected",value:new FI.en({path:r,reason:e||""})}}),onPermissionDenied:(e,t)=>new FI.v3({result:{case:"permissionDenied",value:new FI.U7({path:r,error:e,isReadonly:t?.isReadonly??!1})}})})));if(null!==e)return e}const _=await XM(c,"anotherSpellingRefusal",3e3,(()=>async function(e){const t=(0,s.basename)(e);let r;try{if(!(await(0,xo.stat)(e)).isFile())return;const n=await(0,xo.readdir)((0,s.dirname)(e));if(n.includes(t))return;const o=t.normalize("NFC");if(n.some((e=>e.normalize("NFC")===o)))return;const i=t.toLowerCase(),a=n.filter((e=>e.toLowerCase()===i)),c=o.toLowerCase();r=a.length>0?a:n.filter((e=>e.normalize("NFC").toLowerCase()===c))}catch{return}const n=1===r.length?r[0]:void 0;return void 0===n?`${t} names an existing file that this folder lists under another name, so writing it would replace that file. Nothing was written. List the folder and write the file by its listed name to change it; for a new file, choose a different name.`:`${t} names the existing file ${n}: this volume does not tell names apart by case, so writing it would replace ${n}. Nothing was written. To change that file, write ${n}; for a new file, choose a name no file in this folder has in any case.`}(r)));if(void 0!==_)return new FI.v3({result:{case:"error",value:new FI.QM({path:r,error:_})}});const C=(0,s.dirname)(v);if(await xM(n,C))return rD(r,qT(r));if(await xM(o,C))return rD(r,zT(r));let E,x,P,R;try{E=await XM(c,"mkdir",3e3,(()=>async function(e){const t=function(e){let t=0,r=e;for(;;){const e=(0,s.dirname)(r);if(e===r)return t;t+=1,r=e}}(e),r=t+4;let n=0,o=0,i=await eD(e,t),a=0;for(;ar)throw QM(e);try{await(0,xo.mkdir)(c,{recursive:!1})}catch(r){const n=_c(r);if("EEXIST"===n){if("directory"!==await YM(c))throw r;a+=1;continue}if("ENOENT"===n){const n=(0,s.dirname)(c);if(n===c||"missing"!==await YM(n))throw r;i=await eD(e,t),a=0,o=0;continue}throw r}o+=1,a+=1}return o}(C)))}catch(e){const t=_c(e);return"EACCES"===t||"EPERM"===t?new FI.v3({result:{case:"permissionDenied",value:new FI.U7({path:r,directory:C,operation:"create_directory",error:"Permission denied"})}}):new FI.v3({result:{case:"error",value:new FI.QM({path:r,error:Cc(e)})}})}if(void 0!==u)x=u,P=0;else{const e=await XM(c,"getBufferForWrite",3e3,(()=>qi(r,l,this.workspacePath,t.encodingHint)));x=e.buffer,P=e.lines,R=e.format.encoding}const I=()=>XM(c,"writeFile",3e3,(async()=>{const e=await b();if(void 0!==e)throw new Error(e);let t;c.signal.throwIfAborted(),i.writeStarted=!0,await async function(e,t,r){const n=r?.singleLink,{fd:o}=void 0===n?await VM(e,Ro.constants.O_WRONLY|Ro.constants.O_CREAT,"write"):await async function(e,t){const r="create"===t.kind,n=r?Ro.constants.O_WRONLY|Ro.constants.O_CREAT|Ro.constants.O_EXCL:Ro.constants.O_WRONLY;let o;try{o=await VM(e,n,"write",{removeOnRefusal:r})}catch(t){const r=_c(t);if("EEXIST"===r||"ENOENT"===r)throw new WM(e,`Refusing to write: ${e} was ${"EEXIST"===r?"created":"removed"} after it was checked`);throw t}const{fd:s}=o;try{const r=await s.stat({bigint:!0});if(1n!==r.nlink)throw new WM(e,`Refusing to write: ${e} has ${r.nlink} hard links`);if("existing"===t.kind&&(r.dev!==t.dev||r.ino!==t.ino))throw new WM(e,`Refusing to write: ${e} was replaced after it was checked`);return o}catch(t){throw r&&await GM(e,s),await s.close(),t}}(e,n);try{await async function(e){for(let t=0;;t++)try{return void await e.truncate(0)}catch(e){const r=_c(e);if(t>=qM.length||void 0===r||!zM.has(r))throw e;await(0,Lg.setTimeout)(qM[t])}}(o);const e=function(e){return Buffer.isBuffer(e)?e:Buffer.from(e)}(t);let n=0;for(;n{try{await I()}catch(e){throw T=e,A=!0,e}};try{void 0===this.writeFileMutationGuard?await I():await this.writeFileMutationGuard.runExclusive(v,$)}catch(e){if(void 0!==this.writeFileMutationGuard&&(!A||e!==T))return new FI.v3({result:{case:"error",value:new FI.QM({path:r,error:e instanceof Error?e.message:String(e)})}});if(e instanceof WM)return new FI.v3({result:{case:"permissionDenied",value:new FI.U7({path:r,directory:"",operation:"create_file",error:e.message})}});const t=_c(e);return"EACCES"===t||"EPERM"===t?new FI.v3({result:{case:"permissionDenied",value:new FI.U7({path:r,directory:"",operation:"create_file",error:"Permission denied"})}}):"ENOSPC"===_c(e)?new FI.v3({result:{case:"noSpace",value:new FI.bM({path:r})}}):"EDQUOT"===t?new FI.v3({result:{case:"error",value:new FI.QM({path:r,error:"Agent-store quota exceeded: this write was rejected because the storage quota is full. Nothing was written; your local copy is intact. Delete or truncate files to free space (including resolved *.conflict* files), then retry. Do not retry the same write without freeing space first."})}}):new FI.v3({result:{case:"error",value:new FI.QM({path:r,error:Cc(e)})}})}if(this.fileChangeTracker&&void 0===u&&!h&&!w){const e={...t.toolCallId?{toolCallId:t.toolCallId}:{},...v===r?{}:{writtenPath:v},...void 0===g?{}:{beforeMode:g},...E>0?{createdDirectories:E}:{}};await this.fileChangeTracker.trackChange(r,p,l,e,m)}if(this.onWriteForAiTracking&&void 0===u&&!h){const e=t.toolCallId?{toolCallId:t.toolCallId}:{};try{await this.onWriteForAiTracking({path:r,beforeContent:p,afterContent:l,metadata:e})}catch(e){JM.warn(c,"onWriteForAiTracking failed (write succeeded)",{path:r,error:e instanceof Error?e.message:String(e)})}}const M=x.byteLength;let O;if(void 0!==u||w||h||this.recordEncodingChecks(c,r,p,f,l),t.returnFileContentAfterWrite)try{O=await XM(c,"readText after write",3e3,(()=>Bi(r,t.encodingHint)))}catch{}return new FI.v3({result:{case:"success",value:new FI.j6({path:r,linesCreated:P,fileSize:M,...void 0!==O&&{fileContentAfterWrite:O}})}})}catch(e){a.error=e,a.hasError=!0}finally{KM(a)}}recordEncodingChecks(e,t,r,n,o){try{const i={path:t,encoding:n,pages:(s=yu.pages(),"failed"===s?"none":s)};for(const t of function(e,t,r){return[yl(e,t,r),vl(e,t,r)]}(r,n,o))ZM.increment(e,1,El(t,i))}catch(t){for(const t of dl)ZM.increment(e,1,{detector:t,outcome:"error",file:"unclassified"});JM.warn(e,"encoding check failed (write succeeded)",{error:t instanceof Error?t.message:String(t)})}var s}}function rD(e,t){return new FI.v3({result:{case:"error",value:new FI.QM({path:e,error:t})}})}class nD extends Error{constructor(e){super("stale write refusal"),this.result=e,this.name="StaleWriteRefusal"}}function oD(e){if("error"!==e.result.case)return!1;const{error:t,path:r}=e.result.value;return t===qT(r)||t===zT(r)}const sD=(0,d.h)("local-exec:provider"),iD=new Set,aD=new bd.AsyncLocalStorage;class cD extends Z{getMcpExecutionPolicyDeps(){return{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionStore}}static dropOwnedRequestContextCaches(){for(const e of iD)e.ownedRequestContextExecutor?.invalidateGlobalCache()}static rebuildRequestContextCachesFor(e){for(const t of iD)t.cursorRulesService===e&&t.ownedRequestContextExecutor?.refreshGlobalCache()}constructor(e){super(),this.pendingDecisionStore=e.pendingDecisionStore,this.fileChangeTracker=e.fileChangeTracker,this.gitExecutor=e.gitExecutor,this.ignoreService=e.ignoreService,this.grepProvider=e.grepProvider,this.permissionsService=e.permissionsService,this.workspacePaths=e.workspacePaths,this.worktreeMainPath=e.worktreeMainPath,this.diagnosticsProvider=e.diagnosticsProvider,this.mcpLease=e.mcpLease,this.mcpStateAccessor=e.mcpStateAccessor,this.cursorRulesService=e.cursorRulesService,this.cloudRulesService=e.cloudRulesService,this.subagentsService=e.subagentsService,this.repositoryProvider=e.repositoryProvider,this.projectDir=e.projectDir,this.shellManager=e.shellManager,this._sandboxPolicyResolver=e._sandboxPolicyResolver,this._defaultSandboxPolicy=e._defaultSandboxPolicy??{type:"insecure_none"};const t=e.workspacePaths[0],r=t?function(e){const t=(0,s.join)(e,".cursor/sandbox.json");try{const r=(0,Ro.readFileSync)(t,"utf-8"),n=JSON.parse(r),o=(0,No.$6)(n);return(0,No.l7)(o,e)}catch{return}}(t):void 0,n=e._defaultSandboxPolicySources;this._defaultSandboxPolicySources=r||n?{perUser:n?.perUser,perRepo:r??n?.perRepo,teamAdmin:n?.teamAdmin}:void 0,this.mcpFileOutputThresholdBytes=e.mcpFileOutputThresholdBytes,this.blankSharedPaymentTokensInMcpOutputFiles=!0===e.blankSharedPaymentTokensInMcpOutputFiles,this.backgroundShellFactory=e.backgroundShellFactory,this.backgroundWorkRegistry=e.backgroundWorkRegistry,this.wakeupOwnerConversationId=e.wakeupOwnerConversationId,this.mcpElicitationFactory=e.mcpElicitationFactory,this.createFileWatcher=e.createFileWatcher,this.sharedRequestContextExecutor=e.sharedRequestContextExecutor,this.terminalExecutor=e.terminalExecutor,this.mcpMetaToolEnabled=e.mcpMetaToolEnabled??!1,this.mcpMetaToolSlimDescriptors=e.mcpMetaToolSlimDescriptors??!1,this.mcpInputSchemaJson=e.mcpInputSchemaJson??!1,this.alwaysExposeVirtualMcpAuthTool=e.alwaysExposeVirtualMcpAuthTool??!1,this.enableRecordScreen=e.enableRecordScreen??!1,this.recordScreenArtifactsDir=e.recordScreenArtifactsDir,this.recordScreenDisplay=e.recordScreenDisplay,this.disableRecordScreenRendering=e.disableRecordScreenRendering??!1,this.userTerminalHint=e.userTerminalHint,this.attributionConfigProvider=e.attributionConfigProvider,this.isAttributionDisabledByAdmin=e.isAttributionDisabledByAdmin,this.getAgentSkills=e.getAgentSkills,this.getSmartModeClassifierAutoModeEnabled=e.getSmartModeClassifierAutoModeEnabled,this.getAdminCommandDenylist=e.getAdminCommandDenylist,this.devForceNextSmartModeClassifierBlockToken=e.devForceNextSmartModeClassifierBlockToken,this.getMockPromptTime=e.getMockPromptTime,this.additionalRules=e.additionalRules??[],this.askpassConfig=e.askpassConfig,this.rebuildRequestContextOnRulesChange=!0===e.rebuildRequestContextOnRulesChange;const i=this.terminalExecutor??(0,No.Fn)({env:{CURSOR_AGENT:"1"},userTerminalHint:this.userTerminalHint,isLoginShellEnabled:e.isLoginShellEnabled});let a;if(this.workspacePaths.length>1){const e=this.workspacePaths.map((e=>(0,s.dirname)(e)));a=e.every((t=>t===e[0]))?e[0]:void 0}else a=t;let c=new Xu(i,t??(0,o.homedir)(),this.projectDir,{shellOutputBackpressureOptions:e.shellOutputBackpressureOptions,extraEnvProvider:e.shellExtraEnvProvider,powershellUtf8Console:e.powershellUtf8Console,powershellUtf8ChildEnv:e.powershellUtf8ChildEnv,powershellParseAfterUtf8Switch:e.powershellParseAfterUtf8Switch,powershellWebRequestUtf8:e.powershellWebRequestUtf8,powershellPerLineStateDump:e.powershellPerLineStateDump,encodingSlices:e.encodingSlices,keepBackgroundJobs:e.keepShellBackgroundJobs});e.shellCoreWrapper&&(c=e.shellCoreWrapper(c)),this.askpassConfig&&(c=new Yu(c,this.askpassConfig)),this.shellManager&&(c=new Qu(c,this.shellManager));const l=e.overrideShellExecutor??(!0===e.suppressDefaultShellExecutor?void 0:new pM(this.permissionsService,c,this.ignoreService,this.pendingDecisionStore));void 0!==l&&this.register(WT,Fg(l)),this.register(HT,Fg(new BT(this.permissionsService,this.ignoreService,a??t??this.projectDir)));const u=new _M,d=new CM,h=e.overrideWriteExecutor??new tD(this.fileChangeTracker,this.permissionsService,this.pendingDecisionStore,{workspacePaths:this.workspacePaths,workspacePath:a,worktreeMainPath:this.worktreeMainPath,projectDir:this.projectDir,onWriteForAiTracking:e.onWriteForAiTracking,writeFileMutationGuard:e.writeFileMutationGuard,toolCallReads:u,agentFileViews:d});this.register(GT,function(e){const t=(r={execute:(t,r,n)=>e.execute(t,r,n).then((e=>{if(oD(e))throw new nD(e);return e}))},Fg(r));var r;return{async execute(e,r,n){try{return await t.execute(e,r,n)}catch(e){if(e instanceof nD)return e.result;throw e}}}}(h));const p=e.overrideDeleteExecutor??new Gw(this.pendingDecisionStore,this.fileChangeTracker,this.permissionsService,a,e.onDeleteForAiTracking,d);this.register(VT,Fg(p)),this.register(KT,Fg(new Qw({encodingSlices:e.encodingSlices}))),this.register(JT,new P$);const f=this.mcpStateAccessor??new aM(this.mcpLease),m=e.overrideGrepExecutor??new fC(this.ignoreService,this.grepProvider,this.workspacePaths,{mcpStateAccessor:f,permissionsService:this.permissionsService,useStreamingGrep:e.useStreamingGrep,encodingSlices:e.encodingSlices});this.register(ZT,Fg(m));const g=e.overrideReadExecutor??new PM(new B_(this.permissionsService,a,{mcpStateAccessor:f,useStreamingRead:e.useStreamingRead,pendingDecisionProvider:this.pendingDecisionStore,encodingSlices:e.encodingSlices}),u,this.permissionsService,a,d),w=new eA(g);this.register(tA,w),e.registerRedactedReadExecutor&&this.register(rA,w);const y=e.overrideLsExecutor??new SC(this.permissionsService,this.ignoreService,a);this.register(nA,Fg(y)),this.register(oA,Fg(new zA(a,this.diagnosticsProvider))),e.getCanvasDiagnostics&&this.register(sA,Fg(new LA(e.getCanvasDiagnostics,e.beginCanvasSave))),this.register(ro,Fg(new SA(ou(new TT(this.mcpLease,this.permissionsService,this.pendingDecisionStore,this.projectDir,this.mcpFileOutputThresholdBytes,this.mcpElicitationFactory,e.ensureMcpServersLoaded,{blankSharedPaymentTokens:this.blankSharedPaymentTokensInMcpOutputFiles}),e.encodingSlices,"exec_mcp",(e=>"success"===e.result.case)),(()=>this.get(tA))))),this.register(no,Fg(new AT(this.mcpLease,e.ensureMcpServersLoaded))),this.register(oo,Fg(ou(new $T(this.mcpLease,a||this.projectDir,this.permissionsService,this.workspacePaths,this.pendingDecisionStore,e.ensureMcpServersLoaded,h),e.encodingSlices,"exec_mcp",(e=>"success"===e.result.case)))),this.register(so,Fg(new lM(f,e.ensureMcpServersLoaded,{filterToRequestedServers:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,...void 0===e.mcpServerRuleSubjects?{}:{serverRuleSubjects:e.mcpServerRuleSubjects}})));const v=this.sharedRequestContextExecutor??this.createOwnedRequestContextExecutor(f,t,e),b=Fg({execute:(e,t,r)=>{const n=aD.getStore();return void 0!==n&&(n.ran=!0),v.execute(e,t,r)}});this.register(Dr,{execute:async(t,r,n)=>{const o={ran:!1},s=await aD.run(o,(()=>b.execute(t,r,n)));if("success"!==s.result.case||void 0===s.result.value.requestContext)return s;const i=s.clone();if("success"!==i.result.case)return s;const a=i.result.value.requestContext;if(void 0===a)return i;const c=await f.getState(t),l=nM(c,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson});if(a.tools=l.tools,a.mcpInstructions=l.mcpInstructions,a.mcpMetaToolOptions=this.mcpMetaToolEnabled?oM(c,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,slimDescriptors:this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}):void 0,o.ran&&void 0!==e.getMcpFileSystemOptions||(a.mcpFileSystemOptions=await(e.getMcpFileSystemOptions?.(t))),void 0!==a.env&&(a.env.artifactsFolder=e.getArtifactsFolder?.(t),void 0!==e.getSandboxEnabled&&(a.env.sandboxEnabled=e.getSandboxEnabled()),void 0!==e.getSessionSandboxSupported&&(a.env.sandboxSupported=e.getSessionSandboxSupported())),void 0!==e.getMountedAgentStores&&void 0!==a.env)try{const r=await e.getMountedAgentStores(t);a.env.mountedAgentStores=r.map((e=>e.clone()))}catch{a.env.mountedAgentStores=[],sD.warn(t,"Failed to get mounted agent stores; continuing without prompt inventory")}return i}}),this.backgroundShellExecutor=new vd(this.permissionsService,c,this.ignoreService,this.projectDir,this.backgroundShellFactory,this.backgroundWorkRegistry,this.wakeupOwnerConversationId,e.backgroundShellManager),this.shellRedeliveryCaches=e.shellRedeliveryCaches??{backgroundShell:Og(),shellStream:Og(),writeStdin:Og()},this.register(kA,Fg(this.backgroundShellExecutor,void 0,this.shellRedeliveryCaches.backgroundShell)),this.shellStreamExecutor=new SM(this.permissionsService,c,this.ignoreService,this.backgroundShellExecutor.getManager()),this.register(re,function(e,t,r=Og(t)){return{async*execute(t,n,o){if(!o?.execId)return void(yield*e.execute(t,n,o));const s=Dg(o.execId,n),i=r.get(s);if(i)return void(yield*i.fork());const a=e.execute(t,n,o),c=new Mg(a);r.set(s,c),yield*c.fork()}}}(this.shellStreamExecutor,void 0,this.shellRedeliveryCaches.shellStream)),void 0!==e.agentStoreConflictDrainer&&this.register(CA,new DA(e.agentStoreConflictDrainer)),this.register(EA,new mM(this.permissionsService)),this.register(xA,new I$(this.permissionsService)),this.register(PA,new DM(this.permissionsService));const S=new gM(this.shellStreamExecutor);this.register(RA,Fg(S));const k=!1===e.enableWriteBackgroundShellStdin?new OA((async()=>{throw new Error(e.writeBackgroundShellStdinDisabledReason??"write_shell_stdin is disabled for this session")})):new OA(((e,t)=>this.backgroundShellExecutor.writeStdin(e,t)));if(this.register(_A,Fg(k,void 0,this.shellRedeliveryCaches.writeStdin)),e.computerUseExecutor&&(this.computerUseExecutor=e.computerUseExecutor,this.register(IA,Fg(this.computerUseExecutor)),void 0!==e.computerUseEndTurnExecutor&&this.register(TA,e.computerUseEndTurnExecutor)),this.enableRecordScreen){if(!this.recordScreenArtifactsDir||!this.recordScreenDisplay)throw new Error("recordScreenArtifactsDir and recordScreenDisplay are required when enableRecordScreen is true");this.recordScreenExecutor=new j$({artifactsDir:this.recordScreenArtifactsDir,display:this.recordScreenDisplay,disablePolishedRendering:this.disableRecordScreenRendering,polishedRenderer:e.polishedRecordingRenderer}),this.register(AA,Fg(this.recordScreenExecutor))}}createOwnedRequestContextExecutor(e,t,r){const n=new uM(this.cursorRulesService,this.cloudRulesService,this.subagentsService,this.repositoryProvider,this.grepProvider,e,this.gitExecutor,void 0===r.requestContextWorkspacePaths?this.workspacePaths:[...r.requestContextWorkspacePaths],{projectDir:this.projectDir,isWorkingDirHomeDir:r.requestContextIsWorkingDirHomeDir??(0,ts.yn)(t,(0,o.homedir)()),agentNotesEnabled:r.agentNotesEnabled,reportProcessWorkingDirectory:r.reportProcessWorkingDirectory,sectionLoadTimeoutMs:r.requestContextSectionLoadTimeoutMs,reportSectionCompleteness:r.reportRequestContextSectionCompleteness,freshSectionWaitMs:r.requestContextFreshSectionWaitMs,createFileWatcher:this.createFileWatcher,getSandboxEnabled:r.getSandboxEnabled,getSandboxSupported:r.getSandboxSupported,getNetworkAllowlistInfo:r.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:this.getSmartModeClassifierAutoModeEnabled,getAdminCommandDenylist:this.getAdminCommandDenylist,devForceNextSmartModeClassifierBlockToken:this.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:this.getMockPromptTime,userTerminalHint:this.userTerminalHint,getMcpFileSystemOptions:r.getMcpFileSystemOptions,mcpMetaToolEnabled:this.mcpMetaToolEnabled,mcpMetaToolSlimDescriptors:this.mcpMetaToolSlimDescriptors,mcpInputSchemaJson:this.mcpInputSchemaJson,alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,getArtifactsFolder:r.getArtifactsFolder,secretRedactionEnabled:r.secretRedactionEnabled,attributionConfigProvider:this.attributionConfigProvider,isAttributionDisabledByAdmin:this.isAttributionDisabledByAdmin,getAgentSkills:this.getAgentSkills,additionalRules:this.additionalRules,getComputerUseSupported:()=>void 0!==this.computerUseExecutor,getComputerUseDesktop:r.getComputerUseDesktop,onRequestContext:r.onRequestContext,mcpFieldsFromCaller:!0===r.requestContextMcpFieldsFromOverlay,deferWarmup:!0===r.deferRequestContextWarmup});return!0===r.deferRequestContextWarmup&&(this.requestContextExecutorAwaitingWarmup=n),this.rebuildRequestContextOnRulesChange&&(this.ownedRequestContextExecutor=n,iD.add(this),this.disposeRulesChangeListener=this.cursorRulesService.onDidChangeRules?.((()=>{n.rebuildAllCaches()}))),n}warmRequestContext(){const e=this.requestContextExecutorAwaitingWarmup;this.requestContextExecutorAwaitingWarmup=void 0,e?.warm()}getRecordScreenExecutor(){return this.recordScreenExecutor}getBackgroundShellManager(){return this.backgroundShellExecutor.getManager()}getShellRedeliveryCaches(){return this.shellRedeliveryCaches}hasForegroundShells(){return this.shellStreamExecutor.hasForegroundWork()}withPendingShells(e){return new X(e,[K(re,this.shellStreamExecutor.pendingFrom(e))])}async dispose(){this.requestContextExecutorAwaitingWarmup=void 0,this.rebuildRequestContextOnRulesChange&&(iD.delete(this),this.disposeRulesChangeListener?.(),this.disposeRulesChangeListener=void 0,this.ownedRequestContextExecutor?.dispose(),this.ownedRequestContextExecutor=void 0),this.backgroundShellExecutor.dispose(),this.recordScreenExecutor&&await this.recordScreenExecutor.dispose()}}function lD(e){return e.replace(/\\/g,"/")}function uD(e,t){for(const r of t){const t=lD(r);if(e===t||e.startsWith(`${t}/`))return!0}return!1}var dD;function hD(e,t,r){if(function(e){return Boolean(e.plugin?.trim()||e.pluginId?.trim()||e.marketplaceId?.trim())}(e))return dD.Plugin;const n=lD(e.fullPath);return uD(n,r.builtinDirs)?dD.Builtin:Um(e.fullPath,t).inAgentStore?dD.UserStore:uD(n,r.userDirs)?dD.UserHome:(uD(n,r.workspaceDirs),dD.Workspace)}"function"==typeof SuppressedError&&SuppressedError,function(e){e[e.Builtin=0]="Builtin",e[e.UserStore=1]="UserStore",e[e.UserHome=2]="UserHome",e[e.Workspace=3]="Workspace",e[e.Plugin=4]="Plugin"}(dD||(dD={}));var pD=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const fD=(0,Vs.debuglog)("merged-agent-skills"),mD=(0,d.h)("merged-agent-skills");class gD{constructor(e,t=()=>[],r){this.services=e,this.getDisabledManagedSkillPaths=t,this.getPromptSortContext=r,this.onChangeCallbacks=new Set}async getAllAgentSkills(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,D.VI)(e.withName("MergedAgentSkillsService.getAllAgentSkills")),!1),n=this.services.map((e=>e.getAllAgentSkills(r.ctx).catch((e=>(fD("Failed to load agent skills from service: %s",e instanceof Error?e.message:String(e)),[]))))),o=async()=>{try{return{ok:!0,paths:await this.getDisabledManagedSkillPaths()}}catch(e){return mD.warn(r.ctx,"getDisabledManagedSkillPaths failed; failing closed by dropping all managed skills for this call",{error:e instanceof Error?e.message:String(e)}),{ok:!1}}},[i,a]=await Promise.all([Promise.all(n),o()]),c=i.flat(),l=this.getPromptSortContext?.(),u=Wm(c,l??Lm);let d=u;return a.ok?a.paths.length>0&&(d=u.filter((e=>!function(e,t){if(!e)return!1;const r=e.replace(/\\/g,"/");return t.some((e=>r.endsWith(e)))}(e.fullPath,a.paths)))):d=u.filter((e=>{return!((t=e.fullPath)&&t.replace(/\\/g,"/").includes(wD));var t})),void 0!==l?function(e,t){if(e.length<=1)return e;const r=function(e){const t=[bm(e.userHomeDirectory).dirPath],r=Pm(e.userHomeDirectory,!0).map((e=>e.dirPath)),n=[];for(const t of e.workspacePaths){n.push((0,s.join)(t,".cursor","rules"));for(const e of xm(t,!0))n.push(e.dirPath)}return{builtinDirs:t,userDirs:r,workspaceDirs:n}}(t),n=e.map(((e,n)=>({skill:e,index:n,tier:hD(e,t,r)})));return n.sort(((e,t)=>e.tier-t.tier||e.index-t.index)),n.map((e=>e.skill))}(d,l):d}catch(e){t.error=e,t.hasError=!0}finally{pD(t)}}reload(e){for(const t of this.services)t.reload(e)}scheduleDidChangeSkills(){void 0===this.changeTimer&&(this.changeTimer=setTimeout((()=>{this.changeTimer=void 0;for(const e of Array.from(this.onChangeCallbacks))e()}),gD.CHANGE_COALESCE_MS))}ensureChangeListenersRegistered(){void 0===this.disposeChangeListeners&&(this.disposeChangeListeners=this.services.map((e=>e.onDidChangeSkills((()=>this.scheduleDidChangeSkills())))))}disposeChangeListenersIfUnused(){if(!(this.onChangeCallbacks.size>0||void 0===this.disposeChangeListeners)){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0,void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0)}}onDidChangeSkills(e){return this.onChangeCallbacks.add(e),this.ensureChangeListenersRegistered(),()=>{this.onChangeCallbacks.delete(e),this.disposeChangeListenersIfUnused()}}dispose(){if(void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0),this.onChangeCallbacks.clear(),void 0!==this.disposeChangeListeners){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0}for(const e of this.services)e.dispose()}}gD.CHANGE_COALESCE_MS=1500;const wD=`/${mm.configDir}/${mm.subdir}/`;function yD(e,t){if((e.disabledEnvironments??[]).includes(t))return!1;const r=e.environments??[];return 0===r.length||r.includes(t)}const vD=(0,d.h)("skill-sync-manifest"),bD=".sync-manifest.json",SD=new Set(["EPERM","EBUSY"]),kD=[20,50,100],_D=new Map;async function CD(e,t){try{const r=await(0,xo.readFile)((0,s.join)(e,bD),"utf-8"),n=JSON.parse(r);return function(e){if(!function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e))return!1;const t=e;return"number"==typeof t.version&&"object"==typeof t.skills&&null!==t.skills&&!Array.isArray(t.skills)&&(void 0===t.lastInventoryAt||"number"==typeof t.lastInventoryAt)}(n)?n:(vD.warn(t,"Manifest failed schema validation, resetting",{skillDir:e}),{version:1,skills:{}})}catch(r){return r instanceof Error&&"ENOENT"===_c(r)||vD.debug(t,"Failed to read sync manifest, resetting",{skillDir:e,error:String(r)}),{version:1,skills:{}}}}function ED(e,t,r){e.skills[t]={lastSyncedAt:r}}function xD(e,t){delete e.skills[t]}var PD=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const RD=(0,d.h)("builtin-skills-sync");function ID(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function TD(e){for(const t of Object.keys(e.resources??{}))if(0===t.length||t.includes("\\")||t.includes("\0")||s.posix.isAbsolute(t)||s.posix.normalize(t)!==t||t.split("/").includes("..")||"SKILL.md"===s.posix.basename(t)||!t.endsWith(".md"))throw new Error(`Unsafe managed skill resource path: ${JSON.stringify(t)}`)}function AD(e){const t=rh(e.content),r=ID(t.data)?t.data:{};return nh(`${t.content.trim()}\n`,function(e,t){const r={...t??{},name:e.id,description:e.description};delete r.disabledEnvironments,e.disableModelInvocation?r["disable-model-invocation"]=!0:delete r["disable-model-invocation"],e.environments&&e.environments.length>0?r.environments=e.environments:delete r.environments,e.disabledEnvironments&&e.disabledEnvironments.length>0?r["disabled-environments"]=e.disabledEnvironments:delete r["disabled-environments"];const n={...ID(r.metadata)?r.metadata:{}};return delete n.environments,delete n.disabledEnvironments,delete n["disabled-environments"],Object.keys(n).length>0?r.metadata=n:delete r.metadata,r}(e,r))}async function $D(e,t,r){const n=(0,s.join)(t,r.id),o=(0,s.join)(n,"SKILL.md"),i=r.fileContent,a=Object.keys(r.resources),c=await MD(n);if(a.length>0||c.length>0){const e=new Map([["SKILL.md",i],...Object.entries(r.resources)]),o=new Set(["SKILL.md",...c]);if(o.size===e.size&&[...e.keys()].every((e=>o.has(e)))){let t=!0;for(const[r,o]of e)try{if(await(0,xo.readFile)((0,s.join)(n,...r.split("/")),"utf-8")!==o){t=!1;break}}catch{t=!1;break}if(t)return!1}return await async function(e,t){const r=(0,s.join)(e,t.id),n=await(0,xo.mkdtemp)((0,s.join)(e,`.${t.id}-staging-`)),o=`${n}-backup`;let i=!1;try{await(0,xo.writeFile)((0,s.join)(n,"SKILL.md"),t.fileContent,"utf-8");for(const[e,r]of Object.entries(t.resources)){const t=(0,s.join)(n,...e.split("/"));await(0,xo.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,xo.writeFile)(t,r,"utf-8")}try{await(0,xo.rename)(r,o),i=!0}catch(e){if(!(e instanceof Error)||"ENOENT"!==_c(e))throw e}try{await(0,xo.rename)(n,r)}catch(e){throw i&&(await(0,xo.rename)(o,r),i=!1),e}i&&(await(0,xo.rm)(o,{recursive:!0,force:!0}),i=!1)}finally{await(0,xo.rm)(n,{recursive:!0,force:!0})}}(t,r),!0}try{if(await(0,xo.readFile)(o,"utf-8")===i)return!1}catch(t){t instanceof Error&&"ENOENT"===_c(t)||RD.warn(e,"Unexpected error reading skill file",{skillId:r.id,error:String(t)})}return await(0,xo.mkdir)(n,{recursive:!0}),await(0,xo.writeFile)(o,i,"utf-8"),!0}async function MD(e,t=""){const r=t?(0,s.join)(e,...t.split("/")):e;let n;try{n=await(0,xo.readdir)(r,{withFileTypes:!0})}catch(e){if(e instanceof Error&&"ENOENT"===_c(e))return[];throw e}const o=[];for(const r of n){const n=t?`${t}/${r.name}`:r.name;r.isDirectory()?o.push(...await MD(e,n)):r.isFile()&&r.name.endsWith(".md")&&"SKILL.md"!==n&&o.push(n)}return o}async function DD(e,t){try{return(await(0,xo.readdir)(t,{withFileTypes:!0})).filter((e=>e.isDirectory()&&!e.name.startsWith("."))).map((e=>e.name))}catch(r){return r instanceof Error&&"ENOENT"===_c(r)||RD.warn(e,"Failed to list skills directory, skipping cleanup",{skillDir:t,error:String(r)}),[]}}async function OD(e,t={}){const r={stack:[],error:void 0,hasError:!1};try{const i=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,D.VI)(e.withName("syncBuiltinSkills")),!1).ctx,a=Date.now(),c=t.userHome??(0,o.homedir)(),l=t.skillDir??bm(c).dirPath;await(0,xo.mkdir)(l,{recursive:!0});const[u,d]=await Promise.all([CD(l,i),DD(i,l)]),h=u.lastInventoryAt;(void 0===h||a-h>=864e5)&&(await async function(e,t,r,n){try{const o=await Promise.all(r.map((async e=>{const r=(0,s.join)(t,e),[o,i]=await Promise.all([FD((0,s.join)(r,"SKILL.md")),"canvas"===e?FD((0,s.join)(r,"sdk")):Promise.resolve(!1)]);return{skill_id:e,has_skill_md:o,has_sdk_dir:i,last_synced_at:n.skills[e]?.lastSyncedAt??null}})));RD.info(e,"managed_skills.startup_inventory",{skills_on_disk:o,manifest_present:Object.keys(n.skills).length>0})}catch(t){RD.warn(e,"Failed to emit managed skills startup inventory",{error:String(t)})}}(i,l,d,u),u.lastInventoryAt=a);const p=new Map;for(const e of t.managedSkills??[])(n=e.id)&&n===n.trim()&&!(n.includes("..")||n.includes("/")||n.includes("\\"))?p.set(e.id,e):RD.warn(i,"Skipping managed skill with unsafe id",{skillId:e.id});const f=void 0===t.canvasKit?void 0:km(c,t.canvasKit).dirPath,m=void 0!==f&&await FD((0,s.join)(f,Sm)),g=new Set([...p.keys(),...d,...m?[Sm]:[]]),w=e=>void 0!==f&&e===Sm?f:l,y=e=>void 0!==f&&e===Sm?m:d.includes(e);let v=0,b=0;const S=[];for(const e of g)try{const t=p.get(e),r=u.skills[e],n=r?a-r.lastSyncedAt:0,o=void 0!==r&&n>2592e5,c=void 0!==t&&yD(t,"local"),d=void 0!==t&&!c,h=void 0!==r||y(e),f=w(e);if(t&&!1!==t.enabled&&c)TD(t),f!==l&&await(0,xo.mkdir)(f,{recursive:!0}),await $D(i,f,{id:e,fileContent:AD(t),resources:t.resources??{}})?v++:b++,ED(u,e,a);else if(!1===t?.enabled||d||o){const n=!1===t?.enabled?"enabled_false":d?"environment_ineligible":"grace_expired";await(0,xo.rm)((0,s.join)(f,e),{recursive:!0,force:!0}),xD(u,e),h&&(S.push(e),RD.info(i,"managed_skills.removed",{skill_id:e,reason:n,server_enabled:t?.enabled??null,had_manifest_entry:void 0!==r,last_synced_ms_ago:r?a-r.lastSyncedAt:null}))}else r||ED(u,e,a)}catch(t){RD.warn(i,"Failed to apply skill, will retry next sync",{skillId:e,error:String(t)})}try{await function(e,t){const r=(_D.get(e)??Promise.resolve()).then((()=>async function(e,t){const r=(0,s.join)(e,`${bD}.${process.pid}.${(0,ko.randomBytes)(6).toString("hex")}.tmp`);await(0,xo.mkdir)(e,{recursive:!0});try{await(0,xo.writeFile)(r,JSON.stringify(t,null,2),"utf-8"),await async function(e,t){for(let r=0;;r++)try{return void await(0,xo.rename)(e,t)}catch(e){const t=_c(e),n=kD[r];if(void 0===n||void 0===t||!SD.has(t))throw e;await(0,Nr.cb)(n)}}(r,(0,s.join)(e,bD))}catch(e){throw await(0,xo.rm)(r,{force:!0}).catch((()=>{})),e}}(e,t))),n=r.catch((()=>{}));return _D.set(e,n),n.then((()=>{_D.get(e)===n&&_D.delete(e)})),r}(l,u)}catch(e){!function(e){if(e instanceof Error&&"ENOENT"===_c(e))return!0;const t=String(e);return t.includes("ENOENT")||t.includes("no such file or directory")}(e)?RD.warn(i,"Failed to persist sync manifest",{skillDir:l,error:String(e)}):RD.debug(i,"Skipped persisting sync manifest, path removed concurrently",{skillDir:l,error:String(e)})}return{synced:v,upToDate:b,removed:S}}catch(e){r.error=e,r.hasError=!0}finally{PD(r)}var n}async function FD(e){try{return await(0,xo.stat)(e),!0}catch(e){const t=_c(e);if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}const ND=(0,d.h)("managed-skills-sync");function LD(e,t,r,n,o,s){const i=[],a=e.mcpServers;if(!a)return i;for(const[e,c]of Object.entries(a)){const a=c,l=`plugin-${n}-${e}`,u=e;a.url?i.push({identifier:l,name:u,marketplace:t,marketplaceId:r,pluginName:n,pluginId:o,pluginSource:s,type:"streamableHttp",url:a.url,headers:a.headers,auth:a.auth,tls:a.tls,enabledTools:a.enabledTools,placement:a.placement,projectManaged:!1,pluginManaged:!0}):a.command&&i.push({identifier:l,name:u,marketplace:t,marketplaceId:r,pluginName:n,pluginId:o,pluginSource:s,type:"stdio",command:a.command,args:a.args??[],env:a.env??{},cwd:a.cwd,envFile:a.envFile,enabledTools:a.enabledTools,projectManaged:!1,pluginManaged:!0})}return i}function jD(e){try{const t=new URL(e),r=new URL(t.pathname,t.origin);return r.search=t.search,r.pathname.endsWith("/")&&r.pathname.length>1&&(r.pathname=r.pathname.slice(0,-1)),"/"===r.pathname?r.origin+r.search:r.toString()}catch{return e.toLowerCase().trim()}}class UD{constructor(e){this.pluginsService=e}async getPluginMcpServers(){const e=await this.pluginsService.reload(),t=[];for(const r of e){const e="marketplace"in r.identifier.sourceInfo?r.identifier.sourceInfo.marketplace:void 0,n="marketplaceDbId"in r.identifier.sourceInfo?r.identifier.sourceInfo.marketplaceDbId:void 0,o=r.identifier.sourceInfo.name,s="pluginDbId"in r.identifier.sourceInfo?r.identifier.sourceInfo.pluginDbId:void 0,i=r.mcpConfig;i&&t.push(...LD(i,e,n,o,s,r.identifier.source))}return function(e){const t=[],r=new Set;for(const n of e){if("streamableHttp"!==n.type||!n.url){t.push(n);continue}const e=jD(n.url);r.has(e)||(r.add(e),t.push(n))}return t}(t)}}var BD=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function WD(e,t){return void 0===e?[]:(Array.isArray(e)?e:[e]).map((e=>({...e,userHomeDir:t})))}class HD{constructor(e,t,r,n,o,s){this.workspacePaths=e,this.userHomeDirectory=t,this.getSettings=r,this.marketplaceOptions=n,this.localPluginVariablesLookup=s,this.plugins=[],this._loadFailures=[],this._pluginSetIncomplete=!0,this._retainedFromPreviousLoad=0,this._wasFirstLoad=!0,this.loadedOnce=!1,this._extensionPlugins=new Map,this._extensionPluginOriginalPaths=new Map,this.pluginLogger=o??$p,this.reload()}async getAllEnabledPlugins(){return await this.ensureLoaded(),[...this.plugins]}getLoadFailures(){return[...this._loadFailures]}isPluginSetIncomplete(){return this._pluginSetIncomplete}getLoadDiagnostics(){return{userHomeDirectory:this.userHomeDirectory,pluginsLoaded:this.plugins.length,retainedFromPreviousLoad:this._retainedFromPreviousLoad,wasFirstLoad:this._wasFirstLoad,sourceUnavailable:this._pluginSetIncomplete}}async reload(){return this.loadPromise||(this.loadPromise=this.load().then((async e=>{const t=!this.loadedOnce;let r=[];try{r=await this._reloadExtensionPlugins()}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugins after base load success: ${Cc(e)}`)}const n=e.sourceUnavailable?this._retainPluginsMissingFromPartialLoad(e.plugins):[],o=[...e.plugins,...n],s=new Set(o.map((e=>e.installPath))),i=r.filter((e=>!s.has(e.installPath)));return this.plugins=[...o,...i],e.sourceUnavailable||(this._loadFailures=e.failures),this._pluginSetIncomplete=e.sourceUnavailable,this._retainedFromPreviousLoad=n.length,this._wasFirstLoad=t,this.loadedOnce=!0,this.pluginLogger.log("info",`Plugins reload completed: ${this.plugins.length} plugins loaded (${i.length} extension, ${n.length} retained), ${e.failures.length} failures`),this.plugins})).catch((async e=>{const t=!this.loadedOnce;this.pluginLogger.log("error",`Failed to load plugins: ${e}`),this._pluginSetIncomplete=!0,this._retainedFromPreviousLoad=0,this._wasFirstLoad=t;try{const e=await this._reloadExtensionPlugins(),t=new Set(this.plugins.map((e=>e.installPath)));this.plugins=[...this.plugins,...e.filter((e=>!t.has(e.installPath)))]}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugins after base load failure: ${Cc(e)}`)}return this.loadedOnce=!0,this.plugins})).finally((()=>{this.loadPromise=void 0}))),this.loadPromise}_retainPluginsMissingFromPartialLoad(e){if(!this.loadedOnce)return[];const t=new Set(e.map(im));return this.plugins.filter((e=>"extension"!==e.identifier.source&&void 0===e.loadError&&e.installPath.length>0&&!t.has(im(e))))}async reloadPlugin(e){this.loadPromise&&await this.loadPromise;const t=WD(this.marketplaceOptions,this.userHomeDirectory);if(0===t.length)return;if(!(this.getSettings().loadCursorFirstParty??t.length>0))return;const r=t=>t.pluginDbId===e.pluginDbId,n=e=>"cursor-first-party"===e.identifier.source||"cursor-third-party"===e.identifier.source?e.identifier.sourceInfo:void 0,o=t=>n(t)?.pluginDbId===e.pluginDbId,s=(t,r)=>void 0!==t.pluginDbId?t.pluginDbId===e.pluginDbId:t.pluginName===r?.name&&t.marketplaceName===r?.marketplace;let i,a,c;for(const l of t){let t;try{t=await om({...l,log:l.log??this.pluginLogger,pluginFilter:r})}catch(t){this.pluginLogger.log("error",`reloadPlugin: source load failed for ${e.name}: ${Cc(t)}`);continue}const u=t.plugins.find((e=>o(e)&&void 0===e.loadError));if(void 0!==u){i=u;break}const d=t.plugins.find(o);if(void 0!==d&&void 0===a){const e=n(d);a=d,c=t.failures.find((t=>s(t,e)))}}if(void 0===i){if(void 0!==a){const t=n(a),r={...c??{pluginName:t?.name??e.name,errorMessage:a.loadError??"Plugin load failed",errorType:"unknown",...void 0!==t?.marketplace&&{marketplaceName:t.marketplace}},pluginDbId:e.pluginDbId};this._loadFailures=[...this._loadFailures.filter((e=>!s(e,t))),r]}return}const l=this.plugins.findIndex(o);if(-1===l)this.plugins=[...this.plugins,i];else{const e=[...this.plugins];e[l]=i,this.plugins=e}this.loadedOnce=!0;const u=n(i);return this._loadFailures=this._loadFailures.filter((e=>!s(e,u))),i}async registerExtensionPlugin({path:e,extensionId:t}){const r=(0,s.resolve)(e),n=await(0,xo.realpath)(r);if(!(await(0,xo.stat)(n)).isDirectory())throw new Error(`Extension plugin path is not a directory: ${n}`);const i=o.homedir();if(n.split(s.sep).filter(Boolean).length<3||n===i||"/"===n)throw new Error(`Extension plugin path is too broad (must be a specific subdirectory, not root or home): ${n}`);for(const[e,r]of this._extensionPlugins)if(e!==t&&r.has(n))throw new Error(`Plugin path ${n} is already registered by extension ${e}`);let a=this._extensionPlugins.get(t);if(a||(a=new Map,this._extensionPlugins.set(t,a)),a.has(n))return void this._rememberExtensionPluginOriginalPath({extensionId:t,originalPath:r,canonicalPath:n});const c=(0,s.basename)(n),l=await this._loadExtensionPluginContent(n,t);a.set(n,l),this._rememberExtensionPluginOriginalPath({extensionId:t,originalPath:r,canonicalPath:n}),this.pluginLogger.log("info",`Registered extension plugin: ${c} from ${n} (extension: ${t})`)}async unregisterExtensionPlugin({path:e,extensionId:t}){const r=this._extensionPlugins.get(t);if(!r)return!1;const n=(0,s.resolve)(e);let o;try{o=await(0,xo.realpath)(n)}catch{const e=this._extensionPluginOriginalPaths.get(t);o=e?.get(n)??n}const i=r.delete(o);return 0===r.size?(this._extensionPlugins.delete(t),this._extensionPluginOriginalPaths.delete(t)):i&&this._forgetExtensionPluginOriginalPath(t,o),i&&this.pluginLogger.log("info",`Unregistered extension plugin: ${o} (extension: ${t})`),i}async _loadExtensionPluginContent(e,t){const r=(0,s.basename)(e),n={name:r,localPath:e,extensionId:t},o=await Zf(e,r,{name:r,version:"0.0.0"});return o.displayName&&(n.name=o.displayName),{identifier:{source:"extension",sourceInfo:n},installPath:e,...void 0!==o.displayName&&{displayName:o.displayName},...void 0!==o.description&&{description:o.description},...void 0!==o.authorName&&{authorName:o.authorName},...void 0!==o.logoUrl&&{logoUrl:o.logoUrl},...void 0!==o.version&&{version:o.version},...void 0!==o.homepage&&{homepage:o.homepage},...void 0!==o.repository&&{repository:o.repository},skills:o.skills,rules:o.rules,agents:o.agents,commands:o.commands,mcpConfig:o.mcpConfig??void 0,capabilities:o.capabilities,hooks:o.hooks}}_rememberExtensionPluginOriginalPath(e){let t=this._extensionPluginOriginalPaths.get(e.extensionId);t||(t=new Map,this._extensionPluginOriginalPaths.set(e.extensionId,t)),t.set(e.originalPath,e.canonicalPath)}_forgetExtensionPluginOriginalPath(e,t){const r=this._extensionPluginOriginalPaths.get(e);if(r){for(const[e,n]of r)n===t&&r.delete(e);0===r.size&&this._extensionPluginOriginalPaths.delete(e)}}_getExtensionPluginPaths(){const e=[];for(const[t,r]of this._extensionPlugins)for(const n of r.keys())e.push({canonicalPath:n,extensionId:t});return e}async _reloadExtensionPlugins(){const e=this._getExtensionPluginPaths(),t=[];for(const{canonicalPath:r,extensionId:n}of e)try{const e=await this._loadExtensionPluginContent(r,n),o=this._extensionPlugins.get(n);o&&o.set(r,e),t.push(e)}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugin ${r}: ${Cc(e)}`);const o=this._extensionPlugins.get(n),s=o?.get(r);s&&t.push(s)}return t}async ensureLoaded(){this.loadPromise?await this.loadPromise:this.loadedOnce||await this.reload()}async load(){const e={stack:[],error:void 0,hasError:!1};try{const t=(0,b.q6)().withName("LocalPluginsService.load"),r=(function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(e,(0,D.VI)(t),!1),performance.now()),n=e=>{this.pluginLogger.increment(`local_plugins_service.load.${e}`,1),this.pluginLogger.distribution("local_plugins_service.load.duration",performance.now()-r,{outcome:e})},o=this.getSettings(),i=WD(this.marketplaceOptions,this.userHomeDirectory),a=o.importThirdPartyPlugins,c=o.loadUserLocalPlugins??!0,l=o.loadCursorFirstParty??i.length>0;if(!a&&!l&&!c)return this.pluginLogger.log("info","Skipping plugin loading, cursor 1p, 3p, and user-local plugins are disabled"),{plugins:[],failures:[],sourceUnavailable:!1};this.pluginLogger.increment("local_plugins_service.load.start",1);const u=(e,t)=>{this.pluginLogger.increment("local_plugins_service.load_plugin.error",1),this.pluginLogger.log("error",`Cursor plugin load error ${e.name}@${e.version}: ${t?.message??String(t)}`)};try{const e=await async function(e,t={}){const r=t.log??$p,n=performance.now(),o=t.loadClaude??!0,i=t.loadUserLocal??!0,a=t.marketplaceSources??[],c=t.loadCursorFirstParty??a.length>0,l=[],u=[];let d;o&&l.push(Yf(e,0,{userHomeDir:t.userHomeDir,onError:t.onError,log:r})),c&&a.length>0&&(d=Promise.allSettled(a.map((e=>om({...e,userHomeDir:e.userHomeDir??t.userHomeDir,log:e.log??r}))))),i&&l.push(async function(e={}){const t=e.log??$p,r=performance.now(),n=e.userHomeDir??process.env.HOME;if(!n)return t.log("info","loadUserLocalPlugins: no home directory available, skipping"),[];const o=(0,s.join)(n,".cursor","plugins","local");let i;try{i=await(0,xo.readdir)(o,{withFileTypes:!0})}catch{return t.log("info",`loadUserLocalPlugins: ${o} not found or not readable (${(performance.now()-r).toFixed(1)}ms)`),[]}const a=await(0,xo.realpath)(o).catch((()=>(0,s.resolve)(o))),c=[];for(const r of i){if(!r.isDirectory()&&!r.isSymbolicLink())continue;if(r.name.startsWith("."))continue;const n=(0,s.join)(o,r.name);try{if(r.isSymbolicLink()){let e;try{e=await(0,xo.realpath)(n)}catch(e){t.log("warn",`loadUserLocalPlugin ${r.name} rejected: failed to resolve symlink (${e instanceof Error?e.message:String(e)})`);continue}try{Sf(a,e)}catch{t.log("warn",`loadUserLocalPlugin ${r.name} rejected: symlink target ${e} is outside ${o}`);continue}}if(!(await(0,xo.stat)(n)).isDirectory()){r.isSymbolicLink()&&t.log("warn",`loadUserLocalPlugin ${r.name} rejected: symlink target is not a directory`);continue}const s=performance.now(),i=await(e.localPluginVariablesLookup?.(r.name)),{displayName:l,description:u,authorName:d,logoUrl:h,version:p,homepage:f,repository:m,variablesSchema:g,skills:w,rules:y,agents:v,commands:b,mcpConfig:S,capabilities:k,hooks:_}=await Zf(n,r.name,void 0,{configuredVariables:i,log:t}),C={source:"user-local",sourceInfo:{name:r.name,localPath:n}};c.push({identifier:C,installPath:n,...void 0!==l&&{displayName:l},...void 0!==u&&{description:u},...void 0!==d&&{authorName:d},...void 0!==h&&{logoUrl:h},...void 0!==p&&{version:p},...void 0!==f&&{homepage:f},...void 0!==m&&{repository:m},variablesSchema:g,skills:w,rules:y,agents:v,commands:b,mcpConfig:S??void 0,capabilities:k,hooks:_}),t.log("info",`loadUserLocalPlugin ${r.name} loaded in ${(performance.now()-s).toFixed(1)}ms`)}catch(e){t.log("error",`loadUserLocalPlugin ${r.name} failed: ${e instanceof Error?e.message:String(e)}`)}}return t.log("info",`loadUserLocalPlugins completed in ${(performance.now()-r).toFixed(1)}ms (${c.length} plugins loaded)`),c}({userHomeDir:t.userHomeDir,log:r,localPluginVariablesLookup:t.localPluginVariablesLookup}));const[h,p]=await Promise.all([Promise.allSettled(l),d??Promise.resolve([])]);let f=!1;const m=[];for(const e of p)"rejected"!==e.status?(e.value.sourceUnavailable&&(f=!0),m.push(...e.value.plugins),u.push(...e.value.failures)):(f=!0,r.log("error",`marketplace source threw while loading; treating it as unavailable: ${String(e.reason)}`));for(const e of h)"rejected"!==e.status?m.push(...e.value):(f=!0,r.log("error",`plugin source threw while loading; treating it as unavailable: ${String(e.reason)}`));const g=new Set,w=[];for(const e of m){if(!e.installPath){w.push(e);continue}const t=await(0,xo.realpath)(e.installPath).catch((()=>e.installPath));g.has(t)||(g.add(t),w.push(e))}const y=new Map,v=[];for(const e of w){const t=sm(e);if(void 0!==t){const r=y.get(t),n=!e.loadError;if(!0===r)continue;if(!1===r&&n){const r=v.findIndex((e=>sm(e)===t&&e.loadError));-1!==r&&v.splice(r,1),y.set(t,!0),v.push(e);continue}y.set(t,n)}v.push(e)}const b=performance.now()-n;return r.log("info",`loadAllPlugins completed in ${b.toFixed(1)}ms (claude=${o}, userLocal=${i}, marketplace=${a.length} sources, total=${v.length} plugins, failures=${u.length}, sourceUnavailable=${f})`),{plugins:v,failures:u,sourceUnavailable:f}}(this.workspacePaths,{userHomeDir:this.userHomeDirectory,loadClaude:a,loadUserLocal:c,loadCursorFirstParty:l&&i.length>0,marketplaceSources:i.length>0?i.map((e=>({...e,onCursorError:u}))):void 0,onError:(e,t)=>{this.pluginLogger.log("error",`Claude plugin load error ${e.raw}: ${t?.message??String(t)}`)},log:this.pluginLogger,localPluginVariablesLookup:this.localPluginVariablesLookup});return n("success"),this.pluginLogger.log("info",`Plugins loaded in ${(performance.now()-r).toFixed(1)}ms`),e}catch(e){return n("error"),this.pluginLogger.log("error",`Failed to load all plugins: ${Cc(e)}`),{plugins:[],failures:[],sourceUnavailable:!0}}}catch(t){e.error=t,e.hasError=!0}finally{BD(e)}}}const qD=["parse binary","parse json"],zD=["decompression failed","unsupported response encoding","unsupported content type","protocol error: promised"],GD=new Set([1,4,10,14]),VD=new Set(["AbortError","TimeoutError"]),KD=["ECONN","ENOT","ETIMEDOUT","EPIPE","EAI_","EHOST","ENET","ERR_HTTP2","ERR_SSL","ERR_TLS","UND_ERR","CERT_","DEPTH_ZERO_SELF_SIGNED_CERT","SELF_SIGNED_CERT","UNABLE_TO_"];function JD(e,t){return t.some((t=>e.startsWith(t)))}function ZD(e){if(e instanceof Error&&VD.has(e.name))return!0;const t=function(e){if("object"==typeof e&&null!==e&&"code"in e)return"string"==typeof e.code?e.code:void 0}(e);return void 0!==t&&JD(t,KD)}function XD(e){const t=function(e){if(e instanceof Error&&"ConnectError"===e.name&&"code"in e&&"number"==typeof e.code&&"rawMessage"in e&&"string"==typeof e.rawMessage)return{code:e.code,text:e.rawMessage,cause:e.cause}}(e);if(void 0===t)return ZD(e)?"transport":"other";const{code:r,text:n,cause:o}=t;return JD(n,qD)?"reply_schema":JD(n,zD)?"reply_encoding":n.startsWith("http/2 stream closed with error code")||GD.has(r)||ZD(o)?"transport":"other"}var QD=r("../proto/dist/generated/aiserver/v1/dashboard_pb.js");const YD=BigInt(0),eO=BigInt(8),tO=BigInt(16),rO=BigInt(65535);function nO(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch{return}}function oO(e){let t=e.trim().replace(/\.+$/,"").toLowerCase();if(t.startsWith("[")){const e=t.indexOf("]");-1!==e&&(t=t.slice(1,e))}else if(t.split(":").length-1==1){const e=t.lastIndexOf(":"),r=t.slice(e+1);Array.from(r).every((e=>/\d/.test(e)))&&(t=t.slice(0,e))}return t}function sO(e){const t=e.split(".");if(4!==t.length)return;let r=YD;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<>tO&rO)),t.push(Number(o.value&rO))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function aO(e){return sO(e)??function(e){const t=oO(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=iO(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<7?void 0:{version:6,value:[...n,...new Array(8-s).fill(0),...o].reduce(((e,t)=>e<i)return!1;const a=BigInt(i-s);return o.value>>a==n.value>>a}(r,n);if(n.startsWith("*.")){const e=n.slice(2);return r===e||r.endsWith(`.${e}`)}return r===n}function lO(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}function uO(e,t){if(lO(e,t))return!0;if(e.includes("://")){let r,n;try{r=new URL(e),n=new URL(t)}catch{return!1}if(""!==r.username||""!==r.password||""!==n.username||""!==n.password||r.protocol!==n.protocol||r.port!==n.port)return!1;const o=oO(r.hostname);return!!cO(oO(n.hostname),o)&&lO(`${r.pathname}${r.search}`,`${n.pathname}${n.search}`)}const r=function(e){const t=function(e){const t=e.trim(),r=t.indexOf("["),n=t.indexOf("]");if(-1!==r&&n>r){const e=t.slice(r+1,n);if(t.slice(n+1).startsWith("("))return`${t.slice(0,r)}${e}`}return t}(e).trim();if(0===t.length)return;const r=t.lastIndexOf("/");if(!t.includes("://")&&r>0&&/^\d+$/.test(t.slice(r+1).trim())){const e=oO(t.slice(0,r));if(e.length>0)return`${e}/${t.slice(r+1).trim()}`}const n=nO(t);if(n)return oO(n.hostname);let o=t;const s=o.indexOf("://");-1!==s&&(o=o.slice(s+3));const i=o.indexOf("/");-1!==i&&(o=o.slice(0,i));const a=oO(function(e){if(e.startsWith("[")){const t=e.indexOf("]");return-1!==t?e.slice(1,t):e}const t=e.split(":");return 2===t.length&&Array.from(t[1]??"").every((e=>/\d/.test(e)))?t[0]:e}(o));if(0!==a.length){if(a.startsWith("*.")){const e=a.slice(2);if(0===e.length||e.includes("*")||e.includes("?"))return;return a}if(!a.includes("*")&&!a.includes("?"))return a}}(e),n=function(e){const t=nO(e);if(t)return oO(t.hostname);const r=oO(e);return r.length>0?r:void 0}(t);return!(!r||!n)&&cO(n,r)}async function dO(e){try{return await e.current()}catch{return}}function hO(e){try{const t=new URL(e);return`${t.protocol}//${t.host}${t.pathname}`}catch{return}}function pO({failOpenWhenEmpty:e,server:t,settings:r}){if(!0!==r?.allowedMcpConfiguration?.requireMcpServersInTeamNetworkAllowlist||void 0===t.url)return{blocked:!1};const n=function(e){return!0===e.cloudAgentMcpAllowlistApplied&&!1===e.mirrorSandboxAllowlistForEgress?e.cloudAgentEgressAllowlist??[]:e.networkAllowlist??[]}(r).map((e=>e.trim())).filter((e=>e.length>0));return 0===n.length&&e||Qv(t.url,n)?{blocked:!1}:{blocked:!0,reason:"teamNetworkAllowlist",message:"Not on the team network allowlist"}}function fO(e){const t=e?.trim();return t&&t.length>0?t:void 0}function mO(e,t,r){if(!0===r?.useCorePolicy)return!function(e,t){if(void 0===t)return!0;if(!0===t.disableAll)return!1;if(CC(e))return!0;if(RC(e,t.offMcpServerRules))return!1;const r=t.allowedMcpServers??[];return 0===r.length&&!0!==t.allowUserOverrideMcpServers||!!function(e,t){return t.length>0&&function(e,t){return t.some((t=>{const r=EC(t.command),n=xC(t.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==e.command&&(0,Lb.mD)(r,e.command),s=void 0===n||void 0!==e.url&&(0,Lb.vc)(n,e.url);return o&&s}))}(e,t)}(e,r)||!0===t.allowUserOverrideMcpServers&&!PC(e,t.deniedMcpServers)}(e,t);if(void 0===t)return!1;if(!0===t.disableAll)return!0;const n=t.allowedMcpServers;return 0!==n.length&&!n.some((t=>function(e,t){const r=fO(e.command),n=fO(e.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==t.command&&function(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}(r,t.command),s=void 0===n||void 0!==t.url&&uO(n,t.url);return o&&s}(t,e)))}class gO{constructor(e,t={}){this.dashboardClient=e,this.options=t}getTeamAdminSettings(){return this.dashboardClient.getTeamAdminSettingsOrEmptyIfNotInTeam(new QD.Byz(!0===this.options.supportsHostMcpBridgeExemption?{supportsHostMcpBridgeExemption:!0}:{}))}getTeamRepos(){return this.dashboardClient.getTeamReposOrEmptyIfNotInTeam(new QD.aYW({}))}}function wO(e,t){if("workspace"!==e)return[];const r=[],n=new Set;for(const e of t??[]){const t=e.trim();0===t.length||n.has(t)||(n.add(t),r.push(t))}return r}class yO{constructor(e){this.fetch=e}get(){const e=this.cached,t=void 0===e?1/0:Date.now()-e.fetchedAt;return void 0===e||t>6e5?(this.cached=void 0,this.refresh()):(t>3e5&&this.refresh().catch((()=>{})),Promise.resolve(e.value))}invalidate(){this.cached=void 0,this.inFlight=void 0}refresh(){if(void 0===this.inFlight){const e=this.fetch().then((t=>(this.inFlight!==e||void 0===t&&void 0!==this.cached||(this.cached={value:t,fetchedAt:Date.now()}),t))).finally((()=>{this.inFlight===e&&(this.inFlight=void 0)}));this.inFlight=e}return this.inFlight}}class vO{constructor(e,t,r={}){this.teamAdminSettingsProvider=e,this.defaultAllowlistProvider=t,this.options=r,this.lastFetchSucceeded=!0,this.lastFetchFailure="other",this.settingsGeneration=0,this.lastFetchedGeneration=0,this.settings=new yO((()=>this.fetchSettings())),this.droppedReplies=new WeakSet,this.hostMcpBridgeClients=new WeakSet,this.mcpServerByClient=new WeakMap,this.teamRepos=new yO((()=>this.teamAdminSettingsProvider.getTeamRepos())),this.defaultAllowlist=new yO((()=>this.fetchDefaultAllowlist())),this.getTeamAdminSettings(),this.prefetchTeamRepos()}async prefetchTeamRepos(){try{await this.teamRepos.get()}catch{}}invalidateCache(){this.settingsGeneration+=1,this.settings.invalidate(),!0!==this.options.preserveTeamReposOnInvalidate&&this.teamRepos.invalidate(),this.defaultAllowlist.invalidate()}invalidateTeamRepos(){this.teamRepos.invalidate()}async refreshTeamAdminSettings(){try{await this.settings.refresh()}catch{}}async fetchSettings(){const{fetchIdentity:e}=this.options;if(void 0!==e)return this.fetchSettingsFor(e);const t=this.settingsGeneration;try{const e=await this.teamAdminSettingsProvider.getTeamAdminSettings();return this.lastFetchSucceeded=!0,t>=this.lastFetchedGeneration&&(this.lastFetchedSettings=e,this.lastFetchedGeneration=t),e}catch(e){throw this.lastFetchSucceeded=!1,this.lastFetchFailure=XD(e),e}}async fetchSettingsFor(e){const t=await dO(e),r=this.settingsGeneration;if(void 0===t)throw this.lastFetchSucceeded=!1,this.lastFetchFailure="other",new Error("No one is named whose team settings a fetch would read");try{const e=await this.teamAdminSettingsProvider.getTeamAdminSettings();return void 0!==e&&this.droppedReplies.delete(e),this.isSentFor(e,t)?(this.lastFetchSucceeded=!0,r>=this.lastFetchedGeneration&&(this.lastFetchedSettings=e,this.lastFetchedGeneration=r),e):e}catch(e){throw this.lastFetchSucceeded=!1,this.lastFetchFailure=XD(e),e}}getTeamAdminSettings(){const{fetchIdentity:e}=this.options;return void 0!==e?this.getTeamAdminSettingsFor(e):this.settings.get().catch((()=>{}))}async getTeamAdminSettingsFor(e){const t=await this.settings.get().catch((()=>{})),r=await dO(e);if(void 0===t)return void(this.isSentFor(this.lastFetchedSettings,r)||(this.settingsGeneration+=1));if(void 0===r)return this.answerAsFailedRead();if(this.isSentFor(t,r))return t;let n=t,o=r;const s=await this.settings.get().catch((()=>{}));if(s!==t){if(void 0===s)return this.answerAsFailedRead();if(this.isSentFor(s,r))return s;if(o=await dO(e),void 0===o)return this.answerAsFailedRead();if(this.isSentFor(s,o))return s;n=s}this.droppedReplies.has(n)||(this.droppedReplies.add(n),this.settingsGeneration+=1,this.settings.invalidate());const i=await this.settings.get().catch((()=>{}));return void 0!==i?this.isSentFor(i,r)||this.isSentFor(i,o)||this.isSentFor(i,await dO(e))?i:this.answerAsFailedRead():void 0}answerAsFailedRead(){this.settingsGeneration+=1,this.lastFetchSucceeded=!1,this.lastFetchFailure="other"}isSentFor(e,t){return void 0!==e&&void 0!==t&&this.options.fetchIdentity?.sentFor(e)===t}async getDotCursorProtection(){const e=await this.getTeamAdminSettings();return e?.dotCursorProtection??!0}async getShouldBlockMcp(){const e=await this.getTeamAdminSettings();return!(!e?.autoRunControls?.enabled||!e?.autoRunControls?.disableMcpAutoRun)}async getDeleteFileProtection(){const e=await this.getTeamAdminSettings();return!(!e?.autoRunControls?.enabled||!e?.autoRunControls?.deleteFileProtection)}async getIsHeadlessDisabled(){return"disabled"===(await this.getHeadlessCliPolicy()).kind}async getHeadlessCliPolicy(){const e=await this.getTeamAdminSettings();return void 0!==e||this.lastFetchSucceeded?!0===e?.cliSettings?.disableHeadless?{kind:"disabled"}:{kind:"enabled"}:{kind:"unavailable"}}async getMcpServerBlockInfo(e){const t=await this.getTeamAdminSettings(),r=t?.allowedMcpConfiguration,n=await this.isMcpSettingsOverhaulEnabled({disableExposureLog:!0});if(!0===r?.disableAll)return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};if(this.isHostMcpBridge(t,e))return{blocked:!1,hostMcpBridge:!0};if(RC(e,r?.offMcpServerRules))return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};if(n){if(mO(e,r,{useCorePolicy:!0}))return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};const n=await this.getMcpNetworkControlsConfig(e),o=void 0===e.url?{allowed:!0}:(0,Lb.ME)(e.url,n);if(!o.allowed)return{blocked:!0,reason:"teamNetworkAllowlist",message:o.message};const s=pO({failOpenWhenEmpty:!1,server:e,settings:t});if(s.blocked)return s}if(!n){const r=function({isMcpAccessNetworkAllowlistEnabled:e,server:t,settings:r}){return e&&!0===r?.allowedMcpConfiguration?.requireMcpServersInTeamNetworkAllowlist?pO({failOpenWhenEmpty:!0,server:t,settings:r}):{blocked:!1}}({isMcpAccessNetworkAllowlistEnabled:await this.isMcpAccessNetworkAllowlistEnabled(),server:e,settings:t});if(r.blocked)return r}return void 0!==t||this.lastFetchSucceeded?{blocked:!1}:{blocked:!1,settingsUnavailable:!0}}async getManagedSlackWorkspaceLists(){const e=await this.getTeamAdminSettings()??this.lastFetchedSettings;return void 0===e?[]:function(e){return e.memberSlackManagedWorkspacesUnreadable?"unconfirmed":e.memberSlackManagedWorkspaces.map((e=>e.slackTeamIds)).filter((e=>e.length>0))}(e)}async getMcpNetworkControlsConfig(e){const t=await this.getTeamAdminSettings(),r=t?.allowedMcpConfiguration;if(await this.isMcpSettingsOverhaulEnabled()&&(void 0===e||!this.isHostMcpBridge(t,e))){const n="win32"===process.platform&&await this.isWin32UserExtensionStdioUnsandboxEnabled();return(0,Lb._N)({allowedMcpConfiguration:r,server:e,localAgentNetworkAllowlist:t?.networkAllowlist,blockMessage:"Not on the team network allowlist",aggregateManagedServerNetworkAllowlists:!1,stdioPlatform:process.platform,unsandboxUserExtensionStdio:n})}return{enabled:!1,localAgentNetworkAllowlist:t?.networkAllowlist,blockMessage:"Not on the team network allowlist"}}isHostMcpBridge(e,t){const r=this.options.hostMcpBridgeUrls;if(!0!==e?.cloudAgentMcpAllowlistApplied||void 0===r||void 0!==t.command||void 0===t.url)return!1;const n=hO(t.url);return void 0!==n&&r.some((e=>hO(e)===n))}recordHostMcpBridgeClient(e){this.hostMcpBridgeClients.add(e)}async isHostMcpBridgeClient(e){if(!this.hostMcpBridgeClients.has(e))return!1;const t=await this.getTeamAdminSettings();return!0===t?.cloudAgentMcpAllowlistApplied&&!0!==t.allowedMcpConfiguration?.disableAll}recordMcpServerClient(e,t){this.mcpServerByClient.set(e,t)}async getMcpAdminToolLimit(e){if(await this.isHostMcpBridgeClient(e))return{kind:"none"};const t=this.mcpServerByClient.get(e);if(void 0===t)return{kind:"unknown_server"};const r=!0===this.options.mcpAdminToolLimitSurvivesFailedRead;let n=await this.getTeamAdminSettings();if(void 0===n&&!this.lastFetchSucceeded&&r&&(n=await this.getTeamAdminSettings()),void 0===n){if(this.lastFetchSucceeded)return{kind:"none"};if(!r)return{kind:"settings_unavailable"};const e=this.lastFetchFailure,t=this.lastFetchedGeneration===this.settingsGeneration?this.lastFetchedSettings:void 0;if(void 0===t)return{kind:"settings_unavailable",failure:e,noLimitApplies:!0};n=t}const o=function(e,t){const r=e?.find((e=>(0,Lb.rM)(e,t)));if(void 0!==r)return Bb({mode:r.toolAllowlistMode,tools:r.toolAllowlist})}(n.allowedMcpConfiguration?.allowedMcpServers,t);return void 0===o?{kind:"none"}:{kind:"limit",policy:o}}async isServerBlocked(e){return(await this.getMcpServerBlockInfo(e)).blocked}async getAutoRunControls(){const e=await this.getTeamAdminSettings();if(e?.autoRunControls?.enabled)return{enabled:e.autoRunControls.enabled,allowed:e.autoRunControls.allowed??[],blocked:e.autoRunControls.blocked??[],enableAllowlistMode:e.autoRunControls.enableAllowlistMode??!0,enableRunEverything:e.autoRunControls.enableRunEverything??!1,enableSmartAuto:e.autoRunControls.enableSmartAuto??!0,mcpToolAllowlist:e.autoRunControls.mcpToolAllowlist??[]}}async isReadControlEnabled(){try{return await(this.options.isReadControlEnabled?.())??!0}catch{return!1}}async isDenylistEnforcementKilled(){try{return!0===await(this.options.isAdminCommandDenylistEnforcementKilled?.())}catch{return!1}}async getAdminCommandDenylist(){if(await this.isDenylistEnforcementKilled())return{rules:[]};const e=await this.getTeamAdminSettings();return{rules:e?.autoRunControls?.adminCommandDenylist?.rules??[]}}async isMcpSettingsOverhaulEnabled(e){const t=this.options.isMcpSettingsOverhaulEnabled?.(e);return void 0!==t&&await t}async isWin32UserExtensionStdioUnsandboxEnabled(){try{const e=this.options.isWin32UserExtensionStdioUnsandboxEnabled?.();return void 0!==e&&await e}catch{return!1}}async getMcpToolControls(){const e=await this.getTeamAdminSettings(),t=e?.allowedMcpConfiguration;if(void 0===t)return;const r=function({autoRunControls:e,allowedMcpServers:t}){const r=!0===e?.enabled?e.mcpToolAllowlist??[]:[],n=function(e){return(e??[]).flatMap((e=>{const t=void 0===e.name?"":jb(e.name);if(0===t.length)return[];const r=Bb({mode:e.toolAllowlistMode,tools:e.toolAllowlist});return[{name:t,policy:r,flattened:Hb(t,r)}]}))}(t);return{tools:(o=[...n.flatMap((e=>[...e.flattened])),...r],[...new Set(o)]),policies:n.map((e=>({name:e.name,policy:e.policy})))};var o}({autoRunControls:e?.autoRunControls,allowedMcpServers:t?.allowedMcpServers});return r.policies.length>0||r.tools.length>0?{enabled:!0,mcpToolAllowlist:r.tools,allowUserOverride:t?.allowUserOverrideMcpServers??!1,serverPolicies:r.policies}:void 0}async getNetworkAccessControls(){const e=await this.getTeamAdminSettings();return void 0!==e||this.lastFetchSucceeded?{allowlist:e?.networkAllowlist??[],denylist:e?.networkDenylist??[],available:!0}:{allowlist:[],denylist:[],available:!1}}async getSandboxingControls(){const e=await this.getTeamAdminSettings(),t=e?.autoRunControls?.sandboxingControls,r=(n=t?.sandboxReadBoundary,n===QD.h0i.WORKSPACE?"workspace":"system");var n;return{sandboxingDisabled:t?.sandboxing===QD.faf.DISABLED,networkingDisabled:t?.sandboxNetworking===QD._mX.ALWAYS_DISABLED,gitDisabled:t?.sandboxGit===QD.i24.ALWAYS_DISABLED,readBoundary:r,readAllowlistPaths:wO(r,t?.sandboxReadAllowlistPaths),allowUserOverrideReadAllowlist:!1!==t?.allowUserOverrideSandboxReadAllowlist}}async isAttributionDisabledByAdmin(){const e=await this.getTeamAdminSettings();return void 0===e&&!this.lastFetchSucceeded||(e?.attributionControls?.disableAttribution??!1)}async isComputerUseDisabledByAdmin(){const e=await this.getTeamAdminSettings();return void 0!==e?!1===e.computerUse:this.lastFetchedGeneration!==this.settingsGeneration||void 0===this.lastFetchedSettings&&!this.lastFetchSucceeded||!1===this.lastFetchedSettings?.computerUse}getDefaultNetworkAllowlist(){return this.defaultAllowlist.get().catch((()=>({allowlist:[],available:!1})))}async fetchDefaultAllowlist(){return this.defaultAllowlistProvider?{allowlist:await this.defaultAllowlistProvider.getDefaultNetworkAllowlist(),available:!0}:{allowlist:[],available:!0}}getTeamRepos(){return this.teamRepos.get()}async isMcpAccessNetworkAllowlistEnabled(){return await(this.options.isMcpAccessNetworkAllowlistEnabled?.())??!1}}const bO=new xy,SO={async resolveWorkspaceState(e){const t=e.workingDirectory??e.projectRoot??e.workspaceRoots?.[0],r=e.projectRoot??(void 0!==t?await tc((0,b.q6)(),bO,t)??t:void 0),n=e.workspaceRoots??(void 0!==r?[r]:void 0!==t?[t]:[]);return{workingDirectory:t,projectRoot:r,projectDirectory:e.projectDirectory??(void 0!==r?Eo(r):void 0),workspaceRoots:n,createdAt:new Date}}},kO=(0,d.h)("ControlledConversationActionManager");class _O{get signal(){return this.abortController.signal}get abortRequested(){return this.abortCalled}constructor(){this.abortCallbacks=[],this.abortController=new AbortController,this.acceptsActions=!0,this.disposed=!1,this.abortStarted=!1,this.abortCalled=!1,this.runActive=!1,this.unprocessedUserMessages=[],this.clientStream=(0,f.Jt)()}addAbortCallback(e){this.abortCallbacks.push(e)}abort(e,t){if(this.abortCalled=!0,this.abortController.signal.aborted||this.abortStarted)return;const r=t?.interruptedPendingToolCallResolutions;if(this.abortStarted=!0,!this.runActive){this.abortController.abort(e);for(const e of this.abortCallbacks)e();return void(this.abortCallbacks.length=0)}const n=this.abortController,o=[...this.abortCallbacks];this.abortCallbacks.length=0,this.submitConversationAction(new c.QFf({action:{case:"cancelAction",value:new c.TTG({reason:e,interruptedPendingToolCallResolutions:r})}})).catch((()=>{})).finally((()=>{n.abort(e);for(const e of o)e();if(this.abortController===n){const e=[...this.abortCallbacks];this.abortCallbacks.length=0;for(const t of e)t()}}))}async submitConversationAction(e){if(!this.acceptsActions)throw new f.W2("ControlledConversationActionManager is not accepting actions");if("userMessageAction"===e.action.case){const t=e.action.value.userMessage;t&&this.unprocessedUserMessages.push(t)}await this.clientStream.write(e)}queueFollowUpUserMessage(e){if(this.disposed||this.abortStarted)throw new f.W2("ControlledConversationActionManager run was aborted or disposed");this.unprocessedUserMessages.push(e)}async enqueueReplayableConversationAction(e){if("asyncAskQuestionCompletionAction"!==e.action.case)throw new TypeError("Only asyncAskQuestionCompletionAction can use enqueue acknowledgement");if(!this.acceptsActions)throw new f.W2("ControlledConversationActionManager is not accepting actions");this.clientStream.write(e).catch((()=>{}))}markMessageAsProcessed(e){this.unprocessedUserMessages=this.unprocessedUserMessages.filter((t=>t.messageId!==e.messageId))}requeueMessage(e){this.unprocessedUserMessages.some((t=>t.messageId===e.messageId))||this.unprocessedUserMessages.unshift(e)}getUnprocessedUserMessages(){return[...this.unprocessedUserMessages]}hasUnprocessedMessages(){return this.unprocessedUserMessages.length>0}close(){this.acceptsActions=!1,this.clientStream.close()}reopen(){this.disposed||this.acceptsActions||this.resetStream()}resetStream(){if(this.disposed)throw new f.W2("ControlledConversationActionManager disposed");this.acceptsActions=!1,this.clientStream.close(),this.clientStream=(0,f.Jt)(),this.acceptsActions=!0,this.abortController=new AbortController,this.abortStarted=!1;for(const e of this.unprocessedUserMessages)this.clientStream.write(new c.QFf({action:{case:"userMessageAction",value:new c.Vtf({userMessage:e})}})).catch((()=>{}))}async run(e,t){const r=this.clientStream;this.runActive=!0;try{for await(const n of r)try{await t.write(n)}catch(t){kO.error(e,"Error writing conversation action",t)}}catch(e){if(!(e instanceof f.W2))throw e}finally{this.clientStream===r&&(this.runActive=!1)}}dispose(){this.disposed||(this.disposed=!0,this.abortCallbacks.length=0,this.acceptsActions=!1,this.clientStream.throw(new f.W2("ControlledConversationActionManager disposed")))}}var CO=r("../cursor-sdk-local-runtime/dist/utils/logger.js"),EO=r("../agent-kv/dist/agent-store.js");const xO="x-blob-encryption-key";function PO(e,t){const r={...t};return void 0!==r[xO]||(0,EO.TU)(e)&&(r[xO]=e),r}const RO=new Map;function IO(e){if("userMessageAction"===e.action.case)return e.action.value.userMessage?.text}function TO(e,t,r){const n=e.runOptions?.requestedModel;return{conversationId:e.conversationId,generationId:e.conversationId,model:n?.modelId??"unknown",modelId:n?.modelId,modelParams:n?.parameters.map((e=>({id:e.id,value:e.value}))),loopCount:t,promptText:r}}function AO(e){return new c.QFf({action:{case:"userMessageAction",value:new c.Vtf({userMessage:new c.RGk({text:e})})}})}function $O(e){return e instanceof DOMException&&"AbortError"===e.name||e instanceof Error&&("AbortError"===e.name||"The operation was aborted"===e.message)}function MO(e){e?.catch((e=>{CO.Jz.warn("[agent-session-runner] fire-and-forget hook failed:",e)}))}class DO{constructor(e,t,r){this.inner=e,this.getToken=t,this.restMcpHost=r}async getDefinitions(e,t=!0){const r=await this.inner.getDefinitions(e,t);return Promise.all(r.map((async e=>{const t=await async function(e,t,r){if(!("url"in e)||!e.url||void 0===cb(e.url,r)||Object.keys(e.headers??{}).some((e=>e.toLowerCase()===ab)))return e;const n=await t();return void 0===n||0===n.length?e:{...e,headers:{...e.headers??{},[ab]:`Bearer ${n}`}}}(e.serverConfig,this.getToken,this.restMcpHost);return t===e.serverConfig?e:{...e,serverConfig:t}})))}clearCache(){this.inner.clearCache?.()}}const OO=new Set(["mcp.slack.com","setup.shopify.com"]);class FO{constructor(e,t){this.inner=e,this.resolver=t}async getDefinitions(e,t=!0){const r=await this.inner.getDefinitions(e,t);return Promise.all(r.map((async e=>{const t=await async function(e,t){if(!("url"in e)||!e.url)return e;const r=await async function(e,t,r,n=fetch){let o;try{o=new URL(e).hostname}catch{return t}const s=void 0!==cb(e,r.restMcpHost);if(!OO.has(o)&&!s)return t;let i=await r.resolve(e);if(!i&&s){const t=(await dx(e,n))?.clientId;void 0!==t&&(i={CLIENT_ID:t})}return i?t?void 0===lx(t.CLIENT_ID)?{...i,...t,CLIENT_ID:i.CLIENT_ID}:{...i,...t}:i:t}(e.url,e.auth,t);return r===e.auth?e:{...e,auth:r}}(e.serverConfig,this.resolver);return t===e.serverConfig?e:{...e,serverConfig:t}})))}clearCache(){this.inner.clearCache?.()}}class NO{constructor(e,t){this.storage=e,this.prefix=t}async loadTokens(e){return this.storage.loadTokens(this.prefix+e)}async saveTokens(e,t){return this.storage.saveTokens(this.prefix+e,t)}async loadClientInformation(e){return this.storage.loadClientInformation(this.prefix+e)}async saveClientInformation(e,t){return this.storage.saveClientInformation(this.prefix+e,t)}}class LO{constructor(e,t){this.storage=e,this.prefix=t}async isServerApproved(e,t,r){return this.storage.isServerApproved(this.prefix+e,t,r)}}class jO{constructor(e){this.higherPrecedenceSources=e}async load(e,t,r,n,o){for(const r of this.higherPrecedenceSources){const n=(await r.getDefinitions(e)).find((e=>e.identifier===t));if(void 0!==n)throw new MC(t,n.configPath??"another config")}return await o(e,r)}}class UO extends iI{constructor(e,t){super(e),this.shadowedClientsClosed=t}async closeAllClients(){await Promise.all([super.closeAllClients(),this.shadowedClientsClosed])}}async function BO(e){try{await(e.close?.())}catch{}}class WO{constructor(e){this.loaders=e}async load(e,t=!0){const r=await Promise.allSettled(this.loaders.map((({loader:r})=>r.load(e,t)))),n=r.find((e=>"rejected"===e.status));if(n)throw await Promise.allSettled(r.flatMap((e=>"fulfilled"===e.status?[e.value.closeAllClients()]:[]))),n.reason;const o=r.filter((e=>"fulfilled"===e.status)).map((e=>e.value)),s={},i=[];for(let e=0;e{})))}async loadClient(e,t,r=!1){for(const{loader:n,prefix:o}of this.loaders)if(t.startsWith(o)){t=t.slice(o.length);try{return await n.loadClient(e,t,r)}catch(e){if(e instanceof Error&&e.message.includes("not found in config"))continue;throw e}}throw new Error(`MCP client "${t}" not found in config`)}clearClient(e){for(const{loader:t,prefix:r}of this.loaders){if(!e.startsWith(r))continue;const n=e.slice(r.length);t.clearClient?.(n)}}clearAllMcpCaches(){for(const{loader:e}of this.loaders)e.clearAllMcpCaches?.()}}class HO{constructor(e,t,r,n,i=!1,a,c,l=s.join((0,o.homedir)(),".cursor","mcp.json"),u,d,h){const p=Array.isArray(e)?e:[e],f={}.location,m=[];"enterprise"===f?.source&&m.push({path:f.path,prefix:"enterprise-",scope:"enterprise"});for(let e=0;e({prefix:t,scope:r,fileSource:new _I(e,"enterprise"===r||"env"===r?RE:void 0)}))),y=[];for(const{prefix:e,scope:o,fileSource:s}of w){const l=i?"":e,d=new NO(t,l),p=new LO(n,l),f=w.flatMap((e=>{return t=e.scope,r=o,IE.indexOf(t)0?[new jO(f)]:[]],g=new CI(u?new FO(s,u):s,d,m,{authRedirectUrlGenerator:a,isLinkSharedPaymentTokenLogRedactionEnabled:h});y.push({prefix:l,loader:g})}this.loader=new WO(y)}static init(e,t,r,n=!1,o,i={}){const a=new DI(s.join(r,"mcp-auth.json"));(async function(e){await(0,xo.rm)(s.join(e,"mcp-cache.json"),{force:!0})})(r).catch((()=>{}));const c=n?{isServerApproved:()=>Promise.resolve(!0)}:new FC(s.join(r,"mcp-approvals.json"),t);return new HO(t,a,e,c,!0,void 0,o,void 0,i.defaultAuthResolver,void 0,i.isLinkSharedPaymentTokenLogRedactionEnabled)}async load(e,t=!0){return this.loader.load(e,t)}async loadClient(e,t,r=!1){return this.loader.loadClient(e,t,r)}clearClient(e){this.loader.clearClient(e)}clearAllMcpCaches(){this.loader.clearAllMcpCaches()}}const qO="cursor-plugins/local";function zO(e){var t;if(e)for(const r of e)if("object"==typeof(t=r)&&null!==t&&t.kind===qO)return r}class GO extends sI{constructor(e){super(e),this.runtimeManager=e,this.disposed=!1}async dispose(){this.disposed||(this.disposed=!0,await this.runtimeManager.closeAllClients())}}class VO{constructor(e){this.storagePath=e}async isServerDisabled(e){try{const t=await(0,xo.readFile)(this.storagePath,"utf8"),r=JSON.parse(t);return Array.isArray(r)?r.includes(e):(await this.writeDisabledServers([]),!1)}catch(e){if("object"==typeof e&&null!==e&&"code"in e&&"ENOENT"===e.code)return!1;throw e}}async writeDisabledServers(e){await(0,xo.mkdir)((0,s.dirname)(this.storagePath),{recursive:!0}),await(0,xo.writeFile)(this.storagePath,JSON.stringify(e,null,2))}}class KO{constructor(e,t){this.pluginMcpService=e,this.importThirdPartyPlugins=t}async getDefinitions(){let e;try{e=await this.pluginMcpService.getPluginMcpServers()}catch(e){return CO.Jz.warn("[cursor-config-mcp] Failed to enumerate plugin MCP servers:",e),[]}const t=[];for(const r of e){if(!this.importThirdPartyPlugins&&YO(r))continue;const e=II(r);e?t.push({identifier:r.identifier,authStorageKey:r.identifier,serverConfig:e,configPath:"",source:"plugin",metadata:{identifier:r.identifier,pluginName:r.pluginName,pluginSource:r.pluginSource}}):CO.Jz.warn("[cursor-config-mcp] Failed to initialize plugin MCP client:",{identifier:r.identifier,pluginName:r.pluginName,pluginSource:r.pluginSource,result:"invalid-config",errorMessage:"pluginMcpDescriptorToServerConfig returned undefined"})}return t}}class JO{constructor(e){this.servers=e}async getDefinitions(){return Object.entries(this.servers).map((([e,t])=>({identifier:e,authStorageKey:`inline:${e}`,serverConfig:QO(e,t),source:"inline",metadata:{source:"cursor-sdk"}})))}}function ZO(e={}){const t=e.teamSettingsService??{getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getAdminCommandDenylist:async()=>({rules:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}},r=e.ignoreApprovals??!1,n=e.importThirdPartyPlugins??!1,i=void 0===e.isLinkSharedPaymentTokenLogRedactionEnabled?{}:{isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled},a=e.restMcpCursorAuthTokenSupplier,c=e=>void 0===a?e:new DO(e,a,"api.cursor.com");return{async createLease(a){const l=a.workspaceState,u=l.projectRoot??l.workingDirectory,d=l.projectDirectory;if(!u||!d)return new oI;const h=new VO((0,s.join)(d,"mcp-disabled.json")),p=function(e){const{teamSettingsService:t,projectRoot:r,projectDirectory:n,ignoreApprovals:i,disabledStore:a,includeProjectMcp:c,includeUserMcp:l,isLinkSharedPaymentTokenLogRedactionEnabled:u}=e;if(c&&l)return HO.init(t,r,n,i,a,{isLinkSharedPaymentTokenLogRedactionEnabled:u});if(!c&&!l)return;const d=new DI((0,s.join)(n,"mcp-auth.json")),h=i?{isServerApproved:()=>Promise.resolve(!0)}:new FC((0,s.join)(n,"mcp-approvals.json"),r),p=[new KC,new OC(h),new PI(t),new DC(a)],f=[];return c&&f.push({prefix:"",loader:new RI((0,s.join)(r,".cursor","mcp.json"),d,p,{isLinkSharedPaymentTokenLogRedactionEnabled:u})}),l&&f.push({prefix:"",loader:new RI((0,s.join)((0,o.homedir)(),".cursor","mcp.json"),d,p,{isLinkSharedPaymentTokenLogRedactionEnabled:u})}),XO(f)}({teamSettingsService:t,projectRoot:u,projectDirectory:d,ignoreApprovals:r,disabledStore:h,includeProjectMcp:e.includeProjectMcp??!0,includeUserMcp:e.includeUserMcp??!0,isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled}),f=[],m=e.inlineMcpServers??{};if(Object.keys(m).length>0){const e=new DI((0,s.join)(d,"mcp-auth.json")),r=[new KC,new PI(t)];f.push({prefix:"",loader:new CI(c(new JO(m)),e,r,i)})}const g=zO(a.services.pluginBootstrapOutputs);if(g&&(e.includePluginMcp??1)){const e=new FC((0,s.join)(d,"mcp-approvals.json"),u),o=new DI((0,s.join)(d,"mcp-auth.json")),a=[new KC];r||a.push(new OC(e)),a.push(new PI(t),new DC(h));const l=new UD(g.pluginsService),p=new CI(c(new KO(l,n)),o,a,i);f.push({prefix:"",loader:p})}if(p&&f.push({prefix:"",loader:p}),0===f.length)return new oI;const w=XO(f),y=await w.load(e.initializationCtx??(0,b.q6)(),e.cache);return new GO(y)}}}function XO(e){return 1===e.length?e[0].loader:new WO(e)}function QO(e,t){if("command"in t){if(void 0!==t.type&&"stdio"!==t.type)throw new Error(`Unsupported MCP server type "${String(t.type)}" for "${e}"`);return{command:t.command,args:t.args?[...t.args]:void 0,env:t.env,cwd:t.cwd,startupTimeoutSec:t.startupTimeoutSec}}if("url"in t){if(void 0!==t.type&&"http"!==t.type&&"sse"!==t.type)throw new Error(`Unsupported MCP server type "${String(t.type)}" for "${e}"`);const r={url:t.url,headers:t.headers,auth:t.auth?{CLIENT_ID:t.auth.CLIENT_ID,CLIENT_SECRET:t.auth.CLIENT_SECRET,scopes:t.auth.scopes?[...t.auth.scopes]:void 0}:void 0};return"sse"===t.type?{...r,type:"sse"}:r}throw new Error(`Invalid inline MCP server config for "${e}"`)}function YO(e){return"claude-plugin"===e.pluginSource}const eF=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass"];function tF(e){let t=e.trim();t.startsWith("&")&&(t=t.slice(1).trim());const r=t.charAt(0);if("'"!==r&&'"'!==r)return t.split(/\s/)[0]??"";let n="";for(let e=1;e0)return{...n,followup_message:n.reason.trim()};if(!cF(t))return n;const o=uF(e),s=dF(o,r)?o:void 0,i=void 0!==s?{...n,...s}:n;return"block"===i.decision&&"string"==typeof i.reason&&i.reason.trim().length>0?{...i,followup_message:i.reason.trim()}:n}const pF=e=>{const t=[];return Td(e)?$d(!0):(t.push("Expected an object"),$d(!1,t))},fF=e=>{const t=[],r=pF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny","ask"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("Invalid user_message value. Expected a string if provided"),void 0!==e.agent_message&&"string"!=typeof e.agent_message&&t.push("Invalid agent_message value. Expected a string if provided"),$d(0===t.length,t)};function mF(e){const t=e.modelId,r=e.modelParams;return{...void 0!==t&&{model_id:t},...void 0!==r&&r.length>0?{model_params:r.map((e=>({id:e.id,value:e.value})))}:{}}}const gF=new Set([Rd.sessionStart,Rd.beforeSubmitPrompt,Rd.preToolUse,Rd.postToolUse,Rd.postToolUseFailure]);function wF(e){return"prompt"===e.type}function yF(e){return"command"===e.type||void 0===e.type}const vF={[Rd.beforeShellExecution]:fF,[Rd.beforeMCPExecution]:fF,[Rd.afterShellExecution]:e=>{const t=pF(e);return t.isValid,t},[Rd.afterMCPExecution]:e=>{const t=pF(e);return t.isValid,t},[Rd.beforeReadFile]:e=>{const t=[],r=pF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("user_message must be a string if provided"),$d(0===t.length,t)},[Rd.afterFileEdit]:e=>{const t=pF(e);return t.isValid,t},[Rd.beforeTabFileRead]:e=>{const t=[],r=pF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("user_message must be a string if provided"),$d(0===t.length,t)},[Rd.afterTabFileEdit]:e=>pF(e),[Rd.beforeSubmitPrompt]:e=>{const t=pF(e);if(!t.isValid)return t;const r=[];return void 0!==e.continue&&"boolean"!=typeof e.continue&&r.push("continue must be a boolean if provided"),void 0!==e.user_message&&"string"!=typeof e.user_message&&r.push("user_message must be a string if provided"),void 0===e.additional_context||Id(e.additional_context)||r.push("additional_context must be a string if provided"),$d(0===r.length,r)},[Rd.stop]:e=>{const t=pF(e);if(!t.isValid)return t;const r=[];return void 0!==e.followup_message&&"string"!=typeof e.followup_message&&r.push("followup_message must be a string if provided"),$d(0===r.length,r)},[Rd.afterAgentResponse]:e=>{const t=pF(e);return t.isValid,t},[Rd.afterAgentThought]:e=>{const t=pF(e);return t.isValid,t},[Rd.sessionStart]:e=>{const t=pF(e);if(!t.isValid)return t;const r=[];if(void 0!==e.env)if(Td(e.env))for(const[t,n]of Object.entries(e.env))Id(t)||r.push(`env key "${t}" must be a string`),Id(n)||r.push(`env value for "${t}" must be a string`);else r.push("env must be an object if provided");return void 0===e.additional_context||Id(e.additional_context)||r.push("additional_context must be a string if provided"),void 0!==e.continue&&"boolean"!=typeof e.continue&&r.push("continue must be a boolean if provided"),void 0===e.user_message||Id(e.user_message)||r.push("user_message must be a string if provided"),$d(0===r.length,r)},[Rd.sessionEnd]:e=>{const t=pF(e);return t.isValid?$d(!0,[]):t},[Rd.preCompact]:e=>{const t=pF(e);if(!t.isValid)return t;if(null==e||0===Object.keys(e).length)return $d(!0,[]);const r=[];if(!Ad(e))return r.push("PreCompact response must be an object"),$d(!1,r);const n=e;return void 0===n.user_message||(e=>"string"==typeof e)(n.user_message)||r.push("user_message must be a string"),$d(0===r.length,r)},[Rd.subagentStart]:e=>{const t=pF(e);if(!t.isValid)return t;if(!Ad(e))return $d(!1,["Expected an object"]);const r=[],n=e;if(void 0!==n.permission){const e=["allow","deny","ask"];"string"==typeof n.permission&&e.includes(n.permission)||r.push(`Invalid permission value. Expected one of: ${e.join(", ")}, or undefined`)}return void 0===n.user_message||Id(n.user_message)||r.push("user_message must be a string if provided"),$d(0===r.length,r)},[Rd.subagentStop]:e=>{const t=pF(e);if(!t.isValid)return t;const r=[];return Ad(e)&&void 0!==e.followup_message&&"string"!=typeof e.followup_message&&r.push("followup_message must be a string if provided"),$d(0===r.length,r)},[Rd.preToolUse]:e=>{const t=[],r=pF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny","ask"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("Invalid user_message value. Expected a string if provided"),void 0!==e.agent_message&&"string"!=typeof e.agent_message&&t.push("Invalid agent_message value. Expected a string if provided"),void 0!==e.updated_input&&("object"!=typeof e.updated_input||null===e.updated_input||Array.isArray(e.updated_input))&&t.push("Invalid updated_input value. Expected a plain object if provided"),Md(e.additional_context,"additional_context",t),$d(0===t.length,t)},[Rd.postToolUse]:e=>{const t=[],r=pF(e);return r.isValid?(Md(e.additional_context,"additional_context",t),$d(0===t.length,t)):r},[Rd.postToolUseFailure]:e=>{const t=pF(e);if(!t.isValid)return t;const r=[];return Md(e.additional_context,"additional_context",r),$d(0===r.length,r)},[Rd.workspaceOpen]:e=>{const t=pF(e);if(!t.isValid)return t;const r=[];return void 0!==e.pluginPaths&&(Array.isArray(e.pluginPaths)?e.pluginPaths.forEach(((e,t)=>{"string"==typeof e?0===e.trim().length&&r.push(`pluginPaths[${t}] must be a non-empty string`):r.push(`pluginPaths[${t}] must be a string`)})):r.push("pluginPaths must be an array of strings if provided")),$d(0===r.length,r)}},bF=(e,t,r)=>{const n=function(e,t,r){let n;return n=e===Rd.preToolUse?function(e,t){if(!lF(e))return e;const r=e;if(void 0!==r.permission||void 0!==r.user_message||void 0!==r.agent_message||void 0!==r.updated_input)return r;if(!cF(t))return r;const n=uF(e);if(!dF(n,"PreToolUse"))return r;const o={...r};let s=!1;return void 0!==n.permissionDecision&&(o.permission=n.permissionDecision,s=!0),"string"==typeof n.permissionDecisionReason&&(o.user_message=n.permissionDecisionReason,s=!0),lF(n.updatedInput)&&(o.updated_input=n.updatedInput,s=!0),s?o:r}(t,r):e===Rd.stop?hF(t,r,"Stop"):e===Rd.subagentStop?hF(t,r,"SubagentStop"):t,function(e,t,r,n){if(!gF.has(e)||!lF(r)||void 0!==r.additional_context)return r;const o=lF(t)?function(e){return"string"==typeof e.additionalContext?e.additionalContext:void 0}(t)??function(e,t,r){if(!cF(r))return;const n=Ld[e];if(void 0===n)return;const o=uF(t);return dF(o,n)&&"string"==typeof o.additionalContext?o.additionalContext:void 0}(e,t,n):void 0;return void 0===o?r:{...r,additional_context:o}}(e,t,n,r)}(e,t,r),o=(0,vF[e])(n);return o.isValid?{success:!0,data:n}:{success:!1,errors:o.errors}},SF=[Rd.beforeShellExecution,Rd.beforeMCPExecution,Rd.beforeReadFile,Rd.beforeTabFileRead,Rd.subagentStart,Rd.preToolUse],kF=[Rd.workspaceOpen];function _F(e,t){const r=[];return"string"==typeof e&&e.trim()&&r.push(e.trim()),"string"==typeof t&&t.trim()&&r.push(t.trim()),r.length>0?r.join("\n\n---\n\n"):void 0}function CF(e,t){return{..."object"==typeof e&&null!==e?e:{},...t}}function EF(e){return SF.includes(e)}function xF({step:e,command:t,failClosed:r,kind:n}){const o=EF(e);if(!r&&!o)return{shouldNotifyUser:!1};const s=r?"Tool blocked because this hook is configured to fail closed (block when it fails). "+("invalid_json"===n?`Hook "${t}" returned invalid JSON.`:`Hook "${t}" returned invalid response.`):"invalid_json"===n?`Hook "${t}" returned invalid JSON. The command was blocked for safety.`:`Hook "${t}" returned an invalid response for this hook step. The command was blocked for safety.`;return{blockResponse:RF(e,s),cause:r?"script_fail_closed":"permission_hook_invalid_output",reason:s,shouldNotifyUser:o&&!r}}function PF(e,t){return t}function RF(e,t){return EF(e)?PF(0,{permission:"deny",user_message:t}):e===Rd.beforeSubmitPrompt||e===Rd.sessionStart?PF(0,{continue:!1,user_message:t}):e===Rd.stop?PF(0,{}):void 0}function IF(e){try{return{value:JSON.parse(e)}}catch{return}}function TF(e){if("object"!=typeof e||null===e)return!1;const t=e.event;return"backgrounded"===t?.case}function AF(e){if("object"!=typeof e||null===e)return;const t=e.path;return"string"==typeof t&&t.length>0?t:void 0}class $F{cacheCarriersForExecId(e,t){const r=this.carriersByExecId.get(e);if(!(void 0!==r&&r.length>0&&0===t.length))for(this.carriersByExecId.has(e)&&this.carriersByExecId.delete(e),this.carriersByExecId.set(e,t);this.carriersByExecId.size>$F.CARRIERS_BY_EXEC_ID_MAX;){const e=this.carriersByExecId.keys().next().value;if(void 0===e)break;this.carriersByExecId.delete(e)}}constructor(e,t,r,n){this.inner=e,this.wake=r,this.carriersByExecId=new Map,this.inFlightByExecId=new Map,this.resolveDrain="function"==typeof t?t:e=>t,this.skipPathWriteDrain=n?.skipPathWriteDrain,this.onWakeWrittenPath=n?.onWakeWrittenPath,this.forceWrittenPathBeforeDrain=n?.forceWrittenPathBeforeDrain,this.writeBarrierTimeoutMs=n?.writeBarrierTimeoutMs??2e3,this.resolveWriteBarrierTimeoutMs=n?.resolveWriteBarrierTimeoutMs,this.onWriteBarrier=n?.onWriteBarrier}resolveTimeoutMs(){if(void 0!==this.resolveWriteBarrierTimeoutMs)try{const e=this.resolveWriteBarrierTimeoutMs();if("number"==typeof e&&Number.isFinite(e))return e}catch{}return this.writeBarrierTimeoutMs}get(e){return this.wrapImpl(e.symbol,this.inner.get(e))}*entries(){for(const[e,t]of this.inner.entries())yield[e,this.wrapImpl(e.symbol,t)]}wrapImpl(e,t){if(!function(e){return"object"==typeof e&&null!==e&&"execute"in e&&"function"==typeof e.execute}(t))return t;const r=function(e){return e===GT.symbol||e===VT.symbol?{kind:"path"}:e===WT.symbol||e===re.symbol||e===kA.symbol?{kind:"exposed"}:void 0}(e),n=this.resolveDrain,o=this.wake,s=this.skipPathWriteDrain,i=this.forceWrittenPathBeforeDrain,a=()=>this.resolveTimeoutMs(),c=this.onWriteBarrier,l=this.onWakeWrittenPath,u=(e,t)=>{if(void 0!==r&&void 0!==o)try{if("path"===r.kind){const r=AF(e);void 0!==r&&(o.wakeForWrittenPath(r),l?.(r,t))}else o.wakeExposedMounts()}catch{}},d=this.cacheCarriersForExecId.bind(this),h=this.carriersByExecId,p=this.inFlightByExecId,f=async(e,t)=>{const r=t?.hookContextCollector;if(void 0===r)return[];if(!1===t?.deliverAgentStoreConflictNotices)return[];const o=void 0!==t?.execId&&t.execId.length>0?t.execId:void 0;if(void 0!==o){const e=h.get(o);if(void 0!==e)return e.length>0&&r.push(...e),e;const t=p.get(o);if(void 0!==t){const e=await t;return e.length>0&&r.push(...e),e}}const s=async t=>{const r=n(e);let s=[];try{const e=await r.peek();if(s=e.eventIds,e.carriers.length>0)return t.push(...e.carriers),r.ack(e.eventIds),void 0!==o&&d(o,e.carriers),e.carriers;s.length>0&&r.ack(s);const n=[];return void 0!==o&&d(o,n),n}catch{return s.length>0&&r.release(s),[]}};if(void 0===o)return await s(r);const i=s(r);p.set(o,i);try{return await i}finally{p.get(o)===i&&p.delete(o)}};return new Proxy(t,{get:(t,n,o)=>"execute"!==n?Reflect.get(t,n,o):(n,o,l)=>{const d=t.execute.call(t,n,o,l);return"object"==typeof(h=d)&&null!==h&&Symbol.asyncIterator in h&&"function"==typeof h[Symbol.asyncIterator]?async function*(){let t=!1,r=!1,s=!1;try{for await(const r of d)if(e===re.symbol&&TF(r)){if(!t){u(o,n);const e=await f(n,l);t=!0,e.length>0&&(yield new fe.FI({event:{case:"hookContext",value:new fe.Ng({hookAdditionalContexts:[...e]})}}))}yield r}else yield r;s=!0}catch(e){throw r=!0,e}finally{u(o,n),t||r||!s||await f(n,l)}}():function(e){return"object"==typeof e&&null!==e&&"then"in e&&"function"==typeof e.then}(d)?(async()=>{try{const t=await d;return u(o,n),e===GT.symbol&&!0===s?.()&&!0===l?.enableAgentStoreConflictNotices||(await async function(e,t,r,n){const o=e=>{try{n.onWriteBarrier?.(e)}catch{}};if(void 0===e||"path"!==r?.kind)return;const s=AF(t);if(void 0===s)return;if(!(n.timeoutMs>0))return void o({durationMs:0,outcome:"skipped"});const i=Date.now(),a=e(s).then((e=>e),(()=>"error")),c=await Promise.race([a,(0,Nr.cb)(n.timeoutMs).then((()=>"timeout"))]);"not_store_path"!==c&&o({durationMs:Date.now()-i,outcome:c})}(i,o,r,{timeoutMs:a(),onWriteBarrier:c}),await f(n,l)),t}catch(e){throw u(o,n),e}})():(u(o,n),d);var h}})}}function MF(e){return new RegExp(`<${e}(?:\\s[^>]*)?>[\\s\\S]*?`,"gi")}$F.CARRIERS_BY_EXEC_ID_MAX=32,Error,iu.execFileSync,new Map,Ro.constants.O_NOFOLLOW,new Set(["write_conflict","create_conflict","truncate_conflict_failed","conflict_fallback_failed","quota_exceeded","gap"]),new Set(["write_conflict","create_conflict","truncate_conflict_failed","conflict_fallback_failed","quota_exceeded"]),Math.max(1,Math.floor(8192));const DF=["user_info","project_layout","rules","always_applied_workspace_rules","agent_requestable_workspace_rules","user_rules","agent_skills","available_skills","cloud_instructions","cloud_task_instructions","open_and_recently_viewed_files","system_reminder","system-reminder","instructions_update","mcp_instructions","mcp_file_system","mcp_file_system_servers","git_status","agent_transcripts","cursor_rules_context","attached_files","system_notification","task_notification","agent_notification"].map(MF);function OF(e){return function(e,t){let r=e;if(r.includes("<"))for(const e of t)r=r.replace(e,"");return(r.includes("\n\n\n")?r.replace(FF,"\n\n"):r).trim()}(e,DF)}["system_reminder","system-reminder"].map(MF);const FF=/\n{3,}/g;function NF(e){const t=(0,_o.sh)(e.conversationId);if("subagent"===e.kind&&e.parentConversationId){const r=(0,_o.sh)(e.parentConversationId);return`${_o.O2}/${r}/subagents/${t}.${e.ext}`}return`${_o.O2}/${t}/${t}.${e.ext}`}function LF(e){const t=(0,_o.sh)(e.conversationId);return`${_o.O2}/${t}.${e.ext}`}function jF(e){const t=e.exts??["jsonl","txt"],r=e.includeLegacy??!0,n=[],o=e=>{n.includes(e)||n.push(e)};for(const n of t)o(NF({conversationId:e.conversationId,ext:n,kind:e.kind,parentConversationId:e.parentConversationId})),"subagent"===e.kind&&e.parentConversationId&&o(NF({conversationId:e.conversationId,ext:n,kind:"primary"})),r&&o(LF({conversationId:e.conversationId,ext:n}));return n}var UF;!function(e){e.INTERNAL="INTERNAL",e.EXTERNAL="EXTERNAL",e.NO_PREAMBLE="NO_PREAMBLE"}(UF||(UF={}));var BF=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},WF=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function HF(e){switch(e){case c.xyI.AGENT:return"agent";case c.xyI.ASK:return"ask";case c.xyI.PLAN:return"plan";case c.xyI.DEBUG:return"debug";case c.xyI.TRIAGE:return"triage";case c.xyI.MULTITASK:return"multitask";case c.xyI.CUSTOM:return"custom";case c.xyI.UNSPECIFIED:default:return"agent"}}function qF(e,t){return t instanceof Uint8Array?{__type:"Uint8Array",hex:(r=t,Array.from(r).map((e=>e.toString(16).padStart(2,"0"))).join(""))}:"bigint"==typeof t?t.toString():t;var r}function zF(e,t){return function(e){return"object"==typeof e&&null!==e&&"__type"in e&&"Uint8Array"===e.__type&&"hex"in e&&"string"==typeof e.hex}(t)?`[Binary data omitted from transcript: ${t.hex.length/2} bytes]`:t}const GF=new TextEncoder,VF=new TextDecoder,KF=new class{serialize(e){const t=JSON.stringify(e,qF);return GF.encode(t)}deserialize(e){const t=VF.decode(e);return t.includes('"__type":"Uint8Array"')?JSON.parse(t,zF):JSON.parse(t)}};function JF(e){const t=e.providerOptions;return!0===t?.cursor?.isSummary}function ZF(e){return"system"!==e.role&&!JF(e)}function XF(e,t){return"user"===e.role&&"user"===t.role}async function QF(e,t,r){const n=await t.getBlob(e,r);return n?c.Anz.fromBinary(n).summarizedMessages:[]}async function YF(e,t,r,n){const o=await t.getBlob(e,r);if(o){if(o.length>5e6)return n.omittedOversizeBlobCount++,n.omittedOversizeBlobBytes+=o.length,n.largestOmittedOversizeBlobBytes=Math.max(n.largestOmittedOversizeBlobBytes,o.length),{role:"assistant",content:`[Oversize transcript blob omitted: ${s=o.length,`${(s/1e6).toFixed(1)} MB`}]`};var s;try{const e=performance.now(),t=KF.deserialize(o);return n.totalDeserializeDurationMs+=performance.now()-e,n.hydratedBlobCount++,n.hydratedBlobBytes+=o.length,n.largestHydratedBlobBytes=Math.max(n.largestHydratedBlobBytes,o.length),t}catch{return}}}async function eN(e,t,r){const n={messages:[],hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0};for(const o of r){const r=await YF(e,t,o,n);r&&n.messages.push(r)}return n}async function tN(e,t,r,n,o){const s=[];let i=0;const a=()=>{const o=YF(e,t,r[i++],n);o.catch((()=>{})),s.push(o)};for(;i{let r;return r="string"==typeof t?t:"object"==typeof t&&null!==t?JSON.stringify(t):String(t),` ${e}: ${r}`})).join("\n")}`}(e.args)}`;case"tool-result":return`[Tool result] ${e.toolName}`;default:return""}}function nN(e){return OF(e)}const oN=/[\s\S]*?<\/think>/gi,sN=/[\s\S]*?<\/thinking>/gi,iN=/\n{3,}/g;function aN(e){let t=e;return t.includes("<")&&(t=t.replace(oN,"").replace(sN,"")),(t.includes("\n\n\n")?t.replace(iN,"\n\n"):t).trim()}function cN(e,t,r){if(void 0===e)return"";if("string"==typeof e){const n=t?nN(e):e;return r?aN(n):n}return e.map((e=>{if(r&&"text"===e.type){const r=aN(t?nN(e.text):e.text);return rN({...e,text:r},!1)}return rN(e,t)})).filter(Boolean).join("\n")}function lN(e,t){const r={role:e.role},n=e.content;if("string"==typeof n){const o=t?nN(n):n,s="assistant"===e.role?aN(o):o;s.trim()&&(r.text=s)}else if(Array.isArray(n)){const o=[],s=[],i=[];let a;for(const r of n)switch(r.type){case"text":{const n=t?nN(r.text):r.text,s="assistant"===e.role?aN(n):n;s.trim()&&o.push(s);break}case"reasoning":r.text.trim()&&s.push(r.text);break;case"redacted-reasoning":s.push("[REDACTED]");break;case"image":o.push("[Image]");break;case"file":o.push(r.filename?`[File: ${r.filename}]`:"[File]");break;case"tool-call":i.push({toolName:r.toolName,args:r.args});break;case"tool-result":a={toolName:r.toolName}}o.length>0&&(r.text=o.join("\n")),s.length>0&&(r.thinking=s.join("\n")),i.length>0&&(r.toolCalls=i),a&&(r.toolResult=a)}return r}function uN(e){return e.endsWith("\n")?e:`${e}\n`}function dN(e){const{turnEnded:t}=e,r=[],n={},o=[];return void 0!==t&&(r.push(function(e){switch(e.status){case"success":return"Turn ended: success.";case"error":return`Turn ended: error: ${e.error}`;case"aborted":return e.error?`Turn ended: aborted: ${e.error}`:"Turn ended: aborted.";default:return e}}(t)),n.turnEnded=t,o.push(JSON.stringify({type:"turn_ended",...t}))),{textSuffixes:r,jsonFields:n,jsonlLines:o}}function hN(e){if("system"===e.role||JF(e))return;const t=lN(e,"user"===e.role),r=[],n=[];if(t.text&&n.push(t.text),t.thinking&&n.push(t.thinking),n.length>0&&r.push({type:"text",text:n.join("\n\n")}),t.toolCalls)for(const e of t.toolCalls)r.push({type:"tool_use",name:e.toolName,input:e.args});if(0===r.length)return;const o={role:e.role,message:{content:r}};return JSON.stringify(o)}class pN{constructor(e,t,r,n={}){this.projectDir=e,this.blobStore=t,this.writeFile=r,this.options={writeText:n.writeText??!0,writeJson:n.writeJson??!1,writeJsonl:n.writeJsonl??!1,pathResolver:n.pathResolver,appendFile:n.appendFile,streamFullJsonlWrites:n.streamFullJsonlWrites??!1,fallbackToFullWriteOnIncrementalFailure:n.fallbackToFullWriteOnIncrementalFailure??!0}}resolveFilePath(e,t){if(this.options.pathResolver)return this.options.pathResolver(e,t);const r=NF({conversationId:e,ext:t,kind:"primary"});return`${this.projectDir}/${r}`}async writeFromStateFull(e,t,r,n={}){const o={stack:[],error:void 0,hasError:!1};try{const s=BF(o,(0,D.VI)(e.withName("writeFromState")),!1);try{const{overviewFactory:e}=n,o=dN(n),{appendFile:i,streamFullJsonlWrites:a,writeJsonl:c,writeText:l,writeJson:u}=this.options;if(i&&a&&c&&!l&&!u&&!e)try{return await this.writeJsonlStreamed(s,{state:t,filePath:this.resolveFilePath(r,"jsonl"),appendFile:i,terminalLines:o.jsonlLines}),!0}catch(e){console.error("[TranscriptStore] Streamed transcript write failed, retrying as a single write:",e)}const d=await async function(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=BF(n,(0,D.VI)(e.withName("hydrateSummaryArchives")),!1);let s=0;const i=(0,D.OA)(o.ctx),a=[];let c=0,l=0,u=0,d=0,h=0,p=0,f=0;const m=await Promise.all(r.summaryArchives.map((async e=>{s++;try{const r=await QF(i,t,e);return s+=r.length,await eN(i,t,r)}catch{return{messages:[],hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0}}})));for(const e of m)a.push(...e.messages),c+=e.hydratedBlobCount,l+=e.hydratedBlobBytes,u=Math.max(u,e.largestHydratedBlobBytes),d+=e.totalDeserializeDurationMs,h+=e.omittedOversizeBlobCount,p+=e.omittedOversizeBlobBytes,f=Math.max(f,e.largestOmittedOversizeBlobBytes);o.span.setAttribute("getBlobCount",s),o.span.setAttribute("hydratedBlobCount",c),o.span.setAttribute("hydratedBlobBytes",l),o.span.setAttribute("largestHydratedBlobBytes",u),o.span.setAttribute("totalDeserializeDurationMs",d),o.span.setAttribute("omittedOversizeBlobCount",h),o.span.setAttribute("omittedOversizeBlobBytes",p),o.span.setAttribute("largestOmittedOversizeBlobBytes",f);const g=BF(n,(0,D.VI)(e.withName("hydratePromptMessages")),!1),w=await eN(i,t,r.rootPromptMessagesJson);g.span.setAttribute("getBlobCount",r.rootPromptMessagesJson.length),g.span.setAttribute("hydratedBlobCount",w.hydratedBlobCount),g.span.setAttribute("hydratedBlobBytes",w.hydratedBlobBytes),g.span.setAttribute("largestHydratedBlobBytes",w.largestHydratedBlobBytes),g.span.setAttribute("totalDeserializeDurationMs",w.totalDeserializeDurationMs),g.span.setAttribute("omittedOversizeBlobCount",w.omittedOversizeBlobCount),g.span.setAttribute("omittedOversizeBlobBytes",w.omittedOversizeBlobBytes),g.span.setAttribute("largestOmittedOversizeBlobBytes",w.largestOmittedOversizeBlobBytes);const y=w.messages.filter(ZF);return a.push(...y),a}catch(e){n.error=e,n.hasError=!0}finally{WF(n)}}(s.ctx,this.blobStore,t);if(0===d.length&&0===o.jsonlLines.length)return!0;let h;if((this.options.writeText||e)&&(h=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&"user"===t[0].role&&"user"===t[1].role&&(t=t.slice(1));const r=[];for(const e of t){const t="user"===e.role,n="assistant"===e.role,o=cN(e.content,t,n);o.trim()&&("tool"===e.role?r.push(o):r.push(`${e.role}:\n${o}`))}return r.join("\n\n")}(d)),this.options.writeText){const e=h??"",t=o.textSuffixes.length>0?e.trim().length>0?`${e}\n\n${o.textSuffixes.join("\n")}`:o.textSuffixes.join("\n"):e;t.trim()&&await this.writeFile(this.resolveFilePath(r,"txt"),t)}if(this.options.writeJson){const e=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&"user"===t[0].role&&"user"===t[1].role&&(t=t.slice(1));const r=[];for(const e of t){const t=lN(e,"user"===e.role);(t.text||t.thinking||t.toolCalls||t.toolResult)&&r.push(t)}return 0===r.length?"":JSON.stringify(r,null,2)}(d);if(e||o.jsonlLines.length>0){const n={mode:HF(t.mode),messages:e?JSON.parse(e):[],...o.jsonFields};await this.writeFile(this.resolveFilePath(r,"json"),JSON.stringify(n,null,2))}}if(this.options.writeJsonl){const t=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&XF(t[0],t[1])&&(t=t.slice(1));const r=[];for(const e of t){const t=hN(e);t&&r.push(t)}return r.join("\n")}(d);let n=[t,...o.jsonlLines].filter((e=>e.length>0)).join("\n");if(n&&e&&h?.trim())try{const t=(await e(h)).trim();t&&(n=function(e,t){const r={type:"metadata",metadata:{overview:t}};return`${JSON.stringify(r)}\n${e}`}(n,t))}catch(e){console.error("[TranscriptStore] Failed to generate transcript overview:",e)}n&&await this.writeFile(this.resolveFilePath(r,"jsonl"),uN(n))}return!0}catch(e){return console.error("[TranscriptStore] Failed to write transcript:",e),!1}}catch(e){o.error=e,o.hasError=!0}finally{WF(o)}}async writeJsonlStreamed(e,t){const{filePath:r,appendFile:n}=t;let o=[],s=0,i=0,a=0;const c=async()=>{if(0===o.length)return;const e=`${o.join("\n")}\n`;o=[],s=0,0===i?await this.writeFile(r,e):await n(r,e),i++,a+=e.length},l=async e=>{e&&(o.push(e),s+=e.length+1,s>=1e6&&await c())};let u,d=0;const h=await async function(e,t,r,n){const o={hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0};for(const s of r.summaryArchives){let r;try{r=await QF(e,t,s)}catch{continue}await tN(e,t,r,o,{skipFailedReads:!0,visit:n})}return await tN(e,t,r.rootPromptMessagesJson,o,{skipFailedReads:!1,visit:async e=>{ZF(e)&&await n(e)}}),o}((0,D.OA)(e.ctx),this.blobStore,t.state,(async e=>{"system"!==e.role&&(d++,1!==d?(2===d&&u&&(XF(u,e)||await l(hN(u)),u=void 0),await l(hN(e))):u=e)}));u&&await l(hN(u));for(const e of t.terminalLines)await l(e);await c(),e.span.setAttribute("streamed",!0),e.span.setAttribute("chunkCount",i),e.span.setAttribute("writtenChars",a),e.span.setAttribute("hydratedBlobCount",h.hydratedBlobCount),e.span.setAttribute("hydratedBlobBytes",h.hydratedBlobBytes),e.span.setAttribute("largestHydratedBlobBytes",h.largestHydratedBlobBytes),e.span.setAttribute("totalDeserializeDurationMs",h.totalDeserializeDurationMs),e.span.setAttribute("omittedOversizeBlobCount",h.omittedOversizeBlobCount),e.span.setAttribute("omittedOversizeBlobBytes",h.omittedOversizeBlobBytes),e.span.setAttribute("largestOmittedOversizeBlobBytes",h.largestOmittedOversizeBlobBytes)}async writeFromStateIncremental(e,t,r,n,o={}){const s={stack:[],error:void 0,hasError:!1};try{const i=t.rootPromptMessagesJson.length,a=dN(o),c=a.jsonlLines.length>0;if(i===n&&!c&&!o.overviewFactory)return i;const l=this.options.appendFile;if(!(l&&this.options.writeJsonl&&!this.options.writeText&&!this.options.writeJson&&n>0&&i>=n&&(i>n||c))||o.overviewFactory)return await this.writeFromStateFull(e,t,r,o)?i:0;const u=BF(s,(0,D.VI)(e.withName("writeFromStateIncremental")),!1);if(i===n&&c)try{return await l(this.resolveFilePath(r,"jsonl"),uN(a.jsonlLines.join("\n"))),i}catch(n){return console.error(this.options.fallbackToFullWriteOnIncrementalFailure?"[TranscriptStore] Failed to append transcript, falling back to full write:":"[TranscriptStore] Failed to append transcript:",n),this.options.fallbackToFullWriteOnIncrementalFailure?await this.writeFromStateFull(e,t,r,o)?i:0:0}try{const e=t.rootPromptMessagesJson.slice(n),o=await eN(u.ctx,this.blobStore,e);u.span.setAttribute("hydratedBlobCount",o.hydratedBlobCount),u.span.setAttribute("hydratedBlobBytes",o.hydratedBlobBytes),u.span.setAttribute("largestHydratedBlobBytes",o.largestHydratedBlobBytes),u.span.setAttribute("totalDeserializeDurationMs",o.totalDeserializeDurationMs),u.span.setAttribute("omittedOversizeBlobCount",o.omittedOversizeBlobCount),u.span.setAttribute("omittedOversizeBlobBytes",o.omittedOversizeBlobBytes),u.span.setAttribute("largestOmittedOversizeBlobBytes",o.largestOmittedOversizeBlobBytes);const s=[];for(const e of o.messages){const t=hN(e);t&&s.push(t)}if(s.push(...a.jsonlLines),s.length>0){const e=uN(s.join("\n"));await l(this.resolveFilePath(r,"jsonl"),e)}return i}catch(n){return console.error(this.options.fallbackToFullWriteOnIncrementalFailure?"[TranscriptStore] Failed to append transcript, falling back to full write:":"[TranscriptStore] Failed to append transcript:",n),this.options.fallbackToFullWriteOnIncrementalFailure?await this.writeFromStateFull(e,t,r,o)?i:0:0}}catch(e){s.error=e,s.hasError=!0}finally{WF(s)}}}function fN(e,t){const r=function(e){return"object"==typeof e&&null!==e}(e)&&t in e?e[t]:void 0;return"string"==typeof r&&""!==r?r:void 0}function mN(e,t){return e.filter((e=>function(e,t){if(!e.matcher||""===e.matcher||"*"===e.matcher)return!0;if(void 0===t)return!0;try{return new RegExp(e.matcher).test(t)}catch{return!0}}(e,t)))}function gN(e){return`Tool blocked because this hook is configured to fail closed (block when it fails). ${e}`}function wN(e){return Object.values(Rd).some((t=>t===e))}function yN(e){switch(e??(0,o.platform)()){case"darwin":return s.join("/Library","Application Support","Cursor","hooks.json");case"win32":return s.join("C:\\","ProgramData","Cursor","hooks.json");default:return s.join("/etc","cursor","hooks.json")}}function vN(e){return wF(e)?`prompt:${e.prompt}`:`command:${e.command}`}function bN(e){return(e.repoHooks??[]).flatMap((e=>[e.projectHooks,e.claudeProjectHooks,e.claudeProjectLocalHooks]))}class SN{constructor(e,t,r){this.fileReader=e,this.paths=t,this.logger=r||{warn:e=>console.warn(`[hooks] ${e}`),info:e=>{}}}async load(e={}){const{loadProjectHooks:t=!0}=e,r={errors:[],configDirs:{}},n=this.paths.projectConfigPath??this.paths.claudeProjectConfigPath??this.paths.claudeProjectLocalConfigPath,o=n?s.dirname(s.dirname(n)):void 0,i=(e,t)=>{if(!e||!o)return;if(t)return o;const r=s.relative(s.resolve(o),s.resolve(e));return".."===r||r.startsWith(`..${s.sep}`)||s.isAbsolute(r)?void 0:o},a=async(e,t,n,o,i,a,c,l)=>{if(e)try{if(!await this.fileReader.exists(e))return;if(c&&this.fileReader.pathContainsSymlink&&await this.fileReader.pathContainsSymlink(e,c))return r.errors.push({source:t,message:`${i} at ${e}: refusing to load config path that contains a symlink`}),void this.logger.warn(`Refusing to load ${a} config via symlink path: ${e}`);const u=await this.fileReader.readFile(e);if(!u)return;const{config:d,error:h}=l(u);if(d){switch(n){case"enterpriseHooks":r.enterpriseHooks=d;break;case"teamHooks":r.teamHooks=d;break;case"userHooks":r.userHooks=d;break;case"projectHooks":r.projectHooks=d;break;case"claudeUserHooks":r.claudeUserHooks=d;break;case"claudeProjectHooks":r.claudeProjectHooks=d;break;case"claudeProjectLocalHooks":r.claudeProjectLocalHooks=d;break;default:return}((e,t)=>{r.configDirs[e]=s.dirname(t)})(o,e)}else h&&r.errors.push({source:t,message:`${i} at ${e}: ${h}`})}catch(e){r.errors.push({source:t,message:`Error accessing ${a} config file: ${String(e)}`})}},c=[{path:this.paths.enterpriseConfigPath,source:"enterprise",resultKey:"enterpriseHooks",configDirKey:"enterprise",parsePrefix:"Enterprise hooks.json",accessLabel:"enterprise",symlinkCheckRoot:i(this.paths.enterpriseConfigPath,!1)},{path:this.paths.teamConfigPath,source:"team",resultKey:"teamHooks",configDirKey:"team",parsePrefix:"Team hooks.json",accessLabel:"team",symlinkCheckRoot:i(this.paths.teamConfigPath,!1)},{path:this.paths.userConfigPath,source:"user",resultKey:"userHooks",configDirKey:"user",parsePrefix:"User hooks.json",accessLabel:"user",symlinkCheckRoot:i(this.paths.userConfigPath,!1)},{path:t?this.paths.projectConfigPath:void 0,source:"project",resultKey:"projectHooks",configDirKey:"project",parsePrefix:"Project hooks.json",accessLabel:"project",symlinkCheckRoot:i(this.paths.projectConfigPath,!0)}];for(const e of c)await a(e.path,e.source,e.resultKey,e.configDirKey,e.parsePrefix,e.accessLabel,e.symlinkCheckRoot,(t=>this.parseAndValidate(t,e.source)));const l=[{path:this.paths.claudeUserConfigPath,source:"claude-user",resultKey:"claudeUserHooks",configDirKey:"claudeUser",label:"user",symlinkCheckRoot:i(this.paths.claudeUserConfigPath,!1)},{path:t?this.paths.claudeProjectConfigPath:void 0,source:"claude-project",resultKey:"claudeProjectHooks",configDirKey:"claudeProject",label:"project",symlinkCheckRoot:i(this.paths.claudeProjectConfigPath,!0)},{path:t?this.paths.claudeProjectLocalConfigPath:void 0,source:"claude-project-local",resultKey:"claudeProjectLocalHooks",configDirKey:"claudeProjectLocal",label:"project local",symlinkCheckRoot:i(this.paths.claudeProjectLocalConfigPath,!0)}];for(const e of l)await a(e.path,e.source,e.resultKey,e.configDirKey,`Claude ${e.label} settings.json`,`Claude ${e.label}`,e.symlinkCheckRoot,(t=>this.parseClaudeConfig(t,e.source)));return function(e){const{cursorConfigs:t,claudeConfigs:r,logger:n}=e,o=new Map;for(const e of t)if(e?.hooks)for(const[t,r]of Object.entries(e.hooks)){if(!r)continue;let e=o.get(t);e||(e=new Set,o.set(t,e));for(const t of r)e.add(vN(t))}for(const{config:e,source:t}of r)if(e?.hooks)for(const[r,s]of Object.entries(e.hooks)){if(!s)continue;const i=o.get(r);if(!i||0===i.size)continue;const a=s.filter((e=>{const o=vN(e);return!i.has(o)||(n?.info(`Removed duplicate ${t} hook for ${r}: ${o}`),!1)}));a.length!==s.length&&(e.hooks[r]=a)}}({cursorConfigs:[r.enterpriseHooks,r.teamHooks,r.userHooks,r.projectHooks],claudeConfigs:[{config:r.claudeUserHooks,source:"claude-user"},{config:r.claudeProjectHooks,source:"claude-project"},{config:r.claudeProjectLocalHooks,source:"claude-project-local"}],logger:this.logger}),r}parseClaudeConfig(e,t){try{const t=JSON.parse(e);if(!function(e,t={}){if(!Ad(e))return!1;if(!("hooks"in e))return!1;const r=e.hooks;if(!Ad(r))return!1;const n=r;for(const[e,r]of Object.entries(n))if(e in Nd&&Array.isArray(r)){const n=!0===t.allowMatcherlessStop&&"Stop"===e;for(const e of r)if(Ad(e)&&"hooks"in e&&Array.isArray(e.hooks)&&("matcher"in e||n))return!0}return!1}(t))return{};const r=t.hooks;if(!r||0===Object.keys(r).length)return{};const n=Yd(r,this.logger),o=Fd(n);return o.isValid?{config:n}:{error:`Invalid transformed config: ${o.errors.join("; ")}`}}catch(e){return{error:`Failed to parse JSON: ${String(e)}`}}}parseAndValidate(e,t){try{const n=this.parseJSONC(e),o=Fd(n);return o.isValid?"object"==typeof(r=n)&&null!==r&&"version"in r&&"number"==typeof r.version&&"hooks"in r&&"object"==typeof r.hooks&&null!==r.hooks&&!Array.isArray(r.hooks)?{config:n}:{error:`Invalid ${t} config: missing 'hooks' property`}:{error:`Invalid ${t} config: ${o.errors.join("; ")}`}}catch(e){return{error:`Failed to parse ${t} config JSON: ${String(e)}`}}var r}parseJSONC(e){let t=e.replace(/\/\/.*$/gm,"");return t=t.replace(/\/\*[\s\S]*?\*\//g,""),JSON.parse(t)}static getConfiguredSteps(e){const t=new Set,r=[e.enterpriseHooks,e.teamHooks,e.userHooks,e.projectHooks,e.claudeUserHooks,e.claudeProjectHooks,e.claudeProjectLocalHooks,...bN(e)];for(const e of r)if(e?.hooks)for(const r of Object.keys(e.hooks))wN(r)&&t.add(r);for(const r of e.pluginHooks??[])for(const e of Object.keys(r.config.hooks))wN(e)&&t.add(e);return t}}const kN="Read",_N="Write",CN="Delete",EN="List",xN="Grep",PN="Shell",RN="ReadLints";function IN(e,t){if("object"==typeof e&&null!==e)return Object.getOwnPropertyDescriptor(e,t)?.value}const TN=new Set([kN,_N,CN,EN,xN,RN]);function AN(e){const t=IN(e,"tool_name"),r=[IN(e,"file_path"),"string"==typeof t&&TN.has(t)?IN(IN(e,"tool_input"),"file_path"):void 0];for(const e of r)if("string"==typeof e&&e.length>0)return e}const $N=(0,d.h)("cli-hooks-executor");function MN(e){try{return(0,Ro.statSync)(e).isFile()}catch{return!1}}const DN="\nJSON Parse Error: Error: Failed to parse hook stdout as JSON";function ON(e,t){for(const[r,n]of Object.entries(e))if(r===t)return n}function FN(e,t){const r=ON(e,t);if("string"==typeof r||null===r)return r}class NN{constructor(e,t,r,n,o,s,i,a){this.workspacePath=t,this.globalContext=r,this.shellExecutor=n,this.promptHookClient=o,this.onHookExecution=i,this.options=a,this.sessionEnvById=new Map,this.sessionUserEmailById=new Map,this.activeSessionIdsByConversationId=new Map,this.transcriptParentConversationIdById=new Map,this.configReadyPromises=[],this.config=e,s&&this.addConfigReadyPromise(s)}addConfigReadyPromise(e){this.configReadyPromises.push(e.catch((()=>{})))}reportCommandFailure(e,t){if(void 0!==e)try{e(t)}catch{}}finishHookRun(e,t,r,n){const o=e.transportMode??("prompt"===e.hookType?"prompt":this.getCommandHookPayloadTransportMode());try{this.onHookExecution?.({...e,transportMode:o})}catch{}const s=this.options?.onHookRun;if(void 0===s)return;const i=n.exitCode??e.exitCode,a="spawn_error"===(c=e.errorClass)?"shell_exec_transport_error":"prompt_error"===c?"prompt_execution_error":void 0;var c;try{s({step:e.hookStep,script:t,source:e.hookSource,...void 0===e.pluginId?{}:{pluginId:e.pluginId},request:r,response:n.response??null,status:e.status,durationMs:e.latencyMs,...void 0===i?{}:{exitCode:i},stderr:n.stderr,transportMode:o,configuredTimeoutSec:t.timeout??60,timedOut:!0===e.timedOut,...void 0===a?{}:{failureType:a}})}catch{}}getCommandHookPayloadTransportMode(){return"stdin"===this.options?.commandHookPayloadTransport?"win32"===process.platform?"windows_temp_file":"stdin":"argv_heredoc"}shouldUseCommandHookDirectStdinTransport(){return"stdin"===this.getCommandHookPayloadTransportMode()}async writeCommandHookStdinPayload(e,t){if(!e)throw new Error("Hook stdin transport was requested, but the executor did not provide stdin");try{e.end(Buffer.from(t,"utf8"))}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;if("EPIPE"===t||"ERR_STREAM_DESTROYED"===t||"ERR_STREAM_PREMATURE_CLOSE"===t)return;throw e}try{await(0,lh.finished)(e)}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;if("EPIPE"===t||"ERR_STREAM_DESTROYED"===t||"ERR_STREAM_PREMATURE_CLOSE"===t)return;throw e}}updateConfig(e){this.config=e}beginSessionEnvironment(e,t){this.sessionEnvById.delete(e.sessionId),this.sessionUserEmailById.delete(e.sessionId);const r=this.activeSessionIdsByConversationId.get(e.conversationId)??[];this.activeSessionIdsByConversationId.set(e.conversationId,r.filter((t=>t!==e.sessionId)).concat(e.sessionId));const n=t?.userEmail?.trim()??"";n.length>0&&this.sessionUserEmailById.set(e.sessionId,n)}setSessionUserEmail(e,t){const r=t?.trim()??"";0!==r.length&&this.sessionUserEmailById.set(e.sessionId,r)}setSessionEnvironment(e,t){void 0===t?this.sessionEnv={...this.sessionEnv,...e}:this.sessionEnvById.set(t.sessionId,{...this.sessionEnvById.get(t.sessionId),...e})}clearSessionEnvironment(e){if(void 0===e)this.sessionEnv=void 0;else{this.sessionEnvById.delete(e.sessionId),this.sessionUserEmailById.delete(e.sessionId);const t=(this.activeSessionIdsByConversationId.get(e.conversationId)??[]).filter((t=>t!==e.sessionId));0===t.length?this.activeSessionIdsByConversationId.delete(e.conversationId):this.activeSessionIdsByConversationId.set(e.conversationId,t)}}resolveUserEmail(e){const{conversation_id:t,session_id:r}=e;if(void 0!==r&&this.sessionUserEmailById.has(r))return this.sessionUserEmailById.get(r)??null;if(void 0!==t){const e=this.activeSessionIdsByConversationId.get(t)?.at(-1);if(void 0!==e){const t=this.sessionUserEmailById.get(e);if(void 0!==t)return t}}return this.globalContext.user_email}setTranscriptParentConversationId(e,t){this.transcriptParentConversationIdById.set(e,t)}async getTranscriptPathIfExists(e){try{const t=(0,_o.Rv)((0,o.homedir)(),this.workspacePath),r=this.transcriptParentConversationIdById.get(e),n=jF(r?{conversationId:e,kind:"subagent",parentConversationId:r}:{conversationId:e,kind:"primary"}).map((e=>(0,s.join)(t,e)));for(const e of n)try{return await(0,xo.access)(e),e}catch{}return null}catch{return null}}async getSubagentTranscriptPathIfExists(e){const{subagentId:t,parentConversationId:r}=e;try{const e=(0,_o.Rv)((0,o.homedir)(),this.workspacePath),n=jF({conversationId:t,kind:"subagent",parentConversationId:r}).map((t=>(0,s.join)(e,t)));for(const e of n)try{return await(0,xo.access)(e),e}catch{}return null}catch{return null}}hasHooksForStep(e){return[this.config.enterpriseHooks,this.config.teamHooks,this.config.userHooks,this.config.projectHooks,this.options?.runtimeHooks,this.config.claudeUserHooks,this.config.claudeProjectHooks,this.config.claudeProjectLocalHooks,...bN(this.config),...(this.config.pluginHooks??[]).map((e=>e.config))].some((t=>{const r=t?.hooks[e];return void 0!==r&&r.length>0}))}hasFailClosedHooksForStep(e,t){const r=[this.config.enterpriseHooks,this.config.teamHooks,this.config.projectHooks,...(this.config.repoHooks??[]).map((e=>e.projectHooks)),this.config.userHooks,this.options?.runtimeHooks];for(const n of r){const r=n?.hooks[e];if(r&&(t?mN(r,t):r).some((e=>!0===e.failClosed)))return!0}for(const r of this.config.pluginHooks??[]){const n=r.config.hooks[e];if(n&&(t?mN(n,t):n).some((e=>yF(e)&&!0===e.failClosed)))return!0}return!1}configuredHookDirectory(e){const t=this.config.configDirs;switch(e){case"enterprise":return t?.enterprise;case"team":return t?.team;case"user":return t?.user;case"claude-user":return t?.claudeUser;default:return}}cwdForHookSource(e,t){if(void 0!==e?.cwd&&e.cwd.length>0)return e.cwd;const r=this.configuredHookDirectory(t.source);if(void 0!==r&&r.length>0)return r;const n=e?.cwdForSource?.(t.source);return void 0!==n&&n.length>0?n:t.fallback}getCwdForSource(e){const t=this.config.configDirs;switch(e){case"enterprise":return t?.enterprise??this.workspacePath;case"team":return t?.team??this.workspacePath;case"project":case"claude-project":case"claude-project-local":case"claude-plugin":case"runtime":default:return this.workspacePath;case"user":return t?.user??this.workspacePath;case"claude-user":return t?.claudeUser??this.workspacePath}}buildHookEnvironment(e){const{transcriptPath:t,sessionId:r,conversationId:n,executionEnv:o}=e,s=this.resolveUserEmail({conversation_id:n,session_id:r});return{CURSOR_PROJECT_DIR:this.workspacePath,CURSOR_VERSION:this.globalContext.cursor_version,...s&&{CURSOR_USER_EMAIL:s},...t&&{CURSOR_TRANSCRIPT_PATH:t},CLAUDE_PROJECT_DIR:this.workspacePath,...this.sessionEnv,...void 0!==r?this.sessionEnvById.get(r):void 0,...o}}shouldSkipHookDueToLoopLimit(e,t,r){if("stop"!==e&&"subagentStop"!==e)return!1;const n=ON(r,"loop_count");if("number"!=typeof n)return!1;const o=n,s=t.loop_limit;return null!==s&&(void 0===s?o>=5:o>=s)}async executeHookForStep(e,t,r){this.configReadyPromises.length>0&&await this.whenConfigReady();const n=function(e){return kF.includes(e)}(e),o=t,i=n?null:o.conversation_id?await this.getTranscriptPathIfExists(o.conversation_id):null;let a;if(e===Rd.subagentStop){const e=FN(t,"subagent_id"),r=FN(t,"parent_conversation_id");a=e?await this.getSubagentTranscriptPathIfExists({subagentId:e,parentConversationId:r??void 0}):null}const c=n?void 0:o.session_id??o.conversation_id,l={...t,...void 0!==c&&{session_id:c},hook_event_name:e,cursor_version:this.globalContext.cursor_version,workspace_roots:[...new Set([this.workspacePath,...(this.config.repoHooks??[]).map((e=>e.repoPath))])],user_email:this.resolveUserEmail(o),...!n&&{transcript_path:i},...e===Rd.subagentStop&&{agent_transcript_path:a??null}},u=function(e,t){switch(e){case"beforeShellExecution":case"afterShellExecution":return fN(t,"command");case"beforeMCPExecution":case"afterMCPExecution":{const e=fN(t,"tool_name");return e?`MCP:${e}`:void 0}case"beforeReadFile":return"Read";case"afterFileEdit":return"Write";case"beforeTabFileRead":return"TabRead";case"afterTabFileEdit":return"TabWrite";case"beforeSubmitPrompt":return"UserPromptSubmit";case"stop":return"Stop";case"afterAgentResponse":return"AgentResponse";case"afterAgentThought":return"AgentThought";case"subagentStart":case"subagentStop":return fN(t,"subagent_type");case"preToolUse":case"postToolUse":case"postToolUseFailure":return fN(t,"tool_name");default:return}}(e,l),d=[],h=(e,t,n)=>{if(!e)return;const o=mN(e,u),s=this.cwdForHookSource(r,{source:t,fallback:n??this.getCwdForSource(t)}),i=void 0===n?r?.env:{CURSOR_PROJECT_DIR:n,CLAUDE_PROJECT_DIR:n,...r?.env};for(const e of o)wF(e)?this.promptHookClient&&d.push({type:"prompt",script:e,source:t}):yF(e)&&d.push({type:"command",script:e,cwd:s,env:i,source:t})},p=await async function({repoHooks:e,targetPath:t,workspacePath:r}){if(e.length<2||void 0===t||0===t.length)return e;const n=(0,ts.o1)(t,r),[o,i,a]=await Promise.all([(0,ts.DN)(n),(0,ts.DN)(s.dirname(n)),Promise.all(e.map((async e=>await(0,ts.DN)(e.repoPath)??s.resolve(e.repoPath))))]);if(null===o||null===i)return e;const c=t=>{let r;return e.forEach(((e,n)=>{const o=a[n],i=s.relative(o,t);(""===i||".."!==i&&!i.startsWith(`..${s.sep}`)&&!s.isAbsolute(i))&&(void 0===r||o.length>r.repoPath.length)&&(r={repo:e,repoPath:o})})),r?.repo},l=new Set;for(const t of[o,s.join(i,s.basename(n))]){const r=c(t);if(void 0===r)return e;l.add(r)}return e.filter((e=>l.has(e)))}({repoHooks:this.config.repoHooks??[],targetPath:AN(t),workspacePath:this.workspacePath});h(this.config.enterpriseHooks?.hooks[e],"enterprise"),h(this.config.teamHooks?.hooks[e],"team"),h(this.config.projectHooks?.hooks[e],"project");for(const t of p)h(t.projectHooks?.hooks[e],"project",t.repoPath);h(this.config.userHooks?.hooks[e],"user"),h(this.options?.runtimeHooks?.hooks[e],"runtime"),h(this.config.claudeProjectLocalHooks?.hooks[e],"claude-project-local"),h(this.config.claudeProjectHooks?.hooks[e],"claude-project");for(const t of p)h(t.claudeProjectLocalHooks?.hooks[e],"claude-project-local",t.repoPath),h(t.claudeProjectHooks?.hooks[e],"claude-project",t.repoPath);h(this.config.claudeUserHooks?.hooks[e],"claude-user");for(const t of this.config.pluginHooks??[]){const n=t.config.hooks[e];if(!n?.length)continue;const o=r?.cwd??(e===Rd.stop||e===Rd.subagentStop?this.workspacePath:t.installPath),s={...void 0!==t.plugin&&{plugin:t.plugin},...void 0!==t.marketplace&&{marketplace:t.marketplace},...void 0!==t.pluginId&&{pluginId:t.pluginId},...void 0!==t.marketplaceId&&{marketplaceId:t.marketplaceId}};for(const e of mN(n,u))yF(e)&&d.push({type:"command",script:e,cwd:o,env:r?.env,source:"claude-plugin",attribution:s,pluginInstallPath:t.installPath})}if(0!==d.length)return this.executeAllAndMerge(e,d,l,r?.onCommandFailure)}async whenConfigReady(){await Promise.all(this.configReadyPromises)}async executeAllAndMerge(e,t,r,n){let o;const s=()=>o??=function(e){const t=JSON.stringify(e);return{json:t,payloadSizeBytes:Buffer.byteLength(t,"utf8")}}(r),i=t.map((async(t,o)=>{const{source:i,attribution:a}=t;try{return"prompt"===t.type?await this.executePromptHook(e,t.script,r,i,o,s,a):await this.executeCommandHook(e,t.script,t.cwd,t.env,r,i,o,s,a,t.pluginInstallPath,n)}catch(r){const n=r instanceof Error?r.message:String(r);if(!0===t.script.failClosed){const t=gN(`Hook execution failed: ${n}`),r=RF(e,t);if(r)return{success:!0,data:r,source:i,index:o}}return $N.warn((0,b.q6)(),`${e} hook error`,{source:i,index:o,error:n}),{success:!1,source:i,index:o}}})),a=await Promise.all(i),c=[];for(const e of a)e.success&&void 0!==e.data&&c.push(e.data);return function(e,t){if(0===t.length)return;const[r]=t;if(!(1!==t.length||Ad(n=r)&&Ad(n.updated_input)&&0===Object.keys(n.updated_input).length))return r;var n;const o=SF.includes(e),s=e===Rd.sessionStart,i=e===Rd.workspaceOpen,a=gF.has(e),c={};for(const e of t){const t=e;for(const[e,r]of Object.entries(t))if(void 0!==r)if(i&&"pluginPaths"===e&&Array.isArray(r)){const t=c[e],n=Array.isArray(t)?t:[],o=new Set(n),s=[...n];for(const e of r)"string"!=typeof e||o.has(e)||(o.add(e),s.push(e));c[e]=s}else"permission"===e&&o?c[e]=(u=r,"deny"===(l=c[e])||"deny"===u?"deny":"ask"===l||"ask"===u?"ask":"allow"===l||"allow"===u?"allow":void 0):"user_message"!==e&&"agent_message"!==e?"updated_input"!==e?a&&"additional_context"===e&&"string"==typeof r?c[e]=_F(c[e],r):"continue"!==e||"boolean"!=typeof r?c[e]=s&&"env"===e&&"object"==typeof r&&null!==r?CF(c[e],r):r:void 0===c[e]?c[e]=r:c[e]=c[e]&&r:void 0===c[e]&&Ad(r)&&Object.keys(r).length>0&&(c[e]=r):c[e]=_F(c[e],r)}var l,u;return c}(e,c)}async executeCommandHook(e,t,r,n,o,s,i,a,c,l,u){if(this.shouldSkipHookDueToLoopLimit(e,t,o))return{success:!1,source:s,index:i};const d=Date.now(),h=a(),p=h.payloadSizeBytes,f=(e,r)=>this.finishHookRun(e,t,o,r);let m;try{m=await this.executeCommandScript({script:t,cwd:r,request:o,jsonPayload:h.json,env:n,...void 0!==l&&{pluginInstallPath:l}})}catch(r){const n=r instanceof Error?r.message:String(r),o=n.toLowerCase().includes("timed out");this.reportCommandFailure(u,{command:t.command,source:s,exitCode:null,stderr:"",errorMessage:n});const a=Date.now()-d,l=o?"timeout":"spawn_error";if(!0===t.failClosed){const u=RF(e,gN(`Hook "${t.command}" execution failed: ${n}`));if(u)return f({hookStep:e,hookSource:s,hookType:"command",status:o?"timeout":"blocked",latencyMs:a,payloadSizeBytes:p,errorClass:l,failClosed:!0,timedOut:o,...c},{response:null,stderr:String(r)}),{success:!0,data:u,source:s,index:i}}return f({hookStep:e,hookSource:s,hookType:"command",status:o?"timeout":"failed",latencyMs:a,payloadSizeBytes:p,errorClass:l,failClosed:!0===t.failClosed,timedOut:o,...c},{response:null,stderr:String(r)}),{success:!1,source:s,index:i}}if(2===m.exitCode){const r=function(e,t,r){const n=e.trim(),o=t.trim();return n||(o?`Hook blocked with message: ${o}`:`Hook "${r}" blocked this action (exit code 2) but provided no reason.`)}(m.stdout,m.stderr,t.command),n=RF(e,r);return n?(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,failClosed:!0===t.failClosed,exitCode:m.exitCode,...c},{response:n,stderr:m.stderr}),{success:!0,data:n,source:s,index:i}):(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,failClosed:!0===t.failClosed,exitCode:m.exitCode,...c},{response:null,stderr:m.stderr}),{success:!1,source:s,index:i})}if(0!==m.exitCode&&null!==m.exitCode){if(this.reportCommandFailure(u,{command:t.command,source:s,exitCode:m.exitCode,stderr:m.stderr}),!0===t.failClosed){const r=RF(e,gN(`Hook "${t.command}" failed with exit code ${m.exitCode}${m.stderr?`: ${m.stderr.trim()}`:""}`));if(r)return f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"exit_nonzero",failClosed:!0,exitCode:m.exitCode,...c},{response:null,stderr:m.stderr}),{success:!0,data:r,source:s,index:i}}return f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"exit_nonzero",failClosed:!0===t.failClosed,exitCode:m.exitCode,...c},{response:null,stderr:m.stderr}),{success:!1,source:s,index:i}}const g=m.stdout.trim();if(!g){if(!0===t.failClosed){const r=RF(e,gN(`Hook "${t.command}" returned no output.`));if(r)return f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"empty_stdout",failClosed:!0,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr}),{success:!0,data:r,source:s,index:i}}return f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"empty_stdout",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr}),{success:!1,source:s,index:i}}const w=function(e){const t=e.trim();if(0===t.length)return;const r=IF(t);if(void 0!==r)return r.value;if(t.endsWith("}"))for(let e=t.length-1;e>=0;e--){if("{"!==t[e])continue;const r=IF(t.slice(e));if(void 0!==r)return r.value}}(g);if(void 0===w){const r=xF({step:e,command:t.command,failClosed:!0===t.failClosed,kind:"invalid_json"});return r.blockResponse?(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_json",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr+DN}),{success:!0,data:r.blockResponse,source:s,index:i}):(f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_json",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr+DN}),{success:!1,source:s,index:i})}const y=bF(e,w,{enableClaudeNestedHookSpecificOutputCompatibility:this.options?.enableClaudeNestedHookSpecificOutputCompatibility});if(y.success&&null!=y.data){const r=y.data,n="object"==typeof r&&"permission"in r?r.permission:void 0;return f({hookStep:e,hookSource:s,hookType:"command",status:"deny"===n||"ask"===n?"blocked":"success",latencyMs:m.duration,payloadSizeBytes:p,failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:r,stderr:m.stderr}),{success:!0,data:r,source:s,index:i}}const v=xF({step:e,command:t.command,failClosed:!0===t.failClosed,kind:"invalid_response"});return v.blockResponse?(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_response",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:w,stderr:m.stderr}),{success:!0,data:v.blockResponse,source:s,index:i}):(f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_response",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:w,stderr:m.stderr}),{success:!1,source:s,index:i})}async executePromptHook(e,t,r,n,o,s,i){if(this.shouldSkipHookDueToLoopLimit(e,t,r))return{success:!1,source:n,index:o};if(!this.promptHookClient)return{success:!1,source:n,index:o};const a=1e3*(t.timeout??60),c=Date.now(),l=s(),u=l.payloadSizeBytes,d=(e,n)=>this.finishHookRun(e,t,r,n),h=(0,b.q6)(),[p,f]=h.withTimeoutAndCancel(a);try{const r=JSON.parse(l.json),s=await this.promptHookClient.evaluatePromptHook(p,{prompt:t.prompt,hookInputJson:r,modelName:t.model});if(s.ok){const r=function(e){return EF(e)?PF(0,{permission:"allow"}):e===Rd.beforeSubmitPrompt||e===Rd.sessionStart?PF(0,{continue:!0}):e===Rd.stop?PF(0,{}):void 0}(e);return d({hookStep:e,hookSource:n,hookType:"prompt",status:"success",latencyMs:Date.now()-c,payloadSizeBytes:u,failClosed:!0===t.failClosed,...i},{response:r,stderr:"",exitCode:0}),r?{success:!0,data:r,source:n,index:o}:{success:!1,source:n,index:o}}{const r=RF(e,s.reason??"Prompt hook blocked this action");return d({hookStep:e,hookSource:n,hookType:"prompt",status:"blocked",latencyMs:Date.now()-c,payloadSizeBytes:u,failClosed:!0===t.failClosed,...i},{response:r,stderr:"",exitCode:2}),r?{success:!0,data:r,source:n,index:o}:{success:!1,source:n,index:o}}}catch(r){const s=r instanceof Error?r.message:String(r),a=s.toLowerCase().includes("abort")||s.toLowerCase().includes("timed out"),l=a?"timeout":"prompt_error";if(!0===t.failClosed){const t=RF(e,gN(`Prompt hook failed: ${s}`));if(t)return d({hookStep:e,hookSource:n,hookType:"prompt",status:a?"timeout":"blocked",latencyMs:Date.now()-c,payloadSizeBytes:u,errorClass:l,failClosed:!0,timedOut:a,...i},{response:null,stderr:String(r)}),{success:!0,data:t,source:n,index:o}}return d({hookStep:e,hookSource:n,hookType:"prompt",status:a?"timeout":"failed",latencyMs:Date.now()-c,payloadSizeBytes:u,errorClass:l,failClosed:!0===t.failClosed,timedOut:a,...i},{response:null,stderr:String(r)}),{success:!1,source:n,index:o}}finally{f()}}async executeCommandScript(e){const{script:t,cwd:r,request:n,env:i,pluginInstallPath:a,jsonPayload:c}=e,l=1e3*(t.timeout??60),u=Date.now();let d;const h=new AbortController,p=setTimeout((()=>{h.abort()}),l);try{const e="win32"===process.platform,f=this.getCommandHookPayloadTransportMode(),m=this.shouldUseCommandHookDirectStdinTransport(),g=e?function(e,t){const r=function(e){let t=0;for(;t0&&!/^\s/.test(i))return e;if(/[$`{}()|;,<>]/.test(s)||""===o&&/['"]/.test(s))return e;const a=s.slice(Math.max(s.lastIndexOf("\\"),s.lastIndexOf("/"))+1);if(0===a.length||a.includes("."))return e;const c="'"===o?s.replace(/''/g,"'"):s,l=/^[A-Za-z]:[\\/]/.test(u=c)||u.startsWith("\\")||u.startsWith("/")?c:`${t.cwd.replace(/[\\/]+$/,"")}\\${c}`;var u;const d=iF.find((e=>t.isFile(l+e)));return void 0===d?e:""!==o?`${n}${o}${s}${d}${o}${i}`:`${n}'${s}${d}'${i}`}(t.command,{cwd:r,isFile:MN}):t.command;let w;if(m)w=e?aF(g):g;else if("windows_temp_file"===f){d=await(0,xo.mkdtemp)((0,s.join)((0,o.tmpdir)(),"cursor-hooks-"));const e=(0,s.join)(d,"payload.json");await(0,xo.writeFile)(e,c,{encoding:"utf8",flag:"wx"}),w=function(e,t){return`$OutputEncoding = [System.Text.UTF8Encoding]::new($false); try { $global:cursorHookConsoleInputEncoding = [Console]::InputEncoding; $null = Register-EngineEvent -SourceIdentifier PowerShell.Exiting -Action { try { [Console]::InputEncoding = $global:cursorHookConsoleInputEncoding } catch { } }; [Console]::InputEncoding = $OutputEncoding } catch { }; Get-Content -LiteralPath '${e.replace(/'/g,"''")}' -Raw -Encoding UTF8 | & { $input | ${aF(t)} }`+sF(t)}(e,g)}else w=e?`@'\n${c.replace(/'/g,"''")}\n'@ | & ${g}`+sF(g):`${t.command} <<'CURSOR_HOOK_EOF'\n${c}\nCURSOR_HOOK_EOF`;const y=FN(n,"conversation_id")??void 0,v=FN(n,"session_id")??void 0,S=FN(n,"transcript_path"),k=void 0===y?void 0:this.activeSessionIdsByConversationId.get(y),_=void 0===v||v===y&&!this.sessionEnvById.has(v)?void 0===y?void 0:k?.at(-1)??y:v,C=this.buildHookEnvironment({transcriptPath:S,sessionId:_,conversationId:y,executionEnv:i}),E={};for(const[e,t]of Object.entries(C))void 0!==t&&(E[e]=t);void 0!==a&&(E.CURSOR_PLUGIN_ROOT=a,E.CLAUDE_PLUGIN_ROOT=a);const x=(0,b.q6)(),P=new ca.StringDecoder("utf8"),R=new ca.StringDecoder("utf8");let I,T="",A="",$=null,M=!1;for await(const e of this.shellExecutor.execute(x,w,{workingDirectory:r,signal:h.signal,sandboxPolicy:{perUser:{type:"insecure_none"}},env:E,pipeStdin:m}))switch(e.type){case"stdin_ready":m&&(await this.writeCommandHookStdinPayload(e.stdin,c),M=!0);break;case"stdout":T+=P.write(e.data);break;case"stderr":A+=R.write(e.data);break;case"exit":$=e.code,I=e.aborted}if(T+=P.end(),A+=R.end(),m&&!M)throw new Error("Hook stdin transport was requested, but the executor did not signal stdin readiness");clearTimeout(p);const D=Date.now()-u;if(I??h.signal.aborted)throw new Error(`Hook script timed out after ${l}ms`);return{stdout:T,stderr:A,exitCode:$,duration:D}}catch(e){if(clearTimeout(p),Date.now(),h.signal.aborted)throw new Error(`Hook script timed out after ${l}ms`);throw e}finally{if(d)try{await(0,xo.rm)(d,{recursive:!0,force:!0})}catch{}}}}class LN{constructor(e){this.config=e,this.configuredSteps=SN.getConfiguredSteps(e)}getConfig(){return this.config}hasHookForStep(e){return this.configuredSteps.has(e)}getConfiguredSteps(){return new Set(this.configuredSteps)}}var jN=r("node:perf_hooks");const UN=(0,b.cF)(Symbol.for("@anysphere/agent-exec/toolCallHooks"),{kind:"none"});function BN(e){return"inExecute"!==e.get(UN).kind}function WN(e,t){const r=e.get(UN);return"inExecute"!==r.kind||!r.toolStepsInPreToolUse.includes(t)}(0,b.cF)(Symbol.for("@anysphere/agent-exec/hookAsk"),void 0),(0,b.cF)(Symbol.for("@anysphere/agent-exec/hookAllow"),void 0),new WeakMap,new WeakMap,(0,b.cF)(Symbol.for("@anysphere/agent-exec/toolCallRefusal"),void 0),new WeakMap,new WeakMap,new WeakMap,(0,b.cF)(Symbol.for("@anysphere/agent-exec/approvalWaits"),void 0),new WeakMap;const HN=(0,b.cF)(Symbol.for("@anysphere/agent-exec/hookStepTime"),void 0),qN=new bd.AsyncLocalStorage;function zN(e,t){return qN.run(e,t)}function GN(e,t){void 0!==e&&t.length>0&&e.push(...t)}class VN extends Error{constructor(e){super(`Hook additional_context for ${e.hookEventName} is ${e.actualLength} chars (max ${e.maxLength}).`),this.name="HookAdditionalContextTooLargeError",this.hookEventName=e.hookEventName,this.actualLength=e.actualLength,this.maxLength=e.maxLength}}var KN=r("../proto/dist/generated/agent/v1/hook_additional_context_pb.js");function JN({hookEventName:e,additionalContext:t}){const r=function(e){const t=e?.trim();return void 0!==t&&t.length>0?t:void 0}(t);if(void 0===r)return[];if(r.length>1e4)throw new VN({hookEventName:e,actualLength:r.length,maxLength:1e4});return[new KN.C({hookEventName:e,content:r})]}Object.fromEntries(Array.from(gF).map((e=>{if(!function(e){return e===Rd.sessionStart||e===Rd.beforeSubmitPrompt||e===Rd.preToolUse||e===Rd.postToolUse||e===Rd.postToolUseFailure}(e))throw new Error(`HOOK_STEPS_SUPPORTING_ADDITIONAL_CONTEXT lists ${e} but HookStepAdditionalContextEventName does not include it. Extend the Extract<> union in spec.ts.`);return[e,{hookEventName:e}]})));const ZN="Agent note: Do not suggest workarounds to the blocked tool.";function XN(e){return e.includes(ZN)?e:`${e}\n\n${ZN}`}class QN extends Error{constructor(e){super(`Hook denied: ${e}`),this.failureType="permission_denied",this.name="HookDeniedError",this.reason=e}}class YN extends Error{constructor(e,t){super(`Hook failed (fail-closed): ${e}`),this.failureType="error",this.name="FailClosedError",this.reason=e,this.cause=t}}const eL="To view or modify configured hooks, go to Cursor Settings > Hooks.";function tL(e,t){return XN(`${t?`${e} was blocked by a hook: ${t}`:`${e} was blocked by a hook.`}\n\n${eL}`)}function rL(e){return function(e){return e instanceof QN}(e)||function(e){return e instanceof YN}(e)}const nL=(0,d.h)("generic-hooks");function oL(e,t,r,n){try{return JN({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof VN)return nL.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}const sL=e=>Math.round(1e3*e)/1e3;function iL(e,t,r,n,o,s){const i=n(e),a=o.getToolCallId?.(t)??(0,ko.randomUUID)(),c=o.getExtraHookFields?.(t)??{},l={baseHookRequest:i,toolUseId:a,toolInput:o.createToolInput(t),extraHookFields:c,hookContextCollector:s?.hookContextCollector??o.getHookContextCollector?.(t)??[]},u=function(e,t,r,n){let{toolInput:o,extraHookFields:s,hookContextCollector:i}=n;const{baseHookRequest:a,toolUseId:c}=n;return{fireFailureAsync:async(n,l,u,d=!1)=>{try{const h=await zN(e.signal,(()=>t.executeHookForStep(Rd.postToolUseFailure,{...a,tool_name:r,tool_input:o,error_message:l,failure_type:u,duration:n,tool_use_id:c,is_interrupt:d,...s})));GN(i,oL(e,r,Rd.postToolUseFailure,h?.additional_context))}catch(t){nL.warn(e,"postToolUseFailure hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}},fireSuccessAsync:async(n,l)=>{try{const u=await zN(e.signal,(()=>t.executeHookForStep(Rd.postToolUse,{...a,tool_name:r,tool_input:o,tool_output:l,duration:n,tool_use_id:c,...s})));GN(i,oL(e,r,Rd.postToolUse,u?.additional_context))}catch(t){nL.warn(e,"postToolUse hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}},getToolInput:()=>o,setToolInput:e=>{o=e},setExtraHookFields:e=>{s=e,n.extraHookFields=e}}}(e,r,o.toolName,l);return{hookContext:l,helpers:u}}async function aL(e,t,r,n,o,s,i,a){const{baseHookRequest:c,toolUseId:l,extraHookFields:u}=n;try{const a=await zN(e.signal,(()=>r.executeHookForStep(Rd.preToolUse,{...c,tool_name:s.toolName,tool_input:o.getToolInput(),tool_use_id:l,...u})));if("deny"===a?.permission){const r=a.user_message||`${s.toolName} blocked by preToolUse hook`,c=XN(r);try{GN(n.hookContextCollector,JN({hookEventName:Rd.preToolUse,additionalContext:a.additional_context}))}catch(t){if(!(t instanceof VN))throw t;nL.warn(e,"preToolUse deny additional_context exceeded max size; dropping carrier",{toolName:s.toolName,actualLength:t.actualLength,maxLength:t.maxLength})}return await o.fireFailureAsync(0,r,"permission_denied"),{type:"rejected",result:i(t,c),reason:c}}a?.updated_input&&s.applyUpdatedInput&&(s.applyUpdatedInput(t,a.updated_input),o.setToolInput(s.createToolInput(t)),s.getExtraHookFields&&o.setExtraHookFields(s.getExtraHookFields(t))),GN(n.hookContextCollector,JN({hookEventName:Rd.preToolUse,additionalContext:a?.additional_context}))}catch(n){const a=r.hasFailClosedHooksForStep?.(Rd.preToolUse,s.toolName)??!1,c=n instanceof VN;if(a){const e=gN(`${c?"preToolUse additional_context exceeded max size":"preToolUse hook failed"}: ${n instanceof Error?n.message:"preToolUse hook error"}`);return await o.fireFailureAsync(0,e,"error"),{type:"rejected",result:i(t,e),reason:e}}nL.warn(e,c?"preToolUse additional_context exceeded max size; dropping carrier":"preToolUse hook error",{toolName:s.toolName,error:n instanceof Error?n.message:String(n),...c?{actualLength:n.actualLength,maxLength:n.maxLength}:{}})}if(a)try{const s=await a({ctx:e,args:t,baseHookRequest:c,hookExecutor:r,toolInput:o.getToolInput(),toolUseId:l,extraHookFields:n.extraHookFields});if(void 0!==s){const e="Pre-execution hook returned rejection";return await o.fireFailureAsync(0,e,"permission_denied"),{type:"rejected",result:s,reason:e}}}catch(e){if(rL(e))return await o.fireFailureAsync(0,e.reason,e.failureType),{type:"rejected",result:i(t,e.reason),reason:e.reason};throw e}return{type:"continue"}}function cL(e){return e.toolCallId}function lL(e,t,r,n){return{async execute(o,s,i){const a=dL(o,t),{hookContext:c,helpers:l}=iL(o,s,a,r,n,i);let u;try{u=await aL(o,s,a,c,l,n,n.createRejectedResult,n.runPreExecutionHooks)}catch(e){throw n.runCleanup?.(c.toolUseId),e}if("rejected"===u.type)return n.runCleanup?.(c.toolUseId),u.result;const d=jN.performance.now();try{const t=await e.execute(o,s,i),r=sL(jN.performance.now()-d);if(n.runPostExecutionHooks)try{const e=await n.runPostExecutionHooks({ctx:o,args:s,result:t,baseHookRequest:c.baseHookRequest,hookExecutor:a,toolInput:l.getToolInput(),toolUseId:c.toolUseId,executionDurationMs:r,extraHookFields:c.extraHookFields});if(void 0!==e)return await l.fireSuccessAsync(r,JSON.stringify(n.createSuccessOutput(s,e))),n.runCleanup?.(c.toolUseId),e}catch(e){if(rL(e))return await l.fireFailureAsync(r,e.reason,e.failureType),n.runCleanup?.(c.toolUseId),n.createRejectedResult(s,e.reason);nL.warn(o,"postExecutionHooks error",{toolName:n.toolName,error:e instanceof Error?e.message:String(e)})}return n.isSuccess(t)?await l.fireSuccessAsync(r,JSON.stringify(n.createSuccessOutput(s,t))):await l.fireFailureAsync(r,n.getErrorMessage(t),n.getFailureType?.(t)??"error",n.isInterrupt?.(t)??!1),n.runCleanup?.(c.toolUseId),t}catch(e){const t=sL(jN.performance.now()-d);throw await l.fireFailureAsync(t,e instanceof Error?e.message:String(e),"error"),n.runCleanup?.(c.toolUseId),e}}}}function*uL(e,t){const r=t.hookContextCollector;e.createHookContextEvent&&void 0!==r&&0!==r.length&&(yield e.createHookContextEvent(r))}function dL(e,t){const r=BN(e),n=e.get(HN);if(r&&void 0===n)return t;const o=e=>n?.during(e)??e;return{executeHookForStep:async(e,n)=>{if(r||!function(e){return e===Rd.preToolUse||e===Rd.postToolUse||e===Rd.postToolUseFailure}(e))return o(t.executeHookForStep(e,n));await o(t.whenConfigReady())},hasFailClosedHooksForStep:(e,r)=>t.hasFailClosedHooksForStep?.(e,r)??!1,hasHooksForStep:e=>t.hasHooksForStep?.(e)??!0,whenConfigReady:()=>o(t.whenConfigReady())}}function hL(e){if("object"!=typeof e||null===e||!("code"in e))return!1;const t=e.code;return"ENOENT"===t||"ENOTDIR"===t}class pL{async readFile(e){try{return await xo.readFile(e,"utf-8")}catch(e){if("ENOENT"===e?.code)return;throw e}}async exists(e){try{return await xo.access(e),!0}catch{return!1}}async pathContainsSymlink(e,t){return async function(e,t){const r=function(e,t){const r=s.resolve(e),n=s.resolve(t),o=s.relative(n,r);if(0===o.length||".."===o||o.startsWith(`..${s.sep}`)||s.isAbsolute(o))return"unsafe";const i=o.split(s.sep).filter((e=>e.length>0)),a=[];let c=n;for(const e of i)c=s.join(c,e),a.push(c);return a}(e,t);if("unsafe"===r)return!0;for(const e of r)try{if((await(0,xo.lstat)(e)).isSymbolicLink())return!0}catch(e){if(hL(e))return!0;throw e}return!1}(e,t)}}var fL=r("../proto/dist/generated/agent/v1/hooks_pb.js");const mL=G("hook-executor",(e=>new H(e,Q("executeHookArgs"),Y("executeHookResult"))),((e,t)=>{t.register(new A(e,te("executeHookArgs"),ee("executeHookResult")))})),gL=new Set(Object.values(Rd));function wL(e){switch(e){case"completed":case"aborted":case"error":return e;default:return"error"}}function yL(e){switch(e){case"error":case"timeout":case"permission_denied":return e;default:return"error"}}function vL(e){const t=e?.toJson();return"object"!=typeof t||null===t||Array.isArray(t)?{}:t}class bL{constructor(e){this.hookExecutor=e}hasFailClosedHooksForStep(e,t){return!!function(e){return gL.has(e)}(e)&&(this.hookExecutor.hasFailClosedHooksForStep?.(e,t)??!1)}async execute(e,t){const r=t.request;if(!r)return new p.S1({response:void 0});switch(r.request.case){case"preCompact":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...mF(e),trigger:"manual"===e.trigger?"manual":"auto",context_usage_percent:e.contextUsagePercent,context_tokens:Number(e.contextTokens),context_window_size:Number(e.contextWindowSize),message_count:e.messageCount,messages_to_compact:e.messagesToCompact,is_first_compaction:e.isFirstCompaction},n=await this.hookExecutor.executeHookForStep(Rd.preCompact,t);return new p.S1({response:new p.w5({response:{case:"preCompact",value:new fL.$_({userMessage:n?.user_message})}})})}case"subagentStart":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...mF(e),subagent_id:e.subagentId,subagent_type:e.subagentType,task:e.task,parent_conversation_id:e.parentConversationId,tool_call_id:e.toolCallId,subagent_model:e.subagentModel,is_parallel_worker:e.isParallelWorker,git_branch:e.gitBranch},n=await this.hookExecutor.executeHookForStep(Rd.subagentStart,t);return new p.S1({response:new p.w5({response:{case:"subagentStart",value:new fL.W0({permission:n?.permission,userMessage:n?.user_message,additionalContext:n?.additional_context})}})})}case"subagentStop":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...mF(e),subagent_id:e.subagentId,subagent_type:e.subagentType,status:wL(e.status),duration_ms:Number(e.durationMs),summary:e.summary,parent_conversation_id:e.parentConversationId,message_count:e.messageCount,tool_call_count:e.toolCallCount,error_message:e.errorMessage,modified_files:e.modifiedFiles,git_branch:e.gitBranch,loop_count:e.loopCount??0,task:e.task,description:e.description,...e.childConversationId?{child_conversation_id:e.childConversationId}:{}},n=await this.hookExecutor.executeHookForStep(Rd.subagentStop,t);return new p.S1({response:new p.w5({response:{case:"subagentStop",value:new fL.AH({followupMessage:n?.followup_message,additionalContext:n?.additional_context})}})})}case"beforeSubmitPrompt":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(Rd.beforeSubmitPrompt,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...mF(e),prompt:e.prompt,attachments:(n=e.attachments,n.flatMap((e=>"file"===e.type||"rule"===e.type?[{type:e.type,file_path:e.filePath}]:[]))),composer_mode:e.composerMode});return new p.S1({response:new p.w5({response:{case:"beforeSubmitPrompt",value:new fL.u1({continue:t?.continue,userMessage:t?.user_message,additionalContext:t?.additional_context})}})})}case"afterAgentResponse":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(Rd.afterAgentResponse,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...mF(e),text:e.text,input_tokens:void 0!==e.inputTokens?Number(e.inputTokens):void 0,output_tokens:void 0!==e.outputTokens?Number(e.outputTokens):void 0,cache_read_tokens:void 0!==e.cacheReadTokens?Number(e.cacheReadTokens):void 0,cache_write_tokens:void 0!==e.cacheWriteTokens?Number(e.cacheWriteTokens):void 0}),new p.S1({response:new p.w5({response:{case:"afterAgentResponse",value:new fL.FW}})})}case"afterAgentThought":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(Rd.afterAgentThought,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...mF(e),text:e.text,duration_ms:void 0!==e.durationMs?Number(e.durationMs):void 0}),new p.S1({response:new p.w5({response:{case:"afterAgentThought",value:new fL.H}})})}case"stop":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(Rd.stop,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...mF(e),status:wL(e.status),loop_count:e.loopCount,input_tokens:void 0!==e.inputTokens?Number(e.inputTokens):void 0,output_tokens:void 0!==e.outputTokens?Number(e.outputTokens):void 0,cache_read_tokens:void 0!==e.cacheReadTokens?Number(e.cacheReadTokens):void 0,cache_write_tokens:void 0!==e.cacheWriteTokens?Number(e.cacheWriteTokens):void 0});return new p.S1({response:new p.w5({response:{case:"stop",value:new fL.rT({followupMessage:t?.followup_message})}})})}case"preToolUse":{if(!BN(e))return this.skipToolUseStep();const t=r.request.value,n=vL(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...mF(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,tool_use_id:t.toolUseId,cwd:t.cwd},s=await this.hookExecutor.executeHookForStep(Rd.preToolUse,o);return new p.S1({response:new p.w5({response:{case:"preToolUse",value:new fL.Wn({permission:s?.permission,userMessage:s?.user_message,agentMessage:s?.agent_message,updatedInput:s?.updated_input?JSON.stringify(s.updated_input):void 0,additionalContext:s?.additional_context})}})})}case"postToolUse":{if(!BN(e))return this.skipToolUseStep();const t=r.request.value,n=vL(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...mF(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,tool_output:t.toolOutput,duration:Number(t.durationMs),tool_use_id:t.toolUseId,cwd:t.cwd},s=await this.hookExecutor.executeHookForStep(Rd.postToolUse,o);return new p.S1({response:new p.w5({response:{case:"postToolUse",value:new fL.uB({additionalContext:s?.additional_context,updatedMcpToolOutput:void 0===s?.updated_mcp_tool_output?void 0:JSON.stringify(s.updated_mcp_tool_output)})}})})}case"postToolUseFailure":{if(!BN(e))return this.skipToolUseStep();const t=r.request.value,n=vL(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...mF(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,error_message:t.errorMessage,failure_type:yL(t.failureType),duration:Number(t.durationMs),tool_use_id:t.toolUseId,is_interrupt:t.isInterrupt},s=await this.hookExecutor.executeHookForStep(Rd.postToolUseFailure,o);return new p.S1({response:new p.w5({response:{case:"postToolUseFailure",value:new fL.U1({additionalContext:s?.additional_context})}})})}default:return new p.S1({response:void 0})}var n}async skipToolUseStep(){return await this.hookExecutor.whenConfigReady(),new p.S1({response:void 0})}}class SL{constructor(e,t,r,n){this.innerExecutor=e,this.hooksAdditionalContextPromise=t,this.teamHooksReadyPromise=r,this.hooksConfigLease=n}async execute(e,t,r){this.teamHooksReadyPromise&&await this.teamHooksReadyPromise;const n=await this.innerExecutor.execute(e,t,r),o=await this.hooksAdditionalContextPromise,s=this.hooksConfigLease?new Fr.Jy({configuredSteps:Array.from(this.hooksConfigLease.getConfiguredSteps())}):void 0;if("success"===n.result.case&&(o||s)){const e=n.result.value.requestContext,t=e?.clone()??new Fr.bb;return o&&(t.hooksAdditionalContext=o),s&&(t.hooksConfig=s),new Fr._G({result:{case:"success",value:new Fr.yW({requestContext:t,servedFromDiskCache:n.result.value.servedFromDiskCache})}})}return n}}function kL(e){return!!e&&e.type!==is.vc.INSECURE_NONE&&e.type!==is.vc.UNSPECIFIED}async function _L({hookExecutor:e,baseHookRequest:t,toolUseId:r,command:n,cwd:o,sandbox:s}){const i=await e.executeHookForStep(Rd.beforeShellExecution,{...t,command:n,cwd:o,sandbox:s,tool_use_id:r});if("deny"===i?.permission){const e=tL("Command execution",i.user_message);throw new QN(e)}if("ask"===i?.permission)return a=i.user_message,new fe.In({kind:fe.b.FORCE_PROMPT,reason:a});var a}const CL={toolName:PN,getToolCallId:cL,createToolInput:e=>{const t=e.workingDirectory||"";return{command:e.command,cwd:t}},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd)},createRejectedResult:(e,t)=>new Fo.Lt({result:{case:"rejected",value:new fe.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"BackgroundShell error";case"rejected":return e.result.value.reason||"BackgroundShell rejected";case"permissionDenied":return"Permission denied";case"sandboxUnsupported":return`Sandbox policy unsupported on this host: ${e.result.value.reason}`;default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{shell_id:t.result.value.shellId,pid:t.result.value.pid}:{success:!0},getExtraHookFields:e=>({cwd:e.workingDirectory||""}),runPreExecutionHooks:async e=>{const{ctx:t,args:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e,i=r.workingDirectory||"",a=kL(r.sandboxPolicy);WN(t,Rd.beforeShellExecution)&&$o(r,await _L({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:a}))}};class EL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,CL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const xL={toolName:"WriteShellStdin",createToolInput:e=>({shell_id:e.shellId,chars_length:e.chars.length}),createRejectedResult:(e,t)=>new Fo.nt({result:{case:"error",value:new Fo.Gv({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"WriteShellStdin error":"Unknown error",createSuccessOutput:e=>({shell_id:e.shellId,success:!0})};class PL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,xL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const RL={toolName:"ComputerUse",getToolCallId:cL,createToolInput:e=>({actions_count:e.actions.length}),createRejectedResult:(e,t)=>new Ng.ks({result:{case:"error",value:new Ng.Jb({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"ComputerUse error":"Unknown error",createSuccessOutput:(e,t)=>"success"===t.result.case?{action_count:t.result.value.actionCount,duration_ms:t.result.value.durationMs}:{success:!0}};class IL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,RL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const TL={toolName:CN,getToolCallId:cL,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Ww.Pi({result:{case:"rejected",value:new Ww.iq({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"fileNotFound":return`File not found: ${e.result.value.path}`;case"notFile":return`Not a file: ${e.result.value.path}`;case"permissionDenied":return`Permission denied: ${e.result.value.path}`;case"fileBusy":return`File busy: ${e.result.value.path}`;case"rejected":return e.result.value.reason||"Delete rejected";case"error":return e.result.value.error||"Delete error";default:return"Unknown error"}},createSuccessOutput:e=>({file_path:e.path,deleted:!0})};class AL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,TL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const $L={toolName:RN,getToolCallId:cL,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new NA.Ek({result:{case:"rejected",value:new NA.J6({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"Diagnostics error";case"rejected":return e.result.value.reason||"Diagnostics rejected";case"fileNotFound":return`File not found: ${e.result.value.path}`;case"permissionDenied":return`Permission denied: ${e.result.value.path}`;default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{file_path:e.path,diagnostics_count:t.result.value.totalDiagnostics}:{file_path:e.path,success:!0}};class ML{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,$L)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const DL={toolName:"Fetch",getToolCallId:cL,createToolInput:e=>({url:e.url}),applyUpdatedInput:(e,t)=>{"string"==typeof t.url&&(e.url=t.url)},createRejectedResult:(e,t)=>new Jw.uN({result:{case:"error",value:new Jw.fk({url:e.url,error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Fetch error":"Unknown error",createSuccessOutput:(e,t)=>"success"===t.result.case?{url:e.url,status_code:t.result.value.statusCode,content_length:t.result.value.content.length}:{url:e.url,success:!0}};class OL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,DL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const FL={toolName:xN,getToolCallId:cL,createToolInput:e=>({pattern:e.pattern,file_path:e.path,glob:e.glob,output_mode:e.outputMode}),applyUpdatedInput:(e,t)=>{"string"==typeof t.pattern&&(e.pattern=t.pattern),"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Ry.Ud({result:{case:"error",value:new Ry.ts({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Grep error":"Unknown error",createSuccessOutput:e=>({pattern:e.pattern,success:!0})};class NL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,FL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const LL={toolName:EN,getToolCallId:cL,createToolInput:e=>({file_path:e.path,ignore:e.ignore}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new yC.fv({result:{case:"rejected",value:new yC.k2({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"Ls error";case"rejected":return e.result.value.reason||"Ls rejected";case"timeout":return"Ls operation timed out";default:return"Unknown error"}},getFailureType:e=>"timeout"===e.result.case?"timeout":"error",createSuccessOutput:e=>({file_path:e.path,success:!0})};class jL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,LL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const UL=(0,d.h)("hooks-exec:mcp");function BL(e){return!!(null===e||"string"==typeof e||"boolean"==typeof e||"number"==typeof e&&Number.isFinite(e))||(Array.isArray(e)?e.every(BL):"object"==typeof e&&Object.values(e).every((e=>void 0!==e&&BL(e))))}function WL(e,t,r,n){try{return JN({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof VN)return UL.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}class HL{constructor(e,t,r,n,o){this.innerExecutor=e,this.hookExecutor=t,this.baseHookRequestExtractor=r,this.mcpLease=n,this.hooksConfigLease=o}async execute(e,t,r){if(t.smartModeApprovalOnly)return this.innerExecutor.execute(e,t,r);if(t.symbolicPathArguments.length>0&&(!0===this.hooksConfigLease?.hasHookForStep(Rd.preToolUse)||!0===this.hooksConfigLease?.hasHookForStep(Rd.beforeMCPExecution)))return new Mc.iz({result:{case:"error",value:new Mc.Nh({error:`"${iA}" arguments can't be used on this computer: hooks that inspect MCP calls are configured here, and they would not see the file's contents. Read the file and pass its contents instead.`})}});const n=dL(e,this.hookExecutor),o=this.baseHookRequestExtractor(e),s=(0,ko.randomUUID)(),i=r?.hookContextCollector??[];let a=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t?.toJson()])));const c=`MCP:${t.toolName}`;try{const r=await n.executeHookForStep(Rd.preToolUse,{...o,tool_name:c,tool_input:a,tool_use_id:s});if("deny"===r?.permission){const t=r.user_message||"MCP tool blocked by preToolUse hook";try{GN(i,JN({hookEventName:Rd.preToolUse,additionalContext:r.additional_context}))}catch(t){if(!(t instanceof VN))throw t;UL.warn(e,"preToolUse deny additional_context exceeded max size; dropping carrier",{toolName:c,actualLength:t.actualLength,maxLength:t.maxLength})}return await this.firePostToolUseFailureAsync(e,n,o,c,a,t,"permission_denied",0,s,!1,i),new Mc.iz({result:{case:"permissionDenied",value:new Mc.HQ({error:tL("MCP tool execution",t),isReadonly:!1})}})}if(r?.updated_input)try{for(const[e,n]of Object.entries(r.updated_input))if(void 0!==n){if(!BL(n))throw new TypeError("updated_input value is not JSON");t.args[e]=ve.Value.fromJson(n)}a=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t?.toJson()])))}catch(t){UL.warn(e,"Failed to merge updated_input for MCP",{error:t instanceof Error?t.message:String(t)})}GN(i,JN({hookEventName:Rd.preToolUse,additionalContext:r?.additional_context}))}catch(t){const r=n.hasFailClosedHooksForStep?.(Rd.preToolUse,c)??!1,l=t instanceof VN;if(r){const r=gN(`${l?"preToolUse additional_context exceeded max size":"preToolUse hook failed"}: ${t instanceof Error?t.message:"preToolUse hook error"}`);return await this.firePostToolUseFailureAsync(e,n,o,c,a,r,"error",0,s,!1,i),new Mc.iz({result:{case:"permissionDenied",value:new Mc.HQ({error:tL("MCP tool execution",r),isReadonly:!1})}})}UL.warn(e,l?"preToolUse additional_context exceeded max size; dropping carrier":"preToolUse hook error in MCP executor",{toolName:c,error:t instanceof Error?t.message:String(t),...l?{actualLength:t.actualLength,maxLength:t.maxLength}:{}})}const l=await(this.mcpLease?.getClient(e,t.providerIdentifier)),u=l?.config;let d;const h=u&&"url"in u&&u.url?u.url:void 0;d=void 0!==h?{url:h}:u&&"command"in u?{command:[u.command,...u.args??[]].filter(Boolean).join(" ")}:{command:t.providerIdentifier};const p={mcp_server_name:t.providerIdentifier,...void 0!==h?{mcp_server_url:h}:{}},f={...o,tool_name:t.toolName,tool_input:JSON.stringify(a),tool_use_id:s,...p,...d},m=WN(e,Rd.beforeMCPExecution)?await n.executeHookForStep(Rd.beforeMCPExecution,f):void 0;if("deny"===m?.permission){const t=tL("MCP tool execution",m.user_message);return await this.firePostToolUseFailureAsync(e,n,o,c,a,t,"permission_denied",0,s,!1,i),new Mc.iz({result:{case:"permissionDenied",value:new Mc.HQ({error:t,isReadonly:!1})}})}const g=jN.performance.now();try{const l=await this.innerExecutor.execute(e,t,r),u=sL(jN.performance.now()-g);let d="{}";if("success"===l.result.case)try{const e=l.result.value.content.map((e=>"text"===e.content.case?{type:"text",text:e.content.value.text}:"image"===e.content.case?{type:"image",data:Buffer.from(e.content.value.data).toString("base64"),mimeType:e.content.value.mimeType}:{type:"unknown"}));d=JSON.stringify({content:e,isError:l.result.value.isError})}catch(t){UL.warn(e,"Failed to serialize MCP result",{error:t instanceof Error?t.message:String(t)}),d=JSON.stringify({error:"Failed to serialize result"})}else"error"===l.result.case?d=JSON.stringify({error:l.result.value.error}):"rejected"===l.result.case?d=JSON.stringify({rejected:!0,reason:l.result.value.reason}):"permissionDenied"===l.result.case&&(d=JSON.stringify({permissionDenied:!0,error:l.result.value.error}));const h={...o,tool_name:t.toolName,tool_input:JSON.stringify(a),result_json:d,duration:u,tool_use_id:s,...p};await n.executeHookForStep(Rd.afterMCPExecution,h);const f=await this.firePostToolUse(e,n,o,c,a,d,u,s,i);if(void 0!==f?.updated_mcp_tool_output)try{const e=f.updated_mcp_tool_output,t=[];if("string"==typeof e)t.push(new Mc._Z({content:{case:"text",value:new Mc.zN({text:e})}}));else if("object"==typeof e&&null!==e&&"content"in e&&Array.isArray(e.content)){const r=e.content;for(const e of r)"object"==typeof e&&null!==e&&"type"in e&&"text"===e.type&&"text"in e?t.push(new Mc._Z({content:{case:"text",value:new Mc.zN({text:String(e.text)})}})):t.push(new Mc._Z({content:{case:"text",value:new Mc.zN({text:JSON.stringify(e)})}}))}else t.push(new Mc._Z({content:{case:"text",value:new Mc.zN({text:JSON.stringify(e)})}}));const r="object"==typeof e&&null!==e&&"isError"in e&&Boolean(e.isError);return new Mc.iz({result:{case:"success",value:new Mc.QW({content:t,isError:r})}})}catch(t){return UL.warn(e,"Failed to process updated_mcp_tool_output",{error:t instanceof Error?t.message:String(t)}),l}return l}catch(t){const r=sL(jN.performance.now()-g),l=t instanceof Error?t.message:String(t);throw await this.firePostToolUseFailureAsync(e,n,o,c,a,l,"error",r,s,!1,i),t}}async firePostToolUse(e,t,r,n,o,s,i,a,c){try{const l=await t.executeHookForStep(Rd.postToolUse,{...r,tool_name:n,tool_input:o,tool_output:s,duration:i,tool_use_id:a});return GN(c,WL(e,n,Rd.postToolUse,l?.additional_context)),l}catch(t){return void UL.warn(e,"postToolUse hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}async firePostToolUseFailureAsync(e,t,r,n,o,s,i,a,c,l,u){try{const d=await t.executeHookForStep(Rd.postToolUseFailure,{...r,tool_name:n,tool_input:o,error_message:s,failure_type:i,duration:a,tool_use_id:c,is_interrupt:l});GN(u,WL(e,n,Rd.postToolUseFailure,d?.additional_context))}catch(t){UL.warn(e,"postToolUseFailure hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}}const qL={toolName:"ListMcpResources",createToolInput:e=>({server:e.server}),applyUpdatedInput:(e,t)=>{"string"==typeof t.server&&(e.server=t.server)},createRejectedResult:(e,t)=>new Mc.kP({result:{case:"error",value:new Mc.w2({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"ListMcpResources error";case"rejected":return e.result.value.reason||"ListMcpResources rejected";default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{resources_count:t.result.value.resources.length}:{success:!0}};class zL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,qL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const GL={toolName:"FetchMcpResource",createToolInput:e=>({server:e.server,uri:e.uri,download_path:e.downloadPath}),applyUpdatedInput:(e,t)=>{"string"==typeof t.server&&(e.server=t.server),"string"==typeof t.uri&&(e.uri=t.uri),"string"==typeof t.download_path&&(e.downloadPath=t.download_path)},createRejectedResult:(e,t)=>new Mc.ZD({result:{case:"error",value:new Mc.Jx({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"ReadMcpResource error";case"rejected":return e.result.value.reason||"ReadMcpResource rejected";case"notFound":return"Resource not found";default:return"Unknown error"}},createSuccessOutput:(e,t)=>{if("success"===t.result.case){const r=t.result.value;return{uri:e.uri,name:r.name,mime_type:r.mimeType,download_path:r.downloadPath,content_type:r.content.case,content_length:"text"===r.content.case||"blob"===r.content.case?r.content.value.length:void 0}}return{uri:e.uri,success:!0}}};class VL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,GL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const KL={toolName:kN,getToolCallId:cL,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Xy.sV({result:{case:"rejected",value:new Xy.f4({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"Read error";case"rejected":return e.result.value.reason||"Read rejected";case"fileNotFound":return`File not found: ${e.result.value.path}`;case"permissionDenied":return`Permission denied: ${e.result.value.path}`;case"invalidFile":return`Invalid file: ${e.result.value.path}`;default:return"Unknown error"}},createSuccessOutput:(e,t)=>{if("success"===t.result.case){const r="content"===t.result.value.output.case?t.result.value.output.value:"";return{file_path:e.path,content_length:r.length}}return{file_path:e.path,success:!0}},runPostExecutionHooks:async e=>{const{args:t,result:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e;if("success"!==r.result.case||!1===o.hasHooksForStep?.(Rd.beforeReadFile))return;const i="content"===r.result.value.output.case?r.result.value.output.value:"",a=await async function(e,t){try{return await e()}catch(e){const r=function(e,t){return`${e??"Action"} was blocked because a configured hook failed to execute${t?`: ${t}`:"."}\n\nThis is a safety measure (fail-closed) - when hooks cannot be evaluated, the action is blocked to prevent potentially unsafe operations.\n\n${eL}`}(t,e instanceof Error?e.message:String(e));throw new YN(r,e)}}((()=>o.executeHookForStep(Rd.beforeReadFile,{...n,content:i,file_path:t.path,attachments:[],tool_use_id:s})),"File read");if("deny"===a?.permission){const e=tL("File read",a.user_message);throw new QN(e)}}};class JL{constructor(e,t,r){this.wrappedExecutor=new eA(lL(e,t,r,KL))}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const ZL={toolName:"RecordScreen",getToolCallId:cL,createToolInput:e=>({mode:e.mode,save_as_filename:e.saveAsFilename}),createRejectedResult:(e,t)=>new T$.Tj({result:{case:"failure",value:new T$.yH({error:t,kind:T$.Wg.HOOK_REJECTED})}}),isSuccess:e=>"failure"!==e.result.case,getErrorMessage:e=>"failure"===e.result.case?e.result.value.error||"RecordScreen failed":"Unknown error",createSuccessOutput:(e,t)=>({result_type:t.result.case})};class XL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,ZL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}function QL(e){return"success"===e.result.case||"failure"===e.result.case?e.result.value.stdout+e.result.value.stderr:""}const YL={toolName:PN,createToolInput:e=>{const t=e.workingDirectory||"",r=e.timeout;return{command:e.command,cwd:t,..."number"==typeof r&&r>0&&{timeout:r}}},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd),"number"==typeof t.timeout&&t.timeout>=0&&(e.timeout=t.timeout)},createRejectedResult:(e,t)=>new fe.W4({result:{case:"rejected",value:new fe.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),isSuccess:e=>"success"===e.result.case||"failure"===e.result.case&&!e.result.value.aborted,getErrorMessage:e=>{switch(e.result.case){case"timeout":return`Command timed out after ${e.result.value.timeoutMs}ms`;case"spawnError":return e.result.value.error||"Failed to spawn command";case"failure":return e.result.value.aborted?"Command was aborted":"Command failed";case"rejected":return e.result.value.reason||"Command rejected";default:return"Unknown error"}},getFailureType:e=>"timeout"===e.result.case?"timeout":"error",isInterrupt:e=>"failure"===e.result.case&&e.result.value.aborted,createSuccessOutput:(e,t)=>({output:QL(t),exitCode:"success"===t.result.case?0:1}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),runPreExecutionHooks:async e=>{const{ctx:t,args:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e,i=r.workingDirectory||"";WN(t,Rd.beforeShellExecution)&&$o(r,await _L({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:kL(r.requestedSandboxPolicy)}))},runPostExecutionHooks:async e=>{const{args:t,result:r,baseHookRequest:n,hookExecutor:o,executionDurationMs:s,toolUseId:i}=e,a=QL(r);await o.executeHookForStep(Rd.afterShellExecution,{...n,command:t.command,output:a,duration:s,sandbox:kL(t.requestedSandboxPolicy),tool_use_id:i})}};class ej{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,YL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class tj{constructor(){this.output=""}onEvent(e){"stdout"===e.event.case||"stderr"===e.event.case?this.output+=e.event.value.data:"exit"===e.event.case&&(this.exitEvent=e.event.value)}getOutput(){return this.output}isAborted(){return this.exitEvent?.aborted??!1}getExitCode(){return this.exitEvent?.code??0}}const rj={toolName:PN,createToolInput:e=>{const t=e.workingDirectory||"",r=e.timeout;return{command:e.command,cwd:t,..."number"==typeof r&&r>0&&{timeout:r}}},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd),"number"==typeof t.timeout&&t.timeout>=0&&(e.timeout=t.timeout)},createRejectedEvent:(e,t)=>new fe.FI({event:{case:"rejected",value:new fe.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),createHookContextEvent:e=>new fe.FI({event:{case:"hookContext",value:new fe.Ng({hookAdditionalContexts:[...e]})}}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),createResultCollector:()=>new tj,createSuccessOutput:(e,t)=>({output:t.getOutput(),exitCode:t.getExitCode()}),isStreamSuccess:e=>0===e.getExitCode(),getStreamErrorMessage:(e,t)=>t.getOutput().trim()||`Command failed with exit code ${t.getExitCode()}`,runPreExecutionHooks:async e=>{const{ctx:t,args:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e,i=r.workingDirectory||"",a=kL(r.requestedSandboxPolicy);WN(t,Rd.beforeShellExecution)&&$o(r,await _L({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:a}))},runPostExecutionHooks:async e=>{const{args:t,baseHookRequest:r,hookExecutor:n,collector:o,executionDurationMs:s,toolUseId:i}=e,a=kL(t.requestedSandboxPolicy);await n.executeHookForStep(Rd.afterShellExecution,{...r,command:t.command,output:o.getOutput(),duration:s,sandbox:a,tool_use_id:i})}};class nj{constructor(e,t,r){this.wrappedExecutor=function(e,t,r,n){return{async*execute(o,s,i){const a=dL(o,t),{hookContext:c,helpers:l}=iL(o,s,a,r,n,i),u=n.runPreExecutionHooks?async e=>{await n.runPreExecutionHooks(e)}:void 0,d=await aL(o,s,a,c,l,n,((e,t)=>n.createRejectedEvent(e,t)),u);if("rejected"===d.type){yield d.result;for(const e of uL(n,c))yield e;return}const h=jN.performance.now(),p=n.createResultCollector();try{for await(const t of e.execute(o,s,i))p.onEvent(t),yield t}catch(e){const t=sL(jN.performance.now()-h),r=e instanceof Error?e.message:String(e);await l.fireFailureAsync(t,r,"error");for(const e of uL(n,c))yield e;throw e}const f=sL(jN.performance.now()-h);if(n.runPostExecutionHooks)try{await n.runPostExecutionHooks({ctx:o,args:s,baseHookRequest:c.baseHookRequest,hookExecutor:a,toolInput:l.getToolInput(),toolUseId:c.toolUseId,extraHookFields:c.extraHookFields,collector:p,executionDurationMs:f})}catch(e){nL.warn(o,"postExecutionHooks error",{toolName:n.toolName,error:e instanceof Error?e.message:String(e)})}if(p.isAborted())await l.fireFailureAsync(f,"Command was aborted","error",!0);else if(n.isStreamSuccess?.(p)??1)await l.fireSuccessAsync(f,JSON.stringify(n.createSuccessOutput(s,p)));else{const e=n.getStreamErrorMessage?.(s,p)??`Command failed with exit code ${p.getExitCode()}`;await l.fireFailureAsync(f,e,"error")}for(const e of uL(n,c))yield e}}}(e,t,r,rj)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class oj{constructor(e,t,r){const n=new Map;this.wrappedExecutor=lL(e,t,r,function(e){return{toolName:_N,getToolCallId:cL,createToolInput:e=>({file_path:e.path,content:e.fileText}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new FI.v3({result:{case:"error",value:new FI.QM({path:e.path,error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Write error":"Unknown error",createSuccessOutput:e=>({file_path:e.path,success:!0}),runPreExecutionHooks:async t=>{const{args:r,hookExecutor:n,toolUseId:o}=t;if(!1===n.hasHooksForStep?.(Rd.afterFileEdit))return;let s,i=!1;try{(await(0,xo.stat)(r.path)).size>262144?i=!0:s=await Bi(r.path)}catch(e){}e.set(o,{contentBeforeWrite:s,fileTooLarge:i})},runCleanup:t=>{e.delete(t)},runPostExecutionHooks:async t=>{const{args:r,result:n,baseHookRequest:o,hookExecutor:s,toolUseId:i}=t,a=e.get(i);if("success"!==n.result.case||!1===s.hasHooksForStep?.(Rd.afterFileEdit))return;const{contentBeforeWrite:c,fileTooLarge:l}=a??{fileTooLarge:!1};let u;u=l||void 0===c?[{old_string:"",new_string:r.fileText}]:c===r.fileText?[]:function(e,t){const r=(0,dS.YB)("","",e,t,"","",{context:0,timeout:50});return void 0===r?[{old_string:"",new_string:t}]:0===r.hunks.length?[]:r.hunks.map((e=>{const t=[],r=[];for(const n of e.lines)n.startsWith("-")?t.push(n.slice(1)):n.startsWith("+")&&r.push(n.slice(1));return{old_string:t.join("\n"),new_string:r.join("\n")}}))}(c,r.fileText);const d={...o,file_path:r.path,edits:u},h=await s.executeHookForStep(Rd.afterFileEdit,d);if(r.returnFileContentAfterWrite&&void 0!==h){const e=n.result.value.path;try{const t=await Bi(e),r=Xs(t),o=Buffer.byteLength(t,"utf8");return new FI.v3({result:{case:"success",value:new FI.j6({path:n.result.value.path,linesCreated:r,fileSize:o,fileContentAfterWrite:t})}})}catch(e){return}}}}}(n))}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}function sj(e,t,r){return t===e.symbol}function ij(e,t,r){return sj(WT,e)?new ej(t,r.hookExecutor,r.baseHookRequestExtractor):sj(re,e)?new nj(t,r.hookExecutor,r.baseHookRequestExtractor):sj(GT,e)?new oj(t,r.hookExecutor,r.baseHookRequestExtractor):sj(ro,e)?new HL(t,r.hookExecutor,r.baseHookRequestExtractor,r.mcpLease,r.hooksConfigLease):sj(tA,e)||sj(rA,e)?new JL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(nA,e)?new jL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(ZT,e)?new NL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(KT,e)?new OL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(VT,e)?new AL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(oA,e)?new ML(t,r.hookExecutor,r.baseHookRequestExtractor):sj(no,e)?new zL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(oo,e)?new VL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(kA,e)?new EL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(_A,e)?new PL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(IA,e)?new IL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(AA,e)?new XL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(Dr,e)&&(r.hooksAdditionalContextPromise||r.hooksConfigLease)?new SL(t,r.hooksAdditionalContextPromise??Promise.resolve(void 0),r.teamHooksReadyPromise,r.hooksConfigLease):void 0}class aj{constructor(e,t,r,n,o,s,i){this.innerAccessor=e,this.hookExecutor=t,this.baseHookRequestExtractor=r,this.mcpLease=n,this.hooksAdditionalContextPromise=o,this.teamHooksReadyPromise=s,this.hooksConfigLease=i}get(e){const t=function(e,t){if(e.symbol===mL.symbol)return new bL(t)}(e,this.hookExecutor);return void 0!==t?t:function(e,t,r){const n=ij(e.symbol,t,r);return void 0!==n?n:t}(e,this.innerAccessor.get(e),{hookExecutor:this.hookExecutor,baseHookRequestExtractor:this.baseHookRequestExtractor,mcpLease:this.mcpLease,hooksAdditionalContextPromise:this.hooksAdditionalContextPromise,teamHooksReadyPromise:this.teamHooksReadyPromise,hooksConfigLease:this.hooksConfigLease})}*entries(){for(const[e,t]of this.innerAccessor.entries()){const r=ij(e.symbol,t,{hookExecutor:this.hookExecutor,baseHookRequestExtractor:this.baseHookRequestExtractor,mcpLease:this.mcpLease,hooksAdditionalContextPromise:this.hooksAdditionalContextPromise,teamHooksReadyPromise:this.teamHooksReadyPromise,hooksConfigLease:this.hooksConfigLease});yield[e,r??t]}const e=mL;yield[e,new bL(this.hookExecutor)]}}const cj={cursor_version:process.env.AGENT_CLI_STATIC_VERSION??"1.0.0",user_email:null};function lj(e=process.cwd()){let t=e;const r={getCwd:async()=>t,clone:e=>lj(e??t),async*execute(e,r,n={}){const o=n.workingDirectory??t;t=o;const s=function(e){return"win32"===process.platform?{executable:(0,No.oG)(),args:[...eF,"-Command",e]}:{executable:process.env.SHELL||"/bin/sh",args:["-lc",e]}}(r),i=(0,iu.spawn)(s.executable,[...s.args],{cwd:o,env:{...process.env,...n.env??{}},signal:n.signal,stdio:[!0===n.pipeStdin?"pipe":"ignore","pipe","pipe"]}),a=[];let c,l,u=!1;const d=()=>{c?.(),c=void 0},h=e=>{a.push(e),d()};for(i.on("spawn",(()=>{!0===n.pipeStdin&&h({type:"stdin_ready",stdin:i.stdin??void 0})})),i.stdout?.setEncoding("utf8"),i.stdout?.on("data",(e=>{h({type:"stdout",data:String(e)})})),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",(e=>{h({type:"stderr",data:String(e)})})),i.on("error",(e=>{l=e,u=!0,d()})),i.on("close",(e=>{h({type:"exit",code:e}),u=!0}));!u||a.length>0;)0!==a.length?yield a.shift():await new Promise((e=>{c=e}));if(void 0!==l)throw l}};return r}function uj(e,t,...r){for(const n of r){const r=t(e[n]);if(void 0!==r)return r}}function dj(e){return"string"==typeof e&&e.length>0?e:void 0}function hj(e){return"object"==typeof e&&null!==e&&"string"==typeof e.id&&"string"==typeof e.value}function pj(e){if(Array.isArray(e)&&e.every(hj))return e.map((e=>({id:e.id,value:e.value})))}class fj{constructor(e,t){this.innerAccessor=e,this.sessionHooksRuntime=t}get(e){return this.innerAccessor.get(e)}entries(){return this.innerAccessor.entries()}async dispose(){await this.sessionHooksRuntime.dispose()}}async function mj(e,t={}){const r=await new SN(new pL,function(e,t){const r=e.projectRoot??e.workingDirectory??e.workspaceRoots[0],n=t.includeProjectHooks??!0,i=t.includeUserHooks??!0;return{enterpriseConfigPath:t.includeEnterpriseHooks??1?yN():void 0,userConfigPath:i?(0,s.join)((0,o.homedir)(),".cursor","hooks.json"):void 0,claudeUserConfigPath:i?(0,s.join)((0,o.homedir)(),".claude","settings.json"):void 0,projectConfigPath:n&&void 0!==r?(0,s.join)(r,".cursor","hooks.json"):void 0,claudeProjectConfigPath:n&&void 0!==r?(0,s.join)(r,".claude","settings.json"):void 0,claudeProjectLocalConfigPath:n&&void 0!==r?(0,s.join)(r,".claude","settings.local.json"):void 0}}(e,t)).load(),n=new LN(r),i=function(e){return e.projectRoot??e.workingDirectory??e.workspaceRoots[0]??process.cwd()}(e),a=function(e){return Object.freeze({...cj,...e.globalContext??{}})}(t);return{projectDir:e.projectRoot,workspacePath:i,hooksConfig:r,hooksConfigLease:n,globalContext:a,createSessionRuntime(){const e=new NN(r,i,a,(t.createTerminalExecutor??lj)(),t.promptHookClient,void 0,void 0,{enableClaudeNestedHookSpecificOutputCompatibility:!0,commandHookPayloadTransport:(o=t.useCommandHookStdinTransport,!0===o?"stdin":"legacy")});var o;return{hookExecutor:e,hooksConfigLease:n,async dispose(){e.clearSessionEnvironment()}}},async dispose(){}}}function gj(e={}){return{createHooksRuntime:t=>mj(t.workspaceState,e)}}var wj=r("../proto/dist/generated/aiserver/v1/dashboard_service_connect.js");async function yj(e){(function(e){return"object"==typeof e&&null!==e&&"dispose"in e&&"function"==typeof e.dispose})(e)&&await e.dispose()}function vj(e={}){const t=e.getThirdPartyExtensibilityEnabled??(()=>!0),r=e.importThirdPartyPlugins??!1,n=e.includeProjectExtensibility??!0,s=e.includeUserExtensibility??!0,i=e.includeManagedSkills??!0,a=e.includePluginExtensibility??!0,c=new xy,l=(0,o.homedir)(),u=bm(l).dirPath;let d,h=!0;return{async prepareLocalExtensibility(){h=i&&await async function(e){if(!e)return!1;const t=(0,be.createClient)(wj.I,e);return"synced"===(await async function(e,t){try{const r=await t.getManagedSkills()??[],n=await OD(e,{managedSkills:[...r]});return{status:"synced",managedSkillsCount:r.length,syncResult:n}}catch(t){return ND.warn(e,"Failed to sync managed skills from source",{error:t}),{status:"fetch_failed",error:t}}}((0,b.q6)(),{getManagedSkills:async()=>(await t.getManagedSkills(new QD.X8g({}))).skills??[]})).status}(e.dashboardTransport)},async loadLocalExtensibility(o){const i=function(e){if(e.workspaceRoots.length>0)return[...e.workspaceRoots];const t=e.projectRoot??e.workingDirectory;return void 0!==t?[t]:[]}(o.workspaceState);if(0===i.length)return d=void 0,{cursorRulesService:xj(),getAgentSkills:async e=>[]};const p=(0,b.q6)(),f=e.loadNestedRules??!0,m=n?i.map((e=>new gg(p,c,e,f,t,void 0))):[],g=function(e,t){const r=bj(t);return{getAllCursorRules:async t=>Sj(await e.getAllCursorRules(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),dispose(){e.dispose()}}}(0===m.length?xj():1===m.length?m[0]:new mg(m,(()=>Lm)),{allowedRoots:n?i:[],excludedRoots:[]}),w=function(e,t){const r=bj(t);return{getAllCursorRules:async t=>Sj(await e.getAllCursorRules(t),r),getAllAgentSkills:async t=>Sj(await e.getAllAgentSkills(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),onDidChangeSkills:t=>e.onDidChangeSkills(t),dispose(){e.dispose()}}}(new yg(p,n?i:[],l,c,f,void 0,t,Promise.resolve(),"sdk"),{allowedRoots:[...n?i:[],...s?[l]:[],...h?[u]:[]],excludedRoots:h?[]:[u]}),y=n?i.map((e=>new Ig(e,t))):[],v=0===y.length?new _g:1===y.length?y[0]:new Ag(y),S=zO(o.services.pluginBootstrapOutputs),k=S&&a?new bg(p,(()=>({importThirdPartyPlugins:r})),void 0,S.pluginsService):void 0,_=S&&a?new $g((()=>({importThirdPartyPlugins:r})),S.pluginsService):void 0,C=new mg([g,w,...k?[k]:[]],(()=>Lm)),E=new gD([w,...k?[k]:[]],(()=>[]),(()=>({workspacePaths:n?i:[],userHomeDirectory:l,agentStoreSkillsDirs:[]}))),x=new Ag([v,..._?[_]:[]]);d={localRulesService:g,localSkillsService:w,localSubagentsService:v,pluginSkillsService:k,pluginSubagentsService:_,mergedCursorRulesService:C,mergedAgentSkillsService:E,mergedSubagentsService:x};const P={cursorRulesService:C,getAgentSkills:e=>E.getAllAgentSkills(e),subagentsService:x};return P},async disposeLocalExtensibility(){if(!d)return;const e=d;d=void 0,await async function(e){let t;const r=[e.mergedSubagentsService,e.mergedAgentSkillsService,e.mergedCursorRulesService,e.pluginSubagentsService,e.pluginSkillsService,e.localSubagentsService,e.localSkillsService,e.localRulesService];for(const e of r)try{await yj(e)}catch(e){t??=e}if(void 0!==t)throw t}(e)}}}function bj(e){const t=Promise.all(e.allowedRoots.map(Cj)),r=Promise.all(e.excludedRoots.map(Cj));return async e=>{const[n,o,s]=await Promise.all([Ej(e.fullPath),t,r]);return void 0!==n&&!s.some((e=>kj(n,e)))&&o.some((e=>kj(n,e)))}}async function Sj(e,t){const r=await Promise.all(e.map(t));return e.filter(((e,t)=>r[t]))}function kj(e,t){if(e===t)return!0;const r=`${t}/`;return e.startsWith(r)}function _j(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")}async function Cj(e){try{return _j(await(0,xo.realpath)(e))}catch{return _j(e)}}async function Ej(e){try{return _j(await(0,xo.realpath)(e))}catch{return}}function xj(){return{getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}}}function Pj(e,t){const r=e.releaseTag??t;if(e.releaseRepo&&e.releaseAsset&&r)return{kind:"release",releaseRepo:e.releaseRepo,releaseAsset:e.releaseAsset,releaseTag:r}}const Rj=/^[a-z][a-z0-9+.-]*:\/\/([^/?#]*)/i,Ij=/^(?:[^@/\s]+@)?([^:/\s\\]+):(?!\/\/)/,Tj=/^([a-z][a-z0-9+.-]*)::(.*)$/i,Aj=/^([a-z][a-z0-9+.-]*):\/\//i,$j=new Set(["file","git","http","https","ssh"]);function Mj(e){if(/^(?:\\\\|\/\/)[^\\/]/.test(e))throw new Error("Cursor Orbit: plugin git remote could not be validated");const t=Tj.exec(e);if(null!==t){const e=t[1].toLowerCase();if(!$j.has(e))throw new Error("Cursor Orbit: plugin git remote could not be validated");const r=t[2];if(!("http"!==e&&"https"!==e||null!==Aj.exec(r)&&URL.canParse(r)))throw new Error("Cursor Orbit: plugin git remote could not be validated");const n=Mj(r);if(0===n.length)throw new Error("Cursor Orbit: plugin git remote could not be validated");return n}const r=Aj.exec(e)?.[1].toLowerCase();if(void 0!==r&&!$j.has(r))throw new Error("Cursor Orbit: plugin git remote could not be validated");const n=Rj.exec(e)?.[1];if(void 0===n){const t=Ij.exec(e)?.[1];if(void 0===t)return[];const r=function(e){const t=/^\[([^\]]+)\]$/.exec(e)?.[1],r=t??e;if(""!==r&&!/[\[\]\s@%\/\\]/.test(r))return Dj(r)}(t);if(void 0===r)throw new Error("Cursor Orbit: plugin git remote could not be validated");return[r]}const o=[];URL.canParse(e)&&o.push(Dj(new URL(e).hostname));const s=function(e){try{return decodeURIComponent(e)}catch{return e}}(n.slice(n.lastIndexOf("@")+1)),i=`https://${s}`;if(URL.canParse(i))o.push(Dj(new URL(i).hostname));else{const e=/^\[([^\]]+)\](?::\d*)?$/.exec(s)?.[1];if(void 0===e)throw new Error("Cursor Orbit: plugin git remote could not be validated");o.push(Dj(e))}const a=o.filter((e=>""!==e));if(0===a.length)throw new Error("Cursor Orbit: plugin git remote could not be validated");return[...new Set(a)]}function Dj(e){return e.trim().toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,"")}function Oj(){const e=["-c","credential.interactive=false","-c","core.fsmonitor=false"];return"1"===process.env[Yv.K4]&&e.push("-c","http.followRedirects=false"),"win32"===process.platform&&e.push("-c","core.longpaths=true"),e}function Fj(e){return"function"==typeof e?e():e}async function Nj(e,t){const r=function(e){const t={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:void 0,VSCODE_GIT_ASKPASS_NODE:void 0,VSCODE_GIT_ASKPASS_MAIN:void 0,VSCODE_GIT_ASKPASS_EXTRA_ARGS:void 0,GCM_INTERACTIVE:"Never"};if(t.GIT_CONFIG_NOSYSTEM=void 0,!0===e?.sshBatchMode){const e=process.env.GIT_SSH_COMMAND?.trim()||"ssh";t.GIT_SSH_COMMAND=`${e} -oBatchMode=yes`}if(void 0!==e?.extraGitConfig){const r=Object.entries(e.extraGitConfig).flatMap((([e,t])=>Array.isArray(t)?t.map((t=>[e,t])):[[e,t]]));t.GIT_CONFIG_COUNT=String(r.length);for(const[e,[n,o]]of r.entries())t[`GIT_CONFIG_KEY_${e}`]=n,t[`GIT_CONFIG_VALUE_${e}`]=o}return{cwd:e?.cwd,env:t}}({cwd:t?.cwd,sshBatchMode:t?.sshBatchMode,extraGitConfig:t?.extraGitConfig}),n=function(e){return function(e,t=process.env){if("1"!==t[Yv.K4])return;const r=(0,Yv.H)(t[Yv.Zf]);for(const t of e)for(const e of Mj(t))if((0,Yv.ad)(e,r))throw new Error(`Cursor Orbit: plugin git egress to ${e} is refused`)}(e),[...Oj(),...e]}(e);try{return await uy("git",n,{...r,...void 0!==t?.timeoutMs&&{timeout:t.timeoutMs,killSignal:"SIGTERM"}})}catch(e){if("1"===process.env[Yv.K4]&&function(e){if("object"!=typeof e||null===e||!("stderr"in e))return!1;const t=e.stderr;return"string"==typeof t&&/The requested URL returned error: 3\d{2}\b/i.test(t)}(e))throw new Error("Cursor Orbit: the plugin gitUrl redirected. Ask an administrator to update gitUrl to the final URL; redirects are disabled for plugin Git operations.",{cause:e});throw e}}const Lj=/^[0-9a-f]{7,40}$/i,jj=/^[0-9a-f]{40}$/i;function Uj(e){if(void 0===e||""===e)return;const t=e.split(/\r?\n/).map((e=>{const[t,r]=e.split("\t");if(t&&r&&/^[0-9a-f]{40}$/i.test(t))return{sha:t,refName:r}})).filter((e=>void 0!==e)),r=t[0];return void 0!==r?t.find((e=>e.refName.endsWith("^{}")))?.sha??r.sha:void 0}async function Bj(e,t,r){const n=t.trim();if(jj.test(n))return{fullSha:n.toLowerCase()};if(Lj.test(n)){try{const t=await async function(e,t,r){const{stdout:n}=await Nj(["ls-remote",e,`refs/heads/${t}`,`refs/tags/${t}`,`refs/tags/${t}^{}`],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs});return Uj(n)?.toLowerCase()}(e,n,r);if(t)return{fullSha:t}}catch{}return{fullSha:n.toLowerCase()}}let o;try{if("HEAD"===n.toUpperCase()){const t=await Nj(["ls-remote","--symref",e,"HEAD"],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs}),n=Uj(t.stdout);if(!n)throw new Error(`git ls-remote did not return a resolvable commit for HEAD (${e})`);return{fullSha:n.toLowerCase(),headSymrefStdout:t.stdout}}o=(await Nj(["ls-remote",e,n],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs})).stdout}catch(t){const r=t instanceof Error?t.message:String(t),o=new Error(`Failed to resolve git ref "${n}" for ${e}: ${r}`);throw o.cause=t,o}const s=Uj(o);if(!s)throw new Error(`git ls-remote did not return a resolvable commit for ref "${n}" (${e})`);return{fullSha:s.toLowerCase()}}const Wj=Vh.map((function(e){const t=e.split("/")[0];if(void 0===t||0===t.length)throw new Error(`Marketplace manifest path has no directory: ${e}`);return t}));let Hj;function qj(e){let t=e.trim().replaceAll("\\","/");for(;t.startsWith("./");)t=t.slice(2);return t=t.replace(/\/+$/,""),""===t||"."===t||t.startsWith("/")||/^[a-zA-Z]:/.test(t)||t.split("/").some((e=>""===e||"."===e||".."===e))?null:t}function zj(e){const t=[];for(const r of e){const e=qj(r);if(null===e)return"all";t.push(e)}return t}async function Gj(e,t){const r="all"===e?"all":zj(e),n=t&&"all"!==r&&await(process.env.CURSOR_DISABLE_SPARSE_PLUGIN_CLONES?Promise.resolve(!1):(Hj??=(async()=>{try{const{stdout:e}=await Nj(["--version"]),t=function(e){const t=/git version (\d+)\.(\d+)/.exec(e);return t?{major:Number(t[1]),minor:Number(t[2])}:null}(e);return null!==t&&(t.major>2||2===t.major&&t.minor>=28)}catch{return!1}})(),Hj));return{materialize:r,sparse:n,sparseDirs:n?(o=r,[...new Set([...Wj,...o])]):[]};var o}function Vj(e){return e.toLowerCase().includes("filtering not recognized by server")}async function Kj(e,t,r){await Nj(["sparse-checkout","set","--cone","--",...t],{...r,cwd:e})}async function Jj(e){try{await(0,xo.access)((0,s.join)(e,".git","info","sparse-checkout"))}catch{return!1}try{const{stdout:t}=await Nj(["config","--bool","--get","core.sparseCheckout"],{cwd:e});return"true"===t.trim()}catch{return!1}}async function Zj(e,t,r){if("all"!==t&&0===t.length)return;if(!await Jj(e))return;const n={...r,cwd:e,sshBatchMode:!0};if("all"===t)return void await Nj(["sparse-checkout","disable"],n);const o=zj(t);"all"!==o?await Nj(["sparse-checkout","add","--",...o],n):await Nj(["sparse-checkout","disable"],n)}(0,Es.J)((function(){Hj=void 0}));const Xj=/\.git$/i,Qj=new Set(["account","dashboard"]);function Yj(e){return e.replace(Xj,"")}function eU(e){let t;try{t=decodeURIComponent(e)}catch{return}return t.length>0&&!t.includes("/")?t:void 0}function tU(e){const t=e.toLowerCase();return"github.com"===t||t.endsWith(".github.com")}function rU(e){return e.toLowerCase().split(".").includes("gitlab")}function nU(e){const t=e.toLowerCase();return"bitbucket.org"===t||"www.bitbucket.org"===t}function oU(e){const t=e.toLowerCase();return rU(e)?"GitLab":t.includes("bitbucket")?"Bitbucket":t.includes("gitea")||t.includes("codeberg")?"Gitea/Codeberg":t.includes("azure")&&t.includes("dev")?"Azure DevOps":null}function sU(e){return tU(e)?"github":rU(e)?"gitlab":nU(e)?"bitbucket":function(e){const t=e.toLowerCase();return"dev.azure.com"===t||"www.dev.azure.com"===t}(e)?"azure_devops":"generic"}function iU(e){let t;try{const r=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;t=new URL(r.includes("://")?r:`https://${r}`)}catch{return null}const r=t.hostname;let n=t.pathname.split("/").filter(Boolean);Ka(r)&&"git"===n[0]?.toLowerCase()&&(n=n.slice(1));const o=n[0];void 0!==o&&n.length>=3&&"scm"===o.toLowerCase()&&(n=n.slice(1));const s=function(e){const t=e[0],r=e[1];if(!t||!r)return;const n=Yj(r);return n?{owner:t,repo:n,hasSubpath:e.length>2}:void 0}(n);return void 0===s?null:{provider:sU(r),owner:s.owner,repo:s.repo,host:r}}function aU(e){const t=cU(e);if(null===t)return!1;const r=t.pathname.split("/").filter(Boolean),n=r[0];return void 0!==n&&r.length>=3&&"scm"===n.toLowerCase()}function cU(e){try{const t=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;return new URL(t.includes("://")?t:`https://${t}`)}catch{return null}}function lU(e){const t=e.trim();if(""===t)return{error:"URL cannot be empty"};const r=iU(t);if(null===r)return{error:"Invalid URL format. Expected: github.com/owner/repo or gitlab.com/namespace/repo"};if(rU(r.host)){const e=cU(t),r=null===e?void 0:function(e){const t=e.indexOf("-"),r=-1!==t,n=r?e.slice(0,t):[...e];if(n.length<2||n.some((e=>0===e.length)))return;const o=Yj(n[n.length-1]);return o?(n[n.length-1]=o,{repositorySegments:n,hasSpecialRouteSeparator:r}):void 0}(e.pathname.split("/").filter(Boolean));if(null===e||void 0===r)return{error:"Invalid GitLab repository URL format. Expected: https://gitlab.com/namespace/repo"};const n=e.host.replace(/^www\./i,""),o=r.repositorySegments[0],s=r.repositorySegments[r.repositorySegments.length-1];return void 0===o||void 0===s?{error:"Invalid GitLab repository URL format. Expected: https://gitlab.com/namespace/repo"}:{url:`https://${n}/${r.repositorySegments.join("/")}`,owner:o,repo:s,host:n,provider:"gitlab"}}if("bitbucket"===r.provider){const e=function(e){const t=cU(e.trim());if(null!==t&&nU(t.hostname))return function(e){const t=e[0],r=e[1];if(void 0===t||void 0===r)return;const n=eU(t),o=eU(r);if(void 0===n||void 0===o||Qj.has(n.toLowerCase()))return;const s=Yj(o);return s?{workspace:encodeURIComponent(n),repo:encodeURIComponent(s),hasSubpath:e.length>2}:void 0}(function(e){const t=e.pathname.split("/");return""===t[0]&&t.shift(),""===t[t.length-1]&&t.pop(),t}(t))}(t);if(void 0===e)return{error:"Invalid Bitbucket repository URL format. Expected: https://bitbucket.org/{workspace}/{repo}"};const n=r.host.replace(/^www\./i,"");return{url:`https://${n}/${e.workspace}/${e.repo}`,owner:e.workspace,repo:e.repo,host:n,provider:"bitbucket"}}if("azure_devops"===r.provider){const e=cU(t),n=null===e?void 0:function(e){const t=e.findIndex((e=>"_git"===e.toLowerCase()));if(t<1||t>2)return;const r=e[0],n=e[t+1];if(!r||!n)return;const o=Yj(n);if(!o)return;const s=2===t?e[1]:o;return s?{organization:r,project:s,repo:o,hasSubpath:e.length>t+2}:void 0}(e.pathname.split("/").filter(Boolean));if(null===e||void 0===n)return{error:"Invalid Azure DevOps repository URL format. Expected: https://dev.azure.com/{organization}/{project}/_git/{repo}"};const o=r.host.replace(/^www\./i,"");return{url:`https://${o}/${n.organization}/${n.project}/_git/${n.repo}`,owner:n.organization,repo:n.repo,host:o,provider:"azure_devops",project:n.project}}if(function(e){switch(e.provider){case"github":return!0;case"generic":return!Ka(e.host)&&null===oU(e.host);case"gitlab":case"bitbucket":case"azure_devops":return!1;default:return e.provider,!1}}(r)){const e=dU(r.host.replace(/^www\./i,""));return{url:`https://${e}/${aU(t)?"scm/":""}${r.owner}/${r.repo}`,owner:r.owner,repo:r.repo,host:e,provider:"github"}}const n=oU(r.host);return{error:"Only GitHub, GitLab, Bitbucket, and Azure DevOps URLs are currently supported."+(null!==n?` ${n} is not supported yet.`:"")}}function uU(e){const t=lU(e);if("error"in t)return null;switch(t.provider){case"github":return`git@${t.host}:${t.owner}/${t.repo}.git`;case"gitlab":return function(e){let t;try{t=new URL(e.url).pathname.replace(/^\//,"").replace(/\.git$/i,"")}catch{return null}if(0===t.length)return null;return`git@${e.host.replace(/:\d+$/,"")}:${t}.git`}(t);case"bitbucket":case"azure_devops":return null;default:return t.provider,null}}function dU(e){return tU(e)?"github.com":e}function hU(e){return!e.operatingSystems||0===e.operatingSystems.length||e.operatingSystems.includes(function(){const e=(0,o.platform)();return"win32"===e?"Windows":"darwin"===e?"Macintosh":"Linux"}())}function pU(e){return/[\n\r:#[\]{}&*!|>'"%@`]/.test(e)||e.startsWith(" ")||e.endsWith(" ")?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:e}const fU=new Set(["con","prn","aux","nul","com1","com2","com3","com4","com5","com6","com7","com8","com9","lpt1","lpt2","lpt3","lpt4","lpt5","lpt6","lpt7","lpt8","lpt9"]);function mU(e){const t=ih(e).replace(/[. ]+$/g,"");return""===t||"."===t||".."===t?"_":fU.has(t.toLowerCase())?`_${t}`:t}const gU=18e5,wU=6e5,yU={recursive:!0,force:!0,maxRetries:3},vU=["terminal prompts disabled","could not read username","host key verification failed","could not read from remote repository","permission denied","repository not found","user cancelled dialog","spawn git enoent","authentication failed","unable to get password from user","you do not have access to"],bU=["enotempty: directory not empty, rename","/_staging/"],SU=["upload-pack: not our ref","server does not allow request for unadvertised object"];function kU(e){const t=String(e).toLowerCase().replaceAll("\\","/");return vU.some((e=>t.includes(e)))?"user_git_access":bU.every((e=>t.includes(e)))?"local_cache_race":SU.some((e=>t.includes(e)))?"stale_pinned_ref":"infrastructure"}function _U(e){return"object"==typeof e&&null!==e&&(!0===e.killed||_U(e.cause))}function CU(e){return _U(e)?"killed_by_budget":kU(e)}function EU(e){const t=lU(e);if(!("error"in t)&&"gitlab"===t.provider){let r;try{r=new URL(t.url).pathname.replace(/^\//,"")}catch{throw new Error(`Invalid git URL: ${e}`)}const n=r.split("/").filter(Boolean).map((e=>e.toLowerCase()));if(n.length<2)throw new Error(`Invalid git URL: ${e}`);return{host:t.host.toLowerCase(),pathSegments:n}}const r=iU(e);if(null===r)throw new Error(`Invalid git URL: ${e}`);return{host:dU(r.host.replace(/^www\./i,"")).toLowerCase(),pathSegments:[r.owner.toLowerCase(),r.repo.toLowerCase()]}}const xU=new Map;class PU{constructor(e,t){this.cacheRoot=e,this.options=t,this.manifestCache=new Map}get sparsePluginClones(){return this.options?.sparsePluginClones??!1}remoteTimeoutMs(){return this.sparsePluginClones?gU:void 0}localTimeoutMs(){return this.sparsePluginClones?wU:void 0}lsRemoteTimeoutMs(){return this.sparsePluginClones?3e4:void 0}async cloneResolvedRef(e,t,r,n){const o={cwd:e,sshBatchMode:n?.sshBatchMode,extraGitConfig:{...Fj(this.options?.extraGitConfig),"safe.directory":e}},{sparse:s,sparseDirs:i}=await Gj(n?.materialize??"all",this.sparsePluginClones);await Nj(["init"],{...o,timeoutMs:this.localTimeoutMs()}),s&&await Kj(e,i,{sshBatchMode:n?.sshBatchMode,extraGitConfig:Fj(this.options?.extraGitConfig),timeoutMs:this.localTimeoutMs()});const{stderr:a}=await Nj(["fetch","--depth","1",...s?["--filter=blob:none"]:[],t,r],{...o,timeoutMs:this.remoteTimeoutMs()});return await Nj(["checkout","FETCH_HEAD"],{...o,timeoutMs:this.remoteTimeoutMs()}),{strategy:s?"sparse":"full",filterIgnoredByServer:s&&Vj(a??"")}}async createStagingDir(){const e=(0,s.join)(this.cacheRoot,"_staging",(0,ko.randomUUID)());return await(0,xo.mkdir)(e,{recursive:!0}),e}async moveToCanonicalDir(e,t){return await(0,xo.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,xo.rm)(t,yU),await(0,xo.rename)(e,t),t}async cleanStaleStagingDirs(){const e=(0,s.join)(this.cacheRoot,"_staging");try{const t=await(0,xo.readdir)(e,{withFileTypes:!0}),r=Date.now();await Promise.all(t.filter((e=>e.isDirectory())).map((async t=>{try{const n=(0,s.join)(e,t.name),o=await(0,xo.stat)(n);r-o.mtimeMs>PU.STALE_STAGING_THRESHOLD_MS&&await(0,xo.rm)(n,yU)}catch{}})))}catch{}}getLegacyCloneDir(e,t){return(0,s.join)(this.cacheRoot,mU(e),mU(t))}getCanonicalCloneDir(e,t){const{host:r,pathSegments:n}=EU(e);return(0,s.join)(this.cacheRoot,mU(r),...n.map(mU),mU(t))}getCanonicalRepoRootDir(e){const{host:t,pathSegments:r}=EU(e);return(0,s.join)(this.cacheRoot,mU(t),...r.map(mU))}async pruneSiblingCloneDirs(e,t,r){const n=this.getCanonicalRepoRootDir(e),o=mU(t);try{const e=await(0,xo.readdir)(n,{withFileTypes:!0});await Promise.all(e.filter((e=>e.isDirectory()&&e.name!==o)).map((e=>(0,xo.rm)((0,s.join)(n,e.name),yU))))}catch{}if(void 0!==r)try{await(0,xo.rm)(r,yU)}catch{}}async ensureCloned(e,t,r,n=$p,o){const s=this.serializedOnRepo(this.getCanonicalRepoRootDir(t),(()=>this.ensureClonedImpl(e,t,r,n,o?.materialize??"all")));return this.sparsePluginClones?s:(0,Nr.wj)(s,3e4,`ensureCloned timed out after 30000ms for ${t} @ ${r}`)}async ensureMaterialized(e,t,r=$p){const n=this.serializedOnRepo((0,s.dirname)(e),(async()=>{const n=performance.now();try{await Zj(e,t,{extraGitConfig:Fj(this.options?.extraGitConfig),timeoutMs:this.remoteTimeoutMs()}),r.increment("marketplace_cache_manager.ensure_materialized.success",1),r.distribution("marketplace_cache_manager.ensure_materialized.duration",performance.now()-n)}catch(o){throw r.log("error","Failed to materialize plugin directories in sparse marketplace clone",{clonePath:e,spec:"all"===t?"all":t.join(","),error:String(o),errorCategory:CU(o)}),r.increment("marketplace_cache_manager.ensure_materialized.error",1,{error_category:CU(o)}),r.distribution("marketplace_cache_manager.ensure_materialized.duration",performance.now()-n,{outcome:"error"}),o}}));return this.sparsePluginClones?n:(0,Nr.wj)(n,3e4,`ensureMaterialized timed out after 30000ms for ${e}`)}async serializedOnRepo(e,t){const r=`${this.cacheRoot}:${e}`,n=(xU.get(r)??Promise.resolve()).catch((()=>{})).then(t);xU.set(r,n);try{return await n}finally{xU.get(r)===n&&xU.delete(r)}}async ensureClonedImpl(e,t,r,n,o){n.log("info",`MarketplaceCacheManager: Ensuring cloned ${e} at ${t}@${r}`,{marketplaceId:e,gitUrl:t,ref:r});const s=r.trim();let i,a=t.startsWith("git@")||t.startsWith("ssh://")?null:uU(t);if(null!==a)try{i=(await Bj(a,s,{sshBatchMode:!0,extraGitConfig:Fj(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}catch(e){if(this.sparsePluginClones&&_U(e))throw e;n.log("debug","Failed to resolve remote ref using SSH URL, falling back to HTTPS",{gitUrl:t,ref:r,error:String(e),errorCategory:kU(e)}),a=null,i=(await Bj(t,s,{extraGitConfig:Fj(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}else i=(await Bj(t,s,{extraGitConfig:Fj(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha;const c=this.getCanonicalCloneDir(t,i),l=this.getLegacyCloneDir(e,s);n.log("info",`MarketplaceCacheManager: Resolved clone directory for ${e} at ${t}@${r} to ${c}`,{marketplaceId:e,resolvedRef:i,originalRef:s});const u=performance.now(),d=(e,t)=>{n.increment(`marketplace_cache_manager.ensure_cloned.${e}`,1,t),n.distribution(`marketplace_cache_manager.ensure_cloned.${e}.duration`,performance.now()-u,t)};if(await this.isCloneComplete(c)){await this.pruneSiblingCloneDirs(t,i,l);const e=await Jj(c);return e&&await Zj(c,o,{extraGitConfig:Fj(this.options?.extraGitConfig),timeoutMs:this.remoteTimeoutMs()}),d("cache_hit",{strategy:e?"sparse":"full"}),c}return n.increment("marketplace_cache_manager.ensure_cloned.cache_miss",1),this.cloneViaStaging(c,t,a,i,l,r,n,d,o)}async cloneViaStaging(e,t,r,n,o,s,i,a,c){await this.cleanStaleStagingDirs();const l=await this.createStagingDir();i.log("info",`MarketplaceCacheManager: Cloning ${t}@${s} into staging directory: ${l}`,{gitUrl:t,ref:s,cloneDir:e});const u=this.sparsePluginClones?setInterval((()=>{const e=new Date;(0,xo.utimes)(l,e,e).catch((()=>{}))}),PU.STAGING_HEARTBEAT_INTERVAL_MS):void 0;u?.unref?.();try{let u;if(null!==r)try{u=await this.cloneResolvedRef(l,r,n,{sshBatchMode:!0,materialize:c})}catch(e){if(this.sparsePluginClones&&_U(e))throw e;i.log("debug","Falling back to HTTPS clone due to SSH clone failure",{gitUrl:t,ref:s,error:String(e),errorCategory:CU(e)}),await(0,xo.rm)(l,yU),await(0,xo.mkdir)(l,{recursive:!0}),u=await this.cloneResolvedRef(l,t,n,{materialize:c})}else u=await this.cloneResolvedRef(l,t,n,{materialize:c});u.filterIgnoredByServer&&(i.log("warn","Server ignored --filter=blob:none; sparse clone downloaded a full pack",{gitUrl:t,ref:s}),i.increment("marketplace_cache_manager.ensure_cloned.filter_ignored_by_server",1));const d=await this.moveToCanonicalDir(l,e);return await this.pruneSiblingCloneDirs(t,n,o),a("cache_write_success",{strategy:u.strategy}),d}catch(e){const r=CU(e);throw a("error",{error_category:r}),i.log("error","Failed to clone marketplace repository via staging clone",{gitUrl:t,ref:s,error:String(e),errorCategory:r}),i.captureException(e,{error_type:"clone_marketplace_repository",error_category:r}),e}finally{void 0!==u&&clearInterval(u);try{await(0,xo.rm)(l,yU)}catch{}}}async isCloneComplete(e){try{if(!(await(0,xo.stat)(e)).isDirectory())return!1;const t=await(0,xo.readdir)(e);if(!t.includes(".git"))return!1;if(t.length>1)return!0;try{return(await(0,xo.stat)((0,s.join)(e,".git","info","sparse-checkout"))).isFile()}catch{return!1}}catch{return!1}}getPluginDir(e,t){return Sf(e,t)}async copyPluginToDir(e,t){await(0,xo.mkdir)(t,{recursive:!0}),await(0,xo.cp)(e,t,{recursive:!0,verbatimSymlinks:!0})}async readManifest(e,t={}){const r=function(e,t){return JSON.stringify({clonePath:e,repoName:t.repoName??null,fallbackId:t.fallbackId??null})}(e,t);if(this.manifestCache.has(r))return this.manifestCache.get(r)??null;const n=await async function(e,t={}){for(const r of Vh){const n=(0,s.join)(e,r);let o;try{o=await(0,xo.readFile)(n,"utf-8")}catch{continue}const i=kp(o,t);if(i.success)return i.data}return null}(e,t);return this.manifestCache.set(r,n),n}async resolvePluginPath(e,t){const r=await this.readManifest(e);if(!r)return null;const n=r.plugins.find((e=>e.name===t.toLowerCase()));if(!n)return null;const o=Cp(n.source,r.metadata?.pluginRoot);return o&&Ep(o)?o:null}async discoverPlugins(e){const t=await this.readManifest(e);return t?function(e){const t=[],r=function(e,t){const r=[];for(const n of e){const e=n.source;if("string"!=typeof e)switch(e.source){case"github":r.push({entry:n,kind:"external-github",externalUrl:`https://github.com/${e.repo}.git`,externalRef:e.ref,externalSha:e.sha,effectiveRef:e.sha??e.ref});break;case"url":r.push({entry:n,kind:"external-url",externalUrl:e.url,externalRef:e.ref,externalSha:e.sha,effectiveRef:e.sha??e.ref});break;case"git-subdir":r.push({entry:n,kind:"external-git-subdir",externalUrl:e.url,externalRef:e.ref,externalSha:e.sha,effectiveRef:e.sha??e.ref,subdirPath:e.path})}else{const o=Cp(e,t);null!==o?r.push({entry:n,kind:"local",localPath:o}):r.push({entry:n,kind:"unresolvable",rawSource:e})}}return r}(e.plugins,e.metadata?.pluginRoot);for(const e of r){const{name:r,displayName:n,description:o,version:s}=e.entry,i={name:r,displayName:n,description:o,version:s};switch(e.kind){case"local":Ep(e.localPath)&&t.push({...i,sourceType:"local",gitPath:e.localPath});break;case"external-github":t.push({...i,sourceType:"github",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha});break;case"external-url":t.push({...i,sourceType:"url",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha});break;case"external-git-subdir":t.push({...i,sourceType:"git-subdir",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha,subdirPath:e.subdirPath})}}return t}(t):[]}}PU.STALE_STAGING_THRESHOLD_MS=3e5,PU.STAGING_HEARTBEAT_INTERVAL_MS=6e4;const RU=(0,Vs.debuglog)("cursor-plugins");function IU(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function TU(e){return IU(e)?e:void 0}function AU(e){const t=e.name?.trim();return void 0!==t&&t.length>0?t:e.pluginId}function $U(e,t){return void 0!==e?.marketplace?e.marketplace:void 0!==e?.marketplaceId?(t??[]).find((t=>void 0!==t.id&&String(t.id)===String(e.marketplaceId))):void 0}function MU(e,t){const r=t?.distributionGitUrl?.trim();return r?t?.gitUrl&&!qU(e,t.gitUrl)?e:r:e}function DU(e){return e?.distributionGitUrl?.trim()||e?.gitUrl}function OU(e,t){if(e.pinnedGitRef)return e.pinnedGitRef;if(e.plugin?.gitRef)return e.plugin.gitRef;const r=$U(e.plugin,t),n=e.plugin?.gitUrl,o=r?.gitUrl;return n&&o&&n!==o||!r?.gitRef?"main":r.gitRef}const FU="backend-git://";function NU(e,t,r){const n=r?`#${encodeURIComponent(r)}`:"";return`${FU}${encodeURIComponent(e)}@${encodeURIComponent(t)}${n}`}function LU(e){if(!e.startsWith(FU))return null;const t=e.slice(14),r=t.indexOf("#"),n=r>=0?t.slice(0,r):t,o=r>=0?t.slice(r+1):void 0,s=n.lastIndexOf("@");return s<0?null:{gitUrl:decodeURIComponent(n.slice(0,s)),ref:decodeURIComponent(n.slice(s+1)),gitPath:o?decodeURIComponent(o):void 0}}const jU="backend-release://";function UU(e){const t=e.tag?`@${encodeURIComponent(e.tag)}`:"";return`${jU}${encodeURIComponent(e.repo)}#${encodeURIComponent(e.asset)}${t}`}function BU(e){if(!e.startsWith(jU))return null;const t=e.slice(18),r=t.indexOf("#");if(r<0)return null;const n=decodeURIComponent(t.slice(0,r)),o=t.slice(r+1),s=o.lastIndexOf("@");return{repo:n,asset:s>=0?decodeURIComponent(o.slice(0,s)):decodeURIComponent(o),tag:s>=0?decodeURIComponent(o.slice(s+1)):void 0}}const WU=/^[0-9a-f]{7,40}$/i;function HU(e){let t;try{t=EU(e)}catch{return null}return`${t.host}\0${t.pathSegments.join("\0")}`}function qU(e,t){if(e.trim()===t.trim())return!0;const r=HU(e),n=HU(t);return null!==r&&r===n}const zU=104857600;async function GU(e,t,r,n,i,a){const c=await async function(e){const{repo:t,asset:r,tag:n}=e,{apiBase:o,ownerRepo:s,host:i}=function(e){const t=e.split("/"),r=t[0],n=t[1],o=t[2];if(3===t.length&&void 0!==r&&void 0!==n&&void 0!==o)return{apiBase:`https://${r}/api/v3`,ownerRepo:`${n}/${o}`,host:r};if(2===t.length)return{apiBase:"https://api.github.com",ownerRepo:e,host:"github.com"};throw new Error(`Invalid release repo format: ${e}`)}(t),a="github.com"===i&&void 0!==e.githubToken&&e.githubToken.length>0?{Authorization:`token ${e.githubToken}`}:{},c=n?`${o}/repos/${s}/releases/tags/${encodeURIComponent(n)}`:`${o}/repos/${s}/releases/latest`,l=await fetch(c,{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"CursorPluginInstaller",...a}});if(!l.ok)throw new Error(`Failed to fetch release from ${c}: ${l.status} ${l.statusText}`);const u=await l.json();if(!(IU(d=u)&&Array.isArray(d.assets)&&d.assets.every((e=>IU(e)&&"string"==typeof e.name&&"string"==typeof e.browser_download_url&&"number"==typeof e.size))))throw new Error(`Release payload from ${c} did not include assets`);var d;const h=u,p=h.assets.find((e=>e.name===r));if(!p){const e=h.assets.map((e=>e.name)).join(", ");throw new Error(`Release asset "${r}" not found. Available assets: ${e}`)}if(p.size>zU)throw new Error(`Release asset "${r}" exceeds maximum size of 104857600 bytes (actual: ${p.size})`);const f=new URL(p.browser_download_url);if("https:"!==f.protocol||!VU(f.hostname,i))throw new Error(`Refusing to download release asset from untrusted host: ${f.hostname}`);const m=await fetch(p.browser_download_url,{headers:{"User-Agent":"CursorPluginInstaller",Accept:"application/octet-stream",...a}});if(!m.ok)throw new Error(`Failed to download release asset: ${m.status} ${m.statusText}`);if(m.url){const e=new URL(m.url);if("https:"!==e.protocol||!VU(e.hostname,i))throw new Error(`Refusing to download release asset: redirected to untrusted host: ${e.hostname}`)}const g=Buffer.from(await m.arrayBuffer());if(g.byteLength>zU)throw new Error(`Release asset "${r}" actual download size exceeds maximum of 104857600 bytes (actual: ${g.byteLength})`);if(e.expectedSha256){const t=(0,ko.createHash)("sha256").update(g).digest("hex");if(t!==e.expectedSha256)throw new Error(`Release asset "${r}" integrity check failed: expected SHA-256 ${e.expectedSha256}, got ${t}`)}return g}({repo:e,asset:t,tag:r,expectedSha256:i,githubToken:a}),l=c.byteLength;await(0,xo.mkdir)(n,{recursive:!0});const u=await(0,xo.mkdtemp)((0,s.join)((0,o.tmpdir)(),"release-asset-")),d=(0,s.join)(u,"asset.tar.gz"),h=(0,s.join)(u,"extracted");try{await(0,xo.writeFile)(d,c),await(0,xo.mkdir)(h,{recursive:!0});let e=0,t=0;await ah.x({file:d,cwd:h,onReadEntry:r=>{if(t++,t>5e4)throw new Error("Release archive contains too many files (>50000).");if(e+=r.size,e>524288e3)throw new Error("Release archive uncompressed size exceeds maximum of 524288000 bytes.");if(l>0&&e/l>100)throw new Error("Release archive has suspicious compression ratio (>100x).")}});const r=await(0,xo.readdir)(h,{withFileTypes:!0}),o=r.filter((e=>e.isDirectory())),i=r.filter((e=>e.isFile()));let a=h;const u=o[0];if(1===o.length&&0===i.length&&void 0!==u){const e=(0,s.join)(h,u.name);(await(0,xo.readdir)(e)).some((e=>Gh.includes(e)))&&(a=e)}const p=await(0,xo.readdir)(a);await Promise.all(p.map((e=>(0,xo.cp)((0,s.join)(a,e),(0,s.join)(n,e),{recursive:!0,verbatimSymlinks:!0}))))}finally{await(0,xo.rm)(u,{recursive:!0,force:!0}).catch((()=>{}))}}function VU(e,t){return!(e!==t&&!e.endsWith(".githubusercontent.com"))||("github.com"===t?"github.com"===e:e.endsWith(`.${t}`))}class KU{constructor(e,t,r,n,o){this.getEffectiveUserPlugins=e;const s="string"==typeof t||void 0===t?{marketplaceCacheRoot:t,pluginLogger:r,marketplaceCacheOptions:n,listOptions:o}:t,i=s.marketplaceCacheOptions??n;this.pluginLogger=s.pluginLogger??r??$p,this.extraGitConfig=s.extraGitConfig,this.awaitAuthReady=s.awaitAuthReady,this.githubToken=s.githubToken,this.downloadPluginContent=s.downloadPluginContent,this.contentRetries=s.contentRetries??(new Eh).forListing(""),this.sparsePluginClones=s.sparsePluginClones??!1,this.marketplaceCache=s.marketplaceCacheRoot?new PU(s.marketplaceCacheRoot,{...i,extraGitConfig:i?.extraGitConfig??s.extraGitConfig,sparsePluginClones:this.sparsePluginClones}):void 0;const a=s.listOptions??o;this.allowedMarketplaceNames=a?.allowedMarketplaceNames?new Set(a.allowedMarketplaceNames):void 0,this.enableInlinePlugins=a?.enableInlinePlugins??!1}isMarketplaceAllowed(e){return void 0===this.allowedMarketplaceNames||void 0!==e?.name&&this.allowedMarketplaceNames.has(e.name)}async listEnabledPlugins(e,t){const r=await this.getEffectiveUserPlugins(),n=r.plugins??[],o=r.marketplaces??[],s=[],i=[],a=new Map,c=async(e,t)=>{const r=`${e}\0${t}`;let n=a.get(r);if(!n){const o=Fj(this.extraGitConfig),s=this.sparsePluginClones?3e4:void 0,i=e.startsWith("git@")||e.startsWith("ssh://")?null:uU(e),c=async(e,r)=>{const n={};return r&&(n.sshBatchMode=!0),void 0!==o&&(n.extraGitConfig=o),void 0!==s&&(n.timeoutMs=s),(Object.keys(n).length>0?await Bj(e,t,n):await Bj(e,t)).fullSha};if(null!==i)try{n=await c(i,!0)}catch(t){if(this.sparsePluginClones&&_U(t))throw t;n=await c(e,!1)}else n=await c(e,!1);a.set(r,n)}return n},l=async e=>{const{preferredGitUrl:t,sourceGitUrl:r,gitRef:n,pluginId:o}=e;if(t!==r){void 0!==this.awaitAuthReady&&await this.awaitAuthReady();const e=`${t}\0${n}`,s=!a.has(e);let i;s&&this.pluginLogger.increment("marketplace.origin_distribution.fetch",1);try{i={sha:await c(t,n),gitUrl:t}}catch(e){s&&this.pluginLogger.increment("marketplace.origin_distribution.fetch.error",1),this.pluginLogger.captureException(e,{error_type:"distribution_url_fallback"}),this.pluginLogger.log("warn",`Distribution mirror ${t}@${n} unavailable (not synced yet or unreachable); falling back to source ${r}`,{pluginId:o,preferredGitUrl:t,sourceGitUrl:r,gitRef:n,error:String(e)})}if(void 0!==i){if(s)try{this.pluginLogger.log("info",`Resolved plugin ${o} from Origin distribution mirror ${t}@${n}`,{pluginId:o,preferredGitUrl:t,gitRef:n})}catch{}return i}}return{sha:await c(r,n),gitUrl:r}};this.contentRetries.startLoad();for(const e of n){if(!e.isEnabled||!e.plugin?.name)continue;const t=e.plugin,r=$U(t,o);if(!this.isMarketplaceAllowed(r)){this.pluginLogger.log("info",`Skipping plugin ${t.name} because marketplace ${r?.name??""} is not allowed`,{pluginId:t.name,marketplaceName:r?.name,allowedMarketplaceNames:void 0!==this.allowedMarketplaceNames?Array.from(this.allowedMarketplaceNames):void 0});continue}const n=AU({name:t.name,pluginId:void 0!==t.id?String(t.id):t.name??""}),a=n;if(void 0!==t.backendContent&&null!==t.backendContent){const t=this.listBackendContentPlugin(e,r,n);"entry"in t?s.push(t.entry):i.push(t.failure);continue}if(!t.gitUrl){if(!this.enableInlinePlugins){this.pluginLogger.log("info",`Skipping plugin ${n} without gitUrl (enableInlinePlugins=false)`,{pluginId:a});continue}const o=e.inlineContentJson;if(!o){this.pluginLogger.log("info",`Skipping DB-inline plugin ${n}: no inline content provided`,{pluginId:a});continue}const i=(0,ko.createHash)("sha256").update(`${t.id??"0"}:${t.updatedAt??"0"}`).digest("hex").slice(0,40),c=r?.name?{id:void 0!==r.id?`${r.name}-${r.id}`:`${r.name}-inline`,name:r.name}:void 0;this.pluginLogger.log("info",`BackendMarketplaceClient: Adding DB-inline plugin: ${a}`,{pluginId:a,marketplaceId:c?.id??"unknown",version:i}),s.push({pluginId:a,pluginDbId:void 0!==t.id?String(t.id):void 0,configuredVariables:TU(e.configuredVariables),isTeamRequired:e.isTeamRequired,name:n,version:i,downloadUrl:`inline://${t.id??a}`,marketplaceDbId:void 0!==r?.id?String(r.id):void 0,marketplace:c,inlineContentJson:o});continue}const c=t.gitUrl,u=MU(c,r),d=OU(e,o),h=Pj(t,d),p=r?.gitRef??d;let f,m,g=u;try{if(void 0!==h)f=`release/${h.releaseTag}`;else{const e=await l({preferredGitUrl:u,sourceGitUrl:c,gitRef:d,pluginId:a});f=e.sha,g=e.gitUrl}}catch(e){this.pluginLogger.captureException(e,{error_type:"resolve_version_sha"}),this.pluginLogger.log("error",`Failed to resolve version for plugin ${n}@${d}, skipping plugin`,{pluginId:a,ref:d,error:String(e)});const o=e instanceof Error?e.message:String(e);i.push({pluginName:n,pluginId:a,pluginDbId:void 0!==t.id?String(t.id):void 0,marketplaceName:r?.name,errorMessage:o,errorType:/timed?\s*out/i.test(o)?"timeout":"clone"});continue}m=void 0!==h?UU({repo:h.releaseRepo,asset:h.releaseAsset,tag:h.releaseTag}):NU(g,d,t.gitPath??void 0);const w=DU(r);let y=w,v=r?.gitUrl,b=p;if(r?.gitUrl&&w){const e=qU(c,r.gitUrl),t=e?g:w,o=e?c:r.gitUrl,s=e?d:p;v=o;try{const e=await l({preferredGitUrl:t,sourceGitUrl:o,gitRef:s,pluginId:a});b=e.sha,y=e.gitUrl}catch(e){this.pluginLogger.captureException(e,{error_type:"resolve_marketplace_cache_ref"}),this.pluginLogger.log("warn",`Failed to resolve marketplace cache ref for plugin ${n} from ${t}@${s}, falling back to raw ref`,{pluginId:a,cacheRepoUrl:t,cacheRef:s,error:String(e)}),y=o}}const S=r?.name?{id:void 0!==r.id?`${r.name}-${r.id}`:`${r.name}-${encodeURIComponent(r.gitUrl??"project")}`,name:r.name,...y&&{gitUrl:y,gitRef:b}}:void 0,k=void 0!==h||g===c&&y===v?void 0:{downloadUrl:NU(c,d,t.gitPath??void 0),marketplaceGitUrl:v};this.pluginLogger.log("info",`BackendMarketplaceClient: Adding enabled plugin: ${a} from ${b} at ${t.gitPath}`,{pluginId:a,marketplaceId:S?.id??"unknown",gitPath:t.gitPath??void 0,gitRef:b}),s.push({pluginId:a,pluginDbId:void 0!==t.id?String(t.id):void 0,configuredVariables:TU(e.configuredVariables),isTeamRequired:e.isTeamRequired,name:n,version:f,downloadUrl:m,marketplaceDbId:void 0!==r?.id?String(r.id):void 0,marketplace:S,gitPath:t.gitPath??void 0,isOriginBacked:void 0===h&&g!==c||void 0,originSourceFallback:k})}return{plugins:s,listFailures:i}}isBackendContentRetryDue(){return this.contentRetries.isRetryDue()}allowImmediateBackendContentRetry(){this.contentRetries.allowImmediateRetry()}listBackendContentPlugin(e,t,r){const n=xh(e.plugin?.id),o=function(e){const{revision:t}=e;return"string"==typeof t&&wh.test(t)?{revision:t}:{invalid:"revision"}}(e.plugin?.backendContent??{}),s=void 0===n?"plugin_id":"invalid"in o?o.invalid:void 0;if(void 0===n||"invalid"in o)return this.pluginLogger.log("error",`Skipping plugin ${r}: the listing's backend content has an unusable ${s}`,{pluginId:r,invalidField:s}),this.pluginLogger.increment("backend_marketplace_client.backend_content.list.invalid",1),{failure:{pluginName:r,pluginId:r,pluginDbId:n,marketplaceName:t?.name,errorMessage:`Plugin ${JSON.stringify(r)} could not be installed: the server listed it with details this client does not accept.`,errorType:"install"}};const i=t?.name?{id:void 0!==t.id?`${t.name}-${t.id}`:`${t.name}-backend-content`,name:t.name}:void 0;return this.pluginLogger.log("info",`BackendMarketplaceClient: Adding backend-served plugin: ${r}`,{pluginId:r,marketplaceId:i?.id??"unknown",revision:o.revision}),{entry:{pluginId:r,pluginDbId:n,configuredVariables:TU(e.configuredVariables),isTeamRequired:e.isTeamRequired,name:r,version:Rh(o.revision),downloadUrl:(a={pluginDbId:n,revision:o.revision},`${bh}${a.pluginDbId}@${a.revision}`),marketplaceDbId:void 0!==t?.id?String(t.id):void 0,marketplace:i,backendContent:o}};var a}async relistPlugin(e){if(void 0===e.backendContent||void 0===e.pluginDbId)return;const t=await this.getEffectiveUserPlugins(),r=(t.plugins??[]).find((t=>!0===t.isEnabled&&xh(t.plugin?.id)===e.pluginDbId)),n=r?.plugin;if(void 0===r||!n?.name||void 0===n.backendContent||null===n.backendContent)return;const o=$U(n,t.marketplaces??[]);if(!this.isMarketplaceAllowed(o))return;const s=this.listBackendContentPlugin(r,o,e.name);return"entry"in s&&s.entry.version!==e.version?s.entry:void 0}async installBackendContentPlugin(e,t){const r=e.backendContent,n=xh(e.pluginDbId);if(void 0===r||void 0===n)throw new Error(`Plugin ${JSON.stringify(e.name)} has no backend content to install`);const o={pluginDbId:n,revision:r.revision},s=this.contentRetries.heldFailure(o);if(void 0!==s)throw Ih(s,e.name);const i=performance.now();let a="success";try{await Ah({download:this.downloadPluginContent,pluginDbId:n,pluginName:e.name,content:r,targetDir:t}),this.contentRetries.recordAttempt(o)}catch(e){throw a=e instanceof mh?e.reason:"unknown",this.contentRetries.recordAttempt({...o,error:e}),e}finally{this.pluginLogger.increment("backend_marketplace_client.backend_content.install",1,{outcome:a}),this.pluginLogger.distribution("backend_marketplace_client.backend_content.install.duration",performance.now()-i,{outcome:a})}this.pluginLogger.log("info",`Installed backend-served plugin ${e.pluginId}`,{pluginId:e.pluginId,revision:r.revision})}isDirectInstallSameFetch(e){const t=e.marketplace;if(!t?.gitUrl||!t.gitRef)return!1;const r=LU(e.downloadUrl);return!(!r||!qU(r.gitUrl,t.gitUrl)||r.ref!==t.gitRef&&e.version!==t.gitRef)}async installPlugin(e,t){if(void 0!==e.backendContent||Ph(e.downloadUrl))await this.installBackendContentPlugin(e,t);else if(e.inlineContentJson)await async function(e){const{targetDir:t,inlineContentJson:r,pluginName:n}=e,o=JSON.parse(r);await(0,xo.mkdir)(t,{recursive:!0});const i={};if(o.rules&&o.rules.length>0){const e=(0,s.join)(t,"rules");await(0,xo.mkdir)(e,{recursive:!0});const r=[];for(const t of o.rules){if(!t.content)continue;if(!1===t.isActive)continue;const n=`${ih(t.name)}.md`,o=[];o.push(`description: ${pU(t.name)}`),t.globs&&t.globs.length>0&&o.push(`globs: ${pU(t.globs.join(", "))}`),o.push(`alwaysApply: ${!0===t.isRequired}`);const i=`---\n${o.join("\n")}\n---\n\n`;await(0,xo.writeFile)((0,s.join)(e,n),i+t.content,"utf-8"),r.push(`rules/${n}`)}r.length>0&&(i.rules=r)}if(o.commands&&o.commands.length>0){const e=(0,s.join)(t,"commands");await(0,xo.mkdir)(e,{recursive:!0});const r=[];for(const t of o.commands){if(!t.content)continue;if(!1===t.isActive)continue;const n=`${ih(t.name)}.md`,o=t.description?`---\ndescription: ${pU(t.description)}\n---\n\n`:"";await(0,xo.writeFile)((0,s.join)(e,n),o+t.content,"utf-8"),r.push(`commands/${n}`)}r.length>0&&(i.commands=r)}if(o.hooks&&o.hooks.length>0){const e=(0,s.join)(t,"hooks");await(0,xo.mkdir)(e,{recursive:!0});const r={};for(const e of o.hooks){const t=e.hookStep;t&&!1!==e.isActive&&hU(e)&&(r[t]||(r[t]=[]),"prompt"===e.hookType?r[t].push({type:"prompt",prompt:e.promptContent??"",...e.promptModel?{model:e.promptModel}:{}}):r[t].push({type:"command",command:e.scriptContent??""}))}await(0,xo.writeFile)((0,s.join)(e,"hooks.json"),JSON.stringify({version:1,hooks:r},null,2),"utf-8")}if(o.mcpServers&&o.mcpServers.length>0){const e={};for(const t of o.mcpServers)t.config&&(e[t.name]=t.config);Object.keys(e).length>0&&await(0,xo.writeFile)((0,s.join)(t,".mcp.json"),JSON.stringify({mcpServers:e},null,2),"utf-8")}const a={name:n,...i},c=(0,s.join)(t,".cursor-plugin");await(0,xo.mkdir)(c,{recursive:!0}),await(0,xo.writeFile)((0,s.join)(c,"plugin.json"),JSON.stringify(a,null,2),"utf-8")}({targetDir:t,inlineContentJson:e.inlineContentJson,pluginName:e.name});else{e.isOriginBacked&&void 0!==this.awaitAuthReady&&await this.awaitAuthReady();try{return void await this.installFromEntryUrls(e,t)}catch(r){const n=function(e){const t=e.originSourceFallback;if(void 0===t)return;let r=e.marketplace;if(void 0!==r)if(void 0!==t.marketplaceGitUrl)r={...r,gitUrl:t.marketplaceGitUrl};else{const{gitUrl:e,gitRef:t,...n}=r;r=n}return{...e,downloadUrl:t.downloadUrl,marketplace:r,isOriginBacked:void 0,originSourceFallback:void 0}}(e);if(void 0===n)throw r;this.pluginLogger.captureException(r,{error_type:"install_plugin_from_origin_distribution"}),this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from the Origin distribution mirror, falling back to the source repo`,{pluginId:e.pluginId,version:e.version,sourceDownloadUrl:n.downloadUrl,sourceMarketplaceGitUrl:n.marketplace?.gitUrl,error:String(r)}),this.pluginLogger.increment("marketplace.origin_distribution.install.source_fallback",1),await(0,xo.rm)(t,{recursive:!0,force:!0});try{await this.installFromEntryUrls(n,t)}catch(e){throw this.pluginLogger.increment("marketplace.origin_distribution.install.source_fallback.error",1),e}}}}async installFromEntryUrls(e,t){if(null===BU(e.downloadUrl))try{if(await this.tryInstallFromMarketplaceCache(e,t))return void this.emitOriginLoadIfApplicable(e)}catch(t){if(this.pluginLogger.captureException(t,{error_type:"install_plugin_from_marketplace_cache"}),this.sparsePluginClones&&this.isDirectInstallSameFetch(e)&&_U(t))throw this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from marketplace cache; skipping direct install fallback because it would repeat the identical fetch`,{pluginId:e.pluginId,version:e.version,error:String(t)}),t;this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from marketplace cache, falling back to direct install`,{pluginId:e.pluginId,version:e.version,error:String(t)})}await async function(e,t,r=$p,n,i){const a=i?.sparsePluginClones??!1,c=a?gU:void 0,l=BU(e.downloadUrl);if(l){if(e.gitPath){const r=await(0,xo.mkdtemp)((0,s.join)((0,o.tmpdir)(),"release-plugin-"));try{await GU(l.repo,l.asset,l.tag,r,i?.expectedReleaseAssetSha256,i?.githubToken);const n=Sf(r,e.gitPath);await(0,xo.mkdir)(t,{recursive:!0}),await(0,xo.cp)(n,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,xo.rm)(r,{recursive:!0,force:!0}).catch((()=>{}))}}else await GU(l.repo,l.asset,l.tag,t,i?.expectedReleaseAssetSha256,i?.githubToken);return}const u=LU(e.downloadUrl);if(!u)throw new Error(`Invalid download URL format for plugin ${e.pluginId}: ${e.downloadUrl}`);const d=await(0,xo.mkdtemp)((0,s.join)((0,o.tmpdir)(),"backend-plugin-"));try{let o;if(await async function(e,t,r,n=$p,o,s="all",i=!1){const a=performance.now(),c=WU.test(t),l="HEAD"===t.toUpperCase(),u={...o,"safe.directory":r},d=i?gU:void 0,h=i?wU:void 0,{sparse:p,sparseDirs:f}=await Gj(s,i),m=p?["--filter=blob:none","--sparse"]:[],g=!!p||void 0,w=async e=>{p&&await Kj(r,f,{extraGitConfig:u,timeoutMs:e,sshBatchMode:!0})},y=async(e,n)=>{let o;return l?(({stderr:o}=await Nj(["clone","--depth","1",...m,e,r],{extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await w(d)):c?(await Nj(["init"],{cwd:r,extraGitConfig:u,timeoutMs:h}),await Nj(["remote","add","origin",e],{cwd:r,extraGitConfig:u,timeoutMs:h}),await w(h),({stderr:o}=await Nj(["fetch","--depth","1",...p?["--filter=blob:none"]:[],"origin",t],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await Nj(["checkout","FETCH_HEAD"],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})):(({stderr:o}=await Nj(["clone","--depth","1","--branch",t,...m,e,r],{extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await w(d)),o},v=e.startsWith("git@")||e.startsWith("ssh://")?null:uU(e);let b;if(null!==v)try{b=await y(v,!0)}catch(t){if(i&&_U(t))throw t;await(0,xo.rm)(r,{recursive:!0,force:!0}),await(0,xo.mkdir)(r,{recursive:!0}),b=await y(e,g)}else b=await y(e,g);p&&Vj(b)&&(n.log("warn",`shallowClone: server ignored --filter=blob:none for ${e}; sparse clone downloaded a full pack`),n.increment("backend_marketplace_client.shallow_clone.filter_ignored_by_server",1));const S=(performance.now()-a).toFixed(1);RU("shallowClone %s@%s completed in %sms",e,t,S),n.log("info",`shallowClone ${e}@${t} completed in ${S}ms (${p?"sparse":"full"})`)}(u.gitUrl,u.ref,d,r,n,u.gitPath?zj([u.gitPath]):[],a),u.gitPath)o=Sf(d,u.gitPath);else{const t=await async function(e,t){for(const r of Vh){const n=(0,s.join)(e,r);let o;try{o=await(0,xo.readFile)(n,"utf-8")}catch{continue}const i=kp(o);if(!i.success)return{type:"manifest-unresolved",reason:`Invalid marketplace manifest at ${r}: ${i.error}`};const a=i.data,c=a.plugins.find((e=>e.name===t.toLowerCase()));if(!c)return{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} not found in ${r}`};if("string"!=typeof c.source&&"git-subdir"===c.source.source)return{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} uses unsupported git-subdir source`};const l=Cp(c.source,a.metadata?.pluginRoot);return l&&Ep(l)?{type:"resolved",gitPath:l}:{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} has unresolved or unsafe source path`}}return{type:"no-manifest"}}(d,e.name);if("resolved"===t.type)await Zj(d,zj([t.gitPath]),{extraGitConfig:n,timeoutMs:c}),o=Sf(d,t.gitPath);else{if("manifest-unresolved"===t.type)throw new Error(`Unable to install plugin ${JSON.stringify(e.name)} without gitPath: ${t.reason}`);await Zj(d,"all",{extraGitConfig:n,timeoutMs:c}),o=d}}await(0,xo.mkdir)(t,{recursive:!0}),await(0,xo.cp)(o,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,xo.rm)(d,{recursive:!0,force:!0}).catch((()=>{}))}}(e,t,this.pluginLogger,Fj(this.extraGitConfig),{githubToken:this.githubToken,sparsePluginClones:this.sparsePluginClones}),this.emitOriginLoadIfApplicable(e)}emitOriginLoadIfApplicable(e){if(e.isOriginBacked)try{this.pluginLogger.increment("marketplace.origin_distribution.load",1),this.pluginLogger.log("info",`Loaded plugin ${e.pluginId} from Origin distribution (fetch complete)`,{pluginId:e.pluginId})}catch{}}async prewarmMarketplaceClones(e){const t=this.marketplaceCache;if(!t)return;const r=new Map;for(const t of e){const e=t.marketplace;if(!e?.gitUrl)continue;const n=e.gitRef??"main",o=`${e.id}\0${e.gitUrl}\0${n}`;let s=r.get(o);void 0===s&&(s={marketplaceId:e.id,gitUrl:e.gitUrl,gitRef:n,gitPaths:[]},r.set(o,s)),t.gitPath&&s.gitPaths.push(t.gitPath)}for(const e of r.values()){const r=zj(e.gitPaths),n=performance.now();try{await t.ensureCloned(e.marketplaceId,e.gitUrl,e.gitRef,this.pluginLogger,{materialize:r}),this.pluginLogger.log("info",`Prewarmed marketplace clone ${e.gitUrl}@${e.gitRef} for ${e.gitPaths.length} plugin directories`,{marketplaceId:e.marketplaceId,gitUrl:e.gitUrl,gitRef:e.gitRef,requestedDirs:e.gitPaths.length,materialize:"all"===r?"all":r.length}),this.pluginLogger.increment("marketplace_cache_manager.prewarm.success",1,{materialize:"all"===r?"all":"dirs"})}catch(t){this.pluginLogger.captureException(t,{error_type:"prewarm_marketplace_clone"}),this.pluginLogger.log("warn",`Failed to prewarm marketplace clone ${e.gitUrl}@${e.gitRef}; falling back to per-plugin materialization`,{marketplaceId:e.marketplaceId,gitUrl:e.gitUrl,gitRef:e.gitRef,error:String(t)}),this.pluginLogger.increment("marketplace_cache_manager.prewarm.error",1)}this.pluginLogger.distribution("marketplace_cache_manager.prewarm.duration",performance.now()-n)}}async tryInstallFromMarketplaceCache(e,t){const r=this.marketplaceCache,n=e.marketplace;if(!r||!n||!n.gitUrl)return this.pluginLogger.log("info","No marketplace cache or marketplace metadata, skipping cache check",{pluginId:e.pluginId,name:e.name,version:e.version,marketplaceId:e.marketplace?.id}),!1;const o=await r.ensureCloned(n.id,n.gitUrl,n.gitRef??"main",this.pluginLogger,{materialize:e.gitPath?zj([e.gitPath]):[]}),s=e.gitPath??await r.resolvePluginPath(o,e.name);if(!s)return this.pluginLogger.log("info","No git path found for plugin, skipping cache check",{pluginId:e.pluginId,name:e.name,version:e.version,marketplaceId:e.marketplace?.id}),!1;void 0===e.gitPath&&await r.ensureMaterialized(o,zj([s]),this.pluginLogger);const i=r.getPluginDir(o,s);return await r.copyPluginToDir(i,t),!0}async discoverMarketplacePlugins(e,t,r){const n=this.marketplaceCache;if(!n)throw new Error("discoverMarketplacePlugins requires a MarketplaceCacheManager (marketplaceCacheRoot)");const o=await n.ensureCloned(e,t,r,this.pluginLogger,{materialize:[]});return n.discoverPlugins(o)}}function JU(e,t,r,n,o){return new KU(e,t,r,n,o)}function ZU(e){const t=e.trim();if(!t)return!1;if(t.startsWith("git@"))return/^git@[a-zA-Z0-9.-]+:[a-zA-Z0-9._~\-/]+(?:\.git)?$/.test(t);try{const e=new URL(t);return"https:"===e.protocol&&""===e.username&&""===e.password&&""===e.search&&""===e.hash}catch{return!1}}class XU extends Error{constructor(e){super(e),this.name="SettingsParseError"}}function QU(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function YU(e){return 65279===e.charCodeAt(0)?e.slice(1):e}async function eB(e){try{return YU(await(0,xo.readFile)(function(e){return(0,s.join)(e,".cursor","settings.json")}(e),"utf-8"))}catch(e){if(function(e){return e instanceof Error&&"code"in e}(e)&&("ENOENT"===e.code||"ENOTDIR"===e.code))return;throw e}}async function tB(e){const t=await eB(e);return void 0===t?[]:function(e){const t=function(e){const t=YU(e);if(0===t.trim().length)return{};const r=[],n=(0,xp.qg)(t,r,{allowTrailingComma:!0});if(r.length>0){const e=r.slice(0,3).map((e=>`${(0,xp._n)(e.error)} at offset ${e.offset}`)).join("; ");throw new XU(`.cursor/settings.json contains syntax errors: ${e}`)}if(!QU(n))return{};const o=n.plugins;if(void 0===o)return{};if(!QU(o))return{};const s={};for(const[e,t]of Object.entries(o))QU(t)&&(s[e]=t);return{plugins:s}}(e);return t.plugins?Object.entries(t.plugins).filter((([,e])=>!0===e.enabled)).filter((([,e])=>!e.gitUrl||ZU(e.gitUrl))).map((([e,t])=>({key:e,entry:t}))):[]}(t)}function rB(e){const t=e.indexOf("/");return-1===t?{name:e}:{name:e.slice(t+1),marketplaceName:e.slice(0,t)}}const nB={supportsBackendContent:!0};function oB(e={}){const t=e.userHomeDirectory??(0,o.homedir)(),r=e.importThirdPartyPlugins??!1,n=e.pluginLogger??{log(e,t,r){switch(e){case"warn":CO.Jz.warn("[local-plugins-bootstrap]",t,r??{});break;case"error":CO.Jz.error("[local-plugins-bootstrap]",t,r??{})}},increment(){},distribution(){},captureException(e,t){CO.Jz.error("[local-plugins-bootstrap] Unexpected plugin exception:",e,t??{})}},i=sB(e.marketplaceOptions),a=void 0!==e.dashboardTransport,c=e.loadCursorFirstParty??(i||a);return{async loadPluginBootstrapOutputs(o){const i=(a=o.workspaceState).projectRoot??a.workspaceRoots[0]??a.workingDirectory;var a;const{discoveredEntries:l,failures:u}=await async function(e){if(void 0===e)return{discoveredEntries:[],failures:[]};try{return{discoveredEntries:(await tB(e)).map((({key:t,entry:r})=>({source:"project-settings",workspacePath:e,key:t,entry:r}))),failures:[]}}catch(e){return{discoveredEntries:[],failures:[{stage:"discovery",source:"project-settings",message:e instanceof Error?`Failed to read project plugin settings: ${e.message}`:`Failed to read project plugin settings: ${String(e)}`,detail:e}]}}}(i),d=e.marketplaceOptions??(e.dashboardTransport?function(e){const t=(0,s.join)(e.userHomeDirectory,".cursor","plugins","marketplaces"),r=(0,be.createClient)(wj.I,e.dashboardTransport),n=(e,{signal:t})=>r.downloadPluginContent(e,{signal:t}),o=new Eh,i=JU((async()=>{try{return await r.getEffectiveUserPlugins(new QD.EwF(nB))}catch{return{plugins:[]}}}),{marketplaceCacheRoot:t,listOptions:{allowedMarketplaceNames:["cursor-public"]},downloadPluginContent:n,contentRetries:o.forListing("account")}),a=e.workspacePath,c=JU((async()=>{if(void 0===a)return{plugins:[]};try{const e=await tB(a);if(0===e.length)return{plugins:[]};const t=e.filter((e=>e.entry.gitUrl)),n=e.filter((e=>!e.entry.gitUrl)),o=t.filter((({entry:e})=>{const t=e.gitUrl;return!t||ZU(t)})).map((({key:e,entry:t})=>{const r=rB(e),n=t.gitUrl;return{plugin:{name:r.name,gitUrl:n,gitRef:t.gitRef,gitPath:t.gitPath,marketplace:{name:r.marketplaceName,gitUrl:n,gitRef:t.gitRef}},isEnabled:!0}}));let s=[];if(n.length>0)try{const e=n.map((e=>{const t=rB(e.key);return new QD.vwy({name:t.name,marketplaceName:t.marketplaceName})})),t=await r.resolvePluginsByRef(new QD.WvV({refs:e,...nB}));s=t.plugins?.map((e=>({plugin:e,isEnabled:!0})))??[]}catch{}return{plugins:[...o,...s]}}catch{return{plugins:[]}}}),{marketplaceCacheRoot:t,listOptions:{allowedMarketplaceNames:["cursor-public"]},downloadPluginContent:n,contentRetries:o.forListing("project")});return[{client:i,userId:"",cacheManager:new fh(e.userHomeDirectory),pruneOldVersions:!0},{client:c,userId:"",cacheManager:new fh(e.userHomeDirectory),pruneOldVersions:!0}]}({dashboardTransport:e.dashboardTransport,workspacePath:i,userHomeDirectory:t}):void 0),h=sB(d),p=new HD(void 0!==i?[i]:[],t,(()=>({importThirdPartyPlugins:r,loadCursorFirstParty:c})),d,n);let f=[];const m=[...u];try{f=await p.getAllEnabledPlugins()}catch(e){m.push({stage:"resolution",source:"plugin-loader",message:e instanceof Error?`Failed to load plugins: ${e.message}`:`Failed to load plugins: ${String(e)}`,detail:e})}l.length>0&&!h&&m.push({stage:"resolution",source:"plugin-loader",message:"Project plugin entries were discovered, but no marketplace-backed project plugin source was configured. Those entries remain available through discoveredEntries only.",detail:{workspacePath:i,discoveredEntryCount:l.length}});const g={kind:qO,discoveredEntries:l,loadedPlugins:f,loadFailures:p.getLoadFailures(),bootstrapFailures:m,pluginsService:p,async dispose(){}};for(const e of m)CO.Jz.warn("[local-plugins-bootstrap] Plugin bootstrap failure:",{workspacePath:i,stage:e.stage,source:e.source,message:e.message,detail:e.detail});for(const e of g.loadFailures)CO.Jz.warn("[local-plugins-bootstrap] Plugin load failure:",{workspacePath:i,pluginName:e.pluginName,pluginId:e.pluginId,marketplaceName:e.marketplaceName,errorType:e.errorType,errorMessage:e.errorMessage});return[g]}}}function sB(e){return void 0!==e&&(!Array.isArray(e)||e.length>0)}class iB{async getAllCursorRules(e){return[]}reload(e){}dispose(){}onDidChangeRules(e){return()=>{}}}const aB=["projectFolder","terminalsFolder","agentSharedNotesFolder","agentConversationNotesFolder","agentTranscriptsFolder","processWorkingDirectory","artifactsFolder"];function cB(e){if(e.length<=1)return e;let t=e.length;for(;t>1&&("/"===(r=e[t-1])||"\\"===r)&&(3!==t||":"!==e[1]);)t-=1;var r;return e.slice(0,t)}function lB(e){const t=cB(e).replaceAll("\\","/");return/^[A-Za-z]:\/$/.test(t)?t.slice(0,-1):t}function uB(e){const t=cB(e.reportedWorkspacePath);if(""===e.suffix)return t;const r=t.replaceAll("\\","/"),n="/"===r?e.suffix:`${r}${e.suffix}`;return t.includes("\\")?n.replaceAll("/","\\"):n}function dB(e){const t=lB(e.value),r=e.roots.filter((e=>e.host.length>0)).sort(((e,t)=>lB(t.host).length-lB(e.host).length));for(const e of r){const r=lB(e.host);if(t===r)return uB({reportedWorkspacePath:e.reported,suffix:""});const n="/"===r?"/":`${r}/`;if(t.startsWith(n)){const n="/"===r?t:t.slice(r.length);return uB({reportedWorkspacePath:e.reported,suffix:n})}}}const hB={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1};class pB extends cD{constructor(e,t){super(e),this.sessionMcpLease=t}async dispose(){try{await super.dispose()}finally{await yj(this.sessionMcpLease)}}}function fB(e){const t=new xy;return{async createResources(r){const n=e.createSessionDependencies?.(r)??{pendingDecisionStore:e.pendingDecisionStore,fileChangeTracker:e.fileChangeTracker,permissionsService:e.permissionsService};if(!n.pendingDecisionStore||!n.fileChangeTracker||!n.permissionsService)throw new Error("Local resource provider factory requires either shared dependencies or a per-session dependency factory.");const o=r.workspaceServices.cursorRulesService??new iB,s=r.workspaceServices.subagentsService??new _g,i=r.workspaceServices.mcpLease??new oI,a=!0===r.options.excludeProjectMcp,c=void 0!==r.options.mcpServersOverride||a?void 0!==e.createSessionMcpLease?await e.createSessionMcpLease(r,r.options.mcpServersOverride):a?new oI:void 0:void 0,l=(u=c??i,0===(d=r.options.extraMcpTools??[]).length?u:"onDidChange"in(h=u)&&"function"==typeof h.onDidChange?new Kw(u,d):new Vw(u,d));var u,d,h;try{const i=await async function(e,t){return void 0===e?{}:"function"==typeof e?await e({sessionId:t.sessionState.sessionId,metadata:t.metadata}):e}(r.options.localResourceProviderOptions,r),a=await async function(e){if(void 0===e)return hB;try{const t=await e();return{powershellUtf8Console:t.powershellUtf8Console,powershellUtf8ChildEnv:t.powershellUtf8ChildEnv}}catch{return hB}}(e.getPowershellUtf8Options),u={pendingDecisionStore:n.pendingDecisionStore,fileChangeTracker:n.fileChangeTracker,gitExecutor:t,ignoreService:e.ignoreService,grepProvider:e.grepProvider,permissionsService:n.permissionsService,workspacePaths:e.workspacePaths,diagnosticsProvider:e.diagnosticsProvider,mcpLease:l,mcpStateAccessor:e.createMcpStateAccessor?.(l,r.options),cursorRulesService:o,subagentsService:s,repositoryProvider:e.repositoryProvider,projectDir:e.projectDir,shellManager:e.shellManager,_defaultSandboxPolicy:e.defaultSandboxPolicy??{type:"insecure_none"},_defaultSandboxPolicySources:e.defaultSandboxPolicySources,getSandboxEnabled:e.getSandboxEnabled,getSandboxSupported:e.getSandboxSupported,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:e.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:e.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:e.getMockPromptTime,mcpFileOutputThresholdBytes:e.mcpFileOutputThresholdBytes,mcpMetaToolEnabled:e.mcpMetaToolEnabled,getAgentSkills:r.workspaceServices.getAgentSkills,powershellUtf8Console:a.powershellUtf8Console,powershellUtf8ChildEnv:a.powershellUtf8ChildEnv,...i},d=void 0===c?new cD(u):new pB(u,c);return void 0===r.options.reportedWorkspacePath&&void 0===r.options.reportedProjectFolder||function(e,t){const r=e.get(Dr);if(void 0===r)return;const{reportedWorkspacePath:n,reportedProjectFolder:o}=t,s=void 0===n?[]:t.workspacePaths.map((e=>({host:e,reported:n}))),i=o??n;void 0!==i&&s.push({host:t.projectDir,reported:i}),e.register(Dr,{execute:async(e,t,o)=>function(e,t){if("success"!==e.result.case||void 0===e.result.value.requestContext?.env)return e;const r=e.clone();if("success"!==r.result.case)return e;const n=r.result.value.requestContext?.env;if(void 0===n)return r;const{roots:o,reportedWorkspacePath:s}=t;n.workspacePaths=n.workspacePaths.map((e=>dB({value:e,roots:o})??e));for(const e of aB){const t=n[e];if(void 0===t||""===t)continue;const r=dB({value:t,roots:o});n[e]="processWorkingDirectory"===e&&void 0!==s?r??cB(s):r??t}return r}(await r.execute(e,t,o),{roots:s,reportedWorkspacePath:n})})}(d,{reportedWorkspacePath:r.options.reportedWorkspacePath,reportedProjectFolder:r.options.reportedProjectFolder,workspacePaths:u.workspacePaths,projectDir:u.projectDir}),d}catch(e){throw await yj(c),e}}}}const mB=["cursorRulesService","getAgentSkills","subagentsService"],gB=new WeakSet;function wB(e){("object"==typeof e&&null!==e||"function"==typeof e)&&gB.add(e)}function yB(e){return("object"==typeof e&&null!==e||"function"==typeof e)&&gB.has(e)}function vB(e,t){const r=Object.keys(t).filter((e=>!mB.includes(e)));if(r.length>0)throw new Error(`Workspace service contributors may only provide ${mB.join(", ")}. Received unsupported service keys: ${r.join(", ")}.`);for(const r of mB)Object.hasOwn(t,r)&&(e[r]=t[r])}async function bB(e,t,r){const n={config:void 0,plugins:[],pluginBootstrapOutputs:[],cursorRulesService:void 0,getAgentSkills:void 0,subagentsService:void 0,mcpLease:void 0,hooksRuntime:void 0};try{n.config=e.config?await e.config.loadConfig(t):void 0,n.plugins=e.plugins?await e.plugins.loadPlugins(t):[];const o=()=>({workspaceState:t,policy:r,services:n});n.pluginBootstrapOutputs=e.pluginBootstrap?await e.pluginBootstrap.loadPluginBootstrapOutputs(o()):n.pluginBootstrapOutputs,n.mcpLease=e.mcp?await e.mcp.createLease(o()):void 0,n.hooksRuntime=e.hooks?await e.hooks.createHooksRuntime(o()):void 0,e.localExtensibility?.prepareLocalExtensibility&&await e.localExtensibility.prepareLocalExtensibility(o());const s=e.localExtensibility?await e.localExtensibility.loadLocalExtensibility(o()):void 0;void 0!==s&&(wB(s.cursorRulesService),wB(s.subagentsService),Object.assign(n,s));for(const t of e.workspaceServicesContributors??[]){const e=await t.contributeServices(o());void 0!==e&&vB(n,e)}return n}catch(t){try{await SB(n,{disposeLocalExtensibility:void 0===e.localExtensibility?void 0:()=>e.localExtensibility?.disposeLocalExtensibility?.()})}catch(e){throw function(e,t){return new AggregateError([t],"Workspace service loading failed and resource cleanup also failed.",{cause:e})}(t,e)}throw t}}async function SB(e,t){const r=t?.preserveSharedContributorsFrom;let n;const o=async e=>{try{await yj(e)}catch(e){n??=e}};if(e.subagentsService===r?.subagentsService||yB(e.subagentsService)||await o(e.subagentsService),e.cursorRulesService===r?.cursorRulesService||yB(e.cursorRulesService)||await o(e.cursorRulesService),t?.disposeLocalExtensibility)try{await t.disposeLocalExtensibility()}catch(e){n??=e}await o(e.hooksRuntime),await o(e.mcpLease);try{await async function(e){let t;for(let r=e.length-1;r>=0;r-=1)try{await yj(e[r])}catch(e){t??=e}if(void 0!==t)throw t}(e.pluginBootstrapOutputs)}catch(e){n??=e}if(void 0!==n)throw n}const kB=["project","user","team","mdm","plugins"],_B=new Set([...kB,"all"]);function CB(e){if(void 0===e||0===e.length)return xB([]);for(const t of e)if(!_B.has(t))throw new Error(`Unsupported setting source "${t}"`);if(e.includes("all")){if(e.length>1)throw new Error('settingSources cannot mix "all" with individual setting sources');return{...xB(kB),all:!0}}return xB(e.filter((e=>"all"!==e)))}function EB(e,t){return e[t]}function xB(e){const t=new Set(e);return{project:t.has("project"),user:t.has("user"),team:t.has("team"),mdm:t.has("mdm"),plugins:t.has("plugins"),all:!1}}const PB=Object.freeze({}),RB=Object.freeze({allowMcpServers:!0,allowPlugins:!0,allowBackgroundSessions:!0,requireMcpApproval:!1,maxParallelSessions:void 0,sandboxMode:void 0,metadata:PB});async function IB(e){const t=new Set;let r;for(let n=e.length-1;n>=0;n-=1){const o=e[n];if(!t.has(o)){t.add(o);try{await yj(o)}catch(e){r??=e}}}if(void 0!==r)throw r}async function TB(e={}){const t=function(e={}){return{workspace:e.workspace??SO,config:e.config,plugins:e.plugins,pluginBootstrap:e.pluginBootstrap,mcp:e.mcp,hooks:e.hooks,localExtensibility:e.localExtensibility,resourceFactory:e.resourceFactory,resourceWrappers:e.resourceWrappers,workspaceServicesContributors:e.workspaceServicesContributors,lifecycle:e.lifecycle}}(e.adapters),r=await t.workspace.resolveWorkspaceState({workingDirectory:e.workingDirectory,projectRoot:e.projectRoot,projectDirectory:e.projectDirectory,workspaceRoots:e.workspaceRoots}),n=await async function(e,t){return e.resolvePolicy(t)}(e.policyAdapter??function(e={}){const t=Object.freeze({...RB.metadata,...e.metadata}),r={...RB,...e,metadata:t};return{name:"permissive-sdk-local",resolvePolicy:()=>r}}(),{workspaceState:r});let o=await bB(t,r,n),s=!1,i=Promise.resolve();const a=e=>{const t=i.then(e);return i=t.catch((()=>{})),t},c=t.localExtensibility,l=void 0===c?void 0:()=>c.disposeLocalExtensibility?.();return{state:r,get services(){return o},policy:n,async createSessionRuntime(e={}){if(s)throw new Error("Cannot create a session runtime after the workspace runtime has been disposed.");return async function(e){const t={sessionId:e.options?.sessionId??(0,ye.C)(),createdAt:new Date},r=Object.freeze({...e.options?.metadata??{}}),n={options:e.options??{},workspaceState:e.workspaceState,workspaceServices:e.workspaceServices,policy:e.policy,sessionState:t,metadata:r,getAgentSkills:e.workspaceServices.getAgentSkills};let o,s;const i=[];try{o=e.adapters.resourceFactory?await e.adapters.resourceFactory.createResources(n):void 0,s=o,i.push(o);for(const t of e.adapters.resourceWrappers??[])s=await t.wrapResources({...n,baseResources:o,resources:s}),i.push(s);await(e.adapters.lifecycle?.onSessionCreated?.(t))}catch(e){try{await IB(i)}catch(t){throw function(e,t){return new AggregateError([t],"Session creation failed and resource cleanup also failed.",{cause:e})}(e,t)}throw e}let a=!1;return{state:t,resources:{base:o,wrapped:s},metadata:r,workspaceServices:e.workspaceServices,policy:e.policy,async dispose(){if(!a){a=!0;try{await IB(i)}finally{await(e.adapters.lifecycle?.onSessionDisposed?.(t))}}}}}({options:e,workspaceState:r,workspaceServices:o,policy:n,adapters:t})},async reload(){s||await a((async()=>{if(s)return;const e=o,i=await bB(t,r,n);s?await SB(i,{disposeLocalExtensibility:l}):(o=i,await SB(e,{preserveSharedContributorsFrom:i,disposeLocalExtensibility:l}),await(t.lifecycle?.onWorkspaceReload?.(r)))}))},async dispose(){s||(s=!0,await a((async()=>{try{await SB(o,{disposeLocalExtensibility:l})}finally{await(t.lifecycle?.dispose())}})))}}}class AB{async requestApproval(e){return{approved:!0}}}class $B{constructor(e,t,r,n){this.approvalMode=e,this.userConfiguredPolicy=t,this.teamSettingsService=r,this.respectAdminControls=n}async getPermissions(){const e=!(!this.respectAdminControls||"insecure_none"===this.userConfiguredPolicy.type)&&(await this.teamSettingsService.getSandboxingControls()).sandboxingDisabled;return{allow:[],deny:[],approvalMode:this.approvalMode,userConfiguredPolicy:e?{type:"insecure_none"}:this.userConfiguredPolicy}}async updatePermissions(){}}class MB{async open(e,t){}async getDiagnostics(e,t){return[]}}class DB{async getCodebaseReference(e,t){}}class OB{constructor(e,t){this.inner=e,this.allowlistReports=t}async getState(e){const t=await this.inner.getState(e);return await this.reportAllowlists(e),{...t,servers:t.servers.filter((e=>"needsAuth"!==e.status))}}async reportAllowlists(e){if(void 0===this.allowlistReports)return;const{mcpLease:t,onMcpAllowlistInUse:r,onMcpServerBlockedByAllowlist:n}=this.allowlistReports;let o;try{o=await t.getClients(e)}catch(e){return void CO.Jz.warn("[sdk-mcp-state] Could not read the MCP allowlist in use:",e)}for(const[e,t]of Object.entries(o))try{if(void 0!==r){const n=await(t.getAllowlistInUse?.());void 0!==n&&r({serverName:e,allowlist:n})}if(void 0!==n){const r=await(t.getAllowlistRefusal?.());void 0!==r&&n({serverName:e,refusal:r})}}catch(e){CO.Jz.warn("[sdk-mcp-state] Could not read the MCP allowlist in use:",e)}}}class FB{constructor(e){this.subagents=e.map((e=>new Sg.zz({fullPath:`sdk-inline://${e.name}`,name:e.name,description:e.description,tools:[],model:e.model,prompt:e.prompt,permissionMode:Sg.b$.DEFAULT,isBackground:!1,source:"sdk"})))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents}}class NB{constructor(e={}){this.options=e,this.states=new Map,this.runCounterBySession=new Map,this.dispatchQueueBySession=new Map,this.dispatchInProgress=new Set,this.releaseRequestedBySession=new Set}getState(e){return this.states.get(e)??{status:"idle"}}isBusy(e){return"idle"!==this.getState(e).status}startRun(e,t){const r=this.nextRunId(e);return this.enqueueEvent(e,{type:"startRun",runId:r,abort:t?.abort}),r}queueResume(e,t){this.enqueueEvent(e,{type:"queueResume",queuedResume:t.queuedResume,targetRunId:t.targetRunId,mergeQueuedResume:t.mergeQueuedResume})}finishRun(e,t){this.enqueueEvent(e,{type:"runFinished",runId:t})}clearQueuedResume(e){this.enqueueEvent(e,{type:"clearQueuedResume"})}abort(e){this.enqueueEvent(e,{type:"abort"})}release(e){this.enqueueEvent(e,{type:"release"})}nextRunId(e){const t=(this.runCounterBySession.get(e)??0)+1;return this.runCounterBySession.set(e,t),t}enqueueEvent(e,t){const r=this.dispatchQueueBySession.get(e)??[];r.push(t),this.dispatchQueueBySession.set(e,r),this.drainEventQueue(e)}drainEventQueue(e){if(this.dispatchInProgress.has(e))return;let t;this.dispatchInProgress.add(e);try{const r=this.dispatchQueueBySession.get(e);if(!r)return;for(;r.length>0;){const n=r.shift();if(n)try{this.processEvent(e,n)}catch(e){t??=e}}}finally{this.dispatchQueueBySession.delete(e),this.dispatchInProgress.delete(e)}if(t)throw t}processEvent(e,t){const r=this.getState(e),{nextState:n,effects:o}=function(e,t){switch(e.status){case"idle":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"running",runId:t.runId,abort:t.abort},effects:[]};case"queueResume":return void 0===t.targetRunId?{nextState:e,effects:[]}:{nextState:{status:"runningWithQueuedResume",runId:t.targetRunId,queuedResume:t.queuedResume},effects:[]};case"runFinished":case"clearQueuedResume":case"abort":case"release":return{nextState:e,effects:[]};default:throw new Error(`Unhandled idle-state event: ${String(t)}`)}}(e,t);case"running":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"running",runId:t.runId,abort:t.abort},effects:[{type:"abortActiveRun",abort:e.abort}]};case"queueResume":return{nextState:{status:"runningWithQueuedResume",runId:e.runId,abort:e.abort,queuedResume:t.queuedResume},effects:[]};case"runFinished":return t.runId!==e.runId?{nextState:e,effects:[]}:{nextState:{status:"idle"},effects:[]};case"clearQueuedResume":case"release":return{nextState:e,effects:[]};case"abort":return{nextState:{status:"idle"},effects:[{type:"abortActiveRun",abort:e.abort}]};default:throw new Error(`Unhandled running-state event: ${String(t)}`)}}(e,t);case"runningWithQueuedResume":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"runningWithQueuedResume",runId:t.runId,abort:t.abort,queuedResume:e.queuedResume},effects:[{type:"abortActiveRun",abort:e.abort}]};case"queueResume":return{nextState:{...e,queuedResume:t.mergeQueuedResume(e.queuedResume,t.queuedResume)},effects:[]};case"runFinished":return t.runId!==e.runId?{nextState:e,effects:[]}:{nextState:{status:"running",runId:e.runId,abort:e.abort},effects:[{type:"startQueuedRun",sourceRunId:e.runId,queuedResume:e.queuedResume}]};case"clearQueuedResume":return{nextState:{status:"running",runId:e.runId,abort:e.abort},effects:[]};case"abort":return{nextState:{status:"idle"},effects:[{type:"abortActiveRun",abort:e.abort}]};case"release":return{nextState:e,effects:[]};default:throw new Error(`Unhandled runningWithQueuedResume-state event: ${String(t)}`)}}(e,t);default:return{nextState:e,effects:[]}}}(r,t);this.states.set(e,n),this.options.onStateChange?.({sessionId:e,previousState:r,nextState:n});for(const t of o)switch(t.type){case"abortActiveRun":t.abort?.();break;case"startQueuedRun":this.options.onQueuedRunReady?.({sessionId:e,sourceRunId:t.sourceRunId,queuedResume:t.queuedResume});break;default:throw new Error(`Unhandled lifecycle manager effect: ${String(t)}`)}const s=this.getState(e);"release"===t.type&&"idle"!==s.status&&this.releaseRequestedBySession.add(e),"idle"!==s.status||"release"!==t.type&&!this.releaseRequestedBySession.has(e)||(this.states.delete(e),this.runCounterBySession.delete(e),this.releaseRequestedBySession.delete(e))}}function LB(e){return"string"==typeof e&&e.trim().length>0}function jB(e,t){return new fe.jn({command:t.command??"",workingDirectory:t.workingDirectory??"",error:e,isReadonly:!0})}function UB(e){return{execute:async(t,r)=>new FI.v3({result:{case:"permissionDenied",value:new FI.U7({path:r.path,error:e,isReadonly:!0})}})}}function BB(e){return{execute:async(t,r)=>new Ww.Pi({result:{case:"permissionDenied",value:new Ww.QG({path:r.path,clientVisibleError:e,isReadonly:!0})}})}}function WB(e){return{execute:async(t,r)=>new Mc.iz({result:{case:"permissionDenied",value:new Mc.HQ({error:`${e} Tool: ${r.name}`,isReadonly:!0})}})}}var HB=r("../agent-kv/dist/subagent-states.js");let qB;function zB(e){const t=process.env.CURSOR_DATA_DIR;if(t?.trim())return Eo(e);let r;try{r=(0,o.homedir)()}catch{r=void 0}return function(e){const t=e.cursorDataDir?.trim();return t?(0,s.join)(t,"projects",(0,_o.r_)(e.workspacePath)):void 0!==e.homeDir&&function(e){if(""===e.trim())return!1;try{return!!(0,Ro.statSync)(e).isDirectory()&&((0,Ro.accessSync)(e,Ro.constants.W_OK),!0)}catch{return!1}}(e.homeDir)?(0,s.join)(e.homeDir,".cursor","projects",(0,_o.r_)(e.workspacePath)):(0,s.join)(e.ensureFallbackRoot(e.tempDir),(0,_o.r_)(e.workspacePath))}({workspacePath:e,homeDir:r,tempDir:(0,o.tmpdir)(),ensureFallbackRoot:e=>(void 0===qB&&(qB=function(e){return(0,Ro.mkdtempSync)((0,s.join)(e,"cursor-transcripts-"))}(e)),qB)})}async function GB(e,t){const r=(0,s.dirname)(e);await(0,xo.mkdir)(r,{recursive:!0}),await(0,xo.writeFile)(e,t,"utf-8")}class VB{constructor(e){this.writeChain=Promise.resolve(),this.workspacePath=e.workspacePath,this.conversationId=e.conversationId,this.parentConversationId=e.parentConversationId,this.blobStore=e.blobStore,this.projectDir=zB(this.workspacePath);const t=this.parentConversationId?(e,t)=>{const r=NF({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,r)}:void 0;this.transcriptStore=new pN(this.projectDir,e.blobStore,GB,{writeText:!1,writeJsonl:!0,...t?{pathResolver:t}:{}}),this.nestedSubagentTranscriptStore=new pN(this.projectDir,e.blobStore,GB,{writeText:!1,writeJsonl:!0,pathResolver:(e,t)=>{const r=NF({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.conversationId});return(0,s.join)(this.projectDir,r)}})}enqueueWrite(e,t){const r=this.writeChain;return this.writeChain=r.then((async()=>{try{await e()}catch(e){CO.Jz.warn(`${t} ${e instanceof Error?e.message:String(e)}`)}})),this.writeChain}async writeFromState(e,t){return this.enqueueWrite((async()=>{await this.transcriptStore.writeFromStateFull(e,t,this.conversationId);const r=await(0,HB.Vn)(e,t,this.blobStore);for(const[t,n]of Object.entries(r))n?.conversationState&&await this.nestedSubagentTranscriptStore.writeFromStateFull(e,n.conversationState,t)}),"[LocalTranscriptWriter] Failed to write transcript:")}async writeTurnEndedFromState(e,t,r){return this.enqueueWrite((async()=>{await this.transcriptStore.writeFromStateFull(e,t,this.conversationId,{turnEnded:r})}),"[LocalTranscriptWriter] Failed to write turn-ended transcript:")}waitForPendingWrites(){return this.writeChain}getTranscriptPath(){if(this.parentConversationId){const e=NF({conversationId:this.conversationId,ext:"jsonl",kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,e)}return function(e,t){const r=NF({conversationId:t,ext:"jsonl",kind:"primary"});return(0,s.join)(zB(e),r)}(this.workspacePath,this.conversationId)}getProjectDir(){return this.projectDir}}const KB=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,JB="User aborted/interrupted manually.";class ZB{constructor(e){this.sessions=new Map,this.backgroundRuns=new Map,this.activeForegroundExecutions=new Map,this.backgroundPromises=new Set,this.pendingReleaseSessions=new Set,this.childParentIds=new Map,this.parentChildIds=new Map,this.queuedChildCompletions=new Map,this.childCompletionWaiters=new Map,this.childLineageRequestIds=new Map,this.untrackedParentRequestIds=new Map,this.agentClient=e.agentClient,this.getResources=e.getResources,this.mcpTools=e.mcpTools??[],this.workspacePath=e.workspacePath,this.parentConversationId=e.parentConversationId;const t=e.rootRequestId?.trim();this.rootLineageRequestId=void 0!==t&&t.length>0?t:(0,ye.C)(),this.headers=e.headers,this.endlessRetries=e.endlessRetries,this.onSessionCreated=e.onSessionCreated,this.onInteractionUpdate=e.onInteractionUpdate,this.onSessionCompleted=e.onSessionCompleted,this.onSessionReleased=e.onSessionReleased,this.onSubagentTokenDelta=e.onSubagentTokenDelta,this.lifecycleStore=new NB}async createOrResumeSession(e,t){if(t.forkAgentId)throw new Error("forkAgentId is not supported in local subagents.");const r=t.resumeAgentId;if(r&&function(e){if(!KB.test(e))throw new Error(`Invalid resumeAgentId format: ${e}`)}(r),r&&!t.prompt)return r;if(r&&LB(t.prompt)&&this.isBackgroundRunBusy(r))throw new Error("Sub-agent is currently running. You may send the follow-up message when it has completed.");if(r&&this.sessions.get(r))return r;const n=r??(0,ye.C)(),o=function(e){const t=new oe.We,r=(0,EO.sh)(e),n=new EO.pH(new oe.ve,t);return n.setMetadata("agentId",r.agentId),n.setMetadata("latestRootBlobId",r.latestRootBlobId),n.setMetadata("name",r.name),n.setMetadata("createdAt",r.createdAt),n.setMetadata("mode",r.mode),n.setMetadata("isRunEverything",r.isRunEverything),n.setMetadata("lastUsedModel",r.lastUsedModel),n.setMetadata("lastDebugServerPort",r.lastDebugServerPort),n.setMetadata("currentPlanUri",r.currentPlanUri),n.setMetadata("subagentInfo",r.subagentInfo),n.setMetadata("blobEncryptionKey",r.blobEncryptionKey),n}(n),s=new VB({workspacePath:this.workspacePath,conversationId:n,parentConversationId:this.parentConversationId,blobStore:o.getBlobStore()});return this.sessions.set(n,{agentStore:o,transcriptWriter:s,toolCallId:t.toolCallId}),this.onSessionCreated?.({agentId:n,toolCallId:t.toolCallId,subagentType:t.subagentType,parentAgentId:t.parentConversationId}),n}async runSession(e,t,r,n){if(this.isAwaitBackgroundMode(r))return this.awaitBackgroundRun(r.resumeAgentId,e.signal);const o=this.sessions.get(t);if(!o)return{status:"error",error:`Subagent session not found: ${t}`};if(r.runInBackground){const[n,s]=e.withDetached().withCancel();return this.registerBackgroundRun(t,this.executeSubagent(n,t,r,o),r.parentConversationId,s),{status:"background",backgroundReason:Sg.qL.AGENT_REQUEST,toolCallCount:0}}const[s,i]=e.withDetached().withCancel();let a=!1;const c=()=>{a||i()};e.signal.addEventListener("abort",c,{once:!0}),e.signal.aborted&&c();let l=()=>{};const u=new Promise((e=>{l=e})),d={requestBackground:()=>!!a||!s.signal.aborted&&(a=!0,e.signal.removeEventListener("abort",c),l(),!0)};this.activeForegroundExecutions.set(r.toolCallId,d),this.activeForegroundExecutions.set(t,d);try{const e=this.executeSubagent(s,t,r,o),n=await Promise.race([e.then((e=>({handedOff:!1,outcome:e}))),u.then((()=>({handedOff:!0})))]);return n.handedOff?(this.registerBackgroundRun(t,e,r.parentConversationId,i),{status:"background",backgroundReason:Sg.qL.USER_REQUEST,toolCallCount:0}):(this.onSessionCompleted?.(t,n.outcome),n.outcome)}finally{this.clearForegroundExecution(r.toolCallId,d),this.clearForegroundExecution(t,d),a||e.signal.removeEventListener("abort",c)}}forceBackgroundByToolCallId(e){const t=this.activeForegroundExecutions.get(e);return t?.requestBackground()?new io.a3({status:io.jh.ACCEPTED}):new io.a3({status:io.jh.NOT_FOUND})}clearForegroundExecution(e,t){this.activeForegroundExecutions.get(e)===t&&this.activeForegroundExecutions.delete(e)}releaseSession(e){this.lifecycleStore.release(e),this.isBackgroundRunBusy(e)?this.pendingReleaseSessions.add(e):this.cleanupSession(e)}async awaitBackgroundWorkers(){for(;this.backgroundPromises.size>0;)await Promise.allSettled([...this.backgroundPromises])}async waitForBackgroundCompletions(e,t){return this.collectAvailableChildCompletions(e,t)}isBackgroundRunBusy(e){return this.lifecycleStore.isBusy(e)||this.backgroundRuns.has(e)}registerBackgroundRun(e,t,r,n){this.registerParentChildLink(e,r);const o=this.lifecycleStore.startRun(e,{abort:n}),s=t.catch((e=>({status:"error",error:e instanceof Error?e.message:String(e)}))),i={runId:o,promise:s};this.backgroundRuns.set(e,i),this.backgroundPromises.add(s),s.then((t=>{this.lifecycleStore.finishRun(e,o);const r=this.backgroundRuns.get(e);if(r?.runId===o){this.backgroundRuns.delete(e),this.enqueueChildCompletion(e,o,t),this.maybeCleanupReleasedSession(e);try{this.onSessionCompleted?.(e,t)}catch(t){CO.Jz.error("[LocalSubagentHostAdapter] onSessionCompleted threw after background run",{agentId:e,error:t instanceof Error?t.message:String(t)})}}return t})).finally((()=>this.backgroundPromises.delete(s)))}maybeCleanupReleasedSession(e){this.pendingReleaseSessions.has(e)&&!this.isBackgroundRunBusy(e)&&this.cleanupSession(e)}cleanupSession(e){this.pendingReleaseSessions.delete(e);const t=this.sessions.get(e);if(!t)return;const r=this.parentChildIds.get(e);if(r)for(const e of r)this.childParentIds.delete(e);this.removeParentChildLink(e),this.parentChildIds.delete(e),this.queuedChildCompletions.delete(e),this.childCompletionWaiters.delete(e),t.transcriptWriter.waitForPendingWrites().catch((()=>{})),this.sessions.delete(e),this.onSessionReleased?.(e)}async executeSubagent(e,t,r,n){return r.continuationConfig?this.executeSubagentWithContinuation(e,t,r,n,r.continuationConfig):this.executeSubagentOnce(e,t,r,n)}async executeSubagentWithContinuation(e,t,r,n,o){const s=o.maxLoops>0?o.maxLoops:Number.POSITIVE_INFINITY;let i=await this.runContinuationLoop(e,t,r,n,o,s);if(!o.collectBackgroundChildren||"completed"!==i.status)return i;for(let a=0;a<500;a++){if(e.signal.aborted)return{status:"error",error:"Subagent was aborted by the user"};let a;try{a=await this.collectAvailableChildCompletions(t,e.signal)}catch{return{status:"error",error:"Subagent was aborted by the user"}}if(0===a.length)return i;const c=this.buildChildrenCompletedMessage(a,o.childrenCompletedMessageTemplate);if(i=await this.runContinuationLoop(e,t,new io.Pw({...r,prompt:c,resumeAgentId:t,runInBackground:!1}),n,o,s),"completed"!==i.status)return i}return i}async runContinuationLoop(e,t,r,n,o,s){let i,a,c=0;for(let l=0;l0?(c=0,i=void 0):(c+=1,i=c>=o.idleThreshold?`DONE_${(0,ye.C)().replace(/-/g,"").slice(0,8)}`:void 0)}return a??{status:"error",error:"Subagent continuation exited unexpectedly"}}computeContinuationNudge(e,t,r){return t>=e.idleThreshold&&void 0!==r?e.escapeMessageTemplate.replace("{idle_count}",String(t)).replace("{escape_token}",r):e.nudgeMessage}lineageForChildRun(e){this.childLineageRequestIds.has(e.agentId)||this.childLineageRequestIds.set(e.agentId,(0,ye.C)());const t=e.parentConversationId?.trim()??"",r=e.toolCallId.trim();return{parentRequestId:""===t||t===this.parentConversationId?this.rootLineageRequestId:this.childLineageRequestIds.get(t)??this.untrackedParentRequestId(t),rootParentRequestId:this.rootLineageRequestId,...r.length>0?{parentAgentToolCallId:r}:{}}}untrackedParentRequestId(e){let t=this.untrackedParentRequestIds.get(e);return void 0===t&&(t=(0,ye.C)(),this.untrackedParentRequestIds.set(e,t)),t}async executeSubagentOnce(e,t,r,n){const o=this.lineageForChildRun({agentId:t,parentConversationId:r.parentConversationId,toolCallId:r.toolCallId});let s,i=0;const a=new c.QFf({action:{case:"userMessageAction",value:new c.Vtf({userMessage:new c.RGk({text:r.prompt})})}}),l=new c.Gmx({modelId:r.modelId,displayModelId:r.modelId,displayName:r.modelId});void 0!==r.credentials.case&&(l.credentials=r.credentials);const u=new _O,d={sendUpdate:async(e,r)=>{"tokenDelta"===r.message.case&&this.onSubagentTokenDelta?.(t,r.message.value.tokens),"toolCallStarted"!==r.message.case&&"toolCallCompleted"!==r.message.case&&"partialToolCall"!==r.message.case||this.onInteractionUpdate?.(t,r),"toolCallCompleted"===r.message.case&&i++,"textDelta"===r.message.case&&(s=(s??"")+r.message.value.text)},query:async(e,t)=>function(e){const t=e.query.case;switch(t){case"webSearchRequestQuery":return pr(e.id,"Web search is not supported in local subagent");case"webFetchRequestQuery":return mr(e.id,"Web fetch is not supported in local subagent");case"switchModeRequestQuery":return yr(e.id,"Subagent mode switches are not supported in local subagent");case"askQuestionInteractionQuery":{const t=new er.tz({result:{case:"rejected",value:new er.ox({reason:"Interactive questions are not supported in local subagent mode"})}});return gr(e.id,t)}default:throw new Error(`Unhandled interaction query type in local subagent: ${String(t)}`)}}(t)},h={handleCheckpoint:async(e,t)=>{await n.agentStore.handleCheckpoint(e,t),n.transcriptWriter.writeFromState(e,t)},getLatestCheckpoint:()=>n.agentStore.getLatestCheckpoint()};try{const c=r.rootParentConversationId?.trim(),p=r.parentConversationId?.trim(),f=void 0!==c&&""!==c?c:void 0!==p&&""!==p?p:t,m=await this.getResources({agentId:t,parentAgentId:r.parentConversationId}),g=r.readonly?new X(m,function(e){const t=[K(GT,UB(e.errorMessage)),K(VT,BB(e.errorMessage)),K(ro,WB(e.errorMessage))];return e.wrapShell&&t.push(K(WT,function(e){return{execute:async(t,r)=>new fe.W4({result:{case:"permissionDenied",value:jB(e,r)}})}}(e.errorMessage)),K(re,function(e){return{async*execute(t,r){yield new fe.FI({event:{case:"permissionDenied",value:jB(e,r)}})}}}(e.errorMessage)),K(kA,function(e){return{execute:async(t,r)=>new Fo.Lt({result:{case:"permissionDenied",value:jB(e,r)}})}}(e.errorMessage))),e.includeWriteBackgroundShellStdin&&t.push(K(_A,function(e){return{execute:async(t,r)=>new Fo.nt({result:{case:"error",value:new Fo.Gv({error:e})}})}}(e.errorMessage))),t}({errorMessage:"This operation is not allowed in readonly mode. The subagent was launched with readonly: true, which restricts shell, write, delete, and MCP operations.",wrapShell:!0,includeWriteBackgroundShellStdin:!0})):m;return await this.agentClient.run(e,n.agentStore.getConversationStateStructure(),a,l,d,g,n.agentStore.getBlobStore(),u,h,[...this.mcpTools],{conversationGroupId:f,conversationId:t,...n.transcriptWriter.parentConversationId?{transcriptParentConversationId:n.transcriptWriter.parentConversationId}:{},subagentTypeName:r.subagentType||void 0,...o,headers:PO(n.agentStore.getMetadata("blobEncryptionKey"),this.headers),endlessRetries:this.endlessRetries,subagentModelOverrides:[]}),await n.transcriptWriter.writeTurnEndedFromState(e,n.agentStore.getConversationStateStructure(),e.signal.aborted?{status:"aborted",error:JB}:{status:"success"}),{status:"completed",finalMessage:s,toolCallCount:i}}catch(r){const o=r instanceof Error?r.message:String(r);return CO.Jz.error("[LocalSubagentHostAdapter] Subagent session failed",{agentId:t,error:o}),await n.transcriptWriter.writeTurnEndedFromState(e,n.agentStore.getLatestCheckpoint()??n.agentStore.getConversationStateStructure(),this.getTurnEndedFromError(e,o)),e.signal.aborted?{status:"aborted",error:JB}:{status:"error",error:o}}}getTurnEndedFromError(e,t){return e.signal.aborted?{status:"aborted",error:JB}:{status:"error",error:t}}isAwaitBackgroundMode(e){if(!Boolean(e.resumeAgentId&&!LB(e.prompt)&&e.readonly&&!0!==e.runInBackground))return!1;if(0===(e.parentConversationId??"").trim().length)throw new Error(`Missing parentConversationId for subagent await/status check (subagentId: ${e.resumeAgentId})`);return!0}async awaitBackgroundRun(e,t){const r=this.backgroundRuns.get(e);return r?this.awaitBackgroundEntry(r,t):this.isBackgroundRunBusy(e)?this.awaitBusyLifecycleRun(e,t):{status:"error",error:`No background subagent found for id: ${e}`}}async awaitBackgroundRunBounded(e,t){const r=t.agentId;if(e.signal.aborted)return new io.zJ({result:{case:"stillRunning",value:new io.L5({agentId:r})}});const n=this.backgroundRuns.get(r);if(void 0===n){const e=this.takeQueuedChildCompletion(r);return void 0!==e?"success"===e.status?new io.zJ({result:{case:"complete",value:new io.bE({agentId:r,finalMessage:e.finalMessage,toolCallCount:e.toolCallCount??0})}}):new io.zJ({result:{case:"error",value:new io.Y({agentId:r,error:e.finalMessage||"Subagent was aborted"})}}):this.isBackgroundRunBusy(r)?new io.zJ({result:{case:"stillRunning",value:new io.L5({agentId:r})}}):new io.zJ({result:{case:"notFound",value:new io.Hq({agentId:r})}})}const[o,s]=e.withTimeoutAndCancel(Math.max(0,t.timeoutMs)),i=await new Promise((e=>{const t=()=>e(void 0);o.signal.addEventListener("abort",t,{once:!0}),n.promise.then(e).finally((()=>{o.signal.removeEventListener("abort",t),s()}))}));return void 0===i||"background"===i.status||e.signal.aborted?new io.zJ({result:{case:"stillRunning",value:new io.L5({agentId:r})}}):(this.takeQueuedChildCompletion(r,n.runId),"completed"===i.status?new io.zJ({result:{case:"complete",value:new io.bE({agentId:r,finalMessage:i.finalMessage,toolCallCount:i.toolCallCount??0})}}):new io.zJ({result:{case:"error",value:new io.Y({agentId:r,error:i.error??"Subagent was aborted"})}}))}takeQueuedChildCompletion(e,t){for(const[r,n]of this.queuedChildCompletions){const o=n.findIndex((r=>r.agentId===e&&(void 0===t||r.runId===t)));if(-1===o)continue;const[s]=n.splice(o,1);return 0===n.length&&this.queuedChildCompletions.delete(r),s}}async awaitBusyLifecycleRun(e,t){for(;this.isBackgroundRunBusy(e);){if(t.aborted)return{status:"error",error:"Await timed out while task is still running"};const r=this.backgroundRuns.get(e);if(r)return this.awaitBackgroundEntry(r,t);await new Promise((e=>setTimeout(e,50)))}return{status:"completed",toolCallCount:0}}async awaitBackgroundEntry(e,t){if(t.aborted)return{status:"error",error:"Await timed out while task is still running"};const r={status:"error",error:"Await timed out while task is still running"};return new Promise((n=>{const o=()=>{n(r)};t.addEventListener("abort",o,{once:!0}),e.promise.then(n).finally((()=>t.removeEventListener("abort",o)))}))}registerParentChildLink(e,t){const r=t?.trim();if(!r||r===e||!this.sessions.has(r)&&r!==this.parentConversationId)return;const n=this.childParentIds.get(e);if(n===r)return;n&&(this.parentChildIds.get(n)?.delete(e),0===(this.parentChildIds.get(n)?.size??0)&&this.parentChildIds.delete(n)),this.childParentIds.set(e,r);const o=this.parentChildIds.get(r)??new Set;o.add(e),this.parentChildIds.set(r,o)}removeParentChildLink(e){const t=this.childParentIds.get(e);if(!t)return;this.childParentIds.delete(e);const r=this.parentChildIds.get(t);r?.delete(e),0===(r?.size??0)&&this.parentChildIds.delete(t)}enqueueChildCompletion(e,t,r){const n=this.childParentIds.get(e);if(!n)return;const o=this.queuedChildCompletions.get(n)??[];o.push({agentId:e,runId:t,status:"completed"===r.status?"success":"error"===r.status?"error":"aborted",finalMessage:"completed"===r.status?r.finalMessage??"":"error"===r.status?r.error:"Subagent was aborted by the user",..."completed"===r.status&&void 0!==r.toolCallCount?{toolCallCount:r.toolCallCount}:{}}),this.queuedChildCompletions.set(n,o),this.removeParentChildLink(e);const s=this.childCompletionWaiters.get(n);if(s){this.childCompletionWaiters.delete(n);for(const e of s)e()}}async collectAvailableChildCompletions(e,t){const r=this.drainChildCompletions(e);return r.length>0?r:this.hasPendingChildSubagents(e)?(await this.waitForChildCompletion(e,t),this.drainChildCompletions(e)):[]}hasPendingChildSubagents(e){return(this.parentChildIds.get(e)?.size??0)>0}drainChildCompletions(e){const t=this.queuedChildCompletions.get(e)??[];return this.queuedChildCompletions.delete(e),t}async waitForChildCompletion(e,t){if(t.aborted)throw new Error("aborted");await new Promise(((r,n)=>{const o=this.childCompletionWaiters.get(e)??new Set,s=()=>{a(),r()},i=()=>{a(),n(new Error("aborted"))},a=()=>{o.delete(s),0===o.size&&this.childCompletionWaiters.delete(e),t.removeEventListener("abort",i)};o.add(s),this.childCompletionWaiters.set(e,o),t.addEventListener("abort",i,{once:!0})}))}buildChildrenCompletedMessage(e,t){const r=e.map((e=>{const t="success"===e.status?"SUCCESS":"FAILED";return`## Agent ${e.agentId} -- ${t}\n\n${e.finalMessage}`})).join("\n\n---\n\n");return t.replace("{summaries}",r)}}var XB=r("../proto/dist/generated/agent/v1/agent_service_connect.js"),QB=r("../proto/dist/generated/agent/v1/requested_model_pb.js"),YB=r("../proto/dist/generated/agent/v1/selected_context_pb.js"),eW=r("./src/agent/analytics.ts"),tW=r("../proto/dist/generated/agent/v1/todo_tool_pb.js");const rW={[Ng.w3.UNSPECIFIED]:"unspecified",[Ng.w3.LEFT]:"left",[Ng.w3.RIGHT]:"right",[Ng.w3.MIDDLE]:"middle",[Ng.w3.BACK]:"back",[Ng.w3.FORWARD]:"forward"},nW={[Ng.Dh.UNSPECIFIED]:"unspecified",[Ng.Dh.UP]:"up",[Ng.Dh.DOWN]:"down",[Ng.Dh.LEFT]:"left",[Ng.Dh.RIGHT]:"right"},oW={[Ng.EB.UNSPECIFIED]:"unspecified",[Ng.EB.TAP]:"tap",[Ng.EB.DOWN]:"down",[Ng.EB.UP]:"up"};function sW(e){return rW[e]??"unspecified"}function iW(e){return void 0===e?void 0:{x:e.x,y:e.y}}function aW({result:e}){switch(e.case){case"success":return{status:"success",value:{actionCount:e.value.actionCount,durationMs:e.value.durationMs,settleMs:e.value.settleMs,screenshotPath:e.value.screenshotPath,cursorPosition:iW(e.value.cursorPosition),log:e.value.log}};case"error":return{status:"error",error:{message:e.value.error,actionCount:e.value.actionCount,durationMs:e.value.durationMs,screenshotPath:e.value.screenshotPath,log:e.value.log}};default:return}}function cW(e,t){switch(e.message.case){case"textDelta":return{type:"text-delta",text:e.message.value.text};case"thinkingDelta":return{type:"thinking-delta",text:e.message.value.text};case"thinkingCompleted":return{type:"thinking-completed",thinkingDurationMs:e.message.value.thinkingDurationMs};case"userMessageAppended":return{type:"user-message-appended",userMessage:{type:"user_message",session_id:t,text:e.message.value.userMessage?.text??""}};case"tokenDelta":return{type:"token-delta",tokens:e.message.value.tokens};case"summary":return{type:"summary",summary:e.message.value.summary};case"summaryStarted":return{type:"summary-started"};case"summaryCompleted":{const{failed:t,fallback:r}=e.message.value;return{type:"summary-completed",...t?{failed:t}:{},...r?{fallback:r}:{}}}case"shellOutputDelta":return{type:"shell-output-delta",event:e.message.value.event.case?{case:e.message.value.event.case,value:e.message.value.event.value?.toJson?.()??e.message.value.event.value}:{}};case"toolCallStarted":return lW("tool-call-started",e.message.value);case"partialToolCall":return lW("partial-tool-call",e.message.value);case"toolCallCompleted":return lW("tool-call-completed",e.message.value);case"heartbeat":return null;case"turnEnded":{const t=e.message.value;return{type:"turn-ended",...(void 0!==t.inputTokens||void 0!==t.outputTokens||void 0!==t.cacheReadTokens||void 0!==t.cacheWriteTokens)&&{usage:{inputTokens:Number(t.inputTokens??BigInt(0)),outputTokens:Number(t.outputTokens??BigInt(0)),cacheReadTokens:Number(t.cacheReadTokens??BigInt(0)),cacheWriteTokens:Number(t.cacheWriteTokens??BigInt(0)),...t.reasoningTokens&&{reasoningTokens:Number(t.reasoningTokens)}}}}}case"modelCallCompleted":{const t=e.message.value;return{type:"model-call-completed",modelCallId:t.modelCallId,usage:{inputTokens:Number(t.inputTokens),outputTokens:Number(t.outputTokens),cacheReadTokens:Number(t.cacheReadTokens),cacheWriteTokens:Number(t.cacheWriteTokens),...t.reasoningTokens&&{reasoningTokens:Number(t.reasoningTokens)}}}}case"toolCallDelta":{const r=e.message.value,n=r.toolCallDelta;if("taskToolCallDelta"!==n?.delta.case)return null;const o=n.delta.value.interactionUpdate;if(void 0===o)return null;const s=cW(o,t);return null!==s&&function(e){switch(e.type){case"text-delta":case"thinking-delta":case"thinking-completed":case"tool-call-started":case"tool-call-completed":case"partial-tool-call":case"step-started":case"step-completed":case"tool-requests-listed":return!0;default:return!1}}(s)?{type:"tool-call-delta",callId:r.callId,modelCallId:r.modelCallId,taskUpdate:s}:null}case"stepStarted":return{type:"step-started",stepId:Number(e.message.value.stepId)};case"toolRequestsListed":return{type:"tool-requests-listed",callCount:e.message.value.callCount};case"stepCompleted":return{type:"step-completed",stepId:Number(e.message.value.stepId),stepDurationMs:Number(e.message.value.stepDurationMs)};case"postRequestPrompt":case"activeBranchChange":case"feedbackRequest":case"responseComparison":case"contextInjectionState":case"routedModel":case"grokBotNudge":case"thinkingNote":case"voiceCallUtterance":case void 0:return null;default:return e.message,null}}function lW(e,t){const r=function(e){if(!e?.tool)return null;switch(e.tool.case){case"shellToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"shell",args:{command:t.command,...t.workingDirectory?{workingDirectory:t.workingDirectory}:{},...t.timeout?{timeout:t.timeout}:{}},...r?{result:mW(r)}:{}}:null}case"deleteToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"delete",args:{path:t.path},...r?{result:gW(r)}:{}}:null}case"globToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"glob",args:{globPattern:t.globPattern,...t.targetDirectory?{targetDirectory:t.targetDirectory}:{}},...r?{result:wW(r)}:{}}:null}case"grepToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"grep",args:{pattern:t.pattern,...t.path?{path:t.path}:{},...t.glob?{glob:t.glob}:{},...t.outputMode?{outputMode:t.outputMode}:{},...t.contextBefore?{contextBefore:t.contextBefore}:{},...t.contextAfter?{contextAfter:t.contextAfter}:{},...t.context?{context:t.context}:{},...t.caseInsensitive?{caseInsensitive:t.caseInsensitive}:{},...t.type?{type:t.type}:{},...t.headLimit?{headLimit:t.headLimit}:{},...void 0!==t.offset?{offset:t.offset}:{},...t.multiline?{multiline:t.multiline}:{},...t.sort?{sort:t.sort}:{},...t.sortAscending?{sortAscending:t.sortAscending}:{}},...r?{result:yW(r)}:{}}:null}case"readToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"read",args:{path:t.path},...r?{result:bW(r)}:{}}:null}case"editToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"edit",args:{path:t.path},...r?{result:SW(r)}:{}}:null}case"lsToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"ls",args:{path:t.path,...t.ignore&&t.ignore.length>0?{ignore:t.ignore}:{}},...r?{result:kW(r)}:{}}:null}case"readLintsToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"readLints",args:{paths:t.paths},...r?{result:CW(r)}:{}}:null}case"mcpToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"mcp",args:{...t.providerIdentifier?{providerIdentifier:t.providerIdentifier}:{},...t.toolName?{toolName:t.toolName}:{},...t.args?{args:Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()])))}:{}},...r?{result:EW(r)}:{}}:null}case"generateImageToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"generateImage",args:{description:t.description,...t.filePath?{filePath:t.filePath}:{}},...r?{result:PW(r)}:{}}:null}case"recordScreenToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"recordScreen",args:{mode:RW(t.mode)},...r?{result:IW(r)}:{}}:null}case"semSearchToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"semSearch",args:{query:t.query,...t.targetDirectories&&t.targetDirectories.length>0?{targetDirectories:t.targetDirectories}:{},...t.explanation?{explanation:t.explanation}:{}},...r?{result:xW(r)}:{}}:null}case"createPlanToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"createPlan",args:{plan:t.plan},...r?{result:TW(r)}:{}}:null}case"updateTodosToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"updateTodos",args:{todos:t.todos.map((e=>({content:e.content,status:$W(e.status)})))},...r?{result:AW(r)}:{}}:null}case"fetchToolCall":case"switchModeToolCall":return null;case"computerUseToolCall":return function({args:e,result:t}){return e?{type:"computerUse",args:{actions:e.actions.flatMap((e=>function({action:e}){switch(e.case){case"mouseMove":return{type:"mouseMove",coordinate:iW(e.value.coordinate)};case"click":return{type:"click",coordinate:iW(e.value.coordinate),button:sW(e.value.button),count:e.value.count,modifierKeys:e.value.modifierKeys};case"mouseDown":case"mouseUp":return{type:e.case,button:sW(e.value.button)};case"drag":return{type:"drag",path:e.value.path.map((e=>({x:e.x,y:e.y}))),button:sW(e.value.button),modifierKeys:e.value.modifierKeys};case"scroll":return{type:"scroll",coordinate:iW(e.value.coordinate),direction:nW[e.value.direction]??"unspecified",amount:e.value.amount,modifierKeys:e.value.modifierKeys};case"type":return{type:"type",text:e.value.text};case"key":return{type:"key",key:e.value.key,holdDurationMs:e.value.holdDurationMs,stroke:oW[e.value.stroke]??"unspecified"};case"wait":return{type:"wait",durationMs:e.value.durationMs};case"screenshot":case"cursorPosition":return{type:e.case};default:return}}(e)??[])),description:e.description},result:t?aW(t):void 0}:null}(e.tool.value);case"readTodosToolCall":case"webSearchToolCall":case"listMcpResourcesToolCall":case"readMcpResourceToolCall":return null;case"taskToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"task",args:uW(t),...r?{result:pW(r)}:{}}:null}case"applyAgentDiffToolCall":case"askQuestionToolCall":case"writeShellStdinToolCall":case"reflectToolCall":case"setupVmEnvironmentToolCall":case"replaceEnvToolCall":case"startGrindExecutionToolCall":case"startGrindPlanningToolCall":case"truncatedToolCall":case"webFetchToolCall":case"reportBugfixResultsToolCall":case"aiAttributionToolCall":case"prManagementToolCall":case"editPrLabelsToolCall":case"fetchCloudAgentDataToolCall":case"mcpAuthToolCall":case"connectScmToolCall":case"searchConversationsToolCall":case"awaitToolCall":case"blameByFilePathToolCall":case"getMcpToolsToolCall":case"reportBugToolCall":case"setActiveBranchToolCall":case"communicateUpdateToolCall":case"sendFinalSummaryToolCall":case"updateOriginPrCodeTourToolCall":case"getOriginPrCodeTourToolCall":case"recordCiInvestigationFindingsToolCall":case"sendMessageToolCall":case"sendToUserToolCall":case"createGoalToolCall":case"updateGoalToolCall":case"getAgentStatusToolCall":case"sendToAgentToolCall":case"readAgentTranscriptToolCall":case"createAgentToolCall":case"createProjectToolCall":case"startProjectUpdatesToolCall":case"stopProjectUpdatesToolCall":case"manageAccessToolCall":case"stopAgentToolCall":case"listTrackedTasksToolCall":case"createTrackedTasksToolCall":case"updateTrackedTasksToolCall":case"deleteTrackedTasksToolCall":case"updateTrackedTaskStatusesToolCall":case"updateTrackedTaskTagsToolCall":case"writeCanvasToolCall":case"readCanvasToolCall":case"generateVideoToolCall":case"xSearchToolCall":case"executeToolCall":case void 0:return null;default:return e.tool}}(t.toolCall);return r?{type:e,callId:t.callId,toolCall:r,modelCallId:t.modelCallId}:null}function uW(e){return{description:e.description??"",prompt:e.prompt??"",...e.subagentType?{subagentType:dW(e.subagentType)}:{},...e.model?{model:e.model}:{},...e.resume?{resume:e.resume}:{},...e.agentId?{agentId:e.agentId}:{},...e.attachments&&e.attachments.length>0?{attachments:e.attachments}:{},...void 0!==e.mode?{mode:hW(e.mode)}:{},...e.respondingToMessageIds&&e.respondingToMessageIds.length>0?{respondingToMessageIds:e.respondingToMessageIds}:{}}}function dW(e){const t=e.type.case;return t?"custom"===t?{kind:t,name:e.type.value.name}:{kind:t}:{kind:"unspecified"}}function hW(e){switch(e){case Sg.FL.AGENT:return"agent";case Sg.FL.PLAN:return"plan";default:return"unspecified"}}function pW(e){if(e.result?.case)switch(e.result.case){case"success":{const t=e.result.value;return{status:"success",value:{...t.conversationSteps&&t.conversationSteps.length>0?{conversationSteps:t.conversationSteps.map((e=>e.toJson?.()??e))}:{},...t.agentId?{agentId:t.agentId}:{},isBackground:t.isBackground??!1,...void 0!==t.durationMs?{durationMs:Number(t.durationMs)}:{},...t.resultSuffix?{resultSuffix:t.resultSuffix}:{},backgroundReason:fW(t.backgroundReason),...t.transcriptPath?{transcriptPath:t.transcriptPath}:{}}}}case"error":return{status:"error",error:{message:e.result.value.error??"Task failed"}};default:return}}function fW(e){switch(e){case Sg.qL.AGENT_REQUEST:return"agentRequest";case Sg.qL.USER_REQUEST:return"userRequest";case Sg.qL.QUEUED_FOLLOW_UP:return"queuedFollowUp";default:return"unspecified"}}function mW(e){if(e.result?.case)switch(e.result.case){case"success":case"failure":{const t=e.result.value;return{status:"success",value:{exitCode:t.exitCode??0,signal:t.signal??"",stdout:t.stdout??"",stderr:t.stderr??"",executionTime:t.executionTime??0}}}case"timeout":return{status:"error",error:{message:`Command timed out after ${e.result.value.timeoutMs}ms`,command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};case"rejected":return{status:"error",error:{message:e.result.value.reason??"Command rejected",command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};case"spawnError":return{status:"error",error:{message:e.result.value.error??"Failed to spawn command",command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};default:return}}function gW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{fileSize:Number(e.result.value.fileSize??0)}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.value.clientVisibleError??e.result.case,path:e.result.value.path}}}function wW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{files:e.result.value.files??[],totalFiles:e.result.value.totalFiles??0,clientTruncated:e.result.value.clientTruncated??!1,ripgrepTruncated:e.result.value.ripgrepTruncated??!1}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case}}}function yW(e){if(e.result?.case){if("success"===e.result.case){const t=e.result.value,r={};if(t.workspaceResults)for(const[e,n]of Object.entries(t.workspaceResults))r[e]=vW(n);return{status:"success",value:{...Object.keys(r).length>0?{workspaceResults:r}:{},...t.activeEditorResult?{activeEditorResult:vW(t.activeEditorResult)}:{}}}}return{status:"error",error:{message:e.result.value.error??e.result.case}}}}function vW(e){if(e?.result?.case)switch(e.result.case){case"content":return{type:"content",output:{matches:e.result.value.matches?.map((e=>({file:e.file,...void 0!==e.lineNumber?{lineNumber:e.lineNumber}:{},line:e.line,...e.beforeContext?{beforeContext:e.beforeContext}:{},...e.afterContext?{afterContext:e.afterContext}:{}})))??[],totalMatches:e.result.value.totalMatches??0}};case"files":return{type:"files",output:{files:e.result.value.files??[],count:e.result.value.count??0}};case"count":return{type:"count",output:{counts:e.result.value.counts?.map((e=>({file:e.file,count:e.count})))??[],total:e.result.value.total??0}};default:return}}function bW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{content:"content"===e.result.value.output.case?e.result.value.output.value:"",totalLines:e.result.value.totalLines??0,fileSize:Number(e.result.value.fileSize??0)}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case,path:e.result.value.path}}}function SW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{...void 0!==e.result.value.linesAdded?{linesAdded:e.result.value.linesAdded}:{},...void 0!==e.result.value.linesRemoved?{linesRemoved:e.result.value.linesRemoved}:{},...e.result.value.diffString?{diffString:e.result.value.diffString}:{}}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case,path:e.result.value.path}}}function kW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{directoryTreeRoot:_W(e.result.value.directoryTreeRoot)}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function _W(e){if(e)return{absPath:e.absPath??"",childrenDirs:e.childrenDirs?.map(_W)??[],childrenFiles:e.childrenFiles?.map((e=>({name:e.name})))??[],childrenWereProcessed:e.childrenWereProcessed??!1,fullSubtreeExtensionCounts:e.fullSubtreeExtensionCounts??{},numFiles:e.numFiles??0}}function CW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{fileDiagnostics:e.result.value.fileDiagnostics?.map((e=>({path:e.path,diagnostics:e.diagnostics?.map((e=>({severity:MW(e.severity),...e.range?{range:{...e.range.start?{start:{line:e.range.start.line,character:e.range.start.character}}:{},...e.range.end?{end:{line:e.range.end.line,character:e.range.end.character}}:{}}}:{},message:e.message,source:e.source,code:e.code})))??[],diagnosticsCount:e.diagnosticsCount??0})))??[],totalFiles:e.result.value.totalFiles??0,totalDiagnostics:e.result.value.totalDiagnostics??0}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function EW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{content:e.result.value.content?.map((e=>{const t={};return"text"===e.content?.case?t.text={text:e.content.value.text}:"image"===e.content?.case&&(t.image={data:e.content.value.data,...e.content.value.mimeType?{mimeType:e.content.value.mimeType}:{}}),t}))??[],isError:e.result.value.isError??!1}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case}}}function xW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{results:e.result.value.results??""}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function PW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{filePath:e.result.value.filePath??""}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function RW(e){switch(e){case T$.$u.START_RECORDING:return"START_RECORDING";case T$.$u.SAVE_RECORDING:return"SAVE_RECORDING";case T$.$u.DISCARD_RECORDING:return"DISCARD_RECORDING";default:throw new Error(`Unknown RecordingMode: ${e}`)}}function IW(e){if(e.result?.case)switch(e.result.case){case"startSuccess":return{status:"success",value:{wasPriorRecordingCancelled:e.result.value.wasPriorRecordingCancelled??!1}};case"saveSuccess":return{status:"success",value:{path:e.result.value.path??"",recordingDurationMs:Number(e.result.value.recordingDurationMs??0)}};case"discardSuccess":return{status:"success",value:{}};case"failure":return{status:"error",error:{message:e.result.value.error??"Unknown error"}};default:return}}function TW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function AW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{todos:e.result.value.todos?.map((e=>({content:e.content,status:$W(e.status)})))??[],totalCount:e.result.value.totalCount??0}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function $W(e){switch(e){case tW.Vj.UNSPECIFIED:case tW.Vj.PENDING:return"pending";case tW.Vj.IN_PROGRESS:return"inProgress";case tW.Vj.COMPLETED:return"completed";case tW.Vj.CANCELLED:return"cancelled";default:return"pending"}}function MW(e){switch(e){case NA.h_.UNSPECIFIED:case NA.h_.ERROR:return"error";case NA.h_.WARNING:return"warning";case NA.h_.INFORMATION:return"information";case NA.h_.HINT:return"hint";default:return"error"}}const DW={type:"object",properties:{},additionalProperties:!0};function OW(e){const t={};for(const[r,n]of Object.entries(e))t[r]=n;return t}function FW(e){return"text"===e.type?new Mc._Z({content:{case:"text",value:new Mc.zN({text:e.text})}}):new Mc._Z({content:{case:"image",value:new Mc.do({data:n.Buffer.from(e.data,"base64"),mimeType:e.mimeType??""})}})}function NW(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var LW=r("./src/agent/errors.ts");const jW="Shell is not available when local.fs is set: the agent's files live in a FileSystem, and a shell would run on the host disk. Use Read, Grep, Glob, LS, and the edit tools instead.";function UW(e){return{async execute(){throw new Error(e)}}}function BW(e){var t;e.register(WT,UW(jW)),e.register(re,(t=jW,{async*execute(){throw new Error(t)}})),e.register(kA,UW(jW)),e.register(RA,UW(jW)),e.register(_A,UW(jW)),e.register(HT,UW(jW)),e.register(oA,UW("ReadLints is not available when local.fs is set: lint diagnostics come from a host language service, not the FileSystem.")),e.register(JT,UW("Git is not available when local.fs is set: the agent's files live in a FileSystem, not a host git checkout."))}var WW=r("./src/agent/filesystem/executors.ts"),HW=r("./src/agent/filesystem/compose.ts"),qW=r("./src/agent/filesystem/trees.ts"),zW=r("./src/agent/filesystem/walk.ts");const GW="/tmp",VW=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.txt$/i;function KW(e){const{write:t,hostProjectDir:r}=e;return{async execute(e,n,o){const s=function(e){if(t=e.writePath,!/^([/\\]|[A-Za-z]:[/\\])/.test(t))return;var t;const r=function(e){if(void 0===e.hostProjectDir||""===e.hostProjectDir)return;const t=(0,zW.eI)(e.hostProjectDir),r=(0,zW.eI)(e.writePath);return"/"!==t&&(0,zW.hJ)({path:r,prefix:t})?r.slice(t.length):void 0}(e),n=void 0===r?(0,zW.eI)(e.writePath):(0,zW.eI)(`${GW}/${r}`);if(!(0,zW.hJ)({path:n,prefix:GW}))return;const o=a().posix.basename(n),s=a().posix.join(GW,Dc);return a().posix.dirname(n)===s&&VW.test(o)?a().posix.join(GW,o):n}({writePath:n.path,hostProjectDir:r});if(void 0===s||s===n.path)return await t.execute(e,n,o);const i=n.clone();i.path=s;const c=await t.execute(e,i,o);return"success"===c.result.case&&(c.result.value.path=s),c}}}class JW{constructor(e,t="/"){this.fs=e,this.listeners=new Set,this.workspace=(0,zW.eI)(t)}getAllCursorRules(e){return this.rules??=async function(e,t){const[r,n]=await Promise.all([ZW(e,s.posix.join(t,".cursor/rules")),XW(e,s.posix.join(t,"AGENTS.md"))]);return void 0===n?r:[...r,n]}(this.fs,this.workspace),this.rules}reload(e){this.rules=void 0;for(const e of this.listeners)e()}onDidChangeRules(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}dispose(){this.listeners.clear()}}async function ZW(e,t){const r=[];try{for await(const n of e.list(t))"directory"!==n.kind&&n.path.endsWith(".mdc")&&r.push(n.path)}catch{return[]}return(await(0,Nr.PH)(r,(async t=>{const r=await QW(e,t),n=void 0===r?null:rn(r);if(null!==n)return fg({path:t,body:n.body,frontmatter:n.frontmatter,rawFrontmatter:n.rawFrontmatter})}),{max:8})).filter((e=>void 0!==e))}async function XW(e,t){const r=await QW(e,t);if(void 0!==r)return fg({path:t,body:Qr({content:r,filename:"AGENTS.md"}),frontmatter:{alwaysApply:!0}})}async function QW(e,t){try{const r=await e.read(t);return"string"==typeof r?r:(new TextDecoder).decode(r)}catch{return}}const YW={getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}},eH={async exec(){throw new Error("git is not available in a FileSystem session")}},tH={isIgnoredByAny:async()=>!1,isGitIgnored:async()=>!1,isCursorIgnored:async()=>!1,isRepoBlocked:async()=>!1,listCursorIgnoreFilesByRoot:async()=>[],getCursorIgnoreMapping:async()=>({}),getShellSandboxIgnoreMapping:async()=>({}),getGitIgnoreMapping:async()=>({}),getRepoBlockExcludeGlobs:async()=>[]};function rH(e){return{cursorRulesService:!0===e.includeProjectRules?new JW(e.fs,e.workspace):YW,getAgentSkills:async()=>[],subagentsService:e.subagentsService??new _g,gitExecutor:eH,ignoreService:tH,requestContextIsWorkingDirHomeDir:!1,reportProcessWorkingDirectory:!1}}function nH(e,t){const r=t.workspace??"/",n=(0,WW.c9)(e,{workspace:r});return{localResourceProviderOptions:{overrideReadExecutor:n.read,overrideWriteExecutor:KW({write:n.write,hostProjectDir:t.hostProjectDir}),overrideGrepExecutor:n.grep,overrideLsExecutor:n.ls,overrideDeleteExecutor:n.delete,suppressDefaultShellExecutor:!0,...rH({...t.settings,fs:e,workspace:r})},reportedWorkspacePath:r,reportedProjectFolder:GW,excludeHooks:!0,excludeProjectMcp:!0}}var oH=r("./src/agent/executor-common.ts");class sH{constructor(){this.countsByMode=new Map,this.failureKindsByMode=new Map,this.record=e=>{let t=this.countsByMode.get(e.mode);switch(void 0===t&&(t={mode:e.mode,checked_calls:0,outside_limit_calls:0,settings_unavailable_calls:0,unknown_server_calls:0},this.countsByMode.set(e.mode,t)),e.outcome){case"within_limit":return void(t.checked_calls+=1);case"outside_limit":return t.checked_calls+=1,void(t.outside_limit_calls+=1);case"settings_unavailable":{t.settings_unavailable_calls+=1;const r=e.settingsFailure;if(void 0===r)return;let n=this.failureKindsByMode.get(e.mode);return void 0===n&&(n=new Map,this.failureKindsByMode.set(e.mode,n)),void n.set(r,(n.get(r)??0)+1)}case"unknown_server":return void(t.unknown_server_calls+=1);default:return e.outcome}}}take(){const e=[...this.countsByMode.values()].map((e=>{const t=function(e){let t;for(const[r,n]of e??[])(void 0===t||n>t.calls)&&(t={kind:r,calls:n});return t?.kind}(this.failureKindsByMode.get(e.mode));return void 0===t?e:{...e,settings_unavailable_kind:t}}));return this.countsByMode.clear(),this.failureKindsByMode.clear(),e}}class iH{constructor(e=e=>{console.warn(e)}){this.write=e,this.printed=new Set,this.report=e=>{if(!this.printed.has(e.serverName)){this.printed.add(e.serverName);try{this.write(function(e){return`[cursor-sdk] ${e.refusal}`}(e))}catch{}}}}}const aH=new class{constructor(e=e=>{console.warn(e)}){this.write=e,this.printed=new Set,this.report=e=>{const t=JSON.stringify([e.serverName,(r=e.allowlist,JSON.stringify([r.list,r.name,r.reason,r.allowedServers??null,r.blockedServers??null]))]);var r;if(!this.printed.has(t)){this.printed.size>=1e3&&this.printed.clear(),this.printed.add(t);try{this.write(function(e){return`[cursor-sdk] MCP server "${e.serverName}" is under ${function(e){return`${e.name}, which applies because ${e.reason}.${r=e.allowedServers,void 0===r?"":0===r.length?" Allowed servers: none.":zC("Allowed servers",r)}${t=e.blockedServers,void 0===t||0===t.length?"":zC("Blocked",t)}`;var t,r}(e.allowlist)}`}(e))}catch{}}}}};var cH=r("./src/agent/native/vendored-tree-sitter.ts"),lH=r("./src/agent/platform-package-locator.ts"),uH=r("./src/agent/sdk-config.ts"),dH=r("../../node_modules/.pnpm/@statsig+js-client@3.31.0/node_modules/@statsig/js-client/src/index.js"),hH=r("./src/agent/utils/logger.ts");const pH={checkFeatureGate:()=>!1,getDynamicConfigValue:({defaultValue:e})=>e},fH=new Map;async function mH(e){try{const t=await async function(e){const t=await(0,oH.dC)(e,oH.EV);if(!t)return;const r=oH.EV.endsWith("/")?oH.EV.slice(0,-1):oH.EV,n=await fetch(`${r}/aiserver.v1.AnalyticsService/BootstrapStatsig`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json","x-cursor-client-type":"sdk","x-cursor-client-version":(0,oH.tF)(),"x-ghost-mode":(0,oH.U)(e)},body:JSON.stringify({})});if(!n.ok)return void hH.v.log(`Failed to bootstrap SDK Statsig: ${n.status} ${n.statusText}`);const o=await n.json();return gH(o)&&"string"==typeof o.config&&o.config.length>0?o.config:void 0}(e);if(!t)return pH;const r=new dH.StatsigClient("client-Bm4HJ0aDjXHQVsoACMREyLNxm5p6zzuzhO50MgtoT5D",function(e){try{const r=JSON.parse(e);if(gH(r)&&"object"==typeof(t=r.user)&&null!==t&&!Array.isArray(t))return{...r.user,custom:{...r.user.custom,clientType:"sdk",clientVersion:(0,oH.tF)()}}}catch(e){hH.v.log(`Failed to parse SDK Statsig bootstrap user: ${e instanceof Error?e.message:String(e)}`)}var t;return{custom:{clientType:"sdk",clientVersion:(0,oH.tF)()}}}(t),{disableLogging:!0,disableStorage:!0,networkConfig:{preventAllNetworkTraffic:!0}});return r.dataAdapter.setData(t),r.initializeSync(),{checkFeatureGate:(e,t)=>{try{return r.checkGate(e,t)}catch{return!1}},getDynamicConfigValue({configName:e,paramName:t,defaultValue:n}){try{return r.getDynamicConfig(e).get(t,n)}catch{return n}}}}catch(e){return hH.v.log(`Failed to initialize SDK Statsig: ${e instanceof Error?e.message:String(e)}`),pH}}function gH(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function wH(e){let t;return e?.then((e=>{t=e}),(()=>{})),()=>t?.checkFeatureGate("grok_bot_mcp_app_payment_token_filter",{disableExposureLog:!0})??!1}var yH=r("./src/agent/tools-option.ts");class vH{async requestApproval(){return{approved:!0}}}function bH(e,t){if(!function(e){return void 0!==e&&Object.keys(e).length>0}(t))return;const r=e.resources.base;if(!(r instanceof cD))throw new LW.j1("SDK custom tools require the default local workspace resource provider.",{isRetryable:!1});const n=r.getMcpExecutionPolicyDeps(),o=r.get(ro),s=function(e,t){return{async execute(r,n,o){const s=n.toolName||function(e){const t=`${Vn}-`;return e.startsWith(t)?e.slice(t.length):e}(n.name),i=e[s];if(void 0===i)return new Mc.iz({result:{case:"error",value:new Mc.Nh({error:`Unknown custom tool: ${s}`})}});try{return function(e){const t=function(e){return"object"==typeof(t=e)&&null!==t&&!Array.isArray(t)&&"content"in t&&Array.isArray(t.content)?{content:e.content,isError:e.isError,structuredContent:e.structuredContent}:"string"==typeof e?{content:[{type:"text",text:e}]}:{content:[{type:"text",text:JSON.stringify(e)}],structuredContent:NW(e)?e:void 0};var t}(e),r=void 0!==t.structuredContent?ve.Struct.fromJson(t.structuredContent):void 0;return new Mc.iz({result:{case:"success",value:new Mc.QW({content:t.content.map(FW),isError:t.isError??!1,structuredContent:r})}})}(await i.execute(function(e){return Object.fromEntries(Object.entries(e.args).map((([e,t])=>[e,t.toJson()])))}(n),{toolCallId:n.toolCallId||void 0,...void 0===t||""===t?{}:{sessionId:t}}))}catch(e){return new Mc.iz({result:{case:"error",value:new Mc.Nh({error:e instanceof Error?e.message:String(e)})}})}}}}(t,e.state.sessionId),i=new vH;e.resources.base.register(ro,{async execute(e,t,r){if(function(e){return e.providerIdentifier===Vn}(t)){const o=await RT(e,t,{...n,pendingDecisionProvider:i,toolDef:{source:"internal"}});return void 0!==o?o:s.execute(e,t,r)}return o.execute(e,t,r)}})}const SH=new Set(["127.0.0.1","localhost","[::1]"]);function kH(e){if(void 0===e)return{};const t=e.resourceProviderOptions;return{...void 0!==t?{localResourceProviderOptions:t}:{},...void 0!==e.reportedWorkspacePath?{reportedWorkspacePath:e.reportedWorkspacePath}:{}}}function _H(){const e=process.env.CURSOR_SDK_MOCK_PROMPT_TIME;if(void 0===e||""===e)return;const t=new Date(e);return Number.isNaN(t.getTime())?void 0:t}const CH={warn(){},error(){}},EH={log(){}};class xH{async requestApproval(e){return{approved:!1,reason:`Local SDK runs cannot request interactive approval for ${PH(e)}. Keep the action within the configured sandbox policy or Smart Auto Review's auto-approval boundary, or re-run without sandboxing/autoReview enabled.`}}}function PH(e){switch(e.type){case Bw.Shell:return"this shell command";case Bw.Mcp:return"this MCP tool call";case Bw.Write:return"this file edit";case Bw.Delete:return"this file deletion";default:return"this operation"}}function RH(e){return void 0!==e&&"insecure_none"!==e.type}async function IH(e,t){const r="string"==typeof e||void 0===e?{workingDirectory:e,apiKey:t}:e,i=(0,b.q6)().with(d._O,EH),a=CB(r.settingSources),l=void 0===r.hostMcpBridgeUrls?void 0:r.hostMcpBridgeUrls.filter((e=>{let t;try{t=new URL(e)}catch{t=void 0}const r=void 0!==t&&"http:"===t.protocol&&""===t.username&&""===t.password&&SH.has(t.hostname);return r||console.warn(`[cursor-sdk] ignoring local.hostMcpBridgeUrls entry ${e}: not an http URL on 127.0.0.1, localhost or [::1]`),r}));!function(e){if(void 0!==e&&(!Number.isFinite(e)||e<=0))throw new Error(`Workspace scan cache TTL must be a positive number of milliseconds, got ${e}`);ba=e}((0,uH.Mu)()),/:\/\/(localhost|127\.0\.0\.1)/.test(oH.EV)&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0");const u=performance.now();let h=0;if(r.apiKey){const e=performance.now();await Promise.all([(0,oH.ly)(r.apiKey),(0,oH.mU)(r.apiKey)]),h=performance.now()-e}const p=r.workingDirectory||process.cwd();(0,cH.configureVendoredTreeSitterWorkspaceDir)(p);for(const e of r.dirs??[])(0,cH.configureVendoredTreeSitterWorkspaceDir)(e);const f=(0,_o.Rv)((0,o.homedir)(),p),m={hostProjectDir:f,settings:{includeProjectRules:EB(a,"project"),subagentsService:new FB(r.customSubagents??[])}};let g;const w="win32"===process.platform?"rg.exe":"rg",y=process.env.CURSOR_RIPGREP_PATH;g=y&&(0,s.isAbsolute)(y)?y:(0,lH.hQ)({binaryName:w,excludedWorkspaceDir:p}),g||(g=(0,No.xS)()),g&&(0,No.J)(g);let v,S,k,_={getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getAdminCommandDenylist:async()=>({rules:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}};if(r.apiKey)try{const e=(0,oH.qN)(r.apiKey,r.teamId);v=e.transport,S=e.getAccessToken;const t=(0,be.createClient)(wj.I,v),n=function(e){let t=fH.get(e);return t||(t=mH(e),fH.set(e,t),t.then((r=>{r===pH&&fH.get(e)===t&&fH.delete(e)}),(()=>{fH.get(e)===t&&fH.delete(e)}))),t}(r.apiKey);k=n;const o={getDefaultNetworkAllowlist:async()=>(await n).getDynamicConfigValue({configName:"sandbox_default_network_allowlist",paramName:"allowlist",defaultValue:[]})};_=new vO(new gO(t,{supportsHostMcpBridgeExemption:!0}),o,{...void 0===l?{}:{hostMcpBridgeUrls:l},mcpAdminToolLimitSurvivesFailedRead:!0,isMcpAccessNetworkAllowlistEnabled:async()=>(await n).checkFeatureGate("mcp_access_network_allowlist"),isMcpSettingsOverhaulEnabled:async e=>(await n).checkFeatureGate("mcp_settings_overhaul",e),isWin32UserExtensionStdioUnsandboxEnabled:async e=>(await n).checkFeatureGate("mcp_user_extension_stdio_unsandboxed_win32",e),isAdminCommandDenylistEnforcementKilled:async()=>(await n).checkFeatureGate("admin_command_denylist_enforcement_killswitch")})}catch(e){hH.v.log(`Failed to initialize authenticated dashboard services: ${e instanceof Error?e.message:String(e)}`)}const C=performance.now(),E=r.apiKey?await(0,No.tv)(`${(0,o.homedir)()}/.cursor/sandbox.json`,(0,o.homedir)()):void 0,x=void 0!==r.apiKey?await async function(e){const{cwd:t,perUserSandboxPolicy:r,sandboxOptions:n}=e;if(!1===n?.enabled)return{defaultSandboxPolicy:{type:"insecure_none"},defaultSandboxPolicySources:void 0};const o=RH(r)?r:!0===n?.enabled?function(e,t={}){return{type:e,...t}}("workspace_readwrite",{networkPolicy:(0,No.Po)()}):void 0;if(void 0===o)return{defaultSandboxPolicy:{type:"insecure_none"},defaultSandboxPolicySources:void 0};if(function(e){const t="win32"===process.platform?"cursorsandbox.exe":"cursorsandbox",r=(0,lH.hQ)({binaryName:t,excludedWorkspaceDir:e});r&&(0,No.St)({sandboxBinaryPath:r})}(t),!(0,No.K3)(void 0,{ctx:e.initializationCtx}))throw new LW.j1("Local SDK sandboxing was requested, but sandboxing is not supported in this environment. Disable local.sandboxOptions.enabled or remove ~/.cursor/sandbox.json to run without sandboxing.",{isRetryable:!1});const s={};s.perUser=o;const{policy:i}=await(0,No.resolveSandboxPolicyForWorkspace)(t,s);return{defaultSandboxPolicy:i,defaultSandboxPolicySources:s}}({cwd:p,perUserSandboxPolicy:E,sandboxOptions:r.sandboxOptions,initializationCtx:i}):void 0,P=performance.now()-C,R=x?.defaultSandboxPolicy,I=x?.defaultSandboxPolicySources,T=RH(R),A=performance.now(),$=(()=>{const e=[],t=new Set;for(const n of[p,...r.dirs??[]]){const r=(0,s.resolve)(n);t.has(r)||(t.add(r),e.push(n))}return e.length>1?e:void 0})(),M={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1},O=await async function(e){const{workingDirectory:t,projectDir:r}=e,n=function(e,t){const r=[],n=new Set;for(const o of[e,...t??[]]){const e=(0,s.resolve)(o);n.has(e)||(n.add(e),r.push(o))}return r}(t,e.dirs),o=n.length>1?n:void 0,i=CB(e.settingSources),a=e.teamSettingsService??{getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getAdminCommandDenylist:async()=>({rules:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}},c=e.defaultSandboxPolicy??{type:"insecure_none"},l=e.getSandboxSupported??(()=>(0,No.K3)(c,{ctx:e.initializationCtx})),u=e.getSandboxEnabled??(()=>"insecure_none"!==c.type&&l()),d=new xy,h=new Rc(d,a,n),p=new MB,f=new DB,m=e.getSmartModeClassifierAutoModeEnabled?.(),g=new $B(m?"allowlist":e.approvalMode??"unrestricted",c,a,e.respectAdminControls??!1),w=e.pendingDecisionProvider,y={executeIndexedGrep:void 0},v=()=>!0,b=EB(i,"plugins"),S=e.importThirdPartyPlugins??!1,k=e.mcpMetaToolEnabled??!0,_=void 0!==e.mcpServers&&Object.keys(e.mcpServers).length>0,C=void 0!==e.customSubagents&&e.customSubagents.length>0,E=_||EB(i,"project")||EB(i,"user")||b,x=EB(i,"project")||EB(i,"user")||EB(i,"mdm"),P=EB(i,"team"),R=P&&void 0!==e.dashboardTransport,I=EB(i,"project")||EB(i,"user")||P||R||b,T={teamSettingsService:a,initializationCtx:e.initializationCtx,importThirdPartyPlugins:S,ignoreApprovals:!0,includeProjectMcp:EB(i,"project"),includeUserMcp:EB(i,"user"),includePluginMcp:b,isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled,restMcpCursorAuthTokenSupplier:e.restMcpCursorAuthTokenSupplier},A=s=>TB({workingDirectory:t,...void 0!==o?{workspaceRoots:o}:{},adapters:{...s.includeMcp?{mcp:ZO({...T,inlineMcpServers:e.mcpServers})}:{},...b?{pluginBootstrap:oB({importThirdPartyPlugins:S,dashboardTransport:e.dashboardTransport})}:{},...x?{hooks:gj({includeProjectHooks:EB(i,"project"),includeUserHooks:EB(i,"user"),includeEnterpriseHooks:EB(i,"mdm"),useCommandHookStdinTransport:e.useCommandHookStdinTransport})}:{},...I?{localExtensibility:vj({includeProjectExtensibility:EB(i,"project"),includeUserExtensibility:EB(i,"user"),includeManagedSkills:R,includeTeamExtensibility:P,includePluginExtensibility:b,teamSettingsService:a,getThirdPartyExtensibilityEnabled:v,dashboardTransport:e.dashboardTransport,importThirdPartyPlugins:S})}:{},resourceFactory:fB({ignoreService:h,grepProvider:y,workspacePaths:n,diagnosticsProvider:p,repositoryProvider:f,projectDir:r??t,shellManager:void 0,defaultSandboxPolicy:c,defaultSandboxPolicySources:e.defaultSandboxPolicySources,getSandboxEnabled:u,getSandboxSupported:l,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:e.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:e.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:e.getMockPromptTime,getPowershellUtf8Options:e.getPowershellUtf8Options,mcpFileOutputThresholdBytes:void 0,mcpMetaToolEnabled:k,createMcpStateAccessor:(e,t)=>new OB(new aM(e),void 0===t?.onMcpAllowlistInUse&&void 0===t?.onMcpServerBlockedByAllowlist?void 0:{mcpLease:e,onMcpAllowlistInUse:t.onMcpAllowlistInUse,onMcpServerBlockedByAllowlist:t.onMcpServerBlockedByAllowlist}),createSessionMcpLease:(t,r)=>ZO({...T,includeProjectMcp:T.includeProjectMcp&&!0!==t.options.excludeProjectMcp,inlineMcpServers:r??e.mcpServers}).createLease({workspaceState:t.workspaceState,services:t.workspaceServices,policy:t.policy}),createSessionDependencies:r=>{const n=w??new AB;return{pendingDecisionStore:n,fileChangeTracker:new qw(t),permissionsService:new o_(h,n,g,a,t,e.respectAdminControls??!1,{enforceMcpAdminToolLimits:e.isMcpAdminToolLimitEnforced,onMcpAdminToolLimitCheck:r.options.onMcpAdminToolLimitCheck})}}}),resourceWrappers:x?[{wrapResources(e){const t=e.workspaceServices.hooksRuntime;if(!0===e.options.excludeHooks||"object"!=typeof(r=t)||null===r||!("hooksConfigLease"in r)||!("createSessionRuntime"in r)||"function"!=typeof r.createSessionRuntime||!function(e){return"object"==typeof e&&null!==e&&"get"in e&&"function"==typeof e.get&&"entries"in e&&"function"==typeof e.entries}(e.resources))return e.resources;var r;const n=t.createSessionRuntime({sessionState:e.sessionState,metadata:e.metadata});return new fj(new aj(e.resources,n.hookExecutor,(()=>function(e,t){const r=uj(t,dj,"conversationId","conversation_id")??e.sessionId??"";return{conversation_id:r,generation_id:uj(t,dj,"generationId","generation_id")??r,model:uj(t,dj,"model")??"unknown",...mF({modelId:uj(t,dj,"modelId","model_id"),modelParams:uj(t,pj,"modelParams","model_params")})}}(e.sessionState,e.metadata)),e.workspaceServices.mcpLease,void 0,void 0,t.hooksConfigLease),n)}}]:[],...C?{workspaceServicesContributors:[{contributeServices:t=>{const r=new FB(e.customSubagents??[]),n=t.services.subagentsService;return{subagentsService:void 0===n?r:new Ag([r,n])}}}]}:{}}});if(!E)return A({includeMcp:!1});try{return await A({includeMcp:!0})}catch(e){return CO.Jz.warn("[default-local-workspace-runtime] Failed to initialize MCP-enabled runtime, retrying without MCP:",{error:e,workingDirectory:t,projectDir:r,enablePlugins:b,importThirdPartyPlugins:S}),A({includeMcp:!1})}}({workingDirectory:p,...void 0!==$?{dirs:$}:{},projectDir:f,teamSettingsService:_,initializationCtx:i,dashboardTransport:v,settingSources:r.settingSources,mcpServers:r.mcpServers,customSubagents:r.customSubagents,defaultSandboxPolicy:R,defaultSandboxPolicySources:I,approvalMode:T?"allowlist":void 0,pendingDecisionProvider:T||!0===r.autoReview?new xH:void 0,getNetworkAllowlistInfo:T?()=>async function(e,t,r){const[n,o]=await Promise.all([e.getDefaultNetworkAllowlist(),e.getNetworkAccessControls()]),s=[...o.allowlist],i=`${t}/.cursor/sandbox.json`,a=await(0,No.tv)(i,t);if(a&&"insecure_none"!==a.type&&a.networkPolicy?.allow&&s.push(...a.networkPolicy.allow),"1"!==process.env[Yv.K4]&&r){const e=await(0,No.tv)(`${r}/.cursor/sandbox.json`,r);e&&"insecure_none"!==e.type&&e.networkPolicy?.allow&&s.push(...e.networkPolicy.allow)}const c=[...new Set(s)];return{hasDefaults:n.available&&n.allowlist.length>0,explicitEntries:c}}(_,(0,o.homedir)(),p):void 0,getSmartModeClassifierAutoModeEnabled:()=>!0===r.autoReview,devForceNextSmartModeClassifierBlockToken:r.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:_H,getPowershellUtf8Options:async()=>{if(void 0===k)return M;try{const e=await k;return{powershellUtf8Console:e.checkFeatureGate("shell_exec_powershell_utf8_console"),powershellUtf8ChildEnv:e.checkFeatureGate("shell_exec_powershell_utf8_child_env")}}catch{return M}},isLinkSharedPaymentTokenLogRedactionEnabled:wH(k),restMcpCursorAuthTokenSupplier:S,respectAdminControls:void 0!==r.apiKey,isMcpAdminToolLimitEnforced:void 0===k?void 0:(F=k,async()=>{try{return(await F).checkFeatureGate("sdk_local_mcp_admin_tool_limits",{disableExposureLog:!0})}catch{return!1}}),useCommandHookStdinTransport:!0});var F;const N=performance.now()-A;let L,j;return(0,eW.ou)(r.apiKey,{runtime:"local",ensure_ghost_mode_ms:Math.round(h),bootstrap_statsig_ms:0,create_workspace_runtime_ms:Math.round(N),load_sandbox_policy_ms:Math.round(P),total_ms:Math.round(performance.now()-u)}),{run:async(e,t,o)=>(0,CO.ni)(CH,(async()=>{const s=(0,D.VI)((0,b.q6)().withName("sdk.run").with(d._O,EH)),[i,a]=s.ctx.withCancel(),l=t.sessionId??(0,ye.C)(),u=t.mcpServersOverride,h=void 0===(f=t.customTools)?[]:Object.entries(f).map((([e,t])=>({clientKey:Vn,providerIdentifier:Vn,toolName:e,name:`${Vn}-${e}`,description:t.description??"",inputSchema:t.inputSchema??DW,...void 0===t.outputSchema?{}:{outputSchema:t.outputSchema},...void 0===t.annotations?{}:{annotations:OW(t.annotations)},source:"internal"})));var f;let g;const w={...m,workspace:t.fileSystemWorkspace},y=void 0===t.fileSystem?void 0:(_=await async function(e,t){return"function"==typeof e?await e(t):e}(t.fileSystem,{agentId:l,sessionId:l}),C=_,(0,HW.VL)({"/":C,[GW]:(0,qW.Om)()})),v=void 0===t.onMcpAdminToolLimitCounts?void 0:new sH,S=()=>{for(const e of v?.take()??[])try{t.onMcpAdminToolLimitCounts?.(e)}catch{}},k=new iH;var _,C;g=await O.createSessionRuntime({sessionId:l,mcpServersOverride:u,extraMcpTools:h,onMcpAdminToolLimitCheck:v?.record,onMcpAllowlistInUse:aH.report,onMcpServerBlockedByAllowlist:k.report,...void 0===y?kH(t.sessionResources):nH(y,w)});const E=new Map;try{const s=g.resources.wrapped;bH(g,t.customTools),void 0!==y&&BW(g.resources.base);const d=t.blobStore??new oe.ve;let f=t.initialState??new c.Y9z({});const m=void 0!==t.model?new QB.G4({modelId:t.model.id,...!0===t.model.maxMode?{maxMode:!0}:{},parameters:(t.model.params??[]).map((e=>new QB.SR({id:e.id,value:e.value})))}):void 0,b=!0===e.summarize?void 0:e.images,_=Array.isArray(b)?b.map((e=>{const t=(0,ye.C)(),r=new Uint8Array(n.Buffer.from(e.data,"base64")),o=(0,oH.v8)(r);return new YB.d({uuid:t,...o?{mimeType:o}:{},dataOrBlobId:{case:"data",value:r}})})):[],C=_.length>0?new YB.xv({selectedImages:_}):void 0,R=function(e){switch(e){case"agent":return c.xyI.AGENT;case"plan":return c.xyI.PLAN;default:return}}(t.mode),I=!0===e.summarize?new c.QFf({action:{case:"summarizeAction",value:new c.Scs}}):new c.QFf({action:{case:"userMessageAction",value:new c.Vtf({userMessage:new c.RGk({text:e.text,selectedContext:C,...void 0!==R?{mode:R}:{}})})}}),T={sendUpdate:async(e,t)=>{const r=cW(t,l);null!==r&&await o.sendUpdate(r)},query:async(e,r)=>await async function(e,t){if("mcpAuthRequestQuery"===e.query.case&&void 0!==t){const r=await async function(e,t,r){let n;try{n=await e({serverName:r.args?.serverIdentifier??"",toolCallId:r.args?.toolCallId??""})}catch{return Cr(t,"The MCP sign-in request failed.")}if(void 0!==n)switch(n.kind){case"approved":return _r(t);case"rejected":return Cr(t,n.reason);default:return n}}(t,e.id,e.query.value);if(void 0!==r)return r}return function(e){switch(e.query.case){case"webSearchRequestQuery":return hr(e.id);case"webFetchRequestQuery":return fr(e.id);case"switchModeRequestQuery":return wr(e.id);case"askQuestionInteractionQuery":return gr(e.id,new er.tz({result:{case:"rejected",value:new er.ox({reason:"Interactive questions are not supported in local SDK runs"})}}));case"createPlanRequestQuery":return vr(e.id,new tr.bK({result:{case:"success",value:new tr.Jo},planUri:""}));case"setupVmEnvironmentArgs":return br(e.id,new or.r$({result:{case:"success",value:new or.JH}}));case"replaceEnvArgs":return Sr(e.id,new nr.dV({result:{case:"failure",value:new nr.uq({errorMessage:"Environment replacement is not supported in local SDK runs",setupLogs:""})}}));case"prManagementRequestQuery":return kr(e.id,new rr.HL({result:{case:"error",value:new rr.K$({error:"PR management is only available in cloud agents"})}}));case"mcpAuthRequestQuery":return Cr(e.id,"MCP authentication is not supported in local SDK runs");case"connectScmRequestQuery":return Er(e.id,"Connecting GitHub is not supported in local SDK runs");case"generateImageRequestQuery":return xr(e.id,e.query.value.args?.description);case void 0:throw new LW.j1("Missing interaction query type",{isRetryable:!1});default:throw e.query,new LW.j1("Unhandled interaction query type",{isRetryable:!1})}}(e)}(r,t.onMcpAuthRequest)};if(L!==t.apiKey||!j){await Promise.all([(0,oH.ly)(t.apiKey),(0,oH.mU)(t.apiKey)]);const e=(0,oH.KU)(t.apiKey,r.teamId),n=So((0,be.createClient)(XB.N,e),{injectTraceHeaders:!0});j=new qn(n),L=t.apiKey}const A=(0,oH.Vh)(j,(()=>{const e=(0,oH.KU)(t.apiKey,r.teamId),n=So((0,be.createClient)(XB.N,e),{injectTraceHeaders:!0}),o=new qn(n);return j=o,L=t.apiKey,o})),$=function(e){return{...void 0!==e.allowedTools?{[yH.$$]:e.allowedTools.join(",")}:{},...void 0!==e.disallowedTools&&e.disallowedTools.length>0?{[yH.VJ]:e.disallowedTools.join(",")}:{}}}(t),M=new ZB({agentClient:A,rootRequestId:t.requestId,getResources:async({agentId:e})=>{let r=E.get(e);return r||(r=await O.createSessionRuntime({sessionId:e,mcpServersOverride:u,extraMcpTools:h,onMcpAdminToolLimitCheck:v?.record,onMcpAllowlistInUse:aH.report,onMcpServerBlockedByAllowlist:k.report,...void 0===y?kH(t.subagentInherit):nH(y,w)}),bH(r,t.customTools),void 0!==y&&BW(r.resources.base),r.resources.base.register(co,D),r.resources.base.register(lo,F),r.resources.base.register(uo,N),E.set(e,r)),r.resources.wrapped},mcpTools:h,workspacePath:p,parentConversationId:l,...(void 0!==t.subagentInherit||void 0!==y)&&Object.keys($).length>0?{headers:$}:{},onSessionReleased:e=>{const t=E.get(e);t&&(t.dispose(),E.delete(e))}}),D=function(e){const t=new Map,r=new Map;async function n(t,r,n){let o;try{o=await e.createOrResumeSession(t,r);const s=await e.runSession(t,o,r,{execId:n?.execId});return"error"===s.status?new io.vS({result:{case:"error",value:new io.od({agentId:o,error:s.error})}}):"aborted"===s.status?new io.vS({result:{case:"error",value:new io.od({agentId:o,error:s.error??"Subagent was aborted by the user"})}}):"background"===s.status?new io.vS({result:{case:"success",value:new io.HJ({agentId:o,finalMessage:s.finalMessage,toolCallCount:s.toolCallCount??0,backgroundReason:s.backgroundReason,transcriptPath:s.transcriptPath})}}):new io.vS({result:{case:"success",value:new io.HJ({agentId:o,finalMessage:s.finalMessage,toolCallCount:s.toolCallCount??0})}})}catch(t){if(o&&e.releaseSession&&e.releaseSession(o),t instanceof dr)throw t;const n=t instanceof Error?t.message:String(t),s=o??function(e){return e instanceof ao&&e.agentId||e&&"object"==typeof e&&"agentId"in e&&"string"==typeof e.agentId?e.agentId:void 0}(t)??r.resumeAgentId;return new io.vS({result:{case:"error",value:new io.od({...s?{agentId:s}:{},error:n})}})}}return{execute(e,o,s){const i=function(e){if(e.toolCallId&&e.parentConversationId)return[e.parentConversationId,e.toolCallId,e.resumeAgentId??"",e.forkAgentId??""].join("\0")}(o);if(void 0===i)return n(e,o,s);const a=r.get(i);if(void 0!==a)return Promise.resolve(a);const c=t.get(i);if(void 0!==c)return c;const l=n(e,o,s).then((e=>("success"===e.result.case&&(r.set(i,e),r.size>1e3&&r.delete(r.keys().next().value)),e))).finally((()=>{t.delete(i)}));return t.set(i,l),l}}}(M),F=(P=M,{execute:(e,t)=>P.awaitBackgroundRunBounded(e,t)}),N=function(e){return{execute:async(t,r)=>e.forceBackgroundByToolCallId(r.toolCallId)}}(M);g.resources.base.register(co,D),g.resources.base.register(lo,F),g.resources.base.register(uo,N);const U=O.services.hooksRuntime,B="object"==typeof(x=U)&&null!==x&&"workspacePath"in x&&"string"==typeof x.workspacePath&&"createSessionRuntime"in x&&"function"==typeof x.createSessionRuntime?U:void 0,W=void 0!==B&&void 0===y&&!0!==e.summarize?function(e){const{workspaceRuntime:t}=e;if(!(t.hooksConfigLease.hasHookForStep(Rd.sessionStart)||t.hooksConfigLease.hasHookForStep(Rd.sessionEnd)||t.hooksConfigLease.hasHookForStep(Rd.stop)||t.hooksConfigLease.hasHookForStep(Rd.beforeSubmitPrompt)))return{};const r=t.createSessionRuntime({sessionState:e.sessionState,metadata:e.metadata}),{hookExecutor:n}=r;let o;return{async onSessionStart(e){if(o=e,n.hasHooksForStep(Rd.sessionStart))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...mF(e),is_background_agent:!1},r=await n.executeHookForStep(Rd.sessionStart,t);if(r)return r.env&&n.setSessionEnvironment(r.env),{env:r.env,additionalContext:r.additional_context,blocked:!1===r.continue,blockedReason:r.user_message}}catch(e){CO.Jz.warn("[hooks-adapter] sessionStart hook failed:",e)}},async onSessionEnd(e,t){if(n.hasHooksForStep(Rd.sessionEnd))try{const r={conversation_id:o?.conversationId??"",generation_id:o?.generationId??"",model:o?.model??"unknown",...o?mF(o):{},reason:e,duration_ms:t,is_background_agent:!1,final_status:e};await n.executeHookForStep(Rd.sessionEnd,r)}catch(e){CO.Jz.warn("[hooks-adapter] sessionEnd hook failed:",e)}finally{n.clearSessionEnvironment()}else n.clearSessionEnvironment()},async onBeforeSubmitPrompt(e){if(n.hasHooksForStep(Rd.beforeSubmitPrompt))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...mF(e),prompt:e.promptText??"",attachments:[]};await n.executeHookForStep(Rd.beforeSubmitPrompt,t)}catch(e){CO.Jz.warn("[hooks-adapter] beforeSubmitPrompt hook failed:",e)}},async onTurnCompleted(e){if(!n.hasHooksForStep(Rd.stop))return;const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...mF(e),status:"completed",loop_count:e.loopCount},r=await n.executeHookForStep(Rd.stop,t),o="string"==typeof r?.followup_message?r.followup_message.trim():"";return o.length>0?o:void 0},async onTurnError(e){if(n.hasHooksForStep(Rd.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...mF(e),status:"error",loop_count:e.loopCount};await n.executeHookForStep(Rd.stop,t)}catch(e){CO.Jz.warn("[hooks-adapter] onTurnError stop hook failed:",e)}},async onTurnAborted(e){if(n.hasHooksForStep(Rd.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...mF(e),status:"aborted",loop_count:e.loopCount};await n.executeHookForStep(Rd.stop,t)}catch(e){CO.Jz.warn("[hooks-adapter] onTurnAborted stop hook failed:",e)}},async dispose(){await r.dispose()}}}({workspaceRuntime:B,sessionState:g.state,metadata:g.metadata}):void 0,H=new VB({workspacePath:p,conversationId:l,blobStore:d}),q=function(e,t,r){const{hooks:n}=r,[o,s]=e.withCancel(),i=new _O;let a;const l=new Map,u=(e,t)=>{const r=l.get(e);void 0!==r&&(l.delete(e),clearTimeout(r.ackTimer),r.resolve(t))};let d;const h=[],p=e=>{for(const t of h.splice(0))t.resolve(e)},f=()=>{if(0===h.length)return;const e=h.map((e=>e.text)).join("\n\n");return p("complete_delivered"),AO(e)},m=r.interactionListener,g={async sendUpdate(e,t){const r=t.message;if("contextInjectionState"===r?.case){const e=r.value,t="object"==typeof e&&null!==e&&"injectionId"in e&&"string"==typeof e.injectionId?e.injectionId:void 0,n=function(e){if("object"!=typeof e||null===e||!("state"in e))return;const t=e.state;if("object"!=typeof t||null===t||!("state"in t))return;const r=t.state;return"object"==typeof r&&null!==r&&"case"in r&&"string"==typeof r.case?r.case:void 0}(e),o=function(e){switch(e){case"queued":return"queued";case"delivered":return"delivered";case"queuedForNextTurn":return"queued_for_next_turn";case"cancelled":return"cancelled";default:return"rejected"}}(n),s=void 0===t?void 0:l.get(t);if(void 0!==s&&void 0!==t){const e=function(e){switch(e){case"queued":return"confirm_steering";case"delivered":return"complete_delivered";case"queued_for_next_turn":case"cancelled":case"rejected":return"revert_to_followup";default:throw new Error(`Unknown steer ack state: ${String(e)}`)}}(o);"confirm_steering"===e?clearTimeout(s.ackTimer):(l.delete(t),s.resolve(e))}}await m.sendUpdate(e,t)},query:(e,t)=>m.query(e,t),...void 0!==m.enqueuePostTurnEndedWork?{enqueuePostTurnEndedWork:e=>m.enqueuePostTurnEndedWork?.(e)}:{},...void 0!==m.flushPostTurnEndedWork?{flushPostTurnEndedWork:e=>m.flushPostTurnEndedWork?.(e)??Promise.resolve()}:{}};let w=r.initialState;const y={async handleCheckpoint(e,t){w=t,await(r.onCheckpoint?.(t))},getLatestCheckpoint:()=>w};let v="completed";const b=Date.now(),S=PO(function(e,t){if((0,EO.TU)(t))return t;const r=RO.get(e);if(void 0!==r)return r;const n=(0,EO.sh)(e).blobEncryptionKey;if(void 0===n)throw new Error("getDefaultAgentMetadata did not seed a blobEncryptionKey");return RO.set(e,n),n}(r.conversationId,r.blobEncryptionKey),r.runOptions?.headers);return{done:(async()=>{const e=TO(r,0,IO(t));try{const t=await(n?.onSessionStart?.(e));if(t?.blocked)throw v="error",new Error(t.blockedReason??"Session blocked by sessionStart hook")}catch(e){if("completed"!==v)throw e;CO.Jz.warn("[agent-session-runner] sessionStart hook failed:",e)}let s=t,c=0;for(;s;){const e=TO(r,c,IO(s));try{await(n?.onBeforeSubmitPrompt?.(e))}catch(e){CO.Jz.warn("[agent-session-runner] beforeSubmitPrompt hook failed:",e)}a=r.runOptions?.generationUUID??(0,ye.C)();try{await r.agentClient.run(o,w,s,void 0,g,r.resources,r.blobStore,i,y,r.mcpTools??[],{conversationId:r.conversationId,...r.runOptions,generationUUID:a,headers:S,subagentModelOverrides:r.runOptions?.subagentModelOverrides??[]})}catch(t){throw v=$O(t)?"aborted":"error",MO("aborted"===v?n?.onTurnAborted?.(e):n?.onTurnError?.(e)),t}finally{a=void 0;for(const e of[...l.keys()])u(e,"revert_to_followup")}let t;try{t=await(n?.onTurnCompleted?.(e))}catch(e){throw v="error",e}const h="string"==typeof t?t.trim():"";let m;if(h.length>0)m=AO(h);else{const t=new AbortController;d=t;try{m=await(r.nextAction?.(e,AbortSignal.any([o.signal,t.signal])))}catch(r){if(o.signal.aborted||!t.signal.aborted)throw v=o.signal.aborted||$O(r)?"aborted":"error",MO("aborted"===v?n?.onTurnAborted?.(e):n?.onTurnError?.(e)),r}finally{d=void 0}void 0===m?m=f():p("revert_to_followup")}void 0!==m?(c+=1,i.resetStream(),s=m):s=void 0}})().finally((async()=>{p("revert_to_followup");const e=Date.now()-b;try{await(n?.onSessionEnd?.(v,e))}catch(e){CO.Jz.warn("[agent-session-runner] sessionEnd hook failed:",e)}try{await(n?.dispose?.())}catch(e){CO.Jz.warn("[agent-session-runner] hooks dispose failed:",e)}})),abort(){s()},async steer(e){if(""===e.trim())return"revert_to_followup";const t=a;if(void 0===t){const t=d;if(void 0===t)return"revert_to_followup";const r=new Promise((t=>{h.push({text:e,resolve:t})}));return t.abort(),await r}const r=(0,ye.C)(),n=new Promise((e=>{const t=setTimeout((()=>{u(r,"revert_to_followup")}),15e3);t.unref?.(),l.set(r,{resolve:e,ackTimer:t})}));try{return await i.submitConversationAction(new c.QFf({action:{case:"injectContextAction",value:new c.hGJ({injectionId:r,expectedRunId:t,payload:{case:"userContext",value:new c.oW$({userMessage:new c.RGk({messageId:(0,ye.C)(),text:e})})}})}})),await n}catch(e){return u(r,"revert_to_followup"),CO.Jz.warn("[agent-session-runner] context injection failed:",e),"revert_to_followup"}}}}(i,I,{agentClient:A,interactionListener:T,resources:s,blobStore:d,initialState:f,conversationId:l,mcpTools:h,blobEncryptionKey:t.blobEncryptionKey,runOptions:{generationUUID:t.requestId,requestedModel:m,enableAgentRetries:!1!==r.enableAgentRetries,emitModelCallUsage:!0,...void 0!==t.onConnectionStateChange?{onConnectionStateChange:e=>{!function(e,t){if(void 0!==e)try{e(function(e){switch(e.state){case"connected":return{state:"connected"};case"reconnecting":{const t=e.trigger?.errorClass,r=e.trigger?.stallAborted,n={...void 0!==t?{errorClass:t}:{},...void 0!==r?{stallAborted:r}:{}};return{state:"reconnecting",attempt:e.attempt,...Object.keys(n).length>0?{trigger:n}:{}}}default:return e}}(t))}catch(e){hH.v.warn(`onConnectionStateChange failed: ${e instanceof Error?e.message:String(e)}`)}}(t.onConnectionStateChange,e)}}:{},...Object.keys($).length>0?{headers:$}:{},...void 0!==t.systemPrompt?{customSystemPrompt:t.systemPrompt}:{}},hooks:W,async nextAction(e,t){const r=await M.waitForBackgroundCompletions(l,t);return r.length>0?function(e){return new c.QFf({action:{case:"backgroundTaskCompletionAction",value:new c.Kwc({completions:e.map((e=>new c.KFq({taskId:e.agentId,kind:c.aZc.SUBAGENT,status:"success"===e.status?c.uHL.SUCCESS:"aborted"===e.status?c.uHL.ABORTED:c.uHL.ERROR,...e.finalMessage.length>0?{detail:e.finalMessage}:{}})))})}})}(r):void 0},async onCheckpoint(e){f=e,H.writeFromState(i,e),await(t.onCheckpoint?.(e))}}),z=q.done.finally((async()=>{try{await M.awaitBackgroundWorkers()}finally{await H.waitForPendingWrites().catch((()=>{}));for(const e of E.values())try{await e.dispose()}catch(e){hH.v.log(`Failed to dispose subagent session runtime: ${e instanceof Error?e.message:String(e)}`)}E.clear();try{await g.dispose()}finally{S()}}})).catch((e=>{throw e}));return{abort(){q.abort(),a()},done:z,steer:e=>q.steer(e)}}catch(e){for(const e of E.values())try{await e.dispose()}catch{}E.clear();try{await g.dispose()}finally{S()}throw e}var x,P})),async reload(){await O.reload()},async dispose(){await O.dispose()}}}},"./src/agent/native/tree-sitter-bash.webpack.cjs"(e,t,r){const{loadVendoredTreeSitterModule:n}=r("./src/agent/native/vendored-tree-sitter.ts"),o=n({packageName:"tree-sitter-bash",nativeRequire:require});e.exports=o.available?o.module:{}},"./src/agent/native/tree-sitter.webpack.cjs"(e,t,r){const{createUnavailableParserClass:n,loadVendoredTreeSitterModule:o}=r("./src/agent/native/vendored-tree-sitter.ts"),s=o({packageName:"tree-sitter",nativeRequire:require});e.exports=s.available?s.module:n(s.reason)},"../constants/dist/commercial-cursor-hosts.js"(e,t,r){"use strict";r.d(t,{H:()=>c,K4:()=>i,Zf:()=>a,ad:()=>l});const n=["cursor.sh","cursor.com","cursorapi.com","cursor.so","cursor-marketplace.com","cursorusercontent.com","anysphere.co"],o=["cursor.blob.core.windows.net"];function s(e){return e.trim().toLowerCase().replace(/\.+$/,"")}const i="CURSOR_ORBIT_BUILD",a="CURSOR_ORBIT_DEPLOYMENT_HOSTS";function c(e){return new Set((e??"").split(",").map(s).filter((e=>""!==e)))}function l(e,t){return function(e){const t=s(e);return o.includes(t)||n.some((e=>t===e||t.endsWith(`.${e}`)))}(e)&&!t.has(s(e))}},"../context/dist/otel.js"(e,t,r){"use strict";r.d(t,{F:()=>E,HF:()=>_,MG:()=>k,Mf:()=>v,OA:()=>y,V5:()=>C,VI:()=>P,fR:()=>g,fU:()=>w,mJ:()=>b,r2:()=>x,xd:()=>R});var n=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js"),o=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/context-api.js"),s=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace-api.js"),i=r("../context/dist/core.js");const a=(0,i.cF)(Symbol("otel.span"),void 0),c=(0,i.cF)(Symbol("otel.root_span"),void 0),l=(0,i.cF)(Symbol("otel.root_start_ms"),void 0),u=(0,i.cF)(Symbol("otel.suppress_child_spans"),!1),d=(0,i.cF)(Symbol("otel.inheritable_span_attributes"),{});function h(e,t){const r=t.get(d);for(const t in r){const n=r[t];"string"!=typeof n&&"number"!=typeof n&&"boolean"!=typeof n||e.setAttribute(t,n)}}function p(e){return e.name||"anonymous-context"}function f(e,t){return!!t&&(e.get(u)||(p(e),!1))}function m(e="context-tracer"){return s.u.getTracer(e)}function g(e,t){const r=m(),n=e.get(a);if(f(e,n))return e;const i=p(e);let u;if(n){const e=s.u.setSpan(o._.active(),n);u=r.startSpan(i,t,e)}else u=r.startSpan(i,t);h(u,e);const d=Date.now();let g=e.with(a,u);return n||(g=g.with(c,u).with(l,d)),g}function w(e){return e.get(a)}function y(e){return e.with(u,!0)}function v(e,t,r){const n=e.get(d),o=w(e);return o&&null!==r&&o.setAttribute(t,r),e.with(d,{...n,[t]:r})}function b(e){try{const t=w(e);if(!t)return;const r=t.spanContext(),n=e.get(u);return{traceId:r.traceId,spanId:r.spanId,traceFlags:n?0:r.traceFlags,traceState:r.traceState?.serialize()}}catch{return}}const S=Symbol.for("anysphere.context.activeOtelSpanAls");function k(e,t){const r=()=>o._.with(s.u.setSpan(o._.active(),e),t),n=function(){const e=globalThis;if("object"!=typeof(t=e)||null===t||!(S in e))return;var t;const r=e[S];return function(e){return"object"==typeof e&&null!==e&&"run"in e&&"function"==typeof e.run&&"getStore"in e&&"function"==typeof e.getStore}(r)?r:void 0}();return void 0===n?r():n.run(e,r)}function _(e,t){try{const r=m(),n=w(e);if(!n)return;const i=s.u.setSpan(o._.active(),n),a=r.startSpan(t,void 0,i);h(a,e);const u=Date.now(),d=e.get(l),p="number"==typeof d?u-d:0,f=`event.${t}`;(e.get(c)??n).setAttribute(f,p),a.setAttribute(f,p),a.end()}catch{}}function C(e,t,r){const c=m(),l={traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags,isRemote:!0},u=s.u.setSpanContext(o._.active(),l),d=t||"child.span",h=c.startSpan(d,{kind:n.v.INTERNAL},u),p=r??(0,i.q6)();return(t?p.withName(t):p).with(a,h)}function E(e,t,r){const n=s.u.wrapSpanContext({traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags,isRemote:!0}),o=r??(0,i.q6)();return(t?o.withName(t):o).with(a,n)}class x{constructor(e,t,r=!0){this.disposed=!1,this.ctx=e,this.span=t,this.shouldEnd=r}[Symbol.dispose](){this.disposed||(this.disposed=!0,this.shouldEnd&&this.span.end())}}function P(e,t){const r=f(e,w(e)),n=g(e,t),o=w(n);return new x(n,o,!r)}function R(e,t,r){const n=w(e);if(!n||f(e,n))return;const o=w(g(e,t));return o.end(r),o}},"../mcp-core/dist/transport/mcp-url-utils.js"(e,t,r){"use strict";r.d(t,{$H:()=>Q,ME:()=>G,_N:()=>X,b6:()=>z,bi:()=>P,eA:()=>j,mD:()=>A,rM:()=>J,vc:()=>L});const n=BigInt(0),o=BigInt(8),s=BigInt(16),i=BigInt(65535);function a(e){const t=e.split(".");if(4!==t.length)return;let r=n;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<>s&i)),t.push(Number(o.value&i))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function l(e){return a(e)??function(e){const t=H(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=c(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<7?void 0:{version:6,value:[...a,...new Array(8-u).fill(0),...l].reduce(((e,t)=>e<=R&&d.clear();const t=l(e);return d.set(e,t),t}(e);return void 0!==r&&r.version===t.version&&r.value>>t.shift===t.shiftedNetwork}case"subdomainOrBase":return e===t.suffix||e.endsWith(`.${t.suffix}`);case"exact":return e===t.value;default:return t}}(H(e),function(e){const t=u.get(e);if(t)return t;u.size>=R&&u.clear();const r=function(e){const t=H(e);if("*"===t)return{kind:"matchAll"};if(t.includes("/")){const e=t.lastIndexOf("/");if(e<=0||e===t.length-1)return{kind:"invalidCidr"};const r=l(t.slice(0,e));if(!r)return{kind:"invalidCidr"};const n=Number(t.slice(e+1)),o=4===r.version?32:128;if(!Number.isInteger(n)||n<0||n>o)return{kind:"invalidCidr"};const s=BigInt(o-n);return{kind:"cidr",version:r.version,shift:s,shiftedNetwork:r.value>>s}}return t.startsWith("*.")?{kind:"subdomainOrBase",suffix:t.slice(2)}:{kind:"exact",value:t}}(e);return u.set(e,r),r}(t))}new Set(["airtable.com","anysphere.co","api.aws","apify.com","asana.com","ashbyhq.com","atlassian.com","atlassian.net","azuredatabricks.net","box.com","buildkite.com","calendly.com","canva.com","clickhouse.cloud","clickup.com","cloudflare.com","composio.dev","context7.com","cursor.com","cursor.sh","cursorapi.com","databricks.com","datadoghq.com","datadoghq.eu","ddog-gov.com","dropbox.com","elevenlabs.io","exa.ai","figma.com","firecrawl.dev","github.com","githubcopilot.com","gitlab.com","google.com","googleapis.com","granola.ai","hex.tech","hubspot.com","huggingface.co","intercom.com","linear.app","monday.com","neon.tech","notion.com","plain.com","posthog.com","prisma.io","railway.com","ramp.com","render.com","salesforce.com","sentry.dev","sentry.io","slack.com","snowflakecomputing.com","spacelift.io","statsig.com","stripe.com","supabase.com","todoist.net","vercel.com","workos.com","x.ai","x.com","zapier.com"]);const p="Blocked by MCP Network Admin Server Controls";function f(e){return/\s/.test(e)}const m="[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?",g=new RegExp(`^(?:${m}\\.)*${m}$`),w=new RegExp(`^\\*\\.(?:${m}\\.)*${m}$`),y="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)",v=new RegExp(`^${y}(?:\\.${y}){3}$`),b=/^[0-9a-f:]+$/,S=new RegExp(`^(?:${y}(?:\\.${y}){3}|[0-9a-f:]+)\\/\\d{1,3}$`);function k(e){const t=H(e);return t.length>0&&t.length<=253&&g.test(t)}function _(e){const t=H(e);return v.test(t)||function(e){const t=H(e);if(!b.test(t))return!1;try{return new URL(`https://[${t}]`),!0}catch{return!1}}(t)}function C(e,t){return""===t||"http:"===e&&"80"===t||"https:"===e&&"443"===t}function E(e){const t=new URL(e.pathname||"/",e.origin);if(t.search=e.search,t.pathname.endsWith("/")&&t.pathname.length>1&&(t.pathname=t.pathname.slice(0,-1)),"/"===t.pathname&&""===t.search){const t=e.protocol.toLowerCase();let r=`${t}//${e.hostname.toLowerCase()}`;return C(t,e.port)||(r+=`:${e.port}`),r}const r=e.protocol.toLowerCase();let n=`${r}//${e.hostname.toLowerCase()}`;return C(r,e.port)||(n+=`:${e.port}`),`${n}${t.pathname}${t.search}`}function x(e){if(e.includes("://"))return function(e){try{const t=new URL(e);return("http:"===t.protocol||"https:"===t.protocol)&&!(0===t.hostname.length||t.username.length>0||t.password.length>0)&&""===t.hash&&function(e){const t=e.toLowerCase();return!t.includes("*")&&(k(t)||_(t))}(t.hostname)}catch{return!1}}(e);const t=H(e);return"*"===t||!!w.test(t)||(t.includes("/")?function(e){const t=H(e);if(!S.test(t))return!1;const[r]=t.split("/");return void 0!==r&&h(r,t)}(t):k(t)||_(t))}function P(e){if(I.has(e))return I.get(e);I.size>=R&&I.clear();const t=function(e){const t=e.trim();if(0===t.length)return;const r=t.lastIndexOf("/");if(!t.includes("://")&&r>0&&/^\d+$/.test(t.slice(r+1).trim())){const e=`${H(t.slice(0,r))}/${t.slice(r+1).trim()}`;return x(e)?e:void 0}if(f(t)||t.includes("#")||t.includes("@"))return;const n=t.indexOf("://");if(-1!==n){const e=t.slice(0,n).toLowerCase();if("http"!==e&&"https"!==e)return;try{const e=new URL(t);if(0===e.hostname.length||e.username.length>0||e.password.length>0)return;const r="/"!==e.pathname&&""!==e.pathname,n=""!==e.search;if(e.hostname.includes("*"))return;if(r||n){const t=E(e);if(!x(t))return;return t}{const t=E(e);if(!x(t))return;return t}}catch{return}}else if(t.includes("/"))return;const o=t.trim().toLowerCase(),s=function(e){const t=e.indexOf(":");if(-1===t)return e;const r=e.slice(t+1);return/^\d+$/.test(r)?e.slice(0,t):e}(o);return 0===s.length||!x(s)||s!==o&&"*"===s?void 0:s}(e);return I.set(e,t),t}const R=2048,I=new Map,T=new Map;function A(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}function $(e){return e.endsWith("/")&&e.length>1?e.slice(0,-1):e}function M(e,t){return function(e,t,r){const n=D(t);if(!n)return!1;let o;try{o=new URL(e)}catch{return!1}return""===o.username&&""===o.password&&""===n.username&&""===n.password&&o.protocol===n.protocol&&o.port===n.port&&(s=o.hostname,i=n.hostname,!s.includes("*")&&H(s)===H(i)&&(A(a=o.pathname,c=n.pathname)||A($(a),$(c)))&&function(e,t,r){return""===e?r.allowRequestQueryWhenPatternOmitsQuery||""===t:A(e,t)}(o.search,n.search,r));var s,i,a,c}(e,t,{allowRequestQueryWhenPatternOmitsQuery:!0})}function D(e){const t=e.trim();if(0===t.length||f(t))return;if(function(e){const t=e.indexOf("[");return-1!==t&&-1===e.indexOf("]",t)}(t))return;const r=q(t);if(r&&("http:"===r.protocol||"https:"===r.protocol)&&""===r.username&&""===r.password&&0!==r.hostname.length&&(!H(r.hostname).includes(":")||t.includes("["))){if(t.includes("[")){const e=t.indexOf("["),n=t.indexOf("]",e);if(-1===n)return;const o=t.slice(e+1,n);if(H(r.hostname)!==H(o))return}return r}}function O(e,t){const r=e.toLowerCase(),n=t.toLowerCase();if("*"===r)return!0;if(void 0!==a(n))return A(r,n);if(!r.includes("*"))return r===n;const o=r.slice(1);if(r.startsWith("*.")&&!o.includes("*"))return n.endsWith(o)&&n.length>o.length;const s=r.split("."),i=n.split(".");return s.length===i.length&&!s[s.length-1]?.includes("*")&&A(r,n)}const F=/^([^/?#]+\/\/[^/?#]*):\*(?=[/?#]|$)/,N=/^[^/?#]+\/\/[^/?#]*\*$/;function L(e,t){if("*"===e||e===t)return!0;let r;T.has(t)?r=T.get(t):(T.size>=R&&T.clear(),r=q(t),T.set(t,r));const n=function(e){if(void 0===e||!/[^.]\.$/.test(e.hostname))return;const t=new URL(e.href);return t.hostname=e.hostname.slice(0,-1),t.href}(r);if(void 0!==n&&L(e,n))return!0;const o=function(e){const t=e.trim(),r=t.indexOf("://");if(-1===r)return/^[^/?#]*[^.*/?#]\.$/.test(t)?t.slice(0,-1):void 0;if(!t.includes("*"))return;const n=r+3,o=n+(t.slice(n).split(/[/?#]/,1)[0]??"").replace(/:(?:\d+|\*)$/,"").length;return/[^.*]\.$/.test(t.slice(n,o))?`${t.slice(0,o-1)}${t.slice(o)}`:void 0}(e);return!(void 0===o||!L(o,t))||!!r&&(e.includes("://")?function(e,t){const r=N.test(e),n=r||F.test(e),o=e.indexOf("://"),s=e.slice(0,o).toLowerCase(),i=t.protocol.slice(0,-1),a=q((s.includes("*")&&A(s,i)?`${i}${e.slice(o)}`:e).replace(F,"$1"));if(void 0===a||""!==a.username||""!==a.password||""!==t.username||""!==t.password||a.protocol!==t.protocol||!n&&a.port!==t.port)return!1;const c=a.hostname.replace(/%2a/gi,"*");return(O(c,t.hostname)||r&&O(c.replace(/\*$/,""),t.hostname))&&(r||A(`${a.pathname}${a.search}`,`${t.pathname}${t.search}`))}(e,r):h(r.hostname,e))}function j(e,t){if(A(e,t)||L(e,t))return!0;const r=function(e){const t=e.trim();if(t.includes("*")||!t.includes("://"))return;const r=q(t);return void 0!==r&&""===r.search&&""===r.hash?W(r):void 0}(e);if(void 0===r)return!1;const n=q(t.trim());return void 0!==n&&W(n)===r}const U=/%[0-9a-f]{2}/gi,B=/^[A-Za-z0-9\-._~]$/;function W(e){const t="http:"===e.protocol||"https:"===e.protocol?"http(s):":e.protocol,r=e.hostname.endsWith(".")?e.hostname.slice(0,-1):e.hostname,n=""===e.port?"":`:${e.port}`,o=e.pathname.replace(U,(e=>{const t=String.fromCharCode(Number.parseInt(e.slice(1),16));return B.test(t)?t:e.toUpperCase()})).replace(/\/{2,}/g,"/");return`${t}//${r}${n}${o.endsWith("/")?o.slice(0,-1):o}`}function H(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function q(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch{return}}function z(e){return(e.mcpNetworkAllowlist??[]).flatMap((e=>{const t=P(e);return void 0===t?[]:[t]}))}function G(e,t){if(!0!==t.enabled)return{allowed:!0};if("no_sandbox"===t.mcpNetworkMode)return{allowed:!0};if(!D(e))return{allowed:!1,message:t.blockMessage??p};const r=z(t);return r.length>0&&r.some((t=>function(e,t){const r=D(t);if(!r)return!1;if(!e.includes("://"))return h(H(r.hostname),e);if(M(e,t))return!0;const n=function(e){try{const t=new URL(e);if(""!==t.username||""!==t.password||"/"!==t.pathname||""!==t.search||""!==t.hash)return;return`${t.protocol}//${t.host}/*`}catch{return}}(e);return void 0!==n&&M(n,t)}(t,e)))?{allowed:!0}:{allowed:!1,message:t.blockMessage??p}}function V(e){const t=e?.trim();return t&&t.length>0?t:void 0}function K(e){return V(e)?.toLowerCase()}function J(e,t){const r=K(e.builtinServer),n=K(t.builtinServer);if(void 0!==r||void 0!==n)return void 0!==r&&r===n;const o=V(e.command),s=V(e.serverUrl);if(void 0===o&&void 0===s)return!1;const i=void 0===o||void 0!==t.command&&A(o,t.command),a=void 0===s||void 0!==t.url&&L(s,t.url);return i&&a}function Z(e,t,r){return void 0!==r?.command&&void 0===r.url&&void 0===t&&!0===e?.allowUserOverrideMcpServers}function X({allowedMcpConfiguration:e,server:t,localAgentNetworkAllowlist:r,blockMessage:n,unmatchedServerAllowlist:o,aggregateManagedServerNetworkAllowlists:s=!0,stdioPlatform:i,unsandboxUserExtensionStdio:a}){const c=e?.allowedMcpServers,l=function(e){if(!0!==e?.allowUserOverrideMcpServers)return;const t=(e.deniedMcpServers??[]).flatMap((e=>{const t=V(e.serverUrl),r=void 0===t?void 0:function(e){const t=e.trim();if(0===t.length)return;if(function(e){const t=e.indexOf("://");if(-1===t)return!1;const r=e.slice(t+3),n=r.indexOf("/");return-1===n?r.includes("?"):r.slice(n).includes("*")}(t)){const e=t.indexOf("://");if(-1!==e){const r=t.slice(e+3).split(/[/?#]/,1)[0];if(r?.includes("*")){const e=P(r.replace(/:\d+$/,""));if(void 0!==e)return e}}return}if(!t.includes("://")&&t.includes("*")&&"*"!==t&&!t.startsWith("*."))return;const r=P(e);if(void 0!==r)return r;const n=e.indexOf("://");if(-1===n)return;const o=e.slice(0,n).toLowerCase();if("http"!==o&&"https"!==o)return;const s=e.slice(n+3).split(/[/?#]/,1)[0];if(void 0===s||s.includes("@"))return;const i=P(s.replace(/:\d+$/,""));if(void 0!==i)return i;try{return P(new URL(e).hostname)}catch{return}}(t);return void 0===r?[]:[r]}));return t.length>0?t:void 0}(e),u=void 0===t?void 0:function(e,t){return e?.find((e=>J(e,t)))}(c,t),d=Z(e,u,t),h=function({allowedMcpConfiguration:e,matchedServer:t,server:r}){return void 0===r?(e?.allowedMcpServers?.length??0)>0:void 0!==t||Z(e,t,r)}({allowedMcpConfiguration:e,matchedServer:u,server:t})||void 0===t&&void 0!==l,p=void 0===t?s?c?.flatMap((e=>e.networkAllowlist??[])):void 0:d?[]:function(e,t,r){return void 0===e?r:[...e.networkAllowlist??[],...void 0!==V(e.serverUrl)&&void 0!==t.url?[t.url]:[]]}(u,t,o),f=d&&"win32"===i&&!0===a;let m;m=void 0===t?void 0:f?"no_sandbox":d?"allow_all":function(e,t){var r;if(void 0!==V(e?.command)&&void 0!==t.command&&void 0===t.url)return r=e?.networkMode,("allow_all"===r||"allowlist"===r||"deny_all"===r||"no_sandbox"===r?r:void 0)??"no_sandbox"}(u,t);const g=void 0===t||d?l:void 0;return{enabled:h,mcpNetworkAllowlist:p,...void 0!==m?{mcpNetworkMode:m}:{},...void 0!==g?{mcpNetworkDenylist:g}:{},...void 0!==r?{localAgentNetworkAllowlist:r}:{},...void 0!==n?{blockMessage:n}:{},...f?{win32UserExtensionUnsandbox:!0}:{}}}function Q(e){if(!0===e?.enabled&&"no_sandbox"!==e.mcpNetworkMode)return e}},"../shell-exec/dist/api/index.js"(e,t,r){"use strict";r.d(t,{BM:()=>Oo,Ls:()=>f,SandboxUnsupportedError:()=>_r,J:()=>x,St:()=>Er,Fn:()=>Do,Qw:()=>a,ue:()=>s,r5:()=>Ie,getLastSandboxFailureReason:()=>kr,oG:()=>no,Ko:()=>T,CG:()=>ht,W1:()=>Z,G6:()=>Mo,dA:()=>He,_B:()=>Qe,OK:()=>Ze,$b:()=>Xe,K3:()=>Rr,tv:()=>st,wG:()=>vt,fZ:()=>bt,s9:()=>mt,XX:()=>yt,T6:()=>et,Po:()=>Ye,$6:()=>nt,l7:()=>it,xS:()=>E,resolveSandboxPolicyForWorkspace:()=>Ct,fB:()=>Dt,spawnInSandbox:()=>xr,Xw:()=>I});var n=r("node:child_process");new Set;const o=["SSH_CLIENT","SSH2_CLIENT"];function s(e){const t=e||process.env,{ELECTRON_RUN_AS_NODE:r,...n}=t;for(const e of Object.keys(n))e.startsWith("AGENT_HOST_DAEMON_")&&delete n[e];for(const e of o)delete n[e];return n}const i="NODE_COMPILE_CACHE";function a(e){const{[i]:t,...r}=e;return r.NODE_DISABLE_COMPILE_CACHE="1",r}const c=["SSH_AUTH_SOCK","DBUS_SESSION_BUS_ADDRESS","XDG_RUNTIME_DIR","WAYLAND_DISPLAY"];function l(e){const t={...e};for(const e of c)delete t[e];return t}const u=[["core.quotePath","false"]];function d(e){const t=function(e){const t=e.GIT_CONFIG_COUNT;if(void 0===t||""===t)return 0;const r=Number.parseInt(t,10);return Number.isFinite(r)&&r>=0?r:0}(e),r=new Set;for(let n=0;no.endsWith(e)))){const n=S(e,r);if(g.existsSync(n))return k(n,t,r)}for(const o of n){const n=S(`${e}${o}`,r);if(g.existsSync(n))return k(n,t,r)}}return e.match(/\.ps1$/i)?{cmd:m.join(process.env.SYSTEMROOT,"System32","WindowsPowerShell","v1.0","PowerShell.exe"),args:["-ExecutionPolicy","Unrestricted","-NoLogo","-NonInteractive","-File",e].concat(t)}:e.match(/\.(bat|cmd)$/i)?{cmd:m.join(process.env.SYSTEMROOT,"System32","cmd.exe"),args:["/C",e,...t]}:e.match(/\.(js)$/i)?{cmd:process.execPath,args:[e].concat(t)}:{cmd:e,args:t}}let _;const C=["/usr/local/bin","/usr/bin","/bin"];function E(){const e=k("rg",[]).cmd;return"rg"!==e?e:void 0}function x(e){if(!e)throw new Error("configureRipgrepPath: path must not be empty");_=e}function P(e){const t=Object.keys(e).filter((e=>"path"===e.toLowerCase()));if(0!==t.length)return"win32"===process.platform?t.find((e=>"Path"===e))??t[0]:t.find((e=>"PATH"===e))??t[0]}function R(e,t){const r=(0,m.dirname)(t);if(!r||"."===r)return e;let n=function(e){const t=P(e);return void 0!==t?e[t]??"":""}(e).split(m.delimiter).filter(Boolean);return 0===n.length&&"win32"!==process.platform&&(n=C),function(e,t){const r=P(e)??("win32"===process.platform?"Path":"PATH"),n={...e};for(const e of Object.keys(n))e!==r&&"path"===e.toLowerCase()&&delete n[e];return n[r]=t,n}(e,[r,...n.filter((e=>e!==r))].join(m.delimiter))}function I(e){return _&&(0,m.isAbsolute)(_)?{...R(e,_),CURSOR_RIPGREP_PATH:_}:e}function T(){if(!_)throw new Error("Ripgrep path not configured. Call configureRipgrepPath() at startup.");return _}const A="win32"===process.platform;function $(e){return!A&&!!e?.SUDO_ASKPASS}function M(e){return $(e)?"alias sudo='sudo -A'; ":""}function D(e){const t=[];let r=0;for(;r=e.length||/\s/.test(e[n])){let o=n;for(;ovoid 0!==t&&e.toUpperCase()===r))}const F=["PYTHONIOENCODING","PYTHONUTF8","PYTHONLEGACYWINDOWSSTDIO"];function N(e){F.some((t=>O(e,t)))||(e.PYTHONIOENCODING="utf-8:surrogateescape")}function L(e){O(e,"WSL_UTF8")||(e.WSL_UTF8="1")}const j="-Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8 -Dstdout.encoding=UTF-8 -Dstderr.encoding=UTF-8",U=["sun.stdout.encoding","sun.stderr.encoding","stdout.encoding","stderr.encoding"],B=`case " \${MAVEN_OPTS-} \${JAVA_TOOL_OPTIONS-} \${JDK_JAVA_OPTIONS-} \${_JAVA_OPTIONS-} " in ${U.map((e=>`*[[:space:]]-D${e}=*`)).join("|")}) ;; *) builtin export MAVEN_OPTS="\${MAVEN_OPTS:+$MAVEN_OPTS }${j}";; esac; `,W=`if ("$env:MAVEN_OPTS $env:JAVA_TOOL_OPTIONS $env:JDK_JAVA_OPTIONS \${env:_JAVA_OPTIONS}" -cnotmatch '(^|\\s)-D(${U.map((e=>e.replace(/\./g,"\\."))).join("|")})=') {\n if ($env:MAVEN_OPTS) { $env:MAVEN_OPTS = "$env:MAVEN_OPTS ${j}" } else { $env:MAVEN_OPTS = '${j}' }\n}`;var H=r("node:crypto"),q=r("node:os"),z=r("../utils/dist/workspace-paths.js"),G=r("../utils/dist/test-resets.js");let V;function K(e,t){const r=(0,g.lstatSync)(e);return r.isDirectory()&&r.uid===t&&!(18&r.mode)}function J(e){try{(0,g.mkdirSync)(e,{mode:448})}catch(e){if(!(e instanceof Error&&"code"in e&&"EEXIST"===e.code))throw e}}function Z(e){return X(e,{create:!1})}function X(e,{create:t}){const r=process.getuid?.();if(void 0===r)return;const n=(0,m.join)((0,q.tmpdir)(),`cursor-sandbox-${(0,z.r_)((0,m.resolve)(e))}`);try{for(const e of[n,(0,m.join)(n,"tmp")])if(t&&J(e),!K(e,r))return;return n}catch{return}}(0,G.J)((function(){V=void 0}));const Q='builtin eval "${__CURSOR_SANDBOX_TEMP_RESTORE:-}" 2>/dev/null; ',Y=["TMPDIR","TMP","TEMP","TMPPREFIX","NODE_COMPILE_CACHE","NODE_DISABLE_COMPILE_CACHE"],ee="builtin export NODE_DISABLE_COMPILE_CACHE=1; builtin unset NODE_COMPILE_CACHE; ";function te(e){const t=(0,m.join)(e,"tmp");return{TMPDIR:t,TMP:t,TEMP:t,TMPPREFIX:(0,m.join)(t,"sh-")}}function re(e=(0,m.join)((0,q.tmpdir)(),"cursor-sandbox-cache",function(){return V||(V=(0,H.randomBytes)(16).toString("hex")),V}())){return{NPM_CONFIG_CACHE:(0,m.join)(e,"npm"),PNPM_STORE_PATH:(0,m.join)(e,"pnpm-store"),GOCACHE:(0,m.join)(e,"go-build"),GOMODCACHE:(0,m.join)(e,"go-mod"),CARGO_TARGET_DIR:(0,m.join)(e,"cargo-target"),PIP_CACHE_DIR:(0,m.join)(e,"pip"),UV_CACHE_DIR:(0,m.join)(e,"uv"),BUN_INSTALL_CACHE_DIR:(0,m.join)(e,"bun"),YARN_CACHE_FOLDER:(0,m.join)(e,"yarn"),npm_config_devdir:(0,m.join)(e,"node-gyp"),PLAYWRIGHT_BROWSERS_PATH:(0,m.join)(e,"playwright"),PUPPETEER_CACHE_DIR:(0,m.join)(e,"puppeteer"),TURBO_CACHE_DIR:(0,m.join)(e,"turbo"),GRADLE_USER_HOME:(0,m.join)(e,"gradle"),CONDA_PKGS_DIRS:(0,m.join)(e,"conda"),POETRY_CACHE_DIR:(0,m.join)(e,"poetry"),GEM_SPEC_CACHE:(0,m.join)(e,"gem-specs"),COMPOSER_HOME:(0,m.join)(e,"composer"),HOMEBREW_CACHE:(0,m.join)(e,"homebrew"),CYPRESS_CACHE_FOLDER:(0,m.join)(e,"cypress"),NX_CACHE_DIRECTORY:(0,m.join)(e,"nx"),NUGET_PACKAGES:(0,m.join)(e,"nuget"),CCACHE_DIR:(0,m.join)(e,"ccache"),CP_HOME_DIR:(0,m.join)(e,"cocoapods")}}var ne=r("node:fs/promises"),oe=r("../utils/dist/safe-spawn-cwd.js"),se=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js");function ie(){const e=process.env.CURSOR_SANDBOX_POLICY_DIR?.trim();return e?m.resolve(e):m.resolve(m.join(q.homedir(),".cursor","sandbox-policies"))}let ae=0;function ce(){const e=ie();g.mkdirSync(e,{recursive:!0,mode:448});try{g.chmodSync(e,448)}catch{}const t=Date.now();return t-ae>=9e5&&(ae=t,function(e){let t;try{t=g.readdirSync(e)}catch{return}const r=Date.now();for(const n of t){if(!n.startsWith("sandbox-policy-"))continue;const t=m.join(e,n);try{const e=g.statSync(t);if(!e.isFile())continue;r-e.mtimeMs>36e5&&g.unlinkSync(t)}catch{}}}(e)),e}function le(e){const t=ce(),r=H.randomBytes(8).toString("hex"),n=m.join(t,`sandbox-policy-${r}`);return g.writeFileSync(n,e,{encoding:"utf-8",mode:384}),n}const ue="/tmp/node-compile-cache",de="cursor-compile-cache",he=Symbol.for("cursor.startupNodeCompileCache"),pe=process.platform;function fe(e=q.tmpdir(),t=process.platform){if("win32"===t||0===e.length)return[];const r=m.posix.join(e,"node-compile-cache");return r===ue?[]:[r]}function me(e=q.tmpdir(),t=process.env,r=process.platform){if("win32"===r)return[];const n=new Set(fe(e,r));for(const e of["TMPDIR","TMP","TEMP"]){const o=t[e];if(void 0!==o&&m.posix.isAbsolute(o))for(const e of fe(m.posix.resolve(o),r))n.add(e)}return[...n]}function ge(e=process.env,t=q.homedir(),r=process.platform){if("darwin"===r)return t.length>0?m.posix.join(t,"Library/Caches",de):void 0;if("linux"!==r)return;const n=e.XDG_CACHE_HOME;return void 0!==n&&m.posix.isAbsolute(n)?m.posix.join(n,de):t.length>0?m.posix.join(t,".cache",de):void 0}function we(e=process.env,t=process.platform){if("win32"===t)return;const r=Object.getOwnPropertyDescriptor(globalThis,he)?.value,n="string"==typeof r?r:e.NODE_COMPILE_CACHE;if(void 0===n||!m.posix.isAbsolute(n))return;const o=m.posix.resolve(n);return"/"===o?void 0:o}function ye(e=q.homedir(),t=q.tmpdir(),r=process.env,n=process.platform){if("win32"===n)return[];const o=new Set([ue]);e.length>0&&(o.add(m.posix.join(e,".cache",de)),o.add(m.posix.join(e,"Library/Caches",de)));const s=[];for(const i of[...me(t,r,n),ge(r,e,n),we(r,n)])void 0===i||o.has(i)||(o.add(i),s.push(i));return s}function ve(e=q.homedir(),t=q.tmpdir(),r=process.platform,n=process.env){if("win32"===r)return[];const o=[ue,...me(t,n,r)],s=ge(n,e,r);return void 0===s||o.includes(s)||o.push(s),o}function be(e,t){return e.isSymbolicLink()?"a link, not followed":e.isDirectory()?e.uid!==t?`owned by uid ${e.uid}`:void 0:"not a folder"}function Se(e){return"object"!=typeof e||null===e?{}:Object.fromEntries(Object.entries(e).filter((e=>"string"==typeof e[1])))}function ke(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:"error"}const _e=[".local/bin",".local/share/mise",".local/share/pnpm",".nvm",".volta",".asdf",".pyenv",".rbenv",".rustup",".cargo/bin",".cargo/registry",".cargo/git"],Ce=["bin","sbin","lib","opt","Cellar","share","Frameworks","etc/gitconfig","etc/openssl@3/cert.pem","etc/openssl@3/openssl.cnf","etc/ca-certificates"],Ee=(e,t)=>t.flatMap((t=>Ce.map((r=>({platform:e,scope:"global",path:`${t}/${r}`}))))),xe={linux:[".cache/node",".cache/yarn"],darwin:[".cache/node","Library/Caches/Yarn"]},Pe=e=>[..._e,...xe[e]].map((t=>({platform:e,scope:"home-dir",path:t}))),Re=[{platform:"linux",scope:"global",path:"/bin"},{platform:"linux",scope:"global",path:"/sbin"},{platform:"linux",scope:"global",path:"/usr/bin"},{platform:"linux",scope:"global",path:"/usr/sbin"},{platform:"linux",scope:"global",path:"/lib"},{platform:"linux",scope:"global",path:"/lib64"},{platform:"linux",scope:"global",path:"/usr/lib"},{platform:"linux",scope:"global",path:"/usr/lib64"},{platform:"linux",scope:"global",path:"/usr/libexec"},{platform:"linux",scope:"global",path:"/usr/share"},{platform:"linux",scope:"global",path:"/etc/ld.so.cache"},{platform:"linux",scope:"global",path:"/etc/ld.so.conf"},{platform:"linux",scope:"global",path:"/etc/ld.so.conf.d"},{platform:"linux",scope:"global",path:"/etc/ssl/certs"},{platform:"linux",scope:"global",path:"/etc/ssl/openssl.cnf"},{platform:"linux",scope:"global",path:"/etc/ssl/cert.pem"},{platform:"linux",scope:"global",path:"/etc/ssl/ca-bundle.pem"},{platform:"linux",scope:"global",path:"/etc/ssl/certs/ca-certificates.crt"},{platform:"linux",scope:"global",path:"/etc/pki/tls/certs"},{platform:"linux",scope:"global",path:"/etc/pki/tls/openssl.cnf"},{platform:"linux",scope:"global",path:"/etc/pki/ca-trust/extracted"},{platform:"linux",scope:"global",path:"/etc/resolv.conf"},{platform:"linux",scope:"global",path:"/etc/hosts"},{platform:"linux",scope:"global",path:"/etc/nsswitch.conf"},{platform:"linux",scope:"global",path:"/etc/gai.conf"},{platform:"linux",scope:"global",path:"/etc/alternatives"},{platform:"linux",scope:"global",path:"/etc/mime.types"},{platform:"linux",scope:"global",path:"/etc/profile"},{platform:"linux",scope:"global",path:"/etc/bash.bashrc"},{platform:"linux",scope:"global",path:"/etc/zsh/zshenv"},{platform:"linux",scope:"global",path:"/etc/zsh/zprofile"},{platform:"linux",scope:"global",path:"/etc/zsh/zshrc"},{platform:"linux",scope:"global",path:"/etc/zsh/zlogin"},{platform:"linux",scope:"global",path:"/etc/gitconfig"},{platform:"linux",scope:"home",path:".bashrc"},{platform:"linux",scope:"home",path:".bash_profile"},{platform:"linux",scope:"home",path:".profile"},{platform:"linux",scope:"home",path:".zshenv"},{platform:"linux",scope:"home",path:".zprofile"},{platform:"linux",scope:"home",path:".zshrc"},{platform:"linux",scope:"home",path:".zlogin"},{platform:"linux",scope:"home",path:".gitconfig"},{platform:"linux",scope:"home",path:".ssh/known_hosts"},{platform:"linux",scope:"home",path:".config/mise/config.toml"},{platform:"linux",scope:"home-dir",path:".cache/dotslash"},...Pe("linux"),...Ee("linux",["/usr/local","/home/linuxbrew/.linuxbrew"]),{platform:"linux",scope:"global",path:"/usr/local/go"},{platform:"linux",scope:"global",path:"/nix/store"},{platform:"linux",scope:"global",path:"/nix/var/nix/profiles"},{platform:"linux",scope:"bundled",path:"ripgrep"},{platform:"darwin",scope:"global",path:"/bin"},{platform:"darwin",scope:"global",path:"/usr/bin"},{platform:"darwin",scope:"global",path:"/usr/lib"},{platform:"darwin",scope:"global",path:"/usr/libexec"},{platform:"darwin",scope:"global",path:"/usr/share"},{platform:"darwin",scope:"global",path:"/System/Library"},{platform:"darwin",scope:"global",path:"/System/Cryptexes"},{platform:"darwin",scope:"global",path:"/Library/Apple"},{platform:"darwin",scope:"global",path:"/Library/Developer/CommandLineTools"},{platform:"darwin",scope:"global",path:"/Applications/Xcode.app"},{platform:"darwin",scope:"global",path:"/Library/Preferences/com.apple.dt.Xcode.plist"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/cert.pem"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/certs"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/openssl.cnf"},{platform:"darwin",scope:"global",path:"/private/etc/hosts"},{platform:"darwin",scope:"global",path:"/private/etc/resolv.conf"},{platform:"darwin",scope:"global",path:"/private/etc/apache2/mime.types"},{platform:"darwin",scope:"global",path:"/etc/profile"},{platform:"darwin",scope:"global",path:"/etc/bashrc"},{platform:"darwin",scope:"global",path:"/etc/zshenv"},{platform:"darwin",scope:"global",path:"/etc/zprofile"},{platform:"darwin",scope:"global",path:"/etc/zshrc"},{platform:"darwin",scope:"global",path:"/etc/zlogin"},{platform:"darwin",scope:"global",path:"/etc/gitconfig"},{platform:"darwin",scope:"home",path:".bashrc"},{platform:"darwin",scope:"home",path:".bash_profile"},{platform:"darwin",scope:"home",path:".profile"},{platform:"darwin",scope:"home",path:".zshenv"},{platform:"darwin",scope:"home",path:".zprofile"},{platform:"darwin",scope:"home",path:".zshrc"},{platform:"darwin",scope:"home",path:".zlogin"},{platform:"darwin",scope:"home",path:".gitconfig"},{platform:"darwin",scope:"home",path:".ssh/known_hosts"},{platform:"darwin",scope:"home",path:"Library/Preferences/.GlobalPreferences.plist"},{platform:"darwin",scope:"home",path:".config/mise/config.toml"},{platform:"darwin",scope:"home-dir",path:"Library/Python"},{platform:"darwin",scope:"home-dir",path:"Library/Caches/dotslash"},...Pe("darwin"),...Ee("darwin",["/opt/homebrew","/usr/local"]),{platform:"darwin",scope:"global",path:"/nix/store"},{platform:"darwin",scope:"global",path:"/nix/var/nix/profiles"},{platform:"darwin",scope:"bundled",path:"ripgrep"},{platform:"darwin",scope:"global",path:"/dev/null"},{platform:"darwin",scope:"global",path:"/dev/zero"},{platform:"darwin",scope:"global",path:"/dev/random"},{platform:"darwin",scope:"global",path:"/dev/urandom"}];function Ie(e=process.platform,t=q.homedir(),r={}){const n=[];for(const o of Re){if(o.platform!==e)continue;if("global"===o.scope){n.push(o.path);continue}const s="bundled"===o.scope?r[o.path]:(0,m.join)(t,o.path);if(s)try{let e;switch(o.scope){case"home":e=(0,g.lstatSync)(s).isFile();break;case"home-dir":e=(0,g.lstatSync)(s).isDirectory();break;case"bundled":e=(0,g.statSync)(s).isFile()}e&&n.push(s)}catch{}}return n}const Te=[{type:"workspace",pattern:"**/.cursor/*.json"},{type:"workspace",pattern:"**/.cursor/**/*.json"},{type:"workspace",pattern:"**/.cursor/.workspace-trusted"},{type:"workspace",pattern:"!**/.cursor/rules"},{type:"workspace",pattern:"!**/.cursor/rules/**"},{type:"workspace",pattern:"!**/.cursor/commands"},{type:"workspace",pattern:"!**/.cursor/commands/**"},{type:"workspace",pattern:"!**/.cursor/worktrees"},{type:"workspace",pattern:"!**/.cursor/worktrees/**"},{type:"workspace",pattern:"!**/.cursor/skills"},{type:"workspace",pattern:"!**/.cursor/skills/**"},{type:"workspace",pattern:"!**/.cursor/agents"},{type:"workspace",pattern:"!**/.cursor/agents/**"},{type:"workspace",pattern:"**/.claude/*.json"},{type:"workspace",pattern:"**/.claude/**/*.json"},{type:"workspace",pattern:"**/.vscode/**"},{type:"workspace",pattern:"**/.idea/**"},{type:"workspace",pattern:"**/.venv/"},{type:"workspace",pattern:"**/venv/"},{type:"workspace",pattern:"**/*.code-workspace"},{type:"workspace",pattern:"**/.cursorignore"},{type:"workspace",pattern:"**/.workspace-trusted"},{type:"workspace",pattern:"**/.cursor/**/cli.json"},{type:"workspace",pattern:"**/.cursor/**/cli-config.json"},{type:"workspace",pattern:"**/.cursor/**/mcp.json"},{type:"workspace",pattern:"**/.cursor/**/mcp-approvals.json"},{type:"workspace",pattern:"**/.cursor/**/permissions.json"},{type:"git",pattern:"**/.git/hooks/**"},{type:"git",pattern:"**/.git/config"},{type:"git",pattern:"**/.git/config.worktree"},{type:"git",pattern:"**/.git/info/attributes"},{type:"git",pattern:"**/.git/commondir"},{type:"git",pattern:"**/.git/worktrees/*/commondir"},{type:"git",pattern:"**/.git/worktrees/*/gitdir"},{type:"worktree",pattern:".git"},{type:"absolute",pattern:"/etc/ssl/cert.pem"},{type:"absolute",pattern:"/etc/ssl/ca-bundle.pem"},{type:"absolute",pattern:"/private/etc/ssl/cert.pem"},{type:"absolute",pattern:"/etc/ssl/certs/ca-certificates.crt"},{type:"absolute",pattern:"/etc/pki/tls/certs/ca-bundle.crt"},{type:"absolute",pattern:"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem"},{type:"home",pattern:".cursor/sandbox-policies"},{type:"absolute",pattern:"/tmp/node-compile-cache"},{type:"home",pattern:".cache/cursor-compile-cache"},{type:"home",pattern:"Library/Caches/cursor-compile-cache"}];function Ae(e){const t=Te.filter((e=>"workspace"===e.type)).map((e=>e.pattern));return{[e]:t}}function $e(e){const t=Te.filter((e=>"git"===e.type)).map((e=>e.pattern));return{[e]:t}}function Me(e){const t=Te.filter((e=>"worktree"===e.type)).map((e=>e.pattern));return{[e]:t}}Te.filter((e=>"git"===e.type)).map((e=>e.pattern)),Te.filter((e=>"workspace"===e.type&&e.pattern.startsWith("!")&&!e.pattern.endsWith("/**"))).map((e=>e.pattern.replace(/^!(\*\*\/)?/,"")));const De=[];let Oe=null,Fe=null;function Ne(e){if(!(e instanceof Error&&"code"in e&&"string"==typeof e.code)||e.code.startsWith("ERR_"))throw e}async function Le(e,t=""){const r=await(0,ne.lstat)(e).catch(Ne);if(void 0===r||!r.isFile()||r.size>4096)return;const n=await(0,ne.readFile)(e,"utf8").catch(Ne),o=n?.split("\n",1)[0]?.replace(/\r$/,"");if(void 0===o||!o.startsWith(t))return;const s=o.slice(t.length);return s.length>0&&!s.includes("\0")?s:void 0}async function je(e){if(!(0,oe.$f)(e))return(0,ne.realpath)(e).catch(Ne)}async function Ue(e){const t=await Le((0,m.join)(e,".git"),"gitdir: ");if(void 0===t)return;const r=await je((0,m.resolve)(e,t));if(void 0===r)return;const n=await Le((0,m.join)(r,"commondir")),o=void 0===n?r:await je((0,m.resolve)(r,n));return void 0===o?void 0:{gitDir:r,commonDirLink:n,commonDir:o}}async function Be(e){const t=await Ue(e);if(void 0===t||void 0===t.commonDirLink||"worktrees"!==(0,m.basename)((0,m.dirname)(t.gitDir)))return;const r=(0,m.dirname)((0,m.dirname)(t.gitDir));if(".git"!==(0,m.basename)(r)||(ze?t.commonDir.toLowerCase()!==r.toLowerCase():t.commonDir!==r))return;const n=await Le((0,m.join)(t.gitDir,"gitdir"));if(void 0===n)return;const o=(0,m.join)(e,".git"),[s,i]=await Promise.all([je((0,m.resolve)(t.gitDir,n)),je(o)]);return void 0!==s&&void 0!==i&&(ze?s.toLowerCase()===i.toLowerCase():s===i)?r:void 0}let We=null;function He(e){return function(){const e=q.homedir();if(null===We){const t=[];for(const r of Te)switch(r.type){case"absolute":t.push(r.pattern);break;case"home":e.length>0&&t.push((0,m.join)(e,r.pattern))}We=t}return[...We,...ye(e)]}().some((t=>{if(Ke(e,t))return!0;const r=function(e){let t;try{t=g.realpathSync.native((0,m.dirname)(e))}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;return"ENOENT"===t||"ENOTDIR"===t?void 0:qe}const r=(0,m.join)(t,(0,m.basename)(e));return r===(0,m.dirname)(r)?void 0:r}(t);return r===qe||void 0!==r&&Ke(e,r)}))}const qe=Symbol("unresolved parent");const ze="win32"===process.platform||"darwin"===process.platform;function Ge(e){if(!e.endsWith(m.sep))return e;const t=e.slice(0,-1);return""===t||"win32"===process.platform&&/^[a-zA-Z]:$/.test(t)?e:t}function Ve(e){return e.endsWith(m.sep)?e:e+m.sep}function Ke(e,t){const r=Ge(t);if(ze){const t=e.toLowerCase(),n=r.toLowerCase();return t===n||t.startsWith(Ve(n))}return e===r||e.startsWith(Ve(r))}function Je(e,t){const r=Ge(e);return ze?(0,m.relative)(r.toLowerCase(),t.toLowerCase()).replace(/\\/g,"/"):(0,m.relative)(r,t).replace(/\\/g,"/")}async function Ze(e,t){if(Ke(e,t)){const r=Je(t,e);if((null===Oe&&(Oe=se({ignoreCase:!0}),Oe.add(Te.filter((e=>"workspace"===e.type)).map((e=>e.pattern)))),Oe).ignores(r))return!0}const{isWorktree:r,gitDirParent:n}=await async function(e){const t=await(0,ne.lstat)((0,m.join)(e,".git")).catch(Ne);if(!t?.isFile())return{isWorktree:!1,gitDirParent:e};const r=await async function(e){return(await Ue(e))?.commonDir}(e);return{isWorktree:!0,gitDirParent:void 0===r?e:(0,m.dirname)(r)}}(t);for(const r of new Set([n,t]))if(Ke(e,r)){const t=Je(r,e);if((null===Fe&&(Fe=se({ignoreCase:!0}),Fe.add(Te.filter((e=>"git"===e.type)).map((e=>e.pattern)))),Fe).ignores(t))return!0}return!(!r||!Ke(e,t)||".git"!==Je(t,e))||He(e)}function Xe(e){return void 0!==e&&("allow"===e.default||void 0!==e.allow&&e.allow.length>0)}function Qe(e){return void 0!==e&&"allow"===e.default}function Ye(){return{version:1,default:"deny"}}function et(){return{version:1,default:"allow"}}var tt=r("../utils/dist/path-utils.js");function rt(e){if(!e)return;const t={version:1};if("allow"!==e.default&&"deny"!==e.default||(t.default=e.default),Array.isArray(e.allow)&&e.allow.length>0&&(t.allow=e.allow.filter((e=>"string"==typeof e))),Array.isArray(e.deny)&&e.deny.length>0&&(t.deny=e.deny.filter((e=>"string"==typeof e))),e.logging){const r={};"string"==typeof e.logging.decisionLogPath&&(r.decisionLogPath=e.logging.decisionLogPath),"jsonl"===e.logging.logFormat&&(r.logFormat="jsonl"),Object.keys(r).length>0&&(t.logging=r)}return t}function nt(e){const t=e.type??"workspace_readwrite",r={debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,enableSharedBuildCache:e.enableSharedBuildCache};if("insecure_none"===t)return{type:"insecure_none",...r};let n;if(Array.isArray(e.additionalReadonlyPaths)){const t=e.additionalReadonlyPaths;n=t.length>0?t:void 0}const o={...r,networkAccess:e.networkAccess,networkPolicy:rt(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,additionalReadonlyPaths:n,readBoundary:e.readBoundary,additionalReadPaths:Array.isArray(e.additionalReadPaths)?e.additionalReadPaths:void 0,disableTmpWrite:e.disableTmpWrite,privateTmp:e.privateTmp};return"workspace_readonly"===t?{type:"workspace_readonly",...o}:{type:"workspace_readwrite",...o,additionalReadwritePaths:e.additionalReadwritePaths}}function ot(e){if("object"!=typeof e||null===e)return"Expected an object";const t=Object.fromEntries(Object.entries(e));if(void 0!==t.type){const e=["insecure_none","workspace_readwrite","workspace_readonly"];if("string"!=typeof t.type||!e.includes(t.type))return`Invalid type: expected one of ${e.join(", ")}`}const r=["networkAccess","networkPolicyStrict","disableTmpWrite","privateTmp","enableSharedBuildCache","captureDenies"];for(const e of r)if(void 0!==t[e]&&"boolean"!=typeof t[e])return`Invalid ${e}: expected boolean`;const n=["debugOutputDir"];for(const e of n)if(void 0!==t[e]&&"string"!=typeof t[e])return`Invalid ${e}: expected string`;const o=["additionalReadwritePaths","additionalReadonlyPaths","additionalReadPaths"];for(const e of o)if(void 0!==t[e]){if(!Array.isArray(t[e]))return`Invalid ${e}: expected array`;if(!t[e].every((e=>"string"==typeof e)))return`Invalid ${e}: expected array of strings`}if(void 0!==t.readBoundary&&"system"!==t.readBoundary&&"workspace"!==t.readBoundary)return'Invalid readBoundary: expected "system" or "workspace"';if(void 0!==t.networkPolicy){if("object"!=typeof t.networkPolicy||null===t.networkPolicy)return"Invalid networkPolicy: expected object";const e=Object.fromEntries(Object.entries(t.networkPolicy));if(void 0!==e.default&&"allow"!==e.default&&"deny"!==e.default)return'Invalid networkPolicy.default: expected "allow" or "deny"';if(void 0!==e.allow&&!Array.isArray(e.allow))return"Invalid networkPolicy.allow: expected array";if(void 0!==e.deny&&!Array.isArray(e.deny))return"Invalid networkPolicy.deny: expected array"}}async function st(e,t){const r=await async function(e,t){try{const r=await(0,ne.readFile)(e,"utf-8"),n=JSON.parse(r);if(void 0!==ot(n))return{success:!1,error:`Invalid sandbox policy: ${ot(n)??""}`};let o=nt(n);return t&&(o=it(o,t)),{success:!0,policy:o}}catch(e){return e instanceof Error?"code"in e&&"ENOENT"===e.code?{success:!1,error:"File not found"}:e instanceof SyntaxError?{success:!1,error:`Invalid JSON: ${e.message}`}:{success:!1,error:e.message}:{success:!1,error:"Unknown error"}}}(e,t);if(r.success)return r.policy}function it(e,t){if("insecure_none"===e.type)return e;const r=e.additionalReadonlyPaths?.map((e=>(0,tt.o1)(e,t))),n=e.additionalReadPaths?.map((e=>(0,tt.o1)(e,t)));if("workspace_readonly"===e.type)return{...e,additionalReadonlyPaths:r,additionalReadPaths:n};const o=e.additionalReadwritePaths?.map((e=>(0,tt.o1)(e,t)));return{...e,additionalReadonlyPaths:r,additionalReadPaths:n,additionalReadwritePaths:o}}var at=r("../constants/dist/commercial-cursor-hosts.js");function ct(e){const t=e.replace(/\\/g,"/").replace(/\/+$/,"");return""===t?"/":/^[a-zA-Z]:$/.test(t)?`${t}/`:t}function lt(e){const t=ct(e);return/^[a-zA-Z]:\//.test(t)||t.startsWith("//")?t.toLowerCase():t}const ut={insecure_none:0,workspace_readwrite:1,workspace_readonly:2};function dt(){return"1"===process.env[at.K4]}function ht(e){if(!dt())return e.teamAdmin?.type??e.perRepo?.type??e.perUser?.type??"insecure_none";const t=e.teamAdmin?.type??e.perUser?.type;return void 0===t&&void 0===e.perRepo?"insecure_none":Rt(t??"workspace_readwrite",e.perRepo?.type??"insecure_none")}function pt(...e){return e.some((e=>!0===e))}function ft(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return[];if(t.some((e=>0===e.length)))return[];if(1===t.length)return function(e){const t=new Set,r=[];for(const n of e){const e=lt(n);t.has(e)||(t.add(e),r.push(n))}return r}(t[0]).map(ct);let r=new Map(t[0].map((e=>{const t=ct(e);return[lt(t),t]})));for(let e=1;en.has(e))))}return[...r.values()]}function mt(...e){const t=new Map;for(const r of e)if(r)for(const e of r){const r=ct(e),n=lt(r);t.has(n)||t.set(n,r)}return[...t.values()]}const gt=function({defaultValue:e,rank:t}){return{defaultValue:e,merge:(...r)=>{const n=r.filter((e=>void 0!==e));return 0===n.length?e:n.reduce(((e,r)=>t[r]ft(...e);function yt(...e){return gt.merge(...e)}function vt(...e){return wt(...e)}function bt(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return;let r;for(const e of t){if("deny"===e.default){r="deny";break}"allow"===e.default&&void 0===r&&(r="allow")}const n=new Set;for(const e of t)if(e.deny)for(const t of e.deny)n.add(t);const o=new Set;for(const e of t)if(e.allow)for(const t of e.allow)o.add(t);const s=o.size>0?[...o]:void 0;let i;for(let e=t.length-1;e>=0;e--)if(void 0!==t[e].logging){i=t[e].logging;break}const a={version:1};return void 0!==r&&(a.default=r),void 0!==s&&(a.allow=s),n.size>0&&(a.deny=[...n]),void 0!==i&&(a.logging=i),void 0!==a.default||void 0!==a.allow&&0!==a.allow.length||void 0!==a.deny&&0!==a.deny.length||void 0!==a.logging?a:void 0}function St(e,t){if(!e||0===e.length)return[...t];const r=new Set(e);for(const e of t)r.has(e)&&r.delete(e),r.add(e);return[...r]}function kt(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return;const r={};for(const e of t)for(const[t,n]of Object.entries(e))r[t]=St(r[t],n);return 0!==Object.keys(r).length?r:void 0}function _t(...e){for(let t=e.length-1;t>=0;t--)if(void 0!==e[t])return e[t]}async function Ct(e,t,r={}){if(!t)return{policy:{type:"insecure_none"}};if(dt()&&(t=Mt(t,e)),(0,oe.$f)(e))return Ot(t,{workspaceDir:e});if("workspace_readwrite"!==(Pt(t)??"workspace_readwrite"))return Ot(t,{workspaceDir:e});const n=r.stat??ne.stat,o=await async function(e,t){for(let r=e;;r=(0,m.dirname)(r)){if((0,oe.$f)(r))return;const e=await Et(r,t);if(void 0!==e)return e;if((0,m.dirname)(r)===r)return}}(e,n);let s=o?.root??e;if(o?.isFile){const e=await Be(o.root);void 0!==e&&(s=(0,m.dirname)(e)),t=xt(t,void 0===e?[]:[e],Me(o.root))}return t=await async function(e,t,r){const n=Nt(e,"workspace_readwrite"),o=mt(n.perUser?.additionalReadwritePaths,n.perRepo?.additionalReadwritePaths,n.teamAdmin?.additionalReadwritePaths);if(0===o.length)return e;const s=(await Promise.all(o.map((async e=>{if(t.has(ct(e))||(0,oe.$f)(e))return[];const n=await Et(e,r);if(void 0===n)return[];const o=[Ae(e),$e(e)];if(n.isFile){o.push(Me(e));const t=await Be(e);void 0!==t&&o.push($e((0,m.dirname)(t)))}return o})))).flat();return 0===s.length?e:xt(e,[],...s)}(t,new Set([ct(e)]),n),Ot(t,{workspaceDir:e,gitDirParent:s})}async function Et(e,t){const r=await t((0,m.join)(e,".git")).catch(Ne);return r?.isFile()||r?.isDirectory()?{root:e,isFile:r.isFile()}:void 0}function xt(e,t,...r){const n=dt(),o=n?e.perUser:e.perRepo,s="workspace_readwrite"===o?.type||void 0===o?o:void 0,i={...s,type:"workspace_readwrite",additionalReadwritePaths:t.length>0?[...s?.additionalReadwritePaths??[],...t]:s?.additionalReadwritePaths,writeProtectionMapping:kt(s?.writeProtectionMapping,...r)};return n?{...e,perUser:i}:{...e,perRepo:i}}function Pt(e){const{perUser:t,perRepo:r,teamAdmin:n}=e,o=[t,r,n].filter((e=>void 0!==e));if(0===o.length)return;const s=o[0].type;for(const e of o)if(e.type!==s)throw new Error(`Cannot merge policies of different types: found "${s}" and "${e.type}". All policies must be of the same type (all workspace_readwrite, all workspace_readonly, or all insecure_none).`);return s}function Rt(e,t){return ut[e]>=ut[t]?e:t}function It(e,t){if(void 0===e||e.type===t)return e;if("insecure_none"===t)return{type:t,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,enableSharedBuildCache:e.enableSharedBuildCache};if("insecure_none"===e.type)return{...e,type:t};if("workspace_readonly"===t){if("workspace_readwrite"===e.type){const{additionalReadwritePaths:r,...n}=e;return{...n,type:t}}return e}return e}function Tt(e){if("deny"===e?.default||void 0!==e?.deny&&0!==e.deny.length)return{version:1,..."deny"===e.default?{default:"deny"}:{},...void 0!==e.deny&&e.deny.length>0?{deny:e.deny}:{}}}function At(e,t,r){if(void 0===e||"insecure_none"===t)return;const n="insecure_none"===e.type?void 0:e,o={captureDenies:!0===e.captureDenies||void 0,networkPolicy:Tt(n?.networkPolicy),networkPolicyStrict:!0===n?.networkPolicyStrict||void 0,readBoundary:"workspace"===n?.readBoundary?"workspace":void 0,additionalReadPaths:void 0===n?.additionalReadPaths?void 0:ft(n.additionalReadPaths,r),additionalReadonlyPaths:n?.additionalReadonlyPaths,disableTmpWrite:!0===n?.disableTmpWrite||void 0,ignoreMapping:n?.ignoreMapping,writeProtectionMapping:n?.writeProtectionMapping};return"workspace_readonly"===t?{type:t,...o}:{type:"workspace_readwrite",...o}}function $t(e,t){return void 0===e||"insecure_none"===e.type||void 0===t?e:{...e,additionalReadPaths:e.additionalReadPaths?.map((e=>ct((0,tt.o1)(e,t))))}}function Mt(e,t){const r=Pt({perUser:e.perUser,teamAdmin:e.teamAdmin})??"workspace_readwrite",n=void 0===e.perRepo?r:Rt(r,e.perRepo.type),o=$t(It(e.perUser,n),t),s=$t(It(e.teamAdmin,n),t),i=mt("insecure_none"===o?.type?void 0:o?.additionalReadPaths,"insecure_none"===s?.type?void 0:s?.additionalReadPaths);return{perUser:o,perRepo:At(e.perRepo,n,i),teamAdmin:s}}function Dt(e,t){return Mt(e,t)}function Ot(e,t){return function(e,t){dt()&&(e=Mt(e,t?.workspaceDir));const r=Pt(e);if(void 0===r)return Ut({},t);switch(r){case"workspace_readwrite":return Ut(Nt(e,r),t);case"workspace_readonly":return function(e,t){const r=t?.debug,n=Lt(e,t),o={policy:jt({type:"workspace_readonly",disableTmpWrite:n.disableTmpWrite,networkPolicyStrict:n.networkPolicyStrict,readBoundary:n.readBoundary,additionalReadPaths:n.additionalReadPaths,additionalReadonlyPaths:n.additionalReadonlyPaths,networkPolicy:n.networkPolicy,debugOutputDir:n.debugOutputDir,captureDenies:n.captureDenies,enableSharedBuildCache:n.enableSharedBuildCache,privateTmp:n.privateTmp,ignoreMapping:n.ignoreMapping,writeProtectionMapping:n.writeProtectionMapping},"workspace_readonly")};return r&&(o.debug={fieldSources:n.fieldSources}),o}(Nt(e,r),t);case"insecure_none":return function(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,s=t?.debug,i={policy:jt({type:"insecure_none",allowlistEscalated:pt(r?.allowlistEscalated,n?.allowlistEscalated,o?.allowlistEscalated)||void 0,debugOutputDir:_t(r?.debugOutputDir,n?.debugOutputDir,o?.debugOutputDir),captureDenies:pt(r?.captureDenies,n?.captureDenies,o?.captureDenies)||void 0,enableSharedBuildCache:_t(r?.enableSharedBuildCache,n?.enableSharedBuildCache,o?.enableSharedBuildCache)},"insecure_none")};return s&&(i.debug={fieldSources:{}}),i}(Nt(e,r),t);default:throw new Error(`Unknown policy type: ${String(r)}`)}}(e,t)}function Ft(e,t){return e?.type===t}function Nt(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e;return{perUser:Ft(r,t)?r:void 0,perRepo:Ft(n,t)?n:void 0,teamAdmin:Ft(o,t)?o:void 0}}function Lt(e,t){const r=t?.debug,{perUser:n,perRepo:o,teamAdmin:s}=e,i=t?.workspaceDir??process.cwd(),a=function(e){const t=function(){if(0!==De.length)return{version:1,deny:[...De]}}(),r=q.homedir(),n=[];for(const e of Te)switch(e.type){case"workspace":case"git":case"worktree":break;case"absolute":n.push(e.pattern);break;case"home":r.length>0&&n.push((0,m.join)(r,e.pattern));break;default:{const t=e.type;throw new Error(`Unknown entry type: ${String(t)}`)}}return n.push(...ye(r)),{type:"workspace_readwrite",additionalReadonlyPaths:n,writeProtectionMapping:Ae(e),...t&&{networkPolicy:t},networkPolicyStrict:!0}}(i),c={},l=[n,o,s],u=["perUser","perRepo","teamAdmin","hardcoded"],d=(e,t)=>{r&&(c[e]=u[t]??"unknown")},h=pt(n?.disableTmpWrite,o?.disableTmpWrite,s?.disableTmpWrite);for(let e=l.length-1;e>=0;e--)if(!0===l[e]?.disableTmpWrite){d("disableTmpWrite",e);break}const p=pt(n?.networkPolicyStrict,o?.networkPolicyStrict,s?.networkPolicyStrict,a.networkPolicyStrict);a.networkPolicyStrict&&d("networkPolicyStrict",3);const f=dt()?yt(_t(n?.readBoundary,s?.readBoundary)??"system",o?.readBoundary):_t(n?.readBoundary,o?.readBoundary,s?.readBoundary)??"system",g=_t(n?.additionalReadPaths,o?.additionalReadPaths),w=!1===s?.allowUserOverrideReadPaths?mt(s.additionalReadPaths):mt(g,s?.additionalReadPaths),y="workspace"===f?w:void 0,v=mt(n?.additionalReadonlyPaths,o?.additionalReadonlyPaths,s?.additionalReadonlyPaths,a.additionalReadonlyPaths),b=v.length>0?v:void 0;let S=bt(n?.networkPolicy,o?.networkPolicy,s?.networkPolicy,a.networkPolicy);const k=s?.networkPolicy?.allow;void 0!==k&&k.length>0&&void 0!==S&&(S={...S,allow:[...k]},r&&(c["networkPolicy.allow"]="teamAdmin (replace)"));const _=void 0!==(C=S)?C:{version:1,default:"deny"};var C;const E=_t(n?.debugOutputDir,o?.debugOutputDir,s?.debugOutputDir),x=pt(n?.captureDenies,o?.captureDenies,s?.captureDenies),P=_t(n?.enableSharedBuildCache,o?.enableSharedBuildCache,s?.enableSharedBuildCache),R=_t(n?.privateTmp,o?.privateTmp,s?.privateTmp),I=kt(n?.ignoreMapping,o?.ignoreMapping,s?.ignoreMapping,a.ignoreMapping),T=$e(t?.gitDirParent??i);return{disableTmpWrite:h||void 0,networkPolicyStrict:p,readBoundary:f,additionalReadPaths:y,additionalReadonlyPaths:b,networkPolicy:_,debugOutputDir:E,captureDenies:x||void 0,enableSharedBuildCache:P,privateTmp:R,ignoreMapping:I,writeProtectionMapping:kt(n?.writeProtectionMapping,o?.writeProtectionMapping,s?.writeProtectionMapping,a.writeProtectionMapping,T),fieldSources:c}}function jt(e,t){const r={...e,type:t};for(const[e,t]of Object.entries(r))void 0===t&&Reflect.deleteProperty(r,e);return r}function Ut(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,s=t?.debug,i=Lt(e,t),a=mt(r?.additionalReadwritePaths,n?.additionalReadwritePaths,o?.additionalReadwritePaths),c={policy:jt({type:"workspace_readwrite",disableTmpWrite:i.disableTmpWrite,networkPolicyStrict:i.networkPolicyStrict,readBoundary:i.readBoundary,additionalReadPaths:i.additionalReadPaths,additionalReadwritePaths:a.length>0?a:void 0,additionalReadonlyPaths:i.additionalReadonlyPaths,networkPolicy:i.networkPolicy,debugOutputDir:i.debugOutputDir,captureDenies:i.captureDenies,enableSharedBuildCache:i.enableSharedBuildCache,privateTmp:i.privateTmp,ignoreMapping:i.ignoreMapping,writeProtectionMapping:i.writeProtectionMapping},"workspace_readwrite")};return s&&(c.debug={fieldSources:i.fieldSources}),c}var Bt=r("../utils/dist/workload-spawn.js"),Wt=r("../context/dist/logger.js"),Ht=r("../context/dist/core.js"),qt=r("../utils/dist/command-glob.js");const zt=n.execFile,Gt=new WeakMap;function Vt(e,t,r){return e===t?"related":r?.has(e)?"probably_unrelated":"maybe_related"}const Kt="darwin"===process.platform,Jt="linux"===process.platform,Zt=(0,Wt.h)("shell-exec:sandbox");function Xt(e){const t=ce();return e&&0!==e.length?e.includes(t)?e:[...e,t]:[t]}let Qt,Yt=!0,er=!1;function tr(){return Qt}function rr(e){"linux"===process.platform&&Object.assign(e,I(e))}let nr=null,or=null,sr=null,ir=null,ar=!1,cr=null;function lr(e){return{...e,additionalReadonlyPaths:Xt(e.additionalReadonlyPaths)}}class ur extends Error{}function dr(e){return e instanceof Error&&"code"in e&&"string"==typeof e.code?e.code:"unknown"}function hr(e,t,r){let n;e.ignoreMapping&&(n=function(e){return vr(e)}(e.ignoreMapping));const o=function(e,t,r){const n=e&&e.length>0?function(...e){const t={};for(const r of e){let e=!1;try{e=(0,g.existsSync)(r)&&(0,g.statSync)(r).isDirectory()}catch{}if(e)t[r]||(t[r]=[]),t[r].push("**");else{const e=r.lastIndexOf("/"),n=e>0?r.slice(0,e):"/",o=e>=0?r.slice(e+1):r;t[n]||(t[n]=[]),o?t[n].push(o,`${o}/**`):t[n].push("**")}}return t}(...e):{},o=!Jt||yr(r),s={...n};for(const[e,r]of Object.entries(t??{})){const t=e.startsWith("file://")?br(e):e;(o||yr(t))&&(s[e]=St(s[e],r))}if(0!==Object.keys(s).length)return vr(s)}(e.additionalReadonlyPaths,e.writeProtectionMapping,t),s=(i=e.readBoundary,r?.workspaceReadEnabled??function(){const e=Yt;return"function"==typeof e?e():e}()?i??"system":"system");var i;const a=function(e=process.platform){const t=[],r=new Set,n={};try{n.ripgrep=T()}catch{}for(const o of Ie(e,q.homedir(),n))r.has(o)||(r.add(o),t.push(o));return t}(),c=[t,..."workspace_readwrite"===e.type&&e.additionalReadwritePaths||[],Z(t)].filter((e=>void 0!==e)),l="workspace"===s?(e.additionalReadPaths??[]).flatMap((e=>function(e,t){let r=e.trim();(r.startsWith("~/")||r.startsWith("~\\"))&&(r=m.join(q.homedir(),r.slice(2)));const n=e=>e.includes("*")||e.includes("?"),o=/[/\\]\*\*?$/;if(o.test(r)&&n(m.basename(r.replace(/(?:[/\\]\*\*?)+$/,""))))return Zt.warn((0,Ht.q6)(),"[additionalReadPathGrants] a Read Allowlist file-name glob followed by /* or /** grants nothing"),[];const s=m.basename(r);if(o.test(r)||!n(s))return function(e){const t=[],r=new Set;for(const n of e){let e=n.trim();if(!e)continue;"~"===e?e=q.homedir():(e.startsWith("~/")||e.startsWith("~\\"))&&(e=m.join(q.homedir(),e.slice(2))),e=e.replace(/\/\*\*$/,"").replace(/\/\*$/,""),e=e.replace(/\\\*\*$/,"").replace(/\\\*$/,"");const o=m.basename(e);if((o.includes("*")||o.includes("?"))&&(e=m.dirname(e)),!e||"."===e)continue;const s=m.normalize(e);r.has(s)||(r.add(s),t.push(s))}return t}([e]);const i=m.dirname(r);return m.isAbsolute(i)?function(e,t,r){const n=(0,qt.b)(t),o=[];let s;try{const t=(0,g.realpathSync)(e);if(r.filter((e=>g.existsSync(e))).map((e=>(0,g.realpathSync)(e))).some((e=>(0,tt.BJ)(t,e))))return[];s=g.opendirSync(t);for(let e=1;;e++){const r=s.readSync();if(null===r)return o;if(e>1e4)throw new ur("its folder has more than 10000 entries");if(!n(r.name))continue;const i=m.join(t,r.name);try{if(!g.lstatSync(i).isFile()||m.dirname((0,g.realpathSync)(i))!==t)continue}catch(e){Zt.info((0,Ht.q6)(),`[fileNameGlobMatches] skips a matching file: error ${dr(e)}`);continue}if(256===o.length)throw new ur("more than 256 files match");o.push(i)}}catch(e){const t=e instanceof ur?e.message:`error ${dr(e)}`;return Zt.warn((0,Ht.q6)(),`[fileNameGlobMatches] a Read Allowlist file-name glob grants nothing: ${t}`),[]}finally{s?.closeSync()}}(i,s,t):[]}(e,c))):[],u=[...a],d=new Set(a);for(const e of l)d.has(e)||(d.add(e),u.push(e));const h={cwd:t,readBoundary:s,hardcodedReadPaths:u,additionalReadonlyPaths:o,networkAccess:Xe(e.networkPolicy),ignoreMapping:n};return"workspace_readonly"===e.type?{type:e.type,...h}:{type:e.type,...h,additionalReadwritePaths:e.additionalReadwritePaths||[],disableTmpWrite:e.disableTmpWrite||!1}}function pr(e){const t={sandbox:e};return Jt&&function(){const e=er;return"function"==typeof e?e():e}()&&(t.kernelMountBudget=!0),t}function fr(e){if(null!==nr)return nr;try{const t=tr();return Zt.info(e,`[checkBinaryAvailable] Resolved binary path: ${t}`),t?(nr=g.existsSync(t),nr?Zt.info(e,`[checkBinaryAvailable] Binary path exists: ${String(nr)}`):(or=new Error(`Sandbox binary not found at ${t}`),Zt.info(e,`[checkBinaryAvailable] Binary not found at: ${t}`)),nr):(or=new Error("Sandbox binary path was not configured"),nr=!1,Zt.info(e,"[checkBinaryAvailable] Binary path not set, returning false"),!1)}catch(t){return or=t instanceof Error?t:new Error(String(t)),nr=!1,Zt.info(e,`[checkBinaryAvailable] Exception checking binary: ${String(t)}`),!1}}function mr(e){if(null!==ir)return ir;const t=e??(0,Ht.q6)();if(Zt.info(t,"[isSandboxHelperSupported] Starting sandbox support check..."),!fr(t)){const e=or?.message||"Binary check failed";return sr=e,Zt.info(t,`[isSandboxHelperSupported] Binary not available, returning false. Reason: ${e}`),ir=!1,ir}if("win32"===process.platform)return sr="Windows sandbox helper only provides network proxy, not filesystem isolation",Zt.info(t,"[isSandboxHelperSupported] win32: returning false (proxy-only, no filesystem sandbox)"),ir=!1,ir;if("darwin"===process.platform)return sr=null,Zt.info(t,`[isSandboxHelperSupported] ${process.platform} platform, binary available, sandbox supported!`),ir=!0,ir;const{binaryPath:r,args:o,env:s}=function(e,t){const r=pr(hr(lr({type:"workspace_readwrite"}),t)),n=String(tr());Zt.info(e,`[sandboxPreflight] Running preflight with binary: ${n}`),Zt.info(e,`[sandboxPreflight] CWD: ${t}`);const o={...process.env};return rr(o),{binaryPath:n,args:["--policy",le(JSON.stringify(r)),"--preflight-only","--","/bin/true"],env:o}}(t,process.cwd());try{const e=Date.now();(0,Bt.D9)(n.execFileSync,r,o,{stdio:["ignore","ignore","pipe"],timeout:gr,env:s,shell:!1});const i=Date.now()-e;return sr=null,Zt.info(t,`[isSandboxHelperSupported] Preflight succeeded in ${i}ms, sandbox supported!`),ir=!0,ir}catch(e){return function(e,t){const{message:r,status:n,stderrText:o}=t;return Zt.error(e,`[sandboxPreflight] Preflight failed: ${r}`),Zt.error(e,`[sandboxPreflight] Exit status: ${n}`),o&&Zt.error(e,`[sandboxPreflight] Stderr: ${o}`),sr=2===n?`Linux preflight failed with exit code 2 (unsupported kernel features). stderr: ${o||"none"}`:`Linux preflight failed: ${r||"unknown error"}. Exit status: ${n}. stderr: ${o||"none"}`,ir=!1,!1}(t,function(e){if("object"!=typeof e||null===e)return{stderrText:""};const t="message"in e&&"string"==typeof e.message?e.message:void 0,r=!("status"in e)||"number"!=typeof e.status&&null!==e.status?void 0:e.status,n="stderr"in e?e.stderr:void 0;return{message:t,status:r,stderrText:Buffer.isBuffer(n)||"string"==typeof n?n.toString():""}}(e))}}(0,G.J)((function(){ir=null,ar=!1,cr=null,sr=null,nr=null,or=null}));const gr=15e3;function wr(e,t=[],r={},o){const i=(0,Ht.q6)();if(r.env=a(s(r.env)),!fr(i))throw new Error(`Sandbox binary not available: ${or?.message||"binary not configured"}. Please build the binary or use 'insecure_none' policy.`);if("insecure_none"===o.type)return(0,Bt.D9)(n.spawn,e,t,{...r,windowsHide:!0});if("workspace_readwrite"===o.type||"workspace_readonly"===o.type)return function(e,t,r,o){if("workspace_readwrite"!==o.type&&"workspace_readonly"!==o.type)throw new Error("Expected workspace_readwrite or workspace_readonly policy");const i=String(r.cwd??process.cwd()),c=o.sandboxWorkspaceRoot??i;let u=e,d=t;r.shell&&("win32"===process.platform?(u="string"==typeof r.shell?r.shell:"cmd.exe",d=["/c",`${e} ${t.join(" ")}`]):(u="string"==typeof r.shell?r.shell:"/bin/sh",d=["-c",`${e} ${t.join(" ")}`]));const h=function({workspaceRoot:e,executionCwd:t}){const r=m.resolve(e),n=m.resolve(t),o=Sr(r);if(n===r||n===o)return;const s=e=>(0,tt.ZU)({basePath:o,targetPath:e})?m.join(r,m.relative(o,e)):void 0,i=(0,tt.ZU)({basePath:r,targetPath:n})?n:s(n)??n;return{directory:i,fallbackDirectory:s(Sr(n))??i}}({workspaceRoot:c,executionCwd:i});"win32"!==process.platform&&void 0!==h&&({command:u,args:d}=(0,oe.kO)(u,d,h));const p=hr(lr(o),c),f=(0,Ht.q6)();!function({log:e,dirs:t=ve(q.homedir(),q.tmpdir(),pe),createOnly:r=[we(process.env,pe)].filter((e=>void 0!==e)),policyDir:n=ie(),uid:o=process.getuid?.()??-1}){const s=m.join(n,"node-compile-cache-removed-1"),{record:i,problem:a}=function(e){const t=e=>({record:{cleaned:[],kept:{},failed:{}},problem:e});let r,n;try{r=g.readFileSync(e,"utf8")}catch(e){const r=ke(e);return t("ENOENT"===r?void 0:r)}try{n=JSON.parse(r)}catch(e){return t(e instanceof SyntaxError?"not JSON":ke(e))}if("object"!=typeof n||null===n)return t("not a record");const o="cleaned"in n?n.cleaned:void 0;return{record:{cleaned:Array.isArray(o)?o.filter((e=>"string"==typeof e)):[],kept:Se("kept"in n?n.kept:void 0),failed:Se("failed"in n?n.failed:void 0)}}}(s);void 0!==a&&e(`node compile cache: starting a new cleanup record (${a})`);const c=new Set(i.cleaned),l=new Set(t);let u=!1;for(const n of[...t,...r.filter((e=>!l.has(e)))])try{const t=g.lstatSync(n,{throwIfNoEntry:!1});if(void 0!==t){const r=be(t,o);if(void 0!==r){i.kept[n]!==r&&(e(`node compile cache: kept ${n} (${r})`),i.kept[n]=r,u=!0);continue}l.has(n)&&!c.has(n)&&(g.rmSync(n,{recursive:!0,force:!0}),e(`node compile cache: removed ${n}`))}g.mkdirSync(n,{recursive:!0,mode:448}),l.has(n)&&!c.has(n)&&(c.add(n),u=!0),void 0===i.kept[n]&&void 0===i.failed[n]||(delete i.kept[n],delete i.failed[n],u=!0)}catch(t){const r=ke(t);i.failed[n]!==r&&(e(`node compile cache: could not prepare ${n} (${r})`),i.failed[n]=r,u=!0)}u&&function(e,t){const r=`${e}.${process.pid}.tmp`;try{g.writeFileSync(r,`${JSON.stringify(t)}\n`,{mode:384}),g.renameSync(r,e)}catch{g.rmSync(r,{force:!0})}}(s,{...i,cleaned:[...c]})}({log:e=>Zt.info(f,e)});const w=function(e){if(!("workspace"!==e.readBoundary||"workspace_readwrite"===e.type&&e.disableTmpWrite||"win32"===process.platform))return X(e.cwd,{create:!0})}(p);let y;w&&(p.additionalReadwritePaths=[...p.additionalReadwritePaths??[],w],Jt&&!0===o.privateTmp&&(y=te(w).TMPDIR));const v=function(e){if("insecure_none"===e.type)return;const t=e.networkPolicy;if(void 0===t)return;if(!Xe(t))return;const r=void 0!==t.deny&&t.deny.length>0;return"allow"!==t.default||r?{version:1,...t}:void 0}(o),b=pr(p);void 0!==y&&(b.mapTmpTo=y),void 0!==v&&(b.networkPolicy=v),!1===o.networkPolicyStrict&&(b.networkPolicyStrict=!1);const S=["--policy",le(JSON.stringify(b)),"--",u,...d],k=s(process.env),_={..."linux"===process.platform?l(k):k,..."linux"===process.platform&&r.env?l(r.env):r.env,CURSOR_SANDBOX:"native"};rr(_);const C=new Set(Y);if(w){const e=function(e,t,r){const n=te(e);if(r){const r=re();for(const[o,s]of Object.entries(re(e)))t[o]===r[o]&&(n[o]=s)}return n}(w,_,o.enableSharedBuildCache);Object.assign(_,e);for(const t of Object.keys(e))C.add(t);_.__CURSOR_SANDBOX_TEMP_RESTORE=Object.entries(e).map((([e,t])=>`builtin export ${e}='${t.replace(/'/g,"'\\''")}'`)).join("; ")}_.__CURSOR_SANDBOX_OWNED_ENV=[...C].join(" ");const E={cwd:void 0!==y?p.cwd:r.cwd||i,env:a(_),stdio:r.stdio||["pipe","pipe","pipe"],detached:r.detached,windowsHide:!0};try{const e=new Date,t=(0,Bt.D9)(n.spawn,String(tr()),S,E);return Kt&&t.pid&&function(e,t){Gt.set(e,t)}(t,{startTime:e,pid:t.pid}),t}catch(e){throw new Error(`Failed to spawn sandboxed process: ${String(e)}`)}}(e,t,r,o);throw new Error(`Unsupported sandbox policy: ${String(o)}`)}function yr(e,t=e=>g.existsSync(e)){if((0,oe.$f)(e))return!0;let r=m.resolve(e);for(;;){try{if(t(m.join(r,".git")))return!0}catch{}const e=m.dirname(r);if(e===r)return!1;r=e}}function vr(e,t,r,n){const o={};for(const[t,r]of Object.entries(e)){const e=t.startsWith("file://")?br(t):t;o[e]=St(o[e],r);const n=Sr(e);n!==e&&(o[n]=St(o[n],r))}return o}function br(e){let t=e.replace(/^file:\/\//,"");return t=decodeURIComponent(t),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t}function Sr(e,t){if((0,oe.$f)(e))return e;try{return(t??g.realpathSync)(e)}catch{return e}}function kr(){return sr}class _r extends Error{reason;constructor(e,t){super(e),this.reason=t,this.name="SandboxUnsupportedError"}}const Cr="darwin"===process.platform;function Er(e){!function(e){T();const{sandboxBinaryPath:t,workspaceReadEnabled:r,kernelMountBudget:n}=e;Qt||(Qt=t),void 0!==r&&(Yt=r),void 0!==n&&(er=n)}(e)}function xr(e,t=[],r={},o){if(r.env=s(r.env),o.enableSharedBuildCache&&(r={...r,env:{...s(process.env),...re(),...r.env}}),"insecure_none"!==o.type){if(mr())return wr(e,t,r,o);const n=kr();throw new _r(`Sandbox policy '${o.type}' is not supported on this system. Ensure the sandbox helper binary is available, or use 'insecure_none'. Reason: ${n||"unknown"}`,n??void 0)}return function(e,t,r,o={spawn:n.spawn,spawnWorkload:Bt.D9}){return o.spawnWorkload(o.spawn,e,t,{...r,env:a(r.env??process.env),windowsHide:!0})}(e,t,r)}function Pr(e){return Cr?async function(e){const t=Gt.get(e);return t?(r=t.pid,n=t.startTime,o=t.unrelatedPids,new Promise((e=>{try{const t=new Date,s=["show","--style","ndjson","--predicate",'process=="kernel" AND eventMessage CONTAINS "Sandbox:" AND eventMessage contains "deny"',"--last",Math.ceil((t.getTime()-n.getTime())/1e3).toString()];(0,Bt.D9)(zt,"/usr/bin/log",s,((t,n)=>{if(t)return void e([{raw:t.message}]);const s=n.split(/\r?\n/).filter((e=>e.trim().length>0)),i=[];for(const e of s)try{const t=JSON.parse(e),n=t?.eventMessage??"";if(!n||"string"!=typeof n)continue;const s=/^Sandbox:\s+([^(]+)\((\d+)\)\s+([a-zA-Z-]+)\((\d+)\)\s+([^\s]+)\s+(.+)$/.exec(n);if(s){const[,e,a,c,l,u,d]=s,h=Number(a);i.push({timestamp:t.timestamp,processName:e.trim(),pid:h,decision:c.toLowerCase(),decisionCode:Number(l),operation:u,target:d,duplicateCount:1,raw:n,relationship:Vt(h,r,o)});continue}const a=/^(\d+) duplicate report for Sandbox: (.+)$/.exec(n);if(a){const e=Number(a[1]),s=a[2],c=/^([^(]+)\((\d+)\)\s+([a-zA-Z-]+)\((\d+)\)\s+([^\s]+)\s+(.+)$/.exec(s);if(c){const[,s,a,l,u,d,h]=c,p=Number(a);i.push({timestamp:t.timestamp,processName:s.trim(),pid:p,decision:l.toLowerCase(),decisionCode:Number(u),operation:d,target:h,duplicateCount:e,raw:n,relationship:Vt(p,r,o)})}else i.push({timestamp:t.timestamp,duplicateCount:e,raw:n});continue}i.push({timestamp:t.timestamp,raw:n})}catch{}e(i)}))}catch(t){e([{raw:String(t)}])}}))):(console.log("No sandbox metadata found on child process"),[]);var r,n,o}(e):Promise.resolve([])}function Rr(e,t){if(Cr)try{(0,g.accessSync)("/usr/bin/sandbox-exec",g.constants.X_OK)}catch{return!1}return mr(t?.ctx)}var Ir=r("node:stream"),Tr=r("../context/dist/otel.js"),Ar=r("../utils/dist/writable-iterable.js");const $r="--",Mr='builtin eval "$1" 3<&- 4>&-';var Dr=r("node:string_decoder");const Or=50,Fr=262144;class Nr{writable;pending=[];pendingBytes=0;flushTimeout;flushPromise;flushIntervalMs;maxBufferedBytes;constructor(e,t){this.writable=e,this.flushIntervalMs=t?.flushIntervalMs??Or,this.maxBufferedBytes=t?.maxBufferedBytes??Fr}async push(e,t){0!==t.length&&(this.pending.push({type:e,data:t}),this.pendingBytes+=t.length,this.pendingBytes>=this.maxBufferedBytes?await this.flush():this.scheduleFlush())}async flush(){if(this.clearFlushTimeout(),this.flushPromise)return await this.flushPromise,void(this.pendingBytes>0&&await this.flush());if(0===this.pendingBytes)return;const e=this.pending;this.pending=[],this.pendingBytes=0,this.flushPromise=this.writeBufferedOutput(e);try{await this.flushPromise}finally{this.flushPromise=void 0}}async close(){await this.flush()}scheduleFlush(){void 0===this.flushTimeout&&(this.flushTimeout=setTimeout((()=>{this.flushTimeout=void 0,this.flush()}),this.flushIntervalMs))}clearFlushTimeout(){void 0!==this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=void 0)}async writeBufferedOutput(e){for(const t of function(e){if(0===e.length)return[];const t=[];let r=e[0].type,n=[e[0].data];for(let o=1;o{e.writable.write({type:t,data:r}).catch((()=>{}))};return e.stdout?.on("data",(e=>{const n=t.note(e);void 0!==n&&n.length>0&&r("stdout",n)})),e.stderr?.on("data",(e=>{r("stderr",e)})),{get stdoutBytes(){return t.bytes},get stdoutPrefix(){return t.stdoutPrefix},async waitForOutput(){},async releaseHeldStdout(){const e=t.takeHeld();void 0!==e&&e.length>0&&r("stdout",e)},dropHeldStdout(){t.takeHeld()},async flush(){await this.releaseHeldStdout()}}}const r=new Nr(e.writable,e.outputLimiterOptions);let n;const o=Promise.all([jr(e.stdout,r,t),Ur(e.stderr,"stderr",r)]).then((()=>{})).catch((e=>{n=e}));return{get stdoutBytes(){return t.bytes},get stdoutPrefix(){return t.stdoutPrefix},async waitForOutput(){if(await o,void 0!==n)throw(e=n)instanceof Error?e:new Error(String(e));var e},async releaseHeldStdout(){const e=t.takeHeld();void 0!==e&&e.length>0&&await r.push("stdout",e)},dropHeldStdout(){t.takeHeld()},async flush(){await this.releaseHeldStdout(),await r.flush()}}}async function jr(e,t,r){if(e)for await(const n of e){const e=r.note(n);void 0!==e&&e.length>0&&await t.push("stdout",e)}}async function Ur(e,t,r,n){if(e)for await(const o of e)n?.(o),await r.push(t,o)}var Br;!function(e){e.Zsh="zsh",e.ZshLight="zsh-light",e.Bash="bash",e.PowerShell="powershell",e.Naive="naive"}(Br||(Br={}));const Wr={TERM:"dumb",NO_COLOR:"1",FORCE_COLOR:"0",_ZO_DOCTOR:"0"};function Hr(e){return"win32"===e.platform?"windows_tree":e.detached?"process_group":"single_process"}function qr(e,t,r,o={spawn:n.spawn,killPid:process.kill.bind(process)}){const s=e.pid;if(void 0===s)return;const i=()=>{try{e.kill(r)}catch{}};switch(t){case"process_group":try{o.killPid(-s,r)}catch{i()}return;case"windows_tree":try{o.spawn("taskkill",["/pid",String(s),"/t","/f"],{stdio:"ignore",windowsHide:!0}).on("error",i)}catch{i()}return;case"single_process":return void i();default:throw new Error(`Unknown process tree kill mode: ${String(t)}`)}}function zr(e,t=[],r={},n,o){const s=xr(e,t,{...r,env:I(r.env??process.env)},n);return o?Vr(s,{detached:!0===r.detached},o):Gr(s,!0===r.detached),s}function Gr(e,t){"single_process"!==Hr({platform:process.platform,detached:t})&&e.pid}function Vr(e,t,r){const n=Hr({platform:process.platform,detached:t.detached});Gr(e,t.detached);const o=()=>{if(!e.pid)return;qr(e,n,"SIGTERM");const t=setTimeout((()=>{!e.killed&&e.pid&&qr(e,n,"SIGKILL")}),1e3);"process_group"!==n&&e.once("exit",(()=>{clearTimeout(t)}))};r.aborted?o():(r.addEventListener("abort",o,{once:!0}),e.once("exit",(()=>{r.removeEventListener("abort",o)})))}function Kr(e,t,r){if(e){try{process.kill(-e,t)}catch{return}"SIGTERM"===t&&void 0!==r&&r>0&&setTimeout((()=>{try{process.kill(-e,"SIGKILL")}catch{}}),r)}}const Jr=new Set(["SIGTERM","SIGINT","SIGHUP","SIGQUIT","SIGKILL"]);function Zr(e,t,r){null!==t&&Jr.has(t)&&!r&&"win32"!==process.platform&&Kr(e,t)}function Xr(e,{shellName:t,closeGraceMs:r,timeoutMs:n}){const o=r??5e3,s=n??6e4;return new Promise((r=>{const n=[];let i;const a=e=>{n.push(e)},c=()=>{clearTimeout(d),o<=0||(i=setTimeout((()=>{console.warn(`[shell-exec] ${t} state init exited but its stdio did not close within ${o}ms; a startup file left a background process holding the output pipe. Proceeding with the dump received so far.`),u("exit_without_close")}),o))},l=()=>{u("closed")},u=t=>{clearTimeout(d),clearTimeout(i),e.off("exit",c),e.off("close",l),e.stdout?.off("data",a),e.stdout?.resume(),r({outcome:t,stdout:Buffer.concat(n).toString("utf8")})},d=s>0?setTimeout((()=>{console.warn(`[shell-exec] ${t} state init did not exit within ${s}ms; a startup file is blocking. Killing it and falling back to an empty state.`),qr(e,Hr({platform:process.platform,detached:!0}),"SIGKILL"),u("timed_out")}),s):void 0;e.stdout?.on("data",a),Qr(e.stdout),e.on("exit",c),e.on("close",l)}))}function Qr(e){e?.on("error",(()=>{}))}function Yr(e){e.removeAllListeners(),e.on("error",(()=>{})),e.stdout?.removeAllListeners("close"),e.stderr?.removeAllListeners("close");for(const t of e.stdio.slice(3))t?.destroy()}const en="IFS= builtin read -r -d '' __cursor_command <&5 2>/dev/null || { builtin printf '%s\\n' 'The command did not run: a shell startup file ($BASH_ENV or .zshenv) closed or replaced file descriptor 5, which carries the command. Run it again; this shell now passes commands as arguments.' >&2; builtin exit 126; }; exec 5<&-; builtin set -- \"$__cursor_command\"; builtin unset __cursor_command; ";function tn(e,t){return 126===e&&""===t}function rn(){return"win32"!==process.platform}function nn(e,t){const r=e.stdio.at(5);r instanceof Ir.Writable&&(Qr(r),r.end(`${t}\0`))}function on(e,t){e&&(Qr(e),e.write(t),e.end())}function sn(e,t){if(!e)return;Qr(e);const r=new Dr.StringDecoder("utf8");e.on("data",(e=>{const n=r.write(e);""!==n&&t(n)})),e.on("end",(()=>{const e=r.end();""!==e&&t(e)}))}function an(e){const t=e.indexOf("\n");return{cwd:Buffer.from(e.substring(0,t),"utf16le").toString("utf16le"),rest:e.substring(t)}}function cn(e,t){const r=t instanceof Error&&"code"in t&&"string"==typeof t.code?t.code:"unknown";console.warn(e,r)}function ln(e,t){const r=`${t}\n`,n=e.indexOf(r);return n>=0?e.slice(n+r.length):e}function un(e){return!1===e?.isLoginShellEnabled?"-ic":"-ilc"}function dn(e,t,r){const n=`${t}\n`;if(!e.startsWith(n))return;const o=e.indexOf(`\n${r}\n`,n.length-1);return o<0?void 0:e.slice(n.length,o+1)}const hn="__CURSOR_BASH_STATE_START__",pn="__CURSOR_BASH_STATE_END__",fn="\n Emit $PWD.Path\n #Log-Timing \"working_dir\"\n\n function ShouldPersistEnvVar {\n param([string]$Name)\n if ($Name -eq 'CURSOR_CONVERSATION_ID') {\n return $false\n }\n if ($Name -eq 'CURSOR_REQUEST_ID') {\n return $false\n }\n if ($Name -like 'CURSOR_AGENT_STORE*') {\n return $false\n }\n if ($Name -like '*CURSOR_SANDBOX*') {\n return $false\n }\n if ($Name -eq 'ELECTRON_RUN_AS_NODE') {\n return $false\n }\n return $true\n }\n\n $envVars = Get-ChildItem Env: | Sort-Object Name\n foreach ($var in $envVars) {\n if (-not (ShouldPersistEnvVar -Name $var.Name)) {\n continue\n }\n $encoded = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes([string]$var.Value))\n Emit ('Set-Item -LiteralPath ''Env:{0}'' -Value ([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String(''{1}'')))' -f $var.Name, $encoded)\n }\n #Log-Timing \"environment\"\n\n $aliases = Get-Alias | Sort-Object Name\n foreach ($alias in $aliases) {\n $definition = $alias.Definition\n\n if ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::ReadOnly) {\n }\n elseif ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::Constant) {\n }\n elseif ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::AllScope) {\n }\n else {\n Emit ('Set-Alias -Name \"{0}\" -Value \"{1}\"' -f $alias.Name, $definition)\n }\n }\n\n #Log-Timing \"finalize\"\n",mn=`\nfunction Dump-PowerShellState {\n param(\n [Parameter(Mandatory = $true)]\n [string]$OutputFile\n )\n\n function Emit {\n param([string]$Content)\n Add-Content -Path $OutputFile -Value $Content -Encoding UTF8\n }\n\n if (Test-Path $OutputFile) {\n Remove-Item $OutputFile -Force\n }\n New-Item -Path $OutputFile -ItemType File -Force | Out-Null\n #Log-Timing "file_init"\n${fn}}\n`,gn=`\nfunction Dump-PowerShellState {\n param(\n [Parameter(Mandatory = $true)]\n [string]$OutputFile,\n [string]$Trailer\n )\n\n $__cursorDumpText = New-Object System.Text.StringBuilder\n $__cursorDumpNewLine = [Environment]::NewLine\n function Emit {\n param([string]$Content)\n [void]$__cursorDumpText.Append($Content).Append($__cursorDumpNewLine)\n }\n${fn}\n if ($Trailer) {\n Emit $Trailer\n }\n [System.IO.File]::WriteAllText($OutputFile, $__cursorDumpText.ToString(), (New-Object System.Text.UTF8Encoding ($PSVersionTable.PSVersion.Major -lt 6)))\n}\n`,wn="# cursor-shell-timings ",yn="[long](([DateTime]::UtcNow.Ticks - 621355968000000000) / 10000)",vn="\ntry { [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\ntry { [Console]::InputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\ntry { $global:OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\n",bn=e=>e.map((e=>`'${e}'`)).join(", "),Sn=` # The body of the proxy for Set-Content and Export-Csv. Its param block comes from the\n # cmdlet itself. Every step of its own is guarded, so a failure in the proxy leaves the\n # file as the cmdlet writes it.\n $__cursorProxyBody = @'\nbegin {\n # The file system paths the call writes, each with its own 'bom' or 'nobom', and what each\n # held before the call; the call gets -Encoding only when every path has a decision.\n $__cursorFiles = $null\n $__cursorDecisions = @{}\n $__cursorBefore = @{}\n $__cursorDecided = $false\n # The command line asked for UTF8 by name, for files whose readers take it without a BOM.\n $__cursorAsked = $false\n $__cursorStrip = $false\n $__cursorStopped = $false\n $__cursorScopeBound = $null\n $__cursorInvoked = "$($MyInvocation.InvocationName)"\n # The first 8 KiB of the file and its length; $null for a file that does not exist.\n $__cursorHeadOf = {\n param([string]$__cursorFile)\n if (-not [System.IO.File]::Exists($__cursorFile)) { return $null }\n $__cursorHead = New-Object byte[] 8192\n $__cursorCount = 0\n $__cursorStream = [System.IO.File]::Open($__cursorFile, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite -bor [System.IO.FileShare]::Delete)\n try {\n $__cursorLength = $__cursorStream.Length\n while ($__cursorCount -lt $__cursorHead.Length) {\n $__cursorRead = $__cursorStream.Read($__cursorHead, $__cursorCount, $__cursorHead.Length - $__cursorCount)\n if ($__cursorRead -le 0) { break }\n $__cursorCount += $__cursorRead\n }\n } finally { $__cursorStream.Dispose() }\n return @{ Length = $__cursorLength; Head = $__cursorHead; Count = $__cursorCount }\n }\n # 'bom' or 'nobom' for a file the proxy writes in UTF-8, $null for one it leaves to the\n # cmdlet: the file's own bytes decide when it has content, its extension otherwise.\n $__cursorEncodingOf = {\n param([string]$__cursorFile, $__cursorWas)\n $__cursorExtension = [System.IO.Path]::GetExtension($__cursorFile).ToLowerInvariant()\n if ($__cursorExtension -in @(${bn([".bat",".cmd",".reg",".ini",".inf",".vbs",".vbe",".wsf"])})) { return $null }\n if ([System.IO.Directory]::Exists($__cursorFile)) { return $null }\n if ($null -ne $__cursorWas -and $__cursorWas.Count -gt 0) {\n $__cursorHead = $__cursorWas.Head\n $__cursorEnd = $__cursorWas.Count\n if ($__cursorEnd -ge 3 -and $__cursorHead[0] -eq 0xEF -and $__cursorHead[1] -eq 0xBB -and $__cursorHead[2] -eq 0xBF) { return 'bom' }\n if ($__cursorEnd -ge 2 -and (($__cursorHead[0] -eq 0xFF -and $__cursorHead[1] -eq 0xFE) -or ($__cursorHead[0] -eq 0xFE -and $__cursorHead[1] -eq 0xFF))) { return $null }\n if ($__cursorEnd -eq $__cursorHead.Length) {\n # A full header may end inside a character; that character is left out.\n $__cursorAt = $__cursorEnd - 1\n while ($__cursorAt -gt $__cursorEnd - 4 -and ($__cursorHead[$__cursorAt] -band 0xC0) -eq 0x80) { $__cursorAt-- }\n if ($__cursorHead[$__cursorAt] -ge 0xC0) {\n $__cursorNeed = if ($__cursorHead[$__cursorAt] -ge 0xF0) { 4 } elseif ($__cursorHead[$__cursorAt] -ge 0xE0) { 3 } else { 2 }\n if ($__cursorEnd - $__cursorAt -lt $__cursorNeed) { $__cursorEnd = $__cursorAt }\n }\n }\n # A strict decode throws on bytes that are not UTF-8; a character beyond ASCII takes\n # more bytes than code units, so all-ASCII content is the one that decodes to as many.\n try { $__cursorText = [System.Text.UTF8Encoding]::new($false, $true).GetString($__cursorHead, 0, $__cursorEnd) } catch { return $null }\n if ($__cursorText.Length -lt $__cursorEnd) { return 'nobom' }\n }\n if ($__cursorExtension -in @(${bn([".ps1",".psm1",".psd1"])})) { return 'bom' }\n if ($__cursorExtension -in @(${bn([".py",".pyw",".pyi",".js",".mjs",".cjs",".jsx",".ts",".tsx",".mts",".cts",".go",".rs",".kt",".kts",".scala",".swift",".dart",".rb",".cs",".fs",".fsx",".vb",".razor",".cshtml",".sh",".bash",".zsh",".html",".htm",".css",".scss",".sass",".less",".vue",".svelte",".json",".jsonc",".json5",".yaml",".yml",".toml",".xml",".xsd",".xsl",".xslt",".svg",".csproj",".props",".targets",".graphql",".gql",".proto",".tf",".hcl",".md",".markdown",".mdx",".rst",".adoc",".gitignore",".gitattributes",".gitmodules",".editorconfig",".cursorignore",".cursorindexingignore",".mdc"])})) { return 'nobom' }\n return $null\n }\n # Whether the -Encoding the call bound is the UTF-8 with a BOM that Windows PowerShell names\n # UTF8. PowerShell 7 binds the encoding object of that name, and reaches this only when a\n # test fakes the version.\n $__cursorIsUtf8Bom = {\n param($__cursorEncoding)\n if ($__cursorEncoding -is [System.Text.Encoding]) { return ($__cursorEncoding -is [System.Text.UTF8Encoding] -and $__cursorEncoding.GetPreamble().Length -gt 0) }\n return ("$__cursorEncoding" -eq 'UTF8')\n }\n # Whether a default under $PSDefaultParameterValues can reach this call's -Encoding: under\n # the cmdlet's name, an alias it had when the proxy was built, or the name the call used. A\n # value such a default put in $PSBoundParameters is not one the command line asked for.\n $__cursorHasEncodingDefault = {\n param([string]$__cursorInvoked)\n foreach ($__cursorKey in @($PSDefaultParameterValues.Keys)) {\n $__cursorKeyParts = "$__cursorKey" -split ':', 2\n if ($__cursorKeyParts.Count -ne 2 -or 'Encoding' -notlike $__cursorKeyParts[1].Trim()) { continue }\n foreach ($__cursorName in @(__CURSORNAMES__, $__cursorInvoked)) {\n if ($__cursorName -like $__cursorKeyParts[0].Trim()) { return $true }\n }\n }\n return $false\n }\n # Whether a UTF8 asked for by name is UTF-8 without a BOM for this file: one whose reader\n # rejects a BOM, and that is new, empty or starts with no BOM of any encoding.\n $__cursorTakesNoBom = {\n param([string]$__cursorFile, $__cursorWas)\n if ([System.IO.Directory]::Exists($__cursorFile)) { return $false }\n if ([System.IO.Path]::GetExtension($__cursorFile).ToLowerInvariant() -notin @(${bn([".json",".py",".js",".ts",".sh",".yaml",".toml",".mdc"])}) -and\n [System.IO.Path]::GetFileName($__cursorFile).ToLowerInvariant() -notin @(${bn([".gitignore",".editorconfig"])})) { return $false }\n if ($null -eq $__cursorWas -or $__cursorWas.Count -lt 2) { return $true }\n $__cursorHead = $__cursorWas.Head\n if ($__cursorWas.Count -ge 3 -and $__cursorHead[0] -eq 0xEF -and $__cursorHead[1] -eq 0xBB -and $__cursorHead[2] -eq 0xBF) { return $false }\n if (($__cursorHead[0] -eq 0xFF -and $__cursorHead[1] -eq 0xFE) -or ($__cursorHead[0] -eq 0xFE -and $__cursorHead[1] -eq 0xFF)) { return $false }\n if ($__cursorWas.Count -ge 4 -and $__cursorHead[0] -eq 0 -and $__cursorHead[1] -eq 0 -and $__cursorHead[2] -eq 0xFE -and $__cursorHead[3] -eq 0xFF) { return $false }\n return $true\n }\n # Takes a UTF-8 BOM off the front of the file in place, unless it is to stay and the\n # content has a character beyond ASCII. A file the cmdlet left as it was is not touched.\n $__cursorStripBom = {\n param([string]$__cursorFile, [bool]$__cursorKeepUnlessAscii, $__cursorWas)\n if (-not [System.IO.File]::Exists($__cursorFile)) { return }\n $__cursorStream = $null\n # The cmdlet may still hold the file for a moment after it returns.\n for ($__cursorAttempt = 0; $__cursorAttempt -lt 5 -and $null -eq $__cursorStream; $__cursorAttempt++) {\n try { $__cursorStream = [System.IO.File]::Open($__cursorFile, [System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None) }\n catch [System.IO.FileNotFoundException] { return }\n catch [System.IO.DirectoryNotFoundException] { return }\n catch [System.IO.IOException] { Start-Sleep -Milliseconds 20 }\n catch { return }\n }\n if ($null -eq $__cursorStream) { return }\n try {\n $__cursorBuffer = New-Object byte[] 65536\n if ($null -ne $__cursorWas -and $__cursorWas.Length -eq $__cursorStream.Length) {\n $__cursorCount = 0\n while ($__cursorCount -lt $__cursorWas.Count) {\n $__cursorRead = $__cursorStream.Read($__cursorBuffer, $__cursorCount, $__cursorWas.Count - $__cursorCount)\n if ($__cursorRead -le 0) { break }\n $__cursorCount += $__cursorRead\n }\n if ($__cursorCount -eq $__cursorWas.Count -and [System.Convert]::ToBase64String($__cursorBuffer, 0, $__cursorCount) -eq [System.Convert]::ToBase64String($__cursorWas.Head, 0, $__cursorCount)) { return }\n $__cursorStream.Position = 0\n }\n if ($__cursorStream.Read($__cursorBuffer, 0, 3) -ne 3 -or $__cursorBuffer[0] -ne 0xEF -or $__cursorBuffer[1] -ne 0xBB -or $__cursorBuffer[2] -ne 0xBF) { return }\n if ($__cursorKeepUnlessAscii) {\n while (($__cursorRead = $__cursorStream.Read($__cursorBuffer, 0, $__cursorBuffer.Length)) -gt 0) {\n if ([regex]::IsMatch([System.Text.Encoding]::UTF8.GetString($__cursorBuffer, 0, $__cursorRead), '[^\\x00-\\x7F]')) { return }\n }\n }\n $__cursorReadAt = 3L\n $__cursorWriteAt = 0L\n while ($__cursorReadAt -lt $__cursorStream.Length) {\n $__cursorStream.Position = $__cursorReadAt\n $__cursorRead = $__cursorStream.Read($__cursorBuffer, 0, $__cursorBuffer.Length)\n if ($__cursorRead -le 0) { break }\n $__cursorStream.Position = $__cursorWriteAt\n $__cursorStream.Write($__cursorBuffer, 0, $__cursorRead)\n $__cursorReadAt += $__cursorRead\n $__cursorWriteAt += $__cursorRead\n }\n $__cursorStream.SetLength($__cursorWriteAt)\n } catch { } finally { $__cursorStream.Dispose() }\n }\n try {\n $__cursorBound = $null\n if ($PSBoundParameters.ContainsKey('Path')) { $__cursorBound = @{ Path = $PSBoundParameters['Path'] } }\n elseif ($PSBoundParameters.ContainsKey('LiteralPath')) { $__cursorBound = @{ LiteralPath = $PSBoundParameters['LiteralPath'] } }\n if ($null -ne $__cursorBound) {\n # The file system paths that -Path or -LiteralPath names; none when one is on another\n # provider or a wildcard matches nothing.\n $__cursorLiteral = $__cursorBound.ContainsKey('LiteralPath')\n $__cursorFiles = New-Object System.Collections.Generic.List[string]\n foreach ($__cursorPath in @(@($__cursorBound.Values)[0])) {\n $__cursorProvider = $null\n $__cursorDrive = $null\n if ($__cursorLiteral -or -not [System.Management.Automation.WildcardPattern]::ContainsWildcardCharacters("$__cursorPath")) {\n $__cursorResolved = @($ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath("$__cursorPath", [ref]$__cursorProvider, [ref]$__cursorDrive))\n } else {\n $__cursorResolved = @($ExecutionContext.SessionState.Path.GetResolvedProviderPathFromPSPath("$__cursorPath", [ref]$__cursorProvider))\n }\n if ($null -ne $__cursorProvider -and $__cursorProvider.Name -in @('Variable', 'Function', 'Alias')) { $__cursorScopeBound = $__cursorProvider.Name }\n if ($null -eq $__cursorProvider -or $__cursorProvider.Name -ne 'FileSystem' -or $__cursorResolved.Count -eq 0) { $__cursorFiles = $null; break }\n $__cursorFiles.AddRange([string[]]$__cursorResolved)\n }\n }\n # -WhatIf sets $WhatIfPreference and -Confirm sets $ConfirmPreference in this scope.\n if ($null -ne $__cursorFiles -and $__cursorFiles.Count -gt 0 -and -not $PSBoundParameters.ContainsKey('Encoding') -and\n -not $WhatIfPreference -and $ConfirmPreference -notin @('Low', 'Medium') -and -not $PSBoundParameters.ContainsKey('Stream') -and\n -not $PSBoundParameters.ContainsKey('Filter') -and -not $PSBoundParameters.ContainsKey('Include') -and\n -not $PSBoundParameters.ContainsKey('Exclude')) {\n $__cursorAppend = ($PSBoundParameters.ContainsKey('Append') -and $PSBoundParameters['Append']) -or ($PSBoundParameters.ContainsKey('NoClobber') -and $PSBoundParameters['NoClobber'])\n $__cursorDecided = $true\n $__cursorStrip = $true\n foreach ($__cursorFile in $__cursorFiles) {\n $__cursorBefore[$__cursorFile] = & $__cursorHeadOf $__cursorFile\n $__cursorDecisions[$__cursorFile] = & $__cursorEncodingOf $__cursorFile $__cursorBefore[$__cursorFile]\n if ($null -eq $__cursorDecisions[$__cursorFile]) { $__cursorDecided = $false; break }\n # An append onto a file with content writes no BOM, so there is none to take off.\n if ($__cursorAppend -and $null -ne $__cursorBefore[$__cursorFile] -and $__cursorBefore[$__cursorFile].Length -gt 0) { $__cursorStrip = $false }\n }\n }\n elseif ($null -ne $__cursorFiles -and $__cursorFiles.Count -gt 0 -and $PSBoundParameters.ContainsKey('Encoding') -and\n (& $__cursorIsUtf8Bom $PSBoundParameters['Encoding']) -and -not (& $__cursorHasEncodingDefault $__cursorInvoked) -and\n -not $WhatIfPreference -and $ConfirmPreference -notin @('Low', 'Medium') -and -not $PSBoundParameters.ContainsKey('Stream') -and\n -not $PSBoundParameters.ContainsKey('Filter') -and -not $PSBoundParameters.ContainsKey('Include') -and\n -not $PSBoundParameters.ContainsKey('Exclude')) {\n # The UTF8 the command line asked for is UTF-8 with a BOM on this shell and without\n # one on PowerShell 7. For a file whose reader rejects a BOM, and that has none, it\n # means what it means there: the cmdlet writes its BOM, and the proxy takes it off.\n $__cursorAsked = $true\n foreach ($__cursorFile in $__cursorFiles) {\n $__cursorBefore[$__cursorFile] = & $__cursorHeadOf $__cursorFile\n if (-not (& $__cursorTakesNoBom $__cursorFile $__cursorBefore[$__cursorFile])) { $__cursorAsked = $false; break }\n $__cursorDecisions[$__cursorFile] = 'nobom'\n }\n $__cursorStrip = $__cursorAsked\n }\n } catch { $__cursorDecided = $false; $__cursorAsked = $false }\n if ($__cursorDecided) { $PSBoundParameters['Encoding'] = '__CURSORUTF8__' }\n if ($null -ne $__cursorScopeBound) {\n Write-Warning "__CURSORNAME__ runs through a function in this shell, so an item it writes to the $__cursorScopeBound provider lives in a scope that ends with the call. Use an assignment, a function definition or Set-Alias instead."\n }\n # An error the caller asked to stop on ends the caller too, as it does from the cmdlet: it\n # goes on as it is, as from the proxy PowerShell itself generates, which rethrows everything\n # with 'throw'. Any other terminating error of the cmdlet ends the statement and the caller\n # goes on; ThrowTerminatingError keeps that rule, where 'throw' would end the caller's whole\n # script, and the pipeline it ended is not stepped again. Of the two, only the cmdlet's own\n # terminating error names this function rather than the cmdlet's type in the suffix of its\n # FullyQualifiedErrorId; the record of an error the caller asked to stop on is the cmdlet's.\n try {\n $outBuffer = $null\n if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 }\n $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('__CURSORTARGET__', [System.Management.Automation.CommandTypes]::Cmdlet)\n $scriptCmd = { & $wrappedCmd @PSBoundParameters }\n $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)\n $steppablePipeline.Begin($PSCmdlet)\n } catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n}\nprocess {\n if ($__cursorStopped) { return }\n try { $steppablePipeline.Process($_) }\n catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n}\nend {\n if ($__cursorStopped) { return }\n try { $steppablePipeline.End() }\n catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n if (-not $__cursorStrip -or -not ($__cursorDecided -or $__cursorAsked)) { return }\n try {\n foreach ($__cursorFile in $__cursorFiles) { & $__cursorStripBom $__cursorFile ($__cursorDecisions[$__cursorFile] -eq 'bom') $__cursorBefore[$__cursorFile] }\n } catch { }\n}\n'@\n foreach ($__cursorWriter in @('Set-Content', 'Export-Csv')) {\n $__cursorWriterNames = @($__cursorWriter) + @(Get-Alias -Definition $__cursorWriter -ErrorAction Ignore | ForEach-Object { $_.Name })\n $__cursorHasWriterDefault = $false\n foreach ($__cursorKey in @($PSDefaultParameterValues.Keys)) {\n $__cursorKeyParts = "$__cursorKey" -split ':', 2\n if ($__cursorKeyParts.Count -ne 2 -or 'Encoding' -notlike $__cursorKeyParts[1].Trim()) { continue }\n foreach ($__cursorName in $__cursorWriterNames) {\n if ($__cursorName -like $__cursorKeyParts[0].Trim()) { $__cursorHasWriterDefault = $true }\n }\n }\n if ($__cursorHasWriterDefault) { continue }\n try {\n # A function of this name that a profile defined stays in charge; the proxy is built on the cmdlet alone.\n $__cursorCmdlet = @(Microsoft.PowerShell.Core\\Get-Command -Name $__cursorWriter -ErrorAction Stop)[0]\n if ($__cursorCmdlet.CommandType -eq 'Cmdlet') {\n $__cursorTarget = "$($__cursorCmdlet.ModuleName)\\$($__cursorCmdlet.Name)"\n $__cursorMetadata = New-Object System.Management.Automation.CommandMetadata $__cursorCmdlet\n $__cursorNamesList = @($__cursorWriterNames | ForEach-Object { "'" + $_.Replace("'", "''") + "'" }) -join ', '\n $__cursorProxyText = @(\n '<#', ".ForwardHelpTargetName $__cursorTarget", '.ForwardHelpCategory Cmdlet', '#>',\n [System.Management.Automation.ProxyCommand]::GetCmdletBindingAttribute($__cursorMetadata),\n 'param(', [System.Management.Automation.ProxyCommand]::GetParamBlock($__cursorMetadata), ')',\n 'dynamicparam {', [System.Management.Automation.ProxyCommand]::GetDynamicParam($__cursorMetadata), '}',\n $__cursorProxyBody.Replace('__CURSORTARGET__', $__cursorTarget).Replace('__CURSORNAMES__', $__cursorNamesList).Replace('__CURSORNAME__', $__cursorCmdlet.Name).Replace('__CURSORUTF8__', $__cursorUtf8)\n ) -join [Environment]::NewLine\n # Global, as a profile would define it, so that a module's code reaches it too.\n Microsoft.PowerShell.Management\\Set-Item -LiteralPath "function:global:$__cursorWriter" -Value ([scriptblock]::Create($__cursorProxyText)) -ErrorAction Stop\n }\n } catch { }\n }`,kn=String.raw` -+exports.id=977,exports.ids=[977],exports.modules={"./src/agent/local-executor.ts"(e,t,r){"use strict";r.d(t,{createLocalExecutor:()=>IH});var n=r("node:buffer"),o=r("node:os"),s=r("node:path"),i=r.t(s,2),a=r.n(s),c=r("../proto/dist/generated/agent/v1/agent_pb.js");const l={textDelta:(e,t)=>new c.Uq({messageStartedAtMs:t,message:{case:"textDelta",value:new c.PtE({text:e})}}),toolCallStarted:(e,t,r)=>new c.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"toolCallStarted",value:new c.xuG({callId:e,toolCall:t,modelCallId:r})}}),toolCallCompleted:(e,t,r)=>new c.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"toolCallCompleted",value:new c.LLS({callId:e,toolCall:t,modelCallId:r})}}),toolCallDelta:(e,t,r,n)=>new c.Uq({messageStartedAtMs:n,message:{case:"toolCallDelta",value:new c.I0n({callId:e,toolCallDelta:t,modelCallId:r})}}),thinkingDelta:(e,t,r)=>new c.Uq({messageStartedAtMs:r,message:{case:"thinkingDelta",value:new c.cHB({text:e,thinkingStyle:t})}}),thinkingCompleted:(e,t,r)=>new c.Uq({messageStartedAtMs:t,message:{case:"thinkingCompleted",value:new c.tr3({thinkingDurationMs:e,...!0===r?{narration:!0}:{}})}}),thinkingNote:e=>new c.Uq({message:{case:"thinkingNote",value:new c.Y$k({text:e})}}),taskChild:(e,t,r)=>"thinkingNote"===t.message.case?t:l.toolCallDelta(e,new c.V1v({delta:{case:"taskToolCallDelta",value:new c.aon({interactionUpdate:t})}}),r),userMessageAppended:e=>new c.Uq({messageStartedAtMs:e.startedAtMs,message:{case:"userMessageAppended",value:new c.v$T({userMessage:e})}}),partialToolCall:(e,t,r)=>new c.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"partialToolCall",value:new c.fxF({callId:e,toolCall:t,modelCallId:r})}}),tokenDelta:e=>new c.Uq({message:{case:"tokenDelta",value:new c.Fyz({tokens:e})}}),summary:e=>new c.Uq({message:{case:"summary",value:new c.ECk({summary:e})}}),summaryStarted:()=>new c.Uq({message:{case:"summaryStarted",value:new c.lWT}}),heartbeat:()=>new c.Uq({message:{case:"heartbeat",value:new c.ih1}}),summaryCompleted:(e,t,r)=>new c.Uq({message:{case:"summaryCompleted",value:new c.ZM9({hookMessage:e,failed:t,fallback:r})}}),shellOutputDelta:e=>new c.Uq({message:{case:"shellOutputDelta",value:new c.Nn_({event:e})}}),modelCallCompleted:(e,t)=>new c.Uq({message:{case:"modelCallCompleted",value:new c.c2D({modelCallId:e,inputTokens:BigInt(t.inputTokens),outputTokens:BigInt(t.outputTokens),cacheReadTokens:BigInt(t.cacheReadTokens),cacheWriteTokens:BigInt(t.cacheWriteTokens),...void 0!==t.reasoningTokens?{reasoningTokens:BigInt(t.reasoningTokens)}:{}})}}),turnEnded(e,t){const r=e?.catalogCostCents;return new c.Uq({message:{case:"turnEnded",value:new c.lJj({...e?{inputTokens:BigInt(e.inputTokens),outputTokens:BigInt(e.outputTokens),cacheReadTokens:BigInt(e.cacheReadTokens),cacheWriteTokens:BigInt(e.cacheWriteTokens),reasoningTokens:BigInt(e.reasoningTokens??0)}:{},...void 0!==t?{endedAtMs:t}:{},...void 0!==r&&Number.isFinite(r)?{estimatedCost:new c.QVp({rawCostCents:r,chargedCents:r,source:c.nnk.CATALOG})}:{}})}})},stepStarted:e=>new c.Uq({message:{case:"stepStarted",value:new c.dwJ({stepId:BigInt(e)})}}),toolRequestsListed:e=>new c.Uq({message:{case:"toolRequestsListed",value:new c.BU$({callCount:Math.max(0,e)})}}),voiceCallUtterance:e=>new c.Uq({message:{case:"voiceCallUtterance",value:e}}),stepCompleted:(e,t)=>new c.Uq({message:{case:"stepCompleted",value:new c.Lrv({stepId:BigInt(e),stepDurationMs:BigInt(t)})}}),activeBranchChange:(e,t)=>new c.Uq({message:{case:"activeBranchChange",value:new c.PSN({path:e,branchName:t})}}),feedbackRequest:(e,t,r,n=[],o={})=>new c.Uq({message:{case:"feedbackRequest",value:new c.apn({requestId:e,canonicalModelName:t,categories:[...r],categoryGroups:[...n],title:o.title,negativeTitle:o.negativeTitle,commentPlaceholder:o.commentPlaceholder})}})};class u{constructor(e=0){this.nextId=e}next(){return this.nextId++}peekNext(){return this.nextId}observe(e){Number.isSafeInteger(e)&&e>=this.nextId&&(this.nextId=e+1)}}var d=r("../context/dist/logger.js"),h=r("../metrics/dist/index.js"),p=r("../proto/dist/generated/agent/v1/exec_pb.js"),f=r("../utils/dist/writable-iterable.js");const m=/https?:\/\/\S+/gi,g=/[)"'<>,.;:\]}]$/;function w(e){const{url:t,wrappers:r}=function(e){let t=e.length;for(;t>0&&g.test(e.slice(t-1,t));)t-=1;return{url:e.slice(0,t),wrappers:e.slice(t)}}(e),n=t.search(/[?#]/),o=-1===n?t:t.slice(0,n),s=o.indexOf("//")+2,i=o.slice(s).search(/[/?#]/),a=-1===i?o.length:s+i,c=o.lastIndexOf("@",a-1);return c0&&o.push(`gitErrorCode=${n.gitErrorCode}`),"number"==typeof n.exitCode&&Number.isFinite(n.exitCode)&&o.push(`exitCode=${n.exitCode}`),0===o.length)return e;let s=`${e} [git: ${o.join(" ")}]`;var i,a;return!0===r?.includeStderr&&"string"==typeof n.stderr&&n.stderr.length>0&&(s+=`\n--- git stderr ---\n${a=n.stderr,i=a.replace(m,w),i.length<=2048?i:`${i.slice(0,2048)}… [truncated to 2048 chars]`}`),s}var b=r("../context/dist/core.js");const S=(0,b.cF)(Symbol("machineProfile"),void 0),k=(0,d.h)("SimpleControlledExecManager"),_=(0,h.v5)("agent_exec.controlled.exec.duration_ms",{description:"Duration of controlled exec operations in milliseconds",labelNames:["exec_case"]}),C=(0,h.v5)("agent_exec.controlled.exec.machine_duration_ms",{description:"Duration of grep, shell and hook execs by coarse machine profile",labelNames:["exec_case","cpu_cores","ram_gb","defender_rt"]}),E=new Set(["grepArgs","shellStreamArgs","executeHookArgs"]),x=(0,h.Pu)("agent_exec.controlled.exec.success",{description:"Count of successful controlled exec operations",labelNames:["exec_case"]}),P=(0,h.Pu)("agent_exec.controlled.exec.error",{description:"Count of failed controlled exec operations",labelNames:["exec_case"]}),R={computerUseArgs:"Computer use is not enabled for this environment, so the Computer tool and the computerUse subagent cannot run here. Do not retry computer actions; verify with non-GUI methods (automated tests, shell commands) instead. (No computer-use handler is registered on this exec daemon.)",recordScreenArgs:"Screen recording is not enabled for this environment, so recordings cannot be captured here. Do not retry; skip the recording and present other evidence instead. (No record-screen handler is registered on this exec daemon.)"};class I extends Error{constructor(e){super(e),this.name="ControlledExecDisposedError"}}function T(e){return e instanceof I?"EXEC_BACKEND_UNAVAILABLE":e instanceof Error&&"AgentExecStreamStartTimeoutError"===e.name?"AGENT_EXEC_STREAM_START_TIMEOUT":void 0}class A{constructor(e,t,r){this.exec=e,this.deserializeArgs=t,this.serializeResult=r}handle(e,t){const r=this.deserializeArgs(t);if(void 0===r)return;const{id:n,args:o}=r;return async function*(r){const s=performance.now(),i=[],a=await r.exec.execute(e,o,{execId:t.execId,hookContextCollector:i,deliverAgentStoreConflictNotices:!0===t.acceptHookAdditionalContexts,recordAgentView:!0===t.recordAgentView,refuseUnreadChanges:!0===t.refuseUnreadChanges}),c=r.serializeResult(n,a);c.localExecutionTimeMs=Math.round(Math.max(0,performance.now()-s)),i.length>0&&(c.hookAdditionalContexts=i),yield c}(this)}}class ${constructor(e,t,r){this.exec=e,this.deserializeArgs=t,this.serializeStream=r}handle(e,t){const r=this.deserializeArgs(t);if(void 0===r)return;const{id:n,args:o}=r;return async function*(r){const s=performance.now(),i=[],a=r.exec.execute(e,o,{execId:t.execId,hookContextCollector:i,deliverAgentStoreConflictNotices:!0===t.acceptHookAdditionalContexts});try{for await(const e of a){{const __t3h=globalThis[Symbol.for("@cursor/sdk.shellStreamOutput")];const __t3c=e.event?.case;if(typeof __t3h==="function"&&(__t3c==="stdout"||__t3c==="stderr"))try{__t3h({conversationId:o.conversationId,toolCallId:o.toolCallId,event:{case:__t3c,value:{data:e.event.value.data}}})}catch{}}const t=r.serializeStream(n,e);t.localExecutionTimeMs=Math.round(Math.max(0,performance.now()-s)),yield t}}finally{const e=i.filter((e=>"agentStoreConflict"===e.hookEventName));e.length>0&&(yield new p.yT({id:n,hookAdditionalContexts:e}))}}(this)}}class M{constructor(e){this.handlers=[],this.runningExecs=new Map;const t=e?.includeGitStderrInThrows??!1;this.includeGitStderrInThrows="function"==typeof t?t:()=>t,this.observeResults=e?.observeResults}startResultObserver(e,t,r){if(void 0!==this.observeResults)try{return this.observeResults(e,t,r)}catch{return}}register(e){this.handlers.push(e)}handleControlMessage(e){if("abort"===e.message.case){const t=e.message.value.id,r=this.runningExecs.get(t);r&&r()}}handle(e,t){const[r,n]=e.withCancel();this.runningExecs.set(t.id,n);const o=t.message.case??"unknown";for(const e of this.handlers){const s=e.handle(r,t);if(void 0===s)continue;const i=s,a=(0,f.Jt)();let c;const l=()=>{c=setTimeout((()=>{a.write(new p.$Y({message:{case:"heartbeat",value:new p.VA({id:t.id})}})).then(l).catch((()=>{}))}),3e3)};l();const u=performance.now(),d=this.startResultObserver(r,o,t);return(async()=>{try{for await(const e of i){if(void 0!==d&&e instanceof p.yT)try{d.message(e)}catch{}await a.write(e)}await a.write(new p.$Y({message:{case:"streamClose",value:new p.D9({id:t.id})}})),x.increment(r,1,{exec_case:o})}catch(e){if(e instanceof f.W2)return;P.increment(r,1,{exec_case:o}),await a.write(new p.$Y({message:{case:"throw",value:new p.Fu({id:t.id,error:e instanceof Error?v(e.message,e,{includeStderr:this.includeGitStderrInThrows()}):"Unknown error",stackTrace:e instanceof Error?e.stack:void 0,errorCode:T(e)})}}))}finally{if(void 0!==d)try{d.done()}catch{}const e=performance.now()-u;if(_.histogram(r,e,{exec_case:o}),E.has(o)){const t=r.get(S)?.();void 0!==t&&C.histogram(r,e,{exec_case:o,...t})}clearTimeout(c),a.close(),this.runningExecs.delete(t.id),n()}})(),a}this.runningExecs.delete(t.id),n();const s=t.message.case,i=(void 0===s?void 0:R[s])??`No handler found for server message of type ${s}`;return k.error(e,i,{messageCase:s}),P.increment(e,1,{exec_case:o}),async function*(){yield new p.$Y({message:{case:"throw",value:new p.Fu({id:t.id,error:i})}}),yield new p.$Y({message:{case:"streamClose",value:new p.D9({id:t.id})}})}()}static fromResources(e,t){const r=new M(t);for(const[t,n]of e.entries())t.registerControlledImplementation(n,r);return r}}var D=r("../context/dist/otel.js");async function O(e){const t=e[Symbol.asyncIterator](),r=await t.next();if(r.done)return;const n={async*[Symbol.asyncIterator](){for(;;){const e=await t.next();if(e.done)return;yield e.value}}};return{firstItem:r.value,rest:n}}const F=(0,b.cF)(Symbol("agentExec.remoteExecResultObserverFactory"),void 0),N={message(){},[Symbol.dispose](){}};function L(e){const t=e.get(F);if(void 0===t)return N;let r;try{r=t(e)}catch{return N}return void 0===r?N:{message(e){try{r?.message(e)}catch{r=void 0}},[Symbol.dispose](){const e=r;r=void 0;try{e?.end()}catch{}}}}var j=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},U=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const B=(0,d.h)("ExecutorResource"),W=(0,h.Pu)("agent_exec.hook_additional_context.delivered",{description:"Hook additional_context carriers drained into the caller collector",labelNames:["hook_event_name"]});class H{constructor(e,t,r){this.execManager=e,this.serializeArgs=t,this.deserializeResult=r}async execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=j(n,(0,D.VI)(e.withName("ExecutorResource.execute")),!1),s=o.ctx;void 0!==r?.execId&&o.span.setAttribute("exec.id",r.execId);const i=(0,D.mJ)(s),a=i?new p.Kg(i):void 0,c=this.execManager.createExecInstance(s,(e=>{const n=this.serializeArgs(e,t);return new p.Ye({id:n.id,message:n.message,execId:r?.execId,machineId:r?.machineId,spanContext:a,acceptHookAdditionalContexts:void 0!==r?.hookContextCollector,recordAgentView:r?.recordAgentView,refuseUnreadChanges:r?.refuseUnreadChanges})})),l=await O(c);if(void 0===l)throw new Error("No exec result");let{firstItem:u,rest:d}=l;const h=j(n,L(s),!1),f=e=>{if(h.message(e),void 0!==r?.hookContextCollector&&e.hookAdditionalContexts.length>0){r.hookContextCollector.push(...e.hookAdditionalContexts);for(const t of e.hookAdditionalContexts)W.increment(s,1,{hook_event_name:t.hookEventName})}};f(u);let m=this.deserializeResult(u);for(;void 0===m;){const e=await O(d);if(void 0===e)throw new Error("No result value");u=e.firstItem,d=e.rest,f(u),m=this.deserializeResult(u)}return(async()=>{try{for await(const e of d)f(e)}catch(e){B.info(s,"Ignoring exec stream shutdown during detached drain",{error:e})}})().catch((()=>{})),m}catch(e){n.error=e,n.hasError=!0}finally{U(n)}}}class q{constructor(e,t,r){this.execManager=e,this.serializeArgs=t,this.deserializeStream=r}async*execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=j(n,(0,D.VI)(e.withName("StreamExecutorResource.execute")),!1).ctx,s=(0,D.mJ)(o),i=s?new p.Kg(s):void 0,a=this.execManager.createExecInstance(o,(e=>{const n=this.serializeArgs(e,t);return new p.Ye({id:n.id,message:n.message,execId:r?.execId,machineId:r?.machineId,spanContext:i,acceptHookAdditionalContexts:void 0!==r?.hookContextCollector||!0===r?.deliverAgentStoreConflictNotices})})),c=j(n,L(o),!1);for await(const e of a){c.message(e),void 0!==r?.hookContextCollector&&e.hookAdditionalContexts.length>0&&r.hookContextCollector.push(...e.hookAdditionalContexts);const t=this.deserializeStream(e);void 0!==t&&(yield t)}}catch(e){n.error=e,n.hasError=!0}finally{U(n)}}}function z(e){return Symbol.for(`@anysphere/agent-exec/resource/${e}`)}function G(e,t,r){return{name:e,symbol:z(e),remoteImplementation:t,registerControlledImplementation:r}}class V{constructor(e,t){this.resource=e,this.value=t}}function K(e,t){return[e,t]}function J(e,t){return t}class Z{constructor(){this.resources=new Map}register(e,t){this.resources.set(e.symbol,new V(e,t))}get(e){return J(0,this.resources.get(e.symbol)?.value)}entries(){return Array.from(this.resources.values()).map((e=>[e.resource,e.value]))}}class X{constructor(e,t){this.remoteAccessor=e,this.localResources=new Map;for(const[e,r]of t)this.localResources.set(e.symbol,{resource:e,implementation:r})}get(e){const t=this.localResources.get(e.symbol);return t?J(0,t.implementation):this.remoteAccessor.get(e)}*entries(){for(const{resource:e,implementation:t}of this.localResources.values())yield[e,t];for(const e of this.remoteAccessor.entries())this.localResources.has(e[0].symbol)||(yield e)}}function Q(e){return function(t,r){return new p.Ye({id:t,message:{case:e,value:r}})}}function Y(e){return t=>{if(t.message.case===e)return t.message.value}}function ee(e){return function(t,r){const n={case:e,value:r};return new p.yT({id:t,message:n})}}function te(e){return function(t){if(t.message.case===e)return{id:t.id,args:t.message.value}}}const re=G("shell-stream-executor",(e=>new q(e,Q("shellStreamArgs"),Y("shellStream"))),((e,t)=>{t.register(new $(e,te("shellStreamArgs"),ee("shellStream")))}));var ne=r("../proto/dist/generated/agent/v1/kv_pb.js"),oe=r("../agent-kv/dist/blob-store.js"),se=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const ie=(0,d.h)("ControlledKvManager");function ae(e,t,r){return e?(0,D.F)({traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags??1},t,r):r}function ce(e,t,r,n,o){o<=r||(0,D.xd)(e.withName(`${t}.slow`),{startTime:n,attributes:{durationMs:o,slowThresholdMs:r}},n+o)}const le=(0,h.v5)("agent_kv.controlled.get_blob.duration_ms",{description:"Duration of ControlledKvManager getBlob operations in milliseconds"}),ue=(0,h.v5)("agent_kv.controlled.set_blob.duration_ms",{description:"Duration of ControlledKvManager setBlob operations in milliseconds"});class de{constructor(e,t,r,n={}){this.serverStream=e,this.clientStream=t,this.blobStore=r,this.options=n}async run(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,D.VI)(e.withName("ControlledKvManager.run")),!1).ctx,n=new Set,o=e=>{n.add(e),e.finally((()=>{n.delete(e)}))};try{for await(const e of this.serverStream){const t=performance.now(),n=Date.now();switch(e.message.case){case"getBlobArgs":{const s=e.message.value.blobId;o((async()=>{const o=ae(e.spanContext,"ControlledKvManager.getBlob",r);try{await(this.options.beforeGetBlob?.(o,s));const t=await this.blobStore.getBlob(o,s);await this.clientStream.write(new ne.gm({id:e.id,message:{case:"getBlobResult",value:{blobData:t?(0,oe.Fo)(t):void 0}}}))}catch(t){ie.error(o,"Error handling getBlob",t);const r=t instanceof Error?t.message:String(t);try{await this.clientStream.write(new ne.gm({id:e.id,message:{case:"getBlobResult",value:{blobData:void 0,error:{message:r}}}}))}catch(e){ie.error(o,"Error writing failed getBlobResult",e)}}finally{const e=performance.now()-t;le.histogram(o,e),ce(o,"ControlledKvManager.getBlob",50,n,e)}})());break}case"setBlobArgs":{const s=e.message.value.blobId,i=e.message.value.blobData;o((async()=>{const o=ae(e.spanContext,"ControlledKvManager.setBlob",r);try{await this.blobStore.setBlob(o,s,i),await this.clientStream.write(new ne.gm({id:e.id,message:{case:"setBlobResult",value:{error:void 0}}}))}catch(t){const r=t instanceof Error?t.message:String(t);try{await this.clientStream.write(new ne.gm({id:e.id,message:{case:"setBlobResult",value:{error:{message:r}}}}))}catch(e){ie.error(o,"Error writing setBlobResult",e)}}finally{const e=performance.now()-t;ue.histogram(o,e),ce(o,"ControlledKvManager.setBlob",100,n,e)}})());break}}}}finally{await Promise.allSettled(n)}}catch(e){t.error=e,t.hasError=!0}finally{se(t)}}}function he(e){return e instanceof Error?{abortReasonType:"error",abortReasonName:e.name,abortReasonMessage:e.message}:"string"==typeof e?{abortReasonType:"string",abortReasonMessage:e}:void 0===e?{abortReasonType:"undefined"}:{abortReasonType:typeof e}}var pe=r("../proto/dist/generated/agent/v1/agent_service_pb.js"),fe=r("../proto/dist/generated/agent/v1/shell_exec_pb.js");Error;const me={stateRestoreMs:"client_prep_state_restore_ms",rootPromptRestoreMs:"client_prep_root_prompt_restore_ms",requestContextMs:"client_prep_request_context_ms",systemPromptMs:"client_prep_system_prompt_ms",preTurnSnapshotMs:"client_prep_pre_turn_snapshot_ms",preTurnSnapshotWaitMs:"client_prep_pre_turn_snapshot_wait_ms",preTurnSnapshotBlobWritesMs:"client_prep_pre_turn_snapshot_blob_writes_ms",preTurnSnapshotSerializeMs:"client_prep_pre_turn_snapshot_serialize_ms",firstStepToFirstInvocationMs:"client_prep_first_step_to_first_invocation_ms",promptMessageCount:"client_prep_prompt_message_count",turnCount:"client_prep_turn_count"},ge=Object.keys(me).filter((e=>e in me));function we(e){const t={};for(const r of ge){const n=e[r];void 0!==n&&(t[r]=n)}return t}new WeakMap;var ye=r("../utils/dist/fresh-uuid.js"),ve=r("@bufbuild/protobuf"),be=r("@connectrpc/connect"),Se=r("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/protocol/async-iterable.js"),ke=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class _e{constructor(e,t,r){this.checkpointStream=e,this.checkpointHandler=t,this.ctx=r}async run(){const e={stack:[],error:void 0,hasError:!1};try{const t=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(e,(0,D.VI)(this.ctx.withName("CheckpointController.run")),!1).ctx,r=[];for await(const e of this.checkpointStream){let n;try{n=this.checkpointHandler.handleCheckpoint(t,e.checkpoint,e.metadata)}catch(t){throw e.onSettled?.(),t}r.push(n),void 0!==e.onSettled&&n.then(e.onSettled,e.onSettled)}await Promise.all(r)}catch(t){e.error=t,e.hasError=!0}finally{ke(e)}}}const Ce=(0,d.h)("@anysphere/agent-client:checkpoint-store-waits");class Ee{constructor(e={}){this.options=e,this.inFlight=new Map}noteRouted(e){const t=Pe(e.pendingToolCalls);if(0===t.size)return xe;let r;const n=new Promise((e=>{r=e}));for(const e of t){let t=this.inFlight.get(e);void 0===t&&(t=new Set,this.inFlight.set(e,t)),t.add(n)}return()=>{for(const e of t){const t=this.inFlight.get(e);t?.delete(n),0===t?.size&&this.inFlight.delete(e)}r()}}storedBefore(e,t){const r=this.inFlight.get(t);if(void 0!==r){try{this.options.onExecHeld?.(t)}catch(t){Ce.warn(e,"onExecHeldForCheckpointStore callback failed",{error:String(t)})}return Promise.all(r).then(xe)}}}function xe(){}function Pe(e){const t=new Set;for(const r of e){let e;try{e=JSON.parse(r)}catch{continue}const n=Ie(e)?e.content:void 0;if(!Array.isArray(n))continue;const o=n;for(const e of o)Ie(e)&&"tool-call"===e.type&&"string"==typeof e.toolCallId&&t.add(e.toolCallId)}return t}function Re(e){if("executeHookArgs"===e.message.case)return function(e){const t=e.request?.request;switch(t?.case){case"preToolUse":case"postToolUse":case"postToolUseFailure":return""===t.value.toolUseId?void 0:t.value.toolUseId;case"subagentStart":return""===t.value.toolCallId?void 0:t.value.toolCallId;default:return}}(e.message.value);const t=e.message.value;return Ie(t)&&"string"==typeof t.toolCallId&&""!==t.toolCallId?t.toolCallId:void 0}function Ie(e){return"object"==typeof e&&null!==e}const Te=(0,d.h)("@anysphere/agent-client:exec-checkpoint-gate"),Ae=new Set(["shellArgs","shellStreamArgs","backgroundShellSpawnArgs","forceBackgroundShellArgs","miniSweAgentBashArgs","writeArgs","deleteArgs","mcpArgs","readMcpResourceExecArgs","computerUseArgs","recordScreenArgs","subagentArgs","forceBackgroundSubagentArgs","executeHookArgs"]),$e=new Set(["userMessageAction","resumeAction","backgroundTaskCompletionAction","goalContinuationAction","subscriptionNotificationAction","executePlanAction","asyncAskQuestionCompletionAction"]);function Me(e){const t=e.message.case;return void 0!==t&&Ae.has(t)?Re(e):void 0}const De=e=>e.replace(/[\r\n]/g,"");function Oe(e){return{...void 0!==e.parentRequestId?{"x-parent-request-id":De(e.parentRequestId)}:{},...void 0!==e.rootParentRequestId?{"x-root-parent-request-id":De(e.rootParentRequestId)}:{},...void 0!==e.parentAgentToolCallId?{"x-parent-agent-tool-call-id":De(e.parentAgentToolCallId)}:{},...!0===e.directMetaParentChildSubagent?{"x-direct-meta-parent-child-subagent":"true"}:{}}}const Fe="x-inference-authentication-jwt";function Ne(){const e=globalThis.process?.env,t=e?.INFERENCE_PROXY_JWT?.trim();return void 0===t||""===t||t.startsWith("$")?{}:{[Fe]:t}}class Le extends Error{constructor(e,t){super(`This conversation's data is missing and can't be restored. Start a new chat to continue.${function(e){if(0===e.length)return"";const t=e.slice(0,3).map((e=>e.slice(0,12)));return` (${1===e.length?`missing blob ${t[0]}`:`${e.length} missing blobs: ${t.join(", ")}${e.length>t.length?", …":""}`})`}(e)}`,void 0!==t?.cause?{cause:t.cause}:void 0),this.isUsageError=!0,this.isBlobNotFound=!0,this.name="BlobNotFoundError",this.blobIdHexes=[...e]}}function je(e){return e instanceof Error&&(e instanceof Le||"isBlobNotFound"in e&&!0===e.isBlobNotFound||"BlobNotFoundError"===e.name)}var Ue=r("../proto/dist/generated/aiserver/v1/utils_pb.js"),Be=r("zod/v4");const We="relayedAttemptFailure",He=Be.object({transport:Be.boolean(),stallAborted:Be.boolean(),errorName:Be.string(),connectCode:Be.number().optional(),connectCodeName:Be.string().optional(),connectCause:Be.object({code:Be.union([Be.string(),Be.number()]).optional(),name:Be.string().optional()}).optional(),transportFailureKind:Be.string().optional(),loop:Be.string().optional(),transportMode:Be.string().optional()});function qe(e){const t=e?.details?.additionalInfo[We];if(void 0!==t)try{const e=He.safeParse(JSON.parse(t));return e.success?e.data:void 0}catch{return}}class ze extends Error{constructor(e,t={}){super(e),Object.setPrototypeOf(this,new.target.prototype),this.cause=t.cause,this.requestId=t.requestId,this.displayInfo=t.displayInfo,this.isTransport=t.isTransport}get name(){return this.kind}}class Ge extends ze{get kind(){return"RetriableError"}}class Ve extends ze{constructor(e,t,r={}){super(e,r),this.action=t}get kind(){return"ActionRequiredError"}}class Ke extends ze{get kind(){return"NonRetriableError"}}class Je extends Ke{constructor(e){const t=`This turn's step limit (${e}) needs an in-process agent loop; the network client cannot send it.`;super(t,{displayInfo:{title:"Step limit not supported",detail:t,isRetryable:!1}}),this.maxSteps=e}}class Ze extends ze{get kind(){return"CancelledError"}}const Xe=new Set([Ue.yM.NOT_LOGGED_IN,Ue.yM.AGENT_REQUIRES_LOGIN,Ue.yM.AUTH_TOKEN_NOT_FOUND,Ue.yM.AUTH_TOKEN_EXPIRED,Ue.yM.INVALID_AUTH_ID,Ue.yM.UNAUTHORIZED,Ue.yM.GITHUB_NO_USER_CREDENTIALS,Ue.yM.GITHUB_USER_NO_ACCESS]),Qe=new Set([Ue.yM.FREE_USER_USAGE_LIMIT,Ue.yM.FREE_USER_RATE_LIMIT_EXCEEDED,Ue.yM.PRO_USER_ONLY,Ue.yM.PRO_USER_USAGE_LIMIT,Ue.yM.PRO_USER_RATE_LIMIT_EXCEEDED,Ue.yM.RATE_LIMITED,Ue.yM.RATE_LIMITED_CHANGEABLE,Ue.yM.GENERIC_RATE_LIMIT_EXCEEDED]),Ye=new Set([Ue.yM.USAGE_PRICING_REQUIRED,Ue.yM.USAGE_PRICING_REQUIRED_CHANGEABLE]),et=new Set([Ue.yM.BAD_API_KEY,Ue.yM.BAD_USER_API_KEY,Ue.yM.OUTDATED_CLIENT]),tt=new Set([Ue.yM.USER_ABORTED_REQUEST,Ue.yM.DEBOUNCED]),rt=new Set([Ue.yM.CUSTOM_MESSAGE]),nt=new Map([[be.Code.PermissionDenied,"Permission Denied"]]),ot=["NGHTTP2","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE","socket hang up","Premature close","UND_ERR_SOCKET","ERR_STREAM","protocol error","http/2 stream","ERR_HTTP2_SESSION_ERROR","Session closed with error code","connection aborted","PING timed out","HTTP/2 session not established","HTTP/2 peer not answering","refused to tunnel to","HTTP CONNECT through proxy","Could not connect to proxy"],st=new Set(["ENOTFOUND","EAI_AGAIN","EAI_FAIL","ENODATA","ESERVFAIL","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ECONNABORTED"]),it=new RegExp(`\\b(${[...st].join("|")})\\b`),at=["IMAGE_TOO_LARGE","MAX_TOKENS","CONVERSATION_TOO_LONG","CONTENT_POLICY","DEPRECATED","MAX_MODE_REQUIRED","MODEL_NO_LONGER_SUPPORTED","UNSUPPORTED_REGION","OUTDATED_CLIENT"],ct="x-cursor-inference-request-error-type",lt="AgentWebSocketDeliveryAmbiguousError";function ut(e,t={}){const{requestId:r}=t;if(e instanceof ze)return e;if(dt(e))return function(e,t){const r=pt(e),n=r.code,o=ft(e),s=void 0===o?void 0:function(e){if(void 0===e.details?.additionalInfo[We])return e;const t=e.clone();return void 0!==t.details&&(delete t.details.additionalInfo[We],t.details.equals(new Ue.ej)&&(t.details=void 0)),t}(o),i={title:s?.details?.title,detail:s?.details?.detail,isRetryable:s?.details?.isRetryable,connectCode:n,errorCode:s?.error,inferenceRequestErrorType:mt(r,ct)??mt(e,ct),errorDetails:s},a={cause:e,requestId:t,displayInfo:i,...!0===qe(o)?.transport?{isTransport:!0}:{}};if(n===be.Code.Canceled||n===be.Code.Aborted)return kt(e)?new Ge(e.message,a):new Ze(e.message,a);if(void 0!==s?.error){const t=s.error;if(tt.has(t))return new Ze(vt(e,s),a);const r=s.details?.analyticsMetadata?.actionRequired;if(void 0!==r&&""!==r)return new Ve(vt(e,s),r,a);if(void 0!==Mt(s))return new Ge(vt(e,s),a);if(Xe.has(t))return new Ve(vt(e,s),"login",a);if(Qe.has(t))return new Ve(vt(e,s),"upgrade",a);if(Ye.has(t))return new Ve(vt(e,s),"payment",a);if(et.has(t))return new Ve(vt(e,s),"config",a);if(rt.has(t)&&!0!==s.details?.isRetryable)return new Ke(vt(e,s),a);if(!1===s.details?.isRetryable)return new Ke(vt(e,s),a)}if(n===be.Code.Unauthenticated)return new Ve(e.message,"login",{...a,displayInfo:ht(i,"Sign in required",r)});const c=yt(r);if(Tt.test(c))return new Ve(e.message,"proxy_sign_in",{...a,displayInfo:{...i,title:"Proxy sign-in required",detail:`${c}. Please check your sign-in for this proxy and try again.`,isRetryable:!0}});if(At.test(c))return new Ve(e.message,"proxy_blocked",{...a,displayInfo:{...i,title:"Connection blocked by proxy",detail:`${c}. Your proxy doesn't allow this connection. Please ask your network administrator to allow it and try again.`,isRetryable:!0}});const l=nt.get(n);return void 0===l||!0===s?.details?.isRetryable||kt(e)?new Ge(e.message,a):new Ke(vt(e,s),{...a,displayInfo:ht(i,l,r)})}(e,r);const n=function(e){let t=e;for(let e=0;e<10;e++){if(null==t)return;if(je(t))return t;if("object"!=typeof t||!("cause"in t))return;t=t.cause}}(e);if(void 0!==n)return new Ke(n.message,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Conversation data missing",detail:n.message,isRetryable:!1}});const o=function(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){if(r.name===bt)return r;t.add(r),r=r.cause}}(e);if(void 0!==o)return new Ke(o.message,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Context summarization failed",detail:o.message,isRetryable:!1}});if(function(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){const e="code"in r?r.code:void 0,n="errcode"in r?r.errcode:void 0;if("ENOSPC"===e||"ERR_SQLITE_ERROR"===e&&"number"==typeof n&&13==(255&n))return!0;t.add(r),r=r.cause}return!1}(e))return new Ke(St,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Out of disk space",detail:St,isRetryable:!1}});if(e instanceof Error){if("AbortError"===e.name)return new Ze(e.message,{cause:e,requestId:r});if(e.name===lt)return new Ge(e.message,{cause:e,requestId:r,isTransport:!0});if(kt(e))return new Ge(e.message,{cause:e,requestId:r})}const s=e instanceof Error?e.message:String(e);return new Ge(s,{cause:e instanceof Error?e:void 0,requestId:r})}function dt(e){return null!==e&&"object"==typeof e&&"code"in e&&"name"in e&&("ConnectError"===e.name||"rawMessage"in e&&"string"==typeof e.rawMessage&&"details"in e&&Array.isArray(e.details)&&"findDetails"in e&&"function"==typeof e.findDetails)}function ht(e,t,r){return{...e,title:e.title||t,detail:e.detail||yt(r),isRetryable:e.isRetryable??!1}}function pt(e){let t=e;for(let e=0;e<10&&t.code===be.Code.Unknown;e++){const e=t.cause;if(!dt(e))break;t=e}return t}function ft(e){let t=e;for(let e=0;e<10&&dt(t);e++){try{const e=t.findDetails?.(Ue.vj);if(void 0!==e&&e.length>0)return e[0]}catch{}t=t.cause}}function mt(e,t){const r=e.metadata;if(null===r||"object"!=typeof r||!("get"in r)||"function"!=typeof r.get)return;const n=r.get(t);return"string"==typeof n?n:void 0}function gt(e){let t=e;for(let e=0;e<10&&"object"==typeof t&&null!==t;e++){if(dt(t))return t;t="cause"in t?t.cause:void 0}}function wt(e){const t=gt(e);return void 0===t?void 0:pt(t)}function yt(e){const t=e.rawMessage;return"string"==typeof t?t:e.message.replace(/^\[[a-z_]+\] /,"")}function vt(e,t){if(t?.details){const{title:r,detail:n}=t.details;return r&&n?`${r} ${n}`:r||n||e.message}return e.message}const bt="SummaryPlaceholderRejectedError",St="Out of disk space. Free some space and try again.";function kt(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){t.add(r);const e=`${r.name}: ${r.message}`;if(ot.some((t=>e.includes(t)))||it.test(e))return!0;const n=r.code;if("string"==typeof n&&(ot.some((e=>n.includes(e)))||st.has(n)))return!0;r=r.cause}return!1}function _t(e){return ot.some((t=>e.includes(t)))||it.test(e)}function Ct(e){return e instanceof ze&&e.cause instanceof Error?kt(e.cause):e instanceof Error?kt(e):"string"==typeof e&&_t(e)}function Et(e){return void 0!==e&&e>0}function xt(e){return e+1}function Pt(e){return Object.defineProperty(e,"code",{value:"connection_stalled",enumerable:!0,configurable:!0}),e}function Rt(e){const{cause:t,requestId:r,transportErrorRetries:n,connectCode:o}=e;return Et(n)?Pt(new Ge("Connection stalled repeatedly",{cause:t,requestId:r,displayInfo:{title:"Connection stalled",detail:`The connection stalled ${xt(n)} times. Please check your network connection and try again.`,isRetryable:!0,connectCode:o}})):Pt(new Ge("Connection stalled",{cause:t,requestId:r,displayInfo:{title:"Connection stalled",detail:"The connection stalled. Please try again.",isRetryable:!0,connectCode:o}}))}const It=/^(?:Proxy \S+ refused to tunnel to |HTTP CONNECT through proxy \S+ failed: |Could not connect to proxy \S+: )/,Tt=/^Proxy \S+ refused to tunnel to \S+: 407\b/,At=/^Proxy \S+ refused to tunnel to \S+: 403\b/;function $t(e){let t=e.cause;for(let e=0;e<10&&void 0!==t;e++){if(t instanceof Error&&"AbortError"===t.name)return!0;if(dt(t)&&(t.code===be.Code.Canceled||t.code===be.Code.Aborted))return!0;t=null!==t&&"object"==typeof t&&"cause"in t?t.cause:void 0}return!1}function Mt(e){const t=e?.details?.additionalInfo;if(e?.error!==Ue.yM.RATE_LIMITED||"run_inference_novel_tokens"!==t?.kind||void 0===t.retryAfterMs)return;const r=Number(t.retryAfterMs);return Number.isFinite(r)&&r>=0?r:void 0}var Dt=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Ot=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Ft=(0,d.h)("@anysphere/agent-client:exec-controller");class Nt extends Error{constructor(e){super(e),this.name="LostConnection"}}class Lt{constructor(e,t,r,n){this.serverStream=e,this.clientStream=t,this.controlledExecManager=r,this.checkpointStoreWaits=n}async run(e){const t={stack:[],error:void 0,hasError:!1};try{Dt(t,(0,D.VI)(e.withName("ClientExecController.run")),!1);const r=[],n=t=>{if((0,ve.isMessage)(t,p.Nv))this.controlledExecManager.handleControlMessage(t);else{const n=this.execute(e,t);n.catch((()=>{})),r.push(n)}};let o,s,i=!1;try{try{for await(const t of this.serverStream){const r=(0,ve.isMessage)(t,p.Nv)?void 0:Re(t),a=void 0===r?void 0:this.checkpointStoreWaits?.storedBefore(e,r);if(void 0===o&&void 0===a){n(t);continue}const c=(o??Promise.resolve()).then((async()=>{await a,(0,ve.isMessage)(t,p.Nv)||!i&&!e.canceled?n(t):Ft.info(e,"Dropped an exec queued behind a checkpoint's store",{toolCallId:r})})).catch((e=>{s??={error:e}}));o=c,c.then((()=>{o===c&&(o=void 0)}))}}finally{i=!0}if(await o,void 0!==s)throw s.error;await Promise.all(r)}catch(e){if(e instanceof be.ConnectError&&"protocol error: missing EndStreamResponse"===e.rawMessage)throw new Nt(e.message);if(e instanceof be.ConnectError&&e.code===be.Code.Aborted){const t=e.cause;if(t instanceof Error&&"code"in t&&"string"==typeof t.code&&t.code.includes("ERR_STREAM_WRITE_AFTER_END"))throw new Nt(e.message)}else{if(e instanceof f.W2)throw new Nt(e.message);if(e instanceof be.ConnectError&&e.code===be.Code.Internal){const t=e.cause;if(t instanceof Error&&t.message.includes("NGHTTP2_PROTOCOL_ERROR"))throw new Nt(e.message)}}throw e}}catch(e){t.error=e,t.hasError=!0}finally{Ot(t)}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{let n,o;if(t.spanContext){const r=t.spanContext;n=(0,D.V5)({traceId:r.traceId,spanId:r.spanId,traceFlags:r.traceFlags??1},"exec.handle",e),o=(0,D.fU)(n)}else n=e;Dt(r,o?new D.r2(n,o):void 0,!1);const s=this.controlledExecManager.handle(n,t);for await(const e of s)await this.clientStream.write(e)}catch(e){r.error=e,r.hasError=!0}finally{Ot(r)}}}const jt=(0,d.h)("@anysphere/agent-client:stall-detector"),Ut=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,Bt={nal:"[NAL client stall detector]",local_loop:"[local-loop client stall detector]",module:"[module client stall detector]"},Wt=new Set(["http2","http1_sse","http1_poll","websocket"]);function Ht(e){return void 0===e?"unknown":Wt.has(e)?e:"other"}const qt=(0,h.Pu)("agent_client.stream.stall.count",{description:"Number of bidirectional stream stalls detected",labelNames:["activity_type","message_type","loop","transport_mode"]}),zt=(0,h.v5)("agent_client.stream.stall.duration_ms",{description:"Duration of stream stalls in milliseconds",labelNames:["activity_type","loop","transport_mode"]}),Gt=(0,h.Pu)("agent_client.stream.did_stall",{description:"Number of streams that experienced at least one stall",labelNames:["loop","transport_mode"]}),Vt=(0,h.Pu)("agent_client.stream.total",{description:"Total number of streams monitored",labelNames:["loop","transport_mode"]});class Kt{constructor(){this.handlers=new Map}track(e,t){return this.handlers.set(e,{name:e,state:"started",startedAt:Date.now()}),t.then((t=>{const r=this.handlers.get(e);return r&&(r.state="completed",r.endedAt=Date.now()),t})).catch((t=>{const r=this.handlers.get(e);throw r&&(r.state="errored",r.endedAt=Date.now(),r.error=t instanceof Error?t.message:String(t)),t}))}getHandlerStates(){const e=Date.now(),t={};for(const[r,n]of this.handlers)t[r]={state:n.state,durationMs:(n.endedAt??e)-n.startedAt,error:n.error};return t}}class Jt{constructor(e,t,r){this.lastActivityTime=performance.now(),this.lastMeaningfulActivityTime=performance.now(),this.hasLogged=!1,this.hasLoggedAdvisory=!1,this.hasLoggedHeartbeatOnly=!1,this.hasEverStalled=!1,this.paused=!1,this.disposed=!1,this.activityHistory=[],this.ctx=e,"number"==typeof t?(this.thresholdMs=t,this.advisoryThresholdMs=void 0,this.heartbeatOnlyThresholdMs=3*t,this.onStall=r,this.onStallCallback=void 0,this.handlerTracker=void 0,this.loop="nal",this.readTransportMode=void 0):(this.thresholdMs=t.thresholdMs,this.advisoryThresholdMs=t.advisoryThresholdMs,this.heartbeatOnlyThresholdMs=t.heartbeatOnlyThresholdMs??3*t.thresholdMs,this.onStall=t.onStall,this.onStallCallback=t.onStallCallback,this.handlerTracker=t.handlerTracker,this.loop=t.loop??"nal",this.readTransportMode=t.transportMode),this.logPrefix=Bt[this.loop],this.startTimer(),this.startAdvisoryTimer(),this.startHeartbeatOnlyTimer(),this.onCtxSignalAbort=()=>{this.trackActivity("ctx.signal","abort"),this.abortedAt=performance.now(),this.emitLifecycleLog(`${this.logPrefix} Stream aborted while stall detector active`,"aborted")},e.signal.addEventListener("abort",this.onCtxSignalAbort)}metricLabels(){return{loop:this.loop,transport_mode:Ht(this.readTransportMode?.())}}trackActivity(e,t){const r={type:e,messageType:t};this.lastActivity=r,"inbound_message"===e?this.lastInboundMessage=r:"outbound_write"===e&&(this.lastOutboundMessage=r);const n=this.activityHistory.at(-1);n?.type===e&&n.messageType===t?n.repeat=(n.repeat??1)+1:(this.activityHistory.push(r),this.activityHistory.length>10&&this.activityHistory.shift())}reset(e="inbound_message",t,r=!0){if(this.trackActivity(e,t),"inbound_message"===e){const e=this.hasLogged,t=this.hasLoggedAdvisory,n=this.hasLoggedHeartbeatOnly;e&&(this.hasLogged=!1,this.emitLogAndMetric()),n&&r&&(this.hasLoggedHeartbeatOnly=!1),t&&(this.hasLoggedAdvisory=!1),this.lastActivityTime=performance.now(),r&&(this.lastMeaningfulActivityTime=performance.now()),void 0===this.timer&&this.startTimer(),void 0===this.advisoryTimer&&this.startAdvisoryTimer(),r&&void 0===this.heartbeatOnlyTimer&&this.startHeartbeatOnlyTimer()}}onStreamEnded(){this.trackActivity("stream","ended"),this.streamEndedAt=performance.now()}onClientSentHeartbeat(){this.lastClientSentHeartbeatAt=performance.now()}onServerSentHeartbeat(){this.lastServerSentHeartbeatAt=performance.now()}setPaused(e){if(!this.disposed&&e!==this.paused&&(this.paused=e,!e)){const e=performance.now();this.lastActivityTime=e,this.lastMeaningfulActivityTime=e,void 0===this.timer&&this.startTimer(),void 0===this.advisoryTimer&&this.startAdvisoryTimer(),void 0===this.heartbeatOnlyTimer&&this.startHeartbeatOnlyTimer()}}restartedAfterLoopGap(e,t){const r=performance.now(),n=r-e;return!(n<5e3||t>=e||(this.reportLoopGap(n,r-t),this.lastActivityTime=r,this.lastMeaningfulActivityTime=r,0))}reportLoopGap(e,t){try{jt.info(this.ctx,`${this.logPrefix} Stall check ran late - the process was not running, its windows restart`,this.buildLogMetadata({late_ms:e,window_ms:t,stall_type:"loop_gap"}))}catch(e){console.error("Error in stall detection:",e)}}startTimer(){if(this.disposed||this.thresholdMs<=0||void 0!==this.timer)return;let e=0;const t=t=>{e=performance.now()+t,this.timer=setTimeout(r,t)},r=()=>{if(this.paused||this.restartedAfterLoopGap(e,this.lastActivityTime))return void t(this.thresholdMs);const r=this.thresholdMs-(performance.now()-this.lastActivityTime);if(r<=0)return this.timer=void 0,void this.onStallDetected("no_activity");t(r)};t(this.thresholdMs)}startAdvisoryTimer(){if(this.disposed||void 0===this.advisoryThresholdMs||this.advisoryThresholdMs<=0||void 0!==this.advisoryTimer)return;const e=this.advisoryThresholdMs;let t=0;const r=e=>{t=performance.now()+e,this.advisoryTimer=setTimeout(n,e)},n=()=>{if(this.paused||this.restartedAfterLoopGap(t,this.lastActivityTime))return void r(e);const n=e-(performance.now()-this.lastActivityTime);if(n<=0)return this.advisoryTimer=void 0,void this.onAdvisoryDetected();r(n)};r(e)}startHeartbeatOnlyTimer(){if(this.disposed||this.thresholdMs<=0||this.heartbeatOnlyThresholdMs<=0||void 0!==this.heartbeatOnlyTimer)return;let e=0;const t=t=>{e=performance.now()+t,this.heartbeatOnlyTimer=setTimeout(r,t)},r=()=>{if(this.paused||this.restartedAfterLoopGap(e,this.lastMeaningfulActivityTime))return void t(this.heartbeatOnlyThresholdMs);const r=this.heartbeatOnlyThresholdMs-(performance.now()-this.lastMeaningfulActivityTime);if(r<=0)return this.heartbeatOnlyTimer=void 0,void this.onStallDetected("heartbeat_only");t(r)};t(this.heartbeatOnlyThresholdMs)}buildLogMetadata(e){const t=this.ctx.get(On),r={...e};t?.modelDetails?.displayName&&(r.model_name=t.modelDetails.displayName);const n=performance.now();void 0!==this.abortedAt&&(r.aborted_ago_ms=n-this.abortedAt),void 0!==this.disposedAt&&(r.disposed_ago_ms=n-this.disposedAt),void 0!==this.lastClientSentHeartbeatAt&&(r.last_client_sent_heartbeat_ago_ms=n-this.lastClientSentHeartbeatAt),void 0!==this.lastServerSentHeartbeatAt&&(r.last_server_sent_heartbeat_ago_ms=n-this.lastServerSentHeartbeatAt),void 0!==this.streamEndedAt&&(r.stream_ended_ago_ms=n-this.streamEndedAt),this.lastInboundMessage&&(r.last_inbound_message_type=this.lastInboundMessage.messageType),this.lastOutboundMessage&&(r.last_outbound_message_type=this.lastOutboundMessage.messageType);const o=[];let s;for(let e=this.activityHistory.length-1;e>=0;e--){const{type:t,messageType:r,repeat:n}=this.activityHistory[e];s!==t&&(s?o.push(`[${t}]`):o.push(`[${t}] (MOST RECENT)`),s=t),o.push(`${r}${n?` (x${n})`:""}`)}return r.activities=o.join("\n"),{reqId:t?.requestId,loop:this.loop,stall:r}}onAdvisoryDetected(){if(this.hasLogged||this.hasLoggedAdvisory)return;if(void 0===this.advisoryThresholdMs||this.advisoryThresholdMs<=0)return;const e=performance.now()-this.lastActivityTime;e=this.heartbeatOnlyThresholdMs){if(this.hasLoggedHeartbeatOnly)return;this.hasLoggedHeartbeatOnly=!0,this.reportStall(e,n)}return}if(this.hasLogged)return;this.hasLogged=!0,this.hasLoggedAdvisory=!0;const t=performance.now()-this.lastActivityTime;this.reportStall(e,t)}reportStall(e,t){const r=this.lastActivity,n=this.lastInboundMessage,o=this.lastOutboundMessage,s=this.ctx.get(On);try{const i=this.buildLogMetadata({duration_ms:t,threshold_ms:"heartbeat_only"===e?this.heartbeatOnlyThresholdMs:this.thresholdMs,stall_type:e}),a="heartbeat_only"===e?`${this.logPrefix} Stream receiving heartbeats only - no meaningful data for threshold period`:`${this.logPrefix} Bidirectional stream stall detected - no activity for threshold period`;if(jt.warn(this.ctx,a,i),qt.increment(this.ctx,1,{activity_type:r?.type??"unknown",message_type:r?.messageType??"unknown",...this.metricLabels()}),this.hasEverStalled||(this.hasEverStalled=!0,Gt.increment(this.ctx,1,this.metricLabels())),this.onStallCallback){const t=performance.now(),i={type:e,lastActivityAgoMs:t-this.lastActivityTime,lastMeaningfulActivityAgoMs:t-this.lastMeaningfulActivityTime,lastActivityType:r?.messageType,lastInboundMessageType:n?.messageType,lastOutboundMessageType:o?.messageType,requestId:s?.requestId,modelName:s?.modelDetails?.displayName,streamEnded:void 0!==this.streamEndedAt,aborted:void 0!==this.abortedAt,lastServerHeartbeatAgoMs:void 0!==this.lastServerSentHeartbeatAt?t-this.lastServerSentHeartbeatAt:void 0,lastClientHeartbeatAgoMs:void 0!==this.lastClientSentHeartbeatAt?t-this.lastClientSentHeartbeatAt:void 0,thresholdMs:"heartbeat_only"===e?this.heartbeatOnlyThresholdMs:this.thresholdMs,handlers:this.handlerTracker?.getHandlerStates(),loop:this.loop};try{this.onStallCallback(i)}catch(e){console.error("Error in stall callback:",e)}}}catch(e){console.error("Error in stall detection:",e)}try{this.onStall?.(function(e){const t=new DOMException(`the stall detector cut the stream: ${e}`,"AbortError");return Object.defineProperty(t,"cursorStallCut",{value:!0}),t}("heartbeat_only"===e?`heartbeats alone for ${this.heartbeatOnlyThresholdMs} ms`:`no activity for ${this.thresholdMs} ms`))}catch(e){console.error("Error in onStall callback:",e)}}emitLifecycleLog(e,t){const r=performance.now()-this.lastActivityTime;try{const n=this.buildLogMetadata({duration_ms:r,event_type:t});jt.info(this.ctx,e,n)}catch(e){console.error("Error logging stream lifecycle:",e)}}emitLogAndMetric(){const e=performance.now()-this.lastActivityTime;this.emitLifecycleLog(`${this.logPrefix} Stream activity resumed after stall`,"recovered"),zt.histogram(this.ctx,e,{activity_type:this.lastActivity?.type??"unknown",...this.metricLabels()})}[Symbol.dispose](){this.disposed||Vt.increment(this.ctx,1,this.metricLabels()),this.disposed=!0,this.paused=!1,void 0!==this.timer&&(clearTimeout(this.timer),this.timer=void 0),void 0!==this.advisoryTimer&&(clearTimeout(this.advisoryTimer),this.advisoryTimer=void 0),void 0!==this.heartbeatOnlyTimer&&(clearTimeout(this.heartbeatOnlyTimer),this.heartbeatOnlyTimer=void 0),this.ctx.signal.removeEventListener("abort",this.onCtxSignalAbort),this.trackActivity("disposed","disposed"),this.disposedAt=performance.now(),this.emitLifecycleLog(`${this.logPrefix} Stream stall detector disposed`,"disposed")}}const Zt={now:()=>performance.now(),setTimeout(e,t){const r=setTimeout(e,t);return r.unref?.(),r},clearTimeout(e){clearTimeout(e)}},Xt=(0,h.v5)("agent_client.first_message.event_loop_max_lag_ms",{description:"Longest event-loop block between the network phase start and the first server message of a run's first attempt",labelNames:["loop","transport_mode","first_message_slow"]}),Qt=(0,h.v5)("agent_client.first_message.event_loop_total_lag_ms",{description:"Summed event-loop blocking between the network phase start and the first server message of a run's first attempt",labelNames:["loop","transport_mode","first_message_slow"]}),Yt=(0,h.v5)("agent_client.first_message.network_ms",{description:"Time from the network phase start to the first server message of a run's first attempt, on attempts that sampled event-loop lag",labelNames:["loop","transport_mode","first_message_slow"]});var er=r("../proto/dist/generated/agent/v1/ask_question_tool_pb.js"),tr=r("../proto/dist/generated/agent/v1/create_plan_tool_pb.js"),rr=r("../proto/dist/generated/agent/v1/pr_management_tool_pb.js"),nr=r("../proto/dist/generated/agent/v1/replace_env_tool_pb.js"),or=r("../proto/dist/generated/agent/v1/setup_vm_environment_tool_pb.js"),sr=r("../proto/dist/generated/agent/v1/connect_scm_tool_pb.js"),ir=r("../proto/dist/generated/agent/v1/generate_image_tool_pb.js"),ar=r("../proto/dist/generated/agent/v1/mcp_auth_tool_pb.js"),cr=r("../proto/dist/generated/agent/v1/switch_mode_tool_pb.js"),lr=r("../proto/dist/generated/agent/v1/web_fetch_tool_pb.js"),ur=r("../proto/dist/generated/agent/v1/web_search_tool_pb.js");class dr extends Error{constructor(e){super(`Deferred interaction response requested for query ${e.id} (${e.query.case??"unknown"})`),this.query=e,this.name="DeferredInteractionResponseError",Object.setPrototypeOf(this,new.target.prototype)}}const hr=e=>new c.Y5({id:e,result:{case:"webSearchRequestResponse",value:new ur.lI({result:{case:"approved",value:new ur.XJ}})}}),pr=(e,t)=>new c.Y5({id:e,result:{case:"webSearchRequestResponse",value:new ur.lI({result:{case:"rejected",value:new ur.yc({reason:t??""})}})}}),fr=e=>new c.Y5({id:e,result:{case:"webFetchRequestResponse",value:new lr.fS({result:{case:"approved",value:new lr.Hs}})}}),mr=(e,t)=>new c.Y5({id:e,result:{case:"webFetchRequestResponse",value:new lr.fS({result:{case:"rejected",value:new lr.m$({reason:t??""})}})}}),gr=(e,t)=>new c.Y5({id:e,result:{case:"askQuestionInteractionResponse",value:new c.zT({result:t})}}),wr=e=>new c.Y5({id:e,result:{case:"switchModeRequestResponse",value:new cr.w$({result:{case:"approved",value:new cr.q5}})}}),yr=(e,t)=>new c.Y5({id:e,result:{case:"switchModeRequestResponse",value:new cr.w$({result:{case:"rejected",value:new cr.rA({reason:t??""})}})}}),vr=(e,t)=>new c.Y5({id:e,result:{case:"createPlanRequestResponse",value:new tr.gz({result:t})}}),br=(e,t)=>new c.Y5({id:e,result:{case:"setupVmEnvironmentResult",value:t}}),Sr=(e,t)=>new c.Y5({id:e,result:{case:"replaceEnvResult",value:t}}),kr=(e,t)=>new c.Y5({id:e,result:{case:"prManagementResult",value:t}}),_r=e=>new c.Y5({id:e,result:{case:"mcpAuthRequestResponse",value:new ar.h({result:{case:"approved",value:new ar.D5}})}}),Cr=(e,t)=>new c.Y5({id:e,result:{case:"mcpAuthRequestResponse",value:new ar.h({result:{case:"rejected",value:new ar.OI({reason:t??"Authentication was rejected"})}})}}),Er=(e,t)=>new c.Y5({id:e,result:{case:"connectScmRequestResponse",value:new sr.qG({result:{case:"rejected",value:new sr.lB({reason:t??"Connecting GitHub was skipped"})}})}}),xr=(e,t)=>new c.Y5({id:e,result:{case:"generateImageRequestResponse",value:new ir.vW({result:{case:"approved",value:new ir.l3({description:t??""})}})}}),Pr=(e,t)=>new c.Y5({id:e,result:{case:"generateImageRequestResponse",value:new ir.vW({result:{case:"rejected",value:new ir.Uq({reason:t??""})}})}});class Rr extends Error{constructor(e,t={}){super(e),this.name="InteractionListenerStreamClosedError",this.cause=t.cause,Object.setPrototypeOf(this,new.target.prototype)}}Rr.telemetryName="InteractionListenerStreamClosedError";var Ir=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Tr=(0,d.h)("ClientInteractionController"),Ar=new Set(["askQuestionInteractionQuery","switchModeRequestQuery","mcpAuthRequestQuery","connectScmRequestQuery"]);class $r{constructor(e,t,r,n){this.interactionStream=e,this.interactionListener=t,this.queryResponseStream=r,this.stallSuspender=n,this.pendingHumanQueries=0}async run(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,D.VI)(e.withName("ClientInteractionController.run")),!1);e=r.ctx;let n,o=Promise.resolve();for await(const t of this.interactionStream){const r=()=>"interactionQuery"===t.case?this.handleInteractionQuery(e,t.value):this.handleInteractionUpdate(e,t.value);o=o.then(r).catch((r=>{Tr.error(e,"Error handling interaction message",r,{messageCase:t.case}),n??=r}))}if(await o,void 0!==n)throw n}catch(e){t.error=e,t.hasError=!0}finally{Ir(t)}}async handleInteractionUpdate(e,t){await this.interactionListener.sendUpdate(e,t)}handleInteractionQuery(e,t){const r=void 0!==t.query.case&&Ar.has(t.query.case);let n=!1;const o=()=>{r&&!n&&(n=!0,this.pendingHumanQueries--,0===this.pendingHumanQueries&&this.stallSuspender?.setPaused(!1))};r&&(this.pendingHumanQueries++,1===this.pendingHumanQueries&&this.stallSuspender?.setPaused(!0)),(async()=>this.interactionListener.query(e,t))().catch((r=>{const n=function(e,t){switch(e.query.case){case"webSearchRequestQuery":return pr(e.id,t);case"webFetchRequestQuery":return mr(e.id,t);case"askQuestionInteractionQuery":return gr(e.id,new er.tz({result:{case:"rejected",value:new er.ox({reason:t})}}));case"switchModeRequestQuery":return yr(e.id,t);case"createPlanRequestQuery":return vr(e.id,new tr.bK({result:{case:"error",value:new tr.iY({error:t})}}));case"setupVmEnvironmentArgs":return br(e.id,new or.r$({result:{case:"success",value:new or.JH({})}}));case"replaceEnvArgs":return Sr(e.id,new nr.dV({result:{case:"failure",value:new nr.uq({errorMessage:t,setupLogs:""})}}));case"prManagementRequestQuery":return kr(e.id,new rr.HL({result:{case:"error",value:new rr.K$({error:t})}}));case"mcpAuthRequestQuery":return Cr(e.id,t);case"connectScmRequestQuery":return Er(e.id,t);case"generateImageRequestQuery":return Pr(e.id,t);case void 0:return;default:return e.query}}(t,"The client could not show this request to the user");if(!(n instanceof c.Y5))throw r;return Tr.error(e,"Error handling interaction query; answering with a fail-closed response",{queryCase:t.query.case,error:r}),n})).then((e=>(o(),this.queryResponseStream.write(e)))).catch((t=>{Tr.error(e,"Error handling interaction query",t)})).finally(o)}}async function Mr(e,t){let r;try{r=await e(t.signal)}catch(e){if(t.isCanceled())throw new Ze("User aborted request");throw new Ke("Failed to mint LLM Gateway credential",{cause:e instanceof Error?e:void 0,requestId:t.requestId})}if(void 0===r)throw new Ke("LLM Gateway credential minter returned no credential",{requestId:t.requestId});if(""===r.bearerToken.trim())throw new Ke("LLM Gateway credential minter returned an empty bearer token",{requestId:t.requestId});return new c.Ibo({bearerToken:r.bearerToken})}const Dr=G("request-context-executor",(e=>new H(e,Q("requestContextArgs"),Y("requestContextResult"))),((e,t)=>{t.register(new A(e,te("requestContextArgs"),ee("requestContextResult")))}));var Or=r("../agent-kv/dist/serde.js"),Fr=r("../proto/dist/generated/agent/v1/request_context_exec_pb.js"),Nr=r("../utils/dist/promise-extras.js");const Lr=15728640,jr=(0,h.Pu)("agent_client.request_context_blob.prepared",{description:"Prepared RequestContext blob references"}),Ur=(0,h.v5)("agent_client.request_context_blob.bytes",{description:"Serialized RequestContext bytes staged by the client"}),Br=(0,h.v5)("agent_client.request_context_blob.preparation_ms",{description:"Time to hydrate, serialize, and hash RequestContext"});function Wr(e){switch(e.action.case){case"userMessageAction":case"subscriptionNotificationAction":case"resumeAction":case"executePlanAction":return e.action.value;default:return}}class Hr{constructor(e,t=62914560){this.parent=e,this.maxTransientBytes=t,this.transientBlobs=new Map,this.persistedBlobIds=new Set,this.transientBytes=0}seed(e,t){return this.seedAll([{blobId:e,blobData:t}])}seedAll(e){const t=new Map;for(const{blobId:r,blobData:n}of e)t.set((0,Or.nj)(r),n.byteLength);let r=this.transientBytes;for(const[e,n]of t)r-=this.transientBlobs.get(e)?.byteLength??0,r+=n;if(r>this.maxTransientBytes)return!1;for(const{blobId:t,blobData:r}of e)this.transientBlobs.set((0,Or.nj)(t),r);return this.transientBytes=r,!0}has(e){return this.transientBlobs.has((0,Or.nj)(e))}hasAll(e){return e.every((e=>this.has(e)))}async getBlob(e,t){const r=(0,Or.nj)(t),n=this.transientBlobs.get(r);return void 0===n?await this.parent.getBlob(e,t):n}async persistForRemoteRead(e,t){const r=(0,Or.nj)(t),n=this.transientBlobs.get(r);void 0===n||this.persistedBlobIds.has(r)||(await(0,Nr.O$)((()=>this.parent.setBlob(e,t,n)),2),this.persistedBlobIds.add(r))}async setBlob(e,t,r){await this.parent.setBlob(e,t,r)}async setBlobLocallyOnly(e,t,r){await this.parent.setBlobLocallyOnly(e,t,r)}async flush(e){await this.parent.flush(e)}}async function qr({ctx:e,action:t,resources:r,blobStore:n,mode:o,maxBlobBytes:s,maxInlineDynamicBytes:i=1048576,notesSessionId:a}){const c=performance.now(),l=Wr(t);if(void 0===l)return{kind:"not_applicable"};if("legacy"===o)return t.requestContextParts=void 0,{kind:"legacy"};if(void 0!==t.requestContextParts){const e=void 0===(u=t.requestContextParts)?[]:[u.rulesBlobId,u.skillsBlobId,u.subagentsBlobId,u.mcpsBlobId],r=void 0!==l.requestContext,s=e.length>0&&n.hasAll(e);if(r||s){const e=t.requestContextParts;return"ref_only"===o&&r&&s&&void 0!==e?.dynamicContext&&(l.requestContext=void 0),{kind:"already_prepared"}}}var u;t.requestContextParts=void 0;const d=void 0===l.requestContext,h=l.requestContext??await async function({ctx:e,resources:t,notesSessionId:r}){const n=t.get(Dr),o=await n.execute(e,new Fr._K({notesSessionId:r})),s="success"===o.result.case?o.result.value.requestContext:void 0;if(void 0===s)throw new Error(`Failed to compute request context: ${o.result.case}`);return s}({ctx:e,resources:r,notesSessionId:a}),p=Math.min(Math.max(0,s),Lr),f=await async function({requestContext:e,mode:t,maxBlobBytes:r,maxInlineDynamicBytes:n}){const o=function(e){const t=e.clone();return t.rules=[],t.nonFileRules=[],t.cloudRule=void 0,t.agentSkills=[],t.skillOptions=void 0,t.customSubagents=[],t.tools=[],t.mcpInstructions=[],t.mcpFileSystemOptions=void 0,t.mcpMetaToolOptions=void 0,{dynamicContext:t,rules:new Fr.T3({rules:e.rules.map((e=>e.clone())),nonFileRules:e.nonFileRules.map((e=>e.clone())),cloudRule:e.cloudRule}),skills:new Fr.CB({agentSkills:e.agentSkills.map((e=>e.clone())),skillOptions:e.skillOptions?.clone()}),subagents:new Fr.yb({customSubagents:e.customSubagents.map((e=>e.clone()))}),mcps:new Fr.vB({tools:e.tools.map((e=>e.clone())),mcpInstructions:e.mcpInstructions.map((e=>e.clone())),mcpFileSystemOptions:e.mcpFileSystemOptions?.clone(),mcpMetaToolOptions:e.mcpMetaToolOptions?.clone()})}}(e),s="ref_only"===t?o.dynamicContext.toBinary().byteLength:void 0;if(void 0!==s&&s>n)return;const i=o.rules.toBinary(),a=o.skills.toBinary(),c=o.subagents.toBinary(),l=o.mcps.toBinary(),u=i.byteLength+a.byteLength+c.byteLength+l.byteLength;if(u>r)return;const[d,h,p,f]=await Promise.all([(0,oe.Bk)(i),(0,oe.Bk)(a),(0,oe.Bk)(c),(0,oe.Bk)(l)]),m=[{blobId:d,blobData:i},{blobId:h,blobData:a},{blobId:p,blobData:c},{blobId:f,blobData:l}],g=new Fr.sG({rulesBlobId:d,rulesByteLength:i.byteLength,skillsBlobId:h,skillsByteLength:a.byteLength,subagentsBlobId:p,subagentsByteLength:c.byteLength,mcpsBlobId:f,mcpsByteLength:l.byteLength,dynamicContext:"ref_only"===t?o.dynamicContext:void 0});if("dual"===t)return{kind:"dual",inlineContext:e,byteLength:u,parts:g};if(void 0===s)throw new Error("ref_only request context did not measure dynamic bytes");return{kind:"ref_only",stagedBlobs:m,byteLength:u,parts:g,dynamicByteLength:s}}({requestContext:h,mode:o,maxBlobBytes:p,maxInlineDynamicBytes:Math.min(Math.max(0,i),p)});if(void 0===f)return l.requestContext=h,t.requestContextParts=void 0,jr.increment(e,1,{mode:o,outcome:"oversized"}),{kind:"oversized"};if("ref_only"===f.kind&&!n.seedAll(f.stagedBlobs))return l.requestContext=h,t.requestContextParts=void 0,jr.increment(e,1,{mode:o,outcome:"transient_budget_exceeded"}),{kind:"transient_budget_exceeded"};l.requestContext="dual"===f.kind?f.inlineContext:void 0,t.requestContextParts=f.parts;const m=f.byteLength;return jr.increment(e,1,{mode:o,outcome:d?"hydrated":"inline"}),Ur.histogram(e,m,{mode:o}),Br.histogram(e,performance.now()-c,{mode:o}),{kind:"prepared",byteLength:m,hydrated:d,rulesByteLength:f.parts.rulesByteLength,skillsByteLength:f.parts.skillsByteLength,subagentsByteLength:f.parts.subagentsByteLength,mcpsByteLength:f.parts.mcpsByteLength,dynamicByteLength:"ref_only"===f.kind?f.dynamicByteLength:void 0}}function zr(e){return Object.keys(e.fileContents).length>0}function Gr(e,t){return Object.assign(new(e.getType()),e,t)}function Vr(e){return Gr(e,{fileContents:{}})}function Kr(e){for(const[t]of e.entries())if(t.symbol===Dr.symbol)return e.get(Dr)}var Jr=r("../proto/dist/generated/agent/v1/cursor_rules_pb.js");const Zr=102400;function Xr(e){return"AGENTS.md"===e||"CLAUDE.md"===e||"CLAUDE.local.md"===e}function Qr({content:e,filename:t}){return Buffer.byteLength(e,"utf8")>Zr?function({content:e,filename:t}){const r=Buffer.from(e,"utf8");let n=Zr;for(;128==(192&r.readUInt8(n));)n--;const o=`[truncated: ${t} is ${Math.round(r.length/1024)} KB; only the first 100 KB is included]`;return`${r.subarray(0,n).toString("utf8")}\n\n${o}`}({content:e,filename:t}):e}function Yr(e){const t=/^\s*("(?:[^"\\]|\\.)*"|'(?:[^']|'')*')\s+#/.exec(e);return null!==t?t[1]:/^\s*["']/.test(e)?e.trim():e.replace(/\s#.*$/,"").trim()}function en(e,t){return"description"===e?t.trim():Yr(t)}function tn(e){const t=e.trim();return"true"===t||"false"!==t&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t)}function rn(e){const t=e.trimStart();if(!t.startsWith("---"))return null;const r=t.split("---").filter(Boolean);if(r.length<2)return null;const n=r[0].trim(),o=r.slice(1).join("---").trim(),s={};let i=null,a=null;for(const e of n.split("\n")){const t=e.replace(/\r$/,"");if(/^\s*#/.test(t))continue;const r=t.match(/^\s+-\s+(.*)$/);if(r&&a){let e=Yr(r[1]);(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1));const t=s[a];Array.isArray(t)&&t.push(e);continue}const n=t.startsWith(" ")||t.startsWith("\t");if(i&&n){const e=t.trim(),r=e.indexOf(":");if(-1===r)continue;const n=e.slice(0,r).trim(),o=Yr(e.slice(r+1)),c=tn(o),l=`${i}.${n}`;""===o?(s[l]=[],a=l):"metadata.environments"===l||"metadata.disabledEnvironments"===l||"metadata.scopedTo"===l?(s[l]=String(c).split(",").map((e=>e.trim())).filter(Boolean),a=null):(s[l]=c,a=null);continue}i=null,a=null;const o=t.indexOf(":");if(-1===o)continue;const c=t.slice(0,o).trim(),l=en(c,t.slice(o+1));if(""===l&&"metadata"===c){i=c;continue}if("globs"===c&&""===l){s.globs=[],a="globs";continue}const u=tn(l);s[c]="metadata.environments"!==c&&"metadata.disabledEnvironments"!==c&&"metadata.scopedTo"!==c?u:String(u).split(",").map((e=>e.trim())).filter(Boolean)}return{frontmatter:s,rawFrontmatter:`---\n${n}\n---`,body:o}}function nn(e){const t=e.replace(/\\/g,"/").replace(/^[A-Za-z]:/,(e=>e.toLowerCase())),r=[];for(const e of t.split("/"))""!==e&&"."!==e&&(".."!==e?r.push(e):r.pop());return`${t.startsWith("/")?"/":""}${r.join("/")}`}function on(e,t){return"/"===t?e.length>1:e.startsWith(`${t}/`)}const sn=[[".cursor","skills"],[".cursor","skills-cursor"],[".claude","skills"],[".claude","plugins"],[".codex","skills"],[".grok","skills"],[".agents","skills"],[".cursor","plugins"]];class an{constructor(){this.allowed=!1}observeHeaders(e){this.allowed="1"===e.get("x-cursor-lazy-rule-bodies")}isAllowed(){return this.allowed}}function cn(e){if("success"!==e.result.case)return e;const t=e.result.value,r=t.requestContext;if(void 0===r)return e;const n=function(e){const t=e.env?.workspacePaths??[];let r=!1;const n=e.rules.map((e=>{if(!function(e,t){if(!0===e.bodyOmitted||0===e.content.length||void 0!==e.parseError||e.source!==Jr.gv.UNSPECIFIED||void 0!==e.plugin||void 0!==e.marketplace||void 0!==e.pluginId||void 0!==e.marketplaceId)return!1;if(0===e.scopedTo.length&&0===e.frontmatter.length&&e.content.trimStart().startsWith("---"))return!1;const r=nn(e.fullPath),n=r.startsWith("/"),o=r.split("/").filter((e=>e.length>0)),s=o.at(-1);if(void 0===s||function(e){return"SKILL.md"===e.at(-1)||e.some(((t,r)=>sn.some((([n,o])=>t===n&&e[r+1]===o))))}(o))return!1;const i=t.map(nn);if(!i.some((e=>on(r,e))))return!1;const a=function(e,t){let r=e.length-1;for(let t=e.length-2;t>=0;t--)if(".cursor"===e[t]&&"rules"===e[t+1]){r=t;break}return`${t?"/":""}${e.slice(0,r).join("/")}`}(o,n),c=a!==`${n?"/":""}${o.slice(0,-1).join("/")}`,l=e.type?.type.case;return"fileGlobbed"===l?s.endsWith(".mdc")&&c:"global"===l&&!!(Xr(s)||s.endsWith(".mdc")&&c)&&!i.includes(a)&&i.some((e=>on(a,e)))}(e,t))return e;r=!0;const n=Object.assign(new(e.getType()),e);return n.content=e.content.split("\n").find((e=>e.trim().length>0))??"",n.bodyOmitted=!0,n}));return r?Object.assign(new(e.getType()),e,{rules:n}):e}(r);return n===r?e:new Fr._G({result:{case:"success",value:Object.assign(new(t.getType()),t,{requestContext:n})}})}function ln(e){return void 0!==e&&Number.isFinite(e)&&Number.isInteger(e)}function un(e,t){const{rulesByteLength:r,skillsByteLength:n}=e,{subagentsByteLength:o,mcpsByteLength:s}=e;if(!(ln(r)&&ln(n)&&ln(o)&&ln(s)))return;const i=t?.dynamicByteLength;return{bytes:r+n+o+s+(i??0),bytesSource:"blob_parts",rulesBytes:r,skillsBytes:n,mcpBytes:s,subagentsBytes:o,...ln(i)?{dynamicBytes:i}:{}}}const dn=["alpn_failure","poll_seqno_gap","append_fatal","http_464","http_404_unimplemented","socket_reset","stream_closed_early","idle_deadline","stall","other"],hn=/\bHTTP (\d{3})\b/;function pn(e){const t=e.message;return"string"==typeof t?t:""}function fn(e){return e instanceof Error&&("AbortError"===e.name||e.name===lt)}const mn={serverCap:3,transportCap:10},gn={alpn_failure:"server",poll_seqno_gap:"server",append_fatal:"by_signature",http_464:"server",http_404_unimplemented:"server",socket_reset:"transport",stream_closed_early:"server",idle_deadline:"server",stall:"transport",other:"server"};function wn(e){return{action:"retry",countAsServerError:!0,countAsTransportError:!1,transportFailureKind:e}}function yn(e,t,r){const n=r.attemptRequestId,o=!0===t.endless,s=r.retriesEnabled||o,i=(e,n)=>!o&&(e>=n||void 0!==t.sharedCap&&r.serverErrorRetries+r.transportErrorRetries>=t.sharedCap);let a=e instanceof ze?e:ut(e,{requestId:n});const c=a instanceof Ze&&("owner"===r.abortOrigin||function(e){const t=e.displayInfo?.errorCode;return void 0!==t&&tt.has(t)}(a)),l="stall_detector"===r.abortOrigin&&!c&&(a instanceof Ze||a instanceof Ge),u="owner"===r.abortOrigin&&a instanceof Ge&&$t(a),d=function(e,t,r){return t.stalled?"stall":t.userStop?"other":function(e,t={}){const r=function(e){const t=[],r=new Set;let n=e;for(;"object"==typeof n&&null!==n&&!r.has(n);)r.add(n),t.push(n),n="cause"in n?n.cause:void 0;return t}(e);if(r.some((e=>"cursorBidiAppendFatal"in e)))return"append_fatal";const n=r.map(pn),o=e=>n.some((t=>t.includes(e))),s=function(e){return wt(e)?.code}(e),i=void 0===t.transportMode;if(i&&s===be.Code.Unavailable&&o("ALPN protocol failed to negotiate"))return"alpn_failure";if((i||"http1_poll"===t.transportMode)&&s===be.Code.Unavailable&&o("Unexpected seqno"))return"poll_seqno_gap";const a=n.map((e=>hn.exec(e)?.[1])).find((e=>void 0!==e));return i&&s===be.Code.Unknown&&"464"===a?"http_464":i&&s===be.Code.Unimplemented&&"404"===a?"http_404_unimplemented":s===be.Code.DeadlineExceeded&&function(e){const t=gt(e);return void 0===t?void 0:ft(t)?.error}(e)===Ue.yM.TIMEOUT?"idle_deadline":i&&s===be.Code.Unknown&&o("unsupported content type null")?"stream_closed_early":Ct(e)||function(e){return e instanceof Error&&"isTransport"in e&&!0===e.isTransport}(e)||r.some(fn)?"socket_reset":"other"}(e,r)}(e,{stalled:l,userStop:c||u},{transportMode:r.attemptTransportMode}),h=(e,t={})=>({action:"throw",error:e,...t,transportFailureKind:d}),p=(e,n,{immediateFirstRetry:o})=>s?i(r.transportErrorRetries,t.transportCap)?h(e(),{countAsTransportError:!0}):function(e,t){return{action:"retry",countAsServerError:!1,countAsTransportError:!0,transportFailureKind:e,...t?{noBackoff:!0}:{}}}(d,o&&0===r.transportErrorRetries):h(n(),{countAsTransportError:!0}),f=()=>({cause:a.cause,requestId:n,transportErrorRetries:r.transportErrorRetries,connectCode:a.displayInfo?.connectCode});if(l){if(s&&void 0!==r.stallRetryElapsedMs&&r.stallRetryElapsedMs>=18e4)return h(Rt(f()),{countAsTransportError:!0});const e=p((()=>Rt(f())),(()=>Rt({...f(),transportErrorRetries:void 0})),{immediateFirstRetry:!1});return"retry"===e.action?{...e,stall:!0}:e}if(a instanceof Ze&&!c&&$t(a)&&(a=new Ge(a.message,{cause:a.cause,requestId:n,displayInfo:a.displayInfo,isTransport:!0})),u)return h(new Ze(a.message,{cause:a.cause,requestId:n,displayInfo:a.displayInfo}));if(!0===t.retryAllInference&&(a instanceof Ve||a instanceof Ke)&&function(e){const t=e.displayInfo?.inferenceRequestErrorType;return void 0!==t&&!at.some((e=>e===t))}(a))return i(r.serverErrorRetries,t.serverCap)?h(a):wn(d);if(a instanceof Ze||a instanceof Ve||a instanceof Ke)return h(a);const m=function(e){return Mt(e.displayInfo?.errorDetails)}(a);if(a instanceof Ge&&void 0!==m){const e=(r.rateLimitRetryElapsedMs??0)+m;return!s||!o&&e>3e5?h(a):{action:"retry",countAsServerError:!1,countAsTransportError:!1,transportFailureKind:d,retryAfterMs:m,rateLimit:!0}}if(a instanceof Ge&&(!0===a.isTransport||function(e,t){const r=gn[e];return"by_signature"===r?Ct(t):"transport"===r}(d,a)||"owner"!==r.abortOrigin&&$t(a))){const e=function(e){const t=e.displayInfo,r=t?.title,n=t?.detail;return r&&n?{...t,title:r,detail:n}:void 0}(a);return p((()=>function(e){const{cause:t,requestId:r,transportErrorRetries:n,connectCode:o,ownCopy:s}=e;if(void 0!==s)return new Ge(Et(n)?"Connection failed repeatedly":"Connection failed",{cause:t,requestId:r,displayInfo:{...s,isRetryable:!0,connectCode:o??s.connectCode}});const i=function(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){t.add(r);const e=dt(r)?yt(r):r.message;if(It.test(e))return e;r=r.cause}}(t),a=void 0===i?"Please check your network connection and try again.":"Please check your proxy settings and try again.";return Et(n)?new Ge("Connection failed repeatedly",{cause:t,requestId:r,displayInfo:{title:"Connection failed",detail:`${void 0===i?"":`${i}. `}The connection failed ${xt(n)} times. ${a}`,isRetryable:!0,connectCode:o}}):new Ge("Connection failed",{cause:t,requestId:r,displayInfo:{title:"Connection failed",detail:`${i??"The connection was interrupted"}. ${a}`,isRetryable:!0,connectCode:o}})}({...f(),...void 0===e?{}:{ownCopy:e}})),(()=>a),{immediateFirstRetry:!0})}return s?i(r.serverErrorRetries,t.serverCap)?h(function(e){const{classified:t,requestId:r,serverErrorRetries:n}=e,o=t.displayInfo;return new Ge(t.message,{cause:t.cause,requestId:r,displayInfo:{...o,title:o?.title||"Server error",detail:o?.detail||`The server failed ${xt(n)} times. Please try again, or contact support if the issue persists.`,isRetryable:!0}})}({classified:a,requestId:n,serverErrorRetries:r.serverErrorRetries})):wn(d):h(a)}var vn=r("../proto/dist/generated/agent/v1/mcp_pb.js");const bn=(0,b.cF)(Symbol("agentTransportTimingRecorder"),void 0),Sn=(0,d.h)("@anysphere/agent-client:turn-runner"),kn=1e3,_n=6e4,Cn=(0,h.Pu)("agent_client.turn.retry",{description:"Turn attempts retried by the turn runner",labelNames:["attempt","reason","loop"]});function En(e){return e<=1?"1":2===e?"2":e<=5?"3_5":"gt5"}function xn(e){return!0===e.stall?"stall":!0===e.rateLimit?"rate_limit":e.countAsTransportError?"transport":e.countAsServerError?"server":!0===e.immediate?"speculative":"other"}const Pn=new Set(["textDelta","thinkingDelta","thinkingCompleted","partialToolCall","toolCallDelta","toolCallStarted","toolCallCompleted","tokenDelta"]);function Rn(e){const{message:t}=e;return("textDelta"!==t.case||void 0===t.value||!("isServerNotice"in t.value)||!0!==t.value.isServerNotice)&&Pn.has(t.case??"")}async function In(e,t,r){await new Promise(((n,o)=>{if(t?.aborted)return void o(new Ze("Cancelled during backoff"));const s=new AbortController,i=setTimeout(a,e);function a(){clearTimeout(i),t?.removeEventListener("abort",c),s.abort(),n()}function c(){clearTimeout(i),s.abort(),o(new Ze("Cancelled during backoff"))}t?.addEventListener("abort",c,{once:!0});try{r?.(s.signal)?.then(a,(()=>{}))}catch{}}))}function Tn(e,t){return e.length===t.length&&e.every(((e,r)=>{const n=t[r];return void 0!==n&&e.byteLength===n.byteLength&&e.every(((e,t)=>e===n[t]))}))}function An(e){const{connectCode:t,connectCodeName:r,...n}=e;return void 0===r?n:{...n,connectCode:r}}async function $n(e){const{ctx:t,checkpointHandler:r,runOptions:n,requestId:o,hooks:s,cancellation:i}=e,a=e.originalRequestId??o;let l=kn;const u=async(r,o,s,i,a)=>{if(s||(l=kn),void 0!==e.backoff)return void await e.backoff(r,o,i.retryAfterMs);if(!0===i.rateLimit&&void 0!==i.retryAfterMs){const n=i.retryAfterMs+1e3*Math.random();return e.logging&&Sn.info(t,`[${e.logging.tag}] Waiting out a rate limit`,{attempt:r,retryAfterMs:i.retryAfterMs,selectedDelayMs:n}),void await In(n,o)}const c=s?function(e,t){const r=Math.min(3e5,3*e);return t??kn+(r-kn)*Math.random()}(l,n.fixedRetryDelayMs):function(e,t,r){const n=t?100:kn,o=r??Math.min(n*2**e,_n);return o+(void 0===r?.2*o*Math.random():0)}(r,n.isRunningInTest,n.fixedRetryDelayMs),u=function(e,t){if(void 0===t||t<=e)return e;const r=Math.min(t,_n),n=Math.min(r+.2*r*Math.random(),_n);return Math.max(e,n)}(c,i.retryAfterMs);u!==c&&e.logging&&Sn.info(t,`[${e.logging.tag}] Waiting for Retry-After`,{attempt:r,retryAfterMs:i.retryAfterMs,computedDelayMs:c,selectedDelayMs:u,endlessRetries:s}),s&&(l=c,e.logging&&Sn.info(t,`[${e.logging.tag}] Endless retry delay selected`,{selectedDelayMs:u,attempt:r,retryCategory:i.countAsServerError?"server":"transport",endlessRetries:s}));const{retryWake:d}=n;await In(u,o,void 0===d?void 0:e=>d({error:a,delayMs:u,waitEnded:e}))};let d,h,p,f,m,g,w=e.state,y=e.action,v=0,b=o,S=0,k=0,_=!1,C=0;const E=()=>{_&&(n.onConnectionStateChange?.({state:"connected"}),_=!1)},x=(e,t)=>()=>{e===v&&("progress"===t?m=!0:g=!0,E())},P=e=>({handleCheckpoint:async(t,n,o)=>{e===v&&(m=!0),await r.handleCheckpoint(t,n,o),e===v&&(d=n,h=o?.resumeEligibility??"eligible",E())},getLatestCheckpoint:()=>r.getLatestCheckpoint()});for(;;){if(t.canceled)throw i.toCancelledError(void 0,b);if(d=void 0,h=void 0,m=!1,g=!1,s.beginAttempt?.({attempt:v,originalRequestId:a}),v>0?(b=(0,ye.C)(),await(n.onRetryStarting?.(v,{actionCase:y.action.case,conversationState:w,isResume:"resumeAction"===y.action.case,attemptRequestId:b})),e.logging&&Sn.info(t,`[${e.logging.tag}] Retrying attempt ${v}`,{attempt:v,actionCase:y.action.case,requestId:b,originalRequestId:a}),"resumeAction"===y.action.case&&(await(n.onRetryResuming?.({checkpointState:w,nextAttempt:v,reason:"resume_action"})),e.logging&&Sn.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:v,reason:"resume_action"}))):(e.logging&&Sn.info(t,`[${e.logging.tag}] Initial request`,{attempt:v,actionCase:y.action.case,requestId:b}),!0===e.notifyInitialResume&&"resumeAction"===y.action.case&&(await(n.onRetryResuming?.({checkpointState:w,nextAttempt:v,reason:"resume_action"})),e.logging&&Sn.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:v,reason:"resume_action"}))),t.canceled)throw i.toCancelledError(void 0,b);try{return await s.runAttempt({state:w,action:y,checkpointHandler:P(v),attempt:v,attemptRequestId:b,notifyConnected:E,notifyApplicationProgress:x(v,"progress"),notifyApplicationActivity:x(v,"activity")}),E(),void(e.logging&&Sn.info(t,`[${e.logging.tag}] Request successful`,{attempt:v,actionCase:y.action.case,requestId:b,originalRequestId:a}))}catch(r){if(!0===i.shortCircuit?.(r))throw i.toCancelledError(r,b);const o=!0===n.endlessRetries?.(),E=e.nowMs?.()??Date.now();(m||g)&&(p=void 0,f=void 0);const x=void 0===p?void 0:E-p,P=void 0===f?void 0:E-f;let T=s.classify(r,{attempt:v,attemptRequestId:b,originalRequestId:a,serverErrorRetries:S,transportErrorRetries:k,stallRetryElapsedMs:x,rateLimitRetryElapsedMs:P,endlessRetries:o});if("retry"===T.action){const n=!("resumeAction"===y.action.case&&w.pendingToolCalls.length>0)&&("resumeAction"===y.action.case||!0===e.noProgressGuardCountsReplays&&v>0);void 0!==d?C=0:n&&m&&(C++,C>=2&&(e.logging&&Sn.warn(t,`[${e.logging.tag}] Resume attempts are streaming but not producing checkpoints; stopping automatic resume`,{noProgressResumeFailures:C,attempt:v,requestId:b,originalRequestId:a,errorName:r instanceof Error?r.name:typeof r}),T={action:"throw",error:new Ge("Agent turn stopped after repeated resume attempts made no progress",{cause:r instanceof Error?r:void 0,requestId:b,displayInfo:{title:"Agent stopped retrying",detail:"The connection was interrupted repeatedly without saving progress, so the agent stopped to avoid repeating the same work. Retry to continue from the last saved state.",isRetryable:!0}}),transportFailureKind:T.transportFailureKind}))}const A={...void 0===T.transportFailureKind?{}:{transportFailureKind:T.transportFailureKind},...void 0===e.loop?{}:{loop:e.loop}},$=e.logging?.diagnostics?.(r);if(e.logging){const e="retry"===T.action?`RETRY (countAsServerError=${T.countAsServerError}, countAsTransportError=${T.countAsTransportError})`:`THROW ${T.error.kind}`;Sn.warn(t,`[AGENT_ERROR_DIAGNOSTICS] requestId=${b} originalRequestId=${a} decision=${e}`,{decision:e,willRetry:"retry"===T.action,enableAgentRetries:n.enableAgentRetries??!1,endlessRetries:o,isRunningInTest:n.isRunningInTest??!1,serverErrorRetries:S,transportErrorRetries:k,attempt:v,requestId:b,originalRequestId:a,...A,...$})}if("throw"===T.action){if(0===v){const r={attempt:0,actionCase:y.action.case,error:T.error,requestId:b,originalRequestId:a,enableAgentRetries:!0===n.enableAgentRetries,endlessRetries:o,stallAborted:!1,abortSources:[]};try{await(n.onErrorNotRetried?.(s.buildNonRetriedErrorInfo?.(r)??r))}catch(r){e.logging&&Sn.warn(t,`[${e.logging.tag}] onErrorNotRetried callback failed`,{error:String(r),requestId:b,originalRequestId:a})}}throw e.logging&&Sn.warn(t,`[${e.logging.tag}] Error not retryable`,{...A,...$,attempt:v,actionCase:y.action.case,requestId:b,originalRequestId:a,errorName:T.error.name,...!0===e.logging.includeErrorObjects?{error:T.error}:{},serverErrorRetries:S,transportErrorRetries:k}),T.error}const M=v+1;if("ineligible_terminal_turn"===h)return void(e.logging&&Sn.warn(t,`[${e.logging.tag}] Terminal checkpoint received before retryable error; completing without automatic resume`,{errorName:r instanceof Error?r.name:typeof r,errorMessage:r instanceof Error?r.message:String(r)}));!0!==T.immediate&&(n.onConnectionStateChange?.({state:"reconnecting",attempt:M,trigger:{...A,...s.reconnectTrigger?.(r,T,{originalRequestId:a,failedAttemptRequestId:b,nextAttempt:M})??{originatingRequestId:a,attemptRequestId:b}}}),_=!0),T.countAsServerError&&S++,T.countAsTransportError&&k++,!0===T.stall?p??=E:p=void 0,!0===T.rateLimit?f??=E:f=void 0,v=M;try{Cn.increment(t,1,{attempt:En(M),reason:xn(T),loop:e.loop??"nal"})}catch{}void 0!==d&&(I=d,Tn((R=w).turns,I.turns)&&Tn(R.rootPromptMessagesJson,I.rootPromptMessagesJson)||(l=kn),w=d,y=new c.QFf({action:{case:"resumeAction",value:new c.qKo}})),s.onRetryCommitted?.(),!0===T.immediate||!0===T.noBackoff&&void 0===T.retryAfterMs||await u(v,t.signal,o,T,r)}}var R,I}var Mn=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Dn=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const On=(0,b.cF)(Symbol("agentStreamMetadata"),void 0),Fn=(0,d.h)("@anysphere/agent-client:abort"),Nn=(0,d.h)("@anysphere/agent-client:retry"),Ln=(0,d.h)("@anysphere/agent-client:request-context-blob");async function jn({ctx:e,action:t,resources:r,blobStore:n,options:o,source:s,transportMode:i,notifyBytes:a}){!0===o.omitRequestContextFileContents&&function(e){const t=Wr(e);if(void 0===t)return;const r=t.requestContext;void 0!==r&&zr(r)&&(t.requestContext=Vr(r));const n=e.requestContextParts,o=n?.dynamicContext;void 0!==n&&void 0!==o&&zr(o)&&(e.requestContextParts=Gr(n,{dynamicContext:Vr(o)}))}(t);try{const s=await qr({ctx:e,action:t,resources:r,blobStore:n,mode:i??o.requestContextBlobTransportMode??"legacy",maxBlobBytes:o.requestContextBlobMaxBytes??Lr,maxInlineDynamicBytes:o.requestContextDynamicInlineMaxBytes??1048576,notesSessionId:o.conversationId});if(!0===a){const e=function({prepared:e,parts:t}){return"prepared"===e.kind?un(e,{dynamicByteLength:e.dynamicByteLength}):"already_prepared"===e.kind&&void 0!==t?un(t):void 0}({prepared:s,parts:t.requestContextParts});void 0!==e&&o.onRequestContextBytes?.(e)}}catch(r){t.requestContextParts=void 0,Ln.warn(e,"Failed to prepare request context blob; using legacy fallback",{actionCase:t.action.case,errorName:r instanceof Error?r.name:typeof r,source:s})}}const Un=e=>{const t=[];switch(t.push(e.message.case),e.message.case){case"conversationAction":t.push(e.message.value.action.case);break;case"execClientMessage":case"execClientControlMessage":case"kvClientMessage":case"execServerMessage":case"execServerControlMessage":t.push(e.message.value.message.case);break;case"interactionResponse":t.push(e.message.value.result.case);break;case"interactionUpdate":switch(t.push(e.message.value.message.case),e.message.value.message.case){case"partialToolCall":case"toolCallCompleted":case"toolCallStarted":t.push(e.message.value.message.value.toolCall?.tool.case);break;case"toolCallDelta":t.push(e.message.value.message.value.toolCallDelta?.delta.case)}break;case"interactionQuery":t.push(e.message.value.query.case)}return t.filter((e=>void 0!==e)).join(":")};function Bn(e){if(e instanceof Error)return`${e.name}: ${e.message}`;if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e||"bigint"==typeof e)return String(e);if(null==e)return String(e);try{const t=JSON.stringify(e);return"string"==typeof t?t:"unserializable error"}catch{return"unserializable error"}}async function Wn(e,t,r){for await(const n of t)switch(n.event.case){case"stdout":await r.sendUpdate(e,l.shellOutputDelta({case:"stdout",value:new fe.o0({data:n.event.value.data})}));break;case"stderr":await r.sendUpdate(e,l.shellOutputDelta({case:"stderr",value:new fe.Db({data:n.event.value.data})}));break;case"exit":await r.sendUpdate(e,l.shellOutputDelta({case:"exit",value:new fe.vb({code:n.event.value.code,aborted:n.event.value.aborted})}))}}function Hn(e){return e instanceof Error?e.name:void 0}class qn{constructor(e,t,r={}){this.client=e,this.endpointUrl=t,this.options=r,this.hasStartedStream=!1}async run(e,t,r,n,o,s,i,a,c,l,d){const h={stack:[],error:void 0,hasError:!1};try{if(void 0!==d.maxSteps)throw new Je(d.maxSteps);const g=!0===d.omitRequestContextFileContents?function(e){const t=Kr(e);return void 0===t?e:new X(e,[K(Dr,{execute:async(e,r,n)=>function(e){if("success"!==e.result.case)return e;const t=e.result.value,r=t.requestContext;return void 0!==r&&zr(r)?new Fr._G({result:{case:"success",value:Gr(t,{requestContext:Vr(r)})}}):e}(await t.execute(e,r,n))})])}(s):s,w=!0===d.lazyFileScopedRuleBodies?new an:void 0,y=void 0===w?g:function(e,t){const r=Kr(e);return void 0===r?e:new X(e,[K(Dr,{execute:async(e,n,o)=>{const s=await r.execute(e,n,o);return void 0!==o?.execId&&t.isAllowed()?cn(s):s}})])}(g,w),v=void 0===w?d:{...d,onHeader:e=>{w.observeHeaders(e),d.onHeader?.(e)}},b=new Hr(i),S=d.generationUUID??(0,ye.C)(),k=new u,_=(m=k,p=o,f=e=>{m.observe(e.id)},{sendUpdate:(e,t)=>p.sendUpdate(e,t),query:(e,t)=>(f(t),p.query(e,t)),enqueuePostTurnEndedWork:p.enqueuePostTurnEndedWork?.bind(p),flushPostTurnEndedWork:p.flushPostTurnEndedWork?.bind(p)}),C={sources:[],abortReasonName:void 0,abortReasonMessage:void 0},E=e=>{const t=function(e){const t=gt(e);return void 0===t?void 0:qe(ft(t))}(e),r=C.sources.includes("stall_detector")||!0===t?.stallAborted,n=(o=C.sources).some((e=>"stall_detector"!==e))?"owner":o.includes("stall_detector")?"stall_detector":"none";var o;const s=function(e){const t={errorName:Hn(e)},r=wt(e);if(void 0===r)return t;const n=function(e){if(null!==e&&"object"==typeof e&&"cause"in e)return e.cause}(r),o=function(e){if(null===e||"object"!=typeof e||!("code"in e))return;const t=e.code;return"string"==typeof t||"number"==typeof t?t:void 0}(n),s=Hn(n);return{...t,underlyingConnectError:{code:r.code,codeName:be.Code[r.code],cause:void 0!==o||void 0!==s?{code:o,name:s}:void 0}}}(e),i=s.underlyingConnectError;return{relayed:t,stallAborted:r,abortOrigin:"none"===n&&r?"stall_detector":n,reading:void 0===t?{errorName:s.errorName,connectCode:i?.code,connectCodeName:i?.codeName,connectCause:i?.cause,abortSources:[...C.sources],abortReasonName:C.abortReasonName,...void 0===i?{}:{underlyingConnectError:i}}:{errorName:t.errorName,connectCode:t.connectCode,connectCodeName:t.connectCodeName,connectCause:t.connectCause,...(a=t.loop,"nal"===a||"local_loop"===a||"module"===a?{loop:t.loop}:{}),...void 0===t.transportMode?{}:{transportMode:t.transportMode}}};var a};let x=0,P=0;const R={networkPhaseStartedAt:performance.now()};try{d.onNetworkPhaseStart?.()}catch(t){Nn.warn(e,"onNetworkPhaseStart callback failed",{error:String(t)})}const I=Mn(h,(0,D.VI)(e.withName("networkPhase")),!1);e=I.ctx,await(0,D.MG)(I.span,(()=>$n({ctx:e,state:t,action:r,checkpointHandler:c,runOptions:d,requestId:S,loop:this.options.loop??"nal",notifyInitialResume:!0,logging:{...this.options.retryLogging??{tag:"nal_agent_retries",includeErrorObjects:!0},diagnostics:e=>{const{stallAborted:t,abortOrigin:r,reading:n}=E(e);return{stallAborted:t,abortOrigin:r,...An(n)}}},cancellation:{toCancelledError:()=>new Ze("Request cancelled")},hooks:{beginAttempt:()=>{C.sources=[],C.abortReasonName=void 0,C.abortReasonMessage=void 0,P=++x},runAttempt:async({state:t,action:r,checkpointHandler:o,attempt:s,attemptRequestId:i,notifyConnected:c,notifyApplicationProgress:u,notifyApplicationActivity:d})=>{const h=function(e,t,r){return{sendUpdate:async(n,o)=>{if(t===r())return e.sendUpdate(n,o);"toolCallCompleted"===o.message?.case&&Nn.warn(n,"nal.await_stall.stale_completion_dropped",{attemptGen:t,currentGen:r()})},query:async(n,o)=>{if(t!==r())throw new Ze("Stale query from previous attempt");return e.query(n,o)},enqueuePostTurnEndedWork:e.enqueuePostTurnEndedWork?t=>e.enqueuePostTurnEndedWork(t):void 0,flushPostTurnEndedWork:e.flushPostTurnEndedWork?t=>e.flushPostTurnEndedWork(t):void 0}}(_,P,(()=>x));await this.runInternal(e,t,r,n,h,y,b,a,o,l,v,i,S,k,C,c,u,d,s,R)},classify:(e,t)=>{const{abortOrigin:r,relayed:n}=E(e),o=yn(e,function(e,t,r=mn){const n=function(e){if(void 0!==e&&Number.isFinite(e))return Math.min(Math.max(Math.floor(e),1),100)-1}(e.maxRetries),o=void 0===n?r:{serverCap:n,transportCap:n};return{serverCap:o.serverCap,transportCap:!0===e.isRunningInTest?Math.min(o.transportCap,2):o.transportCap,...void 0===n?{}:{sharedCap:n},endless:t.endlessRetries,retryAllInference:!0===e.retryAllInferenceErrors}}(d,t),{...t,retriesEnabled:d.enableAgentRetries??!1,abortOrigin:r}),s=n?.transportFailureKind;return"string"==typeof(i=s)&&dn.includes(i)?{...o,transportFailureKind:s}:o;var i},buildNonRetriedErrorInfo:e=>({...e,enableAgentRetries:d.enableAgentRetries??!1,stallAborted:E(e.error).stallAborted,abortSources:[...C.sources],abortReasonName:C.abortReasonName,abortReasonMessage:C.abortReasonMessage}),reconnectTrigger:(e,t,r)=>{const{relayed:n,stallAborted:o,reading:s}=E(e),i=e instanceof ze?e:ut(e,{requestId:r.failedAttemptRequestId});return{errorClass:n?.errorName??i.name,connectCode:s.connectCode,connectCodeName:s.connectCodeName,errorCode:i.displayInfo?.errorCode,countAsServerError:t.countAsServerError,countAsTransportError:t.countAsTransportError,stallAborted:o,originatingRequestId:r.originalRequestId,attemptRequestId:r.failedAttemptRequestId,...void 0===s.transportMode?{}:{transportMode:s.transportMode},endpointUrl:this.endpointUrl}},onRetryCommitted:()=>a.reopen()}})))}catch(e){h.error=e,h.hasError=!0}finally{Dn(h)}var p,f,m}async runInternal(e,t,r,n,o,s,i,a,l,u,d,h,m,g,w,y,v,b,S,k,_="agent.request.attempt"){const C={stack:[],error:void 0,hasError:!1};try{const P=e;e=this.options.prepareAttemptContext?.(e,{attempt:S,attemptRequestId:h,originalRequestId:m,runOptions:d})??e;const R=Mn(C,(0,D.VI)(e.withName(_)),!1);R.span.setAttribute("agent.attempt",S),R.span.setAttribute("agent.request_id",h),R.span.setAttribute("agent.original_request_id",m),e=R.ctx,e=(0,D.Mf)(e,"agent.request_id",h),e=(e=(0,D.Mf)(e,"agent.original_request_id",m)).with(On,{requestId:h,rootParentRequestId:d.rootParentRequestId,modelDetails:n});const I=new Set(w.sources);let T=void 0!==w.abortReasonName||void 0!==w.abortReasonMessage;const A=(t,r)=>{if(I.has(t))return;I.add(t),w.sources=[...I];const n=(e=>{const t="string"==typeof e?.abortReasonName?e.abortReasonName:void 0,r="string"==typeof e?.abortReasonMessage?e.abortReasonMessage:void 0;if(void 0!==t||void 0!==r)return{abortReasonName:t,abortReasonMessage:r}})(r);T||void 0===n||(T=!0,w.abortReasonName=n.abortReasonName,w.abortReasonMessage=n.abortReasonMessage),Fn.error(e,"Agent client stream abort",new Error(t),{abortSource:t,requestId:h,conversationId:d.conversationId,...r??{}})};if(e.signal.aborted){const t=e.signal.reason;A("ctx_signal_abort",he(t))}else e.signal.addEventListener("abort",(()=>{const t=e.signal.reason;A("ctx_signal_abort",he(t))}),{once:!0});const[$,O]=e.withCancel();if(a.signal?.aborted){const e=a.signal?.reason;A("conversation_action_abort",he(e)),O()}else a.signal?.addEventListener("abort",(()=>{const e=a.signal?.reason;A("conversation_action_abort",he(e)),O()}),{once:!0});if(e.canceled||$.canceled){const t={ctxCanceled:e.canceled,softCancel:$.canceled};throw A("pre_run_cancel",t),new Ze("User aborted request")}const F=(0,D.VI)(e.withName("createControlledExecManager")),N=M.fromResources(s);F[Symbol.dispose]();const[L,j]=e.withCancel(),U=new Kt,{failThresholdMs:B,advisoryThresholdMs:W}=function(e,t){const r=Ut(e?.failTimeoutMs)??3e4,n=r>0&&!0!==t?.isRunningInTest?Math.max(r,2e4):r,o=Ut(e?.advisoryTimeoutMs);return{failThresholdMs:n,advisoryThresholdMs:void 0!==o&&o>0&&(n<=0||oH,onStall:e=>{A("stall_detector",{thresholdMs:B,advisoryThresholdMs:W}),j(e)},onStallCallback:d.onStall,handlerTracker:U}),!1);let z,G,V;const K=(0,Se.Jt)(),J=new f.F8(K,(e=>(q.reset("outbound_write",Un(e)),e))),Z=Mn(C,(0,D.VI)(e.withName("writeInitialRequest")),!1);let X;const Q=function(e){return new vn.Or({mcpTools:e.map((e=>({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?ve.Value.fromJson(e.inputSchema):void 0,outputSchemaJson:void 0!==e.outputSchema?JSON.stringify(e.outputSchema):void 0})))})}(u),Y=d.requestContextBlobTransportMode??"legacy",ee=0===S&&"userMessageAction"===r.action.case&&0===t.turns.length,te="ref_only"===Y&&ee?"dual":Y,[,ne]=await Promise.all([jn({ctx:e,action:r,resources:s,blobStore:i,options:d,source:"run_request",transportMode:te,notifyBytes:0===S}),void 0===d.mintLlmGatewayCredential?Promise.resolve(void 0):Mr(d.mintLlmGatewayCredential,{signal:$.signal,isCanceled:()=>$.canceled,requestId:h})]),oe={action:r,headers:d.headers??{}},se=this.options.decorateAttempt?.(oe,d)??oe,ie=new c.Mpn({conversationState:t,action:se.action,modelDetails:n,requestedModel:d.requestedModel,clientLlmGatewayCredential:ne,mcpTools:Q,conversationGroupId:d.conversationGroupId,conversationId:d.conversationId,agentSessionId:d.agentSessionId,mcpFileSystemOptions:d.mcpFileSystemOptions,customSystemPrompt:d.customSystemPrompt,systemPromptSpec:d.systemPromptSpec,harness:d.harness,computerUseCoordinateMode:d.computerUseCoordinateMode,subagentTypeName:d.subagentTypeName,excludeWorkspaceContext:d.excludeWorkspaceContext,devRawModelSlug:d.devRawModelSlug,selectedSubagentModels:d.selectedSubagentModels,subagentModelOverrides:d.subagentModelOverrides??[],selectedSubagentModelDetails:d.selectedSubagentModelsLegacy,clientSupportsInlineImages:d.clientSupportsInlineImages,clientSupportsPreviewCard:d.clientSupportsPreviewCard,startedAsNewProject:d.startedAsNewProject,firstProjectOnboarding:d.firstProjectOnboarding,clientSupportsSendToUser:d.clientSupportsSendToUser,clientSupportsRoutedModelUpdate:d.clientSupportsRoutedModelUpdate,emitModelCallUsage:d.emitModelCallUsage,canCreateCloudSubagents:d.canCreateCloudSubagents,suppressSubagentProgressUpdateTool:d.suppressSubagentProgressUpdateTool,transcriptParentConversationId:d.transcriptParentConversationId,runId:m,nextInteractionQueryId:g.peekNext(),voiceCallNotes:d.voiceCallNotes});if(X=J.write(new pe.KS({message:{case:"runRequest",value:ie}})),$.canceled){const t={ctxCanceled:e.canceled,softCancel:$.canceled};throw A("post_write_cancel",t),Z[Symbol.dispose](),new Ze("User aborted request")}const ae={...se.headers,"x-request-id":h,"x-original-request-id":m,...Oe(d),...Ne()};z=(0,D.VI)(e.withName("handshakeEstablishment")),z.span.setAttribute("handshake.firstStreamOnClient",!this.hasStartedStream),this.hasStartedStream=!0;const ce=function(e){return e?.get(bn)}(e)?.startTransportRun(),le=void 0===ce?z.ctx:function(e,t){return e.with(bn,t)}(z.ctx,ce),ue=0===S&&void 0!==d.onTtftBreakdown?k?.networkPhaseStartedAt:void 0;let me;const ge=void 0===ce&&void 0===ue?K:(E=K,x=()=>{me=performance.now(),ce?.markFirstRequestSent(me)},{[Symbol.asyncIterator](){const e=E[Symbol.asyncIterator]();let t=!1;const r={next:()=>(t||(t=!0,x()),e.next())};return void 0!==e.return&&(r.return=t=>e.return(t)),void 0!==e.throw&&(r.throw=t=>e.throw(t)),r}}),ye=this.client.run(le,ge,{signal:L.signal,headers:ae,onHeader:e=>{H=e.get("x-cursor-agent-transport-mode")??void 0,d.onHeader?.(e)},onNetworkStarted:()=>{void 0===G&&(G=performance.now(),0===S&&(V=function(e=Zt,t=25){let r,n=0,o=0,s=e.now()+t;const i=e=>{e<=0||(o+=e,e>n&&(n=e))},a=()=>{const r=e.now();i(r-s),s=r+t,c=e.setTimeout(a,t)};let c=e.setTimeout(a,t);return{stop:()=>(void 0===r&&(e.clearTimeout(c),i(e.now()-s),r={maxLagMs:n,totalLagMs:o}),r)}}()))}}),be=performance.now();let ke;const Ce=t=>{z&&(z.span.setAttribute("handshake.firstMessageHeartbeat",t),void 0!==G&&z.span.setAttribute("handshake.preNetworkMs",G-be),z[Symbol.dispose](),z=void 0),y();const r=performance.now();ke=r,d.onFirstMessage?.(r-be),void 0!==G&&(d.onFirstMessageNetwork?.(r-G),void 0!==V&&(function(e,t){const r={loop:t.loop??"nal",transport_mode:Ht(t.transportMode),first_message_slow:t.firstMessageNetworkMs>=1e3?"true":"false"};Xt.histogram(e,t.reading.maxLagMs,r),Qt.histogram(e,t.reading.totalLagMs,r),Yt.histogram(e,t.firstMessageNetworkMs,r)}(e,{loop:this.options.loop,transportMode:H,firstMessageNetworkMs:r-G,reading:V.stop()}),V=void 0))},xe=()=>{b(),d.onFirstNonHeartbeatResponse?.(performance.now()-be,S)},Re=d.onTtftBreakdown?e=>{const t=performance.now(),r=void 0===ue||void 0===me||"server"!==e.clock?void 0:function(e){const t=Math.min(e.firstRequestTakenAt,e.firstMessageAt);return{requestBuildMs:Math.max(0,e.transportRunCalledAt-e.networkPhaseStartedAt),connectMs:Math.max(0,t-e.transportRunCalledAt),roundTripMs:Math.max(0,e.firstMessageAt-t),firstByteToOutputMs:Math.max(0,e.firstOutputAt-e.firstMessageAt),firstOutputReceivedAtEpochMs:e.firstOutputAtEpochMs}}({networkPhaseStartedAt:ue,transportRunCalledAt:be,firstRequestTakenAt:me,firstMessageAt:ke??t,firstOutputAt:t,firstOutputAtEpochMs:Date.now()});d.onTtftBreakdown(void 0===r?e:{...e,transit:r},S)}:void 0,Ie=!0===this.options.execCheckpointGate?function(e,t,r,n={}){return $e.has(r.action.action.case)?async function*(e,t,r,n){const o=[];let s=0;const i=()=>o.flatMap((e=>void 0===e.toolCallId?[]:[e.toolCallId])),a=e=>{const t=[];for(;o.length>0;){const n=o[0];if(!e&&void 0!==n.toolCallId&&!r.has(n.toolCallId))break;t.push(n.message),o.shift()}return t.length>0&&o.length>0&&(s=n.now()),t},c=()=>{const e=o.filter((e=>"execServerControlMessage"===e.message.message.case)),t=o.filter((e=>"execServerControlMessage"!==e.message.message.case));return o.splice(0,o.length,...t),e.map((e=>e.message))},l=t[Symbol.asyncIterator]();let u=!0;try{for(;;){let t;try{t=await l.next()}catch(e){throw u=!1,yield*c(),e}if(!0===t.done)return u=!1,void(yield*c());const d=t.value,h=d.message;if("execServerMessage"!==h.case&&"execServerControlMessage"!==h.case)if("conversationCheckpointUpdate"!==h.case){if(yield d,o.length>0&&n.now()-s>=n.holdMs){Te.info(e,"No checkpoint named held tool calls on a stream still delivering: handed on as they came",{toolCallIds:i().join(", "),waitedMs:Math.round(n.now()-s)});for(const e of i())r.add(e);yield*a(!0)}}else{for(const e of Pe(h.value.pendingToolCalls))r.add(e);if(yield d,o.length>0){const t=Math.round(n.now()-s),r=a(!1);r.length>0&&Te.debug(e,"Handed held execs on after their checkpoint",{count:r.length,waitedMs:t}),yield*r}}else{const t="execServerMessage"===h.case?Me(h.value):void 0,i=void 0!==t&&!r.has(t);if(0===o.length&&!i){yield d;continue}if(0===o.length&&(s=n.now()),o.push({message:d,toolCallId:i?t:void 0}),i){Te.debug(e,"Held a tool call's exec for the checkpoint that names it",{toolCallId:t});try{n.onHeld?.(t)}catch(t){Te.warn(e,"onExecHeldForCheckpoint callback failed",{error:String(t)})}}}}}catch(e){if(u){u=!1;try{await(l.return?.())}catch{}}throw e}finally{o.length>0&&Te.info(e,"The stream ended before a checkpoint named held tool calls: dropped, never run",{toolCallIds:i().join(", ")}),u&&await(l.return?.())}}(e,t,Pe(r.state.pendingToolCalls),{holdMs:n.holdMs??5e3,now:n.now??(()=>performance.now()),onHeld:n.onHeld}):t}(e,ye,{action:se.action,state:t},void 0===this.options.onExecHeldForCheckpoint?{}:{onHeld:this.options.onExecHeldForCheckpoint}):ye,Ae=!0===this.options.execAfterCheckpointStored||!0===this.options.execCheckpointGate?new Ee(void 0===this.options.onExecHeldForCheckpointStore?{}:{onExecHeld:this.options.onExecHeldForCheckpointStore}):void 0,{interactionStream:De,execStream:Fe,checkpointStream:Le,kvStream:je,done:Ue}=function(e,t,r,n,o,s,i,a,c,l){const u=(0,Se.Jt)(),d=(0,Se.Jt)(),h=(0,Se.Jt)(),p=(0,Se.Jt)();let f=!1,m=!1,g=!1;return{interactionStream:u,execStream:d,checkpointStream:h,kvStream:p,done:async function(){let w,y,v=!1,b=!1;try{for await(const o of t){if(void 0!==o.ttftBreakdown){const t=o.ttftBreakdown;try{a?.({serverFirstTokenMs:t.serverFirstTokenMs,preStreamSetupMs:t.preStreamSetupMs,waitForFirstEventMs:t.waitForFirstEventMs,providerTtftMs:t.providerTtftMs,slowPoolWaitMs:t.slowPoolWaitMs,...void 0===t.clientPrepMs?{}:{clientPrepMs:t.clientPrepMs},...void 0===t.clientPrepLegs?{}:{clientPrepLegs:we(t.clientPrepLegs)},...void 0===t.preHandlerMs?{}:{preHandlerMs:t.preHandlerMs},clock:t.clientClock?"client":"server"})}catch(t){Nn.warn(e,"onTtftBreakdown callback failed",{error:String(t)})}}const t="interactionUpdate"===o.message.case&&"heartbeat"===o.message.value.message.case;if(f||(f=!0,n(t)),t)r.onServerSentHeartbeat(),r.reset("inbound_message","heartbeat");else{if(!m){m=!0;try{i?.()}catch(t){Nn.warn(e,"onFirstNonHeartbeatMessage callback failed",{error:String(t)})}}if(!g&&"interactionUpdate"===o.message.case&&Rn(o.message.value)){g=!0;try{l?.()}catch(t){Nn.warn(e,"onFirstModelOutput callback failed",{error:String(t)})}}r.reset("inbound_message",Un(o))}if("interactionUpdate"===o.message.case&&"turnEnded"===o.message.value.message.case&&(v=!0),"interactionUpdate"!==o.message.case&&"interactionQuery"!==o.message.case||await u.write(o.message).catch((()=>{})),"execServerMessage"!==o.message.case&&"execServerControlMessage"!==o.message.case||await d.write(o.message.value),"conversationCheckpointUpdate"===o.message.case){const e=v?"ineligible_terminal_turn":"eligible";"ineligible_terminal_turn"===e&&(b=!0);const t=c?.noteRouted(o.message.value);try{await h.write({checkpoint:o.message.value,metadata:{resumeEligibility:e},...void 0===t?{}:{onSettled:t}})}catch(e){throw t?.(),e}}"kvServerMessage"===o.message.case&&await p.write(o.message.value)}r.onStreamEnded()}catch(e){w=e}finally{if(y=w,v&&b&&void 0!==w&&!o?.aborted&&!s?.aborted&&function(e){const t=e instanceof ze?e:ut(e);return t instanceof Ge&&function(e){return!0===e.isTransport||(e.cause instanceof Error?kt(e.cause):_t(e.message))}(t)}(w)&&(Nn.debug(e,"Ignoring transport close after terminal agent stream",{caughtError:w instanceof Error?`${w.name}: ${w.message}`:String(w)}),r.onStreamEnded(),y=void 0),v||o?.aborted||s?.aborted){if(!v&&!o?.aborted){const t=`Stream ended without turnEnded, abort signals: signal.aborted=${o?.aborted}, parentSignal.aborted=${s?.aborted}; firstMessageFired=${f}`;Nn.warn(e,t)}}else{const t="Stream ended without turnEnded — connection likely dropped mid-stream";void 0===w?(Nn.warn(e,t),y=new Ge(t,{isTransport:!0})):w instanceof Error&&"[aborted] aborted"===w.message?(Nn.warn(e,`${t}; retrying caught [aborted] aborted error`),y=new Ge(t,{cause:w,isTransport:!0})):Nn.warn(e,`${t}; caught non-retriable stream error, rethrowing as-is`,{caughtError:Bn(w)})}u.close(),d.close(),h.close(),p.close()}if(void 0!==y)throw y}()}}(e,Ie,q,Ce,$.signal,e.signal,xe,Re,Ae,v);let Be;const We={handleCheckpoint:async(e,t,r)=>{await l.handleCheckpoint(e,t,r),Be=r?.resumeEligibility??"eligible"},getLatestCheckpoint:()=>l.getLatestCheckpoint()};Z[Symbol.dispose]();const He=5e3;let qe;const Ve=()=>{qe=setTimeout((()=>{J.write(new pe.KS({message:{case:"clientHeartbeat",value:new pe.kA}})).then((()=>q.onClientSentHeartbeat()),(()=>{})),Ve()}),He)},Je=()=>{void 0!==qe&&(clearTimeout(qe),qe=void 0)};Ve();try{let t;if("shellCommandAction"===r.action.case&&r.action.value.execId){const n=r.action.value,i=new fe.a({command:n.shellCommand?.command||"",parsingResult:new fe.HO,skipApproval:!0}),a=s.get(re).execute(e,i,{execId:n.execId}),c=new $r(De,o,new f.F8(J,(e=>new pe.KS({message:{case:"interactionResponse",value:e}}))),q);t={run:async e=>{await Promise.all([U.track("handleShellStream",Wn(e,a,o)),U.track("interactionController",c.run(e))])}}}else{const e=new $r(De,o,new f.F8(J,(e=>new pe.KS({message:{case:"interactionResponse",value:e}}))),q);t={run:async t=>{await U.track("interactionController",e.run(t))}}}void 0!==X&&await Promise.race([X,Ue.catch((()=>{}))]);const c=new f.F8(J,(e=>{if((0,ve.isMessage)(e,p.yT))return new pe.KS({message:{case:"execClientMessage",value:e}});if((0,ve.isMessage)(e,p.$Y))return new pe.KS({message:{case:"execClientControlMessage",value:e}});throw new Error(`Unknown exec message (type: ${(0,ve.isMessage)(e)?e.getType().typeName:typeof e})`)})),l=new Lt(Fe,c,N,Ae),S=new de(je,new f.F8(J,(e=>new pe.KS({message:{case:"kvClientMessage",value:e}}))),i,{beforeGetBlob:async(e,t)=>i.persistForRemoteRead(e,t)}),k=new _e(Le,We,e);let _,C;const E={promise:new Promise(((e,t)=>{_=e,C=t})),resolve:_,reject:C};$.canceled?(E.resolve(),De.close()):$.signal.addEventListener("abort",(()=>{E.resolve(),De.close()}),{once:!0}),l.run($).then(E.resolve).catch(E.reject);const x=Promise.allSettled([U.track("streamSplitter",Ue.finally((()=>{Je(),a.close(),c.close()}))),U.track("execHandler",E.promise),t.run(e),U.track("checkpointController",k.run()),U.track("kvHandler",S.run(e)),U.track("conversationActionManager",a.run(e,{write:async t=>{await jn({ctx:e,action:t,resources:s,blobStore:i,options:d,source:"queued_action"}),await J.write(new pe.KS({message:{case:"conversationAction",value:t}}))}}))]);let R,I;const T={promise:new Promise(((e,t)=>{R=e,I=t})),resolve:R,reject:I};x.then(T.resolve).catch(T.reject),e.canceled?T.reject(new Ze("User aborted request")):e.signal.addEventListener("abort",(()=>T.reject(new Ze("User aborted request"))),{once:!0});const A=()=>{e.signal.aborted?j():function(e){const t=e.lingerMs??6e3;return new Promise((r=>{let n=!1;const o=e=>{n||(n=!0,clearTimeout(s),r(e))},s=setTimeout((()=>o("linger_timed_out")),t);e.done.then((()=>o("stream_ended")),(()=>o("stream_ended")))}))}({done:Ue,lingerMs:d.softCancelLingerMs}).then((t=>{Nn.info(e,"Soft-cancel transport linger finished",{outcome:t,requestId:h}),j()}))};$.canceled?(A(),T.reject(new Ze("User aborted request"))):$.signal.addEventListener("abort",(()=>{A(),T.reject(new Ze("User aborted request"))}),{once:!0});const M=await T.promise,D=M[0],O=M[1],F=M[3],L=e=>e.reason instanceof Error?`${e.reason.name}: ${e.reason.message}`:String(e.reason);if("rejected"===F.status)throw new Ke("Checkpoint persistence failed",{cause:F.reason instanceof Error?F.reason:void 0,requestId:h,displayInfo:{title:"Checkpoint persistence failed",detail:L(F),isRetryable:!1}});const B="ineligible_terminal_turn"===Be;if(B){const t={..."rejected"===D.status?{streamSplitter:L(D)}:{},..."rejected"===O.status?{execHandler:L(O)}:{}};Object.keys(t).length>0&&Nn.debug(e,"Ignoring handler errors after terminal checkpoint",t)}if("rejected"===D.status&&!B)throw D.reason;if("rejected"===O.status&&!B)throw O.reason;$.canceled||await this.processUnprocessedMessages(P,a,We,n,o,s,i,u,d,h,m,g,w,q,y,v,b)}finally{Je(),V?.stop(),V=void 0,z&&(z[Symbol.dispose](),z=void 0)}}catch(e){C.error=e,C.hasError=!0}finally{Dn(C)}var E,x}async processUnprocessedMessages(e,t,r,n,o,s,i,a,l,u,d,h,p,f,m,g,w){if(!t.hasUnprocessedMessages())return;const y=t.getUnprocessedUserMessages(),v=r.getLatestCheckpoint();if(!v||0===y.length)return;const b=y[0];t.markMessageAsProcessed(b),t.resetStream(),f[Symbol.dispose]();const S=r.getLatestCheckpoint();try{await this.runInternal(e,v,new c.QFf({action:{case:"userMessageAction",value:new c.Vtf({userMessage:b})}}),n,o,s,i,t,r,a,l,u,d,h,p,m,g,w,0,void 0,"agent.request.queuedMessage")}catch(e){throw S===r.getLatestCheckpoint()&&t.requeueMessage(b),e}}}const zn="cursor-ide-browser",Gn="cursor-dev-control",Vn="custom-user-tools",Kn=new Set(["cursor-app-control","cursor-backend-control","cursor-browser-extension",zn,Gn,Vn,"fsd","cursor-subscriptions","cursor-cloud","suggestions","Cursor Slack Tools","Cursor Automation Tools"]);function Jn(e){return!Kn.has(e)}const Zn=new Set([Gn,zn]);function Xn(e){if(void 0!==e&&0!==Object.keys(e).length)try{return JSON.stringify(e)}catch{return}}function Qn(e){return{name:e.toolName,description:e.description,arguments:e.inputSchema,outputSchema:e.outputSchema,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId}}var Yn;function eo(e){return void 0===e||void 0===e.serverIdentifiers}function to(e){switch(e.kind){case"ready":return void 0===e.toolListError?"connected":"error";case"requires_authentication":return"needsAuth";case"error":return"error";default:return"loading"}}(0,b.cF)(Symbol("mcpHostFilledArguments"),[]),function(e){e.Snapshots="cursor_mcp_lease_snapshot_store",e.Status="cursor_mcp_lease_server_status",e.Settings="cursor_mcp_lease_settings",e.Providers="cursor_mcp_lease_providers",e.Unknown="cursor_mcp_lease_unknown"}(Yn||(Yn={}));const ro=G("mcp-executor",(e=>new H(e,Q("mcpArgs"),Y("mcpResult"))),((e,t)=>{t.register(new A(e,te("mcpArgs"),ee("mcpResult")))})),no=G("list-mcp-resources-executor",(e=>new H(e,Q("listMcpResourcesExecArgs"),Y("listMcpResourcesExecResult"))),((e,t)=>{t.register(new A(e,te("listMcpResourcesExecArgs"),ee("listMcpResourcesExecResult")))})),oo=G("read-mcp-resource-executor",(e=>new H(e,Q("readMcpResourceExecArgs"),Y("readMcpResourceExecResult"))),((e,t)=>{t.register(new A(e,te("readMcpResourceExecArgs"),ee("readMcpResourceExecResult")))})),so=G("mcp-state-executor",(e=>new H(e,Q("mcpStateExecArgs"),Y("mcpStateExecResult"))),((e,t)=>{t.register(new A(e,te("mcpStateExecArgs"),ee("mcpStateExecResult")))}));var io=r("../proto/dist/generated/agent/v1/subagent_exec_pb.js");(0,b.cF)(Symbol("pendingSubagentReplay"),void 0);class ao extends Error{constructor(e,t){super(e),this.name="SubagentHostError",this.agentId=t?.agentId,this.cause=t?.cause}}const co=G("subagent-executor",(e=>new H(e,Q("subagentArgs"),Y("subagentResult"))),((e,t)=>{t.register(new A(e,te("subagentArgs"),ee("subagentResult")))})),lo=G("subagent-await-executor",(e=>new H(e,Q("subagentAwaitArgs"),Y("subagentAwaitResult"))),((e,t)=>{t.register(new A(e,te("subagentAwaitArgs"),ee("subagentAwaitResult")))})),uo=G("force-background-subagent-executor",(e=>new H(e,Q("forceBackgroundSubagentArgs"),Y("forceBackgroundSubagentResult"))),((e,t)=>{t.register(new A(e,te("forceBackgroundSubagentArgs"),ee("forceBackgroundSubagentResult")))}));var ho=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/status.js"),po=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js");const fo=(0,be.createContextKey)(void 0,{description:"anysphere.callerContext"}),mo=(0,b.cF)(Symbol("context-rpc.expected_error"),void 0);function go(e,t,r){!0===t.get(mo)?.(r)?e?.setAttribute("rpc.expected_error",!0):(e?.recordException(yo(r)),e?.setStatus({code:ho.s.ERROR,message:r instanceof Error?r.message:"RPC call failed"})),e?.end()}function wo(e){return null!==e&&"object"==typeof e&&Symbol.asyncIterator in e}function yo(e){return e instanceof Error?e:new Error(String(e))}function vo(e,t,r){return{[Symbol.asyncIterator](){const n=e[Symbol.asyncIterator]();let o=!1;const s=e=>{o||(o=!0,e?(t?.recordException(yo(e)),t?.setStatus({code:ho.s.ERROR,message:e instanceof Error?e.message:"Stream failed"})):t?.setStatus({code:ho.s.OK}),t?.end(),r?.())};return{async next(){try{const e=await n.next();return e.done&&s(),e}catch(e){throw s(e),e}},return:async e=>(s(),n.return?n.return(e):{done:!0,value:void 0}),async throw(e){if(s(e),n.throw)return n.throw(e);throw e}}}}}function bo(...e){const t=new Headers;for(const r of e)r&&(r instanceof Headers?r:new Headers(r)).forEach(((e,r)=>{t.set(r,e)}));return t}function So(e,t){const{injectTraceHeaders:r=!0,extractHeaders:n}=t;return new Proxy(e,{get(e,o){const s=e[o];return"function"!=typeof s?s:(i,a,c={})=>{const l=(0,D.fR)(i.withName(`rpc.${String(o)}`),{kind:po.v.CLIENT,attributes:{"rpc.method":String(o),"rpc.system":"connect"}}),u=(0,D.fU)(l);let d;try{let o;if(r&&(o=function(e){const t=new Headers;try{const r=(0,D.fU)(e),n=r?.spanContext?.();if(n?.traceId&&n.spanId){const e=n.traceFlags??0,r=`00-${n.traceId}-${n.spanId}-${e.toString(16).padStart(2,"0")}`;t.set("traceparent",r),t.set("backend-traceparent",r),n.traceState&&t.set("tracestate",n.traceState.serialize())}}catch{}return t}(l)),n){const e=n(l);e&&(o=bo(o,e))}const i=bo(c.headers,o),{signal:p,cleanup:f}=!0===t.enableAbortSignal?function(e,t){if(void 0===t||t===e)return{signal:e};const r=new AbortController,n=()=>{r.abort(e.reason)},o=()=>{r.abort(t.reason)};e.addEventListener("abort",n,{once:!0}),t.addEventListener("abort",o,{once:!0}),e.aborted?n():t.aborted&&o();return{signal:r.signal,cleanup:()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",o)}}}(l.signal,c.signal):{signal:c.signal,cleanup:void 0};d=f;const m=(c.contextValues??(0,be.createContextValues)()).set(fo,l),g={...c,headers:i,signal:p,contextValues:m},w=s.call(e,a,g);return wo(w)?vo(w,u,d):null!==(h=w)&&"object"==typeof h&&"then"in h&&"function"==typeof h.then?Promise.resolve(w).then((e=>wo(e)?vo(e,u,d):(u?.setStatus({code:ho.s.OK}),u?.end(),d?.(),e))).catch((e=>{throw go(u,l,e),d?.(),e})):(u?.setStatus({code:ho.s.OK}),u?.end(),d?.(),w)}catch(e){throw go(u,l,e),d?.(),e}var h}}})}var ko=r("node:crypto"),_o=r("../utils/dist/workspace-paths.js");function Co(){return(0,s.join)(function(){const e=process.env.CURSOR_DATA_DIR;return e?.trim()?e:(0,s.join)((0,o.homedir)(),".cursor")}(),"projects")}function Eo(e){return(0,s.join)(Co(),(0,_o.r_)(e))}var xo=r("node:fs/promises"),Po=r("../../node_modules/.pnpm/lru-cache@11.2.5/node_modules/lru-cache/dist/esm/index.js"),Ro=r("node:fs");const Io="local";function To(e,t){return`${e}:task_progress:${t}`}function Ao(e){const t={};return"string"==typeof e.title&&e.title.trim().length>0&&(t.title=e.title),"string"==typeof e.cwd&&e.cwd.trim().length>0&&(t.cwd=e.cwd),"number"==typeof e.startTimeMs&&Number.isFinite(e.startTimeMs)&&e.startTimeMs>0&&(t.startTimeMs=String(Math.floor(e.startTimeMs))),Object.keys(t).length>0?t:void 0}function $o(e,t){e.hookApprovalRequirement=void 0!==t?new fe.In(t):void 0}function Mo(e){return e.hookApprovalRequirement}function Do(e){return e?.kind===fe.b.FORCE_PROMPT}function Oo(e){return!(!e.skipApproval||e.smartModeClassifierAllowed&&Do(e.hookApprovalRequirement))}var Fo=r("../proto/dist/generated/agent/v1/background_shell_exec_pb.js"),No=r("../shell-exec/dist/api/index.js"),Lo=r("./src/agent/native/tree-sitter.webpack.cjs"),jo=r("./src/agent/native/tree-sitter-bash.webpack.cjs");const Uo=function(e,t=console.warn){let r;return()=>{if(void 0!==r)return r;try{const t=e();t.setLanguage(jo),r=t}catch(e){if(!function(e){return"object"==typeof e&&null!==e&&"CURSOR_TREE_SITTER_STUBBED"===e.code}(e))throw e;r=null,t("shell-parser: tree-sitter natives are unavailable in this artifact; shell command analysis degrades to parsingFailed")}return r}}((()=>new Lo)),Bo=new Set(["file_redirect","heredoc_redirect","herestring_redirect","heredoc","here_string","redirect","redirection"]),Wo=new Set(["<",">",">>",">|","<>","<&",">&","&>","&>>"]);function Ho(e,t){if(null===e)return{legacy:{simpleCommands:[],hasInputRedirect:!1,hasOutputRedirect:!1},structured:{parsingFailed:!0,executableCommands:[],hasRedirects:!1,hasCommandSubstitution:!1,redirects:[]}};const r=e.parse(t),n=new WeakSet;let o=!1,s=!0;const i={simpleCommands:[],hasInputRedirect:!1,hasOutputRedirect:!1},a={parsingFailed:!1,executableCommands:[],hasRedirects:!1,hasCommandSubstitution:!1,redirects:[]},c=e=>{o=!0,a.hasRedirects=!0,s=s&&e},l=e=>{if(e&&/^\d+$/.test(e.text))return Number.parseInt(e.text,10)},u=()=>({fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}),d=(e,t)=>{const r=(e=>{const t=e.children,r=t.findIndex((e=>Wo.has(e.type)));if(-1!==r)return{operator:t[r]?.type??"",target:t.slice(r+1).find((e=>"comment"!==e.type))}})(e);if(!r)return!1;const{operator:n,target:o}=r,s=((e,t)=>{if("&>"===t||"&>>"===t)return[1,2];const r=(e=>l(e.children.find((e=>"file_descriptor"===e.type))))(e);return void 0!==r?[r]:t.startsWith("<")?[0]:[1]})(e,n),i=(e=>{if(e){if("word"===e.type)return 0===e.namedChildren.length?e.text:void 0;if("number"===e.type)return e.text;if("raw_string"===e.type){if(e.text.length<2)return;return e.text.slice(1,-1)}if("string"===e.type){const t=e.namedChildren;if(0===t.length||t.some((e=>"string_content"!==e.type)))return;return t.map((e=>e.text)).join("")}}})(o),c={operator:n,destinationFds:s,targetNodeType:o?.type??""};if(void 0!==i&&(c.targetText=i),a.redirects.push(c),">&"===n){const e=l(o),r=void 0===e?void 0:t.fdTargets.get(e);if(!(e=>"original-stdout"===e||"original-stderr"===e||"dev-null"===e)(r)){for(const e of s)t.fdTargets.set(e,"unsafe");return!1}for(const e of s)t.fdTargets.set(e,r);return!0}if("<&"===n){const e=l(o),r=void 0===e?void 0:t.fdTargets.get(e);if("dev-null"!==r){for(const e of s)t.fdTargets.set(e,"unsafe");return!1}for(const e of s)t.fdTargets.set(e,r);return!0}if(!(e=>{if(!e)return!1;if("word"===e.type)return"/dev/null"===e.text;if("raw_string"===e.type)return"'/dev/null'"===e.text;if("string"===e.type){const t=e.namedChildren;return 1===t.length&&"string_content"===t[0]?.type&&"/dev/null"===t[0].text}return!1})(o)){for(const e of s)t.fdTargets.set(e,"unsafe");return!1}for(const e of s)t.fdTargets.set(e,"dev-null");return!0},h=(e,t)=>{if(!n.has(e)){if(n.add(e),(e=>{var t;t=e.text,/(^|\s)[0-9]*<>/.test(t)||/(^|\s)[0-9]*>(\||&)?/.test(t)||/(^|\s)&>/.test(t)||/(^|\s)[0-9]+>&[0-9]+/.test(t))&&(i.hasOutputRedirect=!0),"heredoc_redirect"!==e.type&&"herestring_redirect"!==e.type||(i.hasInputRedirect=!0)})(e),"heredoc_redirect"===e.type){const{redirect:t,isAllowlistSafe:r}=(e=>{const t=(e=>{const t=e.parent;if("redirected_statement"!==t?.type)return;const r=t.children.find((e=>"command"===e.type)),n=r?.childForFieldName("name");return n?.text})(e),r=void 0!==t&&!(e=>{let t=e.parent;for(;t;){if("command_substitution"===t.type&&"string"!==t.parent?.type)return!0;t=t.parent}return!1})(e),n={operator:r?"<<":"",destinationFds:r?[0]:[],targetNodeType:e.type};return r&&(n.targetText=t),{redirect:n,isAllowlistSafe:r}})(e);return a.redirects.push(t),void c(r)}if("file_redirect"!==e.type)return a.redirects.push({operator:"",destinationFds:[],targetNodeType:e.type}),void c(!1);c(d(e,t))}};return function e(t){const r=t.type;if((e=>{const t=u();for(const r of e.children)Bo.has(r.type)&&h(r,t)})(t),Bo.has(r)&&!n.has(t)&&h(t,u()),"command"===r){const e=t.childForFieldName("name");if(null===e)a.parsingFailed=!0;else{i.simpleCommands.push(e.text);let r=e.text;const n=[];for(const e of function(e){const t=[],r=e.walk();if(r.gotoFirstChild())do{"argument"===r.currentFieldName&&t.push(r.currentNode)}while(r.gotoNextSibling());return t}(t))n.push({type:e.type,value:e.text}),r+=` ${e.text}`;a.executableCommands.push({name:e.text,args:n,fullText:r})}}if("command_name"===r||"simple_command"===r)if("command_name"!==r||i.simpleCommands.includes(t.text)){if("simple_command"===r){const e=t.firstNamedChild;e&&"command_name"===e.type?i.simpleCommands.includes(e.text)||i.simpleCommands.push(e.text):i.simpleCommands.push(t.text)}}else i.simpleCommands.push(t.text);"command_substitution"!==r&&"process_substitution"!==r||(a.hasCommandSubstitution=!0);for(const r of t.children)e(r)}(r.rootNode),o&&(a.allRedirectsAreDevNull=s),{legacy:i,structured:a}}function qo(e){return Ho(Uo(),e)}function zo(e,t){return t>0&&t=55296&&r<=56319)&&function(e){return e>=56320&&e<=57343}(e.charCodeAt(t));var r}function Go(e,t){return t>0?t>=e.length?e.length:Math.trunc(t):0}function Vo(e,t){const r=Go(e,t);return zo(e,r)?r-1:r}function Ko(e,t){const r=Go(e,t);return zo(e,r)?r+1:r}function Jo(e,t){return t>0?e.length<=t?e:e.slice(0,Vo(e,t)):""}function Zo(e,t){return t>0?e.length<=t?e:e.slice(Ko(e,e.length-Math.trunc(t))):""}let Xo,Qo;function Yo(e,t){Xo??=new TextEncoder,Qo??=new Uint8Array(65536);let r=0,n=0;for(;r{const t=(0,ts.o1)(e);try{return await(0,xo.realpath)(t)}catch{return t}},os=1048576,ss=52428800;var is=r("../proto/dist/generated/agent/v1/sandbox_pb.js");function as(e){if(!e)return;let t;return"allow"===e.default?t=is.h1.ALLOW:"deny"===e.default&&(t=is.h1.DENY),new is.RB({version:e.version,defaultAction:t,deny:e.deny??[],allow:e.allow??[],logging:e.logging?(r=e.logging,new is.Qq({decisionLogPath:r.decisionLogPath,logFormat:r.logFormat})):void 0});var r}function cs(e){const t=function(e){if(!e)return;const t={};if(1===e.version&&(t.version=1),void 0!==e.defaultAction)switch(e.defaultAction){case is.h1.ALLOW:t.default="allow";break;case is.h1.DENY:t.default="deny"}return e.deny&&e.deny.length>0&&(t.deny=e.deny),e.allow&&e.allow.length>0&&(t.allow=e.allow),e.logging&&(t.logging=function(e){const t={};return e.decisionLogPath&&(t.decisionLogPath=e.decisionLogPath),"jsonl"===e.logFormat&&(t.logFormat="jsonl"),t}(e.logging)),t}(e.networkPolicy);return t||(e.networkAccess?(0,No.T6)():(0,No.Po)())}function ls(e){switch(e){case"system":return is.Sz.SYSTEM;case"workspace":return is.Sz.WORKSPACE;default:return is.Sz.UNSPECIFIED}}function us(e){const t=function(e){switch(e){case is.Sz.SYSTEM:return"system";case is.Sz.WORKSPACE:return"workspace";case is.Sz.UNSPECIFIED:default:return}}(e.readBoundary),r=e.additionalReadPaths??[];return{readBoundary:t,additionalReadPaths:"workspace"===t&&r.length>0?r:void 0,privateTmp:e.privateTmp}}function ds(e){if(!e)return{type:"insecure_none"};switch(e.type){case is.vc.INSECURE_NONE:case is.vc.UNSPECIFIED:return{type:"insecure_none",allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies};case is.vc.WORKSPACE_READWRITE:return{type:"workspace_readwrite",networkPolicy:cs(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadwritePaths:e.additionalReadwritePaths,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict,...us(e)};case is.vc.WORKSPACE_READONLY:return{type:"workspace_readonly",networkPolicy:cs(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict,...us(e)};default:return{type:"insecure_none"}}}function hs(e){if(e)return"insecure_none"===e.type?new is.Mw({type:is.vc.INSECURE_NONE,allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies}):"workspace_readwrite"===e.type?new is.Mw({type:is.vc.WORKSPACE_READWRITE,networkAccess:(0,No.$b)(e.networkPolicy),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadwritePaths:e.additionalReadwritePaths??[],additionalReadonlyPaths:e.additionalReadonlyPaths??[],disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicy:as(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:ls(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[],privateTmp:e.privateTmp}):"workspace_readonly"===e.type?new is.Mw({type:is.vc.WORKSPACE_READONLY,networkAccess:(0,No.$b)(e.networkPolicy),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths??[],disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicy:as(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:ls(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[],privateTmp:e.privateTmp}):new is.Mw({type:is.vc.INSECURE_NONE})}function ps(e){return" "===e||"\t"===e||"\n"===e||"\r"===e||" "===e||"​"===e||"‌"===e||"‍"===e||"\ufeff"===e}function fs(e){let t="",r=!1;for(const n of e)ps(n)?r=!0:(r&&t.length>0&&(t+=" "),r=!1,t+=n);return t}function ms(e){if(0===e.length)return!1;for(let t=0;te.fullText))])]}const vs={a:"",b:"\b",e:"",E:"",f:"\f",n:"\n",r:"\r",t:"\t",v:"\v","\\":"\\","'":"'",'"':'"',"?":"?"};function bs(e){let t="",r="plain",n=0;for(;n=e.length){t+=o,n++;continue}const s=e[n+1],i=vs[s];if(void 0!==i){t+=i,n+=2;continue}const a="x"===s?e.slice(n+2).match(/^[0-9a-fA-F]{1,2}/)?.[0]:"u"===s?e.slice(n+2).match(/^[0-9a-fA-F]{1,4}/)?.[0]:"U"===s?e.slice(n+2).match(/^[0-9a-fA-F]{1,8}/)?.[0]:e.slice(n+1).match(/^[0-7]{1,3}/)?.[0],c="u"===s||"U"===s,l="x"===s||c?16:8;if(void 0!==a){const e=Number.parseInt(a,l);if(!c||e<=1114111){t+=c?String.fromCodePoint(e):String.fromCharCode(e),n+=a.length+(16===l?2:1);continue}}t+=s,n+=2}return fs(t)}function Ss({rule:e,command:t}){const r=fs(e).trim();return 0!==r.length&&(null!==function(e){const t=fs(e).trim();if(0===t.length)return"Rule cannot be empty";if(t.length>512)return"Rule cannot exceed 512 characters";if(ms(t))return"Rule cannot match every command; be more specific than wildcards alone";if(t.startsWith(":"))return"Colon rules need an executable before `:` (e.g. `aws:*s3 rm*`)";const r=gs(t);if(void 0!==r){const{executablePattern:e,argsPattern:t}=r;if(ms(e)&&(0===t.length||ms(t)))return"Rule cannot match every command; narrow the executable or argument pattern"}return null}(r)||[t.trim(),fs(t).trim(),bs(t).trim()].some((e=>function(e,t){const r=gs(e);if(void 0!==r){const{executablePattern:e,argsPattern:n}=r,o=t.indexOf(" "),s=-1===o?t:t.slice(0,o),i=-1===o?"":t.slice(o+1).trim();if((0,ws.T)(e,s)&&(0,ws.T)(n,i))return!0}return e.includes("*")?(0,ws.T)(e,t):t===e||t.startsWith(`${e} `)}(r,e))))}function ks({matchForms:e,blockedCommands:t}){const r=t.map((e=>e.trim())).filter((e=>e.length>0));if(0===r.length)return;const n=e.map((e=>e.trim())).filter((e=>e.length>0)),o=n.length>0?n:[""];for(const e of r)if(o.some((t=>Ss({rule:e,command:t}))))return e}function _s(e){return`Denied: this command was blocked by administrator policy (denylist rule: ${e}) and was not executed. It cannot be approved from this conversation; only a user can run it manually outside the agent. You may continue working on the task.`}function Cs({command:e,parsingResult:t,blockedCommands:r}){if(0===r.length)return;if(t.parsingFailed||0===t.executableCommands.length)return"Denied: this command could not be conclusively analyzed against your team's administrator command denylist, so it was blocked (fail-closed) and was not executed. It cannot be approved from this conversation; only a user can run it manually outside the agent. You may continue working on the task.";const n=ks({matchForms:ys({command:e,parsingResult:t}),blockedCommands:r});return void 0===n?void 0:_s(n)}var Es=r("../utils/dist/test-resets.js");const xs="CURSOR_FORCED_SHELL_EGRESS_NETWORK_DEFAULT",Ps="CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_DENY_DOMAINS",Rs=/\$\(|`|<\(|>\(/,Is=/[;&|]/;let Ts,As,$s,Ms;function Ds(){if(void 0===Ts){const e=(process.env.CURSOR_FORCED_SHELL_EGRESS??"").trim().toLowerCase();Ts=""!==e&&"0"!==e&&"false"!==e&&"off"!==e}return Ts}function Os(e){const t=(process.env[e]??"").trim();if(t)try{return new RegExp(t,"i"),t}catch(t){throw new Error(`[forced-egress] invalid regex in ${e}: ${String(t)}`)}}function Fs(e){return(process.env[e]??"").split(",").map((e=>e.trim())).filter((e=>e.length>0))}function Ns(e){const t=(process.env[e]??"").split(":").map((e=>e.trim())).filter((e=>e.length>0)),r=t.filter((e=>e.startsWith("/"))),n=t.length-r.length;return n>0&&console.error(`[forced-egress] ignoring ${n} non-absolute path(s) in ${e}.`),r}function Ls(){if(void 0===Ms){const e=(process.env[xs]??"").trim().toLowerCase();let t="deny";"allow"===e||"deny"===e?t=e:""!==e&&console.error(`[forced-egress] ignoring invalid value in ${xs} (expected "allow" or "deny"); using "deny".`);const r=Fs("CURSOR_FORCED_SHELL_EGRESS_DENY_DOMAINS"),n=(process.env[Ps]??"").trim();let o=r;"none"===n.toLowerCase()?o=[]:""!==n&&(o=Fs(Ps)),Ms={networkDefault:t,denyDomains:r,dependencyDenyDomains:o,allowDomains:Fs("CURSOR_FORCED_SHELL_EGRESS_ALLOW_DOMAINS"),writablePaths:Ns("CURSOR_FORCED_SHELL_EGRESS_WRITABLE_PATHS")}}return Ms}function js(e,t,r={}){const n=[Os(e),Os(t)].filter((e=>void 0!==e)).map((e=>`(?:${e})`));if(0===n.length)return null;const o=n.join("|"),s=r.anchorToExecutable?`^\\s*(?:[A-Za-z_][A-Za-z0-9_]*=[^\\s]*\\s+)*(?:${o})`:o;return new RegExp(s,"i")}function Us(e,t){const r=function(){const e=Ls();return{type:"workspace_readwrite",...e.writablePaths.length>0?{additionalReadwritePaths:e.writablePaths}:{},networkPolicy:{version:1,default:e.networkDefault,allow:["127.0.0.0/8","::1/128","localhost",...e.allowDomains],...e.denyDomains.length>0?{deny:e.denyDomains}:{}},networkPolicyStrict:!0,skipStatsigDefaults:!0,enableSharedBuildCache:!0}}(),n=(void 0===As&&(As=js("CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_DEPENDENCY_REGEX",{anchorToExecutable:!0})),As);if(null===n)return r;const o=t?.executableCommands??[];if(t?.parsingFailed||0===o.length)return r;if(Rs.test(e))return r;const s=(void 0===$s&&($s=js("CURSOR_FORCED_SHELL_EGRESS_SOURCE_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_SOURCE_REGEX")),$s);for(const e of o){const t=e.fullText?.trim()||e.name?.trim()||"";if(!t||s?.test(t)||Is.test(t))return r}return o.every((e=>n.test(e.fullText?.trim()||e.name?.trim()||"")))?function(){const e=Ls();return{type:"workspace_readwrite",...e.writablePaths.length>0?{additionalReadwritePaths:e.writablePaths}:{},networkPolicy:{version:1,default:"allow",...e.dependencyDenyDomains.length>0?{deny:e.dependencyDenyDomains}:{}},skipStatsigDefaults:!0,enableSharedBuildCache:!0}}():r}(0,Es.J)((function(){Ts=void 0,As=void 0,$s=void 0,Ms=void 0}));var Bs=r("../utils/dist/lru-cache.js");const Ws=["Desktop","Documents","Downloads","Music","Movies","Pictures","Library",".Trash"],Hs="/Volumes";function qs(e){const t=e.replace(/\/{2,}/g,"/");return t.length>1&&t.endsWith("/")?t.slice(0,-1):t}function zs(e,t){if("darwin"!==t.platform)return[];const r=qs(e),n=r.toLowerCase(),o=qs(t.homeDirectory),s="/"===r?1:r.split("/").length;return[...Ws.map((e=>`${o}/${e}`)),Hs].filter((e=>function(e,t){return e!==t&&e.startsWith(t.endsWith("/")?t:`${t}/`)}(e.toLowerCase(),n))).map((e=>{const t=e.split("/").slice(s).join("/");return`${"/"===r?"":r}/${t}`}))}var Gs=r("../utils/dist/safe-spawn-cwd.js"),Vs=r("node:util");const Ks=8388608;var Js=r("../../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/lib/index.js"),Zs=r("../../node_modules/.pnpm/jschardet@3.1.4/node_modules/jschardet/index.js");function Xs(e){let t=1,r=0;for(;;){const n=e.indexOf("\n",r);if(-1===n)return t;t++,r=n+1}}const Qs="utf8",Ys="utf8bom",ei="latin1",ti={"windows-1250":"cp1250","windows-1251":"cp1251","windows-1252":"cp1252","windows-1253":"cp1253","windows-1254":"cp1254","windows-1255":"cp1255","windows-1256":"cp1256","windows-1257":"cp1257","windows-1258":"cp1258","iso-8859-1":"iso88591","iso-8859-2":"iso88592","iso-8859-5":"iso88595","iso-8859-6":"iso88596","iso-8859-7":"iso88597","iso-8859-8":"iso88598","iso-8859-9":"iso88599","iso-8859-15":"iso885915","iso-8859-16":"iso885916",shift_jis:"shiftjis","euc-jp":"eucjp","euc-kr":"euckr","iso-2022-jp":"iso2022jp","iso-2022-kr":"iso2022kr",gb2312:"gb2312",gbk:"gbk",gb18030:"gb18030",big5:"big5","big5-hkscs":"big5hkscs","koi8-r":"koi8r","koi8-u":"koi8u",ibm855:"cp855",ibm866:"cp866",maccyrillic:"maccyrillic","x-mac-cyrillic":"maccyrillic","utf-16le":"utf16le","utf-16be":"utf16be","utf-32le":"utf32le","utf-32be":"utf32be",johab:"johab",cp949:"cp949",cp932:"cp932"};function ri(e){return ti[e]||e}function ni(e){return e.startsWith("\ufeff")?e.slice(1):e}function oi(e){const t=e.toLowerCase();return"latin-1"===t?ei:"utf-8"===t?Qs:"utf-8-bom"===t||"utf-8 bom"===t?Ys:t}function si(e){const t=[],r=[];let n=0;for(let o=e.indexOf("\n");-1!==o;o=e.indexOf("\n",n)){const s=13===e.charCodeAt(o-1);t.push(e.slice(n,s?o-1:o)),r.push(s?"\r\n":"\n"),n=o+1}return t.push(e.slice(n)),r.push(""),{lines:t,ends:r}}const ii=new Vs.TextDecoder("utf-8",{fatal:!1}),ai=new Vs.TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),ci="�";function li(e){return ii.decode(e)}function ui(e){let t=0,r=0,n=0,o=0;for(let s=0;s0?o--:n++}return r+=n,r>t}function di(e,t=1/0){let r=0,n=0;for(;r=194&&r<=223)n=2;else if(r>=224&&r<=239)n=3,224===r&&(o=160),237===r&&(s=159);else{if(!(r>=240&&r<=244))return 1;n=4,240===r&&(o=144),244===r&&(s=143)}let i=1;for(;i(1===i?s:191))break;i++}return i===n?void 0:i}function pi(e){return e<128?1:e<2048?2:e<65536?3:4}var fi;!function(e){e.CRLF="CRLF",e.LF="LF"}(fi||(fi={}));const mi=[".mp4",".webm",".mov",".avi",".mkv",".wmv",".flv",".m4v"],gi=new Set(mi),wi=new Vs.TextDecoder("utf-8",{fatal:!0}),yi=new Vs.TextDecoder("latin1"),vi=Buffer.from([239,187,191]),bi={utf16le:Buffer.from([255,254]),utf16be:Buffer.from([254,255]),utf32le:Buffer.from([255,254,0,0]),utf32be:Buffer.from([0,0,254,255])},Si=8192,ki="UTF-8",_i="windows-1252",Ci=/[^\u0000-\u007f\ufffd]/u,Ei=/(?:\p{Script=Cyrillic}\p{M}*){3,}/gu,xi=/(?:\p{Script=Greek}\p{M}*){3,}/gu,Pi=/(?:\p{Script=Hebrew}\p{M}*){3,}/gu,Ri=new Map([["windows-1251",Ei],["ISO-8859-5",Ei],["KOI8-R",Ei],["x-mac-cyrillic",Ei],["IBM866",Ei],["IBM855",Ei],["ISO-8859-7",xi],["windows-1253",xi],["windows-1255",Pi],["ISO-8859-8",Pi],["TIS-620",/(?:\p{Script=Thai}\p{M}*){3,}/gu]]),Ii=/\p{Script=Latin}\p{M}*[\p{Script=Cyrillic}\p{Script=Greek}\p{Script=Hebrew}\p{Script=Thai}]|[\p{Script=Cyrillic}\p{Script=Greek}\p{Script=Hebrew}\p{Script=Thai}]\p{M}*\p{Script=Latin}/u,Ti=/[\p{L}\p{M}]+/gu,Ai=String.raw`[\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF\u0152\u0153\u0160\u0161\u017D\u017E\u0178]`,$i=new RegExp(`[A-Za-z]${Ai}{1,2}(?!${Ai})|^${Ai}{1,2}[A-Za-z]`,"u"),Mi=new Map,Di=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".pdf",".zip",".tar",".gz",".exe",".dll",".so",".dylib",".bin",...mi]),Oi=/\.(png|jpg|jpeg|gif|webp|ico|bmp)$/i,Fi=new Set([".ps1",".psm1",".psd1"]),Ni=/[^\u0000-\u007f]/u;function Li(e){const t=e.toLowerCase(),r=t.lastIndexOf(".");return-1===r?"":t.substring(r)}function ji(e){const t=Li(e);return gi.has(t)}function Ui(e){const t=Li(e);return{encoding:"binary",lineEnding:fi.LF,isBinaryFile:!0,isImageFile:Oi.test(t),isVideoFile:gi.has(t)}}async function Bi(e,t){return(await Wi(e,t)).text}async function Wi(e,t){const{stamp:r,buf:n}=await async function(e){const t=await(0,xo.open)(e,"r");try{return{stamp:await t.stat(),buf:await t.readFile()}}finally{await t.close()}}(e),o=Gi(n);if(o.isBinaryFile)throw new Error("Binary file cannot be decoded as text");const s=ea(e,r);let i;i=t||s||o.encoding;const{text:a,encoding:c}=na(n,i),l=ni(a),u=c===Qs&&oa(n)?Ys:c;ta(e,r,u);const d=function(e,t){if(t===Ys)return oa(e);const r=bi[ri(oi(t))];return void 0!==r&&e.subarray(0,r.length).equals(r)}(n,u);if(o.lineEnding===fi.CRLF){const e=l.match(/\r\n/g)?.length??0,t=(l.match(/\n/g)?.length??0)-e;return{text:l.replaceAll("\r\n","\n"),encoding:u,bom:d,lineEnding:e>t?"CRLF":"LF"}}return{text:l,encoding:u,bom:d,lineEnding:"LF"}}async function Hi(e,t){if("binary"===t.encoding)return void Yi(e);let r;try{r=await(0,xo.stat)(e)}catch{return void Yi(e)}r.size===t.buffer.byteLength?ta(e,r,t.encoding):Yi(e)}async function qi(e,t,r,o){let s,i;try{s=r?await async function(e,t){try{return await zi(e)}catch{}const r=Li(e);if(Di.has(r))return Ui(e);try{return await async function(e){const t=new Map;let r=0;for await(const n of Xi(e)){if(r>=100)break;try{const e=await zi(n);if(!e.isBinaryFile){const r=`${e.encoding}:${e.lineEnding}`,n=t.get(r);if(n){if(n.count++,n.count>=3)return n.format}else t.set(r,{format:e,count:1})}r++}catch(e){}}let n;for(const e of t.values())(!n||e.count>n.count)&&(n=e);return n?n.format:Qi()}(t)}catch{return Qi()}}(e,r):await zi(e)}catch{const t=Li(e);s=Di.has(t)?Ui(e):Qi()}const a=()=>i??=async function(e){try{const t=await(0,xo.stat)(e);if(!t.isFile()||t.size>Ks)return;return await(0,xo.readFile)(e)}catch{return}}(e),c=ea(e,await async function(e){try{return await(0,xo.stat)(e)}catch{return}}(e));let l;if(!s.isBinaryFile){let r;o?r=oi(o):c?r=oi(c):(r=oi(s.encoding),r===Ys||Js.encodingExists(ri(r))||(r=Qs),r!==Qs&&r!==Ys||(r=await async function(e,t){const r=await t();return void 0===r||(0,n.isUtf8)(r)?e:ra(r).encoding===ei?ei:e}(r,a))),r===Qs&&!o&&function(e,t){return"win32"===process.platform&&Fi.has(Li(e))&&Ni.test(t)&&!t.startsWith("#!")}(e,t)&&(await async function(e){try{return await(0,xo.stat)(e),!1}catch(e){return e instanceof Error&&"code"in e&&"ENOENT"===e.code}}(e)||await async function(e){const t=await e();return void 0!==t&&(0,n.isAscii)(t)}(a))&&(r=Ys);const i=r===Ys||r===Qs&&!o&&await sa(e,vi),u=bi[ri(r)];i?l=vi:u&&await sa(e,u)&&(l=u),s={...s,encoding:i?Ys:r}}const u=Xs(t),d=t.includes("\r\n")?void 0:await async function(e,t){if(t.isBinaryFile)return;const r=await e();if(void 0===r||!r.includes(13))return;const n=ni(na(r,t.encoding).text);return function(e){let t=!1,r=!1;for(let n=e.indexOf("\n");-1!==n;n=e.indexOf("\n",n+1))if(13===e.charCodeAt(n-1)?t=!0:r=!0,t&&r)return!0;return!1}(n)?n:void 0}(a,s);if(void 0!==d?t=function({content:e,existing:t,defaultEnding:r}){const n=si(t),o=si(e),s=function({before:e,after:t}){const r=new Int32Array(t.length).fill(-1);let n=0;for(;n0&&i>0&&(s+1)*(i+1)<=4e6){const o=i+1,a=new Uint16Array((s+1)*o);for(let r=s-1;r>=0;r--)for(let s=i-1;s>=0;s--)a[r*o+s]=e[n+r]===t[n+s]?a[(r+1)*o+s+1]+1:Math.max(a[(r+1)*o+s],a[r*o+s+1]);for(let c=0,l=0;c=a[c*o+l+1]?c++:l++}let a=-1,c=-1;for(let n=0;n<=t.length;n++){const o=n===t.length?e.length:r[n];if(-1!==o){if(o-a==n-c)for(let e=1;e50&&/^[A-Za-z0-9+/]*={0,2}$/.test(t))try{const e=Buffer.from(t,"base64");if(e.length>0){const r=Math.floor(.5*t.length);if(e.length>=r)return e}}catch{}return Buffer.from(e,"latin1")}(t);return{lines:u,buffer:e,format:s}}const h=l?ni(t):t,p=s.encoding===Ys?Qs:s.encoding,f=p===Qs?await async function(e,t){if(!t.includes(ci))return;const r=await e();return void 0===r?void 0:function(e,t){if(!e.includes(ci)||(0,n.isUtf8)(t))return;const r=function(e){const t=[];let r=0;for(const n of ai.decode(e)){const o=n.codePointAt(0)??0;if(65533!==o){r+=pi(o);continue}const s=hi(e,r);void 0===s?(t.push(void 0),r+=3):(t.push(e.subarray(r,r+s)),r+=s)}return r===e.length?t:void 0}(t),o=e.split(ci);if(void 0===r||o.length-1!==r.length)return;const s=[];for(let e=0;e=Math.max(0,e.length-3);t--){const r=e[t];if(r<128)return e;if(r>=192){const n=r>=240?4:r>=224?3:2;return e.length-t=e.length);o+=2){if(0===e[o+1]){const r=e[o];(r>=32&&r<=126||9===r||10===r||13===r)&&t++}if(0===e[o]){const t=e[o+1];(t>=32&&t<=126||9===t||10===t||13===t)&&r++}}return t>.8*n?"UTF-16LE":r>.8*n?"UTF-16BE":null}(e)??function(e){if(e.length<8)return null;if(0===e[0]&&0===e[1]&&254===e[2]&&255===e[3])return"UTF-32BE";if(255===e[0]&&254===e[1]&&0===e[2]&&0===e[3])return"UTF-32LE";let t=0,r=0;const n=Math.min(50,Math.floor(e.length/4));for(let o=0;o<4*n&&!(o+3>=e.length);o+=4){if(0===e[o]&&0===e[o+1]&&0===e[o+2]){const r=e[o+3];(r>=32&&r<=126||9===r||10===r||13===r)&&t++}if(0===e[o+1]&&0===e[o+2]&&0===e[o+3]){const t=e[o];(t>=32&&t<=126||9===t||10===t||13===t)&&r++}}return t>.8*n?"UTF-32BE":r>.8*n?"UTF-32LE":null}(e);if(t)return{encoding:t,lineEnding:Ki(Js.decode(e.subarray(0,Si),ri(oi(t)))),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};if(!function(e){const t=Math.min(Si,e.length);if(0===t)return!0;for(let r=0;r=8&&137===r[0]&&80===r[1]&&78===r[2]&&71===r[3]&&13===r[4]&&10===r[5]&&26===r[6]&&10===r[7]||255===r[0]&&216===r[1]&&255===r[2]||r.length>=12&&82===r[0]&&73===r[1]&&70===r[2]&&70===r[3]&&87===r[8]&&69===r[9]&&66===r[10]&&80===r[11]||r.length>=6&&71===r[0]&&73===r[1]&&70===r[2]&&56===r[3]&&(55===r[4]||57===r[4])&&97===r[5])),isVideoFile:!1};var r,o,s;if((0,n.isUtf8)(e)&&(!e.includes(27)||!(0,n.isAscii)(e)))return{encoding:ki,lineEnding:Vi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};if(!(0,n.isUtf8)(e)&&(o=li(e),s=e.length,ui(o)||1024*di(o)<=s&&!Ci.test(o)))return{encoding:ki,lineEnding:Vi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};const i=Zs.detect(e);let a=i.confidence>.7?i.encoding:"utf-8";"ascii"===a&&(a="utf-8");const c=Ri.get(a);return void 0!==c&&(a=function(e,t,r){const n=ri(oi(t));if(!Js.encodingExists(n))return t;const o=Js.decode(e,n);return Ii.test(o)&&function(e,t,r){const n=t.match(r)?.length??0;let o=0;for(const[t]of Js.decode(e,_i).matchAll(Ti))$i.test(t)&&o++;return o>n}(e,o,r)?_i:t}(e,a,c)),a!==_i||function(e,t){const r=ri(oi(t));return!Js.getDecoder(r).write(e).includes(ci)}(e,a)||(a="utf-8"),{encoding:a??"utf-8",lineEnding:Vi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function Vi(e){let t=0,r=0;for(let n=0;n0&&13===e[n-1]?t++:r++);return Ji(t,r)}function Ki(e){const t=e.match(/\n/g)?.length??0,r=e.match(/\r\n/g)?.length??0;return Ji(r,t-r)}function Ji(e,t){return 0===e&&0===t?fi.LF:e/(e+t)*100>=5?fi.CRLF:fi.LF}async function Zi(e){const t=await(0,xo.open)(e,"r");try{const e=Buffer.allocUnsafe(Si),{bytesRead:r}=await t.read(e,0,Si,0);return e.subarray(0,r)}finally{await t.close()}}async function*Xi(e){const t=new Set(["node_modules",".git",".svn",".hg","dist","build","out",".next",".cache","coverage","__pycache__",".venv","venv",".turbo"]);try{const r=await(0,xo.readdir)(e,{withFileTypes:!0});for(const n of r){if(n.name.startsWith(".")&&".gitignore"!==n.name)continue;const r=(0,s.join)(e,n.name);n.isDirectory()?t.has(n.name)||(yield*Xi(r)):n.isFile()&&(yield r)}}catch(e){return}}function Qi(){return{encoding:Qs,lineEnding:"win32"===process.platform?fi.CRLF:fi.LF,isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function Yi(e){Mi.delete(e)}function ea(e,t){const r=Mi.get(e);if(void 0!==r)return void 0!==t&&r.size===t.size&&r.mtimeMs===t.mtimeMs?r.encoding:void Mi.delete(e)}function ta(e,t,r){if(Mi.has(e)&&Mi.delete(e),Mi.set(e,{encoding:r,size:t.size,mtimeMs:t.mtimeMs}),Mi.size<=100)return;const n=Mi.keys().next().value;void 0!==n&&Mi.delete(n)}function ra(e){try{return{text:wi.decode(e),encoding:Qs}}catch{const t=li(e);return ui(t)?{text:t,encoding:Qs}:{text:yi.decode(e),encoding:ei}}}function na(e,t){const r=oi(t);if(r===Qs||r===Ys||"ascii"===r){const t=ra(e);return r===Ys&&t.encoding===Qs?{text:t.text,encoding:Ys}:t}if(r===ei)return{text:yi.decode(e),encoding:ei};try{const t=ri(r);if(Js.encodingExists(t))return{text:Js.decode(e,t),encoding:r}}catch{}return ra(e)}function oa(e){return e.length>=vi.length&&e[0]===vi[0]&&e[1]===vi[1]&&e[2]===vi[2]}async function sa(e,t){try{return(await Zi(e)).subarray(0,t.length).equals(t)}catch{return!1}}var ia=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js");class aa{constructor({ttlMs:e,now:t=Date.now}){this.entries=new Map,this.nextSweepAtMs=0,this.ttlMs="function"==typeof e?e:aa.validated(e),this.now=t}static validated(e){if(!Number.isFinite(e)||e<=0)throw new Error(`TTL cache requires a positive ttlMs, got ${e}`);return()=>e}get(e){const t=this.entries.get(e);if(void 0!==t){if(!(t.expiresAtMs<=this.now()))return t.value;this.entries.delete(e)}}has(e){const t=this.entries.get(e);return!(void 0===t||t.expiresAtMs<=this.now()&&(this.entries.delete(e),1))}get size(){return this.entries.size}set(e,t){const r=this.now(),n=this.ttlMs();if(this.entries.set(e,{value:t,expiresAtMs:r+n}),!(r1048576?e:await async function(e,t){const r=function(e){const t=Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=Gi(t);return r.isBinaryFile?li(t):ni(na(t,r.encoding).text)}(t);return function(e,t){if(!(0,n.isUtf8)(e))return!1;const r=e.toString("utf8");return(r.startsWith("\ufeff")?r.slice(1):r)===t}(t,r)?e:async function(e,t){const r=await(da??=(0,xo.mkdtemp)((0,s.join)((0,o.tmpdir)(),"cursorignore-utf8-")).then((e=>(process.once("exit",(()=>{try{(0,Ro.rmSync)(e,{recursive:!0,force:!0})}catch{}})),e))),da),n=(0,s.join)(r,`cursorignore-${ha(e)}-${ha(t)}.txt`);if(await pa(n))return n;const i=`${n}.${process.pid}.${Date.now()}.tmp`;return await(0,xo.writeFile)(i,t,"utf8"),await(0,xo.rename)(i,n),n}(e,r)}(e,await(0,xo.readFile)(e));return la.set(e,{mtimeMs:t.mtimeMs,size:t.size,ripgrepPath:i}),i}function ma(e){return Promise.all(e.map((e=>async function(e){const t=ua.get(e);if(void 0!==t)return t;const r=fa(e).catch((()=>e)).finally((()=>{ua.delete(e)}));return ua.set(e,r),r}(e))))}(0,Es.J)((function(){la.clear(),ua.clear()}));var ga=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function wa(e){if(e.aborted)return{aborted:Promise.resolve("aborted"),[Symbol.dispose](){}};let t=()=>{};const r=new Promise((e=>{t=()=>e("aborted")}));return e.addEventListener("abort",t,{once:!0}),{aborted:r,[Symbol.dispose](){e.removeEventListener("abort",t)}}}function ya(e,{root:t,searchPaths:r=[],includeGlobs:n=[],excludeGlobs:s=[],caseSensitive:i=!1,cursorIgnoreFiles:a=[],sandboxPolicy:c={type:"insecure_none"},noIgnoreVcs:l=!1,followSymlinks:u=!1,source:d="ripwalk"}){const h=["--files","--hidden","--no-require-git","--no-config","--color=never"],p=function(e=process.env){const t=e.CURSOR_RIPWALK_THREADS?.trim();if(void 0!==t&&""!==t){const e=Number(t);if(Number.isInteger(e)&&e>=0)return 0===e?void 0:e}return Math.min(2,(0,o.availableParallelism)())}();void 0!==p&&h.push("--threads",String(p)),u&&h.push("--follow"),l&&h.push("--no-ignore-vcs"),i&&h.push("--case-sensitive");for(const e of n)h.push("--iglob",e);for(const e of s)h.push("--iglob",`!${e}`);const f=r.length>0?["--",...r]:[];let m,g=!1;const w=new Promise((e=>{m=e}));return{lines:async function*(){const r={stack:[],error:void 0,hasError:!1};try{const n=[];for(const e of await ma(a))n.push("--cursor-ignore",e);const o=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,function(e,t,r,n){const o=(0,No.spawnInSandbox)((0,No.Ko)(),t,{cwd:r},n),s=[];o.stderr?.on("data",(e=>{s.push(e)}));const i=new Promise(((e,t)=>{o.on("error",t),o.on("close",(t=>e(t??0)))}));if(i.catch((()=>{})),!o.stdout)throw new Error("No stdout from ripgrep process");const a=wa(e.signal);return{stdout:o.stdout,processExit:i,stderr:()=>Buffer.concat(s).toString(),aborted:a.aborted,[Symbol.dispose](){a[Symbol.dispose](),o.kill()}}}(e,[...h,...n,...f],t,c),!1);let s=0;const i=async function*(e){const t=new ca.StringDecoder("utf8");let r="";for await(const n of e){r+=t.write(n);const e=r.split("\n");r=e.pop()??"",e.length>0&&(yield e)}r+=t.end(),r&&(yield[r])}(o.stdout)[Symbol.asyncIterator]();e:for(;;){const t=await Promise.race([i.next(),o.aborted]);if("aborted"===t){g=!0,m(!0);break}if(t.done)break;for(const r of t.value){if(e.signal.aborted){g=!0,m(!0);break e}s++,yield r}}if(s>0);else if(!g){const e=await o.processExit;if(0!==e&&1!==e){const t=o.stderr();throw new Error(`Ripgrep failed (exit ${e}) with no results${t?`: ${t}`:""}`)}}g||m(!1)}catch(e){r.error=e,r.hasError=!0}finally{ga(r)}}(),didTimeout:w}}var va=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});let ba;function Sa(e=process.env){if(void 0!==ba)return ba;const t=e.CURSOR_RIPWALK_CACHE_TTL_MS?.trim();if(void 0!==t&&""!==t){const e=Number(t);if(Number.isFinite(e)&&e>0)return e}return 2e4}function ka({root:e,searchPaths:t=[],includeGlobs:r=[],excludeGlobs:n=[],caseSensitive:o=!1,cursorIgnoreFiles:s=[],sandboxPolicy:i={type:"insecure_none"},noIgnoreVcs:a=!1,followSymlinks:c=!1}){return JSON.stringify({root:e,searchPaths:t,includeGlobs:r,excludeGlobs:n,caseSensitive:o,cursorIgnoreFiles:s,sandboxPolicy:i,noIgnoreVcs:a,followSymlinks:c})}class _a{constructor(e=()=>Sa()){this.cache=new aa({ttlMs:e})}get size(){return this.cache.size}clear(){this.cache.clear()}delete(e){this.cache.delete(ka(e))}walk(e,t){const r=ka(t);let n,o=!1,s=!1;const i=new Promise((e=>{n=e})),a=e=>{s||(s=!0,n(e))};return{lines:async function*(){const n=this.cache.get(r);if(void 0!==n){const t={stack:[],error:void 0,hasError:!1};try{const s=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,wa(e.signal),!1),i=await Promise.race([n.linesPromise.then((e=>({type:"lines",lines:e})),(e=>({type:"error",error:e}))),s.aborted.then((()=>({type:"aborted"})))]);if("aborted"===i.type)return o=!0,void a(!0);if("lines"===i.type)return a(!1),void(yield*i.lines);this.cache.get(r)===n&&this.cache.delete(r)}catch(e){t.error=e,t.hasError=!0}finally{va(t)}}let s,i;const c={linesPromise:new Promise(((e,t)=>{s=e,i=t}))};c.linesPromise.catch((()=>{})),this.cache.set(r,c);const l=[];let u,d=!1;try{const r=ya(e,t);for await(const e of r.lines)l.push(e),yield e;if(await r.didTimeout)return o=!0,u=new Error("Ripwalk aborted before cacheable result was available"),void a(!0);d=!0}catch(e){throw u=e,e}finally{d?s?.(l):(this.cache.get(r)===c&&this.cache.delete(r),i?.(u??new Error("Ripwalk terminated before cacheable result was available"))),o||a(!1)}}.bind(this)(),didTimeout:i}}}const Ca=16777216,Ea=new Set([32,9,10,13]),xa="a path through /proc or /dev/fd",Pa={kind:"none"},Ra={kind:"stop"};function Ia(e,t){return{kind:"refused",refused:{name:e,reason:t}}}async function Ta(e){const t=await async function(e){if(void 0===await(0,xo.lstat)(e).catch((()=>{})))return Pa;if(await Ma(Buffer.from(e)))return Ia(".git",xa);const t=await(0,xo.stat)(e).catch((()=>{}));if(void 0===t)return Pa;if(!t.isFile())return Aa(e);const r=await Na(e,{whole:1048576});if("not-regular"===r.kind)return Ia(".git","not a regular file");if("bytes"!==r.kind)return Ra;const n=Buffer.from("gitdir: "),o=Ba(r.bytes);if(!o.subarray(0,n.length).equals(n)||o.length<=n.length)return Ra;const i=Ua({dir:(0,s.dirname)(e),target:Wa(o.subarray(n.length))});if(await Ma(i))return Ia(".git",xa);const a=await Aa(i);return"none"===a.kind?Ra:a}(ja(e,".git").toString());return"none"!==t.kind?t:Aa(e)}async function Aa(e){const t=await async function(e){const t=await(0,xo.lstat)(e).catch((()=>{}));if(void 0===t||t.isDirectory())return Pa;if(t.isSymbolicLink()){const t=await(0,xo.readlink)(e,{encoding:"buffer"}).catch((()=>{}));return"refs/"===t?.subarray(0,5).toString("latin1")?"valid":Pa}if(!t.isFile())return Ia("HEAD","not a regular file");const r=await Na(e,{prefix:255});if("not-regular"===r.kind)return Ia("HEAD","not a regular file");if("bytes"!==r.kind)return Pa;const n=Wa(r.bytes.subarray(0,255)).toString("latin1");if(n.startsWith("ref:")){let e=4;for(;e{}))){if(await Ma(n))return Ia("commondir",xa);const t=await Na(n,{whole:Ca});switch(t.kind){case"bytes":{if(0===t.bytes.length)return Ra;const n=Ua({dir:e,target:Wa(Ba(t.bytes))});if(await Ma(n))return Ia("commondir",xa);const o=await(0,xo.realpath)(n,{encoding:"buffer"}).catch((()=>{}));if(void 0===o)return Pa;r=o;break}case"too-large":return Ia("commondir","over the size cap");case"not-regular":return Ia("commondir","not a regular file");case"directory":case"unreadable":return Ra;default:throw new Error(`unhandled read ${String(t)}`)}}for(const e of["objects","refs"]){const t=ja(r,e);if(await Ma(t))return Ia(e,xa);if(!await La(t))return Pa}return{kind:"repository",gitDir:e,commonDir:r}}async function $a({gitDir:e,commonDir:t}){const r=[["HEAD",ja(e,"HEAD")],["config.worktree",ja(e,"config.worktree")],["config",ja(t,"config")],["info/exclude",ja(ja(t,"info"),"exclude")]];for(const[e,t]of r){if(await Ma(t))return{name:e,reason:xa};const r=await(0,xo.stat)(t).catch((()=>{}));if(void 0!==r&&!r.isDirectory()&&!await Fa(r)){if(!r.isFile())return{name:e,reason:"not a regular file"};if(r.size>Ca)return{name:e,reason:"over the size cap"}}}}async function Ma(e){if("win32"===process.platform)return!1;const t=Da(e.toString("latin1")).reverse();let r="/",n=0;for(let e=t.pop();void 0!==e;e=t.pop()){if(".."===e){r=(0,s.dirname)(r);continue}const o=(0,s.join)(r,e),i="darwin"===process.platform?o.toLowerCase():o;if(["/proc","/dev/fd"].some((e=>i===e||i.startsWith(`${e}/`))))return!0;const a=await(0,xo.readlink)(Buffer.from(o,"latin1"),{encoding:"buffer"}).catch((()=>{}));if(void 0===a){r=o;continue}if(++n>40)return!1;const c=a.toString("latin1");(0,s.isAbsolute)(c)&&(r="/"),t.push(...Da(c).reverse())}return!1}function Da(e){return e.split("/").filter((e=>""!==e&&"."!==e))}let Oa;async function Fa(e){if(!e.isCharacterDevice())return!1;Oa??=(0,xo.stat)("/dev/null").catch((()=>{}));const t=await Oa;return void 0!==t&&e.dev===t.dev&&e.ino===t.ino}async function Na(e,t){const r=Ro.constants.O_RDONLY|(Ro.constants.O_NONBLOCK??0)|(Ro.constants.O_NOCTTY??0),n=await(0,xo.open)(e,r).catch((()=>{}));if(void 0===n)return{kind:"unreadable"};try{const e=await n.stat();if(e.isDirectory())return{kind:"directory"};if(!e.isFile())return{kind:"not-regular"};if("whole"in t&&e.size>t.whole)return{kind:"too-large"};const r="whole"in t?t.whole:t.prefix,o=Buffer.alloc(Math.min(r+1,e.size+1));let s=0;for(;st.whole?{kind:"too-large"}:{kind:"bytes",bytes:o.subarray(0,s)}}catch{return{kind:"unreadable"}}finally{await n.close().catch((()=>{}))}}function La(e){return(0,xo.access)(e,Ro.constants.X_OK).then((()=>!0),(()=>!1))}function ja(e,t){const r=Buffer.isBuffer(e)?e:Buffer.from(e),n=r.toString("latin1").endsWith(s.sep)?"":s.sep;return Buffer.concat([r,Buffer.from(`${n}${t}`)])}function Ua({dir:e,target:t}){return(0,s.isAbsolute)(t.toString("latin1"))?t:Buffer.concat([ja(e,""),t])}function Ba(e){let t=e.length;for(;t>0&&(10===e[t-1]||13===e[t-1]);)t--;return e.subarray(0,t)}function Wa(e){const t=e.indexOf(0);return-1===t?e:e.subarray(0,t)}const Ha=[{stage:"prod",gitHost:"origin.cursor.com",gitCdnHost:"gitcdn.origin.cursor.com",cloneKitS3Host:"git-forge-prod-bundles.s3.us-east-1.amazonaws.com",rawUserContentHost:"raw.cursorusercontent.com",apiHost:"api.origin.cursor.com",internalHost:"origin-prod.internal.cursor.com"},{stage:"staging",gitHost:"origin-staging.cursor.com",gitCdnHost:"gitcdn.origin-staging.cursor.com",cloneKitS3Host:"git-forge-staging-bundles.s3.us-east-1.amazonaws.com",rawUserContentHost:"raw.staging.cursorusercontent.com",apiHost:"api.origin-staging.cursor.com",internalHost:"origin-staging.internal.cursor.com"},{stage:"test",gitHost:"origin-test.cursor.com",gitCdnHost:"gitcdn.origin-test.cursor.com",cloneKitS3Host:"git-forge-test-bundles.s3.us-east-1.amazonaws.com",rawUserContentHost:"raw.test.cursorusercontent.com",apiHost:"api.origin-test.cursor.com",internalHost:"origin-test.internal.cursor.com"}];function qa(e){let t=e.length;for(;t>0&&47===e.charCodeAt(t-1);)t--;const r=e.slice(0,t).replace(/\.git$/i,"");return r&&"/"!==r?r.startsWith("/")?r:`/${r}`:""}function za(e,t){const r=qa(t);return r?`${e}${r}`.toLowerCase():""}new Map(Ha.map((e=>[e.gitHost,e.apiHost]))),new Map(Ha.map((e=>[e.gitHost,e.gitCdnHost]))),new Map(Ha.map((e=>[e.gitHost,e.cloneKitS3Host]))),new Map(Ha.map((e=>[e.gitHost,e.rawUserContentHost]))),new Map(Ha.map((e=>[e.apiHost,e.gitHost]))),new Map(Ha.map((e=>[e.apiHost,e.internalHost])));const Ga=new Map;function Va(e){const t=Ga.get(e);if(void 0!==t)return t;const r=function(e){const t=e.trim();if(!t)return"";try{const e=function(e){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(e))return e;const t=`https://${e}`;try{return new URL(t),t}catch{const r=e.match(/^([^@/\s]+@)?([^:/\s]+):(.+)$/);return r?`ssh://${r[1]??""}${r[2]}/${r[3]}`:t}}(t),r=new URL(e);return za(r.hostname,r.pathname)}catch{const e=t.replace(/^(?:https?|ssh|git):\/\//i,""),r=e.indexOf("/"),n=-1===r?e:e.slice(0,r),o=-1===r?"":e.slice(r);return za(n.includes("@")?n.slice(n.lastIndexOf("@")+1):n,o)}}(e);return Ga.size>=16384&&Ga.clear(),Ga.set(e,r),r}function Ka(e){return/^origin(-[a-z0-9]+)?\.cursor\.com$/i.test(e)}(function(e){const t=Ha.find((t=>t.stage===e));if(void 0===t)throw new Error(`unknown Origin stage: ${e}`);return t})("prod").gitHost;const Ja=new Map;function Za(e){if(void 0===e)return;if(Ja.has(e))return Ja.get(e);const t=function(e){const t=e?function(e){let t=e.trim();if(""!==t){t.startsWith("git@")?t=`https://${t.slice(4).replace(":","/")}`:/^[a-z][a-z0-9+.-]*:\/\//i.test(t)&&!/^https?:\/\//i.test(t)?t=t.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"https://"):/^https?:\/\//i.test(t)||(t=`https://${t}`);try{return new URL(t)}catch{return}}}(e):void 0;if(void 0===t||!Ka(t.hostname))return;const r=qa(t.pathname).split("/").filter(Boolean),n=3===r.length&&"git"===r[0]?.toLowerCase(),o=2===r.length&&"git"!==r[0]?.toLowerCase();if(!n&&!o)return;const s=n?r[1]:r[0],i=n?r[2]:r[1];return s&&i?Object.freeze({hostname:t.hostname,owner:s,name:i}):void 0}(e);return Ja.size>=16384&&Ja.clear(),Ja.set(e,t),t}function Xa(e){return void 0!==function(e){const t=Za(e);return void 0===t?void 0:{owner:t.owner,name:t.name}}(e)}new Set(["github.com","www.github.com"]),new RegExp("^tmp-[0-9a-f]{16}$");const Qa=(0,d.h)("local-exec:git-root"),Ya=new WeakMap,ec=new Map;function tc(e,t,r){return rc(e,t,r).then((e=>"repository"===e.kind?e.root:null))}function rc(e,t,r){const n=performance.now();let o=Ya.get(t);void 0===o&&(o=new Map,Ya.set(t,o));const s=o.get(r);if(void 0!==s&&nc(s,n))return s.result;for(const[e,t]of o)nc(t,n)||o.delete(e);const i=t.guardedRootLookup,a=void 0===i?{result:ic(e,t,r,void 0),windowStart:n}:{result:oc(e,t,r,i.timeoutMs),windowStart:void 0};return void 0===a.windowStart&&a.result.then((()=>{a.windowStart=performance.now()})),o.set(r,a),a.result}function nc(e,t){return void 0===e.windowStart||t-e.windowStart<5e3}async function oc(e,t,r,n){const o=new AbortController,i=performance.now()+n,a=await(0,Nr.wj)(async function({ctx:e,gitExecutor:t,startPath:r,deadline:n,settled:o}){const i=await function(e){let t=ec.get(e);if(void 0===t){t=async function(e){const t=await(0,xo.realpath)(e).catch((()=>{}));if(void 0===t)return;const r=function(){const e=(process.env.GIT_DISCOVERY_ACROSS_FILESYSTEM??"").toLowerCase();return!["","0","false","no","off"].includes(e)}()?void 0:(await(0,xo.stat)(t).catch((()=>{})))?.dev;for(let e=t;;){const t=await Ta(e);switch(t.kind){case"refused":return t.refused;case"stop":return;case"repository":return $a(t);case"none":break;default:throw new Error(`unhandled probe ${String(t)}`)}const n=(0,s.dirname)(e);if(n===e||void 0!==r&&(await(0,xo.stat)(n).catch((()=>{})))?.dev!==r)return;e=n}}(e),ec.set(e,t);const r=()=>{ec.delete(e)};t.then(r,r)}return t}(r);if(o.aborted)return{kind:"unknown",reason:"timed-out"};if(void 0!==i)return Qa.warn(e,"findGitRoot: not starting git; its answer is unknown",{adminFile:i.name,reason:i.reason}),{kind:"unknown",reason:"refused"};const a=Math.ceil(n-performance.now());return a<=0?{kind:"unknown",reason:"timed-out"}:ic(e,t,r,a)}({ctx:e,gitExecutor:t,startPath:r,deadline:i,settled:o.signal}),n).catch((t=>t instanceof Nr.MU?{kind:"unknown",reason:"timed-out"}:(Qa.warn(e,"findGitRoot: the admin file check failed; not starting git",{code:sc(t)}),{kind:"unknown",reason:"refused"}))).finally((()=>{o.abort()}));return"unknown"===a.kind&&"timed-out"===a.reason&&Qa.warn(e,"findGitRoot: the lookup ran past its bound; its answer is unknown",{timeoutMs:n}),a}function sc(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:void 0}async function ic(e,t,r,n){try{return{kind:"repository",root:(await t.exec(e,r,["rev-parse","--show-toplevel"],{...void 0===n?{}:{timeout:n},caller:"findGitRoot"})).stdout.trim()}}catch(e){return void 0!==n&&function(e){return"object"==typeof e&&null!==e&&"killed"in e&&!0===e.killed}(e)?{kind:"unknown",reason:"timed-out"}:{kind:"none"}}}async function ac(e,t,r){try{return(await t.exec(e,r,["config","--get","remote.origin.url"],{caller:"getGitRemoteUrl"})).stdout.trim()}catch{return}}function cc(e){const t=e.trim();if(""===t)return t;try{const e=new URL(t);return""===e.host?uc(t)??e.toString():(e.username="",e.password="",e.toString())}catch{return function(e){const t=e.replace(/^[\u0000-\u0020]+|[\u0000-\u0020]+$/g,"").replace(/[\t\n\r]/g,""),r=t.indexOf(":"),n=t.slice(0,r);if(r<0||!/^[A-Za-z][A-Za-z0-9+.-]*$/.test(n))return;const o=t.slice(r+1),s=lc.has(n.toLowerCase());let i;if(s)i=o.replace(/^[/\\]+/,"");else{if(!o.startsWith("//"))return;i=o.slice(2)}const a=i.search(s?/[/?#\\]/:/[/?#]/),c=a<0?i.length:a,l=i.slice(0,c),u=l.lastIndexOf("@");return u<0?void 0:`${t.slice(0,t.length-i.length)}${l.slice(u+1)}${i.slice(c)}`}(t)??uc(t)??t}}const lc=new Set(["ftp","file","http","https","ws","wss"]);function uc(e){const t=e.indexOf("/"),r=t<0?e:e.slice(0,t),n=r.indexOf(":"),o=r.lastIndexOf("@",r.lastIndexOf(":"));if(!(n<0||o<0||r.indexOf("@")`/${s.posix.relative(e,t)}`))}var pc=r("../../node_modules/.pnpm/picomatch@4.0.5/node_modules/picomatch/index.js");function fc(e,t){return e.some((e=>{return"*"===e.url.trim()?(e.patterns??[]).some((e=>wc(e.pattern,t))):!((r=e.url).includes("://")||r.includes("github.com")||r.includes("gitlab.com")||r.includes("bitbucket.org")||r.includes("@"))&&wc(e.url,t);var r}))}function mc(e,t,r){return gc(e.url,t)&&(e.patterns??[]).some((e=>wc(e.pattern,r)))}function gc(e,t){return e.includes("*")?"*"===e.trim()||function(e,t){const r=e.trim();return!!wc(r,t)||!!r.startsWith("*/")&&wc(`**/${r.slice(2)}`,t)}(kc(e),kc(t)):kc(e)===kc(t)}function wc(e,t){const r=e.trim();return!("."!==t&&""!==t||"**"!==r&&"**/*"!==r)||function(e){const t=bc.get(e);if(void 0!==t)return t;let r;try{const t=pc(e,{dot:!0});r=r=>{try{return t(r)}catch{return e===r}}}catch{r=t=>e===t}return Sc(bc,yc,e,r)}(r)(t)}const yc=2048,vc=new Map,bc=new Map;function Sc(e,t,r,n){if(e.set(r,n),e.size>t){const t=e.keys().next().value;void 0!==t&&e.delete(t)}return n}function kc(e){const t=vc.get(e);if(void 0!==t)return t;const r=(function(e){const t=Za(e);if(void 0!==t)return`${t.hostname}/git/${t.owner}/${t.name}`.toLowerCase()}(n=e)??Va(n))||function(e){let t=e.trim();t.startsWith("git@")&&(t=`https://${t.slice(4).replace(":","/")}`),/^[a-z][a-z0-9+.-]*:\/\//i.test(t)&&!/^https?:\/\//i.test(t)&&(t=t.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"https://")),/^https?:\/\//i.test(t)||(t=`https://${t}`);try{const e=new URL(t),r=e.pathname.replace(/\/+$/,"").replace(/\.git$/i,"").replace(/\/+$/,"");return e.hostname+r}catch{return t=t.replace(/^https?:\/\//i,""),t=t.replace(/[?#].*$/,""),t=t.replace(/\/+$/,""),t=t.replace(/\.git$/i,""),t=t.replace(/\/+$/,""),t}}(e).toLowerCase();var n;return Sc(vc,2048,e,r)}function _c(e){if("object"==typeof e&&null!==e&&"code"in e){const t=e.code;if("string"==typeof t)return t}}function Cc(e){if(e instanceof Error)return e.message;if("object"==typeof e&&null!==e&&"message"in e){const t=e.message;if("string"==typeof t)return t}return""}(0,Es.J)((function(){vc.clear(),bc.clear()}));const Ec=[".gitignore",".cursorignore"];async function xc(e){if(!(0,s.isAbsolute)(e))return null;const t=await(0,ts.DN)(e);return null===t?null:t}function Pc(e,t){if(!e||0===e.length)return[...t];const r=new Set(e);for(const e of t)r.has(e)&&r.delete(e),r.add(e);return[...r]}class Rc{constructor(e,t,r,n={}){this.disposeRequested=!1,this.initIgnoreService=()=>Ac.init((0,b.q6)(),e,r??[process.cwd()],t),!0!==n.deferInit&&this.ensureStarted()}ensureStarted(){if(void 0===this.ignoreServicePromise){if(this.disposeRequested)return Promise.reject(new Error("LazyIgnoreService was disposed before its ignore-file scan started"));this.ignoreServicePromise=this.initIgnoreService()}return this.ignoreServicePromise}isIgnoredByAny(e){return this.ensureStarted().then((t=>t.isIgnoredByAny(e)))}isGitIgnored(e){return this.ensureStarted().then((t=>t.isGitIgnored(e)))}isCursorIgnored(e,t){return this.ensureStarted().then((r=>r.isCursorIgnored(e,t)))}isRepoBlocked(e){return this.ensureStarted().then((t=>t.isRepoBlocked(e)))}listCursorIgnoreFilesByRoot(e){return this.ensureStarted().then((t=>t.listCursorIgnoreFilesByRoot(e)))}getCursorIgnoreMapping(){return this.ensureStarted().then((e=>e.getCursorIgnoreMapping()))}getShellSandboxIgnoreMapping(e){return this.ensureStarted().then((t=>t.getShellSandboxIgnoreMapping(e)))}getGitIgnoreMapping(){return this.ensureStarted().then((e=>e.getGitIgnoreMapping()))}getRepoBlockExcludeGlobs(e){return this.ensureStarted().then((t=>t.getRepoBlockExcludeGlobs(e)))}handleCursorIgnoreCreated(e){return this.ensureStarted().then((t=>t.handleCursorIgnoreCreated(e)))}handleCursorIgnoreChanged(e){return this.ensureStarted().then((t=>t.handleCursorIgnoreChanged(e)))}handleCursorIgnoreDeleted(e){return this.ensureStarted().then((t=>t.handleCursorIgnoreDeleted(e)))}dispose(){this.disposeRequested||(this.disposeRequested=!0,this.ignoreServicePromise?.then((e=>{e.dispose()})).catch((()=>{})))}}const Ic=Math.min(8,Math.max(1,Math.floor(o.availableParallelism()/2)));class Tc{constructor(e){this.maxLookups=e,this.instances=new Map,this.lookups=0}get(e,t){this.lookups>=this.maxLookups&&this.clear(),this.lookups++;let r=this.instances.get(e);return void 0===r&&(r=ia().add(t),this.instances.set(e,r)),r}delete(e){this.instances.delete(e)}clear(){this.instances.clear(),this.lookups=0}}class Ac{constructor(e,t,r,n,o,s){this.gitExecutor=e,this.gitIgnoreMapping=t,this.cursorIgnoreMapping=r,this.teamSettingsService=n,this.rootDirectories=o,this.scanEnvironment=s,this.gitIgnoreCache=new Bs.q({max:2e3}),this.cursorIgnoreCache=new Bs.q({max:2e3}),this.gitRootCache=new Bs.q({max:1e4}),this.gitRemoteUrlCache=new Bs.q({max:200}),this.hasGitDirCache=new Bs.q({max:1e3}),this.gitParsedIgnoreCache=new Tc(1e4),this.cursorParsedIgnoreCache=new Tc(1e4),this.ignoreMappingsHaveEntries=!1,this.directoryWalkPlacementCache=new Bs.q({max:1e4}),this.extraRootCursorIgnoreCache=new Bs.q({max:32}),this.extraGitRepoMappingCache=new Bs.q({max:32}),this.unwalkedFolders=o.flatMap((e=>zs(e,s)))}static getRipwalkCache(){return Ac.ripwalkCache??=new _a,Ac.ripwalkCache}hasNoWorkspaceFolders(){return!this.ignoreMappingsHaveEntries&&(this.ignoreMappingsHaveEntries=Object.keys(this.gitIgnoreMapping).length>0||Object.keys(this.cursorIgnoreMapping).length>0,!this.ignoreMappingsHaveEntries)}async resolveLookupRoot(e){return await(0,ts.DN)(e)??(0,ts.o1)(e)}static async init(e,t,r,n,s={platform:process.platform,homeDirectory:o.homedir()}){const i={...s,homeDirectory:await(0,ts.DN)(s.homeDirectory)??s.homeDirectory},a=await(0,Nr.PH)(r,(async e=>{const t=await(0,ts.DN)(e);return null===t?(console.warn(`[IgnoreService] Cannot resolve workspace root, using as-is: ${e}`),e):t})),c={},l={},u=await(0,Nr.PH)(a,(async r=>({root:r,lookup:await rc(e,t,r)}))),d=u.map((({root:e,lookup:t})=>"none"===t.kind?null:"unknown"===t.kind||zs(t.root,i).length>0?e:t.root)).filter((e=>null!==e)),h=u.filter((({lookup:e})=>"unknown"===e.kind)).map((({root:e})=>(0,ts.o1)(e)));return d.length>0&&await Promise.all([Ac.initializeIgnoreMapping({rootDirectories:d,ignoreFileName:".gitignore",mapping:c,scanEnvironment:i,unknownRoots:h}),Ac.initializeIgnoreMapping({rootDirectories:a,ignoreFileName:".cursorignore",mapping:l,scanEnvironment:i,unknownRoots:h})]),new Ac(t,c,l,n,a,i)}static async preloadHierarchy(e,t,r,n){let o=(0,ts.o1)(e);const i=(0,s.parse)(o).root;for(;o!==i;){if(n?.has(o)){const e=(0,s.dirname)(o);if(e===o)break;o=e;continue}void 0===r[o]&&await Ac.handleHierarchyIgnore(o,t,r),n?.add(o);const e=(0,s.dirname)(o);if(e===o)break;o=e}}static async handleHierarchyIgnore(e,t,r){const n=(0,s.join)(e,t);try{await(0,xo.access)(n,xo.constants.F_OK);const t=await Bi(n),o=Ac.parseIgnoreRules(t);r[e]=o}catch(o){"ENOENT"===_c(o)||console.error(`Error reading ${t} file at ${n}:`,o),r[e]=[]}}static async initializeIgnoreMapping({rootDirectories:e,ignoreFileName:t,mapping:r,scanEnvironment:n,unknownRoots:o}){try{const i=Ac.deduplicateRootDirectories(e),a=await Ac.promiseQueue.enqueueList(i,(e=>Ac.findFilesWithRipgrep({rootDirectory:e,fileName:t,scanEnvironment:n,noIgnoreVcs:o.some((t=>(0,ts.ZU)({basePath:e,targetPath:t})))}))),c=Array.from(a.values()).flat();await Promise.all(c.map((async e=>{try{const t=await Bi(e),n=Ac.parseIgnoreRules(t),o=(0,s.dirname)(e);r[o]=n}catch(r){console.error(`Error processing ${t} file at ${e}:`,r)}})));const l=new Set;for(const e of i)await Ac.preloadHierarchy(e,t,r,l)}catch(e){console.error(`Error initializing ignore mapping for ${t}:`,e)}}static async findFilesWithRipgrep({rootDirectory:e,fileName:t,scanEnvironment:r,noIgnoreVcs:n}){const o=(0,b.q6)(),i=[],a={root:e,includeGlobs:Ec.map((e=>`**/${e}`)),excludeGlobs:[...dc,...hc(e,r)],noIgnoreVcs:n,source:"ignore_scan"},c=Ac.getRipwalkCache().walk(o,a);for await(const r of c.lines)(0,s.basename)(r)===t&&i.push((0,s.join)(e,r));return i}async handleManualLookupWhenNoWorkspaceDirs(e,t,r){const n={};let o=(0,s.dirname)(e);const i=(0,s.parse)(o).root;for(;;){let e=r?.get(o);if(void 0===e){try{e=Ac.parseIgnoreRules(await Bi((0,s.join)(o,t)))}catch{e=[]}r?.set(o,e)}if(e.length>0&&(n[o]=e),o===i)break;o=(0,s.dirname)(o)}return this.testIgnored(e,n,((e,t)=>ia().add(t)))}async isIgnoredByAny(e){const[t,r,n]=await Promise.all([this.checkGitIgnored(e),this.checkCursorIgnored(e),this.checkRepoBlocked(e)]);return t||r||n}async isGitIgnored(e){return this.checkGitIgnored(e)}async isCursorIgnored(e,t){return this.checkCursorIgnored(e,t)}async checkGitIgnored(e){if(this.hasNoWorkspaceFolders())return this.handleManualLookupWhenNoWorkspaceDirs(e,".gitignore");const t=this.gitIgnoreCache.get(e);if(void 0!==t)return t;await this.populateHierarchyIfNeeded(e,".gitignore",this.gitIgnoreMapping);const r=this.checkIgnored(e,this.gitIgnoreMapping,this.gitParsedIgnoreCache);return this.gitIgnoreCache.set(e,r),r}async checkCursorIgnored(e,t){if(this.hasNoWorkspaceFolders())return this.handleManualLookupWhenNoWorkspaceDirs(e,".cursorignore",t);const r=this.cursorIgnoreCache.get(e);if(void 0!==r)return r;await this.populateHierarchyIfNeeded(e,".cursorignore",this.cursorIgnoreMapping);const n=this.checkIgnored(e,this.cursorIgnoreMapping,this.cursorParsedIgnoreCache);return this.cursorIgnoreCache.set(e,n),n}isInUnwalkedFolder(e){const t="darwin"===this.scanEnvironment.platform,r=t?e.toLowerCase():e;return this.unwalkedFolders.some((e=>(0,ts.ZU)({basePath:t?e.toLowerCase():e,targetPath:r})))}directoryWalkPlacement(e){const t=this.directoryWalkPlacementCache.get(e);if(void 0!==t)return t;let r;return r=this.isInUnwalkedFolder(e)?"unwalked":this.rootDirectories.some((t=>(0,ts.ZU)({basePath:t,targetPath:e})))?"walked":"outside",this.directoryWalkPlacementCache.set(e,r),r}async populateHierarchyIfNeeded(e,t,r){let n=(0,s.dirname)((0,ts.o1)(e));const o=[],i=(0,s.parse)(n).root;for(;n!==i;){const e=this.directoryWalkPlacement(n),t="unwalked"===e;if("walked"===e){n=(0,s.dirname)(n);continue}if(void 0===r[n])o.push(n);else if(!t)break;const i=(0,s.dirname)(n);if(i===n)break;n=i}o.length>0&&(await Ac.promiseQueue.enqueueList(o,(e=>Ac.handleHierarchyIgnore(e,t,r))),".gitignore"===t?this.gitIgnoreCache.clear():this.cursorIgnoreCache.clear())}testIgnored(e,t,r){for(const[n,o]of Object.entries(t)){if(0===o.length)continue;if(!(0,ts.ZU)({basePath:n,targetPath:e}))continue;const t=(0,s.relative)(n,e);if(""===t)continue;const i=r(n,o),a=(0,ts.oL)(t),c=i.test(a);if(c.ignored&&!c.unignored)return!0;const l=i.test(`${a}/`);if(l.ignored&&!l.unignored)return!0}return!1}checkIgnored(e,t,r){return this.testIgnored(e,t,((e,t)=>r.get(e,t)))}async listCursorIgnoreFilesByRoot(e){const t=await this.resolveLookupRoot(e),r=[];for(const[e,n]of Object.entries(this.cursorIgnoreMapping)){if(0===n.length)continue;if(!(0,ts.ZU)({basePath:t,targetPath:e}))continue;const o=(0,s.join)(e,".cursorignore");try{await(0,xo.access)(o),r.push(o)}catch{}}return r}async getCursorIgnoreMapping(){return{...this.cursorIgnoreMapping}}async getShellSandboxIgnoreMapping(e=[]){const t={...this.cursorIgnoreMapping},r=[];for(const t of e){if((0,Gs.$f)(t))continue;const e=await(0,ts.DN)(t);if(null===e||".git"===(0,s.basename)(e)||this.rootDirectories.some((t=>(0,ts.ZU)({basePath:t,targetPath:e})))||r.includes(e))continue;const n=await xo.stat(e).catch((e=>{if(void 0===_c(e))throw e}));n?.isDirectory()&&r.push(e)}const n=Date.now();for(const e of r){let r=this.extraRootCursorIgnoreCache.get(e);if(void 0===r||r.expiresAt<=n){const t={},o=void 0===this.gitExecutor.guardedRootLookup?void 0:await rc((0,b.q6)(),this.gitExecutor,e);await Ac.initializeIgnoreMapping({rootDirectories:[e],ignoreFileName:".cursorignore",mapping:t,scanEnvironment:this.scanEnvironment,unknownRoots:"unknown"===o?.kind?[e]:[]}),r={mapping:t,expiresAt:n+Sa()},this.extraRootCursorIgnoreCache.set(e,r)}for(const[e,n]of Object.entries(r.mapping))t[e]=Pc(t[e],n)}for(const e of[...this.rootDirectories,...r]){const r=await this.getRepoBlockExcludeGlobs(e);0!==r.length&&(t[e]=Pc(t[e],r))}return t}async getGitIgnoreMapping(){return{...this.gitIgnoreMapping}}static deduplicateRootDirectories(e){const t=[...e.map((e=>(0,ts.o1)(e)))].sort(((e,t)=>e.length-t.length)),r=[];for(const e of t)r.some((t=>e.startsWith(`${t}/`)||e.startsWith(`${t}\\`)))||r.push(e);return r}static parseIgnoreRules(e){return e.split("\n").map((e=>e.replace(/\r$/,"").trimStart())).filter((e=>""!==e&&!e.startsWith("#")))}clearCaches(){this.gitIgnoreCache.clear(),this.cursorIgnoreCache.clear(),this.gitRootCache.clear(),this.gitRemoteUrlCache.clear(),this.hasGitDirCache.clear(),this.gitParsedIgnoreCache.clear(),this.cursorParsedIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear(),this.extraGitRepoMappingCache.clear()}dispose(){this.gitIgnoreCache=new Bs.q({max:1}),this.cursorIgnoreCache=new Bs.q({max:1}),this.gitRootCache=new Bs.q({max:1}),this.gitRemoteUrlCache=new Bs.q({max:1}),this.hasGitDirCache=new Bs.q({max:1}),this.directoryWalkPlacementCache=new Bs.q({max:1}),this.extraRootCursorIgnoreCache=new Bs.q({max:1}),this.extraGitRepoMappingCache=new Bs.q({max:1}),this.gitParsedIgnoreCache.clear(),this.cursorParsedIgnoreCache.clear(),this.gitRepoMappingPromise=void 0}async handleCursorIgnoreCreated(e){const t=(0,s.dirname)(e),r=await Bi(e),n=Ac.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear()}async handleCursorIgnoreChanged(e){const t=(0,s.dirname)(e),r=await Bi(e),n=Ac.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear()}handleCursorIgnoreDeleted(e){const t=(0,s.dirname)(e);this.cursorIgnoreMapping[t]=[],this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear()}async findGitRootsForFile(e){const t=(0,ts.o1)(e),r=this.gitRootCache.get(t);if(void 0!==r)return r;const n=[],o=[],i=[];let a=t;const c=(0,s.parse)(a).root;for(;a!==c;){o.push(a),void 0===this.hasGitDirCache.get(a)&&i.push(a);const e=(0,s.dirname)(a);if(e===a)break;a=e}if(i.length>0){const e=i.map((e=>(0,xo.access)((0,s.join)(e,".git"),xo.constants.F_OK).then((()=>[e,!0])).catch((()=>[e,!1])))),t=await Promise.all(e);for(const[e,r]of t)this.hasGitDirCache.set(e,r)}for(const e of o)!0===this.hasGitDirCache.get(e)&&n.push(e);return this.gitRootCache.set(t,n),n}async isRepoBlocked(e){return this.checkRepoBlocked(e)}async checkRepoBlocked(e){const t=function(e){if(void 0===e)return;const t=e.repos??[],r=e.disableLocalExecAllowlistEnforcement?[]:e.allowedRepos??[];return 0===t.length&&0===r.length?void 0:{blocked:t,allowed:r}}(await(this.teamSettingsService?.getTeamRepos()));if(void 0===t)return!1;const r=await this.findGitRootsForFile(e);if(0===r.length)return 0!==t.allowed.length&&!(0,ts.ZU)({basePath:await this.getCursorDataDir(),targetPath:e})&&function(e,t){return 0!==e.allowed.length&&!fc(e.allowed,t)}(t,this.getWorkspaceRelativePath(e));const n=[];for(const t of r)n.push({url:await this.remoteUrlOf(t),relativePath:(0,s.relative)(t,e)||"."});return function(e,t){let r=0===e.allowed.length,n=!1;for(const{url:o,relativePath:s}of t)if(void 0!==o){if(e.blocked.some((e=>mc(e,o,s))))return!0;e.allowed.length>0&&!n&&(n=!0,r=e.allowed.some((e=>mc(e,o,s))))}else 0;return!r}(t,n)}async remoteUrlOf(e){if(this.gitRemoteUrlCache.has(e))return this.gitRemoteUrlCache.get(e);const t=await ac((0,b.q6)(),this.gitExecutor,e);return void 0!==t&&this.gitRemoteUrlCache.set(e,t),t}getWorkspaceRelativePath(e){let t;for(const r of this.rootDirectories)(0,ts.ZU)({basePath:r,targetPath:e})&&(void 0===t||r.length>t.length)&&(t=r);return void 0!==t?(0,ts.oL)((0,s.relative)(t,e)):(0,ts.oL)(e)}getCursorDataDir(){return this.cursorDataDirPromise??=(async()=>{const e=(0,s.join)(o.homedir(),".cursor");return await(0,ts.DN)(e)??e})(),this.cursorDataDirPromise}async getRepoBlockExcludeGlobs(e){const t=await(this.teamSettingsService?.getTeamRepos());if(!t?.repos?.length)return[];const r=await this.resolveLookupRoot(e);let n;if(this.rootDirectories.some((e=>(0,ts.ZU)({basePath:e,targetPath:r}))))n=await this.getGitRepoMapping();else{const e=this.extraGitRepoMappingCache.get(r);void 0!==e?n=e:(n=await this.initializeGitRepoMapping([r]),this.extraGitRepoMappingCache.set(r,n))}if(0===n.size)return[];const o=[];for(const[e,i]of n){if(void 0===i)continue;const n=this.normalizePathForComparison(e),a=this.normalizePathForComparison(r);let c=!1,l="";if(a.startsWith(n)?(c=!0,l=""):n.startsWith(a)&&(c=!0,l=(0,s.relative)(r,e)),!c)continue;const u=t.repos.filter((e=>gc(e.url,i)));if(0!==u.length)for(const e of u)for(const t of e.patterns||[]){const e=t.pattern.trim();if(!e)continue;let r;r=l?(0,s.join)(l,e).replace(/\\/g,"/"):e,o.push(r),r.endsWith("/**")||o.push(`${r}/**`)}}return o}normalizePathForComparison(e){let t=e.replace(/\\/g,"/");return t.startsWith("/")&&t.length>2&&":"===t[2]&&(t=t.substring(1)),"win32"===process.platform&&(t=t.toLowerCase()),t}getGitRepoMapping(){return this.gitRepoMappingPromise||(this.gitRepoMappingPromise=this.initializeGitRepoMapping()),this.gitRepoMappingPromise}async initializeGitRepoMapping(e=this.rootDirectories){const t=new Map,r=[],n=["**/node_modules/**","**/.turbo/**","**/.next/**","**/.cache/**","**/.pnpm/**","**/.yarn/**","**/dist/**","**/build/**","**/out/**","**/target/**","**/.vscode/**","**/.idea/**","**/venv/**","**/__pycache__/**","**/logs/**","**/tmp/**","**/temp/**"],o=(0,b.q6)();for(const t of e){const e=(0,ts.o1)(t);try{await(0,xo.access)((0,s.join)(e,".git"),xo.constants.F_OK),r.includes(e)||r.push(e)}catch{}let i=(0,s.dirname)(e);const a=(0,s.parse)(i).root;for(;i!==a&&""!==i;){try{await(0,xo.access)((0,s.join)(i,".git"),xo.constants.F_OK),r.includes(i)||r.push(i)}catch{}const e=(0,s.dirname)(i);if(e===i)break;i=e}try{const t={root:e,includeGlobs:["**/.git/config"],excludeGlobs:[...n,...hc(e,this.scanEnvironment)],noIgnoreVcs:!0,source:"ignore_scan"},i=Ac.getRipwalkCache().walk(o,t);for await(const t of i.lines){const n=(0,s.join)(e,t),o=(0,s.dirname)(n),i=(0,s.dirname)(o);r.includes(i)||r.push(i)}}catch{}}return await Promise.all(r.map((async e=>{try{const r=await ac(o,this.gitExecutor,e);t.set(e,r)}catch{t.set(e,void 0)}}))),t}}async function $c(e,t){let r=e;if(Ds()&&(r=Us(t.command,t.parsingResult)),!r||"insecure_none"===r.type)return r;const n="workspace_readwrite"===r.type&&t.permissionsService.resolveLinkedWorktreeSandboxGrants?await t.permissionsService.resolveLinkedWorktreeSandboxGrants(r,{command:t.command,workingDirectory:t.workingDirectory}):void 0,o=function(e,t){if(!e)return t;const r={...e};for(const[e,n]of Object.entries(t))r[e]=Pc(r[e],n);return r}(r.ignoreMapping,await async function(e,t){return e.getShellSandboxIgnoreMapping?e.getShellSandboxIgnoreMapping(t):e.getCursorIgnoreMapping()}(t.ignoreService,n?.roots));if("workspace_readwrite"===r.type&&void 0!==n){const e=(0,No.s9)(r.additionalReadwritePaths,[...n.roots,...n.commonDirs]);return{...r,additionalReadwritePaths:e.length>0?e:void 0,ignoreMapping:o}}return{...r,ignoreMapping:o}}Ac.promiseQueue=new Nr.TJ({max:Ic});var Mc=r("../proto/dist/generated/agent/v1/mcp_exec_pb.js");const Dc="agent-tools",Oc=51380224;var Fc=r("../proto/dist/generated/agent/v1/utils_pb.js");const Nc=/^v?(\d{1,9})\.(\d{1,9})(?:\.\d{1,9})?(?:[-+][0-9A-Za-z.+-]*)?$/,Lc=["unknown","other","older","3.24","3.25","3.26","3.27","3.28","3.29","3.30","3.31","3.32","3.33","3.34","3.35","3.36","3.37","3.38","3.39","3.40","newer"].flatMap((e=>{const t=/^(\d+)\.(\d+)$/.exec(e);return null===t?[]:[{major:Number(t[1]),minor:Number(t[2]),bucket:e}]})),jc=Lc[0].major,Uc=Lc[0].minor;function Bc(e){if(null==e)return"unknown";const t=e.trim();if(0===t.length||t.length>128)return"unknown";const r=Nc.exec(t);if(null===r)return"unknown";const n=Number(r[1]),o=Number(r[2]);if(n!==jc)return"other";const s=Lc.find((e=>e.minor===o));return void 0!==s?s.bucket:o=128&&t<=191?t:Jc.get(e)}function ol(e,t){const r=e.charCodeAt(t),n=function(e){return e>=194&&e<=222?201===e?0:2:e>=224&&e<=239?3:240===e?4:0}(r);if(0===n||t+n>e.length)return;const o=new Uint8Array(n);o[0]=r;for(let r=1;r0&&Xc.test(e[t-1]))return}else{if(Qc.has(s))return;if(!0===el.get(r)?.has(s))return;if(3===n&&tl.has(s)&&Qc.has(e[t+2]))return}let i;try{i=Kc.decode(o)}catch{return}return rl.test(i)?void 0:{index:t,text:e.slice(t,t+n),repaired:i}}function sl(e,t=Number.POSITIVE_INFINITY){const r=[];let n=0;for(;n240){n++;continue}const o=ol(e,n);void 0!==o?(r.push(o),n+=o.text.length):n++}return r}const il=`[\\u00c2-\\u00f0][\\u0080-\\u00bf${[...Jc.keys()].join("")}]`,al=new RegExp(il),cl=/\p{L}/u;function ll(e,t){const r=e.charCodeAt(t);let n;if(r>=194&&r<=223)n=2;else if(r>=224&&r<=239)n=3;else{if(!(r>=240&&r<=244))return 0;n=4}if(t+n>e.length)return 0;for(let r=1;r=128&&n<=191)&&(n<128||!Jc.has(e[t+r])))return 0}return n}function ul(e,t){if(t.text.length>2)return!0;const r=t.text.charCodeAt(1);if(r>=128&&r<=159)return!0;if(0===t.index||!Xc.test(e[t.index-1]))return!0;const n=t.index+t.text.length;return n0)return"damaged";const n=bl(r);return"utf8"!==n&&"utf8_bom"!==n?"other_encoding":"intact"}function ml(e,t){return e<=t?"existing_only":"new_damage"}function gl(e,t){const r=new Set(t.map((e=>e.text))),n=e.filter((e=>!r.has(e.text))),o=n.length>0?n:e;if(function(e){let t="",r=-1;for(const n of e){if(n.index!==r){if(sl(t,1).length>0)return!0;t=""}t+=n.repaired,r=n.index+n.text.length}return sl(t,1).length>0}(o))return"double";if(1!==new Set(o.map((e=>e.text.length))).size)return"mixed";switch(o[0].text.length){case 2:return"two_byte";case 3:return"three_byte";default:return"four_byte"}}function wl(e){return{detector:e,outcome:"clean",afterCount:0,beforeCount:0}}function yl(e,t,r){const n=sl(r,1e3);if(0===n.length)return wl("mojibake");const o=void 0===e?[]:sl(e,Math.max(n.length,6));return{detector:"mojibake",outcome:ml(n.length,o.length),file:fl(e,o.length,t),afterCount:n.length,beforeCount:o.length,pattern:gl(n,o)}}function vl(e,t,r){const n=di(r);if(0===n)return wl("replacement_chars");const o=void 0===e?0:di(e);return{detector:"replacement_chars",outcome:ml(n,o),file:fl(e,o,t),afterCount:n,beforeCount:o}}function bl(e){if(void 0===e)return"none";const t=e.toLowerCase().replace(/[^a-z0-9]/g,"");return"utf8"===t||"ascii"===t?"utf8":"utf8bom"===t?"utf8_bom":t.startsWith("utf16")?"utf16":"latin1"===t||"iso88591"===t?"latin1":"windows1252"===t||"cp1252"===t?"windows_1252":"gbk"===t||"gb2312"===t||"gb18030"===t||"cp936"===t?"gbk":"shiftjis"===t||"sjis"===t||"cp932"===t||"windows31j"===t?"shift_jis":"euckr"===t||"cp949"===t?"euc_kr":"big5"===t||"big5hkscs"===t||"cp950"===t?"big5":"other"}const Sl=new Map([["md",["md","mdx","markdown"]],["txt",["txt","text","log","rst","adoc","asciidoc","tex"]],["js_ts",["js","jsx","mjs","cjs","ts","tsx","mts","cts"]],["web",["html","htm","xhtml","css","scss","sass","less","vue","svelte","astro"]],["py",["py","pyi","pyw","ipynb"]],["jvm",["java","kt","kts","scala","groovy","gradle"]],["dotnet",["cs","csx","vb","fs","fsx","razor","cshtml","xaml"]],["c_cpp",["c","h","cc","cpp","cxx","c++","hpp","hh","hxx","h++","m","mm"]],["other_code",["go","rs","rb","erb","php","swift","dart","lua","pl","pm","r","ex","exs","erl","hs","clj","cljs","zig","nim","jl","sol","elm","ml","mli","pas","bas"]],["shell",["sh","bash","zsh","fish","ps1","psm1","psd1","bat","cmd"]],["sql",["sql","psql","ddl","dml"]],["config",["json","jsonc","json5","yaml","yml","toml","ini","cfg","conf","env","properties","editorconfig"]],["xml",["xml","xsl","xslt","xsd","svg","csproj","vbproj","fsproj","props","targets","nuspec","plist","storyboard","xib"]],["i18n",["po","pot","strings","stringsdict","arb","xlf","xliff","ftl","resx"]],["csv",["csv","tsv"]]].flatMap((([e,t])=>t.map((t=>[t,e])))));function kl(e){const t=(0,s.extname)(e).slice(1).toLowerCase();return""===t?"none":Sl.get(t)??"other"}const _l=new Map([[1252,"1252"],[1250,"1250"],[1251,"1251"],[874,"874"],[932,"932"],[936,"936"],[949,"949"],[950,"950"],[65001,"65001"]]);function Cl(e){if("string"==typeof e)return e;const t=void 0===e.acp?void 0:_l.get(e.acp);return void 0===t?"other":e.oemcp===e.acp?t:`${t}_split`}function El(e,t){if("clean"===e.outcome)return{detector:e.detector,outcome:"clean",file:"unclassified"};const r={outcome:e.outcome,file:e.file,ext:kl(t.path),encoding:bl(t.encoding),code_page:Cl(t.pages),run_count:hl(e.afterCount),delta:(n=e.afterCount-e.beforeCount,n<0?"neg":pl(n)),before_count:pl(e.beforeCount)};var n;return"mojibake"===e.detector?{detector:"mojibake",pattern:e.pattern,...r}:{detector:"replacement_chars",...r}}class xl{constructor(){this.counts={stdout:0,stderr:0},this.produced={stdout:!1,stderr:!1}}note(e,t){if(0===t.length)return;this.produced[e]=!0;const r=this.counts[e];r>=6||(this.counts[e]=r+di(t,6-r))}labels(e,t){const r=Cl(t),n=[];for(const t of["stdout","stderr"]){if(!this.produced[t])continue;const o=this.counts[t];n.push({detector:"replacement_chars",outcome:o>0?"damaged":"clean",run_count:pl(o),branch:e[t],stream:t,code_page:r})}return n}}const Pl=/[\ud800-\udbff](?![\udc00-\udfff])|(?=e.length||e.startsWith(Ml,r))&&e.startsWith(Ml,r+Ll(e,r)))return!0}return!1}(e)}(e,o))return"utf16";if(r)return"clean";if(!$l.test(e))return"clean";const s=function(e){if(!al.test(e))return;let t=0,r=!1,n=!0,o=0;for(;o=194&&s<=240?ol(e,o):void 0;if(void 0!==i){if(t++,r=ul(e,i),o+=i.text.length,!n||!r&&t>=256)return"medium";continue}const a=n?ll(e,o):0;if(0===a){if(n=!1,t>0)return"medium";o++}else o+=a}return 0!==t?r&&n?"high":"medium":void 0}(e);return void 0!==s?"high"===s?"mojibake_high":"mojibake_medium":Al.test(e)?"c1":"clean"}const Ul=(0,d.h)("local-exec:encoding-slices");function Bl(e,t){if(void 0===e)return!1;try{return"function"==typeof e?e(t):e}catch{return!1}}function Wl(e,t){return Bl(e?.enabled,t)}function Hl(e,t,r=!1){if("clean"===e)return"clean";switch(t){case"utf8_valid":return"lone_surrogate"===e?"new_damage_cut":"existing_only";case"utf8_invalid":return"lone_surrogate"===e?"new_damage_cut":"replacement"!==e?"existing_only":r?"unknown":"not_text";case"utf8_cut":return"lone_surrogate"===e?"new_damage_cut":"replacement"!==e?"existing_only":r?"unknown":"new_damage_cut";case"utf8_as_other":return"new_damage_decode";case"declared_other":return"replacement"!==e||r?"unknown":"new_damage_decode";case"other_encoding":case"unseen":return"unknown";default:return t}}function ql(e){for(let t=1;t<=Math.min(3,e.length);t++){const r=e[e.length-t]??0;if(128!=(192&r))return(r>=240?4:r>=224?3:r>=192?2:1)>t?t:0}return 0}class zl{constructor(){this.seen=!1,this.invalid=!1,this.carry=new Uint8Array(0)}write(e){if(0===e.length)return;if(this.seen=!0,this.invalid)return;const t=this.carry.length>0?Buffer.concat([this.carry,e]):e,r=ql(t);if(!(0,n.isUtf8)(t.subarray(0,t.length-r)))return this.invalid=!0,void(this.carry=new Uint8Array(0));this.carry=r>0?Uint8Array.from(t.subarray(t.length-r)):t.subarray(0,0)}evidence(){return this.seen?this.invalid?"utf8_invalid":this.carry.length>0?"utf8_cut":"utf8_valid":"unseen"}}const Gl=new Map(Object.entries({zsh:"zsh",zsh_light:"zsh_light",bash:"bash",pwsh:"pwsh",powershell51:"powershell51",naive_pwsh:"naive_pwsh",naive_powershell51:"naive_powershell51",naive_bash:"naive_bash",naive_zsh:"naive_zsh",naive_other:"naive_other"})),Vl=(0,h.Pu)("local_exec.encoding_slice",{description:"Results a local executor returned, and results about to be encoded for the wire, by the boundary they were counted at, the kind of encoding damage their text holds (one kind per result, clean included), whose the damage is as far as the bytes at that boundary say, which executor the result came from, the client's version bucket, for a shell result counted on Windows how the code page lookup stood, and for a shell result which shell ran the command",labelNames:["layer","kind","origin","source","version_bucket","code_page_lookup","shell_kind"]}),Kl=Il[0],Jl=new Map(Il.map(((e,t)=>[e,t])));function Zl(e){return Jl.get(e)??Il.length}class Xl{constructor(){this.worst="clean",this.remaining=262144}note(e){this.walk(e,0)}kind(){return this.worst}capped(){return this.remaining<=0}settled(){return this.remaining<=0||this.worst===Kl}noteText(e){if(0===e.length)return;const t=e.length>this.remaining?Jo(e,this.remaining):e;this.remaining-=Math.max(t.length,1);const r=jl(t);Zl(r)=16)return;if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer)return;if(Array.isArray(e)){for(const r of e)if(this.walk(r,t+1),this.settled())return;return}const r=Object.values(e);for(const e of r)if(this.walk(e,t+1),this.settled())return}}class Ql{constructor(e=1024){this.capacity=e,this.counted=new Set}firstRead(e,t){if(""===e)return!0;const r=`${e}\n${t}`,n=this.counted.delete(r);if(this.counted.add(r),this.counted.size>this.capacity)for(const e of this.counted){this.counted.delete(e);break}return!n}}function Yl(e,t,r,n){const o={layer:r.layer,kind:n,origin:Hl(n,r.evidence??"unseen",!0===r.partial),source:r.source??r.layer,version_bucket:Bc(e.clientVersion)};void 0!==r.codePageLookup&&(o.code_page_lookup=r.codePageLookup),void 0!==r.shellKind&&(o.shell_kind=r.shellKind),Vl.increment(t,1,o)}function eu(e,t){Ul.warn(e,"encoding slice was not counted (result unaffected)",{error:t instanceof Error?t.name:"unknown"})}function tu(e,t,r,n){if(void 0!==e&&Wl(e,t))try{const o=new Xl;o.note(n),Yl(e,t,r,o.kind())}catch(e){eu(t,e)}}function ru(e,t,r,n){if(void 0!==e&&Wl(e,t))try{Yl(e,t,r,n)}catch(e){eu(t,e)}}class nu{constructor(){this.seen=!1,this.invalid=!1}note(e){this.seen=!0,this.invalid||(0,n.isUtf8)(e)||(this.invalid=!0)}evidence(){return this.seen?this.invalid?"utf8_invalid":"utf8_valid":"unseen"}}function ou(e,t,r,n){return void 0===t?e:{execute:async(o,s,i)=>{const a=await e.execute(o,s,i);if(Wl(t,o))try{n(a)&&tu(t,o,{layer:r},a)}catch(e){eu(o,e)}return a}}}new Map([["readArgs","exec_read"],["redactedReadArgs","exec_read"],["grepArgs","exec_grep"],["mcpArgs","exec_mcp"],["readMcpResourceExecArgs","exec_mcp"],["executeHookArgs","exec_hooks"],["fetchArgs","exec_web_fetch"],["shellArgs","exec_shell"],["shellStreamArgs","exec_shell"],["backgroundShellSpawnArgs","exec_shell"],["miniSweAgentBashArgs","exec_shell"],["writeArgs","exec_write"]]);class su{constructor(){this.text={stdout:new Xl,stderr:new Xl},this.bytes={stdout:new zl,stderr:new zl},this.produced={stdout:!1,stderr:!1},this.dropped={stdout:!1,stderr:!1},this.shellKind="unknown"}noteBytes(e,t){this.bytes[e].write(t)}noteText(e,t){0!==t.length&&(this.produced[e]=!0,this.text[e].note(t))}noteDropped(e){this.dropped[e]=!0}noteShell(e){this.shellKind=function(e){return"string"!=typeof e?"unknown":Gl.get(e)??"unknown"}(e)}record(e,t,r,n){for(const o of["stdout","stderr"])this.produced[o]&&ru(e,t,{layer:"exec_shell",evidence:this.evidence(o,r[o]),partial:this.dropped[o]||this.text[o].capped(),codePageLookup:n,shellKind:this.shellKind},this.text[o].kind())}evidence(e,t){if("utf8"!==t)return"other_encoding";const r=this.bytes[e].evidence();return"utf8_cut"===r?"utf8_invalid":r}}var iu=r("node:child_process"),au=r("../utils/dist/workload-spawn.js");const cu=(0,d.h)("local-exec:shell-output-encoding"),lu=(0,Vs.promisify)(iu.execFile),uu=/^\s*OEMCP\s+REG_\w+\s+(\d+)\s*$/m,du=/^\s*ACP\s+REG_\w+\s+(\d+)\s*$/m;function hu(e,t){const r=t.exec(e);return null===r?void 0:Number(r[1])}const pu="㐀-䶿一-鿿豈-﫿",fu=" -〿㈀-㏿︰-﹯＀-￯",mu="‐-※←-⇿─-◿★☆",gu="぀-ヿ",wu=new Map([["cp932",{script:new RegExp(`[${pu}${fu}${mu}${gu}]`),doubleByte:!0}],["cp936",{script:new RegExp(`[${pu}${fu}${mu}${gu}㄀-ㄯ]`),doubleByte:!0}],["cp949",{script:new RegExp(`[${pu}${fu}${mu}${gu}㄰-㆏가-힯]`),doubleByte:!0}],["cp950",{script:new RegExp(`[${pu}${fu}${mu}㄀-ㄯ]`),doubleByte:!0}],["cp874",{script:new RegExp("[฀-๿]"),doubleByte:!1}]]);const yu=function(e){let t,r,n,o,s=!1,i=0;const a=()=>{i+=1;const e=i;n=async function(){const{stdout:e}=await(0,au.D9)(lu,"\\\\.\\GLOBALROOT\\SystemRoot\\System32\\reg.exe",["query","HKLM\\SYSTEM\\CurrentControlSet\\Control\\Nls\\CodePage"],{encoding:"buffer",timeout:3e3,windowsHide:!0});return e}().then((e=>{const i=function(e){const t=Buffer.isBuffer(e)?function(e){return e.length>=2&&255===e[0]&&254===e[1]?e.subarray(2).toString("utf16le"):e.includes(0)?e.toString("utf16le"):e.toString("latin1")}(e):e,r={},n=hu(t,uu),o=hu(t,du);return void 0!==n&&(r.oemcp=n),void 0!==o&&(r.acp=o),r}(e);t=function(e){const{oemcp:t,acp:r}=e;if(void 0===t||void 0===r||t!==r)return;const n=function(e){if(65001===e)return;const t=`cp${e}`;return Js.encodingExists(t)?t:void 0}(t);return void 0!==n&&wu.has(n)?n:void 0}(i),r=i,s=!0,n=void 0,o=void 0===i.oemcp&&void 0===i.acp?"unparsed":"answered",cu.info((0,b.q6)(),"Resolved the fallback encoding for shell output",{encoding:t??"none",oemcp:i.oemcp??"none",acp:i.acp??"none"})}),(t=>{n=void 0,o=function(e){try{if("object"!=typeof e||null===e)return"spawn_error";const t="code"in e?e.code:void 0;return"killed"in e&&!0===e.killed&&"string"!=typeof t?"timeout":"number"==typeof t?"nonzero_exit":"spawn_error"}catch{return"spawn_error"}}(t),cu.warn((0,b.q6)(),"Could not read the Windows code pages; shell output stays UTF-8 only",{error:t instanceof Error?t.message:String(t),attempt:e})}))};return"win32"===e&&a(),{current:()=>("win32"===e&&!s&&void 0===n&&i<3&&a(),t),pages:()=>void 0!==r?r:"win32"!==e?"none":i>=3&&void 0===n?"failed":"pending",lastOutcome:()=>"win32"===e?o??"pending":void 0,settled:()=>n??Promise.resolve()}}(process.platform),vu=Buffer.alloc(0),bu=/[\u0080-\uffff]/;function Su(e){const t=Math.max(0,e.length-3);for(let r=e.length-1;r>=t;r--){const t=e[r];if(128==(192&t))continue;const n=t>=248?1:t>=240?4:t>=224?3:t>=192?2:1,o=e.length-r;return n>o?o:0}return 0}function ku(){const e=new ca.StringDecoder("utf8");return{write:t=>e.write(t),end:()=>e.end()}}function _u(e,t){return Js.decode(t,e,{stripBOM:!1})}const Cu=/[\xe0-\xef][\x80-\xbf]\?/;const Eu=10,xu=Buffer.alloc(0),Pu=new Set([7,8,9,10,11,12,13,27]);function Ru(e,t,r){for(let n=0;n+1(r=void 0,t.end())}}const Au={encoding:"utf8",skip:0};function $u(e){const t=e();let r="utf8";const n={};let o=!1;const s=()=>"utf8"===r?t:n[r]??=Tu(r),i=e=>("utf8"!==r&&e.length>0&&(o=!0),e);let a,c=!0,l=xu,u=!1,d=0;const h=(e,t)=>{const n=function(e){if(!(e.length<2))return 255===e[0]&&254===e[1]?"utf16le":254===e[0]&&255===e[1]?"utf16be":void 0}(e);if(void 0!==n)return{encoding:n,skip:2};if("utf8"===r){if(e.length<2)return t?Au:void 0;const r=0===e[0]?"utf16be":0===e[1]?"utf16le":void 0;if(void 0===r)return Au;const n=Iu(e,r);if(-1!==n)return Ru(e,r,n)?{encoding:r,skip:0}:Au;if(!t)return;const o=e.length-e.length%2;return function(e,t){const r="utf16le"===t?1:0;for(let t=0;te.length?t?o:void 0:Ru(e,r,n)?o:Au}if(-1===i)return t?Au:void 0;if("utf16le"===r&&i%2==0){if(i+1>=e.length)return t?Au:void 0;if(0===e[i+1])return o}return Au},p=e=>{if(e===r)return"";const t=i(s().end());return r=e,t},f=e=>"utf8"===r&&0!==e&&e<128,m=(e,n)=>{let o="",m=e;for(;;){if(c){const e=Math.min(m.length,512-l.length);let r;if(r=l.length>0?Buffer.concat([l,m.subarray(0,e)]):e===m.length?m:m.subarray(0,e),0===r.length)return o;const s=h(r,n||r.length>=512);if(void 0===s)return 1===r.length&&f(r[0])&&(o+=t.write(r),u=!0),l=Buffer.from(r),o;let i=s.skip,g=!1;if(u&&(i="utf8"===s.encoding?1:2,g=r[0]===Eu,u=!1),0===l.length)i>0&&(m=m.subarray(i));else{const t=r.subarray(i);m=m.subarray(e),m=0===m.length?t:0===t.length?m:Buffer.concat([t,m]),l=xu}if(c=g,d=0,a=void 0,o+=p(s.encoding),g)continue}if(0===m.length)return o;if("utf8"===r&&!m.includes(0)&&!m.includes(254)&&!m.includes(255)){const e=m.lastIndexOf(Eu),r=-1===e?-1:m.length-e-1;if(-1===r||r>=2)return o+t.write(m);if(c=!0,0===r)return e>0&&m[e-1]===Eu&&(l=Buffer.of(Eu),u=!0),o+t.write(m);const n=m[m.length-1];return l=Buffer.of(n),u=f(n),o+t.write(u?m:m.subarray(0,e+1))}const e=Iu(m,r,d,a);if(-1===e)return d+=m.length,a=m[m.length-1],o+i(s().write(m));o+=i(s().write(m.subarray(0,e))),m=m.subarray(e),c=!0}};return{write:e=>0===e.length?s().write(e):m(e,!1),peek(){if(!c||0===l.length)return"";const t=h(l,!0);if(void 0===t)return"";const r=u?"utf8"===t.encoding?1:2:t.skip,n=l.subarray(r);return 0===n.length?"":"utf8"===t.encoding?e().write(n):Tu(t.encoding).write(n)},end(){const e=m(xu,!0)+i(s().end());return c=!0,l=xu,u=!1,d=0,a=void 0,e},branch:()=>!0===t.usedCodePage?.()?"code_page":o?"utf16":"utf8"}}var Mu=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Du=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Ou=(0,d.h)("local-exec:shell-core"),Fu=(0,h.Pu)("local_exec.shell.encoding_check",{description:"Shell command output streams that produced text, per encoding detector (U+FFFD): whether the decoded text holds the pattern and how much, which decode path (UTF-8, Windows code page, UTF-16) produced it, which stream, and the machine's Windows code page",labelNames:["detector","outcome","run_count","branch","stream","code_page"]}),Nu="win32"===process.platform,Lu=["CURSOR_CONVERSATION_ID","CURSOR_REQUEST_ID","CURSOR_AGENT_STORE_FILES_DIR","CURSOR_AGENT_STORE_SHARED_PATHS"];function ju(e){return`'${e.replace(/'/g,"'\\''")}'`}async function Uu(e){try{return(await(0,xo.stat)(e)).isDirectory()}catch(e){const t=_c(e);if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}const Bu=["eval-cursorbench","cursorbench","sand-eval","eval-harness"];function Wu(e){return Bu.some((t=>e.includes(t)))?(0,ko.createHash)("sha256").update(e).digest("hex"):e}function Hu(e,t){return e[t]??process.env[t]}const qu=/^[A-Za-z_][A-Za-z0-9_]*$/,zu=/CURSOR_SANDBOX/i;function Gu(e){return qu.test(e)&&!zu.test(e)}function Vu(e){return"function"==typeof e?e():e}function Ku(e,t){const r=void 0===e?[]:[...e];return r.includes(t)||r.push(t),r}function Ju(e){let t=0,r=0;const n=e.length;for(;r"insecure_none"===e?.type?void 0:e?.privateTmp)).find((e=>void 0!==e));if("linux"!==process.platform||!0!==n||void 0===r||!(0,ts.ZU)({basePath:"/tmp",targetPath:e}))return!1;const o=(0,No.W1)(r);return void 0!==o&&await Uu(s.join(o,"tmp",s.relative("/tmp",e)))}(c,t.sandboxPolicy,this.workspacePath))){if(c!==(0,ts.o1)(await i.getCwd(),this.workspacePath))throw new Zu(c);return yield{type:"stderr",data:`The shell's working directory no longer exists: ${c}. The command did not run. Re-run it with working_directory set to an existing directory.\n`},void(yield{type:"exit",code:1,aborted:!1,localExecutionTimeMs:Math.round(performance.now()-o)})}let l,u,d=0,h=0,p=!1,f=!1,m=!1;t.fileOutputThresholdBytes&&this.projectDir&&(l={buffer:"",lineCount:0,size:0,threshold:Number(t.fileOutputThresholdBytes)});const g=t.signal,w={CURSOR_AGENT:"1"};t.conversationId&&(w.CURSOR_CONVERSATION_ID=(0,_o.sh)(t.conversationId)),t.requestId&&(w.CURSOR_REQUEST_ID=t.requestId),this.projectDir&&(w.AGENT_TRANSCRIPTS=s.join(this.projectDir,_o.O2));const y=this.options.extraEnvProvider?.(e,t);void 0!==y&&Object.assign(w,y);const v=t.requestScopedEnv??{};for(const[e,t]of Object.entries(v))void 0!==t&&Gu(e)&&(w[e]=t);const b=w.CURSOR_REQUEST_ID;void 0!==b&&(w.CURSOR_REQUEST_ID=Wu(b)),function(e,t){const r=Lu,n=Object.keys(t).filter((e=>Gu(e)&&!r.includes(e))),o=`builtin unset ${[...Lu,...n].join(" ")} 2>/dev/null || true`,s=[];for(const t of Lu){const r=Hu(e,t);void 0!==r&&s.push(`builtin export ${t}=${ju(r)}`)}for(const e of n){const r=t[e];void 0!==r&&s.push(`builtin export ${e}=${ju(r)}`)}const i=e.__CURSOR_SANDBOX_ENV_RESTORE?.trim(),a=process.env.__CURSOR_SANDBOX_ENV_RESTORE?.trim();e.__CURSOR_SANDBOX_ENV_RESTORE=[o,a,i,...s].filter((e=>void 0!==e&&""!==e)).join("; ")}(w,v),void 0!==w.__CURSOR_SANDBOX_ENV_RESTORE&&(w.__CURSOR_SANDBOX_ENV_RESTORE=function(e,t){let r=e;for(const e of t){if(null==e||0===e.length)continue;const t=Wu(e);t!==e&&(r=r.split(e).join(t))}return r}(w.__CURSOR_SANDBOX_ENV_RESTORE,[t.requestId,b,v.CURSOR_REQUEST_ID,process.env.CURSOR_REQUEST_ID]));const S=function(e,t){const r=Hu(t,"CURSOR_AGENT_STORE_FILES_DIR"),n=function(e){if(void 0===e)return[];try{const t=JSON.parse(e);if("object"!=typeof t||null===t)return[];const r=[];for(const e of Object.values(t))"object"==typeof e&&null!==e&&"path"in e&&"readOnly"in e&&"string"==typeof e.path&&"boolean"==typeof e.readOnly&&r.push({path:e.path,readOnly:e.readOnly});return r}catch{return[]}}(Hu(t,"CURSOR_AGENT_STORE_SHARED_PATHS"));if(void 0===r&&0===n.length)return e;const o=e?.perUser,s=e?.perRepo??e?.perUser??e?.teamAdmin;if("workspace_readwrite"!==s?.type&&"workspace_readonly"!==s?.type)return e;const i=o?.type===s.type?{...o}:{type:s.type};var a;void 0!==r&&(a=r,"workspace_readwrite"!==i.type?i.additionalReadonlyPaths=Ku(i.additionalReadonlyPaths,a):i.additionalReadwritePaths=Ku(i.additionalReadwritePaths,a));for(const e of n)e.readOnly||"workspace_readwrite"!==i.type?i.additionalReadonlyPaths=Ku(i.additionalReadonlyPaths,e.path):i.additionalReadwritePaths=Ku(i.additionalReadwritePaths,e.path);return{...e,perUser:i}}(t.sandboxPolicy,w),k=(0,No.CG)(S??No.BM);let _,C,E,x;S&&(yield{type:"start",sandboxed:"workspace_readonly"===k||"workspace_readwrite"===k}),t.askpassConfig&&!Nu&&(w.SUDO_ASKPASS=t.askpassConfig.helperPath,w.CURSOR_ASKPASS_SOCKET=t.askpassConfig.socketPath,w.CURSOR_ASKPASS_SECRET=t.askpassConfig.secret);const P=this.options.codePageLookup??yu,R=(this.options.outputFallbackEncoding??(()=>P.current()))(),I=()=>function(e){if(void 0===e)return ku();const t=wu.get(e);return void 0!==t&&Js.encodingExists(e)?function(e,t){const{script:r}=t,o=function(e){const{script:t}=e,r=new RegExp(`${t.source}{2}`);let n=!1,o=!1,s=!1;return{note(i,a){if(!s&&0!==i.length){if(!n){const e=bu.exec(i);null!==e&&(n=!0,s=t.test(e[0]))}s||=o&&t.test(i[0])||r.test(i)||e.doubleByte&&void 0!==a&&Cu.test(a.toString("latin1")),o=t.test(i[i.length-1])}},isUtf8Text:()=>s,reset(){n=!1,o=!1,s=!1}}}(t);let s=vu,i=0,a="utf8",c=!1;const l=()=>{a="utf8",o.reset(),i=0},u=(t,n)=>{const s=n?Su(t):0,l=t.subarray(0,t.length-s),u=l.toString("utf8");if("replacement"!==a){const t=l.subarray(i);if(i=0,o.note(t.toString("utf8"),t),o.isUtf8Text())a="replacement";else{const t=0===u.length?"":u[u.length-1],o=n&&r.test(t)?Buffer.byteLength(t):0,d=function(e,t,r){let n=_u(e,t);if(!r)return{text:n,keep:0};const o=Math.min(3,t.length);let s=0;for(;s0&&(c=!0),{text:d.text,keep:i+s}}}return{text:u,keep:s}};return{write:e=>{const t=0===s.length?e:Buffer.concat([s,e]);if(s=vu,"utf8"===a){const e=t.subarray(0,t.length-Su(t));if((0,n.isUtf8)(e)){e.length{const t=e.lastIndexOf("\n");-1===t?o.note(e):(l(),o.note(e.slice(t+1)))})(r),r}}let r="",i=0;for(;i0&&(s=Buffer.from(d.subarray(u.length))),-1===e?o.note(n):l(),i=c;continue}a="undecided"}const{text:h,keep:p}=u(d,-1===e);r+=h,p>0&&(s=Buffer.from(d.subarray(d.length-p))),-1!==e&&l(),i=c}return r},end:()=>{const e=s;s=vu;const t=0===e.length?"":"utf8"===a?e.toString("utf8"):u(e,!1).text;return l(),t},usedCodePage:()=>c}}(e,t):ku()}(R),T={stdout:$u(I),stderr:$u(I)},A=new xl,$=Wl(this.options.encodingSlices,e)?new su:void 0,M=void 0===$?void 0:function(e,t,r){return n=>{try{const o=function(e,t,r){if(!(Object.hasOwn(Hc,e.shell)&&Object.hasOwn(qc,e.parse)&&Object.hasOwn(zc,e.stateFile)&&Object.hasOwn(Gc,e.exit)))return;let n="withheld";if(r){if("function"!=typeof e.callsExit)return;n=!0===e.callsExit()?"yes":"no"}return{shell_kind:e.shell,parse:e.parse,calls_exit:n,state_file:e.stateFile,exit:e.exit,version_bucket:Bc(t)}}(n,t,r);if(void 0===o)return;Vc.increment(e,1,{...o})}catch(t){Wc.warn(e,"PowerShell run was not counted (command unaffected)",{error:t instanceof Error?t.name:"unknown"})}}}(e,this.options.encodingSlices?.clientVersion,function(e,t){return!0===Bl(e?.commandTextReadable,t)}(this.options.encodingSlices,e));let O=!1;const F=()=>{if(!O){O=!0;try{const t={stdout:T.stdout.branch(),stderr:T.stderr.branch()};for(const r of A.labels(t,P.pages()))Fu.increment(e,1,r);$?.record(this.options.encodingSlices,e,t,P.lastOutcome())}catch(t){Ou.warn(e,"shell output encoding check failed (command result unaffected)",{error:t instanceof Error?t.message:String(t)})}}},N=e=>{void 0!==l&&0!==e.length&&(l.file?l.file.write(e):l.buffer+=e)},L=function*(){const e={stdout:p,stderr:f};for(const t of["stdout","stderr"]){const r=T[t].end();if(0===r.length)continue;const n=void 0!==l&&!0!==l.truncated;n&&N(r),!n&&e[t]||(A.note(t,r),$?.noteText(t,r)),e[t]||(yield{type:t,data:r})}F()};try{for await(const r of i.execute(e,t.command,{signal:g,workingDirectory:c,env:w,sandboxPolicy:S,sandboxWorkspaceRoot:this.workspacePath,pipeStdin:t.pipeStdin??!1,keepBackgroundJobs:this.options.keepBackgroundJobs??!1,bufferOutputEvents:this.options.shellOutputBackpressureOptions?.bufferOutputEvents,outputLimiterOptions:this.options.shellOutputBackpressureOptions?.outputLimiterOptions,powershellUtf8Console:Vu(this.options.powershellUtf8Console),powershellUtf8ChildEnv:Vu(this.options.powershellUtf8ChildEnv),powershellParseAfterUtf8Switch:Vu(this.options.powershellParseAfterUtf8Switch),powershellWebRequestUtf8:Vu(this.options.powershellWebRequestUtf8),powershellPerLineStateDump:Vu(this.options.powershellPerLineStateDump),...void 0===M?{}:{powershellRunObserver:M}})){_=0,C="",E="",x="";let e=!1,t=!1;if("stdout"===r.type||"stderr"===r.type){const n=T[r.type],o="stdout"===r.type?p:f,i=void 0===l||!0===l.truncated;let a=!1;if(!o||!i){_=r.data.length;const c="stdout"===r.type?d:h,p=!o&&c+_<=os,f=void 0!==l&&!0!==l.truncated&&l.size+_<=Oc;"stdout"===r.type?e=p:t=p;const m=!o&&!p,g=!i&&!f;if((m||g)&&(x=n.peek(),g&&N(x),m&&(E=x)),(p||f)&&(C=n.write(r.data),a=!0,A.note(r.type,C),$?.noteBytes(r.type,r.data),$?.noteText(r.type,C)),void 0!==l&&l.size+_>Oc)l.truncated=!0;else if(f&&void 0!==l)if(l.size+=_,l.lineCount+=Ju(r.data),l.file)l.file.write(C);else if(l.buffer+=C,l.size>l.threshold){const e=s.join(this.projectDir,Dc);l.path=s.join(e,`${(0,ko.randomUUID)()}.txt`);try{await(0,xo.mkdir)(e,{recursive:!0}),l.file=(0,Ro.createWriteStream)(l.path),l.file.on("error",(e=>{u??=e})),l.file.write(l.buffer)}catch(e){u??=e instanceof Error?e:new Error(String(e)),l.truncated=!0}l.buffer=""}}a||(n.end(),A.note(r.type,x),$?.noteDropped(r.type),$?.noteText(r.type,x))}switch(r.type){case"stdout":e?(d+=_,C&&(yield{type:"stdout",data:C})):p||(E&&(yield{type:"stdout",data:E}),p=!0,yield{type:"stdout_trimmed"});break;case"suppressed_output":m||(m=!0,yield{type:"stdout",data:No.Ls});break;case"stderr":t?(h+=_,C&&(yield{type:"stderr",data:C})):f||(E&&(yield{type:"stderr",data:E}),f=!0,yield{type:"stderr_trimmed"});break;case"exit":{yield*L();const e=Math.max(0,Math.round(performance.now()-o));let t;if(l?.file){if(l.truncated){const e=`\n... (output truncated at ${l.size} bytes) ...\n`;l.file.write(e),l.size+=e.length,l.lineCount+=Xs(e)-1}const e=await new Promise((e=>l.file.end(e)));u??=e??void 0,u?await(0,xo.rm)(l.path,{force:!0}):t=new Fc.pV({filePath:l.path,sizeBytes:BigInt(l.size),lineCount:BigInt(l.lineCount)})}u&&void 0!==l?.path&&(yield{type:"stderr",data:`\nThe full output could not be saved to ${l.path}: ${u.message}\n`}),yield{type:"exit",code:r.code,signal:r.signal,aborted:r.aborted,outputLocation:t,localExecutionTimeMs:e};break}case"stdin_ready":$?.noteShell(r.shell),yield{type:"stdin_ready",stdin:r.stdin,pid:r.pid};break;case"sandbox_denies":yield{type:"sandbox_denies",events:r.events}}}yield*L()}catch(t){if("ENOENT"===_c(t)&&(0,Gs.$f)(c))try{Ou.warn(e,"shell failed with ENOENT in an agent store working directory",{...await(0,Gs.KZ)(c)})}catch{}throw t}finally{F()}}catch(e){r.error=e,r.hasError=!0}finally{Du(r)}}async getCwd(e){return this.executorFor(e).getCwd()}getWorkspacePath(){if(!this.workspacePath)throw new Error("Workspace path is not configured");return this.workspacePath}}class Qu{constructor(e,t){this.innerExecutor=e,this.shellManager=t}async*execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{Mu(r,(0,D.VI)(e.withName("ManagedShellCoreExecutor.execute")),!1),Ou.info(e,"Executing shell command",{command:t.command,workingDirectory:t.workingDirectory,toolCallId:t.toolCallId});let n=null;t.toolCallId&&(n=this.shellManager.getOrCreateShellEmitter(t.toolCallId));for await(const r of this.innerExecutor.execute(e,t)){if(n)switch(r.type){case"stdin_ready":n.emit({type:"stdin_ready",stdin:r.stdin,pid:r.pid});break;case"start":n.emit({type:"start",sandboxed:r.sandboxed});break;case"stdout":n.emit({type:"stdout",data:r.data});break;case"stderr":n.emit({type:"stderr",data:r.data});break;case"exit":n.emit({type:"exit",code:r.code??-1,aborted:r.aborted})}yield r}}catch(e){r.error=e,r.hasError=!0}finally{Du(r)}}async getCwd(e){return this.innerExecutor.getCwd(e)}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}class Yu{constructor(e,t){this.innerExecutor=e,this.askpassConfig=t}async*execute(e,t){const r={...t,askpassConfig:t.askpassConfig??this.askpassConfig};yield*this.innerExecutor.execute(e,r)}async getCwd(e){return this.innerExecutor.getCwd(e)}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}async function ed(e,t){switch(e.type){case"needsApproval":return t.onNeedsApproval(e.approvalReason,e.approvalDetails);case"userRejected":return t.onUserRejected(e.reason);case"cursorIgnore":return t.onPermissionDenied("Blocked by cursor ignore");case"permissionsConfig":return t.onPermissionDenied("Blocked by permissions configuration",{isReadonly:e.isReadonly});case"cursorFiles":return t.onPermissionDenied("Blocked by cursor files protection");case"adminBlock":return t.onPermissionDenied("Blocked by admin repository block");case"adminCommandDenylist":return t.onPermissionDenied(_s(e.pattern));case"unsafeResolution":return t.onPermissionDenied(e.message);default:{const t=e;throw new Error(`Unhandled block reason type: ${JSON.stringify(t)}`)}}}function td(e){switch(e.type){case"userRejected":return e.reason;case"unsafeResolution":return e.message;case"adminCommandDenylist":return _s(e.pattern);case"needsApproval":case"cursorIgnore":case"adminBlock":case"permissionsConfig":case"cursorFiles":return"Command is not allowed";default:{const t=e;return`Command is not allowed (${JSON.stringify(t)})`}}}function rd(e,t,r){return"permissionsConfig"===r.type?{case:"permissionDenied",value:new fe.jn({command:e,workingDirectory:t,error:"Command blocked by permissions configuration",isReadonly:r.isReadonly??!1})}:{case:"rejected",value:new fe.pZ({command:e,workingDirectory:t,reason:td(r)})}}var nd=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const od=(0,d.h)("local-exec:background-shell");function sd(e,t,r){return new Fo.Lt({result:rd(e,t,r)})}class id{constructor(e,t){this.id=e,this.abortController=t,this.disposed=!1,this.completed=!1,this.completionListeners=[]}abort(){this.abortController.abort()}dispose(){this.disposed||(this.disposed=!0,this.abortController.signal.aborted||this.abortController.abort())}get signal(){return this.abortController.signal}isDisposed(){return this.disposed}onComplete(e){this.completed&&this.completion?e(this.completion):this.completionListeners.push(e)}markCompleted(e){if(this.completed)return;this.completed=!0,this.completion=e;const t=[...this.completionListeners];this.completionListeners=[];for(const r of t)r(e)}}async function ad(e,t){let r;try{for(let n=await t.next();!n.done;n=await t.next())"stdin_ready"===n.value.type?(e.stdin=n.value.stdin,e.pid=n.value.pid):"exit"===n.value.type&&(r={code:n.value.code,signal:n.value.signal,aborted:n.value.aborted,outputPath:n.value.outputLocation?.filePath})}catch(e){}finally{e.markCompleted(r??{code:null,aborted:e.signal.aborted})}}function cd(e){e().catch((()=>{}))}class ld{constructor(e){if(this.args=e,this.carryover="",this.matchedOccurrences=0,this.emittedNotifications=0,this.finished=!1,this.monotonicStartMs=performance.now(),this.limit=e.config.notificationLimit??100,e.config.pattern.length>500)throw new Error("Output notification pattern exceeds 500 characters");this.regex=es.L3.compile(e.config.pattern,es.L3.MULTILINE)}observe(e){if(this.finished||this.matchedOccurrences>=this.limit||0===e.length)return;if(e.length>65536){for(const t of function(e){if(0===e.length)return[];const t=Math.max(1,Math.trunc(65536)||1),r=[];let n=0;for(;n=this.limit)break;this.observe(t)}return}const t=this.carryover.length,r=`${this.carryover}${e}`,n=this.regex.matcher(r);for(;this.matchedOccurrencest&&this.queueMatch(e)}this.carryover=Zo(r,1024)}finish(){this.finished||(this.finished=!0,this.flushPendingBatch("finish"),this.clearFlushTimer(),0===this.matchedOccurrences&&this.recordWatchOutcome("silent",{silent_ms:hd(this.monotonicStartMs)}))}queueMatch(e){if(this.matchedOccurrences>=this.limit)return;this.matchedOccurrences+=1;const t=this.matchedOccurrences,r=function(e,t){return e.length<=5e3?`${t}: ${e}`:`${t} is ${e.length} characters; omitted from notification detail.`}(e,1===t?"Matched text":"Latest match");return 1===t?(this.emitNotification({startOccurrence:t,endOccurrence:t,count:1,matchedTextDetail:r}),this.recordWatchOutcome("matched",{first_match_ms:hd(this.monotonicStartMs)}),void(t===this.limit&&this.emitLimitReachedNotification())):(this.pendingBatch?(this.pendingBatch.endOccurrence=t,this.pendingBatch.count+=1,this.pendingBatch.matchedTextDetail=r):this.pendingBatch={startOccurrence:t,endOccurrence:t,count:1,matchedTextDetail:r},t===this.limit?(this.flushPendingBatch("limit"),void this.emitLimitReachedNotification()):void this.scheduleFlush())}scheduleFlush(){if(void 0!==this.flushTimer)return;const e=this.getDebounceMs();this.flushTimer=setTimeout((()=>{this.flushPendingBatch("debounce")}),e)}getDebounceMs(){const e=this.args.debounceMs??function(e){const t=e.debounce;if(void 0!==t&&Number.isFinite(t))return Math.ceil(1e3*t)}(this.args.config)??5e3;return Math.max(e,5e3)}clearFlushTimer(){void 0!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0)}flushPendingBatch(e){const t=this.pendingBatch;t&&(this.pendingBatch=void 0,this.clearFlushTimer(),this.emitNotification(t))}emitNotification(e){this.emittedNotifications+=1;const t=this.args.config.reason.trim()||`Shell output contains /${this.args.config.pattern}/`,r=this.args.config.pattern,n=void 0!==e.matchedTextDetail?` ${e.matchedTextDetail}.`:"",o=1===e.count?`Shell output has pattern /${r}/. This is occurrence number ${e.startOccurrence}.${n} The title message is being displayed to the user.`:`Shell output matched /${r}/ ${e.count} more times since the previous notification. The title message is being displayed to the user.${n}`,s=To(String(this.args.shellId),this.emittedNotifications);var i;this.args.registry.enqueue({conversationId:this.args.conversationId,id:s,source:"shell",payload:{taskId:s,...void 0!==this.args.toolCallId?{toolCallId:this.args.toolCallId}:{},kind:"shell",status:"success",title:(i=t,i.length<=500?i:`${Jo(i,500)}...`),detail:o,outputPath:this.args.outputPath,reason:"task_progress"}})}emitLimitReachedNotification(){this.emittedNotifications+=1;const e=this.args.config.pattern,t=To(String(this.args.shellId),this.emittedNotifications);this.args.registry.enqueue({conversationId:this.args.conversationId,id:t,source:"shell",payload:{taskId:t,...void 0!==this.args.toolCallId?{toolCallId:this.args.toolCallId}:{},kind:"shell",status:"success",title:`Notification limit reached (${this.limit})`,detail:`Shell output matched /${e}/ ${this.limit} times and has reached the notification limit. No further notifications will be sent for this pattern. To continue monitoring, read the output file directly at the output path.`,outputPath:this.args.outputPath,reason:"task_progress"}}),this.recordWatchOutcome("limit_reached")}recordWatchOutcome(e,t){void 0!==this.args.ctx&&od.info(this.args.ctx,"agent.shell_output_notification_match",{event:"agent.shell_output_notification_match",outcome:e,shell_id:this.args.shellId,conversation_id:this.args.conversationId,tool_call_id:this.args.toolCallId,limit:this.limit,...t})}}class ud{constructor(e,t,r){this.innerFactory=e,this.projectDir=t,this.backgroundWorkRegistry=r}async spawn(e,t){const r=this.createObserver(e.ctx,e.shellId,e.conversationId,e.toolCallId,e.outputNotification);if(!r)return this.innerFactory.spawn(e,t);try{return await this.innerFactory.spawn(e,this.createObservingExecutor(t,r))}catch(e){throw r.finish(),e}}async adopt(e){const t=this.createObserver(e.ctx,e.shellId,void 0,e.toolCallId,e.outputNotification);if(!t)return this.innerFactory.adopt(e);e.initialOutput.length>0&&t.observe(e.initialOutput);try{return await this.innerFactory.adopt({...e,eventIterator:this.createObservingIterator(e.eventIterator,t)})}catch(e){throw t.finish(),e}}createObserver(e,t,r,n,o){if(!this.backgroundWorkRegistry||!o)return;if(0===o.pattern.trim().length)return;const i=s.join(this.projectDir,"terminals",`${t}.txt`);try{return new ld({shellId:t,outputPath:i,config:o,conversationId:r??Io,toolCallId:n,registry:this.backgroundWorkRegistry,ctx:e})}catch(r){return void(void 0!==e&&od.warn(e,"Invalid shell output notification pattern",{shellId:t,error:r instanceof Error?r.message:String(r)}))}}createObservingExecutor(e,t){const r=e.execute.bind(e);return{...e,execute:async function*(e,n){try{for await(const o of r(e,n))"stdout"===o.type||"stderr"===o.type?t.observe(o.data):"exit"===o.type&&t.finish(),yield o}finally{t.finish()}}}}createObservingIterator(e,t){const r=e.return?.bind(e);return{next:async()=>{try{const r=await e.next();if(r.done)t.finish();else{const e=r.value;"stdout"===e.type||"stderr"===e.type?t.observe(e.data):"exit"===e.type&&t.finish()}return r}catch(e){throw t.finish(),e}},return:async e=>(t.finish(),r?r(e):{done:!0,value:void 0})}}}class dd{async spawn(e,t){const r=new AbortController,n=new id(e.shellId,r),o=t.execute(e.ctx,{command:e.command,workingDirectory:e.workingDirectory,signal:r.signal,toolCallId:e.toolCallId,conversationId:e.conversationId,requestId:e.requestId,secretScopeId:e.secretScopeId,sandboxPolicy:e.sandboxPolicy,pipeStdin:e.enableWriteShellStdinTool,showElapsedTime:!0})[Symbol.asyncIterator]();try{for(let e=await o.next();!e.done;e=await o.next())if("stdin_ready"===e.value.type){n.stdin=e.value.stdin,n.pid=e.value.pid;break}}catch(e){if(e instanceof No.SandboxUnsupportedError||e instanceof Zu)throw e}return cd((()=>ad(n,o))),n}async adopt(e){const t=new id(e.shellId,e.abortController);return t.stdin=e.stdin,t.pid=e.pid,cd((()=>ad(t,e.eventIterator))),t}}function hd(e){return Math.round(performance.now()-e)}function pd(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}function fd(e){const t=String(e.runningForMs).padEnd(9," "),r=e.status.padEnd(9," ");let n="---\n";return void 0!==e.pid&&0!==e.pid&&(n+=`pid: ${e.pid}\n`),n+=`cwd: ${pd(e.cwd)}\n`,n+=`command: ${pd(e.command)}\n`,void 0!==e.title&&e.title.trim().length>0&&(n+=`title: ${pd(e.title)}\n`),n+=`status: ${r}\n`,n+=`started_at: ${e.startedAt}\n`,n+=`running_for_ms: ${t}\n`,n+="---\n",n}function md(e){return`\n[${e} truncated by cursor: the command wrote more than 1048576 characters to ${e}; only the first 1048576 were captured and the rest was dropped from this file]\n`}class gd{constructor(e,t){this.innerFactory=e,this.projectDir=t}async spawn(e,t){const r=s.join(this.projectDir,"terminals");await(0,xo.mkdir)(r,{recursive:!0});const n=this.createLoggingExecutor(t,e,r);return this.innerFactory.spawn(e,n)}createLoggingExecutor(e,t,r){const o=e.execute.bind(e);return{...e,execute:async function*(e,i){let a,c,l,u=!1,d=!1,h=!1,p=!1;const f=Date.now(),m=new Date(f).toISOString(),g=performance.now();let w,y="running",v=!1,b=Promise.resolve();const S=async e=>{if(c)try{await c.write(e)}catch(e){}},k=t.shellId,_=s.join(r,`${k}.txt`),C=async()=>{if(!a)return;const e=hd(g),r=fd({pid:w,cwd:t.workingDirectory,command:t.command,title:t.description,status:y,startedAt:m,runningForMs:e});try{await a.write(r,0,"utf8")}catch(e){}},E=()=>(b=b.then(C).catch((()=>{})),b),x=()=>{void 0!==l&&(clearInterval(l),l=void 0)},P=async e=>{if(p)return;p=!0,w=e;const r=hd(g),n=fd({pid:e,cwd:t.workingDirectory,command:t.command,title:t.description,status:y,startedAt:m,runningForMs:r});await(0,xo.writeFile)(_,n,"utf8"),l=setInterval((()=>{E()}),5e3)},R=async()=>{a||(a=await Ro.promises.open(_,"r+")),c||(c=await Ro.promises.open(_,"a"))},I=async(e,t)=>{if(!v){if(v=!0,x(),p||await P(),await R(),void 0!==t){const e=hd(g),r=`\n---\n${t}\n`+(i.showElapsedTime?`elapsed_ms: ${e}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await S(r)}y=e,await E()}};try{for await(const r of o(e,i)){if("stdout"===r.type)p||(await P(),await R()),await S(r.data);else if("stderr"===r.type)p||(await P(),await R()),await S(r.data);else if("stdout_trimmed"!==r.type||d)if("stderr_trimmed"!==r.type||h)if("stdin_ready"!==r.type||u)"exit"===r.type&&await I(r.aborted?"aborted":0===r.code?"succeeded":"failed",`exit_code: ${r.code??"unknown"}`);else{u=!0,p||(await P(r.pid),await R());const e=r.stdin;if(e&&!0!==t.suppressStdinLogging){const t=e=>{if(null==e)return;const t="string"==typeof e?e:n.Buffer.isBuffer(e)||e instanceof Uint8Array?n.Buffer.from(e).toString():"";if(!t)return;const r=t.endsWith("\n")?t:`${t}\n`;S(`[stdin] ${r}`)},r=e.write.bind(e);if(e.write=(e,n,o)=>(t(e),r(e,n,o)),"function"==typeof e.end){const r=e.end.bind(e);e.end=(e,n,o)=>(void 0!==e&&t(e),r(e,n,o))}}}else h=!0,p||await P(),await R(),await S(md("stderr"));else d=!0,p||await P(),await R(),await S(md("stdout"));yield r}if(!v){const e=i.signal?.aborted??!1;await I(e?"aborted":"failed")}}catch(e){const t=i.signal?.aborted??!1,r=pd(e instanceof Error?e.message:"Unknown error");if(await I(t?"aborted":"failed",t?void 0:`error: ${r}`),!t)throw e}finally{if(x(),await b,a)try{await a.close()}catch{}if(c)try{await c.close()}catch{}}}}}async adopt(e){const t=s.join(this.projectDir,"terminals");await(0,xo.mkdir)(t,{recursive:!0});const r=s.join(t,`${e.shellId}.txt`),n=e.startTime,o=new Date(n).toISOString(),i=e.monotonicStartMs;let a="running";const c=hd(i),l=fd({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:a,startedAt:o,runningForMs:c})+(e.initialOutput??"");await(0,xo.writeFile)(r,l,"utf8");const u=await Ro.promises.open(r,"r+");let d;try{d=await Ro.promises.open(r,"a")}catch(e){throw await u.close(),e}let h=!1,p=!1,f=!1,m=!1,g=Promise.resolve();const w=async()=>{const t=hd(i),r=fd({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:a,startedAt:o,runningForMs:t});try{await u.write(r,0,"utf8")}catch{}},y=()=>(g=g.then(w).catch((()=>{})),g);let v=setInterval((()=>{y()}),5e3);const b=()=>{void 0!==v&&(clearInterval(v),v=void 0)},S=async()=>{if(!h){h=!0,b(),await g;try{await u.close()}catch{}try{await d.close()}catch{}}},k=async e=>{try{await d.write(e)}catch(e){}},_=async(t,r)=>{if(!p){if(p=!0,b(),void 0!==r){const t=hd(i),n=`\n---\n${r}\n`+(e.showElapsedTime?`elapsed_ms: ${t}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await k(n)}a=t,await y()}},C={next:async()=>{try{const t=await e.eventIterator.next();if(t.done){if(!p){const t=e.abortController.signal.aborted;await _(t?"aborted":"failed")}}else{const e=t.value;"stdout"===e.type||"stderr"===e.type?await k(e.data):"stdout_trimmed"!==e.type||f?"stderr_trimmed"!==e.type||m?"exit"===e.type&&(await _(e.aborted?"aborted":0===e.code?"succeeded":"failed",`exit_code: ${e.code??"unknown"}`),await S()):(m=!0,await k(md("stderr"))):(f=!0,await k(md("stdout")))}return t.done&&await S(),t}catch(t){const r=e.abortController.signal.aborted;throw await _(r?"aborted":"failed"),await S(),t}},return:async()=>{if(!p){const t=e.abortController.signal.aborted;await _(t?"aborted":"failed")}return await S(),e.eventIterator.return?e.eventIterator.return():{done:!0,value:void 0}}};return this.innerFactory.adopt({...e,eventIterator:C})}}class wd{constructor(e,t){this.factory=e,this.backgroundWorkRegistry=t,this.runningShells=new Map,this.nextShellId=1e3+Math.floor(999e3*Math.random())}registerShellWork(e,t){const r=String(e.id);this.backgroundWorkRegistry?.upsertWork({id:r,kind:"shell",state:"running",metadata:Ao(t),abort:()=>{this.abort(e.id)}})}clearShellWork(e){this.backgroundWorkRegistry?.clearWork(String(e))}cleanupShell(e){this.runningShells.has(e)&&(this.runningShells.delete(e),this.clearShellWork(e))}enqueueShellCompletion(e,t,r,n,o,s){if(!this.backgroundWorkRegistry)return;const i=s.aborted?"aborted":0===s.code?"success":"error",a=function(e){if(!e.aborted)return void 0!==e.signal?`signal=${e.signal}`:null!==e.code&&0!==e.code?`exit_code=${e.code}`:void 0}(s),c=function(e){if(!e.aborted)return void 0!==e.signal?{kind:"signal",signal:e.signal}:null!==e.code?{kind:"exit",code:e.code}:void 0}(s),l=n.description?.trim()?n.description:void 0,u=String(e);this.backgroundWorkRegistry.enqueue({conversationId:r??Io,id:u,source:"shell",payload:{taskId:u,...void 0!==t?{toolCallId:t}:{},kind:"shell",status:i,title:n.description||n.command,...a?{detail:a}:{},...s.outputPath?{outputPath:s.outputPath}:{},reason:"task_finished",durationMs:hd(o),...c?{shellEnd:c}:{},...l?{description:l}:{}}})}async spawn(e,t){const r=await this.factory.spawn(e,t),n=Date.now(),o=performance.now();{const __t3b=globalThis[Symbol.for("@cursor/sdk.backgroundShell")];if(typeof __t3b==="function")try{__t3b({conversationId:e.conversationId,toolCallId:e.toolCallId,command:e.command,description:e.description,shell:r})===!0&&(r.__t3kept=!0)}catch{}}return this.runningShells.set(r.id,r),this.registerShellWork(r,{title:e.description||e.command,cwd:e.workingDirectory,startTimeMs:n}),r.signal.addEventListener("abort",(()=>{this.cleanupShell(r.id)})),r.onComplete?.((t=>{this.enqueueShellCompletion(r.id,e.toolCallId,e.conversationId,{command:e.command,description:e.description},o,t),this.cleanupShell(r.id)})),{shellId:r.id,pid:r.pid}}async adopt(e){const t=await this.factory.adopt(e);{const __t3b=globalThis[Symbol.for("@cursor/sdk.backgroundShell")];if(typeof __t3b==="function")try{__t3b({conversationId:e.conversationId,toolCallId:e.toolCallId,command:e.command,description:e.description,shell:t})===!0&&(t.__t3kept=!0)}catch{}}return this.runningShells.set(t.id,t),this.registerShellWork(t,{title:e.description||e.command,cwd:e.workingDirectory,startTimeMs:e.startTime}),t.signal.addEventListener("abort",(()=>{this.cleanupShell(t.id),e.onCleanup?.()})),t.onComplete?.((r=>{this.enqueueShellCompletion(t.id,e.toolCallId,void 0,{command:e.command,description:e.description},e.monotonicStartMs,r),this.cleanupShell(t.id),e.onCleanup?.()})),{shellId:t.id,pid:e.pid}}generateShellId(){for(let e=0;e<=998999;e++){this.nextShellId>999999&&(this.nextShellId=1e3);const e=this.nextShellId;if(this.nextShellId+=1,!this.runningShells.has(e))return e}throw new Error("No available background shell id in range")}abort(e){const t=this.runningShells.get(e);return!!t&&(t.abort(),this.runningShells.delete(e),this.clearShellWork(e),!0)}isRunning(e){return this.runningShells.has(e)}dispose(){for(const[e,t]of this.runningShells)t.__t3kept||t.dispose(),this.clearShellWork(e);this.runningShells.clear()}async writeStdin(e,t){const r=this.runningShells.get(e);if(!r)throw new Error("Shell not found");if(!r.stdin)throw new Error("Shell stdin not available");const n=t.indexOf(""),o=-1!==n?n:t.indexOf("\\u0004");if(-1!==o){const e=t.substring(0,o);e.length>0&&await new Promise(((t,n)=>{r.stdin.write(e,(e=>{e?n(e):t(void 0)}))})),r.stdin.end()}else await new Promise(((e,n)=>{r.stdin.write(t,(t=>{t?n(t):e(void 0)}))}))}}new WeakMap;class yd{constructor(e,t){this.inner=e,this.ownerConversationId=t}enqueue(e){this.inner.enqueue({...e,conversationId:this.ownerConversationId})}enqueueCompletion(e){this.enqueue({conversationId:this.ownerConversationId,id:e.taskId,source:e.kind,payload:e})}pull(e){return this.inner.pull(e)}ack(e){return this.inner.ack(e)}nack(e,t){this.inner.nack(e,t)}suppress(e,t){this.inner.suppress(e,t)}upsertWork(e){this.inner.upsertWork(e)}clearWork(e){return this.inner.clearWork(e)}abortWork(e){return this.inner.abortWork(e)}hasRunningWork(e){return this.inner.hasRunningWork(e)}abortAllWork(e){return this.inner.abortAllWork(e)}listWork(e){return this.inner.listWork(e)}drainCompletions(){return this.inner.drainCompletions()}hasPendingCompletions(e){return this.inner.hasPendingCompletions(e)}markAwaitedCompletion(e){this.inner.suppress(this.ownerConversationId,e)}}class vd{constructor(e,t,r,n,o,s,i,a){if(this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r,void 0!==a)return this.backgroundShellManager=a,void(this.ownsBackgroundShellManager=!1);const c=s&&void 0!==i?new yd(s,i):s,l=o??function(e){const t=new dd;return new gd(t,e)}(n),u=new ud(l,n,c);this.backgroundShellManager=new wd(u,c),this.ownsBackgroundShellManager=!0}getManager(){return this.backgroundShellManager}dispose(){this.ownsBackgroundShellManager&&this.backgroundShellManager.dispose()}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,D.VI)(e.withName("LocalBackgroundShellExecutor.execute")),!1);const n=t.command,o=t.sandboxPolicy?ds(t.sandboxPolicy):void 0,s=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),i=(0,ts.o1)(s),a=new fe.HO(qo(n).structured),c=Cs({command:n,parsingResult:a,blockedCommands:t.adminCommandDenylist});if(void 0!==c)return new Fo.Lt({result:{case:"rejected",value:new fe.pZ({command:n,workingDirectory:i,reason:c})}});let l;if(od.info(e,"Background shell: approval gate reached",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,hasSmartModeApproval:void 0!==t.smartModeApproval,hasSmartModeApprovalReason:void 0!==t.smartModeApproval?.reason,hasSmartModeApprovalRequestId:void 0!==t.smartModeApproval?.requestId,requestedPolicyType:o?.type??"undefined",parserCommandCount:a.executableCommands.length,classifierCommandCount:t.classifierResult?.commands.length??0,commandLength:n.length}),Oo(t)){const r=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:i,skipUnsafeWorkingDirectoryBlock:!0,command:n,parsingResult:a,toolCallId:t.toolCallId,resolveSkippedApprovalPolicy:!0},o);if("block"===r.kind)return od.info(e,"Background shell: invariant blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,skipApproval:t.skipApproval}),sd(n,i,r.reason);l=r.policy??o,od.info(e,"Background shell: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:o?.type??"undefined",effectivePolicyType:l?.type??"undefined"})}else{const r=await this.permissionsService.shouldBlockShellCommand(e,n,{workingDirectory:i,timeout:0,parsingResult:a,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Mo(t)},o);if("block"===r.kind)return od.info(e,"Background shell: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),sd(n,i,r.reason);l=r.policy,od.info(e,"Background shell: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:l.type})}l=await $c(l,{command:n,workingDirectory:i,parsingResult:a,permissionsService:this.permissionsService,ignoreService:this.ignoreService});try{const r=this.backgroundShellManager.generateShellId(),o=l?{perUser:l}:void 0,s={ctx:e,command:n,workingDirectory:i,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:o,shellId:r,enableWriteShellStdinTool:t.enableWriteShellStdinTool,suppressStdinLogging:t.suppressStdinLogging,description:t.description,outputNotification:t.outputNotification},a=await this.backgroundShellManager.spawn(s,this.coreExecutor);return new Fo.Lt({result:{case:"success",value:new Fo.Po({shellId:r,command:n,workingDirectory:i,pid:a.pid})}})}catch(r){if(r instanceof No.SandboxUnsupportedError){const o=l?.type??"unknown";return od.debug(e,"Background shell: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:o,reason:r.reason}),new Fo.Lt({result:{case:"sandboxUnsupported",value:new fe.rI({command:n,workingDirectory:i,sandboxPolicyType:o,reason:r.reason??r.message,isReadonly:"workspace_readonly"===o})}})}return new Fo.Lt({result:{case:"error",value:new Fo.Of({command:n,workingDirectory:i,error:r instanceof Error?r.message:"Unknown error"})}})}}catch(e){r.error=e,r.hasError=!0}finally{nd(r)}}writeStdin(e,t){return this.backgroundShellManager.writeStdin(e,t)}}var bd=r("node:async_hooks");r("../../node_modules/.pnpm/minimatch@10.2.5/node_modules/minimatch/dist/esm/index.js");function Sd(e){return e instanceof Error?e.message:String(e)}function kd(e){return"Failed to read skill file: "+Sd(e)}function _d(e){return"Invalid skill frontmatter: "+Sd(e)}function Cd(e,t){return e||t?void 0:"Description is required"}new Set(["EACCES","EPERM","ENOENT","ENOTDIR","EISDIR","ELOOP","ENAMETOOLONG"]);const Ed=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function xd(e){return e.toLocaleString("en-US")}var Pd=r("node:url");const Rd={beforeShellExecution:"beforeShellExecution",beforeMCPExecution:"beforeMCPExecution",afterShellExecution:"afterShellExecution",afterMCPExecution:"afterMCPExecution",beforeReadFile:"beforeReadFile",afterFileEdit:"afterFileEdit",beforeTabFileRead:"beforeTabFileRead",afterTabFileEdit:"afterTabFileEdit",stop:"stop",beforeSubmitPrompt:"beforeSubmitPrompt",afterAgentResponse:"afterAgentResponse",afterAgentThought:"afterAgentThought",sessionStart:"sessionStart",sessionEnd:"sessionEnd",preCompact:"preCompact",subagentStart:"subagentStart",subagentStop:"subagentStop",preToolUse:"preToolUse",postToolUse:"postToolUse",postToolUseFailure:"postToolUseFailure",workspaceOpen:"workspaceOpen"},Id=e=>"string"==typeof e,Td=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),Ad=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),$d=(e,t=[])=>({isValid:e,errors:t});function Md(e,t,r){void 0===e||Id(e)||r.push(`${t} must be a string if provided`)}const Dd=e=>{const t=[];if(!Td(e))return t.push("Hook script must be an object with either a 'command' property (command hook) or 'type: \"prompt\"' with a 'prompt' property (prompt hook)"),$d(!1,t);const r=e.type;return"prompt"===r?((e,t)=>{Id(e.prompt)?""===e.prompt.trim()&&t.push("Prompt hook 'prompt' property cannot be empty"):t.push("Prompt hook must have a 'prompt' property (string)"),void 0!==e.model&&(Id(e.model)?""===e.model.trim()&&t.push("Prompt hook 'model' cannot be an empty string"):t.push("Prompt hook 'model' must be a string if provided"))})(e,t):"command"===r||void 0===r?((e,t)=>{Id(e.command)||t.push("Hook script command must be a string")})(e,t):t.push(`Invalid hook type: "${r}". Must be "command", "prompt", or omitted (defaults to "command")`),((e,t)=>{if(void 0!==e.matcher)if(Id(e.matcher)){if(""!==e.matcher&&"*"!==e.matcher)try{new RegExp(e.matcher)}catch(r){t.push(`Hook script matcher "${e.matcher}" is not a valid regex: ${r?.message??String(r)}`)}}else t.push("Hook script matcher must be a string if provided");if(void 0!==e.timeout&&("number"!=typeof e.timeout?t.push("Hook script timeout must be a number (seconds)"):e.timeout<=0?t.push("Hook script timeout must be a positive number"):e.timeout>3600&&console.warn(`[hooks] Hook timeout of ${e.timeout}s is very long (>1 hour)`)),void 0!==e.loop_limit){const r=e.loop_limit;null!==r&&("number"!=typeof r?t.push("Hook script loop_limit must be a positive integer or null"):Number.isInteger(r)?r<=0&&t.push("Hook script loop_limit must be a positive integer (use null for no limit)"):t.push("Hook script loop_limit must be an integer"))}void 0!==e.failClosed&&"boolean"!=typeof e.failClosed&&t.push("Hook script failClosed must be a boolean")})(e,t),$d(0===t.length,t)},Od=(e,t)=>{const r=[];if(!Array.isArray(e))return r.push(`${t} must be an array of hook scripts`),$d(!1,r);for(let n=0;n{const t=[];if(!Td(e))return t.push("Hooks config must be an object"),$d(!1,t);if("number"!=typeof e.version?t.push("Config version must be a number"):(!Number.isInteger(e.version)||e.version<1)&&t.push("Config version must be a positive integer"),!Td(e.hooks))return t.push("Config hooks must be an object"),$d(!1,t);void 0!==e.stop_hook_loop_limit&&console.warn("[hooks] DEPRECATION WARNING: 'stop_hook_loop_limit' is deprecated. Use 'loop_limit' on individual hook scripts instead. The configured value is being ignored.");const r=Object.values(Rd),n=e.hooks;for(const[e,o]of Object.entries(n))if(r.includes(e)){if(void 0!==o){const r=Od(o,e);r.isValid||t.push(...r.errors)}}else t.push(`Unknown hook type: ${e}. Valid types are: ${r.join(", ")}`);return $d(0===t.length,t)},Nd={PreToolUse:Rd.preToolUse,PermissionRequest:null,PostToolUse:Rd.postToolUse,UserPromptSubmit:Rd.beforeSubmitPrompt,Stop:Rd.stop,SubagentStop:Rd.subagentStop,SessionStart:Rd.sessionStart,SessionEnd:Rd.sessionEnd,PreCompact:Rd.preCompact,Notification:null},Ld=Object.fromEntries(Object.entries(Nd).filter((e=>jd(e[0])&&null!==e[1])).map((([e,t])=>[t,e])));function jd(e){return Object.prototype.hasOwnProperty.call(Nd,e)}const Ud={Bash:"Shell",Read:"Read",Write:"Write",Edit:"Write",Glob:null,Grep:"Grep",WebFetch:"WebFetch",WebSearch:"WebSearch",Task:"Task"},Bd=["Glob"],Wd=["Notification","PermissionRequest"],Hd=/^[A-Za-z0-9_./:=+-]+$/,qd=/^=|^-.*\./,zd=/\$\{(?:CLAUDE_PROJECT_DIR|CURSOR_PROJECT_DIR|CLAUDE_PLUGIN_ROOT|CURSOR_PLUGIN_ROOT)\}/g,Gd=/^[^\p{Cc}$`"]*$/u,Vd=/\\(?:[$`"\\]|$)/;function Kd(e){return`'${e.replace(/'/g,"'\\''")}'`}function Jd(e){if(Hd.test(e)&&!qd.test(e))return e;const t=e.replace(zd,"");if((t!==e||e.includes("'"))&&Gd.test(t)&&!Vd.test(e))return`"${e}"`;const r=[];let n=0;for(const t of e.matchAll(zd))t.index>n&&r.push(Kd(e.slice(n,t.index))),r.push(`"${t[0]}"`),n=t.index+t[0].length;return(n{},info:()=>{}};function Xd(e,t,r=Zd){const n={loop_limit:null,failClosed:!1};if(t&&"*"!==t&&(n.matcher=t),void 0!==e.timeout&&(n.timeout=e.timeout),"prompt"===e.type)return e.prompt?{type:"prompt",prompt:e.prompt,...n}:null;const o=function(e,t){const r=e.command;if(!r)return null;const n=e.args;return null==n?(void 0!==e.shell&&t.warn(`Hook "${r}" sets shell "${e.shell}", which Cursor does not support; the platform default shell will be used`),r):(o=n,Array.isArray(o)&&o.every((e=>"string"==typeof e))?function(e,t){return[e,...t].map(Jd).join(" ")}(r,n):(t.warn(`Hook "${r}" has invalid "args" (expected an array of strings), skipping`),null));var o}(e,r);return null===o?null:{type:"command",command:o,...n}}function Qd(e,t,r=Zd){const n=[];let o;if("PreToolUse"===t||"PostToolUse"===t){const t=function(e,t=Zd){if(!e||"*"===e)return"*";const r=e.split("|"),n=[],o=[];for(const e of r){const t=e.trim();if(t.startsWith("mcp__")){const e=t.split("__");if(e.length>=3){const t=e.slice(2).join("__");n.push(`MCP:${t}`);continue}}const r=Ud[t];null!==r?void 0!==r?n.includes(r)||n.push(r):n.push(t):Bd.includes(t)&&o.push(`Tool "${t}" is not supported in Cursor and will be ignored`)}for(const e of o)t.warn(e);return 0===n.length?null:n.join("|")}(e.matcher,r);if(null===t)return r.warn(`All tools in matcher "${e.matcher}" are unsupported, skipping hooks`),[];o="*"===t?void 0:t}else"SessionStart"===t||"PreCompact"===t?(e.matcher&&"*"!==e.matcher&&""!==e.matcher&&("SessionStart"===t?["startup","resume","clear","compact"].includes(e.matcher):["manual","auto"].includes(e.matcher))&&r.warn(`${t} trigger matcher "${e.matcher}" is not supported in Cursor, hooks will fire for all triggers`),o=void 0):o=void 0;for(const t of e.hooks){const e=Xd(t,o,r);e&&n.push(e)}return n}function Yd(e,t=Zd){const r={};for(const[n,o]of Object.entries(e)){if(!jd(n)){t.warn(`Unknown Claude Code event "${n}", skipping`);continue}if(Wd.includes(n)){t.warn(`Claude Code event "${n}" is not supported in Cursor and will be ignored`);continue}const e=Nd[n];if(!e){t.warn(`Unknown Claude Code event "${n}", skipping`);continue}const s=[];if(Array.isArray(o))for(const e of o){const r=Qd(e,n,t);s.push(...r)}else void 0!==o&&t.warn(`Claude Code event "${n}" has invalid value (expected array), skipping`);if(s.length>0){const t=r[e]||[];r[e]=[...t,...s]}}return{version:1,hooks:r}}var eh=r("../../node_modules/.pnpm/gray-matter@4.0.3/node_modules/gray-matter/index.js");const th=()=>({});function rh(e,t){return eh(e,{...t,engines:{...t?.engines,js:th,javascript:th}})}function nh(e,t,r){return eh.stringify({content:e,data:{}},t,r)}var oh=r("node:zlib");function sh(e,t){const r=function(e){return e.split(/[/\\]/).filter((e=>e))}(e);for(let e=0;ee.isDirectory())).map((e=>e.name))}catch{return[]}}async removeVersion(e){const t=this.getCacheDir(e);try{await(0,xo.rm)(t,{recursive:!0,force:!0})}catch{}}async removeAllVersions(e){const t=ph(this.cacheRoot,e);await(0,xo.rm)(t,{recursive:!0,force:!0})}async pruneOldVersions(e){const t=await this.listCachedVersions({marketplaceSlug:e.marketplaceSlug,pluginId:e.pluginId}),r=new Set(e.keepVersions.map((e=>dh(e))));for(const n of t)r.has(n)||await this.removeVersion({marketplaceSlug:e.marketplaceSlug,pluginId:e.pluginId,version:n})}async markCacheComplete(e){const t=this.getCacheDir(e);await(0,xo.writeFile)(hh({parent:t,name:uh}),"")}}class mh extends Error{constructor(e,t){super(t),this.reason=e,this.name="PluginContentInstallError"}}const gh=(0,Vs.promisify)(oh.gunzip),wh=/^[A-Za-z0-9._-]{1,128}$/,yh=/^[0-9a-f]{64}$/,vh=/^[1-9]\d{0,18}$/,bh="backend-content://",Sh="backend-content/",kh=new Map([[3,"request_refused"],[5,"not_found"],[9,"account_not_connected"],[10,"revision_superseded"],[12,"unsupported_server"],[14,"unavailable"]]),_h=new Set(["unavailable","revision_superseded","timeout","download_failed","integrity"]);function Ch(e){return e instanceof mh&&_h.has(e.reason)}class Eh{constructor(){this.awaited=new Map}forListing(e){return{startLoad:()=>{for(const[t,r]of this.awaited)r.listing===e&&(r.attemptedThisLoad?r.attemptedThisLoad=!1:this.awaited.delete(t))},heldFailure:({pluginDbId:e,revision:t})=>{const r=this.awaited.get(e);if(void 0!==r&&r.revision===t)return r.attemptedThisLoad=!0,Date.now(){Ch(n)?this.awaited.set(t,{revision:r,reason:n.reason,retryAtMs:Date.now()+6e4,listing:e,attemptedThisLoad:!0}):this.awaited.delete(t)},isRetryDue:()=>this.isRetryDue(),allowImmediateRetry:()=>this.allowImmediateRetry()}}isRetryDue(){const e=Date.now();return[...this.awaited.values()].some((t=>e>=t.retryAtMs))}allowImmediateRetry(){for(const e of this.awaited.values())e.retryAtMs=0}}function xh(e){if("bigint"!=typeof e&&"number"!=typeof e&&"string"!=typeof e)return;const t=String(e);return vh.test(t)?t:void 0}function Ph(e){return e.startsWith(bh)}function Rh(e){return`${Sh}${e}`}function Ih(e,t){return new mh(e,function(e,t){const r=JSON.stringify(t);switch(e){case"unsupported_client":return`Plugin ${r} could not be downloaded: this client cannot install plugins whose files the server provides.`;case"not_found":return`Plugin ${r} could not be downloaded: it no longer exists or you no longer have access to it.`;case"account_not_connected":return`Plugin ${r} could not be downloaded: connect your account on the host of its source repository first.`;case"revision_superseded":return`Plugin ${r} changed while it was downloading. The new version installs on the next plugin refresh.`;case"unavailable":return`Plugin ${r} could not be downloaded: its files cannot be served right now. It installs on a later plugin refresh.`;case"unsupported_server":return`Plugin ${r} could not be downloaded: this server does not provide plugin files.`;case"request_refused":return`Plugin ${r} could not be downloaded: the server refused the request.`;case"download_failed":return`Plugin ${r} could not be downloaded.`;case"timeout":return`Downloading plugin ${r} timed out.`;case"integrity":return`The download of plugin ${r} did not match the size or hash the server gave for it, so it was discarded.`;case"too_large":return`Plugin ${r} could not be downloaded: its files are larger than this client accepts.`;case"unsafe_archive":return`The download of plugin ${r} could not be unpacked safely, so it was discarded.`;case"unpack_failed":return`The download of plugin ${r} could not be written to the plugin cache.`;default:return e}}(e,t))}function Th(e){if("File"!==e.type&&"OldFile"!==e.type&&"Directory"!==e.type)return!0;const t=e.path;return!(0!==t.length&&!t.includes("\0")&&!/^([/\\]|[A-Za-z]:)/.test(t))||t.split(/[/\\]/).includes("..")}async function Ah(e){const{download:t,pluginName:r,content:n,targetDir:o}=e;if(void 0===t)throw Ih("unsupported_client",r);const s=new AbortController;let i;try{i=await async function(e){const t=e[Symbol.asyncIterator](),r=()=>(0,Nr.wj)(t.next(),12e4);try{const e=await r();if(!0===e.done||"header"!==e.value.part.case)return"integrity";const{sha256:t}=e.value.part.value,n=function(e){let t;if("bigint"==typeof e||"number"==typeof e)t=Number(e);else{if("string"!=typeof e||!/^\d{1,15}$/.test(e))return;t=Number(e)}return Number.isSafeInteger(t)&&t>0?t:void 0}(e.value.part.value.sizeBytes);if(void 0===n||"string"!=typeof t||!yh.test(t))return"integrity";if(n>16777216)return"too_large";const o=[];let s=0;for(;;){const e=await r();if(!0===e.done)break;const{part:t}=e.value;if(void 0!==t.case){if("data"!==t.case||0===t.value.byteLength)return"integrity";if(s+=t.value.byteLength,s>n)return"integrity";o.push(t.value)}}const i=Buffer.concat(o,s);return s===n&&(0,ko.createHash)("sha256").update(i).digest("hex")===t?i:"integrity"}finally{Promise.resolve(t.return?.()).catch((()=>{}))}}(t({pluginId:BigInt(e.pluginDbId),revision:n.revision},{signal:s.signal}))}catch(e){throw Ih(function(e){return e instanceof Nr.MU?"timeout":"object"==typeof e&&null!==e&&"code"in e?"number"!=typeof e.code?"download_failed":kh.get(e.code)??"download_failed":"download_failed"}(e),r)}finally{s.abort()}if("string"==typeof i)throw Ih(i,r);const a=await async function(e){let t;try{t=await gh(e,{maxOutputLength:268435456})}catch{return}const r=t.byteLength>=512,n=r&&31===t[0]&&139===t[1],o=r&&682962941===t.readUInt32BE(0);if(r&&!n&&!o)return t}(i);if(void 0===a||!await function(e){return new Promise((t=>{let r=0;const n=(0,ah.p_)({strict:!0,onReadEntry:e=>{r+=1,(r>5e4||Th(e))&&(t(!1),n.abort(new Error("unsafe entry")))}});n.once("end",(()=>t(r>0))),n.once("error",(()=>t(!1))),n.end(e)}))}(a))throw Ih("unsafe_archive",r);try{await async function(e,t){const r=(0,ah.o6)({cwd:t,strict:!0,preserveOwner:!1,filter:(e,t)=>{if(!("type"in t)||Th(t))return!1;const r=!!(64&(t.mode??0));return t.mode="Directory"===t.type||r?493:420,!0}});await new Promise(((t,n)=>{r.once("close",t),r.once("error",n),r.end(e)}))}(a,o)}catch{throw Ih("unpack_failed",r)}}function $h(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")||"/"}function Mh(e,t){if(Object.hasOwn(e,t))return e[t]}function Dh(e,t,r,n){const o=e?.plugins;if(!o||"object"!=typeof o)return[];const s=t?.enabledPlugins??{},i={};r?.enabledPlugins&&Object.assign(i,r.enabledPlugins);const a=void 0!==n?$h(n):void 0,c=new Set,l=[];for(const[e,t]of Object.entries(o)){if(!Array.isArray(t)||0===t.length)continue;if(void 0!==a&&!1===Mh(i,e))continue;let r;void 0!==a&&(r=t.find((t=>!("project"!==t.scope&&"local"!==t.scope||!t.projectPath)&&($h(t.projectPath)===a&&!0===Mh(i,e))))),r||!0!==Mh(s,e)||(r=t.find((e=>"user"===e.scope))),r?.installPath&&!c.has(e)&&(l.push({pluginId:e,installPath:r.installPath}),c.add(e))}return l}var Oh=r("../../node_modules/.pnpm/js-yaml@4.3.1/node_modules/js-yaml/dist/js-yaml.mjs");const Fh=Be.enum(["canvas"]),Nh=Be.array(Fh).transform((e=>[...new Set(e)].sort())),Lh=new Set(["https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","https://agent-plugins.org/schemas/1.0.0/mcp.schema.json"]),jh=/^v?(\d+\.\d+(?:\.\d+)?)$/;function Uh(e){if("object"!=typeof(t=e)||null===t||Array.isArray(t))return;var t;const r=e.$schema;return"string"==typeof r&&r.length>0?r:void 0}function Bh(e){let t;try{t=new URL(e).pathname.split("/")}catch{t=e.split("/")}for(const e of t){const t=jh.exec(e);if(null!==t)return t[1]}}function Wh(e){return void 0===e?{kind:"absent"}:Lh.has(e)?{kind:"supported",id:e,version:Bh(e)??e}:{kind:"unsupported",id:e}}const Hh=10485760,qh=/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/,zh=[".cursor-plugin/plugin.json",".claude-plugin/plugin.json","plugin.json"],Gh=[".cursor-plugin",".claude-plugin"],Vh=[".cursor-plugin/marketplace.json",".claude-plugin/marketplace.json"],Kh=Be.object({source:Be.literal("github"),repo:Be.string().regex(/^[^/]+\/[^/]+$/,"Must be in owner/repo format"),ref:Be.string().optional(),sha:Be.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Jh=Be.object({source:Be.literal("url"),url:Be.string().url().endsWith(".git","URL must end with .git"),ref:Be.string().optional(),sha:Be.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Zh=Be.object({source:Be.literal("git-subdir"),url:Be.string().url().endsWith(".git","URL must end with .git"),path:Be.string().min(1),ref:Be.string().optional(),sha:Be.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Xh=Be.union([Be.string(),Kh,Jh,Zh]),Qh=/^(\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?|never)$/,Yh='Must be a semver version (X.Y.Z) or "never"',ep=Be.object({cursor:Be.string().regex(Qh,Yh).optional(),sand:Be.string().regex(Qh,Yh).optional(),sandMobile:Be.string().regex(Qh,Yh).optional()}),tp=Be.object({name:Be.string().min(1,"Author name is required"),email:Be.string().email().optional()}),rp=Be.enum(["string","number","integer","boolean","object","array","null"]),np=Be.union([rp,Be.array(rp).nonempty().superRefine(((e,t)=>{new Set(e).size!==e.length&&t.addIssue({code:Be.ZodIssueCode.custom,message:"Schema type arrays must not contain duplicates"})}))]);function op(e,t){if(void 0!==e.required)if(void 0===e.properties)for(const r of e.required)t.addIssue({code:Be.ZodIssueCode.custom,message:`Required property "${r}" must be declared in properties`,path:["required"]});else for(const r of e.required)r in e.properties||t.addIssue({code:Be.ZodIssueCode.custom,message:`Required property "${r}" must be declared in properties`,path:["required"]});void 0!==e.minLength&&void 0!==e.maxLength&&e.minLength>e.maxLength&&t.addIssue({code:Be.ZodIssueCode.custom,message:"minLength must be less than or equal to maxLength",path:["minLength"]}),void 0!==e.minimum&&void 0!==e.maximum&&e.minimum>e.maximum&&t.addIssue({code:Be.ZodIssueCode.custom,message:"minimum must be less than or equal to maximum",path:["minimum"]}),void 0!==e.exclusiveMinimum&&void 0!==e.exclusiveMaximum&&e.exclusiveMinimum>=e.exclusiveMaximum&&t.addIssue({code:Be.ZodIssueCode.custom,message:"exclusiveMinimum must be less than exclusiveMaximum",path:["exclusiveMinimum"]}),void 0!==e.minItems&&void 0!==e.maxItems&&e.minItems>e.maxItems&&t.addIssue({code:Be.ZodIssueCode.custom,message:"minItems must be less than or equal to maxItems",path:["minItems"]}),void 0!==e.minProperties&&void 0!==e.maxProperties&&e.minProperties>e.maxProperties&&t.addIssue({code:Be.ZodIssueCode.custom,message:"minProperties must be less than or equal to maxProperties",path:["minProperties"]})}const sp=Be.lazy((()=>Be.object({type:np.optional(),title:Be.string().optional(),description:Be.string().optional(),format:Be.string().optional(),writeOnly:Be.boolean().optional(),placeholder:Be.string().optional(),default:Be.unknown().optional(),enum:Be.array(Be.any()).nonempty().optional(),const:Be.unknown().optional(),properties:Be.record(Be.string(),sp).optional(),required:Be.array(Be.string()).optional(),additionalProperties:Be.union([Be.boolean(),sp]).optional(),items:Be.union([sp,Be.array(sp)]).optional(),minLength:Be.number().int().nonnegative().optional(),maxLength:Be.number().int().nonnegative().optional(),minimum:Be.number().optional(),maximum:Be.number().optional(),exclusiveMinimum:Be.number().optional(),exclusiveMaximum:Be.number().optional(),multipleOf:Be.number().positive().optional(),minItems:Be.number().int().nonnegative().optional(),maxItems:Be.number().int().nonnegative().optional(),uniqueItems:Be.boolean().optional(),minProperties:Be.number().int().nonnegative().optional(),maxProperties:Be.number().int().nonnegative().optional()}).strict().superRefine(op)));function ip(e){const t=sp.superRefine(((e,t)=>{lp(e)&&"object"===e.type||t.addIssue({code:Be.ZodIssueCode.custom,message:'Plugin variable schemas must declare type "object"',path:["type"]})})).safeParse(e);return t.success?up(t.data)?{success:!0,data:t.data}:{success:!1,error:new Be.ZodError([{code:"custom",path:["type"],message:'Plugin variable schemas must declare type "object"'}])}:{success:!1,error:t.error}}const ap=Be.unknown().superRefine(((e,t)=>{const r=ip(e);if(!r.success)for(const e of r.error.issues)t.addIssue({code:"custom",message:e.message,path:e.path})})).transform((e=>{if(!up(e))throw new Error('Plugin variable schema must declare type "object"');return e})),cp=(Be.object({name:Be.string().min(1).transform((e=>e.toLowerCase())).refine((e=>qh.test(e)),"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:Be.string().optional(),source:Xh,description:Be.string().optional(),version:Be.string().optional(),author:tp.optional(),publisher:Be.string().min(1).optional(),homepage:Be.string().url().optional(),repository:Be.string().url().optional(),license:Be.string().optional(),keywords:Be.array(Be.string()).optional(),capabilities:Nh.optional(),logo:Be.string().optional(),category:Be.string().optional(),tags:Be.array(Be.string()).optional(),minClientVersions:ep.optional(),strict:Be.boolean().default(!0),commands:Be.union([Be.string(),Be.array(Be.string())]).optional(),agents:Be.union([Be.string(),Be.array(Be.string())]).optional(),skills:Be.union([Be.string(),Be.array(Be.string())]).optional(),rules:Be.union([Be.string(),Be.array(Be.string())]).optional(),hooks:Be.union([Be.string(),Be.record(Be.string(),Be.unknown())]).optional(),variables:ap.optional(),mcpServers:Be.union([Be.string(),Be.record(Be.string(),Be.unknown()),Be.array(Be.union([Be.string(),Be.record(Be.string(),Be.unknown())]))]).optional()}),Be.object({description:Be.string().optional(),version:Be.string().optional(),pluginRoot:Be.string().optional()}),Be.object({name:Be.string().min(1).regex(qh,"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:Be.string().optional(),description:Be.string().optional(),version:Be.string().optional(),author:tp.optional(),publisher:Be.string().min(1).optional(),homepage:Be.string().url().optional(),repository:Be.string().url().optional(),license:Be.string().optional(),logo:Be.string().optional(),keywords:Be.array(Be.string()).optional(),capabilities:Nh.optional(),minClientVersions:ep.optional(),commands:Be.union([Be.string(),Be.array(Be.string())]).optional(),agents:Be.union([Be.string(),Be.array(Be.string())]).optional(),skills:Be.union([Be.string(),Be.array(Be.string())]).optional(),rules:Be.union([Be.string(),Be.array(Be.string())]).optional(),hooks:Be.union([Be.string(),Be.record(Be.string(),Be.unknown())]).optional(),variables:ap.optional(),mcpServers:Be.union([Be.string(),Be.record(Be.string(),Be.unknown()),Be.array(Be.union([Be.string(),Be.record(Be.string(),Be.unknown())]))]).optional()}));function lp(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function up(e){return lp(e)&&"object"===e.type}function dp(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function hp(e,t){if(lp(e)&&"string"==typeof e.name){const t=dp(e.name);if(t.length>0)return t}return function(e){const t=void 0!==e.repoName?dp(e.repoName):"";return t.length>0?t:`cursor-marketplace-${e.fallbackId??(0,ko.randomUUID)()}`}(t)}function pp(e){if(lp(e)&&lp(e.owner)){const t="string"==typeof e.owner.name&&e.owner.name.trim().length>0?e.owner.name:"Unknown",r="string"==typeof e.owner.email&&e.owner.email.trim().length>0?e.owner.email:void 0;return{name:t,...void 0!==r?{email:r}:{}}}return{name:"Unknown"}}function fp(e){return"string"==typeof e?e:void 0}function mp(e){if(!Array.isArray(e))return;const t=e.filter((e=>"string"==typeof e));return t.length>0?t:void 0}function gp(e){return"string"==typeof e?e:mp(e)}function wp(e){if(!lp(e)||!lp(e.metadata))return;const t={description:fp(e.metadata.description),version:fp(e.metadata.version),pluginRoot:fp(e.metadata.pluginRoot)};return void 0!==t.description||void 0!==t.version||void 0!==t.pluginRoot?t:void 0}function yp(e){if(!lp(e))return;const t=fp(e.name);if(void 0===t||0===t.length)return;const r=fp(e.email);return{name:t,...void 0!==r?{email:r}:{}}}function vp(e){if("string"==typeof e||lp(e))return e;if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e||lp(e)));return t.length>0?t:void 0}}function bp(e){if("string"==typeof e||lp(e))return e}function Sp(e){if(void 0===e)return;const t=ip(e);return t.success?t.data:void 0}function kp(e,t={}){if(e.length>Hh)return{success:!1,error:"Manifest exceeds maximum size of 10485760 bytes"};let r;try{r=JSON.parse(e)}catch(e){return{success:!1,error:`Invalid JSON: ${e instanceof Error?e.message:"Unknown error"}`}}if(!lp(r))return{success:!1,error:"Invalid marketplace manifest: expected a JSON object"};const n=[],o=[],i=new Set;return(Array.isArray(r.plugins)?r.plugins:[]).forEach(((e,t)=>{const r=function(e,t){if(!lp(e))return{skippedEntry:{index:t,error:`Plugin entry at index ${t} is not an object`}};const r="string"==typeof(n=e.source)?n:lp(n)?"github"===n.source&&"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:fp(n.ref),sha:fp(n.sha)}:("url"===n.source||void 0===n.source)&&"string"==typeof n.url&&n.url.length>0?{source:"url",url:n.url,ref:fp(n.ref),sha:fp(n.sha)}:"git-subdir"===n.source&&"string"==typeof n.url&&n.url.length>0&&"string"==typeof n.path&&n.path.length>0?{source:"git-subdir",url:n.url,path:n.path,ref:fp(n.ref),sha:fp(n.sha)}:"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:fp(n.ref),sha:fp(n.sha)}:void 0:void 0;var n;if(void 0===r){const r=fp(e.name);return{skippedEntry:{index:t,...void 0!==r&&r.length>0?{name:r}:{},error:`Plugin entry at index ${t} has no usable source`}}}const o=("string"==typeof e.name?dp(e.name):"")||function(e){if("string"==typeof e){const t=dp((0,s.basename)(e));return t.length>0?t:void 0}if("github"===e.source){const t=dp(e.repo.split("/").at(-1)??"");return t.length>0?t:void 0}if("git-subdir"===e.source){const t=dp((0,s.basename)(e.path));return t.length>0?t:void 0}let t=e.url;try{t=new URL(e.url).pathname}catch{}for(;t.endsWith("/");)t=t.slice(0,-1);t.toLowerCase().endsWith(".git")&&(t=t.slice(0,-4));const r=dp((0,s.basename)(t));return r.length>0?r:void 0}(r);if(void 0===o)return{skippedEntry:{index:t,error:`Plugin entry at index ${t} has no usable name`}};const i=Nh.safeParse(e.capabilities);if(void 0!==e.capabilities&&!i.success)return{skippedEntry:{index:t,name:o,error:`Plugin entry at index ${t} has invalid capabilities: ${i.error.issues.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`}};const a=i.success?i.data:void 0,c=function(e){const t=ep.safeParse(e);if(t.success&&(void 0!==t.data.cursor||void 0!==t.data.sand||void 0!==t.data.sandMobile))return t.data}(e.minClientVersions);return{entry:{name:o,displayName:fp(e.displayName),source:r,description:fp(e.description),version:fp(e.version),author:yp(e.author),publisher:fp(e.publisher),homepage:fp(e.homepage),repository:fp(e.repository),license:fp(e.license),keywords:mp(e.keywords),logo:fp(e.logo),category:fp(e.category),tags:mp(e.tags),strict:"boolean"!=typeof e.strict||e.strict,commands:gp(e.commands),agents:gp(e.agents),skills:gp(e.skills),rules:gp(e.rules),hooks:bp(e.hooks),variables:Sp(e.variables),mcpServers:vp(e.mcpServers),...void 0!==a&&{capabilities:a},...void 0!==c&&{minClientVersions:c}}}}(e,t);"skippedEntry"in r?o.push(r.skippedEntry):i.has(r.entry.name)?o.push({index:t,name:r.entry.name,error:`Duplicate plugin name "${r.entry.name}" at index ${t}`}):(i.add(r.entry.name),n.push(r.entry))})),{success:!0,data:{name:hp(r,t),owner:pp(r),description:fp(r.description),plugins:n,metadata:wp(r),skippedPluginEntries:o}}}function _p(e){if(e.length>Hh)return{success:!1,error:"Manifest exceeds maximum size of 10485760 bytes"};let t;try{t=JSON.parse(e)}catch(e){return{success:!1,error:`Invalid JSON: ${e instanceof Error?e.message:"Unknown error"}`}}const r=Wh(Uh(t)),n=cp.safeParse(t);return n.success?{success:!0,data:n.data,..."unsupported"===r.kind&&{unrecognizedSchemaId:r.id}}:{success:!1,error:`Invalid plugin manifest: ${n.error.issues.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`,details:n.error}}function Cp(e,t){if("string"!=typeof e)return null;let r=e;if(r.startsWith("./")&&(r=r.slice(2)),void 0!==t){let e=t;e.startsWith("./")&&(e=e.slice(2)),e.endsWith("/")&&(e=e.slice(0,-1)),r=`${e}/${r}`}return r||"."}function Ep(e){return!e.includes("..")&&!(0,s.isAbsolute)(e)&&!e.includes("://")}var xp=r("../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js");const Pp=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g,Rp=/\$%7B([^%/?#]+?)%7D/gi;function Ip(e,t){return Tp(e,"function"==typeof t?t:function(e){const t=new Map(Object.entries(e).map((([e,t])=>[e.toLowerCase(),t])));return r=>e[r]??t.get(r.toLowerCase())}(t))}function Tp(e,t){if("string"==typeof e)return function(e,t){return e.replace(Rp,"${$1}").replace(Pp,((e,r,n,o)=>{if(void 0!==r)return t(r)??e;if(void 0===n)return e;const s=t(n);return void 0!==s?s:void 0!==o?o:e}))}(e,t);if(Array.isArray(e))return e.map((e=>Tp(e,t)));if(function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e)){const r={};for(const[n,o]of Object.entries(e))r[n]=Tp(o,t);return r}return e}function Ap(e,t){return e.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g,(()=>t)).replace(/\$\{CURSOR_PLUGIN_ROOT\}/g,(()=>t))}const $p={log:()=>{},increment:()=>{},distribution:()=>{},captureException:()=>{}},Mp=Be.object({command:Be.string().optional(),args:Be.array(Be.string()).optional(),env:Be.record(Be.string(),Be.string()).optional(),url:Be.string().optional(),headers:Be.record(Be.string(),Be.string()).optional(),cwd:Be.string().optional(),envFile:Be.string().optional(),auth:Be.object({CLIENT_ID:Be.string(),CLIENT_SECRET:Be.string().optional(),scopes:Be.array(Be.string()).optional()}).optional(),enabledTools:Be.array(Be.string()).optional(),placement:Be.enum(["server","client"]).optional(),tls:Be.object({caBundle:Be.string().trim().min(1).max(131072)}).optional()}),Dp=Be.object({mcpServers:Be.record(Be.string(),Mp).optional()}),Op=[".mcp.json","mcp.json"],Fp=new Set(["author","owner","source","metadata"].map((e=>e.toLowerCase())));function Np(e,t){if(!function(e){return Fp.has(e.toLowerCase())}(e))return!1;if(!function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(t))return!1;const r=t;switch(e.toLowerCase()){case"author":case"owner":return"string"==typeof r.name;case"source":return"string"==typeof r.source||"string"==typeof r.repo||"string"==typeof r.path||"string"==typeof r.ref||"string"==typeof r.sha;case"metadata":return"string"==typeof r.description||"string"==typeof r.version||"string"==typeof r.pluginRoot;default:return!1}}function Lp(e){return"object"==typeof e&&null!==e&&("command"in e||"url"in e)}function jp(e){const t=void 0!==e&&e.length>0?e.replace(/\/+$/,""):void 0;return Op.map((e=>void 0!==t?`${t}/${e}`:e))}function Up(e,t,r){if(!e.mcpServers)return e;const n={};for(const[r,o]of Object.entries(e.mcpServers)){const e={...o};if("string"==typeof o.command&&(e.command=Ap(o.command,t)),Array.isArray(o.args)&&(e.args=o.args.map((e=>"string"==typeof e?Ap(e,t):e))),o.env&&"object"==typeof o.env){const r={};for(const[e,n]of Object.entries(o.env))r[e]="string"==typeof n?Ap(n,t):n;e.env=r}"string"==typeof o.cwd&&(e.cwd=Ap(o.cwd,t)),n[r]=e}return function(e,t){const r=t?.cloudAgentEnvLookup,n=t?.configuredVariables;if(void 0!==r)return Ip(e,r);const o=new Map(Object.keys(n??{}).map((e=>[e.toLowerCase(),e])));return Ip(e,(e=>{const t=process.env[e];if(void 0!==t)return t;const r=void 0!==n&&Object.hasOwn(n,e)?e:o.get(e.toLowerCase()),s=void 0!==r?n?.[r]:void 0;return null!=s?"string"==typeof s?s:"number"==typeof s||"boolean"==typeof s||"bigint"==typeof s?String(s):JSON.stringify(s):void 0}))}({...e,mcpServers:n},r)}function Bp(e,t,r){try{const n=(0,xp.qg)(e),o=Uh(n);if(void 0!==o){const e=r?.log??$p;"unsupported"===Wh(o).kind?e.log("debug",`mcp.json declares an unrecognized $schema, loading anyway: ${o}`):function(e,t){if(void 0===e||void 0===t)return!1;const r=Bh(e),n=Bh(t);return void 0!==r&&void 0!==n&&r!==n}(r?.pluginSchemaId,o)&&e.log("debug",`mcp.json $schema ${o} disagrees with plugin.json $schema ${r?.pluginSchemaId}, loading anyway`)}const s=Dp.safeParse(n),i=!0===r?.skipExpansion;if(s.success&&s.data.mcpServers&&Object.keys(s.data.mcpServers).length>0)return i?s.data:Up(s.data,t,r);const a={};for(const[e,t]of Object.entries(n))"mcpServers"!==e&&!Np(e,t)&&Lp(t)&&(a[e]=t);if(Object.keys(a).length>0){const e=Dp.safeParse({mcpServers:a});if(e.success)return i?e.data:Up(e.data,t,r)}return null}catch{return null}}function Wp(e,t,r){for(const[n,o]of Object.entries(t))e.mcpServers[n]=o,e.mcpServerSourcePaths[n]=r}async function Hp(e,t,r,n={}){const o=n.toSourcePath??(e=>e),s=n.installPathForExpansion??"",i=n.fallbackFileNames??Op,a=n.manifestPrecedence??"override",c={},l={};for(const t of i){const r=await e(t);if(null===r)continue;const i=Bp(r,s,n.parserOptions);if(i?.mcpServers)for(const[e,r]of Object.entries(i.mcpServers))void 0===c[e]&&(c[e]=r,l[e]=o(t))}if(void 0!==t){const i=await async function(e,t,r={}){const n=r.toSourcePath??(e=>e),o=r.installPathForExpansion??"",s={mcpServers:{},mcpServerSourcePaths:{}},i=async e=>{const i=e.replace(/^\.\//,"");if(!Ep(i))return;const a=await t(i);if(null===a)return;const c=Bp(a,o,r.parserOptions);c?.mcpServers&&Object.keys(c.mcpServers).length>0&&Wp(s,c.mcpServers,n(i))},a=e=>{const t=Bp(JSON.stringify(e),o,r.parserOptions);t?.mcpServers&&Object.keys(t.mcpServers).length>0&&Wp(s,t.mcpServers,r.manifestSourcePath??"manifest")};if("string"==typeof e)await i(e);else if(Array.isArray(e))for(const t of e)"string"==typeof t?await i(t):"object"==typeof t&&null!==t&&a(t);else"object"==typeof e&&null!==e&&a(e);return s}(t,e,{toSourcePath:o,manifestSourcePath:r,installPathForExpansion:s,parserOptions:n.parserOptions});for(const[e,t]of Object.entries(i.mcpServers))"fill"===a&&void 0!==c[e]||(c[e]=t,l[e]=i.mcpServerSourcePaths[e])}return 0===Object.keys(c).length?null:{mcpServers:c,...Object.keys(l).length>0&&{mcpServerSourcePaths:l}}}const qp=new Set(["CREDENTIAL","CREDENTIALS","KEY","PASSPHRASE","PASSWORD","SECRET","TOKEN"]);function zp(e){return function(e){return e.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/[^a-z\d]+/gi,"_").toUpperCase().split("_").filter((e=>e.length>0))}(e).some((e=>qp.has(e)))}const Gp=/\$\{(?:env:([A-Z][A-Z0-9_]*)|([A-Z][A-Z0-9_]*)(?::-([^}]*))?)\}/g,Vp=new Set(["CURSOR_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT"]),Kp=new Set(["api","aws","db","dd","gcp","http","https","id","mcp","ssl","tls","uri","url"]);function Jp(e){return e.split("_").filter((e=>e.length>0)).map((e=>{const t=e.toLowerCase();return Kp.has(t)?e.toUpperCase():e.charAt(0).toUpperCase()+t.slice(1)})).join(" ")}function Zp(e,t){if("string"!=typeof e){if(Array.isArray(e))for(const r of e)Zp(r,t);else if(null!==e&&"object"==typeof e)for(const r of Object.values(e))Zp(r,t)}else for(const[,r,n,o]of e.matchAll(Gp)){const e=r??n;if(void 0===e||Vp.has(e)||t.has(e))continue;const s=void 0===r?`\${${e}}`:`\${env:${e}}`;t.set(e,{reference:s,defaultValue:o})}}function Xp(e){if(void 0===e?.mcpServers)return;const t=new Map;if(Zp(e.mcpServers,t),0===t.size)return;const r={};for(const e of[...t.keys()].sort()){const n=t.get(e);if(void 0===n)continue;const{reference:o,defaultValue:s}=n;r[e]={type:"string",title:Jp(e),description:void 0===s||0===s.length?`Referenced as \`${o}\` in this plugin's MCP configuration.`:`Referenced as \`${o}\` in this plugin's MCP configuration. Defaults to \`${s}\` when left blank.`,...zp(e)?{writeOnly:!0}:{}}}return{type:"object",properties:r}}const Qp=[".md",".mdc",".markdown"],Yp=[...Qp,".txt"],ef=/^---\s*\n([\s\S]*?)\n---/;function tf(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function rf(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9.-]/g,"")}function nf(e){const t=e.match(ef);if(!t)return{};try{const e=Oh.Ay.load(t[1],{schema:Oh.Ay.JSON_SCHEMA});if(!tf(e))return{};const r=tf(e.metadata)?e.metadata:void 0,n=of(e.environments??r?.environments);return{disabledEnvironments:of(e["disabled-environments"]??r?.disabledEnvironments),environments:n,name:"string"==typeof e.name?e.name:void 0,description:"string"==typeof e.description?e.description:void 0}}catch{const e=t[1],r=e.match(/^name:\s*(.+)$/m),n=e.match(/^description:\s*(.+)$/m);return r||n?{name:r?r[1].trim():void 0,description:n?n[1].trim():void 0}:{}}}function of(e){if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e&&e.length>0));return 0===t.length?void 0:t}if("string"==typeof e){const t=e.split(",").map((e=>e.trim())).filter((e=>e.length>0));return 0===t.length?void 0:t}}function sf(e){return rf((0,s.basename)(e).replace(/\.(md|mdc|markdown|txt)$/i,""))}function af(e){const t=new Set,r=[];for(const n of e)t.has(n.name)||(t.add(n.name),r.push(n));return r}class cf{constructor(e){this.fetcher=e}async discoverComponents(e={}){const t=e.basePath??"",r=t?`${t}/`:"",n=e.manifest;let o;try{o=await this.fetcher.listDirectory(t)}catch{o=[]}const s=new Set(o.filter((e=>"dir"===e.type)).map((e=>e.name.toLowerCase()))),i=Op.filter((e=>o.some((t=>"file"===t.type&&t.name===e)))),a=o.some((e=>"file"===e.type&&"SKILL.md"===e.name)),[c,l,u,d,h,p,f]=await Promise.all([a&&void 0===n?.skills?this.discoverRootSkill(r):Promise.resolve(null),void 0!==n?.skills?this.discoverFromManifestPaths(r,n.skills,!0,Qp):s.has("skills")?this.discoverSkills(`${r}skills`):Promise.resolve([]),void 0!==n?.agents?this.discoverFromManifestPaths(r,n.agents,!1,Qp):s.has("agents")?this.discoverMarkdownComponents(`${r}agents`,Qp):Promise.resolve([]),void 0!==n?.hooks?this.discoverHooksFromManifest(r,n.hooks):s.has("hooks")?this.discoverHooksFromJson(`${r}hooks/hooks.json`):Promise.resolve([]),void 0!==n?.commands?this.discoverFromManifestPaths(r,n.commands,!1,Yp):s.has("commands")?this.discoverMarkdownComponents(`${r}commands`,Yp):Promise.resolve([]),void 0!==n?.rules?this.discoverFromManifestPaths(r,n.rules,!1,Qp):s.has("rules")?this.discoverMarkdownComponents(`${r}rules`,Qp):Promise.resolve([]),this.discoverMcpServers(r,n?.mcpServers,i)]);return{skills:af(c?[c,...l]:l),agents:af(u),hooks:d,commands:af(h),rules:af(p),mcpServers:f.servers,mcpVariables:f.variables,mcpConfigs:f.configs}}async discoverHooksFromJson(e){try{if(!await this.fetcher.fileExists(e))return[];const{content:t}=await this.fetcher.fetchFile(e),r=JSON.parse(t);return tf(r)&&tf(r.hooks)?Object.keys(r.hooks).map((t=>({name:rf(t),path:e,description:`Hook: ${t}`}))):[]}catch{return[]}}async discoverHooksFromManifest(e,t){if("string"==typeof t){if(!Ep(t))return[];const r=`${e}${t.replace(/^\.\//,"")}`;return r.endsWith(".json")?this.discoverHooksFromJson(r):this.discoverHooksFromJson(`${r}/hooks.json`)}const r=t.hooks??t;return!r||"object"!=typeof r||Array.isArray(r)?[]:Object.keys(r).map((e=>({name:rf(e),path:"manifest",description:`Hook: ${e}`})))}async discoverFromManifestPaths(e,t,r=!1,n=Qp){if("string"==typeof t){if(!Ep(t))return[];const o=`${e}${t.replace(/^\.\//,"")}`.replace(/\/$/,"");return r?this.discoverSkills(o):this.discoverMarkdownComponents(o,n)}const o=[];for(const n of t)try{if(!Ep(n))continue;const t=`${e}${n.replace(/^\.\//,"")}`;if(r){const e=t.endsWith("SKILL.md")?t:`${t.replace(/\/$/,"")}/SKILL.md`;if(!await this.fetcher.fileExists(e)){const e=t.replace(/\/$/,""),r=await this.discoverSkills(e);o.push(...r);continue}let r=sf(t.endsWith("SKILL.md")?t.slice(0,-8).replace(/\/$/,""):t);const{content:n}=await this.fetcher.fetchFile(e),s=nf(n);if(r=s.name??r,r){const t={disabledEnvironments:s.disabledEnvironments,environments:s.environments,name:rf(r),path:e};void 0!==s.description&&(t.description=s.description),o.push(t)}}else{if(!await this.fetcher.fileExists(t))continue;let e=sf(t);const{content:r}=await this.fetcher.fetchFile(t),n=nf(r);e=n.name??e;const s=n.description;if(e){const r={name:rf(e),path:t};void 0!==s&&(r.description=s),o.push(r)}}}catch{}return o}async discoverMarkdownComponents(e,t=Qp,r=new Set){let n;try{n=await this.fetcher.listDirectory(e,r)}catch{return[]}const o=n.filter((e=>"file"===e.type&&t.some((t=>e.name.endsWith(t))))),s=n.filter((e=>"dir"===e.type)),[i,a]=await Promise.all([Promise.all(o.map((async e=>{try{let t=sf(e.name);const{content:r}=await this.fetcher.fetchFile(e.path),n=nf(r);t=n.name?rf(n.name):t;const o=n.description;if(!t)return null;const s={name:t,path:e.path};return void 0!==o&&(s.description=o),s}catch{return null}}))),Promise.all(s.map((e=>this.discoverMarkdownComponents(e.path,t,r))))]);return[...i.filter((e=>null!==e)),...a.flat()]}async discoverRootSkill(e){try{const t=`${e}SKILL.md`;let r=rf((0,s.basename)(e.replace(/[\\/]+$/,"")));const{content:n}=await this.fetcher.fetchFile(t),o=nf(n);if(r=o.name?rf(o.name):r,!r)return null;const i={disabledEnvironments:o.disabledEnvironments,environments:o.environments,name:r,path:t};return void 0!==o.description&&(i.description=o.description),i}catch{return null}}async discoverSkills(e){let t;try{t=await this.fetcher.listDirectory(e)}catch{return[]}const r=t.filter((e=>"dir"===e.type));return(await Promise.all(r.map((async e=>{try{const t=`${e.path}/SKILL.md`;if(!await this.fetcher.fileExists(t))return null;const{content:r}=await this.fetcher.fetchFile(t),n=nf(r),o=n.name?rf(n.name):rf(e.name);if(!o)return null;const s={disabledEnvironments:n.disabledEnvironments,environments:n.environments,name:o,path:t};return void 0!==n.description&&(s.description=n.description),s}catch{return null}})))).filter((e=>null!==e))}async discoverMcpServers(e,t,r){const n=new Map,o=async t=>{const r=n.get(t);if(void 0!==r)return r;const o=this.fetcher.fetchFile(`${e}${t}`).then((({content:e})=>e)).catch((()=>null));return n.set(t,o),o},s=async n=>Hp(o,t,void 0!==t?"manifest":void 0,{fallbackFileNames:r,manifestPrecedence:n,toSourcePath:t=>`${e}${t}`,parserOptions:{skipExpansion:!0}}),i=await s("fill");if(void 0===i?.mcpServers)return{servers:[],variables:void 0,configs:void 0};const a=void 0===t?i:await s("override"),c=a?.mcpServers??i.mcpServers,l={};for(const[e,t]of Object.entries(c))l[e]=t;return{servers:Object.keys(i.mcpServers).map((e=>({name:rf(e),path:i.mcpServerSourcePaths?.[e]??"manifest"}))),variables:Xp(a??i),configs:l}}}class lf extends Error{constructor(e,t){super(`Invalid Claude Code plugin identifier "${t}": ${e}`),this.raw=t,this.name="CCPluginIdentifierError"}}function uf(e){const t=e.trim();if(!t)throw new lf("Empty identifier",e);const r=/^[a-zA-Z0-9_-]+$/,n=t.indexOf("@");if(n!==t.lastIndexOf("@"))throw new lf("Plugin identifier cannot contain multiple @ symbols",e);if(-1===n){if(!r.test(t))throw new lf("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(t.length>100)throw new lf("Plugin name must be 100 characters or less",e);return{name:t,sourceType:"marketplace",marketplace:"claude-plugins-official",raw:e}}const o=t.slice(0,n).trim(),s=t.slice(n+1).trim();if(!o)throw new lf("Missing plugin name before @",e);if(!s)throw new lf("Missing source after @",e);if(!r.test(o))throw new lf("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(o.length>100)throw new lf("Plugin name must be 100 characters or less",e);if(s.startsWith("github:")){const t=s.slice(7).trim();if(!t||!/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(t))throw new lf("Invalid GitHub repo format, expected 'org/repo' (e.g., 'anthropics/claude-plugins')",e);return{name:o,sourceType:"github",githubRepo:t,raw:e}}if(s.startsWith("local:")){const t=s.slice(6).trim();if(!t)throw new lf("Missing path after 'local:'",e);return{name:o,sourceType:"local",localPath:t,raw:e}}if(s.startsWith("url:")){const t=s.slice(4).trim();if(!t)throw new lf("Missing Git URL after 'url:'",e);try{new URL(t)}catch{throw new lf("Invalid Git URL format",e)}return{name:o,sourceType:"url",gitUrl:t,raw:e}}const i=s.indexOf("#");let a,c;if(-1!==i?(a=s.slice(0,i).trim(),c=s.slice(i+1).trim()):a=s,!a)throw new lf("Missing marketplace name",e);if(!r.test(a))throw new lf("Marketplace name must contain only alphanumeric characters, dashes, and underscores",e);return{name:o,sourceType:"marketplace",marketplace:a,version:c,raw:e}}function df(e){if("claude-plugin"===e.source)return e.sourceInfo.raw;if("user-local"===e.source)return`user-local:${e.sourceInfo.name}`;if("extension"===e.source){const t=e.sourceInfo;return`extension:${t.extensionId}:${t.localPath}`}const t=e.sourceInfo;return`${t.name}-${t.version}`}function hf(e){return e.sourceInfo.name}function pf(e){switch(e.source){case"claude-plugin":case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplace;default:return}}function ff(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.pluginDbId;default:return}}function mf(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplaceDbId;default:return}}function gf(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function wf(e){return!!gf(e)&&(void 0===e.enabledPlugins||gf(e.enabledPlugins))}function yf(e){return JSON.parse(e)}function vf(e){const t=e??process.env.HOME??"";return(0,s.join)(t,".claude")}async function bf(e){const t={enabledPlugins:{}};let r=!1;const n=(0,s.join)(e,".claude","settings.json");try{const e=yf(await(0,xo.readFile)(n,"utf-8"));wf(e)&&e.enabledPlugins&&(Object.assign(t.enabledPlugins,e.enabledPlugins),r=!0)}catch{}const o=(0,s.join)(e,".claude","settings.local.json");try{const e=yf(await(0,xo.readFile)(o,"utf-8"));wf(e)&&e.enabledPlugins&&(Object.assign(t.enabledPlugins,e.enabledPlugins),r=!0)}catch{}return r?t:null}function Sf(e,t){const r=(0,s.resolve)(e),n=(0,s.resolve)(e,t),o=(0,s.relative)(r,n);if(o.startsWith("..")||(0,s.isAbsolute)(o))throw new Error(`Invalid subPath: path traversal not allowed (${JSON.stringify(t)})`);return n}async function kf(e){try{return(await(0,xo.lstat)(e)).isSymbolicLink()}catch{return!1}}async function _f(e){if(await kf(e))throw new Error(`Refusing to read symlink: ${e}`);return(0,xo.readFile)(e,"utf-8")}async function Cf(e){if((await(0,xo.stat)(e)).size>10485760)throw new Error(`File ${e} exceeds maximum size of 10485760 bytes`)}function Ef(e){const t=e instanceof Error?e.message:String(e);return/timed?\s*out/i.test(t)?"timeout":/clone|fetch|git/i.test(t)?"clone":/manifest|marketplace\.json/i.test(t)?"manifest":/parse|invalid|malformed/i.test(t)?"parse":/install|download|copy/i.test(t)?"install":"unknown"}async function xf({installPath:e,logo:t}){const r=t?.trim();if(r&&!(0,s.isAbsolute)(r)&&!r.includes("://"))try{const t=await(0,xo.realpath)(e),n=Sf(t,r),o=await(0,xo.realpath)(n);if(Sf(t,o),!(await(0,xo.stat)(o)).isFile())return;return await Cf(o),(0,Pd.pathToFileURL)(o).href}catch{return}}function Pf(e){const t={};return void 0!==e.version&&(t.version=e.version),void 0!==e.homepage&&(t.homepage=e.homepage),void 0!==e.repository&&(t.repository=e.repository),t}function Rf(e){return void 0!==e.version||void 0!==e.homepage||void 0!==e.repository}function If(e,t){return Pf({version:e.version??t?.version,homepage:e.homepage??t?.homepage,repository:e.repository??t?.repository})}async function Tf(e,t,r){let n;for(const o of zh){const i=(0,s.join)(e,o);let a;try{if(await kf(i))continue;if(!(await(0,xo.stat)(i)).isFile())continue;await Cf(i),a=await _f(i)}catch{continue}const c=_p(a);if(!c.success)continue;const l=c.data,u=l.commands,d=l.agents,h=l.skills,p=l.rules,f=l.hooks,m=l.mcpServers,g=void 0!==u||void 0!==d||void 0!==h||void 0!==p||void 0!==f||void 0!==m,w="string"==typeof l.displayName?l.displayName:void 0,y="string"==typeof l.description?l.description:void 0,v=l.author?.name,b=await xf({installPath:e,logo:l.logo}),S=Pf(l),k=l.variables,_=l.capabilities,C=void 0!==w||void 0!==y||void 0!==v||void 0!==b||void 0!==k||void 0!==_;if(!g&&!C&&!Rf(S))continue;if(!g&&!C){n=n?{...n,fields:If(n.fields,S)}:{fields:S,path:i,relPath:o,unrecognizedSchemaId:c.unrecognizedSchemaId};continue}void 0!==c.unrecognizedSchemaId&&r.log("debug",`${t}: ${o} declares an unrecognized $schema, loading anyway: ${c.unrecognizedSchemaId}`);const E=If(S,n?.fields);return{manifestFilePath:i,...g&&{manifestOptions:{commands:u,agents:d,skills:h,rules:p,hooks:f,mcpServers:m}},...(C||Rf(E))&&{metadata:{displayName:w,description:y,authorName:v,logoUrl:b,...E,variables:k,capabilities:_}}}}if(void 0!==n)return void 0!==n.unrecognizedSchemaId&&r.log("debug",`${t}: ${n.relPath} declares an unrecognized $schema, loading anyway: ${n.unrecognizedSchemaId}`),{manifestFilePath:n.path,metadata:n.fields}}async function Af(e,t){const r=function(e,t){const r=new Map,n=(0,s.resolve)(e),o=(0,s.resolve)(t?.symlinkTargetRoot??n),i=(0,xo.realpath)(o).catch((()=>o));function a(e){const t=(0,s.resolve)(e);try{return Sf(n,t)}catch{throw new Error(`Path escapes plugin directory: ${e}`)}}async function c(e){const t=a(e),r=await i,n=await(0,xo.realpath)(t);try{return Sf(r,n)}catch{throw new Error(`Path escapes plugin directory via symlink: ${e}`)}}return{async listDirectory(t,r){const n=a(t?(0,s.join)(e,t):e);try{const e=await c(n);if(r?.has(e))return[];r?.add(e);const o=await(0,xo.readdir)(e,{withFileTypes:!0}),i=[];for(const e of o){const r=(0,s.join)(n,e.name);let o=e.isDirectory()?"dir":"file";if(e.isSymbolicLink())try{const e=await c(r);o=(await(0,xo.stat)(e)).isDirectory()?"dir":"file"}catch{continue}i.push({name:e.name,type:o,path:t?`${t}/${e.name}`:e.name})}return i}catch{return[]}},async fetchFile(t){const n=r.get(t);if(void 0!==n)return{content:n};const o=a((0,s.join)(e,t)),i=await c(o);await Cf(i);const l=await(0,xo.readFile)(i,"utf-8");return r.set(t,l),{content:l}},async fileExists(t){try{const r=a((0,s.join)(e,t)),n=await c(r);return(await(0,xo.stat)(n)).isFile()}catch{return!1}}}}(e),n=new cf(r),o=await n.discoverComponents({manifest:t}),[i,a,c,l]=await Promise.all([$f(r,o.skills,e),Df(r,o.agents,e),Of(r,o.commands,e),Mf(r,o.rules,e)]);return{skills:i,agents:a,commands:c,rules:l}}async function $f(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Nf({content:Ap(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}async function Mf(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Nf({content:Ap(t,r),relativePath:o.path});s&&n.push({...s,name:o.name})}catch{}return n}async function Df(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Lf({content:Ap(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}async function Of(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=jf({content:Ap(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}function Ff(e){if("string"==typeof e){const t=function(e){const t=[];let r=0,n=0;for(let o=0;o0)n--;else if(","===s&&0===n){const n=e.slice(r,o).trim();n&&t.push(n),r=o+1}}if(n>0){for(const n of e.slice(r).split(",")){const e=n.trim();e&&t.push(e)}return t}const o=e.slice(r).trim();return o&&t.push(o),t}(e);return t.length>0?t:void 0}if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e)).map((e=>e.trim())).filter(Boolean);return t.length>0?t:void 0}}function Nf({content:e,relativePath:t}){try{const r=rh(e),n=t.replace(/\\/g,"/"),o=n.split("/").filter((e=>e.length>0)),s=o.length>=2?o[o.length-2]:void 0,i=o[o.length-1]??n,a=s??i.replace(/\.md$/i,""),c="string"==typeof r.data.name?r.data.name.trim():void 0,l=of(r.data.environments??r.data.metadata?.environments),u=of(r.data["disabled-environments"]??r.data.metadata?.disabledEnvironments);return{path:t,name:c&&c.length>0?c:a,description:"string"==typeof r.data.description?r.data.description:void 0,globs:Ff(r.data.globs),alwaysApply:!0===r.data.alwaysApply,content:e,environments:l,disabledEnvironments:u}}catch{return null}}function Lf({content:e,relativePath:t}){try{const n=rh(e),o=n.content.trim();if(!o)return null;let i;"string"==typeof n.data.tools?i=n.data.tools.split(",").map((e=>e.trim())).filter(Boolean):Array.isArray(n.data.tools)&&(i=n.data.tools.map((e=>"string"==typeof e?e.trim():String(e))).filter(Boolean));const a=n.data.permissionMode??n.data.permissionmode,c=(0,s.basename)(t);return{path:t,name:"string"==typeof n.data.name?n.data.name:(0,s.basename)(c,(0,s.extname)(c)).replace(/[\s_]+/g,"-"),description:"string"==typeof n.data.description?n.data.description:void 0,tools:i,model:"string"==typeof n.data.model?n.data.model:"inherit",prompt:o,permissionMode:(r=a,"readonly"===(r??"").trim().toLowerCase()?"readonly":"default")}}catch{return null}var r}function jf({content:e,relativePath:t}){try{const r=rh(e);let n;const o=r.data["argument-hint"];"string"==typeof o?n=o:Array.isArray(o)&&(n=`[${o.join(" ")}]`);const i=(0,s.basename)(t);return{path:t,name:"string"==typeof r.data.name?r.data.name:(0,s.basename)(i,(0,s.extname)(i)),description:"string"==typeof r.data.description?r.data.description:void 0,argumentHint:n,content:r.content.trim()}}catch{return null}}function Uf(e){if(void 0!==e)return{configuredVariables:e.configuredVariables}}async function Bf(e,t,r){const n=r??Uf(t);return async function(e,t={}){const r=t.toSourcePath??(e=>e);let n,o,s;for(const t of zh){const i=await e(t);if(null===i)continue;let a;try{a=JSON.parse(i)}catch{continue}s=Uh(a);const c=_p(i);if(c.success){void 0!==c.data.mcpServers&&(n=c.data.mcpServers,o=r(t));break}}return Hp(e,n,o,void 0===s?t:{...t,parserOptions:{...t.parserOptions,pluginSchemaId:s}})}(function(e){return async t=>{if(!Ep(t))return null;const r=(0,s.join)(e,t);try{return await kf(r)?null:(await(0,xo.stat)(r)).isFile()?(await Cf(r),await _f(r)):null}catch{return null}}}(e),{fallbackFileNames:jp(),manifestPrecedence:"override",toSourcePath:t=>(0,s.join)(e,t),installPathForExpansion:e,parserOptions:n})}async function Wf(e,t,r){const n=await Bf(e,void 0,{log:r});if(n)return n;for(const n of Vh){const o=(0,s.join)(e,n);try{if(!(await(0,xo.stat)(o)).isFile())continue;const n=await(0,xo.readFile)(o,"utf-8"),i=JSON.parse(n);if(!zf(i)||!Array.isArray(i.plugins))continue;const a=i.plugins.filter(Gf),c=t.name,l=a.find((e=>e.name===c));if(!l?.mcpServers?.length)continue;for(const t of l.mcpServers){const n=t.replace(/^\.\//,"");if(!Ep(n))continue;const o=(0,s.join)(e,n);try{await Cf(o);const t=Bp(await _f(o),e,{log:r});if(t?.mcpServers&&Object.keys(t.mcpServers).length>0){const e=Object.fromEntries(Object.keys(t.mcpServers).map((e=>[e,o])));return{...t,mcpServerSourcePaths:e}}}catch{}}return null}catch{}}return null}Error;const Hf=new Set(Object.values(Rd));function qf(e){return Hf.has(e)}function zf(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Gf(e){return!(!zf(e)||"string"!=typeof e.name)&&(void 0===e.mcpServers||Array.isArray(e.mcpServers)&&e.mcpServers.every((e=>"string"==typeof e)))}function Vf(e,t){const r={};for(const[n,o]of Object.entries(e.hooks))Array.isArray(o)&&qf(n)&&(r[n]=o.map((e=>"command"in e&&"string"==typeof e.command?{...e,command:Ap(e.command,t)}:"prompt"in e&&"string"==typeof e.prompt?{...e,prompt:Ap(e.prompt,t)}:e)));return{...e,hooks:r}}async function Kf(e,t,r,n,o){if("object"==typeof n){const s=Jf(n,t,r);return s&&"config"in s?{config:Vf(s.config,e),...void 0!==o&&{sourcePath:o}}:s}let i,a,c;if("string"==typeof n){const t=n.replace(/^\.\//,"");if(!Ep(t))return;i=t.endsWith(".json")?(0,s.join)(e,t):(0,s.join)(e,t,"hooks.json")}else i=(0,s.join)(e,"hooks","hooks.json");try{if(await kf(i))return;if(!(await(0,xo.stat)(i)).isFile())return}catch{return}try{await Cf(i),a=await(0,xo.readFile)(i,"utf-8")}catch{return}try{c=JSON.parse(a)}catch{return{error:{source:"claude-plugin",message:`Plugin ${t} ${i}: invalid JSON`}}}const l=Jf(c,t,r);return l&&"config"in l?{config:Vf(l.config,e),sourcePath:i}:l}function Jf(e,t,r){const n=function(e){if(!Ad(e))return"unknown";const t=e,r="object"==typeof t.hooks&&null!==t.hooks?t.hooks:null;if(!r)return"unknown";for(const e of Object.values(r)){if(!Array.isArray(e)||0===e.length)continue;const t=e[0];if(Ad(t)){if("hooks"in t&&Array.isArray(t.hooks))return"claude-code";if("command"in t||"prompt"in t||"type"in t)return"cursor"}}return"unknown"}(e);if("cursor"===n){const r=Fd(e);return r.isValid&&Fd(e).isValid?{config:e}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${r.errors.join("; ")}`}}}if("claude-code"===n){if(!(zf(o=e)&&zf(o.hooks)&&Object.keys(o.hooks).length>0))return;const n=Yd(e.hooks,{warn:e=>r.log("warn",`Plugin ${t} hooks: ${e}`),info:e=>r.log("info",`Plugin ${t} hooks: ${e}`)}),s=Fd(n);return s.isValid?{config:n}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${s.errors.join("; ")}`}}}var o}async function Zf(e,t,r,n){const o=n?.log??$p,s=await Tf(e,t,o),i={...Uf(r)??(n?.configuredVariables?{configuredVariables:n.configuredVariables}:void 0),log:o},[a,c,l]=await Promise.all([Af(e,s?.manifestOptions),Bf(e,r,i),Kf(e,t,o,s?.manifestOptions?.hooks,s?.manifestFilePath)]);return{...a,...void 0!==s?.metadata?.displayName&&{displayName:s.metadata.displayName},...void 0!==s?.metadata?.description&&{description:s.metadata.description},...void 0!==s?.metadata?.authorName&&{authorName:s.metadata.authorName},...void 0!==s?.metadata?.logoUrl&&{logoUrl:s.metadata.logoUrl},...void 0!==s?.metadata?.version&&{version:s.metadata.version},...void 0!==s?.metadata?.homepage&&{homepage:s.metadata.homepage},...void 0!==s?.metadata?.repository&&{repository:s.metadata.repository},variablesSchema:s?.metadata?.variables,mcpConfig:c,capabilities:s?.metadata?.capabilities??[],hooks:l}}async function Xf(e,t,r){const n=r?.log??$p,o=await Tf(e,t.raw,n),[s,i,a]=await Promise.all([Af(e,o?.manifestOptions),Wf(e,t,n),Kf(e,t.raw,n,o?.manifestOptions?.hooks,o?.manifestFilePath)]);return{identifier:{source:"claude-plugin",sourceInfo:t},installPath:e,...void 0!==o?.metadata?.displayName&&{displayName:o.metadata.displayName},...void 0!==o?.metadata?.description&&{description:o.metadata.description},...void 0!==o?.metadata?.authorName&&{authorName:o.metadata.authorName},...void 0!==o?.metadata?.logoUrl&&{logoUrl:o.metadata.logoUrl},...void 0!==o?.metadata?.version&&{version:o.metadata.version},...void 0!==o?.metadata?.homepage&&{homepage:o.metadata.homepage},...void 0!==o?.metadata?.repository&&{repository:o.metadata.repository},...s,mcpConfig:i??void 0,capabilities:o?.metadata?.capabilities??[],hooks:a}}async function Qf(e,t,r,n){const o=`${r.name}@${r.version}`,{displayName:s,description:i,authorName:a,logoUrl:c,version:l,homepage:u,repository:d,variablesSchema:h,skills:p,rules:f,agents:m,commands:g,mcpConfig:w,capabilities:y,hooks:v}=await Zf(e,o,r,{log:n?.log});return{identifier:{source:t,sourceInfo:r},installPath:e,...void 0!==s&&{displayName:s},...void 0!==i&&{description:i},...void 0!==a&&{authorName:a},...void 0!==c&&{logoUrl:c},...void 0!==l&&{version:l},...void 0!==u&&{homepage:u},...void 0!==d&&{repository:d},variablesSchema:h,skills:p,rules:f,agents:m,commands:g,mcpConfig:w??void 0,capabilities:y,hooks:v}}async function Yf(e,t,r={}){const n=r.log??$p,o=performance.now(),i=await async function(e){const t=vf(e),r=(0,s.join)(t,"plugins","installed_plugins.json");try{const e=yf(await(0,xo.readFile)(r,"utf-8"));return gf(n=e)&&gf(n.plugins)?e:null}catch{return null}var n}(r.userHomeDir);if(!i?.plugins)return n.log("info",`loadAllEnabledPlugins: no installed plugins metadata found (${(performance.now()-o).toFixed(1)}ms)`),[];const a=await async function(e){const t=vf(e),r=(0,s.join)(t,"settings.json");try{const e=yf(await(0,xo.readFile)(r,"utf-8"));return wf(e)?e:null}catch{return null}}(r.userHomeDir),c=function(e){if(void 0===e)return[];const t="string"==typeof e?[e]:e,r=new Set,n=[];for(const e of t){if(!e)continue;const t=(0,s.resolve)(e);r.has(t)||(r.add(t),n.push(t))}return n}(e),l=function(e,t,r){if(0===r.length)return Dh(e,t,null,void 0);const n=new Set;for(const{settings:e}of r)for(const[t,r]of Object.entries(e?.enabledPlugins??{}))!1===r&&n.add(t);const o=new Set,s=[];for(const{workspacePath:i,settings:a}of r){const r=Dh(e,t,a,i);for(const e of r)o.has(e.pluginId)||n.has(e.pluginId)||(o.add(e.pluginId),s.push(e))}return s}(i,a,await(0,Nr.PH)(c,(async e=>({workspacePath:e,settings:await bf(e)})),{max:8})),u=[],d=r.onError;for(const{pluginId:e,installPath:t}of l)try{const r=performance.now(),o=uf(e),s=await Xf(t,o,{log:n});u.push(s),n.log("info",`loadClaudePlugin ${e} loaded in ${(performance.now()-r).toFixed(1)}ms`)}catch(t){const r=t instanceof Error?t:new Error(String(t));if(d)try{d(uf(e),r)}catch{d({name:e.split("@")[0]??e,sourceType:"marketplace",marketplace:"unknown",raw:e},r)}}return n.log("info",`loadAllEnabledPlugins completed in ${(performance.now()-o).toFixed(1)}ms (${l.length} resolved, ${u.length} loaded)`),u}const em=new Map;async function tm(e){const{entry:t,slug:r,cacheManager:n}=e;if(void 0===t.backendContent&&!Ph(t.downloadUrl))return rm(e);const o=n.getCacheDir({marketplaceSlug:r,pluginId:t.pluginId,version:t.version}),s=em.get(o);if(void 0!==s)return s;const i=rm(e).finally((()=>{em.delete(o)}));return em.set(o,i),i}async function rm(e){const{entry:t,slug:r,client:n,cacheManager:o,pluginLogger:s}=e;if(await o.isCached({marketplaceSlug:r,pluginId:t.pluginId,version:t.version})){const e=o.getCacheDir({marketplaceSlug:r,pluginId:t.pluginId,version:t.version});return s.log("info",`loadFromMarketplaceSource: Found cached plugin: ${t.pluginId} at ${e}`,{marketplaceSlug:r,pluginId:t.pluginId,gitRef:t.version,marketplaceId:t.marketplace?.id}),e}const i=o.getCacheDir({marketplaceSlug:r,pluginId:t.pluginId,version:t.version});s.log("info",`loadFromMarketplaceSource: Plugin missing from cache, installing: ${t.pluginId} at ${i}`,{marketplaceSlug:r,pluginId:t.pluginId,gitRef:t.version,marketplaceId:t.marketplace?.id}),await(0,xo.mkdir)(i,{recursive:!0});try{await n.installPlugin(t,i),await o.markCacheComplete({marketplaceSlug:r,pluginId:t.pluginId,version:t.version})}catch(e){try{await(0,xo.rm)(i,{recursive:!0,force:!0})}catch{}throw e}return i}async function nm(e){const{error:t,entry:r,slug:n,client:o,cacheManager:s,pluginLogger:i}=e;if(!Ch(t))return;if("revision_superseded"===t.reason){const t=await(o.relistPlugin?.(r).catch((()=>{})));if(void 0!==t)try{return{entry:t,installPath:await tm({...e,entry:t})}}catch(e){if(!Ch(e))throw e}}const a=await async function(e){const{cacheManager:t,marketplaceSlug:r,pluginId:n,exceptVersion:o}=e,s=ih(Sh),i=await t.listCachedVersions({marketplaceSlug:r,pluginId:n});let a;for(const e of i){if(!e.startsWith(s))continue;const i=Rh(e.slice(s.length));if(i===o)continue;const c=hh({parent:t.getCacheDir({marketplaceSlug:r,pluginId:n,version:i}),name:uh}),l=await(0,xo.stat)(c).then((e=>e.mtimeMs),(()=>{}));void 0!==l&&(void 0===a||l>a.installedAtMs)&&(a={version:i,installedAtMs:l})}return a?.version}({cacheManager:s,marketplaceSlug:n,pluginId:r.pluginId,exceptVersion:r.version});return void 0!==a?(i.log("warn",`Plugin ${r.pluginId} keeps its installed version until the listed one can be downloaded`,{pluginId:r.pluginId,reason:t.reason}),{entry:{...r,version:a},installPath:s.getCacheDir({marketplaceSlug:n,pluginId:r.pluginId,version:a})}):void 0}async function om(e){const t=e.log??$p,r=performance.now(),{client:n,userId:o,teamId:s,onCursorError:i,pruneOldVersions:a,pluginFilter:c,onPluginsListed:l}=e,u=[],d=e.cacheManager??new fh(e.userHomeDir),h=performance.now();let p;try{p=await n.listEnabledPlugins(o,s)}catch(e){return t.captureException(e,{error_type:"list_enabled_plugins"}),t.increment("marketplace.source_unavailable",1),t.log("error",`marketplace listEnabledPlugins failed after ${(performance.now()-h).toFixed(1)}ms; treating source as unavailable: ${e instanceof Error?e.message:String(e)}`),{plugins:[],failures:[],sourceUnavailable:!0}}t.log("info",`marketplace listEnabledPlugins completed in ${(performance.now()-h).toFixed(1)}ms (${p.plugins.length} plugins)`),l&&await l(p.plugins);const f=[];if(p.listFailures){u.push(...p.listFailures);for(const e of p.listFailures)f.push({identifier:{source:e.marketplaceName&&"cursor-public"!==e.marketplaceName?"cursor-third-party":"cursor-first-party",sourceInfo:{name:e.pluginName,version:"",...void 0!==e.pluginDbId&&{pluginDbId:e.pluginDbId},marketplace:e.marketplaceName}},installPath:"",loadError:e.errorMessage,skills:[],rules:[],agents:[],commands:[],capabilities:[]})}const m=new Map;for(const e of p.plugins){if(c&&!c(e))continue;let r=e;try{const e=r.marketplace?.name;if(!e){const e=new Error(`Plugin ${r.name} has no marketplace metadata — cannot determine cache path`);u.push({pluginName:r.name,pluginId:r.pluginId,marketplaceName:void 0,errorMessage:e.message,errorType:"manifest"}),i&&i(r,e);continue}const o=`${e}/${r.pluginId}`;let s,a=m.get(o);a||(a={slug:e,pluginId:r.pluginId,versions:[]},m.set(o,a)),a.versions.push(r.version);try{s=await tm({entry:r,slug:e,client:n,cacheManager:d,pluginLogger:t})}catch(o){const i=await nm({error:o,entry:r,slug:e,client:n,cacheManager:d,pluginLogger:t});if(void 0===i)throw o;({entry:r,installPath:s}=i),a.versions.push(r.version)}const c=r.marketplace?.name,l=void 0!==c&&"cursor-public"!==c&&c.length>0?"cursor-third-party":"cursor-first-party",h={name:r.name,version:r.version,pluginDbId:r.pluginDbId,configuredVariables:r.configuredVariables,marketplace:c,marketplaceDbId:r.marketplaceDbId,isTeamRequired:r.isTeamRequired},p=await Qf(s,l,h,{log:t});f.push(p);try{await d.pruneOldVersions({marketplaceSlug:e,pluginId:r.pluginId,keepVersions:[r.version]})}catch{}}catch(e){t.captureException(e,{error_type:"load_plugin_from_marketplace"});const n=e instanceof Error?e:new Error(String(e));u.push({pluginName:r.name,pluginId:r.pluginId,marketplaceName:r.marketplace?.name,errorMessage:n.message,errorType:Ef(n)});const o=r.marketplace?.name,s=void 0!==o&&"cursor-public"!==o&&o.length>0;f.push({identifier:{source:s?"cursor-third-party":"cursor-first-party",sourceInfo:{name:r.name,version:r.version,pluginDbId:r.pluginDbId,marketplace:o,marketplaceDbId:r.marketplaceDbId,isTeamRequired:r.isTeamRequired}},installPath:"",loadError:n.message||"Plugin load failed",skills:[],rules:[],agents:[],commands:[],capabilities:[]}),i&&i(r,n)}}if(a)for(const{slug:e,pluginId:t,versions:r}of m.values())try{await d.pruneOldVersions({marketplaceSlug:e,pluginId:t,keepVersions:r})}catch{}return t.log("info",`loadFromMarketplaceSource completed in ${(performance.now()-r).toFixed(1)}ms (${f.length} plugins loaded, ${u.length} failures)`),{plugins:f,failures:u,sourceUnavailable:!1}}function sm(e){const{identifier:t}=e;switch(t.source){case"claude-plugin":return"marketplace"===t.sourceInfo.sourceType&&t.sourceInfo.marketplace?`${t.sourceInfo.marketplace}/${t.sourceInfo.name}`:void 0;case"cursor-first-party":case"cursor-third-party":return t.sourceInfo.marketplace?`${t.sourceInfo.marketplace}/${t.sourceInfo.name}`:void 0;default:return}}function im(e){return sm(e)??`path:${e.installPath}`}function am(e,t={}){return{...e,model:t.stripModel?void 0:e.model,tools:t.stripTools?void 0:e.tools}}function cm(e,t){const r=[];for(const o of e){const e=df(o.identifier),i=`plugin:${e}`,a=hf(o.identifier),c=pf(o.identifier),l=ff(o.identifier),u=mf(o.identifier);for(const d of t(o)){const t=(0,s.join)(o.installPath,d.path),{type:h,globs:p,description:f}=(n=d).alwaysApply?{type:"global"}:n.globs&&n.globs.length>0?{type:"fileGlobbed",globs:n.globs}:n.description?{type:"agentFetched",description:n.description}:{type:"manuallyAttached"};r.push({fullPath:t,content:d.content,type:h,globs:p,description:f,pluginIdentifier:e,gitRemoteOrigin:i,plugin:a,marketplace:c,pluginId:l,marketplaceId:u,environments:d.environments,disabledEnvironments:d.disabledEnvironments})}}var n;return r}var lm=r("../proto/dist/generated/agent/v1/agent_skills_pb.js");const um=(0,Vs.debuglog)("agent-skills-catalog-cache");function dm(e){return(0,ko.createHash)("sha256").update(JSON.stringify({v:1,...e})).digest("hex")}async function hm(e){try{return(await(0,xo.stat)(e)).mtimeMs}catch{return}}function pm(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const fm=[".kits","cursor-pages"],mm={configDir:".cursor",subdir:"skills-cursor",thirdParty:!1,builtin:!0},gm=[{configDir:".cursor",subdir:"skills",thirdParty:!1,builtin:!1},{configDir:".claude",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".codex",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".grok",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".agents",subdir:"skills",thirdParty:!1,builtin:!1},mm],wm=(new Set(gm.map((e=>e.configDir))),new Set(["imagegen","openai-docs","opneai-docs","plugin-creator","skill-creator","skill-installer"]));function ym(e){return e.replace(/\\/g,"/").split("/").filter(Boolean)}function vm(e){const t=ym(e);if(function(e){const t=e.findIndex(((t,r)=>function(e,t){return gm.some((r=>r.configDir===e&&r.subdir===t))}(t,e[r+1])));return-1!==t&&e.slice(t+2).some((e=>e.startsWith(".")))}(t))return!0;const r=t.lastIndexOf(".codex");if(-1===r||"skills"!==t[r+1])return!1;const n=t.at(-1),o="SKILL.md"===n?t.at(-2):n;return void 0!==o&&wm.has(o)}function bm(e){return{dirPath:(0,s.join)(e,mm.configDir,mm.subdir),scope:"builtin",source:"builtin"}}const Sm="canvas";function km(e,t){return{dirPath:(0,s.join)(bm(e).dirPath,...fm),scope:"builtin",source:"builtin"}}function _m(e,t){const r=e.replace(/\\/g,"/"),n=t.replace(/\\/g,"/").replace(/\/+$/,"");if(r.startsWith(`${n}/`))return ym(r.slice(n.length+1))}function Cm(e,t){const r=_m(e,t);return void 0!==r&&!r.some((e=>e.startsWith(".")))}function Em(e){return gm.filter((t=>!t.builtin&&(e||!t.thirdParty)))}function xm(e,t){return Em(t).map((t=>({dirPath:(0,s.join)(e,t.configDir,t.subdir),scope:"project",source:"workspace"})))}function Pm(e,t){return Em(t).map((t=>({dirPath:(0,s.join)(e,t.configDir,t.subdir),scope:"user",source:"user"})))}var Rm=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function Im(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const Tm=gm.map((({configDir:e,subdir:t,thirdParty:r})=>({pattern:new RegExp(`[/\\\\]${Im(e)}[/\\\\]${Im(t)}[/\\\\]`,"i"),requiresThirdParty:r}))),Am=/[/\\]\.cursor[/\\]rules[/\\]/i,$m=[{pattern:/[/\\]\.cursor[/\\]agents[/\\]/i,requiresThirdParty:!1},{pattern:/[/\\]\.claude[/\\]agents[/\\]/i,requiresThirdParty:!0}],Mm=new Set(["AGENTS.md","CLAUDE.md","CLAUDE.local.md"]);function Dm(e,t){const r=e.replace(/\\/g,"/"),n=(0,s.basename)(r);if(Mm.has(n))return"AGENTS.md"===n||t&&("CLAUDE.md"===n||"CLAUDE.local.md"===n)?"markdown":void 0;if(Am.test(r)&&n.endsWith(".mdc"))return"rules";if("SKILL.md"===n)for(const{pattern:e,requiresThirdParty:n}of Tm)if(e.test(r)){if(n&&!t)continue;return"skills"}if(n.endsWith(".md"))for(const{pattern:e,requiresThirdParty:n}of $m)if(e.test(r)){if(n&&!t)continue;return"agents"}}class Om{constructor(e,t,r,n){this.root=e,this.gitExecutor=t,this.userHomeDirectory=r,this.getThirdPartyExtensibilityEnabled=n}static getRipwalkCache(){return Om.ripwalkCache??=new _a,Om.ripwalkCache}async discover(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,D.VI)(e.withName("NestedExtensibilityService.discover")),!1),n={rules:[],skills:[],markdown:[],agents:[]},o=(0,s.resolve)(this.root),i=(0,s.resolve)(this.userHomeDirectory);if(o===i||zs(o,{platform:process.platform,homeDirectory:i}).length>0)return r.span.setAttribute("nested_extensibility.rules",0),r.span.setAttribute("nested_extensibility.skills",0),r.span.setAttribute("nested_extensibility.markdown",0),r.span.setAttribute("nested_extensibility.agents",0),n;if(!await tc(e,this.gitExecutor,(0,s.resolve)(this.root)))return r.span.setAttribute("nested_extensibility.rules",0),r.span.setAttribute("nested_extensibility.skills",0),r.span.setAttribute("nested_extensibility.markdown",0),r.span.setAttribute("nested_extensibility.agents",0),n;const a=this.getThirdPartyExtensibilityEnabled(),c=this.buildIncludeGlobs(a),l={root:this.root,includeGlobs:c,excludeGlobs:dc,followSymlinks:!0,source:"nested_extensibility"},u={rules:[],skills:[],markdown:[],agents:[]},d=Om.getRipwalkCache();try{const e=d.walk(r.ctx,l);try{for await(const t of e.lines){const e=Dm(t,a);e&&u[e].push((0,s.resolve)(this.root,t))}}finally{d.delete(l)}}catch{}return r.span.setAttribute("nested_extensibility.rules",u.rules.length),r.span.setAttribute("nested_extensibility.skills",u.skills.length),r.span.setAttribute("nested_extensibility.markdown",u.markdown.length),r.span.setAttribute("nested_extensibility.agents",u.agents.length),u}catch(e){t.error=e,t.hasError=!0}finally{Rm(t)}}buildIncludeGlobs(e){const t=["*/**/.cursor/**","*/**/.agents/**","*/**/AGENTS.md"];return e&&t.push("*/**/.claude/**","*/**/.codex/**","*/**/.grok/**","*/**/CLAUDE.md","*/**/CLAUDE.local.md"),t}}const Fm=new Set(["node_modules","__pycache__","dist","build"]);async function Nm({rootDir:e,includeFile:t,maxDepth:r=10,containmentRootDir:n}){const o=[],i=[{dir:e,depth:0}],a=new Set,c=void 0!==n?await(0,xo.realpath)(n):null,l=e=>{if(null===c)return!0;const t=(0,s.relative)(c,e);return""===t||!t.startsWith("..")&&!(0,s.isAbsolute)(t)};for(;i.length>0;){const e=i.pop();if(void 0===e)continue;const{dir:n,depth:c}=e;if(c>r)continue;try{const e=await(0,xo.realpath)(n);if(!l(e))continue;if(a.has(e))continue;a.add(e)}catch{continue}const d=await(0,xo.readdir)(n,{withFileTypes:!0,encoding:"utf8"}).catch((()=>null));if(null!==d)for(const e of d){const r=(0,s.join)(n,e.name);let a=e.isDirectory(),l=e.isFile();if(e.isSymbolicLink())try{const e=await(0,xo.stat)(r);a=e.isDirectory(),l=e.isFile()}catch{continue}if(a){if((u=e.name).startsWith(".")||Fm.has(u))continue;i.push({dir:r,depth:c+1})}else l&&t(e.name)&&o.push(r)}}var u;return o.sort(((e,t)=>e.localeCompare(t))),o}const Lm={agentStoreSkillsDirs:[],userHomeDirectory:""};function jm(e){const t=e.replace(/\\/g,"/");return t.endsWith("/")?t.slice(0,-1):t}function Um(e,t){const r=jm(t.userHomeDirectory),n=e.replace(/\\/g,"/");if(r.length>0)for(const e of t.agentStoreSkillsDirs){const t=jm(e);if(t.length>0&&n.startsWith(`${t}/`))return{key:`${r}::skills/${n.slice(t.length+1)}`,inAgentStore:!0}}return{key:Bm(e),inAgentStore:!1}}function Bm(e){const t=e.replace(/\\/g,"/"),r=t.toLowerCase(),n=r.indexOf("/.cursor/"),o=r.indexOf("/.claude/"),s=r.indexOf("/.codex/"),i=r.indexOf("/.grok/"),a=r.indexOf("/.agents/");return-1!==n?`${t.slice(0,n)}::${t.slice(n+9)}`:-1!==o?`${t.slice(0,o)}::${t.slice(o+9)}`:-1!==s?`${t.slice(0,s)}::${t.slice(s+8)}`:-1!==i?`${t.slice(0,i)}::${t.slice(i+7)}`:-1!==a?`${t.slice(0,a)}::${t.slice(a+9)}`:e}function Wm(e,t){const r=new Map,n=[];for(const o of e){const{key:e,inAgentStore:s}=Um(o.fullPath,t),i=r.get(e);void 0!==i?s&&!n[i].inAgentStore&&(n[i]={item:o,inAgentStore:s}):(r.set(e,n.length),n.push({item:o,inAgentStore:s}))}return n.map((e=>e.item))}var Hm=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},qm=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const zm=(0,d.h)("local-exec:cursor-rules");function Gm(e){return"/"===e||"\\"===e}function Vm(e){return e.split(/[\\/]+/).filter((e=>e.length>0)).length}async function Km(e){return await Nm({rootDir:e,includeFile:e=>"SKILL.md"===e})}async function Jm(e){let t;try{t=await Bi(e)}catch(t){return{skillFilePath:e,error:kd(t)}}try{return{skillFilePath:e,content:t,parsed:rh(t)}}catch(t){return{skillFilePath:e,error:_d(t)}}}async function Zm(e){const t=await ns(e);return{...await Jm(e),realSkillFilePath:t}}function Xm(e){return eg(e.data?.environments??e.data?.metadata?.environments)??[]}function Qm(e){return eg(e.data?.["disabled-environments"]??e.data?.metadata?.disabledEnvironments)??[]}function Ym(e){return eg(e.data?.metadata?.scopedTo??e.data?.["metadata.scopedTo"])??[]}function eg(e){if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e&&e.length>0));return 0===t.length?void 0:t}if("string"==typeof e){const t=e.split(",").map((e=>e.trim())).filter((e=>e.length>0));return 0===t.length?void 0:t}}function tg(e,t,r){const n=function(e){const t=e.data?.metadata?.surfaces;return Array.isArray(t)?t:"string"==typeof t?t.split(",").map((e=>e.trim())).filter(Boolean):[]}(e);return n.length>0&&!n.includes(t)&&!r.includes(e.data?.name)}function rg(e){return Jo(e,1536)}function ng(e){return!0===e.data?.alwaysApply}function og(e){return!0===e.data?.["disable-model-invocation"]}function sg({skillFilePath:e,content:t,parsed:r}){const n=function(e){return function(e){const t=(e.matter??"").trim(),r=e.language?.toLowerCase();return t.length>0&&"js"!==r&&"javascript"!==r?`---\n${t}\n---`:nh("",e.data??{}).trim()}(e)}(r),o=function({fullPath:e,name:t,description:r,body:n}){const o=[],s=function(e){const t=e.replace(/\\/g,"/").split("/"),r=t[t.length-1]??"";return"SKILL.md"===r&&t.length>=2?t[t.length-2]??"":r}(e);s.length>64&&o.push(`Name is ${xd(s.length)} characters; the limit is 64. Rename the skill's folder.`),Ed.test(s)||o.push('Name should be lowercase letters and numbers joined by single hyphens, like "pdf-helper". Rename the skill\'s folder.'),void 0!==t&&t!==s&&o.push(`Frontmatter name ${JSON.stringify(t)} doesn't match the folder name ${JSON.stringify(s)}, which is the name the skill goes by. Make them the same.`);const i=r?.trim().length??0;i>1024&&o.push(`Description is ${xd(i)} characters; the limit is ${xd(1024)}.`);const a=Math.round(n.length/4);return a>5e3&&o.push(`Body is about ${xd(a)} tokens; the recommended limit is ${xd(5e3)}. Move details into reference files that SKILL.md links to.`),o}({fullPath:e,name:"string"==typeof r.data?.name?r.data.name:void 0,description:"string"==typeof r.data?.description?r.data.description:void 0,body:r.content});if(ng(r))return new Jr.DX({fullPath:e,content:t,frontmatter:n,type:new Jr.f5({type:{case:"global",value:new Jr.i9}}),environments:Xm(r),disabledEnvironments:Qm(r),scopedTo:Ym(r),warnings:o});const s="string"==typeof r.data?.description?rg(r.data.description):void 0,i=Cd(s,og(r));return i?new Jr.DX({fullPath:e,parseError:i,frontmatter:n,scopedTo:Ym(r),type:new Jr.f5({type:{case:"agentFetched",value:new Jr.Xo}})}):new Jr.DX({fullPath:e,content:t,frontmatter:n,type:new Jr.f5({type:{case:"agentFetched",value:new Jr.Xo({description:s})}}),environments:Xm(r),disabledEnvironments:Qm(r),scopedTo:Ym(r),warnings:o})}function ig({skillFilePath:e,content:t,parsed:r}){const n="string"==typeof r.data?.description?rg(r.data.description):"",o=Ff(r.data?.paths??r.data?.globs),s=og(r);return new lm.N({fullPath:e,content:t,description:n,globs:o??[],parseError:Cd(n,s),environments:Xm(r),disabledEnvironments:Qm(r),scopedTo:Ym(r),disableModelInvocation:s})}function ag({rules:e,agentSkills:t,skillFilePath:r,errorMessage:n}){e.push(function({skillFilePath:e,errorMessage:t}){return new Jr.DX({fullPath:e,parseError:t,type:new Jr.f5({type:{case:"agentFetched",value:new Jr.Xo}})})}({skillFilePath:r,errorMessage:n})),t.push(function({skillFilePath:e,errorMessage:t}){return new lm.N({fullPath:e,parseError:t})}({skillFilePath:r,errorMessage:n}))}function cg(e,t,r,n){if("error"in t)return e.realSkillFilePathsByFullPath.set(t.skillFilePath,t.realSkillFilePath),void ag({rules:e.rules,agentSkills:e.agentSkills,skillFilePath:t.skillFilePath,errorMessage:t.error});tg(t.parsed,r,n)||(e.realSkillFilePathsByFullPath.set(t.skillFilePath,t.realSkillFilePath),e.rules.push(sg(t)),ng(t.parsed)||e.agentSkills.push(ig(t)))}const lg=(0,Vs.debuglog)("cursor-rules-service");function ug(){return{rules:[],agentSkills:[],realSkillFilePathsByFullPath:new Map}}function dg(e){return t=>(lg("%s: %O",e,t),ug())}function hg(e,t){return dm({kind:"agent-store",surface:e,roots:[...t].sort()})}function pg(e,t){const r=t.replace(/\\/g,"/").replace(/\/+$/,"");return""!==r&&e.replace(/\\/g,"/").startsWith(`${r}/`)}function fg(e){let t;if(!0===e.frontmatter.alwaysApply)t={case:"global",value:new Jr.i9};else{const r=Ff(e.frontmatter.globs);t=r&&r.length>0?{case:"fileGlobbed",value:new Jr.uT({globs:r})}:"string"==typeof e.frontmatter.description&&e.frontmatter.description.trim().length>0?{case:"agentFetched",value:new Jr.Xo({description:rg(e.frontmatter.description)})}:{case:"manuallyAttached",value:new Jr._u}}const r=e.frontmatter["metadata.environments"],n=Array.isArray(r)?r:[],o=e.frontmatter["metadata.disabledEnvironments"],s=Array.isArray(o)?o:[],i=e.frontmatter["metadata.scopedTo"],a=Array.isArray(i)?i:[];return new Jr.DX({fullPath:e.path,content:e.body,type:new Jr.f5({type:t}),environments:n,disabledEnvironments:s,scopedTo:a,frontmatter:e.rawFrontmatter??""})}class mg{constructor(e,t){this.cursorRulesServices=e,this.getAgentStoreSkillsContext=t,this.onChangeCallbacks=new Set}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Hm(t,(0,D.VI)(e.withName("MergedCursorRulesService.getAllCursorRules")),!1),n=this.cursorRulesServices.map((e=>e.getAllCursorRules(r.ctx).catch((e=>((0,Vs.debuglog)("Failed to load cursor rules from service:",e),[])))));return Wm((await Promise.all(n)).flat(),this.getAgentStoreSkillsContext())}catch(e){t.error=e,t.hasError=!0}finally{qm(t)}}reload(e){for(const t of this.cursorRulesServices)t.reload(e)}scheduleDidChangeRules(){void 0===this.changeTimer&&(this.changeTimer=setTimeout((()=>{this.changeTimer=void 0;for(const e of Array.from(this.onChangeCallbacks))e()}),mg.CHANGE_COALESCE_MS))}ensureChangeListenersRegistered(){void 0===this.disposeChangeListeners&&(this.disposeChangeListeners=this.cursorRulesServices.map((e=>e.onDidChangeRules((()=>this.scheduleDidChangeRules())))))}disposeChangeListenersIfUnused(){if(!(this.onChangeCallbacks.size>0||void 0===this.disposeChangeListeners)){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0,void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0)}}onDidChangeRules(e){return this.onChangeCallbacks.add(e),this.ensureChangeListenersRegistered(),()=>{this.onChangeCallbacks.delete(e),this.disposeChangeListenersIfUnused()}}dispose(){if(void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0),this.onChangeCallbacks.clear(),void 0!==this.disposeChangeListeners){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0}for(const e of this.cursorRulesServices)e.dispose&&e.dispose()}}mg.CHANGE_COALESCE_MS=1e3;class gg{constructor(e,t,r,n,i,a,c,l){this.gitExecutor=t,this.rootDirectory=r,this.loadNestedRules=n,this.getThirdPartyExtensibilityEnabled=i,this.loadTraceId=void 0,this.onChangeCallbacks=new Set,this.nestedExtensibilityService=new Om(r,t,(0,o.homedir)(),i),this.ignoreService=c??new Rc(t,void 0,[this.rootDirectory]);const u=performance.now();if(this._rules=this.load(e,l).then((t=>{try{zm.info(e,"LocalCursorRulesService load completed",{durationMs:Math.round(performance.now()-u),ruleCount:t.length})}catch{}return t})).catch((e=>((0,Vs.debuglog)("Failed to load cursor rules:",e),[]))),a){const e=[".cursor/rules/**/*.mdc","AGENTS.md","CLAUDE.md","CLAUDE.local.md",".cursorrules",".cursorignore"];this.unsubscribeWatcher=a.subscribe(this.rootDirectory,e,(e=>{const t={stack:[],error:void 0,hasError:!1};try{const r=(0,b.q6)(),n=Hm(t,(0,D.VI)(r.withName("LocalCursorRulesService.fileWatcher.subscribe")),!1);if(".cursorignore"===(0,s.basename)(e))return gg.getRipwalkCache().clear(),void this.reload(n.ctx);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{qm(t)}}))}}reload(e){this._rules=this.load(e).catch((e=>((0,Vs.debuglog)("Failed to load cursor rules:",e),[])));for(const e of this.onChangeCallbacks)e()}static getRipwalkCache(){return gg.ripwalkCache??=new _a,gg.ripwalkCache}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.reloadAtPath")),!1);if(Xr((0,s.basename)(t)))return void this.reload(n.ctx);const o=this._rules;this._rules=(async()=>{const e=(await o).filter((e=>e.fullPath!==t));const r=(await this.readRulesAtPath(n.ctx,t)).map((e=>this.toCursorRule(e)));return[...e,...r]})().catch((e=>((0,Vs.debuglog)("Failed to load cursor rules at path:",e),[])));for(const e of this.onChangeCallbacks)e()}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}isRuleMarkdownFile(e){return Xr(e)}async readRulesAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.readRulesAtPath")),!1),o=(0,s.basename)(t);if(".cursorrules"===o){const e=(0,s.resolve)(this.rootDirectory),t=await tc(n.ctx,this.gitExecutor,e)||e,r=await this.loadCursorRulesRule(n.ctx,t);return r?[r]:[]}if(o.endsWith(".mdc"))return await wg(t);if(this.isRuleMarkdownFile(o))try{return await this.loadRulesFromMarkdownFile(n.ctx,(0,s.dirname)(t),o)}catch{}return[]}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}dispose(){this.unsubscribeWatcher&&(this.unsubscribeWatcher(),this.unsubscribeWatcher=void 0)}async load(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.load")),!1);this.loadTraceId=n.span.spanContext().traceId;const o=(0,s.resolve)(this.rootDirectory),i=await tc(n.ctx,this.gitExecutor,o)||o,a=this.loadCursorRulesRule(n.ctx,i).then((e=>e?[e]:[])),c=this.loadRulesFromDirAndAncestors(n.ctx,o);let l,u;if(this.loadNestedRules){const e=t??this.nestedExtensibilityService.discover(n.ctx);l=e.then((e=>this.parseNestedRuleFiles(n.ctx,e.rules))),u=e.then((e=>this.parseNestedMarkdownFiles(n.ctx,e.markdown)))}else l=[],u=[];const d=(await Promise.all([a,c,l,u])).flat(),h=new Map;for(const e of d)h.set(e.path,e);const p=[...h.values()];return(await async function(e){const t=e.filter((e=>Xr((0,s.basename)(e.fullPath))));if(t.length<=1)return[...e];const r=await(0,Nr.PH)(t,(e=>async function(e){try{const t=await(0,xo.stat)(e,{bigint:!0});if(0n!==t.ino)return`ino:${String(t.dev)}:${String(t.ino)}`}catch{}return await ns(e)}(e.fullPath)),{max:16}),n=t.map(((e,t)=>({item:e,identity:r[t],dir:(0,s.dirname)(e.fullPath),content:e.content.trim()}))).sort(((e,t)=>{const r=Vm(e.dir)-Vm(t.dir);if(0!==r)return r;const n="AGENTS.md"===(0,s.basename)(e.item.fullPath);return n===("AGENTS.md"===(0,s.basename)(t.item.fullPath))?0:n?-1:1})),o=[];for(const e of n)o.some((t=>{return((r=t.dir)===(n=e.dir)||!!n.startsWith(r)&&(Gm(r.at(-1))||Gm(n[r.length])))&&(t.identity===e.identity||t.content===e.content);var r,n}))||o.push(e);const i=new Set(o.map((e=>e.item)));return e.filter((e=>!Xr((0,s.basename)(e.fullPath))||i.has(e)))}(p.map((e=>({fullPath:e.path,content:e.body,rule:e}))))).map((e=>this.toCursorRule(e.rule)))}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}async loadCursorRulesRule(e,t){const r={stack:[],error:void 0,hasError:!1};try{Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.loadCursorrules")),!1);try{const e=(0,s.join)(t,".cursorrules");if((await(0,xo.stat)(e)).isFile())return{filename:".cursorrules",path:e,frontmatter:{alwaysApply:!0},body:await Bi(e)}}catch{}return null}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{return Hm(t,(0,D.VI)(e.withName("LocalCursorRulesService.getAllCursorRules")),!1).span.setAttribute("cacheTraceId",this.loadTraceId??"undefined"),await this._rules}catch(e){t.error=e,t.hasError=!0}finally{qm(t)}}toCursorRule(e){return fg({path:e.path,body:e.body,frontmatter:e.frontmatter,rawFrontmatter:e.rawFrontmatter})}async loadRulesFromDirAndAncestors(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirAndAncestors")),!1),o=[];let i=t;const a=this.getThirdPartyExtensibilityEnabled();for(;;){const e=(0,s.join)(i,".cursor","rules"),t=i;o.push((async()=>await this.dirIsDirectory(n.ctx,e)?this.loadRulesFromDirectory(n.ctx,t):[])());const r=[];a&&r.push("CLAUDE.md","CLAUDE.local.md"),r.push("AGENTS.md");for(const e of r)o.push(this.loadRulesFromMarkdownFile(n.ctx,i,e));const c=(0,s.dirname)(i);if(c===i)break;i=c}const c=(await Promise.all(o)).flat();return n.span.setAttribute("rules",c.length),c}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}async loadRulesFromMarkdownFile(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{Hm(n,(0,D.VI)(e.withName("LocalCursorRulesService.loadRulesFromMarkdownFile")),!1).span.setAttribute("filename",r);try{const e=(0,s.join)(t,r);if(await this.isCursorIgnored(e))return[];if((await(0,xo.stat)(e)).isFile()){const t=Qr({content:await Bi(e),filename:r});return[{filename:(0,s.basename)(e,".md"),path:e,frontmatter:{alwaysApply:!0},body:t}]}}catch{}return[]}catch(e){n.error=e,n.hasError=!0}finally{qm(n)}}async isCursorIgnored(e){try{const t=await xc((0,s.resolve)(this.rootDirectory,e));return null===t||await this.ignoreService.isCursorIgnored(t)}catch{return!1}}async parseNestedRuleFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.parseNestedRuleFiles")),!1),o=(await Promise.all(t.map((async e=>{try{const t=rn(await Bi(e));if(t)return{filename:(0,s.basename)(e,".mdc"),path:e,frontmatter:t.frontmatter,rawFrontmatter:t.rawFrontmatter,body:t.body}}catch{}})))).filter((e=>void 0!==e));return n.span.setAttribute("ruleFiles",o.length),o}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}async parseNestedMarkdownFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.parseNestedMarkdownFiles")),!1),o=(await Promise.all(t.map((async e=>{try{const t=(0,s.basename)(e);if(!this.isRuleMarkdownFile(t))return[];const r=(0,s.dirname)(e);return await this.loadRulesFromMarkdownFile(n.ctx,r,t)}catch{}return[]})))).flat();return n.span.setAttribute("markdownFiles",o.length),o}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}async loadRulesFromDirectory(e,t){return await async function(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=Hm(n,(0,D.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirectory")),!1),i=[];try{(0,s.join)(t,".cursorignore");const e={root:(0,s.join)(t,".cursor","rules"),includeGlobs:["**/*.mdc"],followSymlinks:!0,source:"cursor_rules"},n=r.walk(o.ctx,e);for await(const t of n.lines){const r=(0,s.join)(e.root,t);i.push(...await wg(r))}}catch{}return o.span.setAttribute("rules",i.length),i}catch(e){n.error=e,n.hasError=!0}finally{qm(n)}}(e,t,gg.getRipwalkCache())}async dirIsDirectory(e,t){const r={stack:[],error:void 0,hasError:!1};try{Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.dirIsDirectory")),!1);try{return(await(0,xo.stat)(t)).isDirectory()}catch{return!1}}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}}async function wg(e){try{const t=rn(await Bi(e));if(t)return[{filename:(0,s.basename)(e,".mdc"),path:e,frontmatter:t.frontmatter,rawFrontmatter:t.rawFrontmatter,body:t.body}]}catch{}return[]}class yg{constructor(e,t,r,n,o,s,i=()=>!0,a=Promise.resolve(),c="ide",l,u=()=>[],d,h,p=()=>[],f){if(this.workspacePaths=t,this.userHomeDirectory=r,this.gitExecutor=n,this.getEnabledSkills=p,this.ignoreService=f,this.agentStoreLoadRequestedWhileInFlight=!1,this.agentStoreLoadGeneration=0,this.watchersByFolder=new Map,this.onChangeCallbacks=new Set,this.reloadRequestedDuringSeed=!1,this.surface=c,this.waitBeforeSkillLoad="function"==typeof a?a:()=>a,this.getAgentStoreSkillRoots=u,this.fileWatcher=s,this.getThirdPartyExtensibilityEnabled=i,this.catalogCache=d,this.builtinSkillRootDir=bm(r).dirPath,this.canvasKitSkillRootDir=void 0===h?void 0:km(r).dirPath,this.workspaceCatalogKey=dm({kind:"workspace",surface:c,loadNestedSkills:o,thirdPartyExtensibility:i(),workspacePaths:[...t].sort(),userHomeDirectory:r,...void 0===h?{}:{canvasKit:h}}),void 0!==l&&l.length!==t.length)throw new Error(`initialNestedExtensibilityResults length (${l.length}) must match workspacePaths length (${t.length})`);this.nestedExtensibilityEntries=o?t.map((e=>new Om(e,n,r,i))):[],this.foldersToWatch=this.computeFoldersToWatch();const m=performance.now();let g=!1,w=!1,y=!1;const v=this.loadAll(e,l).then((t=>{try{zm.info(e,"AgentSkillsCursorRulesService load completed",{durationMs:Math.round(performance.now()-m),ruleCount:t.rules.length,skillCount:t.agentSkills.length,servedFromCache:g})}catch{}return t})).catch((e=>(w=!0,dg("Failed to load Agent Skills")(e))));if(void 0===this.catalogCache)this._loaded=v;else{const t=this.readCatalog(this.workspaceCatalogKey).then((r=>(y=!0,this._loaded!==t?this._loaded:(w&&this.closeSeedWindow(e),void 0===r?v:(g=!0,r)))));this.seededLoaded=t,this._loaded=t,v.then((r=>{this._loaded===t?w?y&&this.closeSeedWindow(e):(this._loaded=v,g&&this.notifyChanged(),this.persistCatalog(this.workspaceCatalogKey,r),this.closeSeedWindow(e)):this.seededLoaded=void 0}))}this.refreshAgentStoreSkills(),this.setupWatchers(this.foldersToWatch)}closeSeedWindow(e){this.seededLoaded=void 0,this.reloadRequestedDuringSeed&&(this.reloadRequestedDuringSeed=!1,this.reload(e))}async readCatalog(e){if(void 0!==this.catalogCache)try{const t=await this.catalogCache.read(e);return void 0===t?void 0:await async function(e){if(!function(e){if(!pm(e))return!1;const t=e.fileMtimesMs;return 1===e.version&&Array.isArray(e.rules)&&Array.isArray(e.agentSkills)&&Array.isArray(e.realSkillFilePathsByFullPath)&&e.realSkillFilePathsByFullPath.every((e=>Array.isArray(e)&&2===e.length&&"string"==typeof e[0]&&"string"==typeof e[1]))&&pm(t)&&Object.values(t).every((e=>"number"==typeof e&&Number.isFinite(e)))}(e))return;const t=new Map;if(await Promise.all(e.realSkillFilePathsByFullPath.map((async([r,n])=>{const o=e.fileMtimesMs[n];void 0!==o&&await hm(r)===o&&t.set(r,n)}))),0===t.size)return;const r=e=>void 0!==e&&t.has(e);try{return{rules:e.rules.map((e=>Jr.DX.fromJson(e,{ignoreUnknownFields:!0}))).filter((e=>r(e.fullPath))),agentSkills:e.agentSkills.map((e=>lm.N.fromJson(e,{ignoreUnknownFields:!0}))).filter((e=>r(e.fullPath))),realSkillFilePathsByFullPath:t}}catch(e){return void um("snapshot failed to decode: %O",e)}}(t)}catch(e){return void lg("Failed to read the skills catalog cache: %O",e)}}persistCatalog(e,t){const r=this.catalogCache;void 0!==r&&async function(e){const t=new Set(e.realSkillFilePathsByFullPath.values()),r={};return await Promise.all(Array.from(t,(async e=>{const t=await hm(e);void 0!==t&&(r[e]=t)}))),{version:1,rules:e.rules.map((e=>e.toJson())),agentSkills:e.agentSkills.map((e=>e.toJson())),realSkillFilePathsByFullPath:Array.from(e.realSkillFilePathsByFullPath),fileMtimesMs:r}}(t).then((t=>r.write(e,t))).catch((e=>{lg("Failed to persist the skills catalog cache: %O",e)}))}computeFoldersToWatch(){const e=this.getThirdPartyExtensibilityEnabled(),t=new Set;for(const r of this.workspacePaths){t.add((0,s.join)(r,".cursor","rules"));for(const n of xm(r,e))t.add(n.dirPath)}for(const r of Pm(this.userHomeDirectory,e))t.add(r.dirPath);for(const e of this.getAgentStoreSkillRoots())t.add(e);return t.add(this.builtinSkillRootDir),void 0!==this.canvasKitSkillRootDir&&t.add(this.canvasKitSkillRootDir),Array.from(t)}isIgnoredSkillPath(e){if(void 0!==this.canvasKitSkillRootDir){if(Cm(e,this.canvasKitSkillRootDir))return!1;if(function(e,t){const r=_m(e,t);return void 0!==r&&2===r.length&&r[0]===Sm&&"SKILL.md"===r[1]}(e,this.builtinSkillRootDir))return!0}return vm(e)}setupWatchers(e){if(!this.fileWatcher)return;const t=["**"];for(const r of e){if(this.watchersByFolder.has(r))continue;const e=this.fileWatcher.subscribe(r,t,(e=>{const t={stack:[],error:void 0,hasError:!1};try{const r=(0,b.q6)(),n=Hm(t,(0,D.VI)(r.withName("AgentSkillsCursorRulesService.fileWatcher.subscribe")),!1);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{qm(t)}}));this.watchersByFolder.set(r,e)}}removeWatchers(e){for(const t of e){const e=this.watchersByFolder.get(t);e&&(e(),this.watchersByFolder.delete(t))}}async getAllCursorRules(e){const[t]=await Promise.all([this._loaded,this.awaitAgentStoreSeed()]);return this.withAgentStoreSkills(t).rules}async awaitAgentStoreSeed(){void 0!==this.agentStoreSeedInFlight&&await(0,Nr.wj)(this.agentStoreSeedInFlight,250,"Agent Store skills cache read timed out").catch((()=>{}))}reload(e){this.syncWatchers(),this.seededLoaded=void 0,this.reloadRequestedDuringSeed=!1;const t=this.loadAll(e),r=t.catch(dg("Failed to load Agent Skills"));this._loaded=r,t.then((e=>{this._loaded===r&&this.persistCatalog(this.workspaceCatalogKey,e)}),(()=>{})),this.refreshAgentStoreSkills(),this.notifyChanged()}reloadSkillRoots(){try{this.syncWatchers()}finally{this.refreshAgentStoreSkills()}}async agentStoreSkillsSettled(){for(let e=this.agentStoreWalk;void 0!==e;e=this.agentStoreWalk)await e}syncWatchers(){const e=this.computeFoldersToWatch(),t=new Set(this.foldersToWatch),r=new Set(e);this.removeWatchers(this.foldersToWatch.filter((e=>!r.has(e)))),this.setupWatchers(e.filter((e=>!t.has(e)))),this.foldersToWatch=e}isPrunedByExtensibilityScan(e){if(void 0!==this.canvasKitSkillRootDir&&Cm(e,this.canvasKitSkillRootDir))return!1;const t=e.replace(/\\/g,"/");for(const e of this.foldersToWatch){const r=e.replace(/\\/g,"/");if(t.startsWith(`${r}/`))return t.slice(r.length+1).split("/").slice(0,-1).some((e=>e.startsWith(".")))}return!1}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("AgentSkillsCursorRulesService.reloadAtPath")),!1),o=function(e,t,r=i){for(const n of t){const t=r.relative(n,e);if(""!==t&&".."!==t&&!t.startsWith(`..${r.sep}`)&&!r.isAbsolute(t))return r.join(n,t)}return e}(t,this.foldersToWatch),a=o.endsWith("SKILL.md")?o:(0,s.join)(o,"SKILL.md");if(void 0!==this.seededLoaded&&this._loaded===this.seededLoaded&&!this.getAgentStoreSkillRoots().some((e=>pg(a,e))))return void(this.reloadRequestedDuringSeed=!0);if(this.getAgentStoreSkillRoots().some((e=>pg(a,e))))return void this.refreshAgentStoreSkills();if(this.foldersToWatch.some((e=>""===(0,s.relative)(e,o))))return void this.reload(n.ctx);const c=this._loaded,l=(async()=>{const e=await c,{realSkillFilePathsByFullPath:t}=e,r=function(e,t){const r=new Map(e.realSkillFilePathsByFullPath);for(const e of t)r.delete(e);return{rules:e.rules.filter((e=>!t.has(e.fullPath))),agentSkills:e.agentSkills.filter((e=>!t.has(e.fullPath))),realSkillFilePathsByFullPath:r}}(e,new Set([a]));if(this.isIgnoredSkillPath(a)||this.isPrunedByExtensibilityScan(a))return r;const o=t.get(a);if(void 0===o){try{await(0,xo.stat)(a)}catch{return r}return await this.loadAll(n.ctx)}let s;try{s=await(0,xo.realpath)(a)}catch{return await this.loadAll(n.ctx)}if(s!==o)return await this.loadAll(n.ctx);try{return cg(r,{...await async function(e){const t=await Bi(e);return{skillFilePath:e,content:t,parsed:rh(t)}}(a),realSkillFilePath:s},this.surface,this.getEnabledSkills()),r}catch{return await this.loadAll(n.ctx)}})().catch(dg("Failed to load Agent Skills at path"));this._loaded=l,this.notifyChanged()}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}async getAllAgentSkills(e){const[t]=await Promise.all([this._loaded,this.awaitAgentStoreSeed()]);return this.withAgentStoreSkills(t).agentSkills}withAgentStoreSkills(e){const t=this.settledAgentStoreSkills?.loaded;if(void 0===t||0===t.realSkillFilePathsByFullPath.size)return e;const r=new Set(e.realSkillFilePathsByFullPath.values()),n={rules:[...e.rules],agentSkills:[...e.agentSkills],realSkillFilePathsByFullPath:new Map(e.realSkillFilePathsByFullPath)},o=new Set;for(const[e,s]of t.realSkillFilePathsByFullPath)n.realSkillFilePathsByFullPath.has(e)||r.has(s)?o.add(e):n.realSkillFilePathsByFullPath.set(e,s);for(const e of t.rules)o.has(e.fullPath)||n.rules.push(e);for(const e of t.agentSkills)o.has(e.fullPath)||n.agentSkills.push(e);return n}refreshAgentStoreSkills(){const e=this.getAgentStoreSkillRoots().filter((e=>""!==e.trim())),t=++this.agentStoreLoadGeneration;var r,n;if(void 0===this.settledAgentStoreSkills||(r=this.settledAgentStoreSkills.roots,n=e,r.length===n.length&&r.every(((e,t)=>e===n[t])))||(this.settledAgentStoreSkills=void 0,this.notifyChanged()),0!==e.length){if(void 0===this.settledAgentStoreSkills){const r=this.seedAgentStoreSkills(e,t).finally((()=>{this.agentStoreSeedInFlight===r&&(this.agentStoreSeedInFlight=void 0)}));this.agentStoreSeedInFlight=r}void 0===this.agentStoreWalk?this.agentStoreWalk=(0,Nr.wj)(this.loadAgentStoreSkills(e),3e4,"Agent Store skills walk timed out").then((r=>{t===this.agentStoreLoadGeneration&&(this.settledAgentStoreSkills={roots:e,loaded:r},this.notifyChanged(),(r.rules.length>0||r.agentSkills.length>0)&&this.persistCatalog(hg(this.surface,e),r))}),(e=>{lg("Failed to load Agent Store skills: %O",e)})).finally((()=>{this.agentStoreWalk=void 0,this.agentStoreLoadRequestedWhileInFlight&&(this.agentStoreLoadRequestedWhileInFlight=!1,this.refreshAgentStoreSkills())})):this.agentStoreLoadRequestedWhileInFlight=!0}}async seedAgentStoreSkills(e,t){const r=await this.readCatalog(hg(this.surface,e));void 0!==r&&t===this.agentStoreLoadGeneration&&void 0===this.settledAgentStoreSkills&&(this.settledAgentStoreSkills={roots:e,loaded:r},this.notifyChanged())}async loadAgentStoreSkills(e){const t=ug(),r=(await Promise.all(e.map((e=>Km(e))))).flat().filter((e=>!vm(e))),n=await Promise.all(r.map((e=>Zm(e)))),o=new Set;for(const e of n)o.has(e.realSkillFilePath)||(o.add(e.realSkillFilePath),cg(t,e,this.surface,this.getEnabledSkills()));return t}notifyChanged(){for(const e of Array.from(this.onChangeCallbacks))e()}onDidChangeSkills(e){return this.onDidChangeRules(e)}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}dispose(){for(const e of this.watchersByFolder.values())e();this.watchersByFolder.clear()}async loadAll(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("AgentSkillsCursorRulesService.loadAll")),!1);await this.waitBeforeSkillLoad();const o=[],s=[],i=new Map,a=Promise.all(this.nestedExtensibilityEntries.map(((e,r)=>(t?.[r]??e.discover(n.ctx)).catch((e=>{lg("Failed to discover nested agent skills: %O",e)}))))),c=new Set(this.getAgentStoreSkillRoots()),l=await Promise.all(this.foldersToWatch.filter((e=>!c.has(e))).map((async e=>{const t=(await Km(e)).filter((e=>!this.isIgnoredSkillPath(e)));return Promise.all(t.map((e=>Zm(e))))}))),u=new Set;for(const e of l)for(const t of e)if(!u.has(t.realSkillFilePath))if(u.add(t.realSkillFilePath),"error"in t)i.set(t.skillFilePath,t.realSkillFilePath),ag({rules:o,agentSkills:s,skillFilePath:t.skillFilePath,errorMessage:t.error});else{if(tg(t.parsed,this.surface,this.getEnabledSkills()))continue;i.set(t.skillFilePath,t.realSkillFilePath),o.push(sg(t)),ng(t.parsed)||s.push(ig(t))}const d=(await a).flatMap((e=>e?.skills??[])).filter((e=>!vm(e))),h=await Promise.all(d.map((e=>ns(e)))),p=[];for(const[e,t]of d.entries()){const r=h[e];u.has(r)||(u.add(r),p.push(t))}const f=await Promise.all(p.map((e=>Zm(e))));for(const e of f)if("error"in e)i.set(e.skillFilePath,e.realSkillFilePath),ag({rules:o,agentSkills:s,skillFilePath:e.skillFilePath,errorMessage:e.error});else{if(tg(e.parsed,this.surface,this.getEnabledSkills()))continue;i.set(e.skillFilePath,e.realSkillFilePath),o.push(sg(e)),ng(e.parsed)||s.push(ig(e))}return n.span.setAttribute("agent_skills.total",o.length),n.span.setAttribute("agent_skills_proto.total",s.length),{rules:o,agentSkills:s,realSkillFilePathsByFullPath:i}}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}}function vg(e){let t;switch(e.type){case"global":t=new Jr.f5({type:{case:"global",value:new Jr.i9}});break;case"fileGlobbed":t=new Jr.f5({type:{case:"fileGlobbed",value:new Jr.uT({globs:e.globs??[]})}});break;case"agentFetched":t=new Jr.f5({type:{case:"agentFetched",value:new Jr.Xo({description:rg(e.description??"")})}});break;case"manuallyAttached":t=new Jr.f5({type:{case:"manuallyAttached",value:new Jr._u}});break;default:e.type,t=new Jr.f5({type:{case:"manuallyAttached",value:new Jr._u}})}return new Jr.DX({fullPath:e.fullPath,content:e.content,type:t,gitRemoteOrigin:e.gitRemoteOrigin,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,environments:e.environments??[],disabledEnvironments:e.disabledEnvironments??[],scopedTo:[]})}class bg{constructor(e,t,r,n){this.getImportSettings=t,this.pluginsService=n,this._rules=Promise.resolve([]),this._agentSkills=Promise.resolve([]),this._lastLoaded={rules:[],agentSkills:[]},this._loadGeneration=0,this.onChangeCallbacks=new Set,this.currentImportSettings=this.getImportSettings();const o=performance.now();this.startLoad(e,!1,(t=>{try{zm.info(e,"CursorPluginsAgentSkillsService load completed",{durationMs:Math.round(performance.now()-o),ruleCount:t.rules.length,skillCount:t.agentSkills.length})}catch{}}))}startLoad(e,t,r){const n=++this._loadGeneration,o=this.loadAll(e,t).catch((e=>((0,Vs.debuglog)("cursor-plugins-agent-skills")("Failed to load Cursor Plugins Agent Skills: %s",e instanceof Error?e.message:String(e)),{rules:[],agentSkills:[]}))).then((e=>(n===this._loadGeneration&&(this._lastLoaded=e,r?.(e)),e))),s=()=>(o.then((e=>{n===this._loadGeneration&&(this._rules=Promise.resolve(e.rules),this._agentSkills=Promise.resolve(e.agentSkills),this.notifyChange())})),this._lastLoaded),i=void 0!==this._overBudgetLoad?Promise.resolve(s()):(0,Nr.wj)(o,5e3,"Cursor plugin load did not finish within the rules wait budget").catch((t=>(zm.warn(e,"Serving rules without plugin primitives while plugins load",{error:t instanceof Error?t.message:String(t),waitMs:5e3}),this._overBudgetLoad=o,o.then((()=>{this._overBudgetLoad===o&&(this._overBudgetLoad=void 0)})),s())));this._rules=i.then((e=>e.rules)),this._agentSkills=i.then((e=>e.agentSkills))}notifyChange(){for(const e of Array.from(this.onChangeCallbacks))e()}async getAllCursorRules(e){return await this._rules}async getAllAgentSkills(e){return await this._agentSkills}reload(e){const t=this.getImportSettings();this.currentImportSettings=t,this.startLoad(e,!0),this.notifyChange()}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}onDidChangeSkills(e){return this.onDidChangeRules(e)}dispose(){this.onChangeCallbacks.clear()}async loadAll(e,t=!1){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("CursorPluginsAgentSkillsService.loadAll")),!1),o=[],i=[];try{let e=t?await this.pluginsService.reload():await this.pluginsService.getAllEnabledPlugins();this.currentImportSettings.importThirdPartyPlugins||(e=e.filter((e=>"claude-plugin"!==e.identifier.source))),n.span.setAttribute("cursor_plugins.loaded",e.length);const r=function(e){return cm(e,(e=>e.skills))}(e),a=function(e){return cm(e,(e=>e.rules))}(e);for(const e of[...r,...a])o.push(vg(e));for(const t of e){const e=`plugin:${df(t.identifier)}`,r=hf(t.identifier),n=pf(t.identifier),o=ff(t.identifier),a=mf(t.identifier);for(const c of t.skills){if(!0===c.alwaysApply)continue;let l=!1;if(c.content?.includes("disable-model-invocation"))try{l=!0===rh(c.content).data?.["disable-model-invocation"]}catch{}i.push(new lm.N({fullPath:(0,s.join)(t.installPath,c.path),content:c.content,description:rg(c.description??""),environments:c.environments??[],disabledEnvironments:c.disabledEnvironments??[],gitRemoteOrigin:e,plugin:r,marketplace:n,pluginId:o,marketplaceId:a,disableModelInvocation:l}))}}}catch(e){n.span.setAttribute("cursor_plugins.error",String(e))}return n.span.setAttribute("cursor_plugins.total",o.length),n.span.setAttribute("cursor_plugins_proto.total",i.length),{rules:o,agentSkills:i}}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}}var Sg=r("../proto/dist/generated/agent/v1/subagents_pb.js");const kg=(0,Vs.debuglog)("local-subagents");class _g{async getAllSubagents(){return[]}async reload(){return[]}}function Cg(e){return"true"===(e??"").trim().toLowerCase()}function Eg(e){const t=e.match(/^---\s*\n([\s\S]*?)\n---\s*\n?([\s\S]*)$/m);if(!t)return null;const r=t[1]??"",n=(t[2]??"").trim();if(0===n.length)return null;const o={};for(const e of r.split("\n")){const t=e.trim();if(0===t.length||t.startsWith("#"))continue;const r=t.indexOf(":");if(-1===r)continue;const n=t.slice(0,r).trim().toLowerCase(),s=t.slice(r+1).trim();0!==n.length&&(o[n]=s)}const s=o.name??"",i=o.description,a=o.model,c=Cg(o["force-default-model"]),l="true"===(o.readonly??"").trim().toLowerCase()?Sg.b$.READONLY:Sg.b$.DEFAULT,u=Cg(o.background??o.is_background),d=o.tools;return{name:s,description:i,tools:void 0!==d&&d.length>0?d.split(",").map((e=>e.trim())).filter((e=>e.length>0)):[],model:a,forceDefaultModel:c,prompt:n,permissionMode:l,isBackground:u}}function xg(e){const t=(0,s.extname)(e).toLowerCase();return".md"===t||".mdc"===t||".markdown"===t}function Pg(e){return(0,s.basename)(e,(0,s.extname)(e)).replace(/[\s_]+/g,"-")}async function Rg(e,t){return await Nm({rootDir:e,includeFile:xg,containmentRootDir:t})}class Ig{constructor(e,t,r="workspace",n=!1,o){this.workspacePath=e,this.cursorAgentsSource=r,this.allowExternalAgentSymlinks=n,this.ignoreService=o,this.getThirdPartyExtensibilityEnabled=t??(()=>!0),this.subagents=this.load().catch((e=>(kg("Failed to load subagents: %o",e),[])))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents=this.load().catch((e=>(kg("Failed to load subagents: %o",e),[]))),await this.subagents}computeAgentsDirs(){const e=(0,s.resolve)(this.workspacePath),t=[{dirPath:(0,s.join)(e,".cursor","agents"),source:this.cursorAgentsSource}];return this.getThirdPartyExtensibilityEnabled()&&(t.push({dirPath:(0,s.join)(e,".claude","agents"),source:"claude"}),t.push({dirPath:(0,s.join)(e,".grok","agents"),source:"grok"})),t}async load(){const e=this.computeAgentsDirs(),t=[];for(const{dirPath:r,source:n}of e){const e=await Rg(r,this.allowExternalAgentSymlinks?void 0:this.workspacePath);for(const r of e){const e=(0,s.basename)(r);try{if(!(await(0,xo.stat)(r)).isFile())continue}catch(e){kg("Skipping subagent file %s due to stat error: %o",r,e);continue}try{const o=Eg(await Bi(r));if(!o)continue;t.push(new Sg.zz({fullPath:r,name:o.name||Pg(e),description:o.description??"",tools:o.tools,model:o.model??"inherit",forceDefaultModel:o.forceDefaultModel,prompt:o.prompt,permissionMode:o.permissionMode,isBackground:o.isBackground,source:n}))}catch(e){kg("Failed to parse subagent file %s: %o",r,e)}}}return t}}const Tg=new Set(["claude-code-tutor"]);class Ag{constructor(e){this.subagentsServices=e}async getAllSubagents(){const e=await Promise.all(this.subagentsServices.map((e=>e.getAllSubagents().catch((e=>(kg("Failed to load subagents from merged service: %o",e),[])))))),t=new Map;for(const r of e)for(const e of r)Tg.has(e.name)||t.has(e.name)||t.set(e.name,e);return Array.from(t.values())}async reload(){return await Promise.all(this.subagentsServices.map((e=>e.reload()))),this.getAllSubagents()}}class $g{constructor(e,t){this.getSettings=e,this.pluginsService=t,this._subagentsCache=[],this._loadId=0,this._loadPromise=null,this._loadedOnce=!1,this.runLoadInBackground()}async getAllSubagents(){return this._loadPromise&&await this._loadPromise,this._loadedOnce||await this.reload(),[...this._subagentsCache]}async reload(){return this.runLoadInBackground(!0),this._loadPromise&&await this._loadPromise,this._subagentsCache}runLoadInBackground(e=!1){const t=++this._loadId;this._loadPromise=this.load(e).then((e=>{t===this._loadId&&(this._subagentsCache=e,this._loadedOnce=!0)})).catch((e=>{t===this._loadId&&(kg("Failed to load Cursor plugin subagents: %o",e),this._subagentsCache=[],this._loadedOnce=!0)})).finally((()=>{t===this._loadId&&(this._loadPromise=null)}))}dispose(){}async load(e){const t=[];try{let r=e?await this.pluginsService.reload():await this.pluginsService.getAllEnabledPlugins();this.getSettings().importThirdPartyPlugins||(r=r.filter((e=>"claude-plugin"!==e.identifier.source)));const n=function(e,t={stripModel:!0,stripTools:!0}){const r=[];for(const n of e){const e=hf(n.identifier),o=pf(n.identifier),i=ff(n.identifier),a=mf(n.identifier);for(const c of n.agents){const l=am(c,t),u=(0,s.join)(n.installPath,l.path);r.push({name:l.name,description:l.description??"",prompt:l.prompt,fullPath:u,permissionMode:"readonly"===l.permissionMode?"readonly":"default",plugin:e,marketplace:o,pluginId:i,marketplaceId:a})}}return r}(r,{stripModel:!0,stripTools:!0});for(const e of n){const r="readonly"===e.permissionMode?Sg.b$.READONLY:Sg.b$.DEFAULT;t.push(new Sg.zz({name:e.name,description:e.description,tools:[],model:"inherit",prompt:e.prompt,fullPath:e.fullPath,permissionMode:r,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,source:"plugin"}))}}catch{}return t}}class Mg{constructor(e){this.pastElements=[],this.closed=!1,this.forks=new Set,this.consume(e)}async consume(e){try{for await(const t of e){this.pastElements.push(t);const e=[];for(const r of this.forks)e.push(r.write(t).catch((()=>{})));await Promise.allSettled(e)}}catch(e){this.error=e instanceof Error?e:new Error(String(e))}finally{this.closed=!0;for(const e of this.forks)this.error?e.throw(this.error):e.close();this.forks.clear()}}fork(){if(this.closed){const e=this.pastElements,t=this.error;return async function*(){for(const t of e)yield t;if(t)throw t}()}const e=(0,f.Jt)(),t=this.pastElements.slice();this.forks.add(e);const r=this;return async function*(){for(const e of t)yield e;try{for await(const t of e)yield t}finally{r.forks.delete(e)}}()}}function Dg(e,t){return`${e}:${(0,ko.createHash)("sha256").update(t.toBinary()).digest("hex")}`}function Og(e){return new Po.q({max:e?.max??10,ttl:e?.ttl})}function Fg(e,t,r=Og(t)){return{async execute(t,n,o){if(!o?.execId)return e.execute(t,n,o);const s=Dg(o.execId,n),i=r.get(s);if(void 0!==i)return i;const a=await e.execute(t,n,o);return r.set(s,a),a}}}var Ng=r("../proto/dist/generated/agent/v1/computer_use_tool_pb.js");r("node:readline"),Error;var Lg=r("node:timers/promises");const jg=iu.execFile;function Ug(e,t,r){return new Promise(((n,o)=>{r?.signal?.throwIfAborted();const s={timeout:r?.timeoutMs??3e4,env:r?.env?{...process.env,...r.env}:void 0,signal:r?.signal};(0,au.D9)(jg,e,t.map(String),{...s,encoding:"utf8"},((e,t)=>{e?o(e):n(t)}))}))}Ng.w3.UNSPECIFIED,Ng.w3.LEFT,Ng.w3.MIDDLE,Ng.w3.RIGHT,Ng.w3.BACK,Ng.w3.FORWARD,Ng.Dh.UNSPECIFIED,Ng.Dh.UP,Ng.Dh.DOWN,Ng.Dh.LEFT,Ng.Dh.RIGHT;const Bg=(0,Vs.promisify)(iu.execFile);function Wg(e){const t=e.lastIndexOf(":");if(-1===t)throw new Error(`Invalid X11 display string: ${e} (missing ':')`);const r=e.slice(t+1).split(".")[0],n=parseInt(r,10);if(!Number.isFinite(n)||n<0)throw new Error(`Invalid X11 display number in: ${e} (parsed: ${r})`);return n}function Hg(e,t,r,n){const o=function(e={}){const t=e.displayWidth??1920,r=e.displayHeight??1200,n=e.apiWidth??1280;return{width:n,height:Math.round(n*r/t)}}({displayWidth:e,displayHeight:t,apiWidth:r});return{display:{width:e,height:t},api:{width:o.width,height:n??o.height}}}async function qg(e){const{stdout:t}=await(0,au.D9)(Bg,"xrandr",["--display",e],{timeout:5e3,encoding:"utf8"}),r=function(e){let t,r,n;for(const o of e.split("\n"))if(o.includes("*")){const e=o.trim().match(/^(\d+)x(\d+)/);e&&(t=parseInt(e[1],10),r=parseInt(e[2],10));const s=o.match(/(\d+(?:\.\d+)?)\*(?:\+)?/);if(s){const e=parseFloat(s[1]);e>0&&e<=500&&(n=Math.round(e))}if(t&&r)break}if(!t||!r){const n=e.match(/current\s+(\d+)\s*x\s*(\d+)/i);n&&(t=parseInt(n[1],10),r=parseInt(n[2],10))}if(!t||!r)throw new Error(`Could not detect display resolution from xrandr output.\nExpected a line with '*' indicating active mode, or 'current WxH'.\nxrandr output:\n${e}`);return n||(n=60),{width:t,height:r,refreshRate:n}}(t);return{display:r,resolution:Hg(r.width,r.height),resolutionString:`${r.width}x${r.height}`}}Ng.w3.UNSPECIFIED,Ng.w3.LEFT,Ng.w3.MIDDLE,Ng.w3.RIGHT,Ng.w3.BACK,Ng.w3.FORWARD,Ng.Dh.UNSPECIFIED,Ng.Dh.UP,Ng.Dh.DOWN,Ng.Dh.LEFT,Ng.Dh.RIGHT;const zg={pattern:"[\\w-]{1,64}",next:e=>e},Gg={pattern:"[0-9a-f-]{36}",next:()=>ko.randomUUID()},Vg={pattern:"webp",next:()=>"webp"},Kg={native:[Gg,Vg],agent:[zg,Gg,Vg],legacyNative:[Gg,{pattern:"png",next:()=>"png"}]};new RegExp(`^(?:${Object.values(Kg).map((e=>e.map((e=>e.pattern)).join("\\."))).join("|")})$`),new RegExp(`^${zg.pattern}$`),Ng.Z8.NATIVE_X11,Ng.Z8.XDOTOOL,(0,h.v5)("computer_use.session.duration_ms",{description:"Duration of computer-use session in milliseconds"}),(0,h.v5)("computer_use.session.action_count",{description:"Number of actions executed in a computer-use session"}),(0,h.Pu)("computer_use.session.result",{description:"Result status of computer-use session",labelNames:["outcome"]}),(0,h.Pu)("computer_use.session.action_kind",{description:"Requested computer-use actions by bounded kind",labelNames:["kind"]}),(0,d.h)("computer-use"),Math.floor(35927136),["Skip changes that cannot affect what runs in any deployed environment:","- documentation-only changes (Markdown, docs sites, code comments, changelogs)","- formatting, lint, or typo fixes with no behavior change","- test-only changes (test files, fixtures, snapshots)","Monitor everything else, including dependency bumps, configuration, and infrastructure changes."].join("\n"),Error,(0,h.Pu)("computer_use.desktop_lease.check",{description:"Desktop lease action-gate outcomes",labelNames:["outcome","reason"]});var Jg=r("../proto/dist/runtime/compact.js");Jg.HL;var Zg=(0,Jg.QT)(ve.proto3,"agent.v1.","CursorType",[[0,"UNSPECIFIED"],[1,"ARROW"],[2,"POINTER"],[3,"TEXT"],[4,"WAIT"],[5,"CROSSHAIR"],[6,"MOVE"],[7,"RESIZE_NS"],[8,"RESIZE_EW"],[9,"RESIZE_NWSE"],[10,"RESIZE_NESW"],[11,"NOT_ALLOWED"],[12,"GRAB"],[13,"GRABBING"]],1);ve.proto3,ve.proto3,ve.proto3,ve.proto3;class Xg{constructor(e){this.config=e;const t=e.display.width/e.display.height,r=e.api.width/e.api.height;if(Math.abs(t-r)>.02)throw new Error(`Aspect ratio mismatch: display=${t.toFixed(3)}, api=${r.toFixed(3)}`);this.xScaleUp=e.display.width/e.api.width,this.yScaleUp=e.display.height/e.api.height,this.xScaleDown=e.api.width/e.display.width,this.yScaleDown=e.api.height/e.display.height}apiToDisplay(e,t){return{x:Math.round(e*this.xScaleUp),y:Math.round(t*this.yScaleUp)}}displayToApi(e,t){return{x:Math.round(e*this.xScaleDown),y:Math.round(t*this.yScaleDown)}}get apiWidth(){return this.config.api.width}get apiHeight(){return this.config.api.height}get displayWidth(){return this.config.display.width}get displayHeight(){return this.config.display.height}}const Qg={left_ptr:Zg.ARROW,arrow:Zg.ARROW,default:Zg.ARROW,top_left_arrow:Zg.ARROW,hand:Zg.POINTER,hand1:Zg.POINTER,hand2:Zg.POINTER,pointer:Zg.POINTER,pointing_hand:Zg.POINTER,xterm:Zg.TEXT,ibeam:Zg.TEXT,text:Zg.TEXT,watch:Zg.WAIT,wait:Zg.WAIT,progress:Zg.WAIT,left_ptr_watch:Zg.WAIT,crosshair:Zg.CROSSHAIR,cross:Zg.CROSSHAIR,tcross:Zg.CROSSHAIR,move:Zg.MOVE,fleur:Zg.MOVE,size_all:Zg.MOVE,sb_v_double_arrow:Zg.RESIZE_NS,v_double_arrow:Zg.RESIZE_NS,ns_resize:Zg.RESIZE_NS,row_resize:Zg.RESIZE_NS,top_side:Zg.RESIZE_NS,bottom_side:Zg.RESIZE_NS,sb_h_double_arrow:Zg.RESIZE_EW,h_double_arrow:Zg.RESIZE_EW,ew_resize:Zg.RESIZE_EW,col_resize:Zg.RESIZE_EW,left_side:Zg.RESIZE_EW,right_side:Zg.RESIZE_EW,top_left_corner:Zg.RESIZE_NWSE,bottom_right_corner:Zg.RESIZE_NWSE,nwse_resize:Zg.RESIZE_NWSE,size_fdiag:Zg.RESIZE_NWSE,top_right_corner:Zg.RESIZE_NESW,bottom_left_corner:Zg.RESIZE_NESW,nesw_resize:Zg.RESIZE_NESW,size_bdiag:Zg.RESIZE_NESW,not_allowed:Zg.NOT_ALLOWED,no_drop:Zg.NOT_ALLOWED,forbidden:Zg.NOT_ALLOWED,circle:Zg.NOT_ALLOWED,grab:Zg.GRAB,openhand:Zg.GRAB,grabbing:Zg.GRABBING,closedhand:Zg.GRABBING};class Yg{constructor(e){this.events=[],this.recordingStartTime=0,this.lastKnownPosition={x:0,y:0},this.isRunning=!1,this.pending=Promise.resolve();const t=e.displayNum??1;this.env={DISPLAY:`:${t}`},this.scaler=new Xg(e.resolution)}async start(){this.events=[],this.recordingStartTime=Date.now(),this.isRunning=!0,this.pending=Promise.resolve();try{this.lastKnownPosition=await this.captureCurrentPosition()}catch{this.lastKnownPosition={x:Math.floor(this.scaler.apiWidth/2),y:Math.floor(this.scaler.apiHeight/2)}}}logEvent(e,t,r){if(!this.isRunning)return;const n={...this.lastKnownPosition},o=this.getExpectedPositionAfterAction(e,n);this.lastKnownPosition=o;const s=async()=>{let s,i;try{[s,i]=await Promise.all([this.captureCurrentPosition(),this.detectCursorType()]),this.lastKnownPosition=s}catch{s=o,i=Zg.ARROW}const a={executionTimestampMs:r-this.recordingStartTime,action:e,commandDurationMs:r-t,positionBefore:n,positionAfter:s,cursorTypeAfter:i};this.events.push(a)};this.pending=this.pending.then((()=>s())).catch((()=>{}))}async stop(){return this.isRunning=!1,await this.pending,[...this.events]}getEvents(){return[...this.events]}getRecordingStartTime(){return this.recordingStartTime}getIsRunning(){return this.isRunning}async captureCurrentPosition(){const e=await Ug("xdotool",["getmouselocation","--shell"],{env:this.env}),t=e.match(/X=(\d+)/),r=e.match(/Y=(\d+)/);if(!t||!r)throw new Error(`Failed to parse cursor position: ${e}`);const n=parseInt(t[1],10),o=parseInt(r[1],10);return this.scaler.displayToApi(n,o)}async detectCursorType(){try{const e=(await Ug("xdotool",["getmouselocation","--shell"],{env:this.env})).match(/CURSOR=(\S+)/i);if(e){const t=e[1].toLowerCase();return Qg[t]??Zg.ARROW}try{const e=await Ug("xprop",["-root","_XSERVER_CURSOR"],{env:this.env,timeoutMs:500});for(const[t,r]of Object.entries(Qg))if(e.toLowerCase().includes(t))return r}catch{}return Zg.ARROW}catch{return Zg.ARROW}}getExpectedPositionAfterAction(e,t){const r=e.action;if(!r)return t;switch(r.case){case"mouseMove":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}case"click":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}case"drag":{const e=r.value.path;if(e.length>0){const t=e[e.length-1];return{x:t.x,y:t.y}}break}case"scroll":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}}return t}}(0,d.h)("computer-use-lazy");var ew=r("node:net");function tw(e){return!!e.includes(o.homedir())||e.includes("node_modules")||e.includes("Application Support")||/\.wasm\b/.test(e)||/(?:^|[\s'`"(=])(?:\/|\.{1,2}\/)/.test(e)||/(?:^|[\s'`"(=:])(?:[A-Za-z]:[\\/]|\\\\)/.test(e)||/\bS-1-5-21(?:-\d+){3,}/i.test(e)}class rw extends Error{constructor(e){super(e),this.name="MacRPCProtocolError"}}const nw=Be.object({rpcSocketPath:Be.string().min(1).optional(),appControlSocketPath:Be.string().min(1).optional(),pid:Be.number().int().positive().optional().catch(void 0),protocolMajor:Be.number().int().positive().optional().catch(void 0)}).passthrough(),ow=Be.object({data:Be.string(),mimeType:Be.string().min(1)}).strip(),sw=Be.object({message:Be.string(),screenshot:ow.optional(),screenshotBefore:ow.optional(),structuredContent:Be.unknown().optional(),isError:Be.boolean()}).strip(),iw=Be.object({accessibilityTrusted:Be.boolean(),screenRecordingGranted:Be.boolean()}).strip(),aw=Be.union([Be.object({id:Be.number().int(),result:sw,ok:Be.never().optional(),error:Be.never().optional(),errorCode:Be.never().optional(),permissionStatus:Be.never().optional(),sessionId:Be.never().optional()}).strip(),Be.object({id:Be.number().int(),sessionId:Be.string().min(1),ok:Be.literal(!0).optional(),result:Be.never().optional(),error:Be.never().optional(),errorCode:Be.never().optional(),permissionStatus:Be.never().optional()}).strip(),Be.object({id:Be.number().int(),ok:Be.literal(!0),result:Be.never().optional(),error:Be.never().optional(),errorCode:Be.never().optional(),permissionStatus:Be.never().optional(),sessionId:Be.never().optional()}).strip(),Be.object({id:Be.number().int().nullable().optional(),error:Be.string().min(1),errorCode:Be.string().min(1).optional(),result:Be.never().optional(),ok:Be.never().optional(),permissionStatus:Be.never().optional(),sessionId:Be.never().optional()}).strip(),Be.object({id:Be.number().int(),permissionStatus:iw,result:Be.never().optional(),ok:Be.never().optional(),error:Be.never().optional(),errorCode:Be.never().optional(),sessionId:Be.never().optional()}).strip()]);function cw(e,t){try{return JSON.parse(e)}catch{throw new rw(`local-cua ${t} is not valid JSON`)}}const lw={responseMaxBytes:33554432,parseServiceState(e){const t=nw.safeParse(cw(e,"service state")),r=t.success?t.data.rpcSocketPath??t.data.appControlSocketPath:void 0;if(!t.success||void 0===r)throw new rw("local-cua service state is malformed");return{...t.data,rpcSocketPath:r}},parseResponse({line:e,expectedID:t}){const r=aw.safeParse(cw(e.toString("utf8"),"RPC response"));if(!r.success)throw new rw("local-cua RPC response is malformed");if(void 0!==r.data.id&&null!==r.data.id&&r.data.id!==t)throw new rw("local-cua RPC response ID did not match");return r.data}};class uw extends Error{constructor(e,t){super(e),this.name="MacComputerUseRPCError",this.code=t?.code,this.userFacing=!0===t?.userFacing,this.tool=t?.tool}}function dw(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:e instanceof Error?tw(e.message)?e.name:e.message.length>0?`${e.name}: ${e.message}`:e.name:"unknown"}const hw=new Map([["co.anysphere.cursor-computer-use","cursor-computer-use"],["co.anysphere.cursor-computer-use.dev","cursor-computer-use-dev"]]),pw=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;class fw{constructor(e){this.mode=e}static isInstalled(){if((0,Ro.existsSync)(fw.serviceExecutablePath()))return!0;let e;try{e=lw.parseServiceState((0,Ro.readFileSync)(fw.serviceStatePath(),"utf8"))}catch{return!1}return void 0===e.pid||fw.isProcessAlive(e.pid)}static async runningHelperPid(){const e=await fw.readServiceState(),t=e?.pid;return void 0!==t&&fw.isProcessAlive(t)?t:void 0}static isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}static isExitedIncompatibleHelper(e){return void 0!==e.protocolMajor&&e.protocolMajor!==fw.protocolMajor&&void 0!==e.pid&&!fw.isProcessAlive(e.pid)}screenshot(e){return this.callTool(e,"computer_use_screenshot",{})}click(e,t){return this.callTool(e,"computer_use_click",{method:"coordinate",...void 0!==t.coordinate&&{x:t.coordinate.x,y:t.coordinate.y},button:t.button,count:t.count,modifier_keys:t.modifierKeys})}scroll(e,t){return this.callTool(e,"computer_use_scroll",{x:t.coordinate?.x,y:t.coordinate?.y,direction:t.direction,amount:t.amount,modifier_keys:t.modifierKeys})}move(e,t){return this.callTool(e,"computer_use_mouse_move",{x:t.x,y:t.y})}mouseButton(e,t){return this.callTool(e,"computer_use_mouse_button",{button:t.button,action:t.action})}drag(e,t){return this.callTool(e,"computer_use_drag",{button:t.button,path:t.path,modifier_keys:t.modifierKeys})}typeText(e,t){return this.callTool(e,"computer_use_typing",{value:t})}pressKey(e,t){return this.callTool(e,"computer_use_press_key",{key:t.key,hold_duration_ms:t.holdDurationMs})}checkPermissions(e){return this.callTool(e,"computer_use_check_permissions",{})}async startControl(e){if("remote"!==this.mode||void 0!==this.activeSessionId)return;fw.throwIfAborted(e.signal);const t=(0,ko.randomUUID)(),r=await this.sendWithRelaunchRetry(e,(()=>({id:fw.requestID,method:"control/start",requestID:t,mode:this.mode})),"control/start");if(void 0!==r.error)throw fw.rpcError(r);if(void 0===r.sessionId)throw new uw("local-cua control/start returned no session");this.activeSessionId=r.sessionId}async releaseControl(e){const t=this.activeSessionId;if(void 0!==t){this.activeSessionId=void 0;try{const e=await fw.readServiceState();if(void 0===e)return;const r=await fw.sendOnce(fw.socketPathFrom(e),{id:fw.requestID,method:"control/release",requestID:(0,ko.randomUUID)(),mode:this.mode,sessionId:t},fw.defaultCallTimeoutMs);if(void 0!==r.error)throw fw.rpcError(r)}catch(t){fw.logger.warn(e,"local-cua control release failed",{error:dw(t)})}}}async callTool(e,t,r){fw.throwIfAborted(e.signal);const n=fw.defaultCallTimeoutMs,o=await this.sendWithRelaunchRetry(e,(()=>{const e=Date.now()/1e3,o=this.activeSessionId;return{id:fw.requestID,method:"tools/call",requestID:(0,ko.randomUUID)(),name:t,arguments:r,timeoutSeconds:n/1e3,startedAtEpochSeconds:e,deadlineEpochSeconds:e+n/1e3,mode:this.mode,...void 0!==o&&{sessionId:o}}}),t);if(void 0!==o.error)throw fw.rpcError(o,t);const s=o.result;if(void 0===s)throw new uw(`local-cua tool ${t} returned no result`,{tool:t});if(s.isError){const e=s.message.trim();throw new uw(e.length>0?e:`local-cua tool ${t} reported an error`,{tool:t,userFacing:e.length>0})}return s}async sendWithRelaunchRetry(e,t,r){const n=fw.defaultCallTimeoutMs,o=await this.ensureSocketPath(e);fw.throwIfAborted(e.signal);try{return await fw.sendOnce(o,t(),n,e.signal)}catch(o){if(!fw.isPreDeliveryConnectionError(o))throw o;fw.logger.warn(e,"local-cua callTool failed; relaunching and retrying",{tool:r,error:fw.spawnErrorCode(o)});const s=await this.ensureSocketPath(e,!0);return fw.throwIfAborted(e.signal),void 0!==this.activeSessionId&&(this.activeSessionId=void 0,await this.startControl(e)),await fw.sendOnce(s,t(),n,e.signal)}}static rpcError(e,t){return new uw(e.error,{code:e.errorCode,userFacing:!0,tool:t})}async ensureSocketPath(e,t=!1){if(fw.throwIfAborted(e.signal),!t){const e=await fw.readServiceState();if(e&&!fw.isExitedIncompatibleHelper(e))return fw.socketPathFrom(e)}await this.launchAndWait(e);const r=await fw.readServiceState();if(!r)throw new uw("local-cua sidecar did not publish service.json after launch");return fw.socketPathFrom(r)}static setLaunchGuard(e){fw.launchGuard=e}async launchAndWait(e){const t=fw.serviceAppPath(),r=fw.launchGuard,n=()=>this.launchAppAndWait(e,t);await(void 0===r?n():r(t,n,e.signal))}async launchAppAndWait(e,t){fw.logger.info(e,"launching local-cua sidecar",fw.sidecarLaunchLogFields(t)),"1"===process.env[fw.directLaunchEnv]?await fw.spawnSidecarProcess(e,fw.serviceExecutablePath(),[],{detached:!0}):await fw.spawnSidecarProcess(e,"/usr/bin/open",["-g",t]);const r=Date.now()+fw.launchReadyTimeoutMs;for(;Date.now()0?e:s.join(o.homedir(),...fw.sharedInstallRelativePath,`${fw.serviceAppBundleName}.app`)}static helperIdentity(){const e=fw.serviceAppPath(),t=process.env[fw.appSupportOverrideEnv],r=`${e}\0${t??""}`,n=fw.identityCache;if(n?.key===r)return n.identity;const i=function(e){let t;try{t=(0,Ro.readFileSync)(s.join(e,"Contents","Info.plist"),"utf8")}catch{return{}}const r=e=>{const r=new RegExp(`${e}\\s*([^<]*)`).exec(t)?.[1];return void 0!==r&&pw.test(r.trim())?r.trim():void 0};return{executableName:r("CFBundleExecutable"),bundleIdentifier:r("CFBundleIdentifier")}}(e),a=s.join(e,"Contents","MacOS",i.executableName??fw.productionExecutableName),c={appPath:e,executablePath:a,appSupportDirectory:void 0!==t&&t.length>0?t:s.join(o.homedir(),"Library","Application Support",(void 0===i.bundleIdentifier?void 0:hw.get(i.bundleIdentifier))??fw.appSupportFolder)};return(0,Ro.existsSync)(a)&&(fw.identityCache={key:r,identity:c}),c}static sidecarLaunchLogFields(e){const t=`${fw.serviceAppBundleName}.app`;return{appName:s.basename(e)===t?t:"custom",appPathHash:(0,ko.createHash)("sha256").update(e).digest("hex"),usingOverride:Boolean(process.env[fw.serviceAppOverrideEnv])}}static spawnErrorCode(e){return dw(e)}static socketError(e){const t=dw(e);return new uw(`local-cua RPC connection failed: ${t}`,{code:t})}static serviceExecutablePath(){return fw.helperIdentity().executablePath}static spawnSidecarProcess(e,t,r,n){return new Promise(((o,s)=>{const i=(0,iu.spawn)(t,[...r],{detached:!0===n?.detached,stdio:"ignore"}),a=e=>{s(new uw(`local-cua sidecar launch failed: ${fw.spawnErrorCode(e)}`))};i.once("error",a),i.once("spawn",(()=>{i.removeListener("error",a),i.on("error",(t=>{fw.logger.warn(e,"local-cua sidecar process error after launch",{error:fw.spawnErrorCode(t)})})),i.unref(),o()}))}))}static async readServiceState(){try{const e=await(0,xo.readFile)(fw.serviceStatePath(),"utf8");return lw.parseServiceState(e)}catch(e){if(e instanceof Error&&"code"in e&&"ENOENT"===e.code)return;if(e instanceof rw)return;throw new uw("local-cua service state could not be read")}}static socketPathFrom(e){if(void 0!==e.protocolMajor&&e.protocolMajor!==fw.protocolMajor)throw new uw(`The running Cursor Computer Use speaks protocol ${e.protocolMajor}, and this Cursor CLI speaks protocol ${fw.protocolMajor}. Update the Cursor CLI.`,{userFacing:!0});return e.rpcSocketPath}static abortError(e){return e.reason instanceof Error?e.reason:new uw("local-cua RPC aborted")}static throwIfAborted(e){if(e.aborted)throw fw.abortError(e)}static sendOnce(e,t,r,n){return n?.aborted?Promise.reject(fw.abortError(n)):new Promise(((o,s)=>{let i=!1,a=[],c=0,l=!1;const u=(0,ew.createConnection)({path:e}),d=e=>{i||(i=!0,clearTimeout(p),n?.removeEventListener("abort",h),u.destroy(),e())},h=()=>{d((()=>s(void 0===n?new uw("local-cua RPC aborted"):fw.abortError(n))))},p=setTimeout((()=>{d((()=>s(new uw(`local-cua RPC timed out after ${r}ms`))))}),r);n?.addEventListener("abort",h,{once:!0}),n?.aborted?h():(u.on("connect",(()=>{u.write(`${JSON.stringify(t)}\n`,(e=>{null==e?l=!0:d((()=>s(fw.socketError(e))))}))})),u.on("data",(e=>{const t=e.indexOf(10),r=c+(t<0?e.length:t);if(r>lw.responseMaxBytes)return void d((()=>s(new uw("local-cua RPC response exceeded the size limit"))));if(t<0)return a.push(e),void(c+=e.length);a.push(e.subarray(0,t));const n=Buffer.concat(a,r);a=[],c=0;try{const e=lw.parseResponse({line:n,expectedID:fw.requestID});d((()=>o(e)))}catch(e){d((()=>s(e)))}})),u.on("error",(e=>{d(l?()=>s(new uw("local-cua RPC connection failed after request delivery")):()=>s(fw.socketError(e)))})),u.on("close",(()=>{const e=c>0?"local-cua RPC response ended without a newline":l?"local-cua RPC connection closed after request delivery":"local-cua RPC connection closed";d((()=>s(new uw(e))))})))}))}}let mw;function gw(){if(void 0===mw){const e=async function(){const[{createJimp:e},{default:t},{default:n},{default:o,msBmp:s},{default:i},{default:a},{methods:c}]=await Promise.all([Promise.all([r.e(731),r.e(250)]).then(r.bind(r,"../../node_modules/.pnpm/@jimp+core@1.6.0/node_modules/@jimp/core/dist/esm/index.js")),r.e(690).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-png@1.6.0/node_modules/@jimp/js-png/dist/esm/index.js")),r.e(831).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-jpeg@1.6.0/node_modules/@jimp/js-jpeg/dist/esm/index.js")),Promise.all([r.e(731),r.e(284)]).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-bmp@1.6.0/node_modules/@jimp/js-bmp/dist/esm/index.js")),r.e(295).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-gif@1.6.0/node_modules/@jimp/js-gif/dist/esm/index.js")),r.e(181).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-tiff@1.6.0/node_modules/@jimp/js-tiff/dist/esm/index.js")),r.e(162).then(r.bind(r,"../../node_modules/.pnpm/@jimp+plugin-resize@1.6.0/node_modules/@jimp/plugin-resize/dist/esm/index.js"))]);return e({formats:[t,n,o,s,i,a],plugins:[c]})}().catch((t=>{throw mw===e&&(mw=void 0),t}));mw=e}return mw}fw.logger=(0,d.h)("local-cua:rpc"),fw.serviceAppBundleName="Cursor Computer Use",fw.appSupportFolder="cursor-computer-use",fw.productionExecutableName="CUCursorService",fw.sharedInstallRelativePath=[".cursor","computer-use-sidecar"],fw.appSupportOverrideEnv="CUA_APP_SUPPORT_DIR",fw.serviceAppOverrideEnv="CUA_SERVICE_APP",fw.directLaunchEnv="CUA_DIRECT_LAUNCH",fw.protocolMajor=1,fw.defaultCallTimeoutMs=45e3,fw.launchReadyTimeoutMs=8e3,fw.launchPollIntervalMs=200,fw.requestID=1;var ww=r("node:module"),yw=r.t(ww,2);const vw="mac-webp-runtime.cjs";function bw(e){return"function"==typeof e}function Sw(e){return"object"==typeof e&&null!==e&&"getFileName"in e&&"function"==typeof e.getFileName}function kw(){const e=(new Error).stack;return Array.isArray(e)?e.filter(Sw):[]}let _w,Cw;function Ew(){return _w??=(()=>{const e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;const e=kw()[0]?.getFileName();return function(){const e=yw;if("createRequire"in e&&bw(e.createRequire))return e.createRequire;if("default"in e&&"object"==typeof e.default&&null!==e.default&&"createRequire"in e.default&&bw(e.default.createRequire))return e.default.createRequire;throw new Error("node:module createRequire is unavailable")}()("string"==typeof e&&e.length>0?e:(0,s.join)(process.cwd(),"package.json"))}finally{Error.prepareStackTrace=e}})(),_w}function xw(){const e=globalThis.__MAC_WEBP_IMPORT__;return"function"==typeof e?t=>Promise.resolve(e(t)):(Cw??=function(){const e=[],t=new Set,r=r=>{t.has(r)||(t.add(r),e.push(r))};for(const e of function(){const e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;const e=[];for(const t of kw()){const r=t.getFileName();"string"==typeof r&&r.length>0&&e.push(r)}return e}finally{Error.prepareStackTrace=e}}()){const t=(0,s.dirname)((n=e).startsWith("file:")?(0,Pd.fileURLToPath)(n):n);r((0,s.join)(t,vw)),r((0,s.join)(t,"..","..","src","computer-use",vw))}var n;"string"==typeof process.argv[1]&&process.argv[1].length>0&&r((0,s.join)((0,s.dirname)(process.argv[1]),vw)),r((0,s.join)(process.cwd(),"src","computer-use",vw)),r((0,s.join)(process.cwd(),"computer-use",vw));try{const e=(0,s.dirname)(Ew().resolve("@anysphere/local-exec/package.json"));r((0,s.join)(e,"src","computer-use",vw)),r((0,s.join)(e,"dist","computer-use",vw))}catch{}for(const t of e)try{const e=Ew()(t);if("object"==typeof e&&null!==e&&"importFile"in e&&"function"==typeof e.importFile)return e.importFile.bind(e)}catch{}throw new Error("mac-webp runtime importer was not found next to the bundle")}(),Cw)}function Pw(...e){return t=["@jsquash","webp",...e].join("/"),Ew().resolve(t);var t}async function Rw(...e){var t;return await(t=(0,Pd.pathToFileURL)(Pw(...e)).href,xw()(t))}const Iw=e=>{let t;return()=>{if(void 0===t){const r=e();r.catch((()=>{t===r&&(t=void 0)})),t=r}return t}},Tw=(Iw((async()=>{const e=await Rw("decode.js");return await e.init({wasmBinary:await Ro.promises.readFile(Pw("codec","dec","webp_dec.wasm"))}),e})),Iw((async()=>{const[e,t,r]=await Promise.all([Rw("utils.js"),Rw("meta.js"),Rw("codec","enc","webp_enc.js")]);return{module:await e.initEmscriptenModule(r.default,void 0,{wasmBinary:await Ro.promises.readFile(Pw("codec","enc","webp_enc.wasm"))}),defaultOptions:t.defaultOptions}}))),Aw="image/png",$w={async normalize(e){if(e.mimeType!==Aw)throw new Error(`Mac screenshot must be ${Aw}, received ${e.mimeType}`);const t=await gw(),r=await t.read(Buffer.from(e.data,"base64"));return(await(n={data:r.bitmap.data,width:r.bitmap.width,height:r.bitmap.height},(async e=>{const{module:t,defaultOptions:r}=await Tw(),n=new Uint8ClampedArray(e.data.buffer,e.data.byteOffset,e.data.byteLength);return Buffer.from(t.encode(n,e.width,e.height,{...r,lossless:1,exact:1}))})(n))).toString("base64");var n}},Mw={userFacing:function(e){if(e instanceof uw&&e.userFacing&&e.message.trim().length>0&&!tw(e.message))return e.message.trim()},isCaptureBlocked:function(e){return e instanceof uw&&("computer_use_screenshot"===e.tool||"permission_required"===e.code)}},Dw=new Set(["keys"]),Ow=new Set(["matched","mismatch","unchecked"]),Fw=new Set(["no_text","password","control_keys","too_long","unreadable","moved","chromium","gecko"]),Nw=new Set(["matched"]),Lw=new Set(["too_long"]),jw=new Set(["watched","fell_back","unavailable","over_budget"]);class Uw{constructor({ctx:e,actions:t,sidecar:r,errors:n,reportTyping:o}){this.startTime=Date.now(),this.typingNotes=[],this.typing=[],this.geometryPrimed=!1,this.actionCount=0,this.hasCompletedActuation=!1,this.staleAfterWait=!1,this.ctx=e,this.actions=t,this.sidecar=r,this.errors=n??Mw,this.reportTyping=!0===o}async execute(){const e=this.actions.some((e=>Uw.isInputAction(e.action.case)));try{this.throwIfAborted(),e&&await this.sidecar.startControl(this.ctx);for(const e of this.actions){this.throwIfAborted();const t=e.action;if(void 0===t.case)throw new Error("Computer use action case is undefined");switch(this.actionCount+=1,t.case){case"screenshot":case"cursorPosition":await this.captureScreen();break;case"click":void 0!==t.value.coordinate&&await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.click(this.ctx,{coordinate:t.value.coordinate,button:Uw.mouseButtonName(t.value.button),count:t.value.count>0?t.value.count:1,modifierKeys:t.value.modifierKeys}),t.value.coordinate);break;case"scroll":void 0!==t.value.coordinate&&await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.scroll(this.ctx,{coordinate:t.value.coordinate,direction:Uw.scrollDirectionName(t.value.direction),amount:t.value.amount>0?t.value.amount:3,modifierKeys:t.value.modifierKeys}),t.value.coordinate);break;case"mouseMove":if(void 0===t.value.coordinate)throw new Error("MouseMoveAction requires coordinate");await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.move(this.ctx,{x:t.value.coordinate.x,y:t.value.coordinate.y}),t.value.coordinate);break;case"mouseDown":this.recordActuation(await this.sidecar.mouseButton(this.ctx,{button:Uw.mouseButtonName(t.value.button),action:"down"}));break;case"mouseUp":this.recordActuation(await this.sidecar.mouseButton(this.ctx,{button:Uw.mouseButtonName(t.value.button),action:"up"}));break;case"drag":{const e=t.value.path.map((e=>({x:e.x,y:e.y})));await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.drag(this.ctx,{button:Uw.mouseButtonName(t.value.button),path:e,modifierKeys:t.value.modifierKeys}),e.at(-1));break}case"type":{const e=await this.sidecar.typeText(this.ctx,t.value.text);this.recordActuation(e),this.recordTyping(e);break}case"key":if(t.value.stroke===Ng.EB.DOWN||t.value.stroke===Ng.EB.UP)throw new Error("Held keys (KeyAction.stroke DOWN/UP) are not supported by the computer-use sidecar; use hold_duration_ms");this.recordActuation(await this.sidecar.pressKey(this.ctx,{key:t.value.key,holdDurationMs:t.value.holdDurationMs}));break;case"wait":await this.delay(Math.max(0,t.value.durationMs)),this.staleAfterWait=!0;break;default:{const e=t;throw new Error(`Unknown computer use action: ${JSON.stringify(e)}`)}}}this.throwIfAborted(),(void 0===this.screenshot||this.staleAfterWait)&&await this.captureScreen(),this.throwIfAborted();const t=await this.normalizeRetainedScreenshots();return t.screenshotFailed&&!this.hasCompletedActuation?this.screenshotUnavailableResult(t.failureReason):(this.throwIfAborted(),new Ng.ks({result:{case:"success",value:new Ng.Wd({actionCount:this.actionCount,durationMs:Date.now()-this.startTime,screenshot:t.screenshot,cursorPosition:this.cursor,log:this.log(t.screenshotFailed?"Screenshot unavailable":void 0),typing:this.typing})}}))}catch(e){return this.ctx.signal.aborted?this.abortedResult():this.errorResult(e)}finally{e&&await this.sidecar.releaseControl(this.ctx)}}static isInputAction(e){switch(e){case"click":case"scroll":case"mouseMove":case"mouseDown":case"mouseUp":case"drag":case"type":case"key":return!0;default:return!1}}async captureScreen(){const e=await this.sidecar.screenshot(this.ctx);this.screenshot=e.screenshot,this.cursor=Uw.cursorFromResult(e)??this.cursor,this.geometryPrimed=!0,this.staleAfterWait=!1}async ensureGeometryCached(){this.geometryPrimed||await this.captureScreen()}recordActuation(e,t){this.screenshot=e.screenshot,this.hasCompletedActuation=!0,this.staleAfterWait=!1,void 0!==e.screenshot&&(this.geometryPrimed=!0),this.cursor=Uw.cursorFromResult(e)??Uw.coordinateFromPoint(t)??this.cursor}recordTyping(e){if(!this.reportTyping)return;const t=e.message.trim();""!==t&&this.typingNotes.push(t);const r=Uw.typingFromResult(e);void 0!==r&&this.typing.push(r)}log(e){const t=void 0===e?this.typingNotes:[...this.typingNotes,e];return 0===t.length?void 0:t.join("\n")}static typingFromResult(e){const t=e.structuredContent;if("object"!=typeof t||null===t||!("type"in t))return;const r=t.type;if("object"!=typeof r||null===r)return;const n=new Map(Object.entries(r)),o=(e,t)=>{const r=n.get(e);return"string"==typeof r&&t.has(r)?r:void 0},s=e=>{const t=n.get(e);return"number"==typeof t&&Number.isInteger(t)&&t>=0?t:void 0},i=o("check",Ow),a=o("unchecked",Fw),c=void 0!==n.get("unchecked")&&null!==n.get("unchecked"),l=void 0!==i&&Nw.has(i)&&!c||"unchecked"===i&&void 0!==a&&Lw.has(a);return new Ng.qA({method:o("method",Dw)??"",chars:l?s("chars")??0:0,atoms:l?s("atoms")??0:0,typedAtoms:l?s("typedAtoms")??0:0,aborted:!0===n.get("aborted"),check:i,verified:l?s("verified"):void 0,unchecked:a,landing:o("landing",jw)})}async errorResult(e){let t;if(Uw.logger.error(this.ctx,"local-cua execute failed",void 0,{error:dw(e)}),!this.errors.isCaptureBlocked(e))try{const e=await this.sidecar.screenshot(this.ctx);t=(await this.normalizeScreenshot(e.screenshot,"error")).data}catch(e){Uw.logger.warn(this.ctx,"local-cua error screenshot capture failed",{error:dw(e)})}const r=this.errors.userFacing(e);return new Ng.ks({result:{case:"error",value:new Ng.Jb({error:void 0===r?"Computer use failed":`Computer use failed: ${r}`,actionCount:this.actionCount,durationMs:Date.now()-this.startTime,screenshot:t,log:this.log(),typing:this.typing})}})}screenshotUnavailableResult(e){return new Ng.ks({result:{case:"error",value:new Ng.Jb({error:"Screenshot unavailable",actionCount:this.actionCount,durationMs:Date.now()-this.startTime,log:e})}})}abortedResult(){return new Ng.ks({result:{case:"error",value:new Ng.Jb({error:"Computer use aborted",actionCount:this.actionCount,durationMs:Date.now()-this.startTime,log:this.log(),typing:this.typing})}})}static mouseButtonName(e){return Uw.mouseButtonNames[e]??"left"}static scrollDirectionName(e){return Uw.scrollDirectionNames[e]??"down"}async normalizeRetainedScreenshots(){const e=await this.normalizeScreenshot(this.screenshot,"post-action");return{screenshot:e.data,screenshotFailed:void 0===this.screenshot||e.failed,failureReason:void 0===this.screenshot?"sidecar returned no image":e.reason}}async normalizeScreenshot(e,t){if(void 0===e)return{failed:!1};try{return{data:await $w.normalize(e),failed:!1}}catch(r){const n=dw(r);return Uw.logger.error(this.ctx,"local-cua screenshot conversion failed",void 0,{frame:t,error:n}),"image/png"===e.mimeType&&e.data.length>0?{data:e.data,failed:!1}:{failed:!0,reason:n}}}static coordinateFromPoint(e){if(void 0!==e&&Number.isFinite(e.x)&&Number.isFinite(e.y))return new Ng.xp({x:Math.round(e.x),y:Math.round(e.y)})}static cursorFromResult(e){const t=e.structuredContent;if("object"!=typeof t||null===t||!("cursor"in t))return;const r=t.cursor;return"object"==typeof r&&null!==r&&"x"in r&&"y"in r&&"number"==typeof r.x&&"number"==typeof r.y&&Number.isFinite(r.x)&&Number.isFinite(r.y)?new Ng.xp({x:Math.round(r.x),y:Math.round(r.y)}):void 0}throwIfAborted(){if(this.ctx.signal.aborted)throw this.ctx.signal.reason??new Error("Computer use aborted")}delay(e){return this.throwIfAborted(),new Promise(((t,r)=>{const n=()=>{clearTimeout(o),r(this.ctx.signal.reason??new Error("Computer use aborted"))},o=setTimeout((()=>{this.ctx.signal.removeEventListener("abort",n),t()}),e);this.ctx.signal.addEventListener("abort",n,{once:!0}),this.ctx.signal.aborted&&n()}))}}Uw.logger=(0,d.h)("local-cua:actions"),Uw.mouseButtonNames={[Ng.w3.UNSPECIFIED]:"left",[Ng.w3.LEFT]:"left",[Ng.w3.RIGHT]:"right",[Ng.w3.MIDDLE]:"middle",[Ng.w3.BACK]:"left",[Ng.w3.FORWARD]:"left"},Uw.scrollDirectionNames={[Ng.Dh.UNSPECIFIED]:"down",[Ng.Dh.UP]:"up",[Ng.Dh.DOWN]:"down",[Ng.Dh.LEFT]:"left",[Ng.Dh.RIGHT]:"right"},s.join(o.tmpdir(),"computer-use"),(0,d.h)("local-cua:windows");Error,Buffer.from([137,80,78,71,13,10,26,10]),new Set(["capture_failed","secure_desktop","input_desktop_unavailable","sidecar_unavailable","user_aborted","session_busy","canvas_mismatch"]);var Bw,Ww=r("../proto/dist/generated/agent/v1/delete_exec_pb.js");function Hw({encoding:e,bom:t,lineEnding:r}){return{encoding:e,bom:t,lineEnding:r}}class qw{constructor(e){this.workspacePath=e,this.changes=new Map,this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){for(const t of this.listeners)t(e)}async trackChange(e,t,r,n,o){const s=this.changes.get(e);if(s){const t=s.before,o=n||s.metadata;if(t===r||void 0===t&&void 0===r)this.changes.delete(e),this.notify();else{const n={path:e,before:t,after:r,metadata:o,...void 0===s.beforeFormat?{}:{beforeFormat:s.beforeFormat}};this.changes.set(e,n),this.notify(n)}}else{const s={path:e,before:t,after:r,metadata:n,...void 0===o?{}:{beforeFormat:o}};this.changes.set(e,s),this.notify(s)}}getChanges(){return Array.from(this.changes.values())}getChange(e){return this.changes.get(e)}hasChange(e){return this.changes.has(e)}accept(e){const t=this.changes.get(e);this.changes.delete(e),this.notify(t)}acceptAll(){this.changes.clear(),this.notify()}async reject(e){const t=this.changes.get(e);if(t)try{void 0===t.before&&void 0!==t.after?await(0,xo.unlink)(e):(void 0!==t.before&&void 0===t.after||void 0!==t.before&&void 0!==t.after)&&await async function(e,t,r,n){const{buffer:o,format:s}=await qi(e,t,r,n);await(0,xo.writeFile)(e,o),await Hi(e,{buffer:o,encoding:s.encoding})}(e,t.before,this.workspacePath)}catch{}finally{this.changes.delete(e),this.notify(t)}}async rejectAll(){const e=Array.from(this.changes.keys());await Promise.all(e.map((e=>this.reject(e))))}clear(){const e=this.changes.values().next().value;this.changes.clear(),this.notify(e)}get size(){return this.changes.size}dispose(){this.changes.clear(),this.listeners.clear()}}!function(e){e.Write="write",e.Read="read",e.Shell="shell",e.Delete="delete",e.Mcp="mcp"}(Bw||(Bw={}));var zw=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class Gw{constructor(e,t,r,n,o,s){this.pendingDecisionProvider=e,this.fileChangeTracker=t,this.permissionsService=r,this.workspacePath=n,this.onDeleteForAiTracking=o,this.agentFileViews=s}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,D.VI)(e.withName("LocalDeleteExecutor.execute")),!1);const n=t.path;if(""===n.trim())return new Ww.Pi({result:{case:"error",value:new Ww.GU({path:n,error:rs})}});const o=(0,ts.o1)(n,this.workspacePath),i=await this.permissionsService.shouldBlockWrite(e,o,"");if(i){const e=await ed(i,{onNeedsApproval:async(e,t)=>null,onUserRejected:e=>new Ww.Pi({result:{case:"rejected",value:new Ww.iq({path:o,reason:e||""})}}),onPermissionDenied:(e,t)=>new Ww.Pi({result:{case:"permissionDenied",value:new Ww.QG({path:o,clientVisibleError:e,isReadonly:t?.isReadonly??!1})}})});if(null!==e)return e}const a=await async function(e,t){const r=await(0,xo.realpath)((0,s.dirname)(e)).catch((()=>{}));if(void 0===r)return e;if(void 0!==t){const n=await(0,xo.realpath)(t).catch((()=>{}));if(void 0!==n&&(0,ts.BJ)(r,n))return(0,s.resolve)(t,(0,s.relative)(n,r),(0,s.basename)(e))}return(0,s.join)(r,(0,s.basename)(e))}(o,this.workspacePath),c=await this.pendingDecisionProvider.requestApproval({type:Bw.Delete,details:{path:a},toolCallId:t.toolCallId});if(!c.approved)return new Ww.Pi({result:{case:"rejected",value:new Ww.iq({path:o,reason:c.reason||""})}});let l;try{l=await(0,xo.stat)(o)}catch(e){return"ENOENT"===_c(e)?new Ww.Pi({result:{case:"fileNotFound",value:new Ww.n0({path:o})}}):new Ww.Pi({result:{case:"error",value:new Ww.GU({path:o,error:Cc(e)})}})}if(!l.isFile()){const e=l.isDirectory()?"directory":"other";return new Ww.Pi({result:{case:"notFile",value:new Ww.LX({path:o,actualType:e})}})}const u=l.size;let d,h;if(u<=ss)try{const e=await Wi(o);d=e.text,h=Hw(e)}catch{}const p=d??"",f=await(0,xo.realpath)(o).catch((()=>o)),m=await(0,xo.stat)(o).catch((()=>{}));if(m?.dev!==l.dev||m.ino!==l.ino)return new Ww.Pi({result:{case:"error",value:new Ww.GU({path:o,error:"File changed while deleting; nothing was removed"})}});e.signal.throwIfAborted();try{await(0,xo.unlink)(o),this.agentFileViews?.recordDelete(o)}catch(e){return"EACCES"===_c(e)?new Ww.Pi({result:{case:"permissionDenied",value:new Ww.QG({path:o,clientVisibleError:"Permission denied"})}}):"EBUSY"===_c(e)?new Ww.Pi({result:{case:"fileBusy",value:new Ww.vX({path:o})}}):new Ww.Pi({result:{case:"error",value:new Ww.GU({path:o,error:Cc(e)})}})}if(this.fileChangeTracker&&void 0!==d){const e={...t.toolCallId?{toolCallId:t.toolCallId}:{},...f===o?{}:{writtenPath:f},beforeMode:511&l.mode};await this.fileChangeTracker.trackChange(o,d,void 0,e,h)}return this.onDeleteForAiTracking&&this.onDeleteForAiTracking({path:o}).catch((()=>{})),new Ww.Pi({result:{case:"success",value:new Ww.fl({path:o,deletedFile:o,fileSize:BigInt(u),prevContent:p})}})}catch(e){r.error=e,r.hasError=!0}finally{zw(r)}}}class Vw{constructor(e,t){this.inner=e,this.extraTools=t}async getTools(e){return[...await this.inner.getTools(e).catch((()=>[])),...this.extraTools]}async getToolsForServers(e,t){const r=await this.inner.getToolsForServers(e,t).catch((()=>[])),n=new Set(t);return[...r,...this.extraTools.filter((e=>n.has(e.clientKey)||n.has(e.providerIdentifier)))]}async getClients(e){return this.inner.getClients(e)}async getClient(e,t){return this.inner.getClient(e,t)}async getInstructions(e){const t=await this.inner.getInstructions(e).catch((()=>[])),r=this.extraTools.filter((e=>e.providerIdentifier===Vn));if(0===r.length)return t;const n=r.map((e=>{const t="string"==typeof e.description&&e.description.length>0?e.description:"(no description provided)";return`- ${e.toolName}: ${t}`})).join("\n");return[...t,new vn.I0({serverIdentifier:Vn,serverName:Vn,instructions:`User-defined tools for this session (server "${Vn}"). Discover schemas via MCP meta-tool discovery for that server, then invoke via the MCP invocation meta-tool.\n\nAvailable tools:\n${n}`})]}async getToolSet(e){return this.inner.getToolSet(e)}}class Kw extends Vw{constructor(e,t){super(e,t),this.observableInner=e}onDidChange(e){return this.observableInner.onDidChange(e)}}var Jw=r("../proto/dist/generated/agent/v1/fetch_exec_pb.js"),Zw=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Xw=/;\s*charset\s*=\s*"?([^";\s]+)/i;class Qw{constructor(e){this.encodingSlices=e?.encodingSlices}async readText(e,t){if(!Wl(this.encodingSlices,e))return await t.text();const r=async function(e,t){if(void 0===e)return"unseen";try{return(0,n.isUtf8)(await e.arrayBuffer())?"utf8_valid":t?"declared_other":"utf8_invalid"}catch{return"unseen"}}(function(e){try{return e.clone()}catch{return}}(t),function(e){const t=Xw.exec(e.headers.get("content-type")??"")?.[1];return void 0!==t&&!/^utf-?8$/i.test(t)}(t)),o=await t.text();return this.recordFetched(e,o,r),o}async recordFetched(e,t,r){try{tu(this.encodingSlices,e,{layer:"exec_web_fetch",evidence:await r},t)}catch{}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,D.VI)(e.withName("LocalFetchExecutor.execute")),!1);const n=t.url;try{const t=await fetch(n),r=await this.readText(e,t),o=t.headers.get("content-type")||"text/plain";return new Jw.uN({result:{case:"success",value:new Jw.Uk({url:n,content:r,statusCode:t.status,contentType:o})}})}catch(e){return new Jw.uN({result:{case:"error",value:new Jw.fk({url:n,error:Cc(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{Zw(r)}}}const Yw=[["safe.bareRepository","explicit"]],ey=[["core.fsmonitor","false"],["core.hooksPath",o.devNull],["core.attributesFile",o.devNull]],ty=[["core.quotePath","false"]];function ry(e){const t="allow-hooks"===e?ey.filter((([e])=>"core.hooksPath"!==e)):ey;return[...Yw,...t]}const ny=(0,Vs.promisify)(iu.execFile),oy=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env","--attr-source"]),sy=new Set(["diff","show","blame","log","whatchanged"]);function iy(e){for(let t=0;t["-c",`${e}=${t}`]))}const vy=yy([...ry("block"),["submodule.recurse","false"],["fetch.recurseSubmodules","false"],["diff.submodule","short"],["status.submoduleSummary","false"],["log.showSignature","false"],["log.diffMerges","separate"],["gpg.openpgp.program",o.devNull],["gpg.x509.program",o.devNull],["gpg.ssh.program",o.devNull]]);function by(e){const t=e?.timeout??0,r=Number.isFinite(t)&&t>0?Math.min(t,2147483647):6e4;return performance.now()+r}function Sy(e,t=2147483647){return Math.max(1,Math.ceil(Math.min(t,e-performance.now())))}function ky(){const e=new Map;return{async exec(t,r,n){const o=by(n);return uy("git",await _y(e,t,r,o),{cwd:t,env:wy,windowsHide:!0,killSignal:"SIGTERM",timeout:Sy(o)})},async run(t,r,n){const o=by(n);return function(e,t,r,n){return new Promise(((o,s)=>{const i=function(e,t,r){const{env:n,...o}=r??{},s=cy(t);return(0,iu.spawn)("git",s,{...o,env:ly(s,n)})}(0,t,{cwd:e,env:wy,windowsHide:!0,stdio:[void 0===n?"ignore":"pipe","pipe","pipe"]}),a=[],c=[];let l=!1;const u=()=>{const e=!l;return l=!0,clearTimeout(d),e},d=setTimeout((()=>{u()&&(i.kill("SIGTERM"),i.stdin?.destroy(),i.stdout?.destroy(),i.stderr?.destroy(),s(Object.assign(new Error("git timed out"),{code:null,killed:!0,signal:"SIGTERM"})))}),Sy(r));i.stdout?.on("data",(e=>{a.push(e)})),i.stderr?.on("data",(e=>{c.push(e)}));for(const e of[i.stdout,i.stderr])e?.on("error",(e=>{u()&&(i.kill("SIGTERM"),s(e))}));i.on("error",(e=>{u()&&s(e)})),i.on("close",((e,t)=>{u()&&(null!==e?o({exitCode:e,stdout:Buffer.concat(a).toString("utf8"),stderr:Buffer.concat(c).toString("utf8")}):s(Object.assign(new Error(`git was killed by ${String(t)}`),{code:e,killed:!1,signal:t})))})),void 0!==n&&null!==i.stdin&&(i.stdin.on("error",(()=>{})),i.stdin.end(n))}))}(t,await _y(e,t,r,o),o,n?.input)}}}async function _y(e,t,r,n){const{prefix:o,tail:s,readsConfig:i}=function(e){const t=cy(e),r=iy(t),n=t.findIndex(((e,t)=>t>r&&("--"===e||"--end-of-options"===e))),o=t.slice(0,-1===n?t.length:n);if(o.includes("--help")||o.includes("-h"))throw new TypeError("git help is refused: it starts the repository's man viewer");if(-1===r)return{prefix:[],tail:t,readsConfig:!1};const s=t[r],i=hy.get(s);if(void 0===i)throw new TypeError(`git ${s} is refused: the pins cover only a fixed set of verbs`);const[a,c]=i,l=o.find((e=>function(e,t,r){const n=r.startsWith("--")?r.slice(2).split("=",1)[0]:"",o=[...py,..."status"===e?["verbose"]:[],..."worktree"===e?["checkout","no-force"]:[],...t?["ignore-submodules","no-ignore-submodules"]:[]];return""!==n&&o.some((e=>e.startsWith(n)))||"status"===e&&/^-[^-]*v/.test(r)}(s,c,e)));if(void 0!==l)throw new TypeError(`git ${s} ${l} is refused: it can start a program the pins miss`);const u=t.slice(r+1),d="worktree"===s?u.find((e=>!e.startsWith("-"))):void 0;if("remove"===d&&!o.includes("--force")&&!o.includes("-f"))throw new TypeError("git worktree remove is refused without --force");if("add"===d&&"--no-checkout"!==u[u.indexOf("add")+1])throw new TypeError("git worktree add is refused unless --no-checkout follows add");return{prefix:[...t.slice(0,r),...vy],tail:[s,...c?["--ignore-submodules=dirty"]:[],...u],readsConfig:a}}(r),a=i?await function(e,t,r,n){const o=`${t}\0${r.join("\0")}`,s=e.get(o);if(void 0!==s)return s;const i=async function(e,t,r){let n;try{n=(await uy("git",[...t,"config","--list","--show-scope","--includes","-z"],{cwd:e,env:wy,windowsHide:!0,killSignal:"SIGTERM",timeout:Sy(r,1e4),maxBuffer:16777216})).stdout}catch(e){throw function(e){if(!(e instanceof Error))return new dy("read-failed");if("syscall"in e&&"string"==typeof e.syscall&&e.syscall.startsWith("spawn"))return e;if("killed"in e&&!0===e.killed)return new dy("timed-out");const t="code"in e&&"number"==typeof e.code?e.code:void 0;return new dy("read-failed",t)}(e)}if(performance.now()>=r)throw new dy("timed-out");return function(e){if(""===e)return[];const t=e.split("\0");if(""!==t.pop()||t.length%2!=0)throw new dy("read-failed");const r=new Set;for(let e=0;eyy([[`filter.${e}.clean`,""],[`filter.${e}.smudge`,""],[`filter.${e}.process`,""],[`filter.${e}.required`,"false"]])))}(n)}(t,r,n);return e.set(o,i),i}(e,t,o,n):[];return[...o,...a,...s]}function Cy(e,t,r){return ky().exec(e,t,r)}var Ey=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class xy{constructor(e={}){void 0!==e.guardedRootLookup&&(this.guardedRootLookup=e.guardedRootLookup)}async exec(e,t,r,n){return Py(e,t,r,n,Cy)}forRequest(){const e=ky();return{exec:(t,r,n,o)=>Py(t,r,n,o,((t,r,n)=>e.exec(t,r,n))),...void 0===this.guardedRootLookup?{}:{guardedRootLookup:this.guardedRootLookup}}}}async function Py(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(s,(0,D.VI)(e.withName("LocalGitExecutor.exec"),{attributes:{"git.cwd":t,"git.args":r,"git.caller":n?.caller}}),!1);const{stdout:i,stderr:a}=await o(t,r,{timeout:n?.timeout});return{exitCode:0,stdout:i,stderr:a}}catch(e){s.error=e,s.hasError=!0}finally{Ey(s)}}var Ry=r("../proto/dist/generated/agent/v1/grep_exec_pb.js");class Iy{constructor(){this.lineEnd=0,this.nextStart=0}}function Ty(e,t,r){const n=e.length;if(t>=n)return!1;const o=e.indexOf("\n",t);if(-1!==o){const n=o>t&&13===e.charCodeAt(o-1);return r.lineEnd=n?o-1:o,r.nextStart=o+1,!0}return r.lineEnd=n,r.nextStart=n,!0}function Ay(e,t,r,n,o,s){const i=e.indexOf("\0",t);if(-1===i||i>=r)return;let a=i+1;for(;a=48&&e.charCodeAt(a)<=57;)a++;if(a===i+1||a>=r)return;const c=e.charCodeAt(a);if(58!==c&&45!==c)return;const l=n.indexOf(0,o);if(-1===l||l>=s)return;const u=l+(a-i);return u>=s||n.toString("latin1",l+1,u+1)!==e.slice(i+1,a+1)?void 0:{file:e.slice(t,i),contentStart:a+1,contentEnd:r,contentBytesStart:u+1,contentBytesEnd:s}}const $y=-(2**31),My=2**31-1;function Dy(e){return Number.isNaN(e)?0:e<$y?$y:e>My?My:e}function Oy(e){if("number"==typeof e&&Number.isFinite(e)&&!(e<0))return Dy(Math.trunc(e))}function Fy(e){const t=e.replace(/\s/g,"_").replace(/[^a-zA-Z0-9_.-]/g,"").replace(/\.+/g,".");return"."===t||".."===t?t.replace(/\./g,"_"):0===t.length?"_":t}async function Ny(e,t){const r=Fy(t),n=(0,s.join)(e,"mcps",r,"tools");let o;try{o=await(0,xo.readdir)(n)}catch(e){if("ENOENT"===_c(e))return{toolNames:[],toolsDirExists:!1};throw e}const i=await Promise.all(o.map((async e=>{if(e.endsWith(".json"))try{return function(e){try{const t=JSON.parse(e);return"string"==typeof t.name&&t.name.length>0?t.name:"string"==typeof t.toolName&&t.toolName.length>0?t.toolName:void 0}catch{return}}(await(0,xo.readFile)((0,s.join)(n,e),"utf8"))}catch{return}}))),a=new Set;for(const e of i)e&&a.add(e);return{toolNames:Array.from(a).sort(((e,t)=>e.localeCompare(t))),toolsDirExists:!0}}const Ly=(0,d.h)("local-exec:mcp-disk-freshness-on-access"),jy="/mcps/",Uy=(0,h.Pu)("mcp.discovery_freshness.check",{description:"MCP discovery surface freshness comparison outcome against canonical live tools",labelNames:["surface","outcome"]}),By=(0,h.v5)("mcp.discovery_freshness.missing_tools",{description:"Number of tools present in canonical live state but missing from the observed discovery surface",labelNames:["surface"]}),Wy=(0,h.v5)("mcp.discovery_freshness.extra_tools",{description:"Number of tools present on the observed discovery surface but absent from canonical live state",labelNames:["surface"]}),Hy=(0,h.v5)("mcp.discovery_freshness.symmetric_difference",{description:"Total symmetric difference between canonical live tools and the observed discovery surface",labelNames:["surface"]}),qy=new Map;function zy(e){const t=e.replace(/\\/g,"/");return t.endsWith("/mcps")?`${t}/`:t}async function Gy({ctx:e,mcpStateAccessor:t,projectDir:r,sanitizedServerFolder:n,readDiskCatalog:o,state:s}){let i=s;if(void 0===i)try{i=await t.getState(e)}catch(t){return void Ly.warn(e,"mcp_disk_state_read_failed",{error_type:t instanceof Error?t.name:typeof t})}const a=i.servers.find((e=>Fy(e.serverIdentifier)===n));if(void 0===a)return;let c;try{c=await o(r,a.serverIdentifier)}catch(t){return void Ly.warn(e,"mcp_disk_catalog_read_failed",{error_type:t instanceof Error?t.name:typeof t})}if(!c.toolsDirExists)return;const l=a.tools.map((e=>e.toolName)).filter((e=>e.length>0)).sort(((e,t)=>e.localeCompare(t)));!function({ctx:e,serverIdentifier:t,canonicalToolNames:r,observedToolNames:n}){const o=new Set(n),s=new Set(r),i=r.filter((e=>!o.has(e))),a=n.filter((e=>!s.has(e))),c=0===i.length&&0===a.length?"match":"mismatch",l={surface:"disk"};Uy.increment(e,1,{...l,outcome:c}),By.histogram(e,i.length,l),Wy.histogram(e,a.length,l),Hy.histogram(e,i.length+a.length,l),"mismatch"===c&&Ly.warn(e,"mcp_disk_discovery_freshness_mismatch",{server_identifier:t,missing_tool_count:i.length,extra_tool_count:a.length})}({ctx:e,serverIdentifier:a.serverIdentifier,canonicalToolNames:l,observedToolNames:c.toolNames})}function Vy(e,t,r,n=Ny){if(void 0===r||(void 0===(o=r)||!zy(o).includes(jy)))return;var o;const s=function(e){const t=zy(e),r=t.indexOf(jy);if(-1===r)return;const n=t.slice(0,r),o=t.slice(r+6).split("/").filter(Boolean);return 0!==n.length?0===o.length?{projectDir:n,kind:"mcps_root"}:{projectDir:n,kind:"server",sanitizedServerFolder:o[0]}:void 0}(r);if(void 0===s)return;let i,a;const c="mcps_root"===s.kind;"mcps_root"===s.kind?(i=`${s.projectDir}\0__mcps_root__`,a=void 0):(i=`${s.projectDir}\0${s.sanitizedServerFolder}`,a=s.sanitizedServerFolder);const l=qy.get(i);void 0!==l&&clearTimeout(l);const u=e,d=setTimeout((()=>{qy.delete(i),(async()=>{if(c){const e=await t.getState(u);for(const r of e.servers){const o=Fy(r.serverIdentifier);await Gy({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:o,readDiskCatalog:n,state:e})}}else void 0!==a&&await Gy({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:a,readDiskCatalog:n})})().catch((e=>{Ly.warn(u,"mcp_disk_discovery_freshness_schedule_failed",{error_type:e instanceof Error?e.name:typeof e})}))}),2e3);qy.set(i,d)}async function Ky(e){try{return(await(0,xo.stat)(e,{bigint:!0})).mtimeNs}catch{return}}function Jy(e,t,r){const n=e.map(((e,n)=>({file:e,mtime:t[n],segments:e.path.split(r)})));return n.sort(((e,t)=>e.mtime!==t.mtime?void 0===e.mtime?1:void 0===t.mtime||e.mtime>t.mtime?-1:1:function({left:e,right:t}){const r=Math.min(e.length,t.length);for(let n=0;ne.file))}async function Zy(e,t,r=Ky){const n=e.map((e=>({item:e,path:t(e)})));let o;try{o=await(0,Nr.wj)(Promise.all(n.map((({path:e})=>r(e)))),2e3,"stat timed out")}catch(t){if(t instanceof Nr.MU)return{items:[...e],statTimedOut:!0};throw t}return{items:Jy(n,o,s.sep).map((({item:e})=>e)),statTimedOut:!1}}var Xy=r("../proto/dist/generated/agent/v1/read_exec_pb.js");const Qy=Buffer.from([137,80,78,71,13,10,26,10]),Yy=Buffer.from([0,0,0,0,73,69,78,68,174,66,96,130]),ev=e=>{if(e.lengthe.subarray(e.length-Yy.length).equals(Yy)||(e=>{let t=Qy.length+25;for(;t+Yy.length<=e.length;){const r=e.readUInt32BE(t);if(r>e.length-t-Yy.length)return!1;if("IEND"===e.toString("ascii",t+4,t+8))return e.subarray(t,t+Yy.length).equals(Yy);t+=Yy.length+r}return!1})(e))(e))return;const t=e.readUInt32BE(16),r=e.readUInt32BE(20);return t<1||r<1?void 0:{width:t,height:r,colorType:e.readUInt8(25)}},tv=e=>1===e||e>=208&&e<=216,rv=e=>192===e||193===e||194===e,nv=e=>e>=195&&e<=207&&196!==e&&200!==e&&204!==e,ov=e=>0===e||e>=208&&e<=215,sv=(e,t)=>{let r=e.indexOf(255,t);for(;-1!==r&&r+1(e=>{const t=ev(e);if(void 0!==t)return{mimeType:"image/png",width:t.width,height:t.height}})(e)??(e=>{if(e.length<4||255!==e[0]||216!==e[1]||!(e=>255===e[e.length-2]&&217===e[e.length-1]||(e=>{let t=2;for(;t+2<=e.length;){if(255!==e[t])return!1;const r=e[t+1];if(255===r){t+=1;continue}if(217===r)return!0;if(tv(r)){t+=2;continue}if(t+4>e.length)return!1;const n=e.readUInt16BE(t+2);if(n<2)return!1;const o=t+2+n;if(218!==r){t=o;continue}const s=sv(e,o);if(void 0===s)return!1;t=s}return!1})(e))(e))return;let t=2;for(;t+4<=e.length;){if(255!==e[t])return;const r=e[t+1];if(255===r){t+=1;continue}if(tv(r)){t+=2;continue}if(218===r||217===r||nv(r))return;const n=e.readUInt16BE(t+2);if(n<2)return;if(rv(r)){if(n<8||t+9>e.length)return;const r=e.readUInt16BE(t+5),o=e.readUInt16BE(t+7);if(o<1||r<1)return;return{mimeType:"image/jpeg",width:o,height:r}}t+=2+n}})(e),av=(e,t)=>({width:Math.max(e?.width??0,t.width),height:Math.max(e?.height??0,t.height)}),cv=(e,t)=>{for(;t{const t=e.toString("latin1",0,6);return e.subarray(0,Qy.length).equals(Qy)?"png":t.startsWith("ÿØÿ")?"jpeg":"GIF87a"===t||"GIF89a"===t?"gif":t.startsWith("BM")?"bmp":t.startsWith("II*\0")||t.startsWith("MM\0*")?"tiff":t.startsWith("ID3")?"id3":void 0},uv={0:1,2:3,4:2,6:4},dv=async({data:e,width:t,height:r})=>{const n=hv(e);if(void 0===n||t>n.width||r>n.height)return;const o=n.width*n.channels,s=new Uint32Array(n.width);for(let e=0;e{let t;const r=[];let n=8;for(;n+12<=e.length;){const o=e.readUInt32BE(n),s=e.toString("ascii",n+4,n+8),i=e.subarray(n+8,n+8+o);if(i.length!==o)return;if("IHDR"===s){const e=uv[i[9]];if(void 0!==t||13!==o||8!==i[8]||0!==i[12]||void 0===e)return;t={width:i.readUInt32BE(0),height:i.readUInt32BE(4),channels:e}}else if("IDAT"===s)r.push(i);else{if("tRNS"===s)return;if("IEND"===s)break}n+=o+12}return void 0===t||0===r.length?void 0:{...t,idat:r}},pv=({filter:e,row:t,previous:r,bytesPerPixel:n})=>{if(0!==e)for(let o=0;o=n?t[o-n]:0,i=r[o];switch(e){case 1:t[o]+=s;break;case 2:t[o]+=i;break;case 3:t[o]+=s+i>>1;break;case 4:{const e=o>=n?r[o-n]:0,a=s+i-e,c=Math.abs(a-s),l=Math.abs(a-i),u=Math.abs(a-e);t[o]+=c<=l&&c<=u?s:l<=u?i:e;break}default:throw new Error(`unknown PNG filter type ${e}`)}}},fv=({row:e,channels:t,columnOf:r,sums:n,counts:o})=>{const s=t<3;for(let i=0,a=0;i{for(let s=0;s0&&(e[c]=Math.round(n[i]/a),e[c+1]=Math.round(n[i+1]/a),e[c+2]=Math.round(n[i+2]/a),e[c+3]=Math.round(a/o[s]))}n.fill(0),o.fill(0)},gv={0:1,2:3,3:1,4:2,6:4},wv=[1,2,4,8,16],yv=[[0,0,8,8],[4,0,8,8],[0,4,4,8],[2,0,4,4],[0,2,2,4],[1,0,2,2],[0,1,1,2]],vv=async e=>{const t=bv(e);if(void 0===t)return;const r=Sv(t);let n=0;const o=ch.Readable.from(t.idat).pipe((0,oh.createInflate)());for await(const e of o)if(n+=e.length,n>=r)return void o.destroy();throw new Error(`PNG pixel data ends after ${n} of ${r} bytes`)},bv=e=>{let t;const r=[];let n=8;for(;n+12<=e.length;){const o=e.readUInt32BE(n),s=e.toString("ascii",n+4,n+8),i=e.subarray(n+8,n+8+o);if("IHDR"===s&&void 0===t&&13===i.length){const e=gv[i[9]];if(void 0===e||!wv.includes(i[8])||i[12]>1)return;t={width:i.readUInt32BE(0),height:i.readUInt32BE(4),bitsPerPixel:e*i[8],interlaced:1===i[12]}}else if("IDAT"===s)r.push(i);else if("IEND"===s)break;n+=o+12}return void 0===t||0===r.length?void 0:{...t,idat:r}},Sv=({width:e,height:t,bitsPerPixel:r,interlaced:n})=>{const o=(e,t)=>e<=0||t<=0?0:t*(1+Math.ceil(e*r/8));return n?yv.reduce(((r,[n,s,i,a])=>r+o(Math.ceil((e-n)/i),Math.ceil((t-s)/a))),0):o(e,t)};const kv=()=>{throw new Error("webp codec not registered: registerWebpCodec() must be called by a Node server before decoding/encoding webp")},_v=e=>e.length>=12&&"RIFF"===e.toString("ascii",0,4)&&"WEBP"===e.toString("ascii",8,12),Cv=e=>{if(!_v(e)||e.length<16)return;const t=e.toString("ascii",12,16);if("VP8 "===t){if(e.length<30||157!==e[23]||1!==e[24]||42!==e[25])return;return{width:16383&(e[26]|e[27]<<8),height:16383&(e[28]|e[29]<<8)}}if("VP8L"===t){if(e.length<25||47!==e[20])return;const t=(e[21]|e[22]<<8|e[23]<<16|e[24]<<24)>>>0;return{width:1+(16383&t),height:1+(t>>14&16383)}}if("VP8X"===t){if(e.length<30)return;return{width:1+(e[24]|e[25]<<8|e[26]<<16),height:1+(e[27]|e[28]<<8|e[29]<<16)}}},Ev=e=>kv().decode(e);async function xv(e){((e,t)=>{if(!Number.isSafeInteger(e)||e<1||e>t)throw new Error("pngByteBudgetBytes must be a positive integer at most MAX_IMAGE_SIZE_BYTES")})(e.budgetBytes,e.maxImageBytes);iv(e.data);return e.resizeWithoutBudget(e.data)}const Pv=[{width:1280,height:800},{width:1456,height:840}],Rv=e=>void 0!==e&&Pv.some((t=>t.width===e.width&&t.height===e.height)),Iv=1048576,Tv=e=>{const t=e.buffer;return t instanceof ArrayBuffer?new Uint8Array(t,e.byteOffset,e.byteLength):Uint8Array.from(e)};function Av(e,t,r=1024){if(e<1||t<1)return{width:e,height:t,needsResize:!1};const n=Math.max(e,t);if(n<=r)return{width:e,height:t,needsResize:!1};const o=Math.min(e,t);if(o<8)return{width:e,height:t,needsResize:!1};let s=r/n,i=Math.max(1,Math.round(e*s)),a=Math.max(1,Math.round(t*s));return(i<8||a<8)&&(s=8/o,i=Math.max(8,Math.round(e*s)),a=Math.max(8,Math.round(t*s))),{width:i,height:a,needsResize:i!==e||a!==t}}const $v=(e,t,r=1024)=>Av(e,t,r),Mv=(e,t)=>Rv({width:e,height:t})?{width:e,height:t,needsResize:!1}:Av(e,t),Dv=(e,t,r)=>{e.resize({w:t,h:r})};function Ov(e){if(void 0===e)throw new Error("image dimensions could not be read before decoding");const{width:t,height:r}=e;if(!(t*r<=178956970))throw new Error(`image dimensions ${t}x${r} exceed the 178956970 pixel decode limit`);if(!(Math.max(t,r)<=1e6))throw new Error(`image dimensions ${t}x${r} exceed the 1000000 pixel side limit`)}const Fv=(e,t)=>{switch(t){case"tiff":throw new Error("TIFF images are not supported; convert the image to PNG or JPEG");case"id3":throw new Error("images that start with an ID3 tag are not supported");case"jpeg":return;default:Ov(((e,t)=>{switch(t){case"png":return(e=>{let t,r=Qy.length;for(;r+16<=e.length;)"IHDR"===e.toString("ascii",r+4,r+8)&&(t=av(t,{width:e.readUInt32BE(r+8),height:e.readUInt32BE(r+12)})),r+=12+e.readUInt32BE(r);return t})(e);case"gif":return(e=>{if(e.length<13)return;const t={width:e.readUInt16LE(6),height:e.readUInt16LE(8)};let r=13+(128&(n=e[10])?3<<1+(7&n):0);for(var n;re.length<26?void 0:{width:e.readUInt32LE(18),height:Math.abs(e.readInt32LE(22))})(e)}})(e,t))}},Nv=e=>{const{width:t,height:r}=$v(e.width,e.height,1280);return{width:t,height:r}},Lv=async(e,t)=>{let{width:r,height:n}=e,o=await t({width:r,height:n});for(;o.length>Iv&&r>8&&n>8;)r=Math.max(8,Math.round(.8*r)),n=Math.max(8,Math.round(.8*n)),o=await t({width:r,height:n});return{data:Tv(o),mimeType:"image/webp",reencoded:!0}},jv=async(e,t)=>{const r=(await gw()).fromBitmap({data:Buffer.from(e.data),width:e.width,height:e.height});return Lv(t,(async e=>(r.bitmap.width===e.width&&r.bitmap.height===e.height||Dv(r,e.width,e.height),(e=>kv().encode(e))({data:r.bitmap.data,width:r.bitmap.width,height:r.bitmap.height}))))};let Uv;const Bv=async(e,t)=>{if(void 0!==t?.pngByteBudgetBytes){const{pngByteBudgetBytes:r,...n}=t,o=iv(e);return"image/png"===o?.mimeType&&Rv(o)&&await vv(e),xv({data:e,budgetBytes:r,maxImageBytes:Iv,fitImage:Mv,resizeWithoutBudget:e=>Bv(e,n)})}const r=await(async(e,t)=>{const r=_v(e);if(r&&!0===t?.preserveWebpDimensions)return;const n=r?void 0:iv(e),o=r?Cv(e):n;if(void 0===o||!Rv(o))return;const s=Uv;if(void 0!==n&&void 0!==s&&!Rv(await s.readOrientedDimensions(e)))return;const i="image/png"===n?.mimeType;if(i&&await vv(e),e.length<=Iv)return{data:Tv(e),mimeType:n?.mimeType??"image/webp"};const a=s?.resizeWebp;if(void 0!==a)return Lv(o,(t=>a({data:e,...t})))})(e,t);if(void 0!==r)return r;if(_v(e))return(async(e,t)=>{const r=Cv(e);if(!0===t?.preserveWebpDimensions&&void 0!==r)return{data:Tv(e),mimeType:"image/webp"};if(void 0!==r&&!$v(r.width,r.height,1280).needsResize&&e.length<=Iv)return{data:Tv(e),mimeType:"image/webp"};if("passthrough"===t?.webpWithoutCodec)return{data:Tv(e),mimeType:"image/webp"};Ov(r);const n=undefined;if(void 0!==n)return Lv(Nv(r),(t=>n({data:e,...t})));const o=await Ev(e);return jv(o,Nv(o))})(e,t);const n=iv(e);if(void 0!==n&&e.length<=Iv&&!$v(n.width,n.height).needsResize)return{data:Tv(e),mimeType:n.mimeType};const o=lv(e);void 0!==o&&Fv(e,o);const s=void 0===n?void 0:$v(n.width,n.height),i="image/png"===n?.mimeType&&!0===s?.needsResize?await dv({data:e,width:s.width,height:s.height}).catch((()=>{})):void 0;void 0===i&&"png"===o&&await vv(e);const a=await gw(),c=void 0===i?await a.read(e):a.fromBitmap(i),l=(e=>{switch(e.mime){case"image/png":default:return"image/png";case"image/bmp":return"image/bmp";case"image/tiff":return"image/tiff";case"image/x-ms-bmp":return"image/x-ms-bmp";case"image/gif":return"image/gif";case"image/jpeg":return"image/jpeg"}})(c),u=!0===t?.convertUnsupportedModelFormatsToPng&&"image/png"!==l&&"image/jpeg"!==l?"image/png":l,{width:d,height:h,needsResize:p}=$v(c.width,c.height);if(void 0===i&&!p&&e.length<=Iv&&u===l)return{data:Tv(e),mimeType:l};let f=d,m=h;p&&Dv(c,f,m);let g=await c.getBuffer(u);for(;g.length>Iv&&f>8&&m>8;)f=Math.max(8,Math.round(.8*f)),m=Math.max(8,Math.round(.8*m)),Dv(c,f,m),g=await c.getBuffer(u);return{data:Tv(g),mimeType:u,reencoded:!0}},Wv=async e=>{const t=Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=lv(t);let n;if(_v(t))return{kind:"unchecked"};if(void 0===r)return{kind:"unchecked"};{Fv(t,r);const e=await gw();n=async()=>("png"===r&&await vv(t),e.read(t))}try{return await n(),{kind:"decodes"}}catch(e){return{kind:"undecodable",reason:e instanceof Error?e.message:String(e)}}},Hv=BigInt(0),qv=BigInt(8),zv=BigInt(16),Gv=BigInt(65535);function Vv(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function Kv(e){const t=e.split(".");if(4!==t.length)return;let r=Hv;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<>zv&Gv)),t.push(Number(o.value&Gv))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function Zv(e){return Kv(e)??function(e){const t=Vv(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=Jv(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<7?void 0:{version:6,value:[...s,...new Array(8-a).fill(0),...i].reduce(((e,t)=>e<i)return!1;const a=BigInt(i-s);return o.value>>a==n.value>>a}(r,n);if(n.startsWith("*.")){const e=n.slice(2);return r===e||r.endsWith(`.${e}`)}return r===n}function Qv(e,t){const r=function(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch{return}}(e);return!!r&&function(e,t){return t.some((t=>Xv(e,t)))}(r.hostname,t)}var Yv=r("../constants/dist/commercial-cursor-hosts.js");new Set([1,2]);const eb="cursor/requiresConfirmation",tb="https://grok.com/connectors-oauth-exchange-code/",rb="https://x.com/i/connectors/oauth_callback",nb="https://chat.x.com/connectors/oauth_callback",ob="https://lite.x.com/i/connectors/oauth_callback",sb={provider:"google-workspace",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0,authorizationParams:{access_type:"offline",prompt:"select_account consent"}},ib={provider:"x-money",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,registeredAppRedirectUris:[tb,rb]},ab="x-cursor-auth";function cb(e,t){return function({serverUrl:e,restMcpHost:t}){if(void 0===e)return;let r;try{r=new URL(e)}catch{return}return"https:"===r.protocol&&r.hostname.toLowerCase()===t.toLowerCase()&&""===r.port?lb(e):void 0}({serverUrl:e,restMcpHost:t})}function lb(e){if(void 0===e)return;let t;try{t=new URL(e)}catch{return}const r=/^\/rest-mcp\/([^/]+)\/mcp\/?$/.exec(t.pathname);return r?.[1]}new Set(Object.values({notConnected:"scm_not_connected",tokenUnavailable:"scm_token_unavailable",tokenRejected:"scm_token_rejected",repoNotAccessible:"scm_repo_not_accessible",orgBlocked:"scm_org_blocked"})),new Set(Object.values({originNotEnabled:"origin_not_enabled",teamDisabled:"team_disabled",admissionRejected:"admission_rejected"}));const ub="https://mcp.shop.com",db={provider:"grok-connectors",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,scopes:["grok-plugins:access","offline_access"]},hb=new Map([["mcp.slack.com",{displayName:"Slack",baseScopes:["canvases:read","canvases:write","channels:history","channels:read","channels:write","chat:write","emoji:read","files:read","files:write","groups:history","groups:read","im:history","im:read","im:write","lists:read","lists:write","mpim:history","mpim:read","mpim:write","reactions:read","reactions:write","search:read.files","search:read.im","search:read.mpim","search:read.private","search:read.public","search:read.users","users:read","users:read.email"],stepUpScopes:{"groups:write":{action:"create private channels",tools:[{name:"slack_create_conversation",args:{is_private:!0}}]}},missingScopeAnswer:/\bmissing_scope\b/}]]),pb=new Map([["gmailmcp.googleapis.com",{...sb,scopes:["https://www.googleapis.com/auth/gmail.readonly","https://www.googleapis.com/auth/gmail.compose","https://www.googleapis.com/auth/gmail.modify"]}],["drivemcp.googleapis.com",{...sb,scopes:["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/drive.file"]}],["calendarmcp.googleapis.com",{...sb,scopes:["https://www.googleapis.com/auth/calendar.events","https://www.googleapis.com/auth/calendar.calendarlist.readonly","https://www.googleapis.com/auth/calendar.events.readonly","https://www.googleapis.com/auth/calendar.events.freebusy"]}],["docsmcp.googleapis.com",{...sb,scopes:["https://www.googleapis.com/auth/documents"]}],["sheetsmcp.googleapis.com",{...sb,scopes:["https://www.googleapis.com/auth/spreadsheets"]}],["slidesmcp.googleapis.com",{...sb,scopes:["https://www.googleapis.com/auth/presentations"]}],["bigquery.googleapis.com",{...sb,scopes:["https://www.googleapis.com/auth/bigquery"]}],["api.x.com",{provider:"x",clientRegistration:"static",unauthenticatedConnect:!1,rejectsCustomSchemeRedirects:!1,pinsScopesOverConfiguredScopes:!0}],["mcp.money-dev.x.com",ib],["mcp.money-staging.x.com",ib],["mcp.money.x.com",ib],["connectors-gateway.grok.gcp.mouseion.dev",db],["connectors-gateway.grok.com",db],["mcp.hubspot.com",{provider:"hubspot",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0}],["mcp.box.com",{provider:"box",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0}],["mcp.asana.com",{provider:"asana",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,configuredSecretStaysOnBackend:!0}],["mcp.strava.com",{provider:"strava",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,scopes:["read","activity:read_all","profile:read_all"]}],["mcp.quickbooks.intuit.com",{provider:"quickbooks-online",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,unauthenticatedEndpointBlocked:!0,backendOnlyTokenExchange:!0,scopes:["com.intuit.quickbooks.accounting","foundations.tools.businessreports.read","foundations.tools.bi-dashboard","foundations.tools.transactions.write","foundations.tools.companyprofile.read","foundations.tools.companyprofile.write","payroll.tools.tax.read","payroll.tools.employer.read","payroll.tools.employer.manage","payroll.tools.run.read","payroll.tools.run.manage","payroll.tools.employee.read","payroll.tools.employee.manage","worker-mgmt.tools.employee.read","worker-mgmt.tools.employee.manage","time-tracking.tools.timeentry.read","sales.tools.invoice.read","sales.tools.invoice","sales.tools.estimate.read","sales.tools.estimate","sales.tools.payment-link.read","sales.tools.payment-link","sales.tools.settings.read","sales.tools.settings","sales.tools.salesorder.read","sales.tools.salesorder","contact.tools.customer.read","contact.tools.customer","catalog.tools.item.read","catalog.tools.item","lending.tools.servicing.read","money-onboarding.tools.application"]}],["setup.shopify.com",{provider:"shopify",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!1}],["mcp.cloudflare.com",{provider:"cloudflare",clientRegistration:"dynamic",unauthenticatedConnect:!1,rejectsCustomSchemeRedirects:!1,scopes:["user:read","account:read","offline_access","d1.metadata_read","d1.read","d1.write","workers-scripts.read","workers-scripts.write","workers-routes.read","workers-routes.write","workers-tail.read","workers-kv-storage.metadata_read","workers-kv-storage.read","workers-kv-storage.write","workers-r2.metadata_read","workers-r2.read","workers-r2.write","workers-r2-bucket-item.read","workers-r2-bucket-item.write","workers-observability.read","workers-observability.write","dns.read","dns.write","zone.read","zone.write"],pinsScopesOverConfiguredScopes:!0,scopesPinGate:"mcp_cloudflare_api_oauth_scopes"}],["mcp.shop.com",{provider:"shop",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,backendOnlyTokenExchange:!0,scopes:["openid","personal_agent"],pinsScopesOverConfiguredScopes:!0,authorizationParams:{resource:ub}}],["api.elections.kalshi.com",{provider:"kalshi",clientRegistration:"dynamic",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0}],["mcp.squarespace.com",{provider:"squarespace",clientRegistration:"dynamic",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0}]]),fb=[".databricks.com",".azuredatabricks.net"];const mb=/^\/sncapps\/mcp-server\/mcp\/[^/]+$/,gb={provider:"databricks",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,scopes:["ai-gateway","offline_access"],pinsScopesOverConfiguredScopes:!0},wb={provider:"servicenow",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,unauthenticatedEndpointBlocked:!0,backendOnlyTokenExchange:!0,ownMcpJsonClientMayExchange:!0};function yb(e){if(void 0===e)return;let t;try{t=new URL(e)}catch{return}return function(e){return"https:"===e.protocol&&""===e.port&&""===e.username&&""===e.password&&function(e){const t=e.toLowerCase();return!(!/^[a-z0-9.-]+$/.test(t)||t.includes("..")||t.startsWith("."))&&fb.some((e=>t.endsWith(e)&&t.length>e.length))}(e.hostname)&&"/ai-gateway/mcp-services/system.ai.genie_one_mcp"===e.pathname.replace(/\/+$/,"")}(t)?gb:function(e){return"https:"===e.protocol&&""===e.port&&""===e.username&&""===e.password&&mb.test(e.pathname.replace(/\/+$/,""))}(t)?wb:(r=t.hostname,pb.get(r.toLowerCase()));var r}function vb(e){return e.endsWith("/")?e:`${e}/`}async function bb(e,t){if(void 0===t)return;const r=new URL(e),n=new URL(t);if(r.origin!==n.origin||!vb(r.pathname).startsWith(vb(n.pathname)))throw new Error(`Protected resource ${t} does not match expected ${r.href} (or origin)`);return n}const Sb=/^\/shops\/[A-Za-z0-9-]+\/mcp$/;function kb(e){if(void 0!==e)try{return new URL(e)}catch{return}}async function _b(e,t){if(void 0===t)return;const r=new URL(e),n=kb(t);if(void 0===n||n.origin!==r.origin||n.pathname!==r.pathname&&!Sb.test(n.pathname))throw new Error(`Protected resource ${t} does not match expected ${r.href} (or origin)`);return n}function Cb(e){const t=kb(e);return void 0===t?void 0:hb.get(t.hostname.toLowerCase())}const Eb=new Set([...pb].filter((([,e])=>"google-workspace"===e.provider)).map((([e])=>e))),xb="https://www.cursor.com/bot/mcp/oauth/callback",Pb={portal:"https://www.cursor.com/agents/mcp/oauth/callback",grokBotBounce:xb},Rb="tailnet_";new Set([`${Rb}waiting_for_approval`,`${Rb}tailnet_locked`,`${Rb}joining`]);const Ib="grokbot://mcp/oauth/callback",Tb="http://localhost:8787/callback",Ab="gb";function $b(e){const t=new URL(Tb);return t.port=String(e),t.toString()}function Mb(e){try{const t=new URL(e);if("http:"!==t.protocol)return!1;const r=t.hostname;return"localhost"===r||"127.0.0.1"===r||"[::1]"===r}catch{return!1}}function Db(e){const t=e.redirectUrl??Tb;if(!0!==e.loopbackIpv4||!Mb(t))return t;const r=new URL(t);return r.hostname="127.0.0.1",r.toString()}function Ob(e,t=Pb){const r=new Set,n=void 0!==e&&Mb(e);return e&&!n&&r.add(e),r.add(t.portal),e===Ib&&r.add(t.grokBotBounce),r.add(Tb),e&&n&&r.add(e),Array.from(r)}function Fb(e){var t;if(void 0!==e&&0!==e.length)try{const r=JSON.parse(e);if("object"==typeof(t=r)&&null!==t&&!Array.isArray(t))return r}catch{}}function Nb(e){if(void 0===e)return{};const t={};"string"==typeof e.title&&e.title.length>0&&(t.title=Jo(e.title,256));for(const r of["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"])"boolean"==typeof e[r]&&(t[r]=e[r]);return function(e){return!0===e?.[eb]}(e)&&(t[eb]=!0),0===Object.keys(t).length?{}:{annotationsJson:JSON.stringify(t)}}new Map([[Ab,Ib],["gw",tb],["gd",Tb],["xa",rb],["xc",nb],["xl",ob],...[18787,28787,31787].map((e=>[`gd${e}`,$b(e)]))]),new Map([[Ib,Ab],[xb,Ab],[tb,"gw"],[rb,"xa"],[nb,"xc"],[ob,"xl"]]),Db({loopbackIpv4:!0});var Lb=r("../mcp-core/dist/transport/mcp-url-utils.js");function jb(e){return e.trim().toLowerCase()}const Ub="";function Bb({mode:e,tools:t}){const r=(t??[]).map(jb).filter((e=>e.length>0)),n=void 0===e?void 0:jb(e);return"all"===n?{mode:"all"}:"reads"===n?{mode:"reads"}:r.length>0?{mode:"custom",tools:r}:{mode:"all"}}function Wb(e,t){switch(e.mode){case"all":return!0;case"custom":return function(e,t){const r=jb(e);return 0!==r.length&&r!==Ub&&t.some((e=>jb(e)===r))}(t.name,e.tools);case"reads":return void 0!==(r=t.annotations)&&!0!==r.destructiveHint&&!0===r.readOnlyHint;default:return e}var r}function Hb(e,t){switch(t.mode){case"all":return[`${e}:*`];case"custom":return t.tools.filter((e=>jb(e)!==Ub)).map((t=>`${e}:${t}`));case"reads":return[];default:return t}}const qb=new Set(["ash","bash","csh","dash","fish","ksh","powershell","pwsh","sh","tcsh","zsh","cmd"]);function zb(e){return e.trim().split(/\s+/).filter(Boolean)}function Gb(e){const t=function(e){const t=e.trim(),r=t[0];if('"'===r||"'"===r){const e=t.indexOf(r,1);if(-1!==e)return t.slice(0,e+1)}return zb(t)[0]}(e);if(!t)return!1;const r=t.replace(/^["']|["']$/g,"").replaceAll("\\","/").split("/"),n=(r[r.length-1]??"").replace(/\.exe$/i,"").toLowerCase();return qb.has(n)}function Vb(e,t){if(e.length>t.length)return!1;for(let r=0;r=t.tokenCount)continue;let a=!0;for(const t of e.tokens)if(!n.has(t)){a=!1;break}if(!a)continue;const c=Vb(e.tokens,t.tokens);void 0!==o?e.tokenCount>o.tokenCount?(o=e,s=c):e.tokenCount===o.tokenCount&&c&&!s&&(o=e,s=!0):(o=e,s=c)}void 0!==o&&(t.indentLevel=o.indentLevel+1,t.ancestorIds=[...o.ancestorIds,t.id])}const n=r.filter((e=>!r.some((t=>t.id!==e.id&&t.tokenCounte.id));return{options:r,defaultSelectedOptionIds:n}}(e),n=[...r.defaultSelectedOptionIds];if(!t||0===t.length)return{defaultSelectedOptionIds:n,hasClassifierSuggestions:!1};const o=[],s=new Set;for(const e of t){const t=r.options.find((t=>t.id===e));if(t){o.push(t.id),s.add(Jb(t.id));continue}const n=r.options.filter((t=>t.id.startsWith(`${e} `)||t.id===e)),i=r.options.filter((t=>e.startsWith(`${t.id} `)||e===t.id));if(i.length>0){const e=i.reduce(((e,t)=>e.id.length>t.id.length?e:t));o.push(e.id),s.add(Jb(e.id))}else if(n.length>0){const e=n.reduce(((e,t)=>e.id.length!s.has(Jb(e))));return{defaultSelectedOptionIds:[...new Set([...i,...o])],hasClassifierSuggestions:!0}}(e,t).defaultSelectedOptionIds}const Xb=["com.todesktop.230313mzl4w4u92","co.anysphere.cursor","com.anysphere.molten-glass"],Qb=["cursor","molten glass"];function Yb(e){return Xb.some((t=>e===t||e.startsWith(`${t}.`)))}const eS=[{bundleId:"com.apple.scripteditor2",name:"Script Editor"},{bundleId:"com.apple.automator",name:"Automator"},{bundleId:"com.apple.shortcuts",name:"Shortcuts"}],tS=[{bundleId:"com.apple.terminal",name:"Terminal"},{bundleId:"com.googlecode.iterm2",name:"iTerm",aliases:["iTerm2"]},{bundleId:"dev.warp.warp-stable",name:"Warp"},{bundleId:"dev.warp.warp-preview",name:"WarpPreview",aliases:["Warp Preview"]},{bundleId:"com.mitchellh.ghostty",name:"Ghostty"},{bundleId:"org.alacritty",name:"Alacritty"},{bundleId:"net.kovidgoyal.kitty",name:"kitty"},{bundleId:"com.github.wez.wezterm",name:"WezTerm"},{bundleId:"co.zeit.hyper",name:"Hyper"},{bundleId:"org.tabby",name:"Tabby"},...eS,{bundleId:Xb[0],name:"Cursor"}];function rS(e){const t=e.toLowerCase(),r=(0,s.basename)(e,".app").toLowerCase(),n=tS.find((({bundleId:e,name:n,aliases:o=[]})=>e===t||[n,...o].some((e=>{const n=e.toLowerCase();return n===t||n===r}))));return void 0!==n?{bundleId:n.bundleId,name:n.name}:Yb(t)?{bundleId:t,name:"Cursor"}:[t,r].some((e=>Qb.some((t=>e===t||e.startsWith(`${t} `)))))?{bundleId:Xb[0],name:"Cursor"}:void 0}const nS=new Set(["com.apple.systempreferences","com.apple.keychainaccess","com.apple.passwords","com.1password.1password","com.agilebits.onepassword7","com.bitwarden.desktop","com.lastpass.lastpass","org.keepassxc.keepassxc"]);function oS(e){return nS.has(e.toLowerCase())}function sS(e){return`app/${e}`}function iS(e){return"object"==typeof e&&null!==e}function aS(e){return lS.includes(e)}function cS(e){if(!iS(e))return;const{appArg:t,appSelectorArgs:r,capturesScreen:n}=e;if("boolean"==typeof n){if(void 0!==r){if(void 0!==t||!iS(r))return;const e={};for(const[t,n]of Object.entries(r)){if(!aS(t)||"string"!=typeof n||0===n.length)return;e[t]=n}if(0===Object.keys(e).length)return;return{appSelectorArgs:e,capturesScreen:n}}return void 0===t?{capturesScreen:n}:"string"==typeof t&&t.length>0?{appArg:t,capturesScreen:n}:void 0}}const lS=["pid","bundleId","path","appName"],uS=/^[+-]?\d+$/;var dS=r("../../node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/create.js");const hS=".cursor/worktrees",pS=".grok/build-desktop/worktrees",fS="win32"===process.platform||"darwin"===process.platform,mS=new Map;function gS(e,t){if(!(0,ts.BJ)(t,e))return;const r=(fS?(0,s.relative)(e.toLowerCase(),t.toLowerCase()):(0,s.relative)(e,t)).split(s.sep).filter(Boolean);return r.length>0?r:void 0}function wS(e,t){const r=gS(e,t);if(void 0!==r)return r;const n=function(e){if(mS.has(e))return mS.get(e);const t=[];let r,n=e;for(;;)try{const e=Ro.realpathSync.native(n);r=0===t.length?e:(0,s.join)(e,...t);break}catch(e){const r=_c(e);if("ENOENT"!==r&&"ENOTDIR"!==r)break;const o=(0,s.dirname)(n);if(o===n)break;t.unshift((0,s.basename)(n)),n=o}return mS.size>=64&&mS.clear(),mS.set(e,r),r}(e);var o,i;return void 0!==n&&(o=n,i=e,fS?o.toLowerCase()!==i.toLowerCase():o!==i)?gS(n,t):void 0}function yS(e){const t=e?.trim();return t&&".cursor"!==t?[".cursor",t]:[".cursor"]}function vS(e,t){const r=(0,o.homedir)();return yS(t?.dataFolderName).some((t=>void 0!==wS((0,s.join)(r,t,"projects"),e)))}function bS(e){const t=(0,o.homedir)();return[hS,pS].some((r=>void 0!==wS((0,s.join)(t,...r.split("/")),e)))}function SS(e,t,r){const n=function(e,t){const r=(0,o.homedir)();for(const n of yS(t?.dataFolderName)){const t=wS((0,s.join)(r,n,"projects"),e);if(void 0!==t&&t.length>=2)return t[1]}}(e,r);return void 0!==n&&(fS?t.some((e=>e.toLowerCase()===n.toLowerCase())):t.includes(n))}function kS(e,t,r){const n=wS(e,t);if(void 0===n)return!1;const o=n[0];return fS?r.some((e=>e.toLowerCase()===o.toLowerCase())):r.includes(o)}const _S=/[\s"'`=/\\:;()[\]{},&|<>]/,CS="win32"===process.platform||"darwin"===process.platform;async function ES(e,t,r,n){const o=AS(await TS((0,s.join)(e,"gitdir")),"");if(void 0===o)return;const i=(0,s.resolve)(e,o);if(".git"!==(0,s.basename)(i)||(0,Gs.$f)(i))return;const a=(0,s.dirname)(i);if(r&&bS(a))return;const c=await $S(i);if(void 0===c)return;const l=(0,s.dirname)(c);if(r&&bS(l))return;if(void 0!==n&&(u=DS(a,l)?[l]:[a,l],d=n.command,!(void 0!==(h=n.realWorkingDirectory)&&u.some((e=>(0,ts.BJ)(h,e)))||void 0!==d&&u.some((e=>{const t=(0,s.basename)(e);return t.length>0&&function(e,t){const r=CS?e.toLowerCase():e,n=CS?t.toLowerCase():t;let o=0;for(;;){const e=r.indexOf(n,o);if(-1===e)return!1;const t=0===e||_S.test(r[e-1]),s=e+n.length,i=s===r.length||_S.test(r[s]);if(t&&i)return!0;o=e+1}}(d,t)})))))return;var u,d,h;const p=await IS(i,c);return void 0!==p&&DS(p.commonDir,t)?l:void 0}async function xS(e,t){const r=await(0,xo.readdir)(e).catch(MS);return void 0===r?[]:r.sort().slice(0,t)}function PS(e,t){return t.some((t=>(0,ts.BJ)(t,e)))}async function RS(e){for(let t=e;;t=(0,s.dirname)(t)){if((0,Gs.$f)(t))return;const e=(0,s.join)(t,".git"),r=await(0,xo.lstat)(e).catch(MS);if(r?.isFile())return(await IS(e))?.commonDir;if(r?.isDirectory())return e;if(void 0!==r||(0,s.dirname)(t)===t)return}}async function IS(e,t){const r=AS(await TS(e),"gitdir: ");if(void 0===r)return;const n=await $S((0,s.resolve)((0,s.dirname)(e),r));if(void 0===n||"worktrees"!==(0,s.basename)((0,s.dirname)(n)))return;const o=(0,s.dirname)((0,s.dirname)(n));if(".git"!==(0,s.basename)(o))return;const i=AS(await TS((0,s.join)(n,"commondir")),"");if(void 0===i)return;const a=await $S((0,s.resolve)(n,i));if(void 0===a||!DS(a,o))return;const c=AS(await TS((0,s.join)(n,"gitdir")),"");if(void 0===c)return;const[l,u]=await Promise.all([$S((0,s.resolve)(n,c)),t??$S(e)]);return void 0!==l&&void 0!==u&&DS(l,u)?{commonDir:o,realDotGit:u}:void 0}async function TS(e){const t=await(0,xo.lstat)(e).catch(MS);if(void 0!==t&&t.isFile()&&!(t.size>4096))return(0,xo.readFile)(e,"utf8").catch(MS)}function AS(e,t){const r=e?.split("\n",1)[0]?.replace(/\r$/,"");if(void 0===r||!r.startsWith(t))return;const n=r.slice(t.length);return n.length>0&&!n.includes("\0")?n:void 0}async function $S(e){if(!(0,Gs.$f)(e))return(0,xo.realpath)(e).catch(MS)}function MS(e){const t=_c(e);if(void 0===t||t.startsWith("ERR_"))throw e}function DS(e,t){return CS?e.toLowerCase()===t.toLowerCase():e===t}function OS(e,t,r){return{resolvedPath:e,originalPath:t,resolution:r}}function FS(e){const t=_c(e);switch(t){case"ENOENT":return{status:"newFile"};case"EACCES":case"EPERM":return{status:"permissionDenied",errno:t};case"ELOOP":return{status:"symlinkLoop",errno:t};default:return{status:"unknownError",errno:t??"UNKNOWN",message:Cc(e)}}}async function NS(e,t){const r=(0,ts.o1)(e,t);try{return OS(await(0,xo.realpath)(r),r,{status:"resolved"})}catch(e){if("ENOENT"!==_c(e))return OS(r,r,FS(e));try{if((await(0,xo.lstat)(r)).isSymbolicLink()){let e=null;try{e=await(0,xo.readlink)(r)}catch{}return OS(r,r,{status:"danglingSymlink",symlinkTarget:e})}try{return OS(await(0,xo.realpath)(r),r,{status:"resolved"})}catch(e){if("ENOENT"!==_c(e))return OS(r,r,FS(e))}return OS(r,r,{status:"unknownError",errno:"ENOENT",message:"realpath returned ENOENT but lstat found a non-symlink entry"})}catch(e){return"ENOENT"===_c(e)?async function(e){let t=(0,s.dirname)(e);const r=[(0,s.basename)(e)];for(;(0,s.dirname)(t)!==t;){try{const n=await(0,xo.realpath)(t);return OS((0,s.join)(n,...r),e,{status:"newFile"})}catch(t){if("ENOENT"!==_c(t))return OS(e,e,FS(t))}r.unshift((0,s.basename)(t)),t=(0,s.dirname)(t)}return OS(e,e,{status:"newFile"})}(r):OS(r,r,FS(e))}}}function LS(e){return"resolved"===e.status||"newFile"===e.status}function jS(e,t){switch(t.status){case"resolved":case"newFile":return"";case"danglingSymlink":return`Write blocked: \`${e}\` is a dangling symlink${t.symlinkTarget?` (target: ${t.symlinkTarget})`:""}. Cannot verify it does not point to a protected file.`;case"permissionDenied":return`Write blocked: cannot verify \`${e}\` -- permission denied resolving symlinks (${t.errno}).`;case"symlinkLoop":return`Write blocked: \`${e}\` has a symlink loop (${t.errno}). Cannot verify target.`;case"unknownError":return`Write blocked: cannot verify \`${e}\` -- ${t.errno}: ${t.message}.`;default:return`Write blocked: unknown resolution status for \`${e}\`.`}}function US({realAbsolutePath:e,setting:t,resolvedWorkspaceRoots:r,resolvedAllowFolders:n,resolvedAllowGlobs:o}){return!("workspace"!==t.boundary||BS(e,r)||BS(e,n)||HS(e,t.allowPaths)||HS(e,o))}function BS(e,t){return t.some((t=>(0,ts.BJ)(e,t)))}function WS(e){return e.flatMap((e=>{const t=(0,ts.jl)(e.trim());return!t.includes("*")&&(0,s.isAbsolute)(t)?[(0,s.resolve)(t)]:[]}))}function HS(e,t){const r="win32"===process.platform?ts.oL:e=>e,n=r(e);return t.some((e=>{const t=(0,ts.jl)(e.trim());return!(!t.includes("*")&&(0,s.isAbsolute)(t))&&(0,ws.T)(r(t),n)}))}const qS={caffeinate:{flags:["-d","-i","-m","-s","-u"],valueOptions:["-t","-w"]},command:{flags:["-p"],valueOptions:[],lookupFlags:["-v","-V"]},env:{flags:["-","-i","-0","-v","--ignore-environment","--null","--debug"],valueOptions:["-u","-C","--unset","--chdir"],assignments:!0,directoryOptions:["-C","--chdir"]},nice:{flags:[],valueOptions:["-n","--adjustment"],numericOption:!0},nohup:{flags:[],valueOptions:[]},stdbuf:{flags:[],valueOptions:["-i","-o","-e","--input","--output","--error"]},time:{flags:["-p"],valueOptions:[]},timeout:{flags:["-f","-p","-v","--foreground","--preserve-status","--verbose"],valueOptions:["-k","-s","--kill-after","--signal"],operands:1},xargs:{flags:["-0","-o","-p","-r","-t","-x","--null","--open-tty","--interactive","--no-run-if-empty","--verbose","--exit","--show-limits"],valueOptions:["-a","-d","-E","-I","-J","-L","-n","-P","-R","-S","-s","--arg-file","--delimiter","--max-args","--max-procs","--max-chars","--process-slot-var"],attachedValueOptions:["-e","-i","-l","--eof","--replace","--max-lines"],readsArguments:!0}};function zS(e){const t=[];let r=!0,n=!1,o=e;for(;;){const e=qS[s.posix.basename(o.name)];if(void 0===e)return{command:o,wrapperForms:t,allowlistable:r,readsArguments:n};const i=GS(o.args,e);if("unreadable"===i)return{command:o,wrapperForms:t,allowlistable:!1,readsArguments:n};if("none"===i)return{command:o,wrapperForms:t,allowlistable:r,readsArguments:n};const[a,...c]=o.args.slice(i);if(void 0===a||!XS(a))return{command:o,wrapperForms:t,allowlistable:!1,readsArguments:n};(o.name.includes("/")||o.args.slice(0,i).some((t=>VS(t,e)||KS(t.value,e))))&&(r=!1),n||=!0===e.readsArguments,t.push(o.fullText.trim()),o=new fe.Pv({name:a.value,args:c,fullText:[a.value,...c.map((e=>e.value))].join(" ")})}}function GS(e,t){let r=0;for(;rt.startsWith("--")?e===t||e.startsWith(`${t}=`):/^-[^-]/.test(e)&&e.includes(t.slice(1))))}function JS(e,t,r){const n=e=>!0===r.attachedValueOptions?.includes(e);if(r.flags.includes(e)||n(e))return 1;if(e.startsWith("--")){const o=e.indexOf("=");if(-1!==o){const t=e.slice(0,o);return r.valueOptions.includes(t)||n(t)?1:void 0}if(!r.valueOptions.includes(e))return;return void 0===t?void 0:2}for(let o=1;o{const t=await NS(e);return LS(t.resolution)?t.resolvedPath:(0,ts.o1)(e)})))}function pk(e,t,r){return`${e} blocked: cannot verify ${t} \`${r}\` while resolving symlinks. This can happen when access is denied or the path contains a symlink loop.`}function fk(e){return[...new Set(e)]}function mk(){return{fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}}function gk({basePath:e,targetPath:t,pathModule:r}){const n=r.resolve(e),o=r.resolve(t),s=r.relative(n,o);return""===s||".."!==s&&!s.startsWith(`..${r.sep}`)&&!r.isAbsolute(s)}function wk(e){return">"===e||">>"===e||">|"===e||"&>"===e||"&>>"===e}function yk(e){return"<"!==e.operator&&"<&"!==e.operator}function vk(e){if(void 0===e||e.trim()!==e)return;const t=Number(e);return Number.isInteger(t)&&t>=0?t:void 0}function bk(e){return"<<"===e.operator&&"heredoc_redirect"===e.targetNodeType&&1===e.destinationFds.length&&0===Number(e.destinationFds[0])&&void 0!==e.targetText}function Sk(e,t){return!(/^=|[~*?[{(#^`]/.test(e)||"\\"!==t.sep&&e.includes("\\"))}function kk(e){return"word"===e.type||"number"===e.type?Sk(e.value,i)?e.value:void 0:"raw_string"===e.type||"string"===e.type&&!/[$`\\]/.test(e.value)?e.value.slice(1,-1):void 0}function _k({command:e,readsArguments:t}){if(!function(e){const t=e.replace(/["']/g,"");return[t,t.replace(/\\/g,"")].some((e=>/^tee(?:-object)?(?:\.exe)?$/i.test(e.slice(Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"))+1))))}(e.name))return[];const r=e.args.map(kk);return t?[...r,void 0]:r}const Ck=new Set(["cd","chdir","pushd"]),Ek=new Set(["popd","eval","source",".","trap","set-location","sl","push-location","pop-location"]);function xk(e){const t=e.replace(/["'\\]/g,"");return t.slice(t.lastIndexOf("/")+1).toLowerCase()}function Pk(e,t){return new fe.Pv({name:e,args:t,fullText:[e,...t.map((e=>e.value))].join(" ")})}function Rk(e){let t=e;for(;;){const e=xk(t.name);if("command"===e){const e=Pk("command",t.args),r=zS(e).command;if(r!==e){t=r;continue}const n=t.args[0]?.value;return void 0===n||"-v"===n||"-V"===n?t:"unreadable"}if("builtin"!==e)return t;const r="--"===t.args[0]?.value?t.args.slice(1):t.args,[n,...o]=r;if(void 0===n)return t;const s=kk(n);if(void 0===s||s.startsWith("-"))return"unreadable";t=Pk(s,o)}}function Ik(e,t){return!(!t.isAbsolute(e)||"/"!==t.sep&&/^[\\/]$/.test(t.parse(e).root))}async function Tk({parsingResult:e,workingDirectory:t,resolvePathForPermissions:r,pathModule:n}){const o=[t];for(const t of e.executableCommands.map(zS)){const e=Rk(t.command);if("unreadable"===e)return;const i=xk(e.name),a=e.args;if(Ek.has(i)||/^cd\.\./.test(s=i)||/^[a-z]:$/.test(s))return;if(!Ck.has(i))continue;const c=1===a.length&&void 0!==a[0]?kk(a[0]):void 0;if(void 0===c||!Ik(c,n))return;const l=await r(c);if(!LS(l.resolution))return;o.push(l.resolvedPath)}var s;return o}async function Ak({targetText:e,workingDirectory:t,workingDirectories:r,...n}){const o=Ik(e,n.pathModule)?[t]:r;if(void 0===o)return;let s;for(const t of o)if(s=await $k({...n,targetText:e,workingDirectory:t}),void 0===s)return;return s}async function $k({targetText:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:o,pathModule:s,tempPathOptions:i}){if(""!==s.parse(e).root&&!s.isAbsolute(e))return;const a=await o(e,t);if(!LS(a.resolution))return;const c=[];for(const e of r){const t=await o(e);LS(t.resolution)&&c.push(t.resolvedPath)}return await async function({targetPath:e,rootPaths:t,pathModule:r}){if(e.split(r.sep).some((e=>".git"===e.toLowerCase())))return!0;for(const r of t)if(await(0,No.OK)(e,r).catch((()=>!0)))return!0;return!1}({targetPath:a.resolvedPath,rootPaths:c,pathModule:s})?void 0:c.some((e=>gk({basePath:e,targetPath:a.resolvedPath,pathModule:s})))?"workspace-file":n&&!(0,No.dA)(a.originalPath)&&zk(a.resolvedPath,i)?"tmp-file":void 0}async function Mk({parsingResult:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n}){const s=await Tk({parsingResult:e,workingDirectory:t,resolvePathForPermissions:NS,pathModule:i});for(const a of e.executableCommands.map(zS).flatMap(_k))if("/dev/null"!==a&&(void 0===a||!await Ak({targetText:a,workingDirectory:t,workingDirectories:s,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:NS,pathModule:i,tempPathOptions:{platform:process.platform,env:process.env,pathModule:i,homeDirectory:(0,o.homedir)()}})))return!1;return!0}function Dk(e){return fk(e.map((e=>e.trim())).filter(Boolean))}function Ok(e){const t=e.name.trim();if(!t)return[];const r=e.arguments.map((e=>e.trim())).filter(Boolean),n=r.length>0?`${t} ${r.join(" ")}`:t,o=e.subcommandTokens.map((e=>e.trim())).filter(Boolean);if(0===o.length)return[n];const s=`${t} ${o.join(" ")}`;return s===n?[n]:[n,s]}function Fk(e,t){const r=t.trim();return!!r&&e.some((e=>e===r||e.startsWith(`${r} `)))}function Nk(e){const t=e.name.trim(),r=e.arguments.map((e=>e.trim())).filter(Boolean).map((e=>new fe.r6({type:"word",value:e})));return new fe.Pv({name:t,args:r,fullText:[t,...r.map((e=>e.value))].join(" ").trim()})}function Lk(e,t={}){return{type:e,...t}}function jk(e){return void 0!==e&&("deny"===e.default||void 0!==e.allow&&e.allow.length>0||void 0!==e.deny&&e.deny.length>0)}function Uk(...e){return e.filter((e=>void 0!==e)).join(" • ")}function Bk(e){const t=[];for(const r of e){const e=r.match(/^\s*Read\s*\((.*)\)\s*$/);e&&t.push((e[1]??"").trim())}return t}function Wk(e,t){if("workspace"===e&&void 0!==t)return t}const Hk={workspace:0,system:1};function qk(e){const t=e.match(/^\s*(Shell|Bash)\s*\((.*)\)\s*$/);if(!t)return null;const r=t[1];if("Shell"!==r&&"Bash"!==r)return null;const n=t[2]?.trim()??"",o=n.indexOf(":");return-1!==o?{shellType:r,fullPattern:n,commandPattern:n.slice(0,o).trim(),argsPattern:n.slice(o+1).trim()}:{shellType:r,fullPattern:n,commandPattern:n,argsPattern:null}}function zk(e,{platform:t,env:r,pathModule:n,homeDirectory:o}){if((0,No.dA)(e))return!1;if("win32"===t){const t=r.TEMP??r.TMP;if(t){const r=n.normalize(t).toLowerCase(),o=n.normalize(e).toLowerCase(),s=r.endsWith(n.sep)?r:r+n.sep;return o===r||o.startsWith(s)}return!1}const s=e=>{const r=n.normalize(e);return"darwin"!==t?r:"/tmp"===r||r.startsWith("/tmp/")||"/var"===r||r.startsWith("/var/")?`/private${r}`:r},i=s(e);return(void 0===o||!gk({basePath:s(o),targetPath:i,pathModule:n}))&&("darwin"===t?["/private/tmp/","/private/var/folders/"].some((e=>i.startsWith(e))):["/tmp/","/private/tmp/","/var/folders/","/private/var/folders/","/var/tmp/"].some((e=>i.startsWith(e))))}function Gk(e,t){if("insecure_none"===t.type)return!0;if("insecure_none"===e.type)return!1;const r=(0,No.$b)(e.networkPolicy),n=(0,No.$b)(t.networkPolicy);if(r&&!n)return!1;const o=(0,No._B)(e.networkPolicy),s=(0,No._B)(t.networkPolicy);if(o&&n&&!s)return!1;if("workspace_readonly"===e.type&&"workspace_readwrite"===t.type)return!0;if("workspace_readwrite"===e.type&&"workspace_readonly"===t.type)return!1;const i=e.readBoundary??"system",a=t.readBoundary??"system";return!(Hk[i]>Hk[a])}function Vk(e){return{wrapperForms:e.flatMap((e=>e.wrapperForms)),allowlistable:e.every((e=>e.allowlistable)),readsArguments:e.some((e=>e.readsArguments))}}function Kk(e){return[...e.wrapperForms,e.command.fullText.trim()].filter(Boolean)}class Jk{constructor(e,t,r,n,o){this.command=e,this.requestedPolicy=t,this.wrapperForms=o?.wrapperForms??[],this.allowlistable=o?.allowlistable??!0,this.readsArguments=o?.readsArguments??!1;const s=void 0!==r&&Gk(t,r);this.state=s?"preapproved":"approvable";const i=[e.fullText.trim()].filter(Boolean);this.matchForms=n&&n.length>0?[...n]:i}approveWithPolicy(e){"approvable"!==this.state&&"preapproved"!==this.state||!Gk(this.requestedPolicy,e)||(this.state="allowlisted")}deny(){this.state="denied"}isRunnable(){return"preapproved"===this.state||"allowlisted"===this.state}}function Zk(e){return e?.type??"undefined"}const Xk=["skills","skills-cursor","rules","plugins"],Qk=["assets","agent-notes","agent-tools","swarm-agents"];async function Yk(e,t,r){return e.shouldBlockFileRead?.(t,r)??e.shouldBlockRead(t,r)}function e_(e){const t=e.lastIndexOf("::mcpScope:");return-1===t?e:e.slice(0,t)}function t_({server:e,tool:t}){const r=e=>e.length>0&&e.length<=256&&!/[:*]/.test(e),n=e.trim().toLowerCase(),o=t.trim().toLowerCase();return r(n)&&r(o)?`${n}:${o}`:void 0}const r_=/^\s*Read\s*\((.*)\)\s*$/,n_=/^\s*Write\s*\((.*)\)\s*$/;class o_{constructor(e,t,r,n,i,a=!1,c){this.ignoreService=e,this.pendingDecisionStore=t,this.permissionsProvider=r,this.teamSettingsService=n,this.adminNetworkControlsEnabled=a,this.computerUseAppsAllowedForSession=[],this.rootDirectories=Array.isArray(i)?i:[i??process.cwd()],this.projectDir=c?.projectDir,this.perUserSandboxConfigPath=c?.perUserSandboxConfigPath??(0,s.join)((0,o.homedir)(),".cursor","sandbox.json"),this.mcpAllowlistLog=c?.mcpAllowlistLog,this.computerUse=c?.computerUse,this.computerUseAdminPolicy=c?.computerUseAdminPolicy,this.enforceMcpAdminToolLimits=c?.enforceMcpAdminToolLimits,this.onMcpAdminToolLimitCheck=c?.onMcpAdminToolLimitCheck}async shouldBlockRead(e,t={}){return this.shouldBlockReadInternal(e,t,!1)}async shouldBlockFileRead(e,t={}){return this.shouldBlockReadInternal(e,t,!0)}async getFileReadBoundaryBlocker(){const{perms:e,setting:t}=await this.readControlSetting(),r=e.deny.filter((e=>this.isPathEntry("Read",e))),n="workspace"===t.boundary&&"unrestricted"!==e.approvalMode;if(!n&&0===r.length)return;const[o,s,i]=n?await Promise.all([this.resolveWorkspaceReadRoots(e.userSandboxDataFolderName),this.resolvedReadAllowFolders(t.allowPaths),this.resolvedReadAllowGlobs(t.allowPaths)]):[[],[],[]],a=r.map((e=>this.compileReadDenyMatcher(e))),c=e=>a.some((t=>t(e)));return async(e,r)=>c(e)||c(r)||n&&US({realAbsolutePath:r,setting:t,resolvedWorkspaceRoots:o,resolvedAllowFolders:s,resolvedAllowGlobs:i})}async readControlSetting(){const e=await this.getPermissions(),{enabled:t,...r}=await this.adminReadControls(e);return{perms:e,setting:function(e){if(!e.enabled)return{boundary:"system",allowPaths:[],enforcedByAdmin:!1};const t="workspace"===e.admin.boundary,r=t||"workspace"===e.local.boundary?"workspace":"system",n=t?e.admin.allowPaths:[];return{boundary:r,allowPaths:t&&!1===e.admin.allowUserOverride?[...n]:[...new Set([...n,...e.local.allowPaths])],enforcedByAdmin:t}}({enabled:t,admin:r,local:{boundary:e.readBoundary,allowPaths:Bk(e.allow)}})}}async adminReadControls(e){const t=e.teamAdminPolicy,r=this.teamSettingsService.isReadControlEnabled?.()??!0;if(void 0!==t&&"unavailable"!==t){const e=await r;return"workspace"!==t.readBoundary?{enabled:e,boundary:void 0,allowPaths:[],allowUserOverride:void 0}:{enabled:e,boundary:"workspace",allowPaths:t.additionalReadPaths??[],allowUserOverride:t.allowUserOverrideReadPaths}}const[n,o]=await Promise.all([r,this.teamSettingsService.getSandboxingControls()]);return{enabled:n,boundary:o.readBoundary,allowPaths:o.readAllowlistPaths??[],allowUserOverride:o.allowUserOverrideReadAllowlist}}resolvedReadAllowFolders(e){return hk([...WS(e),...(0,No.r5)()])}async resolvedReadAllowGlobs(e){const t=function(e){return e.flatMap((e=>{const t=(0,ts.jl)(e.trim()),r=t.indexOf("*");if(r<0||!(0,s.isAbsolute)(t))return[];const n="win32"===process.platform?Math.max(t.lastIndexOf("/",r),t.lastIndexOf("\\",r)):t.lastIndexOf("/",r);return n>=(0,s.parse)(t).root.length?[{folder:t.slice(0,n),rest:t.slice(n)}]:[]}))}(e),r=await hk(t.map((({folder:e})=>e)));return t.map((({rest:e},t)=>function(e,t,r={parse:s.parse}){return r.parse(e).root===e&&/[\\/]$/.test(e)?`${e}${t.slice(1)}`:`${e}${t}`}(r[t],e)))}async resolveWorkspaceReadRoots(e){const t=(0,s.join)((0,o.homedir)(),void 0!==e&&e.length>0?e:".cursor"),r=[...this.rootDirectories.map((e=>(0,s.join)(t,"projects",(0,_o.r_)(e)))),...Xk.map((e=>(0,s.join)(t,e)))],n=this.rootDirectories.flatMap((e=>(0,No.W1)(e)??[]));return hk([...this.rootDirectories,...r,...n,...void 0===this.projectDir?[]:[this.projectDir]])}async shouldBlockReadInternal(e,{cursorIgnoreChecked:t=!1},r){const n=(0,ts.o1)(e),o=await xc(n);if(null===o)return{type:"unsafeResolution",message:pk("Read","path",n)};if(await this.ignoreService.isRepoBlocked(o))return{type:"adminBlock",source:"Team repo blocklist"};if(await this.isPathExplicitlyDenied("Read",n))return{type:"permissionsConfig"};if(!t&&!bS(o)&&!vS(o,{dataFolderName:(await this.getPermissions()).userSandboxDataFolderName})&&await this.ignoreService.isCursorIgnored(o))return{type:"cursorIgnore"};if(r){const e=await this.shouldBlockReadForBoundary(o);if(e)return e}return!1}async shouldBlockReadForBoundary(e){const{perms:t,setting:r}=await this.readControlSetting();if("workspace"!==r.boundary||"unrestricted"===t.approvalMode)return!1;const n=await this.resolveWorkspaceReadRoots(t.userSandboxDataFolderName);if(BS(e,n))return!1;const[o,s]=await Promise.all([this.resolvedReadAllowFolders(r.allowPaths),this.resolvedReadAllowGlobs(r.allowPaths)]);return!!US({realAbsolutePath:e,setting:r,resolvedWorkspaceRoots:n,resolvedAllowFolders:o,resolvedAllowGlobs:s})&&{type:"needsApproval",approvalReason:r.enforcedByAdmin?"This reads a file outside your workspace and requires approval under your team's read policy.":"This reads a file outside your workspace.",approvalDetails:{type:"fileRead",path:e}}}async isProjectDirInternalPath(e,t){if(void 0===this.projectDir)return!1;const r=await NS(this.projectDir);return!!LS(r.resolution)&&kS(r.resolvedPath,e,t)}async isFreelyWritableOutsideWorkspace(e,t){return function(e){return zk(e,{platform:process.platform,env:process.env,pathModule:i,homeDirectory:(0,o.homedir)()})}(e)||SS(e,Qk,{dataFolderName:t})||await this.isProjectDirInternalPath(e,Qk)}async shouldBlockWrite(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{tk(n,(0,D.VI)(e.withName("InteractivePermissionsService.shouldBlockWrite")),!1).ctx;const i=await NS(t);if(!LS(i.resolution))return{type:"unsafeResolution",message:jS(i.originalPath,i.resolution)};const a=i.resolvedPath,c=a;if(await this.ignoreService.isRepoBlocked(c))return{type:"adminBlock",source:"Team repo blocklist"};if(await this.isPathExplicitlyDenied("Write",a))return{type:"permissionsConfig"};const l=i.originalPath.split(s.sep).pop()?.toLowerCase()??"",u=a.split(s.sep).pop()?.toLowerCase()??"";if(".cursorignore"===l||".cursorignore"===u)return{type:"permissionsConfig"};if((0,No.dA)(i.originalPath)||(0,No.dA)(a))return{type:"permissionsConfig"};const d=await this.getPermissions();if(!bS(c)&&!vS(c,{dataFolderName:d.userSandboxDataFolderName})&&await this.ignoreService.isCursorIgnored(c))return{type:"cursorIgnore"};if("workspace_readonly"===d.userConfiguredPolicy.type)return{type:"permissionsConfig",isReadonly:!0};if(await this.isPathExplicitlyAllowed("Write",a))return!1;if("unrestricted"===d.approvalMode)return!1;const h=async()=>{let e,t,n="";try{n=await Bi(a),e=!1}catch{e=!0}if(e)t=r;else{const e=e=>e.endsWith("\n")?e:`${e}\n`,{hunks:o}=(0,dS.YB)("a","b",e(n),e(r),"","",{context:2});t=o.map((e=>e.lines.map((e=>e.length>0?`${e[0]} ${e.slice(1)}`:e)).join("\n"))).join("\n...\n")}return{isNewFile:e,diffString:t}};let p;const f=[];for(const e of this.rootDirectories){const t=await NS(e);if(LS(t.resolution)){if((0,ts.BJ)(a,t.resolvedPath)){p=t.resolvedPath;break}f.push(t.resolvedPath)}}const m=void 0===p?await async function(e,t,r={}){if(0===t.length)return;let n;for(let o=(0,s.dirname)(e);;o=(0,s.dirname)(o)){if((0,Gs.$f)(o))return;const e=(0,s.join)(o,".git"),i=await(0,xo.lstat)(e).catch(MS);if(i?.isFile()){const s=await IS(e);if(void 0!==s){const{commonDir:e}=s;if(PS(o,t))return;if(t.some((t=>(0,ts.BJ)(e,t))))return{root:o,commonDir:e};if(!await(r.isUntrustedExternalGitDir?.(e))&&(await(n??=Promise.all(t.map((e=>RS(e)))),n)).some((t=>void 0!==t&&DS(t,e))))return{root:o,commonDir:e}}}if((0,s.dirname)(o)===o)return}}(a,f,{isUntrustedExternalGitDir:e=>this.isFreelyWritableOutsideWorkspace(e,d.userSandboxDataFolderName)}):void 0;let g=!1;const w=p??m?.root;if(void 0!==w){const e=(0,s.relative)(w,a),t=e.split(s.sep).map((e=>"win32"===process.platform&&e.includes(":")?e.split(":")[0]:e));if(g=function(e){const t=e.replace(/\\/g,"/");return/(^|\/)\.cursor\/debug(?:-[a-zA-Z0-9-]+)?\.log$/i.test(t)}(e),!g){const e=await this.checkCursorFileProtection(t);if(e)return e}if("win32"===process.platform&&t.some((e=>e.includes("~")))){const{isNewFile:e,diffString:r}=await h();return{type:"needsApproval",approvalReason:`Protected config file: ${t[t.length-1]??""}`,approvalDetails:{type:"fileEdit",isNewFile:e,diffString:r,blockReason:"protectedConfig"}}}if(await(0,No.OK)(a,w)){const e=t[t.length-1]?.toLowerCase()??"",{isNewFile:r,diffString:n}=await h();return{type:"needsApproval",approvalReason:`Protected config file: ${e}`,approvalDetails:{type:"fileEdit",isNewFile:r,diffString:n,blockReason:"protectedConfig"}}}}if(void 0===p&&(void 0===m||"workspace"===(await this.readControlSetting()).setting.boundary)){if(await this.isFreelyWritableOutsideWorkspace(a,d.userSandboxDataFolderName))return!1;const e=`${(0,o.homedir)()}${s.sep}.cursor${s.sep}`;if(a.startsWith(e)){const e=a.split(s.sep).pop()?.toLowerCase()??"";if(e.endsWith(".md")||e.endsWith(".mdc")||".cursorrules"===e)return!1}const{isNewFile:t,diffString:r}=await h();return{type:"needsApproval",approvalReason:"Out of workspace",approvalDetails:{type:"fileEdit",isNewFile:t,diffString:r,blockReason:"outOfWorkspace"}}}if(g)return!1;if(!0===d.promptWorkspaceWrites){const{isNewFile:e,diffString:t}=await h();return{type:"needsApproval",approvalReason:"Workspace write",approvalDetails:{type:"fileEdit",isNewFile:e,diffString:t,blockReason:"workspaceWrite"}}}return!1}catch(e){n.error=e,n.hasError=!0}finally{rk(n)}}async shouldEnforceShellInvariantBlocks(e,t,r){const n=await this.getAdminCommandDenylistBlock(e,{command:t.command,parsingResult:t.parsingResult,toolCallId:t.toolCallId});if(void 0!==n)return{kind:"block",reason:n};const o=await xc(t.workingDirectory);if(null===o){if(!0!==t.skipUnsafeWorkingDirectoryBlock)return{kind:"block",reason:{type:"unsafeResolution",message:pk("Command","working directory",t.workingDirectory)}}}else if(await this.ignoreService.isRepoBlocked(o))return{kind:"block",reason:{type:"adminBlock",source:"Team repo blocklist"}};const s=(await this.getPermissions()).userConfiguredPolicy,i=r??s;return"workspace_readonly"===s.type&&"workspace_readonly"!==i.type?{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}}:void 0!==r?{kind:"allow",policy:r}:!0!==t.resolveSkippedApprovalPolicy||"workspace_readonly"!==s.type?{kind:"allow",policy:void 0}:{kind:"allow",policy:await this.applyServerAndAdminPolicies({...s,skipStatsigDefaults:s.skipStatsigDefaults??!0})}}async shouldBlockShellCommand(e,t,r,n){const o="insecure_none"===n?.type,s=await this.shouldEnforceShellInvariantBlocks(e,{workingDirectory:r.workingDirectory,command:t,parsingResult:r.parsingResult,toolCallId:r.toolCallId},n);if("block"===s.kind)return s;const i=await this.getPermissions(),a=i.approvalMode,c="unrestricted"===a,l=i.userConfiguredPolicy,u=!i.dashboardTerminalAllowlistOverriddenByPermissionsFile;if(nk.info(e,"Shell permissions: evaluating shell command",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:Zk(l),requestedPolicyType:Zk(n),effectiveRequestedPolicyType:Zk(n??l),smartAllowlistEnabled:!0===i.smartAllowlistEnabled,hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId,hookForcesPrompt:Do(r.hookApprovalRequirement),classifierClassificationFailed:!0===r.classifierResult?.classificationFailed,classifierCommandCount:r.classifierResult?.commands.length??0,parserCommandCount:r.parsingResult.executableCommands.length,parsingFailed:r.parsingResult.parsingFailed,hasRedirects:r.parsingResult.hasRedirects,commandLength:t.length}),await this.shouldPromptForEmptyPlainShellAllowlist(t,i))return nk.info(e,"Shell permissions: prompting for empty allowlist",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:Zk(l),requestedPolicyType:Zk(n),hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId}),await this.requestApprovalForEmptyShellAllowlist(t,r,n??l);const d=r.parsingResult.executableCommands,h=r.parsingResult.parsingFailed,p=r.classifierResult,f=r.smartModeApprovalReason,m=r.smartModeApprovalRequestId,g=void 0!==p&&!p.classificationFailed&&p.commands.length>0?p:void 0,w="allowlist"===a&&i.smartAllowlistEnabled?g?.commands:void 0,y=void 0!==w,v=d.map(zS),b=w?w.map(Nk):v.map((e=>e.command)),S=void 0!==w?w.map(Ok):b.map((e=>[e.fullText.trim()].filter(Boolean))),k=void 0!==g?g.commands.map(Ok):v.map(Kk);if(n||(n=i.userConfiguredPolicy),"insecure_none"!==n.type&&void 0===n.skipStatsigDefaults&&"insecure_none"!==l.type&&(n={...n,skipStatsigDefaults:l.skipStatsigDefaults??!0}),"insecure_none"!==l.type&&(0,No.$b)(l.networkPolicy)&&"insecure_none"!==n.type&&!(0,No._B)(n.networkPolicy)){const e=l.networkPolicy,t=n.networkPolicy?.allow;if(void 0!==t&&t.length>0&&e){const r=[...new Set([...e.allow??[],...t])];n={...n,networkPolicy:{...e,allow:r}}}else n={...n,networkPolicy:e}}let _;n=function({requestedPolicy:e,userConfiguredPolicy:t}){if("insecure_none"===e.type||"insecure_none"===t.type)return e;const r=(0,No.XX)(e.readBoundary,t.readBoundary),n="workspace"===r?(0,No.wG)(Wk(e.readBoundary,e.additionalReadPaths),Wk(t.readBoundary,t.additionalReadPaths)):void 0;return{...e,readBoundary:r,additionalReadPaths:n}}({requestedPolicy:n,userConfiguredPolicy:l}),p&&nk.info(e,"Smart allowlist: classifier result received",{classificationFailed:p.classificationFailed,suggestedSandboxMode:p.suggestedSandboxMode,commandCount:p.commands.length,suggestedAllowlistEntryCount:p.commands.filter((e=>e.suggestedAllowlistEntry)).length});const C=[],E=[];let x=[],P=[],R=[];const I=Dk(i.smartAllowlistDenylist??[]);if(I.length>0){P=[];const t=k.map((e=>e[0]??""));for(let e=0;eFk(r,e)))){const r=t[e];r&&P.push(r)}}P.length>0&&(nk.info(e,"Command blocklist: commands require approval",{count:P.length}),C.push(`In blocklist: ${P.join(", ")}`))}if(y&&p){const t=S.map((e=>e[0]??"")),r=i.allow.filter((e=>this.isShellEntry(e)));nk.info(e,"Smart allowlist: checking commands against lists",{commandCount:t.length,allowlistCount:r.length,commandBlocklistCount:I.length});const n=S.map((e=>r.some((t=>e.some((e=>this.matchesShell(t,e))))))),o=n.every(Boolean),s=[];for(let e=0;efunction(e){const t=e.name.trim();if(!t)return[];if(Gb(t))return[];const r=e.subcommandTokens.map((e=>e.trim())).filter(Boolean),n=e.arguments.map((e=>e.trim())).filter(Boolean),o=[t],s=[t];for(const e of r)s.push(e),o.push(s.join(" "));const i=[t,...n].join(" ");return o.includes(i)||o.push(i),Dk(o)}(e)))),R=s.map((e=>e.suggestedAllowlistEntry)).filter((e=>"string"==typeof e)).filter((e=>x.includes(e))),x.length>0){const e=Zb(x,R),t=e.length>0?e.join(", "):x.join(", ");E.push(`Not in allowlist: ${t}`)}_=o&&0===P.length,_&&nk.info(e,"Smart allowlist: all commands in allowlist, will check security",{commandCount:t.length})}const T="ask-every-time"===a||"insecure_none"===n.type&&"allowlist"===a?void 0:l,A=Vk(v),$=b.map(((e,t)=>new Jk(e,n,T,S[t],y?A:v[t])));if((0===b.length||h&&!y)&&!c){nk.info(e,"Shell permissions: prompting after parser miss",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:Zk(n),userConfiguredPolicyType:Zk(l),isSmartAllowlistActive:y,parsingFailed:h,parserCommandCount:b.length,hasSmartModeApprovalReason:void 0!==f,hasSmartModeApprovalRequestId:void 0!==m});const o={type:Bw.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:Uk(f??(h?"Parser failed to parse command (possible bypass)":"Parser found no commands (possible bypass)"),await this.adminNetworkLimitReason(n)),isSandboxAvailable:!1,isSandboxEnabled:!1,canAllowlist:!1,notAllowedCommands:[],smartModeApprovalReason:f,smartModeApprovalRequestId:m}};r.onApprovalRequested?.();const s=await this.pendingDecisionStore.requestApproval(o);return s.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(n)}:{kind:"block",reason:{type:"userRejected",reason:s.reason}}}if(await this.hasHardDeny(e,$))return{kind:"block",reason:{type:"permissionsConfig",..."workspace_readonly"===l.type?{isReadonly:!0}:{}}};const{allowlistOfferSafe:M,redirectsAllowlistSafe:D}=await this.computeRedirectAllowlistSafety(r.parsingResult,r.workingDirectory,"insecure_none"===l.type||"workspace"!==l.readBoundary),O=await this.teamSettingsService.getAutoRunControls(),F={type:"insecure_none"};for(const e of $)await this.cmdIsAllowedByAllowlist(e,{redirectsAllowlistSafe:D,autoRunControls:O,applyTeamAllowlist:u})&&e.approveWithPolicy(F);for(const e of $)O&&this.isInTeamBlocklist(O,e)&&e.deny();const N=await this.teamSettingsService.getDeleteFileProtection();if(N)for(const e of $)"rm"===e.command.name&&e.deny();const L=this.buildShellApprovalDecisionFacts({commands:$,autoRunControls:O,shouldApplyTeamShellAllowlist:u,deleteProtectionEnabled:N,softDenylistedCommands:P});if("workspace_readonly"===l.type&&"workspace_readonly"!==n.type)return nk.info(e,"Shell permissions: blocked by readonly mode"),{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}};const j=Do(r.hookApprovalRequirement),U=r.hookApprovalRequirement?.reason,B=o&&"insecure_none"!==l.type&&function(e){if(/\brimraf\b/i.test(e))return!0;for(const t of e.replace(/[\\`^]\r?\n/g," ").split(/(?|])&|\|\||[;\n]/)){let e=!1;for(const r of t.split("|")){if(e&&QS.test(r)||ek(r,QS,YS)||ek(r,/(?0&&(L.hasSecurityDenies||L.hasSoftDenies||!L.allCommandsRunnable);if(void 0!==f&&G.push(f),j&&(V||G.push(U?`Hook requested approval: ${U}`:"Hook requested approval"),z=!1),B&&(V||G.push("Recursive delete outside the sandbox"),z=!1),C.length>0&&(V||G.push(...C),z=!1),!V)if(y&&E.length>0)G.push(...E);else if(L.unapprovedCommands.length>0){const e=Zb(this.generateAllowlistPatterns(L.unapprovedCommands)),t=e.length>0?e.join(", "):L.unapprovedCommands.map((e=>e.command.fullText)).join(", ");G.push(`Not in allowlist: ${t}`)}if(L.hasSecurityDenies&&(V||(L.rmDeniedByDeleteProtection.length>0&&G.push("Delete protection is enabled"),L.teamBlocklistedCommands.length>0&&G.push(`In team blocklist: ${L.teamBlocklistedCommands.map((e=>e.command.name)).join(", ")}`)),z=!1),K){const t=L.notInTeamAllowlist.map((e=>e.command.fullText)).join(", ");nk.info(e,"Shell permissions: commands not in team allowlist",{commandCount:L.notInTeamAllowlist.length}),V||G.push(`Not in team allowlist: ${t}`),z=!1}const J="unrestricted"===a&&"workspace_readonly"===n.type,Z="unrestricted"!==a||J?n:{type:"insecure_none"},X=Uk(...G,await this.adminNetworkLimitReason(Z)),Q=[];if(z){const e=void 0!==f?$.filter((e=>"allowlisted"!==e.state)):L.unapprovedCommands;Q.push(...this.generateAllowlistPatterns(e))}const Y=y&&E.length>0,ee=Y?x:Q,te=Y&&R.length>0?R:void 0,re="insecure_none"!==n.type&&"insecure_none"!==l.type,ne="insecure_none"!==n.type,oe=[void 0!==f?"smart_mode_approval":void 0,j?"hook_forces_prompt":void 0,B?"unsandboxed_recursive_delete":void 0,C.length>0?"command_blocklist":void 0,y&&E.length>0?"smart_allowlist_miss":void 0,L.unapprovedCommands.length>0?"unapproved_commands":void 0,L.hasSecurityDenies?"security_denies":void 0,K?"team_allowlist_miss":void 0].filter((e=>void 0!==e));nk.info(e,"Shell permissions: requesting shell approval",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:Zk(n),userConfiguredPolicyType:Zk(l),isSandboxAvailable:re,isSandboxEnabled:ne,canAllowlist:z,isSmartAllowlistActive:y,hasSmartModeApprovalReason:void 0!==f,hasSmartModeApprovalRequestId:void 0!==m,hookForcesPrompt:j,approvalReasonTypes:oe,commandCount:$.length,unapprovedCommandCount:L.unapprovedCommands.length,deniedCommandCount:L.deniedCommands.length,notInTeamAllowlistCount:L.notInTeamAllowlist.length,notAllowedCommandCount:ee.length,suggestedAllowlistEntryCount:te?.length??0,allCommandsRunnable:L.allCommandsRunnable,allCommandsAllowlisted:L.allCommandsAllowlisted,allCommandsPreapproved:L.allCommandsPreapproved,hasSecurityDenies:L.hasSecurityDenies,hasSoftDenies:L.hasSoftDenies});const se={type:Bw.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:X,isSandboxAvailable:"allowlist"===a&&re,isSandboxEnabled:!("allowlist"!==a&&!J)&&ne,canAllowlist:z,notAllowedCommands:ee,suggestedAllowlistEntries:te,smartModeApprovalReason:f,smartModeApprovalRequestId:m}};r.onApprovalRequested?.();const ie=await this.pendingDecisionStore.requestApproval(se);return ie.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(Z)}:{kind:"block",reason:{type:"userRejected",reason:ie.reason}}}async isShellCommandFullyAllowlisted(e,t,r){const n=e.withName("InteractivePermissionsService.isShellCommandFullyAllowlisted"),o=await this.getPermissions(),s=!o.dashboardTerminalAllowlistOverriddenByPermissionsFile;if("allowlist"!==o.approvalMode)return!1;if("workspace_readonly"===o.userConfiguredPolicy.type)return!1;const{redirectsAllowlistSafe:i}=await this.computeRedirectAllowlistSafety(r.parsingResult,r.workingDirectory,"insecure_none"===o.userConfiguredPolicy.type||"workspace"!==o.userConfiguredPolicy.readBoundary);if(!i)return!1;const a=r.classifierResult,c=void 0!==a&&!a.classificationFailed&&a.commands.length>0?a:void 0,l=(o.smartAllowlistEnabled??!1)&&void 0!==c;if(r.parsingResult.parsingFailed&&!l)return!1;const u=r.parsingResult.executableCommands.map(zS),d=l?c.commands.map(Nk):u.map((e=>e.command));if(0===d.length)return!1;const h=l?c.commands.map(Ok):d.map((e=>[e.fullText.trim()].filter(Boolean))),p=void 0!==c?c.commands.map(Ok):u.map(Kk),f={type:"insecure_none"},m=Vk(u),g=d.map(((e,t)=>new Jk(e,f,void 0,h[t],l?m:u[t])));if(await this.hasHardDeny(n,g))return!1;const w=Dk(o.smartAllowlistDenylist??[]);if(w.length>0)for(const e of p)if(e&&0!==e.length&&w.some((t=>Fk(e,t))))return!1;if(await this.teamSettingsService.getDeleteFileProtection()&&g.some((e=>"rm"===e.command.name)))return!1;const y=await this.teamSettingsService.getAutoRunControls();if(void 0!==y&&g.some((e=>this.isInTeamBlocklist(y,e))))return!1;for(const e of g)if(!await this.cmdIsAllowedByAllowlist(e,{redirectsAllowlistSafe:i,autoRunControls:y,applyTeamAllowlist:s}))return!1;return!0}async applyServerAndAdminPolicies(e){if("insecure_none"===e.type)return e;const t=this.rootDirectories.at(0)??(0,o.homedir)(),{userSandboxDataFolderName:r,teamAdminPolicy:n}=await this.getPermissions(),i=void 0!==r&&r.length>0?(0,s.join)((0,o.homedir)(),r,"sandbox.json"):this.perUserSandboxConfigPath,a=await this.foldPerUserFilePolicy(e,i),c=a.skipStatsigDefaults?a:await this.applyStatsigDefaults(a),l=await this.loadPerRepoFilePolicy(c,t),u=await this.resolveTeamAdminLayer(n);if("unavailable"===u){const{policy:e}=await(0,No.resolveSandboxPolicyForWorkspace)(t,{perUser:c,perRepo:l});return function(e){return"insecure_none"===e.type?e:{...e,networkPolicy:(0,No.Po)(),readBoundary:"workspace",additionalReadPaths:[]}}(e)}const d=void 0===u?void 0:Lk(c.type,u),h=(0,No._B)(e.networkPolicy)&&!jk(d?.networkPolicy),{policy:p}=await(0,No.resolveSandboxPolicyForWorkspace)(t,{perUser:c,perRepo:l,teamAdmin:d});return h?{...p,networkPolicy:(0,No.T6)()}:p}async resolveLinkedWorktreeSandboxGrants(e,t){if("workspace_readwrite"!==e.type||"workspace"===e.readBoundary)return;const{perms:r,setting:n}=await this.readControlSetting();if("workspace"===n.boundary||"unavailable"===r.teamAdminPolicy)return;const i=r.userSandboxDataFolderName;if(void 0===e.readBoundary){const t=this.rootDirectories.at(0)??(0,o.homedir)(),n=void 0!==i&&i.length>0?(0,s.join)((0,o.homedir)(),i,"sandbox.json"):this.perUserSandboxConfigPath,a="readBoundary"in r.userConfiguredPolicy&&void 0!==r.userConfiguredPolicy.readBoundary?{...e,readBoundary:r.userConfiguredPolicy.readBoundary}:e,c=await this.foldPerUserFilePolicy(a,n),l=await this.loadPerRepoFilePolicy(c,t);if("workspace"===(l?.readBoundary??c.readBoundary))return}const a=[];for(const e of this.rootDirectories){if((0,Gs.$f)(e))continue;const t=await NS(e);LS(t.resolution)&&!bS(t.resolvedPath)&&a.push(t.resolvedPath)}if(0===a.length)return;let c;if(!(0,Gs.$f)(t.workingDirectory)){const e=await NS(t.workingDirectory);LS(e.resolution)&&(c=e.resolvedPath)}return async function(e,t={}){if(0===e.length)return;const r=await Promise.all(e.map((e=>RS(e)))),n=[];for(const o of r)void 0===o||n.some((e=>DS(e,o)))||!e.some((e=>(0,ts.BJ)(o,e)))&&await(t.isUntrustedExternalGitDir?.(o))||n.push(o);if(0===n.length)return;const o=[],i=[],a=void 0!==t.command||void 0!==t.realWorkingDirectory;for(const r of n){const n=await xS((0,s.join)(r,"worktrees"),256),c=await(0,Nr.PH)(n,(e=>ES((0,s.join)(r,"worktrees",e),r,!0===t.excludeAgentWorktrees,a?{command:t.command,realWorkingDirectory:t.realWorkingDirectory}:void 0)),{max:16});let l=!1;for(const r of c){if(o.length>=16)break;void 0===r||o.some((e=>DS(e,r)))||e.some((e=>(0,ts.BJ)(r,e)))||PS(r,e)||await(t.isExcludedWorktreeRoot?.(r))||(o.push(r),l=!0)}l&&i.push(r)}return 0===o.length?void 0:{roots:o,commonDirs:i}}(a,{command:t.command,realWorkingDirectory:c,excludeAgentWorktrees:!0,isUntrustedExternalGitDir:e=>this.isFreelyWritableOutsideWorkspace(e,i),isExcludedWorktreeRoot:async e=>await this.isFreelyWritableOutsideWorkspace(e,i)||await this.ignoreService.isRepoBlocked(e)})}async foldPerUserFilePolicy(e,t=this.perUserSandboxConfigPath){const r=await(0,No.tv)(t,(0,o.homedir)());if(!r||"insecure_none"===r.type)return e;let n=(0,No.fZ)(r.networkPolicy,e.networkPolicy);n&&void 0!==e.networkPolicy?.default&&(n={...n,default:e.networkPolicy.default});const s=(0,No.s9)(r.additionalReadonlyPaths,e.additionalReadonlyPaths),i={...e,networkPolicy:n,additionalReadonlyPaths:s.length>0?s:void 0,readBoundary:r.readBoundary??e.readBoundary,additionalReadPaths:void 0!==r.additionalReadPaths?r.additionalReadPaths:e.additionalReadPaths,privateTmp:r.privateTmp??e.privateTmp};if("workspace_readwrite"===e.type&&"workspace_readwrite"===r.type){const t=(0,No.s9)(r.additionalReadwritePaths,e.additionalReadwritePaths);return{...i,additionalReadwritePaths:t.length>0?t:void 0}}return i}async applyStatsigDefaults(e){const t=await this.teamSettingsService.getDefaultNetworkAllowlist();if(!t.available||0===t.allowlist.length)return e;if((0,No._B)(e.networkPolicy))return e;const r={default:"deny",allow:fk(t.allowlist)};return{...e,networkPolicy:(0,No.fZ)(e.networkPolicy,r)}}async loadPerRepoFilePolicy(e,t){const r=await(0,No.tv)((0,s.join)(t,".cursor","sandbox.json"),t);if(r){if("1"===process.env[Yv.K4]){const n=(0,No.fB)({perUser:e,perRepo:r},t).perRepo;return"insecure_none"===n?.type?void 0:n}if("insecure_none"!==r.type)return r.type!==e.type?Lk(e.type,{networkPolicy:r.networkPolicy,additionalReadonlyPaths:r.additionalReadonlyPaths,..."additionalReadwritePaths"in r?{additionalReadwritePaths:r.additionalReadwritePaths}:{},disableTmpWrite:r.disableTmpWrite,networkPolicyStrict:r.networkPolicyStrict,readBoundary:r.readBoundary,additionalReadPaths:r.additionalReadPaths,privateTmp:r.privateTmp}):r}}async resolveTeamAdminLayer(e){return void 0!==e?"unavailable"===e?"unavailable":"workspace"===(t=e).readBoundary?t:void 0===t.networkPolicy?{}:{networkPolicy:t.networkPolicy}:async function(e){const{teamSettings:t}=e,r=e.adminNetworkControlsEnabled?(i=await t.getNetworkAccessControls()).available?0!==i.allowlist.length||0!==i.denylist.length?{...i.allowlist.length>0?{default:"deny",allow:fk(i.allowlist)}:{},...i.denylist.length>0?{deny:fk(i.denylist)}:{}}:void 0:(0,No.Po)():void 0,[n,o]=await Promise.all([t.isReadControlEnabled?.()??!0,t.getSandboxingControls()]),s=void 0===r?{}:{networkPolicy:r};var i;return n&&"workspace"===o.readBoundary?{...s,readBoundary:"workspace",additionalReadPaths:o.readAllowlistPaths??[],allowUserOverrideReadPaths:o.allowUserOverrideReadAllowlist}:void 0===r?void 0:s}({teamSettings:this.teamSettingsService,adminNetworkControlsEnabled:this.adminNetworkControlsEnabled});var t}async adminNetworkLimitReason(e){if("insecure_none"===e.type||!(0,No._B)(e.networkPolicy))return;const{teamAdminPolicy:t}=await this.getPermissions(),r=await this.resolveTeamAdminLayer(t);return function(e){if(jk(e))return void 0!==e.allow&&e.allow.length>0?"Network access limited to your admin's allowlist":"deny"===e.default?"Network access limited by your admin":"Network access excludes domains your admin blocks"}("unavailable"===r?(0,No.Po)():r?.networkPolicy)}async getAdminReadSandboxing(){const e=await this.getPermissions();if("unavailable"===e.teamAdminPolicy)return{readBoundary:"workspace"};const{enabled:t,boundary:r}=await this.adminReadControls(e);return{readBoundary:t&&"workspace"===r?"workspace":void 0}}async isInShellAllowlist(e){if(!e.allowlistable)return!1;const t=await this.getPermissions(),r=e.readsArguments?e.matchForms.map((e=>`${e} \0`)):e.matchForms;return t.allow.some((e=>this.isShellEntry(e)&&r.some((t=>this.matchesShell(e,t)))))}isInTeamBlocklist(e,t){const r=[...t.wrapperForms,t.command.fullText];return e.blocked.some((e=>r.some((t=>this.matchesAutoRunCommand(t,e)))))}isInTeamAllowlist(e,t){return!!t.allowlistable&&e.allowed.some((e=>this.matchesAutoRunCommand(t.command.fullText,e)))}async computeRedirectAllowlistSafety(e,t,r){const n=e.hasRedirects,s=e.parsingFailed,a=!0===e.allRedirectsAreDevNull,c=!(!n||a||s)&&await async function({parsingResult:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n=!0,resolvePathForPermissions:s=NS,pathModule:a=i,tempPathOptions:c={platform:process.platform,env:process.env,pathModule:a,homeDirectory:(0,o.homedir)()}}){if(!e.hasRedirects)return!0;const l=e.redirects;if(0===l.length)return!1;const u=e.executableCommands.length>1,d=await Tk({parsingResult:e,workingDirectory:t,resolvePathForPermissions:s,pathModule:a}),h=mk();for(const e of l){if(bk(e))continue;const o=u?mk():h,{operator:i,targetText:l}=e,f=e.destinationFds;if(">&"===i){const e=vk(l),t=void 0===e?void 0:o.fdTargets.get(e);if("original-stdout"!==(p=t)&&"original-stderr"!==p&&"dev-null"!==p&&"workspace-file"!==p&&"tmp-file"!==p){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}for(const e of f)o.fdTargets.set(e,t);continue}if("<&"===i){const e=vk(l),t=void 0===e?void 0:o.fdTargets.get(e);if("dev-null"!==t){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}for(const e of f)o.fdTargets.set(e,t);continue}if("/dev/null"===l){for(const e of f)o.fdTargets.set(e,"dev-null");continue}if(!wk(i)||void 0===l||"word"===e.targetNodeType&&!Sk(l,a)){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}const m=await Ak({targetText:l,workingDirectory:t,workingDirectories:d,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:s,pathModule:a,tempPathOptions:c});if(!m){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}for(const e of f)o.fdTargets.set(e,m)}var p;return!0}({parsingResult:e,workingDirectory:t,rootDirectories:this.rootDirectories,allowTmpRedirects:r}),l=await Mk({parsingResult:e,workingDirectory:t,rootDirectories:this.rootDirectories,allowTmpRedirects:r}),u=!function({parsingResult:e,hasRedirects:t,parsingFailed:r,allRedirectsAreAllowlistSafe:n,allRedirectsAreWorkspaceFileSafe:o}){return!(!t||r||n||o)&&(0===e.redirects.length||e.redirects.some(yk))}({parsingResult:e,hasRedirects:n,parsingFailed:s,allRedirectsAreAllowlistSafe:a,allRedirectsAreWorkspaceFileSafe:c})&&l;return{allowlistOfferSafe:(!n||a||c)&&l&&!s,redirectsAllowlistSafe:u}}async cmdIsAllowedByAllowlist(e,t){return!!t.redirectsAllowlistSafe&&(!!await this.isInShellAllowlist(e)||t.applyTeamAllowlist&&void 0!==t.autoRunControls&&this.isInTeamAllowlist(t.autoRunControls,e))}buildShellApprovalDecisionFacts({commands:e,softDenylistedCommands:t,autoRunControls:r,shouldApplyTeamShellAllowlist:n,deleteProtectionEnabled:o}){const s=e.filter((e=>"denied"===e.state)),i=e.filter((e=>"approvable"===e.state)),a=n&&r?.enabled?e.filter((e=>!this.isInTeamAllowlist(r,e))):[],c=s.filter((e=>void 0!==r&&this.isInTeamBlocklist(r,e))),l=o?s.filter((e=>"rm"===e.command.name)):[];return{hasSecurityDenies:s.length>0,hasSoftDenies:t.length>0,hasTeamAllowlistMisses:a.length>0,allCommandsRunnable:e.every((e=>e.isRunnable())),allCommandsAllowlisted:e.every((e=>"allowlisted"===e.state)),allCommandsPreapproved:e.every((e=>"preapproved"===e.state)),canAllowlistInPrompt:0===s.length&&0===a.length,unapprovedCommands:i,deniedCommands:s,notInTeamAllowlist:a,teamBlocklistedCommands:c,rmDeniedByDeleteProtection:l}}getShellAutoApprovalPolicy({approvalMode:e,isUnrestricted:t,requestedPolicy:r,facts:n,preserveRequestedPolicyForAllowlistedCommands:o}){if(!n.hasSecurityDenies&&!n.hasSoftDenies&&n.allCommandsRunnable){if(t)return"workspace_readonly"===r.type?r:{type:"insecure_none"};if("allowlist"===e)return n.allCommandsAllowlisted&&!o&&"workspace_readonly"!==r.type?{type:"insecure_none",allowlistEscalated:!0}:r}}async getPermissions(){return await this.permissionsProvider.getPermissions()}hasLocalShellControls(e){return e.allow.some((e=>this.isShellEntry(e)))||e.deny.some((e=>this.isShellEntry(e)))||(e.smartAllowlistDenylist?.length??0)>0}hasTeamShellControls(e,t=!0){return void 0!==e&&(t&&(e.enabled||e.allowed.length>0)||e.blocked.length>0)}async shouldPromptForEmptyPlainShellAllowlist(e,t){if("allowlist"!==t.approvalMode||"insecure_none"!==t.userConfiguredPolicy.type||0===e.trim().length||this.hasLocalShellControls(t))return!1;const[r,n]=await Promise.all([this.teamSettingsService.getAutoRunControls(),this.teamSettingsService.getDeleteFileProtection()]);return!this.hasTeamShellControls(r,!t.dashboardTerminalAllowlistOverriddenByPermissionsFile)&&!n}async requestApprovalForEmptyShellAllowlist(e,t,r){const n=await this.getEmptyShellAllowlistCandidates(t);t.onApprovalRequested?.();const o=await this.pendingDecisionStore.requestApproval({type:Bw.Shell,toolCallId:t.toolCallId,details:{command:e,workingDirectory:t.workingDirectory,timeout:t.timeout,reason:Uk(t.smartModeApprovalReason??"Shell allowlist is empty",await this.adminNetworkLimitReason(r)),isSandboxAvailable:!1,isSandboxEnabled:!1,canAllowlist:n.length>0,notAllowedCommands:n,smartModeApprovalReason:t.smartModeApprovalReason,smartModeApprovalRequestId:t.smartModeApprovalRequestId}});return o.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(r)}:{kind:"block",reason:{type:"userRejected",reason:o.reason}}}async getEmptyShellAllowlistCandidates(e){const t=e.parsingResult;return t.parsingFailed||0===t.executableCommands.length||t.hasRedirects&&!0!==t.allRedirectsAreDevNull||!await Mk({parsingResult:t,workingDirectory:e.workingDirectory,rootDirectories:this.rootDirectories,allowTmpRedirects:!0})?[]:this.generateAllowlistPatterns(t.executableCommands.map(zS))}async getAdminCommandDenylistBlock(e,t){const r=(await this.teamSettingsService.getAdminCommandDenylist()).rules;if(0===r.length)return;const n=ks({matchForms:t.parsingResult?ys({command:t.command,parsingResult:t.parsingResult}):[t.command],blockedCommands:r});return void 0!==n?(nk.info(e,"Admin command denylist hard-blocked shell at execution time",{toolCallId:t.toolCallId,parsingFailed:t.parsingResult?.parsingFailed??!0,parserCommandCount:t.parsingResult?.executableCommands.length??0}),{type:"adminCommandDenylist",pattern:n}):void 0}async hasHardDeny(e,t){const r=await this.getPermissions();return t.some((e=>r.deny.some((t=>this.isShellEntry(t)&&[...e.wrapperForms,...e.matchForms].some((e=>this.matchesShell(t,e)))))))}isShellEntry(e){return null!==qk(e)}isPathEntry(e,t){return new RegExp(`^\\s*${e}\\s*\\(`).test(t)}matchesShell(e,t){const r=qk(e);if(!r)return!1;const n=t.trim(),o=this.extractBaseCommand(n);if(null!==r.argsPattern){const e=n.includes(" ")?n.slice(n.indexOf(" ")+1).trim():"",t=this.matchGlob(r.commandPattern,o)||this.matchGlob(r.commandPattern,n),s=this.matchGlob(r.argsPattern,e);if(t&&s)return!0}return!!this.matchGlob(r.fullPattern,n)||!!n.startsWith(`${r.fullPattern} `)||!!this.matchGlob(r.fullPattern,o)||o===r.fullPattern}async checkCursorFileProtection(e){if(!e.some((e=>".cursor"===e.toLowerCase()||".vscode"===e.toLowerCase())))return null;const t=e[e.length-1]?.toLowerCase()??"";return t.endsWith(".md")||t.endsWith(".mdc")||".cursorrules"===t?null:await this.teamSettingsService.getDotCursorProtection()?{type:"permissionsConfig"}:null}extractBaseCommand(e){const t=e.trim(),r=t.indexOf(" ");return-1===r?t:t.substring(0,r)}generateAllowlistPatterns(e){const t=[],r=["git","npm","yarn","pnpm","docker","pip","systemctl","uv","cargo","bun","npx"];for(const{command:n,allowlistable:o}of e)o&&!Gb(n.name)&&(r.includes(n.name)&&n.args.length>0&&"word"===n.args[0].type?t.push(`${n.name} ${n.args[0].value}`):t.push(n.name));return[...new Set(t)]}pathEntryRawPattern(e,t){const r=t.match(function(e){return"Read"===e?r_:n_}(e));if(r)return(r[1]??"").trim()}compileReadDenyMatcher(e){try{const t=this.pathEntryRawPattern("Read",e);if(void 0===t)return()=>!1;const r=(0,ws.b)((0,ts.jl)(t));return e=>r(e)}catch(e){return()=>{throw e}}}matchesPathEntry(e,t,r){const n=this.pathEntryRawPattern(e,t);return void 0!==n&&this.matchGlob((0,ts.jl)(n),r)}async isPathExplicitlyDenied(e,t){return(await this.getPermissions()).deny.some((r=>this.isPathEntry(e,r)&&this.matchesPathEntry(e,r,t)))}async isPathExplicitlyAllowed(e,t){return(await this.getPermissions()).allow.some((r=>this.isPathEntry(e,r)&&this.matchesPathEntry(e,r,t)))}matchGlob(e,t){return(0,ws.T)(e,t)}async addToAllowList(e,t,r){const n=`${t}(${r})`;await this.permissionsProvider.updatePermissions((e=>{const t=e.allow.includes(n)?e.allow:[...e.allow,n];return{...e,allow:t}}))}async addToDenyList(e,t,r){const n=`${t}(${r})`;await this.permissionsProvider.updatePermissions((e=>{const t=e.deny.includes(n)?e.deny:[...e.deny,n];return{...e,deny:t}}))}async shouldBlockMcp(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{tk(o,(0,D.VI)(e.withName("InteractivePermissionsService.shouldBlockMcp")),!1);const{name:s,toolName:i,providerIdentifier:a,args:c}=t,l=function(e,t){if(void 0!==t)return t;const r=e;return void 0!==r.annotations?r.annotations:Fb(r.annotationsJson)}(t,r?.annotations),u=e=>{this.mcpAllowlistLog?.(e)};if(u(`[permissions-service] shouldBlockMcp: toolName="${i}", providerIdentifier="${a}"`),await this.isComputerUseDisabledByAdminFor(a))return u(`[permissions-service] shouldBlockMcp: BLOCKED (Computer Use off for team) toolName="${i}", providerIdentifier="${a}"`),{type:"unsafeResolution",message:"Computer Use is turned off by your team admin. Ask the user to do it instead."};const d=await this.mcpAdminToolLimitRefusal(e,{resolvedTool:n?.resolvedTool,toolName:i});if(void 0!==d)return u(`[permissions-service] shouldBlockMcp: BLOCKED (team tool limit) toolName="${i}", providerIdentifier="${a}"`),{type:"unsafeResolution",message:d};const h=await this.computerUseDecision(t,r);if(await this.isMcpExplicitlyDenied(e,a,i))return u(`[permissions-service] shouldBlockMcp: BLOCKED (explicitly denied) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig"};const p=await this.getPermissions(),f="workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode;if(!0===n?.alreadyApproved&&!f&&"block"!==h.kind&&"askEachCall"!==h.kind)return!1;const m=await this.teamSettingsService.getMcpToolControls(),g=!0===m?.enabled&&!(void 0!==n?.client&&!0===await(this.teamSettingsService.isHostMcpBridgeClient?.(n.client))),w=g&&"block"!==h.kind?{kind:"notComputerUse"}:h,y=void 0!==t.smartModeApproval?.reason&&f,v=t_({server:e_(a),tool:i});let b,S,k;switch(w.kind){case"block":return u(`[permissions-service] shouldBlockMcp: BLOCKED (Computer Use app) toolName="${i}", providerIdentifier="${a}"`),{type:"unsafeResolution",message:w.message};case"noAccess":if(!f&&!await this.teamSettingsService.getShouldBlockMcp())return u(`[permissions-service] shouldBlockMcp: ALLOWED (Computer Use no access) toolName="${i}", providerIdentifier="${a}"`),!1;b=v,k=!0;break;case"app":if(!y&&(this.computerUseAppsAllowedForSession.includes(w.entry)||await this.isComputerUseAppSaved(w.entry)))return u(`[permissions-service] shouldBlockMcp: ALLOWED (Computer Use app grant) toolName="${i}", providerIdentifier="${a}"`),!1;b=w.entry,S=w.app,k=!1;break;case"askEachCall":b=void 0,S=w.app&&{...w.app,allowOnce:!0},k=!1;break;case"notComputerUse":b=v,k=!0}const _=k||void 0!==b,C=t.smartModeApproval?.reason;if(void 0!==C)return"workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode?(u(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode, Smart Mode forced approval) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig",isReadonly:!0}):(u(`[permissions-service] shouldBlockMcp: needsApproval (Smart Mode) toolName="${i}", providerIdentifier="${a}"`),!(g?this.isMcpInTeamAllowlist(m,{providerIdentifier:a,toolName:i,annotations:l}):k&&await this.isMcpExplicitlyAllowed(e,a,i))&&!("unrestricted"===p.approvalMode&&!await this.teamSettingsService.getShouldBlockMcp())&&{type:"needsApproval",approvalReason:C,approvalDetails:{type:"mcp",name:s,toolName:i,...dk(r,l),providerIdentifier:a,args:c,reason:"smartMode",canAllowlist:_&&!this.isComputerUseServer(a),smartModeApprovalReason:C,smartModeApprovalRequestId:t.smartModeApproval?.requestId,allowlistEntry:b,computerUseApp:S}});if(g){const t=this.isMcpInTeamAllowlist(m,{providerIdentifier:a,toolName:i,annotations:l});if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"team",outcome:t?"pass":"fail"}),t)return u(`[permissions-service] shouldBlockMcp: ALLOWED (in admin MCP allowlist) toolName="${i}", providerIdentifier="${a}"`),!1}else if(k){const t=await this.isMcpExplicitlyAllowed(e,a,i);if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"user",outcome:t?"pass":"fail"}),t)return u(`[permissions-service] shouldBlockMcp: ALLOWED (explicitly in allowlist) toolName="${i}", providerIdentifier="${a}"`),!1}if("workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode)return u(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig",isReadonly:!0};if("unrestricted"===p.approvalMode){if(!await this.teamSettingsService.getShouldBlockMcp())return u(`[permissions-service] shouldBlockMcp: ALLOWED (auto-run, no team block) toolName="${i}", providerIdentifier="${a}"`),!1;u(`[permissions-service] shouldBlockMcp: needsApproval (auto-run but team blocks MCP) toolName="${i}", providerIdentifier="${a}"`)}return u(`[permissions-service] shouldBlockMcp: needsApproval (not in allowlist) toolName="${i}", providerIdentifier="${a}", approvalMode="${p.approvalMode}"`),{type:"needsApproval",approvalReason:`MCP tool: ${i}`,approvalDetails:{type:"mcp",name:s,toolName:i,...dk(r,l),providerIdentifier:a,args:c,canAllowlist:_,allowlistEntry:b,computerUseApp:S}}}catch(e){o.error=e,o.hasError=!0}finally{rk(o)}}async mcpAdminToolLimitRefusal(e,{resolvedTool:t,toolName:r}){if(void 0===t||void 0===this.enforceMcpAdminToolLimits)return;if(!await this.enforcesMcpAdminToolLimits())return void(void 0!==this.onMcpAdminToolLimitCheck&&this.judgeMcpAdminToolLimit(t,r).then((e=>this.reportMcpAdminToolLimitCheck("shadow",e)),(()=>{})));const n=await this.judgeMcpAdminToolLimit(t,r);this.reportMcpAdminToolLimitCheck("enforce",n);const o=n?.outcome;switch(o){case void 0:case"within_limit":return;case"outside_limit":return sk.increment(e,1,{reason:"outside_limit"}),"Your team's admin limits this MCP tool";case"settings_unavailable":if(!0===n?.ranWithoutLimit)return;return sk.increment(e,1,{reason:"settings_unavailable"}),"Your team's MCP settings could not be read, so this MCP tool can't run right now";case"unknown_server":return sk.increment(e,1,{reason:"unknown_server"}),ik;default:return o}}async judgeMcpAdminToolLimit(e,t){if("unresolved"===e)return{outcome:"unknown_server"};const r=await(this.teamSettingsService.getMcpAdminToolLimit?.(e.client));if(void 0!==r)switch(r.kind){case"none":return;case"settings_unavailable":return{outcome:"settings_unavailable",...void 0===r.failure?{}:{settingsFailure:r.failure},...!0===r.noLimitApplies?{ranWithoutLimit:!0}:{}};case"unknown_server":return{outcome:"unknown_server"};case"limit":return{outcome:Wb(r.policy,{name:t,annotations:e.annotations})?"within_limit":"outside_limit"};default:return r}}reportMcpAdminToolLimitCheck(e,t){if(void 0!==t)try{this.onMcpAdminToolLimitCheck?.({mode:e,...t})}catch{}}async enforcesMcpAdminToolLimits(){if(void 0===this.enforceMcpAdminToolLimits)return!1;try{return await this.enforceMcpAdminToolLimits()}catch{return!1}}async computerUseDecision(e,t){const r=this.computerUse;if(void 0===r||!this.isComputerUseServer(e.providerIdentifier))return{kind:"notComputerUse"};const n=await r.isOwnServer(e_(e.serverIdentifier||e.providerIdentifier),t);if(!1===n)return{kind:"notComputerUse"};const o=await async function(e,t){const r=cS(e.meta?.["cursor/computerUseScope"])??cS(t.toolScopes?.[e.toolName]);if(void 0===r)return{kind:"screen"};let n;if(void 0!==r.appSelectorArgs){const t=Object.entries(r.appSelectorArgs).flatMap((([t,r])=>aS(t)&&void 0!==r&&void 0!==e.args[r]&&null!==e.args[r]?[{selector:t,value:e.args[r]}]:[]));if(0===t.length){const t=new Intl.ListFormat("en",{type:"disjunction"}).format(Object.values(r.appSelectorArgs).filter((e=>void 0!==e)));return{kind:"noAppSelector",message:`${e.toolName} needs exactly one of ${t} to name the app. Call it again with one of them.`}}const o=t.filter((({selector:e,value:t})=>function(e,t){return"pid"===e?"number"==typeof t&&Number.isInteger(t)||"string"==typeof t&&uS.test(t):"string"==typeof t&&t.length>0}(e,t)));if(1!==o.length){for(const{value:e}of t){const t="string"==typeof e?rS(e.trim()):void 0;if(void 0!==t)return{kind:"app",app:t}}return{kind:"unknownApp"}}n=function(e,t){if("pid"===e){const e="string"==typeof t&&uS.test(t)?Number(t):t;return"number"==typeof e&&Number.isSafeInteger(e)&&e>0?{pid:e}:void 0}const r="string"==typeof t?t.trim():"";if(0!==r.length)return"bundleId"===e?{bundleId:r}:"path"===e?{path:r}:{appName:r}}(o[0].selector,o[0].value)}else{if(void 0===r.appArg)return r.capturesScreen?{kind:"screen"}:{kind:"none"};{const t=e.args[r.appArg];if(null==t||function(e){return"object"==typeof e&&null!==e&&"screen"===e.scope}(t))return{kind:"screen"};n=function(e){if("string"==typeof e){const t=e.trim();return t.length>0?{name:t}:void 0}if("object"!=typeof e||null===e)return;const{scope:t,pid:r}=e;return"app"===t&&"number"==typeof r&&Number.isInteger(r)&&r>0?{pid:r}:void 0}(t)}}if(void 0===n)return{kind:"unknownApp"};const o=function(e){return"pid"in e?void 0:"name"in e?e.name:"bundleId"in e?e.bundleId:"path"in e?e.path:e.appName}(n),s=await t.describeApp(n)??(void 0===o?void 0:rS(o));return void 0===s?{kind:"unknownApp"}:{kind:"app",app:s}}({toolName:e.toolName,args:Object.fromEntries(Object.entries(e.args).map((([e,t])=>[e,t.toJson()]))),meta:t?._meta},r);if(void 0===n&&"app"!==o.kind)return{kind:"askEachCall"};switch(o.kind){case"none":return{kind:"noAccess"};case"screen":return{kind:"notComputerUse"};case"unknownApp":return{kind:"askEachCall"};case"noAppSelector":return{kind:"block",message:o.message};case"app":{const e=function(e){const t=e.toLowerCase();return Yb(t)?"Computer Use doesn't control Cursor itself, including its approval cards. Ask the user to do it instead.":eS.some((e=>e.bundleId===t))?"Computer Use doesn't control apps that run scripts, such as Script Editor, Automator and Shortcuts. Ask the user to do it instead.":tS.some((e=>e.bundleId===t))?"Computer Use doesn't control terminal apps. Use your shell tool to run commands instead.":void 0}(o.app.bundleId);if(void 0!==e)return{kind:"block",message:e};if(void 0===n)return{kind:"askEachCall"};const t=oS(o.app.bundleId)?void 0:t_({server:r.serverId,tool:sS(o.app.bundleId)});return void 0===t?{kind:"askEachCall",app:o.app}:{kind:"app",app:o.app,entry:t}}}throw new Error("unreachable computer-use subject")}isComputerUseServer(e){const t=e_(e);return!0===this.computerUse?.providerIdentifiers.has(t)}async isComputerUseDisabledByAdminFor(e){const t=this.computerUseAdminPolicy;return t?.providerIdentifiers.has(e_(e))?await t.isDisabledByAdmin():!!this.isComputerUseServer(e)&&!0===await(this.teamSettingsService.isComputerUseDisabledByAdmin?.())}allowComputerUseAppForSession({bundleId:e}){const t=void 0===this.computerUse||oS(e)?void 0:t_({server:this.computerUse.serverId,tool:sS(e)});void 0!==t&&this.computerUseAppsAllowedForSession.push(t)}async isMcpFullyAllowlisted(e,t){const r=e.withName("InteractivePermissionsService.isMcpFullyAllowlisted"),{providerIdentifier:n,toolName:o}=t,s=t.annotations??Fb(t.annotationsJson);if(await this.isMcpExplicitlyDenied(r,n,o)||await this.isComputerUseDisabledByAdminFor(n))return!1;const i=await this.teamSettingsService.getMcpToolControls();return!0===i?.enabled?!!this.isMcpInTeamAllowlist(i,{providerIdentifier:n,toolName:o,annotations:s}):!this.isComputerUseServer(n)&&await this.isMcpExplicitlyAllowed(r,n,o)}async isWebFetchFullyAllowlisted(e,t){const r=await this.getPermissions();if("allowlist"!==r.approvalMode)return!1;let n;try{n=new URL(t.url)}catch{return!1}const o=n.hostname;return!r.deny.some((e=>this.matchesWebFetchEntry(e,o)))&&r.allow.some((e=>this.matchesWebFetchEntry(e,o)))}matchesAutoRunCommand(e,t){const r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^${r}(\\s|$)`).test(e.trim())}matchesMcpPattern({pattern:e,providerIdentifier:t,toolName:r,logLabel:n}){const o=e.indexOf(":");if(-1===o)return!1;const s=e.slice(0,o).trim().toLowerCase(),i=e.slice(o+1).trim().toLowerCase(),a=e_(t).toLowerCase().trim(),c=r.toLowerCase().trim(),l="*"===s||this.matchGlob(s,a),u="*"===i||this.matchGlob(i,c),d=l&&u,h=`[permissions-service] ${n}: serverPattern="${s}", toolPattern="${i}", normalizedProviderIdentifier="${a}", normalizedToolName="${c}", serverMatches=${l}, toolMatches=${u}, result=${d}`;return this.mcpAllowlistLog?.(h),d}recordMcpAllowlistCheckResult(e,{allowlistScope:t,outcome:r}){ok.increment(e,1,{allowlist_scope:t,outcome:r})}matchesMcpEntry(e,t,r){const n=e.match(/^\s*Mcp\s*\((.*)\)\s*$/);if(!n)return!1;const o=n[1]?.trim()??"";return this.matchesMcpPattern({pattern:o,providerIdentifier:t,toolName:r,logLabel:"matchesMcpEntry"})}matchesWebFetchEntry(e,t){const r=e.match(/^\s*WebFetch\s*\((.*)\)\s*$/);return!!r&&Xv(t,r[1]?.trim()??"")}matchesMcpEntryBare({pattern:e,providerIdentifier:t,toolName:r}){return this.matchesMcpPattern({pattern:e,providerIdentifier:t,toolName:r,logLabel:"matchesMcpEntryBare"})}isMcpInTeamAllowlist(e,{providerIdentifier:t,toolName:r,annotations:n}){if(e.mcpToolAllowlist.some((e=>this.matchesMcpEntryBare({pattern:e,providerIdentifier:t,toolName:r}))))return!0;const o=this.findTeamMcpServerPolicy(e,t);return void 0!==o&&"reads"===o.mode&&Wb(o,{name:r,annotations:n})}findTeamMcpServerPolicy(e,t){for(const r of e.serverPolicies??[])if(this.matchesMcpEntryBare({pattern:`${r.name}:*`,providerIdentifier:t,toolName:""}))return r.policy}async isMcpExplicitlyDenied(e,t,r){return(await this.getPermissions()).deny.some((e=>this.matchesMcpEntry(e,t,r)))}async isComputerUseAppSaved(e){return(await this.getPermissions()).allow.some((t=>t.match(/^\s*Mcp\s*\((.*)\)\s*$/)?.[1]?.trim().toLowerCase()===e))}async isMcpExplicitlyAllowed(e,t,r){return(await this.getPermissions()).allow.some((e=>this.matchesMcpEntry(e,t,r)))}}var s_=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const i_=65536,a_=1048576,c_=(0,d.h)("LocalReadExecutor"),l_=async(e,t,r,n)=>{const o=setTimeout((()=>{c_.warn(e,`[watchdog, LocalReadExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function u_(e){return BigInt(Math.min(e,4294967295))}async function d_(e,t){if(0===t)return(0,xo.readFile)(e);if(t>2147483647)throw new RangeError(`File size (${t}) is greater than 2 GiB`);const r=await(0,xo.open)(e,"r");try{const e=Buffer.allocUnsafe(t);let n=0;for(;n=32&&e<=126||9===e||10===e||13===e}function f_(e){if(e.length>=2){if(255===e[0]&&254===e[1])return"utf-16le";if(254===e[0]&&255===e[1])return"utf-16be"}const t=Math.min(4096,e.length);if(t<16)return"utf-8";let r=0,n=0;for(let o=0;o+1=8&&r>=4*Math.max(1,n)?"utf-16le":n>=8&&n>=4*Math.max(1,r)?"utf-16be":"utf-8"}const m_=Buffer.from("\n---\n");function g_(e,t){const r=e.length;if(r<2*m_.length)return r;if(10!==e[r-1]||45!==e[r-2]||45!==e[r-3]||45!==e[r-4]||10!==e[r-5])return r;const n=Math.max(t,r-4096),o=e.lastIndexOf(m_,r-m_.length-1);return-1===o||o126))return!1}const t=e.split("\n").filter((e=>e.length>0));if(t.length<2||t.length>3)return!1;const r=t[0],n=t[t.length-1];return!(!/^(exit_code: (?:-?\d+|unknown)|error: .+)$/.test(r)||!n.startsWith("ended_at: ")||3===t.length&&!/^elapsed_ms: \d+$/.test(t[1]))}(e.subarray(o+m_.length,r-4).toString("utf-8"))?o:r}const w_=[Buffer.from("%PDF-","ascii"),Buffer.from([208,207,17,224,161,177,26,225]),Buffer.from([80,75,3,4]),Buffer.from([80,75,5,6]),Buffer.from([80,75,7,8]),Buffer.from([127,69,76,70]),Buffer.from([254,237,250,206]),Buffer.from([254,237,250,207]),Buffer.from([206,250,237,254]),Buffer.from([207,250,237,254]),Buffer.from([77,90,144]),Buffer.from([0,97,115,109]),Buffer.from([137,80,78,71,13,10,26,10]),Buffer.from([255,216,255]),Buffer.from("GIF87a","ascii"),Buffer.from("GIF89a","ascii"),Buffer.from("SQLite format 3\0","ascii"),Buffer.from([31,139]),Buffer.from("BZh","ascii"),Buffer.from([253,55,122,88,90,0]),Buffer.from([40,181,47,253]),Buffer.from([55,122,188,175,39,28]),Buffer.from([82,97,114,33,26,7,0]),Buffer.from([82,97,114,33,26,7,1,0])];function y_(e){return new Xy.sV({result:{case:"invalidFile",value:new Xy.cW({path:e,reason:"File content is binary data, not text"})}})}function v_(e,t,r){if(void 0===r.offset&&void 0===r.limit)return{applied:!1};if(t)return{applied:!1};const n=r.offset??1,o=r.limit??(n<0?Math.abs(n):e),s=n<0?Math.max(0,e+n):Math.max(0,n-1);if(s>=e)return{applied:!1};const i=Math.min(e,s+o),a=b_(s,e),c=b_(i,e);return{applied:!0,start:a,end:Math.max(a,c)}}function b_(e,t){if(Number.isNaN(e)||0===e)return 0;if(e===Number.POSITIVE_INFINITY)return t;if(e===Number.NEGATIVE_INFINITY)return 0;const r=Math.trunc(e);return r<0?Math.max(t+r,0):Math.min(r,t)}function S_(e){return-1===e.indexOf("\r\n")?e:e.replaceAll("\r\n","\n")}function k_(e,t,r,n,o,s){if(n>=o)return{from:0,to:0};let i=0,a=0,c=0===n,l=0;for(;ia&&13===r(t)?t-1:t};l=t+1}return c?{from:a,to:t}:{from:t,to:t}}function __(e,t,r){const n=k_((t=>e.indexOf("\n",t)),e.length,(t=>e.charCodeAt(t-1)),t,r,!1);return 0===n.from&&n.to===e.length?e:n.from>=n.to?"":e.slice(n.from,n.to)}function C_(e,t,r,n,o){if(t>=r)return{text:"",truncated:!1};const s=n>=0?n+3:-1;let i=t;if(n>=0&&i>=n&&i=r)return{text:"",truncated:!1};const a=function(e,t,r,n){if(r>=n)return n;if(r<=t)return t;const o=Math.max(t,r-3);let s=r;for(;s>o;){if(128!=(192&(e[s]??0)))return s;s--}return 192&~(e[s]??0)?r:s}(e,i,Math.min(r,i+3*(o+1)+3),r);let c=S_(function(e,t,r,n){if(t>=r)return"";if(n<0)return e.toString("utf8",t,r);const o=n+3;return r<=n||t>=o?e.toString("utf8",t,r):t>=n&&r<=o?"":(to?e.toString("utf8",Math.max(t,o),r):"")}(e,i,a,n));const l=c.length>o||ao&&(c=Jo(c,o)),{text:c,truncated:l}}function E_(e,t,r,n){if(t>=r)return{text:"",truncated:!1};const o=Math.min(r,t+2*n+1);let s=S_(e.slice(t,o));const i=s.length>n||on&&(s=Jo(s,n)),s.lengthn?{text:e.text+Jo(t,n),truncated:!0}:{text:e.text+t,truncated:e.truncated}}function P_(e,t){if(e.truncated)return e;const r=x_(e,t);return{text:r.text,truncated:r.truncated}}function R_(e,t,r){let n=e;return t.forEach(((e,t)=>{const o=function(e,t){const{line:r,hasNewline:n}=e;return t&&n&&r.text.endsWith("\r")?{...r,text:r.text.slice(0,-1)}:r}(e,r);t>0&&(n=x_(n,"\n")),n=x_(n,o.text),o.truncated&&(n={text:n.text,truncated:!0})})),n}function I_(e){const t=e.toLowerCase();return"utf-8"===t?"utf8":"utf-8-bom"===t||"utf-8 bom"===t?"utf8bom":"latin-1"===t?"latin1":t}function T_(e){return void 0===e.maxChars||void 0!==e.offset||void 0!==e.limit?Ks:Math.min(Ks,e.maxChars+2)}function A_(e,t,r){if(!t||void 0===r.maxChars||e.length-1<=r.maxChars)return e;const n=e.charCodeAt(e.length-1);return n>=55296&&n<=56319?e.slice(0,-1):e}class $_ extends Error{constructor(){super("Invalid UTF-8 while streaming read"),this.name="InvalidUtf8Error"}}function M_(e){for(let t=1;t<=Math.min(3,e.length);t++){const r=e[e.length-t]??0;if(128!=(192&r))return D_(r)>t?t:0}return 0}function D_(e){return e>=240?4:e>=224?3:e>=192?2:1}class O_{constructor(e,t,r){this.previousEndsWithCr=e,this.carry=t,this.strict=r,this.lines=0,this.crlfCount=0,this.lfOnlyCount=0,this.continuesLine=t.length>0}count(e){this.strict&&this.validate(e),0===this.lines&&e.length>0&&10!==e[0]&&(this.continuesLine=!0);for(let t=e.indexOf(10);-1!==t;t=e.indexOf(10,t+1))(t>0?13===e[t-1]:this.previousEndsWithCr)?this.crlfCount++:this.lfOnlyCount++,this.lines++;e.length>0&&(this.previousEndsWithCr=13===e[e.length-1])}finish(){if(this.strict&&this.carry.length>0)throw new $_}validate(e){let t=e;if(this.carry.length>0){const r=D_(this.carry[0]??0)-this.carry.length;if(e.length0&&(0,n.isUtf8)(e.subarray(0,e.length-t))?"utf8_cut":"utf8_invalid"}(e)}async function L_(e,t){const r=t>0?Math.min(t,a_):a_,o=await d_(e,r);return o.length===t&&(0,n.isUtf8)(o)||ui(new Vs.TextDecoder("utf-8",{fatal:!1}).decode(o,{stream:o.length===a_&&o.length!==t}))?{kind:"lossyUtf8",cacheEncoding:"utf8"}:{kind:"iconv",decoderEncoding:"latin1",cacheEncoding:"latin1"}}async function j_(e){const t=await(0,xo.stat)(e),r=await zi(e);if(r.isBinaryFile)return;const n=F_({file:e,stats:t,format:r},void 0);if("iconv"===n.kind)return n.decoderEncoding;const o=await L_(e,t.size);return"iconv"===o.kind?o.decoderEncoding:void 0}async function U_(e,{file:t,stats:r},n,o,s){const i=r.size,a=void 0!==n.offset||void 0!==n.limit,c=(n.offset??1)<0,l=n.offset??1,u=Math.max(0,l-1),d=void 0===n.limit?void 0:u+n.limit,h=c?Math.abs(l):0,p=a?1/0:n.maxChars??1/0,f=a&&!c?n.maxChars??1/0:1/0;let m=[],g=0,w=!1,y=0,v=!1,b=!(c||a&&u<=0),S=!1;const k=[];let _,C=0,E=!1,x=0,P=!1,R=[],I=0,T=0,A=0,$=!1,M={text:"",truncated:!1},D=!1,O=!1,F=0,N=0,L=0,j=!1,U=!1;const B=e=>{let t=e;return!j&&t.length>0&&(j=!0,65279===t.charCodeAt(0)&&(U=!0,t=t.slice(1))),t},W=(e,t)=>t&&13===e.text.charCodeAt(e.text.length-1),H=()=>P||E&&C>=Ks,q=()=>v||w&&g>=Ks,z=(e,t)=>{if(H())return;const r=k.length>0?1:0;let n=Ks-C;if(r>0){if(n<=0)return void(E=!0);n--}const o=e.text.length>n?{line:{text:Jo(e.text,n),truncated:!0},hasNewline:t}:{line:e,hasNewline:t};k.push(o),C+=r+(o.line.truncated?n:o.line.text.length),e.truncated&&(E=!0),o.line.truncated&&(E=!0),W(o.line,t)&&x++,C-x>f&&(P=!0,_=F)},G=(e,t)=>{if(q())return;const r=m.length>0?1:0;let n=Ks-g;if(r>0){if(n<=0)return void(w=!0);n--}const o=e.text.length>n?{line:{text:Jo(e.text,n),truncated:!0},hasNewline:t}:{line:e,hasNewline:t};m.push(o),g+=r+(o.line.truncated?n:o.line.text.length),(e.truncated||o.line.truncated)&&(w=!0),W(o.line,t)&&y++,g-y>p&&(v=!0,_=F)},V=(e,t)=>{e&&(t?N++:L++),F++},K=()=>{const e=R[I];void 0!==e&&(A-=e.line.text.length+1),R[I]=void 0,I=(I+1)%R.length,T--},J=(e,t,r)=>{const n=F;if(0===n&&(S=0===e.text.length),!c&&a&&b&&n>=u&&(b=!1,m=[]),b&&G(e,t),c){if(h>0)for(T===h&&K(),(e=>{if(T===R.length){const e=new Array(Math.min(h,Math.max(16,2*R.length)));for(let t=0;t1&&A>Ks;)K(),$=!0}else a&&n>=u&&(void 0===d||n!(D||(!b||q())&&(!a||0!==F)&&!(c?h>0:!(!a||H())&&F>=u&&F<(d??1/0))),X=()=>{const e=M.text.length-1;if(a){const t=!c&&F>=u&&F<(d??1/0),r=k.length>0?1:0;if(!t||C-x+r+e<=f)return;z(M,!1)}else{const t=m.length>0?1:0;if(g-y+t+e<=p)return;G(M,!1)}M={text:"",truncated:!1},D=!0};let Q;const Y=e=>{if(void 0===n.maxChars||c)return;if(!(a?H()||F>=(d??1/0):q()))return;const t=e.subarray(e.length-M_(e));return Q=new O_(ee,Buffer.from(t),"strictUtf8"===o.kind),Q};let ee=!1;for await(const r of async function*(e,t,r,n,o){const s=function(e){return e>0?{start:0,end:e-1}:{}}(n);if("strictUtf8"===r.kind||"lossyUtf8"===r.kind){const n=new Vs.TextDecoder("utf-8",{fatal:"strictUtf8"===r.kind,ignoreBOM:!0}),i=(0,Ro.createReadStream)(t,{highWaterMark:i_,signal:e.signal,...s});let a;try{for await(const e of i){if(void 0!==a){a.count(e);continue}const t=n.decode(e,{stream:!0});t.length>0&&(yield t),e.length>=4&&(a=o?.(e))}if(void 0!==a)return void a.finish();const e=n.decode();e.length>0&&(yield e)}catch(e){if(e instanceof TypeError)throw new $_;throw e}return}const i=(0,Ro.createReadStream)(t,{highWaterMark:i_,signal:e.signal,...s}).pipe(Js.decodeStream(r.decoderEncoding));for await(const e of i)yield"string"==typeof e?e:String(e)}(e,t,o,i,Y)){const e=B(r);let t=0,n=e.indexOf("\n",t);for(;-1!==n;){const r=n>t?13===e.charCodeAt(n-1):ee;Z()?(M=P_(M,e.slice(t,n)),J(M,!0,r)):(D&&n>t&&(O=!0),V(!0,r)),M={text:"",truncated:!1},D=!1,ee=!1,t=n+1,n=e.indexOf("\n",t)}t0&&N/te*100>=5,ne="utf8"===o.cacheEncoding&&U?"utf8bom":o.cacheEncoding;s&&ta(t,r,ne);const oe=Math.min(F,a?d??1/0:1/0),se=void 0!==_&&(O||oe>_+1),ie=(n.maxChars??1/0)+i_,ae=e=>e.text.length>ie?{text:Jo(e.text,ie),truncated:!0}:e,ce=()=>R_({text:"",truncated:w||se},m,re);if(!a){const e=ae(ce());return{content:e.text,totalLines:F,truncated:e.truncated,rangeApplied:!1}}if(F<=1&&S)return{content:"",totalLines:F,truncated:!1,rangeApplied:!1};if(c){const e=n.limit??h,t=[];for(let e=0;e=F){const e=ce();return{content:e.text,totalLines:F,truncated:e.truncated,rangeApplied:!1}}const le=ae(R_({text:"",truncated:E||se},k,re));return{content:le.text,totalLines:F,truncated:le.truncated,rangeApplied:!0}}class B_{constructor(e,t,r){this.permissionsService=e,this.workspacePath=t,this.terminalReads=new Ql,this.mcpStateAccessor=r?.mcpStateAccessor,this.useStreamingRead=r?.useStreamingRead,this.pendingDecisionProvider=r?.pendingDecisionProvider,this.encodingSlices=r?.encodingSlices}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,D.VI)(e.withName("LocalReadExecutor.execute")),!1);const o=t.path;if(""===o.trim())return new Xy.sV({result:{case:"error",value:new Xy.F_({path:o,error:rs})}});const i=(0,ts.o1)(o,this.workspacePath),a=await l_(e,"permissionsService.shouldBlockFileRead",3e3,(()=>Yk(this.permissionsService,i)));if(a){const r=await l_(e,"resolveFileReadBlock",3e3,(()=>async function(e,t){return await ed(e,{onNeedsApproval:async(e,r)=>{const n=t.pendingDecisionProvider?.requestReadApproval?.bind(t.pendingDecisionProvider);if("fileRead"!==r.type||!n)return{kind:"denied",message:"Blocked by permissions configuration"};const o=await n({type:Bw.Read,details:{path:r.path,reason:e},toolCallId:t.toolCallId});return o.approved?null:{kind:"rejected",reason:o.reason}},onUserRejected:e=>({kind:"rejected",reason:e}),onPermissionDenied:e=>({kind:"denied",message:e})})??{kind:"proceed"}}(a,{pendingDecisionProvider:this.pendingDecisionProvider,toolCallId:t.toolCallId})));if("rejected"===r.kind)return new Xy.sV({result:{case:"rejected",value:new Xy.f4({path:i,reason:r.reason??""})}});if("denied"===r.kind)return new Xy.sV({result:{case:"permissionDenied",value:new Xy.lW({path:i})}})}void 0!==this.mcpStateAccessor&&Vy(e,this.mcpStateAccessor,i);try{const r=await l_(e,"stat",3e3,(()=>(0,xo.stat)(i)));if(r.isDirectory())return new Xy.sV({result:{case:"invalidFile",value:new Xy.cW({path:i,reason:"Path is a directory, not a file"})}});if(!r.isFile())return new Xy.sV({result:{case:"invalidFile",value:new Xy.cW({path:i,reason:"Path is neither a file nor a directory"})}});const o=function(e){return null!==function(e){const t=sh(e,"terminals");if(!t||1!==t.remainingPath.length)return null;const r=t.remainingPath[0],n=/^(\d+)\.txt$/.exec(r);if(!n)return null;const o=Number.parseInt(n[1],10);return Number.isNaN(o)?null:{id:o}}(e)}(i),a=function(e){const t=sh(e,"agent-tools");return null!==t&&1===t.remainingPath.length&&t.remainingPath[0].endsWith(".txt")}(i);if(o||a)return await this.readTerminalFile(e,i,r,t,a&&!o);const c=await l_(e,"getFormatForFile",3e3,(()=>zi(i))),l=c.isImageFile,u=function(e){return".pdf"===(0,s.extname)(e).toLowerCase()}(i),d=ji(i);if(l){const t=await l_(e,"prepareImageForModel",3e3,(async()=>(async e=>{let t;try{t=await Bv(e)}catch(t){const r=await Wv(e);if("undecodable"===r.kind)return r;throw t}if(!0===t.reencoded)return{kind:"image",image:t};const r=await Wv(t.data);return"undecodable"===r.kind?r:{kind:"image",image:t}})(await(0,xo.readFile)(i))));return"undecodable"===t.kind?new Xy.sV({result:{case:"invalidFile",value:new Xy.cW({path:i,reason:(n=t.reason,`File is not a valid image: its data could not be decoded (${n}). A truncated or hand-copied file does this; write it again from the original bytes with code.`)})}}):new Xy.sV({result:{case:"success",value:new Xy.mE({path:i,output:{case:"data",value:t.image.data},totalLines:0,fileSize:u_(r.size),truncated:!1})}})}if(u){const t=await l_(e,"readPdfBinary",3e3,(()=>(0,xo.readFile)(i)));return new Xy.sV({result:{case:"success",value:new Xy.mE({path:i,output:{case:"data",value:t},totalLines:0,fileSize:u_(r.size),truncated:!1})}})}if(c.isBinaryFile&&d){if(void 0!==t.maxVideoBytes&&r.size>t.maxVideoBytes)return new Xy.sV({result:{case:"success",value:new Xy.mE({path:i,totalLines:0,fileSize:u_(r.size),truncated:!0})}});const n=await l_(e,"readBinaryFile",3e3,(()=>(0,xo.readFile)(i)));return new Xy.sV({result:{case:"success",value:new Xy.mE({path:i,output:{case:"data",value:n},totalLines:0,fileSize:u_(r.size),truncated:!1})}})}if(c.isBinaryFile)return y_(i);{const n=this.useStreamingRead,o=!n||await l_(e,"useStreamingRead",3e3,(()=>n()));if(o||r.size>Ks){const n=await l_(e,"readTextStreaming",7e3,(()=>async function(e,t,r,n){const o=F_(t,r.encodingHint);try{return{...await U_(e,t,r,o,n),decoder:o.kind}}catch(o){if(o instanceof $_){const o=await L_(t.file,t.stats.size);return{...await U_(e,t,r,o,n),decoder:o.kind}}throw o}}(e,{file:i,stats:r,format:c},t,o))),s=A_(n.content,n.truncated,t);return Wl(this.encodingSlices,e)&&this.recordStreamedRead(e,i,r.size,n,s),new Xy.sV({result:{case:"success",value:new Xy.mE({path:i,output:{case:"content",value:s},totalLines:n.totalLines,fileSize:u_(r.size),truncated:n.truncated,rangeApplied:n.rangeApplied})}})}const s=await l_(e,"readText",3e3,(()=>Bi(i,t.encodingHint))),a=await l_(e,"countLines",3e3,(()=>Xs(s))),l=function(e,t,r){const n=v_(t,""===e,r);return n.applied?n.start>=n.end?{content:"",rangeApplied:!0}:{content:__(e,n.start,n.end),rangeApplied:!0}:{content:e,rangeApplied:!1}}(s,a,t);let u=l.content,d=!1;const h=T_(t);return u.length>h&&(u=A_(u.substring(0,h),!0,t),d=!0),u.length16777216)return"other_encoding";try{return r=await d_(e,t),!(0,n.isAscii)(r)&&(0,n.isUtf8)(r)?"utf8_as_other":"other_encoding"}catch{return"other_encoding"}var r}(t,r)),ru(this.encodingSlices,e,{layer:"exec_read",evidence:a,partial:o.rangeApplied||o.truncated},i)}catch{}}async readTerminalFile(e,t,r,n,o){const s=await l_(e,"readTerminalFile",3e3,(()=>d_(t,r.size)));if(o&&(i=s,w_.some((e=>function(e,t){return e.length>=t.length&&e.subarray(0,t.length).equals(t)}(i,e)))))return y_(t);var i;const a=function(e,t,r=8388608){if(0===e.length)return{content:"",totalLines:1,rangeApplied:!1,truncated:!1};const n=h_(e),o=g_(e,n);if("utf-8"!==f_(e.subarray(n,o)))return function(e,t,r){const n=0===e.length,o=function(e){let t=0,r=0;const n=e.length;for(;r=s.end)return{content:"",totalLines:o,rangeApplied:!0,truncated:!1};const i=k_((t=>e.indexOf("\n",t)),e.length,(t=>e.charCodeAt(t-1)),s.start,s.end,!0),a=E_(e,i.from,i.to,r);return{content:a.text,totalLines:o,rangeApplied:!0,truncated:a.truncated}}(function(e){const t=h_(e),r=t>0?e.subarray(0,t).toString("utf-8"):"",n=g_(e,t),o=nr?-1:239===e[t]&&187===e[t+1]&&191===e[t+2]?t:-1}(e,n,o);return function(e,t,r,n){const o=e.length-(t>=0?3:0)==0,s=function(e){let t=0,r=0;const n=e.length;for(;r=i.end)return{content:"",totalLines:s,rangeApplied:!0,truncated:!1};const a=k_((t=>e.indexOf(10,t)),e.length,(t=>e[t-1]??0),i.start,i.end,!0),c=C_(e,a.from,a.to,t,n);return{content:c.text,totalLines:s,rangeApplied:!0,truncated:c.truncated}}(e,s,t,r)}(s,n,T_(n)),c=A_(a.content,a.truncated,n);return Wl(this.encodingSlices,e)&&(o||this.terminalReads.firstRead(n.toolCallId,t))&&tu(this.encodingSlices,e,{layer:o?"exec_read":"exec_terminal_context",evidence:N_(s),partial:a.rangeApplied||a.truncated},c),new Xy.sV({result:{case:"success",value:new Xy.mE({path:t,output:{case:"content",value:c},totalLines:a.totalLines,fileSize:u_(r.size),truncated:a.truncated,rangeApplied:a.rangeApplied})}})}}function W_(e){return Buffer.from(e,"utf16le").toString("utf16le")}var H_=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},q_=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function z_(e){return`Path '${e}' could not be verified while resolving symlinks. This can happen when access is denied or the path contains a symlink loop.`}function G_(e){return`Path '${e}' is neither a file nor a directory`}async function V_(e){const t=await(0,xo.stat)(e).catch((()=>{}));return void 0!==t&&!t.isFile()&&!t.isDirectory()}function K_(e,t,r){const n=function(e,t){let r;for(const n of t)(0,ts.ZU)({basePath:n,targetPath:e})&&(void 0===r||n.length>r.length)&&(r=n);return r}((0,s.resolve)(e,t),r);return void 0===n||n===e}class J_ extends Error{}function Z_(e){const t=new AbortController,r=setTimeout((()=>t.abort()),e);return{signal:t.signal,clear:()=>clearTimeout(r)}}function X_(e){switch(e.result.case){case"content":return e.result.value.matches.length>0;case"files":return e.result.value.files.length>0;case"count":return e.result.value.counts.length>0;case void 0:return!1;default:{const t=e.result;throw new Error(`Unknown grep result: ${String(t)}`)}}}function Q_(e){switch(e){case"content":return new Ry.vD({result:{case:"content",value:new Ry.Zp({ripgrepTruncated:!0})}});case"files_with_matches":return new Ry.vD({result:{case:"files",value:new Ry.T7({ripgrepTruncated:!0})}});case"count":return new Ry.vD({result:{case:"count",value:new Ry.xA({ripgrepTruncated:!0})}});default:throw new Error(`Unknown output mode: ${String(e)}`)}}function Y_(e){return"success"===e.result.case&&Object.values(e.result.value.workspaceResults).some((e=>!0===e.result.value?.clientTruncated))}function eC(e,t,r){let n=Buffer.concat(e);t&&(n=n.subarray(0,n.lastIndexOf(10)+1)),r?.note(n);const o=n.toString("utf8");return o.includes("�")?{stdout:o,stdoutBytes:n}:{stdout:o}}function tC(e){return/^(utf-?16|ucs-?2)/i.test(e)}const rC=(0,d.h)("local-exec/grep"),nC=(0,h.Pu)("local_exec.grep.deadline_reached",{description:"Grep and Glob searches the search deadline stopped, by whether they kept what was found",labelNames:["output_mode","outcome","streaming"]}),oC=(0,h.Pu)("local_exec.grep.newest_first_stat_fallback",{description:"Grep and Glob results left in ripgrep's order because stat was too slow to sort them",labelNames:["output_mode"]}),sC=(0,h.v5)("local_exec.grep.rg.spawn_ms",{description:"Time to start the ripgrep process for one Grep or Glob search",labelNames:["sandboxed"]}),iC=(0,h.v5)("local_exec.grep.rg.search_ms",{description:"Time ripgrep took to search and exit after it started, for runs it finished",labelNames:["output_mode","sandboxed"]});function aC(e){return e instanceof Error&&e.message.includes("ENOENT")&&e.message.includes("spawn")}function cC(e){try{return(0,Ro.existsSync)(e)}catch{return"check_failed"}}function lC(e){if("object"==typeof e&&null!==e&&"errno"in e){const t=e.errno;if("number"==typeof t)return t}}function uC(e,t){if("object"==typeof e&&null!==e)return"syscall"===t&&"syscall"in e&&"string"==typeof e.syscall?e.syscall:"path"===t&&"path"in e&&"string"==typeof e.path?e.path:void 0}function dC(e,t,r,n){return{...pC(e),...n,cwd:t,cwdExists:cC(t),errorMessage:Cc(r),errorCode:_c(r),errno:lC(r),syscall:uC(r,"syscall"),errorPath:uC(r,"path")}}function hC(e){return new Error(`Path does not exist: ${e}`)}function pC(e){const t={rgPath:e,platform:process.platform,arch:process.arch,pid:process.pid,uptimeSeconds:Math.round(process.uptime()),execPath:process.execPath};try{t.rgPathExists=(0,Ro.existsSync)(e)}catch(e){t.rgPathExists=!1,t.rgPathExistsError=e instanceof Error?e.message:String(e)}try{const r=(0,Ro.lstatSync)(e);t.rgIsSymlink=r.isSymbolicLink(),r.isSymbolicLink()&&!t.rgPathExists&&(t.rgBrokenSymlink=!0)}catch{t.rgLstatFailed=!0}const r=(0,s.dirname)(e);try{t.parentDirExists=(0,Ro.existsSync)(r),t.parentDirExists&&(t.parentDirContents=(0,Ro.readdirSync)(r).slice(0,50))}catch(e){t.parentDirError=e instanceof Error?e.message:String(e)}const n=(0,s.dirname)(r);try{t.grandparentDirExists=(0,Ro.existsSync)(n),t.grandparentDirExists&&(t.grandparentDirContents=(0,Ro.readdirSync)(n).slice(0,50))}catch(e){t.grandparentDirError=e instanceof Error?e.message:String(e)}if(t.rgPathExists)try{const r=(0,Ro.statSync)(e);t.rgFileSize=r.size,t.rgFileMode=r.mode.toString(8),t.rgIsFile=r.isFile(),t.rgModifiedMs=r.mtimeMs}catch(e){t.rgStatError=e instanceof Error?e.message:String(e)}const o="node_modules.asar.unpacked";if(e.includes(o)){const r=e.split(o)[0];if(r){const n=r.concat("node_modules.asar");try{t.asarExists=(0,Ro.existsSync)(n)}catch{t.asarExists="check_failed"}const i=r.concat(o);try{if(t.asarUnpackedDirExists=(0,Ro.existsSync)(i),t.asarUnpackedDirExists){const r=(0,s.dirname)((0,s.dirname)(e));t.ripgrepPkgDirExists=(0,Ro.existsSync)(r)}}catch{t.asarUnpackedDirExists="check_failed"}}}return t}class fC{constructor(e,t,r,n){this.ignoreService=e,this.grepProvider=t,this.workspacePath=r,this.stdoutDecodes=new WeakMap;const o=Array.isArray(this.workspacePath)?this.workspacePath[0]:this.workspacePath;this.singleWorkspacePath=Array.isArray(this.workspacePath)&&this.workspacePath.length>1?void 0:o,this.mcpStateAccessor=n?.mcpStateAccessor,this.permissionsService=n?.permissionsService,this.useStreamingGrep=n?.useStreamingGrep,this.encodingSlices=n?.encodingSlices}computeRelativeTarget(e,t){const r=(0,ts.o1)(e,this.singleWorkspacePath??t);return r===t?".":(0,s.relative)(t,r)}isRootIndependentSearchPath(e){return(0,s.isAbsolute)(e)||/^~(?=$|[/\\])/.test(e)||e.startsWith("file://")}resolveSearchTargets(e,t){const r=this.isRootIndependentSearchPath(e);return t.map((t=>{const n=(0,s.resolve)(t);return{root:t,resolvedRoot:n,target:(0,ts.o1)(e,r?void 0:n)}}))}findOutsideTargets(e,t){if(void 0===e||""===e)return;const r=this.resolveSearchTargets(e,t);return r.some((({resolvedRoot:e,target:t})=>(0,ts.BJ)(t,e)))?void 0:[...new Set(r.map((({target:e})=>e)))]}searchTarget(e,t){if(!t.path)return".";const r=(0,ts.o1)(t.path,this.singleWorkspacePath??e);return(0,ts.BJ)(r,(0,s.resolve)(e))?this.computeRelativeTarget(t.path,e):r}sortsAfterRipgrep(e,t,r){return void 0===t.sort&&(r?!0!==t.sortAscending:(0,s.isAbsolute)(this.searchTarget(e,t)))}async buildArgs(e,t,r,n){const o=[],s=function(e,t){return"files_with_matches"===t&&""===e.pattern&&Boolean(e.glob)}(t,r),i=await ma(await this.ignoreService.listCursorIgnoreFilesByRoot(e));for(const e of i)o.push("--cursor-ignore",e);if("content"===r)o.push("--line-number","--with-filename","--no-heading","-0"),void 0!==t.contextBefore&&o.push("--before-context",String(t.contextBefore)),void 0!==t.contextAfter&&o.push("--after-context",String(t.contextAfter)),o.push("--max-columns",String(1e3),"--max-columns-preview"),void 0!==t.context&&void 0===t.contextBefore&&void 0===t.contextAfter&&o.push("--before-context",String(t.context),"--after-context",String(t.context));else if("files_with_matches"===r)o.push(s?"--files":"-l");else{if("count"!==r)throw new Error(`Unknown output mode: ${String(r)}`);o.push("-c","--with-filename")}!0===t.caseInsensitive?o.push("--ignore-case"):o.push("--case-sensitive"),t.type&&o.push("--type",t.type),t.glob&&(o.push("--iglob",t.glob),s&&o.push("--iglob","!**/.git")),t.multiline&&o.push("--multiline","--multiline-dotall");const a=n?"none":t.sort??"modified";if(n&&o.push("--line-buffered"),"none"!==a){const e=!0===t.sortAscending?"--sort":"--sortr";o.push(e,a)}o.push("--no-config","--color=never"),o.push("--hidden"),o.push("--follow");const c=this.searchTarget(e,t);if(t.path){const t=await async function(e){try{if(!(await(0,xo.stat)(e)).isFile())return;const{encoding:t}=await zi(e);return tC(t)?t.toLowerCase():void 0}catch{return}}((0,ts.o1)(c,e));void 0!==t&&o.push("--encoding",t)}return s||o.push("--regexp",t.pattern),o.push("--"),o.push(c),o}async filterBlockedFiles(e,t){const r=new Map,n=await(this.permissionsService?.getFileReadBoundaryBlocker?.()),o=[];for(const s of e){const e=(0,ts.o1)(s.file,t),i=await xc(e);null===i||await this.isPostRipgrepBlocked(i,r)||void 0!==n&&await n(e,i)||o.push(s)}return o}async isPostRipgrepBlocked(e,t){const[r,n]=await Promise.all([this.ignoreService.isCursorIgnored(e,t),this.ignoreService.isRepoBlocked(e)]);return r||n}throwOnRipgrepFailure(e,t,r){if((""!==e.stderr||2===e.exitCode)&&""===e.stdout.trim()&&!function({stderr:e,target:t}){return e.trim().split(/\r?\n/).every((e=>{if(/^rg: .+: line \d+: /.test(e))return!0;const r=/^rg: (.+?): .*\(os error (?:13|5|2|1)\)$/.exec(e)?.[1]??/^rg: File system loop found: (.+) points to an ancestor /.exec(e)?.[1];return void 0!==r&&r!==t}))}({stderr:e.stderr,target:this.searchTarget(t,r)}))throw new Error(e.stderr||`ripgrep exited with code ${e.exitCode}`)}async orderNewestFirst(e,t,r,n,o){const s=await Zy(t,(e=>(0,ts.o1)(n(e),r)));return s.statTimedOut&&(rC.info(e,"newest_first.stat_timeout_fallback",{toolCallId:o.toolCallId,execId:o.execId,outputMode:o.outputMode,fileCount:t.length}),oC.increment(e,1,{output_mode:o.outputMode})),s.items}async keepNewestPage(e,t,r,n,o){return(await this.orderNewestFirst(e,t,r,n,o)).slice(0,fC.CLIENT_LIMIT_LINES)}async runFilesMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const d=H_(a,(0,D.VI)(e.withName("LocalGrepExecutor.runFilesMode")),!1),h=await this.buildArgs(t,r,"files_with_matches",n),p=await this.executeRg(d.ctx,t,h,void 0,o,s,i);this.throwOnRipgrepFailure(p,t,r);const f=(c=p.stdout,l=n?fC.HARD_MAX_OUTPUT_LINES:fC.CLIENT_LIMIT_LINES,u=fC.HARD_MAX_OUTPUT_LINES,function(e,t,r){const n=e.trim();if(""===n)return{files:[],totalFiles:0,clientTruncated:!1,ripgrepTruncated:!1};const o=new Iy;let s=0,i=0,a=0;for(;Ty(n,a,o);)a=o.nextStart,st?Buffer.from(n.slice(0,i)).toString():n,l=[];for(a=0;l.lengtht,ripgrepTruncated:s>=r}}(c,l,u)),m=f.totalFiles>fC.CLIENT_LIMIT_LINES;let g=f.files;n&&(g=await this.keepNewestPage(d.ctx,g,t,(e=>e),i),m&&(g=g.join("\0").split("\0")));const w=(await this.filterBlockedFiles(g.map((e=>({file:e}))),t)).map((({file:e})=>e)),y=g.length-w.length,v=new Ry.T7({files:w,totalFiles:Dy(f.totalFiles-y),clientTruncated:m,ripgrepTruncated:f.ripgrepTruncated||p.timedOut||p.stdoutByteCapped});return{result:new Ry.vD({result:{case:"files",value:v}}),timedOut:p.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{q_(a)}var c,l,u}async runCountMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const d=H_(a,(0,D.VI)(e.withName("LocalGrepExecutor.runCountMode")),!1),h=await this.buildArgs(t,r,"count",n),p=await this.executeRg(d.ctx,t,h,void 0,o,s,i);this.throwOnRipgrepFailure(p,t,r);const f=(c=p.stdout,l=n?fC.HARD_MAX_OUTPUT_LINES:fC.CLIENT_LIMIT_LINES,u=fC.HARD_MAX_OUTPUT_LINES,function(e,t,r){const n=e.trim();if(""===n)return{counts:[],totalFiles:0,totalMatches:0,clientTruncated:!1,ripgrepTruncated:!1};const o=[],s=new Iy;let i=0;for(;Ty(n,i,s);){const e=i,t=s.lineEnd;if(i=s.nextStart,t===e)continue;const r=n.lastIndexOf(":",t-1);if(rt,ripgrepTruncated:a>=r}}(c,l,u)),m=n?await this.keepNewestPage(d.ctx,f.counts,t,(e=>e.file),i):f.counts,g=await this.filterBlockedFiles(m,t),w=g.reduce(((e,t)=>e+t.count),0),y=m.length-g.length,v=m.reduce(((e,t)=>e+t.count),0)-w,b=new Ry.xA({counts:g.map((e=>new Ry.sS({file:e.file,count:Dy(e.count)}))),totalFiles:Dy(f.totalFiles-y),totalMatches:Dy(f.totalMatches-v),clientTruncated:f.totalFiles>fC.CLIENT_LIMIT_LINES,ripgrepTruncated:f.ripgrepTruncated||p.timedOut||p.stdoutByteCapped});return{result:new Ry.vD({result:{case:"count",value:b}}),timedOut:p.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{q_(a)}var c,l,u}async runContentMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const c=H_(a,(0,D.VI)(e.withName("LocalGrepExecutor.runContentMode")),!1),l=await this.buildArgs(t,r,"content",n),u=void 0!==r.context||void 0!==r.contextBefore||void 0!==r.contextAfter,d=fC.CLIENT_LIMIT_LINES*(u?2:1),h=await this.executeRg(c.ctx,t,l,d,o,s,i);this.throwOnRipgrepFailure(h,t,r);const p=await this.decodeLinesAsRead(c.ctx,h,t,i),{byFile:f,totalLines:m,totalMatchedLines:g,clientTruncated:w,ripgrepTruncated:y}=function(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{return H_(o,(0,D.VI)(n.withName("parseContentOutput")),!1),function(e,t,r){const n={byFile:new Map,totalLines:0,totalMatchedLines:0,totalFiles:0,clientTruncated:!1,ripgrepTruncated:!1};if(""===e.trim())return n;const o=new Map,s=new Set,i=new Iy;let a=0,c=0,l=0,u=0;for(;Ty(e,u,i);){const r=u,n=i.lineEnd;if(u=i.nextStart,l++,d=e,n-(h=r)==2&&45===d.charCodeAt(h)&&45===d.charCodeAt(h+1))continue;let p=-1;for(let t=r;t=n)continue;let m=0,g=0;for(;f57)break;m=10*m+(t-48),g++,f++}if(0===g||f>=n||!Number.isFinite(m))continue;const w=e.charCodeAt(f);if(58!==w&&45!==w)continue;const y=45===w;y||a++;const v=e.slice(r,p);if(s.has(v)||s.add(v),c>=t)continue;const b=e.slice(f+1,n);let S=o.get(v);void 0===S&&(S={file:v,matches:[]},o.set(v,S)),S.matches.push({lineNumber:m,content:b,isContextLine:y}),c++}var d,h;return{byFile:o,totalLines:Dy(l),totalMatchedLines:Dy(a),totalFiles:Dy(s.size),clientTruncated:c>=t,ripgrepTruncated:l>=r}}(e,t,r)}catch(e){o.error=e,o.hasError=!0}finally{q_(o)}}(p,fC.CLIENT_LIMIT_LINES,d,c.ctx),v=Array.from(f.values()),b=await this.filterBlockedFiles(v,t),S=v.filter((e=>!b.includes(e))),k=S.reduce(((e,t)=>e+t.matches.length),0),_=S.reduce(((e,t)=>e+t.matches.filter((e=>!e.isContextLine)).length),0),C=n?await this.orderNewestFirst(c.ctx,b,t,(e=>e.file),i):b,E=new Ry.Zp({matches:C.map((e=>new Ry.uI({file:e.file,matches:e.matches.map((e=>new Ry.dx({lineNumber:e.lineNumber,content:e.content,isContextLine:e.isContextLine})))}))),totalLines:Dy(m-k),totalMatchedLines:Dy(g-_),clientTruncated:w,ripgrepTruncated:y||h.timedOut||h.stdoutByteCapped});return{result:new Ry.vD({result:{case:"content",value:E}}),timedOut:h.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{q_(a)}}async decodeLinesAsRead(e,t,r,o){const s={stack:[],error:void 0,hasError:!1};try{const i=t.stdoutBytes;if(void 0===i)return t.stdout;const a=H_(s,(0,D.VI)(e.withName("LocalGrepExecutor.decodeLinesAsRead")),!1),c=function(e,t){const r=[],o=new Iy;let s=0,i=0,a=e.indexOf("�");for(;-1!==a&&Ty(e,s,o);){const{lineEnd:c,nextStart:l}=o,u=t.indexOf(10,i),d=-1===u?t.length:u+1;let h=-1===u?t.length:u;if(h>i&&-1!==u&&13===t[h-1]&&h--,ae.file)))],u=new Map,d=performance.now()+fC.LINE_ENCODING_TIMEOUT_MS;let h=0;for(;h{let d=!1,h=!1;const p=()=>{h||(h=!0,a.span.end())};if(e.signal.aborted)return p(),void u(new Error("Grep was cancelled"));if(o.aborted)return p(),void u(fC.ripgrepTimeoutError());let f;const m="insecure_none"===s.type?"false":"true",g=performance.now();let w=g;try{const e=s;f=(0,No.spawnInSandbox)((0,No.Ko)(),r,{cwd:t},e),w=performance.now(),0}catch(r){if(p(),aC(r)){const n=(0,No.Ko)();if(rC.error(e,"rg_diagnostics.spawn_throw",void 0,dC(n,t,r,i)),!1===cC(t))return u(hC(t))}return u(r)}const y=[],v=[];let b=0,S=0,k=0,_=!1,C=!1,E=!1;const x=()=>{if(!d)try{p(),E=!0;const e=eC(y,!0,this.stdoutDecodes.get(i));""===e.stdout?u(fC.ripgrepTimeoutError()):l({...e,stderr:"",exitCode:0,timedOut:!0,stdoutByteCapped:C}),f.kill()}catch{}};o.addEventListener("abort",x,{once:!0});const P=()=>{o.removeEventListener("abort",x),p(),u(new Error("Grep was cancelled"));try{f.kill()}catch{}};e.signal.addEventListener("abort",P,{once:!0}),f.stdout?.on("data",(e=>{if(!C&&!_)if(b+=e.length,b>c){C=!0;try{f.kill()}catch{}}else if(void 0!==n){let t=-1,r=0;for(let o=0;o=n)){t=o+1,_=!0;try{f.kill()}catch{}break}k+=r;const o=t>=0?e.subarray(0,t):e;y.push(o)}else y.push(e)})),f.stderr?.on("data",(e=>{S+=e.length,S<=c&&v.push(e)})),f.on("error",(r=>{if(o.removeEventListener("abort",x),e.signal.removeEventListener("abort",P),p(),aC(r)){const n=(0,No.Ko)();if(rC.error(e,"rg_diagnostics.spawn_enoent",void 0,dC(n,t,r,i)),!1===cC(t))return void u(hC(t))}u(r)})),f.on("close",(t=>{const r=performance.now()-w;d=!0,o.removeEventListener("abort",x),e.signal.removeEventListener("abort",P);const n=eC(y,C,E?void 0:this.stdoutDecodes.get(i)),s=Buffer.concat(v).toString("utf8");p(),l({...n,stderr:s,exitCode:t??0,timedOut:!1,stdoutByteCapped:C}),sC.histogram(e,w-g,{sandboxed:m}),C||_||o.aborted||e.signal.aborted||0!==t&&1!==t||iC.histogram(e,r,{output_mode:i.outputMode,sandboxed:m})}))}))}async checkOutsideTarget(e,t){if(1!==t.length||void 0===t[0])return{error:`Path '${e}' points to a different folder from each workspace root; use an absolute path`};const r=await xc(t[0]);return null===r?{error:z_(e)}:await this.ignoreService.isCursorIgnored(r)?{error:`Path '${e}' is filtered out by .cursorignore`}:await V_(t[0])?{error:G_(e)}:{resolvedTarget:r}}async execute(e,t,r){if(!Wl(this.encodingSlices,e))return this.search(e,t,r,void 0);const n=new nu,o=await this.search(e,t,r,n);return"success"===o.result.case&&tu(this.encodingSlices,e,{layer:"exec_grep",evidence:n.evidence(),partial:Y_(o)},o),o}async search(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{const a=H_(o,(0,D.VI)(e.withName("LocalGrepExecutor.execute")),!1),c=Array.isArray(this.workspacePath)?this.workspacePath:[this.workspacePath??process.cwd()],l=t.outputMode??"content";if("content"!==(i=l)&&"files_with_matches"!==i&&"count"!==i)throw new Error(`Unknown output mode: ${l}`);const u=l,d={toolCallId:t.toolCallId,execId:r?.execId,outputMode:u,targetPath:t.path,workspacePaths:c};void 0!==n&&this.stdoutDecodes.set(d,n);const h=ds(t.sandboxPolicy),p=this.grepProvider.getWorktreeGuardInfo?.(c);if((0,ts.fl)({targetPath:t.path,workspacePaths:c,mainWorktreePath:p?.mainWorktreePath}))return new Ry.Ud({result:{case:"error",value:new Ry.ts({error:ts.PS})}});const f=this.findOutsideTargets(t.path,c);let m=t,g=c;try{if(t.path&&void 0!==f){const r=await this.checkOutsideTarget(t.path,f);if("error"in r)return new Ry.Ud({result:{case:"error",value:new Ry.ts({error:r.error})}});void 0!==this.mcpStateAccessor&&Vy(e,this.mcpStateAccessor,r.resolvedTarget),g=c.slice(0,1),m=t.clone(),m.path=f[0]}else if(m.path){const t=[];let r=!1;for(const{root:n,resolvedRoot:o,target:s}of this.resolveSearchTargets(m.path,c)){if(!(0,ts.BJ)(s,o))continue;const i=await xc(s);if(null!==i)if(await this.ignoreService.isCursorIgnored(i))r=!0;else{if(await V_(s))return new Ry.Ud({result:{case:"error",value:new Ry.ts({error:G_(m.path)})}});t.push(n),void 0!==this.mcpStateAccessor&&Vy(e,this.mcpStateAccessor,i)}}if(0===t.length){const e=r?`Path '${m.path}' is filtered out by .cursorignore`:z_(m.path);return new Ry.Ud({result:{case:"error",value:new Ry.ts({error:e})}})}g=t}let r={};const n=void 0===f?await this.executeIndexedGrepWithTimeout(a.ctx,g,m,d):void 0;if(void 0!==n){r=n;for(const[e,t]of Object.entries(r)){const r=t.result;switch(r.case){case"content":r.value.matches=await this.filterBlockedFiles(r.value.matches,e);break;case"files":r.value.files=(await this.filterBlockedFiles(r.value.files.map((e=>({file:e}))),e)).map((({file:e})=>e));break;case"count":r.value.counts=await this.filterBlockedFiles(r.value.counts,e)}}}else{const e=await this.streamingEnabled(a.ctx,d),t=e?Z_(fC.MAIN_TIMEOUT_MS):void 0;let n=0,o=!1;try{for(const s of g){if(!0===t?.signal.aborted){r[s]=Q_(u),n++,o=!0;continue}if(!1===cC(s))return new Ry.Ud({result:{case:"error",value:new Ry.ts({error:`Path does not exist: ${s}`})}});const i=t??Z_(fC.MAIN_TIMEOUT_MS);try{const t=await this.runMode(a.ctx,u,s,m,e,i.signal,h,d);r[s]=t.result,t.timedOut&&n++}catch(t){if(!(t instanceof J_))throw t;if(r[s]=Q_(u),n++,o=!0,!e)break}finally{i!==t&&i.clear()}}}finally{t?.clear()}if(n>0){const t=o&&(!e||!Object.values(r).some(X_));if(this.reportDeadlineReached(a.ctx,d,{streaming:e,folderCount:g.length,stoppedFolderCount:n,outcome:t?"failed":"partial"}),t)throw fC.ripgrepTimeoutError()}}const o=function(e,t){if(t.length<=1)return e;const r=[...new Set(t.map((e=>(0,s.resolve)(e))))],n={};for(const[t,o]of Object.entries(e)){const e=(0,s.resolve)(t),i=t=>K_(e,t,r),a=o.result;switch(a.case){case"content":{const e=a.value,r=[];let o=0,s=0;for(const t of e.matches)i(t.file)?r.push(t):(o+=t.matches.length,s+=t.matches.filter((e=>!e.isContextLine)).length);const c=e.clone();c.matches=r,c.totalLines=Math.max(0,e.totalLines-o),c.totalMatchedLines=Math.max(0,e.totalMatchedLines-s),n[t]=new Ry.vD({result:{case:"content",value:c}});break}case"files":{const e=a.value,r=e.files.filter((e=>i(e))),o=e.clone();o.files=r,o.totalFiles=Math.max(0,e.totalFiles-(e.files.length-r.length)),n[t]=new Ry.vD({result:{case:"files",value:o}});break}case"count":{const e=a.value,r=[];let o=0;for(const t of e.counts)i(t.file)?r.push(t):o+=t.count;const s=e.clone();s.counts=r,s.totalFiles=Math.max(0,e.totalFiles-(e.counts.length-r.length)),s.totalMatches=Math.max(0,e.totalMatches-o),n[t]=new Ry.vD({result:{case:"count",value:s}});break}default:n[t]=o}}return n}(r,g),i=new Ry._0({pattern:m.pattern,path:void 0!==m.path&&this.isRootIndependentSearchPath(m.path)?(0,ts.o1)(m.path):m.path,outputMode:u,workspaceResults:o});return new Ry.Ud({result:{case:"success",value:i}})}catch(e){if(m.path){const e=(0,ts.o1)(m.path,this.singleWorkspacePath);try{await(0,xo.stat)(e)}catch(t){return new Ry.Ud({result:{case:"error",value:new Ry.ts({error:`Path does not exist: ${e}`})}})}}return new Ry.Ud({result:{case:"error",value:new Ry.ts({error:e instanceof Error?e.message:String(e)})}})}}catch(e){o.error=e,o.hasError=!0}finally{q_(o)}var i}}fC.MAIN_TIMEOUT_MS=25e3,fC.INDEXED_GREP_TIMEOUT_MS=25e3,fC.INDEXED_GREP_CONTEXT_TIMEOUT_MS=fC.INDEXED_GREP_TIMEOUT_MS+100,fC.HARD_MAX_OUTPUT_LINES=1e4,fC.CLIENT_LIMIT_LINES=2e3,fC.LINE_ENCODING_TIMEOUT_MS=2e3,Be.object({record_v:Be.number().int().nullish(),pid:Be.number().int().nonnegative().nullish(),version:Be.string().nullish(),started_at:Be.number().nullish(),control_sock:Be.string().nullish(),runtime_dir:Be.string().nullish(),data_dir:Be.string().nullish(),config_path:Be.string().nullish(),log_path:Be.string().nullish(),metrics_addr:Be.string().nullish(),exe:Be.string().nullish()}),Be.object({mountpoint:Be.string().nullish(),capabilities:Be.array(Be.string()).nullish(),nfs_transport:Be.string().nullish(),bind_ignored:Be.object({active:Be.array(Be.string()).nullish()}).passthrough().nullish()});const mC=Be.object({daemon_alive:Be.boolean().nullish(),mounts:Be.array(Be.unknown()).nullish(),data_plane:Be.object({enabled:Be.boolean().nullish()}).passthrough().nullish()});Be.object({daemon_alive:Be.boolean().nullish(),daemon_version:Be.string().nullish(),capabilities:Be.array(Be.string()).nullish()}),mC.extend({memory:Be.object({anon_bytes:Be.number()}).nullish().catch(null)});const gC=Be.number().int().nonnegative(),wC=Be.object({line_no:Be.number().int().positive(),kind:Be.enum(["match","before","after"]),text:Be.string().optional(),bytes:Be.string().regex(/^(?:[0-9a-fA-F]{2})*$/).optional(),truncated:Be.boolean().default(!1)}).refine((e=>void 0!==e.text||void 0!==e.bytes));Be.object({type:Be.literal("file"),path:Be.string(),lines:Be.array(wC)}),Be.object({type:Be.literal("summary"),files_searched:gC,more:Be.boolean(),stop_reason:Be.string().nullable(),skipped:Be.object({over_size:gC,size_unknown:gC,budget_exhausted:gC,fetch_failed:gC,unreadable:gC})}),Be.object({type:Be.string()}),(0,d.h)("local-exec/grove-grep"),(0,h.Pu)("local_exec.grep.grove",{description:"Grep searches Grove served, or declined to ripgrep, by decline reason",labelNames:["outcome","reason"]}),(0,h.v5)("local_exec.grep.grove.served_ms",{description:"Time Grove took to answer a Grep search it served"});var yC=r("../proto/dist/generated/agent/v1/ls_exec_pb.js"),vC=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},bC=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class SC{constructor(e,t,r){this.permissionsService=e,this.ignoreService=t,this.workspacePath=r}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{vC(r,(0,D.VI)(e.withName("LocalLsExecutor.execute")),!1).ctx;const n=(0,ts.o1)(t.path,this.workspacePath);try{let r;try{r=await(0,xo.stat)(n)}catch(e){return"ENOENT"===_c(e)?function(e){const t=sh(e,"terminals");return null!==t&&0===t.remainingPath.length}(n)?new yC.fv({result:{case:"error",value:new yC.uj({path:n,error:"No active terminals."})}}):new yC.fv({result:{case:"error",value:new yC.uj({path:n,error:`Path does not exist: ${n}`})}}):new yC.fv({result:{case:"error",value:new yC.uj({path:n,error:Cc(e)})}})}if(!r.isDirectory())return new yC.fv({result:{case:"error",value:new yC.uj({path:n,error:`Path is not a directory: ${n}`})}});const o=ds(t.sandboxPolicy),s=t.timeoutMs??5e3,i=e.withTimeout(s),{tree:a,didTimeout:c}=await this.getDirectoryTree(i,n,t.ignore,o);return c?new yC.fv({result:{case:"timeout",value:new yC.ze({directoryTreeRoot:a})}}):new yC.fv({result:{case:"success",value:new yC.PC({directoryTreeRoot:a})}})}catch(e){return new yC.fv({result:{case:"error",value:new yC.uj({path:n,error:e instanceof Error?e.message:"Unknown error occurred"})}})}}catch(e){r.error=e,r.hasError=!0}finally{bC(r)}}async getDirectoryTree(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{return vC(o,(0,D.VI)(e.withName("LocalLsExecutor.getDirectoryTree")),!1),await this.buildTreeFromRipgrepStream(e,t,r,n,2500)}catch(e){o.error=e,o.hasError=!0}finally{bC(o)}}async buildTreeFromRipgrepStream(e,t,r,n,o){const i={stack:[],error:void 0,hasError:!1};try{vC(i,(0,D.VI)(e.withName("LocalLsExecutor.buildTreeFromRipgrepStream")),!1);const a=(0,s.resolve)(t),c=new yC.vq({absPath:a,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!0,fullSubtreeExtensionCounts:{}}),l=new Map;l.set(a,c);const u={charactersUsed:a.length,budgetExceeded:!1},[d,h]=await Promise.all([this.ignoreService.listCursorIgnoreFilesByRoot(t),this.ignoreService.getRepoBlockExcludeGlobs(t)]),p=[...r,...h],{lines:f,didTimeout:m}=ya(e,{root:t,excludeGlobs:p,caseSensitive:!0,cursorIgnoreFiles:d,sandboxPolicy:n,source:"ls"});for await(const e of f){if(!e)continue;const r=(0,s.resolve)(t,e),n=await xc(r);null===n||await this.ignoreService.isCursorIgnored(n)||await this.ignoreService.isRepoBlocked(n)||this.addPathToTree(r,a,l,u,o)}return this.sortTreeChildren(c),{tree:c,didTimeout:await m}}catch(e){i.error=e,i.hasError=!0}finally{bC(i)}}addPathToTree(e,t,r,n,o){const i=(0,s.basename)(e),a=(0,s.dirname)(e);this.ensureDirectoryPath(a,t,r,n.budgetExceeded);const c=r.get(a);if(!c)return;const l=i.length;if(!n.budgetExceeded&&n.charactersUsed+l<=o){const e=new yC.ur({name:i});c.childrenFiles.push(e),n.charactersUsed+=l}else{if(!n.budgetExceeded){n.budgetExceeded=!0;let e=a;for(;e.startsWith(t);){const t=r.get(e);t&&(t.childrenWereProcessed=!1);const n=(0,s.dirname)(e);if(n===e)break;e=n}}let o=n.overflowChain;if(n.overflowDir!==a||void 0===o){o=[];let e=a;for(;e.startsWith(t);){const t=r.get(e);t&&o.push(t);const n=(0,s.dirname)(e);if(n===e)break;e=n}n.overflowDir=a,n.overflowChain=o}const i=(0,s.extname)(e);for(const e of o)e.fullSubtreeExtensionCounts[i]??=0,e.fullSubtreeExtensionCounts[i]=Dy(e.fullSubtreeExtensionCounts[i]+1),e.numFiles??=0,e.numFiles=Dy(e.numFiles+1)}}ensureDirectoryPath(e,t,r,n){if(r.has(e)||e===t)return;const o=(0,s.dirname)(e);o!==e&&o.startsWith(t)&&this.ensureDirectoryPath(o,t,r,n);const i=new yC.vq({absPath:e,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!n,fullSubtreeExtensionCounts:{}});r.set(e,i);const a=r.get(o);a&&a.childrenDirs.push(i)}sortTreeChildren(e){e.childrenDirs.sort(((e,t)=>(0,s.basename)(e.absPath).localeCompare((0,s.basename)(t.absPath)))),e.childrenFiles.sort(((e,t)=>e.name.localeCompare(t.name)));for(const t of e.childrenDirs)this.sortTreeChildren(t)}}class kC extends Error{constructor(e,t){super(`Tool ${e} not found, available tools: ${t.join(", ")}`),this.toolName=e,this.availableTools=t,this.name="McpToolNotFoundError"}}function _C(e){if(e instanceof kC)return!0;if(!(e instanceof Error)||"McpToolNotFoundError"!==e.name)return!1;const t=e;return"string"==typeof t.toolName&&Array.isArray(t.availableTools)}function CC(e){return!0===e.url?.startsWith("mcp-provider://")}function EC(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function xC(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function PC(e,t){return(t??[]).some((t=>{const r=EC(t.command),n=xC(t.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==e.command&&(0,Lb.mD)(r,e.command),s=void 0===n||void 0!==e.url&&(0,Lb.eA)(n,e.url);return o&&s}))}function RC(e,t){if(CC(e))return!1;const r=t?.rules??[];if(0===r.length)return!1;if(PC(e,r))return!0;const n=function(e){return e.flatMap((e=>{if(void 0===e.serverUrl)return[];const t=function(e){if(e.includes("*"))return e;const t=e.search(/[?#]/);return-1===t?e:e.slice(0,t)}(e.serverUrl);return t===e.serverUrl?[]:[{...e,serverUrl:t}]}))}(r);return n.length>0&&PC(e,n)}function IC(e,t){const{command:r,url:n}=e;return void 0!==r&&t.commandPatterns.some((e=>(0,Lb.mD)(e.trim(),r)))||void 0!==n&&t.serverUrlPatterns.some((e=>(0,Lb.eA)(e.trim(),n)))}var TC=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class AC extends Error{constructor(e){super(`MCP server "${e}" is disabled`),this.name="McpServerDisabledError"}}class $C extends Error{constructor(e){super(`MCP server "${e}" has not been approved`),this.serverName=e,this.name="McpServerNotApprovedError"}}class MC extends Error{constructor(e,t){super(`MCP server "${e}" is overridden by ${t}`),this.serverName=e,this.overridingConfigPath=t,this.name="McpServerOverriddenError"}}class DC{constructor(e){this.disabledService=e}async load(e,t,r,n,o){if(await this.disabledService.isServerDisabled(t))throw new AC(t);return await o(e,r)}}class OC{constructor(e){this.approvalService=e}async load(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{if(function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(s,(0,D.VI)(e.withName("ServerApprovalMiddleware.load")),!1),!await this.approvalService.isServerApproved(t,r,n))throw new $C(t);return await o(e,r)}catch(e){s.error=e,s.hasError=!0}finally{TC(s)}}}class FC{constructor(e,t){this.approvalsPath=e,this.cwd=t,this.approvalsPromise=this.loadApprovals()}async isServerApproved(e,t,r){const n=function(e,t,r){const n={path:r,server:t};return`${e}-${(0,ko.createHash)("sha256").update(JSON.stringify(n)).digest("hex").substring(0,16)}`}(e,t,this.cwd);return(await this.getApprovals()).includes(n)}async loadApprovals(){try{const e=await(0,xo.readFile)(this.approvalsPath,"utf8"),t=JSON.parse(e);return Array.isArray(t)?t:(await this.saveApprovalsToFile([]),[])}catch(e){if(e instanceof Error&&e.message.includes("ENOENT"))return[];throw e}}async getApprovals(){return this.approvalsPromise}async addApproval(e){const t=await this.approvalsPromise;t.includes(e)||(t.push(e),await this.saveApprovals(t))}async addApprovals(e){const t=await this.approvalsPromise,r=e.filter((e=>!t.includes(e)));r.length>0&&(t.push(...r),await this.saveApprovals(t))}async removeApproval(e){const t=await this.approvalsPromise,r=t.filter((t=>t!==e));r.length!==t.length&&await this.saveApprovals(r)}async clearApprovals(e){const t=await this.approvalsPromise,r=e?t.filter((t=>!e(t))):[];r.length!==t.length&&await this.saveApprovals(r)}async saveApprovalsToFile(e){await(0,xo.mkdir)(s.dirname(this.approvalsPath),{recursive:!0}),await(0,xo.writeFile)(this.approvalsPath,JSON.stringify(e,null,2))}async saveApprovals(e){await this.saveApprovalsToFile(e),this.approvalsPromise=Promise.resolve(e)}}const NC=["https://api.cursor.com","https://api2.cursor.sh"],LC=["CURSOR_API_BASE_URL","CURSOR_BACKEND_URL"],jC=/^MCP server ".+" is blocked by \S/u;function UC(e){if(void 0!==e&&""!==e)try{return new URL(e).origin}catch{return}}function BC(e,t=process.env){if(void 0===e)return!1;let r;try{r=new URL(e)}catch{return!1}if("/v1/agent/mcp"!==r.pathname.replace(/\/+$/,"")&&!r.pathname.startsWith("/internal/agent-serve/agent-sdk-mcp-relay/"))return!1;const n=new Set(NC);for(const e of LC){const r=UC(t[e]);void 0!==r&&n.add(r)}return n.has(r.origin)}function WC(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function HC(e,t){if("string"!=typeof e)return;const r=e.trim();return""===r||r.length>t||/\p{Cc}/u.test(r)?void 0:r}function qC(e){if(!Array.isArray(e))return;const t=[];for(const r of e.slice(0,200)){const e=HC(r,200);void 0!==e&&t.push(e)}return t}function zC(e,t){const r=t.slice(0,20).join(", "),n=t.length-20;return n>0?` ${e}: ${r}, and ${n} more.`:` ${e}: ${r}.`}var GC=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},VC=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class KC{async load(e,t,r,n,o){const s=o(e,r);return new ZC(e,t,s,r)}}function JC(e){let t;return e.then((e=>{t=e})).catch((()=>{})),t}class ZC{constructor(e,t,r,n){this.serverName=t,this.clientPromise=r,this.config=n,this.clientPromiseTraceId=(0,D.fU)(e)?.spanContext()?.traceId,this.toolsPromise=this.clientPromise.then((async t=>null===t?[]:await t.getTools(e))),this.resourcesPromise=this.clientPromise.then((async t=>null===t?[]:(await t.listResources(e)).resources)),this.promptsPromise=this.clientPromise.then((async t=>null===t?[]:await t.listPrompts(e))),this.toolsPromise.catch((()=>{})),this.resourcesPromise.catch((()=>{})),this.promptsPromise.catch((()=>{}))}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=GC(t,(0,D.VI)(e.withName("CachedMcpClient.getTools")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=JC(this.toolsPromise);return void 0!==n?n:await this.toolsPromise}catch(e){t.error=e,t.hasError=!0}finally{VC(t)}}async callTool(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{const i=GC(s,(0,D.VI)(e.withName("CachedMcpClient.callTool")),!1),a=await this.getClient(i.ctx);if(null===a)throw new Error("Client is not ready");return a.callTool(i.ctx,t,r,n,o)}catch(e){s.error=e,s.hasError=!0}finally{VC(s)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=GC(t,(0,D.VI)(e.withName("CachedMcpClient.getInstructions")),!1),n=await this.getClient(r.ctx);if(null===n)return;return await n.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{VC(t)}}async getClient(e){const t={stack:[],error:void 0,hasError:!1};try{const r=GC(t,(0,D.VI)(e.withName("CachedMcpClient.getClient")),!1);return r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined"),await this.clientPromise}catch(e){t.error=e,t.hasError=!0}finally{VC(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{const r=GC(t,(0,D.VI)(e.withName("CachedMcpClient.listResources")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=JC(this.resourcesPromise);return void 0!==n?{resources:n}:{resources:await this.resourcesPromise}}catch(e){t.error=e,t.hasError=!0}finally{VC(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=GC(r,(0,D.VI)(e.withName("CachedMcpClient.readResource")),!1),o=await this.getClient(n.ctx);return null===o?{contents:[]}:o.readResource(n.ctx,t)}catch(e){r.error=e,r.hasError=!0}finally{VC(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{const r=GC(t,(0,D.VI)(e.withName("CachedMcpClient.listPrompts")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=JC(this.promptsPromise);return void 0!==n?n:await this.promptsPromise}catch(e){t.error=e,t.hasError=!0}finally{VC(t)}}async getPrompt(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=GC(n,(0,D.VI)(e.withName("CachedMcpClient.getPrompt")),!1),s=await this.getClient(o.ctx);return null===s?{messages:[]}:s.getPrompt(o.ctx,t,r)}catch(e){n.error=e,n.hasError=!0}finally{VC(n)}}async getState(e){const t={stack:[],error:void 0,hasError:!1};try{const r=GC(t,(0,D.VI)(e.withName("CachedMcpClient.getState")),!1);r.span.setAttribute("serverName",this.serverName);const n=await this.getClient(r.ctx);if(null===n)throw new Error("Client is not ready");return await n.getState(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{VC(t)}}async getAllowlistInUse(){try{await this.toolsPromise;const e=await this.clientPromise;return await(e?.getAllowlistInUse?.())}catch{return}}async getAllowlistRefusal(){if(void 0!==this.config&&"url"in this.config&&BC(this.config.url))try{return void await this.toolsPromise}catch(e){return function(e){const t=e instanceof Error?e.message:"string"==typeof e?e:void 0;if(void 0===t)return;const r=t.indexOf("{");if(-1===r)return;let n;try{n=JSON.parse(t.slice(r))}catch{return}if(!WC(n))return;const o=HC(n.error,700);return void 0!==o&&jC.test(o)?o:void 0}(e)}}async close(){try{const e=await this.clientPromise;await(e?.close?.())}catch{}}}function XC(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function QC(e,t){if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e||"bigint"==typeof e)return String(e);if(null==e)return t;try{const r=JSON.stringify(e);return"string"==typeof r?r:t}catch{return t}}function YC(e){return e?` (${QC(e,"")})`:""}function eE(e){if(null===e||"string"==typeof e||"boolean"==typeof e)return e;if("number"==typeof e)return Number.isFinite(e)?e:void 0;if(Array.isArray(e)){const t=[];for(const r of e){if(void 0===r){t.push(null);continue}const e=eE(r);if(void 0===e)return;t.push(e)}return t}if("object"!=typeof e)return;const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&null!==t)return;const r={};for(const[t,n]of Object.entries(e)){if(void 0===n)continue;const e=eE(n);if(void 0===e)return;r[t]=e}return r}function tE(e){const t=eE(e);if(null!=t&&"object"==typeof t&&!Array.isArray(t))return t}const rE=new TextDecoder("utf-8",{fatal:!0});function nE(e){return"string"==typeof e?e.split(";")[0]?.trim().toLowerCase()??"":""}function oE(e,t){const r=Buffer.from(t,"base64"),n=function(e){try{const t=rE.decode(e);return t.includes("\0")?void 0:t}catch{return}}(r)??(function(e){const t=nE(e);return t.startsWith("text/")||"application/xml"===t||t.endsWith("+xml")}(e.mimeType)?r.toString("utf8").replace(/^\uFEFF/,""):void 0);if(void 0!==n)return{text:n,binary:!1};const o="string"==typeof e.mimeType&&e.mimeType.length>0?e.mimeType:"unknown type";return{text:`[Binary resource: ${QC(e.uri,"unknown")} (${o}, ${r.byteLength} bytes). The file is not text, so its contents are not included.]`,binary:!0}}const sE=new Set(["image/png","image/jpeg","image/jpg","image/gif","image/webp"]);function iE(e){return"string"==typeof e.text&&e.text.length>0?e.text:void 0}function aE(e){if(!XC(e))return;const t=e.resource;return XC(t)&&void 0===iE(t)&&"string"==typeof t.blob&&sE.has(nE(t.mimeType))?t.blob:void 0}function cE(e){const t=e,r=t.resource;if(XC(r)){const e=iE(r);return void 0!==e?e:"string"==typeof r.blob?oE(r,r.blob).text:`Resource: ${QC(r.uri,"unknown")}${YC(r.name)}`}return t.uri?`Resource: ${QC(t.uri,"unknown")}${YC(t.name)}`:`Unsupported content type "${e.type}": ${JSON.stringify(e)}`}function lE(e){const t=tE(e);if(void 0!==t&&0!==Object.keys(t).length)try{return Buffer.byteLength(JSON.stringify(t))<=262144?t:void 0}catch{return}}var uE=r("zod/v4-mini");const dE=uE.object({CLIENT_ID:uE.string(),CLIENT_SECRET:uE.optional(uE.string()),scopes:uE.optional(uE.array(uE.string()))}),hE=uE.strictObject({caBundle:uE.string().check(uE.trim(),uE.minLength(1),uE.maxLength(131072))}),pE=uE.object({type:uE.optional(uE.literal("stdio")),command:uE.string(),args:uE.optional(uE.array(uE.string())),env:uE.optional(uE.record(uE.string(),uE.string())),envFile:uE.optional(uE.string()),cwd:uE.optional(uE.string()),enabledTools:uE.optional(uE.array(uE.string())),startupTimeoutSec:uE.catch(uE.optional(uE.number().check(uE.positive())),void 0)}),fE=uE.object({type:uE.optional(uE.enum(["http","sse"])),url:uE.string(),headers:uE.optional(uE.record(uE.string(),uE.string())),auth:uE.optional(dE),tls:uE.optional(hE),placement:uE.optional(uE.enum(["server","client"])),enabledTools:uE.optional(uE.array(uE.string()))}),mE=uE.union([pE,fE]),gE=uE.object({mcpServers:uE.record(uE.string(),mE)});Error;const wE=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g;function yE(e,t){if("string"==typeof e)return function(e,t){return e.replace(wE,((e,r,n,o)=>{if(void 0!==r){const n=t(r);return void 0!==n?n:e}if(void 0===n)return e;const s=t(n);return void 0!==s?s:void 0!==o?o:e}))}(e,t);if(Array.isArray(e))return e.map((e=>yE(e,t)));if(null!==e&&"object"==typeof e){const r={};for(const[n,o]of Object.entries(e))r[n]=yE(o,t);return r}return e}r("../../node_modules/.pnpm/smol-toml@1.9.0/node_modules/smol-toml/dist/index.js");Symbol("invalid");function vE(e){const t=Object.entries(e);return{jsonKeyOf:new Map(t.map((([e,t])=>[t,e]))),tomlKeyOf:new Map(t)}}const bE=vE({CLIENT_ID:"client_id",CLIENT_SECRET:"client_secret",scopes:"scopes"}),SE=vE({caBundle:"ca_bundle"}),kE=vE({type:"type",command:"command",args:"args",env:"env",envFile:"env_file",cwd:"cwd",enabledTools:"enabled_tools",startupTimeoutSec:"startup_timeout_sec"}),_E=vE({type:"type",url:"url",headers:"http_headers",auth:"auth",tls:"tls",placement:"placement",enabledTools:"enabled_tools"}),CE=(new Map([["auth",{keys:bE,unknownKeyIsError:!1}],["tls",{keys:SE,unknownKeyIsError:!0}]]),"enabled");new Set([...kE.jsonKeyOf.keys(),..._E.jsonKeyOf.keys(),CE]);Symbol("disabled");const EE=(0,d.h)("McpConfig");async function xE(e,t=e=>process.env[e]){try{const r=await(0,xo.readFile)(e,"utf8"),n=yE((0,xp.qg)(r),t);return gE.parse(n)}catch{return{mcpServers:{}}}}async function PE(e,t=e=>process.env[e]){const r={config:{mcpServers:{}},diagnostics:[]};return r}async function RE(e,t=e=>process.env[e]){const{config:r,diagnostics:n}=await PE(0,t);return n.length>0&&EE.warn((0,b.q6)(),"[mcp config] problems in MCP config; `agent mcp list` shows them",{errorCount:n.filter((e=>"error"===e.severity)).length,warningCount:n.filter((e=>"warning"===e.severity)).length,fileNames:[...new Set(n.map((e=>s.basename(e.file))))]}),r}const IE=["enterprise","project","user","env"];function TE(e){return"project"===e||"env"===e}const AE=["0.0.0.0/0","::/0"];function $E(e){const t=(e??[]).filter((e=>e.trim().length>0)),r=t.flatMap((e=>{const t=(0,Lb.bi)(e);return void 0===t?[]:[t]}));return{hasInvalidEntries:r.length!==t.length,entries:r}}function ME(e){const t=!0===e.enabled,r=$E(e.mcpNetworkDenylist),n="deny_all"===e.mcpNetworkMode||r.entries.includes("*")||r.hasInvalidEntries,o=t?function(e){if("allow_all"===e.mcpNetworkMode)return[...AE];const t=$E(e.mcpNetworkAllowlist);if("allowlist"===e.mcpNetworkMode)return t.entries.includes("*")?[...AE]:t.entries;if(!function(e){return(e.mcpNetworkAllowlist??[]).some((e=>e.trim().length>0))}(e))return[...AE];const r=(0,Lb.b6)(e);return r.includes("*")?[...AE]:r}(e):[],s=t?n?["*"]:r.entries:[];return JSON.stringify({enabled:t,mode:e.mcpNetworkMode,allow:n?[]:o,deny:s})}class DE extends Error{constructor(e,t){super(`MCP server "${e}" wasn't started: your team's MCP settings require it to run in a sandbox, and the sandbox isn't supported on this machine. Ask a team admin to review the team's MCP settings for this server.`),this.serverName=e,this.name="McpSandboxUnavailableError",void 0!==t&&(this.cause=t)}}const OE=new Set(["invalid_auth","not_authed","account_inactive","token_revoked","token_expired"]);class FE extends Error{constructor(){super("Your organization admin only allows Slack workspaces your company manages. Connect your company Slack workspace instead."),this.name="SlackWorkspaceNotManagedError"}}class NE extends Error{constructor(){super("Slack couldn't confirm which workspace this connection is for, and your organization admin only allows the Slack workspaces your company manages. Try again in a moment."),this.name="SlackWorkspaceUnconfirmedError"}}function LE(e){return URL.canParse(e)&&"mcp.slack.com"===new URL(e).hostname.toLowerCase()}function jE(e,t){const r=new Map,n=t.lookUpWorkspace??(t=>async function(e,t){let r;try{const n=await e("https://slack.com/api/auth.test",{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/x-www-form-urlencoded"},signal:AbortSignal.timeout(5e3)});r=await n.json()}catch{return{kind:"unavailable"}}if("object"!=typeof r||null===r)return{kind:"unavailable"};if("object"!=typeof(n=r)||null===n||Array.isArray(n))return{kind:"unavailable"};var n;const o=r;return!0!==o.ok?"string"==typeof o.error&&OE.has(o.error)?{kind:"dead"}:{kind:"unavailable"}:"string"!=typeof o.team_id||0===o.team_id.length?{kind:"unavailable"}:"string"==typeof o.enterprise_id&&o.enterprise_id.length>0?{kind:"found",slackTeamId:o.team_id,slackEnterpriseId:o.enterprise_id}:{kind:"found",slackTeamId:o.team_id}}(e,t));let o,s=[];return async(i,a)=>{if(!LE(function(e){return"string"==typeof e?e:e instanceof URL?e.href:e.url}(i)))return e(i,a);const c=function(e,t){const r=new Headers(t?.headers??(e instanceof Request?e.headers:void 0)),n=/^Bearer\s+(.+)$/i.exec(r.get("authorization")??"");return n?.[1]?.trim()||void 0}(i,a);if(void 0===c)return e(i,a);const l=await((void 0===o||Date.now()-o.atMs>=3e4)&&(o={atMs:Date.now(),lists:t.managedSlackWorkspaceLists().then((e=>"unconfirmed"===e?e:(s=e.filter((e=>e.length>0)).map((e=>e.map((e=>e.toUpperCase())))),s)),(()=>s))}),o.lists);if("unconfirmed"===l)throw new NE;if(0===l.length)return e(i,a);let u=r.get(c);if(void 0===u){const t=await n(c);if("dead"===t.kind)return e(i,a);if("unavailable"===t.kind)throw new NE;r.size>=64&&r.clear(),r.set(c,t),u=t}const d=[u.slackTeamId,u.slackEnterpriseId].flatMap((e=>void 0===e?[]:[e.toUpperCase()]));if(!l.every((e=>d.some((t=>e.includes(t))))))throw new FE;return e(i,a)}}function UE(e,t,r){if("string"==typeof e)return t(e);if(!(e instanceof Error))return e;if(r.results.has(e))return r.results.get(e)===e&&r.cycled.add(e),r.results.get(e);r.results.set(e,e);const n=Object.isFrozen(e)&&JE(e,t)?new Error:void 0;void 0!==n&&r.results.set(e,n);const o=t(e.message),s="string"==typeof e.stack?t(e.stack):void 0,i=Object.keys(e).flatMap((n=>{if("cause"===n)return[];const o=HE(e,n),s=VE(o,t,r);return Object.is(s,o)?[]:[[n,s]]})),a=Object.getOwnPropertyDescriptor(e,"cause"),c=void 0===a?void 0:HE(e,"cause"),l=VE(c,t,r),u=e instanceof AggregateError?HE(e,"errors"):void 0,d=function(e,t,r){if(!Array.isArray(e))return e;const n=e.map((e=>VE(e,t,r)));if(n.every(((t,r)=>Object.is(t,e[r]))))return e;try{return n.forEach(((t,r)=>{e[r]=t})),e}catch{return n}}(u,t,r),h=[...i,...Object.is(l,c)?[]:[["cause",l]],...Object.is(d,u)?[]:[["errors",d]]];let p=!1;if(void 0===n)try{o!==e.message&&(e.message=o),void 0!==s&&s!==e.stack&&(e.stack=s),p=e.message===o&&(void 0===s||e.stack===s)&&h.every((([t,r])=>WE(e,t,r)))}catch{}if(p)return e;const f=Object.defineProperties(n??new Error,{message:{value:o,writable:!0,enumerable:!1,configurable:!0},...Object.getOwnPropertyDescriptors(zE(e,new Map(i)))});Array.isArray(d)&&Object.defineProperty(f,"errors",{value:d,writable:!0,enumerable:!1,configurable:!0}),void 0!==a&&Object.defineProperty(f,"cause",{value:l,writable:!0,enumerable:!0===a.enumerable,configurable:!0});const m=Object.getPrototypeOf(e);null!==m&&"object"==typeof m&&m!==Error.prototype&&(Object.setPrototypeOf(f,m),function(e){try{let t=Object.getPrototypeOf(e);for(let r=0;r<8&&null!==t&&"object"==typeof t&&t!==Error.prototype&&t!==Object.prototype;r++){for(const r of Reflect.ownKeys(t)){const n=Object.getOwnPropertyDescriptor(t,r)?.get;void 0!==n&&Reflect.apply(n,e,[])}t=Object.getPrototypeOf(t)}String(e);const r=e;"function"==typeof r.toJSON&&Reflect.apply(r.toJSON,e,[""]);const n=r[qE];return"function"==typeof n&&Reflect.apply(n,e,[0,{depth:0,stylize:String},String]),!0}catch{return!1}}(f)||Object.setPrototypeOf(f,Error.prototype));const g=QE(e);return void 0!==g&&QE(f)!==g&&Object.defineProperty(f,"name",{value:g,writable:!0,configurable:!0,enumerable:!1}),void 0!==s&&(f.stack=s),r.results.set(e,f),f}function BE(e,t){if(e instanceof Error)return t.get(e)??e;if(!Array.isArray(e)||!Object.isFrozen(e))return e;const r=e.map((e=>e instanceof Error?t.get(e)??e:e));return r.every(((t,r)=>Object.is(t,e[r])))?e:r}function WE(e,t,r){const n=Object.getOwnPropertyDescriptor(e,t);return!0===n?.writable&&Reflect.defineProperty(e,t,{...n,value:r})}function HE(e,t){try{const r=Object.getOwnPropertyDescriptor(e,t);return void 0===r?.get?r?.value:r.get.call(e)}catch{return}}const qE=Symbol.for("nodejs.util.inspect.custom");function zE(e,t){const r={};for(const n of Object.keys(e))try{const o=Object.getOwnPropertyDescriptor(e,n),s=void 0===o?.get?o?.value:o.get.call(e);Object.defineProperty(r,n,{value:t.has(n)?t.get(n):s,writable:!0,enumerable:!0,configurable:!0})}catch{}return r}function GE(e,t,r,n){if("string"==typeof e)return t(e);if("object"!=typeof e||null===e)return e;if(e instanceof Error)return UE(e,t,n);if(Array.isArray(e)){if(r>=4)return;return e.slice(0,64).map((e=>GE(e,t,r+1,n)))}const o=Object.getPrototypeOf(e);return o!==Object.prototype&&null!==o?e:r>=4?void 0:function(e,t,r,n){const o={};for(const s of Object.keys(e).slice(0,64))try{const i=Object.getOwnPropertyDescriptor(e,s),a=void 0===i?.get?i?.value:i.get.call(e);Object.defineProperty(o,s,{value:GE(a,t,r,n),writable:!0,enumerable:!0,configurable:!0})}catch{}return o}(e,t,r+1,n)}function VE(e,t,r){if(e instanceof Error)return UE(e,t,r);try{return JE(e,t)?GE(e,t,1,r):e}catch{return}}const KE=4096;function JE(e,t){const r=new Set,n=[e];for(let o=0;n.length>0;o++){if(o>=KE||n.length>KE)return ZE(e,t);const s=n.pop();if("string"==typeof s){if(t(s)!==s)return!0}else if((XE(s)||s instanceof Error)&&!r.has(s)){r.add(s),s instanceof Error&&(n.push(HE(s,"message"),HE(s,"stack"),HE(s,"cause")),s instanceof AggregateError&&n.push(HE(s,"errors")));for(const e of Object.keys(s))n.push(HE(s,e))}}return!1}function ZE(e,t){const r=new Set;let n;try{n=JSON.stringify(e,((e,t)=>{return"bigint"==typeof t?t.toString():"object"!=typeof t||null===t?t:r.has(t)?void 0:(r.add(t),t instanceof Error?(n=t,{...Object.fromEntries(Object.keys(n).map((e=>[e,HE(n,e)]))),message:HE(n,"message"),stack:HE(n,"stack"),cause:HE(n,"cause"),...n instanceof AggregateError?{errors:HE(n,"errors")}:{}}):t);var n}))}catch{return!0}return void 0!==n&&t(n)!==n}function XE(e){if(Array.isArray(e))return!0;if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function QE(e){try{return"string"==typeof e.name?e.name:void 0}catch{return}}const YE=/spt_[A-Za-z0-9_]{6,}/g,ex=/[A-Z0-9]/;function tx(e){return function(e){return e.replace(YE,(e=>function(e){return e.slice(4).split("_").some((e=>e.length>=8&&ex.test(e)))}(e)?"[redacted Link shared payment token]":e))}(e)}var rx=r("../../node_modules/.pnpm/string-argv@0.3.2/node_modules/string-argv/index.js");new Set(["EAI_AGAIN","ECONNABORTED","ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ENOTFOUND","EPIPE","ETIMEDOUT","EADDRNOTAVAIL","UND_ERR_CONNECT_TIMEOUT"]),new Set(["ECONNRESET","EPIPE"]);const nx=new Set([429,502,503,504]);function ox(e){return"object"==typeof e&&null!==e}function sx(e){const t=ox(e)?e.code:void 0,r=(e instanceof Error||ox(e)&&"string"==typeof e.message?e.message:"").match(/\(HTTP (\d+)\)|Non-200 status code \((\d+)\)|\bHTTP\s+(\d{3})\b/i),n=r?.[1]??r?.[2]??r?.[3],o=void 0!==n?parseInt(n,10):void 0;if("number"==typeof t&&t>=100)return void 0!==o&&nx.has(o)&&!nx.has(t)?o:t;if("string"==typeof t&&/^\d{3}$/.test(t)){const e=Number.parseInt(t,10);return e>=100&&e<=599?e:o}return o}new Set(["UND_ERR_SOCKET","UND_ERR_CLOSED","ECONNRESET"]);const ix=8192;function ax(e){return void 0===e?"unknown":"url"in e&&e.url.length>0?void 0!==lb(e.url)?"rest_mcp":"streamable_http":"command"in e?"stdio":"unknown"}new Set(["ENOENT","EACCES","ENOTDIR","EPERM"]);const cx=/\$\{[^}]*\}/;function lx(e){if(void 0!==function(e){if(void 0===e)return;const t=e.trim();return 0!==t.length&&cx.test(t)?t:void 0}(e))return;const t=e?.trim();return t&&t.length>0?t:void 0}const ux=new Map;async function dx(e,t=fetch){if(void 0===lb(e))return;const r=new URL(e),n=`${r.origin}/.well-known/oauth-protected-resource${r.pathname.replace(/\/+$/,"")}`,o=ux.get(n);if(void 0!==o&&o.expiresAtMs>Date.now())return o.metadata;let s;try{const e=await t(n);if(!e.ok)return;s=function(e){if("object"!=typeof(t=e)||null===t)return{};var t;const r=e,n="string"==typeof r.cursor_client_id&&r.cursor_client_id.length>0?r.cursor_client_id:void 0;let o;if("object"==typeof r.cursor_authorization_params&&null!==r.cursor_authorization_params){const e=Object.entries(r.cursor_authorization_params).filter((e=>"string"==typeof e[1]));e.length>0&&(o=Object.fromEntries(e))}return{...void 0!==n?{clientId:n}:{},...!0===r.cursor_omit_resource_indicator?{omitResourceIndicator:!0}:{},...!0===r.cursor_omit_consent_prompt?{omitConsentPrompt:!0}:{},...void 0!==o?{authorizationParams:o}:{},...!0===r.cursor_rejects_custom_scheme_redirects?{rejectsCustomSchemeRedirects:!0}:{},...!0===r.cursor_unauthenticated_connect?{unauthenticatedConnect:!0}:{},...!0===r.cursor_loopback_ipv4?{loopbackIpv4:!0}:{},...!0===r.cursor_backend_only_token_exchange?{backendOnlyTokenExchange:!0}:{}}}(await e.json())}catch{return}return ux.set(n,{metadata:s,expiresAtMs:Date.now()+3e5}),s}(0,Es.J)((function(){ux.clear()}));const hx={info:()=>{},warn:()=>{},error:()=>{},debug:()=>{}};function px(e){return hx}const fx=/^[\x21\x23-\x5B\x5D-\x7E]+$/,mx=["invalid_request","invalid_token","insufficient_scope"];function gx(e){return mx.some((t=>t===e))}function wx(e){const t=new Set;for(const r of e)r.length<=200&&fx.test(r)&&t.add(r);return[...t]}const yx=/[!#$%&'*+.^_`|~0-9A-Za-z-]+/y,vx=/"((?:[^"\\]|\\.)*)"?/y,bx=/[^\s,]*/y;function Sx(e,t){let r,n=0;const o=t=>{t.lastIndex=n;const r=t.exec(e);return null!==r&&(n=t.lastIndex),r};for(;n"string"==typeof e&&e.length>0)):void 0}function Cx(e){if("object"!=typeof e||null===e||Array.isArray(e))return kx;const t=_x("grantedScopes"in e?e.grantedScopes:void 0),r=_x("requestedScopes"in e?e.requestedScopes:void 0);return{...void 0!==t?{grantedScopes:t}:{},stepUpScopes:_x("stepUpScopes"in e?e.stepUpScopes:void 0)??[],signInMissing:_x("signInMissing"in e?e.signInMissing:void 0)??[],...void 0!==r?{requestedScopes:r}:{}}}function Ex(e){return(e??"").split(/\s+/).filter((e=>e.length>0))}function xx(e,t){return e.filter((e=>!t.has(e)))}function Px(e){const t=Cb(e.serverUrl),r=e.connectorName??t?.displayName??e.accountKey,n=px(e.accountKey);let o;const s=async()=>Cx(await e.readRecord()),i=async t=>{if(void 0!==t.grantedScopes)return t.grantedScopes;const r=Ex(await e.readTokenScope());return r.length>0?r:void 0},a=(e,t)=>{n.info(`MCP OAuth scope step-up: ${e}`,{event:`mcp_oauth_scope_step_up_${e}`,...t})};return{accountKey:e.accountKey,connectorName:r,async decide(r){if(401!==r.status&&403!==r.status)return;const n=function(e){const t=e??"",r=Sx(t,"error")?.toLowerCase(),n=Sx(t,"resource_metadata");return{error:void 0===r||""===r?"none":gx(r)?r:"other",scopes:wx((Sx(t,"scope")??"").split(/\s+/)),resourceMetadata:void 0===n||""===n?void 0:n}}(r.wwwAuthenticate);if("insufficient_scope"!==n.error||0===n.scopes.length)return;if(function(e){try{return Eb.has(new URL(e).hostname.toLowerCase())}catch{return!1}}(e.serverUrl))return;const o=function(e,t){if(void 0!==t)try{return new URL(t).origin===new URL(e).origin?t:void 0}catch{return}}(e.serverUrl,n.resourceMetadata),c=void 0===t?await e.readScopesSupported(o).catch((()=>{})):void 0,l=await s(),u=await i(l),{accepted:d,dropped:h}=function(e){const t=new Set(e.granted??[]),r=[],n=[];for(const o of wx(e.named))e.allowlist.has(o)?t.has(o)||r.push(o):n.push(o);return{accepted:r,dropped:n}}({named:n.scopes,allowlist:(p={policy:t,scopesSupported:c,configuredScopes:e.configuredScopes},void 0!==p.policy?new Set([...p.policy.baseScopes,...Object.keys(p.policy.stepUpScopes)]):new Set([...p.scopesSupported??[],...p.configuredScopes??[]])),granted:u});var p;if(0===d.length)return void a("none_accepted",{status:r.status,namedCount:n.scopes.length,droppedCount:h.length});const f=new Set(l.signInMissing),m=d.every((e=>f.has(e)))?"blocked":"offer";return"offer"===m&&await e.writeRecord({...l,...void 0!==u?{grantedScopes:u}:{},stepUpScopes:[...new Set([...l.stepUpScopes,...d])]}),a(m,{status:r.status,acceptedCount:d.length,droppedCount:h.length}),{kind:m,status:r.status,scopes:d,dropped:h,toolName:r.toolName,resourceMetadataUrl:o}},signIn:async e=>(void 0===o&&(o=Promise.resolve().then(e).finally((()=>{o=void 0}))),o),get isSigningIn(){return void 0!==o},tokensForSdk(e){if(void 0===o||void 0===e?.refresh_token)return e;const{refresh_token:t,...r}=e;return r},async prepareAuthorization(){const t=await s();return{stepUpScopes:t.stepUpScopes.length>0?[...new Set([...await i(t)??[],...t.stepUpScopes])]:[],recordRequestedScopes:async t=>{await e.writeRecord({...await s(),requestedScopes:Ex(t.searchParams.get("scope"))})}}},async recordTokens(t,{isRefresh:r}){const n=await e.readRecord();if(void 0===n)return;const o=Cx(n),s=Ex(t.scope);if(r)return void(s.length>0&&await e.writeRecord({...o,grantedScopes:s}));if(void 0===o.requestedScopes)return;const i=s.length>0?s:o.requestedScopes,c=new Set(i),l=xx(o.requestedScopes,c);await e.writeRecord({grantedScopes:i,stepUpScopes:xx(o.stepUpScopes,c),signInMissing:l}),a("sign_in_recorded",{grantedCount:i.length,signInMissingCount:l.length,scopeReported:s.length>0})},async clear(t){await e.writeRecord(!0===t?.keepPendingScopes?function(e){const{stepUpScopes:t}=Cx(e);return t.length>0?{stepUpScopes:t,signInMissing:[]}:void 0}(await e.readRecord()):void 0)}}}function Rx(e){const t=Cb(e.serverUrl);for(const r of e.scopes){const e=t?.stepUpScopes[r]?.action;if(void 0!==e)return e}return e.toolTitle}function Ix(e){const t=function(e){return void 0===e.action?`${e.connectorName} needs a permission its sign-in did not grant.`:`${e.connectorName} needs one more permission to ${e.action}.`}({connectorName:e.connectorName,action:Rx(e)}),r="offer"===e.kind?`Authorize ${e.connectorName} again to approve it; the turn can continue once it's granted.`:`Its last sign-in did not grant ${1===e.scopes.length?"it":"them"}, so an admin or your consent is blocking this. Reconnect ${e.connectorName} from its MCP settings to ask again.`,n=function(e){if(0===e.length)return;const t=e.slice(0,3).join(", "),r=e.length-3;return`${1===e.length?"Permission":"Permissions"}: ${t}${r>0?` and ${r} more`:""}`}(e.scopes);return void 0===n?`${t} ${r}`:`${t} ${r}\n${n}`}class Tx extends Error{constructor(e,t,r){super(Ix({kind:e.kind,serverUrl:t,connectorName:r,scopes:e.scopes,toolTitle:e.toolName})),this.decision=e,this.serverUrl=t,this.connectorName=r,this.name="McpOAuthScopeStepUpError"}answerWithToolTitle(e){return Ix({kind:this.decision.kind,serverUrl:this.serverUrl,connectorName:this.connectorName,scopes:this.decision.scopes,toolTitle:e??this.decision.toolName})}}function Ax(e){if("string"!=typeof e)return;let t;try{t=JSON.parse(e)}catch{return}const r=Array.isArray(t)?t:[t];for(const e of r){if("object"!=typeof e||null===e||!("method"in e)||"tools/call"!==e.method)continue;const t="params"in e?e.params:void 0,r="object"==typeof t&&null!==t&&"name"in t?t.name:void 0;return"string"==typeof r?r:void 0}}function $x(e){return e instanceof Error&&/does not support dynamic client registration/i.test(e.message)}Error,Error;const Mx=new Set(["UnauthorizedError","InvalidGrantError","InvalidTokenError","InvalidClientError","UnauthorizedClientError"]),Dx=new Set(["invalid_grant","invalid_token","invalid_client","unauthorized_client"]),Ox=[/\btoken (?:has |is )?expired\b/i,/\btoken (?:was|is) invalid\b/i,/\binvalid (?:refresh[ _]?)?token\b/i,/\btoken (?:has been |was )?revoked\b/i];var Fx=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js");const Nx="2026-07-28",Lx=-32022,jx="io.modelcontextprotocol/protocolVersion",Ux="io.modelcontextprotocol/clientCapabilities",Bx="io.modelcontextprotocol/clientInfo",Wx="io.modelcontextprotocol/serverInfo",Hx={name:"cursor",version:"1.0.0"},qx=new Map;function zx(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Gx(e){const t=new URL(String(e));return t.hash="",t.href}function Vx(e,t){const r=qx.get(e);return!(void 0===r||r<=t()&&(qx.delete(e),1))}function Kx(e,t){try{return Gx(e)===t}catch{return!1}}function Jx(e){return(e.headers.get("content-type")??"").toLowerCase().includes("application/json")}const Zx=new Set(["events/subscribe","events/unsubscribe","events/poll","events/stream"]);function Xx(e,t,r,n,o=t.message){const s=new Headers(e?.headers);if(s.set("mcp-protocol-version",Nx),s.set("mcp-method",r),s.delete("mcp-session-id"),!t.isRequest&&o===t.message)return{...e,headers:s};const i=zx(o.params)?o.params:{},a=zx(i._meta)?i._meta:{},c=function(e,t){const r="tools/call"===e||"prompts/get"===e||Zx.has(e)?"name":"resources/read"===e?"uri":void 0,n=void 0===r?void 0:t[r];return"string"==typeof n?n:void 0}(r,i);void 0!==c&&s.set("mcp-name",c);const l=JSON.stringify({...o,params:{...i,_meta:{...a,[jx]:Nx,[Ux]:n.capabilities,[Bx]:n.clientInfo}}});return{...e,headers:s,body:l}}function Qx(e){return new Response(JSON.stringify({jsonrpc:"2.0",...e}),{status:200,headers:{"content-type":"application/json"}})}function Yx(e,t){const r=Gx(t.serverUrl),n=t.now??Date.now;let o={capabilities:{},clientInfo:{...Hx}},s=!1;const i=()=>s||Vx(r,n),a=async(t,i,a)=>{const{method:c,message:l}=t;if(void 0===c)return e(i,a);if("notifications/initialized"===c)return new Response(null,{status:202});if(t.isRequest&&"initialize"===c){const c={jsonrpc:"2.0",id:l.id,method:"server/discover",params:{}},u=await e(i,Xx(a,t,"server/discover",o,c)),d=await async function(e,t,r){if(!e.ok||!Jx(e))return e;let n;try{n=await e.clone().json()}catch{return e}if(!zx(n)||!zx(n.result))return e;const o=n.result,s=o.supportedVersions;if(!Array.isArray(s)||!s.includes(Nx))return Qx({id:t,error:{code:Lx,message:"Unsupported protocol version",data:{requested:Nx,supported:s??[]}}});const i=zx(o._meta)?o._meta:{},a=zx(i[Wx])?i[Wx]:{name:new URL(r).hostname,version:"unknown"};return Qx({id:t,result:{protocolVersion:Fx.aE,capabilities:zx(o.capabilities)?o.capabilities:{},serverInfo:a,..."string"==typeof o.instructions?{instructions:o.instructions}:{}}})}(u,l.id,r);return d!==u&&(s=!0,function(e,t){qx.set(e,t()+6e5)}(r,n)),d}return e(i,Xx(a,t,c,o))};return async(t,c)=>{const l=function(e,t,r){if("POST"!==(t?.method??"GET").toUpperCase()||"string"!=typeof t?.body||!Kx(e,r))return;let n;try{n=JSON.parse(t.body)}catch{return}if(!zx(n)||"2.0"!==n.jsonrpc)return;const o="string"==typeof n.method?n.method:void 0;return{message:n,method:o,isRequest:void 0!==o&&"id"in n}}(t,c,r);if(void 0===l)return function(e,t,r){return"GET"===(t?.method??"GET").toUpperCase()&&Kx(e,r)}(t,c,r)&&i()?new Response(null,{status:405}):e(t,c);if(l.isRequest&&"initialize"===l.method){const e=zx(l.message.params)?l.message.params:{};o={capabilities:zx(e.capabilities)?e.capabilities:{},clientInfo:zx(e.clientInfo)?e.clientInfo:o.clientInfo}}const u=l.isRequest&&"initialize"===l.method;if(u?Vx(r,n):i())return a(l,t,c);if(u&&(s=!1),!l.isRequest)return e(t,c);const d=await e(t,c);if(u&&await async function(e){if(e.status>=500||!Jx(e))return!1;const t=Number(e.headers.get("content-length"));if(Number.isFinite(t)&&t>4096)return!1;let r;try{r=await e.clone().json()}catch{return!1}if(!zx(r)||!zx(r.error))return!1;const n=r.error;if(n.code!==Lx||!zx(n.data))return!1;const o=n.data.supported;return Array.isArray(o)&&o.includes(Nx)}(d)){const e=await a(l,t,c);return s?e:d}return d}}function eP(e,t){if(void 0===t)return{headers:t,cursorAuthHeaderValue:void 0,cursorAuthOrigin:void 0};const r=Object.entries(t),n=r.find((([e])=>e.toLowerCase()===ab));if(void 0===n)return{headers:t,cursorAuthHeaderValue:void 0,cursorAuthOrigin:void 0};let o;try{o=new URL(e).origin}catch{o=void 0}return{headers:Object.fromEntries(r.filter((([e])=>e.toLowerCase()!==ab))),cursorAuthHeaderValue:n[1],cursorAuthOrigin:o}}function tP(e,t,r){return async(n,o)=>{let s;try{s=new URL("string"==typeof n?n:n.toString()).origin}catch{return r(n,o)}if(s!==t)return r(n,o);const i=await e();if(void 0===i||0===i.length)return r(n,o);const a=new Headers(o?.headers);return a.set(ab,i),r(n,{...o,headers:a,redirect:"manual"})}}class rP{constructor(e=864e5){this.ttl=e,this.staleDirty=!1,this.refreshGeneration=0}async get(e){const t=performance.now();if(this.state&&this.state.expiresAt>t&&!this.staleDirty)return this.state.value;if(this.staleDirty&&this.state){const t=this.state.value;if(!this.refreshInFlight){const t=this.refreshGeneration;let r;r=(async()=>{try{const r=await e();if(t!==this.refreshGeneration)return;this.state={expiresAt:performance.now()+this.ttl,value:r},this.staleDirty=!1}catch{}finally{r&&this.refreshInFlight===r&&(this.refreshInFlight=void 0)}})(),this.refreshInFlight=r}return t}const r=this.refreshGeneration,n=await e();return r!==this.refreshGeneration||(this.state={expiresAt:performance.now()+this.ttl,value:n},this.staleDirty=!1),n}invalidate(){this.refreshGeneration++,this.state=void 0,this.staleDirty=!1,this.refreshInFlight=void 0}invalidateKeepingStale(){this.state&&(this.staleDirty=!0)}}var nP=r("crypto");function oP(e){const t={};for(const[r,n]of Object.entries(e))void 0!==n&&(t[r]=n);return t}function sP(e,t){const r=function(e){try{const t=new URL(e);return{host:t.host,origin:t.origin,pathname:t.pathname}}catch{return{host:null,origin:null,pathname:null}}}(e),n=!1!==t?.includePath;return{host:r.host,origin:r.origin,path:n?r.pathname:null}}function iP(e,t){return sP(e,t)}function aP(e){if(e)return(0,nP.createHash)("sha256").update(e).digest("hex").slice(0,12)}function cP(e){if(e&&0!==e.length)return aP(JSON.stringify([...e].sort()))}function lP(e){return{clientIdHash:aP(e?.client_id),hasClientSecret:(e?.client_secret??"").length>0,redirectUrisHash:cP(e?.redirect_uris),redirectUriCount:e?.redirect_uris?.length??0}}function uP(e){return"object"==typeof e&&null!==e}function dP(e,t){let r=e;for(const e of t){if(!uP(r)||!(e in r))return;r=r[e]}return r}function hP(e,t){for(const r of t){const t=dP(e,r.split("."));if("string"==typeof t)return t}}function pP(e){if(!e||"object"!=typeof e)return;const t=e.errorCode;return"string"==typeof t?t:void 0}function fP(e){if(!e)return;const t=e.match(/\(HTTP (\d+)\)|Non-200 status code \((\d+)\)|\bHTTP\s+(\d{3})\b/i),r=t?.[1]??t?.[2]??t?.[3];if(!r)return;const n=Number.parseInt(r,10);return Number.isNaN(n)?void 0:n}const mP=e=>e;function gP(e,t){if(e instanceof Error){const r=e.message;return r&&r!==e.name?_P(t(r)):void 0}if("string"==typeof e||"number"==typeof e||"boolean"==typeof e){const r=String(e);return r?_P(t(r)):void 0}}function wP(e){if(e&&"object"==typeof e)return uP(e)?e.cause:void 0}function yP(e,t,r=4){const n=[];let o=e;for(let e=0;e1?n.join(" > "):void 0}const vP="[REDACTED]",bP=/(^|_|-)(token|secret|password|assertion|authorization|verifier|challenge|code)(_|-|$)/i;function SP(e){return e.replace(/(authorization[^:=\r\n]{0,32}[:=]\s*["']?)(?:[A-Za-z][\w.~+/-]*[ \t]+)?[^"',\s&}]+/gi,`$1${vP}`).replace(/((?:access_token|refresh_token|id_token|client_secret|code|password|assertion|token|secret)[^:=\r\n]{0,32}[:=]\s*["']?)([^"',\s&}]+)/gi,`$1${vP}`).replace(/(\bBearer\s+)([A-Za-z0-9\-._~+/]+=*)/gi,`$1${vP}`)}function kP(e,t=256){return e.length>t?`${e.slice(0,Math.max(0,t-3))}...`:e}function _P(e,t){return kP(SP(e),t?.maxLength)}function CP(e,t=mP){if("string"==typeof e)return kP(SP(t(e)));if(void 0!==e)try{const r=JSON.stringify(e,((e,r)=>e&&function(e){const t=e.toLowerCase();return"code"===t||"authorization"===t||t.includes("token")||t.includes("secret")||t.includes("password")||t.includes("assertion")||t.includes("verifier")||t.includes("challenge")||bP.test(t)}(e)?vP:"string"==typeof r?SP(t(r)):r));if(!r)return;return kP(r)}catch{return}}function EP(e,t=mP){const r=wP(e),n=e instanceof Error?e.name:null!=e?typeof e:void 0,o=r instanceof Error?r.name:void 0,s=gP(r,t),i=gP(e,t)??s,a=hP(e,["code","cause.code"]),c=pP(e)??pP(r)??hP(e,["errorCode","error","cause.errorCode","cause.error","body.error","response.body.error"]),l=void 0===c?void 0:_P(t(c)),u=function(e){for(const t of["status","statusCode","response.status","response.statusCode","cause.status","cause.statusCode","cause.response.status","cause.response.statusCode"]){const r=dP(e,t.split("."));if("number"==typeof r&&Number.isFinite(r))return r}}(e)??fP(i)??fP(s),d=CP(dP(e,["response","body"])??dP(e,["body"])??dP(e,["data"])??dP(e,["cause","body"])??dP(e,["cause","response","body"]),t),h=function(e){const t=e.message?.toLowerCase(),r=e.code?.toLowerCase();return t?.includes("timed out")||t?.includes("timeout")||t?.includes("etimedout")||"etimedout"===r?"timeout":t?.includes("enotfound")||t?.includes("eai_again")||t?.includes("dns")||"enotfound"===r||"eai_again"===r?"dns":t?.includes("certificate")||t?.includes("tls")||t?.includes("ssl")?"tls":t?.includes("econnreset")||t?.includes("connection reset")||"econnreset"===r?"connection_reset":t?.includes("econnrefused")||t?.includes("connection refused")||"econnrefused"===r?"connection_refused":void 0}({message:i,code:a}),p=l?"oauth_error":h?"auth_transport_error":i?"generic_error":void 0;return oP({errorName:n,errorMessage:i,errorType:null!=e?typeof e:void 0,httpStatus:u,oauthErrorCode:l,errorResponseSummary:d,networkClassification:h,causeName:o,causeMessage:s,causeChain:yP(e,t),sdkErrorKind:p})}const xP={mcp_oauth_provider_initialized:"MCP OAuth provider initialized",mcp_oauth_tokens_loaded:"MCP OAuth tokens loaded",mcp_oauth_tokens_saved:"MCP OAuth tokens saved",mcp_oauth_callback_completion:"MCP OAuth callback exchange completed",mcp_oauth_client_info_loaded:"MCP OAuth client information loaded",mcp_oauth_client_info_saved:"MCP OAuth client information saved",mcp_oauth_refresh_prepare:"MCP OAuth refresh prepared",mcp_oauth_refresh_error_release:"MCP OAuth refresh error released",mcp_oauth_state_transition:"MCP OAuth state transition",mcp_oauth_credentials_invalidated:"MCP OAuth credentials invalidated"};function PP(e){const t=e.message??xP[e.event],r={event:e.event,cursorMcp:{oauth:oP({...e.metadata})}},n=e.level??"info";"error"!==n?"warn"!==n?"debug"!==n?e.logger.info?.(t,r):e.logger.debug?.(t,r):e.logger.warn?.(t,r):e.logger.error?.(t,e.error,r)}const RP=new Map(["AWS4-HMAC-SHA256","Api-Key","ApiKey","Basic","Bearer","Bot","DPoP","Digest","GNAP","HOBA","Key","Mutual","NTLM","Negotiate","OAuth","PrivateToken","SCRAM-SHA-1","SCRAM-SHA-256","Token","vapid"].map((e=>[e.toLowerCase(),e]))),IP=4096;function TP(e){return"object"==typeof e&&null!==e&&"url"in e&&"string"==typeof e.url}function AP(e){return"string"==typeof e?e:e instanceof URL?e.toString():e.url}function $P(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function MP(e){if(e instanceof Headers)return e;if(Array.isArray(e)){const t=[];for(const r of e){if(!Array.isArray(r)||"string"!=typeof r[0]||"string"!=typeof r[1])return;t.push([r[0],r[1]])}return t}if($P(e)){const t={};for(const[r,n]of Object.entries(e)){if("string"!=typeof n)return;t[r]=n}return t}}function DP(e,t){const r=new Headers(MP(TP(e)?e.headers:void 0));return new Headers(MP(t?.headers)).forEach(((e,t)=>{r.set(t,e)})),r}function OP(e){const t=[];return e.forEach(((e,r)=>{t.push(r)})),t.sort()}function FP(e){if(null===e)return null;const t=Number.parseInt(e,10);return Number.isNaN(t)?null:t}function NP(e,t){if(null==e)return{kind:"none",bytes:0,contentLength:FP(t.get("content-length"))};if("string"==typeof e){const r=(new TextEncoder).encode(e).length;return{kind:"text",bytes:r,contentLength:FP(t.get("content-length"))??r}}if(e instanceof URLSearchParams){const r=e.toString(),n=(new TextEncoder).encode(r).length;return{kind:"text",bytes:n,contentLength:FP(t.get("content-length"))??n}}return e instanceof Blob?{kind:"blob",bytes:e.size,contentLength:FP(t.get("content-length"))??e.size}:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?{kind:"binary",bytes:e.byteLength,contentLength:FP(t.get("content-length"))??e.byteLength}:"object"==typeof e&&null!==e&&("getReader"in e||Symbol.asyncIterator in e)?{kind:"stream",bytes:null,contentLength:FP(t.get("content-length"))}:{kind:"unknown",bytes:null,contentLength:FP(t.get("content-length"))}}function LP(e,t){if(null===e||!e.toLowerCase().startsWith("application/x-www-form-urlencoded"))return;const r="string"==typeof t?function(e){for(const t of e.split("&")){const e=t.indexOf("="),r=e>=0?t.slice(0,e):t;let n;try{n=decodeURIComponent(r.replaceAll("+"," "))}catch{return}if("grant_type"!==n)continue;const o=e>=0?t.slice(e+1):"";try{return decodeURIComponent(o.replaceAll("+"," "))}catch{return}}}(t):t instanceof URLSearchParams?t.get("grant_type")??void 0:void 0;return r?function(e){switch(e){case"authorization_code":case"refresh_token":case"client_credentials":case"urn:ietf:params:oauth:grant-type:jwt-bearer":case"urn:ietf:params:oauth:grant-type:token-exchange":return e;default:return"other"}}(r):void 0}function jP(e){const{input:t,init:r}=e,n=sP(AP(t)),o=DP(t,r),s=OP(o),i=o.get("content-type"),a=aP(o.get("mcp-session-id")??void 0),c=function(e){if(!e)return null;const t=e.trim().split(/\s+/,1)[0]??"";return RP.get(t.toLowerCase())??"unrecognized"}(o.get("authorization"));return{method:(r?.method??(TP(t)?t.method:void 0)??"GET").toUpperCase(),url:n,headers:{names:s,count:s.length},contentType:i,body:NP(r?.body,o),sessionIdHash:a??null,authorizationScheme:c}}function UP(e,t){const r=OP(e.headers),n=FP(e.headers.get("content-length"));return{status:e.status,ok:e.ok,headers:{names:r,count:r.length},contentType:e.headers.get("content-type"),body:{kind:null===e.body?"none":"stream",bytes:null===e.body?0:n,contentLength:n,...void 0!==t?{errorSummary:t}:{}},sessionIdHash:aP(e.headers.get("mcp-session-id")??void 0)??null,wwwAuthenticateHash:aP(e.headers.get("www-authenticate")??void 0)??null,mcpProtocolVersion:e.headers.get("mcp-protocol-version")??null,requestId:e.headers.get("x-request-id")??null,retryAfter:BP(e.headers,"retry-after"),slackRateLimitType:BP(e.headers,"x-slack-ratelimit-type")}}function BP(e,t){return e.get(t)?.slice(0,64)??null}function WP(e){const t={};return void 0!==e.errorName&&(t.name=e.errorName),void 0!==e.errorMessage&&(t.message=e.errorMessage),void 0!==e.errorType&&(t.type=e.errorType),void 0!==e.oauthErrorCode&&(t.oauthErrorCode=e.oauthErrorCode),void 0!==e.errorResponseSummary&&(t.responseSummary=e.errorResponseSummary),void 0!==e.networkClassification&&(t.networkClassification=e.networkClassification),void 0!==e.sdkErrorKind&&(t.sdkErrorKind=e.sdkErrorKind),t}function HP(e,t){const r=jP({input:e,init:t});if(void 0!==LP(r.contentType,t?.body))return!0;const n=r.url.path?.toLowerCase()??"";return n.endsWith("/token")||n.includes("/oauth/token")||n.includes("/connect/token")}const qP=e=>e,zP="REDACTED_SESSION_ID",GP=/\b00D[A-Za-z0-9]{12,15}![A-Za-z0-9._]{20,512}/g;async function VP(e,t,r){try{const n=r(await e.clone().text());return n.length>t?n.slice(0,t):n}catch{return}}async function KP(e){if(!HP(e.input,e.init))return;const t=await VP(e.response,IP,e.redact);if(void 0!==t)try{return CP(JSON.parse(t))}catch{return _P(t,{maxLength:IP})}}async function JP(e){const t=await async function(e,t,r){try{if(t.ok)return;const n=t.headers.get("content-type")?.toLowerCase()??"";if(!n.includes("json")&&!n.includes("text"))return;const o=await VP(t,IP,r);if(void 0===o)return;return function(e){if("/mcp"!==(t=sP(AP(e.input)).path)&&!0!==t?.endsWith("/mcp"))return _P(e.rawText,{maxLength:IP});var t;try{const t=JSON.parse(e.rawText);return $P(t)?function(e){const t=e.error;if("string"==typeof t)return JSON.stringify({error:t});if("object"!=typeof t||null===t)return;if(!$P(t))return;const r=t,n="number"==typeof r.code||"string"==typeof r.code?r.code:void 0,o="string"==typeof r.message?_P(r.message,{maxLength:IP}):void 0;return void 0!==n||void 0!==o?JSON.stringify({...void 0!==n?{code:n}:{},...void 0!==o?{message:o}:{}}):void 0}(t):void 0}catch{return}}({input:e,rawText:o})}catch{return}}(e.input,e.response,e.redact);return{responseErrorSummary:t,oauthTokenErrorBodySummary:void 0===t?await KP({input:e.input,response:e.response,init:e.init,redact:e.redact}):void 0}}function ZP(e,t,r){try{e()}catch{t.warn?.("MCP HTTP exchange logging failed",{event:"mcp_http_exchange_logging_failure",phase:r})}}function XP(e,t,r){if("string"==typeof e)return t(e);if("object"!=typeof e||null===e||r>12)return e;if(Array.isArray(e))return e.map((e=>XP(e,t,r+1)));const n=Object.getPrototypeOf(e);return n!==Object.prototype&&null!==n?e:Object.fromEntries(Object.entries(e).map((([e,n])=>[e,XP(n,t,r+1)])))}function QP(e,t){const r=e=>{const r=XP(e,t,0);return $P(r)?r:void 0};return{debug:(t,n)=>e.debug?.(t,r(n)),info:(t,n)=>e.info?.(t,r(n)),warn:(t,n)=>e.warn?.(t,r(n))}}function YP(e){const{fetch:t,logSuccessfulExchanges:r=!0,redactLogText:n}=e,o=void 0===n?e.logger:QP(e.logger,n);return async(s,i)=>{const a=Date.now(),c="function"==typeof e.metadata?e.metadata(s):e.metadata,l=!0===e.redactEchoedSessionId?function(e,t,r){const n=DP(e,t).get("mcp-session-id")?.trim()??"";return e=>{const t=n.length>=8?e.split(n).join(zP):e;return r(t.replace(GP,zP))}}(s,i,n??qP):n??qP;try{const e=await t(s,i),{responseErrorSummary:n,oauthTokenErrorBodySummary:u}=e.ok?{}:await JP({input:s,init:i,response:e,redact:l});return!r&&e.ok||ZP((()=>{!function(e){const{logger:t,response:r}=e,n=function(e){const{input:t,init:r,response:n,durationMs:o,metadata:s,responseErrorSummary:i,oauthTokenErrorBodySummary:a}=e,c=jP({input:t,init:r}),l=LP(c.contentType,r?.body);return{event:"mcp_http_exchange",outcome:n.ok?"success":"http_error",durationMs:o,cursorMcp:{transport:{...s,request:c,response:UP(n,i),...void 0!==l?{oauth:{grantType:l}}:{},...void 0!==a?{oauthTokenErrorBodySummary:a}:{}}}}}(e);r.ok?t.info?.("MCP HTTP exchange completed",n):function(e){return 401===e.response.status&&null===e.request.authorizationScheme&&e.response.headers.has("www-authenticate")&&!HP(e.input,e.init)}({response:r,request:n.cursorMcp.transport.request,input:e.input,init:e.init})?t.debug?.("MCP HTTP exchange completed",n):t.warn?.("MCP HTTP exchange completed",n)}({logger:o,input:s,init:i,response:e,durationMs:Date.now()-a,metadata:c,responseErrorSummary:n,oauthTokenErrorBodySummary:u})}),o,"success"),e}catch(t){const r=function(e){if(!uP(e))return;const t=uP(e.cause)?e.cause:void 0,r=[e.response,t?.response];for(const e of r)if("object"==typeof(n=e)&&null!==n&&"status"in n&&"number"==typeof n.status&&"headers"in n&&"object"==typeof n.headers&&null!==n.headers&&"get"in n.headers&&"function"==typeof n.headers.get)return e;var n}(t),{responseErrorSummary:u,oauthTokenErrorBodySummary:d}=r?await JP({input:s,init:i,response:r,redact:l}):{};throw ZP((()=>{!function(e){const{logger:t}=e;t.warn?.("MCP HTTP exchange failed",function(e){const{input:t,init:r,error:n,durationMs:o,metadata:s,responseFromError:i,responseErrorSummary:a,oauthTokenErrorBodySummary:c}=e,l=EP(n,e.redactLogText),u=jP({input:t,init:r}),d=LP(u.contentType,r?.body);return{event:"mcp_http_exchange",outcome:"error",durationMs:o,cursorMcp:{transport:{...s,request:u,response:void 0!==i?UP(i,a):{status:l.httpStatus??null,ok:null,headers:{names:[],count:0},contentType:null,body:{kind:"none",bytes:null,contentLength:null,...void 0!==a?{errorSummary:a}:{}},requestId:null,sessionIdHash:null,wwwAuthenticateHash:null,mcpProtocolVersion:null,retryAfter:null,slackRateLimitType:null},...void 0!==d?{oauth:{grantType:d}}:{},...void 0!==c?{oauthTokenErrorBodySummary:c}:{},error:WP(l)}}}}(e))}({logger:o,input:s,init:i,error:t,durationMs:Date.now()-a,metadata:c,responseFromError:r,responseErrorSummary:u,oauthTokenErrorBodySummary:d,redactLogText:!0===e.redactEchoedSessionId?l:n})}),o,"failure"),t}}}function eR(e,t){const r=e?.access_token,n="string"==typeof r?r.length:0,o=Boolean(e?.refresh_token),s="number"==typeof e?.expires_in&&Number.isFinite(e.expires_in)?e.expires_in:null;return{accessTokenLen:n,refreshTokenPresent:o,expiresAtTimestamp:t?.expiresInIsFresh&&null!==s?Date.now()+Math.round(1e3*s):null,grantedScope:"string"==typeof e?.scope&&e.scope.length>0?e.scope:null}}function tR(e){const t=function(e){if(!e||"object"!=typeof e)return;const t=e.code;if("number"==typeof t&&t>=100&&t<=599)return t;if("string"==typeof t&&/^\d{3}$/.test(t)&&Number(t)>=100&&Number(t)<=599)return Number(t);const r=e instanceof Error||"object"==typeof e&&null!==e&&"message"in e&&"string"==typeof e.message?e.message:void 0;if(!r)return;const n=r.match(/\bHTTP\s+(\d{3})\b/i);if(!n?.[1])return;const o=Number.parseInt(n[1],10);return Number.isNaN(o)?void 0:o}(e);return void 0!==t?400===t||404===t||405===t:!!(e instanceof Error&&e.message.toLowerCase().includes("sessionid must be provided"))||function(e){if(!(e instanceof Error))return!1;const t="code"in e&&"string"==typeof e.code?e.code:void 0,r="cause"in e&&"object"==typeof e.cause&&null!==e.cause&&"code"in e.cause&&"string"==typeof e.cause.code?e.cause.code:void 0;return"ECONNREFUSED"===t||"ECONNREFUSED"===r||e.message.includes("ECONNREFUSED")}(e)}function rR(e,t=process.env){const r=t.TMPDIR,n={...void 0===r?{}:{TMPDIR:r},...e},{NODE_COMPILE_CACHE:o,...s}=n;return{...s,NODE_DISABLE_COMPILE_CACHE:"1"}}const nR=["PYTHONIOENCODING","PYTHONUTF8","PYTHONLEGACYWINDOWSSTDIO"],oR=[".exe",".cmd",".bat"],sR=/^pythonw?(?:\d+(?:\.\d+)*t?)?$/,iR=new Set(["py","pyw"]),aR=new Set(["--cache-dir","--color","--allow-insecure-host","--directory","--project","--config-file"]),cR=new Set;function lR(e){return nR.some((t=>function(e,t){const r=t.toUpperCase();return Object.entries(e).some((([e,t])=>void 0!==t&&e.toUpperCase()===r))}(e,t)))}function uR(e,t){for(let r=0;r=2&&e.endsWith(t)?e.slice(1,-1):e}(e.trim())).toLowerCase();for(const e of oR)if(t.endsWith(e))return t.slice(0,-e.length);return t}(e);if(sR.test(r)||iR.has(r)||"uvx"===r)return!0;if("uv"===r){const e=uR(t,aR);return"run"===e?.value||"tool"===e?.value&&"run"===uR(e.rest,aR)?.value}return"pipx"===r&&"run"===uR(t,cR)?.value}(n,o)?lR(i)||lR(r)?i:{...i,PYTHONIOENCODING:"utf-8:surrogateescape"}:i}async function hR(e){const t=[],r=new Set;let n;for(let o=1;;o++){const s=await e.fetchPage(n),i=e.itemsOf(s);t.push(...i);const a=e.nextCursorOf(s);if(!a||r.has(a))return t;if(o>=1e3)throw new Error("MCP list did not end after 1000 pages; refusing to keep paging");r.add(a),n=a}}var pR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"),fR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js"),mR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js"),gR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js");var wR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js");function yR(e){return`${typeof e}:${String(e)}`}function vR(e){const t=new Map,r=new Set,n=new Set,o=e=>{for(const t of n)t(e)},s=e=>{t.delete(e),r.delete(e)},i=e.send.bind(e);e.send=(e,n)=>((e=>{if("method"in e)if("tools/call"===e.method&&"id"in e){const r=e.params?.name;"string"==typeof r&&t.set(yR(e.id),r)}else if("notifications/cancelled"===e.method){const n=e.params?.requestId;if("string"!=typeof n&&"number"!=typeof n)return;const o=yR(n);if(!t.has(o))return;if(r.add(o),r.size>64){const e=r.values().next().value;void 0!==e&&s(e)}}})(e),i(e,n));const a=e.onmessage;return e.onmessage=(e,n)=>{(e=>{if("method"in e)return void("notifications/tools/list_changed"===e.method&&o({kind:"tools_list_changed"}));if(!("id"in e))return;const n=e.id;if("string"!=typeof n&&"number"!=typeof n)return;const i=yR(n),a=t.get(i);if(void 0===a)return;const c=r.has(i);if(s(i),!c)return;const l="error"in e||"object"==typeof e.result&&null!==e.result&&"isError"in e.result&&!0===e.result.isError;o({kind:"late_tool_result",toolName:a,isError:l})})(e),a?.(e,n)},{subscribe:e=>(n.add(e),()=>{n.delete(e)})}}function bR(e){const t=Object.entries(e.headers??{}).map((([e,t])=>[e.toLowerCase(),t])).sort((([e],[t])=>et?1:0));return(0,ko.createHash)("sha256").update(JSON.stringify([e.url,t,e.accessToken??null])).digest("hex")}class SR{constructor(e,t){this.inner=e,this.initializeResult=t,e.onclose=()=>this.onclose?.(),e.onerror=e=>this.onerror?.(e),e.onmessage=e=>this.onmessage?.(e)}get sessionId(){return this.inner.sessionId}setProtocolVersion(e){this.inner.setProtocolVersion(e)}start(){return this.inner.start()}close(){return this.inner.close()}async send(e,t){if((0,Fx.vo)(e)&&(0,Fx.eK)(e)){const t={jsonrpc:"2.0",id:e.id,result:this.initializeResult};queueMicrotask((()=>this.onmessage?.(t)))}else(0,Fx.wU)(e)||await this.inner.send(e,t)}}const kR=Be.object({tools:Be.array(Be.unknown()),nextCursor:Be.unknown().optional(),_meta:Be.unknown().optional()}),_R={typeFilled:0,toolDropped:0,outputStripped:0};function CR(e){if(TR(e))return"string"==typeof e.name?e.name:void 0}function ER(e){return xR(e.issues.filter((e=>"outputSchema"===e.path[0])))}function xR(e){return e.map((e=>`${e.path.map(String).join(".")}: ${e.message}`))}function PR(e){if(!TR(e))return e;const t={...e};return delete t.outputSchema,t}function RR(e){return TR(e)&&!("type"in e)}function IR(e,t){return{...e,inputSchema:{type:"object",...t}}}function TR(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var AR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js");const $R=new class{constructor({maxSchemasPerCompiler:e=2048,createCompiler:t=()=>new AR.p}={}){this.compiled=new Map,this.maxSchemasPerCompiler=e,this.createCompiler=t,this.compiler=t()}get compiledSchemaCount(){return this.compiled.size}getValidator(e){let t;return r=>(t??=this.compile(e),t(r))}compile(e){const t=JSON.stringify(e),r=(0,ko.createHash)("sha256").update(t).digest("base64url"),n=this.compiled.get(r);if(void 0!==n)return n;this.compiled.size>=this.maxSchemasPerCompiler&&(this.compiler=this.createCompiler(),this.compiled.clear());const o=(t.includes('"$id"')?this.createCompiler():this.compiler).getValidator(e);return this.compiled.set(r,o),o}};class MR{constructor(){this.decoder=new TextDecoder("utf-8"),this.captured="",this.capturedBytes=0}push(e){const t="string"==typeof e?e:this.decoder.decode(e,{stream:!0});return this.append(t),t}end(){const e=this.decoder.decode();return this.append(e),e}get text(){return this.captured}get full(){return this.capturedBytes>=ix}append(e){const t=ix-this.capturedBytes;if(t<=0||0===e.length)return;const r=function(e,t){if(!(t>0))return"";if(3*e.length<=t)return e;const{read:r}=Yo(e,Math.trunc(t));return r>=e.length?e:e.slice(0,r)}(e,t);this.captured+=r,this.capturedBytes=r.length=100&&t<=599?{error_class:"http",error_code:String(t),transport:e.transport}:void 0!==e.error||!0===e.failed?{error_class:"other",error_code:"exception",transport:e.transport}:!0===e.isError?{error_class:"payload",error_code:"is_error",transport:e.transport}:{error_class:"none",error_code:"none",transport:e.transport}}({transport:ax(t),...r}))}catch{}}const UR=(0,h.Pu)("mcp_tool.oauth_scope_step_up",{description:"A tools/call refused for a missing OAuth scope, by step-up decision",labelNames:["decision","dropped"]});function BR(e){return void 0===e?"unknown":"url"in e?"http":"stdio"}const WR=["authorization_code","refresh_token"],HR=["code"];class qR{constructor(e){this._refreshInProgress=!1,this._identifier=e.identifier,this._redirectUrl=e.redirectUrl,this._serverUrl=e.serverUrl,this._restMcpProviderMetadata=e.restMcpProviderMetadata,this.validateResourceURL=!0===e.restMcpProviderMetadata?.omitResourceIndicator?async()=>{}:function(e,t){if(function(e,t){const r=t.gtmApiOrigin;if(void 0===e||void 0===r)return!1;let n,o;try{n=new URL(e),o=new URL(r)}catch{return!1}return n.protocol===o.protocol&&n.hostname===o.hostname&&""===n.port&&"/mcp"===n.pathname}(e,t))return async()=>{};const r=kb(e);return void 0!==r&&function(e){return"https:"===e.protocol&&e.hostname===new URL(ub).hostname}(r)?async()=>{}:void 0!==r&&function(e){return"https:"===e.protocol&&"setup.shopify.com"===e.hostname&&""===e.port&&"/mcp"===e.pathname}(r)?_b:bb}(e.serverUrl,e.gtmMcpMatch),this._clientMetadata=e.clientMetadata,this._scopes=e.scopes,this._isScopePinGateEnabled=e.isScopePinGateEnabled,this.scopeStepUp=e.scopeStepUp,this._tokens=e.tokens,this._clientInformation=e.clientInformation,this._saveTokens=e.saveTokens,this._prepareForRefresh=e.prepareForRefresh,this._releaseRefreshLeaseOnError=e.releaseRefreshLeaseOnError,this._invalidateCredentials=e.invalidateCredentials,this._saveClientInformation=e.saveClientInformation,this.addClientAuthentication=e.addClientAuthentication}get redirectUrl(){return this._redirectUrl}get clientMetadata(){return this._clientMetadata}state(){return this._oauthAttemptId=(0,ko.randomUUID)(),this._oauthState=function(e,t,r){const n={id:e,owner:t,...r?{attemptId:r}:{}};return Buffer.from(JSON.stringify(n),"utf8").toString("base64url")}(this._identifier,{workspaceId:this._redirectUrl},this._oauthAttemptId),this._oauthState}clientInformation(){return this._clientInformation}hasClientInformation(){return void 0!==this._clientInformation}async saveClientInformation(e){this._clientInformation=e,await this._saveClientInformation(e)}tokens(){return this.scopeStepUp?.tokensForSdk(this._tokens)??this._tokens}async saveTokens(e){const t=this._refreshInProgress;this._refreshInProgress=!1,this._tokens=e,await this._saveTokens(e),await(this.scopeStepUp?.recordTokens(e,{isRefresh:t}))}async prepareForRefresh(){await(this._prepareForRefresh?.()),this._refreshInProgress=!0}async releaseRefreshLeaseOnError(e){this._refreshInProgress=!1,await(this._releaseRefreshLeaseOnError?.(e))}async invalidateCredentials(e){switch(this._refreshInProgress=!1,e){case"tokens":this._tokens=void 0;break;case"client":this._clientInformation=void 0;break;case"verifier":this._codeVerifier=void 0,this._oauthState=void 0,this._oauthAttemptId=void 0;break;case"all":this._tokens=void 0,this._clientInformation=void 0,this._codeVerifier=void 0,this._oauthState=void 0,this._oauthAttemptId=void 0,this._lastRedirectUrl=void 0,await(this.scopeStepUp?.clear({keepPendingScopes:!0}));break;default:return e}await(this._invalidateCredentials?.(e))}async redirectToAuthorization(e){const t=await(this.scopeStepUp?.prepareAuthorization());(function(e,t,r={}){const n=r.stepUpScopes??[],o=void 0!==t&&t.length>0?t:n.length>0?(e.searchParams.get("scope")??"").split(" ").filter((e=>e.length>0)):void 0;var s;void 0!==o&&e.searchParams.set("scope",(s={scopes:o,stepUpScopes:n},[...new Set([...s.scopes,...s.stepUpScopes])]).join(" "))})(e,function(e,t,r){const n=yb(e);return!0!==n?.pinsScopesOverConfiguredScopes?void 0!==t&&t.length>0||void 0===r?t:Cb(e)?.baseScopes??t:void 0!==n.scopesPinGate&&!0!==r?.(n.scopesPinGate)?t:n.scopes??t}(this._serverUrl??"",this._scopes,this._isScopePinGateEnabled),{stepUpScopes:t?.stepUpScopes}),void 0!==this._serverUrl&&function(e,t){const r=yb(t)?.authorizationParams;if(void 0!==r)for(const[t,n]of Object.entries(r))e.searchParams.set(t,n)}(e,this._serverUrl);for(const[t,r]of Object.entries(this._restMcpProviderMetadata?.authorizationParams??{}))e.searchParams.set(t,r);(!0===this._restMcpProviderMetadata?.omitConsentPrompt||function(e){return"login.microsoftonline.com"===e.hostname}(e))&&function(e){const t=new Set(e.searchParams.getAll("prompt").flatMap((e=>e.split(" "))).filter((e=>""!==e&&"consent"!==e)));e.searchParams.delete("prompt"),t.size>0&&e.searchParams.set("prompt",[...t].join(" "))}(e),await(t?.recordRequestedScopes(e)),this._lastRedirectUrl=e}get lastRedirectUrl(){return this._lastRedirectUrl}async saveCodeVerifier(e){this._codeVerifier=e}codeVerifier(){if(!this._codeVerifier)throw new Error("No code verifier saved");return this._codeVerifier}}async function zR(e){const{serverName:t,config:n,tokenStorage:o}=e,s=await dx(n.url,e.fetchImpl),i=Db({loopbackIpv4:s?.loopbackIpv4,redirectUrl:e.authRedirectUrl}),a=function(e,t){const r=lx(e?.CLIENT_ID);if(void 0!==r)return{client_id:r,...e?.CLIENT_SECRET?{client_secret:e.CLIENT_SECRET}:{},redirect_uris:Ob(t),grant_types:[...WR],response_types:[...HR],token_endpoint_auth_method:"none"}}(n.auth,i),c=function({storedClientInformation:e,staticClientInformation:t}){return t?e&&e.client_id===t.client_id?{...t,...e,client_secret:t.client_secret??e.client_secret,redirect_uris:t.redirect_uris,grant_types:e.grant_types??t.grant_types,response_types:e.response_types??t.response_types,token_endpoint_auth_method:e.token_endpoint_auth_method??t.token_endpoint_auth_method}:t:e}({storedClientInformation:await o.loadClientInformation(),staticClientInformation:a});return new qR({identifier:t,redirectUrl:i,serverUrl:n.url,restMcpProviderMetadata:s,gtmMcpMatch:e.gtmMcpMatch??{gtmApiOrigin:void 0},clientMetadata:{redirect_uris:Ob(i),token_endpoint_auth_method:"none",grant_types:[...WR],response_types:[...HR],client_name:"Cursor",logo_uri:"https://ptht05hbb1ssoooe.public.blob.vercel-storage.com/assets/uploads/cursorlogomcpv3.svg"},scopes:n.auth?.scopes,isScopePinGateEnabled:e.isScopePinGateEnabled,...!0===e.scopeChallengeStepUp&&void 0!==o.loadScopeStepUpRecord&&void 0!==o.saveScopeStepUpRecord?{scopeStepUp:Px({serverUrl:n.url,accountKey:t,configuredScopes:n.auth?.scopes,readTokenScope:async()=>void 0!==o.loadGrantedScope?o.loadGrantedScope():(await o.loadTokens())?.scope,readRecord:async()=>o.loadScopeStepUpRecord?.(),writeRecord:async e=>o.saveScopeStepUpRecord?.(e),readScopesSupported:t=>async function(e){try{const{discoverAuthorizationServerMetadata:t,discoverOAuthProtectedResourceMetadata:n}=await Promise.resolve().then(r.bind(r,"../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js")),o=await n(e.serverUrl,void 0!==e.resourceMetadataUrl?{resourceMetadataUrl:new URL(e.resourceMetadataUrl)}:void 0,e.fetch),s=await t(o.authorization_servers?.[0]??new URL("/",e.serverUrl),{fetchFn:e.fetch}).catch((()=>{}));if(void 0===s&&!0===e.requireAuthorizationServerMetadata)return;const i=new Set([...o.scopes_supported??[],...s?.scopes_supported??[]]);return i.size>0?[...i]:void 0}catch{return}}({serverUrl:n.url,resourceMetadataUrl:t,fetch:e.fetchImpl})})}:{},tokens:await o.loadTokens(),clientInformation:c,saveTokens:e=>o.saveTokens(e),prepareForRefresh:()=>o.prepareForRefresh?.()??Promise.resolve(),releaseRefreshLeaseOnError:e=>o.releaseRefreshLeaseOnError?.(e)??Promise.resolve(),invalidateCredentials:o.invalidateCredentials?e=>o.invalidateCredentials(e):void 0,saveClientInformation:e=>o.saveClientInformation(e),addClientAuthentication:o.tokenEndpointAuth?.({clientId:c?.client_id})})}const GR=new Set;let VR=!1;function KR(){for(const e of GR)try{process.kill(e,"SIGKILL")}catch{}}function JR(e){return $x(e)?new pR.D_:e}function ZR(e,t){return Yx(e??globalThis.fetch.bind(globalThis),{serverUrl:t})}function XR(e,t,r){const n=eP(e,t),o=r??(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),s=void 0!==n.cursorAuthHeaderValue&&void 0!==n.cursorAuthOrigin&&void 0!==o?tP((()=>n.cursorAuthHeaderValue),n.cursorAuthOrigin,o):o;return{transportHeaders:n.headers,baseFetch:s}}class QR{constructor(e,t,r){this._toolListGeneration=0,this._toolListSuccessGeneration=0,this._toolListStateGeneration=0,this._callToolLock=Promise.resolve(),this._callToolQueueDepth=0,this._stateEnteredAtMs=Date.now(),this._terminatingSession=!1,this._closeRequested=!1,this.serverName=e,this.client=t,this.tools=new rP,this.stateValue=r.initialState,this._authProvider=r.authProvider,this._authCodeExchange=r.authCodeExchange,this._sessionId=r.sessionId,this._protocolVersion=r.protocolVersion,this._resumedInstructions=r.resumedInstructions,this._sessionlessInitialize=r.sessionlessInitialize,this.config=r.config,this._oauthLifecycleLogger=r.oauthLifecycleLogger,this._serverSignals=r.serverSignals,this._redactLogText=r.redactLogText,this.setupElicitationHandler(),!0===r.stdioServer&&(t.onclose=()=>{this._closeRequested||(this.updateState({kind:"error",message:"MCP server exited"},"stdio_exited"),this.tools.invalidate())})}_stateKindLabel(e){return"requires_authentication"===e.kind?"needsAuth":e.kind}_logStateTransition(e,t,r,n){if(!this._oauthLifecycleLogger)return;const o=this._stateKindLabel(e),s=this._stateKindLabel(t);if(o===s)return;const i=Date.now()-this._stateEnteredAtMs,a=(()=>{try{const e=this.config&&"url"in this.config?this.config.url:void 0;return e?new URL(e).host:void 0}catch{return}})();PP({logger:this._oauthLifecycleLogger,event:"mcp_oauth_state_transition",metadata:{identifier:this.serverName,from:o,to:s,cause:r,serverUrlHost:a,previousStateDurationMs:i,...n}})}static createClient(e={}){const t={elicitation:{form:{}},...!1===e.mcpAppsUi?{}:{extensions:{"io.modelcontextprotocol/ui":{mimeTypes:["text/html;profile=mcp-app"]}}}};return new wR.K({name:"Cursor",version:"1.0.0"},{capabilities:t,jsonSchemaValidator:$R})}setupElicitationHandler(){this.client.setRequestHandler(Fx.$9,(async e=>{if(!this._currentElicitationProvider)return{action:"decline"};if(!("requestedSchema"in e.params))return{action:"decline"};try{const t=e.params.requestedSchema,r=await this._currentElicitationProvider.elicit({message:e.params.message,requestedSchema:t});return{action:r.action,content:r.content}}catch(e){return{action:"decline"}}}))}static async fromStreamableHttp(e,t,r,n,o,s,i,a,c,l,u,d=!1,h={}){const p=new URL(t.url);o=o??Tb;const f=await zR({serverName:e,config:t,tokenStorage:r,authRedirectUrl:o,fetchImpl:s,gtmMcpMatch:c,isScopePinGateEnabled:l,scopeChallengeStepUp:u}),m=f.tokens(),g=eP(t.url,n),w=g.headers,y=d&&function(e){return Object.entries(e??{}).some((([e,t])=>"authorization"===e.toLowerCase()&&t.trim().length>0))}(w)?void 0:f,v=s??(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),b=void 0!==g.cursorAuthHeaderValue&&void 0!==g.cursorAuthOrigin&&void 0!==v?tP((()=>g.cursorAuthHeaderValue),g.cursorAuthOrigin,v):v,S=e=>void 0===b||void 0===i?b:YP({fetch:b,logger:i.logger,metadata:{...i.metadata,transportType:e},redactLogText:i.redactLogText});let k;const _=e=>{const r=f.scopeStepUp,n=e??v;return void 0===r||void 0===n?e:(o={fetch:n,scopeStepUp:r,serverUrl:t.url,startSignIn:async e=>{const t=void 0!==e.resourceMetadataUrl&&URL.canParse(e.resourceMetadataUrl)?new URL(e.resourceMetadataUrl):void 0;await(0,pR.j2)(f,{serverUrl:p.toString(),...void 0!==t?{resourceMetadataUrl:t}:{},...void 0!==b?{fetchFn:b}:{}});const r=f.lastRedirectUrl;k=void 0!==r&&void 0!==t?{redirectUrl:r,resourceMetadataUrl:t}:void 0}},async(e,t)=>{const r=await o.fetch(e,t);if(401!==r.status&&403!==r.status||!function(e){if("string"!=typeof e)return!1;let t;try{t=JSON.parse(e)}catch{return!1}return(Array.isArray(t)?t:[t]).some((e=>"object"==typeof e&&null!==e&&"method"in e&&"tools/call"===e.method))}(t?.body))return r;const n=await o.scopeStepUp.decide({status:r.status,wwwAuthenticate:r.headers.get("www-authenticate"),toolName:Ax(t?.body)});if(void 0===n)return r;if(o.onDecision?.(n),await(r.body?.cancel().catch((()=>{}))),"offer"===n.kind)try{await o.scopeStepUp.signIn((()=>o.startSignIn(n)))}catch(e){px(o.scopeStepUp.accountKey).warn("MCP OAuth scope step-up: could not start the sign-in",{event:"mcp_oauth_scope_step_up_sign_in_failed",errorName:e instanceof Error?e.name:typeof e})}throw new Tx(n,o.serverUrl,o.scopeStepUp.connectorName)});var o},C=QR.createClient(h),E=e=>e instanceof pR.D_||function(e){if(null===e||"object"!=typeof e)return!1;const t=e.name;if("string"==typeof t&&Mx.has(t))return!0;const r=e.errorCode;return!("string"!=typeof r||!Dx.has(r.toLowerCase()))||function(e){if(null===e||"object"!=typeof e)return!1;const t=e.name,r=e.errorCode;if("InvalidRequestError"!==t&&("string"!=typeof r||"invalid_request"!==r.toLowerCase()))return!1;const n=e.message;return"string"==typeof n&&Ox.some((e=>e.test(n)))}(e)}(e)||$x(e),x=async t=>{if(!f.hasClientInformation())throw new Error("OAuth client registration has not completed. The MCP server may not support dynamic client registration or the registration failed.");const r=void 0!==k&&k.redirectUrl===f.lastRedirectUrl?k.resourceMetadataUrl:void 0;await(0,pR.j2)(f,{serverUrl:p.toString(),authorizationCode:t,...void 0!==r?{resourceMetadataUrl:r}:{},...void 0!==b?{fetchFn:b}:{}}),a&&PP({logger:a,event:"mcp_oauth_callback_completion",metadata:{identifier:e,...iP(p.toString()),...eR(f.tokens(),{expiresInIsFresh:!0})}})},P=r=>{const n=f.lastRedirectUrl?.toString?.()??"",o=new QR(e,C,{oauthLifecycleLogger:a,redactLogText:i?.redactLogText,initialState:{kind:"requires_authentication",url:n,callback:async e=>{try{await x(e),o.updateState({kind:"ready"})}catch(e){const t=e instanceof Error?e.message:"Authentication failed";throw new Error(`Authentication callback failed: ${t}`)}}},authProvider:f,authCodeExchange:x,sessionId:r,config:t});return o},R=async r=>{const n=new fR.A(p,{authProvider:y,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...w??{}}},fetch:_(S("sse"))});try{return await C.connect(n),new QR(e,C,{initialState:{kind:"ready"},authProvider:f,authCodeExchange:x,config:t,oauthLifecycleLogger:a,redactLogText:i?.redactLogText})}catch(t){if(await n.close().catch((()=>{})),E(t))return a&&PP({logger:a,event:"mcp_oauth_state_transition",metadata:{identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"sse",refreshTokenPresent:Boolean(m?.refresh_token),...iP(p.toString()),...EP(t,i?.redactLogText)}}),P();if(void 0!==r&&tR(t)&&t instanceof fR._)throw function(e,t){let r=e;for(let e=0;e<8&&r instanceof Error&&r.cause instanceof Error;e++)r=r.cause;return r instanceof Error&&void 0===r.cause&&Reflect.defineProperty(r,"cause",{value:t,writable:!0,configurable:!0,enumerable:!1}),e}(r,t);throw t}};if("sse"===t.type)return R();const I=new gR.j(p,{authProvider:y,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...w??{}}},fetch:_(ZR(S("streamableHttp"),p))});try{await C.connect(I);const r=function(e,t=Date.now){return Vx(Gx(e),t)}(t.url)?void 0:function(e,r){const o=r.protocolVersion;if(void 0!==r.sessionId||void 0===o)return;const s=e.getServerCapabilities(),i=e.getServerVersion();if(void 0===s||void 0===i)return;const a=e.getInstructions();return{result:{protocolVersion:o,capabilities:s,serverInfo:i,...void 0===a?{}:{instructions:a}},credentialFingerprint:bR({url:t.url,headers:n,accessToken:f.tokens()?.access_token})}}(C,I);return new QR(e,C,{initialState:{kind:"ready"},authProvider:f,authCodeExchange:x,sessionId:I.sessionId,protocolVersion:I.protocolVersion,...void 0===r?{}:{sessionlessInitialize:r},config:t,oauthLifecycleLogger:a,redactLogText:i?.redactLogText})}catch(t){if(E(t))return a&&PP({logger:a,event:"mcp_oauth_state_transition",metadata:{identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"streamableHttp",refreshTokenPresent:Boolean(m?.refresh_token),...iP(p.toString()),...EP(t,i?.redactLogText)}}),P(I.sessionId);if(tR(t))return R(t);throw t}}static async fromStreamableHttpWithoutOAuth(e,t,r){const n=QR.createClient(),o=new gR.j(new URL(t.url),{requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...t.headers}},fetch:r});return await n.connect(o),new QR(e,n,{initialState:{kind:"ready"},sessionId:o.sessionId,protocolVersion:o.protocolVersion,config:t})}static async fromCachedSession(e,t,r,n,o,s=Tb,i,a,c,l,u){const d=new URL(t.url),h=await zR({serverName:e,config:t,tokenStorage:n,authRedirectUrl:s,fetchImpl:i,gtmMcpMatch:l,isScopePinGateEnabled:u}),{transportHeaders:p,baseFetch:f}=XR(t.url,o,i),m=new gR.j(d,{authProvider:h,sessionId:r.sessionId,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...p??{}}},fetch:void 0!==f&&void 0!==a?YP({fetch:f,logger:a.logger,metadata:{...a.metadata,transportType:"streamableHttp"},redactLogText:a.redactLogText}):f});m.setProtocolVersion(r.protocolVersion);const g=function(e){return e._requestMessageId=(0,ko.randomInt)(1048576,2146435072),e}(QR.createClient());return await g.connect(m),new QR(e,g,{initialState:{kind:"ready"},authProvider:h,sessionId:m.sessionId,protocolVersion:r.protocolVersion,...void 0===r.instructions?{}:{resumedInstructions:r.instructions},config:t,oauthLifecycleLogger:c,redactLogText:a?.redactLogText})}static async fromSessionlessInitialize(e,t,r,n,o,s=Tb,i,a,c,l){const u=await zR({serverName:e,config:t,tokenStorage:n,authRedirectUrl:s,fetchImpl:i,gtmMcpMatch:a,isScopePinGateEnabled:c});if(bR({url:t.url,headers:o,accessToken:u.tokens()?.access_token})!==r.credentialFingerprint)return;const{transportHeaders:d,baseFetch:h}=XR(t.url,o,i),p=new gR.j(new URL(t.url),{authProvider:u,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...d??{}}},fetch:h}),f=QR.createClient();return await f.connect(new SR(p,r.result)),new QR(e,f,{initialState:{kind:"ready"},authProvider:u,sessionlessInitialize:r,config:t,redactLogText:l})}get sessionId(){return this._sessionId}get protocolVersion(){return this._protocolVersion}get sessionlessInitialize(){return this._sessionlessInitialize}get holdsOAuthAccessToken(){return Boolean(this._authProvider?.tokens()?.access_token)}async openStandaloneStream(){const e=this.client.transport;e instanceof gR.j&&await e.resumeStream("")}static async fromCommand(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{OR(s,(0,D.VI)(e.withName("McpSdkClient.fromCommand")),!1);const l=(c=o?.spawn,void 0!==c||"linux"!==process.platform?c:(e,t,r)=>(0,au.D9)(iu.spawn,e,t,r)),u=r.args??[],d=new mR.oQ({command:r.command,args:u,env:rR(dR({command:r.command,args:u,env:n})),cwd:r.cwd,stderr:"pipe",...l&&{spawn:l}}),h=function(e){const t=new MR;let r=null===e;return null!==e&&(e.on("data",(e=>{t.full||t.push(e)})),e.once("end",(()=>{t.end(),r=!0}))),{read:()=>_P(t.text.replace(/\s+/g," ").trim(),{maxLength:ix}),waitForFlush:async()=>{r||null===e||await new Promise((t=>{let r;const n=()=>{void 0!==r&&clearTimeout(r),e.off("end",n),t()};r=setTimeout(n,250),r.unref(),e.once("end",n)}))}}}(d.stderr),p=QR.createClient({mcpAppsUi:o?.mcpAppsUi}),f=o?.connectTimeoutMs??(void 0!==(a=r.startupTimeoutSec)&&Number.isFinite(a)&&a>0?Math.min(1e3*a,3e5):6e4);let m;d.onclose=()=>{var e;void 0!==m&&(e=m,GR.delete(e))};let g=0,w=!0;d.onerror=e=>{w&&function(e){return e instanceof SyntaxError||"ZodError"===e.name}(e)&&(g+=1)};const y=new AbortController,v=p.connect(d,{timeout:f,signal:y.signal});let b;m=d.pid??void 0,void 0!==m&&(i=m,GR.add(i),VR||(VR=!0,process.on("exit",KR)));const S=new Promise(((e,r)=>{b=setTimeout((()=>r(new Error(`MCP server connection timed out after ${f}ms: ${t}`))),f)}));try{await Promise.race([v,S])}catch(e){throw y.abort(),v.catch((()=>{})),await d.close().catch((()=>{})),await h.waitForFlush(),g>0&&e instanceof Error&&(e.message=`${e.message}; non-JSON-RPC output on stdout before initialize (${String(g)} line${1===g?"":"s"})`),function(e,t){if(""===t)return e;const r=e instanceof Error?e:new Error(String(e));return r.message=`${r.message}; stderr: ${t}`,DR.set(r,t),r}(e,h.read())}finally{w=!1,void 0!==b&&clearTimeout(b)}return new QR(t,p,{initialState:{kind:"ready"},config:r,stdioServer:void 0!==m,serverSignals:vR(d)})}catch(e){s.error=e,s.hasError=!0}finally{FR(s)}var i,a,c}terminateSessionOnClose(e){this._sessionTermination=e}setToolCallRequestOptions(e){this._toolCallRequestOptions=e}failToolCallInFlight(e){const t=this._toolCallInFlight;return void 0!==t&&!t.signal.aborted&&(t.abort(e),!0)}onServerSignal(e){return this._serverSignals?.subscribe(e)??(()=>{})}setToolCallOutputSchemaPassthrough(e){this._toolCallOutputSchemaPassthrough=e}async close(){if(this._closeRequested=!0,this._terminatingSession)return;const e=this._sessionTermination,t=this.client.transport;if(void 0!==e&&t instanceof gR.j)return this._terminatingSession=!0,void(async()=>{await async function(e,t){const r=await async function(e,t){if(void 0===e.sessionId)return{outcome:"no_session",durationMs:0};const r=Date.now(),n=e.terminateSession();n.catch((()=>{}));try{await(0,Nr.wj)(n,t.timeoutMs)}catch(e){const t=Date.now()-r;return e instanceof Nr.MU?{outcome:"timeout",durationMs:t}:e instanceof gR.b&&void 0!==e.code&&e.code>0?{outcome:"rejected",durationMs:t,httpStatus:e.code,error:e.message}:{outcome:"failed",durationMs:t,error:String(e)}}const o=t.deleteObserver?.lastDeleteStatus;return{outcome:405===o?"unsupported":"terminated",durationMs:Date.now()-r,...void 0!==o?{httpStatus:o}:{}}}(e,t);try{t.onResult?.(r)}catch{}return r}(t,e),await this.client.close()})().catch((()=>{}));await this.client.close()}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=OR(t,(0,D.VI)(e.withName("McpSdkClient.getTools")),!1);if(r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("mcp.transport",BR(this.config)),"requires_authentication"===this.stateValue.kind)return r.span.setAttribute("mcp.tools.requires_authentication",!0),[];if("error"===this.stateValue.kind)return[];const n=++this._toolListGeneration;let o=0,s=0;try{const e=await this.tools.get((async()=>{let e;const t=await hR({fetchPage:async t=>{o++;const n=await async function(e,t,r){try{const r=await e.listTools({cursor:t});return{tools:r.tools,nextCursor:r.nextCursor,meta:r._meta,..._R}}catch(c){if(!(c instanceof Error&&"issues"in c&&Array.isArray(c.issues)))throw c}const n=await e.request({method:"tools/list",params:{cursor:t}},kR),o=[];let s=0,i=0,a=0;for(const e of n.tools){let t=e;if(TR(e)){const r=e.inputSchema;RR(r)&&(t=IR(e,r),s++)}let n=Fx.Dn.safeParse(t);if(!n.success&&(c=n.error).issues.some((e=>"outputSchema"===e.path[0]))){const o=Fx.Dn.safeParse(PR(t));o.success&&(a++,r(CR(e),ER(n.error),"output_stripped"),n=o)}n.success?o.push(n.data):(i++,r(CR(e),xR(n.error.issues),"dropped"))}var c;return{tools:o,nextCursor:"string"==typeof n.nextCursor?n.nextCursor:void 0,meta:n._meta,typeFilled:s,toolDropped:i,outputStripped:a}}(this.client,t,((e,t,n)=>{(function(e,t,r){const n=JSON.stringify([e,t,r]);if(eI.has(n))return eI.delete(n),eI.add(n),!1;if(eI.add(n),eI.size>256){const e=eI.keys().next().value;void 0!==e&&eI.delete(e)}return!0})(n,this.serverName,e??"")&&NR.warn(r.ctx,"output_stripped"===n?"Removed an MCP tool output schema the client rejected":"Left out an MCP tool whose definition is invalid",{serverName:this.serverName,..."string"==typeof e?{toolName:e}:{},issues:t})}));return s+=n.typeFilled,tI(r.ctx,"type_filled",n.typeFilled),tI(r.ctx,"tool_dropped",n.toolDropped),tI(r.ctx,"output_stripped",n.outputStripped),e??=function(e){if(!WC(e))return;const t=e.mcpAllowlist;if(!WC(t)||"string"!=typeof t.list)return;const r=HC(t.name,200),n=HC(t.reason,200);if(void 0===r||void 0===n)return;const o={list:"local"===t.list||"cloud"===t.list?t.list:"other",name:r,reason:n},s=qC(t.allowedServerNames)??qC(t.allowedServers);void 0!==s&&(o.allowedServers=s);const i=qC(t.blockedServers);return void 0!==i&&(o.blockedServers=i),o}(n.meta),n},itemsOf:e=>e.tools,nextCursorOf:e=>e.nextCursor});return this._allowlistInUse=this.reportsCursorMcpAllowlist()?e:void 0,t.map((e=>({...e,inputSchema:eE(e.inputSchema),outputSchema:void 0===e.outputSchema?void 0:eE(e.outputSchema)})))}));return this.noteToolListSuccess(),r.span.setAttribute("mcp.tools.fetched",o>0),r.span.setAttribute("mcp.tools.pages",o),o>0&&r.span.setAttribute("mcp.tools.type_filled",s),r.span.setAttribute("mcp.tools.count",e.length),e}catch(e){const t=JR(e);if(r.span.setAttribute("mcp.tools.fetched",o>0),r.span.setAttribute("mcp.tools.pages",o),o>0&&r.span.setAttribute("mcp.tools.type_filled",s),this.noteToolListFailure(r.ctx,t,n),t instanceof pR.D_&&n===this._toolListGeneration&&n>this._toolListStateGeneration&&"ready"===this.stateValue.kind){const e=this.stateValue,r=this._authProvider?.lastRedirectUrl?.toString()??"";this.stateValue={kind:"requires_authentication",url:r,callback:e=>this.completeRuntimeAuthorization(e)},this.discardToolListError(),this._logStateTransition(e,this.stateValue,"runtime_unauthorized",{...EP(t,this._redactLogText)}),this._stateEnteredAtMs=Date.now()}throw t}}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async getAllowlistInUse(){return this._allowlistInUse}reportsCursorMcpAllowlist(){return void 0!==this.config&&"url"in this.config&&BC(this.config.url)}toolListAttemptIsCurrent(e){return e>this._toolListSuccessGeneration&&e>this._toolListStateGeneration}noteToolListSuccess(){this._toolListError=void 0,this._toolListSuccessGeneration=this._toolListGeneration}discardToolListError(){this._toolListError=void 0,this._toolListStateGeneration=this._toolListGeneration}noteToolListFailure(e,t,r){const n=Fx.O4.MethodNotFound;if(t instanceof Fx.Nh&&t.code===n&&void 0===this.client.getServerCapabilities()?.tools)return void this.noteToolListSuccess();if(t instanceof pR.D_||!this.toolListAttemptIsCurrent(r))return;const o=function(e){if(e instanceof Fx.Nh)return{descriptor:`McpError ${e.code}`,errorClass:"McpError",jsonRpcCode:e.code};if(e instanceof gR.b||e instanceof fR._){const t=e instanceof gR.b?"StreamableHTTPError":"SseError",r="number"==typeof e.code?e.code:void 0;return{descriptor:void 0===r?t:`${t} ${r}`,errorClass:t,...void 0===r?{}:{httpStatus:r}}}return e instanceof Error?{descriptor:"Error",errorClass:"Error"}:{descriptor:"unknown",errorClass:"unknown"}}(t);o.descriptor!==this._toolListError&&NR.warn(e,"MCP server failed to list its tools",{serverName:this.serverName,errorClass:o.errorClass,...void 0!==o.jsonRpcCode?{jsonRpcCode:o.jsonRpcCode}:{},...void 0!==o.httpStatus?{httpStatus:o.httpStatus}:{}}),this._toolListError=o.descriptor}async callTool(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{const a=OR(s,(0,D.VI)(e.withName("McpSdkClient.callTool")),!1);a.span.setAttribute("toolName",t),a.span.setAttribute("serverName",this.serverName),a.span.setAttribute("mcp.transport",BR(this.config));const c=this._callToolLock,l=this._callToolQueueDepth;let u;this._callToolQueueDepth++,this._callToolLock=new Promise((e=>{u=e}));try{{const e={stack:[],error:void 0,hasError:!1};try{const t=OR(e,(0,D.VI)(a.ctx.withName("McpSdkClient.callTool.lockWait")),!1);t.span.setAttribute("serverName",this.serverName),t.span.setAttribute("mcp.call_tool.queued_ahead",l);const r=performance.now();await c;const n=performance.now()-r;t.span.setAttribute("mcp.call_tool.lock_wait_ms",n),a.span.setAttribute("mcp.call_tool.lock_wait_ms",n),a.span.setAttribute("mcp.call_tool.queued_ahead",l)}catch(t){e.error=t,e.hasError=!0}finally{FR(e)}}if("requires_authentication"===this.stateValue.kind)throw new pR.D_(`MCP server "${this.serverName}" requires authentication`);this._currentToolCallId=n,this._currentToolName=t,this._currentElicitationProvider=o;const s=new AbortController;this._toolCallInFlight=s;const u=this._authProvider?.lastRedirectUrl;try{const n={stack:[],error:void 0,hasError:!1};try{const o=OR(n,(0,D.VI)(a.ctx.withName("McpSdkClient.callTool.sdk")),!1);o.span.setAttribute("toolName",t),o.span.setAttribute("serverName",this.serverName);const c=await this.sendToolCall({name:t,arguments:r},s.signal);return o.span.setAttribute("mcp.call_tool.is_error",!0===c.isError),jR(e,this.config,{isError:!0===c.isError}),{content:c.content,isError:!0===c.isError,structuredContent:(i=c.structuredContent,tE(i)),_meta:lE(c._meta)}}catch(e){n.error=e,n.hasError=!0}finally{FR(n)}}catch(t){const r=JR(t);r instanceof Tx?(jR(e,this.config,{error:r,httpStatus:r.decision.status}),function(e,t){try{UR.increment(e,1,{decision:t.decision.kind,dropped:String(t.decision.dropped.length>0)})}catch{}}(e,r)):jR(e,this.config,{error:r});const n=r instanceof Tx&&"offer"===r.decision.kind&&void 0!==this._authProvider?.lastRedirectUrl&&this._authProvider.lastRedirectUrl!==u;if((r instanceof pR.D_||n)&&"ready"===this.stateValue.kind){const e=this.stateValue,t=this._authProvider?.lastRedirectUrl?.toString()??"";this.stateValue={kind:"requires_authentication",url:t,callback:e=>this.completeRuntimeAuthorization(e)},this.discardToolListError(),this._logStateTransition(e,this.stateValue,n?"scope_step_up":"runtime_unauthorized",{...EP(r,this._redactLogText)}),this._stateEnteredAtMs=Date.now()}throw r}finally{this._toolCallInFlight=void 0,this._currentElicitationProvider=void 0,this._currentToolCallId=void 0,this._currentToolName=void 0}}finally{this._callToolQueueDepth--,c.then(u)}}catch(e){s.error=e,s.hasError=!0}finally{FR(s)}var i}sendToolCall(e,t){const r=this._toolCallRequestOptions?.(e.name),n={...r,signal:void 0===r?.signal?t:AbortSignal.any([r.signal,t])};return!0===this._toolCallOutputSchemaPassthrough?.()?this.client.request({method:"tools/call",params:e},Fx.TF,n):this.client.callTool(e,void 0,n)}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{if(OR(t,(0,D.VI)(e.withName("McpSdkClient.getInstructions")),!1).span.setAttribute("serverName",this.serverName),"requires_authentication"===this.stateValue.kind)return;return this.client.getInstructions()??this._resumedInstructions}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{if(OR(t,(0,D.VI)(e.withName("McpSdkClient.listResources")),!1),"requires_authentication"===this.stateValue.kind||"error"===this.stateValue.kind)return{resources:[]};const r=this.client.getServerCapabilities();return r?.resources?{resources:await hR({fetchPage:e=>this.client.listResources({cursor:e}),itemsOf:e=>e.resources,nextCursorOf:e=>e.nextCursor})}:{resources:[]}}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{return OR(r,(0,D.VI)(e.withName("McpSdkClient.readResource")),!1),"requires_authentication"===this.stateValue.kind?{contents:[]}:{contents:(await this.client.readResource({uri:t.uri})).contents}}catch(e){r.error=e,r.hasError=!0}finally{FR(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{return OR(t,(0,D.VI)(e.withName("McpSdkClient.listPrompts")),!1),"requires_authentication"===this.stateValue.kind||"error"===this.stateValue.kind?[]:(this.client.getServerCapabilities()??{prompts:!1}).prompts?(await hR({fetchPage:e=>this.client.listPrompts({cursor:e}),itemsOf:e=>e.prompts,nextCursorOf:e=>e.nextCursor})).map((e=>({name:e.name,description:e.description,arguments:e.arguments?.map((e=>({name:e.name,description:e.description,required:e.required})))}))):[]}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async getPrompt(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{return OR(n,(0,D.VI)(e.withName("McpSdkClient.getPrompt")),!1),"requires_authentication"===this.stateValue.kind?{messages:[]}:{messages:(await this.client.getPrompt({name:t,arguments:r})).messages.map((e=>({role:e.role,content:Array.isArray(e.content)?e.content.map((e=>"text"===e.type?{type:"text",text:e.text}:"image"===e.type?{type:"image",data:e.data,mimeType:e.mimeType}:{type:"text",text:JSON.stringify(e)})):[{type:"text",text:"string"==typeof e.content?e.content:JSON.stringify(e.content)}]})))}}catch(e){n.error=e,n.hasError=!0}finally{FR(n)}}getCurrentToolCallContext(){if(this._currentToolName)return{toolName:this._currentToolName,toolCallId:this._currentToolCallId}}async getState(e){return"ready"===this.stateValue.kind&&void 0!==this._toolListError?{kind:"ready",toolListError:this._toolListError}:this.stateValue}async completeRuntimeAuthorization(e){if(!this._authCodeExchange)throw new Error(`MCP server "${this.serverName}" cannot complete authorization: no code exchange is configured for this client.`);try{await this._authCodeExchange(e)}catch(e){const t=e instanceof Error?e.message:"Authentication failed";throw new Error(`Authentication callback failed: ${t}`)}this.updateState({kind:"ready"},"runtime_authorization_completed")}updateState(e,t){const r=this.stateValue;this.discardToolListError(),this.stateValue=e,this._logStateTransition(r,e,t??"explicit_update"),this._stateEnteredAtMs=Date.now()}}const YR=(0,h.Pu)("mcp_tool.schema",{description:"One MCP tool definition a tools/list repair touched",labelNames:["outcome"]}),eI=new Set;function tI(e,t,r){if(0!==r)try{YR.increment(e,r,{outcome:t})}catch{}}class rI extends Error{constructor(e,t){super(`MCP server ${e} not found, available servers: ${t.join(", ")}`),this.serverName=e,this.availableServers=t,this.name="McpServerNotFoundError"}}Error,Error;class nI{constructor(e){this.tools=e}async execute(e,t,r,n){const o=this.tools[e];if(!o)throw new kC(e,Object.keys(this.tools));return o.execute(t,r,n)}async executeOn(e,t,r,n,o){const s=this.tools[t];if(!s)throw new kC(t,Object.keys(this.tools));if(s.client===e)return s.execute(r,n,o)}getTools(){return Object.entries(this.tools).map((([e,t])=>({...t.definition,name:e})))}}class oI{async getClients(e){return{}}async getClient(e,t){}async getInstructions(e){return[]}async getToolSet(e){return new nI({})}async getTools(e){return[]}async getToolsForServers(e,t){return[]}}class sI{constructor(e){this.manager=e}async getClients(e){return this.manager.getClients()}async getClient(e,t){return this.manager.getClient(t)}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=OR(t,(0,D.VI)(e.withName("ManagerMcpLease.getInstructions")),!1);return await this.manager.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async getToolSet(e){const t={stack:[],error:void 0,hasError:!1};try{const r=OR(t,(0,D.VI)(e.withName("ManagerMcpLease.getToolSet")),!1);return await this.manager.getToolSet(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=OR(t,(0,D.VI)(e.withName("ManagerMcpLease.getTools")),!1);return(await this.getToolSet(r.ctx)).getTools()}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async getToolsForServers(e,t){const r=new Set(t);return(await this.getTools(e)).filter((e=>r.has(e.clientKey)))}onDidChange(e){return{dispose:this.manager.onDidChange((()=>e(void 0)))}}async reconcileSelection(e,t,r){for(const e of t.removed){const t=this.manager.getClient(e);this.manager.deleteClient(e);try{await(t?.close?.())}catch{}}for(const n of t.added){if(this.manager.getClient(n))continue;const t=await r(e,n);this.manager.setClient(n,t)}}}class iI{constructor(e,t){this.clients=e,this.elicitationFactory=t,this.changeListeners=new Set,this.warnedToolNameCollisions=new Set}onDidChange(e){return this.changeListeners.add(e),()=>{this.changeListeners.delete(e)}}fireDidChange(){for(const e of this.changeListeners)try{e()}catch(e){console.error("Error in McpManager change listener:",e)}}getClients(){return this.clients}getClient(e){return this.clients[e]}setClient(e,t){this.clients[e]=t,this.fireDidChange()}deleteClient(e){delete this.clients[e],this.fireDidChange()}setListingDeadline(e){this.listingDeadlineAt=void 0===e?void 0:performance.now()+e}async closeAllClients(){const e=Object.values(this.clients);await Promise.all(e.map((async e=>{try{await(e.close?.())}catch{}})))}async getToolSet(e){const t={stack:[],error:void 0,hasError:!1};try{const r=OR(t,(0,D.VI)(e.withName("McpManager.getToolSet")),!1),n=OR(t,aI(this.listingDeadlineAt),!1),o=await(0,Nr.PH)(Object.entries(this.clients),(([e,t])=>n.within(t,r.ctx,(()=>t.getTools(r.ctx))).then((r=>(r??[]).map((r=>({...r,clientKey:e,clientName:t.serverName,client:t}))))).catch((()=>[]))),{max:n.concurrency}),s=Array.from(o.values()).flat(),i=new Map;for(const e of s){const t=`${e.clientName}-${e.name}`,r=i.get(t);void 0===r?i.set(t,[e]):r.push(e)}const a={};for(const[e,t]of i){const n=t[0];if(void 0===n)continue;if(t.some((e=>e.clientName!==n.clientName||e.name!==n.name))){if(!this.warnedToolNameCollisions.has(e)){this.warnedToolNameCollisions.add(e);const r=t.map((e=>`${e.clientName}/${e.name}`)).join(", ");console.warn("Colliding MCP tool name; exposing neither:",`${e} (${r})`)}continue}const o=t[t.length-1]?.clientKey,s=t.filter((e=>e.clientKey===o)),i=s[0]??n;s.length>1&&!this.warnedToolNameCollisions.has(e)&&(this.warnedToolNameCollisions.add(e),console.warn("MCP server lists a tool name more than once; using the first:",`${i.clientName}/${i.name}`)),a[e]={definition:{...i,clientKey:i.clientKey,providerIdentifier:i.clientName,toolName:i.name},client:i.client,execute:async(e,t,n)=>{const o=n?.createProvider(i.clientName,i.name,t);return await i.client.callTool(r.ctx,i.name,e,t,o)}}}return new nI(a)}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=OR(t,(0,D.VI)(e.withName("McpManager.getInstructions")),!1),n=OR(t,aI(this.listingDeadlineAt),!1),o=await(0,Nr.PH)(Object.entries(this.clients),(([e,t])=>n.within(t,r.ctx,(()=>t.getInstructions(r.ctx))).then((e=>e&&0!==e.trim().length?new vn.I0({serverName:t.serverName,instructions:e.trim()}):null)).catch((()=>null))),{max:n.concurrency});return Array.from(o.values()).filter((e=>null!==e))}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}}function aI(e){if(void 0===e)return{concurrency:4,within:(e,t,r)=>r(),[Symbol.dispose]:()=>{}};let t;const r=new Promise((r=>{t=setTimeout((()=>r(void 0)),Math.max(0,e-performance.now()))}));return{concurrency:Number.POSITIVE_INFINITY,within:async(t,n,o)=>{const s=await Promise.race([t.getState(n).catch((()=>{})),r]);if("ready"!==s?.kind)return Promise.race([o(),r]);let i;try{return await Promise.race([o(),new Promise((t=>{i=setTimeout((()=>t(void 0)),Math.max(2e3,e-performance.now()))}))])}finally{clearTimeout(i)}},[Symbol.dispose]:()=>clearTimeout(t)}}function cI(e,t){return function(e){const{logger:t,ctx:r}=e;return{debug:(e,n)=>t.debug(r,e,n),info:(e,n)=>t.info(r,e,n),warn:(e,n)=>t.warn(r,e,n),error:(e,n,o)=>t.error(r,e,n,o)}}({ctx:e,logger:t})}Error;class lI{constructor(e){this.options=e,PP({logger:e.logger,event:"mcp_oauth_provider_initialized",metadata:this.baseMetadata})}get baseMetadata(){return{identifier:this.options.identifier,...this.options.serverUrl?{serverUrl:iP(this.options.serverUrl)}:{}}}async loadTokens(){const e=await this.options.inner.loadTokens();return PP({logger:this.options.logger,event:"mcp_oauth_tokens_loaded",level:"debug",metadata:{...this.baseMetadata,...eR(e)}}),e}async saveTokens(e){await this.options.inner.saveTokens(e),PP({logger:this.options.logger,event:"mcp_oauth_tokens_saved",metadata:{...this.baseMetadata,...eR(e,{expiresInIsFresh:!0})}})}async prepareForRefresh(){PP({logger:this.options.logger,event:"mcp_oauth_refresh_prepare",metadata:this.baseMetadata}),await(this.options.inner.prepareForRefresh?.())}async releaseRefreshLeaseOnError(e){PP({logger:this.options.logger,event:"mcp_oauth_refresh_error_release",level:"warn",error:e,metadata:{...this.baseMetadata,...EP(e,this.options.redactLogText)}}),await(this.options.inner.releaseRefreshLeaseOnError?.(e))}async loadClientInformation(){const e=await this.options.inner.loadClientInformation();return PP({logger:this.options.logger,event:"mcp_oauth_client_info_loaded",level:"debug",metadata:{...this.baseMetadata,...lP(e)}}),e}async saveClientInformation(e){await this.options.inner.saveClientInformation(e),PP({logger:this.options.logger,event:"mcp_oauth_client_info_saved",metadata:{...this.baseMetadata,...lP(e)}})}async invalidateCredentials(e){void 0!==this.options.inner.invalidateCredentials&&(PP({logger:this.options.logger,event:"mcp_oauth_credentials_invalidated",level:"warn",metadata:{...this.baseMetadata,scope:e}}),await this.options.inner.invalidateCredentials(e))}tokenEndpointAuth(e){return this.options.inner.tokenEndpointAuth?.(e)}get loadScopeStepUpRecord(){return this.options.inner.loadScopeStepUpRecord?.bind(this.options.inner)}get saveScopeStepUpRecord(){return this.options.inner.saveScopeStepUpRecord?.bind(this.options.inner)}}class uI{constructor(e,t){this.storage=e,this.identifier=t}async loadTokens(){return this.storage.loadTokens(this.identifier)}async saveTokens(e){return this.storage.saveTokens(this.identifier,e)}async loadClientInformation(){return this.storage.loadClientInformation(this.identifier)}async saveClientInformation(e){return this.storage.saveClientInformation(this.identifier,e)}get loadScopeStepUpRecord(){const{storage:e,identifier:t}=this;return void 0===e.loadScopeStepUpRecord?void 0:()=>e.loadScopeStepUpRecord(t)}get saveScopeStepUpRecord(){const{storage:e,identifier:t}=this;return void 0===e.saveScopeStepUpRecord?void 0:r=>e.saveScopeStepUpRecord(t,r)}}class dI{constructor(e){this.inner=e}async loadTokens(){}async loadClientInformation(){}async saveTokens(e){return this.inner.saveTokens(e)}async saveClientInformation(e){return this.inner.saveClientInformation(e)}async invalidateCredentials(e){await(this.inner.invalidateCredentials?.(e))}get loadScopeStepUpRecord(){return this.inner.loadScopeStepUpRecord?.bind(this.inner)}get saveScopeStepUpRecord(){return this.inner.saveScopeStepUpRecord?.bind(this.inner)}async loadGrantedScope(){return void 0!==this.inner.loadGrantedScope?this.inner.loadGrantedScope():(await this.inner.loadTokens())?.scope}}var hI=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},pI=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const fI=(0,d.h)("DefinitionMcpLoader"),mI=(0,h.Pu)("connector_policy.blocked",{description:"MCP servers a team or org policy refused to load, once per loader and server.",labelNames:["surface","stage","reason"]});function gI(e){const{filePath:t,baseDir:r}=e;return"~"===t||t.startsWith("~/")?s.join(o.homedir(),t.slice(1)):t.startsWith("./")||"."===t?s.resolve(r??process.cwd(),t):t}function wI(e){return"getManagedSlackWorkspaceLists"in e&&"function"==typeof e.getManagedSlackWorkspaceLists}function yI(e){return"getMcpNetworkControlsConfig"in e&&"function"==typeof e.getMcpNetworkControlsConfig}function vI(e){return e?.length??0}function bI(e){if(void 0!==e)return(0,ko.createHash)("sha256").update(ME(e)).digest("hex")}function SI(e){if(void 0===e)return;let t;return r=>(void 0===t&&(t=e(),queueMicrotask((()=>{t=void 0}))),t?tx(r):r)}async function kI(e,t,n,o,s={middlewares:[],configPath:""},i,a,c={},l={}){const u={stack:[],error:void 0,hasError:!1};try{const{middlewares:d,configPath:h}=s,p=hI(u,(0,D.VI)(e.withName("mcp-agent-exec.loadServer")),!1);p.span.setAttribute("serverName",t);const f=!1!==l.mcpAppsUi;p.span.setAttribute("mcpAppsUi",f),fI.info(p.ctx,`Loading MCP server "${t}" ${f?"declaring":"without declaring"} the MCP Apps UI extension`,{event:"mcp_apps_ui_capability",serverName:t,mcpAppsUi:f,transport:"command"in n?"stdio":"http"});let m=async(e,n)=>{const s={stack:[],error:void 0,hasError:!1};try{const u=hI(s,(0,D.VI)(e.withName("loadServer.next")),!1);u.span.setAttribute("serverName",t);const h=u.ctx;if("command"in n){u.span.setAttribute("kind","command");const e=d.find(yI);return await async function(e,t,n,o,s={}){const i=n.cwd?gI({filePath:n.cwd}):void 0;let a,c;if(n.args&&n.args.length>0)a=gI({filePath:n.command,baseDir:i}),c=n.args.map((e=>gI({filePath:e,baseDir:i})));else{const e=(0,rx.A)(n.command);a=gI({filePath:e[0],baseDir:i}),c=e.slice(1).map((e=>gI({filePath:e,baseDir:i})))}const l=n.env??{},{startupTimeoutSec:u}=n,d=await(o?.getMcpNetworkControlsConfig?.({command:[n.command,...n.args??[]].join(" ")})),h=(0,Lb.$H)(d);if(void 0!==h){const{buildMcpSandboxPolicy:n}=await r.e(449).then(r.bind(r,"../mcp-agent-exec/dist/mcp-sandbox-policy.js")),{SandboxUnsupportedError:o,spawnInSandbox:p}=await Promise.resolve().then(r.bind(r,"../shell-exec/dist/api/index.js")),f=i??process.cwd(),m=await n(h,f);fI.info(e,function(e){return`Sandboxing local MCP server "${e.serverName}" with network controls: networkControlsEnabled=${String(!0===e.networkControlsConfig?.enabled)}, mcpNetworkMode=${e.networkControlsConfig?.mcpNetworkMode??"unset"}, mcpNetworkAllowlistCount=${vI(e.networkControlsConfig?.mcpNetworkAllowlist)}, mcpNetworkDenylistCount=${vI(e.networkControlsConfig?.mcpNetworkDenylist)}, localAgentNetworkAllowlistCount=${vI(e.networkControlsConfig?.localAgentNetworkAllowlist)}, sandboxPolicyHash=${bI(e.sandboxNetworkControlsConfig)??"none"}`}({serverName:t,networkControlsConfig:d,sandboxNetworkControlsConfig:h}),function(e){return{event:"mcp_stdio_sandbox_policy",serverName:e.serverName,networkControlsEnabled:!0===e.networkControlsConfig?.enabled,mcpNetworkMode:e.networkControlsConfig?.mcpNetworkMode,mcpNetworkAllowlistCount:vI(e.networkControlsConfig?.mcpNetworkAllowlist),mcpNetworkDenylistCount:vI(e.networkControlsConfig?.mcpNetworkDenylist),localAgentNetworkAllowlistCount:vI(e.networkControlsConfig?.localAgentNetworkAllowlist),sandboxPolicyHash:bI(e.sandboxNetworkControlsConfig)}}({serverName:t,networkControlsConfig:d,sandboxNetworkControlsConfig:h}));try{return await QR.fromCommand(e,t,{command:a,args:c,cwd:i,startupTimeoutSec:u},l,{...s,spawn:(e,t,r)=>p(e,t,r,m)})}catch(e){if(e instanceof o)throw new DE(t,e);throw e}}return!0===d?.enabled&&"no_sandbox"===d.mcpNetworkMode&&(!0===d.win32UserExtensionUnsandbox?fI.info(e,`Starting local MCP server "${t}" without MCP sandboxing`,{event:"mcp_stdio_win32_user_extension_unsandbox",serverName:t}):fI.info(e,`Starting local MCP server "${t}" without MCP sandboxing`)),QR.fromCommand(e,t,{command:a,args:c,cwd:i,startupTimeoutSec:u},l,s)}(h,t,n,e,l)}if("url"in n){u.span.setAttribute("kind","url");const e=i?.(t);return await async function(e,t,r,n,o,s,i,a,c={}){const l=cI(e,fI),u=function(e,t,r){return{logger:{debug:(t,r)=>fI.debug(e,t,r),info:(t,r)=>fI.info(e,t,r),warn:(t,r)=>fI.warn(e,t,r),error:(t,r,n)=>fI.error(e,t,r,n)},metadata:{identifier:t,source:"mcp-agent-exec"},redactLogText:SI(r)}}(e,t,a),d=void 0!==s&&LE(r.url)?jE(globalThis.fetch.bind(globalThis),{managedSlackWorkspaceLists:()=>s.getManagedSlackWorkspaceLists()}):void 0;return QR.fromStreamableHttp(t,r,n,r.headers,o,d,u,l,void 0,void 0,i,!1,c)}(h,t,n,o,e,d.find(wI),a,c.isLinkSharedPaymentTokenLogRedactionEnabled,l)}throw new Error(`Invalid server: ${JSON.stringify(n)}`)}catch(e){s.error=e,s.hasError=!0}finally{pI(s)}};for(const e of d){const r=m;m=async(n,o)=>await e.load(n,t,o,h,r)}try{return await m(p.ctx,n)}catch(e){throw function(e,t){if(void 0===t)return e;!function(e,t){if("object"!=typeof e||null===e)return;const r=DR.get(e);void 0!==r&&DR.set(e,t(r))}(e,t);const r=function(e,t){if(void 0===t)return e;const r={results:new Map,cycled:new Set},n=UE(e,t,r),o=new Map([...r.cycled].flatMap((e=>{const t=r.results.get(e);return t===e?[]:[[e,t]]})));return o.size>0&&function(e,t){const r=new Set,n=[e];for(let e=0;n.length>0&&e({identifier:e,serverConfig:t,configPath:this.configPath})))}}class CI{constructor(e,t,r=[],n={}){this.source=e,this.tokenStorage=t,this.middlewares=r,this.options=n,this.clientCache=new Map}async load(e,t=!0){const r={stack:[],error:void 0,hasError:!1};try{hI(r,(0,D.VI)(e.withName("DefinitionMcpLoader.load")),!1),t||(await this.closeAllCachedClients(),this.source.clearCache?.());const n=await this.source.getDefinitions(e,t);await this.evictClientsOnSandboxPolicyChange(e,n);const o={};return await(0,Nr.PH)([...n],(async r=>{try{const n=t?this.clientCache.get(r.identifier):void 0,s=n??await this.loadDefinitionClient(e,r);n||this.clientCache.set(r.identifier,s),o[r.identifier]=s}catch(t){if(this.handleDefinitionLoadError(e,r,t))return;!function(e,t,r,n){const o=SI(n)??(e=>e),s=function(e){if("object"==typeof e&&null!==e)return DR.get(e)}(r);fI.warn(e,"Failed to load MCP server",{identifier:t.identifier,source:t.source,configPath:t.configPath,metadata:t.metadata,errorMessage:o(r instanceof Error?r.message:String(r)),stderrTail:void 0===s?void 0:o(s)})}(e,r,t,this.options.isLinkSharedPaymentTokenLogRedactionEnabled)}}),{max:this.options.maxConcurrency??Math.max(n.length,1)}),new iI(o,this.options.elicitationFactory)}catch(e){r.error=e,r.hasError=!0}finally{pI(r)}}clearClient(e){this.clientCache.delete(e)}clearAllMcpCaches(){this.clientCache.clear()}async evictClientsOnSandboxPolicyChange(e,t){const r=this.middlewares.find(yI);if(!r)return;let n;try{n=JSON.stringify(await Promise.all([...t].sort(((e,t)=>e.identifier.localeCompare(t.identifier))).map((async e=>{const t=await(r.getMcpNetworkControlsConfig?.((n=e.serverConfig,"url"in n?{url:n.url}:{command:[n.command,...n.args??[]].join(" ")})))??{};var n;return[e.identifier,ME(t)]}))))}catch{return}const o=this.sandboxPolicyFingerprint;this.sandboxPolicyFingerprint=n,void 0!==o&&o!==n&&(fI.info(e,"MCP network-controls policy changed; reloading MCP clients to apply the new egress policy"),await this.closeAllCachedClients())}async closeAllCachedClients(){const e=[...this.clientCache.values()];this.clientCache.clear(),await(0,Nr.PH)(e,(async e=>{try{await(e.close?.())}catch{}}),{max:Math.max(e.length,1)})}async loadClient(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{hI(n,(0,D.VI)(e.withName("DefinitionMcpLoader.loadClient")),!1);const o=await this.source.getDefinitions(e);if(await this.evictClientsOnSandboxPolicyChange(e,o),!r){const e=this.clientCache.get(t);if(e)return e}const s=o.find((e=>e.identifier===t));if(!s)throw new Error(`MCP server "${t}" not found in config`);let i;try{i=await this.loadDefinitionClient(e,s,r)}catch(t){throw this.handleDefinitionLoadError(e,s,t),t}return r||this.clientCache.set(t,i),i}catch(e){n.error=e,n.hasError=!0}finally{pI(n)}}async loadDefinitionClient(e,t,r){const n=t.authStorageKey??t.identifier,o=new uI(this.tokenStorage,n),s=cI(e,fI),i=new lI({inner:o,logger:s,redactLogText:SI(this.options.isLinkSharedPaymentTokenLogRedactionEnabled),identifier:n,serverUrl:"url"in t.serverConfig?t.serverConfig.url:void 0}),a=r?new dI(i):i;return kI(e,t.identifier,t.serverConfig,a,{middlewares:this.middlewares,configPath:t.configPath??""},this.options.authRedirectUrlGenerator,this.options.scopeChallengeStepUp,{isLinkSharedPaymentTokenLogRedactionEnabled:this.options.isLinkSharedPaymentTokenLogRedactionEnabled})}handleDefinitionLoadError(e,t,r){let n=!1;try{n="handled"===this.options.onDefinitionLoadError?.(e,t,r)}catch(r){fI.warn(e,"MCP definition load error hook failed",{identifier:t.identifier,source:t.source,configPath:t.configPath,metadata:t.metadata,errorMessage:r instanceof Error?r.message:String(r)})}return n||function(e){return e instanceof AC||e instanceof $C||e instanceof MC||e instanceof EI}(r)}}class EI extends Error{constructor(e,t,r){super(r??("teamNetworkAllowlist"===t?`MCP server "${e}" is not on the team network allowlist`:`MCP server "${e}" is blocked by team policy`)),this.serverName=e,this.reason=t,this.name="McpServerBlockedError"}}const xI=[1e3,3e3];class PI{constructor(e){this.blockingService=e,this.countedPolicyBlocks=new Set}async getMcpNetworkControlsConfig(e){return await(this.blockingService.getMcpNetworkControlsConfig?.(e))??{}}async getManagedSlackWorkspaceLists(){return await(this.blockingService.getManagedSlackWorkspaceLists?.())??[]}async load(e,t,r,n,o){const s=function(e){return{command:"command"in e?[e.command,...e.args??[]].join(" "):void 0,url:"url"in e?e.url:void 0}}(r),i=await(this.blockingService.getMcpServerBlockInfo?.(s))??{blocked:await this.blockingService.isServerBlocked(s)};if(i.blocked){const r=i.reason??"teamPolicy";throw"teamPolicy"!==r||this.countedPolicyBlocks.has(t)||(this.countedPolicyBlocks.add(t),mI.increment(e,1,{surface:"desktop",stage:"tool_call",reason:"server_not_allowed"})),new EI(t,r,i.message)}for(let n=0;;n++)try{const t=await o(e,r);return!0===i.hostMcpBridge&&this.blockingService.recordHostMcpBridgeClient?.(t),this.blockingService.recordMcpServerClient?.(t,s),t}catch(e){if(e instanceof FE)throw new EI(t,"teamPolicy",e.message);const r=e instanceof NE?xI[n]:void 0;if(void 0===r)throw e;await(0,Nr.cb)(r)}}}class RI extends CI{constructor(e,t,r=[],n={}){super(new _I(e),t,r,n),this.configPath=e}static init(e,t,r=[]){return new RI(t,e,r)}}function II(e){return"stdio"===e.type&&e.command?{command:e.command,args:e.args??[],env:e.env,cwd:e.cwd}:"streamableHttp"===e.type&&e.url?{url:e.url,headers:e.headers,auth:e.auth,...void 0!==e.tls?{tls:e.tls}:{},...void 0!==e.placement?{placement:e.placement}:{}}:void 0}var TI=r("../utils/dist/private-file.js"),AI=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js");function $I(e){const t=AI.VE.safeParse(e);return t.success?t.data:void 0}function MI(e){const t=AI.H5.safeParse(e);return t.success?t.data:void 0}class DI{constructor(e){this.mcpAuthPath=e;const t=DI.mcpAuthPromises.get(e);if(t)this.mcpAuthPromise=t;else{const t=this.loadMcpAuth();this.mcpAuthPromise=t,DI.mcpAuthPromises.set(e,t),t.catch((()=>{DI.mcpAuthPromises.get(e)===t&&DI.mcpAuthPromises.delete(e)}))}DI.saveLocks.has(e)||DI.saveLocks.set(e,Promise.resolve())}async loadMcpAuth(){try{await(0,TI.rV)(this.mcpAuthPath);const e=await(0,xo.readFile)(this.mcpAuthPath,"utf8"),t=JSON.parse(e);if(t&&"object"==typeof t){if(Object.values(t).some((e=>e&&"object"==typeof e&&null!==e&&("access_token"in e||"refresh_token"in e)&&!("tokens"in e)&&!("clientInfo"in e)))){const e={};for(const[r,n]of Object.entries(t)){const t=$I(n);void 0!==t&&(e[r]={tokens:t})}return e}const e={};for(const[r,n]of Object.entries(t))n&&"object"==typeof n&&null!==n&&(e[r]={tokens:"tokens"in n?$I(n.tokens):void 0,clientInfo:"clientInfo"in n?MI(n.clientInfo):void 0,..."scopeStepUp"in n?{scopeStepUp:n.scopeStepUp}:{}});return e}return{}}catch(e){if(e instanceof Error&&e.message.includes("ENOENT"))return{};throw e}}async loadTokens(e){const t=await this.mcpAuthPromise;return t[e]?.tokens}async saveTokens(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),r[e].tokens=t,await this.saveMcpAuth(r)}))}async loadClientInformation(e){const t=await this.mcpAuthPromise;return t[e]?.clientInfo}async withSaveLock(e){const t=DI.saveLocks.get(this.mcpAuthPath)??Promise.resolve();let r;DI.saveLocks.set(this.mcpAuthPath,new Promise((e=>{r=e})));try{return await t,await e()}finally{r()}}async saveClientInformation(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),r[e].clientInfo=t,await this.saveMcpAuth(r)}))}async loadScopeStepUpRecord(e){const t=await this.mcpAuthPromise;return t[e]?.scopeStepUp}async saveScopeStepUpRecord(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),void 0===t?delete r[e].scopeStepUp:r[e].scopeStepUp=t,await this.saveMcpAuth(r)}))}async deleteCredentials(e){await this.withSaveLock((async()=>{const t=await this.mcpAuthPromise;e in t&&(delete t[e],await this.saveMcpAuth(t))}))}async saveMcpAuth(e){await(0,TI.Pl)(this.mcpAuthPath,JSON.stringify(e,null,2))}}DI.mcpAuthPromises=new Map,DI.saveLocks=new Map,(0,b.cF)(Symbol("execHookConversationId"),void 0),(0,b.cF)(Symbol("execHookGenerationId"),void 0),(0,b.cF)(Symbol("execHookModel"),void 0);const OI=(0,b.cF)(Symbol("execHookWorkspaceRoots"),void 0);var FI=r("../proto/dist/generated/agent/v1/write_exec_pb.js"),NI=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},LI=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const jI=(0,h.Pu)("mcp.filesystem.divergence",{description:"Divergence detected between MCP lease state and filesystem state",labelNames:["divergence_type","mcp_source","configured_servers","mcp_version"]}),UI=(0,h.Pu)("mcp.filesystem.sync_check",{description:"MCP filesystem sync check executed",labelNames:["synced","mcp_source","configured_servers","mcp_version"]}),BI=(0,h.wt)("mcp.filesystem.sync_check.expected_servers",{description:"Number of expected MCP servers at last sync check",labelNames:["mcp_source","mcp_version"]}),WI=(0,h.wt)("mcp.filesystem.sync_check.actual_servers",{description:"Number of actual MCP servers on disk at last sync check",labelNames:["mcp_source","mcp_version"]}),HI=(0,h.wt)("mcp.filesystem.sync_check.servers_missing",{description:"Number of expected MCP servers missing from disk at last sync check",labelNames:["mcp_source","mcp_version"]}),qI=(0,h.wt)("mcp.filesystem.sync_check.tool_mismatches",{description:"Number of MCP servers with tool count mismatches at last sync check",labelNames:["mcp_source","mcp_version"]}),zI=(0,d.h)("McpFileSystemWriter"),GI="mcpFsStructuredLogOptIn";function VI(e,t){return t?.includeStructuredLogs?{...e??{},[GI]:!0}:e}const KI={debug(e,t,r,n){zI.debug(e,t,VI(r,n))},info(e,t,r,n){zI.info(e,t,VI(r,n))},warn(e,t,r,n){zI.warn(e,t,VI(r,n))},error(e,t,r,n,o){zI.error(e,t,r,VI(n,o))}},JI="mcps",ZI="tools",XI="~staging",QI="~prev",YI=[25,50,100,200],eT=new Set(["EPERM","EBUSY","EACCES"]),tT=new Map;function rT(e){return e.slice(0,e.indexOf("~"))}function nT(e,t){return`${e}~${Date.now()}-${process.pid}-${(0,ko.randomBytes)(4).toString("hex")}${t}`}const oT=/~(\d+)-\d+-[0-9a-f]+~(?:staging|prev)$/;async function sT(e,t){const r=oT.exec(t),n=r?Number(r[1]):0;try{const{mtimeMs:r}=await(0,xo.stat)((0,s.join)(e,t));return Date.now()-Math.max(n,r)>6e4}catch{return!1}}const iT="mcp_auth",aT="Authenticate this MCP server so its tools can be used. Call this tool through your MCP tool-calling interface when STATUS.md indicates this server needs authentication.",cT="# >>> CURSOR MANAGED BLOCK >>>",lT="# <<< CURSOR MANAGED BLOCK <<<",uT=["# Ignore everything in .cursor","*","# Un-ignore projects so we can descend to allowlisted subdirs","!projects/","projects/*","!projects/*/","projects/*/*","# MCP tool descriptors, resources, prompts","!projects/*/mcps/","!projects/*/mcps/**","# Agent transcripts for citation","!projects/*/agent-transcripts/","!projects/*/agent-transcripts/**","# Terminal output files","!projects/*/terminals/","!projects/*/terminals/**","# Conversation notes (shared scratchpad)","!projects/*/agent-notes/","!projects/*/agent-notes/**","# Large tool output files","!projects/*/agent-tools/","!projects/*/agent-tools/**","# Plugin cache (rules, skills, agents)","!plugins/","!plugins/**","# Built-in Cursor skills","!skills-cursor/","!skills-cursor/**","# User's personal skills","!skills/","!skills/**","# User's personal slash commands","!commands/","!commands/**","# User's plan files","!plans/","!plans/**","# Subagent state/transcripts","!subagents/","!subagents/**","# User-level cursor rules","!rules/","!rules/**"].join("\n");function dT(e,t,r=15e3){let n;return Promise.race([e.catch((()=>t)),new Promise((e=>{n=setTimeout((()=>e(t)),r)}))]).finally((()=>clearTimeout(n)))}function hT(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function pT(e){if(void 0===e)return;const t=e.trim();return t.length>0?t:void 0}function fT(e){switch(e.kind){case"loading":return"initializing";case"requires_authentication":return"needsAuth";case"ready":return"connected";case"error":return"error";default:return"disconnected"}}function mT(e){if(Array.isArray(e))return e.map((e=>mT(e)));if(function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e)){const t=Object.entries(e).filter((([,e])=>void 0!==e)).sort((([e],[t])=>et?1:0)).map((([e,t])=>[e,mT(t)]));return Object.fromEntries(t)}return e}function gT(e){return JSON.stringify(mT(e))}function wT(e){const t=e.map((e=>({value:e,key:gT(e)})));return t.sort(((e,t)=>e.keyt.key?1:0)),t.map((e=>e.value))}function yT(e){const t=wT(e.tools.map((e=>({name:e.toolName,description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema})))),r=wT(e.resources.map((e=>({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType})))),n=wT(e.prompts.map((e=>({name:e.name,description:e.description,arguments:e.arguments}))));return gT({id:e.serverIdentifier,name:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,tools:t,resources:r,prompts:n,instructions:e.instructions,status:e.status})}class vT{constructor(e,t,r){this.cachedFingerprints=new Map,this.disposed=!1,this.hasPendingLeaseChangeEvent=!1,this.lastDivergenceCheckMs=0,this.mcpLease=e,this.projectDir=t,this.debounceMs=r?.debounceMs??100,this.mcpAuthCopyOverrides=r?.mcpAuthCopyOverrides,this.exposeVirtualMcpAuthTool=r?.exposeVirtualMcpAuthTool??!0,this.alwaysExposeVirtualMcpAuthTool=r?.alwaysExposeVirtualMcpAuthTool??!1,this.snapshotProvider=r?.snapshotProvider,this.mcpVersion=r?.mcpVersion??(this.snapshotProvider?"snapshots":"v1"),this.onDidWrite=r?.onDidWrite,this.ctx=this.getContext(r?.loggerBackend),this.startupCleanupPromise=this.cleanupStaleStagingDirs(this.ctx),this.leaseChangeDisposable=this.mcpLease.onDidChange((e=>{KI.info(this.ctx,"Lease change event received",{serverIdentifiers:e?.serverIdentifiers,reason:e?.reason}),this.onLeaseChanged(this.ctx,e)})),KI.info(this.ctx,"Constructor: scheduling initial write"),this.scheduleWrite(this.ctx),this.ensureCursorDirGitignore()}ensureCursorDirGitignore(){(async function(e){const t=(0,s.join)(e,".gitignore"),r=`${cT}\n${uT}\n${lT}\n`;let n;await(0,xo.mkdir)(e,{recursive:!0});try{n=await(0,xo.readFile)(t,"utf-8")}catch(e){if("ENOENT"!==_c(e))throw e}if(void 0===n)return void await(0,xo.writeFile)(t,r);const o=n.indexOf(cT),i=n.indexOf(lT,o+30);if(-1===o||-1===i)await(0,xo.writeFile)(t,r);else{const e=`${n.slice(0,o)}${r}${n.slice(i+30).replace(/^\n/,"")}`;e!==n&&await(0,xo.writeFile)(t,e)}})((0,s.join)((0,o.homedir)(),".cursor")).catch((e=>{KI.warn(this.ctx,"Failed to ensure ~/.cursor/.gitignore",e)}))}async cleanupStaleStagingDirs(e){const t=this.getLogContext(e),r=(0,s.join)(this.projectDir,JI);try{const e=await(0,xo.readdir)(r);await Promise.allSettled(e.filter((e=>e.endsWith(XI))).map((async e=>{await sT(r,e)&&await(0,xo.rm)((0,s.join)(r,e),{recursive:!0,force:!0})})))}catch(e){"ENOENT"!==_c(e)&&KI.error(t,"Error clearing stale mcps staging dirs",e)}}onLeaseChanged(e,t){if(this.disposed)return;const r=t??{serverIdentifiers:void 0};this.hasPendingLeaseChangeEvent?this.pendingLeaseChangeEvent=function(...e){const[t,r]=e;return e.length<2?t:eo(r)?{serverIdentifiers:void 0,reason:t?.reason??r?.reason}:void 0===t?r:eo(t)?{serverIdentifiers:void 0,reason:t.reason??r?.reason}:{serverIdentifiers:[...new Set([...t.serverIdentifiers??[],...r?.serverIdentifiers??[]])],reason:t.reason??r?.reason}}(this.pendingLeaseChangeEvent??{serverIdentifiers:void 0},r):(this.pendingLeaseChangeEvent=r,this.hasPendingLeaseChangeEvent=!0),void 0!==this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout((()=>{this.debounceTimer=void 0;const t=this.takePendingLeaseChangeEvent();this.scheduleWrite(e,t)}),this.debounceMs)}takePendingLeaseChangeEvent(){if(!this.hasPendingLeaseChangeEvent)return;const e=this.pendingLeaseChangeEvent??{serverIdentifiers:void 0};return this.pendingLeaseChangeEvent=void 0,this.hasPendingLeaseChangeEvent=!1,e}scheduleWrite(e,t){const r=this.getLogContext(e);if(this.disposed)return;const n=this.writePromise;this.writePromise=(async()=>{if(n)try{await n}catch(e){KI.error(r,"Error waiting for previous write",e)}this.disposed||(await this.startupCleanupPromise,this.disposed||await this.fetchAndWrite(e,t))})()}getContext(e){let t=(0,b.q6)();return e&&(t=t.with(d._O,e)),t}getLogContext(e){return e.with(d._O,this.ctx.get(d._O))}getMetricTags(e){return{...e,mcp_version:this.mcpVersion}}getMcpAuthToolDescription(){return pT(this.mcpAuthCopyOverrides?.authToolDescription)??aT}shouldExposeVirtualMcpAuthToolForStatus(e,t){return this.exposeVirtualMcpAuthTool&&Jn(e)&&(this.alwaysExposeVirtualMcpAuthTool||"needsAuth"===t)}getErrorStatusMessage(){return pT(this.mcpAuthCopyOverrides?.errorStatusMessage)??"The MCP server errored. If this server is important for completing the task, concisely inform the user and ask them to check the MCP status in Cursor's Customize page > MCPs; otherwise continue with a different approach."}getNeedsAuthStatusMessage(e){return t=pT(this.mcpAuthCopyOverrides?.needsAuthStatusMessageWithAuthTool)??'The MCP server needs authentication. Authenticate it by calling the `{authToolName}` tool for server "{serverIdentifier}" through your MCP tool-calling interface using an empty arguments object. If this server is important for completing the task, authenticate it first; otherwise continue with a different approach.',r={serverIdentifier:e,authToolName:iT},t.replace(/\{serverIdentifier\}/g,r.serverIdentifier).replace(/\{authToolName\}/g,r.authToolName);var t,r}getNeedsAuthStatusMessageForWrite(e){return this.exposeVirtualMcpAuthTool&&Jn(e)?this.getNeedsAuthStatusMessage(e):pT(this.mcpAuthCopyOverrides?.needsAuthStatusMessageWithoutVirtualTool)??"This MCP server requires authentication before its tools can be used. Open Cursor's Customize page > MCPs, select this server, and use Authenticate/Reopen, or refresh credentials in your MCP configuration (for example mcp.json), then restart this environment. If this server is not required for the task, continue without it."}async getToolsForServers(e,t){if(0===t.length)return[];const r=this.getLogContext(e);try{return await this.mcpLease.getToolsForServers(e,t)}catch(n){KI.warn(r,`getToolsForServers() threw, falling back to filtered getTools(): ${Cc(n)}`);const o=await this.mcpLease.getTools(e).catch((e=>(KI.warn(r,`getTools() threw during scoped-tool fallback, defaulting to []: ${e}`),[]))),s=new Set(t);return o.filter((e=>s.has(e.clientKey)))}}async fetchClientDataForServer(e,t,r,n){const o=await dT(r.getState(e),{kind:"error"}).then((r=>("error"!==r.kind||"message"in r||KI.warn(e,`getState() timed out for "${t}", defaulting to error`),r))),s="ready"===o.kind||"requires_authentication"===o.kind,[i,a,c]=await Promise.all([s?dT(r.listResources(e),{resources:[]}):Promise.resolve({resources:[]}),s?dT(r.listPrompts(e),[]):Promise.resolve([]),s&&n?.fetchInstructions?dT(r.getInstructions(e),void 0):Promise.resolve(void 0)]);return{clientKey:t,serverName:r.serverName,plugin:r.plugin,marketplace:r.marketplace,pluginId:r.pluginId,marketplaceId:r.marketplaceId,resources:i.resources.map((e=>({...e,serverIdentifier:t,serverName:r.serverName}))),prompts:a.map((e=>({...e,serverIdentifier:t,serverName:r.serverName}))),instructions:c,status:fT(o)}}buildServerDataMap(e,t,r){const n=new Map;for(const e of t){const t=Fy(e.clientKey);n.set(e.clientKey,{serverIdentifier:e.clientKey,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,sanitizedId:t,folderPath:(0,s.join)(this.projectDir,JI,t),tools:[],resources:e.resources,prompts:e.prompts,instructions:e.instructions,status:e.status})}for(const t of e){let e=n.get(t.clientKey);if(!e){const r=Fy(t.clientKey);e={serverIdentifier:t.clientKey,serverName:t.providerIdentifier,plugin:t.plugin,marketplace:t.marketplace,pluginId:t.pluginId,marketplaceId:t.marketplaceId,sanitizedId:r,folderPath:(0,s.join)(this.projectDir,JI,r),tools:[],resources:[],prompts:[],instructions:void 0,status:void 0},n.set(t.clientKey,e)}e.tools.push(t)}if(void 0!==r)for(const e of r){const t=e.serverIdentifier?.trim();let r=t?Array.from(n.values()).find((e=>e.serverIdentifier===t)):void 0;if(!r){const t=e.serverName?.trim();r=t?Array.from(n.values()).find((e=>e.serverName===t)):void 0}r&&e.instructions&&(r.instructions=e.instructions)}if(this.exposeVirtualMcpAuthTool)for(const e of n.values())this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&(e.tools.some((e=>e.toolName===iT))||e.tools.push({clientKey:(o={serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,authToolDescription:this.getMcpAuthToolDescription()}).serverIdentifier,providerIdentifier:o.serverName,plugin:o.plugin,marketplace:o.marketplace,pluginId:o.pluginId,marketplaceId:o.marketplaceId,toolName:iT,name:iT,description:o.authToolDescription,inputSchema:{type:"object",properties:{},additionalProperties:!1}}));var o;return n}buildServersToWrite(e,t){const r=[],n=new Set;for(const o of t.values()){const t=o.tools.length>0||o.resources.length>0||o.prompts.length>0||o.instructions,s="error"===o.status||"needsAuth"===o.status||"initializing"===o.status;t||s?n.has(o.sanitizedId)?KI.warn(e,`Skipping server "${o.serverIdentifier}" — sanitizedId "${o.sanitizedId}" collides with another server`):(n.add(o.sanitizedId),r.push(o)):KI.info(e,`Server "${o.serverIdentifier}" excluded from write: tools=${o.tools.length}, resources=${o.resources.length}, prompts=${o.prompts.length}, hasInstructions=${!!o.instructions}, status=${o.status}`)}return r}mergeScopedRefreshWithCachedServerData(e,t){const r=[...t.tools];if(this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&!r.some((e=>e.toolName===iT))){const t=e.tools.find((e=>e.toolName===iT));void 0!==t&&r.push(t)}return{...e,...t,tools:r,resources:e.resources,prompts:e.prompts,instructions:e.instructions,status:e.status,plugin:t.plugin??e.plugin,marketplace:t.marketplace??e.marketplace,pluginId:t.pluginId??e.pluginId,marketplaceId:t.marketplaceId??e.marketplaceId}}async refreshServersFromLease(e,t){const r=this.getLogContext(e),n=[...new Set(t.serverIdentifiers??[])];KI.info(r,`fetchAndWrite: refreshing ${n.length} targeted servers`,{serverIdentifiers:n});const o=await this.getToolsForServers(e,n),s=await this.mcpLease.getInstructions(e).catch((e=>(KI.warn(r,`getInstructions() threw during scoped refresh, defaulting to []: ${e}`),[]))),i=await Promise.all(n.map((async t=>{try{const r=await this.mcpLease.getClient(e,t);return void 0===r?{serverIdentifier:t,kind:"missing"}:{serverIdentifier:t,kind:"client",client:r}}catch(e){return KI.warn(r,`getClient("${t}") threw during scoped refresh, preserving cached data: ${Cc(e)}`),{serverIdentifier:t,kind:"error",error:e}}}))),a=i.filter((e=>"missing"===e.kind)).map((e=>e.serverIdentifier));let c=new Set;if(a.length>0){const t=await this.mcpLease.getClients(e).catch((e=>{KI.warn(r,`getClients() threw while confirming targeted server removal, preserving cached data: ${e}`)}));void 0!==t&&(c=new Set(a.filter((e=>void 0===t[e]))))}const l=await Promise.all(i.filter((e=>"client"===e.kind)).map((({serverIdentifier:t,client:r})=>this.fetchClientDataForServer(e,t,r,{fetchInstructions:!0})))),u=new Map((this.cachedServerData??[]).map((e=>[e.serverIdentifier,e]))),d=this.buildServerDataMap(o,l,s),h=new Set(n),p=new Set(i.filter((e=>"error"===e.kind||"missing"===e.kind&&!c.has(e.serverIdentifier))).map((e=>e.serverIdentifier)));for(const e of n){const t=u.get(e),n=d.get(e);if(void 0===n)c.has(e)?u.delete(e):KI.warn(r,`refreshServersFromLease: preserving cached data for "${e}" because targeted refresh returned no replacement`);else{if(p.has(e)&&void 0!==t){u.set(e,this.mergeScopedRefreshWithCachedServerData(t,n)),KI.warn(r,`refreshServersFromLease: preserving cached metadata for "${e}" because the client was unavailable during targeted refresh`);continue}u.set(e,n)}}const f=new Map(Array.from(u.values()).map((e=>[e.sanitizedId,e.serverIdentifier])));for(const[e,t]of this.cachedFingerprints)if(!h.has(e)&&!u.has(e)){const t=Fy(e);f.set(t,e)}const m=this.buildServersToWrite(e,u);await this.writeServerData(e,m,f),this.cachedServerData=m,this.fireOnDidWrite(m)}async fetchAndWrite(e,t){const r={stack:[],error:void 0,hasError:!1};try{NI(r,(0,D.VI)(e.withName("McpFileSystemWriter.fetchAndWrite")),!1);const n=this.getLogContext(e);try{if(void 0!==this.cachedServerData&&void 0!==t&&!eo(t)&&[...new Set(t.serverIdentifiers??[])].length>0)return void await this.refreshServersFromLease(e,t);const[r,o,s]=await Promise.all([this.mcpLease.getTools(e).catch((e=>(KI.warn(n,`getTools() threw, defaulting to []: ${e}`),[]))),this.mcpLease.getInstructions(e).catch((()=>[])),this.mcpLease.getClients(e).catch((e=>(KI.warn(n,`getClients() threw, defaulting to {}: ${e}`),{})))]),i=Object.keys(s);KI.info(n,`fetchAndWrite: lease returned ${r.length} tools across ${i.length} clients`);const a=Object.entries(s).map((([t,r])=>this.fetchClientDataForServer(e,t,r))),c=await Promise.all(a),l=this.buildServerDataMap(r,c,o),u=this.buildServersToWrite(e,l),d=new Map(Array.from(l.values()).map((e=>[e.sanitizedId,e.serverIdentifier])));await this.writeServerData(e,u,d),this.cachedServerData=u,this.fireOnDidWrite(u)}catch(e){KI.error(n,"Error fetching/writing MCP state",e)}}catch(e){r.error=e,r.hasError=!0}finally{LI(r)}}fireOnDidWrite(e){if(this.onDidWrite)try{const t=e.map((e=>({serverIdentifier:e.serverIdentifier,folderPath:e.folderPath,tools:e.tools.map((t=>({toolName:t.toolName,definitionPath:(0,s.join)(e.folderPath,ZI,`${hT(t.toolName)}.json`)})))})));this.onDidWrite(t)}catch{}}async writeServerData(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{NI(n,(0,D.VI)(e.withName("McpFileSystemWriter.writeServerData")),!1);const o=this.getLogContext(e),i=(0,s.join)(this.projectDir,JI);await(0,xo.mkdir)(i,{recursive:!0});const a=new Map;for(const e of t)try{a.set(e.serverIdentifier,yT(e))}catch(t){KI.error(o,"Error computing server fingerprint, will force write",t,{serverIdentifier:e.serverIdentifier}),a.set(e.serverIdentifier,`__error_${Date.now()}_${Math.random()}`)}const c=[];for(const e of t){const t=this.cachedFingerprints.get(e.serverIdentifier);t!==a.get(e.serverIdentifier)&&(c.push(e),void 0!==t&&KI.info(o,`Server "${e.serverIdentifier}" fingerprint changed: tools=${e.tools.length}, status=${e.status}`))}for(const e of t)if(!c.includes(e))try{await(0,xo.stat)((0,s.join)(i,e.sanitizedId))}catch{KI.info(o,`Server "${e.serverIdentifier}" directory missing on disk, forcing write`),c.push(e)}const l=new Set;for(const[e]of this.cachedFingerprints)if(!a.has(e)){const t=this.cachedServerData?.find((t=>t.serverIdentifier===e)),n=t?.sanitizedId??Fy(e);r.has(n)?(KI.info(o,`Server "${e}" (sanitized="${n}") still in lease but excluded from write, preserving directory`),a.set(e,this.cachedFingerprints.get(e))):(KI.info(o,`Server "${e}" (sanitized="${n}") left the lease, scheduling directory removal`),l.add(n))}const u=void 0===this.cachedServerData;if(u)try{const e=await(0,xo.readdir)(i),t=new Set(e.filter((e=>!e.endsWith(XI)&&!e.endsWith(QI))));for(const r of e){const e=r.endsWith(XI),n=r.endsWith(QI);if((e||n)&&await sT(i,r))if(e)await(0,xo.rm)((0,s.join)(i,r),{recursive:!0,force:!0});else{const e=rT(r);if(t.has(e))await(0,xo.rm)((0,s.join)(i,r),{recursive:!0,force:!0});else try{await(0,xo.rename)((0,s.join)(i,r),(0,s.join)(i,e)),t.add(e)}catch{await(0,xo.rm)((0,s.join)(i,r),{recursive:!0,force:!0}).catch((()=>{}))}}}for(const e of t)if(r.has(e)){const t=r.get(e);a.has(t)||a.set(t,`__preserved_${e}`)}else l.add(e)}catch(e){KI.error(o,"Error clearing mcps directory",e)}const d=Array.from(l);if(c.length>0||l.size>0){const e=c.map((e=>({serverIdentifier:e.serverIdentifier,sanitizedId:e.sanitizedId,toolCount:e.tools.length})));KI.info(o,`Incremental write: ${c.length} changed, ${l.size} removed, ${t.length-c.length} unchanged`,{changedServerCount:c.length,changedServers:e,removedServerCount:l.size,removedServerSanitizedIds:d,unchangedServerCount:t.length-c.length,totalServerCount:t.length,leaseServerCount:r.size,coldStartReconcile:u,projectDirHash:(0,ko.createHash)("sha256").update(this.projectDir).digest("hex")},{includeStructuredLogs:!0})}const h=await Promise.allSettled(c.map((t=>this.writeServerAtomic(e,t,i))));for(let t=0;t(0,xo.rm)((0,s.join)(i,e),{recursive:!0,force:!0}))));for(let r=0;r{await(i?.catch((()=>{}))),await this.swapServerDirectory(e,t,r)})();tT.set(o,a);try{await a}finally{tT.get(o)===a&&tT.delete(o)}}catch(e){n.error=e,n.hasError=!0}finally{LI(n)}}async swapServerDirectory(e,t,r){const n=nT(t.sanitizedId,XI),o=(0,s.join)(r,n),i=(0,s.join)(r,t.sanitizedId);try{await this.writeServerDirectory(e,t,{basePath:r,dirName:n})}catch(e){throw await(0,xo.rm)(o,{recursive:!0,force:!0}).catch((()=>{})),e}const a=(0,s.join)(r,nT(t.sanitizedId,QI));let c=!1;try{try{await this.renameWithRetry(i,a),c=!0}catch(e){if("ENOENT"!==_c(e))throw e}await this.renameWithRetry(o,i)}catch(r){if(KI.error(e,"Per-server swap failed",r,{serverIdentifier:t.serverIdentifier,sanitizedId:t.sanitizedId},{includeStructuredLogs:!0}),c)try{await this.renameWithRetry(a,i)}catch{await(0,xo.stat)(i).then((()=>!0),(()=>!1))&&await(0,xo.rm)(a,{recursive:!0,force:!0}).catch((()=>{}))}throw await(0,xo.rm)(o,{recursive:!0,force:!0}).catch((()=>{})),r}await(0,xo.rm)(a,{recursive:!0,force:!0}).catch((()=>{}))}async renameWithRetry(e,t){for(let r=0;;r++)try{return void await(0,xo.rename)(e,t)}catch(e){const t=_c(e);if(r>=YI.length||void 0===t||!eT.has(t))throw e;await(0,Nr.cb)(YI[r])}}async writeServerDirectory(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{NI(n,(0,D.VI)(e.withName("McpFileSystemWriter.writeServerDirectory")),!1);const o=(0,s.join)(r.basePath,r.dirName??t.sanitizedId);await(0,xo.mkdir)(o,{recursive:!0});const i=[];if(t.tools.length>0){const e=(0,s.join)(o,ZI);await(0,xo.mkdir)(e,{recursive:!0});for(const r of t.tools){const t=hT(r.toolName);i.push({path:(0,s.join)(e,`${t}.json`),content:JSON.stringify(Qn(r),null,2)})}}if(t.resources.length>0){const e=(0,s.join)(o,"resources");await(0,xo.mkdir)(e,{recursive:!0});for(const r of t.resources){const t=hT(r.name||r.uri.replace(/[^a-zA-Z0-9_-]/g,"_")),n={uri:r.uri,name:r.name,description:r.description,mimeType:r.mimeType};i.push({path:(0,s.join)(e,`${t}.json`),content:JSON.stringify(n,null,2)})}}if(t.prompts.length>0){const e=(0,s.join)(o,"prompts");await(0,xo.mkdir)(e,{recursive:!0});for(const r of t.prompts){const t=hT(r.name),n={name:r.name,description:r.description,arguments:r.arguments};i.push({path:(0,s.join)(e,`${t}.json`),content:JSON.stringify(n,null,2)})}}t.instructions&&t.instructions.trim().length>0&&i.push({path:(0,s.join)(o,"INSTRUCTIONS.md"),content:t.instructions.trim()}),"error"!==t.status&&"needsAuth"!==t.status||i.push({path:(0,s.join)(o,"STATUS.md"),content:"error"===t.status?this.getErrorStatusMessage():this.getNeedsAuthStatusMessageForWrite(t.serverIdentifier)});const a={serverIdentifier:t.serverIdentifier,serverName:t.serverName};i.push({path:(0,s.join)(o,"SERVER_METADATA.json"),content:JSON.stringify(a,null,2)});if(new Set(i.map((e=>e.path.toLowerCase()))).size!==i.length){for(const e of i)await(0,xo.writeFile)(e.path,e.content);return}const c=(await(0,Nr.up)(i,(e=>(0,xo.writeFile)(e.path,e.content)),{max:8})).find((e=>"rejected"===e.status));if(c)throw c.reason}catch(e){n.error=e,n.hasError=!0}finally{LI(n)}}async getMcpFileSystemOptions(e,t){const r={stack:[],error:void 0,hasError:!1};try{if(this.disposed)return;NI(r,(0,D.VI)(e.withName("McpFileSystemWriter.getMcpFileSystemOptions")),!1);const n=this.getLogContext(e),o=await this.ensureWritesSettled(e,t?.timeoutMs);if(this.snapshotProvider&&!o)return this.buildOptionsFromSnapshots(e);this.snapshotProvider&&o&&KI.warn(n,"Snapshot mode write barrier timed out; falling back to cached descriptors",{timeoutMs:t?.timeoutMs},{includeStructuredLogs:!0});const i=(this.cachedServerData??[]).map((e=>{const t=e.tools.map((t=>{const r=hT(t.toolName),n=(0,s.join)(e.folderPath,ZI,`${r}.json`);return new vn.E$({toolName:t.toolName,definitionPath:n,...Nb(t.annotations)})}));return new vn.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,folderPath:e.folderPath,serverUseInstructions:e.instructions,tools:t})}));return this.checkDescriptorsVsFilesystem(e,i,"workbench_lease"),new vn.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:i})}catch(e){r.error=e,r.hasError=!0}finally{LI(r)}}async ensureWritesSettled(e,t){const r=this.getLogContext(e),n=void 0!==this.debounceTimer;if(void 0!==this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0,this.scheduleWrite(e,this.takePendingLeaseChangeEvent())),n&&KI.info(r,"getMcpFileSystemOptions force-fired pending debounce"),!this.writePromise)return!1;if(void 0!==t){let e,n=!1;try{await Promise.race([this.writePromise,new Promise((r=>{e=setTimeout((()=>{n=!0,r()}),t)}))])}catch(e){KI.error(r,"Error waiting for pending write to complete",e)}finally{clearTimeout(e)}return n&&KI.warn(r,`getMcpFileSystemOptions timed out after ${t}ms waiting for write; returning stale cache`),n}try{await this.writePromise}catch(e){KI.error(r,"Error waiting for pending write to complete",e)}return!1}async buildOptionsFromSnapshots(e){const t={stack:[],error:void 0,hasError:!1};try{NI(t,(0,D.VI)(e.withName("McpFileSystemWriter.buildOptionsFromSnapshots")),!1);const r=this.getLogContext(e),n=Date.now(),o=await this.snapshotProvider.getAllSnapshots(e),i=(0,s.join)(this.projectDir,JI),a=o.filter((e=>e.tools.length>0||e.resources.length>0||e.prompts.length>0||void 0!==e.instructions||this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)||"needsAuth"===e.status||"error"===e.status)).map((e=>{const t=Fy(e.serverIdentifier),r=(0,s.join)(i,t),n=e.tools.map((e=>{const t=hT(e.name);return new vn.E$({toolName:e.name,definitionPath:(0,s.join)(r,ZI,`${t}.json`),...Nb(e.annotations)})}));if(this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&!e.tools.some((e=>e.name===iT))){const e=hT(iT);n.push(new vn.E$({toolName:iT,definitionPath:(0,s.join)(r,ZI,`${e}.json`)}))}return new vn.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,folderPath:r,serverUseInstructions:e.instructions,tools:n})})),c=a.reduce(((e,t)=>e+t.tools.length),0);return KI.info(r,`buildOptionsFromSnapshots completed in ${Date.now()-n}ms: ${o.length} snapshots, ${a.length} descriptors, ${c} tools`),this.checkDescriptorsVsFilesystem(e,a,"snapshot"),new vn.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:a})}catch(e){t.error=e,t.hasError=!0}finally{LI(t)}}async waitForPendingWrites(){if(void 0!==this.debounceTimer&&await new Promise((e=>{const t=()=>{void 0===this.debounceTimer?e():setTimeout(t,10)};t()})),this.writePromise)try{await this.writePromise}catch{}}getCachedServerData(){return this.cachedServerData}checkDescriptorsVsFilesystem(e,t,r){const n=this.getLogContext(e),o=Date.now();o-this.lastDivergenceCheckMs{KI.warn(n,"Divergence check failed",e)})))}async _checkDescriptorsVsFilesystemAsync(e,t,r){const n=this.getLogContext(e),o=(0,s.join)(this.projectDir,JI),i=new Set,a=new Map;for(const e of t){const t=Fy(e.serverIdentifier);i.add(t),a.set(t,e.tools.length)}let c=[];try{c=await(0,xo.readdir)(o),c=c.filter((e=>!e.endsWith(XI)&&!e.endsWith(QI)))}catch(e){if("ENOENT"!==_c(e))throw e}const l=new Set(c);let u=!0,d=0,h=0,p=0;const f=function(e){return 0===e?"0":e<=3?"1-3":e<=6?"4-6":e<=10?"7-10":"11+"}(i.size);for(const t of i)l.has(t)||(u=!1,d++,jI.increment(e,1,this.getMetricTags({divergence_type:"server_missing",mcp_source:r,configured_servers:f})),KI.warn(n,"Divergence detected: server missing from filesystem",{mcpFileSystemMeta:{divergenceType:"server_missing",serverId:t,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}));for(const t of l)i.has(t)||(u=!1,h++,jI.increment(e,1,this.getMetricTags({divergence_type:"server_stale",mcp_source:r,configured_servers:f})));for(const t of i){if(!l.has(t))continue;const c=a.get(t)??0,d=(0,s.join)(o,t,ZI);let h=0;try{h=(await(0,xo.readdir)(d)).filter((e=>e.endsWith(".json"))).length}catch{}h!==c&&(u=!1,p++,jI.increment(e,1,this.getMetricTags({divergence_type:"tool_count_mismatch",mcp_source:r,configured_servers:f})),KI.warn(n,"Divergence detected: tool count mismatch",{mcpFileSystemMeta:{divergenceType:"tool_count_mismatch",serverId:t,expected:c,actual:h,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}))}UI.increment(e,1,this.getMetricTags({synced:String(u),mcp_source:r,configured_servers:f})),BI.gauge(e,i.size,this.getMetricTags({mcp_source:r})),WI.gauge(e,l.size,this.getMetricTags({mcp_source:r})),HI.gauge(e,d,this.getMetricTags({mcp_source:r})),qI.gauge(e,p,this.getMetricTags({mcp_source:r})),KI.info(n,"MCP filesystem sync check",{mcpFileSystemMeta:{synced:u,expectedServers:i.size,actualServers:l.size,serversMissing:d,serversStale:h,toolMismatches:p,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}),u||KI.warn(n,"MCP filesystem divergence summary",{mcpFileSystemMeta:{synced:u,expectedServers:i.size,actualServers:l.size,serversMissing:d,serversStale:h,toolMismatches:p,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0})}dispose(){this.disposed||(this.disposed=!0,void 0!==this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.leaseChangeDisposable&&(this.leaseChangeDisposable.dispose(),this.leaseChangeDisposable=void 0),this.cachedServerData=void 0,this.cachedFingerprints.clear())}}vT.DIVERGENCE_CHECK_COOLDOWN_MS=1e4;var bT=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},ST=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function kT(e){if("object"!=typeof e||null===e||Array.isArray(e))return;const t={};for(const[r,n]of Object.entries(e))"string"==typeof n&&(t[r]=n);return t}const _T=(0,d.h)("local-exec:mcp");function CT(e,t){const r=s.relative(e,t);return""===r||!s.isAbsolute(r)&&".."!==r&&!r.startsWith(`..${s.sep}`)}function ET(e){return e instanceof Error&&"code"in e&&"string"==typeof e.code?e.code:void 0}function xT(e){return new Mc._Z({content:{case:"image",value:new Mc.do({data:e.data,mimeType:e.mimeType})}})}function PT(e){return new Mc._Z({content:{case:"text",value:new Mc.zN({text:e})}})}async function RT(e,t,r){const n=await r.permissionsService.shouldBlockMcp(e,t,r.toolDef,{alreadyApproved:t.skipApproval,...void 0===r.client?{}:{client:r.client},...void 0===r.resolvedTool?{}:{resolvedTool:r.resolvedTool}});if(!n)return;const o=await ed(n,{onNeedsApproval:async(e,n)=>{if("mcp"!==n.type)return new Mc.iz({result:{case:"error",value:new Mc.Nh({error:"Invalid approval details type for MCP execution"})}});const o=await r.pendingDecisionProvider.requestApproval({type:Bw.Mcp,details:{name:n.name,toolName:n.toolName,toolTitle:n.toolTitle,destructiveHint:n.destructiveHint,providerIdentifier:n.providerIdentifier,source:r.toolDef?.source,args:n.args,reason:n.reason??e,canAllowlist:n.canAllowlist,smartModeApprovalReason:n.smartModeApprovalReason,smartModeApprovalRequestId:n.smartModeApprovalRequestId,allowlistEntry:n.allowlistEntry,computerUseApp:n.computerUseApp},toolCallId:t.toolCallId});return o.approved&&void 0!==n.computerUseApp&&!0!==n.computerUseApp.allowOnce&&r.permissionsService.allowComputerUseAppForSession?.({bundleId:n.computerUseApp.bundleId}),o.approved?t.smartModeApprovalOnly?new Mc.iz({result:{case:"approved",value:new Mc.Ke}}):null:new Mc.iz({result:{case:"rejected",value:new Mc.xo({reason:`User rejected MCP: ${t.name}${o.reason?` - ${o.reason}`:""}`})}})},onUserRejected:e=>new Mc.iz({result:{case:"error",value:new Mc.Nh({error:`User rejected MCP: ${t.name}${e?` - ${e}`:""}`})}}),onPermissionDenied:(e,r)=>IT({name:t.name,reason:e,isReadonly:r?.isReadonly??!1})});return o??void 0}function IT({name:e,reason:t,isReadonly:r}){return new Mc.iz({result:{case:"permissionDenied",value:new Mc.HQ({error:`MCP tool execution blocked: ${e} - ${t}`,isReadonly:r})}})}class TT{constructor(e,t,r,n,o=4e4,s,i,a={}){this.toolSet=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.projectDir=n,this.fileOutputThresholdBytes=o,this.elicitationFactory=s,this.ensureMcpServersLoaded=i,this.spillOptions=a}async describeDisconnectedServer(e,t){const r=new Set(t.filter((e=>""!==e)));if(0===r.size)return;let n;try{n=await this.toolSet.getClients(e)}catch{return}const o=Object.entries(n).find((([e,t])=>r.has(e)||r.has(t.serverName)));if(void 0===o)return;const[s,i]=o;let a;try{a=await i.getState(e)}catch{return}if("ready"===a.kind&&void 0===a.toolListError)return;const c=function(e){switch(e){case"needsAuth":return"This MCP server requires authentication before its tools can be used.";case"error":return"This MCP server failed during live tool discovery. Its tools are unavailable until the connection is fixed.";case"loading":return"This MCP server is still loading; tools may not be available yet.";default:return}}(to(a));return void 0!==c?`MCP server "${s}" has no callable tools right now. ${c}${"error"===a.kind&&a.message?` (${a.message})`:""}`:void 0}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=bT(r,(0,D.VI)(e.withName("LocalMcpToolExecutor.execute")),!1).ctx,i=t.serverIdentifier||t.providerIdentifier;await(this.ensureMcpServersLoaded?.(o,[i]));const a=await this.toolSet.getTools(o),c=Array.from(new Set(a.map((e=>e.clientKey)))).sort(),l=a.find((e=>e.clientKey===i&&e.toolName===t.toolName)),u=a.find((e=>e.name===t.name));if(void 0!==u&&(void 0!==l?u!==l:u.toolName!==t.toolName||u.clientKey!==i&&u.providerIdentifier!==i))return new Mc.iz({result:{case:"error",value:new Mc.Nh({error:`MCP tool "${t.name}" is not the tool "${t.toolName}" on server "${i}" that the call names.`})}});const d=void 0===l?void 0:await this.toolSet.getClient(o,l.clientKey).catch((()=>{})),h=l??u,p=void 0===h?void 0:h===l?d:await this.toolSet.getClient(o,h.clientKey).catch((()=>{})),f=await RT(o,t,{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionProvider,toolDef:l,...void 0===d?{}:{client:d},...void 0===h?{}:{resolvedTool:void 0===p?"unresolved":{client:p,annotations:h.annotations}}});if(void 0!==f)return f;const m=await this.toolSet.getToolSet(o),g=!0===await(this.permissionsService.enforcesMcpAdminToolLimits?.());let w;try{if(g&&void 0===h)throw new kC(t.name,a.map((e=>e.name)));const e=l?.name??t.name,r=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()])));if(g){const n=void 0===p?void 0:await(m.executeOn?.(p,e,r,t.toolCallId,this.elicitationFactory));if(void 0===n)return _T.warn(o,"Refusing an MCP tool whose client was not judged",{toolName:t.toolName,toolSetNamesClients:void 0!==m.executeOn}),IT({name:t.name,reason:ik,isReadonly:!1});w=n}else w=await m.execute(e,r,t.toolCallId,this.elicitationFactory)}catch(e){let r=e;if(_C(r)&&t.providerIdentifier.length>0&&!a.some((e=>e.clientKey===t.providerIdentifier||e.providerIdentifier===t.providerIdentifier))&&(r=new rI(t.providerIdentifier,c)),r instanceof rI){const e=await this.describeDisconnectedServer(o,[i,t.providerIdentifier]);return void 0!==e?new Mc.iz({result:{case:"error",value:new Mc.Nh({error:e})}}):new Mc.iz({result:{case:"serverNotFound",value:new Mc.JL({name:r.serverName,availableServers:r.availableServers})}})}if(_C(r))return new Mc.iz({result:{case:"toolNotFound",value:new Mc.WV({name:r.toolName,availableTools:r.availableTools})}});throw r}const y=[];for(const e of w.content){const r=e.type;if("text"===r&&"object"==typeof e&&null!==e&&"text"in e&&"string"==typeof e.text)y.push(PT(e.text));else if("resource"===r){const r=aE(e),n=void 0===r?void 0:Buffer.from(r,"base64"),s=void 0===n?void 0:await Bv(n).then(xT,(e=>{_T.warn(o,"Describing an undecodable MCP resource image",{toolName:t.toolName,bytes:n.byteLength,error:e instanceof Error?e.message:String(e)})}));y.push(s??PT(cE(e)))}else if("image"===r){const r=e,s="string"==typeof r.data?Buffer.from(r.data,"base64"):Buffer.alloc(0);let i;try{i=await Bv(s)}catch(e){_T.warn(o,"Omitting undecodable MCP tool image",{toolName:t.toolName,mimeType:"string"==typeof r.mimeType?r.mimeType.slice(0,100):typeof r.mimeType,bytes:s.byteLength,error:e instanceof Error?e.message:String(e)}),y.push(PT(`[Image omitted: the tool returned ${n=r.mimeType,"string"==typeof n&&/^image\/[\w.+-]{1,40}$/.test(n)?n:"image"} data (${s.byteLength} bytes) that could not be decoded.]`));continue}y.push(xT(i))}else if("image"!==r){const t=cE(e);y.push(PT(t))}}const v=await async function({contentItems:e,thresholdBytes:t,write:r}){const n=e.filter((e=>"text"===e.content.case&&void 0===e.content.value.outputLocation)).map((e=>"text"===e.content.case?e.content.value.text:"")).join("\n\n");if(t<=0||Buffer.byteLength(n,"utf8")<=t)return e;const o=await r(n);if(void 0===o)return;const s=[];let i=!1;for(const t of e)"text"===t.content.case&&void 0===t.content.value.outputLocation?i||(s.push(new Mc._Z({content:{case:"text",value:new Mc.zN({text:"",outputLocation:o})}})),i=!0):s.push(t);return s}({contentItems:y,thresholdBytes:this.fileOutputThresholdBytes,write:e=>async function(e,t,r){const n=s.join(t,Dc),o=s.join(n,`${(0,ko.randomUUID)()}.txt`);await(0,xo.mkdir)(s.dirname(o),{recursive:!0});const i=Jo(!0===r.blankSharedPaymentTokens?tx(e):e,Oc),a=Xs(i),c=Buffer.byteLength(i,"utf8");return await(0,xo.writeFile)(o,i,"utf8"),new Fc.pV({filePath:o,sizeBytes:BigInt(c),lineCount:BigInt(a)})}(e,this.projectDir,this.spillOptions)});if(void 0===v)throw new Error("Failed to materialize MCP text output");const b=w.structuredContent&&"object"==typeof w.structuredContent&&!Array.isArray(w.structuredContent)?ve.Struct.fromJson(w.structuredContent):void 0,S=new Mc.QW({content:v,isError:w.isError,structuredContent:b,resultMeta:void 0===w._meta?void 0:ve.Struct.fromJson(w._meta)});return new Mc.iz({result:{case:"success",value:S}})}catch(e){r.error=e,r.hasError=!0}finally{ST(r)}var n}}class AT{constructor(e,t){this.mcpLease=e,this.ensureMcpServersLoaded=t}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=bT(r,(0,D.VI)(e.withName("LocalListMcpResourcesExecutor.execute")),!1).ctx;try{if(t.server){await(this.ensureMcpServersLoaded?.(n,[t.server]));const e=await this.mcpLease.getClients(n),r=e[t.server]??Object.values(e).find((e=>e.serverName===t.server));if(!r)return new Mc.kP({result:{case:"error",value:new Mc.w2({error:`Server "${t.server}" not found`})}});const o=await this.listResourcesFromClient(n,r,t.server,!0);return new Mc.kP({result:{case:"success",value:new Mc.T2({resources:o})}})}const e=await this.mcpLease.getClients(n),r=new Set,o=await this.mcpLease.getTools(n);for(const e of o)r.add(e.providerIdentifier),r.add(`user-${e.providerIdentifier}`);const s=[];for(const[t,o]of Object.entries(e)){if(r.size>0&&!r.has(t))continue;const e=await this.listResourcesFromClient(n,o,t);s.push(...e)}return new Mc.kP({result:{case:"success",value:new Mc.T2({resources:s})}})}catch(e){const t=e instanceof Error?e.message:String(e);return new Mc.kP({result:{case:"error",value:new Mc.w2({error:`Failed to list MCP resources: ${t}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{ST(r)}}async listResourcesFromClient(e,t,r,n=!1){const o=await t.getState(e);if("ready"!==o.kind&&(!n||"loading"!==o.kind))return[];const s=await t.listResources(e);return s&&s.resources?s.resources.map((e=>new Mc.X2({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType,server:r,annotations:kT(e.annotations)}))):[]}}class $T{constructor(e,t=".",r,n=[],o,s,i){this.mcpLease=e,this.projectDir=t,this.pendingDecisionProvider=o,this.ensureMcpServersLoaded=s,this.writeExecutor=i,this.workspacePaths=n.filter((e=>e.length>0))}resolveProjectDir(e){const t=e.get(OI),r=t?.find((e=>"string"==typeof e&&e.length>0));return r||(this.workspacePaths.length>0?this.workspacePaths[0]:this.projectDir)}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=bT(r,(0,D.VI)(e.withName("LocalReadMcpResourceExecutor.execute")),!1).ctx,o=t.smartModeApproval?.reason;if(void 0!==o){if(void 0===this.pendingDecisionProvider)return new Mc.ZD({result:{case:"error",value:new Mc.Jx({uri:t.uri,error:"Auto-review approval provider is not configured"})}});const e=await this.pendingDecisionProvider.requestApproval({type:Bw.Mcp,details:{name:"FetchMcpResource",toolName:"FetchMcpResource",providerIdentifier:t.server,args:{server:ve.Value.fromJson(t.server),uri:ve.Value.fromJson(t.uri),...void 0!==t.downloadPath?{downloadPath:ve.Value.fromJson(t.downloadPath)}:{}},reason:"smartMode",canAllowlist:!1,smartModeApprovalReason:o,smartModeApprovalRequestId:t.smartModeApproval?.requestId},toolCallId:t.toolCallId});if(!e.approved)return new Mc.ZD({result:{case:"rejected",value:new Mc.Dh({reason:"User rejected MCP resource fetch"+(e.reason?` - ${e.reason}`:"")})}})}await(this.ensureMcpServersLoaded?.(n,[t.server]));const i=await this.mcpLease.getClients(n),a=i[t.server]??Object.values(i).find((e=>e.serverName===t.server));if(!a)return new Mc.ZD({result:{case:"error",value:new Mc.Jx({uri:t.uri,error:`Server "${t.server}" not found`})}});try{if("ready"!==(await a.getState(n)).kind)return new Mc.ZD({result:{case:"error",value:new Mc.Jx({uri:t.uri,error:`Server "${t.server}" is not ready`})}});const e=await a.readResource(n,{uri:t.uri});if(!e||!e.contents||0===e.contents.length)return new Mc.ZD({result:{case:"notFound",value:new Mc.ov({uri:t.uri})}});const r=e.contents[0];if(t.downloadPath){const e=await async function(e,t){const r=s.resolve(e),n=await(0,xo.realpath)(r),o=s.isAbsolute(t)?s.resolve(t):s.resolve(r,t),i=CT(r,o),a=s.isAbsolute(t)&&CT(n,o);if(!i&&!a)throw new Error("downloadPath must stay within the workspace");let c=s.dirname(o);for(;;)try{if(!CT(n,await(0,xo.realpath)(c)))throw new Error("downloadPath must stay within the workspace");break}catch(e){if("ENOENT"!==ET(e))throw e;const t=s.dirname(c);if(t===c)throw e;c=t}try{if((await(0,xo.lstat)(o)).isSymbolicLink())throw new Error("downloadPath must stay within the workspace")}catch(e){if("ENOENT"!==ET(e))throw e}return o}(this.resolveProjectDir(n),t.downloadPath);let o=e;if(r.text||r.blob){if(void 0===this.writeExecutor)throw new Error("File-write executor is not configured");const s=await this.writeExecutor.execute(n,new FI.hY({path:e,fileText:r.text??"",fileBytes:r.text||void 0===r.blob?new Uint8Array:new Uint8Array(Buffer.from(r.blob,"base64")),toolCallId:t.toolCallId,confineToWorkspace:!0}));if("rejected"===s.result.case)return new Mc.ZD({result:{case:"rejected",value:new Mc.Dh({uri:t.uri,reason:s.result.value.reason})}});if("success"!==s.result.case)return new Mc.ZD({result:{case:"error",value:new Mc.Jx({uri:t.uri,error:MT(s)})}});o=s.result.value.path}return new Mc.ZD({result:{case:"success",value:new Mc.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,downloadPath:o})}})}if(r.text)return new Mc.ZD({result:{case:"success",value:new Mc.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:kT(r.annotations),metaJson:Xn(r._meta),content:{case:"text",value:r.text}})}});if(r.blob){const e=Buffer.from(r.blob,"base64");return new Mc.ZD({result:{case:"success",value:new Mc.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:kT(r.annotations),metaJson:Xn(r._meta),content:{case:"blob",value:e}})}})}return new Mc.ZD({result:{case:"error",value:new Mc.Jx({uri:t.uri,error:"Failed to read resource"})}})}catch(e){const r=e instanceof Error?e.message:String(e);return _T.warn(n,"LocalReadMcpResourceExecutor.execute failed",{server:t.server,hasDownloadPath:Boolean(t.downloadPath),errorName:e instanceof Error?e.name:typeof e,errorMessage:r}),new Mc.ZD({result:{case:"error",value:new Mc.Jx({uri:t.uri,error:`Failed to read MCP resource: ${r}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{ST(r)}}}function MT(e){switch(e.result.case){case"error":return e.result.value.error;case"permissionDenied":return e.result.value.error||"Permission denied";case"noSpace":return"No space left on device";case"rejected":return e.result.value.reason||"Write rejected";case"success":return"";case void 0:return"Write executor returned result without case";default:{const t=e.result;return String(t)}}}var DT=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const OT=1e4,FT=5e3,NT={PAGER:"cat",MANPAGER:"cat",LESS:"-R",PIP_PROGRESS_BAR:"off",TQDM_DISABLE:"1"};class LT{constructor(){this.fullOutput="",this.outputHead="",this.outputTail="",this.totalChars=0}append(e){if(0===e.length)return;const t=this.totalChars;if(this.totalChars+=e.length,tOT&&(this.fullOutput="")}getOutput(){return this.totalChars<=OT?this.fullOutput:void 0}getTruncation(){if(!(this.totalChars<=OT))return{outputHead:this.outputHead,outputTail:this.outputTail,elidedChars:this.totalChars-this.outputHead.length-this.outputTail.length}}}class jT{constructor(){this.kept="",this.full=!1}append(e){if(this.full)return;const t=os-this.kept.length;this.full=e.length>=t,this.kept+=Jo(e,t)}get text(){return this.kept}}function UT(e,t){return null!==e?e:null===t?-1:-o.constants.signals[t]}class BT{constructor(e,t,r){this.permissionsService=e,this.ignoreService=t,this.defaultCwd=r}buildResult({args:e,workingDirectory:t,processResult:r,sandboxPolicy:n}){const o={command:e.command,workingDirectory:t,exitCode:r.returncode,signal:r.signal,stdout:r.stdout,stderr:r.exceptionInfo||r.stderr,interleavedOutput:r.output,outputHead:r.outputTruncation?.outputHead,outputTail:r.outputTruncation?.outputTail,elidedChars:r.outputTruncation?.elidedChars,executionTime:r.localExecutionTimeMs??0,localExecutionTimeMs:r.localExecutionTimeMs},s=r.exceptionInfo.length>0,i=0!==r.returncode||s?{case:"failure",value:new fe.xC({...o,aborted:s,abortReason:r.abortReason})}:{case:"success",value:new fe.QR(o)};return new fe.W4({result:i,sandboxPolicy:hs(n)})}async runProcess({ctx:e,args:t,workingDirectory:r,sandboxPolicy:n,timeoutMs:o}){const s=performance.now(),i=this.defaultCwd,a=(await(0,No.resolveSandboxPolicyForWorkspace)(i,n?{perUser:n}:void 0)).policy,c="insecure_none"!==a.type?{...a,sandboxWorkspaceRoot:i}:a;return await new Promise((n=>{const i=new LT,a=new jT,l=new jT;let u,d,h=!1,p=!1,f="",m=()=>{};const g=(0,No.Qw)((0,No.ue)((0,No.Xw)({...process.env,...NT,CURSOR_AGENT:"1"}))),w={cwd:r,env:g,stdio:["pipe","pipe","pipe"],detached:"win32"!==process.platform,windowsVerbatimArguments:"win32"===process.platform},y="win32"===process.platform?{executable:process.env.ComSpec??"cmd.exe",args:(v=t.command,["/d","/s","/c",`"${v}"`])}:{executable:"/bin/sh",args:["-c",t.command]};var v;const b="insecure_none"===c.type?(0,au.D9)(iu.spawn,y.executable,y.args,w):(0,No.spawnInSandbox)(y.executable,y.args,w,c);b.stdin?.end();const S=e=>{h||(h=!0,clearTimeout(d),m(),n({...e,output:i.getOutput(),outputTruncation:i.getTruncation(),localExecutionTimeMs:Oy(performance.now()-s)}))};d=setTimeout((()=>{if(p=!0,void 0===u&&(f=`An error occurred while executing the command: Command timed out after ${o}ms`,u=fe.Lv.TIMEOUT,m()),void 0!==b.pid&&"win32"!==process.platform)try{return void process.kill(-b.pid,"SIGKILL")}catch{}b.kill("SIGKILL")}),o);const k=()=>{if(void 0===u){if(f="An error occurred while executing the command: Command aborted",u=fe.Lv.USER_ABORT,void 0!==b.pid&&"win32"!==process.platform)try{return void process.kill(-b.pid,"SIGTERM")}catch{}b.kill("SIGTERM")}};e.signal.aborted?k():(e.signal.addEventListener("abort",k,{once:!0}),m=()=>{e.signal.removeEventListener("abort",k)}),b.stdout?.setEncoding("utf8"),b.stdout?.on("data",(e=>{a.append(e),i.append(e)})),b.stderr?.setEncoding("utf8"),b.stderr?.on("data",(e=>{l.append(e),i.append(e)})),b.on("error",(e=>{S({stdout:a.text,stderr:l.text,returncode:-1,signal:"",exceptionInfo:`An error occurred while executing the command: ${e.message}`})})),b.on("close",((e,t)=>{S({stdout:a.text,stderr:l.text,returncode:f.length>0?-1:UT(e,t),signal:t??(p?"SIGKILL":""),exceptionInfo:f,abortReason:u})}))}))}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,D.VI)(e.withName("LocalMiniSweAgentBashExecutor.execute")),!1).ctx;(0,D.HF)(n,"LocalMiniSweAgentBashExecutor.execute");const o=t.command,s=(0,ts.o1)(t.workingDirectory||this.defaultCwd),i=t.timeout>0?t.timeout:3e4;if(!t.parsingResult)return new fe.W4({result:{case:"spawnError",value:new fe.mJ({command:o,workingDirectory:s,error:"Parsing result is required"})}});let a=t.requestedSandboxPolicy?ds(t.requestedSandboxPolicy):void 0;const c=await this.permissionsService.shouldBlockShellCommand(n,o,{workingDirectory:s,timeout:i,parsingResult:t.parsingResult,toolCallId:t.toolCallId},a);if("block"===c.kind)return"permissionsConfig"===c.reason.type&&c.reason.isReadonly?new fe.W4({result:{case:"permissionDenied",value:new fe.jn({command:o,workingDirectory:s,error:"Command blocked by permissions configuration",isReadonly:!0})}}):new fe.W4({result:{case:"rejected",value:new fe.pZ({command:o,workingDirectory:s,reason:td(c.reason)})}});a=c.policy,Ds()&&(a=Us(o,t.parsingResult)),a&&"insecure_none"!==a.type&&(a={...a,ignoreMapping:await this.ignoreService.getCursorIgnoreMapping()});const l=await this.runProcess({ctx:n,args:t,workingDirectory:s,sandboxPolicy:a,timeoutMs:i});return this.buildResult({args:t,workingDirectory:s,processResult:l,sandboxPolicy:a})}catch(e){r.error=e,r.hasError=!0}finally{DT(r)}}}const WT=G("shell-executor",(e=>new H(e,Q("shellArgs"),Y("shellResult"))),((e,t)=>{t.register(new A(e,te("shellArgs"),ee("shellResult")))})),HT=G("mini-swe-agent-bash-executor",(e=>new H(e,Q("miniSweAgentBashArgs"),Y("miniSweAgentBashResult"))),((e,t)=>{t.register(new A(e,te("miniSweAgentBashArgs"),ee("miniSweAgentBashResult")))}));function qT(e){return`${e} changed on disk after this tool call read it. Nothing was written. Read the file again and retry.`}function zT(e){return`${e} changed on disk after you last read or wrote it. Nothing was written. Read the file again and retry.`}(0,b.cF)(Symbol("optionalPendingPodWrite"),!1);const GT=G("write-executor",(e=>new H(e,Q("writeArgs"),Y("writeResult"))),((e,t)=>{t.register(new A(e,te("writeArgs"),ee("writeResult")))})),VT=G("delete-executor",(e=>new H(e,Q("deleteArgs"),Y("deleteResult"))),((e,t)=>{t.register(new A(e,te("deleteArgs"),ee("deleteResult")))})),KT=G("fetch-executor",(e=>new H(e,Q("fetchArgs"),Y("fetchResult"))),((e,t)=>{t.register(new A(e,te("fetchArgs"),ee("fetchResult")))})),JT=G("git-diff-executor",(e=>new H(e,Q("gitDiffRequest"),Y("gitDiffResponse"))),((e,t)=>{t.register(new A(e,te("gitDiffRequest"),ee("gitDiffResponse")))})),ZT=G("grep-executor",(e=>new H(e,Q("grepArgs"),Y("grepResult"))),((e,t)=>{t.register(new A(e,te("grepArgs"),ee("grepResult")))})),XT="[REDACTED]",QT=new TextEncoder;async function YT(e){const t=QT.encode(e),r=await crypto.subtle.digest("SHA-256",t);return{sha256:[...new Uint8Array(r)].map((e=>e.toString(16).padStart(2,"0"))).join(""),bytes:t.byteLength}}class eA{constructor(e){this.inner=e}async execute(e,t,r){if(!0!==t.digestOnly)return this.inner.execute(e,t,r);const n=t.clone();return n.digestOnly=void 0,n.maxChars=void 0,async function(e){if("success"!==e.result.case)return e;const t=e.result.value;if("content"!==t.output.case)return e;const{sha256:r,bytes:n}=await YT(t.output.value),o=t.clone();return o.output={case:void 0},o.outputBlobId=void 0,o.sha256=r,o.sizeBytes=BigInt(n),new Xy.sV({result:{case:"success",value:o}})}(await this.inner.execute(e,n,r))}}const tA=G("read-executor",(e=>new H(e,Q("readArgs"),Y("readResult"))),((e,t)=>{t.register(new A(e,te("readArgs"),ee("readResult")))})),rA=G("redacted-read-executor",(e=>new H(e,Q("redactedReadArgs"),Y("redactedReadResult"))),((e,t)=>{t.register(new A(e,te("redactedReadArgs"),ee("redactedReadResult")))})),nA=G("ls-executor",(e=>new H(e,Q("lsArgs"),Y("lsResult"))),((e,t)=>{t.register(new A(e,te("lsArgs"),ee("lsResult")))})),oA=G("diagnostics-executor",(e=>new H(e,Q("diagnosticsArgs"),Y("diagnosticsResult"))),((e,t)=>{t.register(new A(e,te("diagnosticsArgs"),ee("diagnosticsResult")))})),sA=G("canvas-diagnostics-executor",(e=>new H(e,Q("canvasDiagnosticsArgs"),Y("canvasDiagnosticsResult"))),((e,t)=>{t.register(new A(e,te("canvasDiagnosticsArgs"),ee("canvasDiagnosticsResult")))})),iA="$file:";const aA=(0,h.Pu)("mcp.symbolic_args.expansion",{description:"Outcome of late-binding $file:/abs/path MCP argument expansion at the executor boundary. The call is refused rather than carrying a placeholder to the server when the read reports having replaced a saved secret (`redacted`), or, from a read executor too old to report that, when its text still carries the redaction marker (`redacted_marker`)",labelNames:["route","outcome"]}),cA=(0,h.v5)("mcp.symbolic_args.bytes",{description:"Total bytes substituted into one MCP tool call by $file:/abs/path arguments",labelNames:["route"]}),lA=(0,h.Pu)("mcp.symbolic_args.describe",{description:"Per-file $file:/abs/path describe reads: `vm_digest` when the read executor hashed the file where it lives, `outdated_executor` when it returned the text instead (it predates $file: expansion, so the call is refused)",labelNames:["source"]}),uA=(0,h.v5)("mcp.symbolic_args.paths",{description:"Number of distinct $file:/abs/path arguments expanded in one MCP tool call",labelNames:["route"]});function dA(e,t,r){return{kind:e,message:`Could not resolve the symbolic argument "${iA}${t}": ${r} A string argument of the form "${iA}/absolute/path" is replaced with that file's contents before the tool runs; pass the literal text instead if you did not intend that.`}}const hA={redacted:e=>`${e} contains a saved secret, and a saved secret is never sent through a "${iA}/absolute/path" argument, so this call was not made. Do not retry it, and do not read the file to pass the value yourself. Tell the user that this file holds a saved secret and that they have to enter it in the tool's service themselves.`,redacted_marker:e=>`${e} may contain a saved secret: its text includes the placeholder "${XT}", and the computer that read it is too old to say whether a saved secret stood there, so this call was not made. Do not retry it, and do not read the file to pass the value yourself. Tell the user that this file may hold a saved secret and that they have to enter it in the tool's service themselves.`};function pA(e,t){return{kind:e,message:`Could not resolve the symbolic argument "${iA}${t}": ${hA[e](t)}`}}class fA extends Error{constructor(e){super(e.message),this.failure=e}}let mA;async function gA(e,t,r,n,o,{maxFileBytes:s=8388608,maxTotalBytes:i=16777216,refuseSavedSecrets:a=!1}){if(t.length>4)throw new fA(dA("too_many",t[4]??"",`at most 4 symbolic arguments may be used in one call (${t.length} given). Split the call or pass paths to tools that accept them.`));const c=r();if(void 0===c)throw new fA(dA("no_read_executor",t[0]??"","this environment cannot read files on behalf of a tool call."));const l=await(0,Nr.xb)(t,(t=>async function(e,t,r,n,o){const s=await t.execute(e,new Xy.a2({path:r,toolCallId:n,...o.digestOnly?{digestOnly:!0}:{}}));if("success"!==s.result.case)throw new fA(function(e,t,r){switch(e.result.case){case"fileNotFound":return dA("not_found",t,"the file does not exist.");case"permissionDenied":return dA("permission_denied",t,"reading it was not permitted.");case"rejected":return dA("rejected",t,`${e.result.value.reason||"the read was rejected"}. Only files the Read tool can read without approval can be substituted; read it with Read instead.`);case"invalidFile":return dA("not_text",t,"the file cannot be read as text.");case"error":return r?{kind:"read_error",message:`Could not resolve the symbolic argument "${iA}${t}": ${e.result.value.error}`}:dA("read_error",t,e.result.value.error);default:return dA("read_error",t,"the read returned no result.")}}(s,r,o.refuseSavedSecrets));return await async function(e,t,r,{maxFileBytes:n,digestOnly:o,refuseSavedSecrets:s}){const i=function(e,t,r,n){const o=n&&void 0!==t.sha256&&void 0!==t.sizeBytes?{sha256:t.sha256,bytes:Number(t.sizeBytes)}:void 0;if(void 0===o&&"content"!==t.output.case)throw new fA(dA("not_text",r,"the file is not a text file."));if(n){if(lA.increment(e,1,{source:void 0!==o?"vm_digest":"outdated_executor"}),void 0===o)throw new fA(dA("outdated_executor",r,"the computer that would run this tool has an older tool runner that cannot substitute files. Read the file and pass its contents instead."));return o}}(e,t,r,o),a="content"===t.output.case?t.output.value:void 0,{sha256:c,bytes:l}=i??await YT(a??""),u={content:a,bytes:l,sha256:c};if(t.truncated||l>n)throw new fA(dA("too_large",r,`the file is too large to inline (${Number(t.fileSize)||l} bytes; at most ${n} bytes per file may be substituted). Pass the path to a tool that accepts one, or read a range of it.`));return await async function(e,t,r,n){if(n){if(!0===e.redacted)throw new fA(pA("redacted",r));if(void 0===e.redacted&&await async function(e){return void 0!==e.content?e.content.includes(XT):(await(mA??=Promise.all([XT,`${XT}\n`,`${XT}\r\n`].map((async e=>(await YT(e)).sha256))).then((e=>new Set(e))),mA)).has(e.sha256)}(t))throw new fA(pA("redacted_marker",r))}}(t,u,r,s),u}(e,s.result.value,r,o)}(e,c,t,n,{maxFileBytes:s,digestOnly:o,refuseSavedSecrets:a})),{max:4});let u=0;for(const[e,r]of l)if(u+=r.bytes,u>i)throw new fA(dA("over_budget",e,`together the ${t.length} symbolic arguments exceed the ${i} bytes that may be substituted per call. Pass paths to tools that accept them instead.`));return l}async function wA(e,t,{route:r,getReadExecutor:n,...o}){if(0===t.symbolicPathArguments.length)return{kind:"none"};const s=new Map(t.symbolicPathArguments.map((e=>[e.path,e]))),i=[...s.keys()],a=t=>(aA.increment(e,1,{route:r,outcome:t.kind}),{kind:"failed",failure:t,result:new Mc.iz({result:{case:"error",value:new Mc.Nh({error:t.message})}})});let c;try{c=await gA(e,i,n,t.toolCallId,!1,o)}catch(e){return a(function(e,t){return e instanceof fA?e.failure:dA("read_error",t,e instanceof Error?e.message:String(e))}(e,i[0]??""))}let l=0;for(const[e,t]of c){l+=t.bytes;const r=s.get(e);if(r?.sha256!==t.sha256)return a(dA("content_changed",e,`the file changed after the call was reviewed (${r?.sizeBytes??0} bytes then, ${t.bytes} bytes now), so its new contents were not sent. Re-run the call to review the current contents.`))}const u=new Map([...c].map((([e,t])=>[e,t.content??""]))),d=function(e,t){const r=e=>{const n=function(e){if("string"!=typeof e||!e.startsWith(iA))return;const t=e.slice(6);return(r=t).startsWith("/")||/^[a-zA-Z]:[\\/]/.test(r)||r.startsWith("\\\\")?t:void 0;var r}(e);return void 0!==n?t.get(n)??e:Array.isArray(e)?e.map(r):null!==e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map((([e,t])=>[e,r(t)]))):e};return Object.fromEntries(Object.entries(e).map((([e,t])=>[e,r(t)])))}(Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()]))),u),h=t.clone();return h.args=Object.fromEntries(Object.entries(d).map((([e,t])=>[e,ve.Value.fromJson(t)]))),h.symbolicPathArguments=[],h.argumentsRepaired=!1,aA.increment(e,1,{route:r,outcome:"expanded"}),cA.record(e,l,{route:r}),uA.record(e,i.length,{route:r}),{kind:"expanded",expansion:{args:h,files:[...c].map((([e,t])=>({path:e,bytes:t.bytes}))),paths:i.length,bytes:l}}}const yA=/\b413\b|payload too large|request entity too large|body.*too large|too large.*body|ECONNRESET|EPIPE|socket hang up|max(?:imum)? (?:body|payload|request|content) (?:size|length)/i;function vA(e,t,r,n){return yA.test(t)?(aA.increment(e,1,{route:n,outcome:"server_rejected_body"}),`${t}\n\nThe request carried ${r.bytes} bytes of file contents substituted from ${r.paths} "${iA}/abs/path" argument(s), and the server appears to have rejected the request body as too large. Do not retry the same call: pass a smaller file or a range of it, or use a tool that accepts a path or upload instead.`):t}function bA(e){return e.files.map((e=>`"${iA}${e.path}" was replaced with the contents of ${e.path} (${e.bytes} bytes) before the call.`)).join("\n")}class SA{constructor(e,t,r={}){this.inner=e,this.getReadExecutor=t,this.options=r}isBackendRouted(e){return this.inner.isBackendRouted?.(e)??!1}async execute(e,t,r){if(0===t.symbolicPathArguments.length)return this.inner.execute(e,t,r);const n=await wA(e,t,{route:"local",getReadExecutor:this.getReadExecutor,refuseSavedSecrets:!0===this.options.refuseSavedSecrets&&t.refuseSavedSecrets});if("none"===n.kind)return this.inner.execute(e,t,r);if("failed"===n.kind)return n.result;let o;try{o=await this.inner.execute(e,n.expansion.args,r)}catch(t){throw t instanceof Error&&(t.message=vA(e,t.message,n.expansion,"local")),t}return function(e,t,r){const n=t.clone();return"success"===n.result.case?n.result.value.content.push(new Mc._Z({content:{case:"text",value:new Mc.zN({text:bA(r)})}})):"error"===n.result.case&&(n.result.value.error=vA(e,n.result.value.error,r,"local")),n}(e,o,n.expansion)}}const kA=G("background-shell-executor",(e=>new H(e,Q("backgroundShellSpawnArgs"),Y("backgroundShellSpawnResult"))),((e,t)=>{t.register(new A(e,te("backgroundShellSpawnArgs"),ee("backgroundShellSpawnResult")))})),_A=G("write-background-shell-input-executor",(e=>new H(e,Q("writeShellStdinArgs"),Y("writeShellStdinResult"))),((e,t)=>{t.register(new A(e,te("writeShellStdinArgs"),ee("writeShellStdinResult")))})),CA=G("agent-store-conflict-executor",(e=>new H(e,Q("agentStoreConflictArgs"),Y("agentStoreConflictResult"))),((e,t)=>{t.register(new A(e,te("agentStoreConflictArgs"),ee("agentStoreConflictResult")))})),EA=G("shell-allowlist-precheck-executor",(e=>new H(e,Q("shellAllowlistPrecheckArgs"),Y("shellAllowlistPrecheckResult"))),((e,t)=>{t.register(new A(e,te("shellAllowlistPrecheckArgs"),ee("shellAllowlistPrecheckResult")))})),xA=G("mcp-allowlist-precheck-executor",(e=>new H(e,Q("mcpAllowlistPrecheckArgs"),Y("mcpAllowlistPrecheckResult"))),((e,t)=>{t.register(new A(e,te("mcpAllowlistPrecheckArgs"),ee("mcpAllowlistPrecheckResult")))})),PA=G("web-fetch-allowlist-precheck-executor",(e=>new H(e,Q("webFetchAllowlistPrecheckArgs"),Y("webFetchAllowlistPrecheckResult"))),((e,t)=>{t.register(new A(e,te("webFetchAllowlistPrecheckArgs"),ee("webFetchAllowlistPrecheckResult")))})),RA=G("force-background-shell-executor",(e=>new H(e,Q("forceBackgroundShellArgs"),Y("forceBackgroundShellResult"))),((e,t)=>{t.register(new A(e,te("forceBackgroundShellArgs"),ee("forceBackgroundShellResult")))})),IA=G("computer-use-executor",(e=>new H(e,Q("computerUseArgs"),Y("computerUseResult"))),((e,t)=>{t.register(new A(e,te("computerUseArgs"),ee("computerUseResult")))})),TA=G("computer-use-end-turn-executor",(e=>new H(function(e){return{createExecInstance:(t,r)=>e.createExecInstance(t,(e=>{if(t.signal.aborted)throw new Error("computer-use turn end not sent: its caller stopped waiting");return r(e)}))}}(e),Q("computerUseEndTurnArgs"),Y("computerUseEndTurnResult"))),((e,t)=>{t.register(new A(e,te("computerUseEndTurnArgs"),ee("computerUseEndTurnResult")))})),AA=G("record-screen-executor",(e=>new H(e,Q("recordScreenArgs"),Y("recordScreenResult"))),((e,t)=>{t.register(new A(e,te("recordScreenArgs"),ee("recordScreenResult")))}));var $A=r("../proto/dist/generated/agent/v1/agent_store_conflict_exec_pb.js");function MA(e){if(void 0!==e)return{journalEpoch:e.journalEpoch,seq:Number(e.seq),lastEventId:e.lastEventId}}class DA{constructor(e){this.drainer=e}async execute(e,t){try{void 0!==t.includeQuotaNotices&&this.drainer.setIncludeQuotaNoticesOverride(t.includeQuotaNotices);const e=await this.drainer.drain({cursor:MA(t.cursor),advance:!1!==t.advance});return new $A.Ev({result:{case:"success",value:new $A.iS({events:e.events.map((e=>new $A.RZ({v:e.v,eventId:e.event_id,journalEpoch:e.journal_epoch,seq:BigInt(e.seq),tsMs:BigInt(e.ts_ms),kind:e.kind,storeId:e.store_id,originalRelPath:e.original_rel_path,conflictRelPath:e.conflict_rel_path,originalAbsPath:e.original_abs_path,conflictAbsPath:e.conflict_abs_path,preservedBytes:void 0===e.preserved_bytes?void 0:BigInt(e.preserved_bytes),scopeKind:e.scope_kind,limitBytes:void 0===e.limit_bytes?void 0:BigInt(e.limit_bytes),usageBytes:void 0===e.usage_bytes?void 0:BigInt(e.usage_bytes)}))),nextCursor:(r=e.nextCursor,new $A.LK({journalEpoch:r.journalEpoch,seq:BigInt(r.seq),lastEventId:r.lastEventId})),gap:e.gap})}})}catch(e){return new $A.Ev({result:{case:"error",value:new $A.h6({error:e instanceof Error?e.message:String(e)})}})}var r}}class OA{constructor(e){this.shellStdinWriter=e}async execute(e,t){const r=t.shellId;try{await this.shellStdinWriter(r,t.chars)}catch(e){return new Fo.nt({result:{case:"error",value:new Fo.Gv({error:`Failed to write to shell ${r} stdin: ${e instanceof Error?e.message:"Unknown error"}`})}})}return new Fo.nt({result:{case:"success",value:new Fo.tR({shellId:r,terminalFileLengthBeforeInputWritten:0})}})}}var FA=r("../proto/dist/generated/agent/v1/canvas_diagnostics_exec_pb.js"),NA=r("../proto/dist/generated/agent/v1/diagnostics_exec_pb.js");class LA{constructor(e,t){this.getCanvasDiagnostics=e,this.beginCanvasSave=t}async execute(e,t){let r=()=>{};const n=new Promise((e=>{r=e}));let o;if(void 0===this.beginCanvasSave)o=Promise.resolve(void 0);else try{o=this.beginCanvasSave(t.path,{typecheckOutcome:n}).catch((()=>{}))}catch{o=Promise.resolve(void 0)}try{const e=await this.getCanvasDiagnostics(t.path);return void 0===e?(r("unavailable"),jA(UA(t.path,"diagnostics unavailable"),await o)):(r(e.some((e=>1===e.severity))?"failed":"passed"),jA(new FA.GL({result:{case:"success",value:new FA.uX({path:t.path,diagnostics:e.map(BA)})}}),await o))}catch(e){return r("unavailable"),jA(UA(t.path,e instanceof Error?e.message:String(e)),await o)}}}function jA(e,t){return void 0===t||(e.saveState=t.saveState,e.canvasId=t.canvasId,e.title=t.title,e.saveDetail=t.saveDetail),e}function UA(e,t){return new FA.GL({result:{case:"error",value:new FA.HW({path:e,error:t})}})}function BA(e){return new NA.oQ({severity:WA(e.severity),range:new Fc.Q6({start:new Fc.yX({line:e.range.start.line+1,column:e.range.start.character+1}),end:new Fc.yX({line:e.range.end.line+1,column:e.range.end.character+1})}),message:e.message,source:"ts",code:e.code??""})}function WA(e){switch(e){case 1:return NA.h_.ERROR;case 2:return NA.h_.WARNING;case 3:return NA.h_.INFORMATION;case 4:return NA.h_.HINT;default:return NA.h_.UNSPECIFIED}}class HA{constructor(e){if(e.startsWith("file://")){if(!this.isValidFileUrl(e))throw new Error(`Invalid file URL: ${e}`);this.urlString=e}else{const t=this.resolvePath(e);this.urlString=this.pathToFileUrl(t)}}isValidFileUrl(e){try{return"file:"===new URL(e).protocol}catch{return!1}}resolvePath(e){if(e.includes("\\")&&(e=e.replace(/\\/g,"/")),/^[a-zA-Z]:\//.test(e)||/^\//.test(e))return e;const t=e.split("/"),r=[];for(let e=0;ethis.convertDiagnostic(e)));return new NA.Ek({result:{case:"success",value:new NA.a1({path:t.path,diagnostics:s,totalDiagnostics:s.length})}})}catch(r){return e.canceled?new NA.Ek({result:{case:"error",value:new NA.Ho({path:t.path,error:"Request timed out after 10 seconds"})}}):new NA.Ek({result:{case:"error",value:new NA.Ho({path:t.path,error:r instanceof Error?r.message:String(r)})}})}finally{n()}}catch(e){r.error=e,r.hasError=!0}finally{qA(r)}}convertDiagnostic(e){const t=e.message,r="string"==typeof t?t:t&&"object"==typeof t&&"value"in t&&"string"==typeof t.value?t.value:"";return new NA.oQ({severity:this.convertSeverity(e.severity),range:e.range?new Fc.Q6({start:new Fc.yX({line:e.range.start.line,column:e.range.start.character}),end:new Fc.yX({line:e.range.end.line,column:e.range.end.character})}):void 0,message:r,source:e.source,code:e.code?String(e.code):void 0})}convertSeverity(e){switch(e){case 1:return NA.h_.ERROR;case 2:return NA.h_.WARNING;case 3:return NA.h_.INFORMATION;case 4:return NA.h_.HINT;default:return NA.h_.UNSPECIFIED}}}async function GA(e){const{repoRoot:t,filePaths:r,getContent:n}=e,o=new Map;if(0===r.length)return o;const s=await async function(e,t){const r=new Map;if(0===t.length)return r;try{const{stdout:n}=await ky().run(e,["check-attr","linguist-generated","--stdin"],{input:`${t.join("\n")}\n`});for(const e of n.trim().split("\n")){const t=e.match(/^(.+): linguist-generated: (.+)$/);if(t){const e=t[1],n=t[2];"true"===n||"set"===n?r.set(e,!0):"false"!==n&&"unset"!==n||r.set(e,!1)}}}catch{}return r}(t,r);return await Promise.all(r.map((async e=>{const t=s.get(e);if(!0!==t)if(!1!==t)if(function(e){return new VA(e).isGeneratedByPath()}(e))o.set(e,{isGenerated:!0,source:"path-heuristic"});else{if(n){const t=await n(e);if(void 0!==t&&function(e,t){return new VA(e,(()=>t)).isGeneratedByContent()}(e,t))return void o.set(e,{isGenerated:!0,source:"content-heuristic"})}o.set(e,{isGenerated:!1,source:"none"})}else o.set(e,{isGenerated:!1,source:"gitattributes"});else o.set(e,{isGenerated:!0,source:"gitattributes"})}))),o}class VA{constructor(e,t){this.name=e,this.extname=s.extname(e).toLowerCase(),this.getContent=t}get lines(){if(void 0===this.cachedLines){const e=this.getContent?.();this.cachedLines=e?e.split("\n"):[]}return this.cachedLines}get data(){return this.getContent?.()}isGeneratedByPath(){return this.xcodeFile()||this.intellijFile()||this.cocoapods()||this.carthageBuild()||this.generatedGraphqlRelay()||this.generatedNetDesignerFile()||this.generatedNetSpecflowFeatureFile()||this.composerLock()||this.cargoLock()||this.cargoOrig()||this.denoLock()||this.flakeLock()||this.bazelLock()||this.nodeModules()||this.goVendor()||this.goLock()||this.packageResolved()||this.poetryLock()||this.pdmLock()||this.uvLock()||this.pixiLock()||this.esyLock()||this.npmShrinkwrapOrPackageLock()||this.pnpmLock()||this.bunLock()||this.terraformLock()||this.generatedYarnPlugnplay()||this.godeps()||this.generatedByZephir()||this.htmlcov()||this.gradleWrapper()||this.mavenWrapper()||this.pipenvLock()||this.generatedPascalTlb()||this.generatedSqlxQuery()||this.sourceMapByName()}isGeneratedByContent(){return!!this.getContent&&(this.minifiedFiles()||this.hasSourceMap()||this.sourceMap()||this.compiledCoffeescript()||this.generatedParser()||this.generatedNetDocfile()||this.generatedPostscript()||this.compiledCythonFile()||this.generatedGo()||this.generatedProtocolBufferFromGo()||this.generatedProtocolBuffer()||this.generatedJavascriptProtocolBuffer()||this.generatedTypescriptProtocolBuffer()||this.generatedApacheThrift()||this.generatedJniHeader()||this.vcrCassette()||this.generatedAntlr()||this.generatedModule()||this.generatedUnity3dMeta()||this.generatedRacc()||this.generatedJflex()||this.generatedGrammarkit()||this.generatedRoxygen2()||this.generatedHtml()||this.generatedJison()||this.generatedGrpcCpp()||this.generatedDart()||this.generatedPerlPpportHeader()||this.generatedGamemakerstudio()||this.generatedGimp()||this.generatedVisualstudio6()||this.generatedHaxe()||this.generatedJooq()||this.generatedSorbetRbi()||this.generatedMysqlViewDefinitionFormat())}xcodeFile(){return[".nib",".xcworkspacedata",".xcuserstate"].includes(this.extname)}intellijFile(){return/(?:^|\/)\.idea\//.test(this.name)}cocoapods(){return/(^Pods|\/Pods)\//.test(this.name)}carthageBuild(){return/(^|\/)Carthage\/Build\//.test(this.name)}generatedGraphqlRelay(){return/__generated__\//.test(this.name)}generatedNetDesignerFile(){return/\.designer\.(cs|vb)$/i.test(this.name)}generatedNetSpecflowFeatureFile(){return/\.feature\.cs$/i.test(this.name)}composerLock(){return/composer\.lock/.test(this.name)}cargoLock(){return/Cargo\.lock/.test(this.name)}cargoOrig(){return/Cargo\.toml\.orig/.test(this.name)}denoLock(){return/deno\.lock/.test(this.name)}flakeLock(){return/(^|\/)flake\.lock$/.test(this.name)}bazelLock(){return/(^|\/)MODULE\.bazel\.lock$/.test(this.name)}nodeModules(){return/node_modules\//.test(this.name)}goVendor(){return/vendor\/((?!-)[-0-9A-Za-z]+(?e+t.length),0)/this.lines.length>110}hasSourceMap(){return!!this.maybeMinified()&&this.lines.slice(-2).some((e=>/^\/[*/][#@] source(?:Mapping)?URL|sourceURL=/.test(e)))}sourceMap(){if(".map"!==this.extname)return!1;if(/\.(css|js)\.map$/i.test(this.name))return!0;const e=this.lines[0]||"";return/^{"version":\d+,/.test(e)||/^\/\*\* Begin line maps\. \*\*\/{/.test(e)}compiledCoffeescript(){if(".js"!==this.extname)return!1;const e=this.lines[0]||"";if(/^\/\/ Generated by /.test(e))return!0;if("(function() {"===e&&"}).call(this);"===(this.lines[this.lines.length-2]||"")&&""===(this.lines[this.lines.length-1]||"")){let e=0;for(const t of this.lines)if(/var /.test(t)){const r=t.match(/_fn|_i|_len|_ref|_results/g);e+=1*(r?.length||0);const n=t.match(/__bind|__extends|__hasProp|__indexOf|__slice/g);e+=3*(n?.length||0)}return e>=3}return!1}generatedNetDocfile(){return".xml"===this.extname&&!(this.lines.length<=3)&&(this.lines[1]||"").includes("")&&(this.lines[2]||"").includes("")&&(this.lines[this.lines.length-2]||"").includes("")}generatedParser(){if(".js"!==this.extname)return!1;const e=this.lines.slice(0,5).join("");return/^(?:[^/]|\/[^*])*\/\*(?:[^*]|\*[^/])*Generated by PEG\.js/.test(e)}generatedPostscript(){if(![".ps",".eps",".pfa"].includes(this.extname))return!1;const e=this.data;if(!e)return!1;if(/^\s*(?:currentfile eexec\s+|\/sfnts\s+\[\s<)/.test(e))return!0;const t=this.lines.slice(0,10).find((e=>/^%%Creator: /.test(e)));return!!t&&(!(!/[0-9]|draw|mpage|ImageMagick|inkscape|MATLAB/.test(t)&&!/PCBNEW|pnmtops|\(Unknown\)|Serif Affinity|Filterimage -tops/.test(t))||!!t.includes("EAGLE")&&this.lines.slice(0,5).some((e=>/^%%Title: EAGLE Drawing /.test(e))))}generatedGo(){return".go"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,40).some((e=>/^\/\/ Code generated .*/.test(e)))}generatedProtocolBufferFromGo(){return".proto"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,20).some((e=>e.includes("This file was autogenerated by go-to-protobuf")))}generatedProtocolBuffer(){return!![".py",".java",".h",".cc",".cpp",".m",".rb",".php"].includes(this.extname)&&!(this.lines.length<=1)&&this.lines.slice(0,3).some((e=>e.includes("Generated by the protocol buffer compiler. DO NOT EDIT!")))}generatedJavascriptProtocolBuffer(){return".js"===this.extname&&!(this.lines.length<=6)&&(this.lines[5]||"").includes("GENERATED CODE -- DO NOT EDIT!")}generatedTypescriptProtocolBuffer(){return".ts"===this.extname&&!(this.lines.length<=4)&&(this.lines[0]||"").includes("Code generated by protoc-gen-ts_proto. DO NOT EDIT.")}generatedApacheThrift(){return!![".rb",".py",".go",".js",".m",".java",".h",".cc",".cpp",".php"].includes(this.extname)&&this.lines.slice(0,6).some((e=>e.includes("Autogenerated by Thrift Compiler")))}generatedJniHeader(){return".h"===this.extname&&!(this.lines.length<=2)&&(this.lines[0]||"").includes("/* DO NOT EDIT THIS FILE - it is machine generated */")&&(this.lines[1]||"").includes("#include ")}vcrCassette(){return".yml"===this.extname&&!(this.lines.length<=2)&&(this.lines[this.lines.length-2]||"").includes("recorded_with: VCR")}generatedAntlr(){return".g"===this.extname&&!(this.lines.length<=2)&&(this.lines[1]||"").includes("generated by Xtest")}compiledCythonFile(){return!![".c",".cpp"].includes(this.extname)&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("Generated by Cython")}generatedModule(){if(".mod"!==this.extname)return!1;if(this.lines.length<=1)return!1;const e=this.lines[0]||"";return e.includes("PCBNEW-LibModule-V")||e.includes("GFORTRAN module version '")}generatedUnity3dMeta(){return".meta"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("fileFormatVersion: ")}generatedRacc(){return".rb"===this.extname&&!(this.lines.length<=2)&&(this.lines[2]||"").startsWith("# This file is automatically generated by Racc")}generatedJflex(){return".java"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("/* The following code was generated by JFlex ")}generatedGrammarkit(){return".java"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("// This is a generated file. Not intended for manual editing.")}generatedRoxygen2(){return".rd"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("% Generated by roxygen2: do not edit by hand")}generatedHtml(){if(![".html",".htm",".xhtml"].includes(this.extname))return!1;if(this.lines.length<=1)return!1;if(this.lines.slice(0,2).some((e=>//.test(e))))return!0;if(this.lines.length>2&&(this.lines[2]||"").startsWith("\x3c!-- This is an automatically generated file."))return!0;if(this.lines.slice(0,31).some((e=>//i.test(e))))return!0;const e=this.lines.slice(0,31).join(" ").match(/]+)>/gi);if(!e)return!1;for(const t of e){const e=this.extractHtmlMeta(t);if("generator"===e.name?.toLowerCase()&&(e.content||e.value)){const t=e.content||e.value||"";if(/^(org\s+mode|j?latex2html|groff|makeinfo|texi2html|ronn)\b/i.test(t))return!0}}return!1}extractHtmlMeta(e){const t={},r=e.matchAll(/(?<=^|\s)(name|content|value)\s*=\s*("[^"]+"|'[^']+'|[^\s"']+)/gi);for(const e of r){const r=e[1].toLowerCase();let n=e[2];(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'"))&&(n=n.slice(1,-1)),t[r]=n}return t}generatedJison(){if(".js"!==this.extname)return!1;if(this.lines.length<=1)return!1;const e=this.lines[0]||"";return e.startsWith("/* parser generated by jison ")||e.startsWith("/* generated by jison-lex ")}generatedGrpcCpp(){return!![".cpp",".hpp",".h",".cc"].includes(this.extname)&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("// Generated by the gRPC")}generatedDart(){return".dart"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,3).some((e=>/generated code\W{2,3}do not modify/i.test(e)))}generatedPerlPpportHeader(){return!!/ppport\.h$/.test(this.name)&&!(this.lines.length<=10)&&(this.lines[8]||"").includes("Automatically created by Devel::PPPort")}generatedGamemakerstudio(){if(![".yy",".yyp"].includes(this.extname))return!1;if(this.lines.length<=3)return!1;const e=this.lines.slice(0,3).join("");return/^\s*[{[]/.test(e)||/^\d\.\d\.\d.+\|\{/.test(this.lines[0]||"")}generatedGimp(){if(![".c",".h"].includes(this.extname))return!1;if(0===this.lines.length)return!1;const e=this.lines[0]||"";return/^\/\* GIMP [a-zA-Z0-9- ]+ C-Source image dump \(.+?\.c\) \*\//.test(e)||/^\/\* {2}GIMP header image file format \([a-zA-Z0-9- ]+\): .+?\.h {2}\*\//.test(e)}generatedVisualstudio6(){return".dsp"===this.extname&&this.lines.slice(0,3).some((e=>e.includes("# Microsoft Developer Studio Generated Build File")))}generatedHaxe(){return!![".js",".py",".lua",".cpp",".h",".java",".cs",".php"].includes(this.extname)&&this.lines.slice(0,3).some((e=>e.includes("Generated by Haxe")))}generatedJooq(){return".java"===this.extname&&this.lines.slice(0,2).some((e=>e.includes("This file is generated by jOOQ.")))}generatedSorbetRbi(){return".rbi"===this.extname&&!(this.lines.length<5)&&/^# typed:/.test(this.lines[0]||"")&&(this.lines[2]||"").includes("DO NOT EDIT MANUALLY")&&/^# Please (run|instead update this file by running) `bin\/tapioca/.test(this.lines[4]||"")}generatedMysqlViewDefinitionFormat(){return".frm"===this.extname&&(this.lines[0]||"").includes("TYPE=VIEW")}}const KA=e=>{if(!e)return[];if("string"!=typeof e||e.match(/^\s+$/))return[];const t=e.split("\n");if(0===t.length)return[];const r=[];let n=null,o=null,s=0,i=0,a=null;const c=e=>{o?.changes.push({type:"normal",normal:!0,ln1:s++,ln2:i++,content:e}),a.oldLines--,a.newLines--},l=e=>{const[t,o]=XA(e)??[];n={chunks:[],deletions:0,additions:0,from:t,to:o},r.push(n)},u=()=>{n&&!n.chunks.length||l()},d=e=>+(e||1),h=e=>{o&&(o.changes.push({type:"del",del:!0,ln:s++,content:e}),n.deletions++,a.oldLines--)},p=e=>{o&&(o.changes.push({type:"add",add:!0,ln:i++,content:e}),n.additions++,a.newLines--)},f=e=>{if(!o)return;const[t]=o.changes.slice(-1);o.changes.push({type:t.type,[t.type]:!0,ln1:t.ln1,ln2:t.ln2,ln:t.ln,content:e})},m=[[/^diff\s/,l],[/^new file mode (\d+)$/,(e,t)=>{u(),n.new=!0,n.newMode=t[1],n.from="/dev/null"}],[/^deleted file mode (\d+)$/,(e,t)=>{u(),n.deleted=!0,n.oldMode=t[1],n.to="/dev/null"}],[/^old mode (\d+)$/,(e,t)=>{u(),n.oldMode=t[1]}],[/^new mode (\d+)$/,(e,t)=>{u(),n.newMode=t[1]}],[/^index\s[\da-zA-Z]+\.\.[\da-zA-Z]+(\s(\d+))?$/,(e,t)=>{u(),n.index=e.split(" ").slice(1),t[1]&&(n.oldMode=n.newMode=t[1].trim())}],[/^---\s/,e=>{u(),n.from=YA(e)}],[/^\+\+\+\s/,e=>{u(),n.to=YA(e)}],[/^@@\s+-(\d+),?(\d+)?\s+\+(\d+),?(\d+)?\s@@/,(e,t)=>{n||l(e);const[r,c,u,h]=t.slice(1);s=+r,i=+u,o={content:e,changes:[],oldStart:+r,oldLines:d(c),newStart:+u,newLines:d(h)},a={oldLines:d(c),newLines:d(h)},n.chunks.push(o)}],[/^\\ No newline at end of file$/,f]],g=[[/^\\ No newline at end of file$/,f],[/^-/,h],[/^\+/,p],[/^\s+/,c]],w=e=>{a?(e=>{const t=e.charCodeAt(0);if(43===t)p(e);else if(45===t)h(e);else if(32===t)c(e);else if(92===t&&/^\\ No newline at end of file$/.test(e))f(e);else for(const[t,r]of g){const n=e.match(t);if(n){r(e,n);break}}0===a.oldLines&&0===a.newLines&&(a=null)})(e):(e=>{for(const[t,r]of m){const n=e.match(t);if(n){r(e,n);break}}})(e)};for(const e of t)w(e);return r},JA=/(a|i|w|c|o|1|2)\/.*(?=["']? ["']?(b|i|w|c|o|1|2)\/)|(b|i|w|c|o|1|2)\/.*$/g,ZA=/^(a|b|i|w|c|o|1|2)\//,XA=e=>{const t=e?.match(JA);return t?.map((e=>e.replace(ZA,"").replace(/("|')$/,"")))},QA=/^\\?['"]|\\?['"]$/g,YA=e=>{let t=e$(e,"-+").trim();return t=r$(t),t.replace(QA,"").replace(ZA,"")},e$=(e,t)=>{if(e=o$(e),!t&&String.prototype.trimLeft)return e.trimLeft();const r=n$(t);return e.replace(new RegExp(`^${r}+`),"")},t$=/\t.*|\d{4}-\d\d-\d\d\s\d\d:\d\d:\d\d(.\d+)?\s(\+|-)\d\d\d\d/,r$=e=>{const t=t$.exec(e);return t&&(e=e.substring(0,t.index).trim()),e},n$=e=>null==e?"\\s":e instanceof RegExp?e.source:`[${o$(e).replace(/([.*+?^=!:${}()|[\]/\\])/g,"\\$1")}]`,o$=e=>`${e??""}`,s$=(0,d.h)("local-mercurial-diff"),i$=5242880,a$="0000000000000000000000000000000000000000";let c$,l$;async function u$(e,t,r={}){const n=await async function(){if(void 0===c$&&(c$=await async function(e){const t="win32"===process.platform?["hg.com","hg.exe"]:["hg"];for(const r of e.split(s.delimiter))if(s.isAbsolute(r))for(const e of t){const t=s.join(r,e);try{if(!(await xo.stat(t)).isFile())continue;return"win32"!==process.platform&&await xo.access(t,Ro.constants.X_OK),t}catch{}}}(process.env.PATH??"")??null),null===c$){const e=new Error("hg executable not found");throw e.code="ENOENT",e}return c$}(),o=await new Promise(((o,s)=>{const i=(0,iu.spawn)(n,t,{cwd:e,env:{...process.env,HGPLAIN:"+strictflags",HGRCPATH:"",HGRCSKIPREPO:"1"},shell:!1}),a=new ca.StringDecoder("utf8");let c="";i.stdout.on("data",(e=>{c+=a.write(e)})),i.stderr.on("data",(()=>{})),i.on("error",(e=>{!0===r.allowFailure?o(""):s(e)})),i.on("close",(e=>{if(0===e||!0===r.allowFailure)o(c+a.end());else{const r=t.find((e=>!e.startsWith("-")))??"hg";s(new Error(`MercurialDiffFailed: hg ${r} exited ${e??"unknown"}`))}}))}));return o}async function d$(e){const t=await async function(e){let t=s.resolve(e);for(;;){try{if((await xo.stat(s.join(t,".hg"))).isDirectory())return!0}catch{}const e=s.dirname(t);if(e===t)return!1;t=e}}(e);if(!t)return;const r=function(e,t){return e&&"absent"!==t?"skips-repo-config"!==t?"unsafe":"proceed":"not-mercurial"}(t,await async function(){if(void 0!==l$)return l$;const e=await xo.mkdtemp(s.join((0,o.tmpdir)(),"hg-probe-"));try{const t=await u$(e,["help","environment"]);l$=/\bHGRCSKIPREPO\b/.test(t)?"skips-repo-config":"reads-repo-config"}catch(e){l$=function(e){return"object"==typeof e&&null!==e&&"code"in e&&"ENOENT"===e.code}(e)?"absent":"reads-repo-config"}finally{await xo.rm(e,{recursive:!0,force:!0})}return l$}());if("not-mercurial"===r)return;if("unsafe"===r)throw new Error("MercurialClientUnsafe: hg would read repository config");let n;try{n=(await u$(e,["root"])).trim()}catch{return}if(0!==n.length)try{return(await xo.stat(s.join(n,".hg"))).isDirectory()?n:void 0}catch{return}}function h$(e,t){return"win32"===process.platform?s.win32.normalize(e).toLowerCase()===s.win32.normalize(t).toLowerCase():s.resolve(e)===s.resolve(t)}function p$(e,t){const r=s.relative(s.resolve(t),s.resolve(e));return 0===r.length||!s.isAbsolute(r)&&!r.split(s.sep).includes("..")}async function f$(e){const t=s.resolve(e);try{return await xo.realpath(t)}catch{return t}}function m$(e){if(0===e.length)return[];const t=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),r=t.split("\n");return t.endsWith("\n")&&r.pop(),r}function g$(e){if(e.includes("\0")||/[\r\n]/.test(e))throw new Error("MercurialDiffFailed: base ref contains a newline")}async function w$({repositoryRoot:e,rev:t,filePath:r}){const n=await async function({repositoryRoot:e,rev:t,filePath:r}){let n;try{n=await u$(e,["files","-r",t,"-T","{size}","--",r])}catch{return}const o=n.trim();if(!/^\d+$/.test(o))return;const s=Number(o);return Number.isFinite(s)?s:void 0}({repositoryRoot:e,rev:t,filePath:r});return void 0===n||n>i$?"":u$(e,["cat","-r",t,"--",r])}async function y$(e,t,r){const n=function(e){switch(e){case Ue.ek.NAME_STATUS:return Ue.ek.NAME_STATUS;case Ue.ek.NAME_STATUS_AND_NUMSTAT:return Ue.ek.NAME_STATUS_AND_NUMSTAT;case Ue.ek.FILE_DIFFS:return Ue.ek.FILE_DIFFS;case Ue.ek.DIFFS_WITH_BEFORE_AND_AFTER:return Ue.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return Ue.ek.FILE_DIFFS}}(r.outputFormat),o=["root"],i=(await u$(t,["root"])).trim();if(0===i.length)throw new Error("MercurialDiffFailed: hg root did not resolve");let a,c;if(0!==r.ref.length||"HEAD"!==r.baseRef&&(r.mergeBase||0!==r.baseRef.length)){if(r.mergeBase||0===r.baseRef.length)a=await async function({cwd:e,baseRef:t,commands:r}){if(t.length>0&&"HEAD"!==t){g$(t),r.push("log");const n=(await u$(e,["log","-r",`ancestor(., (${t}))`,"-T","{node}"])).trim();if(0===n.length||n===a$)throw new Error("MercurialDiffFailed: base ref did not resolve");return n}r.push("log");const n=(await u$(e,["log","-r","max(::. and public())","-T","{node}"],{allowFailure:!0})).trim();if(n.length>0&&n!==a$)return n;const o=(await u$(e,["log","-r","ancestor(., default)","-T","{node}"],{allowFailure:!0})).trim();if(o.length>0&&o!==a$)return o;const s=(await u$(e,["log","-r",".","-T","{node}"],{allowFailure:!0})).trim();return s.length>0?s:a$}({cwd:t,baseRef:r.baseRef,commands:o});else if(g$(r.baseRef),o.push("log"),a=(await u$(t,["log","-r",r.baseRef,"-T","{node}"])).trim(),0===a.length)throw new Error("MercurialDiffFailed: base ref did not resolve");r.ref.length>0&&(g$(r.ref),o.push("log"),c=(await u$(t,["log","-r",r.ref,"-T","{node}"])).trim())}const l=["diff","--git"];r.includeSpaceChanges||l.push("-b"),void 0!==r.unifiedContextLines&&l.push(`-U${r.unifiedContextLines}`),void 0!==a&&l.push("-r",a),void 0!==c&&l.push("-r",c),r.targetPaths.length>0&&l.push("--",...r.targetPaths),o.push("diff");const u=await u$(t,l),d=function(e){const t=e.replace(/\r\n/g,"\n");return new Ue.o$({diffs:KA(t).map((e=>function(e){const t=new Ue.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new Ue.Ei({content:e.content,lines:e.changes.map((e=>e.content)),oldStart:e.oldStart,oldLines:e.oldLines,newStart:e.newStart,newLines:e.newLines})))});return t.added=e.additions,t.removed=e.deletions,t}(e))),diffType:Ue.Wf.UNSPECIFIED})}(u);let h=[];if(r.maxUntrackedFiles>0&&(o.push("status"),h=await async function({cwd:e,repositoryRoot:t,maxUnknownFiles:r}){let n=(await u$(e,["status","-un0"])).split("\0").filter((e=>e.length>0));return n.length>r&&(n=n.slice(0,r)),(await Promise.all(n.map((async e=>{try{const r=s.join(t,e),n=await xo.stat(r);if(n.size>i$){const t=await async function(e){const t=(0,ko.createHash)("sha256"),r=await xo.open(e,"r");try{const e=Buffer.alloc(65536);let n=0;for(;;){const{bytesRead:o}=await r.read(e,0,e.length,n);if(0===o)break;t.update(e.subarray(0,o)),n+=o}}finally{await r.close()}return t.digest("hex")}(r);return{contents:"",path:e,omittedDueToSize:!0,byteSize:n.size,contentHash:t}}return{contents:await xo.readFile(r,"utf8"),path:e}}catch{return}})))).filter((e=>void 0!==e))}({cwd:t,repositoryRoot:i,maxUnknownFiles:r.maxUntrackedFiles}),d.diffs.push(...h.map((e=>function(e){if(!0===e.omittedDueToSize)return new Ue.QP({from:"/dev/null",to:e.path,chunks:[],added:0,removed:0});const t=m$(e.contents);if(0===t.length)return new Ue.QP({from:"/dev/null",to:e.path,chunks:[],added:0,removed:0});const r=t.length;return new Ue.QP({from:"/dev/null",to:e.path,chunks:[new Ue.Ei({content:`@@ -0,0 +1${1===r?"":`,${r}`} @@`,lines:t.map((e=>`+${e}`)),oldStart:0,oldLines:0,newStart:1,newLines:r})],added:r,removed:0})}(e))))),n!==Ue.ek.FILE_DIFFS)for(const e of d.diffs)e.chunks=[];if(n===Ue.ek.DIFFS_WITH_BEFORE_AND_AFTER){const e=a??".";await Promise.all(d.diffs.map((async t=>{if("/dev/null"!==t.from)try{t.beforeFileContents=await w$({repositoryRoot:i,rev:e,filePath:t.from})}catch{t.beforeFileContents=""}else t.beforeFileContents="";if("/dev/null"!==t.to)if(void 0===c)try{const e=s.join(i,t.to),r=await xo.stat(e);t.afterFileContents=r.size>i$?"":await xo.readFile(e,"utf8")}catch{t.afterFileContents=""}else try{t.afterFileContents=await w$({repositoryRoot:i,rev:c,filePath:t.to})}catch{t.afterFileContents=""}else t.afterFileContents=""})))}const p=[u,function(e){const t=[];for(const r of e){const e=m$(r.contents);if(t.push(`diff --git a/${r.path} b/${r.path}`),t.push("new file mode 100644"),t.push("--- /dev/null"),t.push(`+++ b/${r.path}`),0===e.length)continue;const n=e.length;t.push(`@@ -0,0 +1${1===n?"":`,${n}`} @@`),t.push(...e.map((e=>`+${e}`)))}return t.join("\n")}(h.filter((e=>!0!==e.omittedDueToSize))),h.filter((e=>!0===e.omittedDueToSize)).map((e=>`omitted-untracked ${e.byteSize??0} ${e.contentHash??""} ${JSON.stringify(e.path)}`)).join("\n")].filter((e=>e.length>0)).join("\n"),f=r.computePatchId?function(e){if(0!==e.length)return`hg:${(0,ko.createHash)("sha256").update(e).digest("hex")}`}(p.length>0?`${p}\n`:""):void 0;let m,g;if(!0===r.returnHeadSha){o.push("log","status");const e=(await u$(t,["log","-r",".","-T","{node}"],{allowFailure:!0})).trim();m=e.length>0?e:a$,g=(await u$(t,["status","-0"])).length>0}s$.info(e,"Local mercurial diff commands",{sourceControl:"mercurial",commands:o});const w=new Ue.df({diff:d,submoduleDiffs:[],patchId:f,headSha:m,hasUncommittedChanges:g}),y=r.maxResponseBytes??0;if(y>0){const t=w.toBinary().byteLength;if(t>y)throw s$.info(e,"Local diff outcome",{sourceControl:"mercurial",outcome:"too_large"}),new Error(`GetDiffResponseTooLarge: ${t} bytes exceeds the ${y} byte limit`)}return s$.info(e,"Local diff outcome",{sourceControl:"mercurial",outcome:"ok",fileCount:d.diffs.length,patchIdPrefixed:!0===f?.startsWith("hg:")}),w}const v$=(0,d.h)("local-git-diff");function b$({exitCode:e,stderr:t}){return new Error(`Git command failed with code ${e}: ${t}`)}async function S$(e,t,r={}){let n;try{n=await e(t)}catch(e){if(!0===r.ignoreErrors)return"";throw e}if(0!==n.exitCode&&!0!==r.ignoreErrors)throw b$(n);return!0===r.shouldNotTrimOutput?n.stdout:n.stdout.trim()}function k$(e){const t=KA(e);return new Ue.o$({diffs:t.map((e=>function(e){const t=new Ue.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new Ue.Ei({content:e.content,lines:e.changes.map((e=>e.content)),oldStart:e.oldStart,oldLines:e.oldLines,newStart:e.newStart,newLines:e.newLines})))});return t.added=e.additions,t.removed=e.deletions,t}(e))),diffType:Ue.Wf.UNSPECIFIED})}function _$(e){const t=[];for(const n of e){const e={body:`+${(r=n.contents).replaceAll("\n","\n+")}`,numLines:Xs(r)},o=1===e.numLines?"@@ -0,0 +1 @@":`@@ -0,0 +1,${e.numLines} @@`;t.push(`diff --git a/${n.path} b/${n.path}\n--- /dev/null\n+++ b/${n.path}\n${o}\n${e.body}`)}var r;return t.join("\n")}const C$=["main","master","develop"];async function E$(e,t){const r=s.join(e,t),n=await xo.lstat(r);if(n.isSymbolicLink())return{contents:await xo.readlink(r),path:t,isSymlink:!0};if(!n.isFile())throw new Error("Not a regular file or symlink");return{contents:await xo.readFile(r,"utf8"),path:t,isSymlink:!1}}async function x$(e,t,r){const n=ky(),o=(e,r)=>n.run(t,e,r),i=await async function(e,t){let r;try{const e=(await S$(t,["rev-parse","--show-toplevel"])).trim();e.length>0&&(r=e)}catch{}if(void 0!==r){const t=await async function({cwd:e,gitRoot:t}){const r=await f$(t);let n=await f$(e);if(h$(n,r))return;let o=!1;for(;p$(n,r)&&!h$(n,r);){try{if((await xo.stat(s.join(n,".hg"))).isDirectory()){o=!0;break}}catch{}const e=s.dirname(n);if(e===n)break;n=e}return o?d$(e):void 0}({cwd:e,gitRoot:r});return void 0!==t?"mercurial":"git"}return void 0===await d$(e)?"none":"mercurial"}(t,o);if(v$.info(e,"Local diff source control",{sourceControl:i}),"none"===i)throw v$.info(e,"Local diff outcome",{sourceControl:i,outcome:"no_version_control"}),new Error("NoVersionControl: no git or mercurial repository");if("mercurial"===i)return y$(e,t,r);const a=function(e){switch(e){case Ue.ek.NAME_STATUS:return Ue.ek.NAME_STATUS;case Ue.ek.NAME_STATUS_AND_NUMSTAT:return Ue.ek.NAME_STATUS_AND_NUMSTAT;case Ue.ek.FILE_DIFFS:return Ue.ek.FILE_DIFFS;case Ue.ek.DIFFS_WITH_BEFORE_AND_AFTER:return Ue.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return Ue.ek.FILE_DIFFS}}(r.outputFormat),c=await(async()=>{let e=r.baseRef.length>0?r.baseRef:await async function(e){try{const t=await S$(e,["symbolic-ref","--short","refs/remotes/origin/HEAD"]);if(t)return t.trim()}catch{}for(const t of C$){const r=`origin/${t}`;try{return await S$(e,["rev-parse","--verify",r]),r}catch{}}try{const t=(await S$(e,["branch","-r"])).split("\n").map((e=>e.trim())).find((e=>e.startsWith("origin/")));if(t)return t}catch{}try{const t=await S$(e,["config","--get","init.defaultBranch"]);if(t)return t.trim()}catch{}throw new Error("Could not determine default branch")}(o);if(r.mergeBase){const t=r.ref.length>0?r.ref:"HEAD";e=(await S$(o,["merge-base","--end-of-options",e,t])).trim()}return e})(),l=["diff","--no-color"];r.includeSpaceChanges||l.push("--ignore-space-change"),void 0!==r.unifiedContextLines&&l.push(`-U${r.unifiedContextLines}`);const u=["--end-of-options",c];r.ref.length>0&&u.push(r.ref),r.targetPaths.length>0&&u.push("--",...r.targetPaths);const d=await o([...l,...u]);let h,p;if(0===d.exitCode)h=d.stdout,p=k$(h);else{const t=b$(d);if(r.computePatchId||!await async function(e){return(await S$(e,["config","--get-regexp","^(extensions\\.partialclone|remote\\..+\\.promisor)$"],{ignoreErrors:!0})).split("\n").some((e=>/^(extensions\.partialclone \S|remote\..+\.promisor( (true|yes|on|1))?$)/i.test(e)))}(o))throw t;p=await async function(e,t){const r=(await S$(e,["diff","--name-status","--no-renames","-z",...t])).split("\0"),n=[];for(let e=1;e{throw t})),v$.info(e,"Local diff outcome",{sourceControl:i,outcome:"partial_clone_names_only"})}let f=[];if(r.maxUntrackedFiles>0){f=await async function(e,t,r){let n=(await S$(t,["ls-files","--others","--exclude-standard"])).split("\n").map((e=>e.trim())).filter((e=>e.length>0));return n.length>r&&(n=n.slice(0,r)),(await Promise.all(n.map((async t=>{try{return await E$(e,t)}catch{return}})))).filter((e=>void 0!==e))}(t,o,r.maxUntrackedFiles);for(const e of f){const t=e.isSymlink?`${_$([e])}\n\\ No newline at end of file`:await S$(o,["diff","--no-color","--no-index","--","/dev/null",e.path],{ignoreErrors:!0,shouldNotTrimOutput:!0});p.diffs.push(...k$(t).diffs)}}if(a!==Ue.ek.FILE_DIFFS||!0===p.fileContentsOmitted)for(const e of p.diffs)e.chunks=[];if(a===Ue.ek.DIFFS_WITH_BEFORE_AND_AFTER&&!0!==p.fileContentsOmitted){const n=r.ref.length>0?r.ref:"HEAD";await Promise.all(p.diffs.map((async s=>{try{if("/dev/null"!==s.from)try{s.beforeFileContents=await S$(o,["show","--end-of-options",`${c}:${s.from}`],{shouldNotTrimOutput:!0})}catch{s.beforeFileContents=""}else s.beforeFileContents="";if("/dev/null"!==s.to)if(r.ref.length>0)try{s.afterFileContents=await S$(o,["show","--end-of-options",`${n}:${s.to}`],{shouldNotTrimOutput:!0})}catch{s.afterFileContents=""}else try{s.afterFileContents=(await E$(t,s.to)).contents}catch{try{s.afterFileContents=await S$(o,["show","--end-of-options",`${n}:${s.to}`],{shouldNotTrimOutput:!0})}catch{s.afterFileContents=""}}else s.afterFileContents=""}catch(t){v$.error(e,"Error fetching file contents for diff",t)}})))}const m=new Map;for(const e of p.diffs){const t="/dev/null"!==e.to?e.to:e.from;t&&m.set(t,e)}const g=[...m.keys()],w=r.ref.length>0?r.ref:"HEAD";try{const e=await GA({repoRoot:t,filePaths:g,getContent:async e=>{const t=m.get(e);if(t){if(void 0!==t.afterFileContents)return t.afterFileContents;try{if(t.to&&"/dev/null"!==t.to)return await S$(o,["show","--end-of-options",`${w}:${t.to}`],{shouldNotTrimOutput:!0})}catch{}}}});for(const[t,r]of e){const e=m.get(t);e&&(e.isGenerated=r.isGenerated)}}catch(t){v$.warn(e,"Generated-file detection failed; continuing without it",{error:t instanceof Error?t.message:String(t)})}const y=r.computePatchId&&void 0!==h?await async function(e,t){if(0===t.length)return;const{exitCode:r,stdout:n,stderr:o}=await e(["patch-id","--stable"],{input:t});if(0!==r)throw new Error(`git patch-id failed with code ${r}: ${o}`);return n.trim().split(/\s+/)[0]||void 0}(o,function(...e){const t=e.filter((e=>e.length>0));return 0===t.length?"":`${t.join("\n")}\n`}(h,_$(f))):void 0,v=!0===r.returnHeadSha?(await S$(o,["rev-parse","HEAD"])).trim():void 0,b=!0===r.returnHeadSha?(await S$(o,["status","--porcelain=v1","--untracked-files=all"])).trim().length>0:void 0,S=new Ue.df({diff:p,submoduleDiffs:[],patchId:y,headSha:v,hasUncommittedChanges:b}),k=r.maxResponseBytes??0;if(k>0){const e=S.toBinary().byteLength;if(e>k)throw new Error(`GetDiffResponseTooLarge: ${e} bytes exceeds the ${k} byte limit`)}return S}class P${async execute(e,t){return x$(e,t.cwd,t)}}var R$=r("../proto/dist/generated/agent/v1/mcp_allowlist_precheck_exec_pb.js");class I${constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isMcpFullyAllowlisted(e,{providerIdentifier:t.providerIdentifier,toolName:t.toolName,annotationsJson:t.annotationsJson});return new R$.M({allowlisted:r})}}var T$=r("../proto/dist/generated/agent/v1/record_screen_exec_pb.js"),A$=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function $$(e){return null!==e.exitCode||null!==e.signalCode||e.killed}function M$(e,t){return"object"==typeof e&&null!==e&&"code"in e&&e.code===t}function D$(e){return e instanceof Error?e.message:String(e)}function O$(e,t){return new T$.Tj({result:{case:"failure",value:new T$.yH({error:t,kind:e})}})}function F$(e){return e instanceof Error?e.message.startsWith("Failed to load polished-renderer native binding")?"binding_load_failed":"code"in e&&"string"==typeof e.code?e.code:e.name:typeof e}function N$(e,t,r,n){const o=[],s=function(e,t){const r=e.ffmpegExitCode??e.childProcess.exitCode,n=e.ffmpegExitSignal??e.childProcess.signalCode;if(e.ffmpegDiedEarly||null!==e.ffmpegDiedTime||null!==r||null!==n)return`ffmpeg exited code=${r} signal=${n}${null!==e.ffmpegDiedTime?` ${Math.max(0,Math.round((t-e.ffmpegDiedTime)/1e3))}s before SAVE`:""}`}(t,n);return void 0!==s&&o.push(s),void 0!==r&&o.push(`stop failed: ${D$(r)}`),o.length>0?`${e} (${o.join("; ")})`:e}const L$=(0,Vs.promisify)(iu.execFile);class j${constructor(e){if(this.activeRecording=null,this.inFlightSaves=[],this.onRecordingStartedCallback=null,this.onRecordingStoppedCallback=null,this.recordingStoppedCallbackInvoked=!1,this.artifactsDir=e.artifactsDir,this.stagingDir=e.stagingDir??"/opt/cursor/recording-staging/",this.display=e.display,this.disablePolishedRendering=e.disablePolishedRendering??!1,this.polishedRenderer=e.polishedRenderer,!this.disablePolishedRendering){if(!this.polishedRenderer)throw new Error("record_screen requires a polished recording renderer when polished rendering is enabled. This tool should run via exec-daemon where that dependency is bundled.");this.polishedRenderer.assertAvailable()}}setOnRecordingStarted(e){this.onRecordingStartedCallback=e}setOnRecordingStopped(e){this.onRecordingStoppedCallback=e}invokeStoppedCallbackOnce(){!this.recordingStoppedCallbackInvoked&&this.onRecordingStoppedCallback&&(this.recordingStoppedCallbackInvoked=!0,this.onRecordingStoppedCallback())}async cleanupRecording(e){try{await(e.inputEventLogger?.stop())}catch{}if(!$$(e.childProcess)&&e.childProcess.pid)try{await this.stopFfmpegRecording(e)}catch{try{process.kill(e.childProcess.pid,"SIGKILL")}catch{}}}getActiveInputEventLogger(){return this.activeRecording?.inputEventLogger??null}async dispose(){const e=this.inFlightSaves.map((e=>e.promise));if(e.length>0)try{await(0,Nr.wj)(Promise.all(e),j$.IN_FLIGHT_SAVE_DISPOSE_TIMEOUT_MS,"Timed out waiting for in-flight recording save")}catch{}if(this.activeRecording){await this.cleanupRecording(this.activeRecording),this.invokeStoppedCallbackOnce();try{await xo.rm(this.activeRecording.sessionDir,{force:!0,recursive:!0})}catch{}this.activeRecording=null}}findInFlightSave(e){return this.inFlightSaves.find((t=>t.state===e))}clearActiveRecordingIfCurrent(e){this.activeRecording===e&&(this.activeRecording=null)}invokeStoppedCallbackIfCurrent(e){this.activeRecording===e&&this.invokeStoppedCallbackOnce()}sanitizeToolCallId(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}async ensureRecordingDirectoryExists(){await xo.mkdir(this.stagingDir,{recursive:!0}),await xo.mkdir(this.artifactsDir,{recursive:!0})}buildSessionDir(e){const t=this.sanitizeToolCallId(e),r=`session-${(new Date).toISOString().replace(/[:.]/g,"-")}-${t}`;return s.join(this.stagingDir,r)}validateAndNormalizeSaveAsFilename(e){let t=e.trim();return t.startsWith(this.artifactsDir)&&(t=t.slice(this.artifactsDir.length),t.startsWith("/")&&(t=t.slice(1))),t=t.trim(),0===t.length?{success:!1,reason:T$.y.UNSPECIFIED}:t.includes("/")||t.includes("\\")?{success:!1,reason:T$.y.SLASHES_NOT_ALLOWED}:(t=t.replace(/[^a-zA-Z0-9 ._-]/g,"_"),t=t.trim(),0===t.length?{success:!1,reason:T$.y.UNSPECIFIED}:(t.length>128&&(t=t.slice(0,128).trim()),t.toLowerCase().endsWith(".mp4")||(t=`${t}.mp4`),{success:!0,filename:t}))}async movePolishedVideo(e,t){try{return void await xo.rename(e,t)}catch(e){if(!M$(e,"EXDEV"))throw e}try{await xo.copyFile(e,t)}catch(e){throw await xo.rm(t,{force:!0}).catch((()=>{})),e}try{await xo.unlink(e)}catch(e){throw await xo.rm(t,{force:!0}).catch((()=>{})),e}}async getUniqueArtifactVideoPath(e){const t=s.parse(e),r=t.name||"recording",n=t.ext||".mp4";let o=`${r}${n}`,i=2;for(;;){const e=s.join(this.artifactsDir,o);try{const t=await xo.open(e,"wx");return await t.close(),e}catch(e){if(!M$(e,"EEXIST"))throw e;o=`${r}-${i}${n}`,i++}}}async resolveArtifactVideoPath(e){const{saveAsFilename:t,stagingSessionDir:r}=e;let n,o;if(t){const e=this.validateAndNormalizeSaveAsFilename(t);e.success?o=e.filename:(n=e.reason,o=`${s.basename(r)}.mp4`)}else o=`${s.basename(r)}.mp4`;return{finalVideoPath:await this.getUniqueArtifactVideoPath(o),requestedFilePathRejectedReason:n}}async getVideoDurationMs(e){const{stdout:t}=await(0,au.D9)(L$,"ffprobe",["-v","error","-show_entries","format=duration","-of","default=noprint_wrappers=1:nokey=1",e],{encoding:"utf8"}),r=parseFloat(t.trim());if(!Number.isFinite(r)||r<0)throw new Error(`Invalid video duration from ffprobe: ${t.trim()}`);return Math.floor(1e3*r)}async getVideoDimensions(e){const{stdout:t}=await(0,au.D9)(L$,"ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=width,height","-of","csv=p=0:s=x",e],{encoding:"utf8"}),[r,n]=t.trim().split("x"),o=Number.parseInt(r,10),s=Number.parseInt(n,10);if(!Number.isFinite(o)||!Number.isFinite(s))throw new Error(`Invalid video dimensions from ffprobe: ${t.trim()}`);if(o<=0||s<=0)throw new Error(`Invalid non-positive video dimensions from ffprobe: ${t.trim()}`);return{width:o,height:s}}async renderPolished(e,t){const r=s.join(t,"recording"),n=s.join(r,"recording_full.mp4");try{await this.polishedRenderer.renderRecordingSession({stagingSessionDir:t,outputVideoPath:n,fps:j$.PROXY_TARGET_FPS,includeBrandTag:!0}),await xo.access(n,xo.constants.R_OK)}catch(t){const r=(0,D.fU)(e);throw r?.setAttribute("error.type",F$(t)),r?.setStatus({code:2}),t}return n}async getVideoFramerate(e){try{const{stdout:t}=await(0,au.D9)(L$,"ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=r_frame_rate","-of","default=noprint_wrappers=1:nokey=1",e],{encoding:"utf8"}),r=t.trim();if(r.includes("/")){const[e,t]=r.split("/"),n=Number.parseFloat(e),o=Number.parseFloat(t);if(Number.isFinite(n)&&Number.isFinite(o)&&0!==o){const e=n/o;if(e>0&&e<500)return Math.round(e)}}else{const e=Number.parseFloat(r);if(Number.isFinite(e)&&e>0&&e<500)return Math.round(e)}console.warn(`[record-screen] Unexpected ffprobe r_frame_rate output "${r}", defaulting to ${j$.PROXY_TARGET_FPS}fps`)}catch(e){console.warn(`[record-screen] Failed to read video framerate: ${e instanceof Error?e.message:String(e)}, defaulting to ${j$.PROXY_TARGET_FPS}fps`)}return j$.PROXY_TARGET_FPS}async startFfmpegRecording(e,t){const r=s.join(t,"recording");await xo.mkdir(r,{recursive:!0});const n=s.join(r,"recording_render_proxy_1080p.mp4"),o="windowsDesktop"===e.kind?["-f","gdigrab","-i","desktop"]:["-video_size",e.resolution,"-framerate",String(await this.detectRefreshRate(e.display)),"-draw_mouse","0","-f","x11grab","-i",e.display],i=["-vf",`scale=${j$.PROXY_TARGET_WIDTH}:-2:flags=lanczos,fps=${j$.PROXY_TARGET_FPS}`,"-c:v","libx264","-preset",j$.PROXY_PRESET,"-crf",String(j$.PROXY_CRF),"-pix_fmt","yuv420p","-profile:v","high","-x264-params","keyint=1:min-keyint=1:scenecut=0:bframes=0","-movflags","+faststart","-tune","fastdecode"],a=["-vf",`scale=${j$.PROXY_TARGET_WIDTH}:-2:flags=lanczos`,"-c:v","libx264","-preset",j$.PROXY_PRESET,"-pix_fmt","yuv420p","-movflags","+faststart"],c=this.disablePolishedRendering?a:i,l=(0,au.D9)(iu.spawn,"ffmpeg",[...o,...c,"-y",n],{stdio:["win32"===process.platform?"pipe":"ignore","pipe","pipe"],detached:"win32"!==process.platform,windowsHide:!0}),u=new Promise(((e,t)=>{let r="",n=!1;l.stderr?.on("data",(t=>{r+=t.toString(),!n&&r.includes("frame=")&&(n=!0,e(Date.now()))}));const o=setTimeout((()=>{n||t(new Error("ffmpeg did not start encoding within 5 seconds"))}),5e3);l.once("exit",((e,r)=>{clearTimeout(o),n||t(new Error(`ffmpeg exited before starting: code=${e} signal=${r}`))})),l.once("error",(e=>{clearTimeout(o),n||t(new Error(`ffmpeg failed to start: ${e.message}`))}))}));return await new Promise(((e,t)=>{const r=setTimeout(e,300);l.once("error",(e=>{clearTimeout(r),t(new Error(`Failed to start ffmpeg: ${e.message}`))})),l.once("exit",((e,n)=>{clearTimeout(r),t(null!==e&&0!==e?new Error(`ffmpeg exited with code ${e}`):null!==n?new Error(`ffmpeg killed by signal ${n}`):new Error("ffmpeg exited unexpectedly during startup"))}))})),{process:l,videoStartedPromise:u}}async detectRefreshRate(e){try{return(await qg(e)).display.refreshRate}catch(e){return console.warn(`[record-screen] Failed to detect refresh rate: ${e instanceof Error?e.message:String(e)}, using default ${j$.DEFAULT_REFRESH_RATE}Hz`),j$.DEFAULT_REFRESH_RATE}}async runFfmpegCommand(e,t){return await new Promise(((r,n)=>{const o=(0,au.D9)(iu.spawn,"ffmpeg",t,{stdio:["ignore","ignore","pipe"]});let s="";o.stderr?.on("data",(e=>{s.length<2e4&&(s+=e.toString())})),o.once("error",(t=>{n(new Error(`ffmpeg ${e} failed to start: ${t instanceof Error?t.message:String(t)}`))})),o.once("close",(t=>{0===t?r():n(new Error(`ffmpeg ${e} exited with code ${t}: ${s.trim()}`))}))}))}async saveRecordingDataPackage(e){const{sessionDir:t,durationMs:r,recordingStartEpochMs:n,ffmpegStartedEpochMs:o,inputEvents:i,resolution:a,renderProxies:c}=e,l=s.join(t,"recording"),u=s.join(l,"recording-data.json"),d=o-n,h=i.map((e=>({executionTimestampMs:e.executionTimestampMs,commandDurationMs:e.commandDurationMs,positionBefore:e.positionBefore,positionAfter:e.positionAfter,cursorTypeAfter:e.cursorTypeAfter,action:{action:this.serializeAction(e.action)}}))),p={version:3,durationMs:r,recordingStartEpochMs:n,ffmpegStartedEpochMs:o,eventToVideoOffsetMs:d,displayWidth:a.display.width,displayHeight:a.display.height,apiWidth:a.api.width,apiHeight:a.api.height,inputEvents:h,renderProxies:c??null};await xo.writeFile(u,JSON.stringify(p,null,2))}serializeAction(e){const{action:t}=e,r={case:t.case};switch(t.case){case"click":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null,button:t.value.button,count:t.value.count,modifierKeys:t.value.modifierKeys};break;case"mouseMove":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null};break;case"type":r.value={text:t.value.text};break;case"key":r.value={key:t.value.key,holdDurationMs:t.value.holdDurationMs};break;case"scroll":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null,direction:t.value.direction,amount:t.value.amount,modifierKeys:t.value.modifierKeys};break;case"drag":r.value={path:t.value.path.map((e=>({x:e.x,y:e.y}))),button:t.value.button};break;case"wait":r.value={durationMs:t.value.durationMs};break;case"screenshot":case"cursorPosition":case"mouseDown":case"mouseUp":r.value=t.value;break;default:r.value={}}return r}async stopFfmpegRecording(e){const{childProcess:t}=e;if($$(t)||!t.pid)return;const r=t.pid;return new Promise(((e,n)=>{const o=setTimeout((()=>{try{try{process.kill(-r,"SIGKILL")}catch{process.kill(r,"SIGKILL")}}catch{}n(new Error("Timeout waiting for ffmpeg to stop"))}),2e4);t.once("exit",(()=>{clearTimeout(o),e()})),t.once("error",(e=>{clearTimeout(o),n(new Error(`Error stopping ffmpeg: ${e.message}`))}));try{if(t.stdin)return t.stdin.on("error",(()=>{})),void t.stdin.end("q");try{process.kill(-r,"SIGTERM")}catch{process.kill(r,"SIGTERM")}}catch(t){if(clearTimeout(o),M$(t,"ESRCH"))return void e();n(new Error(`Failed to send SIGTERM: ${t instanceof Error?t.message:String(t)}`))}}))}async performSave(e,t,r){const n=Date.now();let o=T$.Wg.INTERNAL;try{const i=await(r.inputEventLogger?.stop())??[],a=r.inputEventLogger?.getRecordingStartTime()??r.startTime;let c;this.invokeStoppedCallbackIfCurrent(r);try{!$$(r.childProcess)&&r.childProcess.pid&&await this.stopFfmpegRecording(r)}catch(e){c=e,console.warn(`[record-screen] Failed to stop ffmpeg: ${D$(e)}`)}const l=r.ffmpegStartedEpochMs??a,u=r.sessionDir,d=s.join(u,"recording"),h=s.join(d,"recording_render_proxy_1080p.mp4");let p,f,m;try{await xo.access(h,xo.constants.R_OK)}catch(e){await this.cleanupRecording(r),this.clearActiveRecordingIfCurrent(r);const t=M$(e,"ENOENT"),o=t?`Recording proxy not found at ${h}`:`Recording proxy at ${h} could not be validated: ${D$(e)}`;return O$(t?T$.Wg.PROXY_MISSING:T$.Wg.STAGING_IO,N$(o,r,c,n))}try{if([p,f,m]=await Promise.all([this.getVideoDurationMs(h),this.getVideoDimensions(h),this.getVideoFramerate(h)]),p<=0)throw new Error(`Recording proxy has zero duration at ${h}`)}catch(e){await this.cleanupRecording(r);const t=D$(e),o=t.includes(h)?t:`Recording proxy at ${h} could not be validated: ${t}`;return O$(T$.Wg.PROXY_INVALID,N$(o,r,c,n))}const g={profileVersion:j$.PROXY_PROFILE_VERSION,generatedAtEpochMs:Date.now(),source:{width:f.width,height:f.height,durationMs:p,fps:m},artifacts:[{name:"render_proxy_1080p",path:"recording_render_proxy_1080p.mp4",width:f.width,height:f.height,fps:j$.PROXY_TARGET_FPS,codec:"h264",profile:j$.PROXY_PROFILE_VERSION,keyint:1,status:"success",elapsedMs:0}]};o=T$.Wg.STAGING_IO,void 0!==r.resolution&&await this.saveRecordingDataPackage({sessionDir:u,durationMs:p,recordingStartEpochMs:a,ffmpegStartedEpochMs:l,inputEvents:i,resolution:r.resolution,renderProxies:g}),o=T$.Wg.ARTIFACT_WRITE_FAILED;const{finalVideoPath:w,requestedFilePathRejectedReason:y}=await this.resolveArtifactVideoPath({saveAsFilename:t.saveAsFilename,stagingSessionDir:u});try{if(this.disablePolishedRendering)await xo.copyFile(h,w);else{o=T$.Wg.RENDER_FAILED;const t=await this.renderPolished(e,u);o=T$.Wg.ARTIFACT_WRITE_FAILED,await this.movePolishedVideo(t,w)}}catch(e){throw await xo.rm(w,{force:!0}).catch((()=>{})),e}try{await xo.rm(u,{force:!0,recursive:!0})}catch(e){console.warn(`[record-screen] Failed to remove staging session ${u}: ${D$(e)}`)}return this.clearActiveRecordingIfCurrent(r),new T$.Tj({result:{case:"saveSuccess",value:new T$.ol({path:w,recordingDurationMs:ve.protoInt64.parse(p.toString()),requestedFilePathRejectedReason:y})}})}catch(e){return await this.cleanupRecording(r),this.invokeStoppedCallbackIfCurrent(r),O$("binding_load_failed"===F$(e)?T$.Wg.RENDERER_UNAVAILABLE:o,D$(e))}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,D.VI)(e.withName("LocalRecordScreenExecutor.execute")),!1);try{await this.ensureRecordingDirectoryExists()}catch(e){return O$(T$.Wg.STAGING_IO,`Failed to create recording directory: ${e instanceof Error?e.message:String(e)}. Ensure the parent directory exists and has write permissions, or run: sudo mkdir -p ${this.stagingDir} ${this.artifactsDir} && sudo chmod 777 ${this.stagingDir} ${this.artifactsDir}`)}if(t.mode===T$.$u.UNSPECIFIED)return O$(T$.Wg.INVALID_MODE,"Mode must be one of START_RECORDING, SAVE_RECORDING, DISCARD_RECORDING");switch(t.mode){case T$.$u.START_RECORDING:{this.recordingStoppedCallbackInvoked=!1;let e=!1;if(this.activeRecording){const t=this.activeRecording;if(!this.inFlightSaves.some((e=>e.state===t))){e=!0;try{await this.cleanupRecording(t),await xo.rm(t.sessionDir,{force:!0,recursive:!0}).catch((()=>{}))}catch{}}this.activeRecording=null}let r,n=null,o=null,s=T$.Wg.STAGING_IO;try{o=this.buildSessionDir(t.toolCallId||"recording"),await xo.mkdir(o,{recursive:!0}),s=T$.Wg.DISPLAY_UNAVAILABLE;const i="win32"===process.platform?void 0:await qg(this.display),a=void 0===i?{kind:"windowsDesktop"}:{kind:"x11",display:this.display,resolution:i.resolutionString};s=T$.Wg.FFMPEG_START_FAILED;const{process:c,videoStartedPromise:l}=await this.startFfmpegRecording(a,o);n=c;const u=this.disablePolishedRendering?void 0:i?.resolution;void 0!==u&&(s=T$.Wg.INTERNAL,r=new Yg({displayNum:Wg(this.display),resolution:u}),await r.start());const d=r?.getRecordingStartTime()??Date.now();let h;s=T$.Wg.FFMPEG_START_FAILED;try{h=await l}catch(e){throw new Error(`ffmpeg failed to start encoding: ${e instanceof Error?e.message:String(e)}`)}const p={childProcess:n,sessionDir:o,startTime:d,inputEventLogger:r,resolution:u,ffmpegStartedEpochMs:h,ffmpegDiedEarly:!1,ffmpegDiedTime:null,ffmpegExitCode:null,ffmpegExitSignal:null};this.activeRecording=p,this.onRecordingStartedCallback&&r&&this.onRecordingStartedCallback(r),n.once("exit",((e,t)=>{p.ffmpegDiedEarly=!0,p.ffmpegDiedTime=Date.now(),p.ffmpegExitCode=e,p.ffmpegExitSignal=t}));const f=!!t.saveAsFilename;return new T$.Tj({result:{case:"startSuccess",value:new T$.T4({wasPriorRecordingCancelled:e,wasSaveAsFilenameIgnored:f})}})}catch(e){if(r)try{await r.stop()}catch{}if(n&&!n.killed&&n.pid)try{process.kill(n.pid,"SIGKILL")}catch{}return o&&await xo.rm(o,{force:!0,recursive:!0}).catch((()=>{})),this.activeRecording=null,O$(s,D$(e))}}case T$.$u.SAVE_RECORDING:{if(!this.activeRecording)return 1===this.inFlightSaves.length?await this.inFlightSaves[0].promise:O$(T$.Wg.NO_ACTIVE_RECORDING,"No active recording to save");const e=this.activeRecording,r=this.findInFlightSave(e);if(r)return await r.promise;const o=Promise.resolve().then((()=>this.performSave(n.ctx,t,e))),s={state:e,promise:o};this.inFlightSaves.push(s);try{return await o}finally{this.inFlightSaves=this.inFlightSaves.filter((e=>e!==s))}}case T$.$u.DISCARD_RECORDING:{if(!this.activeRecording)return O$(T$.Wg.NO_ACTIVE_RECORDING,"No active recording to discard");const e=this.activeRecording;if(this.findInFlightSave(e))return O$(T$.Wg.SAVE_IN_PROGRESS,"Save in progress for this recording; wait for it or start a new recording");let t=T$.Wg.INTERNAL;try{return await(e.inputEventLogger?.stop()),this.invokeStoppedCallbackOnce(),!$$(e.childProcess)&&e.childProcess.pid&&(t=T$.Wg.FFMPEG_STOP_FAILED,await this.stopFfmpegRecording(e)),t=T$.Wg.STAGING_IO,await xo.rm(e.sessionDir,{force:!0,recursive:!0}),this.activeRecording=null,new T$.Tj({result:{case:"discardSuccess",value:new T$.N8}})}catch(r){await this.cleanupRecording(e),this.invokeStoppedCallbackOnce();const n=e.sessionDir;let o=!1;try{await xo.rm(n,{force:!0,recursive:!0}),o=!0}catch{}this.activeRecording=null;return O$(t,`Failed to discard recording: ${r instanceof Error?r.message:String(r)}${o?"":`. Session may remain at: ${n}`}`)}}default:{const e=t.mode;return O$(T$.Wg.INVALID_MODE,`Unhandled recording mode: ${String(e)}`)}}}catch(e){r.error=e,r.hasError=!0}finally{A$(r)}}}async function U$(e){const t=await(0,xo.readdir)(e,{withFileTypes:!0}).catch((()=>[])),r=[];for(const n of t){const t=s.join(e,n.name),o={name:n.name,path:t,isDirectory:n.isDirectory()};n.isDirectory()&&(o.children=await U$(t)),r.push(o)}return r.sort(((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)))}function B$(e,t="",r=!0){const n=[`${t}${r?"└── ":"├── "}${e.isDirectory?`${e.name}/`:e.name}`],o=e.children;if(o?.length){const e=t+(r?" ":"│ ");o.forEach(((t,r)=>{const s=r===o.length-1;n.push(...B$(t,e,s))}))}return n}async function W$(e){if(!await(0,xo.access)(e,xo.constants.R_OK).then((()=>!0),(()=>!1)))return"(No notes directory yet - will be created when you write your first note)";const t=await U$(e);return 0===t.length?"(Notes directory is empty)":t.flatMap(((e,r)=>B$(e,"",r===t.length-1))).join("\n")}async function H$(e,t){return W$(s.join(e,"agent-notes",t))}async function q$(e){return W$(s.join(e,"agent-notes","shared"))}j$.IN_FLIGHT_SAVE_DISPOSE_TIMEOUT_MS=3e4,j$.PROXY_TARGET_WIDTH=1920,j$.PROXY_TARGET_FPS=60,j$.PROXY_CRF=17,j$.PROXY_PRESET="veryfast",j$.PROXY_PROFILE_VERSION="render-proxy-h264-all-i-v1",j$.DEFAULT_REFRESH_RATE=60;var z$=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},G$=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const V$=3e3,K$=(0,d.h)("local-exec:request-context"),J$=Symbol("sectionLoadTimedOut");function Z$(e,t){if(void 0===t)return e;let r;const n=new Promise((e=>{r=setTimeout((()=>e(J$)),t)}));return e.catch((()=>{})),Promise.race([e,n]).finally((()=>{clearTimeout(r)}))}class X${async read(e,t){const r=this.inFlight??this.begin(e),n=this.last;if(void 0===n)return r;const o=await Z$(r,t).catch((()=>J$));return o===J$?n.value:o}prefetch(e){void 0===this.inFlight&&this.begin(e).catch((()=>{}))}begin(e){const t=e();this.inFlight=t;const r=()=>{this.inFlight===t&&(this.inFlight=void 0)};return t.then((e=>{this.last={value:e},r()}),r),t}}async function Q$(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{z$(o,(0,D.VI)(e.withName("LocalRequestContextExecutor.getGitStatusForRepoPath")),!1);try{return(await t.exec(e,r,["--no-optional-locks","status","--short","--branch"],{timeout:n,caller:"getGitStatusForRepoPath"})).stdout}catch{return}}catch(e){o.error=e,o.hasError=!0}finally{G$(o)}}async function Y$(e,t,r,n){try{const o=(await t.exec(e,r,["rev-parse","--abbrev-ref","HEAD"],{timeout:n,caller:"getGitBranchForRepoPath"})).stdout.trim();if("HEAD"===o||0===o.length)return;return o}catch{return}}async function eM(e,t,r,n){const o=e=>{let t;const r=new Promise((e=>{t=setTimeout((()=>{e(void 0)}),n)}));return Promise.race([e.catch((()=>{})),r]).finally((()=>{void 0!==t&&clearTimeout(t)}))},[s,i]=await Promise.all([o(Q$(e,t,r,n)),o(Y$(e,t,r,n))]);return{status:s,branchName:i}}async function tM(e,t,r={}){const{projectDir:n,notesSessionId:s,agentNotesEnabled:i,reportProcessWorkingDirectory:a,getSmartModeClassifierAutoModeEnabled:c,devForceNextSmartModeClassifierBlockToken:l,isWorkingDirHomeDir:u,getSandboxEnabled:d,getSandboxSupported:h,getNetworkAllowlistInfo:p,userTerminalHint:f,artifactsFolder:m,secretRedactionEnabled:g,getComputerUseSupported:w,getComputerUseDesktop:y,getMockPromptTime:v}=r,b=y?.(),S=`${o.platform()} ${o.release()}`,k=(0,No.G6)(f),_=v?.(),C=(()=>{try{return(new Intl.DateTimeFormat).resolvedOptions().timeZone??void 0}catch{return}})(),E=n,x=n?`${n}/terminals`:void 0,P=n&&!1!==i?`${n}/agent-notes/shared`:void 0,R=n&&s&&!1!==i?`${n}/agent-notes/${s}`:void 0,I=n?`${n}/agent-transcripts`:void 0,T=!!d&&d(),A=h?.(),$=c?.();let M;if(p)try{const e=await Z$(p(),3e3);e!==J$&&(M=e)}catch{M=void 0}return new Fr.GE({osVersion:S,workspacePaths:t,shell:k,sandboxEnabled:T,projectFolder:E,terminalsFolder:x,agentSharedNotesFolder:P,agentConversationNotesFolder:R,agentTranscriptsFolder:I,timeZone:C,...!1!==a&&{processWorkingDirectory:process.cwd()},artifactsFolder:m,...void 0!==$&&{smartModeClassifierAutoModeEnabled:$},...void 0!==l&&{devForceNextSmartModeClassifierBlockToken:l},...void 0!==_&&{devMockPromptTime:ve.Timestamp.fromDate(_)},...void 0!==g&&{secretRedactionEnabled:g},...void 0!==A&&{sandboxSupported:A},...void 0!==M?.hasDefaults&&{sandboxNetworkHasDefaults:M.hasDefaults},...M?.explicitEntries&&M.explicitEntries.length>0&&{sandboxNetworkExplicitAllowlist:M.explicitEntries},...void 0!==w&&{computerUseSupported:w()},...void 0!==b&&{computerUseDesktop:b},...void 0!==u&&{isWorkingDirHomeDir:u}})}const rM={type:"object",properties:{},additionalProperties:!1};function nM(e,t){return{tools:(!0===t?.internalBrowserProvidersOnly?e.servers.filter((e=>Zn.has(e.serverIdentifier))):e.servers).flatMap((e=>e.tools)).map((e=>new vn.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,...!0===t?.inputSchemaJson?{inputSchemaJson:void 0===e.inputSchema?void 0:JSON.stringify(e.inputSchema)}:{inputSchema:e.inputSchema?ve.Value.fromJson(e.inputSchema):void 0}}))),mcpInstructions:e.servers.flatMap((e=>e.instructions))}}function oM(e,t){const r=!0===t?.slimDescriptors,n=e.servers.map((e=>{const n=e.instructions.map((e=>e.instructions)).filter(Boolean).join("\n"),o=e.tools.map((e=>new vn.E$({toolName:e.toolName,...Nb(e.annotations),...r?{}:{description:e.description,...!0===t?.inputSchemaJson?{inputSchemaJson:void 0===e.inputSchema?void 0:JSON.stringify(e.inputSchema)}:{inputSchema:void 0!==e.inputSchema?ve.Value.fromJson(e.inputSchema):void 0}}})));return!Jn(e.serverIdentifier)||!0!==t?.alwaysExposeVirtualMcpAuthTool&&"needsAuth"!==e.status||o.some((e=>e.toolName===iT))||o.push(new vn.E$({toolName:iT,...r?{}:{description:aT,...!0===t?.inputSchemaJson?{inputSchemaJson:JSON.stringify(rM)}:{inputSchema:ve.Value.fromJson(rM)}}})),new vn.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,serverUseInstructions:n||void 0,tools:o})}));return new vn.U_({enabled:!0,mcpDescriptors:n})}function sM(e){const t=e?.trim();return t||void 0}function iM(e,t){const r=function(e){return sM(e.serverIdentifier)}(e);if(r)return r;const n=sM(e.serverName);return n?t.get(n)??n:void 0}class aM{constructor(e){this.mcpLease=e}async getState(e){const[t,r]=await Promise.all([this.mcpLease.getTools(e).catch((t=>(K$.warn(e,"Error fetching MCP tools",{error:t}),[]))),this.mcpLease.getInstructions(e).catch((t=>(K$.warn(e,"Error fetching MCP instructions",{error:t}),[])))]);return function(e,t,r,n=!1){const o=new Map;for(const t of e)o.has(t.providerIdentifier)||o.set(t.providerIdentifier,t.clientKey);const s=t.map((e=>iM(e,o))).filter((e=>Boolean(e))),i=[...new Set([...e.map((e=>e.clientKey)),...s,...Array.from(r?.entries()??[]).filter((([,e])=>"connected"!==e.status)).map((([e])=>e))])];if(n&&void 0!==r){const e=new Map(Array.from(r.keys(),((e,t)=>[e,t])));i.sort(((t,r)=>(e.get(t)??e.size)-(e.get(r)??e.size)))}return{servers:i.map((n=>{const s=e.filter((e=>e.clientKey===n));return{serverName:s[0]?.providerIdentifier??n,serverIdentifier:n,plugin:s[0]?.plugin,marketplace:s[0]?.marketplace,tools:s,instructions:t.filter((e=>iM(e,o)===n)),status:r?.get(n)?.status,errorMessage:r?.get(n)?.errorMessage}}))}}(t,r,await async function(e,t){const r=await t.getClients(e).catch((t=>(K$.warn(e,"Error fetching MCP clients",{error:t}),{}))),n=await Promise.all(Object.entries(r).map((async([t,r])=>{const n=await r.getState(e).catch((()=>({kind:"error",message:"Failed to fetch MCP client state"})));return[t,{status:to(n),errorMessage:"error"===n.kind&&void 0!==n.message?n.message:void 0}]})));return new Map(n)}(e,this.mcpLease))}}function cM(e){return new Mc._W({result:{case:"success",value:new Mc.pv({servers:e.servers.map((e=>new Mc.XE({serverName:e.serverName,serverIdentifier:e.serverIdentifier,plugin:e.plugin,marketplace:e.marketplace,tools:e.tools.map((e=>new vn.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?ve.Value.fromJson(e.inputSchema):void 0,metaJson:Xn(e._meta),...Nb(e.annotations)}))),instructions:e.instructions,status:e.status,errorMessage:e.errorMessage})))})}})}class lM{constructor(e,t,r){this.mcpStateAccessor=e,this.ensureMcpServersLoaded=t,this.options=r}async execute(e,t){if(void 0!==t.ruleSubjects&&void 0!==this.options?.serverRuleSubjects)return function(e,t){const r={commandPatterns:t.commandPatterns,serverUrlPatterns:t.serverUrlPatterns},n=[];for(const[t,o]of e){const e=void 0!==o.command?{transport:Mc.zj.STDIO,value:o.command,matched:{command:o.command}}:void 0!==o.url?{transport:Mc.zj.HTTP,value:o.url,matched:{url:o.url}}:void 0;void 0!==e&&n.push(new Mc.XE({serverName:t,serverIdentifier:t,ruleSubject:new Mc.D0({transport:e.transport,...IC(e.matched,r)?{value:e.value}:{}})}))}return new Mc._W({result:{case:"success",value:new Mc.pv({servers:n})}})}(this.options.serverRuleSubjects(),t.ruleSubjects);try{await(this.ensureMcpServersLoaded?.(e,t.serverIdentifiers,{wait:!t.kickOnly}))}catch{}t.refreshPolicy!==Mc.ew.FORCE_IF_MISSING&&t.refreshPolicy!==Mc.ew.FORCE||await(this.mcpStateAccessor.refreshNow?.(e));const r=await this.mcpStateAccessor.getState(e);if(!0===this.options?.filterToRequestedServers&&t.serverIdentifiers.length>0){const e=new Set(t.serverIdentifiers),n=r.servers.filter((t=>e.has(t.serverIdentifier)));if(n.length>0)return cM({...r,servers:n})}return cM(r)}}class uM{constructor(e,t,r,n,o,s,i,a,c={}){this.cursorRulesService=e,this.cloudRulesService=t,this.subagentsService=r,this.repositoryProvider=n,this.grepProvider=o,this.mcpStateAccessor=s,this.gitExecutor=i,this.workspacePaths=a,this.reusedGitInfo=new Map,this.reusedMcpState=new X$,this.reusedAgentSkills=new X$,this.reusedAdminCommandDenylist=new X$,this.cachedWorkspaces=new Map,this.inFlightWorkspaceWarms=new Map;const{projectDir:l,getSmartModeClassifierAutoModeEnabled:u,getAdminCommandDenylist:d,devForceNextSmartModeClassifierBlockToken:h,isWorkingDirHomeDir:p,agentNotesEnabled:f,reportProcessWorkingDirectory:m,createFileWatcher:g,getSandboxEnabled:w,getSandboxSupported:y,getNetworkAllowlistInfo:v,userTerminalHint:b,getMcpFileSystemOptions:S,mcpMetaToolEnabled:k,mcpMetaToolSlimDescriptors:_,mcpInputSchemaJson:C,alwaysExposeVirtualMcpAuthTool:E,getArtifactsFolder:x,secretRedactionEnabled:P,attributionConfigProvider:R,isAttributionDisabledByAdmin:I,getAgentSkills:T,additionalRules:A,getComputerUseSupported:$,getComputerUseDesktop:M,getMockPromptTime:D}=c;this.projectDir=l,this.isWorkingDirHomeDir=p,this.agentNotesEnabled=f??!0,this.reportProcessWorkingDirectory=m??!0,this.getSandboxEnabled=w,this.getSandboxSupported=y,this.getNetworkAllowlistInfo=v,this.getSmartModeClassifierAutoModeEnabled=u,this.getAdminCommandDenylist=d,this.devForceNextSmartModeClassifierBlockToken=h,this.getMockPromptTime=D,this.userTerminalHint=b,this.getMcpFileSystemOptions=S,this.mcpMetaToolEnabled=k??!1,this.mcpMetaToolSlimDescriptors=_??!1,this.mcpInputSchemaJson=C??!1,this.alwaysExposeVirtualMcpAuthTool=E??!1,this.getArtifactsFolder=x,this.secretRedactionEnabled=P,this.attributionConfigProvider=R,this.isAttributionDisabledByAdmin=I,this.getAgentSkills=T,this.additionalRules=A??[],this.getComputerUseSupported=$,this.getComputerUseDesktop=M,this.reduceContextHotPath=c.reduceContextHotPath??!1,this.sectionLoadTimeoutMs=c.sectionLoadTimeoutMs,this.reportSectionCompleteness=c.reportSectionCompleteness??!1,this.freshSectionWaitMs=c.freshSectionWaitMs,this.onRequestContext=c.onRequestContext,this.mcpFieldsFromCaller=c.mcpFieldsFromCaller??!1,!0!==c.deferWarmup&&this.warm(),void 0!==g&&(this.fileWatcher=g(),this.fileWatcher.onDidChange((e=>{this.onWorkspacePathChanged(e)})),this.fileWatcher.onDidCreate((e=>{this.onWorkspacePathChanged(e)})),this.fileWatcher.onDidDelete((e=>{this.onWorkspacePathChanged(e)})))}warm(){this.warmWorkspaceCaches(),void 0===this.globalCache&&this.rebuildGlobalCache()}onWorkspacePathChanged(e){this.rebuildAllCaches()}getWorkspaceCache(e){return this.cachedWorkspaces.get(e)}warmWorkspaceCaches(){const e=(0,b.q6)();Promise.all(this.workspacePaths.map((t=>this.ensureWorkspaceCacheWarm(e,t))))}ensureWorkspaceCacheWarm(e,t){if(this.cachedWorkspaces.has(t))return Promise.resolve();const r=this.inFlightWorkspaceWarms.get(t);if(void 0!==r)return r;const n=this.warmWorkspaceCache(e,t).finally((()=>{this.inFlightWorkspaceWarms.delete(t)}));return this.inFlightWorkspaceWarms.set(t,n),n}async warmWorkspaceCache(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=z$(r,(0,D.VI)(e.withName("LocalRequestContextExecutor.warmWorkspaceCache")),!1),o=await tc(n.ctx,this.gitExecutor,t),s=o?await ac(n.ctx,this.gitExecutor,o):void 0,i={repoPath:o??void 0,remoteUrl:void 0!==s?cc(s):void 0};if(this.cachedWorkspaces.set(t,i),void 0!==this.freshSectionWaitMs&&void 0!==i.repoPath){const e=i.repoPath;this.gitInfoSection(e).prefetch((()=>eM((0,b.q6)(),this.gitExecutor,e,V$)))}}catch(e){r.error=e,r.hasError=!0}finally{G$(r)}}gitInfoSection(e){let t=this.reusedGitInfo.get(e);return void 0===t&&(t=new X$,this.reusedGitInfo.set(e,t)),t}rebuildAllCaches(){this.cacheDebounceTimeout&&clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=setTimeout((()=>{this.cacheDebounceTimeout=void 0,this.rebuildGlobalCache()}),5e3)}invalidateGlobalCache(){this.globalCache=void 0,this.lastGoodGlobalCache=void 0,this.globalCacheTraceId=void 0}refreshGlobalCache(){this.cacheDebounceTimeout&&(clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=void 0),this.rebuildGlobalCache()}rebuildGlobalCache(){const e={stack:[],error:void 0,hasError:!1};try{const t=(0,b.q6)(),r=z$(e,(0,D.VI)(t.withName("LocalRequestContextExecutor.rebuildGlobalCache")),!1);this.globalCacheTraceId=r.span.spanContext().traceId;const n=this.computeGlobalCache(r.ctx);return this.globalCache=n,(this.reduceContextHotPath||void 0!==this.sectionLoadTimeoutMs||void 0!==this.freshSectionWaitMs)&&n.then((e=>{this.globalCache===n&&(this.lastGoodGlobalCache=e)}),(()=>{this.globalCache===n&&(this.globalCache=void 0)})),n}catch(t){e.error=t,e.hasError=!0}finally{G$(e)}}async computeGlobalCache(e){const t={stack:[],error:void 0,hasError:!1};try{const r=z$(t,(0,D.VI)(e.withName("LocalRequestContextExecutor.computeGlobalCache")),!1),n=AbortSignal.timeout(1e3),o=performance.now(),s={},i=(e,t)=>{const r=performance.now();return t.finally((()=>{s[e]=Math.round(performance.now()-r)}))},[a,c,l,u]=await Promise.all([i("cursorRules",this.cursorRulesService.getAllCursorRules(r.ctx)),i("cloudRule",this.cloudRulesService?this.cloudRulesService.getCloudRule(r.ctx):Promise.resolve(null)),i("codebaseRef",this.repositoryProvider.getCodebaseReference(r.ctx,n).catch((()=>{}))),i("subagents",this.subagentsService?this.subagentsService.getAllSubagents().catch((()=>[])):Promise.resolve([]))]),d=Math.round(performance.now()-o);return d>1e3&&K$.warn(r.ctx,"computeGlobalCache: slow",{totalMs:d,...s,ruleCount:a.length}),{rules:[...this.additionalRules,...a],cloudRule:c,codebaseReference:l,customSubagents:u}}catch(e){t.error=e,t.hasError=!0}finally{G$(t)}}dispose(){this.cacheDebounceTimeout&&(clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=void 0),this.fileWatcher&&(this.fileWatcher.dispose(),this.fileWatcher=void 0),this.globalCache=void 0,this.lastGoodGlobalCache=void 0}async collectWorkspaceCaches(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=z$(r,(0,D.VI)(e.withName("LocalRequestContextExecutor.collectWorkspaceCaches")),!1);let o;if(this.grepProvider.getTrackedState)try{o=await this.grepProvider.getTrackedState(this.workspacePaths)}catch{o=void 0}let s=!0,i=!0;return{gitRepos:(await Promise.all(this.workspacePaths.map((async e=>{let r=this.getWorkspaceCache(e);if(void 0===r){if(!t.waitForWorkspaceCache)return s=!1,void this.ensureWorkspaceCacheWarm(n.ctx,e);if(await this.ensureWorkspaceCacheWarm(n.ctx,e),r=this.getWorkspaceCache(e),void 0===r)return void(s=!1)}const a=o?.[e];if(void 0!==a)return void 0!==r.repoPath&&void 0===a.gitStatus&&(i=!1),new Fr.DS({path:r.repoPath,status:a.gitStatus,branchName:a.gitBranchName,remoteUrl:r.remoteUrl,isOriginBacked:Xa(r.remoteUrl)});if(void 0===r.repoPath)return;const c=r.repoPath,{status:l,branchName:u}=void 0===this.freshSectionWaitMs?await eM(n.ctx,t.gitExecutor,c,V$):await this.gitInfoSection(c).read((()=>eM((0,b.q6)(),t.gitExecutor,c,V$)),this.freshSectionWaitMs);return void 0===l&&(i=!1),new Fr.DS({path:r.repoPath,status:l,branchName:u,remoteUrl:r.remoteUrl,isOriginBacked:Xa(r.remoteUrl)})})))).filter((e=>void 0!==e)),gitRepoInfoComplete:s,gitStatusInfoComplete:s&&i}}catch(e){r.error=e,r.hasError=!0}finally{G$(r)}}shareBoundedSectionLoad(e,t,r){if(void 0===this.sectionLoadTimeoutMs)return r();const n=e();if(void 0!==n)return n;const o=r();t(o);const s=()=>{e()===o&&t(void 0)};return o.then(s,s),o}async computeCachedRequestContext(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=z$(n,(0,D.VI)(e.withName("LocalRequestContextExecutor.computeCachedRequestContext")),!1),s=this.projectDir,i=async()=>{const e={stack:[],error:void 0,hasError:!1};try{const t=z$(e,(0,D.VI)(o.ctx.withName("LocalRequestContextExecutor.computeCachedRequestContext.getGlobalData")),!1);if(this.globalCacheTraceId&&t.span.setAttribute("cacheTraceId",this.globalCacheTraceId),!this.reduceContextHotPath&&void 0===this.freshSectionWaitMs){if(void 0===this.globalCache){const e=this.computeGlobalCache(o.ctx);this.globalCache=e,e.catch((()=>{this.globalCache===e&&(this.globalCache=void 0)})),void 0!==this.sectionLoadTimeoutMs&&e.then((t=>{this.globalCache===e&&(this.lastGoodGlobalCache=t)}),(()=>{}))}return this.globalCache}return void 0!==this.lastGoodGlobalCache?this.lastGoodGlobalCache:this.globalCache??this.rebuildGlobalCache()}catch(t){e.error=t,e.hasError=!0}finally{G$(e)}},a=performance.now(),c={},l=(e,t)=>{const r=performance.now();return t.finally((()=>{c[e]=Math.round(performance.now()-r)}))},u=e=>Z$(e,this.sectionLoadTimeoutMs),d=(e,t,r)=>this.shareBoundedSectionLoad(e,t,r),h=this.freshSectionWaitMs,p=(e,t)=>void 0===h?t():e.read(t,h),f=void 0===h?o.ctx:(0,b.q6)(),[m,g,w,{gitRepos:y,gitRepoInfoComplete:v,gitStatusInfoComplete:S},k,_,C,E,x,P]=await Promise.all([l("globalCache",u(i())),l("mcpState",this.mcpFieldsFromCaller?Promise.resolve({servers:[]}):u(p(this.reusedMcpState,(()=>d((()=>this.inFlightMcpState),(e=>{this.inFlightMcpState=e}),(()=>this.mcpStateAccessor.getState(f))))))),l("env",tM(o.ctx,this.workspacePaths,{projectDir:s,notesSessionId:t.notesSessionId,agentNotesEnabled:this.agentNotesEnabled,reportProcessWorkingDirectory:this.reportProcessWorkingDirectory,getSmartModeClassifierAutoModeEnabled:this.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:this.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:this.getMockPromptTime,isWorkingDirHomeDir:this.isWorkingDirHomeDir,getSandboxEnabled:this.getSandboxEnabled,getSandboxSupported:this.getSandboxSupported,getNetworkAllowlistInfo:this.getNetworkAllowlistInfo,userTerminalHint:this.userTerminalHint,artifactsFolder:this.getArtifactsFolder?.(o.ctx),secretRedactionEnabled:this.secretRedactionEnabled,getComputerUseSupported:this.getComputerUseSupported,getComputerUseDesktop:this.getComputerUseDesktop})),l("git",this.collectWorkspaceCaches(o.ctx,{waitForWorkspaceCache:!0===t.waitForWorkspaceCache,gitExecutor:r})),l("conversationNotes",this.agentNotesEnabled&&s&&t.notesSessionId?H$(s,t.notesSessionId):Promise.resolve(void 0)),l("sharedNotes",this.agentNotesEnabled&&s?q$(s):Promise.resolve(void 0)),l("mcpFileSystemOptions",this.getMcpFileSystemOptions?this.getMcpFileSystemOptions(o.ctx,{timeoutMs:3e3}):Promise.resolve(void 0)),l("attribution",this.isAttributionDisabledByAdmin?this.isAttributionDisabledByAdmin().catch((()=>!0)):Promise.resolve(!1)),l("agentSkills",u(p(this.reusedAgentSkills,(()=>d((()=>this.inFlightAgentSkills),(e=>{this.inFlightAgentSkills=e}),(()=>this.getAgentSkills?this.getAgentSkills(f):Promise.resolve([]))))))),l("adminCommandDenylist",u(p(this.reusedAdminCommandDenylist,(()=>d((()=>this.inFlightAdminCommandDenylist),(e=>{this.inFlightAdminCommandDenylist=e}),(()=>this.getAdminCommandDenylist?this.getAdminCommandDenylist():Promise.resolve(void 0)))))))]),R=m===J$,I=g===J$,T=x===J$,A=P===J$,$=R?this.lastGoodGlobalCache??{rules:[...this.additionalRules],cloudRule:null,codebaseReference:void 0,customSubagents:[]}:m,M=I?{servers:[]}:g,O=T?[]:x,F=A?void 0:P;(R||I||T||A)&&K$.warn(o.ctx,"computeCachedRequestContext: section load timed out",{timeoutMs:this.sectionLoadTimeoutMs,rulesAndSubagents:R,mcpState:I,agentSkills:T,adminCommandDenylist:A});const N=performance.now()-a;for(const[e,t]of Object.entries(c))o.span.setAttribute(`requestContext.timing.${e}Ms`,t);o.span.setAttribute("requestContext.timing.totalMs",Math.round(N)),N>1e3&&K$.warn(o.ctx,"computeCachedRequestContext: slow parallel data collection",{durationMs:Math.round(N),...c});const L=this.mcpMetaToolEnabled?oM(M,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,slimDescriptors:this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}):void 0,j=this.attributionConfigProvider?.get(),U=!E&&(j?.attribution?.attributeCommitsToAgent??!0),B=!E&&(j?.attribution?.attributePRsToAgent??!0),W=new Fr.bb({rules:$.rules,env:w,gitRepos:y,gitRepoInfoComplete:v,repositoryInfo:$.codebaseReference?[{relativeWorkspacePath:$.codebaseReference.relativeWorkspacePath,repoName:$.codebaseReference.repoName,repoOwner:$.codebaseReference.repoOwner,isTracked:$.codebaseReference.isTracked,isLocal:$.codebaseReference.isLocal,orthogonalTransformSeed:$.codebaseReference.orthogonalTransformSeed,pathEncryptionKey:$.codebaseReference.pathEncryptionKey}]:[],...nM(M,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}),conversationNotesListing:k,sharedNotesListing:_,customSubagents:$.customSubagents,mcpFileSystemOptions:C,mcpMetaToolOptions:L,supportsMcpAuth:!0,commitAttributionMessage:U?"enabled":void 0,prAttributionMessage:B?"enabled":void 0,agentSkills:O,adminCommandDenylist:F?.rules??[]});return null!==$.cloudRule&&void 0!==$.cloudRule&&(W.cloudRule=$.cloudRule),this.reportSectionCompleteness&&(W.rulesInfoComplete=!R,W.customSubagentsInfoComplete=!R,W.agentSkillsInfoComplete=!T,W.mcpInfoComplete=!I,W.mcpFileSystemInfoComplete=this.mcpMetaToolEnabled||void 0!==C,W.envInfoComplete=!0,W.gitStatusInfoComplete=S),W}catch(e){n.error=e,n.hasError=!0}finally{G$(n)}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{this.onRequestContext?.();const n=z$(r,(0,D.VI)(e.withName("LocalRequestContextExecutor.execute")),!1);n.span.setAttribute("enableCaching",void 0!==this.fileWatcher),n.span.setAttribute("hasGlobalCache",!!this.globalCache);try{const e=this.gitExecutor.forRequest?.()??this.gitExecutor,r=await this.computeCachedRequestContext(n.ctx,t,e);return new Fr._G({result:{case:"success",value:new Fr.yW({requestContext:r})}})}catch(e){return e instanceof Error||"string"==typeof e?n.span.recordException(e):n.span.recordException(Cc(e)),new Fr._G({result:{case:"error",value:new Fr.nf({error:e instanceof Error?e.message:String(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{G$(r)}}}function dM(e){return 0!==e.timeout?e.timeout:e.isBackground||e.timeoutBehavior===fe._d.BACKGROUND||void 0!==e.hardTimeout&&e.hardTimeout>0?0:3e4}var hM=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class pM{constructor(e,t,r,n){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r}buildResultFromExit(e){return 0===(e.exitCode??-1)?new fe.W4({result:{case:"success",value:new fe.QR({...e,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:hs(e.sandboxPolicy)}):new fe.W4({result:{case:"failure",value:new fe.xC({...e,aborted:void 0!==e.abortReason,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:hs(e.sandboxPolicy)})}async executeWithPolicy(e,t,r,n,o){const s=Date.now(),i=new AbortController,a=e.signal?AbortSignal.any([e.signal,i.signal]):i.signal,c=setTimeout((()=>{i.abort()}),n);try{let n,l,u,d="",h="",p=null;const f=o?{perUser:o}:void 0;for await(const o of this.coreExecutor.execute(e,{command:t.command,workingDirectory:r,signal:a,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:f,fileOutputThresholdBytes:t.fileOutputThresholdBytes,pipeStdin:!1}))"stdout"===o.type?d+=o.data:"stderr"===o.type?h+=o.data:"exit"===o.type&&(p=null!=o.code?0|o.code:null,l=o.outputLocation,n=o.aborted?a.aborted?i.signal.aborted&&a.reason===i.signal.reason?fe.Lv.TIMEOUT:fe.Lv.USER_ABORT:fe.Lv.UNSPECIFIED:void 0,u=Oy(o.localExecutionTimeMs));clearTimeout(c);const m=Date.now()-s,g={command:t.command,workingDirectory:r,exitCode:void 0!==n?-1:p??-1,signal:void 0!==n?"SIGTERM":"",abortReason:n,stdout:d,stderr:h,executionTime:m,localExecutionTimeMs:u,sandboxPolicy:o,outputLocation:l};return this.buildResultFromExit(g)}catch(s){return clearTimeout(c),i.signal.aborted&&!e.signal.aborted?new fe.W4({result:{case:"timeout",value:new fe.eG({command:t.command,workingDirectory:r,timeoutMs:n})},sandboxPolicy:hs(o)}):e.signal.aborted?new fe.W4({result:{case:"rejected",value:new fe.pZ({command:t.command,workingDirectory:r,reason:"Command aborted"})},sandboxPolicy:hs(o)}):new fe.W4({result:{case:"spawnError",value:new fe.mJ({command:t.command,workingDirectory:r,error:s instanceof Error?s.message:"Unknown error"})},sandboxPolicy:hs(o)})}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,D.VI)(e.withName("LocalShellExecutor.execute")),!1).ctx;(0,D.HF)(n,"LocalShellExecutor.execute");const o=t.command,s=t.requestedSandboxPolicy?ds(t.requestedSandboxPolicy):void 0,i=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),a=dM(t),c=(0,ts.o1)(i);if(!t.parsingResult)return new fe.W4({result:{case:"spawnError",value:new fe.mJ({command:o,workingDirectory:c,error:"Parsing result is required"})}});let l;if(Oo(t)){const e=await this.permissionsService.shouldEnforceShellInvariantBlocks(n,{workingDirectory:c,skipUnsafeWorkingDirectoryBlock:!0,command:o,parsingResult:t.parsingResult,toolCallId:t.toolCallId,resolveSkippedApprovalPolicy:!0},s);if("block"===e.kind)return new fe.W4({result:rd(o,c,e.reason)});l=e.policy??s}else{const e=await this.permissionsService.shouldBlockShellCommand(n,o,{workingDirectory:c,timeout:a,parsingResult:t.parsingResult,toolCallId:t.toolCallId,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Mo(t)},s);if("block"===e.kind)return new fe.W4({result:rd(o,c,e.reason)});l=e.policy}return l=await $c(l,{command:o,workingDirectory:c,parsingResult:t.parsingResult,permissionsService:this.permissionsService,ignoreService:this.ignoreService}),this.executeWithPolicy(n,t,i,a,l)}catch(e){r.error=e,r.hasError=!0}finally{hM(r)}}}var fM=r("../proto/dist/generated/agent/v1/shell_allowlist_precheck_exec_pb.js");class mM{constructor(e){this.permissionsService=e}async execute(e,t){const r=t.parsingResult??new fe.HO,n=await this.permissionsService.isShellCommandFullyAllowlisted(e,t.command,{workingDirectory:t.workingDirectory,parsingResult:r,classifierResult:t.classifierResult,toolCallId:t.toolCallId});return new fM.e({allowlisted:n})}}class gM{constructor(e){this.shellStreamExecutor=e}async execute(e,t,r){return""===t.toolCallId.trim()?new fe.jK({status:fe.iA.NOT_FOUND}):this.shellStreamExecutor.forceBackgroundByToolCallId(e,t.toolCallId)}}var wM=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const yM=(0,d.h)("local-exec:shell-stream");class vM{constructor(e,t){this.iterator=e,this.timeoutMs=t,this.pendingPromise=null,this.stopPromise=new Promise((e=>{this.stopResolve=e}))}stop(e){return void 0===this.stopReason&&(this.stopReason=e,this.stopResolve?.(),!0)}get timedOut(){return"background"===this.stopReason?.kind&&this.stopReason.reason===fe.Jg.TIMEOUT}get backgroundRequested(){return"background"===this.stopReason?.kind}get backgroundReasonValue(){return"background"===this.stopReason?.kind?this.stopReason.reason:void 0}get stopReasonValue(){return this.stopReason}async*iterate(){this.timer=setTimeout((()=>{this.stop({kind:"background",reason:fe.Jg.TIMEOUT})}),this.timeoutMs);try{for(;;){if(void 0!==this.stopReason)return;this.pendingPromise=this.iterator.next();const e=await Promise.race([this.pendingPromise.then((e=>({kind:"result",result:e}))),this.stopPromise.then((()=>({kind:"stopped"})))]);if("stopped"===e.kind)return;if(this.pendingPromise=null,e.result.done)return;yield e.result.value}}finally{clearTimeout(this.timer)}}requestBackground(){return this.stop({kind:"background",reason:fe.Jg.USER_REQUEST})}abort(){this.stop({kind:"abort"})}getHandoffIterator(){if(this.pendingPromise){const e=this.pendingPromise;this.pendingPromise=null;let t=!1;return{next:async()=>t?this.iterator.next():(t=!0,e)}}return this.iterator}}function bM(){let e=()=>{};return{promise:new Promise((t=>{e=t})),resolve:e}}class SM{constructor(e,t,r,n){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r,this.backgroundShellManager=n,this.activeForegroundExecutions=new Map,this.pendingShells=new Map}hasForegroundWork(){return this.activeForegroundExecutions.size>0||this.pendingShells.size>0}async forceBackgroundByToolCallId(e,t){const r=this.pendingShells.get(t),n=void 0===r||r.awaitingApproval?this.activeForegroundExecutions.get(t):await async function(e,t){const[r,n]=e.withCancel();try{return await Promise.race([t.registered.promise,(0,b.uk)(r).then((()=>{}))])}finally{n()}}(e,r),o=n?.requestBackground();return o?new fe.jK({status:fe.iA.ACCEPTED,shellResult:o}):new fe.jK({status:fe.iA.NOT_FOUND})}pendingFrom(e){return{execute:(t,r,n)=>this.whilePending(r,(()=>e.get(re).execute(t,r,n)))}}execute(e,t){return this.whilePending(t,(r=>this.run(e,t,r)))}async*whilePending(e,t){let r=this.pendingShells.get(e.toolCallId);void 0===r&&(r={awaitingApproval:!1,registered:bM()},""!==e.toolCallId&&e.timeoutBehavior===fe._d.BACKGROUND&&this.pendingShells.set(e.toolCallId,r));try{yield*t(r)}finally{this.settle(e.toolCallId,r,void 0)}}settle(e,t,r){this.pendingShells.get(e)===t&&this.pendingShells.delete(e),t.registered.resolve(r)}async*run(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{e.signal?.throwIfAborted(),function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(n,(0,D.VI)(e.withName("LocalShellStreamExecutor.execute")),!1);const o=t.command;let s=t.requestedSandboxPolicy?ds(t.requestedSandboxPolicy):void 0;const i=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),a=dM(t),c=(0,ts.o1)(i),l=Date.now(),u=performance.now(),d=new fe.HO(qo(o).structured),h=Cs({command:o,parsingResult:d,blockedCommands:t.adminCommandDenylist});if(void 0!==h)return void(yield new fe.FI({event:{case:"rejected",value:new fe.pZ({command:o,workingDirectory:c,reason:h})}}));const p=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:c,skipUnsafeWorkingDirectoryBlock:!0,command:o,parsingResult:d,toolCallId:t.toolCallId,resolveSkippedApprovalPolicy:Oo(t)},s);if("block"===p.kind)return"permissionsConfig"===p.reason.type?void(yield new fe.FI({event:{case:"permissionDenied",value:new fe.jn({command:o,workingDirectory:c,error:"Command blocked by permissions configuration",isReadonly:p.reason.isReadonly??!1})}})):void(yield new fe.FI({event:{case:"rejected",value:new fe.pZ({command:o,workingDirectory:c,reason:td(p.reason)})}}));if(yM.info(e,"Shell stream: approval gate reached",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,hasSmartModeApproval:void 0!==t.smartModeApproval,hasSmartModeApprovalReason:void 0!==t.smartModeApproval?.reason,hasSmartModeApprovalRequestId:void 0!==t.smartModeApproval?.requestId,requestedPolicyType:s?.type??"undefined",parserCommandCount:d.executableCommands.length,classifierCommandCount:t.classifierResult?.commands.length??0,commandLength:o.length}),Oo(t)){const r=p.policy??s;yM.info(e,"Shell stream: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:s?.type??"undefined",effectivePolicyType:r?.type??"undefined"}),s=r}else{r.awaitingApproval=!0;const n=await this.permissionsService.shouldBlockShellCommand(e,o,{workingDirectory:c,timeout:a,parsingResult:d,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Mo(t),onApprovalRequested:()=>{r.registered.resolve(void 0),r.registered=bM()}},s);if(r.awaitingApproval=!1,"block"===n.kind){if(yM.info(e,"Shell stream: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:n.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),"permissionsConfig"===n.reason.type)return void(yield new fe.FI({event:{case:"permissionDenied",value:new fe.jn({command:o,workingDirectory:c,error:"Command blocked by permissions configuration",isReadonly:n.reason.isReadonly??!1})}}));const r=td(n.reason);return void(yield new fe.FI({event:{case:"rejected",value:new fe.pZ({command:o,workingDirectory:c,reason:r})}}))}s=n.policy,yM.info(e,"Shell stream: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:s.type})}s=await $c(s,{command:o,workingDirectory:c,parsingResult:d,permissionsService:this.permissionsService,ignoreService:this.ignoreService}),yield new fe.FI({event:{case:"start",value:new fe.tD({sandboxPolicy:hs(s)})}});const f=t.timeoutBehavior===fe._d.BACKGROUND,m=f&&!t.closeStdin&&void 0===t.smartModeApproval,g=new AbortController,w=f?g.signal:e.signal?AbortSignal.any([e.signal,g.signal]):g.signal,y=!0,v=s?{perUser:s}:void 0,b=this.coreExecutor.execute(e,{command:o,workingDirectory:i,signal:w,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:v,fileOutputThresholdBytes:t.fileOutputThresholdBytes,pipeStdin:m,showElapsedTime:y});let S;f||(S=setTimeout((()=>g.abort()),a));const k=f?new vM(b[Symbol.asyncIterator](),a):null;let _,C,E,x="",P=!1,R=!1;const I=t.toolCallId&&k?{requestBackground:()=>{if(k.requestBackground())return E=E??this.backgroundShellManager.generateShellId(),new fe.W4({result:{case:"success",value:new fe.QR({shellId:E,pid:C,command:o,workingDirectory:c,msToWait:Oy(performance.now()-u),backgroundReason:fe.Jg.USER_REQUEST,interleavedOutput:x})}})}}:void 0;t.toolCallId&&I&&this.activeForegroundExecutions.set(t.toolCallId,I),this.settle(t.toolCallId,r,I);const T=()=>{t.toolCallId&&this.activeForegroundExecutions.get(t.toolCallId)===I&&this.activeForegroundExecutions.delete(t.toolCallId)},A=()=>{k&&!k.backgroundRequested&&(g.abort(),k.abort())};let $;k&&e.signal&&(e.signal.aborted?A():e.signal.addEventListener("abort",A,{once:!0}));const M=t.hardTimeout;void 0!==M&&M>0&&($=setTimeout((()=>{void 0!==E?this.backgroundShellManager.abort(E)||g.abort():(P=!0,g.abort(),k?.abort())}),M));const O=k?.iterate()??b;try{for await(const r of O)if("stdout"===r.type)x+=r.data,yield new fe.FI({event:{case:"stdout",value:new fe.o0({data:r.data})}});else if("stderr"===r.type)x+=r.data,yield new fe.FI({event:{case:"stderr",value:new fe.Db({data:r.data})}});else if("stdin_ready"===r.type)_=r.stdin,C=r.pid;else if("exit"===r.type){let n;R=!0,r.aborted&&(n=e.signal?.aborted?fe.Lv.USER_ABORT:k?.timedOut||g.signal.aborted?fe.Lv.TIMEOUT:fe.Lv.USER_ABORT),yield new fe.FI({event:{case:"exit",value:new fe.vb({code:(r.code??-1)>>>0,cwd:await this.coreExecutor.getCwd(t.conversationId),outputLocation:r.outputLocation,aborted:r.aborted,abortReason:n,localExecutionTimeMs:Oy(r.localExecutionTimeMs)})}})}}catch(r){if(!(r instanceof No.SandboxUnsupportedError))throw r;const n=s?.type??"unknown";return yM.debug(e,"Shell stream: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:n,reason:r.reason}),void(yield new fe.FI({event:{case:"sandboxUnsupported",value:new fe.rI({command:o,workingDirectory:c,sandboxPolicyType:n,reason:r.reason??r.message,isReadonly:"workspace_readonly"===n})}}))}finally{clearTimeout(S),k?.backgroundRequested||clearTimeout($),T(),!k||k.backgroundRequested||R||g.abort(),e.signal?.removeEventListener("abort",A)}if(k?.backgroundRequested&&!P){const r=E??this.backgroundShellManager.generateShellId();E=r;const n=k.backgroundReasonValue===fe.Jg.USER_REQUEST?fe.Jg.USER_REQUEST:fe.Jg.TIMEOUT,s=n===fe.Jg.USER_REQUEST?Math.round(performance.now()-u):a;await this.backgroundShellManager.adopt({ctx:e,shellId:r,command:o,workingDirectory:c,toolCallId:t.toolCallId,sandboxPolicy:v,initialOutput:x,stdin:_,pid:C,abortController:g,eventIterator:k.getHandoffIterator(),startTime:l,monotonicStartMs:u,showElapsedTime:y,description:t.description,outputNotification:t.outputNotification,onCleanup:()=>clearTimeout($)}),yield new fe.FI({event:{case:"backgrounded",value:new fe.Y9({shellId:r,command:o,workingDirectory:c,pid:C,msToWait:y?s:void 0,reason:n})}})}else e.signal?.aborted&&void 0!==k?.stopReasonValue?(clearTimeout($),yield new fe.FI({event:{case:"exit",value:new fe.vb({code:4294967295,cwd:await this.coreExecutor.getCwd(t.conversationId),aborted:!0,abortReason:fe.Lv.USER_ABORT})}})):clearTimeout($)}catch(e){n.error=e,n.hasError=!0}finally{wM(n)}}}const kM={kind:"absent"};class _M{constructor(e){this.cells=new Map,this.takenCells=new WeakMap,this.collectedCells=new FinalizationRegistry((e=>{void 0===this.cells.get(e)?.deref()&&this.cells.delete(e)})),this.claims=new Map,this.nextGeneration=0,this.entries=new Po.q({max:1e3,ttl:6e4,ttlResolution:0,perf:e})}begin(e){this.entries.purgeStale();const t=++this.nextGeneration;return this.claims.set(TM(e),t),t}record(e,t,r){if(!this.claim(e,r))return;const n=TM(e);this.entries.set(n,{recorded:t,generation:r}),this.commitGeneration(n,r)}forget(e,t){if(!this.claim(e,t))return;const r=TM(e);this.entries.delete(r),this.commitGeneration(r,t)}end(e,t){this.claim(e,t)}take(e){const t=TM(e),r=this.entries.get(t);if(void 0===r)return;const n=this.entries.getRemainingTTL(t);this.entries.delete(t);let o=this.cells.get(t)?.deref();void 0===o&&(o={committed:r.generation},this.cells.set(t,new WeakRef(o)),this.collectedCells.register(o,t));const s={read:e,recorded:r.recorded,remainingTtlMs:n,generation:r.generation};return this.takenCells.set(s,o),s}restore(e){const t=this.takenCells.get(e);if(void 0===t||t.committed!==e.generation)return;const r=TM(e.read);this.entries.has(r)||!Number.isFinite(e.remainingTtlMs)||e.remainingTtlMs<=0||this.entries.set(r,{recorded:e.recorded,generation:e.generation},{ttl:e.remainingTtlMs})}commitGeneration(e,t){const r=this.cells.get(e)?.deref();void 0!==r&&(r.committed=t)}claim(e,t){const r=TM(e);return this.claims.get(r)===t&&(this.claims.delete(r),!0)}}class CM{constructor(){this.views=new Po.q({max:1e3})}get(e){return this.views.get(e)}set(e,t){this.views.set(e,t)}forget(e){this.views.delete(e)}recordWrite(e,t){if(t.length>Ks)return void this.views.delete(e);const r=(0,ko.createHash)("sha256").update(t).digest("hex");this.views.set(e,{kind:"fingerprint",byteLength:t.length,sha256:r})}recordDelete(e){this.views.set(e,kM)}}async function EM(e,t){if(void 0===e)return!1;try{if("absent"===e.kind)return await IM(t);const r=await RM(t);return void 0===r||r.byteLength!==e.byteLength||r.sha256!==e.sha256}catch{return!1}}async function xM(e,t){if("fingerprint"!==e?.kind)return!1;try{return!await IM(t)}catch{return!1}}class PM{constructor(e,t,r,n,o){this.inner=e,this.reads=t,this.permissionsService=r,this.workspacePath=n,this.views=o}async execute(e,t,r){const n=!0===r?.recordAgentView?(0,ts.o1)(t.path,this.workspacePath):void 0,o=function(e,t){if(""!==e.toolCallId&&void 0===e.offset&&void 0===e.limit)return{toolCallId:e.toolCallId,resolvedPath:(0,ts.o1)(e.path,t)}}(t,this.workspacePath);if(void 0===o){const o=await this.inner.execute(e,t,r);return this.forgetViewReadPast(n,o),o}const s=this.reads.begin(o);try{let i,a;try{i=await Yk(this.permissionsService,o.resolvedPath)}catch{return await this.readAndForget(e,t,r,o,s,n)}if(!1!==i&&"needsApproval"!==i.type)return await this.readAndForget(e,t,r,o,s,n);if(!1!==i){const i=await this.inner.execute(e,t,r),a=await async function(e,t){if("success"===e.result.case&&"content"===e.result.value.output.case)try{return await RM(t)}catch{return}}(i,o.resolvedPath);return this.commit(o,s,i,a,n),i}try{a=await RM(o.resolvedPath)}catch{return await this.readAndForget(e,t,r,o,s,n)}const c=await this.inner.execute(e,t,r);return this.commit(o,s,c,a,n),c}finally{this.reads.end(o,s)}}commit(e,t,r,n,o){let s;if("fileNotFound"===r.result.case?s=kM:void 0!==n&&"success"===r.result.case&&"content"===r.result.value.output.case&&(s={kind:"fingerprint",...n}),void 0===s)return this.reads.forget(e,t),void this.forgetViewReadPast(o,r);this.reads.record(e,s,t),void 0!==o&&this.views?.set(o,s)}async readAndForget(e,t,r,n,o,s){const i=await this.inner.execute(e,t,r);return this.reads.forget(n,o),this.forgetViewReadPast(s,i),i}forgetViewReadPast(e,t){void 0===e||"success"!==t.result.case&&"fileNotFound"!==t.result.case||this.views?.forget(e)}}async function RM(e){try{const t=await(0,xo.stat)(e);if(!t.isFile()||t.size>Ks)return}catch(e){return AM(e)}let t;try{t=await(0,xo.open)(e,function(){const e=Ro.constants;return e.O_RDONLY|(e.O_NONBLOCK??0)}());const r=await t.stat();if(!r.isFile()||r.size>Ks)return;const n=(0,ko.createHash)("sha256");let o=0;const s=Buffer.alloc(65536);for(;o<=Ks;){const{bytesRead:e}=await t.read(s,0,s.length,o);if(0===e)break;o+=e,n.update(s.subarray(0,e))}if(o>Ks)return;return{byteLength:o,sha256:n.digest("hex")}}catch(e){return AM(e)}finally{await(t?.close())}}async function IM(e){try{return await(0,xo.stat)(e),!0}catch(e){if($M(e))return!1;throw e}}function TM({toolCallId:e,resolvedPath:t}){return`${e}\0${t}`}function AM(e){if(!$M(e))throw e}function $M(e){const t=_c(e);return"ENOENT"===t||"ENOTDIR"===t}var MM=r("../proto/dist/generated/agent/v1/web_fetch_allowlist_precheck_exec_pb.js");class DM{constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isWebFetchFullyAllowlisted(e,{url:t.url});return new MM.M({allowlisted:r})}}var OM=r("node:constants");const FM=[".md",".markdown",".mdown",".mkd",".mkdn",".mdx"];function NM(e){const t=e.trim().toLowerCase();return FM.some((e=>t.endsWith(e)))}function LM(e,t){const r=e.trim().toLowerCase().split("win32"===t?/[\\/]/:"/");if(r.some((e=>"."===e||".."===e)))return!1;const[n,o,s,i,a]=r.slice(-5);return r.length>=5&&".cursor"===n&&"projects"===o&&void 0!==s&&""!==s&&"canvases"===i&&void 0!==a&&a.length>11&&a.endsWith(".canvas.tsx")}const jM="win32"===process.platform;process.platform;const UM="\\"===s.sep?"win32":"posix",BM={allowed:!1};class WM extends Error{constructor(e,t){super(t),this.name="SymlinkRefusedError",this.path=e}}function HM(e,{nonBlocking:t}){const r=Ro.constants;let n=e;return"number"==typeof r.O_NOFOLLOW&&(n|=r.O_NOFOLLOW),t&&"number"==typeof r.O_NONBLOCK&&(n|=r.O_NONBLOCK),"number"==typeof r.O_CLOEXEC&&(n|=r.O_CLOEXEC),n}const qM=[20,40,80],zM=new Set(["UNKNOWN","EBUSY"]);async function GM(e,t){try{const[r,n]=await Promise.all([t.stat({bigint:!0}),(0,xo.lstat)(e,{bigint:!0})]);r.dev===n.dev&&r.ino===n.ino&&await(0,xo.unlink)(e)}catch{}}async function VM(e,t,r,{removeOnRefusal:n=!1}={}){let o;try{o=await async function(e,t){try{return await(0,xo.open)(e,HM(t,{nonBlocking:!0}),438)}catch(r){const n=_c(r);if(("EAGAIN"===n||"EWOULDBLOCK"===n)&&await async function(e){try{return(await(0,xo.lstat)(e)).isFile()}catch{return!1}}(e))return await(0,xo.open)(e,HM(t,{nonBlocking:!1}),438);throw r}}(e,t)}catch(t){if(function(e){const t=_c(e);return"ELOOP"===t||"EMLINK"===t||"EPERM"===t&&"number"==typeof Ro.constants.O_NOFOLLOW}(t))throw new WM(e,`Refusing to ${r} through a symlink at ${e}`);throw t}try{let t;try{t=(0,Ro.realpathSync)(e)}catch{throw new WM(e,`Cannot verify canonical path before ${r}: ${e}`)}if(t!==e)throw new WM(e,`Refusing ${r}: ${e} now resolves through a symlinked parent to ${t}`);const n=await o.stat();if(!n.isFile())throw new WM(e,`Refusing to ${r} non-regular file at ${e}`);return{fd:o,stats:n}}catch(t){throw n&&await GM(e,o),await o.close(),t}}var KM=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const JM=(0,d.h)("LocalWriteExecutor"),ZM=(0,h.Pu)("local_exec.write.encoding_check",{description:"Text writes that landed, per encoding detector (mojibake, U+FFFD): whether the written text holds the pattern and holds more of it than the file did, and for a detection what the file held, its extension family, encoding and the machine's Windows code page",labelNames:["detector","outcome","file","ext","encoding","code_page","run_count","delta","before_count","pattern"]}),XM=async(e,t,r,n)=>{const o=setTimeout((()=>{JM.warn(e,`[watchdog, LocalWriteExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function QM(e){return new Error(`Could not create ${e}: directory creation exceeded the path depth and was stopped.`)}async function YM(e){try{return(await(0,xo.stat)(e)).isDirectory()?"directory":"present"}catch(e){if("ENOENT"===_c(e))return"missing";throw e}}async function eD(e,t){const r=[];let n=e;for(let o=0;o<=t;o+=1){const t=await YM(n);if("directory"===t)return r.reverse(),r;if("present"===t)return await(0,xo.mkdir)(n,{recursive:!1}),r.reverse(),r;r.push(n);const o=(0,s.dirname)(n);if(o===n){const t=new Error(`ENOENT: no such file or directory, mkdir '${e}'`);throw t.code="ENOENT",t.syscall="mkdir",t.path=e,t}n=o}throw QM(e)}class tD{constructor(e,t,r,{workspacePaths:n,workspacePath:o,worktreeMainPath:s,projectDir:i,onWriteForAiTracking:a,writeFileMutationGuard:c,toolCallReads:l,agentFileViews:u}){this.fileChangeTracker=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.workspacePaths=n,this.workspacePath=o,this.worktreeMainPath=s,this.projectDir=i,this.onWriteForAiTracking=a,this.writeFileMutationGuard=c,this.toolCallReads=l,this.agentFileViews=u}async execute(e,t,r){if(function(e){if(!e.startsWith("file://"))return!1;try{return(0,Pd.fileURLToPath)(e),!1}catch{return!0}}(t.path))return new FI.v3({result:{case:"error",value:new FI.QM({path:t.path,error:`${t.path} is not a valid file URL. Use an absolute path instead.`})}});const n=(0,ts.o1)(t.path,this.workspacePath),o=this.toolCallReads,s=void 0!==o&&""!==t.toolCallId?o.take({toolCallId:t.toolCallId,resolvedPath:n}):void 0,i=!0===r?.refuseUnreadChanges?this.agentFileViews?.get(n):void 0,a={writeStarted:!1},c=()=>{void 0===s||a.writeStarted||o?.restore(s)};try{const r=await this.executeWithRecord(e,t,n,s?.recorded,i,a);return oD(r)&&c(),r}catch(e){throw c(),e}}async executeWithRecord(e,t,r,n,o,i){const a={stack:[],error:void 0,hasError:!1};try{const c=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(a,(0,D.VI)(e.withName("LocalWriteExecutor.execute")),!1).ctx,l=(t.path,t.fileText),u=t.fileBytes.length>0?t.fileBytes:void 0,d=["assets","agent-tools","swarm-agents"],h=SS(r,d)||void 0!==this.projectDir&&!this.workspacePaths.some((e=>{return t=e,n=r,jM&&(t=t.toLowerCase(),n=n.toLowerCase()),t===n||(t.charAt(t.length-1)!==s.sep&&(t+=s.sep),n.startsWith(t));var t,n}))&&kS(this.projectDir,r,d);if((0,ts.fl)({targetPath:r,workspacePaths:this.workspacePaths,mainWorktreePath:this.worktreeMainPath}))return new FI.v3({result:{case:"error",value:new FI.QM({path:r,error:ts.PS})}});let p,f,m,g,w=!1;try{const e=await(0,xo.stat)(r);if(g=511&e.mode,e.size<=ss){const e=await XM(c,"readText before write",3e3,(()=>Wi(r,t.encodingHint)));p=e.text,f=e.encoding,m=Hw(e)}else w=!0}catch(e){w="ENOENT"!==_c(e)}const y=await NS(r),v=y.resolvedPath;if(t.confineToWorkspace){let e=(await Promise.all(this.workspacePaths.map((e=>(0,xo.realpath)(e).catch((()=>{})))))).filter((e=>void 0!==e));if(0===e.length&&void 0!==this.projectDir){const t=await(0,xo.realpath)(this.projectDir).catch((()=>{}));void 0!==t&&(e=[t])}if(!e.some((e=>(0,ts.BJ)(v,e))))return new FI.v3({result:{case:"error",value:new FI.QM({path:r,error:"downloadPath must stay within the workspace"})}})}const b=async()=>{return await EM(n,v)?qT(r):(t=n,void 0!==(e=o)&&void 0!==t&&e.kind===t.kind&&("absent"===e.kind||"fingerprint"===t.kind&&e.byteLength===t.byteLength&&e.sha256===t.sha256)||!await EM(o,v)?void 0:zT(r));var e,t},S=t.planMode?await XM(c,"checkPlanModeWriteTarget",3e3,(()=>async function(e,t){switch(t.resolution.status){case"resolved":case"newFile":return NM(t.resolvedPath)?{allowed:!0}:await async function(e,t){if(!(LM(t.resolvedPath,UM)||LM(e,UM)&&t.resolvedPath===await async function(e){const t=(0,s.dirname)((0,s.dirname)((0,s.dirname)((0,s.dirname)(e)))),r=await NS(t);if(LS(r.resolution))return(0,s.join)(r.resolvedPath,(0,s.relative)(t,e))}(e)))return BM;if("newFile"===t.resolution.status)return{allowed:!0,singleLink:{kind:"create"}};const r=await async function(e){try{const t=await(0,xo.lstat)(e,{bigint:!0});return t.isFile()&&1n===t.nlink?{kind:"existing",dev:t.dev,ino:t.ino}:void 0}catch{return}}(t.resolvedPath);return void 0===r?BM:{allowed:!0,singleLink:r}}(e,t);case"danglingSymlink":{const e=await async function(e){let t=e;for(let e=0;e<40;e++){let e;try{e=await(0,xo.readlink)(t)}catch(e){const r=_c(e);return"ENOENT"===r||"EINVAL"===r?t:void 0}t=(0,s.resolve)((0,s.dirname)(t),e)}}(t.resolvedPath);return void 0!==e&&NM(e)?{allowed:!0}:BM}case"permissionDenied":case"symlinkLoop":case"unknownError":return BM;default:return t.resolution,BM}}(r,y))):void 0;if(void 0!==S&&!S.allowed)return new FI.v3({result:{case:"rejected",value:new FI.en({path:r,reason:"Cannot edit non markdown files in plan mode"})}});const k=(".cursorignore"===(r.split(s.sep).pop()?.toLowerCase()??"")?{type:"permissionsConfig"}:void 0)??await XM(c,"permissionsService.shouldBlockWrite",3e3,(()=>this.permissionsService.shouldBlockWrite(c,v,l)));if(k){const e=await XM(c,"handleBlockReason",3e3,(()=>ed(k,{onNeedsApproval:async(e,n)=>{const o="fileEdit"!==n?.type||n.isNewFile,s="fileEdit"===n?.type?n.diffString:l,i="fileEdit"===n?.type?n.blockReason:void 0,a=await b();if(void 0!==a)return rD(r,a);const c=await this.pendingDecisionProvider.requestApproval({type:Bw.Write,details:{path:r,reason:e,isNewFile:o,diffString:s,before:p,after:l,blockReason:i},toolCallId:t.toolCallId});return c.approved?null:new FI.v3({result:{case:"rejected",value:new FI.en({path:r,reason:c.reason||""})}})},onUserRejected:e=>new FI.v3({result:{case:"rejected",value:new FI.en({path:r,reason:e||""})}}),onPermissionDenied:(e,t)=>new FI.v3({result:{case:"permissionDenied",value:new FI.U7({path:r,error:e,isReadonly:t?.isReadonly??!1})}})})));if(null!==e)return e}const _=await XM(c,"anotherSpellingRefusal",3e3,(()=>async function(e){const t=(0,s.basename)(e);let r;try{if(!(await(0,xo.stat)(e)).isFile())return;const n=await(0,xo.readdir)((0,s.dirname)(e));if(n.includes(t))return;const o=t.normalize("NFC");if(n.some((e=>e.normalize("NFC")===o)))return;const i=t.toLowerCase(),a=n.filter((e=>e.toLowerCase()===i)),c=o.toLowerCase();r=a.length>0?a:n.filter((e=>e.normalize("NFC").toLowerCase()===c))}catch{return}const n=1===r.length?r[0]:void 0;return void 0===n?`${t} names an existing file that this folder lists under another name, so writing it would replace that file. Nothing was written. List the folder and write the file by its listed name to change it; for a new file, choose a different name.`:`${t} names the existing file ${n}: this volume does not tell names apart by case, so writing it would replace ${n}. Nothing was written. To change that file, write ${n}; for a new file, choose a name no file in this folder has in any case.`}(r)));if(void 0!==_)return new FI.v3({result:{case:"error",value:new FI.QM({path:r,error:_})}});const C=(0,s.dirname)(v);if(await xM(n,C))return rD(r,qT(r));if(await xM(o,C))return rD(r,zT(r));let E,x,P,R;try{E=await XM(c,"mkdir",3e3,(()=>async function(e){const t=function(e){let t=0,r=e;for(;;){const e=(0,s.dirname)(r);if(e===r)return t;t+=1,r=e}}(e),r=t+4;let n=0,o=0,i=await eD(e,t),a=0;for(;ar)throw QM(e);try{await(0,xo.mkdir)(c,{recursive:!1})}catch(r){const n=_c(r);if("EEXIST"===n){if("directory"!==await YM(c))throw r;a+=1;continue}if("ENOENT"===n){const n=(0,s.dirname)(c);if(n===c||"missing"!==await YM(n))throw r;i=await eD(e,t),a=0,o=0;continue}throw r}o+=1,a+=1}return o}(C)))}catch(e){const t=_c(e);return"EACCES"===t||"EPERM"===t?new FI.v3({result:{case:"permissionDenied",value:new FI.U7({path:r,directory:C,operation:"create_directory",error:"Permission denied"})}}):new FI.v3({result:{case:"error",value:new FI.QM({path:r,error:Cc(e)})}})}if(void 0!==u)x=u,P=0;else{const e=await XM(c,"getBufferForWrite",3e3,(()=>qi(r,l,this.workspacePath,t.encodingHint)));x=e.buffer,P=e.lines,R=e.format.encoding}const I=()=>XM(c,"writeFile",3e3,(async()=>{const e=await b();if(void 0!==e)throw new Error(e);let t;c.signal.throwIfAborted(),i.writeStarted=!0,await async function(e,t,r){const n=r?.singleLink,{fd:o}=void 0===n?await VM(e,Ro.constants.O_WRONLY|Ro.constants.O_CREAT,"write"):await async function(e,t){const r="create"===t.kind,n=r?Ro.constants.O_WRONLY|Ro.constants.O_CREAT|Ro.constants.O_EXCL:Ro.constants.O_WRONLY;let o;try{o=await VM(e,n,"write",{removeOnRefusal:r})}catch(t){const r=_c(t);if("EEXIST"===r||"ENOENT"===r)throw new WM(e,`Refusing to write: ${e} was ${"EEXIST"===r?"created":"removed"} after it was checked`);throw t}const{fd:s}=o;try{const r=await s.stat({bigint:!0});if(1n!==r.nlink)throw new WM(e,`Refusing to write: ${e} has ${r.nlink} hard links`);if("existing"===t.kind&&(r.dev!==t.dev||r.ino!==t.ino))throw new WM(e,`Refusing to write: ${e} was replaced after it was checked`);return o}catch(t){throw r&&await GM(e,s),await s.close(),t}}(e,n);try{await async function(e){for(let t=0;;t++)try{return void await e.truncate(0)}catch(e){const r=_c(e);if(t>=qM.length||void 0===r||!zM.has(r))throw e;await(0,Lg.setTimeout)(qM[t])}}(o);const e=function(e){return Buffer.isBuffer(e)?e:Buffer.from(e)}(t);let n=0;for(;n{try{await I()}catch(e){throw T=e,A=!0,e}};try{void 0===this.writeFileMutationGuard?await I():await this.writeFileMutationGuard.runExclusive(v,$)}catch(e){if(void 0!==this.writeFileMutationGuard&&(!A||e!==T))return new FI.v3({result:{case:"error",value:new FI.QM({path:r,error:e instanceof Error?e.message:String(e)})}});if(e instanceof WM)return new FI.v3({result:{case:"permissionDenied",value:new FI.U7({path:r,directory:"",operation:"create_file",error:e.message})}});const t=_c(e);return"EACCES"===t||"EPERM"===t?new FI.v3({result:{case:"permissionDenied",value:new FI.U7({path:r,directory:"",operation:"create_file",error:"Permission denied"})}}):"ENOSPC"===_c(e)?new FI.v3({result:{case:"noSpace",value:new FI.bM({path:r})}}):"EDQUOT"===t?new FI.v3({result:{case:"error",value:new FI.QM({path:r,error:"Agent-store quota exceeded: this write was rejected because the storage quota is full. Nothing was written; your local copy is intact. Delete or truncate files to free space (including resolved *.conflict* files), then retry. Do not retry the same write without freeing space first."})}}):new FI.v3({result:{case:"error",value:new FI.QM({path:r,error:Cc(e)})}})}if(this.fileChangeTracker&&void 0===u&&!h&&!w){const e={...t.toolCallId?{toolCallId:t.toolCallId}:{},...v===r?{}:{writtenPath:v},...void 0===g?{}:{beforeMode:g},...E>0?{createdDirectories:E}:{}};await this.fileChangeTracker.trackChange(r,p,l,e,m)}if(this.onWriteForAiTracking&&void 0===u&&!h){const e=t.toolCallId?{toolCallId:t.toolCallId}:{};try{await this.onWriteForAiTracking({path:r,beforeContent:p,afterContent:l,metadata:e})}catch(e){JM.warn(c,"onWriteForAiTracking failed (write succeeded)",{path:r,error:e instanceof Error?e.message:String(e)})}}const M=x.byteLength;let O;if(void 0!==u||w||h||this.recordEncodingChecks(c,r,p,f,l),t.returnFileContentAfterWrite)try{O=await XM(c,"readText after write",3e3,(()=>Bi(r,t.encodingHint)))}catch{}return new FI.v3({result:{case:"success",value:new FI.j6({path:r,linesCreated:P,fileSize:M,...void 0!==O&&{fileContentAfterWrite:O}})}})}catch(e){a.error=e,a.hasError=!0}finally{KM(a)}}recordEncodingChecks(e,t,r,n,o){try{const i={path:t,encoding:n,pages:(s=yu.pages(),"failed"===s?"none":s)};for(const t of function(e,t,r){return[yl(e,t,r),vl(e,t,r)]}(r,n,o))ZM.increment(e,1,El(t,i))}catch(t){for(const t of dl)ZM.increment(e,1,{detector:t,outcome:"error",file:"unclassified"});JM.warn(e,"encoding check failed (write succeeded)",{error:t instanceof Error?t.message:String(t)})}var s}}function rD(e,t){return new FI.v3({result:{case:"error",value:new FI.QM({path:e,error:t})}})}class nD extends Error{constructor(e){super("stale write refusal"),this.result=e,this.name="StaleWriteRefusal"}}function oD(e){if("error"!==e.result.case)return!1;const{error:t,path:r}=e.result.value;return t===qT(r)||t===zT(r)}const sD=(0,d.h)("local-exec:provider"),iD=new Set,aD=new bd.AsyncLocalStorage;class cD extends Z{getMcpExecutionPolicyDeps(){return{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionStore}}static dropOwnedRequestContextCaches(){for(const e of iD)e.ownedRequestContextExecutor?.invalidateGlobalCache()}static rebuildRequestContextCachesFor(e){for(const t of iD)t.cursorRulesService===e&&t.ownedRequestContextExecutor?.refreshGlobalCache()}constructor(e){super(),this.pendingDecisionStore=e.pendingDecisionStore,this.fileChangeTracker=e.fileChangeTracker,this.gitExecutor=e.gitExecutor,this.ignoreService=e.ignoreService,this.grepProvider=e.grepProvider,this.permissionsService=e.permissionsService,this.workspacePaths=e.workspacePaths,this.worktreeMainPath=e.worktreeMainPath,this.diagnosticsProvider=e.diagnosticsProvider,this.mcpLease=e.mcpLease,this.mcpStateAccessor=e.mcpStateAccessor,this.cursorRulesService=e.cursorRulesService,this.cloudRulesService=e.cloudRulesService,this.subagentsService=e.subagentsService,this.repositoryProvider=e.repositoryProvider,this.projectDir=e.projectDir,this.shellManager=e.shellManager,this._sandboxPolicyResolver=e._sandboxPolicyResolver,this._defaultSandboxPolicy=e._defaultSandboxPolicy??{type:"insecure_none"};const t=e.workspacePaths[0],r=t?function(e){const t=(0,s.join)(e,".cursor/sandbox.json");try{const r=(0,Ro.readFileSync)(t,"utf-8"),n=JSON.parse(r),o=(0,No.$6)(n);return(0,No.l7)(o,e)}catch{return}}(t):void 0,n=e._defaultSandboxPolicySources;this._defaultSandboxPolicySources=r||n?{perUser:n?.perUser,perRepo:r??n?.perRepo,teamAdmin:n?.teamAdmin}:void 0,this.mcpFileOutputThresholdBytes=e.mcpFileOutputThresholdBytes,this.blankSharedPaymentTokensInMcpOutputFiles=!0===e.blankSharedPaymentTokensInMcpOutputFiles,this.backgroundShellFactory=e.backgroundShellFactory,this.backgroundWorkRegistry=e.backgroundWorkRegistry,this.wakeupOwnerConversationId=e.wakeupOwnerConversationId,this.mcpElicitationFactory=e.mcpElicitationFactory,this.createFileWatcher=e.createFileWatcher,this.sharedRequestContextExecutor=e.sharedRequestContextExecutor,this.terminalExecutor=e.terminalExecutor,this.mcpMetaToolEnabled=e.mcpMetaToolEnabled??!1,this.mcpMetaToolSlimDescriptors=e.mcpMetaToolSlimDescriptors??!1,this.mcpInputSchemaJson=e.mcpInputSchemaJson??!1,this.alwaysExposeVirtualMcpAuthTool=e.alwaysExposeVirtualMcpAuthTool??!1,this.enableRecordScreen=e.enableRecordScreen??!1,this.recordScreenArtifactsDir=e.recordScreenArtifactsDir,this.recordScreenDisplay=e.recordScreenDisplay,this.disableRecordScreenRendering=e.disableRecordScreenRendering??!1,this.userTerminalHint=e.userTerminalHint,this.attributionConfigProvider=e.attributionConfigProvider,this.isAttributionDisabledByAdmin=e.isAttributionDisabledByAdmin,this.getAgentSkills=e.getAgentSkills,this.getSmartModeClassifierAutoModeEnabled=e.getSmartModeClassifierAutoModeEnabled,this.getAdminCommandDenylist=e.getAdminCommandDenylist,this.devForceNextSmartModeClassifierBlockToken=e.devForceNextSmartModeClassifierBlockToken,this.getMockPromptTime=e.getMockPromptTime,this.additionalRules=e.additionalRules??[],this.askpassConfig=e.askpassConfig,this.rebuildRequestContextOnRulesChange=!0===e.rebuildRequestContextOnRulesChange;const i=this.terminalExecutor??(0,No.Fn)({env:{CURSOR_AGENT:"1"},userTerminalHint:this.userTerminalHint,isLoginShellEnabled:e.isLoginShellEnabled});let a;if(this.workspacePaths.length>1){const e=this.workspacePaths.map((e=>(0,s.dirname)(e)));a=e.every((t=>t===e[0]))?e[0]:void 0}else a=t;let c=new Xu(i,t??(0,o.homedir)(),this.projectDir,{shellOutputBackpressureOptions:e.shellOutputBackpressureOptions,extraEnvProvider:e.shellExtraEnvProvider,powershellUtf8Console:e.powershellUtf8Console,powershellUtf8ChildEnv:e.powershellUtf8ChildEnv,powershellParseAfterUtf8Switch:e.powershellParseAfterUtf8Switch,powershellWebRequestUtf8:e.powershellWebRequestUtf8,powershellPerLineStateDump:e.powershellPerLineStateDump,encodingSlices:e.encodingSlices,keepBackgroundJobs:e.keepShellBackgroundJobs});e.shellCoreWrapper&&(c=e.shellCoreWrapper(c)),this.askpassConfig&&(c=new Yu(c,this.askpassConfig)),this.shellManager&&(c=new Qu(c,this.shellManager));const l=e.overrideShellExecutor??(!0===e.suppressDefaultShellExecutor?void 0:new pM(this.permissionsService,c,this.ignoreService,this.pendingDecisionStore));void 0!==l&&this.register(WT,Fg(l)),this.register(HT,Fg(new BT(this.permissionsService,this.ignoreService,a??t??this.projectDir)));const u=new _M,d=new CM,h=e.overrideWriteExecutor??new tD(this.fileChangeTracker,this.permissionsService,this.pendingDecisionStore,{workspacePaths:this.workspacePaths,workspacePath:a,worktreeMainPath:this.worktreeMainPath,projectDir:this.projectDir,onWriteForAiTracking:e.onWriteForAiTracking,writeFileMutationGuard:e.writeFileMutationGuard,toolCallReads:u,agentFileViews:d});this.register(GT,function(e){const t=(r={execute:(t,r,n)=>e.execute(t,r,n).then((e=>{if(oD(e))throw new nD(e);return e}))},Fg(r));var r;return{async execute(e,r,n){try{return await t.execute(e,r,n)}catch(e){if(e instanceof nD)return e.result;throw e}}}}(h));const p=e.overrideDeleteExecutor??new Gw(this.pendingDecisionStore,this.fileChangeTracker,this.permissionsService,a,e.onDeleteForAiTracking,d);this.register(VT,Fg(p)),this.register(KT,Fg(new Qw({encodingSlices:e.encodingSlices}))),this.register(JT,new P$);const f=this.mcpStateAccessor??new aM(this.mcpLease),m=e.overrideGrepExecutor??new fC(this.ignoreService,this.grepProvider,this.workspacePaths,{mcpStateAccessor:f,permissionsService:this.permissionsService,useStreamingGrep:e.useStreamingGrep,encodingSlices:e.encodingSlices});this.register(ZT,Fg(m));const g=e.overrideReadExecutor??new PM(new B_(this.permissionsService,a,{mcpStateAccessor:f,useStreamingRead:e.useStreamingRead,pendingDecisionProvider:this.pendingDecisionStore,encodingSlices:e.encodingSlices}),u,this.permissionsService,a,d),w=new eA(g);this.register(tA,w),e.registerRedactedReadExecutor&&this.register(rA,w);const y=e.overrideLsExecutor??new SC(this.permissionsService,this.ignoreService,a);this.register(nA,Fg(y)),this.register(oA,Fg(new zA(a,this.diagnosticsProvider))),e.getCanvasDiagnostics&&this.register(sA,Fg(new LA(e.getCanvasDiagnostics,e.beginCanvasSave))),this.register(ro,Fg(new SA(ou(new TT(this.mcpLease,this.permissionsService,this.pendingDecisionStore,this.projectDir,this.mcpFileOutputThresholdBytes,this.mcpElicitationFactory,e.ensureMcpServersLoaded,{blankSharedPaymentTokens:this.blankSharedPaymentTokensInMcpOutputFiles}),e.encodingSlices,"exec_mcp",(e=>"success"===e.result.case)),(()=>this.get(tA))))),this.register(no,Fg(new AT(this.mcpLease,e.ensureMcpServersLoaded))),this.register(oo,Fg(ou(new $T(this.mcpLease,a||this.projectDir,this.permissionsService,this.workspacePaths,this.pendingDecisionStore,e.ensureMcpServersLoaded,h),e.encodingSlices,"exec_mcp",(e=>"success"===e.result.case)))),this.register(so,Fg(new lM(f,e.ensureMcpServersLoaded,{filterToRequestedServers:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,...void 0===e.mcpServerRuleSubjects?{}:{serverRuleSubjects:e.mcpServerRuleSubjects}})));const v=this.sharedRequestContextExecutor??this.createOwnedRequestContextExecutor(f,t,e),b=Fg({execute:(e,t,r)=>{const n=aD.getStore();return void 0!==n&&(n.ran=!0),v.execute(e,t,r)}});this.register(Dr,{execute:async(t,r,n)=>{const o={ran:!1},s=await aD.run(o,(()=>b.execute(t,r,n)));if("success"!==s.result.case||void 0===s.result.value.requestContext)return s;const i=s.clone();if("success"!==i.result.case)return s;const a=i.result.value.requestContext;if(void 0===a)return i;const c=await f.getState(t),l=nM(c,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson});if(a.tools=l.tools,a.mcpInstructions=l.mcpInstructions,a.mcpMetaToolOptions=this.mcpMetaToolEnabled?oM(c,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,slimDescriptors:this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}):void 0,o.ran&&void 0!==e.getMcpFileSystemOptions||(a.mcpFileSystemOptions=await(e.getMcpFileSystemOptions?.(t))),void 0!==a.env&&(a.env.artifactsFolder=e.getArtifactsFolder?.(t),void 0!==e.getSandboxEnabled&&(a.env.sandboxEnabled=e.getSandboxEnabled()),void 0!==e.getSessionSandboxSupported&&(a.env.sandboxSupported=e.getSessionSandboxSupported())),void 0!==e.getMountedAgentStores&&void 0!==a.env)try{const r=await e.getMountedAgentStores(t);a.env.mountedAgentStores=r.map((e=>e.clone()))}catch{a.env.mountedAgentStores=[],sD.warn(t,"Failed to get mounted agent stores; continuing without prompt inventory")}return i}}),this.backgroundShellExecutor=new vd(this.permissionsService,c,this.ignoreService,this.projectDir,this.backgroundShellFactory,this.backgroundWorkRegistry,this.wakeupOwnerConversationId,e.backgroundShellManager),this.shellRedeliveryCaches=e.shellRedeliveryCaches??{backgroundShell:Og(),shellStream:Og(),writeStdin:Og()},this.register(kA,Fg(this.backgroundShellExecutor,void 0,this.shellRedeliveryCaches.backgroundShell)),this.shellStreamExecutor=new SM(this.permissionsService,c,this.ignoreService,this.backgroundShellExecutor.getManager()),this.register(re,function(e,t,r=Og(t)){return{async*execute(t,n,o){if(!o?.execId)return void(yield*e.execute(t,n,o));const s=Dg(o.execId,n),i=r.get(s);if(i)return void(yield*i.fork());const a=e.execute(t,n,o),c=new Mg(a);r.set(s,c),yield*c.fork()}}}(this.shellStreamExecutor,void 0,this.shellRedeliveryCaches.shellStream)),void 0!==e.agentStoreConflictDrainer&&this.register(CA,new DA(e.agentStoreConflictDrainer)),this.register(EA,new mM(this.permissionsService)),this.register(xA,new I$(this.permissionsService)),this.register(PA,new DM(this.permissionsService));const S=new gM(this.shellStreamExecutor);this.register(RA,Fg(S));const k=!1===e.enableWriteBackgroundShellStdin?new OA((async()=>{throw new Error(e.writeBackgroundShellStdinDisabledReason??"write_shell_stdin is disabled for this session")})):new OA(((e,t)=>this.backgroundShellExecutor.writeStdin(e,t)));if(this.register(_A,Fg(k,void 0,this.shellRedeliveryCaches.writeStdin)),e.computerUseExecutor&&(this.computerUseExecutor=e.computerUseExecutor,this.register(IA,Fg(this.computerUseExecutor)),void 0!==e.computerUseEndTurnExecutor&&this.register(TA,e.computerUseEndTurnExecutor)),this.enableRecordScreen){if(!this.recordScreenArtifactsDir||!this.recordScreenDisplay)throw new Error("recordScreenArtifactsDir and recordScreenDisplay are required when enableRecordScreen is true");this.recordScreenExecutor=new j$({artifactsDir:this.recordScreenArtifactsDir,display:this.recordScreenDisplay,disablePolishedRendering:this.disableRecordScreenRendering,polishedRenderer:e.polishedRecordingRenderer}),this.register(AA,Fg(this.recordScreenExecutor))}}createOwnedRequestContextExecutor(e,t,r){const n=new uM(this.cursorRulesService,this.cloudRulesService,this.subagentsService,this.repositoryProvider,this.grepProvider,e,this.gitExecutor,void 0===r.requestContextWorkspacePaths?this.workspacePaths:[...r.requestContextWorkspacePaths],{projectDir:this.projectDir,isWorkingDirHomeDir:r.requestContextIsWorkingDirHomeDir??(0,ts.yn)(t,(0,o.homedir)()),agentNotesEnabled:r.agentNotesEnabled,reportProcessWorkingDirectory:r.reportProcessWorkingDirectory,sectionLoadTimeoutMs:r.requestContextSectionLoadTimeoutMs,reportSectionCompleteness:r.reportRequestContextSectionCompleteness,freshSectionWaitMs:r.requestContextFreshSectionWaitMs,createFileWatcher:this.createFileWatcher,getSandboxEnabled:r.getSandboxEnabled,getSandboxSupported:r.getSandboxSupported,getNetworkAllowlistInfo:r.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:this.getSmartModeClassifierAutoModeEnabled,getAdminCommandDenylist:this.getAdminCommandDenylist,devForceNextSmartModeClassifierBlockToken:this.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:this.getMockPromptTime,userTerminalHint:this.userTerminalHint,getMcpFileSystemOptions:r.getMcpFileSystemOptions,mcpMetaToolEnabled:this.mcpMetaToolEnabled,mcpMetaToolSlimDescriptors:this.mcpMetaToolSlimDescriptors,mcpInputSchemaJson:this.mcpInputSchemaJson,alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,getArtifactsFolder:r.getArtifactsFolder,secretRedactionEnabled:r.secretRedactionEnabled,attributionConfigProvider:this.attributionConfigProvider,isAttributionDisabledByAdmin:this.isAttributionDisabledByAdmin,getAgentSkills:this.getAgentSkills,additionalRules:this.additionalRules,getComputerUseSupported:()=>void 0!==this.computerUseExecutor,getComputerUseDesktop:r.getComputerUseDesktop,onRequestContext:r.onRequestContext,mcpFieldsFromCaller:!0===r.requestContextMcpFieldsFromOverlay,deferWarmup:!0===r.deferRequestContextWarmup});return!0===r.deferRequestContextWarmup&&(this.requestContextExecutorAwaitingWarmup=n),this.rebuildRequestContextOnRulesChange&&(this.ownedRequestContextExecutor=n,iD.add(this),this.disposeRulesChangeListener=this.cursorRulesService.onDidChangeRules?.((()=>{n.rebuildAllCaches()}))),n}warmRequestContext(){const e=this.requestContextExecutorAwaitingWarmup;this.requestContextExecutorAwaitingWarmup=void 0,e?.warm()}getRecordScreenExecutor(){return this.recordScreenExecutor}getBackgroundShellManager(){return this.backgroundShellExecutor.getManager()}getShellRedeliveryCaches(){return this.shellRedeliveryCaches}hasForegroundShells(){return this.shellStreamExecutor.hasForegroundWork()}withPendingShells(e){return new X(e,[K(re,this.shellStreamExecutor.pendingFrom(e))])}async dispose(){this.requestContextExecutorAwaitingWarmup=void 0,this.rebuildRequestContextOnRulesChange&&(iD.delete(this),this.disposeRulesChangeListener?.(),this.disposeRulesChangeListener=void 0,this.ownedRequestContextExecutor?.dispose(),this.ownedRequestContextExecutor=void 0),this.backgroundShellExecutor.dispose(),this.recordScreenExecutor&&await this.recordScreenExecutor.dispose()}}function lD(e){return e.replace(/\\/g,"/")}function uD(e,t){for(const r of t){const t=lD(r);if(e===t||e.startsWith(`${t}/`))return!0}return!1}var dD;function hD(e,t,r){if(function(e){return Boolean(e.plugin?.trim()||e.pluginId?.trim()||e.marketplaceId?.trim())}(e))return dD.Plugin;const n=lD(e.fullPath);return uD(n,r.builtinDirs)?dD.Builtin:Um(e.fullPath,t).inAgentStore?dD.UserStore:uD(n,r.userDirs)?dD.UserHome:(uD(n,r.workspaceDirs),dD.Workspace)}"function"==typeof SuppressedError&&SuppressedError,function(e){e[e.Builtin=0]="Builtin",e[e.UserStore=1]="UserStore",e[e.UserHome=2]="UserHome",e[e.Workspace=3]="Workspace",e[e.Plugin=4]="Plugin"}(dD||(dD={}));var pD=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const fD=(0,Vs.debuglog)("merged-agent-skills"),mD=(0,d.h)("merged-agent-skills");class gD{constructor(e,t=()=>[],r){this.services=e,this.getDisabledManagedSkillPaths=t,this.getPromptSortContext=r,this.onChangeCallbacks=new Set}async getAllAgentSkills(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,D.VI)(e.withName("MergedAgentSkillsService.getAllAgentSkills")),!1),n=this.services.map((e=>e.getAllAgentSkills(r.ctx).catch((e=>(fD("Failed to load agent skills from service: %s",e instanceof Error?e.message:String(e)),[]))))),o=async()=>{try{return{ok:!0,paths:await this.getDisabledManagedSkillPaths()}}catch(e){return mD.warn(r.ctx,"getDisabledManagedSkillPaths failed; failing closed by dropping all managed skills for this call",{error:e instanceof Error?e.message:String(e)}),{ok:!1}}},[i,a]=await Promise.all([Promise.all(n),o()]),c=i.flat(),l=this.getPromptSortContext?.(),u=Wm(c,l??Lm);let d=u;return a.ok?a.paths.length>0&&(d=u.filter((e=>!function(e,t){if(!e)return!1;const r=e.replace(/\\/g,"/");return t.some((e=>r.endsWith(e)))}(e.fullPath,a.paths)))):d=u.filter((e=>{return!((t=e.fullPath)&&t.replace(/\\/g,"/").includes(wD));var t})),void 0!==l?function(e,t){if(e.length<=1)return e;const r=function(e){const t=[bm(e.userHomeDirectory).dirPath],r=Pm(e.userHomeDirectory,!0).map((e=>e.dirPath)),n=[];for(const t of e.workspacePaths){n.push((0,s.join)(t,".cursor","rules"));for(const e of xm(t,!0))n.push(e.dirPath)}return{builtinDirs:t,userDirs:r,workspaceDirs:n}}(t),n=e.map(((e,n)=>({skill:e,index:n,tier:hD(e,t,r)})));return n.sort(((e,t)=>e.tier-t.tier||e.index-t.index)),n.map((e=>e.skill))}(d,l):d}catch(e){t.error=e,t.hasError=!0}finally{pD(t)}}reload(e){for(const t of this.services)t.reload(e)}scheduleDidChangeSkills(){void 0===this.changeTimer&&(this.changeTimer=setTimeout((()=>{this.changeTimer=void 0;for(const e of Array.from(this.onChangeCallbacks))e()}),gD.CHANGE_COALESCE_MS))}ensureChangeListenersRegistered(){void 0===this.disposeChangeListeners&&(this.disposeChangeListeners=this.services.map((e=>e.onDidChangeSkills((()=>this.scheduleDidChangeSkills())))))}disposeChangeListenersIfUnused(){if(!(this.onChangeCallbacks.size>0||void 0===this.disposeChangeListeners)){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0,void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0)}}onDidChangeSkills(e){return this.onChangeCallbacks.add(e),this.ensureChangeListenersRegistered(),()=>{this.onChangeCallbacks.delete(e),this.disposeChangeListenersIfUnused()}}dispose(){if(void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0),this.onChangeCallbacks.clear(),void 0!==this.disposeChangeListeners){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0}for(const e of this.services)e.dispose()}}gD.CHANGE_COALESCE_MS=1500;const wD=`/${mm.configDir}/${mm.subdir}/`;function yD(e,t){if((e.disabledEnvironments??[]).includes(t))return!1;const r=e.environments??[];return 0===r.length||r.includes(t)}const vD=(0,d.h)("skill-sync-manifest"),bD=".sync-manifest.json",SD=new Set(["EPERM","EBUSY"]),kD=[20,50,100],_D=new Map;async function CD(e,t){try{const r=await(0,xo.readFile)((0,s.join)(e,bD),"utf-8"),n=JSON.parse(r);return function(e){if(!function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e))return!1;const t=e;return"number"==typeof t.version&&"object"==typeof t.skills&&null!==t.skills&&!Array.isArray(t.skills)&&(void 0===t.lastInventoryAt||"number"==typeof t.lastInventoryAt)}(n)?n:(vD.warn(t,"Manifest failed schema validation, resetting",{skillDir:e}),{version:1,skills:{}})}catch(r){return r instanceof Error&&"ENOENT"===_c(r)||vD.debug(t,"Failed to read sync manifest, resetting",{skillDir:e,error:String(r)}),{version:1,skills:{}}}}function ED(e,t,r){e.skills[t]={lastSyncedAt:r}}function xD(e,t){delete e.skills[t]}var PD=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const RD=(0,d.h)("builtin-skills-sync");function ID(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function TD(e){for(const t of Object.keys(e.resources??{}))if(0===t.length||t.includes("\\")||t.includes("\0")||s.posix.isAbsolute(t)||s.posix.normalize(t)!==t||t.split("/").includes("..")||"SKILL.md"===s.posix.basename(t)||!t.endsWith(".md"))throw new Error(`Unsafe managed skill resource path: ${JSON.stringify(t)}`)}function AD(e){const t=rh(e.content),r=ID(t.data)?t.data:{};return nh(`${t.content.trim()}\n`,function(e,t){const r={...t??{},name:e.id,description:e.description};delete r.disabledEnvironments,e.disableModelInvocation?r["disable-model-invocation"]=!0:delete r["disable-model-invocation"],e.environments&&e.environments.length>0?r.environments=e.environments:delete r.environments,e.disabledEnvironments&&e.disabledEnvironments.length>0?r["disabled-environments"]=e.disabledEnvironments:delete r["disabled-environments"];const n={...ID(r.metadata)?r.metadata:{}};return delete n.environments,delete n.disabledEnvironments,delete n["disabled-environments"],Object.keys(n).length>0?r.metadata=n:delete r.metadata,r}(e,r))}async function $D(e,t,r){const n=(0,s.join)(t,r.id),o=(0,s.join)(n,"SKILL.md"),i=r.fileContent,a=Object.keys(r.resources),c=await MD(n);if(a.length>0||c.length>0){const e=new Map([["SKILL.md",i],...Object.entries(r.resources)]),o=new Set(["SKILL.md",...c]);if(o.size===e.size&&[...e.keys()].every((e=>o.has(e)))){let t=!0;for(const[r,o]of e)try{if(await(0,xo.readFile)((0,s.join)(n,...r.split("/")),"utf-8")!==o){t=!1;break}}catch{t=!1;break}if(t)return!1}return await async function(e,t){const r=(0,s.join)(e,t.id),n=await(0,xo.mkdtemp)((0,s.join)(e,`.${t.id}-staging-`)),o=`${n}-backup`;let i=!1;try{await(0,xo.writeFile)((0,s.join)(n,"SKILL.md"),t.fileContent,"utf-8");for(const[e,r]of Object.entries(t.resources)){const t=(0,s.join)(n,...e.split("/"));await(0,xo.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,xo.writeFile)(t,r,"utf-8")}try{await(0,xo.rename)(r,o),i=!0}catch(e){if(!(e instanceof Error)||"ENOENT"!==_c(e))throw e}try{await(0,xo.rename)(n,r)}catch(e){throw i&&(await(0,xo.rename)(o,r),i=!1),e}i&&(await(0,xo.rm)(o,{recursive:!0,force:!0}),i=!1)}finally{await(0,xo.rm)(n,{recursive:!0,force:!0})}}(t,r),!0}try{if(await(0,xo.readFile)(o,"utf-8")===i)return!1}catch(t){t instanceof Error&&"ENOENT"===_c(t)||RD.warn(e,"Unexpected error reading skill file",{skillId:r.id,error:String(t)})}return await(0,xo.mkdir)(n,{recursive:!0}),await(0,xo.writeFile)(o,i,"utf-8"),!0}async function MD(e,t=""){const r=t?(0,s.join)(e,...t.split("/")):e;let n;try{n=await(0,xo.readdir)(r,{withFileTypes:!0})}catch(e){if(e instanceof Error&&"ENOENT"===_c(e))return[];throw e}const o=[];for(const r of n){const n=t?`${t}/${r.name}`:r.name;r.isDirectory()?o.push(...await MD(e,n)):r.isFile()&&r.name.endsWith(".md")&&"SKILL.md"!==n&&o.push(n)}return o}async function DD(e,t){try{return(await(0,xo.readdir)(t,{withFileTypes:!0})).filter((e=>e.isDirectory()&&!e.name.startsWith("."))).map((e=>e.name))}catch(r){return r instanceof Error&&"ENOENT"===_c(r)||RD.warn(e,"Failed to list skills directory, skipping cleanup",{skillDir:t,error:String(r)}),[]}}async function OD(e,t={}){const r={stack:[],error:void 0,hasError:!1};try{const i=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,D.VI)(e.withName("syncBuiltinSkills")),!1).ctx,a=Date.now(),c=t.userHome??(0,o.homedir)(),l=t.skillDir??bm(c).dirPath;await(0,xo.mkdir)(l,{recursive:!0});const[u,d]=await Promise.all([CD(l,i),DD(i,l)]),h=u.lastInventoryAt;(void 0===h||a-h>=864e5)&&(await async function(e,t,r,n){try{const o=await Promise.all(r.map((async e=>{const r=(0,s.join)(t,e),[o,i]=await Promise.all([FD((0,s.join)(r,"SKILL.md")),"canvas"===e?FD((0,s.join)(r,"sdk")):Promise.resolve(!1)]);return{skill_id:e,has_skill_md:o,has_sdk_dir:i,last_synced_at:n.skills[e]?.lastSyncedAt??null}})));RD.info(e,"managed_skills.startup_inventory",{skills_on_disk:o,manifest_present:Object.keys(n.skills).length>0})}catch(t){RD.warn(e,"Failed to emit managed skills startup inventory",{error:String(t)})}}(i,l,d,u),u.lastInventoryAt=a);const p=new Map;for(const e of t.managedSkills??[])(n=e.id)&&n===n.trim()&&!(n.includes("..")||n.includes("/")||n.includes("\\"))?p.set(e.id,e):RD.warn(i,"Skipping managed skill with unsafe id",{skillId:e.id});const f=void 0===t.canvasKit?void 0:km(c,t.canvasKit).dirPath,m=void 0!==f&&await FD((0,s.join)(f,Sm)),g=new Set([...p.keys(),...d,...m?[Sm]:[]]),w=e=>void 0!==f&&e===Sm?f:l,y=e=>void 0!==f&&e===Sm?m:d.includes(e);let v=0,b=0;const S=[];for(const e of g)try{const t=p.get(e),r=u.skills[e],n=r?a-r.lastSyncedAt:0,o=void 0!==r&&n>2592e5,c=void 0!==t&&yD(t,"local"),d=void 0!==t&&!c,h=void 0!==r||y(e),f=w(e);if(t&&!1!==t.enabled&&c)TD(t),f!==l&&await(0,xo.mkdir)(f,{recursive:!0}),await $D(i,f,{id:e,fileContent:AD(t),resources:t.resources??{}})?v++:b++,ED(u,e,a);else if(!1===t?.enabled||d||o){const n=!1===t?.enabled?"enabled_false":d?"environment_ineligible":"grace_expired";await(0,xo.rm)((0,s.join)(f,e),{recursive:!0,force:!0}),xD(u,e),h&&(S.push(e),RD.info(i,"managed_skills.removed",{skill_id:e,reason:n,server_enabled:t?.enabled??null,had_manifest_entry:void 0!==r,last_synced_ms_ago:r?a-r.lastSyncedAt:null}))}else r||ED(u,e,a)}catch(t){RD.warn(i,"Failed to apply skill, will retry next sync",{skillId:e,error:String(t)})}try{await function(e,t){const r=(_D.get(e)??Promise.resolve()).then((()=>async function(e,t){const r=(0,s.join)(e,`${bD}.${process.pid}.${(0,ko.randomBytes)(6).toString("hex")}.tmp`);await(0,xo.mkdir)(e,{recursive:!0});try{await(0,xo.writeFile)(r,JSON.stringify(t,null,2),"utf-8"),await async function(e,t){for(let r=0;;r++)try{return void await(0,xo.rename)(e,t)}catch(e){const t=_c(e),n=kD[r];if(void 0===n||void 0===t||!SD.has(t))throw e;await(0,Nr.cb)(n)}}(r,(0,s.join)(e,bD))}catch(e){throw await(0,xo.rm)(r,{force:!0}).catch((()=>{})),e}}(e,t))),n=r.catch((()=>{}));return _D.set(e,n),n.then((()=>{_D.get(e)===n&&_D.delete(e)})),r}(l,u)}catch(e){!function(e){if(e instanceof Error&&"ENOENT"===_c(e))return!0;const t=String(e);return t.includes("ENOENT")||t.includes("no such file or directory")}(e)?RD.warn(i,"Failed to persist sync manifest",{skillDir:l,error:String(e)}):RD.debug(i,"Skipped persisting sync manifest, path removed concurrently",{skillDir:l,error:String(e)})}return{synced:v,upToDate:b,removed:S}}catch(e){r.error=e,r.hasError=!0}finally{PD(r)}var n}async function FD(e){try{return await(0,xo.stat)(e),!0}catch(e){const t=_c(e);if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}const ND=(0,d.h)("managed-skills-sync");function LD(e,t,r,n,o,s){const i=[],a=e.mcpServers;if(!a)return i;for(const[e,c]of Object.entries(a)){const a=c,l=`plugin-${n}-${e}`,u=e;a.url?i.push({identifier:l,name:u,marketplace:t,marketplaceId:r,pluginName:n,pluginId:o,pluginSource:s,type:"streamableHttp",url:a.url,headers:a.headers,auth:a.auth,tls:a.tls,enabledTools:a.enabledTools,placement:a.placement,projectManaged:!1,pluginManaged:!0}):a.command&&i.push({identifier:l,name:u,marketplace:t,marketplaceId:r,pluginName:n,pluginId:o,pluginSource:s,type:"stdio",command:a.command,args:a.args??[],env:a.env??{},cwd:a.cwd,envFile:a.envFile,enabledTools:a.enabledTools,projectManaged:!1,pluginManaged:!0})}return i}function jD(e){try{const t=new URL(e),r=new URL(t.pathname,t.origin);return r.search=t.search,r.pathname.endsWith("/")&&r.pathname.length>1&&(r.pathname=r.pathname.slice(0,-1)),"/"===r.pathname?r.origin+r.search:r.toString()}catch{return e.toLowerCase().trim()}}class UD{constructor(e){this.pluginsService=e}async getPluginMcpServers(){const e=await this.pluginsService.reload(),t=[];for(const r of e){const e="marketplace"in r.identifier.sourceInfo?r.identifier.sourceInfo.marketplace:void 0,n="marketplaceDbId"in r.identifier.sourceInfo?r.identifier.sourceInfo.marketplaceDbId:void 0,o=r.identifier.sourceInfo.name,s="pluginDbId"in r.identifier.sourceInfo?r.identifier.sourceInfo.pluginDbId:void 0,i=r.mcpConfig;i&&t.push(...LD(i,e,n,o,s,r.identifier.source))}return function(e){const t=[],r=new Set;for(const n of e){if("streamableHttp"!==n.type||!n.url){t.push(n);continue}const e=jD(n.url);r.has(e)||(r.add(e),t.push(n))}return t}(t)}}var BD=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function WD(e,t){return void 0===e?[]:(Array.isArray(e)?e:[e]).map((e=>({...e,userHomeDir:t})))}class HD{constructor(e,t,r,n,o,s){this.workspacePaths=e,this.userHomeDirectory=t,this.getSettings=r,this.marketplaceOptions=n,this.localPluginVariablesLookup=s,this.plugins=[],this._loadFailures=[],this._pluginSetIncomplete=!0,this._retainedFromPreviousLoad=0,this._wasFirstLoad=!0,this.loadedOnce=!1,this._extensionPlugins=new Map,this._extensionPluginOriginalPaths=new Map,this.pluginLogger=o??$p,this.reload()}async getAllEnabledPlugins(){return await this.ensureLoaded(),[...this.plugins]}getLoadFailures(){return[...this._loadFailures]}isPluginSetIncomplete(){return this._pluginSetIncomplete}getLoadDiagnostics(){return{userHomeDirectory:this.userHomeDirectory,pluginsLoaded:this.plugins.length,retainedFromPreviousLoad:this._retainedFromPreviousLoad,wasFirstLoad:this._wasFirstLoad,sourceUnavailable:this._pluginSetIncomplete}}async reload(){return this.loadPromise||(this.loadPromise=this.load().then((async e=>{const t=!this.loadedOnce;let r=[];try{r=await this._reloadExtensionPlugins()}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugins after base load success: ${Cc(e)}`)}const n=e.sourceUnavailable?this._retainPluginsMissingFromPartialLoad(e.plugins):[],o=[...e.plugins,...n],s=new Set(o.map((e=>e.installPath))),i=r.filter((e=>!s.has(e.installPath)));return this.plugins=[...o,...i],e.sourceUnavailable||(this._loadFailures=e.failures),this._pluginSetIncomplete=e.sourceUnavailable,this._retainedFromPreviousLoad=n.length,this._wasFirstLoad=t,this.loadedOnce=!0,this.pluginLogger.log("info",`Plugins reload completed: ${this.plugins.length} plugins loaded (${i.length} extension, ${n.length} retained), ${e.failures.length} failures`),this.plugins})).catch((async e=>{const t=!this.loadedOnce;this.pluginLogger.log("error",`Failed to load plugins: ${e}`),this._pluginSetIncomplete=!0,this._retainedFromPreviousLoad=0,this._wasFirstLoad=t;try{const e=await this._reloadExtensionPlugins(),t=new Set(this.plugins.map((e=>e.installPath)));this.plugins=[...this.plugins,...e.filter((e=>!t.has(e.installPath)))]}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugins after base load failure: ${Cc(e)}`)}return this.loadedOnce=!0,this.plugins})).finally((()=>{this.loadPromise=void 0}))),this.loadPromise}_retainPluginsMissingFromPartialLoad(e){if(!this.loadedOnce)return[];const t=new Set(e.map(im));return this.plugins.filter((e=>"extension"!==e.identifier.source&&void 0===e.loadError&&e.installPath.length>0&&!t.has(im(e))))}async reloadPlugin(e){this.loadPromise&&await this.loadPromise;const t=WD(this.marketplaceOptions,this.userHomeDirectory);if(0===t.length)return;if(!(this.getSettings().loadCursorFirstParty??t.length>0))return;const r=t=>t.pluginDbId===e.pluginDbId,n=e=>"cursor-first-party"===e.identifier.source||"cursor-third-party"===e.identifier.source?e.identifier.sourceInfo:void 0,o=t=>n(t)?.pluginDbId===e.pluginDbId,s=(t,r)=>void 0!==t.pluginDbId?t.pluginDbId===e.pluginDbId:t.pluginName===r?.name&&t.marketplaceName===r?.marketplace;let i,a,c;for(const l of t){let t;try{t=await om({...l,log:l.log??this.pluginLogger,pluginFilter:r})}catch(t){this.pluginLogger.log("error",`reloadPlugin: source load failed for ${e.name}: ${Cc(t)}`);continue}const u=t.plugins.find((e=>o(e)&&void 0===e.loadError));if(void 0!==u){i=u;break}const d=t.plugins.find(o);if(void 0!==d&&void 0===a){const e=n(d);a=d,c=t.failures.find((t=>s(t,e)))}}if(void 0===i){if(void 0!==a){const t=n(a),r={...c??{pluginName:t?.name??e.name,errorMessage:a.loadError??"Plugin load failed",errorType:"unknown",...void 0!==t?.marketplace&&{marketplaceName:t.marketplace}},pluginDbId:e.pluginDbId};this._loadFailures=[...this._loadFailures.filter((e=>!s(e,t))),r]}return}const l=this.plugins.findIndex(o);if(-1===l)this.plugins=[...this.plugins,i];else{const e=[...this.plugins];e[l]=i,this.plugins=e}this.loadedOnce=!0;const u=n(i);return this._loadFailures=this._loadFailures.filter((e=>!s(e,u))),i}async registerExtensionPlugin({path:e,extensionId:t}){const r=(0,s.resolve)(e),n=await(0,xo.realpath)(r);if(!(await(0,xo.stat)(n)).isDirectory())throw new Error(`Extension plugin path is not a directory: ${n}`);const i=o.homedir();if(n.split(s.sep).filter(Boolean).length<3||n===i||"/"===n)throw new Error(`Extension plugin path is too broad (must be a specific subdirectory, not root or home): ${n}`);for(const[e,r]of this._extensionPlugins)if(e!==t&&r.has(n))throw new Error(`Plugin path ${n} is already registered by extension ${e}`);let a=this._extensionPlugins.get(t);if(a||(a=new Map,this._extensionPlugins.set(t,a)),a.has(n))return void this._rememberExtensionPluginOriginalPath({extensionId:t,originalPath:r,canonicalPath:n});const c=(0,s.basename)(n),l=await this._loadExtensionPluginContent(n,t);a.set(n,l),this._rememberExtensionPluginOriginalPath({extensionId:t,originalPath:r,canonicalPath:n}),this.pluginLogger.log("info",`Registered extension plugin: ${c} from ${n} (extension: ${t})`)}async unregisterExtensionPlugin({path:e,extensionId:t}){const r=this._extensionPlugins.get(t);if(!r)return!1;const n=(0,s.resolve)(e);let o;try{o=await(0,xo.realpath)(n)}catch{const e=this._extensionPluginOriginalPaths.get(t);o=e?.get(n)??n}const i=r.delete(o);return 0===r.size?(this._extensionPlugins.delete(t),this._extensionPluginOriginalPaths.delete(t)):i&&this._forgetExtensionPluginOriginalPath(t,o),i&&this.pluginLogger.log("info",`Unregistered extension plugin: ${o} (extension: ${t})`),i}async _loadExtensionPluginContent(e,t){const r=(0,s.basename)(e),n={name:r,localPath:e,extensionId:t},o=await Zf(e,r,{name:r,version:"0.0.0"});return o.displayName&&(n.name=o.displayName),{identifier:{source:"extension",sourceInfo:n},installPath:e,...void 0!==o.displayName&&{displayName:o.displayName},...void 0!==o.description&&{description:o.description},...void 0!==o.authorName&&{authorName:o.authorName},...void 0!==o.logoUrl&&{logoUrl:o.logoUrl},...void 0!==o.version&&{version:o.version},...void 0!==o.homepage&&{homepage:o.homepage},...void 0!==o.repository&&{repository:o.repository},skills:o.skills,rules:o.rules,agents:o.agents,commands:o.commands,mcpConfig:o.mcpConfig??void 0,capabilities:o.capabilities,hooks:o.hooks}}_rememberExtensionPluginOriginalPath(e){let t=this._extensionPluginOriginalPaths.get(e.extensionId);t||(t=new Map,this._extensionPluginOriginalPaths.set(e.extensionId,t)),t.set(e.originalPath,e.canonicalPath)}_forgetExtensionPluginOriginalPath(e,t){const r=this._extensionPluginOriginalPaths.get(e);if(r){for(const[e,n]of r)n===t&&r.delete(e);0===r.size&&this._extensionPluginOriginalPaths.delete(e)}}_getExtensionPluginPaths(){const e=[];for(const[t,r]of this._extensionPlugins)for(const n of r.keys())e.push({canonicalPath:n,extensionId:t});return e}async _reloadExtensionPlugins(){const e=this._getExtensionPluginPaths(),t=[];for(const{canonicalPath:r,extensionId:n}of e)try{const e=await this._loadExtensionPluginContent(r,n),o=this._extensionPlugins.get(n);o&&o.set(r,e),t.push(e)}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugin ${r}: ${Cc(e)}`);const o=this._extensionPlugins.get(n),s=o?.get(r);s&&t.push(s)}return t}async ensureLoaded(){this.loadPromise?await this.loadPromise:this.loadedOnce||await this.reload()}async load(){const e={stack:[],error:void 0,hasError:!1};try{const t=(0,b.q6)().withName("LocalPluginsService.load"),r=(function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(e,(0,D.VI)(t),!1),performance.now()),n=e=>{this.pluginLogger.increment(`local_plugins_service.load.${e}`,1),this.pluginLogger.distribution("local_plugins_service.load.duration",performance.now()-r,{outcome:e})},o=this.getSettings(),i=WD(this.marketplaceOptions,this.userHomeDirectory),a=o.importThirdPartyPlugins,c=o.loadUserLocalPlugins??!0,l=o.loadCursorFirstParty??i.length>0;if(!a&&!l&&!c)return this.pluginLogger.log("info","Skipping plugin loading, cursor 1p, 3p, and user-local plugins are disabled"),{plugins:[],failures:[],sourceUnavailable:!1};this.pluginLogger.increment("local_plugins_service.load.start",1);const u=(e,t)=>{this.pluginLogger.increment("local_plugins_service.load_plugin.error",1),this.pluginLogger.log("error",`Cursor plugin load error ${e.name}@${e.version}: ${t?.message??String(t)}`)};try{const e=await async function(e,t={}){const r=t.log??$p,n=performance.now(),o=t.loadClaude??!0,i=t.loadUserLocal??!0,a=t.marketplaceSources??[],c=t.loadCursorFirstParty??a.length>0,l=[],u=[];let d;o&&l.push(Yf(e,0,{userHomeDir:t.userHomeDir,onError:t.onError,log:r})),c&&a.length>0&&(d=Promise.allSettled(a.map((e=>om({...e,userHomeDir:e.userHomeDir??t.userHomeDir,log:e.log??r}))))),i&&l.push(async function(e={}){const t=e.log??$p,r=performance.now(),n=e.userHomeDir??process.env.HOME;if(!n)return t.log("info","loadUserLocalPlugins: no home directory available, skipping"),[];const o=(0,s.join)(n,".cursor","plugins","local");let i;try{i=await(0,xo.readdir)(o,{withFileTypes:!0})}catch{return t.log("info",`loadUserLocalPlugins: ${o} not found or not readable (${(performance.now()-r).toFixed(1)}ms)`),[]}const a=await(0,xo.realpath)(o).catch((()=>(0,s.resolve)(o))),c=[];for(const r of i){if(!r.isDirectory()&&!r.isSymbolicLink())continue;if(r.name.startsWith("."))continue;const n=(0,s.join)(o,r.name);try{if(r.isSymbolicLink()){let e;try{e=await(0,xo.realpath)(n)}catch(e){t.log("warn",`loadUserLocalPlugin ${r.name} rejected: failed to resolve symlink (${e instanceof Error?e.message:String(e)})`);continue}try{Sf(a,e)}catch{t.log("warn",`loadUserLocalPlugin ${r.name} rejected: symlink target ${e} is outside ${o}`);continue}}if(!(await(0,xo.stat)(n)).isDirectory()){r.isSymbolicLink()&&t.log("warn",`loadUserLocalPlugin ${r.name} rejected: symlink target is not a directory`);continue}const s=performance.now(),i=await(e.localPluginVariablesLookup?.(r.name)),{displayName:l,description:u,authorName:d,logoUrl:h,version:p,homepage:f,repository:m,variablesSchema:g,skills:w,rules:y,agents:v,commands:b,mcpConfig:S,capabilities:k,hooks:_}=await Zf(n,r.name,void 0,{configuredVariables:i,log:t}),C={source:"user-local",sourceInfo:{name:r.name,localPath:n}};c.push({identifier:C,installPath:n,...void 0!==l&&{displayName:l},...void 0!==u&&{description:u},...void 0!==d&&{authorName:d},...void 0!==h&&{logoUrl:h},...void 0!==p&&{version:p},...void 0!==f&&{homepage:f},...void 0!==m&&{repository:m},variablesSchema:g,skills:w,rules:y,agents:v,commands:b,mcpConfig:S??void 0,capabilities:k,hooks:_}),t.log("info",`loadUserLocalPlugin ${r.name} loaded in ${(performance.now()-s).toFixed(1)}ms`)}catch(e){t.log("error",`loadUserLocalPlugin ${r.name} failed: ${e instanceof Error?e.message:String(e)}`)}}return t.log("info",`loadUserLocalPlugins completed in ${(performance.now()-r).toFixed(1)}ms (${c.length} plugins loaded)`),c}({userHomeDir:t.userHomeDir,log:r,localPluginVariablesLookup:t.localPluginVariablesLookup}));const[h,p]=await Promise.all([Promise.allSettled(l),d??Promise.resolve([])]);let f=!1;const m=[];for(const e of p)"rejected"!==e.status?(e.value.sourceUnavailable&&(f=!0),m.push(...e.value.plugins),u.push(...e.value.failures)):(f=!0,r.log("error",`marketplace source threw while loading; treating it as unavailable: ${String(e.reason)}`));for(const e of h)"rejected"!==e.status?m.push(...e.value):(f=!0,r.log("error",`plugin source threw while loading; treating it as unavailable: ${String(e.reason)}`));const g=new Set,w=[];for(const e of m){if(!e.installPath){w.push(e);continue}const t=await(0,xo.realpath)(e.installPath).catch((()=>e.installPath));g.has(t)||(g.add(t),w.push(e))}const y=new Map,v=[];for(const e of w){const t=sm(e);if(void 0!==t){const r=y.get(t),n=!e.loadError;if(!0===r)continue;if(!1===r&&n){const r=v.findIndex((e=>sm(e)===t&&e.loadError));-1!==r&&v.splice(r,1),y.set(t,!0),v.push(e);continue}y.set(t,n)}v.push(e)}const b=performance.now()-n;return r.log("info",`loadAllPlugins completed in ${b.toFixed(1)}ms (claude=${o}, userLocal=${i}, marketplace=${a.length} sources, total=${v.length} plugins, failures=${u.length}, sourceUnavailable=${f})`),{plugins:v,failures:u,sourceUnavailable:f}}(this.workspacePaths,{userHomeDir:this.userHomeDirectory,loadClaude:a,loadUserLocal:c,loadCursorFirstParty:l&&i.length>0,marketplaceSources:i.length>0?i.map((e=>({...e,onCursorError:u}))):void 0,onError:(e,t)=>{this.pluginLogger.log("error",`Claude plugin load error ${e.raw}: ${t?.message??String(t)}`)},log:this.pluginLogger,localPluginVariablesLookup:this.localPluginVariablesLookup});return n("success"),this.pluginLogger.log("info",`Plugins loaded in ${(performance.now()-r).toFixed(1)}ms`),e}catch(e){return n("error"),this.pluginLogger.log("error",`Failed to load all plugins: ${Cc(e)}`),{plugins:[],failures:[],sourceUnavailable:!0}}}catch(t){e.error=t,e.hasError=!0}finally{BD(e)}}}const qD=["parse binary","parse json"],zD=["decompression failed","unsupported response encoding","unsupported content type","protocol error: promised"],GD=new Set([1,4,10,14]),VD=new Set(["AbortError","TimeoutError"]),KD=["ECONN","ENOT","ETIMEDOUT","EPIPE","EAI_","EHOST","ENET","ERR_HTTP2","ERR_SSL","ERR_TLS","UND_ERR","CERT_","DEPTH_ZERO_SELF_SIGNED_CERT","SELF_SIGNED_CERT","UNABLE_TO_"];function JD(e,t){return t.some((t=>e.startsWith(t)))}function ZD(e){if(e instanceof Error&&VD.has(e.name))return!0;const t=function(e){if("object"==typeof e&&null!==e&&"code"in e)return"string"==typeof e.code?e.code:void 0}(e);return void 0!==t&&JD(t,KD)}function XD(e){const t=function(e){if(e instanceof Error&&"ConnectError"===e.name&&"code"in e&&"number"==typeof e.code&&"rawMessage"in e&&"string"==typeof e.rawMessage)return{code:e.code,text:e.rawMessage,cause:e.cause}}(e);if(void 0===t)return ZD(e)?"transport":"other";const{code:r,text:n,cause:o}=t;return JD(n,qD)?"reply_schema":JD(n,zD)?"reply_encoding":n.startsWith("http/2 stream closed with error code")||GD.has(r)||ZD(o)?"transport":"other"}var QD=r("../proto/dist/generated/aiserver/v1/dashboard_pb.js");const YD=BigInt(0),eO=BigInt(8),tO=BigInt(16),rO=BigInt(65535);function nO(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch{return}}function oO(e){let t=e.trim().replace(/\.+$/,"").toLowerCase();if(t.startsWith("[")){const e=t.indexOf("]");-1!==e&&(t=t.slice(1,e))}else if(t.split(":").length-1==1){const e=t.lastIndexOf(":"),r=t.slice(e+1);Array.from(r).every((e=>/\d/.test(e)))&&(t=t.slice(0,e))}return t}function sO(e){const t=e.split(".");if(4!==t.length)return;let r=YD;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<>tO&rO)),t.push(Number(o.value&rO))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function aO(e){return sO(e)??function(e){const t=oO(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=iO(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<7?void 0:{version:6,value:[...n,...new Array(8-s).fill(0),...o].reduce(((e,t)=>e<i)return!1;const a=BigInt(i-s);return o.value>>a==n.value>>a}(r,n);if(n.startsWith("*.")){const e=n.slice(2);return r===e||r.endsWith(`.${e}`)}return r===n}function lO(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}function uO(e,t){if(lO(e,t))return!0;if(e.includes("://")){let r,n;try{r=new URL(e),n=new URL(t)}catch{return!1}if(""!==r.username||""!==r.password||""!==n.username||""!==n.password||r.protocol!==n.protocol||r.port!==n.port)return!1;const o=oO(r.hostname);return!!cO(oO(n.hostname),o)&&lO(`${r.pathname}${r.search}`,`${n.pathname}${n.search}`)}const r=function(e){const t=function(e){const t=e.trim(),r=t.indexOf("["),n=t.indexOf("]");if(-1!==r&&n>r){const e=t.slice(r+1,n);if(t.slice(n+1).startsWith("("))return`${t.slice(0,r)}${e}`}return t}(e).trim();if(0===t.length)return;const r=t.lastIndexOf("/");if(!t.includes("://")&&r>0&&/^\d+$/.test(t.slice(r+1).trim())){const e=oO(t.slice(0,r));if(e.length>0)return`${e}/${t.slice(r+1).trim()}`}const n=nO(t);if(n)return oO(n.hostname);let o=t;const s=o.indexOf("://");-1!==s&&(o=o.slice(s+3));const i=o.indexOf("/");-1!==i&&(o=o.slice(0,i));const a=oO(function(e){if(e.startsWith("[")){const t=e.indexOf("]");return-1!==t?e.slice(1,t):e}const t=e.split(":");return 2===t.length&&Array.from(t[1]??"").every((e=>/\d/.test(e)))?t[0]:e}(o));if(0!==a.length){if(a.startsWith("*.")){const e=a.slice(2);if(0===e.length||e.includes("*")||e.includes("?"))return;return a}if(!a.includes("*")&&!a.includes("?"))return a}}(e),n=function(e){const t=nO(e);if(t)return oO(t.hostname);const r=oO(e);return r.length>0?r:void 0}(t);return!(!r||!n)&&cO(n,r)}async function dO(e){try{return await e.current()}catch{return}}function hO(e){try{const t=new URL(e);return`${t.protocol}//${t.host}${t.pathname}`}catch{return}}function pO({failOpenWhenEmpty:e,server:t,settings:r}){if(!0!==r?.allowedMcpConfiguration?.requireMcpServersInTeamNetworkAllowlist||void 0===t.url)return{blocked:!1};const n=function(e){return!0===e.cloudAgentMcpAllowlistApplied&&!1===e.mirrorSandboxAllowlistForEgress?e.cloudAgentEgressAllowlist??[]:e.networkAllowlist??[]}(r).map((e=>e.trim())).filter((e=>e.length>0));return 0===n.length&&e||Qv(t.url,n)?{blocked:!1}:{blocked:!0,reason:"teamNetworkAllowlist",message:"Not on the team network allowlist"}}function fO(e){const t=e?.trim();return t&&t.length>0?t:void 0}function mO(e,t,r){if(!0===r?.useCorePolicy)return!function(e,t){if(void 0===t)return!0;if(!0===t.disableAll)return!1;if(CC(e))return!0;if(RC(e,t.offMcpServerRules))return!1;const r=t.allowedMcpServers??[];return 0===r.length&&!0!==t.allowUserOverrideMcpServers||!!function(e,t){return t.length>0&&function(e,t){return t.some((t=>{const r=EC(t.command),n=xC(t.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==e.command&&(0,Lb.mD)(r,e.command),s=void 0===n||void 0!==e.url&&(0,Lb.vc)(n,e.url);return o&&s}))}(e,t)}(e,r)||!0===t.allowUserOverrideMcpServers&&!PC(e,t.deniedMcpServers)}(e,t);if(void 0===t)return!1;if(!0===t.disableAll)return!0;const n=t.allowedMcpServers;return 0!==n.length&&!n.some((t=>function(e,t){const r=fO(e.command),n=fO(e.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==t.command&&function(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}(r,t.command),s=void 0===n||void 0!==t.url&&uO(n,t.url);return o&&s}(t,e)))}class gO{constructor(e,t={}){this.dashboardClient=e,this.options=t}getTeamAdminSettings(){return this.dashboardClient.getTeamAdminSettingsOrEmptyIfNotInTeam(new QD.Byz(!0===this.options.supportsHostMcpBridgeExemption?{supportsHostMcpBridgeExemption:!0}:{}))}getTeamRepos(){return this.dashboardClient.getTeamReposOrEmptyIfNotInTeam(new QD.aYW({}))}}function wO(e,t){if("workspace"!==e)return[];const r=[],n=new Set;for(const e of t??[]){const t=e.trim();0===t.length||n.has(t)||(n.add(t),r.push(t))}return r}class yO{constructor(e){this.fetch=e}get(){const e=this.cached,t=void 0===e?1/0:Date.now()-e.fetchedAt;return void 0===e||t>6e5?(this.cached=void 0,this.refresh()):(t>3e5&&this.refresh().catch((()=>{})),Promise.resolve(e.value))}invalidate(){this.cached=void 0,this.inFlight=void 0}refresh(){if(void 0===this.inFlight){const e=this.fetch().then((t=>(this.inFlight!==e||void 0===t&&void 0!==this.cached||(this.cached={value:t,fetchedAt:Date.now()}),t))).finally((()=>{this.inFlight===e&&(this.inFlight=void 0)}));this.inFlight=e}return this.inFlight}}class vO{constructor(e,t,r={}){this.teamAdminSettingsProvider=e,this.defaultAllowlistProvider=t,this.options=r,this.lastFetchSucceeded=!0,this.lastFetchFailure="other",this.settingsGeneration=0,this.lastFetchedGeneration=0,this.settings=new yO((()=>this.fetchSettings())),this.droppedReplies=new WeakSet,this.hostMcpBridgeClients=new WeakSet,this.mcpServerByClient=new WeakMap,this.teamRepos=new yO((()=>this.teamAdminSettingsProvider.getTeamRepos())),this.defaultAllowlist=new yO((()=>this.fetchDefaultAllowlist())),this.getTeamAdminSettings(),this.prefetchTeamRepos()}async prefetchTeamRepos(){try{await this.teamRepos.get()}catch{}}invalidateCache(){this.settingsGeneration+=1,this.settings.invalidate(),!0!==this.options.preserveTeamReposOnInvalidate&&this.teamRepos.invalidate(),this.defaultAllowlist.invalidate()}invalidateTeamRepos(){this.teamRepos.invalidate()}async refreshTeamAdminSettings(){try{await this.settings.refresh()}catch{}}async fetchSettings(){const{fetchIdentity:e}=this.options;if(void 0!==e)return this.fetchSettingsFor(e);const t=this.settingsGeneration;try{const e=await this.teamAdminSettingsProvider.getTeamAdminSettings();return this.lastFetchSucceeded=!0,t>=this.lastFetchedGeneration&&(this.lastFetchedSettings=e,this.lastFetchedGeneration=t),e}catch(e){throw this.lastFetchSucceeded=!1,this.lastFetchFailure=XD(e),e}}async fetchSettingsFor(e){const t=await dO(e),r=this.settingsGeneration;if(void 0===t)throw this.lastFetchSucceeded=!1,this.lastFetchFailure="other",new Error("No one is named whose team settings a fetch would read");try{const e=await this.teamAdminSettingsProvider.getTeamAdminSettings();return void 0!==e&&this.droppedReplies.delete(e),this.isSentFor(e,t)?(this.lastFetchSucceeded=!0,r>=this.lastFetchedGeneration&&(this.lastFetchedSettings=e,this.lastFetchedGeneration=r),e):e}catch(e){throw this.lastFetchSucceeded=!1,this.lastFetchFailure=XD(e),e}}getTeamAdminSettings(){const{fetchIdentity:e}=this.options;return void 0!==e?this.getTeamAdminSettingsFor(e):this.settings.get().catch((()=>{}))}async getTeamAdminSettingsFor(e){const t=await this.settings.get().catch((()=>{})),r=await dO(e);if(void 0===t)return void(this.isSentFor(this.lastFetchedSettings,r)||(this.settingsGeneration+=1));if(void 0===r)return this.answerAsFailedRead();if(this.isSentFor(t,r))return t;let n=t,o=r;const s=await this.settings.get().catch((()=>{}));if(s!==t){if(void 0===s)return this.answerAsFailedRead();if(this.isSentFor(s,r))return s;if(o=await dO(e),void 0===o)return this.answerAsFailedRead();if(this.isSentFor(s,o))return s;n=s}this.droppedReplies.has(n)||(this.droppedReplies.add(n),this.settingsGeneration+=1,this.settings.invalidate());const i=await this.settings.get().catch((()=>{}));return void 0!==i?this.isSentFor(i,r)||this.isSentFor(i,o)||this.isSentFor(i,await dO(e))?i:this.answerAsFailedRead():void 0}answerAsFailedRead(){this.settingsGeneration+=1,this.lastFetchSucceeded=!1,this.lastFetchFailure="other"}isSentFor(e,t){return void 0!==e&&void 0!==t&&this.options.fetchIdentity?.sentFor(e)===t}async getDotCursorProtection(){const e=await this.getTeamAdminSettings();return e?.dotCursorProtection??!0}async getShouldBlockMcp(){const e=await this.getTeamAdminSettings();return!(!e?.autoRunControls?.enabled||!e?.autoRunControls?.disableMcpAutoRun)}async getDeleteFileProtection(){const e=await this.getTeamAdminSettings();return!(!e?.autoRunControls?.enabled||!e?.autoRunControls?.deleteFileProtection)}async getIsHeadlessDisabled(){return"disabled"===(await this.getHeadlessCliPolicy()).kind}async getHeadlessCliPolicy(){const e=await this.getTeamAdminSettings();return void 0!==e||this.lastFetchSucceeded?!0===e?.cliSettings?.disableHeadless?{kind:"disabled"}:{kind:"enabled"}:{kind:"unavailable"}}async getMcpServerBlockInfo(e){const t=await this.getTeamAdminSettings(),r=t?.allowedMcpConfiguration,n=await this.isMcpSettingsOverhaulEnabled({disableExposureLog:!0});if(!0===r?.disableAll)return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};if(this.isHostMcpBridge(t,e))return{blocked:!1,hostMcpBridge:!0};if(RC(e,r?.offMcpServerRules))return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};if(n){if(mO(e,r,{useCorePolicy:!0}))return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};const n=await this.getMcpNetworkControlsConfig(e),o=void 0===e.url?{allowed:!0}:(0,Lb.ME)(e.url,n);if(!o.allowed)return{blocked:!0,reason:"teamNetworkAllowlist",message:o.message};const s=pO({failOpenWhenEmpty:!1,server:e,settings:t});if(s.blocked)return s}if(!n){const r=function({isMcpAccessNetworkAllowlistEnabled:e,server:t,settings:r}){return e&&!0===r?.allowedMcpConfiguration?.requireMcpServersInTeamNetworkAllowlist?pO({failOpenWhenEmpty:!0,server:t,settings:r}):{blocked:!1}}({isMcpAccessNetworkAllowlistEnabled:await this.isMcpAccessNetworkAllowlistEnabled(),server:e,settings:t});if(r.blocked)return r}return void 0!==t||this.lastFetchSucceeded?{blocked:!1}:{blocked:!1,settingsUnavailable:!0}}async getManagedSlackWorkspaceLists(){const e=await this.getTeamAdminSettings()??this.lastFetchedSettings;return void 0===e?[]:function(e){return e.memberSlackManagedWorkspacesUnreadable?"unconfirmed":e.memberSlackManagedWorkspaces.map((e=>e.slackTeamIds)).filter((e=>e.length>0))}(e)}async getMcpNetworkControlsConfig(e){const t=await this.getTeamAdminSettings(),r=t?.allowedMcpConfiguration;if(await this.isMcpSettingsOverhaulEnabled()&&(void 0===e||!this.isHostMcpBridge(t,e))){const n="win32"===process.platform&&await this.isWin32UserExtensionStdioUnsandboxEnabled();return(0,Lb._N)({allowedMcpConfiguration:r,server:e,localAgentNetworkAllowlist:t?.networkAllowlist,blockMessage:"Not on the team network allowlist",aggregateManagedServerNetworkAllowlists:!1,stdioPlatform:process.platform,unsandboxUserExtensionStdio:n})}return{enabled:!1,localAgentNetworkAllowlist:t?.networkAllowlist,blockMessage:"Not on the team network allowlist"}}isHostMcpBridge(e,t){const r=this.options.hostMcpBridgeUrls;if(!0!==e?.cloudAgentMcpAllowlistApplied||void 0===r||void 0!==t.command||void 0===t.url)return!1;const n=hO(t.url);return void 0!==n&&r.some((e=>hO(e)===n))}recordHostMcpBridgeClient(e){this.hostMcpBridgeClients.add(e)}async isHostMcpBridgeClient(e){if(!this.hostMcpBridgeClients.has(e))return!1;const t=await this.getTeamAdminSettings();return!0===t?.cloudAgentMcpAllowlistApplied&&!0!==t.allowedMcpConfiguration?.disableAll}recordMcpServerClient(e,t){this.mcpServerByClient.set(e,t)}async getMcpAdminToolLimit(e){if(await this.isHostMcpBridgeClient(e))return{kind:"none"};const t=this.mcpServerByClient.get(e);if(void 0===t)return{kind:"unknown_server"};const r=!0===this.options.mcpAdminToolLimitSurvivesFailedRead;let n=await this.getTeamAdminSettings();if(void 0===n&&!this.lastFetchSucceeded&&r&&(n=await this.getTeamAdminSettings()),void 0===n){if(this.lastFetchSucceeded)return{kind:"none"};if(!r)return{kind:"settings_unavailable"};const e=this.lastFetchFailure,t=this.lastFetchedGeneration===this.settingsGeneration?this.lastFetchedSettings:void 0;if(void 0===t)return{kind:"settings_unavailable",failure:e,noLimitApplies:!0};n=t}const o=function(e,t){const r=e?.find((e=>(0,Lb.rM)(e,t)));if(void 0!==r)return Bb({mode:r.toolAllowlistMode,tools:r.toolAllowlist})}(n.allowedMcpConfiguration?.allowedMcpServers,t);return void 0===o?{kind:"none"}:{kind:"limit",policy:o}}async isServerBlocked(e){return(await this.getMcpServerBlockInfo(e)).blocked}async getAutoRunControls(){const e=await this.getTeamAdminSettings();if(e?.autoRunControls?.enabled)return{enabled:e.autoRunControls.enabled,allowed:e.autoRunControls.allowed??[],blocked:e.autoRunControls.blocked??[],enableAllowlistMode:e.autoRunControls.enableAllowlistMode??!0,enableRunEverything:e.autoRunControls.enableRunEverything??!1,enableSmartAuto:e.autoRunControls.enableSmartAuto??!0,mcpToolAllowlist:e.autoRunControls.mcpToolAllowlist??[]}}async isReadControlEnabled(){try{return await(this.options.isReadControlEnabled?.())??!0}catch{return!1}}async isDenylistEnforcementKilled(){try{return!0===await(this.options.isAdminCommandDenylistEnforcementKilled?.())}catch{return!1}}async getAdminCommandDenylist(){if(await this.isDenylistEnforcementKilled())return{rules:[]};const e=await this.getTeamAdminSettings();return{rules:e?.autoRunControls?.adminCommandDenylist?.rules??[]}}async isMcpSettingsOverhaulEnabled(e){const t=this.options.isMcpSettingsOverhaulEnabled?.(e);return void 0!==t&&await t}async isWin32UserExtensionStdioUnsandboxEnabled(){try{const e=this.options.isWin32UserExtensionStdioUnsandboxEnabled?.();return void 0!==e&&await e}catch{return!1}}async getMcpToolControls(){const e=await this.getTeamAdminSettings(),t=e?.allowedMcpConfiguration;if(void 0===t)return;const r=function({autoRunControls:e,allowedMcpServers:t}){const r=!0===e?.enabled?e.mcpToolAllowlist??[]:[],n=function(e){return(e??[]).flatMap((e=>{const t=void 0===e.name?"":jb(e.name);if(0===t.length)return[];const r=Bb({mode:e.toolAllowlistMode,tools:e.toolAllowlist});return[{name:t,policy:r,flattened:Hb(t,r)}]}))}(t);return{tools:(o=[...n.flatMap((e=>[...e.flattened])),...r],[...new Set(o)]),policies:n.map((e=>({name:e.name,policy:e.policy})))};var o}({autoRunControls:e?.autoRunControls,allowedMcpServers:t?.allowedMcpServers});return r.policies.length>0||r.tools.length>0?{enabled:!0,mcpToolAllowlist:r.tools,allowUserOverride:t?.allowUserOverrideMcpServers??!1,serverPolicies:r.policies}:void 0}async getNetworkAccessControls(){const e=await this.getTeamAdminSettings();return void 0!==e||this.lastFetchSucceeded?{allowlist:e?.networkAllowlist??[],denylist:e?.networkDenylist??[],available:!0}:{allowlist:[],denylist:[],available:!1}}async getSandboxingControls(){const e=await this.getTeamAdminSettings(),t=e?.autoRunControls?.sandboxingControls,r=(n=t?.sandboxReadBoundary,n===QD.h0i.WORKSPACE?"workspace":"system");var n;return{sandboxingDisabled:t?.sandboxing===QD.faf.DISABLED,networkingDisabled:t?.sandboxNetworking===QD._mX.ALWAYS_DISABLED,gitDisabled:t?.sandboxGit===QD.i24.ALWAYS_DISABLED,readBoundary:r,readAllowlistPaths:wO(r,t?.sandboxReadAllowlistPaths),allowUserOverrideReadAllowlist:!1!==t?.allowUserOverrideSandboxReadAllowlist}}async isAttributionDisabledByAdmin(){const e=await this.getTeamAdminSettings();return void 0===e&&!this.lastFetchSucceeded||(e?.attributionControls?.disableAttribution??!1)}async isComputerUseDisabledByAdmin(){const e=await this.getTeamAdminSettings();return void 0!==e?!1===e.computerUse:this.lastFetchedGeneration!==this.settingsGeneration||void 0===this.lastFetchedSettings&&!this.lastFetchSucceeded||!1===this.lastFetchedSettings?.computerUse}getDefaultNetworkAllowlist(){return this.defaultAllowlist.get().catch((()=>({allowlist:[],available:!1})))}async fetchDefaultAllowlist(){return this.defaultAllowlistProvider?{allowlist:await this.defaultAllowlistProvider.getDefaultNetworkAllowlist(),available:!0}:{allowlist:[],available:!0}}getTeamRepos(){return this.teamRepos.get()}async isMcpAccessNetworkAllowlistEnabled(){return await(this.options.isMcpAccessNetworkAllowlistEnabled?.())??!1}}const bO=new xy,SO={async resolveWorkspaceState(e){const t=e.workingDirectory??e.projectRoot??e.workspaceRoots?.[0],r=e.projectRoot??(void 0!==t?await tc((0,b.q6)(),bO,t)??t:void 0),n=e.workspaceRoots??(void 0!==r?[r]:void 0!==t?[t]:[]);return{workingDirectory:t,projectRoot:r,projectDirectory:e.projectDirectory??(void 0!==r?Eo(r):void 0),workspaceRoots:n,createdAt:new Date}}},kO=(0,d.h)("ControlledConversationActionManager");class _O{get signal(){return this.abortController.signal}get abortRequested(){return this.abortCalled}constructor(){this.abortCallbacks=[],this.abortController=new AbortController,this.acceptsActions=!0,this.disposed=!1,this.abortStarted=!1,this.abortCalled=!1,this.runActive=!1,this.unprocessedUserMessages=[],this.clientStream=(0,f.Jt)()}addAbortCallback(e){this.abortCallbacks.push(e)}abort(e,t){if(this.abortCalled=!0,this.abortController.signal.aborted||this.abortStarted)return;const r=t?.interruptedPendingToolCallResolutions;if(this.abortStarted=!0,!this.runActive){this.abortController.abort(e);for(const e of this.abortCallbacks)e();return void(this.abortCallbacks.length=0)}const n=this.abortController,o=[...this.abortCallbacks];this.abortCallbacks.length=0,this.submitConversationAction(new c.QFf({action:{case:"cancelAction",value:new c.TTG({reason:e,interruptedPendingToolCallResolutions:r})}})).catch((()=>{})).finally((()=>{n.abort(e);for(const e of o)e();if(this.abortController===n){const e=[...this.abortCallbacks];this.abortCallbacks.length=0;for(const t of e)t()}}))}async submitConversationAction(e){if(!this.acceptsActions)throw new f.W2("ControlledConversationActionManager is not accepting actions");if("userMessageAction"===e.action.case){const t=e.action.value.userMessage;t&&this.unprocessedUserMessages.push(t)}await this.clientStream.write(e)}queueFollowUpUserMessage(e){if(this.disposed||this.abortStarted)throw new f.W2("ControlledConversationActionManager run was aborted or disposed");this.unprocessedUserMessages.push(e)}async enqueueReplayableConversationAction(e){if("asyncAskQuestionCompletionAction"!==e.action.case)throw new TypeError("Only asyncAskQuestionCompletionAction can use enqueue acknowledgement");if(!this.acceptsActions)throw new f.W2("ControlledConversationActionManager is not accepting actions");this.clientStream.write(e).catch((()=>{}))}markMessageAsProcessed(e){this.unprocessedUserMessages=this.unprocessedUserMessages.filter((t=>t.messageId!==e.messageId))}requeueMessage(e){this.unprocessedUserMessages.some((t=>t.messageId===e.messageId))||this.unprocessedUserMessages.unshift(e)}getUnprocessedUserMessages(){return[...this.unprocessedUserMessages]}hasUnprocessedMessages(){return this.unprocessedUserMessages.length>0}close(){this.acceptsActions=!1,this.clientStream.close()}reopen(){this.disposed||this.acceptsActions||this.resetStream()}resetStream(){if(this.disposed)throw new f.W2("ControlledConversationActionManager disposed");this.acceptsActions=!1,this.clientStream.close(),this.clientStream=(0,f.Jt)(),this.acceptsActions=!0,this.abortController=new AbortController,this.abortStarted=!1;for(const e of this.unprocessedUserMessages)this.clientStream.write(new c.QFf({action:{case:"userMessageAction",value:new c.Vtf({userMessage:e})}})).catch((()=>{}))}async run(e,t){const r=this.clientStream;this.runActive=!0;try{for await(const n of r)try{await t.write(n)}catch(t){kO.error(e,"Error writing conversation action",t)}}catch(e){if(!(e instanceof f.W2))throw e}finally{this.clientStream===r&&(this.runActive=!1)}}dispose(){this.disposed||(this.disposed=!0,this.abortCallbacks.length=0,this.acceptsActions=!1,this.clientStream.throw(new f.W2("ControlledConversationActionManager disposed")))}}var CO=r("../cursor-sdk-local-runtime/dist/utils/logger.js"),EO=r("../agent-kv/dist/agent-store.js");const xO="x-blob-encryption-key";function PO(e,t){const r={...t};return void 0!==r[xO]||(0,EO.TU)(e)&&(r[xO]=e),r}const RO=new Map;function IO(e){if("userMessageAction"===e.action.case)return e.action.value.userMessage?.text}function TO(e,t,r){const n=e.runOptions?.requestedModel;return{conversationId:e.conversationId,generationId:e.conversationId,model:n?.modelId??"unknown",modelId:n?.modelId,modelParams:n?.parameters.map((e=>({id:e.id,value:e.value}))),loopCount:t,promptText:r}}function AO(e){return new c.QFf({action:{case:"userMessageAction",value:new c.Vtf({userMessage:new c.RGk({text:e})})}})}function $O(e){return e instanceof DOMException&&"AbortError"===e.name||e instanceof Error&&("AbortError"===e.name||"The operation was aborted"===e.message)}function MO(e){e?.catch((e=>{CO.Jz.warn("[agent-session-runner] fire-and-forget hook failed:",e)}))}class DO{constructor(e,t,r){this.inner=e,this.getToken=t,this.restMcpHost=r}async getDefinitions(e,t=!0){const r=await this.inner.getDefinitions(e,t);return Promise.all(r.map((async e=>{const t=await async function(e,t,r){if(!("url"in e)||!e.url||void 0===cb(e.url,r)||Object.keys(e.headers??{}).some((e=>e.toLowerCase()===ab)))return e;const n=await t();return void 0===n||0===n.length?e:{...e,headers:{...e.headers??{},[ab]:`Bearer ${n}`}}}(e.serverConfig,this.getToken,this.restMcpHost);return t===e.serverConfig?e:{...e,serverConfig:t}})))}clearCache(){this.inner.clearCache?.()}}const OO=new Set(["mcp.slack.com","setup.shopify.com"]);class FO{constructor(e,t){this.inner=e,this.resolver=t}async getDefinitions(e,t=!0){const r=await this.inner.getDefinitions(e,t);return Promise.all(r.map((async e=>{const t=await async function(e,t){if(!("url"in e)||!e.url)return e;const r=await async function(e,t,r,n=fetch){let o;try{o=new URL(e).hostname}catch{return t}const s=void 0!==cb(e,r.restMcpHost);if(!OO.has(o)&&!s)return t;let i=await r.resolve(e);if(!i&&s){const t=(await dx(e,n))?.clientId;void 0!==t&&(i={CLIENT_ID:t})}return i?t?void 0===lx(t.CLIENT_ID)?{...i,...t,CLIENT_ID:i.CLIENT_ID}:{...i,...t}:i:t}(e.url,e.auth,t);return r===e.auth?e:{...e,auth:r}}(e.serverConfig,this.resolver);return t===e.serverConfig?e:{...e,serverConfig:t}})))}clearCache(){this.inner.clearCache?.()}}class NO{constructor(e,t){this.storage=e,this.prefix=t}async loadTokens(e){return this.storage.loadTokens(this.prefix+e)}async saveTokens(e,t){return this.storage.saveTokens(this.prefix+e,t)}async loadClientInformation(e){return this.storage.loadClientInformation(this.prefix+e)}async saveClientInformation(e,t){return this.storage.saveClientInformation(this.prefix+e,t)}}class LO{constructor(e,t){this.storage=e,this.prefix=t}async isServerApproved(e,t,r){return this.storage.isServerApproved(this.prefix+e,t,r)}}class jO{constructor(e){this.higherPrecedenceSources=e}async load(e,t,r,n,o){for(const r of this.higherPrecedenceSources){const n=(await r.getDefinitions(e)).find((e=>e.identifier===t));if(void 0!==n)throw new MC(t,n.configPath??"another config")}return await o(e,r)}}class UO extends iI{constructor(e,t){super(e),this.shadowedClientsClosed=t}async closeAllClients(){await Promise.all([super.closeAllClients(),this.shadowedClientsClosed])}}async function BO(e){try{await(e.close?.())}catch{}}class WO{constructor(e){this.loaders=e}async load(e,t=!0){const r=await Promise.allSettled(this.loaders.map((({loader:r})=>r.load(e,t)))),n=r.find((e=>"rejected"===e.status));if(n)throw await Promise.allSettled(r.flatMap((e=>"fulfilled"===e.status?[e.value.closeAllClients()]:[]))),n.reason;const o=r.filter((e=>"fulfilled"===e.status)).map((e=>e.value)),s={},i=[];for(let e=0;e{})))}async loadClient(e,t,r=!1){for(const{loader:n,prefix:o}of this.loaders)if(t.startsWith(o)){t=t.slice(o.length);try{return await n.loadClient(e,t,r)}catch(e){if(e instanceof Error&&e.message.includes("not found in config"))continue;throw e}}throw new Error(`MCP client "${t}" not found in config`)}clearClient(e){for(const{loader:t,prefix:r}of this.loaders){if(!e.startsWith(r))continue;const n=e.slice(r.length);t.clearClient?.(n)}}clearAllMcpCaches(){for(const{loader:e}of this.loaders)e.clearAllMcpCaches?.()}}class HO{constructor(e,t,r,n,i=!1,a,c,l=s.join((0,o.homedir)(),".cursor","mcp.json"),u,d,h){const p=Array.isArray(e)?e:[e],f={}.location,m=[];"enterprise"===f?.source&&m.push({path:f.path,prefix:"enterprise-",scope:"enterprise"});for(let e=0;e({prefix:t,scope:r,fileSource:new _I(e,"enterprise"===r||"env"===r?RE:void 0)}))),y=[];for(const{prefix:e,scope:o,fileSource:s}of w){const l=i?"":e,d=new NO(t,l),p=new LO(n,l),f=w.flatMap((e=>{return t=e.scope,r=o,IE.indexOf(t)0?[new jO(f)]:[]],g=new CI(u?new FO(s,u):s,d,m,{authRedirectUrlGenerator:a,isLinkSharedPaymentTokenLogRedactionEnabled:h});y.push({prefix:l,loader:g})}this.loader=new WO(y)}static init(e,t,r,n=!1,o,i={}){const a=new DI(s.join(r,"mcp-auth.json"));(async function(e){await(0,xo.rm)(s.join(e,"mcp-cache.json"),{force:!0})})(r).catch((()=>{}));const c=n?{isServerApproved:()=>Promise.resolve(!0)}:new FC(s.join(r,"mcp-approvals.json"),t);return new HO(t,a,e,c,!0,void 0,o,void 0,i.defaultAuthResolver,void 0,i.isLinkSharedPaymentTokenLogRedactionEnabled)}async load(e,t=!0){return this.loader.load(e,t)}async loadClient(e,t,r=!1){return this.loader.loadClient(e,t,r)}clearClient(e){this.loader.clearClient(e)}clearAllMcpCaches(){this.loader.clearAllMcpCaches()}}const qO="cursor-plugins/local";function zO(e){var t;if(e)for(const r of e)if("object"==typeof(t=r)&&null!==t&&t.kind===qO)return r}class GO extends sI{constructor(e){super(e),this.runtimeManager=e,this.disposed=!1}async dispose(){this.disposed||(this.disposed=!0,await this.runtimeManager.closeAllClients())}}class VO{constructor(e){this.storagePath=e}async isServerDisabled(e){try{const t=await(0,xo.readFile)(this.storagePath,"utf8"),r=JSON.parse(t);return Array.isArray(r)?r.includes(e):(await this.writeDisabledServers([]),!1)}catch(e){if("object"==typeof e&&null!==e&&"code"in e&&"ENOENT"===e.code)return!1;throw e}}async writeDisabledServers(e){await(0,xo.mkdir)((0,s.dirname)(this.storagePath),{recursive:!0}),await(0,xo.writeFile)(this.storagePath,JSON.stringify(e,null,2))}}class KO{constructor(e,t){this.pluginMcpService=e,this.importThirdPartyPlugins=t}async getDefinitions(){let e;try{e=await this.pluginMcpService.getPluginMcpServers()}catch(e){return CO.Jz.warn("[cursor-config-mcp] Failed to enumerate plugin MCP servers:",e),[]}const t=[];for(const r of e){if(!this.importThirdPartyPlugins&&YO(r))continue;const e=II(r);e?t.push({identifier:r.identifier,authStorageKey:r.identifier,serverConfig:e,configPath:"",source:"plugin",metadata:{identifier:r.identifier,pluginName:r.pluginName,pluginSource:r.pluginSource}}):CO.Jz.warn("[cursor-config-mcp] Failed to initialize plugin MCP client:",{identifier:r.identifier,pluginName:r.pluginName,pluginSource:r.pluginSource,result:"invalid-config",errorMessage:"pluginMcpDescriptorToServerConfig returned undefined"})}return t}}class JO{constructor(e){this.servers=e}async getDefinitions(){return Object.entries(this.servers).map((([e,t])=>({identifier:e,authStorageKey:`inline:${e}`,serverConfig:QO(e,t),source:"inline",metadata:{source:"cursor-sdk"}})))}}function ZO(e={}){const t=e.teamSettingsService??{getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getAdminCommandDenylist:async()=>({rules:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}},r=e.ignoreApprovals??!1,n=e.importThirdPartyPlugins??!1,i=void 0===e.isLinkSharedPaymentTokenLogRedactionEnabled?{}:{isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled},a=e.restMcpCursorAuthTokenSupplier,c=e=>void 0===a?e:new DO(e,a,"api.cursor.com");return{async createLease(a){const l=a.workspaceState,u=l.projectRoot??l.workingDirectory,d=l.projectDirectory;if(!u||!d)return new oI;const h=new VO((0,s.join)(d,"mcp-disabled.json")),p=function(e){const{teamSettingsService:t,projectRoot:r,projectDirectory:n,ignoreApprovals:i,disabledStore:a,includeProjectMcp:c,includeUserMcp:l,isLinkSharedPaymentTokenLogRedactionEnabled:u}=e;if(c&&l)return HO.init(t,r,n,i,a,{isLinkSharedPaymentTokenLogRedactionEnabled:u});if(!c&&!l)return;const d=new DI((0,s.join)(n,"mcp-auth.json")),h=i?{isServerApproved:()=>Promise.resolve(!0)}:new FC((0,s.join)(n,"mcp-approvals.json"),r),p=[new KC,new OC(h),new PI(t),new DC(a)],f=[];return c&&f.push({prefix:"",loader:new RI((0,s.join)(r,".cursor","mcp.json"),d,p,{isLinkSharedPaymentTokenLogRedactionEnabled:u})}),l&&f.push({prefix:"",loader:new RI((0,s.join)((0,o.homedir)(),".cursor","mcp.json"),d,p,{isLinkSharedPaymentTokenLogRedactionEnabled:u})}),XO(f)}({teamSettingsService:t,projectRoot:u,projectDirectory:d,ignoreApprovals:r,disabledStore:h,includeProjectMcp:e.includeProjectMcp??!0,includeUserMcp:e.includeUserMcp??!0,isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled}),f=[],m=e.inlineMcpServers??{};if(Object.keys(m).length>0){const e=new DI((0,s.join)(d,"mcp-auth.json")),r=[new KC,new PI(t)];f.push({prefix:"",loader:new CI(c(new JO(m)),e,r,i)})}const g=zO(a.services.pluginBootstrapOutputs);if(g&&(e.includePluginMcp??1)){const e=new FC((0,s.join)(d,"mcp-approvals.json"),u),o=new DI((0,s.join)(d,"mcp-auth.json")),a=[new KC];r||a.push(new OC(e)),a.push(new PI(t),new DC(h));const l=new UD(g.pluginsService),p=new CI(c(new KO(l,n)),o,a,i);f.push({prefix:"",loader:p})}if(p&&f.push({prefix:"",loader:p}),0===f.length)return new oI;const w=XO(f),y=await w.load(e.initializationCtx??(0,b.q6)(),e.cache);return new GO(y)}}}function XO(e){return 1===e.length?e[0].loader:new WO(e)}function QO(e,t){if("command"in t){if(void 0!==t.type&&"stdio"!==t.type)throw new Error(`Unsupported MCP server type "${String(t.type)}" for "${e}"`);return{command:t.command,args:t.args?[...t.args]:void 0,env:t.env,cwd:t.cwd,startupTimeoutSec:t.startupTimeoutSec}}if("url"in t){if(void 0!==t.type&&"http"!==t.type&&"sse"!==t.type)throw new Error(`Unsupported MCP server type "${String(t.type)}" for "${e}"`);const r={url:t.url,headers:t.headers,auth:t.auth?{CLIENT_ID:t.auth.CLIENT_ID,CLIENT_SECRET:t.auth.CLIENT_SECRET,scopes:t.auth.scopes?[...t.auth.scopes]:void 0}:void 0};return"sse"===t.type?{...r,type:"sse"}:r}throw new Error(`Invalid inline MCP server config for "${e}"`)}function YO(e){return"claude-plugin"===e.pluginSource}const eF=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass"];function tF(e){let t=e.trim();t.startsWith("&")&&(t=t.slice(1).trim());const r=t.charAt(0);if("'"!==r&&'"'!==r)return t.split(/\s/)[0]??"";let n="";for(let e=1;e0)return{...n,followup_message:n.reason.trim()};if(!cF(t))return n;const o=uF(e),s=dF(o,r)?o:void 0,i=void 0!==s?{...n,...s}:n;return"block"===i.decision&&"string"==typeof i.reason&&i.reason.trim().length>0?{...i,followup_message:i.reason.trim()}:n}const pF=e=>{const t=[];return Td(e)?$d(!0):(t.push("Expected an object"),$d(!1,t))},fF=e=>{const t=[],r=pF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny","ask"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("Invalid user_message value. Expected a string if provided"),void 0!==e.agent_message&&"string"!=typeof e.agent_message&&t.push("Invalid agent_message value. Expected a string if provided"),$d(0===t.length,t)};function mF(e){const t=e.modelId,r=e.modelParams;return{...void 0!==t&&{model_id:t},...void 0!==r&&r.length>0?{model_params:r.map((e=>({id:e.id,value:e.value})))}:{}}}const gF=new Set([Rd.sessionStart,Rd.beforeSubmitPrompt,Rd.preToolUse,Rd.postToolUse,Rd.postToolUseFailure]);function wF(e){return"prompt"===e.type}function yF(e){return"command"===e.type||void 0===e.type}const vF={[Rd.beforeShellExecution]:fF,[Rd.beforeMCPExecution]:fF,[Rd.afterShellExecution]:e=>{const t=pF(e);return t.isValid,t},[Rd.afterMCPExecution]:e=>{const t=pF(e);return t.isValid,t},[Rd.beforeReadFile]:e=>{const t=[],r=pF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("user_message must be a string if provided"),$d(0===t.length,t)},[Rd.afterFileEdit]:e=>{const t=pF(e);return t.isValid,t},[Rd.beforeTabFileRead]:e=>{const t=[],r=pF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("user_message must be a string if provided"),$d(0===t.length,t)},[Rd.afterTabFileEdit]:e=>pF(e),[Rd.beforeSubmitPrompt]:e=>{const t=pF(e);if(!t.isValid)return t;const r=[];return void 0!==e.continue&&"boolean"!=typeof e.continue&&r.push("continue must be a boolean if provided"),void 0!==e.user_message&&"string"!=typeof e.user_message&&r.push("user_message must be a string if provided"),void 0===e.additional_context||Id(e.additional_context)||r.push("additional_context must be a string if provided"),$d(0===r.length,r)},[Rd.stop]:e=>{const t=pF(e);if(!t.isValid)return t;const r=[];return void 0!==e.followup_message&&"string"!=typeof e.followup_message&&r.push("followup_message must be a string if provided"),$d(0===r.length,r)},[Rd.afterAgentResponse]:e=>{const t=pF(e);return t.isValid,t},[Rd.afterAgentThought]:e=>{const t=pF(e);return t.isValid,t},[Rd.sessionStart]:e=>{const t=pF(e);if(!t.isValid)return t;const r=[];if(void 0!==e.env)if(Td(e.env))for(const[t,n]of Object.entries(e.env))Id(t)||r.push(`env key "${t}" must be a string`),Id(n)||r.push(`env value for "${t}" must be a string`);else r.push("env must be an object if provided");return void 0===e.additional_context||Id(e.additional_context)||r.push("additional_context must be a string if provided"),void 0!==e.continue&&"boolean"!=typeof e.continue&&r.push("continue must be a boolean if provided"),void 0===e.user_message||Id(e.user_message)||r.push("user_message must be a string if provided"),$d(0===r.length,r)},[Rd.sessionEnd]:e=>{const t=pF(e);return t.isValid?$d(!0,[]):t},[Rd.preCompact]:e=>{const t=pF(e);if(!t.isValid)return t;if(null==e||0===Object.keys(e).length)return $d(!0,[]);const r=[];if(!Ad(e))return r.push("PreCompact response must be an object"),$d(!1,r);const n=e;return void 0===n.user_message||(e=>"string"==typeof e)(n.user_message)||r.push("user_message must be a string"),$d(0===r.length,r)},[Rd.subagentStart]:e=>{const t=pF(e);if(!t.isValid)return t;if(!Ad(e))return $d(!1,["Expected an object"]);const r=[],n=e;if(void 0!==n.permission){const e=["allow","deny","ask"];"string"==typeof n.permission&&e.includes(n.permission)||r.push(`Invalid permission value. Expected one of: ${e.join(", ")}, or undefined`)}return void 0===n.user_message||Id(n.user_message)||r.push("user_message must be a string if provided"),$d(0===r.length,r)},[Rd.subagentStop]:e=>{const t=pF(e);if(!t.isValid)return t;const r=[];return Ad(e)&&void 0!==e.followup_message&&"string"!=typeof e.followup_message&&r.push("followup_message must be a string if provided"),$d(0===r.length,r)},[Rd.preToolUse]:e=>{const t=[],r=pF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny","ask"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("Invalid user_message value. Expected a string if provided"),void 0!==e.agent_message&&"string"!=typeof e.agent_message&&t.push("Invalid agent_message value. Expected a string if provided"),void 0!==e.updated_input&&("object"!=typeof e.updated_input||null===e.updated_input||Array.isArray(e.updated_input))&&t.push("Invalid updated_input value. Expected a plain object if provided"),Md(e.additional_context,"additional_context",t),$d(0===t.length,t)},[Rd.postToolUse]:e=>{const t=[],r=pF(e);return r.isValid?(Md(e.additional_context,"additional_context",t),$d(0===t.length,t)):r},[Rd.postToolUseFailure]:e=>{const t=pF(e);if(!t.isValid)return t;const r=[];return Md(e.additional_context,"additional_context",r),$d(0===r.length,r)},[Rd.workspaceOpen]:e=>{const t=pF(e);if(!t.isValid)return t;const r=[];return void 0!==e.pluginPaths&&(Array.isArray(e.pluginPaths)?e.pluginPaths.forEach(((e,t)=>{"string"==typeof e?0===e.trim().length&&r.push(`pluginPaths[${t}] must be a non-empty string`):r.push(`pluginPaths[${t}] must be a string`)})):r.push("pluginPaths must be an array of strings if provided")),$d(0===r.length,r)}},bF=(e,t,r)=>{const n=function(e,t,r){let n;return n=e===Rd.preToolUse?function(e,t){if(!lF(e))return e;const r=e;if(void 0!==r.permission||void 0!==r.user_message||void 0!==r.agent_message||void 0!==r.updated_input)return r;if(!cF(t))return r;const n=uF(e);if(!dF(n,"PreToolUse"))return r;const o={...r};let s=!1;return void 0!==n.permissionDecision&&(o.permission=n.permissionDecision,s=!0),"string"==typeof n.permissionDecisionReason&&(o.user_message=n.permissionDecisionReason,s=!0),lF(n.updatedInput)&&(o.updated_input=n.updatedInput,s=!0),s?o:r}(t,r):e===Rd.stop?hF(t,r,"Stop"):e===Rd.subagentStop?hF(t,r,"SubagentStop"):t,function(e,t,r,n){if(!gF.has(e)||!lF(r)||void 0!==r.additional_context)return r;const o=lF(t)?function(e){return"string"==typeof e.additionalContext?e.additionalContext:void 0}(t)??function(e,t,r){if(!cF(r))return;const n=Ld[e];if(void 0===n)return;const o=uF(t);return dF(o,n)&&"string"==typeof o.additionalContext?o.additionalContext:void 0}(e,t,n):void 0;return void 0===o?r:{...r,additional_context:o}}(e,t,n,r)}(e,t,r),o=(0,vF[e])(n);return o.isValid?{success:!0,data:n}:{success:!1,errors:o.errors}},SF=[Rd.beforeShellExecution,Rd.beforeMCPExecution,Rd.beforeReadFile,Rd.beforeTabFileRead,Rd.subagentStart,Rd.preToolUse],kF=[Rd.workspaceOpen];function _F(e,t){const r=[];return"string"==typeof e&&e.trim()&&r.push(e.trim()),"string"==typeof t&&t.trim()&&r.push(t.trim()),r.length>0?r.join("\n\n---\n\n"):void 0}function CF(e,t){return{..."object"==typeof e&&null!==e?e:{},...t}}function EF(e){return SF.includes(e)}function xF({step:e,command:t,failClosed:r,kind:n}){const o=EF(e);if(!r&&!o)return{shouldNotifyUser:!1};const s=r?"Tool blocked because this hook is configured to fail closed (block when it fails). "+("invalid_json"===n?`Hook "${t}" returned invalid JSON.`:`Hook "${t}" returned invalid response.`):"invalid_json"===n?`Hook "${t}" returned invalid JSON. The command was blocked for safety.`:`Hook "${t}" returned an invalid response for this hook step. The command was blocked for safety.`;return{blockResponse:RF(e,s),cause:r?"script_fail_closed":"permission_hook_invalid_output",reason:s,shouldNotifyUser:o&&!r}}function PF(e,t){return t}function RF(e,t){return EF(e)?PF(0,{permission:"deny",user_message:t}):e===Rd.beforeSubmitPrompt||e===Rd.sessionStart?PF(0,{continue:!1,user_message:t}):e===Rd.stop?PF(0,{}):void 0}function IF(e){try{return{value:JSON.parse(e)}}catch{return}}function TF(e){if("object"!=typeof e||null===e)return!1;const t=e.event;return"backgrounded"===t?.case}function AF(e){if("object"!=typeof e||null===e)return;const t=e.path;return"string"==typeof t&&t.length>0?t:void 0}class $F{cacheCarriersForExecId(e,t){const r=this.carriersByExecId.get(e);if(!(void 0!==r&&r.length>0&&0===t.length))for(this.carriersByExecId.has(e)&&this.carriersByExecId.delete(e),this.carriersByExecId.set(e,t);this.carriersByExecId.size>$F.CARRIERS_BY_EXEC_ID_MAX;){const e=this.carriersByExecId.keys().next().value;if(void 0===e)break;this.carriersByExecId.delete(e)}}constructor(e,t,r,n){this.inner=e,this.wake=r,this.carriersByExecId=new Map,this.inFlightByExecId=new Map,this.resolveDrain="function"==typeof t?t:e=>t,this.skipPathWriteDrain=n?.skipPathWriteDrain,this.onWakeWrittenPath=n?.onWakeWrittenPath,this.forceWrittenPathBeforeDrain=n?.forceWrittenPathBeforeDrain,this.writeBarrierTimeoutMs=n?.writeBarrierTimeoutMs??2e3,this.resolveWriteBarrierTimeoutMs=n?.resolveWriteBarrierTimeoutMs,this.onWriteBarrier=n?.onWriteBarrier}resolveTimeoutMs(){if(void 0!==this.resolveWriteBarrierTimeoutMs)try{const e=this.resolveWriteBarrierTimeoutMs();if("number"==typeof e&&Number.isFinite(e))return e}catch{}return this.writeBarrierTimeoutMs}get(e){return this.wrapImpl(e.symbol,this.inner.get(e))}*entries(){for(const[e,t]of this.inner.entries())yield[e,this.wrapImpl(e.symbol,t)]}wrapImpl(e,t){if(!function(e){return"object"==typeof e&&null!==e&&"execute"in e&&"function"==typeof e.execute}(t))return t;const r=function(e){return e===GT.symbol||e===VT.symbol?{kind:"path"}:e===WT.symbol||e===re.symbol||e===kA.symbol?{kind:"exposed"}:void 0}(e),n=this.resolveDrain,o=this.wake,s=this.skipPathWriteDrain,i=this.forceWrittenPathBeforeDrain,a=()=>this.resolveTimeoutMs(),c=this.onWriteBarrier,l=this.onWakeWrittenPath,u=(e,t)=>{if(void 0!==r&&void 0!==o)try{if("path"===r.kind){const r=AF(e);void 0!==r&&(o.wakeForWrittenPath(r),l?.(r,t))}else o.wakeExposedMounts()}catch{}},d=this.cacheCarriersForExecId.bind(this),h=this.carriersByExecId,p=this.inFlightByExecId,f=async(e,t)=>{const r=t?.hookContextCollector;if(void 0===r)return[];if(!1===t?.deliverAgentStoreConflictNotices)return[];const o=void 0!==t?.execId&&t.execId.length>0?t.execId:void 0;if(void 0!==o){const e=h.get(o);if(void 0!==e)return e.length>0&&r.push(...e),e;const t=p.get(o);if(void 0!==t){const e=await t;return e.length>0&&r.push(...e),e}}const s=async t=>{const r=n(e);let s=[];try{const e=await r.peek();if(s=e.eventIds,e.carriers.length>0)return t.push(...e.carriers),r.ack(e.eventIds),void 0!==o&&d(o,e.carriers),e.carriers;s.length>0&&r.ack(s);const n=[];return void 0!==o&&d(o,n),n}catch{return s.length>0&&r.release(s),[]}};if(void 0===o)return await s(r);const i=s(r);p.set(o,i);try{return await i}finally{p.get(o)===i&&p.delete(o)}};return new Proxy(t,{get:(t,n,o)=>"execute"!==n?Reflect.get(t,n,o):(n,o,l)=>{const d=t.execute.call(t,n,o,l);return"object"==typeof(h=d)&&null!==h&&Symbol.asyncIterator in h&&"function"==typeof h[Symbol.asyncIterator]?async function*(){let t=!1,r=!1,s=!1;try{for await(const r of d)if(e===re.symbol&&TF(r)){if(!t){u(o,n);const e=await f(n,l);t=!0,e.length>0&&(yield new fe.FI({event:{case:"hookContext",value:new fe.Ng({hookAdditionalContexts:[...e]})}}))}yield r}else yield r;s=!0}catch(e){throw r=!0,e}finally{u(o,n),t||r||!s||await f(n,l)}}():function(e){return"object"==typeof e&&null!==e&&"then"in e&&"function"==typeof e.then}(d)?(async()=>{try{const t=await d;return u(o,n),e===GT.symbol&&!0===s?.()&&!0===l?.enableAgentStoreConflictNotices||(await async function(e,t,r,n){const o=e=>{try{n.onWriteBarrier?.(e)}catch{}};if(void 0===e||"path"!==r?.kind)return;const s=AF(t);if(void 0===s)return;if(!(n.timeoutMs>0))return void o({durationMs:0,outcome:"skipped"});const i=Date.now(),a=e(s).then((e=>e),(()=>"error")),c=await Promise.race([a,(0,Nr.cb)(n.timeoutMs).then((()=>"timeout"))]);"not_store_path"!==c&&o({durationMs:Date.now()-i,outcome:c})}(i,o,r,{timeoutMs:a(),onWriteBarrier:c}),await f(n,l)),t}catch(e){throw u(o,n),e}})():(u(o,n),d);var h}})}}function MF(e){return new RegExp(`<${e}(?:\\s[^>]*)?>[\\s\\S]*?`,"gi")}$F.CARRIERS_BY_EXEC_ID_MAX=32,Error,iu.execFileSync,new Map,Ro.constants.O_NOFOLLOW,new Set(["write_conflict","create_conflict","truncate_conflict_failed","conflict_fallback_failed","quota_exceeded","gap"]),new Set(["write_conflict","create_conflict","truncate_conflict_failed","conflict_fallback_failed","quota_exceeded"]),Math.max(1,Math.floor(8192));const DF=["user_info","project_layout","rules","always_applied_workspace_rules","agent_requestable_workspace_rules","user_rules","agent_skills","available_skills","cloud_instructions","cloud_task_instructions","open_and_recently_viewed_files","system_reminder","system-reminder","instructions_update","mcp_instructions","mcp_file_system","mcp_file_system_servers","git_status","agent_transcripts","cursor_rules_context","attached_files","system_notification","task_notification","agent_notification"].map(MF);function OF(e){return function(e,t){let r=e;if(r.includes("<"))for(const e of t)r=r.replace(e,"");return(r.includes("\n\n\n")?r.replace(FF,"\n\n"):r).trim()}(e,DF)}["system_reminder","system-reminder"].map(MF);const FF=/\n{3,}/g;function NF(e){const t=(0,_o.sh)(e.conversationId);if("subagent"===e.kind&&e.parentConversationId){const r=(0,_o.sh)(e.parentConversationId);return`${_o.O2}/${r}/subagents/${t}.${e.ext}`}return`${_o.O2}/${t}/${t}.${e.ext}`}function LF(e){const t=(0,_o.sh)(e.conversationId);return`${_o.O2}/${t}.${e.ext}`}function jF(e){const t=e.exts??["jsonl","txt"],r=e.includeLegacy??!0,n=[],o=e=>{n.includes(e)||n.push(e)};for(const n of t)o(NF({conversationId:e.conversationId,ext:n,kind:e.kind,parentConversationId:e.parentConversationId})),"subagent"===e.kind&&e.parentConversationId&&o(NF({conversationId:e.conversationId,ext:n,kind:"primary"})),r&&o(LF({conversationId:e.conversationId,ext:n}));return n}var UF;!function(e){e.INTERNAL="INTERNAL",e.EXTERNAL="EXTERNAL",e.NO_PREAMBLE="NO_PREAMBLE"}(UF||(UF={}));var BF=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},WF=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function HF(e){switch(e){case c.xyI.AGENT:return"agent";case c.xyI.ASK:return"ask";case c.xyI.PLAN:return"plan";case c.xyI.DEBUG:return"debug";case c.xyI.TRIAGE:return"triage";case c.xyI.MULTITASK:return"multitask";case c.xyI.CUSTOM:return"custom";case c.xyI.UNSPECIFIED:default:return"agent"}}function qF(e,t){return t instanceof Uint8Array?{__type:"Uint8Array",hex:(r=t,Array.from(r).map((e=>e.toString(16).padStart(2,"0"))).join(""))}:"bigint"==typeof t?t.toString():t;var r}function zF(e,t){return function(e){return"object"==typeof e&&null!==e&&"__type"in e&&"Uint8Array"===e.__type&&"hex"in e&&"string"==typeof e.hex}(t)?`[Binary data omitted from transcript: ${t.hex.length/2} bytes]`:t}const GF=new TextEncoder,VF=new TextDecoder,KF=new class{serialize(e){const t=JSON.stringify(e,qF);return GF.encode(t)}deserialize(e){const t=VF.decode(e);return t.includes('"__type":"Uint8Array"')?JSON.parse(t,zF):JSON.parse(t)}};function JF(e){const t=e.providerOptions;return!0===t?.cursor?.isSummary}function ZF(e){return"system"!==e.role&&!JF(e)}function XF(e,t){return"user"===e.role&&"user"===t.role}async function QF(e,t,r){const n=await t.getBlob(e,r);return n?c.Anz.fromBinary(n).summarizedMessages:[]}async function YF(e,t,r,n){const o=await t.getBlob(e,r);if(o){if(o.length>5e6)return n.omittedOversizeBlobCount++,n.omittedOversizeBlobBytes+=o.length,n.largestOmittedOversizeBlobBytes=Math.max(n.largestOmittedOversizeBlobBytes,o.length),{role:"assistant",content:`[Oversize transcript blob omitted: ${s=o.length,`${(s/1e6).toFixed(1)} MB`}]`};var s;try{const e=performance.now(),t=KF.deserialize(o);return n.totalDeserializeDurationMs+=performance.now()-e,n.hydratedBlobCount++,n.hydratedBlobBytes+=o.length,n.largestHydratedBlobBytes=Math.max(n.largestHydratedBlobBytes,o.length),t}catch{return}}}async function eN(e,t,r){const n={messages:[],hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0};for(const o of r){const r=await YF(e,t,o,n);r&&n.messages.push(r)}return n}async function tN(e,t,r,n,o){const s=[];let i=0;const a=()=>{const o=YF(e,t,r[i++],n);o.catch((()=>{})),s.push(o)};for(;i{let r;return r="string"==typeof t?t:"object"==typeof t&&null!==t?JSON.stringify(t):String(t),` ${e}: ${r}`})).join("\n")}`}(e.args)}`;case"tool-result":return`[Tool result] ${e.toolName}`;default:return""}}function nN(e){return OF(e)}const oN=/[\s\S]*?<\/think>/gi,sN=/[\s\S]*?<\/thinking>/gi,iN=/\n{3,}/g;function aN(e){let t=e;return t.includes("<")&&(t=t.replace(oN,"").replace(sN,"")),(t.includes("\n\n\n")?t.replace(iN,"\n\n"):t).trim()}function cN(e,t,r){if(void 0===e)return"";if("string"==typeof e){const n=t?nN(e):e;return r?aN(n):n}return e.map((e=>{if(r&&"text"===e.type){const r=aN(t?nN(e.text):e.text);return rN({...e,text:r},!1)}return rN(e,t)})).filter(Boolean).join("\n")}function lN(e,t){const r={role:e.role},n=e.content;if("string"==typeof n){const o=t?nN(n):n,s="assistant"===e.role?aN(o):o;s.trim()&&(r.text=s)}else if(Array.isArray(n)){const o=[],s=[],i=[];let a;for(const r of n)switch(r.type){case"text":{const n=t?nN(r.text):r.text,s="assistant"===e.role?aN(n):n;s.trim()&&o.push(s);break}case"reasoning":r.text.trim()&&s.push(r.text);break;case"redacted-reasoning":s.push("[REDACTED]");break;case"image":o.push("[Image]");break;case"file":o.push(r.filename?`[File: ${r.filename}]`:"[File]");break;case"tool-call":i.push({toolName:r.toolName,args:r.args});break;case"tool-result":a={toolName:r.toolName}}o.length>0&&(r.text=o.join("\n")),s.length>0&&(r.thinking=s.join("\n")),i.length>0&&(r.toolCalls=i),a&&(r.toolResult=a)}return r}function uN(e){return e.endsWith("\n")?e:`${e}\n`}function dN(e){const{turnEnded:t}=e,r=[],n={},o=[];return void 0!==t&&(r.push(function(e){switch(e.status){case"success":return"Turn ended: success.";case"error":return`Turn ended: error: ${e.error}`;case"aborted":return e.error?`Turn ended: aborted: ${e.error}`:"Turn ended: aborted.";default:return e}}(t)),n.turnEnded=t,o.push(JSON.stringify({type:"turn_ended",...t}))),{textSuffixes:r,jsonFields:n,jsonlLines:o}}function hN(e){if("system"===e.role||JF(e))return;const t=lN(e,"user"===e.role),r=[],n=[];if(t.text&&n.push(t.text),t.thinking&&n.push(t.thinking),n.length>0&&r.push({type:"text",text:n.join("\n\n")}),t.toolCalls)for(const e of t.toolCalls)r.push({type:"tool_use",name:e.toolName,input:e.args});if(0===r.length)return;const o={role:e.role,message:{content:r}};return JSON.stringify(o)}class pN{constructor(e,t,r,n={}){this.projectDir=e,this.blobStore=t,this.writeFile=r,this.options={writeText:n.writeText??!0,writeJson:n.writeJson??!1,writeJsonl:n.writeJsonl??!1,pathResolver:n.pathResolver,appendFile:n.appendFile,streamFullJsonlWrites:n.streamFullJsonlWrites??!1,fallbackToFullWriteOnIncrementalFailure:n.fallbackToFullWriteOnIncrementalFailure??!0}}resolveFilePath(e,t){if(this.options.pathResolver)return this.options.pathResolver(e,t);const r=NF({conversationId:e,ext:t,kind:"primary"});return`${this.projectDir}/${r}`}async writeFromStateFull(e,t,r,n={}){const o={stack:[],error:void 0,hasError:!1};try{const s=BF(o,(0,D.VI)(e.withName("writeFromState")),!1);try{const{overviewFactory:e}=n,o=dN(n),{appendFile:i,streamFullJsonlWrites:a,writeJsonl:c,writeText:l,writeJson:u}=this.options;if(i&&a&&c&&!l&&!u&&!e)try{return await this.writeJsonlStreamed(s,{state:t,filePath:this.resolveFilePath(r,"jsonl"),appendFile:i,terminalLines:o.jsonlLines}),!0}catch(e){console.error("[TranscriptStore] Streamed transcript write failed, retrying as a single write:",e)}const d=await async function(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=BF(n,(0,D.VI)(e.withName("hydrateSummaryArchives")),!1);let s=0;const i=(0,D.OA)(o.ctx),a=[];let c=0,l=0,u=0,d=0,h=0,p=0,f=0;const m=await Promise.all(r.summaryArchives.map((async e=>{s++;try{const r=await QF(i,t,e);return s+=r.length,await eN(i,t,r)}catch{return{messages:[],hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0}}})));for(const e of m)a.push(...e.messages),c+=e.hydratedBlobCount,l+=e.hydratedBlobBytes,u=Math.max(u,e.largestHydratedBlobBytes),d+=e.totalDeserializeDurationMs,h+=e.omittedOversizeBlobCount,p+=e.omittedOversizeBlobBytes,f=Math.max(f,e.largestOmittedOversizeBlobBytes);o.span.setAttribute("getBlobCount",s),o.span.setAttribute("hydratedBlobCount",c),o.span.setAttribute("hydratedBlobBytes",l),o.span.setAttribute("largestHydratedBlobBytes",u),o.span.setAttribute("totalDeserializeDurationMs",d),o.span.setAttribute("omittedOversizeBlobCount",h),o.span.setAttribute("omittedOversizeBlobBytes",p),o.span.setAttribute("largestOmittedOversizeBlobBytes",f);const g=BF(n,(0,D.VI)(e.withName("hydratePromptMessages")),!1),w=await eN(i,t,r.rootPromptMessagesJson);g.span.setAttribute("getBlobCount",r.rootPromptMessagesJson.length),g.span.setAttribute("hydratedBlobCount",w.hydratedBlobCount),g.span.setAttribute("hydratedBlobBytes",w.hydratedBlobBytes),g.span.setAttribute("largestHydratedBlobBytes",w.largestHydratedBlobBytes),g.span.setAttribute("totalDeserializeDurationMs",w.totalDeserializeDurationMs),g.span.setAttribute("omittedOversizeBlobCount",w.omittedOversizeBlobCount),g.span.setAttribute("omittedOversizeBlobBytes",w.omittedOversizeBlobBytes),g.span.setAttribute("largestOmittedOversizeBlobBytes",w.largestOmittedOversizeBlobBytes);const y=w.messages.filter(ZF);return a.push(...y),a}catch(e){n.error=e,n.hasError=!0}finally{WF(n)}}(s.ctx,this.blobStore,t);if(0===d.length&&0===o.jsonlLines.length)return!0;let h;if((this.options.writeText||e)&&(h=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&"user"===t[0].role&&"user"===t[1].role&&(t=t.slice(1));const r=[];for(const e of t){const t="user"===e.role,n="assistant"===e.role,o=cN(e.content,t,n);o.trim()&&("tool"===e.role?r.push(o):r.push(`${e.role}:\n${o}`))}return r.join("\n\n")}(d)),this.options.writeText){const e=h??"",t=o.textSuffixes.length>0?e.trim().length>0?`${e}\n\n${o.textSuffixes.join("\n")}`:o.textSuffixes.join("\n"):e;t.trim()&&await this.writeFile(this.resolveFilePath(r,"txt"),t)}if(this.options.writeJson){const e=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&"user"===t[0].role&&"user"===t[1].role&&(t=t.slice(1));const r=[];for(const e of t){const t=lN(e,"user"===e.role);(t.text||t.thinking||t.toolCalls||t.toolResult)&&r.push(t)}return 0===r.length?"":JSON.stringify(r,null,2)}(d);if(e||o.jsonlLines.length>0){const n={mode:HF(t.mode),messages:e?JSON.parse(e):[],...o.jsonFields};await this.writeFile(this.resolveFilePath(r,"json"),JSON.stringify(n,null,2))}}if(this.options.writeJsonl){const t=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&XF(t[0],t[1])&&(t=t.slice(1));const r=[];for(const e of t){const t=hN(e);t&&r.push(t)}return r.join("\n")}(d);let n=[t,...o.jsonlLines].filter((e=>e.length>0)).join("\n");if(n&&e&&h?.trim())try{const t=(await e(h)).trim();t&&(n=function(e,t){const r={type:"metadata",metadata:{overview:t}};return`${JSON.stringify(r)}\n${e}`}(n,t))}catch(e){console.error("[TranscriptStore] Failed to generate transcript overview:",e)}n&&await this.writeFile(this.resolveFilePath(r,"jsonl"),uN(n))}return!0}catch(e){return console.error("[TranscriptStore] Failed to write transcript:",e),!1}}catch(e){o.error=e,o.hasError=!0}finally{WF(o)}}async writeJsonlStreamed(e,t){const{filePath:r,appendFile:n}=t;let o=[],s=0,i=0,a=0;const c=async()=>{if(0===o.length)return;const e=`${o.join("\n")}\n`;o=[],s=0,0===i?await this.writeFile(r,e):await n(r,e),i++,a+=e.length},l=async e=>{e&&(o.push(e),s+=e.length+1,s>=1e6&&await c())};let u,d=0;const h=await async function(e,t,r,n){const o={hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0};for(const s of r.summaryArchives){let r;try{r=await QF(e,t,s)}catch{continue}await tN(e,t,r,o,{skipFailedReads:!0,visit:n})}return await tN(e,t,r.rootPromptMessagesJson,o,{skipFailedReads:!1,visit:async e=>{ZF(e)&&await n(e)}}),o}((0,D.OA)(e.ctx),this.blobStore,t.state,(async e=>{"system"!==e.role&&(d++,1!==d?(2===d&&u&&(XF(u,e)||await l(hN(u)),u=void 0),await l(hN(e))):u=e)}));u&&await l(hN(u));for(const e of t.terminalLines)await l(e);await c(),e.span.setAttribute("streamed",!0),e.span.setAttribute("chunkCount",i),e.span.setAttribute("writtenChars",a),e.span.setAttribute("hydratedBlobCount",h.hydratedBlobCount),e.span.setAttribute("hydratedBlobBytes",h.hydratedBlobBytes),e.span.setAttribute("largestHydratedBlobBytes",h.largestHydratedBlobBytes),e.span.setAttribute("totalDeserializeDurationMs",h.totalDeserializeDurationMs),e.span.setAttribute("omittedOversizeBlobCount",h.omittedOversizeBlobCount),e.span.setAttribute("omittedOversizeBlobBytes",h.omittedOversizeBlobBytes),e.span.setAttribute("largestOmittedOversizeBlobBytes",h.largestOmittedOversizeBlobBytes)}async writeFromStateIncremental(e,t,r,n,o={}){const s={stack:[],error:void 0,hasError:!1};try{const i=t.rootPromptMessagesJson.length,a=dN(o),c=a.jsonlLines.length>0;if(i===n&&!c&&!o.overviewFactory)return i;const l=this.options.appendFile;if(!(l&&this.options.writeJsonl&&!this.options.writeText&&!this.options.writeJson&&n>0&&i>=n&&(i>n||c))||o.overviewFactory)return await this.writeFromStateFull(e,t,r,o)?i:0;const u=BF(s,(0,D.VI)(e.withName("writeFromStateIncremental")),!1);if(i===n&&c)try{return await l(this.resolveFilePath(r,"jsonl"),uN(a.jsonlLines.join("\n"))),i}catch(n){return console.error(this.options.fallbackToFullWriteOnIncrementalFailure?"[TranscriptStore] Failed to append transcript, falling back to full write:":"[TranscriptStore] Failed to append transcript:",n),this.options.fallbackToFullWriteOnIncrementalFailure?await this.writeFromStateFull(e,t,r,o)?i:0:0}try{const e=t.rootPromptMessagesJson.slice(n),o=await eN(u.ctx,this.blobStore,e);u.span.setAttribute("hydratedBlobCount",o.hydratedBlobCount),u.span.setAttribute("hydratedBlobBytes",o.hydratedBlobBytes),u.span.setAttribute("largestHydratedBlobBytes",o.largestHydratedBlobBytes),u.span.setAttribute("totalDeserializeDurationMs",o.totalDeserializeDurationMs),u.span.setAttribute("omittedOversizeBlobCount",o.omittedOversizeBlobCount),u.span.setAttribute("omittedOversizeBlobBytes",o.omittedOversizeBlobBytes),u.span.setAttribute("largestOmittedOversizeBlobBytes",o.largestOmittedOversizeBlobBytes);const s=[];for(const e of o.messages){const t=hN(e);t&&s.push(t)}if(s.push(...a.jsonlLines),s.length>0){const e=uN(s.join("\n"));await l(this.resolveFilePath(r,"jsonl"),e)}return i}catch(n){return console.error(this.options.fallbackToFullWriteOnIncrementalFailure?"[TranscriptStore] Failed to append transcript, falling back to full write:":"[TranscriptStore] Failed to append transcript:",n),this.options.fallbackToFullWriteOnIncrementalFailure?await this.writeFromStateFull(e,t,r,o)?i:0:0}}catch(e){s.error=e,s.hasError=!0}finally{WF(s)}}}function fN(e,t){const r=function(e){return"object"==typeof e&&null!==e}(e)&&t in e?e[t]:void 0;return"string"==typeof r&&""!==r?r:void 0}function mN(e,t){return e.filter((e=>function(e,t){if(!e.matcher||""===e.matcher||"*"===e.matcher)return!0;if(void 0===t)return!0;try{return new RegExp(e.matcher).test(t)}catch{return!0}}(e,t)))}function gN(e){return`Tool blocked because this hook is configured to fail closed (block when it fails). ${e}`}function wN(e){return Object.values(Rd).some((t=>t===e))}function yN(e){switch(e??(0,o.platform)()){case"darwin":return s.join("/Library","Application Support","Cursor","hooks.json");case"win32":return s.join("C:\\","ProgramData","Cursor","hooks.json");default:return s.join("/etc","cursor","hooks.json")}}function vN(e){return wF(e)?`prompt:${e.prompt}`:`command:${e.command}`}function bN(e){return(e.repoHooks??[]).flatMap((e=>[e.projectHooks,e.claudeProjectHooks,e.claudeProjectLocalHooks]))}class SN{constructor(e,t,r){this.fileReader=e,this.paths=t,this.logger=r||{warn:e=>console.warn(`[hooks] ${e}`),info:e=>{}}}async load(e={}){const{loadProjectHooks:t=!0}=e,r={errors:[],configDirs:{}},n=this.paths.projectConfigPath??this.paths.claudeProjectConfigPath??this.paths.claudeProjectLocalConfigPath,o=n?s.dirname(s.dirname(n)):void 0,i=(e,t)=>{if(!e||!o)return;if(t)return o;const r=s.relative(s.resolve(o),s.resolve(e));return".."===r||r.startsWith(`..${s.sep}`)||s.isAbsolute(r)?void 0:o},a=async(e,t,n,o,i,a,c,l)=>{if(e)try{if(!await this.fileReader.exists(e))return;if(c&&this.fileReader.pathContainsSymlink&&await this.fileReader.pathContainsSymlink(e,c))return r.errors.push({source:t,message:`${i} at ${e}: refusing to load config path that contains a symlink`}),void this.logger.warn(`Refusing to load ${a} config via symlink path: ${e}`);const u=await this.fileReader.readFile(e);if(!u)return;const{config:d,error:h}=l(u);if(d){switch(n){case"enterpriseHooks":r.enterpriseHooks=d;break;case"teamHooks":r.teamHooks=d;break;case"userHooks":r.userHooks=d;break;case"projectHooks":r.projectHooks=d;break;case"claudeUserHooks":r.claudeUserHooks=d;break;case"claudeProjectHooks":r.claudeProjectHooks=d;break;case"claudeProjectLocalHooks":r.claudeProjectLocalHooks=d;break;default:return}((e,t)=>{r.configDirs[e]=s.dirname(t)})(o,e)}else h&&r.errors.push({source:t,message:`${i} at ${e}: ${h}`})}catch(e){r.errors.push({source:t,message:`Error accessing ${a} config file: ${String(e)}`})}},c=[{path:this.paths.enterpriseConfigPath,source:"enterprise",resultKey:"enterpriseHooks",configDirKey:"enterprise",parsePrefix:"Enterprise hooks.json",accessLabel:"enterprise",symlinkCheckRoot:i(this.paths.enterpriseConfigPath,!1)},{path:this.paths.teamConfigPath,source:"team",resultKey:"teamHooks",configDirKey:"team",parsePrefix:"Team hooks.json",accessLabel:"team",symlinkCheckRoot:i(this.paths.teamConfigPath,!1)},{path:this.paths.userConfigPath,source:"user",resultKey:"userHooks",configDirKey:"user",parsePrefix:"User hooks.json",accessLabel:"user",symlinkCheckRoot:i(this.paths.userConfigPath,!1)},{path:t?this.paths.projectConfigPath:void 0,source:"project",resultKey:"projectHooks",configDirKey:"project",parsePrefix:"Project hooks.json",accessLabel:"project",symlinkCheckRoot:i(this.paths.projectConfigPath,!0)}];for(const e of c)await a(e.path,e.source,e.resultKey,e.configDirKey,e.parsePrefix,e.accessLabel,e.symlinkCheckRoot,(t=>this.parseAndValidate(t,e.source)));const l=[{path:this.paths.claudeUserConfigPath,source:"claude-user",resultKey:"claudeUserHooks",configDirKey:"claudeUser",label:"user",symlinkCheckRoot:i(this.paths.claudeUserConfigPath,!1)},{path:t?this.paths.claudeProjectConfigPath:void 0,source:"claude-project",resultKey:"claudeProjectHooks",configDirKey:"claudeProject",label:"project",symlinkCheckRoot:i(this.paths.claudeProjectConfigPath,!0)},{path:t?this.paths.claudeProjectLocalConfigPath:void 0,source:"claude-project-local",resultKey:"claudeProjectLocalHooks",configDirKey:"claudeProjectLocal",label:"project local",symlinkCheckRoot:i(this.paths.claudeProjectLocalConfigPath,!0)}];for(const e of l)await a(e.path,e.source,e.resultKey,e.configDirKey,`Claude ${e.label} settings.json`,`Claude ${e.label}`,e.symlinkCheckRoot,(t=>this.parseClaudeConfig(t,e.source)));return function(e){const{cursorConfigs:t,claudeConfigs:r,logger:n}=e,o=new Map;for(const e of t)if(e?.hooks)for(const[t,r]of Object.entries(e.hooks)){if(!r)continue;let e=o.get(t);e||(e=new Set,o.set(t,e));for(const t of r)e.add(vN(t))}for(const{config:e,source:t}of r)if(e?.hooks)for(const[r,s]of Object.entries(e.hooks)){if(!s)continue;const i=o.get(r);if(!i||0===i.size)continue;const a=s.filter((e=>{const o=vN(e);return!i.has(o)||(n?.info(`Removed duplicate ${t} hook for ${r}: ${o}`),!1)}));a.length!==s.length&&(e.hooks[r]=a)}}({cursorConfigs:[r.enterpriseHooks,r.teamHooks,r.userHooks,r.projectHooks],claudeConfigs:[{config:r.claudeUserHooks,source:"claude-user"},{config:r.claudeProjectHooks,source:"claude-project"},{config:r.claudeProjectLocalHooks,source:"claude-project-local"}],logger:this.logger}),r}parseClaudeConfig(e,t){try{const t=JSON.parse(e);if(!function(e,t={}){if(!Ad(e))return!1;if(!("hooks"in e))return!1;const r=e.hooks;if(!Ad(r))return!1;const n=r;for(const[e,r]of Object.entries(n))if(e in Nd&&Array.isArray(r)){const n=!0===t.allowMatcherlessStop&&"Stop"===e;for(const e of r)if(Ad(e)&&"hooks"in e&&Array.isArray(e.hooks)&&("matcher"in e||n))return!0}return!1}(t))return{};const r=t.hooks;if(!r||0===Object.keys(r).length)return{};const n=Yd(r,this.logger),o=Fd(n);return o.isValid?{config:n}:{error:`Invalid transformed config: ${o.errors.join("; ")}`}}catch(e){return{error:`Failed to parse JSON: ${String(e)}`}}}parseAndValidate(e,t){try{const n=this.parseJSONC(e),o=Fd(n);return o.isValid?"object"==typeof(r=n)&&null!==r&&"version"in r&&"number"==typeof r.version&&"hooks"in r&&"object"==typeof r.hooks&&null!==r.hooks&&!Array.isArray(r.hooks)?{config:n}:{error:`Invalid ${t} config: missing 'hooks' property`}:{error:`Invalid ${t} config: ${o.errors.join("; ")}`}}catch(e){return{error:`Failed to parse ${t} config JSON: ${String(e)}`}}var r}parseJSONC(e){let t=e.replace(/\/\/.*$/gm,"");return t=t.replace(/\/\*[\s\S]*?\*\//g,""),JSON.parse(t)}static getConfiguredSteps(e){const t=new Set,r=[e.enterpriseHooks,e.teamHooks,e.userHooks,e.projectHooks,e.claudeUserHooks,e.claudeProjectHooks,e.claudeProjectLocalHooks,...bN(e)];for(const e of r)if(e?.hooks)for(const r of Object.keys(e.hooks))wN(r)&&t.add(r);for(const r of e.pluginHooks??[])for(const e of Object.keys(r.config.hooks))wN(e)&&t.add(e);return t}}const kN="Read",_N="Write",CN="Delete",EN="List",xN="Grep",PN="Shell",RN="ReadLints";function IN(e,t){if("object"==typeof e&&null!==e)return Object.getOwnPropertyDescriptor(e,t)?.value}const TN=new Set([kN,_N,CN,EN,xN,RN]);function AN(e){const t=IN(e,"tool_name"),r=[IN(e,"file_path"),"string"==typeof t&&TN.has(t)?IN(IN(e,"tool_input"),"file_path"):void 0];for(const e of r)if("string"==typeof e&&e.length>0)return e}const $N=(0,d.h)("cli-hooks-executor");function MN(e){try{return(0,Ro.statSync)(e).isFile()}catch{return!1}}const DN="\nJSON Parse Error: Error: Failed to parse hook stdout as JSON";function ON(e,t){for(const[r,n]of Object.entries(e))if(r===t)return n}function FN(e,t){const r=ON(e,t);if("string"==typeof r||null===r)return r}class NN{constructor(e,t,r,n,o,s,i,a){this.workspacePath=t,this.globalContext=r,this.shellExecutor=n,this.promptHookClient=o,this.onHookExecution=i,this.options=a,this.sessionEnvById=new Map,this.sessionUserEmailById=new Map,this.activeSessionIdsByConversationId=new Map,this.transcriptParentConversationIdById=new Map,this.configReadyPromises=[],this.config=e,s&&this.addConfigReadyPromise(s)}addConfigReadyPromise(e){this.configReadyPromises.push(e.catch((()=>{})))}reportCommandFailure(e,t){if(void 0!==e)try{e(t)}catch{}}finishHookRun(e,t,r,n){const o=e.transportMode??("prompt"===e.hookType?"prompt":this.getCommandHookPayloadTransportMode());try{this.onHookExecution?.({...e,transportMode:o})}catch{}const s=this.options?.onHookRun;if(void 0===s)return;const i=n.exitCode??e.exitCode,a="spawn_error"===(c=e.errorClass)?"shell_exec_transport_error":"prompt_error"===c?"prompt_execution_error":void 0;var c;try{s({step:e.hookStep,script:t,source:e.hookSource,...void 0===e.pluginId?{}:{pluginId:e.pluginId},request:r,response:n.response??null,status:e.status,durationMs:e.latencyMs,...void 0===i?{}:{exitCode:i},stderr:n.stderr,transportMode:o,configuredTimeoutSec:t.timeout??60,timedOut:!0===e.timedOut,...void 0===a?{}:{failureType:a}})}catch{}}getCommandHookPayloadTransportMode(){return"stdin"===this.options?.commandHookPayloadTransport?"win32"===process.platform?"windows_temp_file":"stdin":"argv_heredoc"}shouldUseCommandHookDirectStdinTransport(){return"stdin"===this.getCommandHookPayloadTransportMode()}async writeCommandHookStdinPayload(e,t){if(!e)throw new Error("Hook stdin transport was requested, but the executor did not provide stdin");try{e.end(Buffer.from(t,"utf8"))}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;if("EPIPE"===t||"ERR_STREAM_DESTROYED"===t||"ERR_STREAM_PREMATURE_CLOSE"===t)return;throw e}try{await(0,lh.finished)(e)}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;if("EPIPE"===t||"ERR_STREAM_DESTROYED"===t||"ERR_STREAM_PREMATURE_CLOSE"===t)return;throw e}}updateConfig(e){this.config=e}beginSessionEnvironment(e,t){this.sessionEnvById.delete(e.sessionId),this.sessionUserEmailById.delete(e.sessionId);const r=this.activeSessionIdsByConversationId.get(e.conversationId)??[];this.activeSessionIdsByConversationId.set(e.conversationId,r.filter((t=>t!==e.sessionId)).concat(e.sessionId));const n=t?.userEmail?.trim()??"";n.length>0&&this.sessionUserEmailById.set(e.sessionId,n)}setSessionUserEmail(e,t){const r=t?.trim()??"";0!==r.length&&this.sessionUserEmailById.set(e.sessionId,r)}setSessionEnvironment(e,t){void 0===t?this.sessionEnv={...this.sessionEnv,...e}:this.sessionEnvById.set(t.sessionId,{...this.sessionEnvById.get(t.sessionId),...e})}clearSessionEnvironment(e){if(void 0===e)this.sessionEnv=void 0;else{this.sessionEnvById.delete(e.sessionId),this.sessionUserEmailById.delete(e.sessionId);const t=(this.activeSessionIdsByConversationId.get(e.conversationId)??[]).filter((t=>t!==e.sessionId));0===t.length?this.activeSessionIdsByConversationId.delete(e.conversationId):this.activeSessionIdsByConversationId.set(e.conversationId,t)}}resolveUserEmail(e){const{conversation_id:t,session_id:r}=e;if(void 0!==r&&this.sessionUserEmailById.has(r))return this.sessionUserEmailById.get(r)??null;if(void 0!==t){const e=this.activeSessionIdsByConversationId.get(t)?.at(-1);if(void 0!==e){const t=this.sessionUserEmailById.get(e);if(void 0!==t)return t}}return this.globalContext.user_email}setTranscriptParentConversationId(e,t){this.transcriptParentConversationIdById.set(e,t)}async getTranscriptPathIfExists(e){try{const t=(0,_o.Rv)((0,o.homedir)(),this.workspacePath),r=this.transcriptParentConversationIdById.get(e),n=jF(r?{conversationId:e,kind:"subagent",parentConversationId:r}:{conversationId:e,kind:"primary"}).map((e=>(0,s.join)(t,e)));for(const e of n)try{return await(0,xo.access)(e),e}catch{}return null}catch{return null}}async getSubagentTranscriptPathIfExists(e){const{subagentId:t,parentConversationId:r}=e;try{const e=(0,_o.Rv)((0,o.homedir)(),this.workspacePath),n=jF({conversationId:t,kind:"subagent",parentConversationId:r}).map((t=>(0,s.join)(e,t)));for(const e of n)try{return await(0,xo.access)(e),e}catch{}return null}catch{return null}}hasHooksForStep(e){return[this.config.enterpriseHooks,this.config.teamHooks,this.config.userHooks,this.config.projectHooks,this.options?.runtimeHooks,this.config.claudeUserHooks,this.config.claudeProjectHooks,this.config.claudeProjectLocalHooks,...bN(this.config),...(this.config.pluginHooks??[]).map((e=>e.config))].some((t=>{const r=t?.hooks[e];return void 0!==r&&r.length>0}))}hasFailClosedHooksForStep(e,t){const r=[this.config.enterpriseHooks,this.config.teamHooks,this.config.projectHooks,...(this.config.repoHooks??[]).map((e=>e.projectHooks)),this.config.userHooks,this.options?.runtimeHooks];for(const n of r){const r=n?.hooks[e];if(r&&(t?mN(r,t):r).some((e=>!0===e.failClosed)))return!0}for(const r of this.config.pluginHooks??[]){const n=r.config.hooks[e];if(n&&(t?mN(n,t):n).some((e=>yF(e)&&!0===e.failClosed)))return!0}return!1}configuredHookDirectory(e){const t=this.config.configDirs;switch(e){case"enterprise":return t?.enterprise;case"team":return t?.team;case"user":return t?.user;case"claude-user":return t?.claudeUser;default:return}}cwdForHookSource(e,t){if(void 0!==e?.cwd&&e.cwd.length>0)return e.cwd;const r=this.configuredHookDirectory(t.source);if(void 0!==r&&r.length>0)return r;const n=e?.cwdForSource?.(t.source);return void 0!==n&&n.length>0?n:t.fallback}getCwdForSource(e){const t=this.config.configDirs;switch(e){case"enterprise":return t?.enterprise??this.workspacePath;case"team":return t?.team??this.workspacePath;case"project":case"claude-project":case"claude-project-local":case"claude-plugin":case"runtime":default:return this.workspacePath;case"user":return t?.user??this.workspacePath;case"claude-user":return t?.claudeUser??this.workspacePath}}buildHookEnvironment(e){const{transcriptPath:t,sessionId:r,conversationId:n,executionEnv:o}=e,s=this.resolveUserEmail({conversation_id:n,session_id:r});return{CURSOR_PROJECT_DIR:this.workspacePath,CURSOR_VERSION:this.globalContext.cursor_version,...s&&{CURSOR_USER_EMAIL:s},...t&&{CURSOR_TRANSCRIPT_PATH:t},CLAUDE_PROJECT_DIR:this.workspacePath,...this.sessionEnv,...void 0!==r?this.sessionEnvById.get(r):void 0,...o}}shouldSkipHookDueToLoopLimit(e,t,r){if("stop"!==e&&"subagentStop"!==e)return!1;const n=ON(r,"loop_count");if("number"!=typeof n)return!1;const o=n,s=t.loop_limit;return null!==s&&(void 0===s?o>=5:o>=s)}async executeHookForStep(e,t,r){this.configReadyPromises.length>0&&await this.whenConfigReady();const n=function(e){return kF.includes(e)}(e),o=t,i=n?null:o.conversation_id?await this.getTranscriptPathIfExists(o.conversation_id):null;let a;if(e===Rd.subagentStop){const e=FN(t,"subagent_id"),r=FN(t,"parent_conversation_id");a=e?await this.getSubagentTranscriptPathIfExists({subagentId:e,parentConversationId:r??void 0}):null}const c=n?void 0:o.session_id??o.conversation_id,l={...t,...void 0!==c&&{session_id:c},hook_event_name:e,cursor_version:this.globalContext.cursor_version,workspace_roots:[...new Set([this.workspacePath,...(this.config.repoHooks??[]).map((e=>e.repoPath))])],user_email:this.resolveUserEmail(o),...!n&&{transcript_path:i},...e===Rd.subagentStop&&{agent_transcript_path:a??null}},u=function(e,t){switch(e){case"beforeShellExecution":case"afterShellExecution":return fN(t,"command");case"beforeMCPExecution":case"afterMCPExecution":{const e=fN(t,"tool_name");return e?`MCP:${e}`:void 0}case"beforeReadFile":return"Read";case"afterFileEdit":return"Write";case"beforeTabFileRead":return"TabRead";case"afterTabFileEdit":return"TabWrite";case"beforeSubmitPrompt":return"UserPromptSubmit";case"stop":return"Stop";case"afterAgentResponse":return"AgentResponse";case"afterAgentThought":return"AgentThought";case"subagentStart":case"subagentStop":return fN(t,"subagent_type");case"preToolUse":case"postToolUse":case"postToolUseFailure":return fN(t,"tool_name");default:return}}(e,l),d=[],h=(e,t,n)=>{if(!e)return;const o=mN(e,u),s=this.cwdForHookSource(r,{source:t,fallback:n??this.getCwdForSource(t)}),i=void 0===n?r?.env:{CURSOR_PROJECT_DIR:n,CLAUDE_PROJECT_DIR:n,...r?.env};for(const e of o)wF(e)?this.promptHookClient&&d.push({type:"prompt",script:e,source:t}):yF(e)&&d.push({type:"command",script:e,cwd:s,env:i,source:t})},p=await async function({repoHooks:e,targetPath:t,workspacePath:r}){if(e.length<2||void 0===t||0===t.length)return e;const n=(0,ts.o1)(t,r),[o,i,a]=await Promise.all([(0,ts.DN)(n),(0,ts.DN)(s.dirname(n)),Promise.all(e.map((async e=>await(0,ts.DN)(e.repoPath)??s.resolve(e.repoPath))))]);if(null===o||null===i)return e;const c=t=>{let r;return e.forEach(((e,n)=>{const o=a[n],i=s.relative(o,t);(""===i||".."!==i&&!i.startsWith(`..${s.sep}`)&&!s.isAbsolute(i))&&(void 0===r||o.length>r.repoPath.length)&&(r={repo:e,repoPath:o})})),r?.repo},l=new Set;for(const t of[o,s.join(i,s.basename(n))]){const r=c(t);if(void 0===r)return e;l.add(r)}return e.filter((e=>l.has(e)))}({repoHooks:this.config.repoHooks??[],targetPath:AN(t),workspacePath:this.workspacePath});h(this.config.enterpriseHooks?.hooks[e],"enterprise"),h(this.config.teamHooks?.hooks[e],"team"),h(this.config.projectHooks?.hooks[e],"project");for(const t of p)h(t.projectHooks?.hooks[e],"project",t.repoPath);h(this.config.userHooks?.hooks[e],"user"),h(this.options?.runtimeHooks?.hooks[e],"runtime"),h(this.config.claudeProjectLocalHooks?.hooks[e],"claude-project-local"),h(this.config.claudeProjectHooks?.hooks[e],"claude-project");for(const t of p)h(t.claudeProjectLocalHooks?.hooks[e],"claude-project-local",t.repoPath),h(t.claudeProjectHooks?.hooks[e],"claude-project",t.repoPath);h(this.config.claudeUserHooks?.hooks[e],"claude-user");for(const t of this.config.pluginHooks??[]){const n=t.config.hooks[e];if(!n?.length)continue;const o=r?.cwd??(e===Rd.stop||e===Rd.subagentStop?this.workspacePath:t.installPath),s={...void 0!==t.plugin&&{plugin:t.plugin},...void 0!==t.marketplace&&{marketplace:t.marketplace},...void 0!==t.pluginId&&{pluginId:t.pluginId},...void 0!==t.marketplaceId&&{marketplaceId:t.marketplaceId}};for(const e of mN(n,u))yF(e)&&d.push({type:"command",script:e,cwd:o,env:r?.env,source:"claude-plugin",attribution:s,pluginInstallPath:t.installPath})}if(0!==d.length)return this.executeAllAndMerge(e,d,l,r?.onCommandFailure)}async whenConfigReady(){await Promise.all(this.configReadyPromises)}async executeAllAndMerge(e,t,r,n){let o;const s=()=>o??=function(e){const t=JSON.stringify(e);return{json:t,payloadSizeBytes:Buffer.byteLength(t,"utf8")}}(r),i=t.map((async(t,o)=>{const{source:i,attribution:a}=t;try{return"prompt"===t.type?await this.executePromptHook(e,t.script,r,i,o,s,a):await this.executeCommandHook(e,t.script,t.cwd,t.env,r,i,o,s,a,t.pluginInstallPath,n)}catch(r){const n=r instanceof Error?r.message:String(r);if(!0===t.script.failClosed){const t=gN(`Hook execution failed: ${n}`),r=RF(e,t);if(r)return{success:!0,data:r,source:i,index:o}}return $N.warn((0,b.q6)(),`${e} hook error`,{source:i,index:o,error:n}),{success:!1,source:i,index:o}}})),a=await Promise.all(i),c=[];for(const e of a)e.success&&void 0!==e.data&&c.push(e.data);return function(e,t){if(0===t.length)return;const[r]=t;if(!(1!==t.length||Ad(n=r)&&Ad(n.updated_input)&&0===Object.keys(n.updated_input).length))return r;var n;const o=SF.includes(e),s=e===Rd.sessionStart,i=e===Rd.workspaceOpen,a=gF.has(e),c={};for(const e of t){const t=e;for(const[e,r]of Object.entries(t))if(void 0!==r)if(i&&"pluginPaths"===e&&Array.isArray(r)){const t=c[e],n=Array.isArray(t)?t:[],o=new Set(n),s=[...n];for(const e of r)"string"!=typeof e||o.has(e)||(o.add(e),s.push(e));c[e]=s}else"permission"===e&&o?c[e]=(u=r,"deny"===(l=c[e])||"deny"===u?"deny":"ask"===l||"ask"===u?"ask":"allow"===l||"allow"===u?"allow":void 0):"user_message"!==e&&"agent_message"!==e?"updated_input"!==e?a&&"additional_context"===e&&"string"==typeof r?c[e]=_F(c[e],r):"continue"!==e||"boolean"!=typeof r?c[e]=s&&"env"===e&&"object"==typeof r&&null!==r?CF(c[e],r):r:void 0===c[e]?c[e]=r:c[e]=c[e]&&r:void 0===c[e]&&Ad(r)&&Object.keys(r).length>0&&(c[e]=r):c[e]=_F(c[e],r)}var l,u;return c}(e,c)}async executeCommandHook(e,t,r,n,o,s,i,a,c,l,u){if(this.shouldSkipHookDueToLoopLimit(e,t,o))return{success:!1,source:s,index:i};const d=Date.now(),h=a(),p=h.payloadSizeBytes,f=(e,r)=>this.finishHookRun(e,t,o,r);let m;try{m=await this.executeCommandScript({script:t,cwd:r,request:o,jsonPayload:h.json,env:n,...void 0!==l&&{pluginInstallPath:l}})}catch(r){const n=r instanceof Error?r.message:String(r),o=n.toLowerCase().includes("timed out");this.reportCommandFailure(u,{command:t.command,source:s,exitCode:null,stderr:"",errorMessage:n});const a=Date.now()-d,l=o?"timeout":"spawn_error";if(!0===t.failClosed){const u=RF(e,gN(`Hook "${t.command}" execution failed: ${n}`));if(u)return f({hookStep:e,hookSource:s,hookType:"command",status:o?"timeout":"blocked",latencyMs:a,payloadSizeBytes:p,errorClass:l,failClosed:!0,timedOut:o,...c},{response:null,stderr:String(r)}),{success:!0,data:u,source:s,index:i}}return f({hookStep:e,hookSource:s,hookType:"command",status:o?"timeout":"failed",latencyMs:a,payloadSizeBytes:p,errorClass:l,failClosed:!0===t.failClosed,timedOut:o,...c},{response:null,stderr:String(r)}),{success:!1,source:s,index:i}}if(2===m.exitCode){const r=function(e,t,r){const n=e.trim(),o=t.trim();return n||(o?`Hook blocked with message: ${o}`:`Hook "${r}" blocked this action (exit code 2) but provided no reason.`)}(m.stdout,m.stderr,t.command),n=RF(e,r);return n?(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,failClosed:!0===t.failClosed,exitCode:m.exitCode,...c},{response:n,stderr:m.stderr}),{success:!0,data:n,source:s,index:i}):(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,failClosed:!0===t.failClosed,exitCode:m.exitCode,...c},{response:null,stderr:m.stderr}),{success:!1,source:s,index:i})}if(0!==m.exitCode&&null!==m.exitCode){if(this.reportCommandFailure(u,{command:t.command,source:s,exitCode:m.exitCode,stderr:m.stderr}),!0===t.failClosed){const r=RF(e,gN(`Hook "${t.command}" failed with exit code ${m.exitCode}${m.stderr?`: ${m.stderr.trim()}`:""}`));if(r)return f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"exit_nonzero",failClosed:!0,exitCode:m.exitCode,...c},{response:null,stderr:m.stderr}),{success:!0,data:r,source:s,index:i}}return f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"exit_nonzero",failClosed:!0===t.failClosed,exitCode:m.exitCode,...c},{response:null,stderr:m.stderr}),{success:!1,source:s,index:i}}const g=m.stdout.trim();if(!g){if(!0===t.failClosed){const r=RF(e,gN(`Hook "${t.command}" returned no output.`));if(r)return f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"empty_stdout",failClosed:!0,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr}),{success:!0,data:r,source:s,index:i}}return f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"empty_stdout",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr}),{success:!1,source:s,index:i}}const w=function(e){const t=e.trim();if(0===t.length)return;const r=IF(t);if(void 0!==r)return r.value;if(t.endsWith("}"))for(let e=t.length-1;e>=0;e--){if("{"!==t[e])continue;const r=IF(t.slice(e));if(void 0!==r)return r.value}}(g);if(void 0===w){const r=xF({step:e,command:t.command,failClosed:!0===t.failClosed,kind:"invalid_json"});return r.blockResponse?(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_json",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr+DN}),{success:!0,data:r.blockResponse,source:s,index:i}):(f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_json",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr+DN}),{success:!1,source:s,index:i})}const y=bF(e,w,{enableClaudeNestedHookSpecificOutputCompatibility:this.options?.enableClaudeNestedHookSpecificOutputCompatibility});if(y.success&&null!=y.data){const r=y.data,n="object"==typeof r&&"permission"in r?r.permission:void 0;return f({hookStep:e,hookSource:s,hookType:"command",status:"deny"===n||"ask"===n?"blocked":"success",latencyMs:m.duration,payloadSizeBytes:p,failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:r,stderr:m.stderr}),{success:!0,data:r,source:s,index:i}}const v=xF({step:e,command:t.command,failClosed:!0===t.failClosed,kind:"invalid_response"});return v.blockResponse?(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_response",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:w,stderr:m.stderr}),{success:!0,data:v.blockResponse,source:s,index:i}):(f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_response",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:w,stderr:m.stderr}),{success:!1,source:s,index:i})}async executePromptHook(e,t,r,n,o,s,i){if(this.shouldSkipHookDueToLoopLimit(e,t,r))return{success:!1,source:n,index:o};if(!this.promptHookClient)return{success:!1,source:n,index:o};const a=1e3*(t.timeout??60),c=Date.now(),l=s(),u=l.payloadSizeBytes,d=(e,n)=>this.finishHookRun(e,t,r,n),h=(0,b.q6)(),[p,f]=h.withTimeoutAndCancel(a);try{const r=JSON.parse(l.json),s=await this.promptHookClient.evaluatePromptHook(p,{prompt:t.prompt,hookInputJson:r,modelName:t.model});if(s.ok){const r=function(e){return EF(e)?PF(0,{permission:"allow"}):e===Rd.beforeSubmitPrompt||e===Rd.sessionStart?PF(0,{continue:!0}):e===Rd.stop?PF(0,{}):void 0}(e);return d({hookStep:e,hookSource:n,hookType:"prompt",status:"success",latencyMs:Date.now()-c,payloadSizeBytes:u,failClosed:!0===t.failClosed,...i},{response:r,stderr:"",exitCode:0}),r?{success:!0,data:r,source:n,index:o}:{success:!1,source:n,index:o}}{const r=RF(e,s.reason??"Prompt hook blocked this action");return d({hookStep:e,hookSource:n,hookType:"prompt",status:"blocked",latencyMs:Date.now()-c,payloadSizeBytes:u,failClosed:!0===t.failClosed,...i},{response:r,stderr:"",exitCode:2}),r?{success:!0,data:r,source:n,index:o}:{success:!1,source:n,index:o}}}catch(r){const s=r instanceof Error?r.message:String(r),a=s.toLowerCase().includes("abort")||s.toLowerCase().includes("timed out"),l=a?"timeout":"prompt_error";if(!0===t.failClosed){const t=RF(e,gN(`Prompt hook failed: ${s}`));if(t)return d({hookStep:e,hookSource:n,hookType:"prompt",status:a?"timeout":"blocked",latencyMs:Date.now()-c,payloadSizeBytes:u,errorClass:l,failClosed:!0,timedOut:a,...i},{response:null,stderr:String(r)}),{success:!0,data:t,source:n,index:o}}return d({hookStep:e,hookSource:n,hookType:"prompt",status:a?"timeout":"failed",latencyMs:Date.now()-c,payloadSizeBytes:u,errorClass:l,failClosed:!0===t.failClosed,timedOut:a,...i},{response:null,stderr:String(r)}),{success:!1,source:n,index:o}}finally{f()}}async executeCommandScript(e){const{script:t,cwd:r,request:n,env:i,pluginInstallPath:a,jsonPayload:c}=e,l=1e3*(t.timeout??60),u=Date.now();let d;const h=new AbortController,p=setTimeout((()=>{h.abort()}),l);try{const e="win32"===process.platform,f=this.getCommandHookPayloadTransportMode(),m=this.shouldUseCommandHookDirectStdinTransport(),g=e?function(e,t){const r=function(e){let t=0;for(;t0&&!/^\s/.test(i))return e;if(/[$`{}()|;,<>]/.test(s)||""===o&&/['"]/.test(s))return e;const a=s.slice(Math.max(s.lastIndexOf("\\"),s.lastIndexOf("/"))+1);if(0===a.length||a.includes("."))return e;const c="'"===o?s.replace(/''/g,"'"):s,l=/^[A-Za-z]:[\\/]/.test(u=c)||u.startsWith("\\")||u.startsWith("/")?c:`${t.cwd.replace(/[\\/]+$/,"")}\\${c}`;var u;const d=iF.find((e=>t.isFile(l+e)));return void 0===d?e:""!==o?`${n}${o}${s}${d}${o}${i}`:`${n}'${s}${d}'${i}`}(t.command,{cwd:r,isFile:MN}):t.command;let w;if(m)w=e?aF(g):g;else if("windows_temp_file"===f){d=await(0,xo.mkdtemp)((0,s.join)((0,o.tmpdir)(),"cursor-hooks-"));const e=(0,s.join)(d,"payload.json");await(0,xo.writeFile)(e,c,{encoding:"utf8",flag:"wx"}),w=function(e,t){return`$OutputEncoding = [System.Text.UTF8Encoding]::new($false); try { $global:cursorHookConsoleInputEncoding = [Console]::InputEncoding; $null = Register-EngineEvent -SourceIdentifier PowerShell.Exiting -Action { try { [Console]::InputEncoding = $global:cursorHookConsoleInputEncoding } catch { } }; [Console]::InputEncoding = $OutputEncoding } catch { }; Get-Content -LiteralPath '${e.replace(/'/g,"''")}' -Raw -Encoding UTF8 | & { $input | ${aF(t)} }`+sF(t)}(e,g)}else w=e?`@'\n${c.replace(/'/g,"''")}\n'@ | & ${g}`+sF(g):`${t.command} <<'CURSOR_HOOK_EOF'\n${c}\nCURSOR_HOOK_EOF`;const y=FN(n,"conversation_id")??void 0,v=FN(n,"session_id")??void 0,S=FN(n,"transcript_path"),k=void 0===y?void 0:this.activeSessionIdsByConversationId.get(y),_=void 0===v||v===y&&!this.sessionEnvById.has(v)?void 0===y?void 0:k?.at(-1)??y:v,C=this.buildHookEnvironment({transcriptPath:S,sessionId:_,conversationId:y,executionEnv:i}),E={};for(const[e,t]of Object.entries(C))void 0!==t&&(E[e]=t);void 0!==a&&(E.CURSOR_PLUGIN_ROOT=a,E.CLAUDE_PLUGIN_ROOT=a);const x=(0,b.q6)(),P=new ca.StringDecoder("utf8"),R=new ca.StringDecoder("utf8");let I,T="",A="",$=null,M=!1;for await(const e of this.shellExecutor.execute(x,w,{workingDirectory:r,signal:h.signal,sandboxPolicy:{perUser:{type:"insecure_none"}},env:E,pipeStdin:m}))switch(e.type){case"stdin_ready":m&&(await this.writeCommandHookStdinPayload(e.stdin,c),M=!0);break;case"stdout":T+=P.write(e.data);break;case"stderr":A+=R.write(e.data);break;case"exit":$=e.code,I=e.aborted}if(T+=P.end(),A+=R.end(),m&&!M)throw new Error("Hook stdin transport was requested, but the executor did not signal stdin readiness");clearTimeout(p);const D=Date.now()-u;if(I??h.signal.aborted)throw new Error(`Hook script timed out after ${l}ms`);return{stdout:T,stderr:A,exitCode:$,duration:D}}catch(e){if(clearTimeout(p),Date.now(),h.signal.aborted)throw new Error(`Hook script timed out after ${l}ms`);throw e}finally{if(d)try{await(0,xo.rm)(d,{recursive:!0,force:!0})}catch{}}}}class LN{constructor(e){this.config=e,this.configuredSteps=SN.getConfiguredSteps(e)}getConfig(){return this.config}hasHookForStep(e){return this.configuredSteps.has(e)}getConfiguredSteps(){return new Set(this.configuredSteps)}}var jN=r("node:perf_hooks");const UN=(0,b.cF)(Symbol.for("@anysphere/agent-exec/toolCallHooks"),{kind:"none"});function BN(e){return"inExecute"!==e.get(UN).kind}function WN(e,t){const r=e.get(UN);return"inExecute"!==r.kind||!r.toolStepsInPreToolUse.includes(t)}(0,b.cF)(Symbol.for("@anysphere/agent-exec/hookAsk"),void 0),(0,b.cF)(Symbol.for("@anysphere/agent-exec/hookAllow"),void 0),new WeakMap,new WeakMap,(0,b.cF)(Symbol.for("@anysphere/agent-exec/toolCallRefusal"),void 0),new WeakMap,new WeakMap,new WeakMap,(0,b.cF)(Symbol.for("@anysphere/agent-exec/approvalWaits"),void 0),new WeakMap;const HN=(0,b.cF)(Symbol.for("@anysphere/agent-exec/hookStepTime"),void 0),qN=new bd.AsyncLocalStorage;function zN(e,t){return qN.run(e,t)}function GN(e,t){void 0!==e&&t.length>0&&e.push(...t)}class VN extends Error{constructor(e){super(`Hook additional_context for ${e.hookEventName} is ${e.actualLength} chars (max ${e.maxLength}).`),this.name="HookAdditionalContextTooLargeError",this.hookEventName=e.hookEventName,this.actualLength=e.actualLength,this.maxLength=e.maxLength}}var KN=r("../proto/dist/generated/agent/v1/hook_additional_context_pb.js");function JN({hookEventName:e,additionalContext:t}){const r=function(e){const t=e?.trim();return void 0!==t&&t.length>0?t:void 0}(t);if(void 0===r)return[];if(r.length>1e4)throw new VN({hookEventName:e,actualLength:r.length,maxLength:1e4});return[new KN.C({hookEventName:e,content:r})]}Object.fromEntries(Array.from(gF).map((e=>{if(!function(e){return e===Rd.sessionStart||e===Rd.beforeSubmitPrompt||e===Rd.preToolUse||e===Rd.postToolUse||e===Rd.postToolUseFailure}(e))throw new Error(`HOOK_STEPS_SUPPORTING_ADDITIONAL_CONTEXT lists ${e} but HookStepAdditionalContextEventName does not include it. Extend the Extract<> union in spec.ts.`);return[e,{hookEventName:e}]})));const ZN="Agent note: Do not suggest workarounds to the blocked tool.";function XN(e){return e.includes(ZN)?e:`${e}\n\n${ZN}`}class QN extends Error{constructor(e){super(`Hook denied: ${e}`),this.failureType="permission_denied",this.name="HookDeniedError",this.reason=e}}class YN extends Error{constructor(e,t){super(`Hook failed (fail-closed): ${e}`),this.failureType="error",this.name="FailClosedError",this.reason=e,this.cause=t}}const eL="To view or modify configured hooks, go to Cursor Settings > Hooks.";function tL(e,t){return XN(`${t?`${e} was blocked by a hook: ${t}`:`${e} was blocked by a hook.`}\n\n${eL}`)}function rL(e){return function(e){return e instanceof QN}(e)||function(e){return e instanceof YN}(e)}const nL=(0,d.h)("generic-hooks");function oL(e,t,r,n){try{return JN({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof VN)return nL.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}const sL=e=>Math.round(1e3*e)/1e3;function iL(e,t,r,n,o,s){const i=n(e),a=o.getToolCallId?.(t)??(0,ko.randomUUID)(),c=o.getExtraHookFields?.(t)??{},l={baseHookRequest:i,toolUseId:a,toolInput:o.createToolInput(t),extraHookFields:c,hookContextCollector:s?.hookContextCollector??o.getHookContextCollector?.(t)??[]},u=function(e,t,r,n){let{toolInput:o,extraHookFields:s,hookContextCollector:i}=n;const{baseHookRequest:a,toolUseId:c}=n;return{fireFailureAsync:async(n,l,u,d=!1)=>{try{const h=await zN(e.signal,(()=>t.executeHookForStep(Rd.postToolUseFailure,{...a,tool_name:r,tool_input:o,error_message:l,failure_type:u,duration:n,tool_use_id:c,is_interrupt:d,...s})));GN(i,oL(e,r,Rd.postToolUseFailure,h?.additional_context))}catch(t){nL.warn(e,"postToolUseFailure hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}},fireSuccessAsync:async(n,l)=>{try{const u=await zN(e.signal,(()=>t.executeHookForStep(Rd.postToolUse,{...a,tool_name:r,tool_input:o,tool_output:l,duration:n,tool_use_id:c,...s})));GN(i,oL(e,r,Rd.postToolUse,u?.additional_context))}catch(t){nL.warn(e,"postToolUse hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}},getToolInput:()=>o,setToolInput:e=>{o=e},setExtraHookFields:e=>{s=e,n.extraHookFields=e}}}(e,r,o.toolName,l);return{hookContext:l,helpers:u}}async function aL(e,t,r,n,o,s,i,a){const{baseHookRequest:c,toolUseId:l,extraHookFields:u}=n;try{const a=await zN(e.signal,(()=>r.executeHookForStep(Rd.preToolUse,{...c,tool_name:s.toolName,tool_input:o.getToolInput(),tool_use_id:l,...u})));if("deny"===a?.permission){const r=a.user_message||`${s.toolName} blocked by preToolUse hook`,c=XN(r);try{GN(n.hookContextCollector,JN({hookEventName:Rd.preToolUse,additionalContext:a.additional_context}))}catch(t){if(!(t instanceof VN))throw t;nL.warn(e,"preToolUse deny additional_context exceeded max size; dropping carrier",{toolName:s.toolName,actualLength:t.actualLength,maxLength:t.maxLength})}return await o.fireFailureAsync(0,r,"permission_denied"),{type:"rejected",result:i(t,c),reason:c}}a?.updated_input&&s.applyUpdatedInput&&(s.applyUpdatedInput(t,a.updated_input),o.setToolInput(s.createToolInput(t)),s.getExtraHookFields&&o.setExtraHookFields(s.getExtraHookFields(t))),GN(n.hookContextCollector,JN({hookEventName:Rd.preToolUse,additionalContext:a?.additional_context}))}catch(n){const a=r.hasFailClosedHooksForStep?.(Rd.preToolUse,s.toolName)??!1,c=n instanceof VN;if(a){const e=gN(`${c?"preToolUse additional_context exceeded max size":"preToolUse hook failed"}: ${n instanceof Error?n.message:"preToolUse hook error"}`);return await o.fireFailureAsync(0,e,"error"),{type:"rejected",result:i(t,e),reason:e}}nL.warn(e,c?"preToolUse additional_context exceeded max size; dropping carrier":"preToolUse hook error",{toolName:s.toolName,error:n instanceof Error?n.message:String(n),...c?{actualLength:n.actualLength,maxLength:n.maxLength}:{}})}if(a)try{const s=await a({ctx:e,args:t,baseHookRequest:c,hookExecutor:r,toolInput:o.getToolInput(),toolUseId:l,extraHookFields:n.extraHookFields});if(void 0!==s){const e="Pre-execution hook returned rejection";return await o.fireFailureAsync(0,e,"permission_denied"),{type:"rejected",result:s,reason:e}}}catch(e){if(rL(e))return await o.fireFailureAsync(0,e.reason,e.failureType),{type:"rejected",result:i(t,e.reason),reason:e.reason};throw e}return{type:"continue"}}function cL(e){return e.toolCallId}function lL(e,t,r,n){return{async execute(o,s,i){const a=dL(o,t),{hookContext:c,helpers:l}=iL(o,s,a,r,n,i);let u;try{u=await aL(o,s,a,c,l,n,n.createRejectedResult,n.runPreExecutionHooks)}catch(e){throw n.runCleanup?.(c.toolUseId),e}if("rejected"===u.type)return n.runCleanup?.(c.toolUseId),u.result;const d=jN.performance.now();try{const t=await e.execute(o,s,i),r=sL(jN.performance.now()-d);if(n.runPostExecutionHooks)try{const e=await n.runPostExecutionHooks({ctx:o,args:s,result:t,baseHookRequest:c.baseHookRequest,hookExecutor:a,toolInput:l.getToolInput(),toolUseId:c.toolUseId,executionDurationMs:r,extraHookFields:c.extraHookFields});if(void 0!==e)return await l.fireSuccessAsync(r,JSON.stringify(n.createSuccessOutput(s,e))),n.runCleanup?.(c.toolUseId),e}catch(e){if(rL(e))return await l.fireFailureAsync(r,e.reason,e.failureType),n.runCleanup?.(c.toolUseId),n.createRejectedResult(s,e.reason);nL.warn(o,"postExecutionHooks error",{toolName:n.toolName,error:e instanceof Error?e.message:String(e)})}return n.isSuccess(t)?await l.fireSuccessAsync(r,JSON.stringify(n.createSuccessOutput(s,t))):await l.fireFailureAsync(r,n.getErrorMessage(t),n.getFailureType?.(t)??"error",n.isInterrupt?.(t)??!1),n.runCleanup?.(c.toolUseId),t}catch(e){const t=sL(jN.performance.now()-d);throw await l.fireFailureAsync(t,e instanceof Error?e.message:String(e),"error"),n.runCleanup?.(c.toolUseId),e}}}}function*uL(e,t){const r=t.hookContextCollector;e.createHookContextEvent&&void 0!==r&&0!==r.length&&(yield e.createHookContextEvent(r))}function dL(e,t){const r=BN(e),n=e.get(HN);if(r&&void 0===n)return t;const o=e=>n?.during(e)??e;return{executeHookForStep:async(e,n)=>{if(r||!function(e){return e===Rd.preToolUse||e===Rd.postToolUse||e===Rd.postToolUseFailure}(e))return o(t.executeHookForStep(e,n));await o(t.whenConfigReady())},hasFailClosedHooksForStep:(e,r)=>t.hasFailClosedHooksForStep?.(e,r)??!1,hasHooksForStep:e=>t.hasHooksForStep?.(e)??!0,whenConfigReady:()=>o(t.whenConfigReady())}}function hL(e){if("object"!=typeof e||null===e||!("code"in e))return!1;const t=e.code;return"ENOENT"===t||"ENOTDIR"===t}class pL{async readFile(e){try{return await xo.readFile(e,"utf-8")}catch(e){if("ENOENT"===e?.code)return;throw e}}async exists(e){try{return await xo.access(e),!0}catch{return!1}}async pathContainsSymlink(e,t){return async function(e,t){const r=function(e,t){const r=s.resolve(e),n=s.resolve(t),o=s.relative(n,r);if(0===o.length||".."===o||o.startsWith(`..${s.sep}`)||s.isAbsolute(o))return"unsafe";const i=o.split(s.sep).filter((e=>e.length>0)),a=[];let c=n;for(const e of i)c=s.join(c,e),a.push(c);return a}(e,t);if("unsafe"===r)return!0;for(const e of r)try{if((await(0,xo.lstat)(e)).isSymbolicLink())return!0}catch(e){if(hL(e))return!0;throw e}return!1}(e,t)}}var fL=r("../proto/dist/generated/agent/v1/hooks_pb.js");const mL=G("hook-executor",(e=>new H(e,Q("executeHookArgs"),Y("executeHookResult"))),((e,t)=>{t.register(new A(e,te("executeHookArgs"),ee("executeHookResult")))})),gL=new Set(Object.values(Rd));function wL(e){switch(e){case"completed":case"aborted":case"error":return e;default:return"error"}}function yL(e){switch(e){case"error":case"timeout":case"permission_denied":return e;default:return"error"}}function vL(e){const t=e?.toJson();return"object"!=typeof t||null===t||Array.isArray(t)?{}:t}class bL{constructor(e){this.hookExecutor=e}hasFailClosedHooksForStep(e,t){return!!function(e){return gL.has(e)}(e)&&(this.hookExecutor.hasFailClosedHooksForStep?.(e,t)??!1)}async execute(e,t){const r=t.request;if(!r)return new p.S1({response:void 0});switch(r.request.case){case"preCompact":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...mF(e),trigger:"manual"===e.trigger?"manual":"auto",context_usage_percent:e.contextUsagePercent,context_tokens:Number(e.contextTokens),context_window_size:Number(e.contextWindowSize),message_count:e.messageCount,messages_to_compact:e.messagesToCompact,is_first_compaction:e.isFirstCompaction},n=await this.hookExecutor.executeHookForStep(Rd.preCompact,t);return new p.S1({response:new p.w5({response:{case:"preCompact",value:new fL.$_({userMessage:n?.user_message})}})})}case"subagentStart":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...mF(e),subagent_id:e.subagentId,subagent_type:e.subagentType,task:e.task,parent_conversation_id:e.parentConversationId,tool_call_id:e.toolCallId,subagent_model:e.subagentModel,is_parallel_worker:e.isParallelWorker,git_branch:e.gitBranch},n=await this.hookExecutor.executeHookForStep(Rd.subagentStart,t);return new p.S1({response:new p.w5({response:{case:"subagentStart",value:new fL.W0({permission:n?.permission,userMessage:n?.user_message,additionalContext:n?.additional_context})}})})}case"subagentStop":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...mF(e),subagent_id:e.subagentId,subagent_type:e.subagentType,status:wL(e.status),duration_ms:Number(e.durationMs),summary:e.summary,parent_conversation_id:e.parentConversationId,message_count:e.messageCount,tool_call_count:e.toolCallCount,error_message:e.errorMessage,modified_files:e.modifiedFiles,git_branch:e.gitBranch,loop_count:e.loopCount??0,task:e.task,description:e.description,...e.childConversationId?{child_conversation_id:e.childConversationId}:{}},n=await this.hookExecutor.executeHookForStep(Rd.subagentStop,t);return new p.S1({response:new p.w5({response:{case:"subagentStop",value:new fL.AH({followupMessage:n?.followup_message,additionalContext:n?.additional_context})}})})}case"beforeSubmitPrompt":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(Rd.beforeSubmitPrompt,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...mF(e),prompt:e.prompt,attachments:(n=e.attachments,n.flatMap((e=>"file"===e.type||"rule"===e.type?[{type:e.type,file_path:e.filePath}]:[]))),composer_mode:e.composerMode});return new p.S1({response:new p.w5({response:{case:"beforeSubmitPrompt",value:new fL.u1({continue:t?.continue,userMessage:t?.user_message,additionalContext:t?.additional_context})}})})}case"afterAgentResponse":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(Rd.afterAgentResponse,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...mF(e),text:e.text,input_tokens:void 0!==e.inputTokens?Number(e.inputTokens):void 0,output_tokens:void 0!==e.outputTokens?Number(e.outputTokens):void 0,cache_read_tokens:void 0!==e.cacheReadTokens?Number(e.cacheReadTokens):void 0,cache_write_tokens:void 0!==e.cacheWriteTokens?Number(e.cacheWriteTokens):void 0}),new p.S1({response:new p.w5({response:{case:"afterAgentResponse",value:new fL.FW}})})}case"afterAgentThought":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(Rd.afterAgentThought,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...mF(e),text:e.text,duration_ms:void 0!==e.durationMs?Number(e.durationMs):void 0}),new p.S1({response:new p.w5({response:{case:"afterAgentThought",value:new fL.H}})})}case"stop":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(Rd.stop,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...mF(e),status:wL(e.status),loop_count:e.loopCount,input_tokens:void 0!==e.inputTokens?Number(e.inputTokens):void 0,output_tokens:void 0!==e.outputTokens?Number(e.outputTokens):void 0,cache_read_tokens:void 0!==e.cacheReadTokens?Number(e.cacheReadTokens):void 0,cache_write_tokens:void 0!==e.cacheWriteTokens?Number(e.cacheWriteTokens):void 0});return new p.S1({response:new p.w5({response:{case:"stop",value:new fL.rT({followupMessage:t?.followup_message})}})})}case"preToolUse":{if(!BN(e))return this.skipToolUseStep();const t=r.request.value,n=vL(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...mF(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,tool_use_id:t.toolUseId,cwd:t.cwd},s=await this.hookExecutor.executeHookForStep(Rd.preToolUse,o);return new p.S1({response:new p.w5({response:{case:"preToolUse",value:new fL.Wn({permission:s?.permission,userMessage:s?.user_message,agentMessage:s?.agent_message,updatedInput:s?.updated_input?JSON.stringify(s.updated_input):void 0,additionalContext:s?.additional_context})}})})}case"postToolUse":{if(!BN(e))return this.skipToolUseStep();const t=r.request.value,n=vL(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...mF(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,tool_output:t.toolOutput,duration:Number(t.durationMs),tool_use_id:t.toolUseId,cwd:t.cwd},s=await this.hookExecutor.executeHookForStep(Rd.postToolUse,o);return new p.S1({response:new p.w5({response:{case:"postToolUse",value:new fL.uB({additionalContext:s?.additional_context,updatedMcpToolOutput:void 0===s?.updated_mcp_tool_output?void 0:JSON.stringify(s.updated_mcp_tool_output)})}})})}case"postToolUseFailure":{if(!BN(e))return this.skipToolUseStep();const t=r.request.value,n=vL(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...mF(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,error_message:t.errorMessage,failure_type:yL(t.failureType),duration:Number(t.durationMs),tool_use_id:t.toolUseId,is_interrupt:t.isInterrupt},s=await this.hookExecutor.executeHookForStep(Rd.postToolUseFailure,o);return new p.S1({response:new p.w5({response:{case:"postToolUseFailure",value:new fL.U1({additionalContext:s?.additional_context})}})})}default:return new p.S1({response:void 0})}var n}async skipToolUseStep(){return await this.hookExecutor.whenConfigReady(),new p.S1({response:void 0})}}class SL{constructor(e,t,r,n){this.innerExecutor=e,this.hooksAdditionalContextPromise=t,this.teamHooksReadyPromise=r,this.hooksConfigLease=n}async execute(e,t,r){this.teamHooksReadyPromise&&await this.teamHooksReadyPromise;const n=await this.innerExecutor.execute(e,t,r),o=await this.hooksAdditionalContextPromise,s=this.hooksConfigLease?new Fr.Jy({configuredSteps:Array.from(this.hooksConfigLease.getConfiguredSteps())}):void 0;if("success"===n.result.case&&(o||s)){const e=n.result.value.requestContext,t=e?.clone()??new Fr.bb;return o&&(t.hooksAdditionalContext=o),s&&(t.hooksConfig=s),new Fr._G({result:{case:"success",value:new Fr.yW({requestContext:t,servedFromDiskCache:n.result.value.servedFromDiskCache})}})}return n}}function kL(e){return!!e&&e.type!==is.vc.INSECURE_NONE&&e.type!==is.vc.UNSPECIFIED}async function _L({hookExecutor:e,baseHookRequest:t,toolUseId:r,command:n,cwd:o,sandbox:s}){const i=await e.executeHookForStep(Rd.beforeShellExecution,{...t,command:n,cwd:o,sandbox:s,tool_use_id:r});if("deny"===i?.permission){const e=tL("Command execution",i.user_message);throw new QN(e)}if("ask"===i?.permission)return a=i.user_message,new fe.In({kind:fe.b.FORCE_PROMPT,reason:a});var a}const CL={toolName:PN,getToolCallId:cL,createToolInput:e=>{const t=e.workingDirectory||"";return{command:e.command,cwd:t}},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd)},createRejectedResult:(e,t)=>new Fo.Lt({result:{case:"rejected",value:new fe.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"BackgroundShell error";case"rejected":return e.result.value.reason||"BackgroundShell rejected";case"permissionDenied":return"Permission denied";case"sandboxUnsupported":return`Sandbox policy unsupported on this host: ${e.result.value.reason}`;default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{shell_id:t.result.value.shellId,pid:t.result.value.pid}:{success:!0},getExtraHookFields:e=>({cwd:e.workingDirectory||""}),runPreExecutionHooks:async e=>{const{ctx:t,args:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e,i=r.workingDirectory||"",a=kL(r.sandboxPolicy);WN(t,Rd.beforeShellExecution)&&$o(r,await _L({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:a}))}};class EL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,CL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const xL={toolName:"WriteShellStdin",createToolInput:e=>({shell_id:e.shellId,chars_length:e.chars.length}),createRejectedResult:(e,t)=>new Fo.nt({result:{case:"error",value:new Fo.Gv({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"WriteShellStdin error":"Unknown error",createSuccessOutput:e=>({shell_id:e.shellId,success:!0})};class PL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,xL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const RL={toolName:"ComputerUse",getToolCallId:cL,createToolInput:e=>({actions_count:e.actions.length}),createRejectedResult:(e,t)=>new Ng.ks({result:{case:"error",value:new Ng.Jb({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"ComputerUse error":"Unknown error",createSuccessOutput:(e,t)=>"success"===t.result.case?{action_count:t.result.value.actionCount,duration_ms:t.result.value.durationMs}:{success:!0}};class IL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,RL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const TL={toolName:CN,getToolCallId:cL,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Ww.Pi({result:{case:"rejected",value:new Ww.iq({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"fileNotFound":return`File not found: ${e.result.value.path}`;case"notFile":return`Not a file: ${e.result.value.path}`;case"permissionDenied":return`Permission denied: ${e.result.value.path}`;case"fileBusy":return`File busy: ${e.result.value.path}`;case"rejected":return e.result.value.reason||"Delete rejected";case"error":return e.result.value.error||"Delete error";default:return"Unknown error"}},createSuccessOutput:e=>({file_path:e.path,deleted:!0})};class AL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,TL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const $L={toolName:RN,getToolCallId:cL,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new NA.Ek({result:{case:"rejected",value:new NA.J6({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"Diagnostics error";case"rejected":return e.result.value.reason||"Diagnostics rejected";case"fileNotFound":return`File not found: ${e.result.value.path}`;case"permissionDenied":return`Permission denied: ${e.result.value.path}`;default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{file_path:e.path,diagnostics_count:t.result.value.totalDiagnostics}:{file_path:e.path,success:!0}};class ML{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,$L)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const DL={toolName:"Fetch",getToolCallId:cL,createToolInput:e=>({url:e.url}),applyUpdatedInput:(e,t)=>{"string"==typeof t.url&&(e.url=t.url)},createRejectedResult:(e,t)=>new Jw.uN({result:{case:"error",value:new Jw.fk({url:e.url,error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Fetch error":"Unknown error",createSuccessOutput:(e,t)=>"success"===t.result.case?{url:e.url,status_code:t.result.value.statusCode,content_length:t.result.value.content.length}:{url:e.url,success:!0}};class OL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,DL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const FL={toolName:xN,getToolCallId:cL,createToolInput:e=>({pattern:e.pattern,file_path:e.path,glob:e.glob,output_mode:e.outputMode}),applyUpdatedInput:(e,t)=>{"string"==typeof t.pattern&&(e.pattern=t.pattern),"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Ry.Ud({result:{case:"error",value:new Ry.ts({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Grep error":"Unknown error",createSuccessOutput:e=>({pattern:e.pattern,success:!0})};class NL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,FL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const LL={toolName:EN,getToolCallId:cL,createToolInput:e=>({file_path:e.path,ignore:e.ignore}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new yC.fv({result:{case:"rejected",value:new yC.k2({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"Ls error";case"rejected":return e.result.value.reason||"Ls rejected";case"timeout":return"Ls operation timed out";default:return"Unknown error"}},getFailureType:e=>"timeout"===e.result.case?"timeout":"error",createSuccessOutput:e=>({file_path:e.path,success:!0})};class jL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,LL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const UL=(0,d.h)("hooks-exec:mcp");function BL(e){return!!(null===e||"string"==typeof e||"boolean"==typeof e||"number"==typeof e&&Number.isFinite(e))||(Array.isArray(e)?e.every(BL):"object"==typeof e&&Object.values(e).every((e=>void 0!==e&&BL(e))))}function WL(e,t,r,n){try{return JN({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof VN)return UL.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}class HL{constructor(e,t,r,n,o){this.innerExecutor=e,this.hookExecutor=t,this.baseHookRequestExtractor=r,this.mcpLease=n,this.hooksConfigLease=o}async execute(e,t,r){if(t.smartModeApprovalOnly)return this.innerExecutor.execute(e,t,r);if(t.symbolicPathArguments.length>0&&(!0===this.hooksConfigLease?.hasHookForStep(Rd.preToolUse)||!0===this.hooksConfigLease?.hasHookForStep(Rd.beforeMCPExecution)))return new Mc.iz({result:{case:"error",value:new Mc.Nh({error:`"${iA}" arguments can't be used on this computer: hooks that inspect MCP calls are configured here, and they would not see the file's contents. Read the file and pass its contents instead.`})}});const n=dL(e,this.hookExecutor),o=this.baseHookRequestExtractor(e),s=(0,ko.randomUUID)(),i=r?.hookContextCollector??[];let a=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t?.toJson()])));const c=`MCP:${t.toolName}`;try{const r=await n.executeHookForStep(Rd.preToolUse,{...o,tool_name:c,tool_input:a,tool_use_id:s});if("deny"===r?.permission){const t=r.user_message||"MCP tool blocked by preToolUse hook";try{GN(i,JN({hookEventName:Rd.preToolUse,additionalContext:r.additional_context}))}catch(t){if(!(t instanceof VN))throw t;UL.warn(e,"preToolUse deny additional_context exceeded max size; dropping carrier",{toolName:c,actualLength:t.actualLength,maxLength:t.maxLength})}return await this.firePostToolUseFailureAsync(e,n,o,c,a,t,"permission_denied",0,s,!1,i),new Mc.iz({result:{case:"permissionDenied",value:new Mc.HQ({error:tL("MCP tool execution",t),isReadonly:!1})}})}if(r?.updated_input)try{for(const[e,n]of Object.entries(r.updated_input))if(void 0!==n){if(!BL(n))throw new TypeError("updated_input value is not JSON");t.args[e]=ve.Value.fromJson(n)}a=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t?.toJson()])))}catch(t){UL.warn(e,"Failed to merge updated_input for MCP",{error:t instanceof Error?t.message:String(t)})}GN(i,JN({hookEventName:Rd.preToolUse,additionalContext:r?.additional_context}))}catch(t){const r=n.hasFailClosedHooksForStep?.(Rd.preToolUse,c)??!1,l=t instanceof VN;if(r){const r=gN(`${l?"preToolUse additional_context exceeded max size":"preToolUse hook failed"}: ${t instanceof Error?t.message:"preToolUse hook error"}`);return await this.firePostToolUseFailureAsync(e,n,o,c,a,r,"error",0,s,!1,i),new Mc.iz({result:{case:"permissionDenied",value:new Mc.HQ({error:tL("MCP tool execution",r),isReadonly:!1})}})}UL.warn(e,l?"preToolUse additional_context exceeded max size; dropping carrier":"preToolUse hook error in MCP executor",{toolName:c,error:t instanceof Error?t.message:String(t),...l?{actualLength:t.actualLength,maxLength:t.maxLength}:{}})}const l=await(this.mcpLease?.getClient(e,t.providerIdentifier)),u=l?.config;let d;const h=u&&"url"in u&&u.url?u.url:void 0;d=void 0!==h?{url:h}:u&&"command"in u?{command:[u.command,...u.args??[]].filter(Boolean).join(" ")}:{command:t.providerIdentifier};const p={mcp_server_name:t.providerIdentifier,...void 0!==h?{mcp_server_url:h}:{}},f={...o,tool_name:t.toolName,tool_input:JSON.stringify(a),tool_use_id:s,...p,...d},m=WN(e,Rd.beforeMCPExecution)?await n.executeHookForStep(Rd.beforeMCPExecution,f):void 0;if("deny"===m?.permission){const t=tL("MCP tool execution",m.user_message);return await this.firePostToolUseFailureAsync(e,n,o,c,a,t,"permission_denied",0,s,!1,i),new Mc.iz({result:{case:"permissionDenied",value:new Mc.HQ({error:t,isReadonly:!1})}})}const g=jN.performance.now();try{const l=await this.innerExecutor.execute(e,t,r),u=sL(jN.performance.now()-g);let d="{}";if("success"===l.result.case)try{const e=l.result.value.content.map((e=>"text"===e.content.case?{type:"text",text:e.content.value.text}:"image"===e.content.case?{type:"image",data:Buffer.from(e.content.value.data).toString("base64"),mimeType:e.content.value.mimeType}:{type:"unknown"}));d=JSON.stringify({content:e,isError:l.result.value.isError})}catch(t){UL.warn(e,"Failed to serialize MCP result",{error:t instanceof Error?t.message:String(t)}),d=JSON.stringify({error:"Failed to serialize result"})}else"error"===l.result.case?d=JSON.stringify({error:l.result.value.error}):"rejected"===l.result.case?d=JSON.stringify({rejected:!0,reason:l.result.value.reason}):"permissionDenied"===l.result.case&&(d=JSON.stringify({permissionDenied:!0,error:l.result.value.error}));const h={...o,tool_name:t.toolName,tool_input:JSON.stringify(a),result_json:d,duration:u,tool_use_id:s,...p};await n.executeHookForStep(Rd.afterMCPExecution,h);const f=await this.firePostToolUse(e,n,o,c,a,d,u,s,i);if(void 0!==f?.updated_mcp_tool_output)try{const e=f.updated_mcp_tool_output,t=[];if("string"==typeof e)t.push(new Mc._Z({content:{case:"text",value:new Mc.zN({text:e})}}));else if("object"==typeof e&&null!==e&&"content"in e&&Array.isArray(e.content)){const r=e.content;for(const e of r)"object"==typeof e&&null!==e&&"type"in e&&"text"===e.type&&"text"in e?t.push(new Mc._Z({content:{case:"text",value:new Mc.zN({text:String(e.text)})}})):t.push(new Mc._Z({content:{case:"text",value:new Mc.zN({text:JSON.stringify(e)})}}))}else t.push(new Mc._Z({content:{case:"text",value:new Mc.zN({text:JSON.stringify(e)})}}));const r="object"==typeof e&&null!==e&&"isError"in e&&Boolean(e.isError);return new Mc.iz({result:{case:"success",value:new Mc.QW({content:t,isError:r})}})}catch(t){return UL.warn(e,"Failed to process updated_mcp_tool_output",{error:t instanceof Error?t.message:String(t)}),l}return l}catch(t){const r=sL(jN.performance.now()-g),l=t instanceof Error?t.message:String(t);throw await this.firePostToolUseFailureAsync(e,n,o,c,a,l,"error",r,s,!1,i),t}}async firePostToolUse(e,t,r,n,o,s,i,a,c){try{const l=await t.executeHookForStep(Rd.postToolUse,{...r,tool_name:n,tool_input:o,tool_output:s,duration:i,tool_use_id:a});return GN(c,WL(e,n,Rd.postToolUse,l?.additional_context)),l}catch(t){return void UL.warn(e,"postToolUse hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}async firePostToolUseFailureAsync(e,t,r,n,o,s,i,a,c,l,u){try{const d=await t.executeHookForStep(Rd.postToolUseFailure,{...r,tool_name:n,tool_input:o,error_message:s,failure_type:i,duration:a,tool_use_id:c,is_interrupt:l});GN(u,WL(e,n,Rd.postToolUseFailure,d?.additional_context))}catch(t){UL.warn(e,"postToolUseFailure hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}}const qL={toolName:"ListMcpResources",createToolInput:e=>({server:e.server}),applyUpdatedInput:(e,t)=>{"string"==typeof t.server&&(e.server=t.server)},createRejectedResult:(e,t)=>new Mc.kP({result:{case:"error",value:new Mc.w2({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"ListMcpResources error";case"rejected":return e.result.value.reason||"ListMcpResources rejected";default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{resources_count:t.result.value.resources.length}:{success:!0}};class zL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,qL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const GL={toolName:"FetchMcpResource",createToolInput:e=>({server:e.server,uri:e.uri,download_path:e.downloadPath}),applyUpdatedInput:(e,t)=>{"string"==typeof t.server&&(e.server=t.server),"string"==typeof t.uri&&(e.uri=t.uri),"string"==typeof t.download_path&&(e.downloadPath=t.download_path)},createRejectedResult:(e,t)=>new Mc.ZD({result:{case:"error",value:new Mc.Jx({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"ReadMcpResource error";case"rejected":return e.result.value.reason||"ReadMcpResource rejected";case"notFound":return"Resource not found";default:return"Unknown error"}},createSuccessOutput:(e,t)=>{if("success"===t.result.case){const r=t.result.value;return{uri:e.uri,name:r.name,mime_type:r.mimeType,download_path:r.downloadPath,content_type:r.content.case,content_length:"text"===r.content.case||"blob"===r.content.case?r.content.value.length:void 0}}return{uri:e.uri,success:!0}}};class VL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,GL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const KL={toolName:kN,getToolCallId:cL,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Xy.sV({result:{case:"rejected",value:new Xy.f4({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"Read error";case"rejected":return e.result.value.reason||"Read rejected";case"fileNotFound":return`File not found: ${e.result.value.path}`;case"permissionDenied":return`Permission denied: ${e.result.value.path}`;case"invalidFile":return`Invalid file: ${e.result.value.path}`;default:return"Unknown error"}},createSuccessOutput:(e,t)=>{if("success"===t.result.case){const r="content"===t.result.value.output.case?t.result.value.output.value:"";return{file_path:e.path,content_length:r.length}}return{file_path:e.path,success:!0}},runPostExecutionHooks:async e=>{const{args:t,result:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e;if("success"!==r.result.case||!1===o.hasHooksForStep?.(Rd.beforeReadFile))return;const i="content"===r.result.value.output.case?r.result.value.output.value:"",a=await async function(e,t){try{return await e()}catch(e){const r=function(e,t){return`${e??"Action"} was blocked because a configured hook failed to execute${t?`: ${t}`:"."}\n\nThis is a safety measure (fail-closed) - when hooks cannot be evaluated, the action is blocked to prevent potentially unsafe operations.\n\n${eL}`}(t,e instanceof Error?e.message:String(e));throw new YN(r,e)}}((()=>o.executeHookForStep(Rd.beforeReadFile,{...n,content:i,file_path:t.path,attachments:[],tool_use_id:s})),"File read");if("deny"===a?.permission){const e=tL("File read",a.user_message);throw new QN(e)}}};class JL{constructor(e,t,r){this.wrappedExecutor=new eA(lL(e,t,r,KL))}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const ZL={toolName:"RecordScreen",getToolCallId:cL,createToolInput:e=>({mode:e.mode,save_as_filename:e.saveAsFilename}),createRejectedResult:(e,t)=>new T$.Tj({result:{case:"failure",value:new T$.yH({error:t,kind:T$.Wg.HOOK_REJECTED})}}),isSuccess:e=>"failure"!==e.result.case,getErrorMessage:e=>"failure"===e.result.case?e.result.value.error||"RecordScreen failed":"Unknown error",createSuccessOutput:(e,t)=>({result_type:t.result.case})};class XL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,ZL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}function QL(e){return"success"===e.result.case||"failure"===e.result.case?e.result.value.stdout+e.result.value.stderr:""}const YL={toolName:PN,createToolInput:e=>{const t=e.workingDirectory||"",r=e.timeout;return{command:e.command,cwd:t,..."number"==typeof r&&r>0&&{timeout:r}}},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd),"number"==typeof t.timeout&&t.timeout>=0&&(e.timeout=t.timeout)},createRejectedResult:(e,t)=>new fe.W4({result:{case:"rejected",value:new fe.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),isSuccess:e=>"success"===e.result.case||"failure"===e.result.case&&!e.result.value.aborted,getErrorMessage:e=>{switch(e.result.case){case"timeout":return`Command timed out after ${e.result.value.timeoutMs}ms`;case"spawnError":return e.result.value.error||"Failed to spawn command";case"failure":return e.result.value.aborted?"Command was aborted":"Command failed";case"rejected":return e.result.value.reason||"Command rejected";default:return"Unknown error"}},getFailureType:e=>"timeout"===e.result.case?"timeout":"error",isInterrupt:e=>"failure"===e.result.case&&e.result.value.aborted,createSuccessOutput:(e,t)=>({output:QL(t),exitCode:"success"===t.result.case?0:1}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),runPreExecutionHooks:async e=>{const{ctx:t,args:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e,i=r.workingDirectory||"";WN(t,Rd.beforeShellExecution)&&$o(r,await _L({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:kL(r.requestedSandboxPolicy)}))},runPostExecutionHooks:async e=>{const{args:t,result:r,baseHookRequest:n,hookExecutor:o,executionDurationMs:s,toolUseId:i}=e,a=QL(r);await o.executeHookForStep(Rd.afterShellExecution,{...n,command:t.command,output:a,duration:s,sandbox:kL(t.requestedSandboxPolicy),tool_use_id:i})}};class ej{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,YL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class tj{constructor(){this.output=""}onEvent(e){"stdout"===e.event.case||"stderr"===e.event.case?this.output+=e.event.value.data:"exit"===e.event.case&&(this.exitEvent=e.event.value)}getOutput(){return this.output}isAborted(){return this.exitEvent?.aborted??!1}getExitCode(){return this.exitEvent?.code??0}}const rj={toolName:PN,createToolInput:e=>{const t=e.workingDirectory||"",r=e.timeout;return{command:e.command,cwd:t,..."number"==typeof r&&r>0&&{timeout:r}}},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd),"number"==typeof t.timeout&&t.timeout>=0&&(e.timeout=t.timeout)},createRejectedEvent:(e,t)=>new fe.FI({event:{case:"rejected",value:new fe.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),createHookContextEvent:e=>new fe.FI({event:{case:"hookContext",value:new fe.Ng({hookAdditionalContexts:[...e]})}}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),createResultCollector:()=>new tj,createSuccessOutput:(e,t)=>({output:t.getOutput(),exitCode:t.getExitCode()}),isStreamSuccess:e=>0===e.getExitCode(),getStreamErrorMessage:(e,t)=>t.getOutput().trim()||`Command failed with exit code ${t.getExitCode()}`,runPreExecutionHooks:async e=>{const{ctx:t,args:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e,i=r.workingDirectory||"",a=kL(r.requestedSandboxPolicy);WN(t,Rd.beforeShellExecution)&&$o(r,await _L({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:a}))},runPostExecutionHooks:async e=>{const{args:t,baseHookRequest:r,hookExecutor:n,collector:o,executionDurationMs:s,toolUseId:i}=e,a=kL(t.requestedSandboxPolicy);await n.executeHookForStep(Rd.afterShellExecution,{...r,command:t.command,output:o.getOutput(),duration:s,sandbox:a,tool_use_id:i})}};class nj{constructor(e,t,r){this.wrappedExecutor=function(e,t,r,n){return{async*execute(o,s,i){const a=dL(o,t),{hookContext:c,helpers:l}=iL(o,s,a,r,n,i),u=n.runPreExecutionHooks?async e=>{await n.runPreExecutionHooks(e)}:void 0,d=await aL(o,s,a,c,l,n,((e,t)=>n.createRejectedEvent(e,t)),u);if("rejected"===d.type){yield d.result;for(const e of uL(n,c))yield e;return}const h=jN.performance.now(),p=n.createResultCollector();try{for await(const t of e.execute(o,s,i))p.onEvent(t),yield t}catch(e){const t=sL(jN.performance.now()-h),r=e instanceof Error?e.message:String(e);await l.fireFailureAsync(t,r,"error");for(const e of uL(n,c))yield e;throw e}const f=sL(jN.performance.now()-h);if(n.runPostExecutionHooks)try{await n.runPostExecutionHooks({ctx:o,args:s,baseHookRequest:c.baseHookRequest,hookExecutor:a,toolInput:l.getToolInput(),toolUseId:c.toolUseId,extraHookFields:c.extraHookFields,collector:p,executionDurationMs:f})}catch(e){nL.warn(o,"postExecutionHooks error",{toolName:n.toolName,error:e instanceof Error?e.message:String(e)})}if(p.isAborted())await l.fireFailureAsync(f,"Command was aborted","error",!0);else if(n.isStreamSuccess?.(p)??1)await l.fireSuccessAsync(f,JSON.stringify(n.createSuccessOutput(s,p)));else{const e=n.getStreamErrorMessage?.(s,p)??`Command failed with exit code ${p.getExitCode()}`;await l.fireFailureAsync(f,e,"error")}for(const e of uL(n,c))yield e}}}(e,t,r,rj)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class oj{constructor(e,t,r){const n=new Map;this.wrappedExecutor=lL(e,t,r,function(e){return{toolName:_N,getToolCallId:cL,createToolInput:e=>({file_path:e.path,content:e.fileText}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new FI.v3({result:{case:"error",value:new FI.QM({path:e.path,error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Write error":"Unknown error",createSuccessOutput:e=>({file_path:e.path,success:!0}),runPreExecutionHooks:async t=>{const{args:r,hookExecutor:n,toolUseId:o}=t;if(!1===n.hasHooksForStep?.(Rd.afterFileEdit))return;let s,i=!1;try{(await(0,xo.stat)(r.path)).size>262144?i=!0:s=await Bi(r.path)}catch(e){}e.set(o,{contentBeforeWrite:s,fileTooLarge:i})},runCleanup:t=>{e.delete(t)},runPostExecutionHooks:async t=>{const{args:r,result:n,baseHookRequest:o,hookExecutor:s,toolUseId:i}=t,a=e.get(i);if("success"!==n.result.case||!1===s.hasHooksForStep?.(Rd.afterFileEdit))return;const{contentBeforeWrite:c,fileTooLarge:l}=a??{fileTooLarge:!1};let u;u=l||void 0===c?[{old_string:"",new_string:r.fileText}]:c===r.fileText?[]:function(e,t){const r=(0,dS.YB)("","",e,t,"","",{context:0,timeout:50});return void 0===r?[{old_string:"",new_string:t}]:0===r.hunks.length?[]:r.hunks.map((e=>{const t=[],r=[];for(const n of e.lines)n.startsWith("-")?t.push(n.slice(1)):n.startsWith("+")&&r.push(n.slice(1));return{old_string:t.join("\n"),new_string:r.join("\n")}}))}(c,r.fileText);const d={...o,file_path:r.path,edits:u},h=await s.executeHookForStep(Rd.afterFileEdit,d);if(r.returnFileContentAfterWrite&&void 0!==h){const e=n.result.value.path;try{const t=await Bi(e),r=Xs(t),o=Buffer.byteLength(t,"utf8");return new FI.v3({result:{case:"success",value:new FI.j6({path:n.result.value.path,linesCreated:r,fileSize:o,fileContentAfterWrite:t})}})}catch(e){return}}}}}(n))}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}function sj(e,t,r){return t===e.symbol}function ij(e,t,r){return sj(WT,e)?new ej(t,r.hookExecutor,r.baseHookRequestExtractor):sj(re,e)?new nj(t,r.hookExecutor,r.baseHookRequestExtractor):sj(GT,e)?new oj(t,r.hookExecutor,r.baseHookRequestExtractor):sj(ro,e)?new HL(t,r.hookExecutor,r.baseHookRequestExtractor,r.mcpLease,r.hooksConfigLease):sj(tA,e)||sj(rA,e)?new JL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(nA,e)?new jL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(ZT,e)?new NL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(KT,e)?new OL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(VT,e)?new AL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(oA,e)?new ML(t,r.hookExecutor,r.baseHookRequestExtractor):sj(no,e)?new zL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(oo,e)?new VL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(kA,e)?new EL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(_A,e)?new PL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(IA,e)?new IL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(AA,e)?new XL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(Dr,e)&&(r.hooksAdditionalContextPromise||r.hooksConfigLease)?new SL(t,r.hooksAdditionalContextPromise??Promise.resolve(void 0),r.teamHooksReadyPromise,r.hooksConfigLease):void 0}class aj{constructor(e,t,r,n,o,s,i){this.innerAccessor=e,this.hookExecutor=t,this.baseHookRequestExtractor=r,this.mcpLease=n,this.hooksAdditionalContextPromise=o,this.teamHooksReadyPromise=s,this.hooksConfigLease=i}get(e){const t=function(e,t){if(e.symbol===mL.symbol)return new bL(t)}(e,this.hookExecutor);return void 0!==t?t:function(e,t,r){const n=ij(e.symbol,t,r);return void 0!==n?n:t}(e,this.innerAccessor.get(e),{hookExecutor:this.hookExecutor,baseHookRequestExtractor:this.baseHookRequestExtractor,mcpLease:this.mcpLease,hooksAdditionalContextPromise:this.hooksAdditionalContextPromise,teamHooksReadyPromise:this.teamHooksReadyPromise,hooksConfigLease:this.hooksConfigLease})}*entries(){for(const[e,t]of this.innerAccessor.entries()){const r=ij(e.symbol,t,{hookExecutor:this.hookExecutor,baseHookRequestExtractor:this.baseHookRequestExtractor,mcpLease:this.mcpLease,hooksAdditionalContextPromise:this.hooksAdditionalContextPromise,teamHooksReadyPromise:this.teamHooksReadyPromise,hooksConfigLease:this.hooksConfigLease});yield[e,r??t]}const e=mL;yield[e,new bL(this.hookExecutor)]}}const cj={cursor_version:process.env.AGENT_CLI_STATIC_VERSION??"1.0.0",user_email:null};function lj(e=process.cwd()){let t=e;const r={getCwd:async()=>t,clone:e=>lj(e??t),async*execute(e,r,n={}){const o=n.workingDirectory??t;t=o;const s=function(e){return"win32"===process.platform?{executable:(0,No.oG)(),args:[...eF,"-Command",e]}:{executable:process.env.SHELL||"/bin/sh",args:["-lc",e]}}(r),i=(0,iu.spawn)(s.executable,[...s.args],{cwd:o,env:{...process.env,...n.env??{}},signal:n.signal,stdio:[!0===n.pipeStdin?"pipe":"ignore","pipe","pipe"]}),a=[];let c,l,u=!1;const d=()=>{c?.(),c=void 0},h=e=>{a.push(e),d()};for(i.on("spawn",(()=>{!0===n.pipeStdin&&h({type:"stdin_ready",stdin:i.stdin??void 0})})),i.stdout?.setEncoding("utf8"),i.stdout?.on("data",(e=>{h({type:"stdout",data:String(e)})})),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",(e=>{h({type:"stderr",data:String(e)})})),i.on("error",(e=>{l=e,u=!0,d()})),i.on("close",(e=>{h({type:"exit",code:e}),u=!0}));!u||a.length>0;)0!==a.length?yield a.shift():await new Promise((e=>{c=e}));if(void 0!==l)throw l}};return r}function uj(e,t,...r){for(const n of r){const r=t(e[n]);if(void 0!==r)return r}}function dj(e){return"string"==typeof e&&e.length>0?e:void 0}function hj(e){return"object"==typeof e&&null!==e&&"string"==typeof e.id&&"string"==typeof e.value}function pj(e){if(Array.isArray(e)&&e.every(hj))return e.map((e=>({id:e.id,value:e.value})))}class fj{constructor(e,t){this.innerAccessor=e,this.sessionHooksRuntime=t}get(e){return this.innerAccessor.get(e)}entries(){return this.innerAccessor.entries()}async dispose(){await this.sessionHooksRuntime.dispose()}}async function mj(e,t={}){const r=await new SN(new pL,function(e,t){const r=e.projectRoot??e.workingDirectory??e.workspaceRoots[0],n=t.includeProjectHooks??!0,i=t.includeUserHooks??!0;return{enterpriseConfigPath:t.includeEnterpriseHooks??1?yN():void 0,userConfigPath:i?(0,s.join)((0,o.homedir)(),".cursor","hooks.json"):void 0,claudeUserConfigPath:i?(0,s.join)((0,o.homedir)(),".claude","settings.json"):void 0,projectConfigPath:n&&void 0!==r?(0,s.join)(r,".cursor","hooks.json"):void 0,claudeProjectConfigPath:n&&void 0!==r?(0,s.join)(r,".claude","settings.json"):void 0,claudeProjectLocalConfigPath:n&&void 0!==r?(0,s.join)(r,".claude","settings.local.json"):void 0}}(e,t)).load(),n=new LN(r),i=function(e){return e.projectRoot??e.workingDirectory??e.workspaceRoots[0]??process.cwd()}(e),a=function(e){return Object.freeze({...cj,...e.globalContext??{}})}(t);return{projectDir:e.projectRoot,workspacePath:i,hooksConfig:r,hooksConfigLease:n,globalContext:a,createSessionRuntime(){const e=new NN(r,i,a,(t.createTerminalExecutor??lj)(),t.promptHookClient,void 0,void 0,{enableClaudeNestedHookSpecificOutputCompatibility:!0,commandHookPayloadTransport:(o=t.useCommandHookStdinTransport,!0===o?"stdin":"legacy")});var o;return{hookExecutor:e,hooksConfigLease:n,async dispose(){e.clearSessionEnvironment()}}},async dispose(){}}}function gj(e={}){return{createHooksRuntime:t=>mj(t.workspaceState,e)}}var wj=r("../proto/dist/generated/aiserver/v1/dashboard_service_connect.js");async function yj(e){(function(e){return"object"==typeof e&&null!==e&&"dispose"in e&&"function"==typeof e.dispose})(e)&&await e.dispose()}function vj(e={}){const t=e.getThirdPartyExtensibilityEnabled??(()=>!0),r=e.importThirdPartyPlugins??!1,n=e.includeProjectExtensibility??!0,s=e.includeUserExtensibility??!0,i=e.includeManagedSkills??!0,a=e.includePluginExtensibility??!0,c=new xy,l=(0,o.homedir)(),u=bm(l).dirPath;let d,h=!0;return{async prepareLocalExtensibility(){h=i&&await async function(e){if(!e)return!1;const t=(0,be.createClient)(wj.I,e);return"synced"===(await async function(e,t){try{const r=await t.getManagedSkills()??[],n=await OD(e,{managedSkills:[...r]});return{status:"synced",managedSkillsCount:r.length,syncResult:n}}catch(t){return ND.warn(e,"Failed to sync managed skills from source",{error:t}),{status:"fetch_failed",error:t}}}((0,b.q6)(),{getManagedSkills:async()=>(await t.getManagedSkills(new QD.X8g({}))).skills??[]})).status}(e.dashboardTransport)},async loadLocalExtensibility(o){const i=function(e){if(e.workspaceRoots.length>0)return[...e.workspaceRoots];const t=e.projectRoot??e.workingDirectory;return void 0!==t?[t]:[]}(o.workspaceState);if(0===i.length)return d=void 0,{cursorRulesService:xj(),getAgentSkills:async e=>[]};const p=(0,b.q6)(),f=e.loadNestedRules??!0,m=n?i.map((e=>new gg(p,c,e,f,t,void 0))):[],g=function(e,t){const r=bj(t);return{getAllCursorRules:async t=>Sj(await e.getAllCursorRules(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),dispose(){e.dispose()}}}(0===m.length?xj():1===m.length?m[0]:new mg(m,(()=>Lm)),{allowedRoots:n?i:[],excludedRoots:[]}),w=function(e,t){const r=bj(t);return{getAllCursorRules:async t=>Sj(await e.getAllCursorRules(t),r),getAllAgentSkills:async t=>Sj(await e.getAllAgentSkills(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),onDidChangeSkills:t=>e.onDidChangeSkills(t),dispose(){e.dispose()}}}(new yg(p,n?i:[],l,c,f,void 0,t,Promise.resolve(),"sdk"),{allowedRoots:[...n?i:[],...s?[l]:[],...h?[u]:[]],excludedRoots:h?[]:[u]}),y=n?i.map((e=>new Ig(e,t))):[],v=0===y.length?new _g:1===y.length?y[0]:new Ag(y),S=zO(o.services.pluginBootstrapOutputs),k=S&&a?new bg(p,(()=>({importThirdPartyPlugins:r})),void 0,S.pluginsService):void 0,_=S&&a?new $g((()=>({importThirdPartyPlugins:r})),S.pluginsService):void 0,C=new mg([g,w,...k?[k]:[]],(()=>Lm)),E=new gD([w,...k?[k]:[]],(()=>[]),(()=>({workspacePaths:n?i:[],userHomeDirectory:l,agentStoreSkillsDirs:[]}))),x=new Ag([v,..._?[_]:[]]);d={localRulesService:g,localSkillsService:w,localSubagentsService:v,pluginSkillsService:k,pluginSubagentsService:_,mergedCursorRulesService:C,mergedAgentSkillsService:E,mergedSubagentsService:x};const P={cursorRulesService:C,getAgentSkills:e=>E.getAllAgentSkills(e),subagentsService:x};return P},async disposeLocalExtensibility(){if(!d)return;const e=d;d=void 0,await async function(e){let t;const r=[e.mergedSubagentsService,e.mergedAgentSkillsService,e.mergedCursorRulesService,e.pluginSubagentsService,e.pluginSkillsService,e.localSubagentsService,e.localSkillsService,e.localRulesService];for(const e of r)try{await yj(e)}catch(e){t??=e}if(void 0!==t)throw t}(e)}}}function bj(e){const t=Promise.all(e.allowedRoots.map(Cj)),r=Promise.all(e.excludedRoots.map(Cj));return async e=>{const[n,o,s]=await Promise.all([Ej(e.fullPath),t,r]);return void 0!==n&&!s.some((e=>kj(n,e)))&&o.some((e=>kj(n,e)))}}async function Sj(e,t){const r=await Promise.all(e.map(t));return e.filter(((e,t)=>r[t]))}function kj(e,t){if(e===t)return!0;const r=`${t}/`;return e.startsWith(r)}function _j(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")}async function Cj(e){try{return _j(await(0,xo.realpath)(e))}catch{return _j(e)}}async function Ej(e){try{return _j(await(0,xo.realpath)(e))}catch{return}}function xj(){return{getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}}}function Pj(e,t){const r=e.releaseTag??t;if(e.releaseRepo&&e.releaseAsset&&r)return{kind:"release",releaseRepo:e.releaseRepo,releaseAsset:e.releaseAsset,releaseTag:r}}const Rj=/^[a-z][a-z0-9+.-]*:\/\/([^/?#]*)/i,Ij=/^(?:[^@/\s]+@)?([^:/\s\\]+):(?!\/\/)/,Tj=/^([a-z][a-z0-9+.-]*)::(.*)$/i,Aj=/^([a-z][a-z0-9+.-]*):\/\//i,$j=new Set(["file","git","http","https","ssh"]);function Mj(e){if(/^(?:\\\\|\/\/)[^\\/]/.test(e))throw new Error("Cursor Orbit: plugin git remote could not be validated");const t=Tj.exec(e);if(null!==t){const e=t[1].toLowerCase();if(!$j.has(e))throw new Error("Cursor Orbit: plugin git remote could not be validated");const r=t[2];if(!("http"!==e&&"https"!==e||null!==Aj.exec(r)&&URL.canParse(r)))throw new Error("Cursor Orbit: plugin git remote could not be validated");const n=Mj(r);if(0===n.length)throw new Error("Cursor Orbit: plugin git remote could not be validated");return n}const r=Aj.exec(e)?.[1].toLowerCase();if(void 0!==r&&!$j.has(r))throw new Error("Cursor Orbit: plugin git remote could not be validated");const n=Rj.exec(e)?.[1];if(void 0===n){const t=Ij.exec(e)?.[1];if(void 0===t)return[];const r=function(e){const t=/^\[([^\]]+)\]$/.exec(e)?.[1],r=t??e;if(""!==r&&!/[\[\]\s@%\/\\]/.test(r))return Dj(r)}(t);if(void 0===r)throw new Error("Cursor Orbit: plugin git remote could not be validated");return[r]}const o=[];URL.canParse(e)&&o.push(Dj(new URL(e).hostname));const s=function(e){try{return decodeURIComponent(e)}catch{return e}}(n.slice(n.lastIndexOf("@")+1)),i=`https://${s}`;if(URL.canParse(i))o.push(Dj(new URL(i).hostname));else{const e=/^\[([^\]]+)\](?::\d*)?$/.exec(s)?.[1];if(void 0===e)throw new Error("Cursor Orbit: plugin git remote could not be validated");o.push(Dj(e))}const a=o.filter((e=>""!==e));if(0===a.length)throw new Error("Cursor Orbit: plugin git remote could not be validated");return[...new Set(a)]}function Dj(e){return e.trim().toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,"")}function Oj(){const e=["-c","credential.interactive=false","-c","core.fsmonitor=false"];return"1"===process.env[Yv.K4]&&e.push("-c","http.followRedirects=false"),"win32"===process.platform&&e.push("-c","core.longpaths=true"),e}function Fj(e){return"function"==typeof e?e():e}async function Nj(e,t){const r=function(e){const t={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:void 0,VSCODE_GIT_ASKPASS_NODE:void 0,VSCODE_GIT_ASKPASS_MAIN:void 0,VSCODE_GIT_ASKPASS_EXTRA_ARGS:void 0,GCM_INTERACTIVE:"Never"};if(t.GIT_CONFIG_NOSYSTEM=void 0,!0===e?.sshBatchMode){const e=process.env.GIT_SSH_COMMAND?.trim()||"ssh";t.GIT_SSH_COMMAND=`${e} -oBatchMode=yes`}if(void 0!==e?.extraGitConfig){const r=Object.entries(e.extraGitConfig).flatMap((([e,t])=>Array.isArray(t)?t.map((t=>[e,t])):[[e,t]]));t.GIT_CONFIG_COUNT=String(r.length);for(const[e,[n,o]]of r.entries())t[`GIT_CONFIG_KEY_${e}`]=n,t[`GIT_CONFIG_VALUE_${e}`]=o}return{cwd:e?.cwd,env:t}}({cwd:t?.cwd,sshBatchMode:t?.sshBatchMode,extraGitConfig:t?.extraGitConfig}),n=function(e){return function(e,t=process.env){if("1"!==t[Yv.K4])return;const r=(0,Yv.H)(t[Yv.Zf]);for(const t of e)for(const e of Mj(t))if((0,Yv.ad)(e,r))throw new Error(`Cursor Orbit: plugin git egress to ${e} is refused`)}(e),[...Oj(),...e]}(e);try{return await uy("git",n,{...r,...void 0!==t?.timeoutMs&&{timeout:t.timeoutMs,killSignal:"SIGTERM"}})}catch(e){if("1"===process.env[Yv.K4]&&function(e){if("object"!=typeof e||null===e||!("stderr"in e))return!1;const t=e.stderr;return"string"==typeof t&&/The requested URL returned error: 3\d{2}\b/i.test(t)}(e))throw new Error("Cursor Orbit: the plugin gitUrl redirected. Ask an administrator to update gitUrl to the final URL; redirects are disabled for plugin Git operations.",{cause:e});throw e}}const Lj=/^[0-9a-f]{7,40}$/i,jj=/^[0-9a-f]{40}$/i;function Uj(e){if(void 0===e||""===e)return;const t=e.split(/\r?\n/).map((e=>{const[t,r]=e.split("\t");if(t&&r&&/^[0-9a-f]{40}$/i.test(t))return{sha:t,refName:r}})).filter((e=>void 0!==e)),r=t[0];return void 0!==r?t.find((e=>e.refName.endsWith("^{}")))?.sha??r.sha:void 0}async function Bj(e,t,r){const n=t.trim();if(jj.test(n))return{fullSha:n.toLowerCase()};if(Lj.test(n)){try{const t=await async function(e,t,r){const{stdout:n}=await Nj(["ls-remote",e,`refs/heads/${t}`,`refs/tags/${t}`,`refs/tags/${t}^{}`],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs});return Uj(n)?.toLowerCase()}(e,n,r);if(t)return{fullSha:t}}catch{}return{fullSha:n.toLowerCase()}}let o;try{if("HEAD"===n.toUpperCase()){const t=await Nj(["ls-remote","--symref",e,"HEAD"],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs}),n=Uj(t.stdout);if(!n)throw new Error(`git ls-remote did not return a resolvable commit for HEAD (${e})`);return{fullSha:n.toLowerCase(),headSymrefStdout:t.stdout}}o=(await Nj(["ls-remote",e,n],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs})).stdout}catch(t){const r=t instanceof Error?t.message:String(t),o=new Error(`Failed to resolve git ref "${n}" for ${e}: ${r}`);throw o.cause=t,o}const s=Uj(o);if(!s)throw new Error(`git ls-remote did not return a resolvable commit for ref "${n}" (${e})`);return{fullSha:s.toLowerCase()}}const Wj=Vh.map((function(e){const t=e.split("/")[0];if(void 0===t||0===t.length)throw new Error(`Marketplace manifest path has no directory: ${e}`);return t}));let Hj;function qj(e){let t=e.trim().replaceAll("\\","/");for(;t.startsWith("./");)t=t.slice(2);return t=t.replace(/\/+$/,""),""===t||"."===t||t.startsWith("/")||/^[a-zA-Z]:/.test(t)||t.split("/").some((e=>""===e||"."===e||".."===e))?null:t}function zj(e){const t=[];for(const r of e){const e=qj(r);if(null===e)return"all";t.push(e)}return t}async function Gj(e,t){const r="all"===e?"all":zj(e),n=t&&"all"!==r&&await(process.env.CURSOR_DISABLE_SPARSE_PLUGIN_CLONES?Promise.resolve(!1):(Hj??=(async()=>{try{const{stdout:e}=await Nj(["--version"]),t=function(e){const t=/git version (\d+)\.(\d+)/.exec(e);return t?{major:Number(t[1]),minor:Number(t[2])}:null}(e);return null!==t&&(t.major>2||2===t.major&&t.minor>=28)}catch{return!1}})(),Hj));return{materialize:r,sparse:n,sparseDirs:n?(o=r,[...new Set([...Wj,...o])]):[]};var o}function Vj(e){return e.toLowerCase().includes("filtering not recognized by server")}async function Kj(e,t,r){await Nj(["sparse-checkout","set","--cone","--",...t],{...r,cwd:e})}async function Jj(e){try{await(0,xo.access)((0,s.join)(e,".git","info","sparse-checkout"))}catch{return!1}try{const{stdout:t}=await Nj(["config","--bool","--get","core.sparseCheckout"],{cwd:e});return"true"===t.trim()}catch{return!1}}async function Zj(e,t,r){if("all"!==t&&0===t.length)return;if(!await Jj(e))return;const n={...r,cwd:e,sshBatchMode:!0};if("all"===t)return void await Nj(["sparse-checkout","disable"],n);const o=zj(t);"all"!==o?await Nj(["sparse-checkout","add","--",...o],n):await Nj(["sparse-checkout","disable"],n)}(0,Es.J)((function(){Hj=void 0}));const Xj=/\.git$/i,Qj=new Set(["account","dashboard"]);function Yj(e){return e.replace(Xj,"")}function eU(e){let t;try{t=decodeURIComponent(e)}catch{return}return t.length>0&&!t.includes("/")?t:void 0}function tU(e){const t=e.toLowerCase();return"github.com"===t||t.endsWith(".github.com")}function rU(e){return e.toLowerCase().split(".").includes("gitlab")}function nU(e){const t=e.toLowerCase();return"bitbucket.org"===t||"www.bitbucket.org"===t}function oU(e){const t=e.toLowerCase();return rU(e)?"GitLab":t.includes("bitbucket")?"Bitbucket":t.includes("gitea")||t.includes("codeberg")?"Gitea/Codeberg":t.includes("azure")&&t.includes("dev")?"Azure DevOps":null}function sU(e){return tU(e)?"github":rU(e)?"gitlab":nU(e)?"bitbucket":function(e){const t=e.toLowerCase();return"dev.azure.com"===t||"www.dev.azure.com"===t}(e)?"azure_devops":"generic"}function iU(e){let t;try{const r=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;t=new URL(r.includes("://")?r:`https://${r}`)}catch{return null}const r=t.hostname;let n=t.pathname.split("/").filter(Boolean);Ka(r)&&"git"===n[0]?.toLowerCase()&&(n=n.slice(1));const o=n[0];void 0!==o&&n.length>=3&&"scm"===o.toLowerCase()&&(n=n.slice(1));const s=function(e){const t=e[0],r=e[1];if(!t||!r)return;const n=Yj(r);return n?{owner:t,repo:n,hasSubpath:e.length>2}:void 0}(n);return void 0===s?null:{provider:sU(r),owner:s.owner,repo:s.repo,host:r}}function aU(e){const t=cU(e);if(null===t)return!1;const r=t.pathname.split("/").filter(Boolean),n=r[0];return void 0!==n&&r.length>=3&&"scm"===n.toLowerCase()}function cU(e){try{const t=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;return new URL(t.includes("://")?t:`https://${t}`)}catch{return null}}function lU(e){const t=e.trim();if(""===t)return{error:"URL cannot be empty"};const r=iU(t);if(null===r)return{error:"Invalid URL format. Expected: github.com/owner/repo or gitlab.com/namespace/repo"};if(rU(r.host)){const e=cU(t),r=null===e?void 0:function(e){const t=e.indexOf("-"),r=-1!==t,n=r?e.slice(0,t):[...e];if(n.length<2||n.some((e=>0===e.length)))return;const o=Yj(n[n.length-1]);return o?(n[n.length-1]=o,{repositorySegments:n,hasSpecialRouteSeparator:r}):void 0}(e.pathname.split("/").filter(Boolean));if(null===e||void 0===r)return{error:"Invalid GitLab repository URL format. Expected: https://gitlab.com/namespace/repo"};const n=e.host.replace(/^www\./i,""),o=r.repositorySegments[0],s=r.repositorySegments[r.repositorySegments.length-1];return void 0===o||void 0===s?{error:"Invalid GitLab repository URL format. Expected: https://gitlab.com/namespace/repo"}:{url:`https://${n}/${r.repositorySegments.join("/")}`,owner:o,repo:s,host:n,provider:"gitlab"}}if("bitbucket"===r.provider){const e=function(e){const t=cU(e.trim());if(null!==t&&nU(t.hostname))return function(e){const t=e[0],r=e[1];if(void 0===t||void 0===r)return;const n=eU(t),o=eU(r);if(void 0===n||void 0===o||Qj.has(n.toLowerCase()))return;const s=Yj(o);return s?{workspace:encodeURIComponent(n),repo:encodeURIComponent(s),hasSubpath:e.length>2}:void 0}(function(e){const t=e.pathname.split("/");return""===t[0]&&t.shift(),""===t[t.length-1]&&t.pop(),t}(t))}(t);if(void 0===e)return{error:"Invalid Bitbucket repository URL format. Expected: https://bitbucket.org/{workspace}/{repo}"};const n=r.host.replace(/^www\./i,"");return{url:`https://${n}/${e.workspace}/${e.repo}`,owner:e.workspace,repo:e.repo,host:n,provider:"bitbucket"}}if("azure_devops"===r.provider){const e=cU(t),n=null===e?void 0:function(e){const t=e.findIndex((e=>"_git"===e.toLowerCase()));if(t<1||t>2)return;const r=e[0],n=e[t+1];if(!r||!n)return;const o=Yj(n);if(!o)return;const s=2===t?e[1]:o;return s?{organization:r,project:s,repo:o,hasSubpath:e.length>t+2}:void 0}(e.pathname.split("/").filter(Boolean));if(null===e||void 0===n)return{error:"Invalid Azure DevOps repository URL format. Expected: https://dev.azure.com/{organization}/{project}/_git/{repo}"};const o=r.host.replace(/^www\./i,"");return{url:`https://${o}/${n.organization}/${n.project}/_git/${n.repo}`,owner:n.organization,repo:n.repo,host:o,provider:"azure_devops",project:n.project}}if(function(e){switch(e.provider){case"github":return!0;case"generic":return!Ka(e.host)&&null===oU(e.host);case"gitlab":case"bitbucket":case"azure_devops":return!1;default:return e.provider,!1}}(r)){const e=dU(r.host.replace(/^www\./i,""));return{url:`https://${e}/${aU(t)?"scm/":""}${r.owner}/${r.repo}`,owner:r.owner,repo:r.repo,host:e,provider:"github"}}const n=oU(r.host);return{error:"Only GitHub, GitLab, Bitbucket, and Azure DevOps URLs are currently supported."+(null!==n?` ${n} is not supported yet.`:"")}}function uU(e){const t=lU(e);if("error"in t)return null;switch(t.provider){case"github":return`git@${t.host}:${t.owner}/${t.repo}.git`;case"gitlab":return function(e){let t;try{t=new URL(e.url).pathname.replace(/^\//,"").replace(/\.git$/i,"")}catch{return null}if(0===t.length)return null;return`git@${e.host.replace(/:\d+$/,"")}:${t}.git`}(t);case"bitbucket":case"azure_devops":return null;default:return t.provider,null}}function dU(e){return tU(e)?"github.com":e}function hU(e){return!e.operatingSystems||0===e.operatingSystems.length||e.operatingSystems.includes(function(){const e=(0,o.platform)();return"win32"===e?"Windows":"darwin"===e?"Macintosh":"Linux"}())}function pU(e){return/[\n\r:#[\]{}&*!|>'"%@`]/.test(e)||e.startsWith(" ")||e.endsWith(" ")?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:e}const fU=new Set(["con","prn","aux","nul","com1","com2","com3","com4","com5","com6","com7","com8","com9","lpt1","lpt2","lpt3","lpt4","lpt5","lpt6","lpt7","lpt8","lpt9"]);function mU(e){const t=ih(e).replace(/[. ]+$/g,"");return""===t||"."===t||".."===t?"_":fU.has(t.toLowerCase())?`_${t}`:t}const gU=18e5,wU=6e5,yU={recursive:!0,force:!0,maxRetries:3},vU=["terminal prompts disabled","could not read username","host key verification failed","could not read from remote repository","permission denied","repository not found","user cancelled dialog","spawn git enoent","authentication failed","unable to get password from user","you do not have access to"],bU=["enotempty: directory not empty, rename","/_staging/"],SU=["upload-pack: not our ref","server does not allow request for unadvertised object"];function kU(e){const t=String(e).toLowerCase().replaceAll("\\","/");return vU.some((e=>t.includes(e)))?"user_git_access":bU.every((e=>t.includes(e)))?"local_cache_race":SU.some((e=>t.includes(e)))?"stale_pinned_ref":"infrastructure"}function _U(e){return"object"==typeof e&&null!==e&&(!0===e.killed||_U(e.cause))}function CU(e){return _U(e)?"killed_by_budget":kU(e)}function EU(e){const t=lU(e);if(!("error"in t)&&"gitlab"===t.provider){let r;try{r=new URL(t.url).pathname.replace(/^\//,"")}catch{throw new Error(`Invalid git URL: ${e}`)}const n=r.split("/").filter(Boolean).map((e=>e.toLowerCase()));if(n.length<2)throw new Error(`Invalid git URL: ${e}`);return{host:t.host.toLowerCase(),pathSegments:n}}const r=iU(e);if(null===r)throw new Error(`Invalid git URL: ${e}`);return{host:dU(r.host.replace(/^www\./i,"")).toLowerCase(),pathSegments:[r.owner.toLowerCase(),r.repo.toLowerCase()]}}const xU=new Map;class PU{constructor(e,t){this.cacheRoot=e,this.options=t,this.manifestCache=new Map}get sparsePluginClones(){return this.options?.sparsePluginClones??!1}remoteTimeoutMs(){return this.sparsePluginClones?gU:void 0}localTimeoutMs(){return this.sparsePluginClones?wU:void 0}lsRemoteTimeoutMs(){return this.sparsePluginClones?3e4:void 0}async cloneResolvedRef(e,t,r,n){const o={cwd:e,sshBatchMode:n?.sshBatchMode,extraGitConfig:{...Fj(this.options?.extraGitConfig),"safe.directory":e}},{sparse:s,sparseDirs:i}=await Gj(n?.materialize??"all",this.sparsePluginClones);await Nj(["init"],{...o,timeoutMs:this.localTimeoutMs()}),s&&await Kj(e,i,{sshBatchMode:n?.sshBatchMode,extraGitConfig:Fj(this.options?.extraGitConfig),timeoutMs:this.localTimeoutMs()});const{stderr:a}=await Nj(["fetch","--depth","1",...s?["--filter=blob:none"]:[],t,r],{...o,timeoutMs:this.remoteTimeoutMs()});return await Nj(["checkout","FETCH_HEAD"],{...o,timeoutMs:this.remoteTimeoutMs()}),{strategy:s?"sparse":"full",filterIgnoredByServer:s&&Vj(a??"")}}async createStagingDir(){const e=(0,s.join)(this.cacheRoot,"_staging",(0,ko.randomUUID)());return await(0,xo.mkdir)(e,{recursive:!0}),e}async moveToCanonicalDir(e,t){return await(0,xo.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,xo.rm)(t,yU),await(0,xo.rename)(e,t),t}async cleanStaleStagingDirs(){const e=(0,s.join)(this.cacheRoot,"_staging");try{const t=await(0,xo.readdir)(e,{withFileTypes:!0}),r=Date.now();await Promise.all(t.filter((e=>e.isDirectory())).map((async t=>{try{const n=(0,s.join)(e,t.name),o=await(0,xo.stat)(n);r-o.mtimeMs>PU.STALE_STAGING_THRESHOLD_MS&&await(0,xo.rm)(n,yU)}catch{}})))}catch{}}getLegacyCloneDir(e,t){return(0,s.join)(this.cacheRoot,mU(e),mU(t))}getCanonicalCloneDir(e,t){const{host:r,pathSegments:n}=EU(e);return(0,s.join)(this.cacheRoot,mU(r),...n.map(mU),mU(t))}getCanonicalRepoRootDir(e){const{host:t,pathSegments:r}=EU(e);return(0,s.join)(this.cacheRoot,mU(t),...r.map(mU))}async pruneSiblingCloneDirs(e,t,r){const n=this.getCanonicalRepoRootDir(e),o=mU(t);try{const e=await(0,xo.readdir)(n,{withFileTypes:!0});await Promise.all(e.filter((e=>e.isDirectory()&&e.name!==o)).map((e=>(0,xo.rm)((0,s.join)(n,e.name),yU))))}catch{}if(void 0!==r)try{await(0,xo.rm)(r,yU)}catch{}}async ensureCloned(e,t,r,n=$p,o){const s=this.serializedOnRepo(this.getCanonicalRepoRootDir(t),(()=>this.ensureClonedImpl(e,t,r,n,o?.materialize??"all")));return this.sparsePluginClones?s:(0,Nr.wj)(s,3e4,`ensureCloned timed out after 30000ms for ${t} @ ${r}`)}async ensureMaterialized(e,t,r=$p){const n=this.serializedOnRepo((0,s.dirname)(e),(async()=>{const n=performance.now();try{await Zj(e,t,{extraGitConfig:Fj(this.options?.extraGitConfig),timeoutMs:this.remoteTimeoutMs()}),r.increment("marketplace_cache_manager.ensure_materialized.success",1),r.distribution("marketplace_cache_manager.ensure_materialized.duration",performance.now()-n)}catch(o){throw r.log("error","Failed to materialize plugin directories in sparse marketplace clone",{clonePath:e,spec:"all"===t?"all":t.join(","),error:String(o),errorCategory:CU(o)}),r.increment("marketplace_cache_manager.ensure_materialized.error",1,{error_category:CU(o)}),r.distribution("marketplace_cache_manager.ensure_materialized.duration",performance.now()-n,{outcome:"error"}),o}}));return this.sparsePluginClones?n:(0,Nr.wj)(n,3e4,`ensureMaterialized timed out after 30000ms for ${e}`)}async serializedOnRepo(e,t){const r=`${this.cacheRoot}:${e}`,n=(xU.get(r)??Promise.resolve()).catch((()=>{})).then(t);xU.set(r,n);try{return await n}finally{xU.get(r)===n&&xU.delete(r)}}async ensureClonedImpl(e,t,r,n,o){n.log("info",`MarketplaceCacheManager: Ensuring cloned ${e} at ${t}@${r}`,{marketplaceId:e,gitUrl:t,ref:r});const s=r.trim();let i,a=t.startsWith("git@")||t.startsWith("ssh://")?null:uU(t);if(null!==a)try{i=(await Bj(a,s,{sshBatchMode:!0,extraGitConfig:Fj(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}catch(e){if(this.sparsePluginClones&&_U(e))throw e;n.log("debug","Failed to resolve remote ref using SSH URL, falling back to HTTPS",{gitUrl:t,ref:r,error:String(e),errorCategory:kU(e)}),a=null,i=(await Bj(t,s,{extraGitConfig:Fj(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}else i=(await Bj(t,s,{extraGitConfig:Fj(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha;const c=this.getCanonicalCloneDir(t,i),l=this.getLegacyCloneDir(e,s);n.log("info",`MarketplaceCacheManager: Resolved clone directory for ${e} at ${t}@${r} to ${c}`,{marketplaceId:e,resolvedRef:i,originalRef:s});const u=performance.now(),d=(e,t)=>{n.increment(`marketplace_cache_manager.ensure_cloned.${e}`,1,t),n.distribution(`marketplace_cache_manager.ensure_cloned.${e}.duration`,performance.now()-u,t)};if(await this.isCloneComplete(c)){await this.pruneSiblingCloneDirs(t,i,l);const e=await Jj(c);return e&&await Zj(c,o,{extraGitConfig:Fj(this.options?.extraGitConfig),timeoutMs:this.remoteTimeoutMs()}),d("cache_hit",{strategy:e?"sparse":"full"}),c}return n.increment("marketplace_cache_manager.ensure_cloned.cache_miss",1),this.cloneViaStaging(c,t,a,i,l,r,n,d,o)}async cloneViaStaging(e,t,r,n,o,s,i,a,c){await this.cleanStaleStagingDirs();const l=await this.createStagingDir();i.log("info",`MarketplaceCacheManager: Cloning ${t}@${s} into staging directory: ${l}`,{gitUrl:t,ref:s,cloneDir:e});const u=this.sparsePluginClones?setInterval((()=>{const e=new Date;(0,xo.utimes)(l,e,e).catch((()=>{}))}),PU.STAGING_HEARTBEAT_INTERVAL_MS):void 0;u?.unref?.();try{let u;if(null!==r)try{u=await this.cloneResolvedRef(l,r,n,{sshBatchMode:!0,materialize:c})}catch(e){if(this.sparsePluginClones&&_U(e))throw e;i.log("debug","Falling back to HTTPS clone due to SSH clone failure",{gitUrl:t,ref:s,error:String(e),errorCategory:CU(e)}),await(0,xo.rm)(l,yU),await(0,xo.mkdir)(l,{recursive:!0}),u=await this.cloneResolvedRef(l,t,n,{materialize:c})}else u=await this.cloneResolvedRef(l,t,n,{materialize:c});u.filterIgnoredByServer&&(i.log("warn","Server ignored --filter=blob:none; sparse clone downloaded a full pack",{gitUrl:t,ref:s}),i.increment("marketplace_cache_manager.ensure_cloned.filter_ignored_by_server",1));const d=await this.moveToCanonicalDir(l,e);return await this.pruneSiblingCloneDirs(t,n,o),a("cache_write_success",{strategy:u.strategy}),d}catch(e){const r=CU(e);throw a("error",{error_category:r}),i.log("error","Failed to clone marketplace repository via staging clone",{gitUrl:t,ref:s,error:String(e),errorCategory:r}),i.captureException(e,{error_type:"clone_marketplace_repository",error_category:r}),e}finally{void 0!==u&&clearInterval(u);try{await(0,xo.rm)(l,yU)}catch{}}}async isCloneComplete(e){try{if(!(await(0,xo.stat)(e)).isDirectory())return!1;const t=await(0,xo.readdir)(e);if(!t.includes(".git"))return!1;if(t.length>1)return!0;try{return(await(0,xo.stat)((0,s.join)(e,".git","info","sparse-checkout"))).isFile()}catch{return!1}}catch{return!1}}getPluginDir(e,t){return Sf(e,t)}async copyPluginToDir(e,t){await(0,xo.mkdir)(t,{recursive:!0}),await(0,xo.cp)(e,t,{recursive:!0,verbatimSymlinks:!0})}async readManifest(e,t={}){const r=function(e,t){return JSON.stringify({clonePath:e,repoName:t.repoName??null,fallbackId:t.fallbackId??null})}(e,t);if(this.manifestCache.has(r))return this.manifestCache.get(r)??null;const n=await async function(e,t={}){for(const r of Vh){const n=(0,s.join)(e,r);let o;try{o=await(0,xo.readFile)(n,"utf-8")}catch{continue}const i=kp(o,t);if(i.success)return i.data}return null}(e,t);return this.manifestCache.set(r,n),n}async resolvePluginPath(e,t){const r=await this.readManifest(e);if(!r)return null;const n=r.plugins.find((e=>e.name===t.toLowerCase()));if(!n)return null;const o=Cp(n.source,r.metadata?.pluginRoot);return o&&Ep(o)?o:null}async discoverPlugins(e){const t=await this.readManifest(e);return t?function(e){const t=[],r=function(e,t){const r=[];for(const n of e){const e=n.source;if("string"!=typeof e)switch(e.source){case"github":r.push({entry:n,kind:"external-github",externalUrl:`https://github.com/${e.repo}.git`,externalRef:e.ref,externalSha:e.sha,effectiveRef:e.sha??e.ref});break;case"url":r.push({entry:n,kind:"external-url",externalUrl:e.url,externalRef:e.ref,externalSha:e.sha,effectiveRef:e.sha??e.ref});break;case"git-subdir":r.push({entry:n,kind:"external-git-subdir",externalUrl:e.url,externalRef:e.ref,externalSha:e.sha,effectiveRef:e.sha??e.ref,subdirPath:e.path})}else{const o=Cp(e,t);null!==o?r.push({entry:n,kind:"local",localPath:o}):r.push({entry:n,kind:"unresolvable",rawSource:e})}}return r}(e.plugins,e.metadata?.pluginRoot);for(const e of r){const{name:r,displayName:n,description:o,version:s}=e.entry,i={name:r,displayName:n,description:o,version:s};switch(e.kind){case"local":Ep(e.localPath)&&t.push({...i,sourceType:"local",gitPath:e.localPath});break;case"external-github":t.push({...i,sourceType:"github",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha});break;case"external-url":t.push({...i,sourceType:"url",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha});break;case"external-git-subdir":t.push({...i,sourceType:"git-subdir",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha,subdirPath:e.subdirPath})}}return t}(t):[]}}PU.STALE_STAGING_THRESHOLD_MS=3e5,PU.STAGING_HEARTBEAT_INTERVAL_MS=6e4;const RU=(0,Vs.debuglog)("cursor-plugins");function IU(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function TU(e){return IU(e)?e:void 0}function AU(e){const t=e.name?.trim();return void 0!==t&&t.length>0?t:e.pluginId}function $U(e,t){return void 0!==e?.marketplace?e.marketplace:void 0!==e?.marketplaceId?(t??[]).find((t=>void 0!==t.id&&String(t.id)===String(e.marketplaceId))):void 0}function MU(e,t){const r=t?.distributionGitUrl?.trim();return r?t?.gitUrl&&!qU(e,t.gitUrl)?e:r:e}function DU(e){return e?.distributionGitUrl?.trim()||e?.gitUrl}function OU(e,t){if(e.pinnedGitRef)return e.pinnedGitRef;if(e.plugin?.gitRef)return e.plugin.gitRef;const r=$U(e.plugin,t),n=e.plugin?.gitUrl,o=r?.gitUrl;return n&&o&&n!==o||!r?.gitRef?"main":r.gitRef}const FU="backend-git://";function NU(e,t,r){const n=r?`#${encodeURIComponent(r)}`:"";return`${FU}${encodeURIComponent(e)}@${encodeURIComponent(t)}${n}`}function LU(e){if(!e.startsWith(FU))return null;const t=e.slice(14),r=t.indexOf("#"),n=r>=0?t.slice(0,r):t,o=r>=0?t.slice(r+1):void 0,s=n.lastIndexOf("@");return s<0?null:{gitUrl:decodeURIComponent(n.slice(0,s)),ref:decodeURIComponent(n.slice(s+1)),gitPath:o?decodeURIComponent(o):void 0}}const jU="backend-release://";function UU(e){const t=e.tag?`@${encodeURIComponent(e.tag)}`:"";return`${jU}${encodeURIComponent(e.repo)}#${encodeURIComponent(e.asset)}${t}`}function BU(e){if(!e.startsWith(jU))return null;const t=e.slice(18),r=t.indexOf("#");if(r<0)return null;const n=decodeURIComponent(t.slice(0,r)),o=t.slice(r+1),s=o.lastIndexOf("@");return{repo:n,asset:s>=0?decodeURIComponent(o.slice(0,s)):decodeURIComponent(o),tag:s>=0?decodeURIComponent(o.slice(s+1)):void 0}}const WU=/^[0-9a-f]{7,40}$/i;function HU(e){let t;try{t=EU(e)}catch{return null}return`${t.host}\0${t.pathSegments.join("\0")}`}function qU(e,t){if(e.trim()===t.trim())return!0;const r=HU(e),n=HU(t);return null!==r&&r===n}const zU=104857600;async function GU(e,t,r,n,i,a){const c=await async function(e){const{repo:t,asset:r,tag:n}=e,{apiBase:o,ownerRepo:s,host:i}=function(e){const t=e.split("/"),r=t[0],n=t[1],o=t[2];if(3===t.length&&void 0!==r&&void 0!==n&&void 0!==o)return{apiBase:`https://${r}/api/v3`,ownerRepo:`${n}/${o}`,host:r};if(2===t.length)return{apiBase:"https://api.github.com",ownerRepo:e,host:"github.com"};throw new Error(`Invalid release repo format: ${e}`)}(t),a="github.com"===i&&void 0!==e.githubToken&&e.githubToken.length>0?{Authorization:`token ${e.githubToken}`}:{},c=n?`${o}/repos/${s}/releases/tags/${encodeURIComponent(n)}`:`${o}/repos/${s}/releases/latest`,l=await fetch(c,{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"CursorPluginInstaller",...a}});if(!l.ok)throw new Error(`Failed to fetch release from ${c}: ${l.status} ${l.statusText}`);const u=await l.json();if(!(IU(d=u)&&Array.isArray(d.assets)&&d.assets.every((e=>IU(e)&&"string"==typeof e.name&&"string"==typeof e.browser_download_url&&"number"==typeof e.size))))throw new Error(`Release payload from ${c} did not include assets`);var d;const h=u,p=h.assets.find((e=>e.name===r));if(!p){const e=h.assets.map((e=>e.name)).join(", ");throw new Error(`Release asset "${r}" not found. Available assets: ${e}`)}if(p.size>zU)throw new Error(`Release asset "${r}" exceeds maximum size of 104857600 bytes (actual: ${p.size})`);const f=new URL(p.browser_download_url);if("https:"!==f.protocol||!VU(f.hostname,i))throw new Error(`Refusing to download release asset from untrusted host: ${f.hostname}`);const m=await fetch(p.browser_download_url,{headers:{"User-Agent":"CursorPluginInstaller",Accept:"application/octet-stream",...a}});if(!m.ok)throw new Error(`Failed to download release asset: ${m.status} ${m.statusText}`);if(m.url){const e=new URL(m.url);if("https:"!==e.protocol||!VU(e.hostname,i))throw new Error(`Refusing to download release asset: redirected to untrusted host: ${e.hostname}`)}const g=Buffer.from(await m.arrayBuffer());if(g.byteLength>zU)throw new Error(`Release asset "${r}" actual download size exceeds maximum of 104857600 bytes (actual: ${g.byteLength})`);if(e.expectedSha256){const t=(0,ko.createHash)("sha256").update(g).digest("hex");if(t!==e.expectedSha256)throw new Error(`Release asset "${r}" integrity check failed: expected SHA-256 ${e.expectedSha256}, got ${t}`)}return g}({repo:e,asset:t,tag:r,expectedSha256:i,githubToken:a}),l=c.byteLength;await(0,xo.mkdir)(n,{recursive:!0});const u=await(0,xo.mkdtemp)((0,s.join)((0,o.tmpdir)(),"release-asset-")),d=(0,s.join)(u,"asset.tar.gz"),h=(0,s.join)(u,"extracted");try{await(0,xo.writeFile)(d,c),await(0,xo.mkdir)(h,{recursive:!0});let e=0,t=0;await ah.x({file:d,cwd:h,onReadEntry:r=>{if(t++,t>5e4)throw new Error("Release archive contains too many files (>50000).");if(e+=r.size,e>524288e3)throw new Error("Release archive uncompressed size exceeds maximum of 524288000 bytes.");if(l>0&&e/l>100)throw new Error("Release archive has suspicious compression ratio (>100x).")}});const r=await(0,xo.readdir)(h,{withFileTypes:!0}),o=r.filter((e=>e.isDirectory())),i=r.filter((e=>e.isFile()));let a=h;const u=o[0];if(1===o.length&&0===i.length&&void 0!==u){const e=(0,s.join)(h,u.name);(await(0,xo.readdir)(e)).some((e=>Gh.includes(e)))&&(a=e)}const p=await(0,xo.readdir)(a);await Promise.all(p.map((e=>(0,xo.cp)((0,s.join)(a,e),(0,s.join)(n,e),{recursive:!0,verbatimSymlinks:!0}))))}finally{await(0,xo.rm)(u,{recursive:!0,force:!0}).catch((()=>{}))}}function VU(e,t){return!(e!==t&&!e.endsWith(".githubusercontent.com"))||("github.com"===t?"github.com"===e:e.endsWith(`.${t}`))}class KU{constructor(e,t,r,n,o){this.getEffectiveUserPlugins=e;const s="string"==typeof t||void 0===t?{marketplaceCacheRoot:t,pluginLogger:r,marketplaceCacheOptions:n,listOptions:o}:t,i=s.marketplaceCacheOptions??n;this.pluginLogger=s.pluginLogger??r??$p,this.extraGitConfig=s.extraGitConfig,this.awaitAuthReady=s.awaitAuthReady,this.githubToken=s.githubToken,this.downloadPluginContent=s.downloadPluginContent,this.contentRetries=s.contentRetries??(new Eh).forListing(""),this.sparsePluginClones=s.sparsePluginClones??!1,this.marketplaceCache=s.marketplaceCacheRoot?new PU(s.marketplaceCacheRoot,{...i,extraGitConfig:i?.extraGitConfig??s.extraGitConfig,sparsePluginClones:this.sparsePluginClones}):void 0;const a=s.listOptions??o;this.allowedMarketplaceNames=a?.allowedMarketplaceNames?new Set(a.allowedMarketplaceNames):void 0,this.enableInlinePlugins=a?.enableInlinePlugins??!1}isMarketplaceAllowed(e){return void 0===this.allowedMarketplaceNames||void 0!==e?.name&&this.allowedMarketplaceNames.has(e.name)}async listEnabledPlugins(e,t){const r=await this.getEffectiveUserPlugins(),n=r.plugins??[],o=r.marketplaces??[],s=[],i=[],a=new Map,c=async(e,t)=>{const r=`${e}\0${t}`;let n=a.get(r);if(!n){const o=Fj(this.extraGitConfig),s=this.sparsePluginClones?3e4:void 0,i=e.startsWith("git@")||e.startsWith("ssh://")?null:uU(e),c=async(e,r)=>{const n={};return r&&(n.sshBatchMode=!0),void 0!==o&&(n.extraGitConfig=o),void 0!==s&&(n.timeoutMs=s),(Object.keys(n).length>0?await Bj(e,t,n):await Bj(e,t)).fullSha};if(null!==i)try{n=await c(i,!0)}catch(t){if(this.sparsePluginClones&&_U(t))throw t;n=await c(e,!1)}else n=await c(e,!1);a.set(r,n)}return n},l=async e=>{const{preferredGitUrl:t,sourceGitUrl:r,gitRef:n,pluginId:o}=e;if(t!==r){void 0!==this.awaitAuthReady&&await this.awaitAuthReady();const e=`${t}\0${n}`,s=!a.has(e);let i;s&&this.pluginLogger.increment("marketplace.origin_distribution.fetch",1);try{i={sha:await c(t,n),gitUrl:t}}catch(e){s&&this.pluginLogger.increment("marketplace.origin_distribution.fetch.error",1),this.pluginLogger.captureException(e,{error_type:"distribution_url_fallback"}),this.pluginLogger.log("warn",`Distribution mirror ${t}@${n} unavailable (not synced yet or unreachable); falling back to source ${r}`,{pluginId:o,preferredGitUrl:t,sourceGitUrl:r,gitRef:n,error:String(e)})}if(void 0!==i){if(s)try{this.pluginLogger.log("info",`Resolved plugin ${o} from Origin distribution mirror ${t}@${n}`,{pluginId:o,preferredGitUrl:t,gitRef:n})}catch{}return i}}return{sha:await c(r,n),gitUrl:r}};this.contentRetries.startLoad();for(const e of n){if(!e.isEnabled||!e.plugin?.name)continue;const t=e.plugin,r=$U(t,o);if(!this.isMarketplaceAllowed(r)){this.pluginLogger.log("info",`Skipping plugin ${t.name} because marketplace ${r?.name??""} is not allowed`,{pluginId:t.name,marketplaceName:r?.name,allowedMarketplaceNames:void 0!==this.allowedMarketplaceNames?Array.from(this.allowedMarketplaceNames):void 0});continue}const n=AU({name:t.name,pluginId:void 0!==t.id?String(t.id):t.name??""}),a=n;if(void 0!==t.backendContent&&null!==t.backendContent){const t=this.listBackendContentPlugin(e,r,n);"entry"in t?s.push(t.entry):i.push(t.failure);continue}if(!t.gitUrl){if(!this.enableInlinePlugins){this.pluginLogger.log("info",`Skipping plugin ${n} without gitUrl (enableInlinePlugins=false)`,{pluginId:a});continue}const o=e.inlineContentJson;if(!o){this.pluginLogger.log("info",`Skipping DB-inline plugin ${n}: no inline content provided`,{pluginId:a});continue}const i=(0,ko.createHash)("sha256").update(`${t.id??"0"}:${t.updatedAt??"0"}`).digest("hex").slice(0,40),c=r?.name?{id:void 0!==r.id?`${r.name}-${r.id}`:`${r.name}-inline`,name:r.name}:void 0;this.pluginLogger.log("info",`BackendMarketplaceClient: Adding DB-inline plugin: ${a}`,{pluginId:a,marketplaceId:c?.id??"unknown",version:i}),s.push({pluginId:a,pluginDbId:void 0!==t.id?String(t.id):void 0,configuredVariables:TU(e.configuredVariables),isTeamRequired:e.isTeamRequired,name:n,version:i,downloadUrl:`inline://${t.id??a}`,marketplaceDbId:void 0!==r?.id?String(r.id):void 0,marketplace:c,inlineContentJson:o});continue}const c=t.gitUrl,u=MU(c,r),d=OU(e,o),h=Pj(t,d),p=r?.gitRef??d;let f,m,g=u;try{if(void 0!==h)f=`release/${h.releaseTag}`;else{const e=await l({preferredGitUrl:u,sourceGitUrl:c,gitRef:d,pluginId:a});f=e.sha,g=e.gitUrl}}catch(e){this.pluginLogger.captureException(e,{error_type:"resolve_version_sha"}),this.pluginLogger.log("error",`Failed to resolve version for plugin ${n}@${d}, skipping plugin`,{pluginId:a,ref:d,error:String(e)});const o=e instanceof Error?e.message:String(e);i.push({pluginName:n,pluginId:a,pluginDbId:void 0!==t.id?String(t.id):void 0,marketplaceName:r?.name,errorMessage:o,errorType:/timed?\s*out/i.test(o)?"timeout":"clone"});continue}m=void 0!==h?UU({repo:h.releaseRepo,asset:h.releaseAsset,tag:h.releaseTag}):NU(g,d,t.gitPath??void 0);const w=DU(r);let y=w,v=r?.gitUrl,b=p;if(r?.gitUrl&&w){const e=qU(c,r.gitUrl),t=e?g:w,o=e?c:r.gitUrl,s=e?d:p;v=o;try{const e=await l({preferredGitUrl:t,sourceGitUrl:o,gitRef:s,pluginId:a});b=e.sha,y=e.gitUrl}catch(e){this.pluginLogger.captureException(e,{error_type:"resolve_marketplace_cache_ref"}),this.pluginLogger.log("warn",`Failed to resolve marketplace cache ref for plugin ${n} from ${t}@${s}, falling back to raw ref`,{pluginId:a,cacheRepoUrl:t,cacheRef:s,error:String(e)}),y=o}}const S=r?.name?{id:void 0!==r.id?`${r.name}-${r.id}`:`${r.name}-${encodeURIComponent(r.gitUrl??"project")}`,name:r.name,...y&&{gitUrl:y,gitRef:b}}:void 0,k=void 0!==h||g===c&&y===v?void 0:{downloadUrl:NU(c,d,t.gitPath??void 0),marketplaceGitUrl:v};this.pluginLogger.log("info",`BackendMarketplaceClient: Adding enabled plugin: ${a} from ${b} at ${t.gitPath}`,{pluginId:a,marketplaceId:S?.id??"unknown",gitPath:t.gitPath??void 0,gitRef:b}),s.push({pluginId:a,pluginDbId:void 0!==t.id?String(t.id):void 0,configuredVariables:TU(e.configuredVariables),isTeamRequired:e.isTeamRequired,name:n,version:f,downloadUrl:m,marketplaceDbId:void 0!==r?.id?String(r.id):void 0,marketplace:S,gitPath:t.gitPath??void 0,isOriginBacked:void 0===h&&g!==c||void 0,originSourceFallback:k})}return{plugins:s,listFailures:i}}isBackendContentRetryDue(){return this.contentRetries.isRetryDue()}allowImmediateBackendContentRetry(){this.contentRetries.allowImmediateRetry()}listBackendContentPlugin(e,t,r){const n=xh(e.plugin?.id),o=function(e){const{revision:t}=e;return"string"==typeof t&&wh.test(t)?{revision:t}:{invalid:"revision"}}(e.plugin?.backendContent??{}),s=void 0===n?"plugin_id":"invalid"in o?o.invalid:void 0;if(void 0===n||"invalid"in o)return this.pluginLogger.log("error",`Skipping plugin ${r}: the listing's backend content has an unusable ${s}`,{pluginId:r,invalidField:s}),this.pluginLogger.increment("backend_marketplace_client.backend_content.list.invalid",1),{failure:{pluginName:r,pluginId:r,pluginDbId:n,marketplaceName:t?.name,errorMessage:`Plugin ${JSON.stringify(r)} could not be installed: the server listed it with details this client does not accept.`,errorType:"install"}};const i=t?.name?{id:void 0!==t.id?`${t.name}-${t.id}`:`${t.name}-backend-content`,name:t.name}:void 0;return this.pluginLogger.log("info",`BackendMarketplaceClient: Adding backend-served plugin: ${r}`,{pluginId:r,marketplaceId:i?.id??"unknown",revision:o.revision}),{entry:{pluginId:r,pluginDbId:n,configuredVariables:TU(e.configuredVariables),isTeamRequired:e.isTeamRequired,name:r,version:Rh(o.revision),downloadUrl:(a={pluginDbId:n,revision:o.revision},`${bh}${a.pluginDbId}@${a.revision}`),marketplaceDbId:void 0!==t?.id?String(t.id):void 0,marketplace:i,backendContent:o}};var a}async relistPlugin(e){if(void 0===e.backendContent||void 0===e.pluginDbId)return;const t=await this.getEffectiveUserPlugins(),r=(t.plugins??[]).find((t=>!0===t.isEnabled&&xh(t.plugin?.id)===e.pluginDbId)),n=r?.plugin;if(void 0===r||!n?.name||void 0===n.backendContent||null===n.backendContent)return;const o=$U(n,t.marketplaces??[]);if(!this.isMarketplaceAllowed(o))return;const s=this.listBackendContentPlugin(r,o,e.name);return"entry"in s&&s.entry.version!==e.version?s.entry:void 0}async installBackendContentPlugin(e,t){const r=e.backendContent,n=xh(e.pluginDbId);if(void 0===r||void 0===n)throw new Error(`Plugin ${JSON.stringify(e.name)} has no backend content to install`);const o={pluginDbId:n,revision:r.revision},s=this.contentRetries.heldFailure(o);if(void 0!==s)throw Ih(s,e.name);const i=performance.now();let a="success";try{await Ah({download:this.downloadPluginContent,pluginDbId:n,pluginName:e.name,content:r,targetDir:t}),this.contentRetries.recordAttempt(o)}catch(e){throw a=e instanceof mh?e.reason:"unknown",this.contentRetries.recordAttempt({...o,error:e}),e}finally{this.pluginLogger.increment("backend_marketplace_client.backend_content.install",1,{outcome:a}),this.pluginLogger.distribution("backend_marketplace_client.backend_content.install.duration",performance.now()-i,{outcome:a})}this.pluginLogger.log("info",`Installed backend-served plugin ${e.pluginId}`,{pluginId:e.pluginId,revision:r.revision})}isDirectInstallSameFetch(e){const t=e.marketplace;if(!t?.gitUrl||!t.gitRef)return!1;const r=LU(e.downloadUrl);return!(!r||!qU(r.gitUrl,t.gitUrl)||r.ref!==t.gitRef&&e.version!==t.gitRef)}async installPlugin(e,t){if(void 0!==e.backendContent||Ph(e.downloadUrl))await this.installBackendContentPlugin(e,t);else if(e.inlineContentJson)await async function(e){const{targetDir:t,inlineContentJson:r,pluginName:n}=e,o=JSON.parse(r);await(0,xo.mkdir)(t,{recursive:!0});const i={};if(o.rules&&o.rules.length>0){const e=(0,s.join)(t,"rules");await(0,xo.mkdir)(e,{recursive:!0});const r=[];for(const t of o.rules){if(!t.content)continue;if(!1===t.isActive)continue;const n=`${ih(t.name)}.md`,o=[];o.push(`description: ${pU(t.name)}`),t.globs&&t.globs.length>0&&o.push(`globs: ${pU(t.globs.join(", "))}`),o.push(`alwaysApply: ${!0===t.isRequired}`);const i=`---\n${o.join("\n")}\n---\n\n`;await(0,xo.writeFile)((0,s.join)(e,n),i+t.content,"utf-8"),r.push(`rules/${n}`)}r.length>0&&(i.rules=r)}if(o.commands&&o.commands.length>0){const e=(0,s.join)(t,"commands");await(0,xo.mkdir)(e,{recursive:!0});const r=[];for(const t of o.commands){if(!t.content)continue;if(!1===t.isActive)continue;const n=`${ih(t.name)}.md`,o=t.description?`---\ndescription: ${pU(t.description)}\n---\n\n`:"";await(0,xo.writeFile)((0,s.join)(e,n),o+t.content,"utf-8"),r.push(`commands/${n}`)}r.length>0&&(i.commands=r)}if(o.hooks&&o.hooks.length>0){const e=(0,s.join)(t,"hooks");await(0,xo.mkdir)(e,{recursive:!0});const r={};for(const e of o.hooks){const t=e.hookStep;t&&!1!==e.isActive&&hU(e)&&(r[t]||(r[t]=[]),"prompt"===e.hookType?r[t].push({type:"prompt",prompt:e.promptContent??"",...e.promptModel?{model:e.promptModel}:{}}):r[t].push({type:"command",command:e.scriptContent??""}))}await(0,xo.writeFile)((0,s.join)(e,"hooks.json"),JSON.stringify({version:1,hooks:r},null,2),"utf-8")}if(o.mcpServers&&o.mcpServers.length>0){const e={};for(const t of o.mcpServers)t.config&&(e[t.name]=t.config);Object.keys(e).length>0&&await(0,xo.writeFile)((0,s.join)(t,".mcp.json"),JSON.stringify({mcpServers:e},null,2),"utf-8")}const a={name:n,...i},c=(0,s.join)(t,".cursor-plugin");await(0,xo.mkdir)(c,{recursive:!0}),await(0,xo.writeFile)((0,s.join)(c,"plugin.json"),JSON.stringify(a,null,2),"utf-8")}({targetDir:t,inlineContentJson:e.inlineContentJson,pluginName:e.name});else{e.isOriginBacked&&void 0!==this.awaitAuthReady&&await this.awaitAuthReady();try{return void await this.installFromEntryUrls(e,t)}catch(r){const n=function(e){const t=e.originSourceFallback;if(void 0===t)return;let r=e.marketplace;if(void 0!==r)if(void 0!==t.marketplaceGitUrl)r={...r,gitUrl:t.marketplaceGitUrl};else{const{gitUrl:e,gitRef:t,...n}=r;r=n}return{...e,downloadUrl:t.downloadUrl,marketplace:r,isOriginBacked:void 0,originSourceFallback:void 0}}(e);if(void 0===n)throw r;this.pluginLogger.captureException(r,{error_type:"install_plugin_from_origin_distribution"}),this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from the Origin distribution mirror, falling back to the source repo`,{pluginId:e.pluginId,version:e.version,sourceDownloadUrl:n.downloadUrl,sourceMarketplaceGitUrl:n.marketplace?.gitUrl,error:String(r)}),this.pluginLogger.increment("marketplace.origin_distribution.install.source_fallback",1),await(0,xo.rm)(t,{recursive:!0,force:!0});try{await this.installFromEntryUrls(n,t)}catch(e){throw this.pluginLogger.increment("marketplace.origin_distribution.install.source_fallback.error",1),e}}}}async installFromEntryUrls(e,t){if(null===BU(e.downloadUrl))try{if(await this.tryInstallFromMarketplaceCache(e,t))return void this.emitOriginLoadIfApplicable(e)}catch(t){if(this.pluginLogger.captureException(t,{error_type:"install_plugin_from_marketplace_cache"}),this.sparsePluginClones&&this.isDirectInstallSameFetch(e)&&_U(t))throw this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from marketplace cache; skipping direct install fallback because it would repeat the identical fetch`,{pluginId:e.pluginId,version:e.version,error:String(t)}),t;this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from marketplace cache, falling back to direct install`,{pluginId:e.pluginId,version:e.version,error:String(t)})}await async function(e,t,r=$p,n,i){const a=i?.sparsePluginClones??!1,c=a?gU:void 0,l=BU(e.downloadUrl);if(l){if(e.gitPath){const r=await(0,xo.mkdtemp)((0,s.join)((0,o.tmpdir)(),"release-plugin-"));try{await GU(l.repo,l.asset,l.tag,r,i?.expectedReleaseAssetSha256,i?.githubToken);const n=Sf(r,e.gitPath);await(0,xo.mkdir)(t,{recursive:!0}),await(0,xo.cp)(n,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,xo.rm)(r,{recursive:!0,force:!0}).catch((()=>{}))}}else await GU(l.repo,l.asset,l.tag,t,i?.expectedReleaseAssetSha256,i?.githubToken);return}const u=LU(e.downloadUrl);if(!u)throw new Error(`Invalid download URL format for plugin ${e.pluginId}: ${e.downloadUrl}`);const d=await(0,xo.mkdtemp)((0,s.join)((0,o.tmpdir)(),"backend-plugin-"));try{let o;if(await async function(e,t,r,n=$p,o,s="all",i=!1){const a=performance.now(),c=WU.test(t),l="HEAD"===t.toUpperCase(),u={...o,"safe.directory":r},d=i?gU:void 0,h=i?wU:void 0,{sparse:p,sparseDirs:f}=await Gj(s,i),m=p?["--filter=blob:none","--sparse"]:[],g=!!p||void 0,w=async e=>{p&&await Kj(r,f,{extraGitConfig:u,timeoutMs:e,sshBatchMode:!0})},y=async(e,n)=>{let o;return l?(({stderr:o}=await Nj(["clone","--depth","1",...m,e,r],{extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await w(d)):c?(await Nj(["init"],{cwd:r,extraGitConfig:u,timeoutMs:h}),await Nj(["remote","add","origin",e],{cwd:r,extraGitConfig:u,timeoutMs:h}),await w(h),({stderr:o}=await Nj(["fetch","--depth","1",...p?["--filter=blob:none"]:[],"origin",t],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await Nj(["checkout","FETCH_HEAD"],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})):(({stderr:o}=await Nj(["clone","--depth","1","--branch",t,...m,e,r],{extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await w(d)),o},v=e.startsWith("git@")||e.startsWith("ssh://")?null:uU(e);let b;if(null!==v)try{b=await y(v,!0)}catch(t){if(i&&_U(t))throw t;await(0,xo.rm)(r,{recursive:!0,force:!0}),await(0,xo.mkdir)(r,{recursive:!0}),b=await y(e,g)}else b=await y(e,g);p&&Vj(b)&&(n.log("warn",`shallowClone: server ignored --filter=blob:none for ${e}; sparse clone downloaded a full pack`),n.increment("backend_marketplace_client.shallow_clone.filter_ignored_by_server",1));const S=(performance.now()-a).toFixed(1);RU("shallowClone %s@%s completed in %sms",e,t,S),n.log("info",`shallowClone ${e}@${t} completed in ${S}ms (${p?"sparse":"full"})`)}(u.gitUrl,u.ref,d,r,n,u.gitPath?zj([u.gitPath]):[],a),u.gitPath)o=Sf(d,u.gitPath);else{const t=await async function(e,t){for(const r of Vh){const n=(0,s.join)(e,r);let o;try{o=await(0,xo.readFile)(n,"utf-8")}catch{continue}const i=kp(o);if(!i.success)return{type:"manifest-unresolved",reason:`Invalid marketplace manifest at ${r}: ${i.error}`};const a=i.data,c=a.plugins.find((e=>e.name===t.toLowerCase()));if(!c)return{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} not found in ${r}`};if("string"!=typeof c.source&&"git-subdir"===c.source.source)return{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} uses unsupported git-subdir source`};const l=Cp(c.source,a.metadata?.pluginRoot);return l&&Ep(l)?{type:"resolved",gitPath:l}:{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} has unresolved or unsafe source path`}}return{type:"no-manifest"}}(d,e.name);if("resolved"===t.type)await Zj(d,zj([t.gitPath]),{extraGitConfig:n,timeoutMs:c}),o=Sf(d,t.gitPath);else{if("manifest-unresolved"===t.type)throw new Error(`Unable to install plugin ${JSON.stringify(e.name)} without gitPath: ${t.reason}`);await Zj(d,"all",{extraGitConfig:n,timeoutMs:c}),o=d}}await(0,xo.mkdir)(t,{recursive:!0}),await(0,xo.cp)(o,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,xo.rm)(d,{recursive:!0,force:!0}).catch((()=>{}))}}(e,t,this.pluginLogger,Fj(this.extraGitConfig),{githubToken:this.githubToken,sparsePluginClones:this.sparsePluginClones}),this.emitOriginLoadIfApplicable(e)}emitOriginLoadIfApplicable(e){if(e.isOriginBacked)try{this.pluginLogger.increment("marketplace.origin_distribution.load",1),this.pluginLogger.log("info",`Loaded plugin ${e.pluginId} from Origin distribution (fetch complete)`,{pluginId:e.pluginId})}catch{}}async prewarmMarketplaceClones(e){const t=this.marketplaceCache;if(!t)return;const r=new Map;for(const t of e){const e=t.marketplace;if(!e?.gitUrl)continue;const n=e.gitRef??"main",o=`${e.id}\0${e.gitUrl}\0${n}`;let s=r.get(o);void 0===s&&(s={marketplaceId:e.id,gitUrl:e.gitUrl,gitRef:n,gitPaths:[]},r.set(o,s)),t.gitPath&&s.gitPaths.push(t.gitPath)}for(const e of r.values()){const r=zj(e.gitPaths),n=performance.now();try{await t.ensureCloned(e.marketplaceId,e.gitUrl,e.gitRef,this.pluginLogger,{materialize:r}),this.pluginLogger.log("info",`Prewarmed marketplace clone ${e.gitUrl}@${e.gitRef} for ${e.gitPaths.length} plugin directories`,{marketplaceId:e.marketplaceId,gitUrl:e.gitUrl,gitRef:e.gitRef,requestedDirs:e.gitPaths.length,materialize:"all"===r?"all":r.length}),this.pluginLogger.increment("marketplace_cache_manager.prewarm.success",1,{materialize:"all"===r?"all":"dirs"})}catch(t){this.pluginLogger.captureException(t,{error_type:"prewarm_marketplace_clone"}),this.pluginLogger.log("warn",`Failed to prewarm marketplace clone ${e.gitUrl}@${e.gitRef}; falling back to per-plugin materialization`,{marketplaceId:e.marketplaceId,gitUrl:e.gitUrl,gitRef:e.gitRef,error:String(t)}),this.pluginLogger.increment("marketplace_cache_manager.prewarm.error",1)}this.pluginLogger.distribution("marketplace_cache_manager.prewarm.duration",performance.now()-n)}}async tryInstallFromMarketplaceCache(e,t){const r=this.marketplaceCache,n=e.marketplace;if(!r||!n||!n.gitUrl)return this.pluginLogger.log("info","No marketplace cache or marketplace metadata, skipping cache check",{pluginId:e.pluginId,name:e.name,version:e.version,marketplaceId:e.marketplace?.id}),!1;const o=await r.ensureCloned(n.id,n.gitUrl,n.gitRef??"main",this.pluginLogger,{materialize:e.gitPath?zj([e.gitPath]):[]}),s=e.gitPath??await r.resolvePluginPath(o,e.name);if(!s)return this.pluginLogger.log("info","No git path found for plugin, skipping cache check",{pluginId:e.pluginId,name:e.name,version:e.version,marketplaceId:e.marketplace?.id}),!1;void 0===e.gitPath&&await r.ensureMaterialized(o,zj([s]),this.pluginLogger);const i=r.getPluginDir(o,s);return await r.copyPluginToDir(i,t),!0}async discoverMarketplacePlugins(e,t,r){const n=this.marketplaceCache;if(!n)throw new Error("discoverMarketplacePlugins requires a MarketplaceCacheManager (marketplaceCacheRoot)");const o=await n.ensureCloned(e,t,r,this.pluginLogger,{materialize:[]});return n.discoverPlugins(o)}}function JU(e,t,r,n,o){return new KU(e,t,r,n,o)}function ZU(e){const t=e.trim();if(!t)return!1;if(t.startsWith("git@"))return/^git@[a-zA-Z0-9.-]+:[a-zA-Z0-9._~\-/]+(?:\.git)?$/.test(t);try{const e=new URL(t);return"https:"===e.protocol&&""===e.username&&""===e.password&&""===e.search&&""===e.hash}catch{return!1}}class XU extends Error{constructor(e){super(e),this.name="SettingsParseError"}}function QU(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function YU(e){return 65279===e.charCodeAt(0)?e.slice(1):e}async function eB(e){try{return YU(await(0,xo.readFile)(function(e){return(0,s.join)(e,".cursor","settings.json")}(e),"utf-8"))}catch(e){if(function(e){return e instanceof Error&&"code"in e}(e)&&("ENOENT"===e.code||"ENOTDIR"===e.code))return;throw e}}async function tB(e){const t=await eB(e);return void 0===t?[]:function(e){const t=function(e){const t=YU(e);if(0===t.trim().length)return{};const r=[],n=(0,xp.qg)(t,r,{allowTrailingComma:!0});if(r.length>0){const e=r.slice(0,3).map((e=>`${(0,xp._n)(e.error)} at offset ${e.offset}`)).join("; ");throw new XU(`.cursor/settings.json contains syntax errors: ${e}`)}if(!QU(n))return{};const o=n.plugins;if(void 0===o)return{};if(!QU(o))return{};const s={};for(const[e,t]of Object.entries(o))QU(t)&&(s[e]=t);return{plugins:s}}(e);return t.plugins?Object.entries(t.plugins).filter((([,e])=>!0===e.enabled)).filter((([,e])=>!e.gitUrl||ZU(e.gitUrl))).map((([e,t])=>({key:e,entry:t}))):[]}(t)}function rB(e){const t=e.indexOf("/");return-1===t?{name:e}:{name:e.slice(t+1),marketplaceName:e.slice(0,t)}}const nB={supportsBackendContent:!0};function oB(e={}){const t=e.userHomeDirectory??(0,o.homedir)(),r=e.importThirdPartyPlugins??!1,n=e.pluginLogger??{log(e,t,r){switch(e){case"warn":CO.Jz.warn("[local-plugins-bootstrap]",t,r??{});break;case"error":CO.Jz.error("[local-plugins-bootstrap]",t,r??{})}},increment(){},distribution(){},captureException(e,t){CO.Jz.error("[local-plugins-bootstrap] Unexpected plugin exception:",e,t??{})}},i=sB(e.marketplaceOptions),a=void 0!==e.dashboardTransport,c=e.loadCursorFirstParty??(i||a);return{async loadPluginBootstrapOutputs(o){const i=(a=o.workspaceState).projectRoot??a.workspaceRoots[0]??a.workingDirectory;var a;const{discoveredEntries:l,failures:u}=await async function(e){if(void 0===e)return{discoveredEntries:[],failures:[]};try{return{discoveredEntries:(await tB(e)).map((({key:t,entry:r})=>({source:"project-settings",workspacePath:e,key:t,entry:r}))),failures:[]}}catch(e){return{discoveredEntries:[],failures:[{stage:"discovery",source:"project-settings",message:e instanceof Error?`Failed to read project plugin settings: ${e.message}`:`Failed to read project plugin settings: ${String(e)}`,detail:e}]}}}(i),d=e.marketplaceOptions??(e.dashboardTransport?function(e){const t=(0,s.join)(e.userHomeDirectory,".cursor","plugins","marketplaces"),r=(0,be.createClient)(wj.I,e.dashboardTransport),n=(e,{signal:t})=>r.downloadPluginContent(e,{signal:t}),o=new Eh,i=JU((async()=>{try{return await r.getEffectiveUserPlugins(new QD.EwF(nB))}catch{return{plugins:[]}}}),{marketplaceCacheRoot:t,listOptions:{allowedMarketplaceNames:["cursor-public"]},downloadPluginContent:n,contentRetries:o.forListing("account")}),a=e.workspacePath,c=JU((async()=>{if(void 0===a)return{plugins:[]};try{const e=await tB(a);if(0===e.length)return{plugins:[]};const t=e.filter((e=>e.entry.gitUrl)),n=e.filter((e=>!e.entry.gitUrl)),o=t.filter((({entry:e})=>{const t=e.gitUrl;return!t||ZU(t)})).map((({key:e,entry:t})=>{const r=rB(e),n=t.gitUrl;return{plugin:{name:r.name,gitUrl:n,gitRef:t.gitRef,gitPath:t.gitPath,marketplace:{name:r.marketplaceName,gitUrl:n,gitRef:t.gitRef}},isEnabled:!0}}));let s=[];if(n.length>0)try{const e=n.map((e=>{const t=rB(e.key);return new QD.vwy({name:t.name,marketplaceName:t.marketplaceName})})),t=await r.resolvePluginsByRef(new QD.WvV({refs:e,...nB}));s=t.plugins?.map((e=>({plugin:e,isEnabled:!0})))??[]}catch{}return{plugins:[...o,...s]}}catch{return{plugins:[]}}}),{marketplaceCacheRoot:t,listOptions:{allowedMarketplaceNames:["cursor-public"]},downloadPluginContent:n,contentRetries:o.forListing("project")});return[{client:i,userId:"",cacheManager:new fh(e.userHomeDirectory),pruneOldVersions:!0},{client:c,userId:"",cacheManager:new fh(e.userHomeDirectory),pruneOldVersions:!0}]}({dashboardTransport:e.dashboardTransport,workspacePath:i,userHomeDirectory:t}):void 0),h=sB(d),p=new HD(void 0!==i?[i]:[],t,(()=>({importThirdPartyPlugins:r,loadCursorFirstParty:c})),d,n);let f=[];const m=[...u];try{f=await p.getAllEnabledPlugins()}catch(e){m.push({stage:"resolution",source:"plugin-loader",message:e instanceof Error?`Failed to load plugins: ${e.message}`:`Failed to load plugins: ${String(e)}`,detail:e})}l.length>0&&!h&&m.push({stage:"resolution",source:"plugin-loader",message:"Project plugin entries were discovered, but no marketplace-backed project plugin source was configured. Those entries remain available through discoveredEntries only.",detail:{workspacePath:i,discoveredEntryCount:l.length}});const g={kind:qO,discoveredEntries:l,loadedPlugins:f,loadFailures:p.getLoadFailures(),bootstrapFailures:m,pluginsService:p,async dispose(){}};for(const e of m)CO.Jz.warn("[local-plugins-bootstrap] Plugin bootstrap failure:",{workspacePath:i,stage:e.stage,source:e.source,message:e.message,detail:e.detail});for(const e of g.loadFailures)CO.Jz.warn("[local-plugins-bootstrap] Plugin load failure:",{workspacePath:i,pluginName:e.pluginName,pluginId:e.pluginId,marketplaceName:e.marketplaceName,errorType:e.errorType,errorMessage:e.errorMessage});return[g]}}}function sB(e){return void 0!==e&&(!Array.isArray(e)||e.length>0)}class iB{async getAllCursorRules(e){return[]}reload(e){}dispose(){}onDidChangeRules(e){return()=>{}}}const aB=["projectFolder","terminalsFolder","agentSharedNotesFolder","agentConversationNotesFolder","agentTranscriptsFolder","processWorkingDirectory","artifactsFolder"];function cB(e){if(e.length<=1)return e;let t=e.length;for(;t>1&&("/"===(r=e[t-1])||"\\"===r)&&(3!==t||":"!==e[1]);)t-=1;var r;return e.slice(0,t)}function lB(e){const t=cB(e).replaceAll("\\","/");return/^[A-Za-z]:\/$/.test(t)?t.slice(0,-1):t}function uB(e){const t=cB(e.reportedWorkspacePath);if(""===e.suffix)return t;const r=t.replaceAll("\\","/"),n="/"===r?e.suffix:`${r}${e.suffix}`;return t.includes("\\")?n.replaceAll("/","\\"):n}function dB(e){const t=lB(e.value),r=e.roots.filter((e=>e.host.length>0)).sort(((e,t)=>lB(t.host).length-lB(e.host).length));for(const e of r){const r=lB(e.host);if(t===r)return uB({reportedWorkspacePath:e.reported,suffix:""});const n="/"===r?"/":`${r}/`;if(t.startsWith(n)){const n="/"===r?t:t.slice(r.length);return uB({reportedWorkspacePath:e.reported,suffix:n})}}}const hB={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1};class pB extends cD{constructor(e,t){super(e),this.sessionMcpLease=t}async dispose(){try{await super.dispose()}finally{await yj(this.sessionMcpLease)}}}function fB(e){const t=new xy;return{async createResources(r){const n=e.createSessionDependencies?.(r)??{pendingDecisionStore:e.pendingDecisionStore,fileChangeTracker:e.fileChangeTracker,permissionsService:e.permissionsService};if(!n.pendingDecisionStore||!n.fileChangeTracker||!n.permissionsService)throw new Error("Local resource provider factory requires either shared dependencies or a per-session dependency factory.");const o=r.workspaceServices.cursorRulesService??new iB,s=r.workspaceServices.subagentsService??new _g,i=r.workspaceServices.mcpLease??new oI,a=!0===r.options.excludeProjectMcp,c=void 0!==r.options.mcpServersOverride||a?void 0!==e.createSessionMcpLease?await e.createSessionMcpLease(r,r.options.mcpServersOverride):a?new oI:void 0:void 0,l=(u=c??i,0===(d=r.options.extraMcpTools??[]).length?u:"onDidChange"in(h=u)&&"function"==typeof h.onDidChange?new Kw(u,d):new Vw(u,d));var u,d,h;try{const i=await async function(e,t){return void 0===e?{}:"function"==typeof e?await e({sessionId:t.sessionState.sessionId,metadata:t.metadata}):e}(r.options.localResourceProviderOptions,r),a=await async function(e){if(void 0===e)return hB;try{const t=await e();return{powershellUtf8Console:t.powershellUtf8Console,powershellUtf8ChildEnv:t.powershellUtf8ChildEnv}}catch{return hB}}(e.getPowershellUtf8Options),u={pendingDecisionStore:n.pendingDecisionStore,fileChangeTracker:n.fileChangeTracker,gitExecutor:t,ignoreService:e.ignoreService,grepProvider:e.grepProvider,permissionsService:n.permissionsService,workspacePaths:e.workspacePaths,diagnosticsProvider:e.diagnosticsProvider,mcpLease:l,mcpStateAccessor:e.createMcpStateAccessor?.(l,r.options),cursorRulesService:o,subagentsService:s,repositoryProvider:e.repositoryProvider,projectDir:e.projectDir,shellManager:e.shellManager,_defaultSandboxPolicy:e.defaultSandboxPolicy??{type:"insecure_none"},_defaultSandboxPolicySources:e.defaultSandboxPolicySources,getSandboxEnabled:e.getSandboxEnabled,getSandboxSupported:e.getSandboxSupported,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:e.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:e.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:e.getMockPromptTime,mcpFileOutputThresholdBytes:e.mcpFileOutputThresholdBytes,mcpMetaToolEnabled:e.mcpMetaToolEnabled,attributionConfigProvider:e.attributionConfigProvider,getAgentSkills:r.workspaceServices.getAgentSkills,powershellUtf8Console:a.powershellUtf8Console,powershellUtf8ChildEnv:a.powershellUtf8ChildEnv,...i},d=void 0===c?new cD(u):new pB(u,c);return void 0===r.options.reportedWorkspacePath&&void 0===r.options.reportedProjectFolder||function(e,t){const r=e.get(Dr);if(void 0===r)return;const{reportedWorkspacePath:n,reportedProjectFolder:o}=t,s=void 0===n?[]:t.workspacePaths.map((e=>({host:e,reported:n}))),i=o??n;void 0!==i&&s.push({host:t.projectDir,reported:i}),e.register(Dr,{execute:async(e,t,o)=>function(e,t){if("success"!==e.result.case||void 0===e.result.value.requestContext?.env)return e;const r=e.clone();if("success"!==r.result.case)return e;const n=r.result.value.requestContext?.env;if(void 0===n)return r;const{roots:o,reportedWorkspacePath:s}=t;n.workspacePaths=n.workspacePaths.map((e=>dB({value:e,roots:o})??e));for(const e of aB){const t=n[e];if(void 0===t||""===t)continue;const r=dB({value:t,roots:o});n[e]="processWorkingDirectory"===e&&void 0!==s?r??cB(s):r??t}return r}(await r.execute(e,t,o),{roots:s,reportedWorkspacePath:n})})}(d,{reportedWorkspacePath:r.options.reportedWorkspacePath,reportedProjectFolder:r.options.reportedProjectFolder,workspacePaths:u.workspacePaths,projectDir:u.projectDir}),d}catch(e){throw await yj(c),e}}}}const mB=["cursorRulesService","getAgentSkills","subagentsService"],gB=new WeakSet;function wB(e){("object"==typeof e&&null!==e||"function"==typeof e)&&gB.add(e)}function yB(e){return("object"==typeof e&&null!==e||"function"==typeof e)&&gB.has(e)}function vB(e,t){const r=Object.keys(t).filter((e=>!mB.includes(e)));if(r.length>0)throw new Error(`Workspace service contributors may only provide ${mB.join(", ")}. Received unsupported service keys: ${r.join(", ")}.`);for(const r of mB)Object.hasOwn(t,r)&&(e[r]=t[r])}async function bB(e,t,r){const n={config:void 0,plugins:[],pluginBootstrapOutputs:[],cursorRulesService:void 0,getAgentSkills:void 0,subagentsService:void 0,mcpLease:void 0,hooksRuntime:void 0};try{n.config=e.config?await e.config.loadConfig(t):void 0,n.plugins=e.plugins?await e.plugins.loadPlugins(t):[];const o=()=>({workspaceState:t,policy:r,services:n});n.pluginBootstrapOutputs=e.pluginBootstrap?await e.pluginBootstrap.loadPluginBootstrapOutputs(o()):n.pluginBootstrapOutputs,n.mcpLease=e.mcp?await e.mcp.createLease(o()):void 0,n.hooksRuntime=e.hooks?await e.hooks.createHooksRuntime(o()):void 0,e.localExtensibility?.prepareLocalExtensibility&&await e.localExtensibility.prepareLocalExtensibility(o());const s=e.localExtensibility?await e.localExtensibility.loadLocalExtensibility(o()):void 0;void 0!==s&&(wB(s.cursorRulesService),wB(s.subagentsService),Object.assign(n,s));for(const t of e.workspaceServicesContributors??[]){const e=await t.contributeServices(o());void 0!==e&&vB(n,e)}return n}catch(t){try{await SB(n,{disposeLocalExtensibility:void 0===e.localExtensibility?void 0:()=>e.localExtensibility?.disposeLocalExtensibility?.()})}catch(e){throw function(e,t){return new AggregateError([t],"Workspace service loading failed and resource cleanup also failed.",{cause:e})}(t,e)}throw t}}async function SB(e,t){const r=t?.preserveSharedContributorsFrom;let n;const o=async e=>{try{await yj(e)}catch(e){n??=e}};if(e.subagentsService===r?.subagentsService||yB(e.subagentsService)||await o(e.subagentsService),e.cursorRulesService===r?.cursorRulesService||yB(e.cursorRulesService)||await o(e.cursorRulesService),t?.disposeLocalExtensibility)try{await t.disposeLocalExtensibility()}catch(e){n??=e}await o(e.hooksRuntime),await o(e.mcpLease);try{await async function(e){let t;for(let r=e.length-1;r>=0;r-=1)try{await yj(e[r])}catch(e){t??=e}if(void 0!==t)throw t}(e.pluginBootstrapOutputs)}catch(e){n??=e}if(void 0!==n)throw n}const kB=["project","user","team","mdm","plugins"],_B=new Set([...kB,"all"]);function CB(e){if(void 0===e||0===e.length)return xB([]);for(const t of e)if(!_B.has(t))throw new Error(`Unsupported setting source "${t}"`);if(e.includes("all")){if(e.length>1)throw new Error('settingSources cannot mix "all" with individual setting sources');return{...xB(kB),all:!0}}return xB(e.filter((e=>"all"!==e)))}function EB(e,t){return e[t]}function xB(e){const t=new Set(e);return{project:t.has("project"),user:t.has("user"),team:t.has("team"),mdm:t.has("mdm"),plugins:t.has("plugins"),all:!1}}const PB=Object.freeze({}),RB=Object.freeze({allowMcpServers:!0,allowPlugins:!0,allowBackgroundSessions:!0,requireMcpApproval:!1,maxParallelSessions:void 0,sandboxMode:void 0,metadata:PB});async function IB(e){const t=new Set;let r;for(let n=e.length-1;n>=0;n-=1){const o=e[n];if(!t.has(o)){t.add(o);try{await yj(o)}catch(e){r??=e}}}if(void 0!==r)throw r}async function TB(e={}){const t=function(e={}){return{workspace:e.workspace??SO,config:e.config,plugins:e.plugins,pluginBootstrap:e.pluginBootstrap,mcp:e.mcp,hooks:e.hooks,localExtensibility:e.localExtensibility,resourceFactory:e.resourceFactory,resourceWrappers:e.resourceWrappers,workspaceServicesContributors:e.workspaceServicesContributors,lifecycle:e.lifecycle}}(e.adapters),r=await t.workspace.resolveWorkspaceState({workingDirectory:e.workingDirectory,projectRoot:e.projectRoot,projectDirectory:e.projectDirectory,workspaceRoots:e.workspaceRoots}),n=await async function(e,t){return e.resolvePolicy(t)}(e.policyAdapter??function(e={}){const t=Object.freeze({...RB.metadata,...e.metadata}),r={...RB,...e,metadata:t};return{name:"permissive-sdk-local",resolvePolicy:()=>r}}(),{workspaceState:r});let o=await bB(t,r,n),s=!1,i=Promise.resolve();const a=e=>{const t=i.then(e);return i=t.catch((()=>{})),t},c=t.localExtensibility,l=void 0===c?void 0:()=>c.disposeLocalExtensibility?.();return{state:r,get services(){return o},policy:n,async createSessionRuntime(e={}){if(s)throw new Error("Cannot create a session runtime after the workspace runtime has been disposed.");return async function(e){const t={sessionId:e.options?.sessionId??(0,ye.C)(),createdAt:new Date},r=Object.freeze({...e.options?.metadata??{}}),n={options:e.options??{},workspaceState:e.workspaceState,workspaceServices:e.workspaceServices,policy:e.policy,sessionState:t,metadata:r,getAgentSkills:e.workspaceServices.getAgentSkills};let o,s;const i=[];try{o=e.adapters.resourceFactory?await e.adapters.resourceFactory.createResources(n):void 0,s=o,i.push(o);for(const t of e.adapters.resourceWrappers??[])s=await t.wrapResources({...n,baseResources:o,resources:s}),i.push(s);await(e.adapters.lifecycle?.onSessionCreated?.(t))}catch(e){try{await IB(i)}catch(t){throw function(e,t){return new AggregateError([t],"Session creation failed and resource cleanup also failed.",{cause:e})}(e,t)}throw e}let a=!1;return{state:t,resources:{base:o,wrapped:s},metadata:r,workspaceServices:e.workspaceServices,policy:e.policy,async dispose(){if(!a){a=!0;try{await IB(i)}finally{await(e.adapters.lifecycle?.onSessionDisposed?.(t))}}}}}({options:e,workspaceState:r,workspaceServices:o,policy:n,adapters:t})},async reload(){s||await a((async()=>{if(s)return;const e=o,i=await bB(t,r,n);s?await SB(i,{disposeLocalExtensibility:l}):(o=i,await SB(e,{preserveSharedContributorsFrom:i,disposeLocalExtensibility:l}),await(t.lifecycle?.onWorkspaceReload?.(r)))}))},async dispose(){s||(s=!0,await a((async()=>{try{await SB(o,{disposeLocalExtensibility:l})}finally{await(t.lifecycle?.dispose())}})))}}}class AB{async requestApproval(e){return{approved:!0}}}class $B{constructor(e,t,r,n){this.approvalMode=e,this.userConfiguredPolicy=t,this.teamSettingsService=r,this.respectAdminControls=n}async getPermissions(){const e=!(!this.respectAdminControls||"insecure_none"===this.userConfiguredPolicy.type)&&(await this.teamSettingsService.getSandboxingControls()).sandboxingDisabled;return{allow:[],deny:[],approvalMode:this.approvalMode,userConfiguredPolicy:e?{type:"insecure_none"}:this.userConfiguredPolicy}}async updatePermissions(){}}class MB{async open(e,t){}async getDiagnostics(e,t){return[]}}class DB{async getCodebaseReference(e,t){}}class OB{constructor(e,t){this.inner=e,this.allowlistReports=t}async getState(e){const t=await this.inner.getState(e);return await this.reportAllowlists(e),{...t,servers:t.servers.filter((e=>"needsAuth"!==e.status))}}async reportAllowlists(e){if(void 0===this.allowlistReports)return;const{mcpLease:t,onMcpAllowlistInUse:r,onMcpServerBlockedByAllowlist:n}=this.allowlistReports;let o;try{o=await t.getClients(e)}catch(e){return void CO.Jz.warn("[sdk-mcp-state] Could not read the MCP allowlist in use:",e)}for(const[e,t]of Object.entries(o))try{if(void 0!==r){const n=await(t.getAllowlistInUse?.());void 0!==n&&r({serverName:e,allowlist:n})}if(void 0!==n){const r=await(t.getAllowlistRefusal?.());void 0!==r&&n({serverName:e,refusal:r})}}catch(e){CO.Jz.warn("[sdk-mcp-state] Could not read the MCP allowlist in use:",e)}}}class FB{constructor(e){this.subagents=e.map((e=>new Sg.zz({fullPath:`sdk-inline://${e.name}`,name:e.name,description:e.description,tools:[],model:e.model,prompt:e.prompt,permissionMode:Sg.b$.DEFAULT,isBackground:!1,source:"sdk"})))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents}}class NB{constructor(e={}){this.options=e,this.states=new Map,this.runCounterBySession=new Map,this.dispatchQueueBySession=new Map,this.dispatchInProgress=new Set,this.releaseRequestedBySession=new Set}getState(e){return this.states.get(e)??{status:"idle"}}isBusy(e){return"idle"!==this.getState(e).status}startRun(e,t){const r=this.nextRunId(e);return this.enqueueEvent(e,{type:"startRun",runId:r,abort:t?.abort}),r}queueResume(e,t){this.enqueueEvent(e,{type:"queueResume",queuedResume:t.queuedResume,targetRunId:t.targetRunId,mergeQueuedResume:t.mergeQueuedResume})}finishRun(e,t){this.enqueueEvent(e,{type:"runFinished",runId:t})}clearQueuedResume(e){this.enqueueEvent(e,{type:"clearQueuedResume"})}abort(e){this.enqueueEvent(e,{type:"abort"})}release(e){this.enqueueEvent(e,{type:"release"})}nextRunId(e){const t=(this.runCounterBySession.get(e)??0)+1;return this.runCounterBySession.set(e,t),t}enqueueEvent(e,t){const r=this.dispatchQueueBySession.get(e)??[];r.push(t),this.dispatchQueueBySession.set(e,r),this.drainEventQueue(e)}drainEventQueue(e){if(this.dispatchInProgress.has(e))return;let t;this.dispatchInProgress.add(e);try{const r=this.dispatchQueueBySession.get(e);if(!r)return;for(;r.length>0;){const n=r.shift();if(n)try{this.processEvent(e,n)}catch(e){t??=e}}}finally{this.dispatchQueueBySession.delete(e),this.dispatchInProgress.delete(e)}if(t)throw t}processEvent(e,t){const r=this.getState(e),{nextState:n,effects:o}=function(e,t){switch(e.status){case"idle":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"running",runId:t.runId,abort:t.abort},effects:[]};case"queueResume":return void 0===t.targetRunId?{nextState:e,effects:[]}:{nextState:{status:"runningWithQueuedResume",runId:t.targetRunId,queuedResume:t.queuedResume},effects:[]};case"runFinished":case"clearQueuedResume":case"abort":case"release":return{nextState:e,effects:[]};default:throw new Error(`Unhandled idle-state event: ${String(t)}`)}}(e,t);case"running":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"running",runId:t.runId,abort:t.abort},effects:[{type:"abortActiveRun",abort:e.abort}]};case"queueResume":return{nextState:{status:"runningWithQueuedResume",runId:e.runId,abort:e.abort,queuedResume:t.queuedResume},effects:[]};case"runFinished":return t.runId!==e.runId?{nextState:e,effects:[]}:{nextState:{status:"idle"},effects:[]};case"clearQueuedResume":case"release":return{nextState:e,effects:[]};case"abort":return{nextState:{status:"idle"},effects:[{type:"abortActiveRun",abort:e.abort}]};default:throw new Error(`Unhandled running-state event: ${String(t)}`)}}(e,t);case"runningWithQueuedResume":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"runningWithQueuedResume",runId:t.runId,abort:t.abort,queuedResume:e.queuedResume},effects:[{type:"abortActiveRun",abort:e.abort}]};case"queueResume":return{nextState:{...e,queuedResume:t.mergeQueuedResume(e.queuedResume,t.queuedResume)},effects:[]};case"runFinished":return t.runId!==e.runId?{nextState:e,effects:[]}:{nextState:{status:"running",runId:e.runId,abort:e.abort},effects:[{type:"startQueuedRun",sourceRunId:e.runId,queuedResume:e.queuedResume}]};case"clearQueuedResume":return{nextState:{status:"running",runId:e.runId,abort:e.abort},effects:[]};case"abort":return{nextState:{status:"idle"},effects:[{type:"abortActiveRun",abort:e.abort}]};case"release":return{nextState:e,effects:[]};default:throw new Error(`Unhandled runningWithQueuedResume-state event: ${String(t)}`)}}(e,t);default:return{nextState:e,effects:[]}}}(r,t);this.states.set(e,n),this.options.onStateChange?.({sessionId:e,previousState:r,nextState:n});for(const t of o)switch(t.type){case"abortActiveRun":t.abort?.();break;case"startQueuedRun":this.options.onQueuedRunReady?.({sessionId:e,sourceRunId:t.sourceRunId,queuedResume:t.queuedResume});break;default:throw new Error(`Unhandled lifecycle manager effect: ${String(t)}`)}const s=this.getState(e);"release"===t.type&&"idle"!==s.status&&this.releaseRequestedBySession.add(e),"idle"!==s.status||"release"!==t.type&&!this.releaseRequestedBySession.has(e)||(this.states.delete(e),this.runCounterBySession.delete(e),this.releaseRequestedBySession.delete(e))}}function LB(e){return"string"==typeof e&&e.trim().length>0}function jB(e,t){return new fe.jn({command:t.command??"",workingDirectory:t.workingDirectory??"",error:e,isReadonly:!0})}function UB(e){return{execute:async(t,r)=>new FI.v3({result:{case:"permissionDenied",value:new FI.U7({path:r.path,error:e,isReadonly:!0})}})}}function BB(e){return{execute:async(t,r)=>new Ww.Pi({result:{case:"permissionDenied",value:new Ww.QG({path:r.path,clientVisibleError:e,isReadonly:!0})}})}}function WB(e){return{execute:async(t,r)=>new Mc.iz({result:{case:"permissionDenied",value:new Mc.HQ({error:`${e} Tool: ${r.name}`,isReadonly:!0})}})}}var HB=r("../agent-kv/dist/subagent-states.js");let qB;function zB(e){const t=process.env.CURSOR_DATA_DIR;if(t?.trim())return Eo(e);let r;try{r=(0,o.homedir)()}catch{r=void 0}return function(e){const t=e.cursorDataDir?.trim();return t?(0,s.join)(t,"projects",(0,_o.r_)(e.workspacePath)):void 0!==e.homeDir&&function(e){if(""===e.trim())return!1;try{return!!(0,Ro.statSync)(e).isDirectory()&&((0,Ro.accessSync)(e,Ro.constants.W_OK),!0)}catch{return!1}}(e.homeDir)?(0,s.join)(e.homeDir,".cursor","projects",(0,_o.r_)(e.workspacePath)):(0,s.join)(e.ensureFallbackRoot(e.tempDir),(0,_o.r_)(e.workspacePath))}({workspacePath:e,homeDir:r,tempDir:(0,o.tmpdir)(),ensureFallbackRoot:e=>(void 0===qB&&(qB=function(e){return(0,Ro.mkdtempSync)((0,s.join)(e,"cursor-transcripts-"))}(e)),qB)})}async function GB(e,t){const r=(0,s.dirname)(e);await(0,xo.mkdir)(r,{recursive:!0}),await(0,xo.writeFile)(e,t,"utf-8")}class VB{constructor(e){this.writeChain=Promise.resolve(),this.workspacePath=e.workspacePath,this.conversationId=e.conversationId,this.parentConversationId=e.parentConversationId,this.blobStore=e.blobStore,this.projectDir=zB(this.workspacePath);const t=this.parentConversationId?(e,t)=>{const r=NF({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,r)}:void 0;this.transcriptStore=new pN(this.projectDir,e.blobStore,GB,{writeText:!1,writeJsonl:!0,...t?{pathResolver:t}:{}}),this.nestedSubagentTranscriptStore=new pN(this.projectDir,e.blobStore,GB,{writeText:!1,writeJsonl:!0,pathResolver:(e,t)=>{const r=NF({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.conversationId});return(0,s.join)(this.projectDir,r)}})}enqueueWrite(e,t){const r=this.writeChain;return this.writeChain=r.then((async()=>{try{await e()}catch(e){CO.Jz.warn(`${t} ${e instanceof Error?e.message:String(e)}`)}})),this.writeChain}async writeFromState(e,t){return this.enqueueWrite((async()=>{await this.transcriptStore.writeFromStateFull(e,t,this.conversationId);const r=await(0,HB.Vn)(e,t,this.blobStore);for(const[t,n]of Object.entries(r))n?.conversationState&&await this.nestedSubagentTranscriptStore.writeFromStateFull(e,n.conversationState,t)}),"[LocalTranscriptWriter] Failed to write transcript:")}async writeTurnEndedFromState(e,t,r){return this.enqueueWrite((async()=>{await this.transcriptStore.writeFromStateFull(e,t,this.conversationId,{turnEnded:r})}),"[LocalTranscriptWriter] Failed to write turn-ended transcript:")}waitForPendingWrites(){return this.writeChain}getTranscriptPath(){if(this.parentConversationId){const e=NF({conversationId:this.conversationId,ext:"jsonl",kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,e)}return function(e,t){const r=NF({conversationId:t,ext:"jsonl",kind:"primary"});return(0,s.join)(zB(e),r)}(this.workspacePath,this.conversationId)}getProjectDir(){return this.projectDir}}const KB=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,JB="User aborted/interrupted manually.";class ZB{constructor(e){this.sessions=new Map,this.backgroundRuns=new Map,this.activeForegroundExecutions=new Map,this.backgroundPromises=new Set,this.pendingReleaseSessions=new Set,this.childParentIds=new Map,this.parentChildIds=new Map,this.queuedChildCompletions=new Map,this.childCompletionWaiters=new Map,this.childLineageRequestIds=new Map,this.untrackedParentRequestIds=new Map,this.agentClient=e.agentClient,this.getResources=e.getResources,this.mcpTools=e.mcpTools??[],this.workspacePath=e.workspacePath,this.parentConversationId=e.parentConversationId;const t=e.rootRequestId?.trim();this.rootLineageRequestId=void 0!==t&&t.length>0?t:(0,ye.C)(),this.headers=e.headers,this.endlessRetries=e.endlessRetries,this.onSessionCreated=e.onSessionCreated,this.onInteractionUpdate=e.onInteractionUpdate,this.onSessionCompleted=e.onSessionCompleted,this.onSessionReleased=e.onSessionReleased,this.onSubagentTokenDelta=e.onSubagentTokenDelta,this.lifecycleStore=new NB}async createOrResumeSession(e,t){if(t.forkAgentId)throw new Error("forkAgentId is not supported in local subagents.");const r=t.resumeAgentId;if(r&&function(e){if(!KB.test(e))throw new Error(`Invalid resumeAgentId format: ${e}`)}(r),r&&!t.prompt)return r;if(r&&LB(t.prompt)&&this.isBackgroundRunBusy(r))throw new Error("Sub-agent is currently running. You may send the follow-up message when it has completed.");if(r&&this.sessions.get(r))return r;const n=r??(0,ye.C)(),o=function(e){const t=new oe.We,r=(0,EO.sh)(e),n=new EO.pH(new oe.ve,t);return n.setMetadata("agentId",r.agentId),n.setMetadata("latestRootBlobId",r.latestRootBlobId),n.setMetadata("name",r.name),n.setMetadata("createdAt",r.createdAt),n.setMetadata("mode",r.mode),n.setMetadata("isRunEverything",r.isRunEverything),n.setMetadata("lastUsedModel",r.lastUsedModel),n.setMetadata("lastDebugServerPort",r.lastDebugServerPort),n.setMetadata("currentPlanUri",r.currentPlanUri),n.setMetadata("subagentInfo",r.subagentInfo),n.setMetadata("blobEncryptionKey",r.blobEncryptionKey),n}(n),s=new VB({workspacePath:this.workspacePath,conversationId:n,parentConversationId:this.parentConversationId,blobStore:o.getBlobStore()});return this.sessions.set(n,{agentStore:o,transcriptWriter:s,toolCallId:t.toolCallId}),this.onSessionCreated?.({agentId:n,toolCallId:t.toolCallId,subagentType:t.subagentType,parentAgentId:t.parentConversationId}),n}async runSession(e,t,r,n){if(this.isAwaitBackgroundMode(r))return this.awaitBackgroundRun(r.resumeAgentId,e.signal);const o=this.sessions.get(t);if(!o)return{status:"error",error:`Subagent session not found: ${t}`};if(r.runInBackground){const[n,s]=e.withDetached().withCancel();return this.registerBackgroundRun(t,this.executeSubagent(n,t,r,o),r.parentConversationId,s),{status:"background",backgroundReason:Sg.qL.AGENT_REQUEST,toolCallCount:0}}const[s,i]=e.withDetached().withCancel();let a=!1;const c=()=>{a||i()};e.signal.addEventListener("abort",c,{once:!0}),e.signal.aborted&&c();let l=()=>{};const u=new Promise((e=>{l=e})),d={requestBackground:()=>!!a||!s.signal.aborted&&(a=!0,e.signal.removeEventListener("abort",c),l(),!0)};this.activeForegroundExecutions.set(r.toolCallId,d),this.activeForegroundExecutions.set(t,d);try{const e=this.executeSubagent(s,t,r,o),n=await Promise.race([e.then((e=>({handedOff:!1,outcome:e}))),u.then((()=>({handedOff:!0})))]);return n.handedOff?(this.registerBackgroundRun(t,e,r.parentConversationId,i),{status:"background",backgroundReason:Sg.qL.USER_REQUEST,toolCallCount:0}):(this.onSessionCompleted?.(t,n.outcome),n.outcome)}finally{this.clearForegroundExecution(r.toolCallId,d),this.clearForegroundExecution(t,d),a||e.signal.removeEventListener("abort",c)}}forceBackgroundByToolCallId(e){const t=this.activeForegroundExecutions.get(e);return t?.requestBackground()?new io.a3({status:io.jh.ACCEPTED}):new io.a3({status:io.jh.NOT_FOUND})}clearForegroundExecution(e,t){this.activeForegroundExecutions.get(e)===t&&this.activeForegroundExecutions.delete(e)}releaseSession(e){this.lifecycleStore.release(e),this.isBackgroundRunBusy(e)?this.pendingReleaseSessions.add(e):this.cleanupSession(e)}async awaitBackgroundWorkers(){for(;this.backgroundPromises.size>0;)await Promise.allSettled([...this.backgroundPromises])}async waitForBackgroundCompletions(e,t){return this.collectAvailableChildCompletions(e,t)}isBackgroundRunBusy(e){return this.lifecycleStore.isBusy(e)||this.backgroundRuns.has(e)}registerBackgroundRun(e,t,r,n){this.registerParentChildLink(e,r);const o=this.lifecycleStore.startRun(e,{abort:n}),s=t.catch((e=>({status:"error",error:e instanceof Error?e.message:String(e)}))),i={runId:o,promise:s};this.backgroundRuns.set(e,i),this.backgroundPromises.add(s),s.then((t=>{this.lifecycleStore.finishRun(e,o);const r=this.backgroundRuns.get(e);if(r?.runId===o){this.backgroundRuns.delete(e),this.enqueueChildCompletion(e,o,t),this.maybeCleanupReleasedSession(e);try{this.onSessionCompleted?.(e,t)}catch(t){CO.Jz.error("[LocalSubagentHostAdapter] onSessionCompleted threw after background run",{agentId:e,error:t instanceof Error?t.message:String(t)})}}return t})).finally((()=>this.backgroundPromises.delete(s)))}maybeCleanupReleasedSession(e){this.pendingReleaseSessions.has(e)&&!this.isBackgroundRunBusy(e)&&this.cleanupSession(e)}cleanupSession(e){this.pendingReleaseSessions.delete(e);const t=this.sessions.get(e);if(!t)return;const r=this.parentChildIds.get(e);if(r)for(const e of r)this.childParentIds.delete(e);this.removeParentChildLink(e),this.parentChildIds.delete(e),this.queuedChildCompletions.delete(e),this.childCompletionWaiters.delete(e),t.transcriptWriter.waitForPendingWrites().catch((()=>{})),this.sessions.delete(e),this.onSessionReleased?.(e)}async executeSubagent(e,t,r,n){return r.continuationConfig?this.executeSubagentWithContinuation(e,t,r,n,r.continuationConfig):this.executeSubagentOnce(e,t,r,n)}async executeSubagentWithContinuation(e,t,r,n,o){const s=o.maxLoops>0?o.maxLoops:Number.POSITIVE_INFINITY;let i=await this.runContinuationLoop(e,t,r,n,o,s);if(!o.collectBackgroundChildren||"completed"!==i.status)return i;for(let a=0;a<500;a++){if(e.signal.aborted)return{status:"error",error:"Subagent was aborted by the user"};let a;try{a=await this.collectAvailableChildCompletions(t,e.signal)}catch{return{status:"error",error:"Subagent was aborted by the user"}}if(0===a.length)return i;const c=this.buildChildrenCompletedMessage(a,o.childrenCompletedMessageTemplate);if(i=await this.runContinuationLoop(e,t,new io.Pw({...r,prompt:c,resumeAgentId:t,runInBackground:!1}),n,o,s),"completed"!==i.status)return i}return i}async runContinuationLoop(e,t,r,n,o,s){let i,a,c=0;for(let l=0;l0?(c=0,i=void 0):(c+=1,i=c>=o.idleThreshold?`DONE_${(0,ye.C)().replace(/-/g,"").slice(0,8)}`:void 0)}return a??{status:"error",error:"Subagent continuation exited unexpectedly"}}computeContinuationNudge(e,t,r){return t>=e.idleThreshold&&void 0!==r?e.escapeMessageTemplate.replace("{idle_count}",String(t)).replace("{escape_token}",r):e.nudgeMessage}lineageForChildRun(e){this.childLineageRequestIds.has(e.agentId)||this.childLineageRequestIds.set(e.agentId,(0,ye.C)());const t=e.parentConversationId?.trim()??"",r=e.toolCallId.trim();return{parentRequestId:""===t||t===this.parentConversationId?this.rootLineageRequestId:this.childLineageRequestIds.get(t)??this.untrackedParentRequestId(t),rootParentRequestId:this.rootLineageRequestId,...r.length>0?{parentAgentToolCallId:r}:{}}}untrackedParentRequestId(e){let t=this.untrackedParentRequestIds.get(e);return void 0===t&&(t=(0,ye.C)(),this.untrackedParentRequestIds.set(e,t)),t}async executeSubagentOnce(e,t,r,n){const o=this.lineageForChildRun({agentId:t,parentConversationId:r.parentConversationId,toolCallId:r.toolCallId});let s,i=0;const a=new c.QFf({action:{case:"userMessageAction",value:new c.Vtf({userMessage:new c.RGk({text:r.prompt})})}}),l=new c.Gmx({modelId:r.modelId,displayModelId:r.modelId,displayName:r.modelId});void 0!==r.credentials.case&&(l.credentials=r.credentials);const u=new _O,d={sendUpdate:async(e,r)=>{"tokenDelta"===r.message.case&&this.onSubagentTokenDelta?.(t,r.message.value.tokens),"toolCallStarted"!==r.message.case&&"toolCallCompleted"!==r.message.case&&"partialToolCall"!==r.message.case||this.onInteractionUpdate?.(t,r),"toolCallCompleted"===r.message.case&&i++,"textDelta"===r.message.case&&(s=(s??"")+r.message.value.text)},query:async(e,t)=>function(e){const t=e.query.case;switch(t){case"webSearchRequestQuery":return pr(e.id,"Web search is not supported in local subagent");case"webFetchRequestQuery":return mr(e.id,"Web fetch is not supported in local subagent");case"switchModeRequestQuery":return yr(e.id,"Subagent mode switches are not supported in local subagent");case"askQuestionInteractionQuery":{const t=new er.tz({result:{case:"rejected",value:new er.ox({reason:"Interactive questions are not supported in local subagent mode"})}});return gr(e.id,t)}default:throw new Error(`Unhandled interaction query type in local subagent: ${String(t)}`)}}(t)},h={handleCheckpoint:async(e,t)=>{await n.agentStore.handleCheckpoint(e,t),n.transcriptWriter.writeFromState(e,t)},getLatestCheckpoint:()=>n.agentStore.getLatestCheckpoint()};try{const c=r.rootParentConversationId?.trim(),p=r.parentConversationId?.trim(),f=void 0!==c&&""!==c?c:void 0!==p&&""!==p?p:t,m=await this.getResources({agentId:t,parentAgentId:r.parentConversationId}),g=r.readonly?new X(m,function(e){const t=[K(GT,UB(e.errorMessage)),K(VT,BB(e.errorMessage)),K(ro,WB(e.errorMessage))];return e.wrapShell&&t.push(K(WT,function(e){return{execute:async(t,r)=>new fe.W4({result:{case:"permissionDenied",value:jB(e,r)}})}}(e.errorMessage)),K(re,function(e){return{async*execute(t,r){yield new fe.FI({event:{case:"permissionDenied",value:jB(e,r)}})}}}(e.errorMessage)),K(kA,function(e){return{execute:async(t,r)=>new Fo.Lt({result:{case:"permissionDenied",value:jB(e,r)}})}}(e.errorMessage))),e.includeWriteBackgroundShellStdin&&t.push(K(_A,function(e){return{execute:async(t,r)=>new Fo.nt({result:{case:"error",value:new Fo.Gv({error:e})}})}}(e.errorMessage))),t}({errorMessage:"This operation is not allowed in readonly mode. The subagent was launched with readonly: true, which restricts shell, write, delete, and MCP operations.",wrapShell:!0,includeWriteBackgroundShellStdin:!0})):m;return await this.agentClient.run(e,n.agentStore.getConversationStateStructure(),a,l,d,g,n.agentStore.getBlobStore(),u,h,[...this.mcpTools],{conversationGroupId:f,conversationId:t,...n.transcriptWriter.parentConversationId?{transcriptParentConversationId:n.transcriptWriter.parentConversationId}:{},subagentTypeName:r.subagentType||void 0,...o,headers:PO(n.agentStore.getMetadata("blobEncryptionKey"),this.headers),endlessRetries:this.endlessRetries,subagentModelOverrides:[]}),await n.transcriptWriter.writeTurnEndedFromState(e,n.agentStore.getConversationStateStructure(),e.signal.aborted?{status:"aborted",error:JB}:{status:"success"}),{status:"completed",finalMessage:s,toolCallCount:i}}catch(r){const o=r instanceof Error?r.message:String(r);return CO.Jz.error("[LocalSubagentHostAdapter] Subagent session failed",{agentId:t,error:o}),await n.transcriptWriter.writeTurnEndedFromState(e,n.agentStore.getLatestCheckpoint()??n.agentStore.getConversationStateStructure(),this.getTurnEndedFromError(e,o)),e.signal.aborted?{status:"aborted",error:JB}:{status:"error",error:o}}}getTurnEndedFromError(e,t){return e.signal.aborted?{status:"aborted",error:JB}:{status:"error",error:t}}isAwaitBackgroundMode(e){if(!Boolean(e.resumeAgentId&&!LB(e.prompt)&&e.readonly&&!0!==e.runInBackground))return!1;if(0===(e.parentConversationId??"").trim().length)throw new Error(`Missing parentConversationId for subagent await/status check (subagentId: ${e.resumeAgentId})`);return!0}async awaitBackgroundRun(e,t){const r=this.backgroundRuns.get(e);return r?this.awaitBackgroundEntry(r,t):this.isBackgroundRunBusy(e)?this.awaitBusyLifecycleRun(e,t):{status:"error",error:`No background subagent found for id: ${e}`}}async awaitBackgroundRunBounded(e,t){const r=t.agentId;if(e.signal.aborted)return new io.zJ({result:{case:"stillRunning",value:new io.L5({agentId:r})}});const n=this.backgroundRuns.get(r);if(void 0===n){const e=this.takeQueuedChildCompletion(r);return void 0!==e?"success"===e.status?new io.zJ({result:{case:"complete",value:new io.bE({agentId:r,finalMessage:e.finalMessage,toolCallCount:e.toolCallCount??0})}}):new io.zJ({result:{case:"error",value:new io.Y({agentId:r,error:e.finalMessage||"Subagent was aborted"})}}):this.isBackgroundRunBusy(r)?new io.zJ({result:{case:"stillRunning",value:new io.L5({agentId:r})}}):new io.zJ({result:{case:"notFound",value:new io.Hq({agentId:r})}})}const[o,s]=e.withTimeoutAndCancel(Math.max(0,t.timeoutMs)),i=await new Promise((e=>{const t=()=>e(void 0);o.signal.addEventListener("abort",t,{once:!0}),n.promise.then(e).finally((()=>{o.signal.removeEventListener("abort",t),s()}))}));return void 0===i||"background"===i.status||e.signal.aborted?new io.zJ({result:{case:"stillRunning",value:new io.L5({agentId:r})}}):(this.takeQueuedChildCompletion(r,n.runId),"completed"===i.status?new io.zJ({result:{case:"complete",value:new io.bE({agentId:r,finalMessage:i.finalMessage,toolCallCount:i.toolCallCount??0})}}):new io.zJ({result:{case:"error",value:new io.Y({agentId:r,error:i.error??"Subagent was aborted"})}}))}takeQueuedChildCompletion(e,t){for(const[r,n]of this.queuedChildCompletions){const o=n.findIndex((r=>r.agentId===e&&(void 0===t||r.runId===t)));if(-1===o)continue;const[s]=n.splice(o,1);return 0===n.length&&this.queuedChildCompletions.delete(r),s}}async awaitBusyLifecycleRun(e,t){for(;this.isBackgroundRunBusy(e);){if(t.aborted)return{status:"error",error:"Await timed out while task is still running"};const r=this.backgroundRuns.get(e);if(r)return this.awaitBackgroundEntry(r,t);await new Promise((e=>setTimeout(e,50)))}return{status:"completed",toolCallCount:0}}async awaitBackgroundEntry(e,t){if(t.aborted)return{status:"error",error:"Await timed out while task is still running"};const r={status:"error",error:"Await timed out while task is still running"};return new Promise((n=>{const o=()=>{n(r)};t.addEventListener("abort",o,{once:!0}),e.promise.then(n).finally((()=>t.removeEventListener("abort",o)))}))}registerParentChildLink(e,t){const r=t?.trim();if(!r||r===e||!this.sessions.has(r)&&r!==this.parentConversationId)return;const n=this.childParentIds.get(e);if(n===r)return;n&&(this.parentChildIds.get(n)?.delete(e),0===(this.parentChildIds.get(n)?.size??0)&&this.parentChildIds.delete(n)),this.childParentIds.set(e,r);const o=this.parentChildIds.get(r)??new Set;o.add(e),this.parentChildIds.set(r,o)}removeParentChildLink(e){const t=this.childParentIds.get(e);if(!t)return;this.childParentIds.delete(e);const r=this.parentChildIds.get(t);r?.delete(e),0===(r?.size??0)&&this.parentChildIds.delete(t)}enqueueChildCompletion(e,t,r){const n=this.childParentIds.get(e);if(!n)return;const o=this.queuedChildCompletions.get(n)??[];o.push({agentId:e,runId:t,status:"completed"===r.status?"success":"error"===r.status?"error":"aborted",finalMessage:"completed"===r.status?r.finalMessage??"":"error"===r.status?r.error:"Subagent was aborted by the user",..."completed"===r.status&&void 0!==r.toolCallCount?{toolCallCount:r.toolCallCount}:{}}),this.queuedChildCompletions.set(n,o),this.removeParentChildLink(e);const s=this.childCompletionWaiters.get(n);if(s){this.childCompletionWaiters.delete(n);for(const e of s)e()}}async collectAvailableChildCompletions(e,t){const r=this.drainChildCompletions(e);return r.length>0?r:this.hasPendingChildSubagents(e)?(await this.waitForChildCompletion(e,t),this.drainChildCompletions(e)):[]}hasPendingChildSubagents(e){return(this.parentChildIds.get(e)?.size??0)>0}drainChildCompletions(e){const t=this.queuedChildCompletions.get(e)??[];return this.queuedChildCompletions.delete(e),t}async waitForChildCompletion(e,t){if(t.aborted)throw new Error("aborted");await new Promise(((r,n)=>{const o=this.childCompletionWaiters.get(e)??new Set,s=()=>{a(),r()},i=()=>{a(),n(new Error("aborted"))},a=()=>{o.delete(s),0===o.size&&this.childCompletionWaiters.delete(e),t.removeEventListener("abort",i)};o.add(s),this.childCompletionWaiters.set(e,o),t.addEventListener("abort",i,{once:!0})}))}buildChildrenCompletedMessage(e,t){const r=e.map((e=>{const t="success"===e.status?"SUCCESS":"FAILED";return`## Agent ${e.agentId} -- ${t}\n\n${e.finalMessage}`})).join("\n\n---\n\n");return t.replace("{summaries}",r)}}var XB=r("../proto/dist/generated/agent/v1/agent_service_connect.js"),QB=r("../proto/dist/generated/agent/v1/requested_model_pb.js"),YB=r("../proto/dist/generated/agent/v1/selected_context_pb.js"),eW=r("./src/agent/analytics.ts"),tW=r("../proto/dist/generated/agent/v1/todo_tool_pb.js");const rW={[Ng.w3.UNSPECIFIED]:"unspecified",[Ng.w3.LEFT]:"left",[Ng.w3.RIGHT]:"right",[Ng.w3.MIDDLE]:"middle",[Ng.w3.BACK]:"back",[Ng.w3.FORWARD]:"forward"},nW={[Ng.Dh.UNSPECIFIED]:"unspecified",[Ng.Dh.UP]:"up",[Ng.Dh.DOWN]:"down",[Ng.Dh.LEFT]:"left",[Ng.Dh.RIGHT]:"right"},oW={[Ng.EB.UNSPECIFIED]:"unspecified",[Ng.EB.TAP]:"tap",[Ng.EB.DOWN]:"down",[Ng.EB.UP]:"up"};function sW(e){return rW[e]??"unspecified"}function iW(e){return void 0===e?void 0:{x:e.x,y:e.y}}function aW({result:e}){switch(e.case){case"success":return{status:"success",value:{actionCount:e.value.actionCount,durationMs:e.value.durationMs,settleMs:e.value.settleMs,screenshotPath:e.value.screenshotPath,cursorPosition:iW(e.value.cursorPosition),log:e.value.log}};case"error":return{status:"error",error:{message:e.value.error,actionCount:e.value.actionCount,durationMs:e.value.durationMs,screenshotPath:e.value.screenshotPath,log:e.value.log}};default:return}}function cW(e,t){switch(e.message.case){case"textDelta":return{type:"text-delta",text:e.message.value.text};case"thinkingDelta":return{type:"thinking-delta",text:e.message.value.text};case"thinkingCompleted":return{type:"thinking-completed",thinkingDurationMs:e.message.value.thinkingDurationMs};case"userMessageAppended":return{type:"user-message-appended",userMessage:{type:"user_message",session_id:t,text:e.message.value.userMessage?.text??""}};case"tokenDelta":return{type:"token-delta",tokens:e.message.value.tokens};case"summary":return{type:"summary",summary:e.message.value.summary};case"summaryStarted":return{type:"summary-started"};case"summaryCompleted":{const{failed:t,fallback:r}=e.message.value;return{type:"summary-completed",...t?{failed:t}:{},...r?{fallback:r}:{}}}case"shellOutputDelta":return{type:"shell-output-delta",event:e.message.value.event.case?{case:e.message.value.event.case,value:e.message.value.event.value?.toJson?.()??e.message.value.event.value}:{}};case"toolCallStarted":return lW("tool-call-started",e.message.value);case"partialToolCall":return lW("partial-tool-call",e.message.value);case"toolCallCompleted":return lW("tool-call-completed",e.message.value);case"heartbeat":return null;case"turnEnded":{const t=e.message.value;return{type:"turn-ended",...(void 0!==t.inputTokens||void 0!==t.outputTokens||void 0!==t.cacheReadTokens||void 0!==t.cacheWriteTokens)&&{usage:{inputTokens:Number(t.inputTokens??BigInt(0)),outputTokens:Number(t.outputTokens??BigInt(0)),cacheReadTokens:Number(t.cacheReadTokens??BigInt(0)),cacheWriteTokens:Number(t.cacheWriteTokens??BigInt(0)),...t.reasoningTokens&&{reasoningTokens:Number(t.reasoningTokens)}}}}}case"modelCallCompleted":{const t=e.message.value;return{type:"model-call-completed",modelCallId:t.modelCallId,usage:{inputTokens:Number(t.inputTokens),outputTokens:Number(t.outputTokens),cacheReadTokens:Number(t.cacheReadTokens),cacheWriteTokens:Number(t.cacheWriteTokens),...t.reasoningTokens&&{reasoningTokens:Number(t.reasoningTokens)}}}}case"toolCallDelta":{const r=e.message.value,n=r.toolCallDelta;if("taskToolCallDelta"!==n?.delta.case)return null;const o=n.delta.value.interactionUpdate;if(void 0===o)return null;const s=cW(o,t);return null!==s&&function(e){switch(e.type){case"text-delta":case"thinking-delta":case"thinking-completed":case"tool-call-started":case"tool-call-completed":case"partial-tool-call":case"step-started":case"step-completed":case"tool-requests-listed":return!0;default:return!1}}(s)?{type:"tool-call-delta",callId:r.callId,modelCallId:r.modelCallId,taskUpdate:s}:null}case"stepStarted":return{type:"step-started",stepId:Number(e.message.value.stepId)};case"toolRequestsListed":return{type:"tool-requests-listed",callCount:e.message.value.callCount};case"stepCompleted":return{type:"step-completed",stepId:Number(e.message.value.stepId),stepDurationMs:Number(e.message.value.stepDurationMs)};case"postRequestPrompt":case"activeBranchChange":case"feedbackRequest":case"responseComparison":case"contextInjectionState":case"routedModel":case"grokBotNudge":case"thinkingNote":case"voiceCallUtterance":case void 0:return null;default:return e.message,null}}function lW(e,t){const r=function(e){if(!e?.tool)return null;switch(e.tool.case){case"shellToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"shell",args:{command:t.command,...t.workingDirectory?{workingDirectory:t.workingDirectory}:{},...t.timeout?{timeout:t.timeout}:{}},...r?{result:mW(r)}:{}}:null}case"deleteToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"delete",args:{path:t.path},...r?{result:gW(r)}:{}}:null}case"globToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"glob",args:{globPattern:t.globPattern,...t.targetDirectory?{targetDirectory:t.targetDirectory}:{}},...r?{result:wW(r)}:{}}:null}case"grepToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"grep",args:{pattern:t.pattern,...t.path?{path:t.path}:{},...t.glob?{glob:t.glob}:{},...t.outputMode?{outputMode:t.outputMode}:{},...t.contextBefore?{contextBefore:t.contextBefore}:{},...t.contextAfter?{contextAfter:t.contextAfter}:{},...t.context?{context:t.context}:{},...t.caseInsensitive?{caseInsensitive:t.caseInsensitive}:{},...t.type?{type:t.type}:{},...t.headLimit?{headLimit:t.headLimit}:{},...void 0!==t.offset?{offset:t.offset}:{},...t.multiline?{multiline:t.multiline}:{},...t.sort?{sort:t.sort}:{},...t.sortAscending?{sortAscending:t.sortAscending}:{}},...r?{result:yW(r)}:{}}:null}case"readToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"read",args:{path:t.path},...r?{result:bW(r)}:{}}:null}case"editToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"edit",args:{path:t.path},...r?{result:SW(r)}:{}}:null}case"lsToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"ls",args:{path:t.path,...t.ignore&&t.ignore.length>0?{ignore:t.ignore}:{}},...r?{result:kW(r)}:{}}:null}case"readLintsToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"readLints",args:{paths:t.paths},...r?{result:CW(r)}:{}}:null}case"mcpToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"mcp",args:{...t.providerIdentifier?{providerIdentifier:t.providerIdentifier}:{},...t.toolName?{toolName:t.toolName}:{},...t.args?{args:Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()])))}:{}},...r?{result:EW(r)}:{}}:null}case"generateImageToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"generateImage",args:{description:t.description,...t.filePath?{filePath:t.filePath}:{}},...r?{result:PW(r)}:{}}:null}case"recordScreenToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"recordScreen",args:{mode:RW(t.mode)},...r?{result:IW(r)}:{}}:null}case"semSearchToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"semSearch",args:{query:t.query,...t.targetDirectories&&t.targetDirectories.length>0?{targetDirectories:t.targetDirectories}:{},...t.explanation?{explanation:t.explanation}:{}},...r?{result:xW(r)}:{}}:null}case"createPlanToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"createPlan",args:{plan:t.plan},...r?{result:TW(r)}:{}}:null}case"updateTodosToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"updateTodos",args:{todos:t.todos.map((e=>({content:e.content,status:$W(e.status)})))},...r?{result:AW(r)}:{}}:null}case"fetchToolCall":case"switchModeToolCall":return null;case"computerUseToolCall":return function({args:e,result:t}){return e?{type:"computerUse",args:{actions:e.actions.flatMap((e=>function({action:e}){switch(e.case){case"mouseMove":return{type:"mouseMove",coordinate:iW(e.value.coordinate)};case"click":return{type:"click",coordinate:iW(e.value.coordinate),button:sW(e.value.button),count:e.value.count,modifierKeys:e.value.modifierKeys};case"mouseDown":case"mouseUp":return{type:e.case,button:sW(e.value.button)};case"drag":return{type:"drag",path:e.value.path.map((e=>({x:e.x,y:e.y}))),button:sW(e.value.button),modifierKeys:e.value.modifierKeys};case"scroll":return{type:"scroll",coordinate:iW(e.value.coordinate),direction:nW[e.value.direction]??"unspecified",amount:e.value.amount,modifierKeys:e.value.modifierKeys};case"type":return{type:"type",text:e.value.text};case"key":return{type:"key",key:e.value.key,holdDurationMs:e.value.holdDurationMs,stroke:oW[e.value.stroke]??"unspecified"};case"wait":return{type:"wait",durationMs:e.value.durationMs};case"screenshot":case"cursorPosition":return{type:e.case};default:return}}(e)??[])),description:e.description},result:t?aW(t):void 0}:null}(e.tool.value);case"readTodosToolCall":case"webSearchToolCall":case"listMcpResourcesToolCall":case"readMcpResourceToolCall":return null;case"taskToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"task",args:uW(t),...r?{result:pW(r)}:{}}:null}case"applyAgentDiffToolCall":case"askQuestionToolCall":case"writeShellStdinToolCall":case"reflectToolCall":case"setupVmEnvironmentToolCall":case"replaceEnvToolCall":case"startGrindExecutionToolCall":case"startGrindPlanningToolCall":case"truncatedToolCall":case"webFetchToolCall":case"reportBugfixResultsToolCall":case"aiAttributionToolCall":case"prManagementToolCall":case"editPrLabelsToolCall":case"fetchCloudAgentDataToolCall":case"mcpAuthToolCall":case"connectScmToolCall":case"searchConversationsToolCall":case"awaitToolCall":case"blameByFilePathToolCall":case"getMcpToolsToolCall":case"reportBugToolCall":case"setActiveBranchToolCall":case"communicateUpdateToolCall":case"sendFinalSummaryToolCall":case"updateOriginPrCodeTourToolCall":case"getOriginPrCodeTourToolCall":case"recordCiInvestigationFindingsToolCall":case"sendMessageToolCall":case"sendToUserToolCall":case"createGoalToolCall":case"updateGoalToolCall":case"getAgentStatusToolCall":case"sendToAgentToolCall":case"readAgentTranscriptToolCall":case"createAgentToolCall":case"createProjectToolCall":case"startProjectUpdatesToolCall":case"stopProjectUpdatesToolCall":case"manageAccessToolCall":case"stopAgentToolCall":case"listTrackedTasksToolCall":case"createTrackedTasksToolCall":case"updateTrackedTasksToolCall":case"deleteTrackedTasksToolCall":case"updateTrackedTaskStatusesToolCall":case"updateTrackedTaskTagsToolCall":case"writeCanvasToolCall":case"readCanvasToolCall":case"generateVideoToolCall":case"xSearchToolCall":case"executeToolCall":case void 0:return null;default:return e.tool}}(t.toolCall);return r?{type:e,callId:t.callId,toolCall:r,modelCallId:t.modelCallId}:null}function uW(e){return{description:e.description??"",prompt:e.prompt??"",...e.subagentType?{subagentType:dW(e.subagentType)}:{},...e.model?{model:e.model}:{},...e.resume?{resume:e.resume}:{},...e.agentId?{agentId:e.agentId}:{},...e.attachments&&e.attachments.length>0?{attachments:e.attachments}:{},...void 0!==e.mode?{mode:hW(e.mode)}:{},...e.respondingToMessageIds&&e.respondingToMessageIds.length>0?{respondingToMessageIds:e.respondingToMessageIds}:{}}}function dW(e){const t=e.type.case;return t?"custom"===t?{kind:t,name:e.type.value.name}:{kind:t}:{kind:"unspecified"}}function hW(e){switch(e){case Sg.FL.AGENT:return"agent";case Sg.FL.PLAN:return"plan";default:return"unspecified"}}function pW(e){if(e.result?.case)switch(e.result.case){case"success":{const t=e.result.value;return{status:"success",value:{...t.conversationSteps&&t.conversationSteps.length>0?{conversationSteps:t.conversationSteps.map((e=>e.toJson?.()??e))}:{},...t.agentId?{agentId:t.agentId}:{},isBackground:t.isBackground??!1,...void 0!==t.durationMs?{durationMs:Number(t.durationMs)}:{},...t.resultSuffix?{resultSuffix:t.resultSuffix}:{},backgroundReason:fW(t.backgroundReason),...t.transcriptPath?{transcriptPath:t.transcriptPath}:{}}}}case"error":return{status:"error",error:{message:e.result.value.error??"Task failed"}};default:return}}function fW(e){switch(e){case Sg.qL.AGENT_REQUEST:return"agentRequest";case Sg.qL.USER_REQUEST:return"userRequest";case Sg.qL.QUEUED_FOLLOW_UP:return"queuedFollowUp";default:return"unspecified"}}function mW(e){if(e.result?.case)switch(e.result.case){case"success":case"failure":{const t=e.result.value;return{status:"success",value:{exitCode:t.exitCode??0,signal:t.signal??"",stdout:t.stdout??"",stderr:t.stderr??"",executionTime:t.executionTime??0}}}case"timeout":return{status:"error",error:{message:`Command timed out after ${e.result.value.timeoutMs}ms`,command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};case"rejected":return{status:"error",error:{message:e.result.value.reason??"Command rejected",command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};case"spawnError":return{status:"error",error:{message:e.result.value.error??"Failed to spawn command",command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};default:return}}function gW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{fileSize:Number(e.result.value.fileSize??0)}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.value.clientVisibleError??e.result.case,path:e.result.value.path}}}function wW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{files:e.result.value.files??[],totalFiles:e.result.value.totalFiles??0,clientTruncated:e.result.value.clientTruncated??!1,ripgrepTruncated:e.result.value.ripgrepTruncated??!1}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case}}}function yW(e){if(e.result?.case){if("success"===e.result.case){const t=e.result.value,r={};if(t.workspaceResults)for(const[e,n]of Object.entries(t.workspaceResults))r[e]=vW(n);return{status:"success",value:{...Object.keys(r).length>0?{workspaceResults:r}:{},...t.activeEditorResult?{activeEditorResult:vW(t.activeEditorResult)}:{}}}}return{status:"error",error:{message:e.result.value.error??e.result.case}}}}function vW(e){if(e?.result?.case)switch(e.result.case){case"content":return{type:"content",output:{matches:e.result.value.matches?.map((e=>({file:e.file,...void 0!==e.lineNumber?{lineNumber:e.lineNumber}:{},line:e.line,...e.beforeContext?{beforeContext:e.beforeContext}:{},...e.afterContext?{afterContext:e.afterContext}:{}})))??[],totalMatches:e.result.value.totalMatches??0}};case"files":return{type:"files",output:{files:e.result.value.files??[],count:e.result.value.count??0}};case"count":return{type:"count",output:{counts:e.result.value.counts?.map((e=>({file:e.file,count:e.count})))??[],total:e.result.value.total??0}};default:return}}function bW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{content:"content"===e.result.value.output.case?e.result.value.output.value:"",totalLines:e.result.value.totalLines??0,fileSize:Number(e.result.value.fileSize??0)}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case,path:e.result.value.path}}}function SW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{...void 0!==e.result.value.linesAdded?{linesAdded:e.result.value.linesAdded}:{},...void 0!==e.result.value.linesRemoved?{linesRemoved:e.result.value.linesRemoved}:{},...e.result.value.diffString?{diffString:e.result.value.diffString}:{}}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case,path:e.result.value.path}}}function kW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{directoryTreeRoot:_W(e.result.value.directoryTreeRoot)}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function _W(e){if(e)return{absPath:e.absPath??"",childrenDirs:e.childrenDirs?.map(_W)??[],childrenFiles:e.childrenFiles?.map((e=>({name:e.name})))??[],childrenWereProcessed:e.childrenWereProcessed??!1,fullSubtreeExtensionCounts:e.fullSubtreeExtensionCounts??{},numFiles:e.numFiles??0}}function CW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{fileDiagnostics:e.result.value.fileDiagnostics?.map((e=>({path:e.path,diagnostics:e.diagnostics?.map((e=>({severity:MW(e.severity),...e.range?{range:{...e.range.start?{start:{line:e.range.start.line,character:e.range.start.character}}:{},...e.range.end?{end:{line:e.range.end.line,character:e.range.end.character}}:{}}}:{},message:e.message,source:e.source,code:e.code})))??[],diagnosticsCount:e.diagnosticsCount??0})))??[],totalFiles:e.result.value.totalFiles??0,totalDiagnostics:e.result.value.totalDiagnostics??0}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function EW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{content:e.result.value.content?.map((e=>{const t={};return"text"===e.content?.case?t.text={text:e.content.value.text}:"image"===e.content?.case&&(t.image={data:e.content.value.data,...e.content.value.mimeType?{mimeType:e.content.value.mimeType}:{}}),t}))??[],isError:e.result.value.isError??!1}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case}}}function xW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{results:e.result.value.results??""}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function PW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{filePath:e.result.value.filePath??""}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function RW(e){switch(e){case T$.$u.START_RECORDING:return"START_RECORDING";case T$.$u.SAVE_RECORDING:return"SAVE_RECORDING";case T$.$u.DISCARD_RECORDING:return"DISCARD_RECORDING";default:throw new Error(`Unknown RecordingMode: ${e}`)}}function IW(e){if(e.result?.case)switch(e.result.case){case"startSuccess":return{status:"success",value:{wasPriorRecordingCancelled:e.result.value.wasPriorRecordingCancelled??!1}};case"saveSuccess":return{status:"success",value:{path:e.result.value.path??"",recordingDurationMs:Number(e.result.value.recordingDurationMs??0)}};case"discardSuccess":return{status:"success",value:{}};case"failure":return{status:"error",error:{message:e.result.value.error??"Unknown error"}};default:return}}function TW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function AW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{todos:e.result.value.todos?.map((e=>({content:e.content,status:$W(e.status)})))??[],totalCount:e.result.value.totalCount??0}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function $W(e){switch(e){case tW.Vj.UNSPECIFIED:case tW.Vj.PENDING:return"pending";case tW.Vj.IN_PROGRESS:return"inProgress";case tW.Vj.COMPLETED:return"completed";case tW.Vj.CANCELLED:return"cancelled";default:return"pending"}}function MW(e){switch(e){case NA.h_.UNSPECIFIED:case NA.h_.ERROR:return"error";case NA.h_.WARNING:return"warning";case NA.h_.INFORMATION:return"information";case NA.h_.HINT:return"hint";default:return"error"}}const DW={type:"object",properties:{},additionalProperties:!0};function OW(e){const t={};for(const[r,n]of Object.entries(e))t[r]=n;return t}function FW(e){return"text"===e.type?new Mc._Z({content:{case:"text",value:new Mc.zN({text:e.text})}}):new Mc._Z({content:{case:"image",value:new Mc.do({data:n.Buffer.from(e.data,"base64"),mimeType:e.mimeType??""})}})}function NW(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var LW=r("./src/agent/errors.ts");const jW="Shell is not available when local.fs is set: the agent's files live in a FileSystem, and a shell would run on the host disk. Use Read, Grep, Glob, LS, and the edit tools instead.";function UW(e){return{async execute(){throw new Error(e)}}}function BW(e){var t;e.register(WT,UW(jW)),e.register(re,(t=jW,{async*execute(){throw new Error(t)}})),e.register(kA,UW(jW)),e.register(RA,UW(jW)),e.register(_A,UW(jW)),e.register(HT,UW(jW)),e.register(oA,UW("ReadLints is not available when local.fs is set: lint diagnostics come from a host language service, not the FileSystem.")),e.register(JT,UW("Git is not available when local.fs is set: the agent's files live in a FileSystem, not a host git checkout."))}var WW=r("./src/agent/filesystem/executors.ts"),HW=r("./src/agent/filesystem/compose.ts"),qW=r("./src/agent/filesystem/trees.ts"),zW=r("./src/agent/filesystem/walk.ts");const GW="/tmp",VW=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.txt$/i;function KW(e){const{write:t,hostProjectDir:r}=e;return{async execute(e,n,o){const s=function(e){if(t=e.writePath,!/^([/\\]|[A-Za-z]:[/\\])/.test(t))return;var t;const r=function(e){if(void 0===e.hostProjectDir||""===e.hostProjectDir)return;const t=(0,zW.eI)(e.hostProjectDir),r=(0,zW.eI)(e.writePath);return"/"!==t&&(0,zW.hJ)({path:r,prefix:t})?r.slice(t.length):void 0}(e),n=void 0===r?(0,zW.eI)(e.writePath):(0,zW.eI)(`${GW}/${r}`);if(!(0,zW.hJ)({path:n,prefix:GW}))return;const o=a().posix.basename(n),s=a().posix.join(GW,Dc);return a().posix.dirname(n)===s&&VW.test(o)?a().posix.join(GW,o):n}({writePath:n.path,hostProjectDir:r});if(void 0===s||s===n.path)return await t.execute(e,n,o);const i=n.clone();i.path=s;const c=await t.execute(e,i,o);return"success"===c.result.case&&(c.result.value.path=s),c}}}class JW{constructor(e,t="/"){this.fs=e,this.listeners=new Set,this.workspace=(0,zW.eI)(t)}getAllCursorRules(e){return this.rules??=async function(e,t){const[r,n]=await Promise.all([ZW(e,s.posix.join(t,".cursor/rules")),XW(e,s.posix.join(t,"AGENTS.md"))]);return void 0===n?r:[...r,n]}(this.fs,this.workspace),this.rules}reload(e){this.rules=void 0;for(const e of this.listeners)e()}onDidChangeRules(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}dispose(){this.listeners.clear()}}async function ZW(e,t){const r=[];try{for await(const n of e.list(t))"directory"!==n.kind&&n.path.endsWith(".mdc")&&r.push(n.path)}catch{return[]}return(await(0,Nr.PH)(r,(async t=>{const r=await QW(e,t),n=void 0===r?null:rn(r);if(null!==n)return fg({path:t,body:n.body,frontmatter:n.frontmatter,rawFrontmatter:n.rawFrontmatter})}),{max:8})).filter((e=>void 0!==e))}async function XW(e,t){const r=await QW(e,t);if(void 0!==r)return fg({path:t,body:Qr({content:r,filename:"AGENTS.md"}),frontmatter:{alwaysApply:!0}})}async function QW(e,t){try{const r=await e.read(t);return"string"==typeof r?r:(new TextDecoder).decode(r)}catch{return}}const YW={getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}},eH={async exec(){throw new Error("git is not available in a FileSystem session")}},tH={isIgnoredByAny:async()=>!1,isGitIgnored:async()=>!1,isCursorIgnored:async()=>!1,isRepoBlocked:async()=>!1,listCursorIgnoreFilesByRoot:async()=>[],getCursorIgnoreMapping:async()=>({}),getShellSandboxIgnoreMapping:async()=>({}),getGitIgnoreMapping:async()=>({}),getRepoBlockExcludeGlobs:async()=>[]};function rH(e){return{cursorRulesService:!0===e.includeProjectRules?new JW(e.fs,e.workspace):YW,getAgentSkills:async()=>[],subagentsService:e.subagentsService??new _g,gitExecutor:eH,ignoreService:tH,requestContextIsWorkingDirHomeDir:!1,reportProcessWorkingDirectory:!1}}function nH(e,t){const r=t.workspace??"/",n=(0,WW.c9)(e,{workspace:r});return{localResourceProviderOptions:{overrideReadExecutor:n.read,overrideWriteExecutor:KW({write:n.write,hostProjectDir:t.hostProjectDir}),overrideGrepExecutor:n.grep,overrideLsExecutor:n.ls,overrideDeleteExecutor:n.delete,suppressDefaultShellExecutor:!0,...rH({...t.settings,fs:e,workspace:r})},reportedWorkspacePath:r,reportedProjectFolder:GW,excludeHooks:!0,excludeProjectMcp:!0}}var oH=r("./src/agent/executor-common.ts");class sH{constructor(){this.countsByMode=new Map,this.failureKindsByMode=new Map,this.record=e=>{let t=this.countsByMode.get(e.mode);switch(void 0===t&&(t={mode:e.mode,checked_calls:0,outside_limit_calls:0,settings_unavailable_calls:0,unknown_server_calls:0},this.countsByMode.set(e.mode,t)),e.outcome){case"within_limit":return void(t.checked_calls+=1);case"outside_limit":return t.checked_calls+=1,void(t.outside_limit_calls+=1);case"settings_unavailable":{t.settings_unavailable_calls+=1;const r=e.settingsFailure;if(void 0===r)return;let n=this.failureKindsByMode.get(e.mode);return void 0===n&&(n=new Map,this.failureKindsByMode.set(e.mode,n)),void n.set(r,(n.get(r)??0)+1)}case"unknown_server":return void(t.unknown_server_calls+=1);default:return e.outcome}}}take(){const e=[...this.countsByMode.values()].map((e=>{const t=function(e){let t;for(const[r,n]of e??[])(void 0===t||n>t.calls)&&(t={kind:r,calls:n});return t?.kind}(this.failureKindsByMode.get(e.mode));return void 0===t?e:{...e,settings_unavailable_kind:t}}));return this.countsByMode.clear(),this.failureKindsByMode.clear(),e}}class iH{constructor(e=e=>{console.warn(e)}){this.write=e,this.printed=new Set,this.report=e=>{if(!this.printed.has(e.serverName)){this.printed.add(e.serverName);try{this.write(function(e){return`[cursor-sdk] ${e.refusal}`}(e))}catch{}}}}}const aH=new class{constructor(e=e=>{console.warn(e)}){this.write=e,this.printed=new Set,this.report=e=>{const t=JSON.stringify([e.serverName,(r=e.allowlist,JSON.stringify([r.list,r.name,r.reason,r.allowedServers??null,r.blockedServers??null]))]);var r;if(!this.printed.has(t)){this.printed.size>=1e3&&this.printed.clear(),this.printed.add(t);try{this.write(function(e){return`[cursor-sdk] MCP server "${e.serverName}" is under ${function(e){return`${e.name}, which applies because ${e.reason}.${r=e.allowedServers,void 0===r?"":0===r.length?" Allowed servers: none.":zC("Allowed servers",r)}${t=e.blockedServers,void 0===t||0===t.length?"":zC("Blocked",t)}`;var t,r}(e.allowlist)}`}(e))}catch{}}}}};var cH=r("./src/agent/native/vendored-tree-sitter.ts"),lH=r("./src/agent/platform-package-locator.ts"),uH=r("./src/agent/sdk-config.ts"),dH=r("../../node_modules/.pnpm/@statsig+js-client@3.31.0/node_modules/@statsig/js-client/src/index.js"),hH=r("./src/agent/utils/logger.ts");const pH={checkFeatureGate:()=>!1,getDynamicConfigValue:({defaultValue:e})=>e},fH=new Map;async function mH(e){try{const t=await async function(e){const t=await(0,oH.dC)(e,oH.EV);if(!t)return;const r=oH.EV.endsWith("/")?oH.EV.slice(0,-1):oH.EV,n=await fetch(`${r}/aiserver.v1.AnalyticsService/BootstrapStatsig`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json","x-cursor-client-type":"sdk","x-cursor-client-version":(0,oH.tF)(),"x-ghost-mode":(0,oH.U)(e)},body:JSON.stringify({})});if(!n.ok)return void hH.v.log(`Failed to bootstrap SDK Statsig: ${n.status} ${n.statusText}`);const o=await n.json();return gH(o)&&"string"==typeof o.config&&o.config.length>0?o.config:void 0}(e);if(!t)return pH;const r=new dH.StatsigClient("client-Bm4HJ0aDjXHQVsoACMREyLNxm5p6zzuzhO50MgtoT5D",function(e){try{const r=JSON.parse(e);if(gH(r)&&"object"==typeof(t=r.user)&&null!==t&&!Array.isArray(t))return{...r.user,custom:{...r.user.custom,clientType:"sdk",clientVersion:(0,oH.tF)()}}}catch(e){hH.v.log(`Failed to parse SDK Statsig bootstrap user: ${e instanceof Error?e.message:String(e)}`)}var t;return{custom:{clientType:"sdk",clientVersion:(0,oH.tF)()}}}(t),{disableLogging:!0,disableStorage:!0,networkConfig:{preventAllNetworkTraffic:!0}});return r.dataAdapter.setData(t),r.initializeSync(),{checkFeatureGate:(e,t)=>{try{return r.checkGate(e,t)}catch{return!1}},getDynamicConfigValue({configName:e,paramName:t,defaultValue:n}){try{return r.getDynamicConfig(e).get(t,n)}catch{return n}}}}catch(e){return hH.v.log(`Failed to initialize SDK Statsig: ${e instanceof Error?e.message:String(e)}`),pH}}function gH(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function wH(e){let t;return e?.then((e=>{t=e}),(()=>{})),()=>t?.checkFeatureGate("grok_bot_mcp_app_payment_token_filter",{disableExposureLog:!0})??!1}var yH=r("./src/agent/tools-option.ts");class vH{async requestApproval(){return{approved:!0}}}function bH(e,t){if(!function(e){return void 0!==e&&Object.keys(e).length>0}(t))return;const r=e.resources.base;if(!(r instanceof cD))throw new LW.j1("SDK custom tools require the default local workspace resource provider.",{isRetryable:!1});const n=r.getMcpExecutionPolicyDeps(),o=r.get(ro),s=function(e,t){return{async execute(r,n,o){const s=n.toolName||function(e){const t=`${Vn}-`;return e.startsWith(t)?e.slice(t.length):e}(n.name),i=e[s];if(void 0===i)return new Mc.iz({result:{case:"error",value:new Mc.Nh({error:`Unknown custom tool: ${s}`})}});try{return function(e){const t=function(e){return"object"==typeof(t=e)&&null!==t&&!Array.isArray(t)&&"content"in t&&Array.isArray(t.content)?{content:e.content,isError:e.isError,structuredContent:e.structuredContent}:"string"==typeof e?{content:[{type:"text",text:e}]}:{content:[{type:"text",text:JSON.stringify(e)}],structuredContent:NW(e)?e:void 0};var t}(e),r=void 0!==t.structuredContent?ve.Struct.fromJson(t.structuredContent):void 0;return new Mc.iz({result:{case:"success",value:new Mc.QW({content:t.content.map(FW),isError:t.isError??!1,structuredContent:r})}})}(await i.execute(function(e){return Object.fromEntries(Object.entries(e.args).map((([e,t])=>[e,t.toJson()])))}(n),{toolCallId:n.toolCallId||void 0,...void 0===t||""===t?{}:{sessionId:t}}))}catch(e){return new Mc.iz({result:{case:"error",value:new Mc.Nh({error:e instanceof Error?e.message:String(e)})}})}}}}(t,e.state.sessionId),i=new vH;e.resources.base.register(ro,{async execute(e,t,r){if(function(e){return e.providerIdentifier===Vn}(t)){const o=await RT(e,t,{...n,pendingDecisionProvider:i,toolDef:{source:"internal"}});return void 0!==o?o:s.execute(e,t,r)}return o.execute(e,t,r)}})}const SH=new Set(["127.0.0.1","localhost","[::1]"]);function kH(e){if(void 0===e)return{};const t=e.resourceProviderOptions;return{...void 0!==t?{localResourceProviderOptions:t}:{},...void 0!==e.reportedWorkspacePath?{reportedWorkspacePath:e.reportedWorkspacePath}:{}}}function _H(){const e=process.env.CURSOR_SDK_MOCK_PROMPT_TIME;if(void 0===e||""===e)return;const t=new Date(e);return Number.isNaN(t.getTime())?void 0:t}const CH={warn(){},error(){}},EH={log(){}};class xH{async requestApproval(e){return{approved:!1,reason:`Local SDK runs cannot request interactive approval for ${PH(e)}. Keep the action within the configured sandbox policy or Smart Auto Review's auto-approval boundary, or re-run without sandboxing/autoReview enabled.`}}}function PH(e){switch(e.type){case Bw.Shell:return"this shell command";case Bw.Mcp:return"this MCP tool call";case Bw.Write:return"this file edit";case Bw.Delete:return"this file deletion";default:return"this operation"}}function RH(e){return void 0!==e&&"insecure_none"!==e.type}async function IH(e,t){const r="string"==typeof e||void 0===e?{workingDirectory:e,apiKey:t}:e,i=(0,b.q6)().with(d._O,EH),a=CB(r.settingSources),l=void 0===r.hostMcpBridgeUrls?void 0:r.hostMcpBridgeUrls.filter((e=>{let t;try{t=new URL(e)}catch{t=void 0}const r=void 0!==t&&"http:"===t.protocol&&""===t.username&&""===t.password&&SH.has(t.hostname);return r||console.warn(`[cursor-sdk] ignoring local.hostMcpBridgeUrls entry ${e}: not an http URL on 127.0.0.1, localhost or [::1]`),r}));!function(e){if(void 0!==e&&(!Number.isFinite(e)||e<=0))throw new Error(`Workspace scan cache TTL must be a positive number of milliseconds, got ${e}`);ba=e}((0,uH.Mu)()),/:\/\/(localhost|127\.0\.0\.1)/.test(oH.EV)&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0");const u=performance.now();let h=0;if(r.apiKey){const e=performance.now();await Promise.all([(0,oH.ly)(r.apiKey),(0,oH.mU)(r.apiKey)]),h=performance.now()-e}const p=r.workingDirectory||process.cwd();(0,cH.configureVendoredTreeSitterWorkspaceDir)(p);for(const e of r.dirs??[])(0,cH.configureVendoredTreeSitterWorkspaceDir)(e);const f=(0,_o.Rv)((0,o.homedir)(),p),m={hostProjectDir:f,settings:{includeProjectRules:EB(a,"project"),subagentsService:new FB(r.customSubagents??[])}};let g;const w="win32"===process.platform?"rg.exe":"rg",y=process.env.CURSOR_RIPGREP_PATH;g=y&&(0,s.isAbsolute)(y)?y:(0,lH.hQ)({binaryName:w,excludedWorkspaceDir:p}),g||(g=(0,No.xS)()),g&&(0,No.J)(g);let v,S,k,_={getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getAdminCommandDenylist:async()=>({rules:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}};if(r.apiKey)try{const e=(0,oH.qN)(r.apiKey,r.teamId);v=e.transport,S=e.getAccessToken;const t=(0,be.createClient)(wj.I,v),n=function(e){let t=fH.get(e);return t||(t=mH(e),fH.set(e,t),t.then((r=>{r===pH&&fH.get(e)===t&&fH.delete(e)}),(()=>{fH.get(e)===t&&fH.delete(e)}))),t}(r.apiKey);k=n;const o={getDefaultNetworkAllowlist:async()=>(await n).getDynamicConfigValue({configName:"sandbox_default_network_allowlist",paramName:"allowlist",defaultValue:[]})};_=new vO(new gO(t,{supportsHostMcpBridgeExemption:!0}),o,{...void 0===l?{}:{hostMcpBridgeUrls:l},mcpAdminToolLimitSurvivesFailedRead:!0,isMcpAccessNetworkAllowlistEnabled:async()=>(await n).checkFeatureGate("mcp_access_network_allowlist"),isMcpSettingsOverhaulEnabled:async e=>(await n).checkFeatureGate("mcp_settings_overhaul",e),isWin32UserExtensionStdioUnsandboxEnabled:async e=>(await n).checkFeatureGate("mcp_user_extension_stdio_unsandboxed_win32",e),isAdminCommandDenylistEnforcementKilled:async()=>(await n).checkFeatureGate("admin_command_denylist_enforcement_killswitch")})}catch(e){hH.v.log(`Failed to initialize authenticated dashboard services: ${e instanceof Error?e.message:String(e)}`)}const C=performance.now(),E=r.apiKey?await(0,No.tv)(`${(0,o.homedir)()}/.cursor/sandbox.json`,(0,o.homedir)()):void 0,x=void 0!==r.apiKey?await async function(e){const{cwd:t,perUserSandboxPolicy:r,sandboxOptions:n}=e;if(!1===n?.enabled)return{defaultSandboxPolicy:{type:"insecure_none"},defaultSandboxPolicySources:void 0};const o=RH(r)?r:!0===n?.enabled?function(e,t={}){return{type:e,...t}}("workspace_readwrite",{networkPolicy:(0,No.Po)()}):void 0;if(void 0===o)return{defaultSandboxPolicy:{type:"insecure_none"},defaultSandboxPolicySources:void 0};if(function(e){const t="win32"===process.platform?"cursorsandbox.exe":"cursorsandbox",r=(0,lH.hQ)({binaryName:t,excludedWorkspaceDir:e});r&&(0,No.St)({sandboxBinaryPath:r})}(t),!(0,No.K3)(void 0,{ctx:e.initializationCtx}))throw new LW.j1("Local SDK sandboxing was requested, but sandboxing is not supported in this environment. Disable local.sandboxOptions.enabled or remove ~/.cursor/sandbox.json to run without sandboxing.",{isRetryable:!1});const s={};s.perUser=o;const{policy:i}=await(0,No.resolveSandboxPolicyForWorkspace)(t,s);return{defaultSandboxPolicy:i,defaultSandboxPolicySources:s}}({cwd:p,perUserSandboxPolicy:E,sandboxOptions:r.sandboxOptions,initializationCtx:i}):void 0,P=performance.now()-C,R=x?.defaultSandboxPolicy,I=x?.defaultSandboxPolicySources,T=RH(R),A=performance.now(),$=(()=>{const e=[],t=new Set;for(const n of[p,...r.dirs??[]]){const r=(0,s.resolve)(n);t.has(r)||(t.add(r),e.push(n))}return e.length>1?e:void 0})(),M={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1},O=await async function(e){const{workingDirectory:t,projectDir:r}=e,n=function(e,t){const r=[],n=new Set;for(const o of[e,...t??[]]){const e=(0,s.resolve)(o);n.has(e)||(n.add(e),r.push(o))}return r}(t,e.dirs),o=n.length>1?n:void 0,i=CB(e.settingSources),a=e.teamSettingsService??{getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getAdminCommandDenylist:async()=>({rules:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}},c=e.defaultSandboxPolicy??{type:"insecure_none"},l=e.getSandboxSupported??(()=>(0,No.K3)(c,{ctx:e.initializationCtx})),u=e.getSandboxEnabled??(()=>"insecure_none"!==c.type&&l()),d=new xy,h=new Rc(d,a,n),p=new MB,f=new DB,m=e.getSmartModeClassifierAutoModeEnabled?.(),g=new $B(m?"allowlist":e.approvalMode??"unrestricted",c,a,e.respectAdminControls??!1),w=e.pendingDecisionProvider,y={executeIndexedGrep:void 0},v=()=>!0,b=EB(i,"plugins"),S=e.importThirdPartyPlugins??!1,k=e.mcpMetaToolEnabled??!0,_=void 0!==e.mcpServers&&Object.keys(e.mcpServers).length>0,C=void 0!==e.customSubagents&&e.customSubagents.length>0,E=_||EB(i,"project")||EB(i,"user")||b,x=EB(i,"project")||EB(i,"user")||EB(i,"mdm"),P=EB(i,"team"),R=P&&void 0!==e.dashboardTransport,I=EB(i,"project")||EB(i,"user")||P||R||b,T={teamSettingsService:a,initializationCtx:e.initializationCtx,importThirdPartyPlugins:S,ignoreApprovals:!0,includeProjectMcp:EB(i,"project"),includeUserMcp:EB(i,"user"),includePluginMcp:b,isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled,restMcpCursorAuthTokenSupplier:e.restMcpCursorAuthTokenSupplier},A=s=>TB({workingDirectory:t,...void 0!==o?{workspaceRoots:o}:{},adapters:{...s.includeMcp?{mcp:ZO({...T,inlineMcpServers:e.mcpServers})}:{},...b?{pluginBootstrap:oB({importThirdPartyPlugins:S,dashboardTransport:e.dashboardTransport})}:{},...x?{hooks:gj({includeProjectHooks:EB(i,"project"),includeUserHooks:EB(i,"user"),includeEnterpriseHooks:EB(i,"mdm"),useCommandHookStdinTransport:e.useCommandHookStdinTransport})}:{},...I?{localExtensibility:vj({includeProjectExtensibility:EB(i,"project"),includeUserExtensibility:EB(i,"user"),includeManagedSkills:R,includeTeamExtensibility:P,includePluginExtensibility:b,teamSettingsService:a,getThirdPartyExtensibilityEnabled:v,dashboardTransport:e.dashboardTransport,importThirdPartyPlugins:S})}:{},resourceFactory:fB({attributionConfigProvider:EB(i,"user")?{get(){try{const{readFileSync:r}=process.getBuiltinModule("node:fs"),{join:j}=process.getBuiltinModule("node:path"),{homedir:h}=process.getBuiltinModule("node:os"),x=process.env.XDG_CONFIG_HOME,d=process.env.CURSOR_CONFIG_DIR||(x&&process.platform!=="darwin"&&process.platform!=="win32"?j(x,"cursor"):j(h(),".cursor"));return JSON.parse(r(j(d,"cli-config.json"),"utf8"))}catch{return}}}:void 0,ignoreService:h,grepProvider:y,workspacePaths:n,diagnosticsProvider:p,repositoryProvider:f,projectDir:r??t,shellManager:void 0,defaultSandboxPolicy:c,defaultSandboxPolicySources:e.defaultSandboxPolicySources,getSandboxEnabled:u,getSandboxSupported:l,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:e.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:e.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:e.getMockPromptTime,getPowershellUtf8Options:e.getPowershellUtf8Options,mcpFileOutputThresholdBytes:void 0,mcpMetaToolEnabled:k,createMcpStateAccessor:(e,t)=>new OB(new aM(e),void 0===t?.onMcpAllowlistInUse&&void 0===t?.onMcpServerBlockedByAllowlist?void 0:{mcpLease:e,onMcpAllowlistInUse:t.onMcpAllowlistInUse,onMcpServerBlockedByAllowlist:t.onMcpServerBlockedByAllowlist}),createSessionMcpLease:(t,r)=>ZO({...T,includeProjectMcp:T.includeProjectMcp&&!0!==t.options.excludeProjectMcp,inlineMcpServers:r??e.mcpServers}).createLease({workspaceState:t.workspaceState,services:t.workspaceServices,policy:t.policy}),createSessionDependencies:r=>{const n=w??new AB;return{pendingDecisionStore:n,fileChangeTracker:new qw(t),permissionsService:new o_(h,n,g,a,t,e.respectAdminControls??!1,{enforceMcpAdminToolLimits:e.isMcpAdminToolLimitEnforced,onMcpAdminToolLimitCheck:r.options.onMcpAdminToolLimitCheck})}}}),resourceWrappers:x?[{wrapResources(e){const t=e.workspaceServices.hooksRuntime;if(!0===e.options.excludeHooks||"object"!=typeof(r=t)||null===r||!("hooksConfigLease"in r)||!("createSessionRuntime"in r)||"function"!=typeof r.createSessionRuntime||!function(e){return"object"==typeof e&&null!==e&&"get"in e&&"function"==typeof e.get&&"entries"in e&&"function"==typeof e.entries}(e.resources))return e.resources;var r;const n=t.createSessionRuntime({sessionState:e.sessionState,metadata:e.metadata});return new fj(new aj(e.resources,n.hookExecutor,(()=>function(e,t){const r=uj(t,dj,"conversationId","conversation_id")??e.sessionId??"";return{conversation_id:r,generation_id:uj(t,dj,"generationId","generation_id")??r,model:uj(t,dj,"model")??"unknown",...mF({modelId:uj(t,dj,"modelId","model_id"),modelParams:uj(t,pj,"modelParams","model_params")})}}(e.sessionState,e.metadata)),e.workspaceServices.mcpLease,void 0,void 0,t.hooksConfigLease),n)}}]:[],...C?{workspaceServicesContributors:[{contributeServices:t=>{const r=new FB(e.customSubagents??[]),n=t.services.subagentsService;return{subagentsService:void 0===n?r:new Ag([r,n])}}}]}:{}}});if(!E)return A({includeMcp:!1});try{return await A({includeMcp:!0})}catch(e){return CO.Jz.warn("[default-local-workspace-runtime] Failed to initialize MCP-enabled runtime, retrying without MCP:",{error:e,workingDirectory:t,projectDir:r,enablePlugins:b,importThirdPartyPlugins:S}),A({includeMcp:!1})}}({workingDirectory:p,...void 0!==$?{dirs:$}:{},projectDir:f,teamSettingsService:_,initializationCtx:i,dashboardTransport:v,settingSources:r.settingSources,mcpServers:r.mcpServers,customSubagents:r.customSubagents,defaultSandboxPolicy:R,defaultSandboxPolicySources:I,approvalMode:T?"allowlist":void 0,pendingDecisionProvider:T||!0===r.autoReview?new xH:void 0,getNetworkAllowlistInfo:T?()=>async function(e,t,r){const[n,o]=await Promise.all([e.getDefaultNetworkAllowlist(),e.getNetworkAccessControls()]),s=[...o.allowlist],i=`${t}/.cursor/sandbox.json`,a=await(0,No.tv)(i,t);if(a&&"insecure_none"!==a.type&&a.networkPolicy?.allow&&s.push(...a.networkPolicy.allow),"1"!==process.env[Yv.K4]&&r){const e=await(0,No.tv)(`${r}/.cursor/sandbox.json`,r);e&&"insecure_none"!==e.type&&e.networkPolicy?.allow&&s.push(...e.networkPolicy.allow)}const c=[...new Set(s)];return{hasDefaults:n.available&&n.allowlist.length>0,explicitEntries:c}}(_,(0,o.homedir)(),p):void 0,getSmartModeClassifierAutoModeEnabled:()=>!0===r.autoReview,devForceNextSmartModeClassifierBlockToken:r.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:_H,getPowershellUtf8Options:async()=>{if(void 0===k)return M;try{const e=await k;return{powershellUtf8Console:e.checkFeatureGate("shell_exec_powershell_utf8_console"),powershellUtf8ChildEnv:e.checkFeatureGate("shell_exec_powershell_utf8_child_env")}}catch{return M}},isLinkSharedPaymentTokenLogRedactionEnabled:wH(k),restMcpCursorAuthTokenSupplier:S,respectAdminControls:void 0!==r.apiKey,isMcpAdminToolLimitEnforced:void 0===k?void 0:(F=k,async()=>{try{return(await F).checkFeatureGate("sdk_local_mcp_admin_tool_limits",{disableExposureLog:!0})}catch{return!1}}),useCommandHookStdinTransport:!0});var F;const N=performance.now()-A;let L,j;return(0,eW.ou)(r.apiKey,{runtime:"local",ensure_ghost_mode_ms:Math.round(h),bootstrap_statsig_ms:0,create_workspace_runtime_ms:Math.round(N),load_sandbox_policy_ms:Math.round(P),total_ms:Math.round(performance.now()-u)}),{run:async(e,t,o)=>(0,CO.ni)(CH,(async()=>{const s=(0,D.VI)((0,b.q6)().withName("sdk.run").with(d._O,EH)),[i,a]=s.ctx.withCancel(),l=t.sessionId??(0,ye.C)(),u=t.mcpServersOverride,h=void 0===(f=t.customTools)?[]:Object.entries(f).map((([e,t])=>({clientKey:Vn,providerIdentifier:Vn,toolName:e,name:`${Vn}-${e}`,description:t.description??"",inputSchema:t.inputSchema??DW,...void 0===t.outputSchema?{}:{outputSchema:t.outputSchema},...void 0===t.annotations?{}:{annotations:OW(t.annotations)},source:"internal"})));var f;let g;const w={...m,workspace:t.fileSystemWorkspace},y=void 0===t.fileSystem?void 0:(_=await async function(e,t){return"function"==typeof e?await e(t):e}(t.fileSystem,{agentId:l,sessionId:l}),C=_,(0,HW.VL)({"/":C,[GW]:(0,qW.Om)()})),v=void 0===t.onMcpAdminToolLimitCounts?void 0:new sH,S=()=>{for(const e of v?.take()??[])try{t.onMcpAdminToolLimitCounts?.(e)}catch{}},k=new iH;var _,C;g=await O.createSessionRuntime({sessionId:l,mcpServersOverride:u,extraMcpTools:h,onMcpAdminToolLimitCheck:v?.record,onMcpAllowlistInUse:aH.report,onMcpServerBlockedByAllowlist:k.report,...void 0===y?kH(t.sessionResources):nH(y,w)});const E=new Map;try{const s=g.resources.wrapped;bH(g,t.customTools),void 0!==y&&BW(g.resources.base);const d=t.blobStore??new oe.ve;let f=t.initialState??new c.Y9z({});const m=void 0!==t.model?new QB.G4({modelId:t.model.id,...!0===t.model.maxMode?{maxMode:!0}:{},parameters:(t.model.params??[]).map((e=>new QB.SR({id:e.id,value:e.value})))}):void 0,b=!0===e.summarize?void 0:e.images,_=Array.isArray(b)?b.map((e=>{const t=(0,ye.C)(),r=new Uint8Array(n.Buffer.from(e.data,"base64")),o=(0,oH.v8)(r);return new YB.d({uuid:t,...o?{mimeType:o}:{},dataOrBlobId:{case:"data",value:r}})})):[],C=_.length>0?new YB.xv({selectedImages:_}):void 0,R=function(e){switch(e){case"agent":return c.xyI.AGENT;case"plan":return c.xyI.PLAN;default:return}}(t.mode),I=e.resume===!0?new c.QFf({action:{case:"resumeAction",value:new c.qKo}}):!0===e.summarize?new c.QFf({action:{case:"summarizeAction",value:new c.Scs}}):new c.QFf({action:{case:"userMessageAction",value:new c.Vtf({userMessage:new c.RGk({text:e.text,selectedContext:C,...void 0!==R?{mode:R}:{}})})}}),T={sendUpdate:async(e,t)=>{const r=cW(t,l);null!==r&&await o.sendUpdate(r)},query:async(e,r)=>await async function(e,t){if("mcpAuthRequestQuery"===e.query.case&&void 0!==t){const r=await async function(e,t,r){let n;try{n=await e({serverName:r.args?.serverIdentifier??"",toolCallId:r.args?.toolCallId??""})}catch{return Cr(t,"The MCP sign-in request failed.")}if(void 0!==n)switch(n.kind){case"approved":return _r(t);case"rejected":return Cr(t,n.reason);default:return n}}(t,e.id,e.query.value);if(void 0!==r)return r}return function(e){switch(e.query.case){case"webSearchRequestQuery":return hr(e.id);case"webFetchRequestQuery":return fr(e.id);case"switchModeRequestQuery":return wr(e.id);case"askQuestionInteractionQuery":return gr(e.id,new er.tz({result:{case:"rejected",value:new er.ox({reason:"Interactive questions are not supported in local SDK runs"})}}));case"createPlanRequestQuery":return vr(e.id,new tr.bK({result:{case:"success",value:new tr.Jo},planUri:""}));case"setupVmEnvironmentArgs":return br(e.id,new or.r$({result:{case:"success",value:new or.JH}}));case"replaceEnvArgs":return Sr(e.id,new nr.dV({result:{case:"failure",value:new nr.uq({errorMessage:"Environment replacement is not supported in local SDK runs",setupLogs:""})}}));case"prManagementRequestQuery":return kr(e.id,new rr.HL({result:{case:"error",value:new rr.K$({error:"PR management is only available in cloud agents"})}}));case"mcpAuthRequestQuery":return Cr(e.id,"MCP authentication is not supported in local SDK runs");case"connectScmRequestQuery":return Er(e.id,"Connecting GitHub is not supported in local SDK runs");case"generateImageRequestQuery":return xr(e.id,e.query.value.args?.description);case void 0:throw new LW.j1("Missing interaction query type",{isRetryable:!1});default:throw e.query,new LW.j1("Unhandled interaction query type",{isRetryable:!1})}}(e)}(r,t.onMcpAuthRequest)};if(L!==t.apiKey||!j){await Promise.all([(0,oH.ly)(t.apiKey),(0,oH.mU)(t.apiKey)]);const e=(0,oH.KU)(t.apiKey,r.teamId),n=So((0,be.createClient)(XB.N,e),{injectTraceHeaders:!0});j=new qn(n),L=t.apiKey}const A=(0,oH.Vh)(j,(()=>{const e=(0,oH.KU)(t.apiKey,r.teamId),n=So((0,be.createClient)(XB.N,e),{injectTraceHeaders:!0}),o=new qn(n);return j=o,L=t.apiKey,o})),$=function(e){return{...void 0!==e.allowedTools?{[yH.$$]:e.allowedTools.join(",")}:{},...void 0!==e.disallowedTools&&e.disallowedTools.length>0?{[yH.VJ]:e.disallowedTools.join(",")}:{}}}(t),M=new ZB({agentClient:A,rootRequestId:t.requestId,getResources:async({agentId:e})=>{let r=E.get(e);return r||(r=await O.createSessionRuntime({sessionId:e,mcpServersOverride:u,extraMcpTools:h,onMcpAdminToolLimitCheck:v?.record,onMcpAllowlistInUse:aH.report,onMcpServerBlockedByAllowlist:k.report,...void 0===y?kH(t.subagentInherit):nH(y,w)}),bH(r,t.customTools),void 0!==y&&BW(r.resources.base),r.resources.base.register(co,D),r.resources.base.register(lo,F),r.resources.base.register(uo,N),E.set(e,r)),r.resources.wrapped},mcpTools:h,workspacePath:p,parentConversationId:l,...(void 0!==t.subagentInherit||void 0!==y)&&Object.keys($).length>0?{headers:$}:{},onSessionReleased:e=>{const t=E.get(e);t&&(t.dispose(),E.delete(e))}}),D=function(e){const t=new Map,r=new Map;async function n(t,r,n){let o;try{o=await e.createOrResumeSession(t,r);const s=await e.runSession(t,o,r,{execId:n?.execId});return"error"===s.status?new io.vS({result:{case:"error",value:new io.od({agentId:o,error:s.error})}}):"aborted"===s.status?new io.vS({result:{case:"error",value:new io.od({agentId:o,error:s.error??"Subagent was aborted by the user"})}}):"background"===s.status?new io.vS({result:{case:"success",value:new io.HJ({agentId:o,finalMessage:s.finalMessage,toolCallCount:s.toolCallCount??0,backgroundReason:s.backgroundReason,transcriptPath:s.transcriptPath})}}):new io.vS({result:{case:"success",value:new io.HJ({agentId:o,finalMessage:s.finalMessage,toolCallCount:s.toolCallCount??0})}})}catch(t){if(o&&e.releaseSession&&e.releaseSession(o),t instanceof dr)throw t;const n=t instanceof Error?t.message:String(t),s=o??function(e){return e instanceof ao&&e.agentId||e&&"object"==typeof e&&"agentId"in e&&"string"==typeof e.agentId?e.agentId:void 0}(t)??r.resumeAgentId;return new io.vS({result:{case:"error",value:new io.od({...s?{agentId:s}:{},error:n})}})}}return{execute(e,o,s){const i=function(e){if(e.toolCallId&&e.parentConversationId)return[e.parentConversationId,e.toolCallId,e.resumeAgentId??"",e.forkAgentId??""].join("\0")}(o);if(void 0===i)return n(e,o,s);const a=r.get(i);if(void 0!==a)return Promise.resolve(a);const c=t.get(i);if(void 0!==c)return c;const l=n(e,o,s).then((e=>("success"===e.result.case&&(r.set(i,e),r.size>1e3&&r.delete(r.keys().next().value)),e))).finally((()=>{t.delete(i)}));return t.set(i,l),l}}}(M),F=(P=M,{execute:(e,t)=>P.awaitBackgroundRunBounded(e,t)}),N=function(e){return{execute:async(t,r)=>e.forceBackgroundByToolCallId(r.toolCallId)}}(M);g.resources.base.register(co,D),g.resources.base.register(lo,F),g.resources.base.register(uo,N);const U=O.services.hooksRuntime,B="object"==typeof(x=U)&&null!==x&&"workspacePath"in x&&"string"==typeof x.workspacePath&&"createSessionRuntime"in x&&"function"==typeof x.createSessionRuntime?U:void 0,W=void 0!==B&&void 0===y&&!0!==e.summarize?function(e){const{workspaceRuntime:t}=e;if(!(t.hooksConfigLease.hasHookForStep(Rd.sessionStart)||t.hooksConfigLease.hasHookForStep(Rd.sessionEnd)||t.hooksConfigLease.hasHookForStep(Rd.stop)||t.hooksConfigLease.hasHookForStep(Rd.beforeSubmitPrompt)))return{};const r=t.createSessionRuntime({sessionState:e.sessionState,metadata:e.metadata}),{hookExecutor:n}=r;let o;return{async onSessionStart(e){if(o=e,n.hasHooksForStep(Rd.sessionStart))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...mF(e),is_background_agent:!1},r=await n.executeHookForStep(Rd.sessionStart,t);if(r)return r.env&&n.setSessionEnvironment(r.env),{env:r.env,additionalContext:r.additional_context,blocked:!1===r.continue,blockedReason:r.user_message}}catch(e){CO.Jz.warn("[hooks-adapter] sessionStart hook failed:",e)}},async onSessionEnd(e,t){if(n.hasHooksForStep(Rd.sessionEnd))try{const r={conversation_id:o?.conversationId??"",generation_id:o?.generationId??"",model:o?.model??"unknown",...o?mF(o):{},reason:e,duration_ms:t,is_background_agent:!1,final_status:e};await n.executeHookForStep(Rd.sessionEnd,r)}catch(e){CO.Jz.warn("[hooks-adapter] sessionEnd hook failed:",e)}finally{n.clearSessionEnvironment()}else n.clearSessionEnvironment()},async onBeforeSubmitPrompt(e){if(n.hasHooksForStep(Rd.beforeSubmitPrompt))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...mF(e),prompt:e.promptText??"",attachments:[]};await n.executeHookForStep(Rd.beforeSubmitPrompt,t)}catch(e){CO.Jz.warn("[hooks-adapter] beforeSubmitPrompt hook failed:",e)}},async onTurnCompleted(e){if(!n.hasHooksForStep(Rd.stop))return;const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...mF(e),status:"completed",loop_count:e.loopCount},r=await n.executeHookForStep(Rd.stop,t),o="string"==typeof r?.followup_message?r.followup_message.trim():"";return o.length>0?o:void 0},async onTurnError(e){if(n.hasHooksForStep(Rd.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...mF(e),status:"error",loop_count:e.loopCount};await n.executeHookForStep(Rd.stop,t)}catch(e){CO.Jz.warn("[hooks-adapter] onTurnError stop hook failed:",e)}},async onTurnAborted(e){if(n.hasHooksForStep(Rd.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...mF(e),status:"aborted",loop_count:e.loopCount};await n.executeHookForStep(Rd.stop,t)}catch(e){CO.Jz.warn("[hooks-adapter] onTurnAborted stop hook failed:",e)}},async dispose(){await r.dispose()}}}({workspaceRuntime:B,sessionState:g.state,metadata:g.metadata}):void 0,H=new VB({workspacePath:p,conversationId:l,blobStore:d}),q=function(e,t,r){const{hooks:n}=r,[o,s]=e.withCancel(),i=new _O;let a;const l=new Map,u=(e,t)=>{const r=l.get(e);void 0!==r&&(l.delete(e),clearTimeout(r.ackTimer),r.resolve(t))};let d;const h=[],p=e=>{for(const t of h.splice(0))t.resolve(e)},f=()=>{if(0===h.length)return;const e=h.map((e=>e.text)).join("\n\n");return p("complete_delivered"),AO(e)},m=r.interactionListener,g={async sendUpdate(e,t){const r=t.message;if("contextInjectionState"===r?.case){const e=r.value,t="object"==typeof e&&null!==e&&"injectionId"in e&&"string"==typeof e.injectionId?e.injectionId:void 0,n=function(e){if("object"!=typeof e||null===e||!("state"in e))return;const t=e.state;if("object"!=typeof t||null===t||!("state"in t))return;const r=t.state;return"object"==typeof r&&null!==r&&"case"in r&&"string"==typeof r.case?r.case:void 0}(e),o=function(e){switch(e){case"queued":return"queued";case"delivered":return"delivered";case"queuedForNextTurn":return"queued_for_next_turn";case"cancelled":return"cancelled";default:return"rejected"}}(n),s=void 0===t?void 0:l.get(t);if(void 0!==s&&void 0!==t){const e=function(e){switch(e){case"queued":return"confirm_steering";case"delivered":return"complete_delivered";case"queued_for_next_turn":case"cancelled":case"rejected":return"revert_to_followup";default:throw new Error(`Unknown steer ack state: ${String(e)}`)}}(o);"confirm_steering"===e?clearTimeout(s.ackTimer):(l.delete(t),s.resolve(e))}}await m.sendUpdate(e,t)},query:(e,t)=>m.query(e,t),...void 0!==m.enqueuePostTurnEndedWork?{enqueuePostTurnEndedWork:e=>m.enqueuePostTurnEndedWork?.(e)}:{},...void 0!==m.flushPostTurnEndedWork?{flushPostTurnEndedWork:e=>m.flushPostTurnEndedWork?.(e)??Promise.resolve()}:{}};let w=r.initialState;const y={async handleCheckpoint(e,t){w=t,await(r.onCheckpoint?.(t))},getLatestCheckpoint:()=>w};let v="completed";const b=Date.now(),S=PO(function(e,t){if((0,EO.TU)(t))return t;const r=RO.get(e);if(void 0!==r)return r;const n=(0,EO.sh)(e).blobEncryptionKey;if(void 0===n)throw new Error("getDefaultAgentMetadata did not seed a blobEncryptionKey");return RO.set(e,n),n}(r.conversationId,r.blobEncryptionKey),r.runOptions?.headers);return{done:(async()=>{const e=TO(r,0,IO(t));try{const t=await(n?.onSessionStart?.(e));if(t?.blocked)throw v="error",new Error(t.blockedReason??"Session blocked by sessionStart hook")}catch(e){if("completed"!==v)throw e;CO.Jz.warn("[agent-session-runner] sessionStart hook failed:",e)}let s=t,c=0;for(;s;){const e=TO(r,c,IO(s));try{await(n?.onBeforeSubmitPrompt?.(e))}catch(e){CO.Jz.warn("[agent-session-runner] beforeSubmitPrompt hook failed:",e)}a=r.runOptions?.generationUUID??(0,ye.C)();try{await r.agentClient.run(o,w,s,void 0,g,r.resources,r.blobStore,i,y,r.mcpTools??[],{conversationId:r.conversationId,...r.runOptions,generationUUID:a,headers:S,subagentModelOverrides:r.runOptions?.subagentModelOverrides??[]})}catch(t){throw v=$O(t)?"aborted":"error",MO("aborted"===v?n?.onTurnAborted?.(e):n?.onTurnError?.(e)),t}finally{a=void 0;for(const e of[...l.keys()])u(e,"revert_to_followup")}let t;try{t=await(n?.onTurnCompleted?.(e))}catch(e){throw v="error",e}const h="string"==typeof t?t.trim():"";let m;if(h.length>0)m=AO(h);else{const t=new AbortController;d=t;try{m=await(r.nextAction?.(e,AbortSignal.any([o.signal,t.signal])))}catch(r){if(o.signal.aborted||!t.signal.aborted)throw v=o.signal.aborted||$O(r)?"aborted":"error",MO("aborted"===v?n?.onTurnAborted?.(e):n?.onTurnError?.(e)),r}finally{d=void 0}void 0===m?m=f():p("revert_to_followup")}void 0!==m?(c+=1,i.resetStream(),s=m):s=void 0}})().finally((async()=>{p("revert_to_followup");const e=Date.now()-b;try{await(n?.onSessionEnd?.(v,e))}catch(e){CO.Jz.warn("[agent-session-runner] sessionEnd hook failed:",e)}try{await(n?.dispose?.())}catch(e){CO.Jz.warn("[agent-session-runner] hooks dispose failed:",e)}})),abort(){s()},async steer(e){if(""===e.trim())return"revert_to_followup";const t=a;if(void 0===t){const t=d;if(void 0===t)return"revert_to_followup";const r=new Promise((t=>{h.push({text:e,resolve:t})}));return t.abort(),await r}const r=(0,ye.C)(),n=new Promise((e=>{const t=setTimeout((()=>{u(r,"revert_to_followup")}),15e3);t.unref?.(),l.set(r,{resolve:e,ackTimer:t})}));try{return await i.submitConversationAction(new c.QFf({action:{case:"injectContextAction",value:new c.hGJ({injectionId:r,expectedRunId:t,payload:{case:"userContext",value:new c.oW$({userMessage:new c.RGk({messageId:(0,ye.C)(),text:e})})}})}})),await n}catch(e){return u(r,"revert_to_followup"),CO.Jz.warn("[agent-session-runner] context injection failed:",e),"revert_to_followup"}}}}(i,I,{agentClient:A,interactionListener:T,resources:s,blobStore:d,initialState:f,conversationId:l,mcpTools:h,blobEncryptionKey:t.blobEncryptionKey,runOptions:{generationUUID:t.requestId,requestedModel:m,enableAgentRetries:!1!==r.enableAgentRetries,emitModelCallUsage:!0,...void 0!==t.onConnectionStateChange?{onConnectionStateChange:e=>{!function(e,t){if(void 0!==e)try{e(function(e){switch(e.state){case"connected":return{state:"connected"};case"reconnecting":{const t=e.trigger?.errorClass,r=e.trigger?.stallAborted,n={...void 0!==t?{errorClass:t}:{},...void 0!==r?{stallAborted:r}:{}};return{state:"reconnecting",attempt:e.attempt,...Object.keys(n).length>0?{trigger:n}:{}}}default:return e}}(t))}catch(e){hH.v.warn(`onConnectionStateChange failed: ${e instanceof Error?e.message:String(e)}`)}}(t.onConnectionStateChange,e)}}:{},...Object.keys($).length>0?{headers:$}:{},...void 0!==t.systemPrompt?{customSystemPrompt:t.systemPrompt}:{}},hooks:W,async nextAction(e,t){const r=await M.waitForBackgroundCompletions(l,t);return r.length>0?function(e){return new c.QFf({action:{case:"backgroundTaskCompletionAction",value:new c.Kwc({completions:e.map((e=>new c.KFq({taskId:e.agentId,kind:c.aZc.SUBAGENT,status:"success"===e.status?c.uHL.SUCCESS:"aborted"===e.status?c.uHL.ABORTED:c.uHL.ERROR,...e.finalMessage.length>0?{detail:e.finalMessage}:{}})))})}})}(r):void 0},async onCheckpoint(e){f=e,H.writeFromState(i,e),await(t.onCheckpoint?.(e))}}),z=q.done.finally((async()=>{try{await M.awaitBackgroundWorkers()}finally{await H.waitForPendingWrites().catch((()=>{}));for(const e of E.values())try{await e.dispose()}catch(e){hH.v.log(`Failed to dispose subagent session runtime: ${e instanceof Error?e.message:String(e)}`)}E.clear();try{await g.dispose()}finally{S()}}})).catch((e=>{throw e}));return{abort(){q.abort(),a()},done:z,steer:e=>q.steer(e)}}catch(e){for(const e of E.values())try{await e.dispose()}catch{}E.clear();try{await g.dispose()}finally{S()}throw e}var x,P})),async reload(){await O.reload()},async dispose(){await O.dispose()}}}},"./src/agent/native/tree-sitter-bash.webpack.cjs"(e,t,r){const{loadVendoredTreeSitterModule:n}=r("./src/agent/native/vendored-tree-sitter.ts"),o=n({packageName:"tree-sitter-bash",nativeRequire:require});e.exports=o.available?o.module:{}},"./src/agent/native/tree-sitter.webpack.cjs"(e,t,r){const{createUnavailableParserClass:n,loadVendoredTreeSitterModule:o}=r("./src/agent/native/vendored-tree-sitter.ts"),s=o({packageName:"tree-sitter",nativeRequire:require});e.exports=s.available?s.module:n(s.reason)},"../constants/dist/commercial-cursor-hosts.js"(e,t,r){"use strict";r.d(t,{H:()=>c,K4:()=>i,Zf:()=>a,ad:()=>l});const n=["cursor.sh","cursor.com","cursorapi.com","cursor.so","cursor-marketplace.com","cursorusercontent.com","anysphere.co"],o=["cursor.blob.core.windows.net"];function s(e){return e.trim().toLowerCase().replace(/\.+$/,"")}const i="CURSOR_ORBIT_BUILD",a="CURSOR_ORBIT_DEPLOYMENT_HOSTS";function c(e){return new Set((e??"").split(",").map(s).filter((e=>""!==e)))}function l(e,t){return function(e){const t=s(e);return o.includes(t)||n.some((e=>t===e||t.endsWith(`.${e}`)))}(e)&&!t.has(s(e))}},"../context/dist/otel.js"(e,t,r){"use strict";r.d(t,{F:()=>E,HF:()=>_,MG:()=>k,Mf:()=>v,OA:()=>y,V5:()=>C,VI:()=>P,fR:()=>g,fU:()=>w,mJ:()=>b,r2:()=>x,xd:()=>R});var n=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js"),o=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/context-api.js"),s=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace-api.js"),i=r("../context/dist/core.js");const a=(0,i.cF)(Symbol("otel.span"),void 0),c=(0,i.cF)(Symbol("otel.root_span"),void 0),l=(0,i.cF)(Symbol("otel.root_start_ms"),void 0),u=(0,i.cF)(Symbol("otel.suppress_child_spans"),!1),d=(0,i.cF)(Symbol("otel.inheritable_span_attributes"),{});function h(e,t){const r=t.get(d);for(const t in r){const n=r[t];"string"!=typeof n&&"number"!=typeof n&&"boolean"!=typeof n||e.setAttribute(t,n)}}function p(e){return e.name||"anonymous-context"}function f(e,t){return!!t&&(e.get(u)||(p(e),!1))}function m(e="context-tracer"){return s.u.getTracer(e)}function g(e,t){const r=m(),n=e.get(a);if(f(e,n))return e;const i=p(e);let u;if(n){const e=s.u.setSpan(o._.active(),n);u=r.startSpan(i,t,e)}else u=r.startSpan(i,t);h(u,e);const d=Date.now();let g=e.with(a,u);return n||(g=g.with(c,u).with(l,d)),g}function w(e){return e.get(a)}function y(e){return e.with(u,!0)}function v(e,t,r){const n=e.get(d),o=w(e);return o&&null!==r&&o.setAttribute(t,r),e.with(d,{...n,[t]:r})}function b(e){try{const t=w(e);if(!t)return;const r=t.spanContext(),n=e.get(u);return{traceId:r.traceId,spanId:r.spanId,traceFlags:n?0:r.traceFlags,traceState:r.traceState?.serialize()}}catch{return}}const S=Symbol.for("anysphere.context.activeOtelSpanAls");function k(e,t){const r=()=>o._.with(s.u.setSpan(o._.active(),e),t),n=function(){const e=globalThis;if("object"!=typeof(t=e)||null===t||!(S in e))return;var t;const r=e[S];return function(e){return"object"==typeof e&&null!==e&&"run"in e&&"function"==typeof e.run&&"getStore"in e&&"function"==typeof e.getStore}(r)?r:void 0}();return void 0===n?r():n.run(e,r)}function _(e,t){try{const r=m(),n=w(e);if(!n)return;const i=s.u.setSpan(o._.active(),n),a=r.startSpan(t,void 0,i);h(a,e);const u=Date.now(),d=e.get(l),p="number"==typeof d?u-d:0,f=`event.${t}`;(e.get(c)??n).setAttribute(f,p),a.setAttribute(f,p),a.end()}catch{}}function C(e,t,r){const c=m(),l={traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags,isRemote:!0},u=s.u.setSpanContext(o._.active(),l),d=t||"child.span",h=c.startSpan(d,{kind:n.v.INTERNAL},u),p=r??(0,i.q6)();return(t?p.withName(t):p).with(a,h)}function E(e,t,r){const n=s.u.wrapSpanContext({traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags,isRemote:!0}),o=r??(0,i.q6)();return(t?o.withName(t):o).with(a,n)}class x{constructor(e,t,r=!0){this.disposed=!1,this.ctx=e,this.span=t,this.shouldEnd=r}[Symbol.dispose](){this.disposed||(this.disposed=!0,this.shouldEnd&&this.span.end())}}function P(e,t){const r=f(e,w(e)),n=g(e,t),o=w(n);return new x(n,o,!r)}function R(e,t,r){const n=w(e);if(!n||f(e,n))return;const o=w(g(e,t));return o.end(r),o}},"../mcp-core/dist/transport/mcp-url-utils.js"(e,t,r){"use strict";r.d(t,{$H:()=>Q,ME:()=>G,_N:()=>X,b6:()=>z,bi:()=>P,eA:()=>j,mD:()=>A,rM:()=>J,vc:()=>L});const n=BigInt(0),o=BigInt(8),s=BigInt(16),i=BigInt(65535);function a(e){const t=e.split(".");if(4!==t.length)return;let r=n;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<>s&i)),t.push(Number(o.value&i))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function l(e){return a(e)??function(e){const t=H(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=c(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<7?void 0:{version:6,value:[...a,...new Array(8-u).fill(0),...l].reduce(((e,t)=>e<=R&&d.clear();const t=l(e);return d.set(e,t),t}(e);return void 0!==r&&r.version===t.version&&r.value>>t.shift===t.shiftedNetwork}case"subdomainOrBase":return e===t.suffix||e.endsWith(`.${t.suffix}`);case"exact":return e===t.value;default:return t}}(H(e),function(e){const t=u.get(e);if(t)return t;u.size>=R&&u.clear();const r=function(e){const t=H(e);if("*"===t)return{kind:"matchAll"};if(t.includes("/")){const e=t.lastIndexOf("/");if(e<=0||e===t.length-1)return{kind:"invalidCidr"};const r=l(t.slice(0,e));if(!r)return{kind:"invalidCidr"};const n=Number(t.slice(e+1)),o=4===r.version?32:128;if(!Number.isInteger(n)||n<0||n>o)return{kind:"invalidCidr"};const s=BigInt(o-n);return{kind:"cidr",version:r.version,shift:s,shiftedNetwork:r.value>>s}}return t.startsWith("*.")?{kind:"subdomainOrBase",suffix:t.slice(2)}:{kind:"exact",value:t}}(e);return u.set(e,r),r}(t))}new Set(["airtable.com","anysphere.co","api.aws","apify.com","asana.com","ashbyhq.com","atlassian.com","atlassian.net","azuredatabricks.net","box.com","buildkite.com","calendly.com","canva.com","clickhouse.cloud","clickup.com","cloudflare.com","composio.dev","context7.com","cursor.com","cursor.sh","cursorapi.com","databricks.com","datadoghq.com","datadoghq.eu","ddog-gov.com","dropbox.com","elevenlabs.io","exa.ai","figma.com","firecrawl.dev","github.com","githubcopilot.com","gitlab.com","google.com","googleapis.com","granola.ai","hex.tech","hubspot.com","huggingface.co","intercom.com","linear.app","monday.com","neon.tech","notion.com","plain.com","posthog.com","prisma.io","railway.com","ramp.com","render.com","salesforce.com","sentry.dev","sentry.io","slack.com","snowflakecomputing.com","spacelift.io","statsig.com","stripe.com","supabase.com","todoist.net","vercel.com","workos.com","x.ai","x.com","zapier.com"]);const p="Blocked by MCP Network Admin Server Controls";function f(e){return/\s/.test(e)}const m="[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?",g=new RegExp(`^(?:${m}\\.)*${m}$`),w=new RegExp(`^\\*\\.(?:${m}\\.)*${m}$`),y="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)",v=new RegExp(`^${y}(?:\\.${y}){3}$`),b=/^[0-9a-f:]+$/,S=new RegExp(`^(?:${y}(?:\\.${y}){3}|[0-9a-f:]+)\\/\\d{1,3}$`);function k(e){const t=H(e);return t.length>0&&t.length<=253&&g.test(t)}function _(e){const t=H(e);return v.test(t)||function(e){const t=H(e);if(!b.test(t))return!1;try{return new URL(`https://[${t}]`),!0}catch{return!1}}(t)}function C(e,t){return""===t||"http:"===e&&"80"===t||"https:"===e&&"443"===t}function E(e){const t=new URL(e.pathname||"/",e.origin);if(t.search=e.search,t.pathname.endsWith("/")&&t.pathname.length>1&&(t.pathname=t.pathname.slice(0,-1)),"/"===t.pathname&&""===t.search){const t=e.protocol.toLowerCase();let r=`${t}//${e.hostname.toLowerCase()}`;return C(t,e.port)||(r+=`:${e.port}`),r}const r=e.protocol.toLowerCase();let n=`${r}//${e.hostname.toLowerCase()}`;return C(r,e.port)||(n+=`:${e.port}`),`${n}${t.pathname}${t.search}`}function x(e){if(e.includes("://"))return function(e){try{const t=new URL(e);return("http:"===t.protocol||"https:"===t.protocol)&&!(0===t.hostname.length||t.username.length>0||t.password.length>0)&&""===t.hash&&function(e){const t=e.toLowerCase();return!t.includes("*")&&(k(t)||_(t))}(t.hostname)}catch{return!1}}(e);const t=H(e);return"*"===t||!!w.test(t)||(t.includes("/")?function(e){const t=H(e);if(!S.test(t))return!1;const[r]=t.split("/");return void 0!==r&&h(r,t)}(t):k(t)||_(t))}function P(e){if(I.has(e))return I.get(e);I.size>=R&&I.clear();const t=function(e){const t=e.trim();if(0===t.length)return;const r=t.lastIndexOf("/");if(!t.includes("://")&&r>0&&/^\d+$/.test(t.slice(r+1).trim())){const e=`${H(t.slice(0,r))}/${t.slice(r+1).trim()}`;return x(e)?e:void 0}if(f(t)||t.includes("#")||t.includes("@"))return;const n=t.indexOf("://");if(-1!==n){const e=t.slice(0,n).toLowerCase();if("http"!==e&&"https"!==e)return;try{const e=new URL(t);if(0===e.hostname.length||e.username.length>0||e.password.length>0)return;const r="/"!==e.pathname&&""!==e.pathname,n=""!==e.search;if(e.hostname.includes("*"))return;if(r||n){const t=E(e);if(!x(t))return;return t}{const t=E(e);if(!x(t))return;return t}}catch{return}}else if(t.includes("/"))return;const o=t.trim().toLowerCase(),s=function(e){const t=e.indexOf(":");if(-1===t)return e;const r=e.slice(t+1);return/^\d+$/.test(r)?e.slice(0,t):e}(o);return 0===s.length||!x(s)||s!==o&&"*"===s?void 0:s}(e);return I.set(e,t),t}const R=2048,I=new Map,T=new Map;function A(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}function $(e){return e.endsWith("/")&&e.length>1?e.slice(0,-1):e}function M(e,t){return function(e,t,r){const n=D(t);if(!n)return!1;let o;try{o=new URL(e)}catch{return!1}return""===o.username&&""===o.password&&""===n.username&&""===n.password&&o.protocol===n.protocol&&o.port===n.port&&(s=o.hostname,i=n.hostname,!s.includes("*")&&H(s)===H(i)&&(A(a=o.pathname,c=n.pathname)||A($(a),$(c)))&&function(e,t,r){return""===e?r.allowRequestQueryWhenPatternOmitsQuery||""===t:A(e,t)}(o.search,n.search,r));var s,i,a,c}(e,t,{allowRequestQueryWhenPatternOmitsQuery:!0})}function D(e){const t=e.trim();if(0===t.length||f(t))return;if(function(e){const t=e.indexOf("[");return-1!==t&&-1===e.indexOf("]",t)}(t))return;const r=q(t);if(r&&("http:"===r.protocol||"https:"===r.protocol)&&""===r.username&&""===r.password&&0!==r.hostname.length&&(!H(r.hostname).includes(":")||t.includes("["))){if(t.includes("[")){const e=t.indexOf("["),n=t.indexOf("]",e);if(-1===n)return;const o=t.slice(e+1,n);if(H(r.hostname)!==H(o))return}return r}}function O(e,t){const r=e.toLowerCase(),n=t.toLowerCase();if("*"===r)return!0;if(void 0!==a(n))return A(r,n);if(!r.includes("*"))return r===n;const o=r.slice(1);if(r.startsWith("*.")&&!o.includes("*"))return n.endsWith(o)&&n.length>o.length;const s=r.split("."),i=n.split(".");return s.length===i.length&&!s[s.length-1]?.includes("*")&&A(r,n)}const F=/^([^/?#]+\/\/[^/?#]*):\*(?=[/?#]|$)/,N=/^[^/?#]+\/\/[^/?#]*\*$/;function L(e,t){if("*"===e||e===t)return!0;let r;T.has(t)?r=T.get(t):(T.size>=R&&T.clear(),r=q(t),T.set(t,r));const n=function(e){if(void 0===e||!/[^.]\.$/.test(e.hostname))return;const t=new URL(e.href);return t.hostname=e.hostname.slice(0,-1),t.href}(r);if(void 0!==n&&L(e,n))return!0;const o=function(e){const t=e.trim(),r=t.indexOf("://");if(-1===r)return/^[^/?#]*[^.*/?#]\.$/.test(t)?t.slice(0,-1):void 0;if(!t.includes("*"))return;const n=r+3,o=n+(t.slice(n).split(/[/?#]/,1)[0]??"").replace(/:(?:\d+|\*)$/,"").length;return/[^.*]\.$/.test(t.slice(n,o))?`${t.slice(0,o-1)}${t.slice(o)}`:void 0}(e);return!(void 0===o||!L(o,t))||!!r&&(e.includes("://")?function(e,t){const r=N.test(e),n=r||F.test(e),o=e.indexOf("://"),s=e.slice(0,o).toLowerCase(),i=t.protocol.slice(0,-1),a=q((s.includes("*")&&A(s,i)?`${i}${e.slice(o)}`:e).replace(F,"$1"));if(void 0===a||""!==a.username||""!==a.password||""!==t.username||""!==t.password||a.protocol!==t.protocol||!n&&a.port!==t.port)return!1;const c=a.hostname.replace(/%2a/gi,"*");return(O(c,t.hostname)||r&&O(c.replace(/\*$/,""),t.hostname))&&(r||A(`${a.pathname}${a.search}`,`${t.pathname}${t.search}`))}(e,r):h(r.hostname,e))}function j(e,t){if(A(e,t)||L(e,t))return!0;const r=function(e){const t=e.trim();if(t.includes("*")||!t.includes("://"))return;const r=q(t);return void 0!==r&&""===r.search&&""===r.hash?W(r):void 0}(e);if(void 0===r)return!1;const n=q(t.trim());return void 0!==n&&W(n)===r}const U=/%[0-9a-f]{2}/gi,B=/^[A-Za-z0-9\-._~]$/;function W(e){const t="http:"===e.protocol||"https:"===e.protocol?"http(s):":e.protocol,r=e.hostname.endsWith(".")?e.hostname.slice(0,-1):e.hostname,n=""===e.port?"":`:${e.port}`,o=e.pathname.replace(U,(e=>{const t=String.fromCharCode(Number.parseInt(e.slice(1),16));return B.test(t)?t:e.toUpperCase()})).replace(/\/{2,}/g,"/");return`${t}//${r}${n}${o.endsWith("/")?o.slice(0,-1):o}`}function H(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function q(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch{return}}function z(e){return(e.mcpNetworkAllowlist??[]).flatMap((e=>{const t=P(e);return void 0===t?[]:[t]}))}function G(e,t){if(!0!==t.enabled)return{allowed:!0};if("no_sandbox"===t.mcpNetworkMode)return{allowed:!0};if(!D(e))return{allowed:!1,message:t.blockMessage??p};const r=z(t);return r.length>0&&r.some((t=>function(e,t){const r=D(t);if(!r)return!1;if(!e.includes("://"))return h(H(r.hostname),e);if(M(e,t))return!0;const n=function(e){try{const t=new URL(e);if(""!==t.username||""!==t.password||"/"!==t.pathname||""!==t.search||""!==t.hash)return;return`${t.protocol}//${t.host}/*`}catch{return}}(e);return void 0!==n&&M(n,t)}(t,e)))?{allowed:!0}:{allowed:!1,message:t.blockMessage??p}}function V(e){const t=e?.trim();return t&&t.length>0?t:void 0}function K(e){return V(e)?.toLowerCase()}function J(e,t){const r=K(e.builtinServer),n=K(t.builtinServer);if(void 0!==r||void 0!==n)return void 0!==r&&r===n;const o=V(e.command),s=V(e.serverUrl);if(void 0===o&&void 0===s)return!1;const i=void 0===o||void 0!==t.command&&A(o,t.command),a=void 0===s||void 0!==t.url&&L(s,t.url);return i&&a}function Z(e,t,r){return void 0!==r?.command&&void 0===r.url&&void 0===t&&!0===e?.allowUserOverrideMcpServers}function X({allowedMcpConfiguration:e,server:t,localAgentNetworkAllowlist:r,blockMessage:n,unmatchedServerAllowlist:o,aggregateManagedServerNetworkAllowlists:s=!0,stdioPlatform:i,unsandboxUserExtensionStdio:a}){const c=e?.allowedMcpServers,l=function(e){if(!0!==e?.allowUserOverrideMcpServers)return;const t=(e.deniedMcpServers??[]).flatMap((e=>{const t=V(e.serverUrl),r=void 0===t?void 0:function(e){const t=e.trim();if(0===t.length)return;if(function(e){const t=e.indexOf("://");if(-1===t)return!1;const r=e.slice(t+3),n=r.indexOf("/");return-1===n?r.includes("?"):r.slice(n).includes("*")}(t)){const e=t.indexOf("://");if(-1!==e){const r=t.slice(e+3).split(/[/?#]/,1)[0];if(r?.includes("*")){const e=P(r.replace(/:\d+$/,""));if(void 0!==e)return e}}return}if(!t.includes("://")&&t.includes("*")&&"*"!==t&&!t.startsWith("*."))return;const r=P(e);if(void 0!==r)return r;const n=e.indexOf("://");if(-1===n)return;const o=e.slice(0,n).toLowerCase();if("http"!==o&&"https"!==o)return;const s=e.slice(n+3).split(/[/?#]/,1)[0];if(void 0===s||s.includes("@"))return;const i=P(s.replace(/:\d+$/,""));if(void 0!==i)return i;try{return P(new URL(e).hostname)}catch{return}}(t);return void 0===r?[]:[r]}));return t.length>0?t:void 0}(e),u=void 0===t?void 0:function(e,t){return e?.find((e=>J(e,t)))}(c,t),d=Z(e,u,t),h=function({allowedMcpConfiguration:e,matchedServer:t,server:r}){return void 0===r?(e?.allowedMcpServers?.length??0)>0:void 0!==t||Z(e,t,r)}({allowedMcpConfiguration:e,matchedServer:u,server:t})||void 0===t&&void 0!==l,p=void 0===t?s?c?.flatMap((e=>e.networkAllowlist??[])):void 0:d?[]:function(e,t,r){return void 0===e?r:[...e.networkAllowlist??[],...void 0!==V(e.serverUrl)&&void 0!==t.url?[t.url]:[]]}(u,t,o),f=d&&"win32"===i&&!0===a;let m;m=void 0===t?void 0:f?"no_sandbox":d?"allow_all":function(e,t){var r;if(void 0!==V(e?.command)&&void 0!==t.command&&void 0===t.url)return r=e?.networkMode,("allow_all"===r||"allowlist"===r||"deny_all"===r||"no_sandbox"===r?r:void 0)??"no_sandbox"}(u,t);const g=void 0===t||d?l:void 0;return{enabled:h,mcpNetworkAllowlist:p,...void 0!==m?{mcpNetworkMode:m}:{},...void 0!==g?{mcpNetworkDenylist:g}:{},...void 0!==r?{localAgentNetworkAllowlist:r}:{},...void 0!==n?{blockMessage:n}:{},...f?{win32UserExtensionUnsandbox:!0}:{}}}function Q(e){if(!0===e?.enabled&&"no_sandbox"!==e.mcpNetworkMode)return e}},"../shell-exec/dist/api/index.js"(e,t,r){"use strict";r.d(t,{BM:()=>Oo,Ls:()=>f,SandboxUnsupportedError:()=>_r,J:()=>x,St:()=>Er,Fn:()=>Do,Qw:()=>a,ue:()=>s,r5:()=>Ie,getLastSandboxFailureReason:()=>kr,oG:()=>no,Ko:()=>T,CG:()=>ht,W1:()=>Z,G6:()=>Mo,dA:()=>He,_B:()=>Qe,OK:()=>Ze,$b:()=>Xe,K3:()=>Rr,tv:()=>st,wG:()=>vt,fZ:()=>bt,s9:()=>mt,XX:()=>yt,T6:()=>et,Po:()=>Ye,$6:()=>nt,l7:()=>it,xS:()=>E,resolveSandboxPolicyForWorkspace:()=>Ct,fB:()=>Dt,spawnInSandbox:()=>xr,Xw:()=>I});var n=r("node:child_process");new Set;const o=["SSH_CLIENT","SSH2_CLIENT"];function s(e){const t=e||process.env,{ELECTRON_RUN_AS_NODE:r,...n}=t;for(const e of Object.keys(n))e.startsWith("AGENT_HOST_DAEMON_")&&delete n[e];for(const e of o)delete n[e];return n}const i="NODE_COMPILE_CACHE";function a(e){const{[i]:t,...r}=e;return r.NODE_DISABLE_COMPILE_CACHE="1",r}const c=["SSH_AUTH_SOCK","DBUS_SESSION_BUS_ADDRESS","XDG_RUNTIME_DIR","WAYLAND_DISPLAY"];function l(e){const t={...e};for(const e of c)delete t[e];return t}const u=[["core.quotePath","false"]];function d(e){const t=function(e){const t=e.GIT_CONFIG_COUNT;if(void 0===t||""===t)return 0;const r=Number.parseInt(t,10);return Number.isFinite(r)&&r>=0?r:0}(e),r=new Set;for(let n=0;no.endsWith(e)))){const n=S(e,r);if(g.existsSync(n))return k(n,t,r)}for(const o of n){const n=S(`${e}${o}`,r);if(g.existsSync(n))return k(n,t,r)}}return e.match(/\.ps1$/i)?{cmd:m.join(process.env.SYSTEMROOT,"System32","WindowsPowerShell","v1.0","PowerShell.exe"),args:["-ExecutionPolicy","Unrestricted","-NoLogo","-NonInteractive","-File",e].concat(t)}:e.match(/\.(bat|cmd)$/i)?{cmd:m.join(process.env.SYSTEMROOT,"System32","cmd.exe"),args:["/C",e,...t]}:e.match(/\.(js)$/i)?{cmd:process.execPath,args:[e].concat(t)}:{cmd:e,args:t}}let _;const C=["/usr/local/bin","/usr/bin","/bin"];function E(){const e=k("rg",[]).cmd;return"rg"!==e?e:void 0}function x(e){if(!e)throw new Error("configureRipgrepPath: path must not be empty");_=e}function P(e){const t=Object.keys(e).filter((e=>"path"===e.toLowerCase()));if(0!==t.length)return"win32"===process.platform?t.find((e=>"Path"===e))??t[0]:t.find((e=>"PATH"===e))??t[0]}function R(e,t){const r=(0,m.dirname)(t);if(!r||"."===r)return e;let n=function(e){const t=P(e);return void 0!==t?e[t]??"":""}(e).split(m.delimiter).filter(Boolean);return 0===n.length&&"win32"!==process.platform&&(n=C),function(e,t){const r=P(e)??("win32"===process.platform?"Path":"PATH"),n={...e};for(const e of Object.keys(n))e!==r&&"path"===e.toLowerCase()&&delete n[e];return n[r]=t,n}(e,[r,...n.filter((e=>e!==r))].join(m.delimiter))}function I(e){return _&&(0,m.isAbsolute)(_)?{...R(e,_),CURSOR_RIPGREP_PATH:_}:e}function T(){if(!_)throw new Error("Ripgrep path not configured. Call configureRipgrepPath() at startup.");return _}const A="win32"===process.platform;function $(e){return!A&&!!e?.SUDO_ASKPASS}function M(e){return $(e)?"alias sudo='sudo -A'; ":""}function D(e){const t=[];let r=0;for(;r=e.length||/\s/.test(e[n])){let o=n;for(;ovoid 0!==t&&e.toUpperCase()===r))}const F=["PYTHONIOENCODING","PYTHONUTF8","PYTHONLEGACYWINDOWSSTDIO"];function N(e){F.some((t=>O(e,t)))||(e.PYTHONIOENCODING="utf-8:surrogateescape")}function L(e){O(e,"WSL_UTF8")||(e.WSL_UTF8="1")}const j="-Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8 -Dstdout.encoding=UTF-8 -Dstderr.encoding=UTF-8",U=["sun.stdout.encoding","sun.stderr.encoding","stdout.encoding","stderr.encoding"],B=`case " \${MAVEN_OPTS-} \${JAVA_TOOL_OPTIONS-} \${JDK_JAVA_OPTIONS-} \${_JAVA_OPTIONS-} " in ${U.map((e=>`*[[:space:]]-D${e}=*`)).join("|")}) ;; *) builtin export MAVEN_OPTS="\${MAVEN_OPTS:+$MAVEN_OPTS }${j}";; esac; `,W=`if ("$env:MAVEN_OPTS $env:JAVA_TOOL_OPTIONS $env:JDK_JAVA_OPTIONS \${env:_JAVA_OPTIONS}" -cnotmatch '(^|\\s)-D(${U.map((e=>e.replace(/\./g,"\\."))).join("|")})=') {\n if ($env:MAVEN_OPTS) { $env:MAVEN_OPTS = "$env:MAVEN_OPTS ${j}" } else { $env:MAVEN_OPTS = '${j}' }\n}`;var H=r("node:crypto"),q=r("node:os"),z=r("../utils/dist/workspace-paths.js"),G=r("../utils/dist/test-resets.js");let V;function K(e,t){const r=(0,g.lstatSync)(e);return r.isDirectory()&&r.uid===t&&!(18&r.mode)}function J(e){try{(0,g.mkdirSync)(e,{mode:448})}catch(e){if(!(e instanceof Error&&"code"in e&&"EEXIST"===e.code))throw e}}function Z(e){return X(e,{create:!1})}function X(e,{create:t}){const r=process.getuid?.();if(void 0===r)return;const n=(0,m.join)((0,q.tmpdir)(),`cursor-sandbox-${(0,z.r_)((0,m.resolve)(e))}`);try{for(const e of[n,(0,m.join)(n,"tmp")])if(t&&J(e),!K(e,r))return;return n}catch{return}}(0,G.J)((function(){V=void 0}));const Q='builtin eval "${__CURSOR_SANDBOX_TEMP_RESTORE:-}" 2>/dev/null; ',Y=["TMPDIR","TMP","TEMP","TMPPREFIX","NODE_COMPILE_CACHE","NODE_DISABLE_COMPILE_CACHE"],ee="builtin export NODE_DISABLE_COMPILE_CACHE=1; builtin unset NODE_COMPILE_CACHE; ";function te(e){const t=(0,m.join)(e,"tmp");return{TMPDIR:t,TMP:t,TEMP:t,TMPPREFIX:(0,m.join)(t,"sh-")}}function re(e=(0,m.join)((0,q.tmpdir)(),"cursor-sandbox-cache",function(){return V||(V=(0,H.randomBytes)(16).toString("hex")),V}())){return{NPM_CONFIG_CACHE:(0,m.join)(e,"npm"),PNPM_STORE_PATH:(0,m.join)(e,"pnpm-store"),GOCACHE:(0,m.join)(e,"go-build"),GOMODCACHE:(0,m.join)(e,"go-mod"),CARGO_TARGET_DIR:(0,m.join)(e,"cargo-target"),PIP_CACHE_DIR:(0,m.join)(e,"pip"),UV_CACHE_DIR:(0,m.join)(e,"uv"),BUN_INSTALL_CACHE_DIR:(0,m.join)(e,"bun"),YARN_CACHE_FOLDER:(0,m.join)(e,"yarn"),npm_config_devdir:(0,m.join)(e,"node-gyp"),PLAYWRIGHT_BROWSERS_PATH:(0,m.join)(e,"playwright"),PUPPETEER_CACHE_DIR:(0,m.join)(e,"puppeteer"),TURBO_CACHE_DIR:(0,m.join)(e,"turbo"),GRADLE_USER_HOME:(0,m.join)(e,"gradle"),CONDA_PKGS_DIRS:(0,m.join)(e,"conda"),POETRY_CACHE_DIR:(0,m.join)(e,"poetry"),GEM_SPEC_CACHE:(0,m.join)(e,"gem-specs"),COMPOSER_HOME:(0,m.join)(e,"composer"),HOMEBREW_CACHE:(0,m.join)(e,"homebrew"),CYPRESS_CACHE_FOLDER:(0,m.join)(e,"cypress"),NX_CACHE_DIRECTORY:(0,m.join)(e,"nx"),NUGET_PACKAGES:(0,m.join)(e,"nuget"),CCACHE_DIR:(0,m.join)(e,"ccache"),CP_HOME_DIR:(0,m.join)(e,"cocoapods")}}var ne=r("node:fs/promises"),oe=r("../utils/dist/safe-spawn-cwd.js"),se=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js");function ie(){const e=process.env.CURSOR_SANDBOX_POLICY_DIR?.trim();return e?m.resolve(e):m.resolve(m.join(q.homedir(),".cursor","sandbox-policies"))}let ae=0;function ce(){const e=ie();g.mkdirSync(e,{recursive:!0,mode:448});try{g.chmodSync(e,448)}catch{}const t=Date.now();return t-ae>=9e5&&(ae=t,function(e){let t;try{t=g.readdirSync(e)}catch{return}const r=Date.now();for(const n of t){if(!n.startsWith("sandbox-policy-"))continue;const t=m.join(e,n);try{const e=g.statSync(t);if(!e.isFile())continue;r-e.mtimeMs>36e5&&g.unlinkSync(t)}catch{}}}(e)),e}function le(e){const t=ce(),r=H.randomBytes(8).toString("hex"),n=m.join(t,`sandbox-policy-${r}`);return g.writeFileSync(n,e,{encoding:"utf-8",mode:384}),n}const ue="/tmp/node-compile-cache",de="cursor-compile-cache",he=Symbol.for("cursor.startupNodeCompileCache"),pe=process.platform;function fe(e=q.tmpdir(),t=process.platform){if("win32"===t||0===e.length)return[];const r=m.posix.join(e,"node-compile-cache");return r===ue?[]:[r]}function me(e=q.tmpdir(),t=process.env,r=process.platform){if("win32"===r)return[];const n=new Set(fe(e,r));for(const e of["TMPDIR","TMP","TEMP"]){const o=t[e];if(void 0!==o&&m.posix.isAbsolute(o))for(const e of fe(m.posix.resolve(o),r))n.add(e)}return[...n]}function ge(e=process.env,t=q.homedir(),r=process.platform){if("darwin"===r)return t.length>0?m.posix.join(t,"Library/Caches",de):void 0;if("linux"!==r)return;const n=e.XDG_CACHE_HOME;return void 0!==n&&m.posix.isAbsolute(n)?m.posix.join(n,de):t.length>0?m.posix.join(t,".cache",de):void 0}function we(e=process.env,t=process.platform){if("win32"===t)return;const r=Object.getOwnPropertyDescriptor(globalThis,he)?.value,n="string"==typeof r?r:e.NODE_COMPILE_CACHE;if(void 0===n||!m.posix.isAbsolute(n))return;const o=m.posix.resolve(n);return"/"===o?void 0:o}function ye(e=q.homedir(),t=q.tmpdir(),r=process.env,n=process.platform){if("win32"===n)return[];const o=new Set([ue]);e.length>0&&(o.add(m.posix.join(e,".cache",de)),o.add(m.posix.join(e,"Library/Caches",de)));const s=[];for(const i of[...me(t,r,n),ge(r,e,n),we(r,n)])void 0===i||o.has(i)||(o.add(i),s.push(i));return s}function ve(e=q.homedir(),t=q.tmpdir(),r=process.platform,n=process.env){if("win32"===r)return[];const o=[ue,...me(t,n,r)],s=ge(n,e,r);return void 0===s||o.includes(s)||o.push(s),o}function be(e,t){return e.isSymbolicLink()?"a link, not followed":e.isDirectory()?e.uid!==t?`owned by uid ${e.uid}`:void 0:"not a folder"}function Se(e){return"object"!=typeof e||null===e?{}:Object.fromEntries(Object.entries(e).filter((e=>"string"==typeof e[1])))}function ke(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:"error"}const _e=[".local/bin",".local/share/mise",".local/share/pnpm",".nvm",".volta",".asdf",".pyenv",".rbenv",".rustup",".cargo/bin",".cargo/registry",".cargo/git"],Ce=["bin","sbin","lib","opt","Cellar","share","Frameworks","etc/gitconfig","etc/openssl@3/cert.pem","etc/openssl@3/openssl.cnf","etc/ca-certificates"],Ee=(e,t)=>t.flatMap((t=>Ce.map((r=>({platform:e,scope:"global",path:`${t}/${r}`}))))),xe={linux:[".cache/node",".cache/yarn"],darwin:[".cache/node","Library/Caches/Yarn"]},Pe=e=>[..._e,...xe[e]].map((t=>({platform:e,scope:"home-dir",path:t}))),Re=[{platform:"linux",scope:"global",path:"/bin"},{platform:"linux",scope:"global",path:"/sbin"},{platform:"linux",scope:"global",path:"/usr/bin"},{platform:"linux",scope:"global",path:"/usr/sbin"},{platform:"linux",scope:"global",path:"/lib"},{platform:"linux",scope:"global",path:"/lib64"},{platform:"linux",scope:"global",path:"/usr/lib"},{platform:"linux",scope:"global",path:"/usr/lib64"},{platform:"linux",scope:"global",path:"/usr/libexec"},{platform:"linux",scope:"global",path:"/usr/share"},{platform:"linux",scope:"global",path:"/etc/ld.so.cache"},{platform:"linux",scope:"global",path:"/etc/ld.so.conf"},{platform:"linux",scope:"global",path:"/etc/ld.so.conf.d"},{platform:"linux",scope:"global",path:"/etc/ssl/certs"},{platform:"linux",scope:"global",path:"/etc/ssl/openssl.cnf"},{platform:"linux",scope:"global",path:"/etc/ssl/cert.pem"},{platform:"linux",scope:"global",path:"/etc/ssl/ca-bundle.pem"},{platform:"linux",scope:"global",path:"/etc/ssl/certs/ca-certificates.crt"},{platform:"linux",scope:"global",path:"/etc/pki/tls/certs"},{platform:"linux",scope:"global",path:"/etc/pki/tls/openssl.cnf"},{platform:"linux",scope:"global",path:"/etc/pki/ca-trust/extracted"},{platform:"linux",scope:"global",path:"/etc/resolv.conf"},{platform:"linux",scope:"global",path:"/etc/hosts"},{platform:"linux",scope:"global",path:"/etc/nsswitch.conf"},{platform:"linux",scope:"global",path:"/etc/gai.conf"},{platform:"linux",scope:"global",path:"/etc/alternatives"},{platform:"linux",scope:"global",path:"/etc/mime.types"},{platform:"linux",scope:"global",path:"/etc/profile"},{platform:"linux",scope:"global",path:"/etc/bash.bashrc"},{platform:"linux",scope:"global",path:"/etc/zsh/zshenv"},{platform:"linux",scope:"global",path:"/etc/zsh/zprofile"},{platform:"linux",scope:"global",path:"/etc/zsh/zshrc"},{platform:"linux",scope:"global",path:"/etc/zsh/zlogin"},{platform:"linux",scope:"global",path:"/etc/gitconfig"},{platform:"linux",scope:"home",path:".bashrc"},{platform:"linux",scope:"home",path:".bash_profile"},{platform:"linux",scope:"home",path:".profile"},{platform:"linux",scope:"home",path:".zshenv"},{platform:"linux",scope:"home",path:".zprofile"},{platform:"linux",scope:"home",path:".zshrc"},{platform:"linux",scope:"home",path:".zlogin"},{platform:"linux",scope:"home",path:".gitconfig"},{platform:"linux",scope:"home",path:".ssh/known_hosts"},{platform:"linux",scope:"home",path:".config/mise/config.toml"},{platform:"linux",scope:"home-dir",path:".cache/dotslash"},...Pe("linux"),...Ee("linux",["/usr/local","/home/linuxbrew/.linuxbrew"]),{platform:"linux",scope:"global",path:"/usr/local/go"},{platform:"linux",scope:"global",path:"/nix/store"},{platform:"linux",scope:"global",path:"/nix/var/nix/profiles"},{platform:"linux",scope:"bundled",path:"ripgrep"},{platform:"darwin",scope:"global",path:"/bin"},{platform:"darwin",scope:"global",path:"/usr/bin"},{platform:"darwin",scope:"global",path:"/usr/lib"},{platform:"darwin",scope:"global",path:"/usr/libexec"},{platform:"darwin",scope:"global",path:"/usr/share"},{platform:"darwin",scope:"global",path:"/System/Library"},{platform:"darwin",scope:"global",path:"/System/Cryptexes"},{platform:"darwin",scope:"global",path:"/Library/Apple"},{platform:"darwin",scope:"global",path:"/Library/Developer/CommandLineTools"},{platform:"darwin",scope:"global",path:"/Applications/Xcode.app"},{platform:"darwin",scope:"global",path:"/Library/Preferences/com.apple.dt.Xcode.plist"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/cert.pem"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/certs"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/openssl.cnf"},{platform:"darwin",scope:"global",path:"/private/etc/hosts"},{platform:"darwin",scope:"global",path:"/private/etc/resolv.conf"},{platform:"darwin",scope:"global",path:"/private/etc/apache2/mime.types"},{platform:"darwin",scope:"global",path:"/etc/profile"},{platform:"darwin",scope:"global",path:"/etc/bashrc"},{platform:"darwin",scope:"global",path:"/etc/zshenv"},{platform:"darwin",scope:"global",path:"/etc/zprofile"},{platform:"darwin",scope:"global",path:"/etc/zshrc"},{platform:"darwin",scope:"global",path:"/etc/zlogin"},{platform:"darwin",scope:"global",path:"/etc/gitconfig"},{platform:"darwin",scope:"home",path:".bashrc"},{platform:"darwin",scope:"home",path:".bash_profile"},{platform:"darwin",scope:"home",path:".profile"},{platform:"darwin",scope:"home",path:".zshenv"},{platform:"darwin",scope:"home",path:".zprofile"},{platform:"darwin",scope:"home",path:".zshrc"},{platform:"darwin",scope:"home",path:".zlogin"},{platform:"darwin",scope:"home",path:".gitconfig"},{platform:"darwin",scope:"home",path:".ssh/known_hosts"},{platform:"darwin",scope:"home",path:"Library/Preferences/.GlobalPreferences.plist"},{platform:"darwin",scope:"home",path:".config/mise/config.toml"},{platform:"darwin",scope:"home-dir",path:"Library/Python"},{platform:"darwin",scope:"home-dir",path:"Library/Caches/dotslash"},...Pe("darwin"),...Ee("darwin",["/opt/homebrew","/usr/local"]),{platform:"darwin",scope:"global",path:"/nix/store"},{platform:"darwin",scope:"global",path:"/nix/var/nix/profiles"},{platform:"darwin",scope:"bundled",path:"ripgrep"},{platform:"darwin",scope:"global",path:"/dev/null"},{platform:"darwin",scope:"global",path:"/dev/zero"},{platform:"darwin",scope:"global",path:"/dev/random"},{platform:"darwin",scope:"global",path:"/dev/urandom"}];function Ie(e=process.platform,t=q.homedir(),r={}){const n=[];for(const o of Re){if(o.platform!==e)continue;if("global"===o.scope){n.push(o.path);continue}const s="bundled"===o.scope?r[o.path]:(0,m.join)(t,o.path);if(s)try{let e;switch(o.scope){case"home":e=(0,g.lstatSync)(s).isFile();break;case"home-dir":e=(0,g.lstatSync)(s).isDirectory();break;case"bundled":e=(0,g.statSync)(s).isFile()}e&&n.push(s)}catch{}}return n}const Te=[{type:"workspace",pattern:"**/.cursor/*.json"},{type:"workspace",pattern:"**/.cursor/**/*.json"},{type:"workspace",pattern:"**/.cursor/.workspace-trusted"},{type:"workspace",pattern:"!**/.cursor/rules"},{type:"workspace",pattern:"!**/.cursor/rules/**"},{type:"workspace",pattern:"!**/.cursor/commands"},{type:"workspace",pattern:"!**/.cursor/commands/**"},{type:"workspace",pattern:"!**/.cursor/worktrees"},{type:"workspace",pattern:"!**/.cursor/worktrees/**"},{type:"workspace",pattern:"!**/.cursor/skills"},{type:"workspace",pattern:"!**/.cursor/skills/**"},{type:"workspace",pattern:"!**/.cursor/agents"},{type:"workspace",pattern:"!**/.cursor/agents/**"},{type:"workspace",pattern:"**/.claude/*.json"},{type:"workspace",pattern:"**/.claude/**/*.json"},{type:"workspace",pattern:"**/.vscode/**"},{type:"workspace",pattern:"**/.idea/**"},{type:"workspace",pattern:"**/.venv/"},{type:"workspace",pattern:"**/venv/"},{type:"workspace",pattern:"**/*.code-workspace"},{type:"workspace",pattern:"**/.cursorignore"},{type:"workspace",pattern:"**/.workspace-trusted"},{type:"workspace",pattern:"**/.cursor/**/cli.json"},{type:"workspace",pattern:"**/.cursor/**/cli-config.json"},{type:"workspace",pattern:"**/.cursor/**/mcp.json"},{type:"workspace",pattern:"**/.cursor/**/mcp-approvals.json"},{type:"workspace",pattern:"**/.cursor/**/permissions.json"},{type:"git",pattern:"**/.git/hooks/**"},{type:"git",pattern:"**/.git/config"},{type:"git",pattern:"**/.git/config.worktree"},{type:"git",pattern:"**/.git/info/attributes"},{type:"git",pattern:"**/.git/commondir"},{type:"git",pattern:"**/.git/worktrees/*/commondir"},{type:"git",pattern:"**/.git/worktrees/*/gitdir"},{type:"worktree",pattern:".git"},{type:"absolute",pattern:"/etc/ssl/cert.pem"},{type:"absolute",pattern:"/etc/ssl/ca-bundle.pem"},{type:"absolute",pattern:"/private/etc/ssl/cert.pem"},{type:"absolute",pattern:"/etc/ssl/certs/ca-certificates.crt"},{type:"absolute",pattern:"/etc/pki/tls/certs/ca-bundle.crt"},{type:"absolute",pattern:"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem"},{type:"home",pattern:".cursor/sandbox-policies"},{type:"absolute",pattern:"/tmp/node-compile-cache"},{type:"home",pattern:".cache/cursor-compile-cache"},{type:"home",pattern:"Library/Caches/cursor-compile-cache"}];function Ae(e){const t=Te.filter((e=>"workspace"===e.type)).map((e=>e.pattern));return{[e]:t}}function $e(e){const t=Te.filter((e=>"git"===e.type)).map((e=>e.pattern));return{[e]:t}}function Me(e){const t=Te.filter((e=>"worktree"===e.type)).map((e=>e.pattern));return{[e]:t}}Te.filter((e=>"git"===e.type)).map((e=>e.pattern)),Te.filter((e=>"workspace"===e.type&&e.pattern.startsWith("!")&&!e.pattern.endsWith("/**"))).map((e=>e.pattern.replace(/^!(\*\*\/)?/,"")));const De=[];let Oe=null,Fe=null;function Ne(e){if(!(e instanceof Error&&"code"in e&&"string"==typeof e.code)||e.code.startsWith("ERR_"))throw e}async function Le(e,t=""){const r=await(0,ne.lstat)(e).catch(Ne);if(void 0===r||!r.isFile()||r.size>4096)return;const n=await(0,ne.readFile)(e,"utf8").catch(Ne),o=n?.split("\n",1)[0]?.replace(/\r$/,"");if(void 0===o||!o.startsWith(t))return;const s=o.slice(t.length);return s.length>0&&!s.includes("\0")?s:void 0}async function je(e){if(!(0,oe.$f)(e))return(0,ne.realpath)(e).catch(Ne)}async function Ue(e){const t=await Le((0,m.join)(e,".git"),"gitdir: ");if(void 0===t)return;const r=await je((0,m.resolve)(e,t));if(void 0===r)return;const n=await Le((0,m.join)(r,"commondir")),o=void 0===n?r:await je((0,m.resolve)(r,n));return void 0===o?void 0:{gitDir:r,commonDirLink:n,commonDir:o}}async function Be(e){const t=await Ue(e);if(void 0===t||void 0===t.commonDirLink||"worktrees"!==(0,m.basename)((0,m.dirname)(t.gitDir)))return;const r=(0,m.dirname)((0,m.dirname)(t.gitDir));if(".git"!==(0,m.basename)(r)||(ze?t.commonDir.toLowerCase()!==r.toLowerCase():t.commonDir!==r))return;const n=await Le((0,m.join)(t.gitDir,"gitdir"));if(void 0===n)return;const o=(0,m.join)(e,".git"),[s,i]=await Promise.all([je((0,m.resolve)(t.gitDir,n)),je(o)]);return void 0!==s&&void 0!==i&&(ze?s.toLowerCase()===i.toLowerCase():s===i)?r:void 0}let We=null;function He(e){return function(){const e=q.homedir();if(null===We){const t=[];for(const r of Te)switch(r.type){case"absolute":t.push(r.pattern);break;case"home":e.length>0&&t.push((0,m.join)(e,r.pattern))}We=t}return[...We,...ye(e)]}().some((t=>{if(Ke(e,t))return!0;const r=function(e){let t;try{t=g.realpathSync.native((0,m.dirname)(e))}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;return"ENOENT"===t||"ENOTDIR"===t?void 0:qe}const r=(0,m.join)(t,(0,m.basename)(e));return r===(0,m.dirname)(r)?void 0:r}(t);return r===qe||void 0!==r&&Ke(e,r)}))}const qe=Symbol("unresolved parent");const ze="win32"===process.platform||"darwin"===process.platform;function Ge(e){if(!e.endsWith(m.sep))return e;const t=e.slice(0,-1);return""===t||"win32"===process.platform&&/^[a-zA-Z]:$/.test(t)?e:t}function Ve(e){return e.endsWith(m.sep)?e:e+m.sep}function Ke(e,t){const r=Ge(t);if(ze){const t=e.toLowerCase(),n=r.toLowerCase();return t===n||t.startsWith(Ve(n))}return e===r||e.startsWith(Ve(r))}function Je(e,t){const r=Ge(e);return ze?(0,m.relative)(r.toLowerCase(),t.toLowerCase()).replace(/\\/g,"/"):(0,m.relative)(r,t).replace(/\\/g,"/")}async function Ze(e,t){if(Ke(e,t)){const r=Je(t,e);if((null===Oe&&(Oe=se({ignoreCase:!0}),Oe.add(Te.filter((e=>"workspace"===e.type)).map((e=>e.pattern)))),Oe).ignores(r))return!0}const{isWorktree:r,gitDirParent:n}=await async function(e){const t=await(0,ne.lstat)((0,m.join)(e,".git")).catch(Ne);if(!t?.isFile())return{isWorktree:!1,gitDirParent:e};const r=await async function(e){return(await Ue(e))?.commonDir}(e);return{isWorktree:!0,gitDirParent:void 0===r?e:(0,m.dirname)(r)}}(t);for(const r of new Set([n,t]))if(Ke(e,r)){const t=Je(r,e);if((null===Fe&&(Fe=se({ignoreCase:!0}),Fe.add(Te.filter((e=>"git"===e.type)).map((e=>e.pattern)))),Fe).ignores(t))return!0}return!(!r||!Ke(e,t)||".git"!==Je(t,e))||He(e)}function Xe(e){return void 0!==e&&("allow"===e.default||void 0!==e.allow&&e.allow.length>0)}function Qe(e){return void 0!==e&&"allow"===e.default}function Ye(){return{version:1,default:"deny"}}function et(){return{version:1,default:"allow"}}var tt=r("../utils/dist/path-utils.js");function rt(e){if(!e)return;const t={version:1};if("allow"!==e.default&&"deny"!==e.default||(t.default=e.default),Array.isArray(e.allow)&&e.allow.length>0&&(t.allow=e.allow.filter((e=>"string"==typeof e))),Array.isArray(e.deny)&&e.deny.length>0&&(t.deny=e.deny.filter((e=>"string"==typeof e))),e.logging){const r={};"string"==typeof e.logging.decisionLogPath&&(r.decisionLogPath=e.logging.decisionLogPath),"jsonl"===e.logging.logFormat&&(r.logFormat="jsonl"),Object.keys(r).length>0&&(t.logging=r)}return t}function nt(e){const t=e.type??"workspace_readwrite",r={debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,enableSharedBuildCache:e.enableSharedBuildCache};if("insecure_none"===t)return{type:"insecure_none",...r};let n;if(Array.isArray(e.additionalReadonlyPaths)){const t=e.additionalReadonlyPaths;n=t.length>0?t:void 0}const o={...r,networkAccess:e.networkAccess,networkPolicy:rt(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,additionalReadonlyPaths:n,readBoundary:e.readBoundary,additionalReadPaths:Array.isArray(e.additionalReadPaths)?e.additionalReadPaths:void 0,disableTmpWrite:e.disableTmpWrite,privateTmp:e.privateTmp};return"workspace_readonly"===t?{type:"workspace_readonly",...o}:{type:"workspace_readwrite",...o,additionalReadwritePaths:e.additionalReadwritePaths}}function ot(e){if("object"!=typeof e||null===e)return"Expected an object";const t=Object.fromEntries(Object.entries(e));if(void 0!==t.type){const e=["insecure_none","workspace_readwrite","workspace_readonly"];if("string"!=typeof t.type||!e.includes(t.type))return`Invalid type: expected one of ${e.join(", ")}`}const r=["networkAccess","networkPolicyStrict","disableTmpWrite","privateTmp","enableSharedBuildCache","captureDenies"];for(const e of r)if(void 0!==t[e]&&"boolean"!=typeof t[e])return`Invalid ${e}: expected boolean`;const n=["debugOutputDir"];for(const e of n)if(void 0!==t[e]&&"string"!=typeof t[e])return`Invalid ${e}: expected string`;const o=["additionalReadwritePaths","additionalReadonlyPaths","additionalReadPaths"];for(const e of o)if(void 0!==t[e]){if(!Array.isArray(t[e]))return`Invalid ${e}: expected array`;if(!t[e].every((e=>"string"==typeof e)))return`Invalid ${e}: expected array of strings`}if(void 0!==t.readBoundary&&"system"!==t.readBoundary&&"workspace"!==t.readBoundary)return'Invalid readBoundary: expected "system" or "workspace"';if(void 0!==t.networkPolicy){if("object"!=typeof t.networkPolicy||null===t.networkPolicy)return"Invalid networkPolicy: expected object";const e=Object.fromEntries(Object.entries(t.networkPolicy));if(void 0!==e.default&&"allow"!==e.default&&"deny"!==e.default)return'Invalid networkPolicy.default: expected "allow" or "deny"';if(void 0!==e.allow&&!Array.isArray(e.allow))return"Invalid networkPolicy.allow: expected array";if(void 0!==e.deny&&!Array.isArray(e.deny))return"Invalid networkPolicy.deny: expected array"}}async function st(e,t){const r=await async function(e,t){try{const r=await(0,ne.readFile)(e,"utf-8"),n=JSON.parse(r);if(void 0!==ot(n))return{success:!1,error:`Invalid sandbox policy: ${ot(n)??""}`};let o=nt(n);return t&&(o=it(o,t)),{success:!0,policy:o}}catch(e){return e instanceof Error?"code"in e&&"ENOENT"===e.code?{success:!1,error:"File not found"}:e instanceof SyntaxError?{success:!1,error:`Invalid JSON: ${e.message}`}:{success:!1,error:e.message}:{success:!1,error:"Unknown error"}}}(e,t);if(r.success)return r.policy}function it(e,t){if("insecure_none"===e.type)return e;const r=e.additionalReadonlyPaths?.map((e=>(0,tt.o1)(e,t))),n=e.additionalReadPaths?.map((e=>(0,tt.o1)(e,t)));if("workspace_readonly"===e.type)return{...e,additionalReadonlyPaths:r,additionalReadPaths:n};const o=e.additionalReadwritePaths?.map((e=>(0,tt.o1)(e,t)));return{...e,additionalReadonlyPaths:r,additionalReadPaths:n,additionalReadwritePaths:o}}var at=r("../constants/dist/commercial-cursor-hosts.js");function ct(e){const t=e.replace(/\\/g,"/").replace(/\/+$/,"");return""===t?"/":/^[a-zA-Z]:$/.test(t)?`${t}/`:t}function lt(e){const t=ct(e);return/^[a-zA-Z]:\//.test(t)||t.startsWith("//")?t.toLowerCase():t}const ut={insecure_none:0,workspace_readwrite:1,workspace_readonly:2};function dt(){return"1"===process.env[at.K4]}function ht(e){if(!dt())return e.teamAdmin?.type??e.perRepo?.type??e.perUser?.type??"insecure_none";const t=e.teamAdmin?.type??e.perUser?.type;return void 0===t&&void 0===e.perRepo?"insecure_none":Rt(t??"workspace_readwrite",e.perRepo?.type??"insecure_none")}function pt(...e){return e.some((e=>!0===e))}function ft(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return[];if(t.some((e=>0===e.length)))return[];if(1===t.length)return function(e){const t=new Set,r=[];for(const n of e){const e=lt(n);t.has(e)||(t.add(e),r.push(n))}return r}(t[0]).map(ct);let r=new Map(t[0].map((e=>{const t=ct(e);return[lt(t),t]})));for(let e=1;en.has(e))))}return[...r.values()]}function mt(...e){const t=new Map;for(const r of e)if(r)for(const e of r){const r=ct(e),n=lt(r);t.has(n)||t.set(n,r)}return[...t.values()]}const gt=function({defaultValue:e,rank:t}){return{defaultValue:e,merge:(...r)=>{const n=r.filter((e=>void 0!==e));return 0===n.length?e:n.reduce(((e,r)=>t[r]ft(...e);function yt(...e){return gt.merge(...e)}function vt(...e){return wt(...e)}function bt(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return;let r;for(const e of t){if("deny"===e.default){r="deny";break}"allow"===e.default&&void 0===r&&(r="allow")}const n=new Set;for(const e of t)if(e.deny)for(const t of e.deny)n.add(t);const o=new Set;for(const e of t)if(e.allow)for(const t of e.allow)o.add(t);const s=o.size>0?[...o]:void 0;let i;for(let e=t.length-1;e>=0;e--)if(void 0!==t[e].logging){i=t[e].logging;break}const a={version:1};return void 0!==r&&(a.default=r),void 0!==s&&(a.allow=s),n.size>0&&(a.deny=[...n]),void 0!==i&&(a.logging=i),void 0!==a.default||void 0!==a.allow&&0!==a.allow.length||void 0!==a.deny&&0!==a.deny.length||void 0!==a.logging?a:void 0}function St(e,t){if(!e||0===e.length)return[...t];const r=new Set(e);for(const e of t)r.has(e)&&r.delete(e),r.add(e);return[...r]}function kt(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return;const r={};for(const e of t)for(const[t,n]of Object.entries(e))r[t]=St(r[t],n);return 0!==Object.keys(r).length?r:void 0}function _t(...e){for(let t=e.length-1;t>=0;t--)if(void 0!==e[t])return e[t]}async function Ct(e,t,r={}){if(!t)return{policy:{type:"insecure_none"}};if(dt()&&(t=Mt(t,e)),(0,oe.$f)(e))return Ot(t,{workspaceDir:e});if("workspace_readwrite"!==(Pt(t)??"workspace_readwrite"))return Ot(t,{workspaceDir:e});const n=r.stat??ne.stat,o=await async function(e,t){for(let r=e;;r=(0,m.dirname)(r)){if((0,oe.$f)(r))return;const e=await Et(r,t);if(void 0!==e)return e;if((0,m.dirname)(r)===r)return}}(e,n);let s=o?.root??e;if(o?.isFile){const e=await Be(o.root);void 0!==e&&(s=(0,m.dirname)(e)),t=xt(t,void 0===e?[]:[e],Me(o.root))}return t=await async function(e,t,r){const n=Nt(e,"workspace_readwrite"),o=mt(n.perUser?.additionalReadwritePaths,n.perRepo?.additionalReadwritePaths,n.teamAdmin?.additionalReadwritePaths);if(0===o.length)return e;const s=(await Promise.all(o.map((async e=>{if(t.has(ct(e))||(0,oe.$f)(e))return[];const n=await Et(e,r);if(void 0===n)return[];const o=[Ae(e),$e(e)];if(n.isFile){o.push(Me(e));const t=await Be(e);void 0!==t&&o.push($e((0,m.dirname)(t)))}return o})))).flat();return 0===s.length?e:xt(e,[],...s)}(t,new Set([ct(e)]),n),Ot(t,{workspaceDir:e,gitDirParent:s})}async function Et(e,t){const r=await t((0,m.join)(e,".git")).catch(Ne);return r?.isFile()||r?.isDirectory()?{root:e,isFile:r.isFile()}:void 0}function xt(e,t,...r){const n=dt(),o=n?e.perUser:e.perRepo,s="workspace_readwrite"===o?.type||void 0===o?o:void 0,i={...s,type:"workspace_readwrite",additionalReadwritePaths:t.length>0?[...s?.additionalReadwritePaths??[],...t]:s?.additionalReadwritePaths,writeProtectionMapping:kt(s?.writeProtectionMapping,...r)};return n?{...e,perUser:i}:{...e,perRepo:i}}function Pt(e){const{perUser:t,perRepo:r,teamAdmin:n}=e,o=[t,r,n].filter((e=>void 0!==e));if(0===o.length)return;const s=o[0].type;for(const e of o)if(e.type!==s)throw new Error(`Cannot merge policies of different types: found "${s}" and "${e.type}". All policies must be of the same type (all workspace_readwrite, all workspace_readonly, or all insecure_none).`);return s}function Rt(e,t){return ut[e]>=ut[t]?e:t}function It(e,t){if(void 0===e||e.type===t)return e;if("insecure_none"===t)return{type:t,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,enableSharedBuildCache:e.enableSharedBuildCache};if("insecure_none"===e.type)return{...e,type:t};if("workspace_readonly"===t){if("workspace_readwrite"===e.type){const{additionalReadwritePaths:r,...n}=e;return{...n,type:t}}return e}return e}function Tt(e){if("deny"===e?.default||void 0!==e?.deny&&0!==e.deny.length)return{version:1,..."deny"===e.default?{default:"deny"}:{},...void 0!==e.deny&&e.deny.length>0?{deny:e.deny}:{}}}function At(e,t,r){if(void 0===e||"insecure_none"===t)return;const n="insecure_none"===e.type?void 0:e,o={captureDenies:!0===e.captureDenies||void 0,networkPolicy:Tt(n?.networkPolicy),networkPolicyStrict:!0===n?.networkPolicyStrict||void 0,readBoundary:"workspace"===n?.readBoundary?"workspace":void 0,additionalReadPaths:void 0===n?.additionalReadPaths?void 0:ft(n.additionalReadPaths,r),additionalReadonlyPaths:n?.additionalReadonlyPaths,disableTmpWrite:!0===n?.disableTmpWrite||void 0,ignoreMapping:n?.ignoreMapping,writeProtectionMapping:n?.writeProtectionMapping};return"workspace_readonly"===t?{type:t,...o}:{type:"workspace_readwrite",...o}}function $t(e,t){return void 0===e||"insecure_none"===e.type||void 0===t?e:{...e,additionalReadPaths:e.additionalReadPaths?.map((e=>ct((0,tt.o1)(e,t))))}}function Mt(e,t){const r=Pt({perUser:e.perUser,teamAdmin:e.teamAdmin})??"workspace_readwrite",n=void 0===e.perRepo?r:Rt(r,e.perRepo.type),o=$t(It(e.perUser,n),t),s=$t(It(e.teamAdmin,n),t),i=mt("insecure_none"===o?.type?void 0:o?.additionalReadPaths,"insecure_none"===s?.type?void 0:s?.additionalReadPaths);return{perUser:o,perRepo:At(e.perRepo,n,i),teamAdmin:s}}function Dt(e,t){return Mt(e,t)}function Ot(e,t){return function(e,t){dt()&&(e=Mt(e,t?.workspaceDir));const r=Pt(e);if(void 0===r)return Ut({},t);switch(r){case"workspace_readwrite":return Ut(Nt(e,r),t);case"workspace_readonly":return function(e,t){const r=t?.debug,n=Lt(e,t),o={policy:jt({type:"workspace_readonly",disableTmpWrite:n.disableTmpWrite,networkPolicyStrict:n.networkPolicyStrict,readBoundary:n.readBoundary,additionalReadPaths:n.additionalReadPaths,additionalReadonlyPaths:n.additionalReadonlyPaths,networkPolicy:n.networkPolicy,debugOutputDir:n.debugOutputDir,captureDenies:n.captureDenies,enableSharedBuildCache:n.enableSharedBuildCache,privateTmp:n.privateTmp,ignoreMapping:n.ignoreMapping,writeProtectionMapping:n.writeProtectionMapping},"workspace_readonly")};return r&&(o.debug={fieldSources:n.fieldSources}),o}(Nt(e,r),t);case"insecure_none":return function(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,s=t?.debug,i={policy:jt({type:"insecure_none",allowlistEscalated:pt(r?.allowlistEscalated,n?.allowlistEscalated,o?.allowlistEscalated)||void 0,debugOutputDir:_t(r?.debugOutputDir,n?.debugOutputDir,o?.debugOutputDir),captureDenies:pt(r?.captureDenies,n?.captureDenies,o?.captureDenies)||void 0,enableSharedBuildCache:_t(r?.enableSharedBuildCache,n?.enableSharedBuildCache,o?.enableSharedBuildCache)},"insecure_none")};return s&&(i.debug={fieldSources:{}}),i}(Nt(e,r),t);default:throw new Error(`Unknown policy type: ${String(r)}`)}}(e,t)}function Ft(e,t){return e?.type===t}function Nt(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e;return{perUser:Ft(r,t)?r:void 0,perRepo:Ft(n,t)?n:void 0,teamAdmin:Ft(o,t)?o:void 0}}function Lt(e,t){const r=t?.debug,{perUser:n,perRepo:o,teamAdmin:s}=e,i=t?.workspaceDir??process.cwd(),a=function(e){const t=function(){if(0!==De.length)return{version:1,deny:[...De]}}(),r=q.homedir(),n=[];for(const e of Te)switch(e.type){case"workspace":case"git":case"worktree":break;case"absolute":n.push(e.pattern);break;case"home":r.length>0&&n.push((0,m.join)(r,e.pattern));break;default:{const t=e.type;throw new Error(`Unknown entry type: ${String(t)}`)}}return n.push(...ye(r)),{type:"workspace_readwrite",additionalReadonlyPaths:n,writeProtectionMapping:Ae(e),...t&&{networkPolicy:t},networkPolicyStrict:!0}}(i),c={},l=[n,o,s],u=["perUser","perRepo","teamAdmin","hardcoded"],d=(e,t)=>{r&&(c[e]=u[t]??"unknown")},h=pt(n?.disableTmpWrite,o?.disableTmpWrite,s?.disableTmpWrite);for(let e=l.length-1;e>=0;e--)if(!0===l[e]?.disableTmpWrite){d("disableTmpWrite",e);break}const p=pt(n?.networkPolicyStrict,o?.networkPolicyStrict,s?.networkPolicyStrict,a.networkPolicyStrict);a.networkPolicyStrict&&d("networkPolicyStrict",3);const f=dt()?yt(_t(n?.readBoundary,s?.readBoundary)??"system",o?.readBoundary):_t(n?.readBoundary,o?.readBoundary,s?.readBoundary)??"system",g=_t(n?.additionalReadPaths,o?.additionalReadPaths),w=!1===s?.allowUserOverrideReadPaths?mt(s.additionalReadPaths):mt(g,s?.additionalReadPaths),y="workspace"===f?w:void 0,v=mt(n?.additionalReadonlyPaths,o?.additionalReadonlyPaths,s?.additionalReadonlyPaths,a.additionalReadonlyPaths),b=v.length>0?v:void 0;let S=bt(n?.networkPolicy,o?.networkPolicy,s?.networkPolicy,a.networkPolicy);const k=s?.networkPolicy?.allow;void 0!==k&&k.length>0&&void 0!==S&&(S={...S,allow:[...k]},r&&(c["networkPolicy.allow"]="teamAdmin (replace)"));const _=void 0!==(C=S)?C:{version:1,default:"deny"};var C;const E=_t(n?.debugOutputDir,o?.debugOutputDir,s?.debugOutputDir),x=pt(n?.captureDenies,o?.captureDenies,s?.captureDenies),P=_t(n?.enableSharedBuildCache,o?.enableSharedBuildCache,s?.enableSharedBuildCache),R=_t(n?.privateTmp,o?.privateTmp,s?.privateTmp),I=kt(n?.ignoreMapping,o?.ignoreMapping,s?.ignoreMapping,a.ignoreMapping),T=$e(t?.gitDirParent??i);return{disableTmpWrite:h||void 0,networkPolicyStrict:p,readBoundary:f,additionalReadPaths:y,additionalReadonlyPaths:b,networkPolicy:_,debugOutputDir:E,captureDenies:x||void 0,enableSharedBuildCache:P,privateTmp:R,ignoreMapping:I,writeProtectionMapping:kt(n?.writeProtectionMapping,o?.writeProtectionMapping,s?.writeProtectionMapping,a.writeProtectionMapping,T),fieldSources:c}}function jt(e,t){const r={...e,type:t};for(const[e,t]of Object.entries(r))void 0===t&&Reflect.deleteProperty(r,e);return r}function Ut(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,s=t?.debug,i=Lt(e,t),a=mt(r?.additionalReadwritePaths,n?.additionalReadwritePaths,o?.additionalReadwritePaths),c={policy:jt({type:"workspace_readwrite",disableTmpWrite:i.disableTmpWrite,networkPolicyStrict:i.networkPolicyStrict,readBoundary:i.readBoundary,additionalReadPaths:i.additionalReadPaths,additionalReadwritePaths:a.length>0?a:void 0,additionalReadonlyPaths:i.additionalReadonlyPaths,networkPolicy:i.networkPolicy,debugOutputDir:i.debugOutputDir,captureDenies:i.captureDenies,enableSharedBuildCache:i.enableSharedBuildCache,privateTmp:i.privateTmp,ignoreMapping:i.ignoreMapping,writeProtectionMapping:i.writeProtectionMapping},"workspace_readwrite")};return s&&(c.debug={fieldSources:i.fieldSources}),c}var Bt=r("../utils/dist/workload-spawn.js"),Wt=r("../context/dist/logger.js"),Ht=r("../context/dist/core.js"),qt=r("../utils/dist/command-glob.js");const zt=n.execFile,Gt=new WeakMap;function Vt(e,t,r){return e===t?"related":r?.has(e)?"probably_unrelated":"maybe_related"}const Kt="darwin"===process.platform,Jt="linux"===process.platform,Zt=(0,Wt.h)("shell-exec:sandbox");function Xt(e){const t=ce();return e&&0!==e.length?e.includes(t)?e:[...e,t]:[t]}let Qt,Yt=!0,er=!1;function tr(){return Qt}function rr(e){"linux"===process.platform&&Object.assign(e,I(e))}let nr=null,or=null,sr=null,ir=null,ar=!1,cr=null;function lr(e){return{...e,additionalReadonlyPaths:Xt(e.additionalReadonlyPaths)}}class ur extends Error{}function dr(e){return e instanceof Error&&"code"in e&&"string"==typeof e.code?e.code:"unknown"}function hr(e,t,r){let n;e.ignoreMapping&&(n=function(e){return vr(e)}(e.ignoreMapping));const o=function(e,t,r){const n=e&&e.length>0?function(...e){const t={};for(const r of e){let e=!1;try{e=(0,g.existsSync)(r)&&(0,g.statSync)(r).isDirectory()}catch{}if(e)t[r]||(t[r]=[]),t[r].push("**");else{const e=r.lastIndexOf("/"),n=e>0?r.slice(0,e):"/",o=e>=0?r.slice(e+1):r;t[n]||(t[n]=[]),o?t[n].push(o,`${o}/**`):t[n].push("**")}}return t}(...e):{},o=!Jt||yr(r),s={...n};for(const[e,r]of Object.entries(t??{})){const t=e.startsWith("file://")?br(e):e;(o||yr(t))&&(s[e]=St(s[e],r))}if(0!==Object.keys(s).length)return vr(s)}(e.additionalReadonlyPaths,e.writeProtectionMapping,t),s=(i=e.readBoundary,r?.workspaceReadEnabled??function(){const e=Yt;return"function"==typeof e?e():e}()?i??"system":"system");var i;const a=function(e=process.platform){const t=[],r=new Set,n={};try{n.ripgrep=T()}catch{}for(const o of Ie(e,q.homedir(),n))r.has(o)||(r.add(o),t.push(o));return t}(),c=[t,..."workspace_readwrite"===e.type&&e.additionalReadwritePaths||[],Z(t)].filter((e=>void 0!==e)),l="workspace"===s?(e.additionalReadPaths??[]).flatMap((e=>function(e,t){let r=e.trim();(r.startsWith("~/")||r.startsWith("~\\"))&&(r=m.join(q.homedir(),r.slice(2)));const n=e=>e.includes("*")||e.includes("?"),o=/[/\\]\*\*?$/;if(o.test(r)&&n(m.basename(r.replace(/(?:[/\\]\*\*?)+$/,""))))return Zt.warn((0,Ht.q6)(),"[additionalReadPathGrants] a Read Allowlist file-name glob followed by /* or /** grants nothing"),[];const s=m.basename(r);if(o.test(r)||!n(s))return function(e){const t=[],r=new Set;for(const n of e){let e=n.trim();if(!e)continue;"~"===e?e=q.homedir():(e.startsWith("~/")||e.startsWith("~\\"))&&(e=m.join(q.homedir(),e.slice(2))),e=e.replace(/\/\*\*$/,"").replace(/\/\*$/,""),e=e.replace(/\\\*\*$/,"").replace(/\\\*$/,"");const o=m.basename(e);if((o.includes("*")||o.includes("?"))&&(e=m.dirname(e)),!e||"."===e)continue;const s=m.normalize(e);r.has(s)||(r.add(s),t.push(s))}return t}([e]);const i=m.dirname(r);return m.isAbsolute(i)?function(e,t,r){const n=(0,qt.b)(t),o=[];let s;try{const t=(0,g.realpathSync)(e);if(r.filter((e=>g.existsSync(e))).map((e=>(0,g.realpathSync)(e))).some((e=>(0,tt.BJ)(t,e))))return[];s=g.opendirSync(t);for(let e=1;;e++){const r=s.readSync();if(null===r)return o;if(e>1e4)throw new ur("its folder has more than 10000 entries");if(!n(r.name))continue;const i=m.join(t,r.name);try{if(!g.lstatSync(i).isFile()||m.dirname((0,g.realpathSync)(i))!==t)continue}catch(e){Zt.info((0,Ht.q6)(),`[fileNameGlobMatches] skips a matching file: error ${dr(e)}`);continue}if(256===o.length)throw new ur("more than 256 files match");o.push(i)}}catch(e){const t=e instanceof ur?e.message:`error ${dr(e)}`;return Zt.warn((0,Ht.q6)(),`[fileNameGlobMatches] a Read Allowlist file-name glob grants nothing: ${t}`),[]}finally{s?.closeSync()}}(i,s,t):[]}(e,c))):[],u=[...a],d=new Set(a);for(const e of l)d.has(e)||(d.add(e),u.push(e));const h={cwd:t,readBoundary:s,hardcodedReadPaths:u,additionalReadonlyPaths:o,networkAccess:Xe(e.networkPolicy),ignoreMapping:n};return"workspace_readonly"===e.type?{type:e.type,...h}:{type:e.type,...h,additionalReadwritePaths:e.additionalReadwritePaths||[],disableTmpWrite:e.disableTmpWrite||!1}}function pr(e){const t={sandbox:e};return Jt&&function(){const e=er;return"function"==typeof e?e():e}()&&(t.kernelMountBudget=!0),t}function fr(e){if(null!==nr)return nr;try{const t=tr();return Zt.info(e,`[checkBinaryAvailable] Resolved binary path: ${t}`),t?(nr=g.existsSync(t),nr?Zt.info(e,`[checkBinaryAvailable] Binary path exists: ${String(nr)}`):(or=new Error(`Sandbox binary not found at ${t}`),Zt.info(e,`[checkBinaryAvailable] Binary not found at: ${t}`)),nr):(or=new Error("Sandbox binary path was not configured"),nr=!1,Zt.info(e,"[checkBinaryAvailable] Binary path not set, returning false"),!1)}catch(t){return or=t instanceof Error?t:new Error(String(t)),nr=!1,Zt.info(e,`[checkBinaryAvailable] Exception checking binary: ${String(t)}`),!1}}function mr(e){if(null!==ir)return ir;const t=e??(0,Ht.q6)();if(Zt.info(t,"[isSandboxHelperSupported] Starting sandbox support check..."),!fr(t)){const e=or?.message||"Binary check failed";return sr=e,Zt.info(t,`[isSandboxHelperSupported] Binary not available, returning false. Reason: ${e}`),ir=!1,ir}if("win32"===process.platform)return sr="Windows sandbox helper only provides network proxy, not filesystem isolation",Zt.info(t,"[isSandboxHelperSupported] win32: returning false (proxy-only, no filesystem sandbox)"),ir=!1,ir;if("darwin"===process.platform)return sr=null,Zt.info(t,`[isSandboxHelperSupported] ${process.platform} platform, binary available, sandbox supported!`),ir=!0,ir;const{binaryPath:r,args:o,env:s}=function(e,t){const r=pr(hr(lr({type:"workspace_readwrite"}),t)),n=String(tr());Zt.info(e,`[sandboxPreflight] Running preflight with binary: ${n}`),Zt.info(e,`[sandboxPreflight] CWD: ${t}`);const o={...process.env};return rr(o),{binaryPath:n,args:["--policy",le(JSON.stringify(r)),"--preflight-only","--","/bin/true"],env:o}}(t,process.cwd());try{const e=Date.now();(0,Bt.D9)(n.execFileSync,r,o,{stdio:["ignore","ignore","pipe"],timeout:gr,env:s,shell:!1});const i=Date.now()-e;return sr=null,Zt.info(t,`[isSandboxHelperSupported] Preflight succeeded in ${i}ms, sandbox supported!`),ir=!0,ir}catch(e){return function(e,t){const{message:r,status:n,stderrText:o}=t;return Zt.error(e,`[sandboxPreflight] Preflight failed: ${r}`),Zt.error(e,`[sandboxPreflight] Exit status: ${n}`),o&&Zt.error(e,`[sandboxPreflight] Stderr: ${o}`),sr=2===n?`Linux preflight failed with exit code 2 (unsupported kernel features). stderr: ${o||"none"}`:`Linux preflight failed: ${r||"unknown error"}. Exit status: ${n}. stderr: ${o||"none"}`,ir=!1,!1}(t,function(e){if("object"!=typeof e||null===e)return{stderrText:""};const t="message"in e&&"string"==typeof e.message?e.message:void 0,r=!("status"in e)||"number"!=typeof e.status&&null!==e.status?void 0:e.status,n="stderr"in e?e.stderr:void 0;return{message:t,status:r,stderrText:Buffer.isBuffer(n)||"string"==typeof n?n.toString():""}}(e))}}(0,G.J)((function(){ir=null,ar=!1,cr=null,sr=null,nr=null,or=null}));const gr=15e3;function wr(e,t=[],r={},o){const i=(0,Ht.q6)();if(r.env=a(s(r.env)),!fr(i))throw new Error(`Sandbox binary not available: ${or?.message||"binary not configured"}. Please build the binary or use 'insecure_none' policy.`);if("insecure_none"===o.type)return(0,Bt.D9)(n.spawn,e,t,{...r,windowsHide:!0});if("workspace_readwrite"===o.type||"workspace_readonly"===o.type)return function(e,t,r,o){if("workspace_readwrite"!==o.type&&"workspace_readonly"!==o.type)throw new Error("Expected workspace_readwrite or workspace_readonly policy");const i=String(r.cwd??process.cwd()),c=o.sandboxWorkspaceRoot??i;let u=e,d=t;r.shell&&("win32"===process.platform?(u="string"==typeof r.shell?r.shell:"cmd.exe",d=["/c",`${e} ${t.join(" ")}`]):(u="string"==typeof r.shell?r.shell:"/bin/sh",d=["-c",`${e} ${t.join(" ")}`]));const h=function({workspaceRoot:e,executionCwd:t}){const r=m.resolve(e),n=m.resolve(t),o=Sr(r);if(n===r||n===o)return;const s=e=>(0,tt.ZU)({basePath:o,targetPath:e})?m.join(r,m.relative(o,e)):void 0,i=(0,tt.ZU)({basePath:r,targetPath:n})?n:s(n)??n;return{directory:i,fallbackDirectory:s(Sr(n))??i}}({workspaceRoot:c,executionCwd:i});"win32"!==process.platform&&void 0!==h&&({command:u,args:d}=(0,oe.kO)(u,d,h));const p=hr(lr(o),c),f=(0,Ht.q6)();!function({log:e,dirs:t=ve(q.homedir(),q.tmpdir(),pe),createOnly:r=[we(process.env,pe)].filter((e=>void 0!==e)),policyDir:n=ie(),uid:o=process.getuid?.()??-1}){const s=m.join(n,"node-compile-cache-removed-1"),{record:i,problem:a}=function(e){const t=e=>({record:{cleaned:[],kept:{},failed:{}},problem:e});let r,n;try{r=g.readFileSync(e,"utf8")}catch(e){const r=ke(e);return t("ENOENT"===r?void 0:r)}try{n=JSON.parse(r)}catch(e){return t(e instanceof SyntaxError?"not JSON":ke(e))}if("object"!=typeof n||null===n)return t("not a record");const o="cleaned"in n?n.cleaned:void 0;return{record:{cleaned:Array.isArray(o)?o.filter((e=>"string"==typeof e)):[],kept:Se("kept"in n?n.kept:void 0),failed:Se("failed"in n?n.failed:void 0)}}}(s);void 0!==a&&e(`node compile cache: starting a new cleanup record (${a})`);const c=new Set(i.cleaned),l=new Set(t);let u=!1;for(const n of[...t,...r.filter((e=>!l.has(e)))])try{const t=g.lstatSync(n,{throwIfNoEntry:!1});if(void 0!==t){const r=be(t,o);if(void 0!==r){i.kept[n]!==r&&(e(`node compile cache: kept ${n} (${r})`),i.kept[n]=r,u=!0);continue}l.has(n)&&!c.has(n)&&(g.rmSync(n,{recursive:!0,force:!0}),e(`node compile cache: removed ${n}`))}g.mkdirSync(n,{recursive:!0,mode:448}),l.has(n)&&!c.has(n)&&(c.add(n),u=!0),void 0===i.kept[n]&&void 0===i.failed[n]||(delete i.kept[n],delete i.failed[n],u=!0)}catch(t){const r=ke(t);i.failed[n]!==r&&(e(`node compile cache: could not prepare ${n} (${r})`),i.failed[n]=r,u=!0)}u&&function(e,t){const r=`${e}.${process.pid}.tmp`;try{g.writeFileSync(r,`${JSON.stringify(t)}\n`,{mode:384}),g.renameSync(r,e)}catch{g.rmSync(r,{force:!0})}}(s,{...i,cleaned:[...c]})}({log:e=>Zt.info(f,e)});const w=function(e){if(!("workspace"!==e.readBoundary||"workspace_readwrite"===e.type&&e.disableTmpWrite||"win32"===process.platform))return X(e.cwd,{create:!0})}(p);let y;w&&(p.additionalReadwritePaths=[...p.additionalReadwritePaths??[],w],Jt&&!0===o.privateTmp&&(y=te(w).TMPDIR));const v=function(e){if("insecure_none"===e.type)return;const t=e.networkPolicy;if(void 0===t)return;if(!Xe(t))return;const r=void 0!==t.deny&&t.deny.length>0;return"allow"!==t.default||r?{version:1,...t}:void 0}(o),b=pr(p);void 0!==y&&(b.mapTmpTo=y),void 0!==v&&(b.networkPolicy=v),!1===o.networkPolicyStrict&&(b.networkPolicyStrict=!1);const S=["--policy",le(JSON.stringify(b)),"--",u,...d],k=s(process.env),_={..."linux"===process.platform?l(k):k,..."linux"===process.platform&&r.env?l(r.env):r.env,CURSOR_SANDBOX:"native"};rr(_);const C=new Set(Y);if(w){const e=function(e,t,r){const n=te(e);if(r){const r=re();for(const[o,s]of Object.entries(re(e)))t[o]===r[o]&&(n[o]=s)}return n}(w,_,o.enableSharedBuildCache);Object.assign(_,e);for(const t of Object.keys(e))C.add(t);_.__CURSOR_SANDBOX_TEMP_RESTORE=Object.entries(e).map((([e,t])=>`builtin export ${e}='${t.replace(/'/g,"'\\''")}'`)).join("; ")}_.__CURSOR_SANDBOX_OWNED_ENV=[...C].join(" ");const E={cwd:void 0!==y?p.cwd:r.cwd||i,env:a(_),stdio:r.stdio||["pipe","pipe","pipe"],detached:r.detached,windowsHide:!0};try{const e=new Date,t=(0,Bt.D9)(n.spawn,String(tr()),S,E);return Kt&&t.pid&&function(e,t){Gt.set(e,t)}(t,{startTime:e,pid:t.pid}),t}catch(e){throw new Error(`Failed to spawn sandboxed process: ${String(e)}`)}}(e,t,r,o);throw new Error(`Unsupported sandbox policy: ${String(o)}`)}function yr(e,t=e=>g.existsSync(e)){if((0,oe.$f)(e))return!0;let r=m.resolve(e);for(;;){try{if(t(m.join(r,".git")))return!0}catch{}const e=m.dirname(r);if(e===r)return!1;r=e}}function vr(e,t,r,n){const o={};for(const[t,r]of Object.entries(e)){const e=t.startsWith("file://")?br(t):t;o[e]=St(o[e],r);const n=Sr(e);n!==e&&(o[n]=St(o[n],r))}return o}function br(e){let t=e.replace(/^file:\/\//,"");return t=decodeURIComponent(t),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t}function Sr(e,t){if((0,oe.$f)(e))return e;try{return(t??g.realpathSync)(e)}catch{return e}}function kr(){return sr}class _r extends Error{reason;constructor(e,t){super(e),this.reason=t,this.name="SandboxUnsupportedError"}}const Cr="darwin"===process.platform;function Er(e){!function(e){T();const{sandboxBinaryPath:t,workspaceReadEnabled:r,kernelMountBudget:n}=e;Qt||(Qt=t),void 0!==r&&(Yt=r),void 0!==n&&(er=n)}(e)}function xr(e,t=[],r={},o){if(r.env=s(r.env),o.enableSharedBuildCache&&(r={...r,env:{...s(process.env),...re(),...r.env}}),"insecure_none"!==o.type){if(mr())return wr(e,t,r,o);const n=kr();throw new _r(`Sandbox policy '${o.type}' is not supported on this system. Ensure the sandbox helper binary is available, or use 'insecure_none'. Reason: ${n||"unknown"}`,n??void 0)}return function(e,t,r,o={spawn:n.spawn,spawnWorkload:Bt.D9}){return o.spawnWorkload(o.spawn,e,t,{...r,env:a(r.env??process.env),windowsHide:!0})}(e,t,r)}function Pr(e){return Cr?async function(e){const t=Gt.get(e);return t?(r=t.pid,n=t.startTime,o=t.unrelatedPids,new Promise((e=>{try{const t=new Date,s=["show","--style","ndjson","--predicate",'process=="kernel" AND eventMessage CONTAINS "Sandbox:" AND eventMessage contains "deny"',"--last",Math.ceil((t.getTime()-n.getTime())/1e3).toString()];(0,Bt.D9)(zt,"/usr/bin/log",s,((t,n)=>{if(t)return void e([{raw:t.message}]);const s=n.split(/\r?\n/).filter((e=>e.trim().length>0)),i=[];for(const e of s)try{const t=JSON.parse(e),n=t?.eventMessage??"";if(!n||"string"!=typeof n)continue;const s=/^Sandbox:\s+([^(]+)\((\d+)\)\s+([a-zA-Z-]+)\((\d+)\)\s+([^\s]+)\s+(.+)$/.exec(n);if(s){const[,e,a,c,l,u,d]=s,h=Number(a);i.push({timestamp:t.timestamp,processName:e.trim(),pid:h,decision:c.toLowerCase(),decisionCode:Number(l),operation:u,target:d,duplicateCount:1,raw:n,relationship:Vt(h,r,o)});continue}const a=/^(\d+) duplicate report for Sandbox: (.+)$/.exec(n);if(a){const e=Number(a[1]),s=a[2],c=/^([^(]+)\((\d+)\)\s+([a-zA-Z-]+)\((\d+)\)\s+([^\s]+)\s+(.+)$/.exec(s);if(c){const[,s,a,l,u,d,h]=c,p=Number(a);i.push({timestamp:t.timestamp,processName:s.trim(),pid:p,decision:l.toLowerCase(),decisionCode:Number(u),operation:d,target:h,duplicateCount:e,raw:n,relationship:Vt(p,r,o)})}else i.push({timestamp:t.timestamp,duplicateCount:e,raw:n});continue}i.push({timestamp:t.timestamp,raw:n})}catch{}e(i)}))}catch(t){e([{raw:String(t)}])}}))):(console.log("No sandbox metadata found on child process"),[]);var r,n,o}(e):Promise.resolve([])}function Rr(e,t){if(Cr)try{(0,g.accessSync)("/usr/bin/sandbox-exec",g.constants.X_OK)}catch{return!1}return mr(t?.ctx)}var Ir=r("node:stream"),Tr=r("../context/dist/otel.js"),Ar=r("../utils/dist/writable-iterable.js");const $r="--",Mr='builtin eval "$1" 3<&- 4>&-';var Dr=r("node:string_decoder");const Or=50,Fr=262144;class Nr{writable;pending=[];pendingBytes=0;flushTimeout;flushPromise;flushIntervalMs;maxBufferedBytes;constructor(e,t){this.writable=e,this.flushIntervalMs=t?.flushIntervalMs??Or,this.maxBufferedBytes=t?.maxBufferedBytes??Fr}async push(e,t){0!==t.length&&(this.pending.push({type:e,data:t}),this.pendingBytes+=t.length,this.pendingBytes>=this.maxBufferedBytes?await this.flush():this.scheduleFlush())}async flush(){if(this.clearFlushTimeout(),this.flushPromise)return await this.flushPromise,void(this.pendingBytes>0&&await this.flush());if(0===this.pendingBytes)return;const e=this.pending;this.pending=[],this.pendingBytes=0,this.flushPromise=this.writeBufferedOutput(e);try{await this.flushPromise}finally{this.flushPromise=void 0}}async close(){await this.flush()}scheduleFlush(){void 0===this.flushTimeout&&(this.flushTimeout=setTimeout((()=>{this.flushTimeout=void 0,this.flush()}),this.flushIntervalMs))}clearFlushTimeout(){void 0!==this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=void 0)}async writeBufferedOutput(e){for(const t of function(e){if(0===e.length)return[];const t=[];let r=e[0].type,n=[e[0].data];for(let o=1;o{e.writable.write({type:t,data:r}).catch((()=>{}))};return e.stdout?.on("data",(e=>{const n=t.note(e);void 0!==n&&n.length>0&&r("stdout",n)})),e.stderr?.on("data",(e=>{r("stderr",e)})),{get stdoutBytes(){return t.bytes},get stdoutPrefix(){return t.stdoutPrefix},async waitForOutput(){},async releaseHeldStdout(){const e=t.takeHeld();void 0!==e&&e.length>0&&r("stdout",e)},dropHeldStdout(){t.takeHeld()},async flush(){await this.releaseHeldStdout()}}}const r=new Nr(e.writable,e.outputLimiterOptions);let n;const o=Promise.all([jr(e.stdout,r,t),Ur(e.stderr,"stderr",r)]).then((()=>{})).catch((e=>{n=e}));return{get stdoutBytes(){return t.bytes},get stdoutPrefix(){return t.stdoutPrefix},async waitForOutput(){if(await o,void 0!==n)throw(e=n)instanceof Error?e:new Error(String(e));var e},async releaseHeldStdout(){const e=t.takeHeld();void 0!==e&&e.length>0&&await r.push("stdout",e)},dropHeldStdout(){t.takeHeld()},async flush(){await this.releaseHeldStdout(),await r.flush()}}}async function jr(e,t,r){if(e)for await(const n of e){const e=r.note(n);void 0!==e&&e.length>0&&await t.push("stdout",e)}}async function Ur(e,t,r,n){if(e)for await(const o of e)n?.(o),await r.push(t,o)}var Br;!function(e){e.Zsh="zsh",e.ZshLight="zsh-light",e.Bash="bash",e.PowerShell="powershell",e.Naive="naive"}(Br||(Br={}));const Wr={TERM:"dumb",NO_COLOR:"1",FORCE_COLOR:"0",_ZO_DOCTOR:"0"};function Hr(e){return"win32"===e.platform?"windows_tree":e.detached?"process_group":"single_process"}function qr(e,t,r,o={spawn:n.spawn,killPid:process.kill.bind(process)}){const s=e.pid;if(void 0===s)return;const i=()=>{try{e.kill(r)}catch{}};switch(t){case"process_group":try{o.killPid(-s,r)}catch{i()}return;case"windows_tree":try{o.spawn("taskkill",["/pid",String(s),"/t","/f"],{stdio:"ignore",windowsHide:!0}).on("error",i)}catch{i()}return;case"single_process":return void i();default:throw new Error(`Unknown process tree kill mode: ${String(t)}`)}}function zr(e,t=[],r={},n,o){const s=xr(e,t,{...r,env:I(r.env??process.env)},n);return o?Vr(s,{detached:!0===r.detached},o):Gr(s,!0===r.detached),s}function Gr(e,t){"single_process"!==Hr({platform:process.platform,detached:t})&&e.pid}function Vr(e,t,r){const n=Hr({platform:process.platform,detached:t.detached});Gr(e,t.detached);const o=()=>{if(!e.pid)return;qr(e,n,"SIGTERM");const t=setTimeout((()=>{!e.killed&&e.pid&&qr(e,n,"SIGKILL")}),1e3);"process_group"!==n&&e.once("exit",(()=>{clearTimeout(t)}))};r.aborted?o():(r.addEventListener("abort",o,{once:!0}),e.once("exit",(()=>{r.removeEventListener("abort",o)})))}function Kr(e,t,r){if(e){try{process.kill(-e,t)}catch{return}"SIGTERM"===t&&void 0!==r&&r>0&&setTimeout((()=>{try{process.kill(-e,"SIGKILL")}catch{}}),r)}}const Jr=new Set(["SIGTERM","SIGINT","SIGHUP","SIGQUIT","SIGKILL"]);function Zr(e,t,r){null!==t&&Jr.has(t)&&!r&&"win32"!==process.platform&&Kr(e,t)}function Xr(e,{shellName:t,closeGraceMs:r,timeoutMs:n}){const o=r??5e3,s=n??6e4;return new Promise((r=>{const n=[];let i;const a=e=>{n.push(e)},c=()=>{clearTimeout(d),o<=0||(i=setTimeout((()=>{console.warn(`[shell-exec] ${t} state init exited but its stdio did not close within ${o}ms; a startup file left a background process holding the output pipe. Proceeding with the dump received so far.`),u("exit_without_close")}),o))},l=()=>{u("closed")},u=t=>{clearTimeout(d),clearTimeout(i),e.off("exit",c),e.off("close",l),e.stdout?.off("data",a),e.stdout?.resume(),r({outcome:t,stdout:Buffer.concat(n).toString("utf8")})},d=s>0?setTimeout((()=>{console.warn(`[shell-exec] ${t} state init did not exit within ${s}ms; a startup file is blocking. Killing it and falling back to an empty state.`),qr(e,Hr({platform:process.platform,detached:!0}),"SIGKILL"),u("timed_out")}),s):void 0;e.stdout?.on("data",a),Qr(e.stdout),e.on("exit",c),e.on("close",l)}))}function Qr(e){e?.on("error",(()=>{}))}function Yr(e){e.removeAllListeners(),e.on("error",(()=>{})),e.stdout?.removeAllListeners("close"),e.stderr?.removeAllListeners("close");for(const t of e.stdio.slice(3))t?.destroy()}const en="IFS= builtin read -r -d '' __cursor_command <&5 2>/dev/null || { builtin printf '%s\\n' 'The command did not run: a shell startup file ($BASH_ENV or .zshenv) closed or replaced file descriptor 5, which carries the command. Run it again; this shell now passes commands as arguments.' >&2; builtin exit 126; }; exec 5<&-; builtin set -- \"$__cursor_command\"; builtin unset __cursor_command; ";function tn(e,t){return 126===e&&""===t}function rn(){return"win32"!==process.platform}function nn(e,t){const r=e.stdio.at(5);r instanceof Ir.Writable&&(Qr(r),r.end(`${t}\0`))}function on(e,t){e&&(Qr(e),e.write(t),e.end())}function sn(e,t){if(!e)return;Qr(e);const r=new Dr.StringDecoder("utf8");e.on("data",(e=>{const n=r.write(e);""!==n&&t(n)})),e.on("end",(()=>{const e=r.end();""!==e&&t(e)}))}function an(e){const t=e.indexOf("\n");return{cwd:Buffer.from(e.substring(0,t),"utf16le").toString("utf16le"),rest:e.substring(t)}}function cn(e,t){const r=t instanceof Error&&"code"in t&&"string"==typeof t.code?t.code:"unknown";console.warn(e,r)}function ln(e,t){const r=`${t}\n`,n=e.indexOf(r);return n>=0?e.slice(n+r.length):e}function un(e){return!1===e?.isLoginShellEnabled?"-ic":"-ilc"}function dn(e,t,r){const n=`${t}\n`;if(!e.startsWith(n))return;const o=e.indexOf(`\n${r}\n`,n.length-1);return o<0?void 0:e.slice(n.length,o+1)}const hn="__CURSOR_BASH_STATE_START__",pn="__CURSOR_BASH_STATE_END__",fn="\n Emit $PWD.Path\n #Log-Timing \"working_dir\"\n\n function ShouldPersistEnvVar {\n param([string]$Name)\n if ($Name -eq 'CURSOR_CONVERSATION_ID') {\n return $false\n }\n if ($Name -eq 'CURSOR_REQUEST_ID') {\n return $false\n }\n if ($Name -like 'CURSOR_AGENT_STORE*') {\n return $false\n }\n if ($Name -like '*CURSOR_SANDBOX*') {\n return $false\n }\n if ($Name -eq 'ELECTRON_RUN_AS_NODE') {\n return $false\n }\n return $true\n }\n\n $envVars = Get-ChildItem Env: | Sort-Object Name\n foreach ($var in $envVars) {\n if (-not (ShouldPersistEnvVar -Name $var.Name)) {\n continue\n }\n $encoded = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes([string]$var.Value))\n Emit ('Set-Item -LiteralPath ''Env:{0}'' -Value ([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String(''{1}'')))' -f $var.Name, $encoded)\n }\n #Log-Timing \"environment\"\n\n $aliases = Get-Alias | Sort-Object Name\n foreach ($alias in $aliases) {\n $definition = $alias.Definition\n\n if ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::ReadOnly) {\n }\n elseif ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::Constant) {\n }\n elseif ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::AllScope) {\n }\n else {\n Emit ('Set-Alias -Name \"{0}\" -Value \"{1}\"' -f $alias.Name, $definition)\n }\n }\n\n #Log-Timing \"finalize\"\n",mn=`\nfunction Dump-PowerShellState {\n param(\n [Parameter(Mandatory = $true)]\n [string]$OutputFile\n )\n\n function Emit {\n param([string]$Content)\n Add-Content -Path $OutputFile -Value $Content -Encoding UTF8\n }\n\n if (Test-Path $OutputFile) {\n Remove-Item $OutputFile -Force\n }\n New-Item -Path $OutputFile -ItemType File -Force | Out-Null\n #Log-Timing "file_init"\n${fn}}\n`,gn=`\nfunction Dump-PowerShellState {\n param(\n [Parameter(Mandatory = $true)]\n [string]$OutputFile,\n [string]$Trailer\n )\n\n $__cursorDumpText = New-Object System.Text.StringBuilder\n $__cursorDumpNewLine = [Environment]::NewLine\n function Emit {\n param([string]$Content)\n [void]$__cursorDumpText.Append($Content).Append($__cursorDumpNewLine)\n }\n${fn}\n if ($Trailer) {\n Emit $Trailer\n }\n [System.IO.File]::WriteAllText($OutputFile, $__cursorDumpText.ToString(), (New-Object System.Text.UTF8Encoding ($PSVersionTable.PSVersion.Major -lt 6)))\n}\n`,wn="# cursor-shell-timings ",yn="[long](([DateTime]::UtcNow.Ticks - 621355968000000000) / 10000)",vn="\ntry { [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\ntry { [Console]::InputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\ntry { $global:OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\n",bn=e=>e.map((e=>`'${e}'`)).join(", "),Sn=` # The body of the proxy for Set-Content and Export-Csv. Its param block comes from the\n # cmdlet itself. Every step of its own is guarded, so a failure in the proxy leaves the\n # file as the cmdlet writes it.\n $__cursorProxyBody = @'\nbegin {\n # The file system paths the call writes, each with its own 'bom' or 'nobom', and what each\n # held before the call; the call gets -Encoding only when every path has a decision.\n $__cursorFiles = $null\n $__cursorDecisions = @{}\n $__cursorBefore = @{}\n $__cursorDecided = $false\n # The command line asked for UTF8 by name, for files whose readers take it without a BOM.\n $__cursorAsked = $false\n $__cursorStrip = $false\n $__cursorStopped = $false\n $__cursorScopeBound = $null\n $__cursorInvoked = "$($MyInvocation.InvocationName)"\n # The first 8 KiB of the file and its length; $null for a file that does not exist.\n $__cursorHeadOf = {\n param([string]$__cursorFile)\n if (-not [System.IO.File]::Exists($__cursorFile)) { return $null }\n $__cursorHead = New-Object byte[] 8192\n $__cursorCount = 0\n $__cursorStream = [System.IO.File]::Open($__cursorFile, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite -bor [System.IO.FileShare]::Delete)\n try {\n $__cursorLength = $__cursorStream.Length\n while ($__cursorCount -lt $__cursorHead.Length) {\n $__cursorRead = $__cursorStream.Read($__cursorHead, $__cursorCount, $__cursorHead.Length - $__cursorCount)\n if ($__cursorRead -le 0) { break }\n $__cursorCount += $__cursorRead\n }\n } finally { $__cursorStream.Dispose() }\n return @{ Length = $__cursorLength; Head = $__cursorHead; Count = $__cursorCount }\n }\n # 'bom' or 'nobom' for a file the proxy writes in UTF-8, $null for one it leaves to the\n # cmdlet: the file's own bytes decide when it has content, its extension otherwise.\n $__cursorEncodingOf = {\n param([string]$__cursorFile, $__cursorWas)\n $__cursorExtension = [System.IO.Path]::GetExtension($__cursorFile).ToLowerInvariant()\n if ($__cursorExtension -in @(${bn([".bat",".cmd",".reg",".ini",".inf",".vbs",".vbe",".wsf"])})) { return $null }\n if ([System.IO.Directory]::Exists($__cursorFile)) { return $null }\n if ($null -ne $__cursorWas -and $__cursorWas.Count -gt 0) {\n $__cursorHead = $__cursorWas.Head\n $__cursorEnd = $__cursorWas.Count\n if ($__cursorEnd -ge 3 -and $__cursorHead[0] -eq 0xEF -and $__cursorHead[1] -eq 0xBB -and $__cursorHead[2] -eq 0xBF) { return 'bom' }\n if ($__cursorEnd -ge 2 -and (($__cursorHead[0] -eq 0xFF -and $__cursorHead[1] -eq 0xFE) -or ($__cursorHead[0] -eq 0xFE -and $__cursorHead[1] -eq 0xFF))) { return $null }\n if ($__cursorEnd -eq $__cursorHead.Length) {\n # A full header may end inside a character; that character is left out.\n $__cursorAt = $__cursorEnd - 1\n while ($__cursorAt -gt $__cursorEnd - 4 -and ($__cursorHead[$__cursorAt] -band 0xC0) -eq 0x80) { $__cursorAt-- }\n if ($__cursorHead[$__cursorAt] -ge 0xC0) {\n $__cursorNeed = if ($__cursorHead[$__cursorAt] -ge 0xF0) { 4 } elseif ($__cursorHead[$__cursorAt] -ge 0xE0) { 3 } else { 2 }\n if ($__cursorEnd - $__cursorAt -lt $__cursorNeed) { $__cursorEnd = $__cursorAt }\n }\n }\n # A strict decode throws on bytes that are not UTF-8; a character beyond ASCII takes\n # more bytes than code units, so all-ASCII content is the one that decodes to as many.\n try { $__cursorText = [System.Text.UTF8Encoding]::new($false, $true).GetString($__cursorHead, 0, $__cursorEnd) } catch { return $null }\n if ($__cursorText.Length -lt $__cursorEnd) { return 'nobom' }\n }\n if ($__cursorExtension -in @(${bn([".ps1",".psm1",".psd1"])})) { return 'bom' }\n if ($__cursorExtension -in @(${bn([".py",".pyw",".pyi",".js",".mjs",".cjs",".jsx",".ts",".tsx",".mts",".cts",".go",".rs",".kt",".kts",".scala",".swift",".dart",".rb",".cs",".fs",".fsx",".vb",".razor",".cshtml",".sh",".bash",".zsh",".html",".htm",".css",".scss",".sass",".less",".vue",".svelte",".json",".jsonc",".json5",".yaml",".yml",".toml",".xml",".xsd",".xsl",".xslt",".svg",".csproj",".props",".targets",".graphql",".gql",".proto",".tf",".hcl",".md",".markdown",".mdx",".rst",".adoc",".gitignore",".gitattributes",".gitmodules",".editorconfig",".cursorignore",".cursorindexingignore",".mdc"])})) { return 'nobom' }\n return $null\n }\n # Whether the -Encoding the call bound is the UTF-8 with a BOM that Windows PowerShell names\n # UTF8. PowerShell 7 binds the encoding object of that name, and reaches this only when a\n # test fakes the version.\n $__cursorIsUtf8Bom = {\n param($__cursorEncoding)\n if ($__cursorEncoding -is [System.Text.Encoding]) { return ($__cursorEncoding -is [System.Text.UTF8Encoding] -and $__cursorEncoding.GetPreamble().Length -gt 0) }\n return ("$__cursorEncoding" -eq 'UTF8')\n }\n # Whether a default under $PSDefaultParameterValues can reach this call's -Encoding: under\n # the cmdlet's name, an alias it had when the proxy was built, or the name the call used. A\n # value such a default put in $PSBoundParameters is not one the command line asked for.\n $__cursorHasEncodingDefault = {\n param([string]$__cursorInvoked)\n foreach ($__cursorKey in @($PSDefaultParameterValues.Keys)) {\n $__cursorKeyParts = "$__cursorKey" -split ':', 2\n if ($__cursorKeyParts.Count -ne 2 -or 'Encoding' -notlike $__cursorKeyParts[1].Trim()) { continue }\n foreach ($__cursorName in @(__CURSORNAMES__, $__cursorInvoked)) {\n if ($__cursorName -like $__cursorKeyParts[0].Trim()) { return $true }\n }\n }\n return $false\n }\n # Whether a UTF8 asked for by name is UTF-8 without a BOM for this file: one whose reader\n # rejects a BOM, and that is new, empty or starts with no BOM of any encoding.\n $__cursorTakesNoBom = {\n param([string]$__cursorFile, $__cursorWas)\n if ([System.IO.Directory]::Exists($__cursorFile)) { return $false }\n if ([System.IO.Path]::GetExtension($__cursorFile).ToLowerInvariant() -notin @(${bn([".json",".py",".js",".ts",".sh",".yaml",".toml",".mdc"])}) -and\n [System.IO.Path]::GetFileName($__cursorFile).ToLowerInvariant() -notin @(${bn([".gitignore",".editorconfig"])})) { return $false }\n if ($null -eq $__cursorWas -or $__cursorWas.Count -lt 2) { return $true }\n $__cursorHead = $__cursorWas.Head\n if ($__cursorWas.Count -ge 3 -and $__cursorHead[0] -eq 0xEF -and $__cursorHead[1] -eq 0xBB -and $__cursorHead[2] -eq 0xBF) { return $false }\n if (($__cursorHead[0] -eq 0xFF -and $__cursorHead[1] -eq 0xFE) -or ($__cursorHead[0] -eq 0xFE -and $__cursorHead[1] -eq 0xFF)) { return $false }\n if ($__cursorWas.Count -ge 4 -and $__cursorHead[0] -eq 0 -and $__cursorHead[1] -eq 0 -and $__cursorHead[2] -eq 0xFE -and $__cursorHead[3] -eq 0xFF) { return $false }\n return $true\n }\n # Takes a UTF-8 BOM off the front of the file in place, unless it is to stay and the\n # content has a character beyond ASCII. A file the cmdlet left as it was is not touched.\n $__cursorStripBom = {\n param([string]$__cursorFile, [bool]$__cursorKeepUnlessAscii, $__cursorWas)\n if (-not [System.IO.File]::Exists($__cursorFile)) { return }\n $__cursorStream = $null\n # The cmdlet may still hold the file for a moment after it returns.\n for ($__cursorAttempt = 0; $__cursorAttempt -lt 5 -and $null -eq $__cursorStream; $__cursorAttempt++) {\n try { $__cursorStream = [System.IO.File]::Open($__cursorFile, [System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None) }\n catch [System.IO.FileNotFoundException] { return }\n catch [System.IO.DirectoryNotFoundException] { return }\n catch [System.IO.IOException] { Start-Sleep -Milliseconds 20 }\n catch { return }\n }\n if ($null -eq $__cursorStream) { return }\n try {\n $__cursorBuffer = New-Object byte[] 65536\n if ($null -ne $__cursorWas -and $__cursorWas.Length -eq $__cursorStream.Length) {\n $__cursorCount = 0\n while ($__cursorCount -lt $__cursorWas.Count) {\n $__cursorRead = $__cursorStream.Read($__cursorBuffer, $__cursorCount, $__cursorWas.Count - $__cursorCount)\n if ($__cursorRead -le 0) { break }\n $__cursorCount += $__cursorRead\n }\n if ($__cursorCount -eq $__cursorWas.Count -and [System.Convert]::ToBase64String($__cursorBuffer, 0, $__cursorCount) -eq [System.Convert]::ToBase64String($__cursorWas.Head, 0, $__cursorCount)) { return }\n $__cursorStream.Position = 0\n }\n if ($__cursorStream.Read($__cursorBuffer, 0, 3) -ne 3 -or $__cursorBuffer[0] -ne 0xEF -or $__cursorBuffer[1] -ne 0xBB -or $__cursorBuffer[2] -ne 0xBF) { return }\n if ($__cursorKeepUnlessAscii) {\n while (($__cursorRead = $__cursorStream.Read($__cursorBuffer, 0, $__cursorBuffer.Length)) -gt 0) {\n if ([regex]::IsMatch([System.Text.Encoding]::UTF8.GetString($__cursorBuffer, 0, $__cursorRead), '[^\\x00-\\x7F]')) { return }\n }\n }\n $__cursorReadAt = 3L\n $__cursorWriteAt = 0L\n while ($__cursorReadAt -lt $__cursorStream.Length) {\n $__cursorStream.Position = $__cursorReadAt\n $__cursorRead = $__cursorStream.Read($__cursorBuffer, 0, $__cursorBuffer.Length)\n if ($__cursorRead -le 0) { break }\n $__cursorStream.Position = $__cursorWriteAt\n $__cursorStream.Write($__cursorBuffer, 0, $__cursorRead)\n $__cursorReadAt += $__cursorRead\n $__cursorWriteAt += $__cursorRead\n }\n $__cursorStream.SetLength($__cursorWriteAt)\n } catch { } finally { $__cursorStream.Dispose() }\n }\n try {\n $__cursorBound = $null\n if ($PSBoundParameters.ContainsKey('Path')) { $__cursorBound = @{ Path = $PSBoundParameters['Path'] } }\n elseif ($PSBoundParameters.ContainsKey('LiteralPath')) { $__cursorBound = @{ LiteralPath = $PSBoundParameters['LiteralPath'] } }\n if ($null -ne $__cursorBound) {\n # The file system paths that -Path or -LiteralPath names; none when one is on another\n # provider or a wildcard matches nothing.\n $__cursorLiteral = $__cursorBound.ContainsKey('LiteralPath')\n $__cursorFiles = New-Object System.Collections.Generic.List[string]\n foreach ($__cursorPath in @(@($__cursorBound.Values)[0])) {\n $__cursorProvider = $null\n $__cursorDrive = $null\n if ($__cursorLiteral -or -not [System.Management.Automation.WildcardPattern]::ContainsWildcardCharacters("$__cursorPath")) {\n $__cursorResolved = @($ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath("$__cursorPath", [ref]$__cursorProvider, [ref]$__cursorDrive))\n } else {\n $__cursorResolved = @($ExecutionContext.SessionState.Path.GetResolvedProviderPathFromPSPath("$__cursorPath", [ref]$__cursorProvider))\n }\n if ($null -ne $__cursorProvider -and $__cursorProvider.Name -in @('Variable', 'Function', 'Alias')) { $__cursorScopeBound = $__cursorProvider.Name }\n if ($null -eq $__cursorProvider -or $__cursorProvider.Name -ne 'FileSystem' -or $__cursorResolved.Count -eq 0) { $__cursorFiles = $null; break }\n $__cursorFiles.AddRange([string[]]$__cursorResolved)\n }\n }\n # -WhatIf sets $WhatIfPreference and -Confirm sets $ConfirmPreference in this scope.\n if ($null -ne $__cursorFiles -and $__cursorFiles.Count -gt 0 -and -not $PSBoundParameters.ContainsKey('Encoding') -and\n -not $WhatIfPreference -and $ConfirmPreference -notin @('Low', 'Medium') -and -not $PSBoundParameters.ContainsKey('Stream') -and\n -not $PSBoundParameters.ContainsKey('Filter') -and -not $PSBoundParameters.ContainsKey('Include') -and\n -not $PSBoundParameters.ContainsKey('Exclude')) {\n $__cursorAppend = ($PSBoundParameters.ContainsKey('Append') -and $PSBoundParameters['Append']) -or ($PSBoundParameters.ContainsKey('NoClobber') -and $PSBoundParameters['NoClobber'])\n $__cursorDecided = $true\n $__cursorStrip = $true\n foreach ($__cursorFile in $__cursorFiles) {\n $__cursorBefore[$__cursorFile] = & $__cursorHeadOf $__cursorFile\n $__cursorDecisions[$__cursorFile] = & $__cursorEncodingOf $__cursorFile $__cursorBefore[$__cursorFile]\n if ($null -eq $__cursorDecisions[$__cursorFile]) { $__cursorDecided = $false; break }\n # An append onto a file with content writes no BOM, so there is none to take off.\n if ($__cursorAppend -and $null -ne $__cursorBefore[$__cursorFile] -and $__cursorBefore[$__cursorFile].Length -gt 0) { $__cursorStrip = $false }\n }\n }\n elseif ($null -ne $__cursorFiles -and $__cursorFiles.Count -gt 0 -and $PSBoundParameters.ContainsKey('Encoding') -and\n (& $__cursorIsUtf8Bom $PSBoundParameters['Encoding']) -and -not (& $__cursorHasEncodingDefault $__cursorInvoked) -and\n -not $WhatIfPreference -and $ConfirmPreference -notin @('Low', 'Medium') -and -not $PSBoundParameters.ContainsKey('Stream') -and\n -not $PSBoundParameters.ContainsKey('Filter') -and -not $PSBoundParameters.ContainsKey('Include') -and\n -not $PSBoundParameters.ContainsKey('Exclude')) {\n # The UTF8 the command line asked for is UTF-8 with a BOM on this shell and without\n # one on PowerShell 7. For a file whose reader rejects a BOM, and that has none, it\n # means what it means there: the cmdlet writes its BOM, and the proxy takes it off.\n $__cursorAsked = $true\n foreach ($__cursorFile in $__cursorFiles) {\n $__cursorBefore[$__cursorFile] = & $__cursorHeadOf $__cursorFile\n if (-not (& $__cursorTakesNoBom $__cursorFile $__cursorBefore[$__cursorFile])) { $__cursorAsked = $false; break }\n $__cursorDecisions[$__cursorFile] = 'nobom'\n }\n $__cursorStrip = $__cursorAsked\n }\n } catch { $__cursorDecided = $false; $__cursorAsked = $false }\n if ($__cursorDecided) { $PSBoundParameters['Encoding'] = '__CURSORUTF8__' }\n if ($null -ne $__cursorScopeBound) {\n Write-Warning "__CURSORNAME__ runs through a function in this shell, so an item it writes to the $__cursorScopeBound provider lives in a scope that ends with the call. Use an assignment, a function definition or Set-Alias instead."\n }\n # An error the caller asked to stop on ends the caller too, as it does from the cmdlet: it\n # goes on as it is, as from the proxy PowerShell itself generates, which rethrows everything\n # with 'throw'. Any other terminating error of the cmdlet ends the statement and the caller\n # goes on; ThrowTerminatingError keeps that rule, where 'throw' would end the caller's whole\n # script, and the pipeline it ended is not stepped again. Of the two, only the cmdlet's own\n # terminating error names this function rather than the cmdlet's type in the suffix of its\n # FullyQualifiedErrorId; the record of an error the caller asked to stop on is the cmdlet's.\n try {\n $outBuffer = $null\n if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 }\n $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('__CURSORTARGET__', [System.Management.Automation.CommandTypes]::Cmdlet)\n $scriptCmd = { & $wrappedCmd @PSBoundParameters }\n $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)\n $steppablePipeline.Begin($PSCmdlet)\n } catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n}\nprocess {\n if ($__cursorStopped) { return }\n try { $steppablePipeline.Process($_) }\n catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n}\nend {\n if ($__cursorStopped) { return }\n try { $steppablePipeline.End() }\n catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n if (-not $__cursorStrip -or -not ($__cursorDecided -or $__cursorAsked)) { return }\n try {\n foreach ($__cursorFile in $__cursorFiles) { & $__cursorStripBom $__cursorFile ($__cursorDecisions[$__cursorFile] -eq 'bom') $__cursorBefore[$__cursorFile] }\n } catch { }\n}\n'@\n foreach ($__cursorWriter in @('Set-Content', 'Export-Csv')) {\n $__cursorWriterNames = @($__cursorWriter) + @(Get-Alias -Definition $__cursorWriter -ErrorAction Ignore | ForEach-Object { $_.Name })\n $__cursorHasWriterDefault = $false\n foreach ($__cursorKey in @($PSDefaultParameterValues.Keys)) {\n $__cursorKeyParts = "$__cursorKey" -split ':', 2\n if ($__cursorKeyParts.Count -ne 2 -or 'Encoding' -notlike $__cursorKeyParts[1].Trim()) { continue }\n foreach ($__cursorName in $__cursorWriterNames) {\n if ($__cursorName -like $__cursorKeyParts[0].Trim()) { $__cursorHasWriterDefault = $true }\n }\n }\n if ($__cursorHasWriterDefault) { continue }\n try {\n # A function of this name that a profile defined stays in charge; the proxy is built on the cmdlet alone.\n $__cursorCmdlet = @(Microsoft.PowerShell.Core\\Get-Command -Name $__cursorWriter -ErrorAction Stop)[0]\n if ($__cursorCmdlet.CommandType -eq 'Cmdlet') {\n $__cursorTarget = "$($__cursorCmdlet.ModuleName)\\$($__cursorCmdlet.Name)"\n $__cursorMetadata = New-Object System.Management.Automation.CommandMetadata $__cursorCmdlet\n $__cursorNamesList = @($__cursorWriterNames | ForEach-Object { "'" + $_.Replace("'", "''") + "'" }) -join ', '\n $__cursorProxyText = @(\n '<#', ".ForwardHelpTargetName $__cursorTarget", '.ForwardHelpCategory Cmdlet', '#>',\n [System.Management.Automation.ProxyCommand]::GetCmdletBindingAttribute($__cursorMetadata),\n 'param(', [System.Management.Automation.ProxyCommand]::GetParamBlock($__cursorMetadata), ')',\n 'dynamicparam {', [System.Management.Automation.ProxyCommand]::GetDynamicParam($__cursorMetadata), '}',\n $__cursorProxyBody.Replace('__CURSORTARGET__', $__cursorTarget).Replace('__CURSORNAMES__', $__cursorNamesList).Replace('__CURSORNAME__', $__cursorCmdlet.Name).Replace('__CURSORUTF8__', $__cursorUtf8)\n ) -join [Environment]::NewLine\n # Global, as a profile would define it, so that a module's code reaches it too.\n Microsoft.PowerShell.Management\\Set-Item -LiteralPath "function:global:$__cursorWriter" -Value ([scriptblock]::Create($__cursorProxyText)) -ErrorAction Stop\n }\n } catch { }\n }`,kn=String.raw` ++exports.id=977,exports.ids=[977],exports.modules={"./src/agent/local-executor.ts"(e,t,r){"use strict";r.d(t,{createLocalExecutor:()=>IH});var n=r("node:buffer"),o=r("node:os"),s=r("node:path"),i=r.t(s,2),a=r.n(s),c=r("../proto/dist/generated/agent/v1/agent_pb.js");const l={textDelta:(e,t)=>new c.Uq({messageStartedAtMs:t,message:{case:"textDelta",value:new c.PtE({text:e})}}),toolCallStarted:(e,t,r)=>new c.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"toolCallStarted",value:new c.xuG({callId:e,toolCall:t,modelCallId:r})}}),toolCallCompleted:(e,t,r)=>new c.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"toolCallCompleted",value:new c.LLS({callId:e,toolCall:t,modelCallId:r})}}),toolCallDelta:(e,t,r,n)=>new c.Uq({messageStartedAtMs:n,message:{case:"toolCallDelta",value:new c.I0n({callId:e,toolCallDelta:t,modelCallId:r})}}),thinkingDelta:(e,t,r)=>new c.Uq({messageStartedAtMs:r,message:{case:"thinkingDelta",value:new c.cHB({text:e,thinkingStyle:t})}}),thinkingCompleted:(e,t,r)=>new c.Uq({messageStartedAtMs:t,message:{case:"thinkingCompleted",value:new c.tr3({thinkingDurationMs:e,...!0===r?{narration:!0}:{}})}}),thinkingNote:e=>new c.Uq({message:{case:"thinkingNote",value:new c.Y$k({text:e})}}),taskChild:(e,t,r)=>"thinkingNote"===t.message.case?t:l.toolCallDelta(e,new c.V1v({delta:{case:"taskToolCallDelta",value:new c.aon({interactionUpdate:t})}}),r),userMessageAppended:e=>new c.Uq({messageStartedAtMs:e.startedAtMs,message:{case:"userMessageAppended",value:new c.v$T({userMessage:e})}}),partialToolCall:(e,t,r)=>new c.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"partialToolCall",value:new c.fxF({callId:e,toolCall:t,modelCallId:r})}}),tokenDelta:e=>new c.Uq({message:{case:"tokenDelta",value:new c.Fyz({tokens:e})}}),summary:e=>new c.Uq({message:{case:"summary",value:new c.ECk({summary:e})}}),summaryStarted:()=>new c.Uq({message:{case:"summaryStarted",value:new c.lWT}}),heartbeat:()=>new c.Uq({message:{case:"heartbeat",value:new c.ih1}}),summaryCompleted:(e,t,r)=>new c.Uq({message:{case:"summaryCompleted",value:new c.ZM9({hookMessage:e,failed:t,fallback:r})}}),shellOutputDelta:e=>new c.Uq({message:{case:"shellOutputDelta",value:new c.Nn_({event:e})}}),modelCallCompleted:(e,t)=>new c.Uq({message:{case:"modelCallCompleted",value:new c.c2D({modelCallId:e,inputTokens:BigInt(t.inputTokens),outputTokens:BigInt(t.outputTokens),cacheReadTokens:BigInt(t.cacheReadTokens),cacheWriteTokens:BigInt(t.cacheWriteTokens),...void 0!==t.reasoningTokens?{reasoningTokens:BigInt(t.reasoningTokens)}:{}})}}),turnEnded(e,t){const r=e?.catalogCostCents;return new c.Uq({message:{case:"turnEnded",value:new c.lJj({...e?{inputTokens:BigInt(e.inputTokens),outputTokens:BigInt(e.outputTokens),cacheReadTokens:BigInt(e.cacheReadTokens),cacheWriteTokens:BigInt(e.cacheWriteTokens),reasoningTokens:BigInt(e.reasoningTokens??0)}:{},...void 0!==t?{endedAtMs:t}:{},...void 0!==r&&Number.isFinite(r)?{estimatedCost:new c.QVp({rawCostCents:r,chargedCents:r,source:c.nnk.CATALOG})}:{}})}})},stepStarted:e=>new c.Uq({message:{case:"stepStarted",value:new c.dwJ({stepId:BigInt(e)})}}),toolRequestsListed:e=>new c.Uq({message:{case:"toolRequestsListed",value:new c.BU$({callCount:Math.max(0,e)})}}),voiceCallUtterance:e=>new c.Uq({message:{case:"voiceCallUtterance",value:e}}),stepCompleted:(e,t)=>new c.Uq({message:{case:"stepCompleted",value:new c.Lrv({stepId:BigInt(e),stepDurationMs:BigInt(t)})}}),activeBranchChange:(e,t)=>new c.Uq({message:{case:"activeBranchChange",value:new c.PSN({path:e,branchName:t})}}),feedbackRequest:(e,t,r,n=[],o={})=>new c.Uq({message:{case:"feedbackRequest",value:new c.apn({requestId:e,canonicalModelName:t,categories:[...r],categoryGroups:[...n],title:o.title,negativeTitle:o.negativeTitle,commentPlaceholder:o.commentPlaceholder})}})};class u{constructor(e=0){this.nextId=e}next(){return this.nextId++}peekNext(){return this.nextId}observe(e){Number.isSafeInteger(e)&&e>=this.nextId&&(this.nextId=e+1)}}var d=r("../context/dist/logger.js"),h=r("../metrics/dist/index.js"),p=r("../proto/dist/generated/agent/v1/exec_pb.js"),f=r("../utils/dist/writable-iterable.js");const m=/https?:\/\/\S+/gi,g=/[)"'<>,.;:\]}]$/;function w(e){const{url:t,wrappers:r}=function(e){let t=e.length;for(;t>0&&g.test(e.slice(t-1,t));)t-=1;return{url:e.slice(0,t),wrappers:e.slice(t)}}(e),n=t.search(/[?#]/),o=-1===n?t:t.slice(0,n),s=o.indexOf("//")+2,i=o.slice(s).search(/[/?#]/),a=-1===i?o.length:s+i,c=o.lastIndexOf("@",a-1);return c0&&o.push(`gitErrorCode=${n.gitErrorCode}`),"number"==typeof n.exitCode&&Number.isFinite(n.exitCode)&&o.push(`exitCode=${n.exitCode}`),0===o.length)return e;let s=`${e} [git: ${o.join(" ")}]`;var i,a;return!0===r?.includeStderr&&"string"==typeof n.stderr&&n.stderr.length>0&&(s+=`\n--- git stderr ---\n${a=n.stderr,i=a.replace(m,w),i.length<=2048?i:`${i.slice(0,2048)}… [truncated to 2048 chars]`}`),s}var b=r("../context/dist/core.js");const S=(0,b.cF)(Symbol("machineProfile"),void 0),k=(0,d.h)("SimpleControlledExecManager"),_=(0,h.v5)("agent_exec.controlled.exec.duration_ms",{description:"Duration of controlled exec operations in milliseconds",labelNames:["exec_case"]}),C=(0,h.v5)("agent_exec.controlled.exec.machine_duration_ms",{description:"Duration of grep, shell and hook execs by coarse machine profile",labelNames:["exec_case","cpu_cores","ram_gb","defender_rt"]}),E=new Set(["grepArgs","shellStreamArgs","executeHookArgs"]),x=(0,h.Pu)("agent_exec.controlled.exec.success",{description:"Count of successful controlled exec operations",labelNames:["exec_case"]}),P=(0,h.Pu)("agent_exec.controlled.exec.error",{description:"Count of failed controlled exec operations",labelNames:["exec_case"]}),R={computerUseArgs:"Computer use is not enabled for this environment, so the Computer tool and the computerUse subagent cannot run here. Do not retry computer actions; verify with non-GUI methods (automated tests, shell commands) instead. (No computer-use handler is registered on this exec daemon.)",recordScreenArgs:"Screen recording is not enabled for this environment, so recordings cannot be captured here. Do not retry; skip the recording and present other evidence instead. (No record-screen handler is registered on this exec daemon.)"};class I extends Error{constructor(e){super(e),this.name="ControlledExecDisposedError"}}function T(e){return e instanceof I?"EXEC_BACKEND_UNAVAILABLE":e instanceof Error&&"AgentExecStreamStartTimeoutError"===e.name?"AGENT_EXEC_STREAM_START_TIMEOUT":void 0}class A{constructor(e,t,r){this.exec=e,this.deserializeArgs=t,this.serializeResult=r}handle(e,t){const r=this.deserializeArgs(t);if(void 0===r)return;const{id:n,args:o}=r;return async function*(r){const s=performance.now(),i=[],a=await r.exec.execute(e,o,{execId:t.execId,hookContextCollector:i,deliverAgentStoreConflictNotices:!0===t.acceptHookAdditionalContexts,recordAgentView:!0===t.recordAgentView,refuseUnreadChanges:!0===t.refuseUnreadChanges}),c=r.serializeResult(n,a);c.localExecutionTimeMs=Math.round(Math.max(0,performance.now()-s)),i.length>0&&(c.hookAdditionalContexts=i),yield c}(this)}}class ${constructor(e,t,r){this.exec=e,this.deserializeArgs=t,this.serializeStream=r}handle(e,t){const r=this.deserializeArgs(t);if(void 0===r)return;const{id:n,args:o}=r;return async function*(r){const s=performance.now(),i=[],a=r.exec.execute(e,o,{execId:t.execId,hookContextCollector:i,deliverAgentStoreConflictNotices:!0===t.acceptHookAdditionalContexts});try{for await(const e of a){{const __t3h=globalThis[Symbol.for("@cursor/sdk.shellStreamOutput")];const __t3c=e.event?.case;if(typeof __t3h==="function"&&(__t3c==="stdout"||__t3c==="stderr"))try{__t3h({conversationId:o.conversationId,toolCallId:o.toolCallId,event:{case:__t3c,value:{data:e.event.value.data}}})}catch{}}const t=r.serializeStream(n,e);t.localExecutionTimeMs=Math.round(Math.max(0,performance.now()-s)),yield t}}finally{const e=i.filter((e=>"agentStoreConflict"===e.hookEventName));e.length>0&&(yield new p.yT({id:n,hookAdditionalContexts:e}))}}(this)}}class M{constructor(e){this.handlers=[],this.runningExecs=new Map;const t=e?.includeGitStderrInThrows??!1;this.includeGitStderrInThrows="function"==typeof t?t:()=>t,this.observeResults=e?.observeResults}startResultObserver(e,t,r){if(void 0!==this.observeResults)try{return this.observeResults(e,t,r)}catch{return}}register(e){this.handlers.push(e)}handleControlMessage(e){if("abort"===e.message.case){const t=e.message.value.id,r=this.runningExecs.get(t);r&&r()}}handle(e,t){const[r,n]=e.withCancel();this.runningExecs.set(t.id,n);const o=t.message.case??"unknown";for(const e of this.handlers){const s=e.handle(r,t);if(void 0===s)continue;const i=s,a=(0,f.Jt)();let c;const l=()=>{c=setTimeout((()=>{a.write(new p.$Y({message:{case:"heartbeat",value:new p.VA({id:t.id})}})).then(l).catch((()=>{}))}),3e3)};l();const u=performance.now(),d=this.startResultObserver(r,o,t);return(async()=>{try{for await(const e of i){if(void 0!==d&&e instanceof p.yT)try{d.message(e)}catch{}await a.write(e)}await a.write(new p.$Y({message:{case:"streamClose",value:new p.D9({id:t.id})}})),x.increment(r,1,{exec_case:o})}catch(e){if(e instanceof f.W2)return;P.increment(r,1,{exec_case:o}),await a.write(new p.$Y({message:{case:"throw",value:new p.Fu({id:t.id,error:e instanceof Error?v(e.message,e,{includeStderr:this.includeGitStderrInThrows()}):"Unknown error",stackTrace:e instanceof Error?e.stack:void 0,errorCode:T(e)})}}))}finally{if(void 0!==d)try{d.done()}catch{}const e=performance.now()-u;if(_.histogram(r,e,{exec_case:o}),E.has(o)){const t=r.get(S)?.();void 0!==t&&C.histogram(r,e,{exec_case:o,...t})}clearTimeout(c),a.close(),this.runningExecs.delete(t.id),n()}})(),a}this.runningExecs.delete(t.id),n();const s=t.message.case,i=(void 0===s?void 0:R[s])??`No handler found for server message of type ${s}`;return k.error(e,i,{messageCase:s}),P.increment(e,1,{exec_case:o}),async function*(){yield new p.$Y({message:{case:"throw",value:new p.Fu({id:t.id,error:i})}}),yield new p.$Y({message:{case:"streamClose",value:new p.D9({id:t.id})}})}()}static fromResources(e,t){const r=new M(t);for(const[t,n]of e.entries())t.registerControlledImplementation(n,r);return r}}var D=r("../context/dist/otel.js");async function O(e){const t=e[Symbol.asyncIterator](),r=await t.next();if(r.done)return;const n={async*[Symbol.asyncIterator](){for(;;){const e=await t.next();if(e.done)return;yield e.value}}};return{firstItem:r.value,rest:n}}const F=(0,b.cF)(Symbol("agentExec.remoteExecResultObserverFactory"),void 0),N={message(){},[Symbol.dispose](){}};function L(e){const t=e.get(F);if(void 0===t)return N;let r;try{r=t(e)}catch{return N}return void 0===r?N:{message(e){try{r?.message(e)}catch{r=void 0}},[Symbol.dispose](){const e=r;r=void 0;try{e?.end()}catch{}}}}var j=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},U=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const B=(0,d.h)("ExecutorResource"),W=(0,h.Pu)("agent_exec.hook_additional_context.delivered",{description:"Hook additional_context carriers drained into the caller collector",labelNames:["hook_event_name"]});class H{constructor(e,t,r){this.execManager=e,this.serializeArgs=t,this.deserializeResult=r}async execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=j(n,(0,D.VI)(e.withName("ExecutorResource.execute")),!1),s=o.ctx;void 0!==r?.execId&&o.span.setAttribute("exec.id",r.execId);const i=(0,D.mJ)(s),a=i?new p.Kg(i):void 0,c=this.execManager.createExecInstance(s,(e=>{const n=this.serializeArgs(e,t);return new p.Ye({id:n.id,message:n.message,execId:r?.execId,machineId:r?.machineId,spanContext:a,acceptHookAdditionalContexts:void 0!==r?.hookContextCollector,recordAgentView:r?.recordAgentView,refuseUnreadChanges:r?.refuseUnreadChanges})})),l=await O(c);if(void 0===l)throw new Error("No exec result");let{firstItem:u,rest:d}=l;const h=j(n,L(s),!1),f=e=>{if(h.message(e),void 0!==r?.hookContextCollector&&e.hookAdditionalContexts.length>0){r.hookContextCollector.push(...e.hookAdditionalContexts);for(const t of e.hookAdditionalContexts)W.increment(s,1,{hook_event_name:t.hookEventName})}};f(u);let m=this.deserializeResult(u);for(;void 0===m;){const e=await O(d);if(void 0===e)throw new Error("No result value");u=e.firstItem,d=e.rest,f(u),m=this.deserializeResult(u)}return(async()=>{try{for await(const e of d)f(e)}catch(e){B.info(s,"Ignoring exec stream shutdown during detached drain",{error:e})}})().catch((()=>{})),m}catch(e){n.error=e,n.hasError=!0}finally{U(n)}}}class q{constructor(e,t,r){this.execManager=e,this.serializeArgs=t,this.deserializeStream=r}async*execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=j(n,(0,D.VI)(e.withName("StreamExecutorResource.execute")),!1).ctx,s=(0,D.mJ)(o),i=s?new p.Kg(s):void 0,a=this.execManager.createExecInstance(o,(e=>{const n=this.serializeArgs(e,t);return new p.Ye({id:n.id,message:n.message,execId:r?.execId,machineId:r?.machineId,spanContext:i,acceptHookAdditionalContexts:void 0!==r?.hookContextCollector||!0===r?.deliverAgentStoreConflictNotices})})),c=j(n,L(o),!1);for await(const e of a){c.message(e),void 0!==r?.hookContextCollector&&e.hookAdditionalContexts.length>0&&r.hookContextCollector.push(...e.hookAdditionalContexts);const t=this.deserializeStream(e);void 0!==t&&(yield t)}}catch(e){n.error=e,n.hasError=!0}finally{U(n)}}}function z(e){return Symbol.for(`@anysphere/agent-exec/resource/${e}`)}function G(e,t,r){return{name:e,symbol:z(e),remoteImplementation:t,registerControlledImplementation:r}}class V{constructor(e,t){this.resource=e,this.value=t}}function K(e,t){return[e,t]}function J(e,t){return t}class Z{constructor(){this.resources=new Map}register(e,t){this.resources.set(e.symbol,new V(e,t))}get(e){return J(0,this.resources.get(e.symbol)?.value)}entries(){return Array.from(this.resources.values()).map((e=>[e.resource,e.value]))}}class X{constructor(e,t){this.remoteAccessor=e,this.localResources=new Map;for(const[e,r]of t)this.localResources.set(e.symbol,{resource:e,implementation:r})}get(e){const t=this.localResources.get(e.symbol);return t?J(0,t.implementation):this.remoteAccessor.get(e)}*entries(){for(const{resource:e,implementation:t}of this.localResources.values())yield[e,t];for(const e of this.remoteAccessor.entries())this.localResources.has(e[0].symbol)||(yield e)}}function Q(e){return function(t,r){return new p.Ye({id:t,message:{case:e,value:r}})}}function Y(e){return t=>{if(t.message.case===e)return t.message.value}}function ee(e){return function(t,r){const n={case:e,value:r};return new p.yT({id:t,message:n})}}function te(e){return function(t){if(t.message.case===e)return{id:t.id,args:t.message.value}}}const re=G("shell-stream-executor",(e=>new q(e,Q("shellStreamArgs"),Y("shellStream"))),((e,t)=>{t.register(new $(e,te("shellStreamArgs"),ee("shellStream")))}));var ne=r("../proto/dist/generated/agent/v1/kv_pb.js"),oe=r("../agent-kv/dist/blob-store.js"),se=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const ie=(0,d.h)("ControlledKvManager");function ae(e,t,r){return e?(0,D.F)({traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags??1},t,r):r}function ce(e,t,r,n,o){o<=r||(0,D.xd)(e.withName(`${t}.slow`),{startTime:n,attributes:{durationMs:o,slowThresholdMs:r}},n+o)}const le=(0,h.v5)("agent_kv.controlled.get_blob.duration_ms",{description:"Duration of ControlledKvManager getBlob operations in milliseconds"}),ue=(0,h.v5)("agent_kv.controlled.set_blob.duration_ms",{description:"Duration of ControlledKvManager setBlob operations in milliseconds"});class de{constructor(e,t,r,n={}){this.serverStream=e,this.clientStream=t,this.blobStore=r,this.options=n}async run(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,D.VI)(e.withName("ControlledKvManager.run")),!1).ctx,n=new Set,o=e=>{n.add(e),e.finally((()=>{n.delete(e)}))};try{for await(const e of this.serverStream){const t=performance.now(),n=Date.now();switch(e.message.case){case"getBlobArgs":{const s=e.message.value.blobId;o((async()=>{const o=ae(e.spanContext,"ControlledKvManager.getBlob",r);try{await(this.options.beforeGetBlob?.(o,s));const t=await this.blobStore.getBlob(o,s);await this.clientStream.write(new ne.gm({id:e.id,message:{case:"getBlobResult",value:{blobData:t?(0,oe.Fo)(t):void 0}}}))}catch(t){ie.error(o,"Error handling getBlob",t);const r=t instanceof Error?t.message:String(t);try{await this.clientStream.write(new ne.gm({id:e.id,message:{case:"getBlobResult",value:{blobData:void 0,error:{message:r}}}}))}catch(e){ie.error(o,"Error writing failed getBlobResult",e)}}finally{const e=performance.now()-t;le.histogram(o,e),ce(o,"ControlledKvManager.getBlob",50,n,e)}})());break}case"setBlobArgs":{const s=e.message.value.blobId,i=e.message.value.blobData;o((async()=>{const o=ae(e.spanContext,"ControlledKvManager.setBlob",r);try{await this.blobStore.setBlob(o,s,i),await this.clientStream.write(new ne.gm({id:e.id,message:{case:"setBlobResult",value:{error:void 0}}}))}catch(t){const r=t instanceof Error?t.message:String(t);try{await this.clientStream.write(new ne.gm({id:e.id,message:{case:"setBlobResult",value:{error:{message:r}}}}))}catch(e){ie.error(o,"Error writing setBlobResult",e)}}finally{const e=performance.now()-t;ue.histogram(o,e),ce(o,"ControlledKvManager.setBlob",100,n,e)}})());break}}}}finally{await Promise.allSettled(n)}}catch(e){t.error=e,t.hasError=!0}finally{se(t)}}}function he(e){return e instanceof Error?{abortReasonType:"error",abortReasonName:e.name,abortReasonMessage:e.message}:"string"==typeof e?{abortReasonType:"string",abortReasonMessage:e}:void 0===e?{abortReasonType:"undefined"}:{abortReasonType:typeof e}}var pe=r("../proto/dist/generated/agent/v1/agent_service_pb.js"),fe=r("../proto/dist/generated/agent/v1/shell_exec_pb.js");Error;const me={stateRestoreMs:"client_prep_state_restore_ms",rootPromptRestoreMs:"client_prep_root_prompt_restore_ms",requestContextMs:"client_prep_request_context_ms",systemPromptMs:"client_prep_system_prompt_ms",preTurnSnapshotMs:"client_prep_pre_turn_snapshot_ms",preTurnSnapshotWaitMs:"client_prep_pre_turn_snapshot_wait_ms",preTurnSnapshotBlobWritesMs:"client_prep_pre_turn_snapshot_blob_writes_ms",preTurnSnapshotSerializeMs:"client_prep_pre_turn_snapshot_serialize_ms",firstStepToFirstInvocationMs:"client_prep_first_step_to_first_invocation_ms",promptMessageCount:"client_prep_prompt_message_count",turnCount:"client_prep_turn_count"},ge=Object.keys(me).filter((e=>e in me));function we(e){const t={};for(const r of ge){const n=e[r];void 0!==n&&(t[r]=n)}return t}new WeakMap;var ye=r("../utils/dist/fresh-uuid.js"),ve=r("@bufbuild/protobuf"),be=r("@connectrpc/connect"),Se=r("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/protocol/async-iterable.js"),ke=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class _e{constructor(e,t,r){this.checkpointStream=e,this.checkpointHandler=t,this.ctx=r}async run(){const e={stack:[],error:void 0,hasError:!1};try{const t=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(e,(0,D.VI)(this.ctx.withName("CheckpointController.run")),!1).ctx,r=[];for await(const e of this.checkpointStream){let n;try{n=this.checkpointHandler.handleCheckpoint(t,e.checkpoint,e.metadata)}catch(t){throw e.onSettled?.(),t}r.push(n),void 0!==e.onSettled&&n.then(e.onSettled,e.onSettled)}await Promise.all(r)}catch(t){e.error=t,e.hasError=!0}finally{ke(e)}}}const Ce=(0,d.h)("@anysphere/agent-client:checkpoint-store-waits");class Ee{constructor(e={}){this.options=e,this.inFlight=new Map}noteRouted(e){const t=Pe(e.pendingToolCalls);if(0===t.size)return xe;let r;const n=new Promise((e=>{r=e}));for(const e of t){let t=this.inFlight.get(e);void 0===t&&(t=new Set,this.inFlight.set(e,t)),t.add(n)}return()=>{for(const e of t){const t=this.inFlight.get(e);t?.delete(n),0===t?.size&&this.inFlight.delete(e)}r()}}storedBefore(e,t){const r=this.inFlight.get(t);if(void 0!==r){try{this.options.onExecHeld?.(t)}catch(t){Ce.warn(e,"onExecHeldForCheckpointStore callback failed",{error:String(t)})}return Promise.all(r).then(xe)}}}function xe(){}function Pe(e){const t=new Set;for(const r of e){let e;try{e=JSON.parse(r)}catch{continue}const n=Ie(e)?e.content:void 0;if(!Array.isArray(n))continue;const o=n;for(const e of o)Ie(e)&&"tool-call"===e.type&&"string"==typeof e.toolCallId&&t.add(e.toolCallId)}return t}function Re(e){if("executeHookArgs"===e.message.case)return function(e){const t=e.request?.request;switch(t?.case){case"preToolUse":case"postToolUse":case"postToolUseFailure":return""===t.value.toolUseId?void 0:t.value.toolUseId;case"subagentStart":return""===t.value.toolCallId?void 0:t.value.toolCallId;default:return}}(e.message.value);const t=e.message.value;return Ie(t)&&"string"==typeof t.toolCallId&&""!==t.toolCallId?t.toolCallId:void 0}function Ie(e){return"object"==typeof e&&null!==e}const Te=(0,d.h)("@anysphere/agent-client:exec-checkpoint-gate"),Ae=new Set(["shellArgs","shellStreamArgs","backgroundShellSpawnArgs","forceBackgroundShellArgs","miniSweAgentBashArgs","writeArgs","deleteArgs","mcpArgs","readMcpResourceExecArgs","computerUseArgs","recordScreenArgs","subagentArgs","forceBackgroundSubagentArgs","executeHookArgs"]),$e=new Set(["userMessageAction","resumeAction","backgroundTaskCompletionAction","goalContinuationAction","subscriptionNotificationAction","executePlanAction","asyncAskQuestionCompletionAction"]);function Me(e){const t=e.message.case;return void 0!==t&&Ae.has(t)?Re(e):void 0}const De=e=>e.replace(/[\r\n]/g,"");function Oe(e){return{...void 0!==e.parentRequestId?{"x-parent-request-id":De(e.parentRequestId)}:{},...void 0!==e.rootParentRequestId?{"x-root-parent-request-id":De(e.rootParentRequestId)}:{},...void 0!==e.parentAgentToolCallId?{"x-parent-agent-tool-call-id":De(e.parentAgentToolCallId)}:{},...!0===e.directMetaParentChildSubagent?{"x-direct-meta-parent-child-subagent":"true"}:{}}}const Fe="x-inference-authentication-jwt";function Ne(){const e=globalThis.process?.env,t=e?.INFERENCE_PROXY_JWT?.trim();return void 0===t||""===t||t.startsWith("$")?{}:{[Fe]:t}}class Le extends Error{constructor(e,t){super(`This conversation's data is missing and can't be restored. Start a new chat to continue.${function(e){if(0===e.length)return"";const t=e.slice(0,3).map((e=>e.slice(0,12)));return` (${1===e.length?`missing blob ${t[0]}`:`${e.length} missing blobs: ${t.join(", ")}${e.length>t.length?", …":""}`})`}(e)}`,void 0!==t?.cause?{cause:t.cause}:void 0),this.isUsageError=!0,this.isBlobNotFound=!0,this.name="BlobNotFoundError",this.blobIdHexes=[...e]}}function je(e){return e instanceof Error&&(e instanceof Le||"isBlobNotFound"in e&&!0===e.isBlobNotFound||"BlobNotFoundError"===e.name)}var Ue=r("../proto/dist/generated/aiserver/v1/utils_pb.js"),Be=r("zod/v4");const We="relayedAttemptFailure",He=Be.object({transport:Be.boolean(),stallAborted:Be.boolean(),errorName:Be.string(),connectCode:Be.number().optional(),connectCodeName:Be.string().optional(),connectCause:Be.object({code:Be.union([Be.string(),Be.number()]).optional(),name:Be.string().optional()}).optional(),transportFailureKind:Be.string().optional(),loop:Be.string().optional(),transportMode:Be.string().optional()});function qe(e){const t=e?.details?.additionalInfo[We];if(void 0!==t)try{const e=He.safeParse(JSON.parse(t));return e.success?e.data:void 0}catch{return}}class ze extends Error{constructor(e,t={}){super(e),Object.setPrototypeOf(this,new.target.prototype),this.cause=t.cause,this.requestId=t.requestId,this.displayInfo=t.displayInfo,this.isTransport=t.isTransport}get name(){return this.kind}}class Ge extends ze{get kind(){return"RetriableError"}}class Ve extends ze{constructor(e,t,r={}){super(e,r),this.action=t}get kind(){return"ActionRequiredError"}}class Ke extends ze{get kind(){return"NonRetriableError"}}class Je extends Ke{constructor(e){const t=`This turn's step limit (${e}) needs an in-process agent loop; the network client cannot send it.`;super(t,{displayInfo:{title:"Step limit not supported",detail:t,isRetryable:!1}}),this.maxSteps=e}}class Ze extends ze{get kind(){return"CancelledError"}}const Xe=new Set([Ue.yM.NOT_LOGGED_IN,Ue.yM.AGENT_REQUIRES_LOGIN,Ue.yM.AUTH_TOKEN_NOT_FOUND,Ue.yM.AUTH_TOKEN_EXPIRED,Ue.yM.INVALID_AUTH_ID,Ue.yM.UNAUTHORIZED,Ue.yM.GITHUB_NO_USER_CREDENTIALS,Ue.yM.GITHUB_USER_NO_ACCESS]),Qe=new Set([Ue.yM.FREE_USER_USAGE_LIMIT,Ue.yM.FREE_USER_RATE_LIMIT_EXCEEDED,Ue.yM.PRO_USER_ONLY,Ue.yM.PRO_USER_USAGE_LIMIT,Ue.yM.PRO_USER_RATE_LIMIT_EXCEEDED,Ue.yM.RATE_LIMITED,Ue.yM.RATE_LIMITED_CHANGEABLE,Ue.yM.GENERIC_RATE_LIMIT_EXCEEDED]),Ye=new Set([Ue.yM.USAGE_PRICING_REQUIRED,Ue.yM.USAGE_PRICING_REQUIRED_CHANGEABLE]),et=new Set([Ue.yM.BAD_API_KEY,Ue.yM.BAD_USER_API_KEY,Ue.yM.OUTDATED_CLIENT]),tt=new Set([Ue.yM.USER_ABORTED_REQUEST,Ue.yM.DEBOUNCED]),rt=new Set([Ue.yM.CUSTOM_MESSAGE]),nt=new Map([[be.Code.PermissionDenied,"Permission Denied"]]),ot=["NGHTTP2","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE","socket hang up","Premature close","UND_ERR_SOCKET","ERR_STREAM","protocol error","http/2 stream","ERR_HTTP2_SESSION_ERROR","Session closed with error code","connection aborted","PING timed out","HTTP/2 session not established","HTTP/2 peer not answering","refused to tunnel to","HTTP CONNECT through proxy","Could not connect to proxy"],st=new Set(["ENOTFOUND","EAI_AGAIN","EAI_FAIL","ENODATA","ESERVFAIL","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ECONNABORTED"]),it=new RegExp(`\\b(${[...st].join("|")})\\b`),at=["IMAGE_TOO_LARGE","MAX_TOKENS","CONVERSATION_TOO_LONG","CONTENT_POLICY","DEPRECATED","MAX_MODE_REQUIRED","MODEL_NO_LONGER_SUPPORTED","UNSUPPORTED_REGION","OUTDATED_CLIENT"],ct="x-cursor-inference-request-error-type",lt="AgentWebSocketDeliveryAmbiguousError";function ut(e,t={}){const{requestId:r}=t;if(e instanceof ze)return e;if(dt(e))return function(e,t){const r=pt(e),n=r.code,o=ft(e),s=void 0===o?void 0:function(e){if(void 0===e.details?.additionalInfo[We])return e;const t=e.clone();return void 0!==t.details&&(delete t.details.additionalInfo[We],t.details.equals(new Ue.ej)&&(t.details=void 0)),t}(o),i={title:s?.details?.title,detail:s?.details?.detail,isRetryable:s?.details?.isRetryable,connectCode:n,errorCode:s?.error,inferenceRequestErrorType:mt(r,ct)??mt(e,ct),errorDetails:s},a={cause:e,requestId:t,displayInfo:i,...!0===qe(o)?.transport?{isTransport:!0}:{}};if(n===be.Code.Canceled||n===be.Code.Aborted)return kt(e)?new Ge(e.message,a):new Ze(e.message,a);if(void 0!==s?.error){const t=s.error;if(tt.has(t))return new Ze(vt(e,s),a);const r=s.details?.analyticsMetadata?.actionRequired;if(void 0!==r&&""!==r)return new Ve(vt(e,s),r,a);if(void 0!==Mt(s))return new Ge(vt(e,s),a);if(Xe.has(t))return new Ve(vt(e,s),"login",a);if(Qe.has(t))return new Ve(vt(e,s),"upgrade",a);if(Ye.has(t))return new Ve(vt(e,s),"payment",a);if(et.has(t))return new Ve(vt(e,s),"config",a);if(rt.has(t)&&!0!==s.details?.isRetryable)return new Ke(vt(e,s),a);if(!1===s.details?.isRetryable)return new Ke(vt(e,s),a)}if(n===be.Code.Unauthenticated)return new Ve(e.message,"login",{...a,displayInfo:ht(i,"Sign in required",r)});const c=yt(r);if(Tt.test(c))return new Ve(e.message,"proxy_sign_in",{...a,displayInfo:{...i,title:"Proxy sign-in required",detail:`${c}. Please check your sign-in for this proxy and try again.`,isRetryable:!0}});if(At.test(c))return new Ve(e.message,"proxy_blocked",{...a,displayInfo:{...i,title:"Connection blocked by proxy",detail:`${c}. Your proxy doesn't allow this connection. Please ask your network administrator to allow it and try again.`,isRetryable:!0}});const l=nt.get(n);return void 0===l||!0===s?.details?.isRetryable||kt(e)?new Ge(e.message,a):new Ke(vt(e,s),{...a,displayInfo:ht(i,l,r)})}(e,r);const n=function(e){let t=e;for(let e=0;e<10;e++){if(null==t)return;if(je(t))return t;if("object"!=typeof t||!("cause"in t))return;t=t.cause}}(e);if(void 0!==n)return new Ke(n.message,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Conversation data missing",detail:n.message,isRetryable:!1}});const o=function(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){if(r.name===bt)return r;t.add(r),r=r.cause}}(e);if(void 0!==o)return new Ke(o.message,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Context summarization failed",detail:o.message,isRetryable:!1}});if(function(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){const e="code"in r?r.code:void 0,n="errcode"in r?r.errcode:void 0;if("ENOSPC"===e||"ERR_SQLITE_ERROR"===e&&"number"==typeof n&&13==(255&n))return!0;t.add(r),r=r.cause}return!1}(e))return new Ke(St,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Out of disk space",detail:St,isRetryable:!1}});if(e instanceof Error){if("AbortError"===e.name)return new Ze(e.message,{cause:e,requestId:r});if(e.name===lt)return new Ge(e.message,{cause:e,requestId:r,isTransport:!0});if(kt(e))return new Ge(e.message,{cause:e,requestId:r})}const s=e instanceof Error?e.message:String(e);return new Ge(s,{cause:e instanceof Error?e:void 0,requestId:r})}function dt(e){return null!==e&&"object"==typeof e&&"code"in e&&"name"in e&&("ConnectError"===e.name||"rawMessage"in e&&"string"==typeof e.rawMessage&&"details"in e&&Array.isArray(e.details)&&"findDetails"in e&&"function"==typeof e.findDetails)}function ht(e,t,r){return{...e,title:e.title||t,detail:e.detail||yt(r),isRetryable:e.isRetryable??!1}}function pt(e){let t=e;for(let e=0;e<10&&t.code===be.Code.Unknown;e++){const e=t.cause;if(!dt(e))break;t=e}return t}function ft(e){let t=e;for(let e=0;e<10&&dt(t);e++){try{const e=t.findDetails?.(Ue.vj);if(void 0!==e&&e.length>0)return e[0]}catch{}t=t.cause}}function mt(e,t){const r=e.metadata;if(null===r||"object"!=typeof r||!("get"in r)||"function"!=typeof r.get)return;const n=r.get(t);return"string"==typeof n?n:void 0}function gt(e){let t=e;for(let e=0;e<10&&"object"==typeof t&&null!==t;e++){if(dt(t))return t;t="cause"in t?t.cause:void 0}}function wt(e){const t=gt(e);return void 0===t?void 0:pt(t)}function yt(e){const t=e.rawMessage;return"string"==typeof t?t:e.message.replace(/^\[[a-z_]+\] /,"")}function vt(e,t){if(t?.details){const{title:r,detail:n}=t.details;return r&&n?`${r} ${n}`:r||n||e.message}return e.message}const bt="SummaryPlaceholderRejectedError",St="Out of disk space. Free some space and try again.";function kt(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){t.add(r);const e=`${r.name}: ${r.message}`;if(ot.some((t=>e.includes(t)))||it.test(e))return!0;const n=r.code;if("string"==typeof n&&(ot.some((e=>n.includes(e)))||st.has(n)))return!0;r=r.cause}return!1}function _t(e){return ot.some((t=>e.includes(t)))||it.test(e)}function Ct(e){return e instanceof ze&&e.cause instanceof Error?kt(e.cause):e instanceof Error?kt(e):"string"==typeof e&&_t(e)}function Et(e){return void 0!==e&&e>0}function xt(e){return e+1}function Pt(e){return Object.defineProperty(e,"code",{value:"connection_stalled",enumerable:!0,configurable:!0}),e}function Rt(e){const{cause:t,requestId:r,transportErrorRetries:n,connectCode:o}=e;return Et(n)?Pt(new Ge("Connection stalled repeatedly",{cause:t,requestId:r,displayInfo:{title:"Connection stalled",detail:`The connection stalled ${xt(n)} times. Please check your network connection and try again.`,isRetryable:!0,connectCode:o}})):Pt(new Ge("Connection stalled",{cause:t,requestId:r,displayInfo:{title:"Connection stalled",detail:"The connection stalled. Please try again.",isRetryable:!0,connectCode:o}}))}const It=/^(?:Proxy \S+ refused to tunnel to |HTTP CONNECT through proxy \S+ failed: |Could not connect to proxy \S+: )/,Tt=/^Proxy \S+ refused to tunnel to \S+: 407\b/,At=/^Proxy \S+ refused to tunnel to \S+: 403\b/;function $t(e){let t=e.cause;for(let e=0;e<10&&void 0!==t;e++){if(t instanceof Error&&"AbortError"===t.name)return!0;if(dt(t)&&(t.code===be.Code.Canceled||t.code===be.Code.Aborted))return!0;t=null!==t&&"object"==typeof t&&"cause"in t?t.cause:void 0}return!1}function Mt(e){const t=e?.details?.additionalInfo;if(e?.error!==Ue.yM.RATE_LIMITED||"run_inference_novel_tokens"!==t?.kind||void 0===t.retryAfterMs)return;const r=Number(t.retryAfterMs);return Number.isFinite(r)&&r>=0?r:void 0}var Dt=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Ot=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Ft=(0,d.h)("@anysphere/agent-client:exec-controller");class Nt extends Error{constructor(e){super(e),this.name="LostConnection"}}class Lt{constructor(e,t,r,n){this.serverStream=e,this.clientStream=t,this.controlledExecManager=r,this.checkpointStoreWaits=n}async run(e){const t={stack:[],error:void 0,hasError:!1};try{Dt(t,(0,D.VI)(e.withName("ClientExecController.run")),!1);const r=[],n=t=>{if((0,ve.isMessage)(t,p.Nv))this.controlledExecManager.handleControlMessage(t);else{const n=this.execute(e,t);n.catch((()=>{})),r.push(n)}};let o,s,i=!1;try{try{for await(const t of this.serverStream){const r=(0,ve.isMessage)(t,p.Nv)?void 0:Re(t),a=void 0===r?void 0:this.checkpointStoreWaits?.storedBefore(e,r);if(void 0===o&&void 0===a){n(t);continue}const c=(o??Promise.resolve()).then((async()=>{await a,(0,ve.isMessage)(t,p.Nv)||!i&&!e.canceled?n(t):Ft.info(e,"Dropped an exec queued behind a checkpoint's store",{toolCallId:r})})).catch((e=>{s??={error:e}}));o=c,c.then((()=>{o===c&&(o=void 0)}))}}finally{i=!0}if(await o,void 0!==s)throw s.error;await Promise.all(r)}catch(e){if(e instanceof be.ConnectError&&"protocol error: missing EndStreamResponse"===e.rawMessage)throw new Nt(e.message);if(e instanceof be.ConnectError&&e.code===be.Code.Aborted){const t=e.cause;if(t instanceof Error&&"code"in t&&"string"==typeof t.code&&t.code.includes("ERR_STREAM_WRITE_AFTER_END"))throw new Nt(e.message)}else{if(e instanceof f.W2)throw new Nt(e.message);if(e instanceof be.ConnectError&&e.code===be.Code.Internal){const t=e.cause;if(t instanceof Error&&t.message.includes("NGHTTP2_PROTOCOL_ERROR"))throw new Nt(e.message)}}throw e}}catch(e){t.error=e,t.hasError=!0}finally{Ot(t)}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{let n,o;if(t.spanContext){const r=t.spanContext;n=(0,D.V5)({traceId:r.traceId,spanId:r.spanId,traceFlags:r.traceFlags??1},"exec.handle",e),o=(0,D.fU)(n)}else n=e;Dt(r,o?new D.r2(n,o):void 0,!1);const s=this.controlledExecManager.handle(n,t);for await(const e of s)await this.clientStream.write(e)}catch(e){r.error=e,r.hasError=!0}finally{Ot(r)}}}const jt=(0,d.h)("@anysphere/agent-client:stall-detector"),Ut=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,Bt={nal:"[NAL client stall detector]",local_loop:"[local-loop client stall detector]",module:"[module client stall detector]"},Wt=new Set(["http2","http1_sse","http1_poll","websocket"]);function Ht(e){return void 0===e?"unknown":Wt.has(e)?e:"other"}const qt=(0,h.Pu)("agent_client.stream.stall.count",{description:"Number of bidirectional stream stalls detected",labelNames:["activity_type","message_type","loop","transport_mode"]}),zt=(0,h.v5)("agent_client.stream.stall.duration_ms",{description:"Duration of stream stalls in milliseconds",labelNames:["activity_type","loop","transport_mode"]}),Gt=(0,h.Pu)("agent_client.stream.did_stall",{description:"Number of streams that experienced at least one stall",labelNames:["loop","transport_mode"]}),Vt=(0,h.Pu)("agent_client.stream.total",{description:"Total number of streams monitored",labelNames:["loop","transport_mode"]});class Kt{constructor(){this.handlers=new Map}track(e,t){return this.handlers.set(e,{name:e,state:"started",startedAt:Date.now()}),t.then((t=>{const r=this.handlers.get(e);return r&&(r.state="completed",r.endedAt=Date.now()),t})).catch((t=>{const r=this.handlers.get(e);throw r&&(r.state="errored",r.endedAt=Date.now(),r.error=t instanceof Error?t.message:String(t)),t}))}getHandlerStates(){const e=Date.now(),t={};for(const[r,n]of this.handlers)t[r]={state:n.state,durationMs:(n.endedAt??e)-n.startedAt,error:n.error};return t}}class Jt{constructor(e,t,r){this.lastActivityTime=performance.now(),this.lastMeaningfulActivityTime=performance.now(),this.hasLogged=!1,this.hasLoggedAdvisory=!1,this.hasLoggedHeartbeatOnly=!1,this.hasEverStalled=!1,this.paused=!1,this.disposed=!1,this.activityHistory=[],this.ctx=e,"number"==typeof t?(this.thresholdMs=t,this.advisoryThresholdMs=void 0,this.heartbeatOnlyThresholdMs=3*t,this.onStall=r,this.onStallCallback=void 0,this.handlerTracker=void 0,this.loop="nal",this.readTransportMode=void 0):(this.thresholdMs=t.thresholdMs,this.advisoryThresholdMs=t.advisoryThresholdMs,this.heartbeatOnlyThresholdMs=t.heartbeatOnlyThresholdMs??3*t.thresholdMs,this.onStall=t.onStall,this.onStallCallback=t.onStallCallback,this.handlerTracker=t.handlerTracker,this.loop=t.loop??"nal",this.readTransportMode=t.transportMode),this.logPrefix=Bt[this.loop],this.startTimer(),this.startAdvisoryTimer(),this.startHeartbeatOnlyTimer(),this.onCtxSignalAbort=()=>{this.trackActivity("ctx.signal","abort"),this.abortedAt=performance.now(),this.emitLifecycleLog(`${this.logPrefix} Stream aborted while stall detector active`,"aborted")},e.signal.addEventListener("abort",this.onCtxSignalAbort)}metricLabels(){return{loop:this.loop,transport_mode:Ht(this.readTransportMode?.())}}trackActivity(e,t){const r={type:e,messageType:t};this.lastActivity=r,"inbound_message"===e?this.lastInboundMessage=r:"outbound_write"===e&&(this.lastOutboundMessage=r);const n=this.activityHistory.at(-1);n?.type===e&&n.messageType===t?n.repeat=(n.repeat??1)+1:(this.activityHistory.push(r),this.activityHistory.length>10&&this.activityHistory.shift())}reset(e="inbound_message",t,r=!0){if(this.trackActivity(e,t),"inbound_message"===e){const e=this.hasLogged,t=this.hasLoggedAdvisory,n=this.hasLoggedHeartbeatOnly;e&&(this.hasLogged=!1,this.emitLogAndMetric()),n&&r&&(this.hasLoggedHeartbeatOnly=!1),t&&(this.hasLoggedAdvisory=!1),this.lastActivityTime=performance.now(),r&&(this.lastMeaningfulActivityTime=performance.now()),void 0===this.timer&&this.startTimer(),void 0===this.advisoryTimer&&this.startAdvisoryTimer(),r&&void 0===this.heartbeatOnlyTimer&&this.startHeartbeatOnlyTimer()}}onStreamEnded(){this.trackActivity("stream","ended"),this.streamEndedAt=performance.now()}onClientSentHeartbeat(){this.lastClientSentHeartbeatAt=performance.now()}onServerSentHeartbeat(){this.lastServerSentHeartbeatAt=performance.now()}setPaused(e){if(!this.disposed&&e!==this.paused&&(this.paused=e,!e)){const e=performance.now();this.lastActivityTime=e,this.lastMeaningfulActivityTime=e,void 0===this.timer&&this.startTimer(),void 0===this.advisoryTimer&&this.startAdvisoryTimer(),void 0===this.heartbeatOnlyTimer&&this.startHeartbeatOnlyTimer()}}restartedAfterLoopGap(e,t){const r=performance.now(),n=r-e;return!(n<5e3||t>=e||(this.reportLoopGap(n,r-t),this.lastActivityTime=r,this.lastMeaningfulActivityTime=r,0))}reportLoopGap(e,t){try{jt.info(this.ctx,`${this.logPrefix} Stall check ran late - the process was not running, its windows restart`,this.buildLogMetadata({late_ms:e,window_ms:t,stall_type:"loop_gap"}))}catch(e){console.error("Error in stall detection:",e)}}startTimer(){if(this.disposed||this.thresholdMs<=0||void 0!==this.timer)return;let e=0;const t=t=>{e=performance.now()+t,this.timer=setTimeout(r,t)},r=()=>{if(this.paused||this.restartedAfterLoopGap(e,this.lastActivityTime))return void t(this.thresholdMs);const r=this.thresholdMs-(performance.now()-this.lastActivityTime);if(r<=0)return this.timer=void 0,void this.onStallDetected("no_activity");t(r)};t(this.thresholdMs)}startAdvisoryTimer(){if(this.disposed||void 0===this.advisoryThresholdMs||this.advisoryThresholdMs<=0||void 0!==this.advisoryTimer)return;const e=this.advisoryThresholdMs;let t=0;const r=e=>{t=performance.now()+e,this.advisoryTimer=setTimeout(n,e)},n=()=>{if(this.paused||this.restartedAfterLoopGap(t,this.lastActivityTime))return void r(e);const n=e-(performance.now()-this.lastActivityTime);if(n<=0)return this.advisoryTimer=void 0,void this.onAdvisoryDetected();r(n)};r(e)}startHeartbeatOnlyTimer(){if(this.disposed||this.thresholdMs<=0||this.heartbeatOnlyThresholdMs<=0||void 0!==this.heartbeatOnlyTimer)return;let e=0;const t=t=>{e=performance.now()+t,this.heartbeatOnlyTimer=setTimeout(r,t)},r=()=>{if(this.paused||this.restartedAfterLoopGap(e,this.lastMeaningfulActivityTime))return void t(this.heartbeatOnlyThresholdMs);const r=this.heartbeatOnlyThresholdMs-(performance.now()-this.lastMeaningfulActivityTime);if(r<=0)return this.heartbeatOnlyTimer=void 0,void this.onStallDetected("heartbeat_only");t(r)};t(this.heartbeatOnlyThresholdMs)}buildLogMetadata(e){const t=this.ctx.get(On),r={...e};t?.modelDetails?.displayName&&(r.model_name=t.modelDetails.displayName);const n=performance.now();void 0!==this.abortedAt&&(r.aborted_ago_ms=n-this.abortedAt),void 0!==this.disposedAt&&(r.disposed_ago_ms=n-this.disposedAt),void 0!==this.lastClientSentHeartbeatAt&&(r.last_client_sent_heartbeat_ago_ms=n-this.lastClientSentHeartbeatAt),void 0!==this.lastServerSentHeartbeatAt&&(r.last_server_sent_heartbeat_ago_ms=n-this.lastServerSentHeartbeatAt),void 0!==this.streamEndedAt&&(r.stream_ended_ago_ms=n-this.streamEndedAt),this.lastInboundMessage&&(r.last_inbound_message_type=this.lastInboundMessage.messageType),this.lastOutboundMessage&&(r.last_outbound_message_type=this.lastOutboundMessage.messageType);const o=[];let s;for(let e=this.activityHistory.length-1;e>=0;e--){const{type:t,messageType:r,repeat:n}=this.activityHistory[e];s!==t&&(s?o.push(`[${t}]`):o.push(`[${t}] (MOST RECENT)`),s=t),o.push(`${r}${n?` (x${n})`:""}`)}return r.activities=o.join("\n"),{reqId:t?.requestId,loop:this.loop,stall:r}}onAdvisoryDetected(){if(this.hasLogged||this.hasLoggedAdvisory)return;if(void 0===this.advisoryThresholdMs||this.advisoryThresholdMs<=0)return;const e=performance.now()-this.lastActivityTime;e=this.heartbeatOnlyThresholdMs){if(this.hasLoggedHeartbeatOnly)return;this.hasLoggedHeartbeatOnly=!0,this.reportStall(e,n)}return}if(this.hasLogged)return;this.hasLogged=!0,this.hasLoggedAdvisory=!0;const t=performance.now()-this.lastActivityTime;this.reportStall(e,t)}reportStall(e,t){const r=this.lastActivity,n=this.lastInboundMessage,o=this.lastOutboundMessage,s=this.ctx.get(On);try{const i=this.buildLogMetadata({duration_ms:t,threshold_ms:"heartbeat_only"===e?this.heartbeatOnlyThresholdMs:this.thresholdMs,stall_type:e}),a="heartbeat_only"===e?`${this.logPrefix} Stream receiving heartbeats only - no meaningful data for threshold period`:`${this.logPrefix} Bidirectional stream stall detected - no activity for threshold period`;if(jt.warn(this.ctx,a,i),qt.increment(this.ctx,1,{activity_type:r?.type??"unknown",message_type:r?.messageType??"unknown",...this.metricLabels()}),this.hasEverStalled||(this.hasEverStalled=!0,Gt.increment(this.ctx,1,this.metricLabels())),this.onStallCallback){const t=performance.now(),i={type:e,lastActivityAgoMs:t-this.lastActivityTime,lastMeaningfulActivityAgoMs:t-this.lastMeaningfulActivityTime,lastActivityType:r?.messageType,lastInboundMessageType:n?.messageType,lastOutboundMessageType:o?.messageType,requestId:s?.requestId,modelName:s?.modelDetails?.displayName,streamEnded:void 0!==this.streamEndedAt,aborted:void 0!==this.abortedAt,lastServerHeartbeatAgoMs:void 0!==this.lastServerSentHeartbeatAt?t-this.lastServerSentHeartbeatAt:void 0,lastClientHeartbeatAgoMs:void 0!==this.lastClientSentHeartbeatAt?t-this.lastClientSentHeartbeatAt:void 0,thresholdMs:"heartbeat_only"===e?this.heartbeatOnlyThresholdMs:this.thresholdMs,handlers:this.handlerTracker?.getHandlerStates(),loop:this.loop};try{this.onStallCallback(i)}catch(e){console.error("Error in stall callback:",e)}}}catch(e){console.error("Error in stall detection:",e)}try{this.onStall?.(function(e){const t=new DOMException(`the stall detector cut the stream: ${e}`,"AbortError");return Object.defineProperty(t,"cursorStallCut",{value:!0}),t}("heartbeat_only"===e?`heartbeats alone for ${this.heartbeatOnlyThresholdMs} ms`:`no activity for ${this.thresholdMs} ms`))}catch(e){console.error("Error in onStall callback:",e)}}emitLifecycleLog(e,t){const r=performance.now()-this.lastActivityTime;try{const n=this.buildLogMetadata({duration_ms:r,event_type:t});jt.info(this.ctx,e,n)}catch(e){console.error("Error logging stream lifecycle:",e)}}emitLogAndMetric(){const e=performance.now()-this.lastActivityTime;this.emitLifecycleLog(`${this.logPrefix} Stream activity resumed after stall`,"recovered"),zt.histogram(this.ctx,e,{activity_type:this.lastActivity?.type??"unknown",...this.metricLabels()})}[Symbol.dispose](){this.disposed||Vt.increment(this.ctx,1,this.metricLabels()),this.disposed=!0,this.paused=!1,void 0!==this.timer&&(clearTimeout(this.timer),this.timer=void 0),void 0!==this.advisoryTimer&&(clearTimeout(this.advisoryTimer),this.advisoryTimer=void 0),void 0!==this.heartbeatOnlyTimer&&(clearTimeout(this.heartbeatOnlyTimer),this.heartbeatOnlyTimer=void 0),this.ctx.signal.removeEventListener("abort",this.onCtxSignalAbort),this.trackActivity("disposed","disposed"),this.disposedAt=performance.now(),this.emitLifecycleLog(`${this.logPrefix} Stream stall detector disposed`,"disposed")}}const Zt={now:()=>performance.now(),setTimeout(e,t){const r=setTimeout(e,t);return r.unref?.(),r},clearTimeout(e){clearTimeout(e)}},Xt=(0,h.v5)("agent_client.first_message.event_loop_max_lag_ms",{description:"Longest event-loop block between the network phase start and the first server message of a run's first attempt",labelNames:["loop","transport_mode","first_message_slow"]}),Qt=(0,h.v5)("agent_client.first_message.event_loop_total_lag_ms",{description:"Summed event-loop blocking between the network phase start and the first server message of a run's first attempt",labelNames:["loop","transport_mode","first_message_slow"]}),Yt=(0,h.v5)("agent_client.first_message.network_ms",{description:"Time from the network phase start to the first server message of a run's first attempt, on attempts that sampled event-loop lag",labelNames:["loop","transport_mode","first_message_slow"]});var er=r("../proto/dist/generated/agent/v1/ask_question_tool_pb.js"),tr=r("../proto/dist/generated/agent/v1/create_plan_tool_pb.js"),rr=r("../proto/dist/generated/agent/v1/pr_management_tool_pb.js"),nr=r("../proto/dist/generated/agent/v1/replace_env_tool_pb.js"),or=r("../proto/dist/generated/agent/v1/setup_vm_environment_tool_pb.js"),sr=r("../proto/dist/generated/agent/v1/connect_scm_tool_pb.js"),ir=r("../proto/dist/generated/agent/v1/generate_image_tool_pb.js"),ar=r("../proto/dist/generated/agent/v1/mcp_auth_tool_pb.js"),cr=r("../proto/dist/generated/agent/v1/switch_mode_tool_pb.js"),lr=r("../proto/dist/generated/agent/v1/web_fetch_tool_pb.js"),ur=r("../proto/dist/generated/agent/v1/web_search_tool_pb.js");class dr extends Error{constructor(e){super(`Deferred interaction response requested for query ${e.id} (${e.query.case??"unknown"})`),this.query=e,this.name="DeferredInteractionResponseError",Object.setPrototypeOf(this,new.target.prototype)}}const hr=e=>new c.Y5({id:e,result:{case:"webSearchRequestResponse",value:new ur.lI({result:{case:"approved",value:new ur.XJ}})}}),pr=(e,t)=>new c.Y5({id:e,result:{case:"webSearchRequestResponse",value:new ur.lI({result:{case:"rejected",value:new ur.yc({reason:t??""})}})}}),fr=e=>new c.Y5({id:e,result:{case:"webFetchRequestResponse",value:new lr.fS({result:{case:"approved",value:new lr.Hs}})}}),mr=(e,t)=>new c.Y5({id:e,result:{case:"webFetchRequestResponse",value:new lr.fS({result:{case:"rejected",value:new lr.m$({reason:t??""})}})}}),gr=(e,t)=>new c.Y5({id:e,result:{case:"askQuestionInteractionResponse",value:new c.zT({result:t})}}),wr=e=>new c.Y5({id:e,result:{case:"switchModeRequestResponse",value:new cr.w$({result:{case:"approved",value:new cr.q5}})}}),yr=(e,t)=>new c.Y5({id:e,result:{case:"switchModeRequestResponse",value:new cr.w$({result:{case:"rejected",value:new cr.rA({reason:t??""})}})}}),vr=(e,t)=>new c.Y5({id:e,result:{case:"createPlanRequestResponse",value:new tr.gz({result:t})}}),br=(e,t)=>new c.Y5({id:e,result:{case:"setupVmEnvironmentResult",value:t}}),Sr=(e,t)=>new c.Y5({id:e,result:{case:"replaceEnvResult",value:t}}),kr=(e,t)=>new c.Y5({id:e,result:{case:"prManagementResult",value:t}}),_r=e=>new c.Y5({id:e,result:{case:"mcpAuthRequestResponse",value:new ar.h({result:{case:"approved",value:new ar.D5}})}}),Cr=(e,t)=>new c.Y5({id:e,result:{case:"mcpAuthRequestResponse",value:new ar.h({result:{case:"rejected",value:new ar.OI({reason:t??"Authentication was rejected"})}})}}),Er=(e,t)=>new c.Y5({id:e,result:{case:"connectScmRequestResponse",value:new sr.qG({result:{case:"rejected",value:new sr.lB({reason:t??"Connecting GitHub was skipped"})}})}}),xr=(e,t)=>new c.Y5({id:e,result:{case:"generateImageRequestResponse",value:new ir.vW({result:{case:"approved",value:new ir.l3({description:t??""})}})}}),Pr=(e,t)=>new c.Y5({id:e,result:{case:"generateImageRequestResponse",value:new ir.vW({result:{case:"rejected",value:new ir.Uq({reason:t??""})}})}});class Rr extends Error{constructor(e,t={}){super(e),this.name="InteractionListenerStreamClosedError",this.cause=t.cause,Object.setPrototypeOf(this,new.target.prototype)}}Rr.telemetryName="InteractionListenerStreamClosedError";var Ir=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Tr=(0,d.h)("ClientInteractionController"),Ar=new Set(["askQuestionInteractionQuery","switchModeRequestQuery","mcpAuthRequestQuery","connectScmRequestQuery"]);class $r{constructor(e,t,r,n){this.interactionStream=e,this.interactionListener=t,this.queryResponseStream=r,this.stallSuspender=n,this.pendingHumanQueries=0}async run(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,D.VI)(e.withName("ClientInteractionController.run")),!1);e=r.ctx;let n,o=Promise.resolve();for await(const t of this.interactionStream){const r=()=>"interactionQuery"===t.case?this.handleInteractionQuery(e,t.value):this.handleInteractionUpdate(e,t.value);o=o.then(r).catch((r=>{Tr.error(e,"Error handling interaction message",r,{messageCase:t.case}),n??=r}))}if(await o,void 0!==n)throw n}catch(e){t.error=e,t.hasError=!0}finally{Ir(t)}}async handleInteractionUpdate(e,t){await this.interactionListener.sendUpdate(e,t)}handleInteractionQuery(e,t){const r=void 0!==t.query.case&&Ar.has(t.query.case);let n=!1;const o=()=>{r&&!n&&(n=!0,this.pendingHumanQueries--,0===this.pendingHumanQueries&&this.stallSuspender?.setPaused(!1))};r&&(this.pendingHumanQueries++,1===this.pendingHumanQueries&&this.stallSuspender?.setPaused(!0)),(async()=>this.interactionListener.query(e,t))().catch((r=>{const n=function(e,t){switch(e.query.case){case"webSearchRequestQuery":return pr(e.id,t);case"webFetchRequestQuery":return mr(e.id,t);case"askQuestionInteractionQuery":return gr(e.id,new er.tz({result:{case:"rejected",value:new er.ox({reason:t})}}));case"switchModeRequestQuery":return yr(e.id,t);case"createPlanRequestQuery":return vr(e.id,new tr.bK({result:{case:"error",value:new tr.iY({error:t})}}));case"setupVmEnvironmentArgs":return br(e.id,new or.r$({result:{case:"success",value:new or.JH({})}}));case"replaceEnvArgs":return Sr(e.id,new nr.dV({result:{case:"failure",value:new nr.uq({errorMessage:t,setupLogs:""})}}));case"prManagementRequestQuery":return kr(e.id,new rr.HL({result:{case:"error",value:new rr.K$({error:t})}}));case"mcpAuthRequestQuery":return Cr(e.id,t);case"connectScmRequestQuery":return Er(e.id,t);case"generateImageRequestQuery":return Pr(e.id,t);case void 0:return;default:return e.query}}(t,"The client could not show this request to the user");if(!(n instanceof c.Y5))throw r;return Tr.error(e,"Error handling interaction query; answering with a fail-closed response",{queryCase:t.query.case,error:r}),n})).then((e=>(o(),this.queryResponseStream.write(e)))).catch((t=>{Tr.error(e,"Error handling interaction query",t)})).finally(o)}}async function Mr(e,t){let r;try{r=await e(t.signal)}catch(e){if(t.isCanceled())throw new Ze("User aborted request");throw new Ke("Failed to mint LLM Gateway credential",{cause:e instanceof Error?e:void 0,requestId:t.requestId})}if(void 0===r)throw new Ke("LLM Gateway credential minter returned no credential",{requestId:t.requestId});if(""===r.bearerToken.trim())throw new Ke("LLM Gateway credential minter returned an empty bearer token",{requestId:t.requestId});return new c.Ibo({bearerToken:r.bearerToken})}const Dr=G("request-context-executor",(e=>new H(e,Q("requestContextArgs"),Y("requestContextResult"))),((e,t)=>{t.register(new A(e,te("requestContextArgs"),ee("requestContextResult")))}));var Or=r("../agent-kv/dist/serde.js"),Fr=r("../proto/dist/generated/agent/v1/request_context_exec_pb.js"),Nr=r("../utils/dist/promise-extras.js");const Lr=15728640,jr=(0,h.Pu)("agent_client.request_context_blob.prepared",{description:"Prepared RequestContext blob references"}),Ur=(0,h.v5)("agent_client.request_context_blob.bytes",{description:"Serialized RequestContext bytes staged by the client"}),Br=(0,h.v5)("agent_client.request_context_blob.preparation_ms",{description:"Time to hydrate, serialize, and hash RequestContext"});function Wr(e){switch(e.action.case){case"userMessageAction":case"subscriptionNotificationAction":case"resumeAction":case"executePlanAction":return e.action.value;default:return}}class Hr{constructor(e,t=62914560){this.parent=e,this.maxTransientBytes=t,this.transientBlobs=new Map,this.persistedBlobIds=new Set,this.transientBytes=0}seed(e,t){return this.seedAll([{blobId:e,blobData:t}])}seedAll(e){const t=new Map;for(const{blobId:r,blobData:n}of e)t.set((0,Or.nj)(r),n.byteLength);let r=this.transientBytes;for(const[e,n]of t)r-=this.transientBlobs.get(e)?.byteLength??0,r+=n;if(r>this.maxTransientBytes)return!1;for(const{blobId:t,blobData:r}of e)this.transientBlobs.set((0,Or.nj)(t),r);return this.transientBytes=r,!0}has(e){return this.transientBlobs.has((0,Or.nj)(e))}hasAll(e){return e.every((e=>this.has(e)))}async getBlob(e,t){const r=(0,Or.nj)(t),n=this.transientBlobs.get(r);return void 0===n?await this.parent.getBlob(e,t):n}async persistForRemoteRead(e,t){const r=(0,Or.nj)(t),n=this.transientBlobs.get(r);void 0===n||this.persistedBlobIds.has(r)||(await(0,Nr.O$)((()=>this.parent.setBlob(e,t,n)),2),this.persistedBlobIds.add(r))}async setBlob(e,t,r){await this.parent.setBlob(e,t,r)}async setBlobLocallyOnly(e,t,r){await this.parent.setBlobLocallyOnly(e,t,r)}async flush(e){await this.parent.flush(e)}}async function qr({ctx:e,action:t,resources:r,blobStore:n,mode:o,maxBlobBytes:s,maxInlineDynamicBytes:i=1048576,notesSessionId:a}){const c=performance.now(),l=Wr(t);if(void 0===l)return{kind:"not_applicable"};if("legacy"===o)return t.requestContextParts=void 0,{kind:"legacy"};if(void 0!==t.requestContextParts){const e=void 0===(u=t.requestContextParts)?[]:[u.rulesBlobId,u.skillsBlobId,u.subagentsBlobId,u.mcpsBlobId],r=void 0!==l.requestContext,s=e.length>0&&n.hasAll(e);if(r||s){const e=t.requestContextParts;return"ref_only"===o&&r&&s&&void 0!==e?.dynamicContext&&(l.requestContext=void 0),{kind:"already_prepared"}}}var u;t.requestContextParts=void 0;const d=void 0===l.requestContext,h=l.requestContext??await async function({ctx:e,resources:t,notesSessionId:r}){const n=t.get(Dr),o=await n.execute(e,new Fr._K({notesSessionId:r})),s="success"===o.result.case?o.result.value.requestContext:void 0;if(void 0===s)throw new Error(`Failed to compute request context: ${o.result.case}`);return s}({ctx:e,resources:r,notesSessionId:a}),p=Math.min(Math.max(0,s),Lr),f=await async function({requestContext:e,mode:t,maxBlobBytes:r,maxInlineDynamicBytes:n}){const o=function(e){const t=e.clone();return t.rules=[],t.nonFileRules=[],t.cloudRule=void 0,t.agentSkills=[],t.skillOptions=void 0,t.customSubagents=[],t.tools=[],t.mcpInstructions=[],t.mcpFileSystemOptions=void 0,t.mcpMetaToolOptions=void 0,{dynamicContext:t,rules:new Fr.T3({rules:e.rules.map((e=>e.clone())),nonFileRules:e.nonFileRules.map((e=>e.clone())),cloudRule:e.cloudRule}),skills:new Fr.CB({agentSkills:e.agentSkills.map((e=>e.clone())),skillOptions:e.skillOptions?.clone()}),subagents:new Fr.yb({customSubagents:e.customSubagents.map((e=>e.clone()))}),mcps:new Fr.vB({tools:e.tools.map((e=>e.clone())),mcpInstructions:e.mcpInstructions.map((e=>e.clone())),mcpFileSystemOptions:e.mcpFileSystemOptions?.clone(),mcpMetaToolOptions:e.mcpMetaToolOptions?.clone()})}}(e),s="ref_only"===t?o.dynamicContext.toBinary().byteLength:void 0;if(void 0!==s&&s>n)return;const i=o.rules.toBinary(),a=o.skills.toBinary(),c=o.subagents.toBinary(),l=o.mcps.toBinary(),u=i.byteLength+a.byteLength+c.byteLength+l.byteLength;if(u>r)return;const[d,h,p,f]=await Promise.all([(0,oe.Bk)(i),(0,oe.Bk)(a),(0,oe.Bk)(c),(0,oe.Bk)(l)]),m=[{blobId:d,blobData:i},{blobId:h,blobData:a},{blobId:p,blobData:c},{blobId:f,blobData:l}],g=new Fr.sG({rulesBlobId:d,rulesByteLength:i.byteLength,skillsBlobId:h,skillsByteLength:a.byteLength,subagentsBlobId:p,subagentsByteLength:c.byteLength,mcpsBlobId:f,mcpsByteLength:l.byteLength,dynamicContext:"ref_only"===t?o.dynamicContext:void 0});if("dual"===t)return{kind:"dual",inlineContext:e,byteLength:u,parts:g};if(void 0===s)throw new Error("ref_only request context did not measure dynamic bytes");return{kind:"ref_only",stagedBlobs:m,byteLength:u,parts:g,dynamicByteLength:s}}({requestContext:h,mode:o,maxBlobBytes:p,maxInlineDynamicBytes:Math.min(Math.max(0,i),p)});if(void 0===f)return l.requestContext=h,t.requestContextParts=void 0,jr.increment(e,1,{mode:o,outcome:"oversized"}),{kind:"oversized"};if("ref_only"===f.kind&&!n.seedAll(f.stagedBlobs))return l.requestContext=h,t.requestContextParts=void 0,jr.increment(e,1,{mode:o,outcome:"transient_budget_exceeded"}),{kind:"transient_budget_exceeded"};l.requestContext="dual"===f.kind?f.inlineContext:void 0,t.requestContextParts=f.parts;const m=f.byteLength;return jr.increment(e,1,{mode:o,outcome:d?"hydrated":"inline"}),Ur.histogram(e,m,{mode:o}),Br.histogram(e,performance.now()-c,{mode:o}),{kind:"prepared",byteLength:m,hydrated:d,rulesByteLength:f.parts.rulesByteLength,skillsByteLength:f.parts.skillsByteLength,subagentsByteLength:f.parts.subagentsByteLength,mcpsByteLength:f.parts.mcpsByteLength,dynamicByteLength:"ref_only"===f.kind?f.dynamicByteLength:void 0}}function zr(e){return Object.keys(e.fileContents).length>0}function Gr(e,t){return Object.assign(new(e.getType()),e,t)}function Vr(e){return Gr(e,{fileContents:{}})}function Kr(e){for(const[t]of e.entries())if(t.symbol===Dr.symbol)return e.get(Dr)}var Jr=r("../proto/dist/generated/agent/v1/cursor_rules_pb.js");const Zr=102400;function Xr(e){return"AGENTS.md"===e||"CLAUDE.md"===e||"CLAUDE.local.md"===e}function Qr({content:e,filename:t}){return Buffer.byteLength(e,"utf8")>Zr?function({content:e,filename:t}){const r=Buffer.from(e,"utf8");let n=Zr;for(;128==(192&r.readUInt8(n));)n--;const o=`[truncated: ${t} is ${Math.round(r.length/1024)} KB; only the first 100 KB is included]`;return`${r.subarray(0,n).toString("utf8")}\n\n${o}`}({content:e,filename:t}):e}function Yr(e){const t=/^\s*("(?:[^"\\]|\\.)*"|'(?:[^']|'')*')\s+#/.exec(e);return null!==t?t[1]:/^\s*["']/.test(e)?e.trim():e.replace(/\s#.*$/,"").trim()}function en(e,t){return"description"===e?t.trim():Yr(t)}function tn(e){const t=e.trim();return"true"===t||"false"!==t&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t)}function rn(e){const t=e.trimStart();if(!t.startsWith("---"))return null;const r=t.split("---").filter(Boolean);if(r.length<2)return null;const n=r[0].trim(),o=r.slice(1).join("---").trim(),s={};let i=null,a=null;for(const e of n.split("\n")){const t=e.replace(/\r$/,"");if(/^\s*#/.test(t))continue;const r=t.match(/^\s+-\s+(.*)$/);if(r&&a){let e=Yr(r[1]);(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1));const t=s[a];Array.isArray(t)&&t.push(e);continue}const n=t.startsWith(" ")||t.startsWith("\t");if(i&&n){const e=t.trim(),r=e.indexOf(":");if(-1===r)continue;const n=e.slice(0,r).trim(),o=Yr(e.slice(r+1)),c=tn(o),l=`${i}.${n}`;""===o?(s[l]=[],a=l):"metadata.environments"===l||"metadata.disabledEnvironments"===l||"metadata.scopedTo"===l?(s[l]=String(c).split(",").map((e=>e.trim())).filter(Boolean),a=null):(s[l]=c,a=null);continue}i=null,a=null;const o=t.indexOf(":");if(-1===o)continue;const c=t.slice(0,o).trim(),l=en(c,t.slice(o+1));if(""===l&&"metadata"===c){i=c;continue}if("globs"===c&&""===l){s.globs=[],a="globs";continue}const u=tn(l);s[c]="metadata.environments"!==c&&"metadata.disabledEnvironments"!==c&&"metadata.scopedTo"!==c?u:String(u).split(",").map((e=>e.trim())).filter(Boolean)}return{frontmatter:s,rawFrontmatter:`---\n${n}\n---`,body:o}}function nn(e){const t=e.replace(/\\/g,"/").replace(/^[A-Za-z]:/,(e=>e.toLowerCase())),r=[];for(const e of t.split("/"))""!==e&&"."!==e&&(".."!==e?r.push(e):r.pop());return`${t.startsWith("/")?"/":""}${r.join("/")}`}function on(e,t){return"/"===t?e.length>1:e.startsWith(`${t}/`)}const sn=[[".cursor","skills"],[".cursor","skills-cursor"],[".claude","skills"],[".claude","plugins"],[".codex","skills"],[".grok","skills"],[".agents","skills"],[".cursor","plugins"]];class an{constructor(){this.allowed=!1}observeHeaders(e){this.allowed="1"===e.get("x-cursor-lazy-rule-bodies")}isAllowed(){return this.allowed}}function cn(e){if("success"!==e.result.case)return e;const t=e.result.value,r=t.requestContext;if(void 0===r)return e;const n=function(e){const t=e.env?.workspacePaths??[];let r=!1;const n=e.rules.map((e=>{if(!function(e,t){if(!0===e.bodyOmitted||0===e.content.length||void 0!==e.parseError||e.source!==Jr.gv.UNSPECIFIED||void 0!==e.plugin||void 0!==e.marketplace||void 0!==e.pluginId||void 0!==e.marketplaceId)return!1;if(0===e.scopedTo.length&&0===e.frontmatter.length&&e.content.trimStart().startsWith("---"))return!1;const r=nn(e.fullPath),n=r.startsWith("/"),o=r.split("/").filter((e=>e.length>0)),s=o.at(-1);if(void 0===s||function(e){return"SKILL.md"===e.at(-1)||e.some(((t,r)=>sn.some((([n,o])=>t===n&&e[r+1]===o))))}(o))return!1;const i=t.map(nn);if(!i.some((e=>on(r,e))))return!1;const a=function(e,t){let r=e.length-1;for(let t=e.length-2;t>=0;t--)if(".cursor"===e[t]&&"rules"===e[t+1]){r=t;break}return`${t?"/":""}${e.slice(0,r).join("/")}`}(o,n),c=a!==`${n?"/":""}${o.slice(0,-1).join("/")}`,l=e.type?.type.case;return"fileGlobbed"===l?s.endsWith(".mdc")&&c:"global"===l&&!!(Xr(s)||s.endsWith(".mdc")&&c)&&!i.includes(a)&&i.some((e=>on(a,e)))}(e,t))return e;r=!0;const n=Object.assign(new(e.getType()),e);return n.content=e.content.split("\n").find((e=>e.trim().length>0))??"",n.bodyOmitted=!0,n}));return r?Object.assign(new(e.getType()),e,{rules:n}):e}(r);return n===r?e:new Fr._G({result:{case:"success",value:Object.assign(new(t.getType()),t,{requestContext:n})}})}function ln(e){return void 0!==e&&Number.isFinite(e)&&Number.isInteger(e)}function un(e,t){const{rulesByteLength:r,skillsByteLength:n}=e,{subagentsByteLength:o,mcpsByteLength:s}=e;if(!(ln(r)&&ln(n)&&ln(o)&&ln(s)))return;const i=t?.dynamicByteLength;return{bytes:r+n+o+s+(i??0),bytesSource:"blob_parts",rulesBytes:r,skillsBytes:n,mcpBytes:s,subagentsBytes:o,...ln(i)?{dynamicBytes:i}:{}}}const dn=["alpn_failure","poll_seqno_gap","append_fatal","http_464","http_404_unimplemented","socket_reset","stream_closed_early","idle_deadline","stall","other"],hn=/\bHTTP (\d{3})\b/;function pn(e){const t=e.message;return"string"==typeof t?t:""}function fn(e){return e instanceof Error&&("AbortError"===e.name||e.name===lt)}const mn={serverCap:3,transportCap:10},gn={alpn_failure:"server",poll_seqno_gap:"server",append_fatal:"by_signature",http_464:"server",http_404_unimplemented:"server",socket_reset:"transport",stream_closed_early:"server",idle_deadline:"server",stall:"transport",other:"server"};function wn(e){return{action:"retry",countAsServerError:!0,countAsTransportError:!1,transportFailureKind:e}}function yn(e,t,r){const n=r.attemptRequestId,o=!0===t.endless,s=r.retriesEnabled||o,i=(e,n)=>!o&&(e>=n||void 0!==t.sharedCap&&r.serverErrorRetries+r.transportErrorRetries>=t.sharedCap);let a=e instanceof ze?e:ut(e,{requestId:n});const c=a instanceof Ze&&("owner"===r.abortOrigin||function(e){const t=e.displayInfo?.errorCode;return void 0!==t&&tt.has(t)}(a)),l="stall_detector"===r.abortOrigin&&!c&&(a instanceof Ze||a instanceof Ge),u="owner"===r.abortOrigin&&a instanceof Ge&&$t(a),d=function(e,t,r){return t.stalled?"stall":t.userStop?"other":function(e,t={}){const r=function(e){const t=[],r=new Set;let n=e;for(;"object"==typeof n&&null!==n&&!r.has(n);)r.add(n),t.push(n),n="cause"in n?n.cause:void 0;return t}(e);if(r.some((e=>"cursorBidiAppendFatal"in e)))return"append_fatal";const n=r.map(pn),o=e=>n.some((t=>t.includes(e))),s=function(e){return wt(e)?.code}(e),i=void 0===t.transportMode;if(i&&s===be.Code.Unavailable&&o("ALPN protocol failed to negotiate"))return"alpn_failure";if((i||"http1_poll"===t.transportMode)&&s===be.Code.Unavailable&&o("Unexpected seqno"))return"poll_seqno_gap";const a=n.map((e=>hn.exec(e)?.[1])).find((e=>void 0!==e));return i&&s===be.Code.Unknown&&"464"===a?"http_464":i&&s===be.Code.Unimplemented&&"404"===a?"http_404_unimplemented":s===be.Code.DeadlineExceeded&&function(e){const t=gt(e);return void 0===t?void 0:ft(t)?.error}(e)===Ue.yM.TIMEOUT?"idle_deadline":i&&s===be.Code.Unknown&&o("unsupported content type null")?"stream_closed_early":Ct(e)||function(e){return e instanceof Error&&"isTransport"in e&&!0===e.isTransport}(e)||r.some(fn)?"socket_reset":"other"}(e,r)}(e,{stalled:l,userStop:c||u},{transportMode:r.attemptTransportMode}),h=(e,t={})=>({action:"throw",error:e,...t,transportFailureKind:d}),p=(e,n,{immediateFirstRetry:o})=>s?i(r.transportErrorRetries,t.transportCap)?h(e(),{countAsTransportError:!0}):function(e,t){return{action:"retry",countAsServerError:!1,countAsTransportError:!0,transportFailureKind:e,...t?{noBackoff:!0}:{}}}(d,o&&0===r.transportErrorRetries):h(n(),{countAsTransportError:!0}),f=()=>({cause:a.cause,requestId:n,transportErrorRetries:r.transportErrorRetries,connectCode:a.displayInfo?.connectCode});if(l){if(s&&void 0!==r.stallRetryElapsedMs&&r.stallRetryElapsedMs>=18e4)return h(Rt(f()),{countAsTransportError:!0});const e=p((()=>Rt(f())),(()=>Rt({...f(),transportErrorRetries:void 0})),{immediateFirstRetry:!1});return"retry"===e.action?{...e,stall:!0}:e}if(a instanceof Ze&&!c&&$t(a)&&(a=new Ge(a.message,{cause:a.cause,requestId:n,displayInfo:a.displayInfo,isTransport:!0})),u)return h(new Ze(a.message,{cause:a.cause,requestId:n,displayInfo:a.displayInfo}));if(!0===t.retryAllInference&&(a instanceof Ve||a instanceof Ke)&&function(e){const t=e.displayInfo?.inferenceRequestErrorType;return void 0!==t&&!at.some((e=>e===t))}(a))return i(r.serverErrorRetries,t.serverCap)?h(a):wn(d);if(a instanceof Ze||a instanceof Ve||a instanceof Ke)return h(a);const m=function(e){return Mt(e.displayInfo?.errorDetails)}(a);if(a instanceof Ge&&void 0!==m){const e=(r.rateLimitRetryElapsedMs??0)+m;return!s||!o&&e>3e5?h(a):{action:"retry",countAsServerError:!1,countAsTransportError:!1,transportFailureKind:d,retryAfterMs:m,rateLimit:!0}}if(a instanceof Ge&&(!0===a.isTransport||function(e,t){const r=gn[e];return"by_signature"===r?Ct(t):"transport"===r}(d,a)||"owner"!==r.abortOrigin&&$t(a))){const e=function(e){const t=e.displayInfo,r=t?.title,n=t?.detail;return r&&n?{...t,title:r,detail:n}:void 0}(a);return p((()=>function(e){const{cause:t,requestId:r,transportErrorRetries:n,connectCode:o,ownCopy:s}=e;if(void 0!==s)return new Ge(Et(n)?"Connection failed repeatedly":"Connection failed",{cause:t,requestId:r,displayInfo:{...s,isRetryable:!0,connectCode:o??s.connectCode}});const i=function(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){t.add(r);const e=dt(r)?yt(r):r.message;if(It.test(e))return e;r=r.cause}}(t),a=void 0===i?"Please check your network connection and try again.":"Please check your proxy settings and try again.";return Et(n)?new Ge("Connection failed repeatedly",{cause:t,requestId:r,displayInfo:{title:"Connection failed",detail:`${void 0===i?"":`${i}. `}The connection failed ${xt(n)} times. ${a}`,isRetryable:!0,connectCode:o}}):new Ge("Connection failed",{cause:t,requestId:r,displayInfo:{title:"Connection failed",detail:`${i??"The connection was interrupted"}. ${a}`,isRetryable:!0,connectCode:o}})}({...f(),...void 0===e?{}:{ownCopy:e}})),(()=>a),{immediateFirstRetry:!0})}return s?i(r.serverErrorRetries,t.serverCap)?h(function(e){const{classified:t,requestId:r,serverErrorRetries:n}=e,o=t.displayInfo;return new Ge(t.message,{cause:t.cause,requestId:r,displayInfo:{...o,title:o?.title||"Server error",detail:o?.detail||`The server failed ${xt(n)} times. Please try again, or contact support if the issue persists.`,isRetryable:!0}})}({classified:a,requestId:n,serverErrorRetries:r.serverErrorRetries})):wn(d):h(a)}var vn=r("../proto/dist/generated/agent/v1/mcp_pb.js");const bn=(0,b.cF)(Symbol("agentTransportTimingRecorder"),void 0),Sn=(0,d.h)("@anysphere/agent-client:turn-runner"),kn=1e3,_n=6e4,Cn=(0,h.Pu)("agent_client.turn.retry",{description:"Turn attempts retried by the turn runner",labelNames:["attempt","reason","loop"]});function En(e){return e<=1?"1":2===e?"2":e<=5?"3_5":"gt5"}function xn(e){return!0===e.stall?"stall":!0===e.rateLimit?"rate_limit":e.countAsTransportError?"transport":e.countAsServerError?"server":!0===e.immediate?"speculative":"other"}const Pn=new Set(["textDelta","thinkingDelta","thinkingCompleted","partialToolCall","toolCallDelta","toolCallStarted","toolCallCompleted","tokenDelta"]);function Rn(e){const{message:t}=e;return("textDelta"!==t.case||void 0===t.value||!("isServerNotice"in t.value)||!0!==t.value.isServerNotice)&&Pn.has(t.case??"")}async function In(e,t,r){await new Promise(((n,o)=>{if(t?.aborted)return void o(new Ze("Cancelled during backoff"));const s=new AbortController,i=setTimeout(a,e);function a(){clearTimeout(i),t?.removeEventListener("abort",c),s.abort(),n()}function c(){clearTimeout(i),s.abort(),o(new Ze("Cancelled during backoff"))}t?.addEventListener("abort",c,{once:!0});try{r?.(s.signal)?.then(a,(()=>{}))}catch{}}))}function Tn(e,t){return e.length===t.length&&e.every(((e,r)=>{const n=t[r];return void 0!==n&&e.byteLength===n.byteLength&&e.every(((e,t)=>e===n[t]))}))}function An(e){const{connectCode:t,connectCodeName:r,...n}=e;return void 0===r?n:{...n,connectCode:r}}async function $n(e){const{ctx:t,checkpointHandler:r,runOptions:n,requestId:o,hooks:s,cancellation:i}=e,a=e.originalRequestId??o;let l=kn;const u=async(r,o,s,i,a)=>{if(s||(l=kn),void 0!==e.backoff)return void await e.backoff(r,o,i.retryAfterMs);if(!0===i.rateLimit&&void 0!==i.retryAfterMs){const n=i.retryAfterMs+1e3*Math.random();return e.logging&&Sn.info(t,`[${e.logging.tag}] Waiting out a rate limit`,{attempt:r,retryAfterMs:i.retryAfterMs,selectedDelayMs:n}),void await In(n,o)}const c=s?function(e,t){const r=Math.min(3e5,3*e);return t??kn+(r-kn)*Math.random()}(l,n.fixedRetryDelayMs):function(e,t,r){const n=t?100:kn,o=r??Math.min(n*2**e,_n);return o+(void 0===r?.2*o*Math.random():0)}(r,n.isRunningInTest,n.fixedRetryDelayMs),u=function(e,t){if(void 0===t||t<=e)return e;const r=Math.min(t,_n),n=Math.min(r+.2*r*Math.random(),_n);return Math.max(e,n)}(c,i.retryAfterMs);u!==c&&e.logging&&Sn.info(t,`[${e.logging.tag}] Waiting for Retry-After`,{attempt:r,retryAfterMs:i.retryAfterMs,computedDelayMs:c,selectedDelayMs:u,endlessRetries:s}),s&&(l=c,e.logging&&Sn.info(t,`[${e.logging.tag}] Endless retry delay selected`,{selectedDelayMs:u,attempt:r,retryCategory:i.countAsServerError?"server":"transport",endlessRetries:s}));const{retryWake:d}=n;await In(u,o,void 0===d?void 0:e=>d({error:a,delayMs:u,waitEnded:e}))};let d,h,p,f,m,g,w=e.state,y=e.action,v=0,b=o,S=0,k=0,_=!1,C=0;const E=()=>{_&&(n.onConnectionStateChange?.({state:"connected"}),_=!1)},x=(e,t)=>()=>{e===v&&("progress"===t?m=!0:g=!0,E())},P=e=>({handleCheckpoint:async(t,n,o)=>{e===v&&(m=!0),await r.handleCheckpoint(t,n,o),e===v&&(d=n,h=o?.resumeEligibility??"eligible",E())},getLatestCheckpoint:()=>r.getLatestCheckpoint()});for(;;){if(t.canceled)throw i.toCancelledError(void 0,b);if(d=void 0,h=void 0,m=!1,g=!1,s.beginAttempt?.({attempt:v,originalRequestId:a}),v>0?(b=(0,ye.C)(),await(n.onRetryStarting?.(v,{actionCase:y.action.case,conversationState:w,isResume:"resumeAction"===y.action.case,attemptRequestId:b})),e.logging&&Sn.info(t,`[${e.logging.tag}] Retrying attempt ${v}`,{attempt:v,actionCase:y.action.case,requestId:b,originalRequestId:a}),"resumeAction"===y.action.case&&(await(n.onRetryResuming?.({checkpointState:w,nextAttempt:v,reason:"resume_action"})),e.logging&&Sn.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:v,reason:"resume_action"}))):(e.logging&&Sn.info(t,`[${e.logging.tag}] Initial request`,{attempt:v,actionCase:y.action.case,requestId:b}),!0===e.notifyInitialResume&&"resumeAction"===y.action.case&&(await(n.onRetryResuming?.({checkpointState:w,nextAttempt:v,reason:"resume_action"})),e.logging&&Sn.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:v,reason:"resume_action"}))),t.canceled)throw i.toCancelledError(void 0,b);try{return await s.runAttempt({state:w,action:y,checkpointHandler:P(v),attempt:v,attemptRequestId:b,notifyConnected:E,notifyApplicationProgress:x(v,"progress"),notifyApplicationActivity:x(v,"activity")}),E(),void(e.logging&&Sn.info(t,`[${e.logging.tag}] Request successful`,{attempt:v,actionCase:y.action.case,requestId:b,originalRequestId:a}))}catch(r){if(!0===i.shortCircuit?.(r))throw i.toCancelledError(r,b);const o=!0===n.endlessRetries?.(),E=e.nowMs?.()??Date.now();(m||g)&&(p=void 0,f=void 0);const x=void 0===p?void 0:E-p,P=void 0===f?void 0:E-f;let T=s.classify(r,{attempt:v,attemptRequestId:b,originalRequestId:a,serverErrorRetries:S,transportErrorRetries:k,stallRetryElapsedMs:x,rateLimitRetryElapsedMs:P,endlessRetries:o});if("retry"===T.action){const n=!("resumeAction"===y.action.case&&w.pendingToolCalls.length>0)&&("resumeAction"===y.action.case||!0===e.noProgressGuardCountsReplays&&v>0);void 0!==d?C=0:n&&m&&(C++,C>=2&&(e.logging&&Sn.warn(t,`[${e.logging.tag}] Resume attempts are streaming but not producing checkpoints; stopping automatic resume`,{noProgressResumeFailures:C,attempt:v,requestId:b,originalRequestId:a,errorName:r instanceof Error?r.name:typeof r}),T={action:"throw",error:new Ge("Agent turn stopped after repeated resume attempts made no progress",{cause:r instanceof Error?r:void 0,requestId:b,displayInfo:{title:"Agent stopped retrying",detail:"The connection was interrupted repeatedly without saving progress, so the agent stopped to avoid repeating the same work. Retry to continue from the last saved state.",isRetryable:!0}}),transportFailureKind:T.transportFailureKind}))}const A={...void 0===T.transportFailureKind?{}:{transportFailureKind:T.transportFailureKind},...void 0===e.loop?{}:{loop:e.loop}},$=e.logging?.diagnostics?.(r);if(e.logging){const e="retry"===T.action?`RETRY (countAsServerError=${T.countAsServerError}, countAsTransportError=${T.countAsTransportError})`:`THROW ${T.error.kind}`;Sn.warn(t,`[AGENT_ERROR_DIAGNOSTICS] requestId=${b} originalRequestId=${a} decision=${e}`,{decision:e,willRetry:"retry"===T.action,enableAgentRetries:n.enableAgentRetries??!1,endlessRetries:o,isRunningInTest:n.isRunningInTest??!1,serverErrorRetries:S,transportErrorRetries:k,attempt:v,requestId:b,originalRequestId:a,...A,...$})}if("throw"===T.action){if(0===v){const r={attempt:0,actionCase:y.action.case,error:T.error,requestId:b,originalRequestId:a,enableAgentRetries:!0===n.enableAgentRetries,endlessRetries:o,stallAborted:!1,abortSources:[]};try{await(n.onErrorNotRetried?.(s.buildNonRetriedErrorInfo?.(r)??r))}catch(r){e.logging&&Sn.warn(t,`[${e.logging.tag}] onErrorNotRetried callback failed`,{error:String(r),requestId:b,originalRequestId:a})}}throw e.logging&&Sn.warn(t,`[${e.logging.tag}] Error not retryable`,{...A,...$,attempt:v,actionCase:y.action.case,requestId:b,originalRequestId:a,errorName:T.error.name,...!0===e.logging.includeErrorObjects?{error:T.error}:{},serverErrorRetries:S,transportErrorRetries:k}),T.error}const M=v+1;if("ineligible_terminal_turn"===h)return void(e.logging&&Sn.warn(t,`[${e.logging.tag}] Terminal checkpoint received before retryable error; completing without automatic resume`,{errorName:r instanceof Error?r.name:typeof r,errorMessage:r instanceof Error?r.message:String(r)}));!0!==T.immediate&&(n.onConnectionStateChange?.({state:"reconnecting",attempt:M,trigger:{...A,...s.reconnectTrigger?.(r,T,{originalRequestId:a,failedAttemptRequestId:b,nextAttempt:M})??{originatingRequestId:a,attemptRequestId:b}}}),_=!0),T.countAsServerError&&S++,T.countAsTransportError&&k++,!0===T.stall?p??=E:p=void 0,!0===T.rateLimit?f??=E:f=void 0,v=M;try{Cn.increment(t,1,{attempt:En(M),reason:xn(T),loop:e.loop??"nal"})}catch{}void 0!==d&&(I=d,Tn((R=w).turns,I.turns)&&Tn(R.rootPromptMessagesJson,I.rootPromptMessagesJson)||(l=kn),w=d,y=new c.QFf({action:{case:"resumeAction",value:new c.qKo}})),s.onRetryCommitted?.(),!0===T.immediate||!0===T.noBackoff&&void 0===T.retryAfterMs||await u(v,t.signal,o,T,r)}}var R,I}var Mn=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Dn=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const On=(0,b.cF)(Symbol("agentStreamMetadata"),void 0),Fn=(0,d.h)("@anysphere/agent-client:abort"),Nn=(0,d.h)("@anysphere/agent-client:retry"),Ln=(0,d.h)("@anysphere/agent-client:request-context-blob");async function jn({ctx:e,action:t,resources:r,blobStore:n,options:o,source:s,transportMode:i,notifyBytes:a}){!0===o.omitRequestContextFileContents&&function(e){const t=Wr(e);if(void 0===t)return;const r=t.requestContext;void 0!==r&&zr(r)&&(t.requestContext=Vr(r));const n=e.requestContextParts,o=n?.dynamicContext;void 0!==n&&void 0!==o&&zr(o)&&(e.requestContextParts=Gr(n,{dynamicContext:Vr(o)}))}(t);try{const s=await qr({ctx:e,action:t,resources:r,blobStore:n,mode:i??o.requestContextBlobTransportMode??"legacy",maxBlobBytes:o.requestContextBlobMaxBytes??Lr,maxInlineDynamicBytes:o.requestContextDynamicInlineMaxBytes??1048576,notesSessionId:o.conversationId});if(!0===a){const e=function({prepared:e,parts:t}){return"prepared"===e.kind?un(e,{dynamicByteLength:e.dynamicByteLength}):"already_prepared"===e.kind&&void 0!==t?un(t):void 0}({prepared:s,parts:t.requestContextParts});void 0!==e&&o.onRequestContextBytes?.(e)}}catch(r){t.requestContextParts=void 0,Ln.warn(e,"Failed to prepare request context blob; using legacy fallback",{actionCase:t.action.case,errorName:r instanceof Error?r.name:typeof r,source:s})}}const Un=e=>{const t=[];switch(t.push(e.message.case),e.message.case){case"conversationAction":t.push(e.message.value.action.case);break;case"execClientMessage":case"execClientControlMessage":case"kvClientMessage":case"execServerMessage":case"execServerControlMessage":t.push(e.message.value.message.case);break;case"interactionResponse":t.push(e.message.value.result.case);break;case"interactionUpdate":switch(t.push(e.message.value.message.case),e.message.value.message.case){case"partialToolCall":case"toolCallCompleted":case"toolCallStarted":t.push(e.message.value.message.value.toolCall?.tool.case);break;case"toolCallDelta":t.push(e.message.value.message.value.toolCallDelta?.delta.case)}break;case"interactionQuery":t.push(e.message.value.query.case)}return t.filter((e=>void 0!==e)).join(":")};function Bn(e){if(e instanceof Error)return`${e.name}: ${e.message}`;if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e||"bigint"==typeof e)return String(e);if(null==e)return String(e);try{const t=JSON.stringify(e);return"string"==typeof t?t:"unserializable error"}catch{return"unserializable error"}}async function Wn(e,t,r){for await(const n of t)switch(n.event.case){case"stdout":await r.sendUpdate(e,l.shellOutputDelta({case:"stdout",value:new fe.o0({data:n.event.value.data})}));break;case"stderr":await r.sendUpdate(e,l.shellOutputDelta({case:"stderr",value:new fe.Db({data:n.event.value.data})}));break;case"exit":await r.sendUpdate(e,l.shellOutputDelta({case:"exit",value:new fe.vb({code:n.event.value.code,aborted:n.event.value.aborted})}))}}function Hn(e){return e instanceof Error?e.name:void 0}class qn{constructor(e,t,r={}){this.client=e,this.endpointUrl=t,this.options=r,this.hasStartedStream=!1}async run(e,t,r,n,o,s,i,a,c,l,d){const h={stack:[],error:void 0,hasError:!1};try{if(void 0!==d.maxSteps)throw new Je(d.maxSteps);const g=!0===d.omitRequestContextFileContents?function(e){const t=Kr(e);return void 0===t?e:new X(e,[K(Dr,{execute:async(e,r,n)=>function(e){if("success"!==e.result.case)return e;const t=e.result.value,r=t.requestContext;return void 0!==r&&zr(r)?new Fr._G({result:{case:"success",value:Gr(t,{requestContext:Vr(r)})}}):e}(await t.execute(e,r,n))})])}(s):s,w=!0===d.lazyFileScopedRuleBodies?new an:void 0,y=void 0===w?g:function(e,t){const r=Kr(e);return void 0===r?e:new X(e,[K(Dr,{execute:async(e,n,o)=>{const s=await r.execute(e,n,o);return void 0!==o?.execId&&t.isAllowed()?cn(s):s}})])}(g,w),v=void 0===w?d:{...d,onHeader:e=>{w.observeHeaders(e),d.onHeader?.(e)}},b=new Hr(i),S=d.generationUUID??(0,ye.C)(),k=new u,_=(m=k,p=o,f=e=>{m.observe(e.id)},{sendUpdate:(e,t)=>p.sendUpdate(e,t),query:(e,t)=>(f(t),p.query(e,t)),enqueuePostTurnEndedWork:p.enqueuePostTurnEndedWork?.bind(p),flushPostTurnEndedWork:p.flushPostTurnEndedWork?.bind(p)}),C={sources:[],abortReasonName:void 0,abortReasonMessage:void 0},E=e=>{const t=function(e){const t=gt(e);return void 0===t?void 0:qe(ft(t))}(e),r=C.sources.includes("stall_detector")||!0===t?.stallAborted,n=(o=C.sources).some((e=>"stall_detector"!==e))?"owner":o.includes("stall_detector")?"stall_detector":"none";var o;const s=function(e){const t={errorName:Hn(e)},r=wt(e);if(void 0===r)return t;const n=function(e){if(null!==e&&"object"==typeof e&&"cause"in e)return e.cause}(r),o=function(e){if(null===e||"object"!=typeof e||!("code"in e))return;const t=e.code;return"string"==typeof t||"number"==typeof t?t:void 0}(n),s=Hn(n);return{...t,underlyingConnectError:{code:r.code,codeName:be.Code[r.code],cause:void 0!==o||void 0!==s?{code:o,name:s}:void 0}}}(e),i=s.underlyingConnectError;return{relayed:t,stallAborted:r,abortOrigin:"none"===n&&r?"stall_detector":n,reading:void 0===t?{errorName:s.errorName,connectCode:i?.code,connectCodeName:i?.codeName,connectCause:i?.cause,abortSources:[...C.sources],abortReasonName:C.abortReasonName,...void 0===i?{}:{underlyingConnectError:i}}:{errorName:t.errorName,connectCode:t.connectCode,connectCodeName:t.connectCodeName,connectCause:t.connectCause,...(a=t.loop,"nal"===a||"local_loop"===a||"module"===a?{loop:t.loop}:{}),...void 0===t.transportMode?{}:{transportMode:t.transportMode}}};var a};let x=0,P=0;const R={networkPhaseStartedAt:performance.now()};try{d.onNetworkPhaseStart?.()}catch(t){Nn.warn(e,"onNetworkPhaseStart callback failed",{error:String(t)})}const I=Mn(h,(0,D.VI)(e.withName("networkPhase")),!1);e=I.ctx,await(0,D.MG)(I.span,(()=>$n({ctx:e,state:t,action:r,checkpointHandler:c,runOptions:d,requestId:S,loop:this.options.loop??"nal",notifyInitialResume:!0,logging:{...this.options.retryLogging??{tag:"nal_agent_retries",includeErrorObjects:!0},diagnostics:e=>{const{stallAborted:t,abortOrigin:r,reading:n}=E(e);return{stallAborted:t,abortOrigin:r,...An(n)}}},cancellation:{toCancelledError:()=>new Ze("Request cancelled")},hooks:{beginAttempt:()=>{C.sources=[],C.abortReasonName=void 0,C.abortReasonMessage=void 0,P=++x},runAttempt:async({state:t,action:r,checkpointHandler:o,attempt:s,attemptRequestId:i,notifyConnected:c,notifyApplicationProgress:u,notifyApplicationActivity:d})=>{const h=function(e,t,r){return{sendUpdate:async(n,o)=>{if(t===r())return e.sendUpdate(n,o);"toolCallCompleted"===o.message?.case&&Nn.warn(n,"nal.await_stall.stale_completion_dropped",{attemptGen:t,currentGen:r()})},query:async(n,o)=>{if(t!==r())throw new Ze("Stale query from previous attempt");return e.query(n,o)},enqueuePostTurnEndedWork:e.enqueuePostTurnEndedWork?t=>e.enqueuePostTurnEndedWork(t):void 0,flushPostTurnEndedWork:e.flushPostTurnEndedWork?t=>e.flushPostTurnEndedWork(t):void 0}}(_,P,(()=>x));await this.runInternal(e,t,r,n,h,y,b,a,o,l,v,i,S,k,C,c,u,d,s,R)},classify:(e,t)=>{const{abortOrigin:r,relayed:n}=E(e),o=yn(e,function(e,t,r=mn){const n=function(e){if(void 0!==e&&Number.isFinite(e))return Math.min(Math.max(Math.floor(e),1),100)-1}(e.maxRetries),o=void 0===n?r:{serverCap:n,transportCap:n};return{serverCap:o.serverCap,transportCap:!0===e.isRunningInTest?Math.min(o.transportCap,2):o.transportCap,...void 0===n?{}:{sharedCap:n},endless:t.endlessRetries,retryAllInference:!0===e.retryAllInferenceErrors}}(d,t),{...t,retriesEnabled:d.enableAgentRetries??!1,abortOrigin:r}),s=n?.transportFailureKind;return"string"==typeof(i=s)&&dn.includes(i)?{...o,transportFailureKind:s}:o;var i},buildNonRetriedErrorInfo:e=>({...e,enableAgentRetries:d.enableAgentRetries??!1,stallAborted:E(e.error).stallAborted,abortSources:[...C.sources],abortReasonName:C.abortReasonName,abortReasonMessage:C.abortReasonMessage}),reconnectTrigger:(e,t,r)=>{const{relayed:n,stallAborted:o,reading:s}=E(e),i=e instanceof ze?e:ut(e,{requestId:r.failedAttemptRequestId});return{errorClass:n?.errorName??i.name,connectCode:s.connectCode,connectCodeName:s.connectCodeName,errorCode:i.displayInfo?.errorCode,countAsServerError:t.countAsServerError,countAsTransportError:t.countAsTransportError,stallAborted:o,originatingRequestId:r.originalRequestId,attemptRequestId:r.failedAttemptRequestId,...void 0===s.transportMode?{}:{transportMode:s.transportMode},endpointUrl:this.endpointUrl}},onRetryCommitted:()=>a.reopen()}})))}catch(e){h.error=e,h.hasError=!0}finally{Dn(h)}var p,f,m}async runInternal(e,t,r,n,o,s,i,a,l,u,d,h,m,g,w,y,v,b,S,k,_="agent.request.attempt"){const C={stack:[],error:void 0,hasError:!1};try{const P=e;e=this.options.prepareAttemptContext?.(e,{attempt:S,attemptRequestId:h,originalRequestId:m,runOptions:d})??e;const R=Mn(C,(0,D.VI)(e.withName(_)),!1);R.span.setAttribute("agent.attempt",S),R.span.setAttribute("agent.request_id",h),R.span.setAttribute("agent.original_request_id",m),e=R.ctx,e=(0,D.Mf)(e,"agent.request_id",h),e=(e=(0,D.Mf)(e,"agent.original_request_id",m)).with(On,{requestId:h,rootParentRequestId:d.rootParentRequestId,modelDetails:n});const I=new Set(w.sources);let T=void 0!==w.abortReasonName||void 0!==w.abortReasonMessage;const A=(t,r)=>{if(I.has(t))return;I.add(t),w.sources=[...I];const n=(e=>{const t="string"==typeof e?.abortReasonName?e.abortReasonName:void 0,r="string"==typeof e?.abortReasonMessage?e.abortReasonMessage:void 0;if(void 0!==t||void 0!==r)return{abortReasonName:t,abortReasonMessage:r}})(r);T||void 0===n||(T=!0,w.abortReasonName=n.abortReasonName,w.abortReasonMessage=n.abortReasonMessage),Fn.error(e,"Agent client stream abort",new Error(t),{abortSource:t,requestId:h,conversationId:d.conversationId,...r??{}})};if(e.signal.aborted){const t=e.signal.reason;A("ctx_signal_abort",he(t))}else e.signal.addEventListener("abort",(()=>{const t=e.signal.reason;A("ctx_signal_abort",he(t))}),{once:!0});const[$,O]=e.withCancel();if(a.signal?.aborted){const e=a.signal?.reason;A("conversation_action_abort",he(e)),O()}else a.signal?.addEventListener("abort",(()=>{const e=a.signal?.reason;A("conversation_action_abort",he(e)),O()}),{once:!0});if(e.canceled||$.canceled){const t={ctxCanceled:e.canceled,softCancel:$.canceled};throw A("pre_run_cancel",t),new Ze("User aborted request")}const F=(0,D.VI)(e.withName("createControlledExecManager")),N=M.fromResources(s);F[Symbol.dispose]();const[L,j]=e.withCancel(),U=new Kt,{failThresholdMs:B,advisoryThresholdMs:W}=function(e,t){const r=Ut(e?.failTimeoutMs)??3e4,n=r>0&&!0!==t?.isRunningInTest?Math.max(r,2e4):r,o=Ut(e?.advisoryTimeoutMs);return{failThresholdMs:n,advisoryThresholdMs:void 0!==o&&o>0&&(n<=0||oH,onStall:e=>{A("stall_detector",{thresholdMs:B,advisoryThresholdMs:W}),j(e)},onStallCallback:d.onStall,handlerTracker:U}),!1);let z,G,V;const K=(0,Se.Jt)(),J=new f.F8(K,(e=>(q.reset("outbound_write",Un(e)),e))),Z=Mn(C,(0,D.VI)(e.withName("writeInitialRequest")),!1);let X;const Q=function(e){return new vn.Or({mcpTools:e.map((e=>({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?ve.Value.fromJson(e.inputSchema):void 0,outputSchemaJson:void 0!==e.outputSchema?JSON.stringify(e.outputSchema):void 0})))})}(u),Y=d.requestContextBlobTransportMode??"legacy",ee=0===S&&"userMessageAction"===r.action.case&&0===t.turns.length,te="ref_only"===Y&&ee?"dual":Y,[,ne]=await Promise.all([jn({ctx:e,action:r,resources:s,blobStore:i,options:d,source:"run_request",transportMode:te,notifyBytes:0===S}),void 0===d.mintLlmGatewayCredential?Promise.resolve(void 0):Mr(d.mintLlmGatewayCredential,{signal:$.signal,isCanceled:()=>$.canceled,requestId:h})]),oe={action:r,headers:d.headers??{}},se=this.options.decorateAttempt?.(oe,d)??oe,ie=new c.Mpn({conversationState:t,action:se.action,modelDetails:n,requestedModel:d.requestedModel,clientLlmGatewayCredential:ne,mcpTools:Q,conversationGroupId:d.conversationGroupId,conversationId:d.conversationId,agentSessionId:d.agentSessionId,mcpFileSystemOptions:d.mcpFileSystemOptions,customSystemPrompt:d.customSystemPrompt,systemPromptSpec:d.systemPromptSpec,harness:d.harness,computerUseCoordinateMode:d.computerUseCoordinateMode,subagentTypeName:d.subagentTypeName,excludeWorkspaceContext:d.excludeWorkspaceContext,devRawModelSlug:d.devRawModelSlug,selectedSubagentModels:d.selectedSubagentModels,subagentModelOverrides:d.subagentModelOverrides??[],selectedSubagentModelDetails:d.selectedSubagentModelsLegacy,clientSupportsInlineImages:d.clientSupportsInlineImages,clientSupportsPreviewCard:d.clientSupportsPreviewCard,startedAsNewProject:d.startedAsNewProject,firstProjectOnboarding:d.firstProjectOnboarding,clientSupportsSendToUser:d.clientSupportsSendToUser,clientSupportsRoutedModelUpdate:d.clientSupportsRoutedModelUpdate,emitModelCallUsage:d.emitModelCallUsage,canCreateCloudSubagents:d.canCreateCloudSubagents,suppressSubagentProgressUpdateTool:d.suppressSubagentProgressUpdateTool,transcriptParentConversationId:d.transcriptParentConversationId,runId:m,nextInteractionQueryId:g.peekNext(),voiceCallNotes:d.voiceCallNotes});if(X=J.write(new pe.KS({message:{case:"runRequest",value:ie}})),$.canceled){const t={ctxCanceled:e.canceled,softCancel:$.canceled};throw A("post_write_cancel",t),Z[Symbol.dispose](),new Ze("User aborted request")}const ae={...se.headers,"x-request-id":h,"x-original-request-id":m,...Oe(d),...Ne()};z=(0,D.VI)(e.withName("handshakeEstablishment")),z.span.setAttribute("handshake.firstStreamOnClient",!this.hasStartedStream),this.hasStartedStream=!0;const ce=function(e){return e?.get(bn)}(e)?.startTransportRun(),le=void 0===ce?z.ctx:function(e,t){return e.with(bn,t)}(z.ctx,ce),ue=0===S&&void 0!==d.onTtftBreakdown?k?.networkPhaseStartedAt:void 0;let me;const ge=void 0===ce&&void 0===ue?K:(E=K,x=()=>{me=performance.now(),ce?.markFirstRequestSent(me)},{[Symbol.asyncIterator](){const e=E[Symbol.asyncIterator]();let t=!1;const r={next:()=>(t||(t=!0,x()),e.next())};return void 0!==e.return&&(r.return=t=>e.return(t)),void 0!==e.throw&&(r.throw=t=>e.throw(t)),r}}),ye=this.client.run(le,ge,{signal:L.signal,headers:ae,onHeader:e=>{H=e.get("x-cursor-agent-transport-mode")??void 0,d.onHeader?.(e)},onNetworkStarted:()=>{void 0===G&&(G=performance.now(),0===S&&(V=function(e=Zt,t=25){let r,n=0,o=0,s=e.now()+t;const i=e=>{e<=0||(o+=e,e>n&&(n=e))},a=()=>{const r=e.now();i(r-s),s=r+t,c=e.setTimeout(a,t)};let c=e.setTimeout(a,t);return{stop:()=>(void 0===r&&(e.clearTimeout(c),i(e.now()-s),r={maxLagMs:n,totalLagMs:o}),r)}}()))}}),be=performance.now();let ke;const Ce=t=>{z&&(z.span.setAttribute("handshake.firstMessageHeartbeat",t),void 0!==G&&z.span.setAttribute("handshake.preNetworkMs",G-be),z[Symbol.dispose](),z=void 0),y();const r=performance.now();ke=r,d.onFirstMessage?.(r-be),void 0!==G&&(d.onFirstMessageNetwork?.(r-G),void 0!==V&&(function(e,t){const r={loop:t.loop??"nal",transport_mode:Ht(t.transportMode),first_message_slow:t.firstMessageNetworkMs>=1e3?"true":"false"};Xt.histogram(e,t.reading.maxLagMs,r),Qt.histogram(e,t.reading.totalLagMs,r),Yt.histogram(e,t.firstMessageNetworkMs,r)}(e,{loop:this.options.loop,transportMode:H,firstMessageNetworkMs:r-G,reading:V.stop()}),V=void 0))},xe=()=>{b(),d.onFirstNonHeartbeatResponse?.(performance.now()-be,S)},Re=d.onTtftBreakdown?e=>{const t=performance.now(),r=void 0===ue||void 0===me||"server"!==e.clock?void 0:function(e){const t=Math.min(e.firstRequestTakenAt,e.firstMessageAt);return{requestBuildMs:Math.max(0,e.transportRunCalledAt-e.networkPhaseStartedAt),connectMs:Math.max(0,t-e.transportRunCalledAt),roundTripMs:Math.max(0,e.firstMessageAt-t),firstByteToOutputMs:Math.max(0,e.firstOutputAt-e.firstMessageAt),firstOutputReceivedAtEpochMs:e.firstOutputAtEpochMs}}({networkPhaseStartedAt:ue,transportRunCalledAt:be,firstRequestTakenAt:me,firstMessageAt:ke??t,firstOutputAt:t,firstOutputAtEpochMs:Date.now()});d.onTtftBreakdown(void 0===r?e:{...e,transit:r},S)}:void 0,Ie=!0===this.options.execCheckpointGate?function(e,t,r,n={}){return $e.has(r.action.action.case)?async function*(e,t,r,n){const o=[];let s=0;const i=()=>o.flatMap((e=>void 0===e.toolCallId?[]:[e.toolCallId])),a=e=>{const t=[];for(;o.length>0;){const n=o[0];if(!e&&void 0!==n.toolCallId&&!r.has(n.toolCallId))break;t.push(n.message),o.shift()}return t.length>0&&o.length>0&&(s=n.now()),t},c=()=>{const e=o.filter((e=>"execServerControlMessage"===e.message.message.case)),t=o.filter((e=>"execServerControlMessage"!==e.message.message.case));return o.splice(0,o.length,...t),e.map((e=>e.message))},l=t[Symbol.asyncIterator]();let u=!0;try{for(;;){let t;try{t=await l.next()}catch(e){throw u=!1,yield*c(),e}if(!0===t.done)return u=!1,void(yield*c());const d=t.value,h=d.message;if("execServerMessage"!==h.case&&"execServerControlMessage"!==h.case)if("conversationCheckpointUpdate"!==h.case){if(yield d,o.length>0&&n.now()-s>=n.holdMs){Te.info(e,"No checkpoint named held tool calls on a stream still delivering: handed on as they came",{toolCallIds:i().join(", "),waitedMs:Math.round(n.now()-s)});for(const e of i())r.add(e);yield*a(!0)}}else{for(const e of Pe(h.value.pendingToolCalls))r.add(e);if(yield d,o.length>0){const t=Math.round(n.now()-s),r=a(!1);r.length>0&&Te.debug(e,"Handed held execs on after their checkpoint",{count:r.length,waitedMs:t}),yield*r}}else{const t="execServerMessage"===h.case?Me(h.value):void 0,i=void 0!==t&&!r.has(t);if(0===o.length&&!i){yield d;continue}if(0===o.length&&(s=n.now()),o.push({message:d,toolCallId:i?t:void 0}),i){Te.debug(e,"Held a tool call's exec for the checkpoint that names it",{toolCallId:t});try{n.onHeld?.(t)}catch(t){Te.warn(e,"onExecHeldForCheckpoint callback failed",{error:String(t)})}}}}}catch(e){if(u){u=!1;try{await(l.return?.())}catch{}}throw e}finally{o.length>0&&Te.info(e,"The stream ended before a checkpoint named held tool calls: dropped, never run",{toolCallIds:i().join(", ")}),u&&await(l.return?.())}}(e,t,Pe(r.state.pendingToolCalls),{holdMs:n.holdMs??5e3,now:n.now??(()=>performance.now()),onHeld:n.onHeld}):t}(e,ye,{action:se.action,state:t},void 0===this.options.onExecHeldForCheckpoint?{}:{onHeld:this.options.onExecHeldForCheckpoint}):ye,Ae=!0===this.options.execAfterCheckpointStored||!0===this.options.execCheckpointGate?new Ee(void 0===this.options.onExecHeldForCheckpointStore?{}:{onExecHeld:this.options.onExecHeldForCheckpointStore}):void 0,{interactionStream:De,execStream:Fe,checkpointStream:Le,kvStream:je,done:Ue}=function(e,t,r,n,o,s,i,a,c,l){const u=(0,Se.Jt)(),d=(0,Se.Jt)(),h=(0,Se.Jt)(),p=(0,Se.Jt)();let f=!1,m=!1,g=!1;return{interactionStream:u,execStream:d,checkpointStream:h,kvStream:p,done:async function(){let w,y,v=!1,b=!1;try{for await(const o of t){if(void 0!==o.ttftBreakdown){const t=o.ttftBreakdown;try{a?.({serverFirstTokenMs:t.serverFirstTokenMs,preStreamSetupMs:t.preStreamSetupMs,waitForFirstEventMs:t.waitForFirstEventMs,providerTtftMs:t.providerTtftMs,slowPoolWaitMs:t.slowPoolWaitMs,...void 0===t.clientPrepMs?{}:{clientPrepMs:t.clientPrepMs},...void 0===t.clientPrepLegs?{}:{clientPrepLegs:we(t.clientPrepLegs)},...void 0===t.preHandlerMs?{}:{preHandlerMs:t.preHandlerMs},clock:t.clientClock?"client":"server"})}catch(t){Nn.warn(e,"onTtftBreakdown callback failed",{error:String(t)})}}const t="interactionUpdate"===o.message.case&&"heartbeat"===o.message.value.message.case;if(f||(f=!0,n(t)),t)r.onServerSentHeartbeat(),r.reset("inbound_message","heartbeat");else{if(!m){m=!0;try{i?.()}catch(t){Nn.warn(e,"onFirstNonHeartbeatMessage callback failed",{error:String(t)})}}if(!g&&"interactionUpdate"===o.message.case&&Rn(o.message.value)){g=!0;try{l?.()}catch(t){Nn.warn(e,"onFirstModelOutput callback failed",{error:String(t)})}}r.reset("inbound_message",Un(o))}if("interactionUpdate"===o.message.case&&"turnEnded"===o.message.value.message.case&&(v=!0),"interactionUpdate"!==o.message.case&&"interactionQuery"!==o.message.case||await u.write(o.message).catch((()=>{})),"execServerMessage"!==o.message.case&&"execServerControlMessage"!==o.message.case||await d.write(o.message.value),"conversationCheckpointUpdate"===o.message.case){const e=v?"ineligible_terminal_turn":"eligible";"ineligible_terminal_turn"===e&&(b=!0);const t=c?.noteRouted(o.message.value);try{await h.write({checkpoint:o.message.value,metadata:{resumeEligibility:e},...void 0===t?{}:{onSettled:t}})}catch(e){throw t?.(),e}}"kvServerMessage"===o.message.case&&await p.write(o.message.value)}r.onStreamEnded()}catch(e){w=e}finally{if(y=w,v&&b&&void 0!==w&&!o?.aborted&&!s?.aborted&&function(e){const t=e instanceof ze?e:ut(e);return t instanceof Ge&&function(e){return!0===e.isTransport||(e.cause instanceof Error?kt(e.cause):_t(e.message))}(t)}(w)&&(Nn.debug(e,"Ignoring transport close after terminal agent stream",{caughtError:w instanceof Error?`${w.name}: ${w.message}`:String(w)}),r.onStreamEnded(),y=void 0),v||o?.aborted||s?.aborted){if(!v&&!o?.aborted){const t=`Stream ended without turnEnded, abort signals: signal.aborted=${o?.aborted}, parentSignal.aborted=${s?.aborted}; firstMessageFired=${f}`;Nn.warn(e,t)}}else{const t="Stream ended without turnEnded — connection likely dropped mid-stream";void 0===w?(Nn.warn(e,t),y=new Ge(t,{isTransport:!0})):w instanceof Error&&"[aborted] aborted"===w.message?(Nn.warn(e,`${t}; retrying caught [aborted] aborted error`),y=new Ge(t,{cause:w,isTransport:!0})):Nn.warn(e,`${t}; caught non-retriable stream error, rethrowing as-is`,{caughtError:Bn(w)})}u.close(),d.close(),h.close(),p.close()}if(void 0!==y)throw y}()}}(e,Ie,q,Ce,$.signal,e.signal,xe,Re,Ae,v);let Be;const We={handleCheckpoint:async(e,t,r)=>{await l.handleCheckpoint(e,t,r),Be=r?.resumeEligibility??"eligible"},getLatestCheckpoint:()=>l.getLatestCheckpoint()};Z[Symbol.dispose]();const He=5e3;let qe;const Ve=()=>{qe=setTimeout((()=>{J.write(new pe.KS({message:{case:"clientHeartbeat",value:new pe.kA}})).then((()=>q.onClientSentHeartbeat()),(()=>{})),Ve()}),He)},Je=()=>{void 0!==qe&&(clearTimeout(qe),qe=void 0)};Ve();try{let t;if("shellCommandAction"===r.action.case&&r.action.value.execId){const n=r.action.value,i=new fe.a({command:n.shellCommand?.command||"",parsingResult:new fe.HO,skipApproval:!0}),a=s.get(re).execute(e,i,{execId:n.execId}),c=new $r(De,o,new f.F8(J,(e=>new pe.KS({message:{case:"interactionResponse",value:e}}))),q);t={run:async e=>{await Promise.all([U.track("handleShellStream",Wn(e,a,o)),U.track("interactionController",c.run(e))])}}}else{const e=new $r(De,o,new f.F8(J,(e=>new pe.KS({message:{case:"interactionResponse",value:e}}))),q);t={run:async t=>{await U.track("interactionController",e.run(t))}}}void 0!==X&&await Promise.race([X,Ue.catch((()=>{}))]);const c=new f.F8(J,(e=>{if((0,ve.isMessage)(e,p.yT))return new pe.KS({message:{case:"execClientMessage",value:e}});if((0,ve.isMessage)(e,p.$Y))return new pe.KS({message:{case:"execClientControlMessage",value:e}});throw new Error(`Unknown exec message (type: ${(0,ve.isMessage)(e)?e.getType().typeName:typeof e})`)})),l=new Lt(Fe,c,N,Ae),S=new de(je,new f.F8(J,(e=>new pe.KS({message:{case:"kvClientMessage",value:e}}))),i,{beforeGetBlob:async(e,t)=>i.persistForRemoteRead(e,t)}),k=new _e(Le,We,e);let _,C;const E={promise:new Promise(((e,t)=>{_=e,C=t})),resolve:_,reject:C};$.canceled?(E.resolve(),De.close()):$.signal.addEventListener("abort",(()=>{E.resolve(),De.close()}),{once:!0}),l.run($).then(E.resolve).catch(E.reject);const x=Promise.allSettled([U.track("streamSplitter",Ue.finally((()=>{Je(),a.close(),c.close()}))),U.track("execHandler",E.promise),t.run(e),U.track("checkpointController",k.run()),U.track("kvHandler",S.run(e)),U.track("conversationActionManager",a.run(e,{write:async t=>{await jn({ctx:e,action:t,resources:s,blobStore:i,options:d,source:"queued_action"}),await J.write(new pe.KS({message:{case:"conversationAction",value:t}}))}}))]);let R,I;const T={promise:new Promise(((e,t)=>{R=e,I=t})),resolve:R,reject:I};x.then(T.resolve).catch(T.reject),e.canceled?T.reject(new Ze("User aborted request")):e.signal.addEventListener("abort",(()=>T.reject(new Ze("User aborted request"))),{once:!0});const A=()=>{e.signal.aborted?j():function(e){const t=e.lingerMs??6e3;return new Promise((r=>{let n=!1;const o=e=>{n||(n=!0,clearTimeout(s),r(e))},s=setTimeout((()=>o("linger_timed_out")),t);e.done.then((()=>o("stream_ended")),(()=>o("stream_ended")))}))}({done:Ue,lingerMs:d.softCancelLingerMs}).then((t=>{Nn.info(e,"Soft-cancel transport linger finished",{outcome:t,requestId:h}),j()}))};$.canceled?(A(),T.reject(new Ze("User aborted request"))):$.signal.addEventListener("abort",(()=>{A(),T.reject(new Ze("User aborted request"))}),{once:!0});const M=await T.promise,D=M[0],O=M[1],F=M[3],L=e=>e.reason instanceof Error?`${e.reason.name}: ${e.reason.message}`:String(e.reason);if("rejected"===F.status)throw new Ke("Checkpoint persistence failed",{cause:F.reason instanceof Error?F.reason:void 0,requestId:h,displayInfo:{title:"Checkpoint persistence failed",detail:L(F),isRetryable:!1}});const B="ineligible_terminal_turn"===Be;if(B){const t={..."rejected"===D.status?{streamSplitter:L(D)}:{},..."rejected"===O.status?{execHandler:L(O)}:{}};Object.keys(t).length>0&&Nn.debug(e,"Ignoring handler errors after terminal checkpoint",t)}if("rejected"===D.status&&!B)throw D.reason;if("rejected"===O.status&&!B)throw O.reason;$.canceled||await this.processUnprocessedMessages(P,a,We,n,o,s,i,u,d,h,m,g,w,q,y,v,b)}finally{Je(),V?.stop(),V=void 0,z&&(z[Symbol.dispose](),z=void 0)}}catch(e){C.error=e,C.hasError=!0}finally{Dn(C)}var E,x}async processUnprocessedMessages(e,t,r,n,o,s,i,a,l,u,d,h,p,f,m,g,w){if(!t.hasUnprocessedMessages())return;const y=t.getUnprocessedUserMessages(),v=r.getLatestCheckpoint();if(!v||0===y.length)return;const b=y[0];t.markMessageAsProcessed(b),t.resetStream(),f[Symbol.dispose]();const S=r.getLatestCheckpoint();try{await this.runInternal(e,v,new c.QFf({action:{case:"userMessageAction",value:new c.Vtf({userMessage:b})}}),n,o,s,i,t,r,a,l,u,d,h,p,m,g,w,0,void 0,"agent.request.queuedMessage")}catch(e){throw S===r.getLatestCheckpoint()&&t.requeueMessage(b),e}}}const zn="cursor-ide-browser",Gn="cursor-dev-control",Vn="custom-user-tools",Kn=new Set(["cursor-app-control","cursor-backend-control","cursor-browser-extension",zn,Gn,Vn,"fsd","cursor-subscriptions","cursor-cloud","suggestions","Cursor Slack Tools","Cursor Automation Tools"]);function Jn(e){return!Kn.has(e)}const Zn=new Set([Gn,zn]);function Xn(e){if(void 0!==e&&0!==Object.keys(e).length)try{return JSON.stringify(e)}catch{return}}function Qn(e){return{name:e.toolName,description:e.description,arguments:e.inputSchema,outputSchema:e.outputSchema,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId}}var Yn;function eo(e){return void 0===e||void 0===e.serverIdentifiers}function to(e){switch(e.kind){case"ready":return void 0===e.toolListError?"connected":"error";case"requires_authentication":return"needsAuth";case"error":return"error";default:return"loading"}}(0,b.cF)(Symbol("mcpHostFilledArguments"),[]),function(e){e.Snapshots="cursor_mcp_lease_snapshot_store",e.Status="cursor_mcp_lease_server_status",e.Settings="cursor_mcp_lease_settings",e.Providers="cursor_mcp_lease_providers",e.Unknown="cursor_mcp_lease_unknown"}(Yn||(Yn={}));const ro=G("mcp-executor",(e=>new H(e,Q("mcpArgs"),Y("mcpResult"))),((e,t)=>{t.register(new A(e,te("mcpArgs"),ee("mcpResult")))})),no=G("list-mcp-resources-executor",(e=>new H(e,Q("listMcpResourcesExecArgs"),Y("listMcpResourcesExecResult"))),((e,t)=>{t.register(new A(e,te("listMcpResourcesExecArgs"),ee("listMcpResourcesExecResult")))})),oo=G("read-mcp-resource-executor",(e=>new H(e,Q("readMcpResourceExecArgs"),Y("readMcpResourceExecResult"))),((e,t)=>{t.register(new A(e,te("readMcpResourceExecArgs"),ee("readMcpResourceExecResult")))})),so=G("mcp-state-executor",(e=>new H(e,Q("mcpStateExecArgs"),Y("mcpStateExecResult"))),((e,t)=>{t.register(new A(e,te("mcpStateExecArgs"),ee("mcpStateExecResult")))}));var io=r("../proto/dist/generated/agent/v1/subagent_exec_pb.js");(0,b.cF)(Symbol("pendingSubagentReplay"),void 0);class ao extends Error{constructor(e,t){super(e),this.name="SubagentHostError",this.agentId=t?.agentId,this.cause=t?.cause}}const co=G("subagent-executor",(e=>new H(e,Q("subagentArgs"),Y("subagentResult"))),((e,t)=>{t.register(new A(e,te("subagentArgs"),ee("subagentResult")))})),lo=G("subagent-await-executor",(e=>new H(e,Q("subagentAwaitArgs"),Y("subagentAwaitResult"))),((e,t)=>{t.register(new A(e,te("subagentAwaitArgs"),ee("subagentAwaitResult")))})),uo=G("force-background-subagent-executor",(e=>new H(e,Q("forceBackgroundSubagentArgs"),Y("forceBackgroundSubagentResult"))),((e,t)=>{t.register(new A(e,te("forceBackgroundSubagentArgs"),ee("forceBackgroundSubagentResult")))}));var ho=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/status.js"),po=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js");const fo=(0,be.createContextKey)(void 0,{description:"anysphere.callerContext"}),mo=(0,b.cF)(Symbol("context-rpc.expected_error"),void 0);function go(e,t,r){!0===t.get(mo)?.(r)?e?.setAttribute("rpc.expected_error",!0):(e?.recordException(yo(r)),e?.setStatus({code:ho.s.ERROR,message:r instanceof Error?r.message:"RPC call failed"})),e?.end()}function wo(e){return null!==e&&"object"==typeof e&&Symbol.asyncIterator in e}function yo(e){return e instanceof Error?e:new Error(String(e))}function vo(e,t,r){return{[Symbol.asyncIterator](){const n=e[Symbol.asyncIterator]();let o=!1;const s=e=>{o||(o=!0,e?(t?.recordException(yo(e)),t?.setStatus({code:ho.s.ERROR,message:e instanceof Error?e.message:"Stream failed"})):t?.setStatus({code:ho.s.OK}),t?.end(),r?.())};return{async next(){try{const e=await n.next();return e.done&&s(),e}catch(e){throw s(e),e}},return:async e=>(s(),n.return?n.return(e):{done:!0,value:void 0}),async throw(e){if(s(e),n.throw)return n.throw(e);throw e}}}}}function bo(...e){const t=new Headers;for(const r of e)r&&(r instanceof Headers?r:new Headers(r)).forEach(((e,r)=>{t.set(r,e)}));return t}function So(e,t){const{injectTraceHeaders:r=!0,extractHeaders:n}=t;return new Proxy(e,{get(e,o){const s=e[o];return"function"!=typeof s?s:(i,a,c={})=>{const l=(0,D.fR)(i.withName(`rpc.${String(o)}`),{kind:po.v.CLIENT,attributes:{"rpc.method":String(o),"rpc.system":"connect"}}),u=(0,D.fU)(l);let d;try{let o;if(r&&(o=function(e){const t=new Headers;try{const r=(0,D.fU)(e),n=r?.spanContext?.();if(n?.traceId&&n.spanId){const e=n.traceFlags??0,r=`00-${n.traceId}-${n.spanId}-${e.toString(16).padStart(2,"0")}`;t.set("traceparent",r),t.set("backend-traceparent",r),n.traceState&&t.set("tracestate",n.traceState.serialize())}}catch{}return t}(l)),n){const e=n(l);e&&(o=bo(o,e))}const i=bo(c.headers,o),{signal:p,cleanup:f}=!0===t.enableAbortSignal?function(e,t){if(void 0===t||t===e)return{signal:e};const r=new AbortController,n=()=>{r.abort(e.reason)},o=()=>{r.abort(t.reason)};e.addEventListener("abort",n,{once:!0}),t.addEventListener("abort",o,{once:!0}),e.aborted?n():t.aborted&&o();return{signal:r.signal,cleanup:()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",o)}}}(l.signal,c.signal):{signal:c.signal,cleanup:void 0};d=f;const m=(c.contextValues??(0,be.createContextValues)()).set(fo,l),g={...c,headers:i,signal:p,contextValues:m},w=s.call(e,a,g);return wo(w)?vo(w,u,d):null!==(h=w)&&"object"==typeof h&&"then"in h&&"function"==typeof h.then?Promise.resolve(w).then((e=>wo(e)?vo(e,u,d):(u?.setStatus({code:ho.s.OK}),u?.end(),d?.(),e))).catch((e=>{throw go(u,l,e),d?.(),e})):(u?.setStatus({code:ho.s.OK}),u?.end(),d?.(),w)}catch(e){throw go(u,l,e),d?.(),e}var h}}})}var ko=r("node:crypto"),_o=r("../utils/dist/workspace-paths.js");function Co(){return(0,s.join)(function(){const e=process.env.CURSOR_DATA_DIR;return e?.trim()?e:(0,s.join)((0,o.homedir)(),".cursor")}(),"projects")}function Eo(e){return(0,s.join)(Co(),(0,_o.r_)(e))}var xo=r("node:fs/promises"),Po=r("../../node_modules/.pnpm/lru-cache@11.2.5/node_modules/lru-cache/dist/esm/index.js"),Ro=r("node:fs");const Io="local";function To(e,t){return`${e}:task_progress:${t}`}function Ao(e){const t={};return"string"==typeof e.title&&e.title.trim().length>0&&(t.title=e.title),"string"==typeof e.cwd&&e.cwd.trim().length>0&&(t.cwd=e.cwd),"number"==typeof e.startTimeMs&&Number.isFinite(e.startTimeMs)&&e.startTimeMs>0&&(t.startTimeMs=String(Math.floor(e.startTimeMs))),Object.keys(t).length>0?t:void 0}function $o(e,t){e.hookApprovalRequirement=void 0!==t?new fe.In(t):void 0}function Mo(e){return e.hookApprovalRequirement}function Do(e){return e?.kind===fe.b.FORCE_PROMPT}function Oo(e){return!(!e.skipApproval||e.smartModeClassifierAllowed&&Do(e.hookApprovalRequirement))}var Fo=r("../proto/dist/generated/agent/v1/background_shell_exec_pb.js"),No=r("../shell-exec/dist/api/index.js"),Lo=r("./src/agent/native/tree-sitter.webpack.cjs"),jo=r("./src/agent/native/tree-sitter-bash.webpack.cjs");const Uo=function(e,t=console.warn){let r;return()=>{if(void 0!==r)return r;try{const t=e();t.setLanguage(jo),r=t}catch(e){if(!function(e){return"object"==typeof e&&null!==e&&"CURSOR_TREE_SITTER_STUBBED"===e.code}(e))throw e;r=null,t("shell-parser: tree-sitter natives are unavailable in this artifact; shell command analysis degrades to parsingFailed")}return r}}((()=>new Lo)),Bo=new Set(["file_redirect","heredoc_redirect","herestring_redirect","heredoc","here_string","redirect","redirection"]),Wo=new Set(["<",">",">>",">|","<>","<&",">&","&>","&>>"]);function Ho(e,t){if(null===e)return{legacy:{simpleCommands:[],hasInputRedirect:!1,hasOutputRedirect:!1},structured:{parsingFailed:!0,executableCommands:[],hasRedirects:!1,hasCommandSubstitution:!1,redirects:[]}};const r=e.parse(t),n=new WeakSet;let o=!1,s=!0;const i={simpleCommands:[],hasInputRedirect:!1,hasOutputRedirect:!1},a={parsingFailed:!1,executableCommands:[],hasRedirects:!1,hasCommandSubstitution:!1,redirects:[]},c=e=>{o=!0,a.hasRedirects=!0,s=s&&e},l=e=>{if(e&&/^\d+$/.test(e.text))return Number.parseInt(e.text,10)},u=()=>({fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}),d=(e,t)=>{const r=(e=>{const t=e.children,r=t.findIndex((e=>Wo.has(e.type)));if(-1!==r)return{operator:t[r]?.type??"",target:t.slice(r+1).find((e=>"comment"!==e.type))}})(e);if(!r)return!1;const{operator:n,target:o}=r,s=((e,t)=>{if("&>"===t||"&>>"===t)return[1,2];const r=(e=>l(e.children.find((e=>"file_descriptor"===e.type))))(e);return void 0!==r?[r]:t.startsWith("<")?[0]:[1]})(e,n),i=(e=>{if(e){if("word"===e.type)return 0===e.namedChildren.length?e.text:void 0;if("number"===e.type)return e.text;if("raw_string"===e.type){if(e.text.length<2)return;return e.text.slice(1,-1)}if("string"===e.type){const t=e.namedChildren;if(0===t.length||t.some((e=>"string_content"!==e.type)))return;return t.map((e=>e.text)).join("")}}})(o),c={operator:n,destinationFds:s,targetNodeType:o?.type??""};if(void 0!==i&&(c.targetText=i),a.redirects.push(c),">&"===n){const e=l(o),r=void 0===e?void 0:t.fdTargets.get(e);if(!(e=>"original-stdout"===e||"original-stderr"===e||"dev-null"===e)(r)){for(const e of s)t.fdTargets.set(e,"unsafe");return!1}for(const e of s)t.fdTargets.set(e,r);return!0}if("<&"===n){const e=l(o),r=void 0===e?void 0:t.fdTargets.get(e);if("dev-null"!==r){for(const e of s)t.fdTargets.set(e,"unsafe");return!1}for(const e of s)t.fdTargets.set(e,r);return!0}if(!(e=>{if(!e)return!1;if("word"===e.type)return"/dev/null"===e.text;if("raw_string"===e.type)return"'/dev/null'"===e.text;if("string"===e.type){const t=e.namedChildren;return 1===t.length&&"string_content"===t[0]?.type&&"/dev/null"===t[0].text}return!1})(o)){for(const e of s)t.fdTargets.set(e,"unsafe");return!1}for(const e of s)t.fdTargets.set(e,"dev-null");return!0},h=(e,t)=>{if(!n.has(e)){if(n.add(e),(e=>{var t;t=e.text,/(^|\s)[0-9]*<>/.test(t)||/(^|\s)[0-9]*>(\||&)?/.test(t)||/(^|\s)&>/.test(t)||/(^|\s)[0-9]+>&[0-9]+/.test(t))&&(i.hasOutputRedirect=!0),"heredoc_redirect"!==e.type&&"herestring_redirect"!==e.type||(i.hasInputRedirect=!0)})(e),"heredoc_redirect"===e.type){const{redirect:t,isAllowlistSafe:r}=(e=>{const t=(e=>{const t=e.parent;if("redirected_statement"!==t?.type)return;const r=t.children.find((e=>"command"===e.type)),n=r?.childForFieldName("name");return n?.text})(e),r=void 0!==t&&!(e=>{let t=e.parent;for(;t;){if("command_substitution"===t.type&&"string"!==t.parent?.type)return!0;t=t.parent}return!1})(e),n={operator:r?"<<":"",destinationFds:r?[0]:[],targetNodeType:e.type};return r&&(n.targetText=t),{redirect:n,isAllowlistSafe:r}})(e);return a.redirects.push(t),void c(r)}if("file_redirect"!==e.type)return a.redirects.push({operator:"",destinationFds:[],targetNodeType:e.type}),void c(!1);c(d(e,t))}};return function e(t){const r=t.type;if((e=>{const t=u();for(const r of e.children)Bo.has(r.type)&&h(r,t)})(t),Bo.has(r)&&!n.has(t)&&h(t,u()),"command"===r){const e=t.childForFieldName("name");if(null===e)a.parsingFailed=!0;else{i.simpleCommands.push(e.text);let r=e.text;const n=[];for(const e of function(e){const t=[],r=e.walk();if(r.gotoFirstChild())do{"argument"===r.currentFieldName&&t.push(r.currentNode)}while(r.gotoNextSibling());return t}(t))n.push({type:e.type,value:e.text}),r+=` ${e.text}`;a.executableCommands.push({name:e.text,args:n,fullText:r})}}if("command_name"===r||"simple_command"===r)if("command_name"!==r||i.simpleCommands.includes(t.text)){if("simple_command"===r){const e=t.firstNamedChild;e&&"command_name"===e.type?i.simpleCommands.includes(e.text)||i.simpleCommands.push(e.text):i.simpleCommands.push(t.text)}}else i.simpleCommands.push(t.text);"command_substitution"!==r&&"process_substitution"!==r||(a.hasCommandSubstitution=!0);for(const r of t.children)e(r)}(r.rootNode),o&&(a.allRedirectsAreDevNull=s),{legacy:i,structured:a}}function qo(e){return Ho(Uo(),e)}function zo(e,t){return t>0&&t=55296&&r<=56319)&&function(e){return e>=56320&&e<=57343}(e.charCodeAt(t));var r}function Go(e,t){return t>0?t>=e.length?e.length:Math.trunc(t):0}function Vo(e,t){const r=Go(e,t);return zo(e,r)?r-1:r}function Ko(e,t){const r=Go(e,t);return zo(e,r)?r+1:r}function Jo(e,t){return t>0?e.length<=t?e:e.slice(0,Vo(e,t)):""}function Zo(e,t){return t>0?e.length<=t?e:e.slice(Ko(e,e.length-Math.trunc(t))):""}let Xo,Qo;function Yo(e,t){Xo??=new TextEncoder,Qo??=new Uint8Array(65536);let r=0,n=0;for(;r{const t=(0,ts.o1)(e);try{return await(0,xo.realpath)(t)}catch{return t}},os=1048576,ss=52428800;var is=r("../proto/dist/generated/agent/v1/sandbox_pb.js");function as(e){if(!e)return;let t;return"allow"===e.default?t=is.h1.ALLOW:"deny"===e.default&&(t=is.h1.DENY),new is.RB({version:e.version,defaultAction:t,deny:e.deny??[],allow:e.allow??[],logging:e.logging?(r=e.logging,new is.Qq({decisionLogPath:r.decisionLogPath,logFormat:r.logFormat})):void 0});var r}function cs(e){const t=function(e){if(!e)return;const t={};if(1===e.version&&(t.version=1),void 0!==e.defaultAction)switch(e.defaultAction){case is.h1.ALLOW:t.default="allow";break;case is.h1.DENY:t.default="deny"}return e.deny&&e.deny.length>0&&(t.deny=e.deny),e.allow&&e.allow.length>0&&(t.allow=e.allow),e.logging&&(t.logging=function(e){const t={};return e.decisionLogPath&&(t.decisionLogPath=e.decisionLogPath),"jsonl"===e.logFormat&&(t.logFormat="jsonl"),t}(e.logging)),t}(e.networkPolicy);return t||(e.networkAccess?(0,No.T6)():(0,No.Po)())}function ls(e){switch(e){case"system":return is.Sz.SYSTEM;case"workspace":return is.Sz.WORKSPACE;default:return is.Sz.UNSPECIFIED}}function us(e){const t=function(e){switch(e){case is.Sz.SYSTEM:return"system";case is.Sz.WORKSPACE:return"workspace";case is.Sz.UNSPECIFIED:default:return}}(e.readBoundary),r=e.additionalReadPaths??[];return{readBoundary:t,additionalReadPaths:"workspace"===t&&r.length>0?r:void 0,privateTmp:e.privateTmp}}function ds(e){if(!e)return{type:"insecure_none"};switch(e.type){case is.vc.INSECURE_NONE:case is.vc.UNSPECIFIED:return{type:"insecure_none",allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies};case is.vc.WORKSPACE_READWRITE:return{type:"workspace_readwrite",networkPolicy:cs(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadwritePaths:e.additionalReadwritePaths,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict,...us(e)};case is.vc.WORKSPACE_READONLY:return{type:"workspace_readonly",networkPolicy:cs(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict,...us(e)};default:return{type:"insecure_none"}}}function hs(e){if(e)return"insecure_none"===e.type?new is.Mw({type:is.vc.INSECURE_NONE,allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies}):"workspace_readwrite"===e.type?new is.Mw({type:is.vc.WORKSPACE_READWRITE,networkAccess:(0,No.$b)(e.networkPolicy),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadwritePaths:e.additionalReadwritePaths??[],additionalReadonlyPaths:e.additionalReadonlyPaths??[],disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicy:as(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:ls(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[],privateTmp:e.privateTmp}):"workspace_readonly"===e.type?new is.Mw({type:is.vc.WORKSPACE_READONLY,networkAccess:(0,No.$b)(e.networkPolicy),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths??[],disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicy:as(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:ls(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[],privateTmp:e.privateTmp}):new is.Mw({type:is.vc.INSECURE_NONE})}function ps(e){return" "===e||"\t"===e||"\n"===e||"\r"===e||" "===e||"​"===e||"‌"===e||"‍"===e||"\ufeff"===e}function fs(e){let t="",r=!1;for(const n of e)ps(n)?r=!0:(r&&t.length>0&&(t+=" "),r=!1,t+=n);return t}function ms(e){if(0===e.length)return!1;for(let t=0;te.fullText))])]}const vs={a:"",b:"\b",e:"",E:"",f:"\f",n:"\n",r:"\r",t:"\t",v:"\v","\\":"\\","'":"'",'"':'"',"?":"?"};function bs(e){let t="",r="plain",n=0;for(;n=e.length){t+=o,n++;continue}const s=e[n+1],i=vs[s];if(void 0!==i){t+=i,n+=2;continue}const a="x"===s?e.slice(n+2).match(/^[0-9a-fA-F]{1,2}/)?.[0]:"u"===s?e.slice(n+2).match(/^[0-9a-fA-F]{1,4}/)?.[0]:"U"===s?e.slice(n+2).match(/^[0-9a-fA-F]{1,8}/)?.[0]:e.slice(n+1).match(/^[0-7]{1,3}/)?.[0],c="u"===s||"U"===s,l="x"===s||c?16:8;if(void 0!==a){const e=Number.parseInt(a,l);if(!c||e<=1114111){t+=c?String.fromCodePoint(e):String.fromCharCode(e),n+=a.length+(16===l?2:1);continue}}t+=s,n+=2}return fs(t)}function Ss({rule:e,command:t}){const r=fs(e).trim();return 0!==r.length&&(null!==function(e){const t=fs(e).trim();if(0===t.length)return"Rule cannot be empty";if(t.length>512)return"Rule cannot exceed 512 characters";if(ms(t))return"Rule cannot match every command; be more specific than wildcards alone";if(t.startsWith(":"))return"Colon rules need an executable before `:` (e.g. `aws:*s3 rm*`)";const r=gs(t);if(void 0!==r){const{executablePattern:e,argsPattern:t}=r;if(ms(e)&&(0===t.length||ms(t)))return"Rule cannot match every command; narrow the executable or argument pattern"}return null}(r)||[t.trim(),fs(t).trim(),bs(t).trim()].some((e=>function(e,t){const r=gs(e);if(void 0!==r){const{executablePattern:e,argsPattern:n}=r,o=t.indexOf(" "),s=-1===o?t:t.slice(0,o),i=-1===o?"":t.slice(o+1).trim();if((0,ws.T)(e,s)&&(0,ws.T)(n,i))return!0}return e.includes("*")?(0,ws.T)(e,t):t===e||t.startsWith(`${e} `)}(r,e))))}function ks({matchForms:e,blockedCommands:t}){const r=t.map((e=>e.trim())).filter((e=>e.length>0));if(0===r.length)return;const n=e.map((e=>e.trim())).filter((e=>e.length>0)),o=n.length>0?n:[""];for(const e of r)if(o.some((t=>Ss({rule:e,command:t}))))return e}function _s(e){return`Denied: this command was blocked by administrator policy (denylist rule: ${e}) and was not executed. It cannot be approved from this conversation; only a user can run it manually outside the agent. You may continue working on the task.`}function Cs({command:e,parsingResult:t,blockedCommands:r}){if(0===r.length)return;if(t.parsingFailed||0===t.executableCommands.length)return"Denied: this command could not be conclusively analyzed against your team's administrator command denylist, so it was blocked (fail-closed) and was not executed. It cannot be approved from this conversation; only a user can run it manually outside the agent. You may continue working on the task.";const n=ks({matchForms:ys({command:e,parsingResult:t}),blockedCommands:r});return void 0===n?void 0:_s(n)}var Es=r("../utils/dist/test-resets.js");const xs="CURSOR_FORCED_SHELL_EGRESS_NETWORK_DEFAULT",Ps="CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_DENY_DOMAINS",Rs=/\$\(|`|<\(|>\(/,Is=/[;&|]/;let Ts,As,$s,Ms;function Ds(){if(void 0===Ts){const e=(process.env.CURSOR_FORCED_SHELL_EGRESS??"").trim().toLowerCase();Ts=""!==e&&"0"!==e&&"false"!==e&&"off"!==e}return Ts}function Os(e){const t=(process.env[e]??"").trim();if(t)try{return new RegExp(t,"i"),t}catch(t){throw new Error(`[forced-egress] invalid regex in ${e}: ${String(t)}`)}}function Fs(e){return(process.env[e]??"").split(",").map((e=>e.trim())).filter((e=>e.length>0))}function Ns(e){const t=(process.env[e]??"").split(":").map((e=>e.trim())).filter((e=>e.length>0)),r=t.filter((e=>e.startsWith("/"))),n=t.length-r.length;return n>0&&console.error(`[forced-egress] ignoring ${n} non-absolute path(s) in ${e}.`),r}function Ls(){if(void 0===Ms){const e=(process.env[xs]??"").trim().toLowerCase();let t="deny";"allow"===e||"deny"===e?t=e:""!==e&&console.error(`[forced-egress] ignoring invalid value in ${xs} (expected "allow" or "deny"); using "deny".`);const r=Fs("CURSOR_FORCED_SHELL_EGRESS_DENY_DOMAINS"),n=(process.env[Ps]??"").trim();let o=r;"none"===n.toLowerCase()?o=[]:""!==n&&(o=Fs(Ps)),Ms={networkDefault:t,denyDomains:r,dependencyDenyDomains:o,allowDomains:Fs("CURSOR_FORCED_SHELL_EGRESS_ALLOW_DOMAINS"),writablePaths:Ns("CURSOR_FORCED_SHELL_EGRESS_WRITABLE_PATHS")}}return Ms}function js(e,t,r={}){const n=[Os(e),Os(t)].filter((e=>void 0!==e)).map((e=>`(?:${e})`));if(0===n.length)return null;const o=n.join("|"),s=r.anchorToExecutable?`^\\s*(?:[A-Za-z_][A-Za-z0-9_]*=[^\\s]*\\s+)*(?:${o})`:o;return new RegExp(s,"i")}function Us(e,t){const r=function(){const e=Ls();return{type:"workspace_readwrite",...e.writablePaths.length>0?{additionalReadwritePaths:e.writablePaths}:{},networkPolicy:{version:1,default:e.networkDefault,allow:["127.0.0.0/8","::1/128","localhost",...e.allowDomains],...e.denyDomains.length>0?{deny:e.denyDomains}:{}},networkPolicyStrict:!0,skipStatsigDefaults:!0,enableSharedBuildCache:!0}}(),n=(void 0===As&&(As=js("CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_DEPENDENCY_REGEX",{anchorToExecutable:!0})),As);if(null===n)return r;const o=t?.executableCommands??[];if(t?.parsingFailed||0===o.length)return r;if(Rs.test(e))return r;const s=(void 0===$s&&($s=js("CURSOR_FORCED_SHELL_EGRESS_SOURCE_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_SOURCE_REGEX")),$s);for(const e of o){const t=e.fullText?.trim()||e.name?.trim()||"";if(!t||s?.test(t)||Is.test(t))return r}return o.every((e=>n.test(e.fullText?.trim()||e.name?.trim()||"")))?function(){const e=Ls();return{type:"workspace_readwrite",...e.writablePaths.length>0?{additionalReadwritePaths:e.writablePaths}:{},networkPolicy:{version:1,default:"allow",...e.dependencyDenyDomains.length>0?{deny:e.dependencyDenyDomains}:{}},skipStatsigDefaults:!0,enableSharedBuildCache:!0}}():r}(0,Es.J)((function(){Ts=void 0,As=void 0,$s=void 0,Ms=void 0}));var Bs=r("../utils/dist/lru-cache.js");const Ws=["Desktop","Documents","Downloads","Music","Movies","Pictures","Library",".Trash"],Hs="/Volumes";function qs(e){const t=e.replace(/\/{2,}/g,"/");return t.length>1&&t.endsWith("/")?t.slice(0,-1):t}function zs(e,t){if("darwin"!==t.platform)return[];const r=qs(e),n=r.toLowerCase(),o=qs(t.homeDirectory),s="/"===r?1:r.split("/").length;return[...Ws.map((e=>`${o}/${e}`)),Hs].filter((e=>function(e,t){return e!==t&&e.startsWith(t.endsWith("/")?t:`${t}/`)}(e.toLowerCase(),n))).map((e=>{const t=e.split("/").slice(s).join("/");return`${"/"===r?"":r}/${t}`}))}var Gs=r("../utils/dist/safe-spawn-cwd.js"),Vs=r("node:util");const Ks=8388608;var Js=r("../../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/lib/index.js"),Zs=r("../../node_modules/.pnpm/jschardet@3.1.4/node_modules/jschardet/index.js");function Xs(e){let t=1,r=0;for(;;){const n=e.indexOf("\n",r);if(-1===n)return t;t++,r=n+1}}const Qs="utf8",Ys="utf8bom",ei="latin1",ti={"windows-1250":"cp1250","windows-1251":"cp1251","windows-1252":"cp1252","windows-1253":"cp1253","windows-1254":"cp1254","windows-1255":"cp1255","windows-1256":"cp1256","windows-1257":"cp1257","windows-1258":"cp1258","iso-8859-1":"iso88591","iso-8859-2":"iso88592","iso-8859-5":"iso88595","iso-8859-6":"iso88596","iso-8859-7":"iso88597","iso-8859-8":"iso88598","iso-8859-9":"iso88599","iso-8859-15":"iso885915","iso-8859-16":"iso885916",shift_jis:"shiftjis","euc-jp":"eucjp","euc-kr":"euckr","iso-2022-jp":"iso2022jp","iso-2022-kr":"iso2022kr",gb2312:"gb2312",gbk:"gbk",gb18030:"gb18030",big5:"big5","big5-hkscs":"big5hkscs","koi8-r":"koi8r","koi8-u":"koi8u",ibm855:"cp855",ibm866:"cp866",maccyrillic:"maccyrillic","x-mac-cyrillic":"maccyrillic","utf-16le":"utf16le","utf-16be":"utf16be","utf-32le":"utf32le","utf-32be":"utf32be",johab:"johab",cp949:"cp949",cp932:"cp932"};function ri(e){return ti[e]||e}function ni(e){return e.startsWith("\ufeff")?e.slice(1):e}function oi(e){const t=e.toLowerCase();return"latin-1"===t?ei:"utf-8"===t?Qs:"utf-8-bom"===t||"utf-8 bom"===t?Ys:t}function si(e){const t=[],r=[];let n=0;for(let o=e.indexOf("\n");-1!==o;o=e.indexOf("\n",n)){const s=13===e.charCodeAt(o-1);t.push(e.slice(n,s?o-1:o)),r.push(s?"\r\n":"\n"),n=o+1}return t.push(e.slice(n)),r.push(""),{lines:t,ends:r}}const ii=new Vs.TextDecoder("utf-8",{fatal:!1}),ai=new Vs.TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),ci="�";function li(e){return ii.decode(e)}function ui(e){let t=0,r=0,n=0,o=0;for(let s=0;s0?o--:n++}return r+=n,r>t}function di(e,t=1/0){let r=0,n=0;for(;r=194&&r<=223)n=2;else if(r>=224&&r<=239)n=3,224===r&&(o=160),237===r&&(s=159);else{if(!(r>=240&&r<=244))return 1;n=4,240===r&&(o=144),244===r&&(s=143)}let i=1;for(;i(1===i?s:191))break;i++}return i===n?void 0:i}function pi(e){return e<128?1:e<2048?2:e<65536?3:4}var fi;!function(e){e.CRLF="CRLF",e.LF="LF"}(fi||(fi={}));const mi=[".mp4",".webm",".mov",".avi",".mkv",".wmv",".flv",".m4v"],gi=new Set(mi),wi=new Vs.TextDecoder("utf-8",{fatal:!0}),yi=new Vs.TextDecoder("latin1"),vi=Buffer.from([239,187,191]),bi={utf16le:Buffer.from([255,254]),utf16be:Buffer.from([254,255]),utf32le:Buffer.from([255,254,0,0]),utf32be:Buffer.from([0,0,254,255])},Si=8192,ki="UTF-8",_i="windows-1252",Ci=/[^\u0000-\u007f\ufffd]/u,Ei=/(?:\p{Script=Cyrillic}\p{M}*){3,}/gu,xi=/(?:\p{Script=Greek}\p{M}*){3,}/gu,Pi=/(?:\p{Script=Hebrew}\p{M}*){3,}/gu,Ri=new Map([["windows-1251",Ei],["ISO-8859-5",Ei],["KOI8-R",Ei],["x-mac-cyrillic",Ei],["IBM866",Ei],["IBM855",Ei],["ISO-8859-7",xi],["windows-1253",xi],["windows-1255",Pi],["ISO-8859-8",Pi],["TIS-620",/(?:\p{Script=Thai}\p{M}*){3,}/gu]]),Ii=/\p{Script=Latin}\p{M}*[\p{Script=Cyrillic}\p{Script=Greek}\p{Script=Hebrew}\p{Script=Thai}]|[\p{Script=Cyrillic}\p{Script=Greek}\p{Script=Hebrew}\p{Script=Thai}]\p{M}*\p{Script=Latin}/u,Ti=/[\p{L}\p{M}]+/gu,Ai=String.raw`[\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF\u0152\u0153\u0160\u0161\u017D\u017E\u0178]`,$i=new RegExp(`[A-Za-z]${Ai}{1,2}(?!${Ai})|^${Ai}{1,2}[A-Za-z]`,"u"),Mi=new Map,Di=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".pdf",".zip",".tar",".gz",".exe",".dll",".so",".dylib",".bin",...mi]),Oi=/\.(png|jpg|jpeg|gif|webp|ico|bmp)$/i,Fi=new Set([".ps1",".psm1",".psd1"]),Ni=/[^\u0000-\u007f]/u;function Li(e){const t=e.toLowerCase(),r=t.lastIndexOf(".");return-1===r?"":t.substring(r)}function ji(e){const t=Li(e);return gi.has(t)}function Ui(e){const t=Li(e);return{encoding:"binary",lineEnding:fi.LF,isBinaryFile:!0,isImageFile:Oi.test(t),isVideoFile:gi.has(t)}}async function Bi(e,t){return(await Wi(e,t)).text}async function Wi(e,t){const{stamp:r,buf:n}=await async function(e){const t=await(0,xo.open)(e,"r");try{return{stamp:await t.stat(),buf:await t.readFile()}}finally{await t.close()}}(e),o=Gi(n);if(o.isBinaryFile)throw new Error("Binary file cannot be decoded as text");const s=ea(e,r);let i;i=t||s||o.encoding;const{text:a,encoding:c}=na(n,i),l=ni(a),u=c===Qs&&oa(n)?Ys:c;ta(e,r,u);const d=function(e,t){if(t===Ys)return oa(e);const r=bi[ri(oi(t))];return void 0!==r&&e.subarray(0,r.length).equals(r)}(n,u);if(o.lineEnding===fi.CRLF){const e=l.match(/\r\n/g)?.length??0,t=(l.match(/\n/g)?.length??0)-e;return{text:l.replaceAll("\r\n","\n"),encoding:u,bom:d,lineEnding:e>t?"CRLF":"LF"}}return{text:l,encoding:u,bom:d,lineEnding:"LF"}}async function Hi(e,t){if("binary"===t.encoding)return void Yi(e);let r;try{r=await(0,xo.stat)(e)}catch{return void Yi(e)}r.size===t.buffer.byteLength?ta(e,r,t.encoding):Yi(e)}async function qi(e,t,r,o){let s,i;try{s=r?await async function(e,t){try{return await zi(e)}catch{}const r=Li(e);if(Di.has(r))return Ui(e);try{return await async function(e){const t=new Map;let r=0;for await(const n of Xi(e)){if(r>=100)break;try{const e=await zi(n);if(!e.isBinaryFile){const r=`${e.encoding}:${e.lineEnding}`,n=t.get(r);if(n){if(n.count++,n.count>=3)return n.format}else t.set(r,{format:e,count:1})}r++}catch(e){}}let n;for(const e of t.values())(!n||e.count>n.count)&&(n=e);return n?n.format:Qi()}(t)}catch{return Qi()}}(e,r):await zi(e)}catch{const t=Li(e);s=Di.has(t)?Ui(e):Qi()}const a=()=>i??=async function(e){try{const t=await(0,xo.stat)(e);if(!t.isFile()||t.size>Ks)return;return await(0,xo.readFile)(e)}catch{return}}(e),c=ea(e,await async function(e){try{return await(0,xo.stat)(e)}catch{return}}(e));let l;if(!s.isBinaryFile){let r;o?r=oi(o):c?r=oi(c):(r=oi(s.encoding),r===Ys||Js.encodingExists(ri(r))||(r=Qs),r!==Qs&&r!==Ys||(r=await async function(e,t){const r=await t();return void 0===r||(0,n.isUtf8)(r)?e:ra(r).encoding===ei?ei:e}(r,a))),r===Qs&&!o&&function(e,t){return"win32"===process.platform&&Fi.has(Li(e))&&Ni.test(t)&&!t.startsWith("#!")}(e,t)&&(await async function(e){try{return await(0,xo.stat)(e),!1}catch(e){return e instanceof Error&&"code"in e&&"ENOENT"===e.code}}(e)||await async function(e){const t=await e();return void 0!==t&&(0,n.isAscii)(t)}(a))&&(r=Ys);const i=r===Ys||r===Qs&&!o&&await sa(e,vi),u=bi[ri(r)];i?l=vi:u&&await sa(e,u)&&(l=u),s={...s,encoding:i?Ys:r}}const u=Xs(t),d=t.includes("\r\n")?void 0:await async function(e,t){if(t.isBinaryFile)return;const r=await e();if(void 0===r||!r.includes(13))return;const n=ni(na(r,t.encoding).text);return function(e){let t=!1,r=!1;for(let n=e.indexOf("\n");-1!==n;n=e.indexOf("\n",n+1))if(13===e.charCodeAt(n-1)?t=!0:r=!0,t&&r)return!0;return!1}(n)?n:void 0}(a,s);if(void 0!==d?t=function({content:e,existing:t,defaultEnding:r}){const n=si(t),o=si(e),s=function({before:e,after:t}){const r=new Int32Array(t.length).fill(-1);let n=0;for(;n0&&i>0&&(s+1)*(i+1)<=4e6){const o=i+1,a=new Uint16Array((s+1)*o);for(let r=s-1;r>=0;r--)for(let s=i-1;s>=0;s--)a[r*o+s]=e[n+r]===t[n+s]?a[(r+1)*o+s+1]+1:Math.max(a[(r+1)*o+s],a[r*o+s+1]);for(let c=0,l=0;c=a[c*o+l+1]?c++:l++}let a=-1,c=-1;for(let n=0;n<=t.length;n++){const o=n===t.length?e.length:r[n];if(-1!==o){if(o-a==n-c)for(let e=1;e50&&/^[A-Za-z0-9+/]*={0,2}$/.test(t))try{const e=Buffer.from(t,"base64");if(e.length>0){const r=Math.floor(.5*t.length);if(e.length>=r)return e}}catch{}return Buffer.from(e,"latin1")}(t);return{lines:u,buffer:e,format:s}}const h=l?ni(t):t,p=s.encoding===Ys?Qs:s.encoding,f=p===Qs?await async function(e,t){if(!t.includes(ci))return;const r=await e();return void 0===r?void 0:function(e,t){if(!e.includes(ci)||(0,n.isUtf8)(t))return;const r=function(e){const t=[];let r=0;for(const n of ai.decode(e)){const o=n.codePointAt(0)??0;if(65533!==o){r+=pi(o);continue}const s=hi(e,r);void 0===s?(t.push(void 0),r+=3):(t.push(e.subarray(r,r+s)),r+=s)}return r===e.length?t:void 0}(t),o=e.split(ci);if(void 0===r||o.length-1!==r.length)return;const s=[];for(let e=0;e=Math.max(0,e.length-3);t--){const r=e[t];if(r<128)return e;if(r>=192){const n=r>=240?4:r>=224?3:2;return e.length-t=e.length);o+=2){if(0===e[o+1]){const r=e[o];(r>=32&&r<=126||9===r||10===r||13===r)&&t++}if(0===e[o]){const t=e[o+1];(t>=32&&t<=126||9===t||10===t||13===t)&&r++}}return t>.8*n?"UTF-16LE":r>.8*n?"UTF-16BE":null}(e)??function(e){if(e.length<8)return null;if(0===e[0]&&0===e[1]&&254===e[2]&&255===e[3])return"UTF-32BE";if(255===e[0]&&254===e[1]&&0===e[2]&&0===e[3])return"UTF-32LE";let t=0,r=0;const n=Math.min(50,Math.floor(e.length/4));for(let o=0;o<4*n&&!(o+3>=e.length);o+=4){if(0===e[o]&&0===e[o+1]&&0===e[o+2]){const r=e[o+3];(r>=32&&r<=126||9===r||10===r||13===r)&&t++}if(0===e[o+1]&&0===e[o+2]&&0===e[o+3]){const t=e[o];(t>=32&&t<=126||9===t||10===t||13===t)&&r++}}return t>.8*n?"UTF-32BE":r>.8*n?"UTF-32LE":null}(e);if(t)return{encoding:t,lineEnding:Ki(Js.decode(e.subarray(0,Si),ri(oi(t)))),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};if(!function(e){const t=Math.min(Si,e.length);if(0===t)return!0;for(let r=0;r=8&&137===r[0]&&80===r[1]&&78===r[2]&&71===r[3]&&13===r[4]&&10===r[5]&&26===r[6]&&10===r[7]||255===r[0]&&216===r[1]&&255===r[2]||r.length>=12&&82===r[0]&&73===r[1]&&70===r[2]&&70===r[3]&&87===r[8]&&69===r[9]&&66===r[10]&&80===r[11]||r.length>=6&&71===r[0]&&73===r[1]&&70===r[2]&&56===r[3]&&(55===r[4]||57===r[4])&&97===r[5])),isVideoFile:!1};var r,o,s;if((0,n.isUtf8)(e)&&(!e.includes(27)||!(0,n.isAscii)(e)))return{encoding:ki,lineEnding:Vi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};if(!(0,n.isUtf8)(e)&&(o=li(e),s=e.length,ui(o)||1024*di(o)<=s&&!Ci.test(o)))return{encoding:ki,lineEnding:Vi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};const i=Zs.detect(e);let a=i.confidence>.7?i.encoding:"utf-8";"ascii"===a&&(a="utf-8");const c=Ri.get(a);return void 0!==c&&(a=function(e,t,r){const n=ri(oi(t));if(!Js.encodingExists(n))return t;const o=Js.decode(e,n);return Ii.test(o)&&function(e,t,r){const n=t.match(r)?.length??0;let o=0;for(const[t]of Js.decode(e,_i).matchAll(Ti))$i.test(t)&&o++;return o>n}(e,o,r)?_i:t}(e,a,c)),a!==_i||function(e,t){const r=ri(oi(t));return!Js.getDecoder(r).write(e).includes(ci)}(e,a)||(a="utf-8"),{encoding:a??"utf-8",lineEnding:Vi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function Vi(e){let t=0,r=0;for(let n=0;n0&&13===e[n-1]?t++:r++);return Ji(t,r)}function Ki(e){const t=e.match(/\n/g)?.length??0,r=e.match(/\r\n/g)?.length??0;return Ji(r,t-r)}function Ji(e,t){return 0===e&&0===t?fi.LF:e/(e+t)*100>=5?fi.CRLF:fi.LF}async function Zi(e){const t=await(0,xo.open)(e,"r");try{const e=Buffer.allocUnsafe(Si),{bytesRead:r}=await t.read(e,0,Si,0);return e.subarray(0,r)}finally{await t.close()}}async function*Xi(e){const t=new Set(["node_modules",".git",".svn",".hg","dist","build","out",".next",".cache","coverage","__pycache__",".venv","venv",".turbo"]);try{const r=await(0,xo.readdir)(e,{withFileTypes:!0});for(const n of r){if(n.name.startsWith(".")&&".gitignore"!==n.name)continue;const r=(0,s.join)(e,n.name);n.isDirectory()?t.has(n.name)||(yield*Xi(r)):n.isFile()&&(yield r)}}catch(e){return}}function Qi(){return{encoding:Qs,lineEnding:"win32"===process.platform?fi.CRLF:fi.LF,isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function Yi(e){Mi.delete(e)}function ea(e,t){const r=Mi.get(e);if(void 0!==r)return void 0!==t&&r.size===t.size&&r.mtimeMs===t.mtimeMs?r.encoding:void Mi.delete(e)}function ta(e,t,r){if(Mi.has(e)&&Mi.delete(e),Mi.set(e,{encoding:r,size:t.size,mtimeMs:t.mtimeMs}),Mi.size<=100)return;const n=Mi.keys().next().value;void 0!==n&&Mi.delete(n)}function ra(e){try{return{text:wi.decode(e),encoding:Qs}}catch{const t=li(e);return ui(t)?{text:t,encoding:Qs}:{text:yi.decode(e),encoding:ei}}}function na(e,t){const r=oi(t);if(r===Qs||r===Ys||"ascii"===r){const t=ra(e);return r===Ys&&t.encoding===Qs?{text:t.text,encoding:Ys}:t}if(r===ei)return{text:yi.decode(e),encoding:ei};try{const t=ri(r);if(Js.encodingExists(t))return{text:Js.decode(e,t),encoding:r}}catch{}return ra(e)}function oa(e){return e.length>=vi.length&&e[0]===vi[0]&&e[1]===vi[1]&&e[2]===vi[2]}async function sa(e,t){try{return(await Zi(e)).subarray(0,t.length).equals(t)}catch{return!1}}var ia=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js");class aa{constructor({ttlMs:e,now:t=Date.now}){this.entries=new Map,this.nextSweepAtMs=0,this.ttlMs="function"==typeof e?e:aa.validated(e),this.now=t}static validated(e){if(!Number.isFinite(e)||e<=0)throw new Error(`TTL cache requires a positive ttlMs, got ${e}`);return()=>e}get(e){const t=this.entries.get(e);if(void 0!==t){if(!(t.expiresAtMs<=this.now()))return t.value;this.entries.delete(e)}}has(e){const t=this.entries.get(e);return!(void 0===t||t.expiresAtMs<=this.now()&&(this.entries.delete(e),1))}get size(){return this.entries.size}set(e,t){const r=this.now(),n=this.ttlMs();if(this.entries.set(e,{value:t,expiresAtMs:r+n}),!(r1048576?e:await async function(e,t){const r=function(e){const t=Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=Gi(t);return r.isBinaryFile?li(t):ni(na(t,r.encoding).text)}(t);return function(e,t){if(!(0,n.isUtf8)(e))return!1;const r=e.toString("utf8");return(r.startsWith("\ufeff")?r.slice(1):r)===t}(t,r)?e:async function(e,t){const r=await(da??=(0,xo.mkdtemp)((0,s.join)((0,o.tmpdir)(),"cursorignore-utf8-")).then((e=>(process.once("exit",(()=>{try{(0,Ro.rmSync)(e,{recursive:!0,force:!0})}catch{}})),e))),da),n=(0,s.join)(r,`cursorignore-${ha(e)}-${ha(t)}.txt`);if(await pa(n))return n;const i=`${n}.${process.pid}.${Date.now()}.tmp`;return await(0,xo.writeFile)(i,t,"utf8"),await(0,xo.rename)(i,n),n}(e,r)}(e,await(0,xo.readFile)(e));return la.set(e,{mtimeMs:t.mtimeMs,size:t.size,ripgrepPath:i}),i}function ma(e){return Promise.all(e.map((e=>async function(e){const t=ua.get(e);if(void 0!==t)return t;const r=fa(e).catch((()=>e)).finally((()=>{ua.delete(e)}));return ua.set(e,r),r}(e))))}(0,Es.J)((function(){la.clear(),ua.clear()}));var ga=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function wa(e){if(e.aborted)return{aborted:Promise.resolve("aborted"),[Symbol.dispose](){}};let t=()=>{};const r=new Promise((e=>{t=()=>e("aborted")}));return e.addEventListener("abort",t,{once:!0}),{aborted:r,[Symbol.dispose](){e.removeEventListener("abort",t)}}}function ya(e,{root:t,searchPaths:r=[],includeGlobs:n=[],excludeGlobs:s=[],caseSensitive:i=!1,cursorIgnoreFiles:a=[],sandboxPolicy:c={type:"insecure_none"},noIgnoreVcs:l=!1,followSymlinks:u=!1,source:d="ripwalk"}){const h=["--files","--hidden","--no-require-git","--no-config","--color=never"],p=function(e=process.env){const t=e.CURSOR_RIPWALK_THREADS?.trim();if(void 0!==t&&""!==t){const e=Number(t);if(Number.isInteger(e)&&e>=0)return 0===e?void 0:e}return Math.min(2,(0,o.availableParallelism)())}();void 0!==p&&h.push("--threads",String(p)),u&&h.push("--follow"),l&&h.push("--no-ignore-vcs"),i&&h.push("--case-sensitive");for(const e of n)h.push("--iglob",e);for(const e of s)h.push("--iglob",`!${e}`);const f=r.length>0?["--",...r]:[];let m,g=!1;const w=new Promise((e=>{m=e}));return{lines:async function*(){const r={stack:[],error:void 0,hasError:!1};try{const n=[];for(const e of await ma(a))n.push("--cursor-ignore",e);const o=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,function(e,t,r,n){const o=(0,No.spawnInSandbox)((0,No.Ko)(),t,{cwd:r},n),s=[];o.stderr?.on("data",(e=>{s.push(e)}));const i=new Promise(((e,t)=>{o.on("error",t),o.on("close",(t=>e(t??0)))}));if(i.catch((()=>{})),!o.stdout)throw new Error("No stdout from ripgrep process");const a=wa(e.signal);return{stdout:o.stdout,processExit:i,stderr:()=>Buffer.concat(s).toString(),aborted:a.aborted,[Symbol.dispose](){a[Symbol.dispose](),o.kill()}}}(e,[...h,...n,...f],t,c),!1);let s=0;const i=async function*(e){const t=new ca.StringDecoder("utf8");let r="";for await(const n of e){r+=t.write(n);const e=r.split("\n");r=e.pop()??"",e.length>0&&(yield e)}r+=t.end(),r&&(yield[r])}(o.stdout)[Symbol.asyncIterator]();e:for(;;){const t=await Promise.race([i.next(),o.aborted]);if("aborted"===t){g=!0,m(!0);break}if(t.done)break;for(const r of t.value){if(e.signal.aborted){g=!0,m(!0);break e}s++,yield r}}if(s>0);else if(!g){const e=await o.processExit;if(0!==e&&1!==e){const t=o.stderr();throw new Error(`Ripgrep failed (exit ${e}) with no results${t?`: ${t}`:""}`)}}g||m(!1)}catch(e){r.error=e,r.hasError=!0}finally{ga(r)}}(),didTimeout:w}}var va=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});let ba;function Sa(e=process.env){if(void 0!==ba)return ba;const t=e.CURSOR_RIPWALK_CACHE_TTL_MS?.trim();if(void 0!==t&&""!==t){const e=Number(t);if(Number.isFinite(e)&&e>0)return e}return 2e4}function ka({root:e,searchPaths:t=[],includeGlobs:r=[],excludeGlobs:n=[],caseSensitive:o=!1,cursorIgnoreFiles:s=[],sandboxPolicy:i={type:"insecure_none"},noIgnoreVcs:a=!1,followSymlinks:c=!1}){return JSON.stringify({root:e,searchPaths:t,includeGlobs:r,excludeGlobs:n,caseSensitive:o,cursorIgnoreFiles:s,sandboxPolicy:i,noIgnoreVcs:a,followSymlinks:c})}class _a{constructor(e=()=>Sa()){this.cache=new aa({ttlMs:e})}get size(){return this.cache.size}clear(){this.cache.clear()}delete(e){this.cache.delete(ka(e))}walk(e,t){const r=ka(t);let n,o=!1,s=!1;const i=new Promise((e=>{n=e})),a=e=>{s||(s=!0,n(e))};return{lines:async function*(){const n=this.cache.get(r);if(void 0!==n){const t={stack:[],error:void 0,hasError:!1};try{const s=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,wa(e.signal),!1),i=await Promise.race([n.linesPromise.then((e=>({type:"lines",lines:e})),(e=>({type:"error",error:e}))),s.aborted.then((()=>({type:"aborted"})))]);if("aborted"===i.type)return o=!0,void a(!0);if("lines"===i.type)return a(!1),void(yield*i.lines);this.cache.get(r)===n&&this.cache.delete(r)}catch(e){t.error=e,t.hasError=!0}finally{va(t)}}let s,i;const c={linesPromise:new Promise(((e,t)=>{s=e,i=t}))};c.linesPromise.catch((()=>{})),this.cache.set(r,c);const l=[];let u,d=!1;try{const r=ya(e,t);for await(const e of r.lines)l.push(e),yield e;if(await r.didTimeout)return o=!0,u=new Error("Ripwalk aborted before cacheable result was available"),void a(!0);d=!0}catch(e){throw u=e,e}finally{d?s?.(l):(this.cache.get(r)===c&&this.cache.delete(r),i?.(u??new Error("Ripwalk terminated before cacheable result was available"))),o||a(!1)}}.bind(this)(),didTimeout:i}}}const Ca=16777216,Ea=new Set([32,9,10,13]),xa="a path through /proc or /dev/fd",Pa={kind:"none"},Ra={kind:"stop"};function Ia(e,t){return{kind:"refused",refused:{name:e,reason:t}}}async function Ta(e){const t=await async function(e){if(void 0===await(0,xo.lstat)(e).catch((()=>{})))return Pa;if(await Ma(Buffer.from(e)))return Ia(".git",xa);const t=await(0,xo.stat)(e).catch((()=>{}));if(void 0===t)return Pa;if(!t.isFile())return Aa(e);const r=await Na(e,{whole:1048576});if("not-regular"===r.kind)return Ia(".git","not a regular file");if("bytes"!==r.kind)return Ra;const n=Buffer.from("gitdir: "),o=Ba(r.bytes);if(!o.subarray(0,n.length).equals(n)||o.length<=n.length)return Ra;const i=Ua({dir:(0,s.dirname)(e),target:Wa(o.subarray(n.length))});if(await Ma(i))return Ia(".git",xa);const a=await Aa(i);return"none"===a.kind?Ra:a}(ja(e,".git").toString());return"none"!==t.kind?t:Aa(e)}async function Aa(e){const t=await async function(e){const t=await(0,xo.lstat)(e).catch((()=>{}));if(void 0===t||t.isDirectory())return Pa;if(t.isSymbolicLink()){const t=await(0,xo.readlink)(e,{encoding:"buffer"}).catch((()=>{}));return"refs/"===t?.subarray(0,5).toString("latin1")?"valid":Pa}if(!t.isFile())return Ia("HEAD","not a regular file");const r=await Na(e,{prefix:255});if("not-regular"===r.kind)return Ia("HEAD","not a regular file");if("bytes"!==r.kind)return Pa;const n=Wa(r.bytes.subarray(0,255)).toString("latin1");if(n.startsWith("ref:")){let e=4;for(;e{}))){if(await Ma(n))return Ia("commondir",xa);const t=await Na(n,{whole:Ca});switch(t.kind){case"bytes":{if(0===t.bytes.length)return Ra;const n=Ua({dir:e,target:Wa(Ba(t.bytes))});if(await Ma(n))return Ia("commondir",xa);const o=await(0,xo.realpath)(n,{encoding:"buffer"}).catch((()=>{}));if(void 0===o)return Pa;r=o;break}case"too-large":return Ia("commondir","over the size cap");case"not-regular":return Ia("commondir","not a regular file");case"directory":case"unreadable":return Ra;default:throw new Error(`unhandled read ${String(t)}`)}}for(const e of["objects","refs"]){const t=ja(r,e);if(await Ma(t))return Ia(e,xa);if(!await La(t))return Pa}return{kind:"repository",gitDir:e,commonDir:r}}async function $a({gitDir:e,commonDir:t}){const r=[["HEAD",ja(e,"HEAD")],["config.worktree",ja(e,"config.worktree")],["config",ja(t,"config")],["info/exclude",ja(ja(t,"info"),"exclude")]];for(const[e,t]of r){if(await Ma(t))return{name:e,reason:xa};const r=await(0,xo.stat)(t).catch((()=>{}));if(void 0!==r&&!r.isDirectory()&&!await Fa(r)){if(!r.isFile())return{name:e,reason:"not a regular file"};if(r.size>Ca)return{name:e,reason:"over the size cap"}}}}async function Ma(e){if("win32"===process.platform)return!1;const t=Da(e.toString("latin1")).reverse();let r="/",n=0;for(let e=t.pop();void 0!==e;e=t.pop()){if(".."===e){r=(0,s.dirname)(r);continue}const o=(0,s.join)(r,e),i="darwin"===process.platform?o.toLowerCase():o;if(["/proc","/dev/fd"].some((e=>i===e||i.startsWith(`${e}/`))))return!0;const a=await(0,xo.readlink)(Buffer.from(o,"latin1"),{encoding:"buffer"}).catch((()=>{}));if(void 0===a){r=o;continue}if(++n>40)return!1;const c=a.toString("latin1");(0,s.isAbsolute)(c)&&(r="/"),t.push(...Da(c).reverse())}return!1}function Da(e){return e.split("/").filter((e=>""!==e&&"."!==e))}let Oa;async function Fa(e){if(!e.isCharacterDevice())return!1;Oa??=(0,xo.stat)("/dev/null").catch((()=>{}));const t=await Oa;return void 0!==t&&e.dev===t.dev&&e.ino===t.ino}async function Na(e,t){const r=Ro.constants.O_RDONLY|(Ro.constants.O_NONBLOCK??0)|(Ro.constants.O_NOCTTY??0),n=await(0,xo.open)(e,r).catch((()=>{}));if(void 0===n)return{kind:"unreadable"};try{const e=await n.stat();if(e.isDirectory())return{kind:"directory"};if(!e.isFile())return{kind:"not-regular"};if("whole"in t&&e.size>t.whole)return{kind:"too-large"};const r="whole"in t?t.whole:t.prefix,o=Buffer.alloc(Math.min(r+1,e.size+1));let s=0;for(;st.whole?{kind:"too-large"}:{kind:"bytes",bytes:o.subarray(0,s)}}catch{return{kind:"unreadable"}}finally{await n.close().catch((()=>{}))}}function La(e){return(0,xo.access)(e,Ro.constants.X_OK).then((()=>!0),(()=>!1))}function ja(e,t){const r=Buffer.isBuffer(e)?e:Buffer.from(e),n=r.toString("latin1").endsWith(s.sep)?"":s.sep;return Buffer.concat([r,Buffer.from(`${n}${t}`)])}function Ua({dir:e,target:t}){return(0,s.isAbsolute)(t.toString("latin1"))?t:Buffer.concat([ja(e,""),t])}function Ba(e){let t=e.length;for(;t>0&&(10===e[t-1]||13===e[t-1]);)t--;return e.subarray(0,t)}function Wa(e){const t=e.indexOf(0);return-1===t?e:e.subarray(0,t)}const Ha=[{stage:"prod",gitHost:"origin.cursor.com",gitCdnHost:"gitcdn.origin.cursor.com",cloneKitS3Host:"git-forge-prod-bundles.s3.us-east-1.amazonaws.com",rawUserContentHost:"raw.cursorusercontent.com",apiHost:"api.origin.cursor.com",internalHost:"origin-prod.internal.cursor.com"},{stage:"staging",gitHost:"origin-staging.cursor.com",gitCdnHost:"gitcdn.origin-staging.cursor.com",cloneKitS3Host:"git-forge-staging-bundles.s3.us-east-1.amazonaws.com",rawUserContentHost:"raw.staging.cursorusercontent.com",apiHost:"api.origin-staging.cursor.com",internalHost:"origin-staging.internal.cursor.com"},{stage:"test",gitHost:"origin-test.cursor.com",gitCdnHost:"gitcdn.origin-test.cursor.com",cloneKitS3Host:"git-forge-test-bundles.s3.us-east-1.amazonaws.com",rawUserContentHost:"raw.test.cursorusercontent.com",apiHost:"api.origin-test.cursor.com",internalHost:"origin-test.internal.cursor.com"}];function qa(e){let t=e.length;for(;t>0&&47===e.charCodeAt(t-1);)t--;const r=e.slice(0,t).replace(/\.git$/i,"");return r&&"/"!==r?r.startsWith("/")?r:`/${r}`:""}function za(e,t){const r=qa(t);return r?`${e}${r}`.toLowerCase():""}new Map(Ha.map((e=>[e.gitHost,e.apiHost]))),new Map(Ha.map((e=>[e.gitHost,e.gitCdnHost]))),new Map(Ha.map((e=>[e.gitHost,e.cloneKitS3Host]))),new Map(Ha.map((e=>[e.gitHost,e.rawUserContentHost]))),new Map(Ha.map((e=>[e.apiHost,e.gitHost]))),new Map(Ha.map((e=>[e.apiHost,e.internalHost])));const Ga=new Map;function Va(e){const t=Ga.get(e);if(void 0!==t)return t;const r=function(e){const t=e.trim();if(!t)return"";try{const e=function(e){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(e))return e;const t=`https://${e}`;try{return new URL(t),t}catch{const r=e.match(/^([^@/\s]+@)?([^:/\s]+):(.+)$/);return r?`ssh://${r[1]??""}${r[2]}/${r[3]}`:t}}(t),r=new URL(e);return za(r.hostname,r.pathname)}catch{const e=t.replace(/^(?:https?|ssh|git):\/\//i,""),r=e.indexOf("/"),n=-1===r?e:e.slice(0,r),o=-1===r?"":e.slice(r);return za(n.includes("@")?n.slice(n.lastIndexOf("@")+1):n,o)}}(e);return Ga.size>=16384&&Ga.clear(),Ga.set(e,r),r}function Ka(e){return/^origin(-[a-z0-9]+)?\.cursor\.com$/i.test(e)}(function(e){const t=Ha.find((t=>t.stage===e));if(void 0===t)throw new Error(`unknown Origin stage: ${e}`);return t})("prod").gitHost;const Ja=new Map;function Za(e){if(void 0===e)return;if(Ja.has(e))return Ja.get(e);const t=function(e){const t=e?function(e){let t=e.trim();if(""!==t){t.startsWith("git@")?t=`https://${t.slice(4).replace(":","/")}`:/^[a-z][a-z0-9+.-]*:\/\//i.test(t)&&!/^https?:\/\//i.test(t)?t=t.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"https://"):/^https?:\/\//i.test(t)||(t=`https://${t}`);try{return new URL(t)}catch{return}}}(e):void 0;if(void 0===t||!Ka(t.hostname))return;const r=qa(t.pathname).split("/").filter(Boolean),n=3===r.length&&"git"===r[0]?.toLowerCase(),o=2===r.length&&"git"!==r[0]?.toLowerCase();if(!n&&!o)return;const s=n?r[1]:r[0],i=n?r[2]:r[1];return s&&i?Object.freeze({hostname:t.hostname,owner:s,name:i}):void 0}(e);return Ja.size>=16384&&Ja.clear(),Ja.set(e,t),t}function Xa(e){return void 0!==function(e){const t=Za(e);return void 0===t?void 0:{owner:t.owner,name:t.name}}(e)}new Set(["github.com","www.github.com"]),new RegExp("^tmp-[0-9a-f]{16}$");const Qa=(0,d.h)("local-exec:git-root"),Ya=new WeakMap,ec=new Map;function tc(e,t,r){return rc(e,t,r).then((e=>"repository"===e.kind?e.root:null))}function rc(e,t,r){const n=performance.now();let o=Ya.get(t);void 0===o&&(o=new Map,Ya.set(t,o));const s=o.get(r);if(void 0!==s&&nc(s,n))return s.result;for(const[e,t]of o)nc(t,n)||o.delete(e);const i=t.guardedRootLookup,a=void 0===i?{result:ic(e,t,r,void 0),windowStart:n}:{result:oc(e,t,r,i.timeoutMs),windowStart:void 0};return void 0===a.windowStart&&a.result.then((()=>{a.windowStart=performance.now()})),o.set(r,a),a.result}function nc(e,t){return void 0===e.windowStart||t-e.windowStart<5e3}async function oc(e,t,r,n){const o=new AbortController,i=performance.now()+n,a=await(0,Nr.wj)(async function({ctx:e,gitExecutor:t,startPath:r,deadline:n,settled:o}){const i=await function(e){let t=ec.get(e);if(void 0===t){t=async function(e){const t=await(0,xo.realpath)(e).catch((()=>{}));if(void 0===t)return;const r=function(){const e=(process.env.GIT_DISCOVERY_ACROSS_FILESYSTEM??"").toLowerCase();return!["","0","false","no","off"].includes(e)}()?void 0:(await(0,xo.stat)(t).catch((()=>{})))?.dev;for(let e=t;;){const t=await Ta(e);switch(t.kind){case"refused":return t.refused;case"stop":return;case"repository":return $a(t);case"none":break;default:throw new Error(`unhandled probe ${String(t)}`)}const n=(0,s.dirname)(e);if(n===e||void 0!==r&&(await(0,xo.stat)(n).catch((()=>{})))?.dev!==r)return;e=n}}(e),ec.set(e,t);const r=()=>{ec.delete(e)};t.then(r,r)}return t}(r);if(o.aborted)return{kind:"unknown",reason:"timed-out"};if(void 0!==i)return Qa.warn(e,"findGitRoot: not starting git; its answer is unknown",{adminFile:i.name,reason:i.reason}),{kind:"unknown",reason:"refused"};const a=Math.ceil(n-performance.now());return a<=0?{kind:"unknown",reason:"timed-out"}:ic(e,t,r,a)}({ctx:e,gitExecutor:t,startPath:r,deadline:i,settled:o.signal}),n).catch((t=>t instanceof Nr.MU?{kind:"unknown",reason:"timed-out"}:(Qa.warn(e,"findGitRoot: the admin file check failed; not starting git",{code:sc(t)}),{kind:"unknown",reason:"refused"}))).finally((()=>{o.abort()}));return"unknown"===a.kind&&"timed-out"===a.reason&&Qa.warn(e,"findGitRoot: the lookup ran past its bound; its answer is unknown",{timeoutMs:n}),a}function sc(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:void 0}async function ic(e,t,r,n){try{return{kind:"repository",root:(await t.exec(e,r,["rev-parse","--show-toplevel"],{...void 0===n?{}:{timeout:n},caller:"findGitRoot"})).stdout.trim()}}catch(e){return void 0!==n&&function(e){return"object"==typeof e&&null!==e&&"killed"in e&&!0===e.killed}(e)?{kind:"unknown",reason:"timed-out"}:{kind:"none"}}}async function ac(e,t,r){try{return(await t.exec(e,r,["config","--get","remote.origin.url"],{caller:"getGitRemoteUrl"})).stdout.trim()}catch{return}}function cc(e){const t=e.trim();if(""===t)return t;try{const e=new URL(t);return""===e.host?uc(t)??e.toString():(e.username="",e.password="",e.toString())}catch{return function(e){const t=e.replace(/^[\u0000-\u0020]+|[\u0000-\u0020]+$/g,"").replace(/[\t\n\r]/g,""),r=t.indexOf(":"),n=t.slice(0,r);if(r<0||!/^[A-Za-z][A-Za-z0-9+.-]*$/.test(n))return;const o=t.slice(r+1),s=lc.has(n.toLowerCase());let i;if(s)i=o.replace(/^[/\\]+/,"");else{if(!o.startsWith("//"))return;i=o.slice(2)}const a=i.search(s?/[/?#\\]/:/[/?#]/),c=a<0?i.length:a,l=i.slice(0,c),u=l.lastIndexOf("@");return u<0?void 0:`${t.slice(0,t.length-i.length)}${l.slice(u+1)}${i.slice(c)}`}(t)??uc(t)??t}}const lc=new Set(["ftp","file","http","https","ws","wss"]);function uc(e){const t=e.indexOf("/"),r=t<0?e:e.slice(0,t),n=r.indexOf(":"),o=r.lastIndexOf("@",r.lastIndexOf(":"));if(!(n<0||o<0||r.indexOf("@")`/${s.posix.relative(e,t)}`))}var pc=r("../../node_modules/.pnpm/picomatch@4.0.5/node_modules/picomatch/index.js");function fc(e,t){return e.some((e=>{return"*"===e.url.trim()?(e.patterns??[]).some((e=>wc(e.pattern,t))):!((r=e.url).includes("://")||r.includes("github.com")||r.includes("gitlab.com")||r.includes("bitbucket.org")||r.includes("@"))&&wc(e.url,t);var r}))}function mc(e,t,r){return gc(e.url,t)&&(e.patterns??[]).some((e=>wc(e.pattern,r)))}function gc(e,t){return e.includes("*")?"*"===e.trim()||function(e,t){const r=e.trim();return!!wc(r,t)||!!r.startsWith("*/")&&wc(`**/${r.slice(2)}`,t)}(kc(e),kc(t)):kc(e)===kc(t)}function wc(e,t){const r=e.trim();return!("."!==t&&""!==t||"**"!==r&&"**/*"!==r)||function(e){const t=bc.get(e);if(void 0!==t)return t;let r;try{const t=pc(e,{dot:!0});r=r=>{try{return t(r)}catch{return e===r}}}catch{r=t=>e===t}return Sc(bc,yc,e,r)}(r)(t)}const yc=2048,vc=new Map,bc=new Map;function Sc(e,t,r,n){if(e.set(r,n),e.size>t){const t=e.keys().next().value;void 0!==t&&e.delete(t)}return n}function kc(e){const t=vc.get(e);if(void 0!==t)return t;const r=(function(e){const t=Za(e);if(void 0!==t)return`${t.hostname}/git/${t.owner}/${t.name}`.toLowerCase()}(n=e)??Va(n))||function(e){let t=e.trim();t.startsWith("git@")&&(t=`https://${t.slice(4).replace(":","/")}`),/^[a-z][a-z0-9+.-]*:\/\//i.test(t)&&!/^https?:\/\//i.test(t)&&(t=t.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"https://")),/^https?:\/\//i.test(t)||(t=`https://${t}`);try{const e=new URL(t),r=e.pathname.replace(/\/+$/,"").replace(/\.git$/i,"").replace(/\/+$/,"");return e.hostname+r}catch{return t=t.replace(/^https?:\/\//i,""),t=t.replace(/[?#].*$/,""),t=t.replace(/\/+$/,""),t=t.replace(/\.git$/i,""),t=t.replace(/\/+$/,""),t}}(e).toLowerCase();var n;return Sc(vc,2048,e,r)}function _c(e){if("object"==typeof e&&null!==e&&"code"in e){const t=e.code;if("string"==typeof t)return t}}function Cc(e){if(e instanceof Error)return e.message;if("object"==typeof e&&null!==e&&"message"in e){const t=e.message;if("string"==typeof t)return t}return""}(0,Es.J)((function(){vc.clear(),bc.clear()}));const Ec=[".gitignore",".cursorignore"];async function xc(e){if(!(0,s.isAbsolute)(e))return null;const t=await(0,ts.DN)(e);return null===t?null:t}function Pc(e,t){if(!e||0===e.length)return[...t];const r=new Set(e);for(const e of t)r.has(e)&&r.delete(e),r.add(e);return[...r]}class Rc{constructor(e,t,r,n={}){this.disposeRequested=!1,this.initIgnoreService=()=>Ac.init((0,b.q6)(),e,r??[process.cwd()],t),!0!==n.deferInit&&this.ensureStarted()}ensureStarted(){if(void 0===this.ignoreServicePromise){if(this.disposeRequested)return Promise.reject(new Error("LazyIgnoreService was disposed before its ignore-file scan started"));this.ignoreServicePromise=this.initIgnoreService()}return this.ignoreServicePromise}isIgnoredByAny(e){return this.ensureStarted().then((t=>t.isIgnoredByAny(e)))}isGitIgnored(e){return this.ensureStarted().then((t=>t.isGitIgnored(e)))}isCursorIgnored(e,t){return this.ensureStarted().then((r=>r.isCursorIgnored(e,t)))}isRepoBlocked(e){return this.ensureStarted().then((t=>t.isRepoBlocked(e)))}listCursorIgnoreFilesByRoot(e){return this.ensureStarted().then((t=>t.listCursorIgnoreFilesByRoot(e)))}getCursorIgnoreMapping(){return this.ensureStarted().then((e=>e.getCursorIgnoreMapping()))}getShellSandboxIgnoreMapping(e){return this.ensureStarted().then((t=>t.getShellSandboxIgnoreMapping(e)))}getGitIgnoreMapping(){return this.ensureStarted().then((e=>e.getGitIgnoreMapping()))}getRepoBlockExcludeGlobs(e){return this.ensureStarted().then((t=>t.getRepoBlockExcludeGlobs(e)))}handleCursorIgnoreCreated(e){return this.ensureStarted().then((t=>t.handleCursorIgnoreCreated(e)))}handleCursorIgnoreChanged(e){return this.ensureStarted().then((t=>t.handleCursorIgnoreChanged(e)))}handleCursorIgnoreDeleted(e){return this.ensureStarted().then((t=>t.handleCursorIgnoreDeleted(e)))}dispose(){this.disposeRequested||(this.disposeRequested=!0,this.ignoreServicePromise?.then((e=>{e.dispose()})).catch((()=>{})))}}const Ic=Math.min(8,Math.max(1,Math.floor(o.availableParallelism()/2)));class Tc{constructor(e){this.maxLookups=e,this.instances=new Map,this.lookups=0}get(e,t){this.lookups>=this.maxLookups&&this.clear(),this.lookups++;let r=this.instances.get(e);return void 0===r&&(r=ia().add(t),this.instances.set(e,r)),r}delete(e){this.instances.delete(e)}clear(){this.instances.clear(),this.lookups=0}}class Ac{constructor(e,t,r,n,o,s){this.gitExecutor=e,this.gitIgnoreMapping=t,this.cursorIgnoreMapping=r,this.teamSettingsService=n,this.rootDirectories=o,this.scanEnvironment=s,this.gitIgnoreCache=new Bs.q({max:2e3}),this.cursorIgnoreCache=new Bs.q({max:2e3}),this.gitRootCache=new Bs.q({max:1e4}),this.gitRemoteUrlCache=new Bs.q({max:200}),this.hasGitDirCache=new Bs.q({max:1e3}),this.gitParsedIgnoreCache=new Tc(1e4),this.cursorParsedIgnoreCache=new Tc(1e4),this.ignoreMappingsHaveEntries=!1,this.directoryWalkPlacementCache=new Bs.q({max:1e4}),this.extraRootCursorIgnoreCache=new Bs.q({max:32}),this.extraGitRepoMappingCache=new Bs.q({max:32}),this.unwalkedFolders=o.flatMap((e=>zs(e,s)))}static getRipwalkCache(){return Ac.ripwalkCache??=new _a,Ac.ripwalkCache}hasNoWorkspaceFolders(){return!this.ignoreMappingsHaveEntries&&(this.ignoreMappingsHaveEntries=Object.keys(this.gitIgnoreMapping).length>0||Object.keys(this.cursorIgnoreMapping).length>0,!this.ignoreMappingsHaveEntries)}async resolveLookupRoot(e){return await(0,ts.DN)(e)??(0,ts.o1)(e)}static async init(e,t,r,n,s={platform:process.platform,homeDirectory:o.homedir()}){const i={...s,homeDirectory:await(0,ts.DN)(s.homeDirectory)??s.homeDirectory},a=await(0,Nr.PH)(r,(async e=>{const t=await(0,ts.DN)(e);return null===t?(console.warn(`[IgnoreService] Cannot resolve workspace root, using as-is: ${e}`),e):t})),c={},l={},u=await(0,Nr.PH)(a,(async r=>({root:r,lookup:await rc(e,t,r)}))),d=u.map((({root:e,lookup:t})=>"none"===t.kind?null:"unknown"===t.kind||zs(t.root,i).length>0?e:t.root)).filter((e=>null!==e)),h=u.filter((({lookup:e})=>"unknown"===e.kind)).map((({root:e})=>(0,ts.o1)(e)));return d.length>0&&await Promise.all([Ac.initializeIgnoreMapping({rootDirectories:d,ignoreFileName:".gitignore",mapping:c,scanEnvironment:i,unknownRoots:h}),Ac.initializeIgnoreMapping({rootDirectories:a,ignoreFileName:".cursorignore",mapping:l,scanEnvironment:i,unknownRoots:h})]),new Ac(t,c,l,n,a,i)}static async preloadHierarchy(e,t,r,n){let o=(0,ts.o1)(e);const i=(0,s.parse)(o).root;for(;o!==i;){if(n?.has(o)){const e=(0,s.dirname)(o);if(e===o)break;o=e;continue}void 0===r[o]&&await Ac.handleHierarchyIgnore(o,t,r),n?.add(o);const e=(0,s.dirname)(o);if(e===o)break;o=e}}static async handleHierarchyIgnore(e,t,r){const n=(0,s.join)(e,t);try{await(0,xo.access)(n,xo.constants.F_OK);const t=await Bi(n),o=Ac.parseIgnoreRules(t);r[e]=o}catch(o){"ENOENT"===_c(o)||console.error(`Error reading ${t} file at ${n}:`,o),r[e]=[]}}static async initializeIgnoreMapping({rootDirectories:e,ignoreFileName:t,mapping:r,scanEnvironment:n,unknownRoots:o}){try{const i=Ac.deduplicateRootDirectories(e),a=await Ac.promiseQueue.enqueueList(i,(e=>Ac.findFilesWithRipgrep({rootDirectory:e,fileName:t,scanEnvironment:n,noIgnoreVcs:o.some((t=>(0,ts.ZU)({basePath:e,targetPath:t})))}))),c=Array.from(a.values()).flat();await Promise.all(c.map((async e=>{try{const t=await Bi(e),n=Ac.parseIgnoreRules(t),o=(0,s.dirname)(e);r[o]=n}catch(r){console.error(`Error processing ${t} file at ${e}:`,r)}})));const l=new Set;for(const e of i)await Ac.preloadHierarchy(e,t,r,l)}catch(e){console.error(`Error initializing ignore mapping for ${t}:`,e)}}static async findFilesWithRipgrep({rootDirectory:e,fileName:t,scanEnvironment:r,noIgnoreVcs:n}){const o=(0,b.q6)(),i=[],a={root:e,includeGlobs:Ec.map((e=>`**/${e}`)),excludeGlobs:[...dc,...hc(e,r)],noIgnoreVcs:n,source:"ignore_scan"},c=Ac.getRipwalkCache().walk(o,a);for await(const r of c.lines)(0,s.basename)(r)===t&&i.push((0,s.join)(e,r));return i}async handleManualLookupWhenNoWorkspaceDirs(e,t,r){const n={};let o=(0,s.dirname)(e);const i=(0,s.parse)(o).root;for(;;){let e=r?.get(o);if(void 0===e){try{e=Ac.parseIgnoreRules(await Bi((0,s.join)(o,t)))}catch{e=[]}r?.set(o,e)}if(e.length>0&&(n[o]=e),o===i)break;o=(0,s.dirname)(o)}return this.testIgnored(e,n,((e,t)=>ia().add(t)))}async isIgnoredByAny(e){const[t,r,n]=await Promise.all([this.checkGitIgnored(e),this.checkCursorIgnored(e),this.checkRepoBlocked(e)]);return t||r||n}async isGitIgnored(e){return this.checkGitIgnored(e)}async isCursorIgnored(e,t){return this.checkCursorIgnored(e,t)}async checkGitIgnored(e){if(this.hasNoWorkspaceFolders())return this.handleManualLookupWhenNoWorkspaceDirs(e,".gitignore");const t=this.gitIgnoreCache.get(e);if(void 0!==t)return t;await this.populateHierarchyIfNeeded(e,".gitignore",this.gitIgnoreMapping);const r=this.checkIgnored(e,this.gitIgnoreMapping,this.gitParsedIgnoreCache);return this.gitIgnoreCache.set(e,r),r}async checkCursorIgnored(e,t){if(this.hasNoWorkspaceFolders())return this.handleManualLookupWhenNoWorkspaceDirs(e,".cursorignore",t);const r=this.cursorIgnoreCache.get(e);if(void 0!==r)return r;await this.populateHierarchyIfNeeded(e,".cursorignore",this.cursorIgnoreMapping);const n=this.checkIgnored(e,this.cursorIgnoreMapping,this.cursorParsedIgnoreCache);return this.cursorIgnoreCache.set(e,n),n}isInUnwalkedFolder(e){const t="darwin"===this.scanEnvironment.platform,r=t?e.toLowerCase():e;return this.unwalkedFolders.some((e=>(0,ts.ZU)({basePath:t?e.toLowerCase():e,targetPath:r})))}directoryWalkPlacement(e){const t=this.directoryWalkPlacementCache.get(e);if(void 0!==t)return t;let r;return r=this.isInUnwalkedFolder(e)?"unwalked":this.rootDirectories.some((t=>(0,ts.ZU)({basePath:t,targetPath:e})))?"walked":"outside",this.directoryWalkPlacementCache.set(e,r),r}async populateHierarchyIfNeeded(e,t,r){let n=(0,s.dirname)((0,ts.o1)(e));const o=[],i=(0,s.parse)(n).root;for(;n!==i;){const e=this.directoryWalkPlacement(n),t="unwalked"===e;if("walked"===e){n=(0,s.dirname)(n);continue}if(void 0===r[n])o.push(n);else if(!t)break;const i=(0,s.dirname)(n);if(i===n)break;n=i}o.length>0&&(await Ac.promiseQueue.enqueueList(o,(e=>Ac.handleHierarchyIgnore(e,t,r))),".gitignore"===t?this.gitIgnoreCache.clear():this.cursorIgnoreCache.clear())}testIgnored(e,t,r){for(const[n,o]of Object.entries(t)){if(0===o.length)continue;if(!(0,ts.ZU)({basePath:n,targetPath:e}))continue;const t=(0,s.relative)(n,e);if(""===t)continue;const i=r(n,o),a=(0,ts.oL)(t),c=i.test(a);if(c.ignored&&!c.unignored)return!0;const l=i.test(`${a}/`);if(l.ignored&&!l.unignored)return!0}return!1}checkIgnored(e,t,r){return this.testIgnored(e,t,((e,t)=>r.get(e,t)))}async listCursorIgnoreFilesByRoot(e){const t=await this.resolveLookupRoot(e),r=[];for(const[e,n]of Object.entries(this.cursorIgnoreMapping)){if(0===n.length)continue;if(!(0,ts.ZU)({basePath:t,targetPath:e}))continue;const o=(0,s.join)(e,".cursorignore");try{await(0,xo.access)(o),r.push(o)}catch{}}return r}async getCursorIgnoreMapping(){return{...this.cursorIgnoreMapping}}async getShellSandboxIgnoreMapping(e=[]){const t={...this.cursorIgnoreMapping},r=[];for(const t of e){if((0,Gs.$f)(t))continue;const e=await(0,ts.DN)(t);if(null===e||".git"===(0,s.basename)(e)||this.rootDirectories.some((t=>(0,ts.ZU)({basePath:t,targetPath:e})))||r.includes(e))continue;const n=await xo.stat(e).catch((e=>{if(void 0===_c(e))throw e}));n?.isDirectory()&&r.push(e)}const n=Date.now();for(const e of r){let r=this.extraRootCursorIgnoreCache.get(e);if(void 0===r||r.expiresAt<=n){const t={},o=void 0===this.gitExecutor.guardedRootLookup?void 0:await rc((0,b.q6)(),this.gitExecutor,e);await Ac.initializeIgnoreMapping({rootDirectories:[e],ignoreFileName:".cursorignore",mapping:t,scanEnvironment:this.scanEnvironment,unknownRoots:"unknown"===o?.kind?[e]:[]}),r={mapping:t,expiresAt:n+Sa()},this.extraRootCursorIgnoreCache.set(e,r)}for(const[e,n]of Object.entries(r.mapping))t[e]=Pc(t[e],n)}for(const e of[...this.rootDirectories,...r]){const r=await this.getRepoBlockExcludeGlobs(e);0!==r.length&&(t[e]=Pc(t[e],r))}return t}async getGitIgnoreMapping(){return{...this.gitIgnoreMapping}}static deduplicateRootDirectories(e){const t=[...e.map((e=>(0,ts.o1)(e)))].sort(((e,t)=>e.length-t.length)),r=[];for(const e of t)r.some((t=>e.startsWith(`${t}/`)||e.startsWith(`${t}\\`)))||r.push(e);return r}static parseIgnoreRules(e){return e.split("\n").map((e=>e.replace(/\r$/,"").trimStart())).filter((e=>""!==e&&!e.startsWith("#")))}clearCaches(){this.gitIgnoreCache.clear(),this.cursorIgnoreCache.clear(),this.gitRootCache.clear(),this.gitRemoteUrlCache.clear(),this.hasGitDirCache.clear(),this.gitParsedIgnoreCache.clear(),this.cursorParsedIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear(),this.extraGitRepoMappingCache.clear()}dispose(){this.gitIgnoreCache=new Bs.q({max:1}),this.cursorIgnoreCache=new Bs.q({max:1}),this.gitRootCache=new Bs.q({max:1}),this.gitRemoteUrlCache=new Bs.q({max:1}),this.hasGitDirCache=new Bs.q({max:1}),this.directoryWalkPlacementCache=new Bs.q({max:1}),this.extraRootCursorIgnoreCache=new Bs.q({max:1}),this.extraGitRepoMappingCache=new Bs.q({max:1}),this.gitParsedIgnoreCache.clear(),this.cursorParsedIgnoreCache.clear(),this.gitRepoMappingPromise=void 0}async handleCursorIgnoreCreated(e){const t=(0,s.dirname)(e),r=await Bi(e),n=Ac.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear()}async handleCursorIgnoreChanged(e){const t=(0,s.dirname)(e),r=await Bi(e),n=Ac.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear()}handleCursorIgnoreDeleted(e){const t=(0,s.dirname)(e);this.cursorIgnoreMapping[t]=[],this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear()}async findGitRootsForFile(e){const t=(0,ts.o1)(e),r=this.gitRootCache.get(t);if(void 0!==r)return r;const n=[],o=[],i=[];let a=t;const c=(0,s.parse)(a).root;for(;a!==c;){o.push(a),void 0===this.hasGitDirCache.get(a)&&i.push(a);const e=(0,s.dirname)(a);if(e===a)break;a=e}if(i.length>0){const e=i.map((e=>(0,xo.access)((0,s.join)(e,".git"),xo.constants.F_OK).then((()=>[e,!0])).catch((()=>[e,!1])))),t=await Promise.all(e);for(const[e,r]of t)this.hasGitDirCache.set(e,r)}for(const e of o)!0===this.hasGitDirCache.get(e)&&n.push(e);return this.gitRootCache.set(t,n),n}async isRepoBlocked(e){return this.checkRepoBlocked(e)}async checkRepoBlocked(e){const t=function(e){if(void 0===e)return;const t=e.repos??[],r=e.disableLocalExecAllowlistEnforcement?[]:e.allowedRepos??[];return 0===t.length&&0===r.length?void 0:{blocked:t,allowed:r}}(await(this.teamSettingsService?.getTeamRepos()));if(void 0===t)return!1;const r=await this.findGitRootsForFile(e);if(0===r.length)return 0!==t.allowed.length&&!(0,ts.ZU)({basePath:await this.getCursorDataDir(),targetPath:e})&&function(e,t){return 0!==e.allowed.length&&!fc(e.allowed,t)}(t,this.getWorkspaceRelativePath(e));const n=[];for(const t of r)n.push({url:await this.remoteUrlOf(t),relativePath:(0,s.relative)(t,e)||"."});return function(e,t){let r=0===e.allowed.length,n=!1;for(const{url:o,relativePath:s}of t)if(void 0!==o){if(e.blocked.some((e=>mc(e,o,s))))return!0;e.allowed.length>0&&!n&&(n=!0,r=e.allowed.some((e=>mc(e,o,s))))}else 0;return!r}(t,n)}async remoteUrlOf(e){if(this.gitRemoteUrlCache.has(e))return this.gitRemoteUrlCache.get(e);const t=await ac((0,b.q6)(),this.gitExecutor,e);return void 0!==t&&this.gitRemoteUrlCache.set(e,t),t}getWorkspaceRelativePath(e){let t;for(const r of this.rootDirectories)(0,ts.ZU)({basePath:r,targetPath:e})&&(void 0===t||r.length>t.length)&&(t=r);return void 0!==t?(0,ts.oL)((0,s.relative)(t,e)):(0,ts.oL)(e)}getCursorDataDir(){return this.cursorDataDirPromise??=(async()=>{const e=(0,s.join)(o.homedir(),".cursor");return await(0,ts.DN)(e)??e})(),this.cursorDataDirPromise}async getRepoBlockExcludeGlobs(e){const t=await(this.teamSettingsService?.getTeamRepos());if(!t?.repos?.length)return[];const r=await this.resolveLookupRoot(e);let n;if(this.rootDirectories.some((e=>(0,ts.ZU)({basePath:e,targetPath:r}))))n=await this.getGitRepoMapping();else{const e=this.extraGitRepoMappingCache.get(r);void 0!==e?n=e:(n=await this.initializeGitRepoMapping([r]),this.extraGitRepoMappingCache.set(r,n))}if(0===n.size)return[];const o=[];for(const[e,i]of n){if(void 0===i)continue;const n=this.normalizePathForComparison(e),a=this.normalizePathForComparison(r);let c=!1,l="";if(a.startsWith(n)?(c=!0,l=""):n.startsWith(a)&&(c=!0,l=(0,s.relative)(r,e)),!c)continue;const u=t.repos.filter((e=>gc(e.url,i)));if(0!==u.length)for(const e of u)for(const t of e.patterns||[]){const e=t.pattern.trim();if(!e)continue;let r;r=l?(0,s.join)(l,e).replace(/\\/g,"/"):e,o.push(r),r.endsWith("/**")||o.push(`${r}/**`)}}return o}normalizePathForComparison(e){let t=e.replace(/\\/g,"/");return t.startsWith("/")&&t.length>2&&":"===t[2]&&(t=t.substring(1)),"win32"===process.platform&&(t=t.toLowerCase()),t}getGitRepoMapping(){return this.gitRepoMappingPromise||(this.gitRepoMappingPromise=this.initializeGitRepoMapping()),this.gitRepoMappingPromise}async initializeGitRepoMapping(e=this.rootDirectories){const t=new Map,r=[],n=["**/node_modules/**","**/.turbo/**","**/.next/**","**/.cache/**","**/.pnpm/**","**/.yarn/**","**/dist/**","**/build/**","**/out/**","**/target/**","**/.vscode/**","**/.idea/**","**/venv/**","**/__pycache__/**","**/logs/**","**/tmp/**","**/temp/**"],o=(0,b.q6)();for(const t of e){const e=(0,ts.o1)(t);try{await(0,xo.access)((0,s.join)(e,".git"),xo.constants.F_OK),r.includes(e)||r.push(e)}catch{}let i=(0,s.dirname)(e);const a=(0,s.parse)(i).root;for(;i!==a&&""!==i;){try{await(0,xo.access)((0,s.join)(i,".git"),xo.constants.F_OK),r.includes(i)||r.push(i)}catch{}const e=(0,s.dirname)(i);if(e===i)break;i=e}try{const t={root:e,includeGlobs:["**/.git/config"],excludeGlobs:[...n,...hc(e,this.scanEnvironment)],noIgnoreVcs:!0,source:"ignore_scan"},i=Ac.getRipwalkCache().walk(o,t);for await(const t of i.lines){const n=(0,s.join)(e,t),o=(0,s.dirname)(n),i=(0,s.dirname)(o);r.includes(i)||r.push(i)}}catch{}}return await Promise.all(r.map((async e=>{try{const r=await ac(o,this.gitExecutor,e);t.set(e,r)}catch{t.set(e,void 0)}}))),t}}async function $c(e,t){let r=e;if(Ds()&&(r=Us(t.command,t.parsingResult)),!r||"insecure_none"===r.type)return r;const n="workspace_readwrite"===r.type&&t.permissionsService.resolveLinkedWorktreeSandboxGrants?await t.permissionsService.resolveLinkedWorktreeSandboxGrants(r,{command:t.command,workingDirectory:t.workingDirectory}):void 0,o=function(e,t){if(!e)return t;const r={...e};for(const[e,n]of Object.entries(t))r[e]=Pc(r[e],n);return r}(r.ignoreMapping,await async function(e,t){return e.getShellSandboxIgnoreMapping?e.getShellSandboxIgnoreMapping(t):e.getCursorIgnoreMapping()}(t.ignoreService,n?.roots));if("workspace_readwrite"===r.type&&void 0!==n){const e=(0,No.s9)(r.additionalReadwritePaths,[...n.roots,...n.commonDirs]);return{...r,additionalReadwritePaths:e.length>0?e:void 0,ignoreMapping:o}}return{...r,ignoreMapping:o}}Ac.promiseQueue=new Nr.TJ({max:Ic});var Mc=r("../proto/dist/generated/agent/v1/mcp_exec_pb.js");const Dc="agent-tools",Oc=51380224;var Fc=r("../proto/dist/generated/agent/v1/utils_pb.js");const Nc=/^v?(\d{1,9})\.(\d{1,9})(?:\.\d{1,9})?(?:[-+][0-9A-Za-z.+-]*)?$/,Lc=["unknown","other","older","3.24","3.25","3.26","3.27","3.28","3.29","3.30","3.31","3.32","3.33","3.34","3.35","3.36","3.37","3.38","3.39","3.40","newer"].flatMap((e=>{const t=/^(\d+)\.(\d+)$/.exec(e);return null===t?[]:[{major:Number(t[1]),minor:Number(t[2]),bucket:e}]})),jc=Lc[0].major,Uc=Lc[0].minor;function Bc(e){if(null==e)return"unknown";const t=e.trim();if(0===t.length||t.length>128)return"unknown";const r=Nc.exec(t);if(null===r)return"unknown";const n=Number(r[1]),o=Number(r[2]);if(n!==jc)return"other";const s=Lc.find((e=>e.minor===o));return void 0!==s?s.bucket:o=128&&t<=191?t:Jc.get(e)}function ol(e,t){const r=e.charCodeAt(t),n=function(e){return e>=194&&e<=222?201===e?0:2:e>=224&&e<=239?3:240===e?4:0}(r);if(0===n||t+n>e.length)return;const o=new Uint8Array(n);o[0]=r;for(let r=1;r0&&Xc.test(e[t-1]))return}else{if(Qc.has(s))return;if(!0===el.get(r)?.has(s))return;if(3===n&&tl.has(s)&&Qc.has(e[t+2]))return}let i;try{i=Kc.decode(o)}catch{return}return rl.test(i)?void 0:{index:t,text:e.slice(t,t+n),repaired:i}}function sl(e,t=Number.POSITIVE_INFINITY){const r=[];let n=0;for(;n240){n++;continue}const o=ol(e,n);void 0!==o?(r.push(o),n+=o.text.length):n++}return r}const il=`[\\u00c2-\\u00f0][\\u0080-\\u00bf${[...Jc.keys()].join("")}]`,al=new RegExp(il),cl=/\p{L}/u;function ll(e,t){const r=e.charCodeAt(t);let n;if(r>=194&&r<=223)n=2;else if(r>=224&&r<=239)n=3;else{if(!(r>=240&&r<=244))return 0;n=4}if(t+n>e.length)return 0;for(let r=1;r=128&&n<=191)&&(n<128||!Jc.has(e[t+r])))return 0}return n}function ul(e,t){if(t.text.length>2)return!0;const r=t.text.charCodeAt(1);if(r>=128&&r<=159)return!0;if(0===t.index||!Xc.test(e[t.index-1]))return!0;const n=t.index+t.text.length;return n0)return"damaged";const n=bl(r);return"utf8"!==n&&"utf8_bom"!==n?"other_encoding":"intact"}function ml(e,t){return e<=t?"existing_only":"new_damage"}function gl(e,t){const r=new Set(t.map((e=>e.text))),n=e.filter((e=>!r.has(e.text))),o=n.length>0?n:e;if(function(e){let t="",r=-1;for(const n of e){if(n.index!==r){if(sl(t,1).length>0)return!0;t=""}t+=n.repaired,r=n.index+n.text.length}return sl(t,1).length>0}(o))return"double";if(1!==new Set(o.map((e=>e.text.length))).size)return"mixed";switch(o[0].text.length){case 2:return"two_byte";case 3:return"three_byte";default:return"four_byte"}}function wl(e){return{detector:e,outcome:"clean",afterCount:0,beforeCount:0}}function yl(e,t,r){const n=sl(r,1e3);if(0===n.length)return wl("mojibake");const o=void 0===e?[]:sl(e,Math.max(n.length,6));return{detector:"mojibake",outcome:ml(n.length,o.length),file:fl(e,o.length,t),afterCount:n.length,beforeCount:o.length,pattern:gl(n,o)}}function vl(e,t,r){const n=di(r);if(0===n)return wl("replacement_chars");const o=void 0===e?0:di(e);return{detector:"replacement_chars",outcome:ml(n,o),file:fl(e,o,t),afterCount:n,beforeCount:o}}function bl(e){if(void 0===e)return"none";const t=e.toLowerCase().replace(/[^a-z0-9]/g,"");return"utf8"===t||"ascii"===t?"utf8":"utf8bom"===t?"utf8_bom":t.startsWith("utf16")?"utf16":"latin1"===t||"iso88591"===t?"latin1":"windows1252"===t||"cp1252"===t?"windows_1252":"gbk"===t||"gb2312"===t||"gb18030"===t||"cp936"===t?"gbk":"shiftjis"===t||"sjis"===t||"cp932"===t||"windows31j"===t?"shift_jis":"euckr"===t||"cp949"===t?"euc_kr":"big5"===t||"big5hkscs"===t||"cp950"===t?"big5":"other"}const Sl=new Map([["md",["md","mdx","markdown"]],["txt",["txt","text","log","rst","adoc","asciidoc","tex"]],["js_ts",["js","jsx","mjs","cjs","ts","tsx","mts","cts"]],["web",["html","htm","xhtml","css","scss","sass","less","vue","svelte","astro"]],["py",["py","pyi","pyw","ipynb"]],["jvm",["java","kt","kts","scala","groovy","gradle"]],["dotnet",["cs","csx","vb","fs","fsx","razor","cshtml","xaml"]],["c_cpp",["c","h","cc","cpp","cxx","c++","hpp","hh","hxx","h++","m","mm"]],["other_code",["go","rs","rb","erb","php","swift","dart","lua","pl","pm","r","ex","exs","erl","hs","clj","cljs","zig","nim","jl","sol","elm","ml","mli","pas","bas"]],["shell",["sh","bash","zsh","fish","ps1","psm1","psd1","bat","cmd"]],["sql",["sql","psql","ddl","dml"]],["config",["json","jsonc","json5","yaml","yml","toml","ini","cfg","conf","env","properties","editorconfig"]],["xml",["xml","xsl","xslt","xsd","svg","csproj","vbproj","fsproj","props","targets","nuspec","plist","storyboard","xib"]],["i18n",["po","pot","strings","stringsdict","arb","xlf","xliff","ftl","resx"]],["csv",["csv","tsv"]]].flatMap((([e,t])=>t.map((t=>[t,e])))));function kl(e){const t=(0,s.extname)(e).slice(1).toLowerCase();return""===t?"none":Sl.get(t)??"other"}const _l=new Map([[1252,"1252"],[1250,"1250"],[1251,"1251"],[874,"874"],[932,"932"],[936,"936"],[949,"949"],[950,"950"],[65001,"65001"]]);function Cl(e){if("string"==typeof e)return e;const t=void 0===e.acp?void 0:_l.get(e.acp);return void 0===t?"other":e.oemcp===e.acp?t:`${t}_split`}function El(e,t){if("clean"===e.outcome)return{detector:e.detector,outcome:"clean",file:"unclassified"};const r={outcome:e.outcome,file:e.file,ext:kl(t.path),encoding:bl(t.encoding),code_page:Cl(t.pages),run_count:hl(e.afterCount),delta:(n=e.afterCount-e.beforeCount,n<0?"neg":pl(n)),before_count:pl(e.beforeCount)};var n;return"mojibake"===e.detector?{detector:"mojibake",pattern:e.pattern,...r}:{detector:"replacement_chars",...r}}class xl{constructor(){this.counts={stdout:0,stderr:0},this.produced={stdout:!1,stderr:!1}}note(e,t){if(0===t.length)return;this.produced[e]=!0;const r=this.counts[e];r>=6||(this.counts[e]=r+di(t,6-r))}labels(e,t){const r=Cl(t),n=[];for(const t of["stdout","stderr"]){if(!this.produced[t])continue;const o=this.counts[t];n.push({detector:"replacement_chars",outcome:o>0?"damaged":"clean",run_count:pl(o),branch:e[t],stream:t,code_page:r})}return n}}const Pl=/[\ud800-\udbff](?![\udc00-\udfff])|(?=e.length||e.startsWith(Ml,r))&&e.startsWith(Ml,r+Ll(e,r)))return!0}return!1}(e)}(e,o))return"utf16";if(r)return"clean";if(!$l.test(e))return"clean";const s=function(e){if(!al.test(e))return;let t=0,r=!1,n=!0,o=0;for(;o=194&&s<=240?ol(e,o):void 0;if(void 0!==i){if(t++,r=ul(e,i),o+=i.text.length,!n||!r&&t>=256)return"medium";continue}const a=n?ll(e,o):0;if(0===a){if(n=!1,t>0)return"medium";o++}else o+=a}return 0!==t?r&&n?"high":"medium":void 0}(e);return void 0!==s?"high"===s?"mojibake_high":"mojibake_medium":Al.test(e)?"c1":"clean"}const Ul=(0,d.h)("local-exec:encoding-slices");function Bl(e,t){if(void 0===e)return!1;try{return"function"==typeof e?e(t):e}catch{return!1}}function Wl(e,t){return Bl(e?.enabled,t)}function Hl(e,t,r=!1){if("clean"===e)return"clean";switch(t){case"utf8_valid":return"lone_surrogate"===e?"new_damage_cut":"existing_only";case"utf8_invalid":return"lone_surrogate"===e?"new_damage_cut":"replacement"!==e?"existing_only":r?"unknown":"not_text";case"utf8_cut":return"lone_surrogate"===e?"new_damage_cut":"replacement"!==e?"existing_only":r?"unknown":"new_damage_cut";case"utf8_as_other":return"new_damage_decode";case"declared_other":return"replacement"!==e||r?"unknown":"new_damage_decode";case"other_encoding":case"unseen":return"unknown";default:return t}}function ql(e){for(let t=1;t<=Math.min(3,e.length);t++){const r=e[e.length-t]??0;if(128!=(192&r))return(r>=240?4:r>=224?3:r>=192?2:1)>t?t:0}return 0}class zl{constructor(){this.seen=!1,this.invalid=!1,this.carry=new Uint8Array(0)}write(e){if(0===e.length)return;if(this.seen=!0,this.invalid)return;const t=this.carry.length>0?Buffer.concat([this.carry,e]):e,r=ql(t);if(!(0,n.isUtf8)(t.subarray(0,t.length-r)))return this.invalid=!0,void(this.carry=new Uint8Array(0));this.carry=r>0?Uint8Array.from(t.subarray(t.length-r)):t.subarray(0,0)}evidence(){return this.seen?this.invalid?"utf8_invalid":this.carry.length>0?"utf8_cut":"utf8_valid":"unseen"}}const Gl=new Map(Object.entries({zsh:"zsh",zsh_light:"zsh_light",bash:"bash",pwsh:"pwsh",powershell51:"powershell51",naive_pwsh:"naive_pwsh",naive_powershell51:"naive_powershell51",naive_bash:"naive_bash",naive_zsh:"naive_zsh",naive_other:"naive_other"})),Vl=(0,h.Pu)("local_exec.encoding_slice",{description:"Results a local executor returned, and results about to be encoded for the wire, by the boundary they were counted at, the kind of encoding damage their text holds (one kind per result, clean included), whose the damage is as far as the bytes at that boundary say, which executor the result came from, the client's version bucket, for a shell result counted on Windows how the code page lookup stood, and for a shell result which shell ran the command",labelNames:["layer","kind","origin","source","version_bucket","code_page_lookup","shell_kind"]}),Kl=Il[0],Jl=new Map(Il.map(((e,t)=>[e,t])));function Zl(e){return Jl.get(e)??Il.length}class Xl{constructor(){this.worst="clean",this.remaining=262144}note(e){this.walk(e,0)}kind(){return this.worst}capped(){return this.remaining<=0}settled(){return this.remaining<=0||this.worst===Kl}noteText(e){if(0===e.length)return;const t=e.length>this.remaining?Jo(e,this.remaining):e;this.remaining-=Math.max(t.length,1);const r=jl(t);Zl(r)=16)return;if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer)return;if(Array.isArray(e)){for(const r of e)if(this.walk(r,t+1),this.settled())return;return}const r=Object.values(e);for(const e of r)if(this.walk(e,t+1),this.settled())return}}class Ql{constructor(e=1024){this.capacity=e,this.counted=new Set}firstRead(e,t){if(""===e)return!0;const r=`${e}\n${t}`,n=this.counted.delete(r);if(this.counted.add(r),this.counted.size>this.capacity)for(const e of this.counted){this.counted.delete(e);break}return!n}}function Yl(e,t,r,n){const o={layer:r.layer,kind:n,origin:Hl(n,r.evidence??"unseen",!0===r.partial),source:r.source??r.layer,version_bucket:Bc(e.clientVersion)};void 0!==r.codePageLookup&&(o.code_page_lookup=r.codePageLookup),void 0!==r.shellKind&&(o.shell_kind=r.shellKind),Vl.increment(t,1,o)}function eu(e,t){Ul.warn(e,"encoding slice was not counted (result unaffected)",{error:t instanceof Error?t.name:"unknown"})}function tu(e,t,r,n){if(void 0!==e&&Wl(e,t))try{const o=new Xl;o.note(n),Yl(e,t,r,o.kind())}catch(e){eu(t,e)}}function ru(e,t,r,n){if(void 0!==e&&Wl(e,t))try{Yl(e,t,r,n)}catch(e){eu(t,e)}}class nu{constructor(){this.seen=!1,this.invalid=!1}note(e){this.seen=!0,this.invalid||(0,n.isUtf8)(e)||(this.invalid=!0)}evidence(){return this.seen?this.invalid?"utf8_invalid":"utf8_valid":"unseen"}}function ou(e,t,r,n){return void 0===t?e:{execute:async(o,s,i)=>{const a=await e.execute(o,s,i);if(Wl(t,o))try{n(a)&&tu(t,o,{layer:r},a)}catch(e){eu(o,e)}return a}}}new Map([["readArgs","exec_read"],["redactedReadArgs","exec_read"],["grepArgs","exec_grep"],["mcpArgs","exec_mcp"],["readMcpResourceExecArgs","exec_mcp"],["executeHookArgs","exec_hooks"],["fetchArgs","exec_web_fetch"],["shellArgs","exec_shell"],["shellStreamArgs","exec_shell"],["backgroundShellSpawnArgs","exec_shell"],["miniSweAgentBashArgs","exec_shell"],["writeArgs","exec_write"]]);class su{constructor(){this.text={stdout:new Xl,stderr:new Xl},this.bytes={stdout:new zl,stderr:new zl},this.produced={stdout:!1,stderr:!1},this.dropped={stdout:!1,stderr:!1},this.shellKind="unknown"}noteBytes(e,t){this.bytes[e].write(t)}noteText(e,t){0!==t.length&&(this.produced[e]=!0,this.text[e].note(t))}noteDropped(e){this.dropped[e]=!0}noteShell(e){this.shellKind=function(e){return"string"!=typeof e?"unknown":Gl.get(e)??"unknown"}(e)}record(e,t,r,n){for(const o of["stdout","stderr"])this.produced[o]&&ru(e,t,{layer:"exec_shell",evidence:this.evidence(o,r[o]),partial:this.dropped[o]||this.text[o].capped(),codePageLookup:n,shellKind:this.shellKind},this.text[o].kind())}evidence(e,t){if("utf8"!==t)return"other_encoding";const r=this.bytes[e].evidence();return"utf8_cut"===r?"utf8_invalid":r}}var iu=r("node:child_process"),au=r("../utils/dist/workload-spawn.js");const cu=(0,d.h)("local-exec:shell-output-encoding"),lu=(0,Vs.promisify)(iu.execFile),uu=/^\s*OEMCP\s+REG_\w+\s+(\d+)\s*$/m,du=/^\s*ACP\s+REG_\w+\s+(\d+)\s*$/m;function hu(e,t){const r=t.exec(e);return null===r?void 0:Number(r[1])}const pu="㐀-䶿一-鿿豈-﫿",fu=" -〿㈀-㏿︰-﹯＀-￯",mu="‐-※←-⇿─-◿★☆",gu="぀-ヿ",wu=new Map([["cp932",{script:new RegExp(`[${pu}${fu}${mu}${gu}]`),doubleByte:!0}],["cp936",{script:new RegExp(`[${pu}${fu}${mu}${gu}㄀-ㄯ]`),doubleByte:!0}],["cp949",{script:new RegExp(`[${pu}${fu}${mu}${gu}㄰-㆏가-힯]`),doubleByte:!0}],["cp950",{script:new RegExp(`[${pu}${fu}${mu}㄀-ㄯ]`),doubleByte:!0}],["cp874",{script:new RegExp("[฀-๿]"),doubleByte:!1}]]);const yu=function(e){let t,r,n,o,s=!1,i=0;const a=()=>{i+=1;const e=i;n=async function(){const{stdout:e}=await(0,au.D9)(lu,"\\\\.\\GLOBALROOT\\SystemRoot\\System32\\reg.exe",["query","HKLM\\SYSTEM\\CurrentControlSet\\Control\\Nls\\CodePage"],{encoding:"buffer",timeout:3e3,windowsHide:!0});return e}().then((e=>{const i=function(e){const t=Buffer.isBuffer(e)?function(e){return e.length>=2&&255===e[0]&&254===e[1]?e.subarray(2).toString("utf16le"):e.includes(0)?e.toString("utf16le"):e.toString("latin1")}(e):e,r={},n=hu(t,uu),o=hu(t,du);return void 0!==n&&(r.oemcp=n),void 0!==o&&(r.acp=o),r}(e);t=function(e){const{oemcp:t,acp:r}=e;if(void 0===t||void 0===r||t!==r)return;const n=function(e){if(65001===e)return;const t=`cp${e}`;return Js.encodingExists(t)?t:void 0}(t);return void 0!==n&&wu.has(n)?n:void 0}(i),r=i,s=!0,n=void 0,o=void 0===i.oemcp&&void 0===i.acp?"unparsed":"answered",cu.info((0,b.q6)(),"Resolved the fallback encoding for shell output",{encoding:t??"none",oemcp:i.oemcp??"none",acp:i.acp??"none"})}),(t=>{n=void 0,o=function(e){try{if("object"!=typeof e||null===e)return"spawn_error";const t="code"in e?e.code:void 0;return"killed"in e&&!0===e.killed&&"string"!=typeof t?"timeout":"number"==typeof t?"nonzero_exit":"spawn_error"}catch{return"spawn_error"}}(t),cu.warn((0,b.q6)(),"Could not read the Windows code pages; shell output stays UTF-8 only",{error:t instanceof Error?t.message:String(t),attempt:e})}))};return"win32"===e&&a(),{current:()=>("win32"===e&&!s&&void 0===n&&i<3&&a(),t),pages:()=>void 0!==r?r:"win32"!==e?"none":i>=3&&void 0===n?"failed":"pending",lastOutcome:()=>"win32"===e?o??"pending":void 0,settled:()=>n??Promise.resolve()}}(process.platform),vu=Buffer.alloc(0),bu=/[\u0080-\uffff]/;function Su(e){const t=Math.max(0,e.length-3);for(let r=e.length-1;r>=t;r--){const t=e[r];if(128==(192&t))continue;const n=t>=248?1:t>=240?4:t>=224?3:t>=192?2:1,o=e.length-r;return n>o?o:0}return 0}function ku(){const e=new ca.StringDecoder("utf8");return{write:t=>e.write(t),end:()=>e.end()}}function _u(e,t){return Js.decode(t,e,{stripBOM:!1})}const Cu=/[\xe0-\xef][\x80-\xbf]\?/;const Eu=10,xu=Buffer.alloc(0),Pu=new Set([7,8,9,10,11,12,13,27]);function Ru(e,t,r){for(let n=0;n+1(r=void 0,t.end())}}const Au={encoding:"utf8",skip:0};function $u(e){const t=e();let r="utf8";const n={};let o=!1;const s=()=>"utf8"===r?t:n[r]??=Tu(r),i=e=>("utf8"!==r&&e.length>0&&(o=!0),e);let a,c=!0,l=xu,u=!1,d=0;const h=(e,t)=>{const n=function(e){if(!(e.length<2))return 255===e[0]&&254===e[1]?"utf16le":254===e[0]&&255===e[1]?"utf16be":void 0}(e);if(void 0!==n)return{encoding:n,skip:2};if("utf8"===r){if(e.length<2)return t?Au:void 0;const r=0===e[0]?"utf16be":0===e[1]?"utf16le":void 0;if(void 0===r)return Au;const n=Iu(e,r);if(-1!==n)return Ru(e,r,n)?{encoding:r,skip:0}:Au;if(!t)return;const o=e.length-e.length%2;return function(e,t){const r="utf16le"===t?1:0;for(let t=0;te.length?t?o:void 0:Ru(e,r,n)?o:Au}if(-1===i)return t?Au:void 0;if("utf16le"===r&&i%2==0){if(i+1>=e.length)return t?Au:void 0;if(0===e[i+1])return o}return Au},p=e=>{if(e===r)return"";const t=i(s().end());return r=e,t},f=e=>"utf8"===r&&0!==e&&e<128,m=(e,n)=>{let o="",m=e;for(;;){if(c){const e=Math.min(m.length,512-l.length);let r;if(r=l.length>0?Buffer.concat([l,m.subarray(0,e)]):e===m.length?m:m.subarray(0,e),0===r.length)return o;const s=h(r,n||r.length>=512);if(void 0===s)return 1===r.length&&f(r[0])&&(o+=t.write(r),u=!0),l=Buffer.from(r),o;let i=s.skip,g=!1;if(u&&(i="utf8"===s.encoding?1:2,g=r[0]===Eu,u=!1),0===l.length)i>0&&(m=m.subarray(i));else{const t=r.subarray(i);m=m.subarray(e),m=0===m.length?t:0===t.length?m:Buffer.concat([t,m]),l=xu}if(c=g,d=0,a=void 0,o+=p(s.encoding),g)continue}if(0===m.length)return o;if("utf8"===r&&!m.includes(0)&&!m.includes(254)&&!m.includes(255)){const e=m.lastIndexOf(Eu),r=-1===e?-1:m.length-e-1;if(-1===r||r>=2)return o+t.write(m);if(c=!0,0===r)return e>0&&m[e-1]===Eu&&(l=Buffer.of(Eu),u=!0),o+t.write(m);const n=m[m.length-1];return l=Buffer.of(n),u=f(n),o+t.write(u?m:m.subarray(0,e+1))}const e=Iu(m,r,d,a);if(-1===e)return d+=m.length,a=m[m.length-1],o+i(s().write(m));o+=i(s().write(m.subarray(0,e))),m=m.subarray(e),c=!0}};return{write:e=>0===e.length?s().write(e):m(e,!1),peek(){if(!c||0===l.length)return"";const t=h(l,!0);if(void 0===t)return"";const r=u?"utf8"===t.encoding?1:2:t.skip,n=l.subarray(r);return 0===n.length?"":"utf8"===t.encoding?e().write(n):Tu(t.encoding).write(n)},end(){const e=m(xu,!0)+i(s().end());return c=!0,l=xu,u=!1,d=0,a=void 0,e},branch:()=>!0===t.usedCodePage?.()?"code_page":o?"utf16":"utf8"}}var Mu=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Du=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Ou=(0,d.h)("local-exec:shell-core"),Fu=(0,h.Pu)("local_exec.shell.encoding_check",{description:"Shell command output streams that produced text, per encoding detector (U+FFFD): whether the decoded text holds the pattern and how much, which decode path (UTF-8, Windows code page, UTF-16) produced it, which stream, and the machine's Windows code page",labelNames:["detector","outcome","run_count","branch","stream","code_page"]}),Nu="win32"===process.platform,Lu=["CURSOR_CONVERSATION_ID","CURSOR_REQUEST_ID","CURSOR_AGENT_STORE_FILES_DIR","CURSOR_AGENT_STORE_SHARED_PATHS"];function ju(e){return`'${e.replace(/'/g,"'\\''")}'`}async function Uu(e){try{return(await(0,xo.stat)(e)).isDirectory()}catch(e){const t=_c(e);if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}const Bu=["eval-cursorbench","cursorbench","sand-eval","eval-harness"];function Wu(e){return Bu.some((t=>e.includes(t)))?(0,ko.createHash)("sha256").update(e).digest("hex"):e}function Hu(e,t){return e[t]??process.env[t]}const qu=/^[A-Za-z_][A-Za-z0-9_]*$/,zu=/CURSOR_SANDBOX/i;function Gu(e){return qu.test(e)&&!zu.test(e)}function Vu(e){return"function"==typeof e?e():e}function Ku(e,t){const r=void 0===e?[]:[...e];return r.includes(t)||r.push(t),r}function Ju(e){let t=0,r=0;const n=e.length;for(;r"insecure_none"===e?.type?void 0:e?.privateTmp)).find((e=>void 0!==e));if("linux"!==process.platform||!0!==n||void 0===r||!(0,ts.ZU)({basePath:"/tmp",targetPath:e}))return!1;const o=(0,No.W1)(r);return void 0!==o&&await Uu(s.join(o,"tmp",s.relative("/tmp",e)))}(c,t.sandboxPolicy,this.workspacePath))){if(c!==(0,ts.o1)(await i.getCwd(),this.workspacePath))throw new Zu(c);return yield{type:"stderr",data:`The shell's working directory no longer exists: ${c}. The command did not run. Re-run it with working_directory set to an existing directory.\n`},void(yield{type:"exit",code:1,aborted:!1,localExecutionTimeMs:Math.round(performance.now()-o)})}let l,u,d=0,h=0,p=!1,f=!1,m=!1;t.fileOutputThresholdBytes&&this.projectDir&&(l={buffer:"",lineCount:0,size:0,threshold:Number(t.fileOutputThresholdBytes)});const g=t.signal,w={CURSOR_AGENT:"1"};t.conversationId&&(w.CURSOR_CONVERSATION_ID=(0,_o.sh)(t.conversationId)),t.requestId&&(w.CURSOR_REQUEST_ID=t.requestId),this.projectDir&&(w.AGENT_TRANSCRIPTS=s.join(this.projectDir,_o.O2));const y=this.options.extraEnvProvider?.(e,t);void 0!==y&&Object.assign(w,y);const v=t.requestScopedEnv??{};for(const[e,t]of Object.entries(v))void 0!==t&&Gu(e)&&(w[e]=t);const b=w.CURSOR_REQUEST_ID;void 0!==b&&(w.CURSOR_REQUEST_ID=Wu(b)),function(e,t){const r=Lu,n=Object.keys(t).filter((e=>Gu(e)&&!r.includes(e))),o=`builtin unset ${[...Lu,...n].join(" ")} 2>/dev/null || true`,s=[];for(const t of Lu){const r=Hu(e,t);void 0!==r&&s.push(`builtin export ${t}=${ju(r)}`)}for(const e of n){const r=t[e];void 0!==r&&s.push(`builtin export ${e}=${ju(r)}`)}const i=e.__CURSOR_SANDBOX_ENV_RESTORE?.trim(),a=process.env.__CURSOR_SANDBOX_ENV_RESTORE?.trim();e.__CURSOR_SANDBOX_ENV_RESTORE=[o,a,i,...s].filter((e=>void 0!==e&&""!==e)).join("; ")}(w,v),void 0!==w.__CURSOR_SANDBOX_ENV_RESTORE&&(w.__CURSOR_SANDBOX_ENV_RESTORE=function(e,t){let r=e;for(const e of t){if(null==e||0===e.length)continue;const t=Wu(e);t!==e&&(r=r.split(e).join(t))}return r}(w.__CURSOR_SANDBOX_ENV_RESTORE,[t.requestId,b,v.CURSOR_REQUEST_ID,process.env.CURSOR_REQUEST_ID]));const S=function(e,t){const r=Hu(t,"CURSOR_AGENT_STORE_FILES_DIR"),n=function(e){if(void 0===e)return[];try{const t=JSON.parse(e);if("object"!=typeof t||null===t)return[];const r=[];for(const e of Object.values(t))"object"==typeof e&&null!==e&&"path"in e&&"readOnly"in e&&"string"==typeof e.path&&"boolean"==typeof e.readOnly&&r.push({path:e.path,readOnly:e.readOnly});return r}catch{return[]}}(Hu(t,"CURSOR_AGENT_STORE_SHARED_PATHS"));if(void 0===r&&0===n.length)return e;const o=e?.perUser,s=e?.perRepo??e?.perUser??e?.teamAdmin;if("workspace_readwrite"!==s?.type&&"workspace_readonly"!==s?.type)return e;const i=o?.type===s.type?{...o}:{type:s.type};var a;void 0!==r&&(a=r,"workspace_readwrite"!==i.type?i.additionalReadonlyPaths=Ku(i.additionalReadonlyPaths,a):i.additionalReadwritePaths=Ku(i.additionalReadwritePaths,a));for(const e of n)e.readOnly||"workspace_readwrite"!==i.type?i.additionalReadonlyPaths=Ku(i.additionalReadonlyPaths,e.path):i.additionalReadwritePaths=Ku(i.additionalReadwritePaths,e.path);return{...e,perUser:i}}(t.sandboxPolicy,w),k=(0,No.CG)(S??No.BM);let _,C,E,x;S&&(yield{type:"start",sandboxed:"workspace_readonly"===k||"workspace_readwrite"===k}),t.askpassConfig&&!Nu&&(w.SUDO_ASKPASS=t.askpassConfig.helperPath,w.CURSOR_ASKPASS_SOCKET=t.askpassConfig.socketPath,w.CURSOR_ASKPASS_SECRET=t.askpassConfig.secret);const P=this.options.codePageLookup??yu,R=(this.options.outputFallbackEncoding??(()=>P.current()))(),I=()=>function(e){if(void 0===e)return ku();const t=wu.get(e);return void 0!==t&&Js.encodingExists(e)?function(e,t){const{script:r}=t,o=function(e){const{script:t}=e,r=new RegExp(`${t.source}{2}`);let n=!1,o=!1,s=!1;return{note(i,a){if(!s&&0!==i.length){if(!n){const e=bu.exec(i);null!==e&&(n=!0,s=t.test(e[0]))}s||=o&&t.test(i[0])||r.test(i)||e.doubleByte&&void 0!==a&&Cu.test(a.toString("latin1")),o=t.test(i[i.length-1])}},isUtf8Text:()=>s,reset(){n=!1,o=!1,s=!1}}}(t);let s=vu,i=0,a="utf8",c=!1;const l=()=>{a="utf8",o.reset(),i=0},u=(t,n)=>{const s=n?Su(t):0,l=t.subarray(0,t.length-s),u=l.toString("utf8");if("replacement"!==a){const t=l.subarray(i);if(i=0,o.note(t.toString("utf8"),t),o.isUtf8Text())a="replacement";else{const t=0===u.length?"":u[u.length-1],o=n&&r.test(t)?Buffer.byteLength(t):0,d=function(e,t,r){let n=_u(e,t);if(!r)return{text:n,keep:0};const o=Math.min(3,t.length);let s=0;for(;s0&&(c=!0),{text:d.text,keep:i+s}}}return{text:u,keep:s}};return{write:e=>{const t=0===s.length?e:Buffer.concat([s,e]);if(s=vu,"utf8"===a){const e=t.subarray(0,t.length-Su(t));if((0,n.isUtf8)(e)){e.length{const t=e.lastIndexOf("\n");-1===t?o.note(e):(l(),o.note(e.slice(t+1)))})(r),r}}let r="",i=0;for(;i0&&(s=Buffer.from(d.subarray(u.length))),-1===e?o.note(n):l(),i=c;continue}a="undecided"}const{text:h,keep:p}=u(d,-1===e);r+=h,p>0&&(s=Buffer.from(d.subarray(d.length-p))),-1!==e&&l(),i=c}return r},end:()=>{const e=s;s=vu;const t=0===e.length?"":"utf8"===a?e.toString("utf8"):u(e,!1).text;return l(),t},usedCodePage:()=>c}}(e,t):ku()}(R),T={stdout:$u(I),stderr:$u(I)},A=new xl,$=Wl(this.options.encodingSlices,e)?new su:void 0,M=void 0===$?void 0:function(e,t,r){return n=>{try{const o=function(e,t,r){if(!(Object.hasOwn(Hc,e.shell)&&Object.hasOwn(qc,e.parse)&&Object.hasOwn(zc,e.stateFile)&&Object.hasOwn(Gc,e.exit)))return;let n="withheld";if(r){if("function"!=typeof e.callsExit)return;n=!0===e.callsExit()?"yes":"no"}return{shell_kind:e.shell,parse:e.parse,calls_exit:n,state_file:e.stateFile,exit:e.exit,version_bucket:Bc(t)}}(n,t,r);if(void 0===o)return;Vc.increment(e,1,{...o})}catch(t){Wc.warn(e,"PowerShell run was not counted (command unaffected)",{error:t instanceof Error?t.name:"unknown"})}}}(e,this.options.encodingSlices?.clientVersion,function(e,t){return!0===Bl(e?.commandTextReadable,t)}(this.options.encodingSlices,e));let O=!1;const F=()=>{if(!O){O=!0;try{const t={stdout:T.stdout.branch(),stderr:T.stderr.branch()};for(const r of A.labels(t,P.pages()))Fu.increment(e,1,r);$?.record(this.options.encodingSlices,e,t,P.lastOutcome())}catch(t){Ou.warn(e,"shell output encoding check failed (command result unaffected)",{error:t instanceof Error?t.message:String(t)})}}},N=e=>{void 0!==l&&0!==e.length&&(l.file?l.file.write(e):l.buffer+=e)},L=function*(){const e={stdout:p,stderr:f};for(const t of["stdout","stderr"]){const r=T[t].end();if(0===r.length)continue;const n=void 0!==l&&!0!==l.truncated;n&&N(r),!n&&e[t]||(A.note(t,r),$?.noteText(t,r)),e[t]||(yield{type:t,data:r})}F()};try{for await(const r of i.execute(e,t.command,{signal:g,workingDirectory:c,env:w,sandboxPolicy:S,sandboxWorkspaceRoot:this.workspacePath,pipeStdin:t.pipeStdin??!1,keepBackgroundJobs:this.options.keepBackgroundJobs??!1,bufferOutputEvents:this.options.shellOutputBackpressureOptions?.bufferOutputEvents,outputLimiterOptions:this.options.shellOutputBackpressureOptions?.outputLimiterOptions,powershellUtf8Console:Vu(this.options.powershellUtf8Console),powershellUtf8ChildEnv:Vu(this.options.powershellUtf8ChildEnv),powershellParseAfterUtf8Switch:Vu(this.options.powershellParseAfterUtf8Switch),powershellWebRequestUtf8:Vu(this.options.powershellWebRequestUtf8),powershellPerLineStateDump:Vu(this.options.powershellPerLineStateDump),...void 0===M?{}:{powershellRunObserver:M}})){_=0,C="",E="",x="";let e=!1,t=!1;if("stdout"===r.type||"stderr"===r.type){const n=T[r.type],o="stdout"===r.type?p:f,i=void 0===l||!0===l.truncated;let a=!1;if(!o||!i){_=r.data.length;const c="stdout"===r.type?d:h,p=!o&&c+_<=os,f=void 0!==l&&!0!==l.truncated&&l.size+_<=Oc;"stdout"===r.type?e=p:t=p;const m=!o&&!p,g=!i&&!f;if((m||g)&&(x=n.peek(),g&&N(x),m&&(E=x)),(p||f)&&(C=n.write(r.data),a=!0,A.note(r.type,C),$?.noteBytes(r.type,r.data),$?.noteText(r.type,C)),void 0!==l&&l.size+_>Oc)l.truncated=!0;else if(f&&void 0!==l)if(l.size+=_,l.lineCount+=Ju(r.data),l.file)l.file.write(C);else if(l.buffer+=C,l.size>l.threshold){const e=s.join(this.projectDir,Dc);l.path=s.join(e,`${(0,ko.randomUUID)()}.txt`);try{await(0,xo.mkdir)(e,{recursive:!0}),l.file=(0,Ro.createWriteStream)(l.path),l.file.on("error",(e=>{u??=e})),l.file.write(l.buffer)}catch(e){u??=e instanceof Error?e:new Error(String(e)),l.truncated=!0}l.buffer=""}}a||(n.end(),A.note(r.type,x),$?.noteDropped(r.type),$?.noteText(r.type,x))}switch(r.type){case"stdout":e?(d+=_,C&&(yield{type:"stdout",data:C})):p||(E&&(yield{type:"stdout",data:E}),p=!0,yield{type:"stdout_trimmed"});break;case"suppressed_output":m||(m=!0,yield{type:"stdout",data:No.Ls});break;case"stderr":t?(h+=_,C&&(yield{type:"stderr",data:C})):f||(E&&(yield{type:"stderr",data:E}),f=!0,yield{type:"stderr_trimmed"});break;case"exit":{yield*L();const e=Math.max(0,Math.round(performance.now()-o));let t;if(l?.file){if(l.truncated){const e=`\n... (output truncated at ${l.size} bytes) ...\n`;l.file.write(e),l.size+=e.length,l.lineCount+=Xs(e)-1}const e=await new Promise((e=>l.file.end(e)));u??=e??void 0,u?await(0,xo.rm)(l.path,{force:!0}):t=new Fc.pV({filePath:l.path,sizeBytes:BigInt(l.size),lineCount:BigInt(l.lineCount)})}u&&void 0!==l?.path&&(yield{type:"stderr",data:`\nThe full output could not be saved to ${l.path}: ${u.message}\n`}),yield{type:"exit",code:r.code,signal:r.signal,aborted:r.aborted,outputLocation:t,localExecutionTimeMs:e};break}case"stdin_ready":$?.noteShell(r.shell),yield{type:"stdin_ready",stdin:r.stdin,pid:r.pid};break;case"sandbox_denies":yield{type:"sandbox_denies",events:r.events}}}yield*L()}catch(t){if("ENOENT"===_c(t)&&(0,Gs.$f)(c))try{Ou.warn(e,"shell failed with ENOENT in an agent store working directory",{...await(0,Gs.KZ)(c)})}catch{}throw t}finally{F()}}catch(e){r.error=e,r.hasError=!0}finally{Du(r)}}async getCwd(e){return this.executorFor(e).getCwd()}getWorkspacePath(){if(!this.workspacePath)throw new Error("Workspace path is not configured");return this.workspacePath}}class Qu{constructor(e,t){this.innerExecutor=e,this.shellManager=t}async*execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{Mu(r,(0,D.VI)(e.withName("ManagedShellCoreExecutor.execute")),!1),Ou.info(e,"Executing shell command",{command:t.command,workingDirectory:t.workingDirectory,toolCallId:t.toolCallId});let n=null;t.toolCallId&&(n=this.shellManager.getOrCreateShellEmitter(t.toolCallId));for await(const r of this.innerExecutor.execute(e,t)){if(n)switch(r.type){case"stdin_ready":n.emit({type:"stdin_ready",stdin:r.stdin,pid:r.pid});break;case"start":n.emit({type:"start",sandboxed:r.sandboxed});break;case"stdout":n.emit({type:"stdout",data:r.data});break;case"stderr":n.emit({type:"stderr",data:r.data});break;case"exit":n.emit({type:"exit",code:r.code??-1,aborted:r.aborted})}yield r}}catch(e){r.error=e,r.hasError=!0}finally{Du(r)}}async getCwd(e){return this.innerExecutor.getCwd(e)}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}class Yu{constructor(e,t){this.innerExecutor=e,this.askpassConfig=t}async*execute(e,t){const r={...t,askpassConfig:t.askpassConfig??this.askpassConfig};yield*this.innerExecutor.execute(e,r)}async getCwd(e){return this.innerExecutor.getCwd(e)}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}async function ed(e,t){switch(e.type){case"needsApproval":return t.onNeedsApproval(e.approvalReason,e.approvalDetails);case"userRejected":return t.onUserRejected(e.reason);case"cursorIgnore":return t.onPermissionDenied("Blocked by cursor ignore");case"permissionsConfig":return t.onPermissionDenied("Blocked by permissions configuration",{isReadonly:e.isReadonly});case"cursorFiles":return t.onPermissionDenied("Blocked by cursor files protection");case"adminBlock":return t.onPermissionDenied("Blocked by admin repository block");case"adminCommandDenylist":return t.onPermissionDenied(_s(e.pattern));case"unsafeResolution":return t.onPermissionDenied(e.message);default:{const t=e;throw new Error(`Unhandled block reason type: ${JSON.stringify(t)}`)}}}function td(e){switch(e.type){case"userRejected":return e.reason;case"unsafeResolution":return e.message;case"adminCommandDenylist":return _s(e.pattern);case"needsApproval":case"cursorIgnore":case"adminBlock":case"permissionsConfig":case"cursorFiles":return"Command is not allowed";default:{const t=e;return`Command is not allowed (${JSON.stringify(t)})`}}}function rd(e,t,r){return"permissionsConfig"===r.type?{case:"permissionDenied",value:new fe.jn({command:e,workingDirectory:t,error:"Command blocked by permissions configuration",isReadonly:r.isReadonly??!1})}:{case:"rejected",value:new fe.pZ({command:e,workingDirectory:t,reason:td(r)})}}var nd=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const od=(0,d.h)("local-exec:background-shell");function sd(e,t,r){return new Fo.Lt({result:rd(e,t,r)})}class id{constructor(e,t){this.id=e,this.abortController=t,this.disposed=!1,this.completed=!1,this.completionListeners=[]}abort(){this.abortController.abort()}dispose(){this.disposed||(this.disposed=!0,this.abortController.signal.aborted||this.abortController.abort())}get signal(){return this.abortController.signal}isDisposed(){return this.disposed}onComplete(e){this.completed&&this.completion?e(this.completion):this.completionListeners.push(e)}markCompleted(e){if(this.completed)return;this.completed=!0,this.completion=e;const t=[...this.completionListeners];this.completionListeners=[];for(const r of t)r(e)}}async function ad(e,t){let r;try{for(let n=await t.next();!n.done;n=await t.next())"stdin_ready"===n.value.type?(e.stdin=n.value.stdin,e.pid=n.value.pid):"exit"===n.value.type&&(r={code:n.value.code,signal:n.value.signal,aborted:n.value.aborted,outputPath:n.value.outputLocation?.filePath})}catch(e){}finally{e.markCompleted(r??{code:null,aborted:e.signal.aborted})}}function cd(e){e().catch((()=>{}))}class ld{constructor(e){if(this.args=e,this.carryover="",this.matchedOccurrences=0,this.emittedNotifications=0,this.finished=!1,this.monotonicStartMs=performance.now(),this.limit=e.config.notificationLimit??100,e.config.pattern.length>500)throw new Error("Output notification pattern exceeds 500 characters");this.regex=es.L3.compile(e.config.pattern,es.L3.MULTILINE)}observe(e){if(this.finished||this.matchedOccurrences>=this.limit||0===e.length)return;if(e.length>65536){for(const t of function(e){if(0===e.length)return[];const t=Math.max(1,Math.trunc(65536)||1),r=[];let n=0;for(;n=this.limit)break;this.observe(t)}return}const t=this.carryover.length,r=`${this.carryover}${e}`,n=this.regex.matcher(r);for(;this.matchedOccurrencest&&this.queueMatch(e)}this.carryover=Zo(r,1024)}finish(){this.finished||(this.finished=!0,this.flushPendingBatch("finish"),this.clearFlushTimer(),0===this.matchedOccurrences&&this.recordWatchOutcome("silent",{silent_ms:hd(this.monotonicStartMs)}))}queueMatch(e){if(this.matchedOccurrences>=this.limit)return;this.matchedOccurrences+=1;const t=this.matchedOccurrences,r=function(e,t){return e.length<=5e3?`${t}: ${e}`:`${t} is ${e.length} characters; omitted from notification detail.`}(e,1===t?"Matched text":"Latest match");return 1===t?(this.emitNotification({startOccurrence:t,endOccurrence:t,count:1,matchedTextDetail:r}),this.recordWatchOutcome("matched",{first_match_ms:hd(this.monotonicStartMs)}),void(t===this.limit&&this.emitLimitReachedNotification())):(this.pendingBatch?(this.pendingBatch.endOccurrence=t,this.pendingBatch.count+=1,this.pendingBatch.matchedTextDetail=r):this.pendingBatch={startOccurrence:t,endOccurrence:t,count:1,matchedTextDetail:r},t===this.limit?(this.flushPendingBatch("limit"),void this.emitLimitReachedNotification()):void this.scheduleFlush())}scheduleFlush(){if(void 0!==this.flushTimer)return;const e=this.getDebounceMs();this.flushTimer=setTimeout((()=>{this.flushPendingBatch("debounce")}),e)}getDebounceMs(){const e=this.args.debounceMs??function(e){const t=e.debounce;if(void 0!==t&&Number.isFinite(t))return Math.ceil(1e3*t)}(this.args.config)??5e3;return Math.max(e,5e3)}clearFlushTimer(){void 0!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0)}flushPendingBatch(e){const t=this.pendingBatch;t&&(this.pendingBatch=void 0,this.clearFlushTimer(),this.emitNotification(t))}emitNotification(e){this.emittedNotifications+=1;const t=this.args.config.reason.trim()||`Shell output contains /${this.args.config.pattern}/`,r=this.args.config.pattern,n=void 0!==e.matchedTextDetail?` ${e.matchedTextDetail}.`:"",o=1===e.count?`Shell output has pattern /${r}/. This is occurrence number ${e.startOccurrence}.${n} The title message is being displayed to the user.`:`Shell output matched /${r}/ ${e.count} more times since the previous notification. The title message is being displayed to the user.${n}`,s=To(String(this.args.shellId),this.emittedNotifications);var i;this.args.registry.enqueue({conversationId:this.args.conversationId,id:s,source:"shell",payload:{taskId:s,...void 0!==this.args.toolCallId?{toolCallId:this.args.toolCallId}:{},kind:"shell",status:"success",title:(i=t,i.length<=500?i:`${Jo(i,500)}...`),detail:o,outputPath:this.args.outputPath,reason:"task_progress"}})}emitLimitReachedNotification(){this.emittedNotifications+=1;const e=this.args.config.pattern,t=To(String(this.args.shellId),this.emittedNotifications);this.args.registry.enqueue({conversationId:this.args.conversationId,id:t,source:"shell",payload:{taskId:t,...void 0!==this.args.toolCallId?{toolCallId:this.args.toolCallId}:{},kind:"shell",status:"success",title:`Notification limit reached (${this.limit})`,detail:`Shell output matched /${e}/ ${this.limit} times and has reached the notification limit. No further notifications will be sent for this pattern. To continue monitoring, read the output file directly at the output path.`,outputPath:this.args.outputPath,reason:"task_progress"}}),this.recordWatchOutcome("limit_reached")}recordWatchOutcome(e,t){void 0!==this.args.ctx&&od.info(this.args.ctx,"agent.shell_output_notification_match",{event:"agent.shell_output_notification_match",outcome:e,shell_id:this.args.shellId,conversation_id:this.args.conversationId,tool_call_id:this.args.toolCallId,limit:this.limit,...t})}}class ud{constructor(e,t,r){this.innerFactory=e,this.projectDir=t,this.backgroundWorkRegistry=r}async spawn(e,t){const r=this.createObserver(e.ctx,e.shellId,e.conversationId,e.toolCallId,e.outputNotification);if(!r)return this.innerFactory.spawn(e,t);try{return await this.innerFactory.spawn(e,this.createObservingExecutor(t,r))}catch(e){throw r.finish(),e}}async adopt(e){const t=this.createObserver(e.ctx,e.shellId,void 0,e.toolCallId,e.outputNotification);if(!t)return this.innerFactory.adopt(e);e.initialOutput.length>0&&t.observe(e.initialOutput);try{return await this.innerFactory.adopt({...e,eventIterator:this.createObservingIterator(e.eventIterator,t)})}catch(e){throw t.finish(),e}}createObserver(e,t,r,n,o){if(!this.backgroundWorkRegistry||!o)return;if(0===o.pattern.trim().length)return;const i=s.join(this.projectDir,"terminals",`${t}.txt`);try{return new ld({shellId:t,outputPath:i,config:o,conversationId:r??Io,toolCallId:n,registry:this.backgroundWorkRegistry,ctx:e})}catch(r){return void(void 0!==e&&od.warn(e,"Invalid shell output notification pattern",{shellId:t,error:r instanceof Error?r.message:String(r)}))}}createObservingExecutor(e,t){const r=e.execute.bind(e);return{...e,execute:async function*(e,n){try{for await(const o of r(e,n))"stdout"===o.type||"stderr"===o.type?t.observe(o.data):"exit"===o.type&&t.finish(),yield o}finally{t.finish()}}}}createObservingIterator(e,t){const r=e.return?.bind(e);return{next:async()=>{try{const r=await e.next();if(r.done)t.finish();else{const e=r.value;"stdout"===e.type||"stderr"===e.type?t.observe(e.data):"exit"===e.type&&t.finish()}return r}catch(e){throw t.finish(),e}},return:async e=>(t.finish(),r?r(e):{done:!0,value:void 0})}}}class dd{async spawn(e,t){const r=new AbortController,n=new id(e.shellId,r),o=t.execute(e.ctx,{command:e.command,workingDirectory:e.workingDirectory,signal:r.signal,toolCallId:e.toolCallId,conversationId:e.conversationId,requestId:e.requestId,secretScopeId:e.secretScopeId,sandboxPolicy:e.sandboxPolicy,pipeStdin:e.enableWriteShellStdinTool,showElapsedTime:!0})[Symbol.asyncIterator]();try{for(let e=await o.next();!e.done;e=await o.next())if("stdin_ready"===e.value.type){n.stdin=e.value.stdin,n.pid=e.value.pid;break}}catch(e){if(e instanceof No.SandboxUnsupportedError||e instanceof Zu)throw e}return cd((()=>ad(n,o))),n}async adopt(e){const t=new id(e.shellId,e.abortController);return t.stdin=e.stdin,t.pid=e.pid,cd((()=>ad(t,e.eventIterator))),t}}function hd(e){return Math.round(performance.now()-e)}function pd(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}function fd(e){const t=String(e.runningForMs).padEnd(9," "),r=e.status.padEnd(9," ");let n="---\n";return void 0!==e.pid&&0!==e.pid&&(n+=`pid: ${e.pid}\n`),n+=`cwd: ${pd(e.cwd)}\n`,n+=`command: ${pd(e.command)}\n`,void 0!==e.title&&e.title.trim().length>0&&(n+=`title: ${pd(e.title)}\n`),n+=`status: ${r}\n`,n+=`started_at: ${e.startedAt}\n`,n+=`running_for_ms: ${t}\n`,n+="---\n",n}function md(e){return`\n[${e} truncated by cursor: the command wrote more than 1048576 characters to ${e}; only the first 1048576 were captured and the rest was dropped from this file]\n`}class gd{constructor(e,t){this.innerFactory=e,this.projectDir=t}async spawn(e,t){const r=s.join(this.projectDir,"terminals");await(0,xo.mkdir)(r,{recursive:!0});const n=this.createLoggingExecutor(t,e,r);return this.innerFactory.spawn(e,n)}createLoggingExecutor(e,t,r){const o=e.execute.bind(e);return{...e,execute:async function*(e,i){let a,c,l,u=!1,d=!1,h=!1,p=!1;const f=Date.now(),m=new Date(f).toISOString(),g=performance.now();let w,y="running",v=!1,b=Promise.resolve();const S=async e=>{if(c)try{await c.write(e)}catch(e){}},k=t.shellId,_=s.join(r,`${k}.txt`),C=async()=>{if(!a)return;const e=hd(g),r=fd({pid:w,cwd:t.workingDirectory,command:t.command,title:t.description,status:y,startedAt:m,runningForMs:e});try{await a.write(r,0,"utf8")}catch(e){}},E=()=>(b=b.then(C).catch((()=>{})),b),x=()=>{void 0!==l&&(clearInterval(l),l=void 0)},P=async e=>{if(p)return;p=!0,w=e;const r=hd(g),n=fd({pid:e,cwd:t.workingDirectory,command:t.command,title:t.description,status:y,startedAt:m,runningForMs:r});await(0,xo.writeFile)(_,n,"utf8"),l=setInterval((()=>{E()}),5e3)},R=async()=>{a||(a=await Ro.promises.open(_,"r+")),c||(c=await Ro.promises.open(_,"a"))},I=async(e,t)=>{if(!v){if(v=!0,x(),p||await P(),await R(),void 0!==t){const e=hd(g),r=`\n---\n${t}\n`+(i.showElapsedTime?`elapsed_ms: ${e}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await S(r)}y=e,await E()}};try{for await(const r of o(e,i)){if("stdout"===r.type)p||(await P(),await R()),await S(r.data);else if("stderr"===r.type)p||(await P(),await R()),await S(r.data);else if("stdout_trimmed"!==r.type||d)if("stderr_trimmed"!==r.type||h)if("stdin_ready"!==r.type||u)"exit"===r.type&&await I(r.aborted?"aborted":0===r.code?"succeeded":"failed",`exit_code: ${r.code??"unknown"}`);else{u=!0,p||(await P(r.pid),await R());const e=r.stdin;if(e&&!0!==t.suppressStdinLogging){const t=e=>{if(null==e)return;const t="string"==typeof e?e:n.Buffer.isBuffer(e)||e instanceof Uint8Array?n.Buffer.from(e).toString():"";if(!t)return;const r=t.endsWith("\n")?t:`${t}\n`;S(`[stdin] ${r}`)},r=e.write.bind(e);if(e.write=(e,n,o)=>(t(e),r(e,n,o)),"function"==typeof e.end){const r=e.end.bind(e);e.end=(e,n,o)=>(void 0!==e&&t(e),r(e,n,o))}}}else h=!0,p||await P(),await R(),await S(md("stderr"));else d=!0,p||await P(),await R(),await S(md("stdout"));yield r}if(!v){const e=i.signal?.aborted??!1;await I(e?"aborted":"failed")}}catch(e){const t=i.signal?.aborted??!1,r=pd(e instanceof Error?e.message:"Unknown error");if(await I(t?"aborted":"failed",t?void 0:`error: ${r}`),!t)throw e}finally{if(x(),await b,a)try{await a.close()}catch{}if(c)try{await c.close()}catch{}}}}}async adopt(e){const t=s.join(this.projectDir,"terminals");await(0,xo.mkdir)(t,{recursive:!0});const r=s.join(t,`${e.shellId}.txt`),n=e.startTime,o=new Date(n).toISOString(),i=e.monotonicStartMs;let a="running";const c=hd(i),l=fd({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:a,startedAt:o,runningForMs:c})+(e.initialOutput??"");await(0,xo.writeFile)(r,l,"utf8");const u=await Ro.promises.open(r,"r+");let d;try{d=await Ro.promises.open(r,"a")}catch(e){throw await u.close(),e}let h=!1,p=!1,f=!1,m=!1,g=Promise.resolve();const w=async()=>{const t=hd(i),r=fd({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:a,startedAt:o,runningForMs:t});try{await u.write(r,0,"utf8")}catch{}},y=()=>(g=g.then(w).catch((()=>{})),g);let v=setInterval((()=>{y()}),5e3);const b=()=>{void 0!==v&&(clearInterval(v),v=void 0)},S=async()=>{if(!h){h=!0,b(),await g;try{await u.close()}catch{}try{await d.close()}catch{}}},k=async e=>{try{await d.write(e)}catch(e){}},_=async(t,r)=>{if(!p){if(p=!0,b(),void 0!==r){const t=hd(i),n=`\n---\n${r}\n`+(e.showElapsedTime?`elapsed_ms: ${t}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await k(n)}a=t,await y()}},C={next:async()=>{try{const t=await e.eventIterator.next();if(t.done){if(!p){const t=e.abortController.signal.aborted;await _(t?"aborted":"failed")}}else{const e=t.value;"stdout"===e.type||"stderr"===e.type?await k(e.data):"stdout_trimmed"!==e.type||f?"stderr_trimmed"!==e.type||m?"exit"===e.type&&(await _(e.aborted?"aborted":0===e.code?"succeeded":"failed",`exit_code: ${e.code??"unknown"}`),await S()):(m=!0,await k(md("stderr"))):(f=!0,await k(md("stdout")))}return t.done&&await S(),t}catch(t){const r=e.abortController.signal.aborted;throw await _(r?"aborted":"failed"),await S(),t}},return:async()=>{if(!p){const t=e.abortController.signal.aborted;await _(t?"aborted":"failed")}return await S(),e.eventIterator.return?e.eventIterator.return():{done:!0,value:void 0}}};return this.innerFactory.adopt({...e,eventIterator:C})}}class wd{constructor(e,t){this.factory=e,this.backgroundWorkRegistry=t,this.runningShells=new Map,this.nextShellId=1e3+Math.floor(999e3*Math.random())}registerShellWork(e,t){const r=String(e.id);this.backgroundWorkRegistry?.upsertWork({id:r,kind:"shell",state:"running",metadata:Ao(t),abort:()=>{this.abort(e.id)}})}clearShellWork(e){this.backgroundWorkRegistry?.clearWork(String(e))}cleanupShell(e){this.runningShells.has(e)&&(this.runningShells.delete(e),this.clearShellWork(e))}enqueueShellCompletion(e,t,r,n,o,s){if(!this.backgroundWorkRegistry)return;const i=s.aborted?"aborted":0===s.code?"success":"error",a=function(e){if(!e.aborted)return void 0!==e.signal?`signal=${e.signal}`:null!==e.code&&0!==e.code?`exit_code=${e.code}`:void 0}(s),c=function(e){if(!e.aborted)return void 0!==e.signal?{kind:"signal",signal:e.signal}:null!==e.code?{kind:"exit",code:e.code}:void 0}(s),l=n.description?.trim()?n.description:void 0,u=String(e);this.backgroundWorkRegistry.enqueue({conversationId:r??Io,id:u,source:"shell",payload:{taskId:u,...void 0!==t?{toolCallId:t}:{},kind:"shell",status:i,title:n.description||n.command,...a?{detail:a}:{},...s.outputPath?{outputPath:s.outputPath}:{},reason:"task_finished",durationMs:hd(o),...c?{shellEnd:c}:{},...l?{description:l}:{}}})}async spawn(e,t){const r=await this.factory.spawn(e,t),n=Date.now(),o=performance.now();{const __t3b=globalThis[Symbol.for("@cursor/sdk.backgroundShell")];if(typeof __t3b==="function")try{__t3b({conversationId:e.conversationId,toolCallId:e.toolCallId,command:e.command,description:e.description,shell:r})===!0&&(r.__t3kept=!0)}catch{}}return this.runningShells.set(r.id,r),this.registerShellWork(r,{title:e.description||e.command,cwd:e.workingDirectory,startTimeMs:n}),r.signal.addEventListener("abort",(()=>{this.cleanupShell(r.id)})),r.onComplete?.((t=>{this.enqueueShellCompletion(r.id,e.toolCallId,e.conversationId,{command:e.command,description:e.description},o,t),this.cleanupShell(r.id)})),{shellId:r.id,pid:r.pid}}async adopt(e){const t=await this.factory.adopt(e);{const __t3b=globalThis[Symbol.for("@cursor/sdk.backgroundShell")];if(typeof __t3b==="function")try{__t3b({conversationId:e.conversationId,toolCallId:e.toolCallId,command:e.command,description:e.description,shell:t})===!0&&(t.__t3kept=!0)}catch{}}return this.runningShells.set(t.id,t),this.registerShellWork(t,{title:e.description||e.command,cwd:e.workingDirectory,startTimeMs:e.startTime}),t.signal.addEventListener("abort",(()=>{this.cleanupShell(t.id),e.onCleanup?.()})),t.onComplete?.((r=>{this.enqueueShellCompletion(t.id,e.toolCallId,void 0,{command:e.command,description:e.description},e.monotonicStartMs,r),this.cleanupShell(t.id),e.onCleanup?.()})),{shellId:t.id,pid:e.pid}}generateShellId(){for(let e=0;e<=998999;e++){this.nextShellId>999999&&(this.nextShellId=1e3);const e=this.nextShellId;if(this.nextShellId+=1,!this.runningShells.has(e))return e}throw new Error("No available background shell id in range")}abort(e){const t=this.runningShells.get(e);return!!t&&(t.abort(),this.runningShells.delete(e),this.clearShellWork(e),!0)}isRunning(e){return this.runningShells.has(e)}dispose(){for(const[e,t]of this.runningShells)t.__t3kept||t.dispose(),this.clearShellWork(e);this.runningShells.clear()}async writeStdin(e,t){const r=this.runningShells.get(e);if(!r)throw new Error("Shell not found");if(!r.stdin)throw new Error("Shell stdin not available");const n=t.indexOf(""),o=-1!==n?n:t.indexOf("\\u0004");if(-1!==o){const e=t.substring(0,o);e.length>0&&await new Promise(((t,n)=>{r.stdin.write(e,(e=>{e?n(e):t(void 0)}))})),r.stdin.end()}else await new Promise(((e,n)=>{r.stdin.write(t,(t=>{t?n(t):e(void 0)}))}))}}new WeakMap;class yd{constructor(e,t){this.inner=e,this.ownerConversationId=t}enqueue(e){this.inner.enqueue({...e,conversationId:this.ownerConversationId})}enqueueCompletion(e){this.enqueue({conversationId:this.ownerConversationId,id:e.taskId,source:e.kind,payload:e})}pull(e){return this.inner.pull(e)}ack(e){return this.inner.ack(e)}nack(e,t){this.inner.nack(e,t)}suppress(e,t){this.inner.suppress(e,t)}upsertWork(e){this.inner.upsertWork(e)}clearWork(e){return this.inner.clearWork(e)}abortWork(e){return this.inner.abortWork(e)}hasRunningWork(e){return this.inner.hasRunningWork(e)}abortAllWork(e){return this.inner.abortAllWork(e)}listWork(e){return this.inner.listWork(e)}drainCompletions(){return this.inner.drainCompletions()}hasPendingCompletions(e){return this.inner.hasPendingCompletions(e)}markAwaitedCompletion(e){this.inner.suppress(this.ownerConversationId,e)}}class vd{constructor(e,t,r,n,o,s,i,a){if(this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r,void 0!==a)return this.backgroundShellManager=a,void(this.ownsBackgroundShellManager=!1);const c=s&&void 0!==i?new yd(s,i):s,l=o??function(e){const t=new dd;return new gd(t,e)}(n),u=new ud(l,n,c);this.backgroundShellManager=new wd(u,c),this.ownsBackgroundShellManager=!0}getManager(){return this.backgroundShellManager}dispose(){this.ownsBackgroundShellManager&&this.backgroundShellManager.dispose()}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,D.VI)(e.withName("LocalBackgroundShellExecutor.execute")),!1);const n=t.command,o=t.sandboxPolicy?ds(t.sandboxPolicy):void 0,s=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),i=(0,ts.o1)(s),a=new fe.HO(qo(n).structured),c=Cs({command:n,parsingResult:a,blockedCommands:t.adminCommandDenylist});if(void 0!==c)return new Fo.Lt({result:{case:"rejected",value:new fe.pZ({command:n,workingDirectory:i,reason:c})}});let l;if(od.info(e,"Background shell: approval gate reached",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,hasSmartModeApproval:void 0!==t.smartModeApproval,hasSmartModeApprovalReason:void 0!==t.smartModeApproval?.reason,hasSmartModeApprovalRequestId:void 0!==t.smartModeApproval?.requestId,requestedPolicyType:o?.type??"undefined",parserCommandCount:a.executableCommands.length,classifierCommandCount:t.classifierResult?.commands.length??0,commandLength:n.length}),Oo(t)){const r=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:i,skipUnsafeWorkingDirectoryBlock:!0,command:n,parsingResult:a,toolCallId:t.toolCallId,resolveSkippedApprovalPolicy:!0},o);if("block"===r.kind)return od.info(e,"Background shell: invariant blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,skipApproval:t.skipApproval}),sd(n,i,r.reason);l=r.policy??o,od.info(e,"Background shell: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:o?.type??"undefined",effectivePolicyType:l?.type??"undefined"})}else{const r=await this.permissionsService.shouldBlockShellCommand(e,n,{workingDirectory:i,timeout:0,parsingResult:a,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Mo(t)},o);if("block"===r.kind)return od.info(e,"Background shell: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),sd(n,i,r.reason);l=r.policy,od.info(e,"Background shell: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:l.type})}l=await $c(l,{command:n,workingDirectory:i,parsingResult:a,permissionsService:this.permissionsService,ignoreService:this.ignoreService});try{const r=this.backgroundShellManager.generateShellId(),o=l?{perUser:l}:void 0,s={ctx:e,command:n,workingDirectory:i,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:o,shellId:r,enableWriteShellStdinTool:t.enableWriteShellStdinTool,suppressStdinLogging:t.suppressStdinLogging,description:t.description,outputNotification:t.outputNotification},a=await this.backgroundShellManager.spawn(s,this.coreExecutor);return new Fo.Lt({result:{case:"success",value:new Fo.Po({shellId:r,command:n,workingDirectory:i,pid:a.pid})}})}catch(r){if(r instanceof No.SandboxUnsupportedError){const o=l?.type??"unknown";return od.debug(e,"Background shell: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:o,reason:r.reason}),new Fo.Lt({result:{case:"sandboxUnsupported",value:new fe.rI({command:n,workingDirectory:i,sandboxPolicyType:o,reason:r.reason??r.message,isReadonly:"workspace_readonly"===o})}})}return new Fo.Lt({result:{case:"error",value:new Fo.Of({command:n,workingDirectory:i,error:r instanceof Error?r.message:"Unknown error"})}})}}catch(e){r.error=e,r.hasError=!0}finally{nd(r)}}writeStdin(e,t){return this.backgroundShellManager.writeStdin(e,t)}}var bd=r("node:async_hooks");r("../../node_modules/.pnpm/minimatch@10.2.5/node_modules/minimatch/dist/esm/index.js");function Sd(e){return e instanceof Error?e.message:String(e)}function kd(e){return"Failed to read skill file: "+Sd(e)}function _d(e){return"Invalid skill frontmatter: "+Sd(e)}function Cd(e,t){return e||t?void 0:"Description is required"}new Set(["EACCES","EPERM","ENOENT","ENOTDIR","EISDIR","ELOOP","ENAMETOOLONG"]);const Ed=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function xd(e){return e.toLocaleString("en-US")}var Pd=r("node:url");const Rd={beforeShellExecution:"beforeShellExecution",beforeMCPExecution:"beforeMCPExecution",afterShellExecution:"afterShellExecution",afterMCPExecution:"afterMCPExecution",beforeReadFile:"beforeReadFile",afterFileEdit:"afterFileEdit",beforeTabFileRead:"beforeTabFileRead",afterTabFileEdit:"afterTabFileEdit",stop:"stop",beforeSubmitPrompt:"beforeSubmitPrompt",afterAgentResponse:"afterAgentResponse",afterAgentThought:"afterAgentThought",sessionStart:"sessionStart",sessionEnd:"sessionEnd",preCompact:"preCompact",subagentStart:"subagentStart",subagentStop:"subagentStop",preToolUse:"preToolUse",postToolUse:"postToolUse",postToolUseFailure:"postToolUseFailure",workspaceOpen:"workspaceOpen"},Id=e=>"string"==typeof e,Td=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),Ad=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),$d=(e,t=[])=>({isValid:e,errors:t});function Md(e,t,r){void 0===e||Id(e)||r.push(`${t} must be a string if provided`)}const Dd=e=>{const t=[];if(!Td(e))return t.push("Hook script must be an object with either a 'command' property (command hook) or 'type: \"prompt\"' with a 'prompt' property (prompt hook)"),$d(!1,t);const r=e.type;return"prompt"===r?((e,t)=>{Id(e.prompt)?""===e.prompt.trim()&&t.push("Prompt hook 'prompt' property cannot be empty"):t.push("Prompt hook must have a 'prompt' property (string)"),void 0!==e.model&&(Id(e.model)?""===e.model.trim()&&t.push("Prompt hook 'model' cannot be an empty string"):t.push("Prompt hook 'model' must be a string if provided"))})(e,t):"command"===r||void 0===r?((e,t)=>{Id(e.command)||t.push("Hook script command must be a string")})(e,t):t.push(`Invalid hook type: "${r}". Must be "command", "prompt", or omitted (defaults to "command")`),((e,t)=>{if(void 0!==e.matcher)if(Id(e.matcher)){if(""!==e.matcher&&"*"!==e.matcher)try{new RegExp(e.matcher)}catch(r){t.push(`Hook script matcher "${e.matcher}" is not a valid regex: ${r?.message??String(r)}`)}}else t.push("Hook script matcher must be a string if provided");if(void 0!==e.timeout&&("number"!=typeof e.timeout?t.push("Hook script timeout must be a number (seconds)"):e.timeout<=0?t.push("Hook script timeout must be a positive number"):e.timeout>3600&&console.warn(`[hooks] Hook timeout of ${e.timeout}s is very long (>1 hour)`)),void 0!==e.loop_limit){const r=e.loop_limit;null!==r&&("number"!=typeof r?t.push("Hook script loop_limit must be a positive integer or null"):Number.isInteger(r)?r<=0&&t.push("Hook script loop_limit must be a positive integer (use null for no limit)"):t.push("Hook script loop_limit must be an integer"))}void 0!==e.failClosed&&"boolean"!=typeof e.failClosed&&t.push("Hook script failClosed must be a boolean")})(e,t),$d(0===t.length,t)},Od=(e,t)=>{const r=[];if(!Array.isArray(e))return r.push(`${t} must be an array of hook scripts`),$d(!1,r);for(let n=0;n{const t=[];if(!Td(e))return t.push("Hooks config must be an object"),$d(!1,t);if("number"!=typeof e.version?t.push("Config version must be a number"):(!Number.isInteger(e.version)||e.version<1)&&t.push("Config version must be a positive integer"),!Td(e.hooks))return t.push("Config hooks must be an object"),$d(!1,t);void 0!==e.stop_hook_loop_limit&&console.warn("[hooks] DEPRECATION WARNING: 'stop_hook_loop_limit' is deprecated. Use 'loop_limit' on individual hook scripts instead. The configured value is being ignored.");const r=Object.values(Rd),n=e.hooks;for(const[e,o]of Object.entries(n))if(r.includes(e)){if(void 0!==o){const r=Od(o,e);r.isValid||t.push(...r.errors)}}else t.push(`Unknown hook type: ${e}. Valid types are: ${r.join(", ")}`);return $d(0===t.length,t)},Nd={PreToolUse:Rd.preToolUse,PermissionRequest:null,PostToolUse:Rd.postToolUse,UserPromptSubmit:Rd.beforeSubmitPrompt,Stop:Rd.stop,SubagentStop:Rd.subagentStop,SessionStart:Rd.sessionStart,SessionEnd:Rd.sessionEnd,PreCompact:Rd.preCompact,Notification:null},Ld=Object.fromEntries(Object.entries(Nd).filter((e=>jd(e[0])&&null!==e[1])).map((([e,t])=>[t,e])));function jd(e){return Object.prototype.hasOwnProperty.call(Nd,e)}const Ud={Bash:"Shell",Read:"Read",Write:"Write",Edit:"Write",Glob:null,Grep:"Grep",WebFetch:"WebFetch",WebSearch:"WebSearch",Task:"Task"},Bd=["Glob"],Wd=["Notification","PermissionRequest"],Hd=/^[A-Za-z0-9_./:=+-]+$/,qd=/^=|^-.*\./,zd=/\$\{(?:CLAUDE_PROJECT_DIR|CURSOR_PROJECT_DIR|CLAUDE_PLUGIN_ROOT|CURSOR_PLUGIN_ROOT)\}/g,Gd=/^[^\p{Cc}$`"]*$/u,Vd=/\\(?:[$`"\\]|$)/;function Kd(e){return`'${e.replace(/'/g,"'\\''")}'`}function Jd(e){if(Hd.test(e)&&!qd.test(e))return e;const t=e.replace(zd,"");if((t!==e||e.includes("'"))&&Gd.test(t)&&!Vd.test(e))return`"${e}"`;const r=[];let n=0;for(const t of e.matchAll(zd))t.index>n&&r.push(Kd(e.slice(n,t.index))),r.push(`"${t[0]}"`),n=t.index+t[0].length;return(n{},info:()=>{}};function Xd(e,t,r=Zd){const n={loop_limit:null,failClosed:!1};if(t&&"*"!==t&&(n.matcher=t),void 0!==e.timeout&&(n.timeout=e.timeout),"prompt"===e.type)return e.prompt?{type:"prompt",prompt:e.prompt,...n}:null;const o=function(e,t){const r=e.command;if(!r)return null;const n=e.args;return null==n?(void 0!==e.shell&&t.warn(`Hook "${r}" sets shell "${e.shell}", which Cursor does not support; the platform default shell will be used`),r):(o=n,Array.isArray(o)&&o.every((e=>"string"==typeof e))?function(e,t){return[e,...t].map(Jd).join(" ")}(r,n):(t.warn(`Hook "${r}" has invalid "args" (expected an array of strings), skipping`),null));var o}(e,r);return null===o?null:{type:"command",command:o,...n}}function Qd(e,t,r=Zd){const n=[];let o;if("PreToolUse"===t||"PostToolUse"===t){const t=function(e,t=Zd){if(!e||"*"===e)return"*";const r=e.split("|"),n=[],o=[];for(const e of r){const t=e.trim();if(t.startsWith("mcp__")){const e=t.split("__");if(e.length>=3){const t=e.slice(2).join("__");n.push(`MCP:${t}`);continue}}const r=Ud[t];null!==r?void 0!==r?n.includes(r)||n.push(r):n.push(t):Bd.includes(t)&&o.push(`Tool "${t}" is not supported in Cursor and will be ignored`)}for(const e of o)t.warn(e);return 0===n.length?null:n.join("|")}(e.matcher,r);if(null===t)return r.warn(`All tools in matcher "${e.matcher}" are unsupported, skipping hooks`),[];o="*"===t?void 0:t}else"SessionStart"===t||"PreCompact"===t?(e.matcher&&"*"!==e.matcher&&""!==e.matcher&&("SessionStart"===t?["startup","resume","clear","compact"].includes(e.matcher):["manual","auto"].includes(e.matcher))&&r.warn(`${t} trigger matcher "${e.matcher}" is not supported in Cursor, hooks will fire for all triggers`),o=void 0):o=void 0;for(const t of e.hooks){const e=Xd(t,o,r);e&&n.push(e)}return n}function Yd(e,t=Zd){const r={};for(const[n,o]of Object.entries(e)){if(!jd(n)){t.warn(`Unknown Claude Code event "${n}", skipping`);continue}if(Wd.includes(n)){t.warn(`Claude Code event "${n}" is not supported in Cursor and will be ignored`);continue}const e=Nd[n];if(!e){t.warn(`Unknown Claude Code event "${n}", skipping`);continue}const s=[];if(Array.isArray(o))for(const e of o){const r=Qd(e,n,t);s.push(...r)}else void 0!==o&&t.warn(`Claude Code event "${n}" has invalid value (expected array), skipping`);if(s.length>0){const t=r[e]||[];r[e]=[...t,...s]}}return{version:1,hooks:r}}var eh=r("../../node_modules/.pnpm/gray-matter@4.0.3/node_modules/gray-matter/index.js");const th=()=>({});function rh(e,t){return eh(e,{...t,engines:{...t?.engines,js:th,javascript:th}})}function nh(e,t,r){return eh.stringify({content:e,data:{}},t,r)}var oh=r("node:zlib");function sh(e,t){const r=function(e){return e.split(/[/\\]/).filter((e=>e))}(e);for(let e=0;ee.isDirectory())).map((e=>e.name))}catch{return[]}}async removeVersion(e){const t=this.getCacheDir(e);try{await(0,xo.rm)(t,{recursive:!0,force:!0})}catch{}}async removeAllVersions(e){const t=ph(this.cacheRoot,e);await(0,xo.rm)(t,{recursive:!0,force:!0})}async pruneOldVersions(e){const t=await this.listCachedVersions({marketplaceSlug:e.marketplaceSlug,pluginId:e.pluginId}),r=new Set(e.keepVersions.map((e=>dh(e))));for(const n of t)r.has(n)||await this.removeVersion({marketplaceSlug:e.marketplaceSlug,pluginId:e.pluginId,version:n})}async markCacheComplete(e){const t=this.getCacheDir(e);await(0,xo.writeFile)(hh({parent:t,name:uh}),"")}}class mh extends Error{constructor(e,t){super(t),this.reason=e,this.name="PluginContentInstallError"}}const gh=(0,Vs.promisify)(oh.gunzip),wh=/^[A-Za-z0-9._-]{1,128}$/,yh=/^[0-9a-f]{64}$/,vh=/^[1-9]\d{0,18}$/,bh="backend-content://",Sh="backend-content/",kh=new Map([[3,"request_refused"],[5,"not_found"],[9,"account_not_connected"],[10,"revision_superseded"],[12,"unsupported_server"],[14,"unavailable"]]),_h=new Set(["unavailable","revision_superseded","timeout","download_failed","integrity"]);function Ch(e){return e instanceof mh&&_h.has(e.reason)}class Eh{constructor(){this.awaited=new Map}forListing(e){return{startLoad:()=>{for(const[t,r]of this.awaited)r.listing===e&&(r.attemptedThisLoad?r.attemptedThisLoad=!1:this.awaited.delete(t))},heldFailure:({pluginDbId:e,revision:t})=>{const r=this.awaited.get(e);if(void 0!==r&&r.revision===t)return r.attemptedThisLoad=!0,Date.now(){Ch(n)?this.awaited.set(t,{revision:r,reason:n.reason,retryAtMs:Date.now()+6e4,listing:e,attemptedThisLoad:!0}):this.awaited.delete(t)},isRetryDue:()=>this.isRetryDue(),allowImmediateRetry:()=>this.allowImmediateRetry()}}isRetryDue(){const e=Date.now();return[...this.awaited.values()].some((t=>e>=t.retryAtMs))}allowImmediateRetry(){for(const e of this.awaited.values())e.retryAtMs=0}}function xh(e){if("bigint"!=typeof e&&"number"!=typeof e&&"string"!=typeof e)return;const t=String(e);return vh.test(t)?t:void 0}function Ph(e){return e.startsWith(bh)}function Rh(e){return`${Sh}${e}`}function Ih(e,t){return new mh(e,function(e,t){const r=JSON.stringify(t);switch(e){case"unsupported_client":return`Plugin ${r} could not be downloaded: this client cannot install plugins whose files the server provides.`;case"not_found":return`Plugin ${r} could not be downloaded: it no longer exists or you no longer have access to it.`;case"account_not_connected":return`Plugin ${r} could not be downloaded: connect your account on the host of its source repository first.`;case"revision_superseded":return`Plugin ${r} changed while it was downloading. The new version installs on the next plugin refresh.`;case"unavailable":return`Plugin ${r} could not be downloaded: its files cannot be served right now. It installs on a later plugin refresh.`;case"unsupported_server":return`Plugin ${r} could not be downloaded: this server does not provide plugin files.`;case"request_refused":return`Plugin ${r} could not be downloaded: the server refused the request.`;case"download_failed":return`Plugin ${r} could not be downloaded.`;case"timeout":return`Downloading plugin ${r} timed out.`;case"integrity":return`The download of plugin ${r} did not match the size or hash the server gave for it, so it was discarded.`;case"too_large":return`Plugin ${r} could not be downloaded: its files are larger than this client accepts.`;case"unsafe_archive":return`The download of plugin ${r} could not be unpacked safely, so it was discarded.`;case"unpack_failed":return`The download of plugin ${r} could not be written to the plugin cache.`;default:return e}}(e,t))}function Th(e){if("File"!==e.type&&"OldFile"!==e.type&&"Directory"!==e.type)return!0;const t=e.path;return!(0!==t.length&&!t.includes("\0")&&!/^([/\\]|[A-Za-z]:)/.test(t))||t.split(/[/\\]/).includes("..")}async function Ah(e){const{download:t,pluginName:r,content:n,targetDir:o}=e;if(void 0===t)throw Ih("unsupported_client",r);const s=new AbortController;let i;try{i=await async function(e){const t=e[Symbol.asyncIterator](),r=()=>(0,Nr.wj)(t.next(),12e4);try{const e=await r();if(!0===e.done||"header"!==e.value.part.case)return"integrity";const{sha256:t}=e.value.part.value,n=function(e){let t;if("bigint"==typeof e||"number"==typeof e)t=Number(e);else{if("string"!=typeof e||!/^\d{1,15}$/.test(e))return;t=Number(e)}return Number.isSafeInteger(t)&&t>0?t:void 0}(e.value.part.value.sizeBytes);if(void 0===n||"string"!=typeof t||!yh.test(t))return"integrity";if(n>16777216)return"too_large";const o=[];let s=0;for(;;){const e=await r();if(!0===e.done)break;const{part:t}=e.value;if(void 0!==t.case){if("data"!==t.case||0===t.value.byteLength)return"integrity";if(s+=t.value.byteLength,s>n)return"integrity";o.push(t.value)}}const i=Buffer.concat(o,s);return s===n&&(0,ko.createHash)("sha256").update(i).digest("hex")===t?i:"integrity"}finally{Promise.resolve(t.return?.()).catch((()=>{}))}}(t({pluginId:BigInt(e.pluginDbId),revision:n.revision},{signal:s.signal}))}catch(e){throw Ih(function(e){return e instanceof Nr.MU?"timeout":"object"==typeof e&&null!==e&&"code"in e?"number"!=typeof e.code?"download_failed":kh.get(e.code)??"download_failed":"download_failed"}(e),r)}finally{s.abort()}if("string"==typeof i)throw Ih(i,r);const a=await async function(e){let t;try{t=await gh(e,{maxOutputLength:268435456})}catch{return}const r=t.byteLength>=512,n=r&&31===t[0]&&139===t[1],o=r&&682962941===t.readUInt32BE(0);if(r&&!n&&!o)return t}(i);if(void 0===a||!await function(e){return new Promise((t=>{let r=0;const n=(0,ah.p_)({strict:!0,onReadEntry:e=>{r+=1,(r>5e4||Th(e))&&(t(!1),n.abort(new Error("unsafe entry")))}});n.once("end",(()=>t(r>0))),n.once("error",(()=>t(!1))),n.end(e)}))}(a))throw Ih("unsafe_archive",r);try{await async function(e,t){const r=(0,ah.o6)({cwd:t,strict:!0,preserveOwner:!1,filter:(e,t)=>{if(!("type"in t)||Th(t))return!1;const r=!!(64&(t.mode??0));return t.mode="Directory"===t.type||r?493:420,!0}});await new Promise(((t,n)=>{r.once("close",t),r.once("error",n),r.end(e)}))}(a,o)}catch{throw Ih("unpack_failed",r)}}function $h(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")||"/"}function Mh(e,t){if(Object.hasOwn(e,t))return e[t]}function Dh(e,t,r,n){const o=e?.plugins;if(!o||"object"!=typeof o)return[];const s=t?.enabledPlugins??{},i={};r?.enabledPlugins&&Object.assign(i,r.enabledPlugins);const a=void 0!==n?$h(n):void 0,c=new Set,l=[];for(const[e,t]of Object.entries(o)){if(!Array.isArray(t)||0===t.length)continue;if(void 0!==a&&!1===Mh(i,e))continue;let r;void 0!==a&&(r=t.find((t=>!("project"!==t.scope&&"local"!==t.scope||!t.projectPath)&&($h(t.projectPath)===a&&!0===Mh(i,e))))),r||!0!==Mh(s,e)||(r=t.find((e=>"user"===e.scope))),r?.installPath&&!c.has(e)&&(l.push({pluginId:e,installPath:r.installPath}),c.add(e))}return l}var Oh=r("../../node_modules/.pnpm/js-yaml@4.3.1/node_modules/js-yaml/dist/js-yaml.mjs");const Fh=Be.enum(["canvas"]),Nh=Be.array(Fh).transform((e=>[...new Set(e)].sort())),Lh=new Set(["https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","https://agent-plugins.org/schemas/1.0.0/mcp.schema.json"]),jh=/^v?(\d+\.\d+(?:\.\d+)?)$/;function Uh(e){if("object"!=typeof(t=e)||null===t||Array.isArray(t))return;var t;const r=e.$schema;return"string"==typeof r&&r.length>0?r:void 0}function Bh(e){let t;try{t=new URL(e).pathname.split("/")}catch{t=e.split("/")}for(const e of t){const t=jh.exec(e);if(null!==t)return t[1]}}function Wh(e){return void 0===e?{kind:"absent"}:Lh.has(e)?{kind:"supported",id:e,version:Bh(e)??e}:{kind:"unsupported",id:e}}const Hh=10485760,qh=/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/,zh=[".cursor-plugin/plugin.json",".claude-plugin/plugin.json","plugin.json"],Gh=[".cursor-plugin",".claude-plugin"],Vh=[".cursor-plugin/marketplace.json",".claude-plugin/marketplace.json"],Kh=Be.object({source:Be.literal("github"),repo:Be.string().regex(/^[^/]+\/[^/]+$/,"Must be in owner/repo format"),ref:Be.string().optional(),sha:Be.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Jh=Be.object({source:Be.literal("url"),url:Be.string().url().endsWith(".git","URL must end with .git"),ref:Be.string().optional(),sha:Be.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Zh=Be.object({source:Be.literal("git-subdir"),url:Be.string().url().endsWith(".git","URL must end with .git"),path:Be.string().min(1),ref:Be.string().optional(),sha:Be.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Xh=Be.union([Be.string(),Kh,Jh,Zh]),Qh=/^(\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?|never)$/,Yh='Must be a semver version (X.Y.Z) or "never"',ep=Be.object({cursor:Be.string().regex(Qh,Yh).optional(),sand:Be.string().regex(Qh,Yh).optional(),sandMobile:Be.string().regex(Qh,Yh).optional()}),tp=Be.object({name:Be.string().min(1,"Author name is required"),email:Be.string().email().optional()}),rp=Be.enum(["string","number","integer","boolean","object","array","null"]),np=Be.union([rp,Be.array(rp).nonempty().superRefine(((e,t)=>{new Set(e).size!==e.length&&t.addIssue({code:Be.ZodIssueCode.custom,message:"Schema type arrays must not contain duplicates"})}))]);function op(e,t){if(void 0!==e.required)if(void 0===e.properties)for(const r of e.required)t.addIssue({code:Be.ZodIssueCode.custom,message:`Required property "${r}" must be declared in properties`,path:["required"]});else for(const r of e.required)r in e.properties||t.addIssue({code:Be.ZodIssueCode.custom,message:`Required property "${r}" must be declared in properties`,path:["required"]});void 0!==e.minLength&&void 0!==e.maxLength&&e.minLength>e.maxLength&&t.addIssue({code:Be.ZodIssueCode.custom,message:"minLength must be less than or equal to maxLength",path:["minLength"]}),void 0!==e.minimum&&void 0!==e.maximum&&e.minimum>e.maximum&&t.addIssue({code:Be.ZodIssueCode.custom,message:"minimum must be less than or equal to maximum",path:["minimum"]}),void 0!==e.exclusiveMinimum&&void 0!==e.exclusiveMaximum&&e.exclusiveMinimum>=e.exclusiveMaximum&&t.addIssue({code:Be.ZodIssueCode.custom,message:"exclusiveMinimum must be less than exclusiveMaximum",path:["exclusiveMinimum"]}),void 0!==e.minItems&&void 0!==e.maxItems&&e.minItems>e.maxItems&&t.addIssue({code:Be.ZodIssueCode.custom,message:"minItems must be less than or equal to maxItems",path:["minItems"]}),void 0!==e.minProperties&&void 0!==e.maxProperties&&e.minProperties>e.maxProperties&&t.addIssue({code:Be.ZodIssueCode.custom,message:"minProperties must be less than or equal to maxProperties",path:["minProperties"]})}const sp=Be.lazy((()=>Be.object({type:np.optional(),title:Be.string().optional(),description:Be.string().optional(),format:Be.string().optional(),writeOnly:Be.boolean().optional(),placeholder:Be.string().optional(),default:Be.unknown().optional(),enum:Be.array(Be.any()).nonempty().optional(),const:Be.unknown().optional(),properties:Be.record(Be.string(),sp).optional(),required:Be.array(Be.string()).optional(),additionalProperties:Be.union([Be.boolean(),sp]).optional(),items:Be.union([sp,Be.array(sp)]).optional(),minLength:Be.number().int().nonnegative().optional(),maxLength:Be.number().int().nonnegative().optional(),minimum:Be.number().optional(),maximum:Be.number().optional(),exclusiveMinimum:Be.number().optional(),exclusiveMaximum:Be.number().optional(),multipleOf:Be.number().positive().optional(),minItems:Be.number().int().nonnegative().optional(),maxItems:Be.number().int().nonnegative().optional(),uniqueItems:Be.boolean().optional(),minProperties:Be.number().int().nonnegative().optional(),maxProperties:Be.number().int().nonnegative().optional()}).strict().superRefine(op)));function ip(e){const t=sp.superRefine(((e,t)=>{lp(e)&&"object"===e.type||t.addIssue({code:Be.ZodIssueCode.custom,message:'Plugin variable schemas must declare type "object"',path:["type"]})})).safeParse(e);return t.success?up(t.data)?{success:!0,data:t.data}:{success:!1,error:new Be.ZodError([{code:"custom",path:["type"],message:'Plugin variable schemas must declare type "object"'}])}:{success:!1,error:t.error}}const ap=Be.unknown().superRefine(((e,t)=>{const r=ip(e);if(!r.success)for(const e of r.error.issues)t.addIssue({code:"custom",message:e.message,path:e.path})})).transform((e=>{if(!up(e))throw new Error('Plugin variable schema must declare type "object"');return e})),cp=(Be.object({name:Be.string().min(1).transform((e=>e.toLowerCase())).refine((e=>qh.test(e)),"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:Be.string().optional(),source:Xh,description:Be.string().optional(),version:Be.string().optional(),author:tp.optional(),publisher:Be.string().min(1).optional(),homepage:Be.string().url().optional(),repository:Be.string().url().optional(),license:Be.string().optional(),keywords:Be.array(Be.string()).optional(),capabilities:Nh.optional(),logo:Be.string().optional(),category:Be.string().optional(),tags:Be.array(Be.string()).optional(),minClientVersions:ep.optional(),strict:Be.boolean().default(!0),commands:Be.union([Be.string(),Be.array(Be.string())]).optional(),agents:Be.union([Be.string(),Be.array(Be.string())]).optional(),skills:Be.union([Be.string(),Be.array(Be.string())]).optional(),rules:Be.union([Be.string(),Be.array(Be.string())]).optional(),hooks:Be.union([Be.string(),Be.record(Be.string(),Be.unknown())]).optional(),variables:ap.optional(),mcpServers:Be.union([Be.string(),Be.record(Be.string(),Be.unknown()),Be.array(Be.union([Be.string(),Be.record(Be.string(),Be.unknown())]))]).optional()}),Be.object({description:Be.string().optional(),version:Be.string().optional(),pluginRoot:Be.string().optional()}),Be.object({name:Be.string().min(1).regex(qh,"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:Be.string().optional(),description:Be.string().optional(),version:Be.string().optional(),author:tp.optional(),publisher:Be.string().min(1).optional(),homepage:Be.string().url().optional(),repository:Be.string().url().optional(),license:Be.string().optional(),logo:Be.string().optional(),keywords:Be.array(Be.string()).optional(),capabilities:Nh.optional(),minClientVersions:ep.optional(),commands:Be.union([Be.string(),Be.array(Be.string())]).optional(),agents:Be.union([Be.string(),Be.array(Be.string())]).optional(),skills:Be.union([Be.string(),Be.array(Be.string())]).optional(),rules:Be.union([Be.string(),Be.array(Be.string())]).optional(),hooks:Be.union([Be.string(),Be.record(Be.string(),Be.unknown())]).optional(),variables:ap.optional(),mcpServers:Be.union([Be.string(),Be.record(Be.string(),Be.unknown()),Be.array(Be.union([Be.string(),Be.record(Be.string(),Be.unknown())]))]).optional()}));function lp(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function up(e){return lp(e)&&"object"===e.type}function dp(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function hp(e,t){if(lp(e)&&"string"==typeof e.name){const t=dp(e.name);if(t.length>0)return t}return function(e){const t=void 0!==e.repoName?dp(e.repoName):"";return t.length>0?t:`cursor-marketplace-${e.fallbackId??(0,ko.randomUUID)()}`}(t)}function pp(e){if(lp(e)&&lp(e.owner)){const t="string"==typeof e.owner.name&&e.owner.name.trim().length>0?e.owner.name:"Unknown",r="string"==typeof e.owner.email&&e.owner.email.trim().length>0?e.owner.email:void 0;return{name:t,...void 0!==r?{email:r}:{}}}return{name:"Unknown"}}function fp(e){return"string"==typeof e?e:void 0}function mp(e){if(!Array.isArray(e))return;const t=e.filter((e=>"string"==typeof e));return t.length>0?t:void 0}function gp(e){return"string"==typeof e?e:mp(e)}function wp(e){if(!lp(e)||!lp(e.metadata))return;const t={description:fp(e.metadata.description),version:fp(e.metadata.version),pluginRoot:fp(e.metadata.pluginRoot)};return void 0!==t.description||void 0!==t.version||void 0!==t.pluginRoot?t:void 0}function yp(e){if(!lp(e))return;const t=fp(e.name);if(void 0===t||0===t.length)return;const r=fp(e.email);return{name:t,...void 0!==r?{email:r}:{}}}function vp(e){if("string"==typeof e||lp(e))return e;if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e||lp(e)));return t.length>0?t:void 0}}function bp(e){if("string"==typeof e||lp(e))return e}function Sp(e){if(void 0===e)return;const t=ip(e);return t.success?t.data:void 0}function kp(e,t={}){if(e.length>Hh)return{success:!1,error:"Manifest exceeds maximum size of 10485760 bytes"};let r;try{r=JSON.parse(e)}catch(e){return{success:!1,error:`Invalid JSON: ${e instanceof Error?e.message:"Unknown error"}`}}if(!lp(r))return{success:!1,error:"Invalid marketplace manifest: expected a JSON object"};const n=[],o=[],i=new Set;return(Array.isArray(r.plugins)?r.plugins:[]).forEach(((e,t)=>{const r=function(e,t){if(!lp(e))return{skippedEntry:{index:t,error:`Plugin entry at index ${t} is not an object`}};const r="string"==typeof(n=e.source)?n:lp(n)?"github"===n.source&&"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:fp(n.ref),sha:fp(n.sha)}:("url"===n.source||void 0===n.source)&&"string"==typeof n.url&&n.url.length>0?{source:"url",url:n.url,ref:fp(n.ref),sha:fp(n.sha)}:"git-subdir"===n.source&&"string"==typeof n.url&&n.url.length>0&&"string"==typeof n.path&&n.path.length>0?{source:"git-subdir",url:n.url,path:n.path,ref:fp(n.ref),sha:fp(n.sha)}:"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:fp(n.ref),sha:fp(n.sha)}:void 0:void 0;var n;if(void 0===r){const r=fp(e.name);return{skippedEntry:{index:t,...void 0!==r&&r.length>0?{name:r}:{},error:`Plugin entry at index ${t} has no usable source`}}}const o=("string"==typeof e.name?dp(e.name):"")||function(e){if("string"==typeof e){const t=dp((0,s.basename)(e));return t.length>0?t:void 0}if("github"===e.source){const t=dp(e.repo.split("/").at(-1)??"");return t.length>0?t:void 0}if("git-subdir"===e.source){const t=dp((0,s.basename)(e.path));return t.length>0?t:void 0}let t=e.url;try{t=new URL(e.url).pathname}catch{}for(;t.endsWith("/");)t=t.slice(0,-1);t.toLowerCase().endsWith(".git")&&(t=t.slice(0,-4));const r=dp((0,s.basename)(t));return r.length>0?r:void 0}(r);if(void 0===o)return{skippedEntry:{index:t,error:`Plugin entry at index ${t} has no usable name`}};const i=Nh.safeParse(e.capabilities);if(void 0!==e.capabilities&&!i.success)return{skippedEntry:{index:t,name:o,error:`Plugin entry at index ${t} has invalid capabilities: ${i.error.issues.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`}};const a=i.success?i.data:void 0,c=function(e){const t=ep.safeParse(e);if(t.success&&(void 0!==t.data.cursor||void 0!==t.data.sand||void 0!==t.data.sandMobile))return t.data}(e.minClientVersions);return{entry:{name:o,displayName:fp(e.displayName),source:r,description:fp(e.description),version:fp(e.version),author:yp(e.author),publisher:fp(e.publisher),homepage:fp(e.homepage),repository:fp(e.repository),license:fp(e.license),keywords:mp(e.keywords),logo:fp(e.logo),category:fp(e.category),tags:mp(e.tags),strict:"boolean"!=typeof e.strict||e.strict,commands:gp(e.commands),agents:gp(e.agents),skills:gp(e.skills),rules:gp(e.rules),hooks:bp(e.hooks),variables:Sp(e.variables),mcpServers:vp(e.mcpServers),...void 0!==a&&{capabilities:a},...void 0!==c&&{minClientVersions:c}}}}(e,t);"skippedEntry"in r?o.push(r.skippedEntry):i.has(r.entry.name)?o.push({index:t,name:r.entry.name,error:`Duplicate plugin name "${r.entry.name}" at index ${t}`}):(i.add(r.entry.name),n.push(r.entry))})),{success:!0,data:{name:hp(r,t),owner:pp(r),description:fp(r.description),plugins:n,metadata:wp(r),skippedPluginEntries:o}}}function _p(e){if(e.length>Hh)return{success:!1,error:"Manifest exceeds maximum size of 10485760 bytes"};let t;try{t=JSON.parse(e)}catch(e){return{success:!1,error:`Invalid JSON: ${e instanceof Error?e.message:"Unknown error"}`}}const r=Wh(Uh(t)),n=cp.safeParse(t);return n.success?{success:!0,data:n.data,..."unsupported"===r.kind&&{unrecognizedSchemaId:r.id}}:{success:!1,error:`Invalid plugin manifest: ${n.error.issues.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`,details:n.error}}function Cp(e,t){if("string"!=typeof e)return null;let r=e;if(r.startsWith("./")&&(r=r.slice(2)),void 0!==t){let e=t;e.startsWith("./")&&(e=e.slice(2)),e.endsWith("/")&&(e=e.slice(0,-1)),r=`${e}/${r}`}return r||"."}function Ep(e){return!e.includes("..")&&!(0,s.isAbsolute)(e)&&!e.includes("://")}var xp=r("../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js");const Pp=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g,Rp=/\$%7B([^%/?#]+?)%7D/gi;function Ip(e,t){return Tp(e,"function"==typeof t?t:function(e){const t=new Map(Object.entries(e).map((([e,t])=>[e.toLowerCase(),t])));return r=>e[r]??t.get(r.toLowerCase())}(t))}function Tp(e,t){if("string"==typeof e)return function(e,t){return e.replace(Rp,"${$1}").replace(Pp,((e,r,n,o)=>{if(void 0!==r)return t(r)??e;if(void 0===n)return e;const s=t(n);return void 0!==s?s:void 0!==o?o:e}))}(e,t);if(Array.isArray(e))return e.map((e=>Tp(e,t)));if(function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e)){const r={};for(const[n,o]of Object.entries(e))r[n]=Tp(o,t);return r}return e}function Ap(e,t){return e.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g,(()=>t)).replace(/\$\{CURSOR_PLUGIN_ROOT\}/g,(()=>t))}const $p={log:()=>{},increment:()=>{},distribution:()=>{},captureException:()=>{}},Mp=Be.object({command:Be.string().optional(),args:Be.array(Be.string()).optional(),env:Be.record(Be.string(),Be.string()).optional(),url:Be.string().optional(),headers:Be.record(Be.string(),Be.string()).optional(),cwd:Be.string().optional(),envFile:Be.string().optional(),auth:Be.object({CLIENT_ID:Be.string(),CLIENT_SECRET:Be.string().optional(),scopes:Be.array(Be.string()).optional()}).optional(),enabledTools:Be.array(Be.string()).optional(),placement:Be.enum(["server","client"]).optional(),tls:Be.object({caBundle:Be.string().trim().min(1).max(131072)}).optional()}),Dp=Be.object({mcpServers:Be.record(Be.string(),Mp).optional()}),Op=[".mcp.json","mcp.json"],Fp=new Set(["author","owner","source","metadata"].map((e=>e.toLowerCase())));function Np(e,t){if(!function(e){return Fp.has(e.toLowerCase())}(e))return!1;if(!function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(t))return!1;const r=t;switch(e.toLowerCase()){case"author":case"owner":return"string"==typeof r.name;case"source":return"string"==typeof r.source||"string"==typeof r.repo||"string"==typeof r.path||"string"==typeof r.ref||"string"==typeof r.sha;case"metadata":return"string"==typeof r.description||"string"==typeof r.version||"string"==typeof r.pluginRoot;default:return!1}}function Lp(e){return"object"==typeof e&&null!==e&&("command"in e||"url"in e)}function jp(e){const t=void 0!==e&&e.length>0?e.replace(/\/+$/,""):void 0;return Op.map((e=>void 0!==t?`${t}/${e}`:e))}function Up(e,t,r){if(!e.mcpServers)return e;const n={};for(const[r,o]of Object.entries(e.mcpServers)){const e={...o};if("string"==typeof o.command&&(e.command=Ap(o.command,t)),Array.isArray(o.args)&&(e.args=o.args.map((e=>"string"==typeof e?Ap(e,t):e))),o.env&&"object"==typeof o.env){const r={};for(const[e,n]of Object.entries(o.env))r[e]="string"==typeof n?Ap(n,t):n;e.env=r}"string"==typeof o.cwd&&(e.cwd=Ap(o.cwd,t)),n[r]=e}return function(e,t){const r=t?.cloudAgentEnvLookup,n=t?.configuredVariables;if(void 0!==r)return Ip(e,r);const o=new Map(Object.keys(n??{}).map((e=>[e.toLowerCase(),e])));return Ip(e,(e=>{const t=process.env[e];if(void 0!==t)return t;const r=void 0!==n&&Object.hasOwn(n,e)?e:o.get(e.toLowerCase()),s=void 0!==r?n?.[r]:void 0;return null!=s?"string"==typeof s?s:"number"==typeof s||"boolean"==typeof s||"bigint"==typeof s?String(s):JSON.stringify(s):void 0}))}({...e,mcpServers:n},r)}function Bp(e,t,r){try{const n=(0,xp.qg)(e),o=Uh(n);if(void 0!==o){const e=r?.log??$p;"unsupported"===Wh(o).kind?e.log("debug",`mcp.json declares an unrecognized $schema, loading anyway: ${o}`):function(e,t){if(void 0===e||void 0===t)return!1;const r=Bh(e),n=Bh(t);return void 0!==r&&void 0!==n&&r!==n}(r?.pluginSchemaId,o)&&e.log("debug",`mcp.json $schema ${o} disagrees with plugin.json $schema ${r?.pluginSchemaId}, loading anyway`)}const s=Dp.safeParse(n),i=!0===r?.skipExpansion;if(s.success&&s.data.mcpServers&&Object.keys(s.data.mcpServers).length>0)return i?s.data:Up(s.data,t,r);const a={};for(const[e,t]of Object.entries(n))"mcpServers"!==e&&!Np(e,t)&&Lp(t)&&(a[e]=t);if(Object.keys(a).length>0){const e=Dp.safeParse({mcpServers:a});if(e.success)return i?e.data:Up(e.data,t,r)}return null}catch{return null}}function Wp(e,t,r){for(const[n,o]of Object.entries(t))e.mcpServers[n]=o,e.mcpServerSourcePaths[n]=r}async function Hp(e,t,r,n={}){const o=n.toSourcePath??(e=>e),s=n.installPathForExpansion??"",i=n.fallbackFileNames??Op,a=n.manifestPrecedence??"override",c={},l={};for(const t of i){const r=await e(t);if(null===r)continue;const i=Bp(r,s,n.parserOptions);if(i?.mcpServers)for(const[e,r]of Object.entries(i.mcpServers))void 0===c[e]&&(c[e]=r,l[e]=o(t))}if(void 0!==t){const i=await async function(e,t,r={}){const n=r.toSourcePath??(e=>e),o=r.installPathForExpansion??"",s={mcpServers:{},mcpServerSourcePaths:{}},i=async e=>{const i=e.replace(/^\.\//,"");if(!Ep(i))return;const a=await t(i);if(null===a)return;const c=Bp(a,o,r.parserOptions);c?.mcpServers&&Object.keys(c.mcpServers).length>0&&Wp(s,c.mcpServers,n(i))},a=e=>{const t=Bp(JSON.stringify(e),o,r.parserOptions);t?.mcpServers&&Object.keys(t.mcpServers).length>0&&Wp(s,t.mcpServers,r.manifestSourcePath??"manifest")};if("string"==typeof e)await i(e);else if(Array.isArray(e))for(const t of e)"string"==typeof t?await i(t):"object"==typeof t&&null!==t&&a(t);else"object"==typeof e&&null!==e&&a(e);return s}(t,e,{toSourcePath:o,manifestSourcePath:r,installPathForExpansion:s,parserOptions:n.parserOptions});for(const[e,t]of Object.entries(i.mcpServers))"fill"===a&&void 0!==c[e]||(c[e]=t,l[e]=i.mcpServerSourcePaths[e])}return 0===Object.keys(c).length?null:{mcpServers:c,...Object.keys(l).length>0&&{mcpServerSourcePaths:l}}}const qp=new Set(["CREDENTIAL","CREDENTIALS","KEY","PASSPHRASE","PASSWORD","SECRET","TOKEN"]);function zp(e){return function(e){return e.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/[^a-z\d]+/gi,"_").toUpperCase().split("_").filter((e=>e.length>0))}(e).some((e=>qp.has(e)))}const Gp=/\$\{(?:env:([A-Z][A-Z0-9_]*)|([A-Z][A-Z0-9_]*)(?::-([^}]*))?)\}/g,Vp=new Set(["CURSOR_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT"]),Kp=new Set(["api","aws","db","dd","gcp","http","https","id","mcp","ssl","tls","uri","url"]);function Jp(e){return e.split("_").filter((e=>e.length>0)).map((e=>{const t=e.toLowerCase();return Kp.has(t)?e.toUpperCase():e.charAt(0).toUpperCase()+t.slice(1)})).join(" ")}function Zp(e,t){if("string"!=typeof e){if(Array.isArray(e))for(const r of e)Zp(r,t);else if(null!==e&&"object"==typeof e)for(const r of Object.values(e))Zp(r,t)}else for(const[,r,n,o]of e.matchAll(Gp)){const e=r??n;if(void 0===e||Vp.has(e)||t.has(e))continue;const s=void 0===r?`\${${e}}`:`\${env:${e}}`;t.set(e,{reference:s,defaultValue:o})}}function Xp(e){if(void 0===e?.mcpServers)return;const t=new Map;if(Zp(e.mcpServers,t),0===t.size)return;const r={};for(const e of[...t.keys()].sort()){const n=t.get(e);if(void 0===n)continue;const{reference:o,defaultValue:s}=n;r[e]={type:"string",title:Jp(e),description:void 0===s||0===s.length?`Referenced as \`${o}\` in this plugin's MCP configuration.`:`Referenced as \`${o}\` in this plugin's MCP configuration. Defaults to \`${s}\` when left blank.`,...zp(e)?{writeOnly:!0}:{}}}return{type:"object",properties:r}}const Qp=[".md",".mdc",".markdown"],Yp=[...Qp,".txt"],ef=/^---\s*\n([\s\S]*?)\n---/;function tf(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function rf(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9.-]/g,"")}function nf(e){const t=e.match(ef);if(!t)return{};try{const e=Oh.Ay.load(t[1],{schema:Oh.Ay.JSON_SCHEMA});if(!tf(e))return{};const r=tf(e.metadata)?e.metadata:void 0,n=of(e.environments??r?.environments);return{disabledEnvironments:of(e["disabled-environments"]??r?.disabledEnvironments),environments:n,name:"string"==typeof e.name?e.name:void 0,description:"string"==typeof e.description?e.description:void 0}}catch{const e=t[1],r=e.match(/^name:\s*(.+)$/m),n=e.match(/^description:\s*(.+)$/m);return r||n?{name:r?r[1].trim():void 0,description:n?n[1].trim():void 0}:{}}}function of(e){if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e&&e.length>0));return 0===t.length?void 0:t}if("string"==typeof e){const t=e.split(",").map((e=>e.trim())).filter((e=>e.length>0));return 0===t.length?void 0:t}}function sf(e){return rf((0,s.basename)(e).replace(/\.(md|mdc|markdown|txt)$/i,""))}function af(e){const t=new Set,r=[];for(const n of e)t.has(n.name)||(t.add(n.name),r.push(n));return r}class cf{constructor(e){this.fetcher=e}async discoverComponents(e={}){const t=e.basePath??"",r=t?`${t}/`:"",n=e.manifest;let o;try{o=await this.fetcher.listDirectory(t)}catch{o=[]}const s=new Set(o.filter((e=>"dir"===e.type)).map((e=>e.name.toLowerCase()))),i=Op.filter((e=>o.some((t=>"file"===t.type&&t.name===e)))),a=o.some((e=>"file"===e.type&&"SKILL.md"===e.name)),[c,l,u,d,h,p,f]=await Promise.all([a&&void 0===n?.skills?this.discoverRootSkill(r):Promise.resolve(null),void 0!==n?.skills?this.discoverFromManifestPaths(r,n.skills,!0,Qp):s.has("skills")?this.discoverSkills(`${r}skills`):Promise.resolve([]),void 0!==n?.agents?this.discoverFromManifestPaths(r,n.agents,!1,Qp):s.has("agents")?this.discoverMarkdownComponents(`${r}agents`,Qp):Promise.resolve([]),void 0!==n?.hooks?this.discoverHooksFromManifest(r,n.hooks):s.has("hooks")?this.discoverHooksFromJson(`${r}hooks/hooks.json`):Promise.resolve([]),void 0!==n?.commands?this.discoverFromManifestPaths(r,n.commands,!1,Yp):s.has("commands")?this.discoverMarkdownComponents(`${r}commands`,Yp):Promise.resolve([]),void 0!==n?.rules?this.discoverFromManifestPaths(r,n.rules,!1,Qp):s.has("rules")?this.discoverMarkdownComponents(`${r}rules`,Qp):Promise.resolve([]),this.discoverMcpServers(r,n?.mcpServers,i)]);return{skills:af(c?[c,...l]:l),agents:af(u),hooks:d,commands:af(h),rules:af(p),mcpServers:f.servers,mcpVariables:f.variables,mcpConfigs:f.configs}}async discoverHooksFromJson(e){try{if(!await this.fetcher.fileExists(e))return[];const{content:t}=await this.fetcher.fetchFile(e),r=JSON.parse(t);return tf(r)&&tf(r.hooks)?Object.keys(r.hooks).map((t=>({name:rf(t),path:e,description:`Hook: ${t}`}))):[]}catch{return[]}}async discoverHooksFromManifest(e,t){if("string"==typeof t){if(!Ep(t))return[];const r=`${e}${t.replace(/^\.\//,"")}`;return r.endsWith(".json")?this.discoverHooksFromJson(r):this.discoverHooksFromJson(`${r}/hooks.json`)}const r=t.hooks??t;return!r||"object"!=typeof r||Array.isArray(r)?[]:Object.keys(r).map((e=>({name:rf(e),path:"manifest",description:`Hook: ${e}`})))}async discoverFromManifestPaths(e,t,r=!1,n=Qp){if("string"==typeof t){if(!Ep(t))return[];const o=`${e}${t.replace(/^\.\//,"")}`.replace(/\/$/,"");return r?this.discoverSkills(o):this.discoverMarkdownComponents(o,n)}const o=[];for(const n of t)try{if(!Ep(n))continue;const t=`${e}${n.replace(/^\.\//,"")}`;if(r){const e=t.endsWith("SKILL.md")?t:`${t.replace(/\/$/,"")}/SKILL.md`;if(!await this.fetcher.fileExists(e)){const e=t.replace(/\/$/,""),r=await this.discoverSkills(e);o.push(...r);continue}let r=sf(t.endsWith("SKILL.md")?t.slice(0,-8).replace(/\/$/,""):t);const{content:n}=await this.fetcher.fetchFile(e),s=nf(n);if(r=s.name??r,r){const t={disabledEnvironments:s.disabledEnvironments,environments:s.environments,name:rf(r),path:e};void 0!==s.description&&(t.description=s.description),o.push(t)}}else{if(!await this.fetcher.fileExists(t))continue;let e=sf(t);const{content:r}=await this.fetcher.fetchFile(t),n=nf(r);e=n.name??e;const s=n.description;if(e){const r={name:rf(e),path:t};void 0!==s&&(r.description=s),o.push(r)}}}catch{}return o}async discoverMarkdownComponents(e,t=Qp,r=new Set){let n;try{n=await this.fetcher.listDirectory(e,r)}catch{return[]}const o=n.filter((e=>"file"===e.type&&t.some((t=>e.name.endsWith(t))))),s=n.filter((e=>"dir"===e.type)),[i,a]=await Promise.all([Promise.all(o.map((async e=>{try{let t=sf(e.name);const{content:r}=await this.fetcher.fetchFile(e.path),n=nf(r);t=n.name?rf(n.name):t;const o=n.description;if(!t)return null;const s={name:t,path:e.path};return void 0!==o&&(s.description=o),s}catch{return null}}))),Promise.all(s.map((e=>this.discoverMarkdownComponents(e.path,t,r))))]);return[...i.filter((e=>null!==e)),...a.flat()]}async discoverRootSkill(e){try{const t=`${e}SKILL.md`;let r=rf((0,s.basename)(e.replace(/[\\/]+$/,"")));const{content:n}=await this.fetcher.fetchFile(t),o=nf(n);if(r=o.name?rf(o.name):r,!r)return null;const i={disabledEnvironments:o.disabledEnvironments,environments:o.environments,name:r,path:t};return void 0!==o.description&&(i.description=o.description),i}catch{return null}}async discoverSkills(e){let t;try{t=await this.fetcher.listDirectory(e)}catch{return[]}const r=t.filter((e=>"dir"===e.type));return(await Promise.all(r.map((async e=>{try{const t=`${e.path}/SKILL.md`;if(!await this.fetcher.fileExists(t))return null;const{content:r}=await this.fetcher.fetchFile(t),n=nf(r),o=n.name?rf(n.name):rf(e.name);if(!o)return null;const s={disabledEnvironments:n.disabledEnvironments,environments:n.environments,name:o,path:t};return void 0!==n.description&&(s.description=n.description),s}catch{return null}})))).filter((e=>null!==e))}async discoverMcpServers(e,t,r){const n=new Map,o=async t=>{const r=n.get(t);if(void 0!==r)return r;const o=this.fetcher.fetchFile(`${e}${t}`).then((({content:e})=>e)).catch((()=>null));return n.set(t,o),o},s=async n=>Hp(o,t,void 0!==t?"manifest":void 0,{fallbackFileNames:r,manifestPrecedence:n,toSourcePath:t=>`${e}${t}`,parserOptions:{skipExpansion:!0}}),i=await s("fill");if(void 0===i?.mcpServers)return{servers:[],variables:void 0,configs:void 0};const a=void 0===t?i:await s("override"),c=a?.mcpServers??i.mcpServers,l={};for(const[e,t]of Object.entries(c))l[e]=t;return{servers:Object.keys(i.mcpServers).map((e=>({name:rf(e),path:i.mcpServerSourcePaths?.[e]??"manifest"}))),variables:Xp(a??i),configs:l}}}class lf extends Error{constructor(e,t){super(`Invalid Claude Code plugin identifier "${t}": ${e}`),this.raw=t,this.name="CCPluginIdentifierError"}}function uf(e){const t=e.trim();if(!t)throw new lf("Empty identifier",e);const r=/^[a-zA-Z0-9_-]+$/,n=t.indexOf("@");if(n!==t.lastIndexOf("@"))throw new lf("Plugin identifier cannot contain multiple @ symbols",e);if(-1===n){if(!r.test(t))throw new lf("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(t.length>100)throw new lf("Plugin name must be 100 characters or less",e);return{name:t,sourceType:"marketplace",marketplace:"claude-plugins-official",raw:e}}const o=t.slice(0,n).trim(),s=t.slice(n+1).trim();if(!o)throw new lf("Missing plugin name before @",e);if(!s)throw new lf("Missing source after @",e);if(!r.test(o))throw new lf("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(o.length>100)throw new lf("Plugin name must be 100 characters or less",e);if(s.startsWith("github:")){const t=s.slice(7).trim();if(!t||!/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(t))throw new lf("Invalid GitHub repo format, expected 'org/repo' (e.g., 'anthropics/claude-plugins')",e);return{name:o,sourceType:"github",githubRepo:t,raw:e}}if(s.startsWith("local:")){const t=s.slice(6).trim();if(!t)throw new lf("Missing path after 'local:'",e);return{name:o,sourceType:"local",localPath:t,raw:e}}if(s.startsWith("url:")){const t=s.slice(4).trim();if(!t)throw new lf("Missing Git URL after 'url:'",e);try{new URL(t)}catch{throw new lf("Invalid Git URL format",e)}return{name:o,sourceType:"url",gitUrl:t,raw:e}}const i=s.indexOf("#");let a,c;if(-1!==i?(a=s.slice(0,i).trim(),c=s.slice(i+1).trim()):a=s,!a)throw new lf("Missing marketplace name",e);if(!r.test(a))throw new lf("Marketplace name must contain only alphanumeric characters, dashes, and underscores",e);return{name:o,sourceType:"marketplace",marketplace:a,version:c,raw:e}}function df(e){if("claude-plugin"===e.source)return e.sourceInfo.raw;if("user-local"===e.source)return`user-local:${e.sourceInfo.name}`;if("extension"===e.source){const t=e.sourceInfo;return`extension:${t.extensionId}:${t.localPath}`}const t=e.sourceInfo;return`${t.name}-${t.version}`}function hf(e){return e.sourceInfo.name}function pf(e){switch(e.source){case"claude-plugin":case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplace;default:return}}function ff(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.pluginDbId;default:return}}function mf(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplaceDbId;default:return}}function gf(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function wf(e){return!!gf(e)&&(void 0===e.enabledPlugins||gf(e.enabledPlugins))}function yf(e){return JSON.parse(e)}function vf(e){const t=e??process.env.HOME??"";return(0,s.join)(t,".claude")}async function bf(e){const t={enabledPlugins:{}};let r=!1;const n=(0,s.join)(e,".claude","settings.json");try{const e=yf(await(0,xo.readFile)(n,"utf-8"));wf(e)&&e.enabledPlugins&&(Object.assign(t.enabledPlugins,e.enabledPlugins),r=!0)}catch{}const o=(0,s.join)(e,".claude","settings.local.json");try{const e=yf(await(0,xo.readFile)(o,"utf-8"));wf(e)&&e.enabledPlugins&&(Object.assign(t.enabledPlugins,e.enabledPlugins),r=!0)}catch{}return r?t:null}function Sf(e,t){const r=(0,s.resolve)(e),n=(0,s.resolve)(e,t),o=(0,s.relative)(r,n);if(o.startsWith("..")||(0,s.isAbsolute)(o))throw new Error(`Invalid subPath: path traversal not allowed (${JSON.stringify(t)})`);return n}async function kf(e){try{return(await(0,xo.lstat)(e)).isSymbolicLink()}catch{return!1}}async function _f(e){if(await kf(e))throw new Error(`Refusing to read symlink: ${e}`);return(0,xo.readFile)(e,"utf-8")}async function Cf(e){if((await(0,xo.stat)(e)).size>10485760)throw new Error(`File ${e} exceeds maximum size of 10485760 bytes`)}function Ef(e){const t=e instanceof Error?e.message:String(e);return/timed?\s*out/i.test(t)?"timeout":/clone|fetch|git/i.test(t)?"clone":/manifest|marketplace\.json/i.test(t)?"manifest":/parse|invalid|malformed/i.test(t)?"parse":/install|download|copy/i.test(t)?"install":"unknown"}async function xf({installPath:e,logo:t}){const r=t?.trim();if(r&&!(0,s.isAbsolute)(r)&&!r.includes("://"))try{const t=await(0,xo.realpath)(e),n=Sf(t,r),o=await(0,xo.realpath)(n);if(Sf(t,o),!(await(0,xo.stat)(o)).isFile())return;return await Cf(o),(0,Pd.pathToFileURL)(o).href}catch{return}}function Pf(e){const t={};return void 0!==e.version&&(t.version=e.version),void 0!==e.homepage&&(t.homepage=e.homepage),void 0!==e.repository&&(t.repository=e.repository),t}function Rf(e){return void 0!==e.version||void 0!==e.homepage||void 0!==e.repository}function If(e,t){return Pf({version:e.version??t?.version,homepage:e.homepage??t?.homepage,repository:e.repository??t?.repository})}async function Tf(e,t,r){let n;for(const o of zh){const i=(0,s.join)(e,o);let a;try{if(await kf(i))continue;if(!(await(0,xo.stat)(i)).isFile())continue;await Cf(i),a=await _f(i)}catch{continue}const c=_p(a);if(!c.success)continue;const l=c.data,u=l.commands,d=l.agents,h=l.skills,p=l.rules,f=l.hooks,m=l.mcpServers,g=void 0!==u||void 0!==d||void 0!==h||void 0!==p||void 0!==f||void 0!==m,w="string"==typeof l.displayName?l.displayName:void 0,y="string"==typeof l.description?l.description:void 0,v=l.author?.name,b=await xf({installPath:e,logo:l.logo}),S=Pf(l),k=l.variables,_=l.capabilities,C=void 0!==w||void 0!==y||void 0!==v||void 0!==b||void 0!==k||void 0!==_;if(!g&&!C&&!Rf(S))continue;if(!g&&!C){n=n?{...n,fields:If(n.fields,S)}:{fields:S,path:i,relPath:o,unrecognizedSchemaId:c.unrecognizedSchemaId};continue}void 0!==c.unrecognizedSchemaId&&r.log("debug",`${t}: ${o} declares an unrecognized $schema, loading anyway: ${c.unrecognizedSchemaId}`);const E=If(S,n?.fields);return{manifestFilePath:i,...g&&{manifestOptions:{commands:u,agents:d,skills:h,rules:p,hooks:f,mcpServers:m}},...(C||Rf(E))&&{metadata:{displayName:w,description:y,authorName:v,logoUrl:b,...E,variables:k,capabilities:_}}}}if(void 0!==n)return void 0!==n.unrecognizedSchemaId&&r.log("debug",`${t}: ${n.relPath} declares an unrecognized $schema, loading anyway: ${n.unrecognizedSchemaId}`),{manifestFilePath:n.path,metadata:n.fields}}async function Af(e,t){const r=function(e,t){const r=new Map,n=(0,s.resolve)(e),o=(0,s.resolve)(t?.symlinkTargetRoot??n),i=(0,xo.realpath)(o).catch((()=>o));function a(e){const t=(0,s.resolve)(e);try{return Sf(n,t)}catch{throw new Error(`Path escapes plugin directory: ${e}`)}}async function c(e){const t=a(e),r=await i,n=await(0,xo.realpath)(t);try{return Sf(r,n)}catch{throw new Error(`Path escapes plugin directory via symlink: ${e}`)}}return{async listDirectory(t,r){const n=a(t?(0,s.join)(e,t):e);try{const e=await c(n);if(r?.has(e))return[];r?.add(e);const o=await(0,xo.readdir)(e,{withFileTypes:!0}),i=[];for(const e of o){const r=(0,s.join)(n,e.name);let o=e.isDirectory()?"dir":"file";if(e.isSymbolicLink())try{const e=await c(r);o=(await(0,xo.stat)(e)).isDirectory()?"dir":"file"}catch{continue}i.push({name:e.name,type:o,path:t?`${t}/${e.name}`:e.name})}return i}catch{return[]}},async fetchFile(t){const n=r.get(t);if(void 0!==n)return{content:n};const o=a((0,s.join)(e,t)),i=await c(o);await Cf(i);const l=await(0,xo.readFile)(i,"utf-8");return r.set(t,l),{content:l}},async fileExists(t){try{const r=a((0,s.join)(e,t)),n=await c(r);return(await(0,xo.stat)(n)).isFile()}catch{return!1}}}}(e),n=new cf(r),o=await n.discoverComponents({manifest:t}),[i,a,c,l]=await Promise.all([$f(r,o.skills,e),Df(r,o.agents,e),Of(r,o.commands,e),Mf(r,o.rules,e)]);return{skills:i,agents:a,commands:c,rules:l}}async function $f(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Nf({content:Ap(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}async function Mf(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Nf({content:Ap(t,r),relativePath:o.path});s&&n.push({...s,name:o.name})}catch{}return n}async function Df(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Lf({content:Ap(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}async function Of(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=jf({content:Ap(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}function Ff(e){if("string"==typeof e){const t=function(e){const t=[];let r=0,n=0;for(let o=0;o0)n--;else if(","===s&&0===n){const n=e.slice(r,o).trim();n&&t.push(n),r=o+1}}if(n>0){for(const n of e.slice(r).split(",")){const e=n.trim();e&&t.push(e)}return t}const o=e.slice(r).trim();return o&&t.push(o),t}(e);return t.length>0?t:void 0}if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e)).map((e=>e.trim())).filter(Boolean);return t.length>0?t:void 0}}function Nf({content:e,relativePath:t}){try{const r=rh(e),n=t.replace(/\\/g,"/"),o=n.split("/").filter((e=>e.length>0)),s=o.length>=2?o[o.length-2]:void 0,i=o[o.length-1]??n,a=s??i.replace(/\.md$/i,""),c="string"==typeof r.data.name?r.data.name.trim():void 0,l=of(r.data.environments??r.data.metadata?.environments),u=of(r.data["disabled-environments"]??r.data.metadata?.disabledEnvironments);return{path:t,name:c&&c.length>0?c:a,description:"string"==typeof r.data.description?r.data.description:void 0,globs:Ff(r.data.globs),alwaysApply:!0===r.data.alwaysApply,content:e,environments:l,disabledEnvironments:u}}catch{return null}}function Lf({content:e,relativePath:t}){try{const n=rh(e),o=n.content.trim();if(!o)return null;let i;"string"==typeof n.data.tools?i=n.data.tools.split(",").map((e=>e.trim())).filter(Boolean):Array.isArray(n.data.tools)&&(i=n.data.tools.map((e=>"string"==typeof e?e.trim():String(e))).filter(Boolean));const a=n.data.permissionMode??n.data.permissionmode,c=(0,s.basename)(t);return{path:t,name:"string"==typeof n.data.name?n.data.name:(0,s.basename)(c,(0,s.extname)(c)).replace(/[\s_]+/g,"-"),description:"string"==typeof n.data.description?n.data.description:void 0,tools:i,model:"string"==typeof n.data.model?n.data.model:"inherit",prompt:o,permissionMode:(r=a,"readonly"===(r??"").trim().toLowerCase()?"readonly":"default")}}catch{return null}var r}function jf({content:e,relativePath:t}){try{const r=rh(e);let n;const o=r.data["argument-hint"];"string"==typeof o?n=o:Array.isArray(o)&&(n=`[${o.join(" ")}]`);const i=(0,s.basename)(t);return{path:t,name:"string"==typeof r.data.name?r.data.name:(0,s.basename)(i,(0,s.extname)(i)),description:"string"==typeof r.data.description?r.data.description:void 0,argumentHint:n,content:r.content.trim()}}catch{return null}}function Uf(e){if(void 0!==e)return{configuredVariables:e.configuredVariables}}async function Bf(e,t,r){const n=r??Uf(t);return async function(e,t={}){const r=t.toSourcePath??(e=>e);let n,o,s;for(const t of zh){const i=await e(t);if(null===i)continue;let a;try{a=JSON.parse(i)}catch{continue}s=Uh(a);const c=_p(i);if(c.success){void 0!==c.data.mcpServers&&(n=c.data.mcpServers,o=r(t));break}}return Hp(e,n,o,void 0===s?t:{...t,parserOptions:{...t.parserOptions,pluginSchemaId:s}})}(function(e){return async t=>{if(!Ep(t))return null;const r=(0,s.join)(e,t);try{return await kf(r)?null:(await(0,xo.stat)(r)).isFile()?(await Cf(r),await _f(r)):null}catch{return null}}}(e),{fallbackFileNames:jp(),manifestPrecedence:"override",toSourcePath:t=>(0,s.join)(e,t),installPathForExpansion:e,parserOptions:n})}async function Wf(e,t,r){const n=await Bf(e,void 0,{log:r});if(n)return n;for(const n of Vh){const o=(0,s.join)(e,n);try{if(!(await(0,xo.stat)(o)).isFile())continue;const n=await(0,xo.readFile)(o,"utf-8"),i=JSON.parse(n);if(!zf(i)||!Array.isArray(i.plugins))continue;const a=i.plugins.filter(Gf),c=t.name,l=a.find((e=>e.name===c));if(!l?.mcpServers?.length)continue;for(const t of l.mcpServers){const n=t.replace(/^\.\//,"");if(!Ep(n))continue;const o=(0,s.join)(e,n);try{await Cf(o);const t=Bp(await _f(o),e,{log:r});if(t?.mcpServers&&Object.keys(t.mcpServers).length>0){const e=Object.fromEntries(Object.keys(t.mcpServers).map((e=>[e,o])));return{...t,mcpServerSourcePaths:e}}}catch{}}return null}catch{}}return null}Error;const Hf=new Set(Object.values(Rd));function qf(e){return Hf.has(e)}function zf(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Gf(e){return!(!zf(e)||"string"!=typeof e.name)&&(void 0===e.mcpServers||Array.isArray(e.mcpServers)&&e.mcpServers.every((e=>"string"==typeof e)))}function Vf(e,t){const r={};for(const[n,o]of Object.entries(e.hooks))Array.isArray(o)&&qf(n)&&(r[n]=o.map((e=>"command"in e&&"string"==typeof e.command?{...e,command:Ap(e.command,t)}:"prompt"in e&&"string"==typeof e.prompt?{...e,prompt:Ap(e.prompt,t)}:e)));return{...e,hooks:r}}async function Kf(e,t,r,n,o){if("object"==typeof n){const s=Jf(n,t,r);return s&&"config"in s?{config:Vf(s.config,e),...void 0!==o&&{sourcePath:o}}:s}let i,a,c;if("string"==typeof n){const t=n.replace(/^\.\//,"");if(!Ep(t))return;i=t.endsWith(".json")?(0,s.join)(e,t):(0,s.join)(e,t,"hooks.json")}else i=(0,s.join)(e,"hooks","hooks.json");try{if(await kf(i))return;if(!(await(0,xo.stat)(i)).isFile())return}catch{return}try{await Cf(i),a=await(0,xo.readFile)(i,"utf-8")}catch{return}try{c=JSON.parse(a)}catch{return{error:{source:"claude-plugin",message:`Plugin ${t} ${i}: invalid JSON`}}}const l=Jf(c,t,r);return l&&"config"in l?{config:Vf(l.config,e),sourcePath:i}:l}function Jf(e,t,r){const n=function(e){if(!Ad(e))return"unknown";const t=e,r="object"==typeof t.hooks&&null!==t.hooks?t.hooks:null;if(!r)return"unknown";for(const e of Object.values(r)){if(!Array.isArray(e)||0===e.length)continue;const t=e[0];if(Ad(t)){if("hooks"in t&&Array.isArray(t.hooks))return"claude-code";if("command"in t||"prompt"in t||"type"in t)return"cursor"}}return"unknown"}(e);if("cursor"===n){const r=Fd(e);return r.isValid&&Fd(e).isValid?{config:e}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${r.errors.join("; ")}`}}}if("claude-code"===n){if(!(zf(o=e)&&zf(o.hooks)&&Object.keys(o.hooks).length>0))return;const n=Yd(e.hooks,{warn:e=>r.log("warn",`Plugin ${t} hooks: ${e}`),info:e=>r.log("info",`Plugin ${t} hooks: ${e}`)}),s=Fd(n);return s.isValid?{config:n}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${s.errors.join("; ")}`}}}var o}async function Zf(e,t,r,n){const o=n?.log??$p,s=await Tf(e,t,o),i={...Uf(r)??(n?.configuredVariables?{configuredVariables:n.configuredVariables}:void 0),log:o},[a,c,l]=await Promise.all([Af(e,s?.manifestOptions),Bf(e,r,i),Kf(e,t,o,s?.manifestOptions?.hooks,s?.manifestFilePath)]);return{...a,...void 0!==s?.metadata?.displayName&&{displayName:s.metadata.displayName},...void 0!==s?.metadata?.description&&{description:s.metadata.description},...void 0!==s?.metadata?.authorName&&{authorName:s.metadata.authorName},...void 0!==s?.metadata?.logoUrl&&{logoUrl:s.metadata.logoUrl},...void 0!==s?.metadata?.version&&{version:s.metadata.version},...void 0!==s?.metadata?.homepage&&{homepage:s.metadata.homepage},...void 0!==s?.metadata?.repository&&{repository:s.metadata.repository},variablesSchema:s?.metadata?.variables,mcpConfig:c,capabilities:s?.metadata?.capabilities??[],hooks:l}}async function Xf(e,t,r){const n=r?.log??$p,o=await Tf(e,t.raw,n),[s,i,a]=await Promise.all([Af(e,o?.manifestOptions),Wf(e,t,n),Kf(e,t.raw,n,o?.manifestOptions?.hooks,o?.manifestFilePath)]);return{identifier:{source:"claude-plugin",sourceInfo:t},installPath:e,...void 0!==o?.metadata?.displayName&&{displayName:o.metadata.displayName},...void 0!==o?.metadata?.description&&{description:o.metadata.description},...void 0!==o?.metadata?.authorName&&{authorName:o.metadata.authorName},...void 0!==o?.metadata?.logoUrl&&{logoUrl:o.metadata.logoUrl},...void 0!==o?.metadata?.version&&{version:o.metadata.version},...void 0!==o?.metadata?.homepage&&{homepage:o.metadata.homepage},...void 0!==o?.metadata?.repository&&{repository:o.metadata.repository},...s,mcpConfig:i??void 0,capabilities:o?.metadata?.capabilities??[],hooks:a}}async function Qf(e,t,r,n){const o=`${r.name}@${r.version}`,{displayName:s,description:i,authorName:a,logoUrl:c,version:l,homepage:u,repository:d,variablesSchema:h,skills:p,rules:f,agents:m,commands:g,mcpConfig:w,capabilities:y,hooks:v}=await Zf(e,o,r,{log:n?.log});return{identifier:{source:t,sourceInfo:r},installPath:e,...void 0!==s&&{displayName:s},...void 0!==i&&{description:i},...void 0!==a&&{authorName:a},...void 0!==c&&{logoUrl:c},...void 0!==l&&{version:l},...void 0!==u&&{homepage:u},...void 0!==d&&{repository:d},variablesSchema:h,skills:p,rules:f,agents:m,commands:g,mcpConfig:w??void 0,capabilities:y,hooks:v}}async function Yf(e,t,r={}){const n=r.log??$p,o=performance.now(),i=await async function(e){const t=vf(e),r=(0,s.join)(t,"plugins","installed_plugins.json");try{const e=yf(await(0,xo.readFile)(r,"utf-8"));return gf(n=e)&&gf(n.plugins)?e:null}catch{return null}var n}(r.userHomeDir);if(!i?.plugins)return n.log("info",`loadAllEnabledPlugins: no installed plugins metadata found (${(performance.now()-o).toFixed(1)}ms)`),[];const a=await async function(e){const t=vf(e),r=(0,s.join)(t,"settings.json");try{const e=yf(await(0,xo.readFile)(r,"utf-8"));return wf(e)?e:null}catch{return null}}(r.userHomeDir),c=function(e){if(void 0===e)return[];const t="string"==typeof e?[e]:e,r=new Set,n=[];for(const e of t){if(!e)continue;const t=(0,s.resolve)(e);r.has(t)||(r.add(t),n.push(t))}return n}(e),l=function(e,t,r){if(0===r.length)return Dh(e,t,null,void 0);const n=new Set;for(const{settings:e}of r)for(const[t,r]of Object.entries(e?.enabledPlugins??{}))!1===r&&n.add(t);const o=new Set,s=[];for(const{workspacePath:i,settings:a}of r){const r=Dh(e,t,a,i);for(const e of r)o.has(e.pluginId)||n.has(e.pluginId)||(o.add(e.pluginId),s.push(e))}return s}(i,a,await(0,Nr.PH)(c,(async e=>({workspacePath:e,settings:await bf(e)})),{max:8})),u=[],d=r.onError;for(const{pluginId:e,installPath:t}of l)try{const r=performance.now(),o=uf(e),s=await Xf(t,o,{log:n});u.push(s),n.log("info",`loadClaudePlugin ${e} loaded in ${(performance.now()-r).toFixed(1)}ms`)}catch(t){const r=t instanceof Error?t:new Error(String(t));if(d)try{d(uf(e),r)}catch{d({name:e.split("@")[0]??e,sourceType:"marketplace",marketplace:"unknown",raw:e},r)}}return n.log("info",`loadAllEnabledPlugins completed in ${(performance.now()-o).toFixed(1)}ms (${l.length} resolved, ${u.length} loaded)`),u}const em=new Map;async function tm(e){const{entry:t,slug:r,cacheManager:n}=e;if(void 0===t.backendContent&&!Ph(t.downloadUrl))return rm(e);const o=n.getCacheDir({marketplaceSlug:r,pluginId:t.pluginId,version:t.version}),s=em.get(o);if(void 0!==s)return s;const i=rm(e).finally((()=>{em.delete(o)}));return em.set(o,i),i}async function rm(e){const{entry:t,slug:r,client:n,cacheManager:o,pluginLogger:s}=e;if(await o.isCached({marketplaceSlug:r,pluginId:t.pluginId,version:t.version})){const e=o.getCacheDir({marketplaceSlug:r,pluginId:t.pluginId,version:t.version});return s.log("info",`loadFromMarketplaceSource: Found cached plugin: ${t.pluginId} at ${e}`,{marketplaceSlug:r,pluginId:t.pluginId,gitRef:t.version,marketplaceId:t.marketplace?.id}),e}const i=o.getCacheDir({marketplaceSlug:r,pluginId:t.pluginId,version:t.version});s.log("info",`loadFromMarketplaceSource: Plugin missing from cache, installing: ${t.pluginId} at ${i}`,{marketplaceSlug:r,pluginId:t.pluginId,gitRef:t.version,marketplaceId:t.marketplace?.id}),await(0,xo.mkdir)(i,{recursive:!0});try{await n.installPlugin(t,i),await o.markCacheComplete({marketplaceSlug:r,pluginId:t.pluginId,version:t.version})}catch(e){try{await(0,xo.rm)(i,{recursive:!0,force:!0})}catch{}throw e}return i}async function nm(e){const{error:t,entry:r,slug:n,client:o,cacheManager:s,pluginLogger:i}=e;if(!Ch(t))return;if("revision_superseded"===t.reason){const t=await(o.relistPlugin?.(r).catch((()=>{})));if(void 0!==t)try{return{entry:t,installPath:await tm({...e,entry:t})}}catch(e){if(!Ch(e))throw e}}const a=await async function(e){const{cacheManager:t,marketplaceSlug:r,pluginId:n,exceptVersion:o}=e,s=ih(Sh),i=await t.listCachedVersions({marketplaceSlug:r,pluginId:n});let a;for(const e of i){if(!e.startsWith(s))continue;const i=Rh(e.slice(s.length));if(i===o)continue;const c=hh({parent:t.getCacheDir({marketplaceSlug:r,pluginId:n,version:i}),name:uh}),l=await(0,xo.stat)(c).then((e=>e.mtimeMs),(()=>{}));void 0!==l&&(void 0===a||l>a.installedAtMs)&&(a={version:i,installedAtMs:l})}return a?.version}({cacheManager:s,marketplaceSlug:n,pluginId:r.pluginId,exceptVersion:r.version});return void 0!==a?(i.log("warn",`Plugin ${r.pluginId} keeps its installed version until the listed one can be downloaded`,{pluginId:r.pluginId,reason:t.reason}),{entry:{...r,version:a},installPath:s.getCacheDir({marketplaceSlug:n,pluginId:r.pluginId,version:a})}):void 0}async function om(e){const t=e.log??$p,r=performance.now(),{client:n,userId:o,teamId:s,onCursorError:i,pruneOldVersions:a,pluginFilter:c,onPluginsListed:l}=e,u=[],d=e.cacheManager??new fh(e.userHomeDir),h=performance.now();let p;try{p=await n.listEnabledPlugins(o,s)}catch(e){return t.captureException(e,{error_type:"list_enabled_plugins"}),t.increment("marketplace.source_unavailable",1),t.log("error",`marketplace listEnabledPlugins failed after ${(performance.now()-h).toFixed(1)}ms; treating source as unavailable: ${e instanceof Error?e.message:String(e)}`),{plugins:[],failures:[],sourceUnavailable:!0}}t.log("info",`marketplace listEnabledPlugins completed in ${(performance.now()-h).toFixed(1)}ms (${p.plugins.length} plugins)`),l&&await l(p.plugins);const f=[];if(p.listFailures){u.push(...p.listFailures);for(const e of p.listFailures)f.push({identifier:{source:e.marketplaceName&&"cursor-public"!==e.marketplaceName?"cursor-third-party":"cursor-first-party",sourceInfo:{name:e.pluginName,version:"",...void 0!==e.pluginDbId&&{pluginDbId:e.pluginDbId},marketplace:e.marketplaceName}},installPath:"",loadError:e.errorMessage,skills:[],rules:[],agents:[],commands:[],capabilities:[]})}const m=new Map;for(const e of p.plugins){if(c&&!c(e))continue;let r=e;try{const e=r.marketplace?.name;if(!e){const e=new Error(`Plugin ${r.name} has no marketplace metadata — cannot determine cache path`);u.push({pluginName:r.name,pluginId:r.pluginId,marketplaceName:void 0,errorMessage:e.message,errorType:"manifest"}),i&&i(r,e);continue}const o=`${e}/${r.pluginId}`;let s,a=m.get(o);a||(a={slug:e,pluginId:r.pluginId,versions:[]},m.set(o,a)),a.versions.push(r.version);try{s=await tm({entry:r,slug:e,client:n,cacheManager:d,pluginLogger:t})}catch(o){const i=await nm({error:o,entry:r,slug:e,client:n,cacheManager:d,pluginLogger:t});if(void 0===i)throw o;({entry:r,installPath:s}=i),a.versions.push(r.version)}const c=r.marketplace?.name,l=void 0!==c&&"cursor-public"!==c&&c.length>0?"cursor-third-party":"cursor-first-party",h={name:r.name,version:r.version,pluginDbId:r.pluginDbId,configuredVariables:r.configuredVariables,marketplace:c,marketplaceDbId:r.marketplaceDbId,isTeamRequired:r.isTeamRequired},p=await Qf(s,l,h,{log:t});f.push(p);try{await d.pruneOldVersions({marketplaceSlug:e,pluginId:r.pluginId,keepVersions:[r.version]})}catch{}}catch(e){t.captureException(e,{error_type:"load_plugin_from_marketplace"});const n=e instanceof Error?e:new Error(String(e));u.push({pluginName:r.name,pluginId:r.pluginId,marketplaceName:r.marketplace?.name,errorMessage:n.message,errorType:Ef(n)});const o=r.marketplace?.name,s=void 0!==o&&"cursor-public"!==o&&o.length>0;f.push({identifier:{source:s?"cursor-third-party":"cursor-first-party",sourceInfo:{name:r.name,version:r.version,pluginDbId:r.pluginDbId,marketplace:o,marketplaceDbId:r.marketplaceDbId,isTeamRequired:r.isTeamRequired}},installPath:"",loadError:n.message||"Plugin load failed",skills:[],rules:[],agents:[],commands:[],capabilities:[]}),i&&i(r,n)}}if(a)for(const{slug:e,pluginId:t,versions:r}of m.values())try{await d.pruneOldVersions({marketplaceSlug:e,pluginId:t,keepVersions:r})}catch{}return t.log("info",`loadFromMarketplaceSource completed in ${(performance.now()-r).toFixed(1)}ms (${f.length} plugins loaded, ${u.length} failures)`),{plugins:f,failures:u,sourceUnavailable:!1}}function sm(e){const{identifier:t}=e;switch(t.source){case"claude-plugin":return"marketplace"===t.sourceInfo.sourceType&&t.sourceInfo.marketplace?`${t.sourceInfo.marketplace}/${t.sourceInfo.name}`:void 0;case"cursor-first-party":case"cursor-third-party":return t.sourceInfo.marketplace?`${t.sourceInfo.marketplace}/${t.sourceInfo.name}`:void 0;default:return}}function im(e){return sm(e)??`path:${e.installPath}`}function am(e,t={}){return{...e,model:t.stripModel?void 0:e.model,tools:t.stripTools?void 0:e.tools}}function cm(e,t){const r=[];for(const o of e){const e=df(o.identifier),i=`plugin:${e}`,a=hf(o.identifier),c=pf(o.identifier),l=ff(o.identifier),u=mf(o.identifier);for(const d of t(o)){const t=(0,s.join)(o.installPath,d.path),{type:h,globs:p,description:f}=(n=d).alwaysApply?{type:"global"}:n.globs&&n.globs.length>0?{type:"fileGlobbed",globs:n.globs}:n.description?{type:"agentFetched",description:n.description}:{type:"manuallyAttached"};r.push({fullPath:t,content:d.content,type:h,globs:p,description:f,pluginIdentifier:e,gitRemoteOrigin:i,plugin:a,marketplace:c,pluginId:l,marketplaceId:u,environments:d.environments,disabledEnvironments:d.disabledEnvironments})}}var n;return r}var lm=r("../proto/dist/generated/agent/v1/agent_skills_pb.js");const um=(0,Vs.debuglog)("agent-skills-catalog-cache");function dm(e){return(0,ko.createHash)("sha256").update(JSON.stringify({v:1,...e})).digest("hex")}async function hm(e){try{return(await(0,xo.stat)(e)).mtimeMs}catch{return}}function pm(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const fm=[".kits","cursor-pages"],mm={configDir:".cursor",subdir:"skills-cursor",thirdParty:!1,builtin:!0},gm=[{configDir:".cursor",subdir:"skills",thirdParty:!1,builtin:!1},{configDir:".claude",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".codex",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".grok",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".agents",subdir:"skills",thirdParty:!1,builtin:!1},mm],wm=(new Set(gm.map((e=>e.configDir))),new Set(["imagegen","openai-docs","opneai-docs","plugin-creator","skill-creator","skill-installer"]));function ym(e){return e.replace(/\\/g,"/").split("/").filter(Boolean)}function vm(e){const t=ym(e);if(function(e){const t=e.findIndex(((t,r)=>function(e,t){return gm.some((r=>r.configDir===e&&r.subdir===t))}(t,e[r+1])));return-1!==t&&e.slice(t+2).some((e=>e.startsWith(".")))}(t))return!0;const r=t.lastIndexOf(".codex");if(-1===r||"skills"!==t[r+1])return!1;const n=t.at(-1),o="SKILL.md"===n?t.at(-2):n;return void 0!==o&&wm.has(o)}function bm(e){return{dirPath:(0,s.join)(e,mm.configDir,mm.subdir),scope:"builtin",source:"builtin"}}const Sm="canvas";function km(e,t){return{dirPath:(0,s.join)(bm(e).dirPath,...fm),scope:"builtin",source:"builtin"}}function _m(e,t){const r=e.replace(/\\/g,"/"),n=t.replace(/\\/g,"/").replace(/\/+$/,"");if(r.startsWith(`${n}/`))return ym(r.slice(n.length+1))}function Cm(e,t){const r=_m(e,t);return void 0!==r&&!r.some((e=>e.startsWith(".")))}function Em(e){return gm.filter((t=>!t.builtin&&(e||!t.thirdParty)))}function xm(e,t){return Em(t).map((t=>({dirPath:(0,s.join)(e,t.configDir,t.subdir),scope:"project",source:"workspace"})))}function Pm(e,t){return Em(t).map((t=>({dirPath:(0,s.join)(e,t.configDir,t.subdir),scope:"user",source:"user"})))}var Rm=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function Im(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const Tm=gm.map((({configDir:e,subdir:t,thirdParty:r})=>({pattern:new RegExp(`[/\\\\]${Im(e)}[/\\\\]${Im(t)}[/\\\\]`,"i"),requiresThirdParty:r}))),Am=/[/\\]\.cursor[/\\]rules[/\\]/i,$m=[{pattern:/[/\\]\.cursor[/\\]agents[/\\]/i,requiresThirdParty:!1},{pattern:/[/\\]\.claude[/\\]agents[/\\]/i,requiresThirdParty:!0}],Mm=new Set(["AGENTS.md","CLAUDE.md","CLAUDE.local.md"]);function Dm(e,t){const r=e.replace(/\\/g,"/"),n=(0,s.basename)(r);if(Mm.has(n))return"AGENTS.md"===n||t&&("CLAUDE.md"===n||"CLAUDE.local.md"===n)?"markdown":void 0;if(Am.test(r)&&n.endsWith(".mdc"))return"rules";if("SKILL.md"===n)for(const{pattern:e,requiresThirdParty:n}of Tm)if(e.test(r)){if(n&&!t)continue;return"skills"}if(n.endsWith(".md"))for(const{pattern:e,requiresThirdParty:n}of $m)if(e.test(r)){if(n&&!t)continue;return"agents"}}class Om{constructor(e,t,r,n){this.root=e,this.gitExecutor=t,this.userHomeDirectory=r,this.getThirdPartyExtensibilityEnabled=n}static getRipwalkCache(){return Om.ripwalkCache??=new _a,Om.ripwalkCache}async discover(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,D.VI)(e.withName("NestedExtensibilityService.discover")),!1),n={rules:[],skills:[],markdown:[],agents:[]},o=(0,s.resolve)(this.root),i=(0,s.resolve)(this.userHomeDirectory);if(o===i||zs(o,{platform:process.platform,homeDirectory:i}).length>0)return r.span.setAttribute("nested_extensibility.rules",0),r.span.setAttribute("nested_extensibility.skills",0),r.span.setAttribute("nested_extensibility.markdown",0),r.span.setAttribute("nested_extensibility.agents",0),n;if(!await tc(e,this.gitExecutor,(0,s.resolve)(this.root)))return r.span.setAttribute("nested_extensibility.rules",0),r.span.setAttribute("nested_extensibility.skills",0),r.span.setAttribute("nested_extensibility.markdown",0),r.span.setAttribute("nested_extensibility.agents",0),n;const a=this.getThirdPartyExtensibilityEnabled(),c=this.buildIncludeGlobs(a),l={root:this.root,includeGlobs:c,excludeGlobs:dc,followSymlinks:!0,source:"nested_extensibility"},u={rules:[],skills:[],markdown:[],agents:[]},d=Om.getRipwalkCache();try{const e=d.walk(r.ctx,l);try{for await(const t of e.lines){const e=Dm(t,a);e&&u[e].push((0,s.resolve)(this.root,t))}}finally{d.delete(l)}}catch{}return r.span.setAttribute("nested_extensibility.rules",u.rules.length),r.span.setAttribute("nested_extensibility.skills",u.skills.length),r.span.setAttribute("nested_extensibility.markdown",u.markdown.length),r.span.setAttribute("nested_extensibility.agents",u.agents.length),u}catch(e){t.error=e,t.hasError=!0}finally{Rm(t)}}buildIncludeGlobs(e){const t=["*/**/.cursor/**","*/**/.agents/**","*/**/AGENTS.md"];return e&&t.push("*/**/.claude/**","*/**/.codex/**","*/**/.grok/**","*/**/CLAUDE.md","*/**/CLAUDE.local.md"),t}}const Fm=new Set(["node_modules","__pycache__","dist","build"]);async function Nm({rootDir:e,includeFile:t,maxDepth:r=10,containmentRootDir:n}){const o=[],i=[{dir:e,depth:0}],a=new Set,c=void 0!==n?await(0,xo.realpath)(n):null,l=e=>{if(null===c)return!0;const t=(0,s.relative)(c,e);return""===t||!t.startsWith("..")&&!(0,s.isAbsolute)(t)};for(;i.length>0;){const e=i.pop();if(void 0===e)continue;const{dir:n,depth:c}=e;if(c>r)continue;try{const e=await(0,xo.realpath)(n);if(!l(e))continue;if(a.has(e))continue;a.add(e)}catch{continue}const d=await(0,xo.readdir)(n,{withFileTypes:!0,encoding:"utf8"}).catch((()=>null));if(null!==d)for(const e of d){const r=(0,s.join)(n,e.name);let a=e.isDirectory(),l=e.isFile();if(e.isSymbolicLink())try{const e=await(0,xo.stat)(r);a=e.isDirectory(),l=e.isFile()}catch{continue}if(a){if((u=e.name).startsWith(".")||Fm.has(u))continue;i.push({dir:r,depth:c+1})}else l&&t(e.name)&&o.push(r)}}var u;return o.sort(((e,t)=>e.localeCompare(t))),o}const Lm={agentStoreSkillsDirs:[],userHomeDirectory:""};function jm(e){const t=e.replace(/\\/g,"/");return t.endsWith("/")?t.slice(0,-1):t}function Um(e,t){const r=jm(t.userHomeDirectory),n=e.replace(/\\/g,"/");if(r.length>0)for(const e of t.agentStoreSkillsDirs){const t=jm(e);if(t.length>0&&n.startsWith(`${t}/`))return{key:`${r}::skills/${n.slice(t.length+1)}`,inAgentStore:!0}}return{key:Bm(e),inAgentStore:!1}}function Bm(e){const t=e.replace(/\\/g,"/"),r=t.toLowerCase(),n=r.indexOf("/.cursor/"),o=r.indexOf("/.claude/"),s=r.indexOf("/.codex/"),i=r.indexOf("/.grok/"),a=r.indexOf("/.agents/");return-1!==n?`${t.slice(0,n)}::${t.slice(n+9)}`:-1!==o?`${t.slice(0,o)}::${t.slice(o+9)}`:-1!==s?`${t.slice(0,s)}::${t.slice(s+8)}`:-1!==i?`${t.slice(0,i)}::${t.slice(i+7)}`:-1!==a?`${t.slice(0,a)}::${t.slice(a+9)}`:e}function Wm(e,t){const r=new Map,n=[];for(const o of e){const{key:e,inAgentStore:s}=Um(o.fullPath,t),i=r.get(e);void 0!==i?s&&!n[i].inAgentStore&&(n[i]={item:o,inAgentStore:s}):(r.set(e,n.length),n.push({item:o,inAgentStore:s}))}return n.map((e=>e.item))}var Hm=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},qm=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const zm=(0,d.h)("local-exec:cursor-rules");function Gm(e){return"/"===e||"\\"===e}function Vm(e){return e.split(/[\\/]+/).filter((e=>e.length>0)).length}async function Km(e){return await Nm({rootDir:e,includeFile:e=>"SKILL.md"===e})}async function Jm(e){let t;try{t=await Bi(e)}catch(t){return{skillFilePath:e,error:kd(t)}}try{return{skillFilePath:e,content:t,parsed:rh(t)}}catch(t){return{skillFilePath:e,error:_d(t)}}}async function Zm(e){const t=await ns(e);return{...await Jm(e),realSkillFilePath:t}}function Xm(e){return eg(e.data?.environments??e.data?.metadata?.environments)??[]}function Qm(e){return eg(e.data?.["disabled-environments"]??e.data?.metadata?.disabledEnvironments)??[]}function Ym(e){return eg(e.data?.metadata?.scopedTo??e.data?.["metadata.scopedTo"])??[]}function eg(e){if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e&&e.length>0));return 0===t.length?void 0:t}if("string"==typeof e){const t=e.split(",").map((e=>e.trim())).filter((e=>e.length>0));return 0===t.length?void 0:t}}function tg(e,t,r){const n=function(e){const t=e.data?.metadata?.surfaces;return Array.isArray(t)?t:"string"==typeof t?t.split(",").map((e=>e.trim())).filter(Boolean):[]}(e);return n.length>0&&!n.includes(t)&&!r.includes(e.data?.name)}function rg(e){return Jo(e,1536)}function ng(e){return!0===e.data?.alwaysApply}function og(e){return!0===e.data?.["disable-model-invocation"]}function sg({skillFilePath:e,content:t,parsed:r}){const n=function(e){return function(e){const t=(e.matter??"").trim(),r=e.language?.toLowerCase();return t.length>0&&"js"!==r&&"javascript"!==r?`---\n${t}\n---`:nh("",e.data??{}).trim()}(e)}(r),o=function({fullPath:e,name:t,description:r,body:n}){const o=[],s=function(e){const t=e.replace(/\\/g,"/").split("/"),r=t[t.length-1]??"";return"SKILL.md"===r&&t.length>=2?t[t.length-2]??"":r}(e);s.length>64&&o.push(`Name is ${xd(s.length)} characters; the limit is 64. Rename the skill's folder.`),Ed.test(s)||o.push('Name should be lowercase letters and numbers joined by single hyphens, like "pdf-helper". Rename the skill\'s folder.'),void 0!==t&&t!==s&&o.push(`Frontmatter name ${JSON.stringify(t)} doesn't match the folder name ${JSON.stringify(s)}, which is the name the skill goes by. Make them the same.`);const i=r?.trim().length??0;i>1024&&o.push(`Description is ${xd(i)} characters; the limit is ${xd(1024)}.`);const a=Math.round(n.length/4);return a>5e3&&o.push(`Body is about ${xd(a)} tokens; the recommended limit is ${xd(5e3)}. Move details into reference files that SKILL.md links to.`),o}({fullPath:e,name:"string"==typeof r.data?.name?r.data.name:void 0,description:"string"==typeof r.data?.description?r.data.description:void 0,body:r.content});if(ng(r))return new Jr.DX({fullPath:e,content:t,frontmatter:n,type:new Jr.f5({type:{case:"global",value:new Jr.i9}}),environments:Xm(r),disabledEnvironments:Qm(r),scopedTo:Ym(r),warnings:o});const s="string"==typeof r.data?.description?rg(r.data.description):void 0,i=Cd(s,og(r));return i?new Jr.DX({fullPath:e,parseError:i,frontmatter:n,scopedTo:Ym(r),type:new Jr.f5({type:{case:"agentFetched",value:new Jr.Xo}})}):new Jr.DX({fullPath:e,content:t,frontmatter:n,type:new Jr.f5({type:{case:"agentFetched",value:new Jr.Xo({description:s})}}),environments:Xm(r),disabledEnvironments:Qm(r),scopedTo:Ym(r),warnings:o})}function ig({skillFilePath:e,content:t,parsed:r}){const n="string"==typeof r.data?.description?rg(r.data.description):"",o=Ff(r.data?.paths??r.data?.globs),s=og(r);return new lm.N({fullPath:e,content:t,description:n,globs:o??[],parseError:Cd(n,s),environments:Xm(r),disabledEnvironments:Qm(r),scopedTo:Ym(r),disableModelInvocation:s})}function ag({rules:e,agentSkills:t,skillFilePath:r,errorMessage:n}){e.push(function({skillFilePath:e,errorMessage:t}){return new Jr.DX({fullPath:e,parseError:t,type:new Jr.f5({type:{case:"agentFetched",value:new Jr.Xo}})})}({skillFilePath:r,errorMessage:n})),t.push(function({skillFilePath:e,errorMessage:t}){return new lm.N({fullPath:e,parseError:t})}({skillFilePath:r,errorMessage:n}))}function cg(e,t,r,n){if("error"in t)return e.realSkillFilePathsByFullPath.set(t.skillFilePath,t.realSkillFilePath),void ag({rules:e.rules,agentSkills:e.agentSkills,skillFilePath:t.skillFilePath,errorMessage:t.error});tg(t.parsed,r,n)||(e.realSkillFilePathsByFullPath.set(t.skillFilePath,t.realSkillFilePath),e.rules.push(sg(t)),ng(t.parsed)||e.agentSkills.push(ig(t)))}const lg=(0,Vs.debuglog)("cursor-rules-service");function ug(){return{rules:[],agentSkills:[],realSkillFilePathsByFullPath:new Map}}function dg(e){return t=>(lg("%s: %O",e,t),ug())}function hg(e,t){return dm({kind:"agent-store",surface:e,roots:[...t].sort()})}function pg(e,t){const r=t.replace(/\\/g,"/").replace(/\/+$/,"");return""!==r&&e.replace(/\\/g,"/").startsWith(`${r}/`)}function fg(e){let t;if(!0===e.frontmatter.alwaysApply)t={case:"global",value:new Jr.i9};else{const r=Ff(e.frontmatter.globs);t=r&&r.length>0?{case:"fileGlobbed",value:new Jr.uT({globs:r})}:"string"==typeof e.frontmatter.description&&e.frontmatter.description.trim().length>0?{case:"agentFetched",value:new Jr.Xo({description:rg(e.frontmatter.description)})}:{case:"manuallyAttached",value:new Jr._u}}const r=e.frontmatter["metadata.environments"],n=Array.isArray(r)?r:[],o=e.frontmatter["metadata.disabledEnvironments"],s=Array.isArray(o)?o:[],i=e.frontmatter["metadata.scopedTo"],a=Array.isArray(i)?i:[];return new Jr.DX({fullPath:e.path,content:e.body,type:new Jr.f5({type:t}),environments:n,disabledEnvironments:s,scopedTo:a,frontmatter:e.rawFrontmatter??""})}class mg{constructor(e,t){this.cursorRulesServices=e,this.getAgentStoreSkillsContext=t,this.onChangeCallbacks=new Set}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Hm(t,(0,D.VI)(e.withName("MergedCursorRulesService.getAllCursorRules")),!1),n=this.cursorRulesServices.map((e=>e.getAllCursorRules(r.ctx).catch((e=>((0,Vs.debuglog)("Failed to load cursor rules from service:",e),[])))));return Wm((await Promise.all(n)).flat(),this.getAgentStoreSkillsContext())}catch(e){t.error=e,t.hasError=!0}finally{qm(t)}}reload(e){for(const t of this.cursorRulesServices)t.reload(e)}scheduleDidChangeRules(){void 0===this.changeTimer&&(this.changeTimer=setTimeout((()=>{this.changeTimer=void 0;for(const e of Array.from(this.onChangeCallbacks))e()}),mg.CHANGE_COALESCE_MS))}ensureChangeListenersRegistered(){void 0===this.disposeChangeListeners&&(this.disposeChangeListeners=this.cursorRulesServices.map((e=>e.onDidChangeRules((()=>this.scheduleDidChangeRules())))))}disposeChangeListenersIfUnused(){if(!(this.onChangeCallbacks.size>0||void 0===this.disposeChangeListeners)){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0,void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0)}}onDidChangeRules(e){return this.onChangeCallbacks.add(e),this.ensureChangeListenersRegistered(),()=>{this.onChangeCallbacks.delete(e),this.disposeChangeListenersIfUnused()}}dispose(){if(void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0),this.onChangeCallbacks.clear(),void 0!==this.disposeChangeListeners){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0}for(const e of this.cursorRulesServices)e.dispose&&e.dispose()}}mg.CHANGE_COALESCE_MS=1e3;class gg{constructor(e,t,r,n,i,a,c,l){this.gitExecutor=t,this.rootDirectory=r,this.loadNestedRules=n,this.getThirdPartyExtensibilityEnabled=i,this.loadTraceId=void 0,this.onChangeCallbacks=new Set,this.nestedExtensibilityService=new Om(r,t,(0,o.homedir)(),i),this.ignoreService=c??new Rc(t,void 0,[this.rootDirectory]);const u=performance.now();if(this._rules=this.load(e,l).then((t=>{try{zm.info(e,"LocalCursorRulesService load completed",{durationMs:Math.round(performance.now()-u),ruleCount:t.length})}catch{}return t})).catch((e=>((0,Vs.debuglog)("Failed to load cursor rules:",e),[]))),a){const e=[".cursor/rules/**/*.mdc","AGENTS.md","CLAUDE.md","CLAUDE.local.md",".cursorrules",".cursorignore"];this.unsubscribeWatcher=a.subscribe(this.rootDirectory,e,(e=>{const t={stack:[],error:void 0,hasError:!1};try{const r=(0,b.q6)(),n=Hm(t,(0,D.VI)(r.withName("LocalCursorRulesService.fileWatcher.subscribe")),!1);if(".cursorignore"===(0,s.basename)(e))return gg.getRipwalkCache().clear(),void this.reload(n.ctx);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{qm(t)}}))}}reload(e){this._rules=this.load(e).catch((e=>((0,Vs.debuglog)("Failed to load cursor rules:",e),[])));for(const e of this.onChangeCallbacks)e()}static getRipwalkCache(){return gg.ripwalkCache??=new _a,gg.ripwalkCache}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.reloadAtPath")),!1);if(Xr((0,s.basename)(t)))return void this.reload(n.ctx);const o=this._rules;this._rules=(async()=>{const e=(await o).filter((e=>e.fullPath!==t));const r=(await this.readRulesAtPath(n.ctx,t)).map((e=>this.toCursorRule(e)));return[...e,...r]})().catch((e=>((0,Vs.debuglog)("Failed to load cursor rules at path:",e),[])));for(const e of this.onChangeCallbacks)e()}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}isRuleMarkdownFile(e){return Xr(e)}async readRulesAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.readRulesAtPath")),!1),o=(0,s.basename)(t);if(".cursorrules"===o){const e=(0,s.resolve)(this.rootDirectory),t=await tc(n.ctx,this.gitExecutor,e)||e,r=await this.loadCursorRulesRule(n.ctx,t);return r?[r]:[]}if(o.endsWith(".mdc"))return await wg(t);if(this.isRuleMarkdownFile(o))try{return await this.loadRulesFromMarkdownFile(n.ctx,(0,s.dirname)(t),o)}catch{}return[]}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}dispose(){this.unsubscribeWatcher&&(this.unsubscribeWatcher(),this.unsubscribeWatcher=void 0)}async load(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.load")),!1);this.loadTraceId=n.span.spanContext().traceId;const o=(0,s.resolve)(this.rootDirectory),i=await tc(n.ctx,this.gitExecutor,o)||o,a=this.loadCursorRulesRule(n.ctx,i).then((e=>e?[e]:[])),c=this.loadRulesFromDirAndAncestors(n.ctx,o);let l,u;if(this.loadNestedRules){const e=t??this.nestedExtensibilityService.discover(n.ctx);l=e.then((e=>this.parseNestedRuleFiles(n.ctx,e.rules))),u=e.then((e=>this.parseNestedMarkdownFiles(n.ctx,e.markdown)))}else l=[],u=[];const d=(await Promise.all([a,c,l,u])).flat(),h=new Map;for(const e of d)h.set(e.path,e);const p=[...h.values()];return(await async function(e){const t=e.filter((e=>Xr((0,s.basename)(e.fullPath))));if(t.length<=1)return[...e];const r=await(0,Nr.PH)(t,(e=>async function(e){try{const t=await(0,xo.stat)(e,{bigint:!0});if(0n!==t.ino)return`ino:${String(t.dev)}:${String(t.ino)}`}catch{}return await ns(e)}(e.fullPath)),{max:16}),n=t.map(((e,t)=>({item:e,identity:r[t],dir:(0,s.dirname)(e.fullPath),content:e.content.trim()}))).sort(((e,t)=>{const r=Vm(e.dir)-Vm(t.dir);if(0!==r)return r;const n="AGENTS.md"===(0,s.basename)(e.item.fullPath);return n===("AGENTS.md"===(0,s.basename)(t.item.fullPath))?0:n?-1:1})),o=[];for(const e of n)o.some((t=>{return((r=t.dir)===(n=e.dir)||!!n.startsWith(r)&&(Gm(r.at(-1))||Gm(n[r.length])))&&(t.identity===e.identity||t.content===e.content);var r,n}))||o.push(e);const i=new Set(o.map((e=>e.item)));return e.filter((e=>!Xr((0,s.basename)(e.fullPath))||i.has(e)))}(p.map((e=>({fullPath:e.path,content:e.body,rule:e}))))).map((e=>this.toCursorRule(e.rule)))}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}async loadCursorRulesRule(e,t){const r={stack:[],error:void 0,hasError:!1};try{Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.loadCursorrules")),!1);try{const e=(0,s.join)(t,".cursorrules");if((await(0,xo.stat)(e)).isFile())return{filename:".cursorrules",path:e,frontmatter:{alwaysApply:!0},body:await Bi(e)}}catch{}return null}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{return Hm(t,(0,D.VI)(e.withName("LocalCursorRulesService.getAllCursorRules")),!1).span.setAttribute("cacheTraceId",this.loadTraceId??"undefined"),await this._rules}catch(e){t.error=e,t.hasError=!0}finally{qm(t)}}toCursorRule(e){return fg({path:e.path,body:e.body,frontmatter:e.frontmatter,rawFrontmatter:e.rawFrontmatter})}async loadRulesFromDirAndAncestors(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirAndAncestors")),!1),o=[];let i=t;const a=this.getThirdPartyExtensibilityEnabled();for(;;){const e=(0,s.join)(i,".cursor","rules"),t=i;o.push((async()=>await this.dirIsDirectory(n.ctx,e)?this.loadRulesFromDirectory(n.ctx,t):[])());const r=[];a&&r.push("CLAUDE.md","CLAUDE.local.md"),r.push("AGENTS.md");for(const e of r)o.push(this.loadRulesFromMarkdownFile(n.ctx,i,e));const c=(0,s.dirname)(i);if(c===i)break;i=c}const c=(await Promise.all(o)).flat();return n.span.setAttribute("rules",c.length),c}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}async loadRulesFromMarkdownFile(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{Hm(n,(0,D.VI)(e.withName("LocalCursorRulesService.loadRulesFromMarkdownFile")),!1).span.setAttribute("filename",r);try{const e=(0,s.join)(t,r);if(await this.isCursorIgnored(e))return[];if((await(0,xo.stat)(e)).isFile()){const t=Qr({content:await Bi(e),filename:r});return[{filename:(0,s.basename)(e,".md"),path:e,frontmatter:{alwaysApply:!0},body:t}]}}catch{}return[]}catch(e){n.error=e,n.hasError=!0}finally{qm(n)}}async isCursorIgnored(e){try{const t=await xc((0,s.resolve)(this.rootDirectory,e));return null===t||await this.ignoreService.isCursorIgnored(t)}catch{return!1}}async parseNestedRuleFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.parseNestedRuleFiles")),!1),o=(await Promise.all(t.map((async e=>{try{const t=rn(await Bi(e));if(t)return{filename:(0,s.basename)(e,".mdc"),path:e,frontmatter:t.frontmatter,rawFrontmatter:t.rawFrontmatter,body:t.body}}catch{}})))).filter((e=>void 0!==e));return n.span.setAttribute("ruleFiles",o.length),o}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}async parseNestedMarkdownFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.parseNestedMarkdownFiles")),!1),o=(await Promise.all(t.map((async e=>{try{const t=(0,s.basename)(e);if(!this.isRuleMarkdownFile(t))return[];const r=(0,s.dirname)(e);return await this.loadRulesFromMarkdownFile(n.ctx,r,t)}catch{}return[]})))).flat();return n.span.setAttribute("markdownFiles",o.length),o}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}async loadRulesFromDirectory(e,t){return await async function(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=Hm(n,(0,D.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirectory")),!1),i=[];try{(0,s.join)(t,".cursorignore");const e={root:(0,s.join)(t,".cursor","rules"),includeGlobs:["**/*.mdc"],followSymlinks:!0,source:"cursor_rules"},n=r.walk(o.ctx,e);for await(const t of n.lines){const r=(0,s.join)(e.root,t);i.push(...await wg(r))}}catch{}return o.span.setAttribute("rules",i.length),i}catch(e){n.error=e,n.hasError=!0}finally{qm(n)}}(e,t,gg.getRipwalkCache())}async dirIsDirectory(e,t){const r={stack:[],error:void 0,hasError:!1};try{Hm(r,(0,D.VI)(e.withName("LocalCursorRulesService.dirIsDirectory")),!1);try{return(await(0,xo.stat)(t)).isDirectory()}catch{return!1}}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}}async function wg(e){try{const t=rn(await Bi(e));if(t)return[{filename:(0,s.basename)(e,".mdc"),path:e,frontmatter:t.frontmatter,rawFrontmatter:t.rawFrontmatter,body:t.body}]}catch{}return[]}class yg{constructor(e,t,r,n,o,s,i=()=>!0,a=Promise.resolve(),c="ide",l,u=()=>[],d,h,p=()=>[],f){if(this.workspacePaths=t,this.userHomeDirectory=r,this.gitExecutor=n,this.getEnabledSkills=p,this.ignoreService=f,this.agentStoreLoadRequestedWhileInFlight=!1,this.agentStoreLoadGeneration=0,this.watchersByFolder=new Map,this.onChangeCallbacks=new Set,this.reloadRequestedDuringSeed=!1,this.surface=c,this.waitBeforeSkillLoad="function"==typeof a?a:()=>a,this.getAgentStoreSkillRoots=u,this.fileWatcher=s,this.getThirdPartyExtensibilityEnabled=i,this.catalogCache=d,this.builtinSkillRootDir=bm(r).dirPath,this.canvasKitSkillRootDir=void 0===h?void 0:km(r).dirPath,this.workspaceCatalogKey=dm({kind:"workspace",surface:c,loadNestedSkills:o,thirdPartyExtensibility:i(),workspacePaths:[...t].sort(),userHomeDirectory:r,...void 0===h?{}:{canvasKit:h}}),void 0!==l&&l.length!==t.length)throw new Error(`initialNestedExtensibilityResults length (${l.length}) must match workspacePaths length (${t.length})`);this.nestedExtensibilityEntries=o?t.map((e=>new Om(e,n,r,i))):[],this.foldersToWatch=this.computeFoldersToWatch();const m=performance.now();let g=!1,w=!1,y=!1;const v=this.loadAll(e,l).then((t=>{try{zm.info(e,"AgentSkillsCursorRulesService load completed",{durationMs:Math.round(performance.now()-m),ruleCount:t.rules.length,skillCount:t.agentSkills.length,servedFromCache:g})}catch{}return t})).catch((e=>(w=!0,dg("Failed to load Agent Skills")(e))));if(void 0===this.catalogCache)this._loaded=v;else{const t=this.readCatalog(this.workspaceCatalogKey).then((r=>(y=!0,this._loaded!==t?this._loaded:(w&&this.closeSeedWindow(e),void 0===r?v:(g=!0,r)))));this.seededLoaded=t,this._loaded=t,v.then((r=>{this._loaded===t?w?y&&this.closeSeedWindow(e):(this._loaded=v,g&&this.notifyChanged(),this.persistCatalog(this.workspaceCatalogKey,r),this.closeSeedWindow(e)):this.seededLoaded=void 0}))}this.refreshAgentStoreSkills(),this.setupWatchers(this.foldersToWatch)}closeSeedWindow(e){this.seededLoaded=void 0,this.reloadRequestedDuringSeed&&(this.reloadRequestedDuringSeed=!1,this.reload(e))}async readCatalog(e){if(void 0!==this.catalogCache)try{const t=await this.catalogCache.read(e);return void 0===t?void 0:await async function(e){if(!function(e){if(!pm(e))return!1;const t=e.fileMtimesMs;return 1===e.version&&Array.isArray(e.rules)&&Array.isArray(e.agentSkills)&&Array.isArray(e.realSkillFilePathsByFullPath)&&e.realSkillFilePathsByFullPath.every((e=>Array.isArray(e)&&2===e.length&&"string"==typeof e[0]&&"string"==typeof e[1]))&&pm(t)&&Object.values(t).every((e=>"number"==typeof e&&Number.isFinite(e)))}(e))return;const t=new Map;if(await Promise.all(e.realSkillFilePathsByFullPath.map((async([r,n])=>{const o=e.fileMtimesMs[n];void 0!==o&&await hm(r)===o&&t.set(r,n)}))),0===t.size)return;const r=e=>void 0!==e&&t.has(e);try{return{rules:e.rules.map((e=>Jr.DX.fromJson(e,{ignoreUnknownFields:!0}))).filter((e=>r(e.fullPath))),agentSkills:e.agentSkills.map((e=>lm.N.fromJson(e,{ignoreUnknownFields:!0}))).filter((e=>r(e.fullPath))),realSkillFilePathsByFullPath:t}}catch(e){return void um("snapshot failed to decode: %O",e)}}(t)}catch(e){return void lg("Failed to read the skills catalog cache: %O",e)}}persistCatalog(e,t){const r=this.catalogCache;void 0!==r&&async function(e){const t=new Set(e.realSkillFilePathsByFullPath.values()),r={};return await Promise.all(Array.from(t,(async e=>{const t=await hm(e);void 0!==t&&(r[e]=t)}))),{version:1,rules:e.rules.map((e=>e.toJson())),agentSkills:e.agentSkills.map((e=>e.toJson())),realSkillFilePathsByFullPath:Array.from(e.realSkillFilePathsByFullPath),fileMtimesMs:r}}(t).then((t=>r.write(e,t))).catch((e=>{lg("Failed to persist the skills catalog cache: %O",e)}))}computeFoldersToWatch(){const e=this.getThirdPartyExtensibilityEnabled(),t=new Set;for(const r of this.workspacePaths){t.add((0,s.join)(r,".cursor","rules"));for(const n of xm(r,e))t.add(n.dirPath)}for(const r of Pm(this.userHomeDirectory,e))t.add(r.dirPath);for(const e of this.getAgentStoreSkillRoots())t.add(e);return t.add(this.builtinSkillRootDir),void 0!==this.canvasKitSkillRootDir&&t.add(this.canvasKitSkillRootDir),Array.from(t)}isIgnoredSkillPath(e){if(void 0!==this.canvasKitSkillRootDir){if(Cm(e,this.canvasKitSkillRootDir))return!1;if(function(e,t){const r=_m(e,t);return void 0!==r&&2===r.length&&r[0]===Sm&&"SKILL.md"===r[1]}(e,this.builtinSkillRootDir))return!0}return vm(e)}setupWatchers(e){if(!this.fileWatcher)return;const t=["**"];for(const r of e){if(this.watchersByFolder.has(r))continue;const e=this.fileWatcher.subscribe(r,t,(e=>{const t={stack:[],error:void 0,hasError:!1};try{const r=(0,b.q6)(),n=Hm(t,(0,D.VI)(r.withName("AgentSkillsCursorRulesService.fileWatcher.subscribe")),!1);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{qm(t)}}));this.watchersByFolder.set(r,e)}}removeWatchers(e){for(const t of e){const e=this.watchersByFolder.get(t);e&&(e(),this.watchersByFolder.delete(t))}}async getAllCursorRules(e){const[t]=await Promise.all([this._loaded,this.awaitAgentStoreSeed()]);return this.withAgentStoreSkills(t).rules}async awaitAgentStoreSeed(){void 0!==this.agentStoreSeedInFlight&&await(0,Nr.wj)(this.agentStoreSeedInFlight,250,"Agent Store skills cache read timed out").catch((()=>{}))}reload(e){this.syncWatchers(),this.seededLoaded=void 0,this.reloadRequestedDuringSeed=!1;const t=this.loadAll(e),r=t.catch(dg("Failed to load Agent Skills"));this._loaded=r,t.then((e=>{this._loaded===r&&this.persistCatalog(this.workspaceCatalogKey,e)}),(()=>{})),this.refreshAgentStoreSkills(),this.notifyChanged()}reloadSkillRoots(){try{this.syncWatchers()}finally{this.refreshAgentStoreSkills()}}async agentStoreSkillsSettled(){for(let e=this.agentStoreWalk;void 0!==e;e=this.agentStoreWalk)await e}syncWatchers(){const e=this.computeFoldersToWatch(),t=new Set(this.foldersToWatch),r=new Set(e);this.removeWatchers(this.foldersToWatch.filter((e=>!r.has(e)))),this.setupWatchers(e.filter((e=>!t.has(e)))),this.foldersToWatch=e}isPrunedByExtensibilityScan(e){if(void 0!==this.canvasKitSkillRootDir&&Cm(e,this.canvasKitSkillRootDir))return!1;const t=e.replace(/\\/g,"/");for(const e of this.foldersToWatch){const r=e.replace(/\\/g,"/");if(t.startsWith(`${r}/`))return t.slice(r.length+1).split("/").slice(0,-1).some((e=>e.startsWith(".")))}return!1}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("AgentSkillsCursorRulesService.reloadAtPath")),!1),o=function(e,t,r=i){for(const n of t){const t=r.relative(n,e);if(""!==t&&".."!==t&&!t.startsWith(`..${r.sep}`)&&!r.isAbsolute(t))return r.join(n,t)}return e}(t,this.foldersToWatch),a=o.endsWith("SKILL.md")?o:(0,s.join)(o,"SKILL.md");if(void 0!==this.seededLoaded&&this._loaded===this.seededLoaded&&!this.getAgentStoreSkillRoots().some((e=>pg(a,e))))return void(this.reloadRequestedDuringSeed=!0);if(this.getAgentStoreSkillRoots().some((e=>pg(a,e))))return void this.refreshAgentStoreSkills();if(this.foldersToWatch.some((e=>""===(0,s.relative)(e,o))))return void this.reload(n.ctx);const c=this._loaded,l=(async()=>{const e=await c,{realSkillFilePathsByFullPath:t}=e,r=function(e,t){const r=new Map(e.realSkillFilePathsByFullPath);for(const e of t)r.delete(e);return{rules:e.rules.filter((e=>!t.has(e.fullPath))),agentSkills:e.agentSkills.filter((e=>!t.has(e.fullPath))),realSkillFilePathsByFullPath:r}}(e,new Set([a]));if(this.isIgnoredSkillPath(a)||this.isPrunedByExtensibilityScan(a))return r;const o=t.get(a);if(void 0===o){try{await(0,xo.stat)(a)}catch{return r}return await this.loadAll(n.ctx)}let s;try{s=await(0,xo.realpath)(a)}catch{return await this.loadAll(n.ctx)}if(s!==o)return await this.loadAll(n.ctx);try{return cg(r,{...await async function(e){const t=await Bi(e);return{skillFilePath:e,content:t,parsed:rh(t)}}(a),realSkillFilePath:s},this.surface,this.getEnabledSkills()),r}catch{return await this.loadAll(n.ctx)}})().catch(dg("Failed to load Agent Skills at path"));this._loaded=l,this.notifyChanged()}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}async getAllAgentSkills(e){const[t]=await Promise.all([this._loaded,this.awaitAgentStoreSeed()]);return this.withAgentStoreSkills(t).agentSkills}withAgentStoreSkills(e){const t=this.settledAgentStoreSkills?.loaded;if(void 0===t||0===t.realSkillFilePathsByFullPath.size)return e;const r=new Set(e.realSkillFilePathsByFullPath.values()),n={rules:[...e.rules],agentSkills:[...e.agentSkills],realSkillFilePathsByFullPath:new Map(e.realSkillFilePathsByFullPath)},o=new Set;for(const[e,s]of t.realSkillFilePathsByFullPath)n.realSkillFilePathsByFullPath.has(e)||r.has(s)?o.add(e):n.realSkillFilePathsByFullPath.set(e,s);for(const e of t.rules)o.has(e.fullPath)||n.rules.push(e);for(const e of t.agentSkills)o.has(e.fullPath)||n.agentSkills.push(e);return n}refreshAgentStoreSkills(){const e=this.getAgentStoreSkillRoots().filter((e=>""!==e.trim())),t=++this.agentStoreLoadGeneration;var r,n;if(void 0===this.settledAgentStoreSkills||(r=this.settledAgentStoreSkills.roots,n=e,r.length===n.length&&r.every(((e,t)=>e===n[t])))||(this.settledAgentStoreSkills=void 0,this.notifyChanged()),0!==e.length){if(void 0===this.settledAgentStoreSkills){const r=this.seedAgentStoreSkills(e,t).finally((()=>{this.agentStoreSeedInFlight===r&&(this.agentStoreSeedInFlight=void 0)}));this.agentStoreSeedInFlight=r}void 0===this.agentStoreWalk?this.agentStoreWalk=(0,Nr.wj)(this.loadAgentStoreSkills(e),3e4,"Agent Store skills walk timed out").then((r=>{t===this.agentStoreLoadGeneration&&(this.settledAgentStoreSkills={roots:e,loaded:r},this.notifyChanged(),(r.rules.length>0||r.agentSkills.length>0)&&this.persistCatalog(hg(this.surface,e),r))}),(e=>{lg("Failed to load Agent Store skills: %O",e)})).finally((()=>{this.agentStoreWalk=void 0,this.agentStoreLoadRequestedWhileInFlight&&(this.agentStoreLoadRequestedWhileInFlight=!1,this.refreshAgentStoreSkills())})):this.agentStoreLoadRequestedWhileInFlight=!0}}async seedAgentStoreSkills(e,t){const r=await this.readCatalog(hg(this.surface,e));void 0!==r&&t===this.agentStoreLoadGeneration&&void 0===this.settledAgentStoreSkills&&(this.settledAgentStoreSkills={roots:e,loaded:r},this.notifyChanged())}async loadAgentStoreSkills(e){const t=ug(),r=(await Promise.all(e.map((e=>Km(e))))).flat().filter((e=>!vm(e))),n=await Promise.all(r.map((e=>Zm(e)))),o=new Set;for(const e of n)o.has(e.realSkillFilePath)||(o.add(e.realSkillFilePath),cg(t,e,this.surface,this.getEnabledSkills()));return t}notifyChanged(){for(const e of Array.from(this.onChangeCallbacks))e()}onDidChangeSkills(e){return this.onDidChangeRules(e)}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}dispose(){for(const e of this.watchersByFolder.values())e();this.watchersByFolder.clear()}async loadAll(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("AgentSkillsCursorRulesService.loadAll")),!1);await this.waitBeforeSkillLoad();const o=[],s=[],i=new Map,a=Promise.all(this.nestedExtensibilityEntries.map(((e,r)=>(t?.[r]??e.discover(n.ctx)).catch((e=>{lg("Failed to discover nested agent skills: %O",e)}))))),c=new Set(this.getAgentStoreSkillRoots()),l=await Promise.all(this.foldersToWatch.filter((e=>!c.has(e))).map((async e=>{const t=(await Km(e)).filter((e=>!this.isIgnoredSkillPath(e)));return Promise.all(t.map((e=>Zm(e))))}))),u=new Set;for(const e of l)for(const t of e)if(!u.has(t.realSkillFilePath))if(u.add(t.realSkillFilePath),"error"in t)i.set(t.skillFilePath,t.realSkillFilePath),ag({rules:o,agentSkills:s,skillFilePath:t.skillFilePath,errorMessage:t.error});else{if(tg(t.parsed,this.surface,this.getEnabledSkills()))continue;i.set(t.skillFilePath,t.realSkillFilePath),o.push(sg(t)),ng(t.parsed)||s.push(ig(t))}const d=(await a).flatMap((e=>e?.skills??[])).filter((e=>!vm(e))),h=await Promise.all(d.map((e=>ns(e)))),p=[];for(const[e,t]of d.entries()){const r=h[e];u.has(r)||(u.add(r),p.push(t))}const f=await Promise.all(p.map((e=>Zm(e))));for(const e of f)if("error"in e)i.set(e.skillFilePath,e.realSkillFilePath),ag({rules:o,agentSkills:s,skillFilePath:e.skillFilePath,errorMessage:e.error});else{if(tg(e.parsed,this.surface,this.getEnabledSkills()))continue;i.set(e.skillFilePath,e.realSkillFilePath),o.push(sg(e)),ng(e.parsed)||s.push(ig(e))}return n.span.setAttribute("agent_skills.total",o.length),n.span.setAttribute("agent_skills_proto.total",s.length),{rules:o,agentSkills:s,realSkillFilePathsByFullPath:i}}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}}function vg(e){let t;switch(e.type){case"global":t=new Jr.f5({type:{case:"global",value:new Jr.i9}});break;case"fileGlobbed":t=new Jr.f5({type:{case:"fileGlobbed",value:new Jr.uT({globs:e.globs??[]})}});break;case"agentFetched":t=new Jr.f5({type:{case:"agentFetched",value:new Jr.Xo({description:rg(e.description??"")})}});break;case"manuallyAttached":t=new Jr.f5({type:{case:"manuallyAttached",value:new Jr._u}});break;default:e.type,t=new Jr.f5({type:{case:"manuallyAttached",value:new Jr._u}})}return new Jr.DX({fullPath:e.fullPath,content:e.content,type:t,gitRemoteOrigin:e.gitRemoteOrigin,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,environments:e.environments??[],disabledEnvironments:e.disabledEnvironments??[],scopedTo:[]})}class bg{constructor(e,t,r,n){this.getImportSettings=t,this.pluginsService=n,this._rules=Promise.resolve([]),this._agentSkills=Promise.resolve([]),this._lastLoaded={rules:[],agentSkills:[]},this._loadGeneration=0,this.onChangeCallbacks=new Set,this.currentImportSettings=this.getImportSettings();const o=performance.now();this.startLoad(e,!1,(t=>{try{zm.info(e,"CursorPluginsAgentSkillsService load completed",{durationMs:Math.round(performance.now()-o),ruleCount:t.rules.length,skillCount:t.agentSkills.length})}catch{}}))}startLoad(e,t,r){const n=++this._loadGeneration,o=this.loadAll(e,t).catch((e=>((0,Vs.debuglog)("cursor-plugins-agent-skills")("Failed to load Cursor Plugins Agent Skills: %s",e instanceof Error?e.message:String(e)),{rules:[],agentSkills:[]}))).then((e=>(n===this._loadGeneration&&(this._lastLoaded=e,r?.(e)),e))),s=()=>(o.then((e=>{n===this._loadGeneration&&(this._rules=Promise.resolve(e.rules),this._agentSkills=Promise.resolve(e.agentSkills),this.notifyChange())})),this._lastLoaded),i=void 0!==this._overBudgetLoad?Promise.resolve(s()):(0,Nr.wj)(o,5e3,"Cursor plugin load did not finish within the rules wait budget").catch((t=>(zm.warn(e,"Serving rules without plugin primitives while plugins load",{error:t instanceof Error?t.message:String(t),waitMs:5e3}),this._overBudgetLoad=o,o.then((()=>{this._overBudgetLoad===o&&(this._overBudgetLoad=void 0)})),s())));this._rules=i.then((e=>e.rules)),this._agentSkills=i.then((e=>e.agentSkills))}notifyChange(){for(const e of Array.from(this.onChangeCallbacks))e()}async getAllCursorRules(e){return await this._rules}async getAllAgentSkills(e){return await this._agentSkills}reload(e){const t=this.getImportSettings();this.currentImportSettings=t,this.startLoad(e,!0),this.notifyChange()}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}onDidChangeSkills(e){return this.onDidChangeRules(e)}dispose(){this.onChangeCallbacks.clear()}async loadAll(e,t=!1){const r={stack:[],error:void 0,hasError:!1};try{const n=Hm(r,(0,D.VI)(e.withName("CursorPluginsAgentSkillsService.loadAll")),!1),o=[],i=[];try{let e=t?await this.pluginsService.reload():await this.pluginsService.getAllEnabledPlugins();this.currentImportSettings.importThirdPartyPlugins||(e=e.filter((e=>"claude-plugin"!==e.identifier.source))),n.span.setAttribute("cursor_plugins.loaded",e.length);const r=function(e){return cm(e,(e=>e.skills))}(e),a=function(e){return cm(e,(e=>e.rules))}(e);for(const e of[...r,...a])o.push(vg(e));for(const t of e){const e=`plugin:${df(t.identifier)}`,r=hf(t.identifier),n=pf(t.identifier),o=ff(t.identifier),a=mf(t.identifier);for(const c of t.skills){if(!0===c.alwaysApply)continue;let l=!1;if(c.content?.includes("disable-model-invocation"))try{l=!0===rh(c.content).data?.["disable-model-invocation"]}catch{}i.push(new lm.N({fullPath:(0,s.join)(t.installPath,c.path),content:c.content,description:rg(c.description??""),environments:c.environments??[],disabledEnvironments:c.disabledEnvironments??[],gitRemoteOrigin:e,plugin:r,marketplace:n,pluginId:o,marketplaceId:a,disableModelInvocation:l}))}}}catch(e){n.span.setAttribute("cursor_plugins.error",String(e))}return n.span.setAttribute("cursor_plugins.total",o.length),n.span.setAttribute("cursor_plugins_proto.total",i.length),{rules:o,agentSkills:i}}catch(e){r.error=e,r.hasError=!0}finally{qm(r)}}}var Sg=r("../proto/dist/generated/agent/v1/subagents_pb.js");const kg=(0,Vs.debuglog)("local-subagents");class _g{async getAllSubagents(){return[]}async reload(){return[]}}function Cg(e){return"true"===(e??"").trim().toLowerCase()}function Eg(e){const t=e.match(/^---\s*\n([\s\S]*?)\n---\s*\n?([\s\S]*)$/m);if(!t)return null;const r=t[1]??"",n=(t[2]??"").trim();if(0===n.length)return null;const o={};for(const e of r.split("\n")){const t=e.trim();if(0===t.length||t.startsWith("#"))continue;const r=t.indexOf(":");if(-1===r)continue;const n=t.slice(0,r).trim().toLowerCase(),s=t.slice(r+1).trim();0!==n.length&&(o[n]=s)}const s=o.name??"",i=o.description,a=o.model,c=Cg(o["force-default-model"]),l="true"===(o.readonly??"").trim().toLowerCase()?Sg.b$.READONLY:Sg.b$.DEFAULT,u=Cg(o.background??o.is_background),d=o.tools;return{name:s,description:i,tools:void 0!==d&&d.length>0?d.split(",").map((e=>e.trim())).filter((e=>e.length>0)):[],model:a,forceDefaultModel:c,prompt:n,permissionMode:l,isBackground:u}}function xg(e){const t=(0,s.extname)(e).toLowerCase();return".md"===t||".mdc"===t||".markdown"===t}function Pg(e){return(0,s.basename)(e,(0,s.extname)(e)).replace(/[\s_]+/g,"-")}async function Rg(e,t){return await Nm({rootDir:e,includeFile:xg,containmentRootDir:t})}class Ig{constructor(e,t,r="workspace",n=!1,o){this.workspacePath=e,this.cursorAgentsSource=r,this.allowExternalAgentSymlinks=n,this.ignoreService=o,this.getThirdPartyExtensibilityEnabled=t??(()=>!0),this.subagents=this.load().catch((e=>(kg("Failed to load subagents: %o",e),[])))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents=this.load().catch((e=>(kg("Failed to load subagents: %o",e),[]))),await this.subagents}computeAgentsDirs(){const e=(0,s.resolve)(this.workspacePath),t=[{dirPath:(0,s.join)(e,".cursor","agents"),source:this.cursorAgentsSource}];return this.getThirdPartyExtensibilityEnabled()&&(t.push({dirPath:(0,s.join)(e,".claude","agents"),source:"claude"}),t.push({dirPath:(0,s.join)(e,".grok","agents"),source:"grok"})),t}async load(){const e=this.computeAgentsDirs(),t=[];for(const{dirPath:r,source:n}of e){const e=await Rg(r,this.allowExternalAgentSymlinks?void 0:this.workspacePath);for(const r of e){const e=(0,s.basename)(r);try{if(!(await(0,xo.stat)(r)).isFile())continue}catch(e){kg("Skipping subagent file %s due to stat error: %o",r,e);continue}try{const o=Eg(await Bi(r));if(!o)continue;t.push(new Sg.zz({fullPath:r,name:o.name||Pg(e),description:o.description??"",tools:o.tools,model:o.model??"inherit",forceDefaultModel:o.forceDefaultModel,prompt:o.prompt,permissionMode:o.permissionMode,isBackground:o.isBackground,source:n}))}catch(e){kg("Failed to parse subagent file %s: %o",r,e)}}}return t}}const Tg=new Set(["claude-code-tutor"]);class Ag{constructor(e){this.subagentsServices=e}async getAllSubagents(){const e=await Promise.all(this.subagentsServices.map((e=>e.getAllSubagents().catch((e=>(kg("Failed to load subagents from merged service: %o",e),[])))))),t=new Map;for(const r of e)for(const e of r)Tg.has(e.name)||t.has(e.name)||t.set(e.name,e);return Array.from(t.values())}async reload(){return await Promise.all(this.subagentsServices.map((e=>e.reload()))),this.getAllSubagents()}}class $g{constructor(e,t){this.getSettings=e,this.pluginsService=t,this._subagentsCache=[],this._loadId=0,this._loadPromise=null,this._loadedOnce=!1,this.runLoadInBackground()}async getAllSubagents(){return this._loadPromise&&await this._loadPromise,this._loadedOnce||await this.reload(),[...this._subagentsCache]}async reload(){return this.runLoadInBackground(!0),this._loadPromise&&await this._loadPromise,this._subagentsCache}runLoadInBackground(e=!1){const t=++this._loadId;this._loadPromise=this.load(e).then((e=>{t===this._loadId&&(this._subagentsCache=e,this._loadedOnce=!0)})).catch((e=>{t===this._loadId&&(kg("Failed to load Cursor plugin subagents: %o",e),this._subagentsCache=[],this._loadedOnce=!0)})).finally((()=>{t===this._loadId&&(this._loadPromise=null)}))}dispose(){}async load(e){const t=[];try{let r=e?await this.pluginsService.reload():await this.pluginsService.getAllEnabledPlugins();this.getSettings().importThirdPartyPlugins||(r=r.filter((e=>"claude-plugin"!==e.identifier.source)));const n=function(e,t={stripModel:!0,stripTools:!0}){const r=[];for(const n of e){const e=hf(n.identifier),o=pf(n.identifier),i=ff(n.identifier),a=mf(n.identifier);for(const c of n.agents){const l=am(c,t),u=(0,s.join)(n.installPath,l.path);r.push({name:l.name,description:l.description??"",prompt:l.prompt,fullPath:u,permissionMode:"readonly"===l.permissionMode?"readonly":"default",plugin:e,marketplace:o,pluginId:i,marketplaceId:a})}}return r}(r,{stripModel:!0,stripTools:!0});for(const e of n){const r="readonly"===e.permissionMode?Sg.b$.READONLY:Sg.b$.DEFAULT;t.push(new Sg.zz({name:e.name,description:e.description,tools:[],model:"inherit",prompt:e.prompt,fullPath:e.fullPath,permissionMode:r,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,source:"plugin"}))}}catch{}return t}}class Mg{constructor(e){this.pastElements=[],this.closed=!1,this.forks=new Set,this.consume(e)}async consume(e){try{for await(const t of e){this.pastElements.push(t);const e=[];for(const r of this.forks)e.push(r.write(t).catch((()=>{})));await Promise.allSettled(e)}}catch(e){this.error=e instanceof Error?e:new Error(String(e))}finally{this.closed=!0;for(const e of this.forks)this.error?e.throw(this.error):e.close();this.forks.clear()}}fork(){if(this.closed){const e=this.pastElements,t=this.error;return async function*(){for(const t of e)yield t;if(t)throw t}()}const e=(0,f.Jt)(),t=this.pastElements.slice();this.forks.add(e);const r=this;return async function*(){for(const e of t)yield e;try{for await(const t of e)yield t}finally{r.forks.delete(e)}}()}}function Dg(e,t){return`${e}:${(0,ko.createHash)("sha256").update(t.toBinary()).digest("hex")}`}function Og(e){return new Po.q({max:e?.max??10,ttl:e?.ttl})}function Fg(e,t,r=Og(t)){return{async execute(t,n,o){if(!o?.execId)return e.execute(t,n,o);const s=Dg(o.execId,n),i=r.get(s);if(void 0!==i)return i;const a=await e.execute(t,n,o);return r.set(s,a),a}}}var Ng=r("../proto/dist/generated/agent/v1/computer_use_tool_pb.js");r("node:readline"),Error;var Lg=r("node:timers/promises");const jg=iu.execFile;function Ug(e,t,r){return new Promise(((n,o)=>{r?.signal?.throwIfAborted();const s={timeout:r?.timeoutMs??3e4,env:r?.env?{...process.env,...r.env}:void 0,signal:r?.signal};(0,au.D9)(jg,e,t.map(String),{...s,encoding:"utf8"},((e,t)=>{e?o(e):n(t)}))}))}Ng.w3.UNSPECIFIED,Ng.w3.LEFT,Ng.w3.MIDDLE,Ng.w3.RIGHT,Ng.w3.BACK,Ng.w3.FORWARD,Ng.Dh.UNSPECIFIED,Ng.Dh.UP,Ng.Dh.DOWN,Ng.Dh.LEFT,Ng.Dh.RIGHT;const Bg=(0,Vs.promisify)(iu.execFile);function Wg(e){const t=e.lastIndexOf(":");if(-1===t)throw new Error(`Invalid X11 display string: ${e} (missing ':')`);const r=e.slice(t+1).split(".")[0],n=parseInt(r,10);if(!Number.isFinite(n)||n<0)throw new Error(`Invalid X11 display number in: ${e} (parsed: ${r})`);return n}function Hg(e,t,r,n){const o=function(e={}){const t=e.displayWidth??1920,r=e.displayHeight??1200,n=e.apiWidth??1280;return{width:n,height:Math.round(n*r/t)}}({displayWidth:e,displayHeight:t,apiWidth:r});return{display:{width:e,height:t},api:{width:o.width,height:n??o.height}}}async function qg(e){const{stdout:t}=await(0,au.D9)(Bg,"xrandr",["--display",e],{timeout:5e3,encoding:"utf8"}),r=function(e){let t,r,n;for(const o of e.split("\n"))if(o.includes("*")){const e=o.trim().match(/^(\d+)x(\d+)/);e&&(t=parseInt(e[1],10),r=parseInt(e[2],10));const s=o.match(/(\d+(?:\.\d+)?)\*(?:\+)?/);if(s){const e=parseFloat(s[1]);e>0&&e<=500&&(n=Math.round(e))}if(t&&r)break}if(!t||!r){const n=e.match(/current\s+(\d+)\s*x\s*(\d+)/i);n&&(t=parseInt(n[1],10),r=parseInt(n[2],10))}if(!t||!r)throw new Error(`Could not detect display resolution from xrandr output.\nExpected a line with '*' indicating active mode, or 'current WxH'.\nxrandr output:\n${e}`);return n||(n=60),{width:t,height:r,refreshRate:n}}(t);return{display:r,resolution:Hg(r.width,r.height),resolutionString:`${r.width}x${r.height}`}}Ng.w3.UNSPECIFIED,Ng.w3.LEFT,Ng.w3.MIDDLE,Ng.w3.RIGHT,Ng.w3.BACK,Ng.w3.FORWARD,Ng.Dh.UNSPECIFIED,Ng.Dh.UP,Ng.Dh.DOWN,Ng.Dh.LEFT,Ng.Dh.RIGHT;const zg={pattern:"[\\w-]{1,64}",next:e=>e},Gg={pattern:"[0-9a-f-]{36}",next:()=>ko.randomUUID()},Vg={pattern:"webp",next:()=>"webp"},Kg={native:[Gg,Vg],agent:[zg,Gg,Vg],legacyNative:[Gg,{pattern:"png",next:()=>"png"}]};new RegExp(`^(?:${Object.values(Kg).map((e=>e.map((e=>e.pattern)).join("\\."))).join("|")})$`),new RegExp(`^${zg.pattern}$`),Ng.Z8.NATIVE_X11,Ng.Z8.XDOTOOL,(0,h.v5)("computer_use.session.duration_ms",{description:"Duration of computer-use session in milliseconds"}),(0,h.v5)("computer_use.session.action_count",{description:"Number of actions executed in a computer-use session"}),(0,h.Pu)("computer_use.session.result",{description:"Result status of computer-use session",labelNames:["outcome"]}),(0,h.Pu)("computer_use.session.action_kind",{description:"Requested computer-use actions by bounded kind",labelNames:["kind"]}),(0,d.h)("computer-use"),Math.floor(35927136),["Skip changes that cannot affect what runs in any deployed environment:","- documentation-only changes (Markdown, docs sites, code comments, changelogs)","- formatting, lint, or typo fixes with no behavior change","- test-only changes (test files, fixtures, snapshots)","Monitor everything else, including dependency bumps, configuration, and infrastructure changes."].join("\n"),Error,(0,h.Pu)("computer_use.desktop_lease.check",{description:"Desktop lease action-gate outcomes",labelNames:["outcome","reason"]});var Jg=r("../proto/dist/runtime/compact.js");Jg.HL;var Zg=(0,Jg.QT)(ve.proto3,"agent.v1.","CursorType",[[0,"UNSPECIFIED"],[1,"ARROW"],[2,"POINTER"],[3,"TEXT"],[4,"WAIT"],[5,"CROSSHAIR"],[6,"MOVE"],[7,"RESIZE_NS"],[8,"RESIZE_EW"],[9,"RESIZE_NWSE"],[10,"RESIZE_NESW"],[11,"NOT_ALLOWED"],[12,"GRAB"],[13,"GRABBING"]],1);ve.proto3,ve.proto3,ve.proto3,ve.proto3;class Xg{constructor(e){this.config=e;const t=e.display.width/e.display.height,r=e.api.width/e.api.height;if(Math.abs(t-r)>.02)throw new Error(`Aspect ratio mismatch: display=${t.toFixed(3)}, api=${r.toFixed(3)}`);this.xScaleUp=e.display.width/e.api.width,this.yScaleUp=e.display.height/e.api.height,this.xScaleDown=e.api.width/e.display.width,this.yScaleDown=e.api.height/e.display.height}apiToDisplay(e,t){return{x:Math.round(e*this.xScaleUp),y:Math.round(t*this.yScaleUp)}}displayToApi(e,t){return{x:Math.round(e*this.xScaleDown),y:Math.round(t*this.yScaleDown)}}get apiWidth(){return this.config.api.width}get apiHeight(){return this.config.api.height}get displayWidth(){return this.config.display.width}get displayHeight(){return this.config.display.height}}const Qg={left_ptr:Zg.ARROW,arrow:Zg.ARROW,default:Zg.ARROW,top_left_arrow:Zg.ARROW,hand:Zg.POINTER,hand1:Zg.POINTER,hand2:Zg.POINTER,pointer:Zg.POINTER,pointing_hand:Zg.POINTER,xterm:Zg.TEXT,ibeam:Zg.TEXT,text:Zg.TEXT,watch:Zg.WAIT,wait:Zg.WAIT,progress:Zg.WAIT,left_ptr_watch:Zg.WAIT,crosshair:Zg.CROSSHAIR,cross:Zg.CROSSHAIR,tcross:Zg.CROSSHAIR,move:Zg.MOVE,fleur:Zg.MOVE,size_all:Zg.MOVE,sb_v_double_arrow:Zg.RESIZE_NS,v_double_arrow:Zg.RESIZE_NS,ns_resize:Zg.RESIZE_NS,row_resize:Zg.RESIZE_NS,top_side:Zg.RESIZE_NS,bottom_side:Zg.RESIZE_NS,sb_h_double_arrow:Zg.RESIZE_EW,h_double_arrow:Zg.RESIZE_EW,ew_resize:Zg.RESIZE_EW,col_resize:Zg.RESIZE_EW,left_side:Zg.RESIZE_EW,right_side:Zg.RESIZE_EW,top_left_corner:Zg.RESIZE_NWSE,bottom_right_corner:Zg.RESIZE_NWSE,nwse_resize:Zg.RESIZE_NWSE,size_fdiag:Zg.RESIZE_NWSE,top_right_corner:Zg.RESIZE_NESW,bottom_left_corner:Zg.RESIZE_NESW,nesw_resize:Zg.RESIZE_NESW,size_bdiag:Zg.RESIZE_NESW,not_allowed:Zg.NOT_ALLOWED,no_drop:Zg.NOT_ALLOWED,forbidden:Zg.NOT_ALLOWED,circle:Zg.NOT_ALLOWED,grab:Zg.GRAB,openhand:Zg.GRAB,grabbing:Zg.GRABBING,closedhand:Zg.GRABBING};class Yg{constructor(e){this.events=[],this.recordingStartTime=0,this.lastKnownPosition={x:0,y:0},this.isRunning=!1,this.pending=Promise.resolve();const t=e.displayNum??1;this.env={DISPLAY:`:${t}`},this.scaler=new Xg(e.resolution)}async start(){this.events=[],this.recordingStartTime=Date.now(),this.isRunning=!0,this.pending=Promise.resolve();try{this.lastKnownPosition=await this.captureCurrentPosition()}catch{this.lastKnownPosition={x:Math.floor(this.scaler.apiWidth/2),y:Math.floor(this.scaler.apiHeight/2)}}}logEvent(e,t,r){if(!this.isRunning)return;const n={...this.lastKnownPosition},o=this.getExpectedPositionAfterAction(e,n);this.lastKnownPosition=o;const s=async()=>{let s,i;try{[s,i]=await Promise.all([this.captureCurrentPosition(),this.detectCursorType()]),this.lastKnownPosition=s}catch{s=o,i=Zg.ARROW}const a={executionTimestampMs:r-this.recordingStartTime,action:e,commandDurationMs:r-t,positionBefore:n,positionAfter:s,cursorTypeAfter:i};this.events.push(a)};this.pending=this.pending.then((()=>s())).catch((()=>{}))}async stop(){return this.isRunning=!1,await this.pending,[...this.events]}getEvents(){return[...this.events]}getRecordingStartTime(){return this.recordingStartTime}getIsRunning(){return this.isRunning}async captureCurrentPosition(){const e=await Ug("xdotool",["getmouselocation","--shell"],{env:this.env}),t=e.match(/X=(\d+)/),r=e.match(/Y=(\d+)/);if(!t||!r)throw new Error(`Failed to parse cursor position: ${e}`);const n=parseInt(t[1],10),o=parseInt(r[1],10);return this.scaler.displayToApi(n,o)}async detectCursorType(){try{const e=(await Ug("xdotool",["getmouselocation","--shell"],{env:this.env})).match(/CURSOR=(\S+)/i);if(e){const t=e[1].toLowerCase();return Qg[t]??Zg.ARROW}try{const e=await Ug("xprop",["-root","_XSERVER_CURSOR"],{env:this.env,timeoutMs:500});for(const[t,r]of Object.entries(Qg))if(e.toLowerCase().includes(t))return r}catch{}return Zg.ARROW}catch{return Zg.ARROW}}getExpectedPositionAfterAction(e,t){const r=e.action;if(!r)return t;switch(r.case){case"mouseMove":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}case"click":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}case"drag":{const e=r.value.path;if(e.length>0){const t=e[e.length-1];return{x:t.x,y:t.y}}break}case"scroll":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}}return t}}(0,d.h)("computer-use-lazy");var ew=r("node:net");function tw(e){return!!e.includes(o.homedir())||e.includes("node_modules")||e.includes("Application Support")||/\.wasm\b/.test(e)||/(?:^|[\s'`"(=])(?:\/|\.{1,2}\/)/.test(e)||/(?:^|[\s'`"(=:])(?:[A-Za-z]:[\\/]|\\\\)/.test(e)||/\bS-1-5-21(?:-\d+){3,}/i.test(e)}class rw extends Error{constructor(e){super(e),this.name="MacRPCProtocolError"}}const nw=Be.object({rpcSocketPath:Be.string().min(1).optional(),appControlSocketPath:Be.string().min(1).optional(),pid:Be.number().int().positive().optional().catch(void 0),protocolMajor:Be.number().int().positive().optional().catch(void 0)}).passthrough(),ow=Be.object({data:Be.string(),mimeType:Be.string().min(1)}).strip(),sw=Be.object({message:Be.string(),screenshot:ow.optional(),screenshotBefore:ow.optional(),structuredContent:Be.unknown().optional(),isError:Be.boolean()}).strip(),iw=Be.object({accessibilityTrusted:Be.boolean(),screenRecordingGranted:Be.boolean()}).strip(),aw=Be.union([Be.object({id:Be.number().int(),result:sw,ok:Be.never().optional(),error:Be.never().optional(),errorCode:Be.never().optional(),permissionStatus:Be.never().optional(),sessionId:Be.never().optional()}).strip(),Be.object({id:Be.number().int(),sessionId:Be.string().min(1),ok:Be.literal(!0).optional(),result:Be.never().optional(),error:Be.never().optional(),errorCode:Be.never().optional(),permissionStatus:Be.never().optional()}).strip(),Be.object({id:Be.number().int(),ok:Be.literal(!0),result:Be.never().optional(),error:Be.never().optional(),errorCode:Be.never().optional(),permissionStatus:Be.never().optional(),sessionId:Be.never().optional()}).strip(),Be.object({id:Be.number().int().nullable().optional(),error:Be.string().min(1),errorCode:Be.string().min(1).optional(),result:Be.never().optional(),ok:Be.never().optional(),permissionStatus:Be.never().optional(),sessionId:Be.never().optional()}).strip(),Be.object({id:Be.number().int(),permissionStatus:iw,result:Be.never().optional(),ok:Be.never().optional(),error:Be.never().optional(),errorCode:Be.never().optional(),sessionId:Be.never().optional()}).strip()]);function cw(e,t){try{return JSON.parse(e)}catch{throw new rw(`local-cua ${t} is not valid JSON`)}}const lw={responseMaxBytes:33554432,parseServiceState(e){const t=nw.safeParse(cw(e,"service state")),r=t.success?t.data.rpcSocketPath??t.data.appControlSocketPath:void 0;if(!t.success||void 0===r)throw new rw("local-cua service state is malformed");return{...t.data,rpcSocketPath:r}},parseResponse({line:e,expectedID:t}){const r=aw.safeParse(cw(e.toString("utf8"),"RPC response"));if(!r.success)throw new rw("local-cua RPC response is malformed");if(void 0!==r.data.id&&null!==r.data.id&&r.data.id!==t)throw new rw("local-cua RPC response ID did not match");return r.data}};class uw extends Error{constructor(e,t){super(e),this.name="MacComputerUseRPCError",this.code=t?.code,this.userFacing=!0===t?.userFacing,this.tool=t?.tool}}function dw(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:e instanceof Error?tw(e.message)?e.name:e.message.length>0?`${e.name}: ${e.message}`:e.name:"unknown"}const hw=new Map([["co.anysphere.cursor-computer-use","cursor-computer-use"],["co.anysphere.cursor-computer-use.dev","cursor-computer-use-dev"]]),pw=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;class fw{constructor(e){this.mode=e}static isInstalled(){if((0,Ro.existsSync)(fw.serviceExecutablePath()))return!0;let e;try{e=lw.parseServiceState((0,Ro.readFileSync)(fw.serviceStatePath(),"utf8"))}catch{return!1}return void 0===e.pid||fw.isProcessAlive(e.pid)}static async runningHelperPid(){const e=await fw.readServiceState(),t=e?.pid;return void 0!==t&&fw.isProcessAlive(t)?t:void 0}static isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}static isExitedIncompatibleHelper(e){return void 0!==e.protocolMajor&&e.protocolMajor!==fw.protocolMajor&&void 0!==e.pid&&!fw.isProcessAlive(e.pid)}screenshot(e){return this.callTool(e,"computer_use_screenshot",{})}click(e,t){return this.callTool(e,"computer_use_click",{method:"coordinate",...void 0!==t.coordinate&&{x:t.coordinate.x,y:t.coordinate.y},button:t.button,count:t.count,modifier_keys:t.modifierKeys})}scroll(e,t){return this.callTool(e,"computer_use_scroll",{x:t.coordinate?.x,y:t.coordinate?.y,direction:t.direction,amount:t.amount,modifier_keys:t.modifierKeys})}move(e,t){return this.callTool(e,"computer_use_mouse_move",{x:t.x,y:t.y})}mouseButton(e,t){return this.callTool(e,"computer_use_mouse_button",{button:t.button,action:t.action})}drag(e,t){return this.callTool(e,"computer_use_drag",{button:t.button,path:t.path,modifier_keys:t.modifierKeys})}typeText(e,t){return this.callTool(e,"computer_use_typing",{value:t})}pressKey(e,t){return this.callTool(e,"computer_use_press_key",{key:t.key,hold_duration_ms:t.holdDurationMs})}checkPermissions(e){return this.callTool(e,"computer_use_check_permissions",{})}async startControl(e){if("remote"!==this.mode||void 0!==this.activeSessionId)return;fw.throwIfAborted(e.signal);const t=(0,ko.randomUUID)(),r=await this.sendWithRelaunchRetry(e,(()=>({id:fw.requestID,method:"control/start",requestID:t,mode:this.mode})),"control/start");if(void 0!==r.error)throw fw.rpcError(r);if(void 0===r.sessionId)throw new uw("local-cua control/start returned no session");this.activeSessionId=r.sessionId}async releaseControl(e){const t=this.activeSessionId;if(void 0!==t){this.activeSessionId=void 0;try{const e=await fw.readServiceState();if(void 0===e)return;const r=await fw.sendOnce(fw.socketPathFrom(e),{id:fw.requestID,method:"control/release",requestID:(0,ko.randomUUID)(),mode:this.mode,sessionId:t},fw.defaultCallTimeoutMs);if(void 0!==r.error)throw fw.rpcError(r)}catch(t){fw.logger.warn(e,"local-cua control release failed",{error:dw(t)})}}}async callTool(e,t,r){fw.throwIfAborted(e.signal);const n=fw.defaultCallTimeoutMs,o=await this.sendWithRelaunchRetry(e,(()=>{const e=Date.now()/1e3,o=this.activeSessionId;return{id:fw.requestID,method:"tools/call",requestID:(0,ko.randomUUID)(),name:t,arguments:r,timeoutSeconds:n/1e3,startedAtEpochSeconds:e,deadlineEpochSeconds:e+n/1e3,mode:this.mode,...void 0!==o&&{sessionId:o}}}),t);if(void 0!==o.error)throw fw.rpcError(o,t);const s=o.result;if(void 0===s)throw new uw(`local-cua tool ${t} returned no result`,{tool:t});if(s.isError){const e=s.message.trim();throw new uw(e.length>0?e:`local-cua tool ${t} reported an error`,{tool:t,userFacing:e.length>0})}return s}async sendWithRelaunchRetry(e,t,r){const n=fw.defaultCallTimeoutMs,o=await this.ensureSocketPath(e);fw.throwIfAborted(e.signal);try{return await fw.sendOnce(o,t(),n,e.signal)}catch(o){if(!fw.isPreDeliveryConnectionError(o))throw o;fw.logger.warn(e,"local-cua callTool failed; relaunching and retrying",{tool:r,error:fw.spawnErrorCode(o)});const s=await this.ensureSocketPath(e,!0);return fw.throwIfAborted(e.signal),void 0!==this.activeSessionId&&(this.activeSessionId=void 0,await this.startControl(e)),await fw.sendOnce(s,t(),n,e.signal)}}static rpcError(e,t){return new uw(e.error,{code:e.errorCode,userFacing:!0,tool:t})}async ensureSocketPath(e,t=!1){if(fw.throwIfAborted(e.signal),!t){const e=await fw.readServiceState();if(e&&!fw.isExitedIncompatibleHelper(e))return fw.socketPathFrom(e)}await this.launchAndWait(e);const r=await fw.readServiceState();if(!r)throw new uw("local-cua sidecar did not publish service.json after launch");return fw.socketPathFrom(r)}static setLaunchGuard(e){fw.launchGuard=e}async launchAndWait(e){const t=fw.serviceAppPath(),r=fw.launchGuard,n=()=>this.launchAppAndWait(e,t);await(void 0===r?n():r(t,n,e.signal))}async launchAppAndWait(e,t){fw.logger.info(e,"launching local-cua sidecar",fw.sidecarLaunchLogFields(t)),"1"===process.env[fw.directLaunchEnv]?await fw.spawnSidecarProcess(e,fw.serviceExecutablePath(),[],{detached:!0}):await fw.spawnSidecarProcess(e,"/usr/bin/open",["-g",t]);const r=Date.now()+fw.launchReadyTimeoutMs;for(;Date.now()0?e:s.join(o.homedir(),...fw.sharedInstallRelativePath,`${fw.serviceAppBundleName}.app`)}static helperIdentity(){const e=fw.serviceAppPath(),t=process.env[fw.appSupportOverrideEnv],r=`${e}\0${t??""}`,n=fw.identityCache;if(n?.key===r)return n.identity;const i=function(e){let t;try{t=(0,Ro.readFileSync)(s.join(e,"Contents","Info.plist"),"utf8")}catch{return{}}const r=e=>{const r=new RegExp(`${e}\\s*([^<]*)`).exec(t)?.[1];return void 0!==r&&pw.test(r.trim())?r.trim():void 0};return{executableName:r("CFBundleExecutable"),bundleIdentifier:r("CFBundleIdentifier")}}(e),a=s.join(e,"Contents","MacOS",i.executableName??fw.productionExecutableName),c={appPath:e,executablePath:a,appSupportDirectory:void 0!==t&&t.length>0?t:s.join(o.homedir(),"Library","Application Support",(void 0===i.bundleIdentifier?void 0:hw.get(i.bundleIdentifier))??fw.appSupportFolder)};return(0,Ro.existsSync)(a)&&(fw.identityCache={key:r,identity:c}),c}static sidecarLaunchLogFields(e){const t=`${fw.serviceAppBundleName}.app`;return{appName:s.basename(e)===t?t:"custom",appPathHash:(0,ko.createHash)("sha256").update(e).digest("hex"),usingOverride:Boolean(process.env[fw.serviceAppOverrideEnv])}}static spawnErrorCode(e){return dw(e)}static socketError(e){const t=dw(e);return new uw(`local-cua RPC connection failed: ${t}`,{code:t})}static serviceExecutablePath(){return fw.helperIdentity().executablePath}static spawnSidecarProcess(e,t,r,n){return new Promise(((o,s)=>{const i=(0,iu.spawn)(t,[...r],{detached:!0===n?.detached,stdio:"ignore"}),a=e=>{s(new uw(`local-cua sidecar launch failed: ${fw.spawnErrorCode(e)}`))};i.once("error",a),i.once("spawn",(()=>{i.removeListener("error",a),i.on("error",(t=>{fw.logger.warn(e,"local-cua sidecar process error after launch",{error:fw.spawnErrorCode(t)})})),i.unref(),o()}))}))}static async readServiceState(){try{const e=await(0,xo.readFile)(fw.serviceStatePath(),"utf8");return lw.parseServiceState(e)}catch(e){if(e instanceof Error&&"code"in e&&"ENOENT"===e.code)return;if(e instanceof rw)return;throw new uw("local-cua service state could not be read")}}static socketPathFrom(e){if(void 0!==e.protocolMajor&&e.protocolMajor!==fw.protocolMajor)throw new uw(`The running Cursor Computer Use speaks protocol ${e.protocolMajor}, and this Cursor CLI speaks protocol ${fw.protocolMajor}. Update the Cursor CLI.`,{userFacing:!0});return e.rpcSocketPath}static abortError(e){return e.reason instanceof Error?e.reason:new uw("local-cua RPC aborted")}static throwIfAborted(e){if(e.aborted)throw fw.abortError(e)}static sendOnce(e,t,r,n){return n?.aborted?Promise.reject(fw.abortError(n)):new Promise(((o,s)=>{let i=!1,a=[],c=0,l=!1;const u=(0,ew.createConnection)({path:e}),d=e=>{i||(i=!0,clearTimeout(p),n?.removeEventListener("abort",h),u.destroy(),e())},h=()=>{d((()=>s(void 0===n?new uw("local-cua RPC aborted"):fw.abortError(n))))},p=setTimeout((()=>{d((()=>s(new uw(`local-cua RPC timed out after ${r}ms`))))}),r);n?.addEventListener("abort",h,{once:!0}),n?.aborted?h():(u.on("connect",(()=>{u.write(`${JSON.stringify(t)}\n`,(e=>{null==e?l=!0:d((()=>s(fw.socketError(e))))}))})),u.on("data",(e=>{const t=e.indexOf(10),r=c+(t<0?e.length:t);if(r>lw.responseMaxBytes)return void d((()=>s(new uw("local-cua RPC response exceeded the size limit"))));if(t<0)return a.push(e),void(c+=e.length);a.push(e.subarray(0,t));const n=Buffer.concat(a,r);a=[],c=0;try{const e=lw.parseResponse({line:n,expectedID:fw.requestID});d((()=>o(e)))}catch(e){d((()=>s(e)))}})),u.on("error",(e=>{d(l?()=>s(new uw("local-cua RPC connection failed after request delivery")):()=>s(fw.socketError(e)))})),u.on("close",(()=>{const e=c>0?"local-cua RPC response ended without a newline":l?"local-cua RPC connection closed after request delivery":"local-cua RPC connection closed";d((()=>s(new uw(e))))})))}))}}let mw;function gw(){if(void 0===mw){const e=async function(){const[{createJimp:e},{default:t},{default:n},{default:o,msBmp:s},{default:i},{default:a},{methods:c}]=await Promise.all([Promise.all([r.e(731),r.e(250)]).then(r.bind(r,"../../node_modules/.pnpm/@jimp+core@1.6.0/node_modules/@jimp/core/dist/esm/index.js")),r.e(690).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-png@1.6.0/node_modules/@jimp/js-png/dist/esm/index.js")),r.e(831).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-jpeg@1.6.0/node_modules/@jimp/js-jpeg/dist/esm/index.js")),Promise.all([r.e(731),r.e(284)]).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-bmp@1.6.0/node_modules/@jimp/js-bmp/dist/esm/index.js")),r.e(295).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-gif@1.6.0/node_modules/@jimp/js-gif/dist/esm/index.js")),r.e(181).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-tiff@1.6.0/node_modules/@jimp/js-tiff/dist/esm/index.js")),r.e(162).then(r.bind(r,"../../node_modules/.pnpm/@jimp+plugin-resize@1.6.0/node_modules/@jimp/plugin-resize/dist/esm/index.js"))]);return e({formats:[t,n,o,s,i,a],plugins:[c]})}().catch((t=>{throw mw===e&&(mw=void 0),t}));mw=e}return mw}fw.logger=(0,d.h)("local-cua:rpc"),fw.serviceAppBundleName="Cursor Computer Use",fw.appSupportFolder="cursor-computer-use",fw.productionExecutableName="CUCursorService",fw.sharedInstallRelativePath=[".cursor","computer-use-sidecar"],fw.appSupportOverrideEnv="CUA_APP_SUPPORT_DIR",fw.serviceAppOverrideEnv="CUA_SERVICE_APP",fw.directLaunchEnv="CUA_DIRECT_LAUNCH",fw.protocolMajor=1,fw.defaultCallTimeoutMs=45e3,fw.launchReadyTimeoutMs=8e3,fw.launchPollIntervalMs=200,fw.requestID=1;var ww=r("node:module"),yw=r.t(ww,2);const vw="mac-webp-runtime.cjs";function bw(e){return"function"==typeof e}function Sw(e){return"object"==typeof e&&null!==e&&"getFileName"in e&&"function"==typeof e.getFileName}function kw(){const e=(new Error).stack;return Array.isArray(e)?e.filter(Sw):[]}let _w,Cw;function Ew(){return _w??=(()=>{const e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;const e=kw()[0]?.getFileName();return function(){const e=yw;if("createRequire"in e&&bw(e.createRequire))return e.createRequire;if("default"in e&&"object"==typeof e.default&&null!==e.default&&"createRequire"in e.default&&bw(e.default.createRequire))return e.default.createRequire;throw new Error("node:module createRequire is unavailable")}()("string"==typeof e&&e.length>0?e:(0,s.join)(process.cwd(),"package.json"))}finally{Error.prepareStackTrace=e}})(),_w}function xw(){const e=globalThis.__MAC_WEBP_IMPORT__;return"function"==typeof e?t=>Promise.resolve(e(t)):(Cw??=function(){const e=[],t=new Set,r=r=>{t.has(r)||(t.add(r),e.push(r))};for(const e of function(){const e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;const e=[];for(const t of kw()){const r=t.getFileName();"string"==typeof r&&r.length>0&&e.push(r)}return e}finally{Error.prepareStackTrace=e}}()){const t=(0,s.dirname)((n=e).startsWith("file:")?(0,Pd.fileURLToPath)(n):n);r((0,s.join)(t,vw)),r((0,s.join)(t,"..","..","src","computer-use",vw))}var n;"string"==typeof process.argv[1]&&process.argv[1].length>0&&r((0,s.join)((0,s.dirname)(process.argv[1]),vw)),r((0,s.join)(process.cwd(),"src","computer-use",vw)),r((0,s.join)(process.cwd(),"computer-use",vw));try{const e=(0,s.dirname)(Ew().resolve("@anysphere/local-exec/package.json"));r((0,s.join)(e,"src","computer-use",vw)),r((0,s.join)(e,"dist","computer-use",vw))}catch{}for(const t of e)try{const e=Ew()(t);if("object"==typeof e&&null!==e&&"importFile"in e&&"function"==typeof e.importFile)return e.importFile.bind(e)}catch{}throw new Error("mac-webp runtime importer was not found next to the bundle")}(),Cw)}function Pw(...e){return t=["@jsquash","webp",...e].join("/"),Ew().resolve(t);var t}async function Rw(...e){var t;return await(t=(0,Pd.pathToFileURL)(Pw(...e)).href,xw()(t))}const Iw=e=>{let t;return()=>{if(void 0===t){const r=e();r.catch((()=>{t===r&&(t=void 0)})),t=r}return t}},Tw=(Iw((async()=>{const e=await Rw("decode.js");return await e.init({wasmBinary:await Ro.promises.readFile(Pw("codec","dec","webp_dec.wasm"))}),e})),Iw((async()=>{const[e,t,r]=await Promise.all([Rw("utils.js"),Rw("meta.js"),Rw("codec","enc","webp_enc.js")]);return{module:await e.initEmscriptenModule(r.default,void 0,{wasmBinary:await Ro.promises.readFile(Pw("codec","enc","webp_enc.wasm"))}),defaultOptions:t.defaultOptions}}))),Aw="image/png",$w={async normalize(e){if(e.mimeType!==Aw)throw new Error(`Mac screenshot must be ${Aw}, received ${e.mimeType}`);const t=await gw(),r=await t.read(Buffer.from(e.data,"base64"));return(await(n={data:r.bitmap.data,width:r.bitmap.width,height:r.bitmap.height},(async e=>{const{module:t,defaultOptions:r}=await Tw(),n=new Uint8ClampedArray(e.data.buffer,e.data.byteOffset,e.data.byteLength);return Buffer.from(t.encode(n,e.width,e.height,{...r,lossless:1,exact:1}))})(n))).toString("base64");var n}},Mw={userFacing:function(e){if(e instanceof uw&&e.userFacing&&e.message.trim().length>0&&!tw(e.message))return e.message.trim()},isCaptureBlocked:function(e){return e instanceof uw&&("computer_use_screenshot"===e.tool||"permission_required"===e.code)}},Dw=new Set(["keys"]),Ow=new Set(["matched","mismatch","unchecked"]),Fw=new Set(["no_text","password","control_keys","too_long","unreadable","moved","chromium","gecko"]),Nw=new Set(["matched"]),Lw=new Set(["too_long"]),jw=new Set(["watched","fell_back","unavailable","over_budget"]);class Uw{constructor({ctx:e,actions:t,sidecar:r,errors:n,reportTyping:o}){this.startTime=Date.now(),this.typingNotes=[],this.typing=[],this.geometryPrimed=!1,this.actionCount=0,this.hasCompletedActuation=!1,this.staleAfterWait=!1,this.ctx=e,this.actions=t,this.sidecar=r,this.errors=n??Mw,this.reportTyping=!0===o}async execute(){const e=this.actions.some((e=>Uw.isInputAction(e.action.case)));try{this.throwIfAborted(),e&&await this.sidecar.startControl(this.ctx);for(const e of this.actions){this.throwIfAborted();const t=e.action;if(void 0===t.case)throw new Error("Computer use action case is undefined");switch(this.actionCount+=1,t.case){case"screenshot":case"cursorPosition":await this.captureScreen();break;case"click":void 0!==t.value.coordinate&&await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.click(this.ctx,{coordinate:t.value.coordinate,button:Uw.mouseButtonName(t.value.button),count:t.value.count>0?t.value.count:1,modifierKeys:t.value.modifierKeys}),t.value.coordinate);break;case"scroll":void 0!==t.value.coordinate&&await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.scroll(this.ctx,{coordinate:t.value.coordinate,direction:Uw.scrollDirectionName(t.value.direction),amount:t.value.amount>0?t.value.amount:3,modifierKeys:t.value.modifierKeys}),t.value.coordinate);break;case"mouseMove":if(void 0===t.value.coordinate)throw new Error("MouseMoveAction requires coordinate");await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.move(this.ctx,{x:t.value.coordinate.x,y:t.value.coordinate.y}),t.value.coordinate);break;case"mouseDown":this.recordActuation(await this.sidecar.mouseButton(this.ctx,{button:Uw.mouseButtonName(t.value.button),action:"down"}));break;case"mouseUp":this.recordActuation(await this.sidecar.mouseButton(this.ctx,{button:Uw.mouseButtonName(t.value.button),action:"up"}));break;case"drag":{const e=t.value.path.map((e=>({x:e.x,y:e.y})));await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.drag(this.ctx,{button:Uw.mouseButtonName(t.value.button),path:e,modifierKeys:t.value.modifierKeys}),e.at(-1));break}case"type":{const e=await this.sidecar.typeText(this.ctx,t.value.text);this.recordActuation(e),this.recordTyping(e);break}case"key":if(t.value.stroke===Ng.EB.DOWN||t.value.stroke===Ng.EB.UP)throw new Error("Held keys (KeyAction.stroke DOWN/UP) are not supported by the computer-use sidecar; use hold_duration_ms");this.recordActuation(await this.sidecar.pressKey(this.ctx,{key:t.value.key,holdDurationMs:t.value.holdDurationMs}));break;case"wait":await this.delay(Math.max(0,t.value.durationMs)),this.staleAfterWait=!0;break;default:{const e=t;throw new Error(`Unknown computer use action: ${JSON.stringify(e)}`)}}}this.throwIfAborted(),(void 0===this.screenshot||this.staleAfterWait)&&await this.captureScreen(),this.throwIfAborted();const t=await this.normalizeRetainedScreenshots();return t.screenshotFailed&&!this.hasCompletedActuation?this.screenshotUnavailableResult(t.failureReason):(this.throwIfAborted(),new Ng.ks({result:{case:"success",value:new Ng.Wd({actionCount:this.actionCount,durationMs:Date.now()-this.startTime,screenshot:t.screenshot,cursorPosition:this.cursor,log:this.log(t.screenshotFailed?"Screenshot unavailable":void 0),typing:this.typing})}}))}catch(e){return this.ctx.signal.aborted?this.abortedResult():this.errorResult(e)}finally{e&&await this.sidecar.releaseControl(this.ctx)}}static isInputAction(e){switch(e){case"click":case"scroll":case"mouseMove":case"mouseDown":case"mouseUp":case"drag":case"type":case"key":return!0;default:return!1}}async captureScreen(){const e=await this.sidecar.screenshot(this.ctx);this.screenshot=e.screenshot,this.cursor=Uw.cursorFromResult(e)??this.cursor,this.geometryPrimed=!0,this.staleAfterWait=!1}async ensureGeometryCached(){this.geometryPrimed||await this.captureScreen()}recordActuation(e,t){this.screenshot=e.screenshot,this.hasCompletedActuation=!0,this.staleAfterWait=!1,void 0!==e.screenshot&&(this.geometryPrimed=!0),this.cursor=Uw.cursorFromResult(e)??Uw.coordinateFromPoint(t)??this.cursor}recordTyping(e){if(!this.reportTyping)return;const t=e.message.trim();""!==t&&this.typingNotes.push(t);const r=Uw.typingFromResult(e);void 0!==r&&this.typing.push(r)}log(e){const t=void 0===e?this.typingNotes:[...this.typingNotes,e];return 0===t.length?void 0:t.join("\n")}static typingFromResult(e){const t=e.structuredContent;if("object"!=typeof t||null===t||!("type"in t))return;const r=t.type;if("object"!=typeof r||null===r)return;const n=new Map(Object.entries(r)),o=(e,t)=>{const r=n.get(e);return"string"==typeof r&&t.has(r)?r:void 0},s=e=>{const t=n.get(e);return"number"==typeof t&&Number.isInteger(t)&&t>=0?t:void 0},i=o("check",Ow),a=o("unchecked",Fw),c=void 0!==n.get("unchecked")&&null!==n.get("unchecked"),l=void 0!==i&&Nw.has(i)&&!c||"unchecked"===i&&void 0!==a&&Lw.has(a);return new Ng.qA({method:o("method",Dw)??"",chars:l?s("chars")??0:0,atoms:l?s("atoms")??0:0,typedAtoms:l?s("typedAtoms")??0:0,aborted:!0===n.get("aborted"),check:i,verified:l?s("verified"):void 0,unchecked:a,landing:o("landing",jw)})}async errorResult(e){let t;if(Uw.logger.error(this.ctx,"local-cua execute failed",void 0,{error:dw(e)}),!this.errors.isCaptureBlocked(e))try{const e=await this.sidecar.screenshot(this.ctx);t=(await this.normalizeScreenshot(e.screenshot,"error")).data}catch(e){Uw.logger.warn(this.ctx,"local-cua error screenshot capture failed",{error:dw(e)})}const r=this.errors.userFacing(e);return new Ng.ks({result:{case:"error",value:new Ng.Jb({error:void 0===r?"Computer use failed":`Computer use failed: ${r}`,actionCount:this.actionCount,durationMs:Date.now()-this.startTime,screenshot:t,log:this.log(),typing:this.typing})}})}screenshotUnavailableResult(e){return new Ng.ks({result:{case:"error",value:new Ng.Jb({error:"Screenshot unavailable",actionCount:this.actionCount,durationMs:Date.now()-this.startTime,log:e})}})}abortedResult(){return new Ng.ks({result:{case:"error",value:new Ng.Jb({error:"Computer use aborted",actionCount:this.actionCount,durationMs:Date.now()-this.startTime,log:this.log(),typing:this.typing})}})}static mouseButtonName(e){return Uw.mouseButtonNames[e]??"left"}static scrollDirectionName(e){return Uw.scrollDirectionNames[e]??"down"}async normalizeRetainedScreenshots(){const e=await this.normalizeScreenshot(this.screenshot,"post-action");return{screenshot:e.data,screenshotFailed:void 0===this.screenshot||e.failed,failureReason:void 0===this.screenshot?"sidecar returned no image":e.reason}}async normalizeScreenshot(e,t){if(void 0===e)return{failed:!1};try{return{data:await $w.normalize(e),failed:!1}}catch(r){const n=dw(r);return Uw.logger.error(this.ctx,"local-cua screenshot conversion failed",void 0,{frame:t,error:n}),"image/png"===e.mimeType&&e.data.length>0?{data:e.data,failed:!1}:{failed:!0,reason:n}}}static coordinateFromPoint(e){if(void 0!==e&&Number.isFinite(e.x)&&Number.isFinite(e.y))return new Ng.xp({x:Math.round(e.x),y:Math.round(e.y)})}static cursorFromResult(e){const t=e.structuredContent;if("object"!=typeof t||null===t||!("cursor"in t))return;const r=t.cursor;return"object"==typeof r&&null!==r&&"x"in r&&"y"in r&&"number"==typeof r.x&&"number"==typeof r.y&&Number.isFinite(r.x)&&Number.isFinite(r.y)?new Ng.xp({x:Math.round(r.x),y:Math.round(r.y)}):void 0}throwIfAborted(){if(this.ctx.signal.aborted)throw this.ctx.signal.reason??new Error("Computer use aborted")}delay(e){return this.throwIfAborted(),new Promise(((t,r)=>{const n=()=>{clearTimeout(o),r(this.ctx.signal.reason??new Error("Computer use aborted"))},o=setTimeout((()=>{this.ctx.signal.removeEventListener("abort",n),t()}),e);this.ctx.signal.addEventListener("abort",n,{once:!0}),this.ctx.signal.aborted&&n()}))}}Uw.logger=(0,d.h)("local-cua:actions"),Uw.mouseButtonNames={[Ng.w3.UNSPECIFIED]:"left",[Ng.w3.LEFT]:"left",[Ng.w3.RIGHT]:"right",[Ng.w3.MIDDLE]:"middle",[Ng.w3.BACK]:"left",[Ng.w3.FORWARD]:"left"},Uw.scrollDirectionNames={[Ng.Dh.UNSPECIFIED]:"down",[Ng.Dh.UP]:"up",[Ng.Dh.DOWN]:"down",[Ng.Dh.LEFT]:"left",[Ng.Dh.RIGHT]:"right"},s.join(o.tmpdir(),"computer-use"),(0,d.h)("local-cua:windows");Error,Buffer.from([137,80,78,71,13,10,26,10]),new Set(["capture_failed","secure_desktop","input_desktop_unavailable","sidecar_unavailable","user_aborted","session_busy","canvas_mismatch"]);var Bw,Ww=r("../proto/dist/generated/agent/v1/delete_exec_pb.js");function Hw({encoding:e,bom:t,lineEnding:r}){return{encoding:e,bom:t,lineEnding:r}}class qw{constructor(e){this.workspacePath=e,this.changes=new Map,this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){for(const t of this.listeners)t(e)}async trackChange(e,t,r,n,o){const s=this.changes.get(e);if(s){const t=s.before,o=n||s.metadata;if(t===r||void 0===t&&void 0===r)this.changes.delete(e),this.notify();else{const n={path:e,before:t,after:r,metadata:o,...void 0===s.beforeFormat?{}:{beforeFormat:s.beforeFormat}};this.changes.set(e,n),this.notify(n)}}else{const s={path:e,before:t,after:r,metadata:n,...void 0===o?{}:{beforeFormat:o}};this.changes.set(e,s),this.notify(s)}}getChanges(){return Array.from(this.changes.values())}getChange(e){return this.changes.get(e)}hasChange(e){return this.changes.has(e)}accept(e){const t=this.changes.get(e);this.changes.delete(e),this.notify(t)}acceptAll(){this.changes.clear(),this.notify()}async reject(e){const t=this.changes.get(e);if(t)try{void 0===t.before&&void 0!==t.after?await(0,xo.unlink)(e):(void 0!==t.before&&void 0===t.after||void 0!==t.before&&void 0!==t.after)&&await async function(e,t,r,n){const{buffer:o,format:s}=await qi(e,t,r,n);await(0,xo.writeFile)(e,o),await Hi(e,{buffer:o,encoding:s.encoding})}(e,t.before,this.workspacePath)}catch{}finally{this.changes.delete(e),this.notify(t)}}async rejectAll(){const e=Array.from(this.changes.keys());await Promise.all(e.map((e=>this.reject(e))))}clear(){const e=this.changes.values().next().value;this.changes.clear(),this.notify(e)}get size(){return this.changes.size}dispose(){this.changes.clear(),this.listeners.clear()}}!function(e){e.Write="write",e.Read="read",e.Shell="shell",e.Delete="delete",e.Mcp="mcp"}(Bw||(Bw={}));var zw=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class Gw{constructor(e,t,r,n,o,s){this.pendingDecisionProvider=e,this.fileChangeTracker=t,this.permissionsService=r,this.workspacePath=n,this.onDeleteForAiTracking=o,this.agentFileViews=s}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,D.VI)(e.withName("LocalDeleteExecutor.execute")),!1);const n=t.path;if(""===n.trim())return new Ww.Pi({result:{case:"error",value:new Ww.GU({path:n,error:rs})}});const o=(0,ts.o1)(n,this.workspacePath),i=await this.permissionsService.shouldBlockWrite(e,o,"");if(i){const e=await ed(i,{onNeedsApproval:async(e,t)=>null,onUserRejected:e=>new Ww.Pi({result:{case:"rejected",value:new Ww.iq({path:o,reason:e||""})}}),onPermissionDenied:(e,t)=>new Ww.Pi({result:{case:"permissionDenied",value:new Ww.QG({path:o,clientVisibleError:e,isReadonly:t?.isReadonly??!1})}})});if(null!==e)return e}const a=await async function(e,t){const r=await(0,xo.realpath)((0,s.dirname)(e)).catch((()=>{}));if(void 0===r)return e;if(void 0!==t){const n=await(0,xo.realpath)(t).catch((()=>{}));if(void 0!==n&&(0,ts.BJ)(r,n))return(0,s.resolve)(t,(0,s.relative)(n,r),(0,s.basename)(e))}return(0,s.join)(r,(0,s.basename)(e))}(o,this.workspacePath),c=await this.pendingDecisionProvider.requestApproval({type:Bw.Delete,details:{path:a},toolCallId:t.toolCallId});if(!c.approved)return new Ww.Pi({result:{case:"rejected",value:new Ww.iq({path:o,reason:c.reason||""})}});let l;try{l=await(0,xo.stat)(o)}catch(e){return"ENOENT"===_c(e)?new Ww.Pi({result:{case:"fileNotFound",value:new Ww.n0({path:o})}}):new Ww.Pi({result:{case:"error",value:new Ww.GU({path:o,error:Cc(e)})}})}if(!l.isFile()){const e=l.isDirectory()?"directory":"other";return new Ww.Pi({result:{case:"notFile",value:new Ww.LX({path:o,actualType:e})}})}const u=l.size;let d,h;if(u<=ss)try{const e=await Wi(o);d=e.text,h=Hw(e)}catch{}const p=d??"",f=await(0,xo.realpath)(o).catch((()=>o)),m=await(0,xo.stat)(o).catch((()=>{}));if(m?.dev!==l.dev||m.ino!==l.ino)return new Ww.Pi({result:{case:"error",value:new Ww.GU({path:o,error:"File changed while deleting; nothing was removed"})}});e.signal.throwIfAborted();try{await(0,xo.unlink)(o),this.agentFileViews?.recordDelete(o)}catch(e){return"EACCES"===_c(e)?new Ww.Pi({result:{case:"permissionDenied",value:new Ww.QG({path:o,clientVisibleError:"Permission denied"})}}):"EBUSY"===_c(e)?new Ww.Pi({result:{case:"fileBusy",value:new Ww.vX({path:o})}}):new Ww.Pi({result:{case:"error",value:new Ww.GU({path:o,error:Cc(e)})}})}if(this.fileChangeTracker&&void 0!==d){const e={...t.toolCallId?{toolCallId:t.toolCallId}:{},...f===o?{}:{writtenPath:f},beforeMode:511&l.mode};await this.fileChangeTracker.trackChange(o,d,void 0,e,h)}return this.onDeleteForAiTracking&&this.onDeleteForAiTracking({path:o}).catch((()=>{})),new Ww.Pi({result:{case:"success",value:new Ww.fl({path:o,deletedFile:o,fileSize:BigInt(u),prevContent:p})}})}catch(e){r.error=e,r.hasError=!0}finally{zw(r)}}}class Vw{constructor(e,t){this.inner=e,this.extraTools=t}async getTools(e){return[...await this.inner.getTools(e).catch((()=>[])),...this.extraTools]}async getToolsForServers(e,t){const r=await this.inner.getToolsForServers(e,t).catch((()=>[])),n=new Set(t);return[...r,...this.extraTools.filter((e=>n.has(e.clientKey)||n.has(e.providerIdentifier)))]}async getClients(e){return this.inner.getClients(e)}async getClient(e,t){return this.inner.getClient(e,t)}async getInstructions(e){const t=await this.inner.getInstructions(e).catch((()=>[])),r=this.extraTools.filter((e=>e.providerIdentifier===Vn));if(0===r.length)return t;const n=r.map((e=>{const t="string"==typeof e.description&&e.description.length>0?e.description:"(no description provided)";return`- ${e.toolName}: ${t}`})).join("\n");return[...t,new vn.I0({serverIdentifier:Vn,serverName:Vn,instructions:`User-defined tools for this session (server "${Vn}"). Discover schemas via MCP meta-tool discovery for that server, then invoke via the MCP invocation meta-tool.\n\nAvailable tools:\n${n}`})]}async getToolSet(e){return this.inner.getToolSet(e)}}class Kw extends Vw{constructor(e,t){super(e,t),this.observableInner=e}onDidChange(e){return this.observableInner.onDidChange(e)}}var Jw=r("../proto/dist/generated/agent/v1/fetch_exec_pb.js"),Zw=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Xw=/;\s*charset\s*=\s*"?([^";\s]+)/i;class Qw{constructor(e){this.encodingSlices=e?.encodingSlices}async readText(e,t){if(!Wl(this.encodingSlices,e))return await t.text();const r=async function(e,t){if(void 0===e)return"unseen";try{return(0,n.isUtf8)(await e.arrayBuffer())?"utf8_valid":t?"declared_other":"utf8_invalid"}catch{return"unseen"}}(function(e){try{return e.clone()}catch{return}}(t),function(e){const t=Xw.exec(e.headers.get("content-type")??"")?.[1];return void 0!==t&&!/^utf-?8$/i.test(t)}(t)),o=await t.text();return this.recordFetched(e,o,r),o}async recordFetched(e,t,r){try{tu(this.encodingSlices,e,{layer:"exec_web_fetch",evidence:await r},t)}catch{}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,D.VI)(e.withName("LocalFetchExecutor.execute")),!1);const n=t.url;try{const t=await fetch(n),r=await this.readText(e,t),o=t.headers.get("content-type")||"text/plain";return new Jw.uN({result:{case:"success",value:new Jw.Uk({url:n,content:r,statusCode:t.status,contentType:o})}})}catch(e){return new Jw.uN({result:{case:"error",value:new Jw.fk({url:n,error:Cc(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{Zw(r)}}}const Yw=[["safe.bareRepository","explicit"]],ey=[["core.fsmonitor","false"],["core.hooksPath",o.devNull],["core.attributesFile",o.devNull]],ty=[["core.quotePath","false"]];function ry(e){const t="allow-hooks"===e?ey.filter((([e])=>"core.hooksPath"!==e)):ey;return[...Yw,...t]}const ny=(0,Vs.promisify)(iu.execFile),oy=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env","--attr-source"]),sy=new Set(["diff","show","blame","log","whatchanged"]);function iy(e){for(let t=0;t["-c",`${e}=${t}`]))}const vy=yy([...ry("block"),["submodule.recurse","false"],["fetch.recurseSubmodules","false"],["diff.submodule","short"],["status.submoduleSummary","false"],["log.showSignature","false"],["log.diffMerges","separate"],["gpg.openpgp.program",o.devNull],["gpg.x509.program",o.devNull],["gpg.ssh.program",o.devNull]]);function by(e){const t=e?.timeout??0,r=Number.isFinite(t)&&t>0?Math.min(t,2147483647):6e4;return performance.now()+r}function Sy(e,t=2147483647){return Math.max(1,Math.ceil(Math.min(t,e-performance.now())))}function ky(){const e=new Map;return{async exec(t,r,n){const o=by(n);return uy("git",await _y(e,t,r,o),{cwd:t,env:wy,windowsHide:!0,killSignal:"SIGTERM",timeout:Sy(o)})},async run(t,r,n){const o=by(n);return function(e,t,r,n){return new Promise(((o,s)=>{const i=function(e,t,r){const{env:n,...o}=r??{},s=cy(t);return(0,iu.spawn)("git",s,{...o,env:ly(s,n)})}(0,t,{cwd:e,env:wy,windowsHide:!0,stdio:[void 0===n?"ignore":"pipe","pipe","pipe"]}),a=[],c=[];let l=!1;const u=()=>{const e=!l;return l=!0,clearTimeout(d),e},d=setTimeout((()=>{u()&&(i.kill("SIGTERM"),i.stdin?.destroy(),i.stdout?.destroy(),i.stderr?.destroy(),s(Object.assign(new Error("git timed out"),{code:null,killed:!0,signal:"SIGTERM"})))}),Sy(r));i.stdout?.on("data",(e=>{a.push(e)})),i.stderr?.on("data",(e=>{c.push(e)}));for(const e of[i.stdout,i.stderr])e?.on("error",(e=>{u()&&(i.kill("SIGTERM"),s(e))}));i.on("error",(e=>{u()&&s(e)})),i.on("close",((e,t)=>{u()&&(null!==e?o({exitCode:e,stdout:Buffer.concat(a).toString("utf8"),stderr:Buffer.concat(c).toString("utf8")}):s(Object.assign(new Error(`git was killed by ${String(t)}`),{code:e,killed:!1,signal:t})))})),void 0!==n&&null!==i.stdin&&(i.stdin.on("error",(()=>{})),i.stdin.end(n))}))}(t,await _y(e,t,r,o),o,n?.input)}}}async function _y(e,t,r,n){const{prefix:o,tail:s,readsConfig:i}=function(e){const t=cy(e),r=iy(t),n=t.findIndex(((e,t)=>t>r&&("--"===e||"--end-of-options"===e))),o=t.slice(0,-1===n?t.length:n);if(o.includes("--help")||o.includes("-h"))throw new TypeError("git help is refused: it starts the repository's man viewer");if(-1===r)return{prefix:[],tail:t,readsConfig:!1};const s=t[r],i=hy.get(s);if(void 0===i)throw new TypeError(`git ${s} is refused: the pins cover only a fixed set of verbs`);const[a,c]=i,l=o.find((e=>function(e,t,r){const n=r.startsWith("--")?r.slice(2).split("=",1)[0]:"",o=[...py,..."status"===e?["verbose"]:[],..."worktree"===e?["checkout","no-force"]:[],...t?["ignore-submodules","no-ignore-submodules"]:[]];return""!==n&&o.some((e=>e.startsWith(n)))||"status"===e&&/^-[^-]*v/.test(r)}(s,c,e)));if(void 0!==l)throw new TypeError(`git ${s} ${l} is refused: it can start a program the pins miss`);const u=t.slice(r+1),d="worktree"===s?u.find((e=>!e.startsWith("-"))):void 0;if("remove"===d&&!o.includes("--force")&&!o.includes("-f"))throw new TypeError("git worktree remove is refused without --force");if("add"===d&&"--no-checkout"!==u[u.indexOf("add")+1])throw new TypeError("git worktree add is refused unless --no-checkout follows add");return{prefix:[...t.slice(0,r),...vy],tail:[s,...c?["--ignore-submodules=dirty"]:[],...u],readsConfig:a}}(r),a=i?await function(e,t,r,n){const o=`${t}\0${r.join("\0")}`,s=e.get(o);if(void 0!==s)return s;const i=async function(e,t,r){let n;try{n=(await uy("git",[...t,"config","--list","--show-scope","--includes","-z"],{cwd:e,env:wy,windowsHide:!0,killSignal:"SIGTERM",timeout:Sy(r,1e4),maxBuffer:16777216})).stdout}catch(e){throw function(e){if(!(e instanceof Error))return new dy("read-failed");if("syscall"in e&&"string"==typeof e.syscall&&e.syscall.startsWith("spawn"))return e;if("killed"in e&&!0===e.killed)return new dy("timed-out");const t="code"in e&&"number"==typeof e.code?e.code:void 0;return new dy("read-failed",t)}(e)}if(performance.now()>=r)throw new dy("timed-out");return function(e){if(""===e)return[];const t=e.split("\0");if(""!==t.pop()||t.length%2!=0)throw new dy("read-failed");const r=new Set;for(let e=0;eyy([[`filter.${e}.clean`,""],[`filter.${e}.smudge`,""],[`filter.${e}.process`,""],[`filter.${e}.required`,"false"]])))}(n)}(t,r,n);return e.set(o,i),i}(e,t,o,n):[];return[...o,...a,...s]}function Cy(e,t,r){return ky().exec(e,t,r)}var Ey=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class xy{constructor(e={}){void 0!==e.guardedRootLookup&&(this.guardedRootLookup=e.guardedRootLookup)}async exec(e,t,r,n){return Py(e,t,r,n,Cy)}forRequest(){const e=ky();return{exec:(t,r,n,o)=>Py(t,r,n,o,((t,r,n)=>e.exec(t,r,n))),...void 0===this.guardedRootLookup?{}:{guardedRootLookup:this.guardedRootLookup}}}}async function Py(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(s,(0,D.VI)(e.withName("LocalGitExecutor.exec"),{attributes:{"git.cwd":t,"git.args":r,"git.caller":n?.caller}}),!1);const{stdout:i,stderr:a}=await o(t,r,{timeout:n?.timeout});return{exitCode:0,stdout:i,stderr:a}}catch(e){s.error=e,s.hasError=!0}finally{Ey(s)}}var Ry=r("../proto/dist/generated/agent/v1/grep_exec_pb.js");class Iy{constructor(){this.lineEnd=0,this.nextStart=0}}function Ty(e,t,r){const n=e.length;if(t>=n)return!1;const o=e.indexOf("\n",t);if(-1!==o){const n=o>t&&13===e.charCodeAt(o-1);return r.lineEnd=n?o-1:o,r.nextStart=o+1,!0}return r.lineEnd=n,r.nextStart=n,!0}function Ay(e,t,r,n,o,s){const i=e.indexOf("\0",t);if(-1===i||i>=r)return;let a=i+1;for(;a=48&&e.charCodeAt(a)<=57;)a++;if(a===i+1||a>=r)return;const c=e.charCodeAt(a);if(58!==c&&45!==c)return;const l=n.indexOf(0,o);if(-1===l||l>=s)return;const u=l+(a-i);return u>=s||n.toString("latin1",l+1,u+1)!==e.slice(i+1,a+1)?void 0:{file:e.slice(t,i),contentStart:a+1,contentEnd:r,contentBytesStart:u+1,contentBytesEnd:s}}const $y=-(2**31),My=2**31-1;function Dy(e){return Number.isNaN(e)?0:e<$y?$y:e>My?My:e}function Oy(e){if("number"==typeof e&&Number.isFinite(e)&&!(e<0))return Dy(Math.trunc(e))}function Fy(e){const t=e.replace(/\s/g,"_").replace(/[^a-zA-Z0-9_.-]/g,"").replace(/\.+/g,".");return"."===t||".."===t?t.replace(/\./g,"_"):0===t.length?"_":t}async function Ny(e,t){const r=Fy(t),n=(0,s.join)(e,"mcps",r,"tools");let o;try{o=await(0,xo.readdir)(n)}catch(e){if("ENOENT"===_c(e))return{toolNames:[],toolsDirExists:!1};throw e}const i=await Promise.all(o.map((async e=>{if(e.endsWith(".json"))try{return function(e){try{const t=JSON.parse(e);return"string"==typeof t.name&&t.name.length>0?t.name:"string"==typeof t.toolName&&t.toolName.length>0?t.toolName:void 0}catch{return}}(await(0,xo.readFile)((0,s.join)(n,e),"utf8"))}catch{return}}))),a=new Set;for(const e of i)e&&a.add(e);return{toolNames:Array.from(a).sort(((e,t)=>e.localeCompare(t))),toolsDirExists:!0}}const Ly=(0,d.h)("local-exec:mcp-disk-freshness-on-access"),jy="/mcps/",Uy=(0,h.Pu)("mcp.discovery_freshness.check",{description:"MCP discovery surface freshness comparison outcome against canonical live tools",labelNames:["surface","outcome"]}),By=(0,h.v5)("mcp.discovery_freshness.missing_tools",{description:"Number of tools present in canonical live state but missing from the observed discovery surface",labelNames:["surface"]}),Wy=(0,h.v5)("mcp.discovery_freshness.extra_tools",{description:"Number of tools present on the observed discovery surface but absent from canonical live state",labelNames:["surface"]}),Hy=(0,h.v5)("mcp.discovery_freshness.symmetric_difference",{description:"Total symmetric difference between canonical live tools and the observed discovery surface",labelNames:["surface"]}),qy=new Map;function zy(e){const t=e.replace(/\\/g,"/");return t.endsWith("/mcps")?`${t}/`:t}async function Gy({ctx:e,mcpStateAccessor:t,projectDir:r,sanitizedServerFolder:n,readDiskCatalog:o,state:s}){let i=s;if(void 0===i)try{i=await t.getState(e)}catch(t){return void Ly.warn(e,"mcp_disk_state_read_failed",{error_type:t instanceof Error?t.name:typeof t})}const a=i.servers.find((e=>Fy(e.serverIdentifier)===n));if(void 0===a)return;let c;try{c=await o(r,a.serverIdentifier)}catch(t){return void Ly.warn(e,"mcp_disk_catalog_read_failed",{error_type:t instanceof Error?t.name:typeof t})}if(!c.toolsDirExists)return;const l=a.tools.map((e=>e.toolName)).filter((e=>e.length>0)).sort(((e,t)=>e.localeCompare(t)));!function({ctx:e,serverIdentifier:t,canonicalToolNames:r,observedToolNames:n}){const o=new Set(n),s=new Set(r),i=r.filter((e=>!o.has(e))),a=n.filter((e=>!s.has(e))),c=0===i.length&&0===a.length?"match":"mismatch",l={surface:"disk"};Uy.increment(e,1,{...l,outcome:c}),By.histogram(e,i.length,l),Wy.histogram(e,a.length,l),Hy.histogram(e,i.length+a.length,l),"mismatch"===c&&Ly.warn(e,"mcp_disk_discovery_freshness_mismatch",{server_identifier:t,missing_tool_count:i.length,extra_tool_count:a.length})}({ctx:e,serverIdentifier:a.serverIdentifier,canonicalToolNames:l,observedToolNames:c.toolNames})}function Vy(e,t,r,n=Ny){if(void 0===r||(void 0===(o=r)||!zy(o).includes(jy)))return;var o;const s=function(e){const t=zy(e),r=t.indexOf(jy);if(-1===r)return;const n=t.slice(0,r),o=t.slice(r+6).split("/").filter(Boolean);return 0!==n.length?0===o.length?{projectDir:n,kind:"mcps_root"}:{projectDir:n,kind:"server",sanitizedServerFolder:o[0]}:void 0}(r);if(void 0===s)return;let i,a;const c="mcps_root"===s.kind;"mcps_root"===s.kind?(i=`${s.projectDir}\0__mcps_root__`,a=void 0):(i=`${s.projectDir}\0${s.sanitizedServerFolder}`,a=s.sanitizedServerFolder);const l=qy.get(i);void 0!==l&&clearTimeout(l);const u=e,d=setTimeout((()=>{qy.delete(i),(async()=>{if(c){const e=await t.getState(u);for(const r of e.servers){const o=Fy(r.serverIdentifier);await Gy({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:o,readDiskCatalog:n,state:e})}}else void 0!==a&&await Gy({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:a,readDiskCatalog:n})})().catch((e=>{Ly.warn(u,"mcp_disk_discovery_freshness_schedule_failed",{error_type:e instanceof Error?e.name:typeof e})}))}),2e3);qy.set(i,d)}async function Ky(e){try{return(await(0,xo.stat)(e,{bigint:!0})).mtimeNs}catch{return}}function Jy(e,t,r){const n=e.map(((e,n)=>({file:e,mtime:t[n],segments:e.path.split(r)})));return n.sort(((e,t)=>e.mtime!==t.mtime?void 0===e.mtime?1:void 0===t.mtime||e.mtime>t.mtime?-1:1:function({left:e,right:t}){const r=Math.min(e.length,t.length);for(let n=0;ne.file))}async function Zy(e,t,r=Ky){const n=e.map((e=>({item:e,path:t(e)})));let o;try{o=await(0,Nr.wj)(Promise.all(n.map((({path:e})=>r(e)))),2e3,"stat timed out")}catch(t){if(t instanceof Nr.MU)return{items:[...e],statTimedOut:!0};throw t}return{items:Jy(n,o,s.sep).map((({item:e})=>e)),statTimedOut:!1}}var Xy=r("../proto/dist/generated/agent/v1/read_exec_pb.js");const Qy=Buffer.from([137,80,78,71,13,10,26,10]),Yy=Buffer.from([0,0,0,0,73,69,78,68,174,66,96,130]),ev=e=>{if(e.lengthe.subarray(e.length-Yy.length).equals(Yy)||(e=>{let t=Qy.length+25;for(;t+Yy.length<=e.length;){const r=e.readUInt32BE(t);if(r>e.length-t-Yy.length)return!1;if("IEND"===e.toString("ascii",t+4,t+8))return e.subarray(t,t+Yy.length).equals(Yy);t+=Yy.length+r}return!1})(e))(e))return;const t=e.readUInt32BE(16),r=e.readUInt32BE(20);return t<1||r<1?void 0:{width:t,height:r,colorType:e.readUInt8(25)}},tv=e=>1===e||e>=208&&e<=216,rv=e=>192===e||193===e||194===e,nv=e=>e>=195&&e<=207&&196!==e&&200!==e&&204!==e,ov=e=>0===e||e>=208&&e<=215,sv=(e,t)=>{let r=e.indexOf(255,t);for(;-1!==r&&r+1(e=>{const t=ev(e);if(void 0!==t)return{mimeType:"image/png",width:t.width,height:t.height}})(e)??(e=>{if(e.length<4||255!==e[0]||216!==e[1]||!(e=>255===e[e.length-2]&&217===e[e.length-1]||(e=>{let t=2;for(;t+2<=e.length;){if(255!==e[t])return!1;const r=e[t+1];if(255===r){t+=1;continue}if(217===r)return!0;if(tv(r)){t+=2;continue}if(t+4>e.length)return!1;const n=e.readUInt16BE(t+2);if(n<2)return!1;const o=t+2+n;if(218!==r){t=o;continue}const s=sv(e,o);if(void 0===s)return!1;t=s}return!1})(e))(e))return;let t=2;for(;t+4<=e.length;){if(255!==e[t])return;const r=e[t+1];if(255===r){t+=1;continue}if(tv(r)){t+=2;continue}if(218===r||217===r||nv(r))return;const n=e.readUInt16BE(t+2);if(n<2)return;if(rv(r)){if(n<8||t+9>e.length)return;const r=e.readUInt16BE(t+5),o=e.readUInt16BE(t+7);if(o<1||r<1)return;return{mimeType:"image/jpeg",width:o,height:r}}t+=2+n}})(e),av=(e,t)=>({width:Math.max(e?.width??0,t.width),height:Math.max(e?.height??0,t.height)}),cv=(e,t)=>{for(;t{const t=e.toString("latin1",0,6);return e.subarray(0,Qy.length).equals(Qy)?"png":t.startsWith("ÿØÿ")?"jpeg":"GIF87a"===t||"GIF89a"===t?"gif":t.startsWith("BM")?"bmp":t.startsWith("II*\0")||t.startsWith("MM\0*")?"tiff":t.startsWith("ID3")?"id3":void 0},uv={0:1,2:3,4:2,6:4},dv=async({data:e,width:t,height:r})=>{const n=hv(e);if(void 0===n||t>n.width||r>n.height)return;const o=n.width*n.channels,s=new Uint32Array(n.width);for(let e=0;e{let t;const r=[];let n=8;for(;n+12<=e.length;){const o=e.readUInt32BE(n),s=e.toString("ascii",n+4,n+8),i=e.subarray(n+8,n+8+o);if(i.length!==o)return;if("IHDR"===s){const e=uv[i[9]];if(void 0!==t||13!==o||8!==i[8]||0!==i[12]||void 0===e)return;t={width:i.readUInt32BE(0),height:i.readUInt32BE(4),channels:e}}else if("IDAT"===s)r.push(i);else{if("tRNS"===s)return;if("IEND"===s)break}n+=o+12}return void 0===t||0===r.length?void 0:{...t,idat:r}},pv=({filter:e,row:t,previous:r,bytesPerPixel:n})=>{if(0!==e)for(let o=0;o=n?t[o-n]:0,i=r[o];switch(e){case 1:t[o]+=s;break;case 2:t[o]+=i;break;case 3:t[o]+=s+i>>1;break;case 4:{const e=o>=n?r[o-n]:0,a=s+i-e,c=Math.abs(a-s),l=Math.abs(a-i),u=Math.abs(a-e);t[o]+=c<=l&&c<=u?s:l<=u?i:e;break}default:throw new Error(`unknown PNG filter type ${e}`)}}},fv=({row:e,channels:t,columnOf:r,sums:n,counts:o})=>{const s=t<3;for(let i=0,a=0;i{for(let s=0;s0&&(e[c]=Math.round(n[i]/a),e[c+1]=Math.round(n[i+1]/a),e[c+2]=Math.round(n[i+2]/a),e[c+3]=Math.round(a/o[s]))}n.fill(0),o.fill(0)},gv={0:1,2:3,3:1,4:2,6:4},wv=[1,2,4,8,16],yv=[[0,0,8,8],[4,0,8,8],[0,4,4,8],[2,0,4,4],[0,2,2,4],[1,0,2,2],[0,1,1,2]],vv=async e=>{const t=bv(e);if(void 0===t)return;const r=Sv(t);let n=0;const o=ch.Readable.from(t.idat).pipe((0,oh.createInflate)());for await(const e of o)if(n+=e.length,n>=r)return void o.destroy();throw new Error(`PNG pixel data ends after ${n} of ${r} bytes`)},bv=e=>{let t;const r=[];let n=8;for(;n+12<=e.length;){const o=e.readUInt32BE(n),s=e.toString("ascii",n+4,n+8),i=e.subarray(n+8,n+8+o);if("IHDR"===s&&void 0===t&&13===i.length){const e=gv[i[9]];if(void 0===e||!wv.includes(i[8])||i[12]>1)return;t={width:i.readUInt32BE(0),height:i.readUInt32BE(4),bitsPerPixel:e*i[8],interlaced:1===i[12]}}else if("IDAT"===s)r.push(i);else if("IEND"===s)break;n+=o+12}return void 0===t||0===r.length?void 0:{...t,idat:r}},Sv=({width:e,height:t,bitsPerPixel:r,interlaced:n})=>{const o=(e,t)=>e<=0||t<=0?0:t*(1+Math.ceil(e*r/8));return n?yv.reduce(((r,[n,s,i,a])=>r+o(Math.ceil((e-n)/i),Math.ceil((t-s)/a))),0):o(e,t)};const kv=()=>{throw new Error("webp codec not registered: registerWebpCodec() must be called by a Node server before decoding/encoding webp")},_v=e=>e.length>=12&&"RIFF"===e.toString("ascii",0,4)&&"WEBP"===e.toString("ascii",8,12),Cv=e=>{if(!_v(e)||e.length<16)return;const t=e.toString("ascii",12,16);if("VP8 "===t){if(e.length<30||157!==e[23]||1!==e[24]||42!==e[25])return;return{width:16383&(e[26]|e[27]<<8),height:16383&(e[28]|e[29]<<8)}}if("VP8L"===t){if(e.length<25||47!==e[20])return;const t=(e[21]|e[22]<<8|e[23]<<16|e[24]<<24)>>>0;return{width:1+(16383&t),height:1+(t>>14&16383)}}if("VP8X"===t){if(e.length<30)return;return{width:1+(e[24]|e[25]<<8|e[26]<<16),height:1+(e[27]|e[28]<<8|e[29]<<16)}}},Ev=e=>kv().decode(e);async function xv(e){((e,t)=>{if(!Number.isSafeInteger(e)||e<1||e>t)throw new Error("pngByteBudgetBytes must be a positive integer at most MAX_IMAGE_SIZE_BYTES")})(e.budgetBytes,e.maxImageBytes);iv(e.data);return e.resizeWithoutBudget(e.data)}const Pv=[{width:1280,height:800},{width:1456,height:840}],Rv=e=>void 0!==e&&Pv.some((t=>t.width===e.width&&t.height===e.height)),Iv=1048576,Tv=e=>{const t=e.buffer;return t instanceof ArrayBuffer?new Uint8Array(t,e.byteOffset,e.byteLength):Uint8Array.from(e)};function Av(e,t,r=1024){if(e<1||t<1)return{width:e,height:t,needsResize:!1};const n=Math.max(e,t);if(n<=r)return{width:e,height:t,needsResize:!1};const o=Math.min(e,t);if(o<8)return{width:e,height:t,needsResize:!1};let s=r/n,i=Math.max(1,Math.round(e*s)),a=Math.max(1,Math.round(t*s));return(i<8||a<8)&&(s=8/o,i=Math.max(8,Math.round(e*s)),a=Math.max(8,Math.round(t*s))),{width:i,height:a,needsResize:i!==e||a!==t}}const $v=(e,t,r=1024)=>Av(e,t,r),Mv=(e,t)=>Rv({width:e,height:t})?{width:e,height:t,needsResize:!1}:Av(e,t),Dv=(e,t,r)=>{e.resize({w:t,h:r})};function Ov(e){if(void 0===e)throw new Error("image dimensions could not be read before decoding");const{width:t,height:r}=e;if(!(t*r<=178956970))throw new Error(`image dimensions ${t}x${r} exceed the 178956970 pixel decode limit`);if(!(Math.max(t,r)<=1e6))throw new Error(`image dimensions ${t}x${r} exceed the 1000000 pixel side limit`)}const Fv=(e,t)=>{switch(t){case"tiff":throw new Error("TIFF images are not supported; convert the image to PNG or JPEG");case"id3":throw new Error("images that start with an ID3 tag are not supported");case"jpeg":return;default:Ov(((e,t)=>{switch(t){case"png":return(e=>{let t,r=Qy.length;for(;r+16<=e.length;)"IHDR"===e.toString("ascii",r+4,r+8)&&(t=av(t,{width:e.readUInt32BE(r+8),height:e.readUInt32BE(r+12)})),r+=12+e.readUInt32BE(r);return t})(e);case"gif":return(e=>{if(e.length<13)return;const t={width:e.readUInt16LE(6),height:e.readUInt16LE(8)};let r=13+(128&(n=e[10])?3<<1+(7&n):0);for(var n;re.length<26?void 0:{width:e.readUInt32LE(18),height:Math.abs(e.readInt32LE(22))})(e)}})(e,t))}},Nv=e=>{const{width:t,height:r}=$v(e.width,e.height,1280);return{width:t,height:r}},Lv=async(e,t)=>{let{width:r,height:n}=e,o=await t({width:r,height:n});for(;o.length>Iv&&r>8&&n>8;)r=Math.max(8,Math.round(.8*r)),n=Math.max(8,Math.round(.8*n)),o=await t({width:r,height:n});return{data:Tv(o),mimeType:"image/webp",reencoded:!0}},jv=async(e,t)=>{const r=(await gw()).fromBitmap({data:Buffer.from(e.data),width:e.width,height:e.height});return Lv(t,(async e=>(r.bitmap.width===e.width&&r.bitmap.height===e.height||Dv(r,e.width,e.height),(e=>kv().encode(e))({data:r.bitmap.data,width:r.bitmap.width,height:r.bitmap.height}))))};let Uv;const Bv=async(e,t)=>{if(void 0!==t?.pngByteBudgetBytes){const{pngByteBudgetBytes:r,...n}=t,o=iv(e);return"image/png"===o?.mimeType&&Rv(o)&&await vv(e),xv({data:e,budgetBytes:r,maxImageBytes:Iv,fitImage:Mv,resizeWithoutBudget:e=>Bv(e,n)})}const r=await(async(e,t)=>{const r=_v(e);if(r&&!0===t?.preserveWebpDimensions)return;const n=r?void 0:iv(e),o=r?Cv(e):n;if(void 0===o||!Rv(o))return;const s=Uv;if(void 0!==n&&void 0!==s&&!Rv(await s.readOrientedDimensions(e)))return;const i="image/png"===n?.mimeType;if(i&&await vv(e),e.length<=Iv)return{data:Tv(e),mimeType:n?.mimeType??"image/webp"};const a=s?.resizeWebp;if(void 0!==a)return Lv(o,(t=>a({data:e,...t})))})(e,t);if(void 0!==r)return r;if(_v(e))return(async(e,t)=>{const r=Cv(e);if(!0===t?.preserveWebpDimensions&&void 0!==r)return{data:Tv(e),mimeType:"image/webp"};if(void 0!==r&&!$v(r.width,r.height,1280).needsResize&&e.length<=Iv)return{data:Tv(e),mimeType:"image/webp"};if("passthrough"===t?.webpWithoutCodec)return{data:Tv(e),mimeType:"image/webp"};Ov(r);const n=undefined;if(void 0!==n)return Lv(Nv(r),(t=>n({data:e,...t})));const o=await Ev(e);return jv(o,Nv(o))})(e,t);const n=iv(e);if(void 0!==n&&e.length<=Iv&&!$v(n.width,n.height).needsResize)return{data:Tv(e),mimeType:n.mimeType};const o=lv(e);void 0!==o&&Fv(e,o);const s=void 0===n?void 0:$v(n.width,n.height),i="image/png"===n?.mimeType&&!0===s?.needsResize?await dv({data:e,width:s.width,height:s.height}).catch((()=>{})):void 0;void 0===i&&"png"===o&&await vv(e);const a=await gw(),c=void 0===i?await a.read(e):a.fromBitmap(i),l=(e=>{switch(e.mime){case"image/png":default:return"image/png";case"image/bmp":return"image/bmp";case"image/tiff":return"image/tiff";case"image/x-ms-bmp":return"image/x-ms-bmp";case"image/gif":return"image/gif";case"image/jpeg":return"image/jpeg"}})(c),u=!0===t?.convertUnsupportedModelFormatsToPng&&"image/png"!==l&&"image/jpeg"!==l?"image/png":l,{width:d,height:h,needsResize:p}=$v(c.width,c.height);if(void 0===i&&!p&&e.length<=Iv&&u===l)return{data:Tv(e),mimeType:l};let f=d,m=h;p&&Dv(c,f,m);let g=await c.getBuffer(u);for(;g.length>Iv&&f>8&&m>8;)f=Math.max(8,Math.round(.8*f)),m=Math.max(8,Math.round(.8*m)),Dv(c,f,m),g=await c.getBuffer(u);return{data:Tv(g),mimeType:u,reencoded:!0}},Wv=async e=>{const t=Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=lv(t);let n;if(_v(t))return{kind:"unchecked"};if(void 0===r)return{kind:"unchecked"};{Fv(t,r);const e=await gw();n=async()=>("png"===r&&await vv(t),e.read(t))}try{return await n(),{kind:"decodes"}}catch(e){return{kind:"undecodable",reason:e instanceof Error?e.message:String(e)}}},Hv=BigInt(0),qv=BigInt(8),zv=BigInt(16),Gv=BigInt(65535);function Vv(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function Kv(e){const t=e.split(".");if(4!==t.length)return;let r=Hv;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<>zv&Gv)),t.push(Number(o.value&Gv))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function Zv(e){return Kv(e)??function(e){const t=Vv(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=Jv(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<7?void 0:{version:6,value:[...s,...new Array(8-a).fill(0),...i].reduce(((e,t)=>e<i)return!1;const a=BigInt(i-s);return o.value>>a==n.value>>a}(r,n);if(n.startsWith("*.")){const e=n.slice(2);return r===e||r.endsWith(`.${e}`)}return r===n}function Qv(e,t){const r=function(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch{return}}(e);return!!r&&function(e,t){return t.some((t=>Xv(e,t)))}(r.hostname,t)}var Yv=r("../constants/dist/commercial-cursor-hosts.js");new Set([1,2]);const eb="cursor/requiresConfirmation",tb="https://grok.com/connectors-oauth-exchange-code/",rb="https://x.com/i/connectors/oauth_callback",nb="https://chat.x.com/connectors/oauth_callback",ob="https://lite.x.com/i/connectors/oauth_callback",sb={provider:"google-workspace",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0,authorizationParams:{access_type:"offline",prompt:"select_account consent"}},ib={provider:"x-money",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,registeredAppRedirectUris:[tb,rb]},ab="x-cursor-auth";function cb(e,t){return function({serverUrl:e,restMcpHost:t}){if(void 0===e)return;let r;try{r=new URL(e)}catch{return}return"https:"===r.protocol&&r.hostname.toLowerCase()===t.toLowerCase()&&""===r.port?lb(e):void 0}({serverUrl:e,restMcpHost:t})}function lb(e){if(void 0===e)return;let t;try{t=new URL(e)}catch{return}const r=/^\/rest-mcp\/([^/]+)\/mcp\/?$/.exec(t.pathname);return r?.[1]}new Set(Object.values({notConnected:"scm_not_connected",tokenUnavailable:"scm_token_unavailable",tokenRejected:"scm_token_rejected",repoNotAccessible:"scm_repo_not_accessible",orgBlocked:"scm_org_blocked"})),new Set(Object.values({originNotEnabled:"origin_not_enabled",teamDisabled:"team_disabled",admissionRejected:"admission_rejected"}));const ub="https://mcp.shop.com",db={provider:"grok-connectors",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,scopes:["grok-plugins:access","offline_access"]},hb=new Map([["mcp.slack.com",{displayName:"Slack",baseScopes:["canvases:read","canvases:write","channels:history","channels:read","channels:write","chat:write","emoji:read","files:read","files:write","groups:history","groups:read","im:history","im:read","im:write","lists:read","lists:write","mpim:history","mpim:read","mpim:write","reactions:read","reactions:write","search:read.files","search:read.im","search:read.mpim","search:read.private","search:read.public","search:read.users","users:read","users:read.email"],stepUpScopes:{"groups:write":{action:"create private channels",tools:[{name:"slack_create_conversation",args:{is_private:!0}}]}},missingScopeAnswer:/\bmissing_scope\b/}]]),pb=new Map([["gmailmcp.googleapis.com",{...sb,scopes:["https://www.googleapis.com/auth/gmail.readonly","https://www.googleapis.com/auth/gmail.compose","https://www.googleapis.com/auth/gmail.modify"]}],["drivemcp.googleapis.com",{...sb,scopes:["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/drive.file"]}],["calendarmcp.googleapis.com",{...sb,scopes:["https://www.googleapis.com/auth/calendar.events","https://www.googleapis.com/auth/calendar.calendarlist.readonly","https://www.googleapis.com/auth/calendar.events.readonly","https://www.googleapis.com/auth/calendar.events.freebusy"]}],["docsmcp.googleapis.com",{...sb,scopes:["https://www.googleapis.com/auth/documents"]}],["sheetsmcp.googleapis.com",{...sb,scopes:["https://www.googleapis.com/auth/spreadsheets"]}],["slidesmcp.googleapis.com",{...sb,scopes:["https://www.googleapis.com/auth/presentations"]}],["bigquery.googleapis.com",{...sb,scopes:["https://www.googleapis.com/auth/bigquery"]}],["api.x.com",{provider:"x",clientRegistration:"static",unauthenticatedConnect:!1,rejectsCustomSchemeRedirects:!1,pinsScopesOverConfiguredScopes:!0}],["mcp.money-dev.x.com",ib],["mcp.money-staging.x.com",ib],["mcp.money.x.com",ib],["connectors-gateway.grok.gcp.mouseion.dev",db],["connectors-gateway.grok.com",db],["mcp.hubspot.com",{provider:"hubspot",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0}],["mcp.box.com",{provider:"box",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0}],["mcp.asana.com",{provider:"asana",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,configuredSecretStaysOnBackend:!0}],["mcp.strava.com",{provider:"strava",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,scopes:["read","activity:read_all","profile:read_all"]}],["mcp.quickbooks.intuit.com",{provider:"quickbooks-online",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,unauthenticatedEndpointBlocked:!0,backendOnlyTokenExchange:!0,scopes:["com.intuit.quickbooks.accounting","foundations.tools.businessreports.read","foundations.tools.bi-dashboard","foundations.tools.transactions.write","foundations.tools.companyprofile.read","foundations.tools.companyprofile.write","payroll.tools.tax.read","payroll.tools.employer.read","payroll.tools.employer.manage","payroll.tools.run.read","payroll.tools.run.manage","payroll.tools.employee.read","payroll.tools.employee.manage","worker-mgmt.tools.employee.read","worker-mgmt.tools.employee.manage","time-tracking.tools.timeentry.read","sales.tools.invoice.read","sales.tools.invoice","sales.tools.estimate.read","sales.tools.estimate","sales.tools.payment-link.read","sales.tools.payment-link","sales.tools.settings.read","sales.tools.settings","sales.tools.salesorder.read","sales.tools.salesorder","contact.tools.customer.read","contact.tools.customer","catalog.tools.item.read","catalog.tools.item","lending.tools.servicing.read","money-onboarding.tools.application"]}],["setup.shopify.com",{provider:"shopify",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!1}],["mcp.cloudflare.com",{provider:"cloudflare",clientRegistration:"dynamic",unauthenticatedConnect:!1,rejectsCustomSchemeRedirects:!1,scopes:["user:read","account:read","offline_access","d1.metadata_read","d1.read","d1.write","workers-scripts.read","workers-scripts.write","workers-routes.read","workers-routes.write","workers-tail.read","workers-kv-storage.metadata_read","workers-kv-storage.read","workers-kv-storage.write","workers-r2.metadata_read","workers-r2.read","workers-r2.write","workers-r2-bucket-item.read","workers-r2-bucket-item.write","workers-observability.read","workers-observability.write","dns.read","dns.write","zone.read","zone.write"],pinsScopesOverConfiguredScopes:!0,scopesPinGate:"mcp_cloudflare_api_oauth_scopes"}],["mcp.shop.com",{provider:"shop",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,backendOnlyTokenExchange:!0,scopes:["openid","personal_agent"],pinsScopesOverConfiguredScopes:!0,authorizationParams:{resource:ub}}],["api.elections.kalshi.com",{provider:"kalshi",clientRegistration:"dynamic",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0}],["mcp.squarespace.com",{provider:"squarespace",clientRegistration:"dynamic",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0}]]),fb=[".databricks.com",".azuredatabricks.net"];const mb=/^\/sncapps\/mcp-server\/mcp\/[^/]+$/,gb={provider:"databricks",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,scopes:["ai-gateway","offline_access"],pinsScopesOverConfiguredScopes:!0},wb={provider:"servicenow",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,unauthenticatedEndpointBlocked:!0,backendOnlyTokenExchange:!0,ownMcpJsonClientMayExchange:!0};function yb(e){if(void 0===e)return;let t;try{t=new URL(e)}catch{return}return function(e){return"https:"===e.protocol&&""===e.port&&""===e.username&&""===e.password&&function(e){const t=e.toLowerCase();return!(!/^[a-z0-9.-]+$/.test(t)||t.includes("..")||t.startsWith("."))&&fb.some((e=>t.endsWith(e)&&t.length>e.length))}(e.hostname)&&"/ai-gateway/mcp-services/system.ai.genie_one_mcp"===e.pathname.replace(/\/+$/,"")}(t)?gb:function(e){return"https:"===e.protocol&&""===e.port&&""===e.username&&""===e.password&&mb.test(e.pathname.replace(/\/+$/,""))}(t)?wb:(r=t.hostname,pb.get(r.toLowerCase()));var r}function vb(e){return e.endsWith("/")?e:`${e}/`}async function bb(e,t){if(void 0===t)return;const r=new URL(e),n=new URL(t);if(r.origin!==n.origin||!vb(r.pathname).startsWith(vb(n.pathname)))throw new Error(`Protected resource ${t} does not match expected ${r.href} (or origin)`);return n}const Sb=/^\/shops\/[A-Za-z0-9-]+\/mcp$/;function kb(e){if(void 0!==e)try{return new URL(e)}catch{return}}async function _b(e,t){if(void 0===t)return;const r=new URL(e),n=kb(t);if(void 0===n||n.origin!==r.origin||n.pathname!==r.pathname&&!Sb.test(n.pathname))throw new Error(`Protected resource ${t} does not match expected ${r.href} (or origin)`);return n}function Cb(e){const t=kb(e);return void 0===t?void 0:hb.get(t.hostname.toLowerCase())}const Eb=new Set([...pb].filter((([,e])=>"google-workspace"===e.provider)).map((([e])=>e))),xb="https://www.cursor.com/bot/mcp/oauth/callback",Pb={portal:"https://www.cursor.com/agents/mcp/oauth/callback",grokBotBounce:xb},Rb="tailnet_";new Set([`${Rb}waiting_for_approval`,`${Rb}tailnet_locked`,`${Rb}joining`]);const Ib="grokbot://mcp/oauth/callback",Tb="http://localhost:8787/callback",Ab="gb";function $b(e){const t=new URL(Tb);return t.port=String(e),t.toString()}function Mb(e){try{const t=new URL(e);if("http:"!==t.protocol)return!1;const r=t.hostname;return"localhost"===r||"127.0.0.1"===r||"[::1]"===r}catch{return!1}}function Db(e){const t=e.redirectUrl??Tb;if(!0!==e.loopbackIpv4||!Mb(t))return t;const r=new URL(t);return r.hostname="127.0.0.1",r.toString()}function Ob(e,t=Pb){const r=new Set,n=void 0!==e&&Mb(e);return e&&!n&&r.add(e),r.add(t.portal),e===Ib&&r.add(t.grokBotBounce),r.add(Tb),e&&n&&r.add(e),Array.from(r)}function Fb(e){var t;if(void 0!==e&&0!==e.length)try{const r=JSON.parse(e);if("object"==typeof(t=r)&&null!==t&&!Array.isArray(t))return r}catch{}}function Nb(e){if(void 0===e)return{};const t={};"string"==typeof e.title&&e.title.length>0&&(t.title=Jo(e.title,256));for(const r of["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"])"boolean"==typeof e[r]&&(t[r]=e[r]);return function(e){return!0===e?.[eb]}(e)&&(t[eb]=!0),0===Object.keys(t).length?{}:{annotationsJson:JSON.stringify(t)}}new Map([[Ab,Ib],["gw",tb],["gd",Tb],["xa",rb],["xc",nb],["xl",ob],...[18787,28787,31787].map((e=>[`gd${e}`,$b(e)]))]),new Map([[Ib,Ab],[xb,Ab],[tb,"gw"],[rb,"xa"],[nb,"xc"],[ob,"xl"]]),Db({loopbackIpv4:!0});var Lb=r("../mcp-core/dist/transport/mcp-url-utils.js");function jb(e){return e.trim().toLowerCase()}const Ub="";function Bb({mode:e,tools:t}){const r=(t??[]).map(jb).filter((e=>e.length>0)),n=void 0===e?void 0:jb(e);return"all"===n?{mode:"all"}:"reads"===n?{mode:"reads"}:r.length>0?{mode:"custom",tools:r}:{mode:"all"}}function Wb(e,t){switch(e.mode){case"all":return!0;case"custom":return function(e,t){const r=jb(e);return 0!==r.length&&r!==Ub&&t.some((e=>jb(e)===r))}(t.name,e.tools);case"reads":return void 0!==(r=t.annotations)&&!0!==r.destructiveHint&&!0===r.readOnlyHint;default:return e}var r}function Hb(e,t){switch(t.mode){case"all":return[`${e}:*`];case"custom":return t.tools.filter((e=>jb(e)!==Ub)).map((t=>`${e}:${t}`));case"reads":return[];default:return t}}const qb=new Set(["ash","bash","csh","dash","fish","ksh","powershell","pwsh","sh","tcsh","zsh","cmd"]);function zb(e){return e.trim().split(/\s+/).filter(Boolean)}function Gb(e){const t=function(e){const t=e.trim(),r=t[0];if('"'===r||"'"===r){const e=t.indexOf(r,1);if(-1!==e)return t.slice(0,e+1)}return zb(t)[0]}(e);if(!t)return!1;const r=t.replace(/^["']|["']$/g,"").replaceAll("\\","/").split("/"),n=(r[r.length-1]??"").replace(/\.exe$/i,"").toLowerCase();return qb.has(n)}function Vb(e,t){if(e.length>t.length)return!1;for(let r=0;r=t.tokenCount)continue;let a=!0;for(const t of e.tokens)if(!n.has(t)){a=!1;break}if(!a)continue;const c=Vb(e.tokens,t.tokens);void 0!==o?e.tokenCount>o.tokenCount?(o=e,s=c):e.tokenCount===o.tokenCount&&c&&!s&&(o=e,s=!0):(o=e,s=c)}void 0!==o&&(t.indentLevel=o.indentLevel+1,t.ancestorIds=[...o.ancestorIds,t.id])}const n=r.filter((e=>!r.some((t=>t.id!==e.id&&t.tokenCounte.id));return{options:r,defaultSelectedOptionIds:n}}(e),n=[...r.defaultSelectedOptionIds];if(!t||0===t.length)return{defaultSelectedOptionIds:n,hasClassifierSuggestions:!1};const o=[],s=new Set;for(const e of t){const t=r.options.find((t=>t.id===e));if(t){o.push(t.id),s.add(Jb(t.id));continue}const n=r.options.filter((t=>t.id.startsWith(`${e} `)||t.id===e)),i=r.options.filter((t=>e.startsWith(`${t.id} `)||e===t.id));if(i.length>0){const e=i.reduce(((e,t)=>e.id.length>t.id.length?e:t));o.push(e.id),s.add(Jb(e.id))}else if(n.length>0){const e=n.reduce(((e,t)=>e.id.length!s.has(Jb(e))));return{defaultSelectedOptionIds:[...new Set([...i,...o])],hasClassifierSuggestions:!0}}(e,t).defaultSelectedOptionIds}const Xb=["com.todesktop.230313mzl4w4u92","co.anysphere.cursor","com.anysphere.molten-glass"],Qb=["cursor","molten glass"];function Yb(e){return Xb.some((t=>e===t||e.startsWith(`${t}.`)))}const eS=[{bundleId:"com.apple.scripteditor2",name:"Script Editor"},{bundleId:"com.apple.automator",name:"Automator"},{bundleId:"com.apple.shortcuts",name:"Shortcuts"}],tS=[{bundleId:"com.apple.terminal",name:"Terminal"},{bundleId:"com.googlecode.iterm2",name:"iTerm",aliases:["iTerm2"]},{bundleId:"dev.warp.warp-stable",name:"Warp"},{bundleId:"dev.warp.warp-preview",name:"WarpPreview",aliases:["Warp Preview"]},{bundleId:"com.mitchellh.ghostty",name:"Ghostty"},{bundleId:"org.alacritty",name:"Alacritty"},{bundleId:"net.kovidgoyal.kitty",name:"kitty"},{bundleId:"com.github.wez.wezterm",name:"WezTerm"},{bundleId:"co.zeit.hyper",name:"Hyper"},{bundleId:"org.tabby",name:"Tabby"},...eS,{bundleId:Xb[0],name:"Cursor"}];function rS(e){const t=e.toLowerCase(),r=(0,s.basename)(e,".app").toLowerCase(),n=tS.find((({bundleId:e,name:n,aliases:o=[]})=>e===t||[n,...o].some((e=>{const n=e.toLowerCase();return n===t||n===r}))));return void 0!==n?{bundleId:n.bundleId,name:n.name}:Yb(t)?{bundleId:t,name:"Cursor"}:[t,r].some((e=>Qb.some((t=>e===t||e.startsWith(`${t} `)))))?{bundleId:Xb[0],name:"Cursor"}:void 0}const nS=new Set(["com.apple.systempreferences","com.apple.keychainaccess","com.apple.passwords","com.1password.1password","com.agilebits.onepassword7","com.bitwarden.desktop","com.lastpass.lastpass","org.keepassxc.keepassxc"]);function oS(e){return nS.has(e.toLowerCase())}function sS(e){return`app/${e}`}function iS(e){return"object"==typeof e&&null!==e}function aS(e){return lS.includes(e)}function cS(e){if(!iS(e))return;const{appArg:t,appSelectorArgs:r,capturesScreen:n}=e;if("boolean"==typeof n){if(void 0!==r){if(void 0!==t||!iS(r))return;const e={};for(const[t,n]of Object.entries(r)){if(!aS(t)||"string"!=typeof n||0===n.length)return;e[t]=n}if(0===Object.keys(e).length)return;return{appSelectorArgs:e,capturesScreen:n}}return void 0===t?{capturesScreen:n}:"string"==typeof t&&t.length>0?{appArg:t,capturesScreen:n}:void 0}}const lS=["pid","bundleId","path","appName"],uS=/^[+-]?\d+$/;var dS=r("../../node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/create.js");const hS=".cursor/worktrees",pS=".grok/build-desktop/worktrees",fS="win32"===process.platform||"darwin"===process.platform,mS=new Map;function gS(e,t){if(!(0,ts.BJ)(t,e))return;const r=(fS?(0,s.relative)(e.toLowerCase(),t.toLowerCase()):(0,s.relative)(e,t)).split(s.sep).filter(Boolean);return r.length>0?r:void 0}function wS(e,t){const r=gS(e,t);if(void 0!==r)return r;const n=function(e){if(mS.has(e))return mS.get(e);const t=[];let r,n=e;for(;;)try{const e=Ro.realpathSync.native(n);r=0===t.length?e:(0,s.join)(e,...t);break}catch(e){const r=_c(e);if("ENOENT"!==r&&"ENOTDIR"!==r)break;const o=(0,s.dirname)(n);if(o===n)break;t.unshift((0,s.basename)(n)),n=o}return mS.size>=64&&mS.clear(),mS.set(e,r),r}(e);var o,i;return void 0!==n&&(o=n,i=e,fS?o.toLowerCase()!==i.toLowerCase():o!==i)?gS(n,t):void 0}function yS(e){const t=e?.trim();return t&&".cursor"!==t?[".cursor",t]:[".cursor"]}function vS(e,t){const r=(0,o.homedir)();return yS(t?.dataFolderName).some((t=>void 0!==wS((0,s.join)(r,t,"projects"),e)))}function bS(e){const t=(0,o.homedir)();return[hS,pS].some((r=>void 0!==wS((0,s.join)(t,...r.split("/")),e)))}function SS(e,t,r){const n=function(e,t){const r=(0,o.homedir)();for(const n of yS(t?.dataFolderName)){const t=wS((0,s.join)(r,n,"projects"),e);if(void 0!==t&&t.length>=2)return t[1]}}(e,r);return void 0!==n&&(fS?t.some((e=>e.toLowerCase()===n.toLowerCase())):t.includes(n))}function kS(e,t,r){const n=wS(e,t);if(void 0===n)return!1;const o=n[0];return fS?r.some((e=>e.toLowerCase()===o.toLowerCase())):r.includes(o)}const _S=/[\s"'`=/\\:;()[\]{},&|<>]/,CS="win32"===process.platform||"darwin"===process.platform;async function ES(e,t,r,n){const o=AS(await TS((0,s.join)(e,"gitdir")),"");if(void 0===o)return;const i=(0,s.resolve)(e,o);if(".git"!==(0,s.basename)(i)||(0,Gs.$f)(i))return;const a=(0,s.dirname)(i);if(r&&bS(a))return;const c=await $S(i);if(void 0===c)return;const l=(0,s.dirname)(c);if(r&&bS(l))return;if(void 0!==n&&(u=DS(a,l)?[l]:[a,l],d=n.command,!(void 0!==(h=n.realWorkingDirectory)&&u.some((e=>(0,ts.BJ)(h,e)))||void 0!==d&&u.some((e=>{const t=(0,s.basename)(e);return t.length>0&&function(e,t){const r=CS?e.toLowerCase():e,n=CS?t.toLowerCase():t;let o=0;for(;;){const e=r.indexOf(n,o);if(-1===e)return!1;const t=0===e||_S.test(r[e-1]),s=e+n.length,i=s===r.length||_S.test(r[s]);if(t&&i)return!0;o=e+1}}(d,t)})))))return;var u,d,h;const p=await IS(i,c);return void 0!==p&&DS(p.commonDir,t)?l:void 0}async function xS(e,t){const r=await(0,xo.readdir)(e).catch(MS);return void 0===r?[]:r.sort().slice(0,t)}function PS(e,t){return t.some((t=>(0,ts.BJ)(t,e)))}async function RS(e){for(let t=e;;t=(0,s.dirname)(t)){if((0,Gs.$f)(t))return;const e=(0,s.join)(t,".git"),r=await(0,xo.lstat)(e).catch(MS);if(r?.isFile())return(await IS(e))?.commonDir;if(r?.isDirectory())return e;if(void 0!==r||(0,s.dirname)(t)===t)return}}async function IS(e,t){const r=AS(await TS(e),"gitdir: ");if(void 0===r)return;const n=await $S((0,s.resolve)((0,s.dirname)(e),r));if(void 0===n||"worktrees"!==(0,s.basename)((0,s.dirname)(n)))return;const o=(0,s.dirname)((0,s.dirname)(n));if(".git"!==(0,s.basename)(o))return;const i=AS(await TS((0,s.join)(n,"commondir")),"");if(void 0===i)return;const a=await $S((0,s.resolve)(n,i));if(void 0===a||!DS(a,o))return;const c=AS(await TS((0,s.join)(n,"gitdir")),"");if(void 0===c)return;const[l,u]=await Promise.all([$S((0,s.resolve)(n,c)),t??$S(e)]);return void 0!==l&&void 0!==u&&DS(l,u)?{commonDir:o,realDotGit:u}:void 0}async function TS(e){const t=await(0,xo.lstat)(e).catch(MS);if(void 0!==t&&t.isFile()&&!(t.size>4096))return(0,xo.readFile)(e,"utf8").catch(MS)}function AS(e,t){const r=e?.split("\n",1)[0]?.replace(/\r$/,"");if(void 0===r||!r.startsWith(t))return;const n=r.slice(t.length);return n.length>0&&!n.includes("\0")?n:void 0}async function $S(e){if(!(0,Gs.$f)(e))return(0,xo.realpath)(e).catch(MS)}function MS(e){const t=_c(e);if(void 0===t||t.startsWith("ERR_"))throw e}function DS(e,t){return CS?e.toLowerCase()===t.toLowerCase():e===t}function OS(e,t,r){return{resolvedPath:e,originalPath:t,resolution:r}}function FS(e){const t=_c(e);switch(t){case"ENOENT":return{status:"newFile"};case"EACCES":case"EPERM":return{status:"permissionDenied",errno:t};case"ELOOP":return{status:"symlinkLoop",errno:t};default:return{status:"unknownError",errno:t??"UNKNOWN",message:Cc(e)}}}async function NS(e,t){const r=(0,ts.o1)(e,t);try{return OS(await(0,xo.realpath)(r),r,{status:"resolved"})}catch(e){if("ENOENT"!==_c(e))return OS(r,r,FS(e));try{if((await(0,xo.lstat)(r)).isSymbolicLink()){let e=null;try{e=await(0,xo.readlink)(r)}catch{}return OS(r,r,{status:"danglingSymlink",symlinkTarget:e})}try{return OS(await(0,xo.realpath)(r),r,{status:"resolved"})}catch(e){if("ENOENT"!==_c(e))return OS(r,r,FS(e))}return OS(r,r,{status:"unknownError",errno:"ENOENT",message:"realpath returned ENOENT but lstat found a non-symlink entry"})}catch(e){return"ENOENT"===_c(e)?async function(e){let t=(0,s.dirname)(e);const r=[(0,s.basename)(e)];for(;(0,s.dirname)(t)!==t;){try{const n=await(0,xo.realpath)(t);return OS((0,s.join)(n,...r),e,{status:"newFile"})}catch(t){if("ENOENT"!==_c(t))return OS(e,e,FS(t))}r.unshift((0,s.basename)(t)),t=(0,s.dirname)(t)}return OS(e,e,{status:"newFile"})}(r):OS(r,r,FS(e))}}}function LS(e){return"resolved"===e.status||"newFile"===e.status}function jS(e,t){switch(t.status){case"resolved":case"newFile":return"";case"danglingSymlink":return`Write blocked: \`${e}\` is a dangling symlink${t.symlinkTarget?` (target: ${t.symlinkTarget})`:""}. Cannot verify it does not point to a protected file.`;case"permissionDenied":return`Write blocked: cannot verify \`${e}\` -- permission denied resolving symlinks (${t.errno}).`;case"symlinkLoop":return`Write blocked: \`${e}\` has a symlink loop (${t.errno}). Cannot verify target.`;case"unknownError":return`Write blocked: cannot verify \`${e}\` -- ${t.errno}: ${t.message}.`;default:return`Write blocked: unknown resolution status for \`${e}\`.`}}function US({realAbsolutePath:e,setting:t,resolvedWorkspaceRoots:r,resolvedAllowFolders:n,resolvedAllowGlobs:o}){return!("workspace"!==t.boundary||BS(e,r)||BS(e,n)||HS(e,t.allowPaths)||HS(e,o))}function BS(e,t){return t.some((t=>(0,ts.BJ)(e,t)))}function WS(e){return e.flatMap((e=>{const t=(0,ts.jl)(e.trim());return!t.includes("*")&&(0,s.isAbsolute)(t)?[(0,s.resolve)(t)]:[]}))}function HS(e,t){const r="win32"===process.platform?ts.oL:e=>e,n=r(e);return t.some((e=>{const t=(0,ts.jl)(e.trim());return!(!t.includes("*")&&(0,s.isAbsolute)(t))&&(0,ws.T)(r(t),n)}))}const qS={caffeinate:{flags:["-d","-i","-m","-s","-u"],valueOptions:["-t","-w"]},command:{flags:["-p"],valueOptions:[],lookupFlags:["-v","-V"]},env:{flags:["-","-i","-0","-v","--ignore-environment","--null","--debug"],valueOptions:["-u","-C","--unset","--chdir"],assignments:!0,directoryOptions:["-C","--chdir"]},nice:{flags:[],valueOptions:["-n","--adjustment"],numericOption:!0},nohup:{flags:[],valueOptions:[]},stdbuf:{flags:[],valueOptions:["-i","-o","-e","--input","--output","--error"]},time:{flags:["-p"],valueOptions:[]},timeout:{flags:["-f","-p","-v","--foreground","--preserve-status","--verbose"],valueOptions:["-k","-s","--kill-after","--signal"],operands:1},xargs:{flags:["-0","-o","-p","-r","-t","-x","--null","--open-tty","--interactive","--no-run-if-empty","--verbose","--exit","--show-limits"],valueOptions:["-a","-d","-E","-I","-J","-L","-n","-P","-R","-S","-s","--arg-file","--delimiter","--max-args","--max-procs","--max-chars","--process-slot-var"],attachedValueOptions:["-e","-i","-l","--eof","--replace","--max-lines"],readsArguments:!0}};function zS(e){const t=[];let r=!0,n=!1,o=e;for(;;){const e=qS[s.posix.basename(o.name)];if(void 0===e)return{command:o,wrapperForms:t,allowlistable:r,readsArguments:n};const i=GS(o.args,e);if("unreadable"===i)return{command:o,wrapperForms:t,allowlistable:!1,readsArguments:n};if("none"===i)return{command:o,wrapperForms:t,allowlistable:r,readsArguments:n};const[a,...c]=o.args.slice(i);if(void 0===a||!XS(a))return{command:o,wrapperForms:t,allowlistable:!1,readsArguments:n};(o.name.includes("/")||o.args.slice(0,i).some((t=>VS(t,e)||KS(t.value,e))))&&(r=!1),n||=!0===e.readsArguments,t.push(o.fullText.trim()),o=new fe.Pv({name:a.value,args:c,fullText:[a.value,...c.map((e=>e.value))].join(" ")})}}function GS(e,t){let r=0;for(;rt.startsWith("--")?e===t||e.startsWith(`${t}=`):/^-[^-]/.test(e)&&e.includes(t.slice(1))))}function JS(e,t,r){const n=e=>!0===r.attachedValueOptions?.includes(e);if(r.flags.includes(e)||n(e))return 1;if(e.startsWith("--")){const o=e.indexOf("=");if(-1!==o){const t=e.slice(0,o);return r.valueOptions.includes(t)||n(t)?1:void 0}if(!r.valueOptions.includes(e))return;return void 0===t?void 0:2}for(let o=1;o{const t=await NS(e);return LS(t.resolution)?t.resolvedPath:(0,ts.o1)(e)})))}function pk(e,t,r){return`${e} blocked: cannot verify ${t} \`${r}\` while resolving symlinks. This can happen when access is denied or the path contains a symlink loop.`}function fk(e){return[...new Set(e)]}function mk(){return{fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}}function gk({basePath:e,targetPath:t,pathModule:r}){const n=r.resolve(e),o=r.resolve(t),s=r.relative(n,o);return""===s||".."!==s&&!s.startsWith(`..${r.sep}`)&&!r.isAbsolute(s)}function wk(e){return">"===e||">>"===e||">|"===e||"&>"===e||"&>>"===e}function yk(e){return"<"!==e.operator&&"<&"!==e.operator}function vk(e){if(void 0===e||e.trim()!==e)return;const t=Number(e);return Number.isInteger(t)&&t>=0?t:void 0}function bk(e){return"<<"===e.operator&&"heredoc_redirect"===e.targetNodeType&&1===e.destinationFds.length&&0===Number(e.destinationFds[0])&&void 0!==e.targetText}function Sk(e,t){return!(/^=|[~*?[{(#^`]/.test(e)||"\\"!==t.sep&&e.includes("\\"))}function kk(e){return"word"===e.type||"number"===e.type?Sk(e.value,i)?e.value:void 0:"raw_string"===e.type||"string"===e.type&&!/[$`\\]/.test(e.value)?e.value.slice(1,-1):void 0}function _k({command:e,readsArguments:t}){if(!function(e){const t=e.replace(/["']/g,"");return[t,t.replace(/\\/g,"")].some((e=>/^tee(?:-object)?(?:\.exe)?$/i.test(e.slice(Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"))+1))))}(e.name))return[];const r=e.args.map(kk);return t?[...r,void 0]:r}const Ck=new Set(["cd","chdir","pushd"]),Ek=new Set(["popd","eval","source",".","trap","set-location","sl","push-location","pop-location"]);function xk(e){const t=e.replace(/["'\\]/g,"");return t.slice(t.lastIndexOf("/")+1).toLowerCase()}function Pk(e,t){return new fe.Pv({name:e,args:t,fullText:[e,...t.map((e=>e.value))].join(" ")})}function Rk(e){let t=e;for(;;){const e=xk(t.name);if("command"===e){const e=Pk("command",t.args),r=zS(e).command;if(r!==e){t=r;continue}const n=t.args[0]?.value;return void 0===n||"-v"===n||"-V"===n?t:"unreadable"}if("builtin"!==e)return t;const r="--"===t.args[0]?.value?t.args.slice(1):t.args,[n,...o]=r;if(void 0===n)return t;const s=kk(n);if(void 0===s||s.startsWith("-"))return"unreadable";t=Pk(s,o)}}function Ik(e,t){return!(!t.isAbsolute(e)||"/"!==t.sep&&/^[\\/]$/.test(t.parse(e).root))}async function Tk({parsingResult:e,workingDirectory:t,resolvePathForPermissions:r,pathModule:n}){const o=[t];for(const t of e.executableCommands.map(zS)){const e=Rk(t.command);if("unreadable"===e)return;const i=xk(e.name),a=e.args;if(Ek.has(i)||/^cd\.\./.test(s=i)||/^[a-z]:$/.test(s))return;if(!Ck.has(i))continue;const c=1===a.length&&void 0!==a[0]?kk(a[0]):void 0;if(void 0===c||!Ik(c,n))return;const l=await r(c);if(!LS(l.resolution))return;o.push(l.resolvedPath)}var s;return o}async function Ak({targetText:e,workingDirectory:t,workingDirectories:r,...n}){const o=Ik(e,n.pathModule)?[t]:r;if(void 0===o)return;let s;for(const t of o)if(s=await $k({...n,targetText:e,workingDirectory:t}),void 0===s)return;return s}async function $k({targetText:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:o,pathModule:s,tempPathOptions:i}){if(""!==s.parse(e).root&&!s.isAbsolute(e))return;const a=await o(e,t);if(!LS(a.resolution))return;const c=[];for(const e of r){const t=await o(e);LS(t.resolution)&&c.push(t.resolvedPath)}return await async function({targetPath:e,rootPaths:t,pathModule:r}){if(e.split(r.sep).some((e=>".git"===e.toLowerCase())))return!0;for(const r of t)if(await(0,No.OK)(e,r).catch((()=>!0)))return!0;return!1}({targetPath:a.resolvedPath,rootPaths:c,pathModule:s})?void 0:c.some((e=>gk({basePath:e,targetPath:a.resolvedPath,pathModule:s})))?"workspace-file":n&&!(0,No.dA)(a.originalPath)&&zk(a.resolvedPath,i)?"tmp-file":void 0}async function Mk({parsingResult:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n}){const s=await Tk({parsingResult:e,workingDirectory:t,resolvePathForPermissions:NS,pathModule:i});for(const a of e.executableCommands.map(zS).flatMap(_k))if("/dev/null"!==a&&(void 0===a||!await Ak({targetText:a,workingDirectory:t,workingDirectories:s,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:NS,pathModule:i,tempPathOptions:{platform:process.platform,env:process.env,pathModule:i,homeDirectory:(0,o.homedir)()}})))return!1;return!0}function Dk(e){return fk(e.map((e=>e.trim())).filter(Boolean))}function Ok(e){const t=e.name.trim();if(!t)return[];const r=e.arguments.map((e=>e.trim())).filter(Boolean),n=r.length>0?`${t} ${r.join(" ")}`:t,o=e.subcommandTokens.map((e=>e.trim())).filter(Boolean);if(0===o.length)return[n];const s=`${t} ${o.join(" ")}`;return s===n?[n]:[n,s]}function Fk(e,t){const r=t.trim();return!!r&&e.some((e=>e===r||e.startsWith(`${r} `)))}function Nk(e){const t=e.name.trim(),r=e.arguments.map((e=>e.trim())).filter(Boolean).map((e=>new fe.r6({type:"word",value:e})));return new fe.Pv({name:t,args:r,fullText:[t,...r.map((e=>e.value))].join(" ").trim()})}function Lk(e,t={}){return{type:e,...t}}function jk(e){return void 0!==e&&("deny"===e.default||void 0!==e.allow&&e.allow.length>0||void 0!==e.deny&&e.deny.length>0)}function Uk(...e){return e.filter((e=>void 0!==e)).join(" • ")}function Bk(e){const t=[];for(const r of e){const e=r.match(/^\s*Read\s*\((.*)\)\s*$/);e&&t.push((e[1]??"").trim())}return t}function Wk(e,t){if("workspace"===e&&void 0!==t)return t}const Hk={workspace:0,system:1};function qk(e){const t=e.match(/^\s*(Shell|Bash)\s*\((.*)\)\s*$/);if(!t)return null;const r=t[1];if("Shell"!==r&&"Bash"!==r)return null;const n=t[2]?.trim()??"",o=n.indexOf(":");return-1!==o?{shellType:r,fullPattern:n,commandPattern:n.slice(0,o).trim(),argsPattern:n.slice(o+1).trim()}:{shellType:r,fullPattern:n,commandPattern:n,argsPattern:null}}function zk(e,{platform:t,env:r,pathModule:n,homeDirectory:o}){if((0,No.dA)(e))return!1;if("win32"===t){const t=r.TEMP??r.TMP;if(t){const r=n.normalize(t).toLowerCase(),o=n.normalize(e).toLowerCase(),s=r.endsWith(n.sep)?r:r+n.sep;return o===r||o.startsWith(s)}return!1}const s=e=>{const r=n.normalize(e);return"darwin"!==t?r:"/tmp"===r||r.startsWith("/tmp/")||"/var"===r||r.startsWith("/var/")?`/private${r}`:r},i=s(e);return(void 0===o||!gk({basePath:s(o),targetPath:i,pathModule:n}))&&("darwin"===t?["/private/tmp/","/private/var/folders/"].some((e=>i.startsWith(e))):["/tmp/","/private/tmp/","/var/folders/","/private/var/folders/","/var/tmp/"].some((e=>i.startsWith(e))))}function Gk(e,t){if("insecure_none"===t.type)return!0;if("insecure_none"===e.type)return!1;const r=(0,No.$b)(e.networkPolicy),n=(0,No.$b)(t.networkPolicy);if(r&&!n)return!1;const o=(0,No._B)(e.networkPolicy),s=(0,No._B)(t.networkPolicy);if(o&&n&&!s)return!1;if("workspace_readonly"===e.type&&"workspace_readwrite"===t.type)return!0;if("workspace_readwrite"===e.type&&"workspace_readonly"===t.type)return!1;const i=e.readBoundary??"system",a=t.readBoundary??"system";return!(Hk[i]>Hk[a])}function Vk(e){return{wrapperForms:e.flatMap((e=>e.wrapperForms)),allowlistable:e.every((e=>e.allowlistable)),readsArguments:e.some((e=>e.readsArguments))}}function Kk(e){return[...e.wrapperForms,e.command.fullText.trim()].filter(Boolean)}class Jk{constructor(e,t,r,n,o){this.command=e,this.requestedPolicy=t,this.wrapperForms=o?.wrapperForms??[],this.allowlistable=o?.allowlistable??!0,this.readsArguments=o?.readsArguments??!1;const s=void 0!==r&&Gk(t,r);this.state=s?"preapproved":"approvable";const i=[e.fullText.trim()].filter(Boolean);this.matchForms=n&&n.length>0?[...n]:i}approveWithPolicy(e){"approvable"!==this.state&&"preapproved"!==this.state||!Gk(this.requestedPolicy,e)||(this.state="allowlisted")}deny(){this.state="denied"}isRunnable(){return"preapproved"===this.state||"allowlisted"===this.state}}function Zk(e){return e?.type??"undefined"}const Xk=["skills","skills-cursor","rules","plugins"],Qk=["assets","agent-notes","agent-tools","swarm-agents"];async function Yk(e,t,r){return e.shouldBlockFileRead?.(t,r)??e.shouldBlockRead(t,r)}function e_(e){const t=e.lastIndexOf("::mcpScope:");return-1===t?e:e.slice(0,t)}function t_({server:e,tool:t}){const r=e=>e.length>0&&e.length<=256&&!/[:*]/.test(e),n=e.trim().toLowerCase(),o=t.trim().toLowerCase();return r(n)&&r(o)?`${n}:${o}`:void 0}const r_=/^\s*Read\s*\((.*)\)\s*$/,n_=/^\s*Write\s*\((.*)\)\s*$/;class o_{constructor(e,t,r,n,i,a=!1,c){this.ignoreService=e,this.pendingDecisionStore=t,this.permissionsProvider=r,this.teamSettingsService=n,this.adminNetworkControlsEnabled=a,this.computerUseAppsAllowedForSession=[],this.rootDirectories=Array.isArray(i)?i:[i??process.cwd()],this.projectDir=c?.projectDir,this.perUserSandboxConfigPath=c?.perUserSandboxConfigPath??(0,s.join)((0,o.homedir)(),".cursor","sandbox.json"),this.mcpAllowlistLog=c?.mcpAllowlistLog,this.computerUse=c?.computerUse,this.computerUseAdminPolicy=c?.computerUseAdminPolicy,this.enforceMcpAdminToolLimits=c?.enforceMcpAdminToolLimits,this.onMcpAdminToolLimitCheck=c?.onMcpAdminToolLimitCheck}async shouldBlockRead(e,t={}){return this.shouldBlockReadInternal(e,t,!1)}async shouldBlockFileRead(e,t={}){return this.shouldBlockReadInternal(e,t,!0)}async getFileReadBoundaryBlocker(){const{perms:e,setting:t}=await this.readControlSetting(),r=e.deny.filter((e=>this.isPathEntry("Read",e))),n="workspace"===t.boundary&&"unrestricted"!==e.approvalMode;if(!n&&0===r.length)return;const[o,s,i]=n?await Promise.all([this.resolveWorkspaceReadRoots(e.userSandboxDataFolderName),this.resolvedReadAllowFolders(t.allowPaths),this.resolvedReadAllowGlobs(t.allowPaths)]):[[],[],[]],a=r.map((e=>this.compileReadDenyMatcher(e))),c=e=>a.some((t=>t(e)));return async(e,r)=>c(e)||c(r)||n&&US({realAbsolutePath:r,setting:t,resolvedWorkspaceRoots:o,resolvedAllowFolders:s,resolvedAllowGlobs:i})}async readControlSetting(){const e=await this.getPermissions(),{enabled:t,...r}=await this.adminReadControls(e);return{perms:e,setting:function(e){if(!e.enabled)return{boundary:"system",allowPaths:[],enforcedByAdmin:!1};const t="workspace"===e.admin.boundary,r=t||"workspace"===e.local.boundary?"workspace":"system",n=t?e.admin.allowPaths:[];return{boundary:r,allowPaths:t&&!1===e.admin.allowUserOverride?[...n]:[...new Set([...n,...e.local.allowPaths])],enforcedByAdmin:t}}({enabled:t,admin:r,local:{boundary:e.readBoundary,allowPaths:Bk(e.allow)}})}}async adminReadControls(e){const t=e.teamAdminPolicy,r=this.teamSettingsService.isReadControlEnabled?.()??!0;if(void 0!==t&&"unavailable"!==t){const e=await r;return"workspace"!==t.readBoundary?{enabled:e,boundary:void 0,allowPaths:[],allowUserOverride:void 0}:{enabled:e,boundary:"workspace",allowPaths:t.additionalReadPaths??[],allowUserOverride:t.allowUserOverrideReadPaths}}const[n,o]=await Promise.all([r,this.teamSettingsService.getSandboxingControls()]);return{enabled:n,boundary:o.readBoundary,allowPaths:o.readAllowlistPaths??[],allowUserOverride:o.allowUserOverrideReadAllowlist}}resolvedReadAllowFolders(e){return hk([...WS(e),...(0,No.r5)()])}async resolvedReadAllowGlobs(e){const t=function(e){return e.flatMap((e=>{const t=(0,ts.jl)(e.trim()),r=t.indexOf("*");if(r<0||!(0,s.isAbsolute)(t))return[];const n="win32"===process.platform?Math.max(t.lastIndexOf("/",r),t.lastIndexOf("\\",r)):t.lastIndexOf("/",r);return n>=(0,s.parse)(t).root.length?[{folder:t.slice(0,n),rest:t.slice(n)}]:[]}))}(e),r=await hk(t.map((({folder:e})=>e)));return t.map((({rest:e},t)=>function(e,t,r={parse:s.parse}){return r.parse(e).root===e&&/[\\/]$/.test(e)?`${e}${t.slice(1)}`:`${e}${t}`}(r[t],e)))}async resolveWorkspaceReadRoots(e){const t=(0,s.join)((0,o.homedir)(),void 0!==e&&e.length>0?e:".cursor"),r=[...this.rootDirectories.map((e=>(0,s.join)(t,"projects",(0,_o.r_)(e)))),...Xk.map((e=>(0,s.join)(t,e)))],n=this.rootDirectories.flatMap((e=>(0,No.W1)(e)??[]));return hk([...this.rootDirectories,...r,...n,...void 0===this.projectDir?[]:[this.projectDir]])}async shouldBlockReadInternal(e,{cursorIgnoreChecked:t=!1},r){const n=(0,ts.o1)(e),o=await xc(n);if(null===o)return{type:"unsafeResolution",message:pk("Read","path",n)};if(await this.ignoreService.isRepoBlocked(o))return{type:"adminBlock",source:"Team repo blocklist"};if(await this.isPathExplicitlyDenied("Read",n))return{type:"permissionsConfig"};if(!t&&!bS(o)&&!vS(o,{dataFolderName:(await this.getPermissions()).userSandboxDataFolderName})&&await this.ignoreService.isCursorIgnored(o))return{type:"cursorIgnore"};if(r){const e=await this.shouldBlockReadForBoundary(o);if(e)return e}return!1}async shouldBlockReadForBoundary(e){const{perms:t,setting:r}=await this.readControlSetting();if("workspace"!==r.boundary||"unrestricted"===t.approvalMode)return!1;const n=await this.resolveWorkspaceReadRoots(t.userSandboxDataFolderName);if(BS(e,n))return!1;const[o,s]=await Promise.all([this.resolvedReadAllowFolders(r.allowPaths),this.resolvedReadAllowGlobs(r.allowPaths)]);return!!US({realAbsolutePath:e,setting:r,resolvedWorkspaceRoots:n,resolvedAllowFolders:o,resolvedAllowGlobs:s})&&{type:"needsApproval",approvalReason:r.enforcedByAdmin?"This reads a file outside your workspace and requires approval under your team's read policy.":"This reads a file outside your workspace.",approvalDetails:{type:"fileRead",path:e}}}async isProjectDirInternalPath(e,t){if(void 0===this.projectDir)return!1;const r=await NS(this.projectDir);return!!LS(r.resolution)&&kS(r.resolvedPath,e,t)}async isFreelyWritableOutsideWorkspace(e,t){return function(e){return zk(e,{platform:process.platform,env:process.env,pathModule:i,homeDirectory:(0,o.homedir)()})}(e)||SS(e,Qk,{dataFolderName:t})||await this.isProjectDirInternalPath(e,Qk)}async shouldBlockWrite(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{tk(n,(0,D.VI)(e.withName("InteractivePermissionsService.shouldBlockWrite")),!1).ctx;const i=await NS(t);if(!LS(i.resolution))return{type:"unsafeResolution",message:jS(i.originalPath,i.resolution)};const a=i.resolvedPath,c=a;if(await this.ignoreService.isRepoBlocked(c))return{type:"adminBlock",source:"Team repo blocklist"};if(await this.isPathExplicitlyDenied("Write",a))return{type:"permissionsConfig"};const l=i.originalPath.split(s.sep).pop()?.toLowerCase()??"",u=a.split(s.sep).pop()?.toLowerCase()??"";if(".cursorignore"===l||".cursorignore"===u)return{type:"permissionsConfig"};if((0,No.dA)(i.originalPath)||(0,No.dA)(a))return{type:"permissionsConfig"};const d=await this.getPermissions();if(!bS(c)&&!vS(c,{dataFolderName:d.userSandboxDataFolderName})&&await this.ignoreService.isCursorIgnored(c))return{type:"cursorIgnore"};if("workspace_readonly"===d.userConfiguredPolicy.type)return{type:"permissionsConfig",isReadonly:!0};if(await this.isPathExplicitlyAllowed("Write",a))return!1;if("unrestricted"===d.approvalMode)return!1;const h=async()=>{let e,t,n="";try{n=await Bi(a),e=!1}catch{e=!0}if(e)t=r;else{const e=e=>e.endsWith("\n")?e:`${e}\n`,{hunks:o}=(0,dS.YB)("a","b",e(n),e(r),"","",{context:2});t=o.map((e=>e.lines.map((e=>e.length>0?`${e[0]} ${e.slice(1)}`:e)).join("\n"))).join("\n...\n")}return{isNewFile:e,diffString:t}};let p;const f=[];for(const e of this.rootDirectories){const t=await NS(e);if(LS(t.resolution)){if((0,ts.BJ)(a,t.resolvedPath)){p=t.resolvedPath;break}f.push(t.resolvedPath)}}const m=void 0===p?await async function(e,t,r={}){if(0===t.length)return;let n;for(let o=(0,s.dirname)(e);;o=(0,s.dirname)(o)){if((0,Gs.$f)(o))return;const e=(0,s.join)(o,".git"),i=await(0,xo.lstat)(e).catch(MS);if(i?.isFile()){const s=await IS(e);if(void 0!==s){const{commonDir:e}=s;if(PS(o,t))return;if(t.some((t=>(0,ts.BJ)(e,t))))return{root:o,commonDir:e};if(!await(r.isUntrustedExternalGitDir?.(e))&&(await(n??=Promise.all(t.map((e=>RS(e)))),n)).some((t=>void 0!==t&&DS(t,e))))return{root:o,commonDir:e}}}if((0,s.dirname)(o)===o)return}}(a,f,{isUntrustedExternalGitDir:e=>this.isFreelyWritableOutsideWorkspace(e,d.userSandboxDataFolderName)}):void 0;let g=!1;const w=p??m?.root;if(void 0!==w){const e=(0,s.relative)(w,a),t=e.split(s.sep).map((e=>"win32"===process.platform&&e.includes(":")?e.split(":")[0]:e));if(g=function(e){const t=e.replace(/\\/g,"/");return/(^|\/)\.cursor\/debug(?:-[a-zA-Z0-9-]+)?\.log$/i.test(t)}(e),!g){const e=await this.checkCursorFileProtection(t);if(e)return e}if("win32"===process.platform&&t.some((e=>e.includes("~")))){const{isNewFile:e,diffString:r}=await h();return{type:"needsApproval",approvalReason:`Protected config file: ${t[t.length-1]??""}`,approvalDetails:{type:"fileEdit",isNewFile:e,diffString:r,blockReason:"protectedConfig"}}}if(await(0,No.OK)(a,w)){const e=t[t.length-1]?.toLowerCase()??"",{isNewFile:r,diffString:n}=await h();return{type:"needsApproval",approvalReason:`Protected config file: ${e}`,approvalDetails:{type:"fileEdit",isNewFile:r,diffString:n,blockReason:"protectedConfig"}}}}if(void 0===p&&(void 0===m||"workspace"===(await this.readControlSetting()).setting.boundary)){if(await this.isFreelyWritableOutsideWorkspace(a,d.userSandboxDataFolderName))return!1;const e=`${(0,o.homedir)()}${s.sep}.cursor${s.sep}`;if(a.startsWith(e)){const e=a.split(s.sep).pop()?.toLowerCase()??"";if(e.endsWith(".md")||e.endsWith(".mdc")||".cursorrules"===e)return!1}const{isNewFile:t,diffString:r}=await h();return{type:"needsApproval",approvalReason:"Out of workspace",approvalDetails:{type:"fileEdit",isNewFile:t,diffString:r,blockReason:"outOfWorkspace"}}}if(g)return!1;if(!0===d.promptWorkspaceWrites){const{isNewFile:e,diffString:t}=await h();return{type:"needsApproval",approvalReason:"Workspace write",approvalDetails:{type:"fileEdit",isNewFile:e,diffString:t,blockReason:"workspaceWrite"}}}return!1}catch(e){n.error=e,n.hasError=!0}finally{rk(n)}}async shouldEnforceShellInvariantBlocks(e,t,r){const n=await this.getAdminCommandDenylistBlock(e,{command:t.command,parsingResult:t.parsingResult,toolCallId:t.toolCallId});if(void 0!==n)return{kind:"block",reason:n};const o=await xc(t.workingDirectory);if(null===o){if(!0!==t.skipUnsafeWorkingDirectoryBlock)return{kind:"block",reason:{type:"unsafeResolution",message:pk("Command","working directory",t.workingDirectory)}}}else if(await this.ignoreService.isRepoBlocked(o))return{kind:"block",reason:{type:"adminBlock",source:"Team repo blocklist"}};const s=(await this.getPermissions()).userConfiguredPolicy,i=r??s;return"workspace_readonly"===s.type&&"workspace_readonly"!==i.type?{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}}:void 0!==r?{kind:"allow",policy:r}:!0!==t.resolveSkippedApprovalPolicy||"workspace_readonly"!==s.type?{kind:"allow",policy:void 0}:{kind:"allow",policy:await this.applyServerAndAdminPolicies({...s,skipStatsigDefaults:s.skipStatsigDefaults??!0})}}async shouldBlockShellCommand(e,t,r,n){const o="insecure_none"===n?.type,s=await this.shouldEnforceShellInvariantBlocks(e,{workingDirectory:r.workingDirectory,command:t,parsingResult:r.parsingResult,toolCallId:r.toolCallId},n);if("block"===s.kind)return s;const i=await this.getPermissions(),a=i.approvalMode,c="unrestricted"===a,l=i.userConfiguredPolicy,u=!i.dashboardTerminalAllowlistOverriddenByPermissionsFile;if(nk.info(e,"Shell permissions: evaluating shell command",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:Zk(l),requestedPolicyType:Zk(n),effectiveRequestedPolicyType:Zk(n??l),smartAllowlistEnabled:!0===i.smartAllowlistEnabled,hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId,hookForcesPrompt:Do(r.hookApprovalRequirement),classifierClassificationFailed:!0===r.classifierResult?.classificationFailed,classifierCommandCount:r.classifierResult?.commands.length??0,parserCommandCount:r.parsingResult.executableCommands.length,parsingFailed:r.parsingResult.parsingFailed,hasRedirects:r.parsingResult.hasRedirects,commandLength:t.length}),await this.shouldPromptForEmptyPlainShellAllowlist(t,i))return nk.info(e,"Shell permissions: prompting for empty allowlist",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:Zk(l),requestedPolicyType:Zk(n),hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId}),await this.requestApprovalForEmptyShellAllowlist(t,r,n??l);const d=r.parsingResult.executableCommands,h=r.parsingResult.parsingFailed,p=r.classifierResult,f=r.smartModeApprovalReason,m=r.smartModeApprovalRequestId,g=void 0!==p&&!p.classificationFailed&&p.commands.length>0?p:void 0,w="allowlist"===a&&i.smartAllowlistEnabled?g?.commands:void 0,y=void 0!==w,v=d.map(zS),b=w?w.map(Nk):v.map((e=>e.command)),S=void 0!==w?w.map(Ok):b.map((e=>[e.fullText.trim()].filter(Boolean))),k=void 0!==g?g.commands.map(Ok):v.map(Kk);if(n||(n=i.userConfiguredPolicy),"insecure_none"!==n.type&&void 0===n.skipStatsigDefaults&&"insecure_none"!==l.type&&(n={...n,skipStatsigDefaults:l.skipStatsigDefaults??!0}),"insecure_none"!==l.type&&(0,No.$b)(l.networkPolicy)&&"insecure_none"!==n.type&&!(0,No._B)(n.networkPolicy)){const e=l.networkPolicy,t=n.networkPolicy?.allow;if(void 0!==t&&t.length>0&&e){const r=[...new Set([...e.allow??[],...t])];n={...n,networkPolicy:{...e,allow:r}}}else n={...n,networkPolicy:e}}let _;n=function({requestedPolicy:e,userConfiguredPolicy:t}){if("insecure_none"===e.type||"insecure_none"===t.type)return e;const r=(0,No.XX)(e.readBoundary,t.readBoundary),n="workspace"===r?(0,No.wG)(Wk(e.readBoundary,e.additionalReadPaths),Wk(t.readBoundary,t.additionalReadPaths)):void 0;return{...e,readBoundary:r,additionalReadPaths:n}}({requestedPolicy:n,userConfiguredPolicy:l}),p&&nk.info(e,"Smart allowlist: classifier result received",{classificationFailed:p.classificationFailed,suggestedSandboxMode:p.suggestedSandboxMode,commandCount:p.commands.length,suggestedAllowlistEntryCount:p.commands.filter((e=>e.suggestedAllowlistEntry)).length});const C=[],E=[];let x=[],P=[],R=[];const I=Dk(i.smartAllowlistDenylist??[]);if(I.length>0){P=[];const t=k.map((e=>e[0]??""));for(let e=0;eFk(r,e)))){const r=t[e];r&&P.push(r)}}P.length>0&&(nk.info(e,"Command blocklist: commands require approval",{count:P.length}),C.push(`In blocklist: ${P.join(", ")}`))}if(y&&p){const t=S.map((e=>e[0]??"")),r=i.allow.filter((e=>this.isShellEntry(e)));nk.info(e,"Smart allowlist: checking commands against lists",{commandCount:t.length,allowlistCount:r.length,commandBlocklistCount:I.length});const n=S.map((e=>r.some((t=>e.some((e=>this.matchesShell(t,e))))))),o=n.every(Boolean),s=[];for(let e=0;efunction(e){const t=e.name.trim();if(!t)return[];if(Gb(t))return[];const r=e.subcommandTokens.map((e=>e.trim())).filter(Boolean),n=e.arguments.map((e=>e.trim())).filter(Boolean),o=[t],s=[t];for(const e of r)s.push(e),o.push(s.join(" "));const i=[t,...n].join(" ");return o.includes(i)||o.push(i),Dk(o)}(e)))),R=s.map((e=>e.suggestedAllowlistEntry)).filter((e=>"string"==typeof e)).filter((e=>x.includes(e))),x.length>0){const e=Zb(x,R),t=e.length>0?e.join(", "):x.join(", ");E.push(`Not in allowlist: ${t}`)}_=o&&0===P.length,_&&nk.info(e,"Smart allowlist: all commands in allowlist, will check security",{commandCount:t.length})}const T="ask-every-time"===a||"insecure_none"===n.type&&"allowlist"===a?void 0:l,A=Vk(v),$=b.map(((e,t)=>new Jk(e,n,T,S[t],y?A:v[t])));if((0===b.length||h&&!y)&&!c){nk.info(e,"Shell permissions: prompting after parser miss",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:Zk(n),userConfiguredPolicyType:Zk(l),isSmartAllowlistActive:y,parsingFailed:h,parserCommandCount:b.length,hasSmartModeApprovalReason:void 0!==f,hasSmartModeApprovalRequestId:void 0!==m});const o={type:Bw.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:Uk(f??(h?"Parser failed to parse command (possible bypass)":"Parser found no commands (possible bypass)"),await this.adminNetworkLimitReason(n)),isSandboxAvailable:!1,isSandboxEnabled:!1,canAllowlist:!1,notAllowedCommands:[],smartModeApprovalReason:f,smartModeApprovalRequestId:m}};r.onApprovalRequested?.();const s=await this.pendingDecisionStore.requestApproval(o);return s.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(n)}:{kind:"block",reason:{type:"userRejected",reason:s.reason}}}if(await this.hasHardDeny(e,$))return{kind:"block",reason:{type:"permissionsConfig",..."workspace_readonly"===l.type?{isReadonly:!0}:{}}};const{allowlistOfferSafe:M,redirectsAllowlistSafe:D}=await this.computeRedirectAllowlistSafety(r.parsingResult,r.workingDirectory,"insecure_none"===l.type||"workspace"!==l.readBoundary),O=await this.teamSettingsService.getAutoRunControls(),F={type:"insecure_none"};for(const e of $)await this.cmdIsAllowedByAllowlist(e,{redirectsAllowlistSafe:D,autoRunControls:O,applyTeamAllowlist:u})&&e.approveWithPolicy(F);for(const e of $)O&&this.isInTeamBlocklist(O,e)&&e.deny();const N=await this.teamSettingsService.getDeleteFileProtection();if(N)for(const e of $)"rm"===e.command.name&&e.deny();const L=this.buildShellApprovalDecisionFacts({commands:$,autoRunControls:O,shouldApplyTeamShellAllowlist:u,deleteProtectionEnabled:N,softDenylistedCommands:P});if("workspace_readonly"===l.type&&"workspace_readonly"!==n.type)return nk.info(e,"Shell permissions: blocked by readonly mode"),{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}};const j=Do(r.hookApprovalRequirement),U=r.hookApprovalRequirement?.reason,B=o&&"insecure_none"!==l.type&&function(e){if(/\brimraf\b/i.test(e))return!0;for(const t of e.replace(/[\\`^]\r?\n/g," ").split(/(?|])&|\|\||[;\n]/)){let e=!1;for(const r of t.split("|")){if(e&&QS.test(r)||ek(r,QS,YS)||ek(r,/(?0&&(L.hasSecurityDenies||L.hasSoftDenies||!L.allCommandsRunnable);if(void 0!==f&&G.push(f),j&&(V||G.push(U?`Hook requested approval: ${U}`:"Hook requested approval"),z=!1),B&&(V||G.push("Recursive delete outside the sandbox"),z=!1),C.length>0&&(V||G.push(...C),z=!1),!V)if(y&&E.length>0)G.push(...E);else if(L.unapprovedCommands.length>0){const e=Zb(this.generateAllowlistPatterns(L.unapprovedCommands)),t=e.length>0?e.join(", "):L.unapprovedCommands.map((e=>e.command.fullText)).join(", ");G.push(`Not in allowlist: ${t}`)}if(L.hasSecurityDenies&&(V||(L.rmDeniedByDeleteProtection.length>0&&G.push("Delete protection is enabled"),L.teamBlocklistedCommands.length>0&&G.push(`In team blocklist: ${L.teamBlocklistedCommands.map((e=>e.command.name)).join(", ")}`)),z=!1),K){const t=L.notInTeamAllowlist.map((e=>e.command.fullText)).join(", ");nk.info(e,"Shell permissions: commands not in team allowlist",{commandCount:L.notInTeamAllowlist.length}),V||G.push(`Not in team allowlist: ${t}`),z=!1}const J="unrestricted"===a&&"workspace_readonly"===n.type,Z="unrestricted"!==a||J?n:{type:"insecure_none"},X=Uk(...G,await this.adminNetworkLimitReason(Z)),Q=[];if(z){const e=void 0!==f?$.filter((e=>"allowlisted"!==e.state)):L.unapprovedCommands;Q.push(...this.generateAllowlistPatterns(e))}const Y=y&&E.length>0,ee=Y?x:Q,te=Y&&R.length>0?R:void 0,re="insecure_none"!==n.type&&"insecure_none"!==l.type,ne="insecure_none"!==n.type,oe=[void 0!==f?"smart_mode_approval":void 0,j?"hook_forces_prompt":void 0,B?"unsandboxed_recursive_delete":void 0,C.length>0?"command_blocklist":void 0,y&&E.length>0?"smart_allowlist_miss":void 0,L.unapprovedCommands.length>0?"unapproved_commands":void 0,L.hasSecurityDenies?"security_denies":void 0,K?"team_allowlist_miss":void 0].filter((e=>void 0!==e));nk.info(e,"Shell permissions: requesting shell approval",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:Zk(n),userConfiguredPolicyType:Zk(l),isSandboxAvailable:re,isSandboxEnabled:ne,canAllowlist:z,isSmartAllowlistActive:y,hasSmartModeApprovalReason:void 0!==f,hasSmartModeApprovalRequestId:void 0!==m,hookForcesPrompt:j,approvalReasonTypes:oe,commandCount:$.length,unapprovedCommandCount:L.unapprovedCommands.length,deniedCommandCount:L.deniedCommands.length,notInTeamAllowlistCount:L.notInTeamAllowlist.length,notAllowedCommandCount:ee.length,suggestedAllowlistEntryCount:te?.length??0,allCommandsRunnable:L.allCommandsRunnable,allCommandsAllowlisted:L.allCommandsAllowlisted,allCommandsPreapproved:L.allCommandsPreapproved,hasSecurityDenies:L.hasSecurityDenies,hasSoftDenies:L.hasSoftDenies});const se={type:Bw.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:X,isSandboxAvailable:"allowlist"===a&&re,isSandboxEnabled:!("allowlist"!==a&&!J)&&ne,canAllowlist:z,notAllowedCommands:ee,suggestedAllowlistEntries:te,smartModeApprovalReason:f,smartModeApprovalRequestId:m}};r.onApprovalRequested?.();const ie=await this.pendingDecisionStore.requestApproval(se);return ie.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(Z)}:{kind:"block",reason:{type:"userRejected",reason:ie.reason}}}async isShellCommandFullyAllowlisted(e,t,r){const n=e.withName("InteractivePermissionsService.isShellCommandFullyAllowlisted"),o=await this.getPermissions(),s=!o.dashboardTerminalAllowlistOverriddenByPermissionsFile;if("allowlist"!==o.approvalMode)return!1;if("workspace_readonly"===o.userConfiguredPolicy.type)return!1;const{redirectsAllowlistSafe:i}=await this.computeRedirectAllowlistSafety(r.parsingResult,r.workingDirectory,"insecure_none"===o.userConfiguredPolicy.type||"workspace"!==o.userConfiguredPolicy.readBoundary);if(!i)return!1;const a=r.classifierResult,c=void 0!==a&&!a.classificationFailed&&a.commands.length>0?a:void 0,l=(o.smartAllowlistEnabled??!1)&&void 0!==c;if(r.parsingResult.parsingFailed&&!l)return!1;const u=r.parsingResult.executableCommands.map(zS),d=l?c.commands.map(Nk):u.map((e=>e.command));if(0===d.length)return!1;const h=l?c.commands.map(Ok):d.map((e=>[e.fullText.trim()].filter(Boolean))),p=void 0!==c?c.commands.map(Ok):u.map(Kk),f={type:"insecure_none"},m=Vk(u),g=d.map(((e,t)=>new Jk(e,f,void 0,h[t],l?m:u[t])));if(await this.hasHardDeny(n,g))return!1;const w=Dk(o.smartAllowlistDenylist??[]);if(w.length>0)for(const e of p)if(e&&0!==e.length&&w.some((t=>Fk(e,t))))return!1;if(await this.teamSettingsService.getDeleteFileProtection()&&g.some((e=>"rm"===e.command.name)))return!1;const y=await this.teamSettingsService.getAutoRunControls();if(void 0!==y&&g.some((e=>this.isInTeamBlocklist(y,e))))return!1;for(const e of g)if(!await this.cmdIsAllowedByAllowlist(e,{redirectsAllowlistSafe:i,autoRunControls:y,applyTeamAllowlist:s}))return!1;return!0}async applyServerAndAdminPolicies(e){if("insecure_none"===e.type)return e;const t=this.rootDirectories.at(0)??(0,o.homedir)(),{userSandboxDataFolderName:r,teamAdminPolicy:n}=await this.getPermissions(),i=void 0!==r&&r.length>0?(0,s.join)((0,o.homedir)(),r,"sandbox.json"):this.perUserSandboxConfigPath,a=await this.foldPerUserFilePolicy(e,i),c=a.skipStatsigDefaults?a:await this.applyStatsigDefaults(a),l=await this.loadPerRepoFilePolicy(c,t),u=await this.resolveTeamAdminLayer(n);if("unavailable"===u){const{policy:e}=await(0,No.resolveSandboxPolicyForWorkspace)(t,{perUser:c,perRepo:l});return function(e){return"insecure_none"===e.type?e:{...e,networkPolicy:(0,No.Po)(),readBoundary:"workspace",additionalReadPaths:[]}}(e)}const d=void 0===u?void 0:Lk(c.type,u),h=(0,No._B)(e.networkPolicy)&&!jk(d?.networkPolicy),{policy:p}=await(0,No.resolveSandboxPolicyForWorkspace)(t,{perUser:c,perRepo:l,teamAdmin:d});return h?{...p,networkPolicy:(0,No.T6)()}:p}async resolveLinkedWorktreeSandboxGrants(e,t){if("workspace_readwrite"!==e.type||"workspace"===e.readBoundary)return;const{perms:r,setting:n}=await this.readControlSetting();if("workspace"===n.boundary||"unavailable"===r.teamAdminPolicy)return;const i=r.userSandboxDataFolderName;if(void 0===e.readBoundary){const t=this.rootDirectories.at(0)??(0,o.homedir)(),n=void 0!==i&&i.length>0?(0,s.join)((0,o.homedir)(),i,"sandbox.json"):this.perUserSandboxConfigPath,a="readBoundary"in r.userConfiguredPolicy&&void 0!==r.userConfiguredPolicy.readBoundary?{...e,readBoundary:r.userConfiguredPolicy.readBoundary}:e,c=await this.foldPerUserFilePolicy(a,n),l=await this.loadPerRepoFilePolicy(c,t);if("workspace"===(l?.readBoundary??c.readBoundary))return}const a=[];for(const e of this.rootDirectories){if((0,Gs.$f)(e))continue;const t=await NS(e);LS(t.resolution)&&!bS(t.resolvedPath)&&a.push(t.resolvedPath)}if(0===a.length)return;let c;if(!(0,Gs.$f)(t.workingDirectory)){const e=await NS(t.workingDirectory);LS(e.resolution)&&(c=e.resolvedPath)}return async function(e,t={}){if(0===e.length)return;const r=await Promise.all(e.map((e=>RS(e)))),n=[];for(const o of r)void 0===o||n.some((e=>DS(e,o)))||!e.some((e=>(0,ts.BJ)(o,e)))&&await(t.isUntrustedExternalGitDir?.(o))||n.push(o);if(0===n.length)return;const o=[],i=[],a=void 0!==t.command||void 0!==t.realWorkingDirectory;for(const r of n){const n=await xS((0,s.join)(r,"worktrees"),256),c=await(0,Nr.PH)(n,(e=>ES((0,s.join)(r,"worktrees",e),r,!0===t.excludeAgentWorktrees,a?{command:t.command,realWorkingDirectory:t.realWorkingDirectory}:void 0)),{max:16});let l=!1;for(const r of c){if(o.length>=16)break;void 0===r||o.some((e=>DS(e,r)))||e.some((e=>(0,ts.BJ)(r,e)))||PS(r,e)||await(t.isExcludedWorktreeRoot?.(r))||(o.push(r),l=!0)}l&&i.push(r)}return 0===o.length?void 0:{roots:o,commonDirs:i}}(a,{command:t.command,realWorkingDirectory:c,excludeAgentWorktrees:!0,isUntrustedExternalGitDir:e=>this.isFreelyWritableOutsideWorkspace(e,i),isExcludedWorktreeRoot:async e=>await this.isFreelyWritableOutsideWorkspace(e,i)||await this.ignoreService.isRepoBlocked(e)})}async foldPerUserFilePolicy(e,t=this.perUserSandboxConfigPath){const r=await(0,No.tv)(t,(0,o.homedir)());if(!r||"insecure_none"===r.type)return e;let n=(0,No.fZ)(r.networkPolicy,e.networkPolicy);n&&void 0!==e.networkPolicy?.default&&(n={...n,default:e.networkPolicy.default});const s=(0,No.s9)(r.additionalReadonlyPaths,e.additionalReadonlyPaths),i={...e,networkPolicy:n,additionalReadonlyPaths:s.length>0?s:void 0,readBoundary:r.readBoundary??e.readBoundary,additionalReadPaths:void 0!==r.additionalReadPaths?r.additionalReadPaths:e.additionalReadPaths,privateTmp:r.privateTmp??e.privateTmp};if("workspace_readwrite"===e.type&&"workspace_readwrite"===r.type){const t=(0,No.s9)(r.additionalReadwritePaths,e.additionalReadwritePaths);return{...i,additionalReadwritePaths:t.length>0?t:void 0}}return i}async applyStatsigDefaults(e){const t=await this.teamSettingsService.getDefaultNetworkAllowlist();if(!t.available||0===t.allowlist.length)return e;if((0,No._B)(e.networkPolicy))return e;const r={default:"deny",allow:fk(t.allowlist)};return{...e,networkPolicy:(0,No.fZ)(e.networkPolicy,r)}}async loadPerRepoFilePolicy(e,t){const r=await(0,No.tv)((0,s.join)(t,".cursor","sandbox.json"),t);if(r){if("1"===process.env[Yv.K4]){const n=(0,No.fB)({perUser:e,perRepo:r},t).perRepo;return"insecure_none"===n?.type?void 0:n}if("insecure_none"!==r.type)return r.type!==e.type?Lk(e.type,{networkPolicy:r.networkPolicy,additionalReadonlyPaths:r.additionalReadonlyPaths,..."additionalReadwritePaths"in r?{additionalReadwritePaths:r.additionalReadwritePaths}:{},disableTmpWrite:r.disableTmpWrite,networkPolicyStrict:r.networkPolicyStrict,readBoundary:r.readBoundary,additionalReadPaths:r.additionalReadPaths,privateTmp:r.privateTmp}):r}}async resolveTeamAdminLayer(e){return void 0!==e?"unavailable"===e?"unavailable":"workspace"===(t=e).readBoundary?t:void 0===t.networkPolicy?{}:{networkPolicy:t.networkPolicy}:async function(e){const{teamSettings:t}=e,r=e.adminNetworkControlsEnabled?(i=await t.getNetworkAccessControls()).available?0!==i.allowlist.length||0!==i.denylist.length?{...i.allowlist.length>0?{default:"deny",allow:fk(i.allowlist)}:{},...i.denylist.length>0?{deny:fk(i.denylist)}:{}}:void 0:(0,No.Po)():void 0,[n,o]=await Promise.all([t.isReadControlEnabled?.()??!0,t.getSandboxingControls()]),s=void 0===r?{}:{networkPolicy:r};var i;return n&&"workspace"===o.readBoundary?{...s,readBoundary:"workspace",additionalReadPaths:o.readAllowlistPaths??[],allowUserOverrideReadPaths:o.allowUserOverrideReadAllowlist}:void 0===r?void 0:s}({teamSettings:this.teamSettingsService,adminNetworkControlsEnabled:this.adminNetworkControlsEnabled});var t}async adminNetworkLimitReason(e){if("insecure_none"===e.type||!(0,No._B)(e.networkPolicy))return;const{teamAdminPolicy:t}=await this.getPermissions(),r=await this.resolveTeamAdminLayer(t);return function(e){if(jk(e))return void 0!==e.allow&&e.allow.length>0?"Network access limited to your admin's allowlist":"deny"===e.default?"Network access limited by your admin":"Network access excludes domains your admin blocks"}("unavailable"===r?(0,No.Po)():r?.networkPolicy)}async getAdminReadSandboxing(){const e=await this.getPermissions();if("unavailable"===e.teamAdminPolicy)return{readBoundary:"workspace"};const{enabled:t,boundary:r}=await this.adminReadControls(e);return{readBoundary:t&&"workspace"===r?"workspace":void 0}}async isInShellAllowlist(e){if(!e.allowlistable)return!1;const t=await this.getPermissions(),r=e.readsArguments?e.matchForms.map((e=>`${e} \0`)):e.matchForms;return t.allow.some((e=>this.isShellEntry(e)&&r.some((t=>this.matchesShell(e,t)))))}isInTeamBlocklist(e,t){const r=[...t.wrapperForms,t.command.fullText];return e.blocked.some((e=>r.some((t=>this.matchesAutoRunCommand(t,e)))))}isInTeamAllowlist(e,t){return!!t.allowlistable&&e.allowed.some((e=>this.matchesAutoRunCommand(t.command.fullText,e)))}async computeRedirectAllowlistSafety(e,t,r){const n=e.hasRedirects,s=e.parsingFailed,a=!0===e.allRedirectsAreDevNull,c=!(!n||a||s)&&await async function({parsingResult:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n=!0,resolvePathForPermissions:s=NS,pathModule:a=i,tempPathOptions:c={platform:process.platform,env:process.env,pathModule:a,homeDirectory:(0,o.homedir)()}}){if(!e.hasRedirects)return!0;const l=e.redirects;if(0===l.length)return!1;const u=e.executableCommands.length>1,d=await Tk({parsingResult:e,workingDirectory:t,resolvePathForPermissions:s,pathModule:a}),h=mk();for(const e of l){if(bk(e))continue;const o=u?mk():h,{operator:i,targetText:l}=e,f=e.destinationFds;if(">&"===i){const e=vk(l),t=void 0===e?void 0:o.fdTargets.get(e);if("original-stdout"!==(p=t)&&"original-stderr"!==p&&"dev-null"!==p&&"workspace-file"!==p&&"tmp-file"!==p){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}for(const e of f)o.fdTargets.set(e,t);continue}if("<&"===i){const e=vk(l),t=void 0===e?void 0:o.fdTargets.get(e);if("dev-null"!==t){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}for(const e of f)o.fdTargets.set(e,t);continue}if("/dev/null"===l){for(const e of f)o.fdTargets.set(e,"dev-null");continue}if(!wk(i)||void 0===l||"word"===e.targetNodeType&&!Sk(l,a)){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}const m=await Ak({targetText:l,workingDirectory:t,workingDirectories:d,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:s,pathModule:a,tempPathOptions:c});if(!m){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}for(const e of f)o.fdTargets.set(e,m)}var p;return!0}({parsingResult:e,workingDirectory:t,rootDirectories:this.rootDirectories,allowTmpRedirects:r}),l=await Mk({parsingResult:e,workingDirectory:t,rootDirectories:this.rootDirectories,allowTmpRedirects:r}),u=!function({parsingResult:e,hasRedirects:t,parsingFailed:r,allRedirectsAreAllowlistSafe:n,allRedirectsAreWorkspaceFileSafe:o}){return!(!t||r||n||o)&&(0===e.redirects.length||e.redirects.some(yk))}({parsingResult:e,hasRedirects:n,parsingFailed:s,allRedirectsAreAllowlistSafe:a,allRedirectsAreWorkspaceFileSafe:c})&&l;return{allowlistOfferSafe:(!n||a||c)&&l&&!s,redirectsAllowlistSafe:u}}async cmdIsAllowedByAllowlist(e,t){return!!t.redirectsAllowlistSafe&&(!!await this.isInShellAllowlist(e)||t.applyTeamAllowlist&&void 0!==t.autoRunControls&&this.isInTeamAllowlist(t.autoRunControls,e))}buildShellApprovalDecisionFacts({commands:e,softDenylistedCommands:t,autoRunControls:r,shouldApplyTeamShellAllowlist:n,deleteProtectionEnabled:o}){const s=e.filter((e=>"denied"===e.state)),i=e.filter((e=>"approvable"===e.state)),a=n&&r?.enabled?e.filter((e=>!this.isInTeamAllowlist(r,e))):[],c=s.filter((e=>void 0!==r&&this.isInTeamBlocklist(r,e))),l=o?s.filter((e=>"rm"===e.command.name)):[];return{hasSecurityDenies:s.length>0,hasSoftDenies:t.length>0,hasTeamAllowlistMisses:a.length>0,allCommandsRunnable:e.every((e=>e.isRunnable())),allCommandsAllowlisted:e.every((e=>"allowlisted"===e.state)),allCommandsPreapproved:e.every((e=>"preapproved"===e.state)),canAllowlistInPrompt:0===s.length&&0===a.length,unapprovedCommands:i,deniedCommands:s,notInTeamAllowlist:a,teamBlocklistedCommands:c,rmDeniedByDeleteProtection:l}}getShellAutoApprovalPolicy({approvalMode:e,isUnrestricted:t,requestedPolicy:r,facts:n,preserveRequestedPolicyForAllowlistedCommands:o}){if(!n.hasSecurityDenies&&!n.hasSoftDenies&&n.allCommandsRunnable){if(t)return"workspace_readonly"===r.type?r:{type:"insecure_none"};if("allowlist"===e)return n.allCommandsAllowlisted&&!o&&"workspace_readonly"!==r.type?{type:"insecure_none",allowlistEscalated:!0}:r}}async getPermissions(){return await this.permissionsProvider.getPermissions()}hasLocalShellControls(e){return e.allow.some((e=>this.isShellEntry(e)))||e.deny.some((e=>this.isShellEntry(e)))||(e.smartAllowlistDenylist?.length??0)>0}hasTeamShellControls(e,t=!0){return void 0!==e&&(t&&(e.enabled||e.allowed.length>0)||e.blocked.length>0)}async shouldPromptForEmptyPlainShellAllowlist(e,t){if("allowlist"!==t.approvalMode||"insecure_none"!==t.userConfiguredPolicy.type||0===e.trim().length||this.hasLocalShellControls(t))return!1;const[r,n]=await Promise.all([this.teamSettingsService.getAutoRunControls(),this.teamSettingsService.getDeleteFileProtection()]);return!this.hasTeamShellControls(r,!t.dashboardTerminalAllowlistOverriddenByPermissionsFile)&&!n}async requestApprovalForEmptyShellAllowlist(e,t,r){const n=await this.getEmptyShellAllowlistCandidates(t);t.onApprovalRequested?.();const o=await this.pendingDecisionStore.requestApproval({type:Bw.Shell,toolCallId:t.toolCallId,details:{command:e,workingDirectory:t.workingDirectory,timeout:t.timeout,reason:Uk(t.smartModeApprovalReason??"Shell allowlist is empty",await this.adminNetworkLimitReason(r)),isSandboxAvailable:!1,isSandboxEnabled:!1,canAllowlist:n.length>0,notAllowedCommands:n,smartModeApprovalReason:t.smartModeApprovalReason,smartModeApprovalRequestId:t.smartModeApprovalRequestId}});return o.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(r)}:{kind:"block",reason:{type:"userRejected",reason:o.reason}}}async getEmptyShellAllowlistCandidates(e){const t=e.parsingResult;return t.parsingFailed||0===t.executableCommands.length||t.hasRedirects&&!0!==t.allRedirectsAreDevNull||!await Mk({parsingResult:t,workingDirectory:e.workingDirectory,rootDirectories:this.rootDirectories,allowTmpRedirects:!0})?[]:this.generateAllowlistPatterns(t.executableCommands.map(zS))}async getAdminCommandDenylistBlock(e,t){const r=(await this.teamSettingsService.getAdminCommandDenylist()).rules;if(0===r.length)return;const n=ks({matchForms:t.parsingResult?ys({command:t.command,parsingResult:t.parsingResult}):[t.command],blockedCommands:r});return void 0!==n?(nk.info(e,"Admin command denylist hard-blocked shell at execution time",{toolCallId:t.toolCallId,parsingFailed:t.parsingResult?.parsingFailed??!0,parserCommandCount:t.parsingResult?.executableCommands.length??0}),{type:"adminCommandDenylist",pattern:n}):void 0}async hasHardDeny(e,t){const r=await this.getPermissions();return t.some((e=>r.deny.some((t=>this.isShellEntry(t)&&[...e.wrapperForms,...e.matchForms].some((e=>this.matchesShell(t,e)))))))}isShellEntry(e){return null!==qk(e)}isPathEntry(e,t){return new RegExp(`^\\s*${e}\\s*\\(`).test(t)}matchesShell(e,t){const r=qk(e);if(!r)return!1;const n=t.trim(),o=this.extractBaseCommand(n);if(null!==r.argsPattern){const e=n.includes(" ")?n.slice(n.indexOf(" ")+1).trim():"",t=this.matchGlob(r.commandPattern,o)||this.matchGlob(r.commandPattern,n),s=this.matchGlob(r.argsPattern,e);if(t&&s)return!0}return!!this.matchGlob(r.fullPattern,n)||!!n.startsWith(`${r.fullPattern} `)||!!this.matchGlob(r.fullPattern,o)||o===r.fullPattern}async checkCursorFileProtection(e){if(!e.some((e=>".cursor"===e.toLowerCase()||".vscode"===e.toLowerCase())))return null;const t=e[e.length-1]?.toLowerCase()??"";return t.endsWith(".md")||t.endsWith(".mdc")||".cursorrules"===t?null:await this.teamSettingsService.getDotCursorProtection()?{type:"permissionsConfig"}:null}extractBaseCommand(e){const t=e.trim(),r=t.indexOf(" ");return-1===r?t:t.substring(0,r)}generateAllowlistPatterns(e){const t=[],r=["git","npm","yarn","pnpm","docker","pip","systemctl","uv","cargo","bun","npx"];for(const{command:n,allowlistable:o}of e)o&&!Gb(n.name)&&(r.includes(n.name)&&n.args.length>0&&"word"===n.args[0].type?t.push(`${n.name} ${n.args[0].value}`):t.push(n.name));return[...new Set(t)]}pathEntryRawPattern(e,t){const r=t.match(function(e){return"Read"===e?r_:n_}(e));if(r)return(r[1]??"").trim()}compileReadDenyMatcher(e){try{const t=this.pathEntryRawPattern("Read",e);if(void 0===t)return()=>!1;const r=(0,ws.b)((0,ts.jl)(t));return e=>r(e)}catch(e){return()=>{throw e}}}matchesPathEntry(e,t,r){const n=this.pathEntryRawPattern(e,t);return void 0!==n&&this.matchGlob((0,ts.jl)(n),r)}async isPathExplicitlyDenied(e,t){return(await this.getPermissions()).deny.some((r=>this.isPathEntry(e,r)&&this.matchesPathEntry(e,r,t)))}async isPathExplicitlyAllowed(e,t){return(await this.getPermissions()).allow.some((r=>this.isPathEntry(e,r)&&this.matchesPathEntry(e,r,t)))}matchGlob(e,t){return(0,ws.T)(e,t)}async addToAllowList(e,t,r){const n=`${t}(${r})`;await this.permissionsProvider.updatePermissions((e=>{const t=e.allow.includes(n)?e.allow:[...e.allow,n];return{...e,allow:t}}))}async addToDenyList(e,t,r){const n=`${t}(${r})`;await this.permissionsProvider.updatePermissions((e=>{const t=e.deny.includes(n)?e.deny:[...e.deny,n];return{...e,deny:t}}))}async shouldBlockMcp(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{tk(o,(0,D.VI)(e.withName("InteractivePermissionsService.shouldBlockMcp")),!1);const{name:s,toolName:i,providerIdentifier:a,args:c}=t,l=function(e,t){if(void 0!==t)return t;const r=e;return void 0!==r.annotations?r.annotations:Fb(r.annotationsJson)}(t,r?.annotations),u=e=>{this.mcpAllowlistLog?.(e)};if(u(`[permissions-service] shouldBlockMcp: toolName="${i}", providerIdentifier="${a}"`),await this.isComputerUseDisabledByAdminFor(a))return u(`[permissions-service] shouldBlockMcp: BLOCKED (Computer Use off for team) toolName="${i}", providerIdentifier="${a}"`),{type:"unsafeResolution",message:"Computer Use is turned off by your team admin. Ask the user to do it instead."};const d=await this.mcpAdminToolLimitRefusal(e,{resolvedTool:n?.resolvedTool,toolName:i});if(void 0!==d)return u(`[permissions-service] shouldBlockMcp: BLOCKED (team tool limit) toolName="${i}", providerIdentifier="${a}"`),{type:"unsafeResolution",message:d};const h=await this.computerUseDecision(t,r);if(await this.isMcpExplicitlyDenied(e,a,i))return u(`[permissions-service] shouldBlockMcp: BLOCKED (explicitly denied) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig"};const p=await this.getPermissions(),f="workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode;if(!0===n?.alreadyApproved&&!f&&"block"!==h.kind&&"askEachCall"!==h.kind)return!1;const m=await this.teamSettingsService.getMcpToolControls(),g=!0===m?.enabled&&!(void 0!==n?.client&&!0===await(this.teamSettingsService.isHostMcpBridgeClient?.(n.client))),w=g&&"block"!==h.kind?{kind:"notComputerUse"}:h,y=void 0!==t.smartModeApproval?.reason&&f,v=t_({server:e_(a),tool:i});let b,S,k;switch(w.kind){case"block":return u(`[permissions-service] shouldBlockMcp: BLOCKED (Computer Use app) toolName="${i}", providerIdentifier="${a}"`),{type:"unsafeResolution",message:w.message};case"noAccess":if(!f&&!await this.teamSettingsService.getShouldBlockMcp())return u(`[permissions-service] shouldBlockMcp: ALLOWED (Computer Use no access) toolName="${i}", providerIdentifier="${a}"`),!1;b=v,k=!0;break;case"app":if(!y&&(this.computerUseAppsAllowedForSession.includes(w.entry)||await this.isComputerUseAppSaved(w.entry)))return u(`[permissions-service] shouldBlockMcp: ALLOWED (Computer Use app grant) toolName="${i}", providerIdentifier="${a}"`),!1;b=w.entry,S=w.app,k=!1;break;case"askEachCall":b=void 0,S=w.app&&{...w.app,allowOnce:!0},k=!1;break;case"notComputerUse":b=v,k=!0}const _=k||void 0!==b,C=t.smartModeApproval?.reason;if(void 0!==C)return"workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode?(u(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode, Smart Mode forced approval) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig",isReadonly:!0}):(u(`[permissions-service] shouldBlockMcp: needsApproval (Smart Mode) toolName="${i}", providerIdentifier="${a}"`),!(g?this.isMcpInTeamAllowlist(m,{providerIdentifier:a,toolName:i,annotations:l}):k&&await this.isMcpExplicitlyAllowed(e,a,i))&&!("unrestricted"===p.approvalMode&&!await this.teamSettingsService.getShouldBlockMcp())&&{type:"needsApproval",approvalReason:C,approvalDetails:{type:"mcp",name:s,toolName:i,...dk(r,l),providerIdentifier:a,args:c,reason:"smartMode",canAllowlist:_&&!this.isComputerUseServer(a),smartModeApprovalReason:C,smartModeApprovalRequestId:t.smartModeApproval?.requestId,allowlistEntry:b,computerUseApp:S}});if(g){const t=this.isMcpInTeamAllowlist(m,{providerIdentifier:a,toolName:i,annotations:l});if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"team",outcome:t?"pass":"fail"}),t)return u(`[permissions-service] shouldBlockMcp: ALLOWED (in admin MCP allowlist) toolName="${i}", providerIdentifier="${a}"`),!1}else if(k){const t=await this.isMcpExplicitlyAllowed(e,a,i);if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"user",outcome:t?"pass":"fail"}),t)return u(`[permissions-service] shouldBlockMcp: ALLOWED (explicitly in allowlist) toolName="${i}", providerIdentifier="${a}"`),!1}if("workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode)return u(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig",isReadonly:!0};if("unrestricted"===p.approvalMode){if(!await this.teamSettingsService.getShouldBlockMcp())return u(`[permissions-service] shouldBlockMcp: ALLOWED (auto-run, no team block) toolName="${i}", providerIdentifier="${a}"`),!1;u(`[permissions-service] shouldBlockMcp: needsApproval (auto-run but team blocks MCP) toolName="${i}", providerIdentifier="${a}"`)}return u(`[permissions-service] shouldBlockMcp: needsApproval (not in allowlist) toolName="${i}", providerIdentifier="${a}", approvalMode="${p.approvalMode}"`),{type:"needsApproval",approvalReason:`MCP tool: ${i}`,approvalDetails:{type:"mcp",name:s,toolName:i,...dk(r,l),providerIdentifier:a,args:c,canAllowlist:_,allowlistEntry:b,computerUseApp:S}}}catch(e){o.error=e,o.hasError=!0}finally{rk(o)}}async mcpAdminToolLimitRefusal(e,{resolvedTool:t,toolName:r}){if(void 0===t||void 0===this.enforceMcpAdminToolLimits)return;if(!await this.enforcesMcpAdminToolLimits())return void(void 0!==this.onMcpAdminToolLimitCheck&&this.judgeMcpAdminToolLimit(t,r).then((e=>this.reportMcpAdminToolLimitCheck("shadow",e)),(()=>{})));const n=await this.judgeMcpAdminToolLimit(t,r);this.reportMcpAdminToolLimitCheck("enforce",n);const o=n?.outcome;switch(o){case void 0:case"within_limit":return;case"outside_limit":return sk.increment(e,1,{reason:"outside_limit"}),"Your team's admin limits this MCP tool";case"settings_unavailable":if(!0===n?.ranWithoutLimit)return;return sk.increment(e,1,{reason:"settings_unavailable"}),"Your team's MCP settings could not be read, so this MCP tool can't run right now";case"unknown_server":return sk.increment(e,1,{reason:"unknown_server"}),ik;default:return o}}async judgeMcpAdminToolLimit(e,t){if("unresolved"===e)return{outcome:"unknown_server"};const r=await(this.teamSettingsService.getMcpAdminToolLimit?.(e.client));if(void 0!==r)switch(r.kind){case"none":return;case"settings_unavailable":return{outcome:"settings_unavailable",...void 0===r.failure?{}:{settingsFailure:r.failure},...!0===r.noLimitApplies?{ranWithoutLimit:!0}:{}};case"unknown_server":return{outcome:"unknown_server"};case"limit":return{outcome:Wb(r.policy,{name:t,annotations:e.annotations})?"within_limit":"outside_limit"};default:return r}}reportMcpAdminToolLimitCheck(e,t){if(void 0!==t)try{this.onMcpAdminToolLimitCheck?.({mode:e,...t})}catch{}}async enforcesMcpAdminToolLimits(){if(void 0===this.enforceMcpAdminToolLimits)return!1;try{return await this.enforceMcpAdminToolLimits()}catch{return!1}}async computerUseDecision(e,t){const r=this.computerUse;if(void 0===r||!this.isComputerUseServer(e.providerIdentifier))return{kind:"notComputerUse"};const n=await r.isOwnServer(e_(e.serverIdentifier||e.providerIdentifier),t);if(!1===n)return{kind:"notComputerUse"};const o=await async function(e,t){const r=cS(e.meta?.["cursor/computerUseScope"])??cS(t.toolScopes?.[e.toolName]);if(void 0===r)return{kind:"screen"};let n;if(void 0!==r.appSelectorArgs){const t=Object.entries(r.appSelectorArgs).flatMap((([t,r])=>aS(t)&&void 0!==r&&void 0!==e.args[r]&&null!==e.args[r]?[{selector:t,value:e.args[r]}]:[]));if(0===t.length){const t=new Intl.ListFormat("en",{type:"disjunction"}).format(Object.values(r.appSelectorArgs).filter((e=>void 0!==e)));return{kind:"noAppSelector",message:`${e.toolName} needs exactly one of ${t} to name the app. Call it again with one of them.`}}const o=t.filter((({selector:e,value:t})=>function(e,t){return"pid"===e?"number"==typeof t&&Number.isInteger(t)||"string"==typeof t&&uS.test(t):"string"==typeof t&&t.length>0}(e,t)));if(1!==o.length){for(const{value:e}of t){const t="string"==typeof e?rS(e.trim()):void 0;if(void 0!==t)return{kind:"app",app:t}}return{kind:"unknownApp"}}n=function(e,t){if("pid"===e){const e="string"==typeof t&&uS.test(t)?Number(t):t;return"number"==typeof e&&Number.isSafeInteger(e)&&e>0?{pid:e}:void 0}const r="string"==typeof t?t.trim():"";if(0!==r.length)return"bundleId"===e?{bundleId:r}:"path"===e?{path:r}:{appName:r}}(o[0].selector,o[0].value)}else{if(void 0===r.appArg)return r.capturesScreen?{kind:"screen"}:{kind:"none"};{const t=e.args[r.appArg];if(null==t||function(e){return"object"==typeof e&&null!==e&&"screen"===e.scope}(t))return{kind:"screen"};n=function(e){if("string"==typeof e){const t=e.trim();return t.length>0?{name:t}:void 0}if("object"!=typeof e||null===e)return;const{scope:t,pid:r}=e;return"app"===t&&"number"==typeof r&&Number.isInteger(r)&&r>0?{pid:r}:void 0}(t)}}if(void 0===n)return{kind:"unknownApp"};const o=function(e){return"pid"in e?void 0:"name"in e?e.name:"bundleId"in e?e.bundleId:"path"in e?e.path:e.appName}(n),s=await t.describeApp(n)??(void 0===o?void 0:rS(o));return void 0===s?{kind:"unknownApp"}:{kind:"app",app:s}}({toolName:e.toolName,args:Object.fromEntries(Object.entries(e.args).map((([e,t])=>[e,t.toJson()]))),meta:t?._meta},r);if(void 0===n&&"app"!==o.kind)return{kind:"askEachCall"};switch(o.kind){case"none":return{kind:"noAccess"};case"screen":return{kind:"notComputerUse"};case"unknownApp":return{kind:"askEachCall"};case"noAppSelector":return{kind:"block",message:o.message};case"app":{const e=function(e){const t=e.toLowerCase();return Yb(t)?"Computer Use doesn't control Cursor itself, including its approval cards. Ask the user to do it instead.":eS.some((e=>e.bundleId===t))?"Computer Use doesn't control apps that run scripts, such as Script Editor, Automator and Shortcuts. Ask the user to do it instead.":tS.some((e=>e.bundleId===t))?"Computer Use doesn't control terminal apps. Use your shell tool to run commands instead.":void 0}(o.app.bundleId);if(void 0!==e)return{kind:"block",message:e};if(void 0===n)return{kind:"askEachCall"};const t=oS(o.app.bundleId)?void 0:t_({server:r.serverId,tool:sS(o.app.bundleId)});return void 0===t?{kind:"askEachCall",app:o.app}:{kind:"app",app:o.app,entry:t}}}throw new Error("unreachable computer-use subject")}isComputerUseServer(e){const t=e_(e);return!0===this.computerUse?.providerIdentifiers.has(t)}async isComputerUseDisabledByAdminFor(e){const t=this.computerUseAdminPolicy;return t?.providerIdentifiers.has(e_(e))?await t.isDisabledByAdmin():!!this.isComputerUseServer(e)&&!0===await(this.teamSettingsService.isComputerUseDisabledByAdmin?.())}allowComputerUseAppForSession({bundleId:e}){const t=void 0===this.computerUse||oS(e)?void 0:t_({server:this.computerUse.serverId,tool:sS(e)});void 0!==t&&this.computerUseAppsAllowedForSession.push(t)}async isMcpFullyAllowlisted(e,t){const r=e.withName("InteractivePermissionsService.isMcpFullyAllowlisted"),{providerIdentifier:n,toolName:o}=t,s=t.annotations??Fb(t.annotationsJson);if(await this.isMcpExplicitlyDenied(r,n,o)||await this.isComputerUseDisabledByAdminFor(n))return!1;const i=await this.teamSettingsService.getMcpToolControls();return!0===i?.enabled?!!this.isMcpInTeamAllowlist(i,{providerIdentifier:n,toolName:o,annotations:s}):!this.isComputerUseServer(n)&&await this.isMcpExplicitlyAllowed(r,n,o)}async isWebFetchFullyAllowlisted(e,t){const r=await this.getPermissions();if("allowlist"!==r.approvalMode)return!1;let n;try{n=new URL(t.url)}catch{return!1}const o=n.hostname;return!r.deny.some((e=>this.matchesWebFetchEntry(e,o)))&&r.allow.some((e=>this.matchesWebFetchEntry(e,o)))}matchesAutoRunCommand(e,t){const r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^${r}(\\s|$)`).test(e.trim())}matchesMcpPattern({pattern:e,providerIdentifier:t,toolName:r,logLabel:n}){const o=e.indexOf(":");if(-1===o)return!1;const s=e.slice(0,o).trim().toLowerCase(),i=e.slice(o+1).trim().toLowerCase(),a=e_(t).toLowerCase().trim(),c=r.toLowerCase().trim(),l="*"===s||this.matchGlob(s,a),u="*"===i||this.matchGlob(i,c),d=l&&u,h=`[permissions-service] ${n}: serverPattern="${s}", toolPattern="${i}", normalizedProviderIdentifier="${a}", normalizedToolName="${c}", serverMatches=${l}, toolMatches=${u}, result=${d}`;return this.mcpAllowlistLog?.(h),d}recordMcpAllowlistCheckResult(e,{allowlistScope:t,outcome:r}){ok.increment(e,1,{allowlist_scope:t,outcome:r})}matchesMcpEntry(e,t,r){const n=e.match(/^\s*Mcp\s*\((.*)\)\s*$/);if(!n)return!1;const o=n[1]?.trim()??"";return this.matchesMcpPattern({pattern:o,providerIdentifier:t,toolName:r,logLabel:"matchesMcpEntry"})}matchesWebFetchEntry(e,t){const r=e.match(/^\s*WebFetch\s*\((.*)\)\s*$/);return!!r&&Xv(t,r[1]?.trim()??"")}matchesMcpEntryBare({pattern:e,providerIdentifier:t,toolName:r}){return this.matchesMcpPattern({pattern:e,providerIdentifier:t,toolName:r,logLabel:"matchesMcpEntryBare"})}isMcpInTeamAllowlist(e,{providerIdentifier:t,toolName:r,annotations:n}){if(e.mcpToolAllowlist.some((e=>this.matchesMcpEntryBare({pattern:e,providerIdentifier:t,toolName:r}))))return!0;const o=this.findTeamMcpServerPolicy(e,t);return void 0!==o&&"reads"===o.mode&&Wb(o,{name:r,annotations:n})}findTeamMcpServerPolicy(e,t){for(const r of e.serverPolicies??[])if(this.matchesMcpEntryBare({pattern:`${r.name}:*`,providerIdentifier:t,toolName:""}))return r.policy}async isMcpExplicitlyDenied(e,t,r){return(await this.getPermissions()).deny.some((e=>this.matchesMcpEntry(e,t,r)))}async isComputerUseAppSaved(e){return(await this.getPermissions()).allow.some((t=>t.match(/^\s*Mcp\s*\((.*)\)\s*$/)?.[1]?.trim().toLowerCase()===e))}async isMcpExplicitlyAllowed(e,t,r){return(await this.getPermissions()).allow.some((e=>this.matchesMcpEntry(e,t,r)))}}var s_=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const i_=65536,a_=1048576,c_=(0,d.h)("LocalReadExecutor"),l_=async(e,t,r,n)=>{const o=setTimeout((()=>{c_.warn(e,`[watchdog, LocalReadExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function u_(e){return BigInt(Math.min(e,4294967295))}async function d_(e,t){if(0===t)return(0,xo.readFile)(e);if(t>2147483647)throw new RangeError(`File size (${t}) is greater than 2 GiB`);const r=await(0,xo.open)(e,"r");try{const e=Buffer.allocUnsafe(t);let n=0;for(;n=32&&e<=126||9===e||10===e||13===e}function f_(e){if(e.length>=2){if(255===e[0]&&254===e[1])return"utf-16le";if(254===e[0]&&255===e[1])return"utf-16be"}const t=Math.min(4096,e.length);if(t<16)return"utf-8";let r=0,n=0;for(let o=0;o+1=8&&r>=4*Math.max(1,n)?"utf-16le":n>=8&&n>=4*Math.max(1,r)?"utf-16be":"utf-8"}const m_=Buffer.from("\n---\n");function g_(e,t){const r=e.length;if(r<2*m_.length)return r;if(10!==e[r-1]||45!==e[r-2]||45!==e[r-3]||45!==e[r-4]||10!==e[r-5])return r;const n=Math.max(t,r-4096),o=e.lastIndexOf(m_,r-m_.length-1);return-1===o||o126))return!1}const t=e.split("\n").filter((e=>e.length>0));if(t.length<2||t.length>3)return!1;const r=t[0],n=t[t.length-1];return!(!/^(exit_code: (?:-?\d+|unknown)|error: .+)$/.test(r)||!n.startsWith("ended_at: ")||3===t.length&&!/^elapsed_ms: \d+$/.test(t[1]))}(e.subarray(o+m_.length,r-4).toString("utf-8"))?o:r}const w_=[Buffer.from("%PDF-","ascii"),Buffer.from([208,207,17,224,161,177,26,225]),Buffer.from([80,75,3,4]),Buffer.from([80,75,5,6]),Buffer.from([80,75,7,8]),Buffer.from([127,69,76,70]),Buffer.from([254,237,250,206]),Buffer.from([254,237,250,207]),Buffer.from([206,250,237,254]),Buffer.from([207,250,237,254]),Buffer.from([77,90,144]),Buffer.from([0,97,115,109]),Buffer.from([137,80,78,71,13,10,26,10]),Buffer.from([255,216,255]),Buffer.from("GIF87a","ascii"),Buffer.from("GIF89a","ascii"),Buffer.from("SQLite format 3\0","ascii"),Buffer.from([31,139]),Buffer.from("BZh","ascii"),Buffer.from([253,55,122,88,90,0]),Buffer.from([40,181,47,253]),Buffer.from([55,122,188,175,39,28]),Buffer.from([82,97,114,33,26,7,0]),Buffer.from([82,97,114,33,26,7,1,0])];function y_(e){return new Xy.sV({result:{case:"invalidFile",value:new Xy.cW({path:e,reason:"File content is binary data, not text"})}})}function v_(e,t,r){if(void 0===r.offset&&void 0===r.limit)return{applied:!1};if(t)return{applied:!1};const n=r.offset??1,o=r.limit??(n<0?Math.abs(n):e),s=n<0?Math.max(0,e+n):Math.max(0,n-1);if(s>=e)return{applied:!1};const i=Math.min(e,s+o),a=b_(s,e),c=b_(i,e);return{applied:!0,start:a,end:Math.max(a,c)}}function b_(e,t){if(Number.isNaN(e)||0===e)return 0;if(e===Number.POSITIVE_INFINITY)return t;if(e===Number.NEGATIVE_INFINITY)return 0;const r=Math.trunc(e);return r<0?Math.max(t+r,0):Math.min(r,t)}function S_(e){return-1===e.indexOf("\r\n")?e:e.replaceAll("\r\n","\n")}function k_(e,t,r,n,o,s){if(n>=o)return{from:0,to:0};let i=0,a=0,c=0===n,l=0;for(;ia&&13===r(t)?t-1:t};l=t+1}return c?{from:a,to:t}:{from:t,to:t}}function __(e,t,r){const n=k_((t=>e.indexOf("\n",t)),e.length,(t=>e.charCodeAt(t-1)),t,r,!1);return 0===n.from&&n.to===e.length?e:n.from>=n.to?"":e.slice(n.from,n.to)}function C_(e,t,r,n,o){if(t>=r)return{text:"",truncated:!1};const s=n>=0?n+3:-1;let i=t;if(n>=0&&i>=n&&i=r)return{text:"",truncated:!1};const a=function(e,t,r,n){if(r>=n)return n;if(r<=t)return t;const o=Math.max(t,r-3);let s=r;for(;s>o;){if(128!=(192&(e[s]??0)))return s;s--}return 192&~(e[s]??0)?r:s}(e,i,Math.min(r,i+3*(o+1)+3),r);let c=S_(function(e,t,r,n){if(t>=r)return"";if(n<0)return e.toString("utf8",t,r);const o=n+3;return r<=n||t>=o?e.toString("utf8",t,r):t>=n&&r<=o?"":(to?e.toString("utf8",Math.max(t,o),r):"")}(e,i,a,n));const l=c.length>o||ao&&(c=Jo(c,o)),{text:c,truncated:l}}function E_(e,t,r,n){if(t>=r)return{text:"",truncated:!1};const o=Math.min(r,t+2*n+1);let s=S_(e.slice(t,o));const i=s.length>n||on&&(s=Jo(s,n)),s.lengthn?{text:e.text+Jo(t,n),truncated:!0}:{text:e.text+t,truncated:e.truncated}}function P_(e,t){if(e.truncated)return e;const r=x_(e,t);return{text:r.text,truncated:r.truncated}}function R_(e,t,r){let n=e;return t.forEach(((e,t)=>{const o=function(e,t){const{line:r,hasNewline:n}=e;return t&&n&&r.text.endsWith("\r")?{...r,text:r.text.slice(0,-1)}:r}(e,r);t>0&&(n=x_(n,"\n")),n=x_(n,o.text),o.truncated&&(n={text:n.text,truncated:!0})})),n}function I_(e){const t=e.toLowerCase();return"utf-8"===t?"utf8":"utf-8-bom"===t||"utf-8 bom"===t?"utf8bom":"latin-1"===t?"latin1":t}function T_(e){return void 0===e.maxChars||void 0!==e.offset||void 0!==e.limit?Ks:Math.min(Ks,e.maxChars+2)}function A_(e,t,r){if(!t||void 0===r.maxChars||e.length-1<=r.maxChars)return e;const n=e.charCodeAt(e.length-1);return n>=55296&&n<=56319?e.slice(0,-1):e}class $_ extends Error{constructor(){super("Invalid UTF-8 while streaming read"),this.name="InvalidUtf8Error"}}function M_(e){for(let t=1;t<=Math.min(3,e.length);t++){const r=e[e.length-t]??0;if(128!=(192&r))return D_(r)>t?t:0}return 0}function D_(e){return e>=240?4:e>=224?3:e>=192?2:1}class O_{constructor(e,t,r){this.previousEndsWithCr=e,this.carry=t,this.strict=r,this.lines=0,this.crlfCount=0,this.lfOnlyCount=0,this.continuesLine=t.length>0}count(e){this.strict&&this.validate(e),0===this.lines&&e.length>0&&10!==e[0]&&(this.continuesLine=!0);for(let t=e.indexOf(10);-1!==t;t=e.indexOf(10,t+1))(t>0?13===e[t-1]:this.previousEndsWithCr)?this.crlfCount++:this.lfOnlyCount++,this.lines++;e.length>0&&(this.previousEndsWithCr=13===e[e.length-1])}finish(){if(this.strict&&this.carry.length>0)throw new $_}validate(e){let t=e;if(this.carry.length>0){const r=D_(this.carry[0]??0)-this.carry.length;if(e.length0&&(0,n.isUtf8)(e.subarray(0,e.length-t))?"utf8_cut":"utf8_invalid"}(e)}async function L_(e,t){const r=t>0?Math.min(t,a_):a_,o=await d_(e,r);return o.length===t&&(0,n.isUtf8)(o)||ui(new Vs.TextDecoder("utf-8",{fatal:!1}).decode(o,{stream:o.length===a_&&o.length!==t}))?{kind:"lossyUtf8",cacheEncoding:"utf8"}:{kind:"iconv",decoderEncoding:"latin1",cacheEncoding:"latin1"}}async function j_(e){const t=await(0,xo.stat)(e),r=await zi(e);if(r.isBinaryFile)return;const n=F_({file:e,stats:t,format:r},void 0);if("iconv"===n.kind)return n.decoderEncoding;const o=await L_(e,t.size);return"iconv"===o.kind?o.decoderEncoding:void 0}async function U_(e,{file:t,stats:r},n,o,s){const i=r.size,a=void 0!==n.offset||void 0!==n.limit,c=(n.offset??1)<0,l=n.offset??1,u=Math.max(0,l-1),d=void 0===n.limit?void 0:u+n.limit,h=c?Math.abs(l):0,p=a?1/0:n.maxChars??1/0,f=a&&!c?n.maxChars??1/0:1/0;let m=[],g=0,w=!1,y=0,v=!1,b=!(c||a&&u<=0),S=!1;const k=[];let _,C=0,E=!1,x=0,P=!1,R=[],I=0,T=0,A=0,$=!1,M={text:"",truncated:!1},D=!1,O=!1,F=0,N=0,L=0,j=!1,U=!1;const B=e=>{let t=e;return!j&&t.length>0&&(j=!0,65279===t.charCodeAt(0)&&(U=!0,t=t.slice(1))),t},W=(e,t)=>t&&13===e.text.charCodeAt(e.text.length-1),H=()=>P||E&&C>=Ks,q=()=>v||w&&g>=Ks,z=(e,t)=>{if(H())return;const r=k.length>0?1:0;let n=Ks-C;if(r>0){if(n<=0)return void(E=!0);n--}const o=e.text.length>n?{line:{text:Jo(e.text,n),truncated:!0},hasNewline:t}:{line:e,hasNewline:t};k.push(o),C+=r+(o.line.truncated?n:o.line.text.length),e.truncated&&(E=!0),o.line.truncated&&(E=!0),W(o.line,t)&&x++,C-x>f&&(P=!0,_=F)},G=(e,t)=>{if(q())return;const r=m.length>0?1:0;let n=Ks-g;if(r>0){if(n<=0)return void(w=!0);n--}const o=e.text.length>n?{line:{text:Jo(e.text,n),truncated:!0},hasNewline:t}:{line:e,hasNewline:t};m.push(o),g+=r+(o.line.truncated?n:o.line.text.length),(e.truncated||o.line.truncated)&&(w=!0),W(o.line,t)&&y++,g-y>p&&(v=!0,_=F)},V=(e,t)=>{e&&(t?N++:L++),F++},K=()=>{const e=R[I];void 0!==e&&(A-=e.line.text.length+1),R[I]=void 0,I=(I+1)%R.length,T--},J=(e,t,r)=>{const n=F;if(0===n&&(S=0===e.text.length),!c&&a&&b&&n>=u&&(b=!1,m=[]),b&&G(e,t),c){if(h>0)for(T===h&&K(),(e=>{if(T===R.length){const e=new Array(Math.min(h,Math.max(16,2*R.length)));for(let t=0;t1&&A>Ks;)K(),$=!0}else a&&n>=u&&(void 0===d||n!(D||(!b||q())&&(!a||0!==F)&&!(c?h>0:!(!a||H())&&F>=u&&F<(d??1/0))),X=()=>{const e=M.text.length-1;if(a){const t=!c&&F>=u&&F<(d??1/0),r=k.length>0?1:0;if(!t||C-x+r+e<=f)return;z(M,!1)}else{const t=m.length>0?1:0;if(g-y+t+e<=p)return;G(M,!1)}M={text:"",truncated:!1},D=!0};let Q;const Y=e=>{if(void 0===n.maxChars||c)return;if(!(a?H()||F>=(d??1/0):q()))return;const t=e.subarray(e.length-M_(e));return Q=new O_(ee,Buffer.from(t),"strictUtf8"===o.kind),Q};let ee=!1;for await(const r of async function*(e,t,r,n,o){const s=function(e){return e>0?{start:0,end:e-1}:{}}(n);if("strictUtf8"===r.kind||"lossyUtf8"===r.kind){const n=new Vs.TextDecoder("utf-8",{fatal:"strictUtf8"===r.kind,ignoreBOM:!0}),i=(0,Ro.createReadStream)(t,{highWaterMark:i_,signal:e.signal,...s});let a;try{for await(const e of i){if(void 0!==a){a.count(e);continue}const t=n.decode(e,{stream:!0});t.length>0&&(yield t),e.length>=4&&(a=o?.(e))}if(void 0!==a)return void a.finish();const e=n.decode();e.length>0&&(yield e)}catch(e){if(e instanceof TypeError)throw new $_;throw e}return}const i=(0,Ro.createReadStream)(t,{highWaterMark:i_,signal:e.signal,...s}).pipe(Js.decodeStream(r.decoderEncoding));for await(const e of i)yield"string"==typeof e?e:String(e)}(e,t,o,i,Y)){const e=B(r);let t=0,n=e.indexOf("\n",t);for(;-1!==n;){const r=n>t?13===e.charCodeAt(n-1):ee;Z()?(M=P_(M,e.slice(t,n)),J(M,!0,r)):(D&&n>t&&(O=!0),V(!0,r)),M={text:"",truncated:!1},D=!1,ee=!1,t=n+1,n=e.indexOf("\n",t)}t0&&N/te*100>=5,ne="utf8"===o.cacheEncoding&&U?"utf8bom":o.cacheEncoding;s&&ta(t,r,ne);const oe=Math.min(F,a?d??1/0:1/0),se=void 0!==_&&(O||oe>_+1),ie=(n.maxChars??1/0)+i_,ae=e=>e.text.length>ie?{text:Jo(e.text,ie),truncated:!0}:e,ce=()=>R_({text:"",truncated:w||se},m,re);if(!a){const e=ae(ce());return{content:e.text,totalLines:F,truncated:e.truncated,rangeApplied:!1}}if(F<=1&&S)return{content:"",totalLines:F,truncated:!1,rangeApplied:!1};if(c){const e=n.limit??h,t=[];for(let e=0;e=F){const e=ce();return{content:e.text,totalLines:F,truncated:e.truncated,rangeApplied:!1}}const le=ae(R_({text:"",truncated:E||se},k,re));return{content:le.text,totalLines:F,truncated:le.truncated,rangeApplied:!0}}class B_{constructor(e,t,r){this.permissionsService=e,this.workspacePath=t,this.terminalReads=new Ql,this.mcpStateAccessor=r?.mcpStateAccessor,this.useStreamingRead=r?.useStreamingRead,this.pendingDecisionProvider=r?.pendingDecisionProvider,this.encodingSlices=r?.encodingSlices}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,D.VI)(e.withName("LocalReadExecutor.execute")),!1);const o=t.path;if(""===o.trim())return new Xy.sV({result:{case:"error",value:new Xy.F_({path:o,error:rs})}});const i=(0,ts.o1)(o,this.workspacePath),a=await l_(e,"permissionsService.shouldBlockFileRead",3e3,(()=>Yk(this.permissionsService,i)));if(a){const r=await l_(e,"resolveFileReadBlock",3e3,(()=>async function(e,t){return await ed(e,{onNeedsApproval:async(e,r)=>{const n=t.pendingDecisionProvider?.requestReadApproval?.bind(t.pendingDecisionProvider);if("fileRead"!==r.type||!n)return{kind:"denied",message:"Blocked by permissions configuration"};const o=await n({type:Bw.Read,details:{path:r.path,reason:e},toolCallId:t.toolCallId});return o.approved?null:{kind:"rejected",reason:o.reason}},onUserRejected:e=>({kind:"rejected",reason:e}),onPermissionDenied:e=>({kind:"denied",message:e})})??{kind:"proceed"}}(a,{pendingDecisionProvider:this.pendingDecisionProvider,toolCallId:t.toolCallId})));if("rejected"===r.kind)return new Xy.sV({result:{case:"rejected",value:new Xy.f4({path:i,reason:r.reason??""})}});if("denied"===r.kind)return new Xy.sV({result:{case:"permissionDenied",value:new Xy.lW({path:i})}})}void 0!==this.mcpStateAccessor&&Vy(e,this.mcpStateAccessor,i);try{const r=await l_(e,"stat",3e3,(()=>(0,xo.stat)(i)));if(r.isDirectory())return new Xy.sV({result:{case:"invalidFile",value:new Xy.cW({path:i,reason:"Path is a directory, not a file"})}});if(!r.isFile())return new Xy.sV({result:{case:"invalidFile",value:new Xy.cW({path:i,reason:"Path is neither a file nor a directory"})}});const o=function(e){return null!==function(e){const t=sh(e,"terminals");if(!t||1!==t.remainingPath.length)return null;const r=t.remainingPath[0],n=/^(\d+)\.txt$/.exec(r);if(!n)return null;const o=Number.parseInt(n[1],10);return Number.isNaN(o)?null:{id:o}}(e)}(i),a=function(e){const t=sh(e,"agent-tools");return null!==t&&1===t.remainingPath.length&&t.remainingPath[0].endsWith(".txt")}(i);if(o||a)return await this.readTerminalFile(e,i,r,t,a&&!o);const c=await l_(e,"getFormatForFile",3e3,(()=>zi(i))),l=c.isImageFile,u=function(e){return".pdf"===(0,s.extname)(e).toLowerCase()}(i),d=ji(i);if(l){const t=await l_(e,"prepareImageForModel",3e3,(async()=>(async e=>{let t;try{t=await Bv(e)}catch(t){const r=await Wv(e);if("undecodable"===r.kind)return r;throw t}if(!0===t.reencoded)return{kind:"image",image:t};const r=await Wv(t.data);return"undecodable"===r.kind?r:{kind:"image",image:t}})(await(0,xo.readFile)(i))));return"undecodable"===t.kind?new Xy.sV({result:{case:"invalidFile",value:new Xy.cW({path:i,reason:(n=t.reason,`File is not a valid image: its data could not be decoded (${n}). A truncated or hand-copied file does this; write it again from the original bytes with code.`)})}}):new Xy.sV({result:{case:"success",value:new Xy.mE({path:i,output:{case:"data",value:t.image.data},totalLines:0,fileSize:u_(r.size),truncated:!1})}})}if(u){const t=await l_(e,"readPdfBinary",3e3,(()=>(0,xo.readFile)(i)));return new Xy.sV({result:{case:"success",value:new Xy.mE({path:i,output:{case:"data",value:t},totalLines:0,fileSize:u_(r.size),truncated:!1})}})}if(c.isBinaryFile&&d){if(void 0!==t.maxVideoBytes&&r.size>t.maxVideoBytes)return new Xy.sV({result:{case:"success",value:new Xy.mE({path:i,totalLines:0,fileSize:u_(r.size),truncated:!0})}});const n=await l_(e,"readBinaryFile",3e3,(()=>(0,xo.readFile)(i)));return new Xy.sV({result:{case:"success",value:new Xy.mE({path:i,output:{case:"data",value:n},totalLines:0,fileSize:u_(r.size),truncated:!1})}})}if(c.isBinaryFile)return y_(i);{const n=this.useStreamingRead,o=!n||await l_(e,"useStreamingRead",3e3,(()=>n()));if(o||r.size>Ks){const n=await l_(e,"readTextStreaming",7e3,(()=>async function(e,t,r,n){const o=F_(t,r.encodingHint);try{return{...await U_(e,t,r,o,n),decoder:o.kind}}catch(o){if(o instanceof $_){const o=await L_(t.file,t.stats.size);return{...await U_(e,t,r,o,n),decoder:o.kind}}throw o}}(e,{file:i,stats:r,format:c},t,o))),s=A_(n.content,n.truncated,t);return Wl(this.encodingSlices,e)&&this.recordStreamedRead(e,i,r.size,n,s),new Xy.sV({result:{case:"success",value:new Xy.mE({path:i,output:{case:"content",value:s},totalLines:n.totalLines,fileSize:u_(r.size),truncated:n.truncated,rangeApplied:n.rangeApplied})}})}const s=await l_(e,"readText",3e3,(()=>Bi(i,t.encodingHint))),a=await l_(e,"countLines",3e3,(()=>Xs(s))),l=function(e,t,r){const n=v_(t,""===e,r);return n.applied?n.start>=n.end?{content:"",rangeApplied:!0}:{content:__(e,n.start,n.end),rangeApplied:!0}:{content:e,rangeApplied:!1}}(s,a,t);let u=l.content,d=!1;const h=T_(t);return u.length>h&&(u=A_(u.substring(0,h),!0,t),d=!0),u.length16777216)return"other_encoding";try{return r=await d_(e,t),!(0,n.isAscii)(r)&&(0,n.isUtf8)(r)?"utf8_as_other":"other_encoding"}catch{return"other_encoding"}var r}(t,r)),ru(this.encodingSlices,e,{layer:"exec_read",evidence:a,partial:o.rangeApplied||o.truncated},i)}catch{}}async readTerminalFile(e,t,r,n,o){const s=await l_(e,"readTerminalFile",3e3,(()=>d_(t,r.size)));if(o&&(i=s,w_.some((e=>function(e,t){return e.length>=t.length&&e.subarray(0,t.length).equals(t)}(i,e)))))return y_(t);var i;const a=function(e,t,r=8388608){if(0===e.length)return{content:"",totalLines:1,rangeApplied:!1,truncated:!1};const n=h_(e),o=g_(e,n);if("utf-8"!==f_(e.subarray(n,o)))return function(e,t,r){const n=0===e.length,o=function(e){let t=0,r=0;const n=e.length;for(;r=s.end)return{content:"",totalLines:o,rangeApplied:!0,truncated:!1};const i=k_((t=>e.indexOf("\n",t)),e.length,(t=>e.charCodeAt(t-1)),s.start,s.end,!0),a=E_(e,i.from,i.to,r);return{content:a.text,totalLines:o,rangeApplied:!0,truncated:a.truncated}}(function(e){const t=h_(e),r=t>0?e.subarray(0,t).toString("utf-8"):"",n=g_(e,t),o=nr?-1:239===e[t]&&187===e[t+1]&&191===e[t+2]?t:-1}(e,n,o);return function(e,t,r,n){const o=e.length-(t>=0?3:0)==0,s=function(e){let t=0,r=0;const n=e.length;for(;r=i.end)return{content:"",totalLines:s,rangeApplied:!0,truncated:!1};const a=k_((t=>e.indexOf(10,t)),e.length,(t=>e[t-1]??0),i.start,i.end,!0),c=C_(e,a.from,a.to,t,n);return{content:c.text,totalLines:s,rangeApplied:!0,truncated:c.truncated}}(e,s,t,r)}(s,n,T_(n)),c=A_(a.content,a.truncated,n);return Wl(this.encodingSlices,e)&&(o||this.terminalReads.firstRead(n.toolCallId,t))&&tu(this.encodingSlices,e,{layer:o?"exec_read":"exec_terminal_context",evidence:N_(s),partial:a.rangeApplied||a.truncated},c),new Xy.sV({result:{case:"success",value:new Xy.mE({path:t,output:{case:"content",value:c},totalLines:a.totalLines,fileSize:u_(r.size),truncated:a.truncated,rangeApplied:a.rangeApplied})}})}}function W_(e){return Buffer.from(e,"utf16le").toString("utf16le")}var H_=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},q_=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function z_(e){return`Path '${e}' could not be verified while resolving symlinks. This can happen when access is denied or the path contains a symlink loop.`}function G_(e){return`Path '${e}' is neither a file nor a directory`}async function V_(e){const t=await(0,xo.stat)(e).catch((()=>{}));return void 0!==t&&!t.isFile()&&!t.isDirectory()}function K_(e,t,r){const n=function(e,t){let r;for(const n of t)(0,ts.ZU)({basePath:n,targetPath:e})&&(void 0===r||n.length>r.length)&&(r=n);return r}((0,s.resolve)(e,t),r);return void 0===n||n===e}class J_ extends Error{}function Z_(e){const t=new AbortController,r=setTimeout((()=>t.abort()),e);return{signal:t.signal,clear:()=>clearTimeout(r)}}function X_(e){switch(e.result.case){case"content":return e.result.value.matches.length>0;case"files":return e.result.value.files.length>0;case"count":return e.result.value.counts.length>0;case void 0:return!1;default:{const t=e.result;throw new Error(`Unknown grep result: ${String(t)}`)}}}function Q_(e){switch(e){case"content":return new Ry.vD({result:{case:"content",value:new Ry.Zp({ripgrepTruncated:!0})}});case"files_with_matches":return new Ry.vD({result:{case:"files",value:new Ry.T7({ripgrepTruncated:!0})}});case"count":return new Ry.vD({result:{case:"count",value:new Ry.xA({ripgrepTruncated:!0})}});default:throw new Error(`Unknown output mode: ${String(e)}`)}}function Y_(e){return"success"===e.result.case&&Object.values(e.result.value.workspaceResults).some((e=>!0===e.result.value?.clientTruncated))}function eC(e,t,r){let n=Buffer.concat(e);t&&(n=n.subarray(0,n.lastIndexOf(10)+1)),r?.note(n);const o=n.toString("utf8");return o.includes("�")?{stdout:o,stdoutBytes:n}:{stdout:o}}function tC(e){return/^(utf-?16|ucs-?2)/i.test(e)}const rC=(0,d.h)("local-exec/grep"),nC=(0,h.Pu)("local_exec.grep.deadline_reached",{description:"Grep and Glob searches the search deadline stopped, by whether they kept what was found",labelNames:["output_mode","outcome","streaming"]}),oC=(0,h.Pu)("local_exec.grep.newest_first_stat_fallback",{description:"Grep and Glob results left in ripgrep's order because stat was too slow to sort them",labelNames:["output_mode"]}),sC=(0,h.v5)("local_exec.grep.rg.spawn_ms",{description:"Time to start the ripgrep process for one Grep or Glob search",labelNames:["sandboxed"]}),iC=(0,h.v5)("local_exec.grep.rg.search_ms",{description:"Time ripgrep took to search and exit after it started, for runs it finished",labelNames:["output_mode","sandboxed"]});function aC(e){return e instanceof Error&&e.message.includes("ENOENT")&&e.message.includes("spawn")}function cC(e){try{return(0,Ro.existsSync)(e)}catch{return"check_failed"}}function lC(e){if("object"==typeof e&&null!==e&&"errno"in e){const t=e.errno;if("number"==typeof t)return t}}function uC(e,t){if("object"==typeof e&&null!==e)return"syscall"===t&&"syscall"in e&&"string"==typeof e.syscall?e.syscall:"path"===t&&"path"in e&&"string"==typeof e.path?e.path:void 0}function dC(e,t,r,n){return{...pC(e),...n,cwd:t,cwdExists:cC(t),errorMessage:Cc(r),errorCode:_c(r),errno:lC(r),syscall:uC(r,"syscall"),errorPath:uC(r,"path")}}function hC(e){return new Error(`Path does not exist: ${e}`)}function pC(e){const t={rgPath:e,platform:process.platform,arch:process.arch,pid:process.pid,uptimeSeconds:Math.round(process.uptime()),execPath:process.execPath};try{t.rgPathExists=(0,Ro.existsSync)(e)}catch(e){t.rgPathExists=!1,t.rgPathExistsError=e instanceof Error?e.message:String(e)}try{const r=(0,Ro.lstatSync)(e);t.rgIsSymlink=r.isSymbolicLink(),r.isSymbolicLink()&&!t.rgPathExists&&(t.rgBrokenSymlink=!0)}catch{t.rgLstatFailed=!0}const r=(0,s.dirname)(e);try{t.parentDirExists=(0,Ro.existsSync)(r),t.parentDirExists&&(t.parentDirContents=(0,Ro.readdirSync)(r).slice(0,50))}catch(e){t.parentDirError=e instanceof Error?e.message:String(e)}const n=(0,s.dirname)(r);try{t.grandparentDirExists=(0,Ro.existsSync)(n),t.grandparentDirExists&&(t.grandparentDirContents=(0,Ro.readdirSync)(n).slice(0,50))}catch(e){t.grandparentDirError=e instanceof Error?e.message:String(e)}if(t.rgPathExists)try{const r=(0,Ro.statSync)(e);t.rgFileSize=r.size,t.rgFileMode=r.mode.toString(8),t.rgIsFile=r.isFile(),t.rgModifiedMs=r.mtimeMs}catch(e){t.rgStatError=e instanceof Error?e.message:String(e)}const o="node_modules.asar.unpacked";if(e.includes(o)){const r=e.split(o)[0];if(r){const n=r.concat("node_modules.asar");try{t.asarExists=(0,Ro.existsSync)(n)}catch{t.asarExists="check_failed"}const i=r.concat(o);try{if(t.asarUnpackedDirExists=(0,Ro.existsSync)(i),t.asarUnpackedDirExists){const r=(0,s.dirname)((0,s.dirname)(e));t.ripgrepPkgDirExists=(0,Ro.existsSync)(r)}}catch{t.asarUnpackedDirExists="check_failed"}}}return t}class fC{constructor(e,t,r,n){this.ignoreService=e,this.grepProvider=t,this.workspacePath=r,this.stdoutDecodes=new WeakMap;const o=Array.isArray(this.workspacePath)?this.workspacePath[0]:this.workspacePath;this.singleWorkspacePath=Array.isArray(this.workspacePath)&&this.workspacePath.length>1?void 0:o,this.mcpStateAccessor=n?.mcpStateAccessor,this.permissionsService=n?.permissionsService,this.useStreamingGrep=n?.useStreamingGrep,this.encodingSlices=n?.encodingSlices}computeRelativeTarget(e,t){const r=(0,ts.o1)(e,this.singleWorkspacePath??t);return r===t?".":(0,s.relative)(t,r)}isRootIndependentSearchPath(e){return(0,s.isAbsolute)(e)||/^~(?=$|[/\\])/.test(e)||e.startsWith("file://")}resolveSearchTargets(e,t){const r=this.isRootIndependentSearchPath(e);return t.map((t=>{const n=(0,s.resolve)(t);return{root:t,resolvedRoot:n,target:(0,ts.o1)(e,r?void 0:n)}}))}findOutsideTargets(e,t){if(void 0===e||""===e)return;const r=this.resolveSearchTargets(e,t);return r.some((({resolvedRoot:e,target:t})=>(0,ts.BJ)(t,e)))?void 0:[...new Set(r.map((({target:e})=>e)))]}searchTarget(e,t){if(!t.path)return".";const r=(0,ts.o1)(t.path,this.singleWorkspacePath??e);return(0,ts.BJ)(r,(0,s.resolve)(e))?this.computeRelativeTarget(t.path,e):r}sortsAfterRipgrep(e,t,r){return void 0===t.sort&&(r?!0!==t.sortAscending:(0,s.isAbsolute)(this.searchTarget(e,t)))}async buildArgs(e,t,r,n){const o=[],s=function(e,t){return"files_with_matches"===t&&""===e.pattern&&Boolean(e.glob)}(t,r),i=await ma(await this.ignoreService.listCursorIgnoreFilesByRoot(e));for(const e of i)o.push("--cursor-ignore",e);if("content"===r)o.push("--line-number","--with-filename","--no-heading","-0"),void 0!==t.contextBefore&&o.push("--before-context",String(t.contextBefore)),void 0!==t.contextAfter&&o.push("--after-context",String(t.contextAfter)),o.push("--max-columns",String(1e3),"--max-columns-preview"),void 0!==t.context&&void 0===t.contextBefore&&void 0===t.contextAfter&&o.push("--before-context",String(t.context),"--after-context",String(t.context));else if("files_with_matches"===r)o.push(s?"--files":"-l");else{if("count"!==r)throw new Error(`Unknown output mode: ${String(r)}`);o.push("-c","--with-filename")}!0===t.caseInsensitive?o.push("--ignore-case"):o.push("--case-sensitive"),t.type&&o.push("--type",t.type),t.glob&&(o.push("--iglob",t.glob),s&&o.push("--iglob","!**/.git")),t.multiline&&o.push("--multiline","--multiline-dotall");const a=n?"none":t.sort??"modified";if(n&&o.push("--line-buffered"),"none"!==a){const e=!0===t.sortAscending?"--sort":"--sortr";o.push(e,a)}o.push("--no-config","--color=never"),o.push("--hidden"),o.push("--follow");const c=this.searchTarget(e,t);if(t.path){const t=await async function(e){try{if(!(await(0,xo.stat)(e)).isFile())return;const{encoding:t}=await zi(e);return tC(t)?t.toLowerCase():void 0}catch{return}}((0,ts.o1)(c,e));void 0!==t&&o.push("--encoding",t)}return s||o.push("--regexp",t.pattern),o.push("--"),o.push(c),o}async filterBlockedFiles(e,t){const r=new Map,n=await(this.permissionsService?.getFileReadBoundaryBlocker?.()),o=[];for(const s of e){const e=(0,ts.o1)(s.file,t),i=await xc(e);null===i||await this.isPostRipgrepBlocked(i,r)||void 0!==n&&await n(e,i)||o.push(s)}return o}async isPostRipgrepBlocked(e,t){const[r,n]=await Promise.all([this.ignoreService.isCursorIgnored(e,t),this.ignoreService.isRepoBlocked(e)]);return r||n}throwOnRipgrepFailure(e,t,r){if((""!==e.stderr||2===e.exitCode)&&""===e.stdout.trim()&&!function({stderr:e,target:t}){return e.trim().split(/\r?\n/).every((e=>{if(/^rg: .+: line \d+: /.test(e))return!0;const r=/^rg: (.+?): .*\(os error (?:13|5|2|1)\)$/.exec(e)?.[1]??/^rg: File system loop found: (.+) points to an ancestor /.exec(e)?.[1];return void 0!==r&&r!==t}))}({stderr:e.stderr,target:this.searchTarget(t,r)}))throw new Error(e.stderr||`ripgrep exited with code ${e.exitCode}`)}async orderNewestFirst(e,t,r,n,o){const s=await Zy(t,(e=>(0,ts.o1)(n(e),r)));return s.statTimedOut&&(rC.info(e,"newest_first.stat_timeout_fallback",{toolCallId:o.toolCallId,execId:o.execId,outputMode:o.outputMode,fileCount:t.length}),oC.increment(e,1,{output_mode:o.outputMode})),s.items}async keepNewestPage(e,t,r,n,o){return(await this.orderNewestFirst(e,t,r,n,o)).slice(0,fC.CLIENT_LIMIT_LINES)}async runFilesMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const d=H_(a,(0,D.VI)(e.withName("LocalGrepExecutor.runFilesMode")),!1),h=await this.buildArgs(t,r,"files_with_matches",n),p=await this.executeRg(d.ctx,t,h,void 0,o,s,i);this.throwOnRipgrepFailure(p,t,r);const f=(c=p.stdout,l=n?fC.HARD_MAX_OUTPUT_LINES:fC.CLIENT_LIMIT_LINES,u=fC.HARD_MAX_OUTPUT_LINES,function(e,t,r){const n=e.trim();if(""===n)return{files:[],totalFiles:0,clientTruncated:!1,ripgrepTruncated:!1};const o=new Iy;let s=0,i=0,a=0;for(;Ty(n,a,o);)a=o.nextStart,st?Buffer.from(n.slice(0,i)).toString():n,l=[];for(a=0;l.lengtht,ripgrepTruncated:s>=r}}(c,l,u)),m=f.totalFiles>fC.CLIENT_LIMIT_LINES;let g=f.files;n&&(g=await this.keepNewestPage(d.ctx,g,t,(e=>e),i),m&&(g=g.join("\0").split("\0")));const w=(await this.filterBlockedFiles(g.map((e=>({file:e}))),t)).map((({file:e})=>e)),y=g.length-w.length,v=new Ry.T7({files:w,totalFiles:Dy(f.totalFiles-y),clientTruncated:m,ripgrepTruncated:f.ripgrepTruncated||p.timedOut||p.stdoutByteCapped});return{result:new Ry.vD({result:{case:"files",value:v}}),timedOut:p.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{q_(a)}var c,l,u}async runCountMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const d=H_(a,(0,D.VI)(e.withName("LocalGrepExecutor.runCountMode")),!1),h=await this.buildArgs(t,r,"count",n),p=await this.executeRg(d.ctx,t,h,void 0,o,s,i);this.throwOnRipgrepFailure(p,t,r);const f=(c=p.stdout,l=n?fC.HARD_MAX_OUTPUT_LINES:fC.CLIENT_LIMIT_LINES,u=fC.HARD_MAX_OUTPUT_LINES,function(e,t,r){const n=e.trim();if(""===n)return{counts:[],totalFiles:0,totalMatches:0,clientTruncated:!1,ripgrepTruncated:!1};const o=[],s=new Iy;let i=0;for(;Ty(n,i,s);){const e=i,t=s.lineEnd;if(i=s.nextStart,t===e)continue;const r=n.lastIndexOf(":",t-1);if(rt,ripgrepTruncated:a>=r}}(c,l,u)),m=n?await this.keepNewestPage(d.ctx,f.counts,t,(e=>e.file),i):f.counts,g=await this.filterBlockedFiles(m,t),w=g.reduce(((e,t)=>e+t.count),0),y=m.length-g.length,v=m.reduce(((e,t)=>e+t.count),0)-w,b=new Ry.xA({counts:g.map((e=>new Ry.sS({file:e.file,count:Dy(e.count)}))),totalFiles:Dy(f.totalFiles-y),totalMatches:Dy(f.totalMatches-v),clientTruncated:f.totalFiles>fC.CLIENT_LIMIT_LINES,ripgrepTruncated:f.ripgrepTruncated||p.timedOut||p.stdoutByteCapped});return{result:new Ry.vD({result:{case:"count",value:b}}),timedOut:p.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{q_(a)}var c,l,u}async runContentMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const c=H_(a,(0,D.VI)(e.withName("LocalGrepExecutor.runContentMode")),!1),l=await this.buildArgs(t,r,"content",n),u=void 0!==r.context||void 0!==r.contextBefore||void 0!==r.contextAfter,d=fC.CLIENT_LIMIT_LINES*(u?2:1),h=await this.executeRg(c.ctx,t,l,d,o,s,i);this.throwOnRipgrepFailure(h,t,r);const p=await this.decodeLinesAsRead(c.ctx,h,t,i),{byFile:f,totalLines:m,totalMatchedLines:g,clientTruncated:w,ripgrepTruncated:y}=function(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{return H_(o,(0,D.VI)(n.withName("parseContentOutput")),!1),function(e,t,r){const n={byFile:new Map,totalLines:0,totalMatchedLines:0,totalFiles:0,clientTruncated:!1,ripgrepTruncated:!1};if(""===e.trim())return n;const o=new Map,s=new Set,i=new Iy;let a=0,c=0,l=0,u=0;for(;Ty(e,u,i);){const r=u,n=i.lineEnd;if(u=i.nextStart,l++,d=e,n-(h=r)==2&&45===d.charCodeAt(h)&&45===d.charCodeAt(h+1))continue;let p=-1;for(let t=r;t=n)continue;let m=0,g=0;for(;f57)break;m=10*m+(t-48),g++,f++}if(0===g||f>=n||!Number.isFinite(m))continue;const w=e.charCodeAt(f);if(58!==w&&45!==w)continue;const y=45===w;y||a++;const v=e.slice(r,p);if(s.has(v)||s.add(v),c>=t)continue;const b=e.slice(f+1,n);let S=o.get(v);void 0===S&&(S={file:v,matches:[]},o.set(v,S)),S.matches.push({lineNumber:m,content:b,isContextLine:y}),c++}var d,h;return{byFile:o,totalLines:Dy(l),totalMatchedLines:Dy(a),totalFiles:Dy(s.size),clientTruncated:c>=t,ripgrepTruncated:l>=r}}(e,t,r)}catch(e){o.error=e,o.hasError=!0}finally{q_(o)}}(p,fC.CLIENT_LIMIT_LINES,d,c.ctx),v=Array.from(f.values()),b=await this.filterBlockedFiles(v,t),S=v.filter((e=>!b.includes(e))),k=S.reduce(((e,t)=>e+t.matches.length),0),_=S.reduce(((e,t)=>e+t.matches.filter((e=>!e.isContextLine)).length),0),C=n?await this.orderNewestFirst(c.ctx,b,t,(e=>e.file),i):b,E=new Ry.Zp({matches:C.map((e=>new Ry.uI({file:e.file,matches:e.matches.map((e=>new Ry.dx({lineNumber:e.lineNumber,content:e.content,isContextLine:e.isContextLine})))}))),totalLines:Dy(m-k),totalMatchedLines:Dy(g-_),clientTruncated:w,ripgrepTruncated:y||h.timedOut||h.stdoutByteCapped});return{result:new Ry.vD({result:{case:"content",value:E}}),timedOut:h.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{q_(a)}}async decodeLinesAsRead(e,t,r,o){const s={stack:[],error:void 0,hasError:!1};try{const i=t.stdoutBytes;if(void 0===i)return t.stdout;const a=H_(s,(0,D.VI)(e.withName("LocalGrepExecutor.decodeLinesAsRead")),!1),c=function(e,t){const r=[],o=new Iy;let s=0,i=0,a=e.indexOf("�");for(;-1!==a&&Ty(e,s,o);){const{lineEnd:c,nextStart:l}=o,u=t.indexOf(10,i),d=-1===u?t.length:u+1;let h=-1===u?t.length:u;if(h>i&&-1!==u&&13===t[h-1]&&h--,ae.file)))],u=new Map,d=performance.now()+fC.LINE_ENCODING_TIMEOUT_MS;let h=0;for(;h{let d=!1,h=!1;const p=()=>{h||(h=!0,a.span.end())};if(e.signal.aborted)return p(),void u(new Error("Grep was cancelled"));if(o.aborted)return p(),void u(fC.ripgrepTimeoutError());let f;const m="insecure_none"===s.type?"false":"true",g=performance.now();let w=g;try{const e=s;f=(0,No.spawnInSandbox)((0,No.Ko)(),r,{cwd:t},e),w=performance.now(),0}catch(r){if(p(),aC(r)){const n=(0,No.Ko)();if(rC.error(e,"rg_diagnostics.spawn_throw",void 0,dC(n,t,r,i)),!1===cC(t))return u(hC(t))}return u(r)}const y=[],v=[];let b=0,S=0,k=0,_=!1,C=!1,E=!1;const x=()=>{if(!d)try{p(),E=!0;const e=eC(y,!0,this.stdoutDecodes.get(i));""===e.stdout?u(fC.ripgrepTimeoutError()):l({...e,stderr:"",exitCode:0,timedOut:!0,stdoutByteCapped:C}),f.kill()}catch{}};o.addEventListener("abort",x,{once:!0});const P=()=>{o.removeEventListener("abort",x),p(),u(new Error("Grep was cancelled"));try{f.kill()}catch{}};e.signal.addEventListener("abort",P,{once:!0}),f.stdout?.on("data",(e=>{if(!C&&!_)if(b+=e.length,b>c){C=!0;try{f.kill()}catch{}}else if(void 0!==n){let t=-1,r=0;for(let o=0;o=n)){t=o+1,_=!0;try{f.kill()}catch{}break}k+=r;const o=t>=0?e.subarray(0,t):e;y.push(o)}else y.push(e)})),f.stderr?.on("data",(e=>{S+=e.length,S<=c&&v.push(e)})),f.on("error",(r=>{if(o.removeEventListener("abort",x),e.signal.removeEventListener("abort",P),p(),aC(r)){const n=(0,No.Ko)();if(rC.error(e,"rg_diagnostics.spawn_enoent",void 0,dC(n,t,r,i)),!1===cC(t))return void u(hC(t))}u(r)})),f.on("close",(t=>{const r=performance.now()-w;d=!0,o.removeEventListener("abort",x),e.signal.removeEventListener("abort",P);const n=eC(y,C,E?void 0:this.stdoutDecodes.get(i)),s=Buffer.concat(v).toString("utf8");p(),l({...n,stderr:s,exitCode:t??0,timedOut:!1,stdoutByteCapped:C}),sC.histogram(e,w-g,{sandboxed:m}),C||_||o.aborted||e.signal.aborted||0!==t&&1!==t||iC.histogram(e,r,{output_mode:i.outputMode,sandboxed:m})}))}))}async checkOutsideTarget(e,t){if(1!==t.length||void 0===t[0])return{error:`Path '${e}' points to a different folder from each workspace root; use an absolute path`};const r=await xc(t[0]);return null===r?{error:z_(e)}:await this.ignoreService.isCursorIgnored(r)?{error:`Path '${e}' is filtered out by .cursorignore`}:await V_(t[0])?{error:G_(e)}:{resolvedTarget:r}}async execute(e,t,r){if(!Wl(this.encodingSlices,e))return this.search(e,t,r,void 0);const n=new nu,o=await this.search(e,t,r,n);return"success"===o.result.case&&tu(this.encodingSlices,e,{layer:"exec_grep",evidence:n.evidence(),partial:Y_(o)},o),o}async search(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{const a=H_(o,(0,D.VI)(e.withName("LocalGrepExecutor.execute")),!1),c=Array.isArray(this.workspacePath)?this.workspacePath:[this.workspacePath??process.cwd()],l=t.outputMode??"content";if("content"!==(i=l)&&"files_with_matches"!==i&&"count"!==i)throw new Error(`Unknown output mode: ${l}`);const u=l,d={toolCallId:t.toolCallId,execId:r?.execId,outputMode:u,targetPath:t.path,workspacePaths:c};void 0!==n&&this.stdoutDecodes.set(d,n);const h=ds(t.sandboxPolicy),p=this.grepProvider.getWorktreeGuardInfo?.(c);if((0,ts.fl)({targetPath:t.path,workspacePaths:c,mainWorktreePath:p?.mainWorktreePath}))return new Ry.Ud({result:{case:"error",value:new Ry.ts({error:ts.PS})}});const f=this.findOutsideTargets(t.path,c);let m=t,g=c;try{if(t.path&&void 0!==f){const r=await this.checkOutsideTarget(t.path,f);if("error"in r)return new Ry.Ud({result:{case:"error",value:new Ry.ts({error:r.error})}});void 0!==this.mcpStateAccessor&&Vy(e,this.mcpStateAccessor,r.resolvedTarget),g=c.slice(0,1),m=t.clone(),m.path=f[0]}else if(m.path){const t=[];let r=!1;for(const{root:n,resolvedRoot:o,target:s}of this.resolveSearchTargets(m.path,c)){if(!(0,ts.BJ)(s,o))continue;const i=await xc(s);if(null!==i)if(await this.ignoreService.isCursorIgnored(i))r=!0;else{if(await V_(s))return new Ry.Ud({result:{case:"error",value:new Ry.ts({error:G_(m.path)})}});t.push(n),void 0!==this.mcpStateAccessor&&Vy(e,this.mcpStateAccessor,i)}}if(0===t.length){const e=r?`Path '${m.path}' is filtered out by .cursorignore`:z_(m.path);return new Ry.Ud({result:{case:"error",value:new Ry.ts({error:e})}})}g=t}let r={};const n=void 0===f?await this.executeIndexedGrepWithTimeout(a.ctx,g,m,d):void 0;if(void 0!==n){r=n;for(const[e,t]of Object.entries(r)){const r=t.result;switch(r.case){case"content":r.value.matches=await this.filterBlockedFiles(r.value.matches,e);break;case"files":r.value.files=(await this.filterBlockedFiles(r.value.files.map((e=>({file:e}))),e)).map((({file:e})=>e));break;case"count":r.value.counts=await this.filterBlockedFiles(r.value.counts,e)}}}else{const e=await this.streamingEnabled(a.ctx,d),t=e?Z_(fC.MAIN_TIMEOUT_MS):void 0;let n=0,o=!1;try{for(const s of g){if(!0===t?.signal.aborted){r[s]=Q_(u),n++,o=!0;continue}if(!1===cC(s))return new Ry.Ud({result:{case:"error",value:new Ry.ts({error:`Path does not exist: ${s}`})}});const i=t??Z_(fC.MAIN_TIMEOUT_MS);try{const t=await this.runMode(a.ctx,u,s,m,e,i.signal,h,d);r[s]=t.result,t.timedOut&&n++}catch(t){if(!(t instanceof J_))throw t;if(r[s]=Q_(u),n++,o=!0,!e)break}finally{i!==t&&i.clear()}}}finally{t?.clear()}if(n>0){const t=o&&(!e||!Object.values(r).some(X_));if(this.reportDeadlineReached(a.ctx,d,{streaming:e,folderCount:g.length,stoppedFolderCount:n,outcome:t?"failed":"partial"}),t)throw fC.ripgrepTimeoutError()}}const o=function(e,t){if(t.length<=1)return e;const r=[...new Set(t.map((e=>(0,s.resolve)(e))))],n={};for(const[t,o]of Object.entries(e)){const e=(0,s.resolve)(t),i=t=>K_(e,t,r),a=o.result;switch(a.case){case"content":{const e=a.value,r=[];let o=0,s=0;for(const t of e.matches)i(t.file)?r.push(t):(o+=t.matches.length,s+=t.matches.filter((e=>!e.isContextLine)).length);const c=e.clone();c.matches=r,c.totalLines=Math.max(0,e.totalLines-o),c.totalMatchedLines=Math.max(0,e.totalMatchedLines-s),n[t]=new Ry.vD({result:{case:"content",value:c}});break}case"files":{const e=a.value,r=e.files.filter((e=>i(e))),o=e.clone();o.files=r,o.totalFiles=Math.max(0,e.totalFiles-(e.files.length-r.length)),n[t]=new Ry.vD({result:{case:"files",value:o}});break}case"count":{const e=a.value,r=[];let o=0;for(const t of e.counts)i(t.file)?r.push(t):o+=t.count;const s=e.clone();s.counts=r,s.totalFiles=Math.max(0,e.totalFiles-(e.counts.length-r.length)),s.totalMatches=Math.max(0,e.totalMatches-o),n[t]=new Ry.vD({result:{case:"count",value:s}});break}default:n[t]=o}}return n}(r,g),i=new Ry._0({pattern:m.pattern,path:void 0!==m.path&&this.isRootIndependentSearchPath(m.path)?(0,ts.o1)(m.path):m.path,outputMode:u,workspaceResults:o});return new Ry.Ud({result:{case:"success",value:i}})}catch(e){if(m.path){const e=(0,ts.o1)(m.path,this.singleWorkspacePath);try{await(0,xo.stat)(e)}catch(t){return new Ry.Ud({result:{case:"error",value:new Ry.ts({error:`Path does not exist: ${e}`})}})}}return new Ry.Ud({result:{case:"error",value:new Ry.ts({error:e instanceof Error?e.message:String(e)})}})}}catch(e){o.error=e,o.hasError=!0}finally{q_(o)}var i}}fC.MAIN_TIMEOUT_MS=25e3,fC.INDEXED_GREP_TIMEOUT_MS=25e3,fC.INDEXED_GREP_CONTEXT_TIMEOUT_MS=fC.INDEXED_GREP_TIMEOUT_MS+100,fC.HARD_MAX_OUTPUT_LINES=1e4,fC.CLIENT_LIMIT_LINES=2e3,fC.LINE_ENCODING_TIMEOUT_MS=2e3,Be.object({record_v:Be.number().int().nullish(),pid:Be.number().int().nonnegative().nullish(),version:Be.string().nullish(),started_at:Be.number().nullish(),control_sock:Be.string().nullish(),runtime_dir:Be.string().nullish(),data_dir:Be.string().nullish(),config_path:Be.string().nullish(),log_path:Be.string().nullish(),metrics_addr:Be.string().nullish(),exe:Be.string().nullish()}),Be.object({mountpoint:Be.string().nullish(),capabilities:Be.array(Be.string()).nullish(),nfs_transport:Be.string().nullish(),bind_ignored:Be.object({active:Be.array(Be.string()).nullish()}).passthrough().nullish()});const mC=Be.object({daemon_alive:Be.boolean().nullish(),mounts:Be.array(Be.unknown()).nullish(),data_plane:Be.object({enabled:Be.boolean().nullish()}).passthrough().nullish()});Be.object({daemon_alive:Be.boolean().nullish(),daemon_version:Be.string().nullish(),capabilities:Be.array(Be.string()).nullish()}),mC.extend({memory:Be.object({anon_bytes:Be.number()}).nullish().catch(null)});const gC=Be.number().int().nonnegative(),wC=Be.object({line_no:Be.number().int().positive(),kind:Be.enum(["match","before","after"]),text:Be.string().optional(),bytes:Be.string().regex(/^(?:[0-9a-fA-F]{2})*$/).optional(),truncated:Be.boolean().default(!1)}).refine((e=>void 0!==e.text||void 0!==e.bytes));Be.object({type:Be.literal("file"),path:Be.string(),lines:Be.array(wC)}),Be.object({type:Be.literal("summary"),files_searched:gC,more:Be.boolean(),stop_reason:Be.string().nullable(),skipped:Be.object({over_size:gC,size_unknown:gC,budget_exhausted:gC,fetch_failed:gC,unreadable:gC})}),Be.object({type:Be.string()}),(0,d.h)("local-exec/grove-grep"),(0,h.Pu)("local_exec.grep.grove",{description:"Grep searches Grove served, or declined to ripgrep, by decline reason",labelNames:["outcome","reason"]}),(0,h.v5)("local_exec.grep.grove.served_ms",{description:"Time Grove took to answer a Grep search it served"});var yC=r("../proto/dist/generated/agent/v1/ls_exec_pb.js"),vC=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},bC=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class SC{constructor(e,t,r){this.permissionsService=e,this.ignoreService=t,this.workspacePath=r}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{vC(r,(0,D.VI)(e.withName("LocalLsExecutor.execute")),!1).ctx;const n=(0,ts.o1)(t.path,this.workspacePath);try{let r;try{r=await(0,xo.stat)(n)}catch(e){return"ENOENT"===_c(e)?function(e){const t=sh(e,"terminals");return null!==t&&0===t.remainingPath.length}(n)?new yC.fv({result:{case:"error",value:new yC.uj({path:n,error:"No active terminals."})}}):new yC.fv({result:{case:"error",value:new yC.uj({path:n,error:`Path does not exist: ${n}`})}}):new yC.fv({result:{case:"error",value:new yC.uj({path:n,error:Cc(e)})}})}if(!r.isDirectory())return new yC.fv({result:{case:"error",value:new yC.uj({path:n,error:`Path is not a directory: ${n}`})}});const o=ds(t.sandboxPolicy),s=t.timeoutMs??5e3,i=e.withTimeout(s),{tree:a,didTimeout:c}=await this.getDirectoryTree(i,n,t.ignore,o);return c?new yC.fv({result:{case:"timeout",value:new yC.ze({directoryTreeRoot:a})}}):new yC.fv({result:{case:"success",value:new yC.PC({directoryTreeRoot:a})}})}catch(e){return new yC.fv({result:{case:"error",value:new yC.uj({path:n,error:e instanceof Error?e.message:"Unknown error occurred"})}})}}catch(e){r.error=e,r.hasError=!0}finally{bC(r)}}async getDirectoryTree(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{return vC(o,(0,D.VI)(e.withName("LocalLsExecutor.getDirectoryTree")),!1),await this.buildTreeFromRipgrepStream(e,t,r,n,2500)}catch(e){o.error=e,o.hasError=!0}finally{bC(o)}}async buildTreeFromRipgrepStream(e,t,r,n,o){const i={stack:[],error:void 0,hasError:!1};try{vC(i,(0,D.VI)(e.withName("LocalLsExecutor.buildTreeFromRipgrepStream")),!1);const a=(0,s.resolve)(t),c=new yC.vq({absPath:a,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!0,fullSubtreeExtensionCounts:{}}),l=new Map;l.set(a,c);const u={charactersUsed:a.length,budgetExceeded:!1},[d,h]=await Promise.all([this.ignoreService.listCursorIgnoreFilesByRoot(t),this.ignoreService.getRepoBlockExcludeGlobs(t)]),p=[...r,...h],{lines:f,didTimeout:m}=ya(e,{root:t,excludeGlobs:p,caseSensitive:!0,cursorIgnoreFiles:d,sandboxPolicy:n,source:"ls"});for await(const e of f){if(!e)continue;const r=(0,s.resolve)(t,e),n=await xc(r);null===n||await this.ignoreService.isCursorIgnored(n)||await this.ignoreService.isRepoBlocked(n)||this.addPathToTree(r,a,l,u,o)}return this.sortTreeChildren(c),{tree:c,didTimeout:await m}}catch(e){i.error=e,i.hasError=!0}finally{bC(i)}}addPathToTree(e,t,r,n,o){const i=(0,s.basename)(e),a=(0,s.dirname)(e);this.ensureDirectoryPath(a,t,r,n.budgetExceeded);const c=r.get(a);if(!c)return;const l=i.length;if(!n.budgetExceeded&&n.charactersUsed+l<=o){const e=new yC.ur({name:i});c.childrenFiles.push(e),n.charactersUsed+=l}else{if(!n.budgetExceeded){n.budgetExceeded=!0;let e=a;for(;e.startsWith(t);){const t=r.get(e);t&&(t.childrenWereProcessed=!1);const n=(0,s.dirname)(e);if(n===e)break;e=n}}let o=n.overflowChain;if(n.overflowDir!==a||void 0===o){o=[];let e=a;for(;e.startsWith(t);){const t=r.get(e);t&&o.push(t);const n=(0,s.dirname)(e);if(n===e)break;e=n}n.overflowDir=a,n.overflowChain=o}const i=(0,s.extname)(e);for(const e of o)e.fullSubtreeExtensionCounts[i]??=0,e.fullSubtreeExtensionCounts[i]=Dy(e.fullSubtreeExtensionCounts[i]+1),e.numFiles??=0,e.numFiles=Dy(e.numFiles+1)}}ensureDirectoryPath(e,t,r,n){if(r.has(e)||e===t)return;const o=(0,s.dirname)(e);o!==e&&o.startsWith(t)&&this.ensureDirectoryPath(o,t,r,n);const i=new yC.vq({absPath:e,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!n,fullSubtreeExtensionCounts:{}});r.set(e,i);const a=r.get(o);a&&a.childrenDirs.push(i)}sortTreeChildren(e){e.childrenDirs.sort(((e,t)=>(0,s.basename)(e.absPath).localeCompare((0,s.basename)(t.absPath)))),e.childrenFiles.sort(((e,t)=>e.name.localeCompare(t.name)));for(const t of e.childrenDirs)this.sortTreeChildren(t)}}class kC extends Error{constructor(e,t){super(`Tool ${e} not found, available tools: ${t.join(", ")}`),this.toolName=e,this.availableTools=t,this.name="McpToolNotFoundError"}}function _C(e){if(e instanceof kC)return!0;if(!(e instanceof Error)||"McpToolNotFoundError"!==e.name)return!1;const t=e;return"string"==typeof t.toolName&&Array.isArray(t.availableTools)}function CC(e){return!0===e.url?.startsWith("mcp-provider://")}function EC(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function xC(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function PC(e,t){return(t??[]).some((t=>{const r=EC(t.command),n=xC(t.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==e.command&&(0,Lb.mD)(r,e.command),s=void 0===n||void 0!==e.url&&(0,Lb.eA)(n,e.url);return o&&s}))}function RC(e,t){if(CC(e))return!1;const r=t?.rules??[];if(0===r.length)return!1;if(PC(e,r))return!0;const n=function(e){return e.flatMap((e=>{if(void 0===e.serverUrl)return[];const t=function(e){if(e.includes("*"))return e;const t=e.search(/[?#]/);return-1===t?e:e.slice(0,t)}(e.serverUrl);return t===e.serverUrl?[]:[{...e,serverUrl:t}]}))}(r);return n.length>0&&PC(e,n)}function IC(e,t){const{command:r,url:n}=e;return void 0!==r&&t.commandPatterns.some((e=>(0,Lb.mD)(e.trim(),r)))||void 0!==n&&t.serverUrlPatterns.some((e=>(0,Lb.eA)(e.trim(),n)))}var TC=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class AC extends Error{constructor(e){super(`MCP server "${e}" is disabled`),this.name="McpServerDisabledError"}}class $C extends Error{constructor(e){super(`MCP server "${e}" has not been approved`),this.serverName=e,this.name="McpServerNotApprovedError"}}class MC extends Error{constructor(e,t){super(`MCP server "${e}" is overridden by ${t}`),this.serverName=e,this.overridingConfigPath=t,this.name="McpServerOverriddenError"}}class DC{constructor(e){this.disabledService=e}async load(e,t,r,n,o){if(await this.disabledService.isServerDisabled(t))throw new AC(t);return await o(e,r)}}class OC{constructor(e){this.approvalService=e}async load(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{if(function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(s,(0,D.VI)(e.withName("ServerApprovalMiddleware.load")),!1),!await this.approvalService.isServerApproved(t,r,n))throw new $C(t);return await o(e,r)}catch(e){s.error=e,s.hasError=!0}finally{TC(s)}}}class FC{constructor(e,t){this.approvalsPath=e,this.cwd=t,this.approvalsPromise=this.loadApprovals()}async isServerApproved(e,t,r){const n=function(e,t,r){const n={path:r,server:t};return`${e}-${(0,ko.createHash)("sha256").update(JSON.stringify(n)).digest("hex").substring(0,16)}`}(e,t,this.cwd);return(await this.getApprovals()).includes(n)}async loadApprovals(){try{const e=await(0,xo.readFile)(this.approvalsPath,"utf8"),t=JSON.parse(e);return Array.isArray(t)?t:(await this.saveApprovalsToFile([]),[])}catch(e){if(e instanceof Error&&e.message.includes("ENOENT"))return[];throw e}}async getApprovals(){return this.approvalsPromise}async addApproval(e){const t=await this.approvalsPromise;t.includes(e)||(t.push(e),await this.saveApprovals(t))}async addApprovals(e){const t=await this.approvalsPromise,r=e.filter((e=>!t.includes(e)));r.length>0&&(t.push(...r),await this.saveApprovals(t))}async removeApproval(e){const t=await this.approvalsPromise,r=t.filter((t=>t!==e));r.length!==t.length&&await this.saveApprovals(r)}async clearApprovals(e){const t=await this.approvalsPromise,r=e?t.filter((t=>!e(t))):[];r.length!==t.length&&await this.saveApprovals(r)}async saveApprovalsToFile(e){await(0,xo.mkdir)(s.dirname(this.approvalsPath),{recursive:!0}),await(0,xo.writeFile)(this.approvalsPath,JSON.stringify(e,null,2))}async saveApprovals(e){await this.saveApprovalsToFile(e),this.approvalsPromise=Promise.resolve(e)}}const NC=["https://api.cursor.com","https://api2.cursor.sh"],LC=["CURSOR_API_BASE_URL","CURSOR_BACKEND_URL"],jC=/^MCP server ".+" is blocked by \S/u;function UC(e){if(void 0!==e&&""!==e)try{return new URL(e).origin}catch{return}}function BC(e,t=process.env){if(void 0===e)return!1;let r;try{r=new URL(e)}catch{return!1}if("/v1/agent/mcp"!==r.pathname.replace(/\/+$/,"")&&!r.pathname.startsWith("/internal/agent-serve/agent-sdk-mcp-relay/"))return!1;const n=new Set(NC);for(const e of LC){const r=UC(t[e]);void 0!==r&&n.add(r)}return n.has(r.origin)}function WC(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function HC(e,t){if("string"!=typeof e)return;const r=e.trim();return""===r||r.length>t||/\p{Cc}/u.test(r)?void 0:r}function qC(e){if(!Array.isArray(e))return;const t=[];for(const r of e.slice(0,200)){const e=HC(r,200);void 0!==e&&t.push(e)}return t}function zC(e,t){const r=t.slice(0,20).join(", "),n=t.length-20;return n>0?` ${e}: ${r}, and ${n} more.`:` ${e}: ${r}.`}var GC=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},VC=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class KC{async load(e,t,r,n,o){const s=o(e,r);return new ZC(e,t,s,r)}}function JC(e){let t;return e.then((e=>{t=e})).catch((()=>{})),t}class ZC{constructor(e,t,r,n){this.serverName=t,this.clientPromise=r,this.config=n,this.clientPromiseTraceId=(0,D.fU)(e)?.spanContext()?.traceId,this.toolsPromise=this.clientPromise.then((async t=>null===t?[]:await t.getTools(e))),this.resourcesPromise=this.clientPromise.then((async t=>null===t?[]:(await t.listResources(e)).resources)),this.promptsPromise=this.clientPromise.then((async t=>null===t?[]:await t.listPrompts(e))),this.toolsPromise.catch((()=>{})),this.resourcesPromise.catch((()=>{})),this.promptsPromise.catch((()=>{}))}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=GC(t,(0,D.VI)(e.withName("CachedMcpClient.getTools")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=JC(this.toolsPromise);return void 0!==n?n:await this.toolsPromise}catch(e){t.error=e,t.hasError=!0}finally{VC(t)}}async callTool(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{const i=GC(s,(0,D.VI)(e.withName("CachedMcpClient.callTool")),!1),a=await this.getClient(i.ctx);if(null===a)throw new Error("Client is not ready");return a.callTool(i.ctx,t,r,n,o)}catch(e){s.error=e,s.hasError=!0}finally{VC(s)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=GC(t,(0,D.VI)(e.withName("CachedMcpClient.getInstructions")),!1),n=await this.getClient(r.ctx);if(null===n)return;return await n.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{VC(t)}}async getClient(e){const t={stack:[],error:void 0,hasError:!1};try{const r=GC(t,(0,D.VI)(e.withName("CachedMcpClient.getClient")),!1);return r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined"),await this.clientPromise}catch(e){t.error=e,t.hasError=!0}finally{VC(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{const r=GC(t,(0,D.VI)(e.withName("CachedMcpClient.listResources")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=JC(this.resourcesPromise);return void 0!==n?{resources:n}:{resources:await this.resourcesPromise}}catch(e){t.error=e,t.hasError=!0}finally{VC(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=GC(r,(0,D.VI)(e.withName("CachedMcpClient.readResource")),!1),o=await this.getClient(n.ctx);return null===o?{contents:[]}:o.readResource(n.ctx,t)}catch(e){r.error=e,r.hasError=!0}finally{VC(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{const r=GC(t,(0,D.VI)(e.withName("CachedMcpClient.listPrompts")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=JC(this.promptsPromise);return void 0!==n?n:await this.promptsPromise}catch(e){t.error=e,t.hasError=!0}finally{VC(t)}}async getPrompt(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=GC(n,(0,D.VI)(e.withName("CachedMcpClient.getPrompt")),!1),s=await this.getClient(o.ctx);return null===s?{messages:[]}:s.getPrompt(o.ctx,t,r)}catch(e){n.error=e,n.hasError=!0}finally{VC(n)}}async getState(e){const t={stack:[],error:void 0,hasError:!1};try{const r=GC(t,(0,D.VI)(e.withName("CachedMcpClient.getState")),!1);r.span.setAttribute("serverName",this.serverName);const n=await this.getClient(r.ctx);if(null===n)throw new Error("Client is not ready");return await n.getState(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{VC(t)}}async getAllowlistInUse(){try{await this.toolsPromise;const e=await this.clientPromise;return await(e?.getAllowlistInUse?.())}catch{return}}async getAllowlistRefusal(){if(void 0!==this.config&&"url"in this.config&&BC(this.config.url))try{return void await this.toolsPromise}catch(e){return function(e){const t=e instanceof Error?e.message:"string"==typeof e?e:void 0;if(void 0===t)return;const r=t.indexOf("{");if(-1===r)return;let n;try{n=JSON.parse(t.slice(r))}catch{return}if(!WC(n))return;const o=HC(n.error,700);return void 0!==o&&jC.test(o)?o:void 0}(e)}}async close(){try{const e=await this.clientPromise;await(e?.close?.())}catch{}}}function XC(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function QC(e,t){if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e||"bigint"==typeof e)return String(e);if(null==e)return t;try{const r=JSON.stringify(e);return"string"==typeof r?r:t}catch{return t}}function YC(e){return e?` (${QC(e,"")})`:""}function eE(e){if(null===e||"string"==typeof e||"boolean"==typeof e)return e;if("number"==typeof e)return Number.isFinite(e)?e:void 0;if(Array.isArray(e)){const t=[];for(const r of e){if(void 0===r){t.push(null);continue}const e=eE(r);if(void 0===e)return;t.push(e)}return t}if("object"!=typeof e)return;const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&null!==t)return;const r={};for(const[t,n]of Object.entries(e)){if(void 0===n)continue;const e=eE(n);if(void 0===e)return;r[t]=e}return r}function tE(e){const t=eE(e);if(null!=t&&"object"==typeof t&&!Array.isArray(t))return t}const rE=new TextDecoder("utf-8",{fatal:!0});function nE(e){return"string"==typeof e?e.split(";")[0]?.trim().toLowerCase()??"":""}function oE(e,t){const r=Buffer.from(t,"base64"),n=function(e){try{const t=rE.decode(e);return t.includes("\0")?void 0:t}catch{return}}(r)??(function(e){const t=nE(e);return t.startsWith("text/")||"application/xml"===t||t.endsWith("+xml")}(e.mimeType)?r.toString("utf8").replace(/^\uFEFF/,""):void 0);if(void 0!==n)return{text:n,binary:!1};const o="string"==typeof e.mimeType&&e.mimeType.length>0?e.mimeType:"unknown type";return{text:`[Binary resource: ${QC(e.uri,"unknown")} (${o}, ${r.byteLength} bytes). The file is not text, so its contents are not included.]`,binary:!0}}const sE=new Set(["image/png","image/jpeg","image/jpg","image/gif","image/webp"]);function iE(e){return"string"==typeof e.text&&e.text.length>0?e.text:void 0}function aE(e){if(!XC(e))return;const t=e.resource;return XC(t)&&void 0===iE(t)&&"string"==typeof t.blob&&sE.has(nE(t.mimeType))?t.blob:void 0}function cE(e){const t=e,r=t.resource;if(XC(r)){const e=iE(r);return void 0!==e?e:"string"==typeof r.blob?oE(r,r.blob).text:`Resource: ${QC(r.uri,"unknown")}${YC(r.name)}`}return t.uri?`Resource: ${QC(t.uri,"unknown")}${YC(t.name)}`:`Unsupported content type "${e.type}": ${JSON.stringify(e)}`}function lE(e){const t=tE(e);if(void 0!==t&&0!==Object.keys(t).length)try{return Buffer.byteLength(JSON.stringify(t))<=262144?t:void 0}catch{return}}var uE=r("zod/v4-mini");const dE=uE.object({CLIENT_ID:uE.string(),CLIENT_SECRET:uE.optional(uE.string()),scopes:uE.optional(uE.array(uE.string()))}),hE=uE.strictObject({caBundle:uE.string().check(uE.trim(),uE.minLength(1),uE.maxLength(131072))}),pE=uE.object({type:uE.optional(uE.literal("stdio")),command:uE.string(),args:uE.optional(uE.array(uE.string())),env:uE.optional(uE.record(uE.string(),uE.string())),envFile:uE.optional(uE.string()),cwd:uE.optional(uE.string()),enabledTools:uE.optional(uE.array(uE.string())),startupTimeoutSec:uE.catch(uE.optional(uE.number().check(uE.positive())),void 0)}),fE=uE.object({type:uE.optional(uE.enum(["http","sse"])),url:uE.string(),headers:uE.optional(uE.record(uE.string(),uE.string())),auth:uE.optional(dE),tls:uE.optional(hE),placement:uE.optional(uE.enum(["server","client"])),enabledTools:uE.optional(uE.array(uE.string()))}),mE=uE.union([pE,fE]),gE=uE.object({mcpServers:uE.record(uE.string(),mE)});Error;const wE=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g;function yE(e,t){if("string"==typeof e)return function(e,t){return e.replace(wE,((e,r,n,o)=>{if(void 0!==r){const n=t(r);return void 0!==n?n:e}if(void 0===n)return e;const s=t(n);return void 0!==s?s:void 0!==o?o:e}))}(e,t);if(Array.isArray(e))return e.map((e=>yE(e,t)));if(null!==e&&"object"==typeof e){const r={};for(const[n,o]of Object.entries(e))r[n]=yE(o,t);return r}return e}r("../../node_modules/.pnpm/smol-toml@1.9.0/node_modules/smol-toml/dist/index.js");Symbol("invalid");function vE(e){const t=Object.entries(e);return{jsonKeyOf:new Map(t.map((([e,t])=>[t,e]))),tomlKeyOf:new Map(t)}}const bE=vE({CLIENT_ID:"client_id",CLIENT_SECRET:"client_secret",scopes:"scopes"}),SE=vE({caBundle:"ca_bundle"}),kE=vE({type:"type",command:"command",args:"args",env:"env",envFile:"env_file",cwd:"cwd",enabledTools:"enabled_tools",startupTimeoutSec:"startup_timeout_sec"}),_E=vE({type:"type",url:"url",headers:"http_headers",auth:"auth",tls:"tls",placement:"placement",enabledTools:"enabled_tools"}),CE=(new Map([["auth",{keys:bE,unknownKeyIsError:!1}],["tls",{keys:SE,unknownKeyIsError:!0}]]),"enabled");new Set([...kE.jsonKeyOf.keys(),..._E.jsonKeyOf.keys(),CE]);Symbol("disabled");const EE=(0,d.h)("McpConfig");async function xE(e,t=e=>process.env[e]){try{const r=await(0,xo.readFile)(e,"utf8"),n=yE((0,xp.qg)(r),t);return gE.parse(n)}catch{return{mcpServers:{}}}}async function PE(e,t=e=>process.env[e]){const r={config:{mcpServers:{}},diagnostics:[]};return r}async function RE(e,t=e=>process.env[e]){const{config:r,diagnostics:n}=await PE(0,t);return n.length>0&&EE.warn((0,b.q6)(),"[mcp config] problems in MCP config; `agent mcp list` shows them",{errorCount:n.filter((e=>"error"===e.severity)).length,warningCount:n.filter((e=>"warning"===e.severity)).length,fileNames:[...new Set(n.map((e=>s.basename(e.file))))]}),r}const IE=["enterprise","project","user","env"];function TE(e){return"project"===e||"env"===e}const AE=["0.0.0.0/0","::/0"];function $E(e){const t=(e??[]).filter((e=>e.trim().length>0)),r=t.flatMap((e=>{const t=(0,Lb.bi)(e);return void 0===t?[]:[t]}));return{hasInvalidEntries:r.length!==t.length,entries:r}}function ME(e){const t=!0===e.enabled,r=$E(e.mcpNetworkDenylist),n="deny_all"===e.mcpNetworkMode||r.entries.includes("*")||r.hasInvalidEntries,o=t?function(e){if("allow_all"===e.mcpNetworkMode)return[...AE];const t=$E(e.mcpNetworkAllowlist);if("allowlist"===e.mcpNetworkMode)return t.entries.includes("*")?[...AE]:t.entries;if(!function(e){return(e.mcpNetworkAllowlist??[]).some((e=>e.trim().length>0))}(e))return[...AE];const r=(0,Lb.b6)(e);return r.includes("*")?[...AE]:r}(e):[],s=t?n?["*"]:r.entries:[];return JSON.stringify({enabled:t,mode:e.mcpNetworkMode,allow:n?[]:o,deny:s})}class DE extends Error{constructor(e,t){super(`MCP server "${e}" wasn't started: your team's MCP settings require it to run in a sandbox, and the sandbox isn't supported on this machine. Ask a team admin to review the team's MCP settings for this server.`),this.serverName=e,this.name="McpSandboxUnavailableError",void 0!==t&&(this.cause=t)}}const OE=new Set(["invalid_auth","not_authed","account_inactive","token_revoked","token_expired"]);class FE extends Error{constructor(){super("Your organization admin only allows Slack workspaces your company manages. Connect your company Slack workspace instead."),this.name="SlackWorkspaceNotManagedError"}}class NE extends Error{constructor(){super("Slack couldn't confirm which workspace this connection is for, and your organization admin only allows the Slack workspaces your company manages. Try again in a moment."),this.name="SlackWorkspaceUnconfirmedError"}}function LE(e){return URL.canParse(e)&&"mcp.slack.com"===new URL(e).hostname.toLowerCase()}function jE(e,t){const r=new Map,n=t.lookUpWorkspace??(t=>async function(e,t){let r;try{const n=await e("https://slack.com/api/auth.test",{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/x-www-form-urlencoded"},signal:AbortSignal.timeout(5e3)});r=await n.json()}catch{return{kind:"unavailable"}}if("object"!=typeof r||null===r)return{kind:"unavailable"};if("object"!=typeof(n=r)||null===n||Array.isArray(n))return{kind:"unavailable"};var n;const o=r;return!0!==o.ok?"string"==typeof o.error&&OE.has(o.error)?{kind:"dead"}:{kind:"unavailable"}:"string"!=typeof o.team_id||0===o.team_id.length?{kind:"unavailable"}:"string"==typeof o.enterprise_id&&o.enterprise_id.length>0?{kind:"found",slackTeamId:o.team_id,slackEnterpriseId:o.enterprise_id}:{kind:"found",slackTeamId:o.team_id}}(e,t));let o,s=[];return async(i,a)=>{if(!LE(function(e){return"string"==typeof e?e:e instanceof URL?e.href:e.url}(i)))return e(i,a);const c=function(e,t){const r=new Headers(t?.headers??(e instanceof Request?e.headers:void 0)),n=/^Bearer\s+(.+)$/i.exec(r.get("authorization")??"");return n?.[1]?.trim()||void 0}(i,a);if(void 0===c)return e(i,a);const l=await((void 0===o||Date.now()-o.atMs>=3e4)&&(o={atMs:Date.now(),lists:t.managedSlackWorkspaceLists().then((e=>"unconfirmed"===e?e:(s=e.filter((e=>e.length>0)).map((e=>e.map((e=>e.toUpperCase())))),s)),(()=>s))}),o.lists);if("unconfirmed"===l)throw new NE;if(0===l.length)return e(i,a);let u=r.get(c);if(void 0===u){const t=await n(c);if("dead"===t.kind)return e(i,a);if("unavailable"===t.kind)throw new NE;r.size>=64&&r.clear(),r.set(c,t),u=t}const d=[u.slackTeamId,u.slackEnterpriseId].flatMap((e=>void 0===e?[]:[e.toUpperCase()]));if(!l.every((e=>d.some((t=>e.includes(t))))))throw new FE;return e(i,a)}}function UE(e,t,r){if("string"==typeof e)return t(e);if(!(e instanceof Error))return e;if(r.results.has(e))return r.results.get(e)===e&&r.cycled.add(e),r.results.get(e);r.results.set(e,e);const n=Object.isFrozen(e)&&JE(e,t)?new Error:void 0;void 0!==n&&r.results.set(e,n);const o=t(e.message),s="string"==typeof e.stack?t(e.stack):void 0,i=Object.keys(e).flatMap((n=>{if("cause"===n)return[];const o=HE(e,n),s=VE(o,t,r);return Object.is(s,o)?[]:[[n,s]]})),a=Object.getOwnPropertyDescriptor(e,"cause"),c=void 0===a?void 0:HE(e,"cause"),l=VE(c,t,r),u=e instanceof AggregateError?HE(e,"errors"):void 0,d=function(e,t,r){if(!Array.isArray(e))return e;const n=e.map((e=>VE(e,t,r)));if(n.every(((t,r)=>Object.is(t,e[r]))))return e;try{return n.forEach(((t,r)=>{e[r]=t})),e}catch{return n}}(u,t,r),h=[...i,...Object.is(l,c)?[]:[["cause",l]],...Object.is(d,u)?[]:[["errors",d]]];let p=!1;if(void 0===n)try{o!==e.message&&(e.message=o),void 0!==s&&s!==e.stack&&(e.stack=s),p=e.message===o&&(void 0===s||e.stack===s)&&h.every((([t,r])=>WE(e,t,r)))}catch{}if(p)return e;const f=Object.defineProperties(n??new Error,{message:{value:o,writable:!0,enumerable:!1,configurable:!0},...Object.getOwnPropertyDescriptors(zE(e,new Map(i)))});Array.isArray(d)&&Object.defineProperty(f,"errors",{value:d,writable:!0,enumerable:!1,configurable:!0}),void 0!==a&&Object.defineProperty(f,"cause",{value:l,writable:!0,enumerable:!0===a.enumerable,configurable:!0});const m=Object.getPrototypeOf(e);null!==m&&"object"==typeof m&&m!==Error.prototype&&(Object.setPrototypeOf(f,m),function(e){try{let t=Object.getPrototypeOf(e);for(let r=0;r<8&&null!==t&&"object"==typeof t&&t!==Error.prototype&&t!==Object.prototype;r++){for(const r of Reflect.ownKeys(t)){const n=Object.getOwnPropertyDescriptor(t,r)?.get;void 0!==n&&Reflect.apply(n,e,[])}t=Object.getPrototypeOf(t)}String(e);const r=e;"function"==typeof r.toJSON&&Reflect.apply(r.toJSON,e,[""]);const n=r[qE];return"function"==typeof n&&Reflect.apply(n,e,[0,{depth:0,stylize:String},String]),!0}catch{return!1}}(f)||Object.setPrototypeOf(f,Error.prototype));const g=QE(e);return void 0!==g&&QE(f)!==g&&Object.defineProperty(f,"name",{value:g,writable:!0,configurable:!0,enumerable:!1}),void 0!==s&&(f.stack=s),r.results.set(e,f),f}function BE(e,t){if(e instanceof Error)return t.get(e)??e;if(!Array.isArray(e)||!Object.isFrozen(e))return e;const r=e.map((e=>e instanceof Error?t.get(e)??e:e));return r.every(((t,r)=>Object.is(t,e[r])))?e:r}function WE(e,t,r){const n=Object.getOwnPropertyDescriptor(e,t);return!0===n?.writable&&Reflect.defineProperty(e,t,{...n,value:r})}function HE(e,t){try{const r=Object.getOwnPropertyDescriptor(e,t);return void 0===r?.get?r?.value:r.get.call(e)}catch{return}}const qE=Symbol.for("nodejs.util.inspect.custom");function zE(e,t){const r={};for(const n of Object.keys(e))try{const o=Object.getOwnPropertyDescriptor(e,n),s=void 0===o?.get?o?.value:o.get.call(e);Object.defineProperty(r,n,{value:t.has(n)?t.get(n):s,writable:!0,enumerable:!0,configurable:!0})}catch{}return r}function GE(e,t,r,n){if("string"==typeof e)return t(e);if("object"!=typeof e||null===e)return e;if(e instanceof Error)return UE(e,t,n);if(Array.isArray(e)){if(r>=4)return;return e.slice(0,64).map((e=>GE(e,t,r+1,n)))}const o=Object.getPrototypeOf(e);return o!==Object.prototype&&null!==o?e:r>=4?void 0:function(e,t,r,n){const o={};for(const s of Object.keys(e).slice(0,64))try{const i=Object.getOwnPropertyDescriptor(e,s),a=void 0===i?.get?i?.value:i.get.call(e);Object.defineProperty(o,s,{value:GE(a,t,r,n),writable:!0,enumerable:!0,configurable:!0})}catch{}return o}(e,t,r+1,n)}function VE(e,t,r){if(e instanceof Error)return UE(e,t,r);try{return JE(e,t)?GE(e,t,1,r):e}catch{return}}const KE=4096;function JE(e,t){const r=new Set,n=[e];for(let o=0;n.length>0;o++){if(o>=KE||n.length>KE)return ZE(e,t);const s=n.pop();if("string"==typeof s){if(t(s)!==s)return!0}else if((XE(s)||s instanceof Error)&&!r.has(s)){r.add(s),s instanceof Error&&(n.push(HE(s,"message"),HE(s,"stack"),HE(s,"cause")),s instanceof AggregateError&&n.push(HE(s,"errors")));for(const e of Object.keys(s))n.push(HE(s,e))}}return!1}function ZE(e,t){const r=new Set;let n;try{n=JSON.stringify(e,((e,t)=>{return"bigint"==typeof t?t.toString():"object"!=typeof t||null===t?t:r.has(t)?void 0:(r.add(t),t instanceof Error?(n=t,{...Object.fromEntries(Object.keys(n).map((e=>[e,HE(n,e)]))),message:HE(n,"message"),stack:HE(n,"stack"),cause:HE(n,"cause"),...n instanceof AggregateError?{errors:HE(n,"errors")}:{}}):t);var n}))}catch{return!0}return void 0!==n&&t(n)!==n}function XE(e){if(Array.isArray(e))return!0;if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function QE(e){try{return"string"==typeof e.name?e.name:void 0}catch{return}}const YE=/spt_[A-Za-z0-9_]{6,}/g,ex=/[A-Z0-9]/;function tx(e){return function(e){return e.replace(YE,(e=>function(e){return e.slice(4).split("_").some((e=>e.length>=8&&ex.test(e)))}(e)?"[redacted Link shared payment token]":e))}(e)}var rx=r("../../node_modules/.pnpm/string-argv@0.3.2/node_modules/string-argv/index.js");new Set(["EAI_AGAIN","ECONNABORTED","ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ENOTFOUND","EPIPE","ETIMEDOUT","EADDRNOTAVAIL","UND_ERR_CONNECT_TIMEOUT"]),new Set(["ECONNRESET","EPIPE"]);const nx=new Set([429,502,503,504]);function ox(e){return"object"==typeof e&&null!==e}function sx(e){const t=ox(e)?e.code:void 0,r=(e instanceof Error||ox(e)&&"string"==typeof e.message?e.message:"").match(/\(HTTP (\d+)\)|Non-200 status code \((\d+)\)|\bHTTP\s+(\d{3})\b/i),n=r?.[1]??r?.[2]??r?.[3],o=void 0!==n?parseInt(n,10):void 0;if("number"==typeof t&&t>=100)return void 0!==o&&nx.has(o)&&!nx.has(t)?o:t;if("string"==typeof t&&/^\d{3}$/.test(t)){const e=Number.parseInt(t,10);return e>=100&&e<=599?e:o}return o}new Set(["UND_ERR_SOCKET","UND_ERR_CLOSED","ECONNRESET"]);const ix=8192;function ax(e){return void 0===e?"unknown":"url"in e&&e.url.length>0?void 0!==lb(e.url)?"rest_mcp":"streamable_http":"command"in e?"stdio":"unknown"}new Set(["ENOENT","EACCES","ENOTDIR","EPERM"]);const cx=/\$\{[^}]*\}/;function lx(e){if(void 0!==function(e){if(void 0===e)return;const t=e.trim();return 0!==t.length&&cx.test(t)?t:void 0}(e))return;const t=e?.trim();return t&&t.length>0?t:void 0}const ux=new Map;async function dx(e,t=fetch){if(void 0===lb(e))return;const r=new URL(e),n=`${r.origin}/.well-known/oauth-protected-resource${r.pathname.replace(/\/+$/,"")}`,o=ux.get(n);if(void 0!==o&&o.expiresAtMs>Date.now())return o.metadata;let s;try{const e=await t(n);if(!e.ok)return;s=function(e){if("object"!=typeof(t=e)||null===t)return{};var t;const r=e,n="string"==typeof r.cursor_client_id&&r.cursor_client_id.length>0?r.cursor_client_id:void 0;let o;if("object"==typeof r.cursor_authorization_params&&null!==r.cursor_authorization_params){const e=Object.entries(r.cursor_authorization_params).filter((e=>"string"==typeof e[1]));e.length>0&&(o=Object.fromEntries(e))}return{...void 0!==n?{clientId:n}:{},...!0===r.cursor_omit_resource_indicator?{omitResourceIndicator:!0}:{},...!0===r.cursor_omit_consent_prompt?{omitConsentPrompt:!0}:{},...void 0!==o?{authorizationParams:o}:{},...!0===r.cursor_rejects_custom_scheme_redirects?{rejectsCustomSchemeRedirects:!0}:{},...!0===r.cursor_unauthenticated_connect?{unauthenticatedConnect:!0}:{},...!0===r.cursor_loopback_ipv4?{loopbackIpv4:!0}:{},...!0===r.cursor_backend_only_token_exchange?{backendOnlyTokenExchange:!0}:{}}}(await e.json())}catch{return}return ux.set(n,{metadata:s,expiresAtMs:Date.now()+3e5}),s}(0,Es.J)((function(){ux.clear()}));const hx={info:()=>{},warn:()=>{},error:()=>{},debug:()=>{}};function px(e){return hx}const fx=/^[\x21\x23-\x5B\x5D-\x7E]+$/,mx=["invalid_request","invalid_token","insufficient_scope"];function gx(e){return mx.some((t=>t===e))}function wx(e){const t=new Set;for(const r of e)r.length<=200&&fx.test(r)&&t.add(r);return[...t]}const yx=/[!#$%&'*+.^_`|~0-9A-Za-z-]+/y,vx=/"((?:[^"\\]|\\.)*)"?/y,bx=/[^\s,]*/y;function Sx(e,t){let r,n=0;const o=t=>{t.lastIndex=n;const r=t.exec(e);return null!==r&&(n=t.lastIndex),r};for(;n"string"==typeof e&&e.length>0)):void 0}function Cx(e){if("object"!=typeof e||null===e||Array.isArray(e))return kx;const t=_x("grantedScopes"in e?e.grantedScopes:void 0),r=_x("requestedScopes"in e?e.requestedScopes:void 0);return{...void 0!==t?{grantedScopes:t}:{},stepUpScopes:_x("stepUpScopes"in e?e.stepUpScopes:void 0)??[],signInMissing:_x("signInMissing"in e?e.signInMissing:void 0)??[],...void 0!==r?{requestedScopes:r}:{}}}function Ex(e){return(e??"").split(/\s+/).filter((e=>e.length>0))}function xx(e,t){return e.filter((e=>!t.has(e)))}function Px(e){const t=Cb(e.serverUrl),r=e.connectorName??t?.displayName??e.accountKey,n=px(e.accountKey);let o;const s=async()=>Cx(await e.readRecord()),i=async t=>{if(void 0!==t.grantedScopes)return t.grantedScopes;const r=Ex(await e.readTokenScope());return r.length>0?r:void 0},a=(e,t)=>{n.info(`MCP OAuth scope step-up: ${e}`,{event:`mcp_oauth_scope_step_up_${e}`,...t})};return{accountKey:e.accountKey,connectorName:r,async decide(r){if(401!==r.status&&403!==r.status)return;const n=function(e){const t=e??"",r=Sx(t,"error")?.toLowerCase(),n=Sx(t,"resource_metadata");return{error:void 0===r||""===r?"none":gx(r)?r:"other",scopes:wx((Sx(t,"scope")??"").split(/\s+/)),resourceMetadata:void 0===n||""===n?void 0:n}}(r.wwwAuthenticate);if("insufficient_scope"!==n.error||0===n.scopes.length)return;if(function(e){try{return Eb.has(new URL(e).hostname.toLowerCase())}catch{return!1}}(e.serverUrl))return;const o=function(e,t){if(void 0!==t)try{return new URL(t).origin===new URL(e).origin?t:void 0}catch{return}}(e.serverUrl,n.resourceMetadata),c=void 0===t?await e.readScopesSupported(o).catch((()=>{})):void 0,l=await s(),u=await i(l),{accepted:d,dropped:h}=function(e){const t=new Set(e.granted??[]),r=[],n=[];for(const o of wx(e.named))e.allowlist.has(o)?t.has(o)||r.push(o):n.push(o);return{accepted:r,dropped:n}}({named:n.scopes,allowlist:(p={policy:t,scopesSupported:c,configuredScopes:e.configuredScopes},void 0!==p.policy?new Set([...p.policy.baseScopes,...Object.keys(p.policy.stepUpScopes)]):new Set([...p.scopesSupported??[],...p.configuredScopes??[]])),granted:u});var p;if(0===d.length)return void a("none_accepted",{status:r.status,namedCount:n.scopes.length,droppedCount:h.length});const f=new Set(l.signInMissing),m=d.every((e=>f.has(e)))?"blocked":"offer";return"offer"===m&&await e.writeRecord({...l,...void 0!==u?{grantedScopes:u}:{},stepUpScopes:[...new Set([...l.stepUpScopes,...d])]}),a(m,{status:r.status,acceptedCount:d.length,droppedCount:h.length}),{kind:m,status:r.status,scopes:d,dropped:h,toolName:r.toolName,resourceMetadataUrl:o}},signIn:async e=>(void 0===o&&(o=Promise.resolve().then(e).finally((()=>{o=void 0}))),o),get isSigningIn(){return void 0!==o},tokensForSdk(e){if(void 0===o||void 0===e?.refresh_token)return e;const{refresh_token:t,...r}=e;return r},async prepareAuthorization(){const t=await s();return{stepUpScopes:t.stepUpScopes.length>0?[...new Set([...await i(t)??[],...t.stepUpScopes])]:[],recordRequestedScopes:async t=>{await e.writeRecord({...await s(),requestedScopes:Ex(t.searchParams.get("scope"))})}}},async recordTokens(t,{isRefresh:r}){const n=await e.readRecord();if(void 0===n)return;const o=Cx(n),s=Ex(t.scope);if(r)return void(s.length>0&&await e.writeRecord({...o,grantedScopes:s}));if(void 0===o.requestedScopes)return;const i=s.length>0?s:o.requestedScopes,c=new Set(i),l=xx(o.requestedScopes,c);await e.writeRecord({grantedScopes:i,stepUpScopes:xx(o.stepUpScopes,c),signInMissing:l}),a("sign_in_recorded",{grantedCount:i.length,signInMissingCount:l.length,scopeReported:s.length>0})},async clear(t){await e.writeRecord(!0===t?.keepPendingScopes?function(e){const{stepUpScopes:t}=Cx(e);return t.length>0?{stepUpScopes:t,signInMissing:[]}:void 0}(await e.readRecord()):void 0)}}}function Rx(e){const t=Cb(e.serverUrl);for(const r of e.scopes){const e=t?.stepUpScopes[r]?.action;if(void 0!==e)return e}return e.toolTitle}function Ix(e){const t=function(e){return void 0===e.action?`${e.connectorName} needs a permission its sign-in did not grant.`:`${e.connectorName} needs one more permission to ${e.action}.`}({connectorName:e.connectorName,action:Rx(e)}),r="offer"===e.kind?`Authorize ${e.connectorName} again to approve it; the turn can continue once it's granted.`:`Its last sign-in did not grant ${1===e.scopes.length?"it":"them"}, so an admin or your consent is blocking this. Reconnect ${e.connectorName} from its MCP settings to ask again.`,n=function(e){if(0===e.length)return;const t=e.slice(0,3).join(", "),r=e.length-3;return`${1===e.length?"Permission":"Permissions"}: ${t}${r>0?` and ${r} more`:""}`}(e.scopes);return void 0===n?`${t} ${r}`:`${t} ${r}\n${n}`}class Tx extends Error{constructor(e,t,r){super(Ix({kind:e.kind,serverUrl:t,connectorName:r,scopes:e.scopes,toolTitle:e.toolName})),this.decision=e,this.serverUrl=t,this.connectorName=r,this.name="McpOAuthScopeStepUpError"}answerWithToolTitle(e){return Ix({kind:this.decision.kind,serverUrl:this.serverUrl,connectorName:this.connectorName,scopes:this.decision.scopes,toolTitle:e??this.decision.toolName})}}function Ax(e){if("string"!=typeof e)return;let t;try{t=JSON.parse(e)}catch{return}const r=Array.isArray(t)?t:[t];for(const e of r){if("object"!=typeof e||null===e||!("method"in e)||"tools/call"!==e.method)continue;const t="params"in e?e.params:void 0,r="object"==typeof t&&null!==t&&"name"in t?t.name:void 0;return"string"==typeof r?r:void 0}}function $x(e){return e instanceof Error&&/does not support dynamic client registration/i.test(e.message)}Error,Error;const Mx=new Set(["UnauthorizedError","InvalidGrantError","InvalidTokenError","InvalidClientError","UnauthorizedClientError"]),Dx=new Set(["invalid_grant","invalid_token","invalid_client","unauthorized_client"]),Ox=[/\btoken (?:has |is )?expired\b/i,/\btoken (?:was|is) invalid\b/i,/\binvalid (?:refresh[ _]?)?token\b/i,/\btoken (?:has been |was )?revoked\b/i];var Fx=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js");const Nx="2026-07-28",Lx=-32022,jx="io.modelcontextprotocol/protocolVersion",Ux="io.modelcontextprotocol/clientCapabilities",Bx="io.modelcontextprotocol/clientInfo",Wx="io.modelcontextprotocol/serverInfo",Hx={name:"cursor",version:"1.0.0"},qx=new Map;function zx(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Gx(e){const t=new URL(String(e));return t.hash="",t.href}function Vx(e,t){const r=qx.get(e);return!(void 0===r||r<=t()&&(qx.delete(e),1))}function Kx(e,t){try{return Gx(e)===t}catch{return!1}}function Jx(e){return(e.headers.get("content-type")??"").toLowerCase().includes("application/json")}const Zx=new Set(["events/subscribe","events/unsubscribe","events/poll","events/stream"]);function Xx(e,t,r,n,o=t.message){const s=new Headers(e?.headers);if(s.set("mcp-protocol-version",Nx),s.set("mcp-method",r),s.delete("mcp-session-id"),!t.isRequest&&o===t.message)return{...e,headers:s};const i=zx(o.params)?o.params:{},a=zx(i._meta)?i._meta:{},c=function(e,t){const r="tools/call"===e||"prompts/get"===e||Zx.has(e)?"name":"resources/read"===e?"uri":void 0,n=void 0===r?void 0:t[r];return"string"==typeof n?n:void 0}(r,i);void 0!==c&&s.set("mcp-name",c);const l=JSON.stringify({...o,params:{...i,_meta:{...a,[jx]:Nx,[Ux]:n.capabilities,[Bx]:n.clientInfo}}});return{...e,headers:s,body:l}}function Qx(e){return new Response(JSON.stringify({jsonrpc:"2.0",...e}),{status:200,headers:{"content-type":"application/json"}})}function Yx(e,t){const r=Gx(t.serverUrl),n=t.now??Date.now;let o={capabilities:{},clientInfo:{...Hx}},s=!1;const i=()=>s||Vx(r,n),a=async(t,i,a)=>{const{method:c,message:l}=t;if(void 0===c)return e(i,a);if("notifications/initialized"===c)return new Response(null,{status:202});if(t.isRequest&&"initialize"===c){const c={jsonrpc:"2.0",id:l.id,method:"server/discover",params:{}},u=await e(i,Xx(a,t,"server/discover",o,c)),d=await async function(e,t,r){if(!e.ok||!Jx(e))return e;let n;try{n=await e.clone().json()}catch{return e}if(!zx(n)||!zx(n.result))return e;const o=n.result,s=o.supportedVersions;if(!Array.isArray(s)||!s.includes(Nx))return Qx({id:t,error:{code:Lx,message:"Unsupported protocol version",data:{requested:Nx,supported:s??[]}}});const i=zx(o._meta)?o._meta:{},a=zx(i[Wx])?i[Wx]:{name:new URL(r).hostname,version:"unknown"};return Qx({id:t,result:{protocolVersion:Fx.aE,capabilities:zx(o.capabilities)?o.capabilities:{},serverInfo:a,..."string"==typeof o.instructions?{instructions:o.instructions}:{}}})}(u,l.id,r);return d!==u&&(s=!0,function(e,t){qx.set(e,t()+6e5)}(r,n)),d}return e(i,Xx(a,t,c,o))};return async(t,c)=>{const l=function(e,t,r){if("POST"!==(t?.method??"GET").toUpperCase()||"string"!=typeof t?.body||!Kx(e,r))return;let n;try{n=JSON.parse(t.body)}catch{return}if(!zx(n)||"2.0"!==n.jsonrpc)return;const o="string"==typeof n.method?n.method:void 0;return{message:n,method:o,isRequest:void 0!==o&&"id"in n}}(t,c,r);if(void 0===l)return function(e,t,r){return"GET"===(t?.method??"GET").toUpperCase()&&Kx(e,r)}(t,c,r)&&i()?new Response(null,{status:405}):e(t,c);if(l.isRequest&&"initialize"===l.method){const e=zx(l.message.params)?l.message.params:{};o={capabilities:zx(e.capabilities)?e.capabilities:{},clientInfo:zx(e.clientInfo)?e.clientInfo:o.clientInfo}}const u=l.isRequest&&"initialize"===l.method;if(u?Vx(r,n):i())return a(l,t,c);if(u&&(s=!1),!l.isRequest)return e(t,c);const d=await e(t,c);if(u&&await async function(e){if(e.status>=500||!Jx(e))return!1;const t=Number(e.headers.get("content-length"));if(Number.isFinite(t)&&t>4096)return!1;let r;try{r=await e.clone().json()}catch{return!1}if(!zx(r)||!zx(r.error))return!1;const n=r.error;if(n.code!==Lx||!zx(n.data))return!1;const o=n.data.supported;return Array.isArray(o)&&o.includes(Nx)}(d)){const e=await a(l,t,c);return s?e:d}return d}}function eP(e,t){if(void 0===t)return{headers:t,cursorAuthHeaderValue:void 0,cursorAuthOrigin:void 0};const r=Object.entries(t),n=r.find((([e])=>e.toLowerCase()===ab));if(void 0===n)return{headers:t,cursorAuthHeaderValue:void 0,cursorAuthOrigin:void 0};let o;try{o=new URL(e).origin}catch{o=void 0}return{headers:Object.fromEntries(r.filter((([e])=>e.toLowerCase()!==ab))),cursorAuthHeaderValue:n[1],cursorAuthOrigin:o}}function tP(e,t,r){return async(n,o)=>{let s;try{s=new URL("string"==typeof n?n:n.toString()).origin}catch{return r(n,o)}if(s!==t)return r(n,o);const i=await e();if(void 0===i||0===i.length)return r(n,o);const a=new Headers(o?.headers);return a.set(ab,i),r(n,{...o,headers:a,redirect:"manual"})}}class rP{constructor(e=864e5){this.ttl=e,this.staleDirty=!1,this.refreshGeneration=0}async get(e){const t=performance.now();if(this.state&&this.state.expiresAt>t&&!this.staleDirty)return this.state.value;if(this.staleDirty&&this.state){const t=this.state.value;if(!this.refreshInFlight){const t=this.refreshGeneration;let r;r=(async()=>{try{const r=await e();if(t!==this.refreshGeneration)return;this.state={expiresAt:performance.now()+this.ttl,value:r},this.staleDirty=!1}catch{}finally{r&&this.refreshInFlight===r&&(this.refreshInFlight=void 0)}})(),this.refreshInFlight=r}return t}const r=this.refreshGeneration,n=await e();return r!==this.refreshGeneration||(this.state={expiresAt:performance.now()+this.ttl,value:n},this.staleDirty=!1),n}invalidate(){this.refreshGeneration++,this.state=void 0,this.staleDirty=!1,this.refreshInFlight=void 0}invalidateKeepingStale(){this.state&&(this.staleDirty=!0)}}var nP=r("crypto");function oP(e){const t={};for(const[r,n]of Object.entries(e))void 0!==n&&(t[r]=n);return t}function sP(e,t){const r=function(e){try{const t=new URL(e);return{host:t.host,origin:t.origin,pathname:t.pathname}}catch{return{host:null,origin:null,pathname:null}}}(e),n=!1!==t?.includePath;return{host:r.host,origin:r.origin,path:n?r.pathname:null}}function iP(e,t){return sP(e,t)}function aP(e){if(e)return(0,nP.createHash)("sha256").update(e).digest("hex").slice(0,12)}function cP(e){if(e&&0!==e.length)return aP(JSON.stringify([...e].sort()))}function lP(e){return{clientIdHash:aP(e?.client_id),hasClientSecret:(e?.client_secret??"").length>0,redirectUrisHash:cP(e?.redirect_uris),redirectUriCount:e?.redirect_uris?.length??0}}function uP(e){return"object"==typeof e&&null!==e}function dP(e,t){let r=e;for(const e of t){if(!uP(r)||!(e in r))return;r=r[e]}return r}function hP(e,t){for(const r of t){const t=dP(e,r.split("."));if("string"==typeof t)return t}}function pP(e){if(!e||"object"!=typeof e)return;const t=e.errorCode;return"string"==typeof t?t:void 0}function fP(e){if(!e)return;const t=e.match(/\(HTTP (\d+)\)|Non-200 status code \((\d+)\)|\bHTTP\s+(\d{3})\b/i),r=t?.[1]??t?.[2]??t?.[3];if(!r)return;const n=Number.parseInt(r,10);return Number.isNaN(n)?void 0:n}const mP=e=>e;function gP(e,t){if(e instanceof Error){const r=e.message;return r&&r!==e.name?_P(t(r)):void 0}if("string"==typeof e||"number"==typeof e||"boolean"==typeof e){const r=String(e);return r?_P(t(r)):void 0}}function wP(e){if(e&&"object"==typeof e)return uP(e)?e.cause:void 0}function yP(e,t,r=4){const n=[];let o=e;for(let e=0;e1?n.join(" > "):void 0}const vP="[REDACTED]",bP=/(^|_|-)(token|secret|password|assertion|authorization|verifier|challenge|code)(_|-|$)/i;function SP(e){return e.replace(/(authorization[^:=\r\n]{0,32}[:=]\s*["']?)(?:[A-Za-z][\w.~+/-]*[ \t]+)?[^"',\s&}]+/gi,`$1${vP}`).replace(/((?:access_token|refresh_token|id_token|client_secret|code|password|assertion|token|secret)[^:=\r\n]{0,32}[:=]\s*["']?)([^"',\s&}]+)/gi,`$1${vP}`).replace(/(\bBearer\s+)([A-Za-z0-9\-._~+/]+=*)/gi,`$1${vP}`)}function kP(e,t=256){return e.length>t?`${e.slice(0,Math.max(0,t-3))}...`:e}function _P(e,t){return kP(SP(e),t?.maxLength)}function CP(e,t=mP){if("string"==typeof e)return kP(SP(t(e)));if(void 0!==e)try{const r=JSON.stringify(e,((e,r)=>e&&function(e){const t=e.toLowerCase();return"code"===t||"authorization"===t||t.includes("token")||t.includes("secret")||t.includes("password")||t.includes("assertion")||t.includes("verifier")||t.includes("challenge")||bP.test(t)}(e)?vP:"string"==typeof r?SP(t(r)):r));if(!r)return;return kP(r)}catch{return}}function EP(e,t=mP){const r=wP(e),n=e instanceof Error?e.name:null!=e?typeof e:void 0,o=r instanceof Error?r.name:void 0,s=gP(r,t),i=gP(e,t)??s,a=hP(e,["code","cause.code"]),c=pP(e)??pP(r)??hP(e,["errorCode","error","cause.errorCode","cause.error","body.error","response.body.error"]),l=void 0===c?void 0:_P(t(c)),u=function(e){for(const t of["status","statusCode","response.status","response.statusCode","cause.status","cause.statusCode","cause.response.status","cause.response.statusCode"]){const r=dP(e,t.split("."));if("number"==typeof r&&Number.isFinite(r))return r}}(e)??fP(i)??fP(s),d=CP(dP(e,["response","body"])??dP(e,["body"])??dP(e,["data"])??dP(e,["cause","body"])??dP(e,["cause","response","body"]),t),h=function(e){const t=e.message?.toLowerCase(),r=e.code?.toLowerCase();return t?.includes("timed out")||t?.includes("timeout")||t?.includes("etimedout")||"etimedout"===r?"timeout":t?.includes("enotfound")||t?.includes("eai_again")||t?.includes("dns")||"enotfound"===r||"eai_again"===r?"dns":t?.includes("certificate")||t?.includes("tls")||t?.includes("ssl")?"tls":t?.includes("econnreset")||t?.includes("connection reset")||"econnreset"===r?"connection_reset":t?.includes("econnrefused")||t?.includes("connection refused")||"econnrefused"===r?"connection_refused":void 0}({message:i,code:a}),p=l?"oauth_error":h?"auth_transport_error":i?"generic_error":void 0;return oP({errorName:n,errorMessage:i,errorType:null!=e?typeof e:void 0,httpStatus:u,oauthErrorCode:l,errorResponseSummary:d,networkClassification:h,causeName:o,causeMessage:s,causeChain:yP(e,t),sdkErrorKind:p})}const xP={mcp_oauth_provider_initialized:"MCP OAuth provider initialized",mcp_oauth_tokens_loaded:"MCP OAuth tokens loaded",mcp_oauth_tokens_saved:"MCP OAuth tokens saved",mcp_oauth_callback_completion:"MCP OAuth callback exchange completed",mcp_oauth_client_info_loaded:"MCP OAuth client information loaded",mcp_oauth_client_info_saved:"MCP OAuth client information saved",mcp_oauth_refresh_prepare:"MCP OAuth refresh prepared",mcp_oauth_refresh_error_release:"MCP OAuth refresh error released",mcp_oauth_state_transition:"MCP OAuth state transition",mcp_oauth_credentials_invalidated:"MCP OAuth credentials invalidated"};function PP(e){const t=e.message??xP[e.event],r={event:e.event,cursorMcp:{oauth:oP({...e.metadata})}},n=e.level??"info";"error"!==n?"warn"!==n?"debug"!==n?e.logger.info?.(t,r):e.logger.debug?.(t,r):e.logger.warn?.(t,r):e.logger.error?.(t,e.error,r)}const RP=new Map(["AWS4-HMAC-SHA256","Api-Key","ApiKey","Basic","Bearer","Bot","DPoP","Digest","GNAP","HOBA","Key","Mutual","NTLM","Negotiate","OAuth","PrivateToken","SCRAM-SHA-1","SCRAM-SHA-256","Token","vapid"].map((e=>[e.toLowerCase(),e]))),IP=4096;function TP(e){return"object"==typeof e&&null!==e&&"url"in e&&"string"==typeof e.url}function AP(e){return"string"==typeof e?e:e instanceof URL?e.toString():e.url}function $P(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function MP(e){if(e instanceof Headers)return e;if(Array.isArray(e)){const t=[];for(const r of e){if(!Array.isArray(r)||"string"!=typeof r[0]||"string"!=typeof r[1])return;t.push([r[0],r[1]])}return t}if($P(e)){const t={};for(const[r,n]of Object.entries(e)){if("string"!=typeof n)return;t[r]=n}return t}}function DP(e,t){const r=new Headers(MP(TP(e)?e.headers:void 0));return new Headers(MP(t?.headers)).forEach(((e,t)=>{r.set(t,e)})),r}function OP(e){const t=[];return e.forEach(((e,r)=>{t.push(r)})),t.sort()}function FP(e){if(null===e)return null;const t=Number.parseInt(e,10);return Number.isNaN(t)?null:t}function NP(e,t){if(null==e)return{kind:"none",bytes:0,contentLength:FP(t.get("content-length"))};if("string"==typeof e){const r=(new TextEncoder).encode(e).length;return{kind:"text",bytes:r,contentLength:FP(t.get("content-length"))??r}}if(e instanceof URLSearchParams){const r=e.toString(),n=(new TextEncoder).encode(r).length;return{kind:"text",bytes:n,contentLength:FP(t.get("content-length"))??n}}return e instanceof Blob?{kind:"blob",bytes:e.size,contentLength:FP(t.get("content-length"))??e.size}:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?{kind:"binary",bytes:e.byteLength,contentLength:FP(t.get("content-length"))??e.byteLength}:"object"==typeof e&&null!==e&&("getReader"in e||Symbol.asyncIterator in e)?{kind:"stream",bytes:null,contentLength:FP(t.get("content-length"))}:{kind:"unknown",bytes:null,contentLength:FP(t.get("content-length"))}}function LP(e,t){if(null===e||!e.toLowerCase().startsWith("application/x-www-form-urlencoded"))return;const r="string"==typeof t?function(e){for(const t of e.split("&")){const e=t.indexOf("="),r=e>=0?t.slice(0,e):t;let n;try{n=decodeURIComponent(r.replaceAll("+"," "))}catch{return}if("grant_type"!==n)continue;const o=e>=0?t.slice(e+1):"";try{return decodeURIComponent(o.replaceAll("+"," "))}catch{return}}}(t):t instanceof URLSearchParams?t.get("grant_type")??void 0:void 0;return r?function(e){switch(e){case"authorization_code":case"refresh_token":case"client_credentials":case"urn:ietf:params:oauth:grant-type:jwt-bearer":case"urn:ietf:params:oauth:grant-type:token-exchange":return e;default:return"other"}}(r):void 0}function jP(e){const{input:t,init:r}=e,n=sP(AP(t)),o=DP(t,r),s=OP(o),i=o.get("content-type"),a=aP(o.get("mcp-session-id")??void 0),c=function(e){if(!e)return null;const t=e.trim().split(/\s+/,1)[0]??"";return RP.get(t.toLowerCase())??"unrecognized"}(o.get("authorization"));return{method:(r?.method??(TP(t)?t.method:void 0)??"GET").toUpperCase(),url:n,headers:{names:s,count:s.length},contentType:i,body:NP(r?.body,o),sessionIdHash:a??null,authorizationScheme:c}}function UP(e,t){const r=OP(e.headers),n=FP(e.headers.get("content-length"));return{status:e.status,ok:e.ok,headers:{names:r,count:r.length},contentType:e.headers.get("content-type"),body:{kind:null===e.body?"none":"stream",bytes:null===e.body?0:n,contentLength:n,...void 0!==t?{errorSummary:t}:{}},sessionIdHash:aP(e.headers.get("mcp-session-id")??void 0)??null,wwwAuthenticateHash:aP(e.headers.get("www-authenticate")??void 0)??null,mcpProtocolVersion:e.headers.get("mcp-protocol-version")??null,requestId:e.headers.get("x-request-id")??null,retryAfter:BP(e.headers,"retry-after"),slackRateLimitType:BP(e.headers,"x-slack-ratelimit-type")}}function BP(e,t){return e.get(t)?.slice(0,64)??null}function WP(e){const t={};return void 0!==e.errorName&&(t.name=e.errorName),void 0!==e.errorMessage&&(t.message=e.errorMessage),void 0!==e.errorType&&(t.type=e.errorType),void 0!==e.oauthErrorCode&&(t.oauthErrorCode=e.oauthErrorCode),void 0!==e.errorResponseSummary&&(t.responseSummary=e.errorResponseSummary),void 0!==e.networkClassification&&(t.networkClassification=e.networkClassification),void 0!==e.sdkErrorKind&&(t.sdkErrorKind=e.sdkErrorKind),t}function HP(e,t){const r=jP({input:e,init:t});if(void 0!==LP(r.contentType,t?.body))return!0;const n=r.url.path?.toLowerCase()??"";return n.endsWith("/token")||n.includes("/oauth/token")||n.includes("/connect/token")}const qP=e=>e,zP="REDACTED_SESSION_ID",GP=/\b00D[A-Za-z0-9]{12,15}![A-Za-z0-9._]{20,512}/g;async function VP(e,t,r){try{const n=r(await e.clone().text());return n.length>t?n.slice(0,t):n}catch{return}}async function KP(e){if(!HP(e.input,e.init))return;const t=await VP(e.response,IP,e.redact);if(void 0!==t)try{return CP(JSON.parse(t))}catch{return _P(t,{maxLength:IP})}}async function JP(e){const t=await async function(e,t,r){try{if(t.ok)return;const n=t.headers.get("content-type")?.toLowerCase()??"";if(!n.includes("json")&&!n.includes("text"))return;const o=await VP(t,IP,r);if(void 0===o)return;return function(e){if("/mcp"!==(t=sP(AP(e.input)).path)&&!0!==t?.endsWith("/mcp"))return _P(e.rawText,{maxLength:IP});var t;try{const t=JSON.parse(e.rawText);return $P(t)?function(e){const t=e.error;if("string"==typeof t)return JSON.stringify({error:t});if("object"!=typeof t||null===t)return;if(!$P(t))return;const r=t,n="number"==typeof r.code||"string"==typeof r.code?r.code:void 0,o="string"==typeof r.message?_P(r.message,{maxLength:IP}):void 0;return void 0!==n||void 0!==o?JSON.stringify({...void 0!==n?{code:n}:{},...void 0!==o?{message:o}:{}}):void 0}(t):void 0}catch{return}}({input:e,rawText:o})}catch{return}}(e.input,e.response,e.redact);return{responseErrorSummary:t,oauthTokenErrorBodySummary:void 0===t?await KP({input:e.input,response:e.response,init:e.init,redact:e.redact}):void 0}}function ZP(e,t,r){try{e()}catch{t.warn?.("MCP HTTP exchange logging failed",{event:"mcp_http_exchange_logging_failure",phase:r})}}function XP(e,t,r){if("string"==typeof e)return t(e);if("object"!=typeof e||null===e||r>12)return e;if(Array.isArray(e))return e.map((e=>XP(e,t,r+1)));const n=Object.getPrototypeOf(e);return n!==Object.prototype&&null!==n?e:Object.fromEntries(Object.entries(e).map((([e,n])=>[e,XP(n,t,r+1)])))}function QP(e,t){const r=e=>{const r=XP(e,t,0);return $P(r)?r:void 0};return{debug:(t,n)=>e.debug?.(t,r(n)),info:(t,n)=>e.info?.(t,r(n)),warn:(t,n)=>e.warn?.(t,r(n))}}function YP(e){const{fetch:t,logSuccessfulExchanges:r=!0,redactLogText:n}=e,o=void 0===n?e.logger:QP(e.logger,n);return async(s,i)=>{const a=Date.now(),c="function"==typeof e.metadata?e.metadata(s):e.metadata,l=!0===e.redactEchoedSessionId?function(e,t,r){const n=DP(e,t).get("mcp-session-id")?.trim()??"";return e=>{const t=n.length>=8?e.split(n).join(zP):e;return r(t.replace(GP,zP))}}(s,i,n??qP):n??qP;try{const e=await t(s,i),{responseErrorSummary:n,oauthTokenErrorBodySummary:u}=e.ok?{}:await JP({input:s,init:i,response:e,redact:l});return!r&&e.ok||ZP((()=>{!function(e){const{logger:t,response:r}=e,n=function(e){const{input:t,init:r,response:n,durationMs:o,metadata:s,responseErrorSummary:i,oauthTokenErrorBodySummary:a}=e,c=jP({input:t,init:r}),l=LP(c.contentType,r?.body);return{event:"mcp_http_exchange",outcome:n.ok?"success":"http_error",durationMs:o,cursorMcp:{transport:{...s,request:c,response:UP(n,i),...void 0!==l?{oauth:{grantType:l}}:{},...void 0!==a?{oauthTokenErrorBodySummary:a}:{}}}}}(e);r.ok?t.info?.("MCP HTTP exchange completed",n):function(e){return 401===e.response.status&&null===e.request.authorizationScheme&&e.response.headers.has("www-authenticate")&&!HP(e.input,e.init)}({response:r,request:n.cursorMcp.transport.request,input:e.input,init:e.init})?t.debug?.("MCP HTTP exchange completed",n):t.warn?.("MCP HTTP exchange completed",n)}({logger:o,input:s,init:i,response:e,durationMs:Date.now()-a,metadata:c,responseErrorSummary:n,oauthTokenErrorBodySummary:u})}),o,"success"),e}catch(t){const r=function(e){if(!uP(e))return;const t=uP(e.cause)?e.cause:void 0,r=[e.response,t?.response];for(const e of r)if("object"==typeof(n=e)&&null!==n&&"status"in n&&"number"==typeof n.status&&"headers"in n&&"object"==typeof n.headers&&null!==n.headers&&"get"in n.headers&&"function"==typeof n.headers.get)return e;var n}(t),{responseErrorSummary:u,oauthTokenErrorBodySummary:d}=r?await JP({input:s,init:i,response:r,redact:l}):{};throw ZP((()=>{!function(e){const{logger:t}=e;t.warn?.("MCP HTTP exchange failed",function(e){const{input:t,init:r,error:n,durationMs:o,metadata:s,responseFromError:i,responseErrorSummary:a,oauthTokenErrorBodySummary:c}=e,l=EP(n,e.redactLogText),u=jP({input:t,init:r}),d=LP(u.contentType,r?.body);return{event:"mcp_http_exchange",outcome:"error",durationMs:o,cursorMcp:{transport:{...s,request:u,response:void 0!==i?UP(i,a):{status:l.httpStatus??null,ok:null,headers:{names:[],count:0},contentType:null,body:{kind:"none",bytes:null,contentLength:null,...void 0!==a?{errorSummary:a}:{}},requestId:null,sessionIdHash:null,wwwAuthenticateHash:null,mcpProtocolVersion:null,retryAfter:null,slackRateLimitType:null},...void 0!==d?{oauth:{grantType:d}}:{},...void 0!==c?{oauthTokenErrorBodySummary:c}:{},error:WP(l)}}}}(e))}({logger:o,input:s,init:i,error:t,durationMs:Date.now()-a,metadata:c,responseFromError:r,responseErrorSummary:u,oauthTokenErrorBodySummary:d,redactLogText:!0===e.redactEchoedSessionId?l:n})}),o,"failure"),t}}}function eR(e,t){const r=e?.access_token,n="string"==typeof r?r.length:0,o=Boolean(e?.refresh_token),s="number"==typeof e?.expires_in&&Number.isFinite(e.expires_in)?e.expires_in:null;return{accessTokenLen:n,refreshTokenPresent:o,expiresAtTimestamp:t?.expiresInIsFresh&&null!==s?Date.now()+Math.round(1e3*s):null,grantedScope:"string"==typeof e?.scope&&e.scope.length>0?e.scope:null}}function tR(e){const t=function(e){if(!e||"object"!=typeof e)return;const t=e.code;if("number"==typeof t&&t>=100&&t<=599)return t;if("string"==typeof t&&/^\d{3}$/.test(t)&&Number(t)>=100&&Number(t)<=599)return Number(t);const r=e instanceof Error||"object"==typeof e&&null!==e&&"message"in e&&"string"==typeof e.message?e.message:void 0;if(!r)return;const n=r.match(/\bHTTP\s+(\d{3})\b/i);if(!n?.[1])return;const o=Number.parseInt(n[1],10);return Number.isNaN(o)?void 0:o}(e);return void 0!==t?400===t||404===t||405===t:!!(e instanceof Error&&e.message.toLowerCase().includes("sessionid must be provided"))||function(e){if(!(e instanceof Error))return!1;const t="code"in e&&"string"==typeof e.code?e.code:void 0,r="cause"in e&&"object"==typeof e.cause&&null!==e.cause&&"code"in e.cause&&"string"==typeof e.cause.code?e.cause.code:void 0;return"ECONNREFUSED"===t||"ECONNREFUSED"===r||e.message.includes("ECONNREFUSED")}(e)}function rR(e,t=process.env){const r=t.TMPDIR,n={...void 0===r?{}:{TMPDIR:r},...e},{NODE_COMPILE_CACHE:o,...s}=n;return{...s,NODE_DISABLE_COMPILE_CACHE:"1"}}const nR=["PYTHONIOENCODING","PYTHONUTF8","PYTHONLEGACYWINDOWSSTDIO"],oR=[".exe",".cmd",".bat"],sR=/^pythonw?(?:\d+(?:\.\d+)*t?)?$/,iR=new Set(["py","pyw"]),aR=new Set(["--cache-dir","--color","--allow-insecure-host","--directory","--project","--config-file"]),cR=new Set;function lR(e){return nR.some((t=>function(e,t){const r=t.toUpperCase();return Object.entries(e).some((([e,t])=>void 0!==t&&e.toUpperCase()===r))}(e,t)))}function uR(e,t){for(let r=0;r=2&&e.endsWith(t)?e.slice(1,-1):e}(e.trim())).toLowerCase();for(const e of oR)if(t.endsWith(e))return t.slice(0,-e.length);return t}(e);if(sR.test(r)||iR.has(r)||"uvx"===r)return!0;if("uv"===r){const e=uR(t,aR);return"run"===e?.value||"tool"===e?.value&&"run"===uR(e.rest,aR)?.value}return"pipx"===r&&"run"===uR(t,cR)?.value}(n,o)?lR(i)||lR(r)?i:{...i,PYTHONIOENCODING:"utf-8:surrogateescape"}:i}async function hR(e){const t=[],r=new Set;let n;for(let o=1;;o++){const s=await e.fetchPage(n),i=e.itemsOf(s);t.push(...i);const a=e.nextCursorOf(s);if(!a||r.has(a))return t;if(o>=1e3)throw new Error("MCP list did not end after 1000 pages; refusing to keep paging");r.add(a),n=a}}var pR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"),fR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js"),mR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js"),gR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js");var wR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js");function yR(e){return`${typeof e}:${String(e)}`}function vR(e){const t=new Map,r=new Set,n=new Set,o=e=>{for(const t of n)t(e)},s=e=>{t.delete(e),r.delete(e)},i=e.send.bind(e);e.send=(e,n)=>((e=>{if("method"in e)if("tools/call"===e.method&&"id"in e){const r=e.params?.name;"string"==typeof r&&t.set(yR(e.id),r)}else if("notifications/cancelled"===e.method){const n=e.params?.requestId;if("string"!=typeof n&&"number"!=typeof n)return;const o=yR(n);if(!t.has(o))return;if(r.add(o),r.size>64){const e=r.values().next().value;void 0!==e&&s(e)}}})(e),i(e,n));const a=e.onmessage;return e.onmessage=(e,n)=>{(e=>{if("method"in e)return void("notifications/tools/list_changed"===e.method&&o({kind:"tools_list_changed"}));if(!("id"in e))return;const n=e.id;if("string"!=typeof n&&"number"!=typeof n)return;const i=yR(n),a=t.get(i);if(void 0===a)return;const c=r.has(i);if(s(i),!c)return;const l="error"in e||"object"==typeof e.result&&null!==e.result&&"isError"in e.result&&!0===e.result.isError;o({kind:"late_tool_result",toolName:a,isError:l})})(e),a?.(e,n)},{subscribe:e=>(n.add(e),()=>{n.delete(e)})}}function bR(e){const t=Object.entries(e.headers??{}).map((([e,t])=>[e.toLowerCase(),t])).sort((([e],[t])=>et?1:0));return(0,ko.createHash)("sha256").update(JSON.stringify([e.url,t,e.accessToken??null])).digest("hex")}class SR{constructor(e,t){this.inner=e,this.initializeResult=t,e.onclose=()=>this.onclose?.(),e.onerror=e=>this.onerror?.(e),e.onmessage=e=>this.onmessage?.(e)}get sessionId(){return this.inner.sessionId}setProtocolVersion(e){this.inner.setProtocolVersion(e)}start(){return this.inner.start()}close(){return this.inner.close()}async send(e,t){if((0,Fx.vo)(e)&&(0,Fx.eK)(e)){const t={jsonrpc:"2.0",id:e.id,result:this.initializeResult};queueMicrotask((()=>this.onmessage?.(t)))}else(0,Fx.wU)(e)||await this.inner.send(e,t)}}const kR=Be.object({tools:Be.array(Be.unknown()),nextCursor:Be.unknown().optional(),_meta:Be.unknown().optional()}),_R={typeFilled:0,toolDropped:0,outputStripped:0};function CR(e){if(TR(e))return"string"==typeof e.name?e.name:void 0}function ER(e){return xR(e.issues.filter((e=>"outputSchema"===e.path[0])))}function xR(e){return e.map((e=>`${e.path.map(String).join(".")}: ${e.message}`))}function PR(e){if(!TR(e))return e;const t={...e};return delete t.outputSchema,t}function RR(e){return TR(e)&&!("type"in e)}function IR(e,t){return{...e,inputSchema:{type:"object",...t}}}function TR(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var AR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js");const $R=new class{constructor({maxSchemasPerCompiler:e=2048,createCompiler:t=()=>new AR.p}={}){this.compiled=new Map,this.maxSchemasPerCompiler=e,this.createCompiler=t,this.compiler=t()}get compiledSchemaCount(){return this.compiled.size}getValidator(e){let t;return r=>(t??=this.compile(e),t(r))}compile(e){const t=JSON.stringify(e),r=(0,ko.createHash)("sha256").update(t).digest("base64url"),n=this.compiled.get(r);if(void 0!==n)return n;this.compiled.size>=this.maxSchemasPerCompiler&&(this.compiler=this.createCompiler(),this.compiled.clear());const o=(t.includes('"$id"')?this.createCompiler():this.compiler).getValidator(e);return this.compiled.set(r,o),o}};class MR{constructor(){this.decoder=new TextDecoder("utf-8"),this.captured="",this.capturedBytes=0}push(e){const t="string"==typeof e?e:this.decoder.decode(e,{stream:!0});return this.append(t),t}end(){const e=this.decoder.decode();return this.append(e),e}get text(){return this.captured}get full(){return this.capturedBytes>=ix}append(e){const t=ix-this.capturedBytes;if(t<=0||0===e.length)return;const r=function(e,t){if(!(t>0))return"";if(3*e.length<=t)return e;const{read:r}=Yo(e,Math.trunc(t));return r>=e.length?e:e.slice(0,r)}(e,t);this.captured+=r,this.capturedBytes=r.length=100&&t<=599?{error_class:"http",error_code:String(t),transport:e.transport}:void 0!==e.error||!0===e.failed?{error_class:"other",error_code:"exception",transport:e.transport}:!0===e.isError?{error_class:"payload",error_code:"is_error",transport:e.transport}:{error_class:"none",error_code:"none",transport:e.transport}}({transport:ax(t),...r}))}catch{}}const UR=(0,h.Pu)("mcp_tool.oauth_scope_step_up",{description:"A tools/call refused for a missing OAuth scope, by step-up decision",labelNames:["decision","dropped"]});function BR(e){return void 0===e?"unknown":"url"in e?"http":"stdio"}const WR=["authorization_code","refresh_token"],HR=["code"];class qR{constructor(e){this._refreshInProgress=!1,this._identifier=e.identifier,this._redirectUrl=e.redirectUrl,this._serverUrl=e.serverUrl,this._restMcpProviderMetadata=e.restMcpProviderMetadata,this.validateResourceURL=!0===e.restMcpProviderMetadata?.omitResourceIndicator?async()=>{}:function(e,t){if(function(e,t){const r=t.gtmApiOrigin;if(void 0===e||void 0===r)return!1;let n,o;try{n=new URL(e),o=new URL(r)}catch{return!1}return n.protocol===o.protocol&&n.hostname===o.hostname&&""===n.port&&"/mcp"===n.pathname}(e,t))return async()=>{};const r=kb(e);return void 0!==r&&function(e){return"https:"===e.protocol&&e.hostname===new URL(ub).hostname}(r)?async()=>{}:void 0!==r&&function(e){return"https:"===e.protocol&&"setup.shopify.com"===e.hostname&&""===e.port&&"/mcp"===e.pathname}(r)?_b:bb}(e.serverUrl,e.gtmMcpMatch),this._clientMetadata=e.clientMetadata,this._scopes=e.scopes,this._isScopePinGateEnabled=e.isScopePinGateEnabled,this.scopeStepUp=e.scopeStepUp,this._tokens=e.tokens,this._clientInformation=e.clientInformation,this._saveTokens=e.saveTokens,this._prepareForRefresh=e.prepareForRefresh,this._releaseRefreshLeaseOnError=e.releaseRefreshLeaseOnError,this._invalidateCredentials=e.invalidateCredentials,this._saveClientInformation=e.saveClientInformation,this.addClientAuthentication=e.addClientAuthentication}get redirectUrl(){return this._redirectUrl}get clientMetadata(){return this._clientMetadata}state(){return this._oauthAttemptId=(0,ko.randomUUID)(),this._oauthState=function(e,t,r){const n={id:e,owner:t,...r?{attemptId:r}:{}};return Buffer.from(JSON.stringify(n),"utf8").toString("base64url")}(this._identifier,{workspaceId:this._redirectUrl},this._oauthAttemptId),this._oauthState}clientInformation(){return this._clientInformation}hasClientInformation(){return void 0!==this._clientInformation}async saveClientInformation(e){this._clientInformation=e,await this._saveClientInformation(e)}tokens(){return this.scopeStepUp?.tokensForSdk(this._tokens)??this._tokens}async saveTokens(e){const t=this._refreshInProgress;this._refreshInProgress=!1,this._tokens=e,await this._saveTokens(e),await(this.scopeStepUp?.recordTokens(e,{isRefresh:t}))}async prepareForRefresh(){await(this._prepareForRefresh?.()),this._refreshInProgress=!0}async releaseRefreshLeaseOnError(e){this._refreshInProgress=!1,await(this._releaseRefreshLeaseOnError?.(e))}async invalidateCredentials(e){switch(this._refreshInProgress=!1,e){case"tokens":this._tokens=void 0;break;case"client":this._clientInformation=void 0;break;case"verifier":this._codeVerifier=void 0,this._oauthState=void 0,this._oauthAttemptId=void 0;break;case"all":this._tokens=void 0,this._clientInformation=void 0,this._codeVerifier=void 0,this._oauthState=void 0,this._oauthAttemptId=void 0,this._lastRedirectUrl=void 0,await(this.scopeStepUp?.clear({keepPendingScopes:!0}));break;default:return e}await(this._invalidateCredentials?.(e))}async redirectToAuthorization(e){const t=await(this.scopeStepUp?.prepareAuthorization());(function(e,t,r={}){const n=r.stepUpScopes??[],o=void 0!==t&&t.length>0?t:n.length>0?(e.searchParams.get("scope")??"").split(" ").filter((e=>e.length>0)):void 0;var s;void 0!==o&&e.searchParams.set("scope",(s={scopes:o,stepUpScopes:n},[...new Set([...s.scopes,...s.stepUpScopes])]).join(" "))})(e,function(e,t,r){const n=yb(e);return!0!==n?.pinsScopesOverConfiguredScopes?void 0!==t&&t.length>0||void 0===r?t:Cb(e)?.baseScopes??t:void 0!==n.scopesPinGate&&!0!==r?.(n.scopesPinGate)?t:n.scopes??t}(this._serverUrl??"",this._scopes,this._isScopePinGateEnabled),{stepUpScopes:t?.stepUpScopes}),void 0!==this._serverUrl&&function(e,t){const r=yb(t)?.authorizationParams;if(void 0!==r)for(const[t,n]of Object.entries(r))e.searchParams.set(t,n)}(e,this._serverUrl);for(const[t,r]of Object.entries(this._restMcpProviderMetadata?.authorizationParams??{}))e.searchParams.set(t,r);(!0===this._restMcpProviderMetadata?.omitConsentPrompt||function(e){return"login.microsoftonline.com"===e.hostname}(e))&&function(e){const t=new Set(e.searchParams.getAll("prompt").flatMap((e=>e.split(" "))).filter((e=>""!==e&&"consent"!==e)));e.searchParams.delete("prompt"),t.size>0&&e.searchParams.set("prompt",[...t].join(" "))}(e),await(t?.recordRequestedScopes(e)),this._lastRedirectUrl=e}get lastRedirectUrl(){return this._lastRedirectUrl}async saveCodeVerifier(e){this._codeVerifier=e}codeVerifier(){if(!this._codeVerifier)throw new Error("No code verifier saved");return this._codeVerifier}}async function zR(e){const{serverName:t,config:n,tokenStorage:o}=e,s=await dx(n.url,e.fetchImpl),i=Db({loopbackIpv4:s?.loopbackIpv4,redirectUrl:e.authRedirectUrl}),a=function(e,t){const r=lx(e?.CLIENT_ID);if(void 0!==r)return{client_id:r,...e?.CLIENT_SECRET?{client_secret:e.CLIENT_SECRET}:{},redirect_uris:Ob(t),grant_types:[...WR],response_types:[...HR],token_endpoint_auth_method:"none"}}(n.auth,i),c=function({storedClientInformation:e,staticClientInformation:t}){return t?e&&e.client_id===t.client_id?{...t,...e,client_secret:t.client_secret??e.client_secret,redirect_uris:t.redirect_uris,grant_types:e.grant_types??t.grant_types,response_types:e.response_types??t.response_types,token_endpoint_auth_method:e.token_endpoint_auth_method??t.token_endpoint_auth_method}:t:e}({storedClientInformation:await o.loadClientInformation(),staticClientInformation:a});return new qR({identifier:t,redirectUrl:i,serverUrl:n.url,restMcpProviderMetadata:s,gtmMcpMatch:e.gtmMcpMatch??{gtmApiOrigin:void 0},clientMetadata:{redirect_uris:Ob(i),token_endpoint_auth_method:"none",grant_types:[...WR],response_types:[...HR],client_name:"Cursor",logo_uri:"https://ptht05hbb1ssoooe.public.blob.vercel-storage.com/assets/uploads/cursorlogomcpv3.svg"},scopes:n.auth?.scopes,isScopePinGateEnabled:e.isScopePinGateEnabled,...!0===e.scopeChallengeStepUp&&void 0!==o.loadScopeStepUpRecord&&void 0!==o.saveScopeStepUpRecord?{scopeStepUp:Px({serverUrl:n.url,accountKey:t,configuredScopes:n.auth?.scopes,readTokenScope:async()=>void 0!==o.loadGrantedScope?o.loadGrantedScope():(await o.loadTokens())?.scope,readRecord:async()=>o.loadScopeStepUpRecord?.(),writeRecord:async e=>o.saveScopeStepUpRecord?.(e),readScopesSupported:t=>async function(e){try{const{discoverAuthorizationServerMetadata:t,discoverOAuthProtectedResourceMetadata:n}=await Promise.resolve().then(r.bind(r,"../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js")),o=await n(e.serverUrl,void 0!==e.resourceMetadataUrl?{resourceMetadataUrl:new URL(e.resourceMetadataUrl)}:void 0,e.fetch),s=await t(o.authorization_servers?.[0]??new URL("/",e.serverUrl),{fetchFn:e.fetch}).catch((()=>{}));if(void 0===s&&!0===e.requireAuthorizationServerMetadata)return;const i=new Set([...o.scopes_supported??[],...s?.scopes_supported??[]]);return i.size>0?[...i]:void 0}catch{return}}({serverUrl:n.url,resourceMetadataUrl:t,fetch:e.fetchImpl})})}:{},tokens:await o.loadTokens(),clientInformation:c,saveTokens:e=>o.saveTokens(e),prepareForRefresh:()=>o.prepareForRefresh?.()??Promise.resolve(),releaseRefreshLeaseOnError:e=>o.releaseRefreshLeaseOnError?.(e)??Promise.resolve(),invalidateCredentials:o.invalidateCredentials?e=>o.invalidateCredentials(e):void 0,saveClientInformation:e=>o.saveClientInformation(e),addClientAuthentication:o.tokenEndpointAuth?.({clientId:c?.client_id})})}const GR=new Set;let VR=!1;function KR(){for(const e of GR)try{process.kill(e,"SIGKILL")}catch{}}function JR(e){return $x(e)?new pR.D_:e}function ZR(e,t){return Yx(e??globalThis.fetch.bind(globalThis),{serverUrl:t})}function XR(e,t,r){const n=eP(e,t),o=r??(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),s=void 0!==n.cursorAuthHeaderValue&&void 0!==n.cursorAuthOrigin&&void 0!==o?tP((()=>n.cursorAuthHeaderValue),n.cursorAuthOrigin,o):o;return{transportHeaders:n.headers,baseFetch:s}}class QR{constructor(e,t,r){this._toolListGeneration=0,this._toolListSuccessGeneration=0,this._toolListStateGeneration=0,this._callToolLock=Promise.resolve(),this._callToolQueueDepth=0,this._stateEnteredAtMs=Date.now(),this._terminatingSession=!1,this._closeRequested=!1,this.serverName=e,this.client=t,this.tools=new rP,this.stateValue=r.initialState,this._authProvider=r.authProvider,this._authCodeExchange=r.authCodeExchange,this._sessionId=r.sessionId,this._protocolVersion=r.protocolVersion,this._resumedInstructions=r.resumedInstructions,this._sessionlessInitialize=r.sessionlessInitialize,this.config=r.config,this._oauthLifecycleLogger=r.oauthLifecycleLogger,this._serverSignals=r.serverSignals,this._redactLogText=r.redactLogText,this.setupElicitationHandler(),!0===r.stdioServer&&(t.onclose=()=>{this._closeRequested||(this.updateState({kind:"error",message:"MCP server exited"},"stdio_exited"),this.tools.invalidate())})}_stateKindLabel(e){return"requires_authentication"===e.kind?"needsAuth":e.kind}_logStateTransition(e,t,r,n){if(!this._oauthLifecycleLogger)return;const o=this._stateKindLabel(e),s=this._stateKindLabel(t);if(o===s)return;const i=Date.now()-this._stateEnteredAtMs,a=(()=>{try{const e=this.config&&"url"in this.config?this.config.url:void 0;return e?new URL(e).host:void 0}catch{return}})();PP({logger:this._oauthLifecycleLogger,event:"mcp_oauth_state_transition",metadata:{identifier:this.serverName,from:o,to:s,cause:r,serverUrlHost:a,previousStateDurationMs:i,...n}})}static createClient(e={}){const t={elicitation:{form:{}},...!1===e.mcpAppsUi?{}:{extensions:{"io.modelcontextprotocol/ui":{mimeTypes:["text/html;profile=mcp-app"]}}}};return new wR.K({name:"Cursor",version:"1.0.0"},{capabilities:t,jsonSchemaValidator:$R})}setupElicitationHandler(){this.client.setRequestHandler(Fx.$9,(async e=>{if(!this._currentElicitationProvider)return{action:"decline"};if(!("requestedSchema"in e.params))return{action:"decline"};try{const t=e.params.requestedSchema,r=await this._currentElicitationProvider.elicit({message:e.params.message,requestedSchema:t});return{action:r.action,content:r.content}}catch(e){return{action:"decline"}}}))}static async fromStreamableHttp(e,t,r,n,o,s,i,a,c,l,u,d=!1,h={}){const p=new URL(t.url);o=o??Tb;const f=await zR({serverName:e,config:t,tokenStorage:r,authRedirectUrl:o,fetchImpl:s,gtmMcpMatch:c,isScopePinGateEnabled:l,scopeChallengeStepUp:u}),m=f.tokens(),g=eP(t.url,n),w=g.headers,y=d&&function(e){return Object.entries(e??{}).some((([e,t])=>"authorization"===e.toLowerCase()&&t.trim().length>0))}(w)?void 0:f,v=s??(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),b=void 0!==g.cursorAuthHeaderValue&&void 0!==g.cursorAuthOrigin&&void 0!==v?tP((()=>g.cursorAuthHeaderValue),g.cursorAuthOrigin,v):v,S=e=>void 0===b||void 0===i?b:YP({fetch:b,logger:i.logger,metadata:{...i.metadata,transportType:e},redactLogText:i.redactLogText});let k;const _=e=>{const r=f.scopeStepUp,n=e??v;return void 0===r||void 0===n?e:(o={fetch:n,scopeStepUp:r,serverUrl:t.url,startSignIn:async e=>{const t=void 0!==e.resourceMetadataUrl&&URL.canParse(e.resourceMetadataUrl)?new URL(e.resourceMetadataUrl):void 0;await(0,pR.j2)(f,{serverUrl:p.toString(),...void 0!==t?{resourceMetadataUrl:t}:{},...void 0!==b?{fetchFn:b}:{}});const r=f.lastRedirectUrl;k=void 0!==r&&void 0!==t?{redirectUrl:r,resourceMetadataUrl:t}:void 0}},async(e,t)=>{const r=await o.fetch(e,t);if(401!==r.status&&403!==r.status||!function(e){if("string"!=typeof e)return!1;let t;try{t=JSON.parse(e)}catch{return!1}return(Array.isArray(t)?t:[t]).some((e=>"object"==typeof e&&null!==e&&"method"in e&&"tools/call"===e.method))}(t?.body))return r;const n=await o.scopeStepUp.decide({status:r.status,wwwAuthenticate:r.headers.get("www-authenticate"),toolName:Ax(t?.body)});if(void 0===n)return r;if(o.onDecision?.(n),await(r.body?.cancel().catch((()=>{}))),"offer"===n.kind)try{await o.scopeStepUp.signIn((()=>o.startSignIn(n)))}catch(e){px(o.scopeStepUp.accountKey).warn("MCP OAuth scope step-up: could not start the sign-in",{event:"mcp_oauth_scope_step_up_sign_in_failed",errorName:e instanceof Error?e.name:typeof e})}throw new Tx(n,o.serverUrl,o.scopeStepUp.connectorName)});var o},C=QR.createClient(h),E=e=>e instanceof pR.D_||function(e){if(null===e||"object"!=typeof e)return!1;const t=e.name;if("string"==typeof t&&Mx.has(t))return!0;const r=e.errorCode;return!("string"!=typeof r||!Dx.has(r.toLowerCase()))||function(e){if(null===e||"object"!=typeof e)return!1;const t=e.name,r=e.errorCode;if("InvalidRequestError"!==t&&("string"!=typeof r||"invalid_request"!==r.toLowerCase()))return!1;const n=e.message;return"string"==typeof n&&Ox.some((e=>e.test(n)))}(e)}(e)||$x(e),x=async t=>{if(!f.hasClientInformation())throw new Error("OAuth client registration has not completed. The MCP server may not support dynamic client registration or the registration failed.");const r=void 0!==k&&k.redirectUrl===f.lastRedirectUrl?k.resourceMetadataUrl:void 0;await(0,pR.j2)(f,{serverUrl:p.toString(),authorizationCode:t,...void 0!==r?{resourceMetadataUrl:r}:{},...void 0!==b?{fetchFn:b}:{}}),a&&PP({logger:a,event:"mcp_oauth_callback_completion",metadata:{identifier:e,...iP(p.toString()),...eR(f.tokens(),{expiresInIsFresh:!0})}})},P=r=>{const n=f.lastRedirectUrl?.toString?.()??"",o=new QR(e,C,{oauthLifecycleLogger:a,redactLogText:i?.redactLogText,initialState:{kind:"requires_authentication",url:n,callback:async e=>{try{await x(e),o.updateState({kind:"ready"})}catch(e){const t=e instanceof Error?e.message:"Authentication failed";throw new Error(`Authentication callback failed: ${t}`)}}},authProvider:f,authCodeExchange:x,sessionId:r,config:t});return o},R=async r=>{const n=new fR.A(p,{authProvider:y,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...w??{}}},fetch:_(S("sse"))});try{return await C.connect(n),new QR(e,C,{initialState:{kind:"ready"},authProvider:f,authCodeExchange:x,config:t,oauthLifecycleLogger:a,redactLogText:i?.redactLogText})}catch(t){if(await n.close().catch((()=>{})),E(t))return a&&PP({logger:a,event:"mcp_oauth_state_transition",metadata:{identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"sse",refreshTokenPresent:Boolean(m?.refresh_token),...iP(p.toString()),...EP(t,i?.redactLogText)}}),P();if(void 0!==r&&tR(t)&&t instanceof fR._)throw function(e,t){let r=e;for(let e=0;e<8&&r instanceof Error&&r.cause instanceof Error;e++)r=r.cause;return r instanceof Error&&void 0===r.cause&&Reflect.defineProperty(r,"cause",{value:t,writable:!0,configurable:!0,enumerable:!1}),e}(r,t);throw t}};if("sse"===t.type)return R();const I=new gR.j(p,{authProvider:y,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...w??{}}},fetch:_(ZR(S("streamableHttp"),p))});try{await C.connect(I);const r=function(e,t=Date.now){return Vx(Gx(e),t)}(t.url)?void 0:function(e,r){const o=r.protocolVersion;if(void 0!==r.sessionId||void 0===o)return;const s=e.getServerCapabilities(),i=e.getServerVersion();if(void 0===s||void 0===i)return;const a=e.getInstructions();return{result:{protocolVersion:o,capabilities:s,serverInfo:i,...void 0===a?{}:{instructions:a}},credentialFingerprint:bR({url:t.url,headers:n,accessToken:f.tokens()?.access_token})}}(C,I);return new QR(e,C,{initialState:{kind:"ready"},authProvider:f,authCodeExchange:x,sessionId:I.sessionId,protocolVersion:I.protocolVersion,...void 0===r?{}:{sessionlessInitialize:r},config:t,oauthLifecycleLogger:a,redactLogText:i?.redactLogText})}catch(t){if(E(t))return a&&PP({logger:a,event:"mcp_oauth_state_transition",metadata:{identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"streamableHttp",refreshTokenPresent:Boolean(m?.refresh_token),...iP(p.toString()),...EP(t,i?.redactLogText)}}),P(I.sessionId);if(tR(t))return R(t);throw t}}static async fromStreamableHttpWithoutOAuth(e,t,r){const n=QR.createClient(),o=new gR.j(new URL(t.url),{requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...t.headers}},fetch:r});return await n.connect(o),new QR(e,n,{initialState:{kind:"ready"},sessionId:o.sessionId,protocolVersion:o.protocolVersion,config:t})}static async fromCachedSession(e,t,r,n,o,s=Tb,i,a,c,l,u){const d=new URL(t.url),h=await zR({serverName:e,config:t,tokenStorage:n,authRedirectUrl:s,fetchImpl:i,gtmMcpMatch:l,isScopePinGateEnabled:u}),{transportHeaders:p,baseFetch:f}=XR(t.url,o,i),m=new gR.j(d,{authProvider:h,sessionId:r.sessionId,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...p??{}}},fetch:void 0!==f&&void 0!==a?YP({fetch:f,logger:a.logger,metadata:{...a.metadata,transportType:"streamableHttp"},redactLogText:a.redactLogText}):f});m.setProtocolVersion(r.protocolVersion);const g=function(e){return e._requestMessageId=(0,ko.randomInt)(1048576,2146435072),e}(QR.createClient());return await g.connect(m),new QR(e,g,{initialState:{kind:"ready"},authProvider:h,sessionId:m.sessionId,protocolVersion:r.protocolVersion,...void 0===r.instructions?{}:{resumedInstructions:r.instructions},config:t,oauthLifecycleLogger:c,redactLogText:a?.redactLogText})}static async fromSessionlessInitialize(e,t,r,n,o,s=Tb,i,a,c,l){const u=await zR({serverName:e,config:t,tokenStorage:n,authRedirectUrl:s,fetchImpl:i,gtmMcpMatch:a,isScopePinGateEnabled:c});if(bR({url:t.url,headers:o,accessToken:u.tokens()?.access_token})!==r.credentialFingerprint)return;const{transportHeaders:d,baseFetch:h}=XR(t.url,o,i),p=new gR.j(new URL(t.url),{authProvider:u,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...d??{}}},fetch:h}),f=QR.createClient();return await f.connect(new SR(p,r.result)),new QR(e,f,{initialState:{kind:"ready"},authProvider:u,sessionlessInitialize:r,config:t,redactLogText:l})}get sessionId(){return this._sessionId}get protocolVersion(){return this._protocolVersion}get sessionlessInitialize(){return this._sessionlessInitialize}get holdsOAuthAccessToken(){return Boolean(this._authProvider?.tokens()?.access_token)}async openStandaloneStream(){const e=this.client.transport;e instanceof gR.j&&await e.resumeStream("")}static async fromCommand(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{OR(s,(0,D.VI)(e.withName("McpSdkClient.fromCommand")),!1);const l=(c=o?.spawn,void 0!==c||"linux"!==process.platform?c:(e,t,r)=>(0,au.D9)(iu.spawn,e,t,r)),u=r.args??[],d=new mR.oQ({command:r.command,args:u,env:rR(dR({command:r.command,args:u,env:n})),cwd:r.cwd,stderr:"pipe",...l&&{spawn:l}}),h=function(e){const t=new MR;let r=null===e;return null!==e&&(e.on("data",(e=>{t.full||t.push(e)})),e.once("end",(()=>{t.end(),r=!0}))),{read:()=>_P(t.text.replace(/\s+/g," ").trim(),{maxLength:ix}),waitForFlush:async()=>{r||null===e||await new Promise((t=>{let r;const n=()=>{void 0!==r&&clearTimeout(r),e.off("end",n),t()};r=setTimeout(n,250),r.unref(),e.once("end",n)}))}}}(d.stderr),p=QR.createClient({mcpAppsUi:o?.mcpAppsUi}),f=o?.connectTimeoutMs??(void 0!==(a=r.startupTimeoutSec)&&Number.isFinite(a)&&a>0?Math.min(1e3*a,3e5):6e4);let m;d.onclose=()=>{var e;void 0!==m&&(e=m,GR.delete(e))};let g=0,w=!0;d.onerror=e=>{w&&function(e){return e instanceof SyntaxError||"ZodError"===e.name}(e)&&(g+=1)};const y=new AbortController,v=p.connect(d,{timeout:f,signal:y.signal});let b;m=d.pid??void 0,void 0!==m&&(i=m,GR.add(i),VR||(VR=!0,process.on("exit",KR)));const S=new Promise(((e,r)=>{b=setTimeout((()=>r(new Error(`MCP server connection timed out after ${f}ms: ${t}`))),f)}));try{await Promise.race([v,S])}catch(e){throw y.abort(),v.catch((()=>{})),await d.close().catch((()=>{})),await h.waitForFlush(),g>0&&e instanceof Error&&(e.message=`${e.message}; non-JSON-RPC output on stdout before initialize (${String(g)} line${1===g?"":"s"})`),function(e,t){if(""===t)return e;const r=e instanceof Error?e:new Error(String(e));return r.message=`${r.message}; stderr: ${t}`,DR.set(r,t),r}(e,h.read())}finally{w=!1,void 0!==b&&clearTimeout(b)}return new QR(t,p,{initialState:{kind:"ready"},config:r,stdioServer:void 0!==m,serverSignals:vR(d)})}catch(e){s.error=e,s.hasError=!0}finally{FR(s)}var i,a,c}terminateSessionOnClose(e){this._sessionTermination=e}setToolCallRequestOptions(e){this._toolCallRequestOptions=e}failToolCallInFlight(e){const t=this._toolCallInFlight;return void 0!==t&&!t.signal.aborted&&(t.abort(e),!0)}onServerSignal(e){return this._serverSignals?.subscribe(e)??(()=>{})}setToolCallOutputSchemaPassthrough(e){this._toolCallOutputSchemaPassthrough=e}async close(){if(this._closeRequested=!0,this._terminatingSession)return;const e=this._sessionTermination,t=this.client.transport;if(void 0!==e&&t instanceof gR.j)return this._terminatingSession=!0,void(async()=>{await async function(e,t){const r=await async function(e,t){if(void 0===e.sessionId)return{outcome:"no_session",durationMs:0};const r=Date.now(),n=e.terminateSession();n.catch((()=>{}));try{await(0,Nr.wj)(n,t.timeoutMs)}catch(e){const t=Date.now()-r;return e instanceof Nr.MU?{outcome:"timeout",durationMs:t}:e instanceof gR.b&&void 0!==e.code&&e.code>0?{outcome:"rejected",durationMs:t,httpStatus:e.code,error:e.message}:{outcome:"failed",durationMs:t,error:String(e)}}const o=t.deleteObserver?.lastDeleteStatus;return{outcome:405===o?"unsupported":"terminated",durationMs:Date.now()-r,...void 0!==o?{httpStatus:o}:{}}}(e,t);try{t.onResult?.(r)}catch{}return r}(t,e),await this.client.close()})().catch((()=>{}));await this.client.close()}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=OR(t,(0,D.VI)(e.withName("McpSdkClient.getTools")),!1);if(r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("mcp.transport",BR(this.config)),"requires_authentication"===this.stateValue.kind)return r.span.setAttribute("mcp.tools.requires_authentication",!0),[];if("error"===this.stateValue.kind)return[];const n=++this._toolListGeneration;let o=0,s=0;try{const e=await this.tools.get((async()=>{let e;const t=await hR({fetchPage:async t=>{o++;const n=await async function(e,t,r){try{const r=await e.listTools({cursor:t});return{tools:r.tools,nextCursor:r.nextCursor,meta:r._meta,..._R}}catch(c){if(!(c instanceof Error&&"issues"in c&&Array.isArray(c.issues)))throw c}const n=await e.request({method:"tools/list",params:{cursor:t}},kR),o=[];let s=0,i=0,a=0;for(const e of n.tools){let t=e;if(TR(e)){const r=e.inputSchema;RR(r)&&(t=IR(e,r),s++)}let n=Fx.Dn.safeParse(t);if(!n.success&&(c=n.error).issues.some((e=>"outputSchema"===e.path[0]))){const o=Fx.Dn.safeParse(PR(t));o.success&&(a++,r(CR(e),ER(n.error),"output_stripped"),n=o)}n.success?o.push(n.data):(i++,r(CR(e),xR(n.error.issues),"dropped"))}var c;return{tools:o,nextCursor:"string"==typeof n.nextCursor?n.nextCursor:void 0,meta:n._meta,typeFilled:s,toolDropped:i,outputStripped:a}}(this.client,t,((e,t,n)=>{(function(e,t,r){const n=JSON.stringify([e,t,r]);if(eI.has(n))return eI.delete(n),eI.add(n),!1;if(eI.add(n),eI.size>256){const e=eI.keys().next().value;void 0!==e&&eI.delete(e)}return!0})(n,this.serverName,e??"")&&NR.warn(r.ctx,"output_stripped"===n?"Removed an MCP tool output schema the client rejected":"Left out an MCP tool whose definition is invalid",{serverName:this.serverName,..."string"==typeof e?{toolName:e}:{},issues:t})}));return s+=n.typeFilled,tI(r.ctx,"type_filled",n.typeFilled),tI(r.ctx,"tool_dropped",n.toolDropped),tI(r.ctx,"output_stripped",n.outputStripped),e??=function(e){if(!WC(e))return;const t=e.mcpAllowlist;if(!WC(t)||"string"!=typeof t.list)return;const r=HC(t.name,200),n=HC(t.reason,200);if(void 0===r||void 0===n)return;const o={list:"local"===t.list||"cloud"===t.list?t.list:"other",name:r,reason:n},s=qC(t.allowedServerNames)??qC(t.allowedServers);void 0!==s&&(o.allowedServers=s);const i=qC(t.blockedServers);return void 0!==i&&(o.blockedServers=i),o}(n.meta),n},itemsOf:e=>e.tools,nextCursorOf:e=>e.nextCursor});return this._allowlistInUse=this.reportsCursorMcpAllowlist()?e:void 0,t.map((e=>({...e,inputSchema:eE(e.inputSchema),outputSchema:void 0===e.outputSchema?void 0:eE(e.outputSchema)})))}));return this.noteToolListSuccess(),r.span.setAttribute("mcp.tools.fetched",o>0),r.span.setAttribute("mcp.tools.pages",o),o>0&&r.span.setAttribute("mcp.tools.type_filled",s),r.span.setAttribute("mcp.tools.count",e.length),e}catch(e){const t=JR(e);if(r.span.setAttribute("mcp.tools.fetched",o>0),r.span.setAttribute("mcp.tools.pages",o),o>0&&r.span.setAttribute("mcp.tools.type_filled",s),this.noteToolListFailure(r.ctx,t,n),t instanceof pR.D_&&n===this._toolListGeneration&&n>this._toolListStateGeneration&&"ready"===this.stateValue.kind){const e=this.stateValue,r=this._authProvider?.lastRedirectUrl?.toString()??"";this.stateValue={kind:"requires_authentication",url:r,callback:e=>this.completeRuntimeAuthorization(e)},this.discardToolListError(),this._logStateTransition(e,this.stateValue,"runtime_unauthorized",{...EP(t,this._redactLogText)}),this._stateEnteredAtMs=Date.now()}throw t}}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async getAllowlistInUse(){return this._allowlistInUse}reportsCursorMcpAllowlist(){return void 0!==this.config&&"url"in this.config&&BC(this.config.url)}toolListAttemptIsCurrent(e){return e>this._toolListSuccessGeneration&&e>this._toolListStateGeneration}noteToolListSuccess(){this._toolListError=void 0,this._toolListSuccessGeneration=this._toolListGeneration}discardToolListError(){this._toolListError=void 0,this._toolListStateGeneration=this._toolListGeneration}noteToolListFailure(e,t,r){const n=Fx.O4.MethodNotFound;if(t instanceof Fx.Nh&&t.code===n&&void 0===this.client.getServerCapabilities()?.tools)return void this.noteToolListSuccess();if(t instanceof pR.D_||!this.toolListAttemptIsCurrent(r))return;const o=function(e){if(e instanceof Fx.Nh)return{descriptor:`McpError ${e.code}`,errorClass:"McpError",jsonRpcCode:e.code};if(e instanceof gR.b||e instanceof fR._){const t=e instanceof gR.b?"StreamableHTTPError":"SseError",r="number"==typeof e.code?e.code:void 0;return{descriptor:void 0===r?t:`${t} ${r}`,errorClass:t,...void 0===r?{}:{httpStatus:r}}}return e instanceof Error?{descriptor:"Error",errorClass:"Error"}:{descriptor:"unknown",errorClass:"unknown"}}(t);o.descriptor!==this._toolListError&&NR.warn(e,"MCP server failed to list its tools",{serverName:this.serverName,errorClass:o.errorClass,...void 0!==o.jsonRpcCode?{jsonRpcCode:o.jsonRpcCode}:{},...void 0!==o.httpStatus?{httpStatus:o.httpStatus}:{}}),this._toolListError=o.descriptor}async callTool(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{const a=OR(s,(0,D.VI)(e.withName("McpSdkClient.callTool")),!1);a.span.setAttribute("toolName",t),a.span.setAttribute("serverName",this.serverName),a.span.setAttribute("mcp.transport",BR(this.config));const c=this._callToolLock,l=this._callToolQueueDepth;let u;this._callToolQueueDepth++,this._callToolLock=new Promise((e=>{u=e}));try{{const e={stack:[],error:void 0,hasError:!1};try{const t=OR(e,(0,D.VI)(a.ctx.withName("McpSdkClient.callTool.lockWait")),!1);t.span.setAttribute("serverName",this.serverName),t.span.setAttribute("mcp.call_tool.queued_ahead",l);const r=performance.now();await c;const n=performance.now()-r;t.span.setAttribute("mcp.call_tool.lock_wait_ms",n),a.span.setAttribute("mcp.call_tool.lock_wait_ms",n),a.span.setAttribute("mcp.call_tool.queued_ahead",l)}catch(t){e.error=t,e.hasError=!0}finally{FR(e)}}if("requires_authentication"===this.stateValue.kind)throw new pR.D_(`MCP server "${this.serverName}" requires authentication`);this._currentToolCallId=n,this._currentToolName=t,this._currentElicitationProvider=o;const s=new AbortController;this._toolCallInFlight=s;const u=this._authProvider?.lastRedirectUrl;try{const n={stack:[],error:void 0,hasError:!1};try{const o=OR(n,(0,D.VI)(a.ctx.withName("McpSdkClient.callTool.sdk")),!1);o.span.setAttribute("toolName",t),o.span.setAttribute("serverName",this.serverName);const c=await this.sendToolCall({name:t,arguments:r},s.signal);return o.span.setAttribute("mcp.call_tool.is_error",!0===c.isError),jR(e,this.config,{isError:!0===c.isError}),{content:c.content,isError:!0===c.isError,structuredContent:(i=c.structuredContent,tE(i)),_meta:lE(c._meta)}}catch(e){n.error=e,n.hasError=!0}finally{FR(n)}}catch(t){const r=JR(t);r instanceof Tx?(jR(e,this.config,{error:r,httpStatus:r.decision.status}),function(e,t){try{UR.increment(e,1,{decision:t.decision.kind,dropped:String(t.decision.dropped.length>0)})}catch{}}(e,r)):jR(e,this.config,{error:r});const n=r instanceof Tx&&"offer"===r.decision.kind&&void 0!==this._authProvider?.lastRedirectUrl&&this._authProvider.lastRedirectUrl!==u;if((r instanceof pR.D_||n)&&"ready"===this.stateValue.kind){const e=this.stateValue,t=this._authProvider?.lastRedirectUrl?.toString()??"";this.stateValue={kind:"requires_authentication",url:t,callback:e=>this.completeRuntimeAuthorization(e)},this.discardToolListError(),this._logStateTransition(e,this.stateValue,n?"scope_step_up":"runtime_unauthorized",{...EP(r,this._redactLogText)}),this._stateEnteredAtMs=Date.now()}throw r}finally{this._toolCallInFlight=void 0,this._currentElicitationProvider=void 0,this._currentToolCallId=void 0,this._currentToolName=void 0}}finally{this._callToolQueueDepth--,c.then(u)}}catch(e){s.error=e,s.hasError=!0}finally{FR(s)}var i}sendToolCall(e,t){const r=this._toolCallRequestOptions?.(e.name),n={...r,signal:void 0===r?.signal?t:AbortSignal.any([r.signal,t])};return!0===this._toolCallOutputSchemaPassthrough?.()?this.client.request({method:"tools/call",params:e},Fx.TF,n):this.client.callTool(e,void 0,n)}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{if(OR(t,(0,D.VI)(e.withName("McpSdkClient.getInstructions")),!1).span.setAttribute("serverName",this.serverName),"requires_authentication"===this.stateValue.kind)return;return this.client.getInstructions()??this._resumedInstructions}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{if(OR(t,(0,D.VI)(e.withName("McpSdkClient.listResources")),!1),"requires_authentication"===this.stateValue.kind||"error"===this.stateValue.kind)return{resources:[]};const r=this.client.getServerCapabilities();return r?.resources?{resources:await hR({fetchPage:e=>this.client.listResources({cursor:e}),itemsOf:e=>e.resources,nextCursorOf:e=>e.nextCursor})}:{resources:[]}}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{return OR(r,(0,D.VI)(e.withName("McpSdkClient.readResource")),!1),"requires_authentication"===this.stateValue.kind?{contents:[]}:{contents:(await this.client.readResource({uri:t.uri})).contents}}catch(e){r.error=e,r.hasError=!0}finally{FR(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{return OR(t,(0,D.VI)(e.withName("McpSdkClient.listPrompts")),!1),"requires_authentication"===this.stateValue.kind||"error"===this.stateValue.kind?[]:(this.client.getServerCapabilities()??{prompts:!1}).prompts?(await hR({fetchPage:e=>this.client.listPrompts({cursor:e}),itemsOf:e=>e.prompts,nextCursorOf:e=>e.nextCursor})).map((e=>({name:e.name,description:e.description,arguments:e.arguments?.map((e=>({name:e.name,description:e.description,required:e.required})))}))):[]}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async getPrompt(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{return OR(n,(0,D.VI)(e.withName("McpSdkClient.getPrompt")),!1),"requires_authentication"===this.stateValue.kind?{messages:[]}:{messages:(await this.client.getPrompt({name:t,arguments:r})).messages.map((e=>({role:e.role,content:Array.isArray(e.content)?e.content.map((e=>"text"===e.type?{type:"text",text:e.text}:"image"===e.type?{type:"image",data:e.data,mimeType:e.mimeType}:{type:"text",text:JSON.stringify(e)})):[{type:"text",text:"string"==typeof e.content?e.content:JSON.stringify(e.content)}]})))}}catch(e){n.error=e,n.hasError=!0}finally{FR(n)}}getCurrentToolCallContext(){if(this._currentToolName)return{toolName:this._currentToolName,toolCallId:this._currentToolCallId}}async getState(e){return"ready"===this.stateValue.kind&&void 0!==this._toolListError?{kind:"ready",toolListError:this._toolListError}:this.stateValue}async completeRuntimeAuthorization(e){if(!this._authCodeExchange)throw new Error(`MCP server "${this.serverName}" cannot complete authorization: no code exchange is configured for this client.`);try{await this._authCodeExchange(e)}catch(e){const t=e instanceof Error?e.message:"Authentication failed";throw new Error(`Authentication callback failed: ${t}`)}this.updateState({kind:"ready"},"runtime_authorization_completed")}updateState(e,t){const r=this.stateValue;this.discardToolListError(),this.stateValue=e,this._logStateTransition(r,e,t??"explicit_update"),this._stateEnteredAtMs=Date.now()}}const YR=(0,h.Pu)("mcp_tool.schema",{description:"One MCP tool definition a tools/list repair touched",labelNames:["outcome"]}),eI=new Set;function tI(e,t,r){if(0!==r)try{YR.increment(e,r,{outcome:t})}catch{}}class rI extends Error{constructor(e,t){super(`MCP server ${e} not found, available servers: ${t.join(", ")}`),this.serverName=e,this.availableServers=t,this.name="McpServerNotFoundError"}}Error,Error;class nI{constructor(e){this.tools=e}async execute(e,t,r,n){const o=this.tools[e];if(!o)throw new kC(e,Object.keys(this.tools));return o.execute(t,r,n)}async executeOn(e,t,r,n,o){const s=this.tools[t];if(!s)throw new kC(t,Object.keys(this.tools));if(s.client===e)return s.execute(r,n,o)}getTools(){return Object.entries(this.tools).map((([e,t])=>({...t.definition,name:e})))}}class oI{async getClients(e){return{}}async getClient(e,t){}async getInstructions(e){return[]}async getToolSet(e){return new nI({})}async getTools(e){return[]}async getToolsForServers(e,t){return[]}}class sI{constructor(e){this.manager=e}async getClients(e){return this.manager.getClients()}async getClient(e,t){return this.manager.getClient(t)}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=OR(t,(0,D.VI)(e.withName("ManagerMcpLease.getInstructions")),!1);return await this.manager.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async getToolSet(e){const t={stack:[],error:void 0,hasError:!1};try{const r=OR(t,(0,D.VI)(e.withName("ManagerMcpLease.getToolSet")),!1);return await this.manager.getToolSet(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=OR(t,(0,D.VI)(e.withName("ManagerMcpLease.getTools")),!1);return(await this.getToolSet(r.ctx)).getTools()}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async getToolsForServers(e,t){const r=new Set(t);return(await this.getTools(e)).filter((e=>r.has(e.clientKey)))}onDidChange(e){return{dispose:this.manager.onDidChange((()=>e(void 0)))}}async reconcileSelection(e,t,r){for(const e of t.removed){const t=this.manager.getClient(e);this.manager.deleteClient(e);try{await(t?.close?.())}catch{}}for(const n of t.added){if(this.manager.getClient(n))continue;const t=await r(e,n);this.manager.setClient(n,t)}}}class iI{constructor(e,t){this.clients=e,this.elicitationFactory=t,this.changeListeners=new Set,this.warnedToolNameCollisions=new Set}onDidChange(e){return this.changeListeners.add(e),()=>{this.changeListeners.delete(e)}}fireDidChange(){for(const e of this.changeListeners)try{e()}catch(e){console.error("Error in McpManager change listener:",e)}}getClients(){return this.clients}getClient(e){return this.clients[e]}setClient(e,t){this.clients[e]=t,this.fireDidChange()}deleteClient(e){delete this.clients[e],this.fireDidChange()}setListingDeadline(e){this.listingDeadlineAt=void 0===e?void 0:performance.now()+e}async closeAllClients(){const e=Object.values(this.clients);await Promise.all(e.map((async e=>{try{await(e.close?.())}catch{}})))}async getToolSet(e){const t={stack:[],error:void 0,hasError:!1};try{const r=OR(t,(0,D.VI)(e.withName("McpManager.getToolSet")),!1),n=OR(t,aI(this.listingDeadlineAt),!1),o=await(0,Nr.PH)(Object.entries(this.clients),(([e,t])=>n.within(t,r.ctx,(()=>t.getTools(r.ctx))).then((r=>(r??[]).map((r=>({...r,clientKey:e,clientName:t.serverName,client:t}))))).catch((()=>[]))),{max:n.concurrency}),s=Array.from(o.values()).flat(),i=new Map;for(const e of s){const t=`${e.clientName}-${e.name}`,r=i.get(t);void 0===r?i.set(t,[e]):r.push(e)}const a={};for(const[e,t]of i){const n=t[0];if(void 0===n)continue;if(t.some((e=>e.clientName!==n.clientName||e.name!==n.name))){if(!this.warnedToolNameCollisions.has(e)){this.warnedToolNameCollisions.add(e);const r=t.map((e=>`${e.clientName}/${e.name}`)).join(", ");console.warn("Colliding MCP tool name; exposing neither:",`${e} (${r})`)}continue}const o=t[t.length-1]?.clientKey,s=t.filter((e=>e.clientKey===o)),i=s[0]??n;s.length>1&&!this.warnedToolNameCollisions.has(e)&&(this.warnedToolNameCollisions.add(e),console.warn("MCP server lists a tool name more than once; using the first:",`${i.clientName}/${i.name}`)),a[e]={definition:{...i,clientKey:i.clientKey,providerIdentifier:i.clientName,toolName:i.name},client:i.client,execute:async(e,t,n)=>{const o=n?.createProvider(i.clientName,i.name,t);return await i.client.callTool(r.ctx,i.name,e,t,o)}}}return new nI(a)}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=OR(t,(0,D.VI)(e.withName("McpManager.getInstructions")),!1),n=OR(t,aI(this.listingDeadlineAt),!1),o=await(0,Nr.PH)(Object.entries(this.clients),(([e,t])=>n.within(t,r.ctx,(()=>t.getInstructions(r.ctx))).then((e=>e&&0!==e.trim().length?new vn.I0({serverName:t.serverName,instructions:e.trim()}):null)).catch((()=>null))),{max:n.concurrency});return Array.from(o.values()).filter((e=>null!==e))}catch(e){t.error=e,t.hasError=!0}finally{FR(t)}}}function aI(e){if(void 0===e)return{concurrency:4,within:(e,t,r)=>r(),[Symbol.dispose]:()=>{}};let t;const r=new Promise((r=>{t=setTimeout((()=>r(void 0)),Math.max(0,e-performance.now()))}));return{concurrency:Number.POSITIVE_INFINITY,within:async(t,n,o)=>{const s=await Promise.race([t.getState(n).catch((()=>{})),r]);if("ready"!==s?.kind)return Promise.race([o(),r]);let i;try{return await Promise.race([o(),new Promise((t=>{i=setTimeout((()=>t(void 0)),Math.max(2e3,e-performance.now()))}))])}finally{clearTimeout(i)}},[Symbol.dispose]:()=>clearTimeout(t)}}function cI(e,t){return function(e){const{logger:t,ctx:r}=e;return{debug:(e,n)=>t.debug(r,e,n),info:(e,n)=>t.info(r,e,n),warn:(e,n)=>t.warn(r,e,n),error:(e,n,o)=>t.error(r,e,n,o)}}({ctx:e,logger:t})}Error;class lI{constructor(e){this.options=e,PP({logger:e.logger,event:"mcp_oauth_provider_initialized",metadata:this.baseMetadata})}get baseMetadata(){return{identifier:this.options.identifier,...this.options.serverUrl?{serverUrl:iP(this.options.serverUrl)}:{}}}async loadTokens(){const e=await this.options.inner.loadTokens();return PP({logger:this.options.logger,event:"mcp_oauth_tokens_loaded",level:"debug",metadata:{...this.baseMetadata,...eR(e)}}),e}async saveTokens(e){await this.options.inner.saveTokens(e),PP({logger:this.options.logger,event:"mcp_oauth_tokens_saved",metadata:{...this.baseMetadata,...eR(e,{expiresInIsFresh:!0})}})}async prepareForRefresh(){PP({logger:this.options.logger,event:"mcp_oauth_refresh_prepare",metadata:this.baseMetadata}),await(this.options.inner.prepareForRefresh?.())}async releaseRefreshLeaseOnError(e){PP({logger:this.options.logger,event:"mcp_oauth_refresh_error_release",level:"warn",error:e,metadata:{...this.baseMetadata,...EP(e,this.options.redactLogText)}}),await(this.options.inner.releaseRefreshLeaseOnError?.(e))}async loadClientInformation(){const e=await this.options.inner.loadClientInformation();return PP({logger:this.options.logger,event:"mcp_oauth_client_info_loaded",level:"debug",metadata:{...this.baseMetadata,...lP(e)}}),e}async saveClientInformation(e){await this.options.inner.saveClientInformation(e),PP({logger:this.options.logger,event:"mcp_oauth_client_info_saved",metadata:{...this.baseMetadata,...lP(e)}})}async invalidateCredentials(e){void 0!==this.options.inner.invalidateCredentials&&(PP({logger:this.options.logger,event:"mcp_oauth_credentials_invalidated",level:"warn",metadata:{...this.baseMetadata,scope:e}}),await this.options.inner.invalidateCredentials(e))}tokenEndpointAuth(e){return this.options.inner.tokenEndpointAuth?.(e)}get loadScopeStepUpRecord(){return this.options.inner.loadScopeStepUpRecord?.bind(this.options.inner)}get saveScopeStepUpRecord(){return this.options.inner.saveScopeStepUpRecord?.bind(this.options.inner)}}class uI{constructor(e,t){this.storage=e,this.identifier=t}async loadTokens(){return this.storage.loadTokens(this.identifier)}async saveTokens(e){return this.storage.saveTokens(this.identifier,e)}async loadClientInformation(){return this.storage.loadClientInformation(this.identifier)}async saveClientInformation(e){return this.storage.saveClientInformation(this.identifier,e)}get loadScopeStepUpRecord(){const{storage:e,identifier:t}=this;return void 0===e.loadScopeStepUpRecord?void 0:()=>e.loadScopeStepUpRecord(t)}get saveScopeStepUpRecord(){const{storage:e,identifier:t}=this;return void 0===e.saveScopeStepUpRecord?void 0:r=>e.saveScopeStepUpRecord(t,r)}}class dI{constructor(e){this.inner=e}async loadTokens(){}async loadClientInformation(){}async saveTokens(e){return this.inner.saveTokens(e)}async saveClientInformation(e){return this.inner.saveClientInformation(e)}async invalidateCredentials(e){await(this.inner.invalidateCredentials?.(e))}get loadScopeStepUpRecord(){return this.inner.loadScopeStepUpRecord?.bind(this.inner)}get saveScopeStepUpRecord(){return this.inner.saveScopeStepUpRecord?.bind(this.inner)}async loadGrantedScope(){return void 0!==this.inner.loadGrantedScope?this.inner.loadGrantedScope():(await this.inner.loadTokens())?.scope}}var hI=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},pI=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const fI=(0,d.h)("DefinitionMcpLoader"),mI=(0,h.Pu)("connector_policy.blocked",{description:"MCP servers a team or org policy refused to load, once per loader and server.",labelNames:["surface","stage","reason"]});function gI(e){const{filePath:t,baseDir:r}=e;return"~"===t||t.startsWith("~/")?s.join(o.homedir(),t.slice(1)):t.startsWith("./")||"."===t?s.resolve(r??process.cwd(),t):t}function wI(e){return"getManagedSlackWorkspaceLists"in e&&"function"==typeof e.getManagedSlackWorkspaceLists}function yI(e){return"getMcpNetworkControlsConfig"in e&&"function"==typeof e.getMcpNetworkControlsConfig}function vI(e){return e?.length??0}function bI(e){if(void 0!==e)return(0,ko.createHash)("sha256").update(ME(e)).digest("hex")}function SI(e){if(void 0===e)return;let t;return r=>(void 0===t&&(t=e(),queueMicrotask((()=>{t=void 0}))),t?tx(r):r)}async function kI(e,t,n,o,s={middlewares:[],configPath:""},i,a,c={},l={}){const u={stack:[],error:void 0,hasError:!1};try{const{middlewares:d,configPath:h}=s,p=hI(u,(0,D.VI)(e.withName("mcp-agent-exec.loadServer")),!1);p.span.setAttribute("serverName",t);const f=!1!==l.mcpAppsUi;p.span.setAttribute("mcpAppsUi",f),fI.info(p.ctx,`Loading MCP server "${t}" ${f?"declaring":"without declaring"} the MCP Apps UI extension`,{event:"mcp_apps_ui_capability",serverName:t,mcpAppsUi:f,transport:"command"in n?"stdio":"http"});let m=async(e,n)=>{const s={stack:[],error:void 0,hasError:!1};try{const u=hI(s,(0,D.VI)(e.withName("loadServer.next")),!1);u.span.setAttribute("serverName",t);const h=u.ctx;if("command"in n){u.span.setAttribute("kind","command");const e=d.find(yI);return await async function(e,t,n,o,s={}){const i=n.cwd?gI({filePath:n.cwd}):void 0;let a,c;if(n.args&&n.args.length>0)a=gI({filePath:n.command,baseDir:i}),c=n.args.map((e=>gI({filePath:e,baseDir:i})));else{const e=(0,rx.A)(n.command);a=gI({filePath:e[0],baseDir:i}),c=e.slice(1).map((e=>gI({filePath:e,baseDir:i})))}const l=n.env??{},{startupTimeoutSec:u}=n,d=await(o?.getMcpNetworkControlsConfig?.({command:[n.command,...n.args??[]].join(" ")})),h=(0,Lb.$H)(d);if(void 0!==h){const{buildMcpSandboxPolicy:n}=await r.e(449).then(r.bind(r,"../mcp-agent-exec/dist/mcp-sandbox-policy.js")),{SandboxUnsupportedError:o,spawnInSandbox:p}=await Promise.resolve().then(r.bind(r,"../shell-exec/dist/api/index.js")),f=i??process.cwd(),m=await n(h,f);fI.info(e,function(e){return`Sandboxing local MCP server "${e.serverName}" with network controls: networkControlsEnabled=${String(!0===e.networkControlsConfig?.enabled)}, mcpNetworkMode=${e.networkControlsConfig?.mcpNetworkMode??"unset"}, mcpNetworkAllowlistCount=${vI(e.networkControlsConfig?.mcpNetworkAllowlist)}, mcpNetworkDenylistCount=${vI(e.networkControlsConfig?.mcpNetworkDenylist)}, localAgentNetworkAllowlistCount=${vI(e.networkControlsConfig?.localAgentNetworkAllowlist)}, sandboxPolicyHash=${bI(e.sandboxNetworkControlsConfig)??"none"}`}({serverName:t,networkControlsConfig:d,sandboxNetworkControlsConfig:h}),function(e){return{event:"mcp_stdio_sandbox_policy",serverName:e.serverName,networkControlsEnabled:!0===e.networkControlsConfig?.enabled,mcpNetworkMode:e.networkControlsConfig?.mcpNetworkMode,mcpNetworkAllowlistCount:vI(e.networkControlsConfig?.mcpNetworkAllowlist),mcpNetworkDenylistCount:vI(e.networkControlsConfig?.mcpNetworkDenylist),localAgentNetworkAllowlistCount:vI(e.networkControlsConfig?.localAgentNetworkAllowlist),sandboxPolicyHash:bI(e.sandboxNetworkControlsConfig)}}({serverName:t,networkControlsConfig:d,sandboxNetworkControlsConfig:h}));try{return await QR.fromCommand(e,t,{command:a,args:c,cwd:i,startupTimeoutSec:u},l,{...s,spawn:(e,t,r)=>p(e,t,r,m)})}catch(e){if(e instanceof o)throw new DE(t,e);throw e}}return!0===d?.enabled&&"no_sandbox"===d.mcpNetworkMode&&(!0===d.win32UserExtensionUnsandbox?fI.info(e,`Starting local MCP server "${t}" without MCP sandboxing`,{event:"mcp_stdio_win32_user_extension_unsandbox",serverName:t}):fI.info(e,`Starting local MCP server "${t}" without MCP sandboxing`)),QR.fromCommand(e,t,{command:a,args:c,cwd:i,startupTimeoutSec:u},l,s)}(h,t,n,e,l)}if("url"in n){u.span.setAttribute("kind","url");const e=i?.(t);return await async function(e,t,r,n,o,s,i,a,c={}){const l=cI(e,fI),u=function(e,t,r){return{logger:{debug:(t,r)=>fI.debug(e,t,r),info:(t,r)=>fI.info(e,t,r),warn:(t,r)=>fI.warn(e,t,r),error:(t,r,n)=>fI.error(e,t,r,n)},metadata:{identifier:t,source:"mcp-agent-exec"},redactLogText:SI(r)}}(e,t,a),d=void 0!==s&&LE(r.url)?jE(globalThis.fetch.bind(globalThis),{managedSlackWorkspaceLists:()=>s.getManagedSlackWorkspaceLists()}):void 0;return QR.fromStreamableHttp(t,r,n,r.headers,o,d,u,l,void 0,void 0,i,!1,c)}(h,t,n,o,e,d.find(wI),a,c.isLinkSharedPaymentTokenLogRedactionEnabled,l)}throw new Error(`Invalid server: ${JSON.stringify(n)}`)}catch(e){s.error=e,s.hasError=!0}finally{pI(s)}};for(const e of d){const r=m;m=async(n,o)=>await e.load(n,t,o,h,r)}try{return await m(p.ctx,n)}catch(e){throw function(e,t){if(void 0===t)return e;!function(e,t){if("object"!=typeof e||null===e)return;const r=DR.get(e);void 0!==r&&DR.set(e,t(r))}(e,t);const r=function(e,t){if(void 0===t)return e;const r={results:new Map,cycled:new Set},n=UE(e,t,r),o=new Map([...r.cycled].flatMap((e=>{const t=r.results.get(e);return t===e?[]:[[e,t]]})));return o.size>0&&function(e,t){const r=new Set,n=[e];for(let e=0;n.length>0&&e({identifier:e,serverConfig:t,configPath:this.configPath})))}}class CI{constructor(e,t,r=[],n={}){this.source=e,this.tokenStorage=t,this.middlewares=r,this.options=n,this.clientCache=new Map}async load(e,t=!0){const r={stack:[],error:void 0,hasError:!1};try{hI(r,(0,D.VI)(e.withName("DefinitionMcpLoader.load")),!1),t||(await this.closeAllCachedClients(),this.source.clearCache?.());const n=await this.source.getDefinitions(e,t);await this.evictClientsOnSandboxPolicyChange(e,n);const o={};return await(0,Nr.PH)([...n],(async r=>{try{const n=t?this.clientCache.get(r.identifier):void 0,s=n??await this.loadDefinitionClient(e,r);n||this.clientCache.set(r.identifier,s),o[r.identifier]=s}catch(t){if(this.handleDefinitionLoadError(e,r,t))return;!function(e,t,r,n){const o=SI(n)??(e=>e),s=function(e){if("object"==typeof e&&null!==e)return DR.get(e)}(r);fI.warn(e,"Failed to load MCP server",{identifier:t.identifier,source:t.source,configPath:t.configPath,metadata:t.metadata,errorMessage:o(r instanceof Error?r.message:String(r)),stderrTail:void 0===s?void 0:o(s)})}(e,r,t,this.options.isLinkSharedPaymentTokenLogRedactionEnabled)}}),{max:this.options.maxConcurrency??Math.max(n.length,1)}),new iI(o,this.options.elicitationFactory)}catch(e){r.error=e,r.hasError=!0}finally{pI(r)}}clearClient(e){this.clientCache.delete(e)}clearAllMcpCaches(){this.clientCache.clear()}async evictClientsOnSandboxPolicyChange(e,t){const r=this.middlewares.find(yI);if(!r)return;let n;try{n=JSON.stringify(await Promise.all([...t].sort(((e,t)=>e.identifier.localeCompare(t.identifier))).map((async e=>{const t=await(r.getMcpNetworkControlsConfig?.((n=e.serverConfig,"url"in n?{url:n.url}:{command:[n.command,...n.args??[]].join(" ")})))??{};var n;return[e.identifier,ME(t)]}))))}catch{return}const o=this.sandboxPolicyFingerprint;this.sandboxPolicyFingerprint=n,void 0!==o&&o!==n&&(fI.info(e,"MCP network-controls policy changed; reloading MCP clients to apply the new egress policy"),await this.closeAllCachedClients())}async closeAllCachedClients(){const e=[...this.clientCache.values()];this.clientCache.clear(),await(0,Nr.PH)(e,(async e=>{try{await(e.close?.())}catch{}}),{max:Math.max(e.length,1)})}async loadClient(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{hI(n,(0,D.VI)(e.withName("DefinitionMcpLoader.loadClient")),!1);const o=await this.source.getDefinitions(e);if(await this.evictClientsOnSandboxPolicyChange(e,o),!r){const e=this.clientCache.get(t);if(e)return e}const s=o.find((e=>e.identifier===t));if(!s)throw new Error(`MCP server "${t}" not found in config`);let i;try{i=await this.loadDefinitionClient(e,s,r)}catch(t){throw this.handleDefinitionLoadError(e,s,t),t}return r||this.clientCache.set(t,i),i}catch(e){n.error=e,n.hasError=!0}finally{pI(n)}}async loadDefinitionClient(e,t,r){const n=t.authStorageKey??t.identifier,o=new uI(this.tokenStorage,n),s=cI(e,fI),i=new lI({inner:o,logger:s,redactLogText:SI(this.options.isLinkSharedPaymentTokenLogRedactionEnabled),identifier:n,serverUrl:"url"in t.serverConfig?t.serverConfig.url:void 0}),a=r?new dI(i):i;return kI(e,t.identifier,t.serverConfig,a,{middlewares:this.middlewares,configPath:t.configPath??""},this.options.authRedirectUrlGenerator,this.options.scopeChallengeStepUp,{isLinkSharedPaymentTokenLogRedactionEnabled:this.options.isLinkSharedPaymentTokenLogRedactionEnabled})}handleDefinitionLoadError(e,t,r){let n=!1;try{n="handled"===this.options.onDefinitionLoadError?.(e,t,r)}catch(r){fI.warn(e,"MCP definition load error hook failed",{identifier:t.identifier,source:t.source,configPath:t.configPath,metadata:t.metadata,errorMessage:r instanceof Error?r.message:String(r)})}return n||function(e){return e instanceof AC||e instanceof $C||e instanceof MC||e instanceof EI}(r)}}class EI extends Error{constructor(e,t,r){super(r??("teamNetworkAllowlist"===t?`MCP server "${e}" is not on the team network allowlist`:`MCP server "${e}" is blocked by team policy`)),this.serverName=e,this.reason=t,this.name="McpServerBlockedError"}}const xI=[1e3,3e3];class PI{constructor(e){this.blockingService=e,this.countedPolicyBlocks=new Set}async getMcpNetworkControlsConfig(e){return await(this.blockingService.getMcpNetworkControlsConfig?.(e))??{}}async getManagedSlackWorkspaceLists(){return await(this.blockingService.getManagedSlackWorkspaceLists?.())??[]}async load(e,t,r,n,o){const s=function(e){return{command:"command"in e?[e.command,...e.args??[]].join(" "):void 0,url:"url"in e?e.url:void 0}}(r),i=await(this.blockingService.getMcpServerBlockInfo?.(s))??{blocked:await this.blockingService.isServerBlocked(s)};if(i.blocked){const r=i.reason??"teamPolicy";throw"teamPolicy"!==r||this.countedPolicyBlocks.has(t)||(this.countedPolicyBlocks.add(t),mI.increment(e,1,{surface:"desktop",stage:"tool_call",reason:"server_not_allowed"})),new EI(t,r,i.message)}for(let n=0;;n++)try{const t=await o(e,r);return!0===i.hostMcpBridge&&this.blockingService.recordHostMcpBridgeClient?.(t),this.blockingService.recordMcpServerClient?.(t,s),t}catch(e){if(e instanceof FE)throw new EI(t,"teamPolicy",e.message);const r=e instanceof NE?xI[n]:void 0;if(void 0===r)throw e;await(0,Nr.cb)(r)}}}class RI extends CI{constructor(e,t,r=[],n={}){super(new _I(e),t,r,n),this.configPath=e}static init(e,t,r=[]){return new RI(t,e,r)}}function II(e){return"stdio"===e.type&&e.command?{command:e.command,args:e.args??[],env:e.env,cwd:e.cwd}:"streamableHttp"===e.type&&e.url?{url:e.url,headers:e.headers,auth:e.auth,...void 0!==e.tls?{tls:e.tls}:{},...void 0!==e.placement?{placement:e.placement}:{}}:void 0}var TI=r("../utils/dist/private-file.js"),AI=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js");function $I(e){const t=AI.VE.safeParse(e);return t.success?t.data:void 0}function MI(e){const t=AI.H5.safeParse(e);return t.success?t.data:void 0}class DI{constructor(e){this.mcpAuthPath=e;const t=DI.mcpAuthPromises.get(e);if(t)this.mcpAuthPromise=t;else{const t=this.loadMcpAuth();this.mcpAuthPromise=t,DI.mcpAuthPromises.set(e,t),t.catch((()=>{DI.mcpAuthPromises.get(e)===t&&DI.mcpAuthPromises.delete(e)}))}DI.saveLocks.has(e)||DI.saveLocks.set(e,Promise.resolve())}async loadMcpAuth(){try{await(0,TI.rV)(this.mcpAuthPath);const e=await(0,xo.readFile)(this.mcpAuthPath,"utf8"),t=JSON.parse(e);if(t&&"object"==typeof t){if(Object.values(t).some((e=>e&&"object"==typeof e&&null!==e&&("access_token"in e||"refresh_token"in e)&&!("tokens"in e)&&!("clientInfo"in e)))){const e={};for(const[r,n]of Object.entries(t)){const t=$I(n);void 0!==t&&(e[r]={tokens:t})}return e}const e={};for(const[r,n]of Object.entries(t))n&&"object"==typeof n&&null!==n&&(e[r]={tokens:"tokens"in n?$I(n.tokens):void 0,clientInfo:"clientInfo"in n?MI(n.clientInfo):void 0,..."scopeStepUp"in n?{scopeStepUp:n.scopeStepUp}:{}});return e}return{}}catch(e){if(e instanceof Error&&e.message.includes("ENOENT"))return{};throw e}}async loadTokens(e){const t=await this.mcpAuthPromise;return t[e]?.tokens}async saveTokens(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),r[e].tokens=t,await this.saveMcpAuth(r)}))}async loadClientInformation(e){const t=await this.mcpAuthPromise;return t[e]?.clientInfo}async withSaveLock(e){const t=DI.saveLocks.get(this.mcpAuthPath)??Promise.resolve();let r;DI.saveLocks.set(this.mcpAuthPath,new Promise((e=>{r=e})));try{return await t,await e()}finally{r()}}async saveClientInformation(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),r[e].clientInfo=t,await this.saveMcpAuth(r)}))}async loadScopeStepUpRecord(e){const t=await this.mcpAuthPromise;return t[e]?.scopeStepUp}async saveScopeStepUpRecord(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),void 0===t?delete r[e].scopeStepUp:r[e].scopeStepUp=t,await this.saveMcpAuth(r)}))}async deleteCredentials(e){await this.withSaveLock((async()=>{const t=await this.mcpAuthPromise;e in t&&(delete t[e],await this.saveMcpAuth(t))}))}async saveMcpAuth(e){await(0,TI.Pl)(this.mcpAuthPath,JSON.stringify(e,null,2))}}DI.mcpAuthPromises=new Map,DI.saveLocks=new Map,(0,b.cF)(Symbol("execHookConversationId"),void 0),(0,b.cF)(Symbol("execHookGenerationId"),void 0),(0,b.cF)(Symbol("execHookModel"),void 0);const OI=(0,b.cF)(Symbol("execHookWorkspaceRoots"),void 0);var FI=r("../proto/dist/generated/agent/v1/write_exec_pb.js"),NI=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},LI=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const jI=(0,h.Pu)("mcp.filesystem.divergence",{description:"Divergence detected between MCP lease state and filesystem state",labelNames:["divergence_type","mcp_source","configured_servers","mcp_version"]}),UI=(0,h.Pu)("mcp.filesystem.sync_check",{description:"MCP filesystem sync check executed",labelNames:["synced","mcp_source","configured_servers","mcp_version"]}),BI=(0,h.wt)("mcp.filesystem.sync_check.expected_servers",{description:"Number of expected MCP servers at last sync check",labelNames:["mcp_source","mcp_version"]}),WI=(0,h.wt)("mcp.filesystem.sync_check.actual_servers",{description:"Number of actual MCP servers on disk at last sync check",labelNames:["mcp_source","mcp_version"]}),HI=(0,h.wt)("mcp.filesystem.sync_check.servers_missing",{description:"Number of expected MCP servers missing from disk at last sync check",labelNames:["mcp_source","mcp_version"]}),qI=(0,h.wt)("mcp.filesystem.sync_check.tool_mismatches",{description:"Number of MCP servers with tool count mismatches at last sync check",labelNames:["mcp_source","mcp_version"]}),zI=(0,d.h)("McpFileSystemWriter"),GI="mcpFsStructuredLogOptIn";function VI(e,t){return t?.includeStructuredLogs?{...e??{},[GI]:!0}:e}const KI={debug(e,t,r,n){zI.debug(e,t,VI(r,n))},info(e,t,r,n){zI.info(e,t,VI(r,n))},warn(e,t,r,n){zI.warn(e,t,VI(r,n))},error(e,t,r,n,o){zI.error(e,t,r,VI(n,o))}},JI="mcps",ZI="tools",XI="~staging",QI="~prev",YI=[25,50,100,200],eT=new Set(["EPERM","EBUSY","EACCES"]),tT=new Map;function rT(e){return e.slice(0,e.indexOf("~"))}function nT(e,t){return`${e}~${Date.now()}-${process.pid}-${(0,ko.randomBytes)(4).toString("hex")}${t}`}const oT=/~(\d+)-\d+-[0-9a-f]+~(?:staging|prev)$/;async function sT(e,t){const r=oT.exec(t),n=r?Number(r[1]):0;try{const{mtimeMs:r}=await(0,xo.stat)((0,s.join)(e,t));return Date.now()-Math.max(n,r)>6e4}catch{return!1}}const iT="mcp_auth",aT="Authenticate this MCP server so its tools can be used. Call this tool through your MCP tool-calling interface when STATUS.md indicates this server needs authentication.",cT="# >>> CURSOR MANAGED BLOCK >>>",lT="# <<< CURSOR MANAGED BLOCK <<<",uT=["# Ignore everything in .cursor","*","# Un-ignore projects so we can descend to allowlisted subdirs","!projects/","projects/*","!projects/*/","projects/*/*","# MCP tool descriptors, resources, prompts","!projects/*/mcps/","!projects/*/mcps/**","# Agent transcripts for citation","!projects/*/agent-transcripts/","!projects/*/agent-transcripts/**","# Terminal output files","!projects/*/terminals/","!projects/*/terminals/**","# Conversation notes (shared scratchpad)","!projects/*/agent-notes/","!projects/*/agent-notes/**","# Large tool output files","!projects/*/agent-tools/","!projects/*/agent-tools/**","# Plugin cache (rules, skills, agents)","!plugins/","!plugins/**","# Built-in Cursor skills","!skills-cursor/","!skills-cursor/**","# User's personal skills","!skills/","!skills/**","# User's personal slash commands","!commands/","!commands/**","# User's plan files","!plans/","!plans/**","# Subagent state/transcripts","!subagents/","!subagents/**","# User-level cursor rules","!rules/","!rules/**"].join("\n");function dT(e,t,r=15e3){let n;return Promise.race([e.catch((()=>t)),new Promise((e=>{n=setTimeout((()=>e(t)),r)}))]).finally((()=>clearTimeout(n)))}function hT(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function pT(e){if(void 0===e)return;const t=e.trim();return t.length>0?t:void 0}function fT(e){switch(e.kind){case"loading":return"initializing";case"requires_authentication":return"needsAuth";case"ready":return"connected";case"error":return"error";default:return"disconnected"}}function mT(e){if(Array.isArray(e))return e.map((e=>mT(e)));if(function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e)){const t=Object.entries(e).filter((([,e])=>void 0!==e)).sort((([e],[t])=>et?1:0)).map((([e,t])=>[e,mT(t)]));return Object.fromEntries(t)}return e}function gT(e){return JSON.stringify(mT(e))}function wT(e){const t=e.map((e=>({value:e,key:gT(e)})));return t.sort(((e,t)=>e.keyt.key?1:0)),t.map((e=>e.value))}function yT(e){const t=wT(e.tools.map((e=>({name:e.toolName,description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema})))),r=wT(e.resources.map((e=>({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType})))),n=wT(e.prompts.map((e=>({name:e.name,description:e.description,arguments:e.arguments}))));return gT({id:e.serverIdentifier,name:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,tools:t,resources:r,prompts:n,instructions:e.instructions,status:e.status})}class vT{constructor(e,t,r){this.cachedFingerprints=new Map,this.disposed=!1,this.hasPendingLeaseChangeEvent=!1,this.lastDivergenceCheckMs=0,this.mcpLease=e,this.projectDir=t,this.debounceMs=r?.debounceMs??100,this.mcpAuthCopyOverrides=r?.mcpAuthCopyOverrides,this.exposeVirtualMcpAuthTool=r?.exposeVirtualMcpAuthTool??!0,this.alwaysExposeVirtualMcpAuthTool=r?.alwaysExposeVirtualMcpAuthTool??!1,this.snapshotProvider=r?.snapshotProvider,this.mcpVersion=r?.mcpVersion??(this.snapshotProvider?"snapshots":"v1"),this.onDidWrite=r?.onDidWrite,this.ctx=this.getContext(r?.loggerBackend),this.startupCleanupPromise=this.cleanupStaleStagingDirs(this.ctx),this.leaseChangeDisposable=this.mcpLease.onDidChange((e=>{KI.info(this.ctx,"Lease change event received",{serverIdentifiers:e?.serverIdentifiers,reason:e?.reason}),this.onLeaseChanged(this.ctx,e)})),KI.info(this.ctx,"Constructor: scheduling initial write"),this.scheduleWrite(this.ctx),this.ensureCursorDirGitignore()}ensureCursorDirGitignore(){(async function(e){const t=(0,s.join)(e,".gitignore"),r=`${cT}\n${uT}\n${lT}\n`;let n;await(0,xo.mkdir)(e,{recursive:!0});try{n=await(0,xo.readFile)(t,"utf-8")}catch(e){if("ENOENT"!==_c(e))throw e}if(void 0===n)return void await(0,xo.writeFile)(t,r);const o=n.indexOf(cT),i=n.indexOf(lT,o+30);if(-1===o||-1===i)await(0,xo.writeFile)(t,r);else{const e=`${n.slice(0,o)}${r}${n.slice(i+30).replace(/^\n/,"")}`;e!==n&&await(0,xo.writeFile)(t,e)}})((0,s.join)((0,o.homedir)(),".cursor")).catch((e=>{KI.warn(this.ctx,"Failed to ensure ~/.cursor/.gitignore",e)}))}async cleanupStaleStagingDirs(e){const t=this.getLogContext(e),r=(0,s.join)(this.projectDir,JI);try{const e=await(0,xo.readdir)(r);await Promise.allSettled(e.filter((e=>e.endsWith(XI))).map((async e=>{await sT(r,e)&&await(0,xo.rm)((0,s.join)(r,e),{recursive:!0,force:!0})})))}catch(e){"ENOENT"!==_c(e)&&KI.error(t,"Error clearing stale mcps staging dirs",e)}}onLeaseChanged(e,t){if(this.disposed)return;const r=t??{serverIdentifiers:void 0};this.hasPendingLeaseChangeEvent?this.pendingLeaseChangeEvent=function(...e){const[t,r]=e;return e.length<2?t:eo(r)?{serverIdentifiers:void 0,reason:t?.reason??r?.reason}:void 0===t?r:eo(t)?{serverIdentifiers:void 0,reason:t.reason??r?.reason}:{serverIdentifiers:[...new Set([...t.serverIdentifiers??[],...r?.serverIdentifiers??[]])],reason:t.reason??r?.reason}}(this.pendingLeaseChangeEvent??{serverIdentifiers:void 0},r):(this.pendingLeaseChangeEvent=r,this.hasPendingLeaseChangeEvent=!0),void 0!==this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout((()=>{this.debounceTimer=void 0;const t=this.takePendingLeaseChangeEvent();this.scheduleWrite(e,t)}),this.debounceMs)}takePendingLeaseChangeEvent(){if(!this.hasPendingLeaseChangeEvent)return;const e=this.pendingLeaseChangeEvent??{serverIdentifiers:void 0};return this.pendingLeaseChangeEvent=void 0,this.hasPendingLeaseChangeEvent=!1,e}scheduleWrite(e,t){const r=this.getLogContext(e);if(this.disposed)return;const n=this.writePromise;this.writePromise=(async()=>{if(n)try{await n}catch(e){KI.error(r,"Error waiting for previous write",e)}this.disposed||(await this.startupCleanupPromise,this.disposed||await this.fetchAndWrite(e,t))})()}getContext(e){let t=(0,b.q6)();return e&&(t=t.with(d._O,e)),t}getLogContext(e){return e.with(d._O,this.ctx.get(d._O))}getMetricTags(e){return{...e,mcp_version:this.mcpVersion}}getMcpAuthToolDescription(){return pT(this.mcpAuthCopyOverrides?.authToolDescription)??aT}shouldExposeVirtualMcpAuthToolForStatus(e,t){return this.exposeVirtualMcpAuthTool&&Jn(e)&&(this.alwaysExposeVirtualMcpAuthTool||"needsAuth"===t)}getErrorStatusMessage(){return pT(this.mcpAuthCopyOverrides?.errorStatusMessage)??"The MCP server errored. If this server is important for completing the task, concisely inform the user and ask them to check the MCP status in Cursor's Customize page > MCPs; otherwise continue with a different approach."}getNeedsAuthStatusMessage(e){return t=pT(this.mcpAuthCopyOverrides?.needsAuthStatusMessageWithAuthTool)??'The MCP server needs authentication. Authenticate it by calling the `{authToolName}` tool for server "{serverIdentifier}" through your MCP tool-calling interface using an empty arguments object. If this server is important for completing the task, authenticate it first; otherwise continue with a different approach.',r={serverIdentifier:e,authToolName:iT},t.replace(/\{serverIdentifier\}/g,r.serverIdentifier).replace(/\{authToolName\}/g,r.authToolName);var t,r}getNeedsAuthStatusMessageForWrite(e){return this.exposeVirtualMcpAuthTool&&Jn(e)?this.getNeedsAuthStatusMessage(e):pT(this.mcpAuthCopyOverrides?.needsAuthStatusMessageWithoutVirtualTool)??"This MCP server requires authentication before its tools can be used. Open Cursor's Customize page > MCPs, select this server, and use Authenticate/Reopen, or refresh credentials in your MCP configuration (for example mcp.json), then restart this environment. If this server is not required for the task, continue without it."}async getToolsForServers(e,t){if(0===t.length)return[];const r=this.getLogContext(e);try{return await this.mcpLease.getToolsForServers(e,t)}catch(n){KI.warn(r,`getToolsForServers() threw, falling back to filtered getTools(): ${Cc(n)}`);const o=await this.mcpLease.getTools(e).catch((e=>(KI.warn(r,`getTools() threw during scoped-tool fallback, defaulting to []: ${e}`),[]))),s=new Set(t);return o.filter((e=>s.has(e.clientKey)))}}async fetchClientDataForServer(e,t,r,n){const o=await dT(r.getState(e),{kind:"error"}).then((r=>("error"!==r.kind||"message"in r||KI.warn(e,`getState() timed out for "${t}", defaulting to error`),r))),s="ready"===o.kind||"requires_authentication"===o.kind,[i,a,c]=await Promise.all([s?dT(r.listResources(e),{resources:[]}):Promise.resolve({resources:[]}),s?dT(r.listPrompts(e),[]):Promise.resolve([]),s&&n?.fetchInstructions?dT(r.getInstructions(e),void 0):Promise.resolve(void 0)]);return{clientKey:t,serverName:r.serverName,plugin:r.plugin,marketplace:r.marketplace,pluginId:r.pluginId,marketplaceId:r.marketplaceId,resources:i.resources.map((e=>({...e,serverIdentifier:t,serverName:r.serverName}))),prompts:a.map((e=>({...e,serverIdentifier:t,serverName:r.serverName}))),instructions:c,status:fT(o)}}buildServerDataMap(e,t,r){const n=new Map;for(const e of t){const t=Fy(e.clientKey);n.set(e.clientKey,{serverIdentifier:e.clientKey,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,sanitizedId:t,folderPath:(0,s.join)(this.projectDir,JI,t),tools:[],resources:e.resources,prompts:e.prompts,instructions:e.instructions,status:e.status})}for(const t of e){let e=n.get(t.clientKey);if(!e){const r=Fy(t.clientKey);e={serverIdentifier:t.clientKey,serverName:t.providerIdentifier,plugin:t.plugin,marketplace:t.marketplace,pluginId:t.pluginId,marketplaceId:t.marketplaceId,sanitizedId:r,folderPath:(0,s.join)(this.projectDir,JI,r),tools:[],resources:[],prompts:[],instructions:void 0,status:void 0},n.set(t.clientKey,e)}e.tools.push(t)}if(void 0!==r)for(const e of r){const t=e.serverIdentifier?.trim();let r=t?Array.from(n.values()).find((e=>e.serverIdentifier===t)):void 0;if(!r){const t=e.serverName?.trim();r=t?Array.from(n.values()).find((e=>e.serverName===t)):void 0}r&&e.instructions&&(r.instructions=e.instructions)}if(this.exposeVirtualMcpAuthTool)for(const e of n.values())this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&(e.tools.some((e=>e.toolName===iT))||e.tools.push({clientKey:(o={serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,authToolDescription:this.getMcpAuthToolDescription()}).serverIdentifier,providerIdentifier:o.serverName,plugin:o.plugin,marketplace:o.marketplace,pluginId:o.pluginId,marketplaceId:o.marketplaceId,toolName:iT,name:iT,description:o.authToolDescription,inputSchema:{type:"object",properties:{},additionalProperties:!1}}));var o;return n}buildServersToWrite(e,t){const r=[],n=new Set;for(const o of t.values()){const t=o.tools.length>0||o.resources.length>0||o.prompts.length>0||o.instructions,s="error"===o.status||"needsAuth"===o.status||"initializing"===o.status;t||s?n.has(o.sanitizedId)?KI.warn(e,`Skipping server "${o.serverIdentifier}" — sanitizedId "${o.sanitizedId}" collides with another server`):(n.add(o.sanitizedId),r.push(o)):KI.info(e,`Server "${o.serverIdentifier}" excluded from write: tools=${o.tools.length}, resources=${o.resources.length}, prompts=${o.prompts.length}, hasInstructions=${!!o.instructions}, status=${o.status}`)}return r}mergeScopedRefreshWithCachedServerData(e,t){const r=[...t.tools];if(this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&!r.some((e=>e.toolName===iT))){const t=e.tools.find((e=>e.toolName===iT));void 0!==t&&r.push(t)}return{...e,...t,tools:r,resources:e.resources,prompts:e.prompts,instructions:e.instructions,status:e.status,plugin:t.plugin??e.plugin,marketplace:t.marketplace??e.marketplace,pluginId:t.pluginId??e.pluginId,marketplaceId:t.marketplaceId??e.marketplaceId}}async refreshServersFromLease(e,t){const r=this.getLogContext(e),n=[...new Set(t.serverIdentifiers??[])];KI.info(r,`fetchAndWrite: refreshing ${n.length} targeted servers`,{serverIdentifiers:n});const o=await this.getToolsForServers(e,n),s=await this.mcpLease.getInstructions(e).catch((e=>(KI.warn(r,`getInstructions() threw during scoped refresh, defaulting to []: ${e}`),[]))),i=await Promise.all(n.map((async t=>{try{const r=await this.mcpLease.getClient(e,t);return void 0===r?{serverIdentifier:t,kind:"missing"}:{serverIdentifier:t,kind:"client",client:r}}catch(e){return KI.warn(r,`getClient("${t}") threw during scoped refresh, preserving cached data: ${Cc(e)}`),{serverIdentifier:t,kind:"error",error:e}}}))),a=i.filter((e=>"missing"===e.kind)).map((e=>e.serverIdentifier));let c=new Set;if(a.length>0){const t=await this.mcpLease.getClients(e).catch((e=>{KI.warn(r,`getClients() threw while confirming targeted server removal, preserving cached data: ${e}`)}));void 0!==t&&(c=new Set(a.filter((e=>void 0===t[e]))))}const l=await Promise.all(i.filter((e=>"client"===e.kind)).map((({serverIdentifier:t,client:r})=>this.fetchClientDataForServer(e,t,r,{fetchInstructions:!0})))),u=new Map((this.cachedServerData??[]).map((e=>[e.serverIdentifier,e]))),d=this.buildServerDataMap(o,l,s),h=new Set(n),p=new Set(i.filter((e=>"error"===e.kind||"missing"===e.kind&&!c.has(e.serverIdentifier))).map((e=>e.serverIdentifier)));for(const e of n){const t=u.get(e),n=d.get(e);if(void 0===n)c.has(e)?u.delete(e):KI.warn(r,`refreshServersFromLease: preserving cached data for "${e}" because targeted refresh returned no replacement`);else{if(p.has(e)&&void 0!==t){u.set(e,this.mergeScopedRefreshWithCachedServerData(t,n)),KI.warn(r,`refreshServersFromLease: preserving cached metadata for "${e}" because the client was unavailable during targeted refresh`);continue}u.set(e,n)}}const f=new Map(Array.from(u.values()).map((e=>[e.sanitizedId,e.serverIdentifier])));for(const[e,t]of this.cachedFingerprints)if(!h.has(e)&&!u.has(e)){const t=Fy(e);f.set(t,e)}const m=this.buildServersToWrite(e,u);await this.writeServerData(e,m,f),this.cachedServerData=m,this.fireOnDidWrite(m)}async fetchAndWrite(e,t){const r={stack:[],error:void 0,hasError:!1};try{NI(r,(0,D.VI)(e.withName("McpFileSystemWriter.fetchAndWrite")),!1);const n=this.getLogContext(e);try{if(void 0!==this.cachedServerData&&void 0!==t&&!eo(t)&&[...new Set(t.serverIdentifiers??[])].length>0)return void await this.refreshServersFromLease(e,t);const[r,o,s]=await Promise.all([this.mcpLease.getTools(e).catch((e=>(KI.warn(n,`getTools() threw, defaulting to []: ${e}`),[]))),this.mcpLease.getInstructions(e).catch((()=>[])),this.mcpLease.getClients(e).catch((e=>(KI.warn(n,`getClients() threw, defaulting to {}: ${e}`),{})))]),i=Object.keys(s);KI.info(n,`fetchAndWrite: lease returned ${r.length} tools across ${i.length} clients`);const a=Object.entries(s).map((([t,r])=>this.fetchClientDataForServer(e,t,r))),c=await Promise.all(a),l=this.buildServerDataMap(r,c,o),u=this.buildServersToWrite(e,l),d=new Map(Array.from(l.values()).map((e=>[e.sanitizedId,e.serverIdentifier])));await this.writeServerData(e,u,d),this.cachedServerData=u,this.fireOnDidWrite(u)}catch(e){KI.error(n,"Error fetching/writing MCP state",e)}}catch(e){r.error=e,r.hasError=!0}finally{LI(r)}}fireOnDidWrite(e){if(this.onDidWrite)try{const t=e.map((e=>({serverIdentifier:e.serverIdentifier,folderPath:e.folderPath,tools:e.tools.map((t=>({toolName:t.toolName,definitionPath:(0,s.join)(e.folderPath,ZI,`${hT(t.toolName)}.json`)})))})));this.onDidWrite(t)}catch{}}async writeServerData(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{NI(n,(0,D.VI)(e.withName("McpFileSystemWriter.writeServerData")),!1);const o=this.getLogContext(e),i=(0,s.join)(this.projectDir,JI);await(0,xo.mkdir)(i,{recursive:!0});const a=new Map;for(const e of t)try{a.set(e.serverIdentifier,yT(e))}catch(t){KI.error(o,"Error computing server fingerprint, will force write",t,{serverIdentifier:e.serverIdentifier}),a.set(e.serverIdentifier,`__error_${Date.now()}_${Math.random()}`)}const c=[];for(const e of t){const t=this.cachedFingerprints.get(e.serverIdentifier);t!==a.get(e.serverIdentifier)&&(c.push(e),void 0!==t&&KI.info(o,`Server "${e.serverIdentifier}" fingerprint changed: tools=${e.tools.length}, status=${e.status}`))}for(const e of t)if(!c.includes(e))try{await(0,xo.stat)((0,s.join)(i,e.sanitizedId))}catch{KI.info(o,`Server "${e.serverIdentifier}" directory missing on disk, forcing write`),c.push(e)}const l=new Set;for(const[e]of this.cachedFingerprints)if(!a.has(e)){const t=this.cachedServerData?.find((t=>t.serverIdentifier===e)),n=t?.sanitizedId??Fy(e);r.has(n)?(KI.info(o,`Server "${e}" (sanitized="${n}") still in lease but excluded from write, preserving directory`),a.set(e,this.cachedFingerprints.get(e))):(KI.info(o,`Server "${e}" (sanitized="${n}") left the lease, scheduling directory removal`),l.add(n))}const u=void 0===this.cachedServerData;if(u)try{const e=await(0,xo.readdir)(i),t=new Set(e.filter((e=>!e.endsWith(XI)&&!e.endsWith(QI))));for(const r of e){const e=r.endsWith(XI),n=r.endsWith(QI);if((e||n)&&await sT(i,r))if(e)await(0,xo.rm)((0,s.join)(i,r),{recursive:!0,force:!0});else{const e=rT(r);if(t.has(e))await(0,xo.rm)((0,s.join)(i,r),{recursive:!0,force:!0});else try{await(0,xo.rename)((0,s.join)(i,r),(0,s.join)(i,e)),t.add(e)}catch{await(0,xo.rm)((0,s.join)(i,r),{recursive:!0,force:!0}).catch((()=>{}))}}}for(const e of t)if(r.has(e)){const t=r.get(e);a.has(t)||a.set(t,`__preserved_${e}`)}else l.add(e)}catch(e){KI.error(o,"Error clearing mcps directory",e)}const d=Array.from(l);if(c.length>0||l.size>0){const e=c.map((e=>({serverIdentifier:e.serverIdentifier,sanitizedId:e.sanitizedId,toolCount:e.tools.length})));KI.info(o,`Incremental write: ${c.length} changed, ${l.size} removed, ${t.length-c.length} unchanged`,{changedServerCount:c.length,changedServers:e,removedServerCount:l.size,removedServerSanitizedIds:d,unchangedServerCount:t.length-c.length,totalServerCount:t.length,leaseServerCount:r.size,coldStartReconcile:u,projectDirHash:(0,ko.createHash)("sha256").update(this.projectDir).digest("hex")},{includeStructuredLogs:!0})}const h=await Promise.allSettled(c.map((t=>this.writeServerAtomic(e,t,i))));for(let t=0;t(0,xo.rm)((0,s.join)(i,e),{recursive:!0,force:!0}))));for(let r=0;r{await(i?.catch((()=>{}))),await this.swapServerDirectory(e,t,r)})();tT.set(o,a);try{await a}finally{tT.get(o)===a&&tT.delete(o)}}catch(e){n.error=e,n.hasError=!0}finally{LI(n)}}async swapServerDirectory(e,t,r){const n=nT(t.sanitizedId,XI),o=(0,s.join)(r,n),i=(0,s.join)(r,t.sanitizedId);try{await this.writeServerDirectory(e,t,{basePath:r,dirName:n})}catch(e){throw await(0,xo.rm)(o,{recursive:!0,force:!0}).catch((()=>{})),e}const a=(0,s.join)(r,nT(t.sanitizedId,QI));let c=!1;try{try{await this.renameWithRetry(i,a),c=!0}catch(e){if("ENOENT"!==_c(e))throw e}await this.renameWithRetry(o,i)}catch(r){if(KI.error(e,"Per-server swap failed",r,{serverIdentifier:t.serverIdentifier,sanitizedId:t.sanitizedId},{includeStructuredLogs:!0}),c)try{await this.renameWithRetry(a,i)}catch{await(0,xo.stat)(i).then((()=>!0),(()=>!1))&&await(0,xo.rm)(a,{recursive:!0,force:!0}).catch((()=>{}))}throw await(0,xo.rm)(o,{recursive:!0,force:!0}).catch((()=>{})),r}await(0,xo.rm)(a,{recursive:!0,force:!0}).catch((()=>{}))}async renameWithRetry(e,t){for(let r=0;;r++)try{return void await(0,xo.rename)(e,t)}catch(e){const t=_c(e);if(r>=YI.length||void 0===t||!eT.has(t))throw e;await(0,Nr.cb)(YI[r])}}async writeServerDirectory(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{NI(n,(0,D.VI)(e.withName("McpFileSystemWriter.writeServerDirectory")),!1);const o=(0,s.join)(r.basePath,r.dirName??t.sanitizedId);await(0,xo.mkdir)(o,{recursive:!0});const i=[];if(t.tools.length>0){const e=(0,s.join)(o,ZI);await(0,xo.mkdir)(e,{recursive:!0});for(const r of t.tools){const t=hT(r.toolName);i.push({path:(0,s.join)(e,`${t}.json`),content:JSON.stringify(Qn(r),null,2)})}}if(t.resources.length>0){const e=(0,s.join)(o,"resources");await(0,xo.mkdir)(e,{recursive:!0});for(const r of t.resources){const t=hT(r.name||r.uri.replace(/[^a-zA-Z0-9_-]/g,"_")),n={uri:r.uri,name:r.name,description:r.description,mimeType:r.mimeType};i.push({path:(0,s.join)(e,`${t}.json`),content:JSON.stringify(n,null,2)})}}if(t.prompts.length>0){const e=(0,s.join)(o,"prompts");await(0,xo.mkdir)(e,{recursive:!0});for(const r of t.prompts){const t=hT(r.name),n={name:r.name,description:r.description,arguments:r.arguments};i.push({path:(0,s.join)(e,`${t}.json`),content:JSON.stringify(n,null,2)})}}t.instructions&&t.instructions.trim().length>0&&i.push({path:(0,s.join)(o,"INSTRUCTIONS.md"),content:t.instructions.trim()}),"error"!==t.status&&"needsAuth"!==t.status||i.push({path:(0,s.join)(o,"STATUS.md"),content:"error"===t.status?this.getErrorStatusMessage():this.getNeedsAuthStatusMessageForWrite(t.serverIdentifier)});const a={serverIdentifier:t.serverIdentifier,serverName:t.serverName};i.push({path:(0,s.join)(o,"SERVER_METADATA.json"),content:JSON.stringify(a,null,2)});if(new Set(i.map((e=>e.path.toLowerCase()))).size!==i.length){for(const e of i)await(0,xo.writeFile)(e.path,e.content);return}const c=(await(0,Nr.up)(i,(e=>(0,xo.writeFile)(e.path,e.content)),{max:8})).find((e=>"rejected"===e.status));if(c)throw c.reason}catch(e){n.error=e,n.hasError=!0}finally{LI(n)}}async getMcpFileSystemOptions(e,t){const r={stack:[],error:void 0,hasError:!1};try{if(this.disposed)return;NI(r,(0,D.VI)(e.withName("McpFileSystemWriter.getMcpFileSystemOptions")),!1);const n=this.getLogContext(e),o=await this.ensureWritesSettled(e,t?.timeoutMs);if(this.snapshotProvider&&!o)return this.buildOptionsFromSnapshots(e);this.snapshotProvider&&o&&KI.warn(n,"Snapshot mode write barrier timed out; falling back to cached descriptors",{timeoutMs:t?.timeoutMs},{includeStructuredLogs:!0});const i=(this.cachedServerData??[]).map((e=>{const t=e.tools.map((t=>{const r=hT(t.toolName),n=(0,s.join)(e.folderPath,ZI,`${r}.json`);return new vn.E$({toolName:t.toolName,definitionPath:n,...Nb(t.annotations)})}));return new vn.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,folderPath:e.folderPath,serverUseInstructions:e.instructions,tools:t})}));return this.checkDescriptorsVsFilesystem(e,i,"workbench_lease"),new vn.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:i})}catch(e){r.error=e,r.hasError=!0}finally{LI(r)}}async ensureWritesSettled(e,t){const r=this.getLogContext(e),n=void 0!==this.debounceTimer;if(void 0!==this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0,this.scheduleWrite(e,this.takePendingLeaseChangeEvent())),n&&KI.info(r,"getMcpFileSystemOptions force-fired pending debounce"),!this.writePromise)return!1;if(void 0!==t){let e,n=!1;try{await Promise.race([this.writePromise,new Promise((r=>{e=setTimeout((()=>{n=!0,r()}),t)}))])}catch(e){KI.error(r,"Error waiting for pending write to complete",e)}finally{clearTimeout(e)}return n&&KI.warn(r,`getMcpFileSystemOptions timed out after ${t}ms waiting for write; returning stale cache`),n}try{await this.writePromise}catch(e){KI.error(r,"Error waiting for pending write to complete",e)}return!1}async buildOptionsFromSnapshots(e){const t={stack:[],error:void 0,hasError:!1};try{NI(t,(0,D.VI)(e.withName("McpFileSystemWriter.buildOptionsFromSnapshots")),!1);const r=this.getLogContext(e),n=Date.now(),o=await this.snapshotProvider.getAllSnapshots(e),i=(0,s.join)(this.projectDir,JI),a=o.filter((e=>e.tools.length>0||e.resources.length>0||e.prompts.length>0||void 0!==e.instructions||this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)||"needsAuth"===e.status||"error"===e.status)).map((e=>{const t=Fy(e.serverIdentifier),r=(0,s.join)(i,t),n=e.tools.map((e=>{const t=hT(e.name);return new vn.E$({toolName:e.name,definitionPath:(0,s.join)(r,ZI,`${t}.json`),...Nb(e.annotations)})}));if(this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&!e.tools.some((e=>e.name===iT))){const e=hT(iT);n.push(new vn.E$({toolName:iT,definitionPath:(0,s.join)(r,ZI,`${e}.json`)}))}return new vn.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,folderPath:r,serverUseInstructions:e.instructions,tools:n})})),c=a.reduce(((e,t)=>e+t.tools.length),0);return KI.info(r,`buildOptionsFromSnapshots completed in ${Date.now()-n}ms: ${o.length} snapshots, ${a.length} descriptors, ${c} tools`),this.checkDescriptorsVsFilesystem(e,a,"snapshot"),new vn.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:a})}catch(e){t.error=e,t.hasError=!0}finally{LI(t)}}async waitForPendingWrites(){if(void 0!==this.debounceTimer&&await new Promise((e=>{const t=()=>{void 0===this.debounceTimer?e():setTimeout(t,10)};t()})),this.writePromise)try{await this.writePromise}catch{}}getCachedServerData(){return this.cachedServerData}checkDescriptorsVsFilesystem(e,t,r){const n=this.getLogContext(e),o=Date.now();o-this.lastDivergenceCheckMs{KI.warn(n,"Divergence check failed",e)})))}async _checkDescriptorsVsFilesystemAsync(e,t,r){const n=this.getLogContext(e),o=(0,s.join)(this.projectDir,JI),i=new Set,a=new Map;for(const e of t){const t=Fy(e.serverIdentifier);i.add(t),a.set(t,e.tools.length)}let c=[];try{c=await(0,xo.readdir)(o),c=c.filter((e=>!e.endsWith(XI)&&!e.endsWith(QI)))}catch(e){if("ENOENT"!==_c(e))throw e}const l=new Set(c);let u=!0,d=0,h=0,p=0;const f=function(e){return 0===e?"0":e<=3?"1-3":e<=6?"4-6":e<=10?"7-10":"11+"}(i.size);for(const t of i)l.has(t)||(u=!1,d++,jI.increment(e,1,this.getMetricTags({divergence_type:"server_missing",mcp_source:r,configured_servers:f})),KI.warn(n,"Divergence detected: server missing from filesystem",{mcpFileSystemMeta:{divergenceType:"server_missing",serverId:t,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}));for(const t of l)i.has(t)||(u=!1,h++,jI.increment(e,1,this.getMetricTags({divergence_type:"server_stale",mcp_source:r,configured_servers:f})));for(const t of i){if(!l.has(t))continue;const c=a.get(t)??0,d=(0,s.join)(o,t,ZI);let h=0;try{h=(await(0,xo.readdir)(d)).filter((e=>e.endsWith(".json"))).length}catch{}h!==c&&(u=!1,p++,jI.increment(e,1,this.getMetricTags({divergence_type:"tool_count_mismatch",mcp_source:r,configured_servers:f})),KI.warn(n,"Divergence detected: tool count mismatch",{mcpFileSystemMeta:{divergenceType:"tool_count_mismatch",serverId:t,expected:c,actual:h,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}))}UI.increment(e,1,this.getMetricTags({synced:String(u),mcp_source:r,configured_servers:f})),BI.gauge(e,i.size,this.getMetricTags({mcp_source:r})),WI.gauge(e,l.size,this.getMetricTags({mcp_source:r})),HI.gauge(e,d,this.getMetricTags({mcp_source:r})),qI.gauge(e,p,this.getMetricTags({mcp_source:r})),KI.info(n,"MCP filesystem sync check",{mcpFileSystemMeta:{synced:u,expectedServers:i.size,actualServers:l.size,serversMissing:d,serversStale:h,toolMismatches:p,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}),u||KI.warn(n,"MCP filesystem divergence summary",{mcpFileSystemMeta:{synced:u,expectedServers:i.size,actualServers:l.size,serversMissing:d,serversStale:h,toolMismatches:p,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0})}dispose(){this.disposed||(this.disposed=!0,void 0!==this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.leaseChangeDisposable&&(this.leaseChangeDisposable.dispose(),this.leaseChangeDisposable=void 0),this.cachedServerData=void 0,this.cachedFingerprints.clear())}}vT.DIVERGENCE_CHECK_COOLDOWN_MS=1e4;var bT=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},ST=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function kT(e){if("object"!=typeof e||null===e||Array.isArray(e))return;const t={};for(const[r,n]of Object.entries(e))"string"==typeof n&&(t[r]=n);return t}const _T=(0,d.h)("local-exec:mcp");function CT(e,t){const r=s.relative(e,t);return""===r||!s.isAbsolute(r)&&".."!==r&&!r.startsWith(`..${s.sep}`)}function ET(e){return e instanceof Error&&"code"in e&&"string"==typeof e.code?e.code:void 0}function xT(e){return new Mc._Z({content:{case:"image",value:new Mc.do({data:e.data,mimeType:e.mimeType})}})}function PT(e){return new Mc._Z({content:{case:"text",value:new Mc.zN({text:e})}})}async function RT(e,t,r){const n=await r.permissionsService.shouldBlockMcp(e,t,r.toolDef,{alreadyApproved:t.skipApproval,...void 0===r.client?{}:{client:r.client},...void 0===r.resolvedTool?{}:{resolvedTool:r.resolvedTool}});if(!n)return;const o=await ed(n,{onNeedsApproval:async(e,n)=>{if("mcp"!==n.type)return new Mc.iz({result:{case:"error",value:new Mc.Nh({error:"Invalid approval details type for MCP execution"})}});const o=await r.pendingDecisionProvider.requestApproval({type:Bw.Mcp,details:{name:n.name,toolName:n.toolName,toolTitle:n.toolTitle,destructiveHint:n.destructiveHint,providerIdentifier:n.providerIdentifier,source:r.toolDef?.source,args:n.args,reason:n.reason??e,canAllowlist:n.canAllowlist,smartModeApprovalReason:n.smartModeApprovalReason,smartModeApprovalRequestId:n.smartModeApprovalRequestId,allowlistEntry:n.allowlistEntry,computerUseApp:n.computerUseApp},toolCallId:t.toolCallId});return o.approved&&void 0!==n.computerUseApp&&!0!==n.computerUseApp.allowOnce&&r.permissionsService.allowComputerUseAppForSession?.({bundleId:n.computerUseApp.bundleId}),o.approved?t.smartModeApprovalOnly?new Mc.iz({result:{case:"approved",value:new Mc.Ke}}):null:new Mc.iz({result:{case:"rejected",value:new Mc.xo({reason:`User rejected MCP: ${t.name}${o.reason?` - ${o.reason}`:""}`})}})},onUserRejected:e=>new Mc.iz({result:{case:"error",value:new Mc.Nh({error:`User rejected MCP: ${t.name}${e?` - ${e}`:""}`})}}),onPermissionDenied:(e,r)=>IT({name:t.name,reason:e,isReadonly:r?.isReadonly??!1})});return o??void 0}function IT({name:e,reason:t,isReadonly:r}){return new Mc.iz({result:{case:"permissionDenied",value:new Mc.HQ({error:`MCP tool execution blocked: ${e} - ${t}`,isReadonly:r})}})}class TT{constructor(e,t,r,n,o=4e4,s,i,a={}){this.toolSet=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.projectDir=n,this.fileOutputThresholdBytes=o,this.elicitationFactory=s,this.ensureMcpServersLoaded=i,this.spillOptions=a}async describeDisconnectedServer(e,t){const r=new Set(t.filter((e=>""!==e)));if(0===r.size)return;let n;try{n=await this.toolSet.getClients(e)}catch{return}const o=Object.entries(n).find((([e,t])=>r.has(e)||r.has(t.serverName)));if(void 0===o)return;const[s,i]=o;let a;try{a=await i.getState(e)}catch{return}if("ready"===a.kind&&void 0===a.toolListError)return;const c=function(e){switch(e){case"needsAuth":return"This MCP server requires authentication before its tools can be used.";case"error":return"This MCP server failed during live tool discovery. Its tools are unavailable until the connection is fixed.";case"loading":return"This MCP server is still loading; tools may not be available yet.";default:return}}(to(a));return void 0!==c?`MCP server "${s}" has no callable tools right now. ${c}${"error"===a.kind&&a.message?` (${a.message})`:""}`:void 0}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=bT(r,(0,D.VI)(e.withName("LocalMcpToolExecutor.execute")),!1).ctx,i=t.serverIdentifier||t.providerIdentifier;await(this.ensureMcpServersLoaded?.(o,[i]));const a=await this.toolSet.getTools(o),c=Array.from(new Set(a.map((e=>e.clientKey)))).sort(),l=a.find((e=>e.clientKey===i&&e.toolName===t.toolName)),u=a.find((e=>e.name===t.name));if(void 0!==u&&(void 0!==l?u!==l:u.toolName!==t.toolName||u.clientKey!==i&&u.providerIdentifier!==i))return new Mc.iz({result:{case:"error",value:new Mc.Nh({error:`MCP tool "${t.name}" is not the tool "${t.toolName}" on server "${i}" that the call names.`})}});const d=void 0===l?void 0:await this.toolSet.getClient(o,l.clientKey).catch((()=>{})),h=l??u,p=void 0===h?void 0:h===l?d:await this.toolSet.getClient(o,h.clientKey).catch((()=>{})),f=await RT(o,t,{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionProvider,toolDef:l,...void 0===d?{}:{client:d},...void 0===h?{}:{resolvedTool:void 0===p?"unresolved":{client:p,annotations:h.annotations}}});if(void 0!==f)return f;const m=await this.toolSet.getToolSet(o),g=!0===await(this.permissionsService.enforcesMcpAdminToolLimits?.());let w;try{if(g&&void 0===h)throw new kC(t.name,a.map((e=>e.name)));const e=l?.name??t.name,r=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()])));if(g){const n=void 0===p?void 0:await(m.executeOn?.(p,e,r,t.toolCallId,this.elicitationFactory));if(void 0===n)return _T.warn(o,"Refusing an MCP tool whose client was not judged",{toolName:t.toolName,toolSetNamesClients:void 0!==m.executeOn}),IT({name:t.name,reason:ik,isReadonly:!1});w=n}else w=await m.execute(e,r,t.toolCallId,this.elicitationFactory)}catch(e){let r=e;if(_C(r)&&t.providerIdentifier.length>0&&!a.some((e=>e.clientKey===t.providerIdentifier||e.providerIdentifier===t.providerIdentifier))&&(r=new rI(t.providerIdentifier,c)),r instanceof rI){const e=await this.describeDisconnectedServer(o,[i,t.providerIdentifier]);return void 0!==e?new Mc.iz({result:{case:"error",value:new Mc.Nh({error:e})}}):new Mc.iz({result:{case:"serverNotFound",value:new Mc.JL({name:r.serverName,availableServers:r.availableServers})}})}if(_C(r))return new Mc.iz({result:{case:"toolNotFound",value:new Mc.WV({name:r.toolName,availableTools:r.availableTools})}});throw r}const y=[];for(const e of w.content){const r=e.type;if("text"===r&&"object"==typeof e&&null!==e&&"text"in e&&"string"==typeof e.text)y.push(PT(e.text));else if("resource"===r){const r=aE(e),n=void 0===r?void 0:Buffer.from(r,"base64"),s=void 0===n?void 0:await Bv(n).then(xT,(e=>{_T.warn(o,"Describing an undecodable MCP resource image",{toolName:t.toolName,bytes:n.byteLength,error:e instanceof Error?e.message:String(e)})}));y.push(s??PT(cE(e)))}else if("image"===r){const r=e,s="string"==typeof r.data?Buffer.from(r.data,"base64"):Buffer.alloc(0);let i;try{i=await Bv(s)}catch(e){_T.warn(o,"Omitting undecodable MCP tool image",{toolName:t.toolName,mimeType:"string"==typeof r.mimeType?r.mimeType.slice(0,100):typeof r.mimeType,bytes:s.byteLength,error:e instanceof Error?e.message:String(e)}),y.push(PT(`[Image omitted: the tool returned ${n=r.mimeType,"string"==typeof n&&/^image\/[\w.+-]{1,40}$/.test(n)?n:"image"} data (${s.byteLength} bytes) that could not be decoded.]`));continue}y.push(xT(i))}else if("image"!==r){const t=cE(e);y.push(PT(t))}}const v=await async function({contentItems:e,thresholdBytes:t,write:r}){const n=e.filter((e=>"text"===e.content.case&&void 0===e.content.value.outputLocation)).map((e=>"text"===e.content.case?e.content.value.text:"")).join("\n\n");if(t<=0||Buffer.byteLength(n,"utf8")<=t)return e;const o=await r(n);if(void 0===o)return;const s=[];let i=!1;for(const t of e)"text"===t.content.case&&void 0===t.content.value.outputLocation?i||(s.push(new Mc._Z({content:{case:"text",value:new Mc.zN({text:"",outputLocation:o})}})),i=!0):s.push(t);return s}({contentItems:y,thresholdBytes:this.fileOutputThresholdBytes,write:e=>async function(e,t,r){const n=s.join(t,Dc),o=s.join(n,`${(0,ko.randomUUID)()}.txt`);await(0,xo.mkdir)(s.dirname(o),{recursive:!0});const i=Jo(!0===r.blankSharedPaymentTokens?tx(e):e,Oc),a=Xs(i),c=Buffer.byteLength(i,"utf8");return await(0,xo.writeFile)(o,i,"utf8"),new Fc.pV({filePath:o,sizeBytes:BigInt(c),lineCount:BigInt(a)})}(e,this.projectDir,this.spillOptions)});if(void 0===v)throw new Error("Failed to materialize MCP text output");const b=w.structuredContent&&"object"==typeof w.structuredContent&&!Array.isArray(w.structuredContent)?ve.Struct.fromJson(w.structuredContent):void 0,S=new Mc.QW({content:v,isError:w.isError,structuredContent:b,resultMeta:void 0===w._meta?void 0:ve.Struct.fromJson(w._meta)});return new Mc.iz({result:{case:"success",value:S}})}catch(e){r.error=e,r.hasError=!0}finally{ST(r)}var n}}class AT{constructor(e,t){this.mcpLease=e,this.ensureMcpServersLoaded=t}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=bT(r,(0,D.VI)(e.withName("LocalListMcpResourcesExecutor.execute")),!1).ctx;try{if(t.server){await(this.ensureMcpServersLoaded?.(n,[t.server]));const e=await this.mcpLease.getClients(n),r=e[t.server]??Object.values(e).find((e=>e.serverName===t.server));if(!r)return new Mc.kP({result:{case:"error",value:new Mc.w2({error:`Server "${t.server}" not found`})}});const o=await this.listResourcesFromClient(n,r,t.server,!0);return new Mc.kP({result:{case:"success",value:new Mc.T2({resources:o})}})}const e=await this.mcpLease.getClients(n),r=new Set,o=await this.mcpLease.getTools(n);for(const e of o)r.add(e.providerIdentifier),r.add(`user-${e.providerIdentifier}`);const s=[];for(const[t,o]of Object.entries(e)){if(r.size>0&&!r.has(t))continue;const e=await this.listResourcesFromClient(n,o,t);s.push(...e)}return new Mc.kP({result:{case:"success",value:new Mc.T2({resources:s})}})}catch(e){const t=e instanceof Error?e.message:String(e);return new Mc.kP({result:{case:"error",value:new Mc.w2({error:`Failed to list MCP resources: ${t}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{ST(r)}}async listResourcesFromClient(e,t,r,n=!1){const o=await t.getState(e);if("ready"!==o.kind&&(!n||"loading"!==o.kind))return[];const s=await t.listResources(e);return s&&s.resources?s.resources.map((e=>new Mc.X2({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType,server:r,annotations:kT(e.annotations)}))):[]}}class $T{constructor(e,t=".",r,n=[],o,s,i){this.mcpLease=e,this.projectDir=t,this.pendingDecisionProvider=o,this.ensureMcpServersLoaded=s,this.writeExecutor=i,this.workspacePaths=n.filter((e=>e.length>0))}resolveProjectDir(e){const t=e.get(OI),r=t?.find((e=>"string"==typeof e&&e.length>0));return r||(this.workspacePaths.length>0?this.workspacePaths[0]:this.projectDir)}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=bT(r,(0,D.VI)(e.withName("LocalReadMcpResourceExecutor.execute")),!1).ctx,o=t.smartModeApproval?.reason;if(void 0!==o){if(void 0===this.pendingDecisionProvider)return new Mc.ZD({result:{case:"error",value:new Mc.Jx({uri:t.uri,error:"Auto-review approval provider is not configured"})}});const e=await this.pendingDecisionProvider.requestApproval({type:Bw.Mcp,details:{name:"FetchMcpResource",toolName:"FetchMcpResource",providerIdentifier:t.server,args:{server:ve.Value.fromJson(t.server),uri:ve.Value.fromJson(t.uri),...void 0!==t.downloadPath?{downloadPath:ve.Value.fromJson(t.downloadPath)}:{}},reason:"smartMode",canAllowlist:!1,smartModeApprovalReason:o,smartModeApprovalRequestId:t.smartModeApproval?.requestId},toolCallId:t.toolCallId});if(!e.approved)return new Mc.ZD({result:{case:"rejected",value:new Mc.Dh({reason:"User rejected MCP resource fetch"+(e.reason?` - ${e.reason}`:"")})}})}await(this.ensureMcpServersLoaded?.(n,[t.server]));const i=await this.mcpLease.getClients(n),a=i[t.server]??Object.values(i).find((e=>e.serverName===t.server));if(!a)return new Mc.ZD({result:{case:"error",value:new Mc.Jx({uri:t.uri,error:`Server "${t.server}" not found`})}});try{if("ready"!==(await a.getState(n)).kind)return new Mc.ZD({result:{case:"error",value:new Mc.Jx({uri:t.uri,error:`Server "${t.server}" is not ready`})}});const e=await a.readResource(n,{uri:t.uri});if(!e||!e.contents||0===e.contents.length)return new Mc.ZD({result:{case:"notFound",value:new Mc.ov({uri:t.uri})}});const r=e.contents[0];if(t.downloadPath){const e=await async function(e,t){const r=s.resolve(e),n=await(0,xo.realpath)(r),o=s.isAbsolute(t)?s.resolve(t):s.resolve(r,t),i=CT(r,o),a=s.isAbsolute(t)&&CT(n,o);if(!i&&!a)throw new Error("downloadPath must stay within the workspace");let c=s.dirname(o);for(;;)try{if(!CT(n,await(0,xo.realpath)(c)))throw new Error("downloadPath must stay within the workspace");break}catch(e){if("ENOENT"!==ET(e))throw e;const t=s.dirname(c);if(t===c)throw e;c=t}try{if((await(0,xo.lstat)(o)).isSymbolicLink())throw new Error("downloadPath must stay within the workspace")}catch(e){if("ENOENT"!==ET(e))throw e}return o}(this.resolveProjectDir(n),t.downloadPath);let o=e;if(r.text||r.blob){if(void 0===this.writeExecutor)throw new Error("File-write executor is not configured");const s=await this.writeExecutor.execute(n,new FI.hY({path:e,fileText:r.text??"",fileBytes:r.text||void 0===r.blob?new Uint8Array:new Uint8Array(Buffer.from(r.blob,"base64")),toolCallId:t.toolCallId,confineToWorkspace:!0}));if("rejected"===s.result.case)return new Mc.ZD({result:{case:"rejected",value:new Mc.Dh({uri:t.uri,reason:s.result.value.reason})}});if("success"!==s.result.case)return new Mc.ZD({result:{case:"error",value:new Mc.Jx({uri:t.uri,error:MT(s)})}});o=s.result.value.path}return new Mc.ZD({result:{case:"success",value:new Mc.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,downloadPath:o})}})}if(r.text)return new Mc.ZD({result:{case:"success",value:new Mc.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:kT(r.annotations),metaJson:Xn(r._meta),content:{case:"text",value:r.text}})}});if(r.blob){const e=Buffer.from(r.blob,"base64");return new Mc.ZD({result:{case:"success",value:new Mc.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:kT(r.annotations),metaJson:Xn(r._meta),content:{case:"blob",value:e}})}})}return new Mc.ZD({result:{case:"error",value:new Mc.Jx({uri:t.uri,error:"Failed to read resource"})}})}catch(e){const r=e instanceof Error?e.message:String(e);return _T.warn(n,"LocalReadMcpResourceExecutor.execute failed",{server:t.server,hasDownloadPath:Boolean(t.downloadPath),errorName:e instanceof Error?e.name:typeof e,errorMessage:r}),new Mc.ZD({result:{case:"error",value:new Mc.Jx({uri:t.uri,error:`Failed to read MCP resource: ${r}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{ST(r)}}}function MT(e){switch(e.result.case){case"error":return e.result.value.error;case"permissionDenied":return e.result.value.error||"Permission denied";case"noSpace":return"No space left on device";case"rejected":return e.result.value.reason||"Write rejected";case"success":return"";case void 0:return"Write executor returned result without case";default:{const t=e.result;return String(t)}}}var DT=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const OT=1e4,FT=5e3,NT={PAGER:"cat",MANPAGER:"cat",LESS:"-R",PIP_PROGRESS_BAR:"off",TQDM_DISABLE:"1"};class LT{constructor(){this.fullOutput="",this.outputHead="",this.outputTail="",this.totalChars=0}append(e){if(0===e.length)return;const t=this.totalChars;if(this.totalChars+=e.length,tOT&&(this.fullOutput="")}getOutput(){return this.totalChars<=OT?this.fullOutput:void 0}getTruncation(){if(!(this.totalChars<=OT))return{outputHead:this.outputHead,outputTail:this.outputTail,elidedChars:this.totalChars-this.outputHead.length-this.outputTail.length}}}class jT{constructor(){this.kept="",this.full=!1}append(e){if(this.full)return;const t=os-this.kept.length;this.full=e.length>=t,this.kept+=Jo(e,t)}get text(){return this.kept}}function UT(e,t){return null!==e?e:null===t?-1:-o.constants.signals[t]}class BT{constructor(e,t,r){this.permissionsService=e,this.ignoreService=t,this.defaultCwd=r}buildResult({args:e,workingDirectory:t,processResult:r,sandboxPolicy:n}){const o={command:e.command,workingDirectory:t,exitCode:r.returncode,signal:r.signal,stdout:r.stdout,stderr:r.exceptionInfo||r.stderr,interleavedOutput:r.output,outputHead:r.outputTruncation?.outputHead,outputTail:r.outputTruncation?.outputTail,elidedChars:r.outputTruncation?.elidedChars,executionTime:r.localExecutionTimeMs??0,localExecutionTimeMs:r.localExecutionTimeMs},s=r.exceptionInfo.length>0,i=0!==r.returncode||s?{case:"failure",value:new fe.xC({...o,aborted:s,abortReason:r.abortReason})}:{case:"success",value:new fe.QR(o)};return new fe.W4({result:i,sandboxPolicy:hs(n)})}async runProcess({ctx:e,args:t,workingDirectory:r,sandboxPolicy:n,timeoutMs:o}){const s=performance.now(),i=this.defaultCwd,a=(await(0,No.resolveSandboxPolicyForWorkspace)(i,n?{perUser:n}:void 0)).policy,c="insecure_none"!==a.type?{...a,sandboxWorkspaceRoot:i}:a;return await new Promise((n=>{const i=new LT,a=new jT,l=new jT;let u,d,h=!1,p=!1,f="",m=()=>{};const g=(0,No.Qw)((0,No.ue)((0,No.Xw)({...process.env,...NT,CURSOR_AGENT:"1"}))),w={cwd:r,env:g,stdio:["pipe","pipe","pipe"],detached:"win32"!==process.platform,windowsVerbatimArguments:"win32"===process.platform},y="win32"===process.platform?{executable:process.env.ComSpec??"cmd.exe",args:(v=t.command,["/d","/s","/c",`"${v}"`])}:{executable:"/bin/sh",args:["-c",t.command]};var v;const b="insecure_none"===c.type?(0,au.D9)(iu.spawn,y.executable,y.args,w):(0,No.spawnInSandbox)(y.executable,y.args,w,c);b.stdin?.end();const S=e=>{h||(h=!0,clearTimeout(d),m(),n({...e,output:i.getOutput(),outputTruncation:i.getTruncation(),localExecutionTimeMs:Oy(performance.now()-s)}))};d=setTimeout((()=>{if(p=!0,void 0===u&&(f=`An error occurred while executing the command: Command timed out after ${o}ms`,u=fe.Lv.TIMEOUT,m()),void 0!==b.pid&&"win32"!==process.platform)try{return void process.kill(-b.pid,"SIGKILL")}catch{}b.kill("SIGKILL")}),o);const k=()=>{if(void 0===u){if(f="An error occurred while executing the command: Command aborted",u=fe.Lv.USER_ABORT,void 0!==b.pid&&"win32"!==process.platform)try{return void process.kill(-b.pid,"SIGTERM")}catch{}b.kill("SIGTERM")}};e.signal.aborted?k():(e.signal.addEventListener("abort",k,{once:!0}),m=()=>{e.signal.removeEventListener("abort",k)}),b.stdout?.setEncoding("utf8"),b.stdout?.on("data",(e=>{a.append(e),i.append(e)})),b.stderr?.setEncoding("utf8"),b.stderr?.on("data",(e=>{l.append(e),i.append(e)})),b.on("error",(e=>{S({stdout:a.text,stderr:l.text,returncode:-1,signal:"",exceptionInfo:`An error occurred while executing the command: ${e.message}`})})),b.on("close",((e,t)=>{S({stdout:a.text,stderr:l.text,returncode:f.length>0?-1:UT(e,t),signal:t??(p?"SIGKILL":""),exceptionInfo:f,abortReason:u})}))}))}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,D.VI)(e.withName("LocalMiniSweAgentBashExecutor.execute")),!1).ctx;(0,D.HF)(n,"LocalMiniSweAgentBashExecutor.execute");const o=t.command,s=(0,ts.o1)(t.workingDirectory||this.defaultCwd),i=t.timeout>0?t.timeout:3e4;if(!t.parsingResult)return new fe.W4({result:{case:"spawnError",value:new fe.mJ({command:o,workingDirectory:s,error:"Parsing result is required"})}});let a=t.requestedSandboxPolicy?ds(t.requestedSandboxPolicy):void 0;const c=await this.permissionsService.shouldBlockShellCommand(n,o,{workingDirectory:s,timeout:i,parsingResult:t.parsingResult,toolCallId:t.toolCallId},a);if("block"===c.kind)return"permissionsConfig"===c.reason.type&&c.reason.isReadonly?new fe.W4({result:{case:"permissionDenied",value:new fe.jn({command:o,workingDirectory:s,error:"Command blocked by permissions configuration",isReadonly:!0})}}):new fe.W4({result:{case:"rejected",value:new fe.pZ({command:o,workingDirectory:s,reason:td(c.reason)})}});a=c.policy,Ds()&&(a=Us(o,t.parsingResult)),a&&"insecure_none"!==a.type&&(a={...a,ignoreMapping:await this.ignoreService.getCursorIgnoreMapping()});const l=await this.runProcess({ctx:n,args:t,workingDirectory:s,sandboxPolicy:a,timeoutMs:i});return this.buildResult({args:t,workingDirectory:s,processResult:l,sandboxPolicy:a})}catch(e){r.error=e,r.hasError=!0}finally{DT(r)}}}const WT=G("shell-executor",(e=>new H(e,Q("shellArgs"),Y("shellResult"))),((e,t)=>{t.register(new A(e,te("shellArgs"),ee("shellResult")))})),HT=G("mini-swe-agent-bash-executor",(e=>new H(e,Q("miniSweAgentBashArgs"),Y("miniSweAgentBashResult"))),((e,t)=>{t.register(new A(e,te("miniSweAgentBashArgs"),ee("miniSweAgentBashResult")))}));function qT(e){return`${e} changed on disk after this tool call read it. Nothing was written. Read the file again and retry.`}function zT(e){return`${e} changed on disk after you last read or wrote it. Nothing was written. Read the file again and retry.`}(0,b.cF)(Symbol("optionalPendingPodWrite"),!1);const GT=G("write-executor",(e=>new H(e,Q("writeArgs"),Y("writeResult"))),((e,t)=>{t.register(new A(e,te("writeArgs"),ee("writeResult")))})),VT=G("delete-executor",(e=>new H(e,Q("deleteArgs"),Y("deleteResult"))),((e,t)=>{t.register(new A(e,te("deleteArgs"),ee("deleteResult")))})),KT=G("fetch-executor",(e=>new H(e,Q("fetchArgs"),Y("fetchResult"))),((e,t)=>{t.register(new A(e,te("fetchArgs"),ee("fetchResult")))})),JT=G("git-diff-executor",(e=>new H(e,Q("gitDiffRequest"),Y("gitDiffResponse"))),((e,t)=>{t.register(new A(e,te("gitDiffRequest"),ee("gitDiffResponse")))})),ZT=G("grep-executor",(e=>new H(e,Q("grepArgs"),Y("grepResult"))),((e,t)=>{t.register(new A(e,te("grepArgs"),ee("grepResult")))})),XT="[REDACTED]",QT=new TextEncoder;async function YT(e){const t=QT.encode(e),r=await crypto.subtle.digest("SHA-256",t);return{sha256:[...new Uint8Array(r)].map((e=>e.toString(16).padStart(2,"0"))).join(""),bytes:t.byteLength}}class eA{constructor(e){this.inner=e}async execute(e,t,r){if(!0!==t.digestOnly)return this.inner.execute(e,t,r);const n=t.clone();return n.digestOnly=void 0,n.maxChars=void 0,async function(e){if("success"!==e.result.case)return e;const t=e.result.value;if("content"!==t.output.case)return e;const{sha256:r,bytes:n}=await YT(t.output.value),o=t.clone();return o.output={case:void 0},o.outputBlobId=void 0,o.sha256=r,o.sizeBytes=BigInt(n),new Xy.sV({result:{case:"success",value:o}})}(await this.inner.execute(e,n,r))}}const tA=G("read-executor",(e=>new H(e,Q("readArgs"),Y("readResult"))),((e,t)=>{t.register(new A(e,te("readArgs"),ee("readResult")))})),rA=G("redacted-read-executor",(e=>new H(e,Q("redactedReadArgs"),Y("redactedReadResult"))),((e,t)=>{t.register(new A(e,te("redactedReadArgs"),ee("redactedReadResult")))})),nA=G("ls-executor",(e=>new H(e,Q("lsArgs"),Y("lsResult"))),((e,t)=>{t.register(new A(e,te("lsArgs"),ee("lsResult")))})),oA=G("diagnostics-executor",(e=>new H(e,Q("diagnosticsArgs"),Y("diagnosticsResult"))),((e,t)=>{t.register(new A(e,te("diagnosticsArgs"),ee("diagnosticsResult")))})),sA=G("canvas-diagnostics-executor",(e=>new H(e,Q("canvasDiagnosticsArgs"),Y("canvasDiagnosticsResult"))),((e,t)=>{t.register(new A(e,te("canvasDiagnosticsArgs"),ee("canvasDiagnosticsResult")))})),iA="$file:";const aA=(0,h.Pu)("mcp.symbolic_args.expansion",{description:"Outcome of late-binding $file:/abs/path MCP argument expansion at the executor boundary. The call is refused rather than carrying a placeholder to the server when the read reports having replaced a saved secret (`redacted`), or, from a read executor too old to report that, when its text still carries the redaction marker (`redacted_marker`)",labelNames:["route","outcome"]}),cA=(0,h.v5)("mcp.symbolic_args.bytes",{description:"Total bytes substituted into one MCP tool call by $file:/abs/path arguments",labelNames:["route"]}),lA=(0,h.Pu)("mcp.symbolic_args.describe",{description:"Per-file $file:/abs/path describe reads: `vm_digest` when the read executor hashed the file where it lives, `outdated_executor` when it returned the text instead (it predates $file: expansion, so the call is refused)",labelNames:["source"]}),uA=(0,h.v5)("mcp.symbolic_args.paths",{description:"Number of distinct $file:/abs/path arguments expanded in one MCP tool call",labelNames:["route"]});function dA(e,t,r){return{kind:e,message:`Could not resolve the symbolic argument "${iA}${t}": ${r} A string argument of the form "${iA}/absolute/path" is replaced with that file's contents before the tool runs; pass the literal text instead if you did not intend that.`}}const hA={redacted:e=>`${e} contains a saved secret, and a saved secret is never sent through a "${iA}/absolute/path" argument, so this call was not made. Do not retry it, and do not read the file to pass the value yourself. Tell the user that this file holds a saved secret and that they have to enter it in the tool's service themselves.`,redacted_marker:e=>`${e} may contain a saved secret: its text includes the placeholder "${XT}", and the computer that read it is too old to say whether a saved secret stood there, so this call was not made. Do not retry it, and do not read the file to pass the value yourself. Tell the user that this file may hold a saved secret and that they have to enter it in the tool's service themselves.`};function pA(e,t){return{kind:e,message:`Could not resolve the symbolic argument "${iA}${t}": ${hA[e](t)}`}}class fA extends Error{constructor(e){super(e.message),this.failure=e}}let mA;async function gA(e,t,r,n,o,{maxFileBytes:s=8388608,maxTotalBytes:i=16777216,refuseSavedSecrets:a=!1}){if(t.length>4)throw new fA(dA("too_many",t[4]??"",`at most 4 symbolic arguments may be used in one call (${t.length} given). Split the call or pass paths to tools that accept them.`));const c=r();if(void 0===c)throw new fA(dA("no_read_executor",t[0]??"","this environment cannot read files on behalf of a tool call."));const l=await(0,Nr.xb)(t,(t=>async function(e,t,r,n,o){const s=await t.execute(e,new Xy.a2({path:r,toolCallId:n,...o.digestOnly?{digestOnly:!0}:{}}));if("success"!==s.result.case)throw new fA(function(e,t,r){switch(e.result.case){case"fileNotFound":return dA("not_found",t,"the file does not exist.");case"permissionDenied":return dA("permission_denied",t,"reading it was not permitted.");case"rejected":return dA("rejected",t,`${e.result.value.reason||"the read was rejected"}. Only files the Read tool can read without approval can be substituted; read it with Read instead.`);case"invalidFile":return dA("not_text",t,"the file cannot be read as text.");case"error":return r?{kind:"read_error",message:`Could not resolve the symbolic argument "${iA}${t}": ${e.result.value.error}`}:dA("read_error",t,e.result.value.error);default:return dA("read_error",t,"the read returned no result.")}}(s,r,o.refuseSavedSecrets));return await async function(e,t,r,{maxFileBytes:n,digestOnly:o,refuseSavedSecrets:s}){const i=function(e,t,r,n){const o=n&&void 0!==t.sha256&&void 0!==t.sizeBytes?{sha256:t.sha256,bytes:Number(t.sizeBytes)}:void 0;if(void 0===o&&"content"!==t.output.case)throw new fA(dA("not_text",r,"the file is not a text file."));if(n){if(lA.increment(e,1,{source:void 0!==o?"vm_digest":"outdated_executor"}),void 0===o)throw new fA(dA("outdated_executor",r,"the computer that would run this tool has an older tool runner that cannot substitute files. Read the file and pass its contents instead."));return o}}(e,t,r,o),a="content"===t.output.case?t.output.value:void 0,{sha256:c,bytes:l}=i??await YT(a??""),u={content:a,bytes:l,sha256:c};if(t.truncated||l>n)throw new fA(dA("too_large",r,`the file is too large to inline (${Number(t.fileSize)||l} bytes; at most ${n} bytes per file may be substituted). Pass the path to a tool that accepts one, or read a range of it.`));return await async function(e,t,r,n){if(n){if(!0===e.redacted)throw new fA(pA("redacted",r));if(void 0===e.redacted&&await async function(e){return void 0!==e.content?e.content.includes(XT):(await(mA??=Promise.all([XT,`${XT}\n`,`${XT}\r\n`].map((async e=>(await YT(e)).sha256))).then((e=>new Set(e))),mA)).has(e.sha256)}(t))throw new fA(pA("redacted_marker",r))}}(t,u,r,s),u}(e,s.result.value,r,o)}(e,c,t,n,{maxFileBytes:s,digestOnly:o,refuseSavedSecrets:a})),{max:4});let u=0;for(const[e,r]of l)if(u+=r.bytes,u>i)throw new fA(dA("over_budget",e,`together the ${t.length} symbolic arguments exceed the ${i} bytes that may be substituted per call. Pass paths to tools that accept them instead.`));return l}async function wA(e,t,{route:r,getReadExecutor:n,...o}){if(0===t.symbolicPathArguments.length)return{kind:"none"};const s=new Map(t.symbolicPathArguments.map((e=>[e.path,e]))),i=[...s.keys()],a=t=>(aA.increment(e,1,{route:r,outcome:t.kind}),{kind:"failed",failure:t,result:new Mc.iz({result:{case:"error",value:new Mc.Nh({error:t.message})}})});let c;try{c=await gA(e,i,n,t.toolCallId,!1,o)}catch(e){return a(function(e,t){return e instanceof fA?e.failure:dA("read_error",t,e instanceof Error?e.message:String(e))}(e,i[0]??""))}let l=0;for(const[e,t]of c){l+=t.bytes;const r=s.get(e);if(r?.sha256!==t.sha256)return a(dA("content_changed",e,`the file changed after the call was reviewed (${r?.sizeBytes??0} bytes then, ${t.bytes} bytes now), so its new contents were not sent. Re-run the call to review the current contents.`))}const u=new Map([...c].map((([e,t])=>[e,t.content??""]))),d=function(e,t){const r=e=>{const n=function(e){if("string"!=typeof e||!e.startsWith(iA))return;const t=e.slice(6);return(r=t).startsWith("/")||/^[a-zA-Z]:[\\/]/.test(r)||r.startsWith("\\\\")?t:void 0;var r}(e);return void 0!==n?t.get(n)??e:Array.isArray(e)?e.map(r):null!==e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map((([e,t])=>[e,r(t)]))):e};return Object.fromEntries(Object.entries(e).map((([e,t])=>[e,r(t)])))}(Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()]))),u),h=t.clone();return h.args=Object.fromEntries(Object.entries(d).map((([e,t])=>[e,ve.Value.fromJson(t)]))),h.symbolicPathArguments=[],h.argumentsRepaired=!1,aA.increment(e,1,{route:r,outcome:"expanded"}),cA.record(e,l,{route:r}),uA.record(e,i.length,{route:r}),{kind:"expanded",expansion:{args:h,files:[...c].map((([e,t])=>({path:e,bytes:t.bytes}))),paths:i.length,bytes:l}}}const yA=/\b413\b|payload too large|request entity too large|body.*too large|too large.*body|ECONNRESET|EPIPE|socket hang up|max(?:imum)? (?:body|payload|request|content) (?:size|length)/i;function vA(e,t,r,n){return yA.test(t)?(aA.increment(e,1,{route:n,outcome:"server_rejected_body"}),`${t}\n\nThe request carried ${r.bytes} bytes of file contents substituted from ${r.paths} "${iA}/abs/path" argument(s), and the server appears to have rejected the request body as too large. Do not retry the same call: pass a smaller file or a range of it, or use a tool that accepts a path or upload instead.`):t}function bA(e){return e.files.map((e=>`"${iA}${e.path}" was replaced with the contents of ${e.path} (${e.bytes} bytes) before the call.`)).join("\n")}class SA{constructor(e,t,r={}){this.inner=e,this.getReadExecutor=t,this.options=r}isBackendRouted(e){return this.inner.isBackendRouted?.(e)??!1}async execute(e,t,r){if(0===t.symbolicPathArguments.length)return this.inner.execute(e,t,r);const n=await wA(e,t,{route:"local",getReadExecutor:this.getReadExecutor,refuseSavedSecrets:!0===this.options.refuseSavedSecrets&&t.refuseSavedSecrets});if("none"===n.kind)return this.inner.execute(e,t,r);if("failed"===n.kind)return n.result;let o;try{o=await this.inner.execute(e,n.expansion.args,r)}catch(t){throw t instanceof Error&&(t.message=vA(e,t.message,n.expansion,"local")),t}return function(e,t,r){const n=t.clone();return"success"===n.result.case?n.result.value.content.push(new Mc._Z({content:{case:"text",value:new Mc.zN({text:bA(r)})}})):"error"===n.result.case&&(n.result.value.error=vA(e,n.result.value.error,r,"local")),n}(e,o,n.expansion)}}const kA=G("background-shell-executor",(e=>new H(e,Q("backgroundShellSpawnArgs"),Y("backgroundShellSpawnResult"))),((e,t)=>{t.register(new A(e,te("backgroundShellSpawnArgs"),ee("backgroundShellSpawnResult")))})),_A=G("write-background-shell-input-executor",(e=>new H(e,Q("writeShellStdinArgs"),Y("writeShellStdinResult"))),((e,t)=>{t.register(new A(e,te("writeShellStdinArgs"),ee("writeShellStdinResult")))})),CA=G("agent-store-conflict-executor",(e=>new H(e,Q("agentStoreConflictArgs"),Y("agentStoreConflictResult"))),((e,t)=>{t.register(new A(e,te("agentStoreConflictArgs"),ee("agentStoreConflictResult")))})),EA=G("shell-allowlist-precheck-executor",(e=>new H(e,Q("shellAllowlistPrecheckArgs"),Y("shellAllowlistPrecheckResult"))),((e,t)=>{t.register(new A(e,te("shellAllowlistPrecheckArgs"),ee("shellAllowlistPrecheckResult")))})),xA=G("mcp-allowlist-precheck-executor",(e=>new H(e,Q("mcpAllowlistPrecheckArgs"),Y("mcpAllowlistPrecheckResult"))),((e,t)=>{t.register(new A(e,te("mcpAllowlistPrecheckArgs"),ee("mcpAllowlistPrecheckResult")))})),PA=G("web-fetch-allowlist-precheck-executor",(e=>new H(e,Q("webFetchAllowlistPrecheckArgs"),Y("webFetchAllowlistPrecheckResult"))),((e,t)=>{t.register(new A(e,te("webFetchAllowlistPrecheckArgs"),ee("webFetchAllowlistPrecheckResult")))})),RA=G("force-background-shell-executor",(e=>new H(e,Q("forceBackgroundShellArgs"),Y("forceBackgroundShellResult"))),((e,t)=>{t.register(new A(e,te("forceBackgroundShellArgs"),ee("forceBackgroundShellResult")))})),IA=G("computer-use-executor",(e=>new H(e,Q("computerUseArgs"),Y("computerUseResult"))),((e,t)=>{t.register(new A(e,te("computerUseArgs"),ee("computerUseResult")))})),TA=G("computer-use-end-turn-executor",(e=>new H(function(e){return{createExecInstance:(t,r)=>e.createExecInstance(t,(e=>{if(t.signal.aborted)throw new Error("computer-use turn end not sent: its caller stopped waiting");return r(e)}))}}(e),Q("computerUseEndTurnArgs"),Y("computerUseEndTurnResult"))),((e,t)=>{t.register(new A(e,te("computerUseEndTurnArgs"),ee("computerUseEndTurnResult")))})),AA=G("record-screen-executor",(e=>new H(e,Q("recordScreenArgs"),Y("recordScreenResult"))),((e,t)=>{t.register(new A(e,te("recordScreenArgs"),ee("recordScreenResult")))}));var $A=r("../proto/dist/generated/agent/v1/agent_store_conflict_exec_pb.js");function MA(e){if(void 0!==e)return{journalEpoch:e.journalEpoch,seq:Number(e.seq),lastEventId:e.lastEventId}}class DA{constructor(e){this.drainer=e}async execute(e,t){try{void 0!==t.includeQuotaNotices&&this.drainer.setIncludeQuotaNoticesOverride(t.includeQuotaNotices);const e=await this.drainer.drain({cursor:MA(t.cursor),advance:!1!==t.advance});return new $A.Ev({result:{case:"success",value:new $A.iS({events:e.events.map((e=>new $A.RZ({v:e.v,eventId:e.event_id,journalEpoch:e.journal_epoch,seq:BigInt(e.seq),tsMs:BigInt(e.ts_ms),kind:e.kind,storeId:e.store_id,originalRelPath:e.original_rel_path,conflictRelPath:e.conflict_rel_path,originalAbsPath:e.original_abs_path,conflictAbsPath:e.conflict_abs_path,preservedBytes:void 0===e.preserved_bytes?void 0:BigInt(e.preserved_bytes),scopeKind:e.scope_kind,limitBytes:void 0===e.limit_bytes?void 0:BigInt(e.limit_bytes),usageBytes:void 0===e.usage_bytes?void 0:BigInt(e.usage_bytes)}))),nextCursor:(r=e.nextCursor,new $A.LK({journalEpoch:r.journalEpoch,seq:BigInt(r.seq),lastEventId:r.lastEventId})),gap:e.gap})}})}catch(e){return new $A.Ev({result:{case:"error",value:new $A.h6({error:e instanceof Error?e.message:String(e)})}})}var r}}class OA{constructor(e){this.shellStdinWriter=e}async execute(e,t){const r=t.shellId;try{await this.shellStdinWriter(r,t.chars)}catch(e){return new Fo.nt({result:{case:"error",value:new Fo.Gv({error:`Failed to write to shell ${r} stdin: ${e instanceof Error?e.message:"Unknown error"}`})}})}return new Fo.nt({result:{case:"success",value:new Fo.tR({shellId:r,terminalFileLengthBeforeInputWritten:0})}})}}var FA=r("../proto/dist/generated/agent/v1/canvas_diagnostics_exec_pb.js"),NA=r("../proto/dist/generated/agent/v1/diagnostics_exec_pb.js");class LA{constructor(e,t){this.getCanvasDiagnostics=e,this.beginCanvasSave=t}async execute(e,t){let r=()=>{};const n=new Promise((e=>{r=e}));let o;if(void 0===this.beginCanvasSave)o=Promise.resolve(void 0);else try{o=this.beginCanvasSave(t.path,{typecheckOutcome:n}).catch((()=>{}))}catch{o=Promise.resolve(void 0)}try{const e=await this.getCanvasDiagnostics(t.path);return void 0===e?(r("unavailable"),jA(UA(t.path,"diagnostics unavailable"),await o)):(r(e.some((e=>1===e.severity))?"failed":"passed"),jA(new FA.GL({result:{case:"success",value:new FA.uX({path:t.path,diagnostics:e.map(BA)})}}),await o))}catch(e){return r("unavailable"),jA(UA(t.path,e instanceof Error?e.message:String(e)),await o)}}}function jA(e,t){return void 0===t||(e.saveState=t.saveState,e.canvasId=t.canvasId,e.title=t.title,e.saveDetail=t.saveDetail),e}function UA(e,t){return new FA.GL({result:{case:"error",value:new FA.HW({path:e,error:t})}})}function BA(e){return new NA.oQ({severity:WA(e.severity),range:new Fc.Q6({start:new Fc.yX({line:e.range.start.line+1,column:e.range.start.character+1}),end:new Fc.yX({line:e.range.end.line+1,column:e.range.end.character+1})}),message:e.message,source:"ts",code:e.code??""})}function WA(e){switch(e){case 1:return NA.h_.ERROR;case 2:return NA.h_.WARNING;case 3:return NA.h_.INFORMATION;case 4:return NA.h_.HINT;default:return NA.h_.UNSPECIFIED}}class HA{constructor(e){if(e.startsWith("file://")){if(!this.isValidFileUrl(e))throw new Error(`Invalid file URL: ${e}`);this.urlString=e}else{const t=this.resolvePath(e);this.urlString=this.pathToFileUrl(t)}}isValidFileUrl(e){try{return"file:"===new URL(e).protocol}catch{return!1}}resolvePath(e){if(e.includes("\\")&&(e=e.replace(/\\/g,"/")),/^[a-zA-Z]:\//.test(e)||/^\//.test(e))return e;const t=e.split("/"),r=[];for(let e=0;ethis.convertDiagnostic(e)));return new NA.Ek({result:{case:"success",value:new NA.a1({path:t.path,diagnostics:s,totalDiagnostics:s.length})}})}catch(r){return e.canceled?new NA.Ek({result:{case:"error",value:new NA.Ho({path:t.path,error:"Request timed out after 10 seconds"})}}):new NA.Ek({result:{case:"error",value:new NA.Ho({path:t.path,error:r instanceof Error?r.message:String(r)})}})}finally{n()}}catch(e){r.error=e,r.hasError=!0}finally{qA(r)}}convertDiagnostic(e){const t=e.message,r="string"==typeof t?t:t&&"object"==typeof t&&"value"in t&&"string"==typeof t.value?t.value:"";return new NA.oQ({severity:this.convertSeverity(e.severity),range:e.range?new Fc.Q6({start:new Fc.yX({line:e.range.start.line,column:e.range.start.character}),end:new Fc.yX({line:e.range.end.line,column:e.range.end.character})}):void 0,message:r,source:e.source,code:e.code?String(e.code):void 0})}convertSeverity(e){switch(e){case 1:return NA.h_.ERROR;case 2:return NA.h_.WARNING;case 3:return NA.h_.INFORMATION;case 4:return NA.h_.HINT;default:return NA.h_.UNSPECIFIED}}}async function GA(e){const{repoRoot:t,filePaths:r,getContent:n}=e,o=new Map;if(0===r.length)return o;const s=await async function(e,t){const r=new Map;if(0===t.length)return r;try{const{stdout:n}=await ky().run(e,["check-attr","linguist-generated","--stdin"],{input:`${t.join("\n")}\n`});for(const e of n.trim().split("\n")){const t=e.match(/^(.+): linguist-generated: (.+)$/);if(t){const e=t[1],n=t[2];"true"===n||"set"===n?r.set(e,!0):"false"!==n&&"unset"!==n||r.set(e,!1)}}}catch{}return r}(t,r);return await Promise.all(r.map((async e=>{const t=s.get(e);if(!0!==t)if(!1!==t)if(function(e){return new VA(e).isGeneratedByPath()}(e))o.set(e,{isGenerated:!0,source:"path-heuristic"});else{if(n){const t=await n(e);if(void 0!==t&&function(e,t){return new VA(e,(()=>t)).isGeneratedByContent()}(e,t))return void o.set(e,{isGenerated:!0,source:"content-heuristic"})}o.set(e,{isGenerated:!1,source:"none"})}else o.set(e,{isGenerated:!1,source:"gitattributes"});else o.set(e,{isGenerated:!0,source:"gitattributes"})}))),o}class VA{constructor(e,t){this.name=e,this.extname=s.extname(e).toLowerCase(),this.getContent=t}get lines(){if(void 0===this.cachedLines){const e=this.getContent?.();this.cachedLines=e?e.split("\n"):[]}return this.cachedLines}get data(){return this.getContent?.()}isGeneratedByPath(){return this.xcodeFile()||this.intellijFile()||this.cocoapods()||this.carthageBuild()||this.generatedGraphqlRelay()||this.generatedNetDesignerFile()||this.generatedNetSpecflowFeatureFile()||this.composerLock()||this.cargoLock()||this.cargoOrig()||this.denoLock()||this.flakeLock()||this.bazelLock()||this.nodeModules()||this.goVendor()||this.goLock()||this.packageResolved()||this.poetryLock()||this.pdmLock()||this.uvLock()||this.pixiLock()||this.esyLock()||this.npmShrinkwrapOrPackageLock()||this.pnpmLock()||this.bunLock()||this.terraformLock()||this.generatedYarnPlugnplay()||this.godeps()||this.generatedByZephir()||this.htmlcov()||this.gradleWrapper()||this.mavenWrapper()||this.pipenvLock()||this.generatedPascalTlb()||this.generatedSqlxQuery()||this.sourceMapByName()}isGeneratedByContent(){return!!this.getContent&&(this.minifiedFiles()||this.hasSourceMap()||this.sourceMap()||this.compiledCoffeescript()||this.generatedParser()||this.generatedNetDocfile()||this.generatedPostscript()||this.compiledCythonFile()||this.generatedGo()||this.generatedProtocolBufferFromGo()||this.generatedProtocolBuffer()||this.generatedJavascriptProtocolBuffer()||this.generatedTypescriptProtocolBuffer()||this.generatedApacheThrift()||this.generatedJniHeader()||this.vcrCassette()||this.generatedAntlr()||this.generatedModule()||this.generatedUnity3dMeta()||this.generatedRacc()||this.generatedJflex()||this.generatedGrammarkit()||this.generatedRoxygen2()||this.generatedHtml()||this.generatedJison()||this.generatedGrpcCpp()||this.generatedDart()||this.generatedPerlPpportHeader()||this.generatedGamemakerstudio()||this.generatedGimp()||this.generatedVisualstudio6()||this.generatedHaxe()||this.generatedJooq()||this.generatedSorbetRbi()||this.generatedMysqlViewDefinitionFormat())}xcodeFile(){return[".nib",".xcworkspacedata",".xcuserstate"].includes(this.extname)}intellijFile(){return/(?:^|\/)\.idea\//.test(this.name)}cocoapods(){return/(^Pods|\/Pods)\//.test(this.name)}carthageBuild(){return/(^|\/)Carthage\/Build\//.test(this.name)}generatedGraphqlRelay(){return/__generated__\//.test(this.name)}generatedNetDesignerFile(){return/\.designer\.(cs|vb)$/i.test(this.name)}generatedNetSpecflowFeatureFile(){return/\.feature\.cs$/i.test(this.name)}composerLock(){return/composer\.lock/.test(this.name)}cargoLock(){return/Cargo\.lock/.test(this.name)}cargoOrig(){return/Cargo\.toml\.orig/.test(this.name)}denoLock(){return/deno\.lock/.test(this.name)}flakeLock(){return/(^|\/)flake\.lock$/.test(this.name)}bazelLock(){return/(^|\/)MODULE\.bazel\.lock$/.test(this.name)}nodeModules(){return/node_modules\//.test(this.name)}goVendor(){return/vendor\/((?!-)[-0-9A-Za-z]+(?e+t.length),0)/this.lines.length>110}hasSourceMap(){return!!this.maybeMinified()&&this.lines.slice(-2).some((e=>/^\/[*/][#@] source(?:Mapping)?URL|sourceURL=/.test(e)))}sourceMap(){if(".map"!==this.extname)return!1;if(/\.(css|js)\.map$/i.test(this.name))return!0;const e=this.lines[0]||"";return/^{"version":\d+,/.test(e)||/^\/\*\* Begin line maps\. \*\*\/{/.test(e)}compiledCoffeescript(){if(".js"!==this.extname)return!1;const e=this.lines[0]||"";if(/^\/\/ Generated by /.test(e))return!0;if("(function() {"===e&&"}).call(this);"===(this.lines[this.lines.length-2]||"")&&""===(this.lines[this.lines.length-1]||"")){let e=0;for(const t of this.lines)if(/var /.test(t)){const r=t.match(/_fn|_i|_len|_ref|_results/g);e+=1*(r?.length||0);const n=t.match(/__bind|__extends|__hasProp|__indexOf|__slice/g);e+=3*(n?.length||0)}return e>=3}return!1}generatedNetDocfile(){return".xml"===this.extname&&!(this.lines.length<=3)&&(this.lines[1]||"").includes("")&&(this.lines[2]||"").includes("")&&(this.lines[this.lines.length-2]||"").includes("")}generatedParser(){if(".js"!==this.extname)return!1;const e=this.lines.slice(0,5).join("");return/^(?:[^/]|\/[^*])*\/\*(?:[^*]|\*[^/])*Generated by PEG\.js/.test(e)}generatedPostscript(){if(![".ps",".eps",".pfa"].includes(this.extname))return!1;const e=this.data;if(!e)return!1;if(/^\s*(?:currentfile eexec\s+|\/sfnts\s+\[\s<)/.test(e))return!0;const t=this.lines.slice(0,10).find((e=>/^%%Creator: /.test(e)));return!!t&&(!(!/[0-9]|draw|mpage|ImageMagick|inkscape|MATLAB/.test(t)&&!/PCBNEW|pnmtops|\(Unknown\)|Serif Affinity|Filterimage -tops/.test(t))||!!t.includes("EAGLE")&&this.lines.slice(0,5).some((e=>/^%%Title: EAGLE Drawing /.test(e))))}generatedGo(){return".go"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,40).some((e=>/^\/\/ Code generated .*/.test(e)))}generatedProtocolBufferFromGo(){return".proto"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,20).some((e=>e.includes("This file was autogenerated by go-to-protobuf")))}generatedProtocolBuffer(){return!![".py",".java",".h",".cc",".cpp",".m",".rb",".php"].includes(this.extname)&&!(this.lines.length<=1)&&this.lines.slice(0,3).some((e=>e.includes("Generated by the protocol buffer compiler. DO NOT EDIT!")))}generatedJavascriptProtocolBuffer(){return".js"===this.extname&&!(this.lines.length<=6)&&(this.lines[5]||"").includes("GENERATED CODE -- DO NOT EDIT!")}generatedTypescriptProtocolBuffer(){return".ts"===this.extname&&!(this.lines.length<=4)&&(this.lines[0]||"").includes("Code generated by protoc-gen-ts_proto. DO NOT EDIT.")}generatedApacheThrift(){return!![".rb",".py",".go",".js",".m",".java",".h",".cc",".cpp",".php"].includes(this.extname)&&this.lines.slice(0,6).some((e=>e.includes("Autogenerated by Thrift Compiler")))}generatedJniHeader(){return".h"===this.extname&&!(this.lines.length<=2)&&(this.lines[0]||"").includes("/* DO NOT EDIT THIS FILE - it is machine generated */")&&(this.lines[1]||"").includes("#include ")}vcrCassette(){return".yml"===this.extname&&!(this.lines.length<=2)&&(this.lines[this.lines.length-2]||"").includes("recorded_with: VCR")}generatedAntlr(){return".g"===this.extname&&!(this.lines.length<=2)&&(this.lines[1]||"").includes("generated by Xtest")}compiledCythonFile(){return!![".c",".cpp"].includes(this.extname)&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("Generated by Cython")}generatedModule(){if(".mod"!==this.extname)return!1;if(this.lines.length<=1)return!1;const e=this.lines[0]||"";return e.includes("PCBNEW-LibModule-V")||e.includes("GFORTRAN module version '")}generatedUnity3dMeta(){return".meta"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("fileFormatVersion: ")}generatedRacc(){return".rb"===this.extname&&!(this.lines.length<=2)&&(this.lines[2]||"").startsWith("# This file is automatically generated by Racc")}generatedJflex(){return".java"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("/* The following code was generated by JFlex ")}generatedGrammarkit(){return".java"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("// This is a generated file. Not intended for manual editing.")}generatedRoxygen2(){return".rd"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("% Generated by roxygen2: do not edit by hand")}generatedHtml(){if(![".html",".htm",".xhtml"].includes(this.extname))return!1;if(this.lines.length<=1)return!1;if(this.lines.slice(0,2).some((e=>//.test(e))))return!0;if(this.lines.length>2&&(this.lines[2]||"").startsWith("\x3c!-- This is an automatically generated file."))return!0;if(this.lines.slice(0,31).some((e=>//i.test(e))))return!0;const e=this.lines.slice(0,31).join(" ").match(/]+)>/gi);if(!e)return!1;for(const t of e){const e=this.extractHtmlMeta(t);if("generator"===e.name?.toLowerCase()&&(e.content||e.value)){const t=e.content||e.value||"";if(/^(org\s+mode|j?latex2html|groff|makeinfo|texi2html|ronn)\b/i.test(t))return!0}}return!1}extractHtmlMeta(e){const t={},r=e.matchAll(/(?<=^|\s)(name|content|value)\s*=\s*("[^"]+"|'[^']+'|[^\s"']+)/gi);for(const e of r){const r=e[1].toLowerCase();let n=e[2];(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'"))&&(n=n.slice(1,-1)),t[r]=n}return t}generatedJison(){if(".js"!==this.extname)return!1;if(this.lines.length<=1)return!1;const e=this.lines[0]||"";return e.startsWith("/* parser generated by jison ")||e.startsWith("/* generated by jison-lex ")}generatedGrpcCpp(){return!![".cpp",".hpp",".h",".cc"].includes(this.extname)&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("// Generated by the gRPC")}generatedDart(){return".dart"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,3).some((e=>/generated code\W{2,3}do not modify/i.test(e)))}generatedPerlPpportHeader(){return!!/ppport\.h$/.test(this.name)&&!(this.lines.length<=10)&&(this.lines[8]||"").includes("Automatically created by Devel::PPPort")}generatedGamemakerstudio(){if(![".yy",".yyp"].includes(this.extname))return!1;if(this.lines.length<=3)return!1;const e=this.lines.slice(0,3).join("");return/^\s*[{[]/.test(e)||/^\d\.\d\.\d.+\|\{/.test(this.lines[0]||"")}generatedGimp(){if(![".c",".h"].includes(this.extname))return!1;if(0===this.lines.length)return!1;const e=this.lines[0]||"";return/^\/\* GIMP [a-zA-Z0-9- ]+ C-Source image dump \(.+?\.c\) \*\//.test(e)||/^\/\* {2}GIMP header image file format \([a-zA-Z0-9- ]+\): .+?\.h {2}\*\//.test(e)}generatedVisualstudio6(){return".dsp"===this.extname&&this.lines.slice(0,3).some((e=>e.includes("# Microsoft Developer Studio Generated Build File")))}generatedHaxe(){return!![".js",".py",".lua",".cpp",".h",".java",".cs",".php"].includes(this.extname)&&this.lines.slice(0,3).some((e=>e.includes("Generated by Haxe")))}generatedJooq(){return".java"===this.extname&&this.lines.slice(0,2).some((e=>e.includes("This file is generated by jOOQ.")))}generatedSorbetRbi(){return".rbi"===this.extname&&!(this.lines.length<5)&&/^# typed:/.test(this.lines[0]||"")&&(this.lines[2]||"").includes("DO NOT EDIT MANUALLY")&&/^# Please (run|instead update this file by running) `bin\/tapioca/.test(this.lines[4]||"")}generatedMysqlViewDefinitionFormat(){return".frm"===this.extname&&(this.lines[0]||"").includes("TYPE=VIEW")}}const KA=e=>{if(!e)return[];if("string"!=typeof e||e.match(/^\s+$/))return[];const t=e.split("\n");if(0===t.length)return[];const r=[];let n=null,o=null,s=0,i=0,a=null;const c=e=>{o?.changes.push({type:"normal",normal:!0,ln1:s++,ln2:i++,content:e}),a.oldLines--,a.newLines--},l=e=>{const[t,o]=XA(e)??[];n={chunks:[],deletions:0,additions:0,from:t,to:o},r.push(n)},u=()=>{n&&!n.chunks.length||l()},d=e=>+(e||1),h=e=>{o&&(o.changes.push({type:"del",del:!0,ln:s++,content:e}),n.deletions++,a.oldLines--)},p=e=>{o&&(o.changes.push({type:"add",add:!0,ln:i++,content:e}),n.additions++,a.newLines--)},f=e=>{if(!o)return;const[t]=o.changes.slice(-1);o.changes.push({type:t.type,[t.type]:!0,ln1:t.ln1,ln2:t.ln2,ln:t.ln,content:e})},m=[[/^diff\s/,l],[/^new file mode (\d+)$/,(e,t)=>{u(),n.new=!0,n.newMode=t[1],n.from="/dev/null"}],[/^deleted file mode (\d+)$/,(e,t)=>{u(),n.deleted=!0,n.oldMode=t[1],n.to="/dev/null"}],[/^old mode (\d+)$/,(e,t)=>{u(),n.oldMode=t[1]}],[/^new mode (\d+)$/,(e,t)=>{u(),n.newMode=t[1]}],[/^index\s[\da-zA-Z]+\.\.[\da-zA-Z]+(\s(\d+))?$/,(e,t)=>{u(),n.index=e.split(" ").slice(1),t[1]&&(n.oldMode=n.newMode=t[1].trim())}],[/^---\s/,e=>{u(),n.from=YA(e)}],[/^\+\+\+\s/,e=>{u(),n.to=YA(e)}],[/^@@\s+-(\d+),?(\d+)?\s+\+(\d+),?(\d+)?\s@@/,(e,t)=>{n||l(e);const[r,c,u,h]=t.slice(1);s=+r,i=+u,o={content:e,changes:[],oldStart:+r,oldLines:d(c),newStart:+u,newLines:d(h)},a={oldLines:d(c),newLines:d(h)},n.chunks.push(o)}],[/^\\ No newline at end of file$/,f]],g=[[/^\\ No newline at end of file$/,f],[/^-/,h],[/^\+/,p],[/^\s+/,c]],w=e=>{a?(e=>{const t=e.charCodeAt(0);if(43===t)p(e);else if(45===t)h(e);else if(32===t)c(e);else if(92===t&&/^\\ No newline at end of file$/.test(e))f(e);else for(const[t,r]of g){const n=e.match(t);if(n){r(e,n);break}}0===a.oldLines&&0===a.newLines&&(a=null)})(e):(e=>{for(const[t,r]of m){const n=e.match(t);if(n){r(e,n);break}}})(e)};for(const e of t)w(e);return r},JA=/(a|i|w|c|o|1|2)\/.*(?=["']? ["']?(b|i|w|c|o|1|2)\/)|(b|i|w|c|o|1|2)\/.*$/g,ZA=/^(a|b|i|w|c|o|1|2)\//,XA=e=>{const t=e?.match(JA);return t?.map((e=>e.replace(ZA,"").replace(/("|')$/,"")))},QA=/^\\?['"]|\\?['"]$/g,YA=e=>{let t=e$(e,"-+").trim();return t=r$(t),t.replace(QA,"").replace(ZA,"")},e$=(e,t)=>{if(e=o$(e),!t&&String.prototype.trimLeft)return e.trimLeft();const r=n$(t);return e.replace(new RegExp(`^${r}+`),"")},t$=/\t.*|\d{4}-\d\d-\d\d\s\d\d:\d\d:\d\d(.\d+)?\s(\+|-)\d\d\d\d/,r$=e=>{const t=t$.exec(e);return t&&(e=e.substring(0,t.index).trim()),e},n$=e=>null==e?"\\s":e instanceof RegExp?e.source:`[${o$(e).replace(/([.*+?^=!:${}()|[\]/\\])/g,"\\$1")}]`,o$=e=>`${e??""}`,s$=(0,d.h)("local-mercurial-diff"),i$=5242880,a$="0000000000000000000000000000000000000000";let c$,l$;async function u$(e,t,r={}){const n=await async function(){if(void 0===c$&&(c$=await async function(e){const t="win32"===process.platform?["hg.com","hg.exe"]:["hg"];for(const r of e.split(s.delimiter))if(s.isAbsolute(r))for(const e of t){const t=s.join(r,e);try{if(!(await xo.stat(t)).isFile())continue;return"win32"!==process.platform&&await xo.access(t,Ro.constants.X_OK),t}catch{}}}(process.env.PATH??"")??null),null===c$){const e=new Error("hg executable not found");throw e.code="ENOENT",e}return c$}(),o=await new Promise(((o,s)=>{const i=(0,iu.spawn)(n,t,{cwd:e,env:{...process.env,HGPLAIN:"+strictflags",HGRCPATH:"",HGRCSKIPREPO:"1"},shell:!1}),a=new ca.StringDecoder("utf8");let c="";i.stdout.on("data",(e=>{c+=a.write(e)})),i.stderr.on("data",(()=>{})),i.on("error",(e=>{!0===r.allowFailure?o(""):s(e)})),i.on("close",(e=>{if(0===e||!0===r.allowFailure)o(c+a.end());else{const r=t.find((e=>!e.startsWith("-")))??"hg";s(new Error(`MercurialDiffFailed: hg ${r} exited ${e??"unknown"}`))}}))}));return o}async function d$(e){const t=await async function(e){let t=s.resolve(e);for(;;){try{if((await xo.stat(s.join(t,".hg"))).isDirectory())return!0}catch{}const e=s.dirname(t);if(e===t)return!1;t=e}}(e);if(!t)return;const r=function(e,t){return e&&"absent"!==t?"skips-repo-config"!==t?"unsafe":"proceed":"not-mercurial"}(t,await async function(){if(void 0!==l$)return l$;const e=await xo.mkdtemp(s.join((0,o.tmpdir)(),"hg-probe-"));try{const t=await u$(e,["help","environment"]);l$=/\bHGRCSKIPREPO\b/.test(t)?"skips-repo-config":"reads-repo-config"}catch(e){l$=function(e){return"object"==typeof e&&null!==e&&"code"in e&&"ENOENT"===e.code}(e)?"absent":"reads-repo-config"}finally{await xo.rm(e,{recursive:!0,force:!0})}return l$}());if("not-mercurial"===r)return;if("unsafe"===r)throw new Error("MercurialClientUnsafe: hg would read repository config");let n;try{n=(await u$(e,["root"])).trim()}catch{return}if(0!==n.length)try{return(await xo.stat(s.join(n,".hg"))).isDirectory()?n:void 0}catch{return}}function h$(e,t){return"win32"===process.platform?s.win32.normalize(e).toLowerCase()===s.win32.normalize(t).toLowerCase():s.resolve(e)===s.resolve(t)}function p$(e,t){const r=s.relative(s.resolve(t),s.resolve(e));return 0===r.length||!s.isAbsolute(r)&&!r.split(s.sep).includes("..")}async function f$(e){const t=s.resolve(e);try{return await xo.realpath(t)}catch{return t}}function m$(e){if(0===e.length)return[];const t=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),r=t.split("\n");return t.endsWith("\n")&&r.pop(),r}function g$(e){if(e.includes("\0")||/[\r\n]/.test(e))throw new Error("MercurialDiffFailed: base ref contains a newline")}async function w$({repositoryRoot:e,rev:t,filePath:r}){const n=await async function({repositoryRoot:e,rev:t,filePath:r}){let n;try{n=await u$(e,["files","-r",t,"-T","{size}","--",r])}catch{return}const o=n.trim();if(!/^\d+$/.test(o))return;const s=Number(o);return Number.isFinite(s)?s:void 0}({repositoryRoot:e,rev:t,filePath:r});return void 0===n||n>i$?"":u$(e,["cat","-r",t,"--",r])}async function y$(e,t,r){const n=function(e){switch(e){case Ue.ek.NAME_STATUS:return Ue.ek.NAME_STATUS;case Ue.ek.NAME_STATUS_AND_NUMSTAT:return Ue.ek.NAME_STATUS_AND_NUMSTAT;case Ue.ek.FILE_DIFFS:return Ue.ek.FILE_DIFFS;case Ue.ek.DIFFS_WITH_BEFORE_AND_AFTER:return Ue.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return Ue.ek.FILE_DIFFS}}(r.outputFormat),o=["root"],i=(await u$(t,["root"])).trim();if(0===i.length)throw new Error("MercurialDiffFailed: hg root did not resolve");let a,c;if(0!==r.ref.length||"HEAD"!==r.baseRef&&(r.mergeBase||0!==r.baseRef.length)){if(r.mergeBase||0===r.baseRef.length)a=await async function({cwd:e,baseRef:t,commands:r}){if(t.length>0&&"HEAD"!==t){g$(t),r.push("log");const n=(await u$(e,["log","-r",`ancestor(., (${t}))`,"-T","{node}"])).trim();if(0===n.length||n===a$)throw new Error("MercurialDiffFailed: base ref did not resolve");return n}r.push("log");const n=(await u$(e,["log","-r","max(::. and public())","-T","{node}"],{allowFailure:!0})).trim();if(n.length>0&&n!==a$)return n;const o=(await u$(e,["log","-r","ancestor(., default)","-T","{node}"],{allowFailure:!0})).trim();if(o.length>0&&o!==a$)return o;const s=(await u$(e,["log","-r",".","-T","{node}"],{allowFailure:!0})).trim();return s.length>0?s:a$}({cwd:t,baseRef:r.baseRef,commands:o});else if(g$(r.baseRef),o.push("log"),a=(await u$(t,["log","-r",r.baseRef,"-T","{node}"])).trim(),0===a.length)throw new Error("MercurialDiffFailed: base ref did not resolve");r.ref.length>0&&(g$(r.ref),o.push("log"),c=(await u$(t,["log","-r",r.ref,"-T","{node}"])).trim())}const l=["diff","--git"];r.includeSpaceChanges||l.push("-b"),void 0!==r.unifiedContextLines&&l.push(`-U${r.unifiedContextLines}`),void 0!==a&&l.push("-r",a),void 0!==c&&l.push("-r",c),r.targetPaths.length>0&&l.push("--",...r.targetPaths),o.push("diff");const u=await u$(t,l),d=function(e){const t=e.replace(/\r\n/g,"\n");return new Ue.o$({diffs:KA(t).map((e=>function(e){const t=new Ue.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new Ue.Ei({content:e.content,lines:e.changes.map((e=>e.content)),oldStart:e.oldStart,oldLines:e.oldLines,newStart:e.newStart,newLines:e.newLines})))});return t.added=e.additions,t.removed=e.deletions,t}(e))),diffType:Ue.Wf.UNSPECIFIED})}(u);let h=[];if(r.maxUntrackedFiles>0&&(o.push("status"),h=await async function({cwd:e,repositoryRoot:t,maxUnknownFiles:r}){let n=(await u$(e,["status","-un0"])).split("\0").filter((e=>e.length>0));return n.length>r&&(n=n.slice(0,r)),(await Promise.all(n.map((async e=>{try{const r=s.join(t,e),n=await xo.stat(r);if(n.size>i$){const t=await async function(e){const t=(0,ko.createHash)("sha256"),r=await xo.open(e,"r");try{const e=Buffer.alloc(65536);let n=0;for(;;){const{bytesRead:o}=await r.read(e,0,e.length,n);if(0===o)break;t.update(e.subarray(0,o)),n+=o}}finally{await r.close()}return t.digest("hex")}(r);return{contents:"",path:e,omittedDueToSize:!0,byteSize:n.size,contentHash:t}}return{contents:await xo.readFile(r,"utf8"),path:e}}catch{return}})))).filter((e=>void 0!==e))}({cwd:t,repositoryRoot:i,maxUnknownFiles:r.maxUntrackedFiles}),d.diffs.push(...h.map((e=>function(e){if(!0===e.omittedDueToSize)return new Ue.QP({from:"/dev/null",to:e.path,chunks:[],added:0,removed:0});const t=m$(e.contents);if(0===t.length)return new Ue.QP({from:"/dev/null",to:e.path,chunks:[],added:0,removed:0});const r=t.length;return new Ue.QP({from:"/dev/null",to:e.path,chunks:[new Ue.Ei({content:`@@ -0,0 +1${1===r?"":`,${r}`} @@`,lines:t.map((e=>`+${e}`)),oldStart:0,oldLines:0,newStart:1,newLines:r})],added:r,removed:0})}(e))))),n!==Ue.ek.FILE_DIFFS)for(const e of d.diffs)e.chunks=[];if(n===Ue.ek.DIFFS_WITH_BEFORE_AND_AFTER){const e=a??".";await Promise.all(d.diffs.map((async t=>{if("/dev/null"!==t.from)try{t.beforeFileContents=await w$({repositoryRoot:i,rev:e,filePath:t.from})}catch{t.beforeFileContents=""}else t.beforeFileContents="";if("/dev/null"!==t.to)if(void 0===c)try{const e=s.join(i,t.to),r=await xo.stat(e);t.afterFileContents=r.size>i$?"":await xo.readFile(e,"utf8")}catch{t.afterFileContents=""}else try{t.afterFileContents=await w$({repositoryRoot:i,rev:c,filePath:t.to})}catch{t.afterFileContents=""}else t.afterFileContents=""})))}const p=[u,function(e){const t=[];for(const r of e){const e=m$(r.contents);if(t.push(`diff --git a/${r.path} b/${r.path}`),t.push("new file mode 100644"),t.push("--- /dev/null"),t.push(`+++ b/${r.path}`),0===e.length)continue;const n=e.length;t.push(`@@ -0,0 +1${1===n?"":`,${n}`} @@`),t.push(...e.map((e=>`+${e}`)))}return t.join("\n")}(h.filter((e=>!0!==e.omittedDueToSize))),h.filter((e=>!0===e.omittedDueToSize)).map((e=>`omitted-untracked ${e.byteSize??0} ${e.contentHash??""} ${JSON.stringify(e.path)}`)).join("\n")].filter((e=>e.length>0)).join("\n"),f=r.computePatchId?function(e){if(0!==e.length)return`hg:${(0,ko.createHash)("sha256").update(e).digest("hex")}`}(p.length>0?`${p}\n`:""):void 0;let m,g;if(!0===r.returnHeadSha){o.push("log","status");const e=(await u$(t,["log","-r",".","-T","{node}"],{allowFailure:!0})).trim();m=e.length>0?e:a$,g=(await u$(t,["status","-0"])).length>0}s$.info(e,"Local mercurial diff commands",{sourceControl:"mercurial",commands:o});const w=new Ue.df({diff:d,submoduleDiffs:[],patchId:f,headSha:m,hasUncommittedChanges:g}),y=r.maxResponseBytes??0;if(y>0){const t=w.toBinary().byteLength;if(t>y)throw s$.info(e,"Local diff outcome",{sourceControl:"mercurial",outcome:"too_large"}),new Error(`GetDiffResponseTooLarge: ${t} bytes exceeds the ${y} byte limit`)}return s$.info(e,"Local diff outcome",{sourceControl:"mercurial",outcome:"ok",fileCount:d.diffs.length,patchIdPrefixed:!0===f?.startsWith("hg:")}),w}const v$=(0,d.h)("local-git-diff");function b$({exitCode:e,stderr:t}){return new Error(`Git command failed with code ${e}: ${t}`)}async function S$(e,t,r={}){let n;try{n=await e(t)}catch(e){if(!0===r.ignoreErrors)return"";throw e}if(0!==n.exitCode&&!0!==r.ignoreErrors)throw b$(n);return!0===r.shouldNotTrimOutput?n.stdout:n.stdout.trim()}function k$(e){const t=KA(e);return new Ue.o$({diffs:t.map((e=>function(e){const t=new Ue.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new Ue.Ei({content:e.content,lines:e.changes.map((e=>e.content)),oldStart:e.oldStart,oldLines:e.oldLines,newStart:e.newStart,newLines:e.newLines})))});return t.added=e.additions,t.removed=e.deletions,t}(e))),diffType:Ue.Wf.UNSPECIFIED})}function _$(e){const t=[];for(const n of e){const e={body:`+${(r=n.contents).replaceAll("\n","\n+")}`,numLines:Xs(r)},o=1===e.numLines?"@@ -0,0 +1 @@":`@@ -0,0 +1,${e.numLines} @@`;t.push(`diff --git a/${n.path} b/${n.path}\n--- /dev/null\n+++ b/${n.path}\n${o}\n${e.body}`)}var r;return t.join("\n")}const C$=["main","master","develop"];async function E$(e,t){const r=s.join(e,t),n=await xo.lstat(r);if(n.isSymbolicLink())return{contents:await xo.readlink(r),path:t,isSymlink:!0};if(!n.isFile())throw new Error("Not a regular file or symlink");return{contents:await xo.readFile(r,"utf8"),path:t,isSymlink:!1}}async function x$(e,t,r){const n=ky(),o=(e,r)=>n.run(t,e,r),i=await async function(e,t){let r;try{const e=(await S$(t,["rev-parse","--show-toplevel"])).trim();e.length>0&&(r=e)}catch{}if(void 0!==r){const t=await async function({cwd:e,gitRoot:t}){const r=await f$(t);let n=await f$(e);if(h$(n,r))return;let o=!1;for(;p$(n,r)&&!h$(n,r);){try{if((await xo.stat(s.join(n,".hg"))).isDirectory()){o=!0;break}}catch{}const e=s.dirname(n);if(e===n)break;n=e}return o?d$(e):void 0}({cwd:e,gitRoot:r});return void 0!==t?"mercurial":"git"}return void 0===await d$(e)?"none":"mercurial"}(t,o);if(v$.info(e,"Local diff source control",{sourceControl:i}),"none"===i)throw v$.info(e,"Local diff outcome",{sourceControl:i,outcome:"no_version_control"}),new Error("NoVersionControl: no git or mercurial repository");if("mercurial"===i)return y$(e,t,r);const a=function(e){switch(e){case Ue.ek.NAME_STATUS:return Ue.ek.NAME_STATUS;case Ue.ek.NAME_STATUS_AND_NUMSTAT:return Ue.ek.NAME_STATUS_AND_NUMSTAT;case Ue.ek.FILE_DIFFS:return Ue.ek.FILE_DIFFS;case Ue.ek.DIFFS_WITH_BEFORE_AND_AFTER:return Ue.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return Ue.ek.FILE_DIFFS}}(r.outputFormat),c=await(async()=>{let e=r.baseRef.length>0?r.baseRef:await async function(e){try{const t=await S$(e,["symbolic-ref","--short","refs/remotes/origin/HEAD"]);if(t)return t.trim()}catch{}for(const t of C$){const r=`origin/${t}`;try{return await S$(e,["rev-parse","--verify",r]),r}catch{}}try{const t=(await S$(e,["branch","-r"])).split("\n").map((e=>e.trim())).find((e=>e.startsWith("origin/")));if(t)return t}catch{}try{const t=await S$(e,["config","--get","init.defaultBranch"]);if(t)return t.trim()}catch{}throw new Error("Could not determine default branch")}(o);if(r.mergeBase){const t=r.ref.length>0?r.ref:"HEAD";e=(await S$(o,["merge-base","--end-of-options",e,t])).trim()}return e})(),l=["diff","--no-color"];r.includeSpaceChanges||l.push("--ignore-space-change"),void 0!==r.unifiedContextLines&&l.push(`-U${r.unifiedContextLines}`);const u=["--end-of-options",c];r.ref.length>0&&u.push(r.ref),r.targetPaths.length>0&&u.push("--",...r.targetPaths);const d=await o([...l,...u]);let h,p;if(0===d.exitCode)h=d.stdout,p=k$(h);else{const t=b$(d);if(r.computePatchId||!await async function(e){return(await S$(e,["config","--get-regexp","^(extensions\\.partialclone|remote\\..+\\.promisor)$"],{ignoreErrors:!0})).split("\n").some((e=>/^(extensions\.partialclone \S|remote\..+\.promisor( (true|yes|on|1))?$)/i.test(e)))}(o))throw t;p=await async function(e,t){const r=(await S$(e,["diff","--name-status","--no-renames","-z",...t])).split("\0"),n=[];for(let e=1;e{throw t})),v$.info(e,"Local diff outcome",{sourceControl:i,outcome:"partial_clone_names_only"})}let f=[];if(r.maxUntrackedFiles>0){f=await async function(e,t,r){let n=(await S$(t,["ls-files","--others","--exclude-standard"])).split("\n").map((e=>e.trim())).filter((e=>e.length>0));return n.length>r&&(n=n.slice(0,r)),(await Promise.all(n.map((async t=>{try{return await E$(e,t)}catch{return}})))).filter((e=>void 0!==e))}(t,o,r.maxUntrackedFiles);for(const e of f){const t=e.isSymlink?`${_$([e])}\n\\ No newline at end of file`:await S$(o,["diff","--no-color","--no-index","--","/dev/null",e.path],{ignoreErrors:!0,shouldNotTrimOutput:!0});p.diffs.push(...k$(t).diffs)}}if(a!==Ue.ek.FILE_DIFFS||!0===p.fileContentsOmitted)for(const e of p.diffs)e.chunks=[];if(a===Ue.ek.DIFFS_WITH_BEFORE_AND_AFTER&&!0!==p.fileContentsOmitted){const n=r.ref.length>0?r.ref:"HEAD";await Promise.all(p.diffs.map((async s=>{try{if("/dev/null"!==s.from)try{s.beforeFileContents=await S$(o,["show","--end-of-options",`${c}:${s.from}`],{shouldNotTrimOutput:!0})}catch{s.beforeFileContents=""}else s.beforeFileContents="";if("/dev/null"!==s.to)if(r.ref.length>0)try{s.afterFileContents=await S$(o,["show","--end-of-options",`${n}:${s.to}`],{shouldNotTrimOutput:!0})}catch{s.afterFileContents=""}else try{s.afterFileContents=(await E$(t,s.to)).contents}catch{try{s.afterFileContents=await S$(o,["show","--end-of-options",`${n}:${s.to}`],{shouldNotTrimOutput:!0})}catch{s.afterFileContents=""}}else s.afterFileContents=""}catch(t){v$.error(e,"Error fetching file contents for diff",t)}})))}const m=new Map;for(const e of p.diffs){const t="/dev/null"!==e.to?e.to:e.from;t&&m.set(t,e)}const g=[...m.keys()],w=r.ref.length>0?r.ref:"HEAD";try{const e=await GA({repoRoot:t,filePaths:g,getContent:async e=>{const t=m.get(e);if(t){if(void 0!==t.afterFileContents)return t.afterFileContents;try{if(t.to&&"/dev/null"!==t.to)return await S$(o,["show","--end-of-options",`${w}:${t.to}`],{shouldNotTrimOutput:!0})}catch{}}}});for(const[t,r]of e){const e=m.get(t);e&&(e.isGenerated=r.isGenerated)}}catch(t){v$.warn(e,"Generated-file detection failed; continuing without it",{error:t instanceof Error?t.message:String(t)})}const y=r.computePatchId&&void 0!==h?await async function(e,t){if(0===t.length)return;const{exitCode:r,stdout:n,stderr:o}=await e(["patch-id","--stable"],{input:t});if(0!==r)throw new Error(`git patch-id failed with code ${r}: ${o}`);return n.trim().split(/\s+/)[0]||void 0}(o,function(...e){const t=e.filter((e=>e.length>0));return 0===t.length?"":`${t.join("\n")}\n`}(h,_$(f))):void 0,v=!0===r.returnHeadSha?(await S$(o,["rev-parse","HEAD"])).trim():void 0,b=!0===r.returnHeadSha?(await S$(o,["status","--porcelain=v1","--untracked-files=all"])).trim().length>0:void 0,S=new Ue.df({diff:p,submoduleDiffs:[],patchId:y,headSha:v,hasUncommittedChanges:b}),k=r.maxResponseBytes??0;if(k>0){const e=S.toBinary().byteLength;if(e>k)throw new Error(`GetDiffResponseTooLarge: ${e} bytes exceeds the ${k} byte limit`)}return S}class P${async execute(e,t){return x$(e,t.cwd,t)}}var R$=r("../proto/dist/generated/agent/v1/mcp_allowlist_precheck_exec_pb.js");class I${constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isMcpFullyAllowlisted(e,{providerIdentifier:t.providerIdentifier,toolName:t.toolName,annotationsJson:t.annotationsJson});return new R$.M({allowlisted:r})}}var T$=r("../proto/dist/generated/agent/v1/record_screen_exec_pb.js"),A$=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function $$(e){return null!==e.exitCode||null!==e.signalCode||e.killed}function M$(e,t){return"object"==typeof e&&null!==e&&"code"in e&&e.code===t}function D$(e){return e instanceof Error?e.message:String(e)}function O$(e,t){return new T$.Tj({result:{case:"failure",value:new T$.yH({error:t,kind:e})}})}function F$(e){return e instanceof Error?e.message.startsWith("Failed to load polished-renderer native binding")?"binding_load_failed":"code"in e&&"string"==typeof e.code?e.code:e.name:typeof e}function N$(e,t,r,n){const o=[],s=function(e,t){const r=e.ffmpegExitCode??e.childProcess.exitCode,n=e.ffmpegExitSignal??e.childProcess.signalCode;if(e.ffmpegDiedEarly||null!==e.ffmpegDiedTime||null!==r||null!==n)return`ffmpeg exited code=${r} signal=${n}${null!==e.ffmpegDiedTime?` ${Math.max(0,Math.round((t-e.ffmpegDiedTime)/1e3))}s before SAVE`:""}`}(t,n);return void 0!==s&&o.push(s),void 0!==r&&o.push(`stop failed: ${D$(r)}`),o.length>0?`${e} (${o.join("; ")})`:e}const L$=(0,Vs.promisify)(iu.execFile);class j${constructor(e){if(this.activeRecording=null,this.inFlightSaves=[],this.onRecordingStartedCallback=null,this.onRecordingStoppedCallback=null,this.recordingStoppedCallbackInvoked=!1,this.artifactsDir=e.artifactsDir,this.stagingDir=e.stagingDir??"/opt/cursor/recording-staging/",this.display=e.display,this.disablePolishedRendering=e.disablePolishedRendering??!1,this.polishedRenderer=e.polishedRenderer,!this.disablePolishedRendering){if(!this.polishedRenderer)throw new Error("record_screen requires a polished recording renderer when polished rendering is enabled. This tool should run via exec-daemon where that dependency is bundled.");this.polishedRenderer.assertAvailable()}}setOnRecordingStarted(e){this.onRecordingStartedCallback=e}setOnRecordingStopped(e){this.onRecordingStoppedCallback=e}invokeStoppedCallbackOnce(){!this.recordingStoppedCallbackInvoked&&this.onRecordingStoppedCallback&&(this.recordingStoppedCallbackInvoked=!0,this.onRecordingStoppedCallback())}async cleanupRecording(e){try{await(e.inputEventLogger?.stop())}catch{}if(!$$(e.childProcess)&&e.childProcess.pid)try{await this.stopFfmpegRecording(e)}catch{try{process.kill(e.childProcess.pid,"SIGKILL")}catch{}}}getActiveInputEventLogger(){return this.activeRecording?.inputEventLogger??null}async dispose(){const e=this.inFlightSaves.map((e=>e.promise));if(e.length>0)try{await(0,Nr.wj)(Promise.all(e),j$.IN_FLIGHT_SAVE_DISPOSE_TIMEOUT_MS,"Timed out waiting for in-flight recording save")}catch{}if(this.activeRecording){await this.cleanupRecording(this.activeRecording),this.invokeStoppedCallbackOnce();try{await xo.rm(this.activeRecording.sessionDir,{force:!0,recursive:!0})}catch{}this.activeRecording=null}}findInFlightSave(e){return this.inFlightSaves.find((t=>t.state===e))}clearActiveRecordingIfCurrent(e){this.activeRecording===e&&(this.activeRecording=null)}invokeStoppedCallbackIfCurrent(e){this.activeRecording===e&&this.invokeStoppedCallbackOnce()}sanitizeToolCallId(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}async ensureRecordingDirectoryExists(){await xo.mkdir(this.stagingDir,{recursive:!0}),await xo.mkdir(this.artifactsDir,{recursive:!0})}buildSessionDir(e){const t=this.sanitizeToolCallId(e),r=`session-${(new Date).toISOString().replace(/[:.]/g,"-")}-${t}`;return s.join(this.stagingDir,r)}validateAndNormalizeSaveAsFilename(e){let t=e.trim();return t.startsWith(this.artifactsDir)&&(t=t.slice(this.artifactsDir.length),t.startsWith("/")&&(t=t.slice(1))),t=t.trim(),0===t.length?{success:!1,reason:T$.y.UNSPECIFIED}:t.includes("/")||t.includes("\\")?{success:!1,reason:T$.y.SLASHES_NOT_ALLOWED}:(t=t.replace(/[^a-zA-Z0-9 ._-]/g,"_"),t=t.trim(),0===t.length?{success:!1,reason:T$.y.UNSPECIFIED}:(t.length>128&&(t=t.slice(0,128).trim()),t.toLowerCase().endsWith(".mp4")||(t=`${t}.mp4`),{success:!0,filename:t}))}async movePolishedVideo(e,t){try{return void await xo.rename(e,t)}catch(e){if(!M$(e,"EXDEV"))throw e}try{await xo.copyFile(e,t)}catch(e){throw await xo.rm(t,{force:!0}).catch((()=>{})),e}try{await xo.unlink(e)}catch(e){throw await xo.rm(t,{force:!0}).catch((()=>{})),e}}async getUniqueArtifactVideoPath(e){const t=s.parse(e),r=t.name||"recording",n=t.ext||".mp4";let o=`${r}${n}`,i=2;for(;;){const e=s.join(this.artifactsDir,o);try{const t=await xo.open(e,"wx");return await t.close(),e}catch(e){if(!M$(e,"EEXIST"))throw e;o=`${r}-${i}${n}`,i++}}}async resolveArtifactVideoPath(e){const{saveAsFilename:t,stagingSessionDir:r}=e;let n,o;if(t){const e=this.validateAndNormalizeSaveAsFilename(t);e.success?o=e.filename:(n=e.reason,o=`${s.basename(r)}.mp4`)}else o=`${s.basename(r)}.mp4`;return{finalVideoPath:await this.getUniqueArtifactVideoPath(o),requestedFilePathRejectedReason:n}}async getVideoDurationMs(e){const{stdout:t}=await(0,au.D9)(L$,"ffprobe",["-v","error","-show_entries","format=duration","-of","default=noprint_wrappers=1:nokey=1",e],{encoding:"utf8"}),r=parseFloat(t.trim());if(!Number.isFinite(r)||r<0)throw new Error(`Invalid video duration from ffprobe: ${t.trim()}`);return Math.floor(1e3*r)}async getVideoDimensions(e){const{stdout:t}=await(0,au.D9)(L$,"ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=width,height","-of","csv=p=0:s=x",e],{encoding:"utf8"}),[r,n]=t.trim().split("x"),o=Number.parseInt(r,10),s=Number.parseInt(n,10);if(!Number.isFinite(o)||!Number.isFinite(s))throw new Error(`Invalid video dimensions from ffprobe: ${t.trim()}`);if(o<=0||s<=0)throw new Error(`Invalid non-positive video dimensions from ffprobe: ${t.trim()}`);return{width:o,height:s}}async renderPolished(e,t){const r=s.join(t,"recording"),n=s.join(r,"recording_full.mp4");try{await this.polishedRenderer.renderRecordingSession({stagingSessionDir:t,outputVideoPath:n,fps:j$.PROXY_TARGET_FPS,includeBrandTag:!0}),await xo.access(n,xo.constants.R_OK)}catch(t){const r=(0,D.fU)(e);throw r?.setAttribute("error.type",F$(t)),r?.setStatus({code:2}),t}return n}async getVideoFramerate(e){try{const{stdout:t}=await(0,au.D9)(L$,"ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=r_frame_rate","-of","default=noprint_wrappers=1:nokey=1",e],{encoding:"utf8"}),r=t.trim();if(r.includes("/")){const[e,t]=r.split("/"),n=Number.parseFloat(e),o=Number.parseFloat(t);if(Number.isFinite(n)&&Number.isFinite(o)&&0!==o){const e=n/o;if(e>0&&e<500)return Math.round(e)}}else{const e=Number.parseFloat(r);if(Number.isFinite(e)&&e>0&&e<500)return Math.round(e)}console.warn(`[record-screen] Unexpected ffprobe r_frame_rate output "${r}", defaulting to ${j$.PROXY_TARGET_FPS}fps`)}catch(e){console.warn(`[record-screen] Failed to read video framerate: ${e instanceof Error?e.message:String(e)}, defaulting to ${j$.PROXY_TARGET_FPS}fps`)}return j$.PROXY_TARGET_FPS}async startFfmpegRecording(e,t){const r=s.join(t,"recording");await xo.mkdir(r,{recursive:!0});const n=s.join(r,"recording_render_proxy_1080p.mp4"),o="windowsDesktop"===e.kind?["-f","gdigrab","-i","desktop"]:["-video_size",e.resolution,"-framerate",String(await this.detectRefreshRate(e.display)),"-draw_mouse","0","-f","x11grab","-i",e.display],i=["-vf",`scale=${j$.PROXY_TARGET_WIDTH}:-2:flags=lanczos,fps=${j$.PROXY_TARGET_FPS}`,"-c:v","libx264","-preset",j$.PROXY_PRESET,"-crf",String(j$.PROXY_CRF),"-pix_fmt","yuv420p","-profile:v","high","-x264-params","keyint=1:min-keyint=1:scenecut=0:bframes=0","-movflags","+faststart","-tune","fastdecode"],a=["-vf",`scale=${j$.PROXY_TARGET_WIDTH}:-2:flags=lanczos`,"-c:v","libx264","-preset",j$.PROXY_PRESET,"-pix_fmt","yuv420p","-movflags","+faststart"],c=this.disablePolishedRendering?a:i,l=(0,au.D9)(iu.spawn,"ffmpeg",[...o,...c,"-y",n],{stdio:["win32"===process.platform?"pipe":"ignore","pipe","pipe"],detached:"win32"!==process.platform,windowsHide:!0}),u=new Promise(((e,t)=>{let r="",n=!1;l.stderr?.on("data",(t=>{r+=t.toString(),!n&&r.includes("frame=")&&(n=!0,e(Date.now()))}));const o=setTimeout((()=>{n||t(new Error("ffmpeg did not start encoding within 5 seconds"))}),5e3);l.once("exit",((e,r)=>{clearTimeout(o),n||t(new Error(`ffmpeg exited before starting: code=${e} signal=${r}`))})),l.once("error",(e=>{clearTimeout(o),n||t(new Error(`ffmpeg failed to start: ${e.message}`))}))}));return await new Promise(((e,t)=>{const r=setTimeout(e,300);l.once("error",(e=>{clearTimeout(r),t(new Error(`Failed to start ffmpeg: ${e.message}`))})),l.once("exit",((e,n)=>{clearTimeout(r),t(null!==e&&0!==e?new Error(`ffmpeg exited with code ${e}`):null!==n?new Error(`ffmpeg killed by signal ${n}`):new Error("ffmpeg exited unexpectedly during startup"))}))})),{process:l,videoStartedPromise:u}}async detectRefreshRate(e){try{return(await qg(e)).display.refreshRate}catch(e){return console.warn(`[record-screen] Failed to detect refresh rate: ${e instanceof Error?e.message:String(e)}, using default ${j$.DEFAULT_REFRESH_RATE}Hz`),j$.DEFAULT_REFRESH_RATE}}async runFfmpegCommand(e,t){return await new Promise(((r,n)=>{const o=(0,au.D9)(iu.spawn,"ffmpeg",t,{stdio:["ignore","ignore","pipe"]});let s="";o.stderr?.on("data",(e=>{s.length<2e4&&(s+=e.toString())})),o.once("error",(t=>{n(new Error(`ffmpeg ${e} failed to start: ${t instanceof Error?t.message:String(t)}`))})),o.once("close",(t=>{0===t?r():n(new Error(`ffmpeg ${e} exited with code ${t}: ${s.trim()}`))}))}))}async saveRecordingDataPackage(e){const{sessionDir:t,durationMs:r,recordingStartEpochMs:n,ffmpegStartedEpochMs:o,inputEvents:i,resolution:a,renderProxies:c}=e,l=s.join(t,"recording"),u=s.join(l,"recording-data.json"),d=o-n,h=i.map((e=>({executionTimestampMs:e.executionTimestampMs,commandDurationMs:e.commandDurationMs,positionBefore:e.positionBefore,positionAfter:e.positionAfter,cursorTypeAfter:e.cursorTypeAfter,action:{action:this.serializeAction(e.action)}}))),p={version:3,durationMs:r,recordingStartEpochMs:n,ffmpegStartedEpochMs:o,eventToVideoOffsetMs:d,displayWidth:a.display.width,displayHeight:a.display.height,apiWidth:a.api.width,apiHeight:a.api.height,inputEvents:h,renderProxies:c??null};await xo.writeFile(u,JSON.stringify(p,null,2))}serializeAction(e){const{action:t}=e,r={case:t.case};switch(t.case){case"click":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null,button:t.value.button,count:t.value.count,modifierKeys:t.value.modifierKeys};break;case"mouseMove":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null};break;case"type":r.value={text:t.value.text};break;case"key":r.value={key:t.value.key,holdDurationMs:t.value.holdDurationMs};break;case"scroll":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null,direction:t.value.direction,amount:t.value.amount,modifierKeys:t.value.modifierKeys};break;case"drag":r.value={path:t.value.path.map((e=>({x:e.x,y:e.y}))),button:t.value.button};break;case"wait":r.value={durationMs:t.value.durationMs};break;case"screenshot":case"cursorPosition":case"mouseDown":case"mouseUp":r.value=t.value;break;default:r.value={}}return r}async stopFfmpegRecording(e){const{childProcess:t}=e;if($$(t)||!t.pid)return;const r=t.pid;return new Promise(((e,n)=>{const o=setTimeout((()=>{try{try{process.kill(-r,"SIGKILL")}catch{process.kill(r,"SIGKILL")}}catch{}n(new Error("Timeout waiting for ffmpeg to stop"))}),2e4);t.once("exit",(()=>{clearTimeout(o),e()})),t.once("error",(e=>{clearTimeout(o),n(new Error(`Error stopping ffmpeg: ${e.message}`))}));try{if(t.stdin)return t.stdin.on("error",(()=>{})),void t.stdin.end("q");try{process.kill(-r,"SIGTERM")}catch{process.kill(r,"SIGTERM")}}catch(t){if(clearTimeout(o),M$(t,"ESRCH"))return void e();n(new Error(`Failed to send SIGTERM: ${t instanceof Error?t.message:String(t)}`))}}))}async performSave(e,t,r){const n=Date.now();let o=T$.Wg.INTERNAL;try{const i=await(r.inputEventLogger?.stop())??[],a=r.inputEventLogger?.getRecordingStartTime()??r.startTime;let c;this.invokeStoppedCallbackIfCurrent(r);try{!$$(r.childProcess)&&r.childProcess.pid&&await this.stopFfmpegRecording(r)}catch(e){c=e,console.warn(`[record-screen] Failed to stop ffmpeg: ${D$(e)}`)}const l=r.ffmpegStartedEpochMs??a,u=r.sessionDir,d=s.join(u,"recording"),h=s.join(d,"recording_render_proxy_1080p.mp4");let p,f,m;try{await xo.access(h,xo.constants.R_OK)}catch(e){await this.cleanupRecording(r),this.clearActiveRecordingIfCurrent(r);const t=M$(e,"ENOENT"),o=t?`Recording proxy not found at ${h}`:`Recording proxy at ${h} could not be validated: ${D$(e)}`;return O$(t?T$.Wg.PROXY_MISSING:T$.Wg.STAGING_IO,N$(o,r,c,n))}try{if([p,f,m]=await Promise.all([this.getVideoDurationMs(h),this.getVideoDimensions(h),this.getVideoFramerate(h)]),p<=0)throw new Error(`Recording proxy has zero duration at ${h}`)}catch(e){await this.cleanupRecording(r);const t=D$(e),o=t.includes(h)?t:`Recording proxy at ${h} could not be validated: ${t}`;return O$(T$.Wg.PROXY_INVALID,N$(o,r,c,n))}const g={profileVersion:j$.PROXY_PROFILE_VERSION,generatedAtEpochMs:Date.now(),source:{width:f.width,height:f.height,durationMs:p,fps:m},artifacts:[{name:"render_proxy_1080p",path:"recording_render_proxy_1080p.mp4",width:f.width,height:f.height,fps:j$.PROXY_TARGET_FPS,codec:"h264",profile:j$.PROXY_PROFILE_VERSION,keyint:1,status:"success",elapsedMs:0}]};o=T$.Wg.STAGING_IO,void 0!==r.resolution&&await this.saveRecordingDataPackage({sessionDir:u,durationMs:p,recordingStartEpochMs:a,ffmpegStartedEpochMs:l,inputEvents:i,resolution:r.resolution,renderProxies:g}),o=T$.Wg.ARTIFACT_WRITE_FAILED;const{finalVideoPath:w,requestedFilePathRejectedReason:y}=await this.resolveArtifactVideoPath({saveAsFilename:t.saveAsFilename,stagingSessionDir:u});try{if(this.disablePolishedRendering)await xo.copyFile(h,w);else{o=T$.Wg.RENDER_FAILED;const t=await this.renderPolished(e,u);o=T$.Wg.ARTIFACT_WRITE_FAILED,await this.movePolishedVideo(t,w)}}catch(e){throw await xo.rm(w,{force:!0}).catch((()=>{})),e}try{await xo.rm(u,{force:!0,recursive:!0})}catch(e){console.warn(`[record-screen] Failed to remove staging session ${u}: ${D$(e)}`)}return this.clearActiveRecordingIfCurrent(r),new T$.Tj({result:{case:"saveSuccess",value:new T$.ol({path:w,recordingDurationMs:ve.protoInt64.parse(p.toString()),requestedFilePathRejectedReason:y})}})}catch(e){return await this.cleanupRecording(r),this.invokeStoppedCallbackIfCurrent(r),O$("binding_load_failed"===F$(e)?T$.Wg.RENDERER_UNAVAILABLE:o,D$(e))}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,D.VI)(e.withName("LocalRecordScreenExecutor.execute")),!1);try{await this.ensureRecordingDirectoryExists()}catch(e){return O$(T$.Wg.STAGING_IO,`Failed to create recording directory: ${e instanceof Error?e.message:String(e)}. Ensure the parent directory exists and has write permissions, or run: sudo mkdir -p ${this.stagingDir} ${this.artifactsDir} && sudo chmod 777 ${this.stagingDir} ${this.artifactsDir}`)}if(t.mode===T$.$u.UNSPECIFIED)return O$(T$.Wg.INVALID_MODE,"Mode must be one of START_RECORDING, SAVE_RECORDING, DISCARD_RECORDING");switch(t.mode){case T$.$u.START_RECORDING:{this.recordingStoppedCallbackInvoked=!1;let e=!1;if(this.activeRecording){const t=this.activeRecording;if(!this.inFlightSaves.some((e=>e.state===t))){e=!0;try{await this.cleanupRecording(t),await xo.rm(t.sessionDir,{force:!0,recursive:!0}).catch((()=>{}))}catch{}}this.activeRecording=null}let r,n=null,o=null,s=T$.Wg.STAGING_IO;try{o=this.buildSessionDir(t.toolCallId||"recording"),await xo.mkdir(o,{recursive:!0}),s=T$.Wg.DISPLAY_UNAVAILABLE;const i="win32"===process.platform?void 0:await qg(this.display),a=void 0===i?{kind:"windowsDesktop"}:{kind:"x11",display:this.display,resolution:i.resolutionString};s=T$.Wg.FFMPEG_START_FAILED;const{process:c,videoStartedPromise:l}=await this.startFfmpegRecording(a,o);n=c;const u=this.disablePolishedRendering?void 0:i?.resolution;void 0!==u&&(s=T$.Wg.INTERNAL,r=new Yg({displayNum:Wg(this.display),resolution:u}),await r.start());const d=r?.getRecordingStartTime()??Date.now();let h;s=T$.Wg.FFMPEG_START_FAILED;try{h=await l}catch(e){throw new Error(`ffmpeg failed to start encoding: ${e instanceof Error?e.message:String(e)}`)}const p={childProcess:n,sessionDir:o,startTime:d,inputEventLogger:r,resolution:u,ffmpegStartedEpochMs:h,ffmpegDiedEarly:!1,ffmpegDiedTime:null,ffmpegExitCode:null,ffmpegExitSignal:null};this.activeRecording=p,this.onRecordingStartedCallback&&r&&this.onRecordingStartedCallback(r),n.once("exit",((e,t)=>{p.ffmpegDiedEarly=!0,p.ffmpegDiedTime=Date.now(),p.ffmpegExitCode=e,p.ffmpegExitSignal=t}));const f=!!t.saveAsFilename;return new T$.Tj({result:{case:"startSuccess",value:new T$.T4({wasPriorRecordingCancelled:e,wasSaveAsFilenameIgnored:f})}})}catch(e){if(r)try{await r.stop()}catch{}if(n&&!n.killed&&n.pid)try{process.kill(n.pid,"SIGKILL")}catch{}return o&&await xo.rm(o,{force:!0,recursive:!0}).catch((()=>{})),this.activeRecording=null,O$(s,D$(e))}}case T$.$u.SAVE_RECORDING:{if(!this.activeRecording)return 1===this.inFlightSaves.length?await this.inFlightSaves[0].promise:O$(T$.Wg.NO_ACTIVE_RECORDING,"No active recording to save");const e=this.activeRecording,r=this.findInFlightSave(e);if(r)return await r.promise;const o=Promise.resolve().then((()=>this.performSave(n.ctx,t,e))),s={state:e,promise:o};this.inFlightSaves.push(s);try{return await o}finally{this.inFlightSaves=this.inFlightSaves.filter((e=>e!==s))}}case T$.$u.DISCARD_RECORDING:{if(!this.activeRecording)return O$(T$.Wg.NO_ACTIVE_RECORDING,"No active recording to discard");const e=this.activeRecording;if(this.findInFlightSave(e))return O$(T$.Wg.SAVE_IN_PROGRESS,"Save in progress for this recording; wait for it or start a new recording");let t=T$.Wg.INTERNAL;try{return await(e.inputEventLogger?.stop()),this.invokeStoppedCallbackOnce(),!$$(e.childProcess)&&e.childProcess.pid&&(t=T$.Wg.FFMPEG_STOP_FAILED,await this.stopFfmpegRecording(e)),t=T$.Wg.STAGING_IO,await xo.rm(e.sessionDir,{force:!0,recursive:!0}),this.activeRecording=null,new T$.Tj({result:{case:"discardSuccess",value:new T$.N8}})}catch(r){await this.cleanupRecording(e),this.invokeStoppedCallbackOnce();const n=e.sessionDir;let o=!1;try{await xo.rm(n,{force:!0,recursive:!0}),o=!0}catch{}this.activeRecording=null;return O$(t,`Failed to discard recording: ${r instanceof Error?r.message:String(r)}${o?"":`. Session may remain at: ${n}`}`)}}default:{const e=t.mode;return O$(T$.Wg.INVALID_MODE,`Unhandled recording mode: ${String(e)}`)}}}catch(e){r.error=e,r.hasError=!0}finally{A$(r)}}}async function U$(e){const t=await(0,xo.readdir)(e,{withFileTypes:!0}).catch((()=>[])),r=[];for(const n of t){const t=s.join(e,n.name),o={name:n.name,path:t,isDirectory:n.isDirectory()};n.isDirectory()&&(o.children=await U$(t)),r.push(o)}return r.sort(((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)))}function B$(e,t="",r=!0){const n=[`${t}${r?"└── ":"├── "}${e.isDirectory?`${e.name}/`:e.name}`],o=e.children;if(o?.length){const e=t+(r?" ":"│ ");o.forEach(((t,r)=>{const s=r===o.length-1;n.push(...B$(t,e,s))}))}return n}async function W$(e){if(!await(0,xo.access)(e,xo.constants.R_OK).then((()=>!0),(()=>!1)))return"(No notes directory yet - will be created when you write your first note)";const t=await U$(e);return 0===t.length?"(Notes directory is empty)":t.flatMap(((e,r)=>B$(e,"",r===t.length-1))).join("\n")}async function H$(e,t){return W$(s.join(e,"agent-notes",t))}async function q$(e){return W$(s.join(e,"agent-notes","shared"))}j$.IN_FLIGHT_SAVE_DISPOSE_TIMEOUT_MS=3e4,j$.PROXY_TARGET_WIDTH=1920,j$.PROXY_TARGET_FPS=60,j$.PROXY_CRF=17,j$.PROXY_PRESET="veryfast",j$.PROXY_PROFILE_VERSION="render-proxy-h264-all-i-v1",j$.DEFAULT_REFRESH_RATE=60;var z$=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},G$=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const V$=3e3,K$=(0,d.h)("local-exec:request-context"),J$=Symbol("sectionLoadTimedOut");function Z$(e,t){if(void 0===t)return e;let r;const n=new Promise((e=>{r=setTimeout((()=>e(J$)),t)}));return e.catch((()=>{})),Promise.race([e,n]).finally((()=>{clearTimeout(r)}))}class X${async read(e,t){const r=this.inFlight??this.begin(e),n=this.last;if(void 0===n)return r;const o=await Z$(r,t).catch((()=>J$));return o===J$?n.value:o}prefetch(e){void 0===this.inFlight&&this.begin(e).catch((()=>{}))}begin(e){const t=e();this.inFlight=t;const r=()=>{this.inFlight===t&&(this.inFlight=void 0)};return t.then((e=>{this.last={value:e},r()}),r),t}}async function Q$(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{z$(o,(0,D.VI)(e.withName("LocalRequestContextExecutor.getGitStatusForRepoPath")),!1);try{return(await t.exec(e,r,["--no-optional-locks","status","--short","--branch"],{timeout:n,caller:"getGitStatusForRepoPath"})).stdout}catch{return}}catch(e){o.error=e,o.hasError=!0}finally{G$(o)}}async function Y$(e,t,r,n){try{const o=(await t.exec(e,r,["rev-parse","--abbrev-ref","HEAD"],{timeout:n,caller:"getGitBranchForRepoPath"})).stdout.trim();if("HEAD"===o||0===o.length)return;return o}catch{return}}async function eM(e,t,r,n){const o=e=>{let t;const r=new Promise((e=>{t=setTimeout((()=>{e(void 0)}),n)}));return Promise.race([e.catch((()=>{})),r]).finally((()=>{void 0!==t&&clearTimeout(t)}))},[s,i]=await Promise.all([o(Q$(e,t,r,n)),o(Y$(e,t,r,n))]);return{status:s,branchName:i}}async function tM(e,t,r={}){const{projectDir:n,notesSessionId:s,agentNotesEnabled:i,reportProcessWorkingDirectory:a,getSmartModeClassifierAutoModeEnabled:c,devForceNextSmartModeClassifierBlockToken:l,isWorkingDirHomeDir:u,getSandboxEnabled:d,getSandboxSupported:h,getNetworkAllowlistInfo:p,userTerminalHint:f,artifactsFolder:m,secretRedactionEnabled:g,getComputerUseSupported:w,getComputerUseDesktop:y,getMockPromptTime:v}=r,b=y?.(),S=`${o.platform()} ${o.release()}`,k=(0,No.G6)(f),_=v?.(),C=(()=>{try{return(new Intl.DateTimeFormat).resolvedOptions().timeZone??void 0}catch{return}})(),E=n,x=n?`${n}/terminals`:void 0,P=n&&!1!==i?`${n}/agent-notes/shared`:void 0,R=n&&s&&!1!==i?`${n}/agent-notes/${s}`:void 0,I=n?`${n}/agent-transcripts`:void 0,T=!!d&&d(),A=h?.(),$=c?.();let M;if(p)try{const e=await Z$(p(),3e3);e!==J$&&(M=e)}catch{M=void 0}return new Fr.GE({osVersion:S,workspacePaths:t,shell:k,sandboxEnabled:T,projectFolder:E,terminalsFolder:x,agentSharedNotesFolder:P,agentConversationNotesFolder:R,agentTranscriptsFolder:I,timeZone:C,...!1!==a&&{processWorkingDirectory:process.cwd()},artifactsFolder:m,...void 0!==$&&{smartModeClassifierAutoModeEnabled:$},...void 0!==l&&{devForceNextSmartModeClassifierBlockToken:l},...void 0!==_&&{devMockPromptTime:ve.Timestamp.fromDate(_)},...void 0!==g&&{secretRedactionEnabled:g},...void 0!==A&&{sandboxSupported:A},...void 0!==M?.hasDefaults&&{sandboxNetworkHasDefaults:M.hasDefaults},...M?.explicitEntries&&M.explicitEntries.length>0&&{sandboxNetworkExplicitAllowlist:M.explicitEntries},...void 0!==w&&{computerUseSupported:w()},...void 0!==b&&{computerUseDesktop:b},...void 0!==u&&{isWorkingDirHomeDir:u}})}const rM={type:"object",properties:{},additionalProperties:!1};function nM(e,t){return{tools:(!0===t?.internalBrowserProvidersOnly?e.servers.filter((e=>Zn.has(e.serverIdentifier))):e.servers).flatMap((e=>e.tools)).map((e=>new vn.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,...!0===t?.inputSchemaJson?{inputSchemaJson:void 0===e.inputSchema?void 0:JSON.stringify(e.inputSchema)}:{inputSchema:e.inputSchema?ve.Value.fromJson(e.inputSchema):void 0}}))),mcpInstructions:e.servers.flatMap((e=>e.instructions))}}function oM(e,t){const r=!0===t?.slimDescriptors,n=e.servers.map((e=>{const n=e.instructions.map((e=>e.instructions)).filter(Boolean).join("\n"),o=e.tools.map((e=>new vn.E$({toolName:e.toolName,...Nb(e.annotations),...r?{}:{description:e.description,...!0===t?.inputSchemaJson?{inputSchemaJson:void 0===e.inputSchema?void 0:JSON.stringify(e.inputSchema)}:{inputSchema:void 0!==e.inputSchema?ve.Value.fromJson(e.inputSchema):void 0}}})));return!Jn(e.serverIdentifier)||!0!==t?.alwaysExposeVirtualMcpAuthTool&&"needsAuth"!==e.status||o.some((e=>e.toolName===iT))||o.push(new vn.E$({toolName:iT,...r?{}:{description:aT,...!0===t?.inputSchemaJson?{inputSchemaJson:JSON.stringify(rM)}:{inputSchema:ve.Value.fromJson(rM)}}})),new vn.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,serverUseInstructions:n||void 0,tools:o})}));return new vn.U_({enabled:!0,mcpDescriptors:n})}function sM(e){const t=e?.trim();return t||void 0}function iM(e,t){const r=function(e){return sM(e.serverIdentifier)}(e);if(r)return r;const n=sM(e.serverName);return n?t.get(n)??n:void 0}class aM{constructor(e){this.mcpLease=e}async getState(e){const[t,r]=await Promise.all([this.mcpLease.getTools(e).catch((t=>(K$.warn(e,"Error fetching MCP tools",{error:t}),[]))),this.mcpLease.getInstructions(e).catch((t=>(K$.warn(e,"Error fetching MCP instructions",{error:t}),[])))]);return function(e,t,r,n=!1){const o=new Map;for(const t of e)o.has(t.providerIdentifier)||o.set(t.providerIdentifier,t.clientKey);const s=t.map((e=>iM(e,o))).filter((e=>Boolean(e))),i=[...new Set([...e.map((e=>e.clientKey)),...s,...Array.from(r?.entries()??[]).filter((([,e])=>"connected"!==e.status)).map((([e])=>e))])];if(n&&void 0!==r){const e=new Map(Array.from(r.keys(),((e,t)=>[e,t])));i.sort(((t,r)=>(e.get(t)??e.size)-(e.get(r)??e.size)))}return{servers:i.map((n=>{const s=e.filter((e=>e.clientKey===n));return{serverName:s[0]?.providerIdentifier??n,serverIdentifier:n,plugin:s[0]?.plugin,marketplace:s[0]?.marketplace,tools:s,instructions:t.filter((e=>iM(e,o)===n)),status:r?.get(n)?.status,errorMessage:r?.get(n)?.errorMessage}}))}}(t,r,await async function(e,t){const r=await t.getClients(e).catch((t=>(K$.warn(e,"Error fetching MCP clients",{error:t}),{}))),n=await Promise.all(Object.entries(r).map((async([t,r])=>{const n=await r.getState(e).catch((()=>({kind:"error",message:"Failed to fetch MCP client state"})));return[t,{status:to(n),errorMessage:"error"===n.kind&&void 0!==n.message?n.message:void 0}]})));return new Map(n)}(e,this.mcpLease))}}function cM(e){return new Mc._W({result:{case:"success",value:new Mc.pv({servers:e.servers.map((e=>new Mc.XE({serverName:e.serverName,serverIdentifier:e.serverIdentifier,plugin:e.plugin,marketplace:e.marketplace,tools:e.tools.map((e=>new vn.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?ve.Value.fromJson(e.inputSchema):void 0,metaJson:Xn(e._meta),...Nb(e.annotations)}))),instructions:e.instructions,status:e.status,errorMessage:e.errorMessage})))})}})}class lM{constructor(e,t,r){this.mcpStateAccessor=e,this.ensureMcpServersLoaded=t,this.options=r}async execute(e,t){if(void 0!==t.ruleSubjects&&void 0!==this.options?.serverRuleSubjects)return function(e,t){const r={commandPatterns:t.commandPatterns,serverUrlPatterns:t.serverUrlPatterns},n=[];for(const[t,o]of e){const e=void 0!==o.command?{transport:Mc.zj.STDIO,value:o.command,matched:{command:o.command}}:void 0!==o.url?{transport:Mc.zj.HTTP,value:o.url,matched:{url:o.url}}:void 0;void 0!==e&&n.push(new Mc.XE({serverName:t,serverIdentifier:t,ruleSubject:new Mc.D0({transport:e.transport,...IC(e.matched,r)?{value:e.value}:{}})}))}return new Mc._W({result:{case:"success",value:new Mc.pv({servers:n})}})}(this.options.serverRuleSubjects(),t.ruleSubjects);try{await(this.ensureMcpServersLoaded?.(e,t.serverIdentifiers,{wait:!t.kickOnly}))}catch{}t.refreshPolicy!==Mc.ew.FORCE_IF_MISSING&&t.refreshPolicy!==Mc.ew.FORCE||await(this.mcpStateAccessor.refreshNow?.(e));const r=await this.mcpStateAccessor.getState(e);if(!0===this.options?.filterToRequestedServers&&t.serverIdentifiers.length>0){const e=new Set(t.serverIdentifiers),n=r.servers.filter((t=>e.has(t.serverIdentifier)));if(n.length>0)return cM({...r,servers:n})}return cM(r)}}class uM{constructor(e,t,r,n,o,s,i,a,c={}){this.cursorRulesService=e,this.cloudRulesService=t,this.subagentsService=r,this.repositoryProvider=n,this.grepProvider=o,this.mcpStateAccessor=s,this.gitExecutor=i,this.workspacePaths=a,this.reusedGitInfo=new Map,this.reusedMcpState=new X$,this.reusedAgentSkills=new X$,this.reusedAdminCommandDenylist=new X$,this.cachedWorkspaces=new Map,this.inFlightWorkspaceWarms=new Map;const{projectDir:l,getSmartModeClassifierAutoModeEnabled:u,getAdminCommandDenylist:d,devForceNextSmartModeClassifierBlockToken:h,isWorkingDirHomeDir:p,agentNotesEnabled:f,reportProcessWorkingDirectory:m,createFileWatcher:g,getSandboxEnabled:w,getSandboxSupported:y,getNetworkAllowlistInfo:v,userTerminalHint:b,getMcpFileSystemOptions:S,mcpMetaToolEnabled:k,mcpMetaToolSlimDescriptors:_,mcpInputSchemaJson:C,alwaysExposeVirtualMcpAuthTool:E,getArtifactsFolder:x,secretRedactionEnabled:P,attributionConfigProvider:R,isAttributionDisabledByAdmin:I,getAgentSkills:T,additionalRules:A,getComputerUseSupported:$,getComputerUseDesktop:M,getMockPromptTime:D}=c;this.projectDir=l,this.isWorkingDirHomeDir=p,this.agentNotesEnabled=f??!0,this.reportProcessWorkingDirectory=m??!0,this.getSandboxEnabled=w,this.getSandboxSupported=y,this.getNetworkAllowlistInfo=v,this.getSmartModeClassifierAutoModeEnabled=u,this.getAdminCommandDenylist=d,this.devForceNextSmartModeClassifierBlockToken=h,this.getMockPromptTime=D,this.userTerminalHint=b,this.getMcpFileSystemOptions=S,this.mcpMetaToolEnabled=k??!1,this.mcpMetaToolSlimDescriptors=_??!1,this.mcpInputSchemaJson=C??!1,this.alwaysExposeVirtualMcpAuthTool=E??!1,this.getArtifactsFolder=x,this.secretRedactionEnabled=P,this.attributionConfigProvider=R,this.isAttributionDisabledByAdmin=I,this.getAgentSkills=T,this.additionalRules=A??[],this.getComputerUseSupported=$,this.getComputerUseDesktop=M,this.reduceContextHotPath=c.reduceContextHotPath??!1,this.sectionLoadTimeoutMs=c.sectionLoadTimeoutMs,this.reportSectionCompleteness=c.reportSectionCompleteness??!1,this.freshSectionWaitMs=c.freshSectionWaitMs,this.onRequestContext=c.onRequestContext,this.mcpFieldsFromCaller=c.mcpFieldsFromCaller??!1,!0!==c.deferWarmup&&this.warm(),void 0!==g&&(this.fileWatcher=g(),this.fileWatcher.onDidChange((e=>{this.onWorkspacePathChanged(e)})),this.fileWatcher.onDidCreate((e=>{this.onWorkspacePathChanged(e)})),this.fileWatcher.onDidDelete((e=>{this.onWorkspacePathChanged(e)})))}warm(){this.warmWorkspaceCaches(),void 0===this.globalCache&&this.rebuildGlobalCache()}onWorkspacePathChanged(e){this.rebuildAllCaches()}getWorkspaceCache(e){return this.cachedWorkspaces.get(e)}warmWorkspaceCaches(){const e=(0,b.q6)();Promise.all(this.workspacePaths.map((t=>this.ensureWorkspaceCacheWarm(e,t))))}ensureWorkspaceCacheWarm(e,t){if(this.cachedWorkspaces.has(t))return Promise.resolve();const r=this.inFlightWorkspaceWarms.get(t);if(void 0!==r)return r;const n=this.warmWorkspaceCache(e,t).finally((()=>{this.inFlightWorkspaceWarms.delete(t)}));return this.inFlightWorkspaceWarms.set(t,n),n}async warmWorkspaceCache(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=z$(r,(0,D.VI)(e.withName("LocalRequestContextExecutor.warmWorkspaceCache")),!1),o=await tc(n.ctx,this.gitExecutor,t),s=o?await ac(n.ctx,this.gitExecutor,o):void 0,i={repoPath:o??void 0,remoteUrl:void 0!==s?cc(s):void 0};if(this.cachedWorkspaces.set(t,i),void 0!==this.freshSectionWaitMs&&void 0!==i.repoPath){const e=i.repoPath;this.gitInfoSection(e).prefetch((()=>eM((0,b.q6)(),this.gitExecutor,e,V$)))}}catch(e){r.error=e,r.hasError=!0}finally{G$(r)}}gitInfoSection(e){let t=this.reusedGitInfo.get(e);return void 0===t&&(t=new X$,this.reusedGitInfo.set(e,t)),t}rebuildAllCaches(){this.cacheDebounceTimeout&&clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=setTimeout((()=>{this.cacheDebounceTimeout=void 0,this.rebuildGlobalCache()}),5e3)}invalidateGlobalCache(){this.globalCache=void 0,this.lastGoodGlobalCache=void 0,this.globalCacheTraceId=void 0}refreshGlobalCache(){this.cacheDebounceTimeout&&(clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=void 0),this.rebuildGlobalCache()}rebuildGlobalCache(){const e={stack:[],error:void 0,hasError:!1};try{const t=(0,b.q6)(),r=z$(e,(0,D.VI)(t.withName("LocalRequestContextExecutor.rebuildGlobalCache")),!1);this.globalCacheTraceId=r.span.spanContext().traceId;const n=this.computeGlobalCache(r.ctx);return this.globalCache=n,(this.reduceContextHotPath||void 0!==this.sectionLoadTimeoutMs||void 0!==this.freshSectionWaitMs)&&n.then((e=>{this.globalCache===n&&(this.lastGoodGlobalCache=e)}),(()=>{this.globalCache===n&&(this.globalCache=void 0)})),n}catch(t){e.error=t,e.hasError=!0}finally{G$(e)}}async computeGlobalCache(e){const t={stack:[],error:void 0,hasError:!1};try{const r=z$(t,(0,D.VI)(e.withName("LocalRequestContextExecutor.computeGlobalCache")),!1),n=AbortSignal.timeout(1e3),o=performance.now(),s={},i=(e,t)=>{const r=performance.now();return t.finally((()=>{s[e]=Math.round(performance.now()-r)}))},[a,c,l,u]=await Promise.all([i("cursorRules",this.cursorRulesService.getAllCursorRules(r.ctx)),i("cloudRule",this.cloudRulesService?this.cloudRulesService.getCloudRule(r.ctx):Promise.resolve(null)),i("codebaseRef",this.repositoryProvider.getCodebaseReference(r.ctx,n).catch((()=>{}))),i("subagents",this.subagentsService?this.subagentsService.getAllSubagents().catch((()=>[])):Promise.resolve([]))]),d=Math.round(performance.now()-o);return d>1e3&&K$.warn(r.ctx,"computeGlobalCache: slow",{totalMs:d,...s,ruleCount:a.length}),{rules:[...this.additionalRules,...a],cloudRule:c,codebaseReference:l,customSubagents:u}}catch(e){t.error=e,t.hasError=!0}finally{G$(t)}}dispose(){this.cacheDebounceTimeout&&(clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=void 0),this.fileWatcher&&(this.fileWatcher.dispose(),this.fileWatcher=void 0),this.globalCache=void 0,this.lastGoodGlobalCache=void 0}async collectWorkspaceCaches(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=z$(r,(0,D.VI)(e.withName("LocalRequestContextExecutor.collectWorkspaceCaches")),!1);let o;if(this.grepProvider.getTrackedState)try{o=await this.grepProvider.getTrackedState(this.workspacePaths)}catch{o=void 0}let s=!0,i=!0;return{gitRepos:(await Promise.all(this.workspacePaths.map((async e=>{let r=this.getWorkspaceCache(e);if(void 0===r){if(!t.waitForWorkspaceCache)return s=!1,void this.ensureWorkspaceCacheWarm(n.ctx,e);if(await this.ensureWorkspaceCacheWarm(n.ctx,e),r=this.getWorkspaceCache(e),void 0===r)return void(s=!1)}const a=o?.[e];if(void 0!==a)return void 0!==r.repoPath&&void 0===a.gitStatus&&(i=!1),new Fr.DS({path:r.repoPath,status:a.gitStatus,branchName:a.gitBranchName,remoteUrl:r.remoteUrl,isOriginBacked:Xa(r.remoteUrl)});if(void 0===r.repoPath)return;const c=r.repoPath,{status:l,branchName:u}=void 0===this.freshSectionWaitMs?await eM(n.ctx,t.gitExecutor,c,V$):await this.gitInfoSection(c).read((()=>eM((0,b.q6)(),t.gitExecutor,c,V$)),this.freshSectionWaitMs);return void 0===l&&(i=!1),new Fr.DS({path:r.repoPath,status:l,branchName:u,remoteUrl:r.remoteUrl,isOriginBacked:Xa(r.remoteUrl)})})))).filter((e=>void 0!==e)),gitRepoInfoComplete:s,gitStatusInfoComplete:s&&i}}catch(e){r.error=e,r.hasError=!0}finally{G$(r)}}shareBoundedSectionLoad(e,t,r){if(void 0===this.sectionLoadTimeoutMs)return r();const n=e();if(void 0!==n)return n;const o=r();t(o);const s=()=>{e()===o&&t(void 0)};return o.then(s,s),o}async computeCachedRequestContext(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=z$(n,(0,D.VI)(e.withName("LocalRequestContextExecutor.computeCachedRequestContext")),!1),s=this.projectDir,i=async()=>{const e={stack:[],error:void 0,hasError:!1};try{const t=z$(e,(0,D.VI)(o.ctx.withName("LocalRequestContextExecutor.computeCachedRequestContext.getGlobalData")),!1);if(this.globalCacheTraceId&&t.span.setAttribute("cacheTraceId",this.globalCacheTraceId),!this.reduceContextHotPath&&void 0===this.freshSectionWaitMs){if(void 0===this.globalCache){const e=this.computeGlobalCache(o.ctx);this.globalCache=e,e.catch((()=>{this.globalCache===e&&(this.globalCache=void 0)})),void 0!==this.sectionLoadTimeoutMs&&e.then((t=>{this.globalCache===e&&(this.lastGoodGlobalCache=t)}),(()=>{}))}return this.globalCache}return void 0!==this.lastGoodGlobalCache?this.lastGoodGlobalCache:this.globalCache??this.rebuildGlobalCache()}catch(t){e.error=t,e.hasError=!0}finally{G$(e)}},a=performance.now(),c={},l=(e,t)=>{const r=performance.now();return t.finally((()=>{c[e]=Math.round(performance.now()-r)}))},u=e=>Z$(e,this.sectionLoadTimeoutMs),d=(e,t,r)=>this.shareBoundedSectionLoad(e,t,r),h=this.freshSectionWaitMs,p=(e,t)=>void 0===h?t():e.read(t,h),f=void 0===h?o.ctx:(0,b.q6)(),[m,g,w,{gitRepos:y,gitRepoInfoComplete:v,gitStatusInfoComplete:S},k,_,C,E,x,P]=await Promise.all([l("globalCache",u(i())),l("mcpState",this.mcpFieldsFromCaller?Promise.resolve({servers:[]}):u(p(this.reusedMcpState,(()=>d((()=>this.inFlightMcpState),(e=>{this.inFlightMcpState=e}),(()=>this.mcpStateAccessor.getState(f))))))),l("env",tM(o.ctx,this.workspacePaths,{projectDir:s,notesSessionId:t.notesSessionId,agentNotesEnabled:this.agentNotesEnabled,reportProcessWorkingDirectory:this.reportProcessWorkingDirectory,getSmartModeClassifierAutoModeEnabled:this.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:this.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:this.getMockPromptTime,isWorkingDirHomeDir:this.isWorkingDirHomeDir,getSandboxEnabled:this.getSandboxEnabled,getSandboxSupported:this.getSandboxSupported,getNetworkAllowlistInfo:this.getNetworkAllowlistInfo,userTerminalHint:this.userTerminalHint,artifactsFolder:this.getArtifactsFolder?.(o.ctx),secretRedactionEnabled:this.secretRedactionEnabled,getComputerUseSupported:this.getComputerUseSupported,getComputerUseDesktop:this.getComputerUseDesktop})),l("git",this.collectWorkspaceCaches(o.ctx,{waitForWorkspaceCache:!0===t.waitForWorkspaceCache,gitExecutor:r})),l("conversationNotes",this.agentNotesEnabled&&s&&t.notesSessionId?H$(s,t.notesSessionId):Promise.resolve(void 0)),l("sharedNotes",this.agentNotesEnabled&&s?q$(s):Promise.resolve(void 0)),l("mcpFileSystemOptions",this.getMcpFileSystemOptions?this.getMcpFileSystemOptions(o.ctx,{timeoutMs:3e3}):Promise.resolve(void 0)),l("attribution",this.isAttributionDisabledByAdmin?this.isAttributionDisabledByAdmin().catch((()=>!0)):Promise.resolve(!1)),l("agentSkills",u(p(this.reusedAgentSkills,(()=>d((()=>this.inFlightAgentSkills),(e=>{this.inFlightAgentSkills=e}),(()=>this.getAgentSkills?this.getAgentSkills(f):Promise.resolve([]))))))),l("adminCommandDenylist",u(p(this.reusedAdminCommandDenylist,(()=>d((()=>this.inFlightAdminCommandDenylist),(e=>{this.inFlightAdminCommandDenylist=e}),(()=>this.getAdminCommandDenylist?this.getAdminCommandDenylist():Promise.resolve(void 0)))))))]),R=m===J$,I=g===J$,T=x===J$,A=P===J$,$=R?this.lastGoodGlobalCache??{rules:[...this.additionalRules],cloudRule:null,codebaseReference:void 0,customSubagents:[]}:m,M=I?{servers:[]}:g,O=T?[]:x,F=A?void 0:P;(R||I||T||A)&&K$.warn(o.ctx,"computeCachedRequestContext: section load timed out",{timeoutMs:this.sectionLoadTimeoutMs,rulesAndSubagents:R,mcpState:I,agentSkills:T,adminCommandDenylist:A});const N=performance.now()-a;for(const[e,t]of Object.entries(c))o.span.setAttribute(`requestContext.timing.${e}Ms`,t);o.span.setAttribute("requestContext.timing.totalMs",Math.round(N)),N>1e3&&K$.warn(o.ctx,"computeCachedRequestContext: slow parallel data collection",{durationMs:Math.round(N),...c});const L=this.mcpMetaToolEnabled?oM(M,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,slimDescriptors:this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}):void 0,j=this.attributionConfigProvider?.get(),U=!E&&(j?.attribution?.attributeCommitsToAgent??!0),B=!E&&(j?.attribution?.attributePRsToAgent??!0),W=new Fr.bb({rules:$.rules,env:w,gitRepos:y,gitRepoInfoComplete:v,repositoryInfo:$.codebaseReference?[{relativeWorkspacePath:$.codebaseReference.relativeWorkspacePath,repoName:$.codebaseReference.repoName,repoOwner:$.codebaseReference.repoOwner,isTracked:$.codebaseReference.isTracked,isLocal:$.codebaseReference.isLocal,orthogonalTransformSeed:$.codebaseReference.orthogonalTransformSeed,pathEncryptionKey:$.codebaseReference.pathEncryptionKey}]:[],...nM(M,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}),conversationNotesListing:k,sharedNotesListing:_,customSubagents:$.customSubagents,mcpFileSystemOptions:C,mcpMetaToolOptions:L,supportsMcpAuth:!0,commitAttributionMessage:U?"enabled":void 0,prAttributionMessage:B?"enabled":void 0,agentSkills:O,adminCommandDenylist:F?.rules??[]});return null!==$.cloudRule&&void 0!==$.cloudRule&&(W.cloudRule=$.cloudRule),this.reportSectionCompleteness&&(W.rulesInfoComplete=!R,W.customSubagentsInfoComplete=!R,W.agentSkillsInfoComplete=!T,W.mcpInfoComplete=!I,W.mcpFileSystemInfoComplete=this.mcpMetaToolEnabled||void 0!==C,W.envInfoComplete=!0,W.gitStatusInfoComplete=S),W}catch(e){n.error=e,n.hasError=!0}finally{G$(n)}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{this.onRequestContext?.();const n=z$(r,(0,D.VI)(e.withName("LocalRequestContextExecutor.execute")),!1);n.span.setAttribute("enableCaching",void 0!==this.fileWatcher),n.span.setAttribute("hasGlobalCache",!!this.globalCache);try{const e=this.gitExecutor.forRequest?.()??this.gitExecutor,r=await this.computeCachedRequestContext(n.ctx,t,e);return new Fr._G({result:{case:"success",value:new Fr.yW({requestContext:r})}})}catch(e){return e instanceof Error||"string"==typeof e?n.span.recordException(e):n.span.recordException(Cc(e)),new Fr._G({result:{case:"error",value:new Fr.nf({error:e instanceof Error?e.message:String(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{G$(r)}}}function dM(e){return 0!==e.timeout?e.timeout:e.isBackground||e.timeoutBehavior===fe._d.BACKGROUND||void 0!==e.hardTimeout&&e.hardTimeout>0?0:3e4}var hM=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class pM{constructor(e,t,r,n){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r}buildResultFromExit(e){return 0===(e.exitCode??-1)?new fe.W4({result:{case:"success",value:new fe.QR({...e,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:hs(e.sandboxPolicy)}):new fe.W4({result:{case:"failure",value:new fe.xC({...e,aborted:void 0!==e.abortReason,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:hs(e.sandboxPolicy)})}async executeWithPolicy(e,t,r,n,o){const s=Date.now(),i=new AbortController,a=e.signal?AbortSignal.any([e.signal,i.signal]):i.signal,c=setTimeout((()=>{i.abort()}),n);try{let n,l,u,d="",h="",p=null;const f=o?{perUser:o}:void 0;for await(const o of this.coreExecutor.execute(e,{command:t.command,workingDirectory:r,signal:a,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:f,fileOutputThresholdBytes:t.fileOutputThresholdBytes,pipeStdin:!1}))"stdout"===o.type?d+=o.data:"stderr"===o.type?h+=o.data:"exit"===o.type&&(p=null!=o.code?0|o.code:null,l=o.outputLocation,n=o.aborted?a.aborted?i.signal.aborted&&a.reason===i.signal.reason?fe.Lv.TIMEOUT:fe.Lv.USER_ABORT:fe.Lv.UNSPECIFIED:void 0,u=Oy(o.localExecutionTimeMs));clearTimeout(c);const m=Date.now()-s,g={command:t.command,workingDirectory:r,exitCode:void 0!==n?-1:p??-1,signal:void 0!==n?"SIGTERM":"",abortReason:n,stdout:d,stderr:h,executionTime:m,localExecutionTimeMs:u,sandboxPolicy:o,outputLocation:l};return this.buildResultFromExit(g)}catch(s){return clearTimeout(c),i.signal.aborted&&!e.signal.aborted?new fe.W4({result:{case:"timeout",value:new fe.eG({command:t.command,workingDirectory:r,timeoutMs:n})},sandboxPolicy:hs(o)}):e.signal.aborted?new fe.W4({result:{case:"rejected",value:new fe.pZ({command:t.command,workingDirectory:r,reason:"Command aborted"})},sandboxPolicy:hs(o)}):new fe.W4({result:{case:"spawnError",value:new fe.mJ({command:t.command,workingDirectory:r,error:s instanceof Error?s.message:"Unknown error"})},sandboxPolicy:hs(o)})}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,D.VI)(e.withName("LocalShellExecutor.execute")),!1).ctx;(0,D.HF)(n,"LocalShellExecutor.execute");const o=t.command,s=t.requestedSandboxPolicy?ds(t.requestedSandboxPolicy):void 0,i=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),a=dM(t),c=(0,ts.o1)(i);if(!t.parsingResult)return new fe.W4({result:{case:"spawnError",value:new fe.mJ({command:o,workingDirectory:c,error:"Parsing result is required"})}});let l;if(Oo(t)){const e=await this.permissionsService.shouldEnforceShellInvariantBlocks(n,{workingDirectory:c,skipUnsafeWorkingDirectoryBlock:!0,command:o,parsingResult:t.parsingResult,toolCallId:t.toolCallId,resolveSkippedApprovalPolicy:!0},s);if("block"===e.kind)return new fe.W4({result:rd(o,c,e.reason)});l=e.policy??s}else{const e=await this.permissionsService.shouldBlockShellCommand(n,o,{workingDirectory:c,timeout:a,parsingResult:t.parsingResult,toolCallId:t.toolCallId,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Mo(t)},s);if("block"===e.kind)return new fe.W4({result:rd(o,c,e.reason)});l=e.policy}return l=await $c(l,{command:o,workingDirectory:c,parsingResult:t.parsingResult,permissionsService:this.permissionsService,ignoreService:this.ignoreService}),this.executeWithPolicy(n,t,i,a,l)}catch(e){r.error=e,r.hasError=!0}finally{hM(r)}}}var fM=r("../proto/dist/generated/agent/v1/shell_allowlist_precheck_exec_pb.js");class mM{constructor(e){this.permissionsService=e}async execute(e,t){const r=t.parsingResult??new fe.HO,n=await this.permissionsService.isShellCommandFullyAllowlisted(e,t.command,{workingDirectory:t.workingDirectory,parsingResult:r,classifierResult:t.classifierResult,toolCallId:t.toolCallId});return new fM.e({allowlisted:n})}}class gM{constructor(e){this.shellStreamExecutor=e}async execute(e,t,r){return""===t.toolCallId.trim()?new fe.jK({status:fe.iA.NOT_FOUND}):this.shellStreamExecutor.forceBackgroundByToolCallId(e,t.toolCallId)}}var wM=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const yM=(0,d.h)("local-exec:shell-stream");class vM{constructor(e,t){this.iterator=e,this.timeoutMs=t,this.pendingPromise=null,this.stopPromise=new Promise((e=>{this.stopResolve=e}))}stop(e){return void 0===this.stopReason&&(this.stopReason=e,this.stopResolve?.(),!0)}get timedOut(){return"background"===this.stopReason?.kind&&this.stopReason.reason===fe.Jg.TIMEOUT}get backgroundRequested(){return"background"===this.stopReason?.kind}get backgroundReasonValue(){return"background"===this.stopReason?.kind?this.stopReason.reason:void 0}get stopReasonValue(){return this.stopReason}async*iterate(){this.timer=setTimeout((()=>{this.stop({kind:"background",reason:fe.Jg.TIMEOUT})}),this.timeoutMs);try{for(;;){if(void 0!==this.stopReason)return;this.pendingPromise=this.iterator.next();const e=await Promise.race([this.pendingPromise.then((e=>({kind:"result",result:e}))),this.stopPromise.then((()=>({kind:"stopped"})))]);if("stopped"===e.kind)return;if(this.pendingPromise=null,e.result.done)return;yield e.result.value}}finally{clearTimeout(this.timer)}}requestBackground(){return this.stop({kind:"background",reason:fe.Jg.USER_REQUEST})}abort(){this.stop({kind:"abort"})}getHandoffIterator(){if(this.pendingPromise){const e=this.pendingPromise;this.pendingPromise=null;let t=!1;return{next:async()=>t?this.iterator.next():(t=!0,e)}}return this.iterator}}function bM(){let e=()=>{};return{promise:new Promise((t=>{e=t})),resolve:e}}class SM{constructor(e,t,r,n){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r,this.backgroundShellManager=n,this.activeForegroundExecutions=new Map,this.pendingShells=new Map}hasForegroundWork(){return this.activeForegroundExecutions.size>0||this.pendingShells.size>0}async forceBackgroundByToolCallId(e,t){const r=this.pendingShells.get(t),n=void 0===r||r.awaitingApproval?this.activeForegroundExecutions.get(t):await async function(e,t){const[r,n]=e.withCancel();try{return await Promise.race([t.registered.promise,(0,b.uk)(r).then((()=>{}))])}finally{n()}}(e,r),o=n?.requestBackground();return o?new fe.jK({status:fe.iA.ACCEPTED,shellResult:o}):new fe.jK({status:fe.iA.NOT_FOUND})}pendingFrom(e){return{execute:(t,r,n)=>this.whilePending(r,(()=>e.get(re).execute(t,r,n)))}}execute(e,t){return this.whilePending(t,(r=>this.run(e,t,r)))}async*whilePending(e,t){let r=this.pendingShells.get(e.toolCallId);void 0===r&&(r={awaitingApproval:!1,registered:bM()},""!==e.toolCallId&&e.timeoutBehavior===fe._d.BACKGROUND&&this.pendingShells.set(e.toolCallId,r));try{yield*t(r)}finally{this.settle(e.toolCallId,r,void 0)}}settle(e,t,r){this.pendingShells.get(e)===t&&this.pendingShells.delete(e),t.registered.resolve(r)}async*run(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{e.signal?.throwIfAborted(),function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(n,(0,D.VI)(e.withName("LocalShellStreamExecutor.execute")),!1);const o=t.command;let s=t.requestedSandboxPolicy?ds(t.requestedSandboxPolicy):void 0;const i=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),a=dM(t),c=(0,ts.o1)(i),l=Date.now(),u=performance.now(),d=new fe.HO(qo(o).structured),h=Cs({command:o,parsingResult:d,blockedCommands:t.adminCommandDenylist});if(void 0!==h)return void(yield new fe.FI({event:{case:"rejected",value:new fe.pZ({command:o,workingDirectory:c,reason:h})}}));const p=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:c,skipUnsafeWorkingDirectoryBlock:!0,command:o,parsingResult:d,toolCallId:t.toolCallId,resolveSkippedApprovalPolicy:Oo(t)},s);if("block"===p.kind)return"permissionsConfig"===p.reason.type?void(yield new fe.FI({event:{case:"permissionDenied",value:new fe.jn({command:o,workingDirectory:c,error:"Command blocked by permissions configuration",isReadonly:p.reason.isReadonly??!1})}})):void(yield new fe.FI({event:{case:"rejected",value:new fe.pZ({command:o,workingDirectory:c,reason:td(p.reason)})}}));if(yM.info(e,"Shell stream: approval gate reached",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,hasSmartModeApproval:void 0!==t.smartModeApproval,hasSmartModeApprovalReason:void 0!==t.smartModeApproval?.reason,hasSmartModeApprovalRequestId:void 0!==t.smartModeApproval?.requestId,requestedPolicyType:s?.type??"undefined",parserCommandCount:d.executableCommands.length,classifierCommandCount:t.classifierResult?.commands.length??0,commandLength:o.length}),Oo(t)){const r=p.policy??s;yM.info(e,"Shell stream: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:s?.type??"undefined",effectivePolicyType:r?.type??"undefined"}),s=r}else{r.awaitingApproval=!0;const n=await this.permissionsService.shouldBlockShellCommand(e,o,{workingDirectory:c,timeout:a,parsingResult:d,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Mo(t),onApprovalRequested:()=>{r.registered.resolve(void 0),r.registered=bM()}},s);if(r.awaitingApproval=!1,"block"===n.kind){if(yM.info(e,"Shell stream: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:n.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),"permissionsConfig"===n.reason.type)return void(yield new fe.FI({event:{case:"permissionDenied",value:new fe.jn({command:o,workingDirectory:c,error:"Command blocked by permissions configuration",isReadonly:n.reason.isReadonly??!1})}}));const r=td(n.reason);return void(yield new fe.FI({event:{case:"rejected",value:new fe.pZ({command:o,workingDirectory:c,reason:r})}}))}s=n.policy,yM.info(e,"Shell stream: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:s.type})}s=await $c(s,{command:o,workingDirectory:c,parsingResult:d,permissionsService:this.permissionsService,ignoreService:this.ignoreService}),yield new fe.FI({event:{case:"start",value:new fe.tD({sandboxPolicy:hs(s)})}});const f=t.timeoutBehavior===fe._d.BACKGROUND,m=f&&!t.closeStdin&&void 0===t.smartModeApproval,g=new AbortController,w=f?g.signal:e.signal?AbortSignal.any([e.signal,g.signal]):g.signal,y=!0,v=s?{perUser:s}:void 0,b=this.coreExecutor.execute(e,{command:o,workingDirectory:i,signal:w,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:v,fileOutputThresholdBytes:t.fileOutputThresholdBytes,pipeStdin:m,showElapsedTime:y});let S;f||(S=setTimeout((()=>g.abort()),a));const k=f?new vM(b[Symbol.asyncIterator](),a):null;let _,C,E,x="",P=!1,R=!1;const I=t.toolCallId&&k?{requestBackground:()=>{if(k.requestBackground())return E=E??this.backgroundShellManager.generateShellId(),new fe.W4({result:{case:"success",value:new fe.QR({shellId:E,pid:C,command:o,workingDirectory:c,msToWait:Oy(performance.now()-u),backgroundReason:fe.Jg.USER_REQUEST,interleavedOutput:x})}})}}:void 0;t.toolCallId&&I&&this.activeForegroundExecutions.set(t.toolCallId,I),this.settle(t.toolCallId,r,I);const T=()=>{t.toolCallId&&this.activeForegroundExecutions.get(t.toolCallId)===I&&this.activeForegroundExecutions.delete(t.toolCallId)},A=()=>{k&&!k.backgroundRequested&&(g.abort(),k.abort())};let $;k&&e.signal&&(e.signal.aborted?A():e.signal.addEventListener("abort",A,{once:!0}));const M=t.hardTimeout;void 0!==M&&M>0&&($=setTimeout((()=>{void 0!==E?this.backgroundShellManager.abort(E)||g.abort():(P=!0,g.abort(),k?.abort())}),M));const O=k?.iterate()??b;try{for await(const r of O)if("stdout"===r.type)x+=r.data,yield new fe.FI({event:{case:"stdout",value:new fe.o0({data:r.data})}});else if("stderr"===r.type)x+=r.data,yield new fe.FI({event:{case:"stderr",value:new fe.Db({data:r.data})}});else if("stdin_ready"===r.type)_=r.stdin,C=r.pid;else if("exit"===r.type){let n;R=!0,r.aborted&&(n=e.signal?.aborted?fe.Lv.USER_ABORT:k?.timedOut||g.signal.aborted?fe.Lv.TIMEOUT:fe.Lv.USER_ABORT),yield new fe.FI({event:{case:"exit",value:new fe.vb({code:(r.code??-1)>>>0,cwd:await this.coreExecutor.getCwd(t.conversationId),outputLocation:r.outputLocation,aborted:r.aborted,abortReason:n,localExecutionTimeMs:Oy(r.localExecutionTimeMs)})}})}}catch(r){if(!(r instanceof No.SandboxUnsupportedError))throw r;const n=s?.type??"unknown";return yM.debug(e,"Shell stream: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:n,reason:r.reason}),void(yield new fe.FI({event:{case:"sandboxUnsupported",value:new fe.rI({command:o,workingDirectory:c,sandboxPolicyType:n,reason:r.reason??r.message,isReadonly:"workspace_readonly"===n})}}))}finally{clearTimeout(S),k?.backgroundRequested||clearTimeout($),T(),!k||k.backgroundRequested||R||g.abort(),e.signal?.removeEventListener("abort",A)}if(k?.backgroundRequested&&!P){const r=E??this.backgroundShellManager.generateShellId();E=r;const n=k.backgroundReasonValue===fe.Jg.USER_REQUEST?fe.Jg.USER_REQUEST:fe.Jg.TIMEOUT,s=n===fe.Jg.USER_REQUEST?Math.round(performance.now()-u):a;await this.backgroundShellManager.adopt({ctx:e,shellId:r,command:o,workingDirectory:c,toolCallId:t.toolCallId,sandboxPolicy:v,initialOutput:x,stdin:_,pid:C,abortController:g,eventIterator:k.getHandoffIterator(),startTime:l,monotonicStartMs:u,showElapsedTime:y,description:t.description,outputNotification:t.outputNotification,onCleanup:()=>clearTimeout($)}),yield new fe.FI({event:{case:"backgrounded",value:new fe.Y9({shellId:r,command:o,workingDirectory:c,pid:C,msToWait:y?s:void 0,reason:n})}})}else e.signal?.aborted&&void 0!==k?.stopReasonValue?(clearTimeout($),yield new fe.FI({event:{case:"exit",value:new fe.vb({code:4294967295,cwd:await this.coreExecutor.getCwd(t.conversationId),aborted:!0,abortReason:fe.Lv.USER_ABORT})}})):clearTimeout($)}catch(e){n.error=e,n.hasError=!0}finally{wM(n)}}}const kM={kind:"absent"};class _M{constructor(e){this.cells=new Map,this.takenCells=new WeakMap,this.collectedCells=new FinalizationRegistry((e=>{void 0===this.cells.get(e)?.deref()&&this.cells.delete(e)})),this.claims=new Map,this.nextGeneration=0,this.entries=new Po.q({max:1e3,ttl:6e4,ttlResolution:0,perf:e})}begin(e){this.entries.purgeStale();const t=++this.nextGeneration;return this.claims.set(TM(e),t),t}record(e,t,r){if(!this.claim(e,r))return;const n=TM(e);this.entries.set(n,{recorded:t,generation:r}),this.commitGeneration(n,r)}forget(e,t){if(!this.claim(e,t))return;const r=TM(e);this.entries.delete(r),this.commitGeneration(r,t)}end(e,t){this.claim(e,t)}take(e){const t=TM(e),r=this.entries.get(t);if(void 0===r)return;const n=this.entries.getRemainingTTL(t);this.entries.delete(t);let o=this.cells.get(t)?.deref();void 0===o&&(o={committed:r.generation},this.cells.set(t,new WeakRef(o)),this.collectedCells.register(o,t));const s={read:e,recorded:r.recorded,remainingTtlMs:n,generation:r.generation};return this.takenCells.set(s,o),s}restore(e){const t=this.takenCells.get(e);if(void 0===t||t.committed!==e.generation)return;const r=TM(e.read);this.entries.has(r)||!Number.isFinite(e.remainingTtlMs)||e.remainingTtlMs<=0||this.entries.set(r,{recorded:e.recorded,generation:e.generation},{ttl:e.remainingTtlMs})}commitGeneration(e,t){const r=this.cells.get(e)?.deref();void 0!==r&&(r.committed=t)}claim(e,t){const r=TM(e);return this.claims.get(r)===t&&(this.claims.delete(r),!0)}}class CM{constructor(){this.views=new Po.q({max:1e3})}get(e){return this.views.get(e)}set(e,t){this.views.set(e,t)}forget(e){this.views.delete(e)}recordWrite(e,t){if(t.length>Ks)return void this.views.delete(e);const r=(0,ko.createHash)("sha256").update(t).digest("hex");this.views.set(e,{kind:"fingerprint",byteLength:t.length,sha256:r})}recordDelete(e){this.views.set(e,kM)}}async function EM(e,t){if(void 0===e)return!1;try{if("absent"===e.kind)return await IM(t);const r=await RM(t);return void 0===r||r.byteLength!==e.byteLength||r.sha256!==e.sha256}catch{return!1}}async function xM(e,t){if("fingerprint"!==e?.kind)return!1;try{return!await IM(t)}catch{return!1}}class PM{constructor(e,t,r,n,o){this.inner=e,this.reads=t,this.permissionsService=r,this.workspacePath=n,this.views=o}async execute(e,t,r){const n=!0===r?.recordAgentView?(0,ts.o1)(t.path,this.workspacePath):void 0,o=function(e,t){if(""!==e.toolCallId&&void 0===e.offset&&void 0===e.limit)return{toolCallId:e.toolCallId,resolvedPath:(0,ts.o1)(e.path,t)}}(t,this.workspacePath);if(void 0===o){const o=await this.inner.execute(e,t,r);return this.forgetViewReadPast(n,o),o}const s=this.reads.begin(o);try{let i,a;try{i=await Yk(this.permissionsService,o.resolvedPath)}catch{return await this.readAndForget(e,t,r,o,s,n)}if(!1!==i&&"needsApproval"!==i.type)return await this.readAndForget(e,t,r,o,s,n);if(!1!==i){const i=await this.inner.execute(e,t,r),a=await async function(e,t){if("success"===e.result.case&&"content"===e.result.value.output.case)try{return await RM(t)}catch{return}}(i,o.resolvedPath);return this.commit(o,s,i,a,n),i}try{a=await RM(o.resolvedPath)}catch{return await this.readAndForget(e,t,r,o,s,n)}const c=await this.inner.execute(e,t,r);return this.commit(o,s,c,a,n),c}finally{this.reads.end(o,s)}}commit(e,t,r,n,o){let s;if("fileNotFound"===r.result.case?s=kM:void 0!==n&&"success"===r.result.case&&"content"===r.result.value.output.case&&(s={kind:"fingerprint",...n}),void 0===s)return this.reads.forget(e,t),void this.forgetViewReadPast(o,r);this.reads.record(e,s,t),void 0!==o&&this.views?.set(o,s)}async readAndForget(e,t,r,n,o,s){const i=await this.inner.execute(e,t,r);return this.reads.forget(n,o),this.forgetViewReadPast(s,i),i}forgetViewReadPast(e,t){void 0===e||"success"!==t.result.case&&"fileNotFound"!==t.result.case||this.views?.forget(e)}}async function RM(e){try{const t=await(0,xo.stat)(e);if(!t.isFile()||t.size>Ks)return}catch(e){return AM(e)}let t;try{t=await(0,xo.open)(e,function(){const e=Ro.constants;return e.O_RDONLY|(e.O_NONBLOCK??0)}());const r=await t.stat();if(!r.isFile()||r.size>Ks)return;const n=(0,ko.createHash)("sha256");let o=0;const s=Buffer.alloc(65536);for(;o<=Ks;){const{bytesRead:e}=await t.read(s,0,s.length,o);if(0===e)break;o+=e,n.update(s.subarray(0,e))}if(o>Ks)return;return{byteLength:o,sha256:n.digest("hex")}}catch(e){return AM(e)}finally{await(t?.close())}}async function IM(e){try{return await(0,xo.stat)(e),!0}catch(e){if($M(e))return!1;throw e}}function TM({toolCallId:e,resolvedPath:t}){return`${e}\0${t}`}function AM(e){if(!$M(e))throw e}function $M(e){const t=_c(e);return"ENOENT"===t||"ENOTDIR"===t}var MM=r("../proto/dist/generated/agent/v1/web_fetch_allowlist_precheck_exec_pb.js");class DM{constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isWebFetchFullyAllowlisted(e,{url:t.url});return new MM.M({allowlisted:r})}}var OM=r("node:constants");const FM=[".md",".markdown",".mdown",".mkd",".mkdn",".mdx"];function NM(e){const t=e.trim().toLowerCase();return FM.some((e=>t.endsWith(e)))}function LM(e,t){const r=e.trim().toLowerCase().split("win32"===t?/[\\/]/:"/");if(r.some((e=>"."===e||".."===e)))return!1;const[n,o,s,i,a]=r.slice(-5);return r.length>=5&&".cursor"===n&&"projects"===o&&void 0!==s&&""!==s&&"canvases"===i&&void 0!==a&&a.length>11&&a.endsWith(".canvas.tsx")}const jM="win32"===process.platform;process.platform;const UM="\\"===s.sep?"win32":"posix",BM={allowed:!1};class WM extends Error{constructor(e,t){super(t),this.name="SymlinkRefusedError",this.path=e}}function HM(e,{nonBlocking:t}){const r=Ro.constants;let n=e;return"number"==typeof r.O_NOFOLLOW&&(n|=r.O_NOFOLLOW),t&&"number"==typeof r.O_NONBLOCK&&(n|=r.O_NONBLOCK),"number"==typeof r.O_CLOEXEC&&(n|=r.O_CLOEXEC),n}const qM=[20,40,80],zM=new Set(["UNKNOWN","EBUSY"]);async function GM(e,t){try{const[r,n]=await Promise.all([t.stat({bigint:!0}),(0,xo.lstat)(e,{bigint:!0})]);r.dev===n.dev&&r.ino===n.ino&&await(0,xo.unlink)(e)}catch{}}async function VM(e,t,r,{removeOnRefusal:n=!1}={}){let o;try{o=await async function(e,t){try{return await(0,xo.open)(e,HM(t,{nonBlocking:!0}),438)}catch(r){const n=_c(r);if(("EAGAIN"===n||"EWOULDBLOCK"===n)&&await async function(e){try{return(await(0,xo.lstat)(e)).isFile()}catch{return!1}}(e))return await(0,xo.open)(e,HM(t,{nonBlocking:!1}),438);throw r}}(e,t)}catch(t){if(function(e){const t=_c(e);return"ELOOP"===t||"EMLINK"===t||"EPERM"===t&&"number"==typeof Ro.constants.O_NOFOLLOW}(t))throw new WM(e,`Refusing to ${r} through a symlink at ${e}`);throw t}try{let t;try{t=(0,Ro.realpathSync)(e)}catch{throw new WM(e,`Cannot verify canonical path before ${r}: ${e}`)}if(t!==e)throw new WM(e,`Refusing ${r}: ${e} now resolves through a symlinked parent to ${t}`);const n=await o.stat();if(!n.isFile())throw new WM(e,`Refusing to ${r} non-regular file at ${e}`);return{fd:o,stats:n}}catch(t){throw n&&await GM(e,o),await o.close(),t}}var KM=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const JM=(0,d.h)("LocalWriteExecutor"),ZM=(0,h.Pu)("local_exec.write.encoding_check",{description:"Text writes that landed, per encoding detector (mojibake, U+FFFD): whether the written text holds the pattern and holds more of it than the file did, and for a detection what the file held, its extension family, encoding and the machine's Windows code page",labelNames:["detector","outcome","file","ext","encoding","code_page","run_count","delta","before_count","pattern"]}),XM=async(e,t,r,n)=>{const o=setTimeout((()=>{JM.warn(e,`[watchdog, LocalWriteExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function QM(e){return new Error(`Could not create ${e}: directory creation exceeded the path depth and was stopped.`)}async function YM(e){try{return(await(0,xo.stat)(e)).isDirectory()?"directory":"present"}catch(e){if("ENOENT"===_c(e))return"missing";throw e}}async function eD(e,t){const r=[];let n=e;for(let o=0;o<=t;o+=1){const t=await YM(n);if("directory"===t)return r.reverse(),r;if("present"===t)return await(0,xo.mkdir)(n,{recursive:!1}),r.reverse(),r;r.push(n);const o=(0,s.dirname)(n);if(o===n){const t=new Error(`ENOENT: no such file or directory, mkdir '${e}'`);throw t.code="ENOENT",t.syscall="mkdir",t.path=e,t}n=o}throw QM(e)}class tD{constructor(e,t,r,{workspacePaths:n,workspacePath:o,worktreeMainPath:s,projectDir:i,onWriteForAiTracking:a,writeFileMutationGuard:c,toolCallReads:l,agentFileViews:u}){this.fileChangeTracker=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.workspacePaths=n,this.workspacePath=o,this.worktreeMainPath=s,this.projectDir=i,this.onWriteForAiTracking=a,this.writeFileMutationGuard=c,this.toolCallReads=l,this.agentFileViews=u}async execute(e,t,r){if(function(e){if(!e.startsWith("file://"))return!1;try{return(0,Pd.fileURLToPath)(e),!1}catch{return!0}}(t.path))return new FI.v3({result:{case:"error",value:new FI.QM({path:t.path,error:`${t.path} is not a valid file URL. Use an absolute path instead.`})}});const n=(0,ts.o1)(t.path,this.workspacePath),o=this.toolCallReads,s=void 0!==o&&""!==t.toolCallId?o.take({toolCallId:t.toolCallId,resolvedPath:n}):void 0,i=!0===r?.refuseUnreadChanges?this.agentFileViews?.get(n):void 0,a={writeStarted:!1},c=()=>{void 0===s||a.writeStarted||o?.restore(s)};try{const r=await this.executeWithRecord(e,t,n,s?.recorded,i,a);return oD(r)&&c(),r}catch(e){throw c(),e}}async executeWithRecord(e,t,r,n,o,i){const a={stack:[],error:void 0,hasError:!1};try{const c=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(a,(0,D.VI)(e.withName("LocalWriteExecutor.execute")),!1).ctx,l=(t.path,t.fileText),u=t.fileBytes.length>0?t.fileBytes:void 0,d=["assets","agent-tools","swarm-agents"],h=SS(r,d)||void 0!==this.projectDir&&!this.workspacePaths.some((e=>{return t=e,n=r,jM&&(t=t.toLowerCase(),n=n.toLowerCase()),t===n||(t.charAt(t.length-1)!==s.sep&&(t+=s.sep),n.startsWith(t));var t,n}))&&kS(this.projectDir,r,d);if((0,ts.fl)({targetPath:r,workspacePaths:this.workspacePaths,mainWorktreePath:this.worktreeMainPath}))return new FI.v3({result:{case:"error",value:new FI.QM({path:r,error:ts.PS})}});let p,f,m,g,w=!1;try{const e=await(0,xo.stat)(r);if(g=511&e.mode,e.size<=ss){const e=await XM(c,"readText before write",3e3,(()=>Wi(r,t.encodingHint)));p=e.text,f=e.encoding,m=Hw(e)}else w=!0}catch(e){w="ENOENT"!==_c(e)}const y=await NS(r),v=y.resolvedPath;if(t.confineToWorkspace){let e=(await Promise.all(this.workspacePaths.map((e=>(0,xo.realpath)(e).catch((()=>{})))))).filter((e=>void 0!==e));if(0===e.length&&void 0!==this.projectDir){const t=await(0,xo.realpath)(this.projectDir).catch((()=>{}));void 0!==t&&(e=[t])}if(!e.some((e=>(0,ts.BJ)(v,e))))return new FI.v3({result:{case:"error",value:new FI.QM({path:r,error:"downloadPath must stay within the workspace"})}})}const b=async()=>{return await EM(n,v)?qT(r):(t=n,void 0!==(e=o)&&void 0!==t&&e.kind===t.kind&&("absent"===e.kind||"fingerprint"===t.kind&&e.byteLength===t.byteLength&&e.sha256===t.sha256)||!await EM(o,v)?void 0:zT(r));var e,t},S=t.planMode?await XM(c,"checkPlanModeWriteTarget",3e3,(()=>async function(e,t){switch(t.resolution.status){case"resolved":case"newFile":return NM(t.resolvedPath)?{allowed:!0}:await async function(e,t){if(!(LM(t.resolvedPath,UM)||LM(e,UM)&&t.resolvedPath===await async function(e){const t=(0,s.dirname)((0,s.dirname)((0,s.dirname)((0,s.dirname)(e)))),r=await NS(t);if(LS(r.resolution))return(0,s.join)(r.resolvedPath,(0,s.relative)(t,e))}(e)))return BM;if("newFile"===t.resolution.status)return{allowed:!0,singleLink:{kind:"create"}};const r=await async function(e){try{const t=await(0,xo.lstat)(e,{bigint:!0});return t.isFile()&&1n===t.nlink?{kind:"existing",dev:t.dev,ino:t.ino}:void 0}catch{return}}(t.resolvedPath);return void 0===r?BM:{allowed:!0,singleLink:r}}(e,t);case"danglingSymlink":{const e=await async function(e){let t=e;for(let e=0;e<40;e++){let e;try{e=await(0,xo.readlink)(t)}catch(e){const r=_c(e);return"ENOENT"===r||"EINVAL"===r?t:void 0}t=(0,s.resolve)((0,s.dirname)(t),e)}}(t.resolvedPath);return void 0!==e&&NM(e)?{allowed:!0}:BM}case"permissionDenied":case"symlinkLoop":case"unknownError":return BM;default:return t.resolution,BM}}(r,y))):void 0;if(void 0!==S&&!S.allowed)return new FI.v3({result:{case:"rejected",value:new FI.en({path:r,reason:"Cannot edit non markdown files in plan mode"})}});const k=(".cursorignore"===(r.split(s.sep).pop()?.toLowerCase()??"")?{type:"permissionsConfig"}:void 0)??await XM(c,"permissionsService.shouldBlockWrite",3e3,(()=>this.permissionsService.shouldBlockWrite(c,v,l)));if(k){const e=await XM(c,"handleBlockReason",3e3,(()=>ed(k,{onNeedsApproval:async(e,n)=>{const o="fileEdit"!==n?.type||n.isNewFile,s="fileEdit"===n?.type?n.diffString:l,i="fileEdit"===n?.type?n.blockReason:void 0,a=await b();if(void 0!==a)return rD(r,a);const c=await this.pendingDecisionProvider.requestApproval({type:Bw.Write,details:{path:r,reason:e,isNewFile:o,diffString:s,before:p,after:l,blockReason:i},toolCallId:t.toolCallId});return c.approved?null:new FI.v3({result:{case:"rejected",value:new FI.en({path:r,reason:c.reason||""})}})},onUserRejected:e=>new FI.v3({result:{case:"rejected",value:new FI.en({path:r,reason:e||""})}}),onPermissionDenied:(e,t)=>new FI.v3({result:{case:"permissionDenied",value:new FI.U7({path:r,error:e,isReadonly:t?.isReadonly??!1})}})})));if(null!==e)return e}const _=await XM(c,"anotherSpellingRefusal",3e3,(()=>async function(e){const t=(0,s.basename)(e);let r;try{if(!(await(0,xo.stat)(e)).isFile())return;const n=await(0,xo.readdir)((0,s.dirname)(e));if(n.includes(t))return;const o=t.normalize("NFC");if(n.some((e=>e.normalize("NFC")===o)))return;const i=t.toLowerCase(),a=n.filter((e=>e.toLowerCase()===i)),c=o.toLowerCase();r=a.length>0?a:n.filter((e=>e.normalize("NFC").toLowerCase()===c))}catch{return}const n=1===r.length?r[0]:void 0;return void 0===n?`${t} names an existing file that this folder lists under another name, so writing it would replace that file. Nothing was written. List the folder and write the file by its listed name to change it; for a new file, choose a different name.`:`${t} names the existing file ${n}: this volume does not tell names apart by case, so writing it would replace ${n}. Nothing was written. To change that file, write ${n}; for a new file, choose a name no file in this folder has in any case.`}(r)));if(void 0!==_)return new FI.v3({result:{case:"error",value:new FI.QM({path:r,error:_})}});const C=(0,s.dirname)(v);if(await xM(n,C))return rD(r,qT(r));if(await xM(o,C))return rD(r,zT(r));let E,x,P,R;try{E=await XM(c,"mkdir",3e3,(()=>async function(e){const t=function(e){let t=0,r=e;for(;;){const e=(0,s.dirname)(r);if(e===r)return t;t+=1,r=e}}(e),r=t+4;let n=0,o=0,i=await eD(e,t),a=0;for(;ar)throw QM(e);try{await(0,xo.mkdir)(c,{recursive:!1})}catch(r){const n=_c(r);if("EEXIST"===n){if("directory"!==await YM(c))throw r;a+=1;continue}if("ENOENT"===n){const n=(0,s.dirname)(c);if(n===c||"missing"!==await YM(n))throw r;i=await eD(e,t),a=0,o=0;continue}throw r}o+=1,a+=1}return o}(C)))}catch(e){const t=_c(e);return"EACCES"===t||"EPERM"===t?new FI.v3({result:{case:"permissionDenied",value:new FI.U7({path:r,directory:C,operation:"create_directory",error:"Permission denied"})}}):new FI.v3({result:{case:"error",value:new FI.QM({path:r,error:Cc(e)})}})}if(void 0!==u)x=u,P=0;else{const e=await XM(c,"getBufferForWrite",3e3,(()=>qi(r,l,this.workspacePath,t.encodingHint)));x=e.buffer,P=e.lines,R=e.format.encoding}const I=()=>XM(c,"writeFile",3e3,(async()=>{const e=await b();if(void 0!==e)throw new Error(e);let t;c.signal.throwIfAborted(),i.writeStarted=!0,await async function(e,t,r){const n=r?.singleLink,{fd:o}=void 0===n?await VM(e,Ro.constants.O_WRONLY|Ro.constants.O_CREAT,"write"):await async function(e,t){const r="create"===t.kind,n=r?Ro.constants.O_WRONLY|Ro.constants.O_CREAT|Ro.constants.O_EXCL:Ro.constants.O_WRONLY;let o;try{o=await VM(e,n,"write",{removeOnRefusal:r})}catch(t){const r=_c(t);if("EEXIST"===r||"ENOENT"===r)throw new WM(e,`Refusing to write: ${e} was ${"EEXIST"===r?"created":"removed"} after it was checked`);throw t}const{fd:s}=o;try{const r=await s.stat({bigint:!0});if(1n!==r.nlink)throw new WM(e,`Refusing to write: ${e} has ${r.nlink} hard links`);if("existing"===t.kind&&(r.dev!==t.dev||r.ino!==t.ino))throw new WM(e,`Refusing to write: ${e} was replaced after it was checked`);return o}catch(t){throw r&&await GM(e,s),await s.close(),t}}(e,n);try{await async function(e){for(let t=0;;t++)try{return void await e.truncate(0)}catch(e){const r=_c(e);if(t>=qM.length||void 0===r||!zM.has(r))throw e;await(0,Lg.setTimeout)(qM[t])}}(o);const e=function(e){return Buffer.isBuffer(e)?e:Buffer.from(e)}(t);let n=0;for(;n{try{await I()}catch(e){throw T=e,A=!0,e}};try{void 0===this.writeFileMutationGuard?await I():await this.writeFileMutationGuard.runExclusive(v,$)}catch(e){if(void 0!==this.writeFileMutationGuard&&(!A||e!==T))return new FI.v3({result:{case:"error",value:new FI.QM({path:r,error:e instanceof Error?e.message:String(e)})}});if(e instanceof WM)return new FI.v3({result:{case:"permissionDenied",value:new FI.U7({path:r,directory:"",operation:"create_file",error:e.message})}});const t=_c(e);return"EACCES"===t||"EPERM"===t?new FI.v3({result:{case:"permissionDenied",value:new FI.U7({path:r,directory:"",operation:"create_file",error:"Permission denied"})}}):"ENOSPC"===_c(e)?new FI.v3({result:{case:"noSpace",value:new FI.bM({path:r})}}):"EDQUOT"===t?new FI.v3({result:{case:"error",value:new FI.QM({path:r,error:"Agent-store quota exceeded: this write was rejected because the storage quota is full. Nothing was written; your local copy is intact. Delete or truncate files to free space (including resolved *.conflict* files), then retry. Do not retry the same write without freeing space first."})}}):new FI.v3({result:{case:"error",value:new FI.QM({path:r,error:Cc(e)})}})}if(this.fileChangeTracker&&void 0===u&&!h&&!w){const e={...t.toolCallId?{toolCallId:t.toolCallId}:{},...v===r?{}:{writtenPath:v},...void 0===g?{}:{beforeMode:g},...E>0?{createdDirectories:E}:{}};await this.fileChangeTracker.trackChange(r,p,l,e,m)}if(this.onWriteForAiTracking&&void 0===u&&!h){const e=t.toolCallId?{toolCallId:t.toolCallId}:{};try{await this.onWriteForAiTracking({path:r,beforeContent:p,afterContent:l,metadata:e})}catch(e){JM.warn(c,"onWriteForAiTracking failed (write succeeded)",{path:r,error:e instanceof Error?e.message:String(e)})}}const M=x.byteLength;let O;if(void 0!==u||w||h||this.recordEncodingChecks(c,r,p,f,l),t.returnFileContentAfterWrite)try{O=await XM(c,"readText after write",3e3,(()=>Bi(r,t.encodingHint)))}catch{}return new FI.v3({result:{case:"success",value:new FI.j6({path:r,linesCreated:P,fileSize:M,...void 0!==O&&{fileContentAfterWrite:O}})}})}catch(e){a.error=e,a.hasError=!0}finally{KM(a)}}recordEncodingChecks(e,t,r,n,o){try{const i={path:t,encoding:n,pages:(s=yu.pages(),"failed"===s?"none":s)};for(const t of function(e,t,r){return[yl(e,t,r),vl(e,t,r)]}(r,n,o))ZM.increment(e,1,El(t,i))}catch(t){for(const t of dl)ZM.increment(e,1,{detector:t,outcome:"error",file:"unclassified"});JM.warn(e,"encoding check failed (write succeeded)",{error:t instanceof Error?t.message:String(t)})}var s}}function rD(e,t){return new FI.v3({result:{case:"error",value:new FI.QM({path:e,error:t})}})}class nD extends Error{constructor(e){super("stale write refusal"),this.result=e,this.name="StaleWriteRefusal"}}function oD(e){if("error"!==e.result.case)return!1;const{error:t,path:r}=e.result.value;return t===qT(r)||t===zT(r)}const sD=(0,d.h)("local-exec:provider"),iD=new Set,aD=new bd.AsyncLocalStorage;class cD extends Z{getMcpExecutionPolicyDeps(){return{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionStore}}static dropOwnedRequestContextCaches(){for(const e of iD)e.ownedRequestContextExecutor?.invalidateGlobalCache()}static rebuildRequestContextCachesFor(e){for(const t of iD)t.cursorRulesService===e&&t.ownedRequestContextExecutor?.refreshGlobalCache()}constructor(e){super(),this.pendingDecisionStore=e.pendingDecisionStore,this.fileChangeTracker=e.fileChangeTracker,this.gitExecutor=e.gitExecutor,this.ignoreService=e.ignoreService,this.grepProvider=e.grepProvider,this.permissionsService=e.permissionsService,this.workspacePaths=e.workspacePaths,this.worktreeMainPath=e.worktreeMainPath,this.diagnosticsProvider=e.diagnosticsProvider,this.mcpLease=e.mcpLease,this.mcpStateAccessor=e.mcpStateAccessor,this.cursorRulesService=e.cursorRulesService,this.cloudRulesService=e.cloudRulesService,this.subagentsService=e.subagentsService,this.repositoryProvider=e.repositoryProvider,this.projectDir=e.projectDir,this.shellManager=e.shellManager,this._sandboxPolicyResolver=e._sandboxPolicyResolver,this._defaultSandboxPolicy=e._defaultSandboxPolicy??{type:"insecure_none"};const t=e.workspacePaths[0],r=t?function(e){const t=(0,s.join)(e,".cursor/sandbox.json");try{const r=(0,Ro.readFileSync)(t,"utf-8"),n=JSON.parse(r),o=(0,No.$6)(n);return(0,No.l7)(o,e)}catch{return}}(t):void 0,n=e._defaultSandboxPolicySources;this._defaultSandboxPolicySources=r||n?{perUser:n?.perUser,perRepo:r??n?.perRepo,teamAdmin:n?.teamAdmin}:void 0,this.mcpFileOutputThresholdBytes=e.mcpFileOutputThresholdBytes,this.blankSharedPaymentTokensInMcpOutputFiles=!0===e.blankSharedPaymentTokensInMcpOutputFiles,this.backgroundShellFactory=e.backgroundShellFactory,this.backgroundWorkRegistry=e.backgroundWorkRegistry,this.wakeupOwnerConversationId=e.wakeupOwnerConversationId,this.mcpElicitationFactory=e.mcpElicitationFactory,this.createFileWatcher=e.createFileWatcher,this.sharedRequestContextExecutor=e.sharedRequestContextExecutor,this.terminalExecutor=e.terminalExecutor,this.mcpMetaToolEnabled=e.mcpMetaToolEnabled??!1,this.mcpMetaToolSlimDescriptors=e.mcpMetaToolSlimDescriptors??!1,this.mcpInputSchemaJson=e.mcpInputSchemaJson??!1,this.alwaysExposeVirtualMcpAuthTool=e.alwaysExposeVirtualMcpAuthTool??!1,this.enableRecordScreen=e.enableRecordScreen??!1,this.recordScreenArtifactsDir=e.recordScreenArtifactsDir,this.recordScreenDisplay=e.recordScreenDisplay,this.disableRecordScreenRendering=e.disableRecordScreenRendering??!1,this.userTerminalHint=e.userTerminalHint,this.attributionConfigProvider=e.attributionConfigProvider,this.isAttributionDisabledByAdmin=e.isAttributionDisabledByAdmin,this.getAgentSkills=e.getAgentSkills,this.getSmartModeClassifierAutoModeEnabled=e.getSmartModeClassifierAutoModeEnabled,this.getAdminCommandDenylist=e.getAdminCommandDenylist,this.devForceNextSmartModeClassifierBlockToken=e.devForceNextSmartModeClassifierBlockToken,this.getMockPromptTime=e.getMockPromptTime,this.additionalRules=e.additionalRules??[],this.askpassConfig=e.askpassConfig,this.rebuildRequestContextOnRulesChange=!0===e.rebuildRequestContextOnRulesChange;const i=this.terminalExecutor??(0,No.Fn)({env:{CURSOR_AGENT:"1"},userTerminalHint:this.userTerminalHint,isLoginShellEnabled:e.isLoginShellEnabled});let a;if(this.workspacePaths.length>1){const e=this.workspacePaths.map((e=>(0,s.dirname)(e)));a=e.every((t=>t===e[0]))?e[0]:void 0}else a=t;let c=new Xu(i,t??(0,o.homedir)(),this.projectDir,{shellOutputBackpressureOptions:e.shellOutputBackpressureOptions,extraEnvProvider:e.shellExtraEnvProvider,powershellUtf8Console:e.powershellUtf8Console,powershellUtf8ChildEnv:e.powershellUtf8ChildEnv,powershellParseAfterUtf8Switch:e.powershellParseAfterUtf8Switch,powershellWebRequestUtf8:e.powershellWebRequestUtf8,powershellPerLineStateDump:e.powershellPerLineStateDump,encodingSlices:e.encodingSlices,keepBackgroundJobs:e.keepShellBackgroundJobs});e.shellCoreWrapper&&(c=e.shellCoreWrapper(c)),this.askpassConfig&&(c=new Yu(c,this.askpassConfig)),this.shellManager&&(c=new Qu(c,this.shellManager));const l=e.overrideShellExecutor??(!0===e.suppressDefaultShellExecutor?void 0:new pM(this.permissionsService,c,this.ignoreService,this.pendingDecisionStore));void 0!==l&&this.register(WT,Fg(l)),this.register(HT,Fg(new BT(this.permissionsService,this.ignoreService,a??t??this.projectDir)));const u=new _M,d=new CM,h=e.overrideWriteExecutor??new tD(this.fileChangeTracker,this.permissionsService,this.pendingDecisionStore,{workspacePaths:this.workspacePaths,workspacePath:a,worktreeMainPath:this.worktreeMainPath,projectDir:this.projectDir,onWriteForAiTracking:e.onWriteForAiTracking,writeFileMutationGuard:e.writeFileMutationGuard,toolCallReads:u,agentFileViews:d});this.register(GT,function(e){const t=(r={execute:(t,r,n)=>e.execute(t,r,n).then((e=>{if(oD(e))throw new nD(e);return e}))},Fg(r));var r;return{async execute(e,r,n){try{return await t.execute(e,r,n)}catch(e){if(e instanceof nD)return e.result;throw e}}}}(h));const p=e.overrideDeleteExecutor??new Gw(this.pendingDecisionStore,this.fileChangeTracker,this.permissionsService,a,e.onDeleteForAiTracking,d);this.register(VT,Fg(p)),this.register(KT,Fg(new Qw({encodingSlices:e.encodingSlices}))),this.register(JT,new P$);const f=this.mcpStateAccessor??new aM(this.mcpLease),m=e.overrideGrepExecutor??new fC(this.ignoreService,this.grepProvider,this.workspacePaths,{mcpStateAccessor:f,permissionsService:this.permissionsService,useStreamingGrep:e.useStreamingGrep,encodingSlices:e.encodingSlices});this.register(ZT,Fg(m));const g=e.overrideReadExecutor??new PM(new B_(this.permissionsService,a,{mcpStateAccessor:f,useStreamingRead:e.useStreamingRead,pendingDecisionProvider:this.pendingDecisionStore,encodingSlices:e.encodingSlices}),u,this.permissionsService,a,d),w=new eA(g);this.register(tA,w),e.registerRedactedReadExecutor&&this.register(rA,w);const y=e.overrideLsExecutor??new SC(this.permissionsService,this.ignoreService,a);this.register(nA,Fg(y)),this.register(oA,Fg(new zA(a,this.diagnosticsProvider))),e.getCanvasDiagnostics&&this.register(sA,Fg(new LA(e.getCanvasDiagnostics,e.beginCanvasSave))),this.register(ro,Fg(new SA(ou(new TT(this.mcpLease,this.permissionsService,this.pendingDecisionStore,this.projectDir,this.mcpFileOutputThresholdBytes,this.mcpElicitationFactory,e.ensureMcpServersLoaded,{blankSharedPaymentTokens:this.blankSharedPaymentTokensInMcpOutputFiles}),e.encodingSlices,"exec_mcp",(e=>"success"===e.result.case)),(()=>this.get(tA))))),this.register(no,Fg(new AT(this.mcpLease,e.ensureMcpServersLoaded))),this.register(oo,Fg(ou(new $T(this.mcpLease,a||this.projectDir,this.permissionsService,this.workspacePaths,this.pendingDecisionStore,e.ensureMcpServersLoaded,h),e.encodingSlices,"exec_mcp",(e=>"success"===e.result.case)))),this.register(so,Fg(new lM(f,e.ensureMcpServersLoaded,{filterToRequestedServers:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,...void 0===e.mcpServerRuleSubjects?{}:{serverRuleSubjects:e.mcpServerRuleSubjects}})));const v=this.sharedRequestContextExecutor??this.createOwnedRequestContextExecutor(f,t,e),b=Fg({execute:(e,t,r)=>{const n=aD.getStore();return void 0!==n&&(n.ran=!0),v.execute(e,t,r)}});this.register(Dr,{execute:async(t,r,n)=>{const o={ran:!1},s=await aD.run(o,(()=>b.execute(t,r,n)));if("success"!==s.result.case||void 0===s.result.value.requestContext)return s;const i=s.clone();if("success"!==i.result.case)return s;const a=i.result.value.requestContext;if(void 0===a)return i;const c=await f.getState(t),l=nM(c,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson});if(a.tools=l.tools,a.mcpInstructions=l.mcpInstructions,a.mcpMetaToolOptions=this.mcpMetaToolEnabled?oM(c,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,slimDescriptors:this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}):void 0,o.ran&&void 0!==e.getMcpFileSystemOptions||(a.mcpFileSystemOptions=await(e.getMcpFileSystemOptions?.(t))),void 0!==a.env&&(a.env.artifactsFolder=e.getArtifactsFolder?.(t),void 0!==e.getSandboxEnabled&&(a.env.sandboxEnabled=e.getSandboxEnabled()),void 0!==e.getSessionSandboxSupported&&(a.env.sandboxSupported=e.getSessionSandboxSupported())),void 0!==e.getMountedAgentStores&&void 0!==a.env)try{const r=await e.getMountedAgentStores(t);a.env.mountedAgentStores=r.map((e=>e.clone()))}catch{a.env.mountedAgentStores=[],sD.warn(t,"Failed to get mounted agent stores; continuing without prompt inventory")}return i}}),this.backgroundShellExecutor=new vd(this.permissionsService,c,this.ignoreService,this.projectDir,this.backgroundShellFactory,this.backgroundWorkRegistry,this.wakeupOwnerConversationId,e.backgroundShellManager),this.shellRedeliveryCaches=e.shellRedeliveryCaches??{backgroundShell:Og(),shellStream:Og(),writeStdin:Og()},this.register(kA,Fg(this.backgroundShellExecutor,void 0,this.shellRedeliveryCaches.backgroundShell)),this.shellStreamExecutor=new SM(this.permissionsService,c,this.ignoreService,this.backgroundShellExecutor.getManager()),this.register(re,function(e,t,r=Og(t)){return{async*execute(t,n,o){if(!o?.execId)return void(yield*e.execute(t,n,o));const s=Dg(o.execId,n),i=r.get(s);if(i)return void(yield*i.fork());const a=e.execute(t,n,o),c=new Mg(a);r.set(s,c),yield*c.fork()}}}(this.shellStreamExecutor,void 0,this.shellRedeliveryCaches.shellStream)),void 0!==e.agentStoreConflictDrainer&&this.register(CA,new DA(e.agentStoreConflictDrainer)),this.register(EA,new mM(this.permissionsService)),this.register(xA,new I$(this.permissionsService)),this.register(PA,new DM(this.permissionsService));const S=new gM(this.shellStreamExecutor);this.register(RA,Fg(S));const k=!1===e.enableWriteBackgroundShellStdin?new OA((async()=>{throw new Error(e.writeBackgroundShellStdinDisabledReason??"write_shell_stdin is disabled for this session")})):new OA(((e,t)=>this.backgroundShellExecutor.writeStdin(e,t)));if(this.register(_A,Fg(k,void 0,this.shellRedeliveryCaches.writeStdin)),e.computerUseExecutor&&(this.computerUseExecutor=e.computerUseExecutor,this.register(IA,Fg(this.computerUseExecutor)),void 0!==e.computerUseEndTurnExecutor&&this.register(TA,e.computerUseEndTurnExecutor)),this.enableRecordScreen){if(!this.recordScreenArtifactsDir||!this.recordScreenDisplay)throw new Error("recordScreenArtifactsDir and recordScreenDisplay are required when enableRecordScreen is true");this.recordScreenExecutor=new j$({artifactsDir:this.recordScreenArtifactsDir,display:this.recordScreenDisplay,disablePolishedRendering:this.disableRecordScreenRendering,polishedRenderer:e.polishedRecordingRenderer}),this.register(AA,Fg(this.recordScreenExecutor))}}createOwnedRequestContextExecutor(e,t,r){const n=new uM(this.cursorRulesService,this.cloudRulesService,this.subagentsService,this.repositoryProvider,this.grepProvider,e,this.gitExecutor,void 0===r.requestContextWorkspacePaths?this.workspacePaths:[...r.requestContextWorkspacePaths],{projectDir:this.projectDir,isWorkingDirHomeDir:r.requestContextIsWorkingDirHomeDir??(0,ts.yn)(t,(0,o.homedir)()),agentNotesEnabled:r.agentNotesEnabled,reportProcessWorkingDirectory:r.reportProcessWorkingDirectory,sectionLoadTimeoutMs:r.requestContextSectionLoadTimeoutMs,reportSectionCompleteness:r.reportRequestContextSectionCompleteness,freshSectionWaitMs:r.requestContextFreshSectionWaitMs,createFileWatcher:this.createFileWatcher,getSandboxEnabled:r.getSandboxEnabled,getSandboxSupported:r.getSandboxSupported,getNetworkAllowlistInfo:r.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:this.getSmartModeClassifierAutoModeEnabled,getAdminCommandDenylist:this.getAdminCommandDenylist,devForceNextSmartModeClassifierBlockToken:this.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:this.getMockPromptTime,userTerminalHint:this.userTerminalHint,getMcpFileSystemOptions:r.getMcpFileSystemOptions,mcpMetaToolEnabled:this.mcpMetaToolEnabled,mcpMetaToolSlimDescriptors:this.mcpMetaToolSlimDescriptors,mcpInputSchemaJson:this.mcpInputSchemaJson,alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,getArtifactsFolder:r.getArtifactsFolder,secretRedactionEnabled:r.secretRedactionEnabled,attributionConfigProvider:this.attributionConfigProvider,isAttributionDisabledByAdmin:this.isAttributionDisabledByAdmin,getAgentSkills:this.getAgentSkills,additionalRules:this.additionalRules,getComputerUseSupported:()=>void 0!==this.computerUseExecutor,getComputerUseDesktop:r.getComputerUseDesktop,onRequestContext:r.onRequestContext,mcpFieldsFromCaller:!0===r.requestContextMcpFieldsFromOverlay,deferWarmup:!0===r.deferRequestContextWarmup});return!0===r.deferRequestContextWarmup&&(this.requestContextExecutorAwaitingWarmup=n),this.rebuildRequestContextOnRulesChange&&(this.ownedRequestContextExecutor=n,iD.add(this),this.disposeRulesChangeListener=this.cursorRulesService.onDidChangeRules?.((()=>{n.rebuildAllCaches()}))),n}warmRequestContext(){const e=this.requestContextExecutorAwaitingWarmup;this.requestContextExecutorAwaitingWarmup=void 0,e?.warm()}getRecordScreenExecutor(){return this.recordScreenExecutor}getBackgroundShellManager(){return this.backgroundShellExecutor.getManager()}getShellRedeliveryCaches(){return this.shellRedeliveryCaches}hasForegroundShells(){return this.shellStreamExecutor.hasForegroundWork()}withPendingShells(e){return new X(e,[K(re,this.shellStreamExecutor.pendingFrom(e))])}async dispose(){this.requestContextExecutorAwaitingWarmup=void 0,this.rebuildRequestContextOnRulesChange&&(iD.delete(this),this.disposeRulesChangeListener?.(),this.disposeRulesChangeListener=void 0,this.ownedRequestContextExecutor?.dispose(),this.ownedRequestContextExecutor=void 0),this.backgroundShellExecutor.dispose(),this.recordScreenExecutor&&await this.recordScreenExecutor.dispose()}}function lD(e){return e.replace(/\\/g,"/")}function uD(e,t){for(const r of t){const t=lD(r);if(e===t||e.startsWith(`${t}/`))return!0}return!1}var dD;function hD(e,t,r){if(function(e){return Boolean(e.plugin?.trim()||e.pluginId?.trim()||e.marketplaceId?.trim())}(e))return dD.Plugin;const n=lD(e.fullPath);return uD(n,r.builtinDirs)?dD.Builtin:Um(e.fullPath,t).inAgentStore?dD.UserStore:uD(n,r.userDirs)?dD.UserHome:(uD(n,r.workspaceDirs),dD.Workspace)}"function"==typeof SuppressedError&&SuppressedError,function(e){e[e.Builtin=0]="Builtin",e[e.UserStore=1]="UserStore",e[e.UserHome=2]="UserHome",e[e.Workspace=3]="Workspace",e[e.Plugin=4]="Plugin"}(dD||(dD={}));var pD=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const fD=(0,Vs.debuglog)("merged-agent-skills"),mD=(0,d.h)("merged-agent-skills");class gD{constructor(e,t=()=>[],r){this.services=e,this.getDisabledManagedSkillPaths=t,this.getPromptSortContext=r,this.onChangeCallbacks=new Set}async getAllAgentSkills(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,D.VI)(e.withName("MergedAgentSkillsService.getAllAgentSkills")),!1),n=this.services.map((e=>e.getAllAgentSkills(r.ctx).catch((e=>(fD("Failed to load agent skills from service: %s",e instanceof Error?e.message:String(e)),[]))))),o=async()=>{try{return{ok:!0,paths:await this.getDisabledManagedSkillPaths()}}catch(e){return mD.warn(r.ctx,"getDisabledManagedSkillPaths failed; failing closed by dropping all managed skills for this call",{error:e instanceof Error?e.message:String(e)}),{ok:!1}}},[i,a]=await Promise.all([Promise.all(n),o()]),c=i.flat(),l=this.getPromptSortContext?.(),u=Wm(c,l??Lm);let d=u;return a.ok?a.paths.length>0&&(d=u.filter((e=>!function(e,t){if(!e)return!1;const r=e.replace(/\\/g,"/");return t.some((e=>r.endsWith(e)))}(e.fullPath,a.paths)))):d=u.filter((e=>{return!((t=e.fullPath)&&t.replace(/\\/g,"/").includes(wD));var t})),void 0!==l?function(e,t){if(e.length<=1)return e;const r=function(e){const t=[bm(e.userHomeDirectory).dirPath],r=Pm(e.userHomeDirectory,!0).map((e=>e.dirPath)),n=[];for(const t of e.workspacePaths){n.push((0,s.join)(t,".cursor","rules"));for(const e of xm(t,!0))n.push(e.dirPath)}return{builtinDirs:t,userDirs:r,workspaceDirs:n}}(t),n=e.map(((e,n)=>({skill:e,index:n,tier:hD(e,t,r)})));return n.sort(((e,t)=>e.tier-t.tier||e.index-t.index)),n.map((e=>e.skill))}(d,l):d}catch(e){t.error=e,t.hasError=!0}finally{pD(t)}}reload(e){for(const t of this.services)t.reload(e)}scheduleDidChangeSkills(){void 0===this.changeTimer&&(this.changeTimer=setTimeout((()=>{this.changeTimer=void 0;for(const e of Array.from(this.onChangeCallbacks))e()}),gD.CHANGE_COALESCE_MS))}ensureChangeListenersRegistered(){void 0===this.disposeChangeListeners&&(this.disposeChangeListeners=this.services.map((e=>e.onDidChangeSkills((()=>this.scheduleDidChangeSkills())))))}disposeChangeListenersIfUnused(){if(!(this.onChangeCallbacks.size>0||void 0===this.disposeChangeListeners)){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0,void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0)}}onDidChangeSkills(e){return this.onChangeCallbacks.add(e),this.ensureChangeListenersRegistered(),()=>{this.onChangeCallbacks.delete(e),this.disposeChangeListenersIfUnused()}}dispose(){if(void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0),this.onChangeCallbacks.clear(),void 0!==this.disposeChangeListeners){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0}for(const e of this.services)e.dispose()}}gD.CHANGE_COALESCE_MS=1500;const wD=`/${mm.configDir}/${mm.subdir}/`;function yD(e,t){if((e.disabledEnvironments??[]).includes(t))return!1;const r=e.environments??[];return 0===r.length||r.includes(t)}const vD=(0,d.h)("skill-sync-manifest"),bD=".sync-manifest.json",SD=new Set(["EPERM","EBUSY"]),kD=[20,50,100],_D=new Map;async function CD(e,t){try{const r=await(0,xo.readFile)((0,s.join)(e,bD),"utf-8"),n=JSON.parse(r);return function(e){if(!function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e))return!1;const t=e;return"number"==typeof t.version&&"object"==typeof t.skills&&null!==t.skills&&!Array.isArray(t.skills)&&(void 0===t.lastInventoryAt||"number"==typeof t.lastInventoryAt)}(n)?n:(vD.warn(t,"Manifest failed schema validation, resetting",{skillDir:e}),{version:1,skills:{}})}catch(r){return r instanceof Error&&"ENOENT"===_c(r)||vD.debug(t,"Failed to read sync manifest, resetting",{skillDir:e,error:String(r)}),{version:1,skills:{}}}}function ED(e,t,r){e.skills[t]={lastSyncedAt:r}}function xD(e,t){delete e.skills[t]}var PD=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const RD=(0,d.h)("builtin-skills-sync");function ID(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function TD(e){for(const t of Object.keys(e.resources??{}))if(0===t.length||t.includes("\\")||t.includes("\0")||s.posix.isAbsolute(t)||s.posix.normalize(t)!==t||t.split("/").includes("..")||"SKILL.md"===s.posix.basename(t)||!t.endsWith(".md"))throw new Error(`Unsafe managed skill resource path: ${JSON.stringify(t)}`)}function AD(e){const t=rh(e.content),r=ID(t.data)?t.data:{};return nh(`${t.content.trim()}\n`,function(e,t){const r={...t??{},name:e.id,description:e.description};delete r.disabledEnvironments,e.disableModelInvocation?r["disable-model-invocation"]=!0:delete r["disable-model-invocation"],e.environments&&e.environments.length>0?r.environments=e.environments:delete r.environments,e.disabledEnvironments&&e.disabledEnvironments.length>0?r["disabled-environments"]=e.disabledEnvironments:delete r["disabled-environments"];const n={...ID(r.metadata)?r.metadata:{}};return delete n.environments,delete n.disabledEnvironments,delete n["disabled-environments"],Object.keys(n).length>0?r.metadata=n:delete r.metadata,r}(e,r))}async function $D(e,t,r){const n=(0,s.join)(t,r.id),o=(0,s.join)(n,"SKILL.md"),i=r.fileContent,a=Object.keys(r.resources),c=await MD(n);if(a.length>0||c.length>0){const e=new Map([["SKILL.md",i],...Object.entries(r.resources)]),o=new Set(["SKILL.md",...c]);if(o.size===e.size&&[...e.keys()].every((e=>o.has(e)))){let t=!0;for(const[r,o]of e)try{if(await(0,xo.readFile)((0,s.join)(n,...r.split("/")),"utf-8")!==o){t=!1;break}}catch{t=!1;break}if(t)return!1}return await async function(e,t){const r=(0,s.join)(e,t.id),n=await(0,xo.mkdtemp)((0,s.join)(e,`.${t.id}-staging-`)),o=`${n}-backup`;let i=!1;try{await(0,xo.writeFile)((0,s.join)(n,"SKILL.md"),t.fileContent,"utf-8");for(const[e,r]of Object.entries(t.resources)){const t=(0,s.join)(n,...e.split("/"));await(0,xo.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,xo.writeFile)(t,r,"utf-8")}try{await(0,xo.rename)(r,o),i=!0}catch(e){if(!(e instanceof Error)||"ENOENT"!==_c(e))throw e}try{await(0,xo.rename)(n,r)}catch(e){throw i&&(await(0,xo.rename)(o,r),i=!1),e}i&&(await(0,xo.rm)(o,{recursive:!0,force:!0}),i=!1)}finally{await(0,xo.rm)(n,{recursive:!0,force:!0})}}(t,r),!0}try{if(await(0,xo.readFile)(o,"utf-8")===i)return!1}catch(t){t instanceof Error&&"ENOENT"===_c(t)||RD.warn(e,"Unexpected error reading skill file",{skillId:r.id,error:String(t)})}return await(0,xo.mkdir)(n,{recursive:!0}),await(0,xo.writeFile)(o,i,"utf-8"),!0}async function MD(e,t=""){const r=t?(0,s.join)(e,...t.split("/")):e;let n;try{n=await(0,xo.readdir)(r,{withFileTypes:!0})}catch(e){if(e instanceof Error&&"ENOENT"===_c(e))return[];throw e}const o=[];for(const r of n){const n=t?`${t}/${r.name}`:r.name;r.isDirectory()?o.push(...await MD(e,n)):r.isFile()&&r.name.endsWith(".md")&&"SKILL.md"!==n&&o.push(n)}return o}async function DD(e,t){try{return(await(0,xo.readdir)(t,{withFileTypes:!0})).filter((e=>e.isDirectory()&&!e.name.startsWith("."))).map((e=>e.name))}catch(r){return r instanceof Error&&"ENOENT"===_c(r)||RD.warn(e,"Failed to list skills directory, skipping cleanup",{skillDir:t,error:String(r)}),[]}}async function OD(e,t={}){const r={stack:[],error:void 0,hasError:!1};try{const i=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,D.VI)(e.withName("syncBuiltinSkills")),!1).ctx,a=Date.now(),c=t.userHome??(0,o.homedir)(),l=t.skillDir??bm(c).dirPath;await(0,xo.mkdir)(l,{recursive:!0});const[u,d]=await Promise.all([CD(l,i),DD(i,l)]),h=u.lastInventoryAt;(void 0===h||a-h>=864e5)&&(await async function(e,t,r,n){try{const o=await Promise.all(r.map((async e=>{const r=(0,s.join)(t,e),[o,i]=await Promise.all([FD((0,s.join)(r,"SKILL.md")),"canvas"===e?FD((0,s.join)(r,"sdk")):Promise.resolve(!1)]);return{skill_id:e,has_skill_md:o,has_sdk_dir:i,last_synced_at:n.skills[e]?.lastSyncedAt??null}})));RD.info(e,"managed_skills.startup_inventory",{skills_on_disk:o,manifest_present:Object.keys(n.skills).length>0})}catch(t){RD.warn(e,"Failed to emit managed skills startup inventory",{error:String(t)})}}(i,l,d,u),u.lastInventoryAt=a);const p=new Map;for(const e of t.managedSkills??[])(n=e.id)&&n===n.trim()&&!(n.includes("..")||n.includes("/")||n.includes("\\"))?p.set(e.id,e):RD.warn(i,"Skipping managed skill with unsafe id",{skillId:e.id});const f=void 0===t.canvasKit?void 0:km(c,t.canvasKit).dirPath,m=void 0!==f&&await FD((0,s.join)(f,Sm)),g=new Set([...p.keys(),...d,...m?[Sm]:[]]),w=e=>void 0!==f&&e===Sm?f:l,y=e=>void 0!==f&&e===Sm?m:d.includes(e);let v=0,b=0;const S=[];for(const e of g)try{const t=p.get(e),r=u.skills[e],n=r?a-r.lastSyncedAt:0,o=void 0!==r&&n>2592e5,c=void 0!==t&&yD(t,"local"),d=void 0!==t&&!c,h=void 0!==r||y(e),f=w(e);if(t&&!1!==t.enabled&&c)TD(t),f!==l&&await(0,xo.mkdir)(f,{recursive:!0}),await $D(i,f,{id:e,fileContent:AD(t),resources:t.resources??{}})?v++:b++,ED(u,e,a);else if(!1===t?.enabled||d||o){const n=!1===t?.enabled?"enabled_false":d?"environment_ineligible":"grace_expired";await(0,xo.rm)((0,s.join)(f,e),{recursive:!0,force:!0}),xD(u,e),h&&(S.push(e),RD.info(i,"managed_skills.removed",{skill_id:e,reason:n,server_enabled:t?.enabled??null,had_manifest_entry:void 0!==r,last_synced_ms_ago:r?a-r.lastSyncedAt:null}))}else r||ED(u,e,a)}catch(t){RD.warn(i,"Failed to apply skill, will retry next sync",{skillId:e,error:String(t)})}try{await function(e,t){const r=(_D.get(e)??Promise.resolve()).then((()=>async function(e,t){const r=(0,s.join)(e,`${bD}.${process.pid}.${(0,ko.randomBytes)(6).toString("hex")}.tmp`);await(0,xo.mkdir)(e,{recursive:!0});try{await(0,xo.writeFile)(r,JSON.stringify(t,null,2),"utf-8"),await async function(e,t){for(let r=0;;r++)try{return void await(0,xo.rename)(e,t)}catch(e){const t=_c(e),n=kD[r];if(void 0===n||void 0===t||!SD.has(t))throw e;await(0,Nr.cb)(n)}}(r,(0,s.join)(e,bD))}catch(e){throw await(0,xo.rm)(r,{force:!0}).catch((()=>{})),e}}(e,t))),n=r.catch((()=>{}));return _D.set(e,n),n.then((()=>{_D.get(e)===n&&_D.delete(e)})),r}(l,u)}catch(e){!function(e){if(e instanceof Error&&"ENOENT"===_c(e))return!0;const t=String(e);return t.includes("ENOENT")||t.includes("no such file or directory")}(e)?RD.warn(i,"Failed to persist sync manifest",{skillDir:l,error:String(e)}):RD.debug(i,"Skipped persisting sync manifest, path removed concurrently",{skillDir:l,error:String(e)})}return{synced:v,upToDate:b,removed:S}}catch(e){r.error=e,r.hasError=!0}finally{PD(r)}var n}async function FD(e){try{return await(0,xo.stat)(e),!0}catch(e){const t=_c(e);if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}const ND=(0,d.h)("managed-skills-sync");function LD(e,t,r,n,o,s){const i=[],a=e.mcpServers;if(!a)return i;for(const[e,c]of Object.entries(a)){const a=c,l=`plugin-${n}-${e}`,u=e;a.url?i.push({identifier:l,name:u,marketplace:t,marketplaceId:r,pluginName:n,pluginId:o,pluginSource:s,type:"streamableHttp",url:a.url,headers:a.headers,auth:a.auth,tls:a.tls,enabledTools:a.enabledTools,placement:a.placement,projectManaged:!1,pluginManaged:!0}):a.command&&i.push({identifier:l,name:u,marketplace:t,marketplaceId:r,pluginName:n,pluginId:o,pluginSource:s,type:"stdio",command:a.command,args:a.args??[],env:a.env??{},cwd:a.cwd,envFile:a.envFile,enabledTools:a.enabledTools,projectManaged:!1,pluginManaged:!0})}return i}function jD(e){try{const t=new URL(e),r=new URL(t.pathname,t.origin);return r.search=t.search,r.pathname.endsWith("/")&&r.pathname.length>1&&(r.pathname=r.pathname.slice(0,-1)),"/"===r.pathname?r.origin+r.search:r.toString()}catch{return e.toLowerCase().trim()}}class UD{constructor(e){this.pluginsService=e}async getPluginMcpServers(){const e=await this.pluginsService.reload(),t=[];for(const r of e){const e="marketplace"in r.identifier.sourceInfo?r.identifier.sourceInfo.marketplace:void 0,n="marketplaceDbId"in r.identifier.sourceInfo?r.identifier.sourceInfo.marketplaceDbId:void 0,o=r.identifier.sourceInfo.name,s="pluginDbId"in r.identifier.sourceInfo?r.identifier.sourceInfo.pluginDbId:void 0,i=r.mcpConfig;i&&t.push(...LD(i,e,n,o,s,r.identifier.source))}return function(e){const t=[],r=new Set;for(const n of e){if("streamableHttp"!==n.type||!n.url){t.push(n);continue}const e=jD(n.url);r.has(e)||(r.add(e),t.push(n))}return t}(t)}}var BD=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function WD(e,t){return void 0===e?[]:(Array.isArray(e)?e:[e]).map((e=>({...e,userHomeDir:t})))}class HD{constructor(e,t,r,n,o,s){this.workspacePaths=e,this.userHomeDirectory=t,this.getSettings=r,this.marketplaceOptions=n,this.localPluginVariablesLookup=s,this.plugins=[],this._loadFailures=[],this._pluginSetIncomplete=!0,this._retainedFromPreviousLoad=0,this._wasFirstLoad=!0,this.loadedOnce=!1,this._extensionPlugins=new Map,this._extensionPluginOriginalPaths=new Map,this.pluginLogger=o??$p,this.reload()}async getAllEnabledPlugins(){return await this.ensureLoaded(),[...this.plugins]}getLoadFailures(){return[...this._loadFailures]}isPluginSetIncomplete(){return this._pluginSetIncomplete}getLoadDiagnostics(){return{userHomeDirectory:this.userHomeDirectory,pluginsLoaded:this.plugins.length,retainedFromPreviousLoad:this._retainedFromPreviousLoad,wasFirstLoad:this._wasFirstLoad,sourceUnavailable:this._pluginSetIncomplete}}async reload(){return this.loadPromise||(this.loadPromise=this.load().then((async e=>{const t=!this.loadedOnce;let r=[];try{r=await this._reloadExtensionPlugins()}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugins after base load success: ${Cc(e)}`)}const n=e.sourceUnavailable?this._retainPluginsMissingFromPartialLoad(e.plugins):[],o=[...e.plugins,...n],s=new Set(o.map((e=>e.installPath))),i=r.filter((e=>!s.has(e.installPath)));return this.plugins=[...o,...i],e.sourceUnavailable||(this._loadFailures=e.failures),this._pluginSetIncomplete=e.sourceUnavailable,this._retainedFromPreviousLoad=n.length,this._wasFirstLoad=t,this.loadedOnce=!0,this.pluginLogger.log("info",`Plugins reload completed: ${this.plugins.length} plugins loaded (${i.length} extension, ${n.length} retained), ${e.failures.length} failures`),this.plugins})).catch((async e=>{const t=!this.loadedOnce;this.pluginLogger.log("error",`Failed to load plugins: ${e}`),this._pluginSetIncomplete=!0,this._retainedFromPreviousLoad=0,this._wasFirstLoad=t;try{const e=await this._reloadExtensionPlugins(),t=new Set(this.plugins.map((e=>e.installPath)));this.plugins=[...this.plugins,...e.filter((e=>!t.has(e.installPath)))]}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugins after base load failure: ${Cc(e)}`)}return this.loadedOnce=!0,this.plugins})).finally((()=>{this.loadPromise=void 0}))),this.loadPromise}_retainPluginsMissingFromPartialLoad(e){if(!this.loadedOnce)return[];const t=new Set(e.map(im));return this.plugins.filter((e=>"extension"!==e.identifier.source&&void 0===e.loadError&&e.installPath.length>0&&!t.has(im(e))))}async reloadPlugin(e){this.loadPromise&&await this.loadPromise;const t=WD(this.marketplaceOptions,this.userHomeDirectory);if(0===t.length)return;if(!(this.getSettings().loadCursorFirstParty??t.length>0))return;const r=t=>t.pluginDbId===e.pluginDbId,n=e=>"cursor-first-party"===e.identifier.source||"cursor-third-party"===e.identifier.source?e.identifier.sourceInfo:void 0,o=t=>n(t)?.pluginDbId===e.pluginDbId,s=(t,r)=>void 0!==t.pluginDbId?t.pluginDbId===e.pluginDbId:t.pluginName===r?.name&&t.marketplaceName===r?.marketplace;let i,a,c;for(const l of t){let t;try{t=await om({...l,log:l.log??this.pluginLogger,pluginFilter:r})}catch(t){this.pluginLogger.log("error",`reloadPlugin: source load failed for ${e.name}: ${Cc(t)}`);continue}const u=t.plugins.find((e=>o(e)&&void 0===e.loadError));if(void 0!==u){i=u;break}const d=t.plugins.find(o);if(void 0!==d&&void 0===a){const e=n(d);a=d,c=t.failures.find((t=>s(t,e)))}}if(void 0===i){if(void 0!==a){const t=n(a),r={...c??{pluginName:t?.name??e.name,errorMessage:a.loadError??"Plugin load failed",errorType:"unknown",...void 0!==t?.marketplace&&{marketplaceName:t.marketplace}},pluginDbId:e.pluginDbId};this._loadFailures=[...this._loadFailures.filter((e=>!s(e,t))),r]}return}const l=this.plugins.findIndex(o);if(-1===l)this.plugins=[...this.plugins,i];else{const e=[...this.plugins];e[l]=i,this.plugins=e}this.loadedOnce=!0;const u=n(i);return this._loadFailures=this._loadFailures.filter((e=>!s(e,u))),i}async registerExtensionPlugin({path:e,extensionId:t}){const r=(0,s.resolve)(e),n=await(0,xo.realpath)(r);if(!(await(0,xo.stat)(n)).isDirectory())throw new Error(`Extension plugin path is not a directory: ${n}`);const i=o.homedir();if(n.split(s.sep).filter(Boolean).length<3||n===i||"/"===n)throw new Error(`Extension plugin path is too broad (must be a specific subdirectory, not root or home): ${n}`);for(const[e,r]of this._extensionPlugins)if(e!==t&&r.has(n))throw new Error(`Plugin path ${n} is already registered by extension ${e}`);let a=this._extensionPlugins.get(t);if(a||(a=new Map,this._extensionPlugins.set(t,a)),a.has(n))return void this._rememberExtensionPluginOriginalPath({extensionId:t,originalPath:r,canonicalPath:n});const c=(0,s.basename)(n),l=await this._loadExtensionPluginContent(n,t);a.set(n,l),this._rememberExtensionPluginOriginalPath({extensionId:t,originalPath:r,canonicalPath:n}),this.pluginLogger.log("info",`Registered extension plugin: ${c} from ${n} (extension: ${t})`)}async unregisterExtensionPlugin({path:e,extensionId:t}){const r=this._extensionPlugins.get(t);if(!r)return!1;const n=(0,s.resolve)(e);let o;try{o=await(0,xo.realpath)(n)}catch{const e=this._extensionPluginOriginalPaths.get(t);o=e?.get(n)??n}const i=r.delete(o);return 0===r.size?(this._extensionPlugins.delete(t),this._extensionPluginOriginalPaths.delete(t)):i&&this._forgetExtensionPluginOriginalPath(t,o),i&&this.pluginLogger.log("info",`Unregistered extension plugin: ${o} (extension: ${t})`),i}async _loadExtensionPluginContent(e,t){const r=(0,s.basename)(e),n={name:r,localPath:e,extensionId:t},o=await Zf(e,r,{name:r,version:"0.0.0"});return o.displayName&&(n.name=o.displayName),{identifier:{source:"extension",sourceInfo:n},installPath:e,...void 0!==o.displayName&&{displayName:o.displayName},...void 0!==o.description&&{description:o.description},...void 0!==o.authorName&&{authorName:o.authorName},...void 0!==o.logoUrl&&{logoUrl:o.logoUrl},...void 0!==o.version&&{version:o.version},...void 0!==o.homepage&&{homepage:o.homepage},...void 0!==o.repository&&{repository:o.repository},skills:o.skills,rules:o.rules,agents:o.agents,commands:o.commands,mcpConfig:o.mcpConfig??void 0,capabilities:o.capabilities,hooks:o.hooks}}_rememberExtensionPluginOriginalPath(e){let t=this._extensionPluginOriginalPaths.get(e.extensionId);t||(t=new Map,this._extensionPluginOriginalPaths.set(e.extensionId,t)),t.set(e.originalPath,e.canonicalPath)}_forgetExtensionPluginOriginalPath(e,t){const r=this._extensionPluginOriginalPaths.get(e);if(r){for(const[e,n]of r)n===t&&r.delete(e);0===r.size&&this._extensionPluginOriginalPaths.delete(e)}}_getExtensionPluginPaths(){const e=[];for(const[t,r]of this._extensionPlugins)for(const n of r.keys())e.push({canonicalPath:n,extensionId:t});return e}async _reloadExtensionPlugins(){const e=this._getExtensionPluginPaths(),t=[];for(const{canonicalPath:r,extensionId:n}of e)try{const e=await this._loadExtensionPluginContent(r,n),o=this._extensionPlugins.get(n);o&&o.set(r,e),t.push(e)}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugin ${r}: ${Cc(e)}`);const o=this._extensionPlugins.get(n),s=o?.get(r);s&&t.push(s)}return t}async ensureLoaded(){this.loadPromise?await this.loadPromise:this.loadedOnce||await this.reload()}async load(){const e={stack:[],error:void 0,hasError:!1};try{const t=(0,b.q6)().withName("LocalPluginsService.load"),r=(function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(e,(0,D.VI)(t),!1),performance.now()),n=e=>{this.pluginLogger.increment(`local_plugins_service.load.${e}`,1),this.pluginLogger.distribution("local_plugins_service.load.duration",performance.now()-r,{outcome:e})},o=this.getSettings(),i=WD(this.marketplaceOptions,this.userHomeDirectory),a=o.importThirdPartyPlugins,c=o.loadUserLocalPlugins??!0,l=o.loadCursorFirstParty??i.length>0;if(!a&&!l&&!c)return this.pluginLogger.log("info","Skipping plugin loading, cursor 1p, 3p, and user-local plugins are disabled"),{plugins:[],failures:[],sourceUnavailable:!1};this.pluginLogger.increment("local_plugins_service.load.start",1);const u=(e,t)=>{this.pluginLogger.increment("local_plugins_service.load_plugin.error",1),this.pluginLogger.log("error",`Cursor plugin load error ${e.name}@${e.version}: ${t?.message??String(t)}`)};try{const e=await async function(e,t={}){const r=t.log??$p,n=performance.now(),o=t.loadClaude??!0,i=t.loadUserLocal??!0,a=t.marketplaceSources??[],c=t.loadCursorFirstParty??a.length>0,l=[],u=[];let d;o&&l.push(Yf(e,0,{userHomeDir:t.userHomeDir,onError:t.onError,log:r})),c&&a.length>0&&(d=Promise.allSettled(a.map((e=>om({...e,userHomeDir:e.userHomeDir??t.userHomeDir,log:e.log??r}))))),i&&l.push(async function(e={}){const t=e.log??$p,r=performance.now(),n=e.userHomeDir??process.env.HOME;if(!n)return t.log("info","loadUserLocalPlugins: no home directory available, skipping"),[];const o=(0,s.join)(n,".cursor","plugins","local");let i;try{i=await(0,xo.readdir)(o,{withFileTypes:!0})}catch{return t.log("info",`loadUserLocalPlugins: ${o} not found or not readable (${(performance.now()-r).toFixed(1)}ms)`),[]}const a=await(0,xo.realpath)(o).catch((()=>(0,s.resolve)(o))),c=[];for(const r of i){if(!r.isDirectory()&&!r.isSymbolicLink())continue;if(r.name.startsWith("."))continue;const n=(0,s.join)(o,r.name);try{if(r.isSymbolicLink()){let e;try{e=await(0,xo.realpath)(n)}catch(e){t.log("warn",`loadUserLocalPlugin ${r.name} rejected: failed to resolve symlink (${e instanceof Error?e.message:String(e)})`);continue}try{Sf(a,e)}catch{t.log("warn",`loadUserLocalPlugin ${r.name} rejected: symlink target ${e} is outside ${o}`);continue}}if(!(await(0,xo.stat)(n)).isDirectory()){r.isSymbolicLink()&&t.log("warn",`loadUserLocalPlugin ${r.name} rejected: symlink target is not a directory`);continue}const s=performance.now(),i=await(e.localPluginVariablesLookup?.(r.name)),{displayName:l,description:u,authorName:d,logoUrl:h,version:p,homepage:f,repository:m,variablesSchema:g,skills:w,rules:y,agents:v,commands:b,mcpConfig:S,capabilities:k,hooks:_}=await Zf(n,r.name,void 0,{configuredVariables:i,log:t}),C={source:"user-local",sourceInfo:{name:r.name,localPath:n}};c.push({identifier:C,installPath:n,...void 0!==l&&{displayName:l},...void 0!==u&&{description:u},...void 0!==d&&{authorName:d},...void 0!==h&&{logoUrl:h},...void 0!==p&&{version:p},...void 0!==f&&{homepage:f},...void 0!==m&&{repository:m},variablesSchema:g,skills:w,rules:y,agents:v,commands:b,mcpConfig:S??void 0,capabilities:k,hooks:_}),t.log("info",`loadUserLocalPlugin ${r.name} loaded in ${(performance.now()-s).toFixed(1)}ms`)}catch(e){t.log("error",`loadUserLocalPlugin ${r.name} failed: ${e instanceof Error?e.message:String(e)}`)}}return t.log("info",`loadUserLocalPlugins completed in ${(performance.now()-r).toFixed(1)}ms (${c.length} plugins loaded)`),c}({userHomeDir:t.userHomeDir,log:r,localPluginVariablesLookup:t.localPluginVariablesLookup}));const[h,p]=await Promise.all([Promise.allSettled(l),d??Promise.resolve([])]);let f=!1;const m=[];for(const e of p)"rejected"!==e.status?(e.value.sourceUnavailable&&(f=!0),m.push(...e.value.plugins),u.push(...e.value.failures)):(f=!0,r.log("error",`marketplace source threw while loading; treating it as unavailable: ${String(e.reason)}`));for(const e of h)"rejected"!==e.status?m.push(...e.value):(f=!0,r.log("error",`plugin source threw while loading; treating it as unavailable: ${String(e.reason)}`));const g=new Set,w=[];for(const e of m){if(!e.installPath){w.push(e);continue}const t=await(0,xo.realpath)(e.installPath).catch((()=>e.installPath));g.has(t)||(g.add(t),w.push(e))}const y=new Map,v=[];for(const e of w){const t=sm(e);if(void 0!==t){const r=y.get(t),n=!e.loadError;if(!0===r)continue;if(!1===r&&n){const r=v.findIndex((e=>sm(e)===t&&e.loadError));-1!==r&&v.splice(r,1),y.set(t,!0),v.push(e);continue}y.set(t,n)}v.push(e)}const b=performance.now()-n;return r.log("info",`loadAllPlugins completed in ${b.toFixed(1)}ms (claude=${o}, userLocal=${i}, marketplace=${a.length} sources, total=${v.length} plugins, failures=${u.length}, sourceUnavailable=${f})`),{plugins:v,failures:u,sourceUnavailable:f}}(this.workspacePaths,{userHomeDir:this.userHomeDirectory,loadClaude:a,loadUserLocal:c,loadCursorFirstParty:l&&i.length>0,marketplaceSources:i.length>0?i.map((e=>({...e,onCursorError:u}))):void 0,onError:(e,t)=>{this.pluginLogger.log("error",`Claude plugin load error ${e.raw}: ${t?.message??String(t)}`)},log:this.pluginLogger,localPluginVariablesLookup:this.localPluginVariablesLookup});return n("success"),this.pluginLogger.log("info",`Plugins loaded in ${(performance.now()-r).toFixed(1)}ms`),e}catch(e){return n("error"),this.pluginLogger.log("error",`Failed to load all plugins: ${Cc(e)}`),{plugins:[],failures:[],sourceUnavailable:!0}}}catch(t){e.error=t,e.hasError=!0}finally{BD(e)}}}const qD=["parse binary","parse json"],zD=["decompression failed","unsupported response encoding","unsupported content type","protocol error: promised"],GD=new Set([1,4,10,14]),VD=new Set(["AbortError","TimeoutError"]),KD=["ECONN","ENOT","ETIMEDOUT","EPIPE","EAI_","EHOST","ENET","ERR_HTTP2","ERR_SSL","ERR_TLS","UND_ERR","CERT_","DEPTH_ZERO_SELF_SIGNED_CERT","SELF_SIGNED_CERT","UNABLE_TO_"];function JD(e,t){return t.some((t=>e.startsWith(t)))}function ZD(e){if(e instanceof Error&&VD.has(e.name))return!0;const t=function(e){if("object"==typeof e&&null!==e&&"code"in e)return"string"==typeof e.code?e.code:void 0}(e);return void 0!==t&&JD(t,KD)}function XD(e){const t=function(e){if(e instanceof Error&&"ConnectError"===e.name&&"code"in e&&"number"==typeof e.code&&"rawMessage"in e&&"string"==typeof e.rawMessage)return{code:e.code,text:e.rawMessage,cause:e.cause}}(e);if(void 0===t)return ZD(e)?"transport":"other";const{code:r,text:n,cause:o}=t;return JD(n,qD)?"reply_schema":JD(n,zD)?"reply_encoding":n.startsWith("http/2 stream closed with error code")||GD.has(r)||ZD(o)?"transport":"other"}var QD=r("../proto/dist/generated/aiserver/v1/dashboard_pb.js");const YD=BigInt(0),eO=BigInt(8),tO=BigInt(16),rO=BigInt(65535);function nO(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch{return}}function oO(e){let t=e.trim().replace(/\.+$/,"").toLowerCase();if(t.startsWith("[")){const e=t.indexOf("]");-1!==e&&(t=t.slice(1,e))}else if(t.split(":").length-1==1){const e=t.lastIndexOf(":"),r=t.slice(e+1);Array.from(r).every((e=>/\d/.test(e)))&&(t=t.slice(0,e))}return t}function sO(e){const t=e.split(".");if(4!==t.length)return;let r=YD;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<>tO&rO)),t.push(Number(o.value&rO))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function aO(e){return sO(e)??function(e){const t=oO(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=iO(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<7?void 0:{version:6,value:[...n,...new Array(8-s).fill(0),...o].reduce(((e,t)=>e<i)return!1;const a=BigInt(i-s);return o.value>>a==n.value>>a}(r,n);if(n.startsWith("*.")){const e=n.slice(2);return r===e||r.endsWith(`.${e}`)}return r===n}function lO(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}function uO(e,t){if(lO(e,t))return!0;if(e.includes("://")){let r,n;try{r=new URL(e),n=new URL(t)}catch{return!1}if(""!==r.username||""!==r.password||""!==n.username||""!==n.password||r.protocol!==n.protocol||r.port!==n.port)return!1;const o=oO(r.hostname);return!!cO(oO(n.hostname),o)&&lO(`${r.pathname}${r.search}`,`${n.pathname}${n.search}`)}const r=function(e){const t=function(e){const t=e.trim(),r=t.indexOf("["),n=t.indexOf("]");if(-1!==r&&n>r){const e=t.slice(r+1,n);if(t.slice(n+1).startsWith("("))return`${t.slice(0,r)}${e}`}return t}(e).trim();if(0===t.length)return;const r=t.lastIndexOf("/");if(!t.includes("://")&&r>0&&/^\d+$/.test(t.slice(r+1).trim())){const e=oO(t.slice(0,r));if(e.length>0)return`${e}/${t.slice(r+1).trim()}`}const n=nO(t);if(n)return oO(n.hostname);let o=t;const s=o.indexOf("://");-1!==s&&(o=o.slice(s+3));const i=o.indexOf("/");-1!==i&&(o=o.slice(0,i));const a=oO(function(e){if(e.startsWith("[")){const t=e.indexOf("]");return-1!==t?e.slice(1,t):e}const t=e.split(":");return 2===t.length&&Array.from(t[1]??"").every((e=>/\d/.test(e)))?t[0]:e}(o));if(0!==a.length){if(a.startsWith("*.")){const e=a.slice(2);if(0===e.length||e.includes("*")||e.includes("?"))return;return a}if(!a.includes("*")&&!a.includes("?"))return a}}(e),n=function(e){const t=nO(e);if(t)return oO(t.hostname);const r=oO(e);return r.length>0?r:void 0}(t);return!(!r||!n)&&cO(n,r)}async function dO(e){try{return await e.current()}catch{return}}function hO(e){try{const t=new URL(e);return`${t.protocol}//${t.host}${t.pathname}`}catch{return}}function pO({failOpenWhenEmpty:e,server:t,settings:r}){if(!0!==r?.allowedMcpConfiguration?.requireMcpServersInTeamNetworkAllowlist||void 0===t.url)return{blocked:!1};const n=function(e){return!0===e.cloudAgentMcpAllowlistApplied&&!1===e.mirrorSandboxAllowlistForEgress?e.cloudAgentEgressAllowlist??[]:e.networkAllowlist??[]}(r).map((e=>e.trim())).filter((e=>e.length>0));return 0===n.length&&e||Qv(t.url,n)?{blocked:!1}:{blocked:!0,reason:"teamNetworkAllowlist",message:"Not on the team network allowlist"}}function fO(e){const t=e?.trim();return t&&t.length>0?t:void 0}function mO(e,t,r){if(!0===r?.useCorePolicy)return!function(e,t){if(void 0===t)return!0;if(!0===t.disableAll)return!1;if(CC(e))return!0;if(RC(e,t.offMcpServerRules))return!1;const r=t.allowedMcpServers??[];return 0===r.length&&!0!==t.allowUserOverrideMcpServers||!!function(e,t){return t.length>0&&function(e,t){return t.some((t=>{const r=EC(t.command),n=xC(t.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==e.command&&(0,Lb.mD)(r,e.command),s=void 0===n||void 0!==e.url&&(0,Lb.vc)(n,e.url);return o&&s}))}(e,t)}(e,r)||!0===t.allowUserOverrideMcpServers&&!PC(e,t.deniedMcpServers)}(e,t);if(void 0===t)return!1;if(!0===t.disableAll)return!0;const n=t.allowedMcpServers;return 0!==n.length&&!n.some((t=>function(e,t){const r=fO(e.command),n=fO(e.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==t.command&&function(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}(r,t.command),s=void 0===n||void 0!==t.url&&uO(n,t.url);return o&&s}(t,e)))}class gO{constructor(e,t={}){this.dashboardClient=e,this.options=t}getTeamAdminSettings(){return this.dashboardClient.getTeamAdminSettingsOrEmptyIfNotInTeam(new QD.Byz(!0===this.options.supportsHostMcpBridgeExemption?{supportsHostMcpBridgeExemption:!0}:{}))}getTeamRepos(){return this.dashboardClient.getTeamReposOrEmptyIfNotInTeam(new QD.aYW({}))}}function wO(e,t){if("workspace"!==e)return[];const r=[],n=new Set;for(const e of t??[]){const t=e.trim();0===t.length||n.has(t)||(n.add(t),r.push(t))}return r}class yO{constructor(e){this.fetch=e}get(){const e=this.cached,t=void 0===e?1/0:Date.now()-e.fetchedAt;return void 0===e||t>6e5?(this.cached=void 0,this.refresh()):(t>3e5&&this.refresh().catch((()=>{})),Promise.resolve(e.value))}invalidate(){this.cached=void 0,this.inFlight=void 0}refresh(){if(void 0===this.inFlight){const e=this.fetch().then((t=>(this.inFlight!==e||void 0===t&&void 0!==this.cached||(this.cached={value:t,fetchedAt:Date.now()}),t))).finally((()=>{this.inFlight===e&&(this.inFlight=void 0)}));this.inFlight=e}return this.inFlight}}class vO{constructor(e,t,r={}){this.teamAdminSettingsProvider=e,this.defaultAllowlistProvider=t,this.options=r,this.lastFetchSucceeded=!0,this.lastFetchFailure="other",this.settingsGeneration=0,this.lastFetchedGeneration=0,this.settings=new yO((()=>this.fetchSettings())),this.droppedReplies=new WeakSet,this.hostMcpBridgeClients=new WeakSet,this.mcpServerByClient=new WeakMap,this.teamRepos=new yO((()=>this.teamAdminSettingsProvider.getTeamRepos())),this.defaultAllowlist=new yO((()=>this.fetchDefaultAllowlist())),this.getTeamAdminSettings(),this.prefetchTeamRepos()}async prefetchTeamRepos(){try{await this.teamRepos.get()}catch{}}invalidateCache(){this.settingsGeneration+=1,this.settings.invalidate(),!0!==this.options.preserveTeamReposOnInvalidate&&this.teamRepos.invalidate(),this.defaultAllowlist.invalidate()}invalidateTeamRepos(){this.teamRepos.invalidate()}async refreshTeamAdminSettings(){try{await this.settings.refresh()}catch{}}async fetchSettings(){const{fetchIdentity:e}=this.options;if(void 0!==e)return this.fetchSettingsFor(e);const t=this.settingsGeneration;try{const e=await this.teamAdminSettingsProvider.getTeamAdminSettings();return this.lastFetchSucceeded=!0,t>=this.lastFetchedGeneration&&(this.lastFetchedSettings=e,this.lastFetchedGeneration=t),e}catch(e){throw this.lastFetchSucceeded=!1,this.lastFetchFailure=XD(e),e}}async fetchSettingsFor(e){const t=await dO(e),r=this.settingsGeneration;if(void 0===t)throw this.lastFetchSucceeded=!1,this.lastFetchFailure="other",new Error("No one is named whose team settings a fetch would read");try{const e=await this.teamAdminSettingsProvider.getTeamAdminSettings();return void 0!==e&&this.droppedReplies.delete(e),this.isSentFor(e,t)?(this.lastFetchSucceeded=!0,r>=this.lastFetchedGeneration&&(this.lastFetchedSettings=e,this.lastFetchedGeneration=r),e):e}catch(e){throw this.lastFetchSucceeded=!1,this.lastFetchFailure=XD(e),e}}getTeamAdminSettings(){const{fetchIdentity:e}=this.options;return void 0!==e?this.getTeamAdminSettingsFor(e):this.settings.get().catch((()=>{}))}async getTeamAdminSettingsFor(e){const t=await this.settings.get().catch((()=>{})),r=await dO(e);if(void 0===t)return void(this.isSentFor(this.lastFetchedSettings,r)||(this.settingsGeneration+=1));if(void 0===r)return this.answerAsFailedRead();if(this.isSentFor(t,r))return t;let n=t,o=r;const s=await this.settings.get().catch((()=>{}));if(s!==t){if(void 0===s)return this.answerAsFailedRead();if(this.isSentFor(s,r))return s;if(o=await dO(e),void 0===o)return this.answerAsFailedRead();if(this.isSentFor(s,o))return s;n=s}this.droppedReplies.has(n)||(this.droppedReplies.add(n),this.settingsGeneration+=1,this.settings.invalidate());const i=await this.settings.get().catch((()=>{}));return void 0!==i?this.isSentFor(i,r)||this.isSentFor(i,o)||this.isSentFor(i,await dO(e))?i:this.answerAsFailedRead():void 0}answerAsFailedRead(){this.settingsGeneration+=1,this.lastFetchSucceeded=!1,this.lastFetchFailure="other"}isSentFor(e,t){return void 0!==e&&void 0!==t&&this.options.fetchIdentity?.sentFor(e)===t}async getDotCursorProtection(){const e=await this.getTeamAdminSettings();return e?.dotCursorProtection??!0}async getShouldBlockMcp(){const e=await this.getTeamAdminSettings();return!(!e?.autoRunControls?.enabled||!e?.autoRunControls?.disableMcpAutoRun)}async getDeleteFileProtection(){const e=await this.getTeamAdminSettings();return!(!e?.autoRunControls?.enabled||!e?.autoRunControls?.deleteFileProtection)}async getIsHeadlessDisabled(){return"disabled"===(await this.getHeadlessCliPolicy()).kind}async getHeadlessCliPolicy(){const e=await this.getTeamAdminSettings();return void 0!==e||this.lastFetchSucceeded?!0===e?.cliSettings?.disableHeadless?{kind:"disabled"}:{kind:"enabled"}:{kind:"unavailable"}}async getMcpServerBlockInfo(e){const t=await this.getTeamAdminSettings(),r=t?.allowedMcpConfiguration,n=await this.isMcpSettingsOverhaulEnabled({disableExposureLog:!0});if(!0===r?.disableAll)return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};if(this.isHostMcpBridge(t,e))return{blocked:!1,hostMcpBridge:!0};if(RC(e,r?.offMcpServerRules))return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};if(n){if(mO(e,r,{useCorePolicy:!0}))return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};const n=await this.getMcpNetworkControlsConfig(e),o=void 0===e.url?{allowed:!0}:(0,Lb.ME)(e.url,n);if(!o.allowed)return{blocked:!0,reason:"teamNetworkAllowlist",message:o.message};const s=pO({failOpenWhenEmpty:!1,server:e,settings:t});if(s.blocked)return s}if(!n){const r=function({isMcpAccessNetworkAllowlistEnabled:e,server:t,settings:r}){return e&&!0===r?.allowedMcpConfiguration?.requireMcpServersInTeamNetworkAllowlist?pO({failOpenWhenEmpty:!0,server:t,settings:r}):{blocked:!1}}({isMcpAccessNetworkAllowlistEnabled:await this.isMcpAccessNetworkAllowlistEnabled(),server:e,settings:t});if(r.blocked)return r}return void 0!==t||this.lastFetchSucceeded?{blocked:!1}:{blocked:!1,settingsUnavailable:!0}}async getManagedSlackWorkspaceLists(){const e=await this.getTeamAdminSettings()??this.lastFetchedSettings;return void 0===e?[]:function(e){return e.memberSlackManagedWorkspacesUnreadable?"unconfirmed":e.memberSlackManagedWorkspaces.map((e=>e.slackTeamIds)).filter((e=>e.length>0))}(e)}async getMcpNetworkControlsConfig(e){const t=await this.getTeamAdminSettings(),r=t?.allowedMcpConfiguration;if(await this.isMcpSettingsOverhaulEnabled()&&(void 0===e||!this.isHostMcpBridge(t,e))){const n="win32"===process.platform&&await this.isWin32UserExtensionStdioUnsandboxEnabled();return(0,Lb._N)({allowedMcpConfiguration:r,server:e,localAgentNetworkAllowlist:t?.networkAllowlist,blockMessage:"Not on the team network allowlist",aggregateManagedServerNetworkAllowlists:!1,stdioPlatform:process.platform,unsandboxUserExtensionStdio:n})}return{enabled:!1,localAgentNetworkAllowlist:t?.networkAllowlist,blockMessage:"Not on the team network allowlist"}}isHostMcpBridge(e,t){const r=this.options.hostMcpBridgeUrls;if(!0!==e?.cloudAgentMcpAllowlistApplied||void 0===r||void 0!==t.command||void 0===t.url)return!1;const n=hO(t.url);return void 0!==n&&r.some((e=>hO(e)===n))}recordHostMcpBridgeClient(e){this.hostMcpBridgeClients.add(e)}async isHostMcpBridgeClient(e){if(!this.hostMcpBridgeClients.has(e))return!1;const t=await this.getTeamAdminSettings();return!0===t?.cloudAgentMcpAllowlistApplied&&!0!==t.allowedMcpConfiguration?.disableAll}recordMcpServerClient(e,t){this.mcpServerByClient.set(e,t)}async getMcpAdminToolLimit(e){if(await this.isHostMcpBridgeClient(e))return{kind:"none"};const t=this.mcpServerByClient.get(e);if(void 0===t)return{kind:"unknown_server"};const r=!0===this.options.mcpAdminToolLimitSurvivesFailedRead;let n=await this.getTeamAdminSettings();if(void 0===n&&!this.lastFetchSucceeded&&r&&(n=await this.getTeamAdminSettings()),void 0===n){if(this.lastFetchSucceeded)return{kind:"none"};if(!r)return{kind:"settings_unavailable"};const e=this.lastFetchFailure,t=this.lastFetchedGeneration===this.settingsGeneration?this.lastFetchedSettings:void 0;if(void 0===t)return{kind:"settings_unavailable",failure:e,noLimitApplies:!0};n=t}const o=function(e,t){const r=e?.find((e=>(0,Lb.rM)(e,t)));if(void 0!==r)return Bb({mode:r.toolAllowlistMode,tools:r.toolAllowlist})}(n.allowedMcpConfiguration?.allowedMcpServers,t);return void 0===o?{kind:"none"}:{kind:"limit",policy:o}}async isServerBlocked(e){return(await this.getMcpServerBlockInfo(e)).blocked}async getAutoRunControls(){const e=await this.getTeamAdminSettings();if(e?.autoRunControls?.enabled)return{enabled:e.autoRunControls.enabled,allowed:e.autoRunControls.allowed??[],blocked:e.autoRunControls.blocked??[],enableAllowlistMode:e.autoRunControls.enableAllowlistMode??!0,enableRunEverything:e.autoRunControls.enableRunEverything??!1,enableSmartAuto:e.autoRunControls.enableSmartAuto??!0,mcpToolAllowlist:e.autoRunControls.mcpToolAllowlist??[]}}async isReadControlEnabled(){try{return await(this.options.isReadControlEnabled?.())??!0}catch{return!1}}async isDenylistEnforcementKilled(){try{return!0===await(this.options.isAdminCommandDenylistEnforcementKilled?.())}catch{return!1}}async getAdminCommandDenylist(){if(await this.isDenylistEnforcementKilled())return{rules:[]};const e=await this.getTeamAdminSettings();return{rules:e?.autoRunControls?.adminCommandDenylist?.rules??[]}}async isMcpSettingsOverhaulEnabled(e){const t=this.options.isMcpSettingsOverhaulEnabled?.(e);return void 0!==t&&await t}async isWin32UserExtensionStdioUnsandboxEnabled(){try{const e=this.options.isWin32UserExtensionStdioUnsandboxEnabled?.();return void 0!==e&&await e}catch{return!1}}async getMcpToolControls(){const e=await this.getTeamAdminSettings(),t=e?.allowedMcpConfiguration;if(void 0===t)return;const r=function({autoRunControls:e,allowedMcpServers:t}){const r=!0===e?.enabled?e.mcpToolAllowlist??[]:[],n=function(e){return(e??[]).flatMap((e=>{const t=void 0===e.name?"":jb(e.name);if(0===t.length)return[];const r=Bb({mode:e.toolAllowlistMode,tools:e.toolAllowlist});return[{name:t,policy:r,flattened:Hb(t,r)}]}))}(t);return{tools:(o=[...n.flatMap((e=>[...e.flattened])),...r],[...new Set(o)]),policies:n.map((e=>({name:e.name,policy:e.policy})))};var o}({autoRunControls:e?.autoRunControls,allowedMcpServers:t?.allowedMcpServers});return r.policies.length>0||r.tools.length>0?{enabled:!0,mcpToolAllowlist:r.tools,allowUserOverride:t?.allowUserOverrideMcpServers??!1,serverPolicies:r.policies}:void 0}async getNetworkAccessControls(){const e=await this.getTeamAdminSettings();return void 0!==e||this.lastFetchSucceeded?{allowlist:e?.networkAllowlist??[],denylist:e?.networkDenylist??[],available:!0}:{allowlist:[],denylist:[],available:!1}}async getSandboxingControls(){const e=await this.getTeamAdminSettings(),t=e?.autoRunControls?.sandboxingControls,r=(n=t?.sandboxReadBoundary,n===QD.h0i.WORKSPACE?"workspace":"system");var n;return{sandboxingDisabled:t?.sandboxing===QD.faf.DISABLED,networkingDisabled:t?.sandboxNetworking===QD._mX.ALWAYS_DISABLED,gitDisabled:t?.sandboxGit===QD.i24.ALWAYS_DISABLED,readBoundary:r,readAllowlistPaths:wO(r,t?.sandboxReadAllowlistPaths),allowUserOverrideReadAllowlist:!1!==t?.allowUserOverrideSandboxReadAllowlist}}async isAttributionDisabledByAdmin(){const e=await this.getTeamAdminSettings();return void 0===e&&!this.lastFetchSucceeded||(e?.attributionControls?.disableAttribution??!1)}async isComputerUseDisabledByAdmin(){const e=await this.getTeamAdminSettings();return void 0!==e?!1===e.computerUse:this.lastFetchedGeneration!==this.settingsGeneration||void 0===this.lastFetchedSettings&&!this.lastFetchSucceeded||!1===this.lastFetchedSettings?.computerUse}getDefaultNetworkAllowlist(){return this.defaultAllowlist.get().catch((()=>({allowlist:[],available:!1})))}async fetchDefaultAllowlist(){return this.defaultAllowlistProvider?{allowlist:await this.defaultAllowlistProvider.getDefaultNetworkAllowlist(),available:!0}:{allowlist:[],available:!0}}getTeamRepos(){return this.teamRepos.get()}async isMcpAccessNetworkAllowlistEnabled(){return await(this.options.isMcpAccessNetworkAllowlistEnabled?.())??!1}}const bO=new xy,SO={async resolveWorkspaceState(e){const t=e.workingDirectory??e.projectRoot??e.workspaceRoots?.[0],r=e.projectRoot??(void 0!==t?await tc((0,b.q6)(),bO,t)??t:void 0),n=e.workspaceRoots??(void 0!==r?[r]:void 0!==t?[t]:[]);return{workingDirectory:t,projectRoot:r,projectDirectory:e.projectDirectory??(void 0!==r?Eo(r):void 0),workspaceRoots:n,createdAt:new Date}}},kO=(0,d.h)("ControlledConversationActionManager");class _O{get signal(){return this.abortController.signal}get abortRequested(){return this.abortCalled}constructor(){this.abortCallbacks=[],this.abortController=new AbortController,this.acceptsActions=!0,this.disposed=!1,this.abortStarted=!1,this.abortCalled=!1,this.runActive=!1,this.unprocessedUserMessages=[],this.clientStream=(0,f.Jt)()}addAbortCallback(e){this.abortCallbacks.push(e)}abort(e,t){if(this.abortCalled=!0,this.abortController.signal.aborted||this.abortStarted)return;const r=t?.interruptedPendingToolCallResolutions;if(this.abortStarted=!0,!this.runActive){this.abortController.abort(e);for(const e of this.abortCallbacks)e();return void(this.abortCallbacks.length=0)}const n=this.abortController,o=[...this.abortCallbacks];this.abortCallbacks.length=0,this.submitConversationAction(new c.QFf({action:{case:"cancelAction",value:new c.TTG({reason:e,interruptedPendingToolCallResolutions:r})}})).catch((()=>{})).finally((()=>{n.abort(e);for(const e of o)e();if(this.abortController===n){const e=[...this.abortCallbacks];this.abortCallbacks.length=0;for(const t of e)t()}}))}async submitConversationAction(e){if(!this.acceptsActions)throw new f.W2("ControlledConversationActionManager is not accepting actions");if("userMessageAction"===e.action.case){const t=e.action.value.userMessage;t&&this.unprocessedUserMessages.push(t)}await this.clientStream.write(e)}queueFollowUpUserMessage(e){if(this.disposed||this.abortStarted)throw new f.W2("ControlledConversationActionManager run was aborted or disposed");this.unprocessedUserMessages.push(e)}async enqueueReplayableConversationAction(e){if("asyncAskQuestionCompletionAction"!==e.action.case)throw new TypeError("Only asyncAskQuestionCompletionAction can use enqueue acknowledgement");if(!this.acceptsActions)throw new f.W2("ControlledConversationActionManager is not accepting actions");this.clientStream.write(e).catch((()=>{}))}markMessageAsProcessed(e){this.unprocessedUserMessages=this.unprocessedUserMessages.filter((t=>t.messageId!==e.messageId))}requeueMessage(e){this.unprocessedUserMessages.some((t=>t.messageId===e.messageId))||this.unprocessedUserMessages.unshift(e)}getUnprocessedUserMessages(){return[...this.unprocessedUserMessages]}hasUnprocessedMessages(){return this.unprocessedUserMessages.length>0}close(){this.acceptsActions=!1,this.clientStream.close()}reopen(){this.disposed||this.acceptsActions||this.resetStream()}resetStream(){if(this.disposed)throw new f.W2("ControlledConversationActionManager disposed");this.acceptsActions=!1,this.clientStream.close(),this.clientStream=(0,f.Jt)(),this.acceptsActions=!0,this.abortController=new AbortController,this.abortStarted=!1;for(const e of this.unprocessedUserMessages)this.clientStream.write(new c.QFf({action:{case:"userMessageAction",value:new c.Vtf({userMessage:e})}})).catch((()=>{}))}async run(e,t){const r=this.clientStream;this.runActive=!0;try{for await(const n of r)try{await t.write(n)}catch(t){kO.error(e,"Error writing conversation action",t)}}catch(e){if(!(e instanceof f.W2))throw e}finally{this.clientStream===r&&(this.runActive=!1)}}dispose(){this.disposed||(this.disposed=!0,this.abortCallbacks.length=0,this.acceptsActions=!1,this.clientStream.throw(new f.W2("ControlledConversationActionManager disposed")))}}var CO=r("../cursor-sdk-local-runtime/dist/utils/logger.js"),EO=r("../agent-kv/dist/agent-store.js");const xO="x-blob-encryption-key";function PO(e,t){const r={...t};return void 0!==r[xO]||(0,EO.TU)(e)&&(r[xO]=e),r}const RO=new Map;function IO(e){if("userMessageAction"===e.action.case)return e.action.value.userMessage?.text}function TO(e,t,r){const n=e.runOptions?.requestedModel;return{conversationId:e.conversationId,generationId:e.conversationId,model:n?.modelId??"unknown",modelId:n?.modelId,modelParams:n?.parameters.map((e=>({id:e.id,value:e.value}))),loopCount:t,promptText:r}}function AO(e){return new c.QFf({action:{case:"userMessageAction",value:new c.Vtf({userMessage:new c.RGk({text:e})})}})}function $O(e){return e instanceof DOMException&&"AbortError"===e.name||e instanceof Error&&("AbortError"===e.name||"The operation was aborted"===e.message)}function MO(e){e?.catch((e=>{CO.Jz.warn("[agent-session-runner] fire-and-forget hook failed:",e)}))}class DO{constructor(e,t,r){this.inner=e,this.getToken=t,this.restMcpHost=r}async getDefinitions(e,t=!0){const r=await this.inner.getDefinitions(e,t);return Promise.all(r.map((async e=>{const t=await async function(e,t,r){if(!("url"in e)||!e.url||void 0===cb(e.url,r)||Object.keys(e.headers??{}).some((e=>e.toLowerCase()===ab)))return e;const n=await t();return void 0===n||0===n.length?e:{...e,headers:{...e.headers??{},[ab]:`Bearer ${n}`}}}(e.serverConfig,this.getToken,this.restMcpHost);return t===e.serverConfig?e:{...e,serverConfig:t}})))}clearCache(){this.inner.clearCache?.()}}const OO=new Set(["mcp.slack.com","setup.shopify.com"]);class FO{constructor(e,t){this.inner=e,this.resolver=t}async getDefinitions(e,t=!0){const r=await this.inner.getDefinitions(e,t);return Promise.all(r.map((async e=>{const t=await async function(e,t){if(!("url"in e)||!e.url)return e;const r=await async function(e,t,r,n=fetch){let o;try{o=new URL(e).hostname}catch{return t}const s=void 0!==cb(e,r.restMcpHost);if(!OO.has(o)&&!s)return t;let i=await r.resolve(e);if(!i&&s){const t=(await dx(e,n))?.clientId;void 0!==t&&(i={CLIENT_ID:t})}return i?t?void 0===lx(t.CLIENT_ID)?{...i,...t,CLIENT_ID:i.CLIENT_ID}:{...i,...t}:i:t}(e.url,e.auth,t);return r===e.auth?e:{...e,auth:r}}(e.serverConfig,this.resolver);return t===e.serverConfig?e:{...e,serverConfig:t}})))}clearCache(){this.inner.clearCache?.()}}class NO{constructor(e,t){this.storage=e,this.prefix=t}async loadTokens(e){return this.storage.loadTokens(this.prefix+e)}async saveTokens(e,t){return this.storage.saveTokens(this.prefix+e,t)}async loadClientInformation(e){return this.storage.loadClientInformation(this.prefix+e)}async saveClientInformation(e,t){return this.storage.saveClientInformation(this.prefix+e,t)}}class LO{constructor(e,t){this.storage=e,this.prefix=t}async isServerApproved(e,t,r){return this.storage.isServerApproved(this.prefix+e,t,r)}}class jO{constructor(e){this.higherPrecedenceSources=e}async load(e,t,r,n,o){for(const r of this.higherPrecedenceSources){const n=(await r.getDefinitions(e)).find((e=>e.identifier===t));if(void 0!==n)throw new MC(t,n.configPath??"another config")}return await o(e,r)}}class UO extends iI{constructor(e,t){super(e),this.shadowedClientsClosed=t}async closeAllClients(){await Promise.all([super.closeAllClients(),this.shadowedClientsClosed])}}async function BO(e){try{await(e.close?.())}catch{}}class WO{constructor(e){this.loaders=e}async load(e,t=!0){const r=await Promise.allSettled(this.loaders.map((({loader:r})=>r.load(e,t)))),n=r.find((e=>"rejected"===e.status));if(n)throw await Promise.allSettled(r.flatMap((e=>"fulfilled"===e.status?[e.value.closeAllClients()]:[]))),n.reason;const o=r.filter((e=>"fulfilled"===e.status)).map((e=>e.value)),s={},i=[];for(let e=0;e{})))}async loadClient(e,t,r=!1){for(const{loader:n,prefix:o}of this.loaders)if(t.startsWith(o)){t=t.slice(o.length);try{return await n.loadClient(e,t,r)}catch(e){if(e instanceof Error&&e.message.includes("not found in config"))continue;throw e}}throw new Error(`MCP client "${t}" not found in config`)}clearClient(e){for(const{loader:t,prefix:r}of this.loaders){if(!e.startsWith(r))continue;const n=e.slice(r.length);t.clearClient?.(n)}}clearAllMcpCaches(){for(const{loader:e}of this.loaders)e.clearAllMcpCaches?.()}}class HO{constructor(e,t,r,n,i=!1,a,c,l=s.join((0,o.homedir)(),".cursor","mcp.json"),u,d,h){const p=Array.isArray(e)?e:[e],f={}.location,m=[];"enterprise"===f?.source&&m.push({path:f.path,prefix:"enterprise-",scope:"enterprise"});for(let e=0;e({prefix:t,scope:r,fileSource:new _I(e,"enterprise"===r||"env"===r?RE:void 0)}))),y=[];for(const{prefix:e,scope:o,fileSource:s}of w){const l=i?"":e,d=new NO(t,l),p=new LO(n,l),f=w.flatMap((e=>{return t=e.scope,r=o,IE.indexOf(t)0?[new jO(f)]:[]],g=new CI(u?new FO(s,u):s,d,m,{authRedirectUrlGenerator:a,isLinkSharedPaymentTokenLogRedactionEnabled:h});y.push({prefix:l,loader:g})}this.loader=new WO(y)}static init(e,t,r,n=!1,o,i={}){const a=new DI(s.join(r,"mcp-auth.json"));(async function(e){await(0,xo.rm)(s.join(e,"mcp-cache.json"),{force:!0})})(r).catch((()=>{}));const c=n?{isServerApproved:()=>Promise.resolve(!0)}:new FC(s.join(r,"mcp-approvals.json"),t);return new HO(t,a,e,c,!0,void 0,o,void 0,i.defaultAuthResolver,void 0,i.isLinkSharedPaymentTokenLogRedactionEnabled)}async load(e,t=!0){return this.loader.load(e,t)}async loadClient(e,t,r=!1){return this.loader.loadClient(e,t,r)}clearClient(e){this.loader.clearClient(e)}clearAllMcpCaches(){this.loader.clearAllMcpCaches()}}const qO="cursor-plugins/local";function zO(e){var t;if(e)for(const r of e)if("object"==typeof(t=r)&&null!==t&&t.kind===qO)return r}class GO extends sI{constructor(e){super(e),this.runtimeManager=e,this.disposed=!1}async dispose(){this.disposed||(this.disposed=!0,await this.runtimeManager.closeAllClients())}}class VO{constructor(e){this.storagePath=e}async isServerDisabled(e){try{const t=await(0,xo.readFile)(this.storagePath,"utf8"),r=JSON.parse(t);return Array.isArray(r)?r.includes(e):(await this.writeDisabledServers([]),!1)}catch(e){if("object"==typeof e&&null!==e&&"code"in e&&"ENOENT"===e.code)return!1;throw e}}async writeDisabledServers(e){await(0,xo.mkdir)((0,s.dirname)(this.storagePath),{recursive:!0}),await(0,xo.writeFile)(this.storagePath,JSON.stringify(e,null,2))}}class KO{constructor(e,t){this.pluginMcpService=e,this.importThirdPartyPlugins=t}async getDefinitions(){let e;try{e=await this.pluginMcpService.getPluginMcpServers()}catch(e){return CO.Jz.warn("[cursor-config-mcp] Failed to enumerate plugin MCP servers:",e),[]}const t=[];for(const r of e){if(!this.importThirdPartyPlugins&&YO(r))continue;const e=II(r);e?t.push({identifier:r.identifier,authStorageKey:r.identifier,serverConfig:e,configPath:"",source:"plugin",metadata:{identifier:r.identifier,pluginName:r.pluginName,pluginSource:r.pluginSource}}):CO.Jz.warn("[cursor-config-mcp] Failed to initialize plugin MCP client:",{identifier:r.identifier,pluginName:r.pluginName,pluginSource:r.pluginSource,result:"invalid-config",errorMessage:"pluginMcpDescriptorToServerConfig returned undefined"})}return t}}class JO{constructor(e){this.servers=e}async getDefinitions(){return Object.entries(this.servers).map((([e,t])=>({identifier:e,authStorageKey:`inline:${e}`,serverConfig:QO(e,t),source:"inline",metadata:{source:"cursor-sdk"}})))}}function ZO(e={}){const t=e.teamSettingsService??{getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getAdminCommandDenylist:async()=>({rules:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}},r=e.ignoreApprovals??!1,n=e.importThirdPartyPlugins??!1,i=void 0===e.isLinkSharedPaymentTokenLogRedactionEnabled?{}:{isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled},a=e.restMcpCursorAuthTokenSupplier,c=e=>void 0===a?e:new DO(e,a,"api.cursor.com");return{async createLease(a){const l=a.workspaceState,u=l.projectRoot??l.workingDirectory,d=l.projectDirectory;if(!u||!d)return new oI;const h=new VO((0,s.join)(d,"mcp-disabled.json")),p=function(e){const{teamSettingsService:t,projectRoot:r,projectDirectory:n,ignoreApprovals:i,disabledStore:a,includeProjectMcp:c,includeUserMcp:l,isLinkSharedPaymentTokenLogRedactionEnabled:u}=e;if(c&&l)return HO.init(t,r,n,i,a,{isLinkSharedPaymentTokenLogRedactionEnabled:u});if(!c&&!l)return;const d=new DI((0,s.join)(n,"mcp-auth.json")),h=i?{isServerApproved:()=>Promise.resolve(!0)}:new FC((0,s.join)(n,"mcp-approvals.json"),r),p=[new KC,new OC(h),new PI(t),new DC(a)],f=[];return c&&f.push({prefix:"",loader:new RI((0,s.join)(r,".cursor","mcp.json"),d,p,{isLinkSharedPaymentTokenLogRedactionEnabled:u})}),l&&f.push({prefix:"",loader:new RI((0,s.join)((0,o.homedir)(),".cursor","mcp.json"),d,p,{isLinkSharedPaymentTokenLogRedactionEnabled:u})}),XO(f)}({teamSettingsService:t,projectRoot:u,projectDirectory:d,ignoreApprovals:r,disabledStore:h,includeProjectMcp:e.includeProjectMcp??!0,includeUserMcp:e.includeUserMcp??!0,isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled}),f=[],m=e.inlineMcpServers??{};if(Object.keys(m).length>0){const e=new DI((0,s.join)(d,"mcp-auth.json")),r=[new KC,new PI(t)];f.push({prefix:"",loader:new CI(c(new JO(m)),e,r,i)})}const g=zO(a.services.pluginBootstrapOutputs);if(g&&(e.includePluginMcp??1)){const e=new FC((0,s.join)(d,"mcp-approvals.json"),u),o=new DI((0,s.join)(d,"mcp-auth.json")),a=[new KC];r||a.push(new OC(e)),a.push(new PI(t),new DC(h));const l=new UD(g.pluginsService),p=new CI(c(new KO(l,n)),o,a,i);f.push({prefix:"",loader:p})}if(p&&f.push({prefix:"",loader:p}),0===f.length)return new oI;const w=XO(f),y=await w.load(e.initializationCtx??(0,b.q6)(),e.cache);return new GO(y)}}}function XO(e){return 1===e.length?e[0].loader:new WO(e)}function QO(e,t){if("command"in t){if(void 0!==t.type&&"stdio"!==t.type)throw new Error(`Unsupported MCP server type "${String(t.type)}" for "${e}"`);return{command:t.command,args:t.args?[...t.args]:void 0,env:t.env,cwd:t.cwd,startupTimeoutSec:t.startupTimeoutSec}}if("url"in t){if(void 0!==t.type&&"http"!==t.type&&"sse"!==t.type)throw new Error(`Unsupported MCP server type "${String(t.type)}" for "${e}"`);const r={url:t.url,headers:t.headers,auth:t.auth?{CLIENT_ID:t.auth.CLIENT_ID,CLIENT_SECRET:t.auth.CLIENT_SECRET,scopes:t.auth.scopes?[...t.auth.scopes]:void 0}:void 0};return"sse"===t.type?{...r,type:"sse"}:r}throw new Error(`Invalid inline MCP server config for "${e}"`)}function YO(e){return"claude-plugin"===e.pluginSource}const eF=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass"];function tF(e){let t=e.trim();t.startsWith("&")&&(t=t.slice(1).trim());const r=t.charAt(0);if("'"!==r&&'"'!==r)return t.split(/\s/)[0]??"";let n="";for(let e=1;e0)return{...n,followup_message:n.reason.trim()};if(!cF(t))return n;const o=uF(e),s=dF(o,r)?o:void 0,i=void 0!==s?{...n,...s}:n;return"block"===i.decision&&"string"==typeof i.reason&&i.reason.trim().length>0?{...i,followup_message:i.reason.trim()}:n}const pF=e=>{const t=[];return Td(e)?$d(!0):(t.push("Expected an object"),$d(!1,t))},fF=e=>{const t=[],r=pF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny","ask"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("Invalid user_message value. Expected a string if provided"),void 0!==e.agent_message&&"string"!=typeof e.agent_message&&t.push("Invalid agent_message value. Expected a string if provided"),$d(0===t.length,t)};function mF(e){const t=e.modelId,r=e.modelParams;return{...void 0!==t&&{model_id:t},...void 0!==r&&r.length>0?{model_params:r.map((e=>({id:e.id,value:e.value})))}:{}}}const gF=new Set([Rd.sessionStart,Rd.beforeSubmitPrompt,Rd.preToolUse,Rd.postToolUse,Rd.postToolUseFailure]);function wF(e){return"prompt"===e.type}function yF(e){return"command"===e.type||void 0===e.type}const vF={[Rd.beforeShellExecution]:fF,[Rd.beforeMCPExecution]:fF,[Rd.afterShellExecution]:e=>{const t=pF(e);return t.isValid,t},[Rd.afterMCPExecution]:e=>{const t=pF(e);return t.isValid,t},[Rd.beforeReadFile]:e=>{const t=[],r=pF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("user_message must be a string if provided"),$d(0===t.length,t)},[Rd.afterFileEdit]:e=>{const t=pF(e);return t.isValid,t},[Rd.beforeTabFileRead]:e=>{const t=[],r=pF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("user_message must be a string if provided"),$d(0===t.length,t)},[Rd.afterTabFileEdit]:e=>pF(e),[Rd.beforeSubmitPrompt]:e=>{const t=pF(e);if(!t.isValid)return t;const r=[];return void 0!==e.continue&&"boolean"!=typeof e.continue&&r.push("continue must be a boolean if provided"),void 0!==e.user_message&&"string"!=typeof e.user_message&&r.push("user_message must be a string if provided"),void 0===e.additional_context||Id(e.additional_context)||r.push("additional_context must be a string if provided"),$d(0===r.length,r)},[Rd.stop]:e=>{const t=pF(e);if(!t.isValid)return t;const r=[];return void 0!==e.followup_message&&"string"!=typeof e.followup_message&&r.push("followup_message must be a string if provided"),$d(0===r.length,r)},[Rd.afterAgentResponse]:e=>{const t=pF(e);return t.isValid,t},[Rd.afterAgentThought]:e=>{const t=pF(e);return t.isValid,t},[Rd.sessionStart]:e=>{const t=pF(e);if(!t.isValid)return t;const r=[];if(void 0!==e.env)if(Td(e.env))for(const[t,n]of Object.entries(e.env))Id(t)||r.push(`env key "${t}" must be a string`),Id(n)||r.push(`env value for "${t}" must be a string`);else r.push("env must be an object if provided");return void 0===e.additional_context||Id(e.additional_context)||r.push("additional_context must be a string if provided"),void 0!==e.continue&&"boolean"!=typeof e.continue&&r.push("continue must be a boolean if provided"),void 0===e.user_message||Id(e.user_message)||r.push("user_message must be a string if provided"),$d(0===r.length,r)},[Rd.sessionEnd]:e=>{const t=pF(e);return t.isValid?$d(!0,[]):t},[Rd.preCompact]:e=>{const t=pF(e);if(!t.isValid)return t;if(null==e||0===Object.keys(e).length)return $d(!0,[]);const r=[];if(!Ad(e))return r.push("PreCompact response must be an object"),$d(!1,r);const n=e;return void 0===n.user_message||(e=>"string"==typeof e)(n.user_message)||r.push("user_message must be a string"),$d(0===r.length,r)},[Rd.subagentStart]:e=>{const t=pF(e);if(!t.isValid)return t;if(!Ad(e))return $d(!1,["Expected an object"]);const r=[],n=e;if(void 0!==n.permission){const e=["allow","deny","ask"];"string"==typeof n.permission&&e.includes(n.permission)||r.push(`Invalid permission value. Expected one of: ${e.join(", ")}, or undefined`)}return void 0===n.user_message||Id(n.user_message)||r.push("user_message must be a string if provided"),$d(0===r.length,r)},[Rd.subagentStop]:e=>{const t=pF(e);if(!t.isValid)return t;const r=[];return Ad(e)&&void 0!==e.followup_message&&"string"!=typeof e.followup_message&&r.push("followup_message must be a string if provided"),$d(0===r.length,r)},[Rd.preToolUse]:e=>{const t=[],r=pF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny","ask"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("Invalid user_message value. Expected a string if provided"),void 0!==e.agent_message&&"string"!=typeof e.agent_message&&t.push("Invalid agent_message value. Expected a string if provided"),void 0!==e.updated_input&&("object"!=typeof e.updated_input||null===e.updated_input||Array.isArray(e.updated_input))&&t.push("Invalid updated_input value. Expected a plain object if provided"),Md(e.additional_context,"additional_context",t),$d(0===t.length,t)},[Rd.postToolUse]:e=>{const t=[],r=pF(e);return r.isValid?(Md(e.additional_context,"additional_context",t),$d(0===t.length,t)):r},[Rd.postToolUseFailure]:e=>{const t=pF(e);if(!t.isValid)return t;const r=[];return Md(e.additional_context,"additional_context",r),$d(0===r.length,r)},[Rd.workspaceOpen]:e=>{const t=pF(e);if(!t.isValid)return t;const r=[];return void 0!==e.pluginPaths&&(Array.isArray(e.pluginPaths)?e.pluginPaths.forEach(((e,t)=>{"string"==typeof e?0===e.trim().length&&r.push(`pluginPaths[${t}] must be a non-empty string`):r.push(`pluginPaths[${t}] must be a string`)})):r.push("pluginPaths must be an array of strings if provided")),$d(0===r.length,r)}},bF=(e,t,r)=>{const n=function(e,t,r){let n;return n=e===Rd.preToolUse?function(e,t){if(!lF(e))return e;const r=e;if(void 0!==r.permission||void 0!==r.user_message||void 0!==r.agent_message||void 0!==r.updated_input)return r;if(!cF(t))return r;const n=uF(e);if(!dF(n,"PreToolUse"))return r;const o={...r};let s=!1;return void 0!==n.permissionDecision&&(o.permission=n.permissionDecision,s=!0),"string"==typeof n.permissionDecisionReason&&(o.user_message=n.permissionDecisionReason,s=!0),lF(n.updatedInput)&&(o.updated_input=n.updatedInput,s=!0),s?o:r}(t,r):e===Rd.stop?hF(t,r,"Stop"):e===Rd.subagentStop?hF(t,r,"SubagentStop"):t,function(e,t,r,n){if(!gF.has(e)||!lF(r)||void 0!==r.additional_context)return r;const o=lF(t)?function(e){return"string"==typeof e.additionalContext?e.additionalContext:void 0}(t)??function(e,t,r){if(!cF(r))return;const n=Ld[e];if(void 0===n)return;const o=uF(t);return dF(o,n)&&"string"==typeof o.additionalContext?o.additionalContext:void 0}(e,t,n):void 0;return void 0===o?r:{...r,additional_context:o}}(e,t,n,r)}(e,t,r),o=(0,vF[e])(n);return o.isValid?{success:!0,data:n}:{success:!1,errors:o.errors}},SF=[Rd.beforeShellExecution,Rd.beforeMCPExecution,Rd.beforeReadFile,Rd.beforeTabFileRead,Rd.subagentStart,Rd.preToolUse],kF=[Rd.workspaceOpen];function _F(e,t){const r=[];return"string"==typeof e&&e.trim()&&r.push(e.trim()),"string"==typeof t&&t.trim()&&r.push(t.trim()),r.length>0?r.join("\n\n---\n\n"):void 0}function CF(e,t){return{..."object"==typeof e&&null!==e?e:{},...t}}function EF(e){return SF.includes(e)}function xF({step:e,command:t,failClosed:r,kind:n}){const o=EF(e);if(!r&&!o)return{shouldNotifyUser:!1};const s=r?"Tool blocked because this hook is configured to fail closed (block when it fails). "+("invalid_json"===n?`Hook "${t}" returned invalid JSON.`:`Hook "${t}" returned invalid response.`):"invalid_json"===n?`Hook "${t}" returned invalid JSON. The command was blocked for safety.`:`Hook "${t}" returned an invalid response for this hook step. The command was blocked for safety.`;return{blockResponse:RF(e,s),cause:r?"script_fail_closed":"permission_hook_invalid_output",reason:s,shouldNotifyUser:o&&!r}}function PF(e,t){return t}function RF(e,t){return EF(e)?PF(0,{permission:"deny",user_message:t}):e===Rd.beforeSubmitPrompt||e===Rd.sessionStart?PF(0,{continue:!1,user_message:t}):e===Rd.stop?PF(0,{}):void 0}function IF(e){try{return{value:JSON.parse(e)}}catch{return}}function TF(e){if("object"!=typeof e||null===e)return!1;const t=e.event;return"backgrounded"===t?.case}function AF(e){if("object"!=typeof e||null===e)return;const t=e.path;return"string"==typeof t&&t.length>0?t:void 0}class $F{cacheCarriersForExecId(e,t){const r=this.carriersByExecId.get(e);if(!(void 0!==r&&r.length>0&&0===t.length))for(this.carriersByExecId.has(e)&&this.carriersByExecId.delete(e),this.carriersByExecId.set(e,t);this.carriersByExecId.size>$F.CARRIERS_BY_EXEC_ID_MAX;){const e=this.carriersByExecId.keys().next().value;if(void 0===e)break;this.carriersByExecId.delete(e)}}constructor(e,t,r,n){this.inner=e,this.wake=r,this.carriersByExecId=new Map,this.inFlightByExecId=new Map,this.resolveDrain="function"==typeof t?t:e=>t,this.skipPathWriteDrain=n?.skipPathWriteDrain,this.onWakeWrittenPath=n?.onWakeWrittenPath,this.forceWrittenPathBeforeDrain=n?.forceWrittenPathBeforeDrain,this.writeBarrierTimeoutMs=n?.writeBarrierTimeoutMs??2e3,this.resolveWriteBarrierTimeoutMs=n?.resolveWriteBarrierTimeoutMs,this.onWriteBarrier=n?.onWriteBarrier}resolveTimeoutMs(){if(void 0!==this.resolveWriteBarrierTimeoutMs)try{const e=this.resolveWriteBarrierTimeoutMs();if("number"==typeof e&&Number.isFinite(e))return e}catch{}return this.writeBarrierTimeoutMs}get(e){return this.wrapImpl(e.symbol,this.inner.get(e))}*entries(){for(const[e,t]of this.inner.entries())yield[e,this.wrapImpl(e.symbol,t)]}wrapImpl(e,t){if(!function(e){return"object"==typeof e&&null!==e&&"execute"in e&&"function"==typeof e.execute}(t))return t;const r=function(e){return e===GT.symbol||e===VT.symbol?{kind:"path"}:e===WT.symbol||e===re.symbol||e===kA.symbol?{kind:"exposed"}:void 0}(e),n=this.resolveDrain,o=this.wake,s=this.skipPathWriteDrain,i=this.forceWrittenPathBeforeDrain,a=()=>this.resolveTimeoutMs(),c=this.onWriteBarrier,l=this.onWakeWrittenPath,u=(e,t)=>{if(void 0!==r&&void 0!==o)try{if("path"===r.kind){const r=AF(e);void 0!==r&&(o.wakeForWrittenPath(r),l?.(r,t))}else o.wakeExposedMounts()}catch{}},d=this.cacheCarriersForExecId.bind(this),h=this.carriersByExecId,p=this.inFlightByExecId,f=async(e,t)=>{const r=t?.hookContextCollector;if(void 0===r)return[];if(!1===t?.deliverAgentStoreConflictNotices)return[];const o=void 0!==t?.execId&&t.execId.length>0?t.execId:void 0;if(void 0!==o){const e=h.get(o);if(void 0!==e)return e.length>0&&r.push(...e),e;const t=p.get(o);if(void 0!==t){const e=await t;return e.length>0&&r.push(...e),e}}const s=async t=>{const r=n(e);let s=[];try{const e=await r.peek();if(s=e.eventIds,e.carriers.length>0)return t.push(...e.carriers),r.ack(e.eventIds),void 0!==o&&d(o,e.carriers),e.carriers;s.length>0&&r.ack(s);const n=[];return void 0!==o&&d(o,n),n}catch{return s.length>0&&r.release(s),[]}};if(void 0===o)return await s(r);const i=s(r);p.set(o,i);try{return await i}finally{p.get(o)===i&&p.delete(o)}};return new Proxy(t,{get:(t,n,o)=>"execute"!==n?Reflect.get(t,n,o):(n,o,l)=>{const d=t.execute.call(t,n,o,l);return"object"==typeof(h=d)&&null!==h&&Symbol.asyncIterator in h&&"function"==typeof h[Symbol.asyncIterator]?async function*(){let t=!1,r=!1,s=!1;try{for await(const r of d)if(e===re.symbol&&TF(r)){if(!t){u(o,n);const e=await f(n,l);t=!0,e.length>0&&(yield new fe.FI({event:{case:"hookContext",value:new fe.Ng({hookAdditionalContexts:[...e]})}}))}yield r}else yield r;s=!0}catch(e){throw r=!0,e}finally{u(o,n),t||r||!s||await f(n,l)}}():function(e){return"object"==typeof e&&null!==e&&"then"in e&&"function"==typeof e.then}(d)?(async()=>{try{const t=await d;return u(o,n),e===GT.symbol&&!0===s?.()&&!0===l?.enableAgentStoreConflictNotices||(await async function(e,t,r,n){const o=e=>{try{n.onWriteBarrier?.(e)}catch{}};if(void 0===e||"path"!==r?.kind)return;const s=AF(t);if(void 0===s)return;if(!(n.timeoutMs>0))return void o({durationMs:0,outcome:"skipped"});const i=Date.now(),a=e(s).then((e=>e),(()=>"error")),c=await Promise.race([a,(0,Nr.cb)(n.timeoutMs).then((()=>"timeout"))]);"not_store_path"!==c&&o({durationMs:Date.now()-i,outcome:c})}(i,o,r,{timeoutMs:a(),onWriteBarrier:c}),await f(n,l)),t}catch(e){throw u(o,n),e}})():(u(o,n),d);var h}})}}function MF(e){return new RegExp(`<${e}(?:\\s[^>]*)?>[\\s\\S]*?`,"gi")}$F.CARRIERS_BY_EXEC_ID_MAX=32,Error,iu.execFileSync,new Map,Ro.constants.O_NOFOLLOW,new Set(["write_conflict","create_conflict","truncate_conflict_failed","conflict_fallback_failed","quota_exceeded","gap"]),new Set(["write_conflict","create_conflict","truncate_conflict_failed","conflict_fallback_failed","quota_exceeded"]),Math.max(1,Math.floor(8192));const DF=["user_info","project_layout","rules","always_applied_workspace_rules","agent_requestable_workspace_rules","user_rules","agent_skills","available_skills","cloud_instructions","cloud_task_instructions","open_and_recently_viewed_files","system_reminder","system-reminder","instructions_update","mcp_instructions","mcp_file_system","mcp_file_system_servers","git_status","agent_transcripts","cursor_rules_context","attached_files","system_notification","task_notification","agent_notification"].map(MF);function OF(e){return function(e,t){let r=e;if(r.includes("<"))for(const e of t)r=r.replace(e,"");return(r.includes("\n\n\n")?r.replace(FF,"\n\n"):r).trim()}(e,DF)}["system_reminder","system-reminder"].map(MF);const FF=/\n{3,}/g;function NF(e){const t=(0,_o.sh)(e.conversationId);if("subagent"===e.kind&&e.parentConversationId){const r=(0,_o.sh)(e.parentConversationId);return`${_o.O2}/${r}/subagents/${t}.${e.ext}`}return`${_o.O2}/${t}/${t}.${e.ext}`}function LF(e){const t=(0,_o.sh)(e.conversationId);return`${_o.O2}/${t}.${e.ext}`}function jF(e){const t=e.exts??["jsonl","txt"],r=e.includeLegacy??!0,n=[],o=e=>{n.includes(e)||n.push(e)};for(const n of t)o(NF({conversationId:e.conversationId,ext:n,kind:e.kind,parentConversationId:e.parentConversationId})),"subagent"===e.kind&&e.parentConversationId&&o(NF({conversationId:e.conversationId,ext:n,kind:"primary"})),r&&o(LF({conversationId:e.conversationId,ext:n}));return n}var UF;!function(e){e.INTERNAL="INTERNAL",e.EXTERNAL="EXTERNAL",e.NO_PREAMBLE="NO_PREAMBLE"}(UF||(UF={}));var BF=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},WF=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function HF(e){switch(e){case c.xyI.AGENT:return"agent";case c.xyI.ASK:return"ask";case c.xyI.PLAN:return"plan";case c.xyI.DEBUG:return"debug";case c.xyI.TRIAGE:return"triage";case c.xyI.MULTITASK:return"multitask";case c.xyI.CUSTOM:return"custom";case c.xyI.UNSPECIFIED:default:return"agent"}}function qF(e,t){return t instanceof Uint8Array?{__type:"Uint8Array",hex:(r=t,Array.from(r).map((e=>e.toString(16).padStart(2,"0"))).join(""))}:"bigint"==typeof t?t.toString():t;var r}function zF(e,t){return function(e){return"object"==typeof e&&null!==e&&"__type"in e&&"Uint8Array"===e.__type&&"hex"in e&&"string"==typeof e.hex}(t)?`[Binary data omitted from transcript: ${t.hex.length/2} bytes]`:t}const GF=new TextEncoder,VF=new TextDecoder,KF=new class{serialize(e){const t=JSON.stringify(e,qF);return GF.encode(t)}deserialize(e){const t=VF.decode(e);return t.includes('"__type":"Uint8Array"')?JSON.parse(t,zF):JSON.parse(t)}};function JF(e){const t=e.providerOptions;return!0===t?.cursor?.isSummary}function ZF(e){return"system"!==e.role&&!JF(e)}function XF(e,t){return"user"===e.role&&"user"===t.role}async function QF(e,t,r){const n=await t.getBlob(e,r);return n?c.Anz.fromBinary(n).summarizedMessages:[]}async function YF(e,t,r,n){const o=await t.getBlob(e,r);if(o){if(o.length>5e6)return n.omittedOversizeBlobCount++,n.omittedOversizeBlobBytes+=o.length,n.largestOmittedOversizeBlobBytes=Math.max(n.largestOmittedOversizeBlobBytes,o.length),{role:"assistant",content:`[Oversize transcript blob omitted: ${s=o.length,`${(s/1e6).toFixed(1)} MB`}]`};var s;try{const e=performance.now(),t=KF.deserialize(o);return n.totalDeserializeDurationMs+=performance.now()-e,n.hydratedBlobCount++,n.hydratedBlobBytes+=o.length,n.largestHydratedBlobBytes=Math.max(n.largestHydratedBlobBytes,o.length),t}catch{return}}}async function eN(e,t,r){const n={messages:[],hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0};for(const o of r){const r=await YF(e,t,o,n);r&&n.messages.push(r)}return n}async function tN(e,t,r,n,o){const s=[];let i=0;const a=()=>{const o=YF(e,t,r[i++],n);o.catch((()=>{})),s.push(o)};for(;i{let r;return r="string"==typeof t?t:"object"==typeof t&&null!==t?JSON.stringify(t):String(t),` ${e}: ${r}`})).join("\n")}`}(e.args)}`;case"tool-result":return`[Tool result] ${e.toolName}`;default:return""}}function nN(e){return OF(e)}const oN=/[\s\S]*?<\/think>/gi,sN=/[\s\S]*?<\/thinking>/gi,iN=/\n{3,}/g;function aN(e){let t=e;return t.includes("<")&&(t=t.replace(oN,"").replace(sN,"")),(t.includes("\n\n\n")?t.replace(iN,"\n\n"):t).trim()}function cN(e,t,r){if(void 0===e)return"";if("string"==typeof e){const n=t?nN(e):e;return r?aN(n):n}return e.map((e=>{if(r&&"text"===e.type){const r=aN(t?nN(e.text):e.text);return rN({...e,text:r},!1)}return rN(e,t)})).filter(Boolean).join("\n")}function lN(e,t){const r={role:e.role},n=e.content;if("string"==typeof n){const o=t?nN(n):n,s="assistant"===e.role?aN(o):o;s.trim()&&(r.text=s)}else if(Array.isArray(n)){const o=[],s=[],i=[];let a;for(const r of n)switch(r.type){case"text":{const n=t?nN(r.text):r.text,s="assistant"===e.role?aN(n):n;s.trim()&&o.push(s);break}case"reasoning":r.text.trim()&&s.push(r.text);break;case"redacted-reasoning":s.push("[REDACTED]");break;case"image":o.push("[Image]");break;case"file":o.push(r.filename?`[File: ${r.filename}]`:"[File]");break;case"tool-call":i.push({toolName:r.toolName,args:r.args});break;case"tool-result":a={toolName:r.toolName}}o.length>0&&(r.text=o.join("\n")),s.length>0&&(r.thinking=s.join("\n")),i.length>0&&(r.toolCalls=i),a&&(r.toolResult=a)}return r}function uN(e){return e.endsWith("\n")?e:`${e}\n`}function dN(e){const{turnEnded:t}=e,r=[],n={},o=[];return void 0!==t&&(r.push(function(e){switch(e.status){case"success":return"Turn ended: success.";case"error":return`Turn ended: error: ${e.error}`;case"aborted":return e.error?`Turn ended: aborted: ${e.error}`:"Turn ended: aborted.";default:return e}}(t)),n.turnEnded=t,o.push(JSON.stringify({type:"turn_ended",...t}))),{textSuffixes:r,jsonFields:n,jsonlLines:o}}function hN(e){if("system"===e.role||JF(e))return;const t=lN(e,"user"===e.role),r=[],n=[];if(t.text&&n.push(t.text),t.thinking&&n.push(t.thinking),n.length>0&&r.push({type:"text",text:n.join("\n\n")}),t.toolCalls)for(const e of t.toolCalls)r.push({type:"tool_use",name:e.toolName,input:e.args});if(0===r.length)return;const o={role:e.role,message:{content:r}};return JSON.stringify(o)}class pN{constructor(e,t,r,n={}){this.projectDir=e,this.blobStore=t,this.writeFile=r,this.options={writeText:n.writeText??!0,writeJson:n.writeJson??!1,writeJsonl:n.writeJsonl??!1,pathResolver:n.pathResolver,appendFile:n.appendFile,streamFullJsonlWrites:n.streamFullJsonlWrites??!1,fallbackToFullWriteOnIncrementalFailure:n.fallbackToFullWriteOnIncrementalFailure??!0}}resolveFilePath(e,t){if(this.options.pathResolver)return this.options.pathResolver(e,t);const r=NF({conversationId:e,ext:t,kind:"primary"});return`${this.projectDir}/${r}`}async writeFromStateFull(e,t,r,n={}){const o={stack:[],error:void 0,hasError:!1};try{const s=BF(o,(0,D.VI)(e.withName("writeFromState")),!1);try{const{overviewFactory:e}=n,o=dN(n),{appendFile:i,streamFullJsonlWrites:a,writeJsonl:c,writeText:l,writeJson:u}=this.options;if(i&&a&&c&&!l&&!u&&!e)try{return await this.writeJsonlStreamed(s,{state:t,filePath:this.resolveFilePath(r,"jsonl"),appendFile:i,terminalLines:o.jsonlLines}),!0}catch(e){console.error("[TranscriptStore] Streamed transcript write failed, retrying as a single write:",e)}const d=await async function(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=BF(n,(0,D.VI)(e.withName("hydrateSummaryArchives")),!1);let s=0;const i=(0,D.OA)(o.ctx),a=[];let c=0,l=0,u=0,d=0,h=0,p=0,f=0;const m=await Promise.all(r.summaryArchives.map((async e=>{s++;try{const r=await QF(i,t,e);return s+=r.length,await eN(i,t,r)}catch{return{messages:[],hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0}}})));for(const e of m)a.push(...e.messages),c+=e.hydratedBlobCount,l+=e.hydratedBlobBytes,u=Math.max(u,e.largestHydratedBlobBytes),d+=e.totalDeserializeDurationMs,h+=e.omittedOversizeBlobCount,p+=e.omittedOversizeBlobBytes,f=Math.max(f,e.largestOmittedOversizeBlobBytes);o.span.setAttribute("getBlobCount",s),o.span.setAttribute("hydratedBlobCount",c),o.span.setAttribute("hydratedBlobBytes",l),o.span.setAttribute("largestHydratedBlobBytes",u),o.span.setAttribute("totalDeserializeDurationMs",d),o.span.setAttribute("omittedOversizeBlobCount",h),o.span.setAttribute("omittedOversizeBlobBytes",p),o.span.setAttribute("largestOmittedOversizeBlobBytes",f);const g=BF(n,(0,D.VI)(e.withName("hydratePromptMessages")),!1),w=await eN(i,t,r.rootPromptMessagesJson);g.span.setAttribute("getBlobCount",r.rootPromptMessagesJson.length),g.span.setAttribute("hydratedBlobCount",w.hydratedBlobCount),g.span.setAttribute("hydratedBlobBytes",w.hydratedBlobBytes),g.span.setAttribute("largestHydratedBlobBytes",w.largestHydratedBlobBytes),g.span.setAttribute("totalDeserializeDurationMs",w.totalDeserializeDurationMs),g.span.setAttribute("omittedOversizeBlobCount",w.omittedOversizeBlobCount),g.span.setAttribute("omittedOversizeBlobBytes",w.omittedOversizeBlobBytes),g.span.setAttribute("largestOmittedOversizeBlobBytes",w.largestOmittedOversizeBlobBytes);const y=w.messages.filter(ZF);return a.push(...y),a}catch(e){n.error=e,n.hasError=!0}finally{WF(n)}}(s.ctx,this.blobStore,t);if(0===d.length&&0===o.jsonlLines.length)return!0;let h;if((this.options.writeText||e)&&(h=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&"user"===t[0].role&&"user"===t[1].role&&(t=t.slice(1));const r=[];for(const e of t){const t="user"===e.role,n="assistant"===e.role,o=cN(e.content,t,n);o.trim()&&("tool"===e.role?r.push(o):r.push(`${e.role}:\n${o}`))}return r.join("\n\n")}(d)),this.options.writeText){const e=h??"",t=o.textSuffixes.length>0?e.trim().length>0?`${e}\n\n${o.textSuffixes.join("\n")}`:o.textSuffixes.join("\n"):e;t.trim()&&await this.writeFile(this.resolveFilePath(r,"txt"),t)}if(this.options.writeJson){const e=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&"user"===t[0].role&&"user"===t[1].role&&(t=t.slice(1));const r=[];for(const e of t){const t=lN(e,"user"===e.role);(t.text||t.thinking||t.toolCalls||t.toolResult)&&r.push(t)}return 0===r.length?"":JSON.stringify(r,null,2)}(d);if(e||o.jsonlLines.length>0){const n={mode:HF(t.mode),messages:e?JSON.parse(e):[],...o.jsonFields};await this.writeFile(this.resolveFilePath(r,"json"),JSON.stringify(n,null,2))}}if(this.options.writeJsonl){const t=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&XF(t[0],t[1])&&(t=t.slice(1));const r=[];for(const e of t){const t=hN(e);t&&r.push(t)}return r.join("\n")}(d);let n=[t,...o.jsonlLines].filter((e=>e.length>0)).join("\n");if(n&&e&&h?.trim())try{const t=(await e(h)).trim();t&&(n=function(e,t){const r={type:"metadata",metadata:{overview:t}};return`${JSON.stringify(r)}\n${e}`}(n,t))}catch(e){console.error("[TranscriptStore] Failed to generate transcript overview:",e)}n&&await this.writeFile(this.resolveFilePath(r,"jsonl"),uN(n))}return!0}catch(e){return console.error("[TranscriptStore] Failed to write transcript:",e),!1}}catch(e){o.error=e,o.hasError=!0}finally{WF(o)}}async writeJsonlStreamed(e,t){const{filePath:r,appendFile:n}=t;let o=[],s=0,i=0,a=0;const c=async()=>{if(0===o.length)return;const e=`${o.join("\n")}\n`;o=[],s=0,0===i?await this.writeFile(r,e):await n(r,e),i++,a+=e.length},l=async e=>{e&&(o.push(e),s+=e.length+1,s>=1e6&&await c())};let u,d=0;const h=await async function(e,t,r,n){const o={hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0};for(const s of r.summaryArchives){let r;try{r=await QF(e,t,s)}catch{continue}await tN(e,t,r,o,{skipFailedReads:!0,visit:n})}return await tN(e,t,r.rootPromptMessagesJson,o,{skipFailedReads:!1,visit:async e=>{ZF(e)&&await n(e)}}),o}((0,D.OA)(e.ctx),this.blobStore,t.state,(async e=>{"system"!==e.role&&(d++,1!==d?(2===d&&u&&(XF(u,e)||await l(hN(u)),u=void 0),await l(hN(e))):u=e)}));u&&await l(hN(u));for(const e of t.terminalLines)await l(e);await c(),e.span.setAttribute("streamed",!0),e.span.setAttribute("chunkCount",i),e.span.setAttribute("writtenChars",a),e.span.setAttribute("hydratedBlobCount",h.hydratedBlobCount),e.span.setAttribute("hydratedBlobBytes",h.hydratedBlobBytes),e.span.setAttribute("largestHydratedBlobBytes",h.largestHydratedBlobBytes),e.span.setAttribute("totalDeserializeDurationMs",h.totalDeserializeDurationMs),e.span.setAttribute("omittedOversizeBlobCount",h.omittedOversizeBlobCount),e.span.setAttribute("omittedOversizeBlobBytes",h.omittedOversizeBlobBytes),e.span.setAttribute("largestOmittedOversizeBlobBytes",h.largestOmittedOversizeBlobBytes)}async writeFromStateIncremental(e,t,r,n,o={}){const s={stack:[],error:void 0,hasError:!1};try{const i=t.rootPromptMessagesJson.length,a=dN(o),c=a.jsonlLines.length>0;if(i===n&&!c&&!o.overviewFactory)return i;const l=this.options.appendFile;if(!(l&&this.options.writeJsonl&&!this.options.writeText&&!this.options.writeJson&&n>0&&i>=n&&(i>n||c))||o.overviewFactory)return await this.writeFromStateFull(e,t,r,o)?i:0;const u=BF(s,(0,D.VI)(e.withName("writeFromStateIncremental")),!1);if(i===n&&c)try{return await l(this.resolveFilePath(r,"jsonl"),uN(a.jsonlLines.join("\n"))),i}catch(n){return console.error(this.options.fallbackToFullWriteOnIncrementalFailure?"[TranscriptStore] Failed to append transcript, falling back to full write:":"[TranscriptStore] Failed to append transcript:",n),this.options.fallbackToFullWriteOnIncrementalFailure?await this.writeFromStateFull(e,t,r,o)?i:0:0}try{const e=t.rootPromptMessagesJson.slice(n),o=await eN(u.ctx,this.blobStore,e);u.span.setAttribute("hydratedBlobCount",o.hydratedBlobCount),u.span.setAttribute("hydratedBlobBytes",o.hydratedBlobBytes),u.span.setAttribute("largestHydratedBlobBytes",o.largestHydratedBlobBytes),u.span.setAttribute("totalDeserializeDurationMs",o.totalDeserializeDurationMs),u.span.setAttribute("omittedOversizeBlobCount",o.omittedOversizeBlobCount),u.span.setAttribute("omittedOversizeBlobBytes",o.omittedOversizeBlobBytes),u.span.setAttribute("largestOmittedOversizeBlobBytes",o.largestOmittedOversizeBlobBytes);const s=[];for(const e of o.messages){const t=hN(e);t&&s.push(t)}if(s.push(...a.jsonlLines),s.length>0){const e=uN(s.join("\n"));await l(this.resolveFilePath(r,"jsonl"),e)}return i}catch(n){return console.error(this.options.fallbackToFullWriteOnIncrementalFailure?"[TranscriptStore] Failed to append transcript, falling back to full write:":"[TranscriptStore] Failed to append transcript:",n),this.options.fallbackToFullWriteOnIncrementalFailure?await this.writeFromStateFull(e,t,r,o)?i:0:0}}catch(e){s.error=e,s.hasError=!0}finally{WF(s)}}}function fN(e,t){const r=function(e){return"object"==typeof e&&null!==e}(e)&&t in e?e[t]:void 0;return"string"==typeof r&&""!==r?r:void 0}function mN(e,t){return e.filter((e=>function(e,t){if(!e.matcher||""===e.matcher||"*"===e.matcher)return!0;if(void 0===t)return!0;try{return new RegExp(e.matcher).test(t)}catch{return!0}}(e,t)))}function gN(e){return`Tool blocked because this hook is configured to fail closed (block when it fails). ${e}`}function wN(e){return Object.values(Rd).some((t=>t===e))}function yN(e){switch(e??(0,o.platform)()){case"darwin":return s.join("/Library","Application Support","Cursor","hooks.json");case"win32":return s.join("C:\\","ProgramData","Cursor","hooks.json");default:return s.join("/etc","cursor","hooks.json")}}function vN(e){return wF(e)?`prompt:${e.prompt}`:`command:${e.command}`}function bN(e){return(e.repoHooks??[]).flatMap((e=>[e.projectHooks,e.claudeProjectHooks,e.claudeProjectLocalHooks]))}class SN{constructor(e,t,r){this.fileReader=e,this.paths=t,this.logger=r||{warn:e=>console.warn(`[hooks] ${e}`),info:e=>{}}}async load(e={}){const{loadProjectHooks:t=!0}=e,r={errors:[],configDirs:{}},n=this.paths.projectConfigPath??this.paths.claudeProjectConfigPath??this.paths.claudeProjectLocalConfigPath,o=n?s.dirname(s.dirname(n)):void 0,i=(e,t)=>{if(!e||!o)return;if(t)return o;const r=s.relative(s.resolve(o),s.resolve(e));return".."===r||r.startsWith(`..${s.sep}`)||s.isAbsolute(r)?void 0:o},a=async(e,t,n,o,i,a,c,l)=>{if(e)try{if(!await this.fileReader.exists(e))return;if(c&&this.fileReader.pathContainsSymlink&&await this.fileReader.pathContainsSymlink(e,c))return r.errors.push({source:t,message:`${i} at ${e}: refusing to load config path that contains a symlink`}),void this.logger.warn(`Refusing to load ${a} config via symlink path: ${e}`);const u=await this.fileReader.readFile(e);if(!u)return;const{config:d,error:h}=l(u);if(d){switch(n){case"enterpriseHooks":r.enterpriseHooks=d;break;case"teamHooks":r.teamHooks=d;break;case"userHooks":r.userHooks=d;break;case"projectHooks":r.projectHooks=d;break;case"claudeUserHooks":r.claudeUserHooks=d;break;case"claudeProjectHooks":r.claudeProjectHooks=d;break;case"claudeProjectLocalHooks":r.claudeProjectLocalHooks=d;break;default:return}((e,t)=>{r.configDirs[e]=s.dirname(t)})(o,e)}else h&&r.errors.push({source:t,message:`${i} at ${e}: ${h}`})}catch(e){r.errors.push({source:t,message:`Error accessing ${a} config file: ${String(e)}`})}},c=[{path:this.paths.enterpriseConfigPath,source:"enterprise",resultKey:"enterpriseHooks",configDirKey:"enterprise",parsePrefix:"Enterprise hooks.json",accessLabel:"enterprise",symlinkCheckRoot:i(this.paths.enterpriseConfigPath,!1)},{path:this.paths.teamConfigPath,source:"team",resultKey:"teamHooks",configDirKey:"team",parsePrefix:"Team hooks.json",accessLabel:"team",symlinkCheckRoot:i(this.paths.teamConfigPath,!1)},{path:this.paths.userConfigPath,source:"user",resultKey:"userHooks",configDirKey:"user",parsePrefix:"User hooks.json",accessLabel:"user",symlinkCheckRoot:i(this.paths.userConfigPath,!1)},{path:t?this.paths.projectConfigPath:void 0,source:"project",resultKey:"projectHooks",configDirKey:"project",parsePrefix:"Project hooks.json",accessLabel:"project",symlinkCheckRoot:i(this.paths.projectConfigPath,!0)}];for(const e of c)await a(e.path,e.source,e.resultKey,e.configDirKey,e.parsePrefix,e.accessLabel,e.symlinkCheckRoot,(t=>this.parseAndValidate(t,e.source)));const l=[{path:this.paths.claudeUserConfigPath,source:"claude-user",resultKey:"claudeUserHooks",configDirKey:"claudeUser",label:"user",symlinkCheckRoot:i(this.paths.claudeUserConfigPath,!1)},{path:t?this.paths.claudeProjectConfigPath:void 0,source:"claude-project",resultKey:"claudeProjectHooks",configDirKey:"claudeProject",label:"project",symlinkCheckRoot:i(this.paths.claudeProjectConfigPath,!0)},{path:t?this.paths.claudeProjectLocalConfigPath:void 0,source:"claude-project-local",resultKey:"claudeProjectLocalHooks",configDirKey:"claudeProjectLocal",label:"project local",symlinkCheckRoot:i(this.paths.claudeProjectLocalConfigPath,!0)}];for(const e of l)await a(e.path,e.source,e.resultKey,e.configDirKey,`Claude ${e.label} settings.json`,`Claude ${e.label}`,e.symlinkCheckRoot,(t=>this.parseClaudeConfig(t,e.source)));return function(e){const{cursorConfigs:t,claudeConfigs:r,logger:n}=e,o=new Map;for(const e of t)if(e?.hooks)for(const[t,r]of Object.entries(e.hooks)){if(!r)continue;let e=o.get(t);e||(e=new Set,o.set(t,e));for(const t of r)e.add(vN(t))}for(const{config:e,source:t}of r)if(e?.hooks)for(const[r,s]of Object.entries(e.hooks)){if(!s)continue;const i=o.get(r);if(!i||0===i.size)continue;const a=s.filter((e=>{const o=vN(e);return!i.has(o)||(n?.info(`Removed duplicate ${t} hook for ${r}: ${o}`),!1)}));a.length!==s.length&&(e.hooks[r]=a)}}({cursorConfigs:[r.enterpriseHooks,r.teamHooks,r.userHooks,r.projectHooks],claudeConfigs:[{config:r.claudeUserHooks,source:"claude-user"},{config:r.claudeProjectHooks,source:"claude-project"},{config:r.claudeProjectLocalHooks,source:"claude-project-local"}],logger:this.logger}),r}parseClaudeConfig(e,t){try{const t=JSON.parse(e);if(!function(e,t={}){if(!Ad(e))return!1;if(!("hooks"in e))return!1;const r=e.hooks;if(!Ad(r))return!1;const n=r;for(const[e,r]of Object.entries(n))if(e in Nd&&Array.isArray(r)){const n=!0===t.allowMatcherlessStop&&"Stop"===e;for(const e of r)if(Ad(e)&&"hooks"in e&&Array.isArray(e.hooks)&&("matcher"in e||n))return!0}return!1}(t))return{};const r=t.hooks;if(!r||0===Object.keys(r).length)return{};const n=Yd(r,this.logger),o=Fd(n);return o.isValid?{config:n}:{error:`Invalid transformed config: ${o.errors.join("; ")}`}}catch(e){return{error:`Failed to parse JSON: ${String(e)}`}}}parseAndValidate(e,t){try{const n=this.parseJSONC(e),o=Fd(n);return o.isValid?"object"==typeof(r=n)&&null!==r&&"version"in r&&"number"==typeof r.version&&"hooks"in r&&"object"==typeof r.hooks&&null!==r.hooks&&!Array.isArray(r.hooks)?{config:n}:{error:`Invalid ${t} config: missing 'hooks' property`}:{error:`Invalid ${t} config: ${o.errors.join("; ")}`}}catch(e){return{error:`Failed to parse ${t} config JSON: ${String(e)}`}}var r}parseJSONC(e){let t=e.replace(/\/\/.*$/gm,"");return t=t.replace(/\/\*[\s\S]*?\*\//g,""),JSON.parse(t)}static getConfiguredSteps(e){const t=new Set,r=[e.enterpriseHooks,e.teamHooks,e.userHooks,e.projectHooks,e.claudeUserHooks,e.claudeProjectHooks,e.claudeProjectLocalHooks,...bN(e)];for(const e of r)if(e?.hooks)for(const r of Object.keys(e.hooks))wN(r)&&t.add(r);for(const r of e.pluginHooks??[])for(const e of Object.keys(r.config.hooks))wN(e)&&t.add(e);return t}}const kN="Read",_N="Write",CN="Delete",EN="List",xN="Grep",PN="Shell",RN="ReadLints";function IN(e,t){if("object"==typeof e&&null!==e)return Object.getOwnPropertyDescriptor(e,t)?.value}const TN=new Set([kN,_N,CN,EN,xN,RN]);function AN(e){const t=IN(e,"tool_name"),r=[IN(e,"file_path"),"string"==typeof t&&TN.has(t)?IN(IN(e,"tool_input"),"file_path"):void 0];for(const e of r)if("string"==typeof e&&e.length>0)return e}const $N=(0,d.h)("cli-hooks-executor");function MN(e){try{return(0,Ro.statSync)(e).isFile()}catch{return!1}}const DN="\nJSON Parse Error: Error: Failed to parse hook stdout as JSON";function ON(e,t){for(const[r,n]of Object.entries(e))if(r===t)return n}function FN(e,t){const r=ON(e,t);if("string"==typeof r||null===r)return r}class NN{constructor(e,t,r,n,o,s,i,a){this.workspacePath=t,this.globalContext=r,this.shellExecutor=n,this.promptHookClient=o,this.onHookExecution=i,this.options=a,this.sessionEnvById=new Map,this.sessionUserEmailById=new Map,this.activeSessionIdsByConversationId=new Map,this.transcriptParentConversationIdById=new Map,this.configReadyPromises=[],this.config=e,s&&this.addConfigReadyPromise(s)}addConfigReadyPromise(e){this.configReadyPromises.push(e.catch((()=>{})))}reportCommandFailure(e,t){if(void 0!==e)try{e(t)}catch{}}finishHookRun(e,t,r,n){const o=e.transportMode??("prompt"===e.hookType?"prompt":this.getCommandHookPayloadTransportMode());try{this.onHookExecution?.({...e,transportMode:o})}catch{}const s=this.options?.onHookRun;if(void 0===s)return;const i=n.exitCode??e.exitCode,a="spawn_error"===(c=e.errorClass)?"shell_exec_transport_error":"prompt_error"===c?"prompt_execution_error":void 0;var c;try{s({step:e.hookStep,script:t,source:e.hookSource,...void 0===e.pluginId?{}:{pluginId:e.pluginId},request:r,response:n.response??null,status:e.status,durationMs:e.latencyMs,...void 0===i?{}:{exitCode:i},stderr:n.stderr,transportMode:o,configuredTimeoutSec:t.timeout??60,timedOut:!0===e.timedOut,...void 0===a?{}:{failureType:a}})}catch{}}getCommandHookPayloadTransportMode(){return"stdin"===this.options?.commandHookPayloadTransport?"win32"===process.platform?"windows_temp_file":"stdin":"argv_heredoc"}shouldUseCommandHookDirectStdinTransport(){return"stdin"===this.getCommandHookPayloadTransportMode()}async writeCommandHookStdinPayload(e,t){if(!e)throw new Error("Hook stdin transport was requested, but the executor did not provide stdin");try{e.end(Buffer.from(t,"utf8"))}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;if("EPIPE"===t||"ERR_STREAM_DESTROYED"===t||"ERR_STREAM_PREMATURE_CLOSE"===t)return;throw e}try{await(0,lh.finished)(e)}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;if("EPIPE"===t||"ERR_STREAM_DESTROYED"===t||"ERR_STREAM_PREMATURE_CLOSE"===t)return;throw e}}updateConfig(e){this.config=e}beginSessionEnvironment(e,t){this.sessionEnvById.delete(e.sessionId),this.sessionUserEmailById.delete(e.sessionId);const r=this.activeSessionIdsByConversationId.get(e.conversationId)??[];this.activeSessionIdsByConversationId.set(e.conversationId,r.filter((t=>t!==e.sessionId)).concat(e.sessionId));const n=t?.userEmail?.trim()??"";n.length>0&&this.sessionUserEmailById.set(e.sessionId,n)}setSessionUserEmail(e,t){const r=t?.trim()??"";0!==r.length&&this.sessionUserEmailById.set(e.sessionId,r)}setSessionEnvironment(e,t){void 0===t?this.sessionEnv={...this.sessionEnv,...e}:this.sessionEnvById.set(t.sessionId,{...this.sessionEnvById.get(t.sessionId),...e})}clearSessionEnvironment(e){if(void 0===e)this.sessionEnv=void 0;else{this.sessionEnvById.delete(e.sessionId),this.sessionUserEmailById.delete(e.sessionId);const t=(this.activeSessionIdsByConversationId.get(e.conversationId)??[]).filter((t=>t!==e.sessionId));0===t.length?this.activeSessionIdsByConversationId.delete(e.conversationId):this.activeSessionIdsByConversationId.set(e.conversationId,t)}}resolveUserEmail(e){const{conversation_id:t,session_id:r}=e;if(void 0!==r&&this.sessionUserEmailById.has(r))return this.sessionUserEmailById.get(r)??null;if(void 0!==t){const e=this.activeSessionIdsByConversationId.get(t)?.at(-1);if(void 0!==e){const t=this.sessionUserEmailById.get(e);if(void 0!==t)return t}}return this.globalContext.user_email}setTranscriptParentConversationId(e,t){this.transcriptParentConversationIdById.set(e,t)}async getTranscriptPathIfExists(e){try{const t=(0,_o.Rv)((0,o.homedir)(),this.workspacePath),r=this.transcriptParentConversationIdById.get(e),n=jF(r?{conversationId:e,kind:"subagent",parentConversationId:r}:{conversationId:e,kind:"primary"}).map((e=>(0,s.join)(t,e)));for(const e of n)try{return await(0,xo.access)(e),e}catch{}return null}catch{return null}}async getSubagentTranscriptPathIfExists(e){const{subagentId:t,parentConversationId:r}=e;try{const e=(0,_o.Rv)((0,o.homedir)(),this.workspacePath),n=jF({conversationId:t,kind:"subagent",parentConversationId:r}).map((t=>(0,s.join)(e,t)));for(const e of n)try{return await(0,xo.access)(e),e}catch{}return null}catch{return null}}hasHooksForStep(e){return[this.config.enterpriseHooks,this.config.teamHooks,this.config.userHooks,this.config.projectHooks,this.options?.runtimeHooks,this.config.claudeUserHooks,this.config.claudeProjectHooks,this.config.claudeProjectLocalHooks,...bN(this.config),...(this.config.pluginHooks??[]).map((e=>e.config))].some((t=>{const r=t?.hooks[e];return void 0!==r&&r.length>0}))}hasFailClosedHooksForStep(e,t){const r=[this.config.enterpriseHooks,this.config.teamHooks,this.config.projectHooks,...(this.config.repoHooks??[]).map((e=>e.projectHooks)),this.config.userHooks,this.options?.runtimeHooks];for(const n of r){const r=n?.hooks[e];if(r&&(t?mN(r,t):r).some((e=>!0===e.failClosed)))return!0}for(const r of this.config.pluginHooks??[]){const n=r.config.hooks[e];if(n&&(t?mN(n,t):n).some((e=>yF(e)&&!0===e.failClosed)))return!0}return!1}configuredHookDirectory(e){const t=this.config.configDirs;switch(e){case"enterprise":return t?.enterprise;case"team":return t?.team;case"user":return t?.user;case"claude-user":return t?.claudeUser;default:return}}cwdForHookSource(e,t){if(void 0!==e?.cwd&&e.cwd.length>0)return e.cwd;const r=this.configuredHookDirectory(t.source);if(void 0!==r&&r.length>0)return r;const n=e?.cwdForSource?.(t.source);return void 0!==n&&n.length>0?n:t.fallback}getCwdForSource(e){const t=this.config.configDirs;switch(e){case"enterprise":return t?.enterprise??this.workspacePath;case"team":return t?.team??this.workspacePath;case"project":case"claude-project":case"claude-project-local":case"claude-plugin":case"runtime":default:return this.workspacePath;case"user":return t?.user??this.workspacePath;case"claude-user":return t?.claudeUser??this.workspacePath}}buildHookEnvironment(e){const{transcriptPath:t,sessionId:r,conversationId:n,executionEnv:o}=e,s=this.resolveUserEmail({conversation_id:n,session_id:r});return{CURSOR_PROJECT_DIR:this.workspacePath,CURSOR_VERSION:this.globalContext.cursor_version,...s&&{CURSOR_USER_EMAIL:s},...t&&{CURSOR_TRANSCRIPT_PATH:t},CLAUDE_PROJECT_DIR:this.workspacePath,...this.sessionEnv,...void 0!==r?this.sessionEnvById.get(r):void 0,...o}}shouldSkipHookDueToLoopLimit(e,t,r){if("stop"!==e&&"subagentStop"!==e)return!1;const n=ON(r,"loop_count");if("number"!=typeof n)return!1;const o=n,s=t.loop_limit;return null!==s&&(void 0===s?o>=5:o>=s)}async executeHookForStep(e,t,r){this.configReadyPromises.length>0&&await this.whenConfigReady();const n=function(e){return kF.includes(e)}(e),o=t,i=n?null:o.conversation_id?await this.getTranscriptPathIfExists(o.conversation_id):null;let a;if(e===Rd.subagentStop){const e=FN(t,"subagent_id"),r=FN(t,"parent_conversation_id");a=e?await this.getSubagentTranscriptPathIfExists({subagentId:e,parentConversationId:r??void 0}):null}const c=n?void 0:o.session_id??o.conversation_id,l={...t,...void 0!==c&&{session_id:c},hook_event_name:e,cursor_version:this.globalContext.cursor_version,workspace_roots:[...new Set([this.workspacePath,...(this.config.repoHooks??[]).map((e=>e.repoPath))])],user_email:this.resolveUserEmail(o),...!n&&{transcript_path:i},...e===Rd.subagentStop&&{agent_transcript_path:a??null}},u=function(e,t){switch(e){case"beforeShellExecution":case"afterShellExecution":return fN(t,"command");case"beforeMCPExecution":case"afterMCPExecution":{const e=fN(t,"tool_name");return e?`MCP:${e}`:void 0}case"beforeReadFile":return"Read";case"afterFileEdit":return"Write";case"beforeTabFileRead":return"TabRead";case"afterTabFileEdit":return"TabWrite";case"beforeSubmitPrompt":return"UserPromptSubmit";case"stop":return"Stop";case"afterAgentResponse":return"AgentResponse";case"afterAgentThought":return"AgentThought";case"subagentStart":case"subagentStop":return fN(t,"subagent_type");case"preToolUse":case"postToolUse":case"postToolUseFailure":return fN(t,"tool_name");default:return}}(e,l),d=[],h=(e,t,n)=>{if(!e)return;const o=mN(e,u),s=this.cwdForHookSource(r,{source:t,fallback:n??this.getCwdForSource(t)}),i=void 0===n?r?.env:{CURSOR_PROJECT_DIR:n,CLAUDE_PROJECT_DIR:n,...r?.env};for(const e of o)wF(e)?this.promptHookClient&&d.push({type:"prompt",script:e,source:t}):yF(e)&&d.push({type:"command",script:e,cwd:s,env:i,source:t})},p=await async function({repoHooks:e,targetPath:t,workspacePath:r}){if(e.length<2||void 0===t||0===t.length)return e;const n=(0,ts.o1)(t,r),[o,i,a]=await Promise.all([(0,ts.DN)(n),(0,ts.DN)(s.dirname(n)),Promise.all(e.map((async e=>await(0,ts.DN)(e.repoPath)??s.resolve(e.repoPath))))]);if(null===o||null===i)return e;const c=t=>{let r;return e.forEach(((e,n)=>{const o=a[n],i=s.relative(o,t);(""===i||".."!==i&&!i.startsWith(`..${s.sep}`)&&!s.isAbsolute(i))&&(void 0===r||o.length>r.repoPath.length)&&(r={repo:e,repoPath:o})})),r?.repo},l=new Set;for(const t of[o,s.join(i,s.basename(n))]){const r=c(t);if(void 0===r)return e;l.add(r)}return e.filter((e=>l.has(e)))}({repoHooks:this.config.repoHooks??[],targetPath:AN(t),workspacePath:this.workspacePath});h(this.config.enterpriseHooks?.hooks[e],"enterprise"),h(this.config.teamHooks?.hooks[e],"team"),h(this.config.projectHooks?.hooks[e],"project");for(const t of p)h(t.projectHooks?.hooks[e],"project",t.repoPath);h(this.config.userHooks?.hooks[e],"user"),h(this.options?.runtimeHooks?.hooks[e],"runtime"),h(this.config.claudeProjectLocalHooks?.hooks[e],"claude-project-local"),h(this.config.claudeProjectHooks?.hooks[e],"claude-project");for(const t of p)h(t.claudeProjectLocalHooks?.hooks[e],"claude-project-local",t.repoPath),h(t.claudeProjectHooks?.hooks[e],"claude-project",t.repoPath);h(this.config.claudeUserHooks?.hooks[e],"claude-user");for(const t of this.config.pluginHooks??[]){const n=t.config.hooks[e];if(!n?.length)continue;const o=r?.cwd??(e===Rd.stop||e===Rd.subagentStop?this.workspacePath:t.installPath),s={...void 0!==t.plugin&&{plugin:t.plugin},...void 0!==t.marketplace&&{marketplace:t.marketplace},...void 0!==t.pluginId&&{pluginId:t.pluginId},...void 0!==t.marketplaceId&&{marketplaceId:t.marketplaceId}};for(const e of mN(n,u))yF(e)&&d.push({type:"command",script:e,cwd:o,env:r?.env,source:"claude-plugin",attribution:s,pluginInstallPath:t.installPath})}if(0!==d.length)return this.executeAllAndMerge(e,d,l,r?.onCommandFailure)}async whenConfigReady(){await Promise.all(this.configReadyPromises)}async executeAllAndMerge(e,t,r,n){let o;const s=()=>o??=function(e){const t=JSON.stringify(e);return{json:t,payloadSizeBytes:Buffer.byteLength(t,"utf8")}}(r),i=t.map((async(t,o)=>{const{source:i,attribution:a}=t;try{return"prompt"===t.type?await this.executePromptHook(e,t.script,r,i,o,s,a):await this.executeCommandHook(e,t.script,t.cwd,t.env,r,i,o,s,a,t.pluginInstallPath,n)}catch(r){const n=r instanceof Error?r.message:String(r);if(!0===t.script.failClosed){const t=gN(`Hook execution failed: ${n}`),r=RF(e,t);if(r)return{success:!0,data:r,source:i,index:o}}return $N.warn((0,b.q6)(),`${e} hook error`,{source:i,index:o,error:n}),{success:!1,source:i,index:o}}})),a=await Promise.all(i),c=[];for(const e of a)e.success&&void 0!==e.data&&c.push(e.data);return function(e,t){if(0===t.length)return;const[r]=t;if(!(1!==t.length||Ad(n=r)&&Ad(n.updated_input)&&0===Object.keys(n.updated_input).length))return r;var n;const o=SF.includes(e),s=e===Rd.sessionStart,i=e===Rd.workspaceOpen,a=gF.has(e),c={};for(const e of t){const t=e;for(const[e,r]of Object.entries(t))if(void 0!==r)if(i&&"pluginPaths"===e&&Array.isArray(r)){const t=c[e],n=Array.isArray(t)?t:[],o=new Set(n),s=[...n];for(const e of r)"string"!=typeof e||o.has(e)||(o.add(e),s.push(e));c[e]=s}else"permission"===e&&o?c[e]=(u=r,"deny"===(l=c[e])||"deny"===u?"deny":"ask"===l||"ask"===u?"ask":"allow"===l||"allow"===u?"allow":void 0):"user_message"!==e&&"agent_message"!==e?"updated_input"!==e?a&&"additional_context"===e&&"string"==typeof r?c[e]=_F(c[e],r):"continue"!==e||"boolean"!=typeof r?c[e]=s&&"env"===e&&"object"==typeof r&&null!==r?CF(c[e],r):r:void 0===c[e]?c[e]=r:c[e]=c[e]&&r:void 0===c[e]&&Ad(r)&&Object.keys(r).length>0&&(c[e]=r):c[e]=_F(c[e],r)}var l,u;return c}(e,c)}async executeCommandHook(e,t,r,n,o,s,i,a,c,l,u){if(this.shouldSkipHookDueToLoopLimit(e,t,o))return{success:!1,source:s,index:i};const d=Date.now(),h=a(),p=h.payloadSizeBytes,f=(e,r)=>this.finishHookRun(e,t,o,r);let m;try{m=await this.executeCommandScript({script:t,cwd:r,request:o,jsonPayload:h.json,env:n,...void 0!==l&&{pluginInstallPath:l}})}catch(r){const n=r instanceof Error?r.message:String(r),o=n.toLowerCase().includes("timed out");this.reportCommandFailure(u,{command:t.command,source:s,exitCode:null,stderr:"",errorMessage:n});const a=Date.now()-d,l=o?"timeout":"spawn_error";if(!0===t.failClosed){const u=RF(e,gN(`Hook "${t.command}" execution failed: ${n}`));if(u)return f({hookStep:e,hookSource:s,hookType:"command",status:o?"timeout":"blocked",latencyMs:a,payloadSizeBytes:p,errorClass:l,failClosed:!0,timedOut:o,...c},{response:null,stderr:String(r)}),{success:!0,data:u,source:s,index:i}}return f({hookStep:e,hookSource:s,hookType:"command",status:o?"timeout":"failed",latencyMs:a,payloadSizeBytes:p,errorClass:l,failClosed:!0===t.failClosed,timedOut:o,...c},{response:null,stderr:String(r)}),{success:!1,source:s,index:i}}if(2===m.exitCode){const r=function(e,t,r){const n=e.trim(),o=t.trim();return n||(o?`Hook blocked with message: ${o}`:`Hook "${r}" blocked this action (exit code 2) but provided no reason.`)}(m.stdout,m.stderr,t.command),n=RF(e,r);return n?(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,failClosed:!0===t.failClosed,exitCode:m.exitCode,...c},{response:n,stderr:m.stderr}),{success:!0,data:n,source:s,index:i}):(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,failClosed:!0===t.failClosed,exitCode:m.exitCode,...c},{response:null,stderr:m.stderr}),{success:!1,source:s,index:i})}if(0!==m.exitCode&&null!==m.exitCode){if(this.reportCommandFailure(u,{command:t.command,source:s,exitCode:m.exitCode,stderr:m.stderr}),!0===t.failClosed){const r=RF(e,gN(`Hook "${t.command}" failed with exit code ${m.exitCode}${m.stderr?`: ${m.stderr.trim()}`:""}`));if(r)return f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"exit_nonzero",failClosed:!0,exitCode:m.exitCode,...c},{response:null,stderr:m.stderr}),{success:!0,data:r,source:s,index:i}}return f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"exit_nonzero",failClosed:!0===t.failClosed,exitCode:m.exitCode,...c},{response:null,stderr:m.stderr}),{success:!1,source:s,index:i}}const g=m.stdout.trim();if(!g){if(!0===t.failClosed){const r=RF(e,gN(`Hook "${t.command}" returned no output.`));if(r)return f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"empty_stdout",failClosed:!0,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr}),{success:!0,data:r,source:s,index:i}}return f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"empty_stdout",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr}),{success:!1,source:s,index:i}}const w=function(e){const t=e.trim();if(0===t.length)return;const r=IF(t);if(void 0!==r)return r.value;if(t.endsWith("}"))for(let e=t.length-1;e>=0;e--){if("{"!==t[e])continue;const r=IF(t.slice(e));if(void 0!==r)return r.value}}(g);if(void 0===w){const r=xF({step:e,command:t.command,failClosed:!0===t.failClosed,kind:"invalid_json"});return r.blockResponse?(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_json",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr+DN}),{success:!0,data:r.blockResponse,source:s,index:i}):(f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_json",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr+DN}),{success:!1,source:s,index:i})}const y=bF(e,w,{enableClaudeNestedHookSpecificOutputCompatibility:this.options?.enableClaudeNestedHookSpecificOutputCompatibility});if(y.success&&null!=y.data){const r=y.data,n="object"==typeof r&&"permission"in r?r.permission:void 0;return f({hookStep:e,hookSource:s,hookType:"command",status:"deny"===n||"ask"===n?"blocked":"success",latencyMs:m.duration,payloadSizeBytes:p,failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:r,stderr:m.stderr}),{success:!0,data:r,source:s,index:i}}const v=xF({step:e,command:t.command,failClosed:!0===t.failClosed,kind:"invalid_response"});return v.blockResponse?(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_response",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:w,stderr:m.stderr}),{success:!0,data:v.blockResponse,source:s,index:i}):(f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_response",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:w,stderr:m.stderr}),{success:!1,source:s,index:i})}async executePromptHook(e,t,r,n,o,s,i){if(this.shouldSkipHookDueToLoopLimit(e,t,r))return{success:!1,source:n,index:o};if(!this.promptHookClient)return{success:!1,source:n,index:o};const a=1e3*(t.timeout??60),c=Date.now(),l=s(),u=l.payloadSizeBytes,d=(e,n)=>this.finishHookRun(e,t,r,n),h=(0,b.q6)(),[p,f]=h.withTimeoutAndCancel(a);try{const r=JSON.parse(l.json),s=await this.promptHookClient.evaluatePromptHook(p,{prompt:t.prompt,hookInputJson:r,modelName:t.model});if(s.ok){const r=function(e){return EF(e)?PF(0,{permission:"allow"}):e===Rd.beforeSubmitPrompt||e===Rd.sessionStart?PF(0,{continue:!0}):e===Rd.stop?PF(0,{}):void 0}(e);return d({hookStep:e,hookSource:n,hookType:"prompt",status:"success",latencyMs:Date.now()-c,payloadSizeBytes:u,failClosed:!0===t.failClosed,...i},{response:r,stderr:"",exitCode:0}),r?{success:!0,data:r,source:n,index:o}:{success:!1,source:n,index:o}}{const r=RF(e,s.reason??"Prompt hook blocked this action");return d({hookStep:e,hookSource:n,hookType:"prompt",status:"blocked",latencyMs:Date.now()-c,payloadSizeBytes:u,failClosed:!0===t.failClosed,...i},{response:r,stderr:"",exitCode:2}),r?{success:!0,data:r,source:n,index:o}:{success:!1,source:n,index:o}}}catch(r){const s=r instanceof Error?r.message:String(r),a=s.toLowerCase().includes("abort")||s.toLowerCase().includes("timed out"),l=a?"timeout":"prompt_error";if(!0===t.failClosed){const t=RF(e,gN(`Prompt hook failed: ${s}`));if(t)return d({hookStep:e,hookSource:n,hookType:"prompt",status:a?"timeout":"blocked",latencyMs:Date.now()-c,payloadSizeBytes:u,errorClass:l,failClosed:!0,timedOut:a,...i},{response:null,stderr:String(r)}),{success:!0,data:t,source:n,index:o}}return d({hookStep:e,hookSource:n,hookType:"prompt",status:a?"timeout":"failed",latencyMs:Date.now()-c,payloadSizeBytes:u,errorClass:l,failClosed:!0===t.failClosed,timedOut:a,...i},{response:null,stderr:String(r)}),{success:!1,source:n,index:o}}finally{f()}}async executeCommandScript(e){const{script:t,cwd:r,request:n,env:i,pluginInstallPath:a,jsonPayload:c}=e,l=1e3*(t.timeout??60),u=Date.now();let d;const h=new AbortController,p=setTimeout((()=>{h.abort()}),l);try{const e="win32"===process.platform,f=this.getCommandHookPayloadTransportMode(),m=this.shouldUseCommandHookDirectStdinTransport(),g=e?function(e,t){const r=function(e){let t=0;for(;t0&&!/^\s/.test(i))return e;if(/[$`{}()|;,<>]/.test(s)||""===o&&/['"]/.test(s))return e;const a=s.slice(Math.max(s.lastIndexOf("\\"),s.lastIndexOf("/"))+1);if(0===a.length||a.includes("."))return e;const c="'"===o?s.replace(/''/g,"'"):s,l=/^[A-Za-z]:[\\/]/.test(u=c)||u.startsWith("\\")||u.startsWith("/")?c:`${t.cwd.replace(/[\\/]+$/,"")}\\${c}`;var u;const d=iF.find((e=>t.isFile(l+e)));return void 0===d?e:""!==o?`${n}${o}${s}${d}${o}${i}`:`${n}'${s}${d}'${i}`}(t.command,{cwd:r,isFile:MN}):t.command;let w;if(m)w=e?aF(g):g;else if("windows_temp_file"===f){d=await(0,xo.mkdtemp)((0,s.join)((0,o.tmpdir)(),"cursor-hooks-"));const e=(0,s.join)(d,"payload.json");await(0,xo.writeFile)(e,c,{encoding:"utf8",flag:"wx"}),w=function(e,t){return`$OutputEncoding = [System.Text.UTF8Encoding]::new($false); try { $global:cursorHookConsoleInputEncoding = [Console]::InputEncoding; $null = Register-EngineEvent -SourceIdentifier PowerShell.Exiting -Action { try { [Console]::InputEncoding = $global:cursorHookConsoleInputEncoding } catch { } }; [Console]::InputEncoding = $OutputEncoding } catch { }; Get-Content -LiteralPath '${e.replace(/'/g,"''")}' -Raw -Encoding UTF8 | & { $input | ${aF(t)} }`+sF(t)}(e,g)}else w=e?`@'\n${c.replace(/'/g,"''")}\n'@ | & ${g}`+sF(g):`${t.command} <<'CURSOR_HOOK_EOF'\n${c}\nCURSOR_HOOK_EOF`;const y=FN(n,"conversation_id")??void 0,v=FN(n,"session_id")??void 0,S=FN(n,"transcript_path"),k=void 0===y?void 0:this.activeSessionIdsByConversationId.get(y),_=void 0===v||v===y&&!this.sessionEnvById.has(v)?void 0===y?void 0:k?.at(-1)??y:v,C=this.buildHookEnvironment({transcriptPath:S,sessionId:_,conversationId:y,executionEnv:i}),E={};for(const[e,t]of Object.entries(C))void 0!==t&&(E[e]=t);void 0!==a&&(E.CURSOR_PLUGIN_ROOT=a,E.CLAUDE_PLUGIN_ROOT=a);const x=(0,b.q6)(),P=new ca.StringDecoder("utf8"),R=new ca.StringDecoder("utf8");let I,T="",A="",$=null,M=!1;for await(const e of this.shellExecutor.execute(x,w,{workingDirectory:r,signal:h.signal,sandboxPolicy:{perUser:{type:"insecure_none"}},env:E,pipeStdin:m}))switch(e.type){case"stdin_ready":m&&(await this.writeCommandHookStdinPayload(e.stdin,c),M=!0);break;case"stdout":T+=P.write(e.data);break;case"stderr":A+=R.write(e.data);break;case"exit":$=e.code,I=e.aborted}if(T+=P.end(),A+=R.end(),m&&!M)throw new Error("Hook stdin transport was requested, but the executor did not signal stdin readiness");clearTimeout(p);const D=Date.now()-u;if(I??h.signal.aborted)throw new Error(`Hook script timed out after ${l}ms`);return{stdout:T,stderr:A,exitCode:$,duration:D}}catch(e){if(clearTimeout(p),Date.now(),h.signal.aborted)throw new Error(`Hook script timed out after ${l}ms`);throw e}finally{if(d)try{await(0,xo.rm)(d,{recursive:!0,force:!0})}catch{}}}}class LN{constructor(e){this.config=e,this.configuredSteps=SN.getConfiguredSteps(e)}getConfig(){return this.config}hasHookForStep(e){return this.configuredSteps.has(e)}getConfiguredSteps(){return new Set(this.configuredSteps)}}var jN=r("node:perf_hooks");const UN=(0,b.cF)(Symbol.for("@anysphere/agent-exec/toolCallHooks"),{kind:"none"});function BN(e){return"inExecute"!==e.get(UN).kind}function WN(e,t){const r=e.get(UN);return"inExecute"!==r.kind||!r.toolStepsInPreToolUse.includes(t)}(0,b.cF)(Symbol.for("@anysphere/agent-exec/hookAsk"),void 0),(0,b.cF)(Symbol.for("@anysphere/agent-exec/hookAllow"),void 0),new WeakMap,new WeakMap,(0,b.cF)(Symbol.for("@anysphere/agent-exec/toolCallRefusal"),void 0),new WeakMap,new WeakMap,new WeakMap,(0,b.cF)(Symbol.for("@anysphere/agent-exec/approvalWaits"),void 0),new WeakMap;const HN=(0,b.cF)(Symbol.for("@anysphere/agent-exec/hookStepTime"),void 0),qN=new bd.AsyncLocalStorage;function zN(e,t){return qN.run(e,t)}function GN(e,t){void 0!==e&&t.length>0&&e.push(...t)}class VN extends Error{constructor(e){super(`Hook additional_context for ${e.hookEventName} is ${e.actualLength} chars (max ${e.maxLength}).`),this.name="HookAdditionalContextTooLargeError",this.hookEventName=e.hookEventName,this.actualLength=e.actualLength,this.maxLength=e.maxLength}}var KN=r("../proto/dist/generated/agent/v1/hook_additional_context_pb.js");function JN({hookEventName:e,additionalContext:t}){const r=function(e){const t=e?.trim();return void 0!==t&&t.length>0?t:void 0}(t);if(void 0===r)return[];if(r.length>1e4)throw new VN({hookEventName:e,actualLength:r.length,maxLength:1e4});return[new KN.C({hookEventName:e,content:r})]}Object.fromEntries(Array.from(gF).map((e=>{if(!function(e){return e===Rd.sessionStart||e===Rd.beforeSubmitPrompt||e===Rd.preToolUse||e===Rd.postToolUse||e===Rd.postToolUseFailure}(e))throw new Error(`HOOK_STEPS_SUPPORTING_ADDITIONAL_CONTEXT lists ${e} but HookStepAdditionalContextEventName does not include it. Extend the Extract<> union in spec.ts.`);return[e,{hookEventName:e}]})));const ZN="Agent note: Do not suggest workarounds to the blocked tool.";function XN(e){return e.includes(ZN)?e:`${e}\n\n${ZN}`}class QN extends Error{constructor(e){super(`Hook denied: ${e}`),this.failureType="permission_denied",this.name="HookDeniedError",this.reason=e}}class YN extends Error{constructor(e,t){super(`Hook failed (fail-closed): ${e}`),this.failureType="error",this.name="FailClosedError",this.reason=e,this.cause=t}}const eL="To view or modify configured hooks, go to Cursor Settings > Hooks.";function tL(e,t){return XN(`${t?`${e} was blocked by a hook: ${t}`:`${e} was blocked by a hook.`}\n\n${eL}`)}function rL(e){return function(e){return e instanceof QN}(e)||function(e){return e instanceof YN}(e)}const nL=(0,d.h)("generic-hooks");function oL(e,t,r,n){try{return JN({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof VN)return nL.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}const sL=e=>Math.round(1e3*e)/1e3;function iL(e,t,r,n,o,s){const i=n(e),a=o.getToolCallId?.(t)??(0,ko.randomUUID)(),c=o.getExtraHookFields?.(t)??{},l={baseHookRequest:i,toolUseId:a,toolInput:o.createToolInput(t),extraHookFields:c,hookContextCollector:s?.hookContextCollector??o.getHookContextCollector?.(t)??[]},u=function(e,t,r,n){let{toolInput:o,extraHookFields:s,hookContextCollector:i}=n;const{baseHookRequest:a,toolUseId:c}=n;return{fireFailureAsync:async(n,l,u,d=!1)=>{try{const h=await zN(e.signal,(()=>t.executeHookForStep(Rd.postToolUseFailure,{...a,tool_name:r,tool_input:o,error_message:l,failure_type:u,duration:n,tool_use_id:c,is_interrupt:d,...s})));GN(i,oL(e,r,Rd.postToolUseFailure,h?.additional_context))}catch(t){nL.warn(e,"postToolUseFailure hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}},fireSuccessAsync:async(n,l)=>{try{const u=await zN(e.signal,(()=>t.executeHookForStep(Rd.postToolUse,{...a,tool_name:r,tool_input:o,tool_output:l,duration:n,tool_use_id:c,...s})));GN(i,oL(e,r,Rd.postToolUse,u?.additional_context))}catch(t){nL.warn(e,"postToolUse hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}},getToolInput:()=>o,setToolInput:e=>{o=e},setExtraHookFields:e=>{s=e,n.extraHookFields=e}}}(e,r,o.toolName,l);return{hookContext:l,helpers:u}}async function aL(e,t,r,n,o,s,i,a){const{baseHookRequest:c,toolUseId:l,extraHookFields:u}=n;try{const a=await zN(e.signal,(()=>r.executeHookForStep(Rd.preToolUse,{...c,tool_name:s.toolName,tool_input:o.getToolInput(),tool_use_id:l,...u})));if("deny"===a?.permission){const r=a.user_message||`${s.toolName} blocked by preToolUse hook`,c=XN(r);try{GN(n.hookContextCollector,JN({hookEventName:Rd.preToolUse,additionalContext:a.additional_context}))}catch(t){if(!(t instanceof VN))throw t;nL.warn(e,"preToolUse deny additional_context exceeded max size; dropping carrier",{toolName:s.toolName,actualLength:t.actualLength,maxLength:t.maxLength})}return await o.fireFailureAsync(0,r,"permission_denied"),{type:"rejected",result:i(t,c),reason:c}}a?.updated_input&&s.applyUpdatedInput&&(s.applyUpdatedInput(t,a.updated_input),o.setToolInput(s.createToolInput(t)),s.getExtraHookFields&&o.setExtraHookFields(s.getExtraHookFields(t))),GN(n.hookContextCollector,JN({hookEventName:Rd.preToolUse,additionalContext:a?.additional_context}))}catch(n){const a=r.hasFailClosedHooksForStep?.(Rd.preToolUse,s.toolName)??!1,c=n instanceof VN;if(a){const e=gN(`${c?"preToolUse additional_context exceeded max size":"preToolUse hook failed"}: ${n instanceof Error?n.message:"preToolUse hook error"}`);return await o.fireFailureAsync(0,e,"error"),{type:"rejected",result:i(t,e),reason:e}}nL.warn(e,c?"preToolUse additional_context exceeded max size; dropping carrier":"preToolUse hook error",{toolName:s.toolName,error:n instanceof Error?n.message:String(n),...c?{actualLength:n.actualLength,maxLength:n.maxLength}:{}})}if(a)try{const s=await a({ctx:e,args:t,baseHookRequest:c,hookExecutor:r,toolInput:o.getToolInput(),toolUseId:l,extraHookFields:n.extraHookFields});if(void 0!==s){const e="Pre-execution hook returned rejection";return await o.fireFailureAsync(0,e,"permission_denied"),{type:"rejected",result:s,reason:e}}}catch(e){if(rL(e))return await o.fireFailureAsync(0,e.reason,e.failureType),{type:"rejected",result:i(t,e.reason),reason:e.reason};throw e}return{type:"continue"}}function cL(e){return e.toolCallId}function lL(e,t,r,n){return{async execute(o,s,i){const a=dL(o,t),{hookContext:c,helpers:l}=iL(o,s,a,r,n,i);let u;try{u=await aL(o,s,a,c,l,n,n.createRejectedResult,n.runPreExecutionHooks)}catch(e){throw n.runCleanup?.(c.toolUseId),e}if("rejected"===u.type)return n.runCleanup?.(c.toolUseId),u.result;const d=jN.performance.now();try{const t=await e.execute(o,s,i),r=sL(jN.performance.now()-d);if(n.runPostExecutionHooks)try{const e=await n.runPostExecutionHooks({ctx:o,args:s,result:t,baseHookRequest:c.baseHookRequest,hookExecutor:a,toolInput:l.getToolInput(),toolUseId:c.toolUseId,executionDurationMs:r,extraHookFields:c.extraHookFields});if(void 0!==e)return await l.fireSuccessAsync(r,JSON.stringify(n.createSuccessOutput(s,e))),n.runCleanup?.(c.toolUseId),e}catch(e){if(rL(e))return await l.fireFailureAsync(r,e.reason,e.failureType),n.runCleanup?.(c.toolUseId),n.createRejectedResult(s,e.reason);nL.warn(o,"postExecutionHooks error",{toolName:n.toolName,error:e instanceof Error?e.message:String(e)})}return n.isSuccess(t)?await l.fireSuccessAsync(r,JSON.stringify(n.createSuccessOutput(s,t))):await l.fireFailureAsync(r,n.getErrorMessage(t),n.getFailureType?.(t)??"error",n.isInterrupt?.(t)??!1),n.runCleanup?.(c.toolUseId),t}catch(e){const t=sL(jN.performance.now()-d);throw await l.fireFailureAsync(t,e instanceof Error?e.message:String(e),"error"),n.runCleanup?.(c.toolUseId),e}}}}function*uL(e,t){const r=t.hookContextCollector;e.createHookContextEvent&&void 0!==r&&0!==r.length&&(yield e.createHookContextEvent(r))}function dL(e,t){const r=BN(e),n=e.get(HN);if(r&&void 0===n)return t;const o=e=>n?.during(e)??e;return{executeHookForStep:async(e,n)=>{if(r||!function(e){return e===Rd.preToolUse||e===Rd.postToolUse||e===Rd.postToolUseFailure}(e))return o(t.executeHookForStep(e,n));await o(t.whenConfigReady())},hasFailClosedHooksForStep:(e,r)=>t.hasFailClosedHooksForStep?.(e,r)??!1,hasHooksForStep:e=>t.hasHooksForStep?.(e)??!0,whenConfigReady:()=>o(t.whenConfigReady())}}function hL(e){if("object"!=typeof e||null===e||!("code"in e))return!1;const t=e.code;return"ENOENT"===t||"ENOTDIR"===t}class pL{async readFile(e){try{return await xo.readFile(e,"utf-8")}catch(e){if("ENOENT"===e?.code)return;throw e}}async exists(e){try{return await xo.access(e),!0}catch{return!1}}async pathContainsSymlink(e,t){return async function(e,t){const r=function(e,t){const r=s.resolve(e),n=s.resolve(t),o=s.relative(n,r);if(0===o.length||".."===o||o.startsWith(`..${s.sep}`)||s.isAbsolute(o))return"unsafe";const i=o.split(s.sep).filter((e=>e.length>0)),a=[];let c=n;for(const e of i)c=s.join(c,e),a.push(c);return a}(e,t);if("unsafe"===r)return!0;for(const e of r)try{if((await(0,xo.lstat)(e)).isSymbolicLink())return!0}catch(e){if(hL(e))return!0;throw e}return!1}(e,t)}}var fL=r("../proto/dist/generated/agent/v1/hooks_pb.js");const mL=G("hook-executor",(e=>new H(e,Q("executeHookArgs"),Y("executeHookResult"))),((e,t)=>{t.register(new A(e,te("executeHookArgs"),ee("executeHookResult")))})),gL=new Set(Object.values(Rd));function wL(e){switch(e){case"completed":case"aborted":case"error":return e;default:return"error"}}function yL(e){switch(e){case"error":case"timeout":case"permission_denied":return e;default:return"error"}}function vL(e){const t=e?.toJson();return"object"!=typeof t||null===t||Array.isArray(t)?{}:t}class bL{constructor(e){this.hookExecutor=e}hasFailClosedHooksForStep(e,t){return!!function(e){return gL.has(e)}(e)&&(this.hookExecutor.hasFailClosedHooksForStep?.(e,t)??!1)}async execute(e,t){const r=t.request;if(!r)return new p.S1({response:void 0});switch(r.request.case){case"preCompact":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...mF(e),trigger:"manual"===e.trigger?"manual":"auto",context_usage_percent:e.contextUsagePercent,context_tokens:Number(e.contextTokens),context_window_size:Number(e.contextWindowSize),message_count:e.messageCount,messages_to_compact:e.messagesToCompact,is_first_compaction:e.isFirstCompaction},n=await this.hookExecutor.executeHookForStep(Rd.preCompact,t);return new p.S1({response:new p.w5({response:{case:"preCompact",value:new fL.$_({userMessage:n?.user_message})}})})}case"subagentStart":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...mF(e),subagent_id:e.subagentId,subagent_type:e.subagentType,task:e.task,parent_conversation_id:e.parentConversationId,tool_call_id:e.toolCallId,subagent_model:e.subagentModel,is_parallel_worker:e.isParallelWorker,git_branch:e.gitBranch},n=await this.hookExecutor.executeHookForStep(Rd.subagentStart,t);return new p.S1({response:new p.w5({response:{case:"subagentStart",value:new fL.W0({permission:n?.permission,userMessage:n?.user_message,additionalContext:n?.additional_context})}})})}case"subagentStop":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...mF(e),subagent_id:e.subagentId,subagent_type:e.subagentType,status:wL(e.status),duration_ms:Number(e.durationMs),summary:e.summary,parent_conversation_id:e.parentConversationId,message_count:e.messageCount,tool_call_count:e.toolCallCount,error_message:e.errorMessage,modified_files:e.modifiedFiles,git_branch:e.gitBranch,loop_count:e.loopCount??0,task:e.task,description:e.description,...e.childConversationId?{child_conversation_id:e.childConversationId}:{}},n=await this.hookExecutor.executeHookForStep(Rd.subagentStop,t);return new p.S1({response:new p.w5({response:{case:"subagentStop",value:new fL.AH({followupMessage:n?.followup_message,additionalContext:n?.additional_context})}})})}case"beforeSubmitPrompt":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(Rd.beforeSubmitPrompt,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...mF(e),prompt:e.prompt,attachments:(n=e.attachments,n.flatMap((e=>"file"===e.type||"rule"===e.type?[{type:e.type,file_path:e.filePath}]:[]))),composer_mode:e.composerMode});return new p.S1({response:new p.w5({response:{case:"beforeSubmitPrompt",value:new fL.u1({continue:t?.continue,userMessage:t?.user_message,additionalContext:t?.additional_context})}})})}case"afterAgentResponse":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(Rd.afterAgentResponse,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...mF(e),text:e.text,input_tokens:void 0!==e.inputTokens?Number(e.inputTokens):void 0,output_tokens:void 0!==e.outputTokens?Number(e.outputTokens):void 0,cache_read_tokens:void 0!==e.cacheReadTokens?Number(e.cacheReadTokens):void 0,cache_write_tokens:void 0!==e.cacheWriteTokens?Number(e.cacheWriteTokens):void 0}),new p.S1({response:new p.w5({response:{case:"afterAgentResponse",value:new fL.FW}})})}case"afterAgentThought":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(Rd.afterAgentThought,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...mF(e),text:e.text,duration_ms:void 0!==e.durationMs?Number(e.durationMs):void 0}),new p.S1({response:new p.w5({response:{case:"afterAgentThought",value:new fL.H}})})}case"stop":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(Rd.stop,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...mF(e),status:wL(e.status),loop_count:e.loopCount,input_tokens:void 0!==e.inputTokens?Number(e.inputTokens):void 0,output_tokens:void 0!==e.outputTokens?Number(e.outputTokens):void 0,cache_read_tokens:void 0!==e.cacheReadTokens?Number(e.cacheReadTokens):void 0,cache_write_tokens:void 0!==e.cacheWriteTokens?Number(e.cacheWriteTokens):void 0});return new p.S1({response:new p.w5({response:{case:"stop",value:new fL.rT({followupMessage:t?.followup_message})}})})}case"preToolUse":{if(!BN(e))return this.skipToolUseStep();const t=r.request.value,n=vL(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...mF(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,tool_use_id:t.toolUseId,cwd:t.cwd},s=await this.hookExecutor.executeHookForStep(Rd.preToolUse,o);return new p.S1({response:new p.w5({response:{case:"preToolUse",value:new fL.Wn({permission:s?.permission,userMessage:s?.user_message,agentMessage:s?.agent_message,updatedInput:s?.updated_input?JSON.stringify(s.updated_input):void 0,additionalContext:s?.additional_context})}})})}case"postToolUse":{if(!BN(e))return this.skipToolUseStep();const t=r.request.value,n=vL(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...mF(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,tool_output:t.toolOutput,duration:Number(t.durationMs),tool_use_id:t.toolUseId,cwd:t.cwd},s=await this.hookExecutor.executeHookForStep(Rd.postToolUse,o);return new p.S1({response:new p.w5({response:{case:"postToolUse",value:new fL.uB({additionalContext:s?.additional_context,updatedMcpToolOutput:void 0===s?.updated_mcp_tool_output?void 0:JSON.stringify(s.updated_mcp_tool_output)})}})})}case"postToolUseFailure":{if(!BN(e))return this.skipToolUseStep();const t=r.request.value,n=vL(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...mF(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,error_message:t.errorMessage,failure_type:yL(t.failureType),duration:Number(t.durationMs),tool_use_id:t.toolUseId,is_interrupt:t.isInterrupt},s=await this.hookExecutor.executeHookForStep(Rd.postToolUseFailure,o);return new p.S1({response:new p.w5({response:{case:"postToolUseFailure",value:new fL.U1({additionalContext:s?.additional_context})}})})}default:return new p.S1({response:void 0})}var n}async skipToolUseStep(){return await this.hookExecutor.whenConfigReady(),new p.S1({response:void 0})}}class SL{constructor(e,t,r,n){this.innerExecutor=e,this.hooksAdditionalContextPromise=t,this.teamHooksReadyPromise=r,this.hooksConfigLease=n}async execute(e,t,r){this.teamHooksReadyPromise&&await this.teamHooksReadyPromise;const n=await this.innerExecutor.execute(e,t,r),o=await this.hooksAdditionalContextPromise,s=this.hooksConfigLease?new Fr.Jy({configuredSteps:Array.from(this.hooksConfigLease.getConfiguredSteps())}):void 0;if("success"===n.result.case&&(o||s)){const e=n.result.value.requestContext,t=e?.clone()??new Fr.bb;return o&&(t.hooksAdditionalContext=o),s&&(t.hooksConfig=s),new Fr._G({result:{case:"success",value:new Fr.yW({requestContext:t,servedFromDiskCache:n.result.value.servedFromDiskCache})}})}return n}}function kL(e){return!!e&&e.type!==is.vc.INSECURE_NONE&&e.type!==is.vc.UNSPECIFIED}async function _L({hookExecutor:e,baseHookRequest:t,toolUseId:r,command:n,cwd:o,sandbox:s}){const i=await e.executeHookForStep(Rd.beforeShellExecution,{...t,command:n,cwd:o,sandbox:s,tool_use_id:r});if("deny"===i?.permission){const e=tL("Command execution",i.user_message);throw new QN(e)}if("ask"===i?.permission)return a=i.user_message,new fe.In({kind:fe.b.FORCE_PROMPT,reason:a});var a}const CL={toolName:PN,getToolCallId:cL,createToolInput:e=>{const t=e.workingDirectory||"";return{command:e.command,cwd:t}},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd)},createRejectedResult:(e,t)=>new Fo.Lt({result:{case:"rejected",value:new fe.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"BackgroundShell error";case"rejected":return e.result.value.reason||"BackgroundShell rejected";case"permissionDenied":return"Permission denied";case"sandboxUnsupported":return`Sandbox policy unsupported on this host: ${e.result.value.reason}`;default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{shell_id:t.result.value.shellId,pid:t.result.value.pid}:{success:!0},getExtraHookFields:e=>({cwd:e.workingDirectory||""}),runPreExecutionHooks:async e=>{const{ctx:t,args:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e,i=r.workingDirectory||"",a=kL(r.sandboxPolicy);WN(t,Rd.beforeShellExecution)&&$o(r,await _L({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:a}))}};class EL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,CL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const xL={toolName:"WriteShellStdin",createToolInput:e=>({shell_id:e.shellId,chars_length:e.chars.length}),createRejectedResult:(e,t)=>new Fo.nt({result:{case:"error",value:new Fo.Gv({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"WriteShellStdin error":"Unknown error",createSuccessOutput:e=>({shell_id:e.shellId,success:!0})};class PL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,xL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const RL={toolName:"ComputerUse",getToolCallId:cL,createToolInput:e=>({actions_count:e.actions.length}),createRejectedResult:(e,t)=>new Ng.ks({result:{case:"error",value:new Ng.Jb({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"ComputerUse error":"Unknown error",createSuccessOutput:(e,t)=>"success"===t.result.case?{action_count:t.result.value.actionCount,duration_ms:t.result.value.durationMs}:{success:!0}};class IL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,RL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const TL={toolName:CN,getToolCallId:cL,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Ww.Pi({result:{case:"rejected",value:new Ww.iq({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"fileNotFound":return`File not found: ${e.result.value.path}`;case"notFile":return`Not a file: ${e.result.value.path}`;case"permissionDenied":return`Permission denied: ${e.result.value.path}`;case"fileBusy":return`File busy: ${e.result.value.path}`;case"rejected":return e.result.value.reason||"Delete rejected";case"error":return e.result.value.error||"Delete error";default:return"Unknown error"}},createSuccessOutput:e=>({file_path:e.path,deleted:!0})};class AL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,TL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const $L={toolName:RN,getToolCallId:cL,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new NA.Ek({result:{case:"rejected",value:new NA.J6({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"Diagnostics error";case"rejected":return e.result.value.reason||"Diagnostics rejected";case"fileNotFound":return`File not found: ${e.result.value.path}`;case"permissionDenied":return`Permission denied: ${e.result.value.path}`;default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{file_path:e.path,diagnostics_count:t.result.value.totalDiagnostics}:{file_path:e.path,success:!0}};class ML{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,$L)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const DL={toolName:"Fetch",getToolCallId:cL,createToolInput:e=>({url:e.url}),applyUpdatedInput:(e,t)=>{"string"==typeof t.url&&(e.url=t.url)},createRejectedResult:(e,t)=>new Jw.uN({result:{case:"error",value:new Jw.fk({url:e.url,error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Fetch error":"Unknown error",createSuccessOutput:(e,t)=>"success"===t.result.case?{url:e.url,status_code:t.result.value.statusCode,content_length:t.result.value.content.length}:{url:e.url,success:!0}};class OL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,DL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const FL={toolName:xN,getToolCallId:cL,createToolInput:e=>({pattern:e.pattern,file_path:e.path,glob:e.glob,output_mode:e.outputMode}),applyUpdatedInput:(e,t)=>{"string"==typeof t.pattern&&(e.pattern=t.pattern),"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Ry.Ud({result:{case:"error",value:new Ry.ts({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Grep error":"Unknown error",createSuccessOutput:e=>({pattern:e.pattern,success:!0})};class NL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,FL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const LL={toolName:EN,getToolCallId:cL,createToolInput:e=>({file_path:e.path,ignore:e.ignore}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new yC.fv({result:{case:"rejected",value:new yC.k2({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"Ls error";case"rejected":return e.result.value.reason||"Ls rejected";case"timeout":return"Ls operation timed out";default:return"Unknown error"}},getFailureType:e=>"timeout"===e.result.case?"timeout":"error",createSuccessOutput:e=>({file_path:e.path,success:!0})};class jL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,LL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const UL=(0,d.h)("hooks-exec:mcp");function BL(e){return!!(null===e||"string"==typeof e||"boolean"==typeof e||"number"==typeof e&&Number.isFinite(e))||(Array.isArray(e)?e.every(BL):"object"==typeof e&&Object.values(e).every((e=>void 0!==e&&BL(e))))}function WL(e,t,r,n){try{return JN({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof VN)return UL.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}class HL{constructor(e,t,r,n,o){this.innerExecutor=e,this.hookExecutor=t,this.baseHookRequestExtractor=r,this.mcpLease=n,this.hooksConfigLease=o}async execute(e,t,r){if(t.smartModeApprovalOnly)return this.innerExecutor.execute(e,t,r);if(t.symbolicPathArguments.length>0&&(!0===this.hooksConfigLease?.hasHookForStep(Rd.preToolUse)||!0===this.hooksConfigLease?.hasHookForStep(Rd.beforeMCPExecution)))return new Mc.iz({result:{case:"error",value:new Mc.Nh({error:`"${iA}" arguments can't be used on this computer: hooks that inspect MCP calls are configured here, and they would not see the file's contents. Read the file and pass its contents instead.`})}});const n=dL(e,this.hookExecutor),o=this.baseHookRequestExtractor(e),s=(0,ko.randomUUID)(),i=r?.hookContextCollector??[];let a=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t?.toJson()])));const c=`MCP:${t.toolName}`;try{const r=await n.executeHookForStep(Rd.preToolUse,{...o,tool_name:c,tool_input:a,tool_use_id:s});if("deny"===r?.permission){const t=r.user_message||"MCP tool blocked by preToolUse hook";try{GN(i,JN({hookEventName:Rd.preToolUse,additionalContext:r.additional_context}))}catch(t){if(!(t instanceof VN))throw t;UL.warn(e,"preToolUse deny additional_context exceeded max size; dropping carrier",{toolName:c,actualLength:t.actualLength,maxLength:t.maxLength})}return await this.firePostToolUseFailureAsync(e,n,o,c,a,t,"permission_denied",0,s,!1,i),new Mc.iz({result:{case:"permissionDenied",value:new Mc.HQ({error:tL("MCP tool execution",t),isReadonly:!1})}})}if(r?.updated_input)try{for(const[e,n]of Object.entries(r.updated_input))if(void 0!==n){if(!BL(n))throw new TypeError("updated_input value is not JSON");t.args[e]=ve.Value.fromJson(n)}a=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t?.toJson()])))}catch(t){UL.warn(e,"Failed to merge updated_input for MCP",{error:t instanceof Error?t.message:String(t)})}GN(i,JN({hookEventName:Rd.preToolUse,additionalContext:r?.additional_context}))}catch(t){const r=n.hasFailClosedHooksForStep?.(Rd.preToolUse,c)??!1,l=t instanceof VN;if(r){const r=gN(`${l?"preToolUse additional_context exceeded max size":"preToolUse hook failed"}: ${t instanceof Error?t.message:"preToolUse hook error"}`);return await this.firePostToolUseFailureAsync(e,n,o,c,a,r,"error",0,s,!1,i),new Mc.iz({result:{case:"permissionDenied",value:new Mc.HQ({error:tL("MCP tool execution",r),isReadonly:!1})}})}UL.warn(e,l?"preToolUse additional_context exceeded max size; dropping carrier":"preToolUse hook error in MCP executor",{toolName:c,error:t instanceof Error?t.message:String(t),...l?{actualLength:t.actualLength,maxLength:t.maxLength}:{}})}const l=await(this.mcpLease?.getClient(e,t.providerIdentifier)),u=l?.config;let d;const h=u&&"url"in u&&u.url?u.url:void 0;d=void 0!==h?{url:h}:u&&"command"in u?{command:[u.command,...u.args??[]].filter(Boolean).join(" ")}:{command:t.providerIdentifier};const p={mcp_server_name:t.providerIdentifier,...void 0!==h?{mcp_server_url:h}:{}},f={...o,tool_name:t.toolName,tool_input:JSON.stringify(a),tool_use_id:s,...p,...d},m=WN(e,Rd.beforeMCPExecution)?await n.executeHookForStep(Rd.beforeMCPExecution,f):void 0;if("deny"===m?.permission){const t=tL("MCP tool execution",m.user_message);return await this.firePostToolUseFailureAsync(e,n,o,c,a,t,"permission_denied",0,s,!1,i),new Mc.iz({result:{case:"permissionDenied",value:new Mc.HQ({error:t,isReadonly:!1})}})}const g=jN.performance.now();try{const l=await this.innerExecutor.execute(e,t,r),u=sL(jN.performance.now()-g);let d="{}";if("success"===l.result.case)try{const e=l.result.value.content.map((e=>"text"===e.content.case?{type:"text",text:e.content.value.text}:"image"===e.content.case?{type:"image",data:Buffer.from(e.content.value.data).toString("base64"),mimeType:e.content.value.mimeType}:{type:"unknown"}));d=JSON.stringify({content:e,isError:l.result.value.isError})}catch(t){UL.warn(e,"Failed to serialize MCP result",{error:t instanceof Error?t.message:String(t)}),d=JSON.stringify({error:"Failed to serialize result"})}else"error"===l.result.case?d=JSON.stringify({error:l.result.value.error}):"rejected"===l.result.case?d=JSON.stringify({rejected:!0,reason:l.result.value.reason}):"permissionDenied"===l.result.case&&(d=JSON.stringify({permissionDenied:!0,error:l.result.value.error}));const h={...o,tool_name:t.toolName,tool_input:JSON.stringify(a),result_json:d,duration:u,tool_use_id:s,...p};await n.executeHookForStep(Rd.afterMCPExecution,h);const f=await this.firePostToolUse(e,n,o,c,a,d,u,s,i);if(void 0!==f?.updated_mcp_tool_output)try{const e=f.updated_mcp_tool_output,t=[];if("string"==typeof e)t.push(new Mc._Z({content:{case:"text",value:new Mc.zN({text:e})}}));else if("object"==typeof e&&null!==e&&"content"in e&&Array.isArray(e.content)){const r=e.content;for(const e of r)"object"==typeof e&&null!==e&&"type"in e&&"text"===e.type&&"text"in e?t.push(new Mc._Z({content:{case:"text",value:new Mc.zN({text:String(e.text)})}})):t.push(new Mc._Z({content:{case:"text",value:new Mc.zN({text:JSON.stringify(e)})}}))}else t.push(new Mc._Z({content:{case:"text",value:new Mc.zN({text:JSON.stringify(e)})}}));const r="object"==typeof e&&null!==e&&"isError"in e&&Boolean(e.isError);return new Mc.iz({result:{case:"success",value:new Mc.QW({content:t,isError:r})}})}catch(t){return UL.warn(e,"Failed to process updated_mcp_tool_output",{error:t instanceof Error?t.message:String(t)}),l}return l}catch(t){const r=sL(jN.performance.now()-g),l=t instanceof Error?t.message:String(t);throw await this.firePostToolUseFailureAsync(e,n,o,c,a,l,"error",r,s,!1,i),t}}async firePostToolUse(e,t,r,n,o,s,i,a,c){try{const l=await t.executeHookForStep(Rd.postToolUse,{...r,tool_name:n,tool_input:o,tool_output:s,duration:i,tool_use_id:a});return GN(c,WL(e,n,Rd.postToolUse,l?.additional_context)),l}catch(t){return void UL.warn(e,"postToolUse hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}async firePostToolUseFailureAsync(e,t,r,n,o,s,i,a,c,l,u){try{const d=await t.executeHookForStep(Rd.postToolUseFailure,{...r,tool_name:n,tool_input:o,error_message:s,failure_type:i,duration:a,tool_use_id:c,is_interrupt:l});GN(u,WL(e,n,Rd.postToolUseFailure,d?.additional_context))}catch(t){UL.warn(e,"postToolUseFailure hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}}const qL={toolName:"ListMcpResources",createToolInput:e=>({server:e.server}),applyUpdatedInput:(e,t)=>{"string"==typeof t.server&&(e.server=t.server)},createRejectedResult:(e,t)=>new Mc.kP({result:{case:"error",value:new Mc.w2({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"ListMcpResources error";case"rejected":return e.result.value.reason||"ListMcpResources rejected";default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{resources_count:t.result.value.resources.length}:{success:!0}};class zL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,qL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const GL={toolName:"FetchMcpResource",createToolInput:e=>({server:e.server,uri:e.uri,download_path:e.downloadPath}),applyUpdatedInput:(e,t)=>{"string"==typeof t.server&&(e.server=t.server),"string"==typeof t.uri&&(e.uri=t.uri),"string"==typeof t.download_path&&(e.downloadPath=t.download_path)},createRejectedResult:(e,t)=>new Mc.ZD({result:{case:"error",value:new Mc.Jx({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"ReadMcpResource error";case"rejected":return e.result.value.reason||"ReadMcpResource rejected";case"notFound":return"Resource not found";default:return"Unknown error"}},createSuccessOutput:(e,t)=>{if("success"===t.result.case){const r=t.result.value;return{uri:e.uri,name:r.name,mime_type:r.mimeType,download_path:r.downloadPath,content_type:r.content.case,content_length:"text"===r.content.case||"blob"===r.content.case?r.content.value.length:void 0}}return{uri:e.uri,success:!0}}};class VL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,GL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const KL={toolName:kN,getToolCallId:cL,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Xy.sV({result:{case:"rejected",value:new Xy.f4({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"Read error";case"rejected":return e.result.value.reason||"Read rejected";case"fileNotFound":return`File not found: ${e.result.value.path}`;case"permissionDenied":return`Permission denied: ${e.result.value.path}`;case"invalidFile":return`Invalid file: ${e.result.value.path}`;default:return"Unknown error"}},createSuccessOutput:(e,t)=>{if("success"===t.result.case){const r="content"===t.result.value.output.case?t.result.value.output.value:"";return{file_path:e.path,content_length:r.length}}return{file_path:e.path,success:!0}},runPostExecutionHooks:async e=>{const{args:t,result:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e;if("success"!==r.result.case||!1===o.hasHooksForStep?.(Rd.beforeReadFile))return;const i="content"===r.result.value.output.case?r.result.value.output.value:"",a=await async function(e,t){try{return await e()}catch(e){const r=function(e,t){return`${e??"Action"} was blocked because a configured hook failed to execute${t?`: ${t}`:"."}\n\nThis is a safety measure (fail-closed) - when hooks cannot be evaluated, the action is blocked to prevent potentially unsafe operations.\n\n${eL}`}(t,e instanceof Error?e.message:String(e));throw new YN(r,e)}}((()=>o.executeHookForStep(Rd.beforeReadFile,{...n,content:i,file_path:t.path,attachments:[],tool_use_id:s})),"File read");if("deny"===a?.permission){const e=tL("File read",a.user_message);throw new QN(e)}}};class JL{constructor(e,t,r){this.wrappedExecutor=new eA(lL(e,t,r,KL))}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const ZL={toolName:"RecordScreen",getToolCallId:cL,createToolInput:e=>({mode:e.mode,save_as_filename:e.saveAsFilename}),createRejectedResult:(e,t)=>new T$.Tj({result:{case:"failure",value:new T$.yH({error:t,kind:T$.Wg.HOOK_REJECTED})}}),isSuccess:e=>"failure"!==e.result.case,getErrorMessage:e=>"failure"===e.result.case?e.result.value.error||"RecordScreen failed":"Unknown error",createSuccessOutput:(e,t)=>({result_type:t.result.case})};class XL{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,ZL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}function QL(e){return"success"===e.result.case||"failure"===e.result.case?e.result.value.stdout+e.result.value.stderr:""}const YL={toolName:PN,createToolInput:e=>{const t=e.workingDirectory||"",r=e.timeout;return{command:e.command,cwd:t,..."number"==typeof r&&r>0&&{timeout:r}}},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd),"number"==typeof t.timeout&&t.timeout>=0&&(e.timeout=t.timeout)},createRejectedResult:(e,t)=>new fe.W4({result:{case:"rejected",value:new fe.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),isSuccess:e=>"success"===e.result.case||"failure"===e.result.case&&!e.result.value.aborted,getErrorMessage:e=>{switch(e.result.case){case"timeout":return`Command timed out after ${e.result.value.timeoutMs}ms`;case"spawnError":return e.result.value.error||"Failed to spawn command";case"failure":return e.result.value.aborted?"Command was aborted":"Command failed";case"rejected":return e.result.value.reason||"Command rejected";default:return"Unknown error"}},getFailureType:e=>"timeout"===e.result.case?"timeout":"error",isInterrupt:e=>"failure"===e.result.case&&e.result.value.aborted,createSuccessOutput:(e,t)=>({output:QL(t),exitCode:"success"===t.result.case?0:1}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),runPreExecutionHooks:async e=>{const{ctx:t,args:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e,i=r.workingDirectory||"";WN(t,Rd.beforeShellExecution)&&$o(r,await _L({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:kL(r.requestedSandboxPolicy)}))},runPostExecutionHooks:async e=>{const{args:t,result:r,baseHookRequest:n,hookExecutor:o,executionDurationMs:s,toolUseId:i}=e,a=QL(r);await o.executeHookForStep(Rd.afterShellExecution,{...n,command:t.command,output:a,duration:s,sandbox:kL(t.requestedSandboxPolicy),tool_use_id:i})}};class ej{constructor(e,t,r){this.wrappedExecutor=lL(e,t,r,YL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class tj{constructor(){this.output=""}onEvent(e){"stdout"===e.event.case||"stderr"===e.event.case?this.output+=e.event.value.data:"exit"===e.event.case&&(this.exitEvent=e.event.value)}getOutput(){return this.output}isAborted(){return this.exitEvent?.aborted??!1}getExitCode(){return this.exitEvent?.code??0}}const rj={toolName:PN,createToolInput:e=>{const t=e.workingDirectory||"",r=e.timeout;return{command:e.command,cwd:t,..."number"==typeof r&&r>0&&{timeout:r}}},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd),"number"==typeof t.timeout&&t.timeout>=0&&(e.timeout=t.timeout)},createRejectedEvent:(e,t)=>new fe.FI({event:{case:"rejected",value:new fe.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),createHookContextEvent:e=>new fe.FI({event:{case:"hookContext",value:new fe.Ng({hookAdditionalContexts:[...e]})}}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),createResultCollector:()=>new tj,createSuccessOutput:(e,t)=>({output:t.getOutput(),exitCode:t.getExitCode()}),isStreamSuccess:e=>0===e.getExitCode(),getStreamErrorMessage:(e,t)=>t.getOutput().trim()||`Command failed with exit code ${t.getExitCode()}`,runPreExecutionHooks:async e=>{const{ctx:t,args:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e,i=r.workingDirectory||"",a=kL(r.requestedSandboxPolicy);WN(t,Rd.beforeShellExecution)&&$o(r,await _L({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:a}))},runPostExecutionHooks:async e=>{const{args:t,baseHookRequest:r,hookExecutor:n,collector:o,executionDurationMs:s,toolUseId:i}=e,a=kL(t.requestedSandboxPolicy);await n.executeHookForStep(Rd.afterShellExecution,{...r,command:t.command,output:o.getOutput(),duration:s,sandbox:a,tool_use_id:i})}};class nj{constructor(e,t,r){this.wrappedExecutor=function(e,t,r,n){return{async*execute(o,s,i){const a=dL(o,t),{hookContext:c,helpers:l}=iL(o,s,a,r,n,i),u=n.runPreExecutionHooks?async e=>{await n.runPreExecutionHooks(e)}:void 0,d=await aL(o,s,a,c,l,n,((e,t)=>n.createRejectedEvent(e,t)),u);if("rejected"===d.type){yield d.result;for(const e of uL(n,c))yield e;return}const h=jN.performance.now(),p=n.createResultCollector();try{for await(const t of e.execute(o,s,i))p.onEvent(t),yield t}catch(e){const t=sL(jN.performance.now()-h),r=e instanceof Error?e.message:String(e);await l.fireFailureAsync(t,r,"error");for(const e of uL(n,c))yield e;throw e}const f=sL(jN.performance.now()-h);if(n.runPostExecutionHooks)try{await n.runPostExecutionHooks({ctx:o,args:s,baseHookRequest:c.baseHookRequest,hookExecutor:a,toolInput:l.getToolInput(),toolUseId:c.toolUseId,extraHookFields:c.extraHookFields,collector:p,executionDurationMs:f})}catch(e){nL.warn(o,"postExecutionHooks error",{toolName:n.toolName,error:e instanceof Error?e.message:String(e)})}if(p.isAborted())await l.fireFailureAsync(f,"Command was aborted","error",!0);else if(n.isStreamSuccess?.(p)??1)await l.fireSuccessAsync(f,JSON.stringify(n.createSuccessOutput(s,p)));else{const e=n.getStreamErrorMessage?.(s,p)??`Command failed with exit code ${p.getExitCode()}`;await l.fireFailureAsync(f,e,"error")}for(const e of uL(n,c))yield e}}}(e,t,r,rj)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class oj{constructor(e,t,r){const n=new Map;this.wrappedExecutor=lL(e,t,r,function(e){return{toolName:_N,getToolCallId:cL,createToolInput:e=>({file_path:e.path,content:e.fileText}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new FI.v3({result:{case:"error",value:new FI.QM({path:e.path,error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Write error":"Unknown error",createSuccessOutput:e=>({file_path:e.path,success:!0}),runPreExecutionHooks:async t=>{const{args:r,hookExecutor:n,toolUseId:o}=t;if(!1===n.hasHooksForStep?.(Rd.afterFileEdit))return;let s,i=!1;try{(await(0,xo.stat)(r.path)).size>262144?i=!0:s=await Bi(r.path)}catch(e){}e.set(o,{contentBeforeWrite:s,fileTooLarge:i})},runCleanup:t=>{e.delete(t)},runPostExecutionHooks:async t=>{const{args:r,result:n,baseHookRequest:o,hookExecutor:s,toolUseId:i}=t,a=e.get(i);if("success"!==n.result.case||!1===s.hasHooksForStep?.(Rd.afterFileEdit))return;const{contentBeforeWrite:c,fileTooLarge:l}=a??{fileTooLarge:!1};let u;u=l||void 0===c?[{old_string:"",new_string:r.fileText}]:c===r.fileText?[]:function(e,t){const r=(0,dS.YB)("","",e,t,"","",{context:0,timeout:50});return void 0===r?[{old_string:"",new_string:t}]:0===r.hunks.length?[]:r.hunks.map((e=>{const t=[],r=[];for(const n of e.lines)n.startsWith("-")?t.push(n.slice(1)):n.startsWith("+")&&r.push(n.slice(1));return{old_string:t.join("\n"),new_string:r.join("\n")}}))}(c,r.fileText);const d={...o,file_path:r.path,edits:u},h=await s.executeHookForStep(Rd.afterFileEdit,d);if(r.returnFileContentAfterWrite&&void 0!==h){const e=n.result.value.path;try{const t=await Bi(e),r=Xs(t),o=Buffer.byteLength(t,"utf8");return new FI.v3({result:{case:"success",value:new FI.j6({path:n.result.value.path,linesCreated:r,fileSize:o,fileContentAfterWrite:t})}})}catch(e){return}}}}}(n))}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}function sj(e,t,r){return t===e.symbol}function ij(e,t,r){return sj(WT,e)?new ej(t,r.hookExecutor,r.baseHookRequestExtractor):sj(re,e)?new nj(t,r.hookExecutor,r.baseHookRequestExtractor):sj(GT,e)?new oj(t,r.hookExecutor,r.baseHookRequestExtractor):sj(ro,e)?new HL(t,r.hookExecutor,r.baseHookRequestExtractor,r.mcpLease,r.hooksConfigLease):sj(tA,e)||sj(rA,e)?new JL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(nA,e)?new jL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(ZT,e)?new NL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(KT,e)?new OL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(VT,e)?new AL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(oA,e)?new ML(t,r.hookExecutor,r.baseHookRequestExtractor):sj(no,e)?new zL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(oo,e)?new VL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(kA,e)?new EL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(_A,e)?new PL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(IA,e)?new IL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(AA,e)?new XL(t,r.hookExecutor,r.baseHookRequestExtractor):sj(Dr,e)&&(r.hooksAdditionalContextPromise||r.hooksConfigLease)?new SL(t,r.hooksAdditionalContextPromise??Promise.resolve(void 0),r.teamHooksReadyPromise,r.hooksConfigLease):void 0}class aj{constructor(e,t,r,n,o,s,i){this.innerAccessor=e,this.hookExecutor=t,this.baseHookRequestExtractor=r,this.mcpLease=n,this.hooksAdditionalContextPromise=o,this.teamHooksReadyPromise=s,this.hooksConfigLease=i}get(e){const t=function(e,t){if(e.symbol===mL.symbol)return new bL(t)}(e,this.hookExecutor);return void 0!==t?t:function(e,t,r){const n=ij(e.symbol,t,r);return void 0!==n?n:t}(e,this.innerAccessor.get(e),{hookExecutor:this.hookExecutor,baseHookRequestExtractor:this.baseHookRequestExtractor,mcpLease:this.mcpLease,hooksAdditionalContextPromise:this.hooksAdditionalContextPromise,teamHooksReadyPromise:this.teamHooksReadyPromise,hooksConfigLease:this.hooksConfigLease})}*entries(){for(const[e,t]of this.innerAccessor.entries()){const r=ij(e.symbol,t,{hookExecutor:this.hookExecutor,baseHookRequestExtractor:this.baseHookRequestExtractor,mcpLease:this.mcpLease,hooksAdditionalContextPromise:this.hooksAdditionalContextPromise,teamHooksReadyPromise:this.teamHooksReadyPromise,hooksConfigLease:this.hooksConfigLease});yield[e,r??t]}const e=mL;yield[e,new bL(this.hookExecutor)]}}const cj={cursor_version:process.env.AGENT_CLI_STATIC_VERSION??"1.0.0",user_email:null};function lj(e=process.cwd()){let t=e;const r={getCwd:async()=>t,clone:e=>lj(e??t),async*execute(e,r,n={}){const o=n.workingDirectory??t;t=o;const s=function(e){return"win32"===process.platform?{executable:(0,No.oG)(),args:[...eF,"-Command",e]}:{executable:process.env.SHELL||"/bin/sh",args:["-lc",e]}}(r),i=(0,iu.spawn)(s.executable,[...s.args],{cwd:o,env:{...process.env,...n.env??{}},signal:n.signal,stdio:[!0===n.pipeStdin?"pipe":"ignore","pipe","pipe"]}),a=[];let c,l,u=!1;const d=()=>{c?.(),c=void 0},h=e=>{a.push(e),d()};for(i.on("spawn",(()=>{!0===n.pipeStdin&&h({type:"stdin_ready",stdin:i.stdin??void 0})})),i.stdout?.setEncoding("utf8"),i.stdout?.on("data",(e=>{h({type:"stdout",data:String(e)})})),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",(e=>{h({type:"stderr",data:String(e)})})),i.on("error",(e=>{l=e,u=!0,d()})),i.on("close",(e=>{h({type:"exit",code:e}),u=!0}));!u||a.length>0;)0!==a.length?yield a.shift():await new Promise((e=>{c=e}));if(void 0!==l)throw l}};return r}function uj(e,t,...r){for(const n of r){const r=t(e[n]);if(void 0!==r)return r}}function dj(e){return"string"==typeof e&&e.length>0?e:void 0}function hj(e){return"object"==typeof e&&null!==e&&"string"==typeof e.id&&"string"==typeof e.value}function pj(e){if(Array.isArray(e)&&e.every(hj))return e.map((e=>({id:e.id,value:e.value})))}class fj{constructor(e,t){this.innerAccessor=e,this.sessionHooksRuntime=t}get(e){return this.innerAccessor.get(e)}entries(){return this.innerAccessor.entries()}async dispose(){await this.sessionHooksRuntime.dispose()}}async function mj(e,t={}){const r=await new SN(new pL,function(e,t){const r=e.projectRoot??e.workingDirectory??e.workspaceRoots[0],n=t.includeProjectHooks??!0,i=t.includeUserHooks??!0;return{enterpriseConfigPath:t.includeEnterpriseHooks??1?yN():void 0,userConfigPath:i?(0,s.join)((0,o.homedir)(),".cursor","hooks.json"):void 0,claudeUserConfigPath:i?(0,s.join)((0,o.homedir)(),".claude","settings.json"):void 0,projectConfigPath:n&&void 0!==r?(0,s.join)(r,".cursor","hooks.json"):void 0,claudeProjectConfigPath:n&&void 0!==r?(0,s.join)(r,".claude","settings.json"):void 0,claudeProjectLocalConfigPath:n&&void 0!==r?(0,s.join)(r,".claude","settings.local.json"):void 0}}(e,t)).load(),n=new LN(r),i=function(e){return e.projectRoot??e.workingDirectory??e.workspaceRoots[0]??process.cwd()}(e),a=function(e){return Object.freeze({...cj,...e.globalContext??{}})}(t);return{projectDir:e.projectRoot,workspacePath:i,hooksConfig:r,hooksConfigLease:n,globalContext:a,createSessionRuntime(){const e=new NN(r,i,a,(t.createTerminalExecutor??lj)(),t.promptHookClient,void 0,void 0,{enableClaudeNestedHookSpecificOutputCompatibility:!0,commandHookPayloadTransport:(o=t.useCommandHookStdinTransport,!0===o?"stdin":"legacy")});var o;return{hookExecutor:e,hooksConfigLease:n,async dispose(){e.clearSessionEnvironment()}}},async dispose(){}}}function gj(e={}){return{createHooksRuntime:t=>mj(t.workspaceState,e)}}var wj=r("../proto/dist/generated/aiserver/v1/dashboard_service_connect.js");async function yj(e){(function(e){return"object"==typeof e&&null!==e&&"dispose"in e&&"function"==typeof e.dispose})(e)&&await e.dispose()}function vj(e={}){const t=e.getThirdPartyExtensibilityEnabled??(()=>!0),r=e.importThirdPartyPlugins??!1,n=e.includeProjectExtensibility??!0,s=e.includeUserExtensibility??!0,i=e.includeManagedSkills??!0,a=e.includePluginExtensibility??!0,c=new xy,l=(0,o.homedir)(),u=bm(l).dirPath;let d,h=!0;return{async prepareLocalExtensibility(){h=i&&await async function(e){if(!e)return!1;const t=(0,be.createClient)(wj.I,e);return"synced"===(await async function(e,t){try{const r=await t.getManagedSkills()??[],n=await OD(e,{managedSkills:[...r]});return{status:"synced",managedSkillsCount:r.length,syncResult:n}}catch(t){return ND.warn(e,"Failed to sync managed skills from source",{error:t}),{status:"fetch_failed",error:t}}}((0,b.q6)(),{getManagedSkills:async()=>(await t.getManagedSkills(new QD.X8g({}))).skills??[]})).status}(e.dashboardTransport)},async loadLocalExtensibility(o){const i=function(e){if(e.workspaceRoots.length>0)return[...e.workspaceRoots];const t=e.projectRoot??e.workingDirectory;return void 0!==t?[t]:[]}(o.workspaceState);if(0===i.length)return d=void 0,{cursorRulesService:xj(),getAgentSkills:async e=>[]};const p=(0,b.q6)(),f=e.loadNestedRules??!0,m=n?i.map((e=>new gg(p,c,e,f,t,void 0))):[],g=function(e,t){const r=bj(t);return{getAllCursorRules:async t=>Sj(await e.getAllCursorRules(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),dispose(){e.dispose()}}}(0===m.length?xj():1===m.length?m[0]:new mg(m,(()=>Lm)),{allowedRoots:n?i:[],excludedRoots:[]}),w=function(e,t){const r=bj(t);return{getAllCursorRules:async t=>Sj(await e.getAllCursorRules(t),r),getAllAgentSkills:async t=>Sj(await e.getAllAgentSkills(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),onDidChangeSkills:t=>e.onDidChangeSkills(t),dispose(){e.dispose()}}}(new yg(p,n?i:[],l,c,f,void 0,t,Promise.resolve(),"sdk"),{allowedRoots:[...n?i:[],...s?[l]:[],...h?[u]:[]],excludedRoots:h?[]:[u]}),y=n?i.map((e=>new Ig(e,t))):[],v=0===y.length?new _g:1===y.length?y[0]:new Ag(y),S=zO(o.services.pluginBootstrapOutputs),k=S&&a?new bg(p,(()=>({importThirdPartyPlugins:r})),void 0,S.pluginsService):void 0,_=S&&a?new $g((()=>({importThirdPartyPlugins:r})),S.pluginsService):void 0,C=new mg([g,w,...k?[k]:[]],(()=>Lm)),E=new gD([w,...k?[k]:[]],(()=>[]),(()=>({workspacePaths:n?i:[],userHomeDirectory:l,agentStoreSkillsDirs:[]}))),x=new Ag([v,..._?[_]:[]]);d={localRulesService:g,localSkillsService:w,localSubagentsService:v,pluginSkillsService:k,pluginSubagentsService:_,mergedCursorRulesService:C,mergedAgentSkillsService:E,mergedSubagentsService:x};const P={cursorRulesService:C,getAgentSkills:e=>E.getAllAgentSkills(e),subagentsService:x};return P},async disposeLocalExtensibility(){if(!d)return;const e=d;d=void 0,await async function(e){let t;const r=[e.mergedSubagentsService,e.mergedAgentSkillsService,e.mergedCursorRulesService,e.pluginSubagentsService,e.pluginSkillsService,e.localSubagentsService,e.localSkillsService,e.localRulesService];for(const e of r)try{await yj(e)}catch(e){t??=e}if(void 0!==t)throw t}(e)}}}function bj(e){const t=Promise.all(e.allowedRoots.map(Cj)),r=Promise.all(e.excludedRoots.map(Cj));return async e=>{const[n,o,s]=await Promise.all([Ej(e.fullPath),t,r]);return void 0!==n&&!s.some((e=>kj(n,e)))&&o.some((e=>kj(n,e)))}}async function Sj(e,t){const r=await Promise.all(e.map(t));return e.filter(((e,t)=>r[t]))}function kj(e,t){if(e===t)return!0;const r=`${t}/`;return e.startsWith(r)}function _j(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")}async function Cj(e){try{return _j(await(0,xo.realpath)(e))}catch{return _j(e)}}async function Ej(e){try{return _j(await(0,xo.realpath)(e))}catch{return}}function xj(){return{getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}}}function Pj(e,t){const r=e.releaseTag??t;if(e.releaseRepo&&e.releaseAsset&&r)return{kind:"release",releaseRepo:e.releaseRepo,releaseAsset:e.releaseAsset,releaseTag:r}}const Rj=/^[a-z][a-z0-9+.-]*:\/\/([^/?#]*)/i,Ij=/^(?:[^@/\s]+@)?([^:/\s\\]+):(?!\/\/)/,Tj=/^([a-z][a-z0-9+.-]*)::(.*)$/i,Aj=/^([a-z][a-z0-9+.-]*):\/\//i,$j=new Set(["file","git","http","https","ssh"]);function Mj(e){if(/^(?:\\\\|\/\/)[^\\/]/.test(e))throw new Error("Cursor Orbit: plugin git remote could not be validated");const t=Tj.exec(e);if(null!==t){const e=t[1].toLowerCase();if(!$j.has(e))throw new Error("Cursor Orbit: plugin git remote could not be validated");const r=t[2];if(!("http"!==e&&"https"!==e||null!==Aj.exec(r)&&URL.canParse(r)))throw new Error("Cursor Orbit: plugin git remote could not be validated");const n=Mj(r);if(0===n.length)throw new Error("Cursor Orbit: plugin git remote could not be validated");return n}const r=Aj.exec(e)?.[1].toLowerCase();if(void 0!==r&&!$j.has(r))throw new Error("Cursor Orbit: plugin git remote could not be validated");const n=Rj.exec(e)?.[1];if(void 0===n){const t=Ij.exec(e)?.[1];if(void 0===t)return[];const r=function(e){const t=/^\[([^\]]+)\]$/.exec(e)?.[1],r=t??e;if(""!==r&&!/[\[\]\s@%\/\\]/.test(r))return Dj(r)}(t);if(void 0===r)throw new Error("Cursor Orbit: plugin git remote could not be validated");return[r]}const o=[];URL.canParse(e)&&o.push(Dj(new URL(e).hostname));const s=function(e){try{return decodeURIComponent(e)}catch{return e}}(n.slice(n.lastIndexOf("@")+1)),i=`https://${s}`;if(URL.canParse(i))o.push(Dj(new URL(i).hostname));else{const e=/^\[([^\]]+)\](?::\d*)?$/.exec(s)?.[1];if(void 0===e)throw new Error("Cursor Orbit: plugin git remote could not be validated");o.push(Dj(e))}const a=o.filter((e=>""!==e));if(0===a.length)throw new Error("Cursor Orbit: plugin git remote could not be validated");return[...new Set(a)]}function Dj(e){return e.trim().toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,"")}function Oj(){const e=["-c","credential.interactive=false","-c","core.fsmonitor=false"];return"1"===process.env[Yv.K4]&&e.push("-c","http.followRedirects=false"),"win32"===process.platform&&e.push("-c","core.longpaths=true"),e}function Fj(e){return"function"==typeof e?e():e}async function Nj(e,t){const r=function(e){const t={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:void 0,VSCODE_GIT_ASKPASS_NODE:void 0,VSCODE_GIT_ASKPASS_MAIN:void 0,VSCODE_GIT_ASKPASS_EXTRA_ARGS:void 0,GCM_INTERACTIVE:"Never"};if(t.GIT_CONFIG_NOSYSTEM=void 0,!0===e?.sshBatchMode){const e=process.env.GIT_SSH_COMMAND?.trim()||"ssh";t.GIT_SSH_COMMAND=`${e} -oBatchMode=yes`}if(void 0!==e?.extraGitConfig){const r=Object.entries(e.extraGitConfig).flatMap((([e,t])=>Array.isArray(t)?t.map((t=>[e,t])):[[e,t]]));t.GIT_CONFIG_COUNT=String(r.length);for(const[e,[n,o]]of r.entries())t[`GIT_CONFIG_KEY_${e}`]=n,t[`GIT_CONFIG_VALUE_${e}`]=o}return{cwd:e?.cwd,env:t}}({cwd:t?.cwd,sshBatchMode:t?.sshBatchMode,extraGitConfig:t?.extraGitConfig}),n=function(e){return function(e,t=process.env){if("1"!==t[Yv.K4])return;const r=(0,Yv.H)(t[Yv.Zf]);for(const t of e)for(const e of Mj(t))if((0,Yv.ad)(e,r))throw new Error(`Cursor Orbit: plugin git egress to ${e} is refused`)}(e),[...Oj(),...e]}(e);try{return await uy("git",n,{...r,...void 0!==t?.timeoutMs&&{timeout:t.timeoutMs,killSignal:"SIGTERM"}})}catch(e){if("1"===process.env[Yv.K4]&&function(e){if("object"!=typeof e||null===e||!("stderr"in e))return!1;const t=e.stderr;return"string"==typeof t&&/The requested URL returned error: 3\d{2}\b/i.test(t)}(e))throw new Error("Cursor Orbit: the plugin gitUrl redirected. Ask an administrator to update gitUrl to the final URL; redirects are disabled for plugin Git operations.",{cause:e});throw e}}const Lj=/^[0-9a-f]{7,40}$/i,jj=/^[0-9a-f]{40}$/i;function Uj(e){if(void 0===e||""===e)return;const t=e.split(/\r?\n/).map((e=>{const[t,r]=e.split("\t");if(t&&r&&/^[0-9a-f]{40}$/i.test(t))return{sha:t,refName:r}})).filter((e=>void 0!==e)),r=t[0];return void 0!==r?t.find((e=>e.refName.endsWith("^{}")))?.sha??r.sha:void 0}async function Bj(e,t,r){const n=t.trim();if(jj.test(n))return{fullSha:n.toLowerCase()};if(Lj.test(n)){try{const t=await async function(e,t,r){const{stdout:n}=await Nj(["ls-remote",e,`refs/heads/${t}`,`refs/tags/${t}`,`refs/tags/${t}^{}`],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs});return Uj(n)?.toLowerCase()}(e,n,r);if(t)return{fullSha:t}}catch{}return{fullSha:n.toLowerCase()}}let o;try{if("HEAD"===n.toUpperCase()){const t=await Nj(["ls-remote","--symref",e,"HEAD"],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs}),n=Uj(t.stdout);if(!n)throw new Error(`git ls-remote did not return a resolvable commit for HEAD (${e})`);return{fullSha:n.toLowerCase(),headSymrefStdout:t.stdout}}o=(await Nj(["ls-remote",e,n],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs})).stdout}catch(t){const r=t instanceof Error?t.message:String(t),o=new Error(`Failed to resolve git ref "${n}" for ${e}: ${r}`);throw o.cause=t,o}const s=Uj(o);if(!s)throw new Error(`git ls-remote did not return a resolvable commit for ref "${n}" (${e})`);return{fullSha:s.toLowerCase()}}const Wj=Vh.map((function(e){const t=e.split("/")[0];if(void 0===t||0===t.length)throw new Error(`Marketplace manifest path has no directory: ${e}`);return t}));let Hj;function qj(e){let t=e.trim().replaceAll("\\","/");for(;t.startsWith("./");)t=t.slice(2);return t=t.replace(/\/+$/,""),""===t||"."===t||t.startsWith("/")||/^[a-zA-Z]:/.test(t)||t.split("/").some((e=>""===e||"."===e||".."===e))?null:t}function zj(e){const t=[];for(const r of e){const e=qj(r);if(null===e)return"all";t.push(e)}return t}async function Gj(e,t){const r="all"===e?"all":zj(e),n=t&&"all"!==r&&await(process.env.CURSOR_DISABLE_SPARSE_PLUGIN_CLONES?Promise.resolve(!1):(Hj??=(async()=>{try{const{stdout:e}=await Nj(["--version"]),t=function(e){const t=/git version (\d+)\.(\d+)/.exec(e);return t?{major:Number(t[1]),minor:Number(t[2])}:null}(e);return null!==t&&(t.major>2||2===t.major&&t.minor>=28)}catch{return!1}})(),Hj));return{materialize:r,sparse:n,sparseDirs:n?(o=r,[...new Set([...Wj,...o])]):[]};var o}function Vj(e){return e.toLowerCase().includes("filtering not recognized by server")}async function Kj(e,t,r){await Nj(["sparse-checkout","set","--cone","--",...t],{...r,cwd:e})}async function Jj(e){try{await(0,xo.access)((0,s.join)(e,".git","info","sparse-checkout"))}catch{return!1}try{const{stdout:t}=await Nj(["config","--bool","--get","core.sparseCheckout"],{cwd:e});return"true"===t.trim()}catch{return!1}}async function Zj(e,t,r){if("all"!==t&&0===t.length)return;if(!await Jj(e))return;const n={...r,cwd:e,sshBatchMode:!0};if("all"===t)return void await Nj(["sparse-checkout","disable"],n);const o=zj(t);"all"!==o?await Nj(["sparse-checkout","add","--",...o],n):await Nj(["sparse-checkout","disable"],n)}(0,Es.J)((function(){Hj=void 0}));const Xj=/\.git$/i,Qj=new Set(["account","dashboard"]);function Yj(e){return e.replace(Xj,"")}function eU(e){let t;try{t=decodeURIComponent(e)}catch{return}return t.length>0&&!t.includes("/")?t:void 0}function tU(e){const t=e.toLowerCase();return"github.com"===t||t.endsWith(".github.com")}function rU(e){return e.toLowerCase().split(".").includes("gitlab")}function nU(e){const t=e.toLowerCase();return"bitbucket.org"===t||"www.bitbucket.org"===t}function oU(e){const t=e.toLowerCase();return rU(e)?"GitLab":t.includes("bitbucket")?"Bitbucket":t.includes("gitea")||t.includes("codeberg")?"Gitea/Codeberg":t.includes("azure")&&t.includes("dev")?"Azure DevOps":null}function sU(e){return tU(e)?"github":rU(e)?"gitlab":nU(e)?"bitbucket":function(e){const t=e.toLowerCase();return"dev.azure.com"===t||"www.dev.azure.com"===t}(e)?"azure_devops":"generic"}function iU(e){let t;try{const r=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;t=new URL(r.includes("://")?r:`https://${r}`)}catch{return null}const r=t.hostname;let n=t.pathname.split("/").filter(Boolean);Ka(r)&&"git"===n[0]?.toLowerCase()&&(n=n.slice(1));const o=n[0];void 0!==o&&n.length>=3&&"scm"===o.toLowerCase()&&(n=n.slice(1));const s=function(e){const t=e[0],r=e[1];if(!t||!r)return;const n=Yj(r);return n?{owner:t,repo:n,hasSubpath:e.length>2}:void 0}(n);return void 0===s?null:{provider:sU(r),owner:s.owner,repo:s.repo,host:r}}function aU(e){const t=cU(e);if(null===t)return!1;const r=t.pathname.split("/").filter(Boolean),n=r[0];return void 0!==n&&r.length>=3&&"scm"===n.toLowerCase()}function cU(e){try{const t=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;return new URL(t.includes("://")?t:`https://${t}`)}catch{return null}}function lU(e){const t=e.trim();if(""===t)return{error:"URL cannot be empty"};const r=iU(t);if(null===r)return{error:"Invalid URL format. Expected: github.com/owner/repo or gitlab.com/namespace/repo"};if(rU(r.host)){const e=cU(t),r=null===e?void 0:function(e){const t=e.indexOf("-"),r=-1!==t,n=r?e.slice(0,t):[...e];if(n.length<2||n.some((e=>0===e.length)))return;const o=Yj(n[n.length-1]);return o?(n[n.length-1]=o,{repositorySegments:n,hasSpecialRouteSeparator:r}):void 0}(e.pathname.split("/").filter(Boolean));if(null===e||void 0===r)return{error:"Invalid GitLab repository URL format. Expected: https://gitlab.com/namespace/repo"};const n=e.host.replace(/^www\./i,""),o=r.repositorySegments[0],s=r.repositorySegments[r.repositorySegments.length-1];return void 0===o||void 0===s?{error:"Invalid GitLab repository URL format. Expected: https://gitlab.com/namespace/repo"}:{url:`https://${n}/${r.repositorySegments.join("/")}`,owner:o,repo:s,host:n,provider:"gitlab"}}if("bitbucket"===r.provider){const e=function(e){const t=cU(e.trim());if(null!==t&&nU(t.hostname))return function(e){const t=e[0],r=e[1];if(void 0===t||void 0===r)return;const n=eU(t),o=eU(r);if(void 0===n||void 0===o||Qj.has(n.toLowerCase()))return;const s=Yj(o);return s?{workspace:encodeURIComponent(n),repo:encodeURIComponent(s),hasSubpath:e.length>2}:void 0}(function(e){const t=e.pathname.split("/");return""===t[0]&&t.shift(),""===t[t.length-1]&&t.pop(),t}(t))}(t);if(void 0===e)return{error:"Invalid Bitbucket repository URL format. Expected: https://bitbucket.org/{workspace}/{repo}"};const n=r.host.replace(/^www\./i,"");return{url:`https://${n}/${e.workspace}/${e.repo}`,owner:e.workspace,repo:e.repo,host:n,provider:"bitbucket"}}if("azure_devops"===r.provider){const e=cU(t),n=null===e?void 0:function(e){const t=e.findIndex((e=>"_git"===e.toLowerCase()));if(t<1||t>2)return;const r=e[0],n=e[t+1];if(!r||!n)return;const o=Yj(n);if(!o)return;const s=2===t?e[1]:o;return s?{organization:r,project:s,repo:o,hasSubpath:e.length>t+2}:void 0}(e.pathname.split("/").filter(Boolean));if(null===e||void 0===n)return{error:"Invalid Azure DevOps repository URL format. Expected: https://dev.azure.com/{organization}/{project}/_git/{repo}"};const o=r.host.replace(/^www\./i,"");return{url:`https://${o}/${n.organization}/${n.project}/_git/${n.repo}`,owner:n.organization,repo:n.repo,host:o,provider:"azure_devops",project:n.project}}if(function(e){switch(e.provider){case"github":return!0;case"generic":return!Ka(e.host)&&null===oU(e.host);case"gitlab":case"bitbucket":case"azure_devops":return!1;default:return e.provider,!1}}(r)){const e=dU(r.host.replace(/^www\./i,""));return{url:`https://${e}/${aU(t)?"scm/":""}${r.owner}/${r.repo}`,owner:r.owner,repo:r.repo,host:e,provider:"github"}}const n=oU(r.host);return{error:"Only GitHub, GitLab, Bitbucket, and Azure DevOps URLs are currently supported."+(null!==n?` ${n} is not supported yet.`:"")}}function uU(e){const t=lU(e);if("error"in t)return null;switch(t.provider){case"github":return`git@${t.host}:${t.owner}/${t.repo}.git`;case"gitlab":return function(e){let t;try{t=new URL(e.url).pathname.replace(/^\//,"").replace(/\.git$/i,"")}catch{return null}if(0===t.length)return null;return`git@${e.host.replace(/:\d+$/,"")}:${t}.git`}(t);case"bitbucket":case"azure_devops":return null;default:return t.provider,null}}function dU(e){return tU(e)?"github.com":e}function hU(e){return!e.operatingSystems||0===e.operatingSystems.length||e.operatingSystems.includes(function(){const e=(0,o.platform)();return"win32"===e?"Windows":"darwin"===e?"Macintosh":"Linux"}())}function pU(e){return/[\n\r:#[\]{}&*!|>'"%@`]/.test(e)||e.startsWith(" ")||e.endsWith(" ")?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:e}const fU=new Set(["con","prn","aux","nul","com1","com2","com3","com4","com5","com6","com7","com8","com9","lpt1","lpt2","lpt3","lpt4","lpt5","lpt6","lpt7","lpt8","lpt9"]);function mU(e){const t=ih(e).replace(/[. ]+$/g,"");return""===t||"."===t||".."===t?"_":fU.has(t.toLowerCase())?`_${t}`:t}const gU=18e5,wU=6e5,yU={recursive:!0,force:!0,maxRetries:3},vU=["terminal prompts disabled","could not read username","host key verification failed","could not read from remote repository","permission denied","repository not found","user cancelled dialog","spawn git enoent","authentication failed","unable to get password from user","you do not have access to"],bU=["enotempty: directory not empty, rename","/_staging/"],SU=["upload-pack: not our ref","server does not allow request for unadvertised object"];function kU(e){const t=String(e).toLowerCase().replaceAll("\\","/");return vU.some((e=>t.includes(e)))?"user_git_access":bU.every((e=>t.includes(e)))?"local_cache_race":SU.some((e=>t.includes(e)))?"stale_pinned_ref":"infrastructure"}function _U(e){return"object"==typeof e&&null!==e&&(!0===e.killed||_U(e.cause))}function CU(e){return _U(e)?"killed_by_budget":kU(e)}function EU(e){const t=lU(e);if(!("error"in t)&&"gitlab"===t.provider){let r;try{r=new URL(t.url).pathname.replace(/^\//,"")}catch{throw new Error(`Invalid git URL: ${e}`)}const n=r.split("/").filter(Boolean).map((e=>e.toLowerCase()));if(n.length<2)throw new Error(`Invalid git URL: ${e}`);return{host:t.host.toLowerCase(),pathSegments:n}}const r=iU(e);if(null===r)throw new Error(`Invalid git URL: ${e}`);return{host:dU(r.host.replace(/^www\./i,"")).toLowerCase(),pathSegments:[r.owner.toLowerCase(),r.repo.toLowerCase()]}}const xU=new Map;class PU{constructor(e,t){this.cacheRoot=e,this.options=t,this.manifestCache=new Map}get sparsePluginClones(){return this.options?.sparsePluginClones??!1}remoteTimeoutMs(){return this.sparsePluginClones?gU:void 0}localTimeoutMs(){return this.sparsePluginClones?wU:void 0}lsRemoteTimeoutMs(){return this.sparsePluginClones?3e4:void 0}async cloneResolvedRef(e,t,r,n){const o={cwd:e,sshBatchMode:n?.sshBatchMode,extraGitConfig:{...Fj(this.options?.extraGitConfig),"safe.directory":e}},{sparse:s,sparseDirs:i}=await Gj(n?.materialize??"all",this.sparsePluginClones);await Nj(["init"],{...o,timeoutMs:this.localTimeoutMs()}),s&&await Kj(e,i,{sshBatchMode:n?.sshBatchMode,extraGitConfig:Fj(this.options?.extraGitConfig),timeoutMs:this.localTimeoutMs()});const{stderr:a}=await Nj(["fetch","--depth","1",...s?["--filter=blob:none"]:[],t,r],{...o,timeoutMs:this.remoteTimeoutMs()});return await Nj(["checkout","FETCH_HEAD"],{...o,timeoutMs:this.remoteTimeoutMs()}),{strategy:s?"sparse":"full",filterIgnoredByServer:s&&Vj(a??"")}}async createStagingDir(){const e=(0,s.join)(this.cacheRoot,"_staging",(0,ko.randomUUID)());return await(0,xo.mkdir)(e,{recursive:!0}),e}async moveToCanonicalDir(e,t){return await(0,xo.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,xo.rm)(t,yU),await(0,xo.rename)(e,t),t}async cleanStaleStagingDirs(){const e=(0,s.join)(this.cacheRoot,"_staging");try{const t=await(0,xo.readdir)(e,{withFileTypes:!0}),r=Date.now();await Promise.all(t.filter((e=>e.isDirectory())).map((async t=>{try{const n=(0,s.join)(e,t.name),o=await(0,xo.stat)(n);r-o.mtimeMs>PU.STALE_STAGING_THRESHOLD_MS&&await(0,xo.rm)(n,yU)}catch{}})))}catch{}}getLegacyCloneDir(e,t){return(0,s.join)(this.cacheRoot,mU(e),mU(t))}getCanonicalCloneDir(e,t){const{host:r,pathSegments:n}=EU(e);return(0,s.join)(this.cacheRoot,mU(r),...n.map(mU),mU(t))}getCanonicalRepoRootDir(e){const{host:t,pathSegments:r}=EU(e);return(0,s.join)(this.cacheRoot,mU(t),...r.map(mU))}async pruneSiblingCloneDirs(e,t,r){const n=this.getCanonicalRepoRootDir(e),o=mU(t);try{const e=await(0,xo.readdir)(n,{withFileTypes:!0});await Promise.all(e.filter((e=>e.isDirectory()&&e.name!==o)).map((e=>(0,xo.rm)((0,s.join)(n,e.name),yU))))}catch{}if(void 0!==r)try{await(0,xo.rm)(r,yU)}catch{}}async ensureCloned(e,t,r,n=$p,o){const s=this.serializedOnRepo(this.getCanonicalRepoRootDir(t),(()=>this.ensureClonedImpl(e,t,r,n,o?.materialize??"all")));return this.sparsePluginClones?s:(0,Nr.wj)(s,3e4,`ensureCloned timed out after 30000ms for ${t} @ ${r}`)}async ensureMaterialized(e,t,r=$p){const n=this.serializedOnRepo((0,s.dirname)(e),(async()=>{const n=performance.now();try{await Zj(e,t,{extraGitConfig:Fj(this.options?.extraGitConfig),timeoutMs:this.remoteTimeoutMs()}),r.increment("marketplace_cache_manager.ensure_materialized.success",1),r.distribution("marketplace_cache_manager.ensure_materialized.duration",performance.now()-n)}catch(o){throw r.log("error","Failed to materialize plugin directories in sparse marketplace clone",{clonePath:e,spec:"all"===t?"all":t.join(","),error:String(o),errorCategory:CU(o)}),r.increment("marketplace_cache_manager.ensure_materialized.error",1,{error_category:CU(o)}),r.distribution("marketplace_cache_manager.ensure_materialized.duration",performance.now()-n,{outcome:"error"}),o}}));return this.sparsePluginClones?n:(0,Nr.wj)(n,3e4,`ensureMaterialized timed out after 30000ms for ${e}`)}async serializedOnRepo(e,t){const r=`${this.cacheRoot}:${e}`,n=(xU.get(r)??Promise.resolve()).catch((()=>{})).then(t);xU.set(r,n);try{return await n}finally{xU.get(r)===n&&xU.delete(r)}}async ensureClonedImpl(e,t,r,n,o){n.log("info",`MarketplaceCacheManager: Ensuring cloned ${e} at ${t}@${r}`,{marketplaceId:e,gitUrl:t,ref:r});const s=r.trim();let i,a=t.startsWith("git@")||t.startsWith("ssh://")?null:uU(t);if(null!==a)try{i=(await Bj(a,s,{sshBatchMode:!0,extraGitConfig:Fj(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}catch(e){if(this.sparsePluginClones&&_U(e))throw e;n.log("debug","Failed to resolve remote ref using SSH URL, falling back to HTTPS",{gitUrl:t,ref:r,error:String(e),errorCategory:kU(e)}),a=null,i=(await Bj(t,s,{extraGitConfig:Fj(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}else i=(await Bj(t,s,{extraGitConfig:Fj(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha;const c=this.getCanonicalCloneDir(t,i),l=this.getLegacyCloneDir(e,s);n.log("info",`MarketplaceCacheManager: Resolved clone directory for ${e} at ${t}@${r} to ${c}`,{marketplaceId:e,resolvedRef:i,originalRef:s});const u=performance.now(),d=(e,t)=>{n.increment(`marketplace_cache_manager.ensure_cloned.${e}`,1,t),n.distribution(`marketplace_cache_manager.ensure_cloned.${e}.duration`,performance.now()-u,t)};if(await this.isCloneComplete(c)){await this.pruneSiblingCloneDirs(t,i,l);const e=await Jj(c);return e&&await Zj(c,o,{extraGitConfig:Fj(this.options?.extraGitConfig),timeoutMs:this.remoteTimeoutMs()}),d("cache_hit",{strategy:e?"sparse":"full"}),c}return n.increment("marketplace_cache_manager.ensure_cloned.cache_miss",1),this.cloneViaStaging(c,t,a,i,l,r,n,d,o)}async cloneViaStaging(e,t,r,n,o,s,i,a,c){await this.cleanStaleStagingDirs();const l=await this.createStagingDir();i.log("info",`MarketplaceCacheManager: Cloning ${t}@${s} into staging directory: ${l}`,{gitUrl:t,ref:s,cloneDir:e});const u=this.sparsePluginClones?setInterval((()=>{const e=new Date;(0,xo.utimes)(l,e,e).catch((()=>{}))}),PU.STAGING_HEARTBEAT_INTERVAL_MS):void 0;u?.unref?.();try{let u;if(null!==r)try{u=await this.cloneResolvedRef(l,r,n,{sshBatchMode:!0,materialize:c})}catch(e){if(this.sparsePluginClones&&_U(e))throw e;i.log("debug","Falling back to HTTPS clone due to SSH clone failure",{gitUrl:t,ref:s,error:String(e),errorCategory:CU(e)}),await(0,xo.rm)(l,yU),await(0,xo.mkdir)(l,{recursive:!0}),u=await this.cloneResolvedRef(l,t,n,{materialize:c})}else u=await this.cloneResolvedRef(l,t,n,{materialize:c});u.filterIgnoredByServer&&(i.log("warn","Server ignored --filter=blob:none; sparse clone downloaded a full pack",{gitUrl:t,ref:s}),i.increment("marketplace_cache_manager.ensure_cloned.filter_ignored_by_server",1));const d=await this.moveToCanonicalDir(l,e);return await this.pruneSiblingCloneDirs(t,n,o),a("cache_write_success",{strategy:u.strategy}),d}catch(e){const r=CU(e);throw a("error",{error_category:r}),i.log("error","Failed to clone marketplace repository via staging clone",{gitUrl:t,ref:s,error:String(e),errorCategory:r}),i.captureException(e,{error_type:"clone_marketplace_repository",error_category:r}),e}finally{void 0!==u&&clearInterval(u);try{await(0,xo.rm)(l,yU)}catch{}}}async isCloneComplete(e){try{if(!(await(0,xo.stat)(e)).isDirectory())return!1;const t=await(0,xo.readdir)(e);if(!t.includes(".git"))return!1;if(t.length>1)return!0;try{return(await(0,xo.stat)((0,s.join)(e,".git","info","sparse-checkout"))).isFile()}catch{return!1}}catch{return!1}}getPluginDir(e,t){return Sf(e,t)}async copyPluginToDir(e,t){await(0,xo.mkdir)(t,{recursive:!0}),await(0,xo.cp)(e,t,{recursive:!0,verbatimSymlinks:!0})}async readManifest(e,t={}){const r=function(e,t){return JSON.stringify({clonePath:e,repoName:t.repoName??null,fallbackId:t.fallbackId??null})}(e,t);if(this.manifestCache.has(r))return this.manifestCache.get(r)??null;const n=await async function(e,t={}){for(const r of Vh){const n=(0,s.join)(e,r);let o;try{o=await(0,xo.readFile)(n,"utf-8")}catch{continue}const i=kp(o,t);if(i.success)return i.data}return null}(e,t);return this.manifestCache.set(r,n),n}async resolvePluginPath(e,t){const r=await this.readManifest(e);if(!r)return null;const n=r.plugins.find((e=>e.name===t.toLowerCase()));if(!n)return null;const o=Cp(n.source,r.metadata?.pluginRoot);return o&&Ep(o)?o:null}async discoverPlugins(e){const t=await this.readManifest(e);return t?function(e){const t=[],r=function(e,t){const r=[];for(const n of e){const e=n.source;if("string"!=typeof e)switch(e.source){case"github":r.push({entry:n,kind:"external-github",externalUrl:`https://github.com/${e.repo}.git`,externalRef:e.ref,externalSha:e.sha,effectiveRef:e.sha??e.ref});break;case"url":r.push({entry:n,kind:"external-url",externalUrl:e.url,externalRef:e.ref,externalSha:e.sha,effectiveRef:e.sha??e.ref});break;case"git-subdir":r.push({entry:n,kind:"external-git-subdir",externalUrl:e.url,externalRef:e.ref,externalSha:e.sha,effectiveRef:e.sha??e.ref,subdirPath:e.path})}else{const o=Cp(e,t);null!==o?r.push({entry:n,kind:"local",localPath:o}):r.push({entry:n,kind:"unresolvable",rawSource:e})}}return r}(e.plugins,e.metadata?.pluginRoot);for(const e of r){const{name:r,displayName:n,description:o,version:s}=e.entry,i={name:r,displayName:n,description:o,version:s};switch(e.kind){case"local":Ep(e.localPath)&&t.push({...i,sourceType:"local",gitPath:e.localPath});break;case"external-github":t.push({...i,sourceType:"github",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha});break;case"external-url":t.push({...i,sourceType:"url",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha});break;case"external-git-subdir":t.push({...i,sourceType:"git-subdir",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha,subdirPath:e.subdirPath})}}return t}(t):[]}}PU.STALE_STAGING_THRESHOLD_MS=3e5,PU.STAGING_HEARTBEAT_INTERVAL_MS=6e4;const RU=(0,Vs.debuglog)("cursor-plugins");function IU(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function TU(e){return IU(e)?e:void 0}function AU(e){const t=e.name?.trim();return void 0!==t&&t.length>0?t:e.pluginId}function $U(e,t){return void 0!==e?.marketplace?e.marketplace:void 0!==e?.marketplaceId?(t??[]).find((t=>void 0!==t.id&&String(t.id)===String(e.marketplaceId))):void 0}function MU(e,t){const r=t?.distributionGitUrl?.trim();return r?t?.gitUrl&&!qU(e,t.gitUrl)?e:r:e}function DU(e){return e?.distributionGitUrl?.trim()||e?.gitUrl}function OU(e,t){if(e.pinnedGitRef)return e.pinnedGitRef;if(e.plugin?.gitRef)return e.plugin.gitRef;const r=$U(e.plugin,t),n=e.plugin?.gitUrl,o=r?.gitUrl;return n&&o&&n!==o||!r?.gitRef?"main":r.gitRef}const FU="backend-git://";function NU(e,t,r){const n=r?`#${encodeURIComponent(r)}`:"";return`${FU}${encodeURIComponent(e)}@${encodeURIComponent(t)}${n}`}function LU(e){if(!e.startsWith(FU))return null;const t=e.slice(14),r=t.indexOf("#"),n=r>=0?t.slice(0,r):t,o=r>=0?t.slice(r+1):void 0,s=n.lastIndexOf("@");return s<0?null:{gitUrl:decodeURIComponent(n.slice(0,s)),ref:decodeURIComponent(n.slice(s+1)),gitPath:o?decodeURIComponent(o):void 0}}const jU="backend-release://";function UU(e){const t=e.tag?`@${encodeURIComponent(e.tag)}`:"";return`${jU}${encodeURIComponent(e.repo)}#${encodeURIComponent(e.asset)}${t}`}function BU(e){if(!e.startsWith(jU))return null;const t=e.slice(18),r=t.indexOf("#");if(r<0)return null;const n=decodeURIComponent(t.slice(0,r)),o=t.slice(r+1),s=o.lastIndexOf("@");return{repo:n,asset:s>=0?decodeURIComponent(o.slice(0,s)):decodeURIComponent(o),tag:s>=0?decodeURIComponent(o.slice(s+1)):void 0}}const WU=/^[0-9a-f]{7,40}$/i;function HU(e){let t;try{t=EU(e)}catch{return null}return`${t.host}\0${t.pathSegments.join("\0")}`}function qU(e,t){if(e.trim()===t.trim())return!0;const r=HU(e),n=HU(t);return null!==r&&r===n}const zU=104857600;async function GU(e,t,r,n,i,a){const c=await async function(e){const{repo:t,asset:r,tag:n}=e,{apiBase:o,ownerRepo:s,host:i}=function(e){const t=e.split("/"),r=t[0],n=t[1],o=t[2];if(3===t.length&&void 0!==r&&void 0!==n&&void 0!==o)return{apiBase:`https://${r}/api/v3`,ownerRepo:`${n}/${o}`,host:r};if(2===t.length)return{apiBase:"https://api.github.com",ownerRepo:e,host:"github.com"};throw new Error(`Invalid release repo format: ${e}`)}(t),a="github.com"===i&&void 0!==e.githubToken&&e.githubToken.length>0?{Authorization:`token ${e.githubToken}`}:{},c=n?`${o}/repos/${s}/releases/tags/${encodeURIComponent(n)}`:`${o}/repos/${s}/releases/latest`,l=await fetch(c,{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"CursorPluginInstaller",...a}});if(!l.ok)throw new Error(`Failed to fetch release from ${c}: ${l.status} ${l.statusText}`);const u=await l.json();if(!(IU(d=u)&&Array.isArray(d.assets)&&d.assets.every((e=>IU(e)&&"string"==typeof e.name&&"string"==typeof e.browser_download_url&&"number"==typeof e.size))))throw new Error(`Release payload from ${c} did not include assets`);var d;const h=u,p=h.assets.find((e=>e.name===r));if(!p){const e=h.assets.map((e=>e.name)).join(", ");throw new Error(`Release asset "${r}" not found. Available assets: ${e}`)}if(p.size>zU)throw new Error(`Release asset "${r}" exceeds maximum size of 104857600 bytes (actual: ${p.size})`);const f=new URL(p.browser_download_url);if("https:"!==f.protocol||!VU(f.hostname,i))throw new Error(`Refusing to download release asset from untrusted host: ${f.hostname}`);const m=await fetch(p.browser_download_url,{headers:{"User-Agent":"CursorPluginInstaller",Accept:"application/octet-stream",...a}});if(!m.ok)throw new Error(`Failed to download release asset: ${m.status} ${m.statusText}`);if(m.url){const e=new URL(m.url);if("https:"!==e.protocol||!VU(e.hostname,i))throw new Error(`Refusing to download release asset: redirected to untrusted host: ${e.hostname}`)}const g=Buffer.from(await m.arrayBuffer());if(g.byteLength>zU)throw new Error(`Release asset "${r}" actual download size exceeds maximum of 104857600 bytes (actual: ${g.byteLength})`);if(e.expectedSha256){const t=(0,ko.createHash)("sha256").update(g).digest("hex");if(t!==e.expectedSha256)throw new Error(`Release asset "${r}" integrity check failed: expected SHA-256 ${e.expectedSha256}, got ${t}`)}return g}({repo:e,asset:t,tag:r,expectedSha256:i,githubToken:a}),l=c.byteLength;await(0,xo.mkdir)(n,{recursive:!0});const u=await(0,xo.mkdtemp)((0,s.join)((0,o.tmpdir)(),"release-asset-")),d=(0,s.join)(u,"asset.tar.gz"),h=(0,s.join)(u,"extracted");try{await(0,xo.writeFile)(d,c),await(0,xo.mkdir)(h,{recursive:!0});let e=0,t=0;await ah.x({file:d,cwd:h,onReadEntry:r=>{if(t++,t>5e4)throw new Error("Release archive contains too many files (>50000).");if(e+=r.size,e>524288e3)throw new Error("Release archive uncompressed size exceeds maximum of 524288000 bytes.");if(l>0&&e/l>100)throw new Error("Release archive has suspicious compression ratio (>100x).")}});const r=await(0,xo.readdir)(h,{withFileTypes:!0}),o=r.filter((e=>e.isDirectory())),i=r.filter((e=>e.isFile()));let a=h;const u=o[0];if(1===o.length&&0===i.length&&void 0!==u){const e=(0,s.join)(h,u.name);(await(0,xo.readdir)(e)).some((e=>Gh.includes(e)))&&(a=e)}const p=await(0,xo.readdir)(a);await Promise.all(p.map((e=>(0,xo.cp)((0,s.join)(a,e),(0,s.join)(n,e),{recursive:!0,verbatimSymlinks:!0}))))}finally{await(0,xo.rm)(u,{recursive:!0,force:!0}).catch((()=>{}))}}function VU(e,t){return!(e!==t&&!e.endsWith(".githubusercontent.com"))||("github.com"===t?"github.com"===e:e.endsWith(`.${t}`))}class KU{constructor(e,t,r,n,o){this.getEffectiveUserPlugins=e;const s="string"==typeof t||void 0===t?{marketplaceCacheRoot:t,pluginLogger:r,marketplaceCacheOptions:n,listOptions:o}:t,i=s.marketplaceCacheOptions??n;this.pluginLogger=s.pluginLogger??r??$p,this.extraGitConfig=s.extraGitConfig,this.awaitAuthReady=s.awaitAuthReady,this.githubToken=s.githubToken,this.downloadPluginContent=s.downloadPluginContent,this.contentRetries=s.contentRetries??(new Eh).forListing(""),this.sparsePluginClones=s.sparsePluginClones??!1,this.marketplaceCache=s.marketplaceCacheRoot?new PU(s.marketplaceCacheRoot,{...i,extraGitConfig:i?.extraGitConfig??s.extraGitConfig,sparsePluginClones:this.sparsePluginClones}):void 0;const a=s.listOptions??o;this.allowedMarketplaceNames=a?.allowedMarketplaceNames?new Set(a.allowedMarketplaceNames):void 0,this.enableInlinePlugins=a?.enableInlinePlugins??!1}isMarketplaceAllowed(e){return void 0===this.allowedMarketplaceNames||void 0!==e?.name&&this.allowedMarketplaceNames.has(e.name)}async listEnabledPlugins(e,t){const r=await this.getEffectiveUserPlugins(),n=r.plugins??[],o=r.marketplaces??[],s=[],i=[],a=new Map,c=async(e,t)=>{const r=`${e}\0${t}`;let n=a.get(r);if(!n){const o=Fj(this.extraGitConfig),s=this.sparsePluginClones?3e4:void 0,i=e.startsWith("git@")||e.startsWith("ssh://")?null:uU(e),c=async(e,r)=>{const n={};return r&&(n.sshBatchMode=!0),void 0!==o&&(n.extraGitConfig=o),void 0!==s&&(n.timeoutMs=s),(Object.keys(n).length>0?await Bj(e,t,n):await Bj(e,t)).fullSha};if(null!==i)try{n=await c(i,!0)}catch(t){if(this.sparsePluginClones&&_U(t))throw t;n=await c(e,!1)}else n=await c(e,!1);a.set(r,n)}return n},l=async e=>{const{preferredGitUrl:t,sourceGitUrl:r,gitRef:n,pluginId:o}=e;if(t!==r){void 0!==this.awaitAuthReady&&await this.awaitAuthReady();const e=`${t}\0${n}`,s=!a.has(e);let i;s&&this.pluginLogger.increment("marketplace.origin_distribution.fetch",1);try{i={sha:await c(t,n),gitUrl:t}}catch(e){s&&this.pluginLogger.increment("marketplace.origin_distribution.fetch.error",1),this.pluginLogger.captureException(e,{error_type:"distribution_url_fallback"}),this.pluginLogger.log("warn",`Distribution mirror ${t}@${n} unavailable (not synced yet or unreachable); falling back to source ${r}`,{pluginId:o,preferredGitUrl:t,sourceGitUrl:r,gitRef:n,error:String(e)})}if(void 0!==i){if(s)try{this.pluginLogger.log("info",`Resolved plugin ${o} from Origin distribution mirror ${t}@${n}`,{pluginId:o,preferredGitUrl:t,gitRef:n})}catch{}return i}}return{sha:await c(r,n),gitUrl:r}};this.contentRetries.startLoad();for(const e of n){if(!e.isEnabled||!e.plugin?.name)continue;const t=e.plugin,r=$U(t,o);if(!this.isMarketplaceAllowed(r)){this.pluginLogger.log("info",`Skipping plugin ${t.name} because marketplace ${r?.name??""} is not allowed`,{pluginId:t.name,marketplaceName:r?.name,allowedMarketplaceNames:void 0!==this.allowedMarketplaceNames?Array.from(this.allowedMarketplaceNames):void 0});continue}const n=AU({name:t.name,pluginId:void 0!==t.id?String(t.id):t.name??""}),a=n;if(void 0!==t.backendContent&&null!==t.backendContent){const t=this.listBackendContentPlugin(e,r,n);"entry"in t?s.push(t.entry):i.push(t.failure);continue}if(!t.gitUrl){if(!this.enableInlinePlugins){this.pluginLogger.log("info",`Skipping plugin ${n} without gitUrl (enableInlinePlugins=false)`,{pluginId:a});continue}const o=e.inlineContentJson;if(!o){this.pluginLogger.log("info",`Skipping DB-inline plugin ${n}: no inline content provided`,{pluginId:a});continue}const i=(0,ko.createHash)("sha256").update(`${t.id??"0"}:${t.updatedAt??"0"}`).digest("hex").slice(0,40),c=r?.name?{id:void 0!==r.id?`${r.name}-${r.id}`:`${r.name}-inline`,name:r.name}:void 0;this.pluginLogger.log("info",`BackendMarketplaceClient: Adding DB-inline plugin: ${a}`,{pluginId:a,marketplaceId:c?.id??"unknown",version:i}),s.push({pluginId:a,pluginDbId:void 0!==t.id?String(t.id):void 0,configuredVariables:TU(e.configuredVariables),isTeamRequired:e.isTeamRequired,name:n,version:i,downloadUrl:`inline://${t.id??a}`,marketplaceDbId:void 0!==r?.id?String(r.id):void 0,marketplace:c,inlineContentJson:o});continue}const c=t.gitUrl,u=MU(c,r),d=OU(e,o),h=Pj(t,d),p=r?.gitRef??d;let f,m,g=u;try{if(void 0!==h)f=`release/${h.releaseTag}`;else{const e=await l({preferredGitUrl:u,sourceGitUrl:c,gitRef:d,pluginId:a});f=e.sha,g=e.gitUrl}}catch(e){this.pluginLogger.captureException(e,{error_type:"resolve_version_sha"}),this.pluginLogger.log("error",`Failed to resolve version for plugin ${n}@${d}, skipping plugin`,{pluginId:a,ref:d,error:String(e)});const o=e instanceof Error?e.message:String(e);i.push({pluginName:n,pluginId:a,pluginDbId:void 0!==t.id?String(t.id):void 0,marketplaceName:r?.name,errorMessage:o,errorType:/timed?\s*out/i.test(o)?"timeout":"clone"});continue}m=void 0!==h?UU({repo:h.releaseRepo,asset:h.releaseAsset,tag:h.releaseTag}):NU(g,d,t.gitPath??void 0);const w=DU(r);let y=w,v=r?.gitUrl,b=p;if(r?.gitUrl&&w){const e=qU(c,r.gitUrl),t=e?g:w,o=e?c:r.gitUrl,s=e?d:p;v=o;try{const e=await l({preferredGitUrl:t,sourceGitUrl:o,gitRef:s,pluginId:a});b=e.sha,y=e.gitUrl}catch(e){this.pluginLogger.captureException(e,{error_type:"resolve_marketplace_cache_ref"}),this.pluginLogger.log("warn",`Failed to resolve marketplace cache ref for plugin ${n} from ${t}@${s}, falling back to raw ref`,{pluginId:a,cacheRepoUrl:t,cacheRef:s,error:String(e)}),y=o}}const S=r?.name?{id:void 0!==r.id?`${r.name}-${r.id}`:`${r.name}-${encodeURIComponent(r.gitUrl??"project")}`,name:r.name,...y&&{gitUrl:y,gitRef:b}}:void 0,k=void 0!==h||g===c&&y===v?void 0:{downloadUrl:NU(c,d,t.gitPath??void 0),marketplaceGitUrl:v};this.pluginLogger.log("info",`BackendMarketplaceClient: Adding enabled plugin: ${a} from ${b} at ${t.gitPath}`,{pluginId:a,marketplaceId:S?.id??"unknown",gitPath:t.gitPath??void 0,gitRef:b}),s.push({pluginId:a,pluginDbId:void 0!==t.id?String(t.id):void 0,configuredVariables:TU(e.configuredVariables),isTeamRequired:e.isTeamRequired,name:n,version:f,downloadUrl:m,marketplaceDbId:void 0!==r?.id?String(r.id):void 0,marketplace:S,gitPath:t.gitPath??void 0,isOriginBacked:void 0===h&&g!==c||void 0,originSourceFallback:k})}return{plugins:s,listFailures:i}}isBackendContentRetryDue(){return this.contentRetries.isRetryDue()}allowImmediateBackendContentRetry(){this.contentRetries.allowImmediateRetry()}listBackendContentPlugin(e,t,r){const n=xh(e.plugin?.id),o=function(e){const{revision:t}=e;return"string"==typeof t&&wh.test(t)?{revision:t}:{invalid:"revision"}}(e.plugin?.backendContent??{}),s=void 0===n?"plugin_id":"invalid"in o?o.invalid:void 0;if(void 0===n||"invalid"in o)return this.pluginLogger.log("error",`Skipping plugin ${r}: the listing's backend content has an unusable ${s}`,{pluginId:r,invalidField:s}),this.pluginLogger.increment("backend_marketplace_client.backend_content.list.invalid",1),{failure:{pluginName:r,pluginId:r,pluginDbId:n,marketplaceName:t?.name,errorMessage:`Plugin ${JSON.stringify(r)} could not be installed: the server listed it with details this client does not accept.`,errorType:"install"}};const i=t?.name?{id:void 0!==t.id?`${t.name}-${t.id}`:`${t.name}-backend-content`,name:t.name}:void 0;return this.pluginLogger.log("info",`BackendMarketplaceClient: Adding backend-served plugin: ${r}`,{pluginId:r,marketplaceId:i?.id??"unknown",revision:o.revision}),{entry:{pluginId:r,pluginDbId:n,configuredVariables:TU(e.configuredVariables),isTeamRequired:e.isTeamRequired,name:r,version:Rh(o.revision),downloadUrl:(a={pluginDbId:n,revision:o.revision},`${bh}${a.pluginDbId}@${a.revision}`),marketplaceDbId:void 0!==t?.id?String(t.id):void 0,marketplace:i,backendContent:o}};var a}async relistPlugin(e){if(void 0===e.backendContent||void 0===e.pluginDbId)return;const t=await this.getEffectiveUserPlugins(),r=(t.plugins??[]).find((t=>!0===t.isEnabled&&xh(t.plugin?.id)===e.pluginDbId)),n=r?.plugin;if(void 0===r||!n?.name||void 0===n.backendContent||null===n.backendContent)return;const o=$U(n,t.marketplaces??[]);if(!this.isMarketplaceAllowed(o))return;const s=this.listBackendContentPlugin(r,o,e.name);return"entry"in s&&s.entry.version!==e.version?s.entry:void 0}async installBackendContentPlugin(e,t){const r=e.backendContent,n=xh(e.pluginDbId);if(void 0===r||void 0===n)throw new Error(`Plugin ${JSON.stringify(e.name)} has no backend content to install`);const o={pluginDbId:n,revision:r.revision},s=this.contentRetries.heldFailure(o);if(void 0!==s)throw Ih(s,e.name);const i=performance.now();let a="success";try{await Ah({download:this.downloadPluginContent,pluginDbId:n,pluginName:e.name,content:r,targetDir:t}),this.contentRetries.recordAttempt(o)}catch(e){throw a=e instanceof mh?e.reason:"unknown",this.contentRetries.recordAttempt({...o,error:e}),e}finally{this.pluginLogger.increment("backend_marketplace_client.backend_content.install",1,{outcome:a}),this.pluginLogger.distribution("backend_marketplace_client.backend_content.install.duration",performance.now()-i,{outcome:a})}this.pluginLogger.log("info",`Installed backend-served plugin ${e.pluginId}`,{pluginId:e.pluginId,revision:r.revision})}isDirectInstallSameFetch(e){const t=e.marketplace;if(!t?.gitUrl||!t.gitRef)return!1;const r=LU(e.downloadUrl);return!(!r||!qU(r.gitUrl,t.gitUrl)||r.ref!==t.gitRef&&e.version!==t.gitRef)}async installPlugin(e,t){if(void 0!==e.backendContent||Ph(e.downloadUrl))await this.installBackendContentPlugin(e,t);else if(e.inlineContentJson)await async function(e){const{targetDir:t,inlineContentJson:r,pluginName:n}=e,o=JSON.parse(r);await(0,xo.mkdir)(t,{recursive:!0});const i={};if(o.rules&&o.rules.length>0){const e=(0,s.join)(t,"rules");await(0,xo.mkdir)(e,{recursive:!0});const r=[];for(const t of o.rules){if(!t.content)continue;if(!1===t.isActive)continue;const n=`${ih(t.name)}.md`,o=[];o.push(`description: ${pU(t.name)}`),t.globs&&t.globs.length>0&&o.push(`globs: ${pU(t.globs.join(", "))}`),o.push(`alwaysApply: ${!0===t.isRequired}`);const i=`---\n${o.join("\n")}\n---\n\n`;await(0,xo.writeFile)((0,s.join)(e,n),i+t.content,"utf-8"),r.push(`rules/${n}`)}r.length>0&&(i.rules=r)}if(o.commands&&o.commands.length>0){const e=(0,s.join)(t,"commands");await(0,xo.mkdir)(e,{recursive:!0});const r=[];for(const t of o.commands){if(!t.content)continue;if(!1===t.isActive)continue;const n=`${ih(t.name)}.md`,o=t.description?`---\ndescription: ${pU(t.description)}\n---\n\n`:"";await(0,xo.writeFile)((0,s.join)(e,n),o+t.content,"utf-8"),r.push(`commands/${n}`)}r.length>0&&(i.commands=r)}if(o.hooks&&o.hooks.length>0){const e=(0,s.join)(t,"hooks");await(0,xo.mkdir)(e,{recursive:!0});const r={};for(const e of o.hooks){const t=e.hookStep;t&&!1!==e.isActive&&hU(e)&&(r[t]||(r[t]=[]),"prompt"===e.hookType?r[t].push({type:"prompt",prompt:e.promptContent??"",...e.promptModel?{model:e.promptModel}:{}}):r[t].push({type:"command",command:e.scriptContent??""}))}await(0,xo.writeFile)((0,s.join)(e,"hooks.json"),JSON.stringify({version:1,hooks:r},null,2),"utf-8")}if(o.mcpServers&&o.mcpServers.length>0){const e={};for(const t of o.mcpServers)t.config&&(e[t.name]=t.config);Object.keys(e).length>0&&await(0,xo.writeFile)((0,s.join)(t,".mcp.json"),JSON.stringify({mcpServers:e},null,2),"utf-8")}const a={name:n,...i},c=(0,s.join)(t,".cursor-plugin");await(0,xo.mkdir)(c,{recursive:!0}),await(0,xo.writeFile)((0,s.join)(c,"plugin.json"),JSON.stringify(a,null,2),"utf-8")}({targetDir:t,inlineContentJson:e.inlineContentJson,pluginName:e.name});else{e.isOriginBacked&&void 0!==this.awaitAuthReady&&await this.awaitAuthReady();try{return void await this.installFromEntryUrls(e,t)}catch(r){const n=function(e){const t=e.originSourceFallback;if(void 0===t)return;let r=e.marketplace;if(void 0!==r)if(void 0!==t.marketplaceGitUrl)r={...r,gitUrl:t.marketplaceGitUrl};else{const{gitUrl:e,gitRef:t,...n}=r;r=n}return{...e,downloadUrl:t.downloadUrl,marketplace:r,isOriginBacked:void 0,originSourceFallback:void 0}}(e);if(void 0===n)throw r;this.pluginLogger.captureException(r,{error_type:"install_plugin_from_origin_distribution"}),this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from the Origin distribution mirror, falling back to the source repo`,{pluginId:e.pluginId,version:e.version,sourceDownloadUrl:n.downloadUrl,sourceMarketplaceGitUrl:n.marketplace?.gitUrl,error:String(r)}),this.pluginLogger.increment("marketplace.origin_distribution.install.source_fallback",1),await(0,xo.rm)(t,{recursive:!0,force:!0});try{await this.installFromEntryUrls(n,t)}catch(e){throw this.pluginLogger.increment("marketplace.origin_distribution.install.source_fallback.error",1),e}}}}async installFromEntryUrls(e,t){if(null===BU(e.downloadUrl))try{if(await this.tryInstallFromMarketplaceCache(e,t))return void this.emitOriginLoadIfApplicable(e)}catch(t){if(this.pluginLogger.captureException(t,{error_type:"install_plugin_from_marketplace_cache"}),this.sparsePluginClones&&this.isDirectInstallSameFetch(e)&&_U(t))throw this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from marketplace cache; skipping direct install fallback because it would repeat the identical fetch`,{pluginId:e.pluginId,version:e.version,error:String(t)}),t;this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from marketplace cache, falling back to direct install`,{pluginId:e.pluginId,version:e.version,error:String(t)})}await async function(e,t,r=$p,n,i){const a=i?.sparsePluginClones??!1,c=a?gU:void 0,l=BU(e.downloadUrl);if(l){if(e.gitPath){const r=await(0,xo.mkdtemp)((0,s.join)((0,o.tmpdir)(),"release-plugin-"));try{await GU(l.repo,l.asset,l.tag,r,i?.expectedReleaseAssetSha256,i?.githubToken);const n=Sf(r,e.gitPath);await(0,xo.mkdir)(t,{recursive:!0}),await(0,xo.cp)(n,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,xo.rm)(r,{recursive:!0,force:!0}).catch((()=>{}))}}else await GU(l.repo,l.asset,l.tag,t,i?.expectedReleaseAssetSha256,i?.githubToken);return}const u=LU(e.downloadUrl);if(!u)throw new Error(`Invalid download URL format for plugin ${e.pluginId}: ${e.downloadUrl}`);const d=await(0,xo.mkdtemp)((0,s.join)((0,o.tmpdir)(),"backend-plugin-"));try{let o;if(await async function(e,t,r,n=$p,o,s="all",i=!1){const a=performance.now(),c=WU.test(t),l="HEAD"===t.toUpperCase(),u={...o,"safe.directory":r},d=i?gU:void 0,h=i?wU:void 0,{sparse:p,sparseDirs:f}=await Gj(s,i),m=p?["--filter=blob:none","--sparse"]:[],g=!!p||void 0,w=async e=>{p&&await Kj(r,f,{extraGitConfig:u,timeoutMs:e,sshBatchMode:!0})},y=async(e,n)=>{let o;return l?(({stderr:o}=await Nj(["clone","--depth","1",...m,e,r],{extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await w(d)):c?(await Nj(["init"],{cwd:r,extraGitConfig:u,timeoutMs:h}),await Nj(["remote","add","origin",e],{cwd:r,extraGitConfig:u,timeoutMs:h}),await w(h),({stderr:o}=await Nj(["fetch","--depth","1",...p?["--filter=blob:none"]:[],"origin",t],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await Nj(["checkout","FETCH_HEAD"],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})):(({stderr:o}=await Nj(["clone","--depth","1","--branch",t,...m,e,r],{extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await w(d)),o},v=e.startsWith("git@")||e.startsWith("ssh://")?null:uU(e);let b;if(null!==v)try{b=await y(v,!0)}catch(t){if(i&&_U(t))throw t;await(0,xo.rm)(r,{recursive:!0,force:!0}),await(0,xo.mkdir)(r,{recursive:!0}),b=await y(e,g)}else b=await y(e,g);p&&Vj(b)&&(n.log("warn",`shallowClone: server ignored --filter=blob:none for ${e}; sparse clone downloaded a full pack`),n.increment("backend_marketplace_client.shallow_clone.filter_ignored_by_server",1));const S=(performance.now()-a).toFixed(1);RU("shallowClone %s@%s completed in %sms",e,t,S),n.log("info",`shallowClone ${e}@${t} completed in ${S}ms (${p?"sparse":"full"})`)}(u.gitUrl,u.ref,d,r,n,u.gitPath?zj([u.gitPath]):[],a),u.gitPath)o=Sf(d,u.gitPath);else{const t=await async function(e,t){for(const r of Vh){const n=(0,s.join)(e,r);let o;try{o=await(0,xo.readFile)(n,"utf-8")}catch{continue}const i=kp(o);if(!i.success)return{type:"manifest-unresolved",reason:`Invalid marketplace manifest at ${r}: ${i.error}`};const a=i.data,c=a.plugins.find((e=>e.name===t.toLowerCase()));if(!c)return{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} not found in ${r}`};if("string"!=typeof c.source&&"git-subdir"===c.source.source)return{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} uses unsupported git-subdir source`};const l=Cp(c.source,a.metadata?.pluginRoot);return l&&Ep(l)?{type:"resolved",gitPath:l}:{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} has unresolved or unsafe source path`}}return{type:"no-manifest"}}(d,e.name);if("resolved"===t.type)await Zj(d,zj([t.gitPath]),{extraGitConfig:n,timeoutMs:c}),o=Sf(d,t.gitPath);else{if("manifest-unresolved"===t.type)throw new Error(`Unable to install plugin ${JSON.stringify(e.name)} without gitPath: ${t.reason}`);await Zj(d,"all",{extraGitConfig:n,timeoutMs:c}),o=d}}await(0,xo.mkdir)(t,{recursive:!0}),await(0,xo.cp)(o,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,xo.rm)(d,{recursive:!0,force:!0}).catch((()=>{}))}}(e,t,this.pluginLogger,Fj(this.extraGitConfig),{githubToken:this.githubToken,sparsePluginClones:this.sparsePluginClones}),this.emitOriginLoadIfApplicable(e)}emitOriginLoadIfApplicable(e){if(e.isOriginBacked)try{this.pluginLogger.increment("marketplace.origin_distribution.load",1),this.pluginLogger.log("info",`Loaded plugin ${e.pluginId} from Origin distribution (fetch complete)`,{pluginId:e.pluginId})}catch{}}async prewarmMarketplaceClones(e){const t=this.marketplaceCache;if(!t)return;const r=new Map;for(const t of e){const e=t.marketplace;if(!e?.gitUrl)continue;const n=e.gitRef??"main",o=`${e.id}\0${e.gitUrl}\0${n}`;let s=r.get(o);void 0===s&&(s={marketplaceId:e.id,gitUrl:e.gitUrl,gitRef:n,gitPaths:[]},r.set(o,s)),t.gitPath&&s.gitPaths.push(t.gitPath)}for(const e of r.values()){const r=zj(e.gitPaths),n=performance.now();try{await t.ensureCloned(e.marketplaceId,e.gitUrl,e.gitRef,this.pluginLogger,{materialize:r}),this.pluginLogger.log("info",`Prewarmed marketplace clone ${e.gitUrl}@${e.gitRef} for ${e.gitPaths.length} plugin directories`,{marketplaceId:e.marketplaceId,gitUrl:e.gitUrl,gitRef:e.gitRef,requestedDirs:e.gitPaths.length,materialize:"all"===r?"all":r.length}),this.pluginLogger.increment("marketplace_cache_manager.prewarm.success",1,{materialize:"all"===r?"all":"dirs"})}catch(t){this.pluginLogger.captureException(t,{error_type:"prewarm_marketplace_clone"}),this.pluginLogger.log("warn",`Failed to prewarm marketplace clone ${e.gitUrl}@${e.gitRef}; falling back to per-plugin materialization`,{marketplaceId:e.marketplaceId,gitUrl:e.gitUrl,gitRef:e.gitRef,error:String(t)}),this.pluginLogger.increment("marketplace_cache_manager.prewarm.error",1)}this.pluginLogger.distribution("marketplace_cache_manager.prewarm.duration",performance.now()-n)}}async tryInstallFromMarketplaceCache(e,t){const r=this.marketplaceCache,n=e.marketplace;if(!r||!n||!n.gitUrl)return this.pluginLogger.log("info","No marketplace cache or marketplace metadata, skipping cache check",{pluginId:e.pluginId,name:e.name,version:e.version,marketplaceId:e.marketplace?.id}),!1;const o=await r.ensureCloned(n.id,n.gitUrl,n.gitRef??"main",this.pluginLogger,{materialize:e.gitPath?zj([e.gitPath]):[]}),s=e.gitPath??await r.resolvePluginPath(o,e.name);if(!s)return this.pluginLogger.log("info","No git path found for plugin, skipping cache check",{pluginId:e.pluginId,name:e.name,version:e.version,marketplaceId:e.marketplace?.id}),!1;void 0===e.gitPath&&await r.ensureMaterialized(o,zj([s]),this.pluginLogger);const i=r.getPluginDir(o,s);return await r.copyPluginToDir(i,t),!0}async discoverMarketplacePlugins(e,t,r){const n=this.marketplaceCache;if(!n)throw new Error("discoverMarketplacePlugins requires a MarketplaceCacheManager (marketplaceCacheRoot)");const o=await n.ensureCloned(e,t,r,this.pluginLogger,{materialize:[]});return n.discoverPlugins(o)}}function JU(e,t,r,n,o){return new KU(e,t,r,n,o)}function ZU(e){const t=e.trim();if(!t)return!1;if(t.startsWith("git@"))return/^git@[a-zA-Z0-9.-]+:[a-zA-Z0-9._~\-/]+(?:\.git)?$/.test(t);try{const e=new URL(t);return"https:"===e.protocol&&""===e.username&&""===e.password&&""===e.search&&""===e.hash}catch{return!1}}class XU extends Error{constructor(e){super(e),this.name="SettingsParseError"}}function QU(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function YU(e){return 65279===e.charCodeAt(0)?e.slice(1):e}async function eB(e){try{return YU(await(0,xo.readFile)(function(e){return(0,s.join)(e,".cursor","settings.json")}(e),"utf-8"))}catch(e){if(function(e){return e instanceof Error&&"code"in e}(e)&&("ENOENT"===e.code||"ENOTDIR"===e.code))return;throw e}}async function tB(e){const t=await eB(e);return void 0===t?[]:function(e){const t=function(e){const t=YU(e);if(0===t.trim().length)return{};const r=[],n=(0,xp.qg)(t,r,{allowTrailingComma:!0});if(r.length>0){const e=r.slice(0,3).map((e=>`${(0,xp._n)(e.error)} at offset ${e.offset}`)).join("; ");throw new XU(`.cursor/settings.json contains syntax errors: ${e}`)}if(!QU(n))return{};const o=n.plugins;if(void 0===o)return{};if(!QU(o))return{};const s={};for(const[e,t]of Object.entries(o))QU(t)&&(s[e]=t);return{plugins:s}}(e);return t.plugins?Object.entries(t.plugins).filter((([,e])=>!0===e.enabled)).filter((([,e])=>!e.gitUrl||ZU(e.gitUrl))).map((([e,t])=>({key:e,entry:t}))):[]}(t)}function rB(e){const t=e.indexOf("/");return-1===t?{name:e}:{name:e.slice(t+1),marketplaceName:e.slice(0,t)}}const nB={supportsBackendContent:!0};function oB(e={}){const t=e.userHomeDirectory??(0,o.homedir)(),r=e.importThirdPartyPlugins??!1,n=e.pluginLogger??{log(e,t,r){switch(e){case"warn":CO.Jz.warn("[local-plugins-bootstrap]",t,r??{});break;case"error":CO.Jz.error("[local-plugins-bootstrap]",t,r??{})}},increment(){},distribution(){},captureException(e,t){CO.Jz.error("[local-plugins-bootstrap] Unexpected plugin exception:",e,t??{})}},i=sB(e.marketplaceOptions),a=void 0!==e.dashboardTransport,c=e.loadCursorFirstParty??(i||a);return{async loadPluginBootstrapOutputs(o){const i=(a=o.workspaceState).projectRoot??a.workspaceRoots[0]??a.workingDirectory;var a;const{discoveredEntries:l,failures:u}=await async function(e){if(void 0===e)return{discoveredEntries:[],failures:[]};try{return{discoveredEntries:(await tB(e)).map((({key:t,entry:r})=>({source:"project-settings",workspacePath:e,key:t,entry:r}))),failures:[]}}catch(e){return{discoveredEntries:[],failures:[{stage:"discovery",source:"project-settings",message:e instanceof Error?`Failed to read project plugin settings: ${e.message}`:`Failed to read project plugin settings: ${String(e)}`,detail:e}]}}}(i),d=e.marketplaceOptions??(e.dashboardTransport?function(e){const t=(0,s.join)(e.userHomeDirectory,".cursor","plugins","marketplaces"),r=(0,be.createClient)(wj.I,e.dashboardTransport),n=(e,{signal:t})=>r.downloadPluginContent(e,{signal:t}),o=new Eh,i=JU((async()=>{try{return await r.getEffectiveUserPlugins(new QD.EwF(nB))}catch{return{plugins:[]}}}),{marketplaceCacheRoot:t,listOptions:{allowedMarketplaceNames:["cursor-public"]},downloadPluginContent:n,contentRetries:o.forListing("account")}),a=e.workspacePath,c=JU((async()=>{if(void 0===a)return{plugins:[]};try{const e=await tB(a);if(0===e.length)return{plugins:[]};const t=e.filter((e=>e.entry.gitUrl)),n=e.filter((e=>!e.entry.gitUrl)),o=t.filter((({entry:e})=>{const t=e.gitUrl;return!t||ZU(t)})).map((({key:e,entry:t})=>{const r=rB(e),n=t.gitUrl;return{plugin:{name:r.name,gitUrl:n,gitRef:t.gitRef,gitPath:t.gitPath,marketplace:{name:r.marketplaceName,gitUrl:n,gitRef:t.gitRef}},isEnabled:!0}}));let s=[];if(n.length>0)try{const e=n.map((e=>{const t=rB(e.key);return new QD.vwy({name:t.name,marketplaceName:t.marketplaceName})})),t=await r.resolvePluginsByRef(new QD.WvV({refs:e,...nB}));s=t.plugins?.map((e=>({plugin:e,isEnabled:!0})))??[]}catch{}return{plugins:[...o,...s]}}catch{return{plugins:[]}}}),{marketplaceCacheRoot:t,listOptions:{allowedMarketplaceNames:["cursor-public"]},downloadPluginContent:n,contentRetries:o.forListing("project")});return[{client:i,userId:"",cacheManager:new fh(e.userHomeDirectory),pruneOldVersions:!0},{client:c,userId:"",cacheManager:new fh(e.userHomeDirectory),pruneOldVersions:!0}]}({dashboardTransport:e.dashboardTransport,workspacePath:i,userHomeDirectory:t}):void 0),h=sB(d),p=new HD(void 0!==i?[i]:[],t,(()=>({importThirdPartyPlugins:r,loadCursorFirstParty:c})),d,n);let f=[];const m=[...u];try{f=await p.getAllEnabledPlugins()}catch(e){m.push({stage:"resolution",source:"plugin-loader",message:e instanceof Error?`Failed to load plugins: ${e.message}`:`Failed to load plugins: ${String(e)}`,detail:e})}l.length>0&&!h&&m.push({stage:"resolution",source:"plugin-loader",message:"Project plugin entries were discovered, but no marketplace-backed project plugin source was configured. Those entries remain available through discoveredEntries only.",detail:{workspacePath:i,discoveredEntryCount:l.length}});const g={kind:qO,discoveredEntries:l,loadedPlugins:f,loadFailures:p.getLoadFailures(),bootstrapFailures:m,pluginsService:p,async dispose(){}};for(const e of m)CO.Jz.warn("[local-plugins-bootstrap] Plugin bootstrap failure:",{workspacePath:i,stage:e.stage,source:e.source,message:e.message,detail:e.detail});for(const e of g.loadFailures)CO.Jz.warn("[local-plugins-bootstrap] Plugin load failure:",{workspacePath:i,pluginName:e.pluginName,pluginId:e.pluginId,marketplaceName:e.marketplaceName,errorType:e.errorType,errorMessage:e.errorMessage});return[g]}}}function sB(e){return void 0!==e&&(!Array.isArray(e)||e.length>0)}class iB{async getAllCursorRules(e){return[]}reload(e){}dispose(){}onDidChangeRules(e){return()=>{}}}const aB=["projectFolder","terminalsFolder","agentSharedNotesFolder","agentConversationNotesFolder","agentTranscriptsFolder","processWorkingDirectory","artifactsFolder"];function cB(e){if(e.length<=1)return e;let t=e.length;for(;t>1&&("/"===(r=e[t-1])||"\\"===r)&&(3!==t||":"!==e[1]);)t-=1;var r;return e.slice(0,t)}function lB(e){const t=cB(e).replaceAll("\\","/");return/^[A-Za-z]:\/$/.test(t)?t.slice(0,-1):t}function uB(e){const t=cB(e.reportedWorkspacePath);if(""===e.suffix)return t;const r=t.replaceAll("\\","/"),n="/"===r?e.suffix:`${r}${e.suffix}`;return t.includes("\\")?n.replaceAll("/","\\"):n}function dB(e){const t=lB(e.value),r=e.roots.filter((e=>e.host.length>0)).sort(((e,t)=>lB(t.host).length-lB(e.host).length));for(const e of r){const r=lB(e.host);if(t===r)return uB({reportedWorkspacePath:e.reported,suffix:""});const n="/"===r?"/":`${r}/`;if(t.startsWith(n)){const n="/"===r?t:t.slice(r.length);return uB({reportedWorkspacePath:e.reported,suffix:n})}}}const hB={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1};class pB extends cD{constructor(e,t){super(e),this.sessionMcpLease=t}async dispose(){try{await super.dispose()}finally{await yj(this.sessionMcpLease)}}}function fB(e){const t=new xy;return{async createResources(r){const n=e.createSessionDependencies?.(r)??{pendingDecisionStore:e.pendingDecisionStore,fileChangeTracker:e.fileChangeTracker,permissionsService:e.permissionsService};if(!n.pendingDecisionStore||!n.fileChangeTracker||!n.permissionsService)throw new Error("Local resource provider factory requires either shared dependencies or a per-session dependency factory.");const o=r.workspaceServices.cursorRulesService??new iB,s=r.workspaceServices.subagentsService??new _g,i=r.workspaceServices.mcpLease??new oI,a=!0===r.options.excludeProjectMcp,c=void 0!==r.options.mcpServersOverride||a?void 0!==e.createSessionMcpLease?await e.createSessionMcpLease(r,r.options.mcpServersOverride):a?new oI:void 0:void 0,l=(u=c??i,0===(d=r.options.extraMcpTools??[]).length?u:"onDidChange"in(h=u)&&"function"==typeof h.onDidChange?new Kw(u,d):new Vw(u,d));var u,d,h;try{const i=await async function(e,t){return void 0===e?{}:"function"==typeof e?await e({sessionId:t.sessionState.sessionId,metadata:t.metadata}):e}(r.options.localResourceProviderOptions,r),a=await async function(e){if(void 0===e)return hB;try{const t=await e();return{powershellUtf8Console:t.powershellUtf8Console,powershellUtf8ChildEnv:t.powershellUtf8ChildEnv}}catch{return hB}}(e.getPowershellUtf8Options),u={pendingDecisionStore:n.pendingDecisionStore,fileChangeTracker:n.fileChangeTracker,gitExecutor:t,ignoreService:e.ignoreService,grepProvider:e.grepProvider,permissionsService:n.permissionsService,workspacePaths:e.workspacePaths,diagnosticsProvider:e.diagnosticsProvider,mcpLease:l,mcpStateAccessor:e.createMcpStateAccessor?.(l,r.options),cursorRulesService:o,subagentsService:s,repositoryProvider:e.repositoryProvider,projectDir:e.projectDir,shellManager:e.shellManager,_defaultSandboxPolicy:e.defaultSandboxPolicy??{type:"insecure_none"},_defaultSandboxPolicySources:e.defaultSandboxPolicySources,getSandboxEnabled:e.getSandboxEnabled,getSandboxSupported:e.getSandboxSupported,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:e.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:e.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:e.getMockPromptTime,mcpFileOutputThresholdBytes:e.mcpFileOutputThresholdBytes,mcpMetaToolEnabled:e.mcpMetaToolEnabled,attributionConfigProvider:e.attributionConfigProvider,getAgentSkills:r.workspaceServices.getAgentSkills,powershellUtf8Console:a.powershellUtf8Console,powershellUtf8ChildEnv:a.powershellUtf8ChildEnv,...i},d=void 0===c?new cD(u):new pB(u,c);return void 0===r.options.reportedWorkspacePath&&void 0===r.options.reportedProjectFolder||function(e,t){const r=e.get(Dr);if(void 0===r)return;const{reportedWorkspacePath:n,reportedProjectFolder:o}=t,s=void 0===n?[]:t.workspacePaths.map((e=>({host:e,reported:n}))),i=o??n;void 0!==i&&s.push({host:t.projectDir,reported:i}),e.register(Dr,{execute:async(e,t,o)=>function(e,t){if("success"!==e.result.case||void 0===e.result.value.requestContext?.env)return e;const r=e.clone();if("success"!==r.result.case)return e;const n=r.result.value.requestContext?.env;if(void 0===n)return r;const{roots:o,reportedWorkspacePath:s}=t;n.workspacePaths=n.workspacePaths.map((e=>dB({value:e,roots:o})??e));for(const e of aB){const t=n[e];if(void 0===t||""===t)continue;const r=dB({value:t,roots:o});n[e]="processWorkingDirectory"===e&&void 0!==s?r??cB(s):r??t}return r}(await r.execute(e,t,o),{roots:s,reportedWorkspacePath:n})})}(d,{reportedWorkspacePath:r.options.reportedWorkspacePath,reportedProjectFolder:r.options.reportedProjectFolder,workspacePaths:u.workspacePaths,projectDir:u.projectDir}),d}catch(e){throw await yj(c),e}}}}const mB=["cursorRulesService","getAgentSkills","subagentsService"],gB=new WeakSet;function wB(e){("object"==typeof e&&null!==e||"function"==typeof e)&&gB.add(e)}function yB(e){return("object"==typeof e&&null!==e||"function"==typeof e)&&gB.has(e)}function vB(e,t){const r=Object.keys(t).filter((e=>!mB.includes(e)));if(r.length>0)throw new Error(`Workspace service contributors may only provide ${mB.join(", ")}. Received unsupported service keys: ${r.join(", ")}.`);for(const r of mB)Object.hasOwn(t,r)&&(e[r]=t[r])}async function bB(e,t,r){const __p=e=>{try{globalThis[Symbol.for("@cursor/sdk.startupPhase")]?.(e)}catch{}};const n={config:void 0,plugins:[],pluginBootstrapOutputs:[],cursorRulesService:void 0,getAgentSkills:void 0,subagentsService:void 0,mcpLease:void 0,hooksRuntime:void 0};try{n.config=e.config?await e.config.loadConfig(t):void 0,(e.plugins||e.pluginBootstrap)&&__p("plugins"),n.plugins=e.plugins?await e.plugins.loadPlugins(t):[];const o=()=>({workspaceState:t,policy:r,services:n});n.pluginBootstrapOutputs=e.pluginBootstrap?await e.pluginBootstrap.loadPluginBootstrapOutputs(o()):n.pluginBootstrapOutputs,e.mcp&&__p("mcp"),n.mcpLease=e.mcp?await e.mcp.createLease(o()):void 0,e.hooks&&__p("hooks"),n.hooksRuntime=e.hooks?await e.hooks.createHooksRuntime(o()):void 0,e.localExtensibility&&__p("skills"),e.localExtensibility?.prepareLocalExtensibility&&await e.localExtensibility.prepareLocalExtensibility(o());const s=e.localExtensibility?await e.localExtensibility.loadLocalExtensibility(o()):void 0;void 0!==s&&(wB(s.cursorRulesService),wB(s.subagentsService),Object.assign(n,s));for(const t of e.workspaceServicesContributors??[]){const e=await t.contributeServices(o());void 0!==e&&vB(n,e)}return __p("connecting"),n}catch(t){try{await SB(n,{disposeLocalExtensibility:void 0===e.localExtensibility?void 0:()=>e.localExtensibility?.disposeLocalExtensibility?.()})}catch(e){throw function(e,t){return new AggregateError([t],"Workspace service loading failed and resource cleanup also failed.",{cause:e})}(t,e)}throw t}}async function SB(e,t){const r=t?.preserveSharedContributorsFrom;let n;const o=async e=>{try{await yj(e)}catch(e){n??=e}};if(e.subagentsService===r?.subagentsService||yB(e.subagentsService)||await o(e.subagentsService),e.cursorRulesService===r?.cursorRulesService||yB(e.cursorRulesService)||await o(e.cursorRulesService),t?.disposeLocalExtensibility)try{await t.disposeLocalExtensibility()}catch(e){n??=e}await o(e.hooksRuntime),await o(e.mcpLease);try{await async function(e){let t;for(let r=e.length-1;r>=0;r-=1)try{await yj(e[r])}catch(e){t??=e}if(void 0!==t)throw t}(e.pluginBootstrapOutputs)}catch(e){n??=e}if(void 0!==n)throw n}const kB=["project","user","team","mdm","plugins"],_B=new Set([...kB,"all"]);function CB(e){if(void 0===e||0===e.length)return xB([]);for(const t of e)if(!_B.has(t))throw new Error(`Unsupported setting source "${t}"`);if(e.includes("all")){if(e.length>1)throw new Error('settingSources cannot mix "all" with individual setting sources');return{...xB(kB),all:!0}}return xB(e.filter((e=>"all"!==e)))}function EB(e,t){return e[t]}function xB(e){const t=new Set(e);return{project:t.has("project"),user:t.has("user"),team:t.has("team"),mdm:t.has("mdm"),plugins:t.has("plugins"),all:!1}}const PB=Object.freeze({}),RB=Object.freeze({allowMcpServers:!0,allowPlugins:!0,allowBackgroundSessions:!0,requireMcpApproval:!1,maxParallelSessions:void 0,sandboxMode:void 0,metadata:PB});async function IB(e){const t=new Set;let r;for(let n=e.length-1;n>=0;n-=1){const o=e[n];if(!t.has(o)){t.add(o);try{await yj(o)}catch(e){r??=e}}}if(void 0!==r)throw r}async function TB(e={}){const t=function(e={}){return{workspace:e.workspace??SO,config:e.config,plugins:e.plugins,pluginBootstrap:e.pluginBootstrap,mcp:e.mcp,hooks:e.hooks,localExtensibility:e.localExtensibility,resourceFactory:e.resourceFactory,resourceWrappers:e.resourceWrappers,workspaceServicesContributors:e.workspaceServicesContributors,lifecycle:e.lifecycle}}(e.adapters),r=await t.workspace.resolveWorkspaceState({workingDirectory:e.workingDirectory,projectRoot:e.projectRoot,projectDirectory:e.projectDirectory,workspaceRoots:e.workspaceRoots}),n=await async function(e,t){return e.resolvePolicy(t)}(e.policyAdapter??function(e={}){const t=Object.freeze({...RB.metadata,...e.metadata}),r={...RB,...e,metadata:t};return{name:"permissive-sdk-local",resolvePolicy:()=>r}}(),{workspaceState:r});let o=await bB(t,r,n),s=!1,i=Promise.resolve();const a=e=>{const t=i.then(e);return i=t.catch((()=>{})),t},c=t.localExtensibility,l=void 0===c?void 0:()=>c.disposeLocalExtensibility?.();return{state:r,get services(){return o},policy:n,async createSessionRuntime(e={}){if(s)throw new Error("Cannot create a session runtime after the workspace runtime has been disposed.");return async function(e){const t={sessionId:e.options?.sessionId??(0,ye.C)(),createdAt:new Date},r=Object.freeze({...e.options?.metadata??{}}),n={options:e.options??{},workspaceState:e.workspaceState,workspaceServices:e.workspaceServices,policy:e.policy,sessionState:t,metadata:r,getAgentSkills:e.workspaceServices.getAgentSkills};let o,s;const i=[];try{o=e.adapters.resourceFactory?await e.adapters.resourceFactory.createResources(n):void 0,s=o,i.push(o);for(const t of e.adapters.resourceWrappers??[])s=await t.wrapResources({...n,baseResources:o,resources:s}),i.push(s);await(e.adapters.lifecycle?.onSessionCreated?.(t))}catch(e){try{await IB(i)}catch(t){throw function(e,t){return new AggregateError([t],"Session creation failed and resource cleanup also failed.",{cause:e})}(e,t)}throw e}let a=!1;return{state:t,resources:{base:o,wrapped:s},metadata:r,workspaceServices:e.workspaceServices,policy:e.policy,async dispose(){if(!a){a=!0;try{await IB(i)}finally{await(e.adapters.lifecycle?.onSessionDisposed?.(t))}}}}}({options:e,workspaceState:r,workspaceServices:o,policy:n,adapters:t})},async reload(){s||await a((async()=>{if(s)return;const e=o,i=await bB(t,r,n);s?await SB(i,{disposeLocalExtensibility:l}):(o=i,await SB(e,{preserveSharedContributorsFrom:i,disposeLocalExtensibility:l}),await(t.lifecycle?.onWorkspaceReload?.(r)))}))},async dispose(){s||(s=!0,await a((async()=>{try{await SB(o,{disposeLocalExtensibility:l})}finally{await(t.lifecycle?.dispose())}})))}}}class AB{async requestApproval(e){return{approved:!0}}}class $B{constructor(e,t,r,n){this.approvalMode=e,this.userConfiguredPolicy=t,this.teamSettingsService=r,this.respectAdminControls=n}async getPermissions(){const e=!(!this.respectAdminControls||"insecure_none"===this.userConfiguredPolicy.type)&&(await this.teamSettingsService.getSandboxingControls()).sandboxingDisabled;return{allow:[],deny:[],approvalMode:this.approvalMode,userConfiguredPolicy:e?{type:"insecure_none"}:this.userConfiguredPolicy}}async updatePermissions(){}}class MB{async open(e,t){}async getDiagnostics(e,t){return[]}}class DB{async getCodebaseReference(e,t){}}class OB{constructor(e,t){this.inner=e,this.allowlistReports=t}async getState(e){const t=await this.inner.getState(e);return await this.reportAllowlists(e),{...t,servers:t.servers.filter((e=>"needsAuth"!==e.status))}}async reportAllowlists(e){if(void 0===this.allowlistReports)return;const{mcpLease:t,onMcpAllowlistInUse:r,onMcpServerBlockedByAllowlist:n}=this.allowlistReports;let o;try{o=await t.getClients(e)}catch(e){return void CO.Jz.warn("[sdk-mcp-state] Could not read the MCP allowlist in use:",e)}for(const[e,t]of Object.entries(o))try{if(void 0!==r){const n=await(t.getAllowlistInUse?.());void 0!==n&&r({serverName:e,allowlist:n})}if(void 0!==n){const r=await(t.getAllowlistRefusal?.());void 0!==r&&n({serverName:e,refusal:r})}}catch(e){CO.Jz.warn("[sdk-mcp-state] Could not read the MCP allowlist in use:",e)}}}class FB{constructor(e){this.subagents=e.map((e=>new Sg.zz({fullPath:`sdk-inline://${e.name}`,name:e.name,description:e.description,tools:[],model:e.model,prompt:e.prompt,permissionMode:Sg.b$.DEFAULT,isBackground:!1,source:"sdk"})))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents}}class NB{constructor(e={}){this.options=e,this.states=new Map,this.runCounterBySession=new Map,this.dispatchQueueBySession=new Map,this.dispatchInProgress=new Set,this.releaseRequestedBySession=new Set}getState(e){return this.states.get(e)??{status:"idle"}}isBusy(e){return"idle"!==this.getState(e).status}startRun(e,t){const r=this.nextRunId(e);return this.enqueueEvent(e,{type:"startRun",runId:r,abort:t?.abort}),r}queueResume(e,t){this.enqueueEvent(e,{type:"queueResume",queuedResume:t.queuedResume,targetRunId:t.targetRunId,mergeQueuedResume:t.mergeQueuedResume})}finishRun(e,t){this.enqueueEvent(e,{type:"runFinished",runId:t})}clearQueuedResume(e){this.enqueueEvent(e,{type:"clearQueuedResume"})}abort(e){this.enqueueEvent(e,{type:"abort"})}release(e){this.enqueueEvent(e,{type:"release"})}nextRunId(e){const t=(this.runCounterBySession.get(e)??0)+1;return this.runCounterBySession.set(e,t),t}enqueueEvent(e,t){const r=this.dispatchQueueBySession.get(e)??[];r.push(t),this.dispatchQueueBySession.set(e,r),this.drainEventQueue(e)}drainEventQueue(e){if(this.dispatchInProgress.has(e))return;let t;this.dispatchInProgress.add(e);try{const r=this.dispatchQueueBySession.get(e);if(!r)return;for(;r.length>0;){const n=r.shift();if(n)try{this.processEvent(e,n)}catch(e){t??=e}}}finally{this.dispatchQueueBySession.delete(e),this.dispatchInProgress.delete(e)}if(t)throw t}processEvent(e,t){const r=this.getState(e),{nextState:n,effects:o}=function(e,t){switch(e.status){case"idle":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"running",runId:t.runId,abort:t.abort},effects:[]};case"queueResume":return void 0===t.targetRunId?{nextState:e,effects:[]}:{nextState:{status:"runningWithQueuedResume",runId:t.targetRunId,queuedResume:t.queuedResume},effects:[]};case"runFinished":case"clearQueuedResume":case"abort":case"release":return{nextState:e,effects:[]};default:throw new Error(`Unhandled idle-state event: ${String(t)}`)}}(e,t);case"running":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"running",runId:t.runId,abort:t.abort},effects:[{type:"abortActiveRun",abort:e.abort}]};case"queueResume":return{nextState:{status:"runningWithQueuedResume",runId:e.runId,abort:e.abort,queuedResume:t.queuedResume},effects:[]};case"runFinished":return t.runId!==e.runId?{nextState:e,effects:[]}:{nextState:{status:"idle"},effects:[]};case"clearQueuedResume":case"release":return{nextState:e,effects:[]};case"abort":return{nextState:{status:"idle"},effects:[{type:"abortActiveRun",abort:e.abort}]};default:throw new Error(`Unhandled running-state event: ${String(t)}`)}}(e,t);case"runningWithQueuedResume":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"runningWithQueuedResume",runId:t.runId,abort:t.abort,queuedResume:e.queuedResume},effects:[{type:"abortActiveRun",abort:e.abort}]};case"queueResume":return{nextState:{...e,queuedResume:t.mergeQueuedResume(e.queuedResume,t.queuedResume)},effects:[]};case"runFinished":return t.runId!==e.runId?{nextState:e,effects:[]}:{nextState:{status:"running",runId:e.runId,abort:e.abort},effects:[{type:"startQueuedRun",sourceRunId:e.runId,queuedResume:e.queuedResume}]};case"clearQueuedResume":return{nextState:{status:"running",runId:e.runId,abort:e.abort},effects:[]};case"abort":return{nextState:{status:"idle"},effects:[{type:"abortActiveRun",abort:e.abort}]};case"release":return{nextState:e,effects:[]};default:throw new Error(`Unhandled runningWithQueuedResume-state event: ${String(t)}`)}}(e,t);default:return{nextState:e,effects:[]}}}(r,t);this.states.set(e,n),this.options.onStateChange?.({sessionId:e,previousState:r,nextState:n});for(const t of o)switch(t.type){case"abortActiveRun":t.abort?.();break;case"startQueuedRun":this.options.onQueuedRunReady?.({sessionId:e,sourceRunId:t.sourceRunId,queuedResume:t.queuedResume});break;default:throw new Error(`Unhandled lifecycle manager effect: ${String(t)}`)}const s=this.getState(e);"release"===t.type&&"idle"!==s.status&&this.releaseRequestedBySession.add(e),"idle"!==s.status||"release"!==t.type&&!this.releaseRequestedBySession.has(e)||(this.states.delete(e),this.runCounterBySession.delete(e),this.releaseRequestedBySession.delete(e))}}function LB(e){return"string"==typeof e&&e.trim().length>0}function jB(e,t){return new fe.jn({command:t.command??"",workingDirectory:t.workingDirectory??"",error:e,isReadonly:!0})}function UB(e){return{execute:async(t,r)=>new FI.v3({result:{case:"permissionDenied",value:new FI.U7({path:r.path,error:e,isReadonly:!0})}})}}function BB(e){return{execute:async(t,r)=>new Ww.Pi({result:{case:"permissionDenied",value:new Ww.QG({path:r.path,clientVisibleError:e,isReadonly:!0})}})}}function WB(e){return{execute:async(t,r)=>new Mc.iz({result:{case:"permissionDenied",value:new Mc.HQ({error:`${e} Tool: ${r.name}`,isReadonly:!0})}})}}var HB=r("../agent-kv/dist/subagent-states.js");let qB;function zB(e){const t=process.env.CURSOR_DATA_DIR;if(t?.trim())return Eo(e);let r;try{r=(0,o.homedir)()}catch{r=void 0}return function(e){const t=e.cursorDataDir?.trim();return t?(0,s.join)(t,"projects",(0,_o.r_)(e.workspacePath)):void 0!==e.homeDir&&function(e){if(""===e.trim())return!1;try{return!!(0,Ro.statSync)(e).isDirectory()&&((0,Ro.accessSync)(e,Ro.constants.W_OK),!0)}catch{return!1}}(e.homeDir)?(0,s.join)(e.homeDir,".cursor","projects",(0,_o.r_)(e.workspacePath)):(0,s.join)(e.ensureFallbackRoot(e.tempDir),(0,_o.r_)(e.workspacePath))}({workspacePath:e,homeDir:r,tempDir:(0,o.tmpdir)(),ensureFallbackRoot:e=>(void 0===qB&&(qB=function(e){return(0,Ro.mkdtempSync)((0,s.join)(e,"cursor-transcripts-"))}(e)),qB)})}async function GB(e,t){const r=(0,s.dirname)(e);await(0,xo.mkdir)(r,{recursive:!0}),await(0,xo.writeFile)(e,t,"utf-8")}class VB{constructor(e){this.writeChain=Promise.resolve(),this.workspacePath=e.workspacePath,this.conversationId=e.conversationId,this.parentConversationId=e.parentConversationId,this.blobStore=e.blobStore,this.projectDir=zB(this.workspacePath);const t=this.parentConversationId?(e,t)=>{const r=NF({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,r)}:void 0;this.transcriptStore=new pN(this.projectDir,e.blobStore,GB,{writeText:!1,writeJsonl:!0,...t?{pathResolver:t}:{}}),this.nestedSubagentTranscriptStore=new pN(this.projectDir,e.blobStore,GB,{writeText:!1,writeJsonl:!0,pathResolver:(e,t)=>{const r=NF({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.conversationId});return(0,s.join)(this.projectDir,r)}})}enqueueWrite(e,t){const r=this.writeChain;return this.writeChain=r.then((async()=>{try{await e()}catch(e){CO.Jz.warn(`${t} ${e instanceof Error?e.message:String(e)}`)}})),this.writeChain}async writeFromState(e,t){return this.enqueueWrite((async()=>{await this.transcriptStore.writeFromStateFull(e,t,this.conversationId);const r=await(0,HB.Vn)(e,t,this.blobStore);for(const[t,n]of Object.entries(r))n?.conversationState&&await this.nestedSubagentTranscriptStore.writeFromStateFull(e,n.conversationState,t)}),"[LocalTranscriptWriter] Failed to write transcript:")}async writeTurnEndedFromState(e,t,r){return this.enqueueWrite((async()=>{await this.transcriptStore.writeFromStateFull(e,t,this.conversationId,{turnEnded:r})}),"[LocalTranscriptWriter] Failed to write turn-ended transcript:")}waitForPendingWrites(){return this.writeChain}getTranscriptPath(){if(this.parentConversationId){const e=NF({conversationId:this.conversationId,ext:"jsonl",kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,e)}return function(e,t){const r=NF({conversationId:t,ext:"jsonl",kind:"primary"});return(0,s.join)(zB(e),r)}(this.workspacePath,this.conversationId)}getProjectDir(){return this.projectDir}}const KB=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,JB="User aborted/interrupted manually.";class ZB{constructor(e){this.sessions=new Map,this.backgroundRuns=new Map,this.activeForegroundExecutions=new Map,this.backgroundPromises=new Set,this.pendingReleaseSessions=new Set,this.childParentIds=new Map,this.parentChildIds=new Map,this.queuedChildCompletions=new Map,this.childCompletionWaiters=new Map,this.childLineageRequestIds=new Map,this.untrackedParentRequestIds=new Map,this.agentClient=e.agentClient,this.getResources=e.getResources,this.mcpTools=e.mcpTools??[],this.workspacePath=e.workspacePath,this.parentConversationId=e.parentConversationId;const t=e.rootRequestId?.trim();this.rootLineageRequestId=void 0!==t&&t.length>0?t:(0,ye.C)(),this.headers=e.headers,this.endlessRetries=e.endlessRetries,this.onSessionCreated=e.onSessionCreated,this.onInteractionUpdate=e.onInteractionUpdate,this.onSessionCompleted=e.onSessionCompleted,this.onSessionReleased=e.onSessionReleased,this.onSubagentTokenDelta=e.onSubagentTokenDelta,this.lifecycleStore=new NB}async createOrResumeSession(e,t){if(t.forkAgentId)throw new Error("forkAgentId is not supported in local subagents.");const r=t.resumeAgentId;if(r&&function(e){if(!KB.test(e))throw new Error(`Invalid resumeAgentId format: ${e}`)}(r),r&&!t.prompt)return r;if(r&&LB(t.prompt)&&this.isBackgroundRunBusy(r))throw new Error("Sub-agent is currently running. You may send the follow-up message when it has completed.");if(r&&this.sessions.get(r))return r;const n=r??(0,ye.C)(),o=function(e){const t=new oe.We,r=(0,EO.sh)(e),n=new EO.pH(new oe.ve,t);return n.setMetadata("agentId",r.agentId),n.setMetadata("latestRootBlobId",r.latestRootBlobId),n.setMetadata("name",r.name),n.setMetadata("createdAt",r.createdAt),n.setMetadata("mode",r.mode),n.setMetadata("isRunEverything",r.isRunEverything),n.setMetadata("lastUsedModel",r.lastUsedModel),n.setMetadata("lastDebugServerPort",r.lastDebugServerPort),n.setMetadata("currentPlanUri",r.currentPlanUri),n.setMetadata("subagentInfo",r.subagentInfo),n.setMetadata("blobEncryptionKey",r.blobEncryptionKey),n}(n),s=new VB({workspacePath:this.workspacePath,conversationId:n,parentConversationId:this.parentConversationId,blobStore:o.getBlobStore()});return this.sessions.set(n,{agentStore:o,transcriptWriter:s,toolCallId:t.toolCallId}),this.onSessionCreated?.({agentId:n,toolCallId:t.toolCallId,subagentType:t.subagentType,parentAgentId:t.parentConversationId}),n}async runSession(e,t,r,n){if(this.isAwaitBackgroundMode(r))return this.awaitBackgroundRun(r.resumeAgentId,e.signal);const o=this.sessions.get(t);if(!o)return{status:"error",error:`Subagent session not found: ${t}`};if(r.runInBackground){const[n,s]=e.withDetached().withCancel();return this.registerBackgroundRun(t,this.executeSubagent(n,t,r,o),r.parentConversationId,s),{status:"background",backgroundReason:Sg.qL.AGENT_REQUEST,toolCallCount:0}}const[s,i]=e.withDetached().withCancel();let a=!1;const c=()=>{a||i()};e.signal.addEventListener("abort",c,{once:!0}),e.signal.aborted&&c();let l=()=>{};const u=new Promise((e=>{l=e})),d={requestBackground:()=>!!a||!s.signal.aborted&&(a=!0,e.signal.removeEventListener("abort",c),l(),!0)};this.activeForegroundExecutions.set(r.toolCallId,d),this.activeForegroundExecutions.set(t,d);try{const e=this.executeSubagent(s,t,r,o),n=await Promise.race([e.then((e=>({handedOff:!1,outcome:e}))),u.then((()=>({handedOff:!0})))]);return n.handedOff?(this.registerBackgroundRun(t,e,r.parentConversationId,i),{status:"background",backgroundReason:Sg.qL.USER_REQUEST,toolCallCount:0}):(this.onSessionCompleted?.(t,n.outcome),n.outcome)}finally{this.clearForegroundExecution(r.toolCallId,d),this.clearForegroundExecution(t,d),a||e.signal.removeEventListener("abort",c)}}forceBackgroundByToolCallId(e){const t=this.activeForegroundExecutions.get(e);return t?.requestBackground()?new io.a3({status:io.jh.ACCEPTED}):new io.a3({status:io.jh.NOT_FOUND})}clearForegroundExecution(e,t){this.activeForegroundExecutions.get(e)===t&&this.activeForegroundExecutions.delete(e)}releaseSession(e){this.lifecycleStore.release(e),this.isBackgroundRunBusy(e)?this.pendingReleaseSessions.add(e):this.cleanupSession(e)}async awaitBackgroundWorkers(){for(;this.backgroundPromises.size>0;)await Promise.allSettled([...this.backgroundPromises])}async waitForBackgroundCompletions(e,t){return this.collectAvailableChildCompletions(e,t)}isBackgroundRunBusy(e){return this.lifecycleStore.isBusy(e)||this.backgroundRuns.has(e)}registerBackgroundRun(e,t,r,n){this.registerParentChildLink(e,r);const o=this.lifecycleStore.startRun(e,{abort:n}),s=t.catch((e=>({status:"error",error:e instanceof Error?e.message:String(e)}))),i={runId:o,promise:s};this.backgroundRuns.set(e,i),this.backgroundPromises.add(s),s.then((t=>{this.lifecycleStore.finishRun(e,o);const r=this.backgroundRuns.get(e);if(r?.runId===o){this.backgroundRuns.delete(e),this.enqueueChildCompletion(e,o,t),this.maybeCleanupReleasedSession(e);try{this.onSessionCompleted?.(e,t)}catch(t){CO.Jz.error("[LocalSubagentHostAdapter] onSessionCompleted threw after background run",{agentId:e,error:t instanceof Error?t.message:String(t)})}}return t})).finally((()=>this.backgroundPromises.delete(s)))}maybeCleanupReleasedSession(e){this.pendingReleaseSessions.has(e)&&!this.isBackgroundRunBusy(e)&&this.cleanupSession(e)}cleanupSession(e){this.pendingReleaseSessions.delete(e);const t=this.sessions.get(e);if(!t)return;const r=this.parentChildIds.get(e);if(r)for(const e of r)this.childParentIds.delete(e);this.removeParentChildLink(e),this.parentChildIds.delete(e),this.queuedChildCompletions.delete(e),this.childCompletionWaiters.delete(e),t.transcriptWriter.waitForPendingWrites().catch((()=>{})),this.sessions.delete(e),this.onSessionReleased?.(e)}async executeSubagent(e,t,r,n){return r.continuationConfig?this.executeSubagentWithContinuation(e,t,r,n,r.continuationConfig):this.executeSubagentOnce(e,t,r,n)}async executeSubagentWithContinuation(e,t,r,n,o){const s=o.maxLoops>0?o.maxLoops:Number.POSITIVE_INFINITY;let i=await this.runContinuationLoop(e,t,r,n,o,s);if(!o.collectBackgroundChildren||"completed"!==i.status)return i;for(let a=0;a<500;a++){if(e.signal.aborted)return{status:"error",error:"Subagent was aborted by the user"};let a;try{a=await this.collectAvailableChildCompletions(t,e.signal)}catch{return{status:"error",error:"Subagent was aborted by the user"}}if(0===a.length)return i;const c=this.buildChildrenCompletedMessage(a,o.childrenCompletedMessageTemplate);if(i=await this.runContinuationLoop(e,t,new io.Pw({...r,prompt:c,resumeAgentId:t,runInBackground:!1}),n,o,s),"completed"!==i.status)return i}return i}async runContinuationLoop(e,t,r,n,o,s){let i,a,c=0;for(let l=0;l0?(c=0,i=void 0):(c+=1,i=c>=o.idleThreshold?`DONE_${(0,ye.C)().replace(/-/g,"").slice(0,8)}`:void 0)}return a??{status:"error",error:"Subagent continuation exited unexpectedly"}}computeContinuationNudge(e,t,r){return t>=e.idleThreshold&&void 0!==r?e.escapeMessageTemplate.replace("{idle_count}",String(t)).replace("{escape_token}",r):e.nudgeMessage}lineageForChildRun(e){this.childLineageRequestIds.has(e.agentId)||this.childLineageRequestIds.set(e.agentId,(0,ye.C)());const t=e.parentConversationId?.trim()??"",r=e.toolCallId.trim();return{parentRequestId:""===t||t===this.parentConversationId?this.rootLineageRequestId:this.childLineageRequestIds.get(t)??this.untrackedParentRequestId(t),rootParentRequestId:this.rootLineageRequestId,...r.length>0?{parentAgentToolCallId:r}:{}}}untrackedParentRequestId(e){let t=this.untrackedParentRequestIds.get(e);return void 0===t&&(t=(0,ye.C)(),this.untrackedParentRequestIds.set(e,t)),t}async executeSubagentOnce(e,t,r,n){const o=this.lineageForChildRun({agentId:t,parentConversationId:r.parentConversationId,toolCallId:r.toolCallId});let s,i=0;const a=new c.QFf({action:{case:"userMessageAction",value:new c.Vtf({userMessage:new c.RGk({text:r.prompt})})}}),l=new c.Gmx({modelId:r.modelId,displayModelId:r.modelId,displayName:r.modelId});void 0!==r.credentials.case&&(l.credentials=r.credentials);const u=new _O,d={sendUpdate:async(e,r)=>{"tokenDelta"===r.message.case&&this.onSubagentTokenDelta?.(t,r.message.value.tokens),"toolCallStarted"!==r.message.case&&"toolCallCompleted"!==r.message.case&&"partialToolCall"!==r.message.case||this.onInteractionUpdate?.(t,r),"toolCallCompleted"===r.message.case&&i++,"textDelta"===r.message.case&&(s=(s??"")+r.message.value.text)},query:async(e,t)=>function(e){const t=e.query.case;switch(t){case"webSearchRequestQuery":return pr(e.id,"Web search is not supported in local subagent");case"webFetchRequestQuery":return mr(e.id,"Web fetch is not supported in local subagent");case"switchModeRequestQuery":return yr(e.id,"Subagent mode switches are not supported in local subagent");case"askQuestionInteractionQuery":{const t=new er.tz({result:{case:"rejected",value:new er.ox({reason:"Interactive questions are not supported in local subagent mode"})}});return gr(e.id,t)}default:throw new Error(`Unhandled interaction query type in local subagent: ${String(t)}`)}}(t)},h={handleCheckpoint:async(e,t)=>{await n.agentStore.handleCheckpoint(e,t),n.transcriptWriter.writeFromState(e,t)},getLatestCheckpoint:()=>n.agentStore.getLatestCheckpoint()};try{const c=r.rootParentConversationId?.trim(),p=r.parentConversationId?.trim(),f=void 0!==c&&""!==c?c:void 0!==p&&""!==p?p:t,m=await this.getResources({agentId:t,parentAgentId:r.parentConversationId}),g=r.readonly?new X(m,function(e){const t=[K(GT,UB(e.errorMessage)),K(VT,BB(e.errorMessage)),K(ro,WB(e.errorMessage))];return e.wrapShell&&t.push(K(WT,function(e){return{execute:async(t,r)=>new fe.W4({result:{case:"permissionDenied",value:jB(e,r)}})}}(e.errorMessage)),K(re,function(e){return{async*execute(t,r){yield new fe.FI({event:{case:"permissionDenied",value:jB(e,r)}})}}}(e.errorMessage)),K(kA,function(e){return{execute:async(t,r)=>new Fo.Lt({result:{case:"permissionDenied",value:jB(e,r)}})}}(e.errorMessage))),e.includeWriteBackgroundShellStdin&&t.push(K(_A,function(e){return{execute:async(t,r)=>new Fo.nt({result:{case:"error",value:new Fo.Gv({error:e})}})}}(e.errorMessage))),t}({errorMessage:"This operation is not allowed in readonly mode. The subagent was launched with readonly: true, which restricts shell, write, delete, and MCP operations.",wrapShell:!0,includeWriteBackgroundShellStdin:!0})):m;return await this.agentClient.run(e,n.agentStore.getConversationStateStructure(),a,l,d,g,n.agentStore.getBlobStore(),u,h,[...this.mcpTools],{conversationGroupId:f,conversationId:t,...n.transcriptWriter.parentConversationId?{transcriptParentConversationId:n.transcriptWriter.parentConversationId}:{},subagentTypeName:r.subagentType||void 0,...o,headers:PO(n.agentStore.getMetadata("blobEncryptionKey"),this.headers),endlessRetries:this.endlessRetries,subagentModelOverrides:[]}),await n.transcriptWriter.writeTurnEndedFromState(e,n.agentStore.getConversationStateStructure(),e.signal.aborted?{status:"aborted",error:JB}:{status:"success"}),{status:"completed",finalMessage:s,toolCallCount:i}}catch(r){const o=r instanceof Error?r.message:String(r);return CO.Jz.error("[LocalSubagentHostAdapter] Subagent session failed",{agentId:t,error:o}),await n.transcriptWriter.writeTurnEndedFromState(e,n.agentStore.getLatestCheckpoint()??n.agentStore.getConversationStateStructure(),this.getTurnEndedFromError(e,o)),e.signal.aborted?{status:"aborted",error:JB}:{status:"error",error:o}}}getTurnEndedFromError(e,t){return e.signal.aborted?{status:"aborted",error:JB}:{status:"error",error:t}}isAwaitBackgroundMode(e){if(!Boolean(e.resumeAgentId&&!LB(e.prompt)&&e.readonly&&!0!==e.runInBackground))return!1;if(0===(e.parentConversationId??"").trim().length)throw new Error(`Missing parentConversationId for subagent await/status check (subagentId: ${e.resumeAgentId})`);return!0}async awaitBackgroundRun(e,t){const r=this.backgroundRuns.get(e);return r?this.awaitBackgroundEntry(r,t):this.isBackgroundRunBusy(e)?this.awaitBusyLifecycleRun(e,t):{status:"error",error:`No background subagent found for id: ${e}`}}async awaitBackgroundRunBounded(e,t){const r=t.agentId;if(e.signal.aborted)return new io.zJ({result:{case:"stillRunning",value:new io.L5({agentId:r})}});const n=this.backgroundRuns.get(r);if(void 0===n){const e=this.takeQueuedChildCompletion(r);return void 0!==e?"success"===e.status?new io.zJ({result:{case:"complete",value:new io.bE({agentId:r,finalMessage:e.finalMessage,toolCallCount:e.toolCallCount??0})}}):new io.zJ({result:{case:"error",value:new io.Y({agentId:r,error:e.finalMessage||"Subagent was aborted"})}}):this.isBackgroundRunBusy(r)?new io.zJ({result:{case:"stillRunning",value:new io.L5({agentId:r})}}):new io.zJ({result:{case:"notFound",value:new io.Hq({agentId:r})}})}const[o,s]=e.withTimeoutAndCancel(Math.max(0,t.timeoutMs)),i=await new Promise((e=>{const t=()=>e(void 0);o.signal.addEventListener("abort",t,{once:!0}),n.promise.then(e).finally((()=>{o.signal.removeEventListener("abort",t),s()}))}));return void 0===i||"background"===i.status||e.signal.aborted?new io.zJ({result:{case:"stillRunning",value:new io.L5({agentId:r})}}):(this.takeQueuedChildCompletion(r,n.runId),"completed"===i.status?new io.zJ({result:{case:"complete",value:new io.bE({agentId:r,finalMessage:i.finalMessage,toolCallCount:i.toolCallCount??0})}}):new io.zJ({result:{case:"error",value:new io.Y({agentId:r,error:i.error??"Subagent was aborted"})}}))}takeQueuedChildCompletion(e,t){for(const[r,n]of this.queuedChildCompletions){const o=n.findIndex((r=>r.agentId===e&&(void 0===t||r.runId===t)));if(-1===o)continue;const[s]=n.splice(o,1);return 0===n.length&&this.queuedChildCompletions.delete(r),s}}async awaitBusyLifecycleRun(e,t){for(;this.isBackgroundRunBusy(e);){if(t.aborted)return{status:"error",error:"Await timed out while task is still running"};const r=this.backgroundRuns.get(e);if(r)return this.awaitBackgroundEntry(r,t);await new Promise((e=>setTimeout(e,50)))}return{status:"completed",toolCallCount:0}}async awaitBackgroundEntry(e,t){if(t.aborted)return{status:"error",error:"Await timed out while task is still running"};const r={status:"error",error:"Await timed out while task is still running"};return new Promise((n=>{const o=()=>{n(r)};t.addEventListener("abort",o,{once:!0}),e.promise.then(n).finally((()=>t.removeEventListener("abort",o)))}))}registerParentChildLink(e,t){const r=t?.trim();if(!r||r===e||!this.sessions.has(r)&&r!==this.parentConversationId)return;const n=this.childParentIds.get(e);if(n===r)return;n&&(this.parentChildIds.get(n)?.delete(e),0===(this.parentChildIds.get(n)?.size??0)&&this.parentChildIds.delete(n)),this.childParentIds.set(e,r);const o=this.parentChildIds.get(r)??new Set;o.add(e),this.parentChildIds.set(r,o)}removeParentChildLink(e){const t=this.childParentIds.get(e);if(!t)return;this.childParentIds.delete(e);const r=this.parentChildIds.get(t);r?.delete(e),0===(r?.size??0)&&this.parentChildIds.delete(t)}enqueueChildCompletion(e,t,r){const n=this.childParentIds.get(e);if(!n)return;const o=this.queuedChildCompletions.get(n)??[];o.push({agentId:e,runId:t,status:"completed"===r.status?"success":"error"===r.status?"error":"aborted",finalMessage:"completed"===r.status?r.finalMessage??"":"error"===r.status?r.error:"Subagent was aborted by the user",..."completed"===r.status&&void 0!==r.toolCallCount?{toolCallCount:r.toolCallCount}:{}}),this.queuedChildCompletions.set(n,o),this.removeParentChildLink(e);const s=this.childCompletionWaiters.get(n);if(s){this.childCompletionWaiters.delete(n);for(const e of s)e()}}async collectAvailableChildCompletions(e,t){const r=this.drainChildCompletions(e);return r.length>0?r:this.hasPendingChildSubagents(e)?(await this.waitForChildCompletion(e,t),this.drainChildCompletions(e)):[]}hasPendingChildSubagents(e){return(this.parentChildIds.get(e)?.size??0)>0}drainChildCompletions(e){const t=this.queuedChildCompletions.get(e)??[];return this.queuedChildCompletions.delete(e),t}async waitForChildCompletion(e,t){if(t.aborted)throw new Error("aborted");await new Promise(((r,n)=>{const o=this.childCompletionWaiters.get(e)??new Set,s=()=>{a(),r()},i=()=>{a(),n(new Error("aborted"))},a=()=>{o.delete(s),0===o.size&&this.childCompletionWaiters.delete(e),t.removeEventListener("abort",i)};o.add(s),this.childCompletionWaiters.set(e,o),t.addEventListener("abort",i,{once:!0})}))}buildChildrenCompletedMessage(e,t){const r=e.map((e=>{const t="success"===e.status?"SUCCESS":"FAILED";return`## Agent ${e.agentId} -- ${t}\n\n${e.finalMessage}`})).join("\n\n---\n\n");return t.replace("{summaries}",r)}}var XB=r("../proto/dist/generated/agent/v1/agent_service_connect.js"),QB=r("../proto/dist/generated/agent/v1/requested_model_pb.js"),YB=r("../proto/dist/generated/agent/v1/selected_context_pb.js"),eW=r("./src/agent/analytics.ts"),tW=r("../proto/dist/generated/agent/v1/todo_tool_pb.js");const rW={[Ng.w3.UNSPECIFIED]:"unspecified",[Ng.w3.LEFT]:"left",[Ng.w3.RIGHT]:"right",[Ng.w3.MIDDLE]:"middle",[Ng.w3.BACK]:"back",[Ng.w3.FORWARD]:"forward"},nW={[Ng.Dh.UNSPECIFIED]:"unspecified",[Ng.Dh.UP]:"up",[Ng.Dh.DOWN]:"down",[Ng.Dh.LEFT]:"left",[Ng.Dh.RIGHT]:"right"},oW={[Ng.EB.UNSPECIFIED]:"unspecified",[Ng.EB.TAP]:"tap",[Ng.EB.DOWN]:"down",[Ng.EB.UP]:"up"};function sW(e){return rW[e]??"unspecified"}function iW(e){return void 0===e?void 0:{x:e.x,y:e.y}}function aW({result:e}){switch(e.case){case"success":return{status:"success",value:{actionCount:e.value.actionCount,durationMs:e.value.durationMs,settleMs:e.value.settleMs,screenshotPath:e.value.screenshotPath,cursorPosition:iW(e.value.cursorPosition),log:e.value.log}};case"error":return{status:"error",error:{message:e.value.error,actionCount:e.value.actionCount,durationMs:e.value.durationMs,screenshotPath:e.value.screenshotPath,log:e.value.log}};default:return}}function cW(e,t){switch(e.message.case){case"textDelta":return{type:"text-delta",text:e.message.value.text};case"thinkingDelta":return{type:"thinking-delta",text:e.message.value.text};case"thinkingCompleted":return{type:"thinking-completed",thinkingDurationMs:e.message.value.thinkingDurationMs};case"userMessageAppended":return{type:"user-message-appended",userMessage:{type:"user_message",session_id:t,text:e.message.value.userMessage?.text??""}};case"tokenDelta":return{type:"token-delta",tokens:e.message.value.tokens};case"summary":return{type:"summary",summary:e.message.value.summary};case"summaryStarted":return{type:"summary-started"};case"summaryCompleted":{const{failed:t,fallback:r}=e.message.value;return{type:"summary-completed",...t?{failed:t}:{},...r?{fallback:r}:{}}}case"shellOutputDelta":return{type:"shell-output-delta",event:e.message.value.event.case?{case:e.message.value.event.case,value:e.message.value.event.value?.toJson?.()??e.message.value.event.value}:{}};case"toolCallStarted":return lW("tool-call-started",e.message.value);case"partialToolCall":return lW("partial-tool-call",e.message.value);case"toolCallCompleted":return lW("tool-call-completed",e.message.value);case"heartbeat":return null;case"turnEnded":{const t=e.message.value;return{type:"turn-ended",...(void 0!==t.inputTokens||void 0!==t.outputTokens||void 0!==t.cacheReadTokens||void 0!==t.cacheWriteTokens)&&{usage:{inputTokens:Number(t.inputTokens??BigInt(0)),outputTokens:Number(t.outputTokens??BigInt(0)),cacheReadTokens:Number(t.cacheReadTokens??BigInt(0)),cacheWriteTokens:Number(t.cacheWriteTokens??BigInt(0)),...t.reasoningTokens&&{reasoningTokens:Number(t.reasoningTokens)}}}}}case"modelCallCompleted":{const t=e.message.value;return{type:"model-call-completed",modelCallId:t.modelCallId,usage:{inputTokens:Number(t.inputTokens),outputTokens:Number(t.outputTokens),cacheReadTokens:Number(t.cacheReadTokens),cacheWriteTokens:Number(t.cacheWriteTokens),...t.reasoningTokens&&{reasoningTokens:Number(t.reasoningTokens)}}}}case"toolCallDelta":{const r=e.message.value,n=r.toolCallDelta;if("taskToolCallDelta"!==n?.delta.case)return null;const o=n.delta.value.interactionUpdate;if(void 0===o)return null;const s=cW(o,t);return null!==s&&function(e){switch(e.type){case"text-delta":case"thinking-delta":case"thinking-completed":case"tool-call-started":case"tool-call-completed":case"partial-tool-call":case"step-started":case"step-completed":case"tool-requests-listed":return!0;default:return!1}}(s)?{type:"tool-call-delta",callId:r.callId,modelCallId:r.modelCallId,taskUpdate:s}:null}case"stepStarted":return{type:"step-started",stepId:Number(e.message.value.stepId)};case"toolRequestsListed":return{type:"tool-requests-listed",callCount:e.message.value.callCount};case"stepCompleted":return{type:"step-completed",stepId:Number(e.message.value.stepId),stepDurationMs:Number(e.message.value.stepDurationMs)};case"postRequestPrompt":case"activeBranchChange":case"feedbackRequest":case"responseComparison":case"contextInjectionState":case"routedModel":case"grokBotNudge":case"thinkingNote":case"voiceCallUtterance":case void 0:return null;default:return e.message,null}}function lW(e,t){const r=function(e){if(!e?.tool)return null;switch(e.tool.case){case"shellToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"shell",args:{command:t.command,...t.workingDirectory?{workingDirectory:t.workingDirectory}:{},...t.timeout?{timeout:t.timeout}:{}},...r?{result:mW(r)}:{}}:null}case"deleteToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"delete",args:{path:t.path},...r?{result:gW(r)}:{}}:null}case"globToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"glob",args:{globPattern:t.globPattern,...t.targetDirectory?{targetDirectory:t.targetDirectory}:{}},...r?{result:wW(r)}:{}}:null}case"grepToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"grep",args:{pattern:t.pattern,...t.path?{path:t.path}:{},...t.glob?{glob:t.glob}:{},...t.outputMode?{outputMode:t.outputMode}:{},...t.contextBefore?{contextBefore:t.contextBefore}:{},...t.contextAfter?{contextAfter:t.contextAfter}:{},...t.context?{context:t.context}:{},...t.caseInsensitive?{caseInsensitive:t.caseInsensitive}:{},...t.type?{type:t.type}:{},...t.headLimit?{headLimit:t.headLimit}:{},...void 0!==t.offset?{offset:t.offset}:{},...t.multiline?{multiline:t.multiline}:{},...t.sort?{sort:t.sort}:{},...t.sortAscending?{sortAscending:t.sortAscending}:{}},...r?{result:yW(r)}:{}}:null}case"readToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"read",args:{path:t.path},...r?{result:bW(r)}:{}}:null}case"editToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"edit",args:{path:t.path},...r?{result:SW(r)}:{}}:null}case"lsToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"ls",args:{path:t.path,...t.ignore&&t.ignore.length>0?{ignore:t.ignore}:{}},...r?{result:kW(r)}:{}}:null}case"readLintsToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"readLints",args:{paths:t.paths},...r?{result:CW(r)}:{}}:null}case"mcpToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"mcp",args:{...t.providerIdentifier?{providerIdentifier:t.providerIdentifier}:{},...t.toolName?{toolName:t.toolName}:{},...t.args?{args:Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()])))}:{}},...r?{result:EW(r)}:{}}:null}case"generateImageToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"generateImage",args:{description:t.description,...t.filePath?{filePath:t.filePath}:{}},...r?{result:PW(r)}:{}}:null}case"recordScreenToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"recordScreen",args:{mode:RW(t.mode)},...r?{result:IW(r)}:{}}:null}case"semSearchToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"semSearch",args:{query:t.query,...t.targetDirectories&&t.targetDirectories.length>0?{targetDirectories:t.targetDirectories}:{},...t.explanation?{explanation:t.explanation}:{}},...r?{result:xW(r)}:{}}:null}case"createPlanToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"createPlan",args:{plan:t.plan},...r?{result:TW(r)}:{}}:null}case"updateTodosToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"updateTodos",args:{todos:t.todos.map((e=>({content:e.content,status:$W(e.status)})))},...r?{result:AW(r)}:{}}:null}case"fetchToolCall":case"switchModeToolCall":return null;case"computerUseToolCall":return function({args:e,result:t}){return e?{type:"computerUse",args:{actions:e.actions.flatMap((e=>function({action:e}){switch(e.case){case"mouseMove":return{type:"mouseMove",coordinate:iW(e.value.coordinate)};case"click":return{type:"click",coordinate:iW(e.value.coordinate),button:sW(e.value.button),count:e.value.count,modifierKeys:e.value.modifierKeys};case"mouseDown":case"mouseUp":return{type:e.case,button:sW(e.value.button)};case"drag":return{type:"drag",path:e.value.path.map((e=>({x:e.x,y:e.y}))),button:sW(e.value.button),modifierKeys:e.value.modifierKeys};case"scroll":return{type:"scroll",coordinate:iW(e.value.coordinate),direction:nW[e.value.direction]??"unspecified",amount:e.value.amount,modifierKeys:e.value.modifierKeys};case"type":return{type:"type",text:e.value.text};case"key":return{type:"key",key:e.value.key,holdDurationMs:e.value.holdDurationMs,stroke:oW[e.value.stroke]??"unspecified"};case"wait":return{type:"wait",durationMs:e.value.durationMs};case"screenshot":case"cursorPosition":return{type:e.case};default:return}}(e)??[])),description:e.description},result:t?aW(t):void 0}:null}(e.tool.value);case"readTodosToolCall":case"webSearchToolCall":case"listMcpResourcesToolCall":case"readMcpResourceToolCall":return null;case"taskToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"task",args:uW(t),...r?{result:pW(r)}:{}}:null}case"applyAgentDiffToolCall":case"askQuestionToolCall":case"writeShellStdinToolCall":case"reflectToolCall":case"setupVmEnvironmentToolCall":case"replaceEnvToolCall":case"startGrindExecutionToolCall":case"startGrindPlanningToolCall":case"truncatedToolCall":case"webFetchToolCall":case"reportBugfixResultsToolCall":case"aiAttributionToolCall":case"prManagementToolCall":case"editPrLabelsToolCall":case"fetchCloudAgentDataToolCall":case"mcpAuthToolCall":case"connectScmToolCall":case"searchConversationsToolCall":case"awaitToolCall":case"blameByFilePathToolCall":case"getMcpToolsToolCall":case"reportBugToolCall":case"setActiveBranchToolCall":case"communicateUpdateToolCall":case"sendFinalSummaryToolCall":case"updateOriginPrCodeTourToolCall":case"getOriginPrCodeTourToolCall":case"recordCiInvestigationFindingsToolCall":case"sendMessageToolCall":case"sendToUserToolCall":case"createGoalToolCall":case"updateGoalToolCall":case"getAgentStatusToolCall":case"sendToAgentToolCall":case"readAgentTranscriptToolCall":case"createAgentToolCall":case"createProjectToolCall":case"startProjectUpdatesToolCall":case"stopProjectUpdatesToolCall":case"manageAccessToolCall":case"stopAgentToolCall":case"listTrackedTasksToolCall":case"createTrackedTasksToolCall":case"updateTrackedTasksToolCall":case"deleteTrackedTasksToolCall":case"updateTrackedTaskStatusesToolCall":case"updateTrackedTaskTagsToolCall":case"writeCanvasToolCall":case"readCanvasToolCall":case"generateVideoToolCall":case"xSearchToolCall":case"executeToolCall":case void 0:return null;default:return e.tool}}(t.toolCall);return r?{type:e,callId:t.callId,toolCall:r,modelCallId:t.modelCallId}:null}function uW(e){return{description:e.description??"",prompt:e.prompt??"",...e.subagentType?{subagentType:dW(e.subagentType)}:{},...e.model?{model:e.model}:{},...e.resume?{resume:e.resume}:{},...e.agentId?{agentId:e.agentId}:{},...e.attachments&&e.attachments.length>0?{attachments:e.attachments}:{},...void 0!==e.mode?{mode:hW(e.mode)}:{},...e.respondingToMessageIds&&e.respondingToMessageIds.length>0?{respondingToMessageIds:e.respondingToMessageIds}:{}}}function dW(e){const t=e.type.case;return t?"custom"===t?{kind:t,name:e.type.value.name}:{kind:t}:{kind:"unspecified"}}function hW(e){switch(e){case Sg.FL.AGENT:return"agent";case Sg.FL.PLAN:return"plan";default:return"unspecified"}}function pW(e){if(e.result?.case)switch(e.result.case){case"success":{const t=e.result.value;return{status:"success",value:{...t.conversationSteps&&t.conversationSteps.length>0?{conversationSteps:t.conversationSteps.map((e=>e.toJson?.()??e))}:{},...t.agentId?{agentId:t.agentId}:{},isBackground:t.isBackground??!1,...void 0!==t.durationMs?{durationMs:Number(t.durationMs)}:{},...t.resultSuffix?{resultSuffix:t.resultSuffix}:{},backgroundReason:fW(t.backgroundReason),...t.transcriptPath?{transcriptPath:t.transcriptPath}:{}}}}case"error":return{status:"error",error:{message:e.result.value.error??"Task failed"}};default:return}}function fW(e){switch(e){case Sg.qL.AGENT_REQUEST:return"agentRequest";case Sg.qL.USER_REQUEST:return"userRequest";case Sg.qL.QUEUED_FOLLOW_UP:return"queuedFollowUp";default:return"unspecified"}}function mW(e){if(e.result?.case)switch(e.result.case){case"success":case"failure":{const t=e.result.value;return{status:"success",value:{exitCode:t.exitCode??0,signal:t.signal??"",stdout:t.stdout??"",stderr:t.stderr??"",executionTime:t.executionTime??0}}}case"timeout":return{status:"error",error:{message:`Command timed out after ${e.result.value.timeoutMs}ms`,command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};case"rejected":return{status:"error",error:{message:e.result.value.reason??"Command rejected",command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};case"spawnError":return{status:"error",error:{message:e.result.value.error??"Failed to spawn command",command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};default:return}}function gW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{fileSize:Number(e.result.value.fileSize??0)}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.value.clientVisibleError??e.result.case,path:e.result.value.path}}}function wW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{files:e.result.value.files??[],totalFiles:e.result.value.totalFiles??0,clientTruncated:e.result.value.clientTruncated??!1,ripgrepTruncated:e.result.value.ripgrepTruncated??!1}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case}}}function yW(e){if(e.result?.case){if("success"===e.result.case){const t=e.result.value,r={};if(t.workspaceResults)for(const[e,n]of Object.entries(t.workspaceResults))r[e]=vW(n);return{status:"success",value:{...Object.keys(r).length>0?{workspaceResults:r}:{},...t.activeEditorResult?{activeEditorResult:vW(t.activeEditorResult)}:{}}}}return{status:"error",error:{message:e.result.value.error??e.result.case}}}}function vW(e){if(e?.result?.case)switch(e.result.case){case"content":return{type:"content",output:{matches:e.result.value.matches?.map((e=>({file:e.file,...void 0!==e.lineNumber?{lineNumber:e.lineNumber}:{},line:e.line,...e.beforeContext?{beforeContext:e.beforeContext}:{},...e.afterContext?{afterContext:e.afterContext}:{}})))??[],totalMatches:e.result.value.totalMatches??0}};case"files":return{type:"files",output:{files:e.result.value.files??[],count:e.result.value.count??0}};case"count":return{type:"count",output:{counts:e.result.value.counts?.map((e=>({file:e.file,count:e.count})))??[],total:e.result.value.total??0}};default:return}}function bW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{content:"content"===e.result.value.output.case?e.result.value.output.value:"",totalLines:e.result.value.totalLines??0,fileSize:Number(e.result.value.fileSize??0)}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case,path:e.result.value.path}}}function SW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{...void 0!==e.result.value.linesAdded?{linesAdded:e.result.value.linesAdded}:{},...void 0!==e.result.value.linesRemoved?{linesRemoved:e.result.value.linesRemoved}:{},...e.result.value.diffString?{diffString:e.result.value.diffString}:{}}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case,path:e.result.value.path}}}function kW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{directoryTreeRoot:_W(e.result.value.directoryTreeRoot)}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function _W(e){if(e)return{absPath:e.absPath??"",childrenDirs:e.childrenDirs?.map(_W)??[],childrenFiles:e.childrenFiles?.map((e=>({name:e.name})))??[],childrenWereProcessed:e.childrenWereProcessed??!1,fullSubtreeExtensionCounts:e.fullSubtreeExtensionCounts??{},numFiles:e.numFiles??0}}function CW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{fileDiagnostics:e.result.value.fileDiagnostics?.map((e=>({path:e.path,diagnostics:e.diagnostics?.map((e=>({severity:MW(e.severity),...e.range?{range:{...e.range.start?{start:{line:e.range.start.line,character:e.range.start.character}}:{},...e.range.end?{end:{line:e.range.end.line,character:e.range.end.character}}:{}}}:{},message:e.message,source:e.source,code:e.code})))??[],diagnosticsCount:e.diagnosticsCount??0})))??[],totalFiles:e.result.value.totalFiles??0,totalDiagnostics:e.result.value.totalDiagnostics??0}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function EW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{content:e.result.value.content?.map((e=>{const t={};return"text"===e.content?.case?t.text={text:e.content.value.text}:"image"===e.content?.case&&(t.image={data:e.content.value.data,...e.content.value.mimeType?{mimeType:e.content.value.mimeType}:{}}),t}))??[],isError:e.result.value.isError??!1}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case}}}function xW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{results:e.result.value.results??""}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function PW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{filePath:e.result.value.filePath??""}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function RW(e){switch(e){case T$.$u.START_RECORDING:return"START_RECORDING";case T$.$u.SAVE_RECORDING:return"SAVE_RECORDING";case T$.$u.DISCARD_RECORDING:return"DISCARD_RECORDING";default:throw new Error(`Unknown RecordingMode: ${e}`)}}function IW(e){if(e.result?.case)switch(e.result.case){case"startSuccess":return{status:"success",value:{wasPriorRecordingCancelled:e.result.value.wasPriorRecordingCancelled??!1}};case"saveSuccess":return{status:"success",value:{path:e.result.value.path??"",recordingDurationMs:Number(e.result.value.recordingDurationMs??0)}};case"discardSuccess":return{status:"success",value:{}};case"failure":return{status:"error",error:{message:e.result.value.error??"Unknown error"}};default:return}}function TW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function AW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{todos:e.result.value.todos?.map((e=>({content:e.content,status:$W(e.status)})))??[],totalCount:e.result.value.totalCount??0}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function $W(e){switch(e){case tW.Vj.UNSPECIFIED:case tW.Vj.PENDING:return"pending";case tW.Vj.IN_PROGRESS:return"inProgress";case tW.Vj.COMPLETED:return"completed";case tW.Vj.CANCELLED:return"cancelled";default:return"pending"}}function MW(e){switch(e){case NA.h_.UNSPECIFIED:case NA.h_.ERROR:return"error";case NA.h_.WARNING:return"warning";case NA.h_.INFORMATION:return"information";case NA.h_.HINT:return"hint";default:return"error"}}const DW={type:"object",properties:{},additionalProperties:!0};function OW(e){const t={};for(const[r,n]of Object.entries(e))t[r]=n;return t}function FW(e){return"text"===e.type?new Mc._Z({content:{case:"text",value:new Mc.zN({text:e.text})}}):new Mc._Z({content:{case:"image",value:new Mc.do({data:n.Buffer.from(e.data,"base64"),mimeType:e.mimeType??""})}})}function NW(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var LW=r("./src/agent/errors.ts");const jW="Shell is not available when local.fs is set: the agent's files live in a FileSystem, and a shell would run on the host disk. Use Read, Grep, Glob, LS, and the edit tools instead.";function UW(e){return{async execute(){throw new Error(e)}}}function BW(e){var t;e.register(WT,UW(jW)),e.register(re,(t=jW,{async*execute(){throw new Error(t)}})),e.register(kA,UW(jW)),e.register(RA,UW(jW)),e.register(_A,UW(jW)),e.register(HT,UW(jW)),e.register(oA,UW("ReadLints is not available when local.fs is set: lint diagnostics come from a host language service, not the FileSystem.")),e.register(JT,UW("Git is not available when local.fs is set: the agent's files live in a FileSystem, not a host git checkout."))}var WW=r("./src/agent/filesystem/executors.ts"),HW=r("./src/agent/filesystem/compose.ts"),qW=r("./src/agent/filesystem/trees.ts"),zW=r("./src/agent/filesystem/walk.ts");const GW="/tmp",VW=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.txt$/i;function KW(e){const{write:t,hostProjectDir:r}=e;return{async execute(e,n,o){const s=function(e){if(t=e.writePath,!/^([/\\]|[A-Za-z]:[/\\])/.test(t))return;var t;const r=function(e){if(void 0===e.hostProjectDir||""===e.hostProjectDir)return;const t=(0,zW.eI)(e.hostProjectDir),r=(0,zW.eI)(e.writePath);return"/"!==t&&(0,zW.hJ)({path:r,prefix:t})?r.slice(t.length):void 0}(e),n=void 0===r?(0,zW.eI)(e.writePath):(0,zW.eI)(`${GW}/${r}`);if(!(0,zW.hJ)({path:n,prefix:GW}))return;const o=a().posix.basename(n),s=a().posix.join(GW,Dc);return a().posix.dirname(n)===s&&VW.test(o)?a().posix.join(GW,o):n}({writePath:n.path,hostProjectDir:r});if(void 0===s||s===n.path)return await t.execute(e,n,o);const i=n.clone();i.path=s;const c=await t.execute(e,i,o);return"success"===c.result.case&&(c.result.value.path=s),c}}}class JW{constructor(e,t="/"){this.fs=e,this.listeners=new Set,this.workspace=(0,zW.eI)(t)}getAllCursorRules(e){return this.rules??=async function(e,t){const[r,n]=await Promise.all([ZW(e,s.posix.join(t,".cursor/rules")),XW(e,s.posix.join(t,"AGENTS.md"))]);return void 0===n?r:[...r,n]}(this.fs,this.workspace),this.rules}reload(e){this.rules=void 0;for(const e of this.listeners)e()}onDidChangeRules(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}dispose(){this.listeners.clear()}}async function ZW(e,t){const r=[];try{for await(const n of e.list(t))"directory"!==n.kind&&n.path.endsWith(".mdc")&&r.push(n.path)}catch{return[]}return(await(0,Nr.PH)(r,(async t=>{const r=await QW(e,t),n=void 0===r?null:rn(r);if(null!==n)return fg({path:t,body:n.body,frontmatter:n.frontmatter,rawFrontmatter:n.rawFrontmatter})}),{max:8})).filter((e=>void 0!==e))}async function XW(e,t){const r=await QW(e,t);if(void 0!==r)return fg({path:t,body:Qr({content:r,filename:"AGENTS.md"}),frontmatter:{alwaysApply:!0}})}async function QW(e,t){try{const r=await e.read(t);return"string"==typeof r?r:(new TextDecoder).decode(r)}catch{return}}const YW={getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}},eH={async exec(){throw new Error("git is not available in a FileSystem session")}},tH={isIgnoredByAny:async()=>!1,isGitIgnored:async()=>!1,isCursorIgnored:async()=>!1,isRepoBlocked:async()=>!1,listCursorIgnoreFilesByRoot:async()=>[],getCursorIgnoreMapping:async()=>({}),getShellSandboxIgnoreMapping:async()=>({}),getGitIgnoreMapping:async()=>({}),getRepoBlockExcludeGlobs:async()=>[]};function rH(e){return{cursorRulesService:!0===e.includeProjectRules?new JW(e.fs,e.workspace):YW,getAgentSkills:async()=>[],subagentsService:e.subagentsService??new _g,gitExecutor:eH,ignoreService:tH,requestContextIsWorkingDirHomeDir:!1,reportProcessWorkingDirectory:!1}}function nH(e,t){const r=t.workspace??"/",n=(0,WW.c9)(e,{workspace:r});return{localResourceProviderOptions:{overrideReadExecutor:n.read,overrideWriteExecutor:KW({write:n.write,hostProjectDir:t.hostProjectDir}),overrideGrepExecutor:n.grep,overrideLsExecutor:n.ls,overrideDeleteExecutor:n.delete,suppressDefaultShellExecutor:!0,...rH({...t.settings,fs:e,workspace:r})},reportedWorkspacePath:r,reportedProjectFolder:GW,excludeHooks:!0,excludeProjectMcp:!0}}var oH=r("./src/agent/executor-common.ts");class sH{constructor(){this.countsByMode=new Map,this.failureKindsByMode=new Map,this.record=e=>{let t=this.countsByMode.get(e.mode);switch(void 0===t&&(t={mode:e.mode,checked_calls:0,outside_limit_calls:0,settings_unavailable_calls:0,unknown_server_calls:0},this.countsByMode.set(e.mode,t)),e.outcome){case"within_limit":return void(t.checked_calls+=1);case"outside_limit":return t.checked_calls+=1,void(t.outside_limit_calls+=1);case"settings_unavailable":{t.settings_unavailable_calls+=1;const r=e.settingsFailure;if(void 0===r)return;let n=this.failureKindsByMode.get(e.mode);return void 0===n&&(n=new Map,this.failureKindsByMode.set(e.mode,n)),void n.set(r,(n.get(r)??0)+1)}case"unknown_server":return void(t.unknown_server_calls+=1);default:return e.outcome}}}take(){const e=[...this.countsByMode.values()].map((e=>{const t=function(e){let t;for(const[r,n]of e??[])(void 0===t||n>t.calls)&&(t={kind:r,calls:n});return t?.kind}(this.failureKindsByMode.get(e.mode));return void 0===t?e:{...e,settings_unavailable_kind:t}}));return this.countsByMode.clear(),this.failureKindsByMode.clear(),e}}class iH{constructor(e=e=>{console.warn(e)}){this.write=e,this.printed=new Set,this.report=e=>{if(!this.printed.has(e.serverName)){this.printed.add(e.serverName);try{this.write(function(e){return`[cursor-sdk] ${e.refusal}`}(e))}catch{}}}}}const aH=new class{constructor(e=e=>{console.warn(e)}){this.write=e,this.printed=new Set,this.report=e=>{const t=JSON.stringify([e.serverName,(r=e.allowlist,JSON.stringify([r.list,r.name,r.reason,r.allowedServers??null,r.blockedServers??null]))]);var r;if(!this.printed.has(t)){this.printed.size>=1e3&&this.printed.clear(),this.printed.add(t);try{this.write(function(e){return`[cursor-sdk] MCP server "${e.serverName}" is under ${function(e){return`${e.name}, which applies because ${e.reason}.${r=e.allowedServers,void 0===r?"":0===r.length?" Allowed servers: none.":zC("Allowed servers",r)}${t=e.blockedServers,void 0===t||0===t.length?"":zC("Blocked",t)}`;var t,r}(e.allowlist)}`}(e))}catch{}}}}};var cH=r("./src/agent/native/vendored-tree-sitter.ts"),lH=r("./src/agent/platform-package-locator.ts"),uH=r("./src/agent/sdk-config.ts"),dH=r("../../node_modules/.pnpm/@statsig+js-client@3.31.0/node_modules/@statsig/js-client/src/index.js"),hH=r("./src/agent/utils/logger.ts");const pH={checkFeatureGate:()=>!1,getDynamicConfigValue:({defaultValue:e})=>e},fH=new Map;async function mH(e){try{const t=await async function(e){const t=await(0,oH.dC)(e,oH.EV);if(!t)return;const r=oH.EV.endsWith("/")?oH.EV.slice(0,-1):oH.EV,n=await fetch(`${r}/aiserver.v1.AnalyticsService/BootstrapStatsig`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json","x-cursor-client-type":"sdk","x-cursor-client-version":(0,oH.tF)(),"x-ghost-mode":(0,oH.U)(e)},body:JSON.stringify({})});if(!n.ok)return void hH.v.log(`Failed to bootstrap SDK Statsig: ${n.status} ${n.statusText}`);const o=await n.json();return gH(o)&&"string"==typeof o.config&&o.config.length>0?o.config:void 0}(e);if(!t)return pH;const r=new dH.StatsigClient("client-Bm4HJ0aDjXHQVsoACMREyLNxm5p6zzuzhO50MgtoT5D",function(e){try{const r=JSON.parse(e);if(gH(r)&&"object"==typeof(t=r.user)&&null!==t&&!Array.isArray(t))return{...r.user,custom:{...r.user.custom,clientType:"sdk",clientVersion:(0,oH.tF)()}}}catch(e){hH.v.log(`Failed to parse SDK Statsig bootstrap user: ${e instanceof Error?e.message:String(e)}`)}var t;return{custom:{clientType:"sdk",clientVersion:(0,oH.tF)()}}}(t),{disableLogging:!0,disableStorage:!0,networkConfig:{preventAllNetworkTraffic:!0}});return r.dataAdapter.setData(t),r.initializeSync(),{checkFeatureGate:(e,t)=>{try{return r.checkGate(e,t)}catch{return!1}},getDynamicConfigValue({configName:e,paramName:t,defaultValue:n}){try{return r.getDynamicConfig(e).get(t,n)}catch{return n}}}}catch(e){return hH.v.log(`Failed to initialize SDK Statsig: ${e instanceof Error?e.message:String(e)}`),pH}}function gH(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function wH(e){let t;return e?.then((e=>{t=e}),(()=>{})),()=>t?.checkFeatureGate("grok_bot_mcp_app_payment_token_filter",{disableExposureLog:!0})??!1}var yH=r("./src/agent/tools-option.ts");class vH{async requestApproval(){return{approved:!0}}}function bH(e,t){if(!function(e){return void 0!==e&&Object.keys(e).length>0}(t))return;const r=e.resources.base;if(!(r instanceof cD))throw new LW.j1("SDK custom tools require the default local workspace resource provider.",{isRetryable:!1});const n=r.getMcpExecutionPolicyDeps(),o=r.get(ro),s=function(e,t){return{async execute(r,n,o){const s=n.toolName||function(e){const t=`${Vn}-`;return e.startsWith(t)?e.slice(t.length):e}(n.name),i=e[s];if(void 0===i)return new Mc.iz({result:{case:"error",value:new Mc.Nh({error:`Unknown custom tool: ${s}`})}});try{return function(e){const t=function(e){return"object"==typeof(t=e)&&null!==t&&!Array.isArray(t)&&"content"in t&&Array.isArray(t.content)?{content:e.content,isError:e.isError,structuredContent:e.structuredContent}:"string"==typeof e?{content:[{type:"text",text:e}]}:{content:[{type:"text",text:JSON.stringify(e)}],structuredContent:NW(e)?e:void 0};var t}(e),r=void 0!==t.structuredContent?ve.Struct.fromJson(t.structuredContent):void 0;return new Mc.iz({result:{case:"success",value:new Mc.QW({content:t.content.map(FW),isError:t.isError??!1,structuredContent:r})}})}(await i.execute(function(e){return Object.fromEntries(Object.entries(e.args).map((([e,t])=>[e,t.toJson()])))}(n),{toolCallId:n.toolCallId||void 0,...void 0===t||""===t?{}:{sessionId:t}}))}catch(e){return new Mc.iz({result:{case:"error",value:new Mc.Nh({error:e instanceof Error?e.message:String(e)})}})}}}}(t,e.state.sessionId),i=new vH;e.resources.base.register(ro,{async execute(e,t,r){if(function(e){return e.providerIdentifier===Vn}(t)){const o=await RT(e,t,{...n,pendingDecisionProvider:i,toolDef:{source:"internal"}});return void 0!==o?o:s.execute(e,t,r)}return o.execute(e,t,r)}})}const SH=new Set(["127.0.0.1","localhost","[::1]"]);function kH(e){if(void 0===e)return{};const t=e.resourceProviderOptions;return{...void 0!==t?{localResourceProviderOptions:t}:{},...void 0!==e.reportedWorkspacePath?{reportedWorkspacePath:e.reportedWorkspacePath}:{}}}function _H(){const e=process.env.CURSOR_SDK_MOCK_PROMPT_TIME;if(void 0===e||""===e)return;const t=new Date(e);return Number.isNaN(t.getTime())?void 0:t}const CH={warn(){},error(){}},EH={log(){}};class xH{async requestApproval(e){return{approved:!1,reason:`Local SDK runs cannot request interactive approval for ${PH(e)}. Keep the action within the configured sandbox policy or Smart Auto Review's auto-approval boundary, or re-run without sandboxing/autoReview enabled.`}}}function PH(e){switch(e.type){case Bw.Shell:return"this shell command";case Bw.Mcp:return"this MCP tool call";case Bw.Write:return"this file edit";case Bw.Delete:return"this file deletion";default:return"this operation"}}function RH(e){return void 0!==e&&"insecure_none"!==e.type}async function IH(e,t){const r="string"==typeof e||void 0===e?{workingDirectory:e,apiKey:t}:e,i=(0,b.q6)().with(d._O,EH),a=CB(r.settingSources),l=void 0===r.hostMcpBridgeUrls?void 0:r.hostMcpBridgeUrls.filter((e=>{let t;try{t=new URL(e)}catch{t=void 0}const r=void 0!==t&&"http:"===t.protocol&&""===t.username&&""===t.password&&SH.has(t.hostname);return r||console.warn(`[cursor-sdk] ignoring local.hostMcpBridgeUrls entry ${e}: not an http URL on 127.0.0.1, localhost or [::1]`),r}));!function(e){if(void 0!==e&&(!Number.isFinite(e)||e<=0))throw new Error(`Workspace scan cache TTL must be a positive number of milliseconds, got ${e}`);ba=e}((0,uH.Mu)()),/:\/\/(localhost|127\.0\.0\.1)/.test(oH.EV)&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0");const u=performance.now();let h=0;if(r.apiKey){const e=performance.now();await Promise.all([(0,oH.ly)(r.apiKey),(0,oH.mU)(r.apiKey)]),h=performance.now()-e}const p=r.workingDirectory||process.cwd();(0,cH.configureVendoredTreeSitterWorkspaceDir)(p);for(const e of r.dirs??[])(0,cH.configureVendoredTreeSitterWorkspaceDir)(e);const f=(0,_o.Rv)((0,o.homedir)(),p),m={hostProjectDir:f,settings:{includeProjectRules:EB(a,"project"),subagentsService:new FB(r.customSubagents??[])}};let g;const w="win32"===process.platform?"rg.exe":"rg",y=process.env.CURSOR_RIPGREP_PATH;g=y&&(0,s.isAbsolute)(y)?y:(0,lH.hQ)({binaryName:w,excludedWorkspaceDir:p}),g||(g=(0,No.xS)()),g&&(0,No.J)(g);let v,S,k,_={getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getAdminCommandDenylist:async()=>({rules:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}};if(r.apiKey)try{const e=(0,oH.qN)(r.apiKey,r.teamId);v=e.transport,S=e.getAccessToken;const t=(0,be.createClient)(wj.I,v),n=function(e){let t=fH.get(e);return t||(t=mH(e),fH.set(e,t),t.then((r=>{r===pH&&fH.get(e)===t&&fH.delete(e)}),(()=>{fH.get(e)===t&&fH.delete(e)}))),t}(r.apiKey);k=n;const o={getDefaultNetworkAllowlist:async()=>(await n).getDynamicConfigValue({configName:"sandbox_default_network_allowlist",paramName:"allowlist",defaultValue:[]})};_=new vO(new gO(t,{supportsHostMcpBridgeExemption:!0}),o,{...void 0===l?{}:{hostMcpBridgeUrls:l},mcpAdminToolLimitSurvivesFailedRead:!0,isMcpAccessNetworkAllowlistEnabled:async()=>(await n).checkFeatureGate("mcp_access_network_allowlist"),isMcpSettingsOverhaulEnabled:async e=>(await n).checkFeatureGate("mcp_settings_overhaul",e),isWin32UserExtensionStdioUnsandboxEnabled:async e=>(await n).checkFeatureGate("mcp_user_extension_stdio_unsandboxed_win32",e),isAdminCommandDenylistEnforcementKilled:async()=>(await n).checkFeatureGate("admin_command_denylist_enforcement_killswitch")})}catch(e){hH.v.log(`Failed to initialize authenticated dashboard services: ${e instanceof Error?e.message:String(e)}`)}const C=performance.now(),E=r.apiKey?await(0,No.tv)(`${(0,o.homedir)()}/.cursor/sandbox.json`,(0,o.homedir)()):void 0,x=void 0!==r.apiKey?await async function(e){const{cwd:t,perUserSandboxPolicy:r,sandboxOptions:n}=e;if(!1===n?.enabled)return{defaultSandboxPolicy:{type:"insecure_none"},defaultSandboxPolicySources:void 0};const o=RH(r)?r:!0===n?.enabled?function(e,t={}){return{type:e,...t}}("workspace_readwrite",{networkPolicy:(0,No.Po)()}):void 0;if(void 0===o)return{defaultSandboxPolicy:{type:"insecure_none"},defaultSandboxPolicySources:void 0};if(function(e){const t="win32"===process.platform?"cursorsandbox.exe":"cursorsandbox",r=(0,lH.hQ)({binaryName:t,excludedWorkspaceDir:e});r&&(0,No.St)({sandboxBinaryPath:r})}(t),!(0,No.K3)(void 0,{ctx:e.initializationCtx}))throw new LW.j1("Local SDK sandboxing was requested, but sandboxing is not supported in this environment. Disable local.sandboxOptions.enabled or remove ~/.cursor/sandbox.json to run without sandboxing.",{isRetryable:!1});const s={};s.perUser=o;const{policy:i}=await(0,No.resolveSandboxPolicyForWorkspace)(t,s);return{defaultSandboxPolicy:i,defaultSandboxPolicySources:s}}({cwd:p,perUserSandboxPolicy:E,sandboxOptions:r.sandboxOptions,initializationCtx:i}):void 0,P=performance.now()-C,R=x?.defaultSandboxPolicy,I=x?.defaultSandboxPolicySources,T=RH(R),A=performance.now(),$=(()=>{const e=[],t=new Set;for(const n of[p,...r.dirs??[]]){const r=(0,s.resolve)(n);t.has(r)||(t.add(r),e.push(n))}return e.length>1?e:void 0})(),M={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1},O=await async function(e){const{workingDirectory:t,projectDir:r}=e,n=function(e,t){const r=[],n=new Set;for(const o of[e,...t??[]]){const e=(0,s.resolve)(o);n.has(e)||(n.add(e),r.push(o))}return r}(t,e.dirs),o=n.length>1?n:void 0,i=CB(e.settingSources),a=e.teamSettingsService??{getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getAdminCommandDenylist:async()=>({rules:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}},c=e.defaultSandboxPolicy??{type:"insecure_none"},l=e.getSandboxSupported??(()=>(0,No.K3)(c,{ctx:e.initializationCtx})),u=e.getSandboxEnabled??(()=>"insecure_none"!==c.type&&l()),d=new xy,h=new Rc(d,a,n),p=new MB,f=new DB,m=e.getSmartModeClassifierAutoModeEnabled?.(),g=new $B(m?"allowlist":e.approvalMode??"unrestricted",c,a,e.respectAdminControls??!1),w=e.pendingDecisionProvider,y={executeIndexedGrep:void 0},v=()=>!0,b=EB(i,"plugins"),S=e.importThirdPartyPlugins??!1,k=e.mcpMetaToolEnabled??!0,_=void 0!==e.mcpServers&&Object.keys(e.mcpServers).length>0,C=void 0!==e.customSubagents&&e.customSubagents.length>0,E=_||EB(i,"project")||EB(i,"user")||b,x=EB(i,"project")||EB(i,"user")||EB(i,"mdm"),P=EB(i,"team"),R=P&&void 0!==e.dashboardTransport,I=EB(i,"project")||EB(i,"user")||P||R||b,T={teamSettingsService:a,initializationCtx:e.initializationCtx,importThirdPartyPlugins:S,ignoreApprovals:!0,includeProjectMcp:EB(i,"project"),includeUserMcp:EB(i,"user"),includePluginMcp:b,isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled,restMcpCursorAuthTokenSupplier:e.restMcpCursorAuthTokenSupplier},A=s=>TB({workingDirectory:t,...void 0!==o?{workspaceRoots:o}:{},adapters:{...s.includeMcp?{mcp:ZO({...T,inlineMcpServers:e.mcpServers})}:{},...b?{pluginBootstrap:oB({importThirdPartyPlugins:S,dashboardTransport:e.dashboardTransport})}:{},...x?{hooks:gj({includeProjectHooks:EB(i,"project"),includeUserHooks:EB(i,"user"),includeEnterpriseHooks:EB(i,"mdm"),useCommandHookStdinTransport:e.useCommandHookStdinTransport})}:{},...I?{localExtensibility:vj({includeProjectExtensibility:EB(i,"project"),includeUserExtensibility:EB(i,"user"),includeManagedSkills:R,includeTeamExtensibility:P,includePluginExtensibility:b,teamSettingsService:a,getThirdPartyExtensibilityEnabled:v,dashboardTransport:e.dashboardTransport,importThirdPartyPlugins:S})}:{},resourceFactory:fB({attributionConfigProvider:EB(i,"user")?{get(){try{const{readFileSync:r}=process.getBuiltinModule("node:fs"),{join:j}=process.getBuiltinModule("node:path"),{homedir:h}=process.getBuiltinModule("node:os"),x=process.env.XDG_CONFIG_HOME,d=process.env.CURSOR_CONFIG_DIR||(x&&process.platform!=="darwin"&&process.platform!=="win32"?j(x,"cursor"):j(h(),".cursor"));return JSON.parse(r(j(d,"cli-config.json"),"utf8"))}catch{return}}}:void 0,ignoreService:h,grepProvider:y,workspacePaths:n,diagnosticsProvider:p,repositoryProvider:f,projectDir:r??t,shellManager:void 0,defaultSandboxPolicy:c,defaultSandboxPolicySources:e.defaultSandboxPolicySources,getSandboxEnabled:u,getSandboxSupported:l,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:e.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:e.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:e.getMockPromptTime,getPowershellUtf8Options:e.getPowershellUtf8Options,mcpFileOutputThresholdBytes:void 0,mcpMetaToolEnabled:k,createMcpStateAccessor:(e,t)=>new OB(new aM(e),void 0===t?.onMcpAllowlistInUse&&void 0===t?.onMcpServerBlockedByAllowlist?void 0:{mcpLease:e,onMcpAllowlistInUse:t.onMcpAllowlistInUse,onMcpServerBlockedByAllowlist:t.onMcpServerBlockedByAllowlist}),createSessionMcpLease:(t,r)=>ZO({...T,includeProjectMcp:T.includeProjectMcp&&!0!==t.options.excludeProjectMcp,inlineMcpServers:r??e.mcpServers}).createLease({workspaceState:t.workspaceState,services:t.workspaceServices,policy:t.policy}),createSessionDependencies:r=>{const n=w??new AB;return{pendingDecisionStore:n,fileChangeTracker:new qw(t),permissionsService:new o_(h,n,g,a,t,e.respectAdminControls??!1,{enforceMcpAdminToolLimits:e.isMcpAdminToolLimitEnforced,onMcpAdminToolLimitCheck:r.options.onMcpAdminToolLimitCheck})}}}),resourceWrappers:x?[{wrapResources(e){const t=e.workspaceServices.hooksRuntime;if(!0===e.options.excludeHooks||"object"!=typeof(r=t)||null===r||!("hooksConfigLease"in r)||!("createSessionRuntime"in r)||"function"!=typeof r.createSessionRuntime||!function(e){return"object"==typeof e&&null!==e&&"get"in e&&"function"==typeof e.get&&"entries"in e&&"function"==typeof e.entries}(e.resources))return e.resources;var r;const n=t.createSessionRuntime({sessionState:e.sessionState,metadata:e.metadata});return new fj(new aj(e.resources,n.hookExecutor,(()=>function(e,t){const r=uj(t,dj,"conversationId","conversation_id")??e.sessionId??"";return{conversation_id:r,generation_id:uj(t,dj,"generationId","generation_id")??r,model:uj(t,dj,"model")??"unknown",...mF({modelId:uj(t,dj,"modelId","model_id"),modelParams:uj(t,pj,"modelParams","model_params")})}}(e.sessionState,e.metadata)),e.workspaceServices.mcpLease,void 0,void 0,t.hooksConfigLease),n)}}]:[],...C?{workspaceServicesContributors:[{contributeServices:t=>{const r=new FB(e.customSubagents??[]),n=t.services.subagentsService;return{subagentsService:void 0===n?r:new Ag([r,n])}}}]}:{}}});if(!E)return A({includeMcp:!1});try{return await A({includeMcp:!0})}catch(e){return CO.Jz.warn("[default-local-workspace-runtime] Failed to initialize MCP-enabled runtime, retrying without MCP:",{error:e,workingDirectory:t,projectDir:r,enablePlugins:b,importThirdPartyPlugins:S}),A({includeMcp:!1})}}({workingDirectory:p,...void 0!==$?{dirs:$}:{},projectDir:f,teamSettingsService:_,initializationCtx:i,dashboardTransport:v,settingSources:r.settingSources,mcpServers:r.mcpServers,customSubagents:r.customSubagents,defaultSandboxPolicy:R,defaultSandboxPolicySources:I,approvalMode:T?"allowlist":void 0,pendingDecisionProvider:T||!0===r.autoReview?new xH:void 0,getNetworkAllowlistInfo:T?()=>async function(e,t,r){const[n,o]=await Promise.all([e.getDefaultNetworkAllowlist(),e.getNetworkAccessControls()]),s=[...o.allowlist],i=`${t}/.cursor/sandbox.json`,a=await(0,No.tv)(i,t);if(a&&"insecure_none"!==a.type&&a.networkPolicy?.allow&&s.push(...a.networkPolicy.allow),"1"!==process.env[Yv.K4]&&r){const e=await(0,No.tv)(`${r}/.cursor/sandbox.json`,r);e&&"insecure_none"!==e.type&&e.networkPolicy?.allow&&s.push(...e.networkPolicy.allow)}const c=[...new Set(s)];return{hasDefaults:n.available&&n.allowlist.length>0,explicitEntries:c}}(_,(0,o.homedir)(),p):void 0,getSmartModeClassifierAutoModeEnabled:()=>!0===r.autoReview,devForceNextSmartModeClassifierBlockToken:r.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:_H,getPowershellUtf8Options:async()=>{if(void 0===k)return M;try{const e=await k;return{powershellUtf8Console:e.checkFeatureGate("shell_exec_powershell_utf8_console"),powershellUtf8ChildEnv:e.checkFeatureGate("shell_exec_powershell_utf8_child_env")}}catch{return M}},isLinkSharedPaymentTokenLogRedactionEnabled:wH(k),restMcpCursorAuthTokenSupplier:S,respectAdminControls:void 0!==r.apiKey,isMcpAdminToolLimitEnforced:void 0===k?void 0:(F=k,async()=>{try{return(await F).checkFeatureGate("sdk_local_mcp_admin_tool_limits",{disableExposureLog:!0})}catch{return!1}}),useCommandHookStdinTransport:!0});var F;const N=performance.now()-A;let L,j;return(0,eW.ou)(r.apiKey,{runtime:"local",ensure_ghost_mode_ms:Math.round(h),bootstrap_statsig_ms:0,create_workspace_runtime_ms:Math.round(N),load_sandbox_policy_ms:Math.round(P),total_ms:Math.round(performance.now()-u)}),{run:async(e,t,o)=>(0,CO.ni)(CH,(async()=>{const s=(0,D.VI)((0,b.q6)().withName("sdk.run").with(d._O,EH)),[i,a]=s.ctx.withCancel(),l=t.sessionId??(0,ye.C)(),u=t.mcpServersOverride,h=void 0===(f=t.customTools)?[]:Object.entries(f).map((([e,t])=>({clientKey:Vn,providerIdentifier:Vn,toolName:e,name:`${Vn}-${e}`,description:t.description??"",inputSchema:t.inputSchema??DW,...void 0===t.outputSchema?{}:{outputSchema:t.outputSchema},...void 0===t.annotations?{}:{annotations:OW(t.annotations)},source:"internal"})));var f;let g;const w={...m,workspace:t.fileSystemWorkspace},y=void 0===t.fileSystem?void 0:(_=await async function(e,t){return"function"==typeof e?await e(t):e}(t.fileSystem,{agentId:l,sessionId:l}),C=_,(0,HW.VL)({"/":C,[GW]:(0,qW.Om)()})),v=void 0===t.onMcpAdminToolLimitCounts?void 0:new sH,S=()=>{for(const e of v?.take()??[])try{t.onMcpAdminToolLimitCounts?.(e)}catch{}},k=new iH;var _,C;g=await O.createSessionRuntime({sessionId:l,mcpServersOverride:u,extraMcpTools:h,onMcpAdminToolLimitCheck:v?.record,onMcpAllowlistInUse:aH.report,onMcpServerBlockedByAllowlist:k.report,...void 0===y?kH(t.sessionResources):nH(y,w)});const E=new Map;try{const s=g.resources.wrapped;bH(g,t.customTools),void 0!==y&&BW(g.resources.base);const d=t.blobStore??new oe.ve;let f=t.initialState??new c.Y9z({});const m=void 0!==t.model?new QB.G4({modelId:t.model.id,...!0===t.model.maxMode?{maxMode:!0}:{},parameters:(t.model.params??[]).map((e=>new QB.SR({id:e.id,value:e.value})))}):void 0,b=!0===e.summarize?void 0:e.images,_=Array.isArray(b)?b.map((e=>{const t=(0,ye.C)(),r=new Uint8Array(n.Buffer.from(e.data,"base64")),o=(0,oH.v8)(r);return new YB.d({uuid:t,...o?{mimeType:o}:{},dataOrBlobId:{case:"data",value:r}})})):[],C=_.length>0?new YB.xv({selectedImages:_}):void 0,R=function(e){switch(e){case"agent":return c.xyI.AGENT;case"plan":return c.xyI.PLAN;default:return}}(t.mode),I=e.resume===!0?new c.QFf({action:{case:"resumeAction",value:new c.qKo}}):!0===e.summarize?new c.QFf({action:{case:"summarizeAction",value:new c.Scs}}):new c.QFf({action:{case:"userMessageAction",value:new c.Vtf({userMessage:new c.RGk({text:e.text,selectedContext:C,...void 0!==R?{mode:R}:{}})})}}),T={sendUpdate:async(e,t)=>{const r=cW(t,l);null!==r&&await o.sendUpdate(r)},query:async(e,r)=>await async function(e,t){if("mcpAuthRequestQuery"===e.query.case&&void 0!==t){const r=await async function(e,t,r){let n;try{n=await e({serverName:r.args?.serverIdentifier??"",toolCallId:r.args?.toolCallId??""})}catch{return Cr(t,"The MCP sign-in request failed.")}if(void 0!==n)switch(n.kind){case"approved":return _r(t);case"rejected":return Cr(t,n.reason);default:return n}}(t,e.id,e.query.value);if(void 0!==r)return r}return function(e){switch(e.query.case){case"webSearchRequestQuery":return hr(e.id);case"webFetchRequestQuery":return fr(e.id);case"switchModeRequestQuery":return wr(e.id);case"askQuestionInteractionQuery":return gr(e.id,new er.tz({result:{case:"rejected",value:new er.ox({reason:"Interactive questions are not supported in local SDK runs"})}}));case"createPlanRequestQuery":return vr(e.id,new tr.bK({result:{case:"success",value:new tr.Jo},planUri:""}));case"setupVmEnvironmentArgs":return br(e.id,new or.r$({result:{case:"success",value:new or.JH}}));case"replaceEnvArgs":return Sr(e.id,new nr.dV({result:{case:"failure",value:new nr.uq({errorMessage:"Environment replacement is not supported in local SDK runs",setupLogs:""})}}));case"prManagementRequestQuery":return kr(e.id,new rr.HL({result:{case:"error",value:new rr.K$({error:"PR management is only available in cloud agents"})}}));case"mcpAuthRequestQuery":return Cr(e.id,"MCP authentication is not supported in local SDK runs");case"connectScmRequestQuery":return Er(e.id,"Connecting GitHub is not supported in local SDK runs");case"generateImageRequestQuery":return xr(e.id,e.query.value.args?.description);case void 0:throw new LW.j1("Missing interaction query type",{isRetryable:!1});default:throw e.query,new LW.j1("Unhandled interaction query type",{isRetryable:!1})}}(e)}(r,t.onMcpAuthRequest)};if(L!==t.apiKey||!j){await Promise.all([(0,oH.ly)(t.apiKey),(0,oH.mU)(t.apiKey)]);const e=(0,oH.KU)(t.apiKey,r.teamId),n=So((0,be.createClient)(XB.N,e),{injectTraceHeaders:!0});j=new qn(n),L=t.apiKey}const A=(0,oH.Vh)(j,(()=>{const e=(0,oH.KU)(t.apiKey,r.teamId),n=So((0,be.createClient)(XB.N,e),{injectTraceHeaders:!0}),o=new qn(n);return j=o,L=t.apiKey,o})),$=function(e){return{...void 0!==e.allowedTools?{[yH.$$]:e.allowedTools.join(",")}:{},...void 0!==e.disallowedTools&&e.disallowedTools.length>0?{[yH.VJ]:e.disallowedTools.join(",")}:{}}}(t),M=new ZB({agentClient:A,rootRequestId:t.requestId,getResources:async({agentId:e})=>{let r=E.get(e);return r||(r=await O.createSessionRuntime({sessionId:e,mcpServersOverride:u,extraMcpTools:h,onMcpAdminToolLimitCheck:v?.record,onMcpAllowlistInUse:aH.report,onMcpServerBlockedByAllowlist:k.report,...void 0===y?kH(t.subagentInherit):nH(y,w)}),bH(r,t.customTools),void 0!==y&&BW(r.resources.base),r.resources.base.register(co,D),r.resources.base.register(lo,F),r.resources.base.register(uo,N),E.set(e,r)),r.resources.wrapped},mcpTools:h,workspacePath:p,parentConversationId:l,...(void 0!==t.subagentInherit||void 0!==y)&&Object.keys($).length>0?{headers:$}:{},onSessionReleased:e=>{const t=E.get(e);t&&(t.dispose(),E.delete(e))}}),D=function(e){const t=new Map,r=new Map;async function n(t,r,n){let o;try{o=await e.createOrResumeSession(t,r);const s=await e.runSession(t,o,r,{execId:n?.execId});return"error"===s.status?new io.vS({result:{case:"error",value:new io.od({agentId:o,error:s.error})}}):"aborted"===s.status?new io.vS({result:{case:"error",value:new io.od({agentId:o,error:s.error??"Subagent was aborted by the user"})}}):"background"===s.status?new io.vS({result:{case:"success",value:new io.HJ({agentId:o,finalMessage:s.finalMessage,toolCallCount:s.toolCallCount??0,backgroundReason:s.backgroundReason,transcriptPath:s.transcriptPath})}}):new io.vS({result:{case:"success",value:new io.HJ({agentId:o,finalMessage:s.finalMessage,toolCallCount:s.toolCallCount??0})}})}catch(t){if(o&&e.releaseSession&&e.releaseSession(o),t instanceof dr)throw t;const n=t instanceof Error?t.message:String(t),s=o??function(e){return e instanceof ao&&e.agentId||e&&"object"==typeof e&&"agentId"in e&&"string"==typeof e.agentId?e.agentId:void 0}(t)??r.resumeAgentId;return new io.vS({result:{case:"error",value:new io.od({...s?{agentId:s}:{},error:n})}})}}return{execute(e,o,s){const i=function(e){if(e.toolCallId&&e.parentConversationId)return[e.parentConversationId,e.toolCallId,e.resumeAgentId??"",e.forkAgentId??""].join("\0")}(o);if(void 0===i)return n(e,o,s);const a=r.get(i);if(void 0!==a)return Promise.resolve(a);const c=t.get(i);if(void 0!==c)return c;const l=n(e,o,s).then((e=>("success"===e.result.case&&(r.set(i,e),r.size>1e3&&r.delete(r.keys().next().value)),e))).finally((()=>{t.delete(i)}));return t.set(i,l),l}}}(M),F=(P=M,{execute:(e,t)=>P.awaitBackgroundRunBounded(e,t)}),N=function(e){return{execute:async(t,r)=>e.forceBackgroundByToolCallId(r.toolCallId)}}(M);g.resources.base.register(co,D),g.resources.base.register(lo,F),g.resources.base.register(uo,N);const U=O.services.hooksRuntime,B="object"==typeof(x=U)&&null!==x&&"workspacePath"in x&&"string"==typeof x.workspacePath&&"createSessionRuntime"in x&&"function"==typeof x.createSessionRuntime?U:void 0,W=void 0!==B&&void 0===y&&!0!==e.summarize?function(e){const{workspaceRuntime:t}=e;if(!(t.hooksConfigLease.hasHookForStep(Rd.sessionStart)||t.hooksConfigLease.hasHookForStep(Rd.sessionEnd)||t.hooksConfigLease.hasHookForStep(Rd.stop)||t.hooksConfigLease.hasHookForStep(Rd.beforeSubmitPrompt)))return{};const r=t.createSessionRuntime({sessionState:e.sessionState,metadata:e.metadata}),{hookExecutor:n}=r;let o;return{async onSessionStart(e){if(o=e,n.hasHooksForStep(Rd.sessionStart))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...mF(e),is_background_agent:!1},r=await n.executeHookForStep(Rd.sessionStart,t);if(r)return r.env&&n.setSessionEnvironment(r.env),{env:r.env,additionalContext:r.additional_context,blocked:!1===r.continue,blockedReason:r.user_message}}catch(e){CO.Jz.warn("[hooks-adapter] sessionStart hook failed:",e)}},async onSessionEnd(e,t){if(n.hasHooksForStep(Rd.sessionEnd))try{const r={conversation_id:o?.conversationId??"",generation_id:o?.generationId??"",model:o?.model??"unknown",...o?mF(o):{},reason:e,duration_ms:t,is_background_agent:!1,final_status:e};await n.executeHookForStep(Rd.sessionEnd,r)}catch(e){CO.Jz.warn("[hooks-adapter] sessionEnd hook failed:",e)}finally{n.clearSessionEnvironment()}else n.clearSessionEnvironment()},async onBeforeSubmitPrompt(e){if(n.hasHooksForStep(Rd.beforeSubmitPrompt))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...mF(e),prompt:e.promptText??"",attachments:[]};await n.executeHookForStep(Rd.beforeSubmitPrompt,t)}catch(e){CO.Jz.warn("[hooks-adapter] beforeSubmitPrompt hook failed:",e)}},async onTurnCompleted(e){if(!n.hasHooksForStep(Rd.stop))return;const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...mF(e),status:"completed",loop_count:e.loopCount},r=await n.executeHookForStep(Rd.stop,t),o="string"==typeof r?.followup_message?r.followup_message.trim():"";return o.length>0?o:void 0},async onTurnError(e){if(n.hasHooksForStep(Rd.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...mF(e),status:"error",loop_count:e.loopCount};await n.executeHookForStep(Rd.stop,t)}catch(e){CO.Jz.warn("[hooks-adapter] onTurnError stop hook failed:",e)}},async onTurnAborted(e){if(n.hasHooksForStep(Rd.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...mF(e),status:"aborted",loop_count:e.loopCount};await n.executeHookForStep(Rd.stop,t)}catch(e){CO.Jz.warn("[hooks-adapter] onTurnAborted stop hook failed:",e)}},async dispose(){await r.dispose()}}}({workspaceRuntime:B,sessionState:g.state,metadata:g.metadata}):void 0,H=new VB({workspacePath:p,conversationId:l,blobStore:d}),q=function(e,t,r){const{hooks:n}=r,[o,s]=e.withCancel(),i=new _O;let a;const l=new Map,u=(e,t)=>{const r=l.get(e);void 0!==r&&(l.delete(e),clearTimeout(r.ackTimer),r.resolve(t))};let d;const h=[],p=e=>{for(const t of h.splice(0))t.resolve(e)},f=()=>{if(0===h.length)return;const e=h.map((e=>e.text)).join("\n\n");return p("complete_delivered"),AO(e)},m=r.interactionListener,g={async sendUpdate(e,t){const r=t.message;if("contextInjectionState"===r?.case){const e=r.value,t="object"==typeof e&&null!==e&&"injectionId"in e&&"string"==typeof e.injectionId?e.injectionId:void 0,n=function(e){if("object"!=typeof e||null===e||!("state"in e))return;const t=e.state;if("object"!=typeof t||null===t||!("state"in t))return;const r=t.state;return"object"==typeof r&&null!==r&&"case"in r&&"string"==typeof r.case?r.case:void 0}(e),o=function(e){switch(e){case"queued":return"queued";case"delivered":return"delivered";case"queuedForNextTurn":return"queued_for_next_turn";case"cancelled":return"cancelled";default:return"rejected"}}(n),s=void 0===t?void 0:l.get(t);if(void 0!==s&&void 0!==t){const e=function(e){switch(e){case"queued":return"confirm_steering";case"delivered":return"complete_delivered";case"queued_for_next_turn":case"cancelled":case"rejected":return"revert_to_followup";default:throw new Error(`Unknown steer ack state: ${String(e)}`)}}(o);"confirm_steering"===e?clearTimeout(s.ackTimer):(l.delete(t),s.resolve(e))}}await m.sendUpdate(e,t)},query:(e,t)=>m.query(e,t),...void 0!==m.enqueuePostTurnEndedWork?{enqueuePostTurnEndedWork:e=>m.enqueuePostTurnEndedWork?.(e)}:{},...void 0!==m.flushPostTurnEndedWork?{flushPostTurnEndedWork:e=>m.flushPostTurnEndedWork?.(e)??Promise.resolve()}:{}};let w=r.initialState;const y={async handleCheckpoint(e,t){w=t,await(r.onCheckpoint?.(t))},getLatestCheckpoint:()=>w};let v="completed";const b=Date.now(),S=PO(function(e,t){if((0,EO.TU)(t))return t;const r=RO.get(e);if(void 0!==r)return r;const n=(0,EO.sh)(e).blobEncryptionKey;if(void 0===n)throw new Error("getDefaultAgentMetadata did not seed a blobEncryptionKey");return RO.set(e,n),n}(r.conversationId,r.blobEncryptionKey),r.runOptions?.headers);return{done:(async()=>{const e=TO(r,0,IO(t));try{const t=await(n?.onSessionStart?.(e));if(t?.blocked)throw v="error",new Error(t.blockedReason??"Session blocked by sessionStart hook")}catch(e){if("completed"!==v)throw e;CO.Jz.warn("[agent-session-runner] sessionStart hook failed:",e)}let s=t,c=0;for(;s;){const e=TO(r,c,IO(s));try{await(n?.onBeforeSubmitPrompt?.(e))}catch(e){CO.Jz.warn("[agent-session-runner] beforeSubmitPrompt hook failed:",e)}a=r.runOptions?.generationUUID??(0,ye.C)();try{await r.agentClient.run(o,w,s,void 0,g,r.resources,r.blobStore,i,y,r.mcpTools??[],{conversationId:r.conversationId,...r.runOptions,generationUUID:a,headers:S,subagentModelOverrides:r.runOptions?.subagentModelOverrides??[]})}catch(t){throw v=$O(t)?"aborted":"error",MO("aborted"===v?n?.onTurnAborted?.(e):n?.onTurnError?.(e)),t}finally{a=void 0;for(const e of[...l.keys()])u(e,"revert_to_followup")}let t;try{t=await(n?.onTurnCompleted?.(e))}catch(e){throw v="error",e}const h="string"==typeof t?t.trim():"";let m;if(h.length>0)m=AO(h);else{const t=new AbortController;d=t;try{m=await(r.nextAction?.(e,AbortSignal.any([o.signal,t.signal])))}catch(r){if(o.signal.aborted||!t.signal.aborted)throw v=o.signal.aborted||$O(r)?"aborted":"error",MO("aborted"===v?n?.onTurnAborted?.(e):n?.onTurnError?.(e)),r}finally{d=void 0}void 0===m?m=f():p("revert_to_followup")}void 0!==m?(c+=1,i.resetStream(),s=m):s=void 0}})().finally((async()=>{p("revert_to_followup");const e=Date.now()-b;try{await(n?.onSessionEnd?.(v,e))}catch(e){CO.Jz.warn("[agent-session-runner] sessionEnd hook failed:",e)}try{await(n?.dispose?.())}catch(e){CO.Jz.warn("[agent-session-runner] hooks dispose failed:",e)}})),abort(){s()},async steer(e){if(""===e.trim())return"revert_to_followup";const t=a;if(void 0===t){const t=d;if(void 0===t)return"revert_to_followup";const r=new Promise((t=>{h.push({text:e,resolve:t})}));return t.abort(),await r}const r=(0,ye.C)(),n=new Promise((e=>{const t=setTimeout((()=>{u(r,"revert_to_followup")}),15e3);t.unref?.(),l.set(r,{resolve:e,ackTimer:t})}));try{return await i.submitConversationAction(new c.QFf({action:{case:"injectContextAction",value:new c.hGJ({injectionId:r,expectedRunId:t,payload:{case:"userContext",value:new c.oW$({userMessage:new c.RGk({messageId:(0,ye.C)(),text:e})})}})}})),await n}catch(e){return u(r,"revert_to_followup"),CO.Jz.warn("[agent-session-runner] context injection failed:",e),"revert_to_followup"}}}}(i,I,{agentClient:A,interactionListener:T,resources:s,blobStore:d,initialState:f,conversationId:l,mcpTools:h,blobEncryptionKey:t.blobEncryptionKey,runOptions:{generationUUID:t.requestId,requestedModel:m,enableAgentRetries:!1!==r.enableAgentRetries,emitModelCallUsage:!0,...void 0!==t.onConnectionStateChange?{onConnectionStateChange:e=>{!function(e,t){if(void 0!==e)try{e(function(e){switch(e.state){case"connected":return{state:"connected"};case"reconnecting":{const t=e.trigger?.errorClass,r=e.trigger?.stallAborted,n={...void 0!==t?{errorClass:t}:{},...void 0!==r?{stallAborted:r}:{}};return{state:"reconnecting",attempt:e.attempt,...Object.keys(n).length>0?{trigger:n}:{}}}default:return e}}(t))}catch(e){hH.v.warn(`onConnectionStateChange failed: ${e instanceof Error?e.message:String(e)}`)}}(t.onConnectionStateChange,e)}}:{},...Object.keys($).length>0?{headers:$}:{},...void 0!==t.systemPrompt?{customSystemPrompt:t.systemPrompt}:{}},hooks:W,async nextAction(e,t){const r=await M.waitForBackgroundCompletions(l,t);return r.length>0?function(e){return new c.QFf({action:{case:"backgroundTaskCompletionAction",value:new c.Kwc({completions:e.map((e=>new c.KFq({taskId:e.agentId,kind:c.aZc.SUBAGENT,status:"success"===e.status?c.uHL.SUCCESS:"aborted"===e.status?c.uHL.ABORTED:c.uHL.ERROR,...e.finalMessage.length>0?{detail:e.finalMessage}:{}})))})}})}(r):void 0},async onCheckpoint(e){f=e,H.writeFromState(i,e),await(t.onCheckpoint?.(e))}}),z=q.done.finally((async()=>{try{await M.awaitBackgroundWorkers()}finally{await H.waitForPendingWrites().catch((()=>{}));for(const e of E.values())try{await e.dispose()}catch(e){hH.v.log(`Failed to dispose subagent session runtime: ${e instanceof Error?e.message:String(e)}`)}E.clear();try{await g.dispose()}finally{S()}}})).catch((e=>{throw e}));return{abort(){q.abort(),a()},done:z,steer:e=>q.steer(e)}}catch(e){for(const e of E.values())try{await e.dispose()}catch{}E.clear();try{await g.dispose()}finally{S()}throw e}var x,P})),async reload(){await O.reload()},async dispose(){await O.dispose()}}}},"./src/agent/native/tree-sitter-bash.webpack.cjs"(e,t,r){const{loadVendoredTreeSitterModule:n}=r("./src/agent/native/vendored-tree-sitter.ts"),o=n({packageName:"tree-sitter-bash",nativeRequire:require});e.exports=o.available?o.module:{}},"./src/agent/native/tree-sitter.webpack.cjs"(e,t,r){const{createUnavailableParserClass:n,loadVendoredTreeSitterModule:o}=r("./src/agent/native/vendored-tree-sitter.ts"),s=o({packageName:"tree-sitter",nativeRequire:require});e.exports=s.available?s.module:n(s.reason)},"../constants/dist/commercial-cursor-hosts.js"(e,t,r){"use strict";r.d(t,{H:()=>c,K4:()=>i,Zf:()=>a,ad:()=>l});const n=["cursor.sh","cursor.com","cursorapi.com","cursor.so","cursor-marketplace.com","cursorusercontent.com","anysphere.co"],o=["cursor.blob.core.windows.net"];function s(e){return e.trim().toLowerCase().replace(/\.+$/,"")}const i="CURSOR_ORBIT_BUILD",a="CURSOR_ORBIT_DEPLOYMENT_HOSTS";function c(e){return new Set((e??"").split(",").map(s).filter((e=>""!==e)))}function l(e,t){return function(e){const t=s(e);return o.includes(t)||n.some((e=>t===e||t.endsWith(`.${e}`)))}(e)&&!t.has(s(e))}},"../context/dist/otel.js"(e,t,r){"use strict";r.d(t,{F:()=>E,HF:()=>_,MG:()=>k,Mf:()=>v,OA:()=>y,V5:()=>C,VI:()=>P,fR:()=>g,fU:()=>w,mJ:()=>b,r2:()=>x,xd:()=>R});var n=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js"),o=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/context-api.js"),s=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace-api.js"),i=r("../context/dist/core.js");const a=(0,i.cF)(Symbol("otel.span"),void 0),c=(0,i.cF)(Symbol("otel.root_span"),void 0),l=(0,i.cF)(Symbol("otel.root_start_ms"),void 0),u=(0,i.cF)(Symbol("otel.suppress_child_spans"),!1),d=(0,i.cF)(Symbol("otel.inheritable_span_attributes"),{});function h(e,t){const r=t.get(d);for(const t in r){const n=r[t];"string"!=typeof n&&"number"!=typeof n&&"boolean"!=typeof n||e.setAttribute(t,n)}}function p(e){return e.name||"anonymous-context"}function f(e,t){return!!t&&(e.get(u)||(p(e),!1))}function m(e="context-tracer"){return s.u.getTracer(e)}function g(e,t){const r=m(),n=e.get(a);if(f(e,n))return e;const i=p(e);let u;if(n){const e=s.u.setSpan(o._.active(),n);u=r.startSpan(i,t,e)}else u=r.startSpan(i,t);h(u,e);const d=Date.now();let g=e.with(a,u);return n||(g=g.with(c,u).with(l,d)),g}function w(e){return e.get(a)}function y(e){return e.with(u,!0)}function v(e,t,r){const n=e.get(d),o=w(e);return o&&null!==r&&o.setAttribute(t,r),e.with(d,{...n,[t]:r})}function b(e){try{const t=w(e);if(!t)return;const r=t.spanContext(),n=e.get(u);return{traceId:r.traceId,spanId:r.spanId,traceFlags:n?0:r.traceFlags,traceState:r.traceState?.serialize()}}catch{return}}const S=Symbol.for("anysphere.context.activeOtelSpanAls");function k(e,t){const r=()=>o._.with(s.u.setSpan(o._.active(),e),t),n=function(){const e=globalThis;if("object"!=typeof(t=e)||null===t||!(S in e))return;var t;const r=e[S];return function(e){return"object"==typeof e&&null!==e&&"run"in e&&"function"==typeof e.run&&"getStore"in e&&"function"==typeof e.getStore}(r)?r:void 0}();return void 0===n?r():n.run(e,r)}function _(e,t){try{const r=m(),n=w(e);if(!n)return;const i=s.u.setSpan(o._.active(),n),a=r.startSpan(t,void 0,i);h(a,e);const u=Date.now(),d=e.get(l),p="number"==typeof d?u-d:0,f=`event.${t}`;(e.get(c)??n).setAttribute(f,p),a.setAttribute(f,p),a.end()}catch{}}function C(e,t,r){const c=m(),l={traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags,isRemote:!0},u=s.u.setSpanContext(o._.active(),l),d=t||"child.span",h=c.startSpan(d,{kind:n.v.INTERNAL},u),p=r??(0,i.q6)();return(t?p.withName(t):p).with(a,h)}function E(e,t,r){const n=s.u.wrapSpanContext({traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags,isRemote:!0}),o=r??(0,i.q6)();return(t?o.withName(t):o).with(a,n)}class x{constructor(e,t,r=!0){this.disposed=!1,this.ctx=e,this.span=t,this.shouldEnd=r}[Symbol.dispose](){this.disposed||(this.disposed=!0,this.shouldEnd&&this.span.end())}}function P(e,t){const r=f(e,w(e)),n=g(e,t),o=w(n);return new x(n,o,!r)}function R(e,t,r){const n=w(e);if(!n||f(e,n))return;const o=w(g(e,t));return o.end(r),o}},"../mcp-core/dist/transport/mcp-url-utils.js"(e,t,r){"use strict";r.d(t,{$H:()=>Q,ME:()=>G,_N:()=>X,b6:()=>z,bi:()=>P,eA:()=>j,mD:()=>A,rM:()=>J,vc:()=>L});const n=BigInt(0),o=BigInt(8),s=BigInt(16),i=BigInt(65535);function a(e){const t=e.split(".");if(4!==t.length)return;let r=n;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<>s&i)),t.push(Number(o.value&i))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function l(e){return a(e)??function(e){const t=H(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=c(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<7?void 0:{version:6,value:[...a,...new Array(8-u).fill(0),...l].reduce(((e,t)=>e<=R&&d.clear();const t=l(e);return d.set(e,t),t}(e);return void 0!==r&&r.version===t.version&&r.value>>t.shift===t.shiftedNetwork}case"subdomainOrBase":return e===t.suffix||e.endsWith(`.${t.suffix}`);case"exact":return e===t.value;default:return t}}(H(e),function(e){const t=u.get(e);if(t)return t;u.size>=R&&u.clear();const r=function(e){const t=H(e);if("*"===t)return{kind:"matchAll"};if(t.includes("/")){const e=t.lastIndexOf("/");if(e<=0||e===t.length-1)return{kind:"invalidCidr"};const r=l(t.slice(0,e));if(!r)return{kind:"invalidCidr"};const n=Number(t.slice(e+1)),o=4===r.version?32:128;if(!Number.isInteger(n)||n<0||n>o)return{kind:"invalidCidr"};const s=BigInt(o-n);return{kind:"cidr",version:r.version,shift:s,shiftedNetwork:r.value>>s}}return t.startsWith("*.")?{kind:"subdomainOrBase",suffix:t.slice(2)}:{kind:"exact",value:t}}(e);return u.set(e,r),r}(t))}new Set(["airtable.com","anysphere.co","api.aws","apify.com","asana.com","ashbyhq.com","atlassian.com","atlassian.net","azuredatabricks.net","box.com","buildkite.com","calendly.com","canva.com","clickhouse.cloud","clickup.com","cloudflare.com","composio.dev","context7.com","cursor.com","cursor.sh","cursorapi.com","databricks.com","datadoghq.com","datadoghq.eu","ddog-gov.com","dropbox.com","elevenlabs.io","exa.ai","figma.com","firecrawl.dev","github.com","githubcopilot.com","gitlab.com","google.com","googleapis.com","granola.ai","hex.tech","hubspot.com","huggingface.co","intercom.com","linear.app","monday.com","neon.tech","notion.com","plain.com","posthog.com","prisma.io","railway.com","ramp.com","render.com","salesforce.com","sentry.dev","sentry.io","slack.com","snowflakecomputing.com","spacelift.io","statsig.com","stripe.com","supabase.com","todoist.net","vercel.com","workos.com","x.ai","x.com","zapier.com"]);const p="Blocked by MCP Network Admin Server Controls";function f(e){return/\s/.test(e)}const m="[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?",g=new RegExp(`^(?:${m}\\.)*${m}$`),w=new RegExp(`^\\*\\.(?:${m}\\.)*${m}$`),y="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)",v=new RegExp(`^${y}(?:\\.${y}){3}$`),b=/^[0-9a-f:]+$/,S=new RegExp(`^(?:${y}(?:\\.${y}){3}|[0-9a-f:]+)\\/\\d{1,3}$`);function k(e){const t=H(e);return t.length>0&&t.length<=253&&g.test(t)}function _(e){const t=H(e);return v.test(t)||function(e){const t=H(e);if(!b.test(t))return!1;try{return new URL(`https://[${t}]`),!0}catch{return!1}}(t)}function C(e,t){return""===t||"http:"===e&&"80"===t||"https:"===e&&"443"===t}function E(e){const t=new URL(e.pathname||"/",e.origin);if(t.search=e.search,t.pathname.endsWith("/")&&t.pathname.length>1&&(t.pathname=t.pathname.slice(0,-1)),"/"===t.pathname&&""===t.search){const t=e.protocol.toLowerCase();let r=`${t}//${e.hostname.toLowerCase()}`;return C(t,e.port)||(r+=`:${e.port}`),r}const r=e.protocol.toLowerCase();let n=`${r}//${e.hostname.toLowerCase()}`;return C(r,e.port)||(n+=`:${e.port}`),`${n}${t.pathname}${t.search}`}function x(e){if(e.includes("://"))return function(e){try{const t=new URL(e);return("http:"===t.protocol||"https:"===t.protocol)&&!(0===t.hostname.length||t.username.length>0||t.password.length>0)&&""===t.hash&&function(e){const t=e.toLowerCase();return!t.includes("*")&&(k(t)||_(t))}(t.hostname)}catch{return!1}}(e);const t=H(e);return"*"===t||!!w.test(t)||(t.includes("/")?function(e){const t=H(e);if(!S.test(t))return!1;const[r]=t.split("/");return void 0!==r&&h(r,t)}(t):k(t)||_(t))}function P(e){if(I.has(e))return I.get(e);I.size>=R&&I.clear();const t=function(e){const t=e.trim();if(0===t.length)return;const r=t.lastIndexOf("/");if(!t.includes("://")&&r>0&&/^\d+$/.test(t.slice(r+1).trim())){const e=`${H(t.slice(0,r))}/${t.slice(r+1).trim()}`;return x(e)?e:void 0}if(f(t)||t.includes("#")||t.includes("@"))return;const n=t.indexOf("://");if(-1!==n){const e=t.slice(0,n).toLowerCase();if("http"!==e&&"https"!==e)return;try{const e=new URL(t);if(0===e.hostname.length||e.username.length>0||e.password.length>0)return;const r="/"!==e.pathname&&""!==e.pathname,n=""!==e.search;if(e.hostname.includes("*"))return;if(r||n){const t=E(e);if(!x(t))return;return t}{const t=E(e);if(!x(t))return;return t}}catch{return}}else if(t.includes("/"))return;const o=t.trim().toLowerCase(),s=function(e){const t=e.indexOf(":");if(-1===t)return e;const r=e.slice(t+1);return/^\d+$/.test(r)?e.slice(0,t):e}(o);return 0===s.length||!x(s)||s!==o&&"*"===s?void 0:s}(e);return I.set(e,t),t}const R=2048,I=new Map,T=new Map;function A(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}function $(e){return e.endsWith("/")&&e.length>1?e.slice(0,-1):e}function M(e,t){return function(e,t,r){const n=D(t);if(!n)return!1;let o;try{o=new URL(e)}catch{return!1}return""===o.username&&""===o.password&&""===n.username&&""===n.password&&o.protocol===n.protocol&&o.port===n.port&&(s=o.hostname,i=n.hostname,!s.includes("*")&&H(s)===H(i)&&(A(a=o.pathname,c=n.pathname)||A($(a),$(c)))&&function(e,t,r){return""===e?r.allowRequestQueryWhenPatternOmitsQuery||""===t:A(e,t)}(o.search,n.search,r));var s,i,a,c}(e,t,{allowRequestQueryWhenPatternOmitsQuery:!0})}function D(e){const t=e.trim();if(0===t.length||f(t))return;if(function(e){const t=e.indexOf("[");return-1!==t&&-1===e.indexOf("]",t)}(t))return;const r=q(t);if(r&&("http:"===r.protocol||"https:"===r.protocol)&&""===r.username&&""===r.password&&0!==r.hostname.length&&(!H(r.hostname).includes(":")||t.includes("["))){if(t.includes("[")){const e=t.indexOf("["),n=t.indexOf("]",e);if(-1===n)return;const o=t.slice(e+1,n);if(H(r.hostname)!==H(o))return}return r}}function O(e,t){const r=e.toLowerCase(),n=t.toLowerCase();if("*"===r)return!0;if(void 0!==a(n))return A(r,n);if(!r.includes("*"))return r===n;const o=r.slice(1);if(r.startsWith("*.")&&!o.includes("*"))return n.endsWith(o)&&n.length>o.length;const s=r.split("."),i=n.split(".");return s.length===i.length&&!s[s.length-1]?.includes("*")&&A(r,n)}const F=/^([^/?#]+\/\/[^/?#]*):\*(?=[/?#]|$)/,N=/^[^/?#]+\/\/[^/?#]*\*$/;function L(e,t){if("*"===e||e===t)return!0;let r;T.has(t)?r=T.get(t):(T.size>=R&&T.clear(),r=q(t),T.set(t,r));const n=function(e){if(void 0===e||!/[^.]\.$/.test(e.hostname))return;const t=new URL(e.href);return t.hostname=e.hostname.slice(0,-1),t.href}(r);if(void 0!==n&&L(e,n))return!0;const o=function(e){const t=e.trim(),r=t.indexOf("://");if(-1===r)return/^[^/?#]*[^.*/?#]\.$/.test(t)?t.slice(0,-1):void 0;if(!t.includes("*"))return;const n=r+3,o=n+(t.slice(n).split(/[/?#]/,1)[0]??"").replace(/:(?:\d+|\*)$/,"").length;return/[^.*]\.$/.test(t.slice(n,o))?`${t.slice(0,o-1)}${t.slice(o)}`:void 0}(e);return!(void 0===o||!L(o,t))||!!r&&(e.includes("://")?function(e,t){const r=N.test(e),n=r||F.test(e),o=e.indexOf("://"),s=e.slice(0,o).toLowerCase(),i=t.protocol.slice(0,-1),a=q((s.includes("*")&&A(s,i)?`${i}${e.slice(o)}`:e).replace(F,"$1"));if(void 0===a||""!==a.username||""!==a.password||""!==t.username||""!==t.password||a.protocol!==t.protocol||!n&&a.port!==t.port)return!1;const c=a.hostname.replace(/%2a/gi,"*");return(O(c,t.hostname)||r&&O(c.replace(/\*$/,""),t.hostname))&&(r||A(`${a.pathname}${a.search}`,`${t.pathname}${t.search}`))}(e,r):h(r.hostname,e))}function j(e,t){if(A(e,t)||L(e,t))return!0;const r=function(e){const t=e.trim();if(t.includes("*")||!t.includes("://"))return;const r=q(t);return void 0!==r&&""===r.search&&""===r.hash?W(r):void 0}(e);if(void 0===r)return!1;const n=q(t.trim());return void 0!==n&&W(n)===r}const U=/%[0-9a-f]{2}/gi,B=/^[A-Za-z0-9\-._~]$/;function W(e){const t="http:"===e.protocol||"https:"===e.protocol?"http(s):":e.protocol,r=e.hostname.endsWith(".")?e.hostname.slice(0,-1):e.hostname,n=""===e.port?"":`:${e.port}`,o=e.pathname.replace(U,(e=>{const t=String.fromCharCode(Number.parseInt(e.slice(1),16));return B.test(t)?t:e.toUpperCase()})).replace(/\/{2,}/g,"/");return`${t}//${r}${n}${o.endsWith("/")?o.slice(0,-1):o}`}function H(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function q(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch{return}}function z(e){return(e.mcpNetworkAllowlist??[]).flatMap((e=>{const t=P(e);return void 0===t?[]:[t]}))}function G(e,t){if(!0!==t.enabled)return{allowed:!0};if("no_sandbox"===t.mcpNetworkMode)return{allowed:!0};if(!D(e))return{allowed:!1,message:t.blockMessage??p};const r=z(t);return r.length>0&&r.some((t=>function(e,t){const r=D(t);if(!r)return!1;if(!e.includes("://"))return h(H(r.hostname),e);if(M(e,t))return!0;const n=function(e){try{const t=new URL(e);if(""!==t.username||""!==t.password||"/"!==t.pathname||""!==t.search||""!==t.hash)return;return`${t.protocol}//${t.host}/*`}catch{return}}(e);return void 0!==n&&M(n,t)}(t,e)))?{allowed:!0}:{allowed:!1,message:t.blockMessage??p}}function V(e){const t=e?.trim();return t&&t.length>0?t:void 0}function K(e){return V(e)?.toLowerCase()}function J(e,t){const r=K(e.builtinServer),n=K(t.builtinServer);if(void 0!==r||void 0!==n)return void 0!==r&&r===n;const o=V(e.command),s=V(e.serverUrl);if(void 0===o&&void 0===s)return!1;const i=void 0===o||void 0!==t.command&&A(o,t.command),a=void 0===s||void 0!==t.url&&L(s,t.url);return i&&a}function Z(e,t,r){return void 0!==r?.command&&void 0===r.url&&void 0===t&&!0===e?.allowUserOverrideMcpServers}function X({allowedMcpConfiguration:e,server:t,localAgentNetworkAllowlist:r,blockMessage:n,unmatchedServerAllowlist:o,aggregateManagedServerNetworkAllowlists:s=!0,stdioPlatform:i,unsandboxUserExtensionStdio:a}){const c=e?.allowedMcpServers,l=function(e){if(!0!==e?.allowUserOverrideMcpServers)return;const t=(e.deniedMcpServers??[]).flatMap((e=>{const t=V(e.serverUrl),r=void 0===t?void 0:function(e){const t=e.trim();if(0===t.length)return;if(function(e){const t=e.indexOf("://");if(-1===t)return!1;const r=e.slice(t+3),n=r.indexOf("/");return-1===n?r.includes("?"):r.slice(n).includes("*")}(t)){const e=t.indexOf("://");if(-1!==e){const r=t.slice(e+3).split(/[/?#]/,1)[0];if(r?.includes("*")){const e=P(r.replace(/:\d+$/,""));if(void 0!==e)return e}}return}if(!t.includes("://")&&t.includes("*")&&"*"!==t&&!t.startsWith("*."))return;const r=P(e);if(void 0!==r)return r;const n=e.indexOf("://");if(-1===n)return;const o=e.slice(0,n).toLowerCase();if("http"!==o&&"https"!==o)return;const s=e.slice(n+3).split(/[/?#]/,1)[0];if(void 0===s||s.includes("@"))return;const i=P(s.replace(/:\d+$/,""));if(void 0!==i)return i;try{return P(new URL(e).hostname)}catch{return}}(t);return void 0===r?[]:[r]}));return t.length>0?t:void 0}(e),u=void 0===t?void 0:function(e,t){return e?.find((e=>J(e,t)))}(c,t),d=Z(e,u,t),h=function({allowedMcpConfiguration:e,matchedServer:t,server:r}){return void 0===r?(e?.allowedMcpServers?.length??0)>0:void 0!==t||Z(e,t,r)}({allowedMcpConfiguration:e,matchedServer:u,server:t})||void 0===t&&void 0!==l,p=void 0===t?s?c?.flatMap((e=>e.networkAllowlist??[])):void 0:d?[]:function(e,t,r){return void 0===e?r:[...e.networkAllowlist??[],...void 0!==V(e.serverUrl)&&void 0!==t.url?[t.url]:[]]}(u,t,o),f=d&&"win32"===i&&!0===a;let m;m=void 0===t?void 0:f?"no_sandbox":d?"allow_all":function(e,t){var r;if(void 0!==V(e?.command)&&void 0!==t.command&&void 0===t.url)return r=e?.networkMode,("allow_all"===r||"allowlist"===r||"deny_all"===r||"no_sandbox"===r?r:void 0)??"no_sandbox"}(u,t);const g=void 0===t||d?l:void 0;return{enabled:h,mcpNetworkAllowlist:p,...void 0!==m?{mcpNetworkMode:m}:{},...void 0!==g?{mcpNetworkDenylist:g}:{},...void 0!==r?{localAgentNetworkAllowlist:r}:{},...void 0!==n?{blockMessage:n}:{},...f?{win32UserExtensionUnsandbox:!0}:{}}}function Q(e){if(!0===e?.enabled&&"no_sandbox"!==e.mcpNetworkMode)return e}},"../shell-exec/dist/api/index.js"(e,t,r){"use strict";r.d(t,{BM:()=>Oo,Ls:()=>f,SandboxUnsupportedError:()=>_r,J:()=>x,St:()=>Er,Fn:()=>Do,Qw:()=>a,ue:()=>s,r5:()=>Ie,getLastSandboxFailureReason:()=>kr,oG:()=>no,Ko:()=>T,CG:()=>ht,W1:()=>Z,G6:()=>Mo,dA:()=>He,_B:()=>Qe,OK:()=>Ze,$b:()=>Xe,K3:()=>Rr,tv:()=>st,wG:()=>vt,fZ:()=>bt,s9:()=>mt,XX:()=>yt,T6:()=>et,Po:()=>Ye,$6:()=>nt,l7:()=>it,xS:()=>E,resolveSandboxPolicyForWorkspace:()=>Ct,fB:()=>Dt,spawnInSandbox:()=>xr,Xw:()=>I});var n=r("node:child_process");new Set;const o=["SSH_CLIENT","SSH2_CLIENT"];function s(e){const t=e||process.env,{ELECTRON_RUN_AS_NODE:r,...n}=t;for(const e of Object.keys(n))e.startsWith("AGENT_HOST_DAEMON_")&&delete n[e];for(const e of o)delete n[e];return n}const i="NODE_COMPILE_CACHE";function a(e){const{[i]:t,...r}=e;return r.NODE_DISABLE_COMPILE_CACHE="1",r}const c=["SSH_AUTH_SOCK","DBUS_SESSION_BUS_ADDRESS","XDG_RUNTIME_DIR","WAYLAND_DISPLAY"];function l(e){const t={...e};for(const e of c)delete t[e];return t}const u=[["core.quotePath","false"]];function d(e){const t=function(e){const t=e.GIT_CONFIG_COUNT;if(void 0===t||""===t)return 0;const r=Number.parseInt(t,10);return Number.isFinite(r)&&r>=0?r:0}(e),r=new Set;for(let n=0;no.endsWith(e)))){const n=S(e,r);if(g.existsSync(n))return k(n,t,r)}for(const o of n){const n=S(`${e}${o}`,r);if(g.existsSync(n))return k(n,t,r)}}return e.match(/\.ps1$/i)?{cmd:m.join(process.env.SYSTEMROOT,"System32","WindowsPowerShell","v1.0","PowerShell.exe"),args:["-ExecutionPolicy","Unrestricted","-NoLogo","-NonInteractive","-File",e].concat(t)}:e.match(/\.(bat|cmd)$/i)?{cmd:m.join(process.env.SYSTEMROOT,"System32","cmd.exe"),args:["/C",e,...t]}:e.match(/\.(js)$/i)?{cmd:process.execPath,args:[e].concat(t)}:{cmd:e,args:t}}let _;const C=["/usr/local/bin","/usr/bin","/bin"];function E(){const e=k("rg",[]).cmd;return"rg"!==e?e:void 0}function x(e){if(!e)throw new Error("configureRipgrepPath: path must not be empty");_=e}function P(e){const t=Object.keys(e).filter((e=>"path"===e.toLowerCase()));if(0!==t.length)return"win32"===process.platform?t.find((e=>"Path"===e))??t[0]:t.find((e=>"PATH"===e))??t[0]}function R(e,t){const r=(0,m.dirname)(t);if(!r||"."===r)return e;let n=function(e){const t=P(e);return void 0!==t?e[t]??"":""}(e).split(m.delimiter).filter(Boolean);return 0===n.length&&"win32"!==process.platform&&(n=C),function(e,t){const r=P(e)??("win32"===process.platform?"Path":"PATH"),n={...e};for(const e of Object.keys(n))e!==r&&"path"===e.toLowerCase()&&delete n[e];return n[r]=t,n}(e,[r,...n.filter((e=>e!==r))].join(m.delimiter))}function I(e){return _&&(0,m.isAbsolute)(_)?{...R(e,_),CURSOR_RIPGREP_PATH:_}:e}function T(){if(!_)throw new Error("Ripgrep path not configured. Call configureRipgrepPath() at startup.");return _}const A="win32"===process.platform;function $(e){return!A&&!!e?.SUDO_ASKPASS}function M(e){return $(e)?"alias sudo='sudo -A'; ":""}function D(e){const t=[];let r=0;for(;r=e.length||/\s/.test(e[n])){let o=n;for(;ovoid 0!==t&&e.toUpperCase()===r))}const F=["PYTHONIOENCODING","PYTHONUTF8","PYTHONLEGACYWINDOWSSTDIO"];function N(e){F.some((t=>O(e,t)))||(e.PYTHONIOENCODING="utf-8:surrogateescape")}function L(e){O(e,"WSL_UTF8")||(e.WSL_UTF8="1")}const j="-Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8 -Dstdout.encoding=UTF-8 -Dstderr.encoding=UTF-8",U=["sun.stdout.encoding","sun.stderr.encoding","stdout.encoding","stderr.encoding"],B=`case " \${MAVEN_OPTS-} \${JAVA_TOOL_OPTIONS-} \${JDK_JAVA_OPTIONS-} \${_JAVA_OPTIONS-} " in ${U.map((e=>`*[[:space:]]-D${e}=*`)).join("|")}) ;; *) builtin export MAVEN_OPTS="\${MAVEN_OPTS:+$MAVEN_OPTS }${j}";; esac; `,W=`if ("$env:MAVEN_OPTS $env:JAVA_TOOL_OPTIONS $env:JDK_JAVA_OPTIONS \${env:_JAVA_OPTIONS}" -cnotmatch '(^|\\s)-D(${U.map((e=>e.replace(/\./g,"\\."))).join("|")})=') {\n if ($env:MAVEN_OPTS) { $env:MAVEN_OPTS = "$env:MAVEN_OPTS ${j}" } else { $env:MAVEN_OPTS = '${j}' }\n}`;var H=r("node:crypto"),q=r("node:os"),z=r("../utils/dist/workspace-paths.js"),G=r("../utils/dist/test-resets.js");let V;function K(e,t){const r=(0,g.lstatSync)(e);return r.isDirectory()&&r.uid===t&&!(18&r.mode)}function J(e){try{(0,g.mkdirSync)(e,{mode:448})}catch(e){if(!(e instanceof Error&&"code"in e&&"EEXIST"===e.code))throw e}}function Z(e){return X(e,{create:!1})}function X(e,{create:t}){const r=process.getuid?.();if(void 0===r)return;const n=(0,m.join)((0,q.tmpdir)(),`cursor-sandbox-${(0,z.r_)((0,m.resolve)(e))}`);try{for(const e of[n,(0,m.join)(n,"tmp")])if(t&&J(e),!K(e,r))return;return n}catch{return}}(0,G.J)((function(){V=void 0}));const Q='builtin eval "${__CURSOR_SANDBOX_TEMP_RESTORE:-}" 2>/dev/null; ',Y=["TMPDIR","TMP","TEMP","TMPPREFIX","NODE_COMPILE_CACHE","NODE_DISABLE_COMPILE_CACHE"],ee="builtin export NODE_DISABLE_COMPILE_CACHE=1; builtin unset NODE_COMPILE_CACHE; ";function te(e){const t=(0,m.join)(e,"tmp");return{TMPDIR:t,TMP:t,TEMP:t,TMPPREFIX:(0,m.join)(t,"sh-")}}function re(e=(0,m.join)((0,q.tmpdir)(),"cursor-sandbox-cache",function(){return V||(V=(0,H.randomBytes)(16).toString("hex")),V}())){return{NPM_CONFIG_CACHE:(0,m.join)(e,"npm"),PNPM_STORE_PATH:(0,m.join)(e,"pnpm-store"),GOCACHE:(0,m.join)(e,"go-build"),GOMODCACHE:(0,m.join)(e,"go-mod"),CARGO_TARGET_DIR:(0,m.join)(e,"cargo-target"),PIP_CACHE_DIR:(0,m.join)(e,"pip"),UV_CACHE_DIR:(0,m.join)(e,"uv"),BUN_INSTALL_CACHE_DIR:(0,m.join)(e,"bun"),YARN_CACHE_FOLDER:(0,m.join)(e,"yarn"),npm_config_devdir:(0,m.join)(e,"node-gyp"),PLAYWRIGHT_BROWSERS_PATH:(0,m.join)(e,"playwright"),PUPPETEER_CACHE_DIR:(0,m.join)(e,"puppeteer"),TURBO_CACHE_DIR:(0,m.join)(e,"turbo"),GRADLE_USER_HOME:(0,m.join)(e,"gradle"),CONDA_PKGS_DIRS:(0,m.join)(e,"conda"),POETRY_CACHE_DIR:(0,m.join)(e,"poetry"),GEM_SPEC_CACHE:(0,m.join)(e,"gem-specs"),COMPOSER_HOME:(0,m.join)(e,"composer"),HOMEBREW_CACHE:(0,m.join)(e,"homebrew"),CYPRESS_CACHE_FOLDER:(0,m.join)(e,"cypress"),NX_CACHE_DIRECTORY:(0,m.join)(e,"nx"),NUGET_PACKAGES:(0,m.join)(e,"nuget"),CCACHE_DIR:(0,m.join)(e,"ccache"),CP_HOME_DIR:(0,m.join)(e,"cocoapods")}}var ne=r("node:fs/promises"),oe=r("../utils/dist/safe-spawn-cwd.js"),se=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js");function ie(){const e=process.env.CURSOR_SANDBOX_POLICY_DIR?.trim();return e?m.resolve(e):m.resolve(m.join(q.homedir(),".cursor","sandbox-policies"))}let ae=0;function ce(){const e=ie();g.mkdirSync(e,{recursive:!0,mode:448});try{g.chmodSync(e,448)}catch{}const t=Date.now();return t-ae>=9e5&&(ae=t,function(e){let t;try{t=g.readdirSync(e)}catch{return}const r=Date.now();for(const n of t){if(!n.startsWith("sandbox-policy-"))continue;const t=m.join(e,n);try{const e=g.statSync(t);if(!e.isFile())continue;r-e.mtimeMs>36e5&&g.unlinkSync(t)}catch{}}}(e)),e}function le(e){const t=ce(),r=H.randomBytes(8).toString("hex"),n=m.join(t,`sandbox-policy-${r}`);return g.writeFileSync(n,e,{encoding:"utf-8",mode:384}),n}const ue="/tmp/node-compile-cache",de="cursor-compile-cache",he=Symbol.for("cursor.startupNodeCompileCache"),pe=process.platform;function fe(e=q.tmpdir(),t=process.platform){if("win32"===t||0===e.length)return[];const r=m.posix.join(e,"node-compile-cache");return r===ue?[]:[r]}function me(e=q.tmpdir(),t=process.env,r=process.platform){if("win32"===r)return[];const n=new Set(fe(e,r));for(const e of["TMPDIR","TMP","TEMP"]){const o=t[e];if(void 0!==o&&m.posix.isAbsolute(o))for(const e of fe(m.posix.resolve(o),r))n.add(e)}return[...n]}function ge(e=process.env,t=q.homedir(),r=process.platform){if("darwin"===r)return t.length>0?m.posix.join(t,"Library/Caches",de):void 0;if("linux"!==r)return;const n=e.XDG_CACHE_HOME;return void 0!==n&&m.posix.isAbsolute(n)?m.posix.join(n,de):t.length>0?m.posix.join(t,".cache",de):void 0}function we(e=process.env,t=process.platform){if("win32"===t)return;const r=Object.getOwnPropertyDescriptor(globalThis,he)?.value,n="string"==typeof r?r:e.NODE_COMPILE_CACHE;if(void 0===n||!m.posix.isAbsolute(n))return;const o=m.posix.resolve(n);return"/"===o?void 0:o}function ye(e=q.homedir(),t=q.tmpdir(),r=process.env,n=process.platform){if("win32"===n)return[];const o=new Set([ue]);e.length>0&&(o.add(m.posix.join(e,".cache",de)),o.add(m.posix.join(e,"Library/Caches",de)));const s=[];for(const i of[...me(t,r,n),ge(r,e,n),we(r,n)])void 0===i||o.has(i)||(o.add(i),s.push(i));return s}function ve(e=q.homedir(),t=q.tmpdir(),r=process.platform,n=process.env){if("win32"===r)return[];const o=[ue,...me(t,n,r)],s=ge(n,e,r);return void 0===s||o.includes(s)||o.push(s),o}function be(e,t){return e.isSymbolicLink()?"a link, not followed":e.isDirectory()?e.uid!==t?`owned by uid ${e.uid}`:void 0:"not a folder"}function Se(e){return"object"!=typeof e||null===e?{}:Object.fromEntries(Object.entries(e).filter((e=>"string"==typeof e[1])))}function ke(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:"error"}const _e=[".local/bin",".local/share/mise",".local/share/pnpm",".nvm",".volta",".asdf",".pyenv",".rbenv",".rustup",".cargo/bin",".cargo/registry",".cargo/git"],Ce=["bin","sbin","lib","opt","Cellar","share","Frameworks","etc/gitconfig","etc/openssl@3/cert.pem","etc/openssl@3/openssl.cnf","etc/ca-certificates"],Ee=(e,t)=>t.flatMap((t=>Ce.map((r=>({platform:e,scope:"global",path:`${t}/${r}`}))))),xe={linux:[".cache/node",".cache/yarn"],darwin:[".cache/node","Library/Caches/Yarn"]},Pe=e=>[..._e,...xe[e]].map((t=>({platform:e,scope:"home-dir",path:t}))),Re=[{platform:"linux",scope:"global",path:"/bin"},{platform:"linux",scope:"global",path:"/sbin"},{platform:"linux",scope:"global",path:"/usr/bin"},{platform:"linux",scope:"global",path:"/usr/sbin"},{platform:"linux",scope:"global",path:"/lib"},{platform:"linux",scope:"global",path:"/lib64"},{platform:"linux",scope:"global",path:"/usr/lib"},{platform:"linux",scope:"global",path:"/usr/lib64"},{platform:"linux",scope:"global",path:"/usr/libexec"},{platform:"linux",scope:"global",path:"/usr/share"},{platform:"linux",scope:"global",path:"/etc/ld.so.cache"},{platform:"linux",scope:"global",path:"/etc/ld.so.conf"},{platform:"linux",scope:"global",path:"/etc/ld.so.conf.d"},{platform:"linux",scope:"global",path:"/etc/ssl/certs"},{platform:"linux",scope:"global",path:"/etc/ssl/openssl.cnf"},{platform:"linux",scope:"global",path:"/etc/ssl/cert.pem"},{platform:"linux",scope:"global",path:"/etc/ssl/ca-bundle.pem"},{platform:"linux",scope:"global",path:"/etc/ssl/certs/ca-certificates.crt"},{platform:"linux",scope:"global",path:"/etc/pki/tls/certs"},{platform:"linux",scope:"global",path:"/etc/pki/tls/openssl.cnf"},{platform:"linux",scope:"global",path:"/etc/pki/ca-trust/extracted"},{platform:"linux",scope:"global",path:"/etc/resolv.conf"},{platform:"linux",scope:"global",path:"/etc/hosts"},{platform:"linux",scope:"global",path:"/etc/nsswitch.conf"},{platform:"linux",scope:"global",path:"/etc/gai.conf"},{platform:"linux",scope:"global",path:"/etc/alternatives"},{platform:"linux",scope:"global",path:"/etc/mime.types"},{platform:"linux",scope:"global",path:"/etc/profile"},{platform:"linux",scope:"global",path:"/etc/bash.bashrc"},{platform:"linux",scope:"global",path:"/etc/zsh/zshenv"},{platform:"linux",scope:"global",path:"/etc/zsh/zprofile"},{platform:"linux",scope:"global",path:"/etc/zsh/zshrc"},{platform:"linux",scope:"global",path:"/etc/zsh/zlogin"},{platform:"linux",scope:"global",path:"/etc/gitconfig"},{platform:"linux",scope:"home",path:".bashrc"},{platform:"linux",scope:"home",path:".bash_profile"},{platform:"linux",scope:"home",path:".profile"},{platform:"linux",scope:"home",path:".zshenv"},{platform:"linux",scope:"home",path:".zprofile"},{platform:"linux",scope:"home",path:".zshrc"},{platform:"linux",scope:"home",path:".zlogin"},{platform:"linux",scope:"home",path:".gitconfig"},{platform:"linux",scope:"home",path:".ssh/known_hosts"},{platform:"linux",scope:"home",path:".config/mise/config.toml"},{platform:"linux",scope:"home-dir",path:".cache/dotslash"},...Pe("linux"),...Ee("linux",["/usr/local","/home/linuxbrew/.linuxbrew"]),{platform:"linux",scope:"global",path:"/usr/local/go"},{platform:"linux",scope:"global",path:"/nix/store"},{platform:"linux",scope:"global",path:"/nix/var/nix/profiles"},{platform:"linux",scope:"bundled",path:"ripgrep"},{platform:"darwin",scope:"global",path:"/bin"},{platform:"darwin",scope:"global",path:"/usr/bin"},{platform:"darwin",scope:"global",path:"/usr/lib"},{platform:"darwin",scope:"global",path:"/usr/libexec"},{platform:"darwin",scope:"global",path:"/usr/share"},{platform:"darwin",scope:"global",path:"/System/Library"},{platform:"darwin",scope:"global",path:"/System/Cryptexes"},{platform:"darwin",scope:"global",path:"/Library/Apple"},{platform:"darwin",scope:"global",path:"/Library/Developer/CommandLineTools"},{platform:"darwin",scope:"global",path:"/Applications/Xcode.app"},{platform:"darwin",scope:"global",path:"/Library/Preferences/com.apple.dt.Xcode.plist"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/cert.pem"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/certs"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/openssl.cnf"},{platform:"darwin",scope:"global",path:"/private/etc/hosts"},{platform:"darwin",scope:"global",path:"/private/etc/resolv.conf"},{platform:"darwin",scope:"global",path:"/private/etc/apache2/mime.types"},{platform:"darwin",scope:"global",path:"/etc/profile"},{platform:"darwin",scope:"global",path:"/etc/bashrc"},{platform:"darwin",scope:"global",path:"/etc/zshenv"},{platform:"darwin",scope:"global",path:"/etc/zprofile"},{platform:"darwin",scope:"global",path:"/etc/zshrc"},{platform:"darwin",scope:"global",path:"/etc/zlogin"},{platform:"darwin",scope:"global",path:"/etc/gitconfig"},{platform:"darwin",scope:"home",path:".bashrc"},{platform:"darwin",scope:"home",path:".bash_profile"},{platform:"darwin",scope:"home",path:".profile"},{platform:"darwin",scope:"home",path:".zshenv"},{platform:"darwin",scope:"home",path:".zprofile"},{platform:"darwin",scope:"home",path:".zshrc"},{platform:"darwin",scope:"home",path:".zlogin"},{platform:"darwin",scope:"home",path:".gitconfig"},{platform:"darwin",scope:"home",path:".ssh/known_hosts"},{platform:"darwin",scope:"home",path:"Library/Preferences/.GlobalPreferences.plist"},{platform:"darwin",scope:"home",path:".config/mise/config.toml"},{platform:"darwin",scope:"home-dir",path:"Library/Python"},{platform:"darwin",scope:"home-dir",path:"Library/Caches/dotslash"},...Pe("darwin"),...Ee("darwin",["/opt/homebrew","/usr/local"]),{platform:"darwin",scope:"global",path:"/nix/store"},{platform:"darwin",scope:"global",path:"/nix/var/nix/profiles"},{platform:"darwin",scope:"bundled",path:"ripgrep"},{platform:"darwin",scope:"global",path:"/dev/null"},{platform:"darwin",scope:"global",path:"/dev/zero"},{platform:"darwin",scope:"global",path:"/dev/random"},{platform:"darwin",scope:"global",path:"/dev/urandom"}];function Ie(e=process.platform,t=q.homedir(),r={}){const n=[];for(const o of Re){if(o.platform!==e)continue;if("global"===o.scope){n.push(o.path);continue}const s="bundled"===o.scope?r[o.path]:(0,m.join)(t,o.path);if(s)try{let e;switch(o.scope){case"home":e=(0,g.lstatSync)(s).isFile();break;case"home-dir":e=(0,g.lstatSync)(s).isDirectory();break;case"bundled":e=(0,g.statSync)(s).isFile()}e&&n.push(s)}catch{}}return n}const Te=[{type:"workspace",pattern:"**/.cursor/*.json"},{type:"workspace",pattern:"**/.cursor/**/*.json"},{type:"workspace",pattern:"**/.cursor/.workspace-trusted"},{type:"workspace",pattern:"!**/.cursor/rules"},{type:"workspace",pattern:"!**/.cursor/rules/**"},{type:"workspace",pattern:"!**/.cursor/commands"},{type:"workspace",pattern:"!**/.cursor/commands/**"},{type:"workspace",pattern:"!**/.cursor/worktrees"},{type:"workspace",pattern:"!**/.cursor/worktrees/**"},{type:"workspace",pattern:"!**/.cursor/skills"},{type:"workspace",pattern:"!**/.cursor/skills/**"},{type:"workspace",pattern:"!**/.cursor/agents"},{type:"workspace",pattern:"!**/.cursor/agents/**"},{type:"workspace",pattern:"**/.claude/*.json"},{type:"workspace",pattern:"**/.claude/**/*.json"},{type:"workspace",pattern:"**/.vscode/**"},{type:"workspace",pattern:"**/.idea/**"},{type:"workspace",pattern:"**/.venv/"},{type:"workspace",pattern:"**/venv/"},{type:"workspace",pattern:"**/*.code-workspace"},{type:"workspace",pattern:"**/.cursorignore"},{type:"workspace",pattern:"**/.workspace-trusted"},{type:"workspace",pattern:"**/.cursor/**/cli.json"},{type:"workspace",pattern:"**/.cursor/**/cli-config.json"},{type:"workspace",pattern:"**/.cursor/**/mcp.json"},{type:"workspace",pattern:"**/.cursor/**/mcp-approvals.json"},{type:"workspace",pattern:"**/.cursor/**/permissions.json"},{type:"git",pattern:"**/.git/hooks/**"},{type:"git",pattern:"**/.git/config"},{type:"git",pattern:"**/.git/config.worktree"},{type:"git",pattern:"**/.git/info/attributes"},{type:"git",pattern:"**/.git/commondir"},{type:"git",pattern:"**/.git/worktrees/*/commondir"},{type:"git",pattern:"**/.git/worktrees/*/gitdir"},{type:"worktree",pattern:".git"},{type:"absolute",pattern:"/etc/ssl/cert.pem"},{type:"absolute",pattern:"/etc/ssl/ca-bundle.pem"},{type:"absolute",pattern:"/private/etc/ssl/cert.pem"},{type:"absolute",pattern:"/etc/ssl/certs/ca-certificates.crt"},{type:"absolute",pattern:"/etc/pki/tls/certs/ca-bundle.crt"},{type:"absolute",pattern:"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem"},{type:"home",pattern:".cursor/sandbox-policies"},{type:"absolute",pattern:"/tmp/node-compile-cache"},{type:"home",pattern:".cache/cursor-compile-cache"},{type:"home",pattern:"Library/Caches/cursor-compile-cache"}];function Ae(e){const t=Te.filter((e=>"workspace"===e.type)).map((e=>e.pattern));return{[e]:t}}function $e(e){const t=Te.filter((e=>"git"===e.type)).map((e=>e.pattern));return{[e]:t}}function Me(e){const t=Te.filter((e=>"worktree"===e.type)).map((e=>e.pattern));return{[e]:t}}Te.filter((e=>"git"===e.type)).map((e=>e.pattern)),Te.filter((e=>"workspace"===e.type&&e.pattern.startsWith("!")&&!e.pattern.endsWith("/**"))).map((e=>e.pattern.replace(/^!(\*\*\/)?/,"")));const De=[];let Oe=null,Fe=null;function Ne(e){if(!(e instanceof Error&&"code"in e&&"string"==typeof e.code)||e.code.startsWith("ERR_"))throw e}async function Le(e,t=""){const r=await(0,ne.lstat)(e).catch(Ne);if(void 0===r||!r.isFile()||r.size>4096)return;const n=await(0,ne.readFile)(e,"utf8").catch(Ne),o=n?.split("\n",1)[0]?.replace(/\r$/,"");if(void 0===o||!o.startsWith(t))return;const s=o.slice(t.length);return s.length>0&&!s.includes("\0")?s:void 0}async function je(e){if(!(0,oe.$f)(e))return(0,ne.realpath)(e).catch(Ne)}async function Ue(e){const t=await Le((0,m.join)(e,".git"),"gitdir: ");if(void 0===t)return;const r=await je((0,m.resolve)(e,t));if(void 0===r)return;const n=await Le((0,m.join)(r,"commondir")),o=void 0===n?r:await je((0,m.resolve)(r,n));return void 0===o?void 0:{gitDir:r,commonDirLink:n,commonDir:o}}async function Be(e){const t=await Ue(e);if(void 0===t||void 0===t.commonDirLink||"worktrees"!==(0,m.basename)((0,m.dirname)(t.gitDir)))return;const r=(0,m.dirname)((0,m.dirname)(t.gitDir));if(".git"!==(0,m.basename)(r)||(ze?t.commonDir.toLowerCase()!==r.toLowerCase():t.commonDir!==r))return;const n=await Le((0,m.join)(t.gitDir,"gitdir"));if(void 0===n)return;const o=(0,m.join)(e,".git"),[s,i]=await Promise.all([je((0,m.resolve)(t.gitDir,n)),je(o)]);return void 0!==s&&void 0!==i&&(ze?s.toLowerCase()===i.toLowerCase():s===i)?r:void 0}let We=null;function He(e){return function(){const e=q.homedir();if(null===We){const t=[];for(const r of Te)switch(r.type){case"absolute":t.push(r.pattern);break;case"home":e.length>0&&t.push((0,m.join)(e,r.pattern))}We=t}return[...We,...ye(e)]}().some((t=>{if(Ke(e,t))return!0;const r=function(e){let t;try{t=g.realpathSync.native((0,m.dirname)(e))}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;return"ENOENT"===t||"ENOTDIR"===t?void 0:qe}const r=(0,m.join)(t,(0,m.basename)(e));return r===(0,m.dirname)(r)?void 0:r}(t);return r===qe||void 0!==r&&Ke(e,r)}))}const qe=Symbol("unresolved parent");const ze="win32"===process.platform||"darwin"===process.platform;function Ge(e){if(!e.endsWith(m.sep))return e;const t=e.slice(0,-1);return""===t||"win32"===process.platform&&/^[a-zA-Z]:$/.test(t)?e:t}function Ve(e){return e.endsWith(m.sep)?e:e+m.sep}function Ke(e,t){const r=Ge(t);if(ze){const t=e.toLowerCase(),n=r.toLowerCase();return t===n||t.startsWith(Ve(n))}return e===r||e.startsWith(Ve(r))}function Je(e,t){const r=Ge(e);return ze?(0,m.relative)(r.toLowerCase(),t.toLowerCase()).replace(/\\/g,"/"):(0,m.relative)(r,t).replace(/\\/g,"/")}async function Ze(e,t){if(Ke(e,t)){const r=Je(t,e);if((null===Oe&&(Oe=se({ignoreCase:!0}),Oe.add(Te.filter((e=>"workspace"===e.type)).map((e=>e.pattern)))),Oe).ignores(r))return!0}const{isWorktree:r,gitDirParent:n}=await async function(e){const t=await(0,ne.lstat)((0,m.join)(e,".git")).catch(Ne);if(!t?.isFile())return{isWorktree:!1,gitDirParent:e};const r=await async function(e){return(await Ue(e))?.commonDir}(e);return{isWorktree:!0,gitDirParent:void 0===r?e:(0,m.dirname)(r)}}(t);for(const r of new Set([n,t]))if(Ke(e,r)){const t=Je(r,e);if((null===Fe&&(Fe=se({ignoreCase:!0}),Fe.add(Te.filter((e=>"git"===e.type)).map((e=>e.pattern)))),Fe).ignores(t))return!0}return!(!r||!Ke(e,t)||".git"!==Je(t,e))||He(e)}function Xe(e){return void 0!==e&&("allow"===e.default||void 0!==e.allow&&e.allow.length>0)}function Qe(e){return void 0!==e&&"allow"===e.default}function Ye(){return{version:1,default:"deny"}}function et(){return{version:1,default:"allow"}}var tt=r("../utils/dist/path-utils.js");function rt(e){if(!e)return;const t={version:1};if("allow"!==e.default&&"deny"!==e.default||(t.default=e.default),Array.isArray(e.allow)&&e.allow.length>0&&(t.allow=e.allow.filter((e=>"string"==typeof e))),Array.isArray(e.deny)&&e.deny.length>0&&(t.deny=e.deny.filter((e=>"string"==typeof e))),e.logging){const r={};"string"==typeof e.logging.decisionLogPath&&(r.decisionLogPath=e.logging.decisionLogPath),"jsonl"===e.logging.logFormat&&(r.logFormat="jsonl"),Object.keys(r).length>0&&(t.logging=r)}return t}function nt(e){const t=e.type??"workspace_readwrite",r={debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,enableSharedBuildCache:e.enableSharedBuildCache};if("insecure_none"===t)return{type:"insecure_none",...r};let n;if(Array.isArray(e.additionalReadonlyPaths)){const t=e.additionalReadonlyPaths;n=t.length>0?t:void 0}const o={...r,networkAccess:e.networkAccess,networkPolicy:rt(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,additionalReadonlyPaths:n,readBoundary:e.readBoundary,additionalReadPaths:Array.isArray(e.additionalReadPaths)?e.additionalReadPaths:void 0,disableTmpWrite:e.disableTmpWrite,privateTmp:e.privateTmp};return"workspace_readonly"===t?{type:"workspace_readonly",...o}:{type:"workspace_readwrite",...o,additionalReadwritePaths:e.additionalReadwritePaths}}function ot(e){if("object"!=typeof e||null===e)return"Expected an object";const t=Object.fromEntries(Object.entries(e));if(void 0!==t.type){const e=["insecure_none","workspace_readwrite","workspace_readonly"];if("string"!=typeof t.type||!e.includes(t.type))return`Invalid type: expected one of ${e.join(", ")}`}const r=["networkAccess","networkPolicyStrict","disableTmpWrite","privateTmp","enableSharedBuildCache","captureDenies"];for(const e of r)if(void 0!==t[e]&&"boolean"!=typeof t[e])return`Invalid ${e}: expected boolean`;const n=["debugOutputDir"];for(const e of n)if(void 0!==t[e]&&"string"!=typeof t[e])return`Invalid ${e}: expected string`;const o=["additionalReadwritePaths","additionalReadonlyPaths","additionalReadPaths"];for(const e of o)if(void 0!==t[e]){if(!Array.isArray(t[e]))return`Invalid ${e}: expected array`;if(!t[e].every((e=>"string"==typeof e)))return`Invalid ${e}: expected array of strings`}if(void 0!==t.readBoundary&&"system"!==t.readBoundary&&"workspace"!==t.readBoundary)return'Invalid readBoundary: expected "system" or "workspace"';if(void 0!==t.networkPolicy){if("object"!=typeof t.networkPolicy||null===t.networkPolicy)return"Invalid networkPolicy: expected object";const e=Object.fromEntries(Object.entries(t.networkPolicy));if(void 0!==e.default&&"allow"!==e.default&&"deny"!==e.default)return'Invalid networkPolicy.default: expected "allow" or "deny"';if(void 0!==e.allow&&!Array.isArray(e.allow))return"Invalid networkPolicy.allow: expected array";if(void 0!==e.deny&&!Array.isArray(e.deny))return"Invalid networkPolicy.deny: expected array"}}async function st(e,t){const r=await async function(e,t){try{const r=await(0,ne.readFile)(e,"utf-8"),n=JSON.parse(r);if(void 0!==ot(n))return{success:!1,error:`Invalid sandbox policy: ${ot(n)??""}`};let o=nt(n);return t&&(o=it(o,t)),{success:!0,policy:o}}catch(e){return e instanceof Error?"code"in e&&"ENOENT"===e.code?{success:!1,error:"File not found"}:e instanceof SyntaxError?{success:!1,error:`Invalid JSON: ${e.message}`}:{success:!1,error:e.message}:{success:!1,error:"Unknown error"}}}(e,t);if(r.success)return r.policy}function it(e,t){if("insecure_none"===e.type)return e;const r=e.additionalReadonlyPaths?.map((e=>(0,tt.o1)(e,t))),n=e.additionalReadPaths?.map((e=>(0,tt.o1)(e,t)));if("workspace_readonly"===e.type)return{...e,additionalReadonlyPaths:r,additionalReadPaths:n};const o=e.additionalReadwritePaths?.map((e=>(0,tt.o1)(e,t)));return{...e,additionalReadonlyPaths:r,additionalReadPaths:n,additionalReadwritePaths:o}}var at=r("../constants/dist/commercial-cursor-hosts.js");function ct(e){const t=e.replace(/\\/g,"/").replace(/\/+$/,"");return""===t?"/":/^[a-zA-Z]:$/.test(t)?`${t}/`:t}function lt(e){const t=ct(e);return/^[a-zA-Z]:\//.test(t)||t.startsWith("//")?t.toLowerCase():t}const ut={insecure_none:0,workspace_readwrite:1,workspace_readonly:2};function dt(){return"1"===process.env[at.K4]}function ht(e){if(!dt())return e.teamAdmin?.type??e.perRepo?.type??e.perUser?.type??"insecure_none";const t=e.teamAdmin?.type??e.perUser?.type;return void 0===t&&void 0===e.perRepo?"insecure_none":Rt(t??"workspace_readwrite",e.perRepo?.type??"insecure_none")}function pt(...e){return e.some((e=>!0===e))}function ft(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return[];if(t.some((e=>0===e.length)))return[];if(1===t.length)return function(e){const t=new Set,r=[];for(const n of e){const e=lt(n);t.has(e)||(t.add(e),r.push(n))}return r}(t[0]).map(ct);let r=new Map(t[0].map((e=>{const t=ct(e);return[lt(t),t]})));for(let e=1;en.has(e))))}return[...r.values()]}function mt(...e){const t=new Map;for(const r of e)if(r)for(const e of r){const r=ct(e),n=lt(r);t.has(n)||t.set(n,r)}return[...t.values()]}const gt=function({defaultValue:e,rank:t}){return{defaultValue:e,merge:(...r)=>{const n=r.filter((e=>void 0!==e));return 0===n.length?e:n.reduce(((e,r)=>t[r]ft(...e);function yt(...e){return gt.merge(...e)}function vt(...e){return wt(...e)}function bt(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return;let r;for(const e of t){if("deny"===e.default){r="deny";break}"allow"===e.default&&void 0===r&&(r="allow")}const n=new Set;for(const e of t)if(e.deny)for(const t of e.deny)n.add(t);const o=new Set;for(const e of t)if(e.allow)for(const t of e.allow)o.add(t);const s=o.size>0?[...o]:void 0;let i;for(let e=t.length-1;e>=0;e--)if(void 0!==t[e].logging){i=t[e].logging;break}const a={version:1};return void 0!==r&&(a.default=r),void 0!==s&&(a.allow=s),n.size>0&&(a.deny=[...n]),void 0!==i&&(a.logging=i),void 0!==a.default||void 0!==a.allow&&0!==a.allow.length||void 0!==a.deny&&0!==a.deny.length||void 0!==a.logging?a:void 0}function St(e,t){if(!e||0===e.length)return[...t];const r=new Set(e);for(const e of t)r.has(e)&&r.delete(e),r.add(e);return[...r]}function kt(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return;const r={};for(const e of t)for(const[t,n]of Object.entries(e))r[t]=St(r[t],n);return 0!==Object.keys(r).length?r:void 0}function _t(...e){for(let t=e.length-1;t>=0;t--)if(void 0!==e[t])return e[t]}async function Ct(e,t,r={}){if(!t)return{policy:{type:"insecure_none"}};if(dt()&&(t=Mt(t,e)),(0,oe.$f)(e))return Ot(t,{workspaceDir:e});if("workspace_readwrite"!==(Pt(t)??"workspace_readwrite"))return Ot(t,{workspaceDir:e});const n=r.stat??ne.stat,o=await async function(e,t){for(let r=e;;r=(0,m.dirname)(r)){if((0,oe.$f)(r))return;const e=await Et(r,t);if(void 0!==e)return e;if((0,m.dirname)(r)===r)return}}(e,n);let s=o?.root??e;if(o?.isFile){const e=await Be(o.root);void 0!==e&&(s=(0,m.dirname)(e)),t=xt(t,void 0===e?[]:[e],Me(o.root))}return t=await async function(e,t,r){const n=Nt(e,"workspace_readwrite"),o=mt(n.perUser?.additionalReadwritePaths,n.perRepo?.additionalReadwritePaths,n.teamAdmin?.additionalReadwritePaths);if(0===o.length)return e;const s=(await Promise.all(o.map((async e=>{if(t.has(ct(e))||(0,oe.$f)(e))return[];const n=await Et(e,r);if(void 0===n)return[];const o=[Ae(e),$e(e)];if(n.isFile){o.push(Me(e));const t=await Be(e);void 0!==t&&o.push($e((0,m.dirname)(t)))}return o})))).flat();return 0===s.length?e:xt(e,[],...s)}(t,new Set([ct(e)]),n),Ot(t,{workspaceDir:e,gitDirParent:s})}async function Et(e,t){const r=await t((0,m.join)(e,".git")).catch(Ne);return r?.isFile()||r?.isDirectory()?{root:e,isFile:r.isFile()}:void 0}function xt(e,t,...r){const n=dt(),o=n?e.perUser:e.perRepo,s="workspace_readwrite"===o?.type||void 0===o?o:void 0,i={...s,type:"workspace_readwrite",additionalReadwritePaths:t.length>0?[...s?.additionalReadwritePaths??[],...t]:s?.additionalReadwritePaths,writeProtectionMapping:kt(s?.writeProtectionMapping,...r)};return n?{...e,perUser:i}:{...e,perRepo:i}}function Pt(e){const{perUser:t,perRepo:r,teamAdmin:n}=e,o=[t,r,n].filter((e=>void 0!==e));if(0===o.length)return;const s=o[0].type;for(const e of o)if(e.type!==s)throw new Error(`Cannot merge policies of different types: found "${s}" and "${e.type}". All policies must be of the same type (all workspace_readwrite, all workspace_readonly, or all insecure_none).`);return s}function Rt(e,t){return ut[e]>=ut[t]?e:t}function It(e,t){if(void 0===e||e.type===t)return e;if("insecure_none"===t)return{type:t,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,enableSharedBuildCache:e.enableSharedBuildCache};if("insecure_none"===e.type)return{...e,type:t};if("workspace_readonly"===t){if("workspace_readwrite"===e.type){const{additionalReadwritePaths:r,...n}=e;return{...n,type:t}}return e}return e}function Tt(e){if("deny"===e?.default||void 0!==e?.deny&&0!==e.deny.length)return{version:1,..."deny"===e.default?{default:"deny"}:{},...void 0!==e.deny&&e.deny.length>0?{deny:e.deny}:{}}}function At(e,t,r){if(void 0===e||"insecure_none"===t)return;const n="insecure_none"===e.type?void 0:e,o={captureDenies:!0===e.captureDenies||void 0,networkPolicy:Tt(n?.networkPolicy),networkPolicyStrict:!0===n?.networkPolicyStrict||void 0,readBoundary:"workspace"===n?.readBoundary?"workspace":void 0,additionalReadPaths:void 0===n?.additionalReadPaths?void 0:ft(n.additionalReadPaths,r),additionalReadonlyPaths:n?.additionalReadonlyPaths,disableTmpWrite:!0===n?.disableTmpWrite||void 0,ignoreMapping:n?.ignoreMapping,writeProtectionMapping:n?.writeProtectionMapping};return"workspace_readonly"===t?{type:t,...o}:{type:"workspace_readwrite",...o}}function $t(e,t){return void 0===e||"insecure_none"===e.type||void 0===t?e:{...e,additionalReadPaths:e.additionalReadPaths?.map((e=>ct((0,tt.o1)(e,t))))}}function Mt(e,t){const r=Pt({perUser:e.perUser,teamAdmin:e.teamAdmin})??"workspace_readwrite",n=void 0===e.perRepo?r:Rt(r,e.perRepo.type),o=$t(It(e.perUser,n),t),s=$t(It(e.teamAdmin,n),t),i=mt("insecure_none"===o?.type?void 0:o?.additionalReadPaths,"insecure_none"===s?.type?void 0:s?.additionalReadPaths);return{perUser:o,perRepo:At(e.perRepo,n,i),teamAdmin:s}}function Dt(e,t){return Mt(e,t)}function Ot(e,t){return function(e,t){dt()&&(e=Mt(e,t?.workspaceDir));const r=Pt(e);if(void 0===r)return Ut({},t);switch(r){case"workspace_readwrite":return Ut(Nt(e,r),t);case"workspace_readonly":return function(e,t){const r=t?.debug,n=Lt(e,t),o={policy:jt({type:"workspace_readonly",disableTmpWrite:n.disableTmpWrite,networkPolicyStrict:n.networkPolicyStrict,readBoundary:n.readBoundary,additionalReadPaths:n.additionalReadPaths,additionalReadonlyPaths:n.additionalReadonlyPaths,networkPolicy:n.networkPolicy,debugOutputDir:n.debugOutputDir,captureDenies:n.captureDenies,enableSharedBuildCache:n.enableSharedBuildCache,privateTmp:n.privateTmp,ignoreMapping:n.ignoreMapping,writeProtectionMapping:n.writeProtectionMapping},"workspace_readonly")};return r&&(o.debug={fieldSources:n.fieldSources}),o}(Nt(e,r),t);case"insecure_none":return function(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,s=t?.debug,i={policy:jt({type:"insecure_none",allowlistEscalated:pt(r?.allowlistEscalated,n?.allowlistEscalated,o?.allowlistEscalated)||void 0,debugOutputDir:_t(r?.debugOutputDir,n?.debugOutputDir,o?.debugOutputDir),captureDenies:pt(r?.captureDenies,n?.captureDenies,o?.captureDenies)||void 0,enableSharedBuildCache:_t(r?.enableSharedBuildCache,n?.enableSharedBuildCache,o?.enableSharedBuildCache)},"insecure_none")};return s&&(i.debug={fieldSources:{}}),i}(Nt(e,r),t);default:throw new Error(`Unknown policy type: ${String(r)}`)}}(e,t)}function Ft(e,t){return e?.type===t}function Nt(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e;return{perUser:Ft(r,t)?r:void 0,perRepo:Ft(n,t)?n:void 0,teamAdmin:Ft(o,t)?o:void 0}}function Lt(e,t){const r=t?.debug,{perUser:n,perRepo:o,teamAdmin:s}=e,i=t?.workspaceDir??process.cwd(),a=function(e){const t=function(){if(0!==De.length)return{version:1,deny:[...De]}}(),r=q.homedir(),n=[];for(const e of Te)switch(e.type){case"workspace":case"git":case"worktree":break;case"absolute":n.push(e.pattern);break;case"home":r.length>0&&n.push((0,m.join)(r,e.pattern));break;default:{const t=e.type;throw new Error(`Unknown entry type: ${String(t)}`)}}return n.push(...ye(r)),{type:"workspace_readwrite",additionalReadonlyPaths:n,writeProtectionMapping:Ae(e),...t&&{networkPolicy:t},networkPolicyStrict:!0}}(i),c={},l=[n,o,s],u=["perUser","perRepo","teamAdmin","hardcoded"],d=(e,t)=>{r&&(c[e]=u[t]??"unknown")},h=pt(n?.disableTmpWrite,o?.disableTmpWrite,s?.disableTmpWrite);for(let e=l.length-1;e>=0;e--)if(!0===l[e]?.disableTmpWrite){d("disableTmpWrite",e);break}const p=pt(n?.networkPolicyStrict,o?.networkPolicyStrict,s?.networkPolicyStrict,a.networkPolicyStrict);a.networkPolicyStrict&&d("networkPolicyStrict",3);const f=dt()?yt(_t(n?.readBoundary,s?.readBoundary)??"system",o?.readBoundary):_t(n?.readBoundary,o?.readBoundary,s?.readBoundary)??"system",g=_t(n?.additionalReadPaths,o?.additionalReadPaths),w=!1===s?.allowUserOverrideReadPaths?mt(s.additionalReadPaths):mt(g,s?.additionalReadPaths),y="workspace"===f?w:void 0,v=mt(n?.additionalReadonlyPaths,o?.additionalReadonlyPaths,s?.additionalReadonlyPaths,a.additionalReadonlyPaths),b=v.length>0?v:void 0;let S=bt(n?.networkPolicy,o?.networkPolicy,s?.networkPolicy,a.networkPolicy);const k=s?.networkPolicy?.allow;void 0!==k&&k.length>0&&void 0!==S&&(S={...S,allow:[...k]},r&&(c["networkPolicy.allow"]="teamAdmin (replace)"));const _=void 0!==(C=S)?C:{version:1,default:"deny"};var C;const E=_t(n?.debugOutputDir,o?.debugOutputDir,s?.debugOutputDir),x=pt(n?.captureDenies,o?.captureDenies,s?.captureDenies),P=_t(n?.enableSharedBuildCache,o?.enableSharedBuildCache,s?.enableSharedBuildCache),R=_t(n?.privateTmp,o?.privateTmp,s?.privateTmp),I=kt(n?.ignoreMapping,o?.ignoreMapping,s?.ignoreMapping,a.ignoreMapping),T=$e(t?.gitDirParent??i);return{disableTmpWrite:h||void 0,networkPolicyStrict:p,readBoundary:f,additionalReadPaths:y,additionalReadonlyPaths:b,networkPolicy:_,debugOutputDir:E,captureDenies:x||void 0,enableSharedBuildCache:P,privateTmp:R,ignoreMapping:I,writeProtectionMapping:kt(n?.writeProtectionMapping,o?.writeProtectionMapping,s?.writeProtectionMapping,a.writeProtectionMapping,T),fieldSources:c}}function jt(e,t){const r={...e,type:t};for(const[e,t]of Object.entries(r))void 0===t&&Reflect.deleteProperty(r,e);return r}function Ut(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,s=t?.debug,i=Lt(e,t),a=mt(r?.additionalReadwritePaths,n?.additionalReadwritePaths,o?.additionalReadwritePaths),c={policy:jt({type:"workspace_readwrite",disableTmpWrite:i.disableTmpWrite,networkPolicyStrict:i.networkPolicyStrict,readBoundary:i.readBoundary,additionalReadPaths:i.additionalReadPaths,additionalReadwritePaths:a.length>0?a:void 0,additionalReadonlyPaths:i.additionalReadonlyPaths,networkPolicy:i.networkPolicy,debugOutputDir:i.debugOutputDir,captureDenies:i.captureDenies,enableSharedBuildCache:i.enableSharedBuildCache,privateTmp:i.privateTmp,ignoreMapping:i.ignoreMapping,writeProtectionMapping:i.writeProtectionMapping},"workspace_readwrite")};return s&&(c.debug={fieldSources:i.fieldSources}),c}var Bt=r("../utils/dist/workload-spawn.js"),Wt=r("../context/dist/logger.js"),Ht=r("../context/dist/core.js"),qt=r("../utils/dist/command-glob.js");const zt=n.execFile,Gt=new WeakMap;function Vt(e,t,r){return e===t?"related":r?.has(e)?"probably_unrelated":"maybe_related"}const Kt="darwin"===process.platform,Jt="linux"===process.platform,Zt=(0,Wt.h)("shell-exec:sandbox");function Xt(e){const t=ce();return e&&0!==e.length?e.includes(t)?e:[...e,t]:[t]}let Qt,Yt=!0,er=!1;function tr(){return Qt}function rr(e){"linux"===process.platform&&Object.assign(e,I(e))}let nr=null,or=null,sr=null,ir=null,ar=!1,cr=null;function lr(e){return{...e,additionalReadonlyPaths:Xt(e.additionalReadonlyPaths)}}class ur extends Error{}function dr(e){return e instanceof Error&&"code"in e&&"string"==typeof e.code?e.code:"unknown"}function hr(e,t,r){let n;e.ignoreMapping&&(n=function(e){return vr(e)}(e.ignoreMapping));const o=function(e,t,r){const n=e&&e.length>0?function(...e){const t={};for(const r of e){let e=!1;try{e=(0,g.existsSync)(r)&&(0,g.statSync)(r).isDirectory()}catch{}if(e)t[r]||(t[r]=[]),t[r].push("**");else{const e=r.lastIndexOf("/"),n=e>0?r.slice(0,e):"/",o=e>=0?r.slice(e+1):r;t[n]||(t[n]=[]),o?t[n].push(o,`${o}/**`):t[n].push("**")}}return t}(...e):{},o=!Jt||yr(r),s={...n};for(const[e,r]of Object.entries(t??{})){const t=e.startsWith("file://")?br(e):e;(o||yr(t))&&(s[e]=St(s[e],r))}if(0!==Object.keys(s).length)return vr(s)}(e.additionalReadonlyPaths,e.writeProtectionMapping,t),s=(i=e.readBoundary,r?.workspaceReadEnabled??function(){const e=Yt;return"function"==typeof e?e():e}()?i??"system":"system");var i;const a=function(e=process.platform){const t=[],r=new Set,n={};try{n.ripgrep=T()}catch{}for(const o of Ie(e,q.homedir(),n))r.has(o)||(r.add(o),t.push(o));return t}(),c=[t,..."workspace_readwrite"===e.type&&e.additionalReadwritePaths||[],Z(t)].filter((e=>void 0!==e)),l="workspace"===s?(e.additionalReadPaths??[]).flatMap((e=>function(e,t){let r=e.trim();(r.startsWith("~/")||r.startsWith("~\\"))&&(r=m.join(q.homedir(),r.slice(2)));const n=e=>e.includes("*")||e.includes("?"),o=/[/\\]\*\*?$/;if(o.test(r)&&n(m.basename(r.replace(/(?:[/\\]\*\*?)+$/,""))))return Zt.warn((0,Ht.q6)(),"[additionalReadPathGrants] a Read Allowlist file-name glob followed by /* or /** grants nothing"),[];const s=m.basename(r);if(o.test(r)||!n(s))return function(e){const t=[],r=new Set;for(const n of e){let e=n.trim();if(!e)continue;"~"===e?e=q.homedir():(e.startsWith("~/")||e.startsWith("~\\"))&&(e=m.join(q.homedir(),e.slice(2))),e=e.replace(/\/\*\*$/,"").replace(/\/\*$/,""),e=e.replace(/\\\*\*$/,"").replace(/\\\*$/,"");const o=m.basename(e);if((o.includes("*")||o.includes("?"))&&(e=m.dirname(e)),!e||"."===e)continue;const s=m.normalize(e);r.has(s)||(r.add(s),t.push(s))}return t}([e]);const i=m.dirname(r);return m.isAbsolute(i)?function(e,t,r){const n=(0,qt.b)(t),o=[];let s;try{const t=(0,g.realpathSync)(e);if(r.filter((e=>g.existsSync(e))).map((e=>(0,g.realpathSync)(e))).some((e=>(0,tt.BJ)(t,e))))return[];s=g.opendirSync(t);for(let e=1;;e++){const r=s.readSync();if(null===r)return o;if(e>1e4)throw new ur("its folder has more than 10000 entries");if(!n(r.name))continue;const i=m.join(t,r.name);try{if(!g.lstatSync(i).isFile()||m.dirname((0,g.realpathSync)(i))!==t)continue}catch(e){Zt.info((0,Ht.q6)(),`[fileNameGlobMatches] skips a matching file: error ${dr(e)}`);continue}if(256===o.length)throw new ur("more than 256 files match");o.push(i)}}catch(e){const t=e instanceof ur?e.message:`error ${dr(e)}`;return Zt.warn((0,Ht.q6)(),`[fileNameGlobMatches] a Read Allowlist file-name glob grants nothing: ${t}`),[]}finally{s?.closeSync()}}(i,s,t):[]}(e,c))):[],u=[...a],d=new Set(a);for(const e of l)d.has(e)||(d.add(e),u.push(e));const h={cwd:t,readBoundary:s,hardcodedReadPaths:u,additionalReadonlyPaths:o,networkAccess:Xe(e.networkPolicy),ignoreMapping:n};return"workspace_readonly"===e.type?{type:e.type,...h}:{type:e.type,...h,additionalReadwritePaths:e.additionalReadwritePaths||[],disableTmpWrite:e.disableTmpWrite||!1}}function pr(e){const t={sandbox:e};return Jt&&function(){const e=er;return"function"==typeof e?e():e}()&&(t.kernelMountBudget=!0),t}function fr(e){if(null!==nr)return nr;try{const t=tr();return Zt.info(e,`[checkBinaryAvailable] Resolved binary path: ${t}`),t?(nr=g.existsSync(t),nr?Zt.info(e,`[checkBinaryAvailable] Binary path exists: ${String(nr)}`):(or=new Error(`Sandbox binary not found at ${t}`),Zt.info(e,`[checkBinaryAvailable] Binary not found at: ${t}`)),nr):(or=new Error("Sandbox binary path was not configured"),nr=!1,Zt.info(e,"[checkBinaryAvailable] Binary path not set, returning false"),!1)}catch(t){return or=t instanceof Error?t:new Error(String(t)),nr=!1,Zt.info(e,`[checkBinaryAvailable] Exception checking binary: ${String(t)}`),!1}}function mr(e){if(null!==ir)return ir;const t=e??(0,Ht.q6)();if(Zt.info(t,"[isSandboxHelperSupported] Starting sandbox support check..."),!fr(t)){const e=or?.message||"Binary check failed";return sr=e,Zt.info(t,`[isSandboxHelperSupported] Binary not available, returning false. Reason: ${e}`),ir=!1,ir}if("win32"===process.platform)return sr="Windows sandbox helper only provides network proxy, not filesystem isolation",Zt.info(t,"[isSandboxHelperSupported] win32: returning false (proxy-only, no filesystem sandbox)"),ir=!1,ir;if("darwin"===process.platform)return sr=null,Zt.info(t,`[isSandboxHelperSupported] ${process.platform} platform, binary available, sandbox supported!`),ir=!0,ir;const{binaryPath:r,args:o,env:s}=function(e,t){const r=pr(hr(lr({type:"workspace_readwrite"}),t)),n=String(tr());Zt.info(e,`[sandboxPreflight] Running preflight with binary: ${n}`),Zt.info(e,`[sandboxPreflight] CWD: ${t}`);const o={...process.env};return rr(o),{binaryPath:n,args:["--policy",le(JSON.stringify(r)),"--preflight-only","--","/bin/true"],env:o}}(t,process.cwd());try{const e=Date.now();(0,Bt.D9)(n.execFileSync,r,o,{stdio:["ignore","ignore","pipe"],timeout:gr,env:s,shell:!1});const i=Date.now()-e;return sr=null,Zt.info(t,`[isSandboxHelperSupported] Preflight succeeded in ${i}ms, sandbox supported!`),ir=!0,ir}catch(e){return function(e,t){const{message:r,status:n,stderrText:o}=t;return Zt.error(e,`[sandboxPreflight] Preflight failed: ${r}`),Zt.error(e,`[sandboxPreflight] Exit status: ${n}`),o&&Zt.error(e,`[sandboxPreflight] Stderr: ${o}`),sr=2===n?`Linux preflight failed with exit code 2 (unsupported kernel features). stderr: ${o||"none"}`:`Linux preflight failed: ${r||"unknown error"}. Exit status: ${n}. stderr: ${o||"none"}`,ir=!1,!1}(t,function(e){if("object"!=typeof e||null===e)return{stderrText:""};const t="message"in e&&"string"==typeof e.message?e.message:void 0,r=!("status"in e)||"number"!=typeof e.status&&null!==e.status?void 0:e.status,n="stderr"in e?e.stderr:void 0;return{message:t,status:r,stderrText:Buffer.isBuffer(n)||"string"==typeof n?n.toString():""}}(e))}}(0,G.J)((function(){ir=null,ar=!1,cr=null,sr=null,nr=null,or=null}));const gr=15e3;function wr(e,t=[],r={},o){const i=(0,Ht.q6)();if(r.env=a(s(r.env)),!fr(i))throw new Error(`Sandbox binary not available: ${or?.message||"binary not configured"}. Please build the binary or use 'insecure_none' policy.`);if("insecure_none"===o.type)return(0,Bt.D9)(n.spawn,e,t,{...r,windowsHide:!0});if("workspace_readwrite"===o.type||"workspace_readonly"===o.type)return function(e,t,r,o){if("workspace_readwrite"!==o.type&&"workspace_readonly"!==o.type)throw new Error("Expected workspace_readwrite or workspace_readonly policy");const i=String(r.cwd??process.cwd()),c=o.sandboxWorkspaceRoot??i;let u=e,d=t;r.shell&&("win32"===process.platform?(u="string"==typeof r.shell?r.shell:"cmd.exe",d=["/c",`${e} ${t.join(" ")}`]):(u="string"==typeof r.shell?r.shell:"/bin/sh",d=["-c",`${e} ${t.join(" ")}`]));const h=function({workspaceRoot:e,executionCwd:t}){const r=m.resolve(e),n=m.resolve(t),o=Sr(r);if(n===r||n===o)return;const s=e=>(0,tt.ZU)({basePath:o,targetPath:e})?m.join(r,m.relative(o,e)):void 0,i=(0,tt.ZU)({basePath:r,targetPath:n})?n:s(n)??n;return{directory:i,fallbackDirectory:s(Sr(n))??i}}({workspaceRoot:c,executionCwd:i});"win32"!==process.platform&&void 0!==h&&({command:u,args:d}=(0,oe.kO)(u,d,h));const p=hr(lr(o),c),f=(0,Ht.q6)();!function({log:e,dirs:t=ve(q.homedir(),q.tmpdir(),pe),createOnly:r=[we(process.env,pe)].filter((e=>void 0!==e)),policyDir:n=ie(),uid:o=process.getuid?.()??-1}){const s=m.join(n,"node-compile-cache-removed-1"),{record:i,problem:a}=function(e){const t=e=>({record:{cleaned:[],kept:{},failed:{}},problem:e});let r,n;try{r=g.readFileSync(e,"utf8")}catch(e){const r=ke(e);return t("ENOENT"===r?void 0:r)}try{n=JSON.parse(r)}catch(e){return t(e instanceof SyntaxError?"not JSON":ke(e))}if("object"!=typeof n||null===n)return t("not a record");const o="cleaned"in n?n.cleaned:void 0;return{record:{cleaned:Array.isArray(o)?o.filter((e=>"string"==typeof e)):[],kept:Se("kept"in n?n.kept:void 0),failed:Se("failed"in n?n.failed:void 0)}}}(s);void 0!==a&&e(`node compile cache: starting a new cleanup record (${a})`);const c=new Set(i.cleaned),l=new Set(t);let u=!1;for(const n of[...t,...r.filter((e=>!l.has(e)))])try{const t=g.lstatSync(n,{throwIfNoEntry:!1});if(void 0!==t){const r=be(t,o);if(void 0!==r){i.kept[n]!==r&&(e(`node compile cache: kept ${n} (${r})`),i.kept[n]=r,u=!0);continue}l.has(n)&&!c.has(n)&&(g.rmSync(n,{recursive:!0,force:!0}),e(`node compile cache: removed ${n}`))}g.mkdirSync(n,{recursive:!0,mode:448}),l.has(n)&&!c.has(n)&&(c.add(n),u=!0),void 0===i.kept[n]&&void 0===i.failed[n]||(delete i.kept[n],delete i.failed[n],u=!0)}catch(t){const r=ke(t);i.failed[n]!==r&&(e(`node compile cache: could not prepare ${n} (${r})`),i.failed[n]=r,u=!0)}u&&function(e,t){const r=`${e}.${process.pid}.tmp`;try{g.writeFileSync(r,`${JSON.stringify(t)}\n`,{mode:384}),g.renameSync(r,e)}catch{g.rmSync(r,{force:!0})}}(s,{...i,cleaned:[...c]})}({log:e=>Zt.info(f,e)});const w=function(e){if(!("workspace"!==e.readBoundary||"workspace_readwrite"===e.type&&e.disableTmpWrite||"win32"===process.platform))return X(e.cwd,{create:!0})}(p);let y;w&&(p.additionalReadwritePaths=[...p.additionalReadwritePaths??[],w],Jt&&!0===o.privateTmp&&(y=te(w).TMPDIR));const v=function(e){if("insecure_none"===e.type)return;const t=e.networkPolicy;if(void 0===t)return;if(!Xe(t))return;const r=void 0!==t.deny&&t.deny.length>0;return"allow"!==t.default||r?{version:1,...t}:void 0}(o),b=pr(p);void 0!==y&&(b.mapTmpTo=y),void 0!==v&&(b.networkPolicy=v),!1===o.networkPolicyStrict&&(b.networkPolicyStrict=!1);const S=["--policy",le(JSON.stringify(b)),"--",u,...d],k=s(process.env),_={..."linux"===process.platform?l(k):k,..."linux"===process.platform&&r.env?l(r.env):r.env,CURSOR_SANDBOX:"native"};rr(_);const C=new Set(Y);if(w){const e=function(e,t,r){const n=te(e);if(r){const r=re();for(const[o,s]of Object.entries(re(e)))t[o]===r[o]&&(n[o]=s)}return n}(w,_,o.enableSharedBuildCache);Object.assign(_,e);for(const t of Object.keys(e))C.add(t);_.__CURSOR_SANDBOX_TEMP_RESTORE=Object.entries(e).map((([e,t])=>`builtin export ${e}='${t.replace(/'/g,"'\\''")}'`)).join("; ")}_.__CURSOR_SANDBOX_OWNED_ENV=[...C].join(" ");const E={cwd:void 0!==y?p.cwd:r.cwd||i,env:a(_),stdio:r.stdio||["pipe","pipe","pipe"],detached:r.detached,windowsHide:!0};try{const e=new Date,t=(0,Bt.D9)(n.spawn,String(tr()),S,E);return Kt&&t.pid&&function(e,t){Gt.set(e,t)}(t,{startTime:e,pid:t.pid}),t}catch(e){throw new Error(`Failed to spawn sandboxed process: ${String(e)}`)}}(e,t,r,o);throw new Error(`Unsupported sandbox policy: ${String(o)}`)}function yr(e,t=e=>g.existsSync(e)){if((0,oe.$f)(e))return!0;let r=m.resolve(e);for(;;){try{if(t(m.join(r,".git")))return!0}catch{}const e=m.dirname(r);if(e===r)return!1;r=e}}function vr(e,t,r,n){const o={};for(const[t,r]of Object.entries(e)){const e=t.startsWith("file://")?br(t):t;o[e]=St(o[e],r);const n=Sr(e);n!==e&&(o[n]=St(o[n],r))}return o}function br(e){let t=e.replace(/^file:\/\//,"");return t=decodeURIComponent(t),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t}function Sr(e,t){if((0,oe.$f)(e))return e;try{return(t??g.realpathSync)(e)}catch{return e}}function kr(){return sr}class _r extends Error{reason;constructor(e,t){super(e),this.reason=t,this.name="SandboxUnsupportedError"}}const Cr="darwin"===process.platform;function Er(e){!function(e){T();const{sandboxBinaryPath:t,workspaceReadEnabled:r,kernelMountBudget:n}=e;Qt||(Qt=t),void 0!==r&&(Yt=r),void 0!==n&&(er=n)}(e)}function xr(e,t=[],r={},o){if(r.env=s(r.env),o.enableSharedBuildCache&&(r={...r,env:{...s(process.env),...re(),...r.env}}),"insecure_none"!==o.type){if(mr())return wr(e,t,r,o);const n=kr();throw new _r(`Sandbox policy '${o.type}' is not supported on this system. Ensure the sandbox helper binary is available, or use 'insecure_none'. Reason: ${n||"unknown"}`,n??void 0)}return function(e,t,r,o={spawn:n.spawn,spawnWorkload:Bt.D9}){return o.spawnWorkload(o.spawn,e,t,{...r,env:a(r.env??process.env),windowsHide:!0})}(e,t,r)}function Pr(e){return Cr?async function(e){const t=Gt.get(e);return t?(r=t.pid,n=t.startTime,o=t.unrelatedPids,new Promise((e=>{try{const t=new Date,s=["show","--style","ndjson","--predicate",'process=="kernel" AND eventMessage CONTAINS "Sandbox:" AND eventMessage contains "deny"',"--last",Math.ceil((t.getTime()-n.getTime())/1e3).toString()];(0,Bt.D9)(zt,"/usr/bin/log",s,((t,n)=>{if(t)return void e([{raw:t.message}]);const s=n.split(/\r?\n/).filter((e=>e.trim().length>0)),i=[];for(const e of s)try{const t=JSON.parse(e),n=t?.eventMessage??"";if(!n||"string"!=typeof n)continue;const s=/^Sandbox:\s+([^(]+)\((\d+)\)\s+([a-zA-Z-]+)\((\d+)\)\s+([^\s]+)\s+(.+)$/.exec(n);if(s){const[,e,a,c,l,u,d]=s,h=Number(a);i.push({timestamp:t.timestamp,processName:e.trim(),pid:h,decision:c.toLowerCase(),decisionCode:Number(l),operation:u,target:d,duplicateCount:1,raw:n,relationship:Vt(h,r,o)});continue}const a=/^(\d+) duplicate report for Sandbox: (.+)$/.exec(n);if(a){const e=Number(a[1]),s=a[2],c=/^([^(]+)\((\d+)\)\s+([a-zA-Z-]+)\((\d+)\)\s+([^\s]+)\s+(.+)$/.exec(s);if(c){const[,s,a,l,u,d,h]=c,p=Number(a);i.push({timestamp:t.timestamp,processName:s.trim(),pid:p,decision:l.toLowerCase(),decisionCode:Number(u),operation:d,target:h,duplicateCount:e,raw:n,relationship:Vt(p,r,o)})}else i.push({timestamp:t.timestamp,duplicateCount:e,raw:n});continue}i.push({timestamp:t.timestamp,raw:n})}catch{}e(i)}))}catch(t){e([{raw:String(t)}])}}))):(console.log("No sandbox metadata found on child process"),[]);var r,n,o}(e):Promise.resolve([])}function Rr(e,t){if(Cr)try{(0,g.accessSync)("/usr/bin/sandbox-exec",g.constants.X_OK)}catch{return!1}return mr(t?.ctx)}var Ir=r("node:stream"),Tr=r("../context/dist/otel.js"),Ar=r("../utils/dist/writable-iterable.js");const $r="--",Mr='builtin eval "$1" 3<&- 4>&-';var Dr=r("node:string_decoder");const Or=50,Fr=262144;class Nr{writable;pending=[];pendingBytes=0;flushTimeout;flushPromise;flushIntervalMs;maxBufferedBytes;constructor(e,t){this.writable=e,this.flushIntervalMs=t?.flushIntervalMs??Or,this.maxBufferedBytes=t?.maxBufferedBytes??Fr}async push(e,t){0!==t.length&&(this.pending.push({type:e,data:t}),this.pendingBytes+=t.length,this.pendingBytes>=this.maxBufferedBytes?await this.flush():this.scheduleFlush())}async flush(){if(this.clearFlushTimeout(),this.flushPromise)return await this.flushPromise,void(this.pendingBytes>0&&await this.flush());if(0===this.pendingBytes)return;const e=this.pending;this.pending=[],this.pendingBytes=0,this.flushPromise=this.writeBufferedOutput(e);try{await this.flushPromise}finally{this.flushPromise=void 0}}async close(){await this.flush()}scheduleFlush(){void 0===this.flushTimeout&&(this.flushTimeout=setTimeout((()=>{this.flushTimeout=void 0,this.flush()}),this.flushIntervalMs))}clearFlushTimeout(){void 0!==this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=void 0)}async writeBufferedOutput(e){for(const t of function(e){if(0===e.length)return[];const t=[];let r=e[0].type,n=[e[0].data];for(let o=1;o{e.writable.write({type:t,data:r}).catch((()=>{}))};return e.stdout?.on("data",(e=>{const n=t.note(e);void 0!==n&&n.length>0&&r("stdout",n)})),e.stderr?.on("data",(e=>{r("stderr",e)})),{get stdoutBytes(){return t.bytes},get stdoutPrefix(){return t.stdoutPrefix},async waitForOutput(){},async releaseHeldStdout(){const e=t.takeHeld();void 0!==e&&e.length>0&&r("stdout",e)},dropHeldStdout(){t.takeHeld()},async flush(){await this.releaseHeldStdout()}}}const r=new Nr(e.writable,e.outputLimiterOptions);let n;const o=Promise.all([jr(e.stdout,r,t),Ur(e.stderr,"stderr",r)]).then((()=>{})).catch((e=>{n=e}));return{get stdoutBytes(){return t.bytes},get stdoutPrefix(){return t.stdoutPrefix},async waitForOutput(){if(await o,void 0!==n)throw(e=n)instanceof Error?e:new Error(String(e));var e},async releaseHeldStdout(){const e=t.takeHeld();void 0!==e&&e.length>0&&await r.push("stdout",e)},dropHeldStdout(){t.takeHeld()},async flush(){await this.releaseHeldStdout(),await r.flush()}}}async function jr(e,t,r){if(e)for await(const n of e){const e=r.note(n);void 0!==e&&e.length>0&&await t.push("stdout",e)}}async function Ur(e,t,r,n){if(e)for await(const o of e)n?.(o),await r.push(t,o)}var Br;!function(e){e.Zsh="zsh",e.ZshLight="zsh-light",e.Bash="bash",e.PowerShell="powershell",e.Naive="naive"}(Br||(Br={}));const Wr={TERM:"dumb",NO_COLOR:"1",FORCE_COLOR:"0",_ZO_DOCTOR:"0"};function Hr(e){return"win32"===e.platform?"windows_tree":e.detached?"process_group":"single_process"}function qr(e,t,r,o={spawn:n.spawn,killPid:process.kill.bind(process)}){const s=e.pid;if(void 0===s)return;const i=()=>{try{e.kill(r)}catch{}};switch(t){case"process_group":try{o.killPid(-s,r)}catch{i()}return;case"windows_tree":try{o.spawn("taskkill",["/pid",String(s),"/t","/f"],{stdio:"ignore",windowsHide:!0}).on("error",i)}catch{i()}return;case"single_process":return void i();default:throw new Error(`Unknown process tree kill mode: ${String(t)}`)}}function zr(e,t=[],r={},n,o){const s=xr(e,t,{...r,env:I(r.env??process.env)},n);return o?Vr(s,{detached:!0===r.detached},o):Gr(s,!0===r.detached),s}function Gr(e,t){"single_process"!==Hr({platform:process.platform,detached:t})&&e.pid}function Vr(e,t,r){const n=Hr({platform:process.platform,detached:t.detached});Gr(e,t.detached);const o=()=>{if(!e.pid)return;qr(e,n,"SIGTERM");const t=setTimeout((()=>{!e.killed&&e.pid&&qr(e,n,"SIGKILL")}),1e3);"process_group"!==n&&e.once("exit",(()=>{clearTimeout(t)}))};r.aborted?o():(r.addEventListener("abort",o,{once:!0}),e.once("exit",(()=>{r.removeEventListener("abort",o)})))}function Kr(e,t,r){if(e){try{process.kill(-e,t)}catch{return}"SIGTERM"===t&&void 0!==r&&r>0&&setTimeout((()=>{try{process.kill(-e,"SIGKILL")}catch{}}),r)}}const Jr=new Set(["SIGTERM","SIGINT","SIGHUP","SIGQUIT","SIGKILL"]);function Zr(e,t,r){null!==t&&Jr.has(t)&&!r&&"win32"!==process.platform&&Kr(e,t)}function Xr(e,{shellName:t,closeGraceMs:r,timeoutMs:n}){const o=r??5e3,s=n??6e4;return new Promise((r=>{const n=[];let i;const a=e=>{n.push(e)},c=()=>{clearTimeout(d),o<=0||(i=setTimeout((()=>{console.warn(`[shell-exec] ${t} state init exited but its stdio did not close within ${o}ms; a startup file left a background process holding the output pipe. Proceeding with the dump received so far.`),u("exit_without_close")}),o))},l=()=>{u("closed")},u=t=>{clearTimeout(d),clearTimeout(i),e.off("exit",c),e.off("close",l),e.stdout?.off("data",a),e.stdout?.resume(),r({outcome:t,stdout:Buffer.concat(n).toString("utf8")})},d=s>0?setTimeout((()=>{console.warn(`[shell-exec] ${t} state init did not exit within ${s}ms; a startup file is blocking. Killing it and falling back to an empty state.`),qr(e,Hr({platform:process.platform,detached:!0}),"SIGKILL"),u("timed_out")}),s):void 0;e.stdout?.on("data",a),Qr(e.stdout),e.on("exit",c),e.on("close",l)}))}function Qr(e){e?.on("error",(()=>{}))}function Yr(e){e.removeAllListeners(),e.on("error",(()=>{})),e.stdout?.removeAllListeners("close"),e.stderr?.removeAllListeners("close");for(const t of e.stdio.slice(3))t?.destroy()}const en="IFS= builtin read -r -d '' __cursor_command <&5 2>/dev/null || { builtin printf '%s\\n' 'The command did not run: a shell startup file ($BASH_ENV or .zshenv) closed or replaced file descriptor 5, which carries the command. Run it again; this shell now passes commands as arguments.' >&2; builtin exit 126; }; exec 5<&-; builtin set -- \"$__cursor_command\"; builtin unset __cursor_command; ";function tn(e,t){return 126===e&&""===t}function rn(){return"win32"!==process.platform}function nn(e,t){const r=e.stdio.at(5);r instanceof Ir.Writable&&(Qr(r),r.end(`${t}\0`))}function on(e,t){e&&(Qr(e),e.write(t),e.end())}function sn(e,t){if(!e)return;Qr(e);const r=new Dr.StringDecoder("utf8");e.on("data",(e=>{const n=r.write(e);""!==n&&t(n)})),e.on("end",(()=>{const e=r.end();""!==e&&t(e)}))}function an(e){const t=e.indexOf("\n");return{cwd:Buffer.from(e.substring(0,t),"utf16le").toString("utf16le"),rest:e.substring(t)}}function cn(e,t){const r=t instanceof Error&&"code"in t&&"string"==typeof t.code?t.code:"unknown";console.warn(e,r)}function ln(e,t){const r=`${t}\n`,n=e.indexOf(r);return n>=0?e.slice(n+r.length):e}function un(e){return!1===e?.isLoginShellEnabled?"-ic":"-ilc"}function dn(e,t,r){const n=`${t}\n`;if(!e.startsWith(n))return;const o=e.indexOf(`\n${r}\n`,n.length-1);return o<0?void 0:e.slice(n.length,o+1)}const hn="__CURSOR_BASH_STATE_START__",pn="__CURSOR_BASH_STATE_END__",fn="\n Emit $PWD.Path\n #Log-Timing \"working_dir\"\n\n function ShouldPersistEnvVar {\n param([string]$Name)\n if ($Name -eq 'CURSOR_CONVERSATION_ID') {\n return $false\n }\n if ($Name -eq 'CURSOR_REQUEST_ID') {\n return $false\n }\n if ($Name -like 'CURSOR_AGENT_STORE*') {\n return $false\n }\n if ($Name -like '*CURSOR_SANDBOX*') {\n return $false\n }\n if ($Name -eq 'ELECTRON_RUN_AS_NODE') {\n return $false\n }\n return $true\n }\n\n $envVars = Get-ChildItem Env: | Sort-Object Name\n foreach ($var in $envVars) {\n if (-not (ShouldPersistEnvVar -Name $var.Name)) {\n continue\n }\n $encoded = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes([string]$var.Value))\n Emit ('Set-Item -LiteralPath ''Env:{0}'' -Value ([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String(''{1}'')))' -f $var.Name, $encoded)\n }\n #Log-Timing \"environment\"\n\n $aliases = Get-Alias | Sort-Object Name\n foreach ($alias in $aliases) {\n $definition = $alias.Definition\n\n if ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::ReadOnly) {\n }\n elseif ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::Constant) {\n }\n elseif ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::AllScope) {\n }\n else {\n Emit ('Set-Alias -Name \"{0}\" -Value \"{1}\"' -f $alias.Name, $definition)\n }\n }\n\n #Log-Timing \"finalize\"\n",mn=`\nfunction Dump-PowerShellState {\n param(\n [Parameter(Mandatory = $true)]\n [string]$OutputFile\n )\n\n function Emit {\n param([string]$Content)\n Add-Content -Path $OutputFile -Value $Content -Encoding UTF8\n }\n\n if (Test-Path $OutputFile) {\n Remove-Item $OutputFile -Force\n }\n New-Item -Path $OutputFile -ItemType File -Force | Out-Null\n #Log-Timing "file_init"\n${fn}}\n`,gn=`\nfunction Dump-PowerShellState {\n param(\n [Parameter(Mandatory = $true)]\n [string]$OutputFile,\n [string]$Trailer\n )\n\n $__cursorDumpText = New-Object System.Text.StringBuilder\n $__cursorDumpNewLine = [Environment]::NewLine\n function Emit {\n param([string]$Content)\n [void]$__cursorDumpText.Append($Content).Append($__cursorDumpNewLine)\n }\n${fn}\n if ($Trailer) {\n Emit $Trailer\n }\n [System.IO.File]::WriteAllText($OutputFile, $__cursorDumpText.ToString(), (New-Object System.Text.UTF8Encoding ($PSVersionTable.PSVersion.Major -lt 6)))\n}\n`,wn="# cursor-shell-timings ",yn="[long](([DateTime]::UtcNow.Ticks - 621355968000000000) / 10000)",vn="\ntry { [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\ntry { [Console]::InputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\ntry { $global:OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\n",bn=e=>e.map((e=>`'${e}'`)).join(", "),Sn=` # The body of the proxy for Set-Content and Export-Csv. Its param block comes from the\n # cmdlet itself. Every step of its own is guarded, so a failure in the proxy leaves the\n # file as the cmdlet writes it.\n $__cursorProxyBody = @'\nbegin {\n # The file system paths the call writes, each with its own 'bom' or 'nobom', and what each\n # held before the call; the call gets -Encoding only when every path has a decision.\n $__cursorFiles = $null\n $__cursorDecisions = @{}\n $__cursorBefore = @{}\n $__cursorDecided = $false\n # The command line asked for UTF8 by name, for files whose readers take it without a BOM.\n $__cursorAsked = $false\n $__cursorStrip = $false\n $__cursorStopped = $false\n $__cursorScopeBound = $null\n $__cursorInvoked = "$($MyInvocation.InvocationName)"\n # The first 8 KiB of the file and its length; $null for a file that does not exist.\n $__cursorHeadOf = {\n param([string]$__cursorFile)\n if (-not [System.IO.File]::Exists($__cursorFile)) { return $null }\n $__cursorHead = New-Object byte[] 8192\n $__cursorCount = 0\n $__cursorStream = [System.IO.File]::Open($__cursorFile, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite -bor [System.IO.FileShare]::Delete)\n try {\n $__cursorLength = $__cursorStream.Length\n while ($__cursorCount -lt $__cursorHead.Length) {\n $__cursorRead = $__cursorStream.Read($__cursorHead, $__cursorCount, $__cursorHead.Length - $__cursorCount)\n if ($__cursorRead -le 0) { break }\n $__cursorCount += $__cursorRead\n }\n } finally { $__cursorStream.Dispose() }\n return @{ Length = $__cursorLength; Head = $__cursorHead; Count = $__cursorCount }\n }\n # 'bom' or 'nobom' for a file the proxy writes in UTF-8, $null for one it leaves to the\n # cmdlet: the file's own bytes decide when it has content, its extension otherwise.\n $__cursorEncodingOf = {\n param([string]$__cursorFile, $__cursorWas)\n $__cursorExtension = [System.IO.Path]::GetExtension($__cursorFile).ToLowerInvariant()\n if ($__cursorExtension -in @(${bn([".bat",".cmd",".reg",".ini",".inf",".vbs",".vbe",".wsf"])})) { return $null }\n if ([System.IO.Directory]::Exists($__cursorFile)) { return $null }\n if ($null -ne $__cursorWas -and $__cursorWas.Count -gt 0) {\n $__cursorHead = $__cursorWas.Head\n $__cursorEnd = $__cursorWas.Count\n if ($__cursorEnd -ge 3 -and $__cursorHead[0] -eq 0xEF -and $__cursorHead[1] -eq 0xBB -and $__cursorHead[2] -eq 0xBF) { return 'bom' }\n if ($__cursorEnd -ge 2 -and (($__cursorHead[0] -eq 0xFF -and $__cursorHead[1] -eq 0xFE) -or ($__cursorHead[0] -eq 0xFE -and $__cursorHead[1] -eq 0xFF))) { return $null }\n if ($__cursorEnd -eq $__cursorHead.Length) {\n # A full header may end inside a character; that character is left out.\n $__cursorAt = $__cursorEnd - 1\n while ($__cursorAt -gt $__cursorEnd - 4 -and ($__cursorHead[$__cursorAt] -band 0xC0) -eq 0x80) { $__cursorAt-- }\n if ($__cursorHead[$__cursorAt] -ge 0xC0) {\n $__cursorNeed = if ($__cursorHead[$__cursorAt] -ge 0xF0) { 4 } elseif ($__cursorHead[$__cursorAt] -ge 0xE0) { 3 } else { 2 }\n if ($__cursorEnd - $__cursorAt -lt $__cursorNeed) { $__cursorEnd = $__cursorAt }\n }\n }\n # A strict decode throws on bytes that are not UTF-8; a character beyond ASCII takes\n # more bytes than code units, so all-ASCII content is the one that decodes to as many.\n try { $__cursorText = [System.Text.UTF8Encoding]::new($false, $true).GetString($__cursorHead, 0, $__cursorEnd) } catch { return $null }\n if ($__cursorText.Length -lt $__cursorEnd) { return 'nobom' }\n }\n if ($__cursorExtension -in @(${bn([".ps1",".psm1",".psd1"])})) { return 'bom' }\n if ($__cursorExtension -in @(${bn([".py",".pyw",".pyi",".js",".mjs",".cjs",".jsx",".ts",".tsx",".mts",".cts",".go",".rs",".kt",".kts",".scala",".swift",".dart",".rb",".cs",".fs",".fsx",".vb",".razor",".cshtml",".sh",".bash",".zsh",".html",".htm",".css",".scss",".sass",".less",".vue",".svelte",".json",".jsonc",".json5",".yaml",".yml",".toml",".xml",".xsd",".xsl",".xslt",".svg",".csproj",".props",".targets",".graphql",".gql",".proto",".tf",".hcl",".md",".markdown",".mdx",".rst",".adoc",".gitignore",".gitattributes",".gitmodules",".editorconfig",".cursorignore",".cursorindexingignore",".mdc"])})) { return 'nobom' }\n return $null\n }\n # Whether the -Encoding the call bound is the UTF-8 with a BOM that Windows PowerShell names\n # UTF8. PowerShell 7 binds the encoding object of that name, and reaches this only when a\n # test fakes the version.\n $__cursorIsUtf8Bom = {\n param($__cursorEncoding)\n if ($__cursorEncoding -is [System.Text.Encoding]) { return ($__cursorEncoding -is [System.Text.UTF8Encoding] -and $__cursorEncoding.GetPreamble().Length -gt 0) }\n return ("$__cursorEncoding" -eq 'UTF8')\n }\n # Whether a default under $PSDefaultParameterValues can reach this call's -Encoding: under\n # the cmdlet's name, an alias it had when the proxy was built, or the name the call used. A\n # value such a default put in $PSBoundParameters is not one the command line asked for.\n $__cursorHasEncodingDefault = {\n param([string]$__cursorInvoked)\n foreach ($__cursorKey in @($PSDefaultParameterValues.Keys)) {\n $__cursorKeyParts = "$__cursorKey" -split ':', 2\n if ($__cursorKeyParts.Count -ne 2 -or 'Encoding' -notlike $__cursorKeyParts[1].Trim()) { continue }\n foreach ($__cursorName in @(__CURSORNAMES__, $__cursorInvoked)) {\n if ($__cursorName -like $__cursorKeyParts[0].Trim()) { return $true }\n }\n }\n return $false\n }\n # Whether a UTF8 asked for by name is UTF-8 without a BOM for this file: one whose reader\n # rejects a BOM, and that is new, empty or starts with no BOM of any encoding.\n $__cursorTakesNoBom = {\n param([string]$__cursorFile, $__cursorWas)\n if ([System.IO.Directory]::Exists($__cursorFile)) { return $false }\n if ([System.IO.Path]::GetExtension($__cursorFile).ToLowerInvariant() -notin @(${bn([".json",".py",".js",".ts",".sh",".yaml",".toml",".mdc"])}) -and\n [System.IO.Path]::GetFileName($__cursorFile).ToLowerInvariant() -notin @(${bn([".gitignore",".editorconfig"])})) { return $false }\n if ($null -eq $__cursorWas -or $__cursorWas.Count -lt 2) { return $true }\n $__cursorHead = $__cursorWas.Head\n if ($__cursorWas.Count -ge 3 -and $__cursorHead[0] -eq 0xEF -and $__cursorHead[1] -eq 0xBB -and $__cursorHead[2] -eq 0xBF) { return $false }\n if (($__cursorHead[0] -eq 0xFF -and $__cursorHead[1] -eq 0xFE) -or ($__cursorHead[0] -eq 0xFE -and $__cursorHead[1] -eq 0xFF)) { return $false }\n if ($__cursorWas.Count -ge 4 -and $__cursorHead[0] -eq 0 -and $__cursorHead[1] -eq 0 -and $__cursorHead[2] -eq 0xFE -and $__cursorHead[3] -eq 0xFF) { return $false }\n return $true\n }\n # Takes a UTF-8 BOM off the front of the file in place, unless it is to stay and the\n # content has a character beyond ASCII. A file the cmdlet left as it was is not touched.\n $__cursorStripBom = {\n param([string]$__cursorFile, [bool]$__cursorKeepUnlessAscii, $__cursorWas)\n if (-not [System.IO.File]::Exists($__cursorFile)) { return }\n $__cursorStream = $null\n # The cmdlet may still hold the file for a moment after it returns.\n for ($__cursorAttempt = 0; $__cursorAttempt -lt 5 -and $null -eq $__cursorStream; $__cursorAttempt++) {\n try { $__cursorStream = [System.IO.File]::Open($__cursorFile, [System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None) }\n catch [System.IO.FileNotFoundException] { return }\n catch [System.IO.DirectoryNotFoundException] { return }\n catch [System.IO.IOException] { Start-Sleep -Milliseconds 20 }\n catch { return }\n }\n if ($null -eq $__cursorStream) { return }\n try {\n $__cursorBuffer = New-Object byte[] 65536\n if ($null -ne $__cursorWas -and $__cursorWas.Length -eq $__cursorStream.Length) {\n $__cursorCount = 0\n while ($__cursorCount -lt $__cursorWas.Count) {\n $__cursorRead = $__cursorStream.Read($__cursorBuffer, $__cursorCount, $__cursorWas.Count - $__cursorCount)\n if ($__cursorRead -le 0) { break }\n $__cursorCount += $__cursorRead\n }\n if ($__cursorCount -eq $__cursorWas.Count -and [System.Convert]::ToBase64String($__cursorBuffer, 0, $__cursorCount) -eq [System.Convert]::ToBase64String($__cursorWas.Head, 0, $__cursorCount)) { return }\n $__cursorStream.Position = 0\n }\n if ($__cursorStream.Read($__cursorBuffer, 0, 3) -ne 3 -or $__cursorBuffer[0] -ne 0xEF -or $__cursorBuffer[1] -ne 0xBB -or $__cursorBuffer[2] -ne 0xBF) { return }\n if ($__cursorKeepUnlessAscii) {\n while (($__cursorRead = $__cursorStream.Read($__cursorBuffer, 0, $__cursorBuffer.Length)) -gt 0) {\n if ([regex]::IsMatch([System.Text.Encoding]::UTF8.GetString($__cursorBuffer, 0, $__cursorRead), '[^\\x00-\\x7F]')) { return }\n }\n }\n $__cursorReadAt = 3L\n $__cursorWriteAt = 0L\n while ($__cursorReadAt -lt $__cursorStream.Length) {\n $__cursorStream.Position = $__cursorReadAt\n $__cursorRead = $__cursorStream.Read($__cursorBuffer, 0, $__cursorBuffer.Length)\n if ($__cursorRead -le 0) { break }\n $__cursorStream.Position = $__cursorWriteAt\n $__cursorStream.Write($__cursorBuffer, 0, $__cursorRead)\n $__cursorReadAt += $__cursorRead\n $__cursorWriteAt += $__cursorRead\n }\n $__cursorStream.SetLength($__cursorWriteAt)\n } catch { } finally { $__cursorStream.Dispose() }\n }\n try {\n $__cursorBound = $null\n if ($PSBoundParameters.ContainsKey('Path')) { $__cursorBound = @{ Path = $PSBoundParameters['Path'] } }\n elseif ($PSBoundParameters.ContainsKey('LiteralPath')) { $__cursorBound = @{ LiteralPath = $PSBoundParameters['LiteralPath'] } }\n if ($null -ne $__cursorBound) {\n # The file system paths that -Path or -LiteralPath names; none when one is on another\n # provider or a wildcard matches nothing.\n $__cursorLiteral = $__cursorBound.ContainsKey('LiteralPath')\n $__cursorFiles = New-Object System.Collections.Generic.List[string]\n foreach ($__cursorPath in @(@($__cursorBound.Values)[0])) {\n $__cursorProvider = $null\n $__cursorDrive = $null\n if ($__cursorLiteral -or -not [System.Management.Automation.WildcardPattern]::ContainsWildcardCharacters("$__cursorPath")) {\n $__cursorResolved = @($ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath("$__cursorPath", [ref]$__cursorProvider, [ref]$__cursorDrive))\n } else {\n $__cursorResolved = @($ExecutionContext.SessionState.Path.GetResolvedProviderPathFromPSPath("$__cursorPath", [ref]$__cursorProvider))\n }\n if ($null -ne $__cursorProvider -and $__cursorProvider.Name -in @('Variable', 'Function', 'Alias')) { $__cursorScopeBound = $__cursorProvider.Name }\n if ($null -eq $__cursorProvider -or $__cursorProvider.Name -ne 'FileSystem' -or $__cursorResolved.Count -eq 0) { $__cursorFiles = $null; break }\n $__cursorFiles.AddRange([string[]]$__cursorResolved)\n }\n }\n # -WhatIf sets $WhatIfPreference and -Confirm sets $ConfirmPreference in this scope.\n if ($null -ne $__cursorFiles -and $__cursorFiles.Count -gt 0 -and -not $PSBoundParameters.ContainsKey('Encoding') -and\n -not $WhatIfPreference -and $ConfirmPreference -notin @('Low', 'Medium') -and -not $PSBoundParameters.ContainsKey('Stream') -and\n -not $PSBoundParameters.ContainsKey('Filter') -and -not $PSBoundParameters.ContainsKey('Include') -and\n -not $PSBoundParameters.ContainsKey('Exclude')) {\n $__cursorAppend = ($PSBoundParameters.ContainsKey('Append') -and $PSBoundParameters['Append']) -or ($PSBoundParameters.ContainsKey('NoClobber') -and $PSBoundParameters['NoClobber'])\n $__cursorDecided = $true\n $__cursorStrip = $true\n foreach ($__cursorFile in $__cursorFiles) {\n $__cursorBefore[$__cursorFile] = & $__cursorHeadOf $__cursorFile\n $__cursorDecisions[$__cursorFile] = & $__cursorEncodingOf $__cursorFile $__cursorBefore[$__cursorFile]\n if ($null -eq $__cursorDecisions[$__cursorFile]) { $__cursorDecided = $false; break }\n # An append onto a file with content writes no BOM, so there is none to take off.\n if ($__cursorAppend -and $null -ne $__cursorBefore[$__cursorFile] -and $__cursorBefore[$__cursorFile].Length -gt 0) { $__cursorStrip = $false }\n }\n }\n elseif ($null -ne $__cursorFiles -and $__cursorFiles.Count -gt 0 -and $PSBoundParameters.ContainsKey('Encoding') -and\n (& $__cursorIsUtf8Bom $PSBoundParameters['Encoding']) -and -not (& $__cursorHasEncodingDefault $__cursorInvoked) -and\n -not $WhatIfPreference -and $ConfirmPreference -notin @('Low', 'Medium') -and -not $PSBoundParameters.ContainsKey('Stream') -and\n -not $PSBoundParameters.ContainsKey('Filter') -and -not $PSBoundParameters.ContainsKey('Include') -and\n -not $PSBoundParameters.ContainsKey('Exclude')) {\n # The UTF8 the command line asked for is UTF-8 with a BOM on this shell and without\n # one on PowerShell 7. For a file whose reader rejects a BOM, and that has none, it\n # means what it means there: the cmdlet writes its BOM, and the proxy takes it off.\n $__cursorAsked = $true\n foreach ($__cursorFile in $__cursorFiles) {\n $__cursorBefore[$__cursorFile] = & $__cursorHeadOf $__cursorFile\n if (-not (& $__cursorTakesNoBom $__cursorFile $__cursorBefore[$__cursorFile])) { $__cursorAsked = $false; break }\n $__cursorDecisions[$__cursorFile] = 'nobom'\n }\n $__cursorStrip = $__cursorAsked\n }\n } catch { $__cursorDecided = $false; $__cursorAsked = $false }\n if ($__cursorDecided) { $PSBoundParameters['Encoding'] = '__CURSORUTF8__' }\n if ($null -ne $__cursorScopeBound) {\n Write-Warning "__CURSORNAME__ runs through a function in this shell, so an item it writes to the $__cursorScopeBound provider lives in a scope that ends with the call. Use an assignment, a function definition or Set-Alias instead."\n }\n # An error the caller asked to stop on ends the caller too, as it does from the cmdlet: it\n # goes on as it is, as from the proxy PowerShell itself generates, which rethrows everything\n # with 'throw'. Any other terminating error of the cmdlet ends the statement and the caller\n # goes on; ThrowTerminatingError keeps that rule, where 'throw' would end the caller's whole\n # script, and the pipeline it ended is not stepped again. Of the two, only the cmdlet's own\n # terminating error names this function rather than the cmdlet's type in the suffix of its\n # FullyQualifiedErrorId; the record of an error the caller asked to stop on is the cmdlet's.\n try {\n $outBuffer = $null\n if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 }\n $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('__CURSORTARGET__', [System.Management.Automation.CommandTypes]::Cmdlet)\n $scriptCmd = { & $wrappedCmd @PSBoundParameters }\n $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)\n $steppablePipeline.Begin($PSCmdlet)\n } catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n}\nprocess {\n if ($__cursorStopped) { return }\n try { $steppablePipeline.Process($_) }\n catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n}\nend {\n if ($__cursorStopped) { return }\n try { $steppablePipeline.End() }\n catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n if (-not $__cursorStrip -or -not ($__cursorDecided -or $__cursorAsked)) { return }\n try {\n foreach ($__cursorFile in $__cursorFiles) { & $__cursorStripBom $__cursorFile ($__cursorDecisions[$__cursorFile] -eq 'bom') $__cursorBefore[$__cursorFile] }\n } catch { }\n}\n'@\n foreach ($__cursorWriter in @('Set-Content', 'Export-Csv')) {\n $__cursorWriterNames = @($__cursorWriter) + @(Get-Alias -Definition $__cursorWriter -ErrorAction Ignore | ForEach-Object { $_.Name })\n $__cursorHasWriterDefault = $false\n foreach ($__cursorKey in @($PSDefaultParameterValues.Keys)) {\n $__cursorKeyParts = "$__cursorKey" -split ':', 2\n if ($__cursorKeyParts.Count -ne 2 -or 'Encoding' -notlike $__cursorKeyParts[1].Trim()) { continue }\n foreach ($__cursorName in $__cursorWriterNames) {\n if ($__cursorName -like $__cursorKeyParts[0].Trim()) { $__cursorHasWriterDefault = $true }\n }\n }\n if ($__cursorHasWriterDefault) { continue }\n try {\n # A function of this name that a profile defined stays in charge; the proxy is built on the cmdlet alone.\n $__cursorCmdlet = @(Microsoft.PowerShell.Core\\Get-Command -Name $__cursorWriter -ErrorAction Stop)[0]\n if ($__cursorCmdlet.CommandType -eq 'Cmdlet') {\n $__cursorTarget = "$($__cursorCmdlet.ModuleName)\\$($__cursorCmdlet.Name)"\n $__cursorMetadata = New-Object System.Management.Automation.CommandMetadata $__cursorCmdlet\n $__cursorNamesList = @($__cursorWriterNames | ForEach-Object { "'" + $_.Replace("'", "''") + "'" }) -join ', '\n $__cursorProxyText = @(\n '<#', ".ForwardHelpTargetName $__cursorTarget", '.ForwardHelpCategory Cmdlet', '#>',\n [System.Management.Automation.ProxyCommand]::GetCmdletBindingAttribute($__cursorMetadata),\n 'param(', [System.Management.Automation.ProxyCommand]::GetParamBlock($__cursorMetadata), ')',\n 'dynamicparam {', [System.Management.Automation.ProxyCommand]::GetDynamicParam($__cursorMetadata), '}',\n $__cursorProxyBody.Replace('__CURSORTARGET__', $__cursorTarget).Replace('__CURSORNAMES__', $__cursorNamesList).Replace('__CURSORNAME__', $__cursorCmdlet.Name).Replace('__CURSORUTF8__', $__cursorUtf8)\n ) -join [Environment]::NewLine\n # Global, as a profile would define it, so that a module's code reaches it too.\n Microsoft.PowerShell.Management\\Set-Item -LiteralPath "function:global:$__cursorWriter" -Value ([scriptblock]::Create($__cursorProxyText)) -ErrorAction Stop\n }\n } catch { }\n }`,kn=String.raw` function global:__cursorUtf8FromLatin1 { param([string]$Text) Set-StrictMode -Off @@ -81,12 +81,12 @@ index ea133a0f358555bcf9393dba47563ffb208f24ad..10bef97ace282f9c83523150bd73e49c +(()=>{"use strict";var t,r,e,n={"./src/agent/analytics-agent-name.ts"(t,r,e){function n(t){if("string"!=typeof t)return;const r=t.trim();return r.length>0?r:void 0}e.d(r,{o:()=>n})},"./src/agent/analytics-prompt-hash.ts"(t,r,e){e.d(r,{E:()=>s});var n=e("node:crypto");function s(t){if("string"==typeof t&&0!==t.length)return(0,n.createHash)("sha256").update(t,"utf8").digest("hex")}},"./src/agent/analytics.ts"(t,r,e){e.d(r,{rd:()=>Q,ou:()=>rt,GY:()=>Y,CI:()=>Z,id:()=>et,G5:()=>X,Zn:()=>V,pL:()=>tt});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");const i="aiserver.v1.";class o extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return i}}var a=(0,s.QT)(n.proto3,i,"ClientOS",[[0,"CLIENT_OS_UNSPECIFIED"],[1,"CLIENT_OS_WINDOWS"],[2,"CLIENT_OS_MACOS"],[3,"CLIENT_OS_LINUX"],[4,"CLIENT_OS_IOS"],[5,"CLIENT_OS_ANDROID"]]),u=(0,s.QT)(n.proto3,i,"ClientLogLevel",[[0,"UNSPECIFIED"],[1,"INFO"],[2,"DEBUG"],[3,"WARN"],[4,"ERROR"]],1),c=(0,s.QT)(n.proto3,i,"StatsigExposureKind",[[0,"UNSPECIFIED"],[1,"FEATURE_GATE"],[2,"EXPERIMENT"],[3,"DYNAMIC_CONFIG"],[4,"LAYER_PARAMETER"]],1);class l extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["BootstrapStatsigRequest|1 ignore_dev_status 8?|2 operating_system #0?|3 device_model 9?|4 os_version 9?|5 form_factor 9?|6 stable_id 9?|7 client_channel 9?|8 bundle_id 9?|9 mobile_app_store_country 9?|10 native_build 9?|11 ota_update_id 9?|12 ota_runtime_version 9?|13 ota_embedded_launch 8?|14 previous_response_hash 9?|15 name_filter #1|16 grok_build_version 9?|17 grok_build_channel 9?|18 sign_in_email 9?",a,m]}}class m extends o{constructor(t){super(),this.gates=[],this.configs=[],this.layers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["BootstrapStatsigRequest.NameFilter|1 gates 9*|2 configs 9*|3 layers 9*"]}}class f extends o{constructor(t){super(),this.config="",this.generatedAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["BootstrapStatsigResponse|1 config 9|2 generated_at_ms 4"]}}class d extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["GetFirstWindowStatsigDecisionRequest|1 operating_system #0?",a]}}class p extends o{constructor(t){super(),this.variant="",this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["GetFirstWindowStatsigDecisionResponse|1 variant 9|2 reason 9"]}}class h extends o{constructor(t){super(),this.name="",this.kind=c.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["StatsigExposure|1 name 9|2 kind #0|3 parameter 9?",c]}}class g extends o{constructor(t){super(),this.exposures=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["LogStatsigExposuresRequest|1 exposures #0*|2 ignore_dev_status 8?|3 operating_system #1?|4 grok_build_version 9?|5 grok_build_channel 9?",h,a]}}class _ extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _).fromBinary(t,r)}static fromJson(t,r){return(new _).fromJson(t,r)}static fromJsonString(t,r){return(new _).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_,t,r)}static $(){return["LogStatsigExposuresResponse"]}}class J extends o{constructor(t){super(),this.data={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new J).fromBinary(t,r)}static fromJson(t,r){return(new J).fromJson(t,r)}static fromJsonString(t,r){return(new J).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(J,t,r)}static $(){return["EventData|1 string_value 9 data|2 int_value 3 data|3 bool_value 8 data|4 double_value 1 data"]}}class w extends o{constructor(t){super(),this.eventName="",this.eventData={},this.timestamp=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new w).fromBinary(t,r)}static fromJson(t,r){return(new w).fromJson(t,r)}static fromJsonString(t,r){return(new w).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(w,t,r)}static $(){return["AnalyticsEvent|1 event_name 9|2 event_data 9,#0|3 timestamp 3",J]}}class y extends o{constructor(t){super(),this.events=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new y).fromBinary(t,r)}static fromJson(t,r){return(new y).fromJson(t,r)}static fromJsonString(t,r){return(new y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(y,t,r)}static $(){return["TrackEventsRequest|1 events #0*",w]}}class S extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new S).fromBinary(t,r)}static fromJson(t,r){return(new S).fromJson(t,r)}static fromJsonString(t,r){return(new S).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(S,t,r)}static $(){return["TrackEventsResponse"]}}class q extends o{constructor(t){super(),this.event="",this.timestamp=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new q).fromBinary(t,r)}static fromJson(t,r){return(new q).fromJson(t,r)}static fromJsonString(t,r){return(new q).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(q,t,r)}static $(){return["BatchEvent|1 event 9|2 properties #0|3 timestamp 3|4 user_id 9?|5 anonymous_id 9?|6 message_id 9?|7 context #1?",n.Struct,B]}}class B extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new B).fromBinary(t,r)}static fromJson(t,r){return(new B).fromJson(t,r)}static fromJsonString(t,r){return(new B).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(B,t,r)}static $(){return["AnalyticsContext|1 client #0?",I]}}class I extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new I).fromBinary(t,r)}static fromJson(t,r){return(new I).fromJson(t,r)}static fromJsonString(t,r){return(new I).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(I,t,r)}static $(){return["ClientInfo|1 os 9?|2 arch 9?|3 os_version 9?|4 version 9?|5 layout 9?|6 glass_renderer 9?"]}}class P extends o{constructor(t){super(),this.events=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new P).fromBinary(t,r)}static fromJson(t,r){return(new P).fromJson(t,r)}static fromJsonString(t,r){return(new P).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(P,t,r)}static $(){return["BatchRequest|1 events #0*",q]}}class b extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new b).fromBinary(t,r)}static fromJson(t,r){return(new b).fromJson(t,r)}static fromJsonString(t,r){return(new b).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(b,t,r)}static $(){return["BatchResponse"]}}class R extends o{constructor(t){super(),this.level=u.UNSPECIFIED,this.message="",this.metadata={},this.timestamp=n.protoInt64.zero,this.key="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new R).fromBinary(t,r)}static fromJson(t,r){return(new R).fromJson(t,r)}static fromJsonString(t,r){return(new R).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(R,t,r)}static $(){return["ClientLogEntry|1 level #0|2 message 9|3 metadata 9,9|4 timestamp 3|5 error_message 9?|6 error_stack 9?|7 key 9",u]}}class v extends o{constructor(t){super(),this.logs=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new v).fromBinary(t,r)}static fromJson(t,r){return(new v).fromJson(t,r)}static fromJsonString(t,r){return(new v).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(v,t,r)}static $(){return["SubmitLogsRequest|1 logs #0*",R]}}class x extends o{constructor(t){super(),this.success=!1,this.logsProcessed=0,this.logsDropped=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new x).fromBinary(t,r)}static fromJson(t,r){return(new x).fromJson(t,r)}static fromJsonString(t,r){return(new x).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(x,t,r)}static $(){return["SubmitLogsResponse|1 success 8|2 error_message 9?|3 logs_processed 13|4 logs_dropped 13"]}}class k extends o{constructor(t){super(),this.conversationId="",this.transcript="",this.lastUpdatedAt=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new k).fromBinary(t,r)}static fromJson(t,r){return(new k).fromJson(t,r)}static fromJsonString(t,r){return(new k).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(k,t,r)}static $(){return["IngestConversationRequest|1 conversation_id 9|2 transcript 9|3 transcript_json 9?|4 mode 9?|5 model 9?|6 last_updated_at 3"]}}class E extends o{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new E).fromBinary(t,r)}static fromJson(t,r){return(new E).fromJson(t,r)}static fromJsonString(t,r){return(new E).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(E,t,r)}static $(){return["IngestConversationResponse|1 success 8|2 summary 9?|3 detailed_summary 9?|4 error_message 9?"]}}class C extends o{constructor(t){super(),this.token="",this.payload="",this.payloadHash="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new C).fromBinary(t,r)}static fromJson(t,r){return(new C).fromJson(t,r)}static fromJsonString(t,r){return(new C).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(C,t,r)}static $(){return["UploadIssueTraceRequest|1 token 9|2 payload 9|3 payload_hash 9"]}}class T extends o{constructor(t){super(),this.eventId="",this.size=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new T).fromBinary(t,r)}static fromJson(t,r){return(new T).fromJson(t,r)}static fromJsonString(t,r){return(new T).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(T,t,r)}static $(){return["UploadIssueTraceResponse|1 event_id 9|2 size 3"]}}class U extends o{constructor(t){super(),this.token="",this.limit=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new U).fromBinary(t,r)}static fromJson(t,r){return(new U).fromJson(t,r)}static fromJsonString(t,r){return(new U).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(U,t,r)}static $(){return["DownloadIssueTracesRequest|1 token 9|2 limit 5"]}}class A extends o{constructor(t){super(),this.data=new Uint8Array(0),this.totalTraces=0,this.totalBytes=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new A).fromBinary(t,r)}static fromJson(t,r){return(new A).fromJson(t,r)}static fromJsonString(t,r){return(new A).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(A,t,r)}static $(){return["DownloadIssueTracesResponse|1 data 12|2 total_traces 5|3 total_bytes 3"]}}var $=e("@connectrpc/connect");function M(t){const r={};if(!t)return r;for(const[e,n]of Object.entries(t))"string"==typeof n?r[e]=new J({data:{case:"stringValue",value:n}}):"number"==typeof n?r[e]=new J({data:{case:"doubleValue",value:n}}):"boolean"==typeof n?r[e]=new J({data:{case:"boolValue",value:n}}):"bigint"==typeof n&&(r[e]=new J({data:{case:"intValue",value:n}}));return r}const O=Symbol("token_check_timeout"),D={[$.Code.Canceled]:"cancelled",[$.Code.Unknown]:"unknown",[$.Code.InvalidArgument]:"invalid_argument",[$.Code.DeadlineExceeded]:"deadline_exceeded",[$.Code.NotFound]:"not_found",[$.Code.AlreadyExists]:"already_exists",[$.Code.PermissionDenied]:"permission_denied",[$.Code.ResourceExhausted]:"resource_exhausted",[$.Code.FailedPrecondition]:"failed_precondition",[$.Code.Unimplemented]:"unimplemented",[$.Code.Internal]:"internal",[$.Code.Unavailable]:"unavailable",[$.Code.DataLoss]:"data_loss",[$.Code.Unauthenticated]:"unauthenticated"};class N{constructor(t){this.buffer=[],this.flushTimer=null,this.activeFlush=null,this.droppedOldestSinceLastOutcome=0,this.client=t.client,this.tokenProvider=t.tokenProvider,this.bufferLimit=t.bufferLimit??200,this.flushIntervalMs=t.flushIntervalMs??3e3,this.normalFlushTimeoutMs=t.normalFlushTimeoutMs??2500,this.onDebug=t.onDebug??(()=>{}),this.onDeliveryOutcome=t.onDeliveryOutcome??(()=>{})}track(t,r,e){const n="number"==typeof e?BigInt(e):BigInt(Date.now()),s=new w({eventName:t,eventData:M(r),timestamp:n});this.buffer.push(s),this.trimRetainedEvents(),this.buffer.length>=this.bufferLimit?this.flushInBackground():this.scheduleFlush()}async flush(t){for(;;){if(this.activeFlush){if(await this.activeFlush,0===this.buffer.length)return;continue}if(0===this.buffer.length)return;const r=this.flushOnce(t);this.activeFlush=r;let e=0;try{e=await r}finally{this.activeFlush===r&&(this.activeFlush=null)}if(0===this.buffer.length||0===e)return}}async flushOnce(t){if(0===this.buffer.length)return 0;const r=this.buffer.slice(),e=new Set(r);this.inFlightEvents=e;const n=new AbortController,s=setTimeout((()=>n.abort()),t);s.unref?.();try{try{const t=await Promise.race([this.tokenProvider.getAccessToken(),new Promise((t=>{n.signal.addEventListener("abort",(()=>t(O)),{once:!0})}))]);if(t===O)return this.onDebug("analytics.flush.deferred",{reason:"token_check_timed_out",count:this.buffer.length}),this.releaseInFlightEvents(),this.reportRetained("token_check_timed_out"),0;if(!t)return this.onDebug("analytics.flush.deferred",{reason:"no_token",count:this.buffer.length}),this.releaseInFlightEvents(),this.reportRetained("no_token"),0}catch(t){return this.onDebug("analytics.flush.deferred",{reason:"token_check_failed",error:t,count:this.buffer.length}),this.releaseInFlightEvents(),this.reportRetained("token_check_failed"),0}try{return await this.client.trackEvents(new y({events:r}),{signal:n.signal}),this.inFlightEvents=void 0,this.buffer=this.buffer.filter((t=>!e.has(t))),this.reportOutcome({outcome:"sent",sentCount:r.length,retainedCount:this.buffer.length,droppedOldestCount:this.takeDroppedOldestCount(),oldestRowAgeMs:this.oldestRowAgeMs()}),r.length}catch(t){return this.releaseInFlightEvents(),this.onDebug("analytics.flush.error",{error:t}),this.reportRetained("rpc_failed",(i=t,n.signal.aborted?"aborted":i instanceof $.ConnectError?D[i.code]??"other":"other")),0}}finally{clearTimeout(s)}var i}releaseInFlightEvents(){this.inFlightEvents=void 0,this.trimRetainedEvents()}flushInBackground(){this.flush(this.normalFlushTimeoutMs)}reportRetained(t,r){this.reportOutcome({outcome:"retained",reason:t,retainedCount:this.buffer.length,droppedOldestCount:this.takeDroppedOldestCount(),oldestRowAgeMs:this.oldestRowAgeMs(),...void 0===r?{}:{rpcFailureClass:r}})}reportOutcome(t){try{this.onDeliveryOutcome(t)}catch{}}takeDroppedOldestCount(){const t=this.droppedOldestSinceLastOutcome;return this.droppedOldestSinceLastOutcome=0,t}trimRetainedEvents(){let t=(void 0===this.inFlightEvents?this.buffer.length:this.buffer.reduce(((t,r)=>t+(!0===this.inFlightEvents?.has(r)?0:1)),0))-this.bufferLimit;if(t<=0)return;const r=t;this.buffer=this.buffer.filter((r=>t<=0||!0===this.inFlightEvents?.has(r)||(t-=1,!1))),this.droppedOldestSinceLastOutcome+=r}oldestRowAgeMs(){const t=this.buffer[0]?.timestamp;return void 0===t?0:Math.max(0,Date.now()-Number(t))}scheduleFlush(){this.flushTimer||(this.flushTimer=setTimeout((()=>{this.flushTimer=null,this.flushInBackground()}),this.flushIntervalMs),this.flushTimer.unref?.())}}class G{constructor(t,r,e){this.apiKey=t,this.baseUrl=r,this.exchange=e,this.cached=null,this.inflight=null}async getAccessToken(){if(this.cached)return this.cached;if(this.inflight)return this.inflight;const t=this.exchange(this.apiKey,this.baseUrl).then((r=>(this.inflight===t&&(this.cached=r??null),r??null))).catch((()=>null)).finally((()=>{this.inflight===t&&(this.inflight=null)}));return this.inflight=t,this.inflight}invalidate(){this.cached=null,this.inflight=null}}const L={typeName:"aiserver.v1.AnalyticsService",methods:{trackEvents:{name:"TrackEvents",I:y,O:S,kind:n.MethodKind.Unary},batch:{name:"Batch",I:P,O:b,kind:n.MethodKind.Unary},bootstrapStatsig:{name:"BootstrapStatsig",I:l,O:f,kind:n.MethodKind.Unary},getFirstWindowStatsigDecision:{name:"GetFirstWindowStatsigDecision",I:d,O:p,kind:n.MethodKind.Unary},logStatsigExposures:{name:"LogStatsigExposures",I:g,O:_,kind:n.MethodKind.Unary},submitLogs:{name:"SubmitLogs",I:v,O:x,kind:n.MethodKind.Unary},ingestConversation:{name:"IngestConversation",I:k,O:E,kind:n.MethodKind.Unary},uploadIssueTrace:{name:"UploadIssueTrace",I:C,O:T,kind:n.MethodKind.Unary},downloadIssueTraces:{name:"DownloadIssueTraces",I:U,O:A,kind:n.MethodKind.Unary}}};var F=e("./package.json"),K=e("./src/agent/auth/stored-credentials.ts"),z=e("./src/agent/errors.ts"),j=e("./src/agent/executor-common.ts");const H=new Map;function W(t,r,e){const n=(0,K.Lc)(t);if(n)try{(function(t){const r=H.get(t);if(r)return r;const e=(0,j.KU)(t),n=(0,$.createClient)(L,e),s=new G(t,process.env.CURSOR_BACKEND_URL??"https://api2.cursor.sh",j.dC),i=new N({client:n,tokenProvider:s});return H.set(t,i),i})(n).track(r,function(t){const r={surface:"sdk",sdk_version:F.rE,os_platform:process.platform,os_arch:process.arch};for(const[e,n]of Object.entries(t))void 0!==n&&("string"!=typeof n&&"number"!=typeof n&&"boolean"!=typeof n&&"bigint"!=typeof n||(r[e]=n));return r}(e))}catch{}}async function Q(t=2e3){const r=Array.from(H.values());await Promise.allSettled(r.map((r=>r.flush(t))))}function V(t,r){W(t,"sdk.run.created",{...r})}function X(t,r){W(t,"sdk.run.completed",{...r})}function Y(t,r){W(t,"sdk.mcp.admin_tool_limit",{...r})}function Z({apiKey:t,operation:r,runtime:e,error:n}){n instanceof z.v3||401===n.status||W(t,"sdk.operation.failed",{operation:r,runtime:e,error_type:n.name,error_code:n.code,error_status:n.status,error_is_retryable:n.isRetryable,request_id:n.requestId})}function tt(t,r){W(t,"sdk.run.send_latency",{...r})}function rt(t,r){W(t,"sdk.executor.startup",{...r})}function et(t,r){W(t,"sdk.request.pr_opened",{...r})}},"./src/agent/auth/credential-store.ts"(t,r,e){e.d(r,{Nw:()=>u,Tg:()=>c,fZ:()=>l,rJ:()=>a});var n=e("node:fs/promises"),s=e("node:os"),i=e("node:path"),o=e("../utils/dist/private-file.js");function a(){return(0,i.join)((0,s.homedir)(),".cursor","sdk","auth.json")}function u(t){return function(t){return"object"==typeof t&&null!==t&&("version"in t&&1===t.version&&"backendUrl"in t&&"string"==typeof t.backendUrl&&"apiKey"in t&&"string"==typeof t.apiKey&&"createdAtMs"in t&&"number"==typeof t.createdAtMs&&(!("apiKeyExpiresAtMs"in t)||void 0===t.apiKeyExpiresAtMs||"number"==typeof t.apiKeyExpiresAtMs)&&(!("email"in t)||void 0===t.email||"string"==typeof t.email))}(t)?t:void 0}class c{constructor(t){this.filePath=t??a()}get path(){return this.filePath}async load(){let t;try{await(0,o.rV)(this.filePath),t=await(0,n.readFile)(this.filePath,"utf8")}catch{return}try{return u(JSON.parse(t))}catch{return}}async save(t){await(0,o.Pl)(this.filePath,`${JSON.stringify(t,null,2)}\n`)}async clear(){await(0,n.rm)(this.filePath,{force:!0})}}class l{async load(){return this.credentials}async save(t){this.credentials=t}async clear(){this.credentials=void 0}}},"./src/agent/auth/login-flow.ts"(t,r,e){e.d(r,{Fw:()=>o,bi:()=>u,er:()=>f,pi:()=>a});var n=e("node:crypto");function s(t){return t.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function i(t){return t.replace(/\/+$/,"")}function o(t){return i(t??process.env.CURSOR_WEBSITE_URL??"https://cursor.com")}function a(t){return i(t??process.env.CURSOR_BACKEND_URL??"https://api2.cursor.sh")}function u(t){const r=s((0,n.randomBytes)(32)),e=s((0,n.createHash)("sha256").update(r).digest()),i=(0,n.randomUUID)();return{uuid:i,verifier:r,loginUrl:`${t}/loginDeepControl?challenge=${e}&uuid=${i}&mode=login&redirectTarget=sdk`}}function c(t){if(!t.startsWith("{"))return!1;try{const r=JSON.parse(t);if("object"!=typeof r||null===r||!("message"in r))return!1;const e=r.message;return"string"==typeof e&&/^Route \w+:/.test(e)&&e.includes("not found")}catch{return!1}}function l(t){return!0===t?.aborted}function m(t,r){return new Promise((e=>{if(!0===r?.aborted)return void e();const n=()=>{clearTimeout(s),e()},s=setTimeout((()=>{r?.removeEventListener("abort",n),e()}),t);r?.addEventListener("abort",n,{once:!0})}))}async function f(t){const{apiUrl:r,uuid:e,verifier:n,signal:s,onWarning:i,maxAttempts:o=150,baseDelayMs:a=1e3,maxDelayMs:u=1e4}=t;let f=0,d=!1,p=!1;for(let t=0;t=3)return null;await m(o,s);continue}f=0;const a=await t.json();return"object"==typeof(h=a)&&null!==h&&"accessToken"in h&&"string"==typeof h.accessToken&&"refreshToken"in h&&"string"==typeof h.refreshToken?a:null}catch{if(l(s))return null;if(f++,f>=3)return null;await m(o,s)}}var h;return null}},"./src/agent/auth/stored-credentials.ts"(t,r,e){e.d(r,{Lc:()=>u,s1:()=>a});var n=e("node:fs"),s=e("./src/agent/auth/credential-store.ts"),i=e("./src/agent/auth/login-flow.ts");let o;function a(){o=void 0}function u(t){return void 0!==t?t:process.env.CURSOR_API_KEY??function(){const t=function(){const t=Date.now();if(void 0!==o&&t-o.readAtMs<5e3)return o.value;let r;try{const t=(0,n.readFileSync)((0,s.rJ)(),"utf8");r=(0,s.Nw)(JSON.parse(t))}catch{r=void 0}return o={value:r,readAtMs:t},r}();if(void 0!==t&&!(void 0!==t.apiKeyExpiresAtMs&&t.apiKeyExpiresAtMs<=Date.now())&&t.backendUrl===(0,i.pi)())return t.apiKey}()}},"./src/agent/cloud-api-client.ts"(t,r,e){e.d(r,{N_:()=>l,O0:()=>c,nu:()=>u});var n=e("./src/agent/errors.ts"),s=e("./src/agent/executor-common.ts"),i=e("./src/agent/team-id.ts"),o=e("./src/agent/tool-call-utils.ts"),a=e("./src/agent/utils/logger.ts");function u(t){return{usage:t.totalUsage,...void 0!==t.cost?{cost:t.cost}:{},runs:t.runs.map((t=>({runId:t.id,usage:t.usage,...void 0!==t.cost?{cost:t.cost}:{}})))}}function c(t){const r=(0,o.u)(t)?t:{},e="string"==typeof r.result?r.result:void 0,n="string"==typeof r.text?r.text:void 0,s="number"==typeof r.durationMs?r.durationMs:void 0,i=function(t){if((0,o.u)(t)&&"string"==typeof t.message)return{message:t.message,..."string"==typeof t.code?{code:t.code}:{}}}(r.error),a=function(t){if(!(0,o.u)(t)||!Array.isArray(t.branches))return;const r=[];for(const e of t.branches){if(!(0,o.u)(e)||"string"!=typeof e.repoUrl)return;r.push({repoUrl:e.repoUrl,..."string"==typeof e.branch?{branch:e.branch}:{},..."string"==typeof e.prUrl?{prUrl:e.prUrl}:{}})}return{branches:r}}(r.git);return{status:"string"==typeof r.status?r.status:"FINISHED",...void 0!==e?{result:e}:void 0!==n?{result:n}:{},...void 0!==i?{error:i}:{},...void 0!==s?{durationMs:s}:{},...void 0!==a?{git:a}:{}}}class l{constructor(t,r,e){this.baseUrl=r??process.env.CURSOR_BACKEND_URL??"https://api.cursor.com",this.apiKey=t,this.teamId=(0,i.E)(e),this.isLocalhost=/:\/\/(localhost|127\.0\.0\.1)/.test(this.baseUrl),this.useLocalNonVm="true"===process.env.CURSOR_CLOUD_AGENT_USE_LOCAL_NON_VM}async headers(t){await(0,s.ly)(this.apiKey);const r={Authorization:`Bearer ${this.apiKey}`,"x-ghost-mode":(0,s.U)(this.apiKey),"x-cursor-client-version":(0,s.tF)(),"x-cursor-client-type":"sdk"};return void 0!==this.teamId&&(r[i.P]=String(this.teamId)),t?.hasBody&&(r["Content-Type"]="application/json"),this.isLocalhost&&this.useLocalNonVm&&(r["x-background-composer-local-use-non-vm"]="true"),t?.streaming&&(r["x-cursor-streaming"]="true"),t?.idempotencyKey&&(r["Idempotency-Key"]=t.idempotencyKey),r}async request({method:t,path:r,body:e,query:s,idempotencyKey:i,retryable:o=!0}){const u=s?Object.entries(s).filter((([,t])=>void 0!==t)).map((([t,r])=>`${encodeURIComponent(t)}=${encodeURIComponent(String(r))}`)).join("&"):"",c=`${this.baseUrl}${r}${u?`?${u}`:""}`,l=`${t} ${r}`,m=void 0!==e,d=await this.headers({hasBody:m,idempotencyKey:i});let p;a.v.log(`[cloud-api] ${t} ${c}`);try{p=await fetch(c,{method:t,headers:d,...m?{body:JSON.stringify(e)}:{}})}catch(t){throw new n.Dr("Network request failed",{endpoint:l,isRetryable:o,cause:t})}if(!p.ok){const e=await p.text().catch((()=>""));a.v.log(`[cloud-api] ${t} ${r} status=${p.status} ${e}`),this.throwApiError(p.status,e,{endpoint:l,requestId:f(p),retryable:o})}const h=await p.text();if(!h)return{};try{return JSON.parse(h)}catch(t){throw new n.c$("Failed to parse Cursor API response",{endpoint:l,isRetryable:!1,cause:t})}}throwApiError(t,r,e){const s=e.retryable??!0;let i,a,u="unknown",c=r||`Request failed with status ${t}`;try{const t=function(t){const r=(0,o.u)(t)?t:{},e=(0,o.u)(r.error)?r.error:r;return{code:"string"==typeof e.code?e.code:void 0,message:"string"==typeof e.message?e.message:void 0,helpUrl:"string"==typeof e.helpUrl?e.helpUrl:void 0,provider:"string"==typeof e.provider?e.provider:void 0}}(JSON.parse(r));u=t.code??u,c=t.message??c,i=t.helpUrl,a=t.provider}catch{}const l={status:t,code:u,endpoint:e.endpoint,requestId:e.requestId},m=`[${u}] ${c}`;if("integration_not_connected"===u){if(void 0!==i&&void 0!==a)throw new n.VW(m,{...l,helpUrl:i,provider:a,isRetryable:!1});throw new n.j1(m,{...l,isRetryable:!1})}if("feature_unavailable"===u)throw new n.zz(m,{...l,isRetryable:!1});if("agent_busy"===u)throw new n.J1(m,{...l,isRetryable:!1});switch(t){case 401:throw new n.v3(c,{...l,isRetryable:!1});case 429:throw new n.OE(c,{...l,isRetryable:!0});case 400:case 404:case 409:throw new n.j1(m,{...l,isRetryable:!1});default:if(t>=500)throw new n.Dr(m,{...l,isRetryable:s});throw new n.c$(m,{...l,isRetryable:!1})}}async createAgent(t,r){return this.request({method:"POST",path:"/v1/agents",body:t,idempotencyKey:r?.idempotencyKey})}async recoverCreatedAgent(t,r){try{const e=await this.getAgent(t),n=e.latestRunId?.trim();if(e.id!==t||void 0===n||""===n)throw r;const s=await this.getRun({agentId:t,runId:n});if(s.id!==n||s.agentId!==t)throw r;return{agent:{...e,latestRunId:n},run:s}}catch{throw r}}async getAgent(t){return this.request({method:"GET",path:`/v1/agents/${m(t)}`})}async listAgents(t){return this.request({method:"GET",path:"/v1/agents",query:t})}async archiveAgent(t){return this.request({method:"POST",path:`/v1/agents/${m(t)}/archive`})}async unarchiveAgent(t){return this.request({method:"POST",path:`/v1/agents/${m(t)}/unarchive`})}async deleteAgent(t){return this.request({method:"DELETE",path:`/v1/agents/${m(t)}`})}async createRun(t,r,e){return this.request({method:"POST",path:`/v1/agents/${m(t)}/runs`,body:r,idempotencyKey:e?.idempotencyKey})}async steerRun(t,r){return this.request({method:"POST",path:`/v1/agents/${m(t)}/runs`,body:r,retryable:!1})}async listRuns(t,r){return this.request({method:"GET",path:`/v1/agents/${m(t)}/runs`,query:r})}async getRun({agentId:t,runId:r}){return this.request({method:"GET",path:`/v1/agents/${m(t)}/runs/${m(r)}`})}async cancelRun({agentId:t,runId:r}){return this.request({method:"POST",path:`/v1/agents/${m(t)}/runs/${m(r)}/cancel`})}async streamRun({agentId:t,runId:r,lastEventId:e,signal:s}){const i=`/v1/agents/${m(t)}/runs/${m(r)}/stream`,o=`${this.baseUrl}${i}`,u=`GET ${i}`,c=await this.headers({streaming:!0});let l;c.Accept="text/event-stream",e&&(c["Last-Event-ID"]=e),a.v.log(`[cloud-api] GET ${o}`);try{l=await fetch(o,{method:"GET",headers:c,signal:s})}catch(t){throw new n.Dr("Network request failed",{endpoint:u,isRetryable:!0,cause:t})}if(!l.ok||!l.body){const t=await l.text().catch((()=>""));a.v.log(`[cloud-api] stream status=${l.status} ${t}`),this.throwApiError(l.status,t,{endpoint:u,requestId:f(l)})}return l}async listArtifacts(t){return this.request({method:"GET",path:`/v1/agents/${m(t)}/artifacts`})}async getArtifactDownloadUrl({agentId:t,path:r}){return this.request({method:"GET",path:`/v1/agents/${m(t)}/artifacts/download`,query:{path:r}})}async getAgentUsage(t,r){return this.request({method:"GET",path:`/v1/agents/${m(t)}/usage`,query:{runId:r?.runId}})}async getMe(){return this.request({method:"GET",path:"/v1/me"})}async listModels(){return this.request({method:"GET",path:"/v1/models"})}async listRepositories(){return this.request({method:"GET",path:"/v1/repositories"})}}function m(t){return encodeURIComponent(t)}function f(t){return t.headers.get("x-request-id")??void 0}},"./src/agent/errors.ts"(t,r,e){e.d(r,{D7:()=>S,Dr:()=>f,J1:()=>l,LF:()=>i,Nt:()=>y,OE:()=>u,VW:()=>m,W_:()=>I,XB:()=>h,c$:()=>d,e_:()=>R,j1:()=>c,q3:()=>b,ud:()=>o,v3:()=>a,vg:()=>P,zz:()=>p});var n=e("../proto/dist/generated/aiserver/v1/utils_pb.js"),s=e("@connectrpc/connect");class i extends Error{constructor(t,r={}){super(t),this.name=r.errorName??"CursorSdkError",this.isRetryable=r.isRetryable??!1,g(this,"code",r.code),g(this,"status",r.status),g(this,"cause",r.cause),g(this,"endpoint",r.endpoint),g(this,"requestId",r.requestId),g(this,"operation",r.operation),Error.captureStackTrace?.(this,this.constructor)}toJSON(){return t={name:this.name,message:this.message,code:this.code,status:this.status,isRetryable:this.isRetryable,endpoint:this.endpoint,requestId:this.requestId,operation:this.operation},Object.fromEntries(Object.entries(t).filter((([,t])=>void 0!==t)));var t}}class o extends i{constructor(t,r={}){super(t,{...r,errorName:r.errorName??"CursorAgentError"})}}class a extends o{constructor(t,r={}){super(t,{...r,errorName:"AuthenticationError"})}}class u extends o{constructor(t,r={}){super(t,{...r,errorName:"RateLimitError"})}}class c extends o{constructor(t,r={}){super(t,{...r,errorName:"ConfigurationError"})}}class l extends o{constructor(t,r={}){super(t,{...r,errorName:"AgentBusyError"})}}class m extends c{constructor(t,r){super(t,r),this.name="IntegrationNotConnectedError",this.helpUrl=r.helpUrl,this.provider=r.provider}toJSON(){return{...super.toJSON(),helpUrl:this.helpUrl,provider:this.provider}}}class f extends o{constructor(t,r={}){super(t,{...r,errorName:"NetworkError"})}}class d extends o{constructor(t,r={}){super(t,{...r,errorName:"UnknownAgentError"})}}class p extends d{constructor(t,r={}){super(t,r),this.name="FeatureUnavailableError"}}class h extends o{constructor(t,r={}){super(t,{code:"agent_not_found",...r,errorName:"AgentNotFoundError"})}}function g(t,r,e){void 0!==e&&Object.defineProperty(t,r,{value:e,writable:!0,enumerable:!0,configurable:!0})}function _(t,r){if(void 0===r)return t;for(const[e,n]of Object.entries(r))w(e)&&void 0!==n&&void 0===t[e]&&g(t,e,n);return t}const J=["operation","endpoint","status","code","requestId","isRetryable"];function w(t){return J.some((r=>r===t))}function y(t,r={}){if(t instanceof i)return _(t,r);if(t instanceof s.ConnectError)return _(R(t),r);if(function(t){return t instanceof Error&&"AbortError"===t.name}(t))return _(new f(t.message,{code:"ABORT_ERR",isRetryable:!0,cause:t}),r);const e=t instanceof Error?t.message:String(t);return"connection_stalled"===function(t){if("object"!=typeof t||null===t||!("code"in t))return;const r=t.code;return"string"==typeof r&&r.length>0&&r.length<=64?r:void 0}(t)&&t instanceof Error?_(new f(e,{code:"connection_stalled",isRetryable:!0,cause:t}),r):new d(e,{...r,cause:t,isRetryable:r.isRetryable??!1})}function S(t){const r=y(t),e=void 0!==r.code?`[${r.code}] `:void 0;return{message:void 0!==e&&r.message.startsWith(e)?r.message.slice(e.length):r.message,...void 0!==r.code?{code:r.code}:{}}}const q=/^[A-Za-z][A-Za-z0-9_]{0,63}$/,B=/^\[([A-Za-z][A-Za-z0-9_]{0,63})\] ([\s\S]*)$/;function I(t){const r=t.code;if(void 0===r||!q.test(r))return t.message;const e=`[${r}] `;return t.message.startsWith(e)?t.message:`${e}${t.message}`}function P(t){const r=B.exec(t);if(null===r)return{message:t};const e=r[1],n=r[2]??"";return void 0===e?{message:t}:{message:n,code:e}}function b(t){return t instanceof s.ConnectError?R(t):t instanceof Error?t:new Error(String(t))}function R(t){const r=t.cause??void 0;if(r instanceof o)return r;const e=function(t){const r=t.findDetails(n.vj).at(0);if(void 0!==r)return r;const e=t.cause;return e instanceof s.ConnectError?e.findDetails(n.vj).at(0)??null:null}(t);let i,l,m=!1;if(e?.details){const{title:r,detail:n}=e.details;i=r&&n?`${r} ${n}`:r||n||t.message,m=e.details.isRetryable??!1,l=e.error}else i=t.message;if(void 0!==l){const r=function(t){return n.yM[t]??String(t)}(l);switch(l){case n.yM.NOT_LOGGED_IN:case n.yM.INVALID_AUTH_ID:case n.yM.NOT_HIGH_ENOUGH_PERMISSIONS:case n.yM.AGENT_REQUIRES_LOGIN:case n.yM.AUTH_TOKEN_NOT_FOUND:case n.yM.AUTH_TOKEN_EXPIRED:case n.yM.UNAUTHORIZED:return new a(i,{code:r,isRetryable:m,cause:t});case n.yM.FREE_USER_RATE_LIMIT_EXCEEDED:case n.yM.PRO_USER_RATE_LIMIT_EXCEEDED:case n.yM.FREE_USER_USAGE_LIMIT:case n.yM.PRO_USER_USAGE_LIMIT:case n.yM.RESOURCE_EXHAUSTED:case n.yM.OPENAI_RATE_LIMIT_EXCEEDED:case n.yM.GENERIC_RATE_LIMIT_EXCEEDED:case n.yM.GPT_4_VISION_PREVIEW_RATE_LIMIT:case n.yM.API_KEY_RATE_LIMIT:case n.yM.RATE_LIMITED:case n.yM.RATE_LIMITED_CHANGEABLE:return new u(i,{code:r,isRetryable:m,cause:t});case n.yM.BAD_API_KEY:case n.yM.BAD_USER_API_KEY:case n.yM.BAD_MODEL_NAME:case n.yM.MODEL_BLOCKED:case n.yM.NOT_FOUND:case n.yM.DEPRECATED:case n.yM.USER_NOT_FOUND:case n.yM.BAD_REQUEST:case n.yM.FILE_NOT_FOUND:return new c(i,{code:r,isRetryable:m,cause:t});case n.yM.TIMEOUT:return new f(i,{code:r,isRetryable:m,cause:t});default:return new d(i,{code:r,isRetryable:m,cause:t})}}const p=function(t){switch(t){case s.Code.Canceled:return"canceled";case s.Code.Unknown:return"unknown";case s.Code.InvalidArgument:return"invalid_argument";case s.Code.DeadlineExceeded:return"deadline_exceeded";case s.Code.NotFound:return"not_found";case s.Code.AlreadyExists:return"already_exists";case s.Code.PermissionDenied:return"permission_denied";case s.Code.ResourceExhausted:return"resource_exhausted";case s.Code.FailedPrecondition:return"failed_precondition";case s.Code.Aborted:return"aborted";case s.Code.OutOfRange:return"out_of_range";case s.Code.Unimplemented:return"unimplemented";case s.Code.Internal:return"internal";case s.Code.Unavailable:return"unavailable";case s.Code.DataLoss:return"data_loss";case s.Code.Unauthenticated:return"unauthenticated";default:return String(t)}}(t.code);switch(t.code){case s.Code.Unauthenticated:return new a(i,{code:p,isRetryable:m,cause:t});case s.Code.ResourceExhausted:return new u(i,{code:p,isRetryable:m,cause:t});case s.Code.InvalidArgument:case s.Code.NotFound:return new c(i,{code:p,isRetryable:m,cause:t});case s.Code.Unavailable:case s.Code.DeadlineExceeded:case s.Code.Internal:return new f(i,{code:p,isRetryable:m,cause:t});default:return new d(i,{code:p,isRetryable:m,cause:t})}}},"./src/agent/executor-common.ts"(t,r,e){e.d(r,{EV:()=>ar,qN:()=>Tr,KU:()=>Ur,Vh:()=>$r,v8:()=>Or,ly:()=>Ir,mU:()=>_r,dC:()=>wr,U:()=>Sr,tF:()=>Br,qd:()=>qr});var n=e("node:buffer"),s=e("node:crypto"),i=e("node:fs");let o,a=!1;var u=e("../proto/dist/generated/aiserver/v1/bidi_pb.js"),c=e("@bufbuild/protobuf"),l=e("@connectrpc/connect"),m=e("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/protocol/async-iterable.js");function f(t){return t instanceof Error?t:new Error(String(t))}class d extends Error{constructor(){super("Append failed"),this.name="AppendFailedError"}}class p{constructor(t,r,e,n,s={}){this.mapper=t,this.bidiClient=r,this.innerTransport=e,this.onError=n,this.binaryEncoding=!0===s.binaryEncoding,this.appendTimeoutMs=s.appendTimeoutMs??6e4}unary(t,r,e,n,s,i,o){return this.innerTransport.unary(t,r,e,n,s,i,o)}async stream(t,r,e,n,l,f,d){if(r.kind!==c.MethodKind.BiDiStreaming)return this.innerTransport.stream(t,r,e,n,l,f,d);const p=this.mapper.map(r),{requestId:h,header:g}=function(t){const r=t instanceof Headers?t.get("x-request-id"):Array.isArray(t)?t.find((([t])=>"x-request-id"===t))?.[1]:t?.["x-request-id"];if("string"==typeof r&&void 0!==t)return{requestId:r,header:t};const e=function(){const t=function(){if(!a)try{void 0===o&&(o=(0,i.openSync)("/dev/urandom","r"));const t=Buffer.alloc(16);let r=0;for(;r<16;){const e=(0,i.readSync)(o,t,r,16-r,null);if(e<=0)return;r+=e}return t}catch{if(a=!0,void 0!==o){try{(0,i.closeSync)(o)}catch{}o=void 0}return}}();return void 0===t?(0,s.randomUUID)({disableEntropyCache:!0}):function(t){const r=t[6]??0,e=t[8]??0;t[6]=15&r|64,t[8]=63&e|128;const n=t.toString("hex");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}(t)}();if(void 0===t){const t=new Headers;return t.set("x-request-id",e),{requestId:e,header:t}}return t instanceof Headers?t.set("x-request-id",e):Array.isArray(t)?t.push(["x-request-id",e]):"object"==typeof t&&null!==t&&(t["x-request-id"]=e),{requestId:e,header:t}}(l),_=new u.$r({requestId:h}),J=(0,m.T$)([_]);let w;const y=new Promise(((t,r)=>{w=r}));y.catch((()=>{}));const S=this.innerTransport.stream(t,p,e,n,g,J,d);this.startAppendingInputs(h,f,e,n,g,w);const q=await S,B=q.message,I={[Symbol.asyncIterator](){const t=B[Symbol.asyncIterator]();return{next:()=>Promise.race([t.next(),y]),return:r=>t.return?.(r)??Promise.resolve({done:!0,value:void 0}),throw:r=>t.throw?.(r)??Promise.resolve({done:!0,value:void 0})}}};return{...q,method:r,message:I}}startAppendingInputs(t,r,e,n,s,i){Promise.resolve().then((async()=>{let o=0;const a=[],m=r[Symbol.asyncIterator](),p=new AbortController,h=p.signal;let g,_;const J=new Promise(((t,r)=>{_=()=>r(new d)}));let w;if(J.catch((()=>{})),e?.aborted)p.abort(e.reason);else if(void 0!==e){const t=()=>{p.abort(e.reason),_()};e.addEventListener("abort",t,{once:!0}),g=()=>{e.removeEventListener("abort",t)}}try{for(;!h.aborted&&void 0===w;){const r=await Promise.race([m.next(),J]);if(r.done)break;const e=r.value;if(!(0,c.isMessage)(e))throw new Error("bidi append input is not a protobuf message");const d=o++,g=new u.$r({requestId:t}),y=e.toBinary(),S=y.buffer instanceof ArrayBuffer?y:new Uint8Array(y),q=this.binaryEncoding?S.length:2*S.length,B=this.appendTimeoutMs+Math.ceil(q/131072*1e3),I=void 0!==n?Math.min(n,B):B,P=this.bidiClient.bidiAppend(this.binaryEncoding?{requestId:g,appendSeqno:BigInt(d),dataBinary:S}:{requestId:g,appendSeqno:BigInt(d),data:Buffer.from(S.buffer,S.byteOffset,S.byteLength).toString("hex")},{signal:h,timeoutMs:I,headers:s}).then((()=>{})).catch((t=>{var r;if(r=h,!0!==r?.aborted&&void 0===w){const r=t instanceof l.ConnectError&&t.code===l.Code.DeadlineExceeded?new l.ConnectError(`bidi_append_deadline_exceeded: append seqno=${d} (${S.length} bytes) exceeded ${I}ms deadline`,l.Code.DeadlineExceeded,void 0,void 0,t):f(t);w=r,p.abort(r),this.onError(r),i(r),_()}})).finally((()=>{const t=a.indexOf(P);t>-1&&a.splice(t,1)}));if(a.push(P),await Promise.resolve(),h.aborted||void 0!==w)break;a.length>=16&&await Promise.race(a)}await Promise.allSettled(a)}catch(t){if(await Promise.allSettled(a),t instanceof d)return;const r=f(t);p.abort(r),this.onError(r),i(r)}finally{g?.(),await(m.return?.())}}))}}var h=e("../proto/dist/generated/agent/v1/agent_service_connect.js");const g={typeName:"aiserver.v1.BidiService",methods:{bidiAppend:{name:"BidiAppend",I:u.Qd,O:u.yq,kind:c.MethodKind.Unary}}};var _=e("../proto/dist/generated/aiserver/v1/dashboard_service_connect.js"),J=e("../proto/dist/generated/aiserver/v1/dashboard_pb.js"),w=e("../proto/dist/generated/aiserver/v1/privacy_mode_pb.js"),y=e("../proto/dist/generated/aiserver/v1/utils_pb.js"),S=e("../proto/dist/runtime/compact.js");S.HL,c.proto3,c.proto3,c.proto3,e("../proto/dist/generated/aiserver/v1/chat_pb.js"),e("../proto/dist/generated/aiserver/v1/tools_pb.js"),e("../proto/dist/generated/agent/v1/exec_pb.js"),S.HL;S.HL,c.proto3,c.proto3,e("../proto/dist/generated/aiserver/v1/repository_pb.js");S.HL,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,e("../proto/dist/generated/agent/v1/requested_model_pb.js");S.HL,c.proto3,c.proto3,c.proto3,S.HL,e("../proto/dist/generated/aiserver/v1/docs_pb.js"),e("../proto/dist/generated/agent/v1/smart_mode_classifier_exec_pb.js"),S.HL,e("../proto/dist/generated/agent/v1/agent_pb.js");S.HL,c.proto3,c.proto3;S.HL,c.proto3,c.proto3,S.HL,e("../proto/dist/generated/aiserver/v1/usage_pb.js");S.HL,c.proto3;S.HL,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,c.proto3,S.HL;class q extends S.HL{static get runtime(){return(0,S.kU)(this,"runtime",c.proto3)}static $p(){return"aiserver.v1."}}c.proto3;class B extends q{constructor(t){super(),c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new B).fromBinary(t,r)}static fromJson(t,r){return(new B).fromJson(t,r)}static fromJsonString(t,r){return(new B).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(B,t,r)}static $(){return["BugConfigResponse|1 linter_strategy_v1 #0|2 bug_bot_v1 #1|3 linter_strategy_v2 #2",I,b,P]}}class I extends q{constructor(t){super(),this.enabled=!1,this.tryTriggerOnSave=!1,this.waitBetweenTriggersMs=0,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new I).fromBinary(t,r)}static fromJson(t,r){return(new I).fromJson(t,r)}static fromJsonString(t,r){return(new I).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(I,t,r)}static $(){return["BugConfigResponse.LinterStrategyV1|1 enabled 8|2 try_trigger_on_save 8|3 wait_between_triggers_ms 1"]}}class P extends q{constructor(t){super(),this.enabled=!1,this.waitBetweenTriggersMs=0,this.debounceTriggersMs=0,this.keepLinesAroundChunk=0,this.preventTriggeringForFilesWithThisManyLines=0,this.preventTriggeringWhenLints=!1,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new P).fromBinary(t,r)}static fromJson(t,r){return(new P).fromJson(t,r)}static fromJsonString(t,r){return(new P).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(P,t,r)}static $(){return["BugConfigResponse.LinterStrategyV2|1 enabled 8|2 wait_between_triggers_ms 1|3 debounce_triggers_ms 1|4 keep_lines_around_chunk 5|5 prevent_triggering_for_files_with_this_many_lines 5|6 prevent_triggering_when_lints 8"]}}class b extends q{constructor(t){super(),this.enabled=!1,this.isSubsidized=!1,this.backgroundCallFrequencyMs=0,this.killSwitch=!1,this.showIntrusiveNotificationOnlyIfLastTimeWasMoreThanMsAgo=0,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new b).fromBinary(t,r)}static fromJson(t,r){return(new b).fromJson(t,r)}static fromJsonString(t,r){return(new b).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(b,t,r)}static $(){return["BugConfigResponse.BugBotV1|1 enabled 8|2 is_subsidized 8|3 background_call_frequency_ms 5|4 kill_switch 8|5 show_intrusive_notification_only_if_last_time_was_more_than_ms_ago 1|6 background_diff_absolute_max_tokens 5?|7 background_diff_min_min_token_threshold 5?|8 background_diff_min_max_token_threshold 5?|9 background_diff_last_commit_less_than_this_many_ms_ago 1?|15 background_unified_context_lines 5?|16 background_diff_include_uncommitted 8?|10 default_diff_context_lines 5?|11 diff_absolute_max_tokens 5?|12 custom_instructions_max_char_length 5?|13 default_fallback_iterations 5?|14 threshold_for_expensive_run_modal_cents 5?|17 cheap_model_name 9?|18 cheap_absolute_max_tokens 5?|19 expensive_absolute_max_tokens 5?"]}}c.proto3,c.proto3;class R extends S.HL{static get runtime(){return(0,S.kU)(this,"runtime",c.proto3)}static $p(){return"aiserver.v1."}}class v extends R{constructor(t){super(),this.samplingInterval=0,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new v).fromBinary(t,r)}static fromJson(t,r){return(new v).fromJson(t,r)}static fromJsonString(t,r){return(new v).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(v,t,r)}static $(){return["HeapProfileConfig|1 sampling_interval 5|2 include_objects_collected_by_major_gc 8?|3 include_objects_collected_by_minor_gc 8?"]}}class x extends R{constructor(t){super(),this.interval=0,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new x).fromBinary(t,r)}static fromJson(t,r){return(new x).fromJson(t,r)}static fromJsonString(t,r){return(new x).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(x,t,r)}static $(){return["CpuProfileConfig|1 interval 5"]}}class k extends R{constructor(t){super(),this.id="",c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new k).fromBinary(t,r)}static fromJson(t,r){return(new k).fromJson(t,r)}static fromJsonString(t,r){return(new k).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(k,t,r)}static $(){return["ProfileConfig|1 id 9|2 heap #0?|3 cpu #1?",v,x]}}class E extends R{constructor(t){super(),this.id="",this.process="",this.configId="",this.activityTimeout=0,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new E).fromBinary(t,r)}static fromJson(t,r){return(new E).fromJson(t,r)}static fromJsonString(t,r){return(new E).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(E,t,r)}static $(){return["ProfileScheduleConfig|1 id 9|2 process 9|3 config_id 9|4 schedule #0|5 activity_timeout 5",C]}}class C extends R{constructor(t){super(),this.interval=0,this.duration=0,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new C).fromBinary(t,r)}static fromJson(t,r){return(new C).fromJson(t,r)}static fromJsonString(t,r){return(new C).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(C,t,r)}static $(){return["ProfileScheduleConfig.ScheduleConfig|1 interval 5|2 duration 5"]}}class T extends R{constructor(t){super(),this.enabled=!1,this.configs=[],this.schedules=[],c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new T).fromBinary(t,r)}static fromJson(t,r){return(new T).fromJson(t,r)}static fromJsonString(t,r){return(new T).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(T,t,r)}static $(){return["ProfilingConfig|1 enabled 8|2 configs #0*|3 schedules #1*",k,E]}}class U extends S.HL{static get runtime(){return(0,S.kU)(this,"runtime",c.proto3)}static $p(){return"aiserver.v1."}}c.proto3;class A extends U{constructor(t){super(),this.enabled=!1,this.maxRequestsTracked=0,this.maxRequestsTrackedMb=0,this.maxRequestRetentionSeconds=0,this.sendOriginalFileContentsForInitialSnapshot=!1,this.sendFullAddedLinesInDiffChanges=!1,this.numCommitsTracked=0,this.timeIntervalsTrackedMinutes=[],this.tooBigFileSizeBytes=0,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new A).fromBinary(t,r)}static fromJson(t,r){return(new A).fromJson(t,r)}static fromJsonString(t,r){return(new A).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(A,t,r)}static $(){return["OnlineMetricsConfig|1 enabled 8|2 max_requests_tracked 5|3 max_requests_tracked_mb 5|4 max_request_retention_seconds 1|5 send_original_file_contents_for_initial_snapshot 8|6 send_full_added_lines_in_diff_changes 8|7 num_commits_tracked 5|8 time_intervals_tracked_minutes 5*|9 too_big_file_size_bytes 5"]}}const $="aiserver.v1.";class M extends S.HL{static get runtime(){return(0,S.kU)(this,"runtime",c.proto3)}static $p(){return $}}var O=(0,S.QT)(c.proto3,$,"ButtonType",[[0,"UNSPECIFIED"],[1,"LEADING"],[2,"PRIMARY"],[3,"SECONDARY"]],1),D=(0,S.QT)(c.proto3,$,"DisplayMode",[[0,"UNSPECIFIED"],[1,"TOAST"],[2,"MODAL"]],1),N=(0,S.QT)(c.proto3,$,"ClientUpdateLevel",[[0,"UNSPECIFIED"],[1,"NONE"],[2,"RECOMMENDED"],[3,"REQUIRED"]],1),G=(0,S.QT)(c.proto3,$,"RemoteConnectionType",[[0,"UNSPECIFIED"],[1,"LOCAL"],[2,"WSL"],[3,"SSH"],[4,"DEVCONTAINER"],[5,"DEVCONTAINER_SSH"],[6,"DEVCONTAINER_WSL"]],1),L=(0,S.QT)(c.proto3,$,"ClientSurface",[[0,"UNSPECIFIED"],[1,"EDITOR"],[2,"GLASS"]],1),F=(0,S.QT)(c.proto3,$,"InAppAdTrigger",[[0,"UNSPECIFIED"],[1,"MOUNT"],[2,"FIND_ISSUES"],[3,"GIT_PUSH"],[4,"COMMIT"],[5,"IOS_DOWNLOAD_MENU"]],1),K=(0,S.QT)(c.proto3,$,"ScmConnectAdProvider",[[0,"UNSPECIFIED"],[1,"GITHUB"],[2,"GITLAB"]],1),z=(0,S.QT)(c.proto3,$,"ScmConnectAdConnectionState",[[0,"UNSPECIFIED"],[1,"UNKNOWN"],[2,"NOT_CONNECTED"],[3,"HAS_ACCESS"]],1),j=(0,S.QT)(c.proto3,$,"Http2Config",[[0,"UNSPECIFIED"],[1,"FORCE_ALL_DISABLED"],[2,"FORCE_ALL_ENABLED"],[3,"FORCE_BIDI_DISABLED"],[4,"FORCE_BIDI_ENABLED"]],1),H=(0,S.QT)(c.proto3,$,"RetrievalKeepAliveConfig",[[0,"UNSPECIFIED"],[1,"FORCE_DISABLED"],[2,"FORCE_ENABLED"]],1),W=(0,S.QT)(c.proto3,$,"BugbotPlanType",[[0,"UNSPECIFIED"],[1,"TEAM"],[2,"USER"]],1),Q=(0,S.QT)(c.proto3,$,"NewRepoFlowProbeInterpreter",[[0,"UNSPECIFIED"],[1,"VERCEL_PROJECT_LINK_MATCH"],[2,"JSON_PATH_EQUALS"],[3,"BOOLEAN_FIELD"]],1),V=(0,S.QT)(c.proto3,$,"NewRepoFlowFact",[[0,"UNSPECIFIED"],[1,"STARTED_AS_NEW_PROJECT"],[2,"REPO_IS_STANDARD_ORIGIN"],[3,"IS_SUBAGENT_CONVERSATION"],[4,"PLUGIN_INSTALLED"],[5,"PROBE_RESULT"],[6,"STEP_LATCHED"],[7,"SERVER_FACT"],[8,"PROBE_LINKED_WITH_LATCH_FALLBACK"],[9,"MCP_NEEDS_AUTH"]],1),X=(0,S.QT)(c.proto3,$,"NewRepoFlowStepPresentation",[[0,"UNSPECIFIED"],[1,"PILL"],[2,"PLUGIN_NUDGE"],[3,"BLOCKING_TRAY"]],1),Y=(0,S.QT)(c.proto3,$,"NewRepoFlowPluginAuthTarget",[[0,"UNSPECIFIED"],[1,"CLOUD"],[2,"LOCAL"]],1),Z=(0,S.QT)(c.proto3,$,"InferenceProviderWarningTrigger",[[0,"UNSPECIFIED"],[1,"ON_SELECT"],[2,"ON_ERROR"]],1);class tt extends M{constructor(t){super(),c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tt).fromBinary(t,r)}static fromJson(t,r){return(new tt).fromJson(t,r)}static fromJsonString(t,r){return(new tt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(tt,t,r)}static $(){return["ModalDisplayConfig|1 background_gradient 9?|2 description 9?|3 background_gradient_light 9?|4 background_gradient_dark 9?"]}}class rt extends M{constructor(t){super(),this.id="",this.buttons=[],this.displayMode=D.UNSPECIFIED,this.targetSurfaces=[],c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rt).fromBinary(t,r)}static fromJson(t,r){return(new rt).fromJson(t,r)}static fromJsonString(t,r){return(new rt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(rt,t,r)}static $(){return["InAppAd|1 id 9|2 header #0|3 content #1|4 buttons #2*|5 force_dark_close_button 8?|6 display_mode #3|7 analytics_variant 9?|8 modal_display_config #4?|9 target_surfaces #5*|10 ignore_seen 8?",et,nt,it,D,tt,L]}}class et extends M{constructor(t){super(),c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new et).fromBinary(t,r)}static fromJson(t,r){return(new et).fromJson(t,r)}static fromJsonString(t,r){return(new et).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(et,t,r)}static $(){return["AdHeader|1 banner_url 9?|2 banner_url_light 9?|3 banner_url_dark 9?"]}}class nt extends M{constructor(t){super(),this.title="",this.sections=[],c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nt).fromBinary(t,r)}static fromJson(t,r){return(new nt).fromJson(t,r)}static fromJsonString(t,r){return(new nt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(nt,t,r)}static $(){return["AdContent|1 tag 9?|2 title 9|3 sections #0*|4 center_title 8?",st]}}class st extends M{constructor(t){super(),this.iconSvg="",this.title="",this.description="",c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new st).fromBinary(t,r)}static fromJson(t,r){return(new st).fromJson(t,r)}static fromJsonString(t,r){return(new st).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(st,t,r)}static $(){return["AdSection|1 icon_svg 9|2 title 9|3 description 9|4 is_beta 8?"]}}class it extends M{constructor(t){super(),this.text="",this.buttonType=O.UNSPECIFIED,this.action={case:void 0},c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new it).fromBinary(t,r)}static fromJson(t,r){return(new it).fromJson(t,r)}static fromJsonString(t,r){return(new it).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(it,t,r)}static $(){return["AdButton|1 text 9|2 button_type #0|3 external_url 9 action|4 command_id 9 action|5 client_action #1 action",O,y.O2]}}class ot extends M{constructor(t){super(),this.updateLevel=N.UNSPECIFIED,this.currentClientVersion="",this.minSupportedClientVersion="",this.minAllowedClientVersion="",c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ot).fromBinary(t,r)}static fromJson(t,r){return(new ot).fromJson(t,r)}static fromJsonString(t,r){return(new ot).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(ot,t,r)}static $(){return["ClientVersionStatus|1 update_level #0|2 current_client_version 9|3 min_supported_client_version 9|4 min_allowed_client_version 9|5 message 9?",N]}}class at extends M{constructor(t){super(),this.maxConcurrentUploads=0,this.absoluteMaxNumberFiles=0,this.maxFileRetries=0,this.syncConcurrency=0,this.autoIndexingMaxNumFiles=0,this.indexingPeriodSeconds=0,this.repo42AuthToken="",this.copyStatusCheckPeriodSeconds=0,this.copyTimeoutSeconds=0,this.maxBatchBytes=0,this.maxBatchNumRequests=0,this.maxSyncMerkleBatchSize=0,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new at).fromBinary(t,r)}static fromJson(t,r){return(new at).fromJson(t,r)}static fromJsonString(t,r){return(new at).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(at,t,r)}static $(){return["IndexingConfig|1 max_concurrent_uploads 5|2 absolute_max_number_files 5|3 max_file_retries 5|4 sync_concurrency 5|5 auto_indexing_max_num_files 5|6 indexing_period_seconds 5|7 repo42_auth_token 9|8 incremental 8?|9 default_user_path_encryption_key 9?|10 default_team_path_encryption_key 9?|11 multi_root_indexing_enabled 8?|12 copy_status_check_period_seconds 1|13 copy_timeout_seconds 5|14 max_batch_bytes 5|15 max_batch_num_requests 5|16 max_sync_merkle_batch_size 5"]}}class ut extends M{constructor(t){super(),c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ut).fromBinary(t,r)}static fromJson(t,r){return(new ut).fromJson(t,r)}static fromJsonString(t,r){return(new ut).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(ut,t,r)}static $(){return["GitIndexingConfig|1 enabled 8?|2 max_pr_count 5?|3 max_pr_size 5?|4 pr_embedding_context 5?|5 js_concurrency 5?|6 js_chunk_size 5?|7 cpu_concurrency 5?|8 indexing_period_seconds 5?|9 max_attempts_per_pr 5?|10 allow_index_copy_from_server 8?"]}}class ct extends M{constructor(t){super(),this.globalSampleRate=0,this.tracesSampleRate=0,this.loggerSampleRate=0,this.minidumpSampleRate=0,this.errorRateLimit=0,this.performanceUnitRateLimit=0,this.profilesSampleRate=0,this.jsonStringifySampleRate=0,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ct).fromBinary(t,r)}static fromJson(t,r){return(new ct).fromJson(t,r)}static fromJsonString(t,r){return(new ct).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(ct,t,r)}static $(){return["ClientTracingConfig|1 global_sample_rate 1|2 traces_sample_rate 1|3 logger_sample_rate 1|4 minidump_sample_rate 1|5 error_rate_limit 1|6 performance_unit_rate_limit 1|7 profiles_sample_rate 1|8 json_stringify_sample_rate 1"]}}class lt extends M{constructor(t){super(),this.disableUnification=!1,this.fullContextTokenLimit=0,this.disableYoloMode=!1,this.maxRuleLength=0,this.maxMcpTools=0,this.warnMcpTools=0,this.summarizationMessage="",this.numFilesForMemoryGeneration=0,this.memoryDefaultEnabled=!1,this.numSummarizationsBeforeWarningShown=0,this.cursorRulesReadFileFixEnabled=!1,this.dontSendCtrlCBeforeCommand=!1,this.clientStatsigPollIntervalMs=0,this.disableStatsig=!1,this.listDirV2PredefinedIgnoreGlobs=[],c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lt).fromBinary(t,r)}static fromJson(t,r){return(new lt).fromJson(t,r)}static fromJsonString(t,r){return(new lt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(lt,t,r)}static $(){return["ChatConfig|1 disable_unification 8|2 full_context_token_limit 5|3 disable_yolo_mode 8|4 max_rule_length 5|5 max_mcp_tools 5|6 warn_mcp_tools 5|7 summarization_message 9|8 num_files_for_memory_generation 5|9 memory_default_enabled 8|10 num_summarizations_before_warning_shown 5|11 cursor_rules_read_file_fix_enabled 8|12 dont_send_ctrl_c_before_command 8|13 client_statsig_poll_interval_ms 5|14 disable_statsig 8|15 list_dir_v2_predefined_ignore_globs 9*"]}}class mt extends M{constructor(t){super(),this.connectionType=G.UNSPECIFIED,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mt).fromBinary(t,r)}static fromJson(t,r){return(new mt).fromJson(t,r)}static fromJsonString(t,r){return(new mt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(mt,t,r)}static $(){return["RemoteAuthority|1 connection_type #0",G]}}class ft extends M{constructor(t){super(),this.provider=K.UNSPECIFIED,this.remoteUrl="",this.connectionState=z.UNSPECIFIED,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ft).fromBinary(t,r)}static fromJson(t,r){return(new ft).fromJson(t,r)}static fromJsonString(t,r){return(new ft).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(ft,t,r)}static $(){return["ScmConnectAdContext|1 provider #0|2 remote_url 9|3 connection_state #1",K,z]}}class dt extends M{constructor(t){super(),this.hasAlternativeCli=!1,this.hasCursorAgentCli=!1,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dt).fromBinary(t,r)}static fromJson(t,r){return(new dt).fromJson(t,r)}static fromJsonString(t,r){return(new dt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(dt,t,r)}static $(){return["DevEnvironment|1 has_alternative_cli 8|2 has_cursor_agent_cli 8"]}}class pt extends M{constructor(t){super(),this.telemEnabled=!1,this.bugBotDismissedNotificationLast10TimesUnixMs=[],this.bugBotViewedNotificationLast10TimesUnixMs=[],this.inAppAdTrigger=F.UNSPECIFIED,this.clientSurface=L.UNSPECIFIED,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pt).fromBinary(t,r)}static fromJson(t,r){return(new pt).fromJson(t,r)}static fromJsonString(t,r){return(new pt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(pt,t,r)}static $(){return["GetServerConfigRequest|1 telem_enabled 8|2 bug_bot_dismissed_notification_last_10_times_unix_ms 1*|3 bug_bot_viewed_notification_last_10_times_unix_ms 1*|4 os_stats #0|5 os_properties #1|6 remote_authority #2|7 in_app_ad_trigger #3|8 dev_environment #4|9 client_surface #5|10 scm_connect_ad_context #6",y.e$,y.Se,mt,F,dt,L,ft]}}class ht extends M{constructor(t){super(),this.enabledInPrivacyMode=!1,this.enabledInNonPrivacyMode=!1,this.excludedAgentHostModuleTagKeys=[],c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ht).fromBinary(t,r)}static fromJson(t,r){return(new ht).fromJson(t,r)}static fromJsonString(t,r){return(new ht).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(ht,t,r)}static $(){return["MetricsConfig|2 enabled_in_privacy_mode 8|3 enabled_in_non_privacy_mode 8|4 excluded_agent_host_module_tag_keys 9*"]}}class gt extends M{constructor(t){super(),this.enableBackgroundAgent=!1,this.showBackgroundAgentInBetaSettings=!1,this.showBackgroundAgentHistoryAction=!1,this.useModalExperience=!1,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gt).fromBinary(t,r)}static fromJson(t,r){return(new gt).fromJson(t,r)}static fromJsonString(t,r){return(new gt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(gt,t,r)}static $(){return["BackgroundComposerConfig|1 enable_background_agent 8|2 show_background_agent_in_beta_settings 8|3 window_in_window_preload_count 5?|4 window_in_window_ping_interval_ms 1?|5 show_background_agent_disclaimer 8?|6 show_background_agent_slack_ad 8?|7 show_background_agent_history_action 8|8 max_window_in_windows 5?|9 use_modal_experience 8|10 max_multi_repo_environment_repos 5?|11 allow_mixed_host_environment_repos 8?"]}}class _t extends M{constructor(t){super(),this.enabled=!1,this.enabledFallback=!1,this.enabledGitGraph=!1,this.enabledSemSearch=!1,this.enabledV2=!1,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _t).fromBinary(t,r)}static fromJson(t,r){return(new _t).fromJson(t,r)}static fromJsonString(t,r){return(new _t).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(_t,t,r)}static $(){return["AutoContextConfig|1 enabled 8|2 enabled_fallback 8|3 enabled_git_graph 8|4 enabled_sem_search 8|5 enabled_v2 8"]}}class Jt extends M{constructor(t){super(),this.enabled=!1,this.showStatusEntry=!1,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jt).fromBinary(t,r)}static fromJson(t,r){return(new Jt).fromJson(t,r)}static fromJsonString(t,r){return(new Jt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(Jt,t,r)}static $(){return["MemoryMonitorConfig|1 enabled 8|2 show_status_entry 8|3 base_threshold_mb 5?|4 critical_offset_mb 5?|5 process_memory_interval_sec 5?"]}}class wt extends M{constructor(t){super(),this.releaseTrack="",this.mode=yt.UNSPECIFIED,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wt).fromBinary(t,r)}static fromJson(t,r){return(new wt).fromJson(t,r)}static fromJsonString(t,r){return(new wt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(wt,t,r)}static $(){return["UpdateConfig|1 release_track 9|2 mode #0|3 applied_at 5?",yt]}}var yt=(0,S.QT)(c.proto3,$,"UpdateConfig.UpdateMode",[[0,"UNSPECIFIED"],[1,"ONE_TIME"]],1);class St extends M{constructor(t){super(),this.enabled=!1,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new St).fromBinary(t,r)}static fromJson(t,r){return(new St).fromJson(t,r)}static fromJsonString(t,r){return(new St).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(St,t,r)}static $(){return["PerformanceEventsConfig|1 enabled 8|2 buffer_size 5?|3 flush_interval_ms 5?"]}}class qt extends M{constructor(t){super(),this.profilingEnabled=!1,this.metricsEnabled=!1,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qt).fromBinary(t,r)}static fromJson(t,r){return(new qt).fromJson(t,r)}static fromJsonString(t,r){return(new qt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(qt,t,r)}static $(){return["InteractionConfig|1 profiling_enabled 8|2 metrics_enabled 8|3 profiling_interval_sec 5?|4 metrics_interval_sec 5?|5 profiling_max_buffer_size 5?|6 profiling_interaction_duration_threshold_ms 5?|7 profiling_sample_interval_ms 5?|8 metrics_min_interactions_for_loaf 5?|9 metrics_min_foreground_time_ms 5?|10 metrics_combined_inp_drop_highest_count 5?|11 metrics_click_inp_drop_highest_count 5?|12 metrics_keypress_inp_drop_highest_count 5?|13 metrics_startup_threshold_sec 5?|14 analytics_summary_every_n_windows 5?|15 ext_host_lag_summary_interval_sec 5?"]}}class Bt extends M{constructor(t){super(),this.enabled=!1,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bt).fromBinary(t,r)}static fromJson(t,r){return(new Bt).fromJson(t,r)}static fromJsonString(t,r){return(new Bt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(Bt,t,r)}static $(){return["AgentTelemetryConfig|1 enabled 8"]}}class It extends M{constructor(t){super(),this.enabled=!1,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new It).fromBinary(t,r)}static fromJson(t,r){return(new It).fromJson(t,r)}static fromJsonString(t,r){return(new It).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(It,t,r)}static $(){return["TraceConfig|1 enabled 8|2 buffer_size 5?|3 flush_interval_ms 5?|4 sample_rate 1?|5 internal_sample_rate 1?|6 internal_ext_host_sample_rate 1?"]}}class Pt extends M{constructor(t){super(),this.id="",this.modelSetting="",this.targetModel="",c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pt).fromBinary(t,r)}static fromJson(t,r){return(new Pt).fromJson(t,r)}static fromJsonString(t,r){return(new Pt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(Pt,t,r)}static $(){return["ModelMigration|1 id 9|2 model_setting 9|3 target_model 9|4 previous_model 9?|5 migrate_mode_models 8?|6 remove_previous_model 8?|7 max_mode 8?|8 migrate_old_composers_and_current_composer 8?"]}}class bt extends M{constructor(t){super(),this.maxTotalBytes=0,this.maxNumFiles=0,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bt).fromBinary(t,r)}static fromJson(t,r){return(new bt).fromJson(t,r)}static fromJsonString(t,r){return(new bt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(bt,t,r)}static $(){return["FolderSizeLimit|1 max_total_bytes 5|2 max_num_files 5"]}}class Rt extends M{constructor(t){super(),this.compositeShellCommands=[],this.safeShellCommands=[],c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rt).fromBinary(t,r)}static fromJson(t,r){return(new Rt).fromJson(t,r)}static fromJsonString(t,r){return(new Rt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(Rt,t,r)}static $(){return["RunTerminalServerConfig|1 composite_shell_commands 9*|2 safe_shell_commands 9*"]}}class vt extends M{constructor(t){super(),this.allowedActionIds=[],this.deniedActionIds=[],c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vt).fromBinary(t,r)}static fromJson(t,r){return(new vt).fromJson(t,r)}static fromJsonString(t,r){return(new vt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(vt,t,r)}static $(){return["AgentLayoutPolicy|1 allowed_action_ids 9*|2 denied_action_ids 9*"]}}class xt extends M{constructor(t){super(),this.message="",this.enabled=!1,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xt).fromBinary(t,r)}static fromJson(t,r){return(new xt).fromJson(t,r)}static fromJsonString(t,r){return(new xt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(xt,t,r)}static $(){return["TerminalTipConfig|1 message 9|2 enabled 8"]}}class kt extends M{constructor(t){super(),this.marketplacePluginNames=[],this.agenticOnboardingEnabled=!1,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kt).fromBinary(t,r)}static fromJson(t,r){return(new kt).fromJson(t,r)}static fromJsonString(t,r){return(new kt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(kt,t,r)}static $(){return["OnboardingConfig|1 marketplace_plugin_names 9*|2 agentic_onboarding_enabled 8"]}}class Et extends M{constructor(t){super(),this.bugbotPlanEnabled=!1,this.bugbotPlanType=W.UNSPECIFIED,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Et).fromBinary(t,r)}static fromJson(t,r){return(new Et).fromJson(t,r)}static fromJsonString(t,r){return(new Et).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(Et,t,r)}static $(){return["BugbotConfig|1 bugbot_plan_enabled 8|2 bugbot_plan_type #0",W]}}class Ct extends M{constructor(t){super(),this.enabled=!1,this.resetToken="",c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ct).fromBinary(t,r)}static fromJson(t,r){return(new Ct).fromJson(t,r)}static fromJsonString(t,r){return(new Ct).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(Ct,t,r)}static $(){return["CodebaseTelemetryConfig|1 enabled 8|2 reset_token 9"]}}class Tt extends M{constructor(t){super(),this.id="",this.mcpServerNameMatch="",this.toolName="",this.argsJson="",this.interpreter=Q.UNSPECIFIED,this.interpreterParam="",this.interpreterExpectedValue="",this.backendMethod="",c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tt).fromBinary(t,r)}static fromJson(t,r){return(new Tt).fromJson(t,r)}static fromJsonString(t,r){return(new Tt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(Tt,t,r)}static $(){return["NewRepoFlowProbe|1 id 9|2 mcp_server_name_match 9|3 tool_name 9|4 args_json 9|5 interpreter #0|6 interpreter_param 9|7 interpreter_expected_value 9|8 backend_method 9",Q]}}class Ut extends M{constructor(t){super(),this.method="",this.repoName="",this.repoUrl="",this.previousRepoName="",c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ut).fromBinary(t,r)}static fromJson(t,r){return(new Ut).fromJson(t,r)}static fromJsonString(t,r){return(new Ut).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(Ut,t,r)}static $(){return["ResolveNewRepoFlowBackendProbeRequest|1 method 9|2 repo_name 9|3 repo_url 9|4 previous_repo_name 9"]}}class At extends M{constructor(t){super(),this.payloadText="",c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new At).fromBinary(t,r)}static fromJson(t,r){return(new At).fromJson(t,r)}static fromJsonString(t,r){return(new At).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(At,t,r)}static $(){return["ResolveNewRepoFlowBackendProbeResponse|1 payload_text 9"]}}class $t extends M{constructor(t){super(),c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $t).fromBinary(t,r)}static fromJson(t,r){return(new $t).fromJson(t,r)}static fromJsonString(t,r){return(new $t).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals($t,t,r)}static $(){return["GetNewRepoFlowConfigRequest"]}}class Mt extends M{constructor(t){super(),c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mt).fromBinary(t,r)}static fromJson(t,r){return(new Mt).fromJson(t,r)}static fromJsonString(t,r){return(new Mt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(Mt,t,r)}static $(){return["GetNewRepoFlowConfigResponse|1 config #0",zt]}}class Ot extends M{constructor(t){super(),this.fact=V.UNSPECIFIED,this.param="",this.expectedValue="",this.negate=!1,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ot).fromBinary(t,r)}static fromJson(t,r){return(new Ot).fromJson(t,r)}static fromJsonString(t,r){return(new Ot).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(Ot,t,r)}static $(){return["NewRepoFlowCondition|1 fact #0|2 param 9|3 expected_value 9|4 negate 8",V]}}class Dt extends M{constructor(t){super(),this.pluginName="",this.authTarget=Y.UNSPECIFIED,this.redirectMetadata={},c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dt).fromBinary(t,r)}static fromJson(t,r){return(new Dt).fromJson(t,r)}static fromJsonString(t,r){return(new Dt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(Dt,t,r)}static $(){return["NewRepoFlowInstallPluginAction|1 plugin_name 9|2 auth_target #0|3 redirect_metadata 9,9",Y]}}class Nt extends M{constructor(t){super(),this.slashCommand="",this.promptBody="",this.compactTitle="",this.latchKey="",c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nt).fromBinary(t,r)}static fromJson(t,r){return(new Nt).fromJson(t,r)}static fromJsonString(t,r){return(new Nt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(Nt,t,r)}static $(){return["NewRepoFlowSubmitFollowupAction|1 slash_command 9|2 prompt_body 9|3 compact_title 9|4 latch_key 9"]}}class Gt extends M{constructor(t){super(),c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gt).fromBinary(t,r)}static fromJson(t,r){return(new Gt).fromJson(t,r)}static fromJsonString(t,r){return(new Gt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(Gt,t,r)}static $(){return["NewRepoFlowDismissAction"]}}class Lt extends M{constructor(t){super(),this.serverNameMatch="",this.postAuthReturnPathTemplate="",c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lt).fromBinary(t,r)}static fromJson(t,r){return(new Lt).fromJson(t,r)}static fromJsonString(t,r){return(new Lt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(Lt,t,r)}static $(){return["NewRepoFlowMcpAuthenticateAction|1 server_name_match 9|2 post_auth_return_path_template 9"]}}class Ft extends M{constructor(t){super(),this.label="",this.buttonType=O.UNSPECIFIED,this.action={case:void 0},c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ft).fromBinary(t,r)}static fromJson(t,r){return(new Ft).fromJson(t,r)}static fromJsonString(t,r){return(new Ft).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(Ft,t,r)}static $(){return["NewRepoFlowStepButton|1 label 9|2 button_type #0|3 external_url 9 action|4 install_plugin #1 action|5 submit_followup #2 action|6 client_action #3 action|7 dismiss #4 action|8 mcp_authenticate #5 action",O,Dt,Nt,y.O2,Gt,Lt]}}class Kt extends M{constructor(t){super(),this.id="",this.presentation=X.UNSPECIFIED,this.title="",this.bodyMarkdown="",this.pillLabel="",this.buttons=[],this.visibleWhen=[],this.dismissible=!1,this.brandPluginName="",this.disabledWhen=[],this.disabledReason="",c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kt).fromBinary(t,r)}static fromJson(t,r){return(new Kt).fromJson(t,r)}static fromJsonString(t,r){return(new Kt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(Kt,t,r)}static $(){return["NewRepoFlowStep|1 id 9|2 presentation #0|3 title 9|4 body_markdown 9|5 pill_label 9|6 buttons #1*|7 visible_when #2*|8 dismissible 8|9 brand_plugin_name 9|10 disabled_when #2*|11 disabled_reason 9",X,Ft,Ot]}}class zt extends M{constructor(t){super(),this.configVersion="",this.probes=[],this.steps=[],this.serverFacts={},c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zt).fromBinary(t,r)}static fromJson(t,r){return(new zt).fromJson(t,r)}static fromJsonString(t,r){return(new zt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(zt,t,r)}static $(){return["NewRepoFlowConfig|1 config_version 9|2 probes #0*|3 steps #1*|4 server_facts 9,9",Tt,Kt]}}class jt extends M{constructor(t){super(),this.isDevDoNotUseForSecretThingsBecauseCanBeSpoofedByUsers=!1,this.configVersion="",this.http2Config=j.UNSPECIFIED,this.modelMigrations=[],this.useNlbForNal=!1,this.inferenceProviderWarnings=[],this.retrievalKeepAliveConfig=H.UNSPECIFIED,this.voiceInputUnavailable=!1,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jt).fromBinary(t,r)}static fromJson(t,r){return(new jt).fromJson(t,r)}static fromJsonString(t,r){return(new jt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(jt,t,r)}static $(){return["GetServerConfigResponse|1 bug_config_response #0|2 is_dev_do_not_use_for_secret_things_because_can_be_spoofed_by_users 8|3 indexing_config #1|4 client_tracing_config #2|5 chat_config #3|6 config_version 9|7 http2_config #4|8 profiling_config #5|9 metrics_config #6|10 background_composer_config #7|11 auto_context_config #8|12 model_migrations #9*|13 memory_monitor_config #10|14 folder_size_limit #11|20 online_metrics_config #12|15 git_indexing_config #13|16 performance_events_config #14|17 current_in_app_ad #15?|18 trace_config #16|19 run_terminal_server_config #17?|21 interaction_config #18|22 agent_telemetry_config #19|23 client_version_status #20?|24 update_config #21?|25 agent_layout_policy #22?|26 use_nlb_for_nal 8|27 agent_url_config #23|28 cli_sandbox_default_enabled 8?|30 terminal_tip_config #24?|31 model_picker_nudge 9?|32 inference_provider_warnings #25*|33 onboarding_config #26?|34 bugbot_config #27?|35 codebase_telemetry_config #28?|36 retrieval_keep_alive_config #29|37 google_workspace_mcp_oauth_client #30?|38 new_repo_flow_config #31?|39 voice_input_unavailable 8|40 extension_gallery_service_url 9?",B,at,ct,lt,j,T,ht,gt,_t,Pt,Jt,bt,A,ut,St,rt,It,Rt,qt,Bt,ot,wt,vt,Qt,xt,Wt,kt,Et,Ct,H,Ht,zt]}}class Ht extends M{constructor(t){super(),this.clientId="",this.clientSecret="",c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ht).fromBinary(t,r)}static fromJson(t,r){return(new Ht).fromJson(t,r)}static fromJsonString(t,r){return(new Ht).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(Ht,t,r)}static $(){return["GoogleWorkspaceMcpOAuthClient|1 client_id 9|2 client_secret 9"]}}class Wt extends M{constructor(t){super(),this.message="",this.affectedModels=[],this.trigger=Z.UNSPECIFIED,c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wt).fromBinary(t,r)}static fromJson(t,r){return(new Wt).fromJson(t,r)}static fromJsonString(t,r){return(new Wt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(Wt,t,r)}static $(){return["InferenceProviderWarning|1 message 9|2 affected_models 9*|3 fallback_model 9?|4 trigger #0",Z]}}class Qt extends M{constructor(t){super(),this.agentUrl="",this.agentnUrl="",this.localLoopInferenceUrl="",c.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qt).fromBinary(t,r)}static fromJson(t,r){return(new Qt).fromJson(t,r)}static fromJsonString(t,r){return(new Qt).fromJsonString(t,r)}static equals(t,r){return c.proto3.util.equals(Qt,t,r)}static $(){return["AgentUrlConfig|1 agent_url 9|2 agentn_url 9|3 local_loop_inference_url 9"]}}const Vt={typeName:"aiserver.v1.ServerConfigService",methods:{getServerConfig:{name:"GetServerConfig",I:pt,O:jt,kind:c.MethodKind.Unary},resolveNewRepoFlowBackendProbe:{name:"ResolveNewRepoFlowBackendProbe",I:Ut,O:At,kind:c.MethodKind.Unary},getNewRepoFlowConfig:{name:"GetNewRepoFlowConfig",I:$t,O:Mt,kind:c.MethodKind.Unary}}};var Xt=e("../utils/dist/promise-extras.js"),Yt=e("../utils/dist/fresh-uuid.js"),Zt=e("./package.json"),tr=e("./src/agent/auth/stored-credentials.ts"),rr=e("./src/agent/errors.ts"),er=e("./src/agent/sdk-config.ts"),nr=e("./src/agent/team-id.ts"),sr=e("./src/agent/tool-call-utils.ts"),ir=e("./src/agent/transport.ts"),or=e("./src/agent/utils/logger.ts");const ar=process.env.CURSOR_BACKEND_URL||"https://api2.cursor.sh";let ur="true";const cr=new Map,lr=new Map,mr=new Map,fr=new Map,dr=new Map,pr=new Map,hr=t=>{try{return"http:"===new URL(t).protocol}catch{return t.startsWith("http://")}},gr=()=>{const t=Object.getOwnPropertyDescriptor(globalThis,"Bun");return void 0!==t&&(void 0!==t.get||void 0!==t.value)};async function _r(t){if(!t||dr.has(t))return;const r=pr.get(t);if(r)return void await r;const e=(async()=>{const r=await async function(t){try{const r=await wr(t,ar);if(!r)return;const e=t=>async e=>(e.header.set("authorization",`Bearer ${r}`),t(e)),n=(0,ir.cf)({baseUrl:ar,httpVersion:"1.1",interceptors:[e]}),s=(0,l.createClient)(Vt,n);return(await s.getServerConfig(new pt)).http2Config}catch(t){return void or.v.log(`Failed to fetch server HTTP/2 config: ${t instanceof Error?t.message:String(t)}`)}}(t);void 0!==r&&dr.set(t,r)})().finally((()=>{pr.delete(t)}));pr.set(t,e),await e}class Jr{map(t){if(t.name===h.N.methods.run.name)return{name:"RunSSE",I:u.$r,O:t.O,kind:c.MethodKind.ServerStreaming};throw new Error(`Unknown method: ${t.name}`)}}async function wr(t,r,e){const n=r.endsWith("/")?r.slice(0,-1):r;try{const r=await fetch(`${n}/auth/exchange_user_api_key`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:"{}",signal:e});if(!r.ok){const t=await r.text().catch((()=>"")),e=function(t){try{const r=JSON.parse(t);if(!(0,sr.u)(r))return;const e=(0,sr.u)(r.error)?r.error:r;return"string"==typeof e.message?e.message:void 0}catch{return}}(t);throw 401===r.status?new rr.v3(e??"Invalid API key. Please check your Cursor API key and try again.",{code:"unauthenticated",isRetryable:!1}):404===r.status?new rr.j1("API key exchange endpoint not found. Please verify your backend URL.",{code:"not_found",isRetryable:!1}):429===r.status?new rr.OE(e??"Rate limited during API key exchange.",{code:"resource_exhausted",isRetryable:!0}):r.status>=500?new rr.Dr(`Server error during API key exchange: ${t||r.statusText}`,{code:"internal",isRetryable:!0}):new rr.c$(`API key exchange failed with status ${r.status}: ${t||r.statusText}`,{code:"unknown",isRetryable:!1})}const s=await r.json();if("string"==typeof s.accessToken&&s.accessToken.length>0)return s.accessToken;throw new rr.j1("API key exchange succeeded but returned no access token. Please check your API key and try again.",{code:"internal",isRetryable:!1})}catch(t){if(t instanceof rr.LF)throw t;throw new rr.Dr(`Failed to connect to API key exchange endpoint: ${t instanceof Error?t.message:"Unknown error"}`,{code:"unavailable",isRetryable:!0})}}async function yr(t,r){try{const n=await wr(t,ar,r);if(!n)return;const s=t=>async r=>(r.header.set("authorization",`Bearer ${n}`),t(r)),i=(0,ir.cf)({baseUrl:ar,httpVersion:(e=ar,hr(e)||((0,er.it)()??gr())?"1.1":"2"),interceptors:[s]}),o=(0,l.createClient)(_.I,i);return(await o.getUserPrivacyMode(new J.KoG({inferredPrivacyMode:w.Y.NO_STORAGE}),{signal:r})).privacyMode}catch(t){return void or.v.log(`Failed to fetch user privacy mode: ${t instanceof Error?t.message:String(t)}`)}var e}const Sr=t=>t&&cr.has(t)?cr.get(t):ur;async function qr(t){const r=(0,tr.Lc)(t);if(!r)return!1;const e=await async function(t){const r=lr.get(t);if(r&&Date.now()-r.fetchedAt<=6e4)return r.privacyMode;const e=mr.get(t);if(e)return e;const n=(async()=>{const r=new AbortController,e=setTimeout((()=>r.abort()),3e3);e.unref?.();try{const e=await yr(t,r.signal);return lr.set(t,{privacyMode:e,fetchedAt:Date.now()}),e}finally{clearTimeout(e)}})().finally((()=>{mr.delete(t)}));return mr.set(t,n),n}(r);return e===w.Y.NO_TRAINING||e===w.Y.USAGE_DATA_TRAINING_ALLOWED||e===w.Y.USAGE_CODEBASE_TRAINING_ALLOWED}function Br(){const t=process.env.AGENT_CLI_STATIC_VERSION;if("string"==typeof t&&""!==t.trim())return`cli-${t.trim()}`;const r=process.env.CURSOR_AGENTKIT_VERSION;if("string"==typeof r&&""!==r.trim())return`agentkit-${r.trim()}`;const e=Zt.rE,n=process.env.CURSOR_SDK_PYTHON_VERSION;if("python"===process.env.CURSOR_SDK_CLIENT_LANGUAGE){const t="string"==typeof n&&""!==n.trim()?n.trim():"string"==typeof e&&""!==e.trim()?e.trim():void 0;return void 0!==t?`sdk-python-${t}`:"sdk-python-unknown"}return"string"==typeof e&&""!==e.trim()?`sdk-${e}`:"sdk-unknown"}async function Ir(t){if(!t)return;if(cr.has(t))return void(ur=cr.get(t));const r=fr.get(t);if(r)return await r,void(ur=cr.get(t)??ur);const e=(async()=>{const r=await yr(t);lr.set(t,{privacyMode:r,fetchedAt:Date.now()});const e=(t=>t===w.Y.USAGE_DATA_TRAINING_ALLOWED||t===w.Y.USAGE_CODEBASE_TRAINING_ALLOWED?"false":"true")(r);ur=e,cr.set(t,e)})().finally((()=>{fr.delete(t)}));fr.set(t,e),await e}const Pr=18e5;function br(t){return t instanceof l.ConnectError&&t.code===l.Code.Unauthenticated}function Rr(t){return t instanceof rr.LF&&t.isRetryable}async function*vr(t,r){try{yield*t}catch(t){throw br(t)&&r(),t}}const xr=new Set(["asr-runner","asr-at-rest","vuln-hunter"]);function kr(t){let r,e,s;return{getBearer:async()=>{if(void 0!==s)throw s;const i=r;if(void 0!==i&&Date.now(){const e=await wr(t,ar);if(!e)throw new rr.j1("API key exchange succeeded but returned no access token. Please check your API key and try again.",{code:"internal",isRetryable:!1});const s=Date.now(),i=function(t,r){try{const e=t.split(".")[1];if(void 0===e)return r+Pr;const s=JSON.parse(n.Buffer.from(e,"base64url").toString("utf8"));if(!(0,sr.u)(s)||"number"!=typeof s.exp)return r+Pr;const i=1e3*s.exp;return Number.isFinite(i)&&i>0?i:r+Pr}catch{return r+Pr}}(e,s),o={value:e,expiresAtMs:i,refreshAtMs:Math.max(i-3e5,s+(i-s)/2)};return r=o,o})().catch((t=>{const r=t instanceof Error?t:new Error(String(t));throw r instanceof rr.LF&&!r.isRetryable&&(s=r),r})).finally((()=>{e=void 0})));try{return await e}catch(t){if(void 0!==i&&r===i&&Date.now(){r===t&&(r=void 0)}}}const Er=[500,1500];function Cr({getBearer:t}){return async()=>{for(let r=0;;r++)try{return(await t()).value}catch(t){const e=Er[r];if(Rr(t)&&void 0!==e){await(0,Xt.cb)(e);continue}return void or.v.log(`Failed to get an access token for the API key: ${t instanceof Error?t.message:String(t)}`)}}}function Tr(t,r){const e=kr(t);return{transport:Ar(e,t,r),getAccessToken:Cr(e)}}function Ur(t,r){return Ar(kr(t),t,r)}function Ar({getBearer:t,invalidateBearer:r},e,n){const s=(0,nr.E)(n),i=n=>async i=>{i.header.set("x-cursor-client-version",Br()),i.header.set("x-cursor-client-type","sdk"),function(t){const r=process.env.CURSOR_HOST_APP_NAME?.trim();void 0!==r&&xr.has(r)&&t.set("x-cursor-host-app-name",r)}(i.header);const o=cr.get(e)??ur;i.header.set("x-ghost-mode",o),void 0===s||i.header.get(nr.P)||i.header.set(nr.P,String(s)),i.header.get("x-request-id")||i.header.set("x-request-id",(0,Yt.C)());const a=async t=>{i.header.set("authorization",`Bearer ${t.value}`);const e=await n(i);return e.stream?{...e,message:vr(e.message,(()=>{r(t)}))}:e};let u=await t();try{return await a(u)}catch(e){if(br(e)){if(r(u),i.stream)throw or.v.log("Auth rejected, invalidating cached token"),e;or.v.log("Auth expired, re-authenticating"),u=await t()}else{if(i.stream||!function(t,r){return t instanceof l.ConnectError&&t.code===l.Code.Unavailable&&!t.metadata.has("retry-after")&&r.service.typeName!==g.typeName&&t.findDetails(y.vj).some((t=>!0===t.details?.isRetryable))}(e,i))throw e;if(or.v.log("Request unavailable, retrying once"),await(0,Xt.st)(1e3*Math.random(),i.signal),i.signal.aborted)throw e}try{return await a(u)}catch(t){throw br(t)&&r(u),t}}},o=((t,r)=>{const e=(0,er.it)(),n=hr(t)||(e??gr());switch(void 0!==r?dr.get(r):void 0){case j.FORCE_ALL_DISABLED:case j.FORCE_BIDI_DISABLED:return!0;case j.FORCE_ALL_ENABLED:case j.FORCE_BIDI_ENABLED:return!1;case j.UNSPECIFIED:default:return n}})(ar,e),a=(0,ir.cf)({baseUrl:ar,httpVersion:o?"1.1":"2",interceptors:o?[t=>async r=>(r.header.set("x-cursor-streaming","true"),t(r)),i]:[i]});if(!o)return a;const u=(0,l.createClient)(g,a);return new p(new Jr,u,a,(t=>{or.v.log(`Bidi SSE transport error: ${t instanceof Error?t.message:String(t)}`)}))}function $r(t,r){let e=t;return{async run(...t){try{await e.run(...t)}catch(n){if(!(n instanceof l.ConnectError&&n.code===l.Code.Unauthenticated)){if(n instanceof l.ConnectError)throw(0,rr.e_)(n);throw n}e=r();try{await e.run(...t)}catch(t){if(t instanceof l.ConnectError)throw(0,rr.e_)(t);throw t}}}}}const Mr=new Map([[[255,216,255],"image/jpeg"],[[137,80,78,71],"image/png"]]);function Or(t){for(const[r,e]of Mr)if(t.length>=r.length&&r.every(((r,e)=>t[e]===r)))return e}},"./src/agent/filesystem/compose.ts"(t,r,e){e.d(r,{Mb:()=>J,VL:()=>g,w1:()=>S});var n=e("./src/agent/filesystem/errors.ts"),s=e("./src/agent/filesystem/merge.ts"),i=e("./src/agent/filesystem/trees.ts"),o=e("./src/agent/filesystem/walk.ts");function a(t,r){let e;for(const n of r)(0,o.hJ)({path:t,prefix:n.prefix})&&(void 0===e||n.prefix.length>e.prefix.length)&&(e=n);return e}function u(t,r){return r.filter((r=>r.prefix!==t&&(0,o.hJ)({path:r.prefix,prefix:t})))}function c(t){return"/"===t?0:t.split("/").length-1}function l(t,r){return"/"===r?t:t===r?"/":t.startsWith(`${r}/`)?t.slice(r.length):t}function m(t,r){return"/"===r?t:"/"===t||""===t?r:t.startsWith("/")?`${r}${t}`:`${r}/${t}`}async function*f(t,r){try{for await(const e of t)yield{...e,path:m(e.path,r)}}catch(t){throw(0,n.Zu)(t,r)}}async function*d(t,{owner:r,mounts:e}){const n=e.filter((t=>t.prefix.length>r.prefix.length));for await(const r of t)n.some((t=>r.path!==t.prefix&&(0,o.hJ)({path:r.path,prefix:t.prefix})))||(yield r)}async function*p(t,r){const e={maxDepth:1,excludes:r?.excludes};for await(const n of f(t.fs.list(void 0,e),t.prefix))if(!(0,o.a)(n.path,r?.excludes))return void(yield n)}function h(t,r){return{excludes:t?.excludes,maxDepth:r}}function g(t){const r=Object.entries(t).map((([t,r])=>({prefix:(0,o.eI)(t),fs:r})));r.sort(((t,r)=>r.prefix.length-t.prefix.length));const e=(t,e)=>d(f(e,t.prefix),{owner:t,mounts:r}),i=async(t,e)=>{const s=a(t,r);if(void 0===s)throw new n.VV(t);try{return await e(s.fs,l(t,s.prefix))}catch(t){throw(0,n.Zu)(t,s.prefix)}};return{async*list(t,n){const s=(0,o.c9)(t),i=async function*(t,r){for await(const e of t)(0,o.a)(e.path,r)||(yield e)}((0,o.mU)(((t,n)=>{const s=(0,o.eV)(n);void 0===s&&(n?.excludes?.length??0)>0&&(n={...n,limit:void 0});const i=[];for(const o of u(t,r)){if(void 0===s){i.push(e(o,o.fs.list(void 0,n)));continue}const r=s-(c(o.prefix)-c(t));i.push(r<1?p(o,n):e(o,o.fs.list(void 0,h(n,r))))}const m=a(t,r);if(void 0!==m){const r=l(t,m.prefix),o=void 0===s?n:h(n,s);i.push(e(m,m.fs.list("/"===r?void 0:r,o)))}return i})(s,n),{unique:!0}),n?.excludes),m=(0,o.eV)(n);void 0!==m?yield*(0,o.SC)(i,{scope:s,maxDepth:m,limit:n?.limit}):yield*(0,o.I6)(i,n?.limit)},async stat(t){const e=(0,o.eI)(t);if("/"===e)return{kind:"directory"};if(r.some((t=>t.prefix===e)))return{kind:"directory"};const n=a(e,r),s=void 0===n?{kind:"missing"}:await n.fs.stat(l(e,n.prefix));return"missing"===s.kind&&u(e,r).length>0?{kind:"directory"}:s},read:async t=>i((0,o.eI)(t),((t,r)=>t.read(r))),write:async(t,r)=>i((0,o.eI)(t),((t,e)=>t.write(e,r))),delete:async t=>i((0,o.eI)(t),((t,r)=>t.delete(r))),async*grep(t){yield*(0,o.I6)(async function*(){const n=void 0===t.path||""===t.path?"/":(0,o.eI)(t.path);if("/"===n)return void(yield*(0,s.C)(r.map((r=>e(r,r.fs.grep({...t,path:void 0})))),{compare:o.h}));const i=a(n,r);if(void 0===i)return;const u=l(n,i.prefix);yield*e(i,i.fs.grep({...t,path:"/"===u?void 0:u}))}(),t.maxResults)},async*glob(t,n,s){yield*(0,o.I6)(async function*(){const i=void 0===n||""===n?"/":(0,o.eI)(n);if("/"===i)return void(yield*(0,o.mU)(r.map((r=>e(r,r.fs.glob(t,void 0,s)))),{unique:!0}));const c=u(i,r).map((e=>d(async function*(t,r,e){for await(const n of f(t.fs.list(void 0),t.prefix))(0,o.ZC)({filePath:n.path,dir:r,globPattern:e})&&(yield n)}(e,i,t),{owner:e,mounts:r}))),m=a(i,r);if(void 0!==m){const r=l(i,m.prefix);c.push(e(m,m.fs.glob(t,"/"===r?void 0:r,s)))}yield*(0,o.mU)(c,{unique:!0})}(),s?.limit)}}}async function _(t){const r=[];try{for await(const e of t.list())r.push(e.path)}catch{}return r}function J(t){if(0===t.length)throw new Error("overlayFs needs at least one layer.");const r=async r=>{const e=[];let n,s=!1;for(const i of t){const t=[];try{for await(const e of r(i))t.push(e)}catch(t){n??=t;continue}s=!0,e.push(t)}if(!s&&void 0!==n)throw n;return e};return{async*list(t,e){const n=(0,o.eV)(e),s=void 0===n?e:h(e,n),i=await r((r=>r.list(t,s))),a=(0,o.mU)(i,{unique:!0});void 0!==n?yield*(0,o.SC)(a,{scope:(0,o.c9)(t),maxDepth:n,limit:e?.limit}):yield*(0,o.I6)(a,e?.limit)},async stat(r){let e,n=!1;for(const s of t)try{const t=await s.stat(r);if("missing"!==t.kind)return t;n=!0}catch(t){e??=t}if(!n&&void 0!==e)throw e;return{kind:"missing"}},async*glob(t,e,n){const s=await r((r=>r.glob(t,e,n)));yield*(0,o.I6)((0,o.mU)(s,{unique:!0}),n?.limit)},async read(r){let e;for(const s of t)try{return await s.read(r)}catch(t){if((0,n.Wp)(t))continue;e??=t}if(void 0!==e)throw e;throw new n.kG(r)},async*grep(r){const{maxResults:e,...i}=r,a=await(async(r,e)=>{const n=[],s=new Set;let i,o=!1;for(const a of t){const t=[];try{for await(const e of r(a))s.has(e.path)||t.push(e);o=!0}catch(t){if(!0===e?.(t))throw t;i??=t;continue}n.push(t);for(const t of await _(a))s.add(t)}if(!o&&void 0!==i)throw i;return n})((t=>t.grep(i)),(t=>(0,n.q_)(t)));yield*(0,o.I6)((0,s.C)(a,{compare:o.h}),e)},async write(t){throw new n.QK(t)},async delete(t){throw new n.QK(t)}}}function w(t,r){const e=t=>!r.has((0,o.eI)(t));async function*s(t){for await(const r of t)e(r.path)&&(yield r)}return{async*list(e,n){const i=(0,o.eV)(n);if(0===r.size)return void(yield*t.list(e,n));if(void 0===i){const r={...n,limit:void 0};return void(yield*(0,o.I6)(s(t.list(e,r)),n?.limit))}const a=s(t.list(e,{excludes:n?.excludes}));yield*(0,o.SC)(a,{scope:(0,o.c9)(e),maxDepth:i,limit:n?.limit})},async stat(n){const s=(0,o.eI)(n);if(r.has(s))return{kind:"missing"};const i=await t.stat(n);if("directory"!==i.kind||"/"===s)return i;if(![...r].some((t=>(0,o.hJ)({path:t,prefix:s}))))return i;let a=!1;for await(const r of t.list(s)){if(e(r.path))return i;a=!0}return a?{kind:"missing"}:i},async*glob(e,n,i){if(0===r.size)return void(yield*t.glob(e,n,i));const a={...i,limit:void 0};yield*(0,o.I6)(s(t.glob(e,n,a)),i?.limit)},async read(e){const s=(0,o.eI)(e);if(r.has(s))throw new n.kG(s);return t.read(e)},async*grep(r){for await(const n of t.grep(r))e(n.path)&&(yield n)},async write(t){throw new n.QK((0,o.eI)(t))},async delete(t){throw new n.QK((0,o.eI)(t))}}}async function y(t,r){if("missing"===(await t.stat(r)).kind)try{await t.read(r)}catch(t){if((0,n.Wp)(t))return;throw t}}function S(t){const r=(0,i.Om)(),e=new Set,s=J([r,w(t,e)]);return{list:(t,r)=>s.list(t,r),stat:t=>s.stat(t),glob:(t,r,e)=>s.glob(t,r,e),read:t=>s.read(t),grep:t=>s.grep(t),async write(i,a){const u=(0,o.eI)(i);if(await y(t,u),"directory"===(await s.stat(u)).kind)throw new n.JA(u,`path is a directory: ${u}`);e.delete(u),await r.write(u,a)},async delete(i){const a=(0,o.eI)(i);if(await y(t,a),"file"!==(await s.stat(a)).kind)throw new n.kG(a);e.add(a);try{await r.delete(a)}catch(t){if(!(0,n.Wp)(t))throw t}}}}},"./src/agent/filesystem/errors.ts"(t,r,e){e.d(r,{ER:()=>a,F:()=>d,JA:()=>m,QK:()=>c,VV:()=>l,Wp:()=>h,Zu:()=>J,kG:()=>u,kp:()=>p,q_:()=>g,x$:()=>f});var n=e("node:path"),s=e.n(n);function i(t){const r=t.replace(/\\/g,"/");if(""===r)return"/";const e=r.startsWith("/")?r:`/${r}`,n=s().posix.normalize(e);return n.length>1&&n.endsWith("/")?n.slice(0,-1):"."===n||""===n?"/":n}const o=/^(not found|read-only mount|write failed|edit failed|no mount for path|delete is not supported): \/$/;class a extends Error{constructor(t,r){super(r),this.name=Object.hasOwn(new.target,"errorName")?new.target.errorName:new.target.name,this.path=i(t)}withPath(t){const r=i(t);return r===this.path?this:this.recreate(r,(e=this.message,(n=this.path)===(s=r)?e:"/"===n?o.test(e)?e.replace(/\/$/,s):e:e.includes(n)?e.split(n).join(s):e));var e,n,s}recreate(t,r){return new a(t,r)}}a.errorName="PathError";class u extends a{constructor(t,r){super(t,r??`not found: ${i(t)}`)}recreate(t,r){return new u(t,r)}}u.errorName="FileNotFoundError";class c extends a{constructor(t,r){super(t,r??`read-only mount: ${i(t)}`)}recreate(t,r){return new c(t,r)}}c.errorName="ReadOnlyMountError";class l extends a{constructor(t,r){super(t,r??`no mount for path: ${i(t)}`)}recreate(t,r){return new l(t,r)}}l.errorName="NoMountError";class m extends a{constructor(t,r){super(t,r??`write failed: ${i(t)}`)}recreate(t,r){return new m(t,r)}}m.errorName="WriteFailedError";class f extends a{constructor(t,r){super(t,r??`delete is not supported: ${i(t)}`)}recreate(t,r){return new f(t,r)}}f.errorName="DeleteNotSupportedError";class d extends a{recreate(t,r){return new d(t,r)}}d.errorName="EditError";class p extends a{constructor(t,r="/",e){super(r,e??`invalid grep pattern: ${t}`),this.pattern=t}recreate(t,r){return new p(this.pattern,t,r)}}function h(t){return t instanceof u||t instanceof Error&&t.message.startsWith("not found:")}function g(t){return t instanceof p||t instanceof Error&&t.message.startsWith("invalid grep pattern:")}p.errorName="InvalidGrepPatternError";const _=["not found: ","read-only mount: ","write failed: ","edit failed: ","no mount for path: ","delete is not supported: "];function J(t,r){return t instanceof a?t.withPath(w(t.path,r)):t instanceof Error?function(t,r){for(const e of _){if(!t.message.startsWith(e))continue;const n=`${e}${w(t.message.slice(e.length),r)}`;if(n===t.message)return t;const s=new Error(n);return s.name=t.name,s}return t}(t,r):new a(r,String(t))}function w(t,r){const e=i(r),n=i(t);return"/"===e?n:"/"===n?e:`${e}${n}`}},"./src/agent/filesystem/executors.ts"(t,r,e){e.d(r,{c9:()=>q,mv:()=>y});var n=e("node:buffer"),s=e("node:path"),i=e("../proto/dist/generated/agent/v1/delete_exec_pb.js"),o=e("../proto/dist/generated/agent/v1/grep_exec_pb.js"),a=e("../proto/dist/generated/agent/v1/ls_exec_pb.js"),u=e("../proto/dist/generated/agent/v1/read_exec_pb.js"),c=e("../proto/dist/generated/agent/v1/write_exec_pb.js"),l=e("./src/agent/filesystem/errors.ts"),m=e("./src/agent/filesystem/walk.ts");function f(t){const r=(0,m.c9)(t.dir),e=d(r),n=new Map([[r,e]]),s={charactersUsed:r.length,budgetExceeded:!1};for(const e of t.entries)if("directory"!==e.kind)p({filePath:e.path,rootPath:r,nodes:n,state:s});else{const t=g({dirPath:e.path,rootPath:r,nodes:n,state:s});void 0!==t&&(t.childrenWereProcessed=!1)}return t.truncated&&(e.childrenWereProcessed=!1),e}function d(t){return new a.vq({absPath:t,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!0,fullSubtreeExtensionCounts:{},numFiles:0})}function p(t){const{filePath:r,rootPath:e,nodes:n,state:i}=t,o=J(r),u=g({dirPath:o,rootPath:e,nodes:n,state:i});if(void 0===u)return;const c=s.posix.basename(r);if(!i.budgetExceeded&&i.charactersUsed+c.length<=2500)return u.childrenFiles.push(new a.ur({name:c})),void(i.charactersUsed+=c.length);if(!i.budgetExceeded){i.budgetExceeded=!0;for(const t of h({dirPath:o,rootPath:e,nodes:n}))t.childrenWereProcessed=!1}const l=s.posix.extname(r);for(const t of h({dirPath:o,rootPath:e,nodes:n}))t.fullSubtreeExtensionCounts[l]=(t.fullSubtreeExtensionCounts[l]??0)+1,t.numFiles+=1}function*h(t){let r=t.dirPath;for(;_({path:r,rootPath:t.rootPath});){const e=t.nodes.get(r);void 0!==e&&(yield e);const n=J(r);if(n===r)return;r=n}}function g(t){const{dirPath:r,rootPath:e,nodes:n,state:s}=t,i=n.get(r);if(void 0!==i)return i;if(!_({path:r,rootPath:e}))return;const o=g({dirPath:J(r),rootPath:e,nodes:n,state:s});if(void 0===o)return;const a=d(r);return a.childrenWereProcessed=!s.budgetExceeded,n.set(r,a),o.childrenDirs.push(a),a}function _(t){return"/"===t.rootPath||t.path===t.rootPath||t.path.startsWith(`${t.rootPath}/`)}function J(t){const r=s.posix.dirname(t);return"."===r||r===t?"/":r}var w=e("./src/agent/filesystem/types.ts");function y(t){const r=(t.path??"").replace(/\\/g,"/");if(""===r)return t.workspace;const e=r.startsWith("/")||/^[A-Za-z]:(?:\/|$)/.test(r);return(0,m.eI)(e?r:s.posix.join(t.workspace,r))}function S(t){return(0,m.eI)(t?.workspace??"/")}function q(t,r){return{read:B(t,r),write:R(t,r),grep:U(t,r),ls:E(t,r),delete:x(t,r)}}function B(t,r){const e=S(r);return{execute:(r,s)=>async function({fs:t,workspace:r},e){const s=y({workspace:r,path:e.path});let i;try{if("directory"===(await t.stat(s)).kind)return P({case:"invalidFile",value:new u.cW({path:s,reason:"Path is a directory, not a file"})});i=await t.read(s)}catch(t){return function(t){const r=N(t.error,t.path);return(0,l.Wp)(t.error)?P({case:"fileNotFound",value:new u.Ko({path:r})}):t.error instanceof l.QK?P({case:"permissionDenied",value:new u.lW({path:r})}):P({case:"error",value:new u.F_({path:r,error:G(t.error,"read failed")})})}({path:s,error:t})}if(i instanceof Uint8Array){if(void 0!==function(t){const{bytes:r}=t;if(b(r,[255,216,255]))return"image/jpeg";if(b(r,[137,80,78,71]))return"image/png";if(b(r,[71,73,70]))return"image/gif";if(b(r,[82,73,70,70])&&r.length>=12&&"WEBP"===String.fromCharCode(r[8]??0,r[9]??0,r[10]??0,r[11]??0))return"image/webp";const e=t.path.toLowerCase();return e.endsWith(".jpg")||e.endsWith(".jpeg")?"image/jpeg":e.endsWith(".png")?"image/png":e.endsWith(".gif")?"image/gif":e.endsWith(".webp")?"image/webp":void 0}({bytes:i,path:s})||function(t,r){return b(t,[37,80,68,70])||r.toLowerCase().endsWith(".pdf")}(i,s))return P({case:"success",value:new u.mE({path:s,output:{case:"data",value:i},totalLines:0,fileSize:BigInt(i.byteLength),truncated:!1,rangeApplied:!1})});const t=function(t){let r;try{r=new TextDecoder(t.encodingHint??"utf-8",{fatal:!0})}catch{r=new TextDecoder("utf-8",{fatal:!0})}try{const e=r.decode(t.bytes);return e.includes("\0")?void 0:e}catch{return}}({bytes:i,encodingHint:e.encodingHint});return void 0===t?P({case:"invalidFile",value:new u.cW({path:s,reason:"File content is binary data, not text"})}):I({path:s,text:t,fileSize:i.byteLength,args:e})}return I({path:s,text:i,fileSize:n.Buffer.byteLength(i,"utf8"),args:e})}({fs:t,workspace:e},s)}}function I(t){const{text:r}=t,e=r.split("\n"),n=e.length,s=""===r?void 0:function(t){if(void 0===t.offset&&void 0===t.limit||0===t.totalLines)return;const r=t.offset??1,e=t.limit??(r<0?Math.abs(r):t.totalLines),n=r<0?Math.max(0,t.totalLines+r):Math.max(0,r-1);return n>=t.totalLines?void 0:{start:n,end:Math.min(t.totalLines,n+e)}}({totalLines:n,offset:t.args.offset,limit:t.args.limit});return P({case:"success",value:new u.mE({path:t.path,output:{case:"content",value:void 0===s?r:e.slice(s.start,s.end).join("\n")},totalLines:n,fileSize:BigInt(t.fileSize),truncated:!1,rangeApplied:void 0!==s})})}function P(t){return new u.sV({result:t})}function b(t,r){return t.length>=r.length&&r.every(((r,e)=>t[e]===r))}function R(t,r){const e=S(r);return{execute:(r,s)=>async function({fs:t,workspace:r},e){const s=y({workspace:r,path:e.path}),i=e.fileBytes.length>0?e.fileBytes:e.fileText;try{if("directory"===(await t.stat(s)).kind)return v({case:"error",value:new c.QM({path:s,error:`EISDIR: illegal operation on a directory, open '${s}'`})});await t.write(s,i)}catch(t){return function(t){const r=N(t.error,t.path);return t.error instanceof l.QK?v({case:"permissionDenied",value:new c.U7({path:r,directory:"",operation:"create_file",error:t.error.message,isReadonly:!0})}):v({case:"error",value:new c.QM({path:r,error:G(t.error,"write failed")})})}({path:s,error:t})}let o;if(e.returnFileContentAfterWrite)try{const r=await t.read(s);o="string"==typeof r?r:void 0}catch{o=void 0}const a="string"==typeof i?i:void 0;return v({case:"success",value:new c.j6({path:s,linesCreated:void 0===a||""===a?0:a.split("\n").length,fileSize:"string"==typeof i?n.Buffer.byteLength(i):i.byteLength,fileContentAfterWrite:o})})}({fs:t,workspace:e},s)}}function v(t){return new c.v3({result:t})}function x(t,r){const e=S(r);return{execute:(r,s)=>async function({fs:t,workspace:r},e){const s=y({workspace:r,path:e.path});let o,a;try{const r=await t.stat(s);if("missing"===r.kind)return k({case:"fileNotFound",value:new i.n0({path:s})});if("directory"===r.kind)return k({case:"notFile",value:new i.LX({path:s,actualType:"directory"})});const e=await t.read(s);a="string"==typeof e?n.Buffer.byteLength(e):e.byteLength,o="string"==typeof e?e:"",await t.delete(s)}catch(t){return function(t){const r=N(t.error,t.path);return(0,l.Wp)(t.error)?k({case:"fileNotFound",value:new i.n0({path:r})}):t.error instanceof l.QK?k({case:"permissionDenied",value:new i.QG({path:r,clientVisibleError:t.error.message,isReadonly:!0})}):t.error instanceof l.x$?k({case:"rejected",value:new i.iq({path:r,reason:t.error.message})}):k({case:"error",value:new i.GU({path:r,error:G(t.error,"delete failed")})})}({path:s,error:t})}return k({case:"success",value:new i.fl({path:s,deletedFile:s,fileSize:BigInt(a),prevContent:o})})}({fs:t,workspace:e},s)}}function k(t){return new i.Pi({result:t})}function E(t,r){const e=S(r);return{execute:(r,n)=>async function({fs:t,workspace:r},e){const n=y({workspace:r,path:e.path}),s=e.ignore.length>0?e.ignore:void 0,i=[];try{for await(const r of t.list(n,{excludes:s,limit:w.H+1,maxDepth:3})){const t=(0,m.eI)(r.path);(0,m.a)(t,s)||i.push({...r,path:t})}if(0===i.length){const r=(await t.stat(n)).kind;if("missing"===r)return C({path:n,error:`Path does not exist: ${n}`});if("file"===r)return C({path:n,error:`Path is not a directory: ${n}`})}}catch(t){return C({path:n,error:G(t,"list failed")})}const o=(0,m.e4)({entries:i,scope:n,maxDepth:3}),u=i.length>w.H||o.length>w.H;return new a.fv({result:{case:"success",value:new a.PC({directoryTreeRoot:f({dir:n,entries:o.slice(0,w.H),truncated:u})})}})}({fs:t,workspace:e},n)}}function C(t){return new a.fv({result:{case:"error",value:new a.uj({path:t.path,error:t.error})}})}const T={c:"*.{c,h}",cpp:"*.{cc,cpp,cxx,hh,hpp,hxx,h}",css:"*.{css,scss,sass,less}",go:"*.go",html:"*.{htm,html}",java:"*.java",js:"*.{js,jsx,mjs,cjs}",json:"*.json",kotlin:"*.{kt,kts}",md:"*.{md,markdown,mdx}",markdown:"*.{md,markdown,mdx}",py:"*.{py,pyi}",python:"*.{py,pyi}",rb:"*.rb",ruby:"*.rb",rust:"*.rs",sh:"*.{sh,bash,zsh}",sql:"*.sql",swift:"*.swift",toml:"*.toml",ts:"*.{ts,tsx,mts,cts}",typescript:"*.{ts,tsx,mts,cts}",yaml:"*.{yaml,yml}"};function U(t,r){const e=S(r);return{execute:(r,n)=>async function({fs:t,workspace:r},e){const n="files"===(i=e.outputMode)||"files_with_matches"===i?"files_with_matches":"count"===i?"count":"content",s=y({workspace:r,path:e.path});var i;try{if(!0===e.multiline)return M("multiline grep is not supported on this filesystem");const i=function(t){const r=""===t.glob?void 0:t.glob;if(void 0===t.type||""===t.type)return r;const e=T[t.type.toLowerCase()];if(void 0===e)throw new Error(`unsupported grep type: ${t.type}. Use glob instead.`);if(void 0!==r)throw new Error("grep type and glob cannot be combined on this filesystem. Use glob only.");return e}({glob:e.glob,type:e.type});if("missing"===(await t.stat(s)).kind)return M(`Path does not exist: ${s}`);const a={headLimit:D(e.headLimit),offset:D(e.offset)??0},u=""===e.pattern&&"files_with_matches"===n?await async function(t){const r=w.H,e=[];for await(const n of t.fs.glob(t.glob??"**",t.path,{limit:r+1}))"directory"!==n.kind&&e.push((0,m.eI)(n.path));const n=e.length>r,s=e.slice(0,r),i=void 0===t.page.headLimit?void 0:t.page.offset+t.page.headLimit,a=s.slice(t.page.offset,i);return new o.vD({result:{case:"files",value:new o.T7({files:a,totalFiles:s.length,clientTruncated:n||a.length0?t.page.offset:void 0})}})}({fs:t,path:s,glob:i,page:a}):await async function(t){const{matches:r,truncated:e}=await async function(t){const{headLimit:r,offset:e}=t.page,n="content"===t.outputMode,s=n&&void 0!==r?e+r+1:void 0,i=[],o=new Set,a=new Set;let u=0,c=0;for await(const l of t.fs.grep({...t.query,maxResults:s}))if(n){if(u=r)return{matches:i,truncated:!0};i.push(l),c++}else if(!o.has(l.path)){if(!a.has(l.path)){if(u=r)return{matches:i,truncated:!0};a.add(l.path),c++}i.push(l)}return{matches:i,truncated:!1}}(t),n={clientTruncated:e,ripgrepTruncated:e,headLimitApplied:t.page.headLimit,offsetApplied:t.page.offset>0?t.page.offset:void 0};if("files_with_matches"===t.outputMode){const t=[...new Set(r.map((t=>t.path)))];return new o.vD({result:{case:"files",value:new o.T7({files:t,totalFiles:t.length,...n})}})}if("count"===t.outputMode){const t=new Map;for(const e of r)t.set(e.path,(t.get(e.path)??0)+1);const e=[...t].map((([t,r])=>new o.sS({file:t,count:r})));return new o.vD({result:{case:"count",value:new o.xA({counts:e,totalFiles:e.length,totalMatches:r.length,...n})}})}const s=await async function(t){const{before:r,after:e}=t.context,n=new Map,s=new Map;for(const i of t.matches){let a=n.get(i.path);void 0===a&&(a=new Map,n.set(i.path,a));let u=s.get(i.path);void 0===u&&(r>0||e>0)&&(u=await $(t.fs,i.path),s.set(i.path,u));const c=i.lineNumber-1;if(void 0!==u)for(let t=Math.max(0,c-r);tnew o.uI({file:t,matches:[...r.entries()].sort(((t,r)=>t[0]-r[0])).map((t=>t[1]))})))}({fs:t.fs,matches:r,context:t.context});return new o.vD({result:{case:"content",value:new o.Zp({matches:s,totalLines:s.reduce(((t,r)=>t+r.matches.length),0),totalMatchedLines:r.length,...n})}})}({fs:t,query:{pattern:e.pattern,path:s,glob:i,caseInsensitive:!0===e.caseInsensitive},outputMode:n,page:a,context:"content"===n?{before:O({specific:e.contextBefore,both:e.context}),after:O({specific:e.contextAfter,both:e.context})}:{before:0,after:0}});return new o.Ud({result:{case:"success",value:new o._0({pattern:e.pattern,path:s,outputMode:n,workspaceResults:{[r]:u}})}})}catch(t){return M((0,l.q_)(t)?G(t,`invalid grep pattern: ${e.pattern}`):G(t,"grep failed"))}}({fs:t,workspace:e},n)}}function A(t){t.rows.has(t.lineNumber)||t.rows.set(t.lineNumber,new o.dx({lineNumber:t.lineNumber,content:t.content,contentTruncated:!1,isContextLine:!0}))}async function $(t,r){try{return(0,m.Zy)(await t.read(r)).split("\n")}catch{return[]}}function M(t){return new o.Ud({result:{case:"error",value:new o.ts({error:t})}})}function O(t){return D(t.specific??t.both)??0}function D(t){if(void 0!==t&&Number.isFinite(t)&&!(t<=0))return Math.floor(t)}function N(t,r){return t instanceof Error&&"path"in t&&"string"==typeof t.path?t.path:r}function G(t,r){return t instanceof Error&&""!==t.message?t.message:r}},"./src/agent/filesystem/local-fs.ts"(t,r,e){e.d(r,{I2:()=>a,VP:()=>o,rK:()=>i,xh:()=>u});var n=e("node:path"),s=e("./src/agent/errors.ts");const i="localFileSystem";function o(...t){if(t.some((t=>void 0!==t?.fs)))throw new s.j1("local.fs is only supported for local SDK agents. Omit cloud options, or omit local.fs.",{isRetryable:!1})}function a(t){if(void 0===t.fs)return;const r=[void 0!==t.subagentInherit?"local.subagentInherit":void 0,void 0!==t.resourceProviderOptions?"local.resourceProviderOptions":void 0].filter((t=>void 0!==t));if(r.length>0)throw new s.j1(`local.fs cannot be combined with ${r.join(", ")}: local.fs sets the session's executors and its Task children. Remove ${r.join(", ")}.`,{isRetryable:!1});void 0!==t.reportedWorkspacePath&&u(t.reportedWorkspacePath)}function u(t){const r=r=>{throw new s.j1(`local.reportedWorkspacePath ${JSON.stringify(t)} is not a workspace inside local.fs: ${r}.`,{isRetryable:!1})};t.startsWith("/")&&!t.includes("\\")||r('it must be an absolute posix path such as "/repo"');const e=n.posix.normalize(t),i=e.length>1&&e.endsWith("/")?e.slice(0,-1):e;return("/tmp"===i||i.startsWith("/tmp/"))&&r("/tmp is the SDK's scratch space and is empty at the start of every run"),i}},"./src/agent/filesystem/merge.ts"(t,r,e){async function*n(t,r){const{compare:e,unique:n=!1}=r,a=new o(((t,r)=>{const n=e(t.value,r.value);return 0!==n?n:t.source-r.source})),u=t.map(((t,r)=>({iterator:Symbol.asyncIterator in t?t[Symbol.asyncIterator]():async function*(){yield*t}(),sourceIndex:r})));for(await Promise.all(u.map((async({iterator:t,sourceIndex:r})=>{const e=await t.next();e.done||a.push({value:e.value,iterator:t,source:r})})));a.size>0;){const t=a.pop();if(void 0===t)return;yield t.value,n?await i(a,t,e):await s(a,t)}}async function s(t,r){const e=await r.iterator.next();e.done||t.push({value:e.value,iterator:r.iterator,source:r.source})}async function i(t,r,e){for(await s(t,r);t.size>0;){const n=t.peek();if(void 0===n||0!==e(n.value,r.value))return;const i=t.pop();if(void 0===i)return;await s(t,i)}}e.d(r,{C:()=>n});class o{constructor(t){this.compare=t,this.items=[]}get size(){return this.items.length}peek(){return this.items[0]}push(t){this.items.push(t),this.bubbleUp(this.items.length-1)}pop(){const t=this.items[0];if(void 0===t)return;const r=this.items.pop();return void 0===r||0===this.items.length||(this.items[0]=r,this.bubbleDown(0)),t}bubbleUp(t){let r=t;for(;r>0;){const t=Math.floor((r-1)/2),e=this.items[t],n=this.items[r];if(void 0===e||void 0===n||this.compare(n,e)>=0)return;this.items[t]=n,this.items[r]=e,r=t}}bubbleDown(t){let r=t;for(;;){const t=2*r+1,e=t+1;let n=r;const s=this.items[n],i=this.items[t];void 0!==i&&void 0!==s&&this.compare(i,s)<0&&(n=t);const o=this.items[n],a=this.items[e];if(void 0!==a&&void 0!==o&&this.compare(a,o)<0&&(n=e),n===r)return;const u=this.items[r],c=this.items[n];if(void 0===u||void 0===c)return;this.items[r]=c,this.items[n]=u,r=n}}}},"./src/agent/filesystem/trees.ts"(t,r,e){e.d(r,{Om:()=>l,f1:()=>c,i$:()=>f,iK:()=>m});var n=e("./src/agent/filesystem/errors.ts"),s=e("./src/agent/filesystem/walk.ts");async function*i(){}function o(t){return void 0===t||""===t?"/":(0,s.eI)(t)}function a(t){return"string"==typeof t?t:new Uint8Array(t)}const u=new TextEncoder;function c(){return{list:()=>i(),glob:()=>i(),async*grep(t){const r=o(t.path);(0,s.kN)({pattern:t.pattern,caseInsensitive:t.caseInsensitive,path:r}),yield*i()},stat:async t=>(0,s.dN)([],t),async read(t){throw new n.kG((0,s.eI)(t))},async write(t){throw new n.QK((0,s.eI)(t))},async delete(t){throw new n.QK((0,s.eI)(t))}}}function l(t={}){const r=new Map,e=new Map,i=(t,n)=>{const i=(0,s.eI)(t);r.set(i,a(n)),e.set(i,function(t){return"string"==typeof t?u.encode(t).byteLength:t.byteLength}(n))};for(const[r,e]of Object.entries(t))i(r,e);const c=()=>[...e.entries()].map((([t,r])=>({path:t,size:r})));return{list:(t,r)=>(0,s.qq)(c(),t,r),stat:async t=>(0,s.dN)(r.keys(),t),async read(t){const e=(0,s.eI)(t),i=r.get(e);if(void 0===i)throw new n.kG(e);return a(i)},async*grep(t){yield*(0,s.I6)(async function*(){const e=o(t.path),n=(0,s.kN)({pattern:t.pattern,caseInsensitive:t.caseInsensitive,path:e}),i=r.get(e);if("/"!==e&&void 0!==i){if(void 0!==t.glob&&!(0,s.ZC)({filePath:e,dir:e,globPattern:t.glob,matchBasename:!0}))return;if((0,s.a)(e,t.excludes))return;return void(yield*(0,s.sn)({path:e,content:(0,s.Zy)(i),regex:n}))}const a=(0,s.qq)(c(),"/"===e?void 0:e,void 0===t.excludes?void 0:{excludes:t.excludes});for await(const i of a){if(void 0!==t.glob&&!(0,s.ZC)({filePath:i.path,dir:e,globPattern:t.glob,matchBasename:!0}))continue;const o=r.get(i.path);void 0!==o&&(yield*(0,s.sn)({path:i.path,content:(0,s.Zy)(o),regex:n}))}}(),t.maxResults)},async*glob(t,r,e){const n=void 0===r||""===r?"/":(0,s.eI)(r);yield*(0,s.lN)((0,s.qq)(c(),"/"===n?void 0:n),{pattern:t,dir:n,limit:e?.limit})},async write(t,r){i(t,r)},async delete(t){const i=(0,s.eI)(t);if(!r.has(i))throw new n.kG(i);r.delete(i),e.delete(i)}}}function m(t){return{list:(r,e)=>t.list(r,e),stat:r=>t.stat(r),glob:(r,e,n)=>t.glob(r,e,n),read:r=>t.read(r),grep:r=>t.grep(r),async write(t){throw new n.QK((0,s.eI)(t))},async delete(t){throw new n.QK((0,s.eI)(t))}}}async function f(t,r){const e=await t.read(r.path);if("string"!=typeof e)throw new n.F(r.path,`${r.path} is not text`);if(""===r.oldText)throw new n.F(r.path,"oldText is empty");if(r.oldText===r.newText)throw new n.F(r.path,"oldText and newText are exactly the same");const s=function(t){let r=0,e=0;for(;e<=t.haystack.length-t.needle.length;){const n=t.haystack.indexOf(t.needle,e);if(-1===n)break;r++,e=n+t.needle.length}return r}({haystack:e,needle:r.oldText});if(0===s)throw new n.F(r.path,"The string to replace was not found in the file");const i=!0===r.replaceAll;if(s>1&&!i)throw new n.F(r.path,"The string to replace was found multiple times in the file. Use replace_all to replace all occurrences, or include more context to only edit one occurrence.");return await t.write(r.path,function(t){if(t.replaceAll)return t.existing.split(t.oldText).join(t.newText);const r=t.existing.indexOf(t.oldText);return-1===r?t.existing:t.existing.slice(0,r)+t.newText+t.existing.slice(r+t.oldText.length)}({existing:e,oldText:r.oldText,newText:r.newText,replaceAll:i})),{occurrencesModified:s}}},"./src/agent/filesystem/types.ts"(t,r,e){e.d(r,{H:()=>n});const n=1e3},"./src/agent/filesystem/walk.ts"(t,r,e){e.d(r,{SC:()=>ht,e4:()=>pt,h:()=>qt,kN:()=>Bt,Zy:()=>bt,lN:()=>St,sn:()=>It,a:()=>ct,I6:()=>yt,qq:()=>_t,eV:()=>ft,mU:()=>wt,eI:()=>st,c9:()=>ot,hJ:()=>it,ZC:()=>ut,dN:()=>Jt});var n=e("node:path"),s=e.n(n),i=e("../../node_modules/.pnpm/brace-expansion@5.0.12/node_modules/brace-expansion/dist/esm/index.js");const o=t=>{if("string"!=typeof t)throw new TypeError("invalid pattern");if(t.length>65536)throw new TypeError("pattern is too long")},a={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},u=t=>t.replace(/[[\]\\-]/g,"\\$&"),c=t=>t.join(""),l=(t,r)=>{const e=r;if("["!==t.charAt(e))throw new Error("not in a brace expression");const n=[],s=[];let i=e+1,o=!1,l=!1,m=!1,f=!1,d=e,p="";t:for(;ip?n.push(u(p)+"-"+u(r)):r===p&&n.push(u(r)),p="",i++):t.startsWith("-]",i+1)?(n.push(u(r+"-")),i+=2):t.startsWith("-",i+1)?(p=r,i+=2):(n.push(u(r)),i++)}else m=!0,i++}else f=!0,i++}if(de?r?t.replace(/\[([^/\\])\]/g,"$1"):t.replace(/((?!\\).|^)\[([^/\\])\]/g,"$1$2").replace(/\\([^/])/g,"$1"):r?t.replace(/\[([^/\\{}])\]/g,"$1"):t.replace(/((?!\\).|^)\[([^/\\{}])\]/g,"$1$2").replace(/\\([^/{}])/g,"$1");var f;const d=new Set(["!","?","+","*","@"]),p=t=>d.has(t),h=t=>p(t.type),g=new Map([["!",["@"]],["?",["?","@"]],["@",["@"]],["*",["*","+","?","@"]],["+",["+","@"]]]),_=new Map([["!",["?"]],["@",["?"]],["+",["?","*"]]]),J=new Map([["!",["?","@"]],["?",["?","@"]],["@",["?","@"]],["*",["*","+","?","@"]],["+",["+","@","?","*"]]]),w=new Map([["!",new Map([["!","@"]])],["?",new Map([["*","*"],["+","*"]])],["@",new Map([["!","!"],["?","?"],["@","@"],["*","*"],["+","+"]])],["+",new Map([["?","*"],["*","*"]])]]),y="(?!\\.)",S=new Set(["[","."]),q=new Set(["..","."]),B=new Set("().*{}+?[]^$\\!"),I="[^/]",P=I+"*?",b=I+"+?";let R=0;class v{type;#t;#r;#e=!1;#n=[];#s;#i;#o;#a=!1;#u;#c;#l=!1;id=++R;get depth(){return(this.#s?.depth??-1)+1}[Symbol.for("nodejs.util.inspect.custom")](){return{"@@type":"AST",id:this.id,type:this.type,root:this.#t.id,parent:this.#s?.id,depth:this.depth,partsLength:this.#n.length,parts:this.#n}}constructor(t,r,e={}){this.type=t,t&&(this.#r=!0),this.#s=r,this.#t=this.#s?this.#s.#t:this,this.#u=this.#t===this?e:this.#t.#u,this.#o=this.#t===this?[]:this.#t.#o,"!"!==t||this.#t.#a||this.#o.push(this),this.#i=this.#s?this.#s.#n.length:0}get hasMagic(){if(void 0!==this.#r)return this.#r;for(const t of this.#n)if("string"!=typeof t&&(t.type||t.hasMagic))return this.#r=!0;return this.#r}toString(){return void 0!==this.#c?this.#c:this.type?this.#c=this.type+"("+this.#n.map((t=>String(t))).join("|")+")":this.#c=this.#n.map((t=>String(t))).join("")}#m(){if(this!==this.#t)throw new Error("should only call on root");if(this.#a)return this;let t;for(this.toString(),this.#a=!0;t=this.#o.pop();){if("!"!==t.type)continue;let r=t,e=r.#s;for(;e;){for(let n=r.#i+1;!e.type&&n"string"==typeof t?t:t.toJSON())):[this.type,...this.#n.map((t=>t.toJSON()))];return this.isStart()&&!this.type&&t.unshift([]),this.isEnd()&&(this===this.#t||this.#t.#a&&"!"===this.#s?.type)&&t.push({}),t}isStart(){if(this.#t===this)return!0;if(!this.#s?.isStart())return!1;if(0===this.#i)return!0;const t=this.#s;for(let r=0;r"string"!=typeof t)),n=this.#n.map((r=>{const[n,s,i,o]="string"==typeof r?f.#q(r,this.#r,e):r.toRegExpSource(t);return this.#r=this.#r||i,this.#e=this.#e||o,n})).join("");let s="";if(this.isStart()&&"string"==typeof this.#n[0]&&(1!==this.#n.length||!q.has(this.#n[0]))){const e=S,i=r&&e.has(n.charAt(0))||n.startsWith("\\.")&&e.has(n.charAt(2))||n.startsWith("\\.\\.")&&e.has(n.charAt(4)),o=!r&&!t&&e.has(n.charAt(0));s=i?"(?!(?:^|/)\\.\\.?(?:$|/))":o?y:""}let i="";return this.isEnd()&&this.#t.#a&&"!"===this.#s?.type&&(i="(?:$|\\/)"),[s+n+i,m(n),this.#r=!!this.#r,this.#e]}const e="*"===this.type||"+"===this.type,n="!"===this.type?"(?:(?!(?:":"(?:";let s=this.#B(r);if(this.isStart()&&this.isEnd()&&!s&&"!"!==this.type){const t=this.toString(),r=this;return r.#n=[t],r.type=null,r.#r=void 0,[t,m(this.toString()),!1,!1]}let i=!e||t||r?"":this.#B(!0);i===s&&(i=""),i&&(s=`(?:${s})(?:${i})*?`);let o="";return o="!"===this.type&&this.#l?(this.isStart()&&!r?y:"")+b:n+s+("!"===this.type?"))"+(!this.isStart()||r||t?"":y)+P+")":"@"===this.type?")":"?"===this.type?")?":"+"===this.type&&i?")":"*"===this.type&&i?")?":`)${this.type}`),[o,m(s),this.#r=!!this.#r,this.#e]}#S(){if(h(this)){let t=0,r=!1;do{r=!0;for(let t=0;t{if("string"==typeof r)throw new Error("string type in extglob ast??");const[e,n,s,i]=r.toRegExpSource(t);return this.#e=this.#e||i,e})).filter((t=>!(this.isStart()&&this.isEnd()&&!t))).join("|")}static#q(t,r,e=!1){let n=!1,s="",i=!1,o=!1;for(let a=0;a(o(r),!(!e.nocomment&&"#"===r.charAt(0))&&new rt(r,e).match(t)),k=/^\*+([^+@!?*[(]*)$/,E=t=>r=>!r.startsWith(".")&&r.endsWith(t),C=t=>r=>r.endsWith(t),T=t=>(t=t.toLowerCase(),r=>!r.startsWith(".")&&r.toLowerCase().endsWith(t)),U=t=>(t=t.toLowerCase(),r=>r.toLowerCase().endsWith(t)),A=/^\*+\.\*+$/,$=t=>!t.startsWith(".")&&t.includes("."),M=t=>"."!==t&&".."!==t&&t.includes("."),O=/^\.\*+$/,D=t=>"."!==t&&".."!==t&&t.startsWith("."),N=/^\*+$/,G=t=>0!==t.length&&!t.startsWith("."),L=t=>0!==t.length&&"."!==t&&".."!==t,F=/^\?+([^+@!?*[(]*)?$/,K=([t,r=""])=>{const e=W([t]);return r?(r=r.toLowerCase(),t=>e(t)&&t.toLowerCase().endsWith(r)):e},z=([t,r=""])=>{const e=Q([t]);return r?(r=r.toLowerCase(),t=>e(t)&&t.toLowerCase().endsWith(r)):e},j=([t,r=""])=>{const e=Q([t]);return r?t=>e(t)&&t.endsWith(r):e},H=([t,r=""])=>{const e=W([t]);return r?t=>e(t)&&t.endsWith(r):e},W=([t])=>{const r=t.length;return t=>t.length===r&&!t.startsWith(".")},Q=([t])=>{const r=t.length;return t=>t.length===r&&"."!==t&&".."!==t},V="object"==typeof process&&process?"object"==typeof process.env&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix";x.sep="win32"===V?"\\":"/";const X=Symbol("globstar **");x.GLOBSTAR=X,x.filter=(t,r={})=>e=>x(e,t,r);const Y=(t,r={})=>Object.assign({},t,r);x.defaults=t=>{if(!t||"object"!=typeof t||!Object.keys(t).length)return x;const r=x;return Object.assign(((e,n,s={})=>r(e,n,Y(t,s))),{Minimatch:class extends r.Minimatch{constructor(r,e={}){super(r,Y(t,e))}static defaults(e){return r.defaults(Y(t,e)).Minimatch}},AST:class extends r.AST{constructor(r,e,n={}){super(r,e,Y(t,n))}static fromGlob(e,n={}){return r.AST.fromGlob(e,Y(t,n))}},unescape:(e,n={})=>r.unescape(e,Y(t,n)),escape:(e,n={})=>r.escape(e,Y(t,n)),filter:(e,n={})=>r.filter(e,Y(t,n)),defaults:e=>r.defaults(Y(t,e)),makeRe:(e,n={})=>r.makeRe(e,Y(t,n)),braceExpand:(e,n={})=>r.braceExpand(e,Y(t,n)),match:(e,n,s={})=>r.match(e,n,Y(t,s)),sep:r.sep,GLOBSTAR:X})};const Z=(t,r={})=>(o(t),r.nobrace||!/\{(?:(?!\{).)*\}/.test(t)?[t]:(0,i.fT)(t,{max:r.braceExpandMax}));x.braceExpand=Z,x.makeRe=(t,r={})=>new rt(t,r).makeRe(),x.match=(t,r,e={})=>{const n=new rt(r,e);return t=t.filter((t=>n.match(t))),n.options.nonull&&!t.length&&t.push(r),t};const tt=/[?*]|[+@!]\(.*?\)|\[|\]/;class rt{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;regexp;constructor(t,r={}){o(t),r=r||{},this.options=r,this.maxGlobstarRecursion=r.maxGlobstarRecursion??200,this.pattern=t,this.platform=r.platform||V,this.isWindows="win32"===this.platform,this.windowsPathsNoEscape=!!r.windowsPathsNoEscape||!1===r.allowWindowsEscape,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!r.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!r.nonegate,this.comment=!1,this.empty=!1,this.partial=!!r.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=void 0!==r.windowsNoMagicRoot?r.windowsNoMagicRoot:!(!this.isWindows||!this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(const t of this.set)for(const r of t)if("string"!=typeof r)return!0;return!1}debug(...t){}make(){const t=this.pattern,r=this.options;if(!r.nocomment&&"#"===t.charAt(0))return void(this.comment=!0);if(!t)return void(this.empty=!0);this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],r.debug&&(this.debug=(...t)=>console.error(...t)),this.debug(this.pattern,this.globSet);const e=this.globSet.map((t=>this.slashSplit(t)));this.globParts=this.preprocess(e),this.debug(this.pattern,this.globParts);let n=this.globParts.map(((t,r,e)=>{if(this.isWindows&&this.windowsNoMagicRoot){const r=!(""!==t[0]||""!==t[1]||"?"!==t[2]&&tt.test(t[2])||tt.test(t[3])),e=/^[a-z]:/i.test(t[0]);if(r)return[...t.slice(0,4),...t.slice(4).map((t=>this.parse(t)))];if(e)return[t[0],...t.slice(1).map((t=>this.parse(t)))]}return t.map((t=>this.parse(t)))}));if(this.debug(this.pattern,n),this.set=n.filter((t=>-1===t.indexOf(!1))),this.isWindows)for(let t=0;t=2?(t=this.firstPhasePreProcess(t),t=this.secondPhasePreProcess(t)):t=r>=1?this.levelOneOptimize(t):this.adjascentGlobstarOptimize(t),t}adjascentGlobstarOptimize(t){return t.map((t=>{let r=-1;for(;-1!==(r=t.indexOf("**",r+1));){let e=r;for(;"**"===t[e+1];)e++;e!==r&&t.splice(r,e-r)}return t}))}levelOneOptimize(t){return t.map((t=>0===(t=t.reduce(((t,r)=>{const e=t[t.length-1];return"**"===r&&"**"===e?t:".."===r&&e&&".."!==e&&"."!==e&&"**"!==e?(t.pop(),t):(t.push(r),t)}),[])).length?[""]:t))}levelTwoFileOptimize(t){Array.isArray(t)||(t=this.slashSplit(t));let r=!1;do{if(r=!1,!this.preserveMultipleSlashes){for(let e=1;en&&e.splice(n+1,s-n);let i=e[n+1];const o=e[n+2],a=e[n+3];if(".."!==i)continue;if(!o||"."===o||".."===o||!a||"."===a||".."===a)continue;r=!0,e.splice(n,1);const u=e.slice(0);u[n]="**",t.push(u),n--}if(!this.preserveMultipleSlashes){for(let t=1;tt.length))}partsMatch(t,r,e=!1){let n=0,s=0,i=[],o="";for(;n=2&&(t=this.levelTwoFileOptimize(t)),r.includes(X)?this.#I(t,r,e,n,s):this.#P(t,r,e,n,s)}#I(t,r,e,n,s){const i=r.indexOf(X,s),o=r.lastIndexOf(X),[a,u,c]=e?[r.slice(s,i),r.slice(i+1),[]]:[r.slice(s,i),r.slice(i+1,o),r.slice(o+1)];if(a.length){const r=t.slice(n,n+a.length);if(!this.#P(r,a,e,0,0))return!1;n+=a.length,s+=a.length}let l=0;if(c.length){if(c.length+n>t.length)return!1;let r=t.length-c.length;if(this.#P(t,c,e,r,0))l=c.length;else{if(""!==t[t.length-1]||n+c.length===t.length)return!1;if(r--,!this.#P(t,c,e,r,0))return!1;l=c.length+1}}if(!u.length){let r=!!l;for(let e=n;e{const r=t.map((t=>{if(t instanceof RegExp)for(const r of t.flags.split(""))n.add(r);return"string"==typeof t?t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"):t===X?X:t._src}));r.forEach(((t,n)=>{const s=r[n+1],i=r[n-1];t===X&&i!==X&&(void 0===i?void 0!==s&&s!==X?r[n+1]="(?:\\/|"+e+"\\/)?"+s:r[n]=e:void 0===s?r[n-1]=i+"(?:\\/|\\/"+e+")?":s!==X&&(r[n-1]=i+"(?:\\/|\\/"+e+"\\/)"+s,r[n+1]=X))}));const s=r.filter((t=>t!==X));if(this.partial&&s.length>=1){const t=[];for(let r=1;r<=s.length;r++)t.push(s.slice(0,r).join("/"));return"(?:"+t.join("|")+")"}return s.join("/")})).join("|");const[i,o]=t.length>1?["(?:",")"]:["",""];s="^"+i+s+o+"$",this.partial&&(s="^(?:\\/|"+i+s.slice(1,-1)+o+")$"),this.negate&&(s="^(?!"+s+").+$");try{this.regexp=new RegExp(s,[...n].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(t){return this.preserveMultipleSlashes?t.split("/"):this.isWindows&&/^\/\/[^/]+/.test(t)?["",...t.split(/\/+/)]:t.split(/\/+/)}match(t,r=this.partial){if(this.debug("match",t,this.pattern),this.comment)return!1;if(this.empty)return""===t;if("/"===t&&r)return!0;const e=this.options;this.isWindows&&(t=t.split("\\").join("/"));const n=this.slashSplit(t);this.debug(this.pattern,"split",n);const s=this.set;this.debug(this.pattern,"set",s);let i=n[n.length-1];if(!i)for(let t=n.length-2;!i&&t>=0;t--)i=n[t];for(const t of s){let s=n;if(e.matchBase&&1===t.length&&(s=[i]),this.matchOne(s,t,r))return!!e.flipNegate||!this.negate}return!e.flipNegate&&this.negate}static defaults(t){return x.defaults(t).Minimatch}}x.AST=v,x.Minimatch=rt,x.escape=(t,{windowsPathsNoEscape:r=!1,magicalBraces:e=!1}={})=>e?r?t.replace(/[?*()[\]{}]/g,"[$&]"):t.replace(/[?*()[\]\\{}]/g,"\\$&"):r?t.replace(/[?*()[\]]/g,"[$&]"):t.replace(/[?*()[\]\\]/g,"\\$&"),x.unescape=m;var et=e("./src/agent/filesystem/errors.ts"),nt=e("./src/agent/filesystem/merge.ts");function st(t){const r=t.replace(/\\/g,"/");if(""===r)return"/";const e=r.startsWith("/")?r:`/${r}`,n=s().posix.normalize(e);return n.length>1&&n.endsWith("/")?n.slice(0,-1):"."===n||""===n?"/":n}function it(t){const r=st(t.path),e=st(t.prefix);return"/"===e||r===e||r.startsWith(`${e}/`)}function ot(t){return void 0===t||""===t||"/"===t?"/":st(t)}function at(t,r){return x(t,r,{dot:!0,nocase:!1})}function ut(t){const r=t.filePath.replace(/\\/g,"/"),e=t.dir.replace(/\\/g,"/");let n;if(n="/"===e?r.replace(/^\//,""):r.startsWith(`${e}/`)?r.slice(e.length+1):r.replace(/^\//,""),at(n,t.globPattern)||at(r.replace(/^\//,""),t.globPattern))return!0;if(!0===t.matchBasename&&!t.globPattern.includes("/")){const r=n.lastIndexOf("/");return at(-1===r?n:n.slice(r+1),t.globPattern)}return!1}function ct(t,r){return void 0!==r&&0!==r.length&&r.some((r=>function(t,r){const e=r.startsWith("**/")?r:"**/"+r,n=t.replace(/^\//,"");for(const r of[n,t])if(x(r,e,{dot:!0})||x(r,`${e}/**`,{dot:!0}))return!0;return!1}(t,r)))}function lt(t,r){return t.path.localeCompare(r.path)}function mt(t){if(void 0!==t&&Number.isFinite(t))return Math.max(0,Math.floor(t))}function ft(t){return mt(t?.maxDepth)}function dt(t,r,e){const n=function(t,r){return"/"===t?r.replace(/^\//,"").split("/"):r.startsWith(`${t}/`)?r.slice(t.length+1).split("/"):void 0}(r,t.path);return void 0===n||n.length<=e?t:{path:`${"/"===r?"":r}/${n.slice(0,e).join("/")}`,kind:"directory"}}function pt(t){if(t.maxDepth<1)return[];const r=new Map;for(const e of t.entries){const n=dt(e,t.scope,t.maxDepth);r.has(n.path)||r.set(n.path,n)}return[...r.values()].sort(lt)}async function*ht(t,r){const e=[];for await(const r of t)e.push(r);yield*gt(pt({entries:e,scope:r.scope,maxDepth:r.maxDepth}),r.limit)}function gt(t,r){const e=mt(r);return void 0===e?[...t]:t.slice(0,e)}async function*_t(t,r,e){const n=ot(r),s="/"===n?"/":`${n}/`,i=[];for(const r of t){const t=st(r.path);("/"===n||t!==n&&t.startsWith(s))&&(ct(t,e?.excludes)||i.push(void 0===r.size?{path:t}:{path:t,size:r.size}))}const o=ft(e),a=void 0===o?i.sort(lt):pt({entries:i,scope:n,maxDepth:o});yield*gt(a,e?.limit)}function Jt(t,r){const e=ot(r);if("/"===e)return{kind:"directory"};const n=`${e}/`;for(const r of t){const t=st(r);if(t===e)return{kind:"file"};if(t.startsWith(n))return{kind:"directory"}}return{kind:"missing"}}async function*wt(t,r){yield*(0,nt.C)(t,{compare:lt,unique:!0===r?.unique})}async function*yt(t,r){const e=mt(r);if(0===e)return;let n=0;for await(const r of t)if(yield r,n++,void 0!==e&&n>=e)return}async function*St(t,r){yield*yt(async function*(){for await(const e of t)ut({filePath:e.path,dir:r.dir,globPattern:r.pattern})&&(yield e)}(),r.limit)}function qt(t,r){return t.pathr.path?1:t.lineNumber-r.lineNumber}function Bt(t){try{return new RegExp(t.pattern,!0===t.caseInsensitive?"i":void 0)}catch{throw new et.kp(t.pattern,t.path)}}function*It(t){for(const[r,e]of t.content.split("\n").entries())t.regex.test(e)&&(yield{path:t.path,lineNumber:r+1,line:e})}const Pt=new TextDecoder;function bt(t){return"string"==typeof t?t:Pt.decode(t)}},"./src/agent/messages.ts"(t,r,e){e.d(r,{J5:()=>p,LN:()=>c,MV:()=>i,Nk:()=>u,bM:()=>d,cD:()=>a,do:()=>o,xc:()=>f});var n=e("./src/agent/errors.ts"),s=e("./src/agent/usage-types.ts");const i=1,o="run_stream_event";function a(t,r,e){return"summary-started"===t.type?{type:"summary",agent_id:r,run_id:e,status:"running"}:{type:"summary",agent_id:r,run_id:e,status:!0===t.failed?"error":"completed",...!0===t.fallback?{fallback:!0}:{}}}function u(t){return{schemaVersion:i,type:"sdk_message",agentId:t.agent_id,runId:t.run_id,message:t}}function c(t){if(!function(t){return"object"==typeof t&&null!==t&&"schemaVersion"in t&&"type"in t}(t))throw new n.j1("Invalid local run stream event payload",{isRetryable:!1});if(t.schemaVersion!==i)throw new n.j1(`Unsupported local run stream event schema version ${l(t.schemaVersion)}`,{isRetryable:!1});if("sdk_message"!==t.type&&"result"!==t.type&&"done"!==t.type)throw new n.j1(`Unsupported local run stream event type ${l(t.type)}`,{isRetryable:!1});const r="string"==typeof t.agentId?t.agentId:void 0,e="string"==typeof t.runId?t.runId:void 0;if(void 0===r||void 0===e)throw new n.j1("Invalid local run stream event payload",{isRetryable:!1});if("sdk_message"===t.type&&function(t){return"object"==typeof t&&null!==t&&"type"in t&&"agent_id"in t&&"run_id"in t}(t.message))return{schemaVersion:i,type:"sdk_message",agentId:r,runId:e,message:m(t.message)};if("result"===t.type&&("finished"===(s=t.status)||"error"===s||"cancelled"===s)){const n="string"==typeof t.errorCode?t.errorCode:void 0;return{schemaVersion:i,type:"result",agentId:r,runId:e,status:t.status,...void 0!==n?{errorCode:n}:{}}}var s;if("done"===t.type)return{schemaVersion:i,type:"done",agentId:r,runId:e};throw new n.j1(`Unsupported local run stream event type ${l(t.type)}`,{isRetryable:!1})}function l(t){return"string"==typeof t||"number"==typeof t||"boolean"==typeof t?String(t):"unknown"}function m(t){if("usage"!==t.type)return t;const r=(0,s.g8)(t.usage);return r?{...t,usage:r}:t}function f(t){return"sdk_message"===t.type?t.message:void 0}function d(t){const r=c(t),e=f(r);if(!e)throw new n.j1(`Local run stream event ${r.type} is not an SDK message`,{isRetryable:!1});return e}function p(t){return"done"===t.type||"result"===t.type||"status"===(r=t.message).type&&("FINISHED"===r.status||"ERROR"===r.status||"CANCELLED"===r.status||"EXPIRED"===r.status);var r}},"./src/agent/native/vendored-tree-sitter.ts"(t,r,e){e.r(r),e.d(r,{configureVendoredTreeSitterWorkspaceDir:()=>a,createUnavailableParserClass:()=>c,loadVendoredTreeSitterModule:()=>u});var n=e("node:fs"),s=e("node:path"),i=e("./src/agent/platform-package-locator.ts");const o=new Set;function a(t){o.add((0,s.resolve)(t))}function u(t){const r=function(){const t=process.env.CURSOR_TREE_SITTER_VENDOR_DIR;return t&&(0,s.isAbsolute)(t)?t:(0,i.nk)({relativePath:"vendor",excludedWorkspaceDirs:o.size>0?[...o]:[process.cwd()],accept:t=>(0,n.existsSync)((0,s.join)(t,"tree-sitter","index.js"))})}();return void 0===r?{available:!1,reason:`the @cursor/sdk-${process.platform}-${process.arch} optional dependency (which vendors the tree-sitter natives) is not installed; shell command analysis is disabled`}:{available:!0,module:t.nativeRequire((0,s.join)(r,t.packageName,"index.js"))}}function c(t){return class{constructor(){const r=new Error(t);throw Object.assign(r,{code:"CURSOR_TREE_SITTER_STUBBED"})}}}},"./src/agent/platform-package-locator.ts"(t,r,e){e.d(r,{hQ:()=>c,nk:()=>u});var n=e("node:fs"),s=e("node:path");function i(t){try{const r=(0,n.statSync)(t);return r.isFile()&&("win32"===process.platform||!!(73&r.mode))}catch{return!1}}function o(t){let r=(0,s.resolve)(t);const e=(0,s.parse)(r).root;for(;;){if((0,n.existsSync)((0,s.join)(r,".git")))return r;if(r===e)return;r=(0,s.dirname)(r)}}const a="string"==typeof __filename?(0,s.dirname)(__filename):void 0;function u(t){const{relativePath:r,accept:e}=t,n=`${process.platform}-${process.arch}`,i=[`@cursor/sdk-${n}`,`@cursor/february-${n}`],u=[];for(const r of t.excludedWorkspaceDirs){u.push((0,s.resolve)(r));const t=o(r);void 0!==t&&u.push(t)}const c=[];process.argv[1]&&c.push({startDir:(0,s.dirname)((0,s.resolve)(process.argv[1])),excludeWorkspaceHelpers:!1});const l=t.sdkModuleDir??a;void 0!==l&&c.push({startDir:(0,s.resolve)(l),excludeWorkspaceHelpers:!1}),c.push({startDir:(0,s.dirname)((0,s.resolve)(process.execPath)),excludeWorkspaceHelpers:!0});const m=t=>u.some((r=>function(t){const r=(0,s.relative)((0,s.resolve)(t.directory),(0,s.resolve)(t.candidatePath));return""===r||!r.startsWith("..")&&!(0,s.isAbsolute)(r)}({candidatePath:t,directory:r})));for(const{startDir:t,excludeWorkspaceHelpers:n}of c){let o=t;const a=(0,s.parse)(o).root;for(;o!==a;){for(const t of i){const i=(0,s.join)(o,"node_modules",t,r);if(e(i)&&(!n||!m(i)))return i}o=(0,s.dirname)(o)}}}function c(t){return u({relativePath:(0,s.join)("bin",t.binaryName),excludedWorkspaceDirs:[t.excludedWorkspaceDir],accept:i})}},"./src/agent/run-interaction-accumulator.ts"(t,r,e){e.d(r,{KG:()=>i,e4:()=>s});var n=e("./src/agent/usage-types.ts");class s{constructor(t={}){this.options=t,this.turns=[],this.currentTurn=null,this.lastFiredStepIndex=-1,this.openTurnModelCalls=[]}conversation(){return[...this.turns]}usage(){return(0,n.wV)([this.endedTurnsUsage,...this.openTurnModelCalls])}finalAssistantText(){for(let t=this.turns.length-1;t>=0;t--){const r=this.turns[t];if("agentConversationTurn"!==r?.type)continue;const e=r.turn.steps;for(let t=e.length-1;t>=0;t--){const r=e[t];if("assistantMessage"===r?.type)return r.message.text}}}async apply(t){this.recordUsage(t),this.didPreviousStepComplete(t.type)&&await this.flushPendingStep();const{didStepComplete:r}=this.mergeIntoConversation(t);r&&await this.flushPendingStep(),function(t){return"summary"===t.type||"summary-started"===t.type||"summary-completed"===t.type}(t)||await(this.options.onDelta?.({update:t}))}recordUsage(t){switch(t.type){case"model-call-completed":this.openTurnModelCalls.push(t.usage);break;case"turn-ended":this.endedTurnsUsage=(0,n.wV)([this.endedTurnsUsage,t.usage??(0,n.wV)(this.openTurnModelCalls)]),this.openTurnModelCalls=[]}}async flushPendingStep(){const t=this.currentTurn;if(!t)return;const r=t.steps.length-1;if(r>this.lastFiredStepIndex&&r>=0){const e=t.steps[r];await(this.options.onStep?.({step:e})),this.lastFiredStepIndex=r}}ensureCurrentTurn(){if(this.currentTurn)return this.currentTurn;const t={steps:[]};return this.turns.push({type:"agentConversationTurn",turn:t}),this.currentTurn=t,t}mergeIntoConversation(t){switch(t.type){case"user-message-appended":this.onUserMessage(t),this.lastFiredStepIndex=-1;break;case"text-delta":this.onTextDelta(t);break;case"thinking-delta":this.onThinkingDelta(t);break;case"thinking-completed":return this.onThinkingCompleted(t),{didStepComplete:!0};case"tool-call-completed":return this.onTool(t),{didStepComplete:!0}}return{didStepComplete:!1}}onUserMessage(t){const r={userMessage:{text:t.userMessage.text},steps:[]};this.turns.push({type:"agentConversationTurn",turn:r}),this.currentTurn=r}onTextDelta(t){const r=this.ensureCurrentTurn(),e=r.steps[r.steps.length-1];if("assistantMessage"!==e?.type)r.steps.push({type:"assistantMessage",message:{text:t.text}});else{const n=e.message,s={...n,text:`${n.text}${t.text}`};r.steps[r.steps.length-1]={type:"assistantMessage",message:s}}}onThinkingDelta(t){const r=this.ensureCurrentTurn(),e=r.steps[r.steps.length-1];if("thinkingMessage"!==e?.type)r.steps.push({type:"thinkingMessage",message:{text:t.text}});else{const n=e.message,s={...n,text:`${n.text}${t.text}`};r.steps[r.steps.length-1]={type:"thinkingMessage",message:s}}}onThinkingCompleted(t){const r=this.ensureCurrentTurn(),e=r.steps[r.steps.length-1];"thinkingMessage"===e?.type&&(r.steps[r.steps.length-1]={type:"thinkingMessage",message:{...e.message,thinkingDurationMs:t.thinkingDurationMs}})}onTool(t){this.ensureCurrentTurn().steps.push({type:"toolCall",message:t.toolCall})}didPreviousStepComplete(t){const r=this.currentTurn;if(!r||0===r.steps.length)return!1;const e=r.steps[r.steps.length-1].type;return"token-delta"!==t&&"summary"!==t&&"summary-started"!==t&&"summary-completed"!==t&&("assistantMessage"===e&&"text-delta"!==t||"thinkingMessage"===e&&"thinking-delta"!==t&&"thinking-completed"!==t)}}async function i(t){const r=new s;for await(const e of t){const t=o(e);t&&await r.apply(t)}return await r.flushPendingStep(),r.conversation()}function o(t){switch(t.type){case"user":return{type:"user-message-appended",userMessage:{type:"user_message",session_id:t.agent_id,text:t.message.content.map((t=>t.text)).join("")}};case"assistant":{const r=t.message.content.filter((t=>"text"===t.type)).map((t=>t.text)).join("");return r?{type:"text-delta",text:r}:void 0}case"thinking":return void 0!==t.thinking_duration_ms&&""===t.text?{type:"thinking-completed",thinkingDurationMs:t.thinking_duration_ms}:{type:"thinking-delta",text:t.text};case"tool_call":if("running"===t.status)return;return{type:"tool-call-completed",callId:t.call_id,modelCallId:t.call_id,toolCall:a(t)};default:return}}function a(t){return{type:t.name,..."args"in t?{args:t.args}:{},...void 0!==t.result?{result:t.result}:{},...void 0!==t.truncated?{truncated:t.truncated}:{}}}},"./src/agent/sdk-config.ts"(t,r,e){e.d(r,{Mu:()=>c,it:()=>u,xP:()=>a});var n=e("./src/agent/errors.ts"),s=e("./src/agent/store/sdk-local-defaults.ts");let i,o;function a(t){if(void 0!==t.local&&"store"in t.local&&(0,s.Dt)(t.local.store??void 0),void 0!==t.local&&"useHttp1ForAgent"in t.local&&(i=t.local.useHttp1ForAgent??void 0),void 0!==t.local&&"workspaceScanCacheTtlMs"in t.local){const r=t.local.workspaceScanCacheTtlMs??void 0;if(void 0!==r&&(!Number.isFinite(r)||r<=0))throw new n.j1(`local.workspaceScanCacheTtlMs must be a positive number of milliseconds, got ${r}`,{isRetryable:!1});o=r}}function u(){return i}function c(){return o}},"./src/agent/store/local-agent-record-conversion.ts"(t,r,e){function n(t){return{agentId:t.agentId,cwd:t.workspaceRef,status:c(t.status),activeRunId:t.activeRunId??null,latestCheckpoint:t.latestCheckpointRef?a(t.latestCheckpointRef):null,name:t.name??null,createdAt:t.createdAt.getTime(),updatedAt:t.updatedAt.getTime(),sdkMetadata:t.metadata}}function s(t){const r=t.finishedAt?.getTime()??t.cancelledAt?.getTime()??t.expiredAt?.getTime()??null;return{runId:t.runId,requestId:t.requestId??null,agentId:t.agentId,turnNumber:t.turnNumber,status:m(t.status),model:t.model??null,result:t.result??null,error:t.errorCode??null,usageRef:t.usageRef??null,usage:t.usage??null,createdAt:t.createdAt.getTime(),updatedAt:t.updatedAt.getTime(),startedAt:t.startedAt?.getTime()??null,endedAt:r,startCheckpointRef:t.startCheckpointRef?a(t.startCheckpointRef):null,latestCheckpointRef:t.latestCheckpointRef?a(t.latestCheckpointRef):null}}function i(t){return{agentId:t.agentId,workspaceRef:t.cwd,status:l(t.status),activeRunId:t.activeRunId??null,latestCheckpointRef:t.latestCheckpoint?u(t.latestCheckpoint):null,name:t.name??null,createdAt:new Date(t.createdAt),updatedAt:new Date(t.updatedAt),metadata:t.sdkMetadata??{}}}function o(t){const r=function(t){switch(t){case"queued":return"QUEUED";case"running":return"RUNNING";case"finished":return"FINISHED";case"error":return"ERROR";case"cancelled":return"CANCELLED";case"expired":return"EXPIRED";default:throw new Error("unexpected local run status")}}(t.status),e=t.endedAt?new Date(t.endedAt):null;return{runId:t.runId,requestId:t.requestId??null,agentId:t.agentId,turnNumber:t.turnNumber,status:r,model:t.model??null,startCheckpointRef:t.startCheckpointRef?u(t.startCheckpointRef):null,latestCheckpointRef:t.latestCheckpointRef?u(t.latestCheckpointRef):null,errorCode:t.error??null,result:t.result??null,usageRef:t.usageRef??null,usage:t.usage??null,createdAt:new Date(t.createdAt),updatedAt:new Date(t.updatedAt),startedAt:t.startedAt?new Date(t.startedAt):null,finishedAt:"FINISHED"===r?e:null,cancelledAt:"CANCELLED"===r?e:null,expiredAt:"EXPIRED"===r?e:null}}function a(t){return{schemaVersion:1,rootBlobId:t.blobId}}function u(t){return{blobId:t.rootBlobId,storeKind:"local-agent-store"}}function c(t){switch(t){case"IDLE":return"idle";case"RUNNING":return"running";case"ERROR":return"error";case"ARCHIVED":return"archived";default:throw new Error("unexpected agent lifecycle status")}}function l(t){switch(t){case"idle":return"IDLE";case"running":return"RUNNING";case"error":return"ERROR";case"archived":return"ARCHIVED";default:throw new Error("unexpected local agent status")}}function m(t){switch(t){case"QUEUED":return"queued";case"CREATING":case"RUNNING":return"running";case"FINISHED":return"finished";case"ERROR":return"error";case"CANCELLED":return"cancelled";case"EXPIRED":return"expired";default:throw new Error("unexpected run lifecycle status")}}e.d(r,{EB:()=>n,R:()=>o,UY:()=>i,xu:()=>s})},"./src/agent/store/local-agent-store.ts"(t,r,e){e.d(r,{HL:()=>p,In:()=>m,Jg:()=>J,S$:()=>_,f1:()=>S,hA:()=>w,oc:()=>l,tg:()=>y});var n=e("../agent-kv/dist/agent-store.js"),s=e("../agent-kv/dist/blob-store.js"),i=e("../agent-kv/dist/serde.js"),o=e("../context/dist/core.js"),a=e("../proto/dist/generated/agent/v1/agent_pb.js"),u=e("../utils/dist/fresh-uuid.js"),c=e("./src/agent/store/local-agent-record-conversion.ts");function l(t){const r=new d(t.localStore,t.workspaceRef,t.scopedWorkspaceRef);return{store:r,checkpointStore:r,eventStore:new f(t.localStore.runEvents)}}function m(t){return{agents:t.agents,checkpoints:t.checkpoints,runs:t.runs,runEvents:t.runEvents}}class f{constructor(t){this.runEvents=t}appendRunEvent(t){return this.runEvents.append({runId:t.runId,eventType:t.eventType,payload:t.payload,payloadRef:t.payloadRef,idempotencyKey:t.idempotencyKey}).then(b)}listRunEvents(t){return this.runEvents.list({runId:t.runId,afterOffset:t.afterOffset,limit:t.limit}).then(R)}deleteRunEvents(t){return this.runEvents.delete({filter:{runIds:[t.runId]}})}}class d{constructor(t,r,e){this.localStore=t,this.workspaceRef=r,this.scopedWorkspaceRef=e,this.blobStores=new Map}async createAgent(t){const r=t.agentId??`agent-${(0,u.C)()}`;if(await this.localStore.agents.get({agentId:r}))throw new Error(`Agent ${r} already exists`);const e=this.workspaceRefForPersist(t.workspaceRef),n=Date.now(),s=x({agentId:r,requestId:t.requestId,turnNumber:1,model:t.model??null,timestamp:n}),i={agentId:r,cwd:e,status:"idle",activeRunId:null,name:t.name??null,createdAt:n,updatedAt:n,sdkMetadata:t.metadata??{}};await this.localStore.agents.create({agent:i});try{await this.localStore.runs.create({run:s}),await this.localStore.agents.update({agent:{...i,activeRunId:s.runId,updatedAt:Date.now()}})}catch(t){try{await this.localStore.runs.delete({filter:{agentIds:[r]}}),await this.localStore.agents.delete({filter:{agentIds:[r]}})}catch{}throw t}return{agent:k(await this.requireAgent(r)),run:E(s)}}async createFollowUpRun(t,r={}){const e=await this.requireAgent(t);if("archived"===e.status)throw new Error(`Cannot create follow-up run on archived agent ${t}. Unarchive it first.`);if(e.activeRunId){const r=await this.localStore.runs.get({agentId:t,runId:e.activeRunId});if(r&&!C(r.status))throw new Error(`Agent ${t} already has active run`)}const n=await async function(t,r){let e,n=0;do{const s=await t.runs.list({filter:{agentIds:[r],cursor:e}});n+=s.items.length,e=s.nextCursor}while(e);return n+1}(this.localStore,t),s=Date.now(),i=e.latestCheckpoint??null,o=x({agentId:t,requestId:r.requestId,turnNumber:n,model:r.model??null,timestamp:s,startCheckpointRef:i,latestCheckpointRef:i});return await this.localStore.runs.create({run:o}),await this.localStore.agents.update({agent:{...e,status:"idle",activeRunId:o.runId,sdkMetadata:{...e.sdkMetadata,...r.metadata},updatedAt:s}}),E(o)}async listAgents(t){const r=await this.localStore.agents.list({filter:{cursor:t?.cursor,limit:t?.limit,...void 0!==this.scopedWorkspaceRef?{cwd:this.scopedWorkspaceRef}:{}}});return{items:r.items.map(k),nextCursor:r.nextCursor}}async getAgent(t){const r=await this.getScopedAgentDocument(t);return r?k(r):null}async listRuns(t,r){await this.requireAgent(t);const e=await this.localStore.runs.list({filter:{agentIds:[t],cursor:r?.cursor,limit:r?.limit}});return{items:e.items.map((t=>E(t))),nextCursor:e.nextCursor}}async getRun(t,r){await this.requireAgent(t);const e=await this.localStore.runs.get({agentId:t,runId:r});return e?E(e):null}async markRunStarting(t,r,e){await this.updateRun(t,r,(t=>{if(C(t.status))throw new Error(`Cannot start terminal run ${r}`);const n=Date.now();return{run:{...t,requestId:e?.requestId??t.requestId??null,status:"running",startedAt:t.startedAt??n,updatedAt:n},agent:{status:"running",activeRunId:r,updatedAt:n}}}))}async patchCheckpoint(t,r,e){const n={schemaVersion:1,rootBlobId:e.blobId};await this.updateRun(t,r,(t=>{const r=Date.now();return{run:{...t,latestCheckpointRef:n,updatedAt:r},agent:{latestCheckpoint:n,updatedAt:r}}}))}async markRunTerminal(t,r,e){await this.updateRun(t,r,(t=>{if(C(t.status))return void 0===e.usage||null!==t.usage&&void 0!==t.usage?{run:t,agent:{}}:{run:{...t,usage:e.usage},agent:{}};const r=Date.now(),n=function(t){switch(t){case"FINISHED":return"finished";case"ERROR":return"error";case"CANCELLED":return"cancelled";case"EXPIRED":return"expired";default:throw new Error("unexpected run lifecycle status")}}(e.status);return{run:{...t,status:n,error:e.errorCode??t.error??null,usageRef:e.usageRef??t.usageRef??null,usage:void 0!==e.usage?e.usage:t.usage??null,result:e.result??t.result??null,updatedAt:r,endedAt:r},agent:{activeRunId:null,status:"ERROR"===e.status?"error":"idle",updatedAt:r}}}))}async cancelRun(t,r){await this.markRunTerminal(t,r,{status:"CANCELLED"})}async archiveAgent(t){const r=await this.requireAgent(t);await this.localStore.agents.update({agent:{...r,status:"archived",updatedAt:Date.now()}})}async unarchiveAgent(t){const r=await this.requireAgent(t);await this.localStore.agents.update({agent:{...r,status:"idle",updatedAt:Date.now()}})}async deleteAgent(t){const r=await this.requireAgent(t);if(r.activeRunId){const e=await this.localStore.runs.get({agentId:t,runId:r.activeRunId});if(e&&!C(e.status))throw new Error(`Cannot delete agent ${t}: active run ${r.activeRunId} is not terminal. Call run.cancel() first.`)}const e=[];let n;do{const r=await this.localStore.runs.list({filter:{agentIds:[t],cursor:n}});for(const t of r.items)e.push(t.runId);n=r.nextCursor}while(n);this.blobStores.delete(t),await this.localStore.runs.delete({filter:{agentIds:[t]}});for(const t of e)await this.localStore.runEvents.delete({filter:{runIds:[t]}});await this.localStore.checkpoints.delete({filter:{agentIds:[t]}}),await this.localStore.agents.delete({filter:{agentIds:[t]}})}async loadLatest(t){const r=await this.getScopedAgentDocument(t);if(!r?.latestCheckpoint)return this.blobStores.delete(t),null;const e=await g(this.localStore,t,r.latestCheckpoint),n=this.setBlobStore(t,e),s=await n.getBlob((0,o.q6)(),T(e.rootBlobId));if(!s)throw h(t,r.latestCheckpoint.rootBlobId);return a.Y9z.fromBinary(s)}async saveCheckpoint(t,r){const e=await this.getOrCreateBlobStore(t),n=r.toBinary(),a=await(0,s.Bk)(n);await e.setBlob((0,o.q6)(),a,n);const u=(0,i.nj)(a),c=await this.requireAgent(t);return await this.localStore.agents.update({agent:{...c,latestCheckpoint:{schemaVersion:1,rootBlobId:u},updatedAt:Date.now()}}),{blobId:u,storeKind:"local-agent-store"}}async getBlobStore(t){return this.getOrCreateBlobStore(t)}async getFullConversation(t){const r=await this.getScopedAgentDocument(t);if(!r?.latestCheckpoint)return new a.ljj;const e=await g(this.localStore,t,r.latestCheckpoint),i=new s.We;!function(t,r){const e=(0,n.sh)(r);t.set("agentId",e.agentId),t.set("latestRootBlobId",e.latestRootBlobId),t.set("name",e.name),t.set("createdAt",e.createdAt),t.set("mode",e.mode),t.set("isRunEverything",e.isRunEverything),t.set("approvalMode",e.approvalMode),t.set("lastUsedModel",e.lastUsedModel),t.set("lastDebugServerPort",e.lastDebugServerPort),t.set("currentPlanUri",e.currentPlanUri)}(i,t),i.set("latestRootBlobId",T(e.rootBlobId));const u=new n.pH(this.setBlobStore(t,e),i);return await u.resetFromDb((0,o.q6)()),u.getFullConversation((0,o.q6)())}async getScopedAgentDocument(t){const r=await this.localStore.agents.get({agentId:t});return r&&this.agentMatchesScope(r)?r:null}agentMatchesScope(t){return void 0===this.scopedWorkspaceRef||t.cwd===this.scopedWorkspaceRef}workspaceRefForPersist(t){if(void 0!==this.scopedWorkspaceRef&&t!==this.scopedWorkspaceRef)throw new Error(`Cannot create agent: workspaceRef "${t}" does not match scoped workspace "${this.scopedWorkspaceRef}"`);return this.scopedWorkspaceRef??t}async requireAgent(t){const r=await this.getScopedAgentDocument(t);if(!r)throw new Error(`Agent ${t} not found`);return r}async updateRun(t,r,e){await this.requireAgent(t);const n=await this.localStore.runs.get({agentId:t,runId:r});if(!n)throw new Error(`Run ${r} not found for agent ${t}`);const s=e(n);await this.localStore.runs.update({run:s.run});const i=s.agent;if(Object.keys(i).length>0){const r=await this.requireAgent(t),e=r.latestCheckpoint??s.run.latestCheckpointRef??null;await this.localStore.agents.update({agent:{...r,...i,latestCheckpoint:e,status:"archived"===r.status&&void 0!==i.status?"archived":i.status??r.status}})}}async getOrCreateBlobStore(t){const r=this.blobStores.get(t);if(r)return r;const e=await this.getScopedAgentDocument(t);return e?.latestCheckpoint?this.setBlobStore(t,await g(this.localStore,t,e.latestCheckpoint)):this.createPersistingBlobStore(t)}setBlobStore(t,r){const e=v.fromBundle(r,this.createPersistBlob(t));return this.blobStores.set(t,e),e}createPersistingBlobStore(t){const r=new v(this.createPersistBlob(t));return this.blobStores.set(t,r),r}createPersistBlob(t){return async(r,e)=>{null!==await this.localStore.checkpoints.get({agentId:t,blobId:r})?await this.localStore.checkpoints.update({agentId:t,blobId:r,data:e}):await this.localStore.checkpoints.create({agentId:t,blobId:r,data:e})}}}function p(t,r){return!r?.agentIds?.length&&void 0===r?.cwd||!(r.agentIds?.length&&!r.agentIds.includes(t.agentId))&&(void 0===r.cwd||t.cwd===r.cwd)}function h(t,r){return new Error(`Corrupt local agent checkpoint: missing root blob ${r} for agent ${t}`)}async function g(t,r,e){const n=await t.checkpoints.get({agentId:r,blobId:e.rootBlobId});if(!n)throw h(r,e.rootBlobId);const s={[e.rootBlobId]:U(n)};let i;do{const n=await t.checkpoints.list({filter:{agentIds:[r],cursor:i}});for(const i of n.items){if(i===e.rootBlobId)continue;const n=await t.checkpoints.get({agentId:r,blobId:i});n&&(s[i]=U(n))}i=n.nextCursor}while(i);return{schemaVersion:1,rootBlobId:e.rootBlobId,blobs:s}}function _(t,r){return!((r?.agentIds?.length||r?.blobIds?.length)&&(r.agentIds?.length&&!r.agentIds.includes(t.agentId)||r.blobIds?.length&&!r.blobIds.includes(t.blobId)))}function J(t,r){const e=[...t].sort(((t,r)=>t.localeCompare(r))),n=r?.limit??50;let s=e;r?.cursor&&(s=e.filter((t=>t>r.cursor)));const i=s.slice(0,n),o=i.at(-1);return{items:i,...s.length>n&&o?{nextCursor:o}:{}}}function w(t,r){return!((r?.agentIds?.length||r?.runIds?.length)&&(r.agentIds?.length&&!r.agentIds.includes(t.agentId)||r.runIds?.length&&!r.runIds.includes(t.runId)))}function y(t,r){const e=[...void 0===r?.cwd?t:t.filter((t=>t.cwd===r.cwd))].sort(q),n=r?.limit??50;let s=e;if(r?.cursor){const t=function(t){const r=P(t);if("number"!=typeof r.updatedAt||"string"!=typeof r.agentId)throw new Error("Invalid agent list cursor");return{updatedAt:r.updatedAt,agentId:r.agentId}}(r.cursor);s=e.filter((r=>function(t,r){return t.updatedAtr.updatedAt)&&t.agentIdstructuredClone(t))),...s.length>n&&o?{nextCursor:I({updatedAt:o.updatedAt,agentId:o.agentId})}:{}}}function S(t,r){const e=[...t].sort(B),n=r?.limit??50;let s=e;if(r?.cursor){const t=function(t){const r=P(t);if("number"!=typeof r.turnNumber||"string"!=typeof r.runId)throw new Error("Invalid run list cursor");return{turnNumber:r.turnNumber,runId:r.runId}}(r.cursor);s=e.filter((r=>function(t,r){return t.turnNumber>r.turnNumber||!(t.turnNumberr.runId}(r,t)))}const i=s.slice(0,n),o=i.at(-1);return{items:i.map((t=>structuredClone(t))),...s.length>n&&o?{nextCursor:I({turnNumber:o.turnNumber,runId:o.runId})}:{}}}function q(t,r){return r.updatedAt!==t.updatedAt?r.updatedAt-t.updatedAt:r.agentId.localeCompare(t.agentId)}function B(t,r){return t.turnNumber!==r.turnNumber?t.turnNumber-r.turnNumber:t.runId.localeCompare(r.runId)}function I(t){return Buffer.from(JSON.stringify(t),"utf8").toString("base64url")}function P(t){try{const r=JSON.parse(Buffer.from(t,"base64url").toString("utf8"));if(function(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}(r))return r}catch{}throw new Error("Invalid list cursor")}function b(t){return{runId:t.runId,seq:t.seq,offset:t.offset,eventType:t.eventType,payload:t.payload,payloadRef:t.payloadRef,idempotencyKey:t.idempotencyKey,createdAt:new Date(t.createdAt)}}function R(t){return{events:t.items.map(b),...void 0!==t.nextOffset?{nextOffset:t.nextOffset}:{}}}class v{constructor(t){this.persistBlob=t,this.blobs=new Map}static fromBundle(t,r){const e=new v(r);for(const[r,s]of Object.entries(t.blobs))e.blobs.set(r,(n=s,new Uint8Array(Buffer.from(n,"base64"))));var n;return e}async getBlob(t,r){return this.blobs.get((0,i.nj)(r))}async setBlob(t,r,e){const n=(0,i.nj)(r),s=A(e);this.blobs.set(n,s),await(this.persistBlob?.(n,s))}async setBlobLocallyOnly(t,r,e){this.blobs.set((0,i.nj)(r),A(e))}async flush(t){}}function x(t){return{runId:`run-${(0,u.C)()}`,requestId:t.requestId??null,agentId:t.agentId,turnNumber:t.turnNumber,status:"queued",model:t.model,result:null,error:null,usageRef:null,usage:null,createdAt:t.timestamp,updatedAt:t.timestamp,startedAt:null,endedAt:null,startCheckpointRef:t.startCheckpointRef??null,latestCheckpointRef:t.latestCheckpointRef??null}}function k(t){return(0,c.UY)(t)}function E(t){return(0,c.R)(t)}function C(t){return"finished"===t||"error"===t||"cancelled"===t||"expired"===t}function T(t){const r=new Uint8Array(t.length/2);for(let e=0;ei,kP:()=>s})},"./src/agent/store/sdk-state-root.ts"(t,r,e){e.d(r,{V:()=>u});var n=e("node:crypto"),s=e("node:fs"),i=e("node:os"),o=e("node:path"),a=e("../utils/dist/workspace-paths.js");function u(t){const r=(0,o.join)((0,a.Rv)((0,i.homedir)(),t),"sdk-agent-store"),e=(0,o.join)(r,(0,n.createHash)("sha256").update(t).digest("hex"));if((0,s.existsSync)(e))return e;const u=function(t){try{return(0,n.createHash)("md5").update(t).digest("hex")}catch(t){if(function(t){if(!(t instanceof Error))return!1;return"ERR_OSSL_EVP_UNSUPPORTED"===t.code||"Digest method not supported"===t.message}(t))return;throw t}}(t);if(void 0===u)return e;const c=(0,o.join)(r,u);if(!(0,s.existsSync)(c))return e;try{return(0,s.renameSync)(c,e),e}catch{return(0,s.existsSync)(c)?c:e}}},"./src/agent/subagent-conversion.ts"(t,r,e){e.d(r,{DB:()=>o,SB:()=>i});var n=e("./src/agent/errors.ts");function s(t){if(void 0===t)return;const r=Object.entries(t);if(0===r.length)return;const e=[];for(const[t,s]of r){if(void 0!==s.mcpServers)for(const r of s.mcpServers)if("string"!=typeof r)throw new n.j1(`Custom subagent "${t}" has an inline McpServerConfig in mcpServers; SDK custom subagents only support string references in v1.`);const r=void 0===s.model||"inherit"===s.model?"inherit":s.model;e.push({name:t,description:s.description,prompt:s.prompt,model:r})}return e}function i(t){return s(t)}function o(t){const r=s(t);if(void 0!==r)return r.map((t=>({name:t.name,description:t.description,prompt:t.prompt,model:"inherit"===t.model?"inherit":t.model.id})))}},"./src/agent/team-id.ts"(t,r,e){e.d(r,{E:()=>s,P:()=>n});const n="x-cursor-team-id";function s(t){if("number"==typeof t&&Number.isSafeInteger(t)&&!(t<=0))return t}},"./src/agent/tool-call-utils.ts"(t,r,e){function n(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function s(t){return!!n(t)&&!(void 0!==t.args&&"boolean"!=typeof t.args||void 0!==t.result&&"boolean"!=typeof t.result)}e.d(r,{D:()=>s,u:()=>n})},"./src/agent/tools-option.ts"(t,r,e){e.d(r,{$$:()=>i,TX:()=>m,VJ:()=>o,db:()=>f});var n=e("../proto/dist/generated/agent/v1/agent_pb.js"),s=e("./src/agent/errors.ts");const i="x-cursor-agent-allowed-tools",o="x-cursor-agent-exclude-tools",a={shell:["shell_tool_call","write_shell_stdin_tool_call"],mcp:["mcp_tool_call","get_mcp_tools_tool_call","list_mcp_resources_tool_call","read_mcp_resource_tool_call","mcp_auth_tool_call"]};let u,c;function l(){if(void 0===u){u=new Map,c=[];for(const t of n.Dm_.fields.list()){if("tool"!==t.oneof?.localName)continue;const r=t.localName.replace(/ToolCall$/,""),e=a[r]??[t.name];u.set(r,e),u.set(t.name,[t.name]),u.set(t.localName,[t.name]),c.push(r)}c.sort()}return u}function m(t){return d(t,"tools")}function f(t){return d(t,"disallowedTools")}function d(t,r){if(void 0===t)return;const e=l(),n=new Set,i=[];for(const r of t){const t=e.get(r.trim());if(void 0!==t)for(const r of t)n.add(r);else i.push(r)}if(i.length>0)throw new s.j1(`Unknown tool name(s) in \`${r}\`: ${i.join(", ")}. Valid tool names: ${(l(),c??[]).join(", ")}.`,{isRetryable:!1});return[...n]}},"./src/agent/transport.ts"(t,r,e){e.d(r,{cf:()=>s});const n=async t=>{if(function(){const t=Object.getOwnPropertyDescriptor(globalThis,"Deno");return void 0!==t&&(void 0!==t.get||void 0!==t.value)}()){const{createConnectTransport:r}=await Promise.resolve().then(e.t.bind(e,"@connectrpc/connect-web",23));return r({baseUrl:t.baseUrl,interceptors:t.interceptors})}const{createSafeConnectTransport:r}=await Promise.all([e.e(154),e.e(441)]).then(e.bind(e,"./src/agent/safe-connect-transport.ts"));return r({baseUrl:t.baseUrl,httpVersion:t.httpVersion,interceptors:t.interceptors})};function s(t){let r;const e=()=>(r??=function(t){return n(t)}(t),r);return{unary:(t,r,n,s,i,o,a)=>e().then((e=>e.unary(t,r,n,s,i,o,a))),stream:(t,r,n,s,i,o,a)=>e().then((e=>e.stream(t,r,n,s,i,o,a)))}}},"./src/agent/types/delta-types.ts"(t,r,e){e.d(r,{Zs:()=>P,Dx:()=>w,tq:()=>B,ON:()=>f,M7:()=>_,uj:()=>g,Wf:()=>h,XP:()=>p,yP:()=>o,Y3:()=>l,p$:()=>c,IO:()=>d,EC:()=>u,fr:()=>I,a7:()=>a,Ed:()=>J,Sb:()=>m});var n=e("zod/v3"),s=e("../cursor-sdk-shared/dist/message-schemas.js"),i=e("../cursor-sdk-shared/dist/tool-call-types.js");const o=n.object({type:n.literal("text-delta"),text:n.string()}),a=n.object({type:n.literal("tool-call-started"),callId:n.string(),toolCall:i.C6,modelCallId:n.string()}),u=n.object({type:n.literal("tool-call-completed"),callId:n.string(),toolCall:i.C6,modelCallId:n.string()}),c=n.object({type:n.literal("thinking-delta"),text:n.string()}),l=n.object({type:n.literal("thinking-completed"),thinkingDurationMs:n.number()}),m=n.object({type:n.literal("user-message-appended"),userMessage:s.Kx}),f=n.object({type:n.literal("partial-tool-call"),callId:n.string(),toolCall:i.C6,modelCallId:n.string()}),d=n.object({type:n.literal("token-delta"),tokens:n.number()}),p=n.object({type:n.literal("summary"),summary:n.string()}),h=n.object({type:n.literal("summary-started")}),g=n.object({type:n.literal("summary-completed"),failed:n.boolean().optional(),fallback:n.boolean().optional()}),_=n.object({type:n.literal("shell-output-delta"),event:n.record(n.string(),n.unknown())}),J=n.object({type:n.literal("turn-ended"),usage:n.object({inputTokens:n.number(),outputTokens:n.number(),cacheReadTokens:n.number(),cacheWriteTokens:n.number(),reasoningTokens:n.number().optional()}).optional()}),w=n.object({type:n.literal("model-call-completed"),modelCallId:n.string(),usage:n.object({inputTokens:n.number(),outputTokens:n.number(),cacheReadTokens:n.number(),cacheWriteTokens:n.number(),reasoningTokens:n.number().optional()})}),y=n.object({type:n.literal("step-started"),stepId:n.number()}),S=n.object({type:n.literal("tool-requests-listed"),callCount:n.number()}),q=n.object({type:n.literal("step-completed"),stepId:n.number(),stepDurationMs:n.number()}),B=n.discriminatedUnion("type",[o,a,u,c,l,f,y,q,S]),I=n.object({type:n.literal("tool-call-delta"),callId:n.string(),modelCallId:n.string(),taskUpdate:B}),P=n.discriminatedUnion("type",[o,a,u,c,l,m,f,d,p,h,g,_,J,w,y,q,S,I])},"./src/agent/usage-types.ts"(t,r,e){function n(t){if(!t)return;const{inputTokens:r,outputTokens:e,cacheReadTokens:n,cacheWriteTokens:s,reasoningTokens:i}=t;return{inputTokens:r,outputTokens:e,cacheReadTokens:n,cacheWriteTokens:s,totalTokens:r+e,...void 0!==i?{reasoningTokens:i}:{}}}function s(t){let r=0,e=0,n=0,s=0,i=0,o=!1,a=!1;for(const u of t)u&&(o=!0,r+=u.inputTokens,e+=u.outputTokens,n+=u.cacheReadTokens,s+=u.cacheWriteTokens,void 0!==u.reasoningTokens&&(a=!0,i+=u.reasoningTokens));if(o)return{inputTokens:r,outputTokens:e,cacheReadTokens:n,cacheWriteTokens:s,totalTokens:r+e,...a?{reasoningTokens:i}:{}}}function i(t){if(t)return"number"==typeof t.inputTokens&&"number"==typeof t.outputTokens&&"number"==typeof t.cacheReadTokens&&"number"==typeof t.cacheWriteTokens?n(t):t}e.d(r,{g8:()=>i,qI:()=>n,wV:()=>s})},"./src/agent/utils/logger.ts"(t,r,e){e.d(r,{v:()=>n});const n={log:(...t)=>{},error:(...t)=>{},warn:(...t)=>{},info:(...t)=>{},debug:(...t)=>{}}},"@bufbuild/protobuf"(t){t.exports=require("@bufbuild/protobuf")},"@connectrpc/connect"(t){t.exports=require("@connectrpc/connect")},"@connectrpc/connect-web"(t){t.exports=require("@connectrpc/connect-web")},"bun:sqlite"(t){t.exports=require("bun:sqlite")},"node:sqlite"(t){t.exports=require("node:sqlite")},zod(t){t.exports=require("zod")},"zod/v3"(t){t.exports=require("zod/v3")},"zod/v4"(t){t.exports=require("zod/v4")},"zod/v4-mini"(t){t.exports=require("zod/v4-mini")},assert(t){t.exports=require("assert")},buffer(t){t.exports=require("buffer")},child_process(t){t.exports=require("child_process")},crypto(t){t.exports=require("crypto")},events(t){t.exports=require("events")},fs(t){t.exports=require("fs")},http(t){t.exports=require("http")},http2(t){t.exports=require("http2")},https(t){t.exports=require("https")},"node:assert"(t){t.exports=require("node:assert")},"node:async_hooks"(t){t.exports=require("node:async_hooks")},"node:buffer"(t){t.exports=require("node:buffer")},"node:child_process"(t){t.exports=require("node:child_process")},"node:constants"(t){t.exports=require("node:constants")},"node:crypto"(t){t.exports=require("node:crypto")},"node:events"(t){t.exports=require("node:events")},"node:fs"(t){t.exports=require("node:fs")},"node:fs/promises"(t){t.exports=require("node:fs/promises")},"node:module"(t){t.exports=require("node:module")},"node:net"(t){t.exports=require("node:net")},"node:os"(t){t.exports=require("node:os")},"node:path"(t){t.exports=require("node:path")},"node:perf_hooks"(t){t.exports=require("node:perf_hooks")},"node:process"(t){t.exports=require("node:process")},"node:readline"(t){t.exports=require("node:readline")},"node:stream"(t){t.exports=require("node:stream")},"node:stream/promises"(t){t.exports=require("node:stream/promises")},"node:string_decoder"(t){t.exports=require("node:string_decoder")},"node:timers/promises"(t){t.exports=require("node:timers/promises")},"node:url"(t){t.exports=require("node:url")},"node:util"(t){t.exports=require("node:util")},"node:zlib"(t){t.exports=require("node:zlib")},path(t){t.exports=require("path")},stream(t){t.exports=require("stream")},string_decoder(t){t.exports=require("string_decoder")},util(t){t.exports=require("util")},zlib(t){t.exports=require("zlib")},"../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/code.js"(t,r,e){var n;e.d(r,{C:()=>n}),function(t){t[t.Canceled=1]="Canceled",t[t.Unknown=2]="Unknown",t[t.InvalidArgument=3]="InvalidArgument",t[t.DeadlineExceeded=4]="DeadlineExceeded",t[t.NotFound=5]="NotFound",t[t.AlreadyExists=6]="AlreadyExists",t[t.PermissionDenied=7]="PermissionDenied",t[t.ResourceExhausted=8]="ResourceExhausted",t[t.FailedPrecondition=9]="FailedPrecondition",t[t.Aborted=10]="Aborted",t[t.OutOfRange=11]="OutOfRange",t[t.Unimplemented=12]="Unimplemented",t[t.Internal=13]="Internal",t[t.Unavailable=14]="Unavailable",t[t.DataLoss=15]="DataLoss",t[t.Unauthenticated=16]="Unauthenticated"}(n||(n={}))},"../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/connect-error.js"(t,r,e){e.d(r,{T:()=>i});var n=e("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/code.js"),s=e("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/protocol-connect/code-string.js");class i extends Error{constructor(t,r=n.C.Unknown,e,i,o){super(function(t,r){return t.length?`[${(0,s.s)(r)}] ${t}`:`[${(0,s.s)(r)}]`}(t,r)),this.name="ConnectError",Object.setPrototypeOf(this,new.target.prototype),this.rawMessage=t,this.code=r,this.metadata=new Headers(null!=e?e:{}),this.details=null!=i?i:[],this.cause=o}static from(t,r=n.C.Unknown){return t instanceof i?t:t instanceof Error?"AbortError"==t.name?new i(t.message,n.C.Canceled):new i(t.message,r,void 0,void 0,t):new i(String(t),r,void 0,void 0,t)}findDetails(t){const r="typeName"in t?{findMessage:r=>r===t.typeName?t:void 0}:t,e=[];for(const t of this.details){if("getType"in t){r.findMessage(t.getType().typeName)&&e.push(t);continue}const n=r.findMessage(t.type);if(n)try{e.push(n.fromBinary(t.value))}catch(t){}}return e}}},"../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/protocol-connect/code-string.js"(t,r,e){e.d(r,{X:()=>o,s:()=>s});var n=e("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/code.js");function s(t){const r=n.C[t];return"string"!=typeof r?t.toString():r[0].toLowerCase()+r.substring(1).replace(/[A-Z]/g,(t=>"_"+t.toLowerCase()))}let i;function o(t){if(!i){i={};for(const t of Object.values(n.C))"string"!=typeof t&&(i[s(t)]=t)}return i[t]}},"../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/protocol/async-iterable.js"(t,r,e){e.d(r,{T$:()=>I,Jt:()=>B,Fs:()=>h,WK:()=>d,SM:()=>p,fM:()=>J,ew:()=>w,yQ:()=>y,uv:()=>_,XO:()=>g,pY:()=>S});var n=e("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/code.js"),s=e("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/connect-error.js"),i=e("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/protocol/limit-io.js");class o{constructor(t){this.readMaxBytes=t,this.header=new Uint8Array(5),this.headerView=new DataView(this.header.buffer),this.buf=[]}get byteLength(){return this.buf.reduce(((t,r)=>t+r.byteLength),0)}decode(t){this.buf.push(t);const r=[];for(;;){let t=this.pop();if(!t)break;r.push(t)}return r}pop(){if((this.env||(this.env=this.head(),this.env))&&this.cons(this.env.data)){const t=this.env;return this.env=void 0,t}}head(){if(!this.cons(this.header))return;const t=this.headerView.getUint8(0),r=this.headerView.getUint32(1);return(0,i.kk)(this.readMaxBytes,r,!0),{flags:t,data:new Uint8Array(r)}}cons(t){const r=t.byteLength;if(this.byteLengthr-e?(t.set(n.subarray(0,r-e),e),this.buf.unshift(n.subarray(r-e)),e+=r-e):(t.set(n,e),e+=n.byteLength)}return!0}}async function a(t,r,e){let{flags:i,data:o}=t;if(!(1&~i))throw new s.T("invalid envelope, already compressed",n.C.Internal);return r&&o.byteLength>=e&&(o=await r.compress(o),i|=1),{data:o,flags:i}}async function u(t,r,e){let{flags:i,data:o}=t;if(!(1&~i)){if(!r)throw new s.T("received compressed envelope, but do not know how to decompress",n.C.Internal);o=await r.decompress(o,e),i^=1}return{data:o,flags:i}}function c(t,r){const e=new Uint8Array(r.length+5);e.set(r,5);const n=new DataView(e.buffer,e.byteOffset,e.byteLength);return n.setUint8(0,t),n.setUint32(1,r.length),e}var l=function(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,e=t[Symbol.asyncIterator];return e?e.call(t):(t="function"==typeof __values?__values(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(e){r[e]=t[e]&&function(r){return new Promise((function(n,s){!function(t,r,e,n){Promise.resolve(n).then((function(r){t({value:r,done:e})}),r)}(n,s,(r=t[e](r)).done,r.value)}))}}},m=function(t){return this instanceof m?(this.v=t,this):new m(t)},f=function(t,r,e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,s=e.apply(t,r||[]),i=[];return n={},o("next"),o("throw"),o("return",(function(t){return function(r){return Promise.resolve(r).then(t,c)}})),n[Symbol.asyncIterator]=function(){return this},n;function o(t,r){s[t]&&(n[t]=function(r){return new Promise((function(e,n){i.push([t,r,e,n])>1||a(t,r)}))},r&&(n[t]=r(n[t])))}function a(t,r){try{(e=s[t](r)).value instanceof m?Promise.resolve(e.value.v).then(u,c):l(i[0][2],e)}catch(t){l(i[0][3],t)}var e}function u(t){a("next",t)}function c(t){a("throw",t)}function l(t,r){t(r),i.shift(),i.length&&a(i[0][0],i[0][1])}};function d(t,...r){const[e,n,s]=function(t){let r;"function"!=typeof t[t.length-1]&&(r=t.pop());const e=t.pop();return[t,e,r]}(r);let i,o=t;return!0===(null==s?void 0:s.propagateDownStreamError)&&(o=i=q(o)),o=h(o,...e,{propagateDownStreamError:!1}),n(o).catch((t=>i?i.abort(t).then((()=>Promise.reject(t))):Promise.reject(t)))}function p(t,r){return async function(e){return await async function(t,r,e){var o,a,u,c,m,f,d,p;const[h,g]=function(t){if(null==t)return[!1,0];const r="string"==typeof t?parseInt(t,10):t;return!Number.isSafeInteger(r)||r<0?[!1,r]:[!0,r]}(e);if(h){g>r&&(0,i.kk)(r,g,!0);const e=new Uint8Array(g);let m=0;try{for(var _,J=!0,w=l(t);!(o=(_=await w.next()).done);J=!0){c=_.value,J=!1;const t=c;if(m+t.byteLength>g)throw new s.T(`protocol error: promised ${g} bytes, received ${m+t.byteLength}`,n.C.InvalidArgument);e.set(t,m),m+=t.byteLength}}catch(t){a={error:t}}finally{try{J||o||!(u=w.return)||await u.call(w)}finally{if(a)throw a.error}}if(mo};!0===(null==s?void 0:s.propagateDownStreamError)&&(a=i=q(a));for(const t of n)a=t(a);const u=a[Symbol.asyncIterator]();try{for(;;){const t=yield m(u.next());if(!0===t.done)break;if(i)try{yield yield m(t.value)}catch(t){throw yield m(i.abort(t)),t}else yield yield m(t.value)}}finally{!0===(null==s?void 0:s.propagateDownStreamError)&&(null===(e=o.return)||void 0===e||e.call(o).catch((()=>{})))}}))}function g(t,r,e){return void 0===r||void 0===e?function(r){return f(this,arguments,(function*(){var e,n,s,i;try{for(var o,a=!0,u=l(r);!(e=(o=yield m(u.next())).done);a=!0){i=o.value,a=!1;const r=i,e=t.serialize(r);yield yield m({flags:0,data:e})}}catch(t){n={error:t}}finally{try{a||e||!(s=u.return)||(yield m(s.call(u)))}finally{if(n)throw n.error}}}))}:function(n){return f(this,arguments,(function*(){var s,i,o,a;try{for(var u,c=!0,f=l(n);!(s=(u=yield m(f.next())).done);c=!0){a=u.value,c=!1;const n=a;let s,i=0;n.end?(i|=r,s=e.serialize(n.value)):s=t.serialize(n.value),yield yield m({flags:i,data:s})}}catch(t){i={error:t}}finally{try{c||s||!(o=f.return)||(yield m(o.call(f)))}finally{if(i)throw i.error}}}))}}function _(t,r,e){return e&&void 0!==r?function(n){return f(this,arguments,(function*(){var s,i,o,a;try{for(var u,c=!0,f=l(n);!(s=(u=yield m(f.next())).done);c=!0){a=u.value,c=!1;const{flags:n,data:s}=a;(n&r)===r?yield yield m({value:e.parse(s),end:!0}):yield yield m({value:t.parse(s),end:!1})}}catch(t){i={error:t}}finally{try{c||s||!(o=f.return)||(yield m(o.call(f)))}finally{if(i)throw i.error}}}))}:function(i){return f(this,arguments,(function*(){var o,a,u,c;try{for(var f,d=!0,p=l(i);!(o=(f=yield m(p.next())).done);d=!0){c=f.value,d=!1;const{flags:i,data:o}=c;if(void 0===r||(i&r)!==r)yield yield m(t.parse(o));else if(null===e)throw new s.T("unexpected end flag",n.C.InvalidArgument)}}catch(t){a={error:t}}finally{try{d||o||!(u=p.return)||(yield m(u.call(p)))}finally{if(a)throw a.error}}}))}}function J(t,r){return function(e){return f(this,arguments,(function*(){var n,s,i,o;try{for(var u,c=!0,f=l(e);!(n=(u=yield m(f.next())).done);c=!0){o=u.value,c=!1;const e=o;yield yield m(yield m(a(e,t,r)))}}catch(t){s={error:t}}finally{try{c||n||!(i=f.return)||(yield m(i.call(f)))}finally{if(s)throw s.error}}}))}}function w(t,r){return function(e){return f(this,arguments,(function*(){var n,s,i,o;try{for(var a,c=!0,f=l(e);!(n=(a=yield m(f.next())).done);c=!0){o=a.value,c=!1;const e=o;yield yield m(yield m(u(e,t,r)))}}catch(t){s={error:t}}finally{try{c||n||!(i=f.return)||(yield m(i.call(f)))}finally{if(s)throw s.error}}}))}}function y(){return function(t){return f(this,arguments,(function*(){var r,e,n,s;try{for(var i,o=!0,a=l(t);!(r=(i=yield m(a.next())).done);o=!0){s=i.value,o=!1;const{flags:t,data:r}=s;yield yield m(c(t,r))}}catch(t){e={error:t}}finally{try{o||r||!(n=a.return)||(yield m(n.call(a)))}finally{if(e)throw e.error}}}))}}function S(t){return function(r){return f(this,arguments,(function*(){var e,i,a,u;const c=function(t){return new o(t)}(t);try{for(var f,d=!0,p=l(r);!(e=(f=yield m(p.next())).done);d=!0){u=f.value,d=!1;const t=u;for(const r of c.decode(t))yield yield m(r)}}catch(t){i={error:t}}finally{try{d||e||!(a=p.return)||(yield m(a.call(p)))}finally{if(i)throw i.error}}if(c.byteLength>0)throw new s.T("protocol error: incomplete envelope",n.C.InvalidArgument)}))}}function q(t){const r=t[Symbol.asyncIterator]();if(void 0===r.throw)throw new Error("AsyncIterable does not implement throw");const e=r;let n,s,i={next:()=>(s=e.next().finally((()=>{s=void 0})),s),throw:t=>e.throw(t)};void 0!==r.return&&(i=Object.assign(Object.assign({},i),{return:t=>e.return(t)}));let o=!1;return{abort(t){if(n)return n.state;const r=()=>e.throw(t).then((t=>!0===t.done?"completed":"caught"),(()=>"rethrown"));return s?(n={reason:t,state:s.then(r,r)},n.state):(n={reason:t,state:r()},n.state)},[Symbol.asyncIterator](){if(o)throw new Error("AsyncIterable cannot be re-used");return o=!0,i}}}function B(){const t=[],r=[];let e,n,s,i=new Promise(((t,r)=>{n=t,s=r})),o=!1;function a(){for(const r of t.splice(0,t.length))r({done:!0,value:void 0})}return{close(){o=!0,a()},async write(n){if(o)throw null!=e?e:new Error("cannot write, WritableIterable already closed");const s=t.shift();if(void 0===s)r.push(n);else if(s({done:!1,value:n}),t.length>0)return;const a=r.length+1;for(let t=0;t({next(){n(),i=new Promise(((t,r)=>{n=t,s=r}));const e=r.shift();if(void 0!==e)return Promise.resolve({done:!1,value:e});if(o)return Promise.resolve({done:!0,value:void 0});let a;const u=new Promise((t=>a=t));return t.push(a),u},throw:t=>(e=t,o=!0,r.splice(0,r.length),i.catch((()=>{})),s(e),a(),Promise.resolve({done:!0,value:void 0})),return:()=>(o=!0,r.splice(0,r.length),n(),i=Promise.reject(new Error("cannot write, consumer called return")),i.catch((()=>{})),a(),Promise.resolve({done:!0,value:void 0}))})}}function I(t){return f(this,arguments,(function*(){yield m(yield*function(t){var r,e;return r={},n("next"),n("throw",(function(t){throw t})),n("return"),r[Symbol.iterator]=function(){return this},r;function n(n,s){r[n]=t[n]?function(r){return(e=!e)?{value:m(t[n](r)),done:!1}:s?s(r):r}:s}}(l(t)))}))}},"../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/protocol/limit-io.js"(t,r,e){e.d(r,{NL:()=>a,Tw:()=>u,kk:()=>c});var n=e("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/connect-error.js"),s=e("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/code.js");const i=4294967295,o=i;function a(t,r,e){if(null!=r||(r=o),null!=t||(t=i),null!=e||(e=1024),r<1||r>o)throw new n.T(`writeMaxBytes ${r} must be >= 1 and <= 4294967295`,s.C.Internal);if(t<1||t>i)throw new n.T(`readMaxBytes ${t} must be >= 1 and <= 4294967295`,s.C.Internal);return{readMaxBytes:t,writeMaxBytes:r,compressMinBytes:e}}function u(t,r){if(r>t)throw new n.T(`message size ${r} is larger than configured writeMaxBytes ${t}`,s.C.ResourceExhausted)}function c(t,r,e=!1){if(r>t){let i=`message size is larger than configured readMaxBytes ${t}`;throw e&&(i=`message size ${r} is larger than configured readMaxBytes ${t}`),new n.T(i,s.C.ResourceExhausted)}}},"../../node_modules/.pnpm/brace-expansion@5.0.12/node_modules/brace-expansion/dist/esm/index.js"(t,r,e){e.d(r,{fT:()=>x});const n=(t,r,e)=>{const n=t instanceof RegExp?s(t,e):t,o=r instanceof RegExp?s(r,e):r,a=null!==n&&null!=o&&i(n,o,e);return a&&{start:a[0],end:a[1],pre:e.slice(0,a[0]),body:e.slice(a[0]+n.length,a[1]),post:e.slice(a[1]+o.length)}},s=(t,r)=>{const e=r.match(t);return e?e[0]:null},i=(t,r,e)=>{let n,s,i,o,a,u=e.indexOf(t),c=e.indexOf(r,u+1),l=u;if(u>=0&&c>0){if(t===r)return[u,c];for(n=[],i=e.length;l>=0&&!a;){if(l===u)n.push(l),u=e.indexOf(t,l+1);else if(1===n.length){const t=n.pop();void 0!==t&&(a=[t,c])}else s=n.pop(),void 0!==s&&s=0?u:c}n.length&&void 0!==o&&(a=[i,o])}return a},o="\0SLASH"+Math.random()+"\0",a="\0OPEN"+Math.random()+"\0",u="\0CLOSE"+Math.random()+"\0",c="\0COMMA"+Math.random()+"\0",l="\0PERIOD"+Math.random()+"\0",m=new RegExp(o,"g"),f=new RegExp(a,"g"),d=new RegExp(u,"g"),p=new RegExp(c,"g"),h=new RegExp(l,"g"),g=/\\\\/g,_=/\\{/g,J=/\\}/g,w=/\\,/g,y=/\\\./g,S=1e5,q=4e6,B=1e3,I=1e3;function P(t){return isNaN(t)?t.charCodeAt(0):parseInt(t,10)}function b(t){return t.replace(m,"\\").replace(f,"{").replace(d,"}").replace(p,",").replace(h,".")}function R(t,r){for(let e=0;e=r}function U(t,r,e,n,s,i){const o=[];let a=0;for(let u=0;u=n)return o;const l=t[u]+r+e[c];if(!i||l){if(a+l.length>s)return o;o.push(l),a+=l.length}}return o}function A(t,r,e,n){const s=t.split(/\.\./),i=[];if(void 0===s[0]||void 0===s[1])return i;const o=P(s[0]),a=P(s[1]),u=Math.max(s[0].length,s[1].length);let c=3===s.length&&void 0!==s[2]?Math.max(Math.abs(P(s[2])),1):1,l=C;a0){const n=new Array(r+1).join("0");e=t<0?"-"+n+e.slice(1):n+e}}if(f+e.length>n)break;i.push(e),f+=e.length}return i}function $(t,r,e,s,i,o,a){if(i>s)return[t];let c=[""],l=0,m=!1,f=!0;for(;;){const d=n("{","}",t);if(!d)return U(c,t,[""],r,e,m);const p=d.pre;if(/\$$/.test(p)){if(c=U(c,p+"{"+d.body+"}",[""],r,e,m&&!d.post.length),f=!1,!d.post.length)break;t=d.post;continue}const h=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(d.body),g=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(d.body),_=h||g,J=d.body.indexOf(",")>=0;if(!_&&!J){if(l=r||u+n.length>e)break t;w.push(n),u+=n.length}}}}if(c=U(c,p,w,r,e,m&&!d.post.length),!d.post.length)break;t=d.post}return c}},"../agent-kv/dist/agent-store.js"(t,r,e){e.d(r,{TU:()=>p,aY:()=>y,pH:()=>v,sh:()=>g});var n=e("../proto/dist/generated/agent/v1/agent_pb.js"),s=e("../proto/dist/generated/agent/v1/todo_tool_pb.js"),i=e("../utils/dist/disposable.js"),o=e("zod/v4"),a=e("../agent-kv/dist/blob-store.js"),u=e("../agent-kv/dist/serde.js"),c=e("../agent-kv/dist/subagent-states.js");const l=["default","plan","debug","search"],m=["allowlist","unrestricted","auto-review"],f=/^[0-9a-f]+$/;function d(){const t=new Uint8Array(32);return crypto.getRandomValues(t),(0,u.nj)(t)}function p(t){return"string"==typeof t&&64===t.length&&f.test(t)}let h=null;const g=t=>({agentId:t??crypto.randomUUID(),latestRootBlobId:new Uint8Array,name:"New Agent",mode:"default",isRunEverything:!1,approvalMode:void 0,createdAt:Date.now(),lastUsedModel:void 0,lastDebugServerPort:void 0,currentPlanUri:void 0,subagentInfo:void 0,blobEncryptionKey:d()}),_=new Set(l),J=new Set(m);function w(t,r){const e=function(t){return"object"==typeof t&&null!==t}(t)&&r in t?t[r]:void 0;return"string"==typeof e&&e.length>0?e:void 0}class y{serialize(t){const r=(0,u.nj)(t.latestRootBlobId);return u.bO.serialize(JSON.stringify({...t,latestRootBlobId:r}))}deserialize(t){const r=JSON.parse(u.bO.deserialize(t)),e=g(r.agentId),n="string"==typeof r.latestRootBlobId?(0,u.aD)(r.latestRootBlobId):e.latestRootBlobId;let s=!0===r.isRunEverything,i=r.mode;"auto-run"===i&&(i="default",s=!0);const a="string"==typeof i&&(c=i,_.has(c))?i:"default";var c;const f=r.approvalMode,d="string"==typeof f&&function(t){return J.has(t)}(f)?f:void 0,y=function(t){if(!t||"object"!=typeof t)return;const r=w(t,"parentAgentId"),e=w(t,"rootParentAgentId"),n=w(t,"toolCallId"),s=w(t,"typeName");return void 0!==r&&void 0!==e&&void 0!==n&&void 0!==s?{parentAgentId:r,rootParentAgentId:e,toolCallId:n,typeName:s}:void 0}(r.subagentInfo),S=p(r.blobEncryptionKey)?r.blobEncryptionKey:e.blobEncryptionKey;return(null===h&&(h=o.object({agentId:o.string(),latestRootBlobId:o.custom((t=>t instanceof Uint8Array),{error:"Expected Uint8Array"}),name:o.string(),createdAt:o.number(),mode:o.enum(l),isRunEverything:o.boolean(),approvalMode:o.enum(m).optional(),lastUsedModel:o.string().optional(),lastDebugServerPort:o.number().int().positive().optional(),currentPlanUri:o.string().optional(),subagentInfo:o.object({parentAgentId:o.string().min(1),rootParentAgentId:o.string().min(1),toolCallId:o.string().min(1),typeName:o.string().min(1)}).optional(),blobEncryptionKey:o.string().optional()})),h).parse({...e,...r,mode:a,isRunEverything:s,approvalMode:d,latestRootBlobId:n,subagentInfo:y,blobEncryptionKey:S})}getBlobType(){return{kind:"json"}}}const S=new u.cm(s.kW),q=new u.cm(n.RGk),B=new u.cm(n.kJk),I=new u.cm(n.cmU),P=new u.cm(n.KRq),b=new u.cm(n.oIR),R=new u.cm(n.qKL);class v{constructor(t,r,e={}){this.blobStore=t,this.metadataStore=r,this.serde=new u.cm(n.Y9z),this.conversationStateStructure=new n.Y9z,this.fixedRootBlobId=e.fixedRootBlobId}subscribeToMetadata(t,r){return this.metadataStore.subscribe(t,(()=>{r(this.metadataStore.get(t))}))}setMetadata(t,r){this.metadataStore.set(t,r)}getMetadata(t){return this.metadataStore.get(t)}getId(){return this.getMetadata("agentId")}getBlobStore(){return this.blobStore}getConversationStateStructure(){return this.conversationStateStructure}async getLastRequestIdFromConversation(t){const r=this.conversationStateStructure.turns;if(0===r.length)return null;for(let e=r.length-1;e>=0;e--){const n=r[e],s=await this.blobStore.getBlob(t,n);if(!s)continue;const i=I.deserialize(s);if("agentConversationTurn"===i.turn.case)return i.turn.value.requestId??null}return null}async getFullConversation(t){return this.deserializeConversationStateStructure(t,this.conversationStateStructure)}async deserializeConversationStateStructure(t,r){return async function(t,r,e){const s=new n.ljj,i=[],o=r.turns;for(const r of o){const s=await e.getBlob(t,r);if(!s)continue;const o=I.deserialize(s);let a;switch(o.turn.case){case"agentConversationTurn":{const r=o.turn.value,s=await e.getBlob(t,r.userMessage);if(!s)continue;const i=q.deserialize(s),u=[];for(const n of r.steps){const r=await e.getBlob(t,n);if(r){const t=B.deserialize(r);u.push(t)}}const c=new n.i9c({userMessage:i,steps:u});a=new n.j97({turn:{case:"agentConversationTurn",value:c}});break}case"shellConversationTurn":{const r=o.turn.value,s=await e.getBlob(t,r.shellCommand);if(!s)continue;const i=b.deserialize(s),u=await e.getBlob(t,r.shellOutput);if(!u)continue;const c=R.deserialize(u),l=new n.tms({shellCommand:i,shellOutput:c});a=new n.j97({turn:{case:"shellConversationTurn",value:l}});break}}a&&i.push(a)}s.turns=i;const a=[];for(const n of r.todos){const r=await e.getBlob(t,n);if(r){const t=S.deserialize(r);a.push(t)}}if(s.todos=a,r.summary){const n=await e.getBlob(t,r.summary);if(n){const t=P.deserialize(n);s.summary=t}}return s}(t,r,this.blobStore)}async getFullConversationWithSubagents(t){const r=this.conversationStateStructure,e=await this.deserializeConversationStateStructure(t,r),n={},s=await(0,c.Vn)(t,r,this.blobStore);for(const[r,e]of Object.entries(s))if(e.conversationState){const s=await this.deserializeConversationStateStructure(t,e.conversationState);n[r]={conversationState:s,createdTimestampMs:e.createdTimestampMs,lastUsedTimestampMs:e.lastUsedTimestampMs,subagentType:e.subagentType}}return{conversationState:e,subagentStates:n}}getLatestCheckpoint(){return this.getConversationStateStructure()}async handleCheckpoint(t,r){const e=this.serde.serialize(r),n=this.fixedRootBlobId??await(0,a.Bk)(e);await this.blobStore.setBlob(t,n,e),this.setMetadata("latestRootBlobId",n),this.conversationStateStructure=r}async resetFromDb(t){await this.tryResetFromDb(t)}async tryResetFromDb(t){try{const r=this.getMetadata("latestRootBlobId");if(!r||0===r.length)return this.conversationStateStructure=new n.Y9z,!1;const e=await this.blobStore.getBlob(t,r);if(!e)return this.conversationStateStructure=new n.Y9z,!1;const s=this.serde.deserialize(e);return this.conversationStateStructure=s,!0}catch(t){return this.conversationStateStructure=new n.Y9z,!1}}async dispose(){this.blobStore instanceof i.j&&await this.blobStore.dispose()}}},"../agent-kv/dist/blob-store.js"(t,r,e){e.d(r,{Bk:()=>o,Fo:()=>i,We:()=>l,ve:()=>c});var n=e("../metrics/dist/index.js"),s=e("../agent-kv/dist/serde.js");function i(t){const r=t.buffer;return r instanceof ArrayBuffer?new Uint8Array(r,t.byteOffset,t.byteLength):new Uint8Array(t)}async function o(t){const r=await crypto.subtle.digest("SHA-256",i(t));return new Uint8Array(r)}const a=(0,n.v5)("agent_kv.in_memory.get_blob.duration_ms",{description:"Duration of InMemoryBlobStore getBlob operations in milliseconds"}),u=(0,n.v5)("agent_kv.in_memory.set_blob.duration_ms",{description:"Duration of InMemoryBlobStore setBlob operations in milliseconds"});class c{constructor(){this.blobs=new Map}getBlob(t,r){const e=performance.now();try{const t=this.blobs.get((0,s.nj)(r));return Promise.resolve(t)}finally{const r=performance.now()-e;a.histogram(t,r)}}setBlob(t,r,e){const n=performance.now();try{return this.blobs.set((0,s.nj)(r),e),Promise.resolve()}finally{const r=performance.now()-n;u.histogram(t,r)}}setBlobLocallyOnly(t,r,e){return this.setBlob(t,r,e)}flush(t){return Promise.resolve()}}class l{constructor(){this.store=new Map}set(t,r){this.store.set(t,r)}subscribe(t,r){return()=>{}}get(t){const r=this.store.get(t);if(void 0===r)throw new Error(`Key ${String(t)} not found in store`);return r}}},"../agent-kv/dist/serde.js"(t,r,e){e.d(r,{aD:()=>c,bO:()=>i,cm:()=>o,nj:()=>u});const n=new TextDecoder,s=new TextEncoder,i=new class{serialize(t){return s.encode(t)}deserialize(t){return n.decode(t)}getBlobType(){return{kind:"string"}}};class o{constructor(t){this.proto=t}serialize(t){return t.toBinary()}deserialize(t){return this.proto.fromBinary(t)}getBlobType(){return{kind:"proto",typeName:this.proto.typeName}}}const a=Array.from({length:256},((t,r)=>r.toString(16).padStart(2,"0")));function u(t){if("undefined"!=typeof Buffer)return Buffer.from(t).toString("hex");let r="";for(let e=0;e=64&&"undefined"!=typeof Buffer){const t=function(t){if(Buffer.byteLength(t,"utf8")===t.length)try{const r=new Uint8Array(t.length/2);if(Buffer.from(r.buffer,r.byteOffset,r.byteLength).write(t,"hex")===r.length)return r}catch{}}(r);if(void 0!==t)return t}const e=new Uint8Array(r.length/2);for(let t=0;tm});var n=e("../context/dist/logger.js"),s=e("../metrics/dist/index.js"),i=e("../proto/dist/generated/agent/v1/agent_pb.js"),o=e("../utils/dist/promise-extras.js"),a=e("../agent-kv/dist/serde.js");const u=(0,n.h)("@anysphere/agent-kv:subagent-states"),c=(0,s.Pu)("agent_kv.subagent_state_ref.missing_blob",{description:"Subagent state refs whose blob was missing, counted per read until a checkpoint rewrites the ref. fallback=inline kept the entry saved beside the ref (usually a transcript-free summary), dropped omitted the subagent, superseded kept a newer in-memory state.",labelNames:["reader","fallback"]});function l(t,r){u.warn(t,"Subagent state ref blob not found; restoring without its transcript",r),c.increment(t,1,{reader:r.reader,fallback:r.fallback})}async function m(t,r,e){const n={...r.subagentStates??{}},s=Object.entries(r.subagentStateRefs??{});if(0===s.length)return n;const u=await(0,o.PH)(s,(async([r,n])=>{const s=await e.getBlob(t,n);if(void 0===s)return{kind:"missing",subagentId:r,blobIdHex:(0,a.nj)(n)};try{return{kind:"loaded",subagentId:r,state:i.aK_.fromBinary(s)}}catch(t){return{kind:"failed",error:t}}}),{max:8}),c=u.find((t=>"failed"===t.kind));if(void 0!==c&&"failed"===c.kind)throw c.error;for(const r of u)if("loaded"===r.kind)n[r.subagentId]=r.state;else if("missing"===r.kind){const e=void 0!==n[r.subagentId];l(t,{reader:"resolve",fallback:e?"inline":"dropped",subagentId:r.subagentId,blobIdHex:r.blobIdHex})}return n}},"../context/dist/core.js"(t,r,e){function n(t,r){return{symbol:t,defaultValue:r}}function s(t){const r=new AbortController;if(t.aborted)return r.abort(t.reason),{signal:r.signal,abort(t){r.abort(t)},unlink(){}};const e=()=>r.abort(t.reason);return t.addEventListener("abort",e,{once:!0}),{signal:r.signal,abort(n){t.removeEventListener("abort",e),r.abort(n)},unlink(){t.removeEventListener("abort",e)}}}e.d(r,{cF:()=>n,q6:()=>o,uk:()=>a});class i{constructor(t,r,e,n){this.parent=t,this.values=e||new Map,this.name=n,this.signal=r||(t?t.signal:(new AbortController).signal)}get canceled(){return this.signal.aborted}get reason(){return this.signal.reason}get(t){return this.values.has(t.symbol)?this.values.get(t.symbol):this.parent?this.parent.get(t):t.defaultValue}with(t,r){const e=new Map(this.values);return e.set(t.symbol,r),new i(this,void 0,e)}withCancel(){const t=s(this.signal);return[new i(this,t.signal),r=>t.abort(r)]}withUnlinkableCancel(){const t=s(this.signal);return[new i(this,t.signal),r=>t.abort(r),()=>t.unlink()]}withTimeout(t){const r=s(this.signal),e=new i(this,r.signal),n=setTimeout((()=>{r.abort(new Error("context deadline exceeded"))}),t);return r.signal.addEventListener("abort",(()=>{clearTimeout(n)}),{once:!0}),e}withDeadline(t){const r=t.getTime()-Date.now();if(r<=0){const t=s(this.signal);return t.abort(new Error("context deadline exceeded")),new i(this,t.signal)}return this.withTimeout(r)}withTimeoutAndCancel(t){const[r,e]=this.withCancel();return[r.withTimeout(t),e]}withName(t){return new i(this,void 0,void 0,t)}withDetached(){return new i(this,(new AbortController).signal)}getParent(){return this.parent}getPath(){const t=[];let r=this;for(;r;)r.name&&t.unshift(r.name),r=r.getParent();return t}}function o(){return new i}function a(t){return new Promise((r=>{t.canceled?r():t.signal.addEventListener("abort",(()=>r()),{once:!0})}))}},"../context/dist/logger.js"(t,r,e){e.d(r,{_O:()=>m,h:()=>f});var n=e("../context/dist/core.js");function s(t){return"object"==typeof t&&null!==t&&"getPath"in t&&"function"==typeof t.getPath}function i(t){return"object"==typeof t&&null!==t&&("message"in t||"stack"in t||"name"in t||"cause"in t)}function o(t,r,e,n,s,c){const l=function(t,r,e,n){if(!r.inlineSerializer)return t;try{const s=r.inlineSerializer(t,{path:e,depth:n});return void 0===s?t:s}catch{return t}}(t,r,c,n);if(function(t){return"object"==typeof t&&null!==t&&"kind"in t&&"summary"===t.kind&&"summary"in t&&"string"==typeof t.summary}(l))return e.dim(`<${l.summary}>`);if(null===(t=l))return e.gray("null");if(void 0===t)return e.gray("undefined");if("string"==typeof t){const n=function(t,r){return t.length<=r?t:`${t.slice(0,r)}...`}(t,r.maxStringLength);return e.green(JSON.stringify(n))}if("number"==typeof t)return e.yellow(String(t));if("boolean"==typeof t)return e.magenta(String(t));if("bigint"==typeof t)return e.yellow(`${t}n`);if("symbol"==typeof t)return e.cyan(t.toString());if("function"==typeof t){const r=t.name?` ${t.name}`:"";return e.dim(`[Function${r}]`)}if(t instanceof Date){const r=Number.isNaN(t.getTime())?"Invalid Date":t.toISOString();return e.green(r)}if(t instanceof RegExp)return e.cyan(t.toString());if(i(t))return a(t,r,e,n,s,c);if(Array.isArray(t))return u(t,r,e,n,s,c);if("undefined"!=typeof ArrayBuffer&&t instanceof ArrayBuffer)return e.dim(`ArrayBuffer(${t.byteLength})`);if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&ArrayBuffer.isView(t)){const r=t,n=r.constructor?.name??"TypedArray";return e.dim(`${n}(${r.byteLength})`)}return t instanceof Map?function(t,r,e,n,s,i){if(n>=r.maxDepth)return e.dim(`Map(${t.size})`);if(s.has(t))return e.dim("[Circular]");s.add(t);const a=Array.from(t.entries()),u=Math.min(a.length,r.maxEntries),c=a.slice(0,u).map((([t,a])=>{const u=o(t,r,e,n+1,s,i.concat("")),c=o(a,r,e,n+1,s,i.concat(String(t)));return`${u} ${e.dim("=>")} ${c}`}));a.length>u&&c.push(e.dim(`... ${a.length-u} more`));const l=e.dim(", "),m=`${e.dim("Map{")}${c.join(l)}${e.dim("}")}`;return s.delete(t),m}(t,r,e,n,s,c):t instanceof Set?u(Array.from(t.values()),r,e,n,s,c):"object"==typeof t?function(t,r,e,n,s,i){if(n>=r.maxDepth){const r=t?.constructor?.name??"Object";return e.dim(`[${r}]`)}if(s.has(t))return e.dim("[Circular]");s.add(t);const a=Object.entries(t);if(0===a.length){const r=e.dim("{}");return s.delete(t),r}const u=Math.min(a.length,r.maxEntries),c=a.slice(0,u).map((([t,a])=>{const u=o(a,r,e,n+1,s,i.concat(t));return`${e.cyan(t)}: ${u}`}));a.length>u&&c.push(e.dim(`... ${a.length-u} more`));const l=e.dim(", "),m=`${e.dim("{")}${c.join(l)}${e.dim("}")}`;return s.delete(t),m}(t,r,e,n,s,c):e.dim(`[${typeof t}]`)}function a(t,r,e,n,s,i){if(s.has(t))return e.dim("[Circular]");s.add(t);const a="string"==typeof t.name?t.name:"Error",u="string"==typeof t.message?t.message:"",c=u?`${a}: ${u}`:a;let l=e.red(c);if("cause"in t&&void 0!==t.cause){const a=o(t.cause,r,e,n+1,s,i.concat("cause"));l=`${l} ${e.dim("cause=")}${a}`}return s.delete(t),l}function u(t,r,e,n,s,i){if(n>=r.maxDepth)return e.dim(`[Array(${t.length})]`);if(s.has(t))return e.dim("[Circular]");if(s.add(t),0===t.length){const r=e.dim("[]");return s.delete(t),r}const a=Math.min(t.length,r.maxArrayLength),u=t.slice(0,a).map(((t,a)=>o(t,r,e,n+1,s,i.concat(a))));t.length>a&&u.push(e.dim(`... ${t.length-a} more`));const c=e.dim(", "),l=`${e.dim("[")}${u.join(c)}${e.dim("]")}`;return s.delete(t),l}let c=function(t={}){const r=function(t){return{indent:" ".repeat(t.indent??2),maxDepth:t.maxDepth??6,maxEntries:t.maxEntries??50,maxArrayLength:t.maxArrayLength??40,maxStringLength:t.maxStringLength??200,includeTimestamp:t.includeTimestamp??!0,timestampFormat:t.timestampFormat??"time",includeContextPath:t.includeContextPath??!0,inlineSerializer:t.inlineSerializer}}(t),e=function(t){const r=r=>e=>t?`[${r.join(";")}m${e}`:e,e=r([2]),n=r([90]),s=r([31]),i=r([32]),o=r([33]),a=r([34]),u=r([35]),c=r([36]),l=r([1]),m=r([1,31]);return{dim:e,gray:n,red:s,green:i,yellow:o,blue:a,magenta:u,cyan:c,bold:l,level:(t,r)=>{switch(t){case"debug":return u(r);case"info":return a(r);case"warn":return o(r);case"error":return m(r);default:return t}}}}(function(t){if("boolean"==typeof t)return t;if("undefined"==typeof process)return!1;const r=process.env??{};if("NO_COLOR"in r)return!1;if("dumb"===r.TERM)return!1;const e=r.FORCE_COLOR;return"1"===e||"true"===e||"0"!==e&&(process.stdout?.isTTY??!1)}(t.useColors)),n=t.console??console;return{log:(t,u)=>{const c=[];r.includeTimestamp&&c.push(e.dim(function(t,r){const e=t.toISOString();return"date-time"===r?e:e.slice(11,23)}(u.timestamp,r.timestampFormat)));const l=u.level.toUpperCase().padEnd(5);c.push(e.level(u.level,l));const m="error"===u.level?e.bold(u.message):u.message;if(c.push(m),r.includeContextPath&&s(u.context)){const t=u.context.getPath();t.length>0&&c.push(e.dim(`ctx=${t.join("/")}`))}const f=new WeakSet;if(!s(u.context)&&u.context&&Object.keys(u.context).length>0){const t=o(u.context,r,e,0,f,["context"]);c.push(`${e.dim("context=")}${t}`)}if(u.metadata&&Object.keys(u.metadata).length>0){const t=o(u.metadata,r,e,0,f,["metadata"]);c.push(`${e.dim("meta=")}${t}`)}const d=[c.join(" ")];if(void 0!==u.error){const t=i(u.error)?a(u.error,r,e,0,f,["error"]):o(u.error,r,e,0,f,["error"]);if(d[0]=`${d[0]} ${e.dim("error=")}${t}`,i(u.error)&&"string"==typeof u.error.stack){const t=u.error.stack.split("\n").slice(1);for(const n of t){const t=n.trim();t&&d.push(`${r.indent}${e.dim(t)}`)}}}const p=d.join("\n");switch(u.level){case"debug":case"info":n.log(p);break;case"warn":n.warn(p);break;case"error":n.error(p);break;default:{const t=u.level;throw new Error(`Unhandled log level: ${String(t)}`)}}}}}();const l={log:(t,r)=>c.log(t,r)},m=(0,n.cF)(Symbol("loggerBackend"),l);function f(t){function r(r,e){const n=new Date,s=function(t){return t.get(m)}(r);s.log(r,{...e,timestamp:n,logger:t})}return{debug:(t,e,n)=>{r(t,{level:"debug",message:e,context:t,metadata:n})},info:(t,e,n)=>{r(t,{level:"info",message:e,context:t,metadata:n})},warn:(t,e,n)=>{r(t,{level:"warn",message:e,context:t,metadata:n})},error:(t,e,n,s)=>{r(t,{level:"error",message:e,context:t,error:n,metadata:s})}}}},"../cursor-sdk-local-runtime/dist/run-store/id.js"(t,r,e){e.d(r,{M2:()=>i,WQ:()=>s,nq:()=>o});var n=e("../utils/dist/fresh-uuid.js");function s(){return`agent-${(0,n.C)()}`}function i(){return`bc-${(0,n.C)()}`}function o(){return`run-${(0,n.C)()}`}},"../cursor-sdk-local-runtime/dist/run-store/in-memory-run-event-notifier.js"(t,r,e){e.d(r,{U:()=>n,y:()=>s});class n{constructor(){this.subscribersByRun=new Map}async publishRunEventAppended(t){const r=this.subscribersByRun.get(t.runId);if(r)for(const e of r){if(e.closed)continue;const r=e.waiters.shift();r?r({value:t,done:!1}):e.queue.push(t)}}subscribeRunEvents(t){const r={closed:!1,queue:[],waiters:[]},e=this.subscribersByRun.get(t.runId)??new Set;e.add(r),this.subscribersByRun.set(t.runId,e);const n=t.signal,s=()=>{if(n?.removeEventListener("abort",s),!r.closed)for(r.closed=!0,e.delete(r),0===e.size&&this.subscribersByRun.delete(t.runId);r.waiters.length>0;)r.waiters.shift()?.({value:void 0,done:!0})};return n?.aborted?s():n?.addEventListener("abort",s,{once:!0}),{[Symbol.asyncIterator]:()=>({next:async()=>{const t=r.queue.shift();return t?{value:t,done:!1}:r.closed||n?.aborted?(s(),{value:void 0,done:!0}):new Promise((t=>{r.waiters.push(t)}))},return:async()=>(s(),{value:void 0,done:!0})})}}}function s(){return new n}},"../cursor-sdk-local-runtime/dist/run-store/index.js"(t,r,e){e.d(r,{U1:()=>s.U,tY:()=>u,w:()=>c,M2:()=>n.M2,WQ:()=>n.WQ});var n=e("../cursor-sdk-local-runtime/dist/run-store/id.js");e("../cursor-sdk-local-runtime/dist/run-store/status.js");var s=e("../cursor-sdk-local-runtime/dist/run-store/in-memory-run-event-notifier.js"),i=e("node:fs"),o=e("node:net"),a=e("node:path");class u{constructor(t){this.socketPath=t.socketPath,this.connectTimeoutMs=t.connectTimeoutMs??1e3,this.requestTimeoutMs=t.requestTimeoutMs??5e3}async publishRunEventAppended(t){const r=await d({socketPath:this.socketPath,timeoutMs:this.connectTimeoutMs});try{f(r,{type:"publish",hint:t});const e=await async function(t,r){const e=new AbortController,n=setTimeout((()=>e.abort()),r);try{for await(const r of p(t,e.signal))return r}catch(t){if(e.signal.aborted)throw new Error("Timed out waiting for notifier response");throw t}finally{clearTimeout(n)}throw new Error("Notifier closed before sending a response")}(r,this.requestTimeoutMs);if("error"===e.type)throw new Error(e.message);if("ack"!==e.type)throw new Error(`Unexpected notifier response ${e.type}`)}finally{r.destroy()}}subscribeRunEvents(t){const r=function(){let t,r;return{promise:new Promise(((e,n)=>{t=e,r=n})),resolve:t,reject:r}}(),e=this.createSubscription(t,r);return{ready:r.promise,[Symbol.asyncIterator]:()=>e[Symbol.asyncIterator]()}}async*createSubscription(t,r){let e;try{e=await d({socketPath:this.socketPath,timeoutMs:this.connectTimeoutMs,signal:t.signal});const n=p(e,t.signal)[Symbol.asyncIterator]();try{f(e,{type:"subscribe",runId:t.runId});const s=await n.next();if(s.done)throw new Error("Notifier closed before confirming subscription");if("error"===s.value.type)throw new Error(s.value.message);if("ack"!==s.value.type)throw new Error(`Unexpected notifier response ${s.value.type}`);r.resolve();for await(const t of{[Symbol.asyncIterator]:()=>n})if("hint"===t.type&&(yield t.hint),"error"===t.type)throw new Error(t.message)}catch(t){throw r.reject(t),t}finally{await(n.return?.())}}catch(t){throw r.reject(t),t}finally{e?.destroy()}}}class c{static async listen(t){const r=new c(t);return await r.listen(),r}constructor(t){this.options=t,this.subscribersByRun=new Map,this.runBySubscriber=new Map,this.sockets=new Set,this.server=(0,o.createServer)((t=>this.handleSocket(t)))}async listen(){var t;m(t=this.options.socketPath)||((0,i.mkdirSync)((0,a.dirname)(t),{recursive:!0}),l(t)),await new Promise(((t,r)=>{const e=t=>{s(),r(t)},n=()=>{s(),t()},s=()=>{this.server.off("error",e),this.server.off("listening",n)};this.server.once("error",e),this.server.once("listening",n),this.server.listen(this.options.socketPath)}))}async close(){for(const t of this.sockets)t.destroy();this.sockets.clear(),this.subscribersByRun.clear(),this.runBySubscriber.clear(),await new Promise(((t,r)=>{this.server.close((e=>{e?r(e):t()}))})).catch((t=>{if("ERR_SERVER_NOT_RUNNING"!==("object"==typeof t&&null!==t&&"code"in t?t.code:void 0))throw t})),l(this.options.socketPath)}handleSocket(t){this.sockets.add(t);let r="";t.on("data",(e=>{for(r+=e.toString("utf8");;){const e=r.indexOf("\n");if(-1===e)return;const n=r.slice(0,e);r=r.slice(e+1),this.handleLine(t,n)}})),t.on("close",(()=>this.cleanupSocket(t))),t.on("error",(()=>this.cleanupSocket(t)))}handleLine(t,r){const e=function(t){const r=g(t);if(r)return"subscribe"===r.type&&"string"==typeof r.runId?{type:"subscribe",runId:r.runId}:"publish"===r.type&&_(r.hint)?{type:"publish",hint:r.hint}:void 0}(r);return e?"subscribe"===e.type?(this.subscribe(t,e.runId),void f(t,{type:"ack"})):(this.publish(e.hint),f(t,{type:"ack"}),void t.end()):(f(t,{type:"error",message:"Invalid notifier message"}),void t.end())}subscribe(t,r){this.unsubscribe(t);const e=this.subscribersByRun.get(r)??new Set;e.add(t),this.subscribersByRun.set(r,e),this.runBySubscriber.set(t,r)}publish(t){const r=this.subscribersByRun.get(t.runId);if(r)for(const e of r)e.destroyed||f(e,{type:"hint",hint:t})}cleanupSocket(t){this.unsubscribe(t),this.sockets.delete(t)}unsubscribe(t){const r=this.runBySubscriber.get(t);if(!r)return;const e=this.subscribersByRun.get(r);e?.delete(t),0===e?.size&&this.subscribersByRun.delete(r),this.runBySubscriber.delete(t)}}function l(t){m(t)||(0,i.existsSync)(t)&&(0,i.unlinkSync)(t)}function m(t){return t.startsWith("\\\\.\\pipe\\")}function f(t,r){t.write(`${JSON.stringify(r)}\n`)}async function d(t){if(t.signal?.aborted)throw J(t.signal);return new Promise(((r,e)=>{const n=(0,o.createConnection)(t.socketPath),s=setTimeout((()=>{c(),n.destroy(),e(new Error(`Timed out connecting to ${t.socketPath}`))}),t.timeoutMs),i=()=>{c(),r(n)},a=t=>{c(),e(t)},u=()=>{c(),n.destroy(),e(J(t.signal))},c=()=>{clearTimeout(s),n.off("connect",i),n.off("error",a),t.signal?.removeEventListener("abort",u)};n.once("connect",i),n.once("error",a),t.signal?.addEventListener("abort",u,{once:!0})}))}async function*p(t,r){let e="";const n=[];let s,i,o=!1;const a=()=>{s?.(),s=void 0},u=r=>{for(e+=r.toString("utf8");;){const r=e.indexOf("\n");if(-1===r)break;const s=e.slice(0,r);e=e.slice(r+1);const a=h(s);if(!a){i=new Error("Invalid notifier server message"),o=!0,t.destroy();break}n.push(a)}a()},c=()=>{o=!0,a()},l=t=>{i=t,o=!0,a()},m=()=>{i=J(r),o=!0,t.destroy(),a()};t.on("data",u),t.on("close",c),t.on("error",l),r?.addEventListener("abort",m,{once:!0});try{for(;;){const t=n.shift();if(t)yield t;else{if(i)throw i;if(o)return;await new Promise((t=>{s=t}))}}}finally{t.off("data",u),t.off("close",c),t.off("error",l),r?.removeEventListener("abort",m)}}function h(t){const r=g(t);if(r)return"ack"===r.type?{type:"ack"}:"error"===r.type&&"string"==typeof r.message?{type:"error",message:r.message}:"hint"===r.type&&_(r.hint)?{type:"hint",hint:r.hint}:void 0}function g(t){try{const r=JSON.parse(t);if("object"!=typeof r||null===r||Array.isArray(r))return;const e={};for(const[t,n]of Object.entries(r))e[t]=n;return e}catch{return}}function _(t){return Boolean(t&&"object"==typeof t&&"string"==typeof t.runId&&"string"==typeof t.offset)}function J(t){const r=t?.reason;return r instanceof Error?r:new Error("Run event notifier aborted")}},"../cursor-sdk-local-runtime/dist/run-store/sqlite-blob-store.js"(t,r,e){e.d(r,{B_:()=>h,SQLiteBlobStoreWithMetadata:()=>g,hI:()=>p,rZ:()=>f});var n=e("node:fs"),s=e("node:path"),i=e("../agent-kv/dist/agent-store.js"),o=e("../agent-kv/dist/serde.js"),a=e("../utils/dist/disposable.js"),u=e("../cursor-sdk-local-runtime/dist/utils/logger.js"),c=e("../cursor-sdk-local-runtime/dist/run-store/sqlite/open-sqlite-driver.js"),l=e("../cursor-sdk-local-runtime/dist/run-store/sqlite/sqlite-driver.js");const m=new i.aY,f="Local agent storage could not open its database, so this run is continuing in memory. Its checkpoint may be unavailable after the process exits.",d="unable to open database file";function p(t){const r=new Set;let e=t;for(;null!=e&&!r.has(e);){if(r.add(e),"object"!=typeof e)return"string"==typeof e&&e.toLowerCase().includes(d);const t=e;if("SQLITE_CANTOPEN"===t.code)return!0;if("ERR_SQLITE_ERROR"===t.code&&"number"==typeof t.errcode&&14==(255&t.errcode))return!0;if("string"==typeof t.message&&t.message.toLowerCase().includes(d))return!0;e=t.cause}return!1}function h(t,r){const e=t;return"function"!=typeof e.onLocalStoreDegraded?()=>{}:e.onLocalStoreDegraded(r)}class g extends a.j{static async initAndLoad(t){const r=new g(t);return await r.getDriver(),r}constructor(t,r){super(),this.dbPath=t,this.openDisabled=!1,this.memoryBlobs=new Map,this.deletedBlobIds=new Set,this.degradationListeners=new Set,this.listeners={agentId:new Set,latestRootBlobId:new Set,name:new Set,createdAt:new Set,mode:new Set,isRunEverything:new Set,approvalMode:new Set,lastUsedModel:new Set,lastDebugServerPort:new Set,currentPlanUri:new Set,subagentInfo:new Set},this.persistScheduled=!1,this.metadataUnpersisted=!1,this.isDisposing=!1,this.openDriver=r?.openDriver??c.d;const e=(0,s.basename)((0,s.dirname)(this.dbPath));this.metadata=(0,i.sh)(e)}onLocalStoreDegraded(t){return this.degradationListeners.add(t),void 0!==this.degradationWarning&&this.notifyDegradationListener(t,this.degradationWarning),()=>{this.degradationListeners.delete(t)}}async getDriver(){if(!this.openDisabled){if(this.driver)return this.driver;if(!this.driverPromise){const t=(async()=>{const t=(0,s.dirname)(this.dbPath);(0,n.existsSync)(t)||(0,n.mkdirSync)(t,{recursive:!0});const r=await this.openDriver(this.dbPath);try{this.initializeDriver(r)}catch(t){throw r.close(),t}return this.driver=r,r})().catch((r=>{throw this.driverPromise===t&&(this.driverPromise=void 0),r}));this.driverPromise=t}try{return await this.driverPromise}catch(t){if(p(t))return this.openDisabled=!0,void this.degrade(t);throw t}}}degrade(t){if(void 0===this.degradationWarning){this.degradationWarning=f,u.Jz.warn(f,t instanceof Error?t.message:String(t));for(const t of this.degradationListeners)this.notifyDegradationListener(t,this.degradationWarning)}}notifyDegradationListener(t,r){try{t(r)}catch{}}rememberBlob(t,r){this.memoryBlobs.set(t,Uint8Array.from(r))}readRememberedBlob(t){const r=this.memoryBlobs.get(t);return void 0===r?void 0:Uint8Array.from(r)}async withDriver(t,r){try{const e=await this.getDriver();return e?r(e):t()}catch(r){if(!p(r))throw r;return this.degrade(r),t()}}initializeDriver(t){t.exec("PRAGMA journal_mode = WAL;\n PRAGMA synchronous = NORMAL;\n PRAGMA busy_timeout = 5000;\n PRAGMA user_version = 1;\n CREATE TABLE IF NOT EXISTS blobs (id TEXT PRIMARY KEY, data BLOB);\n CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT);");const r=t.get("SELECT value FROM meta WHERE key = ?",["0"]);if(r?.value)this.metadata=m.deserialize((0,o.aD)(r.value)),this.storedMetadataHex=r.value;else{const r=(0,o.nj)(m.serialize(this.metadata));t.run("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)",["0",r]),this.storedMetadataHex=r}this.metadataUnpersisted=!1}async getBlob(t,r){if(this.isDisposing)return;const e=(0,o.nj)(r);if(this.deletedBlobIds.has(e))return;const n=this.readRememberedBlob(e);return void 0!==n?n:this.withDriver((()=>{}),(t=>{const r=t.get("SELECT data FROM blobs WHERE id = ?",[e]);return null==r?.data?void 0:new Uint8Array(r.data)}))}async listBlobIds(){if(this.isDisposing)return[];const t=new Set(this.memoryBlobs.keys()),r=await this.withDriver((()=>[]),(t=>t.all("SELECT id FROM blobs ORDER BY id ASC").map((t=>t.id))));for(const e of r)t.add(e);return[...t].filter((t=>!this.deletedBlobIds.has(t))).sort()}async deleteBlob(t){this.isDisposing||(this.memoryBlobs.delete(t),await this.withDriver((()=>{this.deletedBlobIds.add(t)}),(r=>{r.run("DELETE FROM blobs WHERE id = ?",[t]),this.deletedBlobIds.delete(t)})))}async setBlob(t,r,e){if(this.isDisposing)return;const n=(0,o.nj)(r);await this.withDriver((()=>{this.deletedBlobIds.delete(n),this.rememberBlob(n,e)}),(t=>{t.run("INSERT OR REPLACE INTO blobs (id, data) VALUES (?, ?)",[n,Buffer.from(e)]),this.memoryBlobs.delete(n),this.deletedBlobIds.delete(n)}))}async setBlobLocallyOnly(t,r,e){return Promise.resolve()}async compareAndSetRoot({expected:t,next:r,blobs:e=[],metadata:n={}}){if(this.isDisposing)return!1;const s=await this.withDriver((()=>{}),(s=>(0,l.R)(s,(()=>{const i=s.get("SELECT value FROM meta WHERE key = ?",["0"]),a=i?.value?m.deserialize((0,o.aD)(i.value)):this.metadata;if((0,o.nj)(a.latestRootBlobId)!==(0,o.nj)(t))return;const u=[];for(const[t,r]of e)s.run("INSERT OR IGNORE INTO blobs (id, data) VALUES (?, ?)",[t,Buffer.from(r)]),u.push(t);const c={...a,...n,latestRootBlobId:r},l=(0,o.nj)(m.serialize(c));return s.run("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)",["0",l]),{updated:c,hex:l,ids:u}}))));if(void 0===s)return!1;for(const t of s.ids)this.deletedBlobIds.delete(t);return this.metadata=s.updated,this.storedMetadataHex=s.hex,this.metadataUnpersisted=!1,!0}async flush(t){return Promise.resolve()}get(t){return this.metadata[t]}reloadMetadata(){const t=this.driver;if(void 0===t||this.isDisposing||this.metadataUnpersisted)return;const r=t.get("SELECT value FROM meta WHERE key = ?",["0"]);r?.value&&r.value!==this.storedMetadataHex&&(this.metadata=m.deserialize((0,o.aD)(r.value)),this.storedMetadataHex=r.value)}valuesEqual(t,r,e){if("latestRootBlobId"===t){if(!(r instanceof Uint8Array&&e instanceof Uint8Array))return r===e;const t=r,n=e;if(t===n)return!0;if(!t||!n)return!1;if(t.length!==n.length)return!1;for(let r=0;r{this.persistScheduled=!1,!this.isDisposing&&this.driver&&this.persistMetadata()}))))}set(t,r){const e=this.metadata[t];if(this.valuesEqual(t,e,r))return;this.metadata={...this.metadata,[t]:r},this.metadataUnpersisted=!0,this.driver&&this.schedulePersist();const n=this.listeners[t];n&&n.size>0&&queueMicrotask((()=>{n.forEach((t=>{t()}))}))}persistMetadata(){const t=this.driver;if(!t)return;const r=(0,o.nj)(m.serialize(this.metadata));try{t.run("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)",["0",r]),this.storedMetadataHex=r,this.metadataUnpersisted=!1}catch(t){if(!p(t))throw t;this.degrade(t)}}subscribe(t,r){const e=this.listeners[t];return e?(e.add(r),()=>e.delete(r)):()=>{}}async dispose(){return this.disposePromise?this.disposePromise:this.driverPromise?(this.disposePromise=this.cleanup().then((()=>{this.driverPromise=void 0,this.driver=void 0})),this.disposePromise):void 0}async cleanup(){if(!this.driverPromise)return;const t=await this.driverPromise.catch((()=>{}));if(!t)return this.driverPromise=void 0,void(this.driver=void 0);this.persistScheduled=!1,this.metadataUnpersisted&&this.persistMetadata(),this.isDisposing=!0;const r=t.get("SELECT value FROM meta WHERE key = ?",["0"]);let e=0;if(r?.value){const t=(0,o.aD)(r.value);e=m.deserialize(t).latestRootBlobId.length}const i=t.get("SELECT COUNT(*) AS count FROM blobs"),a=i?.count??0;if(t.close(),0===e&&0===a){this.driverPromise=void 0,this.driver=void 0;const t=(0,s.dirname)(this.dbPath);try{(0,n.rmSync)(t,{recursive:!0,force:!0})}catch{}}}}},"../cursor-sdk-local-runtime/dist/run-store/sqlite/open-sqlite-driver.js"(t,r,e){e.d(r,{d:()=>i});var n=e("../cursor-sdk-local-runtime/dist/run-store/sqlite/sqlite-driver.js"),s=e("node:path");async function i(t){const r=function(t,r=process.platform){if("win32"!==r)return t;const e=s.win32.resolve(t);return t.length+8>259||e.length+8>259?s.win32.toNamespacedPath(e):t}(t);if("Bun"in globalThis)return(await e.e(914).then(e.bind(e,"../cursor-sdk-local-runtime/dist/run-store/sqlite/bun-sqlite-driver.js"))).openBunSqliteDriver(r);let i;try{i=await e.e(343).then(e.bind(e,"../cursor-sdk-local-runtime/dist/run-store/sqlite/node-sqlite-driver.js"))}catch(t){if(function(t){return"ERR_UNKNOWN_BUILTIN_MODULE"===("object"==typeof t&&null!==t&&"code"in t&&"string"==typeof t.code?t.code:void 0)||(t instanceof Error?t.message.toLowerCase():String(t).toLowerCase()).includes("node:sqlite")}(t))throw new n.Y("node:sqlite is not available in this runtime. The default local agent store requires Node >= 22.13 (or another runtime that implements node:sqlite). Configure a JsonlLocalAgentStore instead.",{cause:t});throw t}return i.openNodeSqliteDriver(r)}},"../cursor-sdk-local-runtime/dist/run-store/sqlite/sqlite-driver.js"(t,r,e){e.d(r,{R:()=>s,Y:()=>n});class n extends Error{constructor(t,r){super(t,r),this.name="NoSqliteDriverError"}}function s(t,r){t.exec("BEGIN IMMEDIATE");try{const e=r();return t.exec("COMMIT"),e}catch(r){try{t.exec("ROLLBACK")}catch{}throw r}}},"../cursor-sdk-local-runtime/dist/run-store/status.js"(t,r,e){e.d(r,{Qb:()=>s});const n=new Set(["FINISHED","ERROR","CANCELLED","EXPIRED"]);function s(t){return n.has(t)}},"../cursor-sdk-local-runtime/dist/utils/logger.js"(t,r,e){e.d(r,{Jz:()=>u,ni:()=>o});var n=e("node:async_hooks");let s={warn:console.warn.bind(console),error:console.error.bind(console)};const i=new n.AsyncLocalStorage;function o(t,r){return i.run(t,r)}function a(){return i.getStore()??s}const u={warn(...t){a().warn(...t)},error(...t){a().error(...t)}}},"../cursor-sdk-shared/dist/message-schemas.js"(t,r,e){e.d(r,{JY:()=>s,K8:()=>l,Kx:()=>i,RB:()=>a,d0:()=>u,lK:()=>o,mj:()=>c});var n=e("zod/v3");const s=n.strictObject({type:n.literal("base64"),data:n.string()}),i=n.strictObject({type:n.literal("user_message"),session_id:n.string(),text:n.string(),images:n.array(s).optional()}),o=n.strictObject({type:n.literal("assistant_message"),session_id:n.string(),text:n.string()}),a=n.union([i,o]);function u(t){return i.safeParse(t).success}function c(t){return o.safeParse(t).success}function l(t){return a.safeParse(t).success}},"../cursor-sdk-shared/dist/tool-call-types.js"(t,r,e){e.d(r,{C6:()=>vt});var n=e("zod/v3");const s=n.object({message:n.string()});function i(t,r=s){return n.discriminatedUnion("status",[n.object({status:n.literal("success"),value:t}),n.object({status:n.literal("error"),error:r})])}const o=n.object({command:n.string(),workingDirectory:n.string().optional(),timeout:n.number().optional()}),a=i(n.object({exitCode:n.number(),signal:n.string(),stdout:n.string(),stderr:n.string(),executionTime:n.number()})),u=n.object({type:n.literal("shell"),args:o,result:a.optional()}),c=n.object({path:n.string(),fileText:n.string(),returnFileContentAfterWrite:n.boolean().optional()}),l=i(n.object({path:n.string(),linesCreated:n.number(),fileSize:n.number(),fileContentAfterWrite:n.string().optional()})),m=n.object({type:n.literal("write"),args:c,result:l.optional()}),f=n.object({path:n.string()}),d=i(n.object({fileSize:n.number()})),p=n.object({type:n.literal("delete"),args:f,result:d.optional()}),h=n.object({targetDirectory:n.string().optional(),globPattern:n.string()}),g=i(n.object({files:n.array(n.string()),totalFiles:n.number(),clientTruncated:n.boolean(),ripgrepTruncated:n.boolean()})),_=n.object({type:n.literal("glob"),args:h,result:g.optional()}),J=n.object({pattern:n.string(),path:n.string().optional(),glob:n.string().optional(),outputMode:n.string().optional(),contextBefore:n.number().optional(),contextAfter:n.number().optional(),context:n.number().optional(),caseInsensitive:n.boolean().optional(),type:n.string().optional(),headLimit:n.number().optional(),offset:n.number().optional(),multiline:n.boolean().optional(),sort:n.string().optional(),sortAscending:n.boolean().optional()}),w=n.object({file:n.string(),lineNumber:n.number().optional(),line:n.string(),beforeContext:n.array(n.string()).optional(),afterContext:n.array(n.string()).optional()}),y=n.object({file:n.string(),count:n.number()}),S=n.object({matches:n.array(w),totalMatches:n.number()}),q=n.object({files:n.array(n.string()),count:n.number()}),B=n.object({counts:n.array(y),total:n.number()}),I=n.discriminatedUnion("type",[n.object({type:n.literal("content"),output:S}),n.object({type:n.literal("files"),output:q}),n.object({type:n.literal("count"),output:B})]),P=i(n.object({workspaceResults:n.record(n.string(),I).optional(),activeEditorResult:I.optional()})),b=n.object({type:n.literal("grep"),args:J,result:P.optional()}),R=n.object({path:n.string()}),v=i(n.object({content:n.string(),totalLines:n.number(),fileSize:n.number()})),x=n.object({type:n.literal("read"),args:R,result:v.optional()}),k=(n.object({oldText:n.string(),newText:n.string()}),n.object({oldText:n.string(),newText:n.string(),replaceAll:n.boolean().optional()})),E=(n.object({edits:n.array(k)}),n.object({patchContent:n.string()}),n.object({}),n.object({path:n.string()})),C=i(n.object({linesAdded:n.number().optional(),linesRemoved:n.number().optional(),diffString:n.string().optional()})),T=n.object({type:n.literal("edit"),args:E,result:C.optional()}),U=n.object({path:n.string(),ignore:n.array(n.string()).optional()}),A=n.object({name:n.string()}),$=n.lazy((()=>n.object({absPath:n.string(),childrenDirs:n.array($),childrenFiles:n.array(A),childrenWereProcessed:n.boolean(),fullSubtreeExtensionCounts:n.record(n.string(),n.number()),numFiles:n.number()}))),M=i(n.object({directoryTreeRoot:$})),O=n.object({type:n.literal("ls"),args:U,result:M.optional()}),D=n.enum(["error","warning","information","hint"]),N=n.object({line:n.number().optional(),character:n.number().optional()}),G=n.object({start:N.optional(),end:N.optional()}),L=n.object({severity:D,range:G.optional(),message:n.string(),source:n.string(),code:n.string()}),F=n.object({path:n.string(),diagnostics:n.array(L),diagnosticsCount:n.number()}),K=n.object({paths:n.array(n.string())}),z=i(n.object({fileDiagnostics:n.array(F),totalFiles:n.number(),totalDiagnostics:n.number()})),j=n.object({type:n.literal("readLints"),args:K,result:z.optional()}),H=n.object({args:n.record(n.string(),n.unknown()).optional(),providerIdentifier:n.string().optional(),toolName:n.string().optional()}),W=n.object({text:n.object({text:n.string()}).optional(),image:n.object({data:n.string(),mimeType:n.string().optional()}).optional()}),Q=i(n.object({content:n.array(W),isError:n.boolean()})),V=n.object({type:n.literal("mcp"),args:H,result:Q.optional()}),X=n.object({query:n.string(),targetDirectories:n.array(n.string()).optional(),explanation:n.string().optional()}),Y=i(n.object({results:n.string()})),Z=n.object({type:n.literal("semSearch"),args:X,result:Y.optional()}),tt=n.object({description:n.string(),filePath:n.string().optional()}),rt=i(n.object({filePath:n.string(),imageData:n.string()}),n.object({error:n.string()})),et=n.object({type:n.literal("generateImage"),args:tt,result:rt.optional()}),nt=n.object({plan:n.string()}),st=i(n.object({})),it=n.object({type:n.literal("createPlan"),args:nt,result:st.optional()}),ot=n.object({mode:n.enum(["START_RECORDING","SAVE_RECORDING","DISCARD_RECORDING"])}),at=i(n.object({wasPriorRecordingCancelled:n.boolean().optional(),path:n.string().optional(),recordingDurationMs:n.number().optional()})),ut=n.object({type:n.literal("recordScreen"),args:ot,result:at.optional()}),ct=n.object({x:n.number(),y:n.number()}),lt=n.enum(["unspecified","left","right","middle","back","forward"]),mt=n.enum(["unspecified","up","down","left","right"]),ft=n.enum(["unspecified","tap","down","up"]),dt=n.discriminatedUnion("type",[n.object({type:n.literal("mouseMove"),coordinate:ct.optional()}),n.object({type:n.literal("click"),coordinate:ct.optional(),button:lt,count:n.number(),modifierKeys:n.string().optional()}),n.object({type:n.literal("mouseDown"),button:lt}),n.object({type:n.literal("mouseUp"),button:lt}),n.object({type:n.literal("drag"),path:n.array(ct),button:lt,modifierKeys:n.string().optional()}),n.object({type:n.literal("scroll"),coordinate:ct.optional(),direction:mt,amount:n.number(),modifierKeys:n.string().optional()}),n.object({type:n.literal("type"),text:n.string()}),n.object({type:n.literal("key"),key:n.string(),holdDurationMs:n.number().optional(),stroke:ft}),n.object({type:n.literal("wait"),durationMs:n.number()}),n.object({type:n.literal("screenshot")}),n.object({type:n.literal("cursorPosition")})]),pt=n.object({actions:n.array(dt),description:n.string().optional()}),ht=i(n.object({actionCount:n.number(),durationMs:n.number(),settleMs:n.number().optional(),screenshotPath:n.string().optional(),cursorPosition:ct.optional(),log:n.string().optional()}),n.object({message:n.string(),actionCount:n.number(),durationMs:n.number(),screenshotPath:n.string().optional(),log:n.string().optional()})),gt=n.object({type:n.literal("computerUse"),args:pt,result:ht.optional()}),_t=n.enum(["pending","inProgress","completed","cancelled"]),Jt=n.object({content:n.string(),status:_t}),wt=n.object({todos:n.array(Jt)}),yt=i(n.object({todos:n.array(Jt),totalCount:n.number()})),St=n.object({type:n.literal("updateTodos"),args:wt,result:yt.optional()}),qt=n.object({kind:n.string(),name:n.string().optional()}),Bt=n.enum(["unspecified","agent","plan"]),It=n.object({description:n.string(),prompt:n.string(),subagentType:qt.optional(),model:n.string().optional(),resume:n.string().optional(),agentId:n.string().optional(),attachments:n.array(n.string()).optional(),mode:Bt.optional(),respondingToMessageIds:n.array(n.string()).optional()}),Pt=n.enum(["unspecified","agentRequest","userRequest","queuedFollowUp"]),bt=i(n.object({conversationSteps:n.array(n.unknown()).optional(),agentId:n.string().optional(),isBackground:n.boolean(),durationMs:n.number().optional(),resultSuffix:n.string().optional(),backgroundReason:Pt,transcriptPath:n.string().optional()})),Rt=n.object({type:n.literal("task"),args:It,result:bt.optional()}),vt=n.discriminatedUnion("type",[u,m,p,_,b,x,T,O,j,V,et,ut,gt,Z,it,St,Rt])},"../metrics/dist/index.js"(t,r,e){e.d(r,{Pu:()=>o,v5:()=>u,wt:()=>a});const n=(0,e("../context/dist/core.js").cF)(Symbol("metricsBackend"),{record:()=>{},increment:()=>{},gauge:()=>{},histogram:()=>{}});function s(t){return t.get(n)}function i(t){t instanceof Promise&&t.catch((()=>{}))}function o(t,r){const e={name:t,type:"counter",description:r?.description,labelNames:r?.labelNames};return{increment:(t,r,n)=>{i(s(t).increment(t,e,r??1,n))},record:(t,r,n)=>{i(s(t).record(t,e,r,n))}}}function a(t,r){const e={name:t,type:"gauge",description:r?.description,labelNames:r?.labelNames};return{gauge:(t,r,n)=>{i(s(t).gauge(t,e,r,n))},record:(t,r,n)=>{i(s(t).record(t,e,r,n))}}}function u(t,r){const e={name:t,type:"histogram",description:r?.description,labelNames:r?.labelNames};return{histogram:(t,r,n)=>{i(s(t).histogram(t,e,r,n))},record:(t,r,n)=>{i(s(t).record(t,e,r,n))}}}},"../proto/dist/generated/agent/v1/agent_pb.js"(t,r,e){e.d(r,{PSN:()=>Yu,i9c:()=>Ha,xyI:()=>Ki,Mpn:()=>xu,zT:()=>pc,KFq:()=>$o,Kwc:()=>Ao,aZc:()=>zi,uHL:()=>ji,TTG:()=>Sa,Ibo:()=>Pu,QFf:()=>To,ljj:()=>mu,Y9z:()=>Ju,kJk:()=>Co,KRq:()=>Ya,Anz:()=>Za,j97:()=>La,cmU:()=>ja,o7L:()=>_a,QVp:()=>ju,nnk:()=>no,apn:()=>rc,Mzv:()=>ou,ih1:()=>Lu,hGJ:()=>aa,Pd7:()=>mc,Y5:()=>fc,nh0:()=>va,Uq:()=>ac,D$r:()=>$a,c2D:()=>Xu,Gmx:()=>bu,fxF:()=>Au,onr:()=>vu,d2k:()=>su,HXb:()=>Zi,qKo:()=>qa,oIR:()=>Na,tms:()=>Va,qKL:()=>Ga,Nn_:()=>Ku,c_h:()=>Xi,Lrv:()=>Vu,dwJ:()=>Wu,Bjv:()=>Ru,aK_:()=>pu,gan:()=>xa,vns:()=>Yi,Scs:()=>Ia,ZM9:()=>Fu,lWT:()=>Gu,ECk:()=>Nu,aon:()=>wo,PtE:()=>ku,tr3:()=>Mu,cHB:()=>$u,Y$k:()=>Ou,Fyz:()=>Du,Dm_:()=>Po,LLS:()=>Tu,V1v:()=>Eo,I0n:()=>Uu,xuG:()=>Cu,BU$:()=>Qu,iHX:()=>Uo,lJj:()=>zu,oW$:()=>ua,RGk:()=>Ua,Vtf:()=>sa,v$T:()=>Hu});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/agent/v1/subagents_pb.js"),i=e("../proto/dist/generated/agent/v1/shell_exec_pb.js"),o=e("../proto/dist/runtime/compact.js");class a extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class u extends a{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["ShellToolCall|1 args #0|2 result #1|3 description 9?",i.a,i.W4]}}class c extends a{constructor(t){super(),this.content="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["ShellToolCallStdoutDelta|1 content 9"]}}class l extends a{constructor(t){super(),this.content="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["ShellToolCallStderrDelta|1 content 9"]}}class m extends a{constructor(t){super(),this.delta={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["ShellToolCallDelta|1 stdout #0 delta|2 stderr #1 delta",c,l]}}var f=e("../proto/dist/generated/agent/v1/delete_exec_pb.js");class d extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class p extends d{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["DeleteToolCall|1 args #0|2 result #1",f.dn,f.Pi]}}class h extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class g extends h{constructor(t){super(),this.globPattern="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["GlobToolArgs|1 target_directory 9?|2 glob_pattern 9"]}}class _ extends h{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _).fromBinary(t,r)}static fromJson(t,r){return(new _).fromJson(t,r)}static fromJsonString(t,r){return(new _).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_,t,r)}static $(){return["GlobToolResult|1 success #0 result|2 error #1 result",w,J]}}class J extends h{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new J).fromBinary(t,r)}static fromJson(t,r){return(new J).fromJson(t,r)}static fromJsonString(t,r){return(new J).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(J,t,r)}static $(){return["GlobToolError|1 error 9"]}}class w extends h{constructor(t){super(),this.pattern="",this.path="",this.files=[],this.totalFiles=0,this.clientTruncated=!1,this.ripgrepTruncated=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new w).fromBinary(t,r)}static fromJson(t,r){return(new w).fromJson(t,r)}static fromJsonString(t,r){return(new w).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(w,t,r)}static $(){return["GlobToolSuccess|1 pattern 9|2 path 9|3 files 9*|4 total_files 5|5 client_truncated 8|6 ripgrep_truncated 8"]}}class y extends h{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new y).fromBinary(t,r)}static fromJson(t,r){return(new y).fromJson(t,r)}static fromJsonString(t,r){return(new y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(y,t,r)}static $(){return["GlobToolCall|1 args #0|2 result #1",g,_]}}var S=e("../proto/dist/generated/agent/v1/grep_exec_pb.js");class q extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class B extends q{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new B).fromBinary(t,r)}static fromJson(t,r){return(new B).fromJson(t,r)}static fromJsonString(t,r){return(new B).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(B,t,r)}static $(){return["GrepToolCall|1 args #0|2 result #1",S.Qj,S.Ud]}}var I=e("../proto/dist/generated/agent/v1/cursor_rules_pb.js");class P extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class b extends P{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new b).fromBinary(t,r)}static fromJson(t,r){return(new b).fromJson(t,r)}static fromJsonString(t,r){return(new b).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(b,t,r)}static $(){return["ReadToolCall|1 args #0|2 result #1",R,v]}}class R extends P{constructor(t){super(),this.path="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new R).fromBinary(t,r)}static fromJson(t,r){return(new R).fromJson(t,r)}static fromJsonString(t,r){return(new R).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(R,t,r)}static $(){return["ReadToolArgs|1 path 9|2 offset 5?|3 limit 5?|5 include_line_numbers 8?"]}}class v extends P{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new v).fromBinary(t,r)}static fromJson(t,r){return(new v).fromJson(t,r)}static fromJsonString(t,r){return(new v).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(v,t,r)}static $(){return["ReadToolResult|1 success #0 result|2 error #1 result",k,E]}}class x extends P{constructor(t){super(),this.startLine=0,this.endLine=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new x).fromBinary(t,r)}static fromJson(t,r){return(new x).fromJson(t,r)}static fromJsonString(t,r){return(new x).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(x,t,r)}static $(){return["ReadRange|1 start_line 13|2 end_line 13"]}}class k extends P{constructor(t){super(),this.output={case:void 0},this.isEmpty=!1,this.exceededLimit=!1,this.totalLines=0,this.fileSize=0,this.path="",this.relatedCursorRulePaths=[],this.relatedCursorRules=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new k).fromBinary(t,r)}static fromJson(t,r){return(new k).fromJson(t,r)}static fromJsonString(t,r){return(new k).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(k,t,r)}static $(){return["ReadToolSuccess|1 content 9 output|6 data 12 output|9 data_blob_id 12 output|10 content_blob_id 12 output|2 is_empty 8|3 exceeded_limit 8|4 total_lines 13|5 file_size 13|7 path 9|8 read_range #0?|11 include_line_numbers 8?|12 related_cursor_rule_paths 9*|13 related_cursor_rules #1*",x,I.DX]}}class E extends P{constructor(t){super(),this.errorMessage="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new E).fromBinary(t,r)}static fromJson(t,r){return(new E).fromJson(t,r)}static fromJsonString(t,r){return(new E).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(E,t,r)}static $(){return["ReadToolError|1 error_message 9"]}}var C=e("../proto/dist/generated/agent/v1/todo_tool_pb.js");class T extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class U extends T{constructor(t){super(),this.path="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new U).fromBinary(t,r)}static fromJson(t,r){return(new U).fromJson(t,r)}static fromJsonString(t,r){return(new U).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(U,t,r)}static $(){return["EditArgs|1 path 9|6 stream_content 9?"]}}class A extends T{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new A).fromBinary(t,r)}static fromJson(t,r){return(new A).fromJson(t,r)}static fromJsonString(t,r){return(new A).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(A,t,r)}static $(){return["EditResult|1 success #0 result|2 file_not_found #1 result|3 read_permission_denied #2 result|4 write_permission_denied #3 result|6 rejected #4 result|7 error #5 result",$,M,O,D,N,G]}}class $ extends T{constructor(t){super(),this.path="",this.afterFullFileContent="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $).fromBinary(t,r)}static fromJson(t,r){return(new $).fromJson(t,r)}static fromJsonString(t,r){return(new $).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($,t,r)}static $(){return["EditSuccess|1 path 9|3 lines_added 5?|4 lines_removed 5?|5 diff_string 9?|6 before_full_file_content 9?|7 after_full_file_content 9|8 message 9?"]}}class M extends T{constructor(t){super(),this.path="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new M).fromBinary(t,r)}static fromJson(t,r){return(new M).fromJson(t,r)}static fromJsonString(t,r){return(new M).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(M,t,r)}static $(){return["EditFileNotFound|1 path 9"]}}class O extends T{constructor(t){super(),this.path="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new O).fromBinary(t,r)}static fromJson(t,r){return(new O).fromJson(t,r)}static fromJsonString(t,r){return(new O).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(O,t,r)}static $(){return["EditReadPermissionDenied|1 path 9"]}}class D extends T{constructor(t){super(),this.path="",this.error="",this.isReadonly=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new D).fromBinary(t,r)}static fromJson(t,r){return(new D).fromJson(t,r)}static fromJsonString(t,r){return(new D).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(D,t,r)}static $(){return["EditWritePermissionDenied|1 path 9|2 error 9|3 is_readonly 8"]}}class N extends T{constructor(t){super(),this.path="",this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new N).fromBinary(t,r)}static fromJson(t,r){return(new N).fromJson(t,r)}static fromJsonString(t,r){return(new N).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(N,t,r)}static $(){return["EditRejected|1 path 9|2 reason 9"]}}class G extends T{constructor(t){super(),this.path="",this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new G).fromBinary(t,r)}static fromJson(t,r){return(new G).fromJson(t,r)}static fromJsonString(t,r){return(new G).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(G,t,r)}static $(){return["EditError|1 path 9|2 error 9|5 model_visible_error 9?"]}}class L extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new L).fromBinary(t,r)}static fromJson(t,r){return(new L).fromJson(t,r)}static fromJsonString(t,r){return(new L).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(L,t,r)}static $(){return["EditToolCall|1 args #0|2 result #1",U,A]}}class F extends T{constructor(t){super(),this.streamContentDelta="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new F).fromBinary(t,r)}static fromJson(t,r){return(new F).fromJson(t,r)}static fromJsonString(t,r){return(new F).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(F,t,r)}static $(){return["EditToolCallDelta|1 stream_content_delta 9"]}}var K=e("../proto/dist/generated/agent/v1/ls_exec_pb.js");class z extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class j extends z{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new j).fromBinary(t,r)}static fromJson(t,r){return(new j).fromJson(t,r)}static fromJsonString(t,r){return(new j).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(j,t,r)}static $(){return["LsToolCall|1 args #0|2 result #1",K.xe,K.fv]}}var H=e("../proto/dist/generated/agent/v1/diagnostics_exec_pb.js"),W=e("../proto/dist/generated/agent/v1/utils_pb.js");class Q extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class V extends Q{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new V).fromBinary(t,r)}static fromJson(t,r){return(new V).fromJson(t,r)}static fromJsonString(t,r){return(new V).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(V,t,r)}static $(){return["ReadLintsToolCall|1 args #0|2 result #1",X,Y]}}class X extends Q{constructor(t){super(),this.paths=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new X).fromBinary(t,r)}static fromJson(t,r){return(new X).fromJson(t,r)}static fromJsonString(t,r){return(new X).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(X,t,r)}static $(){return["ReadLintsToolArgs|1 paths 9*"]}}class Y extends Q{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Y).fromBinary(t,r)}static fromJson(t,r){return(new Y).fromJson(t,r)}static fromJsonString(t,r){return(new Y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Y,t,r)}static $(){return["ReadLintsToolResult|1 success #0 result|2 error #1 result",Z,nt]}}class Z extends Q{constructor(t){super(),this.fileDiagnostics=[],this.totalFiles=0,this.totalDiagnostics=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Z).fromBinary(t,r)}static fromJson(t,r){return(new Z).fromJson(t,r)}static fromJsonString(t,r){return(new Z).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Z,t,r)}static $(){return["ReadLintsToolSuccess|1 file_diagnostics #0*|2 total_files 5|3 total_diagnostics 5",tt]}}class tt extends Q{constructor(t){super(),this.path="",this.diagnostics=[],this.diagnosticsCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tt).fromBinary(t,r)}static fromJson(t,r){return(new tt).fromJson(t,r)}static fromJsonString(t,r){return(new tt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tt,t,r)}static $(){return["FileDiagnostics|1 path 9|2 diagnostics #0*|3 diagnostics_count 5",rt]}}class rt extends Q{constructor(t){super(),this.severity=H.h_.UNSPECIFIED,this.message="",this.source="",this.code="",this.isStale=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rt).fromBinary(t,r)}static fromJson(t,r){return(new rt).fromJson(t,r)}static fromJsonString(t,r){return(new rt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rt,t,r)}static $(){return["DiagnosticItem|1 severity #0|2 range #1|3 message 9|4 source 9|5 code 9|6 is_stale 8",H.h_,et]}}class et extends Q{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new et).fromBinary(t,r)}static fromJson(t,r){return(new et).fromJson(t,r)}static fromJsonString(t,r){return(new et).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(et,t,r)}static $(){return["DiagnosticRange|1 start #0|2 end #0",W.yX]}}class nt extends Q{constructor(t){super(),this.errorMessage="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nt).fromBinary(t,r)}static fromJson(t,r){return(new nt).fromJson(t,r)}static fromJsonString(t,r){return(new nt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nt,t,r)}static $(){return["ReadLintsToolError|1 error_message 9"]}}var st=e("../proto/dist/generated/agent/v1/mcp_exec_pb.js");class it extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class ot extends it{constructor(t){super(),this.error="",this.readToolDefReminder="",this.systemReminders=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ot).fromBinary(t,r)}static fromJson(t,r){return(new ot).fromJson(t,r)}static fromJsonString(t,r){return(new ot).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ot,t,r)}static $(){return["McpToolError|1 error 9|2 read_tool_def_reminder 9|3 system_reminders #0*",st.Kp]}}class at extends it{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new at).fromBinary(t,r)}static fromJson(t,r){return(new at).fromJson(t,r)}static fromJsonString(t,r){return(new at).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(at,t,r)}static $(){return["McpToolResult|1 success #0 result|2 error #1 result|3 rejected #2 result|4 permission_denied #3 result",st.QW,ot,st.xo,st.HQ]}}class ut extends it{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ut).fromBinary(t,r)}static fromJson(t,r){return(new ut).fromJson(t,r)}static fromJsonString(t,r){return(new ut).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ut,t,r)}static $(){return["McpToolCall|1 args #0|2 result #1|3 description 9?",st.E_,at]}}var ct=e("../proto/dist/generated/aiserver/v1/repository_pb.js");class lt extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class mt extends lt{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mt).fromBinary(t,r)}static fromJson(t,r){return(new mt).fromJson(t,r)}static fromJsonString(t,r){return(new mt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mt,t,r)}static $(){return["SemSearchToolCall|1 args #0|2 result #1",ft,dt]}}class ft extends lt{constructor(t){super(),this.query="",this.targetDirectories=[],this.explanation="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ft).fromBinary(t,r)}static fromJson(t,r){return(new ft).fromJson(t,r)}static fromJsonString(t,r){return(new ft).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ft,t,r)}static $(){return["SemSearchToolArgs|1 query 9|2 target_directories 9*|3 explanation 9"]}}class dt extends lt{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dt).fromBinary(t,r)}static fromJson(t,r){return(new dt).fromJson(t,r)}static fromJsonString(t,r){return(new dt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dt,t,r)}static $(){return["SemSearchToolResult|1 success #0 result|2 error #1 result",pt,ht]}}class pt extends lt{constructor(t){super(),this.results="",this.codeResults=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pt).fromBinary(t,r)}static fromJson(t,r){return(new pt).fromJson(t,r)}static fromJsonString(t,r){return(new pt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pt,t,r)}static $(){return["SemSearchToolSuccess|1 results 9|2 code_results #0*",ct.PT]}}class ht extends lt{constructor(t){super(),this.errorMessage="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ht).fromBinary(t,r)}static fromJson(t,r){return(new ht).fromJson(t,r)}static fromJsonString(t,r){return(new ht).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ht,t,r)}static $(){return["SemSearchToolError|1 error_message 9"]}}var gt=e("../proto/dist/generated/agent/v1/create_plan_tool_pb.js"),_t=e("../proto/dist/generated/agent/v1/web_search_tool_pb.js");class Jt extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class wt extends Jt{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wt).fromBinary(t,r)}static fromJson(t,r){return(new wt).fromJson(t,r)}static fromJsonString(t,r){return(new wt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wt,t,r)}static $(){return["ListMcpResourcesToolCall|1 args #0|2 result #1",st.kj,st.kP]}}class yt extends Jt{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yt).fromBinary(t,r)}static fromJson(t,r){return(new yt).fromJson(t,r)}static fromJsonString(t,r){return(new yt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yt,t,r)}static $(){return["ReadMcpResourceToolCall|1 args #0|2 result #1",st.DI,st.ZD]}}var St=e("../proto/dist/generated/agent/v1/apply_agent_diff_tool_pb.js"),qt=e("../proto/dist/generated/agent/v1/ask_question_tool_pb.js"),Bt=e("../proto/dist/generated/agent/v1/fetch_exec_pb.js");class It extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class Pt extends It{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pt).fromBinary(t,r)}static fromJson(t,r){return(new Pt).fromJson(t,r)}static fromJsonString(t,r){return(new Pt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pt,t,r)}static $(){return["FetchToolCall|1 args #0|2 result #1",Bt.UM,Bt.uN]}}var bt=e("../proto/dist/generated/agent/v1/switch_mode_tool_pb.js"),Rt=e("../proto/dist/generated/agent/v1/generate_image_tool_pb.js"),vt=e("../proto/dist/generated/agent/v1/record_screen_exec_pb.js");class xt extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class kt extends xt{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kt).fromBinary(t,r)}static fromJson(t,r){return(new kt).fromJson(t,r)}static fromJsonString(t,r){return(new kt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kt,t,r)}static $(){return["RecordScreenToolCall|1 args #0|2 result #1",vt.zH,vt.Tj]}}var Et=e("../proto/dist/generated/agent/v1/computer_use_tool_pb.js"),Ct=e("../proto/dist/generated/agent/v1/background_shell_exec_pb.js");class Tt extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class Ut extends Tt{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ut).fromBinary(t,r)}static fromJson(t,r){return(new Ut).fromJson(t,r)}static fromJsonString(t,r){return(new Ut).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ut,t,r)}static $(){return["WriteShellStdinToolCall|1 args #0|2 result #1",Ct.LL,Ct.nt]}}class At extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class $t extends At{constructor(t){super(),this.unexpectedActionOutcomes="",this.relevantInstructions="",this.scenarioAnalysis="",this.criticalSynthesis="",this.nextSteps="",this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $t).fromBinary(t,r)}static fromJson(t,r){return(new $t).fromJson(t,r)}static fromJsonString(t,r){return(new $t).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($t,t,r)}static $(){return["ReflectArgs|1 unexpected_action_outcomes 9|2 relevant_instructions 9|3 scenario_analysis 9|4 critical_synthesis 9|5 next_steps 9|6 tool_call_id 9"]}}class Mt extends At{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mt).fromBinary(t,r)}static fromJson(t,r){return(new Mt).fromJson(t,r)}static fromJsonString(t,r){return(new Mt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mt,t,r)}static $(){return["ReflectResult|1 success #0 result|2 error #1 result",Ot,Dt]}}class Ot extends At{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ot).fromBinary(t,r)}static fromJson(t,r){return(new Ot).fromJson(t,r)}static fromJsonString(t,r){return(new Ot).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ot,t,r)}static $(){return["ReflectSuccess"]}}class Dt extends At{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dt).fromBinary(t,r)}static fromJson(t,r){return(new Dt).fromJson(t,r)}static fromJsonString(t,r){return(new Dt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dt,t,r)}static $(){return["ReflectError|1 error 9"]}}class Nt extends At{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nt).fromBinary(t,r)}static fromJson(t,r){return(new Nt).fromJson(t,r)}static fromJsonString(t,r){return(new Nt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nt,t,r)}static $(){return["ReflectToolCall|1 args #0|2 result #1",$t,Mt]}}var Gt=e("../proto/dist/generated/agent/v1/setup_vm_environment_tool_pb.js");class Lt extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class Ft extends Lt{constructor(t){super(),this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ft).fromBinary(t,r)}static fromJson(t,r){return(new Ft).fromJson(t,r)}static fromJsonString(t,r){return(new Ft).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ft,t,r)}static $(){return["StartGrindExecutionArgs|1 explanation 9?|2 tool_call_id 9"]}}class Kt extends Lt{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kt).fromBinary(t,r)}static fromJson(t,r){return(new Kt).fromJson(t,r)}static fromJsonString(t,r){return(new Kt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Kt,t,r)}static $(){return["StartGrindExecutionResult|1 success #0 result|2 error #1 result",zt,jt]}}class zt extends Lt{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zt).fromBinary(t,r)}static fromJson(t,r){return(new zt).fromJson(t,r)}static fromJsonString(t,r){return(new zt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zt,t,r)}static $(){return["StartGrindExecutionSuccess"]}}class jt extends Lt{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jt).fromBinary(t,r)}static fromJson(t,r){return(new jt).fromJson(t,r)}static fromJsonString(t,r){return(new jt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jt,t,r)}static $(){return["StartGrindExecutionError|1 error 9"]}}class Ht extends Lt{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ht).fromBinary(t,r)}static fromJson(t,r){return(new Ht).fromJson(t,r)}static fromJsonString(t,r){return(new Ht).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ht,t,r)}static $(){return["StartGrindExecutionToolCall|1 args #0|2 result #1",Ft,Kt]}}class Wt extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class Qt extends Wt{constructor(t){super(),this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qt).fromBinary(t,r)}static fromJson(t,r){return(new Qt).fromJson(t,r)}static fromJsonString(t,r){return(new Qt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qt,t,r)}static $(){return["StartGrindPlanningArgs|1 explanation 9?|2 tool_call_id 9"]}}class Vt extends Wt{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vt).fromBinary(t,r)}static fromJson(t,r){return(new Vt).fromJson(t,r)}static fromJsonString(t,r){return(new Vt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vt,t,r)}static $(){return["StartGrindPlanningResult|1 success #0 result|2 error #1 result",Xt,Yt]}}class Xt extends Wt{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xt).fromBinary(t,r)}static fromJson(t,r){return(new Xt).fromJson(t,r)}static fromJsonString(t,r){return(new Xt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xt,t,r)}static $(){return["StartGrindPlanningSuccess"]}}class Yt extends Wt{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yt).fromBinary(t,r)}static fromJson(t,r){return(new Yt).fromJson(t,r)}static fromJsonString(t,r){return(new Yt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yt,t,r)}static $(){return["StartGrindPlanningError|1 error 9"]}}class Zt extends Wt{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zt).fromBinary(t,r)}static fromJson(t,r){return(new Zt).fromJson(t,r)}static fromJsonString(t,r){return(new Zt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zt,t,r)}static $(){return["StartGrindPlanningToolCall|1 args #0|2 result #1",Qt,Vt]}}var tr=e("../proto/dist/generated/agent/v1/web_fetch_tool_pb.js"),rr=e("../proto/dist/generated/agent/v1/report_bugfix_results_tool_pb.js"),er=e("../proto/dist/generated/agent/v1/ai_attribution_tool_pb.js"),nr=e("../proto/dist/generated/agent/v1/pr_management_tool_pb.js"),sr=e("../proto/dist/generated/agent/v1/mcp_auth_tool_pb.js");class ir extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class or extends ir{constructor(t){super(),this.taskId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new or).fromBinary(t,r)}static fromJson(t,r){return(new or).fromJson(t,r)}static fromJsonString(t,r){return(new or).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(or,t,r)}static $(){return["AwaitArgs|1 task_id 9|2 block_until_ms 13?|3 regex 9?"]}}class ar extends ir{constructor(t){super(),this.taskId="",this.runtimeMs=n.protoInt64.zero,this.outputFilePath="",this.outputLength=n.protoInt64.zero,this.regexRequested=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ar).fromBinary(t,r)}static fromJson(t,r){return(new ar).fromJson(t,r)}static fromJsonString(t,r){return(new ar).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ar,t,r)}static $(){return["AwaitTaskComplete|1 task_id 9|2 runtime_ms 4|3 output_file_path 9|4 output_length 4|5 regex_requested 8|6 regex_match 9?|7 exit_code 17?|8 wake_reason 9?"]}}class ur extends ir{constructor(t){super(),this.taskId="",this.runtimeMs=n.protoInt64.zero,this.outputFilePath="",this.outputLength=n.protoInt64.zero,this.regexRequested=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ur).fromBinary(t,r)}static fromJson(t,r){return(new ur).fromJson(t,r)}static fromJsonString(t,r){return(new ur).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ur,t,r)}static $(){return["AwaitTaskStillRunning|1 task_id 9|2 runtime_ms 4|3 output_file_path 9|4 output_length 4|5 regex_requested 8|6 regex_match 9?|7 wake_reason 9?"]}}class cr extends ir{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cr).fromBinary(t,r)}static fromJson(t,r){return(new cr).fromJson(t,r)}static fromJsonString(t,r){return(new cr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cr,t,r)}static $(){return["AwaitError|1 error 9"]}}class lr extends ir{constructor(t){super(),this.awaitResult={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lr).fromBinary(t,r)}static fromJson(t,r){return(new lr).fromJson(t,r)}static fromJsonString(t,r){return(new lr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lr,t,r)}static $(){return["AwaitSuccess|1 complete #0 await_result|2 still_running #1 await_result",ar,ur]}}class mr extends ir{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mr).fromBinary(t,r)}static fromJson(t,r){return(new mr).fromJson(t,r)}static fromJsonString(t,r){return(new mr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mr,t,r)}static $(){return["AwaitResult|1 complete #0 result|2 still_running #1 result|3 error #2 result|4 success #3 result",ar,ur,cr,lr]}}class fr extends ir{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fr).fromBinary(t,r)}static fromJson(t,r){return(new fr).fromJson(t,r)}static fromJsonString(t,r){return(new fr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fr,t,r)}static $(){return["AwaitToolCall|1 args #0|2 result #1",or,mr]}}class dr extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class pr extends dr{constructor(t){super(),this.filePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pr).fromBinary(t,r)}static fromJson(t,r){return(new pr).fromJson(t,r)}static fromJsonString(t,r){return(new pr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pr,t,r)}static $(){return["BlameByFilePathArgs|1 file_path 9|2 start_line 5?|3 end_line 5?"]}}class hr extends dr{constructor(t){super(),this.content="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hr).fromBinary(t,r)}static fromJson(t,r){return(new hr).fromJson(t,r)}static fromJsonString(t,r){return(new hr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hr,t,r)}static $(){return["BlameByFilePathSuccess|1 content 9"]}}class gr extends dr{constructor(t){super(),this.errorMessage="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gr).fromBinary(t,r)}static fromJson(t,r){return(new gr).fromJson(t,r)}static fromJsonString(t,r){return(new gr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gr,t,r)}static $(){return["BlameByFilePathError|1 error_message 9"]}}class _r extends dr{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _r).fromBinary(t,r)}static fromJson(t,r){return(new _r).fromJson(t,r)}static fromJsonString(t,r){return(new _r).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_r,t,r)}static $(){return["BlameByFilePathResult|1 success #0 result|2 error #1 result",hr,gr]}}class Jr extends dr{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jr).fromBinary(t,r)}static fromJson(t,r){return(new Jr).fromJson(t,r)}static fromJsonString(t,r){return(new Jr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jr,t,r)}static $(){return["BlameByFilePathToolCall|1 args #0|2 result #1",pr,_r]}}class wr extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class yr extends wr{constructor(t){super(),this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yr).fromBinary(t,r)}static fromJson(t,r){return(new yr).fromJson(t,r)}static fromJsonString(t,r){return(new yr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yr,t,r)}static $(){return["GetMcpToolsArgs|1 server 9?|2 tool_name 9?|3 pattern 9?|4 tool_call_id 9"]}}class Sr extends wr{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sr).fromBinary(t,r)}static fromJson(t,r){return(new Sr).fromJson(t,r)}static fromJsonString(t,r){return(new Sr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sr,t,r)}static $(){return["GetMcpToolsAgentResult|1 success #0 result|2 error #1 result",qr,Br]}}class qr extends wr{constructor(t){super(),this.content="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qr).fromBinary(t,r)}static fromJson(t,r){return(new qr).fromJson(t,r)}static fromJsonString(t,r){return(new qr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qr,t,r)}static $(){return["GetMcpToolsSuccess|1 content 9|2 output_file_path 9?"]}}class Br extends wr{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Br).fromBinary(t,r)}static fromJson(t,r){return(new Br).fromJson(t,r)}static fromJsonString(t,r){return(new Br).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Br,t,r)}static $(){return["GetMcpToolsError|1 error 9"]}}class Ir extends wr{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ir).fromBinary(t,r)}static fromJson(t,r){return(new Ir).fromJson(t,r)}static fromJsonString(t,r){return(new Ir).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ir,t,r)}static $(){return["GetMcpToolsToolCall|1 args #0|2 result #1",yr,Sr]}}class Pr extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class br extends Pr{constructor(t){super(),this.title="",this.file="",this.startLine=0,this.endLine=0,this.description="",this.severity="",this.category="",this.rationale="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new br).fromBinary(t,r)}static fromJson(t,r){return(new br).fromJson(t,r)}static fromJsonString(t,r){return(new br).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(br,t,r)}static $(){return["ReportBugArgs|1 title 9|2 file 9|3 start_line 5|4 end_line 5|5 description 9|6 severity 9|7 category 9|8 rationale 9"]}}class Rr extends Pr{constructor(t){super(),this.output="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rr).fromBinary(t,r)}static fromJson(t,r){return(new Rr).fromJson(t,r)}static fromJsonString(t,r){return(new Rr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rr,t,r)}static $(){return["ReportBugSuccess|1 output 9"]}}class vr extends Pr{constructor(t){super(),this.errorMessage="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vr).fromBinary(t,r)}static fromJson(t,r){return(new vr).fromJson(t,r)}static fromJsonString(t,r){return(new vr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vr,t,r)}static $(){return["ReportBugError|1 error_message 9"]}}class xr extends Pr{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xr).fromBinary(t,r)}static fromJson(t,r){return(new xr).fromJson(t,r)}static fromJsonString(t,r){return(new xr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xr,t,r)}static $(){return["ReportBugResult|1 success #0 result|2 error #1 result",Rr,vr]}}class kr extends Pr{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kr).fromBinary(t,r)}static fromJson(t,r){return(new kr).fromJson(t,r)}static fromJsonString(t,r){return(new kr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kr,t,r)}static $(){return["ReportBugToolCall|1 args #0|2 result #1",br,xr]}}class Er extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class Cr extends Er{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cr).fromBinary(t,r)}static fromJson(t,r){return(new Cr).fromJson(t,r)}static fromJsonString(t,r){return(new Cr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cr,t,r)}static $(){return["CommunicateUpdateArgs|1 current_step 9?|3 final_summary 9?|4 completed_subtitle 9?"]}}class Tr extends Er{constructor(t){super(),this.currentStep="",this.messageIndex=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tr).fromBinary(t,r)}static fromJson(t,r){return(new Tr).fromJson(t,r)}static fromJsonString(t,r){return(new Tr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tr,t,r)}static $(){return["CommunicateUpdateSuccess|1 current_step 9|3 message_index 13"]}}class Ur extends Er{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ur).fromBinary(t,r)}static fromJson(t,r){return(new Ur).fromJson(t,r)}static fromJsonString(t,r){return(new Ur).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ur,t,r)}static $(){return["CommunicateUpdateError|1 error 9"]}}class Ar extends Er{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ar).fromBinary(t,r)}static fromJson(t,r){return(new Ar).fromJson(t,r)}static fromJsonString(t,r){return(new Ar).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ar,t,r)}static $(){return["CommunicateUpdateResult|1 success #0 result|2 error #1 result",Tr,Ur]}}class $r extends Er{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $r).fromBinary(t,r)}static fromJson(t,r){return(new $r).fromJson(t,r)}static fromJsonString(t,r){return(new $r).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($r,t,r)}static $(){return["CommunicateUpdateToolCall|1 args #0|2 result #1",Cr,Ar]}}class Mr extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class Or extends Mr{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Or).fromBinary(t,r)}static fromJson(t,r){return(new Or).fromJson(t,r)}static fromJsonString(t,r){return(new Or).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Or,t,r)}static $(){return["SendFinalSummaryArgs|1 final_summary 9?"]}}class Dr extends Mr{constructor(t){super(),this.finalSummary="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dr).fromBinary(t,r)}static fromJson(t,r){return(new Dr).fromJson(t,r)}static fromJsonString(t,r){return(new Dr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dr,t,r)}static $(){return["SendFinalSummarySuccess|1 final_summary 9"]}}class Nr extends Mr{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nr).fromBinary(t,r)}static fromJson(t,r){return(new Nr).fromJson(t,r)}static fromJsonString(t,r){return(new Nr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nr,t,r)}static $(){return["SendFinalSummaryError|1 error 9"]}}class Gr extends Mr{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gr).fromBinary(t,r)}static fromJson(t,r){return(new Gr).fromJson(t,r)}static fromJsonString(t,r){return(new Gr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gr,t,r)}static $(){return["SendFinalSummaryResult|1 success #0 result|2 error #1 result",Dr,Nr]}}class Lr extends Mr{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lr).fromBinary(t,r)}static fromJson(t,r){return(new Lr).fromJson(t,r)}static fromJsonString(t,r){return(new Lr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Lr,t,r)}static $(){return["SendFinalSummaryToolCall|1 args #0|2 result #1",Or,Gr]}}var Fr=e("../proto/dist/generated/agent/v1/replace_env_tool_pb.js");class Kr extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class zr extends Kr{constructor(t){super(),this.toolCallId="",this.prUrl="",this.addLabels=[],this.removeLabels=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zr).fromBinary(t,r)}static fromJson(t,r){return(new zr).fromJson(t,r)}static fromJsonString(t,r){return(new zr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zr,t,r)}static $(){return["EditPrLabelsArgs|1 tool_call_id 9|2 pr_url 9|4 add_labels 9*|5 remove_labels 9*"]}}class jr extends Kr{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jr).fromBinary(t,r)}static fromJson(t,r){return(new jr).fromJson(t,r)}static fromJsonString(t,r){return(new jr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jr,t,r)}static $(){return["EditPrLabelsResult|1 success #0 result|2 error #1 result",Hr,Wr]}}class Hr extends Kr{constructor(t){super(),this.prUrl="",this.prNumber=0,this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hr).fromBinary(t,r)}static fromJson(t,r){return(new Hr).fromJson(t,r)}static fromJsonString(t,r){return(new Hr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hr,t,r)}static $(){return["EditPrLabelsSuccess|1 pr_url 9|2 pr_number 5|3 message 9"]}}class Wr extends Kr{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wr).fromBinary(t,r)}static fromJson(t,r){return(new Wr).fromJson(t,r)}static fromJsonString(t,r){return(new Wr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wr,t,r)}static $(){return["EditPrLabelsError|1 error 9"]}}class Qr extends Kr{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qr).fromBinary(t,r)}static fromJson(t,r){return(new Qr).fromJson(t,r)}static fromJsonString(t,r){return(new Qr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qr,t,r)}static $(){return["EditPrLabelsToolCall|1 args #0|2 result #1",zr,jr]}}class Vr extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class Xr extends Vr{constructor(t){super(),this.checkName="",this.tldr="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xr).fromBinary(t,r)}static fromJson(t,r){return(new Xr).fromJson(t,r)}static fromJsonString(t,r){return(new Xr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xr,t,r)}static $(){return["RecordCiInvestigationFinding|1 check_name 9|2 details_url 9?|3 tldr 9|4 root_cause 9?|5 failing_signal 9?|6 suggested_next_step 9?|7 diff_relation 9?|8 diff_relation_evidence 9?|9 flake_assessment 9?|10 flake_evidence 9?|11 rerun_available 8?|12 rerun_evidence 9?|13 recommended_action 9?|14 recommended_action_evidence 9?|15 confidence 9?"]}}class Yr extends Vr{constructor(t){super(),this.summary="",this.themes=[],this.checkKeys=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yr).fromBinary(t,r)}static fromJson(t,r){return(new Yr).fromJson(t,r)}static fromJsonString(t,r){return(new Yr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yr,t,r)}static $(){return["RecordCiInvestigationOverall|1 summary 9|2 themes 9*|3 recommended_action 9?|4 recommended_action_evidence 9?|5 check_keys 9*"]}}class Zr extends Vr{constructor(t){super(),this.findings=[],this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zr).fromBinary(t,r)}static fromJson(t,r){return(new Zr).fromJson(t,r)}static fromJsonString(t,r){return(new Zr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zr,t,r)}static $(){return["RecordCiInvestigationFindingsArgs|1 findings #0*|2 overall #1?|3 tool_call_id 9",Xr,Yr]}}class te extends Vr{constructor(t){super(),this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new te).fromBinary(t,r)}static fromJson(t,r){return(new te).fromJson(t,r)}static fromJsonString(t,r){return(new te).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(te,t,r)}static $(){return["RecordCiInvestigationFindingsSuccess|1 message 9"]}}class re extends Vr{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new re).fromBinary(t,r)}static fromJson(t,r){return(new re).fromJson(t,r)}static fromJsonString(t,r){return(new re).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(re,t,r)}static $(){return["RecordCiInvestigationFindingsError|1 error 9"]}}class ee extends Vr{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ee).fromBinary(t,r)}static fromJson(t,r){return(new ee).fromJson(t,r)}static fromJsonString(t,r){return(new ee).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ee,t,r)}static $(){return["RecordCiInvestigationFindingsResult|1 success #0 result|2 error #1 result",te,re]}}class ne extends Vr{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ne).fromBinary(t,r)}static fromJson(t,r){return(new ne).fromJson(t,r)}static fromJsonString(t,r){return(new ne).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ne,t,r)}static $(){return["RecordCiInvestigationFindingsToolCall|1 args #0|2 result #1",Zr,ee]}}class se extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class ie extends se{constructor(t){super(),this.content="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ie).fromBinary(t,r)}static fromJson(t,r){return(new ie).fromJson(t,r)}static fromJsonString(t,r){return(new ie).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ie,t,r)}static $(){return["SendMessageText|1 content 9"]}}class oe extends se{constructor(t){super(),this.url="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oe).fromBinary(t,r)}static fromJson(t,r){return(new oe).fromJson(t,r)}static fromJsonString(t,r){return(new oe).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oe,t,r)}static $(){return["SendMessageAttachment|1 url 9|2 alt 9?"]}}class ae extends se{constructor(t){super(),this.message={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ae).fromBinary(t,r)}static fromJson(t,r){return(new ae).fromJson(t,r)}static fromJsonString(t,r){return(new ae).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ae,t,r)}static $(){return["SendMessageArgs|1 text #0 message|2 attachment #1 message|3 reply_to 9?|4 replace_previous_message 8?",ie,oe]}}class ue extends se{constructor(t){super(),this.timestamp=n.protoInt64.zero,this.messageId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ue).fromBinary(t,r)}static fromJson(t,r){return(new ue).fromJson(t,r)}static fromJsonString(t,r){return(new ue).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ue,t,r)}static $(){return["SendMessageSuccess|1 timestamp 4|2 message_id 9|3 thread_id 9?"]}}class ce extends se{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ce).fromBinary(t,r)}static fromJson(t,r){return(new ce).fromJson(t,r)}static fromJsonString(t,r){return(new ce).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ce,t,r)}static $(){return["SendMessageError|1 error 9"]}}class le extends se{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new le).fromBinary(t,r)}static fromJson(t,r){return(new le).fromJson(t,r)}static fromJsonString(t,r){return(new le).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(le,t,r)}static $(){return["SendMessageResult|1 success #0 result|2 error #1 result",ue,ce]}}class me extends se{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new me).fromBinary(t,r)}static fromJson(t,r){return(new me).fromJson(t,r)}static fromJsonString(t,r){return(new me).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(me,t,r)}static $(){return["SendMessageToolCall|1 args #0|2 result #1",ae,le]}}class fe extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class de extends fe{constructor(t){super(),this.bcIds=[],this.sources=[],this.statuses=[],this.includeTeamWide=!1,this.includeArchived=!1,this.includeTranscript=!1,this.activeSince="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new de).fromBinary(t,r)}static fromJson(t,r){return(new de).fromJson(t,r)}static fromJsonString(t,r){return(new de).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(de,t,r)}static $(){return["FetchCloudAgentDataArgs|4 bc_ids 9*|6 sources 9*|7 statuses 9*|8 include_team_wide 8|9 include_archived 8|10 limit 5?|12 include_transcript 8|13 active_since 9"]}}class pe extends fe{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pe).fromBinary(t,r)}static fromJson(t,r){return(new pe).fromJson(t,r)}static fromJsonString(t,r){return(new pe).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pe,t,r)}static $(){return["FetchCloudAgentDataResult|1 success #0 result|2 error #1 result",he,ge]}}class he extends fe{constructor(t){super(),this.summary="",this.agentCount=0,this.writtenPaths=[],this.unavailableBcIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new he).fromBinary(t,r)}static fromJson(t,r){return(new he).fromJson(t,r)}static fromJsonString(t,r){return(new he).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(he,t,r)}static $(){return["FetchCloudAgentDataSuccess|1 summary 9|2 agent_count 5|3 written_paths 9*|4 unavailable_bc_ids 9*"]}}class ge extends fe{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ge).fromBinary(t,r)}static fromJson(t,r){return(new ge).fromJson(t,r)}static fromJsonString(t,r){return(new ge).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ge,t,r)}static $(){return["FetchCloudAgentDataError|1 error 9"]}}class _e extends fe{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _e).fromBinary(t,r)}static fromJson(t,r){return(new _e).fromJson(t,r)}static fromJsonString(t,r){return(new _e).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_e,t,r)}static $(){return["FetchCloudAgentDataToolCall|1 args #0|2 result #1",de,pe]}}class Je extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class we extends Je{constructor(t){super(),this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new we).fromBinary(t,r)}static fromJson(t,r){return(new we).fromJson(t,r)}static fromJsonString(t,r){return(new we).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(we,t,r)}static $(){return["SendToUserArgs|1 message 9"]}}class ye extends Je{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ye).fromBinary(t,r)}static fromJson(t,r){return(new ye).fromJson(t,r)}static fromJsonString(t,r){return(new ye).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ye,t,r)}static $(){return["SendToUserSuccess"]}}class Se extends Je{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Se).fromBinary(t,r)}static fromJson(t,r){return(new Se).fromJson(t,r)}static fromJsonString(t,r){return(new Se).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Se,t,r)}static $(){return["SendToUserError|1 error 9"]}}class qe extends Je{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qe).fromBinary(t,r)}static fromJson(t,r){return(new qe).fromJson(t,r)}static fromJsonString(t,r){return(new qe).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qe,t,r)}static $(){return["SendToUserResult|1 success #0 result|2 error #1 result",ye,Se]}}class Be extends Je{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Be).fromBinary(t,r)}static fromJson(t,r){return(new Be).fromJson(t,r)}static fromJsonString(t,r){return(new Be).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Be,t,r)}static $(){return["SendToUserToolCall|1 args #0|2 result #1",we,qe]}}var Ie=e("../proto/dist/generated/agent/v1/connect_scm_tool_pb.js"),Pe=e("../proto/dist/generated/agent/v1/conversation_search_exec_pb.js");class be extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class Re extends be{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Re).fromBinary(t,r)}static fromJson(t,r){return(new Re).fromJson(t,r)}static fromJsonString(t,r){return(new Re).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Re,t,r)}static $(){return["SearchConversationsToolCall|1 args #0|2 result #1",Pe.$m,Pe.pT]}}const ve="agent.v1.";class xe extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return ve}}var ke=(0,o.QT)(n.proto3,ve,"GoalStatus",[[0,"UNSPECIFIED"],[1,"ACTIVE"],[2,"PAUSED"],[3,"COMPLETE"],[4,"CLEARED"]],1);class Ee extends xe{constructor(t){super(),this.objective="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ee).fromBinary(t,r)}static fromJson(t,r){return(new Ee).fromJson(t,r)}static fromJsonString(t,r){return(new Ee).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ee,t,r)}static $(){return["CreateGoalArgs|1 objective 9"]}}class Ce extends xe{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ce).fromBinary(t,r)}static fromJson(t,r){return(new Ce).fromJson(t,r)}static fromJsonString(t,r){return(new Ce).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ce,t,r)}static $(){return["CreateGoalSuccess"]}}class Te extends xe{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Te).fromBinary(t,r)}static fromJson(t,r){return(new Te).fromJson(t,r)}static fromJsonString(t,r){return(new Te).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Te,t,r)}static $(){return["GoalError|1 error 9"]}}class Ue extends xe{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ue).fromBinary(t,r)}static fromJson(t,r){return(new Ue).fromJson(t,r)}static fromJsonString(t,r){return(new Ue).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ue,t,r)}static $(){return["CreateGoalResult|1 success #0 result|2 error #1 result",Ce,Te]}}class Ae extends xe{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ae).fromBinary(t,r)}static fromJson(t,r){return(new Ae).fromJson(t,r)}static fromJsonString(t,r){return(new Ae).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ae,t,r)}static $(){return["CreateGoalToolCall|1 args #0|2 result #1",Ee,Ue]}}class $e extends xe{constructor(t){super(),this.status=ke.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $e).fromBinary(t,r)}static fromJson(t,r){return(new $e).fromJson(t,r)}static fromJsonString(t,r){return(new $e).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($e,t,r)}static $(){return["UpdateGoalArgs|1 status #0",ke]}}class Me extends xe{constructor(t){super(),this.status=ke.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Me).fromBinary(t,r)}static fromJson(t,r){return(new Me).fromJson(t,r)}static fromJsonString(t,r){return(new Me).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Me,t,r)}static $(){return["UpdateGoalSuccess|1 status #0",ke]}}class Oe extends xe{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Oe).fromBinary(t,r)}static fromJson(t,r){return(new Oe).fromJson(t,r)}static fromJsonString(t,r){return(new Oe).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Oe,t,r)}static $(){return["UpdateGoalResult|1 success #0 result|2 error #1 result",Me,Te]}}class De extends xe{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new De).fromBinary(t,r)}static fromJson(t,r){return(new De).fromJson(t,r)}static fromJsonString(t,r){return(new De).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(De,t,r)}static $(){return["UpdateGoalToolCall|1 args #0|2 result #1",$e,Oe]}}const Ne="agent.v1.";class Ge extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return Ne}}var Le=(0,o.QT)(n.proto3,Ne,"CreateAgentPlacementApprovalState",[[0,"UNSPECIFIED"],[1,"REQUIRED"],[2,"DENIED"]],1);class Fe extends Ge{constructor(t){super(),this.toolCallId="",this.agentIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fe).fromBinary(t,r)}static fromJson(t,r){return(new Fe).fromJson(t,r)}static fromJsonString(t,r){return(new Fe).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fe,t,r)}static $(){return["GetAgentStatusArgs|1 tool_call_id 9|2 agent_ids 9*"]}}class Ke extends Ge{constructor(t){super(),this.bcId="",this.name="",this.lifecycle="",this.turnInFlight=!1,this.lastTerminalTurnStatus="",this.prUrl="",this.lastActivityAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ke).fromBinary(t,r)}static fromJson(t,r){return(new Ke).fromJson(t,r)}static fromJsonString(t,r){return(new Ke).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ke,t,r)}static $(){return["GetAgentStatusWorker|1 bc_id 9|2 name 9|3 lifecycle 9|4 turn_in_flight 8|5 last_terminal_turn_status 9|6 pr_url 9|7 last_activity_at_ms 4"]}}class ze extends Ge{constructor(t){super(),this.workers=[],this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ze).fromBinary(t,r)}static fromJson(t,r){return(new ze).fromJson(t,r)}static fromJsonString(t,r){return(new ze).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ze,t,r)}static $(){return["GetAgentStatusSuccess|1 workers #0*|2 message 9",Ke]}}class je extends Ge{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new je).fromBinary(t,r)}static fromJson(t,r){return(new je).fromJson(t,r)}static fromJsonString(t,r){return(new je).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(je,t,r)}static $(){return["GetAgentStatusError|1 error 9"]}}class He extends Ge{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new He).fromBinary(t,r)}static fromJson(t,r){return(new He).fromJson(t,r)}static fromJsonString(t,r){return(new He).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(He,t,r)}static $(){return["GetAgentStatusResult|1 success #0 result|2 error #1 result",ze,je]}}class We extends Ge{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new We).fromBinary(t,r)}static fromJson(t,r){return(new We).fromJson(t,r)}static fromJsonString(t,r){return(new We).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(We,t,r)}static $(){return["GetAgentStatusToolCall|1 args #0|2 result #1",Fe,He]}}class Qe extends Ge{constructor(t){super(),this.toolCallId="",this.agentId="",this.message="",this.delivery="",this.title="",this.trackedTaskKeys=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qe).fromBinary(t,r)}static fromJson(t,r){return(new Qe).fromJson(t,r)}static fromJsonString(t,r){return(new Qe).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qe,t,r)}static $(){return["SendToAgentArgs|1 tool_call_id 9|2 agent_id 9|3 message 9|4 delivery 9|5 title 9|6 model 9?|7 tracked_task_keys 9*"]}}class Ve extends Ge{constructor(t){super(),this.workerBcId="",this.deliveredAs="",this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ve).fromBinary(t,r)}static fromJson(t,r){return(new Ve).fromJson(t,r)}static fromJsonString(t,r){return(new Ve).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ve,t,r)}static $(){return["SendToAgentSuccess|1 worker_bc_id 9|2 delivered_as 9|3 message 9|4 recipient #0?",Xe]}}class Xe extends Ge{constructor(t){super(),this.kind=Ye.UNSPECIFIED,this.id="",this.displayName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xe).fromBinary(t,r)}static fromJson(t,r){return(new Xe).fromJson(t,r)}static fromJsonString(t,r){return(new Xe).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xe,t,r)}static $(){return["SendToAgentRecipient|1 kind #0|2 id 9|3 display_name 9",Ye]}}var Ye=(0,o.QT)(n.proto3,Ne,"SendToAgentRecipient.Kind",[[0,"UNSPECIFIED"],[1,"MAIN_BOT"],[2,"PROJECT_SESSION"]],1);class Ze extends Ge{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ze).fromBinary(t,r)}static fromJson(t,r){return(new Ze).fromJson(t,r)}static fromJsonString(t,r){return(new Ze).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ze,t,r)}static $(){return["SendToAgentError|1 error 9"]}}class tn extends Ge{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tn).fromBinary(t,r)}static fromJson(t,r){return(new tn).fromJson(t,r)}static fromJsonString(t,r){return(new tn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tn,t,r)}static $(){return["SendToAgentResult|1 success #0 result|2 error #1 result",Ve,Ze]}}class rn extends Ge{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rn).fromBinary(t,r)}static fromJson(t,r){return(new rn).fromJson(t,r)}static fromJsonString(t,r){return(new rn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rn,t,r)}static $(){return["SendToAgentToolCall|1 args #0|2 result #1",Qe,tn]}}class en extends Ge{constructor(t){super(),this.toolCallId="",this.agentId="",this.mode="",this.maxTurns=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new en).fromBinary(t,r)}static fromJson(t,r){return(new en).fromJson(t,r)}static fromJsonString(t,r){return(new en).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(en,t,r)}static $(){return["ReadAgentTranscriptArgs|1 tool_call_id 9|2 agent_id 9|3 mode 9|4 max_turns 13"]}}class nn extends Ge{constructor(t){super(),this.transcript="",this.truncated=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nn).fromBinary(t,r)}static fromJson(t,r){return(new nn).fromJson(t,r)}static fromJsonString(t,r){return(new nn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nn,t,r)}static $(){return["ReadAgentTranscriptSuccess|1 transcript 9|2 truncated 8"]}}class sn extends Ge{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sn).fromBinary(t,r)}static fromJson(t,r){return(new sn).fromJson(t,r)}static fromJsonString(t,r){return(new sn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sn,t,r)}static $(){return["ReadAgentTranscriptError|1 error 9"]}}class on extends Ge{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new on).fromBinary(t,r)}static fromJson(t,r){return(new on).fromJson(t,r)}static fromJsonString(t,r){return(new on).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(on,t,r)}static $(){return["ReadAgentTranscriptResult|1 success #0 result|2 error #1 result",nn,sn]}}class an extends Ge{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new an).fromBinary(t,r)}static fromJson(t,r){return(new an).fromJson(t,r)}static fromJsonString(t,r){return(new an).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(an,t,r)}static $(){return["ReadAgentTranscriptToolCall|1 args #0|2 result #1",en,on]}}class un extends Ge{constructor(t){super(),this.toolCallId="",this.prompt="",this.labels={},this.trackedTaskKeys=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new un).fromBinary(t,r)}static fromJson(t,r){return(new un).fromJson(t,r)}static fromJsonString(t,r){return(new un).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(un,t,r)}static $(){return["CreateAgentArgs|1 tool_call_id 9|2 prompt 9|3 name 9?|4 model 9?|5 base_branch 9?|6 machine_type 9?|7 worker_id 9?|8 pool 9?|9 labels 9,9|10 environment_build_id 9?|11 environment_id 9?|12 repo_url 9?|13 tracked_task_keys 9*|14 fork_from 9?|15 fork_turns 13?"]}}class cn extends Ge{constructor(t){super(),this.agentId="",this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cn).fromBinary(t,r)}static fromJson(t,r){return(new cn).fromJson(t,r)}static fromJsonString(t,r){return(new cn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cn,t,r)}static $(){return["CreateAgentSuccess|1 agent_id 9|2 message 9"]}}class ln extends Ge{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ln).fromBinary(t,r)}static fromJson(t,r){return(new ln).fromJson(t,r)}static fromJsonString(t,r){return(new ln).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ln,t,r)}static $(){return["CreateAgentError|1 error 9|2 placement_approval_state #0?",Le]}}class mn extends Ge{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mn).fromBinary(t,r)}static fromJson(t,r){return(new mn).fromJson(t,r)}static fromJsonString(t,r){return(new mn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mn,t,r)}static $(){return["CreateAgentResult|1 success #0 result|2 error #1 result",cn,ln]}}class fn extends Ge{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fn).fromBinary(t,r)}static fromJson(t,r){return(new fn).fromJson(t,r)}static fromJsonString(t,r){return(new fn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fn,t,r)}static $(){return["CreateAgentToolCall|1 args #0|2 result #1",un,mn]}}class dn extends Ge{constructor(t){super(),this.toolCallId="",this.prompt="",this.labels={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dn).fromBinary(t,r)}static fromJson(t,r){return(new dn).fromJson(t,r)}static fromJsonString(t,r){return(new dn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dn,t,r)}static $(){return["CreateProjectArgs|1 tool_call_id 9|2 prompt 9|3 name 9?|4 model 9?|5 base_branch 9?|6 machine_type 9?|7 worker_id 9?|8 pool 9?|9 labels 9,9|10 environment_build_id 9?|11 environment_id 9?|12 repo_url 9?"]}}class pn extends Ge{constructor(t){super(),this.agentId="",this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pn).fromBinary(t,r)}static fromJson(t,r){return(new pn).fromJson(t,r)}static fromJsonString(t,r){return(new pn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pn,t,r)}static $(){return["CreateProjectSuccess|1 agent_id 9|2 message 9"]}}class hn extends Ge{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hn).fromBinary(t,r)}static fromJson(t,r){return(new hn).fromJson(t,r)}static fromJsonString(t,r){return(new hn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hn,t,r)}static $(){return["CreateProjectError|1 error 9|2 placement_approval_state #0?",Le]}}class gn extends Ge{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gn).fromBinary(t,r)}static fromJson(t,r){return(new gn).fromJson(t,r)}static fromJsonString(t,r){return(new gn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gn,t,r)}static $(){return["CreateProjectResult|1 success #0 result|2 error #1 result",pn,hn]}}class _n extends Ge{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _n).fromBinary(t,r)}static fromJson(t,r){return(new _n).fromJson(t,r)}static fromJsonString(t,r){return(new _n).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_n,t,r)}static $(){return["CreateProjectToolCall|1 args #0|2 result #1",dn,gn]}}class Jn extends Ge{constructor(t){super(),this.toolCallId="",this.agentId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jn).fromBinary(t,r)}static fromJson(t,r){return(new Jn).fromJson(t,r)}static fromJsonString(t,r){return(new Jn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jn,t,r)}static $(){return["StartProjectUpdatesArgs|1 tool_call_id 9|2 agent_id 9"]}}class wn extends Ge{constructor(t){super(),this.agentId="",this.untilMs=n.protoInt64.zero,this.wasOn=!1,this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wn).fromBinary(t,r)}static fromJson(t,r){return(new wn).fromJson(t,r)}static fromJsonString(t,r){return(new wn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wn,t,r)}static $(){return["StartProjectUpdatesSuccess|1 agent_id 9|2 until_ms 3|3 was_on 8|4 message 9"]}}class yn extends Ge{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yn).fromBinary(t,r)}static fromJson(t,r){return(new yn).fromJson(t,r)}static fromJsonString(t,r){return(new yn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yn,t,r)}static $(){return["StartProjectUpdatesError|1 error 9"]}}class Sn extends Ge{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sn).fromBinary(t,r)}static fromJson(t,r){return(new Sn).fromJson(t,r)}static fromJsonString(t,r){return(new Sn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sn,t,r)}static $(){return["StartProjectUpdatesResult|1 success #0 result|2 error #1 result",wn,yn]}}class qn extends Ge{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qn).fromBinary(t,r)}static fromJson(t,r){return(new qn).fromJson(t,r)}static fromJsonString(t,r){return(new qn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qn,t,r)}static $(){return["StartProjectUpdatesToolCall|1 args #0|2 result #1",Jn,Sn]}}class Bn extends Ge{constructor(t){super(),this.toolCallId="",this.agentId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bn).fromBinary(t,r)}static fromJson(t,r){return(new Bn).fromJson(t,r)}static fromJsonString(t,r){return(new Bn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bn,t,r)}static $(){return["StopProjectUpdatesArgs|1 tool_call_id 9|2 agent_id 9"]}}class In extends Ge{constructor(t){super(),this.agentId="",this.wasOn=!1,this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new In).fromBinary(t,r)}static fromJson(t,r){return(new In).fromJson(t,r)}static fromJsonString(t,r){return(new In).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(In,t,r)}static $(){return["StopProjectUpdatesSuccess|1 agent_id 9|2 was_on 8|3 message 9"]}}class Pn extends Ge{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pn).fromBinary(t,r)}static fromJson(t,r){return(new Pn).fromJson(t,r)}static fromJsonString(t,r){return(new Pn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pn,t,r)}static $(){return["StopProjectUpdatesError|1 error 9"]}}class bn extends Ge{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bn).fromBinary(t,r)}static fromJson(t,r){return(new bn).fromJson(t,r)}static fromJsonString(t,r){return(new bn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bn,t,r)}static $(){return["StopProjectUpdatesResult|1 success #0 result|2 error #1 result",In,Pn]}}class Rn extends Ge{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rn).fromBinary(t,r)}static fromJson(t,r){return(new Rn).fromJson(t,r)}static fromJsonString(t,r){return(new Rn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rn,t,r)}static $(){return["StopProjectUpdatesToolCall|1 args #0|2 result #1",Bn,bn]}}class vn extends Ge{constructor(t){super(),this.kind="",this.id="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vn).fromBinary(t,r)}static fromJson(t,r){return(new vn).fromJson(t,r)}static fromJsonString(t,r){return(new vn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vn,t,r)}static $(){return["ManageAccessTarget|1 kind 9|2 id 9"]}}class xn extends Ge{constructor(t){super(),this.toolCallId="",this.action="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xn).fromBinary(t,r)}static fromJson(t,r){return(new xn).fromJson(t,r)}static fromJsonString(t,r){return(new xn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xn,t,r)}static $(){return["ManageAccessArgs|1 tool_call_id 9|2 action 9|3 target #0?",vn]}}class kn extends Ge{constructor(t){super(),this.name="",this.grantedBy="",this.grantedAtMs=n.protoInt64.zero,this.scope="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kn).fromBinary(t,r)}static fromJson(t,r){return(new kn).fromJson(t,r)}static fromJsonString(t,r){return(new kn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kn,t,r)}static $(){return["ManageAccessGrant|1 target #0|2 name 9|3 granted_by 9|4 granted_at_ms 4|5 scope 9",vn]}}class En extends Ge{constructor(t){super(),this.decision="",this.grants=[],this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new En).fromBinary(t,r)}static fromJson(t,r){return(new En).fromJson(t,r)}static fromJsonString(t,r){return(new En).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(En,t,r)}static $(){return["ManageAccessSuccess|1 decision 9|2 grants #0*|3 message 9",kn]}}class Cn extends Ge{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cn).fromBinary(t,r)}static fromJson(t,r){return(new Cn).fromJson(t,r)}static fromJsonString(t,r){return(new Cn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cn,t,r)}static $(){return["ManageAccessError|1 error 9"]}}class Tn extends Ge{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tn).fromBinary(t,r)}static fromJson(t,r){return(new Tn).fromJson(t,r)}static fromJsonString(t,r){return(new Tn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tn,t,r)}static $(){return["ManageAccessResult|1 success #0 result|2 error #1 result",En,Cn]}}class Un extends Ge{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Un).fromBinary(t,r)}static fromJson(t,r){return(new Un).fromJson(t,r)}static fromJsonString(t,r){return(new Un).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Un,t,r)}static $(){return["ManageAccessToolCall|1 args #0|2 result #1",xn,Tn]}}class An extends Ge{constructor(t){super(),this.toolCallId="",this.agentId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new An).fromBinary(t,r)}static fromJson(t,r){return(new An).fromJson(t,r)}static fromJsonString(t,r){return(new An).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(An,t,r)}static $(){return["StopAgentArgs|1 tool_call_id 9|2 agent_id 9"]}}class $n extends Ge{constructor(t){super(),this.workerBcId="",this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $n).fromBinary(t,r)}static fromJson(t,r){return(new $n).fromJson(t,r)}static fromJsonString(t,r){return(new $n).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($n,t,r)}static $(){return["StopAgentSuccess|1 worker_bc_id 9|2 message 9"]}}class Mn extends Ge{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mn).fromBinary(t,r)}static fromJson(t,r){return(new Mn).fromJson(t,r)}static fromJsonString(t,r){return(new Mn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mn,t,r)}static $(){return["StopAgentError|1 error 9"]}}class On extends Ge{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new On).fromBinary(t,r)}static fromJson(t,r){return(new On).fromJson(t,r)}static fromJsonString(t,r){return(new On).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(On,t,r)}static $(){return["StopAgentResult|1 success #0 result|2 error #1 result",$n,Mn]}}class Dn extends Ge{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dn).fromBinary(t,r)}static fromJson(t,r){return(new Dn).fromJson(t,r)}static fromJsonString(t,r){return(new Dn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dn,t,r)}static $(){return["StopAgentToolCall|1 args #0|2 result #1",An,On]}}class Nn extends Ge{constructor(t){super(),this.path="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nn).fromBinary(t,r)}static fromJson(t,r){return(new Nn).fromJson(t,r)}static fromJsonString(t,r){return(new Nn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nn,t,r)}static $(){return["TrackedTaskDocumentInput|1 path 9|2 label 9?"]}}class Gn extends Ge{constructor(t){super(),this.url="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gn).fromBinary(t,r)}static fromJson(t,r){return(new Gn).fromJson(t,r)}static fromJsonString(t,r){return(new Gn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gn,t,r)}static $(){return["TrackedTaskUrlInput|1 url 9|2 label 9?"]}}class Ln extends Ge{constructor(t){super(),this.target={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ln).fromBinary(t,r)}static fromJson(t,r){return(new Ln).fromJson(t,r)}static fromJsonString(t,r){return(new Ln).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ln,t,r)}static $(){return["TrackedTaskLinkInput|1 agent_id 9 target|2 pr_url 9 target|3 document #0 target|4 url #1 target",Nn,Gn]}}class Fn extends Ge{constructor(t){super(),this.url="",this.openedByAgentId="",this.countsForCompletion=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fn).fromBinary(t,r)}static fromJson(t,r){return(new Fn).fromJson(t,r)}static fromJsonString(t,r){return(new Fn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fn,t,r)}static $(){return["TrackedTaskPrLinkView|1 url 9|2 opened_by_agent_id 9|3 counts_for_completion 8"]}}class Kn extends Ge{constructor(t){super(),this.target={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kn).fromBinary(t,r)}static fromJson(t,r){return(new Kn).fromJson(t,r)}static fromJsonString(t,r){return(new Kn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Kn,t,r)}static $(){return["TrackedTaskLinkView|1 agent_id 9 target|2 pr #0 target|3 document #1 target|4 url #2 target",Fn,Nn,Gn]}}class zn extends Ge{constructor(t){super(),this.key="",this.title="",this.statusId="",this.statusLabel="",this.owner="",this.parentKey="",this.links=[],this.updatedAtMs=n.protoInt64.zero,this.ownerSessionId="",this.version=n.protoInt64.zero,this.tag="",this.internalNotes="",this.tags=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zn).fromBinary(t,r)}static fromJson(t,r){return(new zn).fromJson(t,r)}static fromJsonString(t,r){return(new zn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zn,t,r)}static $(){return["TrackedTaskView|1 key 9|2 title 9|3 status_id 9|4 status_label 9|5 owner 9|6 parent_key 9|7 links #0*|8 updated_at_ms 4|9 owner_session_id 9|10 version 4|11 tag 9|12 internal_notes 9|13 tags 9*",Kn]}}class jn extends Ge{constructor(t){super(),this.id="",this.label="",this.category="",this.taskCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jn).fromBinary(t,r)}static fromJson(t,r){return(new jn).fromJson(t,r)}static fromJsonString(t,r){return(new jn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jn,t,r)}static $(){return["TrackedTaskStatusView|1 id 9|2 label 9|3 category 9|4 task_count 13|5 description 9?"]}}class Hn extends Ge{constructor(t){super(),this.id="",this.label="",this.color="",this.taskCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hn).fromBinary(t,r)}static fromJson(t,r){return(new Hn).fromJson(t,r)}static fromJsonString(t,r){return(new Hn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hn,t,r)}static $(){return["TrackedTaskTagView|1 id 9|2 label 9|3 color 9|4 task_count 13"]}}class Wn extends Ge{constructor(t){super(),this.name="",this.sessionId="",this.isYou=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wn).fromBinary(t,r)}static fromJson(t,r){return(new Wn).fromJson(t,r)}static fromJsonString(t,r){return(new Wn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wn,t,r)}static $(){return["TrackedTaskMemberView|1 name 9|2 session_id 9|3 is_you 8"]}}class Qn extends Ge{constructor(t){super(),this.toolCallId="",this.keys=[],this.statusCategories=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qn).fromBinary(t,r)}static fromJson(t,r){return(new Qn).fromJson(t,r)}static fromJsonString(t,r){return(new Qn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qn,t,r)}static $(){return["ListTrackedTasksArgs|1 tool_call_id 9|2 keys 9*|3 status_categories 9*|4 owner 9?|5 linked_agent_id 9?|6 cursor 9?"]}}class Vn extends Ge{constructor(t){super(),this.tasks=[],this.statuses=[],this.members=[],this.olderClosedCount=0,this.truncated=!1,this.matchingCount=0,this.message="",this.tags=[],this.nextCursor="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vn).fromBinary(t,r)}static fromJson(t,r){return(new Vn).fromJson(t,r)}static fromJsonString(t,r){return(new Vn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vn,t,r)}static $(){return["ListTrackedTasksSuccess|1 tasks #0*|2 statuses #1*|3 members #2*|4 older_closed_count 13|5 truncated 8|6 matching_count 13|7 message 9|8 tags #3*|9 next_cursor 9",zn,jn,Wn,Hn]}}class Xn extends Ge{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xn).fromBinary(t,r)}static fromJson(t,r){return(new Xn).fromJson(t,r)}static fromJsonString(t,r){return(new Xn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xn,t,r)}static $(){return["ListTrackedTasksError|1 error 9"]}}class Yn extends Ge{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yn).fromBinary(t,r)}static fromJson(t,r){return(new Yn).fromJson(t,r)}static fromJsonString(t,r){return(new Yn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yn,t,r)}static $(){return["ListTrackedTasksResult|1 success #0 result|2 error #1 result",Vn,Xn]}}class Zn extends Ge{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zn).fromBinary(t,r)}static fromJson(t,r){return(new Zn).fromJson(t,r)}static fromJsonString(t,r){return(new Zn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zn,t,r)}static $(){return["ListTrackedTasksToolCall|1 args #0|2 result #1",Qn,Yn]}}class ts extends Ge{constructor(t){super(),this.title="",this.links=[],this.tags=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ts).fromBinary(t,r)}static fromJson(t,r){return(new ts).fromJson(t,r)}static fromJsonString(t,r){return(new ts).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ts,t,r)}static $(){return["NewTrackedTask|1 client_ref 9?|2 title 9|3 status 9?|4 owner 9?|5 parent 9?|6 links #0*|7 tag 9?|8 internal_notes 9?|9 tags 9*",Ln]}}class rs extends Ge{constructor(t){super(),this.toolCallId="",this.tasks=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rs).fromBinary(t,r)}static fromJson(t,r){return(new rs).fromJson(t,r)}static fromJsonString(t,r){return(new rs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rs,t,r)}static $(){return["CreateTrackedTasksArgs|1 tool_call_id 9|2 tasks #0*",ts]}}class es extends Ge{constructor(t){super(),this.clientRef="",this.key="",this.version=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new es).fromBinary(t,r)}static fromJson(t,r){return(new es).fromJson(t,r)}static fromJsonString(t,r){return(new es).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(es,t,r)}static $(){return["TrackedTaskCreated|1 client_ref 9|2 key 9|3 version 4"]}}class ns extends Ge{constructor(t){super(),this.created=[],this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ns).fromBinary(t,r)}static fromJson(t,r){return(new ns).fromJson(t,r)}static fromJsonString(t,r){return(new ns).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ns,t,r)}static $(){return["CreateTrackedTasksSuccess|1 created #0*|2 message 9",es]}}class ss extends Ge{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ss).fromBinary(t,r)}static fromJson(t,r){return(new ss).fromJson(t,r)}static fromJsonString(t,r){return(new ss).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ss,t,r)}static $(){return["CreateTrackedTasksError|1 error 9"]}}class is extends Ge{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new is).fromBinary(t,r)}static fromJson(t,r){return(new is).fromJson(t,r)}static fromJsonString(t,r){return(new is).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(is,t,r)}static $(){return["CreateTrackedTasksResult|1 success #0 result|2 error #1 result",ns,ss]}}class os extends Ge{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new os).fromBinary(t,r)}static fromJson(t,r){return(new os).fromJson(t,r)}static fromJsonString(t,r){return(new os).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(os,t,r)}static $(){return["CreateTrackedTasksToolCall|1 args #0|2 result #1",rs,is]}}class as extends Ge{constructor(t){super(),this.anchor={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new as).fromBinary(t,r)}static fromJson(t,r){return(new as).fromJson(t,r)}static fromJsonString(t,r){return(new as).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(as,t,r)}static $(){return["TrackedTaskPosition|1 before_key 9 anchor|2 after_key 9 anchor"]}}class us extends Ge{constructor(t){super(),this.key="",this.addLinks=[],this.removeLinks=[],this.version=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new us).fromBinary(t,r)}static fromJson(t,r){return(new us).fromJson(t,r)}static fromJsonString(t,r){return(new us).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(us,t,r)}static $(){return["TrackedTaskUpdate|1 key 9|2 title 9?|3 status 9?|4 owner 9?|5 parent 9?|6 position #0?|7 add_links #1*|8 remove_links #1*|9 version 4|10 tag 9?|11 internal_notes 9?|12 tags #2?",as,Ln,cs]}}class cs extends Ge{constructor(t){super(),this.ids=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cs).fromBinary(t,r)}static fromJson(t,r){return(new cs).fromJson(t,r)}static fromJsonString(t,r){return(new cs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cs,t,r)}static $(){return["TrackedTaskTagIds|1 ids 9*"]}}class ls extends Ge{constructor(t){super(),this.toolCallId="",this.updates=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ls).fromBinary(t,r)}static fromJson(t,r){return(new ls).fromJson(t,r)}static fromJsonString(t,r){return(new ls).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ls,t,r)}static $(){return["UpdateTrackedTasksArgs|1 tool_call_id 9|2 updates #0*",us]}}class ms extends Ge{constructor(t){super(),this.key="",this.field="",this.currentValue="",this.changedBy="",this.changedAtMs=n.protoInt64.zero,this.currentVersion=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ms).fromBinary(t,r)}static fromJson(t,r){return(new ms).fromJson(t,r)}static fromJsonString(t,r){return(new ms).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ms,t,r)}static $(){return["TrackedTaskConflict|1 key 9|2 field 9|3 current_value 9|4 changed_by 9|5 changed_at_ms 4|6 current_version 4"]}}class fs extends Ge{constructor(t){super(),this.key="",this.version=n.protoInt64.zero,this.title="",this.statusLabel="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fs).fromBinary(t,r)}static fromJson(t,r){return(new fs).fromJson(t,r)}static fromJsonString(t,r){return(new fs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fs,t,r)}static $(){return["TrackedTaskUpdated|1 key 9|2 version 4|3 title 9|4 status_label 9"]}}class ds extends Ge{constructor(t){super(),this.updated=[],this.conflicts=[],this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ds).fromBinary(t,r)}static fromJson(t,r){return(new ds).fromJson(t,r)}static fromJsonString(t,r){return(new ds).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ds,t,r)}static $(){return["UpdateTrackedTasksSuccess|1 updated #0*|2 conflicts #1*|3 message 9",fs,ms]}}class ps extends Ge{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ps).fromBinary(t,r)}static fromJson(t,r){return(new ps).fromJson(t,r)}static fromJsonString(t,r){return(new ps).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ps,t,r)}static $(){return["UpdateTrackedTasksError|1 error 9"]}}class hs extends Ge{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hs).fromBinary(t,r)}static fromJson(t,r){return(new hs).fromJson(t,r)}static fromJsonString(t,r){return(new hs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hs,t,r)}static $(){return["UpdateTrackedTasksResult|1 success #0 result|2 error #1 result",ds,ps]}}class gs extends Ge{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gs).fromBinary(t,r)}static fromJson(t,r){return(new gs).fromJson(t,r)}static fromJsonString(t,r){return(new gs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gs,t,r)}static $(){return["UpdateTrackedTasksToolCall|1 args #0|2 result #1",ls,hs]}}class _s extends Ge{constructor(t){super(),this.toolCallId="",this.keys=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _s).fromBinary(t,r)}static fromJson(t,r){return(new _s).fromJson(t,r)}static fromJsonString(t,r){return(new _s).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_s,t,r)}static $(){return["DeleteTrackedTasksArgs|1 tool_call_id 9|2 keys 9*"]}}class Js extends Ge{constructor(t){super(),this.deletedKeys=[],this.unparentedKeys=[],this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Js).fromBinary(t,r)}static fromJson(t,r){return(new Js).fromJson(t,r)}static fromJsonString(t,r){return(new Js).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Js,t,r)}static $(){return["DeleteTrackedTasksSuccess|1 deleted_keys 9*|2 unparented_keys 9*|3 message 9"]}}class ws extends Ge{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ws).fromBinary(t,r)}static fromJson(t,r){return(new ws).fromJson(t,r)}static fromJsonString(t,r){return(new ws).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ws,t,r)}static $(){return["DeleteTrackedTasksError|1 error 9"]}}class ys extends Ge{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ys).fromBinary(t,r)}static fromJson(t,r){return(new ys).fromJson(t,r)}static fromJsonString(t,r){return(new ys).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ys,t,r)}static $(){return["DeleteTrackedTasksResult|1 success #0 result|2 error #1 result",Js,ws]}}class Ss extends Ge{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ss).fromBinary(t,r)}static fromJson(t,r){return(new Ss).fromJson(t,r)}static fromJsonString(t,r){return(new Ss).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ss,t,r)}static $(){return["DeleteTrackedTasksToolCall|1 args #0|2 result #1",_s,ys]}}class qs extends Ge{constructor(t){super(),this.label="",this.category="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qs).fromBinary(t,r)}static fromJson(t,r){return(new qs).fromJson(t,r)}static fromJsonString(t,r){return(new qs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qs,t,r)}static $(){return["TrackedTaskStatusInput|1 id 9?|2 label 9|3 icon 9?|4 category 9|5 description 9?"]}}class Bs extends Ge{constructor(t){super(),this.toolCallId="",this.statuses=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bs).fromBinary(t,r)}static fromJson(t,r){return(new Bs).fromJson(t,r)}static fromJsonString(t,r){return(new Bs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bs,t,r)}static $(){return["UpdateTrackedTaskStatusesArgs|1 tool_call_id 9|2 statuses #0*",qs]}}class Is extends Ge{constructor(t){super(),this.statuses=[],this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Is).fromBinary(t,r)}static fromJson(t,r){return(new Is).fromJson(t,r)}static fromJsonString(t,r){return(new Is).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Is,t,r)}static $(){return["UpdateTrackedTaskStatusesSuccess|1 statuses #0*|2 message 9",jn]}}class Ps extends Ge{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ps).fromBinary(t,r)}static fromJson(t,r){return(new Ps).fromJson(t,r)}static fromJsonString(t,r){return(new Ps).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ps,t,r)}static $(){return["UpdateTrackedTaskStatusesError|1 error 9"]}}class bs extends Ge{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bs).fromBinary(t,r)}static fromJson(t,r){return(new bs).fromJson(t,r)}static fromJsonString(t,r){return(new bs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bs,t,r)}static $(){return["UpdateTrackedTaskStatusesResult|1 success #0 result|2 error #1 result",Is,Ps]}}class Rs extends Ge{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rs).fromBinary(t,r)}static fromJson(t,r){return(new Rs).fromJson(t,r)}static fromJsonString(t,r){return(new Rs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rs,t,r)}static $(){return["UpdateTrackedTaskStatusesToolCall|1 args #0|2 result #1",Bs,bs]}}class vs extends Ge{constructor(t){super(),this.label="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vs).fromBinary(t,r)}static fromJson(t,r){return(new vs).fromJson(t,r)}static fromJsonString(t,r){return(new vs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vs,t,r)}static $(){return["TrackedTaskTagInput|1 id 9?|2 label 9|3 color 9?"]}}class xs extends Ge{constructor(t){super(),this.toolCallId="",this.tags=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xs).fromBinary(t,r)}static fromJson(t,r){return(new xs).fromJson(t,r)}static fromJsonString(t,r){return(new xs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xs,t,r)}static $(){return["UpdateTrackedTaskTagsArgs|1 tool_call_id 9|2 tags #0*",vs]}}class ks extends Ge{constructor(t){super(),this.tags=[],this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ks).fromBinary(t,r)}static fromJson(t,r){return(new ks).fromJson(t,r)}static fromJsonString(t,r){return(new ks).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ks,t,r)}static $(){return["UpdateTrackedTaskTagsSuccess|1 tags #0*|2 message 9",Hn]}}class Es extends Ge{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Es).fromBinary(t,r)}static fromJson(t,r){return(new Es).fromJson(t,r)}static fromJsonString(t,r){return(new Es).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Es,t,r)}static $(){return["UpdateTrackedTaskTagsError|1 error 9"]}}class Cs extends Ge{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cs).fromBinary(t,r)}static fromJson(t,r){return(new Cs).fromJson(t,r)}static fromJsonString(t,r){return(new Cs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cs,t,r)}static $(){return["UpdateTrackedTaskTagsResult|1 success #0 result|2 error #1 result",ks,Es]}}class Ts extends Ge{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ts).fromBinary(t,r)}static fromJson(t,r){return(new Ts).fromJson(t,r)}static fromJsonString(t,r){return(new Ts).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ts,t,r)}static $(){return["UpdateTrackedTaskTagsToolCall|1 args #0|2 result #1",xs,Cs]}}const Us="agent.v1.";class As extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return Us}}var $s=(0,o.QT)(n.proto3,Us,"WriteCanvasFailReason",[[0,"UNSPECIFIED"],[1,"TYPECHECK_FAILED"],[2,"COMPILE_FAILED"],[3,"TOO_LARGE"],[4,"UNAVAILABLE"],[5,"NOT_FOUND"],[6,"REFUSED"]],1),Ms=(0,o.QT)(n.proto3,Us,"ReadCanvasFailReason",[[0,"UNSPECIFIED"],[1,"NOT_FOUND"],[2,"UNAVAILABLE"],[3,"REFUSED"],[4,"INVALID_REFERENCE"]],1);class Os extends As{constructor(t){super(),this.line=0,this.character=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Os).fromBinary(t,r)}static fromJson(t,r){return(new Os).fromJson(t,r)}static fromJsonString(t,r){return(new Os).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Os,t,r)}static $(){return["CloudCanvasToolDiagnosticPosition|1 line 5|2 character 5"]}}class Ds extends As{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ds).fromBinary(t,r)}static fromJson(t,r){return(new Ds).fromJson(t,r)}static fromJsonString(t,r){return(new Ds).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ds,t,r)}static $(){return["CloudCanvasToolDiagnosticRange|1 start #0|2 end #0",Os]}}class Ns extends As{constructor(t){super(),this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ns).fromBinary(t,r)}static fromJson(t,r){return(new Ns).fromJson(t,r)}static fromJsonString(t,r){return(new Ns).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ns,t,r)}static $(){return["CloudCanvasToolDiagnostic|1 message 9|2 code 9?|3 severity 5?|4 range #0?",Ds]}}class Gs extends As{constructor(t){super(),this.contents="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gs).fromBinary(t,r)}static fromJson(t,r){return(new Gs).fromJson(t,r)}static fromJsonString(t,r){return(new Gs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gs,t,r)}static $(){return["WriteCanvasArgs|1 contents 9|2 canvas_id 9?|3 title 9?"]}}class Ls extends As{constructor(t){super(),this.canvasId="",this.url="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ls).fromBinary(t,r)}static fromJson(t,r){return(new Ls).fromJson(t,r)}static fromJsonString(t,r){return(new Ls).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ls,t,r)}static $(){return["WriteCanvasSuccess|1 canvas_id 9|2 title 9?|3 url 9|4 page_url 9?|5 audience_notice 9?"]}}class Fs extends As{constructor(t){super(),this.reason=$s.UNSPECIFIED,this.diagnostics=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fs).fromBinary(t,r)}static fromJson(t,r){return(new Fs).fromJson(t,r)}static fromJsonString(t,r){return(new Fs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fs,t,r)}static $(){return["WriteCanvasFailure|1 reason #0|2 diagnostics #1*|3 detail 9?",$s,Ns]}}class Ks extends As{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ks).fromBinary(t,r)}static fromJson(t,r){return(new Ks).fromJson(t,r)}static fromJsonString(t,r){return(new Ks).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ks,t,r)}static $(){return["WriteCanvasResult|1 success #0 result|2 failure #1 result",Ls,Fs]}}class zs extends As{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zs).fromBinary(t,r)}static fromJson(t,r){return(new zs).fromJson(t,r)}static fromJsonString(t,r){return(new zs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zs,t,r)}static $(){return["WriteCanvasToolCall|1 args #0|2 result #1",Gs,Ks]}}class js extends As{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new js).fromBinary(t,r)}static fromJson(t,r){return(new js).fromJson(t,r)}static fromJsonString(t,r){return(new js).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(js,t,r)}static $(){return["ReadCanvasArgs|1 canvas_id 9?|2 url 9?"]}}class Hs extends As{constructor(t){super(),this.canvasId="",this.url="",this.source="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hs).fromBinary(t,r)}static fromJson(t,r){return(new Hs).fromJson(t,r)}static fromJsonString(t,r){return(new Hs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hs,t,r)}static $(){return["ReadCanvasSuccess|1 canvas_id 9|2 title 9?|3 url 9|4 source 9"]}}class Ws extends As{constructor(t){super(),this.reason=Ms.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ws).fromBinary(t,r)}static fromJson(t,r){return(new Ws).fromJson(t,r)}static fromJsonString(t,r){return(new Ws).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ws,t,r)}static $(){return["ReadCanvasFailure|1 reason #0|2 detail 9?",Ms]}}class Qs extends As{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qs).fromBinary(t,r)}static fromJson(t,r){return(new Qs).fromJson(t,r)}static fromJsonString(t,r){return(new Qs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qs,t,r)}static $(){return["ReadCanvasResult|1 success #0 result|2 failure #1 result",Hs,Ws]}}class Vs extends As{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vs).fromBinary(t,r)}static fromJson(t,r){return(new Vs).fromJson(t,r)}static fromJsonString(t,r){return(new Vs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vs,t,r)}static $(){return["ReadCanvasToolCall|1 args #0|2 result #1",js,Qs]}}class Xs extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class Ys extends Xs{constructor(t){super(),this.prompt="",this.referenceImagePaths=[],this.keyframes=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ys).fromBinary(t,r)}static fromJson(t,r){return(new Ys).fromJson(t,r)}static fromJsonString(t,r){return(new Ys).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ys,t,r)}static $(){return["GenerateVideoArgs|1 prompt 9|2 file_path 9?|3 image_path 9?|4 reference_image_paths 9*|5 duration_seconds 13?|6 aspect_ratio 9?|7 resolution 9?|8 last_frame_path 9?|9 keyframes #0*",Zs]}}class Zs extends Xs{constructor(t){super(),this.imagePath="",this.timestampSeconds=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zs).fromBinary(t,r)}static fromJson(t,r){return(new Zs).fromJson(t,r)}static fromJsonString(t,r){return(new Zs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zs,t,r)}static $(){return["GenerateVideoKeyframe|1 image_path 9|2 timestamp_seconds 1"]}}class ti extends Xs{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ti).fromBinary(t,r)}static fromJson(t,r){return(new ti).fromJson(t,r)}static fromJsonString(t,r){return(new ti).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ti,t,r)}static $(){return["GenerateVideoResult|1 success #0 result|2 error #1 result",ri,ei]}}class ri extends Xs{constructor(t){super(),this.filePath="",this.durationSeconds=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ri).fromBinary(t,r)}static fromJson(t,r){return(new ri).fromJson(t,r)}static fromJsonString(t,r){return(new ri).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ri,t,r)}static $(){return["GenerateVideoSuccess|1 file_path 9|2 duration_seconds 13"]}}class ei extends Xs{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ei).fromBinary(t,r)}static fromJson(t,r){return(new ei).fromJson(t,r)}static fromJsonString(t,r){return(new ei).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ei,t,r)}static $(){return["GenerateVideoError|1 error 9"]}}class ni extends Xs{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ni).fromBinary(t,r)}static fromJson(t,r){return(new ni).fromJson(t,r)}static fromJsonString(t,r){return(new ni).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ni,t,r)}static $(){return["GenerateVideoToolCall|1 args #0|2 result #1",Ys,ti]}}class si extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class ii extends si{constructor(t){super(),this.query="",this.allowedXHandles=[],this.excludedXHandles=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ii).fromBinary(t,r)}static fromJson(t,r){return(new ii).fromJson(t,r)}static fromJsonString(t,r){return(new ii).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ii,t,r)}static $(){return["XSearchArgs|1 query 9|2 from_date 9?|3 to_date 9?|4 allowed_x_handles 9*|5 excluded_x_handles 9*"]}}class oi extends si{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oi).fromBinary(t,r)}static fromJson(t,r){return(new oi).fromJson(t,r)}static fromJsonString(t,r){return(new oi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oi,t,r)}static $(){return["XSearchResult|1 success #0 result|2 error #1 result|3 rejected #2 result",ai,ci,li]}}class ai extends si{constructor(t){super(),this.answer="",this.citations=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ai).fromBinary(t,r)}static fromJson(t,r){return(new ai).fromJson(t,r)}static fromJsonString(t,r){return(new ai).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ai,t,r)}static $(){return["XSearchSuccess|1 answer 9|2 citations #0*",ui]}}class ui extends si{constructor(t){super(),this.url="",this.title="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ui).fromBinary(t,r)}static fromJson(t,r){return(new ui).fromJson(t,r)}static fromJsonString(t,r){return(new ui).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ui,t,r)}static $(){return["XSearchCitation|1 url 9|2 title 9"]}}class ci extends si{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ci).fromBinary(t,r)}static fromJson(t,r){return(new ci).fromJson(t,r)}static fromJsonString(t,r){return(new ci).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ci,t,r)}static $(){return["XSearchError|1 error 9"]}}class li extends si{constructor(t){super(),this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new li).fromBinary(t,r)}static fromJson(t,r){return(new li).fromJson(t,r)}static fromJsonString(t,r){return(new li).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(li,t,r)}static $(){return["XSearchRejected|1 reason 9"]}}class mi extends si{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mi).fromBinary(t,r)}static fromJson(t,r){return(new mi).fromJson(t,r)}static fromJsonString(t,r){return(new mi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mi,t,r)}static $(){return["XSearchToolCall|1 args #0|2 result #1",ii,oi]}}class fi extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class di extends fi{constructor(t){super(),this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new di).fromBinary(t,r)}static fromJson(t,r){return(new di).fromJson(t,r)}static fromJsonString(t,r){return(new di).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(di,t,r)}static $(){return["GetPrCodeTourArgs|1 tool_call_id 9|2 revision_id 9?|3 section_id 9?|4 head_sha 9?|5 pr_url 9?"]}}class pi extends fi{constructor(t){super(),this.revisionId="",this.status="",this.headSha="",this.feedback="",this.updatedAtMs=n.protoInt64.zero,this.isCurrent=!1,this.markdown="",this.source="",this.prUrl="",this.editedByBcId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pi).fromBinary(t,r)}static fromJson(t,r){return(new pi).fromJson(t,r)}static fromJsonString(t,r){return(new pi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pi,t,r)}static $(){return["PrCodeTourRevisionSnapshot|1 revision_id 9|2 status 9|3 head_sha 9|4 feedback 9|5 updated_at_ms 3|6 is_current 8|7 markdown 9|8 source 9|9 pr_url 9|10 edited_by_bc_id 9"]}}class hi extends fi{constructor(t){super(),this.revisions=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hi).fromBinary(t,r)}static fromJson(t,r){return(new hi).fromJson(t,r)}static fromJsonString(t,r){return(new hi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hi,t,r)}static $(){return["GetPrCodeTourSuccess|1 revisions #0*|2 section_id 9?",pi]}}class gi extends fi{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gi).fromBinary(t,r)}static fromJson(t,r){return(new gi).fromJson(t,r)}static fromJsonString(t,r){return(new gi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gi,t,r)}static $(){return["GetPrCodeTourError|1 error 9"]}}class _i extends fi{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _i).fromBinary(t,r)}static fromJson(t,r){return(new _i).fromJson(t,r)}static fromJsonString(t,r){return(new _i).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_i,t,r)}static $(){return["GetPrCodeTourResult|1 success #0 result|2 error #1 result",hi,gi]}}class Ji extends fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ji).fromBinary(t,r)}static fromJson(t,r){return(new Ji).fromJson(t,r)}static fromJsonString(t,r){return(new Ji).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ji,t,r)}static $(){return["GetPrCodeTourToolCall|1 args #0|2 result #1",di,_i]}}const wi="agent.v1.";class yi extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return wi}}var Si=(0,o.QT)(n.proto3,wi,"UpdatePrCodeTourExecutionMode",[[0,"UNSPECIFIED"],[1,"SERVER_SCHEDULED"],[2,"CLIENT_REQUIRED"],[3,"SKIPPED"],[4,"EDITED"]],1);class qi extends yi{constructor(t){super(),this.feedback="",this.toolCallId="",this.scopeCommitHashes=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qi).fromBinary(t,r)}static fromJson(t,r){return(new qi).fromJson(t,r)}static fromJsonString(t,r){return(new qi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qi,t,r)}static $(){return["UpdatePrCodeTourArgs|1 feedback 9|2 tool_call_id 9|3 base_sha 9?|4 head_sha 9?|5 source_revision_id 9?|6 revision_id 9?|7 markdown 9?|8 heading 9?|9 artifact_path 9?|10 artifact_alt 9?|11 scope_commit_hashes 9*|12 explicit_user_prompt 9?|13 pr_url 9?"]}}class Bi extends yi{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bi).fromBinary(t,r)}static fromJson(t,r){return(new Bi).fromJson(t,r)}static fromJsonString(t,r){return(new Bi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bi,t,r)}static $(){return["UpdatePrCodeTourResult|1 success #0 result|2 error #1 result",Ii,Pi]}}class Ii extends yi{constructor(t){super(),this.revisionId="",this.message="",this.executionMode=Si.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ii).fromBinary(t,r)}static fromJson(t,r){return(new Ii).fromJson(t,r)}static fromJsonString(t,r){return(new Ii).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ii,t,r)}static $(){return["UpdatePrCodeTourSuccess|1 revision_id 9|2 message 9|3 execution_mode #0",Si]}}class Pi extends yi{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pi).fromBinary(t,r)}static fromJson(t,r){return(new Pi).fromJson(t,r)}static fromJsonString(t,r){return(new Pi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pi,t,r)}static $(){return["UpdatePrCodeTourError|1 error 9"]}}class bi extends yi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bi).fromBinary(t,r)}static fromJson(t,r){return(new bi).fromJson(t,r)}static fromJsonString(t,r){return(new bi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bi,t,r)}static $(){return["UpdatePrCodeTourToolCall|1 args #0|2 result #1",qi,Bi]}}const Ri="agent.v1.";class vi extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return Ri}}var xi=(0,o.QT)(n.proto3,Ri,"ExecuteOutcome",[[0,"UNSPECIFIED"],[1,"COMPLETED"],[2,"FAILED"],[3,"CANCELLED"]],1);class ki extends vi{constructor(t){super(),this.code="",this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ki).fromBinary(t,r)}static fromJson(t,r){return(new ki).fromJson(t,r)}static fromJsonString(t,r){return(new ki).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ki,t,r)}static $(){return["ExecuteArgs|1 code 9|2 tool_call_id 9"]}}class Ei extends vi{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ei).fromBinary(t,r)}static fromJson(t,r){return(new Ei).fromJson(t,r)}static fromJsonString(t,r){return(new Ei).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ei,t,r)}static $(){return["ExecuteResult|1 success #0 result|2 error #1 result|3 rejected #2 result",Ci,Ti,Ui]}}class Ci extends vi{constructor(t){super(),this.output="",this.outcome=xi.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ci).fromBinary(t,r)}static fromJson(t,r){return(new Ci).fromJson(t,r)}static fromJsonString(t,r){return(new Ci).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ci,t,r)}static $(){return["ExecuteSuccess|1 output 9|2 outcome #0",xi]}}class Ti extends vi{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ti).fromBinary(t,r)}static fromJson(t,r){return(new Ti).fromJson(t,r)}static fromJsonString(t,r){return(new Ti).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ti,t,r)}static $(){return["ExecuteError|1 error 9"]}}class Ui extends vi{constructor(t){super(),this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ui).fromBinary(t,r)}static fromJson(t,r){return(new Ui).fromJson(t,r)}static fromJsonString(t,r){return(new Ui).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ui,t,r)}static $(){return["ExecuteRejected|1 reason 9"]}}class Ai extends vi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ai).fromBinary(t,r)}static fromJson(t,r){return(new Ai).fromJson(t,r)}static fromJsonString(t,r){return(new Ai).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ai,t,r)}static $(){return["ExecuteToolCall|1 args #0|2 result #1",ki,Ei]}}var $i=e("../proto/dist/generated/agent/v1/hook_additional_context_pb.js"),Mi=e("../proto/dist/generated/agent/v1/request_context_exec_pb.js"),Oi=e("../proto/dist/generated/agent/v1/selected_context_pb.js"),Di=e("../proto/dist/generated/agent/v1/requested_model_pb.js"),Ni=e("../proto/dist/generated/agent/v1/mcp_pb.js"),Gi=e("../proto/dist/generated/agent/v1/system_prompt_pb.js");const Li="agent.v1.";class Fi extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return Li}}var Ki=(0,o.QT)(n.proto3,Li,"AgentMode",[[0,"UNSPECIFIED"],[1,"AGENT"],[2,"ASK"],[3,"PLAN"],[4,"DEBUG"],[5,"TRIAGE"],[7,"MULTITASK"],[8,"CUSTOM"]],1),zi=(0,o.QT)(n.proto3,Li,"BackgroundTaskKind",[[0,"UNSPECIFIED"],[1,"SHELL"],[2,"SUBAGENT"]],1),ji=(0,o.QT)(n.proto3,Li,"BackgroundTaskStatus",[[0,"UNSPECIFIED"],[1,"SUCCESS"],[2,"ERROR"],[3,"ABORTED"]],1),Hi=(0,o.QT)(n.proto3,Li,"BackgroundTaskNotificationContext",[[0,"UNSPECIFIED"],[1,"USER_DRIVEN_INTERACTIVE_CHILD"]],1),Wi=(0,o.QT)(n.proto3,Li,"SubagentRunStatus",[[0,"UNSPECIFIED"],[1,"RUNNING"],[2,"BACKGROUNDED"],[3,"SUCCESS"],[4,"ERROR"],[5,"ABORTED"]],1),Qi=(0,o.QT)(n.proto3,Li,"SubagentDispatchTool",[[0,"UNSPECIFIED"],[1,"TASK"],[2,"CREATE_AGENT"],[3,"SEND_TO_AGENT"],[4,"CREATE_PROJECT"]],1),Vi=(0,o.QT)(n.proto3,Li,"CustomModeSource",[[0,"UNSPECIFIED"],[1,"AGENT_SKILL"],[2,"PLUGIN_SKILL"],[3,"REPO_SKILL"],[4,"MANAGED_SKILL"]],1),Xi=(0,o.QT)(n.proto3,Li,"SimulatedMsgReason",[[0,"UNSPECIFIED"],[1,"PLAN_EXECUTION"],[2,"COMMIT_REMINDER"],[3,"BACKGROUND_TASK_COMPLETION"],[4,"DIFF_TAB_COMMIT"],[5,"DIFF_TAB_COMMIT_AND_PUSH"],[6,"DIFF_TAB_PUSH"],[7,"DIFF_TAB_CREATE_PR"],[8,"DIFF_TAB_FIX_MERGE_CONFLICTS"],[9,"USER_SENT_TO_SUBAGENT"],[10,"USER_INTERRUPTED_SUBAGENT"],[11,"USER_QUEUED_TO_SUBAGENT"],[12,"BABYSIT_PR_IN_CLOUD"],[13,"CI_PANEL_INVESTIGATE_FAILURE"],[14,"MULTITASK"],[15,"BUILD_IN_PARALLEL"],[16,"MULTITASK_SPLIT_PRS"],[17,"APPLY_LOCALLY"],[18,"CHECKOUT_BRANCH"],[19,"DIFF_TAB_UPDATE_BRANCH"],[20,"PR_TAB_BUGBOT_FIX"],[22,"RUN_BUGBOT_REVIEW"],[23,"RUN_SECURITY_REVIEW"],[24,"FSD_APPLY_FINDING"],[25,"FSD_UNDO_FINDING"],[26,"FSD_START"],[27,"FSD_PR_INTERRUPT"],[28,"SUBSCRIPTION"],[29,"DIFF_TAB_CREATE_BRANCH"],[30,"AGENT_STORE_CONFLICT"],[31,"GOAL_CONTINUATION"],[32,"PROJECT_KICKOFF"],[33,"MARKDOWN_PROMPT_BUTTON"],[34,"USER_QUICK_ACTION"],[35,"INTERACTION_RESPONSE"],[36,"DESKTOP_CONTROL"]],1),Yi=(0,o.QT)(n.proto3,Li,"SubscriptionSource",[[0,"UNSPECIFIED"],[1,"SLACK"],[2,"GITHUB"],[3,"LINEAR"],[4,"ORIGIN"],[5,"FACTORY"]],1),Zi=(0,o.QT)(n.proto3,Li,"ReplyAudience",[[0,"UNSPECIFIED"],[1,"USER"],[2,"AGENT"]],1),to=(0,o.QT)(n.proto3,Li,"TurnRunStatus",[[0,"UNSPECIFIED"],[1,"RUNNING"],[2,"COMPLETED"],[3,"FAILED"],[4,"INTERRUPTED"]],1),ro=(0,o.QT)(n.proto3,Li,"TurnInterruptReason",[[0,"UNSPECIFIED"],[1,"CANCELLED"],[2,"MAX_STEPS"]],1),eo=(0,o.QT)(n.proto3,Li,"ThinkingStyle",[[0,"UNSPECIFIED"],[1,"DEFAULT"],[2,"CODEX"],[3,"GPT5"]],1),no=(0,o.QT)(n.proto3,Li,"EstimatedCostSource",[[0,"UNSPECIFIED"],[1,"CATALOG"],[2,"USAGE"]],1),so=(0,o.QT)(n.proto3,Li,"ResponseComparisonDisplayOrder",[[0,"UNSPECIFIED"],[1,"PARENT_FIRST"],[2,"ALTERNATE_FIRST"]],1),io=(0,o.QT)(n.proto3,Li,"ResponseComparisonSkipReason",[[0,"UNSPECIFIED"],[1,"ALTERNATE_TOOL_CALL"],[2,"INFERENCE_ERROR"],[3,"TIMEOUT"],[4,"CANCELLED"]],1),oo=(0,o.QT)(n.proto3,Li,"PostRequestPromptButtonAction",[[0,"UNSPECIFIED"],[1,"UPDATE_CLIENT"]],1);class ao extends Fi{constructor(t){super(),this.description="",this.prompt="",this.attachments=[],this.mode=s.FL.UNSPECIFIED,this.respondingToMessageIds=[],this.environment=s.dU.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ao).fromBinary(t,r)}static fromJson(t,r){return(new ao).fromJson(t,r)}static fromJsonString(t,r){return(new ao).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ao,t,r)}static $(){return["TaskArgs|1 description 9|2 prompt 9|3 subagent_type #0|4 model 9?|5 resume 9?|6 agent_id 9?|7 attachments 9*|8 mode #1|9 responding_to_message_ids 9*|10 environment #2|11 machine #3?",s._L,s.FL,s.dU,uo]}}class uo extends Fi{constructor(t){super(),this.machine={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uo).fromBinary(t,r)}static fromJson(t,r){return(new uo).fromJson(t,r)}static fromJsonString(t,r){return(new uo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uo,t,r)}static $(){return["TargetMachine|1 same_machine #0 machine|2 new_cloud_vm #1 machine|3 self_hosted_worker #2 machine|4 self_hosted_pool #3 machine",co,lo,mo,fo]}}class co extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new co).fromBinary(t,r)}static fromJson(t,r){return(new co).fromJson(t,r)}static fromJsonString(t,r){return(new co).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(co,t,r)}static $(){return["SameMachineTarget"]}}class lo extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lo).fromBinary(t,r)}static fromJson(t,r){return(new lo).fromJson(t,r)}static fromJsonString(t,r){return(new lo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lo,t,r)}static $(){return["NewCloudVmTarget|1 environment_build_id 9?|2 base_branch 9?|4 environment_id 9?|5 repo_url 9?"]}}class mo extends Fi{constructor(t){super(),this.workerId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mo).fromBinary(t,r)}static fromJson(t,r){return(new mo).fromJson(t,r)}static fromJsonString(t,r){return(new mo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mo,t,r)}static $(){return["SelfHostedWorkerTarget|1 worker_id 9"]}}class fo extends Fi{constructor(t){super(),this.labels=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fo).fromBinary(t,r)}static fromJson(t,r){return(new fo).fromJson(t,r)}static fromJsonString(t,r){return(new fo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fo,t,r)}static $(){return["SelfHostedPoolTarget|1 pool 9?|2 labels #0*",po]}}class po extends Fi{constructor(t){super(),this.key="",this.value="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new po).fromBinary(t,r)}static fromJson(t,r){return(new po).fromJson(t,r)}static fromJsonString(t,r){return(new po).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(po,t,r)}static $(){return["SelfHostedWorkerLabel|1 key 9|2 value 9"]}}class ho extends Fi{constructor(t){super(),this.conversationSteps=[],this.isBackground=!1,this.backgroundReason=s.qL.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ho).fromBinary(t,r)}static fromJson(t,r){return(new ho).fromJson(t,r)}static fromJsonString(t,r){return(new ho).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ho,t,r)}static $(){return["TaskSuccess|1 conversation_steps #0*|2 agent_id 9?|3 is_background 8|4 duration_ms 4?|5 result_suffix 9?|6 background_reason #1|7 transcript_path 9?",Co,s.qL]}}class go extends Fi{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new go).fromBinary(t,r)}static fromJson(t,r){return(new go).fromJson(t,r)}static fromJsonString(t,r){return(new go).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(go,t,r)}static $(){return["TaskError|1 error 9"]}}class _o extends Fi{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _o).fromBinary(t,r)}static fromJson(t,r){return(new _o).fromJson(t,r)}static fromJsonString(t,r){return(new _o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_o,t,r)}static $(){return["TaskResult|1 success #0 result|2 error #1 result",ho,go]}}class Jo extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jo).fromBinary(t,r)}static fromJson(t,r){return(new Jo).fromJson(t,r)}static fromJsonString(t,r){return(new Jo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jo,t,r)}static $(){return["TaskToolCall|1 args #0|2 result #1|3 cloud_agent_bc_id 9?",ao,_o]}}class wo extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wo).fromBinary(t,r)}static fromJson(t,r){return(new wo).fromJson(t,r)}static fromJsonString(t,r){return(new wo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wo,t,r)}static $(){return["TaskToolCallDelta|1 interaction_update #0",ac]}}class yo extends Fi{constructor(t){super(),this.path="",this.branchName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yo).fromBinary(t,r)}static fromJson(t,r){return(new yo).fromJson(t,r)}static fromJsonString(t,r){return(new yo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yo,t,r)}static $(){return["SetActiveBranchArgs|1 path 9|2 branch_name 9"]}}class So extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new So).fromBinary(t,r)}static fromJson(t,r){return(new So).fromJson(t,r)}static fromJsonString(t,r){return(new So).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(So,t,r)}static $(){return["SetActiveBranchSuccess"]}}class qo extends Fi{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qo).fromBinary(t,r)}static fromJson(t,r){return(new qo).fromJson(t,r)}static fromJsonString(t,r){return(new qo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qo,t,r)}static $(){return["SetActiveBranchError|1 error 9"]}}class Bo extends Fi{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bo).fromBinary(t,r)}static fromJson(t,r){return(new Bo).fromJson(t,r)}static fromJsonString(t,r){return(new Bo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bo,t,r)}static $(){return["SetActiveBranchResult|1 success #0 result|2 error #1 result",So,qo]}}class Io extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Io).fromBinary(t,r)}static fromJson(t,r){return(new Io).fromJson(t,r)}static fromJsonString(t,r){return(new Io).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Io,t,r)}static $(){return["SetActiveBranchToolCall|1 args #0|2 result #1",yo,Bo]}}class Po extends Fi{constructor(t){super(),this.tool={case:void 0},this.hookAdditionalContexts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Po).fromBinary(t,r)}static fromJson(t,r){return(new Po).fromJson(t,r)}static fromJsonString(t,r){return(new Po).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Po,t,r)}static $(){return["ToolCall|1 shell_tool_call #0 tool|3 delete_tool_call #1 tool|4 glob_tool_call #2 tool|5 grep_tool_call #3 tool|8 read_tool_call #4 tool|9 update_todos_tool_call #5 tool|10 read_todos_tool_call #6 tool|12 edit_tool_call #7 tool|13 ls_tool_call #8 tool|14 read_lints_tool_call #9 tool|15 mcp_tool_call #10 tool|16 sem_search_tool_call #11 tool|17 create_plan_tool_call #12 tool|18 web_search_tool_call #13 tool|19 task_tool_call #14 tool|20 list_mcp_resources_tool_call #15 tool|21 read_mcp_resource_tool_call #16 tool|22 apply_agent_diff_tool_call #17 tool|23 ask_question_tool_call #18 tool|24 fetch_tool_call #19 tool|25 switch_mode_tool_call #20 tool|28 generate_image_tool_call #21 tool|29 record_screen_tool_call #22 tool|30 computer_use_tool_call #23 tool|31 write_shell_stdin_tool_call #24 tool|32 reflect_tool_call #25 tool|33 setup_vm_environment_tool_call #26 tool|34 truncated_tool_call #27 tool|35 start_grind_execution_tool_call #28 tool|36 start_grind_planning_tool_call #29 tool|37 web_fetch_tool_call #30 tool|38 report_bugfix_results_tool_call #31 tool|39 ai_attribution_tool_call #32 tool|40 pr_management_tool_call #33 tool|41 mcp_auth_tool_call #34 tool|42 await_tool_call #35 tool|43 blame_by_file_path_tool_call #36 tool|44 get_mcp_tools_tool_call #37 tool|45 report_bug_tool_call #38 tool|46 set_active_branch_tool_call #39 tool|48 communicate_update_tool_call #40 tool|49 send_final_summary_tool_call #41 tool|51 replace_env_tool_call #42 tool|52 edit_pr_labels_tool_call #43 tool|53 record_ci_investigation_findings_tool_call #44 tool|55 send_message_tool_call #45 tool|56 fetch_cloud_agent_data_tool_call #46 tool|58 send_to_user_tool_call #47 tool|68 connect_scm_tool_call #48 tool|69 search_conversations_tool_call #49 tool|70 create_goal_tool_call #50 tool|71 update_goal_tool_call #51 tool|73 get_agent_status_tool_call #52 tool|74 send_to_agent_tool_call #53 tool|75 read_agent_transcript_tool_call #54 tool|76 create_agent_tool_call #55 tool|77 stop_agent_tool_call #56 tool|79 write_canvas_tool_call #57 tool|80 read_canvas_tool_call #58 tool|81 generate_video_tool_call #59 tool|82 x_search_tool_call #60 tool|83 get_origin_pr_code_tour_tool_call #61 tool|84 update_origin_pr_code_tour_tool_call #62 tool|85 list_tracked_tasks_tool_call #63 tool|86 create_tracked_tasks_tool_call #64 tool|87 update_tracked_tasks_tool_call #65 tool|88 delete_tracked_tasks_tool_call #66 tool|89 update_tracked_task_statuses_tool_call #67 tool|90 create_project_tool_call #68 tool|91 update_tracked_task_tags_tool_call #69 tool|93 stop_project_updates_tool_call #70 tool|94 start_project_updates_tool_call #71 tool|95 manage_access_tool_call #72 tool|1000 execute_tool_call #73 tool|54 hook_additional_contexts #74*|57 tool_call_id 9?|59 started_at_ms 4?|60 completed_at_ms 4?",u,p,y,B,b,C.bk,C.AJ,L,j,V,ut,mt,gt.Ih,_t.pn,Jo,wt,yt,St.JU,qt.OU,Pt,bt.Cs,Rt.r9,kt,Et.t8,Ut,Nt,Gt.MU,ko,Ht,Zt,tr.fd,rr.U_,er.ex,nr.AU,sr.NX,fr,Jr,Ir,kr,Io,$r,Lr,Fr.us,Qr,ne,me,_e,Be,Ie.iO,Re,Ae,De,We,rn,an,fn,Dn,zs,Vs,ni,mi,Ji,bi,Zn,os,gs,Ss,Rs,_n,Ts,Rn,qn,Un,Ai,$i.C]}}class bo extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bo).fromBinary(t,r)}static fromJson(t,r){return(new bo).fromJson(t,r)}static fromJsonString(t,r){return(new bo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bo,t,r)}static $(){return["TruncatedToolCallArgs"]}}class Ro extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ro).fromBinary(t,r)}static fromJson(t,r){return(new Ro).fromJson(t,r)}static fromJsonString(t,r){return(new Ro).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ro,t,r)}static $(){return["TruncatedToolCallSuccess"]}}class vo extends Fi{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vo).fromBinary(t,r)}static fromJson(t,r){return(new vo).fromJson(t,r)}static fromJsonString(t,r){return(new vo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vo,t,r)}static $(){return["TruncatedToolCallError|1 error 9"]}}class xo extends Fi{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xo).fromBinary(t,r)}static fromJson(t,r){return(new xo).fromJson(t,r)}static fromJsonString(t,r){return(new xo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xo,t,r)}static $(){return["TruncatedToolCallResult|1 success #0 result|2 error #1 result",Ro,vo]}}class ko extends Fi{constructor(t){super(),this.originalStepBlobId=new Uint8Array(0),this.originalStepSizeBytes=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ko).fromBinary(t,r)}static fromJson(t,r){return(new ko).fromJson(t,r)}static fromJsonString(t,r){return(new ko).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ko,t,r)}static $(){return["TruncatedToolCall|1 original_step_blob_id 12|2 args #0|3 result #1|4 original_step_size_bytes 13|5 preview #2",bo,xo,Po]}}class Eo extends Fi{constructor(t){super(),this.delta={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Eo).fromBinary(t,r)}static fromJson(t,r){return(new Eo).fromJson(t,r)}static fromJsonString(t,r){return(new Eo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Eo,t,r)}static $(){return["ToolCallDelta|1 shell_tool_call_delta #0 delta|2 task_tool_call_delta #1 delta|3 edit_tool_call_delta #2 delta|4 replace_env_tool_call_delta #3 delta",m,wo,F,Fr.km]}}class Co extends Fi{constructor(t){super(),this.message={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Co).fromBinary(t,r)}static fromJson(t,r){return(new Co).fromJson(t,r)}static fromJsonString(t,r){return(new Co).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Co,t,r)}static $(){return["ConversationStep|1 assistant_message #0 message|2 tool_call #1 message|3 thinking_message #2 message",Oa,Po,Da]}}class To extends Fi{constructor(t){super(),this.action={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new To).fromBinary(t,r)}static fromJson(t,r){return(new To).fromJson(t,r)}static fromJsonString(t,r){return(new To).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(To,t,r)}static $(){return["ConversationAction|1 user_message_action #0 action|2 resume_action #1 action|3 cancel_action #2 action|4 summarize_action #3 action|5 shell_command_action #4 action|6 start_plan_action #5 action|7 execute_plan_action #6 action|8 async_ask_question_completion_action #7 action|10 cancel_subagent_action #8 action|12 background_task_completion_action #9 action|13 background_shell_action #10 action|14 background_subagent_action #11 action|16 subscription_notification_action #12 action|18 goal_continuation_action #13 action|19 inject_context_action #14 action|11 triggering_auth_id 9?|15 triggering_user_info #15?|17 request_context_parts #16?",sa,qa,Sa,Ia,Pa,ba,Ra,Ba,No,Ao,Go,Lo,ia,oa,aa,Uo,Mi.sG]}}class Uo extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Uo).fromBinary(t,r)}static fromJson(t,r){return(new Uo).fromJson(t,r)}static fromJsonString(t,r){return(new Uo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Uo,t,r)}static $(){return["TriggeringUserInfo|1 auth_id 9?|2 user_id 5?|3 followup_id 9?"]}}class Ao extends Fi{constructor(t){super(),this.completions=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ao).fromBinary(t,r)}static fromJson(t,r){return(new Ao).fromJson(t,r)}static fromJsonString(t,r){return(new Ao).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ao,t,r)}static $(){return["BackgroundTaskCompletionAction|1 completions #0*|2 system_reminder 9?|3 request_context #1",$o,Mi.bb]}}class $o extends Fi{constructor(t){super(),this.taskId="",this.kind=zi.UNSPECIFIED,this.status=ji.UNSPECIFIED,this.title="",this.reason=s.U6.UNSPECIFIED,this.notificationContext=Hi.UNSPECIFIED,this.recordOnly=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $o).fromBinary(t,r)}static fromJson(t,r){return(new $o).fromJson(t,r)}static fromJsonString(t,r){return(new $o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($o,t,r)}static $(){return["BackgroundTaskCompletion|1 task_id 9|2 kind #0|3 status #1|4 title 9|5 detail 9?|6 output_path 9?|7 thread_id 9?|8 reason #2|9 subagent_id 9?|10 tool_call_id 9?|11 notification_context #3|12 completed_at_ms 4?|13 record_only 8|14 subagent_state #4?",zi,ji,s.U6,Hi,Mo]}}class Mo extends Fi{constructor(t){super(),this.subagentId="",this.blobId=new Uint8Array(0),this.recordedByParentTurn=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mo).fromBinary(t,r)}static fromJson(t,r){return(new Mo).fromJson(t,r)}static fromJsonString(t,r){return(new Mo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mo,t,r)}static $(){return["SubagentStatePointer|1 subagent_id 9|2 blob_id 12|3 recorded_by_parent_turn 8"]}}class Oo extends Fi{constructor(t){super(),this.parentToolCallId="",this.environment=s.dU.UNSPECIFIED,this.status=Wi.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Oo).fromBinary(t,r)}static fromJson(t,r){return(new Oo).fromJson(t,r)}static fromJsonString(t,r){return(new Oo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Oo,t,r)}static $(){return["SubagentRunState|1 parent_tool_call_id 9|2 subagent_id 9?|3 environment #0|4 status #1|5 title 9?|6 detail 9?|7 transcript_path 9?|8 output_path 9?|9 completed_timestamp_ms 4?|10 completion_reason #2?",s.dU,Wi,s.U6]}}class Do extends Fi{constructor(t){super(),this.stepIndex=0,this.toolCallId="",this.tool=Qi.UNSPECIFIED,this.backgrounded=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Do).fromBinary(t,r)}static fromJson(t,r){return(new Do).fromJson(t,r)}static fromJsonString(t,r){return(new Do).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Do,t,r)}static $(){return["SubagentDispatchStep|1 step_index 13|2 tool_call_id 9|3 tool #0|4 backgrounded 8",Qi]}}class No extends Fi{constructor(t){super(),this.subagentId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new No).fromBinary(t,r)}static fromJson(t,r){return(new No).fromJson(t,r)}static fromJsonString(t,r){return(new No).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(No,t,r)}static $(){return["CancelSubagentAction|1 subagent_id 9"]}}class Go extends Fi{constructor(t){super(),this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Go).fromBinary(t,r)}static fromJson(t,r){return(new Go).fromJson(t,r)}static fromJsonString(t,r){return(new Go).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Go,t,r)}static $(){return["BackgroundShellAction|1 tool_call_id 9"]}}class Lo extends Fi{constructor(t){super(),this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lo).fromBinary(t,r)}static fromJson(t,r){return(new Lo).fromJson(t,r)}static fromJsonString(t,r){return(new Lo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Lo,t,r)}static $(){return["BackgroundSubagentAction|1 tool_call_id 9"]}}class Fo extends Fi{constructor(t){super(),this.toolCallId="",this.resolution={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fo).fromBinary(t,r)}static fromJson(t,r){return(new Fo).fromJson(t,r)}static fromJsonString(t,r){return(new Fo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fo,t,r)}static $(){return["InterruptedPendingToolCallResolution|1 tool_call_id 9|2 shell_result #0 resolution|3 task_result #1 resolution",i.W4,_o]}}class Ko extends Fi{constructor(t){super(),this.resolutions=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ko).fromBinary(t,r)}static fromJson(t,r){return(new Ko).fromJson(t,r)}static fromJsonString(t,r){return(new Ko).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ko,t,r)}static $(){return["InterruptedPendingToolCallResolutions|1 resolutions #0*",Fo]}}class zo extends Fi{constructor(t){super(),this.messages=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zo).fromBinary(t,r)}static fromJson(t,r){return(new zo).fromJson(t,r)}static fromJsonString(t,r){return(new zo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zo,t,r)}static $(){return["ConversationHistory|1 messages #0*|2 replace_user_info 8?",jo]}}class jo extends Fi{constructor(t){super(),this.message={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jo).fromBinary(t,r)}static fromJson(t,r){return(new jo).fromJson(t,r)}static fromJsonString(t,r){return(new jo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jo,t,r)}static $(){return["ConversationHistoryMessage|1 user #0 message|2 assistant #1 message|3 tool #2 message",Ho,Xo,ea]}}class Ho extends Fi{constructor(t){super(),this.content=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ho).fromBinary(t,r)}static fromJson(t,r){return(new Ho).fromJson(t,r)}static fromJsonString(t,r){return(new Ho).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ho,t,r)}static $(){return["ConversationHistoryUserMessage|1 content #0*",Wo]}}class Wo extends Fi{constructor(t){super(),this.content={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wo).fromBinary(t,r)}static fromJson(t,r){return(new Wo).fromJson(t,r)}static fromJsonString(t,r){return(new Wo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wo,t,r)}static $(){return["ConversationHistoryUserContent|1 text #0 content|2 image #1 content",Qo,Vo]}}class Qo extends Fi{constructor(t){super(),this.text="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qo).fromBinary(t,r)}static fromJson(t,r){return(new Qo).fromJson(t,r)}static fromJsonString(t,r){return(new Qo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qo,t,r)}static $(){return["ConversationHistoryTextContent|1 text 9"]}}class Vo extends Fi{constructor(t){super(),this.data="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vo).fromBinary(t,r)}static fromJson(t,r){return(new Vo).fromJson(t,r)}static fromJsonString(t,r){return(new Vo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vo,t,r)}static $(){return["ConversationHistoryImageContent|1 data 9|2 mime_type 9?"]}}class Xo extends Fi{constructor(t){super(),this.content=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xo).fromBinary(t,r)}static fromJson(t,r){return(new Xo).fromJson(t,r)}static fromJsonString(t,r){return(new Xo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xo,t,r)}static $(){return["ConversationHistoryAssistantMessage|1 content #0*",Yo]}}class Yo extends Fi{constructor(t){super(),this.content={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yo).fromBinary(t,r)}static fromJson(t,r){return(new Yo).fromJson(t,r)}static fromJsonString(t,r){return(new Yo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yo,t,r)}static $(){return["ConversationHistoryAssistantContent|1 text #0 content|2 reasoning #1 content|3 redacted_reasoning #2 content|4 tool_call #3 content",Qo,Zo,ta,ra]}}class Zo extends Fi{constructor(t){super(),this.text="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zo).fromBinary(t,r)}static fromJson(t,r){return(new Zo).fromJson(t,r)}static fromJsonString(t,r){return(new Zo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zo,t,r)}static $(){return["ConversationHistoryReasoningContent|1 text 9|2 signature 9?"]}}class ta extends Fi{constructor(t){super(),this.data="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ta).fromBinary(t,r)}static fromJson(t,r){return(new ta).fromJson(t,r)}static fromJsonString(t,r){return(new ta).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ta,t,r)}static $(){return["ConversationHistoryRedactedReasoningContent|1 data 9"]}}class ra extends Fi{constructor(t){super(),this.toolCallId="",this.toolName="",this.argsJson="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ra).fromBinary(t,r)}static fromJson(t,r){return(new ra).fromJson(t,r)}static fromJsonString(t,r){return(new ra).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ra,t,r)}static $(){return["ConversationHistoryToolCall|1 tool_call_id 9|2 tool_name 9|3 args_json 9"]}}class ea extends Fi{constructor(t){super(),this.toolCallId="",this.toolName="",this.content=[],this.hookAdditionalContexts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ea).fromBinary(t,r)}static fromJson(t,r){return(new ea).fromJson(t,r)}static fromJsonString(t,r){return(new ea).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ea,t,r)}static $(){return["ConversationHistoryToolMessage|1 tool_call_id 9|2 tool_name 9|3 content #0*|4 is_error 8?|5 hook_additional_contexts #1*",na,$i.C]}}class na extends Fi{constructor(t){super(),this.content={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new na).fromBinary(t,r)}static fromJson(t,r){return(new na).fromJson(t,r)}static fromJsonString(t,r){return(new na).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(na,t,r)}static $(){return["ConversationHistoryToolResultContent|1 text #0 content|2 image #1 content",Qo,Vo]}}class sa extends Fi{constructor(t){super(),this.prependUserMessages=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sa).fromBinary(t,r)}static fromJson(t,r){return(new sa).fromJson(t,r)}static fromJsonString(t,r){return(new sa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sa,t,r)}static $(){return["UserMessageAction|1 user_message #0|2 request_context #1|3 send_to_interaction_listener 8?|4 prepend_user_messages #0*|6 interrupted_pending_tool_call_resolutions #2?|7 conversation_history #3?|8 trailing_conversation_history #3?",Ua,Mi.bb,Ko,zo]}}class ia extends Fi{constructor(t){super(),this.notifications=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ia).fromBinary(t,r)}static fromJson(t,r){return(new ia).fromJson(t,r)}static fromJsonString(t,r){return(new ia).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ia,t,r)}static $(){return["SubscriptionNotificationAction|1 notifications #0*|2 request_context #1|3 send_to_interaction_listener 8?",Ua,Mi.bb]}}class oa extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oa).fromBinary(t,r)}static fromJson(t,r){return(new oa).fromJson(t,r)}static fromJsonString(t,r){return(new oa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oa,t,r)}static $(){return["GoalContinuationAction"]}}class aa extends Fi{constructor(t){super(),this.injectionId="",this.expectedRunId="",this.payload={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aa).fromBinary(t,r)}static fromJson(t,r){return(new aa).fromJson(t,r)}static fromJsonString(t,r){return(new aa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aa,t,r)}static $(){return["InjectContextAction|1 injection_id 9|2 expected_run_id 9|3 user_context #0 payload|4 system_context #1 payload",ua,ca]}}class ua extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ua).fromBinary(t,r)}static fromJson(t,r){return(new ua).fromJson(t,r)}static fromJsonString(t,r){return(new ua).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ua,t,r)}static $(){return["UserContextInjection|1 user_message #0|2 request_context #1",Ua,Mi.bb]}}class ca extends Fi{constructor(t){super(),this.producer="",this.content="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ca).fromBinary(t,r)}static fromJson(t,r){return(new ca).fromJson(t,r)}static fromJsonString(t,r){return(new ca).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ca,t,r)}static $(){return["SystemContextInjection|1 producer 9|2 content 9"]}}class la extends Fi{constructor(t){super(),this.state={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new la).fromBinary(t,r)}static fromJson(t,r){return(new la).fromJson(t,r)}static fromJsonString(t,r){return(new la).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(la,t,r)}static $(){return["ContextInjectionState|1 queued #0 state|2 delivered #1 state|3 queued_for_next_turn #2 state|4 cancelled #3 state|5 rejected #4 state",ma,fa,da,pa,ha]}}class ma extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ma).fromBinary(t,r)}static fromJson(t,r){return(new ma).fromJson(t,r)}static fromJsonString(t,r){return(new ma).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ma,t,r)}static $(){return["ContextInjectionQueued"]}}class fa extends Fi{constructor(t){super(),this.step=0,this.deliveryBatchId="",this.deliveredAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fa).fromBinary(t,r)}static fromJson(t,r){return(new fa).fromJson(t,r)}static fromJsonString(t,r){return(new fa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fa,t,r)}static $(){return["ContextInjectionDelivered|1 step 5|2 delivery_batch_id 9|3 delivered_at_ms 3"]}}class da extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new da).fromBinary(t,r)}static fromJson(t,r){return(new da).fromJson(t,r)}static fromJsonString(t,r){return(new da).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(da,t,r)}static $(){return["ContextInjectionQueuedForNextTurn"]}}class pa extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pa).fromBinary(t,r)}static fromJson(t,r){return(new pa).fromJson(t,r)}static fromJsonString(t,r){return(new pa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pa,t,r)}static $(){return["ContextInjectionCancelled"]}}class ha extends Fi{constructor(t){super(),this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ha).fromBinary(t,r)}static fromJson(t,r){return(new ha).fromJson(t,r)}static fromJsonString(t,r){return(new ha).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ha,t,r)}static $(){return["ContextInjectionRejected|1 reason 9"]}}class ga extends Fi{constructor(t){super(),this.id="",this.label="",this.source=Vi.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ga).fromBinary(t,r)}static fromJson(t,r){return(new ga).fromJson(t,r)}static fromJsonString(t,r){return(new ga).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ga,t,r)}static $(){return["SubmittedCustomMode|1 id 9|2 label 9|5 source #0|6 source_path 9?|7 source_hash 9?|10 managed_skill_id 9?|11 plugin_id 9?|12 plugin_snapshot_token 9?",Vi]}}class _a extends Fi{constructor(t){super(),this.id="",this.label="",this.source=Vi.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _a).fromBinary(t,r)}static fromJson(t,r){return(new _a).fromJson(t,r)}static fromJsonString(t,r){return(new _a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_a,t,r)}static $(){return["CustomModeDescriptor|1 id 9|2 label 9|3 description 9?|4 icon 9?|5 color 9?|6 source #0|7 source_path 9?|8 source_hash 9?|9 managed_skill_id 9?|10 plugin_id 9?|11 plugin_snapshot_token 9?",Vi]}}class Ja extends Fi{constructor(t){super(),this.id="",this.label="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ja).fromBinary(t,r)}static fromJson(t,r){return(new Ja).fromJson(t,r)}static fromJsonString(t,r){return(new Ja).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ja,t,r)}static $(){return["SubmittedExitedCustomMode|1 id 9|2 label 9"]}}class wa extends Fi{constructor(t){super(),this.nextMode=Ki.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wa).fromBinary(t,r)}static fromJson(t,r){return(new wa).fromJson(t,r)}static fromJsonString(t,r){return(new wa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wa,t,r)}static $(){return["CustomModeExitIntent|1 next_mode #0|2 exited_mode #1",Ki,Ja]}}class ya extends Fi{constructor(t){super(),this.intent={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ya).fromBinary(t,r)}static fromJson(t,r){return(new ya).fromJson(t,r)}static fromJsonString(t,r){return(new ya).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ya,t,r)}static $(){return["CustomModeIntent|1 enter #0 intent|2 exit #1 intent",ga,wa]}}class Sa extends Fi{constructor(t){super(),this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sa).fromBinary(t,r)}static fromJson(t,r){return(new Sa).fromJson(t,r)}static fromJsonString(t,r){return(new Sa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sa,t,r)}static $(){return["CancelAction|1 reason 9|3 interrupted_pending_tool_call_resolutions #0?",Ko]}}class qa extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qa).fromBinary(t,r)}static fromJson(t,r){return(new qa).fromJson(t,r)}static fromJsonString(t,r){return(new qa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qa,t,r)}static $(){return["ResumeAction|2 request_context #0",Mi.bb]}}class Ba extends Fi{constructor(t){super(),this.originalToolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ba).fromBinary(t,r)}static fromJson(t,r){return(new Ba).fromJson(t,r)}static fromJsonString(t,r){return(new Ba).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ba,t,r)}static $(){return["AsyncAskQuestionCompletionAction|1 original_tool_call_id 9|2 original_args #0|3 result #1|4 request_context #2|5 during_voice_call 8?|6 voice_calls_read_utterances 8?",qt.ju,qt.tz,Mi.bb]}}class Ia extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ia).fromBinary(t,r)}static fromJson(t,r){return(new Ia).fromJson(t,r)}static fromJsonString(t,r){return(new Ia).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ia,t,r)}static $(){return["SummarizeAction"]}}class Pa extends Fi{constructor(t){super(),this.execId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pa).fromBinary(t,r)}static fromJson(t,r){return(new Pa).fromJson(t,r)}static fromJsonString(t,r){return(new Pa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pa,t,r)}static $(){return["ShellCommandAction|1 shell_command #0|2 exec_id 9",Na]}}class ba extends Fi{constructor(t){super(),this.isSpec=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ba).fromBinary(t,r)}static fromJson(t,r){return(new ba).fromJson(t,r)}static fromJsonString(t,r){return(new ba).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ba,t,r)}static $(){return["StartPlanAction|1 user_message #0|2 request_context #1|3 is_spec 8",Ua,Mi.bb]}}class Ra extends Fi{constructor(t){super(),this.executionMode=Ki.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ra).fromBinary(t,r)}static fromJson(t,r){return(new Ra).fromJson(t,r)}static fromJsonString(t,r){return(new Ra).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ra,t,r)}static $(){return["ExecutePlanAction|1 request_context #0|2 plan #1?|3 plan_file_uri 9?|4 plan_file_content 9?|5 execution_mode #2|6 kickoff_message_id 9?|7 plan_id 9?|8 plan_file_path 9?|9 during_voice_call 8?|10 voice_calls_read_utterances 8?",Mi.bb,Fa,Ki]}}class va extends Fi{constructor(t){super(),this.interactionId="",this.skippedQuestionIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new va).fromBinary(t,r)}static fromJson(t,r){return(new va).fromJson(t,r)}static fromJsonString(t,r){return(new va).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(va,t,r)}static $(){return["InteractionResponseMetadata|1 interaction_id 9|2 response #0?|3 skipped_question_ids 9*",fc]}}class xa extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xa).fromBinary(t,r)}static fromJson(t,r){return(new xa).fromJson(t,r)}static fromJsonString(t,r){return(new xa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xa,t,r)}static $(){return["SubscriptionEventDisplay|1 display_label 9?|2 resource_url 9?|3 subscription_id 9?|5 headline_action 9?|6 headline_subject 9?"]}}class ka extends Fi{constructor(t){super(),this.planId="",this.planTitle="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ka).fromBinary(t,r)}static fromJson(t,r){return(new ka).fromJson(t,r)}static fromJsonString(t,r){return(new ka).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ka,t,r)}static $(){return["ExecutePlanInfo|1 plan_id 9|2 plan_title 9"]}}class Ea extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ea).fromBinary(t,r)}static fromJson(t,r){return(new Ea).fromJson(t,r)}static fromJsonString(t,r){return(new Ea).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ea,t,r)}static $(){return["ProjectDetails|1 name 9?|2 subagent #0?|3 side_chat #1?|4 init_description 9?",Ca,Ta]}}class Ca extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ca).fromBinary(t,r)}static fromJson(t,r){return(new Ca).fromJson(t,r)}static fromJsonString(t,r){return(new Ca).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ca,t,r)}static $(){return["ProjectSubagentDetails|2 store_dir 9?"]}}class Ta extends Fi{constructor(t){super(),this.storeDir="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ta).fromBinary(t,r)}static fromJson(t,r){return(new Ta).fromJson(t,r)}static fromJsonString(t,r){return(new Ta).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ta,t,r)}static $(){return["ProjectSideChatDetails|1 store_dir 9"]}}class Ua extends Fi{constructor(t){super(),this.text="",this.messageId="",this.mode=Ki.UNSPECIFIED,this.conversationStateBlobId=new Uint8Array(0),this.hookAdditionalContexts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ua).fromBinary(t,r)}static fromJson(t,r){return(new Ua).fromJson(t,r)}static fromJsonString(t,r){return(new Ua).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ua,t,r)}static $(){return["UserMessage|1 text 9|2 message_id 9|3 selected_context #0?|4 mode #1|5 is_simulated_msg 8?|6 best_of_n_group_id 9?|7 try_use_best_of_n_promotion 8?|8 rich_text 9?|9 simulated_msg_reason #2?|10 conversation_state_blob_id 12|11 subagent_system_reminder 9?|13 triggering_user_info #3?|14 execute_plan_info #4?|15 simulated_message_metadata #5?|16 prompt_reference_id 9?|17 thread_id 9?|18 text_blob_id 12?|19 rich_text_blob_id 12?|21 hook_additional_contexts #6*|22 custom_mode_intent #7?|23 project_details #8?|24 turn_steer 8?|25 started_at_ms 4?|26 completed_at_ms 4?|27 sent_by_agent_id 9?|28 sent_by_voice_call 8?|29 sender #9?|30 forked_context 9?|31 reply_to 9?|32 reply_audience #10?|33 reply_to_tool_call_id 9?|34 during_voice_call 8?|35 inherits_voice_call 8?|36 voice_calls_read_utterances 8?|37 summarized_tool_call_id 9?|38 sender_time_zone 9?|39 reply_quote 9?",Oi.xv,Ki,Xi,Uo,ka,Aa,$i.C,ya,Ea,$a,Zi]}}class Aa extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Aa).fromBinary(t,r)}static fromJson(t,r){return(new Aa).fromJson(t,r)}static fromJsonString(t,r){return(new Aa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Aa,t,r)}static $(){return["UserMessage.SimulatedMessageMetadata|1 title 9?|2 task_id 9?|3 fsd_finding_action 9?|4 url 9?|5 subscription_source #0?|6 subscription_event_display #1?|7 interaction_response #2?|8 tool_call_id 9?",Yi,xa,va]}}class $a extends Fi{constructor(t){super(),this.kind=Ma.UNSPECIFIED,this.id="",this.displayName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $a).fromBinary(t,r)}static fromJson(t,r){return(new $a).fromJson(t,r)}static fromJsonString(t,r){return(new $a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($a,t,r)}static $(){return["MessageSender|1 kind #0|2 id 9|3 display_name 9",Ma]}}var Ma=(0,o.QT)(n.proto3,Li,"MessageSender.Kind",[[0,"UNSPECIFIED"],[1,"AGENT"],[2,"VOICE_CALL"],[3,"MAIN_BOT"],[4,"PROJECT"],[5,"PROJECT_SLACK"],[6,"PROJECT_TEAMMATE"]],1);class Oa extends Fi{constructor(t){super(),this.text="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Oa).fromBinary(t,r)}static fromJson(t,r){return(new Oa).fromJson(t,r)}static fromJsonString(t,r){return(new Oa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Oa,t,r)}static $(){return["AssistantMessage|1 text 9|2 started_at_ms 4?|3 completed_at_ms 4?"]}}class Da extends Fi{constructor(t){super(),this.text="",this.durationMs=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Da).fromBinary(t,r)}static fromJson(t,r){return(new Da).fromJson(t,r)}static fromJsonString(t,r){return(new Da).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Da,t,r)}static $(){return["ThinkingMessage|1 text 9|2 duration_ms 13|3 started_at_ms 4?|4 completed_at_ms 4?|5 narration 8?"]}}class Na extends Fi{constructor(t){super(),this.command="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Na).fromBinary(t,r)}static fromJson(t,r){return(new Na).fromJson(t,r)}static fromJsonString(t,r){return(new Na).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Na,t,r)}static $(){return["ShellCommand|1 command 9"]}}class Ga extends Fi{constructor(t){super(),this.stdout="",this.stderr="",this.exitCode=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ga).fromBinary(t,r)}static fromJson(t,r){return(new Ga).fromJson(t,r)}static fromJsonString(t,r){return(new Ga).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ga,t,r)}static $(){return["ShellOutput|1 stdout 9|2 stderr 9|3 exit_code 5"]}}class La extends Fi{constructor(t){super(),this.turn={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new La).fromBinary(t,r)}static fromJson(t,r){return(new La).fromJson(t,r)}static fromJsonString(t,r){return(new La).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(La,t,r)}static $(){return["ConversationTurn|1 agent_conversation_turn #0 turn|2 shell_conversation_turn #1 turn",Ha,Va]}}class Fa extends Fi{constructor(t){super(),this.plan="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fa).fromBinary(t,r)}static fromJson(t,r){return(new Fa).fromJson(t,r)}static fromJsonString(t,r){return(new Fa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fa,t,r)}static $(){return["ConversationPlan|1 plan 9"]}}class Ka extends Fi{constructor(t){super(),this.id="",this.path="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ka).fromBinary(t,r)}static fromJson(t,r){return(new Ka).fromJson(t,r)}static fromJsonString(t,r){return(new Ka).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ka,t,r)}static $(){return["PlanRegistryEntry|1 id 9|2 path 9"]}}class za extends Fi{constructor(t){super(),this.conversationId="",this.goalId="",this.objective="",this.status=ke.UNSPECIFIED,this.idleContinuationsWithoutToolCalls=0,this.continuationCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new za).fromBinary(t,r)}static fromJson(t,r){return(new za).fromJson(t,r)}static fromJsonString(t,r){return(new za).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(za,t,r)}static $(){return["GoalState|1 conversation_id 9|2 goal_id 9|3 objective 9|4 status #0|5 idle_continuations_without_tool_calls 13|6 active_duration_ms 4?|7 last_accrued_at_ms 4?|8 continuation_count 13|9 agent_session_id 9?|11 context_tokens_added 3?",ke]}}class ja extends Fi{constructor(t){super(),this.turn={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ja).fromBinary(t,r)}static fromJson(t,r){return(new ja).fromJson(t,r)}static fromJsonString(t,r){return(new ja).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ja,t,r)}static $(){return["ConversationTurnStructure|1 agent_conversation_turn #0 turn|2 shell_conversation_turn #1 turn",Wa,Xa]}}class Ha extends Fi{constructor(t){super(),this.steps=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ha).fromBinary(t,r)}static fromJson(t,r){return(new Ha).fromJson(t,r)}static fromJsonString(t,r){return(new Ha).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ha,t,r)}static $(){return["AgentConversationTurn|1 user_message #0|2 steps #1*|3 request_id 9?",Ua,Co]}}class Wa extends Fi{constructor(t){super(),this.userMessage=new Uint8Array(0),this.steps=[],this.sendMessageStepIndices=[],this.subagentDispatchSteps=[],this.dynamicToolNames=[],this.longReasoningReminderExposureLogged=!1,this.assistantTextStepIndices=[],this.appSecretsRequestStepIndices=[],this.preferenceChangeStepIndices=[],this.unfoldedStepIndices=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wa).fromBinary(t,r)}static fromJson(t,r){return(new Wa).fromJson(t,r)}static fromJsonString(t,r){return(new Wa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wa,t,r)}static $(){return["AgentConversationTurnStructure|1 user_message 12|2 steps 12*|3 request_id 9?|4 encrypted_model 9?|5 dynamic_tool_count 13?|6 send_message_step_indices 13*|7 routed_model_display_name 9?|8 subagent_dispatch_steps #0*|9 dynamic_tool_names 9*|10 user_message_id 9?|11 long_reasoning_reminder #1?|12 long_reasoning_reminder_exposure_logged 8|13 assistant_text_step_indices 13*|14 assistant_text_steps_recorded 8?|15 app_secrets_request_step_indices 13*|16 preference_change_step_indices 13*|17 run #2?|18 thread_id 9?|19 unfolded_step_indices 13*",Do,Qa,lu]}}class Qa extends Fi{constructor(t){super(),this.remainingDelayCalls=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qa).fromBinary(t,r)}static fromJson(t,r){return(new Qa).fromJson(t,r)}static fromJsonString(t,r){return(new Qa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qa,t,r)}static $(){return["LongReasoningReminderState|1 remaining_delay_calls 13"]}}class Va extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Va).fromBinary(t,r)}static fromJson(t,r){return(new Va).fromJson(t,r)}static fromJsonString(t,r){return(new Va).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Va,t,r)}static $(){return["ShellConversationTurn|1 shell_command #0|2 shell_output #1",Na,Ga]}}class Xa extends Fi{constructor(t){super(),this.shellCommand=new Uint8Array(0),this.shellOutput=new Uint8Array(0),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xa).fromBinary(t,r)}static fromJson(t,r){return(new Xa).fromJson(t,r)}static fromJsonString(t,r){return(new Xa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xa,t,r)}static $(){return["ShellConversationTurnStructure|1 shell_command 12|2 shell_output 12"]}}class Ya extends Fi{constructor(t){super(),this.summary="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ya).fromBinary(t,r)}static fromJson(t,r){return(new Ya).fromJson(t,r)}static fromJsonString(t,r){return(new Ya).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ya,t,r)}static $(){return["ConversationSummary|1 summary 9"]}}class Za extends Fi{constructor(t){super(),this.summarizedMessages=[],this.summary="",this.windowTail=0,this.summaryMessage=new Uint8Array(0),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Za).fromBinary(t,r)}static fromJson(t,r){return(new Za).fromJson(t,r)}static fromJsonString(t,r){return(new Za).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Za,t,r)}static $(){return["ConversationSummaryArchive|1 summarized_messages 12*|2 summary 9|3 window_tail 13|4 summary_message 12"]}}class tu extends Fi{constructor(t){super(),this.id="",this.label="",this.estimatedTokens=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tu).fromBinary(t,r)}static fromJson(t,r){return(new tu).fromJson(t,r)}static fromJsonString(t,r){return(new tu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tu,t,r)}static $(){return["PromptTokenBreakdownCategory|1 id 9|2 label 9|3 estimated_tokens 13|4 character_count 13?"]}}class ru extends Fi{constructor(t){super(),this.totalUsedTokens=0,this.maxTokens=0,this.categories=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ru).fromBinary(t,r)}static fromJson(t,r){return(new ru).fromJson(t,r)}static fromJsonString(t,r){return(new ru).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ru,t,r)}static $(){return["PromptTokenBreakdownSnapshot|1 total_used_tokens 13|2 max_tokens 13|3 categories #0*",tu]}}class eu extends Fi{constructor(t){super(),this.sourceType="",this.messageIndex=0,this.contentPath="",this.startOffset=0,this.endOffset=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eu).fromBinary(t,r)}static fromJson(t,r){return(new eu).fromJson(t,r)}static fromJsonString(t,r){return(new eu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eu,t,r)}static $(){return["PromptContextSourceRef|1 source_type 9|3 message_index 13|4 content_path 9|5 start_offset 13|6 end_offset 13"]}}class nu extends Fi{constructor(t){super(),this.id="",this.kind="",this.label="",this.categoryId="",this.estimatedTokens=0,this.characterCount=0,this.contentAvailable=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nu).fromBinary(t,r)}static fromJson(t,r){return(new nu).fromJson(t,r)}static fromJsonString(t,r){return(new nu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nu,t,r)}static $(){return["PromptContextNode|1 id 9|2 parent_id 9?|3 kind 9|4 label 9|5 category_id 9|6 estimated_tokens 13|7 character_count 13|9 content_available 8|11 source #0?|12 inline_content 9?",eu]}}class su extends Fi{constructor(t){super(),this.schemaVersion=0,this.nodes=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new su).fromBinary(t,r)}static fromJson(t,r){return(new su).fromJson(t,r)}static fromJsonString(t,r){return(new su).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(su,t,r)}static $(){return["PromptContextUsageTree|1 schema_version 13|2 nodes #0*",nu]}}class iu extends Fi{constructor(t){super(),this.usedTokens=0,this.maxTokens=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iu).fromBinary(t,r)}static fromJson(t,r){return(new iu).fromJson(t,r)}static fromJsonString(t,r){return(new iu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iu,t,r)}static $(){return["ConversationTokenDetails|1 used_tokens 13|2 max_tokens 13|3 breakdown #0?|4 prompt_context_usage_tree #1?",ru,su]}}class ou extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ou).fromBinary(t,r)}static fromJson(t,r){return(new ou).fromJson(t,r)}static fromJsonString(t,r){return(new ou).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ou,t,r)}static $(){return["FileState|1 content 9?|2 initial_content 9?"]}}class au extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new au).fromBinary(t,r)}static fromJson(t,r){return(new au).fromJson(t,r)}static fromJsonString(t,r){return(new au).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(au,t,r)}static $(){return["FileStateStructure|1 content 12?|2 initial_content 12?"]}}class uu extends Fi{constructor(t){super(),this.durationMs=n.protoInt64.zero,this.timestampMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uu).fromBinary(t,r)}static fromJson(t,r){return(new uu).fromJson(t,r)}static fromJsonString(t,r){return(new uu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uu,t,r)}static $(){return["StepTiming|1 duration_ms 4|2 timestamp_ms 4"]}}class cu extends Fi{constructor(t){super(),this.completedTurnCountCapped=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cu).fromBinary(t,r)}static fromJson(t,r){return(new cu).fromJson(t,r)}static fromJsonString(t,r){return(new cu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cu,t,r)}static $(){return["TurnTelemetryState|1 completed_turn_count_capped 13|2 last_completed_turn_timestamp_ms 4?"]}}class lu extends Fi{constructor(t){super(),this.runId="",this.status=to.UNSPECIFIED,this.startedAtMs=n.protoInt64.zero,this.attemptCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lu).fromBinary(t,r)}static fromJson(t,r){return(new lu).fromJson(t,r)}static fromJsonString(t,r){return(new lu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lu,t,r)}static $(){return["TurnRunRecord|1 run_id 9|2 status #0|3 started_at_ms 4|4 finished_at_ms 4?|5 attempt_count 13|6 interrupt_reason #1?",to,ro]}}class mu extends Fi{constructor(t){super(),this.rootPromptMessagesJson=[],this.turns=[],this.todos=[],this.pendingToolCalls=[],this.fileStates={},this.summaryArchives=[],this.plans={},this.communicateUpdateHistory=[],this.communicateUpdateStatesByParentToolCallId={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mu).fromBinary(t,r)}static fromJson(t,r){return(new mu).fromJson(t,r)}static fromJsonString(t,r){return(new mu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mu,t,r)}static $(){return["ConversationState|1 root_prompt_messages_json 9*|8 turns #0*|3 todos #1*|4 pending_tool_calls 9*|5 token_details #2|6 summary #3?|7 plan #4?|9 summary_archive #5?|10 file_states 9,#6|11 summary_archives #5*|12 plans 9,#7|13 communicate_update_history #8*|14 communicate_update_final_summary 9?|15 communicate_update_completed_subtitle 9?|16 communicate_update_states_by_parent_tool_call_id 9,#9",La,C.kW,iu,Ya,Fa,Za,ou,Ka,fu,du]}}class fu extends Fi{constructor(t){super(),this.step="",this.messageIndex=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fu).fromBinary(t,r)}static fromJson(t,r){return(new fu).fromJson(t,r)}static fromJsonString(t,r){return(new fu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fu,t,r)}static $(){return["CommunicateUpdateHistoryEntry|1 step 9|3 message_index 13"]}}class du extends Fi{constructor(t){super(),this.history=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new du).fromBinary(t,r)}static fromJson(t,r){return(new du).fromJson(t,r)}static fromJsonString(t,r){return(new du).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(du,t,r)}static $(){return["CommunicateUpdateTurnState|1 history #0*|2 final_summary 9?|3 completed_subtitle 9?",fu]}}class pu extends Fi{constructor(t){super(),this.createdTimestampMs=n.protoInt64.zero,this.lastUsedTimestampMs=n.protoInt64.zero,this.environment=s.dU.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pu).fromBinary(t,r)}static fromJson(t,r){return(new pu).fromJson(t,r)}static fromJsonString(t,r){return(new pu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pu,t,r)}static $(){return["SubagentPersistedState|1 conversation_state #0|2 created_timestamp_ms 4|3 last_used_timestamp_ms 4|4 subagent_type #1|5 model_id 9?|6 environment #2|7 cloud_subagent #3?|8 first_class_bc_id 9?|9 cloud_requested_environment_build_id 9?|10 machine #4?|11 attached_video_unavailable #5?",Ju,s._L,s.dU,gu,uo,hu]}}class hu extends Fi{constructor(t){super(),this.videoPaths=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hu).fromBinary(t,r)}static fromJson(t,r){return(new hu).fromJson(t,r)}static fromJsonString(t,r){return(new hu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hu,t,r)}static $(){return["AttachedVideoUnavailable|1 video_paths 9*"]}}class gu extends Fi{constructor(t){super(),this.bcId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gu).fromBinary(t,r)}static fromJson(t,r){return(new gu).fromJson(t,r)}static fromJsonString(t,r){return(new gu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gu,t,r)}static $(){return["CloudSubagentReference|1 bc_id 9|2 transcript_path 9?"]}}class _u extends Fi{constructor(t){super(),this.repoPath="",this.branchName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _u).fromBinary(t,r)}static fromJson(t,r){return(new _u).fromJson(t,r)}static fromJsonString(t,r){return(new _u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_u,t,r)}static $(){return["TrackedGitRepo|1 repo_path 9|2 branch_name 9"]}}class Ju extends Fi{constructor(t){super(),this.rootPromptMessagesJson=[],this.turns=[],this.todos=[],this.pendingToolCalls=[],this.previousWorkspaceUris=[],this.fileStates={},this.fileStatesV2={},this.summaryArchives=[],this.turnTimings=[],this.subagentStates={},this.selfSummaryCount=0,this.readPaths=[],this.plans={},this.trackedGitRepoBranches=[],this.communicateUpdateHistory=[],this.subagentThreads={},this.communicateUpdateStatesByParentToolCallId={},this.subagentRunsByParentToolCallId={},this.subagentStateRefs={},this.completedAskQuestionToolCallIds=[],this.durableSkillBlocks=[],this.recentUserMessageIds=[],this.mentionedAgentIds=[],this.voiceCallUtterances=[],this.voiceCallTimeTaskIds=[],this.writesVoiceCallUtterances=!1,this.threadSummaries={},this.recentThreadReplies=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ju).fromBinary(t,r)}static fromJson(t,r){return(new Ju).fromJson(t,r)}static fromJsonString(t,r){return(new Ju).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ju,t,r)}static $(){return["ConversationStateStructure|1 root_prompt_messages_json 12*|8 turns 12*|3 todos 12*|4 pending_tool_calls 9*|5 token_details #0|6 summary 12?|7 plan 12?|9 previous_workspace_uris 9*|10 mode #1?|11 summary_archive 12?|12 file_states 9,12|15 file_states_v2 9,#2|13 summary_archives 12*|14 turn_timings #3*|16 subagent_states 9,#4|17 self_summary_count 13|18 read_paths 9*|19 active_branch_name 9?|20 plans 9,#5|21 tracked_git_repo_branches #6*|22 agent_type 9?|23 communicate_update_history #7*|24 subagent_threads 9,9|25 communicate_update_final_summary 9?|28 communicate_update_completed_subtitle 9?|29 communicate_update_states_by_parent_tool_call_id 9,#8|30 subagent_runs_by_parent_tool_call_id 9,#9|26 conversation_started_timestamp_ms 4?|27 conversation_started_time_zone 9?|31 subagent_state_refs 9,12|32 goal_state #10?|33 is_root_project_conversation 8?|34 completed_ask_question_tool_call_ids 9*|35 durable_skill_blocks 9*|36 durable_custom_mode_id 9?|37 message_count_at_last_compaction 13?|38 recent_user_message_ids 9*|39 recent_user_message_ids_older_turn_count 13?|40 turn_telemetry #11?|42 mentioned_agent_ids 9*|43 voice_call_utterances #12*|44 voice_call_pending_answer #13?|45 voice_call_time_task_ids 9*|46 writes_voice_call_utterances 8|47 voice_calls_read_utterances 8?|49 user_time_zone 9?|50 project_coordinator_system_section 9?|51 project_coordinator_system_section_communication_rules 8?|52 last_run #14?|53 thread_summaries 9,#15|54 recent_thread_replies #16*|55 turns_cleared 8?|56 project_prompt_turn_count 13?",iu,Ki,au,uu,pu,Ka,_u,fu,du,Oo,za,cu,Su,Bu,lu,yu,wu]}}class wu extends Fi{constructor(t){super(),this.messageId="",this.rootId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wu).fromBinary(t,r)}static fromJson(t,r){return(new wu).fromJson(t,r)}static fromJsonString(t,r){return(new wu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wu,t,r)}static $(){return["ThreadReply|1 message_id 9|2 root_id 9"]}}class yu extends Fi{constructor(t){super(),this.replyCount=0,this.lastReplyAtMs=n.protoInt64.zero,this.preview="",this.participantIds=[],this.createdAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yu).fromBinary(t,r)}static fromJson(t,r){return(new yu).fromJson(t,r)}static fromJsonString(t,r){return(new yu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yu,t,r)}static $(){return["ThreadSummary|1 reply_count 13|2 last_reply_at_ms 4|3 preview 9|4 participant_ids 9*|5 created_at_ms 4"]}}class Su extends Fi{constructor(t){super(),this.id="",this.kind=qu.UNSPECIFIED,this.text="",this.answersMessageIds=[],this.failed=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Su).fromBinary(t,r)}static fromJson(t,r){return(new Su).fromJson(t,r)}static fromJsonString(t,r){return(new Su).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Su,t,r)}static $(){return["VoiceCallUtterance|1 id 9|2 kind #0|3 text 9|4 answers_message_ids 9*|5 failed 8",qu]}}var qu=(0,o.QT)(n.proto3,Li,"VoiceCallUtterance.Kind",[[0,"UNSPECIFIED"],[1,"SEND"],[2,"TERMINAL"]],1);class Bu extends Fi{constructor(t){super(),this.messageIds=[],this.readsUtterances=!1,this.endedOnSend=!1,this.reopenedTerminalId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bu).fromBinary(t,r)}static fromJson(t,r){return(new Bu).fromJson(t,r)}static fromJsonString(t,r){return(new Bu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bu,t,r)}static $(){return["VoiceCallPendingAnswer|1 message_ids 9*|2 reads_utterances 8|3 ended_on_send 8|4 reopened_terminal_id 9"]}}class Iu extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Iu).fromBinary(t,r)}static fromJson(t,r){return(new Iu).fromJson(t,r)}static fromJsonString(t,r){return(new Iu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Iu,t,r)}static $(){return["ThinkingDetails"]}}class Pu extends Fi{constructor(t){super(),this.bearerToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pu).fromBinary(t,r)}static fromJson(t,r){return(new Pu).fromJson(t,r)}static fromJsonString(t,r){return(new Pu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pu,t,r)}static $(){return["ClientLlmGatewayCredential|1 bearer_token 9"]}}class bu extends Fi{constructor(t){super(),this.modelId="",this.displayModelId="",this.displayName="",this.displayNameShort="",this.aliases=[],this.credentials={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bu).fromBinary(t,r)}static fromJson(t,r){return(new bu).fromJson(t,r)}static fromJsonString(t,r){return(new bu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bu,t,r)}static $(){return["ModelDetails|1 model_id 9|3 display_model_id 9|4 display_name 9|5 display_name_short 9|6 aliases 9*|2 thinking_details #0?|7 max_mode 8?|8 api_key_credentials #1 credentials|9 azure_credentials #2 credentials|10 bedrock_credentials #3 credentials",Iu,Di.G0,Di.ih,Di.R4]}}class Ru extends Fi{constructor(t){super(),this.subagentType="",this.selection={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ru).fromBinary(t,r)}static fromJson(t,r){return(new Ru).fromJson(t,r)}static fromJsonString(t,r){return(new Ru).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ru,t,r)}static $(){return["SubagentModelOverride|1 subagent_type 9|2 model #0 selection|3 inherit 8 selection|4 disabled 8 selection",Di.G4]}}class vu extends Fi{constructor(t){super(),this.id=new Uint8Array(0),this.value=new Uint8Array(0),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vu).fromBinary(t,r)}static fromJson(t,r){return(new vu).fromJson(t,r)}static fromJsonString(t,r){return(new vu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vu,t,r)}static $(){return["PreFetchedBlob|1 id 12|2 value 12"]}}class xu extends Fi{constructor(t){super(),this.selectedSubagentModels=[],this.selectedSubagentModelDetails=[],this.preFetchedBlobs=[],this.subagentModelOverrides=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xu).fromBinary(t,r)}static fromJson(t,r){return(new xu).fromJson(t,r)}static fromJsonString(t,r){return(new xu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xu,t,r)}static $(){return["AgentRunRequest|1 conversation_state #0|2 action #1|3 model_details #2|9 requested_model #3?|4 mcp_tools #4|5 conversation_id 9?|6 mcp_file_system_options #5?|7 skill_options #6?|8 custom_system_prompt 9?|11 subagent_type_name 9?|12 exclude_workspace_context 8?|13 harness 9?|14 selected_subagent_models #3*|15 selected_subagent_model_details #2*|16 conversation_group_id 9?|17 pre_fetched_blobs #7*|18 dev_raw_model_slug 9?|19 client_supports_inline_images 8?|20 subagent_model_overrides #8*|21 can_create_cloud_subagents 8?|22 suppress_subagent_progress_update_tool 8?|23 client_supports_send_to_user 8?|24 computer_use_coordinate_mode 9?|25 run_id 9?|26 agent_session_id 9?|28 client_supports_routed_model_update 8?|29 system_prompt_spec #9?|30 client_llm_gateway_credential #10?|31 client_supports_preview_card 8?|32 started_as_new_project 8?|33 first_project_onboarding 8?|34 next_interaction_query_id 13?|35 voice_call_notes #11?|36 transcript_parent_conversation_id 9?|37 emit_model_call_usage 8?",Ju,To,bu,Di.G4,Ni.Or,Ni.Is,Mi.uw,vu,Ru,Gi.$,Pu,s.OT]}}class ku extends Fi{constructor(t){super(),this.text="",this.isServerNotice=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ku).fromBinary(t,r)}static fromJson(t,r){return(new ku).fromJson(t,r)}static fromJsonString(t,r){return(new ku).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ku,t,r)}static $(){return["TextDeltaUpdate|1 text 9|2 is_server_notice 8"]}}class Eu extends Fi{constructor(t){super(),this.displayName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Eu).fromBinary(t,r)}static fromJson(t,r){return(new Eu).fromJson(t,r)}static fromJsonString(t,r){return(new Eu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Eu,t,r)}static $(){return["RoutedModelUpdate|1 display_name 9"]}}class Cu extends Fi{constructor(t){super(),this.callId="",this.modelCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cu).fromBinary(t,r)}static fromJson(t,r){return(new Cu).fromJson(t,r)}static fromJsonString(t,r){return(new Cu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cu,t,r)}static $(){return["ToolCallStartedUpdate|1 call_id 9|2 tool_call #0|3 model_call_id 9",Po]}}class Tu extends Fi{constructor(t){super(),this.callId="",this.modelCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tu).fromBinary(t,r)}static fromJson(t,r){return(new Tu).fromJson(t,r)}static fromJsonString(t,r){return(new Tu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tu,t,r)}static $(){return["ToolCallCompletedUpdate|1 call_id 9|2 tool_call #0|3 model_call_id 9",Po]}}class Uu extends Fi{constructor(t){super(),this.callId="",this.modelCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Uu).fromBinary(t,r)}static fromJson(t,r){return(new Uu).fromJson(t,r)}static fromJsonString(t,r){return(new Uu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Uu,t,r)}static $(){return["ToolCallDeltaUpdate|1 call_id 9|2 tool_call_delta #0|3 model_call_id 9",Eo]}}class Au extends Fi{constructor(t){super(),this.callId="",this.argsTextDelta="",this.modelCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Au).fromBinary(t,r)}static fromJson(t,r){return(new Au).fromJson(t,r)}static fromJsonString(t,r){return(new Au).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Au,t,r)}static $(){return["PartialToolCallUpdate|1 call_id 9|2 tool_call #0|3 args_text_delta 9|4 model_call_id 9",Po]}}class $u extends Fi{constructor(t){super(),this.text="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $u).fromBinary(t,r)}static fromJson(t,r){return(new $u).fromJson(t,r)}static fromJsonString(t,r){return(new $u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($u,t,r)}static $(){return["ThinkingDeltaUpdate|1 text 9|2 thinking_style #0?",eo]}}class Mu extends Fi{constructor(t){super(),this.thinkingDurationMs=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mu).fromBinary(t,r)}static fromJson(t,r){return(new Mu).fromJson(t,r)}static fromJsonString(t,r){return(new Mu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mu,t,r)}static $(){return["ThinkingCompletedUpdate|1 thinking_duration_ms 5|2 narration 8?"]}}class Ou extends Fi{constructor(t){super(),this.text="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ou).fromBinary(t,r)}static fromJson(t,r){return(new Ou).fromJson(t,r)}static fromJsonString(t,r){return(new Ou).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ou,t,r)}static $(){return["ThinkingNoteUpdate|1 text 9"]}}class Du extends Fi{constructor(t){super(),this.tokens=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Du).fromBinary(t,r)}static fromJson(t,r){return(new Du).fromJson(t,r)}static fromJsonString(t,r){return(new Du).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Du,t,r)}static $(){return["TokenDeltaUpdate|1 tokens 5"]}}class Nu extends Fi{constructor(t){super(),this.summary="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nu).fromBinary(t,r)}static fromJson(t,r){return(new Nu).fromJson(t,r)}static fromJsonString(t,r){return(new Nu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nu,t,r)}static $(){return["SummaryUpdate|1 summary 9"]}}class Gu extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gu).fromBinary(t,r)}static fromJson(t,r){return(new Gu).fromJson(t,r)}static fromJsonString(t,r){return(new Gu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gu,t,r)}static $(){return["SummaryStartedUpdate"]}}class Lu extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lu).fromBinary(t,r)}static fromJson(t,r){return(new Lu).fromJson(t,r)}static fromJsonString(t,r){return(new Lu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Lu,t,r)}static $(){return["HeartbeatUpdate"]}}class Fu extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fu).fromBinary(t,r)}static fromJson(t,r){return(new Fu).fromJson(t,r)}static fromJsonString(t,r){return(new Fu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fu,t,r)}static $(){return["SummaryCompletedUpdate|1 hook_message 9?|2 failed 8?|3 fallback 8?"]}}class Ku extends Fi{constructor(t){super(),this.event={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ku).fromBinary(t,r)}static fromJson(t,r){return(new Ku).fromJson(t,r)}static fromJsonString(t,r){return(new Ku).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ku,t,r)}static $(){return["ShellOutputDeltaUpdate|1 stdout #0 event|2 stderr #1 event|3 exit #2 event|4 start #3 event",i.o0,i.Db,i.vb,i.tD]}}class zu extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zu).fromBinary(t,r)}static fromJson(t,r){return(new zu).fromJson(t,r)}static fromJsonString(t,r){return(new zu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zu,t,r)}static $(){return["TurnEndedUpdate|1 input_tokens 3?|2 output_tokens 3?|3 cache_read_tokens 3?|4 cache_write_tokens 3?|5 reasoning_tokens 3?|6 ended_at_ms 4?|7 estimated_cost #0?",ju]}}class ju extends Fi{constructor(t){super(),this.rawCostCents=0,this.chargedCents=0,this.source=no.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ju).fromBinary(t,r)}static fromJson(t,r){return(new ju).fromJson(t,r)}static fromJsonString(t,r){return(new ju).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ju,t,r)}static $(){return["EstimatedCost|1 raw_cost_cents 1|2 charged_cents 1|3 source #0",no]}}class Hu extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hu).fromBinary(t,r)}static fromJson(t,r){return(new Hu).fromJson(t,r)}static fromJsonString(t,r){return(new Hu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hu,t,r)}static $(){return["UserMessageAppendedUpdate|1 user_message #0",Ua]}}class Wu extends Fi{constructor(t){super(),this.stepId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wu).fromBinary(t,r)}static fromJson(t,r){return(new Wu).fromJson(t,r)}static fromJsonString(t,r){return(new Wu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wu,t,r)}static $(){return["StepStartedUpdate|1 step_id 4"]}}class Qu extends Fi{constructor(t){super(),this.callCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qu).fromBinary(t,r)}static fromJson(t,r){return(new Qu).fromJson(t,r)}static fromJsonString(t,r){return(new Qu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qu,t,r)}static $(){return["ToolRequestsListedUpdate|1 call_count 13"]}}class Vu extends Fi{constructor(t){super(),this.stepId=n.protoInt64.zero,this.stepDurationMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vu).fromBinary(t,r)}static fromJson(t,r){return(new Vu).fromJson(t,r)}static fromJsonString(t,r){return(new Vu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vu,t,r)}static $(){return["StepCompletedUpdate|1 step_id 4|2 step_duration_ms 3"]}}class Xu extends Fi{constructor(t){super(),this.modelCallId="",this.inputTokens=n.protoInt64.zero,this.outputTokens=n.protoInt64.zero,this.cacheReadTokens=n.protoInt64.zero,this.cacheWriteTokens=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xu).fromBinary(t,r)}static fromJson(t,r){return(new Xu).fromJson(t,r)}static fromJsonString(t,r){return(new Xu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xu,t,r)}static $(){return["ModelCallCompletedUpdate|1 model_call_id 9|2 input_tokens 3|3 output_tokens 3|4 cache_read_tokens 3|5 cache_write_tokens 3|6 reasoning_tokens 3?"]}}class Yu extends Fi{constructor(t){super(),this.path="",this.branchName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yu).fromBinary(t,r)}static fromJson(t,r){return(new Yu).fromJson(t,r)}static fromJsonString(t,r){return(new Yu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yu,t,r)}static $(){return["ActiveBranchChange|1 path 9|2 branch_name 9"]}}class Zu extends Fi{constructor(t){super(),this.id="",this.label="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zu).fromBinary(t,r)}static fromJson(t,r){return(new Zu).fromJson(t,r)}static fromJsonString(t,r){return(new Zu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zu,t,r)}static $(){return["FeedbackRequestCategory|1 id 9|2 label 9"]}}class tc extends Fi{constructor(t){super(),this.id="",this.prompt="",this.categories=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tc).fromBinary(t,r)}static fromJson(t,r){return(new tc).fromJson(t,r)}static fromJsonString(t,r){return(new tc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tc,t,r)}static $(){return["FeedbackRequestCategoryGroup|1 id 9|2 prompt 9|3 categories #0*",Zu]}}class rc extends Fi{constructor(t){super(),this.requestId="",this.categories=[],this.categoryGroups=[],this.showFormImmediately=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rc).fromBinary(t,r)}static fromJson(t,r){return(new rc).fromJson(t,r)}static fromJsonString(t,r){return(new rc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rc,t,r)}static $(){return["FeedbackRequestUpdate|1 request_id 9|2 canonical_model_name 9?|3 categories #0*|4 category_groups #1*|5 show_form_immediately 8|6 title 9?|7 negative_title 9?|8 comment_placeholder 9?",Zu,tc]}}class ec extends Fi{constructor(t){super(),this.displayOrder=so.UNSPECIFIED,this.parentInvocationId="",this.alternateInvocationId="",this.parentResponse="",this.comparisonConfigId="",this.alternateModelId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ec).fromBinary(t,r)}static fromJson(t,r){return(new ec).fromJson(t,r)}static fromJsonString(t,r){return(new ec).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ec,t,r)}static $(){return["ResponseComparisonStarted|1 display_order #0|2 parent_invocation_id 9|3 alternate_invocation_id 9|4 parent_response 9|5 comparison_config_id 9|6 alternate_model_id 9",so]}}class nc extends Fi{constructor(t){super(),this.text="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nc).fromBinary(t,r)}static fromJson(t,r){return(new nc).fromJson(t,r)}static fromJsonString(t,r){return(new nc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nc,t,r)}static $(){return["ResponseComparisonTextDelta|1 text 9"]}}class sc extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sc).fromBinary(t,r)}static fromJson(t,r){return(new sc).fromJson(t,r)}static fromJsonString(t,r){return(new sc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sc,t,r)}static $(){return["ResponseComparisonCompleted"]}}class ic extends Fi{constructor(t){super(),this.reason=io.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ic).fromBinary(t,r)}static fromJson(t,r){return(new ic).fromJson(t,r)}static fromJsonString(t,r){return(new ic).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ic,t,r)}static $(){return["ResponseComparisonSkipped|1 reason #0",io]}}class oc extends Fi{constructor(t){super(),this.comparisonId="",this.event={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oc).fromBinary(t,r)}static fromJson(t,r){return(new oc).fromJson(t,r)}static fromJsonString(t,r){return(new oc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oc,t,r)}static $(){return["ResponseComparisonUpdate|1 comparison_id 9|2 started #0 event|3 text_delta #1 event|4 completed #2 event|5 skipped #3 event",ec,nc,sc,ic]}}class ac extends Fi{constructor(t){super(),this.message={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ac).fromBinary(t,r)}static fromJson(t,r){return(new ac).fromJson(t,r)}static fromJsonString(t,r){return(new ac).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ac,t,r)}static $(){return["InteractionUpdate|1 text_delta #0 message|7 partial_tool_call #1 message|15 tool_call_delta #2 message|2 tool_call_started #3 message|3 tool_call_completed #4 message|4 thinking_delta #5 message|5 thinking_completed #6 message|6 user_message_appended #7 message|8 token_delta #8 message|9 summary #9 message|10 summary_started #10 message|11 summary_completed #11 message|12 shell_output_delta #12 message|13 heartbeat #13 message|14 turn_ended #14 message|16 step_started #15 message|17 step_completed #16 message|27 tool_requests_listed #17 message|19 post_request_prompt #18 message|20 active_branch_change #19 message|21 feedback_request #20 message|22 response_comparison #21 message|23 context_injection_state #22 message|24 routed_model #23 message|26 grok_bot_nudge #24 message|28 thinking_note #25 message|30 voice_call_utterance #26 message|31 model_call_completed #27 message|25 message_started_at_ms 4?",ku,Au,Uu,Cu,Tu,$u,Mu,Hu,Du,Nu,Gu,Fu,Ku,Lu,zu,Wu,Vu,Qu,cc,Yu,rc,oc,uc,Eu,lc,Ou,Su,Xu]}}class uc extends Fi{constructor(t){super(),this.injectionId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uc).fromBinary(t,r)}static fromJson(t,r){return(new uc).fromJson(t,r)}static fromJsonString(t,r){return(new uc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uc,t,r)}static $(){return["ContextInjectionStateUpdate|1 injection_id 9|2 state #0",la]}}class cc extends Fi{constructor(t){super(),this.title="",this.message="",this.buttonLabel="",this.buttonUrl="",this.buttonAction=oo.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cc).fromBinary(t,r)}static fromJson(t,r){return(new cc).fromJson(t,r)}static fromJsonString(t,r){return(new cc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cc,t,r)}static $(){return["PostRequestPromptUpdate|1 title 9|2 message 9|3 button_label 9|4 button_url 9|5 button_action #0",oo]}}class lc extends Fi{constructor(t){super(),this.job="",this.description="",this.showNumber=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lc).fromBinary(t,r)}static fromJson(t,r){return(new lc).fromJson(t,r)}static fromJsonString(t,r){return(new lc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lc,t,r)}static $(){return["GrokBotNudgeUpdate|1 job 9|2 description 9|3 show_number 13"]}}class mc extends Fi{constructor(t){super(),this.id=0,this.query={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mc).fromBinary(t,r)}static fromJson(t,r){return(new mc).fromJson(t,r)}static fromJsonString(t,r){return(new mc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mc,t,r)}static $(){return["InteractionQuery|1 id 13|2 web_search_request_query #0 query|3 ask_question_interaction_query #1 query|4 switch_mode_request_query #2 query|7 create_plan_request_query #3 query|8 setup_vm_environment_args #4 query|9 web_fetch_request_query #5 query|10 pr_management_request_query #6 query|11 mcp_auth_request_query #7 query|12 generate_image_request_query #8 query|13 replace_env_args #9 query|14 connect_scm_request_query #10 query",_t.KL,dc,bt.Nc,gt.vR,Gt.BI,tr.Un,nr.DY,sr.uL,Rt.Uj,Fr.TO,Ie.$1]}}class fc extends Fi{constructor(t){super(),this.id=0,this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fc).fromBinary(t,r)}static fromJson(t,r){return(new fc).fromJson(t,r)}static fromJsonString(t,r){return(new fc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fc,t,r)}static $(){return["InteractionResponse|1 id 13|2 web_search_request_response #0 result|3 ask_question_interaction_response #1 result|4 switch_mode_request_response #2 result|7 create_plan_request_response #3 result|8 setup_vm_environment_result #4 result|9 web_fetch_request_response #5 result|10 pr_management_result #6 result|11 mcp_auth_request_response #7 result|12 generate_image_request_response #8 result|13 replace_env_result #9 result|14 connect_scm_request_response #10 result",_t.lI,pc,bt.w$,gt.gz,Gt.r$,tr.fS,nr.HL,sr.h,Rt.vW,Fr.dV,Ie.qG]}}class dc extends Fi{constructor(t){super(),this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dc).fromBinary(t,r)}static fromJson(t,r){return(new dc).fromJson(t,r)}static fromJsonString(t,r){return(new dc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dc,t,r)}static $(){return["AskQuestionInteractionQuery|1 args #0|2 tool_call_id 9",qt.ju]}}class pc extends Fi{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pc).fromBinary(t,r)}static fromJson(t,r){return(new pc).fromJson(t,r)}static fromJsonString(t,r){return(new pc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pc,t,r)}static $(){return["AskQuestionInteractionResponse|1 result #0",qt.tz]}}},"../proto/dist/generated/agent/v1/agent_service_connect.js"(t,r,e){e.d(r,{N:()=>o});var n=e("../proto/dist/generated/agent/v1/agent_service_pb.js"),s=e("@bufbuild/protobuf"),i=e("../proto/dist/generated/aiserver/v1/bidi_pb.js");const o={typeName:"agent.v1.AgentService",methods:{run:{name:"Run",I:n.KS,O:n.Oy,kind:s.MethodKind.BiDiStreaming},runSSE:{name:"RunSSE",I:i.$r,O:n.Oy,kind:s.MethodKind.ServerStreaming},runPoll:{name:"RunPoll",I:i.hD,O:i.xy,kind:s.MethodKind.ServerStreaming},nameAgent:{name:"NameAgent",I:n.Il,O:n.mw,kind:s.MethodKind.Unary},updateConversationMetadata:{name:"UpdateConversationMetadata",I:n.vw,O:n.HJ,kind:s.MethodKind.Unary},createTranscriptOverview:{name:"CreateTranscriptOverview",I:n.BU,O:n.Hi,kind:s.MethodKind.Unary},getUsableModels:{name:"GetUsableModels",I:n.KD,O:n.sY,kind:s.MethodKind.Unary},getDefaultModelForCli:{name:"GetDefaultModelForCli",I:n.Tu,O:n.pe,kind:s.MethodKind.Unary},getAllowedModelIntents:{name:"GetAllowedModelIntents",I:n.Ov,O:n.k4,kind:s.MethodKind.Unary},uploadConversationBlobs:{name:"UploadConversationBlobs",I:n.yD,O:n.W$,kind:s.MethodKind.Unary},uploadLocalAgentRunToPromptQuality:{name:"UploadLocalAgentRunToPromptQuality",I:n.uK,O:n.eE,kind:s.MethodKind.Unary},getSignedUrlForAttachedMedia:{name:"GetSignedUrlForAttachedMedia",I:n.W3,O:n.wq,kind:s.MethodKind.Unary},notifyConversationClone:{name:"NotifyConversationClone",I:n.xk,O:n.JF,kind:s.MethodKind.Unary},warmUp:{name:"WarmUp",I:n.EC,O:n.M2,kind:s.MethodKind.Unary},getNewChatNudgeLegacyModelPicker:{name:"GetNewChatNudgeLegacyModelPicker",I:n.Pg,O:n.zP,kind:s.MethodKind.Unary},getNewChatNudgeParameterizedModelPicker:{name:"GetNewChatNudgeParameterizedModelPicker",I:n.hs,O:n.TW,kind:s.MethodKind.Unary},getPromptContextUsage:{name:"GetPromptContextUsage",I:n.Y3,O:n.KE,kind:s.MethodKind.Unary},listLocalSubscriptionTools:{name:"ListLocalSubscriptionTools",I:n.dw,O:n.JH,kind:s.MethodKind.Unary},callLocalSubscriptionTool:{name:"CallLocalSubscriptionTool",I:n.uw,O:n.uu,kind:s.MethodKind.Unary},streamLocalAgentMailbox:{name:"StreamLocalAgentMailbox",I:n.k5,O:n.ic,kind:s.MethodKind.ServerStreaming}}}},"../proto/dist/generated/agent/v1/agent_service_pb.js"(t,r,e){e.d(r,{BU:()=>v,EC:()=>j,HJ:()=>P,Hi:()=>x,Il:()=>q,JF:()=>z,JH:()=>et,KD:()=>k,KE:()=>R,KS:()=>J,M2:()=>H,Ov:()=>U,Oy:()=>S,Pg:()=>W,TW:()=>gt,Tu:()=>C,W$:()=>O,W3:()=>L,Y3:()=>b,dw:()=>tt,eE:()=>G,hs:()=>ht,ic:()=>pt,k4:()=>A,k5:()=>ut,kA:()=>g,mw:()=>B,pe:()=>T,sY:()=>E,uK:()=>N,uu:()=>st,uw:()=>nt,vw:()=>I,wq:()=>F,xk:()=>K,yD:()=>M,zP:()=>Q});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/agent/v1/agent_pb.js"),i=e("../proto/dist/generated/agent/v1/requested_model_pb.js"),o=e("../proto/dist/generated/agent/v1/mcp_pb.js"),a=e("../proto/dist/generated/agent/v1/exec_pb.js"),u=e("../proto/dist/generated/agent/v1/kv_pb.js"),c=e("../proto/dist/runtime/compact.js");const l="agent.v1.";class m extends c.HL{static get runtime(){return(0,c.kU)(this,"runtime",n.proto3)}static $p(){return l}}var f=(0,c.QT)(n.proto3,l,"NameAgentKind",[[0,"UNSPECIFIED"],[1,"PROJECT"]],1),d=(0,c.QT)(n.proto3,l,"LocalPromptQualityInvocationStatus",[[0,"UNSPECIFIED"],[1,"SUCCESS"],[2,"ERRORED"],[3,"ABORTED"]],1),p=(0,c.QT)(n.proto3,l,"LocalAgentMailboxGapReason",[[0,"UNSPECIFIED"],[1,"TRIMMED"],[2,"LOST"]],1),h=(0,c.QT)(n.proto3,l,"LocalAgentMailboxEndedReason",[[0,"UNSPECIFIED"],[1,"NO_ACTIVE_SUBSCRIPTIONS"],[2,"STORE_DELETED"],[3,"MIGRATED_TO_CLOUD"]],1);class g extends m{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["ClientHeartbeat"]}}class _ extends m{constructor(t){super(),this.selectedSubagentModels=[],this.selectedSubagentModelDetails=[],this.preFetchedBlobs=[],this.subagentModelOverrides=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _).fromBinary(t,r)}static fromJson(t,r){return(new _).fromJson(t,r)}static fromJsonString(t,r){return(new _).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_,t,r)}static $(){return["PrewarmRequest|1 model_details #0|9 requested_model #1?|2 conversation_id 9?|3 conversation_state #2|4 mcp_tools #3|5 mcp_file_system_options #4?|6 best_of_n_group_id 9?|7 try_use_best_of_n_promotion 8?|8 custom_system_prompt 9?|11 subagent_type_name 9?|12 exclude_workspace_context 8?|13 harness 9?|14 selected_subagent_models #1*|15 selected_subagent_model_details #0*|16 conversation_group_id 9?|17 pre_fetched_blobs #5*|18 client_supports_inline_images 8?|19 subagent_model_overrides #6*|20 can_create_cloud_subagents 8?|21 suppress_subagent_progress_update_tool 8?|22 client_supports_send_to_user 8?|23 computer_use_coordinate_mode 9?|24 agent_session_id 9?|26 client_supports_routed_model_update 8?|27 client_llm_gateway_credential #7?|28 client_supports_preview_card 8?|29 started_as_new_project 8?|30 first_project_onboarding 8?",s.Gmx,i.G4,s.Y9z,o.Or,o.Is,s.onr,s.Bjv,s.Ibo]}}class J extends m{constructor(t){super(),this.message={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new J).fromBinary(t,r)}static fromJson(t,r){return(new J).fromJson(t,r)}static fromJsonString(t,r){return(new J).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(J,t,r)}static $(){return["AgentClientMessage|1 run_request #0 message|2 exec_client_message #1 message|5 exec_client_control_message #2 message|3 kv_client_message #3 message|4 conversation_action #4 message|6 interaction_response #5 message|7 client_heartbeat #6 message|8 prewarm_request #7 message",s.Mpn,a.yT,a.$Y,u.gm,s.QFf,s.Y5,g,_]}}class w extends m{constructor(t){super(),this.serverFirstTokenMs=0,this.preStreamSetupMs=0,this.waitForFirstEventMs=0,this.slowPoolWaitMs=0,this.clientClock=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new w).fromBinary(t,r)}static fromJson(t,r){return(new w).fromJson(t,r)}static fromJsonString(t,r){return(new w).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(w,t,r)}static $(){return["TtftBreakdown|1 server_first_token_ms 1|2 pre_stream_setup_ms 1|3 wait_for_first_event_ms 1|4 provider_ttft_ms 1?|5 slow_pool_wait_ms 1|6 client_prep_ms 1?|7 client_clock 8|8 pre_handler_ms 1?|9 client_prep_legs #0?",y]}}class y extends m{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new y).fromBinary(t,r)}static fromJson(t,r){return(new y).fromJson(t,r)}static fromJsonString(t,r){return(new y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(y,t,r)}static $(){return["TtftClientPrepLegs|1 state_restore_ms 1?|2 root_prompt_restore_ms 1?|3 request_context_ms 1?|4 system_prompt_ms 1?|5 pre_turn_snapshot_ms 1?|6 pre_turn_snapshot_wait_ms 1?|7 pre_turn_snapshot_blob_writes_ms 1?|8 pre_turn_snapshot_serialize_ms 1?|9 first_step_to_first_invocation_ms 1?|10 prompt_message_count 13?|11 turn_count 13?"]}}class S extends m{constructor(t){super(),this.message={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new S).fromBinary(t,r)}static fromJson(t,r){return(new S).fromJson(t,r)}static fromJsonString(t,r){return(new S).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(S,t,r)}static $(){return["AgentServerMessage|1 interaction_update #0 message|2 exec_server_message #1 message|5 exec_server_control_message #2 message|3 conversation_checkpoint_update #3 message|4 kv_server_message #4 message|7 interaction_query #5 message|8 ttft_breakdown #6",s.Uq,a.Ye,a.Nv,s.Y9z,u.km,s.Pd7,w]}}class q extends m{constructor(t){super(),this.userMessage="",this.kind=f.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new q).fromBinary(t,r)}static fromJson(t,r){return(new q).fromJson(t,r)}static fromJsonString(t,r){return(new q).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(q,t,r)}static $(){return["NameAgentRequest|1 user_message 9|2 kind #0",f]}}class B extends m{constructor(t){super(),this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new B).fromBinary(t,r)}static fromJson(t,r){return(new B).fromJson(t,r)}static fromJsonString(t,r){return(new B).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(B,t,r)}static $(){return["NameAgentResponse|1 name 9"]}}class I extends m{constructor(t){super(),this.conversationId="",this.workspacePaths=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new I).fromBinary(t,r)}static fromJson(t,r){return(new I).fromJson(t,r)}static fromJsonString(t,r){return(new I).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(I,t,r)}static $(){return["UpdateConversationMetadataRequest|1 conversation_id 9|2 name 9?|3 only_set_name_if_empty 8?|4 workspace_paths 9*"]}}class P extends m{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new P).fromBinary(t,r)}static fromJson(t,r){return(new P).fromJson(t,r)}static fromJsonString(t,r){return(new P).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(P,t,r)}static $(){return["UpdateConversationMetadataResponse"]}}class b extends m{constructor(t){super(),this.conversationId="",this.rootPromptMessagesJson=[],this.selfContained=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new b).fromBinary(t,r)}static fromJson(t,r){return(new b).fromJson(t,r)}static fromJsonString(t,r){return(new b).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(b,t,r)}static $(){return["GetPromptContextUsageRequest|1 conversation_id 9|3 root_prompt_messages_json 12*|5 self_contained 8"]}}class R extends m{constructor(t){super(),this.unavailableBlobCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new R).fromBinary(t,r)}static fromJson(t,r){return(new R).fromJson(t,r)}static fromJsonString(t,r){return(new R).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(R,t,r)}static $(){return["GetPromptContextUsageResponse|2 unavailable_blob_count 13|3 tree #0",s.d2k]}}class v extends m{constructor(t){super(),this.formattedConversation="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new v).fromBinary(t,r)}static fromJson(t,r){return(new v).fromJson(t,r)}static fromJsonString(t,r){return(new v).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(v,t,r)}static $(){return["CreateTranscriptOverviewRequest|1 formatted_conversation 9"]}}class x extends m{constructor(t){super(),this.overview="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new x).fromBinary(t,r)}static fromJson(t,r){return(new x).fromJson(t,r)}static fromJsonString(t,r){return(new x).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(x,t,r)}static $(){return["CreateTranscriptOverviewResponse|1 overview 9"]}}class k extends m{constructor(t){super(),this.customModelIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new k).fromBinary(t,r)}static fromJson(t,r){return(new k).fromJson(t,r)}static fromJsonString(t,r){return(new k).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(k,t,r)}static $(){return["GetUsableModelsRequest|1 custom_model_ids 9*"]}}class E extends m{constructor(t){super(),this.models=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new E).fromBinary(t,r)}static fromJson(t,r){return(new E).fromJson(t,r)}static fromJsonString(t,r){return(new E).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(E,t,r)}static $(){return["GetUsableModelsResponse|1 models #0*",s.Gmx]}}class C extends m{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new C).fromBinary(t,r)}static fromJson(t,r){return(new C).fromJson(t,r)}static fromJsonString(t,r){return(new C).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(C,t,r)}static $(){return["GetDefaultModelForCliRequest"]}}class T extends m{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new T).fromBinary(t,r)}static fromJson(t,r){return(new T).fromJson(t,r)}static fromJsonString(t,r){return(new T).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(T,t,r)}static $(){return["GetDefaultModelForCliResponse|1 model #0",s.Gmx]}}class U extends m{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new U).fromBinary(t,r)}static fromJson(t,r){return(new U).fromJson(t,r)}static fromJsonString(t,r){return(new U).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(U,t,r)}static $(){return["GetAllowedModelIntentsRequest"]}}class A extends m{constructor(t){super(),this.modelIntents=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new A).fromBinary(t,r)}static fromJson(t,r){return(new A).fromJson(t,r)}static fromJsonString(t,r){return(new A).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(A,t,r)}static $(){return["GetAllowedModelIntentsResponse|1 model_intents 9*"]}}class $ extends m{constructor(t){super(),this.id=new Uint8Array(0),this.value=new Uint8Array(0),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $).fromBinary(t,r)}static fromJson(t,r){return(new $).fromJson(t,r)}static fromJsonString(t,r){return(new $).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($,t,r)}static $(){return["BlobEntry|1 id 12|2 value 12"]}}class M extends m{constructor(t){super(),this.conversationId="",this.blobs=[],this.chunkIndex=0,this.totalChunks=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new M).fromBinary(t,r)}static fromJson(t,r){return(new M).fromJson(t,r)}static fromJsonString(t,r){return(new M).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(M,t,r)}static $(){return["UploadConversationBlobsRequest|1 conversation_id 9|2 blobs #0*|3 chunk_index 5|4 total_chunks 5",$]}}class O extends m{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new O).fromBinary(t,r)}static fromJson(t,r){return(new O).fromJson(t,r)}static fromJsonString(t,r){return(new O).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(O,t,r)}static $(){return["UploadConversationBlobsResponse"]}}class D extends m{constructor(t){super(),this.invocationId="",this.attemptRequestId="",this.attempt=0,this.startedAt="",this.completedAt="",this.modelId="",this.providerName="",this.status=d.UNSPECIFIED,this.messages=[],this.responseMessages=[],this.toolsJson="",this.promptTokens=n.protoInt64.zero,this.completionTokens=n.protoInt64.zero,this.totalTokens=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new D).fromBinary(t,r)}static fromJson(t,r){return(new D).fromJson(t,r)}static fromJsonString(t,r){return(new D).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(D,t,r)}static $(){return["LocalPromptQualityInvocation|1 invocation_id 9|2 attempt_request_id 9|3 attempt 5|4 started_at 9|5 completed_at 9|6 model_id 9|7 provider_name 9|8 status #0|9 messages 12*|10 response_messages 12*|11 tools_json 9|12 prompt_tokens 3|13 completion_tokens 3|14 total_tokens 3|15 token_limit 3?|16 error_message 9?|17 prompt_tag 9?|18 feature_type 9?",d]}}class N extends m{constructor(t){super(),this.schemaVersion=0,this.generationUuid="",this.conversationId="",this.payloadDigest="",this.invocations=[],this.terminalStatus=d.UNSPECIFIED,this.createdAt="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new N).fromBinary(t,r)}static fromJson(t,r){return(new N).fromJson(t,r)}static fromJsonString(t,r){return(new N).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(N,t,r)}static $(){return["UploadLocalAgentRunToPromptQualityRequest|1 schema_version 5|2 generation_uuid 9|3 conversation_id 9|4 payload_digest 9|5 invocations #0*|6 terminal_status #1|7 created_at 9",D,d]}}class G extends m{constructor(t){super(),this.requestId="",this.primaryInvocationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new G).fromBinary(t,r)}static fromJson(t,r){return(new G).fromJson(t,r)}static fromJsonString(t,r){return(new G).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(G,t,r)}static $(){return["UploadLocalAgentRunToPromptQualityResponse|1 request_id 9|2 primary_invocation_id 9"]}}class L extends m{constructor(t){super(),this.conversationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new L).fromBinary(t,r)}static fromJson(t,r){return(new L).fromJson(t,r)}static fromJsonString(t,r){return(new L).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(L,t,r)}static $(){return["GetSignedUrlForAttachedMediaRequest|3 conversation_id 9|1 key 9?|2 mime_type 9?|4 content_length_bytes 3?"]}}class F extends m{constructor(t){super(),this.key="",this.postUrl="",this.getUrl="",this.expiresAtUnixMs=n.protoInt64.zero,this.refreshAfterUnixMs=n.protoInt64.zero,this.postFields={},this.putUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new F).fromBinary(t,r)}static fromJson(t,r){return(new F).fromJson(t,r)}static fromJsonString(t,r){return(new F).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(F,t,r)}static $(){return["GetSignedUrlForAttachedMediaResponse|1 key 9|2 post_url 9|3 get_url 9|4 expires_at_unix_ms 3|5 refresh_after_unix_ms 3|6 post_fields 9,9|7 put_url 9"]}}class K extends m{constructor(t){super(),this.conversationId="",this.sourceConversationId="",this.sourceRequestId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new K).fromBinary(t,r)}static fromJson(t,r){return(new K).fromJson(t,r)}static fromJsonString(t,r){return(new K).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(K,t,r)}static $(){return["NotifyConversationCloneRequest|1 conversation_id 9|2 source_conversation_id 9|3 source_request_id 9"]}}class z extends m{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new z).fromBinary(t,r)}static fromJson(t,r){return(new z).fromJson(t,r)}static fromJsonString(t,r){return(new z).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(z,t,r)}static $(){return["NotifyConversationCloneResponse"]}}class j extends m{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new j).fromBinary(t,r)}static fromJson(t,r){return(new j).fromJson(t,r)}static fromJsonString(t,r){return(new j).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(j,t,r)}static $(){return["WarmUpRequest"]}}class H extends m{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new H).fromBinary(t,r)}static fromJson(t,r){return(new H).fromJson(t,r)}static fromJsonString(t,r){return(new H).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(H,t,r)}static $(){return["WarmUpResponse"]}}class W extends m{constructor(t){super(),this.currentModel="",this.maxMode=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new W).fromBinary(t,r)}static fromJson(t,r){return(new W).fromJson(t,r)}static fromJsonString(t,r){return(new W).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(W,t,r)}static $(){return["GetNewChatNudgeLegacyModelPickerRequest|1 current_model 9|2 max_mode 8"]}}class Q extends m{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Q).fromBinary(t,r)}static fromJson(t,r){return(new Q).fromJson(t,r)}static fromJsonString(t,r){return(new Q).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Q,t,r)}static $(){return["GetNewChatNudgeLegacyModelPickerResponse|1 nudge #0?",Z]}}class V extends m{constructor(t){super(),this.bannerMessage="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new V).fromBinary(t,r)}static fromJson(t,r){return(new V).fromJson(t,r)}static fromJsonString(t,r){return(new V).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(V,t,r)}static $(){return["NudgeBumpVariant|1 banner_message 9|2 banner_description 9?"]}}class X extends m{constructor(t){super(),this.popupMessage="",this.acceptLabel="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new X).fromBinary(t,r)}static fromJson(t,r){return(new X).fromJson(t,r)}static fromJsonString(t,r){return(new X).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(X,t,r)}static $(){return["NudgeAskVariant|1 popup_message 9|2 accept_label 9"]}}class Y extends m{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Y).fromBinary(t,r)}static fromJson(t,r){return(new Y).fromJson(t,r)}static fromJsonString(t,r){return(new Y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Y,t,r)}static $(){return["NudgeSilentSwitchVariant"]}}class Z extends m{constructor(t){super(),this.nudgeId="",this.targetModel="",this.experimentName="",this.variant={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Z).fromBinary(t,r)}static fromJson(t,r){return(new Z).fromJson(t,r)}static fromJsonString(t,r){return(new Z).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Z,t,r)}static $(){return["NewChatNudge|1 nudge_id 9|2 target_model 9|3 experiment_name 9|4 bump #0 variant|5 ask #1 variant|6 silent_switch #2 variant",V,X,Y]}}class tt extends m{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tt).fromBinary(t,r)}static fromJson(t,r){return(new tt).fromJson(t,r)}static fromJsonString(t,r){return(new tt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tt,t,r)}static $(){return["ListLocalSubscriptionToolsRequest"]}}class rt extends m{constructor(t){super(),this.toolName="",this.description="",this.inputSchemaJson="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rt).fromBinary(t,r)}static fromJson(t,r){return(new rt).fromJson(t,r)}static fromJsonString(t,r){return(new rt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rt,t,r)}static $(){return["LocalSubscriptionToolDefinition|1 tool_name 9|2 description 9|3 input_schema_json 9"]}}class et extends m{constructor(t){super(),this.tools=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new et).fromBinary(t,r)}static fromJson(t,r){return(new et).fromJson(t,r)}static fromJsonString(t,r){return(new et).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(et,t,r)}static $(){return["ListLocalSubscriptionToolsResponse|1 tools #0*",rt]}}class nt extends m{constructor(t){super(),this.conversationId="",this.toolName="",this.toolArgsJson="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nt).fromBinary(t,r)}static fromJson(t,r){return(new nt).fromJson(t,r)}static fromJsonString(t,r){return(new nt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nt,t,r)}static $(){return["CallLocalSubscriptionToolRequest|1 conversation_id 9|2 tool_name 9|3 tool_args_json 9"]}}class st extends m{constructor(t){super(),this.resultJson="",this.isError=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new st).fromBinary(t,r)}static fromJson(t,r){return(new st).fromJson(t,r)}static fromJsonString(t,r){return(new st).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(st,t,r)}static $(){return["CallLocalSubscriptionToolResponse|1 result_json 9|2 is_error 8|3 watch_expires_at_unix_ms 3?"]}}class it extends m{constructor(t){super(),this.subscriptionId="",this.eventId="",this.inboxRelPath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new it).fromBinary(t,r)}static fromJson(t,r){return(new it).fromJson(t,r)}static fromJsonString(t,r){return(new it).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(it,t,r)}static $(){return["SubscriptionDeliveryEntry|1 subscription_id 9|2 event_id 9|3 inbox_rel_path 9"]}}class ot extends m{constructor(t){super(),this.subscriptionId="",this.inboxRelPath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ot).fromBinary(t,r)}static fromJson(t,r){return(new ot).fromJson(t,r)}static fromJsonString(t,r){return(new ot).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ot,t,r)}static $(){return["SubscriptionRemovedEntry|1 subscription_id 9|2 inbox_rel_path 9"]}}class at extends m{constructor(t){super(),this.localAgentMailboxEntryId="",this.payload={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new at).fromBinary(t,r)}static fromJson(t,r){return(new at).fromJson(t,r)}static fromJsonString(t,r){return(new at).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(at,t,r)}static $(){return["LocalAgentMailboxEntry|1 local_agent_mailbox_entry_id 9|2 subscription_delivery #0 payload|3 subscription_removed #1 payload",it,ot]}}class ut extends m{constructor(t){super(),this.conversations=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ut).fromBinary(t,r)}static fromJson(t,r){return(new ut).fromJson(t,r)}static fromJsonString(t,r){return(new ut).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ut,t,r)}static $(){return["StreamLocalAgentMailboxRequest|1 conversations #0*",ct]}}class ct extends m{constructor(t){super(),this.conversationId="",this.afterOffset="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ct).fromBinary(t,r)}static fromJson(t,r){return(new ct).fromJson(t,r)}static fromJsonString(t,r){return(new ct).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ct,t,r)}static $(){return["StreamLocalAgentMailboxRequest.ConversationCursor|1 conversation_id 9|2 after_offset 9"]}}class lt extends m{constructor(t){super(),this.conversationId="",this.offset="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lt).fromBinary(t,r)}static fromJson(t,r){return(new lt).fromJson(t,r)}static fromJsonString(t,r){return(new lt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lt,t,r)}static $(){return["LocalAgentMailboxDelivery|1 conversation_id 9|2 offset 9|3 entry #0",at]}}class mt extends m{constructor(t){super(),this.conversationId="",this.afterOffset="",this.resumeOffset="",this.reason=p.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mt).fromBinary(t,r)}static fromJson(t,r){return(new mt).fromJson(t,r)}static fromJsonString(t,r){return(new mt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mt,t,r)}static $(){return["LocalAgentMailboxGap|1 conversation_id 9|2 after_offset 9|3 resume_offset 9|4 reason #0",p]}}class ft extends m{constructor(t){super(),this.conversationId="",this.reason=h.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ft).fromBinary(t,r)}static fromJson(t,r){return(new ft).fromJson(t,r)}static fromJsonString(t,r){return(new ft).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ft,t,r)}static $(){return["LocalAgentMailboxEnded|1 conversation_id 9|2 reason #0",h]}}class dt extends m{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dt).fromBinary(t,r)}static fromJson(t,r){return(new dt).fromJson(t,r)}static fromJsonString(t,r){return(new dt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dt,t,r)}static $(){return["StreamLocalAgentMailboxHeartbeat"]}}class pt extends m{constructor(t){super(),this.message={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pt).fromBinary(t,r)}static fromJson(t,r){return(new pt).fromJson(t,r)}static fromJsonString(t,r){return(new pt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pt,t,r)}static $(){return["StreamLocalAgentMailboxResponse|1 delivery #0 message|2 heartbeat #1 message|3 gap #2 message|4 ended #3 message",lt,dt,mt,ft]}}class ht extends m{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ht).fromBinary(t,r)}static fromJson(t,r){return(new ht).fromJson(t,r)}static fromJsonString(t,r){return(new ht).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ht,t,r)}static $(){return["GetNewChatNudgeParameterizedModelPickerRequest|1 current_model #0|2 model_nudges_enabled 8?",i.G4]}}class gt extends m{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gt).fromBinary(t,r)}static fromJson(t,r){return(new gt).fromJson(t,r)}static fromJsonString(t,r){return(new gt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gt,t,r)}static $(){return["GetNewChatNudgeParameterizedModelPickerResponse|1 nudge #0?",_t]}}class _t extends m{constructor(t){super(),this.nudgeId="",this.experimentName="",this.variant={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _t).fromBinary(t,r)}static fromJson(t,r){return(new _t).fromJson(t,r)}static fromJsonString(t,r){return(new _t).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_t,t,r)}static $(){return["NewChatNudgeV2|1 nudge_id 9|2 target_model #0|3 experiment_name 9|4 bump #1 variant|5 ask #2 variant|6 silent_switch #3 variant",i.G4,V,X,Y]}}},"../proto/dist/generated/agent/v1/agent_skills_pb.js"(t,r,e){e.d(r,{N:()=>o});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class o extends i{constructor(t){super(),this.fullPath="",this.content="",this.description="",this.environments=[],this.disabledEnvironments=[],this.disableModelInvocation=!1,this.globs=[],this.scopedTo=[],this.argumentHint="",this.disableUserInvocation=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["AgentSkill|1 full_path 9|2 content 9|3 description 9|4 parse_error 9?|5 environments 9*|6 disabled_environments 9*|7 git_remote_origin 9?|8 disable_model_invocation 8|9 plugin 9?|10 marketplace 9?|11 plugin_id 9?|12 marketplace_id 9?|13 globs 9*|14 scoped_to 9*|15 argument_hint 9|16 disable_user_invocation 8"]}}},"../proto/dist/generated/agent/v1/agent_store_conflict_exec_pb.js"(t,r,e){e.d(r,{Ev:()=>c,LK:()=>o,RZ:()=>u,Uz:()=>a,h6:()=>m,iS:()=>l});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class o extends i{constructor(t){super(),this.journalEpoch="",this.seq=n.protoInt64.zero,this.lastEventId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["AgentStoreConflictCursor|1 journal_epoch 9|2 seq 4|3 last_event_id 9"]}}class a extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["AgentStoreConflictArgs|1 cursor #0?|2 advance 8?|3 include_quota_notices 8?",o]}}class u extends i{constructor(t){super(),this.v=0,this.eventId="",this.journalEpoch="",this.seq=n.protoInt64.zero,this.tsMs=n.protoInt64.zero,this.kind="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["AgentStoreConflictEvent|1 v 13|2 event_id 9|3 journal_epoch 9|4 seq 4|5 ts_ms 4|6 kind 9|7 store_id 9?|8 original_rel_path 9?|9 conflict_rel_path 9?|10 original_abs_path 9?|11 conflict_abs_path 9?|12 preserved_bytes 4?|13 scope_kind 9?|14 limit_bytes 4?|15 usage_bytes 4?"]}}class c extends i{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["AgentStoreConflictResult|1 success #0 result|2 error #1 result",l,m]}}class l extends i{constructor(t){super(),this.events=[],this.gap=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["AgentStoreConflictSuccess|1 events #0*|2 next_cursor #1|3 gap 8",u,o]}}class m extends i{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["AgentStoreConflictError|1 error 9"]}}},"../proto/dist/generated/agent/v1/ai_attribution_tool_pb.js"(t,r,e){e.d(r,{Zc:()=>u,ex:()=>m});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/agent/v1/utils_pb.js"),i=e("../proto/dist/runtime/compact.js");class o extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class a extends o{constructor(t){super(),this.filePaths=[],this.commitHashes=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["AiAttributionArgs|5 file_paths 9*|2 start_line 5?|3 end_line 5?|6 commit_hashes 9*|7 output_mode 9?|9 max_commits 5?|10 include_line_ranges 8?"]}}class u extends o{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["AiAttributionResult|1 success #0 result|2 error #1 result",c,l]}}class c extends o{constructor(t){super(),this.attributionText="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["AiAttributionSuccess|1 attribution_text 9|2 output_location #0?",s.pV]}}class l extends o{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["AiAttributionError|1 error 9"]}}class m extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["AiAttributionToolCall|1 args #0|2 result #1",a,u]}}},"../proto/dist/generated/agent/v1/apply_agent_diff_tool_pb.js"(t,r,e){e.d(r,{JU:()=>a,y$:()=>c});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");const i="agent.v1.";class o extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return i}}class a extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["ApplyAgentDiffToolCall|1 args #0|2 result #1",u,c]}}class u extends o{constructor(t){super(),this.agentId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["ApplyAgentDiffArgs|1 agent_id 9"]}}class c extends o{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["ApplyAgentDiffResult|1 success #0 result|2 error #1 result",l,d]}}class l extends o{constructor(t){super(),this.appliedChanges=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["ApplyAgentDiffSuccess|1 applied_changes #0*",m]}}class m extends o{constructor(t){super(),this.path="",this.changeType=f.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["AppliedAgentChange|1 path 9|2 change_type #0|3 before_content 9?|4 after_content 9?|5 error 9?|6 message_for_model 9?",f]}}var f=(0,s.QT)(n.proto3,i,"AppliedAgentChange.ChangeType",[[0,"UNSPECIFIED"],[1,"CREATED"],[2,"MODIFIED"],[3,"DELETED"]],1);class d extends o{constructor(t){super(),this.error="",this.appliedChanges=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["ApplyAgentDiffError|1 error 9|2 applied_changes #0*",m]}}},"../proto/dist/generated/agent/v1/ask_question_tool_pb.js"(t,r,e){e.d(r,{OU:()=>o,ju:()=>a,ox:()=>h,tz:()=>m});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class o extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["AskQuestionToolCall|1 args #0|2 result #1",a,m]}}class a extends i{constructor(t){super(),this.title="",this.questions=[],this.runAsync=!1,this.asyncOriginalToolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["AskQuestionArgs|1 title 9|2 questions #0*|5 run_async 8|6 async_original_tool_call_id 9",u]}}class u extends i{constructor(t){super(),this.id="",this.prompt="",this.options=[],this.allowMultiple=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["AskQuestionArgs.Question|1 id 9|2 prompt 9|3 options #0*|4 allow_multiple 8|5 prompt_markdown 9?",c]}}class c extends i{constructor(t){super(),this.id="",this.label="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["AskQuestionArgs.Option|1 id 9|2 label 9"]}}class l extends i{constructor(t){super(),this.interactionId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["AskQuestionAsync|1 interaction_id 9"]}}class m extends i{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["AskQuestionResult|1 success #0 result|2 error #1 result|3 rejected #2 result|4 async #3 result",f,p,h,l]}}class f extends i{constructor(t){super(),this.answers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["AskQuestionSuccess|1 answers #0*",d]}}class d extends i{constructor(t){super(),this.questionId="",this.selectedOptionIds=[],this.freeformText="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["AskQuestionSuccess.Answer|1 question_id 9|2 selected_option_ids 9*|3 freeform_text 9"]}}class p extends i{constructor(t){super(),this.errorMessage="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["AskQuestionError|1 error_message 9"]}}class h extends i{constructor(t){super(),this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["AskQuestionRejected|1 reason 9"]}}},"../proto/dist/generated/agent/v1/background_shell_exec_pb.js"(t,r,e){e.d(r,{$P:()=>c,Gv:()=>g,LL:()=>d,Lt:()=>l,Of:()=>f,Po:()=>m,nt:()=>p,tR:()=>h});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/agent/v1/shell_exec_pb.js"),i=e("../proto/dist/generated/agent/v1/sandbox_pb.js"),o=e("../proto/dist/generated/agent/v1/utils_pb.js"),a=e("../proto/dist/runtime/compact.js");class u extends a.HL{static get runtime(){return(0,a.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class c extends u{constructor(t){super(),this.command="",this.workingDirectory="",this.toolCallId="",this.enableWriteShellStdinTool=!1,this.skipApproval=!1,this.adminCommandDenylist=[],this.suppressStdinLogging=!1,this.smartModeClassifierAllowed=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["BackgroundShellSpawnArgs|1 command 9|2 working_directory 9|3 tool_call_id 9|4 parsing_result #0|5 sandbox_policy #1?|6 enable_write_shell_stdin_tool 8|7 description 9?|8 classifier_result #2?|9 output_notification #3?|10 smart_mode_approval #4?|11 hook_approval_requirement #5?|12 skip_approval 8|13 conversation_id 9?|14 admin_command_denylist 9*|15 request_id 9?|16 suppress_stdin_logging 8|17 secret_scope_id 9?|18 smart_mode_classifier_allowed 8|19 desktop_lease_actor_id 9?",s.HO,i.Mw,s.E4,s.$F,o.UC,s.In]}}class l extends u{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["BackgroundShellSpawnResult|1 success #0 result|2 error #1 result|3 rejected #2 result|4 permission_denied #3 result|5 sandbox_unsupported #4 result",m,f,s.pZ,s.jn,s.rI]}}class m extends u{constructor(t){super(),this.shellId=0,this.command="",this.workingDirectory="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["BackgroundShellSpawnSuccess|1 shell_id 13|2 command 9|3 working_directory 9|4 pid 13?"]}}class f extends u{constructor(t){super(),this.command="",this.workingDirectory="",this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["BackgroundShellSpawnError|1 command 9|2 working_directory 9|3 error 9"]}}class d extends u{constructor(t){super(),this.shellId=0,this.chars="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["WriteShellStdinArgs|1 shell_id 13|2 chars 9"]}}class p extends u{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["WriteShellStdinResult|1 success #0 result|2 error #1 result",h,g]}}class h extends u{constructor(t){super(),this.shellId=0,this.terminalFileLengthBeforeInputWritten=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["WriteShellStdinSuccess|1 shell_id 13|2 terminal_file_length_before_input_written 13"]}}class g extends u{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["WriteShellStdinError|1 error 9"]}}},"../proto/dist/generated/agent/v1/canvas_diagnostics_exec_pb.js"(t,r,e){e.d(r,{GL:()=>u,HW:()=>l,uX:()=>c,yN:()=>a});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/agent/v1/diagnostics_exec_pb.js"),i=e("../proto/dist/runtime/compact.js");class o extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class a extends o{constructor(t){super(),this.path="",this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["CanvasDiagnosticsArgs|1 path 9|2 tool_call_id 9"]}}class u extends o{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["CanvasDiagnosticsResult|1 success #0 result|2 error #1 result|3 canvas_id 9?|4 title 9?|5 save_state 9?|6 save_detail 9?",c,l]}}class c extends o{constructor(t){super(),this.path="",this.diagnostics=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["CanvasDiagnosticsSuccess|1 path 9|2 diagnostics #0*",s.oQ]}}class l extends o{constructor(t){super(),this.path="",this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["CanvasDiagnosticsError|1 path 9|2 error 9"]}}},"../proto/dist/generated/agent/v1/computer_use_tool_pb.js"(t,r,e){e.d(r,{Dh:()=>u,EB:()=>c,Gx:()=>p,Jb:()=>C,K5:()=>f,OT:()=>d,Wd:()=>x,Z8:()=>l,ho:()=>g,ks:()=>v,qA:()=>E,t8:()=>T,w3:()=>a,xp:()=>m});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");const i="agent.v1.";class o extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return i}}var a=(0,s.QT)(n.proto3,i,"MouseButton",[[0,"UNSPECIFIED"],[1,"LEFT"],[2,"RIGHT"],[3,"MIDDLE"],[4,"BACK"],[5,"FORWARD"]],1),u=(0,s.QT)(n.proto3,i,"ScrollDirection",[[0,"UNSPECIFIED"],[1,"UP"],[2,"DOWN"],[3,"LEFT"],[4,"RIGHT"]],1),c=(0,s.QT)(n.proto3,i,"KeyStroke",[[0,"UNSPECIFIED"],[1,"TAP"],[2,"DOWN"],[3,"UP"]],1),l=(0,s.QT)(n.proto3,i,"ComputerUseDriver",[[0,"UNSPECIFIED"],[1,"XDOTOOL"],[2,"NATIVE_X11"]],1);class m extends o{constructor(t){super(),this.x=0,this.y=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["Coordinate|1 x 5|2 y 5"]}}class f extends o{constructor(t){super(),this.toolCallId="",this.actions=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["ComputerUseArgs|1 tool_call_id 9|2 actions #0*|3 description 9?|4 bind_unmapped_characters 8?|5 desktop_lease_actor_id 9?|6 screenshot_settle_ms 5?|10 native_x11_driver #1?|11 mark_monitor_busy 8?|9 full_resolution_screenshot 8?|12 capture_name_prefix 9?|13 omit_inline_screenshot 8?",g,h]}}class d extends o{constructor(t){super(),this.bcId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["ComputerUseEndTurnArgs|1 bc_id 9"]}}class p extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["ComputerUseEndTurnResult"]}}class h extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["NativeX11Driver|1 typing_delay_ms 5?|2 allow_fallback 8?"]}}class g extends o{constructor(t){super(),this.action={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["ComputerUseAction|1 mouse_move #0 action|2 click #1 action|3 mouse_down #2 action|4 mouse_up #3 action|5 drag #4 action|6 scroll #5 action|7 type #6 action|8 key #7 action|9 wait #8 action|10 screenshot #9 action|11 cursor_position #10 action",_,J,w,y,S,q,B,I,P,b,R]}}class _ extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _).fromBinary(t,r)}static fromJson(t,r){return(new _).fromJson(t,r)}static fromJsonString(t,r){return(new _).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_,t,r)}static $(){return["MouseMoveAction|1 coordinate #0",m]}}class J extends o{constructor(t){super(),this.button=a.UNSPECIFIED,this.count=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new J).fromBinary(t,r)}static fromJson(t,r){return(new J).fromJson(t,r)}static fromJsonString(t,r){return(new J).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(J,t,r)}static $(){return["ClickAction|1 coordinate #0?|2 button #1|3 count 5|4 modifier_keys 9?",m,a]}}class w extends o{constructor(t){super(),this.button=a.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new w).fromBinary(t,r)}static fromJson(t,r){return(new w).fromJson(t,r)}static fromJsonString(t,r){return(new w).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(w,t,r)}static $(){return["MouseDownAction|1 button #0",a]}}class y extends o{constructor(t){super(),this.button=a.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new y).fromBinary(t,r)}static fromJson(t,r){return(new y).fromJson(t,r)}static fromJsonString(t,r){return(new y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(y,t,r)}static $(){return["MouseUpAction|1 button #0",a]}}class S extends o{constructor(t){super(),this.path=[],this.button=a.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new S).fromBinary(t,r)}static fromJson(t,r){return(new S).fromJson(t,r)}static fromJsonString(t,r){return(new S).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(S,t,r)}static $(){return["DragAction|1 path #0*|2 button #1|3 modifier_keys 9?",m,a]}}class q extends o{constructor(t){super(),this.direction=u.UNSPECIFIED,this.amount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new q).fromBinary(t,r)}static fromJson(t,r){return(new q).fromJson(t,r)}static fromJsonString(t,r){return(new q).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(q,t,r)}static $(){return["ScrollAction|1 coordinate #0?|2 direction #1|3 amount 5|4 modifier_keys 9?",m,u]}}class B extends o{constructor(t){super(),this.text="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new B).fromBinary(t,r)}static fromJson(t,r){return(new B).fromJson(t,r)}static fromJsonString(t,r){return(new B).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(B,t,r)}static $(){return["TypeAction|1 text 9"]}}class I extends o{constructor(t){super(),this.key="",this.stroke=c.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new I).fromBinary(t,r)}static fromJson(t,r){return(new I).fromJson(t,r)}static fromJsonString(t,r){return(new I).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(I,t,r)}static $(){return["KeyAction|1 key 9|2 hold_duration_ms 5?|3 stroke #0",c]}}class P extends o{constructor(t){super(),this.durationMs=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new P).fromBinary(t,r)}static fromJson(t,r){return(new P).fromJson(t,r)}static fromJsonString(t,r){return(new P).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(P,t,r)}static $(){return["WaitAction|1 duration_ms 5"]}}class b extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new b).fromBinary(t,r)}static fromJson(t,r){return(new b).fromJson(t,r)}static fromJsonString(t,r){return(new b).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(b,t,r)}static $(){return["ScreenshotAction"]}}class R extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new R).fromBinary(t,r)}static fromJson(t,r){return(new R).fromJson(t,r)}static fromJsonString(t,r){return(new R).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(R,t,r)}static $(){return["CursorPositionAction"]}}class v extends o{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new v).fromBinary(t,r)}static fromJson(t,r){return(new v).fromJson(t,r)}static fromJsonString(t,r){return(new v).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(v,t,r)}static $(){return["ComputerUseResult|1 success #0 result|2 error #1 result",x,C]}}class x extends o{constructor(t){super(),this.actionCount=0,this.durationMs=0,this.typing=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new x).fromBinary(t,r)}static fromJson(t,r){return(new x).fromJson(t,r)}static fromJsonString(t,r){return(new x).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(x,t,r)}static $(){return["ComputerUseSuccess|1 action_count 5|2 duration_ms 5|3 screenshot 9?|4 log 9?|5 screenshot_path 9?|6 cursor_position #0?|7 settle_ms 5?|9 driver #1?|10 monitor_busy_marked 8?|11 full_resolution_screenshot #2?|12 typing #3*",m,l,k,E]}}class k extends o{constructor(t){super(),this.path="",this.sha256="",this.sizeBytes=0,this.width=0,this.height=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new k).fromBinary(t,r)}static fromJson(t,r){return(new k).fromJson(t,r)}static fromJsonString(t,r){return(new k).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(k,t,r)}static $(){return["ComputerUseFullResolutionScreenshot|1 path 9|2 sha256 9|3 size_bytes 13|4 width 5|5 height 5"]}}class E extends o{constructor(t){super(),this.method="",this.chars=0,this.atoms=0,this.typedAtoms=0,this.aborted=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new E).fromBinary(t,r)}static fromJson(t,r){return(new E).fromJson(t,r)}static fromJsonString(t,r){return(new E).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(E,t,r)}static $(){return["ComputerUseTyping|1 method 9|2 chars 5|3 atoms 5|4 typed_atoms 5|5 aborted 8|6 check 9?|7 verified 5?|8 unchecked 9?|9 landing 9?"]}}class C extends o{constructor(t){super(),this.error="",this.actionCount=0,this.durationMs=0,this.typing=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new C).fromBinary(t,r)}static fromJson(t,r){return(new C).fromJson(t,r)}static fromJsonString(t,r){return(new C).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(C,t,r)}static $(){return["ComputerUseError|1 error 9|2 action_count 5|3 duration_ms 5|4 log 9?|5 screenshot 9?|6 screenshot_path 9?|7 driver #0?|8 monitor_busy_marked 8?|9 typing #1*",l,E]}}class T extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new T).fromBinary(t,r)}static fromJson(t,r){return(new T).fromJson(t,r)}static fromJsonString(t,r){return(new T).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(T,t,r)}static $(){return["ComputerUseToolCall|1 args #0|2 result #1",f,v]}}},"../proto/dist/generated/agent/v1/connect_scm_tool_pb.js"(t,r,e){e.d(r,{$1:()=>_,O9:()=>w,iO:()=>g,ik:()=>S,lB:()=>y,qG:()=>J});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class o extends i{constructor(t){super(),this.toolCallId="",this.target={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["ConnectScmArgs|1 tool_call_id 9|2 github #0 target|3 gitlab #1 target|4 bitbucket #2 target|5 azure_devops #3 target|6 reconnect 8?|7 repo_url 9?|8 instance_host 9?",l,a,u,c]}}class a extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["ConnectScmGitlab|1 instance_id 9?"]}}class u extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["ConnectScmBitbucket|1 instance_id 9?"]}}class c extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["ConnectScmAzureDevops"]}}class l extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["ConnectScmGithub|1 repository #0|2 ghe_application 9?",m]}}class m extends i{constructor(t){super(),this.owner="",this.repo="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["ConnectScmGithubRepository|1 owner 9|2 repo 9"]}}class f extends i{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["ConnectScmResult|1 success #0 result|2 error #1 result|3 rejected #2 result|4 scm_target 9?",d,p,h]}}class d extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["ConnectScmSuccess"]}}class p extends i{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["ConnectScmError|1 error 9"]}}class h extends i{constructor(t){super(),this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["ConnectScmRejected|1 reason 9"]}}class g extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["ConnectScmToolCall|1 args #0|2 result #1",o,f]}}class _ extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _).fromBinary(t,r)}static fromJson(t,r){return(new _).fromJson(t,r)}static fromJsonString(t,r){return(new _).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_,t,r)}static $(){return["ConnectScmRequestQuery|1 args #0",o]}}class J extends i{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new J).fromBinary(t,r)}static fromJson(t,r){return(new J).fromJson(t,r)}static fromJsonString(t,r){return(new J).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(J,t,r)}static $(){return["ConnectScmRequestResponse|1 approved #0 result|2 rejected #1 result|3 failed #2 result",w,y,S]}}class w extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new w).fromBinary(t,r)}static fromJson(t,r){return(new w).fromJson(t,r)}static fromJsonString(t,r){return(new w).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(w,t,r)}static $(){return["ConnectScmRequestResponse.Approved|1 scm_target 9?"]}}class y extends i{constructor(t){super(),this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new y).fromBinary(t,r)}static fromJson(t,r){return(new y).fromJson(t,r)}static fromJsonString(t,r){return(new y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(y,t,r)}static $(){return["ConnectScmRequestResponse.Rejected|1 reason 9|2 recorded_args #0?",o]}}class S extends i{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new S).fromBinary(t,r)}static fromJson(t,r){return(new S).fromJson(t,r)}static fromJsonString(t,r){return(new S).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(S,t,r)}static $(){return["ConnectScmRequestResponse.Failed|1 error 9"]}}},"../proto/dist/generated/agent/v1/conversation_search_exec_pb.js"(t,r,e){e.d(r,{$m:()=>u,pT:()=>c});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");const i="agent.v1.";class o extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return i}}var a=(0,s.QT)(n.proto3,i,"ConversationSearchSource",[[0,"UNSPECIFIED"],[1,"LOCAL"],[2,"CLOUD_CACHE"]],1);class u extends o{constructor(t){super(),this.query="",this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["ConversationSearchArgs|1 query 9|2 tool_call_id 9|3 limit 5?"]}}class c extends o{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["ConversationSearchResult|1 success #0 result|2 error #1 result",l,f]}}class l extends o{constructor(t){super(),this.hits=[],this.truncated=!1,this.partial=!1,this.rebuilding=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["ConversationSearchSuccess|1 hits #0*|2 truncated 8|3 partial 8|4 rebuilding 8",m]}}class m extends o{constructor(t){super(),this.conversationId="",this.title="",this.source=a.UNSPECIFIED,this.updatedAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["ConversationSearchHit|1 conversation_id 9|2 title 9|3 source #0|4 updated_at_ms 3|5 snippet 9?",a]}}class f extends o{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["ConversationSearchError|1 error 9"]}}},"../proto/dist/generated/agent/v1/create_plan_tool_pb.js"(t,r,e){e.d(r,{Ih:()=>a,Jo:()=>m,bK:()=>l,gz:()=>p,iY:()=>f,vR:()=>d});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/agent/v1/todo_tool_pb.js"),i=e("../proto/dist/runtime/compact.js");class o extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class a extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["CreatePlanToolCall|1 args #0|2 result #1",c,l]}}class u extends o{constructor(t){super(),this.name="",this.todos=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["Phase|1 name 9|2 todos #0*",s.kW]}}class c extends o{constructor(t){super(),this.plan="",this.todos=[],this.overview="",this.name="",this.isProject=!1,this.phases=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["CreatePlanArgs|1 plan 9|2 todos #0*|3 overview 9|4 name 9|5 is_project 8|6 phases #1*",s.kW,u]}}class l extends o{constructor(t){super(),this.result={case:void 0},this.planUri="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["CreatePlanResult|1 success #0 result|2 error #1 result|3 plan_uri 9",m,f]}}class m extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["CreatePlanSuccess"]}}class f extends o{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["CreatePlanError|1 error 9"]}}class d extends o{constructor(t){super(),this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["CreatePlanRequestQuery|1 args #0|2 tool_call_id 9",c]}}class p extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["CreatePlanRequestResponse|1 result #0",l]}}},"../proto/dist/generated/agent/v1/cursor_rules_pb.js"(t,r,e){e.d(r,{DX:()=>d,Xo:()=>l,_u:()=>m,f5:()=>f,gv:()=>a,i9:()=>u,uT:()=>c});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");const i="agent.v1.";class o extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return i}}var a=(0,s.QT)(n.proto3,i,"CursorRuleSource",[[0,"UNSPECIFIED"],[1,"TEAM"],[2,"USER"]],1);class u extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["CursorRuleTypeGlobal"]}}class c extends o{constructor(t){super(),this.globs=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["CursorRuleTypeFileGlobs|1 globs 9*"]}}class l extends o{constructor(t){super(),this.description="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["CursorRuleTypeAgentFetched|1 description 9"]}}class m extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["CursorRuleTypeManuallyAttached"]}}class f extends o{constructor(t){super(),this.type={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["CursorRuleType|1 global #0 type|2 file_globbed #1 type|3 agent_fetched #2 type|4 manually_attached #3 type",u,c,l,m]}}class d extends o{constructor(t){super(),this.fullPath="",this.content="",this.source=a.UNSPECIFIED,this.environments=[],this.disabledEnvironments=[],this.scopedTo=[],this.frontmatter="",this.warnings=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["CursorRule|1 full_path 9|2 content 9|3 type #0|4 source #1|5 git_remote_origin 9?|6 parse_error 9?|7 environments 9*|8 disabled_environments 9*|9 plugin 9?|10 marketplace 9?|11 plugin_id 9?|12 marketplace_id 9?|13 scoped_to 9*|14 frontmatter 9|15 is_required 8?|16 warnings 9*|17 body_omitted 8?",f,a]}}},"../proto/dist/generated/agent/v1/delete_exec_pb.js"(t,r,e){e.d(r,{GU:()=>p,LX:()=>l,Pi:()=>a,QG:()=>m,dn:()=>o,fl:()=>u,iq:()=>d,n0:()=>c,vX:()=>f});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class o extends i{constructor(t){super(),this.path="",this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["DeleteArgs|1 path 9|2 tool_call_id 9"]}}class a extends i{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["DeleteResult|1 success #0 result|2 file_not_found #1 result|3 not_file #2 result|4 permission_denied #3 result|5 file_busy #4 result|6 rejected #5 result|7 error #6 result",u,c,l,m,f,d,p]}}class u extends i{constructor(t){super(),this.path="",this.deletedFile="",this.fileSize=n.protoInt64.zero,this.prevContent="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["DeleteSuccess|1 path 9|2 deleted_file 9|3 file_size 3|4 prev_content 9"]}}class c extends i{constructor(t){super(),this.path="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["DeleteFileNotFound|1 path 9"]}}class l extends i{constructor(t){super(),this.path="",this.actualType="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["DeleteNotFile|1 path 9|2 actual_type 9"]}}class m extends i{constructor(t){super(),this.path="",this.clientVisibleError="",this.isReadonly=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["DeletePermissionDenied|1 path 9|2 client_visible_error 9|3 is_readonly 8"]}}class f extends i{constructor(t){super(),this.path="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["DeleteFileBusy|1 path 9"]}}class d extends i{constructor(t){super(),this.path="",this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["DeleteRejected|1 path 9|2 reason 9"]}}class p extends i{constructor(t){super(),this.path="",this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["DeleteError|1 path 9|2 error 9"]}}},"../proto/dist/generated/agent/v1/diagnostics_exec_pb.js"(t,r,e){e.d(r,{Ek:()=>l,Ho:()=>d,J6:()=>p,Mu:()=>h,RP:()=>g,_B:()=>c,a1:()=>m,h_:()=>u,oQ:()=>f});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/agent/v1/utils_pb.js"),i=e("../proto/dist/runtime/compact.js");const o="agent.v1.";class a extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",n.proto3)}static $p(){return o}}var u=(0,i.QT)(n.proto3,o,"DiagnosticSeverity",[[0,"UNSPECIFIED"],[1,"ERROR"],[2,"WARNING"],[3,"INFORMATION"],[4,"HINT"]],1);class c extends a{constructor(t){super(),this.path="",this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["DiagnosticsArgs|1 path 9|2 tool_call_id 9"]}}class l extends a{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["DiagnosticsResult|1 success #0 result|2 error #1 result|3 rejected #2 result|4 file_not_found #3 result|5 permission_denied #4 result",m,d,p,h,g]}}class m extends a{constructor(t){super(),this.path="",this.diagnostics=[],this.totalDiagnostics=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["DiagnosticsSuccess|1 path 9|2 diagnostics #0*|3 total_diagnostics 5",f]}}class f extends a{constructor(t){super(),this.severity=u.UNSPECIFIED,this.message="",this.source="",this.code="",this.isStale=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["Diagnostic|1 severity #0|2 range #1|3 message 9|4 source 9|5 code 9|6 is_stale 8",u,s.Q6]}}class d extends a{constructor(t){super(),this.path="",this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["DiagnosticsError|1 path 9|2 error 9"]}}class p extends a{constructor(t){super(),this.path="",this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["DiagnosticsRejected|1 path 9|2 reason 9"]}}class h extends a{constructor(t){super(),this.path="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["DiagnosticsFileNotFound|1 path 9"]}}class g extends a{constructor(t){super(),this.path="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["DiagnosticsPermissionDenied|1 path 9"]}}},"../proto/dist/generated/agent/v1/exec_pb.js"(t,r,e){e.d(r,{$Y:()=>T,D9:()=>k,Fu:()=>E,Kg:()=>$,Nv:()=>A,S1:()=>N,VA:()=>C,Ye:()=>M,w5:()=>L,yT:()=>O});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/agent/v1/shell_exec_pb.js"),i=e("../proto/dist/generated/agent/v1/write_exec_pb.js"),o=e("../proto/dist/generated/agent/v1/delete_exec_pb.js"),a=e("../proto/dist/generated/agent/v1/grep_exec_pb.js"),u=e("../proto/dist/generated/agent/v1/read_exec_pb.js"),c=e("../proto/dist/generated/agent/v1/ls_exec_pb.js"),l=e("../proto/dist/generated/agent/v1/diagnostics_exec_pb.js"),m=e("../proto/dist/generated/agent/v1/request_context_exec_pb.js"),f=e("../proto/dist/generated/agent/v1/mcp_exec_pb.js"),d=e("../proto/dist/generated/agent/v1/background_shell_exec_pb.js"),p=e("../proto/dist/generated/agent/v1/fetch_exec_pb.js"),h=e("../proto/dist/generated/agent/v1/record_screen_exec_pb.js"),g=e("../proto/dist/generated/agent/v1/computer_use_tool_pb.js"),_=e("../proto/dist/generated/agent/v1/subagent_exec_pb.js"),J=e("../proto/dist/generated/agent/v1/smart_mode_classifier_exec_pb.js"),w=e("../proto/dist/generated/agent/v1/canvas_diagnostics_exec_pb.js"),y=e("../proto/dist/generated/agent/v1/shell_allowlist_precheck_exec_pb.js"),S=e("../proto/dist/generated/agent/v1/mcp_allowlist_precheck_exec_pb.js"),q=e("../proto/dist/generated/agent/v1/web_fetch_allowlist_precheck_exec_pb.js"),B=e("../proto/dist/generated/aiserver/v1/utils_pb.js"),I=e("../proto/dist/generated/agent/v1/conversation_search_exec_pb.js"),P=e("../proto/dist/generated/agent/v1/agent_store_conflict_exec_pb.js"),b=e("../proto/dist/generated/agent/v1/hook_additional_context_pb.js"),R=e("../proto/dist/generated/agent/v1/hooks_pb.js"),v=e("../proto/dist/runtime/compact.js");class x extends v.HL{static get runtime(){return(0,v.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class k extends x{constructor(t){super(),this.id=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new k).fromBinary(t,r)}static fromJson(t,r){return(new k).fromJson(t,r)}static fromJsonString(t,r){return(new k).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(k,t,r)}static $(){return["ExecClientStreamClose|1 id 13"]}}class E extends x{constructor(t){super(),this.id=0,this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new E).fromBinary(t,r)}static fromJson(t,r){return(new E).fromJson(t,r)}static fromJsonString(t,r){return(new E).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(E,t,r)}static $(){return["ExecClientThrow|1 id 13|2 error 9|3 stack_trace 9?|4 error_code 9?"]}}class C extends x{constructor(t){super(),this.id=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new C).fromBinary(t,r)}static fromJson(t,r){return(new C).fromJson(t,r)}static fromJsonString(t,r){return(new C).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(C,t,r)}static $(){return["ExecClientHeartbeat|1 id 13"]}}class T extends x{constructor(t){super(),this.message={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new T).fromBinary(t,r)}static fromJson(t,r){return(new T).fromJson(t,r)}static fromJsonString(t,r){return(new T).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(T,t,r)}static $(){return["ExecClientControlMessage|1 stream_close #0 message|2 throw #1 message|3 heartbeat #2 message",k,E,C]}}class U extends x{constructor(t){super(),this.id=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new U).fromBinary(t,r)}static fromJson(t,r){return(new U).fromJson(t,r)}static fromJsonString(t,r){return(new U).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(U,t,r)}static $(){return["ExecServerAbort|1 id 13"]}}class A extends x{constructor(t){super(),this.message={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new A).fromBinary(t,r)}static fromJson(t,r){return(new A).fromJson(t,r)}static fromJsonString(t,r){return(new A).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(A,t,r)}static $(){return["ExecServerControlMessage|1 abort #0 message",U]}}class $ extends x{constructor(t){super(),this.traceId="",this.spanId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $).fromBinary(t,r)}static fromJson(t,r){return(new $).fromJson(t,r)}static fromJsonString(t,r){return(new $).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($,t,r)}static $(){return["SpanContext|1 trace_id 9|2 span_id 9|3 trace_flags 13?|4 trace_state 9?"]}}class M extends x{constructor(t){super(),this.id=0,this.execId="",this.message={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new M).fromBinary(t,r)}static fromJson(t,r){return(new M).fromJson(t,r)}static fromJsonString(t,r){return(new M).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(M,t,r)}static $(){return["ExecServerMessage|1 id 13|15 exec_id 9|57 machine_id 9?|2 shell_args #0 message|3 write_args #1 message|4 delete_args #2 message|5 grep_args #3 message|7 read_args #4 message|29 redacted_read_args #4 message|8 ls_args #5 message|9 diagnostics_args #6 message|10 request_context_args #7 message|11 mcp_args #8 message|14 shell_stream_args #0 message|16 background_shell_spawn_args #9 message|17 list_mcp_resources_exec_args #10 message|18 read_mcp_resource_exec_args #11 message|36 mcp_state_exec_args #12 message|20 fetch_args #13 message|21 record_screen_args #14 message|22 computer_use_args #15 message|23 write_shell_stdin_args #16 message|27 execute_hook_args #17 message|28 subagent_args #18 message|30 force_background_shell_args #19 message|31 force_background_subagent_args #20 message|37 subagent_await_args #21 message|38 smart_mode_classifier_args #22 message|40 canvas_diagnostics_args #23 message|41 shell_allowlist_precheck_args #24 message|42 mcp_allowlist_precheck_args #25 message|43 web_fetch_allowlist_precheck_args #26 message|44 git_diff_request #27 message|52 mini_swe_agent_bash_args #0 message|53 conversation_search_args #28 message|54 agent_store_conflict_args #29 message|60 computer_use_end_turn_args #30 message|19 span_context #31?|55 accept_hook_additional_contexts 8?|58 record_agent_view 8?|59 refuse_unread_changes 8?",s.a,i.hY,o.dn,a.Qj,u.a2,c.xe,l._B,m._K,f.E_,d.$P,f.kj,f.DI,f.Km,p.UM,h.zH,g.K5,d.LL,D,_.Pw,s.Hu,_.S3,_.TN,J.Th,w.yN,y.C,S.c,q.K,B.Vq,I.$m,P.Uz,g.OT,$]}}class O extends x{constructor(t){super(),this.id=0,this.execId="",this.hookAdditionalContexts=[],this.message={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new O).fromBinary(t,r)}static fromJson(t,r){return(new O).fromJson(t,r)}static fromJsonString(t,r){return(new O).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(O,t,r)}static $(){return["ExecClientMessage|1 id 13|15 exec_id 9|39 local_execution_time_ms 5?|45 hook_additional_contexts #0*|2 shell_result #1 message|3 write_result #2 message|4 delete_result #3 message|5 grep_result #4 message|7 read_result #5 message|29 redacted_read_result #5 message|8 ls_result #6 message|9 diagnostics_result #7 message|10 request_context_result #8 message|11 mcp_result #9 message|14 shell_stream #10 message|16 background_shell_spawn_result #11 message|17 list_mcp_resources_exec_result #12 message|18 read_mcp_resource_exec_result #13 message|36 mcp_state_exec_result #14 message|20 fetch_result #15 message|21 record_screen_result #16 message|22 computer_use_result #17 message|23 write_shell_stdin_result #18 message|27 execute_hook_result #19 message|28 subagent_result #20 message|30 force_background_shell_result #21 message|31 force_background_subagent_result #22 message|37 subagent_await_result #23 message|38 smart_mode_classifier_result #24 message|40 canvas_diagnostics_result #25 message|41 shell_allowlist_precheck_result #26 message|42 mcp_allowlist_precheck_result #27 message|43 web_fetch_allowlist_precheck_result #28 message|44 git_diff_response #29 message|53 conversation_search_result #30 message|54 agent_store_conflict_result #31 message|55 mini_swe_agent_bash_result #1 message|57 computer_use_end_turn_result #32 message",b.C,s.W4,i.v3,o.Pi,a.Ud,u.sV,c.fv,l.Ek,m._G,f.iz,s.FI,d.Lt,f.kP,f.ZD,f._W,p.uN,h.Tj,g.ks,d.nt,N,_.vS,s.jK,_.a3,_.zJ,J.bN,w.GL,y.e,S.M,q.M,B.df,I.pT,P.Ev,g.Gx]}}class D extends x{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new D).fromBinary(t,r)}static fromJson(t,r){return(new D).fromJson(t,r)}static fromJsonString(t,r){return(new D).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(D,t,r)}static $(){return["ExecuteHookArgs|1 request #0",G]}}class N extends x{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new N).fromBinary(t,r)}static fromJson(t,r){return(new N).fromJson(t,r)}static fromJsonString(t,r){return(new N).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(N,t,r)}static $(){return["ExecuteHookResult|1 response #0",L]}}class G extends x{constructor(t){super(),this.request={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new G).fromBinary(t,r)}static fromJson(t,r){return(new G).fromJson(t,r)}static fromJsonString(t,r){return(new G).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(G,t,r)}static $(){return["ExecuteHookRequest|1 pre_compact #0 request|2 subagent_start #1 request|3 subagent_stop #2 request|4 pre_tool_use #3 request|5 post_tool_use #4 request|6 post_tool_use_failure #5 request|7 before_submit_prompt #6 request|8 after_agent_response #7 request|9 after_agent_thought #8 request|11 stop #9 request",R.Ks,R.b3,R.ty,R.CI,R.rY,R.hy,R.D2,R.mL,R.AL,R.Od]}}class L extends x{constructor(t){super(),this.response={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new L).fromBinary(t,r)}static fromJson(t,r){return(new L).fromJson(t,r)}static fromJsonString(t,r){return(new L).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(L,t,r)}static $(){return["ExecuteHookResponse|1 pre_compact #0 response|2 subagent_start #1 response|3 subagent_stop #2 response|4 pre_tool_use #3 response|5 post_tool_use #4 response|6 post_tool_use_failure #5 response|7 before_submit_prompt #6 response|8 after_agent_response #7 response|9 after_agent_thought #8 response|11 stop #9 response",R.$_,R.W0,R.AH,R.Wn,R.uB,R.U1,R.u1,R.FW,R.H,R.rT]}}},"../proto/dist/generated/agent/v1/fetch_exec_pb.js"(t,r,e){e.d(r,{UM:()=>o,Uk:()=>u,fk:()=>c,uN:()=>a});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class o extends i{constructor(t){super(),this.url="",this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["FetchArgs|1 url 9|2 tool_call_id 9"]}}class a extends i{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["FetchResult|1 success #0 result|2 error #1 result",u,c]}}class u extends i{constructor(t){super(),this.url="",this.content="",this.statusCode=0,this.contentType="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["FetchSuccess|1 url 9|2 content 9|3 status_code 5|4 content_type 9"]}}class c extends i{constructor(t){super(),this.url="",this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["FetchError|1 url 9|2 error 9"]}}},"../proto/dist/generated/agent/v1/generate_image_tool_pb.js"(t,r,e){e.d(r,{Uj:()=>m,Uq:()=>p,k4:()=>a,l3:()=>d,r9:()=>l,vW:()=>f});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class o extends i{constructor(t){super(),this.description="",this.referenceImagePaths=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["GenerateImageArgs|1 description 9|2 file_path 9?|5 reference_image_paths 9*|6 aspect_ratio 9?"]}}class a extends i{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["GenerateImageResult|1 success #0 result|2 error #1 result",u,c]}}class u extends i{constructor(t){super(),this.filePath="",this.imageData="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["GenerateImageSuccess|1 file_path 9|2 image_data 9"]}}class c extends i{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["GenerateImageError|1 error 9"]}}class l extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["GenerateImageToolCall|1 args #0|2 result #1",o,a]}}class m extends i{constructor(t){super(),this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["GenerateImageRequestQuery|1 args #0|2 tool_call_id 9",o]}}class f extends i{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["GenerateImageRequestResponse|1 approved #0 result|2 rejected #1 result",d,p]}}class d extends i{constructor(t){super(),this.description="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["GenerateImageRequestResponse.Approved|1 description 9"]}}class p extends i{constructor(t){super(),this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["GenerateImageRequestResponse.Rejected|1 reason 9"]}}},"../proto/dist/generated/agent/v1/grep_exec_pb.js"(t,r,e){e.d(r,{Qj:()=>a,T7:()=>p,Ud:()=>u,Zp:()=>h,_0:()=>l,dx:()=>_,sS:()=>d,ts:()=>c,uI:()=>g,vD:()=>m,xA:()=>f});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/agent/v1/sandbox_pb.js"),i=e("../proto/dist/runtime/compact.js");class o extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class a extends o{constructor(t){super(),this.pattern="",this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["GrepArgs|1 pattern 9|2 path 9?|3 glob 9?|4 output_mode 9?|5 context_before 5?|6 context_after 5?|7 context 5?|8 case_insensitive 8?|9 type 9?|10 head_limit 5?|11 multiline 8?|12 sort 9?|13 sort_ascending 8?|14 tool_call_id 9|15 sandbox_policy #0?|16 offset 5?",s.Mw]}}class u extends o{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["GrepResult|1 success #0 result|2 error #1 result",l,c]}}class c extends o{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["GrepError|1 error 9"]}}class l extends o{constructor(t){super(),this.pattern="",this.path="",this.outputMode="",this.workspaceResults={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["GrepSuccess|1 pattern 9|2 path 9|3 output_mode 9|4 workspace_results 9,#0|5 active_editor_result #0?",m]}}class m extends o{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["GrepUnionResult|1 count #0 result|2 files #1 result|3 content #2 result",f,p,h]}}class f extends o{constructor(t){super(),this.counts=[],this.totalFiles=0,this.totalMatches=0,this.clientTruncated=!1,this.ripgrepTruncated=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["GrepCountResult|1 counts #0*|2 total_files 5|3 total_matches 5|4 client_truncated 8|5 ripgrep_truncated 8|6 head_limit_applied 5?|7 offset_applied 5?",d]}}class d extends o{constructor(t){super(),this.file="",this.count=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["GrepFileCount|1 file 9|2 count 5"]}}class p extends o{constructor(t){super(),this.files=[],this.totalFiles=0,this.clientTruncated=!1,this.ripgrepTruncated=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["GrepFilesResult|1 files 9*|2 total_files 5|3 client_truncated 8|4 ripgrep_truncated 8|5 head_limit_applied 5?|6 offset_applied 5?"]}}class h extends o{constructor(t){super(),this.matches=[],this.totalLines=0,this.totalMatchedLines=0,this.clientTruncated=!1,this.ripgrepTruncated=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["GrepContentResult|1 matches #0*|2 total_lines 5|3 total_matched_lines 5|4 client_truncated 8|5 ripgrep_truncated 8|6 head_limit_applied 5?|7 offset_applied 5?",g]}}class g extends o{constructor(t){super(),this.file="",this.matches=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["GrepFileMatch|1 file 9|2 matches #0*",_]}}class _ extends o{constructor(t){super(),this.lineNumber=0,this.content="",this.contentTruncated=!1,this.isContextLine=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _).fromBinary(t,r)}static fromJson(t,r){return(new _).fromJson(t,r)}static fromJsonString(t,r){return(new _).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_,t,r)}static $(){return["GrepContentMatch|1 line_number 5|2 content 9|3 content_truncated 8|4 is_context_line 8"]}}},"../proto/dist/generated/agent/v1/hook_additional_context_pb.js"(t,r,e){e.d(r,{C:()=>o});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class o extends i{constructor(t){super(),this.hookEventName="",this.content="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["HookAdditionalContext|1 hook_event_name 9|2 content 9"]}}},"../proto/dist/generated/agent/v1/hooks_pb.js"(t,r,e){e.d(r,{$_:()=>u,AH:()=>f,AL:()=>J,CI:()=>q,D2:()=>p,FW:()=>_,H:()=>w,Ks:()=>a,Od:()=>y,U1:()=>R,W0:()=>l,Wn:()=>B,b3:()=>c,hy:()=>b,mL:()=>g,rT:()=>S,rY:()=>I,ty:()=>m,u1:()=>h,uB:()=>P});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/agent/v1/requested_model_pb.js"),i=e("../proto/dist/runtime/compact.js");class o extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class a extends o{constructor(t){super(),this.trigger="",this.contextUsagePercent=0,this.contextTokens=n.protoInt64.zero,this.contextWindowSize=n.protoInt64.zero,this.messageCount=0,this.messagesToCompact=0,this.isFirstCompaction=!1,this.modelParams=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["PreCompactRequestQuery|1 trigger 9|2 context_usage_percent 1|3 context_tokens 3|4 context_window_size 3|5 message_count 5|6 messages_to_compact 5|7 is_first_compaction 8|8 conversation_id 9?|9 generation_id 9?|10 model 9?|11 model_id 9?|12 model_params #0*",s.SR]}}class u extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["PreCompactRequestResponse|1 user_message 9?"]}}class c extends o{constructor(t){super(),this.subagentId="",this.subagentType="",this.task="",this.parentConversationId="",this.isParallelWorker=!1,this.modelParams=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["SubagentStartRequestQuery|1 subagent_id 9|2 subagent_type 9|3 task 9|4 parent_conversation_id 9|5 tool_call_id 9?|6 subagent_model 9?|7 is_parallel_worker 8|8 git_branch 9?|9 conversation_id 9?|10 generation_id 9?|11 model 9?|12 model_id 9?|13 model_params #0*",s.SR]}}class l extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["SubagentStartRequestResponse|1 permission 9?|2 user_message 9?|3 additional_context 9?"]}}class m extends o{constructor(t){super(),this.subagentId="",this.subagentType="",this.status="",this.durationMs=n.protoInt64.zero,this.parentConversationId="",this.messageCount=0,this.toolCallCount=0,this.modifiedFiles=[],this.loopCount=0,this.modelParams=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["SubagentStopRequestQuery|1 subagent_id 9|2 subagent_type 9|3 status 9|4 duration_ms 3|5 summary 9?|6 parent_conversation_id 9|7 message_count 5|8 tool_call_count 5|9 error_message 9?|10 modified_files 9*|11 git_branch 9?|12 conversation_id 9?|13 generation_id 9?|14 model 9?|15 loop_count 5|16 task 9?|17 description 9?|18 model_id 9?|19 model_params #0*|20 child_conversation_id 9?",s.SR]}}class f extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["SubagentStopRequestResponse|1 followup_message 9?|2 additional_context 9?"]}}class d extends o{constructor(t){super(),this.type="",this.filePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["BeforeSubmitPromptAttachment|1 type 9|2 file_path 9"]}}class p extends o{constructor(t){super(),this.prompt="",this.attachments=[],this.modelParams=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["BeforeSubmitPromptRequestQuery|1 prompt 9|2 attachments #0*|3 composer_mode 9?|4 conversation_id 9?|5 generation_id 9?|6 model 9?|7 model_id 9?|8 model_params #1*",d,s.SR]}}class h extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["BeforeSubmitPromptRequestResponse|1 continue 8?|2 user_message 9?|3 additional_context 9?"]}}class g extends o{constructor(t){super(),this.text="",this.modelParams=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["AfterAgentResponseRequestQuery|1 text 9|2 conversation_id 9?|3 generation_id 9?|4 model 9?|5 model_id 9?|6 model_params #0*|7 input_tokens 3?|8 output_tokens 3?|9 cache_read_tokens 3?|10 cache_write_tokens 3?",s.SR]}}class _ extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _).fromBinary(t,r)}static fromJson(t,r){return(new _).fromJson(t,r)}static fromJsonString(t,r){return(new _).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_,t,r)}static $(){return["AfterAgentResponseRequestResponse"]}}class J extends o{constructor(t){super(),this.text="",this.modelParams=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new J).fromBinary(t,r)}static fromJson(t,r){return(new J).fromJson(t,r)}static fromJsonString(t,r){return(new J).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(J,t,r)}static $(){return["AfterAgentThoughtRequestQuery|1 text 9|2 duration_ms 3?|3 conversation_id 9?|4 generation_id 9?|5 model 9?|6 model_id 9?|7 model_params #0*",s.SR]}}class w extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new w).fromBinary(t,r)}static fromJson(t,r){return(new w).fromJson(t,r)}static fromJsonString(t,r){return(new w).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(w,t,r)}static $(){return["AfterAgentThoughtRequestResponse"]}}class y extends o{constructor(t){super(),this.status="",this.loopCount=0,this.modelParams=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new y).fromBinary(t,r)}static fromJson(t,r){return(new y).fromJson(t,r)}static fromJsonString(t,r){return(new y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(y,t,r)}static $(){return["StopRequestQuery|1 status 9|2 loop_count 5|3 conversation_id 9?|4 generation_id 9?|5 model 9?|6 model_id 9?|7 model_params #0*|8 input_tokens 3?|9 output_tokens 3?|10 cache_read_tokens 3?|11 cache_write_tokens 3?",s.SR]}}class S extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new S).fromBinary(t,r)}static fromJson(t,r){return(new S).fromJson(t,r)}static fromJsonString(t,r){return(new S).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(S,t,r)}static $(){return["StopRequestResponse|1 followup_message 9?"]}}class q extends o{constructor(t){super(),this.toolName="",this.toolUseId="",this.modelParams=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new q).fromBinary(t,r)}static fromJson(t,r){return(new q).fromJson(t,r)}static fromJsonString(t,r){return(new q).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(q,t,r)}static $(){return["PreToolUseRequestQuery|1 tool_name 9|2 tool_input #0|3 tool_use_id 9|4 cwd 9?|5 conversation_id 9?|6 generation_id 9?|7 model 9?|8 model_id 9?|9 model_params #1*|10 parent_tool_call_id 9?",n.Struct,s.SR]}}class B extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new B).fromBinary(t,r)}static fromJson(t,r){return(new B).fromJson(t,r)}static fromJsonString(t,r){return(new B).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(B,t,r)}static $(){return["PreToolUseRequestResponse|1 permission 9?|2 user_message 9?|3 agent_message 9?|4 updated_input 9?|5 additional_context 9?"]}}class I extends o{constructor(t){super(),this.toolName="",this.toolOutput="",this.durationMs=n.protoInt64.zero,this.toolUseId="",this.modelParams=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new I).fromBinary(t,r)}static fromJson(t,r){return(new I).fromJson(t,r)}static fromJsonString(t,r){return(new I).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(I,t,r)}static $(){return["PostToolUseRequestQuery|1 tool_name 9|2 tool_input #0|3 tool_output 9|4 duration_ms 3|5 tool_use_id 9|6 cwd 9?|7 conversation_id 9?|8 generation_id 9?|9 model 9?|10 model_id 9?|11 model_params #1*|12 parent_tool_call_id 9?",n.Struct,s.SR]}}class P extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new P).fromBinary(t,r)}static fromJson(t,r){return(new P).fromJson(t,r)}static fromJsonString(t,r){return(new P).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(P,t,r)}static $(){return["PostToolUseRequestResponse|1 additional_context 9?|2 updated_mcp_tool_output 9?"]}}class b extends o{constructor(t){super(),this.toolName="",this.errorMessage="",this.failureType="",this.durationMs=n.protoInt64.zero,this.toolUseId="",this.isInterrupt=!1,this.modelParams=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new b).fromBinary(t,r)}static fromJson(t,r){return(new b).fromJson(t,r)}static fromJsonString(t,r){return(new b).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(b,t,r)}static $(){return["PostToolUseFailureRequestQuery|1 tool_name 9|2 tool_input #0|3 error_message 9|4 failure_type 9|5 duration_ms 3|6 tool_use_id 9|7 is_interrupt 8|8 conversation_id 9?|9 generation_id 9?|10 model 9?|11 model_id 9?|12 model_params #1*|13 parent_tool_call_id 9?",n.Struct,s.SR]}}class R extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new R).fromBinary(t,r)}static fromJson(t,r){return(new R).fromJson(t,r)}static fromJsonString(t,r){return(new R).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(R,t,r)}static $(){return["PostToolUseFailureRequestResponse|1 additional_context 9?"]}}},"../proto/dist/generated/agent/v1/kv_pb.js"(t,r,e){e.d(r,{gm:()=>d,km:()=>f});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/agent/v1/exec_pb.js"),i=e("../proto/dist/runtime/compact.js");class o extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class a extends o{constructor(t){super(),this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["Error|1 message 9"]}}class u extends o{constructor(t){super(),this.blobId=new Uint8Array(0),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["GetBlobArgs|1 blob_id 12"]}}class c extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["GetBlobResult|1 blob_data 12?|2 error #0?",a]}}class l extends o{constructor(t){super(),this.blobId=new Uint8Array(0),this.blobData=new Uint8Array(0),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["SetBlobArgs|1 blob_id 12|2 blob_data 12"]}}class m extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["SetBlobResult|1 error #0?",a]}}class f extends o{constructor(t){super(),this.id=0,this.message={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["KvServerMessage|1 id 13|2 get_blob_args #0 message|3 set_blob_args #1 message|4 span_context #2?",u,l,s.Kg]}}class d extends o{constructor(t){super(),this.id=0,this.message={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["KvClientMessage|1 id 13|2 get_blob_result #0 message|3 set_blob_result #1 message",c,m]}}},"../proto/dist/generated/agent/v1/ls_exec_pb.js"(t,r,e){e.d(r,{PC:()=>c,Y$:()=>h,fv:()=>u,k2:()=>d,uj:()=>f,ur:()=>m,vq:()=>l,xe:()=>a,ze:()=>p});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/agent/v1/sandbox_pb.js"),i=e("../proto/dist/runtime/compact.js");class o extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class a extends o{constructor(t){super(),this.path="",this.ignore=[],this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["LsArgs|1 path 9|2 ignore 9*|3 tool_call_id 9|4 sandbox_policy #0?|5 timeout_ms 13?",s.Mw]}}class u extends o{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["LsResult|1 success #0 result|2 error #1 result|3 rejected #2 result|4 timeout #3 result",c,f,d,p]}}class c extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["LsSuccess|1 directory_tree_root #0",l]}}class l extends o{constructor(t){super(),this.absPath="",this.childrenDirs=[],this.childrenFiles=[],this.childrenWereProcessed=!1,this.fullSubtreeExtensionCounts={},this.numFiles=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["LsDirectoryTreeNode|1 abs_path 9|2 children_dirs #0*|3 children_files #1*|4 children_were_processed 8|5 full_subtree_extension_counts 9,5|6 num_files 5",l,m]}}class m extends o{constructor(t){super(),this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["LsDirectoryTreeNode.File|1 name 9|2 terminal_metadata #0?",h]}}class f extends o{constructor(t){super(),this.path="",this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["LsError|1 path 9|2 error 9"]}}class d extends o{constructor(t){super(),this.path="",this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["LsRejected|1 path 9|2 reason 9"]}}class p extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["LsTimeout|1 directory_tree_root #0",l]}}class h extends o{constructor(t){super(),this.lastCommands=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["TerminalMetadata|1 cwd 9?|2 last_commands #0*|3 last_modified_ms 3?|4 current_command #0?",g]}}class g extends o{constructor(t){super(),this.command="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["TerminalMetadata.Command|1 command 9|2 exit_code 5?|3 timestamp_ms 3?|4 duration_ms 3?"]}}},"../proto/dist/generated/agent/v1/mcp_allowlist_precheck_exec_pb.js"(t,r,e){e.d(r,{M:()=>a,c:()=>o});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class o extends i{constructor(t){super(),this.providerIdentifier="",this.toolName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["McpAllowlistPrecheckArgs|1 provider_identifier 9|2 tool_name 9|3 tool_call_id 9?|4 annotations_json 9?"]}}class a extends i{constructor(t){super(),this.allowlisted=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["McpAllowlistPrecheckResult|1 allowlisted 8"]}}},"../proto/dist/generated/agent/v1/mcp_auth_tool_pb.js"(t,r,e){e.d(r,{D5:()=>p,NX:()=>m,OI:()=>h,h:()=>d,uL:()=>f});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class o extends i{constructor(t){super(),this.serverIdentifier="",this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["McpAuthArgs|1 server_identifier 9|2 tool_call_id 9|3 plugin_id 9?"]}}class a extends i{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["McpAuthResult|1 success #0 result|2 error #1 result|3 rejected #2 result",u,c,l]}}class u extends i{constructor(t){super(),this.serverIdentifier="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["McpAuthSuccess|1 server_identifier 9"]}}class c extends i{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["McpAuthError|1 error 9"]}}class l extends i{constructor(t){super(),this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["McpAuthRejected|1 reason 9"]}}class m extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["McpAuthToolCall|1 args #0|2 result #1",o,a]}}class f extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["McpAuthRequestQuery|1 args #0",o]}}class d extends i{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["McpAuthRequestResponse|1 approved #0 result|2 rejected #1 result",p,h]}}class p extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["McpAuthRequestResponse.Approved"]}}class h extends i{constructor(t){super(),this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["McpAuthRequestResponse.Rejected|1 reason 9"]}}},"../proto/dist/generated/agent/v1/mcp_exec_pb.js"(t,r,e){e.d(r,{D0:()=>E,DI:()=>F,Dh:()=>H,E_:()=>f,HQ:()=>v,JL:()=>_,Jx:()=>j,KZ:()=>z,Ke:()=>h,Km:()=>x,Kp:()=>S,Nh:()=>I,QW:()=>q,T2:()=>N,WV:()=>g,X2:()=>D,XE:()=>T,ZD:()=>K,Zl:()=>c,_W:()=>C,_Z:()=>y,do:()=>w,ew:()=>l,iz:()=>p,kP:()=>O,kj:()=>M,ov:()=>W,pv:()=>U,w2:()=>G,xo:()=>R,zN:()=>J,zj:()=>m});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/agent/v1/utils_pb.js"),i=e("../proto/dist/generated/agent/v1/mcp_pb.js"),o=e("../proto/dist/runtime/compact.js");const a="agent.v1.";class u extends o.HL{static get runtime(){return(0,o.kU)(this,"runtime",n.proto3)}static $p(){return a}}var c=(0,o.QT)(n.proto3,a,"McpPolicyBlockedReason",[[0,"UNSPECIFIED"],[1,"MCP_SERVERS_OFF"],[2,"MCP_ALLOWLIST"],[3,"CLOUD_AGENT_ALLOWLIST"],[4,"DENYLIST"],[5,"APPLIES_TO"],[6,"TOOL_ACCESS"]],1),l=(0,o.QT)(n.proto3,a,"McpRefreshPolicy",[[0,"UNSPECIFIED"],[1,"FORCE_IF_MISSING"],[2,"FORCE"]],1),m=(0,o.QT)(n.proto3,a,"McpServerTransport",[[0,"UNSPECIFIED"],[1,"STDIO"],[2,"HTTP"]],1);class f extends u{constructor(t){super(),this.name="",this.args={},this.toolCallId="",this.providerIdentifier="",this.toolName="",this.smartModeApprovalOnly=!1,this.skipApproval=!1,this.serverIdentifier="",this.symbolicPathArguments=[],this.argumentsRepaired=!1,this.refuseSavedSecrets=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["McpArgs|1 name 9|2 args 9,#0|3 tool_call_id 9|4 provider_identifier 9|5 tool_name 9|6 smart_mode_approval #1?|7 smart_mode_approval_only 8|8 skip_approval 8|9 server_identifier 9|10 symbolic_path_arguments #2*|11 arguments_repaired 8|12 refuse_saved_secrets 8",n.Value,s.UC,d]}}class d extends u{constructor(t){super(),this.path="",this.sha256="",this.sizeBytes=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["McpSymbolicPathArgument|1 path 9|2 sha256 9|3 size_bytes 3"]}}class p extends u{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["McpResult|1 success #0 result|2 error #1 result|3 rejected #2 result|4 permission_denied #3 result|5 tool_not_found #4 result|6 server_not_found #5 result|7 approved #6 result",q,I,R,v,g,_,h]}}class h extends u{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["McpApproved"]}}class g extends u{constructor(t){super(),this.name="",this.availableTools=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["McpToolNotFound|1 name 9|2 available_tools 9*|3 recovery #0?",P]}}class _ extends u{constructor(t){super(),this.name="",this.availableServers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _).fromBinary(t,r)}static fromJson(t,r){return(new _).fromJson(t,r)}static fromJsonString(t,r){return(new _).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_,t,r)}static $(){return["McpServerNotFound|1 name 9|2 available_servers 9*"]}}class J extends u{constructor(t){super(),this.text="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new J).fromBinary(t,r)}static fromJson(t,r){return(new J).fromJson(t,r)}static fromJsonString(t,r){return(new J).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(J,t,r)}static $(){return["McpTextContent|1 text 9|2 output_location #0?",s.pV]}}class w extends u{constructor(t){super(),this.data=new Uint8Array(0),this.mimeType="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new w).fromBinary(t,r)}static fromJson(t,r){return(new w).fromJson(t,r)}static fromJsonString(t,r){return(new w).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(w,t,r)}static $(){return["McpImageContent|1 data 12|2 mime_type 9"]}}class y extends u{constructor(t){super(),this.content={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new y).fromBinary(t,r)}static fromJson(t,r){return(new y).fromJson(t,r)}static fromJsonString(t,r){return(new y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(y,t,r)}static $(){return["McpToolResultContentItem|1 text #0 content|2 image #1 content",J,w]}}class S extends u{constructor(t){super(),this.body="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new S).fromBinary(t,r)}static fromJson(t,r){return(new S).fromJson(t,r)}static fromJsonString(t,r){return(new S).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(S,t,r)}static $(){return["SystemReminder|1 body 9"]}}class q extends u{constructor(t){super(),this.content=[],this.isError=!1,this.systemReminders=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new q).fromBinary(t,r)}static fromJson(t,r){return(new q).fromJson(t,r)}static fromJsonString(t,r){return(new q).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(q,t,r)}static $(){return["McpSuccess|1 content #0*|2 is_error 8|3 structured_content #1|4 system_reminders #2*|5 result_meta #1|6 mcp_app_document #3",y,n.Struct,S,B]}}class B extends u{constructor(t){super(),this.uri="",this.mimeType="",this.text="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new B).fromBinary(t,r)}static fromJson(t,r){return(new B).fromJson(t,r)}static fromJsonString(t,r){return(new B).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(B,t,r)}static $(){return["McpAppDocument|1 uri 9|2 mime_type 9|3 text 9|4 meta_json 9?"]}}class I extends u{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new I).fromBinary(t,r)}static fromJson(t,r){return(new I).fromJson(t,r)}static fromJsonString(t,r){return(new I).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(I,t,r)}static $(){return["McpError|1 error 9|2 needs_auth 8?|3 recovery #0?|4 http_status 5?|5 retry_after_ms 13?|6 not_dialed 8?|7 bearer_error 9?|8 policy_blocked_reason #1?",P,c]}}class P extends u{constructor(t){super(),this.outcome=b.UNSPECIFIED,this.availableTools=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new P).fromBinary(t,r)}static fromJson(t,r){return(new P).fromJson(t,r)}static fromJsonString(t,r){return(new P).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(P,t,r)}static $(){return["McpRecovery|1 outcome #0|2 fresh_input_schema_json 9?|3 available_tools 9*",b]}}var b=(0,o.QT)(n.proto3,a,"McpRecovery.Outcome",[[0,"UNSPECIFIED"],[1,"CHANGED"],[2,"REMOVED"],[3,"UNCHANGED"],[4,"REFRESH_FAILED"]],1);class R extends u{constructor(t){super(),this.reason="",this.isReadonly=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new R).fromBinary(t,r)}static fromJson(t,r){return(new R).fromJson(t,r)}static fromJsonString(t,r){return(new R).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(R,t,r)}static $(){return["McpRejected|1 reason 9|2 is_readonly 8"]}}class v extends u{constructor(t){super(),this.error="",this.isReadonly=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new v).fromBinary(t,r)}static fromJson(t,r){return(new v).fromJson(t,r)}static fromJsonString(t,r){return(new v).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(v,t,r)}static $(){return["McpPermissionDenied|1 error 9|2 is_readonly 8"]}}class x extends u{constructor(t){super(),this.serverIdentifiers=[],this.kickOnly=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new x).fromBinary(t,r)}static fromJson(t,r){return(new x).fromJson(t,r)}static fromJsonString(t,r){return(new x).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(x,t,r)}static $(){return["McpStateExecArgs|1 server_identifiers 9*|2 kick_only 8|3 refresh_policy #0?|4 rule_subjects #1?",l,k]}}class k extends u{constructor(t){super(),this.commandPatterns=[],this.serverUrlPatterns=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new k).fromBinary(t,r)}static fromJson(t,r){return(new k).fromJson(t,r)}static fromJsonString(t,r){return(new k).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(k,t,r)}static $(){return["McpRuleSubjectsRequest|1 command_patterns 9*|2 server_url_patterns 9*"]}}class E extends u{constructor(t){super(),this.transport=m.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new E).fromBinary(t,r)}static fromJson(t,r){return(new E).fromJson(t,r)}static fromJsonString(t,r){return(new E).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(E,t,r)}static $(){return["McpRuleSubject|1 transport #0|2 value 9?",m]}}class C extends u{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new C).fromBinary(t,r)}static fromJson(t,r){return(new C).fromJson(t,r)}static fromJsonString(t,r){return(new C).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(C,t,r)}static $(){return["McpStateExecResult|1 success #0 result|2 error #1 result|3 rejected #2 result",U,A,$]}}class T extends u{constructor(t){super(),this.serverName="",this.serverIdentifier="",this.tools=[],this.instructions=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new T).fromBinary(t,r)}static fromJson(t,r){return(new T).fromJson(t,r)}static fromJsonString(t,r){return(new T).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(T,t,r)}static $(){return["McpStateServer|1 server_name 9|2 server_identifier 9|3 plugin 9?|4 marketplace 9?|5 tools #0*|6 instructions #1*|7 status 9?|8 error_message 9?|9 pending_sign_in 8?|10 transport #2?|11 account_label 9?|12 rule_subject #3?",i.gd,i.I0,m,E]}}class U extends u{constructor(t){super(),this.servers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new U).fromBinary(t,r)}static fromJson(t,r){return(new U).fromJson(t,r)}static fromJsonString(t,r){return(new U).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(U,t,r)}static $(){return["McpStateSuccess|1 servers #0*",T]}}class A extends u{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new A).fromBinary(t,r)}static fromJson(t,r){return(new A).fromJson(t,r)}static fromJsonString(t,r){return(new A).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(A,t,r)}static $(){return["McpStateError|1 error 9"]}}class $ extends u{constructor(t){super(),this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $).fromBinary(t,r)}static fromJson(t,r){return(new $).fromJson(t,r)}static fromJsonString(t,r){return(new $).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($,t,r)}static $(){return["McpStateRejected|1 reason 9"]}}class M extends u{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new M).fromBinary(t,r)}static fromJson(t,r){return(new M).fromJson(t,r)}static fromJsonString(t,r){return(new M).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(M,t,r)}static $(){return["ListMcpResourcesExecArgs|1 server 9?"]}}class O extends u{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new O).fromBinary(t,r)}static fromJson(t,r){return(new O).fromJson(t,r)}static fromJsonString(t,r){return(new O).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(O,t,r)}static $(){return["ListMcpResourcesExecResult|1 success #0 result|2 error #1 result|3 rejected #2 result",N,G,L]}}class D extends u{constructor(t){super(),this.uri="",this.server="",this.annotations={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new D).fromBinary(t,r)}static fromJson(t,r){return(new D).fromJson(t,r)}static fromJsonString(t,r){return(new D).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(D,t,r)}static $(){return["ListMcpResourcesExecResult.McpResource|1 uri 9|2 name 9?|3 description 9?|4 mime_type 9?|5 server 9|6 annotations 9,9"]}}class N extends u{constructor(t){super(),this.resources=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new N).fromBinary(t,r)}static fromJson(t,r){return(new N).fromJson(t,r)}static fromJsonString(t,r){return(new N).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(N,t,r)}static $(){return["ListMcpResourcesSuccess|1 resources #0*",D]}}class G extends u{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new G).fromBinary(t,r)}static fromJson(t,r){return(new G).fromJson(t,r)}static fromJsonString(t,r){return(new G).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(G,t,r)}static $(){return["ListMcpResourcesError|1 error 9"]}}class L extends u{constructor(t){super(),this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new L).fromBinary(t,r)}static fromJson(t,r){return(new L).fromJson(t,r)}static fromJsonString(t,r){return(new L).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(L,t,r)}static $(){return["ListMcpResourcesRejected|1 reason 9"]}}class F extends u{constructor(t){super(),this.server="",this.uri="",this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new F).fromBinary(t,r)}static fromJson(t,r){return(new F).fromJson(t,r)}static fromJsonString(t,r){return(new F).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(F,t,r)}static $(){return["ReadMcpResourceExecArgs|1 server 9|2 uri 9|3 download_path 9?|4 tool_call_id 9|5 smart_mode_approval #0?",s.UC]}}class K extends u{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new K).fromBinary(t,r)}static fromJson(t,r){return(new K).fromJson(t,r)}static fromJsonString(t,r){return(new K).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(K,t,r)}static $(){return["ReadMcpResourceExecResult|1 success #0 result|2 error #1 result|3 rejected #2 result|4 not_found #3 result",z,j,H,W]}}class z extends u{constructor(t){super(),this.uri="",this.content={case:void 0},this.annotations={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new z).fromBinary(t,r)}static fromJson(t,r){return(new z).fromJson(t,r)}static fromJsonString(t,r){return(new z).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(z,t,r)}static $(){return["ReadMcpResourceSuccess|1 uri 9|2 name 9?|3 description 9?|4 mime_type 9?|5 text 9 content|6 blob 12 content|7 annotations 9,9|8 download_path 9?|9 output_location #0?|10 meta_json 9?",s.pV]}}class j extends u{constructor(t){super(),this.uri="",this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new j).fromBinary(t,r)}static fromJson(t,r){return(new j).fromJson(t,r)}static fromJsonString(t,r){return(new j).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(j,t,r)}static $(){return["ReadMcpResourceError|1 uri 9|2 error 9"]}}class H extends u{constructor(t){super(),this.uri="",this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new H).fromBinary(t,r)}static fromJson(t,r){return(new H).fromJson(t,r)}static fromJsonString(t,r){return(new H).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(H,t,r)}static $(){return["ReadMcpResourceRejected|1 uri 9|2 reason 9"]}}class W extends u{constructor(t){super(),this.uri="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new W).fromBinary(t,r)}static fromJson(t,r){return(new W).fromJson(t,r)}static fromJsonString(t,r){return(new W).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(W,t,r)}static $(){return["ReadMcpResourceNotFound|1 uri 9"]}}},"../proto/dist/generated/agent/v1/mcp_pb.js"(t,r,e){e.d(r,{E$:()=>l,I0:()=>u,Is:()=>m,Or:()=>a,UC:()=>c,U_:()=>f,gd:()=>o});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class o extends i{constructor(t){super(),this.name="",this.providerIdentifier="",this.toolName="",this.description="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["McpToolDefinition|1 name 9|4 provider_identifier 9|5 tool_name 9|2 description 9|3 input_schema #0|6 input_schema_json 9?|7 output_schema_json 9?|8 annotations_json 9?|9 meta_json 9?",n.Value]}}class a extends i{constructor(t){super(),this.mcpTools=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["McpTools|1 mcp_tools #0*",o]}}class u extends i{constructor(t){super(),this.serverName="",this.instructions="",this.serverIdentifier="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["McpInstructions|1 server_name 9|2 instructions 9|3 server_identifier 9"]}}class c extends i{constructor(t){super(),this.serverName="",this.serverIdentifier="",this.tools=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["McpDescriptor|1 server_name 9|2 server_identifier 9|3 folder_path 9?|4 server_use_instructions 9?|5 tools #0*|7 plugin 9?|8 marketplace 9?|9 plugin_db_id 9?|10 marketplace_id 9?|11 account_label 9?",l]}}class l extends i{constructor(t){super(),this.toolName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["McpToolDescriptor|1 tool_name 9|2 definition_path 9?|3 description 9?|4 input_schema #0?|5 input_schema_json 9?|6 annotations_json 9?",n.Value]}}class m extends i{constructor(t){super(),this.enabled=!1,this.workspaceProjectDir="",this.mcpDescriptors=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["McpFileSystemOptions|1 enabled 8|2 workspace_project_dir 9|3 mcp_descriptors #0*",c]}}class f extends i{constructor(t){super(),this.enabled=!1,this.mcpDescriptors=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["McpMetaToolOptions|1 enabled 8|2 mcp_descriptors #0*",c]}}},"../proto/dist/generated/agent/v1/pr_management_tool_pb.js"(t,r,e){e.d(r,{AU:()=>R,DY:()=>v,HL:()=>y,K$:()=>B});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");const i="agent.v1.";class o extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return i}}var a=(0,s.QT)(n.proto3,i,"MergePrMode",[[0,"UNSPECIFIED"],[1,"MERGE"],[2,"AUTO"],[3,"DISABLE_AUTO"]],1),u=(0,s.QT)(n.proto3,i,"MergePrMethod",[[0,"UNSPECIFIED"],[1,"MERGE"],[2,"SQUASH"]],1),c=(0,s.QT)(n.proto3,i,"PullRequestStatus",[[0,"UNSPECIFIED"],[1,"OPEN"],[2,"CLOSED"]],1);class l extends o{constructor(t){super(),this.toolCallId="",this.action={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["PrManagementArgs|1 tool_call_id 9|2 create_pr #0 action|3 update_pr #1 action|4 post_comment #2 action|5 resolve_comment #3 action|6 get_ci_status #4 action|7 set_pr_status #5 action|8 merge_pr #6 action|9 list_prs #7 action|10 get_pr #8 action",m,f,d,p,h,g,_,J,w]}}class m extends o{constructor(t){super(),this.title="",this.body="",this.branchName="",this.addLabels=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["CreatePrAction|1 title 9|2 body 9|3 base_branch 9?|4 draft 8?|5 branch_name 9|6 add_labels 9*|7 repo_url 9?|8 skip_branch_prefix_check 8?|9 stack_on_pr_number 3?"]}}class f extends o{constructor(t){super(),this.addLabels=[],this.removeLabels=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["UpdatePrAction|1 pr_url 9?|2 title 9?|3 body 9?|4 base_branch 9?|5 branch_name 9?|6 add_labels 9*|7 remove_labels 9*|8 repo_url 9?|9 stack_on_pr_number 3?|10 clear_stack 8?|11 draft 8?"]}}class d extends o{constructor(t){super(),this.body="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["PostCommentAction|1 pr_url 9?|2 branch_name 9?|3 body 9|4 repo_url 9?|5 in_reply_to 3?|6 path 9?|7 line 5?|8 start_line 5?|9 side 9?|10 reply_to_reference 9?"]}}class p extends o{constructor(t){super(),this.commentId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["ResolveCommentAction|1 pr_url 9?|2 branch_name 9?|3 comment_id 3|4 repo_url 9?|5 comment_reference 9?"]}}class h extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["GetCiStatusAction|1 pr_url 9?|2 branch_name 9?|3 repo_url 9?"]}}class g extends o{constructor(t){super(),this.status=c.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["SetPrStatusAction|1 pr_url 9?|2 branch_name 9?|3 repo_url 9?|4 status #0",c]}}class _ extends o{constructor(t){super(),this.mode=a.UNSPECIFIED,this.method=u.UNSPECIFIED,this.expectedMemberHeadShas={},this.downstack=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _).fromBinary(t,r)}static fromJson(t,r){return(new _).fromJson(t,r)}static fromJsonString(t,r){return(new _).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_,t,r)}static $(){return["MergePrAction|1 pr_url 9?|2 branch_name 9?|3 repo_url 9?|4 mode #0|5 method #1|6 expected_head_sha 9?|7 expected_member_head_shas 9,9|8 downstack 8",a,u]}}class J extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new J).fromBinary(t,r)}static fromJson(t,r){return(new J).fromJson(t,r)}static fromJsonString(t,r){return(new J).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(J,t,r)}static $(){return["ListPrsArgs|1 limit 5?"]}}class w extends o{constructor(t){super(),this.prUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new w).fromBinary(t,r)}static fromJson(t,r){return(new w).fromJson(t,r)}static fromJsonString(t,r){return(new w).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(w,t,r)}static $(){return["GetPrArgs|1 pr_url 9"]}}class y extends o{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new y).fromBinary(t,r)}static fromJson(t,r){return(new y).fromJson(t,r)}static fromJsonString(t,r){return(new y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(y,t,r)}static $(){return["PrManagementResult|1 success #0 result|2 error #1 result|3 rejected #2 result|4 registered #3 result|5 needs_confirmation #4 result|6 read #5 result",q,B,I,P,b,S]}}class S extends o{constructor(t){super(),this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new S).fromBinary(t,r)}static fromJson(t,r){return(new S).fromJson(t,r)}static fromJsonString(t,r){return(new S).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(S,t,r)}static $(){return["PrManagementRead|1 message 9"]}}class q extends o{constructor(t){super(),this.prUrl="",this.prNumber=0,this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new q).fromBinary(t,r)}static fromJson(t,r){return(new q).fromJson(t,r)}static fromJsonString(t,r){return(new q).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(q,t,r)}static $(){return["PrManagementSuccess|1 pr_url 9|2 pr_number 5|3 message 9"]}}class B extends o{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new B).fromBinary(t,r)}static fromJson(t,r){return(new B).fromJson(t,r)}static fromJsonString(t,r){return(new B).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(B,t,r)}static $(){return["PrManagementError|1 error 9"]}}class I extends o{constructor(t){super(),this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new I).fromBinary(t,r)}static fromJson(t,r){return(new I).fromJson(t,r)}static fromJsonString(t,r){return(new I).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(I,t,r)}static $(){return["PrManagementRejected|1 reason 9"]}}class P extends o{constructor(t){super(),this.message="",this.title="",this.body="",this.branchName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new P).fromBinary(t,r)}static fromJson(t,r){return(new P).fromJson(t,r)}static fromJsonString(t,r){return(new P).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(P,t,r)}static $(){return["PrManagementRegistered|1 message 9|2 title 9|3 body 9|4 base_branch 9?|5 draft 8?|6 branch_name 9"]}}class b extends o{constructor(t){super(),this.message="",this.discoveredPrUrl="",this.discoveredPrNumber=0,this.discoveredPrTitle="",this.branchName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new b).fromBinary(t,r)}static fromJson(t,r){return(new b).fromJson(t,r)}static fromJsonString(t,r){return(new b).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(b,t,r)}static $(){return["PrManagementNeedsConfirmation|1 message 9|2 discovered_pr_url 9|3 discovered_pr_number 5|4 discovered_pr_title 9|5 branch_name 9"]}}class R extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new R).fromBinary(t,r)}static fromJson(t,r){return(new R).fromJson(t,r)}static fromJsonString(t,r){return(new R).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(R,t,r)}static $(){return["PrManagementToolCall|1 args #0|2 result #1",l,y]}}class v extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new v).fromBinary(t,r)}static fromJson(t,r){return(new v).fromJson(t,r)}static fromJsonString(t,r){return(new v).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(v,t,r)}static $(){return["PrManagementRequestQuery|1 args #0",l]}}},"../proto/dist/generated/agent/v1/read_exec_pb.js"(t,r,e){e.d(r,{F_:()=>c,Ko:()=>m,a2:()=>o,cW:()=>d,f4:()=>l,lW:()=>f,mE:()=>u,sV:()=>a});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class o extends i{constructor(t){super(),this.path="",this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["ReadArgs|1 path 9|2 tool_call_id 9|4 offset 5?|5 limit 13?|6 encoding_hint 9?|7 digest_only 8?|8 max_chars 13?|9 max_video_bytes 13?"]}}class a extends i{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["ReadResult|1 success #0 result|2 error #1 result|3 rejected #2 result|4 file_not_found #3 result|5 permission_denied #4 result|6 invalid_file #5 result",u,c,l,m,f,d]}}class u extends i{constructor(t){super(),this.path="",this.output={case:void 0},this.totalLines=0,this.fileSize=n.protoInt64.zero,this.truncated=!1,this.rangeApplied=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["ReadSuccess|1 path 9|2 content 9 output|5 data 12 output|3 total_lines 5|4 file_size 3|6 truncated 8|7 output_blob_id 12?|8 range_applied 8|9 sha256 9?|10 size_bytes 3?|11 redacted 8?"]}}class c extends i{constructor(t){super(),this.path="",this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["ReadError|1 path 9|2 error 9"]}}class l extends i{constructor(t){super(),this.path="",this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["ReadRejected|1 path 9|2 reason 9"]}}class m extends i{constructor(t){super(),this.path="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["ReadFileNotFound|1 path 9"]}}class f extends i{constructor(t){super(),this.path="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["ReadPermissionDenied|1 path 9"]}}class d extends i{constructor(t){super(),this.path="",this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["ReadInvalidFile|1 path 9|2 reason 9"]}}},"../proto/dist/generated/agent/v1/record_screen_exec_pb.js"(t,r,e){e.d(r,{$u:()=>a,N8:()=>p,T4:()=>f,Tj:()=>m,Wg:()=>c,ol:()=>d,y:()=>u,yH:()=>h,zH:()=>l});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");const i="agent.v1.";class o extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return i}}var a=(0,s.QT)(n.proto3,i,"RecordingMode",[[0,"UNSPECIFIED"],[1,"START_RECORDING"],[2,"SAVE_RECORDING"],[3,"DISCARD_RECORDING"]],1),u=(0,s.QT)(n.proto3,i,"RequestedFilePathRejectedReason",[[0,"UNSPECIFIED"],[1,"SLASHES_NOT_ALLOWED"]],1),c=(0,s.QT)(n.proto3,i,"RecordScreenFailureKind",[[0,"UNSPECIFIED"],[1,"INVALID_MODE"],[2,"STAGING_IO"],[3,"DISPLAY_UNAVAILABLE"],[4,"FFMPEG_START_FAILED"],[5,"NO_ACTIVE_RECORDING"],[6,"SAVE_IN_PROGRESS"],[7,"FFMPEG_STOP_FAILED"],[8,"PROXY_MISSING"],[9,"PROXY_INVALID"],[10,"RENDERER_UNAVAILABLE"],[11,"RENDER_FAILED"],[12,"ARTIFACT_WRITE_FAILED"],[13,"INTERNAL"],[14,"DESKTOP_HELD"],[15,"HOOK_REJECTED"],[16,"EXEC_FAILED"]],1);class l extends o{constructor(t){super(),this.mode=a.UNSPECIFIED,this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["RecordScreenArgs|1 mode #0|2 tool_call_id 9|3 save_as_filename 9?|4 desktop_lease_actor_id 9?",a]}}class m extends o{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["RecordScreenResult|1 start_success #0 result|2 save_success #1 result|3 discard_success #2 result|4 failure #3 result",f,d,p,h]}}class f extends o{constructor(t){super(),this.wasPriorRecordingCancelled=!1,this.wasSaveAsFilenameIgnored=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["RecordScreenStartSuccess|1 was_prior_recording_cancelled 8|2 was_save_as_filename_ignored 8"]}}class d extends o{constructor(t){super(),this.path="",this.recordingDurationMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["RecordScreenSaveSuccess|1 path 9|2 recording_duration_ms 3|3 requested_file_path_rejected_reason #0?",u]}}class p extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["RecordScreenDiscardSuccess"]}}class h extends o{constructor(t){super(),this.error="",this.kind=c.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["RecordScreenFailure|1 error 9|2 kind #0",c]}}},"../proto/dist/generated/agent/v1/replace_env_tool_pb.js"(t,r,e){e.d(r,{TO:()=>l,dV:()=>d,km:()=>h,uq:()=>f,us:()=>p});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");const i="agent.v1.";class o extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return i}}var a=(0,s.QT)(n.proto3,i,"ReplaceEnvMode",[[0,"UNSPECIFIED"],[1,"CUSTOM"],[2,"CLEAN_SLATE"],[3,"DEFAULT"]],1);class u extends o{constructor(t){super(),this.repoUrl="",this.ref="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["RepoCheckoutRefOverride|1 repo_url 9|2 ref 9"]}}class c extends o{constructor(t){super(),this.installScript="",this.dockerfileContents="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["ReplaceEnvConfig|1 install_script 9|2 dockerfile_contents 9"]}}class l extends o{constructor(t){super(),this.mode=a.UNSPECIFIED,this.checkoutRefOverrides=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["ReplaceEnvArgs|1 config #0|2 mode #1|3 checkout_ref_overrides #2*",c,a,u]}}class m extends o{constructor(t){super(),this.setupLogs="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["ReplaceEnvSuccess|1 setup_logs 9"]}}class f extends o{constructor(t){super(),this.errorMessage="",this.setupLogs="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["ReplaceEnvFailure|1 error_message 9|2 setup_logs 9"]}}class d extends o{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["ReplaceEnvResult|1 success #0 result|2 failure #1 result",m,f]}}class p extends o{constructor(t){super(),this.associatedPodKey="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["ReplaceEnvToolCall|1 args #0|2 result #1|3 associated_pod_key 9",l,d]}}class h extends o{constructor(t){super(),this.associatedPodKey="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["ReplaceEnvToolCallDelta|1 associated_pod_key 9"]}}},"../proto/dist/generated/agent/v1/report_bugfix_results_tool_pb.js"(t,r,e){e.d(r,{RH:()=>l,U_:()=>d,Y6:()=>u,q3:()=>m});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");const i="agent.v1.";class o extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return i}}var a=(0,s.QT)(n.proto3,i,"BugfixVerdict",[[0,"UNSPECIFIED"],[1,"FIXED"],[2,"FALSE_POSITIVE"],[3,"COULD_NOT_FIX"],[4,"RESOLVED_BY_OTHER_FIX"]],1);class u extends o{constructor(t){super(),this.bugId="",this.bugTitle="",this.verdict=a.UNSPECIFIED,this.explanation="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["BugfixResultItem|1 bug_id 9|2 bug_title 9|3 verdict #0|4 explanation 9|5 severity 9?",a]}}class c extends o{constructor(t){super(),this.summary="",this.results=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["ReportBugfixResultsArgs|1 summary 9|2 results #0*",u]}}class l extends o{constructor(t){super(),this.results=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["ReportBugfixResultsSuccess|1 results #0*",u]}}class m extends o{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["ReportBugfixResultsError|1 error 9"]}}class f extends o{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["ReportBugfixResultsResult|1 success #0 result|2 error #1 result",l,m]}}class d extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["ReportBugfixResultsToolCall|1 args #0|2 result #1",c,f]}}},"../proto/dist/generated/agent/v1/request_context_exec_pb.js"(t,r,e){e.d(r,{TT:()=>v,DS:()=>B,Jy:()=>E,bb:()=>A,_K:()=>J,GE:()=>I,nf:()=>S,vB:()=>D,sG:()=>N,_G:()=>w,T3:()=>$,CB:()=>M,yb:()=>O,yW:()=>y,uw:()=>k});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");s.HL;var i=(0,s.QT)(n.proto3,"agent.v1.","PackageType",[[0,"UNSPECIFIED"],[1,"CURSOR_PROJECT"],[2,"CURSOR_PERSONAL"],[3,"CLAUDE_SKILL"],[4,"CLAUDE_PLUGIN"]],1),o=e("../proto/dist/generated/agent/v1/cursor_rules_pb.js");class a extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class u extends a{constructor(t){super(),this.relativeWorkspacePath="",this.remoteUrls=[],this.remoteNames=[],this.repoName="",this.repoOwner="",this.isTracked=!1,this.isLocal=!1,this.workspaceUri="",this.pathEncryptionKey="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["RepositoryIndexingInfo|1 relative_workspace_path 9|2 remote_urls 9*|3 remote_names 9*|4 repo_name 9|5 repo_owner 9|6 is_tracked 8|7 is_local 8|8 orthogonal_transform_seed 1?|9 workspace_uri 9|10 path_encryption_key 9"]}}var c=e("../proto/dist/generated/agent/v1/mcp_pb.js"),l=e("../proto/dist/generated/agent/v1/ls_exec_pb.js"),m=e("../proto/dist/generated/agent/v1/subagents_pb.js"),f=e("../proto/dist/generated/agent/v1/agent_skills_pb.js"),d=e("../proto/dist/generated/agent/v1/system_prompt_pb.js");const p="agent.v1.";class h extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return p}}var g=(0,s.QT)(n.proto3,p,"ComputerUseDesktopPlatform",[[0,"UNSPECIFIED"],[1,"LINUX"],[2,"MACOS"],[3,"WINDOWS"]],1),_=(0,s.QT)(n.proto3,p,"MountedAgentStoreKind",[[0,"UNSPECIFIED"],[1,"SELF"],[2,"PEER"],[3,"SHARE"],[4,"PRINCIPAL"]],1);class J extends h{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new J).fromBinary(t,r)}static fromJson(t,r){return(new J).fromJson(t,r)}static fromJsonString(t,r){return(new J).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(J,t,r)}static $(){return["RequestContextArgs|2 notes_session_id 9?|3 workspace_id 9?|4 read_only_pinned_tree_sha 9?|5 read_only_plugin_cache_root 9?|7 use_cached 8?|8 wait_for_workspace_cache 8?"]}}class w extends h{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new w).fromBinary(t,r)}static fromJson(t,r){return(new w).fromJson(t,r)}static fromJsonString(t,r){return(new w).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(w,t,r)}static $(){return["RequestContextResult|1 success #0 result|2 error #1 result|3 rejected #2 result",y,S,q]}}class y extends h{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new y).fromBinary(t,r)}static fromJson(t,r){return(new y).fromJson(t,r)}static fromJsonString(t,r){return(new y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(y,t,r)}static $(){return["RequestContextSuccess|1 request_context #0|2 served_from_disk_cache 8?",A]}}class S extends h{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new S).fromBinary(t,r)}static fromJson(t,r){return(new S).fromJson(t,r)}static fromJsonString(t,r){return(new S).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(S,t,r)}static $(){return["RequestContextError|1 error 9"]}}class q extends h{constructor(t){super(),this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new q).fromBinary(t,r)}static fromJson(t,r){return(new q).fromJson(t,r)}static fromJsonString(t,r){return(new q).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(q,t,r)}static $(){return["RequestContextRejected|1 reason 9"]}}class B extends h{constructor(t){super(),this.path="",this.status="",this.branchName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new B).fromBinary(t,r)}static fromJson(t,r){return(new B).fromJson(t,r)}static fromJsonString(t,r){return(new B).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(B,t,r)}static $(){return["GitRepoInfo|1 path 9|2 status 9|3 branch_name 9|4 remote_url 9?|5 previous_branch_is_ancestor 8?|6 is_origin_backed 8?"]}}class I extends h{constructor(t){super(),this.osVersion="",this.workspacePaths=[],this.shell="",this.sandboxEnabled=!1,this.terminalsFolder="",this.agentSharedNotesFolder="",this.agentConversationNotesFolder="",this.timeZone="",this.projectFolder="",this.agentTranscriptsFolder="",this.sandboxNetworkExplicitAllowlist=[],this.mountedAgentStores=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new I).fromBinary(t,r)}static fromJson(t,r){return(new I).fromJson(t,r)}static fromJsonString(t,r){return(new I).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(I,t,r)}static $(){return["RequestContextEnv|1 os_version 9|2 workspace_paths 9*|3 shell 9|5 sandbox_enabled 8|7 terminals_folder 9|8 agent_shared_notes_folder 9|9 agent_conversation_notes_folder 9|10 time_zone 9|11 project_folder 9|12 agent_transcripts_folder 9|13 artifacts_folder 9?|14 sandbox_supported 8?|16 sandbox_network_has_defaults 8?|17 sandbox_network_explicit_allowlist 9*|18 secret_redaction_enabled 8?|19 computer_use_supported 8?|20 is_working_dir_home_dir 8?|21 process_working_directory 9?|22 smart_mode_classifier_auto_mode_enabled 8?|23 dev_force_next_smart_mode_classifier_block_token 9?|24 dev_delay_next_smart_mode_classifier_token 9?|25 mounted_agent_stores #0*|26 user_agent_store_web_context #1?|27 dev_mock_prompt_time #2?|28 agent_store_dynamic_mount_enabled 8?|29 computer_use_desktop #3?",b,R,n.Timestamp,P]}}class P extends h{constructor(t){super(),this.platform=g.UNSPECIFIED,this.canvasWidth=0,this.canvasHeight=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new P).fromBinary(t,r)}static fromJson(t,r){return(new P).fromJson(t,r)}static fromJsonString(t,r){return(new P).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(P,t,r)}static $(){return["ComputerUseDesktop|1 platform #0|2 canvas_width 5|3 canvas_height 5",g]}}class b extends h{constructor(t){super(),this.path="",this.kind=_.UNSPECIFIED,this.readOnly=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new b).fromBinary(t,r)}static fromJson(t,r){return(new b).fromJson(t,r)}static fromJsonString(t,r){return(new b).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(b,t,r)}static $(){return["MountedAgentStore|1 path 9|2 kind #0|3 alias 9?|4 read_only 8|5 inherited_from_path 9?",_]}}class R extends h{constructor(t){super(),this.storeId="",this.portalBaseUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new R).fromBinary(t,r)}static fromJson(t,r){return(new R).fromJson(t,r)}static fromJsonString(t,r){return(new R).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(R,t,r)}static $(){return["UserAgentStoreWebContext|1 store_id 9|2 portal_base_url 9"]}}class v extends h{constructor(t){super(),this.logPath="",this.serverEndpoint="",this.sessionId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new v).fromBinary(t,r)}static fromJson(t,r){return(new v).fromJson(t,r)}static fromJsonString(t,r){return(new v).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(v,t,r)}static $(){return["DebugModeConfig|1 log_path 9|2 server_endpoint 9|3 session_id 9"]}}class x extends h{constructor(t){super(),this.name="",this.description="",this.folderPath="",this.enabled=!1,this.readmeFilePath="",this.packageType=i.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new x).fromBinary(t,r)}static fromJson(t,r){return(new x).fromJson(t,r)}static fromJsonString(t,r){return(new x).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(x,t,r)}static $(){return["SkillDescriptor|1 name 9|2 description 9|3 folder_path 9|4 enabled 8|5 parse_error 9?|6 readme_file_path 9|7 package_type #0",i]}}class k extends h{constructor(t){super(),this.skillDescriptors=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new k).fromBinary(t,r)}static fromJson(t,r){return(new k).fromJson(t,r)}static fromJsonString(t,r){return(new k).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(k,t,r)}static $(){return["SkillOptions|1 skill_descriptors #0*",x]}}class E extends h{constructor(t){super(),this.configuredSteps=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new E).fromBinary(t,r)}static fromJson(t,r){return(new E).fromJson(t,r)}static fromJsonString(t,r){return(new E).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(E,t,r)}static $(){return["HooksConfigInfo|1 configured_steps 9*"]}}class C extends h{constructor(t){super(),this.allowInstructions=[],this.blockInstructions=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new C).fromBinary(t,r)}static fromJson(t,r){return(new C).fromJson(t,r)}static fromJsonString(t,r){return(new C).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(C,t,r)}static $(){return["PermissionsAutoRunInstructions|1 allow_instructions 9*|2 block_instructions 9*"]}}class T extends h{constructor(t){super(),this.startLineNumber=0,this.endLineNumberExclusive=0,this.beforeContextLines=[],this.removedLines=[],this.addedLines=[],this.afterContextLines=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new T).fromBinary(t,r)}static fromJson(t,r){return(new T).fromJson(t,r)}static fromJsonString(t,r){return(new T).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(T,t,r)}static $(){return["PrecomputedHumanChangeRenderedDiff|1 start_line_number 5|2 end_line_number_exclusive 5|3 before_context_lines 9*|4 removed_lines 9*|5 added_lines 9*|6 after_context_lines 9*"]}}class U extends h{constructor(t){super(),this.path="",this.renderedDiffs=[],this.isNewFile=!1,this.isDeletedFile=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new U).fromBinary(t,r)}static fromJson(t,r){return(new U).fromJson(t,r)}static fromJsonString(t,r){return(new U).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(U,t,r)}static $(){return["PrecomputedHumanChange|1 path 9|2 rendered_diffs #0*|3 is_new_file 8|4 is_deleted_file 8",T]}}class A extends h{constructor(t){super(),this.rules=[],this.repositoryInfo=[],this.tools=[],this.gitRepos=[],this.projectLayouts=[],this.mcpInstructions=[],this.fileContents={},this.customSubagents=[],this.agentSkills=[],this.precomputedHumanChanges=[],this.nonFileRules=[],this.disabledTeamRules=[],this.adminCommandDenylist=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new A).fromBinary(t,r)}static fromJson(t,r){return(new A).fromJson(t,r)}static fromJsonString(t,r){return(new A).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(A,t,r)}static $(){return["RequestContext|2 rules #0*|4 env #1|6 repository_info #2*|7 tools #3*|8 conversation_notes_listing 9?|9 shared_notes_listing 9?|11 git_repos #4*|13 project_layouts #5*|14 mcp_instructions #6*|15 debug_mode_config #7?|16 cloud_rule 9?|17 web_search_enabled 8?|18 skill_options #8?|19 repository_info_should_query_prod 8?|20 file_contents 9,9|21 user_intent_summary 9?|22 custom_subagents #9*|23 mcp_file_system_options #10?|24 web_fetch_enabled 8?|25 hooks_additional_context 9?|26 commit_attribution_message 9?|27 pr_attribution_message 9?|28 hooks_config #11?|29 agent_skills #12*|30 precomputed_human_changes #13*|31 recently_added_plugin #14?|32 supports_mcp_auth 8?|33 git_repo_info_complete 8?|34 mcp_meta_tool_options #15?|35 read_lints_enabled 8?|36 mcp_info_complete 8?|37 non_file_rules #0*|38 matched_installed_plugin #16?|39 rules_info_complete 8?|40 env_info_complete 8?|41 repository_info_complete 8?|42 custom_subagents_info_complete 8?|43 agent_skills_info_complete 8?|44 mcp_file_system_info_complete 8?|45 git_status_info_complete 8?|46 user_permissions_auto_run #17?|47 project_permissions_auto_run #17?|48 admin_permissions_auto_run #17?|49 disabled_team_rules 9*|50 search_conversations_enabled 8?|51 send_message_enabled 8?|52 admin_command_denylist 9*|53 system_prompt_override #18?",o.DX,I,u,c.gd,B,l.vq,c.I0,v,k,m.zz,c.Is,E,f.N,U,G,c.U_,F,C,d.$]}}class $ extends h{constructor(t){super(),this.rules=[],this.nonFileRules=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $).fromBinary(t,r)}static fromJson(t,r){return(new $).fromJson(t,r)}static fromJsonString(t,r){return(new $).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($,t,r)}static $(){return["RequestContextRulesPart|1 rules #0*|2 non_file_rules #0*|3 cloud_rule 9?",o.DX]}}class M extends h{constructor(t){super(),this.agentSkills=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new M).fromBinary(t,r)}static fromJson(t,r){return(new M).fromJson(t,r)}static fromJsonString(t,r){return(new M).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(M,t,r)}static $(){return["RequestContextSkillsPart|1 agent_skills #0*|2 skill_options #1?",f.N,k]}}class O extends h{constructor(t){super(),this.customSubagents=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new O).fromBinary(t,r)}static fromJson(t,r){return(new O).fromJson(t,r)}static fromJsonString(t,r){return(new O).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(O,t,r)}static $(){return["RequestContextSubagentsPart|1 custom_subagents #0*",m.zz]}}class D extends h{constructor(t){super(),this.tools=[],this.mcpInstructions=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new D).fromBinary(t,r)}static fromJson(t,r){return(new D).fromJson(t,r)}static fromJsonString(t,r){return(new D).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(D,t,r)}static $(){return["RequestContextMcpsPart|1 tools #0*|2 mcp_instructions #1*|3 mcp_file_system_options #2?|4 mcp_meta_tool_options #3?",c.gd,c.I0,c.Is,c.U_]}}class N extends h{constructor(t){super(),this.rulesBlobId=new Uint8Array(0),this.rulesByteLength=0,this.skillsBlobId=new Uint8Array(0),this.skillsByteLength=0,this.subagentsBlobId=new Uint8Array(0),this.subagentsByteLength=0,this.mcpsBlobId=new Uint8Array(0),this.mcpsByteLength=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new N).fromBinary(t,r)}static fromJson(t,r){return(new N).fromJson(t,r)}static fromJsonString(t,r){return(new N).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(N,t,r)}static $(){return["RequestContextPartReferences|1 rules_blob_id 12|2 rules_byte_length 13|3 skills_blob_id 12|4 skills_byte_length 13|5 subagents_blob_id 12|6 subagents_byte_length 13|7 mcps_blob_id 12|8 mcps_byte_length 13|9 dynamic_context #0",A]}}class G extends h{constructor(t){super(),this.displayName="",this.description="",this.skills=[],this.subagents=[],this.hooks=[],this.rules=[],this.commands=[],this.mcpServers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new G).fromBinary(t,r)}static fromJson(t,r){return(new G).fromJson(t,r)}static fromJsonString(t,r){return(new G).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(G,t,r)}static $(){return["RecentlyAddedPlugin|1 display_name 9|2 description 9|3 skills #0*|4 subagents #0*|5 hooks #0*|6 rules #0*|7 commands #0*|8 mcp_servers 9*",L]}}class L extends h{constructor(t){super(),this.name="",this.description="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new L).fromBinary(t,r)}static fromJson(t,r){return(new L).fromJson(t,r)}static fromJsonString(t,r){return(new L).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(L,t,r)}static $(){return["RecentlyAddedPlugin.CapabilityDescriptor|1 name 9|2 description 9"]}}class F extends h{constructor(t){super(),this.displayName="",this.description="",this.matchedKeyword="",this.skills=[],this.subagents=[],this.hooks=[],this.rules=[],this.commands=[],this.mcpServers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new F).fromBinary(t,r)}static fromJson(t,r){return(new F).fromJson(t,r)}static fromJsonString(t,r){return(new F).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(F,t,r)}static $(){return["MatchedInstalledPlugin|1 display_name 9|2 description 9|3 matched_keyword 9|4 skills #0*|5 subagents #0*|6 hooks #0*|7 rules #0*|8 commands #0*|9 mcp_servers 9*",L]}}},"../proto/dist/generated/agent/v1/requested_model_pb.js"(t,r,e){e.d(r,{G0:()=>o,G4:()=>c,R4:()=>u,SR:()=>l,ih:()=>a});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class o extends i{constructor(t){super(),this.apiKey="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["ApiKeyCredentials|1 api_key 9|2 base_url 9?"]}}class a extends i{constructor(t){super(),this.apiKey="",this.baseUrl="",this.deployment="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["AzureCredentials|1 api_key 9|2 base_url 9|3 deployment 9"]}}class u extends i{constructor(t){super(),this.accessKey="",this.secretKey="",this.region="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["BedrockCredentials|1 access_key 9|2 secret_key 9|3 region 9|4 session_token 9?"]}}class c extends i{constructor(t){super(),this.modelId="",this.maxMode=!1,this.parameters=[],this.credentials={case:void 0},this.builtInModel=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["RequestedModel|1 model_id 9|2 max_mode 8|3 parameters #0*|4 api_key_credentials #1 credentials|5 azure_credentials #2 credentials|6 bedrock_credentials #3 credentials|7 built_in_model 8",l,o,a,u]}}class l extends i{constructor(t){super(),this.id="",this.value="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["RequestedModel.ModelParameterValue|1 id 9|2 value 9"]}}},"../proto/dist/generated/agent/v1/sandbox_pb.js"(t,r,e){e.d(r,{Mw:()=>l,Qq:()=>a,RB:()=>u,Sz:()=>f,h1:()=>c,vc:()=>m});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");const i="agent.v1.";class o extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return i}}class a extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["NetworkPolicyLoggingConfig|1 decision_log_path 9?|2 log_format 9?"]}}class u extends o{constructor(t){super(),this.deny=[],this.allow=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["NetworkPolicy|1 version 13?|2 default_action #0?|3 deny 9*|4 allow 9*|5 logging #1?",c,a]}}var c=(0,s.QT)(n.proto3,i,"NetworkPolicy.DefaultAction",[[0,"UNSPECIFIED"],[1,"ALLOW"],[2,"DENY"]],1);class l extends o{constructor(t){super(),this.type=m.UNSPECIFIED,this.additionalReadwritePaths=[],this.additionalReadonlyPaths=[],this.readBoundary=f.UNSPECIFIED,this.additionalReadPaths=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["SandboxPolicy|1 type #0|2 network_access 8?|3 additional_readwrite_paths 9*|4 additional_readonly_paths 9*|5 debug_output_dir 9?|7 disable_tmp_write 8?|8 allowlist_escalated 8?|9 enable_shared_build_cache 8?|10 network_policy #1?|11 network_policy_strict 8?|12 capture_denies 8?|13 skip_statsig_defaults 8?|14 read_boundary #2|15 additional_read_paths 9*|16 allow_user_override_read_paths 8?|17 private_tmp 8?",m,u,f]}}var m=(0,s.QT)(n.proto3,i,"SandboxPolicy.Type",[[0,"UNSPECIFIED"],[1,"INSECURE_NONE"],[2,"WORKSPACE_READWRITE"],[3,"WORKSPACE_READONLY"]],1),f=(0,s.QT)(n.proto3,i,"SandboxPolicy.ReadBoundaryMode",[[0,"UNSPECIFIED"],[1,"SYSTEM"],[2,"WORKSPACE"]],1)},"../proto/dist/generated/agent/v1/selected_context_pb.js"(t,r,e){e.d(r,{AW:()=>M,Ps:()=>A,bf:()=>H,d:()=>f,uM:()=>j,xv:()=>st});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/agent/v1/utils_pb.js"),i=e("../proto/dist/generated/agent/v1/ls_exec_pb.js"),o=e("../proto/dist/generated/agent/v1/cursor_rules_pb.js"),a=e("../proto/dist/generated/agent/v1/agent_skills_pb.js"),u=e("../proto/dist/runtime/compact.js");const c="agent.v1.";class l extends u.HL{static get runtime(){return(0,u.kU)(this,"runtime",n.proto3)}static $p(){return c}}var m=(0,u.QT)(n.proto3,c,"SelectedPluginCapabilityType",[[0,"UNSPECIFIED"],[1,"COMMAND"],[2,"SKILL"],[3,"SUBAGENT"]],1);class f extends l{constructor(t){super(),this.dataOrBlobId={case:void 0},this.uuid="",this.path="",this.mimeType="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["SelectedImage|1 blob_id 12 data_or_blob_id|8 data 12 data_or_blob_id|9 blob_id_with_data #0 data_or_blob_id|10 prompt_upload_ref #1 data_or_blob_id|2 uuid 9|3 path 9|4 dimension #2|7 mime_type 9",d,h,p]}}class d extends l{constructor(t){super(),this.blobId=new Uint8Array(0),this.data=new Uint8Array(0),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["SelectedImage.BlobIdWithData|1 blob_id 12|2 data 12"]}}class p extends l{constructor(t){super(),this.width=0,this.height=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["SelectedImage.Dimension|1 width 5|2 height 5"]}}class h extends l{constructor(t){super(),this.uploadId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["PromptUploadRef|1 upload_id 9"]}}class g extends l{constructor(t){super(),this.dataOrBlobId={case:void 0},this.uuid="",this.filename="",this.mimeType="",this.path="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["SelectedDocument|1 blob_id 12 data_or_blob_id|8 data 12 data_or_blob_id|9 blob_id_with_data #0 data_or_blob_id|10 prompt_upload_ref #1 data_or_blob_id|2 uuid 9|3 filename 9|4 mime_type 9|7 path 9",_,h]}}class _ extends l{constructor(t){super(),this.blobId=new Uint8Array(0),this.data=new Uint8Array(0),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _).fromBinary(t,r)}static fromJson(t,r){return(new _).fromJson(t,r)}static fromJsonString(t,r){return(new _).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_,t,r)}static $(){return["SelectedDocument.BlobIdWithData|1 blob_id 12|2 data 12"]}}class J extends l{constructor(t){super(),this.dataOrBlobId={case:void 0},this.uuid="",this.path="",this.mimeType="",this.filename="",this.materializeToFilesystem=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new J).fromBinary(t,r)}static fromJson(t,r){return(new J).fromJson(t,r)}static fromJsonString(t,r){return(new J).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(J,t,r)}static $(){return["SelectedVideo|1 blob_id 12 data_or_blob_id|8 data 12 data_or_blob_id|9 blob_id_with_data #0 data_or_blob_id|11 signed_url #1 data_or_blob_id|13 prompt_upload_ref #2 data_or_blob_id|2 uuid 9|3 path 9|4 fps 2?|7 mime_type 9|10 filename 9|12 materialize_to_filesystem 8",w,y,h]}}class w extends l{constructor(t){super(),this.blobId=new Uint8Array(0),this.data=new Uint8Array(0),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new w).fromBinary(t,r)}static fromJson(t,r){return(new w).fromJson(t,r)}static fromJsonString(t,r){return(new w).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(w,t,r)}static $(){return["SelectedVideo.BlobIdWithData|1 blob_id 12|2 data 12"]}}class y extends l{constructor(t){super(),this.url="",this.key="",this.expiresAtUnixMs=n.protoInt64.zero,this.refreshAfterUnixMs=n.protoInt64.zero,this.conversationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new y).fromBinary(t,r)}static fromJson(t,r){return(new y).fromJson(t,r)}static fromJsonString(t,r){return(new y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(y,t,r)}static $(){return["SelectedVideo.SignedUrl|1 url 9|2 key 9|3 expires_at_unix_ms 3|4 refresh_after_unix_ms 3|5 conversation_id 9"]}}class S extends l{constructor(t){super(),this.dataOrBlobId={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new S).fromBinary(t,r)}static fromJson(t,r){return(new S).fromJson(t,r)}static fromJsonString(t,r){return(new S).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(S,t,r)}static $(){return["ExtraContextEntry|1 data 9 data_or_blob_id|2 blob_id 12 data_or_blob_id"]}}class q extends l{constructor(t){super(),this.content="",this.path="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new q).fromBinary(t,r)}static fromJson(t,r){return(new q).fromJson(t,r)}static fromJsonString(t,r){return(new q).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(q,t,r)}static $(){return["SelectedFile|1 content 9|2 path 9|3 relative_path 9?"]}}class B extends l{constructor(t){super(),this.content="",this.path="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new B).fromBinary(t,r)}static fromJson(t,r){return(new B).fromJson(t,r)}static fromJsonString(t,r){return(new B).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(B,t,r)}static $(){return["SelectedCodeSelection|1 content 9|2 path 9|3 relative_path 9?|4 range #0",s.Q6]}}class I extends l{constructor(t){super(),this.content="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new I).fromBinary(t,r)}static fromJson(t,r){return(new I).fromJson(t,r)}static fromJsonString(t,r){return(new I).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(I,t,r)}static $(){return["SelectedTerminal|1 content 9|2 title 9?|3 path 9?"]}}class P extends l{constructor(t){super(),this.content="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new P).fromBinary(t,r)}static fromJson(t,r){return(new P).fromJson(t,r)}static fromJsonString(t,r){return(new P).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(P,t,r)}static $(){return["SelectedTerminalSelection|1 content 9|2 title 9?|3 path 9?|4 range #0",s.Q6]}}class b extends l{constructor(t){super(),this.path="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new b).fromBinary(t,r)}static fromJson(t,r){return(new b).fromJson(t,r)}static fromJsonString(t,r){return(new b).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(b,t,r)}static $(){return["SelectedFolder|1 path 9|2 relative_path 9?|3 directory_tree #0",i.vq]}}class R extends l{constructor(t){super(),this.url="",this.uuid="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new R).fromBinary(t,r)}static fromJson(t,r){return(new R).fromJson(t,r)}static fromJsonString(t,r){return(new R).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(R,t,r)}static $(){return["SelectedExternalLink|1 url 9|2 uuid 9|3 pdf_content 9?|4 is_pdf 8?|5 filename 9?|6 blob_id 12?"]}}class v extends l{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new v).fromBinary(t,r)}static fromJson(t,r){return(new v).fromJson(t,r)}static fromJsonString(t,r){return(new v).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(v,t,r)}static $(){return["SelectedCursorRule|1 rule #0",o.DX]}}class x extends l{constructor(t){super(),this.content="",this.fullContentLengthCharCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new x).fromBinary(t,r)}static fromJson(t,r){return(new x).fromJson(t,r)}static fromJsonString(t,r){return(new x).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(x,t,r)}static $(){return["SelectedGitDiff|1 content 9|2 full_content_length_char_count 5"]}}class k extends l{constructor(t){super(),this.content="",this.fullContentLengthCharCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new k).fromBinary(t,r)}static fromJson(t,r){return(new k).fromJson(t,r)}static fromJsonString(t,r){return(new k).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(k,t,r)}static $(){return["SelectedGitDiffFromBranchToMain|1 content 9|2 full_content_length_char_count 5"]}}class E extends l{constructor(t){super(),this.sha="",this.message="",this.diff="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new E).fromBinary(t,r)}static fromJson(t,r){return(new E).fromJson(t,r)}static fromJsonString(t,r){return(new E).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(E,t,r)}static $(){return["SelectedGitCommit|1 sha 9|2 message 9|3 description 9?|4 diff 9"]}}class C extends l{constructor(t){super(),this.number=0,this.url="",this.folderPath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new C).fromBinary(t,r)}static fromJson(t,r){return(new C).fromJson(t,r)}static fromJsonString(t,r){return(new C).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(C,t,r)}static $(){return["SelectedPullRequest|1 number 5|2 url 9|3 title 9?|4 folder_path 9|5 summary_json 9?|6 description 9?|7 blob_id 12?"]}}class T extends l{constructor(t){super(),this.prUrl="",this.filePath="",this.startLine=0,this.endLine=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new T).fromBinary(t,r)}static fromJson(t,r){return(new T).fromJson(t,r)}static fromJsonString(t,r){return(new T).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(T,t,r)}static $(){return["SelectedGitPRDiffSelection|1 pr_url 9|2 file_path 9|3 start_line 5|4 end_line 5|5 diff_content 9?|6 blob_id 12?"]}}class U extends l{constructor(t){super(),this.pluginId="",this.capabilityType=m.UNSPECIFIED,this.sourcePath="",this.snapshotToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new U).fromBinary(t,r)}static fromJson(t,r){return(new U).fromJson(t,r)}static fromJsonString(t,r){return(new U).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(U,t,r)}static $(){return["SelectedPluginCapabilityRef|1 plugin_id 9|2 capability_type #0|3 source_path 9|4 snapshot_token 9|5 resolved_commit_sha 9?",m]}}class A extends l{constructor(t){super(),this.name="",this.content="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new A).fromBinary(t,r)}static fromJson(t,r){return(new A).fromJson(t,r)}static fromJsonString(t,r){return(new A).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(A,t,r)}static $(){return["SelectedCursorCommand|1 name 9|2 content 9|3 plugin_capability #0?|4 full_path 9?|5 display_name 9?",U]}}class $ extends l{constructor(t){super(),this.docId="",this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $).fromBinary(t,r)}static fromJson(t,r){return(new $).fromJson(t,r)}static fromJsonString(t,r){return(new $).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($,t,r)}static $(){return["SelectedDocumentation|1 doc_id 9|2 name 9"]}}class M extends l{constructor(t){super(),this.agentId="",this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new M).fromBinary(t,r)}static fromJson(t,r){return(new M).fromJson(t,r)}static fromJsonString(t,r){return(new M).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(M,t,r)}static $(){return["SelectedPastChat|1 agent_id 9|2 name 9"]}}class O extends l{constructor(t){super(),this.name="",this.path="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new O).fromBinary(t,r)}static fromJson(t,r){return(new O).fromJson(t,r)}static fromJsonString(t,r){return(new O).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(O,t,r)}static $(){return["RecentAgent|1 name 9|2 path 9|3 overview 9?"]}}class D extends l{constructor(t){super(),this.recentAgents=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new D).fromBinary(t,r)}static fromJson(t,r){return(new D).fromJson(t,r)}static fromJsonString(t,r){return(new D).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(D,t,r)}static $(){return["RecentAgentsContext|1 recent_agents #0*",O]}}class N extends l{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new N).fromBinary(t,r)}static fromJson(t,r){return(new N).fromJson(t,r)}static fromJsonString(t,r){return(new N).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(N,t,r)}static $(){return["CallFrame|1 function_name 9?|2 url 9?|3 line_number 5?|4 column_number 5?"]}}class G extends l{constructor(t){super(),this.callFrames=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new G).fromBinary(t,r)}static fromJson(t,r){return(new G).fromJson(t,r)}static fromJsonString(t,r){return(new G).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(G,t,r)}static $(){return["StackTrace|1 call_frames #0*|2 raw_stack_trace 9?",N]}}class L extends l{constructor(t){super(),this.message="",this.timestamp=0,this.level="",this.clientName="",this.sessionId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new L).fromBinary(t,r)}static fromJson(t,r){return(new L).fromJson(t,r)}static fromJsonString(t,r){return(new L).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(L,t,r)}static $(){return["SelectedConsoleLog|1 message 9|2 timestamp 1|3 level 9|4 client_name 9|5 session_id 9|6 stack_trace #0?|7 object_data_json 9?",G]}}class F extends l{constructor(t){super(),this.element="",this.xpath="",this.textContent="",this.extra="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new F).fromBinary(t,r)}static fromJson(t,r){return(new F).fromJson(t,r)}static fromJsonString(t,r){return(new F).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(F,t,r)}static $(){return["SelectedUIElement|1 element 9|2 xpath 9|3 text_content 9|4 extra 9|5 component 9?|6 component_props_json 9?"]}}class K extends l{constructor(t){super(),this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new K).fromBinary(t,r)}static fromJson(t,r){return(new K).fromJson(t,r)}static fromJsonString(t,r){return(new K).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(K,t,r)}static $(){return["SelectedSubagent|1 name 9"]}}class z extends l{constructor(t){super(),this.browserId="",this.url="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new z).fromBinary(t,r)}static fromJson(t,r){return(new z).fromJson(t,r)}static fromJsonString(t,r){return(new z).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(z,t,r)}static $(){return["SelectedBrowser|1 browser_id 9|2 url 9|3 page_title 9?"]}}class j extends l{constructor(t){super(),this.repoUrl="",this.label="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new j).fromBinary(t,r)}static fromJson(t,r){return(new j).fromJson(t,r)}static fromJsonString(t,r){return(new j).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(j,t,r)}static $(){return["SelectedRepository|1 repo_url 9|2 label 9"]}}class H extends l{constructor(t){super(),this.environmentPublicId="",this.label="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new H).fromBinary(t,r)}static fromJson(t,r){return(new H).fromJson(t,r)}static fromJsonString(t,r){return(new H).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(H,t,r)}static $(){return["SelectedEnvironment|1 environment_public_id 9|2 label 9"]}}class W extends l{constructor(t){super(),this.filesToCommit=[],this.filesToExcludeFromCommit=[],this.shouldStageAllChanges=!1,this.filesToCommitWithStatus=[],this.filesToExcludeFromCommitWithStatus=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new W).fromBinary(t,r)}static fromJson(t,r){return(new W).fromJson(t,r)}static fromJsonString(t,r){return(new W).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(W,t,r)}static $(){return["SelectedAgenticGitActionCommitParams|1 files_to_commit 9*|2 files_to_exclude_from_commit 9*|3 should_stage_all_changes 8|4 create_pr_draft 8?|5 files_to_commit_with_status #0*|6 files_to_exclude_from_commit_with_status #0*",V]}}class Q extends l{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Q).fromBinary(t,r)}static fromJson(t,r){return(new Q).fromJson(t,r)}static fromJsonString(t,r){return(new Q).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Q,t,r)}static $(){return["SelectedAgenticGitActionCreateBranchParams"]}}class V extends l{constructor(t){super(),this.path="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new V).fromBinary(t,r)}static fromJson(t,r){return(new V).fromJson(t,r)}static fromJsonString(t,r){return(new V).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(V,t,r)}static $(){return["SelectedAgenticGitFileWithStatus|1 path 9|2 status 9?"]}}class X extends l{constructor(t){super(),this.filesToPush=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new X).fromBinary(t,r)}static fromJson(t,r){return(new X).fromJson(t,r)}static fromJsonString(t,r){return(new X).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(X,t,r)}static $(){return["SelectedAgenticGitActionPushParams|1 files_to_push 9*|2 create_pr_draft 8?"]}}class Y extends l{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Y).fromBinary(t,r)}static fromJson(t,r){return(new Y).fromJson(t,r)}static fromJsonString(t,r){return(new Y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Y,t,r)}static $(){return["SelectedAgenticGitActionFixMergeConflictsParams|1 base_branch 9?|2 pr_url 9?"]}}class Z extends l{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Z).fromBinary(t,r)}static fromJson(t,r){return(new Z).fromJson(t,r)}static fromJsonString(t,r){return(new Z).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Z,t,r)}static $(){return["SelectedAgenticGitActionBabysitPrInCloudParams|1 base_branch 9?"]}}class tt extends l{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tt).fromBinary(t,r)}static fromJson(t,r){return(new tt).fromJson(t,r)}static fromJsonString(t,r){return(new tt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tt,t,r)}static $(){return["SelectedAgenticGitActionUpdateBranchParams|1 base_branch 9?"]}}class rt extends l{constructor(t){super(),this.remoteBranch="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rt).fromBinary(t,r)}static fromJson(t,r){return(new rt).fromJson(t,r)}static fromJsonString(t,r){return(new rt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rt,t,r)}static $(){return["SelectedAgenticGitActionPullLocallyParams|1 remote_branch 9"]}}class et extends l{constructor(t){super(),this.params={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new et).fromBinary(t,r)}static fromJson(t,r){return(new et).fromJson(t,r)}static fromJsonString(t,r){return(new et).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(et,t,r)}static $(){return["SelectedAgenticGitAction|2 commit_params #0 params|6 commit_and_push_params #0 params|3 push_params #1 params|7 create_pr_params #1 params|8 create_pr_with_changes_params #0 params|4 fix_merge_conflicts_params #2 params|11 babysit_pr_in_cloud_params #3 params|14 apply_locally_params #4 params|15 checkout_branch_params #4 params|12 create_branch_and_commit_params #0 params|13 create_branch_commit_and_push_params #0 params|16 update_branch_params #5 params|17 create_branch_params #6 params|5 branch_context #7?|9 path_to_template_file 9?|10 path_to_template_dir 9?",W,X,Y,Z,rt,tt,Q,nt]}}class nt extends l{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nt).fromBinary(t,r)}static fromJson(t,r){return(new nt).fromJson(t,r)}static fromJsonString(t,r){return(new nt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nt,t,r)}static $(){return["SelectedGitBranchContext|1 current_branch 9?|2 base_branch 9?|3 agent_branch_prefix 9?"]}}class st extends l{constructor(t){super(),this.selectedImages=[],this.extraContext=[],this.extraContextEntries=[],this.files=[],this.codeSelections=[],this.terminals=[],this.terminalSelections=[],this.folders=[],this.externalLinks=[],this.cursorRules=[],this.cursorCommands=[],this.documentations=[],this.uiElements=[],this.consoleLogs=[],this.gitCommits=[],this.pastChats=[],this.gitPrDiffSelections=[],this.selectedPullRequests=[],this.selectedSubagents=[],this.selectedVideos=[],this.selectedBrowsers=[],this.selectedDocuments=[],this.selectedSkills=[],this.selectedRepositories=[],this.selectedEnvironments=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new st).fromBinary(t,r)}static fromJson(t,r){return(new st).fromJson(t,r)}static fromJsonString(t,r){return(new st).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(st,t,r)}static $(){return["SelectedContext|1 selected_images #0*|2 invocation_context #1?|3 extra_context 9*|16 extra_context_entries #2*|4 files #3*|5 code_selections #4*|6 terminals #5*|7 terminal_selections #6*|8 folders #7*|9 external_links #8*|10 cursor_rules #9*|18 git_diff #10?|11 git_diff_from_branch_to_main #11?|12 cursor_commands #12*|13 documentations #13*|14 ui_elements #14*|15 console_logs #15*|17 git_commits #16*|19 past_chats #17*|20 git_pr_diff_selections #18*|21 selected_pull_requests #19*|22 selected_subagents #20*|23 selected_videos #21*|24 selected_browsers #22*|25 selected_documents #23*|26 selected_skills #24*|27 recent_agents_context #25?|34 selected_agentic_git_action #26?|35 selected_repositories #27*|36 selected_environments #28*",f,it,S,q,B,I,P,b,R,v,x,k,A,$,F,L,E,M,T,C,K,J,z,g,a.N,D,et,j,H]}}class it extends l{constructor(t){super(),this.data={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new it).fromBinary(t,r)}static fromJson(t,r){return(new it).fromJson(t,r)}static fromJsonString(t,r){return(new it).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(it,t,r)}static $(){return["InvocationContext|1 slack_thread #0 data|2 github_pr #1 data|3 ide_state #2 data|4 microsoft_teams_thread #3 data|10 blob_id 12 data",ot,ut,lt,at]}}class ot extends l{constructor(t){super(),this.thread="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ot).fromBinary(t,r)}static fromJson(t,r){return(new ot).fromJson(t,r)}static fromJsonString(t,r){return(new ot).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ot,t,r)}static $(){return["InvocationContext.SlackThread|1 thread 9|2 channel_name 9?|3 channel_purpose 9?|4 channel_topic 9?|5 sender_name 9?|6 sender_id 9?|7 sender_type 9?|8 is_directly_addressed 8?|9 message_permalink 9?"]}}class at extends l{constructor(t){super(),this.thread="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new at).fromBinary(t,r)}static fromJson(t,r){return(new at).fromJson(t,r)}static fromJsonString(t,r){return(new at).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(at,t,r)}static $(){return["InvocationContext.MicrosoftTeamsThread|1 thread 9|2 channel_name 9?|3 team_name 9?|4 channel_description 9?|5 team_description 9?"]}}class ut extends l{constructor(t){super(),this.title="",this.description="",this.comments="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ut).fromBinary(t,r)}static fromJson(t,r){return(new ut).fromJson(t,r)}static fromJsonString(t,r){return(new ut).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ut,t,r)}static $(){return["InvocationContext.GithubPR|1 title 9|2 description 9|3 comments 9|4 ci_failures 9?|5 code_tour_view #0?",ct]}}class ct extends l{constructor(t){super(),this.headSha="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ct).fromBinary(t,r)}static fromJson(t,r){return(new ct).fromJson(t,r)}static fromJsonString(t,r){return(new ct).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ct,t,r)}static $(){return["InvocationContext.GithubPR.CodeTourView|1 head_sha 9|2 current_revision_id 9?|3 visible_section_id 9?|4 visible_step_id 9?|5 path_scope_prefix 9?"]}}class lt extends l{constructor(t){super(),this.visibleFiles=[],this.recentlyViewedFiles=[],this.currentlyViewedPrs=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lt).fromBinary(t,r)}static fromJson(t,r){return(new lt).fromJson(t,r)}static fromJsonString(t,r){return(new lt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lt,t,r)}static $(){return["InvocationContext.IdeState|1 visible_files #0*|2 recently_viewed_files #0*|3 currently_viewed_prs #1*",mt,dt]}}class mt extends l{constructor(t){super(),this.path="",this.totalLines=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mt).fromBinary(t,r)}static fromJson(t,r){return(new mt).fromJson(t,r)}static fromJsonString(t,r){return(new mt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mt,t,r)}static $(){return["InvocationContext.IdeState.File|1 path 9|2 relative_path 9?|3 cursor_position #0?|4 total_lines 5|5 active_command 9?",ft]}}class ft extends l{constructor(t){super(),this.line=0,this.text="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ft).fromBinary(t,r)}static fromJson(t,r){return(new ft).fromJson(t,r)}static fromJsonString(t,r){return(new ft).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ft,t,r)}static $(){return["InvocationContext.IdeState.File.CursorPosition|1 line 5|2 text 9"]}}class dt extends l{constructor(t){super(),this.number=0,this.url="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dt).fromBinary(t,r)}static fromJson(t,r){return(new dt).fromJson(t,r)}static fromJsonString(t,r){return(new dt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dt,t,r)}static $(){return["InvocationContext.IdeState.ViewedPullRequest|1 number 5|2 url 9|3 title 9?|4 folder_path 9?|5 summary_json 9?|6 description 9?"]}}},"../proto/dist/generated/agent/v1/setup_vm_environment_tool_pb.js"(t,r,e){e.d(r,{BI:()=>o,JH:()=>u,MU:()=>c,r$:()=>a});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class o extends i{constructor(t){super(),this.installCommand="",this.startCommand="",this.dockerfileContents="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["SetupVmEnvironmentArgs|2 install_command 9|3 start_command 9|4 dockerfile_contents 9"]}}class a extends i{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["SetupVmEnvironmentResult|1 success #0 result",u]}}class u extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["SetupVmEnvironmentSuccess"]}}class c extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["SetupVmEnvironmentToolCall|1 args #0|2 result #1",o,a]}}},"../proto/dist/generated/agent/v1/shell_allowlist_precheck_exec_pb.js"(t,r,e){e.d(r,{C:()=>a,e:()=>u});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/agent/v1/shell_exec_pb.js"),i=e("../proto/dist/runtime/compact.js");class o extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class a extends o{constructor(t){super(),this.command="",this.workingDirectory="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["ShellAllowlistPrecheckArgs|1 command 9|2 working_directory 9|3 parsing_result #0|4 classifier_result #1?|5 tool_call_id 9?",s.HO,s.E4]}}class u extends o{constructor(t){super(),this.allowlisted=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["ShellAllowlistPrecheckResult|1 allowlisted 8"]}}},"../proto/dist/generated/agent/v1/shell_exec_pb.js"(t,r,e){e.d(r,{$F:()=>S,Db:()=>E,E4:()=>J,FI:()=>M,HO:()=>p,Hu:()=>q,In:()=>I,Jg:()=>m,Lv:()=>d,Ng:()=>A,Pv:()=>g,QR:()=>O,W4:()=>R,Y9:()=>U,_d:()=>l,a:()=>b,b:()=>P,eG:()=>N,iA:()=>f,jK:()=>B,jn:()=>L,mJ:()=>F,o0:()=>k,pZ:()=>G,r6:()=>h,rI:()=>$,tD:()=>T,vb:()=>C,xC:()=>D});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/agent/v1/sandbox_pb.js"),i=e("../proto/dist/generated/agent/v1/utils_pb.js"),o=e("../proto/dist/generated/agent/v1/hook_additional_context_pb.js"),a=e("../proto/dist/runtime/compact.js");const u="agent.v1.";class c extends a.HL{static get runtime(){return(0,a.kU)(this,"runtime",n.proto3)}static $p(){return u}}var l=(0,a.QT)(n.proto3,u,"TimeoutBehavior",[[0,"UNSPECIFIED"],[1,"CANCEL"],[2,"BACKGROUND"]],1),m=(0,a.QT)(n.proto3,u,"ShellBackgroundReason",[[0,"UNSPECIFIED"],[1,"TIMEOUT"],[2,"USER_REQUEST"]],1),f=(0,a.QT)(n.proto3,u,"ForceBackgroundShellStatus",[[0,"UNSPECIFIED"],[1,"ACCEPTED"],[2,"NOT_FOUND"]],1),d=(0,a.QT)(n.proto3,u,"ShellAbortReason",[[0,"UNSPECIFIED"],[1,"USER_ABORT"],[2,"TIMEOUT"]],1);class p extends c{constructor(t){super(),this.parsingFailed=!1,this.executableCommands=[],this.hasRedirects=!1,this.hasCommandSubstitution=!1,this.redirects=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["ShellCommandParsingResult|1 parsing_failed 8|2 executable_commands #0*|3 has_redirects 8|4 has_command_substitution 8|5 all_redirects_are_dev_null 8?|6 redirects #1*",g,_]}}class h extends c{constructor(t){super(),this.type="",this.value="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["ShellCommandParsingResult.ExecutableCommandArg|1 type 9|2 value 9"]}}class g extends c{constructor(t){super(),this.name="",this.args=[],this.fullText="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["ShellCommandParsingResult.ExecutableCommand|1 name 9|2 args #0*|3 full_text 9",h]}}class _ extends c{constructor(t){super(),this.operator="",this.destinationFds=[],this.targetNodeType="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _).fromBinary(t,r)}static fromJson(t,r){return(new _).fromJson(t,r)}static fromJsonString(t,r){return(new _).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_,t,r)}static $(){return["ShellCommandParsingResult.Redirect|1 operator 9|2 destination_fds 13*|3 target_node_type 9|4 target_text 9?"]}}class J extends c{constructor(t){super(),this.commands=[],this.suggestedSandboxMode=w.UNSPECIFIED,this.classificationFailed=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new J).fromBinary(t,r)}static fromJson(t,r){return(new J).fromJson(t,r)}static fromJsonString(t,r){return(new J).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(J,t,r)}static $(){return["CommandClassifierResult|1 commands #0*|2 suggested_sandbox_mode #1|3 classification_failed 8",y,w]}}var w=(0,a.QT)(n.proto3,u,"CommandClassifierResult.SuggestedSandboxMode",[[0,"UNSPECIFIED"],[1,"SANDBOX"],[2,"NO_SANDBOX"],[3,"UNDETERMINED"]],1);class y extends c{constructor(t){super(),this.name="",this.arguments=[],this.subcommandTokens=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new y).fromBinary(t,r)}static fromJson(t,r){return(new y).fromJson(t,r)}static fromJsonString(t,r){return(new y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(y,t,r)}static $(){return["CommandClassifierResult.ClassifiedCommand|1 name 9|2 arguments 9*|3 suggested_allowlist_entry 9?|4 subcommand_tokens 9*"]}}class S extends c{constructor(t){super(),this.pattern="",this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new S).fromBinary(t,r)}static fromJson(t,r){return(new S).fromJson(t,r)}static fromJsonString(t,r){return(new S).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(S,t,r)}static $(){return["ShellOutputNotificationConfig|1 pattern 9|2 reason 9|3 debounce 1?|4 notification_limit 5?"]}}class q extends c{constructor(t){super(),this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new q).fromBinary(t,r)}static fromJson(t,r){return(new q).fromJson(t,r)}static fromJsonString(t,r){return(new q).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(q,t,r)}static $(){return["ForceBackgroundShellArgs|1 tool_call_id 9"]}}class B extends c{constructor(t){super(),this.status=f.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new B).fromBinary(t,r)}static fromJson(t,r){return(new B).fromJson(t,r)}static fromJsonString(t,r){return(new B).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(B,t,r)}static $(){return["ForceBackgroundShellResult|1 status #0|2 shell_result #1?",f,R]}}class I extends c{constructor(t){super(),this.kind=P.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new I).fromBinary(t,r)}static fromJson(t,r){return(new I).fromJson(t,r)}static fromJsonString(t,r){return(new I).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(I,t,r)}static $(){return["ShellHookApprovalRequirement|1 kind #0|2 reason 9?",P]}}var P=(0,a.QT)(n.proto3,u,"ShellHookApprovalRequirement.Kind",[[0,"UNSPECIFIED"],[1,"FORCE_PROMPT"]],1);class b extends c{constructor(t){super(),this.command="",this.workingDirectory="",this.timeout=0,this.toolCallId="",this.simpleCommands=[],this.hasInputRedirect=!1,this.hasOutputRedirect=!1,this.isBackground=!1,this.skipApproval=!1,this.timeoutBehavior=l.UNSPECIFIED,this.closeStdin=!1,this.adminCommandDenylist=[],this.smartModeClassifierAllowed=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new b).fromBinary(t,r)}static fromJson(t,r){return(new b).fromJson(t,r)}static fromJsonString(t,r){return(new b).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(b,t,r)}static $(){return["ShellArgs|1 command 9|2 working_directory 9|3 timeout 5|4 tool_call_id 9|5 simple_commands 9*|6 has_input_redirect 8|7 has_output_redirect 8|8 parsing_result #0|9 requested_sandbox_policy #1?|10 file_output_threshold_bytes 4?|11 is_background 8|12 skip_approval 8|13 timeout_behavior #2|14 hard_timeout 5?|15 description 9?|16 classifier_result #3?|17 close_stdin 8|18 output_notification #4?|19 smart_mode_approval #5?|20 hook_approval_requirement #6?|21 conversation_id 9?|22 admin_command_denylist 9*|23 request_id 9?|24 secret_scope_id 9?|25 smart_mode_classifier_allowed 8|26 desktop_lease_actor_id 9?",p,s.Mw,l,J,S,i.UC,I]}}class R extends c{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new R).fromBinary(t,r)}static fromJson(t,r){return(new R).fromJson(t,r)}static fromJsonString(t,r){return(new R).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(R,t,r)}static $(){return["ShellResult|1 success #0 result|2 failure #1 result|3 timeout #2 result|4 rejected #3 result|5 spawn_error #4 result|7 permission_denied #5 result|101 sandbox_policy #6?|102 is_background 8?|103 terminals_folder 9?|104 pid 13?",O,D,N,G,F,L,s.Mw]}}class v extends c{constructor(t){super(),this.kind=x.UNSPECIFIED,this.memoryLimitBytes=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new v).fromBinary(t,r)}static fromJson(t,r){return(new v).fromJson(t,r)}static fromJsonString(t,r){return(new v).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(v,t,r)}static $(){return["ShellOomKill|1 kind #0|2 memory_limit_bytes 4",x]}}var x=(0,a.QT)(n.proto3,u,"ShellOomKill.Kind",[[0,"UNSPECIFIED"],[1,"COMMAND_KILLED"],[2,"COMMAND_FAILED"],[3,"UNCONFIRMED"]],1);class k extends c{constructor(t){super(),this.data="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new k).fromBinary(t,r)}static fromJson(t,r){return(new k).fromJson(t,r)}static fromJsonString(t,r){return(new k).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(k,t,r)}static $(){return["ShellStreamStdout|1 data 9"]}}class E extends c{constructor(t){super(),this.data="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new E).fromBinary(t,r)}static fromJson(t,r){return(new E).fromJson(t,r)}static fromJsonString(t,r){return(new E).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(E,t,r)}static $(){return["ShellStreamStderr|1 data 9"]}}class C extends c{constructor(t){super(),this.code=0,this.cwd="",this.aborted=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new C).fromBinary(t,r)}static fromJson(t,r){return(new C).fromJson(t,r)}static fromJsonString(t,r){return(new C).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(C,t,r)}static $(){return["ShellStreamExit|1 code 13|2 cwd 9|3 output_location #0?|4 aborted 8|5 abort_reason #1?|6 local_execution_time_ms 5?|7 oom_kill #2?",i.pV,d,v]}}class T extends c{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new T).fromBinary(t,r)}static fromJson(t,r){return(new T).fromJson(t,r)}static fromJsonString(t,r){return(new T).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(T,t,r)}static $(){return["ShellStreamStart|1 sandbox_policy #0?|2 command 9?",s.Mw]}}class U extends c{constructor(t){super(),this.shellId=0,this.command="",this.workingDirectory="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new U).fromBinary(t,r)}static fromJson(t,r){return(new U).fromJson(t,r)}static fromJsonString(t,r){return(new U).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(U,t,r)}static $(){return["ShellStreamBackgrounded|1 shell_id 13|2 command 9|3 working_directory 9|4 pid 13?|5 ms_to_wait 5?|6 reason #0?",m]}}class A extends c{constructor(t){super(),this.hookAdditionalContexts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new A).fromBinary(t,r)}static fromJson(t,r){return(new A).fromJson(t,r)}static fromJsonString(t,r){return(new A).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(A,t,r)}static $(){return["ShellStreamHookContext|1 hook_additional_contexts #0*",o.C]}}class $ extends c{constructor(t){super(),this.command="",this.workingDirectory="",this.sandboxPolicyType="",this.reason="",this.isReadonly=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $).fromBinary(t,r)}static fromJson(t,r){return(new $).fromJson(t,r)}static fromJsonString(t,r){return(new $).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($,t,r)}static $(){return["ShellSandboxUnsupported|1 command 9|2 working_directory 9|3 sandbox_policy_type 9|4 reason 9|5 is_readonly 8"]}}class M extends c{constructor(t){super(),this.event={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new M).fromBinary(t,r)}static fromJson(t,r){return(new M).fromJson(t,r)}static fromJsonString(t,r){return(new M).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(M,t,r)}static $(){return["ShellStream|1 stdout #0 event|2 stderr #1 event|3 exit #2 event|4 start #3 event|5 rejected #4 event|6 permission_denied #5 event|7 backgrounded #6 event|8 hook_context #7 event|9 sandbox_unsupported #8 event",k,E,C,T,G,L,U,A,$]}}class O extends c{constructor(t){super(),this.command="",this.workingDirectory="",this.exitCode=0,this.signal="",this.stdout="",this.stderr="",this.executionTime=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new O).fromBinary(t,r)}static fromJson(t,r){return(new O).fromJson(t,r)}static fromJsonString(t,r){return(new O).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(O,t,r)}static $(){return["ShellSuccess|1 command 9|2 working_directory 9|3 exit_code 5|4 signal 9|5 stdout 9|6 stderr 9|7 execution_time 5|8 output_location #0?|9 shell_id 13?|10 interleaved_output 9?|11 pid 13?|12 ms_to_wait 5?|13 local_execution_time_ms 5?|14 background_reason #1?|15 output_head 9?|16 output_tail 9?|17 elided_chars 13?",i.pV,m]}}class D extends c{constructor(t){super(),this.command="",this.workingDirectory="",this.exitCode=0,this.signal="",this.stdout="",this.stderr="",this.executionTime=0,this.aborted=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new D).fromBinary(t,r)}static fromJson(t,r){return(new D).fromJson(t,r)}static fromJsonString(t,r){return(new D).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(D,t,r)}static $(){return["ShellFailure|1 command 9|2 working_directory 9|3 exit_code 5|4 signal 9|5 stdout 9|6 stderr 9|7 execution_time 5|8 output_location #0?|9 interleaved_output 9?|10 abort_reason #1?|11 aborted 8|12 local_execution_time_ms 5?|13 output_head 9?|14 output_tail 9?|15 elided_chars 13?|16 oom_kill #2?",i.pV,d,v]}}class N extends c{constructor(t){super(),this.command="",this.workingDirectory="",this.timeoutMs=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new N).fromBinary(t,r)}static fromJson(t,r){return(new N).fromJson(t,r)}static fromJsonString(t,r){return(new N).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(N,t,r)}static $(){return["ShellTimeout|1 command 9|2 working_directory 9|3 timeout_ms 5"]}}class G extends c{constructor(t){super(),this.command="",this.workingDirectory="",this.reason="",this.isReadonly=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new G).fromBinary(t,r)}static fromJson(t,r){return(new G).fromJson(t,r)}static fromJsonString(t,r){return(new G).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(G,t,r)}static $(){return["ShellRejected|1 command 9|2 working_directory 9|3 reason 9|4 is_readonly 8"]}}class L extends c{constructor(t){super(),this.command="",this.workingDirectory="",this.error="",this.isReadonly=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new L).fromBinary(t,r)}static fromJson(t,r){return(new L).fromJson(t,r)}static fromJsonString(t,r){return(new L).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(L,t,r)}static $(){return["ShellPermissionDenied|1 command 9|2 working_directory 9|3 error 9|4 is_readonly 8"]}}class F extends c{constructor(t){super(),this.command="",this.workingDirectory="",this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new F).fromBinary(t,r)}static fromJson(t,r){return(new F).fromJson(t,r)}static fromJsonString(t,r){return(new F).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(F,t,r)}static $(){return["ShellSpawnError|1 command 9|2 working_directory 9|3 error 9"]}}},"../proto/dist/generated/agent/v1/smart_mode_classifier_exec_pb.js"(t,r,e){e.d(r,{Th:()=>f,bN:()=>p});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");const i="agent.v1.";class o extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return i}}var a=(0,s.QT)(n.proto3,i,"SmartModeClassifierDecision",[[0,"UNSPECIFIED"],[1,"ALLOW"],[2,"BLOCK"]],1),u=(0,s.QT)(n.proto3,i,"SmartModeClassifierRuleEffect",[[0,"UNSPECIFIED"],[1,"ALLOW"],[2,"ASK_FIRST"]],1),c=(0,s.QT)(n.proto3,i,"SmartModeClassifierRuleSource",[[0,"UNSPECIFIED"],[1,"CUSTOM_RULE"],[2,"TEAM_RULE"]],1);class l extends o{constructor(t){super(),this.role="",this.content="",this.invokedFiles=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["SmartModeClassifierConversationMessage|1 role 9|2 content 9|3 position 13?|4 invoked_files #0*",m]}}class m extends o{constructor(t){super(),this.path="",this.content="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["SmartModeClassifierInvokedFile|1 path 9|2 content 9"]}}class f extends o{constructor(t){super(),this.toolCallId="",this.conversationContext=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["SmartModeClassifierArgs|1 tool_call_id 9|2 parent_conversation_id 9?|3 target #0|4 conversation_context #1*",d,l]}}class d extends o{constructor(t){super(),this.action="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["SmartModeRiskTarget|1 action 9|2 arguments #0",n.Struct]}}class p extends o{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["SmartModeClassifierResult|1 success #0 result|2 error #1 result",h,_]}}class h extends o{constructor(t){super(),this.decision=a.UNSPECIFIED,this.appliedRules=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["SmartModeClassifierSuccess|1 decision #0|2 block_reason 9?|3 proposed_allow_rule 9?|4 applied_rules #1*|5 proposed_allow_rule_replaces 9?|6 blocked_effect 9?|7 irreversible 8?|8 action_description 9?|9 block_reason_category 9?|10 jev_path 9?|11 high_stakes 8?",a,g]}}class g extends o{constructor(t){super(),this.effect=u.UNSPECIFIED,this.text="",this.source=c.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["SmartModeClassifierAppliedRule|1 effect #0|2 text 9|3 source #1",u,c]}}class _ extends o{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _).fromBinary(t,r)}static fromJson(t,r){return(new _).fromJson(t,r)}static fromJsonString(t,r){return(new _).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_,t,r)}static $(){return["SmartModeClassifierError|1 error 9"]}}},"../proto/dist/generated/agent/v1/subagent_exec_pb.js"(t,r,e){e.d(r,{HJ:()=>y,Hq:()=>J,L5:()=>_,Pw:()=>m,S3:()=>q,TN:()=>p,Y:()=>w,a3:()=>B,bE:()=>g,jh:()=>l,od:()=>S,vS:()=>d,zJ:()=>h});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/agent/v1/requested_model_pb.js"),i=e("../proto/dist/generated/agent/v1/subagents_pb.js"),o=e("../proto/dist/generated/agent/v1/selected_context_pb.js"),a=e("../proto/dist/runtime/compact.js");const u="agent.v1.";class c extends a.HL{static get runtime(){return(0,a.kU)(this,"runtime",n.proto3)}static $p(){return u}}var l=(0,a.QT)(n.proto3,u,"ForceBackgroundSubagentStatus",[[0,"UNSPECIFIED"],[1,"ACCEPTED"],[2,"NOT_FOUND"]],1);class m extends c{constructor(t){super(),this.toolCallId="",this.subagentType="",this.modelId="",this.prompt="",this.readonly=!1,this.credentials={case:void 0},this.mode=i.FL.UNSPECIFIED,this.environment=i.dU.UNSPECIFIED,this.modelParameters=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["SubagentArgs|1 tool_call_id 9|2 subagent_type 9|3 model_id 9|4 prompt 9|5 readonly 8|6 resume_agent_id 9?|7 run_in_background 8?|8 continuation_config #0|9 parent_conversation_id 9?|10 api_key_credentials #1 credentials|11 azure_credentials #2 credentials|12 bedrock_credentials #3 credentials|13 interrupt 8?|14 mode #4|15 fork_agent_id 9?|16 root_parent_conversation_id 9?|17 selected_context #5?|18 direct_meta_parent_child_subagent 8?|19 environment #6|20 cloud_base_branch 9?|21 model_parameters #7*|22 voice_call_notes #8?",f,s.G0,s.ih,s.R4,i.FL,o.xv,i.dU,s.SR,i.OT]}}class f extends c{constructor(t){super(),this.idleThreshold=0,this.maxLoops=0,this.nudgeMessage="",this.escapeMessageTemplate="",this.collectBackgroundChildren=!1,this.childrenCompletedMessageTemplate="",this.continuationRoundDelayMs=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["ClientContinuationConfig|1 idle_threshold 5|2 max_loops 5|3 nudge_message 9|4 escape_message_template 9|5 collect_background_children 8|6 children_completed_message_template 9|7 continuation_round_delay_ms 5"]}}class d extends c{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["SubagentResult|1 success #0 result|2 error #1 result",y,S]}}class p extends c{constructor(t){super(),this.agentId="",this.timeoutMs=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["SubagentAwaitArgs|1 agent_id 9|2 timeout_ms 13"]}}class h extends c{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["SubagentAwaitResult|1 complete #0 result|2 still_running #1 result|3 not_found #2 result|4 error #3 result",g,_,J,w]}}class g extends c{constructor(t){super(),this.agentId="",this.toolCallCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["SubagentAwaitComplete|1 agent_id 9|2 transcript_path 9?|3 tool_call_count 5|4 final_message 9?"]}}class _ extends c{constructor(t){super(),this.agentId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _).fromBinary(t,r)}static fromJson(t,r){return(new _).fromJson(t,r)}static fromJsonString(t,r){return(new _).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_,t,r)}static $(){return["SubagentAwaitStillRunning|1 agent_id 9|2 transcript_path 9?"]}}class J extends c{constructor(t){super(),this.agentId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new J).fromBinary(t,r)}static fromJson(t,r){return(new J).fromJson(t,r)}static fromJsonString(t,r){return(new J).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(J,t,r)}static $(){return["SubagentAwaitNotFound|1 agent_id 9"]}}class w extends c{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new w).fromBinary(t,r)}static fromJson(t,r){return(new w).fromJson(t,r)}static fromJsonString(t,r){return(new w).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(w,t,r)}static $(){return["SubagentAwaitError|1 agent_id 9?|2 error 9"]}}class y extends c{constructor(t){super(),this.agentId="",this.toolCallCount=0,this.backgroundReason=i.qL.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new y).fromBinary(t,r)}static fromJson(t,r){return(new y).fromJson(t,r)}static fromJsonString(t,r){return(new y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(y,t,r)}static $(){return["SubagentSuccess|1 agent_id 9|2 final_message 9?|3 tool_call_count 5|4 background_reason #0|5 transcript_path 9?",i.qL]}}class S extends c{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new S).fromBinary(t,r)}static fromJson(t,r){return(new S).fromJson(t,r)}static fromJsonString(t,r){return(new S).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(S,t,r)}static $(){return["SubagentError|1 agent_id 9?|2 error 9"]}}class q extends c{constructor(t){super(),this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new q).fromBinary(t,r)}static fromJson(t,r){return(new q).fromJson(t,r)}static fromJsonString(t,r){return(new q).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(q,t,r)}static $(){return["ForceBackgroundSubagentArgs|1 tool_call_id 9"]}}class B extends c{constructor(t){super(),this.status=l.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new B).fromBinary(t,r)}static fromJson(t,r){return(new B).fromJson(t,r)}static fromJsonString(t,r){return(new B).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(B,t,r)}static $(){return["ForceBackgroundSubagentResult|1 status #0",l]}}},"../proto/dist/generated/agent/v1/subagents_pb.js"(t,r,e){e.d(r,{FL:()=>m,OT:()=>R,U6:()=>l,_L:()=>f,b$:()=>a,dU:()=>u,qL:()=>c,zz:()=>b});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");const i="agent.v1.";class o extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return i}}var a=(0,s.QT)(n.proto3,i,"CustomSubagentPermissionMode",[[0,"UNSPECIFIED"],[1,"DEFAULT"],[2,"READONLY"],[3,"AGENT_ONLY"]],1),u=(0,s.QT)(n.proto3,i,"SubagentExecutionEnvironment",[[0,"UNSPECIFIED"],[1,"LOCAL"],[2,"CLOUD"]],1),c=(0,s.QT)(n.proto3,i,"SubagentBackgroundReason",[[0,"UNSPECIFIED"],[1,"AGENT_REQUEST"],[2,"USER_REQUEST"],[3,"QUEUED_FOLLOW_UP"]],1),l=(0,s.QT)(n.proto3,i,"BackgroundTaskCompletionReason",[[0,"UNSPECIFIED"],[1,"TASK_FINISHED"],[2,"TASK_PROGRESS"],[3,"WORKER_REPARENTED"],[4,"WORKER_MESSAGE"],[5,"WORKER_NEEDS_ATTENTION"],[6,"PROJECT_SESSION_MESSAGE"]],1),m=(0,s.QT)(n.proto3,i,"TaskMode",[[0,"UNSPECIFIED"],[1,"AGENT"],[2,"PLAN"]],1);class f extends o{constructor(t){super(),this.type={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["SubagentType|1 unspecified #0 type|2 computer_use #1 type|3 custom #2 type|4 explore #3 type|5 media_review #4 type|6 bash #5 type|7 browser_use #6 type|8 shell #7 type|9 vm_setup_helper #8 type|10 debug #9 type|11 cursor_guide #10 type|12 watch_video #11 type|13 computer_use_v2 #12 type",d,p,P,h,g,_,w,J,y,S,q,B,I]}}class d extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["SubagentTypeUnspecified"]}}class p extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["SubagentTypeComputerUse"]}}class h extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["SubagentTypeExplore"]}}class g extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["SubagentTypeMediaReview"]}}class _ extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _).fromBinary(t,r)}static fromJson(t,r){return(new _).fromJson(t,r)}static fromJsonString(t,r){return(new _).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_,t,r)}static $(){return["SubagentTypeBash"]}}class J extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new J).fromBinary(t,r)}static fromJson(t,r){return(new J).fromJson(t,r)}static fromJsonString(t,r){return(new J).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(J,t,r)}static $(){return["SubagentTypeShell"]}}class w extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new w).fromBinary(t,r)}static fromJson(t,r){return(new w).fromJson(t,r)}static fromJsonString(t,r){return(new w).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(w,t,r)}static $(){return["SubagentTypeBrowserUse"]}}class y extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new y).fromBinary(t,r)}static fromJson(t,r){return(new y).fromJson(t,r)}static fromJsonString(t,r){return(new y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(y,t,r)}static $(){return["SubagentTypeVmSetupHelper"]}}class S extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new S).fromBinary(t,r)}static fromJson(t,r){return(new S).fromJson(t,r)}static fromJsonString(t,r){return(new S).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(S,t,r)}static $(){return["SubagentTypeDebug"]}}class q extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new q).fromBinary(t,r)}static fromJson(t,r){return(new q).fromJson(t,r)}static fromJsonString(t,r){return(new q).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(q,t,r)}static $(){return["SubagentTypeCursorGuide"]}}class B extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new B).fromBinary(t,r)}static fromJson(t,r){return(new B).fromJson(t,r)}static fromJsonString(t,r){return(new B).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(B,t,r)}static $(){return["SubagentTypeWatchVideo"]}}class I extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new I).fromBinary(t,r)}static fromJson(t,r){return(new I).fromJson(t,r)}static fromJsonString(t,r){return(new I).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(I,t,r)}static $(){return["SubagentTypeComputerUseV2"]}}class P extends o{constructor(t){super(),this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new P).fromBinary(t,r)}static fromJson(t,r){return(new P).fromJson(t,r)}static fromJsonString(t,r){return(new P).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(P,t,r)}static $(){return["SubagentTypeCustom|1 name 9"]}}class b extends o{constructor(t){super(),this.fullPath="",this.name="",this.description="",this.tools=[],this.model="",this.prompt="",this.permissionMode=a.UNSPECIFIED,this.isBackground=!1,this.forceDefaultModel=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new b).fromBinary(t,r)}static fromJson(t,r){return(new b).fromJson(t,r)}static fromJsonString(t,r){return(new b).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(b,t,r)}static $(){return["CustomSubagent|1 full_path 9|2 name 9|3 description 9|4 tools 9*|5 model 9|6 prompt 9|7 permission_mode #0|8 is_background 8|9 plugin 9?|10 marketplace 9?|11 plugin_id 9?|12 marketplace_id 9?|13 force_default_model 8|14 source 9?",a]}}class R extends o{constructor(t){super(),this.request="",this.messageId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new R).fromBinary(t,r)}static fromJson(t,r){return(new R).fromJson(t,r)}static fromJsonString(t,r){return(new R).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(R,t,r)}static $(){return["VoiceCallNotes|1 request 9|2 message_id 9"]}}},"../proto/dist/generated/agent/v1/switch_mode_tool_pb.js"(t,r,e){e.d(r,{Cs:()=>m,Nc:()=>f,q5:()=>p,rA:()=>h,w$:()=>d});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class o extends i{constructor(t){super(),this.targetModeId="",this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["SwitchModeArgs|1 target_mode_id 9|2 explanation 9?|3 tool_call_id 9"]}}class a extends i{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["SwitchModeResult|1 success #0 result|2 error #1 result|3 rejected #2 result",u,c,l]}}class u extends i{constructor(t){super(),this.fromModeId="",this.toModeId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["SwitchModeSuccess|1 from_mode_id 9|2 to_mode_id 9"]}}class c extends i{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["SwitchModeError|1 error 9"]}}class l extends i{constructor(t){super(),this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["SwitchModeRejected|1 reason 9"]}}class m extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["SwitchModeToolCall|1 args #0|2 result #1",o,a]}}class f extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["SwitchModeRequestQuery|1 args #0",o]}}class d extends i{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["SwitchModeRequestResponse|1 approved #0 result|2 rejected #1 result",p,h]}}class p extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["SwitchModeRequestResponse.Approved"]}}class h extends i{constructor(t){super(),this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["SwitchModeRequestResponse.Rejected|1 reason 9"]}}},"../proto/dist/generated/agent/v1/system_prompt_pb.js"(t,r,e){e.d(r,{$:()=>o});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class o extends i{constructor(t){super(),this.spec={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["SystemPromptSpec|1 replace 9 spec|2 append 9 spec"]}}},"../proto/dist/generated/agent/v1/todo_tool_pb.js"(t,r,e){e.d(r,{AJ:()=>p,Vj:()=>a,bk:()=>c,kW:()=>u});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");const i="agent.v1.";class o extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return i}}var a=(0,s.QT)(n.proto3,i,"TodoStatus",[[0,"UNSPECIFIED"],[1,"PENDING"],[2,"IN_PROGRESS"],[3,"COMPLETED"],[4,"CANCELLED"]],1);class u extends o{constructor(t){super(),this.id="",this.content="",this.status=a.UNSPECIFIED,this.createdAt=n.protoInt64.zero,this.updatedAt=n.protoInt64.zero,this.dependencies=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["TodoItem|1 id 9|2 content 9|3 status #0|4 created_at 3|5 updated_at 3|6 dependencies 9*",a]}}class c extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["UpdateTodosToolCall|1 args #0|2 result #1",l,m]}}class l extends o{constructor(t){super(),this.todos=[],this.merge=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["UpdateTodosArgs|1 todos #0*|2 merge 8",u]}}class m extends o{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["UpdateTodosResult|1 success #0 result|2 error #1 result",f,d]}}class f extends o{constructor(t){super(),this.todos=[],this.totalCount=0,this.wasMerge=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["UpdateTodosSuccess|1 todos #0*|2 total_count 5|3 was_merge 8",u]}}class d extends o{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["UpdateTodosError|1 error 9"]}}class p extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["ReadTodosToolCall|1 args #0|2 result #1",h,g]}}class h extends o{constructor(t){super(),this.statusFilter=[],this.idFilter=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["ReadTodosArgs|1 status_filter #0*|2 id_filter 9*",a]}}class g extends o{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["ReadTodosResult|1 success #0 result|2 error #1 result",_,J]}}class _ extends o{constructor(t){super(),this.todos=[],this.totalCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _).fromBinary(t,r)}static fromJson(t,r){return(new _).fromJson(t,r)}static fromJsonString(t,r){return(new _).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_,t,r)}static $(){return["ReadTodosSuccess|1 todos #0*|2 total_count 5",u]}}class J extends o{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new J).fromBinary(t,r)}static fromJson(t,r){return(new J).fromJson(t,r)}static fromJsonString(t,r){return(new J).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(J,t,r)}static $(){return["ReadTodosError|1 error 9"]}}},"../proto/dist/generated/agent/v1/utils_pb.js"(t,r,e){e.d(r,{Q6:()=>o,UC:()=>c,pV:()=>u,yX:()=>a});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class o extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["Range|1 start #0|2 end #0",a]}}class a extends i{constructor(t){super(),this.line=0,this.column=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["Position|1 line 13|2 column 13"]}}class u extends i{constructor(t){super(),this.filePath="",this.sizeBytes=n.protoInt64.zero,this.lineCount=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["OutputLocation|1 file_path 9|2 size_bytes 3|3 line_count 3"]}}class c extends i{constructor(t){super(),this.requestId="",this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["SmartModeApproval|1 request_id 9|2 reason 9"]}}},"../proto/dist/generated/agent/v1/web_fetch_allowlist_precheck_exec_pb.js"(t,r,e){e.d(r,{K:()=>o,M:()=>a});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class o extends i{constructor(t){super(),this.url="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["WebFetchAllowlistPrecheckArgs|1 url 9|2 tool_call_id 9?"]}}class a extends i{constructor(t){super(),this.allowlisted=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["WebFetchAllowlistPrecheckResult|1 allowlisted 8"]}}},"../proto/dist/generated/agent/v1/web_fetch_tool_pb.js"(t,r,e){e.d(r,{Hs:()=>h,Un:()=>d,fS:()=>p,fd:()=>f,m$:()=>g});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/agent/v1/utils_pb.js"),i=e("../proto/dist/runtime/compact.js");class o extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class a extends o{constructor(t){super(),this.url="",this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["WebFetchArgs|1 url 9|2 tool_call_id 9"]}}class u extends o{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["WebFetchResult|1 success #0 result|2 error #1 result|3 rejected #2 result",c,l,m]}}class c extends o{constructor(t){super(),this.url="",this.markdown="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["WebFetchSuccess|1 url 9|2 markdown 9|3 output_location #0?",s.pV]}}class l extends o{constructor(t){super(),this.url="",this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["WebFetchError|1 url 9|2 error 9"]}}class m extends o{constructor(t){super(),this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["WebFetchRejected|1 reason 9"]}}class f extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["WebFetchToolCall|1 args #0|2 result #1",a,u]}}class d extends o{constructor(t){super(),this.skipApproval=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["WebFetchRequestQuery|1 args #0|2 skip_approval 8|3 smart_mode_approval #1",a,s.UC]}}class p extends o{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["WebFetchRequestResponse|1 approved #0 result|2 rejected #1 result",h,g]}}class h extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["WebFetchRequestResponse.Approved"]}}class g extends o{constructor(t){super(),this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["WebFetchRequestResponse.Rejected|1 reason 9"]}}},"../proto/dist/generated/agent/v1/web_search_tool_pb.js"(t,r,e){e.d(r,{KL:()=>d,XJ:()=>h,lI:()=>p,pn:()=>f,yc:()=>g});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class o extends i{constructor(t){super(),this.searchTerm="",this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["WebSearchArgs|1 search_term 9|2 tool_call_id 9"]}}class a extends i{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["WebSearchResult|1 success #0 result|2 error #1 result|3 rejected #2 result",u,c,l]}}class u extends i{constructor(t){super(),this.references=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["WebSearchSuccess|1 references #0*",m]}}class c extends i{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["WebSearchError|1 error 9"]}}class l extends i{constructor(t){super(),this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["WebSearchRejected|1 reason 9"]}}class m extends i{constructor(t){super(),this.title="",this.url="",this.chunk="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["WebSearchReference|1 title 9|2 url 9|3 chunk 9"]}}class f extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["WebSearchToolCall|1 args #0|2 result #1",o,a]}}class d extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["WebSearchRequestQuery|1 args #0",o]}}class p extends i{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["WebSearchRequestResponse|1 approved #0 result|2 rejected #1 result",h,g]}}class h extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["WebSearchRequestResponse.Approved"]}}class g extends i{constructor(t){super(),this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["WebSearchRequestResponse.Rejected|1 reason 9"]}}},"../proto/dist/generated/agent/v1/write_exec_pb.js"(t,r,e){e.d(r,{QM:()=>m,U7:()=>c,bM:()=>l,en:()=>f,hY:()=>o,j6:()=>u,v3:()=>a});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"agent.v1."}}class o extends i{constructor(t){super(),this.path="",this.fileText="",this.toolCallId="",this.returnFileContentAfterWrite=!1,this.fileBytes=new Uint8Array(0),this.planMode=!1,this.confineToWorkspace=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["WriteArgs|1 path 9|2 file_text 9|3 tool_call_id 9|4 return_file_content_after_write 8|5 file_bytes 12|6 encoding_hint 9?|7 plan_mode 8|8 confine_to_workspace 8"]}}class a extends i{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["WriteResult|1 success #0 result|3 permission_denied #1 result|4 no_space #2 result|5 error #3 result|6 rejected #4 result",u,c,l,m,f]}}class u extends i{constructor(t){super(),this.path="",this.linesCreated=0,this.fileSize=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["WriteSuccess|1 path 9|2 lines_created 5|3 file_size 5|4 file_content_after_write 9?"]}}class c extends i{constructor(t){super(),this.path="",this.directory="",this.operation="",this.error="",this.isReadonly=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["WritePermissionDenied|1 path 9|2 directory 9|3 operation 9|4 error 9|5 is_readonly 8"]}}class l extends i{constructor(t){super(),this.path="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["WriteNoSpace|1 path 9"]}}class m extends i{constructor(t){super(),this.path="",this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["WriteError|1 path 9|2 error 9"]}}class f extends i{constructor(t){super(),this.path="",this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["WriteRejected|1 path 9|2 reason 9"]}}},"../proto/dist/generated/aiserver/v1/bidi_pb.js"(t,r,e){e.d(r,{$r:()=>o,Qd:()=>a,hD:()=>c,xy:()=>l,yq:()=>u});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"aiserver.v1."}}class o extends i{constructor(t){super(),this.requestId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["BidiRequestId|1 request_id 9"]}}class a extends i{constructor(t){super(),this.data="",this.appendSeqno=n.protoInt64.zero,this.dataBinary=new Uint8Array(0),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["BidiAppendRequest|1 data 9|2 request_id #0|3 append_seqno 3|4 data_binary 12",o]}}class u extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["BidiAppendResponse"]}}class c extends i{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["BidiPollRequest|1 request_id #0|2 start_request 8?",o]}}class l extends i{constructor(t){super(),this.seqno=n.protoInt64.zero,this.data="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["BidiPollResponse|1 seqno 3|2 data 9|3 eof 8?"]}}},"../proto/dist/generated/aiserver/v1/chat_pb.js"(t,r,e){e.d(r,{O9:()=>z,gn:()=>Xt,yf:()=>nt,An:()=>er,hS:()=>gt,jF:()=>Mt,KR:()=>H,TS:()=>Z,cf:()=>V,Bh:()=>ct,jp:()=>Q,D8:()=>at,XE:()=>et,Bo:()=>ut,O0:()=>X});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/aiserver/v1/tools_pb.js"),i=e("../proto/dist/generated/aiserver/v1/utils_pb.js"),o=e("../proto/dist/generated/aiserver/v1/docs_pb.js"),a=(e("../proto/dist/generated/aiserver/v1/repository_pb.js"),e("../proto/dist/runtime/compact.js"));const u="aiserver.v1.";class c extends a.HL{static get runtime(){return(0,a.kU)(this,"runtime",n.proto3)}static $p(){return u}}class l extends c{constructor(t){super(),this.type=m.UNSPECIFIED,this.data={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["ComposerCapabilityRequest|1 type #0|2 loop_on_lints #1 data|3 loop_on_tests #2 data|4 mega_planner #3 data|5 loop_on_command #4 data|6 tool_call #5 data|7 diff_review #6 data|8 context_picking #7 data|9 edit_trail #8 data|10 auto_context #9 data|11 context_planner #10 data|12 remember_this #11 data|13 decomposer #12 data|14 cursor_rules #13 data",m,h,g,_,J,w,y,I,P,b,R,v,B,x]}}var m=(0,a.QT)(n.proto3,u,"ComposerCapabilityRequest.ComposerCapabilityType",[[0,"UNSPECIFIED"],[1,"LOOP_ON_LINTS"],[2,"LOOP_ON_TESTS"],[3,"MEGA_PLANNER"],[4,"LOOP_ON_COMMAND"],[5,"TOOL_CALL"],[6,"DIFF_REVIEW"],[7,"CONTEXT_PICKING"],[8,"EDIT_TRAIL"],[9,"AUTO_CONTEXT"],[10,"CONTEXT_PLANNER"],[11,"DIFF_HISTORY"],[12,"REMEMBER_THIS"],[13,"DECOMPOSER"],[14,"USES_CODEBASE"],[15,"TOOL_FORMER"],[16,"CURSOR_RULES"],[17,"TOKEN_COUNTER"],[18,"USAGE_DATA"],[19,"CHIMES"],[20,"CODE_DECAY_TRACKER"],[21,"BACKGROUND_COMPOSER"],[22,"SUMMARIZATION"],[23,"AI_CODE_TRACKING"],[24,"QUEUING"],[25,"MEMORIES"],[26,"RCP_LOGS"],[27,"KNOWLEDGE_FETCH"],[28,"SLACK_INTEGRATION"],[29,"SUB_COMPOSER"],[30,"THINKING"],[31,"CONTEXT_WINDOW"],[32,"ONLINE_METRICS"],[33,"NOTIFICATIONS"],[34,"SPEC"],[35,"BROWSER_AGENT"]],1),f=(0,a.QT)(n.proto3,u,"ComposerCapabilityRequest.ToolType",[[0,"UNSPECIFIED"],[1,"ADD_FILE_TO_CONTEXT"],[3,"ITERATE"],[4,"REMOVE_FILE_FROM_CONTEXT"],[5,"SEMANTIC_SEARCH_CODEBASE"]],1);class d extends c{constructor(t){super(),this.type=f.UNSPECIFIED,this.name="",this.properties={},this.required=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["ComposerCapabilityRequest.ToolSchema|1 type #0|2 name 9|3 properties 9,#1|4 required 9*",f,p]}}class p extends c{constructor(t){super(),this.type="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["ComposerCapabilityRequest.SchemaProperty|1 type 9|2 description 9?"]}}class h extends c{constructor(t){super(),this.linterErrors=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["ComposerCapabilityRequest.LoopOnLintsCapability|1 linter_errors #0*|2 custom_instructions 9?",i.wZ]}}class g extends c{constructor(t){super(),this.testNames=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["ComposerCapabilityRequest.LoopOnTestsCapability|1 test_names 9*|2 custom_instructions 9?"]}}class _ extends c{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _).fromBinary(t,r)}static fromJson(t,r){return(new _).fromJson(t,r)}static fromJsonString(t,r){return(new _).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_,t,r)}static $(){return["ComposerCapabilityRequest.MegaPlannerCapability|1 custom_instructions 9?"]}}class J extends c{constructor(t){super(),this.command="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new J).fromBinary(t,r)}static fromJson(t,r){return(new J).fromJson(t,r)}static fromJsonString(t,r){return(new J).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(J,t,r)}static $(){return["ComposerCapabilityRequest.LoopOnCommandCapability|1 command 9|2 custom_instructions 9?|3 output 9?|4 exit_code 5?"]}}class w extends c{constructor(t){super(),this.toolSchemas=[],this.relevantFiles=[],this.filesInContext=[],this.semanticSearchFiles=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new w).fromBinary(t,r)}static fromJson(t,r){return(new w).fromJson(t,r)}static fromJsonString(t,r){return(new w).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(w,t,r)}static $(){return["ComposerCapabilityRequest.ToolCallCapability|1 custom_instructions 9?|2 tool_schemas #0*|3 relevant_files 9*|4 files_in_context 9*|5 semantic_search_files 9*",d]}}class y extends c{constructor(t){super(),this.diffs=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new y).fromBinary(t,r)}static fromJson(t,r){return(new y).fromJson(t,r)}static fromJsonString(t,r){return(new y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(y,t,r)}static $(){return["ComposerCapabilityRequest.DiffReviewCapability|1 custom_instructions 9?|2 diffs #0*",S]}}class S extends c{constructor(t){super(),this.relativeWorkspacePath="",this.chunks=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new S).fromBinary(t,r)}static fromJson(t,r){return(new S).fromJson(t,r)}static fromJsonString(t,r){return(new S).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(S,t,r)}static $(){return["ComposerCapabilityRequest.DiffReviewCapability.SimpleFileDiff|1 relative_workspace_path 9|3 chunks #0*",q]}}class q extends c{constructor(t){super(),this.oldLines=[],this.newLines=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new q).fromBinary(t,r)}static fromJson(t,r){return(new q).fromJson(t,r)}static fromJsonString(t,r){return(new q).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(q,t,r)}static $(){return["ComposerCapabilityRequest.DiffReviewCapability.SimpleFileDiff.Chunk|1 old_lines 9*|2 new_lines 9*|3 old_range #0|4 new_range #0",i.MT]}}class B extends c{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new B).fromBinary(t,r)}static fromJson(t,r){return(new B).fromJson(t,r)}static fromJsonString(t,r){return(new B).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(B,t,r)}static $(){return["ComposerCapabilityRequest.DecomposerCapability|1 custom_instructions 9?"]}}class I extends c{constructor(t){super(),this.potentialContextFiles=[],this.potentialContextCodeChunks=[],this.filesInContext=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new I).fromBinary(t,r)}static fromJson(t,r){return(new I).fromJson(t,r)}static fromJsonString(t,r){return(new I).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(I,t,r)}static $(){return["ComposerCapabilityRequest.ContextPickingCapability|1 custom_instructions 9?|2 potential_context_files 9*|3 potential_context_code_chunks #0*|4 files_in_context 9*",i.FY]}}class P extends c{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new P).fromBinary(t,r)}static fromJson(t,r){return(new P).fromJson(t,r)}static fromJsonString(t,r){return(new P).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(P,t,r)}static $(){return["ComposerCapabilityRequest.EditTrailCapability|1 custom_instructions 9?"]}}class b extends c{constructor(t){super(),this.additionalFiles=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new b).fromBinary(t,r)}static fromJson(t,r){return(new b).fromJson(t,r)}static fromJsonString(t,r){return(new b).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(b,t,r)}static $(){return["ComposerCapabilityRequest.AutoContextCapability|1 custom_instructions 9?|2 additional_files 9*"]}}class R extends c{constructor(t){super(),this.attachedCodeChunks=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new R).fromBinary(t,r)}static fromJson(t,r){return(new R).fromJson(t,r)}static fromJsonString(t,r){return(new R).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(R,t,r)}static $(){return["ComposerCapabilityRequest.ContextPlannerCapability|1 custom_instructions 9?|2 attached_code_chunks #0*",i.FY]}}class v extends c{constructor(t){super(),this.memory="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new v).fromBinary(t,r)}static fromJson(t,r){return(new v).fromJson(t,r)}static fromJsonString(t,r){return(new v).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(v,t,r)}static $(){return["ComposerCapabilityRequest.RememberThisCapability|1 custom_instructions 9?|2 memory 9"]}}class x extends c{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new x).fromBinary(t,r)}static fromJson(t,r){return(new x).fromJson(t,r)}static fromJsonString(t,r){return(new x).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(x,t,r)}static $(){return["ComposerCapabilityRequest.CursorRulesCapability|1 custom_instructions 9?"]}}class k extends c{constructor(t){super(),this.data={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new k).fromBinary(t,r)}static fromJson(t,r){return(new k).fromJson(t,r)}static fromJsonString(t,r){return(new k).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(k,t,r)}static $(){return["ComposerCapabilityContext|27 slack_integration #0 data|28 github_pr #1 data|29 microsoft_teams_integration #2 data",E,T,C]}}class E extends c{constructor(t){super(),this.thread="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new E).fromBinary(t,r)}static fromJson(t,r){return(new E).fromJson(t,r)}static fromJsonString(t,r){return(new E).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(E,t,r)}static $(){return["ComposerCapabilityContext.SlackIntegrationContext|1 thread 9|2 channel_name 9?|3 channel_purpose 9?|4 channel_topic 9?|5 sender_name 9?|6 sender_id 9?|7 sender_type 9?|8 is_directly_addressed 8?|9 message_permalink 9?"]}}class C extends c{constructor(t){super(),this.thread="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new C).fromBinary(t,r)}static fromJson(t,r){return(new C).fromJson(t,r)}static fromJsonString(t,r){return(new C).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(C,t,r)}static $(){return["ComposerCapabilityContext.MicrosoftTeamsIntegrationContext|1 thread 9|2 channel_name 9?|3 team_name 9?|4 channel_description 9?|5 team_description 9?"]}}class T extends c{constructor(t){super(),this.title="",this.description="",this.comments="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new T).fromBinary(t,r)}static fromJson(t,r){return(new T).fromJson(t,r)}static fromJsonString(t,r){return(new T).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(T,t,r)}static $(){return["ComposerCapabilityContext.GithubPRContext|1 title 9|2 description 9|3 comments 9|4 ci_failures 9?|5 code_tour_context #0",U]}}class U extends c{constructor(t){super(),this.changeId="",this.headSha="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new U).fromBinary(t,r)}static fromJson(t,r){return(new U).fromJson(t,r)}static fromJsonString(t,r){return(new U).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(U,t,r)}static $(){return["ComposerCapabilityContext.GithubPRContext.CodeTourContext|1 change_id 9|2 head_sha 9|3 current_revision_id 9?|4 visible_section_id 9?|5 visible_step_id 9?|6 path_scope_prefix 9?"]}}var A=e("../proto/dist/generated/agent/v1/agent_pb.js"),$=e("../proto/dist/generated/agent/v1/request_context_exec_pb.js"),M=e("../proto/dist/generated/agent/v1/selected_context_pb.js");e("../proto/dist/generated/agent/v1/diagnostics_exec_pb.js");class O extends a.HL{static get runtime(){return(0,a.kU)(this,"runtime",n.proto3)}static $p(){return"aiserver.v1."}}class D extends O{constructor(t){super(),this.lints=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new D).fromBinary(t,r)}static fromJson(t,r){return(new D).fromJson(t,r)}static fromJsonString(t,r){return(new D).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(D,t,r)}static $(){return["GetLintsForChangeResponse|1 lints #0*",N]}}class N extends O{constructor(t){super(),this.message="",this.severity="",this.relativeWorkspacePath="",this.startLineNumberOneIndexed=0,this.startColumnOneIndexed=0,this.endLineNumberInclusiveOneIndexed=0,this.endColumnOneIndexed=0,this.quickFixes=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new N).fromBinary(t,r)}static fromJson(t,r){return(new N).fromJson(t,r)}static fromJsonString(t,r){return(new N).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(N,t,r)}static $(){return["GetLintsForChangeResponse.Lint|1 message 9|2 severity 9|3 relative_workspace_path 9|4 start_line_number_one_indexed 5|5 start_column_one_indexed 5|6 end_line_number_inclusive_one_indexed 5|7 end_column_one_indexed 5|9 quick_fixes #0*",G]}}class G extends O{constructor(t){super(),this.message="",this.kind="",this.isPreferred=!1,this.edits=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new G).fromBinary(t,r)}static fromJson(t,r){return(new G).fromJson(t,r)}static fromJsonString(t,r){return(new G).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(G,t,r)}static $(){return["GetLintsForChangeResponse.Lint.QuickFix|1 message 9|2 kind 9|3 is_preferred 8|4 edits #0*",L]}}class L extends O{constructor(t){super(),this.relativeWorkspacePath="",this.text="",this.startLineNumberOneIndexed=0,this.startColumnOneIndexed=0,this.endLineNumberInclusiveOneIndexed=0,this.endColumnOneIndexed=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new L).fromBinary(t,r)}static fromJson(t,r){return(new L).fromJson(t,r)}static fromJsonString(t,r){return(new L).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(L,t,r)}static $(){return["GetLintsForChangeResponse.Lint.QuickFix.Edit|1 relative_workspace_path 9|2 text 9|3 start_line_number_one_indexed 5|4 start_column_one_indexed 5|5 end_line_number_inclusive_one_indexed 5|6 end_column_one_indexed 5"]}}const F="aiserver.v1.";class K extends a.HL{static get runtime(){return(0,a.kU)(this,"runtime",n.proto3)}static $p(){return F}}var z=(0,a.QT)(n.proto3,F,"ChunkType",[[0,"UNSPECIFIED"],[1,"CODEBASE"],[2,"LONG_FILE"],[3,"DOCS"]],1),j=(0,a.QT)(n.proto3,F,"SubagentType",[[0,"UNSPECIFIED"],[1,"DEEP_SEARCH"],[2,"FIX_LINTS"],[3,"TASK"],[4,"SPEC"]],1);class H extends K{constructor(t){super(),this.summary="",this.truncationLastBubbleIdInclusive="",this.clientShouldStartSendingFromInclusiveBubbleId="",this.previousConversationSummaryBubbleId="",this.includesToolResults=!1,this.strategy="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new H).fromBinary(t,r)}static fromJson(t,r){return(new H).fromJson(t,r)}static fromJsonString(t,r){return(new H).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(H,t,r)}static $(){return["ConversationSummary|1 summary 9|2 truncation_last_bubble_id_inclusive 9|3 client_should_start_sending_from_inclusive_bubble_id 9|4 previous_conversation_summary_bubble_id 9|5 includes_tool_results 8|6 strategy 9"]}}class W extends K{constructor(t){super(),this.relativeWorkspacePath="",this.contents="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new W).fromBinary(t,r)}static fromJson(t,r){return(new W).fromJson(t,r)}static fromJsonString(t,r){return(new W).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(W,t,r)}static $(){return["ContextToRank|1 relative_workspace_path 9|2 contents 9|3 line_range #0?|4 code_block #1?",i.MT,i.NG]}}class Q extends K{constructor(t){super(),this.score=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Q).fromBinary(t,r)}static fromJson(t,r){return(new Q).fromJson(t,r)}static fromJsonString(t,r){return(new Q).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Q,t,r)}static $(){return["RankedContext|1 context #0|2 score 2",W]}}class V extends K{constructor(t){super(),this.chunks=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new V).fromBinary(t,r)}static fromJson(t,r){return(new V).fromJson(t,r)}static fromJsonString(t,r){return(new V).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(V,t,r)}static $(){return["DocumentationCitation|1 chunks #0*",o.ci]}}class X extends K{constructor(t){super(),this.references=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new X).fromBinary(t,r)}static fromJson(t,r){return(new X).fromJson(t,r)}static fromJsonString(t,r){return(new X).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(X,t,r)}static $(){return["WebCitation|1 references #0*",Y]}}class Y extends K{constructor(t){super(),this.title="",this.url="",this.chunk="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Y).fromBinary(t,r)}static fromJson(t,r){return(new Y).fromJson(t,r)}static fromJsonString(t,r){return(new Y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Y,t,r)}static $(){return["WebReference|2 title 9|1 url 9|3 chunk 9"]}}class Z extends K{constructor(t){super(),this.title="",this.url="",this.chunk="",this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Z).fromBinary(t,r)}static fromJson(t,r){return(new Z).fromJson(t,r)}static fromJsonString(t,r){return(new Z).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Z,t,r)}static $(){return["DocsReference|1 title 9|2 url 9|3 chunk 9|4 name 9"]}}class tt extends K{constructor(t){super(),this.content="",this.title="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tt).fromBinary(t,r)}static fromJson(t,r){return(new tt).fromJson(t,r)}static fromJsonString(t,r){return(new tt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tt,t,r)}static $(){return["AiWebSearchResult|1 content 9|2 title 9"]}}class rt extends K{constructor(t){super(),this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rt).fromBinary(t,r)}static fromJson(t,r){return(new rt).fromJson(t,r)}static fromJsonString(t,r){return(new rt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rt,t,r)}static $(){return["StatusUpdate|1 message 9|2 metadata 9?"]}}class et extends K{constructor(t){super(),this.updates=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new et).fromBinary(t,r)}static fromJson(t,r){return(new et).fromJson(t,r)}static fromJsonString(t,r){return(new et).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(et,t,r)}static $(){return["StatusUpdates|1 updates #0*",rt]}}class nt extends K{constructor(t){super(),this.fileName="",this.diffHistory=[],this.diffHistoryTimestamps=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nt).fromBinary(t,r)}static fromJson(t,r){return(new nt).fromJson(t,r)}static fromJsonString(t,r){return(new nt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nt,t,r)}static $(){return["ComposerFileDiffHistory|1 file_name 9|2 diff_history 9*|3 diff_history_timestamps 1*"]}}var st=(0,a.QT)(n.proto3,F,"StreamUnifiedChatRequest.UnifiedMode",[[0,"UNSPECIFIED"],[1,"CHAT"],[2,"AGENT"],[3,"EDIT"],[4,"CUSTOM"],[5,"PLAN"],[6,"DEBUG"]],1);n.proto3;class it extends K{constructor(t){super(),this.relativeWorkspacePath="",this.content="",this.score=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new it).fromBinary(t,r)}static fromJson(t,r){return(new it).fromJson(t,r)}static fromJsonString(t,r){return(new it).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(it,t,r)}static $(){return["ContextPiece|1 relative_workspace_path 9|2 content 9|3 score 2"]}}class ot extends K{constructor(t){super(),this.percentageRemaining=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ot).fromBinary(t,r)}static fromJson(t,r){return(new ot).fromJson(t,r)}static fromJsonString(t,r){return(new ot).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ot,t,r)}static $(){return["ContextWindowStatus|1 percentage_remaining 5|2 tokens_used 5?|3 token_limit 5?|4 percentage_remaining_float 2?"]}}class at extends K{constructor(t){super(),this.message="",this.codicon="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new at).fromBinary(t,r)}static fromJson(t,r){return(new at).fromJson(t,r)}static fromJsonString(t,r){return(new at).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(at,t,r)}static $(){return["ServiceStatusUpdate|1 message 9|2 codicon 9|3 allow_command_links_potentially_unsafe_please_only_use_for_handwritten_trusted_markdown 8?|4 action_to_run_on_status_update 9?"]}}class ut extends K{constructor(t){super(),this.symbolName="",this.symbolSearchString="",this.relativeWorkspacePath="",this.roughLineNumber=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ut).fromBinary(t,r)}static fromJson(t,r){return(new ut).fromJson(t,r)}static fromJsonString(t,r){return(new ut).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ut,t,r)}static $(){return["SymbolLink|1 symbol_name 9|2 symbol_search_string 9|3 relative_workspace_path 9|4 rough_line_number 5"]}}class ct extends K{constructor(t){super(),this.displayName="",this.relativeWorkspacePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ct).fromBinary(t,r)}static fromJson(t,r){return(new ct).fromJson(t,r)}static fromJsonString(t,r){return(new ct).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ct,t,r)}static $(){return["FileLink|1 display_name 9|2 relative_workspace_path 9"]}}class lt extends K{constructor(t){super(),this.relativeWorkspacePath="",this.redRanges=[],this.redRangesReversed=[],this.startHash="",this.endHash="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lt).fromBinary(t,r)}static fromJson(t,r){return(new lt).fromJson(t,r)}static fromJsonString(t,r){return(new lt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lt,t,r)}static $(){return["RedDiff|1 relative_workspace_path 9|2 red_ranges #0*|3 red_ranges_reversed #0*|4 start_hash 9|5 end_hash 9",i.l2]}}class mt extends K{constructor(t){super(),this.fileDetails="",this.fileName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mt).fromBinary(t,r)}static fromJson(t,r){return(new mt).fromJson(t,r)}static fromJsonString(t,r){return(new mt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mt,t,r)}static $(){return["DiffFile|1 file_details 9|2 file_name 9"]}}class ft extends K{constructor(t){super(),this.description="",this.message="",this.files=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ft).fromBinary(t,r)}static fromJson(t,r){return(new ft).fromJson(t,r)}static fromJsonString(t,r){return(new ft).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ft,t,r)}static $(){return["ViewableCommitProps|1 description 9|2 message 9|3 files #0*",mt]}}class dt extends K{constructor(t){super(),this.title="",this.body="",this.files=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dt).fromBinary(t,r)}static fromJson(t,r){return(new dt).fromJson(t,r)}static fromJsonString(t,r){return(new dt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dt,t,r)}static $(){return["ViewablePRProps|1 title 9|2 body 9|3 files #0*",mt]}}class pt extends K{constructor(t){super(),this.files=[],this.diffPreface="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pt).fromBinary(t,r)}static fromJson(t,r){return(new pt).fromJson(t,r)}static fromJsonString(t,r){return(new pt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pt,t,r)}static $(){return["ViewableDiffProps|1 files #0*|2 diff_preface 9",mt]}}class ht extends K{constructor(t){super(),this.diffData=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ht).fromBinary(t,r)}static fromJson(t,r){return(new ht).fromJson(t,r)}static fromJsonString(t,r){return(new ht).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ht,t,r)}static $(){return["ViewableGitContext|1 commit_data #0?|2 pull_request_data #1?|3 diff_data #2*",ft,dt,pt]}}class gt extends K{constructor(t){super(),this.text="",this.type=_t.UNSPECIFIED,this.attachedCodeChunks=[],this.codebaseContextChunks=[],this.commits=[],this.pullRequests=[],this.gitDiffs=[],this.assistantSuggestedDiffs=[],this.interpreterResults=[],this.images=[],this.attachedFolders=[],this.approximateLintErrors=[],this.bubbleId="",this.attachedFoldersNew=[],this.lints=[],this.userResponsesToSuggestedCodeBlocks=[],this.relevantFiles=[],this.toolResults=[],this.notepads=[],this.capabilities=[],this.editTrailContexts=[],this.suggestedCodeBlocks=[],this.diffsForCompressingFiles=[],this.multiFileLinterErrors=[],this.diffHistories=[],this.recentlyViewedFiles=[],this.recentLocationsHistory=[],this.isAgentic=!1,this.fileDiffTrajectories=[],this.existedSubsequentTerminalCommand=!1,this.existedPreviousTerminalCommand=!1,this.docsReferences=[],this.webReferences=[],this.aiWebSearchResults=[],this.attachedFoldersListDirResults=[],this.humanChanges=[],this.attachedHumanChanges=!1,this.summarizedComposers=[],this.cursorRules=[],this.contextPieces=[],this.allThinkingBlocks=[],this.diffsSinceLastApply=[],this.deletedFiles=[],this.supportedTools=[],this.consoleLogs=[],this.knowledgeItems=[],this.uiElementPicked=[],this.documentationSelections=[],this.externalLinks=[],this.projectLayouts=[],this.capabilityContexts=[],this.todos=[],this.requestId="",this.createdAt="",this.mcpDescriptors=[],this.workspaceUris=[],this.cursorCommands=[],this.cursorCommandsExplicitlySet=!1,this.pastChats=[],this.pastChatsExplicitlySet=!1,this.selectedRepositories=[],this.selectedEnvironments=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gt).fromBinary(t,r)}static fromJson(t,r){return(new gt).fromJson(t,r)}static fromJsonString(t,r){return(new gt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gt,t,r)}static $(){return["ConversationMessage|1 text 9|2 type #0|3 attached_code_chunks #1*|4 codebase_context_chunks #2*|5 commits #3*|6 pull_requests #4*|7 git_diffs #5*|8 assistant_suggested_diffs #6*|9 interpreter_results #7*|10 images #8*|11 attached_folders 9*|12 approximate_lint_errors #9*|13 bubble_id 9|32 server_bubble_id 9?|14 attached_folders_new #10*|15 lints #11*|16 user_responses_to_suggested_code_blocks #12*|17 relevant_files 9*|18 tool_results #13*|19 notepads #14*|20 is_capability_iteration 8?|21 capabilities #15*|22 edit_trail_contexts #16*|23 suggested_code_blocks #17*|24 diffs_for_compressing_files #18*|25 multi_file_linter_errors #19*|26 diff_histories #20*|27 recently_viewed_files #1*|28 recent_locations_history #21*|29 is_agentic 8|30 file_diff_trajectories #22*|31 conversation_summary #23?|33 existed_subsequent_terminal_command 8|34 existed_previous_terminal_command 8|35 docs_references #24*|36 web_references #25*|75 ai_web_search_results #26*|37 git_context #27?|38 attached_folders_list_dir_results #28*|39 cached_conversation_summary #23?|40 human_changes #29*|41 attached_human_changes 8|42 summarized_composers #30*|43 cursor_rules #31*|44 context_pieces #32*|45 thinking #33?|46 all_thinking_blocks #33*|85 thinking_style #34?|47 unified_mode #35?|98 agent_mode #36?|48 diffs_since_last_apply #37*|49 deleted_files #38*|50 usage_uuid 9?|51 supported_tools #39*|52 current_file_location_data #40?|53 edit_tool_supports_search_and_replace 8?|54 last_terminal_cwd 9?|55 user_explicitly_asked_to_generate_cursor_rules 8?|56 console_logs #41*|57 rich_text 9?|58 knowledge_items #42*|59 ui_element_picked #43*|60 user_explicitly_asked_to_add_to_knowledge_base 8?|61 documentation_selections #44*|62 external_links #45*|63 use_web 8?|64 project_layouts #46*|65 thinking_duration_ms 5?|88 step_duration_ms 5?|66 subagent_return #47?|67 is_simple_looping_message 8?|68 capability_contexts #48*|69 checkpoint_commit_hash 9?|70 git_status_raw 9?|71 todos #49*|72 is_review_edits_followup 8?|74 request_id 9|73 ide_editors_state #50?|76 context_window_status #51?|77 is_plan_execution 8?|78 created_at 9|79 model_info #52|80 is_quick_search_query 8?|81 plan_update #53?|82 is_simulated_msg 8?|95 simulated_msg_reason #54?|97 simulated_message_metadata #55?|83 mcp_descriptors #56*|84 workspace_project_dir 9?|87 workspace_uris 9*|86 debug_mode_config #57?|89 text_blob_id 12?|90 rich_text_blob_id 12?|91 cursor_commands #58*|92 cursor_commands_explicitly_set 8|93 past_chats #59*|94 past_chats_explicitly_set 8|109 selected_repositories #60*|110 selected_environments #61*|96 triggering_user_info #62?|99 turn_steer 8?|100 sent_by_agent_id 9?|101 sent_by_voice_call 8?|102 sender #63?|103 reply_to 9?|104 reply_audience #64?|105 reply_to_tool_call_id 9?|106 summarized_tool_call_id 9?|107 reply_quote 9?|108 thread_id 9?",_t,wt,i.NG,Xt,Yt,i.o$,Qt,Wt,i.UR,xt,jt,kt,tr,It,Pt,l,vt,Zt,lt,i.U$,or,Et,nt,H,Z,Y,tt,ht,s.$PL,Tt,bt,i.DX,it,Ut,Jt,st,A.xyI,At,$t,s.XaY,zt,i.EZ,Mt,i.c5,Ot,i.ot,pr,ar,k,s.kWq,Dt,ot,i.Wj,Gt,A.c_h,Lt,Ft,$.TT,M.Ps,M.AW,M.uM,M.bf,A.iHX,A.D$r,A.HXb]}}var _t=(0,a.QT)(n.proto3,F,"ConversationMessage.MessageType",[[0,"UNSPECIFIED"],[1,"HUMAN"],[2,"AI"]],1),Jt=(0,a.QT)(n.proto3,F,"ConversationMessage.ThinkingStyle",[[0,"UNSPECIFIED"],[1,"DEFAULT"],[2,"CODEX"],[3,"GPT5"]],1);class wt extends K{constructor(t){super(),this.relativeWorkspacePath="",this.startLineNumber=0,this.lines=[],this.languageIdentifier="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wt).fromBinary(t,r)}static fromJson(t,r){return(new wt).fromJson(t,r)}static fromJsonString(t,r){return(new wt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wt,t,r)}static $(){return["ConversationMessage.CodeChunk|1 relative_workspace_path 9|2 start_line_number 5|3 lines 9*|4 summarization_strategy #0?|5 language_identifier 9|6 intent #1?|7 is_final_version 8?|8 is_first_version 8?|9 contents_are_missing 8?|10 is_only_included_from_folder 8?|11 code_chunk_git_context #2?",St,yt,qt]}}var yt=(0,a.QT)(n.proto3,F,"ConversationMessage.CodeChunk.Intent",[[0,"UNSPECIFIED"],[1,"COMPOSER_FILE"],[2,"COMPRESSED_COMPOSER_FILE"],[3,"RECENTLY_VIEWED_FILE"],[4,"OUTLINE"],[5,"MENTIONED_FILE"],[6,"CODE_SELECTION"],[7,"AI_EDITED_FILE"],[8,"VISIBLE_FILE"],[9,"TERMINAL_SELECTION"]],1),St=(0,a.QT)(n.proto3,F,"ConversationMessage.CodeChunk.SummarizationStrategy",[[0,"NONE_UNSPECIFIED"],[1,"SUMMARIZED"],[2,"EMBEDDED"]],1);class qt extends K{constructor(t){super(),this.gitInfo=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qt).fromBinary(t,r)}static fromJson(t,r){return(new qt).fromJson(t,r)}static fromJsonString(t,r){return(new qt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qt,t,r)}static $(){return["ConversationMessage.CodeChunk.CodeChunkGitContext|1 git_info #0*",Bt]}}class Bt extends K{constructor(t){super(),this.commit="",this.author="",this.date="",this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bt).fromBinary(t,r)}static fromJson(t,r){return(new Bt).fromJson(t,r)}static fromJsonString(t,r){return(new Bt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bt,t,r)}static $(){return["ConversationMessage.CodeChunk.CodeChunkGitContext.CodeChunkGitInfo|1 commit 9|2 author 9|3 date 9|4 message 9"]}}class It extends K{constructor(t){super(),this.toolCallId="",this.toolName="",this.toolIndex=0,this.args="",this.rawArgs="",this.attachedCodeChunks=[],this.images=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new It).fromBinary(t,r)}static fromJson(t,r){return(new It).fromJson(t,r)}static fromJsonString(t,r){return(new It).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(It,t,r)}static $(){return["ConversationMessage.ToolResult|1 tool_call_id 9|2 tool_name 9|3 tool_index 13|12 model_call_id 9?|4 args 9|5 raw_args 9|6 attached_code_chunks #0*|7 content 9?|8 result #1|9 error #2?|10 images #3*|11 tool_call #4?|13 started_at_ms 4?|14 completed_at_ms 4?",wt,s.Ue3,s.MtQ,i.UR,s.TE4]}}class Pt extends K{constructor(t){super(),this.name="",this.text="",this.attachedCodeChunks=[],this.attachedFolders=[],this.commits=[],this.pullRequests=[],this.gitDiffs=[],this.images=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pt).fromBinary(t,r)}static fromJson(t,r){return(new Pt).fromJson(t,r)}static fromJsonString(t,r){return(new Pt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pt,t,r)}static $(){return["ConversationMessage.NotepadContext|1 name 9|2 text 9|3 attached_code_chunks #0*|4 attached_folders 9*|5 commits #1*|6 pull_requests #2*|7 git_diffs #3*|8 images #4*",wt,Xt,Yt,i.o$,i.UR]}}class bt extends K{constructor(t){super(),this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bt).fromBinary(t,r)}static fromJson(t,r){return(new bt).fromJson(t,r)}static fromJsonString(t,r){return(new bt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bt,t,r)}static $(){return["ConversationMessage.ComposerContext|1 name 9|2 conversation_summary #0",H]}}class Rt extends K{constructor(t){super(),this.relativeWorkspacePath="",this.contextLines="",this.text="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rt).fromBinary(t,r)}static fromJson(t,r){return(new Rt).fromJson(t,r)}static fromJsonString(t,r){return(new Rt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rt,t,r)}static $(){return["ConversationMessage.EditLocation|1 relative_workspace_path 9|3 range #0|4 initial_range #0|5 context_lines 9|6 text 9|7 text_range #0",i.l2]}}class vt extends K{constructor(t){super(),this.uniqueId="",this.editTrailSorted=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vt).fromBinary(t,r)}static fromJson(t,r){return(new vt).fromJson(t,r)}static fromJsonString(t,r){return(new vt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vt,t,r)}static $(){return["ConversationMessage.EditTrailContext|1 unique_id 9|2 edit_trail_sorted #0*",Rt]}}class xt extends K{constructor(t){super(),this.message="",this.value="",this.startLine=0,this.endLine=0,this.startColumn=0,this.endColumn=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xt).fromBinary(t,r)}static fromJson(t,r){return(new xt).fromJson(t,r)}static fromJsonString(t,r){return(new xt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xt,t,r)}static $(){return["ConversationMessage.ApproximateLintError|1 message 9|2 value 9|3 start_line 5|4 end_line 5|5 start_column 5|6 end_column 5"]}}class kt extends K{constructor(t){super(),this.chatCodeblockModelValue="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kt).fromBinary(t,r)}static fromJson(t,r){return(new kt).fromJson(t,r)}static fromJsonString(t,r){return(new kt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kt,t,r)}static $(){return["ConversationMessage.Lints|1 lints #0|2 chat_codeblock_model_value 9",D]}}class Et extends K{constructor(t){super(),this.relativeWorkspacePath="",this.lineNumber=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Et).fromBinary(t,r)}static fromJson(t,r){return(new Et).fromJson(t,r)}static fromJsonString(t,r){return(new Et).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Et,t,r)}static $(){return["ConversationMessage.RecentLocation|1 relative_workspace_path 9|2 line_number 5"]}}class Ct extends K{constructor(t){super(),this.startLineNumber=0,this.endLineNumberExclusive=0,this.beforeContextLines=[],this.removedLines=[],this.addedLines=[],this.afterContextLines=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ct).fromBinary(t,r)}static fromJson(t,r){return(new Ct).fromJson(t,r)}static fromJsonString(t,r){return(new Ct).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ct,t,r)}static $(){return["ConversationMessage.RenderedDiff|1 start_line_number 5|2 end_line_number_exclusive 5|3 before_context_lines 9*|4 removed_lines 9*|5 added_lines 9*|6 after_context_lines 9*"]}}class Tt extends K{constructor(t){super(),this.relativeWorkspacePath="",this.renderedDiffs=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tt).fromBinary(t,r)}static fromJson(t,r){return(new Tt).fromJson(t,r)}static fromJsonString(t,r){return(new Tt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tt,t,r)}static $(){return["ConversationMessage.HumanChange|1 relative_workspace_path 9|2 rendered_diffs #0*",Ct]}}class Ut extends K{constructor(t){super(),this.text="",this.signature="",this.redactedThinking="",this.isLastThinkingChunk=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ut).fromBinary(t,r)}static fromJson(t,r){return(new Ut).fromJson(t,r)}static fromJsonString(t,r){return(new Ut).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ut,t,r)}static $(){return["ConversationMessage.Thinking|1 text 9|2 signature 9|3 redacted_thinking 9|4 is_last_thinking_chunk 8"]}}class At extends K{constructor(t){super(),this.relativeWorkspacePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new At).fromBinary(t,r)}static fromJson(t,r){return(new At).fromJson(t,r)}static fromJsonString(t,r){return(new At).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(At,t,r)}static $(){return["ConversationMessage.DiffSinceLastApply|1 relative_workspace_path 9|2 diff #0?|4 is_accepted 8?|5 is_rejected 8?|6 last_apply_chained_from_n_human_messages_ago 5?",s.KRm]}}class $t extends K{constructor(t){super(),this.relativeWorkspacePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $t).fromBinary(t,r)}static fromJson(t,r){return(new $t).fromJson(t,r)}static fromJsonString(t,r){return(new $t).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($t,t,r)}static $(){return["ConversationMessage.DeletedFile|1 relative_workspace_path 9"]}}class Mt extends K{constructor(t){super(),this.title="",this.knowledge="",this.knowledgeId="",this.isGenerated=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mt).fromBinary(t,r)}static fromJson(t,r){return(new Mt).fromJson(t,r)}static fromJsonString(t,r){return(new Mt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mt,t,r)}static $(){return["ConversationMessage.KnowledgeItem|1 title 9|2 knowledge 9|3 knowledge_id 9|4 is_generated 8"]}}class Ot extends K{constructor(t){super(),this.docId="",this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ot).fromBinary(t,r)}static fromJson(t,r){return(new Ot).fromJson(t,r)}static fromJsonString(t,r){return(new Ot).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ot,t,r)}static $(){return["ConversationMessage.DocumentationSelection|1 doc_id 9|2 name 9"]}}class Dt extends K{constructor(t){super(),this.isPillDisplayed=!1,this.visibleFilePaths=[],this.recentlyViewedFilePaths=[],this.visibleFiles=[],this.recentlyViewedFiles=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dt).fromBinary(t,r)}static fromJson(t,r){return(new Dt).fromJson(t,r)}static fromJsonString(t,r){return(new Dt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dt,t,r)}static $(){return["ConversationMessage.IdeEditorsState|1 is_pill_displayed 8|2 visible_file_paths 9*|3 recently_viewed_file_paths 9*|4 visible_files #0*|5 recently_viewed_files #0*",Nt]}}class Nt extends K{constructor(t){super(),this.relativePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nt).fromBinary(t,r)}static fromJson(t,r){return(new Nt).fromJson(t,r)}static fromJsonString(t,r){return(new Nt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nt,t,r)}static $(){return["ConversationMessage.IdeEditorsState.File|1 relative_path 9|2 is_currently_focused 8?|3 current_line_number 5?|4 current_line_text 9?|5 line_count 5?|6 absolute_path 9?"]}}class Gt extends K{constructor(t){super(),this.currentPlan="",this.isFirstTimeSeen=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gt).fromBinary(t,r)}static fromJson(t,r){return(new Gt).fromJson(t,r)}static fromJsonString(t,r){return(new Gt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gt,t,r)}static $(){return["ConversationMessage.PlanUpdate|1 current_plan 9|2 is_first_time_seen 8"]}}class Lt extends K{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lt).fromBinary(t,r)}static fromJson(t,r){return(new Lt).fromJson(t,r)}static fromJsonString(t,r){return(new Lt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Lt,t,r)}static $(){return["ConversationMessage.SimulatedMessageMetadata|1 title 9?|2 task_id 9?|3 fsd_finding_action 9?|4 url 9?|5 subscription_source #0?|6 subscription_event_display #1?|7 interaction_response #2?",A.vns,A.gan,A.nh0]}}class Ft extends K{constructor(t){super(),this.folderPath="",this.tools=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ft).fromBinary(t,r)}static fromJson(t,r){return(new Ft).fromJson(t,r)}static fromJsonString(t,r){return(new Ft).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ft,t,r)}static $(){return["ConversationMessage.McpDescriptor|1 folder_path 9|2 server_name 9?|3 tools #0*|4 server_use_instructions 9?",Kt]}}class Kt extends K{constructor(t){super(),this.toolName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kt).fromBinary(t,r)}static fromJson(t,r){return(new Kt).fromJson(t,r)}static fromJsonString(t,r){return(new Kt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Kt,t,r)}static $(){return["ConversationMessage.McpDescriptor.Tool|1 tool_name 9|2 description 9?"]}}class zt extends K{constructor(t){super(),this.relativeWorkspacePath="",this.lineNumber=0,this.text="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zt).fromBinary(t,r)}static fromJson(t,r){return(new zt).fromJson(t,r)}static fromJsonString(t,r){return(new zt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zt,t,r)}static $(){return["CurrentFileLocationData|1 relative_workspace_path 9|2 line_number 5|3 text 9"]}}class jt extends K{constructor(t){super(),this.relativePath="",this.files=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jt).fromBinary(t,r)}static fromJson(t,r){return(new jt).fromJson(t,r)}static fromJsonString(t,r){return(new jt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jt,t,r)}static $(){return["FolderInfo|1 relative_path 9|2 files #0*",Ht]}}class Ht extends K{constructor(t){super(),this.relativePath="",this.content="",this.truncated=!1,this.score=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ht).fromBinary(t,r)}static fromJson(t,r){return(new Ht).fromJson(t,r)}static fromJsonString(t,r){return(new Ht).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ht,t,r)}static $(){return["FolderFileInfo|1 relative_path 9|2 content 9|3 truncated 8|4 score 2"]}}class Wt extends K{constructor(t){super(),this.output="",this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wt).fromBinary(t,r)}static fromJson(t,r){return(new Wt).fromJson(t,r)}static fromJsonString(t,r){return(new Wt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wt,t,r)}static $(){return["InterpreterResult|1 output 9|2 success 8"]}}class Qt extends K{constructor(t){super(),this.relativeWorkspacePath="",this.chunks=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qt).fromBinary(t,r)}static fromJson(t,r){return(new Qt).fromJson(t,r)}static fromJsonString(t,r){return(new Qt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qt,t,r)}static $(){return["SimpleFileDiff|1 relative_workspace_path 9|3 chunks #0*",Vt]}}class Vt extends K{constructor(t){super(),this.oldLines=[],this.newLines=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vt).fromBinary(t,r)}static fromJson(t,r){return(new Vt).fromJson(t,r)}static fromJsonString(t,r){return(new Vt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vt,t,r)}static $(){return["SimpleFileDiff.Chunk|1 old_lines 9*|2 new_lines 9*|3 old_range #0|4 new_range #0",i.MT]}}class Xt extends K{constructor(t){super(),this.sha="",this.message="",this.description="",this.diff=[],this.author="",this.date="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xt).fromBinary(t,r)}static fromJson(t,r){return(new Xt).fromJson(t,r)}static fromJsonString(t,r){return(new Xt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xt,t,r)}static $(){return["Commit|1 sha 9|2 message 9|3 description 9|4 diff #0*|5 author 9|6 date 9",i.QP]}}class Yt extends K{constructor(t){super(),this.title="",this.body="",this.diff=[],this.id=n.protoInt64.zero,this.number=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yt).fromBinary(t,r)}static fromJson(t,r){return(new Yt).fromJson(t,r)}static fromJsonString(t,r){return(new Yt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yt,t,r)}static $(){return["PullRequest|1 title 9|2 body 9|3 diff #0*|4 id 3|5 number 3",i.QP]}}class Zt extends K{constructor(t){super(),this.relativeWorkspacePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zt).fromBinary(t,r)}static fromJson(t,r){return(new Zt).fromJson(t,r)}static fromJsonString(t,r){return(new Zt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zt,t,r)}static $(){return["SuggestedCodeBlock|1 relative_workspace_path 9"]}}class tr extends K{constructor(t){super(),this.userResponseType=rr.UNSPECIFIED,this.filePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tr).fromBinary(t,r)}static fromJson(t,r){return(new tr).fromJson(t,r)}static fromJsonString(t,r){return(new tr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tr,t,r)}static $(){return["UserResponseToSuggestedCodeBlock|1 user_response_type #0|2 file_path 9|3 user_modifications_to_suggested_code_blocks #1?",rr,i.QP]}}var rr=(0,a.QT)(n.proto3,F,"UserResponseToSuggestedCodeBlock.UserResponseType",[[0,"UNSPECIFIED"],[1,"ACCEPT"],[2,"REJECT"],[3,"MODIFY"]],1);class er extends K{constructor(t){super(),this.fileName="",this.fileContent="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new er).fromBinary(t,r)}static fromJson(t,r){return(new er).fromJson(t,r)}static fromJsonString(t,r){return(new er).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(er,t,r)}static $(){return["ContextRerankingCandidateFile|1 file_name 9|2 file_content 9"]}}class nr extends K{constructor(t){super(),this.chunks=[],this.editor=sr.UNSPECIFIED,this.hitTimeout=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nr).fromBinary(t,r)}static fromJson(t,r){return(new nr).fromJson(t,r)}static fromJsonString(t,r){return(new nr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nr,t,r)}static $(){return["ComposerFileDiff|1 chunks #0*|2 editor #1|3 hit_timeout 8",ir,sr]}}var sr=(0,a.QT)(n.proto3,F,"ComposerFileDiff.Editor",[[0,"UNSPECIFIED"],[1,"AI"],[2,"HUMAN"]],1);class ir extends K{constructor(t){super(),this.diffString="",this.oldStart=0,this.newStart=0,this.oldLines=0,this.newLines=0,this.linesRemoved=0,this.linesAdded=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ir).fromBinary(t,r)}static fromJson(t,r){return(new ir).fromJson(t,r)}static fromJsonString(t,r){return(new ir).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ir,t,r)}static $(){return["ComposerFileDiff.ChunkDiff|1 diff_string 9|2 old_start 5|3 new_start 5|4 old_lines 5|5 new_lines 5|6 lines_removed 5|7 lines_added 5"]}}class or extends K{constructor(t){super(),this.relativeWorkspacePath="",this.diffs=[],this.timestamp=0,this.uniqueId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new or).fromBinary(t,r)}static fromJson(t,r){return(new or).fromJson(t,r)}static fromJsonString(t,r){return(new or).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(or,t,r)}static $(){return["DiffHistoryData|1 relative_workspace_path 9|2 diffs #0*|3 timestamp 1|4 unique_id 9|5 start_to_end_diff #0",nr]}}n.proto3,n.proto3,n.proto3,n.proto3;class ar extends K{constructor(t){super(),this.subagentType=j.UNSPECIFIED,this.returnValue={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ar).fromBinary(t,r)}static fromJson(t,r){return(new ar).fromJson(t,r)}static fromJsonString(t,r){return(new ar).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ar,t,r)}static $(){return["SubagentReturnCall|1 subagent_type #0|2 deep_search_return_value #1 return_value|3 fix_lints_return_value #2 return_value|4 task_return_value #3 return_value|5 spec_return_value #4 return_value",j,ur,lr,mr,fr]}}class ur extends K{constructor(t){super(),this.contextItems=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ur).fromBinary(t,r)}static fromJson(t,r){return(new ur).fromJson(t,r)}static fromJsonString(t,r){return(new ur).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ur,t,r)}static $(){return["DeepSearchSubagentReturnValue|1 context_items #0*",cr]}}class cr extends K{constructor(t){super(),this.file="",this.explanation="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cr).fromBinary(t,r)}static fromJson(t,r){return(new cr).fromJson(t,r)}static fromJsonString(t,r){return(new cr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cr,t,r)}static $(){return["DeepSearchSubagentReturnValue.ContextItem|1 file 9|2 line_range #0?|3 explanation 9",i.MT]}}class lr extends K{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lr).fromBinary(t,r)}static fromJson(t,r){return(new lr).fromJson(t,r)}static fromJsonString(t,r){return(new lr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lr,t,r)}static $(){return["FixLintsSubagentReturnValue"]}}class mr extends K{constructor(t){super(),this.summary="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mr).fromBinary(t,r)}static fromJson(t,r){return(new mr).fromJson(t,r)}static fromJsonString(t,r){return(new mr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mr,t,r)}static $(){return["TaskSubagentReturnValue|1 summary 9"]}}class fr extends K{constructor(t){super(),this.summary="",this.stringReplacements=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fr).fromBinary(t,r)}static fromJson(t,r){return(new fr).fromJson(t,r)}static fromJsonString(t,r){return(new fr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fr,t,r)}static $(){return["SpecSubagentReturnValue|1 summary 9|2 string_replacements #0*",dr]}}class dr extends K{constructor(t){super(),this.oldString="",this.newString="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dr).fromBinary(t,r)}static fromJson(t,r){return(new dr).fromJson(t,r)}static fromJsonString(t,r){return(new dr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dr,t,r)}static $(){return["StringReplacement|1 old_string 9|2 new_string 9"]}}class pr extends K{constructor(t){super(),this.rootPath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pr).fromBinary(t,r)}static fromJson(t,r){return(new pr).fromJson(t,r)}static fromJsonString(t,r){return(new pr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pr,t,r)}static $(){return["ProjectLayout|1 root_path 9|2 content #0|3 list_dir_v2_result #1?",hr,s.$rP]}}class hr extends K{constructor(t){super(),this.directories=[],this.files=[],this.hiddenFiles=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hr).fromBinary(t,r)}static fromJson(t,r){return(new hr).fromJson(t,r)}static fromJsonString(t,r){return(new hr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hr,t,r)}static $(){return["ProjectLayoutDirectoryContent|1 directories #0*|2 files #1*|3 total_files 5?|4 total_subfolders 5?|5 hidden_files #1*",gr,_r]}}class gr extends K{constructor(t){super(),this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gr).fromBinary(t,r)}static fromJson(t,r){return(new gr).fromJson(t,r)}static fromJsonString(t,r){return(new gr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gr,t,r)}static $(){return["ProjectLayoutDirectory|1 name 9|2 content #0",hr]}}class _r extends K{constructor(t){super(),this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _r).fromBinary(t,r)}static fromJson(t,r){return(new _r).fromJson(t,r)}static fromJsonString(t,r){return(new _r).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_r,t,r)}static $(){return["ProjectLayoutFile|1 name 9"]}}},"../proto/dist/generated/aiserver/v1/dashboard_pb.js"(t,r,e){e.d(r,{LRJ:()=>bm,bCe:()=>Rm,MSh:()=>xs,Hdf:()=>Is,uHx:()=>ll,yDS:()=>ml,bo5:()=>UC,xWW:()=>AC,fdV:()=>OM,VVb:()=>DM,gMg:()=>oP,yD7:()=>aP,zyk:()=>rz,LLT:()=>ez,Hcr:()=>UE,he9:()=>AE,Y9_:()=>aG,CeW:()=>uG,U8V:()=>oa,mf3:()=>aa,ggo:()=>ga,aHm:()=>_a,$n5:()=>li,pji:()=>v_,D3c:()=>x_,yqO:()=>Ua,Gc8:()=>Aa,Ipj:()=>Dz,a0c:()=>Nz,ZM7:()=>V_,ufl:()=>Q_,GJd:()=>DD,LmS:()=>ND,mi9:()=>ky,Izq:()=>Cy,flJ:()=>ED,SZm:()=>CD,Wew:()=>Yh,AZo:()=>Zh,c2n:()=>XD,ISv:()=>YD,flK:()=>Wb,Pqr:()=>Qb,X2v:()=>Md,B6m:()=>Od,bJ2:()=>ZK,TOY:()=>tz,aFD:()=>ok,W5r:()=>uk,t3S:()=>DE,PXK:()=>GE,VN4:()=>ki,nPy:()=>Ci,Vi2:()=>LF,lXe:()=>FF,v_r:()=>hl,$n:()=>gl,pAq:()=>Ex,LOM:()=>Cx,HZm:()=>Pg,lRG:()=>bg,oOo:()=>Rg,MIx:()=>vg,IV$:()=>bB,yW5:()=>AB,yD0:()=>al,MEI:()=>ul,ukN:()=>p_,cRU:()=>h_,MRM:()=>__,wb2:()=>J_,QKN:()=>iE,wmq:()=>oE,iOH:()=>HO,g5C:()=>WO,uBx:()=>Uw,_rf:()=>Aw,H5i:()=>cU,zah:()=>lU,wKn:()=>LK,wIY:()=>FK,n$8:()=>aK,VxM:()=>uK,KBr:()=>Ju,EAu:()=>wu,OjU:()=>Rn,Ohd:()=>vn,vJq:()=>OG,PaT:()=>DG,wm7:()=>IC,O$A:()=>PC,tI8:()=>ms,xpT:()=>fs,$bV:()=>ep,boh:()=>np,bWR:()=>xx,FQR:()=>kx,SH9:()=>Jn,_$M:()=>yn,X38:()=>_m,tZA:()=>Jm,wlK:()=>hx,Adp:()=>gx,ecT:()=>mk,YdR:()=>fk,ign:()=>ro,WSJ:()=>eo,vaB:()=>Cs,rzz:()=>Ts,nL6:()=>Cm,rEt:()=>Tm,S3E:()=>sc,o6Z:()=>oc,sJl:()=>ec,ukh:()=>nc,_do:()=>PS,EAb:()=>bS,Bdx:()=>SA,Zk6:()=>qA,CHh:()=>aA,GL9:()=>uA,ZN0:()=>Mf,DdV:()=>Of,byf:()=>nd,vXf:()=>sd,m5V:()=>zm,MSw:()=>jm,d7o:()=>NF,LRW:()=>GF,Z9k:()=>$K,rxf:()=>MK,Vbl:()=>wK,lQ7:()=>yK,p8r:()=>vE,Dsz:()=>xE,OoP:()=>LL,gZI:()=>FL,XQi:()=>Ah,FGN:()=>$h,KFb:()=>Bd,WRW:()=>Id,C1F:()=>Vo,wqi:()=>Xo,ed4:()=>Po,urU:()=>Ro,Cqw:()=>yu,mk5:()=>Su,JoU:()=>gu,vU:()=>_u,iQx:()=>Wi,uYE:()=>ao,bhY:()=>s_,XEQ:()=>i_,PTe:()=>_l,pF3:()=>Jl,hzU:()=>hD,rfl:()=>gD,XAW:()=>Pl,bTQ:()=>bl,IW3:()=>A_,wmn:()=>$_,BwS:()=>rC,dnd:()=>eC,PwZ:()=>hC,vFW:()=>gC,C10:()=>Yp,e7b:()=>th,EMn:()=>Dk,QEY:()=>Nk,Cbz:()=>GD,Gf$:()=>LD,_C2:()=>km,Mdl:()=>Em,Ctq:()=>GU,CXw:()=>LU,BEg:()=>Gy,Rz7:()=>Fy,qxp:()=>QC,uts:()=>VC,eW$:()=>qb,eQk:()=>Bb,Qx5:()=>Sy,M3e:()=>qy,oJv:()=>vu,UPX:()=>xu,cbD:()=>va,CiW:()=>xa,WxI:()=>BU,AkX:()=>IU,lW:()=>Nu,$a1:()=>Gu,wT7:()=>CU,a4I:()=>TU,J4c:()=>I_,fCO:()=>P_,nxO:()=>ig,vgA:()=>og,J7F:()=>hU,vZv:()=>gU,HYO:()=>xd,loJ:()=>kd,LAq:()=>yc,x2A:()=>Sc,BlC:()=>qc,Dd7:()=>Bc,cj_:()=>jy,SyP:()=>Hy,_Qn:()=>Jh,UzA:()=>wh,Q1P:()=>XM,kJb:()=>YM,cEg:()=>sp,Aa9:()=>ip,uDD:()=>El,EO4:()=>Cl,azC:()=>dd,cSQ:()=>pd,rhR:()=>zf,RVM:()=>jf,ndP:()=>wj,FRR:()=>yj,gqj:()=>Ss,wER:()=>qs,o0f:()=>iB,mTO:()=>oB,opt:()=>is,ABq:()=>os,hnR:()=>JA,Ld4:()=>wA,ONG:()=>RA,YYN:()=>vA,pj7:()=>mA,rP9:()=>fA,J5_:()=>x$,xQH:()=>k$,Yiy:()=>aF,YY6:()=>uF,mZ$:()=>Mn,WBx:()=>On,iVu:()=>Wn,wuD:()=>Qn,nc6:()=>Yf,Hdd:()=>Zf,aW7:()=>ad,_yh:()=>ud,nG3:()=>Hm,T78:()=>Wm,W5o:()=>NK,c0r:()=>GK,Pzk:()=>ZF,n2r:()=>tK,yqI:()=>_K,YxF:()=>JK,SBx:()=>CE,uDb:()=>TE,XeB:()=>jL,zNr:()=>HL,qtO:()=>Fh,eVU:()=>Kh,pe4:()=>ko,Huq:()=>Eo,tE7:()=>M_,R1c:()=>O_,gwk:()=>iC,CN_:()=>oC,gFI:()=>_C,c7s:()=>JC,shm:()=>VA,_Md:()=>XA,FUz:()=>D$,Z36:()=>N$,CGB:()=>Vk,sHT:()=>Xk,Bz7:()=>Gk,Tfn:()=>Lk,xo6:()=>zU,atP:()=>jU,t1u:()=>ZC,rFi:()=>tT,p9b:()=>Ca,VyS:()=>Ta,lIO:()=>RU,jqE:()=>vU,mA:()=>Lu,U1k:()=>Fu,x4u:()=>$U,FNs:()=>MU,m0x:()=>b_,Cw0:()=>R_,Ch8:()=>wU,uzD:()=>yU,IaO:()=>Ad,WLQ:()=>$d,LME:()=>ZM,rJY:()=>tO,hSg:()=>Jd,rGX:()=>wd,c9k:()=>Vb,gTH:()=>Xb,_mp:()=>tp,sX6:()=>rp,tm2:()=>jE,prK:()=>HE,I5D:()=>BL,e0h:()=>IL,ru_:()=>hF,dyp:()=>gF,jzf:()=>Im,zu1:()=>Pm,D57:()=>hs,llV:()=>gs,KQv:()=>SL,S0I:()=>qL,Xqi:()=>Bx,vXd:()=>Ix,dBq:()=>Jk,VS:()=>wk,sg4:()=>KG,a3K:()=>zG,m_x:()=>TN,EPm:()=>AN,toG:()=>Xc,V$m:()=>Yc,Cul:()=>ib,Y9v:()=>ob,UfC:()=>QI,gJO:()=>VI,jiB:()=>Cn,Z48:()=>Tn,ke0:()=>KK,q1P:()=>zK,RwL:()=>vs,oNu:()=>Bs,hWx:()=>il,dr7:()=>ol,pg$:()=>oU,fSY:()=>aU,gJU:()=>qC,mib:()=>BC,P1T:()=>Zq,VxL:()=>tB,CQB:()=>$s,WQf:()=>Ms,l4W:()=>pb,JZY:()=>hb,Mq$:()=>_b,mTp:()=>Jb,rav:()=>gh,$bx:()=>_h,T1q:()=>YU,RNi:()=>ZU,Nbg:()=>Ai,xel:()=>Mi,Qrr:()=>uy,DfW:()=>PL,lpX:()=>bL,y90:()=>JL,YmN:()=>wL,DrQ:()=>BS,ZhM:()=>IS,Jns:()=>jB,Fkp:()=>HB,meH:()=>KT,ym8:()=>zT,I6A:()=>XP,aBI:()=>YP,JWI:()=>FB,NXG:()=>KB,Nux:()=>OI,hxv:()=>DI,hp9:()=>dA,z7W:()=>pA,qF$:()=>BA,azW:()=>IA,wS2:()=>$T,sWv:()=>MT,sVJ:()=>NT,YHh:()=>GT,lvI:()=>EA,RK5:()=>CA,TOm:()=>UA,tkD:()=>AA,Ioc:()=>GB,GNy:()=>LB,nTs:()=>qI,ZJ6:()=>BI,N8K:()=>iA,RP_:()=>oA,BHX:()=>yP,DLm:()=>SP,zyT:()=>s$,hcJ:()=>i$,SNZ:()=>o$,wEJ:()=>a$,gDx:()=>u$,K6f:()=>l$,dAQ:()=>P$,$sY:()=>b$,Xhp:()=>Ag,JRd:()=>$g,u_0:()=>aS,gHM:()=>uS,V8e:()=>Vq,Pqo:()=>Xq,G24:()=>rA,gNl:()=>nA,ISZ:()=>lJ,yTE:()=>mJ,Hdt:()=>cR,F9z:()=>lR,mPq:()=>qm,i5j:()=>Bm,MjR:()=>Wq,CkD:()=>Qq,yI7:()=>MB,cTj:()=>OB,Dl4:()=>lS,bO3:()=>mS,pmk:()=>uq,LwP:()=>lq,y4P:()=>iL,WY9:()=>oL,irI:()=>_E,GlZ:()=>wE,hst:()=>dj,zUO:()=>pj,aPV:()=>XB,w_Q:()=>YB,LYo:()=>fE,PJy:()=>dE,r$m:()=>g$,ZB$:()=>J$,Upy:()=>Cg,AlS:()=>Ug,hVj:()=>KJ,b$E:()=>zJ,EwF:()=>xN,KhO:()=>EN,i6G:()=>Wg,i0P:()=>Qg,RiQ:()=>eU,XUY:()=>nU,iSm:()=>ws,aUJ:()=>ys,FHO:()=>fb,TpA:()=>db,i20:()=>UP,M7A:()=>AP,y$W:()=>IP,Ik0:()=>PP,Nmm:()=>tU,Xa_:()=>rU,Owv:()=>hI,yq_:()=>gI,kcC:()=>VB,UYU:()=>fI,XT3:()=>oI,HyV:()=>aI,jp5:()=>cs,dpH:()=>ls,Ryr:()=>nb,FPs:()=>sb,YSR:()=>WU,rL_:()=>QU,A9x:()=>Xv,u01:()=>Yv,$7Y:()=>hm,LoC:()=>gm,wcH:()=>GS,cQ7:()=>FS,ovf:()=>Wf,_oI:()=>Qf,_NS:()=>nf,eTm:()=>sf,nxD:()=>Af,Hux:()=>$f,lxC:()=>vf,nxh:()=>xf,SuU:()=>If,yms:()=>Pf,Muw:()=>_z,OFG:()=>Sz,yED:()=>Jz,_2X:()=>wz,jRA:()=>kF,N2o:()=>AF,X26:()=>OF,RhX:()=>EF,VGL:()=>UK,lj2:()=>AK,Vt$:()=>dK,$X0:()=>pK,Il7:()=>qz,SMz:()=>Pz,sLc:()=>xz,CC0:()=>Tz,eNQ:()=>uf,efP:()=>lf,Mly:()=>nK,QJW:()=>sK,dt7:()=>rK,p0o:()=>eK,i$e:()=>bE,StO:()=>RE,CY$:()=>IE,WsC:()=>PE,g6R:()=>$c,oyU:()=>Mc,toQ:()=>XI,P4d:()=>tP,L$Y:()=>HI,ljc:()=>WI,E8o:()=>DN,C17:()=>NN,m8H:()=>cL,G4o:()=>lL,k0s:()=>TL,EGh:()=>UL,XUt:()=>NL,ZU4:()=>GL,CJ0:()=>dL,qZs:()=>pL,WCk:()=>AL,CyC:()=>$L,ND4:()=>ag,Rkv:()=>cg,_9N:()=>dx,wet:()=>px,PG$:()=>nk,bBu:()=>sk,a3w:()=>rk,eZU:()=>ek,MFi:()=>Wx,C0g:()=>Qx,xGO:()=>Sx,zOq:()=>qx,v5z:()=>Gx,HMD:()=>Lx,X8g:()=>eL,p_E:()=>sL,fZH:()=>Qv,hBo:()=>Vv,pUz:()=>EG,hHr:()=>CG,Ewt:()=>Us,S7I:()=>As,BF8:()=>Bg,t__:()=>Ig,_GX:()=>Iq,Q50:()=>Pq,vDB:()=>_x,bIf:()=>Jx,iaP:()=>DB,KuC:()=>NB,yO3:()=>kc,Si_:()=>Ec,Udp:()=>Lv,_am:()=>jv,NEG:()=>Qh,dtn:()=>Vh,q$3:()=>cG,mht:()=>lG,ubJ:()=>yE,DXb:()=>jc,D42:()=>Wc,BHf:()=>ea,lqZ:()=>na,dIX:()=>Ib,fIK:()=>Pb,GoS:()=>Sv,O8k:()=>Bv,jIe:()=>KR,JEj:()=>zR,Yeg:()=>Ry,eBq:()=>xy,iS1:()=>_v,_ax:()=>Jv,QOh:()=>Lo,qbQ:()=>Fo,ZKL:()=>Co,f43:()=>To,nQH:()=>So,rd8:()=>qo,M89:()=>Oo,qlA:()=>Do,wH4:()=>Jo,uwp:()=>wo,bPz:()=>ma,H0j:()=>fa,H8G:()=>jo,rt0:()=>Ho,f5k:()=>go,ZJV:()=>_o,UvC:()=>au,SkP:()=>uu,lN3:()=>Ys,vBH:()=>Zs,cF_:()=>Qs,SY0:()=>Vs,bXT:()=>wi,TQ7:()=>yi,YtZ:()=>pu,UZr:()=>hu,Twg:()=>NR,$H2:()=>GR,Vie:()=>jz,vsf:()=>Hz,Ok7:()=>Vz,Ajm:()=>Yz,ZPB:()=>iv,vfT:()=>ov,C61:()=>Gg,_J0:()=>co,OBE:()=>lo,Exr:()=>pa,aYg:()=>ha,pPB:()=>dv,DxY:()=>pv,kxz:()=>cv,wFu:()=>lv,_v$:()=>WR,yj0:()=>QR,rgp:()=>mo,xa_:()=>po,q9G:()=>Jq,MQS:()=>wq,EcQ:()=>m_,nd7:()=>f_,pGh:()=>o_,XWY:()=>a_,Ig_:()=>ck,Esv:()=>lk,bo4:()=>hk,twU:()=>gk,JmO:()=>dk,bUD:()=>pk,qWG:()=>pB,YJY:()=>gB,jWS:()=>Gm,J41:()=>Lm,V4G:()=>kS,noV:()=>ES,vVx:()=>nD,fAb:()=>sD,Akd:()=>Ic,i7t:()=>Pc,kSp:()=>rD,O5b:()=>eD,TXH:()=>T_,P_k:()=>U_,dwF:()=>QO,t5n:()=>VO,aE$:()=>zA,OCF:()=>HA,ROu:()=>F$,xfP:()=>K$,Xoe:()=>Wl,ZoZ:()=>Ql,Vqj:()=>Vl,pty:()=>Xl,xGV:()=>tL,$EH:()=>rL,bT6:()=>e_,D2n:()=>n_,Gch:()=>t_,gBX:()=>r_,Xdv:()=>bR,hzd:()=>RR,LM4:()=>VU,hcQ:()=>XU,qc8:()=>tJ,Mtj:()=>rJ,n$I:()=>Dg,fMg:()=>Ng,l9M:()=>WE,nPZ:()=>XE,Lys:()=>tI,VS9:()=>rI,tJ9:()=>nI,lIF:()=>sI,ZPw:()=>PI,ZOX:()=>bI,f_r:()=>vR,bJx:()=>xR,JF:()=>FA,B2G:()=>KA,MyJ:()=>A$,mvz:()=>$$,u_Q:()=>xg,WsA:()=>kg,BaG:()=>mO,zYR:()=>fO,eOv:()=>jk,gpX:()=>Hk,St:()=>jl,QKj:()=>Hl,aew:()=>Ck,gjm:()=>Tk,lym:()=>Yl,ddf:()=>Zl,hE5:()=>Mk,LGY:()=>Ok,tcG:()=>Kl,no:()=>zl,YAE:()=>Dl,YyD:()=>Gl,e0r:()=>yk,ewI:()=>Sk,zEV:()=>Lc,pig:()=>Fc,_$o:()=>Mg,Opj:()=>Og,Din:()=>Xd,BMV:()=>Yd,Byz:()=>D_,V5U:()=>Hw,FFq:()=>Wy,LLA:()=>Qy,TdK:()=>Cu,v6H:()=>Tu,CNw:()=>kM,iR7:()=>EM,kfB:()=>UM,iwy:()=>AM,OmT:()=>IM,GoT:()=>PM,fQ:()=>KM,bNb:()=>zM,LRN:()=>$C,Lg7:()=>OC,XDt:()=>DU,lzR:()=>NU,qjo:()=>dl,M_:()=>pl,LWe:()=>aT,F8Y:()=>uT,mD_:()=>iT,wGo:()=>oT,n$w:()=>HC,R9K:()=>WC,ZvO:()=>mw,bhm:()=>fw,yk8:()=>sP,ecN:()=>iP,Mx4:()=>Va,gDX:()=>Xa,bK1:()=>Na,bJ:()=>Ga,J67:()=>ba,VBR:()=>Ra,s$M:()=>ja,MJ:()=>Ha,UQh:()=>Ba,cUB:()=>Ia,vdM:()=>SU,Xu9:()=>qU,DWT:()=>Mz,hSD:()=>Oz,hu7:()=>Iu,BPt:()=>Pu,JbB:()=>Sa,nrv:()=>qa,MrA:()=>Jc,gJp:()=>wc,$kg:()=>kU,PtB:()=>EU,_CN:()=>_g,Kww:()=>Jg,TB_:()=>ST,nE8:()=>qT,lax:()=>xT,rM7:()=>TT,Y44:()=>nu,kE_:()=>su,C4p:()=>im,gRj:()=>om,h1G:()=>vm,doQ:()=>xm,Pxo:()=>Ds,RR2:()=>Ns,v8R:()=>vw,dsv:()=>xw,Obu:()=>pg,S5H:()=>gg,jcw:()=>ZO,X5_:()=>tD,Imd:()=>tm,QI7:()=>sm,XRZ:()=>My,pv1:()=>Oy,NES:()=>N_,Fj9:()=>G_,ax8:()=>_N,_lt:()=>JN,LGu:()=>lN,PnF:()=>mN,i9d:()=>fN,sev:()=>pN,FcH:()=>Sl,$qn:()=>ql,lKh:()=>ju,rsP:()=>Hu,VNQ:()=>Zz,NYc:()=>tj,aJE:()=>yM,SRO:()=>SM,H1L:()=>oM,P8_:()=>aM,K$9:()=>NM,yVw:()=>GM,hUh:()=>Yy,dZ5:()=>Zy,DVl:()=>bv,V$7:()=>Rv,aYW:()=>y_,k1F:()=>S_,EwB:()=>Fd,Eav:()=>zd,yds:()=>dU,KZ$:()=>pU,Uto:()=>nl,EHd:()=>sl,e6P:()=>_B,SuY:()=>JB,Y$T:()=>mB,o35:()=>dB,LWu:()=>gM,fZU:()=>_M,_b6:()=>z$,yTb:()=>j$,FO$:()=>NG,hFv:()=>GG,WjG:()=>eM,OBF:()=>nM,$Sc:()=>aB,R2E:()=>cB,WsN:()=>YR,Afl:()=>ZR,ScF:()=>ev,rcf:()=>Wu,Jcx:()=>Qu,EZo:()=>tl,m0q:()=>rl,SK5:()=>rB,I9h:()=>eB,yIy:()=>Py,C2K:()=>by,nDb:()=>Vg,n8L:()=>Xg,qhH:()=>Aq,I_D:()=>Oq,S9t:()=>Dq,_ty:()=>Fq,_V:()=>rP,KLX:()=>eP,dcL:()=>Vy,n24:()=>Xy,V2d:()=>Os,NjL:()=>Ks,b4u:()=>Rl,$H_:()=>vl,KoG:()=>gR,mWk:()=>_R,mH6:()=>FO,CZF:()=>KO,Mq:()=>pP,M2w:()=>hP,Jjk:()=>JP,$DS:()=>wP,SC5:()=>AD,_kg:()=>$D,c$y:()=>fM,cHR:()=>dM,hsE:()=>XO,vuk:()=>YO,hD2:()=>Tl,ZoF:()=>$l,yq2:()=>Mx,$TS:()=>Px,$0p:()=>bx,jq0:()=>wB,f1t:()=>PB,WAE:()=>Ty,qSX:()=>Ay,DLp:()=>Kg,R$$:()=>zg,i24:()=>Vt,Pt$:()=>Bj,Tmx:()=>Ij,UEe:()=>vL,I67:()=>xL,hvD:()=>JI,p84:()=>wI,q0X:()=>pc,Rq9:()=>sr,lgO:()=>oy,NNb:()=>VS,Zm8:()=>XS,B5B:()=>YS,bh8:()=>ZS,Jjf:()=>SN,hsS:()=>IN,Bi3:()=>nN,jsr:()=>sN,WCl:()=>WS,GYE:()=>QS,p$r:()=>aE,Jag:()=>uE,vfb:()=>cE,$8m:()=>lE,HxK:()=>Yk,jAL:()=>Zk,E2N:()=>lg,iX6:()=>mg,Uao:()=>mL,Gdv:()=>fL,DWb:()=>WL,Fi2:()=>QL,AkD:()=>HD,w2N:()=>WD,PuH:()=>VG,n1r:()=>XG,pVr:()=>kj,jNM:()=>Ej,upR:()=>_j,U2t:()=>Jj,aul:()=>tg,c$T:()=>eg,$F$:()=>Yu,dnq:()=>Zu,Q3t:()=>Yn,Oef:()=>Zn,hHX:()=>mR,D7O:()=>fR,Ezc:()=>dm,cDB:()=>pm,gNW:()=>ym,SuV:()=>Sm,UkG:()=>nh,S$9:()=>ih,CCH:()=>cj,EdW:()=>lj,bHh:()=>sF,jWD:()=>oF,mbE:()=>rF,y5v:()=>nF,KHx:()=>zP,GPC:()=>jP,LdP:()=>xP,l1H:()=>kP,Hrn:()=>HP,pxf:()=>WP,CXL:()=>DP,ybH:()=>NP,k6E:()=>Un,a$2:()=>An,gvC:()=>Gn,WaG:()=>Ln,OOr:()=>Tf,iwb:()=>Uf,cl3:()=>rd,cf9:()=>ed,yeW:()=>SF,ANW:()=>qF,V5S:()=>Fm,lc$:()=>Km,Zav:()=>TF,DyZ:()=>UF,rih:()=>vF,dKG:()=>xF,FFN:()=>zF,dO8:()=>jF,RAf:()=>XK,nYQ:()=>YK,Q_u:()=>QK,Sj7:()=>VK,a_n:()=>CK,g$E:()=>TK,ned:()=>WF,R6h:()=>QF,udh:()=>mK,ahg:()=>fK,flG:()=>cz,fMA:()=>lz,_Yf:()=>gf,g9i:()=>_f,dU3:()=>df,pxp:()=>pf,Vg9:()=>yf,xXb:()=>Sf,AB7:()=>$N,g7m:()=>ON,yMo:()=>Rc,G8V:()=>xc,WXZ:()=>oR,YeS:()=>uR,LuE:()=>gL,VG3:()=>_L,KaV:()=>VL,ySt:()=>XL,ZMX:()=>xO,vEP:()=>kO,iPX:()=>iG,A8F:()=>oG,Cl5:()=>mp,UEj:()=>fp,NsN:()=>Wp,wLf:()=>uO,Sot:()=>cO,_2n:()=>Th,WAf:()=>Uh,bC9:()=>Rd,Xtv:()=>vd,UTl:()=>dC,i4X:()=>pC,rq6:()=>oi,dSe:()=>ai,AUt:()=>jp,Y1Y:()=>Si,G2s:()=>qi,jrM:()=>kv,quH:()=>Pk,eK8:()=>bk,YNI:()=>no,yaP:()=>so,Z_i:()=>dR,jiy:()=>hR,_YH:()=>yS,_i_:()=>qS,nMU:()=>TO,lqq:()=>UO,zdO:()=>HK,HwU:()=>WK,ERl:()=>Cv,Dxu:()=>ZE,LM8:()=>tC,lmw:()=>uC,na4:()=>cC,OWn:()=>mC,c3u:()=>fC,A_u:()=>Pj,IWi:()=>bj,v0n:()=>rh,X1$:()=>eh,xos:()=>WA,xTz:()=>QA,R28:()=>M$,nMz:()=>O$,vV7:()=>qk,vcR:()=>Ik,iHk:()=>oO,gsv:()=>aO,N8I:()=>kk,pZm:()=>Ek,W22:()=>YN,SwX:()=>rG,dMs:()=>Mm,Tsf:()=>Om,l2q:()=>Cj,Lsm:()=>Tj,pbO:()=>CM,xim:()=>TM,$_i:()=>hN,B0l:()=>gN,F70:()=>kp,$bL:()=>Ep,CAc:()=>Ky,GYk:()=>zy,qC3:()=>yb,wHV:()=>Sb,DEE:()=>Uu,xUt:()=>Au,nsd:()=>$u,xYI:()=>Mu,QE:()=>Ou,gsU:()=>Du,sbK:()=>Cb,ofK:()=>Ub,$WS:()=>xb,Rc0:()=>Eb,ryS:()=>jb,rV_:()=>Hb,Ifk:()=>Kp,E7o:()=>Db,MLT:()=>Nb,IJt:()=>GN,pNK:()=>LN,P0D:()=>Ev,SMM:()=>Ed,AhK:()=>Cd,rd_:()=>ph,rkz:()=>hh,kCx:()=>gS,izO:()=>_S,esR:()=>F_,eiD:()=>K_,QBt:()=>_F,SQ3:()=>JF,wfW:()=>QM,UB9:()=>VM,juR:()=>up,ZCs:()=>cp,P_7:()=>e$,H1r:()=>n$,OHt:()=>rN,UgB:()=>eN,R_i:()=>Ox,hN$:()=>Nx,_Br:()=>yd,ylO:()=>Sd,ruw:()=>md,xAe:()=>fd,DJN:()=>Aj,X4T:()=>$j,WEP:()=>ew,odJ:()=>tr,Not:()=>eE,T0x:()=>sE,HOD:()=>tE,pQL:()=>rE,ptC:()=>YA,$bK:()=>ZA,YUq:()=>Uj,JLr:()=>tt,mne:()=>BN,Vsr:()=>Z,eJC:()=>_c,SAH:()=>di,mOD:()=>pi,tE_:()=>at,E3$:()=>rb,MPB:()=>eb,LIs:()=>GC,lW1:()=>LC,kiI:()=>Bi,gqE:()=>Ii,WWi:()=>IR,U5k:()=>PR,_mX:()=>Qt,anf:()=>yC,WJW:()=>SC,P4:()=>bC,HdK:()=>RC,wfI:()=>ir,ggh:()=>SD,nXe:()=>BD,VWM:()=>ID,HiH:()=>PD,k_1:()=>PO,vwy:()=>eG,FMO:()=>hi,PUH:()=>_i,xYM:()=>wl,uif:()=>Bn,EJq:()=>bn,jPV:()=>kn,lP:()=>En,OeX:()=>LE,Wow:()=>zE,Q66:()=>MD,b48:()=>OD,CrG:()=>Xi,YQr:()=>Yi,dOz:()=>kD,smL:()=>xD,qkO:()=>_D,YPJ:()=>JD,sDp:()=>cb,Uj4:()=>mb,QL_:()=>EO,iMY:()=>CO,VF8:()=>sU,Djf:()=>iU,ziV:()=>YT,lme:()=>ZT,J_n:()=>JS,BLE:()=>wS,TGZ:()=>m$,d6S:()=>f$,YDo:()=>hG,cBR:()=>gG,H1p:()=>ds,DUo:()=>ps,Dxc:()=>wG,ZHm:()=>SG,hEC:()=>bh,XUz:()=>Rh,BRM:()=>_G,loc:()=>JG,h$Z:()=>az,lWu:()=>uz,WZo:()=>ZD,oGE:()=>tN,RJA:()=>Gf,$ph:()=>Lf,GsS:()=>iz,YjQ:()=>oz,im6:()=>$E,SSe:()=>ME,Bqo:()=>dG,PQd:()=>pG,mig:()=>Sg,sX9:()=>qg,xQP:()=>ua,TGX:()=>ca,dSX:()=>Ja,nS1:()=>wa,SFI:()=>mi,sw6:()=>zD,qVu:()=>jD,rLu:()=>Ri,Puo:()=>vi,MEU:()=>k_,U0s:()=>E_,rA4:()=>$a,lER:()=>Ma,X6C:()=>Gz,$Fl:()=>Lz,k5b:()=>E$,icQ:()=>C$,Bwq:()=>Cw,nUL:()=>Tw,JrS:()=>nO,HJo:()=>sO,Y6P:()=>ta,QeE:()=>ra,rF_:()=>Yo,DmQ:()=>Zo,be7:()=>ku,THz:()=>Eu,Y53:()=>Fb,Ip9:()=>Kb,ePV:()=>$o,EuD:()=>Mo,L2q:()=>lM,Jiu:()=>mM,I3c:()=>Ka,Qnc:()=>za,_dj:()=>UT,Mob:()=>AT,lpG:()=>uP,LlT:()=>lP,WvV:()=>nG,UgI:()=>sG,OaX:()=>oJ,MX_:()=>aJ,Eg0:()=>KS,c6S:()=>jS,ovZ:()=>sa,gdR:()=>ia,HCf:()=>Sj,x6X:()=>qj,X58:()=>ng,tXQ:()=>sg,AU3:()=>lc,keR:()=>mc,Eh$:()=>kL,aIo:()=>EL,H5R:()=>WT,Tcn:()=>QT,Rig:()=>yI,neC:()=>SI,$lB:()=>SK,XSC:()=>qK,Gci:()=>pp,K_N:()=>hp,ElN:()=>Qp,W6d:()=>Pd,G0c:()=>bd,fOQ:()=>Hp,CdP:()=>Av,lvC:()=>Mv,yYY:()=>uh,w$r:()=>ch,$qF:()=>FD,JUz:()=>KD,_Rg:()=>Um,ubM:()=>Am,yKm:()=>Rb,mmN:()=>vb,kwX:()=>Ab,WRC:()=>Mb,vDi:()=>zp,BaU:()=>Gb,tRU:()=>Lb,Apo:()=>$v,VDS:()=>kh,nRh:()=>Eh,g7r:()=>vh,A7H:()=>xh,kUF:()=>Ih,OV9:()=>Ph,GOY:()=>op,yQR:()=>ap,Z$K:()=>VT,FOE:()=>XT,QAx:()=>Oj,_Hq:()=>Dj,eor:()=>jn,oTi:()=>Hn,pTw:()=>Zm,DZc:()=>tf,wid:()=>Dh,MwB:()=>Nh,OCy:()=>Gd,sJP:()=>Ld,Rbl:()=>lh,t8U:()=>mh,B8P:()=>PT,HQR:()=>bT,Ebu:()=>d$,E7l:()=>p$,rb7:()=>xA,DkK:()=>kA,SDZ:()=>nr,JE6:()=>nw,h0i:()=>Xt,faf:()=>Wt,XRd:()=>$M,joE:()=>MM,v35:()=>jG,pdK:()=>WG,C4E:()=>vp,ya8:()=>xp,PBS:()=>dq,JZ6:()=>gq,EiN:()=>RS,e0Y:()=>vS,e5r:()=>pO,C3d:()=>hO,ZKX:()=>u_,tZb:()=>c_,cn:()=>am,YBJ:()=>um,Naf:()=>cm,pF$:()=>lm,wQX:()=>eq,izm:()=>iq,SAF:()=>Lg,Ix8:()=>Fg,uKx:()=>w$,_w7:()=>y$,V6X:()=>EP,tJA:()=>CP,YBO:()=>GP,Soi:()=>LP,Rns:()=>Kn,PFp:()=>zn,AB3:()=>Zv,IXm:()=>tx,dhe:()=>Ff,PjD:()=>Kf,RDD:()=>Xm,lmF:()=>Ym,$ZN:()=>hc,NtP:()=>gc,iiN:()=>Rz,Qdp:()=>vz,S8y:()=>Uz,QjN:()=>Az,yL5:()=>Oc,se9:()=>Dc,B$8:()=>aL,JgL:()=>uL,xHb:()=>xG,fxk:()=>kG,Ldy:()=>bq,BDC:()=>Rq,ak0:()=>wx,YrR:()=>yx,sy:()=>Gh,uV:()=>Lh,yWy:()=>Qc,as5:()=>Vc,v_8:()=>jR,VgQ:()=>HR,bpP:()=>ci,xBJ:()=>Oi,jFq:()=>Di,NW8:()=>Pi,tP0:()=>bi,$VK:()=>qu,tfN:()=>Bu,xO$:()=>OR,b07:()=>DR,zYy:()=>LR,dwD:()=>FR,yjV:()=>VR,c4k:()=>XR,CLT:()=>yq,q5s:()=>Sq,rhB:()=>nj,p5Q:()=>sj,bkm:()=>kR,Vau:()=>ER,gNG:()=>Rj,QNN:()=>vj,WKP:()=>Ml,mys:()=>Ol,GLj:()=>ij,deZ:()=>oj,dn0:()=>Wk,P7l:()=>Qk,LMY:()=>Kc,LLB:()=>zc,JQv:()=>kw,LQe:()=>Ew,rJW:()=>UG,G_8:()=>AG,RZJ:()=>$G,sst:()=>MG,Kfp:()=>QG,kMn:()=>RG,YOY:()=>vG,npU:()=>Nv,PGd:()=>Gv,HOq:()=>$R,xEn:()=>MR,$ty:()=>Bl,VN6:()=>Il,HeY:()=>iS,V_5:()=>oS,kau:()=>LG,YMP:()=>FG,O8H:()=>tv,wDw:()=>rv,WUm:()=>nv,IHq:()=>By,qks:()=>Iy,DEp:()=>qh,zBo:()=>Bh,ZU_:()=>Yg,X8H:()=>Zg,tol:()=>Ls,b0C:()=>Fs,H16:()=>CR,Tw9:()=>TR,lEN:()=>UR,Z1Y:()=>AR,hk4:()=>Ov,ZpC:()=>Dv,h3x:()=>xl,D9s:()=>kl,eWf:()=>JR,Wig:()=>wR,w9j:()=>Vn,c1o:()=>Xn,MS0:()=>Dn,k09:()=>Nn,tE3:()=>GA,lL7:()=>LA,kHo:()=>T$,QhI:()=>U$,jOB:()=>qR,dGI:()=>BR,yY2:()=>Lp,Ja4:()=>Np,ogM:()=>Gp,vxR:()=>$p,bOn:()=>Mp,S2v:()=>Tp,w9I:()=>Up,MGn:()=>Op,ISK:()=>Dp,NS4:()=>$I,xx6:()=>MI,piC:()=>Ti,T_o:()=>Ui,tVV:()=>cF,zHj:()=>lF,sGA:()=>mD,MmU:()=>fD,PZt:()=>Wd,tJL:()=>Qd,ptw:()=>Rx,zlM:()=>vx,h5c:()=>kC,b9h:()=>EC,vCC:()=>QD,D7h:()=>VD,zuj:()=>CC,NMG:()=>TC,qKw:()=>Fz,SmK:()=>Ku,kjp:()=>zu,L7H:()=>Tq,jGg:()=>Uq,ZrD:()=>as,ffl:()=>us,Xvt:()=>ot,cxP:()=>tu,acM:()=>it,bZb:()=>sv,ybE:()=>rT,YiF:()=>eT,bQB:()=>Hv,Z6E:()=>Wv,hDl:()=>Ax,hWK:()=>$x,UHP:()=>ab,UBK:()=>ub,m:()=>RN,E3F:()=>vN,w66:()=>aN,Mmr:()=>uN,ceB:()=>ZL,WXO:()=>tF,nun:()=>YG,bzo:()=>ZG,h0F:()=>Rk,dTt:()=>vk,GTA:()=>Tx,ev7:()=>Ux,VJo:()=>wD,ZuH:()=>yD,CNn:()=>NI,QOJ:()=>FI,zYv:()=>fc,FmW:()=>dc,KEO:()=>mF,qA0:()=>pF,fKS:()=>rs,tkR:()=>ss,dj5:()=>jT,PFI:()=>HT,hSh:()=>ZP,P8G:()=>tb,BIT:()=>gA,Xmf:()=>_A,UBx:()=>PA,ead:()=>bA,NQP:()=>LT,LK4:()=>FT,rtb:()=>cA,v0c:()=>lA,QWx:()=>qP,Qsl:()=>BP,YG:()=>R$,uNt:()=>v$,PvX:()=>fJ,JPA:()=>dJ,kFu:()=>pE,Mpk:()=>hE,rjZ:()=>_s,FFm:()=>Js,DWR:()=>QP,pGw:()=>VP,zuZ:()=>$P,Dfi:()=>MP,DrI:()=>bP,BRX:()=>RP,J9i:()=>CI,T1W:()=>TI,hxG:()=>UI,Lre:()=>AI,NZ_:()=>kI,l8$:()=>EI,XKz:()=>of,H7s:()=>af,uuc:()=>Df,eo$:()=>Nf,wOq:()=>id,M2G:()=>od,GKl:()=>kf,GIW:()=>Ef,rCL:()=>bf,nbk:()=>Rf,laE:()=>Qm,TCm:()=>Vm,X0z:()=>nz,zxO:()=>sz,kZD:()=>OK,U$g:()=>DK,F5S:()=>XF,PTw:()=>YF,gSd:()=>hK,Egt:()=>gK,$yS:()=>cf,XrM:()=>mf,Eh9:()=>kE,wrT:()=>EE,zFs:()=>KL,bQQ:()=>zL,Fuf:()=>ML,HCj:()=>OL,tJW:()=>Yx,RYJ:()=>Zx,$H8:()=>Vx,XMd:()=>Xx,UJO:()=>mG,Cel:()=>fG,yoo:()=>Mh,fzp:()=>Oh,fS9:()=>Iv,EvY:()=>Pv,b3B:()=>wv,vym:()=>yv,DtR:()=>Ko,dDc:()=>zo,Cwp:()=>Uo,_i8:()=>Ao,rj1:()=>Bo,jWT:()=>Io,$bH:()=>No,nCl:()=>Go,Bhj:()=>vo,LBR:()=>xo,Yir:()=>Wo,GDG:()=>Qo,DqU:()=>Ki,X99:()=>zi,BDH:()=>fi,XwO:()=>ui,vvr:()=>cu,J3N:()=>lu,Tjf:()=>Wz,eWF:()=>Qz,AL:()=>av,EDv:()=>uv,SC0:()=>Ni,kz1:()=>Gi,aam:()=>hv,AF:()=>gv,pmc:()=>mv,PW:()=>fv,Dmk:()=>ji,RAD:()=>Hi,$ht:()=>wg,BrS:()=>yg,Spq:()=>nC,YCH:()=>sC,pNh:()=>KI,vTx:()=>jI,RZf:()=>jd,d6k:()=>Hd,Fo6:()=>oh,rA8:()=>ah,NPW:()=>G$,JAL:()=>L$,xcI:()=>Fk,hbx:()=>Kk,HFD:()=>Ll,Fr4:()=>Fl,F5_:()=>Uk,Lt9:()=>Ak,sCz:()=>cy,aP5:()=>ly,da6:()=>RM,zwl:()=>vM,QRZ:()=>jM,Iz5:()=>HM,sNl:()=>DC,Mlf:()=>NC,XQ_:()=>FU,DZr:()=>KU,UvX:()=>cT,G8P:()=>lT,LJ3:()=>XC,Hen:()=>YC,CoZ:()=>ax,YZV:()=>ux,bLK:()=>dw,YbK:()=>pw,gPk:()=>wy,wZY:()=>yy,yog:()=>fg,K_o:()=>dg,dXc:()=>Ya,zF8:()=>Za,KTu:()=>La,_$O:()=>Fa,jG:()=>Oa,jFj:()=>Da,pbs:()=>Wa,PD$:()=>Qa,NS0:()=>ka,JL8:()=>Ea,dpZ:()=>PU,Lxb:()=>bU,Gor:()=>bu,WWO:()=>Ru,TeW:()=>UU,$lk:()=>AU,Hdl:()=>ix,hHL:()=>ox,qJd:()=>BT,IIB:()=>IT,vq0:()=>iu,npe:()=>ou,cCB:()=>Yb,mFP:()=>Zb,Lr1:()=>my,Bpu:()=>fy,i_X:()=>Ow,wBS:()=>Dw,moj:()=>Nw,k3$:()=>Gw,Vpq:()=>PG,vfz:()=>bG,WFw:()=>TD,gqu:()=>UD,tdz:()=>dy,N4Y:()=>py,l5I:()=>rx,FsH:()=>ex,AKO:()=>Dy,C7S:()=>Ny,YgU:()=>cx,G3W:()=>lx,izj:()=>hy,Qul:()=>gy,hLv:()=>wN,VCH:()=>yN,iRP:()=>PN,y13:()=>bN,es2:()=>vC,CKk:()=>xC,Ozh:()=>rj,wcT:()=>ej,xvP:()=>qM,nhk:()=>BM,omy:()=>uM,wgB:()=>cM,VIg:()=>LM,lxh:()=>FM,ORt:()=>vv,yL9:()=>xv,gez:()=>sJ,MYI:()=>iJ,qEG:()=>_U,CMB:()=>JU,zul:()=>mx,L5U:()=>fx,Ca8:()=>Dd,m6C:()=>Nd,iXm:()=>JM,k8Q:()=>wM,TIw:()=>H$,rRJ:()=>W$,Xtc:()=>sM,bIg:()=>iM,WL_:()=>_y,SPf:()=>Jy,Ebf:()=>yh,Huz:()=>Sh,D3G:()=>rO,rew:()=>eO,Vry:()=>jJ,nNe:()=>HJ,bjc:()=>tR,lLB:()=>rR,__V:()=>iN,c3q:()=>oN,hLX:()=>sR,lYk:()=>iR,LjR:()=>zO,Hoz:()=>jO,G6u:()=>eJ,_E_:()=>nJ,ZVF:()=>pM,zri:()=>hM,dR6:()=>gd,P1K:()=>_d,bBp:()=>jg,rk2:()=>Hg,fRF:()=>Vf,TkS:()=>Xf,P1X:()=>zh,VxX:()=>jh,Jt2:()=>Li,Fmo:()=>Fi,DLo:()=>nx,zQx:()=>sx,J3_:()=>eR,jzZ:()=>nR,Z8m:()=>nB,VbN:()=>sB,Ll_:()=>MS,rKG:()=>OS,rG0:()=>DS,lWs:()=>NS,sRz:()=>yR,mEf:()=>SR,_P7:()=>wF});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/aiserver/v1/privacy_mode_pb.js"),i=e("../proto/dist/generated/aiserver/v1/usage_pb.js"),o=e("../proto/dist/generated/aiserver/v1/utils_pb.js"),a=e("../proto/dist/runtime/compact.js");const u="aiserver.v1.";class c extends a.HL{static get runtime(){return(0,a.kU)(this,"runtime",n.proto3)}static $p(){return u}}class l extends c{constructor(t){super(),this.sessionId="",this.type=m.UNSPECIFIED,this.createdAt="",this.expiresAt="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["Session|1 session_id 9|2 type #0|3 created_at 9|4 expires_at 9",m]}}var m=(0,a.QT)(n.proto3,u,"Session.SessionType",[[0,"UNSPECIFIED"],[1,"WEB"],[2,"CLIENT"],[3,"BUGBOT"],[4,"BACKGROUND_AGENT"],[5,"SUPPORT_IMPERSONATION"],[6,"API_KEY_TOKEN"],[7,"TRAINING"],[8,"EXEC_DAEMON"],[9,"GRAPHITE"],[10,"MOBILE"],[11,"SAND_MOBILE"]],1);n.proto3,n.proto3,n.proto3;class f extends a.HL{static get runtime(){return(0,a.kU)(this,"runtime",n.proto3)}static $p(){return"aiserver.v1."}}class d extends f{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["RemoteControlV2AdminSettings|1 enabled 8?|2 automatic_registration_enabled 8?"]}}class p extends f{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["RemoteControlV2Policy|1 enabled 8?|2 automatic_registration_enabled 8?|3 available 8?|4 automatic_registration_released 8?|5 remote_control_denying_org_name 9?|6 automatic_registration_denying_org_name 9?"]}}var h=e("../proto/dist/generated/agent/v1/requested_model_pb.js");a.HL;var g=(0,a.QT)(n.proto3,"aiserver.v1.","FullSelfDrivingMode",[[0,"UNSPECIFIED"],[1,"SUGGEST"],[2,"APPLY"]],1);n.proto3,n.proto3;var _=e("../proto/dist/generated/aiserver/v1/chat_pb.js");class J extends a.HL{static get runtime(){return(0,a.kU)(this,"runtime",n.proto3)}static $p(){return"aiserver.v1."}}class w extends J{constructor(t){super(),this.name="",this.sha256="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new w).fromBinary(t,r)}static fromJson(t,r){return(new w).fromJson(t,r)}static fromJsonString(t,r){return(new w).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(w,t,r)}static $(){return["CanvasVisualizationRuntimePin|1 name 9|2 sha256 9"]}}const y="aiserver.v1.";class S extends a.HL{static get runtime(){return(0,a.kU)(this,"runtime",n.proto3)}static $p(){return y}}var q=(0,a.QT)(n.proto3,y,"AppSecretState",[[0,"UNSPECIFIED"],[1,"REQUESTED"],[2,"SET"]],1),B=(n.proto3,n.proto3,n.proto3,n.proto3,n.proto3,(0,a.QT)(n.proto3,y,"PublishReviewOverrideState",[[0,"UNSPECIFIED"],[1,"REQUESTED"],[2,"APPROVED"],[3,"DENIED"],[4,"REVOKED"],[5,"EXPIRED"]],1)),I=(n.proto3,(0,a.QT)(n.proto3,y,"AppPublishStatus",[[0,"UNSPECIFIED"],[1,"QUEUED"],[2,"BUILDING"],[3,"READY"],[4,"ERROR"],[5,"CANCELED"]],1)),P=(n.proto3,(0,a.QT)(n.proto3,y,"AppVisibility",[[0,"UNSPECIFIED"],[1,"PRIVATE"],[2,"TEAM"],[3,"PUBLIC"]],1));n.proto3,n.proto3,n.proto3,n.proto3,n.proto3;class b extends S{constructor(t){super(),this.type="",this.version="",this.sha256="",this.markdown="",this.coversTeam=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new b).fromBinary(t,r)}static fromJson(t,r){return(new b).fromJson(t,r)}static fromJsonString(t,r){return(new b).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(b,t,r)}static $(){return["PublishTerms|1 type 9|2 version 9|3 sha256 9|4 markdown 9|5 covers_team 8"]}}class R extends S{constructor(t){super(),this.type="",this.version="",this.sha256="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new R).fromBinary(t,r)}static fromJson(t,r){return(new R).fromJson(t,r)}static fromJsonString(t,r){return(new R).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(R,t,r)}static $(){return["AcceptedPublishTerms|1 type 9|2 version 9|3 sha256 9"]}}class v extends S{constructor(t){super(),this.id="",this.source="",this.category="",this.severity="",this.blocking=!1,this.description="",this.path="",this.line=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new v).fromBinary(t,r)}static fromJson(t,r){return(new v).fromJson(t,r)}static fromJsonString(t,r){return(new v).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(v,t,r)}static $(){return["PublishReviewFinding|1 id 9|2 source 9|3 category 9|4 severity 9|5 blocking 8|6 description 9|7 path 9|8 line 5"]}}class x extends S{constructor(t){super(),this.reason="",this.disabledAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new x).fromBinary(t,r)}static fromJson(t,r){return(new x).fromJson(t,r)}static fromJsonString(t,r){return(new x).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(x,t,r)}static $(){return["AppDisabledByCursor|1 reason 9|2 disabled_at_ms 3"]}}n.proto3,n.proto3;class k extends S{constructor(t){super(),this.width=0,this.url="",this.contentType="",this.sizeBytes=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new k).fromBinary(t,r)}static fromJson(t,r){return(new k).fromJson(t,r)}static fromJsonString(t,r){return(new k).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(k,t,r)}static $(){return["CanvasAssetPreview|1 width 5|2 url 9|3 content_type 9|4 size_bytes 3"]}}var E=e("../proto/dist/generated/agent/v1/agent_pb.js");const C="aiserver.v1.";class T extends a.HL{static get runtime(){return(0,a.kU)(this,"runtime",n.proto3)}static $p(){return C}}var U=(0,a.QT)(n.proto3,C,"ScmConnectIntentSource",[[0,"UNSPECIFIED"],[1,"PORTAL"],[2,"GLASS_CLOUD_AGENT"],[3,"GLASS_DIFF"],[4,"GLASS_AUTOMATIONS"]],1),A=(0,a.QT)(n.proto3,C,"GitlabReposSyncStatus",[[0,"UNSPECIFIED"],[1,"NOT_FOUND"],[2,"RUNNING"],[3,"COMPLETED"],[4,"FAILED"]],1),$=(0,a.QT)(n.proto3,C,"AccountSectionStatus",[[0,"UNSPECIFIED"],[1,"OK"],[2,"NOT_LINKED"],[3,"UNAVAILABLE"]],1),M=(0,a.QT)(n.proto3,C,"AccountHandoffTarget",[[0,"UNSPECIFIED"],[1,"EMAIL"],[2,"PASSWORD"],[3,"TWO_STEP"],[4,"SIGN_IN_METHODS"]],1),O=(0,a.QT)(n.proto3,C,"UserOrganizationRole",[[0,"UNSPECIFIED"],[1,"ADMIN"],[2,"MEMBER"],[4,"BILLING_ADMIN"]],1),D=(0,a.QT)(n.proto3,C,"OrganizationTeamSettingsCopyCategory",[[0,"UNSPECIFIED"],[1,"MODELS"],[2,"SECURITY"],[3,"RULES_AND_COMMANDS"],[4,"HOOKS"],[5,"MCP_AND_PLUGIN_POLICY"],[6,"SPENDING_LIMITS"],[7,"TEAM_ACCESS_DEFAULTS"],[8,"GROK_BOT"]],1),N=(0,a.QT)(n.proto3,C,"OrganizationTeamSettingsCopyOutcome",[[0,"UNSPECIFIED"],[1,"COPIED"],[2,"EMPTY"],[3,"SKIPPED_BY_POLICY"],[4,"BLOCKED"]],1),G=(0,a.QT)(n.proto3,C,"CreateOrganizationTeamIdentityProviderMode",[[0,"UNSPECIFIED"],[1,"USE_ORGANIZATION"],[2,"CREATE_NEW"]],1),L=(0,a.QT)(n.proto3,C,"XaiTeamMembershipHoldSource",[[0,"UNSPECIFIED"],[1,"MIGRATION"],[2,"OPERATOR_MERGE"],[3,"SCIM"],[4,"SSO"],[5,"AUTO_ENROLL"]],1),F=(0,a.QT)(n.proto3,C,"OrganizationScimSource",[[0,"UNSPECIFIED"],[1,"CURSOR"],[2,"GROK"]],1),K=(0,a.QT)(n.proto3,C,"OrganizationScimSourceResolution",[[0,"UNSPECIFIED"],[1,"EXPLICIT"],[2,"DEFAULT"]],1),z=(0,a.QT)(n.proto3,C,"AnthropicCyberVerificationStatus",[[0,"UNSPECIFIED"],[1,"ACTIVE"],[2,"PENDING"],[3,"REJECTED"]],1),j=(0,a.QT)(n.proto3,C,"AnthropicEfsStatus",[[0,"UNSPECIFIED"],[1,"REQUESTED"],[2,"APPROVED"],[3,"REJECTED"]],1),H=(0,a.QT)(n.proto3,C,"GroupVisibility",[[0,"UNSPECIFIED"],[1,"TEAM_ADMIN"],[2,"TEAM"]],1),W=(0,a.QT)(n.proto3,C,"AnthropicEfsReviewDecision",[[0,"UNSPECIFIED"],[1,"APPROVE"],[2,"REJECT"],[3,"REVOKE"]],1),Q=(0,a.QT)(n.proto3,C,"XaiDataRetention",[[0,"UNSPECIFIED"],[1,"ZDR"],[2,"ZDR_EXCEPT_SOC_AUDIT"],[3,"GENERAL"]],1),V=(0,a.QT)(n.proto3,C,"BackgroundComposerSecretLevel",[[0,"UNSPECIFIED"],[1,"ENVIRONMENT_VARIABLE"],[2,"INJECTED_SECRET"],[3,"BUILD_SECRET"],[4,"HTTP_SECRET"]],1),X=(0,a.QT)(n.proto3,C,"BackgroundComposerSecretHttpScheme",[[0,"UNSPECIFIED"],[1,"BEARER"],[2,"TOKEN"],[3,"BASIC"],[4,"HEADER"]],1),Y=(0,a.QT)(n.proto3,C,"BackgroundComposerSecretSurface",[[0,"UNSPECIFIED"],[1,"CLOUD_AGENT"],[2,"GROK_BOT"],[3,"APP"]],1),Z=(0,a.QT)(n.proto3,C,"McpServerAppliesTo",[[0,"UNSPECIFIED"],[1,"LOCAL_AND_CLOUD"],[2,"LOCAL"],[3,"CLOUD"],[4,"NONE"]],1),tt=(0,a.QT)(n.proto3,C,"McpServedBy",[[0,"UNSPECIFIED"],[1,"CURSOR"],[2,"GROK"]],1),rt=(0,a.QT)(n.proto3,C,"McpSignOutReason",[[0,"UNSPECIFIED"],[1,"EXPIRED"],[2,"REVOKED"],[3,"ORGANIZATION_POLICY"],[4,"MFA_REQUIRED"],[5,"ADMIN_BLOCKED"],[6,"ACCOUNT_DISABLED"],[7,"CLIENT_INVALID"],[8,"ACCOUNT_RESTRICTED"],[9,"PROVIDER_UNAVAILABLE"],[10,"PROVIDER_ERROR"]],1),et=(0,a.QT)(n.proto3,C,"CycleType",[[0,"UNSPECIFIED"],[1,"MONTH"],[2,"START_TIME"]],1),nt=(0,a.QT)(n.proto3,C,"SpendLimitPolicyScope",[[0,"UNSPECIFIED"],[1,"TEAM_TOTAL"],[2,"TEAM_MEMBER_DEFAULT"],[3,"GROUP_MEMBER_DEFAULT"]],1),st=(0,a.QT)(n.proto3,C,"SpendLimitPolicyType",[[0,"UNSPECIFIED"],[1,"NONE"],[2,"HARD"],[3,"SOFT"]],1),it=(0,a.QT)(n.proto3,C,"TeamRole",[[0,"UNSPECIFIED"],[1,"OWNER"],[2,"MEMBER"],[3,"FREE_OWNER"],[4,"REMOVED"]],1),ot=(0,a.QT)(n.proto3,C,"TeamMemberBillingTier",[[0,"UNSPECIFIED"],[1,"TIER_1000"],[2,"TIER_2000"]],1),at=(0,a.QT)(n.proto3,C,"MergedTeamSeatTier",[[0,"UNSPECIFIED"],[1,"FREE"],[2,"PLUS"],[3,"SUPER"],[4,"ULTRA"],[5,"PREMIUM"]],1),ut=(0,a.QT)(n.proto3,C,"TeamBillingSource",[[0,"UNSPECIFIED"],[1,"NONE"],[2,"STRIPE"],[3,"XAI"],[4,"CONTRACT"]],1),ct=(0,a.QT)(n.proto3,C,"PrivateInferenceEnablement",[[0,"UNSPECIFIED"],[1,"ENABLED"],[2,"DISABLED"]],1),lt=(0,a.QT)(n.proto3,C,"PrepaidBillingMode",[[0,"UNSPECIFIED"],[1,"ON_DEMAND"],[2,"PREPAID"]],1),mt=(0,a.QT)(n.proto3,C,"XaiCommerceBearerPurpose",[[0,"UNSPECIFIED"],[1,"BROWSER_COMMERCE"],[2,"PREPAID_TOP_UP"]],1),ft=(0,a.QT)(n.proto3,C,"XaiCommerceBearerTokenSource",[[0,"UNSPECIFIED"],[1,"PARTNER_JWT"],[2,"DEV_OVERRIDE"]],1),dt=(0,a.QT)(n.proto3,C,"XaiCommerceBearerRefusalReason",[[0,"UNSPECIFIED"],[1,"UNAVAILABLE"],[2,"INTERACTIVE_ONLY"],[3,"NOT_CONFIGURED"],[4,"NOT_LINKED"],[5,"RATE_LIMITED"]],1),pt=(0,a.QT)(n.proto3,C,"SlackConnectSource",[[0,"UNSPECIFIED"],[1,"LEGACY_UNKNOWN"],[2,"GLASS_CHECKLIST"],[3,"GLASS_SETTINGS"],[4,"GLASS_AUTOMATIONS"],[5,"IDE_SETTINGS"],[6,"IDE_IN_APP_AD"],[7,"DASHBOARD_INTEGRATIONS"],[8,"DASHBOARD_OVERVIEW"],[9,"DASHBOARD_SETUP_PROGRESS"],[10,"DASHBOARD_CHECKLIST"],[11,"DASHBOARD_AUTOMATIONS"],[12,"DASHBOARD_SLACK_SETTINGS"],[13,"DASHBOARD_SAND_SETUP"],[14,"CLOUD_ENVIRONMENT_ONBOARDING"],[15,"MANAGED_AGENTS"],[16,"REVIEW_SETTINGS"],[17,"SAND_LISTENER"],[18,"EMAIL"],[19,"PUBLIC_INSTALL"],[20,"PUBLIC_INSTALL_USER_SCOPES"],[21,"SLACK_AUTH_PROMPT"],[22,"SLACK_LINK_UNFURL"],[23,"GLASS_UNATTRIBUTED"],[24,"IDE_UNATTRIBUTED"],[25,"WEB_UNATTRIBUTED"],[26,"GROK_BOT_UNATTRIBUTED"]],1),ht=(0,a.QT)(n.proto3,C,"SlackConnectSite",[[0,"UNSPECIFIED"],[1,"CURSOR"],[2,"GROK"]],1),gt=(0,a.QT)(n.proto3,C,"TeamEnterpriseGrantState",[[0,"UNSPECIFIED"],[1,"GRANTED"],[2,"NONE"],[3,"UNAVAILABLE"]],1),_t=(0,a.QT)(n.proto3,C,"ContactImportProvider",[[0,"UNSPECIFIED"],[1,"SLACK"],[2,"GOOGLE"]],1),Jt=(0,a.QT)(n.proto3,C,"ContactImportSyncRunStatus",[[0,"UNSPECIFIED"],[1,"IN_PROGRESS"],[2,"ACTIVE"],[3,"SUPERSEDED"],[4,"FAILED"]],1),wt=(0,a.QT)(n.proto3,C,"GrokAdminOutcome",[[0,"UNSPECIFIED"],[1,"AVAILABLE"],[2,"TEAM_NOT_MERGED"],[3,"ACCOUNT_NOT_LINKED"],[4,"NOT_ADMIN"],[5,"BLOCKED_BY_SECURITY"],[6,"NOT_AVAILABLE"],[7,"UNAVAILABLE"]],1),yt=(0,a.QT)(n.proto3,C,"GrokAdminFeatureControlField",[[0,"UNSPECIFIED"],[1,"ENABLE_FILE_UPLOADS"],[2,"ENABLE_IMAGE_UPLOADS"],[3,"ENABLE_WEB_SEARCH"],[4,"ENABLE_X_SEARCH"],[5,"ENABLE_VOICE_MODE"],[6,"ENABLE_IMAGINE"],[7,"ENABLE_IMAGINE_CHAT"],[8,"ENABLE_GROK_CHAT"],[9,"ENABLE_DICTATION"],[10,"ENABLE_BOTS"]],1),St=(0,a.QT)(n.proto3,C,"GrokUserDataControlsStatus",[[0,"UNSPECIFIED"],[1,"AVAILABLE"],[3,"NOT_LINKED"],[4,"REFUSED"],[5,"NO_ACCESS"],[6,"CURSOR_ONLY_ENTERPRISE"]],1),qt=(0,a.QT)(n.proto3,C,"GrokRequestLogKind",[[0,"UNSPECIFIED"],[1,"CHAT"],[2,"IMAGE"],[3,"VIDEO"]],1),Bt=(0,a.QT)(n.proto3,C,"GrokAdminConversationSharingScope",[[0,"UNSPECIFIED"],[1,"PUBLIC"],[2,"ORGANIZATION"],[3,"TEAM"],[4,"PRIVATE"]],1),It=(0,a.QT)(n.proto3,C,"GrokAdminProjectSharingScope",[[0,"UNSPECIFIED"],[1,"ORGANIZATION"],[2,"TEAM"],[3,"PRIVATE"]],1),Pt=(0,a.QT)(n.proto3,C,"GrokAdminSkillSharingScope",[[0,"UNSPECIFIED"],[1,"ORGANIZATION"],[2,"TEAM"],[3,"PRIVATE"]],1),bt=(0,a.QT)(n.proto3,C,"GrokAdminOrganizationRetentionUpdate",[[0,"UNSPECIFIED"],[1,"SET_DAYS"],[2,"KEEP_FOREVER"],[3,"CLEAR"]],1),Rt=(0,a.QT)(n.proto3,C,"StepUpLinkRefusal",[[0,"UNSPECIFIED"],[1,"WRONG_BROWSER"],[2,"EXPIRED"],[3,"USED"],[4,"REPLACED"]],1),vt=(0,a.QT)(n.proto3,C,"ApiKeyInventoryKind",[[0,"UNSPECIFIED"],[1,"PERSONAL"],[2,"TEAM"],[3,"ORGANIZATION"],[4,"FINE_GRAINED"]],1),xt=(0,a.QT)(n.proto3,C,"StaffActionReason",[[0,"UNSPECIFIED"],[1,"SECURITY_INCIDENT"],[2,"LEAKED_KEY"],[3,"CUSTOMER_REQUEST"],[4,"ABUSE"],[5,"OTHER"]],1),kt=(0,a.QT)(n.proto3,C,"ServiceTokenOwnerType",[[0,"UNSPECIFIED"],[1,"USER"],[2,"TEAM"],[3,"ORGANIZATION"]],1),Et=(0,a.QT)(n.proto3,C,"CursorApiKeyOwner",[[0,"UNSPECIFIED"],[1,"TEAM"],[2,"PERSONAL"]],1),Ct=(0,a.QT)(n.proto3,C,"TrustedIssuerStatus",[[0,"UNSPECIFIED"],[1,"ENABLED"],[2,"DISABLED"],[3,"REVOKED"]],1),Tt=(0,a.QT)(n.proto3,C,"OAuthGrantResourceType",[[0,"UNSPECIFIED"],[1,"PERSONAL_ACCOUNT"],[2,"TEAM"],[3,"ORGANIZATION"]],1),Ut=(0,a.QT)(n.proto3,C,"OAuthGrokBotSource",[[0,"UNSPECIFIED"],[1,"PERSONAL"],[2,"SHARED"],[3,"TEAM"]],1),At=(0,a.QT)(n.proto3,C,"ProtectedGitProvider",[[0,"UNSPECIFIED"],[1,"GITHUB"],[2,"GITLAB"],[3,"GITHUB_ENTERPRISE"],[4,"GITLAB_SELF_HOSTED"],[5,"ORIGIN"],[6,"BITBUCKET"]],1),$t=(0,a.QT)(n.proto3,C,"UnlistedMemberServerKind",[[0,"UNSPECIFIED"],[1,"MARKETPLACE_PLUGIN"],[2,"REMOTE_MCP"],[3,"LOCAL_COMMAND_MCP"]],1),Mt=(0,a.QT)(n.proto3,C,"FirstPartyPluginMode",[[0,"UNSPECIFIED"],[1,"ENABLE_ALL"],[2,"ALLOWLIST"]],1),Ot=(0,a.QT)(n.proto3,C,"AutoCreatePrMode",[[0,"UNSPECIFIED"],[1,"ALWAYS"],[2,"SINGLE"],[3,"NEVER"]],1),Dt=(0,a.QT)(n.proto3,C,"PrReviewOpenDestinationMode",[[0,"UNSPECIFIED"],[1,"GITHUB"],[2,"GRAPHITE"],[3,"REVIEW_CURSOR"]],1),Nt=(0,a.QT)(n.proto3,C,"GithubArtifactPostingMode",[[0,"UNSPECIFIED"],[1,"POST_ARTIFACT"],[2,"LINK_ONLY"]],1),Gt=(0,a.QT)(n.proto3,C,"PublicArtifactSharingMode",[[0,"UNSPECIFIED"],[1,"ALLOWED"],[2,"DISABLED"]],1),Lt=(0,a.QT)(n.proto3,C,"CloudAgentEgressProtectionMode",[[0,"UNSPECIFIED"],[1,"ALLOW_ALL"],[2,"DEFAULT_WITH_NETWORK_SETTINGS"],[3,"NETWORK_SETTINGS_ONLY"],[4,"PARENT_PLUS_NETWORK_SETTINGS"]],1),Ft=(0,a.QT)(n.proto3,C,"TeamFollowupEnabledMode",[[0,"UNSPECIFIED"],[1,"DISABLED"],[2,"SERVICE_ACCOUNTS_ONLY"],[3,"ALL"]],1),Kt=(0,a.QT)(n.proto3,C,"SlackReplyMode",[[0,"UNSPECIFIED"],[1,"FOLLOW_THREADS"],[2,"MENTIONS_ONLY"]],1),zt=(0,a.QT)(n.proto3,C,"PreferredRepoSourceMode",[[0,"UNSPECIFIED"],[1,"GITHUB"],[2,"ORIGIN"]],1),jt=(0,a.QT)(n.proto3,C,"AutomationDefaultVisibility",[[0,"UNSPECIFIED"],[1,"VISIBLE"],[2,"EDITABLE"],[3,"PRIVATE"]],1),Ht=(0,a.QT)(n.proto3,C,"PersonalSecretsPolicy",[[0,"UNSPECIFIED"],[1,"ALLOWED"],[2,"DISABLED"]],1),Wt=(0,a.QT)(n.proto3,C,"SandboxingMode",[[0,"UNSPECIFIED"],[1,"ENABLED"],[2,"DISABLED"],[3,"ENFORCED"]],1),Qt=(0,a.QT)(n.proto3,C,"NetworkingMode",[[0,"UNSPECIFIED"],[1,"USER_CONTROLLED"],[2,"ALWAYS_DISABLED"]],1),Vt=(0,a.QT)(n.proto3,C,"GitMode",[[0,"UNSPECIFIED"],[1,"USER_CONTROLLED"],[2,"ALWAYS_DISABLED"]],1),Xt=(0,a.QT)(n.proto3,C,"SandboxReadBoundaryMode",[[0,"UNSPECIFIED"],[1,"SYSTEM"],[2,"WORKSPACE"],[4,"NONE"]],1),Yt=(0,a.QT)(n.proto3,C,"SlackInboundInstallMode",[[0,"UNSPECIFIED"],[1,"OPEN"],[2,"LOCKED"]],1),Zt=(0,a.QT)(n.proto3,C,"GoogleDriveSharedDrivesMode",[[0,"UNSPECIFIED"],[1,"BLOCK"],[2,"ALLOW_ONLY"]],1),tr=(0,a.QT)(n.proto3,C,"LocalToolPermissionCeiling",[[0,"UNSPECIFIED"],[1,"NEVER"],[2,"ASK"],[3,"ALWAYS"]],1),rr=(0,a.QT)(n.proto3,C,"LocalToolOtherCommandsPolicy",[[0,"UNSPECIFIED"],[1,"ASK"],[2,"BLOCK"]],1),er=(0,a.QT)(n.proto3,C,"SandEgressMode",[[0,"UNSPECIFIED"],[1,"ALLOW_ALL"],[2,"DEFAULT_WITH_NETWORK_SETTINGS"],[3,"NETWORK_SETTINGS_ONLY"]],1),nr=(0,a.QT)(n.proto3,C,"SandLocalEgressMode",[[0,"UNSPECIFIED"],[1,"ALWAYS_ON"],[2,"MEMBER_DECIDES"],[3,"ALWAYS_OFF"]],1),sr=(0,a.QT)(n.proto3,C,"GrokBotTeamBotSharing",[[0,"UNSPECIFIED"],[1,"ALLOWED"],[2,"ADMINS_ONLY"],[3,"DISABLED"],[4,"DESIGNATED"]],1),ir=(0,a.QT)(n.proto3,C,"PagesTeamSharingLevel",[[0,"UNSPECIFIED"],[1,"EVERYONE"],[2,"SPECIFIC_TEAMMATES"],[3,"OFF"]],1),or=(0,a.QT)(n.proto3,C,"LlmGatewayAuthMode",[[0,"UNSPECIFIED"],[1,"JWT_ACCESS"],[2,"CUSTOMER_MANAGED"]],1),ar=(0,a.QT)(n.proto3,C,"LlmGatewayRoutingMode",[[0,"UNSPECIFIED"],[1,"LEGACY"],[2,"MODEL_LIST"],[3,"CUSTOM"]],1),ur=(0,a.QT)(n.proto3,C,"LlmGatewayCredentialSourceStrategy",[[0,"UNSPECIFIED"],[1,"TEAM_CREDENTIAL_ALL_SURFACES"],[2,"CLIENT_LOCAL_TEAM_CLOUD"]],1),cr=(0,a.QT)(n.proto3,C,"LlmGatewayDiscoveryScope",[[0,"UNSPECIFIED"],[1,"ALL_MODELS"],[2,"CATALOG_PLUS_UNPUBLISHED"]],1),lr=(0,a.QT)(n.proto3,C,"SandGroupAccessMode",[[0,"UNSPECIFIED"],[1,"ALL"],[2,"LIMITED"]],1),mr=(0,a.QT)(n.proto3,C,"CloudAgentGroupAccessMode",[[0,"UNSPECIFIED"],[1,"ALL"],[2,"LIMITED"]],1),fr=(0,a.QT)(n.proto3,C,"CursorGroupAccessMode",[[0,"UNSPECIFIED"],[1,"ALL"],[2,"LIMITED"]],1),dr=(0,a.QT)(n.proto3,C,"TrialType",[[0,"UNSPECIFIED"],[1,"REQUEST"],[2,"TOKEN"]],1),pr=(0,a.QT)(n.proto3,C,"FreeTrialCodePurpose",[[0,"UNSPECIFIED"],[1,"FREE_TRIAL"],[2,"ORG_INVITE"]],1),hr=(0,a.QT)(n.proto3,C,"CreditGrantOwnership",[[0,"UNSPECIFIED"],[1,"TEAM"],[2,"ORGANIZATION"]],1),gr=(0,a.QT)(n.proto3,C,"BankedUsageResetKind",[[0,"UNSPECIFIED"],[1,"TEAM"],[2,"USER"]],1),_r=(0,a.QT)(n.proto3,C,"UserAccessRequestKind",[[0,"UNSPECIFIED"],[1,"SAND_TEAM_ACCESS"],[2,"TEAM_JOIN"]],1),Jr=(0,a.QT)(n.proto3,C,"IapVerificationProvenance",[[0,"UNSPECIFIED"],[1,"PURCHASE_RETURN"],[2,"PURCHASE_LISTENER"],[3,"COLD_START"],[4,"FOREGROUND"],[5,"MANUAL_RESTORE"],[6,"AUTH_CHANGE"]],1),wr=(0,a.QT)(n.proto3,C,"RestoreCommerceStorePurchaseOutcome",[[0,"UNSPECIFIED"],[1,"BOUND"],[2,"REFUSED"],[3,"UNAVAILABLE"]],1),yr=(0,a.QT)(n.proto3,C,"GooglePlayInventoryClientState",[[0,"UNSPECIFIED"],[1,"ACTIVE"],[2,"SUSPENDED"],[3,"PENDING"]],1),Sr=(0,a.QT)(n.proto3,C,"GooglePlayInventoryTrigger",[[0,"UNSPECIFIED"],[1,"COLD_START"],[2,"FOREGROUND"],[3,"MANUAL_RESTORE"]],1),qr=(0,a.QT)(n.proto3,C,"TestPushScenario",[[0,"UNSPECIFIED"],[1,"FINISHED_SUCCESS"],[2,"FINISHED_ERROR"],[3,"CUSTOM"],[4,"SAND_AGENT_FINISHED"]],1),Br=(0,a.QT)(n.proto3,C,"TestPushPlatform",[[0,"UNSPECIFIED"],[1,"IOS"],[2,"ANDROID"]],1),Ir=(0,a.QT)(n.proto3,C,"TestPushApp",[[0,"UNSPECIFIED"],[1,"GROK_BUILD_IOS"],[2,"GROK_BUILD_ANDROID"],[3,"GROK_BOT_IOS"],[4,"GROK_BOT_ANDROID"]],1),Pr=(0,a.QT)(n.proto3,C,"LimitHitStage",[[0,"UNSPECIFIED"],[1,"AUTO_SWITCH"],[2,"SLOW_POOL"],[3,"HARD_BLOCK"],[4,"WEEKLY_LIMIT"]],1),br=(0,a.QT)(n.proto3,C,"ProjectsCreditSurface",[[0,"UNSPECIFIED"],[1,"COMPOSER_BANNER"],[2,"SIDEBAR_TAG"]],1),Rr=(0,a.QT)(n.proto3,C,"SeatUpgradePoolDriver",[[0,"UNSPECIFIED"],[1,"FIRST_PARTY"],[2,"THIRD_PARTY"],[3,"BOTH"]],1),vr=(0,a.QT)(n.proto3,C,"XaiTeamPlanChangeOutcome",[[0,"UNSPECIFIED"],[1,"DONE"],[2,"PLAN_CANCELLING"],[3,"MANAGE_ON_GROK"],[4,"TRY_AGAIN"],[5,"REQUIRES_ACTION"],[6,"PAYMENT_FAILED"],[7,"CHARGE_IN_FLIGHT"],[8,"CHECK_GONE"],[9,"ADD_PAYMENT_METHOD"],[10,"GROK_SECURITY_BLOCKED"],[11,"GROK_SIGN_IN_REQUIRED"],[12,"GROK_OTHER_ACCOUNT"]],1),xr=(0,a.QT)(n.proto3,C,"DeploymentIntegration",[[0,"UNSPECIFIED"],[1,"SLACK"],[2,"LINEAR"],[3,"ATLASSIAN"],[4,"MICROSOFT_TEAMS"],[5,"SHAREPOINT"],[6,"GROK_CONNECTORS"],[7,"SENTRY"],[8,"PAGERDUTY"],[9,"APP_STORE_CONNECT"],[10,"MERGE"],[11,"GITHUB"],[12,"GITLAB"],[13,"AZURE_DEVOPS"],[14,"BITBUCKET_CLOUD"],[15,"ORIGIN"],[16,"BITBUCKET_DATA_CENTER"],[17,"TAILSCALE"],[18,"PRIVATE_TUNNELS"],[19,"FINANCE"],[20,"XAI_TEAM_MERGE"]],1),kr=(0,a.QT)(n.proto3,C,"ConnectionHealth",[[0,"UNSPECIFIED"],[1,"HEALTHY"],[2,"SETUP_INCOMPLETE"],[3,"DEGRADED"],[4,"NEEDS_REAUTH"],[5,"NEEDS_ADMIN"],[6,"ERROR"],[7,"DISCONNECTED"]],1),Er=(0,a.QT)(n.proto3,C,"ScmReasonCode",[[0,"UNSPECIFIED"],[1,"NEEDS_REAUTH"],[2,"NEEDS_ADMIN"],[3,"REPO_NOT_IN_SELECTION"],[4,"WRONG_TEAM"],[5,"RATE_LIMITED"],[6,"NETWORK_BLOCKED"],[7,"PROVIDER_OUTAGE"],[8,"CAPABILITY_UNSUPPORTED"],[9,"CURSOR_ROLE_REQUIRED"],[10,"READ_ONLY"],[11,"PERSONAL_REPO"],[12,"BLOCKED_BY_POLICY"],[13,"ARCHIVED"],[14,"NO_REPO_ACCESS"],[15,"ACCESS_UNCHECKED"],[16,"MISSING_PERMISSION"]],1),Cr=(0,a.QT)(n.proto3,C,"SecurityAgentType",[[0,"UNSPECIFIED"],[1,"SECURITY_REVIEWER"],[2,"VULNERABILITY_SCANNER"]],1),Tr=(0,a.QT)(n.proto3,C,"AllowlistConfig",[[0,"UNSPECIFIED"],[1,"ALLOWLIST"],[2,"BLOCKLIST"]],1),Ur=(0,a.QT)(n.proto3,C,"BugbotAutofixMode",[[0,"UNSPECIFIED"],[1,"OFF"],[2,"MANUAL"],[3,"AUTO_PR"],[4,"AUTO_MERGE"]],1),Ar=(0,a.QT)(n.proto3,C,"BugbotBackfillStatus",[[0,"UNSPECIFIED"],[1,"RUNNING"],[2,"COMPLETED"],[3,"FAILED"]],1),$r=(0,a.QT)(n.proto3,C,"BugbotUsageTier",[[0,"UNSPECIFIED"],[1,"FREE_TIER"],[2,"TRIAL"],[3,"PAID"]],1),Mr=(0,a.QT)(n.proto3,C,"BugbotBillingMode",[[0,"UNSPECIFIED"],[1,"SEAT"],[2,"TOKEN"]],1),Or=(0,a.QT)(n.proto3,C,"BugbotRepoAutoEnablePolicy",[[0,"UNSPECIFIED"],[1,"OFF"],[2,"DEFAULT_ON"]],1),Dr=(0,a.QT)(n.proto3,C,"TeamPendingInvitePurchaseState",[[0,"UNSPECIFIED"],[1,"PENDING"],[2,"RETRY_NEEDED"],[3,"WAITING_ON_GROK"],[4,"AWAITING_CARD_CHECK"]],1),Nr=(0,a.QT)(n.proto3,C,"LinearActor",[[0,"UNSPECIFIED"],[1,"APP"],[2,"USER"]],1),Gr=(0,a.QT)(n.proto3,C,"MicrosoftTeamsLinkState",[[0,"UNSPECIFIED"],[1,"READY"],[2,"ALREADY_LINKED"],[3,"EXPIRED"],[4,"SUPERSEDED"]],1),Lr=(0,a.QT)(n.proto3,C,"XaiCreditTransferOutcome",[[0,"UNSPECIFIED"],[1,"SUCCEEDED"],[2,"NOT_CONFIGURED"],[3,"FAILED"],[4,"NEEDS_RECONCILIATION"],[5,"PENDING"]],1),Fr=(0,a.QT)(n.proto3,C,"LinearRunOption",[[0,"UNSPECIFIED"],[1,"AUTOMATICALLY"],[2,"BASED_ON_CONDITIONS"],[3,"MANUALLY"]],1),Kr=(0,a.QT)(n.proto3,C,"LabelFilterMode",[[0,"UNSPECIFIED"],[1,"AND"],[2,"OR"]],1),zr=(0,a.QT)(n.proto3,C,"LinearIssuesOrderBy",[[0,"UNSPECIFIED"],[1,"UPDATED_AT"],[2,"CREATED_AT"]],1),jr=(0,a.QT)(n.proto3,C,"LinearIssueSummariesUnavailableReason",[[0,"UNSPECIFIED"],[1,"NOT_CONNECTED"],[2,"WORKSPACE_MISMATCH"],[3,"BUDGET_RESERVED"],[4,"RATE_LIMITED"]],1),Hr=(0,a.QT)(n.proto3,C,"SlackLinkedWorkspaceStatus",[[0,"UNSPECIFIED"],[1,"CONNECTED"],[2,"NEEDS_RECONNECT"],[3,"RESTRICTED"]],1),Wr=(0,a.QT)(n.proto3,C,"SlackRoutingRuleTargetType",[[0,"UNSPECIFIED"],[1,"REPOSITORY"],[2,"ENVIRONMENT"]],1),Qr=(0,a.QT)(n.proto3,C,"GroupType",[[0,"UNSPECIFIED"],[1,"BILLING"],[2,"PRODUCT"]],1),Vr=(0,a.QT)(n.proto3,C,"SpendGroupByCategory",[[0,"UNSPECIFIED"],[1,"MODEL"],[2,"USAGE_TYPE"],[3,"ORIGINATING_FLOW"],[4,"GROK_BOT"],[5,"PRODUCT"],[6,"USER"]],1),Xr=(0,a.QT)(n.proto3,C,"DailySpendRankingMetric",[[0,"UNSPECIFIED"],[1,"SPEND"],[2,"TOKENS"]],1),Yr=(0,a.QT)(n.proto3,C,"SpendType",[[0,"UNSPECIFIED"],[1,"ON_DEMAND"],[2,"INCLUDED"],[3,"ALL"]],1),Zr=(0,a.QT)(n.proto3,C,"GroupMemberChangeType",[[0,"UNSPECIFIED"],[1,"ADD"],[2,"REMOVE"]],1),te=(0,a.QT)(n.proto3,C,"ScimDirectoryOwnerType",[[0,"UNSPECIFIED"],[1,"ORGANIZATION"],[2,"TEAM"]],1),re=(0,a.QT)(n.proto3,C,"ScimDirectoryProvider",[[0,"UNSPECIFIED"],[1,"WORKOS"]],1),ee=(0,a.QT)(n.proto3,C,"ScimTargetMappingTargetType",[[0,"UNSPECIFIED"],[1,"GROUP"],[2,"TEAM"]],1),ne=(0,a.QT)(n.proto3,C,"ScimTargetMappingSyncState",[[0,"UNSPECIFIED"],[1,"PENDING"],[2,"SYNCED"],[3,"ERRORED"]],1),se=(0,a.QT)(n.proto3,C,"ScimTargetMappingSourceType",[[0,"UNSPECIFIED"],[1,"SCIM_DIRECTORY_GROUP"],[2,"CURSOR_GROUP"]],1),ie=(0,a.QT)(n.proto3,C,"ScimTargetMappingRole",[[0,"UNSPECIFIED"],[1,"MEMBER"],[2,"ADMIN"],[3,"UNPAID_ADMIN"]],1),oe=(0,a.QT)(n.proto3,C,"AdminNotificationRequestType",[[0,"UNSPECIFIED"],[1,"PRIVACY_MODE"],[2,"BUGBOT"],[3,"BUGBOT_ENABLE_REPOS"],[4,"ORIGIN"],[5,"SECURITY_REVIEWER_ENABLE_REPOS"],[6,"VULNERABILITY_SCANNER_ENABLE_REPOS"]],1),ae=(0,a.QT)(n.proto3,C,"TeamCustomerTelemetryDestinationKind",[[0,"UNSPECIFIED"],[1,"OTLP_HTTP"]],1),ue=(0,a.QT)(n.proto3,C,"TeamCustomerTelemetryDestinationTestSignal",[[0,"UNSPECIFIED"],[1,"LOGS"],[2,"METRICS"]],1),ce=(0,a.QT)(n.proto3,C,"TeamCustomerTelemetryDestinationTestOutcome",[[0,"UNSPECIFIED"],[1,"OK"],[2,"VALIDATION_ERROR"],[3,"HTTP_ERROR"],[4,"REDIRECT"],[5,"TIMED_OUT"],[6,"TLS_ERROR"],[7,"NETWORK_ERROR"]],1),le=(0,a.QT)(n.proto3,C,"TeamCustomerTelemetryDestinationHealthStatus",[[0,"UNSPECIFIED"],[1,"HEALTHY"],[2,"DEGRADED"],[3,"FAILING"],[4,"IDLE"]],1),me=(0,a.QT)(n.proto3,C,"InferenceHookMode",[[0,"UNSPECIFIED"],[1,"ALLOW"],[2,"BLOCK"],[3,"SHADOW"]],1),fe=(0,a.QT)(n.proto3,C,"InferenceHookSurface",[[0,"UNSPECIFIED"],[1,"GROK_BOT"],[2,"CLOUD_AGENT"],[3,"EDITOR"],[4,"CLI"],[5,"SDK"]],1),de=(0,a.QT)(n.proto3,C,"InferenceHookKind",[[0,"UNSPECIFIED"],[1,"HTTPS_ENDPOINT"],[2,"MICROSOFT_PURVIEW"],[3,"DECISION_RULES"]],1),pe=(0,a.QT)(n.proto3,C,"InferenceHookDecisionRuleOperator",[[0,"UNSPECIFIED"],[1,"AT_LEAST"],[2,"AT_MOST"]],1),he=(0,a.QT)(n.proto3,C,"InferenceHookDecisionRuleMode",[[0,"UNSPECIFIED"],[1,"BLOCK"],[2,"SHADOW"]],1),ge=(0,a.QT)(n.proto3,C,"InferenceHookSensitivityLabelMode",[[0,"UNSPECIFIED"],[1,"OFF"],[2,"BLOCK_LISTED"],[3,"BLOCK_AT_OR_ABOVE"]],1),_e=(0,a.QT)(n.proto3,C,"InferenceHookEndpointStatus",[[0,"UNSPECIFIED"],[1,"NOT_CONFIGURED"],[2,"NOT_ENFORCING"],[3,"HEALTHY"],[4,"TRIPPED"]],1),Je=(0,a.QT)(n.proto3,C,"InferenceHookEventType",[[0,"UNSPECIFIED"],[1,"PROMPT"],[2,"TOOL_CALL"]],1),we=(0,a.QT)(n.proto3,C,"BugbotMode",[[0,"UNSPECIFIED"],[1,"DEFAULT"],[2,"HIGH"],[3,"AUTO"],[5,"LOW"]],1),ye=(0,a.QT)(n.proto3,C,"EventCodeClaimState",[[0,"UNSPECIFIED"],[1,"UPCOMING"],[2,"OPEN"],[3,"FULL"],[4,"CLOSED"],[5,"DISABLED"]],1),Se=(0,a.QT)(n.proto3,C,"EventCodeCreditDestination",[[0,"UNSPECIFIED"],[1,"USAGE_GRANT"],[2,"STRIPE_CUSTOMER_BALANCE"]],1),qe=(0,a.QT)(n.proto3,C,"TeamRuleAgentType",[[0,"UNSPECIFIED"],[1,"ALL"],[2,"SAND"],[3,"CURSOR"]],1),Be=(0,a.QT)(n.proto3,C,"GlobalCommandAvailability",[[0,"UNSPECIFIED"],[1,"ALL_AGENTS"],[2,"CLOUD_ONLY"],[3,"LOCAL_ONLY"]],1),Ie=(0,a.QT)(n.proto3,C,"GlobalCommandSurface",[[0,"UNSPECIFIED"],[1,"CLASSIC"],[2,"GLASS"],[3,"CLI"]],1),Pe=(0,a.QT)(n.proto3,C,"ProjectRepoSkillsOmissionReason",[[0,"UNSPECIFIED"],[1,"NO_GITHUB_CONNECTION"],[2,"GITHUB_APP_CANNOT_READ"],[3,"GITHUB_ENTERPRISE_HOST"],[4,"ATTENUATED_ORIGIN_SESSION"],[5,"REPO_LIMIT"],[6,"ORIGIN_NO_ACCESS"],[7,"ORIGIN_IP_ALLOWLIST"],[9,"ORIGIN_NOT_FOUND"]],1),be=(0,a.QT)(n.proto3,C,"DiamondToBugbotMigrationMode",[[0,"UNSPECIFIED"],[1,"DRY_RUN"],[2,"APPLY"]],1),Re=(0,a.QT)(n.proto3,C,"SharedConversationVisibility",[[0,"UNSPECIFIED"],[1,"PRIVATE"],[2,"TEAM"],[3,"PUBLIC"]],1),ve=(0,a.QT)(n.proto3,C,"SharedCanvasVisibility",[[0,"UNSPECIFIED"],[1,"PRIVATE"],[2,"TEAM"],[3,"PUBLIC"]],1),xe=(0,a.QT)(n.proto3,C,"CanvasBrand",[[0,"UNSPECIFIED"],[1,"CURSOR"],[2,"GROK"]],1),ke=(0,a.QT)(n.proto3,C,"CanvasVisibility",[[0,"UNSPECIFIED"],[1,"PRIVATE"],[2,"TEAM_VIEW"],[3,"PUBLIC"]],1),Ee=(0,a.QT)(n.proto3,C,"ImposedModel",[[0,"UNSPECIFIED"],[1,"LATEST_CURSOR_MODEL"]],1),Ce=(0,a.QT)(n.proto3,C,"ImposedModelMode",[[0,"UNSPECIFIED"],[1,"OFF"],[2,"SOFT"],[3,"HARD"]],1),Te=(0,a.QT)(n.proto3,C,"SmartAutoModelSeverity",[[0,"UNSPECIFIED"],[1,"REQUIRED"],[2,"RECOMMENDED"]],1),Ue=(0,a.QT)(n.proto3,C,"ClaudeCacheTtlPolicy",[[0,"UNSPECIFIED"],[1,"STANDARD_5M"],[2,"EXTENDED_1H"]],1),Ae=(0,a.QT)(n.proto3,C,"IndividualLimitsOptOutOutcome",[[0,"UNSPECIFIED"],[1,"SUCCESS"],[2,"ALREADY_ALLOWED"],[3,"ENTERPRISE"],[4,"NOT_ADMIN"],[5,"CREATED_AFTER_CUTOFF"]],1),$e=(0,a.QT)(n.proto3,C,"SlackConversationType",[[0,"UNSPECIFIED"],[1,"CHANNEL"],[2,"DM"],[3,"GROUP_DM"]],1),Me=(0,a.QT)(n.proto3,C,"PluginStatus",[[0,"UNSPECIFIED"],[1,"DRAFT"],[2,"PENDING_APPROVAL"],[3,"APPROVED"],[4,"REJECTED"],[5,"UNLISTED"]],1),Oe=(0,a.QT)(n.proto3,C,"PluginLifecycleState",[[0,"UNSPECIFIED"],[1,"PUBLIC_LISTED"],[2,"PUBLIC_UNLISTED"],[3,"PUBLIC_DRAFT"],[4,"PUBLIC_PENDING"],[5,"PUBLIC_REJECTED"],[6,"PUBLISHER_SUBMISSION"],[7,"PRIVATE_ACTIVE"],[10,"PUBLIC_DEPRECATED"],[11,"PRIVATE_DEPRECATED"],[12,"PUBLIC_INVALID"],[13,"PRIVATE_INVALID"],[14,"PRIVATE_PUBLISHED"]],1),De=(0,a.QT)(n.proto3,C,"PluginSharepointInstallBlockDetail",[[0,"UNSPECIFIED"],[1,"NO_TEAM"],[2,"TEAM_NOT_CONNECTED"],[3,"TEAM_SETUP_UNFINISHED"]],1),Ne=(0,a.QT)(n.proto3,C,"PluginAccountUnavailableReason",[[0,"UNSPECIFIED"],[1,"TAILSCALE_NOT_ENABLED"]],1),Ge=(0,a.QT)(n.proto3,C,"PluginTeamAdminInstallBlockReason",[[0,"UNSPECIFIED"],[1,"MCP_ADMIN_POLICY"],[2,"FIRST_PARTY_ALLOWLIST"],[3,"TEAM_LIST"],[4,"SHAREPOINT_TEAM_ONLY"]],1),Le=(0,a.QT)(n.proto3,C,"ConnectorPolicyBlockedStage",[[0,"UNSPECIFIED"],[1,"IMPRESSION"],[2,"CONNECT_CLICK"]],1),Fe=(0,a.QT)(n.proto3,C,"ConnectorPolicyBlockedClient",[[0,"UNSPECIFIED"],[1,"GROK_BOT_DESKTOP"],[2,"GROK_BOT_MOBILE"],[3,"GROK_BOT_WEB"]],1),Ke=(0,a.QT)(n.proto3,C,"PluginMcpServerLinkUnknownCause",[[0,"UNSPECIFIED"],[1,"TEAM_NOT_LINKED"],[2,"ACCOUNT_NOT_LINKED"],[3,"NOT_GROK_TEAM_MEMBER"]],1),ze=(0,a.QT)(n.proto3,C,"ServedPlanResultKind",[[0,"UNSPECIFIED"],[1,"OK"],[2,"UNAVAILABLE"]],1),je=(0,a.QT)(n.proto3,C,"XaiOrganizationTeamLinkOutcomeKind",[[0,"UNSPECIFIED"],[1,"LINKED"],[2,"ALREADY_LINKED"],[3,"SKIPPED_DISABLED"],[4,"SKIPPED_UNMAPPED"],[5,"SKIPPED_OWNER_UNLINKED"],[6,"OWNER_LEFT_ORGANIZATION"],[7,"NOT_CONFIGURED"],[8,"GRANT_ROUTE_UNAVAILABLE"],[9,"GRANT_REFUSED"],[10,"CONFLICT"],[11,"UNAVAILABLE"],[12,"REJECTED"],[13,"FAILED"]],1),He=(0,a.QT)(n.proto3,C,"PluginPrimitiveType",[[0,"UNSPECIFIED"],[1,"SKILL"],[2,"MCP"],[3,"SUBAGENT"],[4,"COMMAND"]],1),We=(0,a.QT)(n.proto3,C,"PluginPrimitiveUsageInterval",[[0,"UNSPECIFIED"],[1,"LAST_1W"],[2,"ALL_TIME"],[3,"LAST_1D"],[4,"LAST_14D"],[5,"LAST_90D"],[6,"LAST_30D"]],1),Qe=(0,a.QT)(n.proto3,C,"McpServerAddBlockingSetting",[[0,"UNSPECIFIED"],[1,"MCP_ALLOWLIST"],[2,"CLOUD_AGENT_MCP_ALLOWLIST"]],1),Ve=(0,a.QT)(n.proto3,C,"EffectivePluginInstallMode",[[0,"UNSPECIFIED"],[1,"USER"],[2,"TEAM_DEFAULT"],[3,"TEAM_REQUIRED"]],1),Xe=(0,a.QT)(n.proto3,C,"TeamPluginsTableRowKind",[[0,"UNSPECIFIED"],[1,"PLUGIN"],[2,"MCP_SERVER"]],1),Ye=(0,a.QT)(n.proto3,C,"TeamPluginsTableAccessState",[[0,"UNSPECIFIED"],[1,"NONE"],[2,"ENABLED"],[3,"DISABLED"],[4,"DISABLED_BY_ADMIN"]],1),Ze=(0,a.QT)(n.proto3,C,"TeamPluginsTableRuleKind",[[0,"UNSPECIFIED"],[1,"NO_ALLOWLIST"],[2,"RULE"],[3,"TEAM_LIST"],[4,"NOT_ALLOWED"]],1),tn=(0,a.QT)(n.proto3,C,"MarketplaceAccessPrincipalKind",[[0,"UNSPECIFIED"],[1,"USER"],[2,"TEAM_MEMBER_GROUP"],[3,"TEAM_ADMIN_GROUP"],[4,"GROUP"]],1),rn=(0,a.QT)(n.proto3,C,"TeamMarketplacePluginInstallMode",[[0,"OPTIONAL"],[1,"DEFAULT"],[2,"REQUIRED"]],1),en=(0,a.QT)(n.proto3,C,"GrokBatchRequestState",[[0,"UNSPECIFIED"],[1,"PENDING"],[2,"SUCCEEDED"],[3,"CANCELLED"],[4,"FAILED"]],1),nn=(0,a.QT)(n.proto3,C,"GrokBatchResultFormat",[[0,"UNSPECIFIED"],[1,"JSON_REST"],[2,"PROTOBUF_B64"]],1),sn=(0,a.QT)(n.proto3,C,"GrokVoiceCloningRestriction",[[0,"UNSPECIFIED"],[1,"REGION"]],1),on=(0,a.QT)(n.proto3,C,"GrokVoiceCloneFailure",[[0,"UNSPECIFIED"],[1,"PASSPHRASE_MISMATCH"],[2,"SPEAKER_MISMATCH"],[3,"PASSPHRASE_EXPIRED"],[4,"AUDIO_QUALITY"],[5,"REGION_RESTRICTED"],[6,"CAP_REACHED"],[7,"TEMPORARY"]],1),an=(0,a.QT)(n.proto3,C,"GrokFilesSortBy",[[0,"UNSPECIFIED"],[1,"NAME"],[2,"SIZE"],[3,"AGE"]],1),un=(0,a.QT)(n.proto3,C,"GrokSortOrder",[[0,"UNSPECIFIED"],[1,"ASCENDING"],[2,"DESCENDING"]],1),cn=(0,a.QT)(n.proto3,C,"GrokFieldDefinitionOperation",[[0,"UNSPECIFIED"],[1,"ADD"],[2,"DELETE"]],1),ln=(0,a.QT)(n.proto3,C,"GrokCollectionsSortBy",[[0,"UNSPECIFIED"],[1,"NAME"],[2,"AGE"],[3,"STATUS"],[4,"ACCESS"]],1),mn=(0,a.QT)(n.proto3,C,"GrokDocumentStatus",[[0,"UNSPECIFIED"],[1,"PROCESSING"],[2,"PROCESSED"],[3,"FAILED"],[4,"CHUNKED"],[5,"EMBEDDING"],[6,"WRITING"]],1),fn=(0,a.QT)(n.proto3,C,"GrokModelType",[[0,"UNSPECIFIED"],[1,"LANGUAGE"],[2,"EMBEDDING"],[3,"IMAGE"],[4,"VIDEO"],[5,"AUDIO"]],1),dn=(0,a.QT)(n.proto3,C,"GrokModelModality",[[0,"UNSPECIFIED"],[1,"TEXT"],[2,"IMAGE"],[3,"AUDIO"],[4,"VIDEO"]],1),pn=(0,a.QT)(n.proto3,C,"GrokVoiceEndpointKind",[[0,"UNSPECIFIED"],[1,"TTS"],[2,"STT"],[3,"REALTIME"]],1),hn=(0,a.QT)(n.proto3,C,"DashboardAppScope",[[0,"UNSPECIFIED"],[1,"PERSONAL"],[2,"TEAM"],[3,"SHARED"]],1),gn=(0,a.QT)(n.proto3,C,"DashboardAppViewerRole",[[0,"UNSPECIFIED"],[1,"OWNER"],[2,"TEAM_ADMIN"],[3,"EDITOR"]],1),_n=(0,a.QT)(n.proto3,C,"AppApiKeyAccess",[[0,"UNSPECIFIED"],[1,"ALLOWED"],[2,"TEAM_KEYS_OFF"],[3,"UNAVAILABLE"]],1);class Jn extends T{constructor(t){super(),this.code="",this.installationId="",this.setupAction="",this.cursorCode="",this.source=wn.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jn).fromBinary(t,r)}static fromJson(t,r){return(new Jn).fromJson(t,r)}static fromJsonString(t,r){return(new Jn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jn,t,r)}static $(){return["ConnectGithubCallbackRequest|1 code 9|2 installation_id 9|3 setup_action 9|4 cursor_code 9|5 source #0|7 ghe_application 9?",wn]}}var wn=(0,a.QT)(n.proto3,C,"ConnectGithubCallbackRequest.Source",[[0,"UNSPECIFIED"],[1,"APP"],[2,"SLACK"]],1);class yn extends T{constructor(t){super(),this.needConfirmation=!1,this.installationId="",this.confirmationCode="",this.githubLogin="",this.pendingApproval=!1,this.githubUserNodeId="",this.githubUserDatabaseId="",this.githubName="",this.githubAvatarUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yn).fromBinary(t,r)}static fromJson(t,r){return(new yn).fromJson(t,r)}static fromJsonString(t,r){return(new yn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yn,t,r)}static $(){return["ConnectGithubCallbackResponse|1 need_confirmation 8|2 installation_id 9|3 confirmation_code 9|4 github_login 9|5 pending_approval 8|6 github_user_node_id 9|7 github_user_database_id 9|8 github_name 9|9 github_avatar_url 9"]}}class Sn extends T{constructor(t){super(),this.target={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sn).fromBinary(t,r)}static fromJson(t,r){return(new Sn).fromJson(t,r)}static fromJsonString(t,r){return(new Sn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sn,t,r)}static $(){return["ScmConnectIntentTarget|1 user #0 target|2 team_id 5 target",qn]}}class qn extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qn).fromBinary(t,r)}static fromJson(t,r){return(new qn).fromJson(t,r)}static fromJsonString(t,r){return(new qn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qn,t,r)}static $(){return["ScmConnectIntentTarget.User"]}}class Bn extends T{constructor(t){super(),this.githubRepo="",this.source=In.UNSPECIFIED,this.verifierHash="",this.forceOauth=!1,this.completionBinding=Pn.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bn).fromBinary(t,r)}static fromJson(t,r){return(new Bn).fromJson(t,r)}static fromJsonString(t,r){return(new Bn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bn,t,r)}static $(){return["PrepareGithubConnectFlowRequest|1 github_repo 9|2 ghe_application 9?|3 source #0|4 verifier_hash 9|5 force_oauth 8|6 connect_target #1?|7 connect_source #2?|8 completion_binding #3|9 grok_bot_callback_url 9?",In,Sn,U,Pn]}}var In=(0,a.QT)(n.proto3,C,"PrepareGithubConnectFlowRequest.Source",[[0,"UNSPECIFIED"],[1,"GLASS_CLOUD_AGENT"],[2,"GLASS_DIFF"],[3,"GLASS_AUTOMATIONS"],[4,"GROK_BOT"]],1),Pn=(0,a.QT)(n.proto3,C,"PrepareGithubConnectFlowRequest.CompletionBinding",[[0,"UNSPECIFIED"],[1,"CLIENT_VERIFIER"],[2,"ACCOUNT"]],1);class bn extends T{constructor(t){super(),this.flowId="",this.state="",this.githubUrl="",this.expiresAtMs=n.protoInt64.zero,this.shouldInstall=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bn).fromBinary(t,r)}static fromJson(t,r){return(new bn).fromJson(t,r)}static fromJsonString(t,r){return(new bn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bn,t,r)}static $(){return["PrepareGithubConnectFlowResponse|1 flow_id 9|2 state 9|3 github_url 9|4 expires_at_ms 3|5 should_install 8|6 ghe_application 9?"]}}class Rn extends T{constructor(t){super(),this.state="",this.verifier="",this.code="",this.installationId="",this.setupAction="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rn).fromBinary(t,r)}static fromJson(t,r){return(new Rn).fromJson(t,r)}static fromJsonString(t,r){return(new Rn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rn,t,r)}static $(){return["CompleteGithubConnectFlowRequest|1 state 9|2 verifier 9|3 code 9|4 installation_id 9|5 setup_action 9|6 ghe_application 9?"]}}class vn extends T{constructor(t){super(),this.outcome=xn.UNSPECIFIED,this.installationId="",this.confirmationCode="",this.githubLogin="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vn).fromBinary(t,r)}static fromJson(t,r){return(new vn).fromJson(t,r)}static fromJsonString(t,r){return(new vn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vn,t,r)}static $(){return["CompleteGithubConnectFlowResponse|1 outcome #0|2 installation_id 9|3 confirmation_code 9|4 github_login 9|5 ghe_application 9?",xn]}}var xn=(0,a.QT)(n.proto3,C,"CompleteGithubConnectFlowResponse.Outcome",[[0,"UNSPECIFIED"],[1,"CONNECTED"],[2,"PENDING_APPROVAL"],[3,"NEEDS_CONFIRMATION"]],1);class kn extends T{constructor(t){super(),this.hostname="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kn).fromBinary(t,r)}static fromJson(t,r){return(new kn).fromJson(t,r)}static fromJsonString(t,r){return(new kn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kn,t,r)}static $(){return["PrepareSetupGithubEnterpriseAppRequest|1 hostname 9|2 external_host 9?|3 team_id 5?"]}}class En extends T{constructor(t){super(),this.pendingAppUuid="",this.serializedManifest="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new En).fromBinary(t,r)}static fromJson(t,r){return(new En).fromJson(t,r)}static fromJsonString(t,r){return(new En).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(En,t,r)}static $(){return["PrepareSetupGithubEnterpriseAppResponse|1 pending_app_uuid 9|2 serialized_manifest 9"]}}class Cn extends T{constructor(t){super(),this.installationCode="",this.pendingAppUuid="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cn).fromBinary(t,r)}static fromJson(t,r){return(new Cn).fromJson(t,r)}static fromJsonString(t,r){return(new Cn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cn,t,r)}static $(){return["FinishSetupGithubEnterpriseAppRequest|1 installation_code 9|2 pending_app_uuid 9"]}}class Tn extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tn).fromBinary(t,r)}static fromJson(t,r){return(new Tn).fromJson(t,r)}static fromJsonString(t,r){return(new Tn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tn,t,r)}static $(){return["FinishSetupGithubEnterpriseAppResponse|1 install_url 9?"]}}class Un extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Un).fromBinary(t,r)}static fromJson(t,r){return(new Un).fromJson(t,r)}static fromJsonString(t,r){return(new Un).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Un,t,r)}static $(){return["ListGithubEnterpriseAppsRequest|1 team_id 5?"]}}class An extends T{constructor(t){super(),this.apps=[],this.canManage=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new An).fromBinary(t,r)}static fromJson(t,r){return(new An).fromJson(t,r)}static fromJsonString(t,r){return(new An).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(An,t,r)}static $(){return["ListGithubEnterpriseAppsResponse|1 apps #0*|2 can_manage 8",$n]}}class $n extends T{constructor(t){super(),this.uuid="",this.slug="",this.hostname="",this.canDelete=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $n).fromBinary(t,r)}static fromJson(t,r){return(new $n).fromJson(t,r)}static fromJsonString(t,r){return(new $n).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($n,t,r)}static $(){return["ListGithubEnterpriseAppsResponse.GithubEnterpriseApp|1 uuid 9|2 slug 9|3 hostname 9|4 can_delete 8|5 html_url 9?"]}}class Mn extends T{constructor(t){super(),this.uuid="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mn).fromBinary(t,r)}static fromJson(t,r){return(new Mn).fromJson(t,r)}static fromJsonString(t,r){return(new Mn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mn,t,r)}static $(){return["DeleteGithubEnterpriseAppRequest|1 uuid 9"]}}class On extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new On).fromBinary(t,r)}static fromJson(t,r){return(new On).fromJson(t,r)}static fromJsonString(t,r){return(new On).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(On,t,r)}static $(){return["DeleteGithubEnterpriseAppResponse"]}}class Dn extends T{constructor(t){super(),this.hostname="",this.accessToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dn).fromBinary(t,r)}static fromJson(t,r){return(new Dn).fromJson(t,r)}static fromJsonString(t,r){return(new Dn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dn,t,r)}static $(){return["SetupGitlabEnterpriseInstanceRequest|1 hostname 9|2 access_token 9|3 group_path 9?|4 slug 9?|5 client_id 9?|6 client_secret 9?|7 external_host 9?|8 team_id 5?"]}}class Nn extends T{constructor(t){super(),this.uuid="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nn).fromBinary(t,r)}static fromJson(t,r){return(new Nn).fromJson(t,r)}static fromJsonString(t,r){return(new Nn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nn,t,r)}static $(){return["SetupGitlabEnterpriseInstanceResponse|1 uuid 9"]}}class Gn extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gn).fromBinary(t,r)}static fromJson(t,r){return(new Gn).fromJson(t,r)}static fromJsonString(t,r){return(new Gn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gn,t,r)}static $(){return["ListGitlabEnterpriseInstancesRequest|1 team_id 5?"]}}class Ln extends T{constructor(t){super(),this.instances=[],this.gitlabServiceAccountTokenConfigured=!1,this.canManageGitlabServiceAccountToken=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ln).fromBinary(t,r)}static fromJson(t,r){return(new Ln).fromJson(t,r)}static fromJsonString(t,r){return(new Ln).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ln,t,r)}static $(){return["ListGitlabEnterpriseInstancesResponse|1 instances #0*|2 gitlab_service_account_token_configured 8|3 can_manage_gitlab_service_account_token 8",Fn]}}class Fn extends T{constructor(t){super(),this.uuid="",this.hostname="",this.username="",this.canDelete=!1,this.hostControlledWebhookUrl="",this.hostControlledWebhookSecret="",this.hostControlledServiceAccountTokenConfigured=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fn).fromBinary(t,r)}static fromJson(t,r){return(new Fn).fromJson(t,r)}static fromJsonString(t,r){return(new Fn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fn,t,r)}static $(){return["ListGitlabEnterpriseInstancesResponse.GitlabEnterpriseInstance|1 uuid 9|2 hostname 9|3 username 9|4 can_delete 8|5 host_controlled_webhook_url 9|6 host_controlled_webhook_secret 9|7 host_controlled_service_account_token_configured 8|8 external_host 9?"]}}class Kn extends T{constructor(t){super(),this.gitEnterpriseUuid="",this.accessToken="",this.clearToken=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kn).fromBinary(t,r)}static fromJson(t,r){return(new Kn).fromJson(t,r)}static fromJsonString(t,r){return(new Kn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Kn,t,r)}static $(){return["SetGitlabEnterpriseHostControlledServiceAccountTokenRequest|1 git_enterprise_uuid 9|2 access_token 9|3 clear_token 8|4 team_id 5?"]}}class zn extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zn).fromBinary(t,r)}static fromJson(t,r){return(new zn).fromJson(t,r)}static fromJsonString(t,r){return(new zn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zn,t,r)}static $(){return["SetGitlabEnterpriseHostControlledServiceAccountTokenResponse"]}}class jn extends T{constructor(t){super(),this.gitEnterpriseUuid="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jn).fromBinary(t,r)}static fromJson(t,r){return(new jn).fromJson(t,r)}static fromJsonString(t,r){return(new jn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jn,t,r)}static $(){return["RotateGitlabEnterpriseWebhookSecretRequest|1 git_enterprise_uuid 9|2 team_id 5?"]}}class Hn extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hn).fromBinary(t,r)}static fromJson(t,r){return(new Hn).fromJson(t,r)}static fromJsonString(t,r){return(new Hn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hn,t,r)}static $(){return["RotateGitlabEnterpriseWebhookSecretResponse"]}}class Wn extends T{constructor(t){super(),this.uuid="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wn).fromBinary(t,r)}static fromJson(t,r){return(new Wn).fromJson(t,r)}static fromJsonString(t,r){return(new Wn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wn,t,r)}static $(){return["DeleteGitlabEnterpriseInstanceRequest|1 uuid 9|2 team_id 5?"]}}class Qn extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qn).fromBinary(t,r)}static fromJson(t,r){return(new Qn).fromJson(t,r)}static fromJsonString(t,r){return(new Qn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qn,t,r)}static $(){return["DeleteGitlabEnterpriseInstanceResponse"]}}class Vn extends T{constructor(t){super(),this.hostname="",this.accessToken="",this.oauthClientId="",this.oauthClientSecret="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vn).fromBinary(t,r)}static fromJson(t,r){return(new Vn).fromJson(t,r)}static fromJsonString(t,r){return(new Vn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vn,t,r)}static $(){return["SetupBitbucketServerInstanceRequest|1 hostname 9|2 external_host 9?|3 access_token 9|4 oauth_client_id 9|5 oauth_client_secret 9"]}}class Xn extends T{constructor(t){super(),this.uuid="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xn).fromBinary(t,r)}static fromJson(t,r){return(new Xn).fromJson(t,r)}static fromJsonString(t,r){return(new Xn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xn,t,r)}static $(){return["SetupBitbucketServerInstanceResponse|1 uuid 9"]}}class Yn extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yn).fromBinary(t,r)}static fromJson(t,r){return(new Yn).fromJson(t,r)}static fromJsonString(t,r){return(new Yn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yn,t,r)}static $(){return["ListBitbucketServerInstancesRequest"]}}class Zn extends T{constructor(t){super(),this.instances=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zn).fromBinary(t,r)}static fromJson(t,r){return(new Zn).fromJson(t,r)}static fromJsonString(t,r){return(new Zn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zn,t,r)}static $(){return["ListBitbucketServerInstancesResponse|1 instances #0*",ts]}}class ts extends T{constructor(t){super(),this.uuid="",this.hostname="",this.externalHost="",this.canDelete=!1,this.serviceAccountTokenConfigured=!1,this.browserBaseUrl="",this.outboundBaseUrl="",this.oauthAppConfigured=!1,this.currentUserConnected=!1,this.membersCanLink=!1,this.currentUserReconnectRequired=!1,this.connectedAccountCount=0,this.listsReposWithOwnAccount=!1,this.currentUserWriteAccessMissing=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ts).fromBinary(t,r)}static fromJson(t,r){return(new ts).fromJson(t,r)}static fromJsonString(t,r){return(new ts).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ts,t,r)}static $(){return["ListBitbucketServerInstancesResponse.BitbucketServerInstance|1 uuid 9|2 hostname 9|3 external_host 9|4 can_delete 8|5 service_account_token_configured 8|6 browser_base_url 9|7 outbound_base_url 9|8 oauth_app_configured 8|9 current_user_connected 8|10 members_can_link 8|11 current_user_reconnect_required 8|12 connected_account_count 5|13 lists_repos_with_own_account 8|14 current_user_write_access_missing 8"]}}class rs extends T{constructor(t){super(),this.uuid="",this.action={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rs).fromBinary(t,r)}static fromJson(t,r){return(new rs).fromJson(t,r)}static fromJsonString(t,r){return(new rs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rs,t,r)}static $(){return["UpdateBitbucketServerInstanceTokenRequest|1 uuid 9|2 set_token #0 action|3 clear_token #1 action",es,ns]}}class es extends T{constructor(t){super(),this.accessToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new es).fromBinary(t,r)}static fromJson(t,r){return(new es).fromJson(t,r)}static fromJsonString(t,r){return(new es).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(es,t,r)}static $(){return["UpdateBitbucketServerInstanceTokenRequest.SetToken|1 access_token 9"]}}class ns extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ns).fromBinary(t,r)}static fromJson(t,r){return(new ns).fromJson(t,r)}static fromJsonString(t,r){return(new ns).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ns,t,r)}static $(){return["UpdateBitbucketServerInstanceTokenRequest.ClearToken"]}}class ss extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ss).fromBinary(t,r)}static fromJson(t,r){return(new ss).fromJson(t,r)}static fromJsonString(t,r){return(new ss).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ss,t,r)}static $(){return["UpdateBitbucketServerInstanceTokenResponse"]}}class is extends T{constructor(t){super(),this.uuid="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new is).fromBinary(t,r)}static fromJson(t,r){return(new is).fromJson(t,r)}static fromJsonString(t,r){return(new is).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(is,t,r)}static $(){return["DeleteBitbucketServerInstanceRequest|1 uuid 9"]}}class os extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new os).fromBinary(t,r)}static fromJson(t,r){return(new os).fromJson(t,r)}static fromJsonString(t,r){return(new os).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(os,t,r)}static $(){return["DeleteBitbucketServerInstanceResponse"]}}class as extends T{constructor(t){super(),this.gitEnterpriseUuid="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new as).fromBinary(t,r)}static fromJson(t,r){return(new as).fromJson(t,r)}static fromJsonString(t,r){return(new as).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(as,t,r)}static $(){return["SyncGitlabReposRequest|1 git_enterprise_uuid 9|2 team_id 5?"]}}class us extends T{constructor(t){super(),this.started=!1,this.errorMessage="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new us).fromBinary(t,r)}static fromJson(t,r){return(new us).fromJson(t,r)}static fromJsonString(t,r){return(new us).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(us,t,r)}static $(){return["SyncGitlabReposResponse|1 started 8|2 error_message 9"]}}class cs extends T{constructor(t){super(),this.gitEnterpriseUuid="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cs).fromBinary(t,r)}static fromJson(t,r){return(new cs).fromJson(t,r)}static fromJsonString(t,r){return(new cs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cs,t,r)}static $(){return["GetGitlabReposSyncStatusRequest|1 git_enterprise_uuid 9"]}}class ls extends T{constructor(t){super(),this.status=A.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ls).fromBinary(t,r)}static fromJson(t,r){return(new ls).fromJson(t,r)}static fromJsonString(t,r){return(new ls).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ls,t,r)}static $(){return["GetGitlabReposSyncStatusResponse|1 status #0|2 error_message 9?|3 repos_populated 5?",A]}}class ms extends T{constructor(t){super(),this.installationId="",this.confirmationCode="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ms).fromBinary(t,r)}static fromJson(t,r){return(new ms).fromJson(t,r)}static fromJsonString(t,r){return(new ms).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ms,t,r)}static $(){return["ConfirmGithubInstallationRequest|1 installation_id 9|2 confirmation_code 9"]}}class fs extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fs).fromBinary(t,r)}static fromJson(t,r){return(new fs).fromJson(t,r)}static fromJsonString(t,r){return(new fs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fs,t,r)}static $(){return["ConfirmGithubInstallationResponse|1 ghe_application 9?"]}}class ds extends T{constructor(t){super(),this.githubRepo="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ds).fromBinary(t,r)}static fromJson(t,r){return(new ds).fromJson(t,r)}static fromJsonString(t,r){return(new ds).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ds,t,r)}static $(){return["RegisterGithubCursorCodeRequest|1 github_repo 9|3 ghe_application 9?|4 connect_target #0?|5 connect_source #1?",Sn,U]}}class ps extends T{constructor(t){super(),this.cursorCode="",this.shouldInstall=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ps).fromBinary(t,r)}static fromJson(t,r){return(new ps).fromJson(t,r)}static fromJsonString(t,r){return(new ps).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ps,t,r)}static $(){return["RegisterGithubCursorCodeResponse|1 cursor_code 9|2 should_install 8|3 ghe_hostname 9?|4 ghe_app_slug 9?|5 ghe_client_id 9?|6 github_oauth_client_id 9?|7 github_app_slug 9?|8 ghe_app_html_url 9?"]}}class hs extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hs).fromBinary(t,r)}static fromJson(t,r){return(new hs).fromJson(t,r)}static fromJsonString(t,r){return(new hs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hs,t,r)}static $(){return["DisconnectGithubRequest|2 ghe_application 9?|3 user_only 8?"]}}class gs extends T{constructor(t){super(),this.removedConnectionsCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gs).fromBinary(t,r)}static fromJson(t,r){return(new gs).fromJson(t,r)}static fromJsonString(t,r){return(new gs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gs,t,r)}static $(){return["DisconnectGithubResponse|1 removed_connections_count 5"]}}class _s extends T{constructor(t){super(),this.requestQuota=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _s).fromBinary(t,r)}static fromJson(t,r){return(new _s).fromJson(t,r)}static fromJsonString(t,r){return(new _s).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_s,t,r)}static $(){return["UpdateFastRequestsRequest|1 request_quota 5"]}}class Js extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Js).fromBinary(t,r)}static fromJson(t,r){return(new Js).fromJson(t,r)}static fromJsonString(t,r){return(new Js).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Js,t,r)}static $(){return["UpdateFastRequestsResponse"]}}class ws extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ws).fromBinary(t,r)}static fromJson(t,r){return(new ws).fromJson(t,r)}static fromJsonString(t,r){return(new ws).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ws,t,r)}static $(){return["GetFastRequestsRequest"]}}class ys extends T{constructor(t){super(),this.requestQuota=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ys).fromBinary(t,r)}static fromJson(t,r){return(new ys).fromJson(t,r)}static fromJsonString(t,r){return(new ys).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ys,t,r)}static $(){return["GetFastRequestsResponse|1 request_quota 5"]}}class Ss extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ss).fromBinary(t,r)}static fromJson(t,r){return(new Ss).fromJson(t,r)}static fromJsonString(t,r){return(new Ss).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ss,t,r)}static $(){return["DeleteAccountRequest"]}}class qs extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qs).fromBinary(t,r)}static fromJson(t,r){return(new qs).fromJson(t,r)}static fromJsonString(t,r){return(new qs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qs,t,r)}static $(){return["DeleteAccountResponse"]}}class Bs extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bs).fromBinary(t,r)}static fromJson(t,r){return(new Bs).fromJson(t,r)}static fromJsonString(t,r){return(new Bs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bs,t,r)}static $(){return["GetAccountSettingsRequest"]}}class Is extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Is).fromBinary(t,r)}static fromJson(t,r){return(new Is).fromJson(t,r)}static fromJsonString(t,r){return(new Is).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Is,t,r)}static $(){return["AccountSettings|1 profile #0|2 xai_link #1|3 cursor #2",Ps,bs,Rs]}}class Ps extends T{constructor(t){super(),this.givenName="",this.familyName="",this.email="",this.profileImageUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ps).fromBinary(t,r)}static fromJson(t,r){return(new Ps).fromJson(t,r)}static fromJsonString(t,r){return(new Ps).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ps,t,r)}static $(){return["AccountProfile|1 given_name 9|2 family_name 9|3 email 9|4 profile_image_url 9"]}}class bs extends T{constructor(t){super(),this.status=$.UNSPECIFIED,this.sessionsAvailable=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bs).fromBinary(t,r)}static fromJson(t,r){return(new bs).fromJson(t,r)}static fromJsonString(t,r){return(new bs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bs,t,r)}static $(){return["AccountXaiLink|1 status #0|2 sessions_available 8",$]}}class Rs extends T{constructor(t){super(),this.onPaidTeam=!1,this.pricingOptedOut=!1,this.unpaidTeamAdminDeletionMessage="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rs).fromBinary(t,r)}static fromJson(t,r){return(new Rs).fromJson(t,r)}static fromJsonString(t,r){return(new Rs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rs,t,r)}static $(){return["AccountCursorControls|1 on_paid_team 8|2 pricing_opted_out 8|3 unpaid_team_admin_deletion_message 9"]}}class vs extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vs).fromBinary(t,r)}static fromJson(t,r){return(new vs).fromJson(t,r)}static fromJsonString(t,r){return(new vs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vs,t,r)}static $(){return["GetAccountDeletionSummaryRequest"]}}class xs extends T{constructor(t){super(),this.grokBotCount=0,this.recentGrokBots=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xs).fromBinary(t,r)}static fromJson(t,r){return(new xs).fromJson(t,r)}static fromJsonString(t,r){return(new xs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xs,t,r)}static $(){return["AccountDeletionSummary|1 cursor_member_since #0|2 grok_bot_count 5|3 recent_grok_bots #1*|4 cursor_profile #2|5 grok_account #3",n.Timestamp,Es,Ps,ks]}}class ks extends T{constructor(t){super(),this.email="",this.xUsername="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ks).fromBinary(t,r)}static fromJson(t,r){return(new ks).fromJson(t,r)}static fromJsonString(t,r){return(new ks).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ks,t,r)}static $(){return["AccountDeletionGrokAccount|1 email 9|2 x_username 9"]}}class Es extends T{constructor(t){super(),this.agentId="",this.name="",this.avatarUrl="",this.avatarShape="",this.avatarColor="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Es).fromBinary(t,r)}static fromJson(t,r){return(new Es).fromJson(t,r)}static fromJsonString(t,r){return(new Es).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Es,t,r)}static $(){return["AccountDeletionGrokBot|1 agent_id 9|2 name 9|3 avatar_url 9|4 avatar_shape 9|5 avatar_color 9"]}}class Cs extends T{constructor(t){super(),this.target=M.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cs).fromBinary(t,r)}static fromJson(t,r){return(new Cs).fromJson(t,r)}static fromJsonString(t,r){return(new Cs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cs,t,r)}static $(){return["CreateAccountHandoffRequest|1 target #0",M]}}class Ts extends T{constructor(t){super(),this.url="",this.signedIn=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ts).fromBinary(t,r)}static fromJson(t,r){return(new Ts).fromJson(t,r)}static fromJsonString(t,r){return(new Ts).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ts,t,r)}static $(){return["CreateAccountHandoffResponse|1 url 9|2 signed_in 8"]}}class Us extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Us).fromBinary(t,r)}static fromJson(t,r){return(new Us).fromJson(t,r)}static fromJsonString(t,r){return(new Us).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Us,t,r)}static $(){return["GetMeRequest|1 team_id 5?|2 source_site_hostname 9?|3 include_mobile_app_status 8?|4 include_individual_plan 8?"]}}class As extends T{constructor(t){super(),this.authId="",this.userId=0,this.adminSessionManagementEnabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new As).fromBinary(t,r)}static fromJson(t,r){return(new As).fromJson(t,r)}static fromJsonString(t,r){return(new As).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(As,t,r)}static $(){return["GetMeResponse|1 auth_id 9|2 user_id 5|3 email 9?|4 first_name 9?|5 last_name 9?|6 workos_id 9?|7 team_id 5?|8 created_at 9?|9 is_enterprise_user 8?|10 team_name 9?|11 email_domain_type 9?|12 country 9?|13 profile_picture_url 9?|14 cursor_review_onboarding_use_cursor_github_app 8?|15 organization_id 3?|16 organization_public_id 9?|17 is_team_admin 8?|18 has_active_mobile_session 8?|19 public_user_id 9?|20 scm_only_restricted 8?|21 email_is_synthetic 8?|22 signup_source 9?|23 admin_session_management_enabled 8|24 has_individual_plan 8?|25 membership_type 9?"]}}class $s extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $s).fromBinary(t,r)}static fromJson(t,r){return(new $s).fromJson(t,r)}static fromJsonString(t,r){return(new $s).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($s,t,r)}static $(){return["GetAgenticOnboardingConfigRequest"]}}class Ms extends T{constructor(t){super(),this.agenticOnboardingEnabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ms).fromBinary(t,r)}static fromJson(t,r){return(new Ms).fromJson(t,r)}static fromJsonString(t,r){return(new Ms).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ms,t,r)}static $(){return["GetAgenticOnboardingConfigResponse|1 agentic_onboarding_enabled 8"]}}class Os extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Os).fromBinary(t,r)}static fromJson(t,r){return(new Os).fromJson(t,r)}static fromJsonString(t,r){return(new Os).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Os,t,r)}static $(){return["GetUserOrganizationsRequest"]}}class Ds extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ds).fromBinary(t,r)}static fromJson(t,r){return(new Ds).fromJson(t,r)}static fromJsonString(t,r){return(new Ds).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ds,t,r)}static $(){return["GetTeamLinkedOrganizationRequest|1 team_id 5"]}}class Ns extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ns).fromBinary(t,r)}static fromJson(t,r){return(new Ns).fromJson(t,r)}static fromJsonString(t,r){return(new Ns).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ns,t,r)}static $(){return["GetTeamLinkedOrganizationResponse|1 organization #0?",Gs]}}class Gs extends T{constructor(t){super(),this.organizationId="",this.organizationName="",this.organizationSlug="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gs).fromBinary(t,r)}static fromJson(t,r){return(new Gs).fromJson(t,r)}static fromJsonString(t,r){return(new Gs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gs,t,r)}static $(){return["GetTeamLinkedOrganizationResponse.Organization|1 organization_id 9|2 organization_name 9|3 organization_slug 9"]}}class Ls extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ls).fromBinary(t,r)}static fromJson(t,r){return(new Ls).fromJson(t,r)}static fromJsonString(t,r){return(new Ls).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ls,t,r)}static $(){return["SetUserDefaultTeamRequest|1 team_id 5"]}}class Fs extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fs).fromBinary(t,r)}static fromJson(t,r){return(new Fs).fromJson(t,r)}static fromJsonString(t,r){return(new Fs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fs,t,r)}static $(){return["SetUserDefaultTeamResponse"]}}class Ks extends T{constructor(t){super(),this.organizations=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ks).fromBinary(t,r)}static fromJson(t,r){return(new Ks).fromJson(t,r)}static fromJsonString(t,r){return(new Ks).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ks,t,r)}static $(){return["GetUserOrganizationsResponse|1 organizations #0*",js]}}class zs extends T{constructor(t){super(),this.teamId=0,this.teamName="",this.teamSlug="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zs).fromBinary(t,r)}static fromJson(t,r){return(new zs).fromJson(t,r)}static fromJsonString(t,r){return(new zs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zs,t,r)}static $(){return["GetUserOrganizationsResponse.Team|1 team_id 5|2 team_name 9|3 team_slug 9|4 team_organization_membership_created_at_ms 3?|5 viewer_team_role #0?|6 team_deleted_at_ms 3?|7 icon_url 9?",it]}}class js extends T{constructor(t){super(),this.organizationId="",this.organizationName="",this.organizationSlug="",this.role=O.UNSPECIFIED,this.teams=[],this.grantedPermissions=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new js).fromBinary(t,r)}static fromJson(t,r){return(new js).fromJson(t,r)}static fromJsonString(t,r){return(new js).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(js,t,r)}static $(){return["GetUserOrganizationsResponse.Organization|1 organization_id 9|2 organization_name 9|3 organization_slug 9|4 role #0|5 teams #1*|6 default_team_id 5?|7 effective_max_teams 5?|8 granted_permissions 9*|9 can_create_organization_teams 8?|10 root_team_id 5?|11 xai_team_linked 8?|12 icon_url 9?",O,zs]}}class Hs extends T{constructor(t){super(),this.teamId=0,this.teamName="",this.teamSlug="",this.teamRole=it.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hs).fromBinary(t,r)}static fromJson(t,r){return(new Hs).fromJson(t,r)}static fromJsonString(t,r){return(new Hs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hs,t,r)}static $(){return["OrganizationMemberTeam|1 team_id 5|2 team_name 9|3 team_slug 9|4 team_role #0",it]}}class Ws extends T{constructor(t){super(),this.userId=0,this.authId="",this.role=O.UNSPECIFIED,this.teams=[],this.memberPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ws).fromBinary(t,r)}static fromJson(t,r){return(new Ws).fromJson(t,r)}static fromJsonString(t,r){return(new Ws).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ws,t,r)}static $(){return["OrganizationMember|1 user_id 5|2 auth_id 9|3 email 9?|4 first_name 9?|5 last_name 9?|6 role #0|7 teams #1*|8 member_public_id 9",O,Hs]}}class Qs extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qs).fromBinary(t,r)}static fromJson(t,r){return(new Qs).fromJson(t,r)}static fromJsonString(t,r){return(new Qs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qs,t,r)}static $(){return["GetOrganizationMembersRequest|1 organization_id 9|2 page 5?|3 page_size 5?|4 search_term 9?|5 sort_by 9?|6 sort_direction 9?|7 role_filter #0?|8 team_id 5?",O]}}class Vs extends T{constructor(t){super(),this.members=[],this.totalMembers=0,this.totalPages=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vs).fromBinary(t,r)}static fromJson(t,r){return(new Vs).fromJson(t,r)}static fromJsonString(t,r){return(new Vs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vs,t,r)}static $(){return["GetOrganizationMembersResponse|1 members #0*|2 total_members 5|3 total_pages 5",Ws]}}class Xs extends T{constructor(t){super(),this.groupPublicId="",this.groupName="",this.joinedAt=n.protoInt64.zero,this.isAdmin=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xs).fromBinary(t,r)}static fromJson(t,r){return(new Xs).fromJson(t,r)}static fromJsonString(t,r){return(new Xs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xs,t,r)}static $(){return["OrganizationMemberGroup|1 group_public_id 9|2 group_name 9|3 joined_at 3|4 is_admin 8|5 monthly_spending_limit_dollars 5?"]}}class Ys extends T{constructor(t){super(),this.organizationId="",this.memberPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ys).fromBinary(t,r)}static fromJson(t,r){return(new Ys).fromJson(t,r)}static fromJsonString(t,r){return(new Ys).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ys,t,r)}static $(){return["GetOrganizationMemberRequest|1 organization_id 9|2 member_public_id 9"]}}class Zs extends T{constructor(t){super(),this.groups=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zs).fromBinary(t,r)}static fromJson(t,r){return(new Zs).fromJson(t,r)}static fromJsonString(t,r){return(new Zs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zs,t,r)}static $(){return["GetOrganizationMemberResponse|1 member #0|2 groups #1*",Ws,Xs]}}class ti extends T{constructor(t){super(),this.teamPublicId="",this.teamName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ti).fromBinary(t,r)}static fromJson(t,r){return(new ti).fromJson(t,r)}static fromJsonString(t,r){return(new ti).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ti,t,r)}static $(){return["OrganizationIdentityProviderUsedByTeam|1 team_public_id 9|2 team_name 9"]}}class ri extends T{constructor(t){super(),this.connected=!1,this.summary="",this.manageLink="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ri).fromBinary(t,r)}static fromJson(t,r){return(new ri).fromJson(t,r)}static fromJsonString(t,r){return(new ri).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ri,t,r)}static $(){return["OrganizationIdentityProviderSsoSettings|1 connected 8|2 summary 9|3 manage_link 9"]}}class ei extends T{constructor(t){super(),this.verified=[],this.pending=[],this.verifyLink="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ei).fromBinary(t,r)}static fromJson(t,r){return(new ei).fromJson(t,r)}static fromJsonString(t,r){return(new ei).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ei,t,r)}static $(){return["OrganizationIdentityProviderDomains|1 verified 9*|2 pending 9*|3 verify_link 9"]}}class ni extends T{constructor(t){super(),this.connected=!1,this.summary="",this.manageLink="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ni).fromBinary(t,r)}static fromJson(t,r){return(new ni).fromJson(t,r)}static fromJsonString(t,r){return(new ni).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ni,t,r)}static $(){return["OrganizationIdentityProviderScimSettings|1 connected 8|2 summary 9|3 manage_link 9"]}}class si extends T{constructor(t){super(),this.enabled=!1,this.allowedDomains=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new si).fromBinary(t,r)}static fromJson(t,r){return(new si).fromJson(t,r)}static fromJsonString(t,r){return(new si).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(si,t,r)}static $(){return["OrganizationIdentityProviderDomainJoinSettings|1 enabled 8|2 allowed_domains 9*"]}}class ii extends T{constructor(t){super(),this.publicId="",this.isDefault=!1,this.status="",this.usedByTeams=[],this.description="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ii).fromBinary(t,r)}static fromJson(t,r){return(new ii).fromJson(t,r)}static fromJsonString(t,r){return(new ii).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ii,t,r)}static $(){return["OrganizationIdentityProvider|1 public_id 9|2 is_default 8|3 status 9|4 used_by_teams #0*|5 description 9|6 sso #1|7 domains #2|8 scim #3|9 domain_join #4",ti,ri,ei,ni,si]}}class oi extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oi).fromBinary(t,r)}static fromJson(t,r){return(new oi).fromJson(t,r)}static fromJsonString(t,r){return(new oi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oi,t,r)}static $(){return["ListOrganizationIdentityProvidersRequest|1 organization_id 9"]}}class ai extends T{constructor(t){super(),this.providers=[],this.mergeEnabled=!1,this.scimInsideIdentityProviderEnabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ai).fromBinary(t,r)}static fromJson(t,r){return(new ai).fromJson(t,r)}static fromJsonString(t,r){return(new ai).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ai,t,r)}static $(){return["ListOrganizationIdentityProvidersResponse|1 providers #0*|2 merge_enabled 8|3 scim_inside_identity_provider_enabled 8",ii]}}class ui extends T{constructor(t){super(),this.organizationId="",this.identityProviderPublicId="",this.allowSso=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ui).fromBinary(t,r)}static fromJson(t,r){return(new ui).fromJson(t,r)}static fromJsonString(t,r){return(new ui).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ui,t,r)}static $(){return["UpdateOrganizationIdentityProviderSsoSettingsRequest|1 organization_id 9|2 identity_provider_public_id 9|3 allow_sso 8"]}}class ci extends T{constructor(t){super(),this.organizationId="",this.identityProviderPublicId="",this.allowDomainJoin=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ci).fromBinary(t,r)}static fromJson(t,r){return(new ci).fromJson(t,r)}static fromJsonString(t,r){return(new ci).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ci,t,r)}static $(){return["SetOrganizationIdentityProviderAllowDomainJoinRequest|1 organization_id 9|2 identity_provider_public_id 9|3 allow_domain_join 8"]}}class li extends T{constructor(t){super(),this.organizationId="",this.identityProviderPublicId="",this.domain="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new li).fromBinary(t,r)}static fromJson(t,r){return(new li).fromJson(t,r)}static fromJsonString(t,r){return(new li).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(li,t,r)}static $(){return["AddOrganizationIdentityProviderDomainJoinRequest|1 organization_id 9|2 identity_provider_public_id 9|3 domain 9"]}}class mi extends T{constructor(t){super(),this.organizationId="",this.identityProviderPublicId="",this.domain="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mi).fromBinary(t,r)}static fromJson(t,r){return(new mi).fromJson(t,r)}static fromJsonString(t,r){return(new mi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mi,t,r)}static $(){return["RemoveOrganizationIdentityProviderDomainJoinRequest|1 organization_id 9|2 identity_provider_public_id 9|3 domain 9"]}}class fi extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fi).fromBinary(t,r)}static fromJson(t,r){return(new fi).fromJson(t,r)}static fromJsonString(t,r){return(new fi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fi,t,r)}static $(){return["UpdateOrganizationIdentityProviderResponse|1 provider #0",ii]}}class di extends T{constructor(t){super(),this.organizationId="",this.sourceIdentityProviderPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new di).fromBinary(t,r)}static fromJson(t,r){return(new di).fromJson(t,r)}static fromJsonString(t,r){return(new di).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(di,t,r)}static $(){return["MergeOrganizationIdentityProviderRequest|1 organization_id 9|2 source_identity_provider_public_id 9"]}}class pi extends T{constructor(t){super(),this.requestPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pi).fromBinary(t,r)}static fromJson(t,r){return(new pi).fromJson(t,r)}static fromJsonString(t,r){return(new pi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pi,t,r)}static $(){return["MergeOrganizationIdentityProviderResponse|1 request_public_id 9"]}}class hi extends T{constructor(t){super(),this.organizationId="",this.sourceIdentityProviderPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hi).fromBinary(t,r)}static fromJson(t,r){return(new hi).fromJson(t,r)}static fromJsonString(t,r){return(new hi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hi,t,r)}static $(){return["PreflightMergeOrganizationIdentityProviderRequest|1 organization_id 9|2 source_identity_provider_public_id 9"]}}class gi extends T{constructor(t){super(),this.code="",this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gi).fromBinary(t,r)}static fromJson(t,r){return(new gi).fromJson(t,r)}static fromJsonString(t,r){return(new gi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gi,t,r)}static $(){return["OrganizationMergeIdpBlocker|1 code 9|2 message 9"]}}class _i extends T{constructor(t){super(),this.canMerge=!1,this.blockers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _i).fromBinary(t,r)}static fromJson(t,r){return(new _i).fromJson(t,r)}static fromJsonString(t,r){return(new _i).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_i,t,r)}static $(){return["PreflightMergeOrganizationIdentityProviderResponse|1 can_merge 8|2 blockers #0*",gi]}}class Ji extends T{constructor(t){super(),this.requestPublicId="",this.status="",this.processedUsers=0,this.movedMembershipCount=0,this.skippedMembershipCount=0,this.failedMembershipCount=0,this.createdAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ji).fromBinary(t,r)}static fromJson(t,r){return(new Ji).fromJson(t,r)}static fromJsonString(t,r){return(new Ji).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ji,t,r)}static $(){return["OrganizationMergeIdpRequestInfo|1 request_public_id 9|2 status 9|3 current_phase 9?|4 source_identity_provider_public_id 9?|5 target_identity_provider_public_id 9?|6 total_users 5?|7 processed_users 5|8 moved_membership_count 5|9 skipped_membership_count 5|10 failed_membership_count 5|11 last_error 9?|12 created_at_ms 3|13 started_at_ms 3?|14 completed_at_ms 3?|15 source_deletion_eligible_at_ms 3?"]}}class wi extends T{constructor(t){super(),this.organizationId="",this.requestPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wi).fromBinary(t,r)}static fromJson(t,r){return(new wi).fromJson(t,r)}static fromJsonString(t,r){return(new wi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wi,t,r)}static $(){return["GetOrganizationMergeIdpRequestRequest|1 organization_id 9|2 request_public_id 9"]}}class yi extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yi).fromBinary(t,r)}static fromJson(t,r){return(new yi).fromJson(t,r)}static fromJsonString(t,r){return(new yi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yi,t,r)}static $(){return["GetOrganizationMergeIdpRequestResponse|1 request #0",Ji]}}class Si extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Si).fromBinary(t,r)}static fromJson(t,r){return(new Si).fromJson(t,r)}static fromJsonString(t,r){return(new Si).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Si,t,r)}static $(){return["ListOrganizationMergeIdpRequestsRequest|1 organization_id 9"]}}class qi extends T{constructor(t){super(),this.requests=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qi).fromBinary(t,r)}static fromJson(t,r){return(new qi).fromJson(t,r)}static fromJsonString(t,r){return(new qi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qi,t,r)}static $(){return["ListOrganizationMergeIdpRequestsResponse|1 requests #0*",Ji]}}class Bi extends T{constructor(t){super(),this.organizationId="",this.userId=0,this.destinationTeamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bi).fromBinary(t,r)}static fromJson(t,r){return(new Bi).fromJson(t,r)}static fromJsonString(t,r){return(new Bi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bi,t,r)}static $(){return["MoveOrganizationMemberToTeamRequest|1 organization_id 9|2 user_id 5|3 destination_team_id 5"]}}class Ii extends T{constructor(t){super(),this.moved=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ii).fromBinary(t,r)}static fromJson(t,r){return(new Ii).fromJson(t,r)}static fromJsonString(t,r){return(new Ii).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ii,t,r)}static $(){return["MoveOrganizationMemberToTeamResponse|1 moved 8"]}}class Pi extends T{constructor(t){super(),this.organizationId="",this.userId=0,this.teamIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pi).fromBinary(t,r)}static fromJson(t,r){return(new Pi).fromJson(t,r)}static fromJsonString(t,r){return(new Pi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pi,t,r)}static $(){return["SetOrganizationMemberTeamsRequest|1 organization_id 9|2 user_id 5|3 team_ids 5*"]}}class bi extends T{constructor(t){super(),this.changed=!1,this.addedTeamIds=[],this.removedTeamIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bi).fromBinary(t,r)}static fromJson(t,r){return(new bi).fromJson(t,r)}static fromJsonString(t,r){return(new bi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bi,t,r)}static $(){return["SetOrganizationMemberTeamsResponse|1 changed 8|2 added_team_ids 5*|3 removed_team_ids 5*"]}}class Ri extends T{constructor(t){super(),this.organizationId="",this.userId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ri).fromBinary(t,r)}static fromJson(t,r){return(new Ri).fromJson(t,r)}static fromJsonString(t,r){return(new Ri).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ri,t,r)}static $(){return["RemoveOrganizationMemberRequest|1 organization_id 9|2 user_id 5"]}}class vi extends T{constructor(t){super(),this.removed=!1,this.removedTeamIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vi).fromBinary(t,r)}static fromJson(t,r){return(new vi).fromJson(t,r)}static fromJsonString(t,r){return(new vi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vi,t,r)}static $(){return["RemoveOrganizationMemberResponse|1 removed 8|2 removed_team_ids 5*"]}}class xi extends T{constructor(t){super(),this.email="",this.destinationTeamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xi).fromBinary(t,r)}static fromJson(t,r){return(new xi).fromJson(t,r)}static fromJsonString(t,r){return(new xi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xi,t,r)}static $(){return["OrganizationMemberTeamMove|1 email 9|2 destination_team_id 5|3 destination_team_name 9?"]}}class ki extends T{constructor(t){super(),this.organizationId="",this.moves=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ki).fromBinary(t,r)}static fromJson(t,r){return(new ki).fromJson(t,r)}static fromJsonString(t,r){return(new ki).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ki,t,r)}static $(){return["BulkMoveOrganizationMembersRequest|1 organization_id 9|2 moves #0*",xi]}}class Ei extends T{constructor(t){super(),this.addedCount=0,this.removedCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ei).fromBinary(t,r)}static fromJson(t,r){return(new Ei).fromJson(t,r)}static fromJsonString(t,r){return(new Ei).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ei,t,r)}static $(){return["BulkOrganizationMemberMoveResult|1 added_count 5|2 removed_count 5|3 error_message 9?"]}}class Ci extends T{constructor(t){super(),this.results=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ci).fromBinary(t,r)}static fromJson(t,r){return(new Ci).fromJson(t,r)}static fromJsonString(t,r){return(new Ci).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ci,t,r)}static $(){return["BulkMoveOrganizationMembersResponse|1 results #0*",Ei]}}class Ti extends T{constructor(t){super(),this.organizationId="",this.moves=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ti).fromBinary(t,r)}static fromJson(t,r){return(new Ti).fromJson(t,r)}static fromJsonString(t,r){return(new Ti).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ti,t,r)}static $(){return["StartBulkMoveOrganizationMembersRequest|1 organization_id 9|2 moves #0*",xi]}}class Ui extends T{constructor(t){super(),this.jobHandle="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ui).fromBinary(t,r)}static fromJson(t,r){return(new Ui).fromJson(t,r)}static fromJsonString(t,r){return(new Ui).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ui,t,r)}static $(){return["StartBulkMoveOrganizationMembersResponse|1 job_handle 9"]}}class Ai extends T{constructor(t){super(),this.jobHandle="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ai).fromBinary(t,r)}static fromJson(t,r){return(new Ai).fromJson(t,r)}static fromJsonString(t,r){return(new Ai).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ai,t,r)}static $(){return["GetBackgroundJobRequest|1 job_handle 9"]}}class $i extends T{constructor(t){super(),this.phase="",this.percentDone=0,this.metadata={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $i).fromBinary(t,r)}static fromJson(t,r){return(new $i).fromJson(t,r)}static fromJsonString(t,r){return(new $i).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($i,t,r)}static $(){return["BackgroundJobStatus|1 phase 9|2 percent_done 2|3 message 9?|4 error 9?|5 metadata 9,9|6 result_json 9?"]}}class Mi extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mi).fromBinary(t,r)}static fromJson(t,r){return(new Mi).fromJson(t,r)}static fromJsonString(t,r){return(new Mi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mi,t,r)}static $(){return["GetBackgroundJobResponse|1 status #0?",$i]}}class Oi extends T{constructor(t){super(),this.organizationId="",this.userId=0,this.role=O.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Oi).fromBinary(t,r)}static fromJson(t,r){return(new Oi).fromJson(t,r)}static fromJsonString(t,r){return(new Oi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Oi,t,r)}static $(){return["SetOrganizationMemberRoleRequest|1 organization_id 9|2 user_id 5|3 role #0",O]}}class Di extends T{constructor(t){super(),this.updated=!1,this.role=O.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Di).fromBinary(t,r)}static fromJson(t,r){return(new Di).fromJson(t,r)}static fromJsonString(t,r){return(new Di).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Di,t,r)}static $(){return["SetOrganizationMemberRoleResponse|1 updated 8|2 role #0",O]}}class Ni extends T{constructor(t){super(),this.organizationId="",this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ni).fromBinary(t,r)}static fromJson(t,r){return(new Ni).fromJson(t,r)}static fromJsonString(t,r){return(new Ni).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ni,t,r)}static $(){return["UpdateOrganizationRequest|1 organization_id 9|2 name 9"]}}class Gi extends T{constructor(t){super(),this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gi).fromBinary(t,r)}static fromJson(t,r){return(new Gi).fromJson(t,r)}static fromJsonString(t,r){return(new Gi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gi,t,r)}static $(){return["UpdateOrganizationResponse|1 name 9"]}}class Li extends T{constructor(t){super(),this.organizationId="",this.contentType="",this.bytes=new Uint8Array(0),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Li).fromBinary(t,r)}static fromJson(t,r){return(new Li).fromJson(t,r)}static fromJsonString(t,r){return(new Li).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Li,t,r)}static $(){return["UploadOrganizationIconRequest|1 organization_id 9|2 content_type 9|3 bytes 12"]}}class Fi extends T{constructor(t){super(),this.iconUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fi).fromBinary(t,r)}static fromJson(t,r){return(new Fi).fromJson(t,r)}static fromJsonString(t,r){return(new Fi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fi,t,r)}static $(){return["UploadOrganizationIconResponse|1 icon_url 9"]}}class Ki extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ki).fromBinary(t,r)}static fromJson(t,r){return(new Ki).fromJson(t,r)}static fromJsonString(t,r){return(new Ki).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ki,t,r)}static $(){return["UpdateOrganizationIconRequest|1 organization_id 9|2 icon_url 9?"]}}class zi extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zi).fromBinary(t,r)}static fromJson(t,r){return(new zi).fromJson(t,r)}static fromJsonString(t,r){return(new zi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zi,t,r)}static $(){return["UpdateOrganizationIconResponse|1 icon_url 9?"]}}class ji extends T{constructor(t){super(),this.organizationId="",this.teamId=0,this.name="",this.slug="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ji).fromBinary(t,r)}static fromJson(t,r){return(new ji).fromJson(t,r)}static fromJsonString(t,r){return(new ji).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ji,t,r)}static $(){return["UpdateOrganizationTeamRequest|1 organization_id 9|2 team_id 5|3 name 9|4 slug 9"]}}class Hi extends T{constructor(t){super(),this.name="",this.slug="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hi).fromBinary(t,r)}static fromJson(t,r){return(new Hi).fromJson(t,r)}static fromJsonString(t,r){return(new Hi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hi,t,r)}static $(){return["UpdateOrganizationTeamResponse|1 name 9|2 slug 9"]}}class Wi extends T{constructor(t){super(),this.organizationId="",this.name="",this.slug="",this.ownerUserId=0,this.identityProviderMode=G.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wi).fromBinary(t,r)}static fromJson(t,r){return(new Wi).fromJson(t,r)}static fromJsonString(t,r){return(new Wi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wi,t,r)}static $(){return["CreateOrganizationTeamRequest|1 organization_id 9|2 name 9|3 slug 9|4 owner_user_id 5|5 scim_mapping #0?|6 identity_provider_mode #1|7 settings_copy #2?",oo,G,Qi]}}class Qi extends T{constructor(t){super(),this.sourceTeamId=0,this.categories=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qi).fromBinary(t,r)}static fromJson(t,r){return(new Qi).fromJson(t,r)}static fromJsonString(t,r){return(new Qi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qi,t,r)}static $(){return["OrganizationTeamSettingsCopy|1 source_team_id 5|2 categories #0*",D]}}class Vi extends T{constructor(t){super(),this.category=D.UNSPECIFIED,this.outcome=N.UNSPECIFIED,this.itemCount=0,this.detail="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vi).fromBinary(t,r)}static fromJson(t,r){return(new Vi).fromJson(t,r)}static fromJsonString(t,r){return(new Vi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vi,t,r)}static $(){return["OrganizationTeamSettingsCopyCategoryResult|1 category #0|2 outcome #1|3 item_count 5|4 detail 9",D,N]}}class Xi extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xi).fromBinary(t,r)}static fromJson(t,r){return(new Xi).fromJson(t,r)}static fromJsonString(t,r){return(new Xi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xi,t,r)}static $(){return["PreviewOrganizationTeamSettingsCopyRequest|1 organization_id 9|2 settings_copy #0|3 target_team_id 5?",Qi]}}class Yi extends T{constructor(t){super(),this.results=[],this.reconnectTypes=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yi).fromBinary(t,r)}static fromJson(t,r){return(new Yi).fromJson(t,r)}static fromJsonString(t,r){return(new Yi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yi,t,r)}static $(){return["PreviewOrganizationTeamSettingsCopyResponse|1 results #0*|2 reconnect_types 9*|3 existing_team #1",Vi,Zi]}}class Zi extends T{constructor(t){super(),this.changedAreas=[],this.setupScriptsRemovedCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zi).fromBinary(t,r)}static fromJson(t,r){return(new Zi).fromJson(t,r)}static fromJsonString(t,r){return(new Zi).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zi,t,r)}static $(){return["OrganizationTeamSettingsCopyExistingTeamPreview|1 changed_areas 9*|2 setup_scripts_removed_count 5|3 team_rules #0|4 refused_reason 9?",to]}}class to extends T{constructor(t){super(),this.addedCount=0,this.skippedExistingNameCount=0,this.notCopiedReason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new to).fromBinary(t,r)}static fromJson(t,r){return(new to).fromJson(t,r)}static fromJsonString(t,r){return(new to).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(to,t,r)}static $(){return["OrganizationTeamSettingsCopyGrokBotTeamRules|1 added_count 5|2 skipped_existing_name_count 5|3 not_copied_reason 9"]}}class ro extends T{constructor(t){super(),this.organizationId="",this.targetTeamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ro).fromBinary(t,r)}static fromJson(t,r){return(new ro).fromJson(t,r)}static fromJsonString(t,r){return(new ro).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ro,t,r)}static $(){return["CopyOrganizationTeamSettingsToTeamRequest|1 organization_id 9|2 target_team_id 5|3 settings_copy #0",Qi]}}class eo extends T{constructor(t){super(),this.results=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eo).fromBinary(t,r)}static fromJson(t,r){return(new eo).fromJson(t,r)}static fromJsonString(t,r){return(new eo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eo,t,r)}static $(){return["CopyOrganizationTeamSettingsToTeamResponse|1 results #0*|2 team_rules #1",Vi,to]}}class no extends T{constructor(t){super(),this.organizationId="",this.targetTeamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new no).fromBinary(t,r)}static fromJson(t,r){return(new no).fromJson(t,r)}static fromJsonString(t,r){return(new no).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(no,t,r)}static $(){return["ListOrganizationTeamSettingsCopySourcesRequest|1 organization_id 9|2 target_team_id 5|3 category #0?",D]}}class so extends T{constructor(t){super(),this.sourceTeams=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new so).fromBinary(t,r)}static fromJson(t,r){return(new so).fromJson(t,r)}static fromJsonString(t,r){return(new so).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(so,t,r)}static $(){return["ListOrganizationTeamSettingsCopySourcesResponse|1 source_teams #0*",io]}}class io extends T{constructor(t){super(),this.teamId=0,this.teamName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new io).fromBinary(t,r)}static fromJson(t,r){return(new io).fromJson(t,r)}static fromJsonString(t,r){return(new io).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(io,t,r)}static $(){return["OrganizationTeamSettingsCopySourceTeam|1 team_id 5|2 team_name 9"]}}class oo extends T{constructor(t){super(),this.scimDirectoryId=n.protoInt64.zero,this.scimGroupExternalId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oo).fromBinary(t,r)}static fromJson(t,r){return(new oo).fromJson(t,r)}static fromJsonString(t,r){return(new oo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oo,t,r)}static $(){return["CreateOrganizationTeamScimMapping|1 scim_directory_id 3|2 scim_group_external_id 9"]}}class ao extends T{constructor(t){super(),this.teamId=0,this.name="",this.slug="",this.settingsCopyResults=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ao).fromBinary(t,r)}static fromJson(t,r){return(new ao).fromJson(t,r)}static fromJsonString(t,r){return(new ao).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ao,t,r)}static $(){return["CreateOrganizationTeamResponse|1 team_id 5|2 name 9|3 slug 9|4 settings_copy_results #0*",Vi]}}class uo extends T{constructor(t){super(),this.teamId=0,this.userId=0,this.step="",this.source=L.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uo).fromBinary(t,r)}static fromJson(t,r){return(new uo).fromJson(t,r)}static fromJsonString(t,r){return(new uo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uo,t,r)}static $(){return["TeamXaiMembershipHold|1 team_id 5|2 user_id 5|3 step 9|4 source #0|5 xai_status 5?|6 well_known_code 9?|7 xai_user_id 9?|8 link_next_step 9?|9 reason 9?|10 held_since #1|11 note 9?",L,n.Timestamp]}}class co extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new co).fromBinary(t,r)}static fromJson(t,r){return(new co).fromJson(t,r)}static fromJsonString(t,r){return(new co).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(co,t,r)}static $(){return["GetOrganizationScimSourceRequest|1 organization_id 9"]}}class lo extends T{constructor(t){super(),this.source=F.UNSPECIFIED,this.resolution=K.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lo).fromBinary(t,r)}static fromJson(t,r){return(new lo).fromJson(t,r)}static fromJsonString(t,r){return(new lo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lo,t,r)}static $(){return["GetOrganizationScimSourceResponse|1 source #0|2 resolution #1",F,K]}}class mo extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mo).fromBinary(t,r)}static fromJson(t,r){return(new mo).fromJson(t,r)}static fromJsonString(t,r){return(new mo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mo,t,r)}static $(){return["GetOrganizationTeamAdminCandidatesRequest|1 organization_id 9"]}}class fo extends T{constructor(t){super(),this.userId=0,this.email="",this.firstName="",this.lastName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fo).fromBinary(t,r)}static fromJson(t,r){return(new fo).fromJson(t,r)}static fromJsonString(t,r){return(new fo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fo,t,r)}static $(){return["OrganizationTeamAdminCandidate|1 user_id 5|2 email 9|3 first_name 9|4 last_name 9"]}}class po extends T{constructor(t){super(),this.candidates=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new po).fromBinary(t,r)}static fromJson(t,r){return(new po).fromJson(t,r)}static fromJsonString(t,r){return(new po).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(po,t,r)}static $(){return["GetOrganizationTeamAdminCandidatesResponse|1 candidates #0*",fo]}}class ho extends T{constructor(t){super(),this.id=n.protoInt64.zero,this.name="",this.organizationId="",this.createdAt=n.protoInt64.zero,this.updatedAt=n.protoInt64.zero,this.memberCount=0,this.publicId="",this.antCyberApproved=!1,this.visibility=H.UNSPECIFIED,this.anthropicEfsStatus=j.UNSPECIFIED,this.isIdpSynced=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ho).fromBinary(t,r)}static fromJson(t,r){return(new ho).fromJson(t,r)}static fromJsonString(t,r){return(new ho).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ho,t,r)}static $(){return["OrganizationGroup|1 id 3|2 name 9|3 organization_id 9|4 created_at 3|5 updated_at 3|6 member_count 5|7 public_id 9|8 monthly_spending_limit_dollars 5?|9 ant_cyber_approved 8|10 ant_cyber_verification_status #0?|11 visibility #1|12 anthropic_efs_status #2|13 is_idp_synced 8|14 slug 9?",z,H,j]}}class go extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new go).fromBinary(t,r)}static fromJson(t,r){return(new go).fromJson(t,r)}static fromJsonString(t,r){return(new go).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(go,t,r)}static $(){return["GetOrganizationGroupsRequest|1 organization_id 9|2 page 5?|3 page_size 5?|4 search_term 9?"]}}class _o extends T{constructor(t){super(),this.groups=[],this.totalGroups=0,this.totalPages=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _o).fromBinary(t,r)}static fromJson(t,r){return(new _o).fromJson(t,r)}static fromJsonString(t,r){return(new _o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_o,t,r)}static $(){return["GetOrganizationGroupsResponse|1 groups #0*|2 total_groups 5|3 total_pages 5",ho]}}class Jo extends T{constructor(t){super(),this.organizationId="",this.groupPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jo).fromBinary(t,r)}static fromJson(t,r){return(new Jo).fromJson(t,r)}static fromJsonString(t,r){return(new Jo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jo,t,r)}static $(){return["GetOrganizationGroupRequest|1 organization_id 9|3 group_public_id 9"]}}class wo extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wo).fromBinary(t,r)}static fromJson(t,r){return(new wo).fromJson(t,r)}static fromJsonString(t,r){return(new wo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wo,t,r)}static $(){return["GetOrganizationGroupResponse|1 group #0",ho]}}class yo extends T{constructor(t){super(),this.userId=0,this.joinedAt=n.protoInt64.zero,this.isAdmin=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yo).fromBinary(t,r)}static fromJson(t,r){return(new yo).fromJson(t,r)}static fromJsonString(t,r){return(new yo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yo,t,r)}static $(){return["OrganizationGroupMember|1 user_id 5|2 email 9?|3 first_name 9?|4 last_name 9?|5 joined_at 3|6 is_admin 8|7 monthly_spending_limit_dollars 5?|8 monthly_usage_cents 5?"]}}class So extends T{constructor(t){super(),this.organizationId="",this.groupPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new So).fromBinary(t,r)}static fromJson(t,r){return(new So).fromJson(t,r)}static fromJsonString(t,r){return(new So).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(So,t,r)}static $(){return["GetOrganizationGroupMembersRequest|1 organization_id 9|3 group_public_id 9|4 page 5?|5 page_size 5?|6 search_term 9?|7 sort_by 9?|8 sort_direction 9?"]}}class qo extends T{constructor(t){super(),this.members=[],this.totalMembers=0,this.totalPages=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qo).fromBinary(t,r)}static fromJson(t,r){return(new qo).fromJson(t,r)}static fromJsonString(t,r){return(new qo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qo,t,r)}static $(){return["GetOrganizationGroupMembersResponse|1 members #0*|2 total_members 5|3 total_pages 5",yo]}}class Bo extends T{constructor(t){super(),this.organizationId="",this.groupId=n.protoInt64.zero,this.userId=0,this.clearMonthlySpendingLimitDollars=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bo).fromBinary(t,r)}static fromJson(t,r){return(new Bo).fromJson(t,r)}static fromJsonString(t,r){return(new Bo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bo,t,r)}static $(){return["UpdateOrganizationGroupMemberRequest|1 organization_id 9|2 group_id 3|3 user_id 5|4 monthly_spending_limit_dollars 5?|5 clear_monthly_spending_limit_dollars 8"]}}class Io extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Io).fromBinary(t,r)}static fromJson(t,r){return(new Io).fromJson(t,r)}static fromJsonString(t,r){return(new Io).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Io,t,r)}static $(){return["UpdateOrganizationGroupMemberResponse|1 member #0",yo]}}class Po extends T{constructor(t){super(),this.organizationId="",this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Po).fromBinary(t,r)}static fromJson(t,r){return(new Po).fromJson(t,r)}static fromJsonString(t,r){return(new Po).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Po,t,r)}static $(){return["CreateOrganizationGroupRequest|1 organization_id 9|2 name 9|3 scim_mapping #0?",bo]}}class bo extends T{constructor(t){super(),this.scimDirectoryId=n.protoInt64.zero,this.scimGroupExternalId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bo).fromBinary(t,r)}static fromJson(t,r){return(new bo).fromJson(t,r)}static fromJsonString(t,r){return(new bo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bo,t,r)}static $(){return["CreateOrganizationGroupScimMapping|1 scim_directory_id 3|2 scim_group_external_id 9"]}}class Ro extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ro).fromBinary(t,r)}static fromJson(t,r){return(new Ro).fromJson(t,r)}static fromJsonString(t,r){return(new Ro).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ro,t,r)}static $(){return["CreateOrganizationGroupResponse|1 group #0|2 shadowing_reviewer_group_handle 9?",ho]}}class vo extends T{constructor(t){super(),this.organizationId="",this.groupId=n.protoInt64.zero,this.name="",this.clearMonthlySpendingLimitDollars=!1,this.visibility=H.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vo).fromBinary(t,r)}static fromJson(t,r){return(new vo).fromJson(t,r)}static fromJsonString(t,r){return(new vo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vo,t,r)}static $(){return["UpdateOrganizationGroupRequest|1 organization_id 9|2 group_id 3|3 name 9|4 monthly_spending_limit_dollars 5?|5 clear_monthly_spending_limit_dollars 8|6 visibility #0",H]}}class xo extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xo).fromBinary(t,r)}static fromJson(t,r){return(new xo).fromJson(t,r)}static fromJsonString(t,r){return(new xo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xo,t,r)}static $(){return["UpdateOrganizationGroupResponse|1 group #0",ho]}}class ko extends T{constructor(t){super(),this.organizationId="",this.groupId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ko).fromBinary(t,r)}static fromJson(t,r){return(new ko).fromJson(t,r)}static fromJsonString(t,r){return(new ko).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ko,t,r)}static $(){return["DeleteOrganizationGroupRequest|1 organization_id 9|2 group_id 3"]}}class Eo extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Eo).fromBinary(t,r)}static fromJson(t,r){return(new Eo).fromJson(t,r)}static fromJsonString(t,r){return(new Eo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Eo,t,r)}static $(){return["DeleteOrganizationGroupResponse"]}}class Co extends T{constructor(t){super(),this.organizationId="",this.groupPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Co).fromBinary(t,r)}static fromJson(t,r){return(new Co).fromJson(t,r)}static fromJsonString(t,r){return(new Co).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Co,t,r)}static $(){return["GetOrganizationGroupAutorunSettingsRequest|1 organization_id 9|2 group_public_id 9"]}}class To extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new To).fromBinary(t,r)}static fromJson(t,r){return(new To).fromJson(t,r)}static fromJsonString(t,r){return(new To).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(To,t,r)}static $(){return["GetOrganizationGroupAutorunSettingsResponse|1 auto_run_controls #0|2 auto_review_run_mode_reset #1",j_,jw]}}class Uo extends T{constructor(t){super(),this.organizationId="",this.groupId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Uo).fromBinary(t,r)}static fromJson(t,r){return(new Uo).fromJson(t,r)}static fromJsonString(t,r){return(new Uo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Uo,t,r)}static $(){return["UpdateOrganizationGroupAutorunSettingsRequest|1 organization_id 9|2 group_id 3|3 auto_run_controls #0",j_]}}class Ao extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ao).fromBinary(t,r)}static fromJson(t,r){return(new Ao).fromJson(t,r)}static fromJsonString(t,r){return(new Ao).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ao,t,r)}static $(){return["UpdateOrganizationGroupAutorunSettingsResponse"]}}class $o extends T{constructor(t){super(),this.organizationId="",this.groupId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $o).fromBinary(t,r)}static fromJson(t,r){return(new $o).fromJson(t,r)}static fromJsonString(t,r){return(new $o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($o,t,r)}static $(){return["ResetOrganizationGroupAgentRunModeToAutoReviewRequest|1 organization_id 9|2 group_id 3"]}}class Mo extends T{constructor(t){super(),this.issuedAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mo).fromBinary(t,r)}static fromJson(t,r){return(new Mo).fromJson(t,r)}static fromJsonString(t,r){return(new Mo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mo,t,r)}static $(){return["ResetOrganizationGroupAgentRunModeToAutoReviewResponse|1 issued_at_ms 3"]}}class Oo extends T{constructor(t){super(),this.organizationId="",this.groupPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Oo).fromBinary(t,r)}static fromJson(t,r){return(new Oo).fromJson(t,r)}static fromJsonString(t,r){return(new Oo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Oo,t,r)}static $(){return["GetOrganizationGroupModelAllowlistRequest|1 organization_id 9|2 group_public_id 9"]}}class Do extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Do).fromBinary(t,r)}static fromJson(t,r){return(new Do).fromJson(t,r)}static fromJsonString(t,r){return(new Do).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Do,t,r)}static $(){return["GetOrganizationGroupModelAllowlistResponse|1 model_allowlist #0?",qw]}}class No extends T{constructor(t){super(),this.organizationId="",this.groupId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new No).fromBinary(t,r)}static fromJson(t,r){return(new No).fromJson(t,r)}static fromJsonString(t,r){return(new No).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(No,t,r)}static $(){return["UpdateOrganizationGroupModelAllowlistRequest|1 organization_id 9|2 group_id 3|3 model_allowlist #0?",qw]}}class Go extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Go).fromBinary(t,r)}static fromJson(t,r){return(new Go).fromJson(t,r)}static fromJsonString(t,r){return(new Go).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Go,t,r)}static $(){return["UpdateOrganizationGroupModelAllowlistResponse"]}}class Lo extends T{constructor(t){super(),this.organizationId="",this.groupPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lo).fromBinary(t,r)}static fromJson(t,r){return(new Lo).fromJson(t,r)}static fromJsonString(t,r){return(new Lo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Lo,t,r)}static $(){return["GetOrganizationGroupAutoReviewSettingsRequest|1 organization_id 9|2 group_public_id 9"]}}class Fo extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fo).fromBinary(t,r)}static fromJson(t,r){return(new Fo).fromJson(t,r)}static fromJsonString(t,r){return(new Fo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fo,t,r)}static $(){return["GetOrganizationGroupAutoReviewSettingsResponse|1 auto_review #0",H_]}}class Ko extends T{constructor(t){super(),this.organizationId="",this.groupId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ko).fromBinary(t,r)}static fromJson(t,r){return(new Ko).fromJson(t,r)}static fromJsonString(t,r){return(new Ko).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ko,t,r)}static $(){return["UpdateOrganizationGroupAutoReviewSettingsRequest|1 organization_id 9|2 group_id 3|3 auto_review #0",H_]}}class zo extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zo).fromBinary(t,r)}static fromJson(t,r){return(new zo).fromJson(t,r)}static fromJsonString(t,r){return(new zo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zo,t,r)}static $(){return["UpdateOrganizationGroupAutoReviewSettingsResponse"]}}class jo extends T{constructor(t){super(),this.organizationId="",this.groupPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jo).fromBinary(t,r)}static fromJson(t,r){return(new jo).fromJson(t,r)}static fromJsonString(t,r){return(new jo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jo,t,r)}static $(){return["GetOrganizationGroupSmartAutoSettingsRequest|1 organization_id 9|2 group_public_id 9"]}}class Ho extends T{constructor(t){super(),this.canEnable=!1,this.memberTeamConflicts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ho).fromBinary(t,r)}static fromJson(t,r){return(new Ho).fromJson(t,r)}static fromJsonString(t,r){return(new Ho).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ho,t,r)}static $(){return["GetOrganizationGroupSmartAutoSettingsResponse|1 settings #0|2 can_enable 8|3 new_chat_nudge_all_to_smart_auto 8?|4 member_team_conflicts #1*|5 models_auto_only 8?|6 new_chat_nudge_all_to_smart_auto_optimize_for 9?",Q$,rM]}}class Wo extends T{constructor(t){super(),this.organizationId="",this.groupId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wo).fromBinary(t,r)}static fromJson(t,r){return(new Wo).fromJson(t,r)}static fromJsonString(t,r){return(new Wo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wo,t,r)}static $(){return["UpdateOrganizationGroupSmartAutoSettingsRequest|1 organization_id 9|2 group_id 3|3 settings #0|4 new_chat_nudge_all_to_smart_auto 8?|5 models_auto_only 8?|6 new_chat_nudge_all_to_smart_auto_optimize_for 9?",Q$]}}class Qo extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qo).fromBinary(t,r)}static fromJson(t,r){return(new Qo).fromJson(t,r)}static fromJsonString(t,r){return(new Qo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qo,t,r)}static $(){return["UpdateOrganizationGroupSmartAutoSettingsResponse"]}}class Vo extends T{constructor(t){super(),this.organizationId="",this.groupId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vo).fromBinary(t,r)}static fromJson(t,r){return(new Vo).fromJson(t,r)}static fromJsonString(t,r){return(new Vo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vo,t,r)}static $(){return["CreateOrganizationGroupAnthropicCyberEnrollmentUrlRequest|1 organization_id 9|2 group_id 3"]}}class Xo extends T{constructor(t){super(),this.enrollmentUrl="",this.userProfileId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xo).fromBinary(t,r)}static fromJson(t,r){return(new Xo).fromJson(t,r)}static fromJsonString(t,r){return(new Xo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xo,t,r)}static $(){return["CreateOrganizationGroupAnthropicCyberEnrollmentUrlResponse|1 enrollment_url 9|2 user_profile_id 9"]}}class Yo extends T{constructor(t){super(),this.organizationId="",this.groupId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yo).fromBinary(t,r)}static fromJson(t,r){return(new Yo).fromJson(t,r)}static fromJsonString(t,r){return(new Yo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yo,t,r)}static $(){return["RequestOrganizationGroupAnthropicEfsRequest|1 organization_id 9|2 group_id 3"]}}class Zo extends T{constructor(t){super(),this.anthropicEfsStatus=j.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zo).fromBinary(t,r)}static fromJson(t,r){return(new Zo).fromJson(t,r)}static fromJsonString(t,r){return(new Zo).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zo,t,r)}static $(){return["RequestOrganizationGroupAnthropicEfsResponse|1 anthropic_efs_status #0",j]}}class ta extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ta).fromBinary(t,r)}static fromJson(t,r){return(new ta).fromJson(t,r)}static fromJsonString(t,r){return(new ta).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ta,t,r)}static $(){return["RequestOrganizationAnthropicEfsRequest|1 organization_id 9"]}}class ra extends T{constructor(t){super(),this.anthropicEfsStatus=j.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ra).fromBinary(t,r)}static fromJson(t,r){return(new ra).fromJson(t,r)}static fromJsonString(t,r){return(new ra).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ra,t,r)}static $(){return["RequestOrganizationAnthropicEfsResponse|1 anthropic_efs_status #0",j]}}class ea extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ea).fromBinary(t,r)}static fromJson(t,r){return(new ea).fromJson(t,r)}static fromJsonString(t,r){return(new ea).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ea,t,r)}static $(){return["GetOrganizationAnthropicEfsStatusRequest|1 organization_id 9"]}}class na extends T{constructor(t){super(),this.anthropicEfsStatus=j.UNSPECIFIED,this.canRequestAnthropicEfs=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new na).fromBinary(t,r)}static fromJson(t,r){return(new na).fromJson(t,r)}static fromJsonString(t,r){return(new na).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(na,t,r)}static $(){return["GetOrganizationAnthropicEfsStatusResponse|1 anthropic_efs_status #0|2 can_request_anthropic_efs 8",j]}}class sa extends T{constructor(t){super(),this.target={case:void 0},this.decision=W.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sa).fromBinary(t,r)}static fromJson(t,r){return(new sa).fromJson(t,r)}static fromJsonString(t,r){return(new sa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sa,t,r)}static $(){return["ReviewAnthropicEfsRequestInternalRequest|1 group_id 3 target|3 organization_id 3 target|2 decision #0",W]}}class ia extends T{constructor(t){super(),this.anthropicEfsStatus=j.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ia).fromBinary(t,r)}static fromJson(t,r){return(new ia).fromJson(t,r)}static fromJsonString(t,r){return(new ia).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ia,t,r)}static $(){return["ReviewAnthropicEfsRequestInternalResponse|1 anthropic_efs_status #0",j]}}class oa extends T{constructor(t){super(),this.organizationId="",this.groupId=n.protoInt64.zero,this.userIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oa).fromBinary(t,r)}static fromJson(t,r){return(new oa).fromJson(t,r)}static fromJsonString(t,r){return(new oa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oa,t,r)}static $(){return["AddOrganizationGroupMembersRequest|1 organization_id 9|2 group_id 3|3 user_ids 5*"]}}class aa extends T{constructor(t){super(),this.addedCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aa).fromBinary(t,r)}static fromJson(t,r){return(new aa).fromJson(t,r)}static fromJsonString(t,r){return(new aa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aa,t,r)}static $(){return["AddOrganizationGroupMembersResponse|1 added_count 5"]}}class ua extends T{constructor(t){super(),this.organizationId="",this.groupId=n.protoInt64.zero,this.userIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ua).fromBinary(t,r)}static fromJson(t,r){return(new ua).fromJson(t,r)}static fromJsonString(t,r){return(new ua).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ua,t,r)}static $(){return["RemoveOrganizationGroupMembersRequest|1 organization_id 9|2 group_id 3|3 user_ids 5*"]}}class ca extends T{constructor(t){super(),this.removedCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ca).fromBinary(t,r)}static fromJson(t,r){return(new ca).fromJson(t,r)}static fromJsonString(t,r){return(new ca).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ca,t,r)}static $(){return["RemoveOrganizationGroupMembersResponse|1 removed_count 5"]}}class la extends T{constructor(t){super(),this.serviceAccountId="",this.name="",this.serviceType="",this.joinedAt=n.protoInt64.zero,this.archived=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new la).fromBinary(t,r)}static fromJson(t,r){return(new la).fromJson(t,r)}static fromJsonString(t,r){return(new la).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(la,t,r)}static $(){return["OrganizationGroupServiceAccountMember|1 service_account_id 9|2 name 9|3 service_type 9|4 owning_team_id 5?|5 owning_team_name 9?|6 joined_at 3|7 archived 8"]}}class ma extends T{constructor(t){super(),this.organizationId="",this.groupPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ma).fromBinary(t,r)}static fromJson(t,r){return(new ma).fromJson(t,r)}static fromJsonString(t,r){return(new ma).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ma,t,r)}static $(){return["GetOrganizationGroupServiceAccountMembersRequest|1 organization_id 9|2 group_public_id 9"]}}class fa extends T{constructor(t){super(),this.serviceAccounts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fa).fromBinary(t,r)}static fromJson(t,r){return(new fa).fromJson(t,r)}static fromJsonString(t,r){return(new fa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fa,t,r)}static $(){return["GetOrganizationGroupServiceAccountMembersResponse|1 service_accounts #0*",la]}}class da extends T{constructor(t){super(),this.serviceAccountId="",this.name="",this.serviceType="",this.owningTeamId=0,this.createdAt=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new da).fromBinary(t,r)}static fromJson(t,r){return(new da).fromJson(t,r)}static fromJsonString(t,r){return(new da).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(da,t,r)}static $(){return["OrganizationServiceAccount|1 service_account_id 9|2 name 9|3 service_type 9|4 owning_team_id 5|5 owning_team_name 9?|6 created_at 3"]}}class pa extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pa).fromBinary(t,r)}static fromJson(t,r){return(new pa).fromJson(t,r)}static fromJsonString(t,r){return(new pa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pa,t,r)}static $(){return["GetOrganizationServiceAccountsRequest|1 organization_id 9"]}}class ha extends T{constructor(t){super(),this.serviceAccounts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ha).fromBinary(t,r)}static fromJson(t,r){return(new ha).fromJson(t,r)}static fromJsonString(t,r){return(new ha).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ha,t,r)}static $(){return["GetOrganizationServiceAccountsResponse|1 service_accounts #0*",da]}}class ga extends T{constructor(t){super(),this.organizationId="",this.groupId=n.protoInt64.zero,this.serviceAccountIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ga).fromBinary(t,r)}static fromJson(t,r){return(new ga).fromJson(t,r)}static fromJsonString(t,r){return(new ga).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ga,t,r)}static $(){return["AddOrganizationGroupServiceAccountsRequest|1 organization_id 9|2 group_id 3|3 service_account_ids 9*"]}}class _a extends T{constructor(t){super(),this.addedCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _a).fromBinary(t,r)}static fromJson(t,r){return(new _a).fromJson(t,r)}static fromJsonString(t,r){return(new _a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_a,t,r)}static $(){return["AddOrganizationGroupServiceAccountsResponse|1 added_count 5"]}}class Ja extends T{constructor(t){super(),this.organizationId="",this.groupId=n.protoInt64.zero,this.serviceAccountIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ja).fromBinary(t,r)}static fromJson(t,r){return(new Ja).fromJson(t,r)}static fromJsonString(t,r){return(new Ja).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ja,t,r)}static $(){return["RemoveOrganizationGroupServiceAccountsRequest|1 organization_id 9|2 group_id 3|3 service_account_ids 9*"]}}class wa extends T{constructor(t){super(),this.removedCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wa).fromBinary(t,r)}static fromJson(t,r){return(new wa).fromJson(t,r)}static fromJsonString(t,r){return(new wa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wa,t,r)}static $(){return["RemoveOrganizationGroupServiceAccountsResponse|1 removed_count 5"]}}class ya extends T{constructor(t){super(),this.id=n.protoInt64.zero,this.name="",this.teamId=0,this.createdAt=n.protoInt64.zero,this.updatedAt=n.protoInt64.zero,this.memberCount=0,this.publicId="",this.antCyberApproved=!1,this.visibility=H.UNSPECIFIED,this.anthropicEfsStatus=j.UNSPECIFIED,this.isIdpSynced=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ya).fromBinary(t,r)}static fromJson(t,r){return(new ya).fromJson(t,r)}static fromJsonString(t,r){return(new ya).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ya,t,r)}static $(){return["TeamGroup|1 id 3|2 name 9|3 team_id 5|4 created_at 3|5 updated_at 3|6 member_count 5|7 public_id 9|8 monthly_spending_limit_dollars 5?|9 ant_cyber_approved 8|10 ant_cyber_verification_status #0?|11 visibility #1|12 grok_bot_enabled 8?|15 cloud_agent_enabled 8?|13 anthropic_efs_status #2|14 is_idp_synced 8|16 slug 9?|17 cursor_enabled 8?",z,H,j]}}class Sa extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sa).fromBinary(t,r)}static fromJson(t,r){return(new Sa).fromJson(t,r)}static fromJsonString(t,r){return(new Sa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sa,t,r)}static $(){return["GetTeamGroupsRequest|1 team_id 5|2 page 5?|3 page_size 5?|4 search_term 9?"]}}class qa extends T{constructor(t){super(),this.groups=[],this.totalGroups=0,this.totalPages=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qa).fromBinary(t,r)}static fromJson(t,r){return(new qa).fromJson(t,r)}static fromJsonString(t,r){return(new qa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qa,t,r)}static $(){return["GetTeamGroupsResponse|1 groups #0*|2 total_groups 5|3 total_pages 5",ya]}}class Ba extends T{constructor(t){super(),this.teamId=0,this.groupPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ba).fromBinary(t,r)}static fromJson(t,r){return(new Ba).fromJson(t,r)}static fromJsonString(t,r){return(new Ba).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ba,t,r)}static $(){return["GetTeamGroupRequest|1 team_id 5|2 group_public_id 9"]}}class Ia extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ia).fromBinary(t,r)}static fromJson(t,r){return(new Ia).fromJson(t,r)}static fromJsonString(t,r){return(new Ia).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ia,t,r)}static $(){return["GetTeamGroupResponse|1 group #0",ya]}}class Pa extends T{constructor(t){super(),this.userId=0,this.joinedAt=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pa).fromBinary(t,r)}static fromJson(t,r){return(new Pa).fromJson(t,r)}static fromJsonString(t,r){return(new Pa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pa,t,r)}static $(){return["TeamGroupMember|1 user_id 5|2 email 9?|3 first_name 9?|4 last_name 9?|5 joined_at 3|6 monthly_spending_limit_dollars 5?|7 spend_cents 5?|8 included_spend_cents 5?|9 overall_spend_cents 5?|10 fast_premium_requests 5?"]}}class ba extends T{constructor(t){super(),this.teamId=0,this.groupPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ba).fromBinary(t,r)}static fromJson(t,r){return(new ba).fromJson(t,r)}static fromJsonString(t,r){return(new ba).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ba,t,r)}static $(){return["GetTeamGroupMembersRequest|1 team_id 5|2 group_public_id 9|3 page 5?|4 page_size 5?|5 search_term 9?|6 sort_by 9?|7 sort_direction 9?"]}}class Ra extends T{constructor(t){super(),this.members=[],this.totalMembers=0,this.totalPages=0,this.isPooledPlan=!1,this.hasTokenBasedPricing=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ra).fromBinary(t,r)}static fromJson(t,r){return(new Ra).fromJson(t,r)}static fromJsonString(t,r){return(new Ra).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ra,t,r)}static $(){return["GetTeamGroupMembersResponse|1 members #0*|2 total_members 5|3 total_pages 5|4 is_pooled_plan 8|5 has_token_based_pricing 8",Pa]}}class va extends T{constructor(t){super(),this.teamId=0,this.name="",this.visibility=H.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new va).fromBinary(t,r)}static fromJson(t,r){return(new va).fromJson(t,r)}static fromJsonString(t,r){return(new va).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(va,t,r)}static $(){return["CreateTeamGroupRequest|1 team_id 5|2 name 9|3 scim_mapping #0?|4 visibility #1",bo,H]}}class xa extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xa).fromBinary(t,r)}static fromJson(t,r){return(new xa).fromJson(t,r)}static fromJsonString(t,r){return(new xa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xa,t,r)}static $(){return["CreateTeamGroupResponse|1 group #0|2 shadowing_reviewer_group_handle 9?",ya]}}class ka extends T{constructor(t){super(),this.teamId=0,this.groupId=n.protoInt64.zero,this.name="",this.clearMonthlySpendingLimitDollars=!1,this.visibility=H.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ka).fromBinary(t,r)}static fromJson(t,r){return(new ka).fromJson(t,r)}static fromJsonString(t,r){return(new ka).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ka,t,r)}static $(){return["UpdateTeamGroupRequest|1 team_id 5|2 group_id 3|3 name 9|4 monthly_spending_limit_dollars 5?|5 clear_monthly_spending_limit_dollars 8|6 visibility #0|7 grok_bot_enabled 8?|8 cloud_agent_enabled 8?|9 cursor_enabled 8?",H]}}class Ea extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ea).fromBinary(t,r)}static fromJson(t,r){return(new Ea).fromJson(t,r)}static fromJsonString(t,r){return(new Ea).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ea,t,r)}static $(){return["UpdateTeamGroupResponse|1 group #0",ya]}}class Ca extends T{constructor(t){super(),this.teamId=0,this.groupId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ca).fromBinary(t,r)}static fromJson(t,r){return(new Ca).fromJson(t,r)}static fromJsonString(t,r){return(new Ca).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ca,t,r)}static $(){return["DeleteTeamGroupRequest|1 team_id 5|2 group_id 3"]}}class Ta extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ta).fromBinary(t,r)}static fromJson(t,r){return(new Ta).fromJson(t,r)}static fromJsonString(t,r){return(new Ta).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ta,t,r)}static $(){return["DeleteTeamGroupResponse"]}}class Ua extends T{constructor(t){super(),this.teamId=0,this.groupId=n.protoInt64.zero,this.userIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ua).fromBinary(t,r)}static fromJson(t,r){return(new Ua).fromJson(t,r)}static fromJsonString(t,r){return(new Ua).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ua,t,r)}static $(){return["AddTeamGroupMembersRequest|1 team_id 5|2 group_id 3|3 user_ids 5*"]}}class Aa extends T{constructor(t){super(),this.addedCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Aa).fromBinary(t,r)}static fromJson(t,r){return(new Aa).fromJson(t,r)}static fromJsonString(t,r){return(new Aa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Aa,t,r)}static $(){return["AddTeamGroupMembersResponse|1 added_count 5"]}}class $a extends T{constructor(t){super(),this.teamId=0,this.groupId=n.protoInt64.zero,this.userIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $a).fromBinary(t,r)}static fromJson(t,r){return(new $a).fromJson(t,r)}static fromJsonString(t,r){return(new $a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($a,t,r)}static $(){return["RemoveTeamGroupMembersRequest|1 team_id 5|2 group_id 3|3 user_ids 5*"]}}class Ma extends T{constructor(t){super(),this.removedCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ma).fromBinary(t,r)}static fromJson(t,r){return(new Ma).fromJson(t,r)}static fromJsonString(t,r){return(new Ma).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ma,t,r)}static $(){return["RemoveTeamGroupMembersResponse|1 removed_count 5"]}}class Oa extends T{constructor(t){super(),this.teamId=0,this.groupId=n.protoInt64.zero,this.userId=0,this.clearMonthlySpendingLimitDollars=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Oa).fromBinary(t,r)}static fromJson(t,r){return(new Oa).fromJson(t,r)}static fromJsonString(t,r){return(new Oa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Oa,t,r)}static $(){return["UpdateTeamGroupMemberRequest|1 team_id 5|2 group_id 3|3 user_id 5|4 monthly_spending_limit_dollars 5?|5 clear_monthly_spending_limit_dollars 8"]}}class Da extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Da).fromBinary(t,r)}static fromJson(t,r){return(new Da).fromJson(t,r)}static fromJsonString(t,r){return(new Da).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Da,t,r)}static $(){return["UpdateTeamGroupMemberResponse|1 member #0",Pa]}}class Na extends T{constructor(t){super(),this.teamId=0,this.groupPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Na).fromBinary(t,r)}static fromJson(t,r){return(new Na).fromJson(t,r)}static fromJsonString(t,r){return(new Na).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Na,t,r)}static $(){return["GetTeamGroupAutorunSettingsRequest|1 team_id 5|2 group_public_id 9"]}}class Ga extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ga).fromBinary(t,r)}static fromJson(t,r){return(new Ga).fromJson(t,r)}static fromJsonString(t,r){return(new Ga).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ga,t,r)}static $(){return["GetTeamGroupAutorunSettingsResponse|1 auto_run_controls #0|2 auto_review_run_mode_reset #1",j_,jw]}}class La extends T{constructor(t){super(),this.teamId=0,this.groupId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new La).fromBinary(t,r)}static fromJson(t,r){return(new La).fromJson(t,r)}static fromJsonString(t,r){return(new La).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(La,t,r)}static $(){return["UpdateTeamGroupAutorunSettingsRequest|1 team_id 5|2 group_id 3|3 auto_run_controls #0",j_]}}class Fa extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fa).fromBinary(t,r)}static fromJson(t,r){return(new Fa).fromJson(t,r)}static fromJsonString(t,r){return(new Fa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fa,t,r)}static $(){return["UpdateTeamGroupAutorunSettingsResponse"]}}class Ka extends T{constructor(t){super(),this.teamId=0,this.groupId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ka).fromBinary(t,r)}static fromJson(t,r){return(new Ka).fromJson(t,r)}static fromJsonString(t,r){return(new Ka).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ka,t,r)}static $(){return["ResetTeamGroupAgentRunModeToAutoReviewRequest|1 team_id 5|2 group_id 3"]}}class za extends T{constructor(t){super(),this.issuedAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new za).fromBinary(t,r)}static fromJson(t,r){return(new za).fromJson(t,r)}static fromJsonString(t,r){return(new za).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(za,t,r)}static $(){return["ResetTeamGroupAgentRunModeToAutoReviewResponse|1 issued_at_ms 3"]}}class ja extends T{constructor(t){super(),this.teamId=0,this.groupPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ja).fromBinary(t,r)}static fromJson(t,r){return(new ja).fromJson(t,r)}static fromJsonString(t,r){return(new ja).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ja,t,r)}static $(){return["GetTeamGroupModelAllowlistRequest|1 team_id 5|2 group_public_id 9"]}}class Ha extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ha).fromBinary(t,r)}static fromJson(t,r){return(new Ha).fromJson(t,r)}static fromJsonString(t,r){return(new Ha).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ha,t,r)}static $(){return["GetTeamGroupModelAllowlistResponse|1 model_allowlist #0?",qw]}}class Wa extends T{constructor(t){super(),this.teamId=0,this.groupId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wa).fromBinary(t,r)}static fromJson(t,r){return(new Wa).fromJson(t,r)}static fromJsonString(t,r){return(new Wa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wa,t,r)}static $(){return["UpdateTeamGroupModelAllowlistRequest|1 team_id 5|2 group_id 3|3 model_allowlist #0?",qw]}}class Qa extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qa).fromBinary(t,r)}static fromJson(t,r){return(new Qa).fromJson(t,r)}static fromJsonString(t,r){return(new Qa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qa,t,r)}static $(){return["UpdateTeamGroupModelAllowlistResponse"]}}class Va extends T{constructor(t){super(),this.teamId=0,this.groupPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Va).fromBinary(t,r)}static fromJson(t,r){return(new Va).fromJson(t,r)}static fromJsonString(t,r){return(new Va).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Va,t,r)}static $(){return["GetTeamGroupAutoReviewSettingsRequest|1 team_id 5|2 group_public_id 9"]}}class Xa extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xa).fromBinary(t,r)}static fromJson(t,r){return(new Xa).fromJson(t,r)}static fromJsonString(t,r){return(new Xa).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xa,t,r)}static $(){return["GetTeamGroupAutoReviewSettingsResponse|1 auto_review #0",H_]}}class Ya extends T{constructor(t){super(),this.teamId=0,this.groupId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ya).fromBinary(t,r)}static fromJson(t,r){return(new Ya).fromJson(t,r)}static fromJsonString(t,r){return(new Ya).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ya,t,r)}static $(){return["UpdateTeamGroupAutoReviewSettingsRequest|1 team_id 5|2 group_id 3|3 auto_review #0",H_]}}class Za extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Za).fromBinary(t,r)}static fromJson(t,r){return(new Za).fromJson(t,r)}static fromJsonString(t,r){return(new Za).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Za,t,r)}static $(){return["UpdateTeamGroupAutoReviewSettingsResponse"]}}class tu extends T{constructor(t){super(),this.applies=!1,this.viewerIsOrgAdmin=!1,this.organizationPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tu).fromBinary(t,r)}static fromJson(t,r){return(new tu).fromJson(t,r)}static fromJsonString(t,r){return(new tu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tu,t,r)}static $(){return["TeamOrganizationNetworkBlocklist|1 applies 8|2 viewer_is_org_admin 8|3 organization_public_id 9|4 entry_counts #0|5 enforced_kinds #1",du,fu]}}class ru extends T{constructor(t){super(),this.enabled=!1,this.shadow=!1,this.entries=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ru).fromBinary(t,r)}static fromJson(t,r){return(new ru).fromJson(t,r)}static fromJsonString(t,r){return(new ru).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ru,t,r)}static $(){return["TeamIngressIpAllowlist|1 enabled 8|2 shadow 8|3 entries #0*",eu]}}class eu extends T{constructor(t){super(),this.cidr="",this.description="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eu).fromBinary(t,r)}static fromJson(t,r){return(new eu).fromJson(t,r)}static fromJsonString(t,r){return(new eu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eu,t,r)}static $(){return["TeamIngressIpAllowlistEntry|1 cidr 9|2 description 9"]}}class nu extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nu).fromBinary(t,r)}static fromJson(t,r){return(new nu).fromJson(t,r)}static fromJsonString(t,r){return(new nu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nu,t,r)}static $(){return["GetTeamIngressIpAllowlistRequest|1 team_id 5"]}}class su extends T{constructor(t){super(),this.available=!1,this.organizationInheritanceAvailable=!1,this.organizationPolicyApplied=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new su).fromBinary(t,r)}static fromJson(t,r){return(new su).fromJson(t,r)}static fromJsonString(t,r){return(new su).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(su,t,r)}static $(){return["GetTeamIngressIpAllowlistResponse|1 available 8|2 allowlist #0|3 organization_inheritance_available 8|4 inherited_organization_allowlist #0|5 organization_policy_applied 8|6 inherited_organization_id 9?",ru]}}class iu extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iu).fromBinary(t,r)}static fromJson(t,r){return(new iu).fromJson(t,r)}static fromJsonString(t,r){return(new iu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iu,t,r)}static $(){return["UpdateTeamIngressIpAllowlistRequest|1 team_id 5|2 allowlist #0",ru]}}class ou extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ou).fromBinary(t,r)}static fromJson(t,r){return(new ou).fromJson(t,r)}static fromJsonString(t,r){return(new ou).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ou,t,r)}static $(){return["UpdateTeamIngressIpAllowlistResponse"]}}class au extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new au).fromBinary(t,r)}static fromJson(t,r){return(new au).fromJson(t,r)}static fromJsonString(t,r){return(new au).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(au,t,r)}static $(){return["GetOrganizationIngressIpAllowlistRequest|1 organization_id 9"]}}class uu extends T{constructor(t){super(),this.available=!1,this.teamInheritanceAvailable=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uu).fromBinary(t,r)}static fromJson(t,r){return(new uu).fromJson(t,r)}static fromJsonString(t,r){return(new uu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uu,t,r)}static $(){return["GetOrganizationIngressIpAllowlistResponse|1 available 8|2 allowlist #0|3 team_inheritance_available 8",ru]}}class cu extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cu).fromBinary(t,r)}static fromJson(t,r){return(new cu).fromJson(t,r)}static fromJsonString(t,r){return(new cu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cu,t,r)}static $(){return["UpdateOrganizationIngressIpAllowlistRequest|1 organization_id 9|2 allowlist #0",ru]}}class lu extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lu).fromBinary(t,r)}static fromJson(t,r){return(new lu).fromJson(t,r)}static fromJsonString(t,r){return(new lu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lu,t,r)}static $(){return["UpdateOrganizationIngressIpAllowlistResponse|1 allowlist #0",ru]}}class mu extends T{constructor(t){super(),this.version=0,this.sha256="",this.entryCount=0,this.rowCount=0,this.updatedAt="",this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mu).fromBinary(t,r)}static fromJson(t,r){return(new mu).fromJson(t,r)}static fromJsonString(t,r){return(new mu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mu,t,r)}static $(){return["OrganizationNetworkBlocklistSummary|1 version 13|2 sha256 9|3 entry_count 13|4 row_count 13|5 updated_at 9|6 enabled 8|7 entry_counts #0|8 enforced_kinds #1|9 grok_bot_direct_entry_count 13?|10 grok_bot_site_rule_cap 13?",du,fu]}}class fu extends T{constructor(t){super(),this.site=!1,this.address=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fu).fromBinary(t,r)}static fromJson(t,r){return(new fu).fromJson(t,r)}static fromJsonString(t,r){return(new fu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fu,t,r)}static $(){return["NetworkBlocklistEntryKinds|1 site 8|3 address 8"]}}class du extends T{constructor(t){super(),this.site=0,this.address=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new du).fromBinary(t,r)}static fromJson(t,r){return(new du).fromJson(t,r)}static fromJsonString(t,r){return(new du).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(du,t,r)}static $(){return["NetworkBlocklistEntryCounts|1 site 13|3 address 13"]}}class pu extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pu).fromBinary(t,r)}static fromJson(t,r){return(new pu).fromJson(t,r)}static fromJsonString(t,r){return(new pu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pu,t,r)}static $(){return["GetOrganizationNetworkBlocklistRequest|1 organization_id 9"]}}class hu extends T{constructor(t){super(),this.available=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hu).fromBinary(t,r)}static fromJson(t,r){return(new hu).fromJson(t,r)}static fromJsonString(t,r){return(new hu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hu,t,r)}static $(){return["GetOrganizationNetworkBlocklistResponse|1 available 8|2 summary #0",mu]}}class gu extends T{constructor(t){super(),this.organizationId="",this.sizeBytes=0,this.sha256=new Uint8Array(0),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gu).fromBinary(t,r)}static fromJson(t,r){return(new gu).fromJson(t,r)}static fromJsonString(t,r){return(new gu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gu,t,r)}static $(){return["CreateOrganizationNetworkBlocklistUploadRequest|1 organization_id 9|2 size_bytes 13|3 sha256 12"]}}class _u extends T{constructor(t){super(),this.uploadId="",this.putUrl="",this.putHeaders={},this.expiresAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _u).fromBinary(t,r)}static fromJson(t,r){return(new _u).fromJson(t,r)}static fromJsonString(t,r){return(new _u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_u,t,r)}static $(){return["CreateOrganizationNetworkBlocklistUploadResponse|1 upload_id 9|2 put_url 9|3 put_headers 9,9|4 expires_at_ms 3"]}}class Ju extends T{constructor(t){super(),this.organizationId="",this.uploadId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ju).fromBinary(t,r)}static fromJson(t,r){return(new Ju).fromJson(t,r)}static fromJsonString(t,r){return(new Ju).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ju,t,r)}static $(){return["CommitOrganizationNetworkBlocklistUploadRequest|1 organization_id 9|2 upload_id 9|3 expected_version 13?"]}}class wu extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wu).fromBinary(t,r)}static fromJson(t,r){return(new wu).fromJson(t,r)}static fromJsonString(t,r){return(new wu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wu,t,r)}static $(){return["CommitOrganizationNetworkBlocklistUploadResponse|1 summary #0",mu]}}class yu extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yu).fromBinary(t,r)}static fromJson(t,r){return(new yu).fromJson(t,r)}static fromJsonString(t,r){return(new yu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yu,t,r)}static $(){return["CreateOrganizationNetworkBlocklistExportRequest|1 organization_id 9"]}}class Su extends T{constructor(t){super(),this.url="",this.expiresAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Su).fromBinary(t,r)}static fromJson(t,r){return(new Su).fromJson(t,r)}static fromJsonString(t,r){return(new Su).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Su,t,r)}static $(){return["CreateOrganizationNetworkBlocklistExportResponse|1 url 9|2 expires_at_ms 3|3 summary #0",mu]}}class qu extends T{constructor(t){super(),this.organizationId="",this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qu).fromBinary(t,r)}static fromJson(t,r){return(new qu).fromJson(t,r)}static fromJsonString(t,r){return(new qu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qu,t,r)}static $(){return["SetOrganizationNetworkBlocklistEnabledRequest|1 organization_id 9|2 enabled 8|3 expected_version 13?"]}}class Bu extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bu).fromBinary(t,r)}static fromJson(t,r){return(new Bu).fromJson(t,r)}static fromJsonString(t,r){return(new Bu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bu,t,r)}static $(){return["SetOrganizationNetworkBlocklistEnabledResponse|1 summary #0",mu]}}class Iu extends T{constructor(t){super(),this.teamId=0,this.groupPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Iu).fromBinary(t,r)}static fromJson(t,r){return(new Iu).fromJson(t,r)}static fromJsonString(t,r){return(new Iu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Iu,t,r)}static $(){return["GetTeamGroupSmartAutoSettingsRequest|1 team_id 5|2 group_public_id 9"]}}class Pu extends T{constructor(t){super(),this.canEnable=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pu).fromBinary(t,r)}static fromJson(t,r){return(new Pu).fromJson(t,r)}static fromJsonString(t,r){return(new Pu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pu,t,r)}static $(){return["GetTeamGroupSmartAutoSettingsResponse|1 settings #0|2 can_enable 8|3 new_chat_nudge_all_to_smart_auto 8?|4 models_auto_only 8?|5 new_chat_nudge_all_to_smart_auto_optimize_for 9?",Q$]}}class bu extends T{constructor(t){super(),this.teamId=0,this.groupId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bu).fromBinary(t,r)}static fromJson(t,r){return(new bu).fromJson(t,r)}static fromJsonString(t,r){return(new bu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bu,t,r)}static $(){return["UpdateTeamGroupSmartAutoSettingsRequest|1 team_id 5|2 group_id 3|3 settings #0|4 new_chat_nudge_all_to_smart_auto 8?|5 models_auto_only 8?|6 new_chat_nudge_all_to_smart_auto_optimize_for 9?",Q$]}}class Ru extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ru).fromBinary(t,r)}static fromJson(t,r){return(new Ru).fromJson(t,r)}static fromJsonString(t,r){return(new Ru).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ru,t,r)}static $(){return["UpdateTeamGroupSmartAutoSettingsResponse"]}}class vu extends T{constructor(t){super(),this.teamId=0,this.groupId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vu).fromBinary(t,r)}static fromJson(t,r){return(new vu).fromJson(t,r)}static fromJsonString(t,r){return(new vu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vu,t,r)}static $(){return["CreateTeamGroupAnthropicCyberEnrollmentUrlRequest|1 team_id 5|2 group_id 3"]}}class xu extends T{constructor(t){super(),this.enrollmentUrl="",this.userProfileId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xu).fromBinary(t,r)}static fromJson(t,r){return(new xu).fromJson(t,r)}static fromJsonString(t,r){return(new xu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xu,t,r)}static $(){return["CreateTeamGroupAnthropicCyberEnrollmentUrlResponse|1 enrollment_url 9|2 user_profile_id 9"]}}class ku extends T{constructor(t){super(),this.teamId=0,this.groupId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ku).fromBinary(t,r)}static fromJson(t,r){return(new ku).fromJson(t,r)}static fromJsonString(t,r){return(new ku).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ku,t,r)}static $(){return["RequestTeamGroupAnthropicEfsRequest|1 team_id 5|2 group_id 3"]}}class Eu extends T{constructor(t){super(),this.anthropicEfsStatus=j.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Eu).fromBinary(t,r)}static fromJson(t,r){return(new Eu).fromJson(t,r)}static fromJsonString(t,r){return(new Eu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Eu,t,r)}static $(){return["RequestTeamGroupAnthropicEfsResponse|1 anthropic_efs_status #0",j]}}class Cu extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cu).fromBinary(t,r)}static fromJson(t,r){return(new Cu).fromJson(t,r)}static fromJsonString(t,r){return(new Cu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cu,t,r)}static $(){return["GetTeamAnthropicEfsStatusRequest|1 team_id 5"]}}class Tu extends T{constructor(t){super(),this.organizationAnthropicEfsStatus=j.UNSPECIFIED,this.canRequestAnthropicEfs=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tu).fromBinary(t,r)}static fromJson(t,r){return(new Tu).fromJson(t,r)}static fromJsonString(t,r){return(new Tu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tu,t,r)}static $(){return["GetTeamAnthropicEfsStatusResponse|1 organization_anthropic_efs_status #0|2 can_request_anthropic_efs 8",j]}}class Uu extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Uu).fromBinary(t,r)}static fromJson(t,r){return(new Uu).fromJson(t,r)}static fromJsonString(t,r){return(new Uu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Uu,t,r)}static $(){return["ListTeamGroupScimDirectoriesRequest|1 team_id 5"]}}class Au extends T{constructor(t){super(),this.directories=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Au).fromBinary(t,r)}static fromJson(t,r){return(new Au).fromJson(t,r)}static fromJsonString(t,r){return(new Au).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Au,t,r)}static $(){return["ListTeamGroupScimDirectoriesResponse|1 directories #0*",YE]}}class $u extends T{constructor(t){super(),this.teamId=0,this.scimDirectoryId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $u).fromBinary(t,r)}static fromJson(t,r){return(new $u).fromJson(t,r)}static fromJsonString(t,r){return(new $u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($u,t,r)}static $(){return["ListTeamGroupScimGroupsFromUpstreamRequest|1 team_id 5|2 scim_directory_id 3"]}}class Mu extends T{constructor(t){super(),this.groups=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mu).fromBinary(t,r)}static fromJson(t,r){return(new Mu).fromJson(t,r)}static fromJsonString(t,r){return(new Mu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mu,t,r)}static $(){return["ListTeamGroupScimGroupsFromUpstreamResponse|1 groups #0*",aC]}}class Ou extends T{constructor(t){super(),this.teamId=0,this.groupPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ou).fromBinary(t,r)}static fromJson(t,r){return(new Ou).fromJson(t,r)}static fromJsonString(t,r){return(new Ou).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ou,t,r)}static $(){return["ListTeamGroupScimTargetMappingsRequest|1 team_id 5|2 group_public_id 9"]}}class Du extends T{constructor(t){super(),this.mappings=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Du).fromBinary(t,r)}static fromJson(t,r){return(new Du).fromJson(t,r)}static fromJsonString(t,r){return(new Du).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Du,t,r)}static $(){return["ListTeamGroupScimTargetMappingsResponse|1 mappings #0*",lC]}}class Nu extends T{constructor(t){super(),this.teamId=0,this.groupId=n.protoInt64.zero,this.scimDirectoryId=n.protoInt64.zero,this.scimGroupExternalId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nu).fromBinary(t,r)}static fromJson(t,r){return(new Nu).fromJson(t,r)}static fromJsonString(t,r){return(new Nu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nu,t,r)}static $(){return["CreateTeamGroupScimTargetMappingRequest|1 team_id 5|2 group_id 3|3 scim_directory_id 3|4 scim_group_external_id 9"]}}class Gu extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gu).fromBinary(t,r)}static fromJson(t,r){return(new Gu).fromJson(t,r)}static fromJsonString(t,r){return(new Gu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gu,t,r)}static $(){return["CreateTeamGroupScimTargetMappingResponse|1 mapping #0",lC]}}class Lu extends T{constructor(t){super(),this.teamId=0,this.groupId=n.protoInt64.zero,this.scimTargetMappingId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lu).fromBinary(t,r)}static fromJson(t,r){return(new Lu).fromJson(t,r)}static fromJsonString(t,r){return(new Lu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Lu,t,r)}static $(){return["DeleteTeamGroupScimTargetMappingRequest|1 team_id 5|2 group_id 3|3 scim_target_mapping_id 3"]}}class Fu extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fu).fromBinary(t,r)}static fromJson(t,r){return(new Fu).fromJson(t,r)}static fromJsonString(t,r){return(new Fu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fu,t,r)}static $(){return["DeleteTeamGroupScimTargetMappingResponse"]}}class Ku extends T{constructor(t){super(),this.teamId=0,this.privacyModeForced=!1,this.privacyMode=s.Y.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ku).fromBinary(t,r)}static fromJson(t,r){return(new Ku).fromJson(t,r)}static fromJsonString(t,r){return(new Ku).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ku,t,r)}static $(){return["SwitchTeamPrivacyModeRequest|1 team_id 5|2 privacy_mode_forced 8|3 privacy_mode #0",s.Y]}}class zu extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zu).fromBinary(t,r)}static fromJson(t,r){return(new zu).fromJson(t,r)}static fromJsonString(t,r){return(new zu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zu,t,r)}static $(){return["SwitchTeamPrivacyModeResponse"]}}class ju extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ju).fromBinary(t,r)}static fromJson(t,r){return(new ju).fromJson(t,r)}static fromJsonString(t,r){return(new ju).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ju,t,r)}static $(){return["GetTeamPrivacyModeForcedRequest|1 team_id 5"]}}class Hu extends T{constructor(t){super(),this.privacyModeForced=!1,this.privacyMode=s.Y.UNSPECIFIED,this.privacyModeMigrationOptedOut=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hu).fromBinary(t,r)}static fromJson(t,r){return(new Hu).fromJson(t,r)}static fromJsonString(t,r){return(new Hu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hu,t,r)}static $(){return["GetTeamPrivacyModeForcedResponse|1 privacy_mode_forced 8|2 privacy_mode #0|3 privacy_mode_migration_opted_out 8",s.Y]}}class Wu extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wu).fromBinary(t,r)}static fromJson(t,r){return(new Wu).fromJson(t,r)}static fromJsonString(t,r){return(new Wu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wu,t,r)}static $(){return["GetTeamXaiDataRetentionRequest|1 team_id 5"]}}class Qu extends T{constructor(t){super(),this.retention=Q.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qu).fromBinary(t,r)}static fromJson(t,r){return(new Qu).fromJson(t,r)}static fromJsonString(t,r){return(new Qu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qu,t,r)}static $(){return["GetTeamXaiDataRetentionResponse|1 retention #0",Q]}}class Vu extends T{constructor(t){super(),this.kind={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vu).fromBinary(t,r)}static fromJson(t,r){return(new Vu).fromJson(t,r)}static fromJsonString(t,r){return(new Vu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vu,t,r)}static $(){return["BackgroundComposerSecretOwner|1 user 8 kind|2 team 8 kind|3 environment_id 9 kind"]}}class Xu extends T{constructor(t){super(),this.appIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xu).fromBinary(t,r)}static fromJson(t,r){return(new Xu).fromJson(t,r)}static fromJsonString(t,r){return(new Xu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xu,t,r)}static $(){return["BackgroundComposerSecretAppScope|1 app_ids 9*"]}}class Yu extends T{constructor(t){super(),this.teamScope=!1,this.surface=Y.UNSPECIFIED,this.includeMemberSecrets=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yu).fromBinary(t,r)}static fromJson(t,r){return(new Yu).fromJson(t,r)}static fromJsonString(t,r){return(new Yu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yu,t,r)}static $(){return["ListBackgroundComposerSecretsRequest|1 team_scope 8|2 owner #0|3 surface #1|4 include_member_secrets 8",Vu,Y]}}class Zu extends T{constructor(t){super(),this.secrets=[],this.truncated=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zu).fromBinary(t,r)}static fromJson(t,r){return(new Zu).fromJson(t,r)}static fromJsonString(t,r){return(new Zu).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zu,t,r)}static $(){return["ListBackgroundComposerSecretsResponse|1 secrets #0*|2 truncated 8",rc]}}class tc extends T{constructor(t){super(),this.appId=n.protoInt64.zero,this.slug="",this.apex="",this.live=!1,this.displayName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tc).fromBinary(t,r)}static fromJson(t,r){return(new tc).fromJson(t,r)}static fromJsonString(t,r){return(new tc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tc,t,r)}static $(){return["ListBackgroundComposerSecretsResponse.BoundApp|1 app_id 3|2 slug 9|3 apex 9|4 live 8|5 display_name 9"]}}class rc extends T{constructor(t){super(),this.name="",this.createdAt=0,this.scopedToRepos=[],this.level=V.UNSPECIFIED,this.id=0,this.surface=Y.UNSPECIFIED,this.boundApps=[],this.bindingCount=0,this.scopedToApps=[],this.httpScheme=X.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rc).fromBinary(t,r)}static fromJson(t,r){return(new rc).fromJson(t,r)}static fromJsonString(t,r){return(new rc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rc,t,r)}static $(){return["ListBackgroundComposerSecretsResponse.Secret|1 name 9|2 created_at 1|3 scoped_to_repos 9*|4 level #0|5 id 5|6 owner #1|7 surface #2|8 owner_user_id 5?|9 owner_email 9?|10 owner_name 9?|11 bound_apps #3*|12 binding_count 5|13 scoped_to_apps 9*|14 http_scheme #4|15 http_host 9?|16 http_username_placeholder 9?|17 http_placeholder 9?|18 http_header_name 9?|19 http_value_prefix 9?",V,Vu,Y,tc,X]}}class ec extends T{constructor(t){super(),this.name="",this.value="",this.teamScope=!1,this.scopedToRepos=[],this.level=V.UNSPECIFIED,this.surface=Y.UNSPECIFIED,this.httpScheme=X.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ec).fromBinary(t,r)}static fromJson(t,r){return(new ec).fromJson(t,r)}static fromJsonString(t,r){return(new ec).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ec,t,r)}static $(){return["CreateBackgroundComposerSecretRequest|1 name 9|2 value 9|3 team_scope 8|4 scoped_to_repos 9*|5 level #0|6 owner #1|7 surface #2|8 http_scheme #3|9 http_host 9?|10 http_username 9?|11 http_header_name 9?|12 http_value_prefix 9?",V,Vu,Y,X]}}class nc extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nc).fromBinary(t,r)}static fromJson(t,r){return(new nc).fromJson(t,r)}static fromJsonString(t,r){return(new nc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nc,t,r)}static $(){return["CreateBackgroundComposerSecretResponse"]}}class sc extends T{constructor(t){super(),this.secrets=[],this.teamScope=!1,this.scopedToRepos=[],this.surface=Y.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sc).fromBinary(t,r)}static fromJson(t,r){return(new sc).fromJson(t,r)}static fromJsonString(t,r){return(new sc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sc,t,r)}static $(){return["CreateBackgroundComposerSecretBatchRequest|1 secrets #0*|2 team_scope 8|3 scoped_to_repos 9*|4 owner #1|5 surface #2|6 app_scope #3",ic,Vu,Y,Xu]}}class ic extends T{constructor(t){super(),this.name="",this.value="",this.level=V.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ic).fromBinary(t,r)}static fromJson(t,r){return(new ic).fromJson(t,r)}static fromJsonString(t,r){return(new ic).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ic,t,r)}static $(){return["CreateBackgroundComposerSecretBatchRequest.Secret|1 name 9|2 value 9|3 level #0",V]}}class oc extends T{constructor(t){super(),this.results=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oc).fromBinary(t,r)}static fromJson(t,r){return(new oc).fromJson(t,r)}static fromJsonString(t,r){return(new oc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oc,t,r)}static $(){return["CreateBackgroundComposerSecretBatchResponse|1 results #0*",cc]}}var ac=(0,a.QT)(n.proto3,C,"CreateBackgroundComposerSecretBatchResponse.Status",[[0,"UNSPECIFIED"],[1,"CREATED"],[2,"UPDATED"],[3,"ERROR"]],1),uc=(0,a.QT)(n.proto3,C,"CreateBackgroundComposerSecretBatchResponse.ErrorType",[[0,"UNSPECIFIED"],[1,"BAD_REQUEST"],[2,"UNAUTHORIZED"],[3,"INTERNAL"]],1);class cc extends T{constructor(t){super(),this.name="",this.status=ac.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cc).fromBinary(t,r)}static fromJson(t,r){return(new cc).fromJson(t,r)}static fromJsonString(t,r){return(new cc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cc,t,r)}static $(){return["CreateBackgroundComposerSecretBatchResponse.Result|1 name 9|2 status #0|3 error_message 9?|4 error_type #1?",ac,uc]}}class lc extends T{constructor(t){super(),this.name="",this.teamScope=!1,this.id=0,this.surface=Y.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lc).fromBinary(t,r)}static fromJson(t,r){return(new lc).fromJson(t,r)}static fromJsonString(t,r){return(new lc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lc,t,r)}static $(){return["RevokeBackgroundComposerSecretRequest|1 name 9|2 team_scope 8|3 id 5|4 owner #0|5 surface #1",Vu,Y]}}class mc extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mc).fromBinary(t,r)}static fromJson(t,r){return(new mc).fromJson(t,r)}static fromJsonString(t,r){return(new mc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mc,t,r)}static $(){return["RevokeBackgroundComposerSecretResponse"]}}class fc extends T{constructor(t){super(),this.name="",this.teamScope=!1,this.scopedToRepos=[],this.level=V.UNSPECIFIED,this.id=0,this.surface=Y.UNSPECIFIED,this.httpScheme=X.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fc).fromBinary(t,r)}static fromJson(t,r){return(new fc).fromJson(t,r)}static fromJsonString(t,r){return(new fc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fc,t,r)}static $(){return["UpdateBackgroundComposerSecretRequest|1 name 9|2 team_scope 8|3 scoped_to_repos 9*|4 level #0|5 value 9?|6 id 5|7 owner #1|8 surface #2|9 app_scope #3|10 http_scheme #4|11 http_host 9?|12 http_username 9?|13 http_header_name 9?|14 http_value_prefix 9?",V,Vu,Y,Xu,X]}}class dc extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dc).fromBinary(t,r)}static fromJson(t,r){return(new dc).fromJson(t,r)}static fromJsonString(t,r){return(new dc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dc,t,r)}static $(){return["UpdateBackgroundComposerSecretResponse"]}}class pc extends T{constructor(t){super(),this.agentId="",this.sessionKind="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pc).fromBinary(t,r)}static fromJson(t,r){return(new pc).fromJson(t,r)}static fromJsonString(t,r){return(new pc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pc,t,r)}static $(){return["GrokBotPluginScope|1 agent_id 9|2 session_kind 9"]}}class hc extends T{constructor(t){super(),this.serverIdentifier="",this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hc).fromBinary(t,r)}static fromJson(t,r){return(new hc).fromJson(t,r)}static fromJsonString(t,r){return(new hc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hc,t,r)}static $(){return["SetGrokConnectorEnabledRequest|1 server_identifier 9|2 enabled 8"]}}class gc extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gc).fromBinary(t,r)}static fromJson(t,r){return(new gc).fromJson(t,r)}static fromJsonString(t,r){return(new gc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gc,t,r)}static $(){return["SetGrokConnectorEnabledResponse"]}}class _c extends T{constructor(t){super(),this.reason=rt.UNSPECIFIED,this.signedOutAtMs=n.protoInt64.zero,this.clientConfigured=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _c).fromBinary(t,r)}static fromJson(t,r){return(new _c).fromJson(t,r)}static fromJsonString(t,r){return(new _c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_c,t,r)}static $(){return["McpSignOut|1 reason #0|2 signed_out_at_ms 3|3 client_configured 8",rt]}}class Jc extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jc).fromBinary(t,r)}static fromJson(t,r){return(new Jc).fromJson(t,r)}static fromJsonString(t,r){return(new Jc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jc,t,r)}static $(){return["GetTeamHasValidPaymentMethodRequest|1 team_id 5"]}}class wc extends T{constructor(t){super(),this.hasValidPaymentMethod=!1,this.trialDaysRemaining=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wc).fromBinary(t,r)}static fromJson(t,r){return(new wc).fromJson(t,r)}static fromJsonString(t,r){return(new wc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wc,t,r)}static $(){return["GetTeamHasValidPaymentMethodResponse|1 has_valid_payment_method 8|2 trial_days_remaining 5"]}}class yc extends T{constructor(t){super(),this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yc).fromBinary(t,r)}static fromJson(t,r){return(new yc).fromJson(t,r)}static fromJsonString(t,r){return(new yc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yc,t,r)}static $(){return["CreateTeamWithFreeTrialRequest|1 name 9|2 privacy_mode_forced 8?|3 free_trial_code 9?"]}}class Sc extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sc).fromBinary(t,r)}static fromJson(t,r){return(new Sc).fromJson(t,r)}static fromJsonString(t,r){return(new Sc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sc,t,r)}static $(){return["CreateTeamWithFreeTrialResponse|1 team_id 5"]}}class qc extends T{constructor(t){super(),this.name="",this.inviteCode="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qc).fromBinary(t,r)}static fromJson(t,r){return(new qc).fromJson(t,r)}static fromJsonString(t,r){return(new qc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qc,t,r)}static $(){return["CreateTeamWithOrgRequest|1 name 9|2 invite_code 9|3 privacy_mode_forced 8?"]}}class Bc extends T{constructor(t){super(),this.teamId=0,this.orgId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bc).fromBinary(t,r)}static fromJson(t,r){return(new Bc).fromJson(t,r)}static fromJsonString(t,r){return(new Bc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bc,t,r)}static $(){return["CreateTeamWithOrgResponse|1 team_id 5|2 org_id 3"]}}class Ic extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ic).fromBinary(t,r)}static fromJson(t,r){return(new Ic).fromJson(t,r)}static fromJsonString(t,r){return(new Ic).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ic,t,r)}static $(){return["GetPricingHistoryRequest"]}}class Pc extends T{constructor(t){super(),this.pricingHistory=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pc).fromBinary(t,r)}static fromJson(t,r){return(new Pc).fromJson(t,r)}static fromJsonString(t,r){return(new Pc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pc,t,r)}static $(){return["GetPricingHistoryResponse|1 pricing_history #0*",bc]}}class bc extends T{constructor(t){super(),this.description="",this.id="",this.changelog="",this.createdAt=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bc).fromBinary(t,r)}static fromJson(t,r){return(new bc).fromJson(t,r)}static fromJsonString(t,r){return(new bc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bc,t,r)}static $(){return["GetPricingHistoryResponse.PricingDescription|1 description 9|2 id 9|3 changelog 9|4 created_at 3"]}}class Rc extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rc).fromBinary(t,r)}static fromJson(t,r){return(new Rc).fromJson(t,r)}static fromJsonString(t,r){return(new Rc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rc,t,r)}static $(){return["ListInvoiceCyclesRequest|1 team_id 5?"]}}class vc extends T{constructor(t){super(),this.startMs=n.protoInt64.zero,this.type=et.UNSPECIFIED,this.endMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vc).fromBinary(t,r)}static fromJson(t,r){return(new vc).fromJson(t,r)}static fromJsonString(t,r){return(new vc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vc,t,r)}static $(){return["InvoiceCycle|1 start_ms 3|2 type #0|3 end_ms 3",et]}}class xc extends T{constructor(t){super(),this.cycles=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xc).fromBinary(t,r)}static fromJson(t,r){return(new xc).fromJson(t,r)}static fromJsonString(t,r){return(new xc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xc,t,r)}static $(){return["ListInvoiceCyclesResponse|1 cycles #0*",vc]}}class kc extends T{constructor(t){super(),this.month=0,this.year=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kc).fromBinary(t,r)}static fromJson(t,r){return(new kc).fromJson(t,r)}static fromJsonString(t,r){return(new kc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kc,t,r)}static $(){return["GetMonthlyInvoiceRequest|1 team_id 5?|2 month 5|3 year 5|4 include_usage_events 8?|5 cycle_filter_type #0?|6 start_time_ms 3?|7 use_current_cycle 8?",et]}}class Ec extends T{constructor(t){super(),this.items=[],this.usageEvents=[],this.isUsageEventsMaybeCutoff=!1,this.hasUnpaidMidMonthInvoice=!1,this.lastHardLimitCents=0,this.periodStartMs=n.protoInt64.zero,this.periodEndMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ec).fromBinary(t,r)}static fromJson(t,r){return(new Ec).fromJson(t,r)}static fromJsonString(t,r){return(new Ec).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ec,t,r)}static $(){return["GetMonthlyInvoiceResponse|1 items #0*|2 pricing_description #1|3 usage_events #2*|4 is_usage_events_maybe_cutoff 8|5 has_unpaid_mid_month_invoice 8|6 last_hard_limit_cents 5|7 period_start_ms 3|8 period_end_ms 3|9 not_applicable #3?",Cc,Tc,i.aq,Uc]}}class Cc extends T{constructor(t){super(),this.description="",this.cents=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cc).fromBinary(t,r)}static fromJson(t,r){return(new Cc).fromJson(t,r)}static fromJsonString(t,r){return(new Cc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cc,t,r)}static $(){return["GetMonthlyInvoiceResponse.InvoiceItem|1 description 9|2 cents 5"]}}class Tc extends T{constructor(t){super(),this.description="",this.id="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tc).fromBinary(t,r)}static fromJson(t,r){return(new Tc).fromJson(t,r)}static fromJsonString(t,r){return(new Tc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tc,t,r)}static $(){return["GetMonthlyInvoiceResponse.PricingDescription|1 description 9|2 id 9"]}}class Uc extends T{constructor(t){super(),this.reason=Ac.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Uc).fromBinary(t,r)}static fromJson(t,r){return(new Uc).fromJson(t,r)}static fromJsonString(t,r){return(new Uc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Uc,t,r)}static $(){return["GetMonthlyInvoiceResponse.NotApplicable|1 reason #0",Ac]}}var Ac=(0,a.QT)(n.proto3,C,"GetMonthlyInvoiceResponse.NotApplicable.Reason",[[0,"UNSPECIFIED"],[1,"BILLED_BY_XAI"]],1);class $c extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $c).fromBinary(t,r)}static fromJson(t,r){return(new $c).fromJson(t,r)}static fromJsonString(t,r){return(new $c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($c,t,r)}static $(){return["GetHardLimitRequest|1 team_id 5?|2 personal_scope 8?"]}}class Mc extends T{constructor(t){super(),this.hardLimit=0,this.noUsageBasedAllowed=!1,this.perUserMonthlyLimitDollars=0,this.isDynamicTeamLimit=!1,this.hasPendingSetupOnboardingCreditClaim=!1,this.isSetupPromoActive=!1,this.onDemandSpendDisabledByOrganization=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mc).fromBinary(t,r)}static fromJson(t,r){return(new Mc).fromJson(t,r)}static fromJsonString(t,r){return(new Mc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mc,t,r)}static $(){return["GetHardLimitResponse|1 hard_limit 5|2 no_usage_based_allowed 8|3 hard_limit_per_user 5?|4 per_user_monthly_limit_dollars 5|5 is_dynamic_team_limit 8|6 has_pending_setup_onboarding_credit_claim 8|7 is_setup_promo_active 8|8 setup_promo_amount_cents 5?|9 setup_promo_credit_validity_days 5?|10 on_demand_spend_disabled_by_organization 8|11 per_user_first_party_models_additional_budget_dollars 5?|12 per_user_first_party_models_additional_budget_unlimited 8?"]}}class Oc extends T{constructor(t){super(),this.hardLimit=0,this.noUsageBasedAllowed=!1,this.preserveHardLimitPerUser=!1,this.perUserMonthlyLimitDollars=0,this.clearPerUserMonthlyLimitDollars=!1,this.isDynamicTeamLimit=!1,this.clearConflictingPolicy=!1,this.clearPerUserFirstPartyModelsAdditionalBudgetDollars=!1,this.clearPerUserFirstPartyModelsAdditionalBudgetUnlimited=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Oc).fromBinary(t,r)}static fromJson(t,r){return(new Oc).fromJson(t,r)}static fromJsonString(t,r){return(new Oc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Oc,t,r)}static $(){return["SetHardLimitRequest|1 team_id 5?|2 hard_limit 5|3 no_usage_based_allowed 8|4 hard_limit_per_user 5?|5 preserve_hard_limit_per_user 8|6 per_user_monthly_limit_dollars 5|7 clear_per_user_monthly_limit_dollars 8|8 is_dynamic_team_limit 8|9 clear_conflicting_policy 8|10 auto_alerts_enabled 8?|11 per_user_first_party_models_additional_budget_dollars 5?|12 clear_per_user_first_party_models_additional_budget_dollars 8|13 per_user_first_party_models_additional_budget_unlimited 8?|14 clear_per_user_first_party_models_additional_budget_unlimited 8|15 personal_scope 8?"]}}class Dc extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dc).fromBinary(t,r)}static fromJson(t,r){return(new Dc).fromJson(t,r)}static fromJsonString(t,r){return(new Dc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dc,t,r)}static $(){return["SetHardLimitResponse"]}}class Nc extends T{constructor(t){super(),this.notifyAdminUserIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nc).fromBinary(t,r)}static fromJson(t,r){return(new Nc).fromJson(t,r)}static fromJsonString(t,r){return(new Nc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nc,t,r)}static $(){return["LinkedUsageAlertPolicy|1 alert_id 9?|2 threshold_bps 5?|3 notification_mode 9?|4 notify_all_admins 8?|5 notify_admin_user_ids 5*|6 notify_member 8?"]}}class Gc extends T{constructor(t){super(),this.scope=nt.UNSPECIFIED,this.type=st.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gc).fromBinary(t,r)}static fromJson(t,r){return(new Gc).fromJson(t,r)}static fromJsonString(t,r){return(new Gc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gc,t,r)}static $(){return["SpendLimitPolicy|1 scope #0|2 type #1|3 amount_dollars 5?|4 is_dynamic_team_limit 8?|5 resource_threshold_id 9?|6 linked_alert #2?|7 auto_alerts_enabled 8?",nt,st,Nc]}}class Lc extends T{constructor(t){super(),this.teamId=0,this.scope=nt.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lc).fromBinary(t,r)}static fromJson(t,r){return(new Lc).fromJson(t,r)}static fromJsonString(t,r){return(new Lc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Lc,t,r)}static $(){return["GetSpendLimitPolicyRequest|1 team_id 5|2 scope #0|3 group_id 3?",nt]}}class Fc extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fc).fromBinary(t,r)}static fromJson(t,r){return(new Fc).fromJson(t,r)}static fromJsonString(t,r){return(new Fc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fc,t,r)}static $(){return["GetSpendLimitPolicyResponse|1 policy #0",Gc]}}class Kc extends T{constructor(t){super(),this.teamId=0,this.scope=nt.UNSPECIFIED,this.type=st.UNSPECIFIED,this.notifyAdminUserIds=[],this.clearConflictingPolicy=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kc).fromBinary(t,r)}static fromJson(t,r){return(new Kc).fromJson(t,r)}static fromJsonString(t,r){return(new Kc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Kc,t,r)}static $(){return["SetSpendLimitPolicyRequest|1 team_id 5|2 scope #0|3 type #1|4 amount_dollars 5?|5 is_dynamic_team_limit 8?|6 alert_enabled 8?|7 alert_threshold_bps 5?|8 notification_mode 9?|9 notify_all_admins 8?|10 notify_admin_user_ids 5*|11 notify_member 8?|12 clear_conflicting_policy 8|13 auto_alerts_enabled 8?|14 group_id 3?",nt,st]}}class zc extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zc).fromBinary(t,r)}static fromJson(t,r){return(new zc).fromJson(t,r)}static fromJsonString(t,r){return(new zc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zc,t,r)}static $(){return["SetSpendLimitPolicyResponse|1 policy #0",Gc]}}class jc extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jc).fromBinary(t,r)}static fromJson(t,r){return(new jc).fromJson(t,r)}static fromJsonString(t,r){return(new jc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jc,t,r)}static $(){return["GetOrgTeamBudgetsRequest|1 organization_id 9"]}}class Hc extends T{constructor(t){super(),this.teamId=0,this.teamName="",this.currentSpendCents=0,this.teamSlug="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hc).fromBinary(t,r)}static fromJson(t,r){return(new Hc).fromJson(t,r)}static fromJsonString(t,r){return(new Hc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hc,t,r)}static $(){return["OrgTeamBudget|1 team_id 5|2 team_name 9|3 limit_dollars 5?|4 current_spend_cents 5|5 team_slug 9|6 team_icon_url 9?"]}}class Wc extends T{constructor(t){super(),this.budgets=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wc).fromBinary(t,r)}static fromJson(t,r){return(new Wc).fromJson(t,r)}static fromJsonString(t,r){return(new Wc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wc,t,r)}static $(){return["GetOrgTeamBudgetsResponse|1 budgets #0*",Hc]}}class Qc extends T{constructor(t){super(),this.organizationId="",this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qc).fromBinary(t,r)}static fromJson(t,r){return(new Qc).fromJson(t,r)}static fromJsonString(t,r){return(new Qc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qc,t,r)}static $(){return["SetOrgTeamBudgetRequest|1 organization_id 9|2 team_id 5|3 limit_dollars 5?"]}}class Vc extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vc).fromBinary(t,r)}static fromJson(t,r){return(new Vc).fromJson(t,r)}static fromJsonString(t,r){return(new Vc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vc,t,r)}static $(){return["SetOrgTeamBudgetResponse"]}}class Xc extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xc).fromBinary(t,r)}static fromJson(t,r){return(new Xc).fromJson(t,r)}static fromJsonString(t,r){return(new Xc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xc,t,r)}static $(){return["EnableOnDemandSpendRequest|1 team_id 5?"]}}class Yc extends T{constructor(t){super(),this.hardLimit=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yc).fromBinary(t,r)}static fromJson(t,r){return(new Yc).fromJson(t,r)}static fromJsonString(t,r){return(new Yc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yc,t,r)}static $(){return["EnableOnDemandSpendResponse|1 hard_limit 5|2 hard_limit_per_user 5?"]}}class Zc extends T{constructor(t){super(),this.name="",this.id=0,this.role=it.UNSPECIFIED,this.seats=0,this.hasBilling=!1,this.requestQuotaPerSeat=0,this.privacyModeForced=!1,this.allowSso=!1,this.adminOnlyUsagePricing=!1,this.subscriptionStatus="",this.bedrockIamRole="",this.verified=!1,this.isEnterprise=!1,this.privacyModeMigrationOptedOut=!1,this.bedrockExternalId="",this.membershipType="",this.dataSharingDiscountEligible=!1,this.dashboardAnalyticsRequiresAdmin=!1,this.individualSpendLimitsBlocked=!1,this.allowDomainJoin=!1,this.domainJoinDomains=[],this.ssoEnabled=!1,this.scimRequireUserDirectory=!1,this.selfServeTieredPricingEnabled=!1,this.newMemberUsagePromoEligible=!1,this.grantedPermissions=[],this.isDirectMember=!1,this.teamSlug="",this.privateInferenceEnablement=ct.UNSPECIFIED,this.privateInferenceModeSwitchAllowed=!1,this.privateInferenceAvailable=!1,this.bedrockAssumerRoleArn="",this.privateInferenceBugReportsAllowed=!1,this.billingSource=ut.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zc).fromBinary(t,r)}static fromJson(t,r){return(new Zc).fromJson(t,r)}static fromJsonString(t,r){return(new Zc).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zc,t,r)}static $(){return["Team|1 name 9|2 id 5|3 role #0|4 seats 5|5 has_billing 8|6 request_quota_per_seat 5|7 privacy_mode_forced 8|8 allow_sso 8|9 admin_only_usage_pricing 8|10 subscription_status 9|11 bedrock_iam_role 9|12 verified 8|13 is_enterprise 8|14 privacy_mode_migration_opted_out 8|15 bedrock_external_id 9|16 membership_type 9|17 purchased_seats 5?|18 billing_cycle_start 3?|19 billing_cycle_end 3?|20 pricing_strategy 9?|21 total_committed_dollars 5?|22 data_sharing_discount_eligible 8|23 dashboard_analytics_requires_admin 8|24 individual_spend_limits_blocked 8|25 allow_domain_join 8|26 domain_join_domains 9*|27 sso_enabled 8|28 customer_balance_cents 3?|29 scim_require_user_directory 8|30 self_serve_tiered_pricing_enabled 8|31 new_member_usage_promo_eligible 8|34 deleted_at_ms 3?|35 granted_permissions 9*|36 is_direct_member 8|37 team_slug 9|38 private_inference_enablement #1|39 default_member_billing_tier #2?|40 private_inference_mode_switch_allowed 8|41 private_inference_available 8|42 bedrock_assumer_role_arn 9|46 private_inference_bug_reports_allowed 8|43 icon_url 9?|44 merged_team_has_members 8?|45 billing_source #3|47 is_viewer_default_team 8?|48 can_be_viewer_default_team 8?|49 member_role #0?|50 viewer_has_teammate 8?|51 organization_network_blocklist_bound 8?",it,ct,ot,ut]}}class tl extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tl).fromBinary(t,r)}static fromJson(t,r){return(new tl).fromJson(t,r)}static fromJsonString(t,r){return(new tl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tl,t,r)}static $(){return["GetTeamsRequest|1 active_only 8?"]}}class rl extends T{constructor(t){super(),this.teams=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rl).fromBinary(t,r)}static fromJson(t,r){return(new rl).fromJson(t,r)}static fromJsonString(t,r){return(new rl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rl,t,r)}static $(){return["GetTeamsResponse|1 teams #0*",Zc]}}class el extends T{constructor(t){super(),this.userId=0,this.name="",this.email="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new el).fromBinary(t,r)}static fromJson(t,r){return(new el).fromJson(t,r)}static fromJsonString(t,r){return(new el).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(el,t,r)}static $(){return["ScimRequireUserDirectoryImpactedUser|1 user_id 5|2 name 9|3 email 9|4 profile_picture_url 9?"]}}class nl extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nl).fromBinary(t,r)}static fromJson(t,r){return(new nl).fromJson(t,r)}static fromJsonString(t,r){return(new nl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nl,t,r)}static $(){return["GetTeamScimRequireUserDirectoryPreviewRequest|1 team_id 5"]}}class sl extends T{constructor(t){super(),this.impactedUserCount=0,this.impactedUsers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sl).fromBinary(t,r)}static fromJson(t,r){return(new sl).fromJson(t,r)}static fromJsonString(t,r){return(new sl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sl,t,r)}static $(){return["GetTeamScimRequireUserDirectoryPreviewResponse|1 impacted_user_count 5|2 impacted_users #0*",el]}}class il extends T{constructor(t){super(),this.teamId=0,this.seats=0,this.yearly=!1,this.requestQuotaPerSeat=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new il).fromBinary(t,r)}static fromJson(t,r){return(new il).fromJson(t,r)}static fromJsonString(t,r){return(new il).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(il,t,r)}static $(){return["GetActivationCheckoutUrlRequest|1 team_id 5|2 seats 5|3 yearly 8|4 request_quota_per_seat 5|5 code 9?|6 radar_session_id 9?|7 include_bugbot 8?|8 billing_tier #0?",ot]}}class ol extends T{constructor(t){super(),this.checkoutUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ol).fromBinary(t,r)}static fromJson(t,r){return(new ol).fromJson(t,r)}static fromJsonString(t,r){return(new ol).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ol,t,r)}static $(){return["GetActivationCheckoutUrlResponse|1 checkout_url 9"]}}class al extends T{constructor(t){super(),this.promoTypeId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new al).fromBinary(t,r)}static fromJson(t,r){return(new al).fromJson(t,r)}static fromJsonString(t,r){return(new al).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(al,t,r)}static $(){return["CheckPromotionEligibilityRequest|1 promo_type_id 9"]}}class ul extends T{constructor(t){super(),this.canActivate=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ul).fromBinary(t,r)}static fromJson(t,r){return(new ul).fromJson(t,r)}static fromJsonString(t,r){return(new ul).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ul,t,r)}static $(){return["CheckPromotionEligibilityResponse|1 can_activate 8|2 activation_status #0?",cl]}}class cl extends T{constructor(t){super(),this.isActivated=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cl).fromBinary(t,r)}static fromJson(t,r){return(new cl).fromJson(t,r)}static fromJsonString(t,r){return(new cl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cl,t,r)}static $(){return["ActivationStatus|1 is_activated 8|2 activated_at 3?"]}}class ll extends T{constructor(t){super(),this.promoTypeId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ll).fromBinary(t,r)}static fromJson(t,r){return(new ll).fromJson(t,r)}static fromJsonString(t,r){return(new ll).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ll,t,r)}static $(){return["ActivatePromotionRequest|1 promo_type_id 9"]}}class ml extends T{constructor(t){super(),this.type=fl.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ml).fromBinary(t,r)}static fromJson(t,r){return(new ml).fromJson(t,r)}static fromJsonString(t,r){return(new ml).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ml,t,r)}static $(){return["ActivatePromotionResponse|1 type #0|2 checkout_url 9?|3 success 8?",fl]}}var fl=(0,a.QT)(n.proto3,C,"ActivatePromotionResponse.ActivationType",[[0,"UNSPECIFIED"],[1,"CHECKOUT"],[2,"SUBSCRIPTION"]],1);class dl extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dl).fromBinary(t,r)}static fromJson(t,r){return(new dl).fromJson(t,r)}static fromJsonString(t,r){return(new dl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dl,t,r)}static $(){return["GetTeamCustomerPortalUrlRequest|1 team_id 5"]}}class pl extends T{constructor(t){super(),this.portalUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pl).fromBinary(t,r)}static fromJson(t,r){return(new pl).fromJson(t,r)}static fromJsonString(t,r){return(new pl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pl,t,r)}static $(){return["GetTeamCustomerPortalUrlResponse|1 portal_url 9"]}}class hl extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hl).fromBinary(t,r)}static fromJson(t,r){return(new hl).fromJson(t,r)}static fromJsonString(t,r){return(new hl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hl,t,r)}static $(){return["CancelPendingTeamSubscriptionNowRequest|1 team_id 5"]}}class gl extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gl).fromBinary(t,r)}static fromJson(t,r){return(new gl).fromJson(t,r)}static fromJsonString(t,r){return(new gl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gl,t,r)}static $(){return["CancelPendingTeamSubscriptionNowResponse"]}}class _l extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _l).fromBinary(t,r)}static fromJson(t,r){return(new _l).fromJson(t,r)}static fromJsonString(t,r){return(new _l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_l,t,r)}static $(){return["CreatePendingTeamProCheckoutRequest|1 team_id 5"]}}class Jl extends T{constructor(t){super(),this.checkoutUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jl).fromBinary(t,r)}static fromJson(t,r){return(new Jl).fromJson(t,r)}static fromJsonString(t,r){return(new Jl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jl,t,r)}static $(){return["CreatePendingTeamProCheckoutResponse|1 checkout_url 9"]}}class wl extends T{constructor(t){super(),this.enabled=!1,this.thresholdCents=n.protoInt64.zero,this.topUpAmountCents=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wl).fromBinary(t,r)}static fromJson(t,r){return(new wl).fromJson(t,r)}static fromJsonString(t,r){return(new wl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wl,t,r)}static $(){return["PrepaidAutoTopUpRule|1 enabled 8|2 threshold_cents 3|3 top_up_amount_cents 3|4 monthly_cap_cents 3?"]}}class yl extends T{constructor(t){super(),this.ticket=n.protoInt64.zero,this.origin="",this.amountCents=n.protoInt64.zero,this.status="",this.createdAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yl).fromBinary(t,r)}static fromJson(t,r){return(new yl).fromJson(t,r)}static fromJsonString(t,r){return(new yl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yl,t,r)}static $(){return["PrepaidTopUpEntry|1 ticket 3|2 origin 9|3 amount_cents 3|4 status 9|5 failure_code 9?|6 created_at_ms 3|7 succeeded_at_ms 3?|8 invoice_url 9?|9 invoice_pdf_url 9?"]}}class Sl extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sl).fromBinary(t,r)}static fromJson(t,r){return(new Sl).fromJson(t,r)}static fromJsonString(t,r){return(new Sl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sl,t,r)}static $(){return["GetTeamPrepaidBillingRequest|1 team_id 5|2 limit 5?|3 skip_balance_cache 8?|4 skip_card_check 8?"]}}class ql extends T{constructor(t){super(),this.billingMode=lt.UNSPECIFIED,this.eligible=!1,this.availableCents=n.protoInt64.zero,this.fundedCents=n.protoInt64.zero,this.spentCents=n.protoInt64.zero,this.topUps=[],this.hasPaymentMethod=!1,this.pendingTopUps=0,this.autoTopUpChargedThisMonthCents=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ql).fromBinary(t,r)}static fromJson(t,r){return(new ql).fromJson(t,r)}static fromJsonString(t,r){return(new ql).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ql,t,r)}static $(){return["GetTeamPrepaidBillingResponse|1 billing_mode #0|2 eligible 8|3 available_cents 3|4 funded_cents 3|5 spent_cents 3|6 auto_top_up #1?|7 top_ups #2*|8 has_payment_method 8|9 pending_top_ups 5|10 auto_top_up_charged_this_month_cents 3|11 spent_this_month_cents 3?",lt,wl,yl]}}class Bl extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bl).fromBinary(t,r)}static fromJson(t,r){return(new Bl).fromJson(t,r)}static fromJsonString(t,r){return(new Bl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bl,t,r)}static $(){return["SetTeamPrepaidAutoTopUpRequest|1 team_id 5|2 rule #0?",wl]}}class Il extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Il).fromBinary(t,r)}static fromJson(t,r){return(new Il).fromJson(t,r)}static fromJsonString(t,r){return(new Il).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Il,t,r)}static $(){return["SetTeamPrepaidAutoTopUpResponse|1 rule #0?",wl]}}class Pl extends T{constructor(t){super(),this.teamId=0,this.amountCents=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pl).fromBinary(t,r)}static fromJson(t,r){return(new Pl).fromJson(t,r)}static fromJsonString(t,r){return(new Pl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pl,t,r)}static $(){return["CreatePrepaidTopUpRequest|1 team_id 5|2 amount_cents 3|3 payment_method_id 9?"]}}class bl extends T{constructor(t){super(),this.ticket=n.protoInt64.zero,this.status="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bl).fromBinary(t,r)}static fromJson(t,r){return(new bl).fromJson(t,r)}static fromJsonString(t,r){return(new bl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bl,t,r)}static $(){return["CreatePrepaidTopUpResponse|1 ticket 3|2 status 9|3 invoice_url 9?|4 failure_code 9?"]}}class Rl extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rl).fromBinary(t,r)}static fromJson(t,r){return(new Rl).fromJson(t,r)}static fromJsonString(t,r){return(new Rl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rl,t,r)}static $(){return["GetUserPrepaidBillingRequest|1 limit 5?|2 xai_team_id 9?|3 skip_balance_cache 8?|4 skip_card_check 8?"]}}class vl extends T{constructor(t){super(),this.billingMode=lt.UNSPECIFIED,this.eligible=!1,this.availableCents=n.protoInt64.zero,this.fundedCents=n.protoInt64.zero,this.spentCents=n.protoInt64.zero,this.topUps=[],this.hasPaymentMethod=!1,this.pendingTopUps=0,this.autoTopUpChargedThisMonthCents=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vl).fromBinary(t,r)}static fromJson(t,r){return(new vl).fromJson(t,r)}static fromJsonString(t,r){return(new vl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vl,t,r)}static $(){return["GetUserPrepaidBillingResponse|1 billing_mode #0|2 eligible 8|3 available_cents 3|4 funded_cents 3|5 spent_cents 3|6 auto_top_up #1?|7 top_ups #2*|8 has_payment_method 8|9 pending_top_ups 5|10 auto_top_up_charged_this_month_cents 3|11 spent_this_month_cents 3?",lt,wl,yl]}}class xl extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xl).fromBinary(t,r)}static fromJson(t,r){return(new xl).fromJson(t,r)}static fromJsonString(t,r){return(new xl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xl,t,r)}static $(){return["SetUserPrepaidAutoTopUpRequest|1 rule #0?|2 xai_team_id 9?|3 entrypoint 9?",wl]}}class kl extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kl).fromBinary(t,r)}static fromJson(t,r){return(new kl).fromJson(t,r)}static fromJsonString(t,r){return(new kl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kl,t,r)}static $(){return["SetUserPrepaidAutoTopUpResponse|1 rule #0?",wl]}}class El extends T{constructor(t){super(),this.amountCents=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new El).fromBinary(t,r)}static fromJson(t,r){return(new El).fromJson(t,r)}static fromJsonString(t,r){return(new El).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(El,t,r)}static $(){return["CreateUserPrepaidTopUpRequest|1 amount_cents 3|2 payment_method_id 9?"]}}class Cl extends T{constructor(t){super(),this.ticket=n.protoInt64.zero,this.status="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cl).fromBinary(t,r)}static fromJson(t,r){return(new Cl).fromJson(t,r)}static fromJsonString(t,r){return(new Cl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cl,t,r)}static $(){return["CreateUserPrepaidTopUpResponse|1 ticket 3|2 status 9|3 invoice_url 9?|4 failure_code 9?"]}}class Tl extends T{constructor(t){super(),this.purpose=mt.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tl).fromBinary(t,r)}static fromJson(t,r){return(new Tl).fromJson(t,r)}static fromJsonString(t,r){return(new Tl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tl,t,r)}static $(){return["GetXaiCommerceBearerTokenRequest|1 purpose #0",mt]}}class Ul extends T{constructor(t){super(),this.token="",this.edgeBaseUrl="",this.tokenSource=ft.UNSPECIFIED,this.expiresInSeconds=0,this.assetServerBaseUrl="",this.country="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ul).fromBinary(t,r)}static fromJson(t,r){return(new Ul).fromJson(t,r)}static fromJsonString(t,r){return(new Ul).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ul,t,r)}static $(){return["XaiCommerceBearerCredential|1 token 9|2 edge_base_url 9|3 token_source #0|4 expires_in_seconds 13|5 asset_server_base_url 9|6 country 9",ft]}}class Al extends T{constructor(t){super(),this.reason=dt.UNSPECIFIED,this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Al).fromBinary(t,r)}static fromJson(t,r){return(new Al).fromJson(t,r)}static fromJsonString(t,r){return(new Al).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Al,t,r)}static $(){return["XaiCommerceBearerRefusal|1 reason #0|2 message 9",dt]}}class $l extends T{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $l).fromBinary(t,r)}static fromJson(t,r){return(new $l).fromJson(t,r)}static fromJsonString(t,r){return(new $l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($l,t,r)}static $(){return["GetXaiCommerceBearerTokenResponse|1 credential #0 result|2 refusal #1 result",Ul,Al]}}class Ml extends T{constructor(t){super(),this.slackTeamId="",this.slackUserId="",this.nonce="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ml).fromBinary(t,r)}static fromJson(t,r){return(new Ml).fromJson(t,r)}static fromJsonString(t,r){return(new Ml).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ml,t,r)}static $(){return["SetSlackAuthRequest|1 slack_team_id 9|2 slack_user_id 9|3 nonce 9|4 setup_complete 8?|5 cursor_team_id 5?"]}}class Ol extends T{constructor(t){super(),this.linkedWorkspaceName="",this.otherLinkedWorkspaces=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ol).fromBinary(t,r)}static fromJson(t,r){return(new Ol).fromJson(t,r)}static fromJsonString(t,r){return(new Ol).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ol,t,r)}static $(){return["SetSlackAuthResponse|1 linked_workspace_name 9|2 other_linked_workspaces 5"]}}class Dl extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dl).fromBinary(t,r)}static fromJson(t,r){return(new Dl).fromJson(t,r)}static fromJsonString(t,r){return(new Dl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dl,t,r)}static $(){return["GetSlackTeamSettingsRequest|1 team_id 5"]}}class Nl extends T{constructor(t){super(),this.slackChannel="",this.repo="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nl).fromBinary(t,r)}static fromJson(t,r){return(new Nl).fromJson(t,r)}static fromJsonString(t,r){return(new Nl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nl,t,r)}static $(){return["SlackChannelRepoMapping|1 slack_channel 9|2 repo 9"]}}class Gl extends T{constructor(t){super(),this.defaultRepo="",this.defaultBranch="",this.defaultModel="",this.shareSummary=!1,this.shareSummaryInExternalChannel=!1,this.channelRepoMappings=[],this.branchPrefix="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gl).fromBinary(t,r)}static fromJson(t,r){return(new Gl).fromJson(t,r)}static fromJsonString(t,r){return(new Gl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gl,t,r)}static $(){return["GetSlackTeamSettingsResponse|1 default_repo 9|2 default_branch 9|3 default_model 9|4 share_summary 8|5 share_summary_in_external_channel 8|6 channel_repo_mappings #0*|7 auto_draft_enabled 8?|8 use_github_app_for_auto_draft_prs 8?|9 branch_prefix 9|10 default_model_selection #1?|12 default_environment_public_id 9?",Nl,o.M6]}}class Ll extends T{constructor(t){super(),this.teamId=0,this.defaultRepo="",this.defaultBranch="",this.defaultModel="",this.shareSummary=!1,this.shareSummaryInExternalChannel=!1,this.channelRepoMappings=[],this.branchPrefix="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ll).fromBinary(t,r)}static fromJson(t,r){return(new Ll).fromJson(t,r)}static fromJsonString(t,r){return(new Ll).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ll,t,r)}static $(){return["UpdateSlackTeamSettingsRequest|1 team_id 5|2 default_repo 9|3 default_branch 9|4 default_model 9|5 share_summary 8|6 share_summary_in_external_channel 8|7 channel_repo_mappings #0*|8 use_github_app_for_auto_draft_prs 8?|9 branch_prefix 9|10 default_model_selection #1?|12 default_environment_public_id 9?",Nl,o.M6]}}class Fl extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fl).fromBinary(t,r)}static fromJson(t,r){return(new Fl).fromJson(t,r)}static fromJsonString(t,r){return(new Fl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fl,t,r)}static $(){return["UpdateSlackTeamSettingsResponse"]}}class Kl extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kl).fromBinary(t,r)}static fromJson(t,r){return(new Kl).fromJson(t,r)}static fromJsonString(t,r){return(new Kl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Kl,t,r)}static $(){return["GetSlackSettingsRequest"]}}class zl extends T{constructor(t){super(),this.available=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zl).fromBinary(t,r)}static fromJson(t,r){return(new zl).fromJson(t,r)}static fromJsonString(t,r){return(new zl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zl,t,r)}static $(){return["GetSlackSettingsResponse|1 available 8"]}}class jl extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jl).fromBinary(t,r)}static fromJson(t,r){return(new jl).fromJson(t,r)}static fromJsonString(t,r){return(new jl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jl,t,r)}static $(){return["GetSlackInstallUrlRequest|1 team_id 5|2 repo_url 9?|3 source #0?|4 attempt_id 9?|5 grok_bot_callback_url 9?|6 site #1?|7 reconnect_slack_team_id 9?",pt,ht]}}class Hl extends T{constructor(t){super(),this.url="",this.source=pt.UNSPECIFIED,this.attemptId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hl).fromBinary(t,r)}static fromJson(t,r){return(new Hl).fromJson(t,r)}static fromJsonString(t,r){return(new Hl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hl,t,r)}static $(){return["GetSlackInstallUrlResponse|1 url 9|2 source #0|3 attempt_id 9",pt]}}class Wl extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wl).fromBinary(t,r)}static fromJson(t,r){return(new Wl).fromJson(t,r)}static fromJsonString(t,r){return(new Wl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wl,t,r)}static $(){return["GetPublicSlackInstallUrlRequest|1 source #0?|2 attempt_id 9?",pt]}}class Ql extends T{constructor(t){super(),this.url="",this.source=pt.UNSPECIFIED,this.attemptId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ql).fromBinary(t,r)}static fromJson(t,r){return(new Ql).fromJson(t,r)}static fromJsonString(t,r){return(new Ql).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ql,t,r)}static $(){return["GetPublicSlackInstallUrlResponse|1 url 9|2 source #0|3 attempt_id 9",pt]}}class Vl extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vl).fromBinary(t,r)}static fromJson(t,r){return(new Vl).fromJson(t,r)}static fromJsonString(t,r){return(new Vl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vl,t,r)}static $(){return["GetPublicSlackInstallUrlWithUserScopesRequest|1 source #0?|2 attempt_id 9?",pt]}}class Xl extends T{constructor(t){super(),this.url="",this.source=pt.UNSPECIFIED,this.attemptId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xl).fromBinary(t,r)}static fromJson(t,r){return(new Xl).fromJson(t,r)}static fromJsonString(t,r){return(new Xl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xl,t,r)}static $(){return["GetPublicSlackInstallUrlWithUserScopesResponse|1 url 9|2 source #0|3 attempt_id 9",pt]}}class Yl extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yl).fromBinary(t,r)}static fromJson(t,r){return(new Yl).fromJson(t,r)}static fromJsonString(t,r){return(new Yl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yl,t,r)}static $(){return["GetSlackModelOptionsRequest"]}}class Zl extends T{constructor(t){super(),this.modelOptions=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zl).fromBinary(t,r)}static fromJson(t,r){return(new Zl).fromJson(t,r)}static fromJsonString(t,r){return(new Zl).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zl,t,r)}static $(){return["GetSlackModelOptionsResponse|1 model_options 9*"]}}class tm extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tm).fromBinary(t,r)}static fromJson(t,r){return(new tm).fromJson(t,r)}static fromJsonString(t,r){return(new tm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tm,t,r)}static $(){return["GetTeamMembersRequest|1 team_id 5|2 include_org_admins 8?"]}}class rm extends T{constructor(t){super(),this.name="",this.email="",this.id=0,this.role=it.UNSPECIFIED,this.isRemoved=!1,this.billingTier=ot.UNSPECIFIED,this.pendingBillingTier=ot.UNSPECIFIED,this.roleIsManaged=!1,this.isOrgAdmin=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rm).fromBinary(t,r)}static fromJson(t,r){return(new rm).fromJson(t,r)}static fromJsonString(t,r){return(new rm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rm,t,r)}static $(){return["TeamMember|1 name 9|4 email 9|2 id 5|3 role #0|5 is_removed 8|6 billing_tier #1|7 pending_billing_tier #1|8 role_is_managed 8|10 is_org_admin 8|11 merged_seat_tier #2?|12 profile_picture_url 9?",it,ot,at]}}class em extends T{constructor(t){super(),this.name="",this.id=0,this.email="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new em).fromBinary(t,r)}static fromJson(t,r){return(new em).fromJson(t,r)}static fromJsonString(t,r){return(new em).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(em,t,r)}static $(){return["TeamOrgAdmin|1 name 9|2 id 5|3 email 9"]}}class nm extends T{constructor(t){super(),this.state=gt.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nm).fromBinary(t,r)}static fromJson(t,r){return(new nm).fromJson(t,r)}static fromJsonString(t,r){return(new nm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nm,t,r)}static $(){return["TeamEnterpriseGrantCapacity|1 state #0|2 quantity 5?|3 assigned 5?|4 unassigned 5?",gt]}}class sm extends T{constructor(t){super(),this.teamMembers=[],this.userId=0,this.isScimSynced=!1,this.orgAdmins=[],this.mergedSeatRail=!1,this.teamLinkedToOrganization=!1,this.inviteSeatTierEnabled=!1,this.inviteFreeSeatRefused=!1,this.xaiTeamMembershipHolds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sm).fromBinary(t,r)}static fromJson(t,r){return(new sm).fromJson(t,r)}static fromJsonString(t,r){return(new sm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sm,t,r)}static $(){return["GetTeamMembersResponse|1 team_members #0*|2 user_id 5|3 is_scim_synced 8|4 org_admins #1*|5 merged_seat_rail 8|6 team_linked_to_organization 8|7 invite_seat_tier_enabled 8|8 former_personal_owner_user_id 5?|9 invite_free_seat_refused 8|10 xai_team_membership_holds #2*|11 enterprise_grant_capacity #3?",rm,em,uo,nm]}}class im extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new im).fromBinary(t,r)}static fromJson(t,r){return(new im).fromJson(t,r)}static fromJsonString(t,r){return(new im).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(im,t,r)}static $(){return["GetTeamInviteLinkRequest|1 team_id 5|3 create_if_missing 8?|4 billing_tier #0?|5 role #1?|6 merged_seat_tier #2?|7 attribution_source 9?|8 attribution_surface 9?|9 castle_request_token 9?",ot,it,at]}}class om extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new om).fromBinary(t,r)}static fromJson(t,r){return(new om).fromJson(t,r)}static fromJsonString(t,r){return(new om).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(om,t,r)}static $(){return["GetTeamInviteLinkResponse|1 invite_link 9?"]}}class am extends T{constructor(t){super(),this.teamId=0,this.email="",this.role=it.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new am).fromBinary(t,r)}static fromJson(t,r){return(new am).fromJson(t,r)}static fromJsonString(t,r){return(new am).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(am,t,r)}static $(){return["SendTeamInviteRequest|1 team_id 5|2 email 9|3 role #0|4 message 9?|5 billing_tier #1?|7 onboarding 9?|8 merged_seat_tier #2?|9 attribution_source 9?|10 attribution_surface 9?|11 castle_request_token 9?",it,ot,at]}}class um extends T{constructor(t){super(),this.validUntil=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new um).fromBinary(t,r)}static fromJson(t,r){return(new um).fromJson(t,r)}static fromJsonString(t,r){return(new um).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(um,t,r)}static $(){return["SendTeamInviteResponse|1 valid_until 3"]}}class cm extends T{constructor(t){super(),this.teamId=0,this.emails=[],this.role=it.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cm).fromBinary(t,r)}static fromJson(t,r){return(new cm).fromJson(t,r)}static fromJsonString(t,r){return(new cm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cm,t,r)}static $(){return["SendTeamInvitesRequest|1 team_id 5|2 emails 9*|3 role #0|4 message 9?|5 billing_tier #1?|6 onboarding 9?|7 merged_seat_tier #2?|8 attribution_source 9?|9 attribution_surface 9?|10 castle_request_token 9?",it,ot,at]}}class lm extends T{constructor(t){super(),this.results=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lm).fromBinary(t,r)}static fromJson(t,r){return(new lm).fromJson(t,r)}static fromJsonString(t,r){return(new lm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lm,t,r)}static $(){return["SendTeamInvitesResponse|1 results #0*",mm]}}class mm extends T{constructor(t){super(),this.email="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mm).fromBinary(t,r)}static fromJson(t,r){return(new mm).fromJson(t,r)}static fromJsonString(t,r){return(new mm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mm,t,r)}static $(){return["SendTeamInviteResult|1 email 9|2 valid_until 3?|3 error 9?"]}}class fm extends T{constructor(t){super(),this.connectionId=n.protoInt64.zero,this.provider=_t.UNSPECIFIED,this.providerAccountId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fm).fromBinary(t,r)}static fromJson(t,r){return(new fm).fromJson(t,r)}static fromJsonString(t,r){return(new fm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fm,t,r)}static $(){return["ContactImportConnectionSummary|1 connection_id 3|2 provider #0|3 provider_account_id 9|4 provider_workspace_id 9?|5 provider_account_email 9?|6 last_synced_at_ms 3?|7 latest_sync_status #1?|8 latest_sync_total_contacts 5?|9 latest_sync_completed_at_ms 3?",_t,Jt]}}class dm extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dm).fromBinary(t,r)}static fromJson(t,r){return(new dm).fromJson(t,r)}static fromJsonString(t,r){return(new dm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dm,t,r)}static $(){return["ListContactImportConnectionsRequest"]}}class pm extends T{constructor(t){super(),this.connections=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pm).fromBinary(t,r)}static fromJson(t,r){return(new pm).fromJson(t,r)}static fromJsonString(t,r){return(new pm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pm,t,r)}static $(){return["ListContactImportConnectionsResponse|1 connections #0*",fm]}}class hm extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hm).fromBinary(t,r)}static fromJson(t,r){return(new hm).fromJson(t,r)}static fromJsonString(t,r){return(new hm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hm,t,r)}static $(){return["GetGoogleContactImportAuthUrlRequest"]}}class gm extends T{constructor(t){super(),this.authUrl="",this.csrfToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gm).fromBinary(t,r)}static fromJson(t,r){return(new gm).fromJson(t,r)}static fromJsonString(t,r){return(new gm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gm,t,r)}static $(){return["GetGoogleContactImportAuthUrlResponse|1 auth_url 9|2 csrf_token 9"]}}class _m extends T{constructor(t){super(),this.code="",this.state="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _m).fromBinary(t,r)}static fromJson(t,r){return(new _m).fromJson(t,r)}static fromJsonString(t,r){return(new _m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_m,t,r)}static $(){return["ConnectGoogleContactImportCallbackRequest|1 code 9|2 state 9"]}}class Jm extends T{constructor(t){super(),this.connectionId=n.protoInt64.zero,this.syncRunId=n.protoInt64.zero,this.totalContacts=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jm).fromBinary(t,r)}static fromJson(t,r){return(new Jm).fromJson(t,r)}static fromJsonString(t,r){return(new Jm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jm,t,r)}static $(){return["ConnectGoogleContactImportCallbackResponse|1 connection_id 3|2 sync_run_id 3|3 total_contacts 5"]}}class wm extends T{constructor(t){super(),this.contactId=n.protoInt64.zero,this.providerContactId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wm).fromBinary(t,r)}static fromJson(t,r){return(new wm).fromJson(t,r)}static fromJsonString(t,r){return(new wm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wm,t,r)}static $(){return["ContactImportContactRow|1 contact_id 3|2 provider_contact_id 9|3 display_name 9?|4 given_name 9?|5 family_name 9?|6 primary_email 9?|7 normalized_email 9?|8 photo_url 9?"]}}class ym extends T{constructor(t){super(),this.connectionId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ym).fromBinary(t,r)}static fromJson(t,r){return(new ym).fromJson(t,r)}static fromJsonString(t,r){return(new ym).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ym,t,r)}static $(){return["ListContactImportContactsRequest|1 connection_id 3|2 limit 5?|3 normalized_email_query 9?|4 after_contact_id 3?"]}}class Sm extends T{constructor(t){super(),this.contacts=[],this.totalCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sm).fromBinary(t,r)}static fromJson(t,r){return(new Sm).fromJson(t,r)}static fromJsonString(t,r){return(new Sm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sm,t,r)}static $(){return["ListContactImportContactsResponse|1 contacts #0*|2 total_count 5",wm]}}class qm extends T{constructor(t){super(),this.contactId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qm).fromBinary(t,r)}static fromJson(t,r){return(new qm).fromJson(t,r)}static fromJsonString(t,r){return(new qm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qm,t,r)}static $(){return["GetContactImportAvatarRequest|1 contact_id 3"]}}class Bm extends T{constructor(t){super(),this.bytes=new Uint8Array(0),this.contentType="",this.etag="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bm).fromBinary(t,r)}static fromJson(t,r){return(new Bm).fromJson(t,r)}static fromJsonString(t,r){return(new Bm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bm,t,r)}static $(){return["GetContactImportAvatarResponse|1 bytes 12|2 content_type 9|3 etag 9"]}}class Im extends T{constructor(t){super(),this.connectionId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Im).fromBinary(t,r)}static fromJson(t,r){return(new Im).fromJson(t,r)}static fromJsonString(t,r){return(new Im).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Im,t,r)}static $(){return["DisconnectContactImportConnectionRequest|1 connection_id 3"]}}class Pm extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pm).fromBinary(t,r)}static fromJson(t,r){return(new Pm).fromJson(t,r)}static fromJsonString(t,r){return(new Pm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pm,t,r)}static $(){return["DisconnectContactImportConnectionResponse|1 success 8"]}}class bm extends T{constructor(t){super(),this.inviteCode="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bm).fromBinary(t,r)}static fromJson(t,r){return(new bm).fromJson(t,r)}static fromJsonString(t,r){return(new bm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bm,t,r)}static $(){return["AcceptInviteRequest|1 invite_code 9|2 castle_request_token 9?|3 invite_ref 9?|4 project_invite 9?"]}}class Rm extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rm).fromBinary(t,r)}static fromJson(t,r){return(new Rm).fromJson(t,r)}static fromJsonString(t,r){return(new Rm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rm,t,r)}static $(){return["AcceptInviteResponse|1 team_id 5|2 project_bc_id 9?|3 join_request_pending 8?"]}}class vm extends T{constructor(t){super(),this.inviteCode="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vm).fromBinary(t,r)}static fromJson(t,r){return(new vm).fromJson(t,r)}static fromJsonString(t,r){return(new vm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vm,t,r)}static $(){return["GetTeamInviteMetadataRequest|1 invite_code 9"]}}class xm extends T{constructor(t){super(),this.teamId=0,this.teamName="",this.inviterName="",this.inviterEmail="",this.inviteeEmailMatchesAuthenticatedUser=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xm).fromBinary(t,r)}static fromJson(t,r){return(new xm).fromJson(t,r)}static fromJsonString(t,r){return(new xm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xm,t,r)}static $(){return["GetTeamInviteMetadataResponse|1 team_id 5|2 team_name 9|3 inviter_name 9|4 inviter_email 9|5 invitee_email_matches_authenticated_user 8|6 invite_has_bound_recipient 8?|7 join_requires_approval 8?|8 join_request_pending 8?"]}}class km extends T{constructor(t){super(),this.teamId=0,this.name="",this.scopes=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new km).fromBinary(t,r)}static fromJson(t,r){return(new km).fromJson(t,r)}static fromJsonString(t,r){return(new km).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(km,t,r)}static $(){return["CreateTeamApiKeyRequest|1 team_id 5|2 name 9|3 scopes 9*|4 expires_at 3?|5 castle_request_token 9?"]}}class Em extends T{constructor(t){super(),this.apiKey="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Em).fromBinary(t,r)}static fromJson(t,r){return(new Em).fromJson(t,r)}static fromJsonString(t,r){return(new Em).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Em,t,r)}static $(){return["CreateTeamApiKeyResponse|1 api_key 9"]}}class Cm extends T{constructor(t){super(),this.automationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cm).fromBinary(t,r)}static fromJson(t,r){return(new Cm).fromJson(t,r)}static fromJsonString(t,r){return(new Cm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cm,t,r)}static $(){return["CreateAutomationWebhookApiKeyRequest|1 automation_id 9|2 name 9?"]}}class Tm extends T{constructor(t){super(),this.apiKey="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tm).fromBinary(t,r)}static fromJson(t,r){return(new Tm).fromJson(t,r)}static fromJsonString(t,r){return(new Tm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tm,t,r)}static $(){return["CreateAutomationWebhookApiKeyResponse|1 api_key 9"]}}class Um extends T{constructor(t){super(),this.teamId=0,this.id=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Um).fromBinary(t,r)}static fromJson(t,r){return(new Um).fromJson(t,r)}static fromJsonString(t,r){return(new Um).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Um,t,r)}static $(){return["RevokeTeamApiKeyRequest|1 team_id 5|2 id 5"]}}class Am extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Am).fromBinary(t,r)}static fromJson(t,r){return(new Am).fromJson(t,r)}static fromJsonString(t,r){return(new Am).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Am,t,r)}static $(){return["RevokeTeamApiKeyResponse"]}}class $m extends T{constructor(t){super(),this.id=0,this.maskedKey="",this.name="",this.createdAt=n.protoInt64.zero,this.scopes=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $m).fromBinary(t,r)}static fromJson(t,r){return(new $m).fromJson(t,r)}static fromJsonString(t,r){return(new $m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($m,t,r)}static $(){return["ApiKey|1 id 5|2 masked_key 9|3 name 9|4 created_at 3|5 service_account_name 9?|6 scopes 9*|7 expires_at 3?|8 creator #0|9 last_use #1",Jp,yp]}}class Mm extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mm).fromBinary(t,r)}static fromJson(t,r){return(new Mm).fromJson(t,r)}static fromJsonString(t,r){return(new Mm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mm,t,r)}static $(){return["ListTeamApiKeysRequest|1 team_id 5"]}}class Om extends T{constructor(t){super(),this.apiKeys=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Om).fromBinary(t,r)}static fromJson(t,r){return(new Om).fromJson(t,r)}static fromJsonString(t,r){return(new Om).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Om,t,r)}static $(){return["ListTeamApiKeysResponse|1 api_keys #0*",$m]}}class Dm extends T{constructor(t){super(),this.apiKeyId="",this.maskedKey="",this.name="",this.createdAt=n.protoInt64.zero,this.disabled=!1,this.acls=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dm).fromBinary(t,r)}static fromJson(t,r){return(new Dm).fromJson(t,r)}static fromJsonString(t,r){return(new Dm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dm,t,r)}static $(){return["GrokApiKey|1 api_key_id 9|2 masked_key 9|3 name 9|4 created_at 3|5 expires_at 3?|6 disabled 8|7 acls 9*|8 requests_per_minute 5?|9 requests_per_second 5?|10 tokens_per_minute 3?|11 owner #0|12 modified_at 3?",Nm]}}class Nm extends T{constructor(t){super(),this.name="",this.email="",this.isViewer=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nm).fromBinary(t,r)}static fromJson(t,r){return(new Nm).fromJson(t,r)}static fromJsonString(t,r){return(new Nm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nm,t,r)}static $(){return["GrokKeyOwner|1 name 9|2 email 9|3 is_viewer 8"]}}class Gm extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gm).fromBinary(t,r)}static fromJson(t,r){return(new Gm).fromJson(t,r)}static fromJsonString(t,r){return(new Gm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gm,t,r)}static $(){return["GetPersonalGrokApiKeyTeamRequest"]}}class Lm extends T{constructor(t){super(),this.teamId=0,this.paymentMethodRequired=!1,this.addCreditsAvailable=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lm).fromBinary(t,r)}static fromJson(t,r){return(new Lm).fromJson(t,r)}static fromJsonString(t,r){return(new Lm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Lm,t,r)}static $(){return["GetPersonalGrokApiKeyTeamResponse|1 team_id 5|2 payment_method_required 8|3 add_credits_available 8"]}}class Fm extends T{constructor(t){super(),this.teamId=0,this.pageToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fm).fromBinary(t,r)}static fromJson(t,r){return(new Fm).fromJson(t,r)}static fromJsonString(t,r){return(new Fm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fm,t,r)}static $(){return["ListGrokApiKeysRequest|1 team_id 5|2 page_size 5?|3 page_token 9"]}}class Km extends T{constructor(t){super(),this.apiKeys=[],this.propagationReadsEnabled=!1,this.nextPageToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Km).fromBinary(t,r)}static fromJson(t,r){return(new Km).fromJson(t,r)}static fromJsonString(t,r){return(new Km).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Km,t,r)}static $(){return["ListGrokApiKeysResponse|1 api_keys #0*|2 team_linked 8?|3 user_linked 8?|4 propagation_reads_enabled 8|5 next_page_token 9",Dm]}}class zm extends T{constructor(t){super(),this.teamId=0,this.name="",this.acls=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zm).fromBinary(t,r)}static fromJson(t,r){return(new zm).fromJson(t,r)}static fromJsonString(t,r){return(new zm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zm,t,r)}static $(){return["CreateGrokApiKeyRequest|1 team_id 5|2 name 9|3 expires_at 3?|4 acls 9*|5 requests_per_minute 5?|6 requests_per_second 5?|7 tokens_per_minute 3?"]}}class jm extends T{constructor(t){super(),this.apiKey="",this.apiKeyId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jm).fromBinary(t,r)}static fromJson(t,r){return(new jm).fromJson(t,r)}static fromJsonString(t,r){return(new jm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jm,t,r)}static $(){return["CreateGrokApiKeyResponse|1 api_key 9|2 api_key_id 9|3 requests_per_minute 5?|4 requests_per_second 5?|5 tokens_per_minute 3?"]}}class Hm extends T{constructor(t){super(),this.teamId=0,this.apiKeyId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hm).fromBinary(t,r)}static fromJson(t,r){return(new Hm).fromJson(t,r)}static fromJsonString(t,r){return(new Hm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hm,t,r)}static $(){return["DeleteGrokApiKeyRequest|1 team_id 5|2 api_key_id 9"]}}class Wm extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wm).fromBinary(t,r)}static fromJson(t,r){return(new Wm).fromJson(t,r)}static fromJsonString(t,r){return(new Wm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wm,t,r)}static $(){return["DeleteGrokApiKeyResponse"]}}class Qm extends T{constructor(t){super(),this.teamId=0,this.apiKeyId="",this.name="",this.updateFields=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qm).fromBinary(t,r)}static fromJson(t,r){return(new Qm).fromJson(t,r)}static fromJsonString(t,r){return(new Qm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qm,t,r)}static $(){return["UpdateGrokApiKeyRequest|1 team_id 5|2 api_key_id 9|3 name 9|4 update_fields 9*|5 requests_per_minute 5?|6 requests_per_second 5?|7 tokens_per_minute 3?|8 expires_at 3?|9 disabled 8?"]}}class Vm extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vm).fromBinary(t,r)}static fromJson(t,r){return(new Vm).fromJson(t,r)}static fromJsonString(t,r){return(new Vm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vm,t,r)}static $(){return["UpdateGrokApiKeyResponse"]}}class Xm extends T{constructor(t){super(),this.teamId=0,this.apiKeyId="",this.acls=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xm).fromBinary(t,r)}static fromJson(t,r){return(new Xm).fromJson(t,r)}static fromJsonString(t,r){return(new Xm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xm,t,r)}static $(){return["SetGrokApiKeyAclsRequest|1 team_id 5|2 api_key_id 9|3 acls 9*"]}}class Ym extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ym).fromBinary(t,r)}static fromJson(t,r){return(new Ym).fromJson(t,r)}static fromJsonString(t,r){return(new Ym).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ym,t,r)}static $(){return["SetGrokApiKeyAclsResponse"]}}class Zm extends T{constructor(t){super(),this.teamId=0,this.apiKeyId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zm).fromBinary(t,r)}static fromJson(t,r){return(new Zm).fromJson(t,r)}static fromJsonString(t,r){return(new Zm).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zm,t,r)}static $(){return["RotateGrokApiKeyRequest|1 team_id 5|2 api_key_id 9|3 old_secret_grace_seconds 5?"]}}class tf extends T{constructor(t){super(),this.apiKey="",this.apiKeyId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tf).fromBinary(t,r)}static fromJson(t,r){return(new tf).fromJson(t,r)}static fromJsonString(t,r){return(new tf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tf,t,r)}static $(){return["RotateGrokApiKeyResponse|1 api_key 9|2 api_key_id 9"]}}class rf extends T{constructor(t){super(),this.outcome=wt.UNSPECIFIED,this.reason="",this.cursorOnlyEnterprise=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rf).fromBinary(t,r)}static fromJson(t,r){return(new rf).fromJson(t,r)}static fromJsonString(t,r){return(new rf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rf,t,r)}static $(){return["GrokAdminCallStatus|1 outcome #0|2 reason 9|3 cursor_only_enterprise 8",wt]}}class ef extends T{constructor(t){super(),this.enableFileUploads=!1,this.enableImageUploads=!1,this.enableWebSearch=!1,this.enableXSearch=!1,this.enableVoiceMode=!1,this.enableImagine=!1,this.enableImagineChat=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ef).fromBinary(t,r)}static fromJson(t,r){return(new ef).fromJson(t,r)}static fromJsonString(t,r){return(new ef).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ef,t,r)}static $(){return["GrokAdminFeatureControls|1 enable_file_uploads 8|2 enable_image_uploads 8|3 enable_web_search 8|4 enable_x_search 8|5 enable_voice_mode 8|6 enable_imagine 8|7 enable_imagine_chat 8|8 enable_grok_chat 8?|9 enable_dictation 8?|10 enable_bots 8?"]}}class nf extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nf).fromBinary(t,r)}static fromJson(t,r){return(new nf).fromJson(t,r)}static fromJsonString(t,r){return(new nf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nf,t,r)}static $(){return["GetGrokAdminFeatureControlsRequest|1 team_id 5"]}}class sf extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sf).fromBinary(t,r)}static fromJson(t,r){return(new sf).fromJson(t,r)}static fromJsonString(t,r){return(new sf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sf,t,r)}static $(){return["GetGrokAdminFeatureControlsResponse|1 status #0|2 controls #1",rf,ef]}}class of extends T{constructor(t){super(),this.teamId=0,this.field=yt.UNSPECIFIED,this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new of).fromBinary(t,r)}static fromJson(t,r){return(new of).fromJson(t,r)}static fromJsonString(t,r){return(new of).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(of,t,r)}static $(){return["UpdateGrokAdminFeatureControlsRequest|1 team_id 5|2 field #0|3 enabled 8",yt]}}class af extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new af).fromBinary(t,r)}static fromJson(t,r){return(new af).fromJson(t,r)}static fromJsonString(t,r){return(new af).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(af,t,r)}static $(){return["UpdateGrokAdminFeatureControlsResponse|1 status #0|2 controls #1",rf,ef]}}class uf extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uf).fromBinary(t,r)}static fromJson(t,r){return(new uf).fromJson(t,r)}static fromJsonString(t,r){return(new uf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uf,t,r)}static $(){return["GetGrokUserDataControlsRequest"]}}class cf extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cf).fromBinary(t,r)}static fromJson(t,r){return(new cf).fromJson(t,r)}static fromJsonString(t,r){return(new cf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cf,t,r)}static $(){return["UpdateGrokUserDataControlsRequest|1 exclude_from_training 8?|2 enable_memory 8?"]}}class lf extends T{constructor(t){super(),this.status=St.UNSPECIFIED,this.excludeFromTrainingLocked=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lf).fromBinary(t,r)}static fromJson(t,r){return(new lf).fromJson(t,r)}static fromJsonString(t,r){return(new lf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lf,t,r)}static $(){return["GetGrokUserDataControlsResponse|1 status #0|2 exclude_from_training 8?|3 enable_memory 8?|4 exclude_from_training_locked 8",St]}}class mf extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mf).fromBinary(t,r)}static fromJson(t,r){return(new mf).fromJson(t,r)}static fromJsonString(t,r){return(new mf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mf,t,r)}static $(){return["UpdateGrokUserDataControlsResponse|1 exclude_from_training 8?|2 enable_memory 8?"]}}class ff extends T{constructor(t){super(),this.apiKeyIds=[],this.requestIds=[],this.modelNames=[],this.kinds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ff).fromBinary(t,r)}static fromJson(t,r){return(new ff).fromJson(t,r)}static fromJsonString(t,r){return(new ff).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ff,t,r)}static $(){return["GrokRequestLogFilter|1 api_key_ids 9*|2 time_from_ms 3?|3 time_to_ms 3?|4 request_ids 9*|5 model_names 9*|6 kinds #0*",qt]}}class df extends T{constructor(t){super(),this.teamId=0,this.pageSize=0,this.cursor="",this.timeAscending=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new df).fromBinary(t,r)}static fromJson(t,r){return(new df).fromJson(t,r)}static fromJsonString(t,r){return(new df).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(df,t,r)}static $(){return["ListGrokRequestLogsRequest|1 team_id 5|2 filter #0|3 page_size 5|4 cursor 9|5 time_ascending 8",ff]}}class pf extends T{constructor(t){super(),this.teamLinked=!1,this.userLinked=!1,this.entries=[],this.nextCursor="",this.totalCount=n.protoInt64.zero,this.zeroDataRetention=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pf).fromBinary(t,r)}static fromJson(t,r){return(new pf).fromJson(t,r)}static fromJsonString(t,r){return(new pf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pf,t,r)}static $(){return["ListGrokRequestLogsResponse|1 team_linked 8|2 user_linked 8|3 entries #0*|4 next_cursor 9|5 total_count 3|6 zero_data_retention 8",hf]}}class hf extends T{constructor(t){super(),this.requestId="",this.apiKeyId="",this.timestampMs=n.protoInt64.zero,this.modelName="",this.kind=qt.UNSPECIFIED,this.bodyLogged=!1,this.conversationId="",this.previousResponseId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hf).fromBinary(t,r)}static fromJson(t,r){return(new hf).fromJson(t,r)}static fromJsonString(t,r){return(new hf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hf,t,r)}static $(){return["GrokRequestLog|1 request_id 9|2 api_key_id 9|3 timestamp_ms 3|4 model_name 9|5 kind #0|6 body_logged 8|7 conversation_id 9|8 previous_response_id 9",qt]}}class gf extends T{constructor(t){super(),this.teamId=0,this.pageSize=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gf).fromBinary(t,r)}static fromJson(t,r){return(new gf).fromJson(t,r)}static fromJsonString(t,r){return(new gf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gf,t,r)}static $(){return["ListGrokRequestLogBodiesRequest|1 team_id 5|2 filter #0|3 page_size 5",ff]}}class _f extends T{constructor(t){super(),this.teamLinked=!1,this.userLinked=!1,this.entries=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _f).fromBinary(t,r)}static fromJson(t,r){return(new _f).fromJson(t,r)}static fromJsonString(t,r){return(new _f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_f,t,r)}static $(){return["ListGrokRequestLogBodiesResponse|1 team_linked 8|2 user_linked 8|3 entries #0*",Jf]}}class Jf extends T{constructor(t){super(),this.requestJson="",this.responseJson="",this.partialHistory=!1,this.missingBody=wf.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jf).fromBinary(t,r)}static fromJson(t,r){return(new Jf).fromJson(t,r)}static fromJsonString(t,r){return(new Jf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jf,t,r)}static $(){return["GrokRequestLogEntry|1 meta #0|2 request_json 9|3 response_json 9|4 partial_history 8|5 missing_body #1",hf,wf]}}var wf=(0,a.QT)(n.proto3,C,"GrokRequestLogEntry.MissingBody",[[0,"UNSPECIFIED"],[1,"NOT_LOGGED"],[2,"UNREADABLE"]],1);class yf extends T{constructor(t){super(),this.teamId=0,this.pageSize=0,this.pageToken="",this.conversationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yf).fromBinary(t,r)}static fromJson(t,r){return(new yf).fromJson(t,r)}static fromJsonString(t,r){return(new yf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yf,t,r)}static $(){return["ListGrokVoiceConversationsRequest|1 team_id 5|2 page_size 5|3 page_token 9|4 time_from_ms 3?|5 time_to_ms 3?|6 min_duration_seconds 13?|7 max_duration_seconds 13?|8 conversation_id 9"]}}class Sf extends T{constructor(t){super(),this.teamLinked=!1,this.userLinked=!1,this.conversations=[],this.nextPageToken="",this.prevPageToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sf).fromBinary(t,r)}static fromJson(t,r){return(new Sf).fromJson(t,r)}static fromJsonString(t,r){return(new Sf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sf,t,r)}static $(){return["ListGrokVoiceConversationsResponse|1 team_linked 8|2 user_linked 8|3 conversations #0*|4 next_page_token 9|5 prev_page_token 9",qf]}}class qf extends T{constructor(t){super(),this.conversationId="",this.startTimeMs=n.protoInt64.zero,this.endTimeMs=n.protoInt64.zero,this.callerPhoneNumber="",this.destinationPhoneNumber="",this.agentIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qf).fromBinary(t,r)}static fromJson(t,r){return(new qf).fromJson(t,r)}static fromJsonString(t,r){return(new qf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qf,t,r)}static $(){return["GrokVoiceConversation|1 conversation_id 9|2 start_time_ms 3|3 end_time_ms 3|4 caller_phone_number 9|5 destination_phone_number 9|6 agent_ids 9*"]}}class Bf extends T{constructor(t){super(),this.conversations=Bt.UNSPECIFIED,this.projects=It.UNSPECIFIED,this.skills=Pt.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bf).fromBinary(t,r)}static fromJson(t,r){return(new Bf).fromJson(t,r)}static fromJsonString(t,r){return(new Bf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bf,t,r)}static $(){return["GrokAdminSharingCeiling|1 conversations #0|2 projects #1|3 skills #2",Bt,It,Pt]}}class If extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new If).fromBinary(t,r)}static fromJson(t,r){return(new If).fromJson(t,r)}static fromJsonString(t,r){return(new If).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(If,t,r)}static $(){return["GetGrokAdminTeamSettingsRequest|1 team_id 5"]}}class Pf extends T{constructor(t){super(),this.conversationsRetentionPeriodDisabled=!1,this.conversationSharing=Bt.UNSPECIFIED,this.projectSharing=It.UNSPECIFIED,this.skillSharing=Pt.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pf).fromBinary(t,r)}static fromJson(t,r){return(new Pf).fromJson(t,r)}static fromJsonString(t,r){return(new Pf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pf,t,r)}static $(){return["GetGrokAdminTeamSettingsResponse|1 status #0|2 conversations_retention_period_days 5?|3 conversations_retention_period_disabled 8|4 conversation_sharing #1|5 project_sharing #2|6 skill_sharing #3|7 organization_ceiling #4",rf,Bt,It,Pt,Bf]}}class bf extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bf).fromBinary(t,r)}static fromJson(t,r){return(new bf).fromJson(t,r)}static fromJsonString(t,r){return(new bf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bf,t,r)}static $(){return["UpdateGrokAdminTeamSettingsRequest|1 team_id 5|2 conversations_retention_period_days 5?|3 conversations_retention_period_disabled 8?|4 conversation_sharing #0?|5 project_sharing #1?|6 skill_sharing #2?",Bt,It,Pt]}}class Rf extends T{constructor(t){super(),this.conversationsRetentionPeriodDisabled=!1,this.conversationSharing=Bt.UNSPECIFIED,this.projectSharing=It.UNSPECIFIED,this.skillSharing=Pt.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rf).fromBinary(t,r)}static fromJson(t,r){return(new Rf).fromJson(t,r)}static fromJsonString(t,r){return(new Rf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rf,t,r)}static $(){return["UpdateGrokAdminTeamSettingsResponse|1 status #0|2 conversations_retention_period_days 5?|3 conversations_retention_period_disabled 8|4 conversation_sharing #1|5 project_sharing #2|6 skill_sharing #3|7 organization_ceiling #4",rf,Bt,It,Pt,Bf]}}class vf extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vf).fromBinary(t,r)}static fromJson(t,r){return(new vf).fromJson(t,r)}static fromJsonString(t,r){return(new vf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vf,t,r)}static $(){return["GetGrokAdminOrganizationControlsRequest|1 team_id 5"]}}class xf extends T{constructor(t){super(),this.conversationsRetentionPeriodDisabled=!1,this.conversationSharing=Bt.UNSPECIFIED,this.projectSharing=It.UNSPECIFIED,this.skillSharing=Pt.UNSPECIFIED,this.disableDictation=!1,this.disableBots=!1,this.disablePrivateChats=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xf).fromBinary(t,r)}static fromJson(t,r){return(new xf).fromJson(t,r)}static fromJsonString(t,r){return(new xf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xf,t,r)}static $(){return["GetGrokAdminOrganizationControlsResponse|1 status #0|2 conversations_retention_period_days 5?|3 conversations_retention_period_disabled 8|4 conversation_sharing #1|5 project_sharing #2|6 skill_sharing #3|7 disable_dictation 8|8 disable_bots 8|9 disable_private_chats 8",rf,Bt,It,Pt]}}class kf extends T{constructor(t){super(),this.teamId=0,this.retention=bt.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kf).fromBinary(t,r)}static fromJson(t,r){return(new kf).fromJson(t,r)}static fromJsonString(t,r){return(new kf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kf,t,r)}static $(){return["UpdateGrokAdminOrganizationControlsRequest|1 team_id 5|2 retention #0|3 conversations_retention_period_days 5?|4 conversation_sharing #1?|5 project_sharing #2?|6 skill_sharing #3?|7 disable_dictation 8?|8 disable_bots 8?|9 disable_private_chats 8?",bt,Bt,It,Pt]}}class Ef extends T{constructor(t){super(),this.conversationsRetentionPeriodDisabled=!1,this.conversationSharing=Bt.UNSPECIFIED,this.projectSharing=It.UNSPECIFIED,this.skillSharing=Pt.UNSPECIFIED,this.disableDictation=!1,this.disableBots=!1,this.disablePrivateChats=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ef).fromBinary(t,r)}static fromJson(t,r){return(new Ef).fromJson(t,r)}static fromJsonString(t,r){return(new Ef).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ef,t,r)}static $(){return["UpdateGrokAdminOrganizationControlsResponse|1 status #0|2 conversations_retention_period_days 5?|3 conversations_retention_period_disabled 8|4 conversation_sharing #1|5 project_sharing #2|6 skill_sharing #3|7 disable_dictation 8|8 disable_bots 8|9 disable_private_chats 8",rf,Bt,It,Pt]}}class Cf extends T{constructor(t){super(),this.guardrailId="",this.guardrailName="",this.guardrailContent="",this.isActive=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cf).fromBinary(t,r)}static fromJson(t,r){return(new Cf).fromJson(t,r)}static fromJsonString(t,r){return(new Cf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cf,t,r)}static $(){return["GrokAdminGuardrail|1 guardrail_id 9|2 guardrail_name 9|3 guardrail_description 9?|4 guardrail_content 9|5 is_active 8"]}}class Tf extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tf).fromBinary(t,r)}static fromJson(t,r){return(new Tf).fromJson(t,r)}static fromJsonString(t,r){return(new Tf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tf,t,r)}static $(){return["ListGrokAdminGuardrailsRequest|1 team_id 5"]}}class Uf extends T{constructor(t){super(),this.guardrails=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Uf).fromBinary(t,r)}static fromJson(t,r){return(new Uf).fromJson(t,r)}static fromJsonString(t,r){return(new Uf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Uf,t,r)}static $(){return["ListGrokAdminGuardrailsResponse|1 status #0|2 guardrails #1*",rf,Cf]}}class Af extends T{constructor(t){super(),this.teamId=0,this.guardrailId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Af).fromBinary(t,r)}static fromJson(t,r){return(new Af).fromJson(t,r)}static fromJsonString(t,r){return(new Af).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Af,t,r)}static $(){return["GetGrokAdminGuardrailRequest|1 team_id 5|2 guardrail_id 9"]}}class $f extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $f).fromBinary(t,r)}static fromJson(t,r){return(new $f).fromJson(t,r)}static fromJsonString(t,r){return(new $f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($f,t,r)}static $(){return["GetGrokAdminGuardrailResponse|1 status #0|2 guardrail #1",rf,Cf]}}class Mf extends T{constructor(t){super(),this.teamId=0,this.guardrailName="",this.guardrailDescription="",this.guardrailContent="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mf).fromBinary(t,r)}static fromJson(t,r){return(new Mf).fromJson(t,r)}static fromJsonString(t,r){return(new Mf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mf,t,r)}static $(){return["CreateGrokAdminGuardrailRequest|1 team_id 5|2 guardrail_name 9|3 guardrail_description 9|4 guardrail_content 9"]}}class Of extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Of).fromBinary(t,r)}static fromJson(t,r){return(new Of).fromJson(t,r)}static fromJsonString(t,r){return(new Of).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Of,t,r)}static $(){return["CreateGrokAdminGuardrailResponse|1 status #0|2 guardrail #1",rf,Cf]}}class Df extends T{constructor(t){super(),this.teamId=0,this.guardrailId="",this.guardrailName="",this.guardrailDescription="",this.guardrailContent="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Df).fromBinary(t,r)}static fromJson(t,r){return(new Df).fromJson(t,r)}static fromJsonString(t,r){return(new Df).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Df,t,r)}static $(){return["UpdateGrokAdminGuardrailRequest|1 team_id 5|2 guardrail_id 9|3 guardrail_name 9|4 guardrail_description 9|5 guardrail_content 9"]}}class Nf extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nf).fromBinary(t,r)}static fromJson(t,r){return(new Nf).fromJson(t,r)}static fromJsonString(t,r){return(new Nf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nf,t,r)}static $(){return["UpdateGrokAdminGuardrailResponse|1 status #0|2 guardrail #1",rf,Cf]}}class Gf extends T{constructor(t){super(),this.teamId=0,this.guardrailId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gf).fromBinary(t,r)}static fromJson(t,r){return(new Gf).fromJson(t,r)}static fromJsonString(t,r){return(new Gf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gf,t,r)}static $(){return["RemoveGrokAdminGuardrailRequest|1 team_id 5|2 guardrail_id 9"]}}class Lf extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lf).fromBinary(t,r)}static fromJson(t,r){return(new Lf).fromJson(t,r)}static fromJsonString(t,r){return(new Lf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Lf,t,r)}static $(){return["RemoveGrokAdminGuardrailResponse|1 status #0",rf]}}class Ff extends T{constructor(t){super(),this.teamId=0,this.guardrailId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ff).fromBinary(t,r)}static fromJson(t,r){return(new Ff).fromJson(t,r)}static fromJsonString(t,r){return(new Ff).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ff,t,r)}static $(){return["SetGrokAdminGuardrailActiveRequest|1 team_id 5|2 guardrail_id 9"]}}class Kf extends T{constructor(t){super(),this.guardrails=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kf).fromBinary(t,r)}static fromJson(t,r){return(new Kf).fromJson(t,r)}static fromJsonString(t,r){return(new Kf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Kf,t,r)}static $(){return["SetGrokAdminGuardrailActiveResponse|1 status #0|2 guardrails #1*",rf,Cf]}}class zf extends T{constructor(t){super(),this.teamId=0,this.guardrailId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zf).fromBinary(t,r)}static fromJson(t,r){return(new zf).fromJson(t,r)}static fromJsonString(t,r){return(new zf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zf,t,r)}static $(){return["DeactivateGrokAdminGuardrailRequest|1 team_id 5|2 guardrail_id 9"]}}class jf extends T{constructor(t){super(),this.guardrails=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jf).fromBinary(t,r)}static fromJson(t,r){return(new jf).fromJson(t,r)}static fromJsonString(t,r){return(new jf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jf,t,r)}static $(){return["DeactivateGrokAdminGuardrailResponse|1 status #0|2 guardrails #1*",rf,Cf]}}class Hf extends T{constructor(t){super(),this.hasBlocklist=!1,this.entryCount=n.protoInt64.zero,this.fileName="",this.version=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hf).fromBinary(t,r)}static fromJson(t,r){return(new Hf).fromJson(t,r)}static fromJsonString(t,r){return(new Hf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hf,t,r)}static $(){return["GrokAdminBlockedUrlInfo|1 has_blocklist 8|2 entry_count 3|3 uploaded_at 3?|4 file_name 9|5 version 5"]}}class Wf extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wf).fromBinary(t,r)}static fromJson(t,r){return(new Wf).fromJson(t,r)}static fromJsonString(t,r){return(new Wf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wf,t,r)}static $(){return["GetGrokAdminBlockedUrlsRequest|1 team_id 5"]}}class Qf extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qf).fromBinary(t,r)}static fromJson(t,r){return(new Qf).fromJson(t,r)}static fromJsonString(t,r){return(new Qf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qf,t,r)}static $(){return["GetGrokAdminBlockedUrlsResponse|1 status #0|2 info #1",rf,Hf]}}class Vf extends T{constructor(t){super(),this.teamId=0,this.fileName="",this.content=new Uint8Array(0),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vf).fromBinary(t,r)}static fromJson(t,r){return(new Vf).fromJson(t,r)}static fromJsonString(t,r){return(new Vf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vf,t,r)}static $(){return["UploadGrokAdminBlockedUrlsRequest|1 team_id 5|2 file_name 9|3 content 12"]}}class Xf extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xf).fromBinary(t,r)}static fromJson(t,r){return(new Xf).fromJson(t,r)}static fromJsonString(t,r){return(new Xf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xf,t,r)}static $(){return["UploadGrokAdminBlockedUrlsResponse|1 status #0|2 info #1",rf,Hf]}}class Yf extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yf).fromBinary(t,r)}static fromJson(t,r){return(new Yf).fromJson(t,r)}static fromJsonString(t,r){return(new Yf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yf,t,r)}static $(){return["DeleteGrokAdminBlockedUrlsRequest|1 team_id 5"]}}class Zf extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zf).fromBinary(t,r)}static fromJson(t,r){return(new Zf).fromJson(t,r)}static fromJsonString(t,r){return(new Zf).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zf,t,r)}static $(){return["DeleteGrokAdminBlockedUrlsResponse|1 status #0",rf]}}class td extends T{constructor(t){super(),this.id="",this.promptText="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new td).fromBinary(t,r)}static fromJson(t,r){return(new td).fromJson(t,r)}static fromJsonString(t,r){return(new td).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(td,t,r)}static $(){return["GrokAdminOnboardingPrompt|1 id 9|2 prompt_text 9|3 source 9?|4 connector_id 9?"]}}class rd extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rd).fromBinary(t,r)}static fromJson(t,r){return(new rd).fromJson(t,r)}static fromJsonString(t,r){return(new rd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rd,t,r)}static $(){return["ListGrokAdminOnboardingPromptsRequest|1 team_id 5"]}}class ed extends T{constructor(t){super(),this.prompts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ed).fromBinary(t,r)}static fromJson(t,r){return(new ed).fromJson(t,r)}static fromJsonString(t,r){return(new ed).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ed,t,r)}static $(){return["ListGrokAdminOnboardingPromptsResponse|1 status #0|2 prompts #1*",rf,td]}}class nd extends T{constructor(t){super(),this.teamId=0,this.promptText="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nd).fromBinary(t,r)}static fromJson(t,r){return(new nd).fromJson(t,r)}static fromJsonString(t,r){return(new nd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nd,t,r)}static $(){return["CreateGrokAdminOnboardingPromptRequest|1 team_id 5|2 prompt_text 9|3 source 9?|4 connector_id 9?"]}}class sd extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sd).fromBinary(t,r)}static fromJson(t,r){return(new sd).fromJson(t,r)}static fromJsonString(t,r){return(new sd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sd,t,r)}static $(){return["CreateGrokAdminOnboardingPromptResponse|1 status #0|2 prompt #1",rf,td]}}class id extends T{constructor(t){super(),this.teamId=0,this.promptId="",this.promptText="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new id).fromBinary(t,r)}static fromJson(t,r){return(new id).fromJson(t,r)}static fromJsonString(t,r){return(new id).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(id,t,r)}static $(){return["UpdateGrokAdminOnboardingPromptRequest|1 team_id 5|2 prompt_id 9|3 prompt_text 9|4 source 9?|5 connector_id 9?"]}}class od extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new od).fromBinary(t,r)}static fromJson(t,r){return(new od).fromJson(t,r)}static fromJsonString(t,r){return(new od).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(od,t,r)}static $(){return["UpdateGrokAdminOnboardingPromptResponse|1 status #0|2 prompt #1",rf,td]}}class ad extends T{constructor(t){super(),this.teamId=0,this.promptId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ad).fromBinary(t,r)}static fromJson(t,r){return(new ad).fromJson(t,r)}static fromJsonString(t,r){return(new ad).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ad,t,r)}static $(){return["DeleteGrokAdminOnboardingPromptRequest|1 team_id 5|2 prompt_id 9"]}}class ud extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ud).fromBinary(t,r)}static fromJson(t,r){return(new ud).fromJson(t,r)}static fromJsonString(t,r){return(new ud).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ud,t,r)}static $(){return["DeleteGrokAdminOnboardingPromptResponse|1 status #0",rf]}}class cd extends T{constructor(t){super(),this.apiKeyId="",this.maskedKey="",this.name="",this.acls=[],this.createdAt=n.protoInt64.zero,this.updatedAt=n.protoInt64.zero,this.ipRanges=[],this.ipRangesUnreadable=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cd).fromBinary(t,r)}static fromJson(t,r){return(new cd).fromJson(t,r)}static fromJsonString(t,r){return(new cd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cd,t,r)}static $(){return["XaiManagementApiKey|1 api_key_id 9|2 masked_key 9|3 name 9|4 acls 9*|5 created_at 3|6 updated_at 3|7 ip_ranges 9*|8 ip_ranges_unreadable 8|9 owner #0",Nm]}}class ld extends T{constructor(t){super(),this.acl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ld).fromBinary(t,r)}static fromJson(t,r){return(new ld).fromJson(t,r)}static fromJsonString(t,r){return(new ld).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ld,t,r)}static $(){return["XaiManagementApiKeyEndpointAcl|1 acl 9|2 description 9?"]}}class md extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new md).fromBinary(t,r)}static fromJson(t,r){return(new md).fromJson(t,r)}static fromJsonString(t,r){return(new md).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(md,t,r)}static $(){return["ListXaiManagementApiKeysRequest|1 team_id 5"]}}class fd extends T{constructor(t){super(),this.apiKeys=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fd).fromBinary(t,r)}static fromJson(t,r){return(new fd).fromJson(t,r)}static fromJsonString(t,r){return(new fd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fd,t,r)}static $(){return["ListXaiManagementApiKeysResponse|1 api_keys #0*|2 team_linked 8?",cd]}}class dd extends T{constructor(t){super(),this.teamId=0,this.name="",this.acls=[],this.ipRanges=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dd).fromBinary(t,r)}static fromJson(t,r){return(new dd).fromJson(t,r)}static fromJsonString(t,r){return(new dd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dd,t,r)}static $(){return["CreateXaiManagementApiKeyRequest|1 team_id 5|2 name 9|3 acls 9*|4 ip_ranges 9*"]}}class pd extends T{constructor(t){super(),this.apiKey="",this.apiKeyId="",this.acls=[],this.ipRanges=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pd).fromBinary(t,r)}static fromJson(t,r){return(new pd).fromJson(t,r)}static fromJsonString(t,r){return(new pd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pd,t,r)}static $(){return["CreateXaiManagementApiKeyResponse|1 api_key 9|2 api_key_id 9|3 acls 9*|4 ip_ranges 9*"]}}class hd extends T{constructor(t){super(),this.cidrs=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hd).fromBinary(t,r)}static fromJson(t,r){return(new hd).fromJson(t,r)}static fromJsonString(t,r){return(new hd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hd,t,r)}static $(){return["XaiManagementApiKeyIpRanges|1 cidrs 9*"]}}class gd extends T{constructor(t){super(),this.teamId=0,this.apiKeyId="",this.name="",this.acls=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gd).fromBinary(t,r)}static fromJson(t,r){return(new gd).fromJson(t,r)}static fromJsonString(t,r){return(new gd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gd,t,r)}static $(){return["UpdateXaiManagementApiKeyRequest|1 team_id 5|2 api_key_id 9|3 name 9|4 acls 9*|5 ip_ranges #0",hd]}}class _d extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _d).fromBinary(t,r)}static fromJson(t,r){return(new _d).fromJson(t,r)}static fromJsonString(t,r){return(new _d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_d,t,r)}static $(){return["UpdateXaiManagementApiKeyResponse"]}}class Jd extends T{constructor(t){super(),this.teamId=0,this.apiKeyId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jd).fromBinary(t,r)}static fromJson(t,r){return(new Jd).fromJson(t,r)}static fromJsonString(t,r){return(new Jd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jd,t,r)}static $(){return["DeleteXaiManagementApiKeyRequest|1 team_id 5|2 api_key_id 9"]}}class wd extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wd).fromBinary(t,r)}static fromJson(t,r){return(new wd).fromJson(t,r)}static fromJsonString(t,r){return(new wd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wd,t,r)}static $(){return["DeleteXaiManagementApiKeyResponse"]}}class yd extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yd).fromBinary(t,r)}static fromJson(t,r){return(new yd).fromJson(t,r)}static fromJsonString(t,r){return(new yd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yd,t,r)}static $(){return["ListXaiManagementApiKeyEndpointAclsRequest|1 team_id 5"]}}class Sd extends T{constructor(t){super(),this.acls=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sd).fromBinary(t,r)}static fromJson(t,r){return(new Sd).fromJson(t,r)}static fromJsonString(t,r){return(new Sd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sd,t,r)}static $(){return["ListXaiManagementApiKeyEndpointAclsResponse|1 acls #0*",ld]}}class qd extends T{constructor(t){super(),this.id="",this.maskedKey="",this.name="",this.createdAt=n.protoInt64.zero,this.scopes=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qd).fromBinary(t,r)}static fromJson(t,r){return(new qd).fromJson(t,r)}static fromJsonString(t,r){return(new qd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qd,t,r)}static $(){return["OrganizationApiKey|1 id 9|2 masked_key 9|3 name 9|4 created_at 3|5 scopes 9*|6 expires_at 3?|7 creator #0|8 last_use #1",Jp,yp]}}class Bd extends T{constructor(t){super(),this.organizationId="",this.name="",this.scopes=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bd).fromBinary(t,r)}static fromJson(t,r){return(new Bd).fromJson(t,r)}static fromJsonString(t,r){return(new Bd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bd,t,r)}static $(){return["CreateOrganizationApiKeyRequest|1 organization_id 9|2 name 9|3 scopes 9*|4 expires_at 3?"]}}class Id extends T{constructor(t){super(),this.apiKey="",this.apiKeyId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Id).fromBinary(t,r)}static fromJson(t,r){return(new Id).fromJson(t,r)}static fromJsonString(t,r){return(new Id).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Id,t,r)}static $(){return["CreateOrganizationApiKeyResponse|1 api_key 9|2 api_key_id 9"]}}class Pd extends T{constructor(t){super(),this.organizationId="",this.apiKeyId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pd).fromBinary(t,r)}static fromJson(t,r){return(new Pd).fromJson(t,r)}static fromJsonString(t,r){return(new Pd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pd,t,r)}static $(){return["RevokeOrganizationApiKeyRequest|1 organization_id 9|2 api_key_id 9"]}}class bd extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bd).fromBinary(t,r)}static fromJson(t,r){return(new bd).fromJson(t,r)}static fromJsonString(t,r){return(new bd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bd,t,r)}static $(){return["RevokeOrganizationApiKeyResponse"]}}class Rd extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rd).fromBinary(t,r)}static fromJson(t,r){return(new Rd).fromJson(t,r)}static fromJsonString(t,r){return(new Rd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rd,t,r)}static $(){return["ListOrganizationApiKeysRequest|1 organization_id 9"]}}class vd extends T{constructor(t){super(),this.apiKeys=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vd).fromBinary(t,r)}static fromJson(t,r){return(new vd).fromJson(t,r)}static fromJsonString(t,r){return(new vd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vd,t,r)}static $(){return["ListOrganizationApiKeysResponse|1 api_keys #0*",qd]}}class xd extends T{constructor(t){super(),this.teamId=0,this.name="",this.initialRepoScope=[],this.permissionIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xd).fromBinary(t,r)}static fromJson(t,r){return(new xd).fromJson(t,r)}static fromJsonString(t,r){return(new xd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xd,t,r)}static $(){return["CreateTeamServiceAccountRequest|1 team_id 5|2 name 9|3 description 9?|4 initial_repo_scope 9*|5 initial_repo_scope_enabled 8?|6 permission_ids 9*|7 castle_request_token 9?"]}}class kd extends T{constructor(t){super(),this.apiKey="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kd).fromBinary(t,r)}static fromJson(t,r){return(new kd).fromJson(t,r)}static fromJsonString(t,r){return(new kd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kd,t,r)}static $(){return["CreateTeamServiceAccountResponse|1 service_account #0|2 api_key 9",Td]}}class Ed extends T{constructor(t){super(),this.teamId=0,this.pageToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ed).fromBinary(t,r)}static fromJson(t,r){return(new Ed).fromJson(t,r)}static fromJsonString(t,r){return(new Ed).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ed,t,r)}static $(){return["ListTeamServiceAccountsRequest|1 team_id 5|2 include_archived 8?|3 include_creators 8?|4 page_size 5?|5 page_token 9|6 query 9?"]}}class Cd extends T{constructor(t){super(),this.serviceAccounts=[],this.nextPageToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cd).fromBinary(t,r)}static fromJson(t,r){return(new Cd).fromJson(t,r)}static fromJsonString(t,r){return(new Cd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cd,t,r)}static $(){return["ListTeamServiceAccountsResponse|1 service_accounts #0*|2 next_page_token 9",Td]}}class Td extends T{constructor(t){super(),this.id="",this.serviceType="",this.name="",this.createdAt=n.protoInt64.zero,this.updatedAt=n.protoInt64.zero,this.defaultScopes=[],this.apiKeys=[],this.serviceTokens=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Td).fromBinary(t,r)}static fromJson(t,r){return(new Td).fromJson(t,r)}static fromJsonString(t,r){return(new Td).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Td,t,r)}static $(){return["ServiceAccountInfo|1 id 9|2 service_type 9|3 name 9|4 description 9?|5 created_by_user_id 5?|6 owning_team_id 5?|7 owning_user_id 5?|8 usage_limit_cents 5?|9 created_at 3|10 updated_at 3|11 default_scopes 9*|12 api_keys #0*|13 archived_at 3?|14 current_period_spend_cents 5?|15 suspended_at 3?|16 service_tokens #1*|17 creator #2|18 last_use #3",Ud,Xp,Jp,yp]}}class Ud extends T{constructor(t){super(),this.apiKeyId=0,this.maskedApiKey="",this.scopes=[],this.createdAt=n.protoInt64.zero,this.repoScope=[],this.repoScopeEnabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ud).fromBinary(t,r)}static fromJson(t,r){return(new Ud).fromJson(t,r)}static fromJsonString(t,r){return(new Ud).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ud,t,r)}static $(){return["ServiceAccountKeyInfo|1 api_key_id 5|2 masked_api_key 9|3 scopes 9*|4 created_at 3|5 repo_scope 9*|6 repo_scope_enabled 8|7 creator #0|8 last_use #1",Jp,yp]}}class Ad extends T{constructor(t){super(),this.teamId=0,this.serviceAccountId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ad).fromBinary(t,r)}static fromJson(t,r){return(new Ad).fromJson(t,r)}static fromJsonString(t,r){return(new Ad).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ad,t,r)}static $(){return["DeleteTeamServiceAccountRequest|1 team_id 5|2 service_account_id 9"]}}class $d extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $d).fromBinary(t,r)}static fromJson(t,r){return(new $d).fromJson(t,r)}static fromJsonString(t,r){return(new $d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($d,t,r)}static $(){return["DeleteTeamServiceAccountResponse"]}}class Md extends T{constructor(t){super(),this.teamId=0,this.serviceAccountId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Md).fromBinary(t,r)}static fromJson(t,r){return(new Md).fromJson(t,r)}static fromJsonString(t,r){return(new Md).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Md,t,r)}static $(){return["ArchiveTeamServiceAccountRequest|1 team_id 5|2 service_account_id 9"]}}class Od extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Od).fromBinary(t,r)}static fromJson(t,r){return(new Od).fromJson(t,r)}static fromJsonString(t,r){return(new Od).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Od,t,r)}static $(){return["ArchiveTeamServiceAccountResponse"]}}class Dd extends T{constructor(t){super(),this.teamId=0,this.serviceAccountId="",this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dd).fromBinary(t,r)}static fromJson(t,r){return(new Dd).fromJson(t,r)}static fromJsonString(t,r){return(new Dd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dd,t,r)}static $(){return["UpdateTeamServiceAccountRequest|1 team_id 5|2 service_account_id 9|3 name 9|4 description 9?"]}}class Nd extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nd).fromBinary(t,r)}static fromJson(t,r){return(new Nd).fromJson(t,r)}static fromJsonString(t,r){return(new Nd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nd,t,r)}static $(){return["UpdateTeamServiceAccountResponse"]}}class Gd extends T{constructor(t){super(),this.teamId=0,this.serviceAccountId="",this.permissionIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gd).fromBinary(t,r)}static fromJson(t,r){return(new Gd).fromJson(t,r)}static fromJsonString(t,r){return(new Gd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gd,t,r)}static $(){return["RotateServiceAccountApiKeyRequest|1 team_id 5|2 service_account_id 9|3 old_api_key_id 5?|4 permission_ids 9*|5 old_service_token_public_id 9?|6 castle_request_token 9?"]}}class Ld extends T{constructor(t){super(),this.apiKey="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ld).fromBinary(t,r)}static fromJson(t,r){return(new Ld).fromJson(t,r)}static fromJsonString(t,r){return(new Ld).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ld,t,r)}static $(){return["RotateServiceAccountApiKeyResponse|1 api_key 9|2 key_info #0|3 service_token #1",Ud,Xp]}}class Fd extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fd).fromBinary(t,r)}static fromJson(t,r){return(new Fd).fromJson(t,r)}static fromJsonString(t,r){return(new Fd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fd,t,r)}static $(){return["GetTeamRepositoriesForServiceAccountScopeRequest|1 team_id 5"]}}class Kd extends T{constructor(t){super(),this.owner="",this.name="",this.htmlUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kd).fromBinary(t,r)}static fromJson(t,r){return(new Kd).fromJson(t,r)}static fromJsonString(t,r){return(new Kd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Kd,t,r)}static $(){return["ServiceAccountScopeRepository|1 owner 9|2 name 9|3 html_url 9"]}}class zd extends T{constructor(t){super(),this.repositories=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zd).fromBinary(t,r)}static fromJson(t,r){return(new zd).fromJson(t,r)}static fromJsonString(t,r){return(new zd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zd,t,r)}static $(){return["GetTeamRepositoriesForServiceAccountScopeResponse|1 repositories #0*",Kd]}}class jd extends T{constructor(t){super(),this.teamId=0,this.serviceAccountId="",this.apiKeyId=0,this.repoScope=[],this.repoScopeEnabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jd).fromBinary(t,r)}static fromJson(t,r){return(new jd).fromJson(t,r)}static fromJsonString(t,r){return(new jd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jd,t,r)}static $(){return["UpdateServiceAccountRepoScopeRequest|1 team_id 5|2 service_account_id 9|3 api_key_id 5|4 repo_scope 9*|5 repo_scope_enabled 8|6 service_token_public_id 9?"]}}class Hd extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hd).fromBinary(t,r)}static fromJson(t,r){return(new Hd).fromJson(t,r)}static fromJsonString(t,r){return(new Hd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hd,t,r)}static $(){return["UpdateServiceAccountRepoScopeResponse|1 api_key #0|2 service_token #1",Ud,Xp]}}class Wd extends T{constructor(t){super(),this.challengeId="",this.browserBinding="",this.surfaceOrigin="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wd).fromBinary(t,r)}static fromJson(t,r){return(new Wd).fromJson(t,r)}static fromJsonString(t,r){return(new Wd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wd,t,r)}static $(){return["StartStepUpRequest|1 challenge_id 9|2 browser_binding 9|3 surface_origin 9"]}}class Qd extends T{constructor(t){super(),this.status=Vd.UNSPECIFIED,this.maskedEmail="",this.actionDescription="",this.retryAfterSeconds=0,this.action="",this.linkTtlSeconds=0,this.statusPollSeconds=0,this.confirmAnywhere=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qd).fromBinary(t,r)}static fromJson(t,r){return(new Qd).fromJson(t,r)}static fromJsonString(t,r){return(new Qd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qd,t,r)}static $(){return["StartStepUpResponse|1 status #0|2 masked_email 9|3 action_description 9|4 retry_after_seconds 5|6 action 9|7 link_ttl_seconds 5|8 status_poll_seconds 5|9 confirm_anywhere 8",Vd]}}var Vd=(0,a.QT)(n.proto3,C,"StartStepUpResponse.Status",[[0,"UNSPECIFIED"],[1,"SENT"],[2,"COOLDOWN"],[3,"RATE_LIMITED"],[4,"EXPIRED"],[5,"NO_EMAIL"]],1);class Xd extends T{constructor(t){super(),this.challengeId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xd).fromBinary(t,r)}static fromJson(t,r){return(new Xd).fromJson(t,r)}static fromJsonString(t,r){return(new Xd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xd,t,r)}static $(){return["GetStepUpStatusRequest|1 challenge_id 9"]}}class Yd extends T{constructor(t){super(),this.status=Zd.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yd).fromBinary(t,r)}static fromJson(t,r){return(new Yd).fromJson(t,r)}static fromJsonString(t,r){return(new Yd).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yd,t,r)}static $(){return["GetStepUpStatusResponse|1 status #0",Zd]}}var Zd=(0,a.QT)(n.proto3,C,"GetStepUpStatusResponse.Status",[[0,"UNSPECIFIED"],[1,"PENDING"],[2,"CONFIRMED"],[3,"EXPIRED"],[4,"COMPLETED"]],1);class tp extends T{constructor(t){super(),this.token="",this.browserBinding="",this.surfaceOrigin="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tp).fromBinary(t,r)}static fromJson(t,r){return(new tp).fromJson(t,r)}static fromJsonString(t,r){return(new tp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tp,t,r)}static $(){return["DescribeStepUpLinkRequest|1 token 9|2 browser_binding 9|3 surface_origin 9"]}}class rp extends T{constructor(t){super(),this.refusal=Rt.UNSPECIFIED,this.action="",this.actionDescription="",this.requestContext="",this.requestedAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rp).fromBinary(t,r)}static fromJson(t,r){return(new rp).fromJson(t,r)}static fromJsonString(t,r){return(new rp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rp,t,r)}static $(){return["DescribeStepUpLinkResponse|1 refusal #0|2 action 9|3 action_description 9|4 request_context 9|5 requested_at_ms 3",Rt]}}class ep extends T{constructor(t){super(),this.token="",this.browserBinding="",this.surfaceOrigin="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ep).fromBinary(t,r)}static fromJson(t,r){return(new ep).fromJson(t,r)}static fromJsonString(t,r){return(new ep).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ep,t,r)}static $(){return["ConfirmStepUpLinkRequest|1 token 9|2 browser_binding 9|3 surface_origin 9"]}}class np extends T{constructor(t){super(),this.refusal=Rt.UNSPECIFIED,this.action="",this.actionDescription="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new np).fromBinary(t,r)}static fromJson(t,r){return(new np).fromJson(t,r)}static fromJsonString(t,r){return(new np).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(np,t,r)}static $(){return["ConfirmStepUpLinkResponse|1 refusal #0|2 action 9|3 action_description 9",Rt]}}class sp extends T{constructor(t){super(),this.name="",this.scopes=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sp).fromBinary(t,r)}static fromJson(t,r){return(new sp).fromJson(t,r)}static fromJsonString(t,r){return(new sp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sp,t,r)}static $(){return["CreateUserApiKeyRequest|1 name 9|2 scopes 9*|3 expires_at 3?|4 castle_request_token 9?"]}}class ip extends T{constructor(t){super(),this.apiKey="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ip).fromBinary(t,r)}static fromJson(t,r){return(new ip).fromJson(t,r)}static fromJsonString(t,r){return(new ip).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ip,t,r)}static $(){return["CreateUserApiKeyResponse|1 api_key 9"]}}class op extends T{constructor(t){super(),this.id=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new op).fromBinary(t,r)}static fromJson(t,r){return(new op).fromJson(t,r)}static fromJsonString(t,r){return(new op).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(op,t,r)}static $(){return["RevokeUserApiKeyRequest|1 id 5"]}}class ap extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ap).fromBinary(t,r)}static fromJson(t,r){return(new ap).fromJson(t,r)}static fromJsonString(t,r){return(new ap).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ap,t,r)}static $(){return["RevokeUserApiKeyResponse"]}}class up extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new up).fromBinary(t,r)}static fromJson(t,r){return(new up).fromJson(t,r)}static fromJsonString(t,r){return(new up).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(up,t,r)}static $(){return["ListUserApiKeysRequest"]}}class cp extends T{constructor(t){super(),this.apiKeys=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cp).fromBinary(t,r)}static fromJson(t,r){return(new cp).fromJson(t,r)}static fromJsonString(t,r){return(new cp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cp,t,r)}static $(){return["ListUserApiKeysResponse|1 api_keys #0*",$m]}}class lp extends T{constructor(t){super(),this.userId=0,this.key={case:void 0},this.name="",this.maskedKey="",this.scopes=[],this.createdAt=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lp).fromBinary(t,r)}static fromJson(t,r){return(new lp).fromJson(t,r)}static fromJsonString(t,r){return(new lp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lp,t,r)}static $(){return["MemberPersonalApiKey|1 user_id 5|2 legacy_id 5 key|3 service_token_public_id 9 key|4 name 9|5 masked_key 9|6 scopes 9*|7 created_at 3|8 expires_at 3?|9 last_used_at 3?|10 last_use #0?",yp]}}class mp extends T{constructor(t){super(),this.teamId=0,this.pageToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mp).fromBinary(t,r)}static fromJson(t,r){return(new mp).fromJson(t,r)}static fromJsonString(t,r){return(new mp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mp,t,r)}static $(){return["ListMemberPersonalApiKeysRequest|1 team_id 5|2 user_id 5?|3 page_size 5?|4 page_token 9"]}}class fp extends T{constructor(t){super(),this.keys=[],this.truncated=!1,this.nextPageToken="",this.holders=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fp).fromBinary(t,r)}static fromJson(t,r){return(new fp).fromJson(t,r)}static fromJsonString(t,r){return(new fp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fp,t,r)}static $(){return["ListMemberPersonalApiKeysResponse|1 keys #0*|2 truncated 8|3 next_page_token 9|4 holders #1*",lp,dp]}}class dp extends T{constructor(t){super(),this.userId=0,this.name="",this.email="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dp).fromBinary(t,r)}static fromJson(t,r){return(new dp).fromJson(t,r)}static fromJsonString(t,r){return(new dp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dp,t,r)}static $(){return["MemberPersonalApiKeyHolder|1 user_id 5|2 name 9|3 email 9"]}}class pp extends T{constructor(t){super(),this.teamId=0,this.userId=0,this.key={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pp).fromBinary(t,r)}static fromJson(t,r){return(new pp).fromJson(t,r)}static fromJsonString(t,r){return(new pp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pp,t,r)}static $(){return["RevokeMemberPersonalApiKeysRequest|1 team_id 5|2 user_id 5|3 legacy_id 5 key|4 service_token_public_id 9 key"]}}class hp extends T{constructor(t){super(),this.revokedCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hp).fromBinary(t,r)}static fromJson(t,r){return(new hp).fromJson(t,r)}static fromJsonString(t,r){return(new hp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hp,t,r)}static $(){return["RevokeMemberPersonalApiKeysResponse|1 revoked_count 5"]}}class gp extends T{constructor(t){super(),this.owner={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gp).fromBinary(t,r)}static fromJson(t,r){return(new gp).fromJson(t,r)}static fromJsonString(t,r){return(new gp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gp,t,r)}static $(){return["ApiKeyInventoryOwner|1 user_id 5 owner|2 team_id 5 owner|3 organization_id 9 owner"]}}class _p extends T{constructor(t){super(),this.kind=vt.UNSPECIFIED,this.id={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _p).fromBinary(t,r)}static fromJson(t,r){return(new _p).fromJson(t,r)}static fromJsonString(t,r){return(new _p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_p,t,r)}static $(){return["ApiKeyInventoryKeyRef|1 kind #0|2 legacy_id 5 id|3 organization_key_id 9 id|4 service_token_public_id 9 id|5 owner #1|6 service_account_id 9?",vt,gp]}}class Jp extends T{constructor(t){super(),this.kind=wp.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jp).fromBinary(t,r)}static fromJson(t,r){return(new Jp).fromJson(t,r)}static fromJsonString(t,r){return(new Jp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jp,t,r)}static $(){return["ApiKeyCreator|1 kind #0|2 user_id 5?|3 name 9?|4 email 9?",wp]}}var wp=(0,a.QT)(n.proto3,C,"ApiKeyCreator.Kind",[[0,"UNSPECIFIED"],[1,"USER"],[2,"SYSTEM"],[3,"NOT_RECORDED"]],1);class yp extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yp).fromBinary(t,r)}static fromJson(t,r){return(new yp).fromJson(t,r)}static fromJsonString(t,r){return(new yp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yp,t,r)}static $(){return["ApiKeyLastUse|1 at 3?|2 recorded_since 3?"]}}class Sp extends T{constructor(t){super(),this.name="",this.maskedKey="",this.scopes=[],this.createdAt=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sp).fromBinary(t,r)}static fromJson(t,r){return(new Sp).fromJson(t,r)}static fromJsonString(t,r){return(new Sp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sp,t,r)}static $(){return["ApiKeyInventoryKey|1 ref #0|2 name 9|3 masked_key 9|4 scopes 9*|5 created_at 3|6 expires_at 3?|7 disabled_at 3?|8 created_by #1|9 last_use #2|10 service_account_name 9?",_p,Jp,yp]}}class qp extends T{constructor(t){super(),this.serviceAccountId="",this.serviceType="",this.name="",this.createdAt=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qp).fromBinary(t,r)}static fromJson(t,r){return(new qp).fromJson(t,r)}static fromJsonString(t,r){return(new qp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qp,t,r)}static $(){return["ApiKeyInventoryServiceAccount|1 service_account_id 9|2 owner #0|3 service_type 9|4 name 9|5 created_at 3|6 archived_at 3?|7 suspended_at 3?|8 created_by #1|9 last_use #2",gp,Jp,yp]}}class Bp extends T{constructor(t){super(),this.row={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bp).fromBinary(t,r)}static fromJson(t,r){return(new Bp).fromJson(t,r)}static fromJsonString(t,r){return(new Bp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bp,t,r)}static $(){return["ApiKeyInventoryRow|1 key #0 row|2 service_account #1 row",Sp,qp]}}class Ip extends T{constructor(t){super(),this.teamId=0,this.serviceAccountId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ip).fromBinary(t,r)}static fromJson(t,r){return(new Ip).fromJson(t,r)}static fromJsonString(t,r){return(new Ip).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ip,t,r)}static $(){return["ApiKeyInventoryServiceAccountList|1 team_id 5|2 service_account_id 9"]}}class Pp extends T{constructor(t){super(),this.list={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pp).fromBinary(t,r)}static fromJson(t,r){return(new Pp).fromJson(t,r)}static fromJsonString(t,r){return(new Pp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pp,t,r)}static $(){return["ApiKeyInventoryList|1 personal 8 list|2 team_id 5 list|3 organization_id 9 list|4 members_team_id 5 list|5 service_account #0 list|6 all_owners 8 list",Ip]}}class bp extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bp).fromBinary(t,r)}static fromJson(t,r){return(new bp).fromJson(t,r)}static fromJsonString(t,r){return(new bp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bp,t,r)}static $(){return["ApiKeyInventoryPageRequest|1 page_size 5?|2 cursor 9?"]}}class Rp extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rp).fromBinary(t,r)}static fromJson(t,r){return(new Rp).fromJson(t,r)}static fromJsonString(t,r){return(new Rp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rp,t,r)}static $(){return["ApiKeyInventoryPageInfo|1 next_cursor 9?"]}}class vp extends T{constructor(t){super(),this.query="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vp).fromBinary(t,r)}static fromJson(t,r){return(new vp).fromJson(t,r)}static fromJsonString(t,r){return(new vp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vp,t,r)}static $(){return["SearchApiKeysRequest|1 list #0|2 query 9",Pp]}}class xp extends T{constructor(t){super(),this.rows=[],this.truncated=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xp).fromBinary(t,r)}static fromJson(t,r){return(new xp).fromJson(t,r)}static fromJsonString(t,r){return(new xp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xp,t,r)}static $(){return["SearchApiKeysResponse|1 rows #0*|2 truncated 8",Bp]}}class kp extends T{constructor(t){super(),this.teamId=0,this.pageToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kp).fromBinary(t,r)}static fromJson(t,r){return(new kp).fromJson(t,r)}static fromJsonString(t,r){return(new kp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kp,t,r)}static $(){return["ListTeamCredentialsFromFormerMembersRequest|1 team_id 5|2 page_size 5?|3 page_token 9"]}}class Ep extends T{constructor(t){super(),this.rows=[],this.creators=[],this.nextPageToken="",this.creatorsIncomplete=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ep).fromBinary(t,r)}static fromJson(t,r){return(new Ep).fromJson(t,r)}static fromJsonString(t,r){return(new Ep).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ep,t,r)}static $(){return["ListTeamCredentialsFromFormerMembersResponse|1 rows #0*|2 creators #1*|4 next_page_token 9|5 creators_incomplete 8",Bp,Cp]}}class Cp extends T{constructor(t){super(),this.userId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cp).fromBinary(t,r)}static fromJson(t,r){return(new Cp).fromJson(t,r)}static fromJsonString(t,r){return(new Cp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cp,t,r)}static $(){return["FormerTeamMember|1 user_id 5|2 removed_at 3?"]}}class Tp extends T{constructor(t){super(),this.query="",this.kinds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tp).fromBinary(t,r)}static fromJson(t,r){return(new Tp).fromJson(t,r)}static fromJsonString(t,r){return(new Tp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tp,t,r)}static $(){return["StaffSearchApiKeysRequest|1 query 9|2 kinds #0*|3 owner #1",vt,gp]}}class Up extends T{constructor(t){super(),this.rows=[],this.truncated=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Up).fromBinary(t,r)}static fromJson(t,r){return(new Up).fromJson(t,r)}static fromJsonString(t,r){return(new Up).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Up,t,r)}static $(){return["StaffSearchApiKeysResponse|1 rows #0*|2 truncated 8",Bp]}}class Ap extends T{constructor(t){super(),this.reason=xt.UNSPECIFIED,this.ticketRef="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ap).fromBinary(t,r)}static fromJson(t,r){return(new Ap).fromJson(t,r)}static fromJsonString(t,r){return(new Ap).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ap,t,r)}static $(){return["StaffWriteContext|1 reason #0|2 ticket_ref 9",xt]}}class $p extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $p).fromBinary(t,r)}static fromJson(t,r){return(new $p).fromJson(t,r)}static fromJsonString(t,r){return(new $p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($p,t,r)}static $(){return["StaffRevokeApiKeyRequest|1 context #0|2 key #1",Ap,_p]}}class Mp extends T{constructor(t){super(),this.changed=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mp).fromBinary(t,r)}static fromJson(t,r){return(new Mp).fromJson(t,r)}static fromJsonString(t,r){return(new Mp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mp,t,r)}static $(){return["StaffRevokeApiKeyResponse|1 changed 8"]}}class Op extends T{constructor(t){super(),this.teamId=0,this.serviceAccountId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Op).fromBinary(t,r)}static fromJson(t,r){return(new Op).fromJson(t,r)}static fromJsonString(t,r){return(new Op).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Op,t,r)}static $(){return["StaffServiceAccountActionRequest|1 context #0|2 team_id 5|3 service_account_id 9",Ap]}}class Dp extends T{constructor(t){super(),this.changed=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dp).fromBinary(t,r)}static fromJson(t,r){return(new Dp).fromJson(t,r)}static fromJsonString(t,r){return(new Dp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dp,t,r)}static $(){return["StaffServiceAccountActionResponse|1 changed 8"]}}class Np extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Np).fromBinary(t,r)}static fromJson(t,r){return(new Np).fromJson(t,r)}static fromJsonString(t,r){return(new Np).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Np,t,r)}static $(){return["StaffListOwnerApiKeysRequest|1 owner #0|2 page #1",gp,bp]}}class Gp extends T{constructor(t){super(),this.teamId=0,this.serviceAccountId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gp).fromBinary(t,r)}static fromJson(t,r){return(new Gp).fromJson(t,r)}static fromJsonString(t,r){return(new Gp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gp,t,r)}static $(){return["StaffListServiceAccountApiKeysRequest|1 team_id 5|2 service_account_id 9|3 page #0",bp]}}class Lp extends T{constructor(t){super(),this.rows=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lp).fromBinary(t,r)}static fromJson(t,r){return(new Lp).fromJson(t,r)}static fromJsonString(t,r){return(new Lp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Lp,t,r)}static $(){return["StaffListApiKeysResponse|1 rows #0*|2 page_info #1",Bp,Rp]}}class Fp extends T{constructor(t){super(),this.sessionId="",this.type=m.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fp).fromBinary(t,r)}static fromJson(t,r){return(new Fp).fromJson(t,r)}static fromJsonString(t,r){return(new Fp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fp,t,r)}static $(){return["AdminMemberSessionTarget|1 session_id 9|2 type #0",m]}}class Kp extends T{constructor(t){super(),this.teamId=0,this.userId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kp).fromBinary(t,r)}static fromJson(t,r){return(new Kp).fromJson(t,r)}static fromJsonString(t,r){return(new Kp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Kp,t,r)}static $(){return["ListTeamMemberSessionsRequest|1 team_id 5|2 user_id 5"]}}class zp extends T{constructor(t){super(),this.teamId=0,this.userId=0,this.target={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zp).fromBinary(t,r)}static fromJson(t,r){return(new zp).fromJson(t,r)}static fromJsonString(t,r){return(new zp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zp,t,r)}static $(){return["RevokeTeamMemberSessionRequest|1 team_id 5|2 user_id 5|3 session #0 target|4 all_sessions 8 target",Fp]}}class jp extends T{constructor(t){super(),this.organizationId="",this.userId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jp).fromBinary(t,r)}static fromJson(t,r){return(new jp).fromJson(t,r)}static fromJsonString(t,r){return(new jp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jp,t,r)}static $(){return["ListOrganizationMemberSessionsRequest|1 organization_id 9|2 user_id 5"]}}class Hp extends T{constructor(t){super(),this.organizationId="",this.userId=0,this.target={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hp).fromBinary(t,r)}static fromJson(t,r){return(new Hp).fromJson(t,r)}static fromJsonString(t,r){return(new Hp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hp,t,r)}static $(){return["RevokeOrganizationMemberSessionRequest|1 organization_id 9|2 user_id 5|3 session #0 target|4 all_sessions 8 target",Fp]}}class Wp extends T{constructor(t){super(),this.sessions=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wp).fromBinary(t,r)}static fromJson(t,r){return(new Wp).fromJson(t,r)}static fromJsonString(t,r){return(new Wp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wp,t,r)}static $(){return["ListMemberSessionsResponse|1 sessions #0*",l]}}class Qp extends T{constructor(t){super(),this.revokedCount=0,this.revokedCurrentSession=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qp).fromBinary(t,r)}static fromJson(t,r){return(new Qp).fromJson(t,r)}static fromJsonString(t,r){return(new Qp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qp,t,r)}static $(){return["RevokeMemberSessionResponse|1 revoked_count 5|2 revoked_current_session 8"]}}class Vp extends T{constructor(t){super(),this.userId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vp).fromBinary(t,r)}static fromJson(t,r){return(new Vp).fromJson(t,r)}static fromJsonString(t,r){return(new Vp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vp,t,r)}static $(){return["ServiceTokenCreator|1 user_id 9|2 name 9?"]}}class Xp extends T{constructor(t){super(),this.publicId="",this.ownerType=kt.UNSPECIFIED,this.ownerId="",this.name="",this.maskedKey="",this.permissionIds=[],this.createdAt=n.protoInt64.zero,this.updatedAt=n.protoInt64.zero,this.serviceAccountDisabled=!1,this.writeBlockedReason="",this.repoScope=[],this.repoScopeEnabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xp).fromBinary(t,r)}static fromJson(t,r){return(new Xp).fromJson(t,r)}static fromJsonString(t,r){return(new Xp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xp,t,r)}static $(){return["ServiceToken|1 public_id 9|2 owner_type #0|3 owner_id 9|4 name 9|5 masked_key 9|6 permission_ids 9*|7 created_at 3|8 updated_at 3|9 expires_at 3?|10 revoked_at 3?|11 created_by #1|12 service_account_id 9?|13 service_account_name 9?|14 service_account_disabled 8|15 creator #2|16 write_blocked_reason 9|17 repo_scope 9*|18 repo_scope_enabled 8|19 last_use #3",kt,Vp,Jp,yp]}}class Yp extends T{constructor(t){super(),this.owner={case:void 0},this.name="",this.permissionIds=[],this.apps=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yp).fromBinary(t,r)}static fromJson(t,r){return(new Yp).fromJson(t,r)}static fromJsonString(t,r){return(new Yp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yp,t,r)}static $(){return["CreateServiceTokenRequest|1 current_user 8 owner|2 team_id 5 owner|3 organization_id 9 owner|4 name 9|5 permission_ids 9*|6 expires_at 3?|7 castle_request_token 9?|8 apps #0*",Zp]}}class Zp extends T{constructor(t){super(),this.slug="",this.apex="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zp).fromBinary(t,r)}static fromJson(t,r){return(new Zp).fromJson(t,r)}static fromJsonString(t,r){return(new Zp).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zp,t,r)}static $(){return["DashboardAppRef|1 slug 9|2 apex 9"]}}class th extends T{constructor(t){super(),this.secret="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new th).fromBinary(t,r)}static fromJson(t,r){return(new th).fromJson(t,r)}static fromJsonString(t,r){return(new th).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(th,t,r)}static $(){return["CreateServiceTokenResponse|1 secret 9|2 service_token #0",Xp]}}class rh extends T{constructor(t){super(),this.owner={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rh).fromBinary(t,r)}static fromJson(t,r){return(new rh).fromJson(t,r)}static fromJsonString(t,r){return(new rh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rh,t,r)}static $(){return["ListServiceTokensRequest|1 current_user 8 owner|2 team_id 5 owner|3 organization_id 9 owner|4 app #0",Zp]}}class eh extends T{constructor(t){super(),this.serviceTokens=[],this.fineGrainedKeysEnabled=!1,this.teamCatalogPermissionsEnabled=!1,this.appKeysEnabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eh).fromBinary(t,r)}static fromJson(t,r){return(new eh).fromJson(t,r)}static fromJsonString(t,r){return(new eh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eh,t,r)}static $(){return["ListServiceTokensResponse|1 service_tokens #0*|2 fine_grained_keys_enabled 8|3 team_catalog_permissions_enabled 8|4 app_keys_enabled 8",Xp]}}class nh extends T{constructor(t){super(),this.teamId=0,this.owner=Et.UNSPECIFIED,this.pageSize=0,this.pageToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nh).fromBinary(t,r)}static fromJson(t,r){return(new nh).fromJson(t,r)}static fromJsonString(t,r){return(new nh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nh,t,r)}static $(){return["ListCursorApiKeysRequest|1 team_id 5|2 owner #0|3 page_size 5|4 page_token 9",Et]}}class sh extends T{constructor(t){super(),this.key={case:void 0},this.owner=Et.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sh).fromBinary(t,r)}static fromJson(t,r){return(new sh).fromJson(t,r)}static fromJsonString(t,r){return(new sh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sh,t,r)}static $(){return["CursorApiKey|1 api_key #0 key|2 service_token #1 key|3 owner #2",$m,Xp,Et]}}class ih extends T{constructor(t){super(),this.keys=[],this.nextPageToken="",this.listsTeamKeys=!1,this.personalFineGrainedKeysEnabled=!1,this.teamFineGrainedKeysEnabled=!1,this.teamCatalogPermissionsEnabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ih).fromBinary(t,r)}static fromJson(t,r){return(new ih).fromJson(t,r)}static fromJsonString(t,r){return(new ih).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ih,t,r)}static $(){return["ListCursorApiKeysResponse|1 keys #0*|2 next_page_token 9|3 lists_team_keys 8|4 personal_fine_grained_keys_enabled 8|5 team_fine_grained_keys_enabled 8|6 team_catalog_permissions_enabled 8",sh]}}class oh extends T{constructor(t){super(),this.owner={case:void 0},this.publicId="",this.permissionIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oh).fromBinary(t,r)}static fromJson(t,r){return(new oh).fromJson(t,r)}static fromJsonString(t,r){return(new oh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oh,t,r)}static $(){return["UpdateServiceTokenPermissionsRequest|1 current_user 8 owner|2 team_id 5 owner|3 organization_id 9 owner|4 public_id 9|5 permission_ids 9*|6 castle_request_token 9?"]}}class ah extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ah).fromBinary(t,r)}static fromJson(t,r){return(new ah).fromJson(t,r)}static fromJsonString(t,r){return(new ah).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ah,t,r)}static $(){return["UpdateServiceTokenPermissionsResponse|1 service_token #0",Xp]}}class uh extends T{constructor(t){super(),this.owner={case:void 0},this.publicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uh).fromBinary(t,r)}static fromJson(t,r){return(new uh).fromJson(t,r)}static fromJsonString(t,r){return(new uh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uh,t,r)}static $(){return["RevokeServiceTokenRequest|1 current_user 8 owner|2 team_id 5 owner|3 organization_id 9 owner|4 public_id 9"]}}class ch extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ch).fromBinary(t,r)}static fromJson(t,r){return(new ch).fromJson(t,r)}static fromJsonString(t,r){return(new ch).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ch,t,r)}static $(){return["RevokeServiceTokenResponse"]}}class lh extends T{constructor(t){super(),this.owner={case:void 0},this.publicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lh).fromBinary(t,r)}static fromJson(t,r){return(new lh).fromJson(t,r)}static fromJsonString(t,r){return(new lh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lh,t,r)}static $(){return["RotateServiceTokenRequest|1 current_user 8 owner|2 team_id 5 owner|3 organization_id 9 owner|4 public_id 9|5 castle_request_token 9?"]}}class mh extends T{constructor(t){super(),this.secret="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mh).fromBinary(t,r)}static fromJson(t,r){return(new mh).fromJson(t,r)}static fromJsonString(t,r){return(new mh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mh,t,r)}static $(){return["RotateServiceTokenResponse|1 secret 9|2 service_token #0",Xp]}}class fh extends T{constructor(t){super(),this.kid="",this.alg="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fh).fromBinary(t,r)}static fromJson(t,r){return(new fh).fromJson(t,r)}static fromJsonString(t,r){return(new fh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fh,t,r)}static $(){return["TrustedIssuerPublicKey|1 kid 9|2 alg 9|3 created_at 3?"]}}class dh extends T{constructor(t){super(),this.publicId="",this.name="",this.clientKey="",this.status=Ct.UNSPECIFIED,this.scopes=[],this.redirectUris=[],this.activeKeyCount=0,this.keys=[],this.createdAt=n.protoInt64.zero,this.updatedAt=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dh).fromBinary(t,r)}static fromJson(t,r){return(new dh).fromJson(t,r)}static fromJsonString(t,r){return(new dh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dh,t,r)}static $(){return["TrustedIssuer|1 public_id 9|2 name 9|3 client_key 9|4 status #0|5 scopes 9*|6 redirect_uris 9*|7 active_key_count 5|8 keys #1*|9 created_at 3|10 updated_at 3",Ct,fh]}}class ph extends T{constructor(t){super(),this.owner={case:void 0},this.pageToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ph).fromBinary(t,r)}static fromJson(t,r){return(new ph).fromJson(t,r)}static fromJsonString(t,r){return(new ph).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ph,t,r)}static $(){return["ListTrustedIssuersRequest|1 team_id 5 owner|2 organization_id 9 owner|3 page_size 5?|4 page_token 9"]}}class hh extends T{constructor(t){super(),this.issuers=[],this.nextPageToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hh).fromBinary(t,r)}static fromJson(t,r){return(new hh).fromJson(t,r)}static fromJsonString(t,r){return(new hh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hh,t,r)}static $(){return["ListTrustedIssuersResponse|1 issuers #0*|2 next_page_token 9",dh]}}class gh extends T{constructor(t){super(),this.owner={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gh).fromBinary(t,r)}static fromJson(t,r){return(new gh).fromJson(t,r)}static fromJsonString(t,r){return(new gh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gh,t,r)}static $(){return["GetAuthApplicationsOwnerGateRequest|1 team_id 5 owner|2 organization_id 9 owner"]}}class _h extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _h).fromBinary(t,r)}static fromJson(t,r){return(new _h).fromJson(t,r)}static fromJsonString(t,r){return(new _h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_h,t,r)}static $(){return["GetAuthApplicationsOwnerGateResponse|1 enabled 8"]}}class Jh extends T{constructor(t){super(),this.owner={case:void 0},this.name="",this.scopes=[],this.redirectUris=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jh).fromBinary(t,r)}static fromJson(t,r){return(new Jh).fromJson(t,r)}static fromJsonString(t,r){return(new Jh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jh,t,r)}static $(){return["CreateTrustedIssuerRequest|1 team_id 5 owner|2 organization_id 9 owner|3 name 9|4 scopes 9*|5 redirect_uris 9*|6 castle_request_token 9?"]}}class wh extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wh).fromBinary(t,r)}static fromJson(t,r){return(new wh).fromJson(t,r)}static fromJsonString(t,r){return(new wh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wh,t,r)}static $(){return["CreateTrustedIssuerResponse|1 issuer #0",dh]}}class yh extends T{constructor(t){super(),this.owner={case:void 0},this.publicId="",this.scopes=[],this.redirectUris=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yh).fromBinary(t,r)}static fromJson(t,r){return(new yh).fromJson(t,r)}static fromJsonString(t,r){return(new yh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yh,t,r)}static $(){return["UpdateTrustedIssuerRequest|1 team_id 5 owner|2 organization_id 9 owner|3 public_id 9|4 scopes 9*|5 redirect_uris 9*|6 castle_request_token 9?|7 name 9?"]}}class Sh extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sh).fromBinary(t,r)}static fromJson(t,r){return(new Sh).fromJson(t,r)}static fromJsonString(t,r){return(new Sh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sh,t,r)}static $(){return["UpdateTrustedIssuerResponse|1 issuer #0",dh]}}class qh extends T{constructor(t){super(),this.owner={case:void 0},this.publicId="",this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qh).fromBinary(t,r)}static fromJson(t,r){return(new qh).fromJson(t,r)}static fromJsonString(t,r){return(new qh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qh,t,r)}static $(){return["SetTrustedIssuerEnabledRequest|1 team_id 5 owner|2 organization_id 9 owner|3 public_id 9|4 enabled 8|5 castle_request_token 9?"]}}class Bh extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bh).fromBinary(t,r)}static fromJson(t,r){return(new Bh).fromJson(t,r)}static fromJsonString(t,r){return(new Bh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bh,t,r)}static $(){return["SetTrustedIssuerEnabledResponse|1 issuer #0",dh]}}class Ih extends T{constructor(t){super(),this.owner={case:void 0},this.publicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ih).fromBinary(t,r)}static fromJson(t,r){return(new Ih).fromJson(t,r)}static fromJsonString(t,r){return(new Ih).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ih,t,r)}static $(){return["RevokeTrustedIssuerRequest|1 team_id 5 owner|2 organization_id 9 owner|3 public_id 9"]}}class Ph extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ph).fromBinary(t,r)}static fromJson(t,r){return(new Ph).fromJson(t,r)}static fromJsonString(t,r){return(new Ph).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ph,t,r)}static $(){return["RevokeTrustedIssuerResponse"]}}class bh extends T{constructor(t){super(),this.owner={case:void 0},this.publicId="",this.publicJwkJson="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bh).fromBinary(t,r)}static fromJson(t,r){return(new bh).fromJson(t,r)}static fromJsonString(t,r){return(new bh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bh,t,r)}static $(){return["RegisterTrustedIssuerPublicKeyRequest|1 team_id 5 owner|2 organization_id 9 owner|3 public_id 9|4 public_jwk_json 9|5 castle_request_token 9?"]}}class Rh extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rh).fromBinary(t,r)}static fromJson(t,r){return(new Rh).fromJson(t,r)}static fromJsonString(t,r){return(new Rh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rh,t,r)}static $(){return["RegisterTrustedIssuerPublicKeyResponse|1 issuer #0",dh]}}class vh extends T{constructor(t){super(),this.owner={case:void 0},this.publicId="",this.kid="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vh).fromBinary(t,r)}static fromJson(t,r){return(new vh).fromJson(t,r)}static fromJsonString(t,r){return(new vh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vh,t,r)}static $(){return["RevokeTrustedIssuerPublicKeyRequest|1 team_id 5 owner|2 organization_id 9 owner|3 public_id 9|4 kid 9"]}}class xh extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xh).fromBinary(t,r)}static fromJson(t,r){return(new xh).fromJson(t,r)}static fromJsonString(t,r){return(new xh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xh,t,r)}static $(){return["RevokeTrustedIssuerPublicKeyResponse|1 issuer #0",dh]}}class kh extends T{constructor(t){super(),this.owner={case:void 0},this.publicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kh).fromBinary(t,r)}static fromJson(t,r){return(new kh).fromJson(t,r)}static fromJsonString(t,r){return(new kh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kh,t,r)}static $(){return["RevokeTrustedIssuerGrantsRequest|1 team_id 5 owner|2 organization_id 9 owner|3 public_id 9"]}}class Eh extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Eh).fromBinary(t,r)}static fromJson(t,r){return(new Eh).fromJson(t,r)}static fromJsonString(t,r){return(new Eh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Eh,t,r)}static $(){return["RevokeTrustedIssuerGrantsResponse"]}}class Ch extends T{constructor(t){super(),this.publicId="",this.teamId=0,this.name="",this.clientId="",this.redirectUris=[],this.scopes=[],this.enabled=!1,this.createdAt=n.protoInt64.zero,this.updatedAt=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ch).fromBinary(t,r)}static fromJson(t,r){return(new Ch).fromJson(t,r)}static fromJsonString(t,r){return(new Ch).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ch,t,r)}static $(){return["OAuthApplication|1 public_id 9|2 team_id 5|3 name 9|4 client_id 9|5 logo_url 9?|6 redirect_uris 9*|7 scopes 9*|8 enabled 8|9 ip_allowlist #0?|10 created_at 3|11 updated_at 3|12 previous_secret_expires_at 3?",ru]}}class Th extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Th).fromBinary(t,r)}static fromJson(t,r){return(new Th).fromJson(t,r)}static fromJsonString(t,r){return(new Th).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Th,t,r)}static $(){return["ListOAuthApplicationsRequest|1 team_id 5"]}}class Uh extends T{constructor(t){super(),this.applications=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Uh).fromBinary(t,r)}static fromJson(t,r){return(new Uh).fromJson(t,r)}static fromJsonString(t,r){return(new Uh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Uh,t,r)}static $(){return["ListOAuthApplicationsResponse|1 applications #0*",Ch]}}class Ah extends T{constructor(t){super(),this.teamId=0,this.name="",this.redirectUris=[],this.scopes=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ah).fromBinary(t,r)}static fromJson(t,r){return(new Ah).fromJson(t,r)}static fromJsonString(t,r){return(new Ah).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ah,t,r)}static $(){return["CreateOAuthApplicationRequest|1 team_id 5|2 name 9|3 logo_url 9?|4 redirect_uris 9*|5 scopes 9*|6 ip_allowlist #0?|7 castle_request_token 9?",ru]}}class $h extends T{constructor(t){super(),this.clientSecret="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $h).fromBinary(t,r)}static fromJson(t,r){return(new $h).fromJson(t,r)}static fromJsonString(t,r){return(new $h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($h,t,r)}static $(){return["CreateOAuthApplicationResponse|1 application #0|2 client_secret 9",Ch]}}class Mh extends T{constructor(t){super(),this.teamId=0,this.publicId="",this.name="",this.redirectUris=[],this.scopes=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mh).fromBinary(t,r)}static fromJson(t,r){return(new Mh).fromJson(t,r)}static fromJsonString(t,r){return(new Mh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mh,t,r)}static $(){return["UpdateOAuthApplicationRequest|1 team_id 5|2 public_id 9|3 name 9|4 logo_url 9?|5 redirect_uris 9*|6 scopes 9*|7 ip_allowlist #0?|8 castle_request_token 9?",ru]}}class Oh extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Oh).fromBinary(t,r)}static fromJson(t,r){return(new Oh).fromJson(t,r)}static fromJsonString(t,r){return(new Oh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Oh,t,r)}static $(){return["UpdateOAuthApplicationResponse|1 application #0",Ch]}}class Dh extends T{constructor(t){super(),this.teamId=0,this.publicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dh).fromBinary(t,r)}static fromJson(t,r){return(new Dh).fromJson(t,r)}static fromJsonString(t,r){return(new Dh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dh,t,r)}static $(){return["RotateOAuthApplicationSecretRequest|1 team_id 5|2 public_id 9|3 overlap_seconds 3?|4 castle_request_token 9?"]}}class Nh extends T{constructor(t){super(),this.clientSecret="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nh).fromBinary(t,r)}static fromJson(t,r){return(new Nh).fromJson(t,r)}static fromJsonString(t,r){return(new Nh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nh,t,r)}static $(){return["RotateOAuthApplicationSecretResponse|1 application #0|2 client_secret 9",Ch]}}class Gh extends T{constructor(t){super(),this.teamId=0,this.publicId="",this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gh).fromBinary(t,r)}static fromJson(t,r){return(new Gh).fromJson(t,r)}static fromJsonString(t,r){return(new Gh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gh,t,r)}static $(){return["SetOAuthApplicationEnabledRequest|1 team_id 5|2 public_id 9|3 enabled 8"]}}class Lh extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lh).fromBinary(t,r)}static fromJson(t,r){return(new Lh).fromJson(t,r)}static fromJsonString(t,r){return(new Lh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Lh,t,r)}static $(){return["SetOAuthApplicationEnabledResponse|1 application #0",Ch]}}class Fh extends T{constructor(t){super(),this.teamId=0,this.publicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fh).fromBinary(t,r)}static fromJson(t,r){return(new Fh).fromJson(t,r)}static fromJsonString(t,r){return(new Fh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fh,t,r)}static $(){return["DeleteOAuthApplicationRequest|1 team_id 5|2 public_id 9"]}}class Kh extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kh).fromBinary(t,r)}static fromJson(t,r){return(new Kh).fromJson(t,r)}static fromJsonString(t,r){return(new Kh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Kh,t,r)}static $(){return["DeleteOAuthApplicationResponse"]}}class zh extends T{constructor(t){super(),this.teamId=0,this.contentType="",this.bytes=new Uint8Array(0),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zh).fromBinary(t,r)}static fromJson(t,r){return(new zh).fromJson(t,r)}static fromJsonString(t,r){return(new zh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zh,t,r)}static $(){return["UploadOAuthApplicationLogoRequest|1 team_id 5|2 content_type 9|3 bytes 12"]}}class jh extends T{constructor(t){super(),this.logoUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jh).fromBinary(t,r)}static fromJson(t,r){return(new jh).fromJson(t,r)}static fromJsonString(t,r){return(new jh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jh,t,r)}static $(){return["UploadOAuthApplicationLogoResponse|1 logo_url 9"]}}class Hh extends T{constructor(t){super(),this.id="",this.label="",this.description="",this.resourceType=Tt.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hh).fromBinary(t,r)}static fromJson(t,r){return(new Hh).fromJson(t,r)}static fromJsonString(t,r){return(new Hh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hh,t,r)}static $(){return["OAuthAuthorizationScope|1 id 9|2 label 9|3 description 9|4 resource_type #0",Tt]}}class Wh extends T{constructor(t){super(),this.type=Tt.UNSPECIFIED,this.id=n.protoInt64.zero,this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wh).fromBinary(t,r)}static fromJson(t,r){return(new Wh).fromJson(t,r)}static fromJsonString(t,r){return(new Wh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wh,t,r)}static $(){return["OAuthGrantResource|1 type #0|2 id 3|3 name 9|4 disabled_reason 9?",Tt]}}class Qh extends T{constructor(t){super(),this.clientId="",this.redirectUri="",this.scopes=[],this.state="",this.codeChallenge="",this.codeChallengeMethod="",this.responseType="",this.validateOnly=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qh).fromBinary(t,r)}static fromJson(t,r){return(new Qh).fromJson(t,r)}static fromJsonString(t,r){return(new Qh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qh,t,r)}static $(){return["GetOAuthAuthorizationRequestRequest|1 client_id 9|2 redirect_uri 9|3 scopes 9*|4 state 9|5 code_challenge 9|6 code_challenge_method 9|7 response_type 9|8 validate_only 8"]}}class Vh extends T{constructor(t){super(),this.authorizationRequestId="",this.applicationName="",this.scopes=[],this.teamId=0,this.redirectUri="",this.state="",this.teamName="",this.publisherTeamId=0,this.publisherTeamName="",this.availableResources=[],this.authority=!1,this.grokBotConnect=!1,this.grokBots=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vh).fromBinary(t,r)}static fromJson(t,r){return(new Vh).fromJson(t,r)}static fromJsonString(t,r){return(new Vh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vh,t,r)}static $(){return["GetOAuthAuthorizationRequestResponse|1 authorization_request_id 9|2 application_name 9|3 logo_url 9?|4 scopes #0*|5 team_id 5|6 redirect_uri 9|7 state 9|8 team_name 9|9 error 9?|10 publisher_team_id 5|11 publisher_team_name 9|12 available_resources #1*|13 authority 8|14 grant_max_expires_at 3?|15 grok_bot_connect 8|16 grok_bots #2*",Hh,Wh,Xh]}}class Xh extends T{constructor(t){super(),this.botId="",this.name="",this.source=Ut.UNSPECIFIED,this.avatarShape="",this.avatarColor="",this.description="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xh).fromBinary(t,r)}static fromJson(t,r){return(new Xh).fromJson(t,r)}static fromJsonString(t,r){return(new Xh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xh,t,r)}static $(){return["OAuthGrokBotCandidate|1 bot_id 9|2 name 9|3 avatar_url 9?|4 source #0|5 team_name 9?|6 avatar_shape 9|7 avatar_color 9|8 description 9",Ut]}}class Yh extends T{constructor(t){super(),this.authorizationRequestId="",this.selectedResources=[],this.grokBotIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yh).fromBinary(t,r)}static fromJson(t,r){return(new Yh).fromJson(t,r)}static fromJsonString(t,r){return(new Yh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yh,t,r)}static $(){return["ApproveOAuthAuthorizationRequestRequest|1 authorization_request_id 9|2 castle_request_token 9?|3 selected_resources #0*|4 grant_expires_at 3?|5 grok_bot_ids 9*",Wh]}}class Zh extends T{constructor(t){super(),this.redirectUri="",this.code="",this.state="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zh).fromBinary(t,r)}static fromJson(t,r){return(new Zh).fromJson(t,r)}static fromJsonString(t,r){return(new Zh).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zh,t,r)}static $(){return["ApproveOAuthAuthorizationRequestResponse|1 redirect_uri 9|2 code 9|3 state 9"]}}class tg extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tg).fromBinary(t,r)}static fromJson(t,r){return(new tg).fromJson(t,r)}static fromJsonString(t,r){return(new tg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tg,t,r)}static $(){return["ListAuthorizedApplicationsRequest"]}}class rg extends T{constructor(t){super(),this.publicId="",this.name="",this.publisherName="",this.scopes=[],this.resources=[],this.grantedAt=n.protoInt64.zero,this.expiresAt=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rg).fromBinary(t,r)}static fromJson(t,r){return(new rg).fromJson(t,r)}static fromJsonString(t,r){return(new rg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rg,t,r)}static $(){return["AuthorizedApplication|1 public_id 9|2 name 9|3 publisher_name 9|4 scopes #0*|5 resources #1*|6 granted_at 3|7 expires_at 3",Hh,Wh]}}class eg extends T{constructor(t){super(),this.applications=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eg).fromBinary(t,r)}static fromJson(t,r){return(new eg).fromJson(t,r)}static fromJsonString(t,r){return(new eg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eg,t,r)}static $(){return["ListAuthorizedApplicationsResponse|1 applications #0*",rg]}}class ng extends T{constructor(t){super(),this.publicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ng).fromBinary(t,r)}static fromJson(t,r){return(new ng).fromJson(t,r)}static fromJsonString(t,r){return(new ng).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ng,t,r)}static $(){return["RevokeAuthorizedApplicationRequest|1 public_id 9"]}}class sg extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sg).fromBinary(t,r)}static fromJson(t,r){return(new sg).fromJson(t,r)}static fromJsonString(t,r){return(new sg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sg,t,r)}static $(){return["RevokeAuthorizedApplicationResponse"]}}class ig extends T{constructor(t){super(),this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ig).fromBinary(t,r)}static fromJson(t,r){return(new ig).fromJson(t,r)}static fromJsonString(t,r){return(new ig).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ig,t,r)}static $(){return["CreateTeamRequest|1 name 9|2 privacy_mode_forced 8?|3 allow_domain_join 8?|4 source 9?"]}}class og extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new og).fromBinary(t,r)}static fromJson(t,r){return(new og).fromJson(t,r)}static fromJsonString(t,r){return(new og).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(og,t,r)}static $(){return["CreateTeamResponse|1 team_id 5"]}}class ag extends T{constructor(t){super(),this.includePendingInviteCode=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ag).fromBinary(t,r)}static fromJson(t,r){return(new ag).fromJson(t,r)}static fromJsonString(t,r){return(new ag).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ag,t,r)}static $(){return["GetJoinableTeamsByDomainRequest|1 include_pending_invite_code 8"]}}class ug extends T{constructor(t){super(),this.id=0,this.name="",this.memberCount=0,this.memberNames=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ug).fromBinary(t,r)}static fromJson(t,r){return(new ug).fromJson(t,r)}static fromJsonString(t,r){return(new ug).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ug,t,r)}static $(){return["JoinableTeam|1 id 5|2 name 9|3 member_count 5|4 member_names 9*"]}}class cg extends T{constructor(t){super(),this.teams=[],this.emailDomain="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cg).fromBinary(t,r)}static fromJson(t,r){return(new cg).fromJson(t,r)}static fromJsonString(t,r){return(new cg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cg,t,r)}static $(){return["GetJoinableTeamsByDomainResponse|1 teams #0*|2 email_domain 9|3 pending_invite_code 9?",ug]}}class lg extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lg).fromBinary(t,r)}static fromJson(t,r){return(new lg).fromJson(t,r)}static fromJsonString(t,r){return(new lg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lg,t,r)}static $(){return["JoinTeamByDomainRequest|1 team_id 5"]}}class mg extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mg).fromBinary(t,r)}static fromJson(t,r){return(new mg).fromJson(t,r)}static fromJsonString(t,r){return(new mg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mg,t,r)}static $(){return["JoinTeamByDomainResponse|1 success 8"]}}class fg extends T{constructor(t){super(),this.teamId=0,this.allowDomainJoin=!1,this.enabledDomains=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fg).fromBinary(t,r)}static fromJson(t,r){return(new fg).fromJson(t,r)}static fromJsonString(t,r){return(new fg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fg,t,r)}static $(){return["UpdateTeamDomainJoinSettingRequest|1 team_id 5|2 allow_domain_join 8|3 enabled_domains 9*|4 enforce_invite_domain_on_accept 8?"]}}class dg extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dg).fromBinary(t,r)}static fromJson(t,r){return(new dg).fromJson(t,r)}static fromJsonString(t,r){return(new dg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dg,t,r)}static $(){return["UpdateTeamDomainJoinSettingResponse"]}}class pg extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pg).fromBinary(t,r)}static fromJson(t,r){return(new pg).fromJson(t,r)}static fromJsonString(t,r){return(new pg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pg,t,r)}static $(){return["GetTeamMemberDomainsRequest|1 team_id 5"]}}class hg extends T{constructor(t){super(),this.domain="",this.memberCount=0,this.isEnabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hg).fromBinary(t,r)}static fromJson(t,r){return(new hg).fromJson(t,r)}static fromJsonString(t,r){return(new hg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hg,t,r)}static $(){return["TeamMemberDomain|1 domain 9|2 member_count 5|3 is_enabled 8"]}}class gg extends T{constructor(t){super(),this.domains=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gg).fromBinary(t,r)}static fromJson(t,r){return(new gg).fromJson(t,r)}static fromJsonString(t,r){return(new gg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gg,t,r)}static $(){return["GetTeamMemberDomainsResponse|1 domains #0*",hg]}}class _g extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _g).fromBinary(t,r)}static fromJson(t,r){return(new _g).fromJson(t,r)}static fromJsonString(t,r){return(new _g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_g,t,r)}static $(){return["GetTeamIdForReactivationRequest"]}}class Jg extends T{constructor(t){super(),this.isEligible=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jg).fromBinary(t,r)}static fromJson(t,r){return(new Jg).fromJson(t,r)}static fromJsonString(t,r){return(new Jg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jg,t,r)}static $(){return["GetTeamIdForReactivationResponse|1 team_id 5?|2 is_eligible 8"]}}class wg extends T{constructor(t){super(),this.teamId=0,this.userId=0,this.role=it.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wg).fromBinary(t,r)}static fromJson(t,r){return(new wg).fromJson(t,r)}static fromJsonString(t,r){return(new wg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wg,t,r)}static $(){return["UpdateRoleRequest|1 team_id 5|2 user_id 5|3 role #0|4 castle_request_token 9?",it]}}class yg extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yg).fromBinary(t,r)}static fromJson(t,r){return(new yg).fromJson(t,r)}static fromJsonString(t,r){return(new yg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yg,t,r)}static $(){return["UpdateRoleResponse"]}}class Sg extends T{constructor(t){super(),this.teamId=0,this.userId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sg).fromBinary(t,r)}static fromJson(t,r){return(new Sg).fromJson(t,r)}static fromJsonString(t,r){return(new Sg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sg,t,r)}static $(){return["RemoveMemberRequest|1 team_id 5|2 user_id 5|3 castle_request_token 9?"]}}class qg extends T{constructor(t){super(),this.hasBillingCycleUsage=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qg).fromBinary(t,r)}static fromJson(t,r){return(new qg).fromJson(t,r)}static fromJsonString(t,r){return(new qg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qg,t,r)}static $(){return["RemoveMemberResponse|1 has_billing_cycle_usage 8"]}}class Bg extends T{constructor(t){super(),this.teamId=0,this.userId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bg).fromBinary(t,r)}static fromJson(t,r){return(new Bg).fromJson(t,r)}static fromJsonString(t,r){return(new Bg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bg,t,r)}static $(){return["GetMemberRemovalInsightsRequest|1 team_id 5|2 user_id 5"]}}class Ig extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ig).fromBinary(t,r)}static fromJson(t,r){return(new Ig).fromJson(t,r)}static fromJsonString(t,r){return(new Ig).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ig,t,r)}static $(){return["GetMemberRemovalInsightsResponse|1 last_active_at 3?|2 accepted_generated_lines_last_30_days 5?"]}}class Pg extends T{constructor(t){super(),this.teamId=0,this.newSeats=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pg).fromBinary(t,r)}static fromJson(t,r){return(new Pg).fromJson(t,r)}static fromJsonString(t,r){return(new Pg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pg,t,r)}static $(){return["ChangeSeatRequest|1 team_id 5|2 new_seats 5"]}}class bg extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bg).fromBinary(t,r)}static fromJson(t,r){return(new bg).fromJson(t,r)}static fromJsonString(t,r){return(new bg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bg,t,r)}static $(){return["ChangeSeatResponse|1 success 8"]}}class Rg extends T{constructor(t){super(),this.teamId=0,this.newNumSeats=0,this.newRequestQuotaPerSeat=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rg).fromBinary(t,r)}static fromJson(t,r){return(new Rg).fromJson(t,r)}static fromJsonString(t,r){return(new Rg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rg,t,r)}static $(){return["ChangeTeamSubscriptionRequest|1 team_id 5|2 new_num_seats 5|3 new_request_quota_per_seat 5"]}}class vg extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vg).fromBinary(t,r)}static fromJson(t,r){return(new vg).fromJson(t,r)}static fromJsonString(t,r){return(new vg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vg,t,r)}static $(){return["ChangeTeamSubscriptionResponse|1 success 8"]}}class xg extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xg).fromBinary(t,r)}static fromJson(t,r){return(new xg).fromJson(t,r)}static fromJsonString(t,r){return(new xg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xg,t,r)}static $(){return["GetSignUpTypeRequest"]}}class kg extends T{constructor(t){super(),this.signUpType=Eg.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kg).fromBinary(t,r)}static fromJson(t,r){return(new kg).fromJson(t,r)}static fromJsonString(t,r){return(new kg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kg,t,r)}static $(){return["GetSignUpTypeResponse|1 sign_up_type #0",Eg]}}var Eg=(0,a.QT)(n.proto3,C,"GetSignUpTypeResponse.SignUpType",[[0,"UNSPECIFIED"],[1,"AUTH_0"],[2,"GOOGLE"],[3,"GITHUB"],[4,"WORKOS"],[5,"GROK"],[6,"X"]],1);class Cg extends T{constructor(t){super(),this.platform=Tg.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cg).fromBinary(t,r)}static fromJson(t,r){return(new Cg).fromJson(t,r)}static fromJsonString(t,r){return(new Cg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cg,t,r)}static $(){return["GetDownloadLinkRequest|1 platform #0",Tg]}}var Tg=(0,a.QT)(n.proto3,C,"GetDownloadLinkRequest.Platform",[[0,"UNSPECIFIED"],[1,"MAC_APPLE_SILICON"],[2,"MAC_INTEL"],[3,"MAC_UNIVERSAL"],[4,"WINDOWS"],[5,"LINUX"]],1);class Ug extends T{constructor(t){super(),this.cachedDownloadLink="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ug).fromBinary(t,r)}static fromJson(t,r){return(new Ug).fromJson(t,r)}static fromJsonString(t,r){return(new Ug).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ug,t,r)}static $(){return["GetDownloadLinkResponse|1 cached_download_link 9"]}}class Ag extends T{constructor(t){super(),this.currentVersion="",this.channel="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ag).fromBinary(t,r)}static fromJson(t,r){return(new Ag).fromJson(t,r)}static fromJsonString(t,r){return(new Ag).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ag,t,r)}static $(){return["GetCliDownloadUrlRequest|1 current_version 9|2 channel 9"]}}class $g extends T{constructor(t){super(),this.url="",this.version="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $g).fromBinary(t,r)}static fromJson(t,r){return(new $g).fromJson(t,r)}static fromJsonString(t,r){return(new $g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($g,t,r)}static $(){return["GetCliDownloadUrlResponse|1 url 9|2 version 9"]}}class Mg extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mg).fromBinary(t,r)}static fromJson(t,r){return(new Mg).fromJson(t,r)}static fromJsonString(t,r){return(new Mg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mg,t,r)}static $(){return["GetSsoConfigurationLinksRequest|1 team_id 5"]}}class Og extends T{constructor(t){super(),this.ssoUrl="",this.domainVerificationUrl="",this.ssoStatus="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Og).fromBinary(t,r)}static fromJson(t,r){return(new Og).fromJson(t,r)}static fromJsonString(t,r){return(new Og).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Og,t,r)}static $(){return["GetSsoConfigurationLinksResponse|1 sso_url 9|2 domain_verification_url 9|3 sso_status 9"]}}class Dg extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dg).fromBinary(t,r)}static fromJson(t,r){return(new Dg).fromJson(t,r)}static fromJsonString(t,r){return(new Dg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dg,t,r)}static $(){return["GetScimConfigurationLinksRequest|1 team_id 5"]}}class Ng extends T{constructor(t){super(),this.scimUrl="",this.scimStatus="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ng).fromBinary(t,r)}static fromJson(t,r){return(new Ng).fromJson(t,r)}static fromJsonString(t,r){return(new Ng).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ng,t,r)}static $(){return["GetScimConfigurationLinksResponse|1 scim_url 9|2 scim_status 9"]}}class Gg extends T{constructor(t){super(),this.scimUrl="",this.scimStatuses=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gg).fromBinary(t,r)}static fromJson(t,r){return(new Gg).fromJson(t,r)}static fromJsonString(t,r){return(new Gg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gg,t,r)}static $(){return["GetOrganizationScimConfigurationLinksResponse|1 scim_url 9|2 scim_statuses 9*"]}}class Lg extends T{constructor(t){super(),this.teamId=0,this.adminOnlyUsagePricing=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lg).fromBinary(t,r)}static fromJson(t,r){return(new Lg).fromJson(t,r)}static fromJsonString(t,r){return(new Lg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Lg,t,r)}static $(){return["SetAdminOnlyUsagePricingRequest|1 team_id 5|2 admin_only_usage_pricing 8"]}}class Fg extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fg).fromBinary(t,r)}static fromJson(t,r){return(new Fg).fromJson(t,r)}static fromJsonString(t,r){return(new Fg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fg,t,r)}static $(){return["SetAdminOnlyUsagePricingResponse"]}}class Kg extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kg).fromBinary(t,r)}static fromJson(t,r){return(new Kg).fromJson(t,r)}static fromJsonString(t,r){return(new Kg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Kg,t,r)}static $(){return["GetYearlyUpgradeEligibilityRequest|1 team_id 5"]}}class zg extends T{constructor(t){super(),this.eligible=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zg).fromBinary(t,r)}static fromJson(t,r){return(new zg).fromJson(t,r)}static fromJsonString(t,r){return(new zg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zg,t,r)}static $(){return["GetYearlyUpgradeEligibilityResponse|1 eligible 8"]}}class jg extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jg).fromBinary(t,r)}static fromJson(t,r){return(new jg).fromJson(t,r)}static fromJsonString(t,r){return(new jg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jg,t,r)}static $(){return["UpgradeToYearlyRequest|1 team_id 5"]}}class Hg extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hg).fromBinary(t,r)}static fromJson(t,r){return(new Hg).fromJson(t,r)}static fromJsonString(t,r){return(new Hg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hg,t,r)}static $(){return["UpgradeToYearlyResponse"]}}class Wg extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wg).fromBinary(t,r)}static fromJson(t,r){return(new Wg).fromJson(t,r)}static fromJsonString(t,r){return(new Wg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wg,t,r)}static $(){return["GetEnterpriseCTAEligibilityRequest|1 team_id 5"]}}class Qg extends T{constructor(t){super(),this.eligible=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qg).fromBinary(t,r)}static fromJson(t,r){return(new Qg).fromJson(t,r)}static fromJsonString(t,r){return(new Qg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qg,t,r)}static $(){return["GetEnterpriseCTAEligibilityResponse|1 eligible 8"]}}class Vg extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vg).fromBinary(t,r)}static fromJson(t,r){return(new Vg).fromJson(t,r)}static fromJsonString(t,r){return(new Vg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vg,t,r)}static $(){return["GetUsageBasedPremiumRequestsRequest|1 team_id 5"]}}class Xg extends T{constructor(t){super(),this.usageBasedPremiumRequests=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xg).fromBinary(t,r)}static fromJson(t,r){return(new Xg).fromJson(t,r)}static fromJsonString(t,r){return(new Xg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xg,t,r)}static $(){return["GetUsageBasedPremiumRequestsResponse|1 usage_based_premium_requests 8"]}}class Yg extends T{constructor(t){super(),this.teamId=0,this.usageBasedPremiumRequests=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yg).fromBinary(t,r)}static fromJson(t,r){return(new Yg).fromJson(t,r)}static fromJsonString(t,r){return(new Yg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yg,t,r)}static $(){return["SetUsageBasedPremiumRequestsRequest|1 team_id 5|2 usage_based_premium_requests 8"]}}class Zg extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zg).fromBinary(t,r)}static fromJson(t,r){return(new Zg).fromJson(t,r)}static fromJsonString(t,r){return(new Zg).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zg,t,r)}static $(){return["SetUsageBasedPremiumRequestsResponse"]}}class t_ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new t_).fromBinary(t,r)}static fromJson(t,r){return(new t_).fromJson(t,r)}static fromJsonString(t,r){return(new t_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(t_,t,r)}static $(){return["GetReferralsRequest"]}}class r_ extends T{constructor(t){super(),this.numReferrals=0,this.referralCode="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new r_).fromBinary(t,r)}static fromJson(t,r){return(new r_).fromJson(t,r)}static fromJsonString(t,r){return(new r_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(r_,t,r)}static $(){return["GetReferralsResponse|1 num_referrals 5|2 referral_code 9"]}}class e_ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new e_).fromBinary(t,r)}static fromJson(t,r){return(new e_).fromJson(t,r)}static fromJsonString(t,r){return(new e_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(e_,t,r)}static $(){return["GetReferralCodesRequest"]}}class n_ extends T{constructor(t){super(),this.referralCodes=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new n_).fromBinary(t,r)}static fromJson(t,r){return(new n_).fromJson(t,r)}static fromJsonString(t,r){return(new n_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(n_,t,r)}static $(){return["GetReferralCodesResponse|1 referral_codes #0*",g_]}}class s_ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new s_).fromBinary(t,r)}static fromJson(t,r){return(new s_).fromJson(t,r)}static fromJsonString(t,r){return(new s_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(s_,t,r)}static $(){return["CreateP2PReferralLinkRequest"]}}class i_ extends T{constructor(t){super(),this.code="",this.urlPath="",this.title="",this.description="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new i_).fromBinary(t,r)}static fromJson(t,r){return(new i_).fromJson(t,r)}static fromJsonString(t,r){return(new i_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(i_,t,r)}static $(){return["CreateP2PReferralLinkResponse|1 code 9|2 url_path 9|3 title 9|4 description 9"]}}class o_ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o_).fromBinary(t,r)}static fromJson(t,r){return(new o_).fromJson(t,r)}static fromJsonString(t,r){return(new o_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o_,t,r)}static $(){return["GetP2PReferralStatusRequest"]}}class a_ extends T{constructor(t){super(),this.isEligible=!1,this.successfulReferrals=0,this.pendingReferrals=0,this.remainingCap=0,this.totalCreditCentsEarned=n.protoInt64.zero,this.cycleCreditCentsEarned=n.protoInt64.zero,this.title="",this.description="",this.invitedReferrals=0,this.invitedRewardEarned=0,this.invitedSignedUp=0,this.invitedNotEligible=0,this.invitedClawedBack=0,this.capWindowLabel="",this.referrerCreditCents=0,this.refereeCreditCents=0,this.currency="",this.referrerMode="",this.refereeMode="",this.remainingRedemptionCap=0,this.rewardedReferrals=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a_).fromBinary(t,r)}static fromJson(t,r){return(new a_).fromJson(t,r)}static fromJsonString(t,r){return(new a_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a_,t,r)}static $(){return["GetP2PReferralStatusResponse|1 is_eligible 8|2 code 9?|3 url_path 9?|4 successful_referrals 5|5 pending_referrals 5|6 remaining_cap 5|7 total_credit_cents_earned 3|22 cycle_credit_cents_earned 3|8 title 9|9 description 9|10 cycle_start_ms 3?|11 invited_referrals 5|12 invited_reward_earned 5|13 invited_signed_up 5|14 invited_not_eligible 5|15 invited_clawed_back 5|16 cap_window_label 9|17 referrer_credit_cents 5|18 referee_credit_cents 5|19 currency 9|20 referrer_mode 9|21 referee_mode 9|23 remaining_redemption_cap 5|24 rewarded_referrals 5"]}}class u_ extends T{constructor(t){super(),this.emails=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u_).fromBinary(t,r)}static fromJson(t,r){return(new u_).fromJson(t,r)}static fromJsonString(t,r){return(new u_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u_,t,r)}static $(){return["SendP2PReferralInvitesRequest|1 emails 9*"]}}class c_ extends T{constructor(t){super(),this.sentEmails=[],this.failures=[],this.code="",this.urlPath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c_).fromBinary(t,r)}static fromJson(t,r){return(new c_).fromJson(t,r)}static fromJsonString(t,r){return(new c_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c_,t,r)}static $(){return["SendP2PReferralInvitesResponse|1 sent_emails 9*|2 failures #0*|3 code 9|4 url_path 9",l_]}}class l_ extends T{constructor(t){super(),this.email="",this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l_).fromBinary(t,r)}static fromJson(t,r){return(new l_).fromJson(t,r)}static fromJsonString(t,r){return(new l_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l_,t,r)}static $(){return["SendP2PReferralInvitesFailure|1 email 9|2 reason 9"]}}class m_ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m_).fromBinary(t,r)}static fromJson(t,r){return(new m_).fromJson(t,r)}static fromJsonString(t,r){return(new m_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m_,t,r)}static $(){return["GetP2PReferralHistoryRequest"]}}class f_ extends T{constructor(t){super(),this.entries=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f_).fromBinary(t,r)}static fromJson(t,r){return(new f_).fromJson(t,r)}static fromJsonString(t,r){return(new f_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f_,t,r)}static $(){return["GetP2PReferralHistoryResponse|1 entries #0*",d_]}}class d_ extends T{constructor(t){super(),this.refereeLabel="",this.displayStatus="",this.creditCentsEarned=n.protoInt64.zero,this.createdAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d_).fromBinary(t,r)}static fromJson(t,r){return(new d_).fromJson(t,r)}static fromJsonString(t,r){return(new d_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d_,t,r)}static $(){return["P2PReferralHistoryEntry|1 referee_label 9|2 display_status 9|3 credit_cents_earned 3|4 created_at_ms 3"]}}class p_ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p_).fromBinary(t,r)}static fromJson(t,r){return(new p_).fromJson(t,r)}static fromJsonString(t,r){return(new p_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p_,t,r)}static $(){return["CheckReferralAllowlistRequest"]}}class h_ extends T{constructor(t){super(),this.isInAllowlist=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h_).fromBinary(t,r)}static fromJson(t,r){return(new h_).fromJson(t,r)}static fromJsonString(t,r){return(new h_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h_,t,r)}static $(){return["CheckReferralAllowlistResponse|1 is_in_allowlist 8"]}}class g_ extends T{constructor(t){super(),this.code="",this.createdAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g_).fromBinary(t,r)}static fromJson(t,r){return(new g_).fromJson(t,r)}static fromJsonString(t,r){return(new g_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g_,t,r)}static $(){return["ReferralCodeEntry|1 code 9|2 created_at_ms 3|3 redeemed_at_ms 3?|4 redeemer_name 9?"]}}class __ extends T{constructor(t){super(),this.referralCode="",this.authId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new __).fromBinary(t,r)}static fromJson(t,r){return(new __).fromJson(t,r)}static fromJsonString(t,r){return(new __).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(__,t,r)}static $(){return["CheckReferralCodeRequest|1 referral_code 9|2 auth_id 9"]}}class J_ extends T{constructor(t){super(),this.isValid=!1,this.userIsEligible=!1,this.maxRedemptions=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new J_).fromBinary(t,r)}static fromJson(t,r){return(new J_).fromJson(t,r)}static fromJsonString(t,r){return(new J_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(J_,t,r)}static $(){return["CheckReferralCodeResponse|1 is_valid 8|2 user_is_eligible 8|3 max_redemptions 8|4 metadata #0?",w_]}}class w_ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new w_).fromBinary(t,r)}static fromJson(t,r){return(new w_).fromJson(t,r)}static fromJsonString(t,r){return(new w_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(w_,t,r)}static $(){return["Metadata|1 title 9?|2 description 9?|3 discount_type 9?"]}}class y_ extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new y_).fromBinary(t,r)}static fromJson(t,r){return(new y_).fromJson(t,r)}static fromJsonString(t,r){return(new y_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(y_,t,r)}static $(){return["GetTeamReposRequest|1 team_id 5"]}}class S_ extends T{constructor(t){super(),this.repos=[],this.teamRepoType="",this.allowedRepos=[],this.disableLocalExecAllowlistEnforcement=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new S_).fromBinary(t,r)}static fromJson(t,r){return(new S_).fromJson(t,r)}static fromJsonString(t,r){return(new S_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(S_,t,r)}static $(){return["GetTeamReposResponse|1 repos #0*|2 team_repo_type 9|3 allowed_repos #0*|4 disable_local_exec_allowlist_enforcement 8",q_]}}class q_ extends T{constructor(t){super(),this.id=0,this.url="",this.patterns=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new q_).fromBinary(t,r)}static fromJson(t,r){return(new q_).fromJson(t,r)}static fromJsonString(t,r){return(new q_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(q_,t,r)}static $(){return["GetTeamReposResponse.Repo|1 id 5|2 url 9|3 patterns #0*",B_]}}class B_ extends T{constructor(t){super(),this.id=0,this.pattern="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new B_).fromBinary(t,r)}static fromJson(t,r){return(new B_).fromJson(t,r)}static fromJsonString(t,r){return(new B_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(B_,t,r)}static $(){return["GetTeamReposResponse.Pattern|1 id 5|2 pattern 9"]}}class I_ extends T{constructor(t){super(),this.teamId=0,this.repoUrl="",this.repoType="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new I_).fromBinary(t,r)}static fromJson(t,r){return(new I_).fromJson(t,r)}static fromJsonString(t,r){return(new I_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(I_,t,r)}static $(){return["CreateTeamRepoRequest|1 team_id 5|2 repo_url 9|3 repo_type 9"]}}class P_ extends T{constructor(t){super(),this.repoId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new P_).fromBinary(t,r)}static fromJson(t,r){return(new P_).fromJson(t,r)}static fromJsonString(t,r){return(new P_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(P_,t,r)}static $(){return["CreateTeamRepoResponse|1 repo_id 5"]}}class b_ extends T{constructor(t){super(),this.teamId=0,this.repoId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new b_).fromBinary(t,r)}static fromJson(t,r){return(new b_).fromJson(t,r)}static fromJsonString(t,r){return(new b_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(b_,t,r)}static $(){return["DeleteTeamRepoRequest|1 team_id 5|2 repo_id 5"]}}class R_ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new R_).fromBinary(t,r)}static fromJson(t,r){return(new R_).fromJson(t,r)}static fromJsonString(t,r){return(new R_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(R_,t,r)}static $(){return["DeleteTeamRepoResponse"]}}class v_ extends T{constructor(t){super(),this.teamId=0,this.repoId=0,this.pattern="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new v_).fromBinary(t,r)}static fromJson(t,r){return(new v_).fromJson(t,r)}static fromJsonString(t,r){return(new v_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(v_,t,r)}static $(){return["AddRepoPatternRequest|1 team_id 5|2 repo_id 5|3 pattern 9"]}}class x_ extends T{constructor(t){super(),this.patternId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new x_).fromBinary(t,r)}static fromJson(t,r){return(new x_).fromJson(t,r)}static fromJsonString(t,r){return(new x_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(x_,t,r)}static $(){return["AddRepoPatternResponse|1 pattern_id 5"]}}class k_ extends T{constructor(t){super(),this.teamId=0,this.repoId=0,this.patternId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new k_).fromBinary(t,r)}static fromJson(t,r){return(new k_).fromJson(t,r)}static fromJsonString(t,r){return(new k_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(k_,t,r)}static $(){return["RemoveRepoPatternRequest|1 team_id 5|2 repo_id 5|3 pattern_id 5"]}}class E_ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new E_).fromBinary(t,r)}static fromJson(t,r){return(new E_).fromJson(t,r)}static fromJsonString(t,r){return(new E_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(E_,t,r)}static $(){return["RemoveRepoPatternResponse"]}}class C_ extends T{constructor(t){super(),this.id=n.protoInt64.zero,this.teamId=0,this.teamName="",this.gitOrgOwner="",this.gitProvider=At.UNSPECIFIED,this.createdAt=n.protoInt64.zero,this.updatedAt=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new C_).fromBinary(t,r)}static fromJson(t,r){return(new C_).fromJson(t,r)}static fromJsonString(t,r){return(new C_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(C_,t,r)}static $(){return["ProtectedGitScope|1 id 3|2 team_id 5|3 team_name 9|4 git_org_owner 9|5 git_provider #0|6 git_enterprise_uuid 9?|7 created_at 3|8 updated_at 3",At]}}class T_ extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new T_).fromBinary(t,r)}static fromJson(t,r){return(new T_).fromJson(t,r)}static fromJsonString(t,r){return(new T_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(T_,t,r)}static $(){return["GetProtectedGitScopesRequest|1 team_id 5"]}}class U_ extends T{constructor(t){super(),this.scopes=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new U_).fromBinary(t,r)}static fromJson(t,r){return(new U_).fromJson(t,r)}static fromJsonString(t,r){return(new U_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(U_,t,r)}static $(){return["GetProtectedGitScopesResponse|1 scopes #0*",C_]}}class A_ extends T{constructor(t){super(),this.teamId=0,this.repoUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new A_).fromBinary(t,r)}static fromJson(t,r){return(new A_).fromJson(t,r)}static fromJsonString(t,r){return(new A_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(A_,t,r)}static $(){return["CreateProtectedGitScopeRequest|1 team_id 5|2 repo_url 9"]}}class $_ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $_).fromBinary(t,r)}static fromJson(t,r){return(new $_).fromJson(t,r)}static fromJsonString(t,r){return(new $_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($_,t,r)}static $(){return["CreateProtectedGitScopeResponse|1 scope #0",C_]}}class M_ extends T{constructor(t){super(),this.teamId=0,this.scopeId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new M_).fromBinary(t,r)}static fromJson(t,r){return(new M_).fromJson(t,r)}static fromJsonString(t,r){return(new M_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(M_,t,r)}static $(){return["DeleteProtectedGitScopeRequest|1 team_id 5|2 scope_id 3"]}}class O_ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new O_).fromBinary(t,r)}static fromJson(t,r){return(new O_).fromJson(t,r)}static fromJsonString(t,r){return(new O_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(O_,t,r)}static $(){return["DeleteProtectedGitScopeResponse"]}}class D_ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new D_).fromBinary(t,r)}static fromJson(t,r){return(new D_).fromJson(t,r)}static fromJsonString(t,r){return(new D_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(D_,t,r)}static $(){return["GetTeamAdminSettingsRequest|1 team_id 5?|2 supports_host_mcp_bridge_exemption 8?"]}}class N_ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new N_).fromBinary(t,r)}static fromJson(t,r){return(new N_).fromJson(t,r)}static fromJsonString(t,r){return(new N_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(N_,t,r)}static $(){return["GetTeamOriginDisabledRequest|1 team_id 5?"]}}class G_ extends T{constructor(t){super(),this.originDisabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new G_).fromBinary(t,r)}static fromJson(t,r){return(new G_).fromJson(t,r)}static fromJsonString(t,r){return(new G_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(G_,t,r)}static $(){return["GetTeamOriginDisabledResponse|1 origin_disabled 8"]}}class L_ extends T{constructor(t){super(),this.displayName="",this.kind=$t.UNSPECIFIED,this.host="",this.memberCount=0,this.pluginId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new L_).fromBinary(t,r)}static fromJson(t,r){return(new L_).fromJson(t,r)}static fromJsonString(t,r){return(new L_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(L_,t,r)}static $(){return["UnlistedMemberServer|1 display_name 9|2 kind #0|3 host 9|4 member_count 5|5 plugin_id 9",$t]}}class F_ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new F_).fromBinary(t,r)}static fromJson(t,r){return(new F_).fromJson(t,r)}static fromJsonString(t,r){return(new F_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(F_,t,r)}static $(){return["ListUnlistedMemberServersRequest|1 team_id 5?"]}}class K_ extends T{constructor(t){super(),this.servers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new K_).fromBinary(t,r)}static fromJson(t,r){return(new K_).fromJson(t,r)}static fromJsonString(t,r){return(new K_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(K_,t,r)}static $(){return["ListUnlistedMemberServersResponse|1 servers #0*",L_]}}class z_ extends T{constructor(t){super(),this.rules=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new z_).fromBinary(t,r)}static fromJson(t,r){return(new z_).fromJson(t,r)}static fromJsonString(t,r){return(new z_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(z_,t,r)}static $(){return["AdminCommandDenylist|1 rules 9*"]}}class j_ extends T{constructor(t){super(),this.enabled=!1,this.allowed=[],this.blocked=[],this.disableMcpAutoRun=!1,this.deleteFileProtection=!1,this.enableRunEverything=!1,this.mcpToolAllowlist=[],this.browserProtection=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new j_).fromBinary(t,r)}static fromJson(t,r){return(new j_).fromJson(t,r)}static fromJsonString(t,r){return(new j_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(j_,t,r)}static $(){return["AutoRunControls|1 enabled 8|2 allowed 9*|3 blocked 9*|4 disable_mcp_auto_run 8|5 delete_file_protection 8|6 enable_run_everything 8|7 mcp_tool_allowlist 9*|8 sandboxing_controls #0|9 browser_protection 8|10 enable_smart_auto 8?|11 enable_allowlist_mode 8?|12 admin_command_denylist #1|13 admin_command_denylist_replaces_team 8?",SJ,z_]}}class H_ extends T{constructor(t){super(),this.allowInstructions=[],this.blockInstructions=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new H_).fromBinary(t,r)}static fromJson(t,r){return(new H_).fromJson(t,r)}static fromJsonString(t,r){return(new H_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(H_,t,r)}static $(){return["AutoReviewInstructions|1 allow_instructions 9*|2 block_instructions 9*"]}}class W_ extends T{constructor(t){super(),this.hierarchicalEnabled=!1,this.ignoreSymlinks=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new W_).fromBinary(t,r)}static fromJson(t,r){return(new W_).fromJson(t,r)}static fromJsonString(t,r){return(new W_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(W_,t,r)}static $(){return["CursorIgnoreControls|1 hierarchical_enabled 8|2 ignore_symlinks 8"]}}class Q_ extends T{constructor(t){super(),this.networkAllowlist=[],this.toolAllowlist=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Q_).fromBinary(t,r)}static fromJson(t,r){return(new Q_).fromJson(t,r)}static fromJsonString(t,r){return(new Q_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Q_,t,r)}static $(){return["AllowedMCPServer|1 command 9?|2 server_url 9?|3 name 9?|4 network_allowlist 9*|5 tool_allowlist 9*|6 network_mode 9?|7 tool_allowlist_mode 9?|8 builtin_server 9?|9 is_derived 8?|10 rule_id 9?"]}}class V_ extends T{constructor(t){super(),this.allowedMcpServers=[],this.deniedMcpServers=[],this.builtinMcpServers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new V_).fromBinary(t,r)}static fromJson(t,r){return(new V_).fromJson(t,r)}static fromJsonString(t,r){return(new V_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(V_,t,r)}static $(){return["AllowedMCPConfiguration|1 disable_all 8?|2 allowed_mcp_servers #0*|3 require_mcp_servers_in_team_network_allowlist 8?|4 allow_user_override_mcp_servers 8?|10 denied_mcp_servers #0*|11 enable_cursor_cloud_mcp 8?|12 builtin_mcp_servers #0*|13 off_mcp_server_rules #1",Q_,X_]}}class X_ extends T{constructor(t){super(),this.rules=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new X_).fromBinary(t,r)}static fromJson(t,r){return(new X_).fromJson(t,r)}static fromJsonString(t,r){return(new X_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(X_,t,r)}static $(){return["OffMcpServerRules|1 rules #0*",Q_]}}class Y_ extends T{constructor(t){super(),this.mode=Mt.UNSPECIFIED,this.allowedPluginIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Y_).fromBinary(t,r)}static fromJson(t,r){return(new Y_).fromJson(t,r)}static fromJsonString(t,r){return(new Y_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Y_,t,r)}static $(){return["FirstPartyPluginConfiguration|1 mode #0|2 allowed_plugin_ids 9*",Mt]}}class Z_ extends T{constructor(t){super(),this.prReviewOpenDestination=Dt.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Z_).fromBinary(t,r)}static fromJson(t,r){return(new Z_).fromJson(t,r)}static fromJsonString(t,r){return(new Z_).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Z_,t,r)}static $(){return["PullRequestPreferences|1 pr_review_open_destination #0",Dt]}}class tJ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tJ).fromBinary(t,r)}static fromJson(t,r){return(new tJ).fromJson(t,r)}static fromJsonString(t,r){return(new tJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tJ,t,r)}static $(){return["GetRepoSourcePreferenceRequest|1 team_id 5?"]}}class rJ extends T{constructor(t){super(),this.userPreference=zt.UNSPECIFIED,this.teamPreference=zt.UNSPECIFIED,this.effectivePreference=zt.UNSPECIFIED,this.canConfigure=!1,this.originReposEnabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rJ).fromBinary(t,r)}static fromJson(t,r){return(new rJ).fromJson(t,r)}static fromJsonString(t,r){return(new rJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rJ,t,r)}static $(){return["GetRepoSourcePreferenceResponse|1 user_preference #0|2 team_preference #0|3 effective_preference #0|4 can_configure 8|5 origin_repos_enabled 8",zt]}}class eJ extends T{constructor(t){super(),this.preference=zt.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eJ).fromBinary(t,r)}static fromJson(t,r){return(new eJ).fromJson(t,r)}static fromJsonString(t,r){return(new eJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eJ,t,r)}static $(){return["UpdateUserRepoSourcePreferenceRequest|1 preference #0",zt]}}class nJ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nJ).fromBinary(t,r)}static fromJson(t,r){return(new nJ).fromJson(t,r)}static fromJsonString(t,r){return(new nJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nJ,t,r)}static $(){return["UpdateUserRepoSourcePreferenceResponse"]}}class sJ extends T{constructor(t){super(),this.teamId=0,this.preference=zt.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sJ).fromBinary(t,r)}static fromJson(t,r){return(new sJ).fromJson(t,r)}static fromJsonString(t,r){return(new sJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sJ,t,r)}static $(){return["UpdateTeamRepoSourcePreferenceRequest|1 team_id 5|2 preference #0",zt]}}class iJ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iJ).fromBinary(t,r)}static fromJson(t,r){return(new iJ).fromJson(t,r)}static fromJsonString(t,r){return(new iJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iJ,t,r)}static $(){return["UpdateTeamRepoSourcePreferenceResponse"]}}class oJ extends T{constructor(t){super(),this.repoUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oJ).fromBinary(t,r)}static fromJson(t,r){return(new oJ).fromJson(t,r)}static fromJsonString(t,r){return(new oJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oJ,t,r)}static $(){return["ResolvePrCreationForgeRequest|1 repo_url 9|2 team_id 5?"]}}class aJ extends T{constructor(t){super(),this.forge=uJ.UNSPECIFIED,this.repoUrl="",this.switched=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aJ).fromBinary(t,r)}static fromJson(t,r){return(new aJ).fromJson(t,r)}static fromJsonString(t,r){return(new aJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aJ,t,r)}static $(){return["ResolvePrCreationForgeResponse|1 forge #0|2 repo_url 9|3 switched 8",uJ]}}var uJ=(0,a.QT)(n.proto3,C,"ResolvePrCreationForgeResponse.PrCreationForge",[[0,"UNSPECIFIED"],[1,"GITHUB"],[2,"ORIGIN"]],1);class cJ extends T{constructor(t){super(),this.allowlist=[],this.allowlistConfig=Tr.UNSPECIFIED,this.teamFollowupEnabled=!1,this.autoCreatePr=Ot.UNSPECIFIED,this.prReviewOpenDestination=Dt.UNSPECIFIED,this.githubArtifactPosting=Nt.UNSPECIFIED,this.egressProtectionMode=Lt.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cJ).fromBinary(t,r)}static fromJson(t,r){return(new cJ).fromJson(t,r)}static fromJsonString(t,r){return(new cJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cJ,t,r)}static $(){return["BackgroundAgentSettings|1 allowlist 9*|2 allowlist_config #0|3 team_followup_enabled 8|4 auto_create_pr #1|5 pr_review_open_destination #2|6 require_private_workers 8?|7 github_artifact_posting #3|8 team_followup_enabled_v2 #4?|9 enable_long_running_agent_mode 8?|10 egress_protection_mode #5|11 lock_egress_protection_mode 8?|12 enable_cloud_agent_testing 8?|13 restrict_team_secrets_to_admins 8?|14 enable_automations 8?|15 allow_vm_sharing 8?|16 allow_private_workers 8?|17 public_artifact_sharing #6?|18 ci_failure_followup_enabled 8?|19 data_retention #7|20 restrict_team_environment_writes_to_admins 8?|21 allow_remote_control 8?|22 allow_private_worker_github_token_mint 8?|23 allow_private_worker_secret_sync 8?|24 disable_cloud_agents_in_sand 8?|25 automation_default_visibility #8?|26 auto_allow_project_placements 8?|27 personal_secrets_policy #9?|28 default_private_worker_pool 9?|29 grok_bot_customer_hosted 8?|30 grok_bot_customer_hosted_pool 9?|31 reject_static_pool_credentials 8?|32 slack_reply_mode #10?|33 route_scm_tokens_through_http_rules 8?|34 vnc_enabled 8?",Tr,Ot,Dt,Nt,Ft,Lt,Gt,pJ,jt,Ht,Kt]}}class lJ extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lJ).fromBinary(t,r)}static fromJson(t,r){return(new lJ).fromJson(t,r)}static fromJsonString(t,r){return(new lJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lJ,t,r)}static $(){return["GetCloudAgentStartupScriptRequest|1 team_id 5"]}}class mJ extends T{constructor(t){super(),this.available=!1,this.name="",this.body="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mJ).fromBinary(t,r)}static fromJson(t,r){return(new mJ).fromJson(t,r)}static fromJsonString(t,r){return(new mJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mJ,t,r)}static $(){return["GetCloudAgentStartupScriptResponse|1 available 8|2 name 9|3 body 9"]}}class fJ extends T{constructor(t){super(),this.teamId=0,this.name="",this.body="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fJ).fromBinary(t,r)}static fromJson(t,r){return(new fJ).fromJson(t,r)}static fromJsonString(t,r){return(new fJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fJ,t,r)}static $(){return["UpdateCloudAgentStartupScriptRequest|1 team_id 5|2 name 9|3 body 9"]}}class dJ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dJ).fromBinary(t,r)}static fromJson(t,r){return(new dJ).fromJson(t,r)}static fromJsonString(t,r){return(new dJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dJ,t,r)}static $(){return["UpdateCloudAgentStartupScriptResponse"]}}class pJ extends T{constructor(t){super(),this.kind={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pJ).fromBinary(t,r)}static fromJson(t,r){return(new pJ).fromJson(t,r)}static fromJsonString(t,r){return(new pJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pJ,t,r)}static $(){return["DataRetentionPolicy|1 indefinite #0 kind|2 limited #1 kind",hJ,gJ]}}class hJ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hJ).fromBinary(t,r)}static fromJson(t,r){return(new hJ).fromJson(t,r)}static fromJsonString(t,r){return(new hJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hJ,t,r)}static $(){return["DataRetentionPolicy.Indefinite"]}}class gJ extends T{constructor(t){super(),this.hours=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gJ).fromBinary(t,r)}static fromJson(t,r){return(new gJ).fromJson(t,r)}static fromJsonString(t,r){return(new gJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gJ,t,r)}static $(){return["DataRetentionPolicy.Limited|1 hours 13"]}}class _J extends T{constructor(t){super(),this.allowlist=[],this.allowlistConfig=Tr.UNSPECIFIED,this.disableHeadless=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _J).fromBinary(t,r)}static fromJson(t,r){return(new _J).fromJson(t,r)}static fromJsonString(t,r){return(new _J).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_J,t,r)}static $(){return["CliSettings|1 allowlist 9*|2 allowlist_config #0|3 disable_headless 8",Tr]}}class JJ extends T{constructor(t){super(),this.allowlist=[],this.allowlistConfig=Tr.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new JJ).fromBinary(t,r)}static fromJson(t,r){return(new JJ).fromJson(t,r)}static fromJsonString(t,r){return(new JJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(JJ,t,r)}static $(){return["BrowserAccessControl|1 allowlist 9*|2 allowlist_config #0",Tr]}}class wJ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wJ).fromBinary(t,r)}static fromJson(t,r){return(new wJ).fromJson(t,r)}static fromJsonString(t,r){return(new wJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wJ,t,r)}static $(){return["BrowserSettings|1 access_control #0",JJ]}}class yJ extends T{constructor(t){super(),this.enabled=!1,this.allowedTools=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yJ).fromBinary(t,r)}static fromJson(t,r){return(new yJ).fromJson(t,r)}static fromJsonString(t,r){return(new yJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yJ,t,r)}static $(){return["MCPControls|1 enabled 8|2 allowed_tools 9*"]}}class SJ extends T{constructor(t){super(),this.sandboxing=Wt.UNSPECIFIED,this.sandboxNetworking=Qt.UNSPECIFIED,this.sandboxGit=Vt.UNSPECIFIED,this.sandboxReadBoundary=Xt.UNSPECIFIED,this.sandboxReadAllowlistPaths=[],this.sandboxingEnforcedAvailable=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new SJ).fromBinary(t,r)}static fromJson(t,r){return(new SJ).fromJson(t,r)}static fromJsonString(t,r){return(new SJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(SJ,t,r)}static $(){return["AutoRunSandboxingControls|1 sandboxing #0|2 sandbox_networking #1|3 sandbox_git #2|4 sandbox_read_boundary #3|5 sandbox_read_allowlist_paths 9*|6 allow_user_override_sandbox_read_allowlist 8?|7 sandboxing_enforced_available 8",Wt,Qt,Vt,Xt]}}class qJ extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qJ).fromBinary(t,r)}static fromJson(t,r){return(new qJ).fromJson(t,r)}static fromJsonString(t,r){return(new qJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qJ,t,r)}static $(){return["PromptDeeplinkControls|1 enabled 8"]}}class BJ extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new BJ).fromBinary(t,r)}static fromJson(t,r){return(new BJ).fromJson(t,r)}static fromJsonString(t,r){return(new BJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(BJ,t,r)}static $(){return["CommandDeeplinkControls|1 enabled 8"]}}class IJ extends T{constructor(t){super(),this.enabled=!1,this.allowPublicDeeplinks=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new IJ).fromBinary(t,r)}static fromJson(t,r){return(new IJ).fromJson(t,r)}static fromJsonString(t,r){return(new IJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(IJ,t,r)}static $(){return["DeeplinkControls|1 enabled 8|2 allow_public_deeplinks 8"]}}class PJ extends T{constructor(t){super(),this.hidden=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new PJ).fromBinary(t,r)}static fromJson(t,r){return(new PJ).fromJson(t,r)}static fromJsonString(t,r){return(new PJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(PJ,t,r)}static $(){return["GithubIntegrationSettings|1 hidden 8"]}}class bJ extends T{constructor(t){super(),this.hidden=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bJ).fromBinary(t,r)}static fromJson(t,r){return(new bJ).fromJson(t,r)}static fromJsonString(t,r){return(new bJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bJ,t,r)}static $(){return["GitlabIntegrationSettings|1 hidden 8"]}}class RJ extends T{constructor(t){super(),this.hidden=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new RJ).fromBinary(t,r)}static fromJson(t,r){return(new RJ).fromJson(t,r)}static fromJsonString(t,r){return(new RJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(RJ,t,r)}static $(){return["BitbucketIntegrationSettings|1 hidden 8"]}}class vJ extends T{constructor(t){super(),this.hidden=!1,this.inboundInstallPolicyManagedByOrganization=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vJ).fromBinary(t,r)}static fromJson(t,r){return(new vJ).fromJson(t,r)}static fromJsonString(t,r){return(new vJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vJ,t,r)}static $(){return["SlackIntegrationSettings|1 hidden 8|3 inbound_install_policy #0?|4 inbound_install_policy_managed_by_organization 8",kJ]}}class xJ extends T{constructor(t){super(),this.slackTeamIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xJ).fromBinary(t,r)}static fromJson(t,r){return(new xJ).fromJson(t,r)}static fromJsonString(t,r){return(new xJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xJ,t,r)}static $(){return["SlackManagedWorkspaces|1 slack_team_ids 9*"]}}class kJ extends T{constructor(t){super(),this.mode=Yt.UNSPECIFIED,this.allowed=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kJ).fromBinary(t,r)}static fromJson(t,r){return(new kJ).fromJson(t,r)}static fromJsonString(t,r){return(new kJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kJ,t,r)}static $(){return["SlackInboundInstallPolicy|1 mode #0|2 allowed #1*",Yt,EJ]}}class EJ extends T{constructor(t){super(),this.principal={case:void 0},this.slackWorkspaceIds=[],this.surfaces=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new EJ).fromBinary(t,r)}static fromJson(t,r){return(new EJ).fromJson(t,r)}static fromJsonString(t,r){return(new EJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(EJ,t,r)}static $(){return["SlackInboundInstallAllowedPrincipal|1 team_id 5 principal|2 organization_id 3 principal|5 anyone 8 principal|3 slack_workspace_ids 9*|4 surfaces 9*"]}}class CJ extends T{constructor(t){super(),this.sharedDriveIds=[],this.mode=Zt.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new CJ).fromBinary(t,r)}static fromJson(t,r){return(new CJ).fromJson(t,r)}static fromJsonString(t,r){return(new CJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(CJ,t,r)}static $(){return["GoogleDriveBlockedSharedDrives|1 shared_drive_ids 9*|2 mode #0",Zt]}}class TJ extends T{constructor(t){super(),this.hidden=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new TJ).fromBinary(t,r)}static fromJson(t,r){return(new TJ).fromJson(t,r)}static fromJsonString(t,r){return(new TJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(TJ,t,r)}static $(){return["LinearIntegrationSettings|1 hidden 8"]}}class UJ extends T{constructor(t){super(),this.hidden=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new UJ).fromBinary(t,r)}static fromJson(t,r){return(new UJ).fromJson(t,r)}static fromJsonString(t,r){return(new UJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(UJ,t,r)}static $(){return["JiraIntegrationSettings|1 hidden 8"]}}class AJ extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new AJ).fromBinary(t,r)}static fromJson(t,r){return(new AJ).fromJson(t,r)}static fromJsonString(t,r){return(new AJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(AJ,t,r)}static $(){return["WorkspaceTrustControls|1 enabled 8"]}}class $J extends T{constructor(t){super(),this.enabled=!1,this.allowedVisibilities=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $J).fromBinary(t,r)}static fromJson(t,r){return(new $J).fromJson(t,r)}static fromJsonString(t,r){return(new $J).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($J,t,r)}static $(){return["SharedConversationSettings|1 enabled 8|2 allowed_visibilities #0*|3 allow_public_indexing 8?",Re]}}class MJ extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new MJ).fromBinary(t,r)}static fromJson(t,r){return(new MJ).fromJson(t,r)}static fromJsonString(t,r){return(new MJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(MJ,t,r)}static $(){return["SharedCanvasSettings|1 enabled 8"]}}class OJ extends T{constructor(t){super(),this.publicVisibilityAllowed=!1,this.policy="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new OJ).fromBinary(t,r)}static fromJson(t,r){return(new OJ).fromJson(t,r)}static fromJsonString(t,r){return(new OJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(OJ,t,r)}static $(){return["PublicProfileSettings|1 public_visibility_allowed 8|2 policy 9"]}}class DJ extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new DJ).fromBinary(t,r)}static fromJson(t,r){return(new DJ).fromJson(t,r)}static fromJsonString(t,r){return(new DJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(DJ,t,r)}static $(){return["CursorBlameSettings|1 enabled 8"]}}class NJ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new NJ).fromBinary(t,r)}static fromJson(t,r){return(new NJ).fromJson(t,r)}static fromJsonString(t,r){return(new NJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(NJ,t,r)}static $(){return["ProjectsSettings|1 enabled 8?"]}}class GJ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new GJ).fromBinary(t,r)}static fromJson(t,r){return(new GJ).fromJson(t,r)}static fromJsonString(t,r){return(new GJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(GJ,t,r)}static $(){return["AppsSettings|1 enabled 8?|2 allow_public_apps 8?|3 security #0?|4 allow_api_key_access 8?",LJ]}}class LJ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new LJ).fromBinary(t,r)}static fromJson(t,r){return(new LJ).fromJson(t,r)}static fromJsonString(t,r){return(new LJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(LJ,t,r)}static $(){return["AppsSecuritySettings|1 review_enabled 8?|2 custom_review_rules 8?|3 acknowledged_disable_review 8?|4 allow_review_overrides 8?"]}}class FJ extends T{constructor(t){super(),this.allowed=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new FJ).fromBinary(t,r)}static fromJson(t,r){return(new FJ).fromJson(t,r)}static fromJsonString(t,r){return(new FJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(FJ,t,r)}static $(){return["UserAgentStoreSkillsSyncSettings|1 allowed 8"]}}class KJ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new KJ).fromBinary(t,r)}static fromJson(t,r){return(new KJ).fromJson(t,r)}static fromJsonString(t,r){return(new KJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(KJ,t,r)}static $(){return["GetEffectiveUserAgentStoreSkillsSettingsRequest"]}}class zJ extends T{constructor(t){super(),this.enabled=!1,this.disabledByTeamAdmin=!1,this.disabledByPrivacyMode=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zJ).fromBinary(t,r)}static fromJson(t,r){return(new zJ).fromJson(t,r)}static fromJsonString(t,r){return(new zJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zJ,t,r)}static $(){return["GetEffectiveUserAgentStoreSkillsSettingsResponse|1 enabled 8|2 disabled_by_team_admin 8|3 disabled_by_privacy_mode 8"]}}class jJ extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jJ).fromBinary(t,r)}static fromJson(t,r){return(new jJ).fromJson(t,r)}static fromJsonString(t,r){return(new jJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jJ,t,r)}static $(){return["UpdateUserAgentStoreSkillsSettingsRequest|1 enabled 8"]}}class HJ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new HJ).fromBinary(t,r)}static fromJson(t,r){return(new HJ).fromJson(t,r)}static fromJsonString(t,r){return(new HJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(HJ,t,r)}static $(){return["UpdateUserAgentStoreSkillsSettingsResponse"]}}class WJ extends T{constructor(t){super(),this.verificationEnabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new WJ).fromBinary(t,r)}static fromJson(t,r){return(new WJ).fromJson(t,r)}static fromJsonString(t,r){return(new WJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(WJ,t,r)}static $(){return["ExtensionSigningSettings|1 verification_enabled 8"]}}class QJ extends T{constructor(t){super(),this.cooldownHours=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new QJ).fromBinary(t,r)}static fromJson(t,r){return(new QJ).fromJson(t,r)}static fromJsonString(t,r){return(new QJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(QJ,t,r)}static $(){return["ExtensionInstallCooldownSettings|1 cooldown_hours 5"]}}class VJ extends T{constructor(t){super(),this.vsixInstallBlocked=!1,this.vsixInstallBypassExtensionIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new VJ).fromBinary(t,r)}static fromJson(t,r){return(new VJ).fromJson(t,r)}static fromJsonString(t,r){return(new VJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(VJ,t,r)}static $(){return["ExtensionSideloadSettings|1 vsix_install_blocked 8|2 vsix_install_bypass_extension_ids 9*"]}}class XJ extends T{constructor(t){super(),this.disableAttribution=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new XJ).fromBinary(t,r)}static fromJson(t,r){return(new XJ).fromJson(t,r)}static fromJsonString(t,r){return(new XJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(XJ,t,r)}static $(){return["AttributionControls|1 disable_attribution 8"]}}class YJ extends T{constructor(t){super(),this.modelId="",this.parameters=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new YJ).fromBinary(t,r)}static fromJson(t,r){return(new YJ).fromJson(t,r)}static fromJsonString(t,r){return(new YJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(YJ,t,r)}static $(){return["TeamAdminModelRef|1 model_id 9|2 parameters #0*",ZJ]}}class ZJ extends T{constructor(t){super(),this.id="",this.value="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ZJ).fromBinary(t,r)}static fromJson(t,r){return(new ZJ).fromJson(t,r)}static fromJsonString(t,r){return(new ZJ).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ZJ,t,r)}static $(){return["TeamAdminModelRef.ModelParameterValue|1 id 9|2 value 9"]}}class tw extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tw).fromBinary(t,r)}static fromJson(t,r){return(new tw).fromJson(t,r)}static fromJsonString(t,r){return(new tw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tw,t,r)}static $(){return["TeamAdminNewChatModelResetRule|1 source_model #0|2 target_model #0",YJ]}}class rw extends T{constructor(t){super(),this.enabled=!1,this.rules=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rw).fromBinary(t,r)}static fromJson(t,r){return(new rw).fromJson(t,r)}static fromJsonString(t,r){return(new rw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rw,t,r)}static $(){return["TeamAdminNewChatModelResetSettings|1 enabled 8|2 rules #0*",tw]}}class ew extends T{constructor(t){super(),this.permissionCeiling=tr.UNSPECIFIED,this.commandAllowlist=[],this.otherCommands=rr.UNSPECIFIED,this.commandBlocklist=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ew).fromBinary(t,r)}static fromJson(t,r){return(new ew).fromJson(t,r)}static fromJsonString(t,r){return(new ew).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ew,t,r)}static $(){return["LocalToolControls|1 permission_ceiling #0|2 command_allowlist 9*|3 other_commands #1|4 file_read_write_allowed 8?|5 other_local_actions_allowed 8?|6 command_blocklist 9*",tr,rr]}}class nw extends T{constructor(t){super(),this.egressMode=er.UNSPECIFIED,this.allowlist=[],this.locked=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nw).fromBinary(t,r)}static fromJson(t,r){return(new nw).fromJson(t,r)}static fromJsonString(t,r){return(new nw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nw,t,r)}static $(){return["SandNetworkControls|1 egress_mode #0|2 allowlist 9*|3 locked 8|4 apply_allowlist_to_mcp 8?|5 blocked_domains #1",er,sw]}}class sw extends T{constructor(t){super(),this.domains=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sw).fromBinary(t,r)}static fromJson(t,r){return(new sw).fromJson(t,r)}static fromJsonString(t,r){return(new sw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sw,t,r)}static $(){return["SandNetworkBlockedDomains|1 domains 9*"]}}class iw extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iw).fromBinary(t,r)}static fromJson(t,r){return(new iw).fromJson(t,r)}static fromJsonString(t,r){return(new iw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iw,t,r)}static $(){return["SandActionAuditSettings|1 enabled 8?"]}}class ow extends T{constructor(t){super(),this.allowInstructions=[],this.blockInstructions=[],this.connectorWriteTrustedUrls=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ow).fromBinary(t,r)}static fromJson(t,r){return(new ow).fromJson(t,r)}static fromJsonString(t,r){return(new ow).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ow,t,r)}static $(){return["SandAutoReviewControls|1 enforce_enabled 8?|2 allow_instructions 9*|3 block_instructions 9*|4 update_instructions 8?|5 rules_in_effect #0|6 connector_writes_need_approval 8?|7 connector_write_trusted_urls 9*",aw]}}class aw extends T{constructor(t){super(),this.source=uw.UNSPECIFIED,this.allowInstructions=[],this.blockInstructions=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aw).fromBinary(t,r)}static fromJson(t,r){return(new aw).fromJson(t,r)}static fromJsonString(t,r){return(new aw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aw,t,r)}static $(){return["SandAutoReviewRulesInEffect|1 source #0|2 allow_instructions 9*|3 block_instructions 9*",uw]}}var uw=(0,a.QT)(n.proto3,C,"SandAutoReviewRulesInEffect.Source",[[0,"UNSPECIFIED"],[1,"NONE"],[2,"TEAM_ADDS"],[3,"TEAM_REPLACES"]],1);class cw extends T{constructor(t){super(),this.mode=nr.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cw).fromBinary(t,r)}static fromJson(t,r){return(new cw).fromJson(t,r)}static fromJsonString(t,r){return(new cw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cw,t,r)}static $(){return["SandLocalEgressControls|1 allowed 8?|2 mode #0",nr]}}class lw extends T{constructor(t){super(),this.resourceType="",this.minPeriodDays=0,this.maxPeriodDays=0,this.leadDays=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lw).fromBinary(t,r)}static fromJson(t,r){return(new lw).fromJson(t,r)}static fromJsonString(t,r){return(new lw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lw,t,r)}static $(){return["TeamDataRetentionPolicy|1 resource_type 9|2 period_days 5?|3 min_period_days 5|4 max_period_days 5|5 lead_days 5"]}}class mw extends T{constructor(t){super(),this.teamId=0,this.resourceType="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mw).fromBinary(t,r)}static fromJson(t,r){return(new mw).fromJson(t,r)}static fromJsonString(t,r){return(new mw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mw,t,r)}static $(){return["GetTeamDataRetentionPolicyRequest|1 team_id 5|2 resource_type 9"]}}class fw extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fw).fromBinary(t,r)}static fromJson(t,r){return(new fw).fromJson(t,r)}static fromJsonString(t,r){return(new fw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fw,t,r)}static $(){return["GetTeamDataRetentionPolicyResponse|1 policy #0",lw]}}class dw extends T{constructor(t){super(),this.teamId=0,this.resourceType="",this.acknowledged=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dw).fromBinary(t,r)}static fromJson(t,r){return(new dw).fromJson(t,r)}static fromJsonString(t,r){return(new dw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dw,t,r)}static $(){return["UpdateTeamDataRetentionPolicyRequest|1 team_id 5|2 resource_type 9|3 period_days 5?|4 acknowledged 8"]}}class pw extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pw).fromBinary(t,r)}static fromJson(t,r){return(new pw).fromJson(t,r)}static fromJsonString(t,r){return(new pw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pw,t,r)}static $(){return["UpdateTeamDataRetentionPolicyResponse|1 policy #0",lw]}}class hw extends T{constructor(t){super(),this.allowedUserIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hw).fromBinary(t,r)}static fromJson(t,r){return(new hw).fromJson(t,r)}static fromJsonString(t,r){return(new hw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hw,t,r)}static $(){return["GlassSettings|1 allowed_user_ids 5*|2 allow_all_team_members 8?"]}}class gw extends T{constructor(t){super(),this.allowedValues=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gw).fromBinary(t,r)}static fromJson(t,r){return(new gw).fromJson(t,r)}static fromJsonString(t,r){return(new gw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gw,t,r)}static $(){return["ModelAllowlistParameterRestriction|1 allowed_values 9*"]}}class _w extends T{constructor(t){super(),this.grantedValues=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _w).fromBinary(t,r)}static fromJson(t,r){return(new _w).fromJson(t,r)}static fromJsonString(t,r){return(new _w).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_w,t,r)}static $(){return["ModelAllowlistParameterGrant|1 granted_values 9*"]}}class Jw extends T{constructor(t){super(),this.enabled=!1,this.parameterRestrictions={},this.parameterGrants={},this.defaultParameterValues=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jw).fromBinary(t,r)}static fromJson(t,r){return(new Jw).fromJson(t,r)}static fromJsonString(t,r){return(new Jw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jw,t,r)}static $(){return["ModelAllowlistModelEntry|1 enabled 8|2 parameter_restrictions 9,#0|3 parameter_grants 9,#1|4 default_parameter_values #2*",gw,_w,ZJ]}}class ww extends T{constructor(t){super(),this.enabled=!1,this.models={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ww).fromBinary(t,r)}static fromJson(t,r){return(new ww).fromJson(t,r)}static fromJsonString(t,r){return(new ww).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ww,t,r)}static $(){return["ModelAllowlistProviderEntry|1 enabled 8|2 models 9,#0",Jw]}}class yw extends T{constructor(t){super(),this.enabled=!1,this.models=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yw).fromBinary(t,r)}static fromJson(t,r){return(new yw).fromJson(t,r)}static fromJsonString(t,r){return(new yw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yw,t,r)}static $(){return["ModelAllowlistByokEntry|1 enabled 8|2 models 9*"]}}class Sw extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sw).fromBinary(t,r)}static fromJson(t,r){return(new Sw).fromJson(t,r)}static fromJsonString(t,r){return(new Sw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sw,t,r)}static $(){return["ModelAllowlistByok|1 openai #0?|2 anthropic #0?|3 google #0?|4 azure #0?|5 bedrock #0?",yw]}}class qw extends T{constructor(t){super(),this.newProviderDefault=Bw.UNSPECIFIED,this.newModelDefault=Bw.UNSPECIFIED,this.providers={},this.firstPartyPendingModels=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qw).fromBinary(t,r)}static fromJson(t,r){return(new qw).fromJson(t,r)}static fromJsonString(t,r){return(new qw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qw,t,r)}static $(){return["ModelAllowlist|1 new_provider_default #0|2 new_model_default #0|3 providers 9,#1|4 byok #2?|5 new_model_default_enabled_at 3?|6 new_first_party_model_default #3?|7 can_set_first_party_default_manually 8?|8 new_first_party_model_default_enabled_at 3?|9 first_party_pending_models #4*",Bw,ww,Sw,Iw,Pw]}}var Bw=(0,a.QT)(n.proto3,C,"ModelAllowlist.DefaultBehavior",[[0,"UNSPECIFIED"],[1,"ENABLED"],[2,"DISABLED"]],1),Iw=(0,a.QT)(n.proto3,C,"ModelAllowlist.FirstPartyModelDefault",[[0,"UNSPECIFIED"],[1,"IMMEDIATELY"],[2,"AFTER_7_DAYS"],[3,"MANUALLY"]],1);class Pw extends T{constructor(t){super(),this.mcid="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pw).fromBinary(t,r)}static fromJson(t,r){return(new Pw).fromJson(t,r)}static fromJsonString(t,r){return(new Pw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pw,t,r)}static $(){return["FirstPartyPendingModel|1 mcid 9|2 enables_at 3?"]}}class bw extends T{constructor(t){super(),this.configured=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bw).fromBinary(t,r)}static fromJson(t,r){return(new bw).fromJson(t,r)}static fromJsonString(t,r){return(new bw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bw,t,r)}static $(){return["LlmGatewayTeamCredentialStatus|1 configured 8"]}}class Rw extends T{constructor(t){super(),this.configured=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rw).fromBinary(t,r)}static fromJson(t,r){return(new Rw).fromJson(t,r)}static fromJsonString(t,r){return(new Rw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rw,t,r)}static $(){return["TeamLlmGatewayCredentialStatus|1 configured 8|2 credential_version 5?|3 updated_at_epoch_millis 3?"]}}class vw extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vw).fromBinary(t,r)}static fromJson(t,r){return(new vw).fromJson(t,r)}static fromJsonString(t,r){return(new vw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vw,t,r)}static $(){return["GetTeamLlmGatewayCredentialStatusRequest|1 team_id 5"]}}class xw extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xw).fromBinary(t,r)}static fromJson(t,r){return(new xw).fromJson(t,r)}static fromJsonString(t,r){return(new xw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xw,t,r)}static $(){return["GetTeamLlmGatewayCredentialStatusResponse|1 status #0",Rw]}}class kw extends T{constructor(t){super(),this.teamId=0,this.credential="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kw).fromBinary(t,r)}static fromJson(t,r){return(new kw).fromJson(t,r)}static fromJsonString(t,r){return(new kw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kw,t,r)}static $(){return["SetTeamLlmGatewayCredentialRequest|1 team_id 5|2 credential 9"]}}class Ew extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ew).fromBinary(t,r)}static fromJson(t,r){return(new Ew).fromJson(t,r)}static fromJsonString(t,r){return(new Ew).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ew,t,r)}static $(){return["SetTeamLlmGatewayCredentialResponse|1 status #0",Rw]}}class Cw extends T{constructor(t){super(),this.teamId=0,this.credential="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cw).fromBinary(t,r)}static fromJson(t,r){return(new Cw).fromJson(t,r)}static fromJsonString(t,r){return(new Cw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cw,t,r)}static $(){return["ReplaceTeamLlmGatewayCredentialRequest|1 team_id 5|2 credential 9"]}}class Tw extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tw).fromBinary(t,r)}static fromJson(t,r){return(new Tw).fromJson(t,r)}static fromJsonString(t,r){return(new Tw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tw,t,r)}static $(){return["ReplaceTeamLlmGatewayCredentialResponse|1 status #0",Rw]}}class Uw extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Uw).fromBinary(t,r)}static fromJson(t,r){return(new Uw).fromJson(t,r)}static fromJsonString(t,r){return(new Uw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Uw,t,r)}static $(){return["ClearTeamLlmGatewayCredentialRequest|1 team_id 5"]}}class Aw extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Aw).fromBinary(t,r)}static fromJson(t,r){return(new Aw).fromJson(t,r)}static fromJsonString(t,r){return(new Aw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Aw,t,r)}static $(){return["ClearTeamLlmGatewayCredentialResponse|1 status #0",Rw]}}class $w extends T{constructor(t){super(),this.family="",this.discoveryUrl="",this.adapter="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $w).fromBinary(t,r)}static fromJson(t,r){return(new $w).fromJson(t,r)}static fromJsonString(t,r){return(new $w).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($w,t,r)}static $(){return["LlmGatewayModelDiscoverySource|1 family 9|2 discovery_url 9|3 adapter 9"]}}class Mw extends T{constructor(t){super(),this.enabled=!1,this.sources=[],this.scope=cr.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mw).fromBinary(t,r)}static fromJson(t,r){return(new Mw).fromJson(t,r)}static fromJsonString(t,r){return(new Mw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mw,t,r)}static $(){return["LlmGatewayModelDiscovery|1 enabled 8|2 sources #0*|3 scope #1",$w,cr]}}class Ow extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ow).fromBinary(t,r)}static fromJson(t,r){return(new Ow).fromJson(t,r)}static fromJsonString(t,r){return(new Ow).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ow,t,r)}static $(){return["UpdateTeamLlmGatewayModelDiscoveryRequest|1 team_id 5|2 model_discovery #0",Mw]}}class Dw extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dw).fromBinary(t,r)}static fromJson(t,r){return(new Dw).fromJson(t,r)}static fromJsonString(t,r){return(new Dw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dw,t,r)}static $(){return["UpdateTeamLlmGatewayModelDiscoveryResponse|1 model_discovery #0",Mw]}}class Nw extends T{constructor(t){super(),this.teamId=0,this.endpoints={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nw).fromBinary(t,r)}static fromJson(t,r){return(new Nw).fromJson(t,r)}static fromJsonString(t,r){return(new Nw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nw,t,r)}static $(){return["UpdateTeamLlmGatewayProviderEndpointsRequest|1 team_id 5|2 endpoints 9,9"]}}class Gw extends T{constructor(t){super(),this.endpoints={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gw).fromBinary(t,r)}static fromJson(t,r){return(new Gw).fromJson(t,r)}static fromJsonString(t,r){return(new Gw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gw,t,r)}static $(){return["UpdateTeamLlmGatewayProviderEndpointsResponse|1 endpoints 9,9"]}}class Lw extends T{constructor(t){super(),this.enabled=!1,this.endpoints={},this.outboundModelPrefixes={},this.outboundModelRewrites={},this.audience="",this.canEnable=!1,this.authMode=or.UNSPECIFIED,this.credentialSourceStrategy=ur.UNSPECIFIED,this.routingMode=ar.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lw).fromBinary(t,r)}static fromJson(t,r){return(new Lw).fromJson(t,r)}static fromJsonString(t,r){return(new Lw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Lw,t,r)}static $(){return["LlmGatewaySettings|1 enabled 8|2 endpoints 9,9|9 outbound_model_prefixes 9,9|10 outbound_model_rewrites 9,9|3 audience 9|4 routing #0|5 can_enable 8|6 auth_mode #1|7 team_credential_status #2|8 credential_source_strategy #3|11 model_discovery #4|12 routing_mode #5",Fw,or,bw,ur,Mw,ar]}}class Fw extends T{constructor(t){super(),this.providers={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fw).fromBinary(t,r)}static fromJson(t,r){return(new Fw).fromJson(t,r)}static fromJsonString(t,r){return(new Fw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fw,t,r)}static $(){return["LlmGatewayRouting|1 providers 9,#0",Kw]}}class Kw extends T{constructor(t){super(),this.enabled=!1,this.models={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kw).fromBinary(t,r)}static fromJson(t,r){return(new Kw).fromJson(t,r)}static fromJsonString(t,r){return(new Kw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Kw,t,r)}static $(){return["LlmGatewayRoutingProviderEntry|1 enabled 8|2 models 9,#0",zw]}}class zw extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zw).fromBinary(t,r)}static fromJson(t,r){return(new zw).fromJson(t,r)}static fromJsonString(t,r){return(new zw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zw,t,r)}static $(){return["LlmGatewayRoutedModelEntry|1 enabled 8"]}}class jw extends T{constructor(t){super(),this.issuedAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jw).fromBinary(t,r)}static fromJson(t,r){return(new jw).fromJson(t,r)}static fromJsonString(t,r){return(new jw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jw,t,r)}static $(){return["AutoReviewRunModeReset|1 issued_at_ms 3"]}}class Hw extends T{constructor(t){super(),this.allowedModels=[],this.blockedModels=[],this.dotCursorProtection=!1,this.browserOriginAllowlist=[],this.networkDenylist=[],this.networkAllowlist=[],this.cloudAgentEgressAllowlist=[],this.remotePermissionsFilePaths=[],this.localPermissionsFilePath=[],this.sandGroupAccessMode=lr.UNSPECIFIED,this.memberSlackManagedWorkspaces=[],this.memberSlackManagedWorkspacesUnreadable=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hw).fromBinary(t,r)}static fromJson(t,r){return(new Hw).fromJson(t,r)}static fromJsonString(t,r){return(new Hw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hw,t,r)}static $(){return["GetTeamAdminSettingsResponse|1 allowed_models 9*|2 blocked_models 9*|3 auto_run_controls #0|4 cursor_ignore_controls #1|5 dot_cursor_protection 8|6 allowed_mcp_configuration #2?|7 background_agent_settings #3?|8 cli_settings #4?|9 mcp_controls #5?|10 prompt_deeplink_controls #6?|11 command_deeplink_controls #7?|12 deeplink_controls #8?|13 github_integration_settings #9?|14 slack_integration_settings #10?|15 linear_integration_settings #11?|16 workspace_trust_controls #12?|17 gitlab_integration_settings #13?|18 browser_features 8?|23 browser_origin_allowlist 9*|19 byok_disabled 8?|20 dashboard_analytics_requires_admin 8?|21 shared_conversation_settings #14?|22 allowed_extensions 9?|24 disable_conversation_insights 8?|25 cursor_blame_settings #15?|26 network_denylist 9*|27 network_allowlist 9*|28 extension_signing_settings #16?|29 enforce_invite_domain_on_accept 8?|30 first_party_plugin_configuration #17?|31 attribution_controls #18?|32 allow_third_party_plugin_imports 8?|44 allow_user_local_plugin_imports 8?|33 glass_settings #19?|34 new_chat_model_reset_settings #20?|35 model_allowlist #21?|36 jira_integration_settings #22?|37 pull_request_preferences #23?|38 browser_settings #24?|39 cloud_agent_egress_allowlist 9*|40 mirror_sandbox_allowlist_for_egress 8?|49 auto_review #25|60 local_tool_controls #26?|64 sand_network_controls #27?|61 sand_action_audit_settings #28?|41 remote_permissions_file_path 9?|46 remote_permissions_file_paths 9*|45 local_permissions_file_path 9*|47 permissions_file_overrides_auto_run 8?|42 shared_canvas_settings #29?|43 invite_link_max_ttl_seconds 5?|48 extension_install_cooldown_settings #30?|50 public_profile_settings #31?|51 bitbucket_integration_settings #32?|52 marketplace_leaderboard_disabled 8?|53 new_chat_nudge_all_to_smart_auto 8?|54 models_auto_only 8?|55 new_chat_nudge_all_to_smart_auto_optimize_for 9?|56 restrict_invites_to_admins 8?|57 viewer_can_invite_members 8?|58 enforce_hooks_readiness 8?|59 llm_gateway #33?|62 sand_onboarding #34?|63 origin_disabled 8?|65 user_agent_store_skills_sync_settings #35?|66 auto_review_run_mode_reset #36|67 enterprise_grok_bot_trial_available 8?|68 sand_group_access_mode #37|69 sand_auto_review_controls #38?|71 remote_control_v2_policy #39|72 sand_local_egress_controls #40?|74 projects_settings #41?|75 allow_skills_cli_installs 8?|76 grok_bot_agent_email_controls #42?|77 sand_box_sudo_controls #43?|117 sand_box_vnc_controls #44?|78 sand_box_restart #45?|79 origin_allow_public_repos 8?|80 cloud_agent_group_access_mode #46?|81 allow_unlisted_plugins_and_mcp_servers 8?|82 team_list_enforced 8?|83 grok_bot_secret_forwarding_controls #47?|84 grok_bot_meetings_controls #48?|85 team_list_available 8?|86 grok_bot_pages_sharing_controls #49?|87 grok_bot_bot_messaging_controls #50?|88 member_slack_managed_workspaces #51*|89 member_slack_managed_workspaces_unreadable 8|90 apps_settings #52?|94 grok_bot_team_bot_sharing_controls #53?|91 grok_bot_sharing_admin_controls_available 8?|92 viewer_may_share_team_bots 8?|95 computer_use 8?|96 grok_bot_delegated_auth_controls #54?|97 grok_bot_delegated_auth_controls_available 8?|98 personal_api_key_creation_disabled 8?|99 cloud_agent_mcp_allowlist_applied 8?|100 grok_bot_texting_controls #55?|101 grok_bot_wall_snapshot_controls #56?|102 sand_box_sudo_not_applied_box_count 13?|103 can_control_model_access 8?|104 voice_chat_disabled 8?|105 mcp_allowlist_enabled 8?|106 mcp_servers_surfaces #57?|107 user_mcp_extensions_surfaces #57?|108 organization_network_blocklist #58|109 grok_bot_proactivity_controls #59?|110 off_mcp_server_rules_allowed 8?|111 legacy_model_allowlist #21?|112 cursor_enabled 8?|113 cursor_group_access_mode #60?|114 grok_bot_designated_bot_sharers_available 8?|115 mcp_allowlist_enabled_stored 8?|116 mcp_allowlist_rule_save_turns_on 8?|118 extension_sideload_settings #61?|119 invite_link_join_requires_approval 8?",j_,W_,V_,cJ,_J,yJ,qJ,BJ,IJ,PJ,vJ,TJ,AJ,bJ,$J,DJ,WJ,Y_,XJ,hw,rw,qw,UJ,Z_,wJ,H_,ew,nw,iw,MJ,QJ,OJ,RJ,Lw,ay,FJ,jw,lr,ow,p,cw,NJ,Xw,Qw,Vw,Ww,mr,Yw,Zw,ty,ry,xJ,GJ,ey,ny,sy,oy,Z,tu,iy,fr,VJ]}}class Ww extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ww).fromBinary(t,r)}static fromJson(t,r){return(new Ww).fromJson(t,r)}static fromJsonString(t,r){return(new Ww).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ww,t,r)}static $(){return["SandBoxRestart|1 required_at_ms 3?"]}}class Qw extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qw).fromBinary(t,r)}static fromJson(t,r){return(new Qw).fromJson(t,r)}static fromJsonString(t,r){return(new Qw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qw,t,r)}static $(){return["SandBoxSudoControls|1 disallowed 8?"]}}class Vw extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vw).fromBinary(t,r)}static fromJson(t,r){return(new Vw).fromJson(t,r)}static fromJsonString(t,r){return(new Vw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vw,t,r)}static $(){return["SandBoxVncControls|1 disallowed 8?"]}}class Xw extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xw).fromBinary(t,r)}static fromJson(t,r){return(new Xw).fromJson(t,r)}static fromJsonString(t,r){return(new Xw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xw,t,r)}static $(){return["GrokBotAgentEmailControls|1 allowed 8?"]}}class Yw extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yw).fromBinary(t,r)}static fromJson(t,r){return(new Yw).fromJson(t,r)}static fromJsonString(t,r){return(new Yw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yw,t,r)}static $(){return["GrokBotSecretForwardingControls|1 allowed 8?"]}}class Zw extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zw).fromBinary(t,r)}static fromJson(t,r){return(new Zw).fromJson(t,r)}static fromJsonString(t,r){return(new Zw).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zw,t,r)}static $(){return["GrokBotMeetingsControls|1 allowed 8?"]}}class ty extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ty).fromBinary(t,r)}static fromJson(t,r){return(new ty).fromJson(t,r)}static fromJsonString(t,r){return(new ty).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ty,t,r)}static $(){return["GrokBotPagesSharingControls|1 team_sharing_allowed 8?|2 team_sharing_level #0?",ir]}}class ry extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ry).fromBinary(t,r)}static fromJson(t,r){return(new ry).fromJson(t,r)}static fromJsonString(t,r){return(new ry).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ry,t,r)}static $(){return["GrokBotBotMessagingControls|1 allowed 8?"]}}class ey extends T{constructor(t){super(),this.sharing=sr.UNSPECIFIED,this.designatedSharerUserIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ey).fromBinary(t,r)}static fromJson(t,r){return(new ey).fromJson(t,r)}static fromJsonString(t,r){return(new ey).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ey,t,r)}static $(){return["GrokBotTeamBotSharingControls|1 sharing #0|2 designated_sharer_user_ids 3*",sr]}}class ny extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ny).fromBinary(t,r)}static fromJson(t,r){return(new ny).fromJson(t,r)}static fromJsonString(t,r){return(new ny).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ny,t,r)}static $(){return["GrokBotDelegatedAuthControls|1 allowed 8?"]}}class sy extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sy).fromBinary(t,r)}static fromJson(t,r){return(new sy).fromJson(t,r)}static fromJsonString(t,r){return(new sy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sy,t,r)}static $(){return["GrokBotTextingControls|1 allowed 8?"]}}class iy extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iy).fromBinary(t,r)}static fromJson(t,r){return(new iy).fromJson(t,r)}static fromJsonString(t,r){return(new iy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iy,t,r)}static $(){return["GrokBotProactivityControls|1 allowed 8?"]}}class oy extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oy).fromBinary(t,r)}static fromJson(t,r){return(new oy).fromJson(t,r)}static fromJsonString(t,r){return(new oy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oy,t,r)}static $(){return["GrokBotWallSnapshotControls|1 allowed 8?"]}}class ay extends T{constructor(t){super(),this.completed=!1,this.seen=!1,this.checkedSetupChecklistItems=[],this.skippedSetupChecklistItems=[],this.hasEverCompleted=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ay).fromBinary(t,r)}static fromJson(t,r){return(new ay).fromJson(t,r)}static fromJsonString(t,r){return(new ay).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ay,t,r)}static $(){return["SandOnboardingState|1 completed 8|2 seen 8|3 checked_setup_checklist_items 9*|4 skipped_setup_checklist_items 9*|5 has_ever_completed 8"]}}class uy extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uy).fromBinary(t,r)}static fromJson(t,r){return(new uy).fromJson(t,r)}static fromJsonString(t,r){return(new uy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uy,t,r)}static $(){return["GetBaseTeamAdminSettingsRequest|1 team_id 5"]}}class cy extends T{constructor(t){super(),this.teamId=0,this.allowedModels=[],this.blockedModels=[],this.browserOriginAllowlist=[],this.networkDenylist=[],this.networkAllowlist=[],this.firstPartyWindowDecisionMcids=[],this.cloudAgentEgressAllowlist=[],this.remotePermissionsFilePaths=[],this.localPermissionsFilePath=[],this.sandGroupAccessEnabledGroupIds=[],this.cloudAgentGroupAccessEnabledGroupIds=[],this.cursorGroupAccessEnabledGroupIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cy).fromBinary(t,r)}static fromJson(t,r){return(new cy).fromJson(t,r)}static fromJsonString(t,r){return(new cy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cy,t,r)}static $(){return["UpdateTeamAdminSettingsRequest|1 team_id 5|2 allowed_models 9*|3 blocked_models 9*|4 auto_run_controls #0|5 cursor_ignore_controls #1|6 dot_cursor_protection 8?|7 allowed_mcp_configuration #2?|8 background_agent_settings #3?|9 cli_settings #4?|10 mcp_controls #5?|11 prompt_deeplink_controls #6?|12 command_deeplink_controls #7?|13 deeplink_controls #8?|14 github_integration_settings #9?|15 slack_integration_settings #10?|16 linear_integration_settings #11?|17 workspace_trust_controls #12?|18 gitlab_integration_settings #13?|19 browser_features 8?|24 browser_origin_allowlist 9*|20 byok_disabled 8?|21 dashboard_analytics_requires_admin 8?|22 shared_conversation_settings #14?|23 allowed_extensions 9?|25 disable_conversation_insights 8?|26 cursor_blame_settings #15?|27 network_denylist 9*|28 network_allowlist 9*|29 extension_signing_settings #16?|30 enforce_invite_domain_on_accept 8?|31 first_party_plugin_configuration #17?|32 attribution_controls #18?|33 allow_third_party_plugin_imports 8?|44 allow_user_local_plugin_imports 8?|34 glass_settings #19?|59 local_tool_controls #20?|60 sand_action_audit_settings #21?|35 new_chat_model_reset_settings #22?|36 model_allowlist #23?|76 first_party_window_decision_mcids 9*|37 jira_integration_settings #24?|38 pull_request_preferences #25?|39 browser_settings #26?|40 cloud_agent_egress_allowlist 9*|41 mirror_sandbox_allowlist_for_egress 8?|88 update_cloud_agent_egress_allowlist 8?|89 update_legacy_model_lists 8?|90 update_browser_origin_allowlist 8?|91 update_network_lists 8?|49 auto_review #27|42 remote_permissions_file_path 9?|46 remote_permissions_file_paths 9*|45 local_permissions_file_path 9*|47 permissions_file_overrides_auto_run 8?|57 update_permissions_file_paths 8?|43 shared_canvas_settings #28?|48 extension_install_cooldown_settings #29?|50 public_profile_settings #30?|51 bitbucket_integration_settings #31?|52 marketplace_leaderboard_disabled 8?|53 new_chat_nudge_all_to_smart_auto 8?|54 models_auto_only 8?|55 new_chat_nudge_all_to_smart_auto_optimize_for 9?|56 enforce_hooks_readiness 8?|58 llm_gateway #32?|63 origin_disabled 8?|64 user_agent_store_skills_sync_settings #33?|65 sand_group_access_mode #34?|66 sand_group_access_enabled_group_ids 3*|67 update_sand_group_access_groups 8?|69 sand_auto_review_controls #35?|74 projects_settings #36?|75 allow_skills_cli_installs 8?|79 cloud_agent_group_access_mode #37?|80 cloud_agent_group_access_enabled_group_ids 3*|81 update_cloud_agent_group_access_groups 8?|82 allow_unlisted_plugins_and_mcp_servers 8?|83 apps_settings #38?|84 computer_use 8?|85 mcp_allowlist_enabled 8?|86 mcp_servers_surfaces #39?|87 user_mcp_extensions_surfaces #39?|92 saves_both_mcp_rule_lists 8?|93 cursor_enabled 8?|94 cursor_group_access_mode #40?|95 cursor_group_access_enabled_group_ids 3*|96 update_cursor_group_access_groups 8?|97 extension_sideload_settings #41?",j_,W_,V_,cJ,_J,yJ,qJ,BJ,IJ,PJ,vJ,TJ,AJ,bJ,$J,DJ,WJ,Y_,XJ,hw,ew,iw,rw,qw,UJ,Z_,wJ,H_,MJ,QJ,OJ,RJ,Lw,FJ,lr,ow,NJ,mr,GJ,Z,fr,VJ]}}class ly extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ly).fromBinary(t,r)}static fromJson(t,r){return(new ly).fromJson(t,r)}static fromJsonString(t,r){return(new ly).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ly,t,r)}static $(){return["UpdateTeamAdminSettingsResponse"]}}class my extends T{constructor(t){super(),this.teamId=0,this.inviteLinkMaxTtlSeconds=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new my).fromBinary(t,r)}static fromJson(t,r){return(new my).fromJson(t,r)}static fromJsonString(t,r){return(new my).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(my,t,r)}static $(){return["UpdateTeamInviteLinkTTLSettingRequest|1 team_id 5|2 invite_link_max_ttl_seconds 5"]}}class fy extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fy).fromBinary(t,r)}static fromJson(t,r){return(new fy).fromJson(t,r)}static fromJsonString(t,r){return(new fy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fy,t,r)}static $(){return["UpdateTeamInviteLinkTTLSettingResponse"]}}class dy extends T{constructor(t){super(),this.teamId=0,this.restrictInvitesToAdmins=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dy).fromBinary(t,r)}static fromJson(t,r){return(new dy).fromJson(t,r)}static fromJsonString(t,r){return(new dy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dy,t,r)}static $(){return["UpdateTeamMemberInviteSettingRequest|1 team_id 5|2 restrict_invites_to_admins 8"]}}class py extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new py).fromBinary(t,r)}static fromJson(t,r){return(new py).fromJson(t,r)}static fromJsonString(t,r){return(new py).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(py,t,r)}static $(){return["UpdateTeamMemberInviteSettingResponse"]}}class hy extends T{constructor(t){super(),this.teamId=0,this.personalApiKeyCreationDisabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hy).fromBinary(t,r)}static fromJson(t,r){return(new hy).fromJson(t,r)}static fromJsonString(t,r){return(new hy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hy,t,r)}static $(){return["UpdateTeamPersonalApiKeyCreationSettingRequest|1 team_id 5|2 personal_api_key_creation_disabled 8"]}}class gy extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gy).fromBinary(t,r)}static fromJson(t,r){return(new gy).fromJson(t,r)}static fromJsonString(t,r){return(new gy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gy,t,r)}static $(){return["UpdateTeamPersonalApiKeyCreationSettingResponse"]}}class _y extends T{constructor(t){super(),this.teamId=0,this.voiceChatDisabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _y).fromBinary(t,r)}static fromJson(t,r){return(new _y).fromJson(t,r)}static fromJsonString(t,r){return(new _y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_y,t,r)}static $(){return["UpdateTeamVoiceChatSettingRequest|1 team_id 5|2 voice_chat_disabled 8"]}}class Jy extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jy).fromBinary(t,r)}static fromJson(t,r){return(new Jy).fromJson(t,r)}static fromJsonString(t,r){return(new Jy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jy,t,r)}static $(){return["UpdateTeamVoiceChatSettingResponse"]}}class wy extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wy).fromBinary(t,r)}static fromJson(t,r){return(new wy).fromJson(t,r)}static fromJsonString(t,r){return(new wy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wy,t,r)}static $(){return["UpdateTeamDefaultMemberBillingTierRequest|1 team_id 5|2 billing_tier #0?",ot]}}class yy extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yy).fromBinary(t,r)}static fromJson(t,r){return(new yy).fromJson(t,r)}static fromJsonString(t,r){return(new yy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yy,t,r)}static $(){return["UpdateTeamDefaultMemberBillingTierResponse"]}}class Sy extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sy).fromBinary(t,r)}static fromJson(t,r){return(new Sy).fromJson(t,r)}static fromJsonString(t,r){return(new Sy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sy,t,r)}static $(){return["CreateTeamFreeTrialCodeRequest|1 trial_type #0?|2 code_purpose #1?|3 mint_actor 9?",dr,pr]}}class qy extends T{constructor(t){super(),this.code="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qy).fromBinary(t,r)}static fromJson(t,r){return(new qy).fromJson(t,r)}static fromJsonString(t,r){return(new qy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qy,t,r)}static $(){return["CreateTeamFreeTrialCodeResponse|1 code 9"]}}class By extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new By).fromBinary(t,r)}static fromJson(t,r){return(new By).fromJson(t,r)}static fromJsonString(t,r){return(new By).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(By,t,r)}static $(){return["SetTrialSpendLimitOverrideInternalRequest|1 team_id 5|2 override_dollars 5?|3 clear 8?|4 changed_by 9?"]}}class Iy extends T{constructor(t){super(),this.teamId=0,this.effectiveLimitDollars=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Iy).fromBinary(t,r)}static fromJson(t,r){return(new Iy).fromJson(t,r)}static fromJsonString(t,r){return(new Iy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Iy,t,r)}static $(){return["SetTrialSpendLimitOverrideInternalResponse|1 team_id 5|2 override_dollars 5?|3 effective_limit_dollars 5"]}}class Py extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Py).fromBinary(t,r)}static fromJson(t,r){return(new Py).fromJson(t,r)}static fromJsonString(t,r){return(new Py).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Py,t,r)}static $(){return["GetTrialSpendLimitInternalRequest|1 team_id 5"]}}class by extends T{constructor(t){super(),this.teamId=0,this.isTokenBasedContractTrial=!1,this.defaultLimitDollars=0,this.effectiveLimitDollars=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new by).fromBinary(t,r)}static fromJson(t,r){return(new by).fromJson(t,r)}static fromJsonString(t,r){return(new by).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(by,t,r)}static $(){return["GetTrialSpendLimitInternalResponse|1 team_id 5|2 is_token_based_contract_trial 8|3 override_dollars 5?|4 default_limit_dollars 5|5 effective_limit_dollars 5|6 membership_start_ms 3?|7 membership_expiration_ms 3?"]}}class Ry extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ry).fromBinary(t,r)}static fromJson(t,r){return(new Ry).fromJson(t,r)}static fromJsonString(t,r){return(new Ry).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ry,t,r)}static $(){return["GetOrganizationEnterpriseTrialExtendContextInternalRequest|1 team_id 5"]}}class vy extends T{constructor(t){super(),this.teamId=0,this.membershipType="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vy).fromBinary(t,r)}static fromJson(t,r){return(new vy).fromJson(t,r)}static fromJsonString(t,r){return(new vy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vy,t,r)}static $(){return["OrganizationEnterpriseTrialTeam|1 team_id 5|2 membership_type 9|3 membership_expiration_ms 3?|4 subscription_status 9?|5 customer_id 9?"]}}class xy extends T{constructor(t){super(),this.teamId=0,this.teams=[],this.convertSelfServeEnabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xy).fromBinary(t,r)}static fromJson(t,r){return(new xy).fromJson(t,r)}static fromJsonString(t,r){return(new xy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xy,t,r)}static $(){return["GetOrganizationEnterpriseTrialExtendContextInternalResponse|1 team_id 5|2 organization_id 3?|3 organization_name 9?|4 enterprise_trial_end_ms 3?|5 teams #0*|6 convert_self_serve_enabled 8",vy]}}class ky extends T{constructor(t){super(),this.teamId=0,this.enterpriseTrialEndMs=n.protoInt64.zero,this.denormTeamIds=[],this.convertTeamIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ky).fromBinary(t,r)}static fromJson(t,r){return(new ky).fromJson(t,r)}static fromJsonString(t,r){return(new ky).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ky,t,r)}static $(){return["ApplyOrganizationEnterpriseTrialEndInternalRequest|1 team_id 5|2 enterprise_trial_end_ms 3|3 changed_by 9?|4 denorm_team_ids 5*|5 convert_team_ids 5*|6 convert_membership_type 9?"]}}class Ey extends T{constructor(t){super(),this.teamId=0,this.membershipType="",this.outcome="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ey).fromBinary(t,r)}static fromJson(t,r){return(new Ey).fromJson(t,r)}static fromJsonString(t,r){return(new Ey).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ey,t,r)}static $(){return["OrganizationEnterpriseTrialTeamApplyResult|1 team_id 5|2 membership_type 9|3 outcome 9|4 previous_expiration_ms 3?|5 membership_expiration_ms 3?"]}}class Cy extends T{constructor(t){super(),this.organizationId=n.protoInt64.zero,this.enterpriseTrialEndMs=n.protoInt64.zero,this.teams=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cy).fromBinary(t,r)}static fromJson(t,r){return(new Cy).fromJson(t,r)}static fromJsonString(t,r){return(new Cy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cy,t,r)}static $(){return["ApplyOrganizationEnterpriseTrialEndInternalResponse|1 organization_id 3|2 enterprise_trial_end_ms 3|3 teams #0*",Ey]}}class Ty extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ty).fromBinary(t,r)}static fromJson(t,r){return(new Ty).fromJson(t,r)}static fromJsonString(t,r){return(new Ty).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ty,t,r)}static $(){return["GetXaiUserUsageSnapshotRequest|1 xai_team_id 9?"]}}class Uy extends T{constructor(t){super(),this.product="",this.usagePercent=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Uy).fromBinary(t,r)}static fromJson(t,r){return(new Uy).fromJson(t,r)}static fromJsonString(t,r){return(new Uy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Uy,t,r)}static $(){return["XaiUsageProductShare|1 product 9|2 usage_percent 1"]}}class Ay extends T{constructor(t){super(),this.productUsage=[],this.prepaidBalanceWithheld=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ay).fromBinary(t,r)}static fromJson(t,r){return(new Ay).fromJson(t,r)}static fromJsonString(t,r){return(new Ay).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ay,t,r)}static $(){return["GetXaiUserUsageSnapshotResponse|1 current_period_start_ms 3?|2 current_period_end_ms 3?|3 usage_percent 1?|4 product_usage #0*|5 prepaid_balance_cents 3?|6 prepaid_balance_withheld 8",Uy]}}class $y extends T{constructor(t){super(),this.teamId=0,this.addDelayDays=0,this.hideAllNudges=!1,this.hideNonAdminNudges=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $y).fromBinary(t,r)}static fromJson(t,r){return(new $y).fromJson(t,r)}static fromJsonString(t,r){return(new $y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($y,t,r)}static $(){return["TeamOffboardingConfigInternal|1 team_id 5|2 add_delay_days 5|3 hide_all_nudges 8|4 hide_non_admin_nudges 8"]}}class My extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new My).fromBinary(t,r)}static fromJson(t,r){return(new My).fromJson(t,r)}static fromJsonString(t,r){return(new My).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(My,t,r)}static $(){return["GetTeamOffboardingConfigInternalRequest|1 team_id 5"]}}class Oy extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Oy).fromBinary(t,r)}static fromJson(t,r){return(new Oy).fromJson(t,r)}static fromJsonString(t,r){return(new Oy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Oy,t,r)}static $(){return["GetTeamOffboardingConfigInternalResponse|1 config #0",$y]}}class Dy extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dy).fromBinary(t,r)}static fromJson(t,r){return(new Dy).fromJson(t,r)}static fromJsonString(t,r){return(new Dy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dy,t,r)}static $(){return["UpdateTeamOffboardingConfigInternalRequest|1 team_id 5|2 add_delay_days 5?|3 hide_all_nudges 8?|4 hide_non_admin_nudges 8?|5 changed_by 9?"]}}class Ny extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ny).fromBinary(t,r)}static fromJson(t,r){return(new Ny).fromJson(t,r)}static fromJsonString(t,r){return(new Ny).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ny,t,r)}static $(){return["UpdateTeamOffboardingConfigInternalResponse|1 config #0",$y]}}class Gy extends T{constructor(t){super(),this.teamId=0,this.amountCents=n.protoInt64.zero,this.expiresAtMs=n.protoInt64.zero,this.allowedModelIds=[],this.subscriptionProductId="",this.applicableProducts=[],this.entitlements=[],this.ownership=hr.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gy).fromBinary(t,r)}static fromJson(t,r){return(new Gy).fromJson(t,r)}static fromJsonString(t,r){return(new Gy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gy,t,r)}static $(){return["CreateTeamCreditGrantInternalRequest|1 team_id 5|2 amount_cents 3|3 expires_at_ms 3|4 starts_at_ms 3?|5 allowed_model_ids 9*|6 subscription_product_id 9|7 applicable_products 9*|8 show_in_client 8?|9 created_by 9?|10 entitlements 9*|11 ownership #0",hr]}}class Ly extends T{constructor(t){super(),this.grantId="",this.teamId=0,this.totalCents=n.protoInt64.zero,this.usedCents=n.protoInt64.zero,this.expiresAtMs=n.protoInt64.zero,this.allowedModelIds=[],this.subscriptionProductId="",this.applicableProducts=[],this.showInClient=!1,this.priority=0,this.createdAtMs=n.protoInt64.zero,this.entitlements=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ly).fromBinary(t,r)}static fromJson(t,r){return(new Ly).fromJson(t,r)}static fromJsonString(t,r){return(new Ly).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ly,t,r)}static $(){return["TeamCreditGrantInternal|1 grant_id 9|2 team_id 5|3 total_cents 3|4 used_cents 3|5 starts_at_ms 3?|6 expires_at_ms 3|7 allowed_model_ids 9*|8 subscription_product_id 9|9 applicable_products 9*|10 show_in_client 8|11 priority 5|12 created_at_ms 3|13 source_type 9?|14 organization_id 9?|15 entitlements 9*"]}}class Fy extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fy).fromBinary(t,r)}static fromJson(t,r){return(new Fy).fromJson(t,r)}static fromJsonString(t,r){return(new Fy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fy,t,r)}static $(){return["CreateTeamCreditGrantInternalResponse|1 grant #0",Ly]}}class Ky extends T{constructor(t){super(),this.teamId=0,this.includeExpired=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ky).fromBinary(t,r)}static fromJson(t,r){return(new Ky).fromJson(t,r)}static fromJsonString(t,r){return(new Ky).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ky,t,r)}static $(){return["ListTeamCreditGrantsInternalRequest|1 team_id 5|2 include_expired 8"]}}class zy extends T{constructor(t){super(),this.grants=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zy).fromBinary(t,r)}static fromJson(t,r){return(new zy).fromJson(t,r)}static fromJsonString(t,r){return(new zy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zy,t,r)}static $(){return["ListTeamCreditGrantsInternalResponse|1 grants #0*",Ly]}}class jy extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jy).fromBinary(t,r)}static fromJson(t,r){return(new jy).fromJson(t,r)}static fromJsonString(t,r){return(new jy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jy,t,r)}static $(){return["CreateTeamsTrialV2ReferralCodeRequest"]}}class Hy extends T{constructor(t){super(),this.code="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hy).fromBinary(t,r)}static fromJson(t,r){return(new Hy).fromJson(t,r)}static fromJsonString(t,r){return(new Hy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hy,t,r)}static $(){return["CreateTeamsTrialV2ReferralCodeResponse|1 code 9"]}}class Wy extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wy).fromBinary(t,r)}static fromJson(t,r){return(new Wy).fromJson(t,r)}static fromJsonString(t,r){return(new Wy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wy,t,r)}static $(){return["GetTeamAnalyticsRequest|1 team_id 5|2 start_date 3?|3 end_date 3?|4 version 9?"]}}class Qy extends T{constructor(t){super(),this.dailyMetrics=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qy).fromBinary(t,r)}static fromJson(t,r){return(new Qy).fromJson(t,r)}static fromJsonString(t,r){return(new Qy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qy,t,r)}static $(){return["GetTeamAnalyticsResponse|1 daily_metrics #0*|2 period #1|3 active_users #2",nS,eS,rS]}}class Vy extends T{constructor(t){super(),this.teamId=0,this.userId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vy).fromBinary(t,r)}static fromJson(t,r){return(new Vy).fromJson(t,r)}static fromJsonString(t,r){return(new Vy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vy,t,r)}static $(){return["GetUserAnalyticsRequest|1 team_id 5|2 user_id 5|3 start_date 3?|4 end_date 3?|5 version 9?|6 daily_metrics_only 8?"]}}class Xy extends T{constructor(t){super(),this.dailyMetrics=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xy).fromBinary(t,r)}static fromJson(t,r){return(new Xy).fromJson(t,r)}static fromJsonString(t,r){return(new Xy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xy,t,r)}static $(){return["GetUserAnalyticsResponse|1 daily_metrics #0*|2 period #1|3 apply_lines_rank 5?|4 tabs_accepted_rank 5?|5 total_team_members 5?|6 total_apply_lines 5?|7 team_average_apply_lines 5?|8 total_tabs_accepted 5?|9 team_average_tabs_accepted 5?|10 total_members_in_team 5?",nS,eS]}}class Yy extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yy).fromBinary(t,r)}static fromJson(t,r){return(new Yy).fromJson(t,r)}static fromJsonString(t,r){return(new Yy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yy,t,r)}static $(){return["GetTeamRawDataRequest|1 team_id 5|2 start_date 3?|3 end_date 3?|4 version 9?"]}}class Zy extends T{constructor(t){super(),this.data=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zy).fromBinary(t,r)}static fromJson(t,r){return(new Zy).fromJson(t,r)}static fromJsonString(t,r){return(new Zy).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zy,t,r)}static $(){return["GetTeamRawDataResponse|1 data #0*|2 period #1",tS,eS]}}class tS extends T{constructor(t){super(),this.date=n.protoInt64.zero,this.userId=0,this.isActive=!1,this.totalLinesAdded=0,this.totalLinesDeleted=0,this.acceptedLinesAdded=0,this.acceptedLinesDeleted=0,this.totalApplies=0,this.totalAccepts=0,this.totalRejects=0,this.totalTabsShown=0,this.totalTabsAccepted=0,this.composerRequests=0,this.chatRequests=0,this.agentRequests=0,this.cmdkUsages=0,this.subscriptionIncludedReqs=0,this.apiKeyReqs=0,this.usageBasedReqs=0,this.bugbotUsages=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tS).fromBinary(t,r)}static fromJson(t,r){return(new tS).fromJson(t,r)}static fromJsonString(t,r){return(new tS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tS,t,r)}static $(){return["RawUserData|1 date 3|2 user_id 5|3 is_active 8|4 total_lines_added 5|5 total_lines_deleted 5|6 accepted_lines_added 5|7 accepted_lines_deleted 5|8 total_applies 5|9 total_accepts 5|10 total_rejects 5|11 total_tabs_shown 5|12 total_tabs_accepted 5|13 composer_requests 5|14 chat_requests 5|15 agent_requests 5|16 cmdk_usages 5|17 subscription_included_reqs 5|18 api_key_reqs 5|19 usage_based_reqs 5|20 bugbot_usages 5|21 most_used_model 9?|22 apply_most_used_extension 9?|23 tab_most_used_extension 9?|24 client_version 9?|25 email 9?"]}}class rS extends T{constructor(t){super(),this.current=0,this.previous=0,this.percentChange=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rS).fromBinary(t,r)}static fromJson(t,r){return(new rS).fromJson(t,r)}static fromJsonString(t,r){return(new rS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rS,t,r)}static $(){return["ActiveUsers|1 current 5|2 previous 5|3 percent_change 5"]}}class eS extends T{constructor(t){super(),this.startDate=n.protoInt64.zero,this.endDate=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eS).fromBinary(t,r)}static fromJson(t,r){return(new eS).fromJson(t,r)}static fromJsonString(t,r){return(new eS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eS,t,r)}static $(){return["AnalyticsPeriod|1 start_date 3|2 end_date 3"]}}class nS extends T{constructor(t){super(),this.date=n.protoInt64.zero,this.activeUsers=0,this.linesAdded=0,this.linesDeleted=0,this.acceptedLinesAdded=0,this.acceptedLinesDeleted=0,this.totalApplies=0,this.totalAccepts=0,this.totalRejects=0,this.totalTabsShown=0,this.totalTabsAccepted=0,this.composerRequests=0,this.chatRequests=0,this.agentRequests=0,this.cmdkUsages=0,this.subscriptionIncludedReqs=0,this.apiKeyReqs=0,this.usageBasedReqs=0,this.bugbotUsages=0,this.modelUsage=[],this.extensionUsage=[],this.tabExtensionUsage=[],this.clientVersionUsage=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nS).fromBinary(t,r)}static fromJson(t,r){return(new nS).fromJson(t,r)}static fromJsonString(t,r){return(new nS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nS,t,r)}static $(){return["DailyMetrics|1 date 3|2 active_users 5|3 lines_added 5|4 lines_deleted 5|5 accepted_lines_added 5|6 accepted_lines_deleted 5|7 total_applies 5|8 total_accepts 5|9 total_rejects 5|10 total_tabs_shown 5|11 total_tabs_accepted 5|12 composer_requests 5|13 chat_requests 5|14 agent_requests 5|15 cmdk_usages 5|16 subscription_included_reqs 5|17 api_key_reqs 5|18 usage_based_reqs 5|19 bugbot_usages 5|20 model_usage #0*|21 extension_usage #0*|22 tab_extension_usage #0*|23 client_version_usage #0*",sS]}}class sS extends T{constructor(t){super(),this.name="",this.count=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sS).fromBinary(t,r)}static fromJson(t,r){return(new sS).fromJson(t,r)}static fromJsonString(t,r){return(new sS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sS,t,r)}static $(){return["StringCount|1 name 9|2 count 5"]}}class iS extends T{constructor(t){super(),this.teamId=0,this.teamRepoType="",this.repoId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iS).fromBinary(t,r)}static fromJson(t,r){return(new iS).fromJson(t,r)}static fromJsonString(t,r){return(new iS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iS,t,r)}static $(){return["SetTeamRepoTypeRequest|1 team_id 5|2 team_repo_type 9|3 repo_id 5"]}}class oS extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oS).fromBinary(t,r)}static fromJson(t,r){return(new oS).fromJson(t,r)}static fromJsonString(t,r){return(new oS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oS,t,r)}static $(){return["SetTeamRepoTypeResponse"]}}class aS extends T{constructor(t){super(),this.conversationId="",this.timestampBeforeRequest=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aS).fromBinary(t,r)}static fromJson(t,r){return(new aS).fromJson(t,r)}static fromJsonString(t,r){return(new aS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aS,t,r)}static $(){return["GetClientUsageDataRequest|1 conversation_id 9|2 timestamp_before_request 5"]}}class uS extends T{constructor(t){super(),this.itemsWithCost=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uS).fromBinary(t,r)}static fromJson(t,r){return(new uS).fromJson(t,r)}static fromJsonString(t,r){return(new uS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uS,t,r)}static $(){return["GetClientUsageDataResponse|1 items_with_cost #0*",cS]}}class cS extends T{constructor(t){super(),this.name="",this.costInCents=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cS).fromBinary(t,r)}static fromJson(t,r){return(new cS).fromJson(t,r)}static fromJsonString(t,r){return(new cS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cS,t,r)}static $(){return["GetClientUsageDataResponse.NameToCost|1 name 9|2 cost_in_cents 5"]}}class lS extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lS).fromBinary(t,r)}static fromJson(t,r){return(new lS).fromJson(t,r)}static fromJsonString(t,r){return(new lS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lS,t,r)}static $(){return["GetCurrentPeriodUsageRequest|1 team_id 5?|2 include_pooled_usage 8?|3 personal_scope 8?"]}}class mS extends T{constructor(t){super(),this.billingCycleStart=n.protoInt64.zero,this.billingCycleEnd=n.protoInt64.zero,this.enabled=!1,this.displayMessage="",this.autoBucketModels=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mS).fromBinary(t,r)}static fromJson(t,r){return(new mS).fromJson(t,r)}static fromJsonString(t,r){return(new mS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mS,t,r)}static $(){return["GetCurrentPeriodUsageResponse|1 billing_cycle_start 3|2 billing_cycle_end 3|3 plan_usage #0|4 spend_limit_usage #1|5 display_threshold 5?|6 enabled 8|7 display_message 9|8 free_best_of_n_promotion #2?|11 auto_model_selected_display_message 9?|12 named_model_selected_display_message 9?|13 auto_bucket_models 9*",fS,dS,pS]}}class fS extends T{constructor(t){super(),this.totalSpend=0,this.includedSpend=0,this.bonusSpend=0,this.remaining=0,this.limit=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fS).fromBinary(t,r)}static fromJson(t,r){return(new fS).fromJson(t,r)}static fromJsonString(t,r){return(new fS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fS,t,r)}static $(){return["GetCurrentPeriodUsageResponse.PlanUsage|1 total_spend 5|2 included_spend 5|3 bonus_spend 5|4 remaining 5|5 limit 5|6 remaining_bonus 8?|7 bonus_tooltip 9?|8 auto_spend 5?|9 api_spend 5?|10 auto_limit 5?|11 api_limit 5?|12 auto_percent_used 1?|13 api_percent_used 1?|14 total_percent_used 1?"]}}class dS extends T{constructor(t){super(),this.totalSpend=0,this.individualUsed=0,this.individualRemaining=0,this.limitType="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dS).fromBinary(t,r)}static fromJson(t,r){return(new dS).fromJson(t,r)}static fromJsonString(t,r){return(new dS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dS,t,r)}static $(){return["GetCurrentPeriodUsageResponse.SpendLimitUsage|1 total_spend 5|2 pooled_limit 3?|3 pooled_used 5?|4 pooled_remaining 3?|5 individual_limit 5?|6 individual_used 5|7 individual_remaining 5|8 limit_type 9|9 overall_limit 5?|10 overall_used 5?|11 overall_remaining 5?"]}}class pS extends T{constructor(t){super(),this.trialsUsed=0,this.trialsRemaining=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pS).fromBinary(t,r)}static fromJson(t,r){return(new pS).fromJson(t,r)}static fromJsonString(t,r){return(new pS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pS,t,r)}static $(){return["GetCurrentPeriodUsageResponse.FreeBestOfNPromotion|1 trials_used 5|2 trials_remaining 5"]}}class hS extends T{constructor(t){super(),this.id="",this.kind=gr.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hS).fromBinary(t,r)}static fromJson(t,r){return(new hS).fromJson(t,r)}static fromJsonString(t,r){return(new hS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hS,t,r)}static $(){return["UnifiedBankedUsageReset|1 id 9|2 created_at #0|3 expires_at #0?|4 kind #1",n.Timestamp,gr]}}class gS extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gS).fromBinary(t,r)}static fromJson(t,r){return(new gS).fromJson(t,r)}static fromJsonString(t,r){return(new gS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gS,t,r)}static $(){return["ListUnifiedBankedUsageResetsRequest"]}}class _S extends T{constructor(t){super(),this.resets=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _S).fromBinary(t,r)}static fromJson(t,r){return(new _S).fromJson(t,r)}static fromJsonString(t,r){return(new _S).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_S,t,r)}static $(){return["ListUnifiedBankedUsageResetsResponse|1 resets #0*|2 next_redeem_allowed_at #1?|3 next_team_redeem_allowed_at #1?|4 next_user_redeem_allowed_at #1?",hS,n.Timestamp]}}class JS extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new JS).fromBinary(t,r)}static fromJson(t,r){return(new JS).fromJson(t,r)}static fromJsonString(t,r){return(new JS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(JS,t,r)}static $(){return["RedeemUnifiedBankedUsageResetRequest"]}}class wS extends T{constructor(t){super(),this.remaining=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wS).fromBinary(t,r)}static fromJson(t,r){return(new wS).fromJson(t,r)}static fromJsonString(t,r){return(new wS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wS,t,r)}static $(){return["RedeemUnifiedBankedUsageResetResponse|1 redeemed #0|2 redeemed_at #1|3 next_redeem_allowed_at #1|4 remaining #0*",hS,n.Timestamp]}}class yS extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yS).fromBinary(t,r)}static fromJson(t,r){return(new yS).fromJson(t,r)}static fromJsonString(t,r){return(new yS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yS,t,r)}static $(){return["ListPendingUserAccessRequestsRequest|1 team_id 5"]}}class SS extends T{constructor(t){super(),this.id=n.protoInt64.zero,this.kind=_r.UNSPECIFIED,this.requesterUserId=0,this.requesterName="",this.requesterEmail="",this.summary="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new SS).fromBinary(t,r)}static fromJson(t,r){return(new SS).fromJson(t,r)}static fromJsonString(t,r){return(new SS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(SS,t,r)}static $(){return["PendingUserAccessRequest|1 id 3|2 kind #0|3 requester_user_id 5|4 requester_name 9|5 requester_email 9|6 requested_at #1|7 summary 9",_r,n.Timestamp]}}class qS extends T{constructor(t){super(),this.requests=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qS).fromBinary(t,r)}static fromJson(t,r){return(new qS).fromJson(t,r)}static fromJsonString(t,r){return(new qS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qS,t,r)}static $(){return["ListPendingUserAccessRequestsResponse|1 requests #0*",SS]}}class BS extends T{constructor(t){super(),this.refresh=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new BS).fromBinary(t,r)}static fromJson(t,r){return(new BS).fromJson(t,r)}static fromJsonString(t,r){return(new BS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(BS,t,r)}static $(){return["GetBonfireStatusRequest|1 refresh 8"]}}class IS extends T{constructor(t){super(),this.eligible=!1,this.inviteUrl="",this.inviteCode="",this.pendingRewardCount=0,this.availableResetCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new IS).fromBinary(t,r)}static fromJson(t,r){return(new IS).fromJson(t,r)}static fromJsonString(t,r){return(new IS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(IS,t,r)}static $(){return["GetBonfireStatusResponse|1 eligible 8|2 invite_url 9|3 invite_code 9|4 pending_reward_count 5|5 available_reset_count 5"]}}class PS extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new PS).fromBinary(t,r)}static fromJson(t,r){return(new PS).fromJson(t,r)}static fromJsonString(t,r){return(new PS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(PS,t,r)}static $(){return["CreateBonfireInviteRequest"]}}class bS extends T{constructor(t){super(),this.inviteUrl="",this.inviteCode="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bS).fromBinary(t,r)}static fromJson(t,r){return(new bS).fromJson(t,r)}static fromJsonString(t,r){return(new bS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bS,t,r)}static $(){return["CreateBonfireInviteResponse|1 invite_url 9|2 invite_code 9"]}}class RS extends T{constructor(t){super(),this.inviteeEmail="",this.idempotencyKey="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new RS).fromBinary(t,r)}static fromJson(t,r){return(new RS).fromJson(t,r)}static fromJsonString(t,r){return(new RS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(RS,t,r)}static $(){return["SendBonfireInviteRequest|1 invitee_email 9|2 idempotency_key 9"]}}class vS extends T{constructor(t){super(),this.outcome=xS.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vS).fromBinary(t,r)}static fromJson(t,r){return(new vS).fromJson(t,r)}static fromJsonString(t,r){return(new vS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vS,t,r)}static $(){return["SendBonfireInviteResponse|1 outcome #0|2 retry_after #1?",xS,n.Timestamp]}}var xS=(0,a.QT)(n.proto3,C,"SendBonfireInviteResponse.Outcome",[[0,"UNSPECIFIED"],[1,"SENT"],[2,"RATE_LIMITED"],[3,"NOT_ELIGIBLE"],[4,"INVALID_EMAIL"],[5,"UNAVAILABLE"],[6,"SELF_INVITE"],[7,"UNCONFIRMED"]],1);class kS extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kS).fromBinary(t,r)}static fromJson(t,r){return(new kS).fromJson(t,r)}static fromJsonString(t,r){return(new kS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kS,t,r)}static $(){return["GetPlanInfoRequest"]}}class ES extends T{constructor(t){super(),this.isMerged=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ES).fromBinary(t,r)}static fromJson(t,r){return(new ES).fromJson(t,r)}static fromJsonString(t,r){return(new ES).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ES,t,r)}static $(){return["GetPlanInfoResponse|1 plan_info #0?|2 next_upgrade #1?|3 is_merged 8",TS,$S]}}var CS=(0,a.QT)(n.proto3,C,"GetPlanInfoResponse.IncludedUsagePeriod",[[0,"UNSPECIFIED"],[1,"MONTHLY"],[2,"WEEKLY"]],1);class TS extends T{constructor(t){super(),this.planName="",this.includedAmountCents=0,this.planOwner=US.UNSPECIFIED,this.includedUsagePeriod=CS.UNSPECIFIED,this.standing=AS.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new TS).fromBinary(t,r)}static fromJson(t,r){return(new TS).fromJson(t,r)}static fromJsonString(t,r){return(new TS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(TS,t,r)}static $(){return["GetPlanInfoResponse.PlanInfo|1 plan_name 9|2 included_amount_cents 5|3 price 9?|4 billing_cycle_end 3?|5 plan_owner #0|6 included_usage_period #1|7 included_usage_resets_at 3?|8 cancels_at 3?|9 trial_ends_at 3?|10 grok_bot_trial_ends_at 3?|11 standing #2|12 renews_at 3?|13 restore_by 3?",US,CS,AS]}}var US=(0,a.QT)(n.proto3,C,"GetPlanInfoResponse.PlanInfo.PlanOwner",[[0,"UNSPECIFIED"],[1,"STRIPE"],[2,"APPLE"]],1),AS=(0,a.QT)(n.proto3,C,"GetPlanInfoResponse.PlanInfo.Standing",[[0,"UNSPECIFIED"],[1,"PAST_DUE"],[2,"GRACE"],[3,"EXPIRING"],[4,"CANCELED"],[5,"CANCELED_IN_TRIAL"]],1);class $S extends T{constructor(t){super(),this.tier="",this.name="",this.includedAmountCents=0,this.price="",this.description="",this.includedUsagePeriod=CS.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $S).fromBinary(t,r)}static fromJson(t,r){return(new $S).fromJson(t,r)}static fromJsonString(t,r){return(new $S).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($S,t,r)}static $(){return["GetPlanInfoResponse.NextUpgrade|1 tier 9|2 name 9|3 included_amount_cents 5|4 price 9|5 description 9|6 dashboard_action #0?|7 included_usage_period #1",o.bV,CS]}}class MS extends T{constructor(t){super(),this.signedTransactionJws="",this.productId="",this.appAccountToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new MS).fromBinary(t,r)}static fromJson(t,r){return(new MS).fromJson(t,r)}static fromJsonString(t,r){return(new MS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(MS,t,r)}static $(){return["VerifyAppleTransactionRequest|1 signed_transaction_jws 9|2 product_id 9|3 app_account_token 9|4 verification_provenance #0?",Jr]}}class OS extends T{constructor(t){super(),this.tier="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new OS).fromBinary(t,r)}static fromJson(t,r){return(new OS).fromJson(t,r)}static fromJsonString(t,r){return(new OS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(OS,t,r)}static $(){return["VerifyAppleTransactionResponse|1 tier 9"]}}class DS extends T{constructor(t){super(),this.purchaseToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new DS).fromBinary(t,r)}static fromJson(t,r){return(new DS).fromJson(t,r)}static fromJsonString(t,r){return(new DS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(DS,t,r)}static $(){return["VerifyGooglePlayPurchaseRequest|1 purchase_token 9|2 product_id 9?|3 client_obfuscated_account_id 9?|4 verification_provenance #0?",Jr]}}class NS extends T{constructor(t){super(),this.tier="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new NS).fromBinary(t,r)}static fromJson(t,r){return(new NS).fromJson(t,r)}static fromJsonString(t,r){return(new NS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(NS,t,r)}static $(){return["VerifyGooglePlayPurchaseResponse|1 tier 9|2 pending_tier 9?|3 pending_tier_starts_at_ms 3?"]}}class GS extends T{constructor(t){super(),this.purpose=LS.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new GS).fromBinary(t,r)}static fromJson(t,r){return(new GS).fromJson(t,r)}static fromJsonString(t,r){return(new GS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(GS,t,r)}static $(){return["GetGooglePlayBillingAccountIdRequest|1 product_id 9?|2 purpose #0",LS]}}var LS=(0,a.QT)(n.proto3,C,"GetGooglePlayBillingAccountIdRequest.Purpose",[[0,"UNSPECIFIED"],[1,"LEGACY"],[2,"COMMERCE"]],1);class FS extends T{constructor(t){super(),this.obfuscatedAccountId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new FS).fromBinary(t,r)}static fromJson(t,r){return(new FS).fromJson(t,r)}static fromJsonString(t,r){return(new FS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(FS,t,r)}static $(){return["GetGooglePlayBillingAccountIdResponse|1 obfuscated_account_id 9"]}}class KS extends T{constructor(t){super(),this.googlePurchaseTokens=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new KS).fromBinary(t,r)}static fromJson(t,r){return(new KS).fromJson(t,r)}static fromJsonString(t,r){return(new KS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(KS,t,r)}static $(){return["RestoreCommerceStorePurchasesRequest|1 google_purchase_tokens 9*"]}}class zS extends T{constructor(t){super(),this.googlePurchaseToken="",this.outcome=wr.UNSPECIFIED,this.errorCode="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zS).fromBinary(t,r)}static fromJson(t,r){return(new zS).fromJson(t,r)}static fromJsonString(t,r){return(new zS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zS,t,r)}static $(){return["RestoredCommerceStorePurchase|1 google_purchase_token 9|2 outcome #0|3 error_code 9",wr]}}class jS extends T{constructor(t){super(),this.purchases=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jS).fromBinary(t,r)}static fromJson(t,r){return(new jS).fromJson(t,r)}static fromJsonString(t,r){return(new jS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jS,t,r)}static $(){return["RestoreCommerceStorePurchasesResponse|1 purchases #0*",zS]}}class HS extends T{constructor(t){super(),this.purchaseToken="",this.clientState=yr.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new HS).fromBinary(t,r)}static fromJson(t,r){return(new HS).fromJson(t,r)}static fromJsonString(t,r){return(new HS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(HS,t,r)}static $(){return["GooglePlayPurchaseTokenInventoryItem|1 purchase_token 9|2 product_id 9?|3 client_state #0",yr]}}class WS extends T{constructor(t){super(),this.packageName="",this.items=[],this.trigger=Sr.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new WS).fromBinary(t,r)}static fromJson(t,r){return(new WS).fromJson(t,r)}static fromJsonString(t,r){return(new WS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(WS,t,r)}static $(){return["InventoryGooglePlayPurchaseTokensRequest|1 package_name 9|2 items #0*|3 trigger #1",HS,Sr]}}class QS extends T{constructor(t){super(),this.submittedCount=0,this.retainedCount=0,this.rejectedCount=0,this.unavailableCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new QS).fromBinary(t,r)}static fromJson(t,r){return(new QS).fromJson(t,r)}static fromJsonString(t,r){return(new QS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(QS,t,r)}static $(){return["InventoryGooglePlayPurchaseTokensResponse|1 submitted_count 13|2 retained_count 13|3 rejected_count 13|4 unavailable_count 13"]}}class VS extends T{constructor(t){super(),this.packageName="",this.purchaseToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new VS).fromBinary(t,r)}static fromJson(t,r){return(new VS).fromJson(t,r)}static fromJsonString(t,r){return(new VS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(VS,t,r)}static $(){return["InspectGooglePlaySubscriptionInternalRequest|1 package_name 9|2 purchase_token 9"]}}class XS extends T{constructor(t){super(),this.subscriptionJson="",this.ownerMismatch=!1,this.orderLookupStatus="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new XS).fromBinary(t,r)}static fromJson(t,r){return(new XS).fromJson(t,r)}static fromJsonString(t,r){return(new XS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(XS,t,r)}static $(){return["InspectGooglePlaySubscriptionInternalResponse|1 subscription_json 9|2 token_owner #0?|3 binding_owner #0?|4 ledger_subscription #1?|5 owner_mismatch 8|6 order_json 9?|7 order_lookup_status 9",oq,aq]}}class YS extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new YS).fromBinary(t,r)}static fromJson(t,r){return(new YS).fromJson(t,r)}static fromJsonString(t,r){return(new YS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(YS,t,r)}static $(){return["InspectGooglePlayTransactionsInternalRequest|1 user_id 3?|2 order_id 9?"]}}class ZS extends T{constructor(t){super(),this.diagnosticsJson="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ZS).fromBinary(t,r)}static fromJson(t,r){return(new ZS).fromJson(t,r)}static fromJsonString(t,r){return(new ZS).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ZS,t,r)}static $(){return["InspectGooglePlayTransactionsInternalResponse|1 diagnostics_json 9"]}}class tq extends T{constructor(t){super(),this.title="",this.body="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tq).fromBinary(t,r)}static fromJson(t,r){return(new tq).fromJson(t,r)}static fromJsonString(t,r){return(new tq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tq,t,r)}static $(){return["TestPushCustomContent|1 title 9|2 subtitle 9?|3 body 9|4 type 9?|5 data_json 9?"]}}class rq extends T{constructor(t){super(),this.agentName="",this.awaitingUserResponse=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rq).fromBinary(t,r)}static fromJson(t,r){return(new rq).fromJson(t,r)}static fromJsonString(t,r){return(new rq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rq,t,r)}static $(){return["TestPushSandAgentFinished|1 agent_name 9|2 message_preview 9?|3 awaiting_user_response 8"]}}class eq extends T{constructor(t){super(),this.target={case:void 0},this.platform=Br.UNSPECIFIED,this.scenario=qr.UNSPECIFIED,this.send=!1,this.bypassTypeAllowlist=!1,this.bypassStatsigGate=!1,this.apps=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eq).fromBinary(t,r)}static fromJson(t,r){return(new eq).fromJson(t,r)}static fromJsonString(t,r){return(new eq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eq,t,r)}static $(){return["SendTestPushNotificationInternalRequest|1 user_id 3 target|2 email 9 target|3 platform #0|4 scenario #1|5 custom #2?|6 bc_id 9?|7 send 8|8 bypass_type_allowlist 8|9 bypass_statsig_gate 8|10 apps #3*|11 sand_agent_finished #4?|12 agent_id 9?|13 task_id 9?",Br,qr,tq,Ir,rq]}}class nq extends T{constructor(t){super(),this.tokenId=n.protoInt64.zero,this.platform="",this.app="",this.deviceIdPrefix="",this.outcome="",this.lane=Ir.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nq).fromBinary(t,r)}static fromJson(t,r){return(new nq).fromJson(t,r)}static fromJsonString(t,r){return(new nq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nq,t,r)}static $(){return["TestPushTokenResult|1 token_id 3|2 platform 9|3 app 9|4 bundle_id 9?|5 device_id_prefix 9|6 client_version 9?|7 outcome 9|8 error_code 9?|9 lane #0",Ir]}}class sq extends T{constructor(t){super(),this.app=Ir.UNSPECIFIED,this.outcome="",this.warnings=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sq).fromBinary(t,r)}static fromJson(t,r){return(new sq).fromJson(t,r)}static fromJsonString(t,r){return(new sq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sq,t,r)}static $(){return["TestPushLaneOutcome|1 app #0|2 outcome 9|3 warnings 9*",Ir]}}class iq extends T{constructor(t){super(),this.userId=n.protoInt64.zero,this.email="",this.tokens=[],this.payloadJson="",this.iosOutcome="",this.androidOutcome="",this.lanes=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iq).fromBinary(t,r)}static fromJson(t,r){return(new iq).fromJson(t,r)}static fromJsonString(t,r){return(new iq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iq,t,r)}static $(){return["SendTestPushNotificationInternalResponse|1 user_id 3|2 email 9|3 tokens #0*|4 payload_json 9|5 ios_outcome 9|6 android_outcome 9|7 lanes #1*",nq,sq]}}class oq extends T{constructor(t){super(),this.userId=n.protoInt64.zero,this.authId="",this.email="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oq).fromBinary(t,r)}static fromJson(t,r){return(new oq).fromJson(t,r)}static fromJsonString(t,r){return(new oq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oq,t,r)}static $(){return["GooglePlayInspectedCursorAccount|1 user_id 3|2 auth_id 9|3 email 9"]}}class aq extends T{constructor(t){super(),this.userId=n.protoInt64.zero,this.status="",this.tier="",this.productId="",this.startedAtMs=n.protoInt64.zero,this.expiresAtMs=n.protoInt64.zero,this.autoRenewEnabled=!1,this.acknowledgementState="",this.lastVerifiedAtMs=n.protoInt64.zero,this.purchaseTokenHash="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aq).fromBinary(t,r)}static fromJson(t,r){return(new aq).fromJson(t,r)}static fromJsonString(t,r){return(new aq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aq,t,r)}static $(){return["GooglePlayInspectedLedgerSubscription|1 user_id 3|2 status 9|3 tier 9|4 product_id 9|5 base_plan_id 9?|6 pending_product_id 9?|7 pending_tier 9?|8 started_at_ms 3|9 expires_at_ms 3|10 auto_renew_enabled 8|11 acknowledgement_state 9|12 acknowledged_at_ms 3?|13 last_verified_at_ms 3|14 purchase_token_hash 9|15 linked_purchase_token_hash 9?"]}}class uq extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uq).fromBinary(t,r)}static fromJson(t,r){return(new uq).fromJson(t,r)}static fromJsonString(t,r){return(new uq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uq,t,r)}static $(){return["GetCursorReviewEntitlementRequest"]}}class cq extends T{constructor(t){super(),this.subject={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cq).fromBinary(t,r)}static fromJson(t,r){return(new cq).fromJson(t,r)}static fromJsonString(t,r){return(new cq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cq,t,r)}static $(){return["CursorReviewEntitlementScope|1 team_id 5 subject|2 cursor_user_id 9 subject"]}}class lq extends T{constructor(t){super(),this.eligibleForCursorReview=!1,this.billingContext=mq.UNSPECIFIED,this.reason=fq.UNSPECIFIED,this.eligibleForOriginReview=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lq).fromBinary(t,r)}static fromJson(t,r){return(new lq).fromJson(t,r)}static fromJsonString(t,r){return(new lq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lq,t,r)}static $(){return["GetCursorReviewEntitlementResponse|1 eligible_for_cursor_review 8|3 billing_context #0|4 reason #1|5 team_id 5?|7 scope #2?|8 eligible_for_origin_review 8",mq,fq,cq]}}var mq=(0,a.QT)(n.proto3,C,"GetCursorReviewEntitlementResponse.BillingContext",[[0,"UNSPECIFIED"],[1,"INDIVIDUAL"],[2,"TEAM"],[3,"ENTERPRISE"]],1),fq=(0,a.QT)(n.proto3,C,"GetCursorReviewEntitlementResponse.Reason",[[0,"UNSPECIFIED"],[1,"OK"],[2,"REQUIRES_TEAM_OR_ENTERPRISE"],[3,"CURSOR_REVIEW_DISABLED"],[4,"REQUIRES_PAID_PLAN"],[5,"CURSOR_IDENTITY_UNAVAILABLE"]],1);class dq extends T{constructor(t){super(),this.query="",this.includeTeamBots=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dq).fromBinary(t,r)}static fromJson(t,r){return(new dq).fromJson(t,r)}static fromJsonString(t,r){return(new dq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dq,t,r)}static $(){return["SearchOriginReviewPeopleRequest|1 query 9|2 team_id 5?|3 limit 5?|4 include_team_bots 8"]}}class pq extends T{constructor(t){super(),this.login="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pq).fromBinary(t,r)}static fromJson(t,r){return(new pq).fromJson(t,r)}static fromJsonString(t,r){return(new pq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pq,t,r)}static $(){return["OriginReviewGithubIdentity|1 login 9|2 database_id 9?|3 node_id 9?"]}}class hq extends T{constructor(t){super(),this.displayName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hq).fromBinary(t,r)}static fromJson(t,r){return(new hq).fromJson(t,r)}static fromJsonString(t,r){return(new hq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hq,t,r)}static $(){return["OriginReviewPersonRef|1 cursor_user_id 9?|2 display_name 9|3 avatar_url 9?|4 github #0?|5 service_account_id 9?",pq]}}class gq extends T{constructor(t){super(),this.people=[],this.exactMatchOnly=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gq).fromBinary(t,r)}static fromJson(t,r){return(new gq).fromJson(t,r)}static fromJsonString(t,r){return(new gq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gq,t,r)}static $(){return["SearchOriginReviewPeopleResponse|1 people #0*|2 exact_match_only 8",hq]}}class _q extends T{constructor(t){super(),this.schemaVersion=0,this.prefsJson="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _q).fromBinary(t,r)}static fromJson(t,r){return(new _q).fromJson(t,r)}static fromJsonString(t,r){return(new _q).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_q,t,r)}static $(){return["OriginReviewPreferences|1 schema_version 5|2 prefs_json 9|3 updated_at #0",n.Timestamp]}}class Jq extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jq).fromBinary(t,r)}static fromJson(t,r){return(new Jq).fromJson(t,r)}static fromJsonString(t,r){return(new Jq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jq,t,r)}static $(){return["GetOriginReviewPreferencesRequest"]}}class wq extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wq).fromBinary(t,r)}static fromJson(t,r){return(new wq).fromJson(t,r)}static fromJsonString(t,r){return(new wq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wq,t,r)}static $(){return["GetOriginReviewPreferencesResponse|1 preferences #0?",_q]}}class yq extends T{constructor(t){super(),this.schemaVersion=0,this.prefsJson="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yq).fromBinary(t,r)}static fromJson(t,r){return(new yq).fromJson(t,r)}static fromJsonString(t,r){return(new yq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yq,t,r)}static $(){return["SetOriginReviewPreferencesRequest|1 schema_version 5|2 prefs_json 9"]}}class Sq extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sq).fromBinary(t,r)}static fromJson(t,r){return(new Sq).fromJson(t,r)}static fromJsonString(t,r){return(new Sq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sq,t,r)}static $(){return["SetOriginReviewPreferencesResponse|1 preferences #0",_q]}}class qq extends T{constructor(t){super(),this.id="",this.label="",this.explanation="",this.turnedOn="",this.turnedOff="",this.on=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qq).fromBinary(t,r)}static fromJson(t,r){return(new qq).fromJson(t,r)}static fromJsonString(t,r){return(new qq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qq,t,r)}static $(){return["MergeBotRung|1 id 9|2 label 9|3 explanation 9|4 turned_on 9|5 turned_off 9|6 on 8"]}}class Bq extends T{constructor(t){super(),this.inTestGroup=!1,this.nudges=!1,this.agenticMerge=!1,this.rungs=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bq).fromBinary(t,r)}static fromJson(t,r){return(new Bq).fromJson(t,r)}static fromJsonString(t,r){return(new Bq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bq,t,r)}static $(){return["MergeBotSettings|1 in_test_group 8|2 nudges 8|3 agentic_merge 8|4 rungs #0*|5 saved_at #1|6 working_hours_time_zone 9?",qq,n.Timestamp]}}class Iq extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Iq).fromBinary(t,r)}static fromJson(t,r){return(new Iq).fromJson(t,r)}static fromJsonString(t,r){return(new Iq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Iq,t,r)}static $(){return["GetMergeBotSettingsRequest"]}}class Pq extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pq).fromBinary(t,r)}static fromJson(t,r){return(new Pq).fromJson(t,r)}static fromJsonString(t,r){return(new Pq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pq,t,r)}static $(){return["GetMergeBotSettingsResponse|1 settings #0",Bq]}}class bq extends T{constructor(t){super(),this.rungs={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bq).fromBinary(t,r)}static fromJson(t,r){return(new bq).fromJson(t,r)}static fromJsonString(t,r){return(new bq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bq,t,r)}static $(){return["SetMergeBotConsentRequest|1 nudges 8?|2 agentic_merge 8?|3 rungs 9,8"]}}class Rq extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rq).fromBinary(t,r)}static fromJson(t,r){return(new Rq).fromJson(t,r)}static fromJsonString(t,r){return(new Rq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rq,t,r)}static $(){return["SetMergeBotConsentResponse|1 settings #0",Bq]}}class vq extends T{constructor(t){super(),this.status=[],this.pr=[],this.source=[],this.sourceOptIns=[],this.archivedOnly=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vq).fromBinary(t,r)}static fromJson(t,r){return(new vq).fromJson(t,r)}static fromJsonString(t,r){return(new vq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vq,t,r)}static $(){return["SyncedSidebarFilters|1 status 9*|2 pr 9*|3 source 9*|4 source_opt_ins 9*|5 archived_only 8"]}}class xq extends T{constructor(t){super(),this.value="",this.setAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xq).fromBinary(t,r)}static fromJson(t,r){return(new xq).fromJson(t,r)}static fromJsonString(t,r){return(new xq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xq,t,r)}static $(){return["SyncedStringSetting|1 value 9|2 set_at_ms 3"]}}class kq extends T{constructor(t){super(),this.value=!1,this.setAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kq).fromBinary(t,r)}static fromJson(t,r){return(new kq).fromJson(t,r)}static fromJsonString(t,r){return(new kq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kq,t,r)}static $(){return["SyncedBoolSetting|1 value 8|2 set_at_ms 3"]}}class Eq extends T{constructor(t){super(),this.setAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Eq).fromBinary(t,r)}static fromJson(t,r){return(new Eq).fromJson(t,r)}static fromJsonString(t,r){return(new Eq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Eq,t,r)}static $(){return["SyncedSidebarFiltersSetting|1 value #0|2 set_at_ms 3",vq]}}class Cq extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cq).fromBinary(t,r)}static fromJson(t,r){return(new Cq).fromJson(t,r)}static fromJsonString(t,r){return(new Cq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cq,t,r)}static $(){return["SyncedSettings|1 new_messages #0|2 manual_send #0|3 first_steer_notice_shown #1|4 sidebar_filters #2",xq,kq,Eq]}}class Tq extends T{constructor(t){super(),this.setNow=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tq).fromBinary(t,r)}static fromJson(t,r){return(new Tq).fromJson(t,r)}static fromJsonString(t,r){return(new Tq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tq,t,r)}static $(){return["SyncClientSettingsRequest|1 changed #0|2 set_now 8",Cq]}}class Uq extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Uq).fromBinary(t,r)}static fromJson(t,r){return(new Uq).fromJson(t,r)}static fromJsonString(t,r){return(new Uq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Uq,t,r)}static $(){return["SyncClientSettingsResponse|1 settings #0",Cq]}}class Aq extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Aq).fromBinary(t,r)}static fromJson(t,r){return(new Aq).fromJson(t,r)}static fromJsonString(t,r){return(new Aq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Aq,t,r)}static $(){return["GetUsageLimitPolicyStatusRequest"]}}class $q extends T{constructor(t){super(),this.modelId="",this.parameters=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $q).fromBinary(t,r)}static fromJson(t,r){return(new $q).fromJson(t,r)}static fromJsonString(t,r){return(new $q).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($q,t,r)}static $(){return["AllowedModelSelection|1 model_id 9|2 max_mode 8?|3 parameters #0*",Mq]}}class Mq extends T{constructor(t){super(),this.id="",this.value="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mq).fromBinary(t,r)}static fromJson(t,r){return(new Mq).fromJson(t,r)}static fromJsonString(t,r){return(new Mq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mq,t,r)}static $(){return["AllowedModelSelection.ModelParameterValue|1 id 9|2 value 9"]}}class Oq extends T{constructor(t){super(),this.isInSlowPool=!1,this.features={},this.canConfigureSpendLimit=!1,this.hasPendingRequest=!1,this.allowedModelIds=[],this.allowedModelTags=[],this.allowedModelSelections=[],this.stage=Pr.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Oq).fromBinary(t,r)}static fromJson(t,r){return(new Oq).fromJson(t,r)}static fromJsonString(t,r){return(new Oq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Oq,t,r)}static $(){return["GetUsageLimitPolicyStatusResponse|1 is_in_slow_pool 8|2 error_title 9?|3 error_detail 9?|4 slowness_ms 5?|5 features 9,9|6 can_configure_spend_limit 8|7 limit_type 9?|8 has_pending_request 8|9 allowed_model_ids 9*|10 allowed_model_tags 9*|24 allowed_model_selections #0*|11 primary_button #1?|25 credit_request_button_hidden 8?|12 stage #2|13 tray_label 9?|14 tray_description 9?|15 cta_label 9?|16 dismissible 8?|17 reset_at_ms 3?|18 reset_days_remaining 5?|19 can_adjust_on_demand 8?|20 recommended_on_demand_limit_cents 3?|21 on_demand_min_cents 3?|22 on_demand_max_cents 3?|23 current_on_demand_limit_cents 3?",$q,o.Bo,Pr]}}class Dq extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dq).fromBinary(t,r)}static fromJson(t,r){return(new Dq).fromJson(t,r)}static fromJsonString(t,r){return(new Dq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dq,t,r)}static $(){return["GetUsageLimitStatusAndActiveGrantsRequest|1 mid_conversation_model_recommendation_context #0?",Nq]}}class Nq extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nq).fromBinary(t,r)}static fromJson(t,r){return(new Nq).fromJson(t,r)}static fromJsonString(t,r){return(new Nq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nq,t,r)}static $(){return["MidConversationModelRecommendationContext|1 current_model #0|2 supports_third_party_usage_nudge 8?|3 model_nudges_enabled 8?|4 supports_first_party_limit_upsell 8?|5 declined_first_party_limit_upsell_offer_id 9?",h.G4]}}class Gq extends T{constructor(t){super(),this.grantId="",this.totalCents=n.protoInt64.zero,this.remainingCents=n.protoInt64.zero,this.expiresAtMs=n.protoInt64.zero,this.allowedModelIds=[],this.allowedModelTags=[],this.grantType="",this.showInClient=!1,this.allowedClientTypes=[],this.allowedModelSelections=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gq).fromBinary(t,r)}static fromJson(t,r){return(new Gq).fromJson(t,r)}static fromJsonString(t,r){return(new Gq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gq,t,r)}static $(){return["ActiveCreditGrant|1 grant_id 9|2 total_cents 3|3 remaining_cents 3|4 expires_at_ms 3|5 allowed_model_ids 9*|6 allowed_model_tags 9*|7 grant_type 9|8 slowness_ms 5?|9 source 9?|10 campaign_name 9?|11 show_in_client 8|12 allowed_client_types 9*|13 allowed_model_selections #0*",$q]}}class Lq extends T{constructor(t){super(),this.grantId="",this.remainingCents=n.protoInt64.zero,this.totalCents=n.protoInt64.zero,this.grantedAtMs=n.protoInt64.zero,this.expiresAtMs=n.protoInt64.zero,this.surface=br.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lq).fromBinary(t,r)}static fromJson(t,r){return(new Lq).fromJson(t,r)}static fromJsonString(t,r){return(new Lq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Lq,t,r)}static $(){return["ProjectsCredit|1 grant_id 9|2 remaining_cents 3|3 total_cents 3|4 granted_at_ms 3|5 expires_at_ms 3|6 surface #0|7 campaign_id 3?|8 team_id 3?",br]}}class Fq extends T{constructor(t){super(),this.activeGrants=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fq).fromBinary(t,r)}static fromJson(t,r){return(new Fq).fromJson(t,r)}static fromJsonString(t,r){return(new Fq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fq,t,r)}static $(){return["GetUsageLimitStatusAndActiveGrantsResponse|1 usage_limit_policy_status #0|2 active_grants #1*|3 third_party_usage_nudge #2?|4 model_recommendation_nudge #3?|5 projects_credit #4?|6 first_party_limit_upsell #5?",Kq,Gq,jq,zq,Lq,Hq]}}class Kq extends T{constructor(t){super(),this.isInSlowPool=!1,this.features={},this.canConfigureSpendLimit=!1,this.hasPendingRequest=!1,this.allowedModelIds=[],this.allowedModelTags=[],this.stage=Pr.UNSPECIFIED,this.allowedModelSelections=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kq).fromBinary(t,r)}static fromJson(t,r){return(new Kq).fromJson(t,r)}static fromJsonString(t,r){return(new Kq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Kq,t,r)}static $(){return["GetUsageLimitStatusAndActiveGrantsResponse.UsageLimitPolicyStatus|1 is_in_slow_pool 8|2 error_title 9?|3 error_detail 9?|4 slowness_ms 5?|5 features 9,9|6 can_configure_spend_limit 8|7 limit_type 9?|8 has_pending_request 8|9 allowed_model_ids 9*|10 allowed_model_tags 9*|11 primary_button #0?|12 stage #1|13 tray_label 9?|14 tray_description 9?|15 cta_label 9?|16 dismissible 8?|17 reset_at_ms 3?|18 reset_days_remaining 5?|19 can_adjust_on_demand 8?|20 recommended_on_demand_limit_cents 3?|21 on_demand_min_cents 3?|22 on_demand_max_cents 3?|23 current_on_demand_limit_cents 3?|24 allowed_model_selections #2*|25 secondary_button #0?|26 credit_request_button_hidden 8?",o.Bo,Pr,$q]}}class zq extends T{constructor(t){super(),this.nudgeId="",this.experimentName="",this.group="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zq).fromBinary(t,r)}static fromJson(t,r){return(new zq).fromJson(t,r)}static fromJsonString(t,r){return(new zq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zq,t,r)}static $(){return["ModelRecommendationNudge|1 nudge_id 9|2 experiment_name 9|3 group 9|4 source_model #0|5 target_model #0",h.G4]}}class jq extends T{constructor(t){super(),this.experimentName="",this.group="",this.threshold=0,this.cycleId="",this.targetModel="",this.label="",this.ctaLabel="",this.nudgeId="",this.description="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jq).fromBinary(t,r)}static fromJson(t,r){return(new jq).fromJson(t,r)}static fromJsonString(t,r){return(new jq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jq,t,r)}static $(){return["ThirdPartyUsageNudge|1 experiment_name 9|2 group 9|3 threshold 5|4 cycle_id 9|5 target_model 9|6 label 9|7 cta_label 9|8 nudge_id 9|9 description 9"]}}class Hq extends T{constructor(t){super(),this.offerId="",this.title="",this.body="",this.ctaLabel="",this.ctaUrl="",this.dismissLabel="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hq).fromBinary(t,r)}static fromJson(t,r){return(new Hq).fromJson(t,r)}static fromJsonString(t,r){return(new Hq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hq,t,r)}static $(){return["FirstPartyLimitUpsell|1 offer_id 9|2 title 9|3 body 9|4 cta_label 9|5 cta_url 9|6 dismiss_label 9"]}}class Wq extends T{constructor(t){super(),this.includeAllProducts=!1,this.includePersonalTeam=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wq).fromBinary(t,r)}static fromJson(t,r){return(new Wq).fromJson(t,r)}static fromJsonString(t,r){return(new Wq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wq,t,r)}static $(){return["GetCreditGrantsBalanceRequest|1 team_id 5?|2 include_all_products 8|3 include_personal_team 8"]}}class Qq extends T{constructor(t){super(),this.hasCreditGrants=!1,this.creditBalanceCents=n.protoInt64.zero,this.totalCents=n.protoInt64.zero,this.usedCents=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qq).fromBinary(t,r)}static fromJson(t,r){return(new Qq).fromJson(t,r)}static fromJsonString(t,r){return(new Qq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qq,t,r)}static $(){return["GetCreditGrantsBalanceResponse|1 has_credit_grants 8|2 credit_balance_cents 3|3 total_cents 3|4 used_cents 3"]}}class Vq extends T{constructor(t){super(),this.includeAllProducts=!1,this.includePersonalTeam=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vq).fromBinary(t,r)}static fromJson(t,r){return(new Vq).fromJson(t,r)}static fromJsonString(t,r){return(new Vq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vq,t,r)}static $(){return["GetClientVisibleCreditGrantsRequest|1 team_id 5?|2 include_all_products 8|3 include_personal_team 8"]}}class Xq extends T{constructor(t){super(),this.grants=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xq).fromBinary(t,r)}static fromJson(t,r){return(new Xq).fromJson(t,r)}static fromJsonString(t,r){return(new Xq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xq,t,r)}static $(){return["GetClientVisibleCreditGrantsResponse|1 grants #0*",Yq]}}class Yq extends T{constructor(t){super(),this.remainingCents=n.protoInt64.zero,this.totalCents=n.protoInt64.zero,this.expiresAtMs=n.protoInt64.zero,this.displayName="",this.applicableProducts=[],this.appliesToAllProducts=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yq).fromBinary(t,r)}static fromJson(t,r){return(new Yq).fromJson(t,r)}static fromJsonString(t,r){return(new Yq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yq,t,r)}static $(){return["ClientVisibleCreditGrant|1 remaining_cents 3|2 total_cents 3|3 expires_at_ms 3|4 display_name 9|5 percent_used 5?|6 applicable_products 9*|7 applies_to_all_products 8"]}}class Zq extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zq).fromBinary(t,r)}static fromJson(t,r){return(new Zq).fromJson(t,r)}static fromJsonString(t,r){return(new Zq).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zq,t,r)}static $(){return["GetAdvancedAnalyticsEnabledRequest|1 team_id 5"]}}class tB extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tB).fromBinary(t,r)}static fromJson(t,r){return(new tB).fromJson(t,r)}static fromJsonString(t,r){return(new tB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tB,t,r)}static $(){return["GetAdvancedAnalyticsEnabledResponse|1 enabled 8"]}}class rB extends T{constructor(t){super(),this.usageUuid="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rB).fromBinary(t,r)}static fromJson(t,r){return(new rB).fromJson(t,r)}static fromJsonString(t,r){return(new rB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rB,t,r)}static $(){return["GetTokenUsageRequest|1 usage_uuid 9"]}}class eB extends T{constructor(t){super(),this.inputTokens=0,this.outputTokens=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eB).fromBinary(t,r)}static fromJson(t,r){return(new eB).fromJson(t,r)}static fromJsonString(t,r){return(new eB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eB,t,r)}static $(){return["GetTokenUsageResponse|1 input_tokens 5|2 output_tokens 5"]}}class nB extends T{constructor(t){super(),this.teamId=0,this.bedrockIamRole="",this.region="",this.modelId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nB).fromBinary(t,r)}static fromJson(t,r){return(new nB).fromJson(t,r)}static fromJsonString(t,r){return(new nB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nB,t,r)}static $(){return["ValidateBedrockIamRoleRequest|1 team_id 5|2 bedrock_iam_role 9|3 region 9|4 model_id 9"]}}class sB extends T{constructor(t){super(),this.success=!1,this.errorMessage="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sB).fromBinary(t,r)}static fromJson(t,r){return(new sB).fromJson(t,r)}static fromJsonString(t,r){return(new sB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sB,t,r)}static $(){return["ValidateBedrockIamRoleResponse|1 success 8|2 error_message 9"]}}class iB extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iB).fromBinary(t,r)}static fromJson(t,r){return(new iB).fromJson(t,r)}static fromJsonString(t,r){return(new iB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iB,t,r)}static $(){return["DeleteBedrockIamRoleRequest|1 team_id 5"]}}class oB extends T{constructor(t){super(),this.success=!1,this.errorMessage="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oB).fromBinary(t,r)}static fromJson(t,r){return(new oB).fromJson(t,r)}static fromJsonString(t,r){return(new oB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oB,t,r)}static $(){return["DeleteBedrockIamRoleResponse|1 success 8|2 error_message 9"]}}class aB extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aB).fromBinary(t,r)}static fromJson(t,r){return(new aB).fromJson(t,r)}static fromJsonString(t,r){return(new aB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aB,t,r)}static $(){return["GetTeamSpendRequest|1 team_id 5|2 page 5?|3 page_size 5?|4 sort_by 9?|5 sort_direction 9?|6 search_term 9?|7 directory_group_id 5?|8 start_date 3?|9 end_date 3?|10 user_id 5?"]}}class uB extends T{constructor(t){super(),this.role=it.UNSPECIFIED,this.count=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uB).fromBinary(t,r)}static fromJson(t,r){return(new uB).fromJson(t,r)}static fromJsonString(t,r){return(new uB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uB,t,r)}static $(){return["TeamRoleCount|1 role #0|2 count 5",it]}}class cB extends T{constructor(t){super(),this.teamMemberSpend=[],this.subscriptionCycleStart=n.protoInt64.zero,this.totalMembers=0,this.totalPages=0,this.totalByRole=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cB).fromBinary(t,r)}static fromJson(t,r){return(new cB).fromJson(t,r)}static fromJsonString(t,r){return(new cB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cB,t,r)}static $(){return["GetTeamSpendResponse|1 team_member_spend #0*|2 subscription_cycle_start 3|3 total_members 5|4 total_pages 5|5 total_by_role #1*|6 next_cycle_start 3?|7 pooled_limit_dollars 5?|8 limited_user_count 5?|9 max_user_spend_cents 5?|10 subscription_limited_users 5?|11 has_any_spend_limit_overrides 8?|12 has_any_free_usage 8?|13 self_serve_tiered_pricing_enabled 8?|14 merged_seat_rail 8?|15 unified_included_usage 8?|16 included_usage_resets_at 3?|17 on_demand_usage_unavailable 8?",lB,uB]}}class lB extends T{constructor(t){super(),this.userId=0,this.spendCents=0,this.fastPremiumRequests=0,this.name="",this.email="",this.role=it.UNSPECIFIED,this.hardLimitOverrideDollars=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lB).fromBinary(t,r)}static fromJson(t,r){return(new lB).fromJson(t,r)}static fromJsonString(t,r){return(new lB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lB,t,r)}static $(){return["GetTeamSpendResponse.TeamMemberSpend|1 user_id 5|2 spend_cents 5|3 fast_premium_requests 5|4 name 9|5 email 9|6 role #0|7 hard_limit_override_dollars 5|8 included_spend_cents 5?|9 overall_spend_cents 5?|10 monthly_limit_dollars 5?|11 removed_at 3?|12 effective_per_user_limit_dollars 5?|13 profile_picture_url 9?|14 billing_tier #1?|15 auto_percent_used 1?|16 api_percent_used 1?|17 total_percent_used 1?|18 usage_promo_expires_at 3?|19 first_party_models_additional_budget_dollars 5?|20 first_party_models_additional_budget_unlimited 8?|21 merged_seat_tier #2?|22 included_percent_used 1?",it,ot,at]}}class mB extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mB).fromBinary(t,r)}static fromJson(t,r){return(new mB).fromJson(t,r)}static fromJsonString(t,r){return(new mB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mB,t,r)}static $(){return["GetTeamSeatUpgradeRecommendationsRequest|1 team_id 5"]}}class fB extends T{constructor(t){super(),this.userId=0,this.name="",this.email="",this.role=it.UNSPECIFIED,this.billingTier=ot.UNSPECIFIED,this.previousCycleSavings=!1,this.currentCyclePacing=!1,this.poolDriver=Rr.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fB).fromBinary(t,r)}static fromJson(t,r){return(new fB).fromJson(t,r)}static fromJsonString(t,r){return(new fB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fB,t,r)}static $(){return["SeatUpgradeRecommendation|1 user_id 5|2 name 9|3 email 9|4 profile_picture_url 9?|5 role #0|6 billing_tier #1|7 previous_cycle_savings 8|8 current_cycle_pacing 8|9 pool_driver #2|10 previous_cycle_savings_cents 5?|11 projected_current_cycle_savings_cents 5?",it,ot,Rr]}}class dB extends T{constructor(t){super(),this.recommendations=[],this.enabled=!1,this.totalMonthlySavingsCents=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dB).fromBinary(t,r)}static fromJson(t,r){return(new dB).fromJson(t,r)}static fromJsonString(t,r){return(new dB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dB,t,r)}static $(){return["GetTeamSeatUpgradeRecommendationsResponse|1 recommendations #0*|2 enabled 8|3 total_monthly_savings_cents 5",fB]}}class pB extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pB).fromBinary(t,r)}static fromJson(t,r){return(new pB).fromJson(t,r)}static fromJsonString(t,r){return(new pB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pB,t,r)}static $(){return["GetPendingSeatTierUpgradeRequestsRequest|1 team_id 5"]}}class hB extends T{constructor(t){super(),this.userId=0,this.name="",this.email="",this.role=it.UNSPECIFIED,this.billingTier=ot.UNSPECIFIED,this.requestedAt="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hB).fromBinary(t,r)}static fromJson(t,r){return(new hB).fromJson(t,r)}static fromJsonString(t,r){return(new hB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hB,t,r)}static $(){return["PendingSeatTierUpgradeRequest|1 user_id 5|2 name 9|3 email 9|4 profile_picture_url 9?|5 role #0|6 billing_tier #1|7 requested_at 9",it,ot]}}class gB extends T{constructor(t){super(),this.requests=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gB).fromBinary(t,r)}static fromJson(t,r){return(new gB).fromJson(t,r)}static fromJsonString(t,r){return(new gB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gB,t,r)}static $(){return["GetPendingSeatTierUpgradeRequestsResponse|1 requests #0*",hB]}}class _B extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _B).fromBinary(t,r)}static fromJson(t,r){return(new _B).fromJson(t,r)}static fromJsonString(t,r){return(new _B).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_B,t,r)}static $(){return["GetTeamSeatCapacityRequest|1 team_id 5"]}}class JB extends T{constructor(t){super(),this.purchasedSeats=0,this.inUseSeats=0,this.availableSeats=0,this.pendingReleaseSeats=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new JB).fromBinary(t,r)}static fromJson(t,r){return(new JB).fromJson(t,r)}static fromJsonString(t,r){return(new JB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(JB,t,r)}static $(){return["GetTeamSeatCapacityResponse|1 purchased_seats 5|2 in_use_seats 5|3 available_seats 5|4 pending_release_seats 5"]}}class wB extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wB).fromBinary(t,r)}static fromJson(t,r){return(new wB).fromJson(t,r)}static fromJsonString(t,r){return(new wB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wB,t,r)}static $(){return["GetXaiTeamPlanManagementRequest|1 team_id 5"]}}class yB extends T{constructor(t){super(),this.skuId="",this.quantity=0,this.scheduledQuantity=0,this.reducibleQuantity=0,this.tier=at.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yB).fromBinary(t,r)}static fromJson(t,r){return(new yB).fromJson(t,r)}static fromJsonString(t,r){return(new yB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yB,t,r)}static $(){return["XaiTeamPlanSeatLine|1 sku_id 9|2 quantity 5|3 scheduled_quantity 5|4 reducible_quantity 5|5 tier #0",at]}}class SB extends T{constructor(t){super(),this.skuId="",this.tier=at.UNSPECIFIED,this.currencyCode="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new SB).fromBinary(t,r)}static fromJson(t,r){return(new SB).fromJson(t,r)}static fromJsonString(t,r){return(new SB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(SB,t,r)}static $(){return["XaiTeamPlanSeatOffer|1 sku_id 9|2 tier #0|3 unit_price_micros 3?|4 currency_code 9|5 yearly_unit_price_micros 3?",at]}}class qB extends T{constructor(t){super(),this.kind=BB.UNSPECIFIED,this.value={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qB).fromBinary(t,r)}static fromJson(t,r){return(new qB).fromJson(t,r)}static fromJsonString(t,r){return(new qB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qB,t,r)}static $(){return["XaiTeamPlanDiscount|1 kind #0|2 percent_off 5 value|3 amount_off #1 value|4 ends_at #2?",BB,IB,n.Timestamp]}}var BB=(0,a.QT)(n.proto3,C,"XaiTeamPlanDiscount.Kind",[[0,"UNSPECIFIED"],[1,"TRIAL"],[2,"PERCENT_OFF"],[3,"AMOUNT_OFF"],[4,"PAY_UPFRONT"]],1);class IB extends T{constructor(t){super(),this.unitMicros=n.protoInt64.zero,this.currencyCode="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new IB).fromBinary(t,r)}static fromJson(t,r){return(new IB).fromJson(t,r)}static fromJsonString(t,r){return(new IB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(IB,t,r)}static $(){return["XaiTeamPlanDiscount.AmountOff|1 unit_micros 3|2 currency_code 9"]}}class PB extends T{constructor(t){super(),this.available=!1,this.cancelling=!1,this.seatLines=[],this.unassignedSeats=0,this.manageOnGrokUrl="",this.manageOnGrokOnly=!1,this.reducibleSeats=0,this.pendingChangeAt="",this.addSeatOffered=!1,this.seatOffers=[],this.maxSeatsPerPurchase=0,this.paymentMethodUpdateOffered=!1,this.declinedCardJoin=!1,this.annualSwitchOffered=!1,this.planCancellingJoinerName="",this.declinedCardJoinWaitsForPayer=!1,this.planEnded=!1,this.seatPrices=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new PB).fromBinary(t,r)}static fromJson(t,r){return(new PB).fromJson(t,r)}static fromJsonString(t,r){return(new PB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(PB,t,r)}static $(){return["GetXaiTeamPlanManagementResponse|1 available 8|2 cancelling 8|3 seat_lines #0*|4 unassigned_seats 5|5 manage_on_grok_url 9|6 manage_on_grok_only 8|7 reducible_seats 5|8 seats_after_pending_change 5?|9 pending_change_at 9|10 add_seat_offered 8|11 pending_payment_check #1|12 seat_offers #2*|13 max_seats_per_purchase 5|14 active_discount #3?|15 payment_method_update_offered 8|16 declined_card_join 8|17 annual_switch_offered 8|18 plan_cancelling_joiner_name 9|19 declined_card_join_waits_for_payer 8|20 plan_ended 8|21 seat_prices #2*|22 enterprise_trial_ends_at #4?",yB,yF,SB,qB,n.Timestamp]}}class bB extends T{constructor(t){super(),this.teamId=0,this.idempotencyKey="",this.change={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bB).fromBinary(t,r)}static fromJson(t,r){return(new bB).fromJson(t,r)}static fromJsonString(t,r){return(new bB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bB,t,r)}static $(){return["ChangeXaiTeamPlanRequest|1 team_id 5|2 idempotency_key 9|3 cancel #0 change|4 reinstate #1 change|5 reduce_seats #2 change|6 add_seat #3 change|7 finish_seat_payment_check #4 change|8 start_payment_method_update #5 change|9 update_payment_method #6 change|10 switch_to_annual #7 change",RB,vB,xB,kB,EB,CB,TB,UB]}}class RB extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new RB).fromBinary(t,r)}static fromJson(t,r){return(new RB).fromJson(t,r)}static fromJsonString(t,r){return(new RB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(RB,t,r)}static $(){return["ChangeXaiTeamPlanRequest.Cancel"]}}class vB extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vB).fromBinary(t,r)}static fromJson(t,r){return(new vB).fromJson(t,r)}static fromJsonString(t,r){return(new vB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vB,t,r)}static $(){return["ChangeXaiTeamPlanRequest.Reinstate"]}}class xB extends T{constructor(t){super(),this.quantity=0,this.skuId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xB).fromBinary(t,r)}static fromJson(t,r){return(new xB).fromJson(t,r)}static fromJsonString(t,r){return(new xB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xB,t,r)}static $(){return["ChangeXaiTeamPlanRequest.ReduceSeats|1 quantity 5|2 sku_id 9"]}}class kB extends T{constructor(t){super(),this.quantity=0,this.skuId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kB).fromBinary(t,r)}static fromJson(t,r){return(new kB).fromJson(t,r)}static fromJsonString(t,r){return(new kB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kB,t,r)}static $(){return["ChangeXaiTeamPlanRequest.AddSeat|1 quantity 5|2 sku_id 9"]}}class EB extends T{constructor(t){super(),this.checkId="",this.confirmed=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new EB).fromBinary(t,r)}static fromJson(t,r){return(new EB).fromJson(t,r)}static fromJsonString(t,r){return(new EB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(EB,t,r)}static $(){return["ChangeXaiTeamPlanRequest.FinishSeatPaymentCheck|1 check_id 9|2 confirmed 8"]}}class CB extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new CB).fromBinary(t,r)}static fromJson(t,r){return(new CB).fromJson(t,r)}static fromJsonString(t,r){return(new CB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(CB,t,r)}static $(){return["ChangeXaiTeamPlanRequest.StartPaymentMethodUpdate"]}}class TB extends T{constructor(t){super(),this.paymentMethodId="",this.billingCountry="",this.billingPostalCode="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new TB).fromBinary(t,r)}static fromJson(t,r){return(new TB).fromJson(t,r)}static fromJsonString(t,r){return(new TB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(TB,t,r)}static $(){return["ChangeXaiTeamPlanRequest.UpdatePaymentMethod|1 payment_method_id 9|2 billing_country 9|3 billing_postal_code 9"]}}class UB extends T{constructor(t){super(),this.preview=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new UB).fromBinary(t,r)}static fromJson(t,r){return(new UB).fromJson(t,r)}static fromJsonString(t,r){return(new UB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(UB,t,r)}static $(){return["ChangeXaiTeamPlanRequest.SwitchToAnnual|1 preview 8"]}}class AB extends T{constructor(t){super(),this.outcome=vr.UNSPECIFIED,this.message="",this.effectiveAt="",this.manageOnGrokUrl="",this.stripePublishableKey="",this.billingCountry="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new AB).fromBinary(t,r)}static fromJson(t,r){return(new AB).fromJson(t,r)}static fromJsonString(t,r){return(new AB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(AB,t,r)}static $(){return["ChangeXaiTeamPlanResponse|1 outcome #0|2 message 9|3 effective_at 9|4 manage_on_grok_url 9|5 payment_challenge #1|6 stripe_publishable_key 9|7 annual_switch #2|8 billing_country 9",vr,wF,$B]}}class $B extends T{constructor(t){super(),this.atRenewal=!1,this.currencyCode="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $B).fromBinary(t,r)}static fromJson(t,r){return(new $B).fromJson(t,r)}static fromJsonString(t,r){return(new $B).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($B,t,r)}static $(){return["ChangeXaiTeamPlanResponse.AnnualSwitch|1 at_renewal 8|2 amount_due_cents 3?|3 currency_code 9"]}}class MB extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new MB).fromBinary(t,r)}static fromJson(t,r){return(new MB).fromJson(t,r)}static fromJsonString(t,r){return(new MB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(MB,t,r)}static $(){return["GetCurrentBillingCycleRequest|1 team_id 5?"]}}class OB extends T{constructor(t){super(),this.startDateEpochMillis=n.protoInt64.zero,this.endDateEpochMillis=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new OB).fromBinary(t,r)}static fromJson(t,r){return(new OB).fromJson(t,r)}static fromJsonString(t,r){return(new OB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(OB,t,r)}static $(){return["GetCurrentBillingCycleResponse|1 start_date_epoch_millis 3|2 end_date_epoch_millis 3"]}}class DB extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new DB).fromBinary(t,r)}static fromJson(t,r){return(new DB).fromJson(t,r)}static fromJsonString(t,r){return(new DB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(DB,t,r)}static $(){return["GetMonthlyBillingCycleRequest|1 team_id 5?"]}}class NB extends T{constructor(t){super(),this.startDateEpochMillis=n.protoInt64.zero,this.endDateEpochMillis=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new NB).fromBinary(t,r)}static fromJson(t,r){return(new NB).fromJson(t,r)}static fromJsonString(t,r){return(new NB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(NB,t,r)}static $(){return["GetMonthlyBillingCycleResponse|1 start_date_epoch_millis 3|2 end_date_epoch_millis 3"]}}class GB extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new GB).fromBinary(t,r)}static fromJson(t,r){return(new GB).fromJson(t,r)}static fromJsonString(t,r){return(new GB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(GB,t,r)}static $(){return["GetBugbotSettingsRequest"]}}class LB extends T{constructor(t){super(),this.available=!1,this.enabled=!1,this.prUrls=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new LB).fromBinary(t,r)}static fromJson(t,r){return(new LB).fromJson(t,r)}static fromJsonString(t,r){return(new LB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(LB,t,r)}static $(){return["GetBugbotSettingsResponse|1 available 8|2 enabled 8|3 pr_urls 9*"]}}class FB extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new FB).fromBinary(t,r)}static fromJson(t,r){return(new FB).fromJson(t,r)}static fromJsonString(t,r){return(new FB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(FB,t,r)}static $(){return["GetBugbotAnalyticsV2Request|1 start_date 9?|2 end_date 9?|3 grouping 9?|4 team_id 5?"]}}class KB extends T{constructor(t){super(),this.shouldSeeAnalytics=!1,this.prsReviewedSeries=[],this.bugsFoundSeries=[],this.numRunsSeries=[],this.bugsResolvedSeries=[],this.pctResolutionRate=0,this.uniqueUsersSeries=[],this.uniqueUsersTotal=0,this.highSevResolvedSeries=[],this.mediumSevResolvedSeries=[],this.lowSevResolvedSeries=[],this.autofixPrsMergedSeries=[],this.totalAutofixRuns=0,this.costCentsSeries=[],this.numBilledRunsSeries=[],this.totalBugsFound=0,this.totalBugsEvaluated=0,this.bugsEvaluatedSeries=[],this.prsReviewedTotal=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new KB).fromBinary(t,r)}static fromJson(t,r){return(new KB).fromJson(t,r)}static fromJsonString(t,r){return(new KB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(KB,t,r)}static $(){return["GetBugbotAnalyticsV2Response|1 should_see_analytics 8|2 prs_reviewed_series #0*|3 bugs_found_series #0*|4 num_runs_series #0*|5 bugs_resolved_series #0*|6 pct_resolution_rate 1|7 unique_users_series #0*|8 unique_users_total 5|9 high_sev_resolved_series #0*|10 medium_sev_resolved_series #0*|11 low_sev_resolved_series #0*|12 autofix_prs_merged_series #0*|13 total_autofix_runs 5|14 cost_cents_series #0*|15 num_billed_runs_series #0*|16 total_bugs_found 5|17 total_bugs_evaluated 5|18 bugs_evaluated_series #0*|19 prs_reviewed_total 5",zB]}}class zB extends T{constructor(t){super(),this.date=n.protoInt64.zero,this.value=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zB).fromBinary(t,r)}static fromJson(t,r){return(new zB).fromJson(t,r)}static fromJsonString(t,r){return(new zB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zB,t,r)}static $(){return["BugbotAnalyticsDataPoint|1 date 3|2 value 5"]}}class jB extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jB).fromBinary(t,r)}static fromJson(t,r){return(new jB).fromJson(t,r)}static fromJsonString(t,r){return(new jB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jB,t,r)}static $(){return["GetBugBotPRAnalyticsRequest|1 github_repo_node_id 9?|2 status 9?|3 github_user_node_id 9?|4 start_date 9?|5 end_date 9?|6 min_bugs_found 5?|7 limit 5?|8 team_id 5?"]}}class HB extends T{constructor(t){super(),this.prs=[],this.userOptions=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new HB).fromBinary(t,r)}static fromJson(t,r){return(new HB).fromJson(t,r)}static fromJsonString(t,r){return(new HB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(HB,t,r)}static $(){return["GetBugBotPRAnalyticsResponse|2 prs #0*|3 user_options #1*",QB,WB]}}class WB extends T{constructor(t){super(),this.githubUserNodeId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new WB).fromBinary(t,r)}static fromJson(t,r){return(new WB).fromJson(t,r)}static fromJsonString(t,r){return(new WB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(WB,t,r)}static $(){return["PRUserOption|1 github_user_node_id 9|2 github_username 9?"]}}class QB extends T{constructor(t){super(),this.githubRepoNodeId="",this.prNumber=0,this.requestTime=n.protoInt64.zero,this.totalRuns=0,this.totalBugs=0,this.resolvedBugs=0,this.unresolvedBugs=0,this.isMerged=!1,this.highSevResolvedBugs=0,this.mediumSevResolvedBugs=0,this.lowSevResolvedBugs=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new QB).fromBinary(t,r)}static fromJson(t,r){return(new QB).fromJson(t,r)}static fromJsonString(t,r){return(new QB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(QB,t,r)}static $(){return["BugBotPRAnalytics|1 github_repo_node_id 9|2 pr_number 5|3 request_time 3|4 total_runs 5|5 total_bugs 5|6 resolved_bugs 5|7 unresolved_bugs 5|8 is_merged 8|9 github_username 9?|10 high_sev_resolved_bugs 5|11 medium_sev_resolved_bugs 5|12 low_sev_resolved_bugs 5"]}}class VB extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new VB).fromBinary(t,r)}static fromJson(t,r){return(new VB).fromJson(t,r)}static fromJsonString(t,r){return(new VB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(VB,t,r)}static $(){return["GetGithubInstallationsRequest|2 include_team_owned_repos 8?|3 ghe_application 9?|4 search 9?|5 team_id 5?|6 viewer_credentials_only 8?"]}}class XB extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new XB).fromBinary(t,r)}static fromJson(t,r){return(new XB).fromJson(t,r)}static fromJsonString(t,r){return(new XB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(XB,t,r)}static $(){return["GetDeploymentIntegrationAvailabilityRequest"]}}class YB extends T{constructor(t){super(),this.disabledIntegrations=[],this.hiddenIntegrations=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new YB).fromBinary(t,r)}static fromJson(t,r){return(new YB).fromJson(t,r)}static fromJsonString(t,r){return(new YB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(YB,t,r)}static $(){return["GetDeploymentIntegrationAvailabilityResponse|1 disabled_integrations #0*|2 hidden_integrations #0*",xr]}}class ZB extends T{constructor(t){super(),this.code=Er.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ZB).fromBinary(t,r)}static fromJson(t,r){return(new ZB).fromJson(t,r)}static fromJsonString(t,r){return(new ZB).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ZB,t,r)}static $(){return["ScmReason|1 code #0",Er]}}class tI extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tI).fromBinary(t,r)}static fromJson(t,r){return(new tI).fromJson(t,r)}static fromJsonString(t,r){return(new tI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tI,t,r)}static $(){return["GetScmConnectionStatusRequest|1 ghe_application 9?|2 team_id 5?|3 user_scoped 8?"]}}class rI extends T{constructor(t){super(),this.connected=!1,this.grantedInstallationOwners=[],this.providerDisabled=!1,this.health=kr.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rI).fromBinary(t,r)}static fromJson(t,r){return(new rI).fromJson(t,r)}static fromJsonString(t,r){return(new rI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rI,t,r)}static $(){return["GetScmConnectionStatusResponse|1 connected 8|2 granted_installation_owners #0*|3 connected_at_ms 3?|4 provider_disabled 8|5 health #1|6 reason #2?",eI,kr,ZB]}}class eI extends T{constructor(t){super(),this.ownerTeamId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eI).fromBinary(t,r)}static fromJson(t,r){return(new eI).fromJson(t,r)}static fromJsonString(t,r){return(new eI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eI,t,r)}static $(){return["GetScmConnectionStatusResponse.GrantedInstallationOwner|1 owner_team_id 3|2 owner_team_name 9?"]}}class nI extends T{constructor(t){super(),this.gheApplications=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nI).fromBinary(t,r)}static fromJson(t,r){return(new nI).fromJson(t,r)}static fromJsonString(t,r){return(new nI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nI,t,r)}static $(){return["GetScmConnectionStatusesRequest|1 ghe_applications 9*"]}}class sI extends T{constructor(t){super(),this.statuses=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sI).fromBinary(t,r)}static fromJson(t,r){return(new sI).fromJson(t,r)}static fromJsonString(t,r){return(new sI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sI,t,r)}static $(){return["GetScmConnectionStatusesResponse|1 statuses #0*",iI]}}class iI extends T{constructor(t){super(),this.gheApplication="",this.connected=!1,this.failed=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iI).fromBinary(t,r)}static fromJson(t,r){return(new iI).fromJson(t,r)}static fromJsonString(t,r){return(new iI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iI,t,r)}static $(){return["GetScmConnectionStatusesResponse.Status|1 ghe_application 9|2 connected 8|3 connected_at_ms 3?|4 failed 8"]}}class oI extends T{constructor(t){super(),this.repoSlug="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oI).fromBinary(t,r)}static fromJson(t,r){return(new oI).fromJson(t,r)}static fromJsonString(t,r){return(new oI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oI,t,r)}static $(){return["GetGithubRepoAccessStatusRequest|1 repo_slug 9"]}}class aI extends T{constructor(t){super(),this.granted=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aI).fromBinary(t,r)}static fromJson(t,r){return(new aI).fromJson(t,r)}static fromJsonString(t,r){return(new aI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aI,t,r)}static $(){return["GetGithubRepoAccessStatusResponse|1 granted 8"]}}class uI extends T{constructor(t){super(),this.directPush=!1,this.sideBranchDelivery=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uI).fromBinary(t,r)}static fromJson(t,r){return(new uI).fromJson(t,r)}static fromJsonString(t,r){return(new uI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uI,t,r)}static $(){return["BugbotAutofixCapabilities|1 direct_push 8|2 side_branch_delivery 8"]}}class cI extends T{constructor(t){super(),this.autoEnableNewRepos=!1,this.learnedRules=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cI).fromBinary(t,r)}static fromJson(t,r){return(new cI).fromJson(t,r)}static fromJsonString(t,r){return(new cI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cI,t,r)}static $(){return["BugbotSettingsCapabilities|1 auto_enable_new_repos 8|2 learned_rules 8"]}}class lI extends T{constructor(t){super(),this.label="",this.url="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lI).fromBinary(t,r)}static fromJson(t,r){return(new lI).fromJson(t,r)}static fromJsonString(t,r){return(new lI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lI,t,r)}static $(){return["BugbotSetupAction|1 label 9|2 url 9"]}}class mI extends T{constructor(t){super(),this.title="",this.description="",this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mI).fromBinary(t,r)}static fromJson(t,r){return(new mI).fromJson(t,r)}static fromJsonString(t,r){return(new mI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mI,t,r)}static $(){return["BugbotSetupActionRequired|1 title 9|2 description 9|3 action #0?|4 reason 9",lI]}}class fI extends T{constructor(t){super(),this.installations=[],this.githubConnected=!1,this.teamHasBugbotRepos=!1,this.githubUsernames=[],this.ssoRequiredOrgs=[],this.ssoRequiredOrgDisplayNames=[],this.providerDisabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fI).fromBinary(t,r)}static fromJson(t,r){return(new fI).fromJson(t,r)}static fromJsonString(t,r){return(new fI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fI,t,r)}static $(){return["GetGithubInstallationsResponse|1 installations #0*|2 github_connected 8|3 team_has_bugbot_repos 8|4 github_usernames 9*|5 ghe_hostname 9?|6 ghe_app_slug 9?|7 sso_required_orgs 3*|8 sso_required_org_display_names 9*|9 github_app_slug 9?|10 repo_picker_search_debounce_ms 5?|11 reconnect_reason 9?|12 ghe_app_html_url 9?|13 provider_disabled 8",pI]}}class dI extends T{constructor(t){super(),this.installationId=n.protoInt64.zero,this.repoNodeId="",this.owner="",this.name="",this.htmlUrl="",this.archived=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dI).fromBinary(t,r)}static fromJson(t,r){return(new dI).fromJson(t,r)}static fromJsonString(t,r){return(new dI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dI,t,r)}static $(){return["GetGithubInstallationsResponse.Repository|1 installation_id 3|2 repo_node_id 9|3 owner 9|4 name 9|5 html_url 9|6 settings #0|7 archived 8|8 bugbot_enabled_by_team_name 9?",vI]}}class pI extends T{constructor(t){super(),this.installationId=n.protoInt64.zero,this.repos=[],this.canModify=!1,this.hasMoreRepos=!1,this.canModifyInstallationSettings=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pI).fromBinary(t,r)}static fromJson(t,r){return(new pI).fromJson(t,r)}static fromJsonString(t,r){return(new pI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pI,t,r)}static $(){return["GetGithubInstallationsResponse.Installation|1 installation_id 3|2 repos #0*|3 settings #1|4 can_modify 8|5 has_more_repos 8|6 total_pages 5?|7 access_error 9?|9 needs_team_scope 8?|10 can_modify_installation_settings 8|11 account_login 9?|12 autofix_capabilities #2?|13 team_owned 8?|14 settings_capabilities #3?|15 azure_devops_managed 8?|16 setup_action_required #4?|17 can_share_with_other_teams 8?|18 owner_team_id 3?|19 owner_team_name 9?|20 account_type 9?",dI,RI,uI,cI,mI]}}class hI extends T{constructor(t){super(),this.installationId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hI).fromBinary(t,r)}static fromJson(t,r){return(new hI).fromJson(t,r)}static fromJsonString(t,r){return(new hI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hI,t,r)}static $(){return["GetGithubInstallationTenantGrantsRequest|1 installation_id 3|2 ghe_application 9?"]}}class gI extends T{constructor(t){super(),this.teams=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gI).fromBinary(t,r)}static fromJson(t,r){return(new gI).fromJson(t,r)}static fromJsonString(t,r){return(new gI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gI,t,r)}static $(){return["GetGithubInstallationTenantGrantsResponse|1 teams #0*",_I]}}class _I extends T{constructor(t){super(),this.teamId=0,this.teamName="",this.granted=!1,this.stale=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _I).fromBinary(t,r)}static fromJson(t,r){return(new _I).fromJson(t,r)}static fromJsonString(t,r){return(new _I).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_I,t,r)}static $(){return["GetGithubInstallationTenantGrantsResponse.Team|1 team_id 5|2 team_name 9|3 granted 8|4 stale 8"]}}class JI extends T{constructor(t){super(),this.installationId=n.protoInt64.zero,this.targetTeamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new JI).fromBinary(t,r)}static fromJson(t,r){return(new JI).fromJson(t,r)}static fromJsonString(t,r){return(new JI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(JI,t,r)}static $(){return["GrantGithubInstallationTenantRequest|1 installation_id 3|2 ghe_application 9?|3 target_team_id 5"]}}class wI extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wI).fromBinary(t,r)}static fromJson(t,r){return(new wI).fromJson(t,r)}static fromJsonString(t,r){return(new wI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wI,t,r)}static $(){return["GrantGithubInstallationTenantResponse"]}}class yI extends T{constructor(t){super(),this.installationId=n.protoInt64.zero,this.targetTeamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yI).fromBinary(t,r)}static fromJson(t,r){return(new yI).fromJson(t,r)}static fromJsonString(t,r){return(new yI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yI,t,r)}static $(){return["RevokeGithubInstallationTenantRequest|1 installation_id 3|2 ghe_application 9?|3 target_team_id 5"]}}class SI extends T{constructor(t){super(),this.revoked=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new SI).fromBinary(t,r)}static fromJson(t,r){return(new SI).fromJson(t,r)}static fromJsonString(t,r){return(new SI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(SI,t,r)}static $(){return["RevokeGithubInstallationTenantResponse|1 revoked 8"]}}class qI extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qI).fromBinary(t,r)}static fromJson(t,r){return(new qI).fromJson(t,r)}static fromJsonString(t,r){return(new qI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qI,t,r)}static $(){return["GetBugbotSuggestedReposRequest|1 ghe_application 9?|2 limit 5?"]}}class BI extends T{constructor(t){super(),this.repos=[],this.canEnable=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new BI).fromBinary(t,r)}static fromJson(t,r){return(new BI).fromJson(t,r)}static fromJsonString(t,r){return(new BI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(BI,t,r)}static $(){return["GetBugbotSuggestedReposResponse|1 repos #0*|2 can_enable 8",II]}}class II extends T{constructor(t){super(),this.installationId=n.protoInt64.zero,this.repoNodeId="",this.owner="",this.name="",this.htmlUrl="",this.prCountLastWeek=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new II).fromBinary(t,r)}static fromJson(t,r){return(new II).fromJson(t,r)}static fromJsonString(t,r){return(new II).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(II,t,r)}static $(){return["GetBugbotSuggestedReposResponse.SuggestedRepo|1 installation_id 3|2 repo_node_id 9|3 owner 9|4 name 9|5 html_url 9|6 pr_count_last_week 5"]}}class PI extends T{constructor(t){super(),this.agentType=Cr.UNSPECIFIED,this.coveredRepos=[],this.coveredOrgs=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new PI).fromBinary(t,r)}static fromJson(t,r){return(new PI).fromJson(t,r)}static fromJsonString(t,r){return(new PI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(PI,t,r)}static $(){return["GetSecurityAgentSuggestedReposRequest|1 agent_type #0|2 ghe_application 9?|3 limit 5?|4 covered_repos 9*|5 covered_orgs 9*",Cr]}}class bI extends T{constructor(t){super(),this.repos=[],this.canEnable=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bI).fromBinary(t,r)}static fromJson(t,r){return(new bI).fromJson(t,r)}static fromJsonString(t,r){return(new bI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bI,t,r)}static $(){return["GetSecurityAgentSuggestedReposResponse|1 repos #0*|2 can_enable 8",II]}}class RI extends T{constructor(t){super(),this.allowlist=[],this.allowlistConfig=Tr.UNSPECIFIED,this.runOnlyOnce=!1,this.suppressNoBugsComments=!1,this.disableInlineReviews=!1,this.autoEnableNewRepos=!1,this.isPrSummaryEnabled=!1,this.prSummaryUseComment=!1,this.isLearningEnabled=!1,this.bugbotAutofixMode=Ur.UNSPECIFIED,this.enableDraft=!1,this.failGithubActionOnBugbotFindings=!1,this.bugbotAutofixSeverityFilter=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new RI).fromBinary(t,r)}static fromJson(t,r){return(new RI).fromJson(t,r)}static fromJsonString(t,r){return(new RI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(RI,t,r)}static $(){return["InstallationSettings|1 allowlist 9*|2 allowlist_config #0|3 run_only_once 8|4 suppress_no_bugs_comments 8|5 disable_inline_reviews 8|6 auto_enable_new_repos 8|7 is_pr_summary_enabled 8|8 pr_summary_use_comment 8|9 is_learning_enabled 8|10 bugbot_autofix_mode #1|11 enable_draft 8|12 fail_github_action_on_bugbot_findings 8|13 bugbot_autofix_severity_filter 9*|14 is_pr_risk_score_enabled 8?",Tr,Ur]}}class vI extends T{constructor(t){super(),this.bugBotEnabled=!1,this.bugBotManualOnly=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vI).fromBinary(t,r)}static fromJson(t,r){return(new vI).fromJson(t,r)}static fromJsonString(t,r){return(new vI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vI,t,r)}static $(){return["RepoSettings|1 bug_bot_enabled 8|2 bug_bot_manual_only 8|3 bug_bot_learning_enabled 8?|4 bug_bot_learning_inherit_installation_default 8?"]}}class xI extends T{constructor(t){super(),this.installationId=n.protoInt64.zero,this.repoNodeId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xI).fromBinary(t,r)}static fromJson(t,r){return(new xI).fromJson(t,r)}static fromJsonString(t,r){return(new xI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xI,t,r)}static $(){return["RepoIdentifier|1 installation_id 3|2 repo_node_id 9"]}}class kI extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kI).fromBinary(t,r)}static fromJson(t,r){return(new kI).fromJson(t,r)}static fromJsonString(t,r){return(new kI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kI,t,r)}static $(){return["UpdateGithubRepoSettingsRequest|1 repo #0|2 settings #1|3 skip_write_access_check 8?|4 ghe_application 9?|5 team_id 5?",xI,vI]}}class EI extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new EI).fromBinary(t,r)}static fromJson(t,r){return(new EI).fromJson(t,r)}static fromJsonString(t,r){return(new EI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(EI,t,r)}static $(){return["UpdateGithubRepoSettingsResponse"]}}class CI extends T{constructor(t){super(),this.installationId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new CI).fromBinary(t,r)}static fromJson(t,r){return(new CI).fromJson(t,r)}static fromJsonString(t,r){return(new CI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(CI,t,r)}static $(){return["UpdateGithubInstallationSettingsRequest|1 installation_id 3|2 settings #0|4 ghe_application 9?|5 team_id 5?",RI]}}class TI extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new TI).fromBinary(t,r)}static fromJson(t,r){return(new TI).fromJson(t,r)}static fromJsonString(t,r){return(new TI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(TI,t,r)}static $(){return["UpdateGithubInstallationSettingsResponse"]}}class UI extends T{constructor(t){super(),this.installationId=n.protoInt64.zero,this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new UI).fromBinary(t,r)}static fromJson(t,r){return(new UI).fromJson(t,r)}static fromJsonString(t,r){return(new UI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(UI,t,r)}static $(){return["UpdateGithubInstallationTeamScopeRequest|1 installation_id 3|2 ghe_application 9?|3 team_id 5"]}}class AI extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new AI).fromBinary(t,r)}static fromJson(t,r){return(new AI).fromJson(t,r)}static fromJsonString(t,r){return(new AI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(AI,t,r)}static $(){return["UpdateGithubInstallationTeamScopeResponse"]}}class $I extends T{constructor(t){super(),this.installationId=n.protoInt64.zero,this.repoNodeId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $I).fromBinary(t,r)}static fromJson(t,r){return(new $I).fromJson(t,r)}static fromJsonString(t,r){return(new $I).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($I,t,r)}static $(){return["StartBugbotBackfillLearningRequest|1 installation_id 3|2 repo_node_id 9|3 ghe_application 9?|4 skip_write_access_check 8?"]}}class MI extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new MI).fromBinary(t,r)}static fromJson(t,r){return(new MI).fromJson(t,r)}static fromJsonString(t,r){return(new MI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(MI,t,r)}static $(){return["StartBugbotBackfillLearningResponse"]}}class OI extends T{constructor(t){super(),this.workflowId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new OI).fromBinary(t,r)}static fromJson(t,r){return(new OI).fromJson(t,r)}static fromJsonString(t,r){return(new OI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(OI,t,r)}static $(){return["GetBugbotBackfillStatusRequest|1 workflow_id 9"]}}class DI extends T{constructor(t){super(),this.status=Ar.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new DI).fromBinary(t,r)}static fromJson(t,r){return(new DI).fromJson(t,r)}static fromJsonString(t,r){return(new DI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(DI,t,r)}static $(){return["GetBugbotBackfillStatusResponse|1 status #0|2 error_message 9?|3 rules_generated 5?",Ar]}}class NI extends T{constructor(t){super(),this.installationId=n.protoInt64.zero,this.bugBotEnabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new NI).fromBinary(t,r)}static fromJson(t,r){return(new NI).fromJson(t,r)}static fromJsonString(t,r){return(new NI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(NI,t,r)}static $(){return["UpdateAllGithubRepoSettingsRequest|1 installation_id 3|2 bug_bot_enabled 8|3 total_pages 5?|5 include_all_team_owned_repos 8?|6 ghe_application 9?|7 team_id 5?"]}}class GI extends T{constructor(t){super(),this.repoNodeId="",this.reason=LI.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new GI).fromBinary(t,r)}static fromJson(t,r){return(new GI).fromJson(t,r)}static fromJsonString(t,r){return(new GI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(GI,t,r)}static $(){return["UpdateAllGithubRepoSettingsFailure|1 repo_node_id 9|2 reason #0",LI]}}var LI=(0,a.QT)(n.proto3,C,"UpdateAllGithubRepoSettingsFailure.Reason",[[0,"UNSPECIFIED"],[1,"INTERNAL"],[2,"BITBUCKET_WORKSPACE_UNLINKED"],[3,"BITBUCKET_WORKSPACE_LINKED_TO_OTHER_TEAM"],[4,"BITBUCKET_WORKSPACE_CONNECTION_UNVERIFIABLE"],[5,"BUGBOT_ENABLED_BY_OTHER_TEAM"]],1);class FI extends T{constructor(t){super(),this.updatedCount=0,this.asyncOperationStarted=!1,this.asyncOperationAlreadyInProgress=!1,this.failedRepoNodeIds=[],this.failures=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new FI).fromBinary(t,r)}static fromJson(t,r){return(new FI).fromJson(t,r)}static fromJsonString(t,r){return(new FI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(FI,t,r)}static $(){return["UpdateAllGithubRepoSettingsResponse|1 updated_count 5|2 async_operation_started 8|3 async_operation_already_in_progress 8|4 failed_repo_node_ids 9*|5 failures #0*",GI]}}class KI extends T{constructor(t){super(),this.installationId=n.protoInt64.zero,this.operation=zI.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new KI).fromBinary(t,r)}static fromJson(t,r){return(new KI).fromJson(t,r)}static fromJsonString(t,r){return(new KI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(KI,t,r)}static $(){return["UpdateSelfGithubAllowlistRequest|1 installation_id 3|2 operation #0|4 ghe_application 9?",zI]}}var zI=(0,a.QT)(n.proto3,C,"UpdateSelfGithubAllowlistRequest.Operation",[[0,"UNSPECIFIED"],[1,"ADD"],[2,"REMOVE"]],1);class jI extends T{constructor(t){super(),this.allowlist=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jI).fromBinary(t,r)}static fromJson(t,r){return(new jI).fromJson(t,r)}static fromJsonString(t,r){return(new jI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jI,t,r)}static $(){return["UpdateSelfGithubAllowlistResponse|1 allowlist 9*"]}}class HI extends T{constructor(t){super(),this.installationId=n.protoInt64.zero,this.startPage=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new HI).fromBinary(t,r)}static fromJson(t,r){return(new HI).fromJson(t,r)}static fromJsonString(t,r){return(new HI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(HI,t,r)}static $(){return["GetInstallationReposRequest|1 installation_id 3|2 start_page 5|4 ghe_application 9?|5 page_size 5?|6 search 9?|7 include_all_team_owned_repos 8?|8 viewer_credentials_only 8?"]}}class WI extends T{constructor(t){super(),this.repos=[],this.hasMore=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new WI).fromBinary(t,r)}static fromJson(t,r){return(new WI).fromJson(t,r)}static fromJsonString(t,r){return(new WI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(WI,t,r)}static $(){return["GetInstallationReposResponse|1 repos #0*|2 has_more 8|3 access_error 9?",dI]}}class QI extends T{constructor(t){super(),this.installationId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new QI).fromBinary(t,r)}static fromJson(t,r){return(new QI).fromJson(t,r)}static fromJsonString(t,r){return(new QI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(QI,t,r)}static $(){return["FetchAllInstallationReposRequest|1 installation_id 3|2 total_pages 5?|4 include_all_team_owned_repos 8?|5 ghe_application 9?|6 skip_cache 8?|7 viewer_credentials_only 8?"]}}class VI extends T{constructor(t){super(),this.repos=[],this.hasMoreRepos=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new VI).fromBinary(t,r)}static fromJson(t,r){return(new VI).fromJson(t,r)}static fromJsonString(t,r){return(new VI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(VI,t,r)}static $(){return["FetchAllInstallationReposResponse|1 repos #0*|2 access_error 9?|3 has_more_repos 8",dI]}}class XI extends T{constructor(t){super(),this.installationId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new XI).fromBinary(t,r)}static fromJson(t,r){return(new XI).fromJson(t,r)}static fromJsonString(t,r){return(new XI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(XI,t,r)}static $(){return["GetInstallationGithubUsersRequest|1 installation_id 3|4 ghe_application 9?|5 team_id 5?"]}}class YI extends T{constructor(t){super(),this.login="",this.nodeId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new YI).fromBinary(t,r)}static fromJson(t,r){return(new YI).fromJson(t,r)}static fromJsonString(t,r){return(new YI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(YI,t,r)}static $(){return["GithubUser|1 login 9|2 node_id 9|3 hostname 9?"]}}class ZI extends T{constructor(t){super(),this.hasPermission=!1,this.permissionSettingsUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ZI).fromBinary(t,r)}static fromJson(t,r){return(new ZI).fromJson(t,r)}static fromJsonString(t,r){return(new ZI).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ZI,t,r)}static $(){return["GithubPermissionInfo|1 has_permission 8|2 permission_settings_url 9"]}}class tP extends T{constructor(t){super(),this.githubUsers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tP).fromBinary(t,r)}static fromJson(t,r){return(new tP).fromJson(t,r)}static fromJsonString(t,r){return(new tP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tP,t,r)}static $(){return["GetInstallationGithubUsersResponse|1 github_users #0*|2 permission_info #1?",YI,ZI]}}class rP extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rP).fromBinary(t,r)}static fromJson(t,r){return(new rP).fromJson(t,r)}static fromJsonString(t,r){return(new rP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rP,t,r)}static $(){return["GetUserAdminOrganizationsRequest|1 ghe_application_uuid 9?"]}}class eP extends T{constructor(t){super(),this.organizations=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eP).fromBinary(t,r)}static fromJson(t,r){return(new eP).fromJson(t,r)}static fromJsonString(t,r){return(new eP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eP,t,r)}static $(){return["GetUserAdminOrganizationsResponse|1 organizations #0*",nP]}}class nP extends T{constructor(t){super(),this.login="",this.hostname="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nP).fromBinary(t,r)}static fromJson(t,r){return(new nP).fromJson(t,r)}static fromJsonString(t,r){return(new nP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nP,t,r)}static $(){return["GetUserAdminOrganizationsResponse.Organization|1 login 9|2 hostname 9"]}}class sP extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sP).fromBinary(t,r)}static fromJson(t,r){return(new sP).fromJson(t,r)}static fromJsonString(t,r){return(new sP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sP,t,r)}static $(){return["GetTeamGithubUsersRequest|1 team_id 5|3 ghe_application 9?"]}}class iP extends T{constructor(t){super(),this.users=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iP).fromBinary(t,r)}static fromJson(t,r){return(new iP).fromJson(t,r)}static fromJsonString(t,r){return(new iP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iP,t,r)}static $(){return["GetTeamGithubUsersResponse|1 users #0*",YI]}}class oP extends T{constructor(t){super(),this.installationId=n.protoInt64.zero,this.githubUsers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oP).fromBinary(t,r)}static fromJson(t,r){return(new oP).fromJson(t,r)}static fromJsonString(t,r){return(new oP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oP,t,r)}static $(){return["AddGithubUsersToTeamRequest|1 installation_id 3|2 github_users #0*|4 ghe_application 9?",YI]}}class aP extends T{constructor(t){super(),this.addedUserCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aP).fromBinary(t,r)}static fromJson(t,r){return(new aP).fromJson(t,r)}static fromJsonString(t,r){return(new aP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aP,t,r)}static $(){return["AddGithubUsersToTeamResponse|1 added_user_count 5"]}}class uP extends T{constructor(t){super(),this.scope={case:void 0},this.identities=[],this.resolveLoginsViaGithub=!1,this.export=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uP).fromBinary(t,r)}static fromJson(t,r){return(new uP).fromJson(t,r)}static fromJsonString(t,r){return(new uP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uP,t,r)}static $(){return["ResolveGithubIdentitiesRequest|1 team_id 3 scope|2 org_id 3 scope|3 identities #0*|4 resolve_logins_via_github 8|5 export 8",cP]}}class cP extends T{constructor(t){super(),this.identity={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cP).fromBinary(t,r)}static fromJson(t,r){return(new cP).fromJson(t,r)}static fromJsonString(t,r){return(new cP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cP,t,r)}static $(){return["ResolveGithubIdentitiesRequest.Identity|1 github_user_node_id 9 identity|2 github_user_database_id 3 identity|3 login 9 identity"]}}class lP extends T{constructor(t){super(),this.results=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lP).fromBinary(t,r)}static fromJson(t,r){return(new lP).fromJson(t,r)}static fromJsonString(t,r){return(new lP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lP,t,r)}static $(){return["ResolveGithubIdentitiesResponse|1 results #0*",dP]}}class mP extends T{constructor(t){super(),this.teamPublicId="",this.teamName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mP).fromBinary(t,r)}static fromJson(t,r){return(new mP).fromJson(t,r)}static fromJsonString(t,r){return(new mP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mP,t,r)}static $(){return["ResolveGithubIdentitiesResponse.Team|1 team_public_id 9|2 team_name 9"]}}class fP extends T{constructor(t){super(),this.publicId="",this.displayName="",this.email="",this.profileHandle="",this.teams=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fP).fromBinary(t,r)}static fromJson(t,r){return(new fP).fromJson(t,r)}static fromJsonString(t,r){return(new fP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fP,t,r)}static $(){return["ResolveGithubIdentitiesResponse.Match|1 public_id 9|2 display_name 9|3 email 9|4 profile_handle 9|5 teams #0*",mP]}}class dP extends T{constructor(t){super(),this.githubUserNodeId="",this.matches=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dP).fromBinary(t,r)}static fromJson(t,r){return(new dP).fromJson(t,r)}static fromJsonString(t,r){return(new dP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dP,t,r)}static $(){return["ResolveGithubIdentitiesResponse.Result|1 request #0|2 github_user_node_id 9|3 matches #1*|4 resolved_at #2",cP,fP,n.Timestamp]}}class pP extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pP).fromBinary(t,r)}static fromJson(t,r){return(new pP).fromJson(t,r)}static fromJsonString(t,r){return(new pP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pP,t,r)}static $(){return["GetUserPullRequestsRequest|1 repository_filter 9?|2 git_application 9?|3 page 5?|4 page_size 5?|5 search_query 9?|6 author_filter 9?|7 state_filter 9?|8 pr_number 5?"]}}class hP extends T{constructor(t){super(),this.pullRequests=[],this.hasMore=!1,this.hasGitConnection=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hP).fromBinary(t,r)}static fromJson(t,r){return(new hP).fromJson(t,r)}static fromJsonString(t,r){return(new hP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hP,t,r)}static $(){return["GetUserPullRequestsResponse|1 pull_requests #0*|2 has_more 8|3 total_count 5?|4 has_git_connection 8|5 current_user_login 9?",_P]}}class gP extends T{constructor(t){super(),this.id=n.protoInt64.zero,this.nodeId="",this.url="",this.name="",this.description="",this.color="",this.isDefault=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gP).fromBinary(t,r)}static fromJson(t,r){return(new gP).fromJson(t,r)}static fromJsonString(t,r){return(new gP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gP,t,r)}static $(){return["PullRequestLabel|1 id 3|2 node_id 9|3 url 9|4 name 9|5 description 9|6 color 9|7 is_default 8"]}}class _P extends T{constructor(t){super(),this.number=0,this.title="",this.state="",this.url="",this.repository="",this.createdAt="",this.updatedAt="",this.isDraft=!1,this.author="",this.description="",this.labels=[],this.headRef="",this.baseRef="",this.comments=0,this.reviewComments=0,this.mergedAt="",this.closedAt="",this.descriptionRaw="",this.headSha="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _P).fromBinary(t,r)}static fromJson(t,r){return(new _P).fromJson(t,r)}static fromJsonString(t,r){return(new _P).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_P,t,r)}static $(){return["UserPullRequest|1 number 5|2 title 9|3 state 9|4 url 9|5 repository 9|6 created_at 9|7 updated_at 9|8 is_draft 8|9 author 9|10 description 9|11 labels #0*|12 head_ref 9|13 base_ref 9|14 comments 5|15 review_comments 5|16 merged_at 9|17 closed_at 9|18 description_raw 9|19 head_sha 9",gP]}}class JP extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new JP).fromBinary(t,r)}static fromJson(t,r){return(new JP).fromJson(t,r)}static fromJsonString(t,r){return(new JP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(JP,t,r)}static $(){return["GetUserReviewRequestsRequest|1 repository_filter 9?|2 git_application 9?|3 page 5?|4 page_size 5?|5 search_query 9?|6 state_filter 9?"]}}class wP extends T{constructor(t){super(),this.pullRequests=[],this.hasMore=!1,this.hasGitConnection=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wP).fromBinary(t,r)}static fromJson(t,r){return(new wP).fromJson(t,r)}static fromJsonString(t,r){return(new wP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wP,t,r)}static $(){return["GetUserReviewRequestsResponse|1 pull_requests #0*|2 has_more 8|3 total_count 5?|4 has_git_connection 8|5 current_user_login 9?",_P]}}class yP extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yP).fromBinary(t,r)}static fromJson(t,r){return(new yP).fromJson(t,r)}static fromJsonString(t,r){return(new yP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yP,t,r)}static $(){return["GetBugbotUserSettingsRequest|1 team_id 5?"]}}class SP extends T{constructor(t){super(),this.manualTriggerOnly=!1,this.runOnlyOnce=!1,this.suppressNoBugsComments=!1,this.bugbotAutofixMode=Ur.UNSPECIFIED,this.enableVmRun=!1,this.failGithubActionOnBugbotFindings=!1,this.bugbotAutofixSeverityFilter=[],this.installationDefaultBugbotAutofixMode=Ur.UNSPECIFIED,this.installationDefaultBugbotAutofixSeverityFilter=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new SP).fromBinary(t,r)}static fromJson(t,r){return(new SP).fromJson(t,r)}static fromJsonString(t,r){return(new SP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(SP,t,r)}static $(){return["GetBugbotUserSettingsResponse|1 manual_trigger_only 8|2 run_only_once 8|3 suppress_no_bugs_comments 8|4 enable_draft 8?|5 is_pr_summary_enabled 8?|6 bugbot_autofix_mode #0|7 enable_vm_run 8|8 fail_github_action_on_bugbot_findings 8|9 bugbot_autofix_severity_filter 9*|10 installation_default_enable_draft 8?|11 installation_default_is_pr_summary_enabled 8?|12 installation_default_bugbot_autofix_mode #0|13 installation_default_bugbot_autofix_severity_filter 9*|14 is_incremental_review_enabled 8?|15 team_default_is_incremental_review_enabled 8?|16 is_pr_risk_score_enabled 8?|17 installation_default_is_pr_risk_score_enabled 8?|18 installation_default_enable_draft_mixed 8?|19 installation_default_is_pr_summary_enabled_mixed 8?|20 installation_default_is_pr_risk_score_enabled_mixed 8?|21 installation_default_bugbot_autofix_mode_mixed 8?|22 installation_default_bugbot_autofix_severity_filter_mixed 8?",Ur]}}class qP extends T{constructor(t){super(),this.manualTriggerOnly=!1,this.runOnlyOnce=!1,this.suppressNoBugsComments=!1,this.bugbotAutofixMode=Ur.UNSPECIFIED,this.enableVmRun=!1,this.failGithubActionOnBugbotFindings=!1,this.bugbotAutofixSeverityFilter=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qP).fromBinary(t,r)}static fromJson(t,r){return(new qP).fromJson(t,r)}static fromJsonString(t,r){return(new qP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qP,t,r)}static $(){return["UpdateBugbotUserSettingsRequest|1 manual_trigger_only 8|2 run_only_once 8|3 suppress_no_bugs_comments 8|4 enable_draft 8?|5 is_pr_summary_enabled 8?|6 bugbot_autofix_mode #0|7 enable_vm_run 8|8 fail_github_action_on_bugbot_findings 8|9 bugbot_autofix_severity_filter 9*|10 is_incremental_review_enabled 8?|11 is_pr_risk_score_enabled 8?",Ur]}}class BP extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new BP).fromBinary(t,r)}static fromJson(t,r){return(new BP).fromJson(t,r)}static fromJsonString(t,r){return(new BP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(BP,t,r)}static $(){return["UpdateBugbotUserSettingsResponse"]}}class IP extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new IP).fromBinary(t,r)}static fromJson(t,r){return(new IP).fromJson(t,r)}static fromJsonString(t,r){return(new IP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(IP,t,r)}static $(){return["GetFullSelfDrivingUserSettingsRequest"]}}class PP extends T{constructor(t){super(),this.defaultMode=g.UNSPECIFIED,this.onlyCloudAgentPrs=!1,this.globallyDisabled=!1,this.autoCreateOnFirstPrPush=!1,this.slackNotificationsEnabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new PP).fromBinary(t,r)}static fromJson(t,r){return(new PP).fromJson(t,r)}static fromJsonString(t,r){return(new PP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(PP,t,r)}static $(){return["GetFullSelfDrivingUserSettingsResponse|1 default_mode #0|2 only_cloud_agent_prs 8|3 globally_disabled 8|4 auto_create_on_first_pr_push 8|5 slack_notifications_enabled 8|6 fsd_slack_channel_id 9?|7 default_model 9?",g]}}class bP extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bP).fromBinary(t,r)}static fromJson(t,r){return(new bP).fromJson(t,r)}static fromJsonString(t,r){return(new bP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bP,t,r)}static $(){return["UpdateFullSelfDrivingUserSettingsRequest|1 default_mode #0?|2 only_cloud_agent_prs 8?|3 globally_disabled 8?|4 auto_create_on_first_pr_push 8?|5 slack_notifications_enabled 8?|6 fsd_slack_channel_id 9?|7 default_model 9?",g]}}class RP extends T{constructor(t){super(),this.defaultMode=g.UNSPECIFIED,this.onlyCloudAgentPrs=!1,this.globallyDisabled=!1,this.autoCreateOnFirstPrPush=!1,this.slackNotificationsEnabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new RP).fromBinary(t,r)}static fromJson(t,r){return(new RP).fromJson(t,r)}static fromJsonString(t,r){return(new RP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(RP,t,r)}static $(){return["UpdateFullSelfDrivingUserSettingsResponse|1 default_mode #0|2 only_cloud_agent_prs 8|3 globally_disabled 8|4 auto_create_on_first_pr_push 8|5 slack_notifications_enabled 8|6 fsd_slack_channel_id 9?|7 default_model 9?",g]}}class vP extends T{constructor(t){super(),this.scmProvider=At.UNSPECIFIED,this.scmRepoNodeId="",this.repoUrl="",this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vP).fromBinary(t,r)}static fromJson(t,r){return(new vP).fromJson(t,r)}static fromJsonString(t,r){return(new vP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vP,t,r)}static $(){return["FullSelfDrivingRepoSetting|1 scm_provider #0|2 git_enterprise_uuid 9?|3 scm_repo_node_id 9|4 repo_url 9|5 enabled 8",At]}}class xP extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xP).fromBinary(t,r)}static fromJson(t,r){return(new xP).fromJson(t,r)}static fromJsonString(t,r){return(new xP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xP,t,r)}static $(){return["ListFullSelfDrivingRepoSettingsRequest"]}}class kP extends T{constructor(t){super(),this.repos=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kP).fromBinary(t,r)}static fromJson(t,r){return(new kP).fromJson(t,r)}static fromJsonString(t,r){return(new kP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kP,t,r)}static $(){return["ListFullSelfDrivingRepoSettingsResponse|1 repos #0*",vP]}}class EP extends T{constructor(t){super(),this.scmProvider=At.UNSPECIFIED,this.scmRepoNodeId="",this.repoUrl="",this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new EP).fromBinary(t,r)}static fromJson(t,r){return(new EP).fromJson(t,r)}static fromJsonString(t,r){return(new EP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(EP,t,r)}static $(){return["SetFullSelfDrivingRepoEnabledRequest|1 scm_provider #0|2 git_enterprise_uuid 9?|3 scm_repo_node_id 9|4 repo_url 9|5 enabled 8",At]}}class CP extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new CP).fromBinary(t,r)}static fromJson(t,r){return(new CP).fromJson(t,r)}static fromJsonString(t,r){return(new CP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(CP,t,r)}static $(){return["SetFullSelfDrivingRepoEnabledResponse|1 repo #0",vP]}}class TP extends T{constructor(t){super(),this.teamId=0,this.defaultMode=g.UNSPECIFIED,this.onlyCloudAgentPrs=!1,this.globallyDisabled=!1,this.autoCreateOnFirstPrPush=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new TP).fromBinary(t,r)}static fromJson(t,r){return(new TP).fromJson(t,r)}static fromJsonString(t,r){return(new TP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(TP,t,r)}static $(){return["FullSelfDrivingTeamSettings|1 team_id 5|2 default_mode #0|3 only_cloud_agent_prs 8|4 globally_disabled 8|5 auto_create_on_first_pr_push 8",g]}}class UP extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new UP).fromBinary(t,r)}static fromJson(t,r){return(new UP).fromJson(t,r)}static fromJsonString(t,r){return(new UP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(UP,t,r)}static $(){return["GetFullSelfDrivingTeamSettingsRequest|1 team_id 5"]}}class AP extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new AP).fromBinary(t,r)}static fromJson(t,r){return(new AP).fromJson(t,r)}static fromJsonString(t,r){return(new AP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(AP,t,r)}static $(){return["GetFullSelfDrivingTeamSettingsResponse|1 settings #0",TP]}}class $P extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $P).fromBinary(t,r)}static fromJson(t,r){return(new $P).fromJson(t,r)}static fromJsonString(t,r){return(new $P).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($P,t,r)}static $(){return["UpdateFullSelfDrivingTeamSettingsRequest|1 team_id 5|2 default_mode #0?|3 only_cloud_agent_prs 8?|4 globally_disabled 8?|5 auto_create_on_first_pr_push 8?",g]}}class MP extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new MP).fromBinary(t,r)}static fromJson(t,r){return(new MP).fromJson(t,r)}static fromJsonString(t,r){return(new MP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(MP,t,r)}static $(){return["UpdateFullSelfDrivingTeamSettingsResponse|1 settings #0",TP]}}class OP extends T{constructor(t){super(),this.teamId=0,this.scmProvider=At.UNSPECIFIED,this.scmRepoNodeId="",this.repoUrl="",this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new OP).fromBinary(t,r)}static fromJson(t,r){return(new OP).fromJson(t,r)}static fromJsonString(t,r){return(new OP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(OP,t,r)}static $(){return["FullSelfDrivingTeamRepoSetting|1 team_id 5|2 scm_provider #0|3 git_enterprise_uuid 9?|4 scm_repo_node_id 9|5 repo_url 9|6 enabled 8",At]}}class DP extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new DP).fromBinary(t,r)}static fromJson(t,r){return(new DP).fromJson(t,r)}static fromJsonString(t,r){return(new DP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(DP,t,r)}static $(){return["ListFullSelfDrivingTeamRepoSettingsRequest|1 team_id 5"]}}class NP extends T{constructor(t){super(),this.repos=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new NP).fromBinary(t,r)}static fromJson(t,r){return(new NP).fromJson(t,r)}static fromJsonString(t,r){return(new NP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(NP,t,r)}static $(){return["ListFullSelfDrivingTeamRepoSettingsResponse|1 repos #0*",OP]}}class GP extends T{constructor(t){super(),this.teamId=0,this.scmProvider=At.UNSPECIFIED,this.scmRepoNodeId="",this.repoUrl="",this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new GP).fromBinary(t,r)}static fromJson(t,r){return(new GP).fromJson(t,r)}static fromJsonString(t,r){return(new GP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(GP,t,r)}static $(){return["SetFullSelfDrivingTeamRepoEnabledRequest|1 team_id 5|2 scm_provider #0|3 git_enterprise_uuid 9?|4 scm_repo_node_id 9|5 repo_url 9|6 enabled 8",At]}}class LP extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new LP).fromBinary(t,r)}static fromJson(t,r){return(new LP).fromJson(t,r)}static fromJsonString(t,r){return(new LP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(LP,t,r)}static $(){return["SetFullSelfDrivingTeamRepoEnabledResponse|1 repo #0",OP]}}class FP extends T{constructor(t){super(),this.prUrl="",this.repoUrl="",this.pullNumber=0,this.bcId="",this.enabled=!1,this.mode=g.UNSPECIFIED,this.ownerUserId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new FP).fromBinary(t,r)}static fromJson(t,r){return(new FP).fromJson(t,r)}static fromJsonString(t,r){return(new FP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(FP,t,r)}static $(){return["FullSelfDrivingActiveAgent|1 pr_url 9|2 repo_url 9|3 pull_number 5|4 bc_id 9|5 enabled 8|6 mode #0|7 owner_user_id 5|8 owner_display_name 9?|9 owner_email 9?|10 mergeable_state 9?|11 is_mergeable 8?|12 visible_findings_count 5?|13 latest_status_update #1?|14 pr_title 9?",g,KP]}}class KP extends T{constructor(t){super(),this.state="",this.status="",this.loadingMessages=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new KP).fromBinary(t,r)}static fromJson(t,r){return(new KP).fromJson(t,r)}static fromJsonString(t,r){return(new KP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(KP,t,r)}static $(){return["FullSelfDrivingStatusUpdate|1 state 9|2 status 9|3 loading_messages 9*|4 updated_at #0",n.Timestamp]}}class zP extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zP).fromBinary(t,r)}static fromJson(t,r){return(new zP).fromJson(t,r)}static fromJsonString(t,r){return(new zP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zP,t,r)}static $(){return["ListFullSelfDrivingActiveAgentsRequest|1 search_query 9?|2 page 5?|3 page_size 5?|4 archived 8?|5 status_visual 9?"]}}class jP extends T{constructor(t){super(),this.agents=[],this.totalCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jP).fromBinary(t,r)}static fromJson(t,r){return(new jP).fromJson(t,r)}static fromJsonString(t,r){return(new jP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jP,t,r)}static $(){return["ListFullSelfDrivingActiveAgentsResponse|1 agents #0*|2 total_count 5",FP]}}class HP extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new HP).fromBinary(t,r)}static fromJson(t,r){return(new HP).fromJson(t,r)}static fromJsonString(t,r){return(new HP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(HP,t,r)}static $(){return["ListFullSelfDrivingTeamActiveAgentsRequest|1 team_id 5|2 search_query 9?|3 page 5?|4 page_size 5?|5 archived 8?"]}}class WP extends T{constructor(t){super(),this.agents=[],this.totalCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new WP).fromBinary(t,r)}static fromJson(t,r){return(new WP).fromJson(t,r)}static fromJsonString(t,r){return(new WP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(WP,t,r)}static $(){return["ListFullSelfDrivingTeamActiveAgentsResponse|1 agents #0*|2 total_count 5",FP]}}class QP extends T{constructor(t){super(),this.prUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new QP).fromBinary(t,r)}static fromJson(t,r){return(new QP).fromJson(t,r)}static fromJsonString(t,r){return(new QP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(QP,t,r)}static $(){return["UpdateFullSelfDrivingPrConfigRequest|1 pr_url 9|2 enabled 8?|3 mode #0?|4 team_id 5?",g]}}class VP extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new VP).fromBinary(t,r)}static fromJson(t,r){return(new VP).fromJson(t,r)}static fromJsonString(t,r){return(new VP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(VP,t,r)}static $(){return["UpdateFullSelfDrivingPrConfigResponse|1 agent #0",FP]}}class XP extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new XP).fromBinary(t,r)}static fromJson(t,r){return(new XP).fromJson(t,r)}static fromJsonString(t,r){return(new XP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(XP,t,r)}static $(){return["GetBugBotProUserSettingsRequest"]}}class YP extends T{constructor(t){super(),this.enabled=!1,this.bugbotWasEnabledInThisBillingCycle=!1,this.bugbotUsageTier=$r.UNSPECIFIED,this.bugbotBillingMode=Mr.UNSPECIFIED,this.canMigrateToUsageBased=!1,this.seatLicenseCount=0,this.bugbotUsageBasedOnEnable=!1,this.bugbotMigrationCreditAlreadyGranted=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new YP).fromBinary(t,r)}static fromJson(t,r){return(new YP).fromJson(t,r)}static fromJsonString(t,r){return(new YP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(YP,t,r)}static $(){return["GetBugBotProUserSettingsResponse|1 enabled 8|2 bugbot_was_enabled_in_this_billing_cycle 8|3 bugbot_usage_tier #0|4 bugbot_billing_mode #1|5 can_migrate_to_usage_based 8|6 seat_license_count 5|7 bugbot_usage_based_on_enable 8|8 bugbot_migration_credit_already_granted 8",$r,Mr]}}class ZP extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ZP).fromBinary(t,r)}static fromJson(t,r){return(new ZP).fromJson(t,r)}static fromJsonString(t,r){return(new ZP).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ZP,t,r)}static $(){return["UpdateBugBotProUserSettingsRequest|1 enabled 8"]}}class tb extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tb).fromBinary(t,r)}static fromJson(t,r){return(new tb).fromJson(t,r)}static fromJsonString(t,r){return(new tb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tb,t,r)}static $(){return["UpdateBugBotProUserSettingsResponse"]}}class rb extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rb).fromBinary(t,r)}static fromJson(t,r){return(new rb).fromJson(t,r)}static fromJsonString(t,r){return(new rb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rb,t,r)}static $(){return["MigrateBugBotProUserToUsageBasedBillingRequest|1 keep_high_effort_default 8?"]}}class eb extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eb).fromBinary(t,r)}static fromJson(t,r){return(new eb).fromJson(t,r)}static fromJsonString(t,r){return(new eb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eb,t,r)}static $(){return["MigrateBugBotProUserToUsageBasedBillingResponse"]}}class nb extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nb).fromBinary(t,r)}static fromJson(t,r){return(new nb).fromJson(t,r)}static fromJsonString(t,r){return(new nb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nb,t,r)}static $(){return["GetGlassEarlyPreviewEnrollmentRequest"]}}class sb extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sb).fromBinary(t,r)}static fromJson(t,r){return(new sb).fromJson(t,r)}static fromJsonString(t,r){return(new sb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sb,t,r)}static $(){return["GetGlassEarlyPreviewEnrollmentResponse|1 enabled 8|2 enterprise_glass_self_enroll_eligible 8?|3 glass_access_granted 8?"]}}class ib extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ib).fromBinary(t,r)}static fromJson(t,r){return(new ib).fromJson(t,r)}static fromJsonString(t,r){return(new ib).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ib,t,r)}static $(){return["EnrollInGlassEarlyPreviewRequest"]}}class ob extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ob).fromBinary(t,r)}static fromJson(t,r){return(new ob).fromJson(t,r)}static fromJsonString(t,r){return(new ob).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ob,t,r)}static $(){return["EnrollInGlassEarlyPreviewResponse"]}}class ab extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ab).fromBinary(t,r)}static fromJson(t,r){return(new ab).fromJson(t,r)}static fromJsonString(t,r){return(new ab).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ab,t,r)}static $(){return["UnenrollFromGlassEarlyPreviewRequest"]}}class ub extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ub).fromBinary(t,r)}static fromJson(t,r){return(new ub).fromJson(t,r)}static fromJsonString(t,r){return(new ub).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ub,t,r)}static $(){return["UnenrollFromGlassEarlyPreviewResponse"]}}class cb extends T{constructor(t){super(),this.bugId="",this.event=lb.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cb).fromBinary(t,r)}static fromJson(t,r){return(new cb).fromJson(t,r)}static fromJsonString(t,r){return(new cb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cb,t,r)}static $(){return["RecordBugbotDeeplinkEventRequest|1 bug_id 9|2 event #0|3 comment_id 9?",lb]}}var lb=(0,a.QT)(n.proto3,C,"RecordBugbotDeeplinkEventRequest.BugbotDeeplinkEvent",[[0,"UNSPECIFIED"],[1,"CLICKED"],[2,"HANDLED_DIALOG_SHOWN"],[3,"HANDLED_CHAT_CREATED"],[4,"ERROR"],[5,"HANDLED_FIX_IN_WEB"]],1);class mb extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mb).fromBinary(t,r)}static fromJson(t,r){return(new mb).fromJson(t,r)}static fromJsonString(t,r){return(new mb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mb,t,r)}static $(){return["RecordBugbotDeeplinkEventResponse"]}}class fb extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fb).fromBinary(t,r)}static fromJson(t,r){return(new fb).fromJson(t,r)}static fromJsonString(t,r){return(new fb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fb,t,r)}static $(){return["GetFilteredUsageEventsRequest|1 team_id 5|2 start_date 3?|3 end_date 3?|4 user_id 5?|5 model_id 9?|6 page 5?|7 page_size 5?|8 service_account_id 9?|9 cloud_agent_id 9?|10 automation_id 9?|11 automation_managed_type 9?|12 client_type 9?"]}}class db extends T{constructor(t){super(),this.usageEvents=[],this.totalUsageEventsCount=0,this.usageEventsDisplay=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new db).fromBinary(t,r)}static fromJson(t,r){return(new db).fromJson(t,r)}static fromJsonString(t,r){return(new db).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(db,t,r)}static $(){return["GetFilteredUsageEventsResponse|1 usage_events #0*|2 total_usage_events_count 5|3 usage_events_display #1*",i.aq,i.GF]}}class pb extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pb).fromBinary(t,r)}static fromJson(t,r){return(new pb).fromJson(t,r)}static fromJsonString(t,r){return(new pb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pb,t,r)}static $(){return["GetAggregatedUsageEventsRequest|1 team_id 5|2 start_date 3?|3 end_date 3?|4 user_id 5?|5 use_monthly_billing_cycle_start 8?"]}}class hb extends T{constructor(t){super(),this.aggregations=[],this.totalInputTokens=n.protoInt64.zero,this.totalOutputTokens=n.protoInt64.zero,this.totalCacheWriteTokens=n.protoInt64.zero,this.totalCacheReadTokens=n.protoInt64.zero,this.totalCostCents=0,this.percentOfBurstUsed=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hb).fromBinary(t,r)}static fromJson(t,r){return(new hb).fromJson(t,r)}static fromJsonString(t,r){return(new hb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hb,t,r)}static $(){return["GetAggregatedUsageEventsResponse|1 aggregations #0*|2 total_input_tokens 3|3 total_output_tokens 3|4 total_cache_write_tokens 3|5 total_cache_read_tokens 3|6 total_cost_cents 1|7 percent_of_burst_used 1|8 total_request_cost 1?|9 start_date 3?",gb]}}class gb extends T{constructor(t){super(),this.modelIntent="",this.inputTokens=n.protoInt64.zero,this.outputTokens=n.protoInt64.zero,this.cacheWriteTokens=n.protoInt64.zero,this.cacheReadTokens=n.protoInt64.zero,this.totalCents=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gb).fromBinary(t,r)}static fromJson(t,r){return(new gb).fromJson(t,r)}static fromJsonString(t,r){return(new gb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gb,t,r)}static $(){return["GetAggregatedUsageEventsResponse.ModelUsageAggregation|1 model_intent 9|2 input_tokens 3|3 output_tokens 3|4 cache_write_tokens 3|5 cache_read_tokens 3|6 total_cents 1|7 request_cost 1?|8 tier 5?"]}}class _b extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _b).fromBinary(t,r)}static fromJson(t,r){return(new _b).fromJson(t,r)}static fromJsonString(t,r){return(new _b).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_b,t,r)}static $(){return["GetAuditLogsRequest|1 team_id 5?|2 start_date 3?|3 end_date 3?|4 event_type 9?|5 search 9?|6 page 5?|7 page_size 5?|8 application_type 9?|9 actor_api_key_id 9?|10 actor_api_key_kind 9?"]}}class Jb extends T{constructor(t){super(),this.events=[],this.totalCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jb).fromBinary(t,r)}static fromJson(t,r){return(new Jb).fromJson(t,r)}static fromJsonString(t,r){return(new Jb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jb,t,r)}static $(){return["GetAuditLogsResponse|1 events #0*|2 total_count 5",bb]}}class wb extends T{constructor(t){super(),this.taskHandle="",this.createdAtMs=n.protoInt64.zero,this.sizeBytes=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wb).fromBinary(t,r)}static fromJson(t,r){return(new wb).fromJson(t,r)}static fromJsonString(t,r){return(new wb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wb,t,r)}static $(){return["TeamDataExportArchive|1 task_handle 9|2 created_at_ms 3|3 size_bytes 3"]}}class yb extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yb).fromBinary(t,r)}static fromJson(t,r){return(new yb).fromJson(t,r)}static fromJsonString(t,r){return(new yb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yb,t,r)}static $(){return["ListTeamDataExportsRequest|1 team_id 5?"]}}class Sb extends T{constructor(t){super(),this.archives=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sb).fromBinary(t,r)}static fromJson(t,r){return(new Sb).fromJson(t,r)}static fromJsonString(t,r){return(new Sb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sb,t,r)}static $(){return["ListTeamDataExportsResponse|1 archives #0*",wb]}}class qb extends T{constructor(t){super(),this.taskHandle="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qb).fromBinary(t,r)}static fromJson(t,r){return(new qb).fromJson(t,r)}static fromJsonString(t,r){return(new qb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qb,t,r)}static $(){return["CreateTeamDataExportDownloadUrlRequest|1 team_id 5?|2 task_handle 9"]}}class Bb extends T{constructor(t){super(),this.url="",this.expiresAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bb).fromBinary(t,r)}static fromJson(t,r){return(new Bb).fromJson(t,r)}static fromJsonString(t,r){return(new Bb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bb,t,r)}static $(){return["CreateTeamDataExportDownloadUrlResponse|1 url 9|2 expires_at_ms 3"]}}class Ib extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ib).fromBinary(t,r)}static fromJson(t,r){return(new Ib).fromJson(t,r)}static fromJsonString(t,r){return(new Ib).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ib,t,r)}static $(){return["GetOrganizationAuditLogsRequest|1 organization_id 9|2 team_id 5?|3 start_date 3?|4 end_date 3?|5 event_type 9?|6 search 9?|7 page 5?|8 page_size 5?|9 application_type 9?|10 actor_api_key_id 9?|11 actor_api_key_kind 9?"]}}class Pb extends T{constructor(t){super(),this.events=[],this.totalCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pb).fromBinary(t,r)}static fromJson(t,r){return(new Pb).fromJson(t,r)}static fromJsonString(t,r){return(new Pb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pb,t,r)}static $(){return["GetOrganizationAuditLogsResponse|1 events #0*|2 total_count 5",bb]}}class bb extends T{constructor(t){super(),this.id=n.protoInt64.zero,this.createdAt="",this.eventId="",this.timestamp="",this.requestId="",this.authId="",this.ghostMode=!1,this.teamId="",this.ipAddress="",this.userEmail="",this.eventType="",this.eventData="",this.orgId="",this.applicationType="",this.actorApiKeyKind="",this.actorApiKeyId="",this.actorApiKeyName="",this.actorDelegatedUserEmail="",this.userId="",this.clientType="",this.clientVersion="",this.clientOs="",this.clientOsVersion="",this.clientDeviceType="",this.clientUserAgent="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bb).fromBinary(t,r)}static fromJson(t,r){return(new bb).fromJson(t,r)}static fromJsonString(t,r){return(new bb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bb,t,r)}static $(){return["AuditLogEvent|1 id 3|2 created_at 9|3 event_id 9|4 timestamp 9|5 request_id 9|6 auth_id 9|7 ghost_mode 8|8 team_id 9|9 ip_address 9|10 user_email 9|11 event_type 9|12 event_data 9|13 org_id 9|14 application_type 9|15 actor_api_key_kind 9|16 actor_api_key_id 9|17 actor_api_key_name 9|18 actor_delegated_user_email 9|19 user_id 9|20 client_type 9|21 client_version 9|22 client_os 9|23 client_os_version 9|24 client_device_type 9|25 client_user_agent 9"]}}class Rb extends T{constructor(t){super(),this.inviteCode="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rb).fromBinary(t,r)}static fromJson(t,r){return(new Rb).fromJson(t,r)}static fromJsonString(t,r){return(new Rb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rb,t,r)}static $(){return["RevokeTeamInviteLinkRequest|1 invite_code 9"]}}class vb extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vb).fromBinary(t,r)}static fromJson(t,r){return(new vb).fromJson(t,r)}static fromJsonString(t,r){return(new vb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vb,t,r)}static $(){return["RevokeTeamInviteLinkResponse"]}}class xb extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xb).fromBinary(t,r)}static fromJson(t,r){return(new xb).fromJson(t,r)}static fromJsonString(t,r){return(new xb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xb,t,r)}static $(){return["ListTeamInviteLinksRequest|1 team_id 5|2 castle_request_token 9?"]}}class kb extends T{constructor(t){super(),this.inviteLink="",this.validUntil=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kb).fromBinary(t,r)}static fromJson(t,r){return(new kb).fromJson(t,r)}static fromJsonString(t,r){return(new kb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kb,t,r)}static $(){return["InviteLinkInfo|1 invite_link 9|2 valid_until 3"]}}class Eb extends T{constructor(t){super(),this.inviteLinks=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Eb).fromBinary(t,r)}static fromJson(t,r){return(new Eb).fromJson(t,r)}static fromJsonString(t,r){return(new Eb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Eb,t,r)}static $(){return["ListTeamInviteLinksResponse|1 invite_links #0*",kb]}}class Cb extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cb).fromBinary(t,r)}static fromJson(t,r){return(new Cb).fromJson(t,r)}static fromJsonString(t,r){return(new Cb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cb,t,r)}static $(){return["ListTeamInviteLinksInternalRequest|1 team_id 5"]}}class Tb extends T{constructor(t){super(),this.inviteId="",this.validUntilMs=n.protoInt64.zero,this.kind="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tb).fromBinary(t,r)}static fromJson(t,r){return(new Tb).fromJson(t,r)}static fromJsonString(t,r){return(new Tb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tb,t,r)}static $(){return["InternalTeamInviteLink|1 invite_id 9|2 valid_until_ms 3|3 kind 9|4 creator_user_id 5?|5 created_at_ms 3?"]}}class Ub extends T{constructor(t){super(),this.inviteLinks=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ub).fromBinary(t,r)}static fromJson(t,r){return(new Ub).fromJson(t,r)}static fromJsonString(t,r){return(new Ub).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ub,t,r)}static $(){return["ListTeamInviteLinksInternalResponse|1 invite_links #0*",Tb]}}class Ab extends T{constructor(t){super(),this.teamId=0,this.inviteIds=[],this.revokeAll=!1,this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ab).fromBinary(t,r)}static fromJson(t,r){return(new Ab).fromJson(t,r)}static fromJsonString(t,r){return(new Ab).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ab,t,r)}static $(){return["RevokeTeamInviteLinksInternalRequest|1 team_id 5|2 invite_ids 9*|3 revoke_all 8|4 reason 9"]}}class $b extends T{constructor(t){super(),this.inviteId="",this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $b).fromBinary(t,r)}static fromJson(t,r){return(new $b).fromJson(t,r)}static fromJsonString(t,r){return(new $b).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($b,t,r)}static $(){return["RevokeTeamInviteLinksInternalFailure|1 invite_id 9|2 message 9"]}}class Mb extends T{constructor(t){super(),this.revokedInviteIds=[],this.failures=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mb).fromBinary(t,r)}static fromJson(t,r){return(new Mb).fromJson(t,r)}static fromJsonString(t,r){return(new Mb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mb,t,r)}static $(){return["RevokeTeamInviteLinksInternalResponse|1 revoked_invite_ids 9*|2 failures #0*",$b]}}class Ob extends T{constructor(t){super(),this.inviteId="",this.email="",this.role=it.UNSPECIFIED,this.expiresAt=n.protoInt64.zero,this.purchaseState=Dr.UNSPECIFIED,this.canResend=!1,this.recipientJoined=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ob).fromBinary(t,r)}static fromJson(t,r){return(new Ob).fromJson(t,r)}static fromJsonString(t,r){return(new Ob).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ob,t,r)}static $(){return["TeamPendingInvite|1 invite_id 9|2 email 9|3 role #0|4 billing_tier #1?|5 invited_by_email 9?|6 created_at 3?|7 expires_at 3|8 purchase_state #2|9 purchase_attempt 5?|10 can_resend 8|11 recipient_joined 8|12 merged_seat_tier #3?",it,ot,Dr,at]}}class Db extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Db).fromBinary(t,r)}static fromJson(t,r){return(new Db).fromJson(t,r)}static fromJsonString(t,r){return(new Db).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Db,t,r)}static $(){return["ListTeamPendingInvitesRequest|1 team_id 5"]}}class Nb extends T{constructor(t){super(),this.invites=[],this.membershipManaged=!1,this.truncated=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nb).fromBinary(t,r)}static fromJson(t,r){return(new Nb).fromJson(t,r)}static fromJsonString(t,r){return(new Nb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nb,t,r)}static $(){return["ListTeamPendingInvitesResponse|1 invites #0*|2 membership_managed 8|3 truncated 8",Ob]}}class Gb extends T{constructor(t){super(),this.teamId=0,this.inviteId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gb).fromBinary(t,r)}static fromJson(t,r){return(new Gb).fromJson(t,r)}static fromJsonString(t,r){return(new Gb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gb,t,r)}static $(){return["RevokeTeamPendingInviteRequest|1 team_id 5|2 invite_id 9"]}}class Lb extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lb).fromBinary(t,r)}static fromJson(t,r){return(new Lb).fromJson(t,r)}static fromJsonString(t,r){return(new Lb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Lb,t,r)}static $(){return["RevokeTeamPendingInviteResponse"]}}class Fb extends T{constructor(t){super(),this.teamId=0,this.inviteId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fb).fromBinary(t,r)}static fromJson(t,r){return(new Fb).fromJson(t,r)}static fromJsonString(t,r){return(new Fb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fb,t,r)}static $(){return["ResendTeamPendingInviteRequest|1 team_id 5|2 invite_id 9|3 castle_request_token 9?"]}}class Kb extends T{constructor(t){super(),this.expiresAt=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kb).fromBinary(t,r)}static fromJson(t,r){return(new Kb).fromJson(t,r)}static fromJsonString(t,r){return(new Kb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Kb,t,r)}static $(){return["ResendTeamPendingInviteResponse|1 expires_at 3"]}}class zb extends T{constructor(t){super(),this.requestId=n.protoInt64.zero,this.requesterUserId=0,this.requesterName="",this.requesterEmail="",this.requestedAt=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zb).fromBinary(t,r)}static fromJson(t,r){return(new zb).fromJson(t,r)}static fromJsonString(t,r){return(new zb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zb,t,r)}static $(){return["TeamJoinRequest|1 request_id 3|2 requester_user_id 5|3 requester_name 9|4 requester_email 9|5 requested_at 3"]}}class jb extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jb).fromBinary(t,r)}static fromJson(t,r){return(new jb).fromJson(t,r)}static fromJsonString(t,r){return(new jb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jb,t,r)}static $(){return["ListTeamJoinRequestsRequest|1 team_id 5"]}}class Hb extends T{constructor(t){super(),this.requests=[],this.truncated=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hb).fromBinary(t,r)}static fromJson(t,r){return(new Hb).fromJson(t,r)}static fromJsonString(t,r){return(new Hb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hb,t,r)}static $(){return["ListTeamJoinRequestsResponse|1 requests #0*|2 truncated 8",zb]}}class Wb extends T{constructor(t){super(),this.teamId=0,this.requestId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wb).fromBinary(t,r)}static fromJson(t,r){return(new Wb).fromJson(t,r)}static fromJsonString(t,r){return(new Wb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wb,t,r)}static $(){return["ApproveTeamJoinRequestRequest|1 team_id 5|2 request_id 3"]}}class Qb extends T{constructor(t){super(),this.waitingForSeat=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qb).fromBinary(t,r)}static fromJson(t,r){return(new Qb).fromJson(t,r)}static fromJsonString(t,r){return(new Qb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qb,t,r)}static $(){return["ApproveTeamJoinRequestResponse|1 waiting_for_seat 8"]}}class Vb extends T{constructor(t){super(),this.teamId=0,this.requestId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vb).fromBinary(t,r)}static fromJson(t,r){return(new Vb).fromJson(t,r)}static fromJsonString(t,r){return(new Vb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vb,t,r)}static $(){return["DenyTeamJoinRequestRequest|1 team_id 5|2 request_id 3"]}}class Xb extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xb).fromBinary(t,r)}static fromJson(t,r){return(new Xb).fromJson(t,r)}static fromJsonString(t,r){return(new Xb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xb,t,r)}static $(){return["DenyTeamJoinRequestResponse"]}}class Yb extends T{constructor(t){super(),this.teamId=0,this.requiresApproval=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yb).fromBinary(t,r)}static fromJson(t,r){return(new Yb).fromJson(t,r)}static fromJsonString(t,r){return(new Yb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yb,t,r)}static $(){return["UpdateTeamInviteLinkJoinApprovalSettingRequest|1 team_id 5|2 requires_approval 8"]}}class Zb extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zb).fromBinary(t,r)}static fromJson(t,r){return(new Zb).fromJson(t,r)}static fromJsonString(t,r){return(new Zb).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zb,t,r)}static $(){return["UpdateTeamInviteLinkJoinApprovalSettingResponse"]}}class tR extends T{constructor(t){super(),this.firstName="",this.lastName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tR).fromBinary(t,r)}static fromJson(t,r){return(new tR).fromJson(t,r)}static fromJsonString(t,r){return(new tR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tR,t,r)}static $(){return["UpdateUserNameRequest|1 first_name 9|2 last_name 9"]}}class rR extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rR).fromBinary(t,r)}static fromJson(t,r){return(new rR).fromJson(t,r)}static fromJsonString(t,r){return(new rR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rR,t,r)}static $(){return["UpdateUserNameResponse"]}}class eR extends T{constructor(t){super(),this.contentType="",this.bytes=new Uint8Array(0),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eR).fromBinary(t,r)}static fromJson(t,r){return(new eR).fromJson(t,r)}static fromJsonString(t,r){return(new eR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eR,t,r)}static $(){return["UploadUserProfilePictureRequest|1 content_type 9|2 bytes 12"]}}class nR extends T{constructor(t){super(),this.profilePictureUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nR).fromBinary(t,r)}static fromJson(t,r){return(new nR).fromJson(t,r)}static fromJsonString(t,r){return(new nR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nR,t,r)}static $(){return["UploadUserProfilePictureResponse|1 profile_picture_url 9"]}}class sR extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sR).fromBinary(t,r)}static fromJson(t,r){return(new sR).fromJson(t,r)}static fromJsonString(t,r){return(new sR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sR,t,r)}static $(){return["UpdateUserProfilePictureRequest|1 profile_picture_url 9?"]}}class iR extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iR).fromBinary(t,r)}static fromJson(t,r){return(new iR).fromJson(t,r)}static fromJsonString(t,r){return(new iR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iR,t,r)}static $(){return["UpdateUserProfilePictureResponse|1 profile_picture_url 9?"]}}class oR extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oR).fromBinary(t,r)}static fromJson(t,r){return(new oR).fromJson(t,r)}static fromJsonString(t,r){return(new oR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oR,t,r)}static $(){return["ListInvoicesRequest|1 team_id 5?|2 page 5?|3 page_size 5?|4 status 9?"]}}class aR extends T{constructor(t){super(),this.invoiceId="",this.date=n.protoInt64.zero,this.amountCents=0,this.currency="",this.status="",this.hostedInvoiceUrl="",this.refundAmount=0,this.description="",this.isMidMonthInvoice=!1,this.invoicePdfUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aR).fromBinary(t,r)}static fromJson(t,r){return(new aR).fromJson(t,r)}static fromJsonString(t,r){return(new aR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aR,t,r)}static $(){return["InvoiceInfo|1 invoice_id 9|2 date 3|3 amount_cents 5|4 currency 9|5 status 9|6 hosted_invoice_url 9|7 refund_amount 5|8 description 9|9 is_mid_month_invoice 8|10 invoice_pdf_url 9"]}}class uR extends T{constructor(t){super(),this.invoices=[],this.total=0,this.totalPages=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uR).fromBinary(t,r)}static fromJson(t,r){return(new uR).fromJson(t,r)}static fromJsonString(t,r){return(new uR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uR,t,r)}static $(){return["ListInvoicesResponse|1 invoices #0*|2 total 5|3 total_pages 5|4 has_more 8?",aR]}}class cR extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cR).fromBinary(t,r)}static fromJson(t,r){return(new cR).fromJson(t,r)}static fromJsonString(t,r){return(new cR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cR,t,r)}static $(){return["GetComplatCreditBalanceRequest|1 team_id 5?"]}}class lR extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lR).fromBinary(t,r)}static fromJson(t,r){return(new lR).fromJson(t,r)}static fromJsonString(t,r){return(new lR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lR,t,r)}static $(){return["GetComplatCreditBalanceResponse|1 usd_remaining_cents 3?|2 cursor_credit_pending_cents 3?|3 cursor_credit_refund_requested_cents 3?|4 cursor_credit_in_flight_cents 3?"]}}class mR extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mR).fromBinary(t,r)}static fromJson(t,r){return(new mR).fromJson(t,r)}static fromJsonString(t,r){return(new mR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mR,t,r)}static $(){return["ListBlockingCheckoutInvoicesRequest"]}}class fR extends T{constructor(t){super(),this.invoices=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fR).fromBinary(t,r)}static fromJson(t,r){return(new fR).fromJson(t,r)}static fromJsonString(t,r){return(new fR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fR,t,r)}static $(){return["ListBlockingCheckoutInvoicesResponse|1 invoices #0*",aR]}}class dR extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dR).fromBinary(t,r)}static fromJson(t,r){return(new dR).fromJson(t,r)}static fromJsonString(t,r){return(new dR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dR,t,r)}static $(){return["ListPayableTeamInvoicesRequest"]}}class pR extends T{constructor(t){super(),this.teamId=0,this.teamName="",this.subscriptionStatus="",this.invoices=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pR).fromBinary(t,r)}static fromJson(t,r){return(new pR).fromJson(t,r)}static fromJsonString(t,r){return(new pR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pR,t,r)}static $(){return["PayableTeamInvoices|1 team_id 5|2 team_name 9|3 subscription_status 9|4 invoices #0*",aR]}}class hR extends T{constructor(t){super(),this.teams=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hR).fromBinary(t,r)}static fromJson(t,r){return(new hR).fromJson(t,r)}static fromJsonString(t,r){return(new hR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hR,t,r)}static $(){return["ListPayableTeamInvoicesResponse|1 teams #0*",pR]}}class gR extends T{constructor(t){super(),this.inferredPrivacyMode=s.Y.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gR).fromBinary(t,r)}static fromJson(t,r){return(new gR).fromJson(t,r)}static fromJsonString(t,r){return(new gR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gR,t,r)}static $(){return["GetUserPrivacyModeRequest|1 inferred_privacy_mode #0|2 team_id 5?",s.Y]}}class _R extends T{constructor(t){super(),this.privacyMode=s.Y.UNSPECIFIED,this.hoursRemainingInGracePeriod=0,this.isEnforcedByTeam=!1,this.isNotMigratedToServerSourceOfTruth=!1,this.partnerDataShare=!1,this.hasAcknowledgedGracePeriodDisclaimer=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _R).fromBinary(t,r)}static fromJson(t,r){return(new _R).fromJson(t,r)}static fromJsonString(t,r){return(new _R).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_R,t,r)}static $(){return["GetUserPrivacyModeResponse|1 privacy_mode #0|2 hours_remaining_in_grace_period 5|3 is_enforced_by_team 8|4 is_not_migrated_to_server_source_of_truth 8|5 partner_data_share 8|6 has_acknowledged_grace_period_disclaimer 8|7 account_privacy_mode #0?",s.Y]}}class JR extends T{constructor(t){super(),this.privacyMode=s.Y.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new JR).fromBinary(t,r)}static fromJson(t,r){return(new JR).fromJson(t,r)}static fromJsonString(t,r){return(new JR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(JR,t,r)}static $(){return["SetUserPrivacyModeRequest|1 privacy_mode #0",s.Y]}}class wR extends T{constructor(t){super(),this.usageResetPerformed=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wR).fromBinary(t,r)}static fromJson(t,r){return(new wR).fromJson(t,r)}static fromJsonString(t,r){return(new wR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wR,t,r)}static $(){return["SetUserPrivacyModeResponse|1 usage_reset_performed 8"]}}class yR extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yR).fromBinary(t,r)}static fromJson(t,r){return(new yR).fromJson(t,r)}static fromJsonString(t,r){return(new yR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yR,t,r)}static $(){return["WebAcknowledgeGracePeriodDisclaimerRequest"]}}class SR extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new SR).fromBinary(t,r)}static fromJson(t,r){return(new SR).fromJson(t,r)}static fromJsonString(t,r){return(new SR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(SR,t,r)}static $(){return["WebAcknowledgeGracePeriodDisclaimerResponse"]}}class qR extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qR).fromBinary(t,r)}static fromJson(t,r){return(new qR).fromJson(t,r)}static fromJsonString(t,r){return(new qR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qR,t,r)}static $(){return["SkipPrivacyModeGracePeriodRequest"]}}class BR extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new BR).fromBinary(t,r)}static fromJson(t,r){return(new BR).fromJson(t,r)}static fromJsonString(t,r){return(new BR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(BR,t,r)}static $(){return["SkipPrivacyModeGracePeriodResponse"]}}class IR extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new IR).fromBinary(t,r)}static fromJson(t,r){return(new IR).fromJson(t,r)}static fromJsonString(t,r){return(new IR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(IR,t,r)}static $(){return["NeedsPrivacyModeMigrationRequest"]}}class PR extends T{constructor(t){super(),this.needsMigration=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new PR).fromBinary(t,r)}static fromJson(t,r){return(new PR).fromJson(t,r)}static fromJsonString(t,r){return(new PR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(PR,t,r)}static $(){return["NeedsPrivacyModeMigrationResponse|1 needs_migration 8"]}}class bR extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bR).fromBinary(t,r)}static fromJson(t,r){return(new bR).fromJson(t,r)}static fromJsonString(t,r){return(new bR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bR,t,r)}static $(){return["GetRemainingRefundsRequest"]}}class RR extends T{constructor(t){super(),this.remainingRefunds=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new RR).fromBinary(t,r)}static fromJson(t,r){return(new RR).fromJson(t,r)}static fromJsonString(t,r){return(new RR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(RR,t,r)}static $(){return["GetRemainingRefundsResponse|1 remaining_refunds 5"]}}class vR extends T{constructor(t){super(),this.serviceType="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vR).fromBinary(t,r)}static fromJson(t,r){return(new vR).fromJson(t,r)}static fromJsonString(t,r){return(new vR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vR,t,r)}static $(){return["GetServiceAccountSpendLimitRequest|1 team_id 5?|2 service_type 9|3 service_account_id 9?"]}}class xR extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xR).fromBinary(t,r)}static fromJson(t,r){return(new xR).fromJson(t,r)}static fromJsonString(t,r){return(new xR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xR,t,r)}static $(){return["GetServiceAccountSpendLimitResponse|1 spend_limit_cents 5?|2 current_spend_cents 5?|3 is_in_free_trial 8?|4 free_trial_expires_at 3?"]}}class kR extends T{constructor(t){super(),this.serviceType="",this.spendLimitCents=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kR).fromBinary(t,r)}static fromJson(t,r){return(new kR).fromJson(t,r)}static fromJsonString(t,r){return(new kR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kR,t,r)}static $(){return["SetServiceAccountSpendLimitRequest|1 team_id 5?|2 service_type 9|3 spend_limit_cents 5|4 service_account_id 9?|5 clear_spend_limit 8?"]}}class ER extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ER).fromBinary(t,r)}static fromJson(t,r){return(new ER).fromJson(t,r)}static fromJsonString(t,r){return(new ER).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ER,t,r)}static $(){return["SetServiceAccountSpendLimitResponse|1 success 8"]}}class CR extends T{constructor(t){super(),this.teamId=0,this.userId=0,this.hardLimitDollars=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new CR).fromBinary(t,r)}static fromJson(t,r){return(new CR).fromJson(t,r)}static fromJsonString(t,r){return(new CR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(CR,t,r)}static $(){return["SetUserHardLimitRequest|1 team_id 5|2 user_id 5|3 hard_limit_dollars 5"]}}class TR extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new TR).fromBinary(t,r)}static fromJson(t,r){return(new TR).fromJson(t,r)}static fromJsonString(t,r){return(new TR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(TR,t,r)}static $(){return["SetUserHardLimitResponse"]}}class UR extends T{constructor(t){super(),this.teamId=0,this.userId=0,this.monthlyLimitDollars=0,this.clearFirstPartyModelsAdditionalBudgetDollars=!1,this.clearFirstPartyModelsAdditionalBudgetUnlimited=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new UR).fromBinary(t,r)}static fromJson(t,r){return(new UR).fromJson(t,r)}static fromJsonString(t,r){return(new UR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(UR,t,r)}static $(){return["SetUserMonthlyLimitRequest|1 team_id 5|2 user_id 5|3 monthly_limit_dollars 5|4 first_party_models_additional_budget_dollars 5?|5 clear_first_party_models_additional_budget_dollars 8|6 first_party_models_additional_budget_unlimited 8?|7 clear_first_party_models_additional_budget_unlimited 8"]}}class AR extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new AR).fromBinary(t,r)}static fromJson(t,r){return(new AR).fromJson(t,r)}static fromJsonString(t,r){return(new AR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(AR,t,r)}static $(){return["SetUserMonthlyLimitResponse"]}}class $R extends T{constructor(t){super(),this.teamId=0,this.modelId="",this.enabled=!1,this.acknowledged=!1,this.consentVersion="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $R).fromBinary(t,r)}static fromJson(t,r){return(new $R).fromJson(t,r)}static fromJsonString(t,r){return(new $R).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($R,t,r)}static $(){return["SetTeamNoZdrModelConsentRequest|1 team_id 5|2 model_id 9|3 enabled 8|4 acknowledged 8|5 consent_version 9"]}}class MR extends T{constructor(t){super(),this.consented=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new MR).fromBinary(t,r)}static fromJson(t,r){return(new MR).fromJson(t,r)}static fromJsonString(t,r){return(new MR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(MR,t,r)}static $(){return["SetTeamNoZdrModelConsentResponse|1 consented 8"]}}class OR extends T{constructor(t){super(),this.organizationId="",this.modelId="",this.enabled=!1,this.acknowledged=!1,this.consentVersion="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new OR).fromBinary(t,r)}static fromJson(t,r){return(new OR).fromJson(t,r)}static fromJsonString(t,r){return(new OR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(OR,t,r)}static $(){return["SetOrganizationNoZdrModelConsentRequest|1 organization_id 9|2 model_id 9|3 enabled 8|4 acknowledged 8|5 consent_version 9"]}}class DR extends T{constructor(t){super(),this.consented=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new DR).fromBinary(t,r)}static fromJson(t,r){return(new DR).fromJson(t,r)}static fromJsonString(t,r){return(new DR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(DR,t,r)}static $(){return["SetOrganizationNoZdrModelConsentResponse|1 consented 8"]}}class NR extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new NR).fromBinary(t,r)}static fromJson(t,r){return(new NR).fromJson(t,r)}static fromJsonString(t,r){return(new NR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(NR,t,r)}static $(){return["GetOrganizationOnDemandSpendDisabledRequest|1 organization_id 9"]}}class GR extends T{constructor(t){super(),this.disabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new GR).fromBinary(t,r)}static fromJson(t,r){return(new GR).fromJson(t,r)}static fromJsonString(t,r){return(new GR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(GR,t,r)}static $(){return["GetOrganizationOnDemandSpendDisabledResponse|1 disabled 8"]}}class LR extends T{constructor(t){super(),this.organizationId="",this.disabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new LR).fromBinary(t,r)}static fromJson(t,r){return(new LR).fromJson(t,r)}static fromJsonString(t,r){return(new LR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(LR,t,r)}static $(){return["SetOrganizationOnDemandSpendDisabledRequest|1 organization_id 9|2 disabled 8"]}}class FR extends T{constructor(t){super(),this.disabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new FR).fromBinary(t,r)}static fromJson(t,r){return(new FR).fromJson(t,r)}static fromJsonString(t,r){return(new FR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(FR,t,r)}static $(){return["SetOrganizationOnDemandSpendDisabledResponse|1 disabled 8"]}}class KR extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new KR).fromBinary(t,r)}static fromJson(t,r){return(new KR).fromJson(t,r)}static fromJsonString(t,r){return(new KR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(KR,t,r)}static $(){return["GetOrganizationCreditRequestButtonHiddenRequest|1 organization_id 9"]}}class zR extends T{constructor(t){super(),this.hidden=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zR).fromBinary(t,r)}static fromJson(t,r){return(new zR).fromJson(t,r)}static fromJsonString(t,r){return(new zR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zR,t,r)}static $(){return["GetOrganizationCreditRequestButtonHiddenResponse|1 hidden 8"]}}class jR extends T{constructor(t){super(),this.organizationId="",this.hidden=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jR).fromBinary(t,r)}static fromJson(t,r){return(new jR).fromJson(t,r)}static fromJsonString(t,r){return(new jR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jR,t,r)}static $(){return["SetOrganizationCreditRequestButtonHiddenRequest|1 organization_id 9|2 hidden 8"]}}class HR extends T{constructor(t){super(),this.hidden=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new HR).fromBinary(t,r)}static fromJson(t,r){return(new HR).fromJson(t,r)}static fromJsonString(t,r){return(new HR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(HR,t,r)}static $(){return["SetOrganizationCreditRequestButtonHiddenResponse|1 hidden 8"]}}class WR extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new WR).fromBinary(t,r)}static fromJson(t,r){return(new WR).fromJson(t,r)}static fromJsonString(t,r){return(new WR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(WR,t,r)}static $(){return["GetOrganizationSsoJitAutoEnrollmentRequest|1 organization_id 9"]}}class QR extends T{constructor(t){super(),this.enabled=!1,this.configured=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new QR).fromBinary(t,r)}static fromJson(t,r){return(new QR).fromJson(t,r)}static fromJsonString(t,r){return(new QR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(QR,t,r)}static $(){return["GetOrganizationSsoJitAutoEnrollmentResponse|1 enabled 8|2 configured 8"]}}class VR extends T{constructor(t){super(),this.organizationId="",this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new VR).fromBinary(t,r)}static fromJson(t,r){return(new VR).fromJson(t,r)}static fromJsonString(t,r){return(new VR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(VR,t,r)}static $(){return["SetOrganizationSsoJitAutoEnrollmentRequest|1 organization_id 9|2 enabled 8"]}}class XR extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new XR).fromBinary(t,r)}static fromJson(t,r){return(new XR).fromJson(t,r)}static fromJsonString(t,r){return(new XR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(XR,t,r)}static $(){return["SetOrganizationSsoJitAutoEnrollmentResponse|1 enabled 8"]}}class YR extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new YR).fromBinary(t,r)}static fromJson(t,r){return(new YR).fromJson(t,r)}static fromJsonString(t,r){return(new YR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(YR,t,r)}static $(){return["GetTeamSsoJitAutoEnrollmentRequest|1 team_id 5"]}}class ZR extends T{constructor(t){super(),this.enabled=!1,this.available=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ZR).fromBinary(t,r)}static fromJson(t,r){return(new ZR).fromJson(t,r)}static fromJsonString(t,r){return(new ZR).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ZR,t,r)}static $(){return["GetTeamSsoJitAutoEnrollmentResponse|1 enabled 8|2 available 8"]}}class tv extends T{constructor(t){super(),this.teamId=0,this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tv).fromBinary(t,r)}static fromJson(t,r){return(new tv).fromJson(t,r)}static fromJsonString(t,r){return(new tv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tv,t,r)}static $(){return["SetTeamSsoJitAutoEnrollmentRequest|1 team_id 5|2 enabled 8"]}}class rv extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rv).fromBinary(t,r)}static fromJson(t,r){return(new rv).fromJson(t,r)}static fromJsonString(t,r){return(new rv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rv,t,r)}static $(){return["SetTeamSsoJitAutoEnrollmentResponse|1 enabled 8"]}}class ev extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ev).fromBinary(t,r)}static fromJson(t,r){return(new ev).fromJson(t,r)}static fromJsonString(t,r){return(new ev).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ev,t,r)}static $(){return["GetTeamXAccountLinkingRequest|1 team_id 5"]}}class nv extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nv).fromBinary(t,r)}static fromJson(t,r){return(new nv).fromJson(t,r)}static fromJsonString(t,r){return(new nv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nv,t,r)}static $(){return["SetTeamXAccountLinkingRequest|1 team_id 5|2 allowed 8?"]}}class sv extends T{constructor(t){super(),this.available=!1,this.editable=!1,this.allowed=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sv).fromBinary(t,r)}static fromJson(t,r){return(new sv).fromJson(t,r)}static fromJsonString(t,r){return(new sv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sv,t,r)}static $(){return["TeamXAccountLinking|1 available 8|2 editable 8|3 allowed 8"]}}class iv extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iv).fromBinary(t,r)}static fromJson(t,r){return(new iv).fromJson(t,r)}static fromJsonString(t,r){return(new iv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iv,t,r)}static $(){return["GetOrganizationRemoteControlSettingsRequest|1 organization_id 9"]}}class ov extends T{constructor(t){super(),this.isEnterprise=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ov).fromBinary(t,r)}static fromJson(t,r){return(new ov).fromJson(t,r)}static fromJsonString(t,r){return(new ov).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ov,t,r)}static $(){return["GetOrganizationRemoteControlSettingsResponse|1 settings #0|2 is_enterprise 8",d]}}class av extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new av).fromBinary(t,r)}static fromJson(t,r){return(new av).fromJson(t,r)}static fromJsonString(t,r){return(new av).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(av,t,r)}static $(){return["UpdateOrganizationRemoteControlSettingsRequest|1 organization_id 9|2 enabled 8?|3 automatic_registration_enabled 8?"]}}class uv extends T{constructor(t){super(),this.isEnterprise=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uv).fromBinary(t,r)}static fromJson(t,r){return(new uv).fromJson(t,r)}static fromJsonString(t,r){return(new uv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uv,t,r)}static $(){return["UpdateOrganizationRemoteControlSettingsResponse|1 settings #0|2 is_enterprise 8",d]}}class cv extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cv).fromBinary(t,r)}static fromJson(t,r){return(new cv).fromJson(t,r)}static fromJsonString(t,r){return(new cv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cv,t,r)}static $(){return["GetOrganizationSlackManagedWorkspacesRequest|1 organization_id 9"]}}class lv extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lv).fromBinary(t,r)}static fromJson(t,r){return(new lv).fromJson(t,r)}static fromJsonString(t,r){return(new lv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lv,t,r)}static $(){return["GetOrganizationSlackManagedWorkspacesResponse|1 managed_workspaces #0|2 enabled 8",xJ]}}class mv extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mv).fromBinary(t,r)}static fromJson(t,r){return(new mv).fromJson(t,r)}static fromJsonString(t,r){return(new mv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mv,t,r)}static $(){return["UpdateOrganizationSlackManagedWorkspacesRequest|1 organization_id 9|2 managed_workspaces #0",xJ]}}class fv extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fv).fromBinary(t,r)}static fromJson(t,r){return(new fv).fromJson(t,r)}static fromJsonString(t,r){return(new fv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fv,t,r)}static $(){return["UpdateOrganizationSlackManagedWorkspacesResponse|1 managed_workspaces #0|2 enabled 8",xJ]}}class dv extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dv).fromBinary(t,r)}static fromJson(t,r){return(new dv).fromJson(t,r)}static fromJsonString(t,r){return(new dv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dv,t,r)}static $(){return["GetOrganizationSlackInboundInstallPolicyRequest|1 organization_id 9"]}}class pv extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pv).fromBinary(t,r)}static fromJson(t,r){return(new pv).fromJson(t,r)}static fromJsonString(t,r){return(new pv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pv,t,r)}static $(){return["GetOrganizationSlackInboundInstallPolicyResponse|1 inbound_install_policy #0|2 enabled 8",kJ]}}class hv extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hv).fromBinary(t,r)}static fromJson(t,r){return(new hv).fromJson(t,r)}static fromJsonString(t,r){return(new hv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hv,t,r)}static $(){return["UpdateOrganizationSlackInboundInstallPolicyRequest|1 organization_id 9|2 inbound_install_policy #0",kJ]}}class gv extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gv).fromBinary(t,r)}static fromJson(t,r){return(new gv).fromJson(t,r)}static fromJsonString(t,r){return(new gv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gv,t,r)}static $(){return["UpdateOrganizationSlackInboundInstallPolicyResponse|1 inbound_install_policy #0|2 enabled 8",kJ]}}class _v extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _v).fromBinary(t,r)}static fromJson(t,r){return(new _v).fromJson(t,r)}static fromJsonString(t,r){return(new _v).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_v,t,r)}static $(){return["GetOrganizationGoogleDriveBlockedSharedDrivesRequest|1 organization_id 9"]}}class Jv extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jv).fromBinary(t,r)}static fromJson(t,r){return(new Jv).fromJson(t,r)}static fromJsonString(t,r){return(new Jv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jv,t,r)}static $(){return["GetOrganizationGoogleDriveBlockedSharedDrivesResponse|1 blocked_shared_drives #0|2 enabled 8",CJ]}}class wv extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wv).fromBinary(t,r)}static fromJson(t,r){return(new wv).fromJson(t,r)}static fromJsonString(t,r){return(new wv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wv,t,r)}static $(){return["UpdateOrganizationGoogleDriveBlockedSharedDrivesRequest|1 organization_id 9|2 blocked_shared_drives #0",CJ]}}class yv extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yv).fromBinary(t,r)}static fromJson(t,r){return(new yv).fromJson(t,r)}static fromJsonString(t,r){return(new yv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yv,t,r)}static $(){return["UpdateOrganizationGoogleDriveBlockedSharedDrivesResponse|1 blocked_shared_drives #0|2 enabled 8",CJ]}}class Sv extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sv).fromBinary(t,r)}static fromJson(t,r){return(new Sv).fromJson(t,r)}static fromJsonString(t,r){return(new Sv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sv,t,r)}static $(){return["GetOrganizationConnectorAccountOwnershipRequest|1 organization_id 9"]}}class qv extends T{constructor(t){super(),this.google=[],this.microsoft=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qv).fromBinary(t,r)}static fromJson(t,r){return(new qv).fromJson(t,r)}static fromJsonString(t,r){return(new qv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qv,t,r)}static $(){return["ConnectorAccountMembersOnlyDomains|1 google 9*|2 microsoft 9*"]}}class Bv extends T{constructor(t){super(),this.enabled=!1,this.verifiedDomains=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bv).fromBinary(t,r)}static fromJson(t,r){return(new Bv).fromJson(t,r)}static fromJsonString(t,r){return(new Bv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bv,t,r)}static $(){return["GetOrganizationConnectorAccountOwnershipResponse|2 enabled 8|3 verified_domains 9*|4 members_only_domains #0",qv]}}class Iv extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Iv).fromBinary(t,r)}static fromJson(t,r){return(new Iv).fromJson(t,r)}static fromJsonString(t,r){return(new Iv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Iv,t,r)}static $(){return["UpdateOrganizationConnectorAccountOwnershipRequest|1 organization_id 9|3 members_only_domains #0",qv]}}class Pv extends T{constructor(t){super(),this.enabled=!1,this.verifiedDomains=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pv).fromBinary(t,r)}static fromJson(t,r){return(new Pv).fromJson(t,r)}static fromJsonString(t,r){return(new Pv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pv,t,r)}static $(){return["UpdateOrganizationConnectorAccountOwnershipResponse|2 enabled 8|3 verified_domains 9*|4 members_only_domains #0",qv]}}class bv extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bv).fromBinary(t,r)}static fromJson(t,r){return(new bv).fromJson(t,r)}static fromJsonString(t,r){return(new bv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bv,t,r)}static $(){return["GetTeamRemoteControlSettingsRequest|1 team_id 5"]}}class Rv extends T{constructor(t){super(),this.available=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rv).fromBinary(t,r)}static fromJson(t,r){return(new Rv).fromJson(t,r)}static fromJsonString(t,r){return(new Rv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rv,t,r)}static $(){return["GetTeamRemoteControlSettingsResponse|1 settings #0|2 available 8|3 devices_available 8?",d]}}class vv extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vv).fromBinary(t,r)}static fromJson(t,r){return(new vv).fromJson(t,r)}static fromJsonString(t,r){return(new vv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vv,t,r)}static $(){return["UpdateTeamRemoteControlSettingsRequest|1 team_id 5|2 enabled 8?|3 automatic_registration_enabled 8?"]}}class xv extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xv).fromBinary(t,r)}static fromJson(t,r){return(new xv).fromJson(t,r)}static fromJsonString(t,r){return(new xv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xv,t,r)}static $(){return["UpdateTeamRemoteControlSettingsResponse|1 settings #0",d]}}class kv extends T{constructor(t){super(),this.organizationId="",this.search="",this.cursor="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kv).fromBinary(t,r)}static fromJson(t,r){return(new kv).fromJson(t,r)}static fromJsonString(t,r){return(new kv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kv,t,r)}static $(){return["ListOrganizationRemoteControlDevicesRequest|1 organization_id 9|2 search 9|3 cursor 9|4 page_size 5?"]}}class Ev extends T{constructor(t){super(),this.teamId=0,this.search="",this.cursor="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ev).fromBinary(t,r)}static fromJson(t,r){return(new Ev).fromJson(t,r)}static fromJsonString(t,r){return(new Ev).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ev,t,r)}static $(){return["ListTeamRemoteControlDevicesRequest|1 team_id 5|2 search 9|3 cursor 9|4 page_size 5?"]}}class Cv extends T{constructor(t){super(),this.computers=[],this.nextCursor="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cv).fromBinary(t,r)}static fromJson(t,r){return(new Cv).fromJson(t,r)}static fromJsonString(t,r){return(new Cv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cv,t,r)}static $(){return["ListRemoteControlDevicesResponse|1 computers #0*|2 next_cursor 9",Tv]}}class Tv extends T{constructor(t){super(),this.memberUserId=0,this.memberEmail="",this.memberName="",this.computerId="",this.computerName="",this.pairedDevices=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tv).fromBinary(t,r)}static fromJson(t,r){return(new Tv).fromJson(t,r)}static fromJsonString(t,r){return(new Tv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tv,t,r)}static $(){return["RemoteControlComputerRow|1 member_user_id 5|2 member_email 9|3 member_name 9|4 computer_id 9|5 computer_name 9|6 last_used_at_ms 3?|7 paired_devices #0*",Uv]}}class Uv extends T{constructor(t){super(),this.thumbprint="",this.label="",this.pairedAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Uv).fromBinary(t,r)}static fromJson(t,r){return(new Uv).fromJson(t,r)}static fromJsonString(t,r){return(new Uv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Uv,t,r)}static $(){return["RemoteControlPairedDevice|1 thumbprint 9|2 label 9|3 paired_at_ms 3|4 last_used_at_ms 3?"]}}class Av extends T{constructor(t){super(),this.organizationId="",this.memberUserId=0,this.device={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Av).fromBinary(t,r)}static fromJson(t,r){return(new Av).fromJson(t,r)}static fromJsonString(t,r){return(new Av).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Av,t,r)}static $(){return["RevokeOrganizationRemoteControlDeviceRequest|1 organization_id 9|2 member_user_id 5|3 computer_id 9 device|4 controller_thumbprint 9 device|5 all_devices 8 device"]}}class $v extends T{constructor(t){super(),this.teamId=0,this.memberUserId=0,this.device={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $v).fromBinary(t,r)}static fromJson(t,r){return(new $v).fromJson(t,r)}static fromJsonString(t,r){return(new $v).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($v,t,r)}static $(){return["RevokeTeamRemoteControlDeviceRequest|1 team_id 5|2 member_user_id 5|3 computer_id 9 device|4 controller_thumbprint 9 device|5 all_devices 8 device"]}}class Mv extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mv).fromBinary(t,r)}static fromJson(t,r){return(new Mv).fromJson(t,r)}static fromJsonString(t,r){return(new Mv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mv,t,r)}static $(){return["RevokeRemoteControlDeviceResponse"]}}class Ov extends T{constructor(t){super(),this.modelId="",this.enabled=!1,this.acknowledged=!1,this.consentVersion="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ov).fromBinary(t,r)}static fromJson(t,r){return(new Ov).fromJson(t,r)}static fromJsonString(t,r){return(new Ov).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ov,t,r)}static $(){return["SetUserNoZdrModelConsentRequest|1 model_id 9|2 enabled 8|3 acknowledged 8|4 consent_version 9"]}}class Dv extends T{constructor(t){super(),this.consented=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dv).fromBinary(t,r)}static fromJson(t,r){return(new Dv).fromJson(t,r)}static fromJsonString(t,r){return(new Dv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dv,t,r)}static $(){return["SetUserNoZdrModelConsentResponse|1 consented 8"]}}class Nv extends T{constructor(t){super(),this.teamId=0,this.modelId="",this.enabled=!1,this.acknowledged=!1,this.consentVersion="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nv).fromBinary(t,r)}static fromJson(t,r){return(new Nv).fromJson(t,r)}static fromJsonString(t,r){return(new Nv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nv,t,r)}static $(){return["SetTeamMemberNoZdrModelConsentRequest|1 team_id 5|2 model_id 9|3 enabled 8|4 acknowledged 8|5 consent_version 9"]}}class Gv extends T{constructor(t){super(),this.consented=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gv).fromBinary(t,r)}static fromJson(t,r){return(new Gv).fromJson(t,r)}static fromJsonString(t,r){return(new Gv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gv,t,r)}static $(){return["SetTeamMemberNoZdrModelConsentResponse|1 consented 8"]}}class Lv extends T{constructor(t){super(),this.scope=Fv.UNSPECIFIED,this.teamId=0,this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lv).fromBinary(t,r)}static fromJson(t,r){return(new Lv).fromJson(t,r)}static fromJsonString(t,r){return(new Lv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Lv,t,r)}static $(){return["GetNoZdrModelConsentStatusRequest|1 scope #0|2 team_id 5|3 organization_id 9",Fv]}}var Fv=(0,a.QT)(n.proto3,C,"GetNoZdrModelConsentStatusRequest.Scope",[[0,"UNSPECIFIED"],[1,"TEAM"],[2,"TEAM_MEMBER"],[3,"USER"],[4,"ORGANIZATION"]],1);class Kv extends T{constructor(t){super(),this.modelId="",this.consentVersion="",this.acceptedAt="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kv).fromBinary(t,r)}static fromJson(t,r){return(new Kv).fromJson(t,r)}static fromJsonString(t,r){return(new Kv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Kv,t,r)}static $(){return["NoZdrModelConsentStatusEntry|1 model_id 9|2 consent_version 9|3 accepted_at 9"]}}class zv extends T{constructor(t){super(),this.modelId="",this.displayName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zv).fromBinary(t,r)}static fromJson(t,r){return(new zv).fromJson(t,r)}static fromJsonString(t,r){return(new zv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zv,t,r)}static $(){return["NoZdrRestrictedModel|1 model_id 9|2 display_name 9"]}}class jv extends T{constructor(t){super(),this.consents=[],this.restrictedModels=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jv).fromBinary(t,r)}static fromJson(t,r){return(new jv).fromJson(t,r)}static fromJsonString(t,r){return(new jv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jv,t,r)}static $(){return["GetNoZdrModelConsentStatusResponse|1 consents #0*|2 restricted_models #1*",Kv,zv]}}class Hv extends T{constructor(t){super(),this.optOut=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hv).fromBinary(t,r)}static fromJson(t,r){return(new Hv).fromJson(t,r)}static fromJsonString(t,r){return(new Hv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hv,t,r)}static $(){return["ToggleMarketingEmailOptRequest|1 opt_out 8"]}}class Wv extends T{constructor(t){super(),this.optedOut=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wv).fromBinary(t,r)}static fromJson(t,r){return(new Wv).fromJson(t,r)}static fromJsonString(t,r){return(new Wv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wv,t,r)}static $(){return["ToggleMarketingEmailOptResponse|1 opted_out 8"]}}class Qv extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qv).fromBinary(t,r)}static fromJson(t,r){return(new Qv).fromJson(t,r)}static fromJsonString(t,r){return(new Qv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qv,t,r)}static $(){return["GetMarketingEmailOptRequest"]}}class Vv extends T{constructor(t){super(),this.optedOut=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vv).fromBinary(t,r)}static fromJson(t,r){return(new Vv).fromJson(t,r)}static fromJsonString(t,r){return(new Vv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vv,t,r)}static $(){return["GetMarketingEmailOptResponse|1 opted_out 8"]}}class Xv extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xv).fromBinary(t,r)}static fromJson(t,r){return(new Xv).fromJson(t,r)}static fromJsonString(t,r){return(new Xv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xv,t,r)}static $(){return["GetGlobalLeaderboardOptInRequest"]}}class Yv extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yv).fromBinary(t,r)}static fromJson(t,r){return(new Yv).fromJson(t,r)}static fromJsonString(t,r){return(new Yv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yv,t,r)}static $(){return["GetGlobalLeaderboardOptInResponse|1 opted_in 8?"]}}class Zv extends T{constructor(t){super(),this.optedIn=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zv).fromBinary(t,r)}static fromJson(t,r){return(new Zv).fromJson(t,r)}static fromJsonString(t,r){return(new Zv).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zv,t,r)}static $(){return["SetGlobalLeaderboardOptInRequest|1 opted_in 8"]}}class tx extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tx).fromBinary(t,r)}static fromJson(t,r){return(new tx).fromJson(t,r)}static fromJsonString(t,r){return(new tx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tx,t,r)}static $(){return["SetGlobalLeaderboardOptInResponse"]}}class rx extends T{constructor(t){super(),this.teamId=0,this.newName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rx).fromBinary(t,r)}static fromJson(t,r){return(new rx).fromJson(t,r)}static fromJsonString(t,r){return(new rx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rx,t,r)}static $(){return["UpdateTeamNameRequest|1 team_id 5|2 new_name 9"]}}class ex extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ex).fromBinary(t,r)}static fromJson(t,r){return(new ex).fromJson(t,r)}static fromJsonString(t,r){return(new ex).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ex,t,r)}static $(){return["UpdateTeamNameResponse"]}}class nx extends T{constructor(t){super(),this.teamId=0,this.contentType="",this.bytes=new Uint8Array(0),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nx).fromBinary(t,r)}static fromJson(t,r){return(new nx).fromJson(t,r)}static fromJsonString(t,r){return(new nx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nx,t,r)}static $(){return["UploadTeamIconRequest|1 team_id 5|2 content_type 9|3 bytes 12"]}}class sx extends T{constructor(t){super(),this.iconUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sx).fromBinary(t,r)}static fromJson(t,r){return(new sx).fromJson(t,r)}static fromJsonString(t,r){return(new sx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sx,t,r)}static $(){return["UploadTeamIconResponse|1 icon_url 9"]}}class ix extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ix).fromBinary(t,r)}static fromJson(t,r){return(new ix).fromJson(t,r)}static fromJsonString(t,r){return(new ix).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ix,t,r)}static $(){return["UpdateTeamIconRequest|1 team_id 5|2 icon_url 9?"]}}class ox extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ox).fromBinary(t,r)}static fromJson(t,r){return(new ox).fromJson(t,r)}static fromJsonString(t,r){return(new ox).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ox,t,r)}static $(){return["UpdateTeamIconResponse|1 icon_url 9?"]}}class ax extends T{constructor(t){super(),this.teamId=0,this.dashboardAnalyticsRequiresAdmin=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ax).fromBinary(t,r)}static fromJson(t,r){return(new ax).fromJson(t,r)}static fromJsonString(t,r){return(new ax).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ax,t,r)}static $(){return["UpdateTeamDashboardAnalyticsSettingRequest|1 team_id 5|2 dashboard_analytics_requires_admin 8"]}}class ux extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ux).fromBinary(t,r)}static fromJson(t,r){return(new ux).fromJson(t,r)}static fromJsonString(t,r){return(new ux).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ux,t,r)}static $(){return["UpdateTeamDashboardAnalyticsSettingResponse"]}}class cx extends T{constructor(t){super(),this.teamId=0,this.originDisabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cx).fromBinary(t,r)}static fromJson(t,r){return(new cx).fromJson(t,r)}static fromJsonString(t,r){return(new cx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cx,t,r)}static $(){return["UpdateTeamOriginSettingRequest|1 team_id 5|2 origin_disabled 8|3 origin_allow_public_repos 8?"]}}class lx extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lx).fromBinary(t,r)}static fromJson(t,r){return(new lx).fromJson(t,r)}static fromJsonString(t,r){return(new lx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lx,t,r)}static $(){return["UpdateTeamOriginSettingResponse"]}}class mx extends T{constructor(t){super(),this.teamId=0,this.scimRequireUserDirectory=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mx).fromBinary(t,r)}static fromJson(t,r){return(new mx).fromJson(t,r)}static fromJsonString(t,r){return(new mx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mx,t,r)}static $(){return["UpdateTeamScimRequireUserDirectorySettingRequest|1 team_id 5|2 scim_require_user_directory 8"]}}class fx extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fx).fromBinary(t,r)}static fromJson(t,r){return(new fx).fromJson(t,r)}static fromJsonString(t,r){return(new fx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fx,t,r)}static $(){return["UpdateTeamScimRequireUserDirectorySettingResponse"]}}class dx extends T{constructor(t){super(),this.actor=Nr.UNSPECIFIED,this.usePortalCallback=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dx).fromBinary(t,r)}static fromJson(t,r){return(new dx).fromJson(t,r)}static fromJsonString(t,r){return(new dx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dx,t,r)}static $(){return["GetLinearAuthUrlRequest|1 actor #0|2 use_portal_callback 8",Nr]}}class px extends T{constructor(t){super(),this.authUrl="",this.csrfToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new px).fromBinary(t,r)}static fromJson(t,r){return(new px).fromJson(t,r)}static fromJsonString(t,r){return(new px).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(px,t,r)}static $(){return["GetLinearAuthUrlResponse|1 auth_url 9|2 csrf_token 9"]}}class hx extends T{constructor(t){super(),this.code="",this.state="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hx).fromBinary(t,r)}static fromJson(t,r){return(new hx).fromJson(t,r)}static fromJsonString(t,r){return(new hx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hx,t,r)}static $(){return["ConnectLinearCallbackRequest|1 code 9|2 state 9"]}}class gx extends T{constructor(t){super(),this.successType="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gx).fromBinary(t,r)}static fromJson(t,r){return(new gx).fromJson(t,r)}static fromJsonString(t,r){return(new gx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gx,t,r)}static $(){return["ConnectLinearCallbackResponse|1 success_type 9"]}}class _x extends T{constructor(t){super(),this.linkId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _x).fromBinary(t,r)}static fromJson(t,r){return(new _x).fromJson(t,r)}static fromJsonString(t,r){return(new _x).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_x,t,r)}static $(){return["GetMicrosoftTeamsLinkContextRequest|1 link_id 9"]}}class Jx extends T{constructor(t){super(),this.linkState=Gr.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jx).fromBinary(t,r)}static fromJson(t,r){return(new Jx).fromJson(t,r)}static fromJsonString(t,r){return(new Jx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jx,t,r)}static $(){return["GetMicrosoftTeamsLinkContextResponse|1 team_name 9?|2 user_name 9?|3 link_state #0",Gr]}}class wx extends T{constructor(t){super(),this.linkId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wx).fromBinary(t,r)}static fromJson(t,r){return(new wx).fromJson(t,r)}static fromJsonString(t,r){return(new wx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wx,t,r)}static $(){return["SetMicrosoftTeamsAuthRequest|1 link_id 9"]}}class yx extends T{constructor(t){super(),this.successType="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yx).fromBinary(t,r)}static fromJson(t,r){return(new yx).fromJson(t,r)}static fromJsonString(t,r){return(new yx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yx,t,r)}static $(){return["SetMicrosoftTeamsAuthResponse|1 success_type 9"]}}class Sx extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sx).fromBinary(t,r)}static fromJson(t,r){return(new Sx).fromJson(t,r)}static fromJsonString(t,r){return(new Sx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sx,t,r)}static $(){return["GetLinearStatusRequest"]}}class qx extends T{constructor(t){super(),this.status="",this.autodraftingEnabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qx).fromBinary(t,r)}static fromJson(t,r){return(new qx).fromJson(t,r)}static fromJsonString(t,r){return(new qx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qx,t,r)}static $(){return["GetLinearStatusResponse|1 status 9|2 autodrafting_enabled 8"]}}class Bx extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bx).fromBinary(t,r)}static fromJson(t,r){return(new Bx).fromJson(t,r)}static fromJsonString(t,r){return(new Bx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bx,t,r)}static $(){return["DisconnectLinearRequest"]}}class Ix extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ix).fromBinary(t,r)}static fromJson(t,r){return(new Ix).fromJson(t,r)}static fromJsonString(t,r){return(new Ix).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ix,t,r)}static $(){return["DisconnectLinearResponse"]}}class Px extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Px).fromBinary(t,r)}static fromJson(t,r){return(new Px).fromJson(t,r)}static fromJsonString(t,r){return(new Px).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Px,t,r)}static $(){return["GetXaiTeamLinkStatusRequest|1 organization_id 9"]}}class bx extends T{constructor(t){super(),this.enabled=!1,this.linked=!1,this.xaiTeamId="",this.hasPendingProposal=!1,this.proposedXaiTeamId="",this.canConfirmProposal=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bx).fromBinary(t,r)}static fromJson(t,r){return(new bx).fromJson(t,r)}static fromJsonString(t,r){return(new bx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bx,t,r)}static $(){return["GetXaiTeamLinkStatusResponse|1 enabled 8|2 linked 8|3 xai_team_id 9|4 linked_at_ms 3?|5 has_pending_proposal 8|6 proposed_xai_team_id 9|7 proposal_expires_at_ms 3?|8 can_confirm_proposal 8"]}}class Rx extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rx).fromBinary(t,r)}static fromJson(t,r){return(new Rx).fromJson(t,r)}static fromJsonString(t,r){return(new Rx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rx,t,r)}static $(){return["StartXaiTeamLinkRequest|1 organization_id 9"]}}class vx extends T{constructor(t){super(),this.connectUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vx).fromBinary(t,r)}static fromJson(t,r){return(new vx).fromJson(t,r)}static fromJsonString(t,r){return(new vx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vx,t,r)}static $(){return["StartXaiTeamLinkResponse|1 connect_url 9"]}}class xx extends T{constructor(t){super(),this.organizationId="",this.xaiTeamId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xx).fromBinary(t,r)}static fromJson(t,r){return(new xx).fromJson(t,r)}static fromJsonString(t,r){return(new xx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xx,t,r)}static $(){return["ConfirmXaiTeamLinkRequest|1 organization_id 9|2 xai_team_id 9"]}}class kx extends T{constructor(t){super(),this.linked=!1,this.xaiTeamId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kx).fromBinary(t,r)}static fromJson(t,r){return(new kx).fromJson(t,r)}static fromJsonString(t,r){return(new kx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kx,t,r)}static $(){return["ConfirmXaiTeamLinkResponse|1 linked 8|2 xai_team_id 9"]}}class Ex extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ex).fromBinary(t,r)}static fromJson(t,r){return(new Ex).fromJson(t,r)}static fromJsonString(t,r){return(new Ex).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ex,t,r)}static $(){return["CancelXaiTeamLinkProposalRequest|1 organization_id 9"]}}class Cx extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cx).fromBinary(t,r)}static fromJson(t,r){return(new Cx).fromJson(t,r)}static fromJsonString(t,r){return(new Cx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cx,t,r)}static $(){return["CancelXaiTeamLinkProposalResponse"]}}class Tx extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tx).fromBinary(t,r)}static fromJson(t,r){return(new Tx).fromJson(t,r)}static fromJsonString(t,r){return(new Tx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tx,t,r)}static $(){return["UnlinkXaiTeamRequest|1 organization_id 9"]}}class Ux extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ux).fromBinary(t,r)}static fromJson(t,r){return(new Ux).fromJson(t,r)}static fromJsonString(t,r){return(new Ux).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ux,t,r)}static $(){return["UnlinkXaiTeamResponse"]}}class Ax extends T{constructor(t){super(),this.organizationId="",this.amountCents=n.protoInt64.zero,this.transferId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ax).fromBinary(t,r)}static fromJson(t,r){return(new Ax).fromJson(t,r)}static fromJsonString(t,r){return(new Ax).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ax,t,r)}static $(){return["TransferXaiCreditsRequest|1 organization_id 9|2 amount_cents 3|3 transfer_id 9"]}}class $x extends T{constructor(t){super(),this.outcome=Lr.UNSPECIFIED,this.transferId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $x).fromBinary(t,r)}static fromJson(t,r){return(new $x).fromJson(t,r)}static fromJsonString(t,r){return(new $x).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($x,t,r)}static $(){return["TransferXaiCreditsResponse|1 outcome #0|2 transfer_id 9",Lr]}}class Mx extends T{constructor(t){super(),this.organizationId="",this.transferId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mx).fromBinary(t,r)}static fromJson(t,r){return(new Mx).fromJson(t,r)}static fromJsonString(t,r){return(new Mx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mx,t,r)}static $(){return["GetXaiCreditTransferStatusRequest|1 organization_id 9|2 transfer_id 9"]}}class Ox extends T{constructor(t){super(),this.organizationId="",this.pageSize=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ox).fromBinary(t,r)}static fromJson(t,r){return(new Ox).fromJson(t,r)}static fromJsonString(t,r){return(new Ox).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ox,t,r)}static $(){return["ListXaiCreditTransfersRequest|1 organization_id 9|2 page_size 5"]}}class Dx extends T{constructor(t){super(),this.transferId="",this.createdAtMs=n.protoInt64.zero,this.amountCents=n.protoInt64.zero,this.status="",this.outcome=Lr.UNSPECIFIED,this.requestedByUserDisplayName="",this.requestedByUserEmail="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dx).fromBinary(t,r)}static fromJson(t,r){return(new Dx).fromJson(t,r)}static fromJsonString(t,r){return(new Dx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dx,t,r)}static $(){return["XaiCreditTransfer|1 transfer_id 9|2 created_at_ms 3|3 amount_cents 3|4 status 9|5 outcome #0|6 requested_by_user_id 5?|7 requested_by_user_display_name 9|8 requested_by_user_email 9",Lr]}}class Nx extends T{constructor(t){super(),this.transfers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nx).fromBinary(t,r)}static fromJson(t,r){return(new Nx).fromJson(t,r)}static fromJsonString(t,r){return(new Nx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nx,t,r)}static $(){return["ListXaiCreditTransfersResponse|1 transfers #0*",Dx]}}class Gx extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gx).fromBinary(t,r)}static fromJson(t,r){return(new Gx).fromJson(t,r)}static fromJsonString(t,r){return(new Gx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gx,t,r)}static $(){return["GetLinearTeamsRequest"]}}class Lx extends T{constructor(t){super(),this.teams=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lx).fromBinary(t,r)}static fromJson(t,r){return(new Lx).fromJson(t,r)}static fromJsonString(t,r){return(new Lx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Lx,t,r)}static $(){return["GetLinearTeamsResponse|1 teams #0*|2 error 9?",Fx]}}class Fx extends T{constructor(t){super(),this.id="",this.key="",this.name="",this.displayName="",this.projects=[],this.labels=[],this.states=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fx).fromBinary(t,r)}static fromJson(t,r){return(new Fx).fromJson(t,r)}static fromJsonString(t,r){return(new Fx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fx,t,r)}static $(){return["LinearTeam|1 id 9|2 key 9|3 name 9|4 display_name 9|5 description 9?|6 projects #0*|7 labels #1*|8 states #2*",zx,tk,Kx]}}class Kx extends T{constructor(t){super(),this.id="",this.name="",this.type="",this.position=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kx).fromBinary(t,r)}static fromJson(t,r){return(new Kx).fromJson(t,r)}static fromJsonString(t,r){return(new Kx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Kx,t,r)}static $(){return["LinearWorkflowState|1 id 9|2 name 9|3 color 9?|4 type 9|5 position 1"]}}class zx extends T{constructor(t){super(),this.id="",this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zx).fromBinary(t,r)}static fromJson(t,r){return(new zx).fromJson(t,r)}static fromJsonString(t,r){return(new zx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zx,t,r)}static $(){return["LinearProject|1 id 9|2 name 9"]}}class jx extends T{constructor(t){super(),this.projectId="",this.runOption=Fr.UNSPECIFIED,this.conditions="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jx).fromBinary(t,r)}static fromJson(t,r){return(new jx).fromJson(t,r)}static fromJsonString(t,r){return(new jx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jx,t,r)}static $(){return["LinearProjectSettings|1 project_id 9|2 run_option #0|3 conditions 9",Fr]}}class Hx extends T{constructor(t){super(),this.linearTeamId="",this.defaultRunOption=Fr.UNSPECIFIED,this.projectSettings=[],this.defaultConditions="",this.labelFilterMode=Kr.UNSPECIFIED,this.requiredLabelIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hx).fromBinary(t,r)}static fromJson(t,r){return(new Hx).fromJson(t,r)}static fromJsonString(t,r){return(new Hx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hx,t,r)}static $(){return["LinearTeamSettings|1 linear_team_id 9|2 default_run_option #0|3 project_settings #1*|4 default_conditions 9|5 label_filter_mode #2|6 required_label_ids 9*|7 autorun_as_user_id 5?",Fr,jx,Kr]}}class Wx extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wx).fromBinary(t,r)}static fromJson(t,r){return(new Wx).fromJson(t,r)}static fromJsonString(t,r){return(new Wx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wx,t,r)}static $(){return["GetLinearSettingsRequest|1 team_id 5?"]}}class Qx extends T{constructor(t){super(),this.teamSettings=[],this.isTeamSettings=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qx).fromBinary(t,r)}static fromJson(t,r){return(new Qx).fromJson(t,r)}static fromJsonString(t,r){return(new Qx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qx,t,r)}static $(){return["GetLinearSettingsResponse|1 team_settings #0*|2 is_team_settings 8",Hx]}}class Vx extends T{constructor(t){super(),this.linearTeamId="",this.defaultRunOption=Fr.UNSPECIFIED,this.defaultConditions="",this.labelFilterMode=Kr.UNSPECIFIED,this.requiredLabelIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vx).fromBinary(t,r)}static fromJson(t,r){return(new Vx).fromJson(t,r)}static fromJsonString(t,r){return(new Vx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vx,t,r)}static $(){return["UpdateLinearTeamSettingRequest|1 team_id 5?|2 linear_team_id 9|3 default_run_option #0|4 default_conditions 9|5 label_filter_mode #1|6 required_label_ids 9*|7 autorun_as_user_id 5?",Fr,Kr]}}class Xx extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xx).fromBinary(t,r)}static fromJson(t,r){return(new Xx).fromJson(t,r)}static fromJsonString(t,r){return(new Xx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xx,t,r)}static $(){return["UpdateLinearTeamSettingResponse|1 success 8"]}}class Yx extends T{constructor(t){super(),this.linearTeamId="",this.projectId="",this.runOption=Fr.UNSPECIFIED,this.conditions="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yx).fromBinary(t,r)}static fromJson(t,r){return(new Yx).fromJson(t,r)}static fromJsonString(t,r){return(new Yx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yx,t,r)}static $(){return["UpdateLinearProjectSettingRequest|1 team_id 5?|2 linear_team_id 9|3 project_id 9|4 run_option #0|5 conditions 9",Fr]}}class Zx extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zx).fromBinary(t,r)}static fromJson(t,r){return(new Zx).fromJson(t,r)}static fromJsonString(t,r){return(new Zx).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zx,t,r)}static $(){return["UpdateLinearProjectSettingResponse|1 success 8"]}}class tk extends T{constructor(t){super(),this.id="",this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tk).fromBinary(t,r)}static fromJson(t,r){return(new tk).fromJson(t,r)}static fromJsonString(t,r){return(new tk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tk,t,r)}static $(){return["LinearLabel|1 id 9|2 name 9|3 color 9?"]}}class rk extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rk).fromBinary(t,r)}static fromJson(t,r){return(new rk).fromJson(t,r)}static fromJsonString(t,r){return(new rk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rk,t,r)}static $(){return["GetLinearLabelsRequest|1 team_id 5?"]}}class ek extends T{constructor(t){super(),this.labels=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ek).fromBinary(t,r)}static fromJson(t,r){return(new ek).fromJson(t,r)}static fromJsonString(t,r){return(new ek).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ek,t,r)}static $(){return["GetLinearLabelsResponse|1 labels #0*|2 error 9?",tk]}}class nk extends T{constructor(t){super(),this.orderBy=zr.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nk).fromBinary(t,r)}static fromJson(t,r){return(new nk).fromJson(t,r)}static fromJsonString(t,r){return(new nk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nk,t,r)}static $(){return["GetLinearIssuesRequest|1 team_id 5?|2 linear_team_id 9?|3 search_query 9?|4 include_completed 8?|5 include_archived 8?|6 first 5?|7 after 9?|8 order_by #0|9 assigned_to_me_only 8?",zr]}}class sk extends T{constructor(t){super(),this.issues=[],this.hasMore=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sk).fromBinary(t,r)}static fromJson(t,r){return(new sk).fromJson(t,r)}static fromJsonString(t,r){return(new sk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sk,t,r)}static $(){return["GetLinearIssuesResponse|1 issues #0*|2 next_cursor 9?|3 has_more 8|4 error 9?",ik]}}class ik extends T{constructor(t){super(),this.id="",this.identifier="",this.title="",this.labelIds=[],this.archived=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ik).fromBinary(t,r)}static fromJson(t,r){return(new ik).fromJson(t,r)}static fromJsonString(t,r){return(new ik).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ik,t,r)}static $(){return["LinearIssue|1 id 9|2 identifier 9|3 title 9|4 description 9?|5 state_id 9?|6 state_name 9?|7 state_type 9?|8 team_id 9?|9 project_id 9?|10 project_name 9?|11 assignee_id 9?|12 assignee_name 9?|13 label_ids 9*|14 priority 5?|15 archived 8|16 created_at 3?|17 updated_at 3?|18 url 9?|19 due_date 9?"]}}class ok extends T{constructor(t){super(),this.workspaceUrlKey="",this.identifiers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ok).fromBinary(t,r)}static fromJson(t,r){return(new ok).fromJson(t,r)}static fromJsonString(t,r){return(new ok).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ok,t,r)}static $(){return["BatchGetLinearIssueSummariesRequest|1 workspace_url_key 9|2 identifiers 9*|3 team_id 5?"]}}class ak extends T{constructor(t){super(),this.identifier="",this.title="",this.url="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ak).fromBinary(t,r)}static fromJson(t,r){return(new ak).fromJson(t,r)}static fromJsonString(t,r){return(new ak).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ak,t,r)}static $(){return["LinearIssueSummary|1 identifier 9|2 title 9|3 url 9|4 state_name 9?|5 state_type 9?|6 state_color 9?|7 assignee_name 9?|8 assignee_avatar_url 9?|9 project_name 9?|10 team_name 9?|11 priority 5?|12 priority_label 9?|13 updated_at 3?"]}}class uk extends T{constructor(t){super(),this.issues=[],this.missingIdentifiers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uk).fromBinary(t,r)}static fromJson(t,r){return(new uk).fromJson(t,r)}static fromJsonString(t,r){return(new uk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uk,t,r)}static $(){return["BatchGetLinearIssueSummariesResponse|1 issues #0*|2 missing_identifiers 9*|3 unavailable_reason #1?|4 retry_after_ms 3?",ak,jr]}}class ck extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ck).fromBinary(t,r)}static fromJson(t,r){return(new ck).fromJson(t,r)}static fromJsonString(t,r){return(new ck).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ck,t,r)}static $(){return["GetPagerDutyAuthUrlRequest"]}}class lk extends T{constructor(t){super(),this.authUrl="",this.csrfToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lk).fromBinary(t,r)}static fromJson(t,r){return(new lk).fromJson(t,r)}static fromJsonString(t,r){return(new lk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lk,t,r)}static $(){return["GetPagerDutyAuthUrlResponse|1 auth_url 9|2 csrf_token 9"]}}class mk extends T{constructor(t){super(),this.code="",this.state="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mk).fromBinary(t,r)}static fromJson(t,r){return(new mk).fromJson(t,r)}static fromJsonString(t,r){return(new mk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mk,t,r)}static $(){return["ConnectPagerDutyCallbackRequest|1 code 9|2 state 9"]}}class fk extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fk).fromBinary(t,r)}static fromJson(t,r){return(new fk).fromJson(t,r)}static fromJsonString(t,r){return(new fk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fk,t,r)}static $(){return["ConnectPagerDutyCallbackResponse|1 success 8"]}}class dk extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dk).fromBinary(t,r)}static fromJson(t,r){return(new dk).fromJson(t,r)}static fromJsonString(t,r){return(new dk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dk,t,r)}static $(){return["GetPagerDutyStatusRequest"]}}class pk extends T{constructor(t){super(),this.isConnected=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pk).fromBinary(t,r)}static fromJson(t,r){return(new pk).fromJson(t,r)}static fromJsonString(t,r){return(new pk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pk,t,r)}static $(){return["GetPagerDutyStatusResponse|1 is_connected 8|2 account_name 9?|3 subdomain 9?"]}}class hk extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hk).fromBinary(t,r)}static fromJson(t,r){return(new hk).fromJson(t,r)}static fromJsonString(t,r){return(new hk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hk,t,r)}static $(){return["GetPagerDutyServicesRequest"]}}class gk extends T{constructor(t){super(),this.services=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gk).fromBinary(t,r)}static fromJson(t,r){return(new gk).fromJson(t,r)}static fromJsonString(t,r){return(new gk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gk,t,r)}static $(){return["GetPagerDutyServicesResponse|1 services #0*",_k]}}class _k extends T{constructor(t){super(),this.id="",this.name="",this.description="",this.status="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _k).fromBinary(t,r)}static fromJson(t,r){return(new _k).fromJson(t,r)}static fromJsonString(t,r){return(new _k).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_k,t,r)}static $(){return["PagerDutyServiceInfo|1 id 9|2 name 9|3 description 9|4 status 9"]}}class Jk extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jk).fromBinary(t,r)}static fromJson(t,r){return(new Jk).fromJson(t,r)}static fromJsonString(t,r){return(new Jk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jk,t,r)}static $(){return["DisconnectPagerDutyRequest"]}}class wk extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wk).fromBinary(t,r)}static fromJson(t,r){return(new wk).fromJson(t,r)}static fromJsonString(t,r){return(new wk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wk,t,r)}static $(){return["DisconnectPagerDutyResponse|1 success 8"]}}class yk extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yk).fromBinary(t,r)}static fromJson(t,r){return(new yk).fromJson(t,r)}static fromJsonString(t,r){return(new yk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yk,t,r)}static $(){return["GetSlackUserSettingsRequest|1 team_id 5"]}}class Sk extends T{constructor(t){super(),this.hasSlackAuth=!1,this.defaultRepo="",this.defaultBranch="",this.defaultModel="",this.canShow=!1,this.openPrByDefault=!1,this.ciFailureFollowupEnabled=!1,this.branchPrefix="",this.slackCursorTeamLocked=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sk).fromBinary(t,r)}static fromJson(t,r){return(new Sk).fromJson(t,r)}static fromJsonString(t,r){return(new Sk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sk,t,r)}static $(){return["GetSlackUserSettingsResponse|1 has_slack_auth 8|2 default_repo 9|3 default_branch 9|4 default_model 9|5 can_show 8|6 open_pr_by_default 8|7 use_github_app_for_auto_draft_prs 8?|8 ci_failure_followup_enabled 8|9 branch_prefix 9|10 default_model_selection #0?|11 slack_cursor_team_id 5?|12 slack_effective_cursor_team_id 5?|13 slack_cursor_team_locked 8|14 default_environment_public_id 9?|15 origin_link_unfurls_enabled 8?",o.M6]}}class qk extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qk).fromBinary(t,r)}static fromJson(t,r){return(new qk).fromJson(t,r)}static fromJsonString(t,r){return(new qk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qk,t,r)}static $(){return["ListSlackConnectedWorkspacesRequest|1 team_id 5"]}}class Bk extends T{constructor(t){super(),this.slackTeamId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bk).fromBinary(t,r)}static fromJson(t,r){return(new Bk).fromJson(t,r)}static fromJsonString(t,r){return(new Bk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bk,t,r)}static $(){return["SlackConnectedWorkspace|1 slack_team_id 9|2 slack_enterprise_id 9?|3 linked_at #0|4 connected_by_team_id 5?|5 display_name 9?",n.Timestamp]}}class Ik extends T{constructor(t){super(),this.workspaces=[],this.truncated=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ik).fromBinary(t,r)}static fromJson(t,r){return(new Ik).fromJson(t,r)}static fromJsonString(t,r){return(new Ik).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ik,t,r)}static $(){return["ListSlackConnectedWorkspacesResponse|1 workspaces #0*|2 truncated 8",Bk]}}class Pk extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pk).fromBinary(t,r)}static fromJson(t,r){return(new Pk).fromJson(t,r)}static fromJsonString(t,r){return(new Pk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pk,t,r)}static $(){return["ListOrganizationSlackConnectedWorkspacesRequest|1 organization_id 9"]}}class bk extends T{constructor(t){super(),this.workspaces=[],this.truncated=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bk).fromBinary(t,r)}static fromJson(t,r){return(new bk).fromJson(t,r)}static fromJsonString(t,r){return(new bk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bk,t,r)}static $(){return["ListOrganizationSlackConnectedWorkspacesResponse|1 workspaces #0*|2 truncated 8",Bk]}}class Rk extends T{constructor(t){super(),this.allWorkspaces=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rk).fromBinary(t,r)}static fromJson(t,r){return(new Rk).fromJson(t,r)}static fromJsonString(t,r){return(new Rk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rk,t,r)}static $(){return["UnlinkSlackAccessRequest|1 slack_team_id 9?|2 all_workspaces 8"]}}class vk extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vk).fromBinary(t,r)}static fromJson(t,r){return(new vk).fromJson(t,r)}static fromJsonString(t,r){return(new vk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vk,t,r)}static $(){return["UnlinkSlackAccessResponse|1 success 8"]}}class xk extends T{constructor(t){super(),this.slackTeamId="",this.displayName="",this.linkedAtMs=n.protoInt64.zero,this.status=Hr.UNSPECIFIED,this.sandAutomationCount=0,this.sandAutomationCountTruncated=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xk).fromBinary(t,r)}static fromJson(t,r){return(new xk).fromJson(t,r)}static fromJsonString(t,r){return(new xk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xk,t,r)}static $(){return["SlackLinkedWorkspace|1 slack_team_id 9|2 display_name 9|3 linked_at_ms 3|4 status #0|5 sand_automation_count 5|6 sand_automation_count_truncated 8",Hr]}}class kk extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kk).fromBinary(t,r)}static fromJson(t,r){return(new kk).fromJson(t,r)}static fromJsonString(t,r){return(new kk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kk,t,r)}static $(){return["ListSlackLinkedWorkspacesRequest"]}}class Ek extends T{constructor(t){super(),this.workspaces=[],this.canLinkAnotherWorkspace=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ek).fromBinary(t,r)}static fromJson(t,r){return(new Ek).fromJson(t,r)}static fromJsonString(t,r){return(new Ek).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ek,t,r)}static $(){return["ListSlackLinkedWorkspacesResponse|1 workspaces #0*|2 can_link_another_workspace 8",xk]}}class Ck extends T{constructor(t){super(),this.slackTeamId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ck).fromBinary(t,r)}static fromJson(t,r){return(new Ck).fromJson(t,r)}static fromJsonString(t,r){return(new Ck).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ck,t,r)}static $(){return["GetSlackLinkPreviewRequest|1 slack_team_id 9"]}}class Tk extends T{constructor(t){super(),this.replacesWorkspaces=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tk).fromBinary(t,r)}static fromJson(t,r){return(new Tk).fromJson(t,r)}static fromJsonString(t,r){return(new Tk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tk,t,r)}static $(){return["GetSlackLinkPreviewResponse|1 replaces_workspaces #0*",xk]}}class Uk extends T{constructor(t){super(),this.teamId=0,this.defaultRepo="",this.defaultBranch="",this.defaultModel="",this.openPrByDefault=!1,this.ciFailureFollowupEnabled=!1,this.branchPrefix="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Uk).fromBinary(t,r)}static fromJson(t,r){return(new Uk).fromJson(t,r)}static fromJsonString(t,r){return(new Uk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Uk,t,r)}static $(){return["UpdateSlackUserSettingsRequest|1 team_id 5|2 default_repo 9|3 default_branch 9|4 default_model 9|5 open_pr_by_default 8|6 use_github_app_for_auto_draft_prs 8?|7 ci_failure_followup_enabled 8|8 branch_prefix 9|9 default_model_selection #0?|10 default_environment_public_id 9?|11 origin_link_unfurls_enabled 8?",o.M6]}}class Ak extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ak).fromBinary(t,r)}static fromJson(t,r){return(new Ak).fromJson(t,r)}static fromJsonString(t,r){return(new Ak).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ak,t,r)}static $(){return["UpdateSlackUserSettingsResponse"]}}class $k extends T{constructor(t){super(),this.id=0,this.pattern="",this.repo="",this.isTeamRule=!1,this.targetType=Wr.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $k).fromBinary(t,r)}static fromJson(t,r){return(new $k).fromJson(t,r)}static fromJsonString(t,r){return(new $k).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($k,t,r)}static $(){return["SlackRepoRoutingRule|1 id 5|2 pattern 9|3 repo 9|4 is_team_rule 8|5 target_type #0|6 environment_public_id 9?",Wr]}}class Mk extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mk).fromBinary(t,r)}static fromJson(t,r){return(new Mk).fromJson(t,r)}static fromJsonString(t,r){return(new Mk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mk,t,r)}static $(){return["GetSlackRepoRoutingRulesRequest|1 team_id 5"]}}class Ok extends T{constructor(t){super(),this.rules=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ok).fromBinary(t,r)}static fromJson(t,r){return(new Ok).fromJson(t,r)}static fromJsonString(t,r){return(new Ok).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ok,t,r)}static $(){return["GetSlackRepoRoutingRulesResponse|1 rules #0*",$k]}}class Dk extends T{constructor(t){super(),this.teamId=0,this.pattern="",this.repo="",this.targetType=Wr.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dk).fromBinary(t,r)}static fromJson(t,r){return(new Dk).fromJson(t,r)}static fromJsonString(t,r){return(new Dk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dk,t,r)}static $(){return["CreateSlackRepoRoutingRuleRequest|1 team_id 5|2 pattern 9|3 repo 9|4 target_type #0|5 environment_public_id 9?",Wr]}}class Nk extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nk).fromBinary(t,r)}static fromJson(t,r){return(new Nk).fromJson(t,r)}static fromJsonString(t,r){return(new Nk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nk,t,r)}static $(){return["CreateSlackRepoRoutingRuleResponse|1 rule #0",$k]}}class Gk extends T{constructor(t){super(),this.teamId=0,this.ruleId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gk).fromBinary(t,r)}static fromJson(t,r){return(new Gk).fromJson(t,r)}static fromJsonString(t,r){return(new Gk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gk,t,r)}static $(){return["DeleteSlackRepoRoutingRuleRequest|1 team_id 5|2 rule_id 9"]}}class Lk extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lk).fromBinary(t,r)}static fromJson(t,r){return(new Lk).fromJson(t,r)}static fromJsonString(t,r){return(new Lk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Lk,t,r)}static $(){return["DeleteSlackRepoRoutingRuleResponse"]}}class Fk extends T{constructor(t){super(),this.teamId=0,this.ruleId="",this.pattern="",this.repo="",this.targetType=Wr.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fk).fromBinary(t,r)}static fromJson(t,r){return(new Fk).fromJson(t,r)}static fromJsonString(t,r){return(new Fk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fk,t,r)}static $(){return["UpdateSlackRepoRoutingRuleRequest|1 team_id 5|2 rule_id 9|3 pattern 9|4 repo 9|5 target_type #0|6 environment_public_id 9?",Wr]}}class Kk extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kk).fromBinary(t,r)}static fromJson(t,r){return(new Kk).fromJson(t,r)}static fromJsonString(t,r){return(new Kk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Kk,t,r)}static $(){return["UpdateSlackRepoRoutingRuleResponse|1 rule #0",$k]}}class zk extends T{constructor(t){super(),this.id=0,this.repo="",this.workerName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zk).fromBinary(t,r)}static fromJson(t,r){return(new zk).fromJson(t,r)}static fromJsonString(t,r){return(new zk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zk,t,r)}static $(){return["SlackDefaultWorkerRule|1 id 5|2 repo 9|3 worker_name 9"]}}class jk extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jk).fromBinary(t,r)}static fromJson(t,r){return(new jk).fromJson(t,r)}static fromJsonString(t,r){return(new jk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jk,t,r)}static $(){return["GetSlackDefaultWorkerRulesRequest"]}}class Hk extends T{constructor(t){super(),this.rules=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hk).fromBinary(t,r)}static fromJson(t,r){return(new Hk).fromJson(t,r)}static fromJsonString(t,r){return(new Hk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hk,t,r)}static $(){return["GetSlackDefaultWorkerRulesResponse|1 rules #0*",zk]}}class Wk extends T{constructor(t){super(),this.repo="",this.workerName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wk).fromBinary(t,r)}static fromJson(t,r){return(new Wk).fromJson(t,r)}static fromJsonString(t,r){return(new Wk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wk,t,r)}static $(){return["SetSlackDefaultWorkerRuleRequest|1 repo 9|2 worker_name 9"]}}class Qk extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qk).fromBinary(t,r)}static fromJson(t,r){return(new Qk).fromJson(t,r)}static fromJsonString(t,r){return(new Qk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qk,t,r)}static $(){return["SetSlackDefaultWorkerRuleResponse|1 rule #0",zk]}}class Vk extends T{constructor(t){super(),this.repo="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vk).fromBinary(t,r)}static fromJson(t,r){return(new Vk).fromJson(t,r)}static fromJsonString(t,r){return(new Vk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vk,t,r)}static $(){return["DeleteSlackDefaultWorkerRuleRequest|1 repo 9"]}}class Xk extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xk).fromBinary(t,r)}static fromJson(t,r){return(new Xk).fromJson(t,r)}static fromJsonString(t,r){return(new Xk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xk,t,r)}static $(){return["DeleteSlackDefaultWorkerRuleResponse"]}}class Yk extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yk).fromBinary(t,r)}static fromJson(t,r){return(new Yk).fromJson(t,r)}static fromJsonString(t,r){return(new Yk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yk,t,r)}static $(){return["IsOnNewPricingRequest"]}}class Zk extends T{constructor(t){super(),this.isOnNewPricing=!1,this.isOptedOut=!1,this.hasAutoSpillover=!1,this.hasTieredSelfServeTeamSpillover=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zk).fromBinary(t,r)}static fromJson(t,r){return(new Zk).fromJson(t,r)}static fromJsonString(t,r){return(new Zk).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zk,t,r)}static $(){return["IsOnNewPricingResponse|1 is_on_new_pricing 8|2 is_opted_out 8|3 has_auto_spillover 8|4 dashboard_user_id 5?|5 has_tiered_self_serve_team_spillover 8"]}}class tE extends T{constructor(t){super(),this.checkpoints={},this.isTeamAdmin=!1,this.isLoading=!1,this.isPrivacyModeLoading=!1,this.isGithubLoading=!1,this.isUsagePricingLoading=!1,this.triggeredByGithubConnect=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tE).fromBinary(t,r)}static fromJson(t,r){return(new tE).fromJson(t,r)}static fromJsonString(t,r){return(new tE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tE,t,r)}static $(){return["LogSlackbotAuthConversionFunnelRequest|1 checkpoints 9,8|2 privacy_mode #0?|3 is_team_admin 8|4 is_loading 8|5 is_privacy_mode_loading 8|6 is_github_loading 8|7 is_usage_pricing_loading 8|8 triggered_by_github_connect 8|9 scm_provider 9?",s.Y]}}class rE extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rE).fromBinary(t,r)}static fromJson(t,r){return(new rE).fromJson(t,r)}static fromJsonString(t,r){return(new rE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rE,t,r)}static $(){return["LogSlackbotAuthConversionFunnelResponse"]}}class eE extends T{constructor(t){super(),this.origin=nE.UNSPECIFIED,this.skipSetupFlow=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eE).fromBinary(t,r)}static fromJson(t,r){return(new eE).fromJson(t,r)}static fromJsonString(t,r){return(new eE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eE,t,r)}static $(){return["LogClickedConnectSlackRequest|1 origin #0|2 skip_setup_flow 8",nE]}}var nE=(0,a.QT)(n.proto3,C,"LogClickedConnectSlackRequest.Origin",[[0,"UNSPECIFIED"],[1,"APP"],[2,"WEBSITE"],[3,"SLACK"],[4,"PUBLIC_URL"]],1);class sE extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sE).fromBinary(t,r)}static fromJson(t,r){return(new sE).fromJson(t,r)}static fromJsonString(t,r){return(new sE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sE,t,r)}static $(){return["LogClickedConnectSlackResponse"]}}class iE extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iE).fromBinary(t,r)}static fromJson(t,r){return(new iE).fromJson(t,r)}static fromJsonString(t,r){return(new iE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iE,t,r)}static $(){return["CheckUserApiKeyAccessRequest"]}}class oE extends T{constructor(t){super(),this.hasAccess=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oE).fromBinary(t,r)}static fromJson(t,r){return(new oE).fromJson(t,r)}static fromJsonString(t,r){return(new oE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oE,t,r)}static $(){return["CheckUserApiKeyAccessResponse|1 has_access 8|2 personal_api_key_creation_allowed 8?"]}}class aE extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aE).fromBinary(t,r)}static fromJson(t,r){return(new aE).fromJson(t,r)}static fromJsonString(t,r){return(new aE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aE,t,r)}static $(){return["IsAllowedFreeTrialUsageRequest"]}}class uE extends T{constructor(t){super(),this.isAllowed=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uE).fromBinary(t,r)}static fromJson(t,r){return(new uE).fromJson(t,r)}static fromJsonString(t,r){return(new uE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uE,t,r)}static $(){return["IsAllowedFreeTrialUsageResponse|1 is_allowed 8"]}}class cE extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cE).fromBinary(t,r)}static fromJson(t,r){return(new cE).fromJson(t,r)}static fromJsonString(t,r){return(new cE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cE,t,r)}static $(){return["IsNextSetupRunFreeRequest|1 bc_id 9?"]}}class lE extends T{constructor(t){super(),this.isFree=!1,this.remainingRuns=0,this.isPromotionEnabled=!1,this.areFollowupsFree=!1,this.remainingFollowups=0,this.isCurrentRunFree=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lE).fromBinary(t,r)}static fromJson(t,r){return(new lE).fromJson(t,r)}static fromJsonString(t,r){return(new lE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lE,t,r)}static $(){return["IsNextSetupRunFreeResponse|1 is_free 8|2 remaining_runs 13|3 is_promotion_enabled 8|4 are_followups_free 8|5 remaining_followups 13|6 is_current_run_free 8"]}}class mE extends T{constructor(t){super(),this.name="",this.id=0,this.memberCount=0,this.hardLimitPerUserDollars=0,this.externalId="",this.perUserMonthlyLimitDollars=0,this.canonicalGroupPublicId="",this.owningTeamId=0,this.firstMcpRuleAddsGrokConnectorsRule=!1,this.cloudDropsGrokConnectorRules=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mE).fromBinary(t,r)}static fromJson(t,r){return(new mE).fromJson(t,r)}static fromJsonString(t,r){return(new mE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mE,t,r)}static $(){return["DirectoryGroup|1 name 9|2 id 5|3 member_count 5|4 hard_limit_per_user_dollars 5|5 auto_run_controls #0|6 external_id 9|7 per_user_monthly_limit_dollars 5|8 allowed_mcp_configuration #1|9 canonical_group_public_id 9|10 owning_team_id 5|11 first_mcp_rule_adds_grok_connectors_rule 8|12 cloud_drops_grok_connector_rules 8",j_,V_]}}class fE extends T{constructor(t){super(),this.teamId=0,this.unmigratedOnly=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fE).fromBinary(t,r)}static fromJson(t,r){return(new fE).fromJson(t,r)}static fromJsonString(t,r){return(new fE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fE,t,r)}static $(){return["GetDirectoryGroupsRequest|1 team_id 5|2 unmigrated_only 8"]}}class dE extends T{constructor(t){super(),this.directoryGroups=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dE).fromBinary(t,r)}static fromJson(t,r){return(new dE).fromJson(t,r)}static fromJsonString(t,r){return(new dE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dE,t,r)}static $(){return["GetDirectoryGroupsResponse|1 directory_groups #0*",mE]}}class pE extends T{constructor(t){super(),this.directoryGroupId=0,this.perUserMonthlyLimitDollars=0,this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pE).fromBinary(t,r)}static fromJson(t,r){return(new pE).fromJson(t,r)}static fromJsonString(t,r){return(new pE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pE,t,r)}static $(){return["UpdateDirectoryGroupSettingsRequest|1 directory_group_id 5|2 hard_limit_per_user_dollars 5?|4 per_user_monthly_limit_dollars 5|3 auto_run_controls #0|5 team_id 5|6 allowed_mcp_configuration #1?",j_,V_]}}class hE extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hE).fromBinary(t,r)}static fromJson(t,r){return(new hE).fromJson(t,r)}static fromJsonString(t,r){return(new hE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hE,t,r)}static $(){return["UpdateDirectoryGroupSettingsResponse"]}}class gE extends T{constructor(t){super(),this.day=n.protoInt64.zero,this.spendCents=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gE).fromBinary(t,r)}static fromJson(t,r){return(new gE).fromJson(t,r)}static fromJsonString(t,r){return(new gE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gE,t,r)}static $(){return["DailySpendPoint|1 day 3|2 spend_cents 5"]}}class _E extends T{constructor(t){super(),this.periodStartMs=n.protoInt64.zero,this.periodEndMs=n.protoInt64.zero,this.groupBy=Vr.UNSPECIFIED,this.products=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _E).fromBinary(t,r)}static fromJson(t,r){return(new _E).fromJson(t,r)}static fromJsonString(t,r){return(new _E).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_E,t,r)}static $(){return["GetDailySpendByCategoryRequest|1 team_id 5?|2 user_id 5?|3 period_start_ms 3|4 period_end_ms 3|5 group_by #0|6 spend_type #1?|7 service_account_id 9?|8 cloud_agent_id 9?|9 automation_id 9?|10 automation_managed_type 9?|11 client_type 9?|12 products 9*|13 include_credit_usage 8?|14 ranking_metric #2?",Vr,Yr,Xr]}}class JE extends T{constructor(t){super(),this.day=n.protoInt64.zero,this.category="",this.spendCents=0,this.totalTokens=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new JE).fromBinary(t,r)}static fromJson(t,r){return(new JE).fromJson(t,r)}static fromJsonString(t,r){return(new JE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(JE,t,r)}static $(){return["DailySpendByCategory|1 day 3|2 category 9|3 spend_cents 5|4 total_tokens 3"]}}class wE extends T{constructor(t){super(),this.dailySpend=[],this.categories=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wE).fromBinary(t,r)}static fromJson(t,r){return(new wE).fromJson(t,r)}static fromJsonString(t,r){return(new wE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wE,t,r)}static $(){return["GetDailySpendByCategoryResponse|1 daily_spend #0*|2 categories 9*|3 effective_limit_cents 5?",JE]}}class yE extends T{constructor(t){super(),this.organizationId="",this.periodStartMs=n.protoInt64.zero,this.periodEndMs=n.protoInt64.zero,this.groupBy=Vr.UNSPECIFIED,this.products=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yE).fromBinary(t,r)}static fromJson(t,r){return(new yE).fromJson(t,r)}static fromJsonString(t,r){return(new yE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yE,t,r)}static $(){return["GetOrgDailySpendByCategoryRequest|1 organization_id 9|2 period_start_ms 3|3 period_end_ms 3|4 group_by #0|5 spend_type #1?|6 team_id 5?|7 service_account_id 9?|8 cloud_agent_id 9?|9 automation_id 9?|10 automation_managed_type 9?|11 client_type 9?|12 products 9*|13 user_id 5?|14 ranking_metric #2?",Vr,Yr,Xr]}}class SE extends T{constructor(t){super(),this.id=0,this.name="",this.teamId=0,this.memberCount=0,this.createdAt=n.protoInt64.zero,this.updatedAt=n.protoInt64.zero,this.type=Qr.UNSPECIFIED,this.members=[],this.formerMembers=[],this.dailySpend=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new SE).fromBinary(t,r)}static fromJson(t,r){return(new SE).fromJson(t,r)}static fromJsonString(t,r){return(new SE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(SE,t,r)}static $(){return["Group|1 id 5|2 name 9|3 team_id 5|4 directory_group_id 5?|5 member_count 5|6 created_at 3|7 updated_at 3|8 type #0|9 members #1*|10 spend_cents 5?|11 directory_group_name 9?|12 former_members #1*|13 daily_spend #2*",Qr,qE,gE]}}class qE extends T{constructor(t){super(),this.userId=0,this.name="",this.email="",this.joinedAt=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qE).fromBinary(t,r)}static fromJson(t,r){return(new qE).fromJson(t,r)}static fromJsonString(t,r){return(new qE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qE,t,r)}static $(){return["GroupMember|1 user_id 5|2 name 9|3 email 9|4 joined_at 3|5 spend_cents 5?|6 left_at 3?|7 effective_per_user_limit_dollars 5?"]}}class BE extends T{constructor(t){super(),this.serviceAccountId="",this.name="",this.serviceType="",this.spendCents=0,this.dailySpend=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new BE).fromBinary(t,r)}static fromJson(t,r){return(new BE).fromJson(t,r)}static fromJsonString(t,r){return(new BE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(BE,t,r)}static $(){return["ServiceAccountSpendInfo|1 service_account_id 9|2 name 9|3 service_type 9|4 spend_cents 5|5 daily_spend #0*|6 creator_name 9?|7 created_at 3?",gE]}}class IE extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new IE).fromBinary(t,r)}static fromJson(t,r){return(new IE).fromJson(t,r)}static fromJsonString(t,r){return(new IE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(IE,t,r)}static $(){return["GetGroupsRequest|1 team_id 5|2 type #0?|3 reference_date 3?",Qr]}}class PE extends T{constructor(t){super(),this.groups=[],this.unassignedMembers=[],this.teamDailySpend=[],this.serviceAccounts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new PE).fromBinary(t,r)}static fromJson(t,r){return(new PE).fromJson(t,r)}static fromJsonString(t,r){return(new PE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(PE,t,r)}static $(){return["GetGroupsResponse|1 groups #0*|2 unassigned_members #1*|3 unassigned_group #0?|4 cycle_start 3?|5 cycle_end 3?|6 team_daily_spend #2*|7 service_accounts #3*",SE,qE,gE,BE]}}class bE extends T{constructor(t){super(),this.groupId=0,this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bE).fromBinary(t,r)}static fromJson(t,r){return(new bE).fromJson(t,r)}static fromJsonString(t,r){return(new bE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bE,t,r)}static $(){return["GetGroupMembersRequest|1 group_id 5|2 team_id 5|3 type #0?",Qr]}}class RE extends T{constructor(t){super(),this.members=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new RE).fromBinary(t,r)}static fromJson(t,r){return(new RE).fromJson(t,r)}static fromJsonString(t,r){return(new RE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(RE,t,r)}static $(){return["GetGroupMembersResponse|1 members #0*",qE]}}class vE extends T{constructor(t){super(),this.teamId=0,this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vE).fromBinary(t,r)}static fromJson(t,r){return(new vE).fromJson(t,r)}static fromJsonString(t,r){return(new vE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vE,t,r)}static $(){return["CreateGroupRequest|1 team_id 5|2 name 9|3 directory_group_id 5?|4 type #0?",Qr]}}class xE extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xE).fromBinary(t,r)}static fromJson(t,r){return(new xE).fromJson(t,r)}static fromJsonString(t,r){return(new xE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xE,t,r)}static $(){return["CreateGroupResponse|1 group #0",SE]}}class kE extends T{constructor(t){super(),this.groupId=0,this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kE).fromBinary(t,r)}static fromJson(t,r){return(new kE).fromJson(t,r)}static fromJsonString(t,r){return(new kE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kE,t,r)}static $(){return["UpdateGroupRequest|1 group_id 5|2 team_id 5|3 name 9?|4 type #0?|5 directory_group_id 5?",Qr]}}class EE extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new EE).fromBinary(t,r)}static fromJson(t,r){return(new EE).fromJson(t,r)}static fromJsonString(t,r){return(new EE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(EE,t,r)}static $(){return["UpdateGroupResponse|1 group #0",SE]}}class CE extends T{constructor(t){super(),this.groupId=0,this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new CE).fromBinary(t,r)}static fromJson(t,r){return(new CE).fromJson(t,r)}static fromJsonString(t,r){return(new CE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(CE,t,r)}static $(){return["DeleteGroupRequest|1 group_id 5|2 team_id 5|3 type #0?",Qr]}}class TE extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new TE).fromBinary(t,r)}static fromJson(t,r){return(new TE).fromJson(t,r)}static fromJsonString(t,r){return(new TE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(TE,t,r)}static $(){return["DeleteGroupResponse"]}}class UE extends T{constructor(t){super(),this.groupId=0,this.teamId=0,this.userIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new UE).fromBinary(t,r)}static fromJson(t,r){return(new UE).fromJson(t,r)}static fromJsonString(t,r){return(new UE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(UE,t,r)}static $(){return["AddGroupMembersRequest|1 group_id 5|2 team_id 5|3 user_ids 5*|4 type #0?",Qr]}}class AE extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new AE).fromBinary(t,r)}static fromJson(t,r){return(new AE).fromJson(t,r)}static fromJsonString(t,r){return(new AE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(AE,t,r)}static $(){return["AddGroupMembersResponse|1 group #0",SE]}}class $E extends T{constructor(t){super(),this.groupId=0,this.teamId=0,this.userIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $E).fromBinary(t,r)}static fromJson(t,r){return(new $E).fromJson(t,r)}static fromJsonString(t,r){return(new $E).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($E,t,r)}static $(){return["RemoveGroupMembersRequest|1 group_id 5|2 team_id 5|3 user_ids 5*|4 type #0?",Qr]}}class ME extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ME).fromBinary(t,r)}static fromJson(t,r){return(new ME).fromJson(t,r)}static fromJsonString(t,r){return(new ME).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ME,t,r)}static $(){return["RemoveGroupMembersResponse|1 group #0",SE]}}class OE extends T{constructor(t){super(),this.email="",this.groupName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new OE).fromBinary(t,r)}static fromJson(t,r){return(new OE).fromJson(t,r)}static fromJsonString(t,r){return(new OE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(OE,t,r)}static $(){return["GroupAssignment|1 email 9|2 group_name 9"]}}class DE extends T{constructor(t){super(),this.teamId=0,this.assignments=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new DE).fromBinary(t,r)}static fromJson(t,r){return(new DE).fromJson(t,r)}static fromJsonString(t,r){return(new DE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(DE,t,r)}static $(){return["BulkAssignGroupMembersRequest|1 team_id 5|2 assignments #0*|3 type #1?",OE,Qr]}}class NE extends T{constructor(t){super(),this.email="",this.groupName="",this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new NE).fromBinary(t,r)}static fromJson(t,r){return(new NE).fromJson(t,r)}static fromJsonString(t,r){return(new NE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(NE,t,r)}static $(){return["AssignmentResult|1 email 9|2 group_name 9|3 success 8|4 error_message 9?"]}}class GE extends T{constructor(t){super(),this.createdGroups=[],this.results=[],this.successCount=0,this.errorCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new GE).fromBinary(t,r)}static fromJson(t,r){return(new GE).fromJson(t,r)}static fromJsonString(t,r){return(new GE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(GE,t,r)}static $(){return["BulkAssignGroupMembersResponse|1 created_groups 9*|2 results #0*|3 success_count 5|4 error_count 5",NE]}}class LE extends T{constructor(t){super(),this.groupId=0,this.teamId=0,this.directoryGroupId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new LE).fromBinary(t,r)}static fromJson(t,r){return(new LE).fromJson(t,r)}static fromJsonString(t,r){return(new LE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(LE,t,r)}static $(){return["PreviewAttachGroupToDirectoryRequest|1 group_id 5|2 team_id 5|3 directory_group_id 5|4 type #0?",Qr]}}class FE extends T{constructor(t){super(),this.userId=0,this.email="",this.name="",this.changeType=Zr.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new FE).fromBinary(t,r)}static fromJson(t,r){return(new FE).fromJson(t,r)}static fromJsonString(t,r){return(new FE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(FE,t,r)}static $(){return["GroupMemberChange|1 user_id 5|2 email 9|3 name 9|4 change_type #0",Zr]}}class KE extends T{constructor(t){super(),this.userId=0,this.email="",this.name="",this.currentGroupId=0,this.currentGroupName="",this.isCurrentGroupScim=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new KE).fromBinary(t,r)}static fromJson(t,r){return(new KE).fromJson(t,r)}static fromJsonString(t,r){return(new KE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(KE,t,r)}static $(){return["ConflictedUser|1 user_id 5|2 email 9|3 name 9|4 current_group_id 5|5 current_group_name 9|6 is_current_group_scim 8"]}}class zE extends T{constructor(t){super(),this.changes=[],this.membersToAdd=0,this.membersToRemove=0,this.directoryGroupName="",this.membersSkippedDueToConflict=0,this.conflictedUsers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zE).fromBinary(t,r)}static fromJson(t,r){return(new zE).fromJson(t,r)}static fromJsonString(t,r){return(new zE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zE,t,r)}static $(){return["PreviewAttachGroupToDirectoryResponse|1 changes #0*|2 members_to_add 5|3 members_to_remove 5|4 directory_group_name 9|5 members_skipped_due_to_conflict 5|6 conflicted_users #1*",FE,KE]}}class jE extends T{constructor(t){super(),this.groupId=0,this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jE).fromBinary(t,r)}static fromJson(t,r){return(new jE).fromJson(t,r)}static fromJsonString(t,r){return(new jE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jE,t,r)}static $(){return["DetachGroupFromDirectoryRequest|1 group_id 5|2 team_id 5|3 type #0?",Qr]}}class HE extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new HE).fromBinary(t,r)}static fromJson(t,r){return(new HE).fromJson(t,r)}static fromJsonString(t,r){return(new HE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(HE,t,r)}static $(){return["DetachGroupFromDirectoryResponse|1 group #0",SE]}}class WE extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new WE).fromBinary(t,r)}static fromJson(t,r){return(new WE).fromJson(t,r)}static fromJsonString(t,r){return(new WE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(WE,t,r)}static $(){return["GetScimConflictsRequest|1 team_id 5|2 type #0?",Qr]}}class QE extends T{constructor(t){super(),this.directoryGroupId=0,this.directoryGroupName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new QE).fromBinary(t,r)}static fromJson(t,r){return(new QE).fromJson(t,r)}static fromJsonString(t,r){return(new QE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(QE,t,r)}static $(){return["ScimConflictDirectoryGroup|1 directory_group_id 5|2 directory_group_name 9"]}}class VE extends T{constructor(t){super(),this.userId=0,this.email="",this.name="",this.directoryGroups=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new VE).fromBinary(t,r)}static fromJson(t,r){return(new VE).fromJson(t,r)}static fromJsonString(t,r){return(new VE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(VE,t,r)}static $(){return["ScimConflictUser|1 user_id 5|2 email 9|3 name 9|4 directory_groups #0*|5 current_billing_group_id 5?|6 current_billing_group_name 9?|7 current_billing_group_directory_group_id 5?",QE]}}class XE extends T{constructor(t){super(),this.conflictedUsers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new XE).fromBinary(t,r)}static fromJson(t,r){return(new XE).fromJson(t,r)}static fromJsonString(t,r){return(new XE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(XE,t,r)}static $(){return["GetScimConflictsResponse|1 conflicted_users #0*",VE]}}class YE extends T{constructor(t){super(),this.id=n.protoInt64.zero,this.organizationId="",this.ownerId=n.protoInt64.zero,this.ownerType=te.UNSPECIFIED,this.scimDirectoryExternalId="",this.provider=re.UNSPECIFIED,this.createdAt=n.protoInt64.zero,this.updatedAt=n.protoInt64.zero,this.identityProviderPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new YE).fromBinary(t,r)}static fromJson(t,r){return(new YE).fromJson(t,r)}static fromJsonString(t,r){return(new YE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(YE,t,r)}static $(){return["ScimDirectory|1 id 3|2 organization_id 9|3 owner_id 3|4 owner_type #0|5 scim_directory_external_id 9|6 provider #1|7 created_at 3|8 updated_at 3|9 sync_directory_users_to_root_team 8?|10 identity_provider_public_id 9",te,re]}}class ZE extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ZE).fromBinary(t,r)}static fromJson(t,r){return(new ZE).fromJson(t,r)}static fromJsonString(t,r){return(new ZE).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ZE,t,r)}static $(){return["ListScimDirectoriesRequest|1 organization_id 9"]}}class tC extends T{constructor(t){super(),this.directories=[],this.multiSourceEnabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tC).fromBinary(t,r)}static fromJson(t,r){return(new tC).fromJson(t,r)}static fromJsonString(t,r){return(new tC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tC,t,r)}static $(){return["ListScimDirectoriesResponse|1 directories #0*|2 multi_source_enabled 8",YE]}}class rC extends T{constructor(t){super(),this.organizationId="",this.scimDirectoryExternalId="",this.provider=re.UNSPECIFIED,this.ownerType=te.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rC).fromBinary(t,r)}static fromJson(t,r){return(new rC).fromJson(t,r)}static fromJsonString(t,r){return(new rC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rC,t,r)}static $(){return["CreateScimDirectoryRequest|1 organization_id 9|2 scim_directory_external_id 9|3 provider #0|4 owner_type #1",re,te]}}class eC extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eC).fromBinary(t,r)}static fromJson(t,r){return(new eC).fromJson(t,r)}static fromJsonString(t,r){return(new eC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eC,t,r)}static $(){return["CreateScimDirectoryResponse|1 directory #0",YE]}}class nC extends T{constructor(t){super(),this.organizationId="",this.scimDirectoryId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nC).fromBinary(t,r)}static fromJson(t,r){return(new nC).fromJson(t,r)}static fromJsonString(t,r){return(new nC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nC,t,r)}static $(){return["UpdateScimDirectorySyncSettingsRequest|1 organization_id 9|2 scim_directory_id 3|3 sync_directory_users_to_root_team 8?"]}}class sC extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sC).fromBinary(t,r)}static fromJson(t,r){return(new sC).fromJson(t,r)}static fromJsonString(t,r){return(new sC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sC,t,r)}static $(){return["UpdateScimDirectorySyncSettingsResponse|1 directory #0",YE]}}class iC extends T{constructor(t){super(),this.organizationId="",this.scimDirectoryId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iC).fromBinary(t,r)}static fromJson(t,r){return(new iC).fromJson(t,r)}static fromJsonString(t,r){return(new iC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iC,t,r)}static $(){return["DeleteScimDirectoryRequest|1 organization_id 9|2 scim_directory_id 3"]}}class oC extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oC).fromBinary(t,r)}static fromJson(t,r){return(new oC).fromJson(t,r)}static fromJsonString(t,r){return(new oC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oC,t,r)}static $(){return["DeleteScimDirectoryResponse"]}}class aC extends T{constructor(t){super(),this.scimGroupExternalId="",this.name="",this.workosGroupId="",this.idpId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aC).fromBinary(t,r)}static fromJson(t,r){return(new aC).fromJson(t,r)}static fromJsonString(t,r){return(new aC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aC,t,r)}static $(){return["ScimUpstreamGroup|1 scim_group_external_id 9|2 name 9|3 workos_group_id 9|4 idp_id 9"]}}class uC extends T{constructor(t){super(),this.organizationId="",this.scimDirectoryId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uC).fromBinary(t,r)}static fromJson(t,r){return(new uC).fromJson(t,r)}static fromJsonString(t,r){return(new uC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uC,t,r)}static $(){return["ListScimGroupsFromUpstreamRequest|1 organization_id 9|2 scim_directory_id 3"]}}class cC extends T{constructor(t){super(),this.groups=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cC).fromBinary(t,r)}static fromJson(t,r){return(new cC).fromJson(t,r)}static fromJsonString(t,r){return(new cC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cC,t,r)}static $(){return["ListScimGroupsFromUpstreamResponse|1 groups #0*",aC]}}class lC extends T{constructor(t){super(),this.id=n.protoInt64.zero,this.scimDirectoryId=n.protoInt64.zero,this.scimGroupExternalId="",this.targetId=n.protoInt64.zero,this.targetType=ee.UNSPECIFIED,this.syncState=ne.UNSPECIFIED,this.createdAt=n.protoInt64.zero,this.updatedAt=n.protoInt64.zero,this.sourceType=se.UNSPECIFIED,this.role=ie.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lC).fromBinary(t,r)}static fromJson(t,r){return(new lC).fromJson(t,r)}static fromJsonString(t,r){return(new lC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lC,t,r)}static $(){return["ScimTargetMapping|1 id 3|2 scim_directory_id 3|3 scim_group_external_id 9|4 target_id 3|5 target_type #0|6 sync_state #1|7 last_synced_at 3?|8 created_at 3|9 updated_at 3|10 source_type #2|11 cursor_group_id 3?|12 role #3",ee,ne,se,ie]}}class mC extends T{constructor(t){super(),this.organizationId="",this.scimDirectoryId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mC).fromBinary(t,r)}static fromJson(t,r){return(new mC).fromJson(t,r)}static fromJsonString(t,r){return(new mC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mC,t,r)}static $(){return["ListScimTargetMappingsRequest|1 organization_id 9|2 scim_directory_id 3"]}}class fC extends T{constructor(t){super(),this.mappings=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fC).fromBinary(t,r)}static fromJson(t,r){return(new fC).fromJson(t,r)}static fromJsonString(t,r){return(new fC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fC,t,r)}static $(){return["ListScimTargetMappingsResponse|1 mappings #0*",lC]}}class dC extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dC).fromBinary(t,r)}static fromJson(t,r){return(new dC).fromJson(t,r)}static fromJsonString(t,r){return(new dC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dC,t,r)}static $(){return["ListOrganizationGroupTargetMappingsRequest|1 organization_id 9"]}}class pC extends T{constructor(t){super(),this.mappings=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pC).fromBinary(t,r)}static fromJson(t,r){return(new pC).fromJson(t,r)}static fromJsonString(t,r){return(new pC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pC,t,r)}static $(){return["ListOrganizationGroupTargetMappingsResponse|1 mappings #0*",lC]}}class hC extends T{constructor(t){super(),this.organizationId="",this.scimDirectoryId=n.protoInt64.zero,this.scimGroupExternalId="",this.targetId=n.protoInt64.zero,this.targetType=ee.UNSPECIFIED,this.role=ie.UNSPECIFIED,this.sourceType=se.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hC).fromBinary(t,r)}static fromJson(t,r){return(new hC).fromJson(t,r)}static fromJsonString(t,r){return(new hC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hC,t,r)}static $(){return["CreateScimTargetMappingRequest|1 organization_id 9|2 scim_directory_id 3|3 scim_group_external_id 9|4 target_id 3|5 target_type #0|6 cursor_group_id 3?|7 role #1|8 source_type #2",ee,ie,se]}}class gC extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gC).fromBinary(t,r)}static fromJson(t,r){return(new gC).fromJson(t,r)}static fromJsonString(t,r){return(new gC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gC,t,r)}static $(){return["CreateScimTargetMappingResponse|1 mapping #0",lC]}}class _C extends T{constructor(t){super(),this.organizationId="",this.scimTargetMappingId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _C).fromBinary(t,r)}static fromJson(t,r){return(new _C).fromJson(t,r)}static fromJsonString(t,r){return(new _C).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_C,t,r)}static $(){return["DeleteScimTargetMappingRequest|1 organization_id 9|2 scim_target_mapping_id 3"]}}class JC extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new JC).fromBinary(t,r)}static fromJson(t,r){return(new JC).fromJson(t,r)}static fromJsonString(t,r){return(new JC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(JC,t,r)}static $(){return["DeleteScimTargetMappingResponse"]}}class wC extends T{constructor(t){super(),this.installationId=n.protoInt64.zero,this.repoNodeId="",this.owner="",this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wC).fromBinary(t,r)}static fromJson(t,r){return(new wC).fromJson(t,r)}static fromJsonString(t,r){return(new wC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wC,t,r)}static $(){return["NotifyTeamAdminsRepo|1 installation_id 3|2 repo_node_id 9|3 owner 9|4 name 9"]}}class yC extends T{constructor(t){super(),this.teamId=0,this.requestType=oe.UNSPECIFIED,this.repos=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yC).fromBinary(t,r)}static fromJson(t,r){return(new yC).fromJson(t,r)}static fromJsonString(t,r){return(new yC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yC,t,r)}static $(){return["NotifyTeamAdminsRequest|1 team_id 5|2 request_type #0|3 repos #1*|4 ghe_application 9?",oe,wC]}}class SC extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new SC).fromBinary(t,r)}static fromJson(t,r){return(new SC).fromJson(t,r)}static fromJsonString(t,r){return(new SC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(SC,t,r)}static $(){return["NotifyTeamAdminsResponse|1 success 8|2 error_message 9?"]}}class qC extends T{constructor(t){super(),this.teamId=0,this.requestType=oe.UNSPECIFIED,this.repos=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qC).fromBinary(t,r)}static fromJson(t,r){return(new qC).fromJson(t,r)}static fromJsonString(t,r){return(new qC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qC,t,r)}static $(){return["GetAdminNotificationStatusRequest|1 team_id 5|2 request_type #0|3 repos #1*|4 ghe_application 9?",oe,wC]}}class BC extends T{constructor(t){super(),this.canSend=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new BC).fromBinary(t,r)}static fromJson(t,r){return(new BC).fromJson(t,r)}static fromJsonString(t,r){return(new BC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(BC,t,r)}static $(){return["GetAdminNotificationStatusResponse|1 can_send 8|2 last_sent_timestamp 3?"]}}class IC extends T{constructor(t){super(),this.slackTeamId="",this.slackUserId="",this.setupPrerequisitesComplete=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new IC).fromBinary(t,r)}static fromJson(t,r){return(new IC).fromJson(t,r)}static fromJsonString(t,r){return(new IC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(IC,t,r)}static $(){return["CompletedLinkSlackAccountRequest|1 slack_team_id 9|2 slack_user_id 9|3 setup_prerequisites_complete 8"]}}class PC extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new PC).fromBinary(t,r)}static fromJson(t,r){return(new PC).fromJson(t,r)}static fromJsonString(t,r){return(new PC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(PC,t,r)}static $(){return["CompletedLinkSlackAccountResponse"]}}class bC extends T{constructor(t){super(),this.optIn=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bC).fromBinary(t,r)}static fromJson(t,r){return(new bC).fromJson(t,r)}static fromJsonString(t,r){return(new bC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bC,t,r)}static $(){return["OptOutNewPricingRequest|1 opt_in 8"]}}class RC extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new RC).fromBinary(t,r)}static fromJson(t,r){return(new RC).fromJson(t,r)}static fromJsonString(t,r){return(new RC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(RC,t,r)}static $(){return["OptOutNewPricingResponse"]}}class vC extends T{constructor(t){super(),this.teamId=0,this.optOut=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vC).fromBinary(t,r)}static fromJson(t,r){return(new vC).fromJson(t,r)}static fromJsonString(t,r){return(new vC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vC,t,r)}static $(){return["UpdateTeamPrivacyModeMigrationOptOutRequest|1 team_id 5|2 opt_out 8"]}}class xC extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xC).fromBinary(t,r)}static fromJson(t,r){return(new xC).fromJson(t,r)}static fromJsonString(t,r){return(new xC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xC,t,r)}static $(){return["UpdateTeamPrivacyModeMigrationOptOutResponse"]}}class kC extends T{constructor(t){super(),this.message="",this.version="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kC).fromBinary(t,r)}static fromJson(t,r){return(new kC).fromJson(t,r)}static fromJsonString(t,r){return(new kC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kC,t,r)}static $(){return["SubmitFeedbackRequest|1 message 9|2 version 9|3 last_agent_req_id 9?|4 os 9?|5 terminal 9?|6 shell 9?|7 model 9?|8 update_channel 9?|9 agent_mode 9?"]}}class EC extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new EC).fromBinary(t,r)}static fromJson(t,r){return(new EC).fromJson(t,r)}static fromJsonString(t,r){return(new EC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(EC,t,r)}static $(){return["SubmitFeedbackResponse"]}}class CC extends T{constructor(t){super(),this.token="",this.remotesText="",this.commitsText="",this.claimantCompanyName="",this.claimantContactEmail="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new CC).fromBinary(t,r)}static fromJson(t,r){return(new CC).fromJson(t,r)}static fromJsonString(t,r){return(new CC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(CC,t,r)}static $(){return["SubmitRepositoryProtectionClaimRequest|1 token 9|2 remotes_text 9|3 commits_text 9|4 claimant_company_name 9|5 claimant_contact_email 9"]}}class TC extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new TC).fromBinary(t,r)}static fromJson(t,r){return(new TC).fromJson(t,r)}static fromJsonString(t,r){return(new TC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(TC,t,r)}static $(){return["SubmitRepositoryProtectionClaimResponse"]}}class UC extends T{constructor(t){super(),this.id="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new UC).fromBinary(t,r)}static fromJson(t,r){return(new UC).fromJson(t,r)}static fromJsonString(t,r){return(new UC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(UC,t,r)}static $(){return["ActivateRepositoryProtectionInviteRequest|1 id 9"]}}class AC extends T{constructor(t){super(),this.activated=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new AC).fromBinary(t,r)}static fromJson(t,r){return(new AC).fromJson(t,r)}static fromJsonString(t,r){return(new AC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(AC,t,r)}static $(){return["ActivateRepositoryProtectionInviteResponse|1 activated 5"]}}class $C extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $C).fromBinary(t,r)}static fromJson(t,r){return(new $C).fromJson(t,r)}static fromJsonString(t,r){return(new $C).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($C,t,r)}static $(){return["GetTeamBugbotSettingsRequest|1 team_id 5"]}}class MC extends T{constructor(t){super(),this.githubUsername="",this.firstReviewTimestamp=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new MC).fromBinary(t,r)}static fromJson(t,r){return(new MC).fromJson(t,r)}static fromJsonString(t,r){return(new MC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(MC,t,r)}static $(){return["BugbotLicenseUsage|1 github_username 9|2 first_review_timestamp 3|3 github_user_node_id 9?"]}}class OC extends T{constructor(t){super(),this.bugbotLicensesHardLimit=0,this.bugbotPlanEnabled=!1,this.allowlist=[],this.currentCycleUniqueUsers=0,this.bugbotLicenseCount=0,this.allowlistConfig=Tr.UNSPECIFIED,this.bugbotWasEnabledInThisBillingCycle=!1,this.licenseUsage=[],this.bugbotUsageTier=$r.UNSPECIFIED,this.bugbotGloballyDisabled=!1,this.mcpServerNames=[],this.bugbotBillingMode=Mr.UNSPECIFIED,this.bugbotUsageBasedOnEnable=!1,this.canMigrateToUsageBased=!1,this.seatLicenseCount=0,this.bugbotMigrationCreditAlreadyGranted=!1,this.isIncrementalReviewEnabled=!1,this.mergedPrScanOptedOut=!1,this.coverExternalPublicContributors=!1,this.repoAutoEnablePolicy=Or.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new OC).fromBinary(t,r)}static fromJson(t,r){return(new OC).fromJson(t,r)}static fromJsonString(t,r){return(new OC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(OC,t,r)}static $(){return["GetTeamBugbotSettingsResponse|1 bugbot_licenses_hard_limit 5|2 bugbot_plan_enabled 8|3 allowlist 9*|4 current_cycle_unique_users 5|5 bugbot_license_count 5|6 allowlist_config #0|7 bugbot_was_enabled_in_this_billing_cycle 8|8 license_usage #1*|9 bugbot_usage_tier #2|10 bugbot_globally_disabled 8|11 mcp_server_names 9*|12 bugbot_billing_mode #3|13 bugbot_usage_based_on_enable 8|14 can_migrate_to_usage_based 8|15 seat_license_count 5|16 bugbot_migration_credit_already_granted 8|17 is_incremental_review_enabled 8|18 merged_pr_scan_opted_out 8|23 cover_external_public_contributors 8|24 repo_auto_enable_policy #4",Tr,MC,$r,Mr,Or]}}class DC extends T{constructor(t){super(),this.teamId=0,this.allowlist=[],this.mcpServerNames=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new DC).fromBinary(t,r)}static fromJson(t,r){return(new DC).fromJson(t,r)}static fromJsonString(t,r){return(new DC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(DC,t,r)}static $(){return["UpdateTeamBugbotSettingsRequest|1 team_id 5|2 bugbot_licenses_hard_limit 5?|3 bugbot_plan_enabled 8?|4 allowlist 9*|5 allowlist_config #0?|6 bugbot_globally_disabled 8?|7 mcp_server_names 9*|8 is_incremental_review_enabled 8?|9 merged_pr_scan_opt_out 8?|10 apply_onboarding_high_effort_learning_defaults 8?|14 cover_external_public_contributors 8?|15 repo_auto_enable_policy #1?",Tr,Or]}}class NC extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new NC).fromBinary(t,r)}static fromJson(t,r){return(new NC).fromJson(t,r)}static fromJsonString(t,r){return(new NC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(NC,t,r)}static $(){return["UpdateTeamBugbotSettingsResponse"]}}class GC extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new GC).fromBinary(t,r)}static fromJson(t,r){return(new GC).fromJson(t,r)}static fromJsonString(t,r){return(new GC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(GC,t,r)}static $(){return["MigrateTeamBugbotToUsageBasedBillingRequest|1 team_id 5|2 keep_high_effort_default 8?"]}}class LC extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new LC).fromBinary(t,r)}static fromJson(t,r){return(new LC).fromJson(t,r)}static fromJsonString(t,r){return(new LC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(LC,t,r)}static $(){return["MigrateTeamBugbotToUsageBasedBillingResponse"]}}class FC extends T{constructor(t){super(),this.values={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new FC).fromBinary(t,r)}static fromJson(t,r){return(new FC).fromJson(t,r)}static fromJsonString(t,r){return(new FC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(FC,t,r)}static $(){return["TeamCustomerTelemetryDestinationHeaders|1 values 9,9"]}}class KC extends T{constructor(t){super(),this.ids=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new KC).fromBinary(t,r)}static fromJson(t,r){return(new KC).fromJson(t,r)}static fromJsonString(t,r){return(new KC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(KC,t,r)}static $(){return["TeamCustomerTelemetryDestinationFamilyList|1 ids 9*"]}}class zC extends T{constructor(t){super(),this.id="",this.displayName="",this.description="",this.metrics=!1,this.logs=!1,this.requiresExplicitEnable=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zC).fromBinary(t,r)}static fromJson(t,r){return(new zC).fromJson(t,r)}static fromJsonString(t,r){return(new zC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zC,t,r)}static $(){return["TeamCustomerTelemetryDestinationFamily|1 id 9|2 display_name 9|3 description 9|4 metrics 8|5 logs 8|6 requires_explicit_enable 8"]}}class jC extends T{constructor(t){super(),this.id="",this.kind=ae.UNSPECIFIED,this.endpointUrl="",this.enabled=!1,this.metricsEnabled=!1,this.logsEnabled=!1,this.hasCredentials=!1,this.activatedAtEpochMillis=n.protoInt64.zero,this.createdAtEpochMillis=n.protoInt64.zero,this.updatedAtEpochMillis=n.protoInt64.zero,this.credentialHeaderNames=[],this.disabledFamilies=[],this.enabledFamilies=[],this.autoEnableNewFamilies=!1,this.contentPromptsEnabled=!1,this.contentResponsesEnabled=!1,this.contentToolIoEnabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jC).fromBinary(t,r)}static fromJson(t,r){return(new jC).fromJson(t,r)}static fromJsonString(t,r){return(new jC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jC,t,r)}static $(){return["TeamCustomerTelemetryDestination|1 id 9|2 kind #0|3 endpoint_url 9|4 enabled 8|5 metrics_enabled 8|6 logs_enabled 8|7 has_credentials 8|8 activated_at_epoch_millis 3|9 created_at_epoch_millis 3|10 updated_at_epoch_millis 3|11 credential_header_names 9*|12 disabled_families 9*|13 enabled_families 9*|14 auto_enable_new_families 8|15 content_prompts_enabled 8|16 content_responses_enabled 8|17 content_tool_io_enabled 8",ae]}}class HC extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new HC).fromBinary(t,r)}static fromJson(t,r){return(new HC).fromJson(t,r)}static fromJsonString(t,r){return(new HC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(HC,t,r)}static $(){return["GetTeamCustomerTelemetryDestinationsRequest|1 team_id 5"]}}class WC extends T{constructor(t){super(),this.destinations=[],this.availableFamilies=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new WC).fromBinary(t,r)}static fromJson(t,r){return(new WC).fromJson(t,r)}static fromJsonString(t,r){return(new WC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(WC,t,r)}static $(){return["GetTeamCustomerTelemetryDestinationsResponse|1 destinations #0*|2 available_families #1*",jC,zC]}}class QC extends T{constructor(t){super(),this.teamId=0,this.endpointUrl="",this.metricsEnabled=!1,this.logsEnabled=!1,this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new QC).fromBinary(t,r)}static fromJson(t,r){return(new QC).fromJson(t,r)}static fromJsonString(t,r){return(new QC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(QC,t,r)}static $(){return["CreateTeamCustomerTelemetryDestinationRequest|1 team_id 5|2 endpoint_url 9|3 headers #0?|4 metrics_enabled 8|5 logs_enabled 8|6 enabled 8|7 disabled_families #1?|8 enabled_families #1?|9 auto_enable_new_families 8?|10 content_prompts_enabled 8?|11 content_responses_enabled 8?|12 content_tool_io_enabled 8?",FC,KC]}}class VC extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new VC).fromBinary(t,r)}static fromJson(t,r){return(new VC).fromJson(t,r)}static fromJsonString(t,r){return(new VC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(VC,t,r)}static $(){return["CreateTeamCustomerTelemetryDestinationResponse|1 destination #0",jC]}}class XC extends T{constructor(t){super(),this.teamId=0,this.destinationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new XC).fromBinary(t,r)}static fromJson(t,r){return(new XC).fromJson(t,r)}static fromJsonString(t,r){return(new XC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(XC,t,r)}static $(){return["UpdateTeamCustomerTelemetryDestinationRequest|1 team_id 5|2 destination_id 9|3 endpoint_url 9?|4 headers #0?|5 metrics_enabled 8?|6 logs_enabled 8?|7 enabled 8?|8 disabled_families #1?|9 enabled_families #1?|10 auto_enable_new_families 8?|11 content_prompts_enabled 8?|12 content_responses_enabled 8?|13 content_tool_io_enabled 8?",FC,KC]}}class YC extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new YC).fromBinary(t,r)}static fromJson(t,r){return(new YC).fromJson(t,r)}static fromJsonString(t,r){return(new YC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(YC,t,r)}static $(){return["UpdateTeamCustomerTelemetryDestinationResponse|1 destination #0",jC]}}class ZC extends T{constructor(t){super(),this.teamId=0,this.destinationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ZC).fromBinary(t,r)}static fromJson(t,r){return(new ZC).fromJson(t,r)}static fromJsonString(t,r){return(new ZC).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ZC,t,r)}static $(){return["DeleteTeamCustomerTelemetryDestinationRequest|1 team_id 5|2 destination_id 9"]}}class tT extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tT).fromBinary(t,r)}static fromJson(t,r){return(new tT).fromJson(t,r)}static fromJsonString(t,r){return(new tT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tT,t,r)}static $(){return["DeleteTeamCustomerTelemetryDestinationResponse"]}}class rT extends T{constructor(t){super(),this.teamId=0,this.endpointUrl="",this.signal=ue.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rT).fromBinary(t,r)}static fromJson(t,r){return(new rT).fromJson(t,r)}static fromJsonString(t,r){return(new rT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rT,t,r)}static $(){return["TestTeamCustomerTelemetryDestinationConnectionRequest|1 team_id 5|2 endpoint_url 9|3 headers #0?|4 signal #1",FC,ue]}}class eT extends T{constructor(t){super(),this.ok=!1,this.outcome=ce.UNSPECIFIED,this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eT).fromBinary(t,r)}static fromJson(t,r){return(new eT).fromJson(t,r)}static fromJsonString(t,r){return(new eT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eT,t,r)}static $(){return["TestTeamCustomerTelemetryDestinationConnectionResponse|1 ok 8|2 outcome #0|3 status_code 5?|4 latency_ms 3?|5 message 9",ce]}}class nT extends T{constructor(t){super(),this.bucketStartEpochMillis=n.protoInt64.zero,this.exported=n.protoInt64.zero,this.failed=n.protoInt64.zero,this.dropped=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nT).fromBinary(t,r)}static fromJson(t,r){return(new nT).fromJson(t,r)}static fromJsonString(t,r){return(new nT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nT,t,r)}static $(){return["TeamCustomerTelemetryDestinationHealthBucket|1 bucket_start_epoch_millis 3|2 exported 3|3 failed 3|4 dropped 3"]}}class sT extends T{constructor(t){super(),this.atEpochMillis=n.protoInt64.zero,this.errorClass="",this.signal="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sT).fromBinary(t,r)}static fromJson(t,r){return(new sT).fromJson(t,r)}static fromJsonString(t,r){return(new sT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sT,t,r)}static $(){return["TeamCustomerTelemetryDestinationRecentError|1 at_epoch_millis 3|2 error_class 9|3 status_code 5?|4 signal 9"]}}class iT extends T{constructor(t){super(),this.teamId=0,this.destinationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iT).fromBinary(t,r)}static fromJson(t,r){return(new iT).fromJson(t,r)}static fromJsonString(t,r){return(new iT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iT,t,r)}static $(){return["GetTeamCustomerTelemetryDestinationHealthRequest|1 team_id 5|2 destination_id 9"]}}class oT extends T{constructor(t){super(),this.status=le.UNSPECIFIED,this.buckets=[],this.lastErrorClass="",this.queueDepth=n.protoInt64.zero,this.breakerState="",this.oldestBatchAgeMs=n.protoInt64.zero,this.recentErrors=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oT).fromBinary(t,r)}static fromJson(t,r){return(new oT).fromJson(t,r)}static fromJsonString(t,r){return(new oT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oT,t,r)}static $(){return["GetTeamCustomerTelemetryDestinationHealthResponse|1 status #0|2 buckets #1*|3 last_success_at_epoch_millis 3?|4 last_error_at_epoch_millis 3?|5 last_error_class 9|6 last_error_status 5?|7 queue_depth 3|8 breaker_state 9|9 oldest_batch_age_ms 3|10 recent_errors #2*",le,nT,sT]}}class aT extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aT).fromBinary(t,r)}static fromJson(t,r){return(new aT).fromJson(t,r)}static fromJsonString(t,r){return(new aT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aT,t,r)}static $(){return["GetTeamCustomerTelemetryContentExportOptInRequest|1 team_id 5"]}}class uT extends T{constructor(t){super(),this.enabled=!1,this.available=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uT).fromBinary(t,r)}static fromJson(t,r){return(new uT).fromJson(t,r)}static fromJsonString(t,r){return(new uT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uT,t,r)}static $(){return["GetTeamCustomerTelemetryContentExportOptInResponse|1 enabled 8|2 available 8"]}}class cT extends T{constructor(t){super(),this.teamId=0,this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cT).fromBinary(t,r)}static fromJson(t,r){return(new cT).fromJson(t,r)}static fromJsonString(t,r){return(new cT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cT,t,r)}static $(){return["UpdateTeamCustomerTelemetryContentExportOptInRequest|1 team_id 5|2 enabled 8"]}}class lT extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lT).fromBinary(t,r)}static fromJson(t,r){return(new lT).fromJson(t,r)}static fromJsonString(t,r){return(new lT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lT,t,r)}static $(){return["UpdateTeamCustomerTelemetryContentExportOptInResponse|1 enabled 8"]}}class mT extends T{constructor(t){super(),this.id="",this.name="",this.prompt="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mT).fromBinary(t,r)}static fromJson(t,r){return(new mT).fromJson(t,r)}static fromJsonString(t,r){return(new mT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mT,t,r)}static $(){return["InferenceHookDecisionQuestion|1 id 9|2 name 9|3 prompt 9"]}}class fT extends T{constructor(t){super(),this.questionId="",this.operator=pe.UNSPECIFIED,this.confidencePercent=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fT).fromBinary(t,r)}static fromJson(t,r){return(new fT).fromJson(t,r)}static fromJsonString(t,r){return(new fT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fT,t,r)}static $(){return["InferenceHookDecisionRuleCondition|1 question_id 9|2 operator #0|3 confidence_percent 5",pe]}}class dT extends T{constructor(t){super(),this.id="",this.name="",this.enabled=!1,this.events=[],this.conditions=[],this.mode=he.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dT).fromBinary(t,r)}static fromJson(t,r){return(new dT).fromJson(t,r)}static fromJsonString(t,r){return(new dT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dT,t,r)}static $(){return["InferenceHookDecisionRule|1 id 9|2 name 9|5 enabled 8|6 events #0*|7 deny_reason 9?|8 conditions #1*|9 mode #2",Je,fT,he]}}class pT extends T{constructor(t){super(),this.rules=[],this.questions=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pT).fromBinary(t,r)}static fromJson(t,r){return(new pT).fromJson(t,r)}static fromJsonString(t,r){return(new pT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pT,t,r)}static $(){return["InferenceHookDecisionRuleSet|1 rules #0*|2 questions #1*",dT,mT]}}class hT extends T{constructor(t){super(),this.values={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hT).fromBinary(t,r)}static fromJson(t,r){return(new hT).fromJson(t,r)}static fromJsonString(t,r){return(new hT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hT,t,r)}static $(){return["InferenceHookHeaders|1 values 9,9"]}}class gT extends T{constructor(t){super(),this.surfaces=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gT).fromBinary(t,r)}static fromJson(t,r){return(new gT).fromJson(t,r)}static fromJsonString(t,r){return(new gT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gT,t,r)}static $(){return["InferenceHookSurfaceList|1 surfaces #0*",fe]}}class _T extends T{constructor(t){super(),this.enforceVerdicts=!1,this.mode=me.UNSPECIFIED,this.endpointUrl="",this.headerNames=[],this.hasHeaderValues=!1,this.hasSigningSecret=!1,this.verdictTimeoutMs=0,this.rolloutPercent=0,this.enabledSurfaces=[],this.blockedMessageEnabled=!1,this.configVersion=n.protoInt64.zero,this.createdAtEpochMillis=n.protoInt64.zero,this.updatedAtEpochMillis=n.protoInt64.zero,this.validateToolCalls=!1,this.hookKind=de.UNSPECIFIED,this.purviewTenantId="",this.decisionRules=[],this.decisionQuestions=[],this.refuseLocalLoopTurns=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _T).fromBinary(t,r)}static fromJson(t,r){return(new _T).fromJson(t,r)}static fromJsonString(t,r){return(new _T).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_T,t,r)}static $(){return["TeamInferenceHookConfig|1 enforce_verdicts 8|2 mode #0|3 endpoint_url 9|4 header_names 9*|5 has_header_values 8|6 has_signing_secret 8|7 signing_secret_created_at_epoch_millis 3?|8 verdict_timeout_ms 5|9 rollout_percent 5|10 enabled_surfaces #1*|11 blocked_message_enabled 8|12 blocked_message 9?|13 config_version 3|14 breaker_tripped_at_epoch_millis 3?|15 created_at_epoch_millis 3|16 updated_at_epoch_millis 3|17 validate_tool_calls 8|18 hook_kind #2|19 purview_tenant_id 9|20 sensitivity_label_policy #3|21 decision_rules #4*|22 decision_questions #5*|23 refuse_local_loop_turns 8",me,fe,de,JT,dT,mT]}}class JT extends T{constructor(t){super(),this.mode=ge.UNSPECIFIED,this.labelIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new JT).fromBinary(t,r)}static fromJson(t,r){return(new JT).fromJson(t,r)}static fromJsonString(t,r){return(new JT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(JT,t,r)}static $(){return["InferenceHookSensitivityLabelPolicy|1 mode #0|2 label_ids 9*|3 default_label_id 9?",ge]}}class wT extends T{constructor(t){super(),this.id="",this.name="",this.priority=0,this.appliesEncryption=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wT).fromBinary(t,r)}static fromJson(t,r){return(new wT).fromJson(t,r)}static fromJsonString(t,r){return(new wT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wT,t,r)}static $(){return["InferenceHookSensitivityLabel|1 id 9|2 name 9|3 priority 5|4 applies_encryption 8"]}}class yT extends T{constructor(t){super(),this.available=!1,this.labels=[],this.defaultLabelAvailable=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yT).fromBinary(t,r)}static fromJson(t,r){return(new yT).fromJson(t,r)}static fromJsonString(t,r){return(new yT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yT,t,r)}static $(){return["InferenceHookSensitivityLabelCatalog|1 available 8|2 labels #0*|3 default_label_available 8",wT]}}class ST extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ST).fromBinary(t,r)}static fromJson(t,r){return(new ST).fromJson(t,r)}static fromJsonString(t,r){return(new ST).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ST,t,r)}static $(){return["GetTeamInferenceHookConfigRequest|1 team_id 5"]}}class qT extends T{constructor(t){super(),this.availableSurfaces=[],this.effectiveMode=me.UNSPECIFIED,this.sourceIpRanges=[],this.defaultBlockedMessage="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qT).fromBinary(t,r)}static fromJson(t,r){return(new qT).fromJson(t,r)}static fromJsonString(t,r){return(new qT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qT,t,r)}static $(){return["GetTeamInferenceHookConfigResponse|1 config #0|2 available_surfaces #1*|3 effective_mode #2|4 source_ip_ranges 9*|5 default_blocked_message 9|6 available 8?|7 tool_calls_available 8?|8 purview_available 8?|9 purview_client_id 9?|10 sensitivity_label_catalog #3?|11 decision_rules_available 8?",_T,fe,me,yT]}}class BT extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new BT).fromBinary(t,r)}static fromJson(t,r){return(new BT).fromJson(t,r)}static fromJsonString(t,r){return(new BT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(BT,t,r)}static $(){return["UpdateTeamInferenceHookConfigRequest|1 team_id 5|2 enforce_verdicts 8?|3 mode #0?|4 endpoint_url 9?|5 headers #1|6 verdict_timeout_ms 5?|7 rollout_percent 5?|8 enabled_surfaces #2|9 blocked_message_enabled 8?|10 blocked_message 9?|11 expected_config_version 3?|12 validate_tool_calls 8?|13 hook_kind #3?|14 purview_tenant_id 9?|15 sensitivity_label_policy #4|16 decision_rules #5|17 refuse_local_loop_turns 8?",me,hT,gT,de,JT,pT]}}class IT extends T{constructor(t){super(),this.effectiveMode=me.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new IT).fromBinary(t,r)}static fromJson(t,r){return(new IT).fromJson(t,r)}static fromJsonString(t,r){return(new IT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(IT,t,r)}static $(){return["UpdateTeamInferenceHookConfigResponse|1 config #0|2 effective_mode #1|3 signing_secret 9?",_T,me]}}class PT extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new PT).fromBinary(t,r)}static fromJson(t,r){return(new PT).fromJson(t,r)}static fromJsonString(t,r){return(new PT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(PT,t,r)}static $(){return["RotateTeamInferenceHookSigningSecretRequest|1 team_id 5"]}}class bT extends T{constructor(t){super(),this.signingSecret="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bT).fromBinary(t,r)}static fromJson(t,r){return(new bT).fromJson(t,r)}static fromJsonString(t,r){return(new bT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bT,t,r)}static $(){return["RotateTeamInferenceHookSigningSecretResponse|1 config #0|2 signing_secret 9",_T]}}class RT extends T{constructor(t){super(),this.atEpochMillis=n.protoInt64.zero,this.kind="",this.message="",this.eventType=Je.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new RT).fromBinary(t,r)}static fromJson(t,r){return(new RT).fromJson(t,r)}static fromJsonString(t,r){return(new RT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(RT,t,r)}static $(){return["InferenceHookRecentError|1 at_epoch_millis 3|2 kind 9|3 message 9|4 status_code 5?|5 event_type #0",Je]}}class vT extends T{constructor(t){super(),this.eventType=Je.UNSPECIFIED,this.failuresPerMinute=0,this.verdictsLast24h=n.protoInt64.zero,this.allowedUninspectedLast24h=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vT).fromBinary(t,r)}static fromJson(t,r){return(new vT).fromJson(t,r)}static fromJsonString(t,r){return(new vT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vT,t,r)}static $(){return["InferenceHookEventHealth|1 event_type #0|2 failures_per_minute 1|3 block_rate 1?|4 verdict_latency_p50_ms 3?|5 verdict_latency_p95_ms 3?|6 verdicts_last_24h 3|7 allowed_uninspected_last_24h 3",Je]}}class xT extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xT).fromBinary(t,r)}static fromJson(t,r){return(new xT).fromJson(t,r)}static fromJsonString(t,r){return(new xT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xT,t,r)}static $(){return["GetTeamInferenceHookHealthRequest|1 team_id 5"]}}class kT extends T{constructor(t){super(),this.questionId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kT).fromBinary(t,r)}static fromJson(t,r){return(new kT).fromJson(t,r)}static fromJsonString(t,r){return(new kT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kT,t,r)}static $(){return["InferenceHookDecisionQuestionScore|1 question_id 9|2 probability 1?"]}}class ET extends T{constructor(t){super(),this.atEpochMillis=n.protoInt64.zero,this.surface=fe.UNSPECIFIED,this.eventType=Je.UNSPECIFIED,this.enforced=!1,this.toolCallIds=[],this.questionScores=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ET).fromBinary(t,r)}static fromJson(t,r){return(new ET).fromJson(t,r)}static fromJsonString(t,r){return(new ET).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ET,t,r)}static $(){return["InferenceHookRuleRecentMatch|1 at_epoch_millis 3|2 surface #0|3 event_type #1|4 enforced 8|5 conversation_id 9?|6 turn_id 9?|7 caller_request_id 9?|8 tool_call_ids 9*|9 question_scores #2*",fe,Je,kT]}}class CT extends T{constructor(t){super(),this.ruleId="",this.matchesLast24h=n.protoInt64.zero,this.recentMatches=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new CT).fromBinary(t,r)}static fromJson(t,r){return(new CT).fromJson(t,r)}static fromJsonString(t,r){return(new CT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(CT,t,r)}static $(){return["InferenceHookDecisionRuleHealth|1 rule_id 9|2 matches_last_24h 3|3 recent_matches #0*",ET]}}class TT extends T{constructor(t){super(),this.status=_e.UNSPECIFIED,this.failuresPerMinute=0,this.recentErrors=[],this.verdictsLast24h=n.protoInt64.zero,this.allowedUninspectedLast24h=n.protoInt64.zero,this.eventHealth=[],this.ruleHealth=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new TT).fromBinary(t,r)}static fromJson(t,r){return(new TT).fromJson(t,r)}static fromJsonString(t,r){return(new TT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(TT,t,r)}static $(){return["GetTeamInferenceHookHealthResponse|1 status #0|2 failures_per_minute 1|3 block_rate 1?|4 breaker_tripped_at_epoch_millis 3?|5 recent_errors #1*|6 verdict_latency_p50_ms 3?|7 verdict_latency_p95_ms 3?|8 verdicts_last_24h 3|9 allowed_uninspected_last_24h 3|10 event_health #2*|11 rule_health #3*|12 unmatched_members_last_24h 3?",_e,RT,vT,CT]}}class UT extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new UT).fromBinary(t,r)}static fromJson(t,r){return(new UT).fromJson(t,r)}static fromJsonString(t,r){return(new UT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(UT,t,r)}static $(){return["ResetTeamInferenceHookBreakerRequest|1 team_id 5"]}}class AT extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new AT).fromBinary(t,r)}static fromJson(t,r){return(new AT).fromJson(t,r)}static fromJsonString(t,r){return(new AT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(AT,t,r)}static $(){return["ResetTeamInferenceHookBreakerResponse|1 config #0",_T]}}class $T extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $T).fromBinary(t,r)}static fromJson(t,r){return(new $T).fromJson(t,r)}static fromJsonString(t,r){return(new $T).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($T,t,r)}static $(){return["GetBugbotMergedPrScanSummaryRequest|1 team_id 5"]}}class MT extends T{constructor(t){super(),this.hasScan=!1,this.scannedAtEpochMillis=n.protoInt64.zero,this.windowDays=0,this.prsSampled=0,this.prsWithFindings=0,this.bugsFound=0,this.findings=[],this.totalMergedPrs=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new MT).fromBinary(t,r)}static fromJson(t,r){return(new MT).fromJson(t,r)}static fromJsonString(t,r){return(new MT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(MT,t,r)}static $(){return["GetBugbotMergedPrScanSummaryResponse|1 has_scan 8|2 scanned_at_epoch_millis 3|3 window_days 5|4 prs_sampled 5|5 prs_with_findings 5|6 bugs_found 5|7 findings #0*|8 total_merged_prs 5",OT]}}class OT extends T{constructor(t){super(),this.description="",this.severity="",this.category="",this.repoOwner="",this.repoName="",this.prNumber=0,this.prUrl="",this.file="",this.startLine=0,this.endLine=0,this.codeLines=[],this.installationId="",this.repoNodeId="",this.prMergedAtEpochMillis=n.protoInt64.zero,this.prTitle="",this.diffHunk="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new OT).fromBinary(t,r)}static fromJson(t,r){return(new OT).fromJson(t,r)}static fromJsonString(t,r){return(new OT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(OT,t,r)}static $(){return["GetBugbotMergedPrScanSummaryResponse.Finding|1 description 9|2 severity 9|3 category 9|4 repo_owner 9|5 repo_name 9|6 pr_number 5|7 pr_url 9|8 file 9|9 start_line 5|10 end_line 5|11 code_lines 9*|12 installation_id 9|13 repo_node_id 9|14 pr_merged_at_epoch_millis 3|15 pr_title 9|16 diff_hunk 9"]}}class DT extends T{constructor(t){super(),this.content="",this.sortOrder=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new DT).fromBinary(t,r)}static fromJson(t,r){return(new DT).fromJson(t,r)}static fromJsonString(t,r){return(new DT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(DT,t,r)}static $(){return["BugbotModePrompt|1 content 9|2 sort_order 5"]}}class NT extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new NT).fromBinary(t,r)}static fromJson(t,r){return(new NT).fromJson(t,r)}static fromJsonString(t,r){return(new NT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(NT,t,r)}static $(){return["GetBugbotModeRequest"]}}class GT extends T{constructor(t){super(),this.mode=we.UNSPECIFIED,this.prompts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new GT).fromBinary(t,r)}static fromJson(t,r){return(new GT).fromJson(t,r)}static fromJsonString(t,r){return(new GT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(GT,t,r)}static $(){return["GetBugbotModeResponse|1 mode #0|2 prompts #1*",we,DT]}}class LT extends T{constructor(t){super(),this.mode=we.UNSPECIFIED,this.prompts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new LT).fromBinary(t,r)}static fromJson(t,r){return(new LT).fromJson(t,r)}static fromJsonString(t,r){return(new LT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(LT,t,r)}static $(){return["UpdateBugbotModeRequest|1 mode #0|2 prompts #1*|4 team_id 5?",we,DT]}}class FT extends T{constructor(t){super(),this.mode=we.UNSPECIFIED,this.prompts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new FT).fromBinary(t,r)}static fromJson(t,r){return(new FT).fromJson(t,r)}static fromJsonString(t,r){return(new FT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(FT,t,r)}static $(){return["UpdateBugbotModeResponse|1 mode #0|2 prompts #1*",we,DT]}}class KT extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new KT).fromBinary(t,r)}static fromJson(t,r){return(new KT).fromJson(t,r)}static fromJsonString(t,r){return(new KT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(KT,t,r)}static $(){return["GetBugBotProUserModeRequest"]}}class zT extends T{constructor(t){super(),this.mode=we.UNSPECIFIED,this.prompts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zT).fromBinary(t,r)}static fromJson(t,r){return(new zT).fromJson(t,r)}static fromJsonString(t,r){return(new zT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zT,t,r)}static $(){return["GetBugBotProUserModeResponse|1 mode #0|2 prompts #1*",we,DT]}}class jT extends T{constructor(t){super(),this.mode=we.UNSPECIFIED,this.prompts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jT).fromBinary(t,r)}static fromJson(t,r){return(new jT).fromJson(t,r)}static fromJsonString(t,r){return(new jT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jT,t,r)}static $(){return["UpdateBugBotProUserModeRequest|1 mode #0|2 prompts #1*",we,DT]}}class HT extends T{constructor(t){super(),this.mode=we.UNSPECIFIED,this.prompts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new HT).fromBinary(t,r)}static fromJson(t,r){return(new HT).fromJson(t,r)}static fromJsonString(t,r){return(new HT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(HT,t,r)}static $(){return["UpdateBugBotProUserModeResponse|1 mode #0|2 prompts #1*",we,DT]}}class WT extends T{constructor(t){super(),this.teamId=0,this.newNumLicenses=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new WT).fromBinary(t,r)}static fromJson(t,r){return(new WT).fromJson(t,r)}static fromJsonString(t,r){return(new WT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(WT,t,r)}static $(){return["RevokeBugBotLicensesRequest|1 team_id 5|2 new_num_licenses 5"]}}class QT extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new QT).fromBinary(t,r)}static fromJson(t,r){return(new QT).fromJson(t,r)}static fromJsonString(t,r){return(new QT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(QT,t,r)}static $(){return["RevokeBugBotLicensesResponse"]}}class VT extends T{constructor(t){super(),this.teamId=0,this.githubUserNodeId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new VT).fromBinary(t,r)}static fromJson(t,r){return(new VT).fromJson(t,r)}static fromJsonString(t,r){return(new VT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(VT,t,r)}static $(){return["RevokeUserBugbotLicenseRequest|1 team_id 5|2 github_user_node_id 9"]}}class XT extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new XT).fromBinary(t,r)}static fromJson(t,r){return(new XT).fromJson(t,r)}static fromJsonString(t,r){return(new XT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(XT,t,r)}static $(){return["RevokeUserBugbotLicenseResponse"]}}class YT extends T{constructor(t){super(),this.code="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new YT).fromBinary(t,r)}static fromJson(t,r){return(new YT).fromJson(t,r)}static fromJsonString(t,r){return(new YT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(YT,t,r)}static $(){return["RedeemGiftCodeRequest|1 code 9"]}}class ZT extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ZT).fromBinary(t,r)}static fromJson(t,r){return(new ZT).fromJson(t,r)}static fromJsonString(t,r){return(new ZT).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ZT,t,r)}static $(){return["RedeemGiftCodeResponse|1 success 8|2 error_message 9?|3 credit_cents 5?|4 currency 9?|5 xpass_plan 9?|6 xpass_plan_ends_at_ms 3?|7 credits_expire_at_ms 3?"]}}class tU extends T{constructor(t){super(),this.code="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tU).fromBinary(t,r)}static fromJson(t,r){return(new tU).fromJson(t,r)}static fromJsonString(t,r){return(new tU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tU,t,r)}static $(){return["GetGiftCodeInfoRequest|1 code 9"]}}class rU extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rU).fromBinary(t,r)}static fromJson(t,r){return(new rU).fromJson(t,r)}static fromJsonString(t,r){return(new rU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rU,t,r)}static $(){return["GetGiftCodeInfoResponse|1 xpass_plan 9?|2 xpass_plan_days 5?|3 credit_cents 5?|4 currency 9?|5 credits_expire_after_days 5?"]}}class eU extends T{constructor(t){super(),this.code="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eU).fromBinary(t,r)}static fromJson(t,r){return(new eU).fromJson(t,r)}static fromJsonString(t,r){return(new eU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eU,t,r)}static $(){return["GetEventCodeInfoRequest|1 code 9"]}}class nU extends T{constructor(t){super(),this.found=!1,this.eventName="",this.creditCents=n.protoInt64.zero,this.claimState=ye.UNSPECIFIED,this.claimStartsAtMs=n.protoInt64.zero,this.claimEndsAtMs=n.protoInt64.zero,this.creditTtlDays=0,this.creditDestination=Se.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nU).fromBinary(t,r)}static fromJson(t,r){return(new nU).fromJson(t,r)}static fromJsonString(t,r){return(new nU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nU,t,r)}static $(){return["GetEventCodeInfoResponse|1 found 8|2 event_name 9|3 credit_cents 3|4 claim_state #0|5 claim_starts_at_ms 3|6 claim_ends_at_ms 3|7 credit_ttl_days 5|8 credit_destination #1",ye,Se]}}class sU extends T{constructor(t){super(),this.code="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sU).fromBinary(t,r)}static fromJson(t,r){return(new sU).fromJson(t,r)}static fromJsonString(t,r){return(new sU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sU,t,r)}static $(){return["RedeemEventCodeRequest|1 code 9"]}}class iU extends T{constructor(t){super(),this.success=!1,this.claimState=ye.UNSPECIFIED,this.alreadyClaimed=!1,this.creditCents=n.protoInt64.zero,this.grantExpiresAtMs=n.protoInt64.zero,this.creditDestination=Se.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iU).fromBinary(t,r)}static fromJson(t,r){return(new iU).fromJson(t,r)}static fromJsonString(t,r){return(new iU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iU,t,r)}static $(){return["RedeemEventCodeResponse|1 success 8|2 claim_state #0|3 already_claimed 8|4 credit_cents 3|5 grant_expires_at_ms 3|6 credit_destination #1",ye,Se]}}class oU extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oU).fromBinary(t,r)}static fromJson(t,r){return(new oU).fromJson(t,r)}static fromJsonString(t,r){return(new oU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oU,t,r)}static $(){return["GetActiveOffboardingBannerRequest|1 team_id 5?"]}}class aU extends T{constructor(t){super(),this.hasBanner=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aU).fromBinary(t,r)}static fromJson(t,r){return(new aU).fromJson(t,r)}static fromJsonString(t,r){return(new aU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aU,t,r)}static $(){return["GetActiveOffboardingBannerResponse|1 has_banner 8|2 banner #0?",uU]}}class uU extends T{constructor(t){super(),this.id="",this.severity="",this.messageKey="",this.dismissible=!1,this.flowType="",this.phaseId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uU).fromBinary(t,r)}static fromJson(t,r){return(new uU).fromJson(t,r)}static fromJsonString(t,r){return(new uU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uU,t,r)}static $(){return["OffboardingBanner|1 id 9|2 severity 9|3 message_key 9|4 countdown_date_epoch_millis 3?|5 dismissible 8|6 flow_type 9|7 phase_id 9|8 action_url 9?"]}}class cU extends T{constructor(t){super(),this.action="",this.args={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cU).fromBinary(t,r)}static fromJson(t,r){return(new cU).fromJson(t,r)}static fromJsonString(t,r){return(new cU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cU,t,r)}static $(){return["ClientActionRequest|1 action 9|2 args 9,9"]}}class lU extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lU).fromBinary(t,r)}static fromJson(t,r){return(new lU).fromJson(t,r)}static fromJsonString(t,r){return(new lU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lU,t,r)}static $(){return["ClientActionResponse|1 success 8|2 error_message 9?|3 info_message 9?|4 open_url 9?|5 confirmation #0?",mU]}}class mU extends T{constructor(t){super(),this.title="",this.message="",this.confirmLabel="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mU).fromBinary(t,r)}static fromJson(t,r){return(new mU).fromJson(t,r)}static fromJsonString(t,r){return(new mU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mU,t,r)}static $(){return["ClientActionConfirmation|1 title 9|2 message 9|3 confirm_label 9|4 action #0",o.bV]}}class fU extends T{constructor(t){super(),this.id="",this.name="",this.content="",this.globs=[],this.isActive=!1,this.isRequired=!1,this.agentType=qe.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fU).fromBinary(t,r)}static fromJson(t,r){return(new fU).fromJson(t,r)}static fromJsonString(t,r){return(new fU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fU,t,r)}static $(){return["Rule|1 id 9|2 name 9|3 content 9|6 globs 9*|4 is_active 8|5 is_required 8|7 agent_type #0",qe]}}class dU extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dU).fromBinary(t,r)}static fromJson(t,r){return(new dU).fromJson(t,r)}static fromJsonString(t,r){return(new dU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dU,t,r)}static $(){return["GetTeamRulesRequest|1 active_only 8?|2 team_id 5?|3 include_member_group_rules 8?"]}}class pU extends T{constructor(t){super(),this.rules=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pU).fromBinary(t,r)}static fromJson(t,r){return(new pU).fromJson(t,r)}static fromJsonString(t,r){return(new pU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pU,t,r)}static $(){return["GetTeamRulesResponse|1 rules #0*",fU]}}class hU extends T{constructor(t){super(),this.name="",this.content="",this.globs=[],this.isActive=!1,this.isRequired=!1,this.agentType=qe.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hU).fromBinary(t,r)}static fromJson(t,r){return(new hU).fromJson(t,r)}static fromJsonString(t,r){return(new hU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hU,t,r)}static $(){return["CreateTeamRuleRequest|1 name 9|2 content 9|5 globs 9*|3 is_active 8|4 is_required 8|6 team_id 5?|7 agent_type #0",qe]}}class gU extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gU).fromBinary(t,r)}static fromJson(t,r){return(new gU).fromJson(t,r)}static fromJsonString(t,r){return(new gU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gU,t,r)}static $(){return["CreateTeamRuleResponse|1 rule #0",fU]}}class _U extends T{constructor(t){super(),this.ruleId="",this.globs=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _U).fromBinary(t,r)}static fromJson(t,r){return(new _U).fromJson(t,r)}static fromJsonString(t,r){return(new _U).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_U,t,r)}static $(){return["UpdateTeamRuleRequest|1 rule_id 9|2 name 9?|3 content 9?|6 globs 9*|4 is_active 8?|5 is_required 8?|7 team_id 5?|8 agent_type #0?|9 clear_globs 8?",qe]}}class JU extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new JU).fromBinary(t,r)}static fromJson(t,r){return(new JU).fromJson(t,r)}static fromJsonString(t,r){return(new JU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(JU,t,r)}static $(){return["UpdateTeamRuleResponse|1 rule #0",fU]}}class wU extends T{constructor(t){super(),this.ruleId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wU).fromBinary(t,r)}static fromJson(t,r){return(new wU).fromJson(t,r)}static fromJsonString(t,r){return(new wU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wU,t,r)}static $(){return["DeleteTeamRuleRequest|1 rule_id 9|2 team_id 5?"]}}class yU extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yU).fromBinary(t,r)}static fromJson(t,r){return(new yU).fromJson(t,r)}static fromJsonString(t,r){return(new yU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yU,t,r)}static $(){return["DeleteTeamRuleResponse"]}}class SU extends T{constructor(t){super(),this.teamId=0,this.groupPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new SU).fromBinary(t,r)}static fromJson(t,r){return(new SU).fromJson(t,r)}static fromJsonString(t,r){return(new SU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(SU,t,r)}static $(){return["GetTeamGroupRulesRequest|1 team_id 5|2 group_public_id 9|3 active_only 8?"]}}class qU extends T{constructor(t){super(),this.rules=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qU).fromBinary(t,r)}static fromJson(t,r){return(new qU).fromJson(t,r)}static fromJsonString(t,r){return(new qU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qU,t,r)}static $(){return["GetTeamGroupRulesResponse|1 rules #0*",fU]}}class BU extends T{constructor(t){super(),this.teamId=0,this.groupId=n.protoInt64.zero,this.name="",this.content="",this.globs=[],this.isActive=!1,this.isRequired=!1,this.agentType=qe.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new BU).fromBinary(t,r)}static fromJson(t,r){return(new BU).fromJson(t,r)}static fromJsonString(t,r){return(new BU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(BU,t,r)}static $(){return["CreateTeamGroupRuleRequest|1 team_id 5|2 group_id 3|3 name 9|4 content 9|5 globs 9*|6 is_active 8|7 is_required 8|8 agent_type #0",qe]}}class IU extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new IU).fromBinary(t,r)}static fromJson(t,r){return(new IU).fromJson(t,r)}static fromJsonString(t,r){return(new IU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(IU,t,r)}static $(){return["CreateTeamGroupRuleResponse|1 rule #0",fU]}}class PU extends T{constructor(t){super(),this.teamId=0,this.groupId=n.protoInt64.zero,this.ruleId="",this.globs=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new PU).fromBinary(t,r)}static fromJson(t,r){return(new PU).fromJson(t,r)}static fromJsonString(t,r){return(new PU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(PU,t,r)}static $(){return["UpdateTeamGroupRuleRequest|1 team_id 5|2 group_id 3|3 rule_id 9|4 name 9?|5 content 9?|6 globs 9*|7 is_active 8?|8 is_required 8?|9 agent_type #0?",qe]}}class bU extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bU).fromBinary(t,r)}static fromJson(t,r){return(new bU).fromJson(t,r)}static fromJsonString(t,r){return(new bU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bU,t,r)}static $(){return["UpdateTeamGroupRuleResponse|1 rule #0",fU]}}class RU extends T{constructor(t){super(),this.teamId=0,this.groupId=n.protoInt64.zero,this.ruleId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new RU).fromBinary(t,r)}static fromJson(t,r){return(new RU).fromJson(t,r)}static fromJsonString(t,r){return(new RU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(RU,t,r)}static $(){return["DeleteTeamGroupRuleRequest|1 team_id 5|2 group_id 3|3 rule_id 9"]}}class vU extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vU).fromBinary(t,r)}static fromJson(t,r){return(new vU).fromJson(t,r)}static fromJsonString(t,r){return(new vU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vU,t,r)}static $(){return["DeleteTeamGroupRuleResponse"]}}class xU extends T{constructor(t){super(),this.id=0,this.hookStep="",this.scriptName="",this.operatingSystems=[],this.isActive=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xU).fromBinary(t,r)}static fromJson(t,r){return(new xU).fromJson(t,r)}static fromJsonString(t,r){return(new xU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xU,t,r)}static $(){return["TeamHook|1 id 5|2 hook_step 9|3 script_name 9|4 operating_systems 9*|5 is_active 8|6 script_content 9?|7 hook_type 9?|8 prompt_content 9?|9 prompt_model 9?"]}}class kU extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kU).fromBinary(t,r)}static fromJson(t,r){return(new kU).fromJson(t,r)}static fromJsonString(t,r){return(new kU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kU,t,r)}static $(){return["GetTeamHooksRequest|1 active_only 8?|2 team_id 5?"]}}class EU extends T{constructor(t){super(),this.hooks=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new EU).fromBinary(t,r)}static fromJson(t,r){return(new EU).fromJson(t,r)}static fromJsonString(t,r){return(new EU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(EU,t,r)}static $(){return["GetTeamHooksResponse|1 hooks #0*",xU]}}class CU extends T{constructor(t){super(),this.hookStep="",this.scriptName="",this.operatingSystems=[],this.isActive=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new CU).fromBinary(t,r)}static fromJson(t,r){return(new CU).fromJson(t,r)}static fromJsonString(t,r){return(new CU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(CU,t,r)}static $(){return["CreateTeamHookRequest|1 hook_step 9|2 script_name 9|3 operating_systems 9*|4 is_active 8|5 script_content 9?|6 hook_type 9?|7 prompt_content 9?|8 prompt_model 9?|9 team_id 5?"]}}class TU extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new TU).fromBinary(t,r)}static fromJson(t,r){return(new TU).fromJson(t,r)}static fromJsonString(t,r){return(new TU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(TU,t,r)}static $(){return["CreateTeamHookResponse|1 hook #0",xU]}}class UU extends T{constructor(t){super(),this.hookId="",this.operatingSystems=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new UU).fromBinary(t,r)}static fromJson(t,r){return(new UU).fromJson(t,r)}static fromJsonString(t,r){return(new UU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(UU,t,r)}static $(){return["UpdateTeamHookRequest|1 hook_id 9|2 script_name 9?|3 operating_systems 9*|4 is_active 8?|5 script_content 9?|6 hook_type 9?|7 prompt_content 9?|8 prompt_model 9?|9 team_id 5?|10 clear_prompt_model 8?"]}}class AU extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new AU).fromBinary(t,r)}static fromJson(t,r){return(new AU).fromJson(t,r)}static fromJsonString(t,r){return(new AU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(AU,t,r)}static $(){return["UpdateTeamHookResponse|1 hook #0",xU]}}class $U extends T{constructor(t){super(),this.hookId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $U).fromBinary(t,r)}static fromJson(t,r){return(new $U).fromJson(t,r)}static fromJsonString(t,r){return(new $U).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($U,t,r)}static $(){return["DeleteTeamHookRequest|1 hook_id 9|2 team_id 5?"]}}class MU extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new MU).fromBinary(t,r)}static fromJson(t,r){return(new MU).fromJson(t,r)}static fromJsonString(t,r){return(new MU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(MU,t,r)}static $(){return["DeleteTeamHookResponse"]}}class OU extends T{constructor(t){super(),this.id="",this.name="",this.content="",this.isActive=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new OU).fromBinary(t,r)}static fromJson(t,r){return(new OU).fromJson(t,r)}static fromJsonString(t,r){return(new OU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(OU,t,r)}static $(){return["TeamCommand|1 id 9|2 name 9|3 content 9|4 description 9?|5 is_active 8"]}}class DU extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new DU).fromBinary(t,r)}static fromJson(t,r){return(new DU).fromJson(t,r)}static fromJsonString(t,r){return(new DU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(DU,t,r)}static $(){return["GetTeamCommandsRequest|1 active_only 8?|2 team_id 5?"]}}class NU extends T{constructor(t){super(),this.commands=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new NU).fromBinary(t,r)}static fromJson(t,r){return(new NU).fromJson(t,r)}static fromJsonString(t,r){return(new NU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(NU,t,r)}static $(){return["GetTeamCommandsResponse|1 commands #0*",OU]}}class GU extends T{constructor(t){super(),this.name="",this.content="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new GU).fromBinary(t,r)}static fromJson(t,r){return(new GU).fromJson(t,r)}static fromJsonString(t,r){return(new GU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(GU,t,r)}static $(){return["CreateTeamCommandRequest|1 name 9|2 content 9|3 description 9?|4 is_active 8?|5 team_id 5?"]}}class LU extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new LU).fromBinary(t,r)}static fromJson(t,r){return(new LU).fromJson(t,r)}static fromJsonString(t,r){return(new LU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(LU,t,r)}static $(){return["CreateTeamCommandResponse|1 command #0",OU]}}class FU extends T{constructor(t){super(),this.commandId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new FU).fromBinary(t,r)}static fromJson(t,r){return(new FU).fromJson(t,r)}static fromJsonString(t,r){return(new FU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(FU,t,r)}static $(){return["UpdateTeamCommandRequest|1 command_id 9|2 name 9?|3 content 9?|4 description 9?|5 is_active 8?|6 team_id 5?"]}}class KU extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new KU).fromBinary(t,r)}static fromJson(t,r){return(new KU).fromJson(t,r)}static fromJsonString(t,r){return(new KU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(KU,t,r)}static $(){return["UpdateTeamCommandResponse|1 command #0",OU]}}class zU extends T{constructor(t){super(),this.commandId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zU).fromBinary(t,r)}static fromJson(t,r){return(new zU).fromJson(t,r)}static fromJsonString(t,r){return(new zU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zU,t,r)}static $(){return["DeleteTeamCommandRequest|1 command_id 9|2 team_id 5?"]}}class jU extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jU).fromBinary(t,r)}static fromJson(t,r){return(new jU).fromJson(t,r)}static fromJsonString(t,r){return(new jU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jU,t,r)}static $(){return["DeleteTeamCommandResponse"]}}class HU extends T{constructor(t){super(),this.name="",this.content="",this.availability=Be.UNSPECIFIED,this.disabledSurfaces=[],this.requiresAllWorkspaceFoldersAreGitRepos=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new HU).fromBinary(t,r)}static fromJson(t,r){return(new HU).fromJson(t,r)}static fromJsonString(t,r){return(new HU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(HU,t,r)}static $(){return["GlobalCommand|1 name 9|2 content 9|3 description 9?|4 availability #0|5 argument_hint 9?|6 disabled_surfaces #1*|7 requires_all_workspace_folders_are_git_repos 8",Be,Ie]}}class WU extends T{constructor(t){super(),this.surface=Ie.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new WU).fromBinary(t,r)}static fromJson(t,r){return(new WU).fromJson(t,r)}static fromJsonString(t,r){return(new WU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(WU,t,r)}static $(){return["GetGlobalCommandsRequest|1 surface #0",Ie]}}class QU extends T{constructor(t){super(),this.commands=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new QU).fromBinary(t,r)}static fromJson(t,r){return(new QU).fromJson(t,r)}static fromJsonString(t,r){return(new QU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(QU,t,r)}static $(){return["GetGlobalCommandsResponse|1 commands #0*",HU]}}class VU extends T{constructor(t){super(),this.repoUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new VU).fromBinary(t,r)}static fromJson(t,r){return(new VU).fromJson(t,r)}static fromJsonString(t,r){return(new VU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(VU,t,r)}static $(){return["GetRepoSlashCommandsRequest|1 repo_url 9|2 git_ref 9?|3 include_project_plugin_skills 8?"]}}class XU extends T{constructor(t){super(),this.skillNames=[],this.commandNames=[],this.skills=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new XU).fromBinary(t,r)}static fromJson(t,r){return(new XU).fromJson(t,r)}static fromJsonString(t,r){return(new XU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(XU,t,r)}static $(){return["GetRepoSlashCommandsResponse|3 skill_names 9*|4 command_names 9*|5 skills #0*|6 repo_skills_omission #1?",wO,tA]}}class YU extends T{constructor(t){super(),this.bcId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new YU).fromBinary(t,r)}static fromJson(t,r){return(new YU).fromJson(t,r)}static fromJsonString(t,r){return(new YU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(YU,t,r)}static $(){return["GetBackgroundComposerSlashCommandsRequest|1 bc_id 9|2 repo_url 9?|3 git_ref 9?|4 supports_project_repo_commands 8?"]}}class ZU extends T{constructor(t){super(),this.skillNames=[],this.commandNames=[],this.skills=[],this.commands=[],this.projectRepoSkillsOmissions=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ZU).fromBinary(t,r)}static fromJson(t,r){return(new ZU).fromJson(t,r)}static fromJsonString(t,r){return(new ZU).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ZU,t,r)}static $(){return["GetBackgroundComposerSlashCommandsResponse|3 skill_names 9*|4 command_names 9*|5 skills #0*|6 commands #1*|8 machine_inventory_pending 8?|9 project_repo_skills_incomplete 8?|10 project_repo_skills_omissions #2*|11 project_repo_descriptions_pending 8?",wO,IO,tA]}}class tA extends T{constructor(t){super(),this.reason=Pe.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tA).fromBinary(t,r)}static fromJson(t,r){return(new tA).fromJson(t,r)}static fromJsonString(t,r){return(new tA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tA,t,r)}static $(){return["ProjectRepoSkillsOmission|1 reason #0",Pe]}}class rA extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rA).fromBinary(t,r)}static fromJson(t,r){return(new rA).fromJson(t,r)}static fromJsonString(t,r){return(new rA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rA,t,r)}static $(){return["GetCloudAgentPluginsSnapshotRequest|1 use_replica 8?|2 team_id 5?"]}}class eA extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eA).fromBinary(t,r)}static fromJson(t,r){return(new eA).fromJson(t,r)}static fromJsonString(t,r){return(new eA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eA,t,r)}static $(){return["CloudAgentPluginSnapshot|1 effective_plugin #0|3 git_ref 9?",kN]}}class nA extends T{constructor(t){super(),this.snapshotToken="",this.plugins=[],this.warnings=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nA).fromBinary(t,r)}static fromJson(t,r){return(new nA).fromJson(t,r)}static fromJsonString(t,r){return(new nA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nA,t,r)}static $(){return["GetCloudAgentPluginsSnapshotResponse|1 snapshot_token 9|2 plugins #0*|3 warnings 9*",eA]}}class sA extends T{constructor(t){super(),this.id="",this.name="",this.content="",this.isActive=!1,this.isRequired=!1,this.createdAt="",this.updatedAt="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sA).fromBinary(t,r)}static fromJson(t,r){return(new sA).fromJson(t,r)}static fromJsonString(t,r){return(new sA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sA,t,r)}static $(){return["BugbotRule|1 id 9|2 name 9|3 content 9|4 is_active 8|5 is_required 8|6 created_at 9|7 updated_at 9"]}}class iA extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iA).fromBinary(t,r)}static fromJson(t,r){return(new iA).fromJson(t,r)}static fromJsonString(t,r){return(new iA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iA,t,r)}static $(){return["GetBugbotTeamRulesRequest|1 active_only 8?|2 team_id 5?"]}}class oA extends T{constructor(t){super(),this.rules=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oA).fromBinary(t,r)}static fromJson(t,r){return(new oA).fromJson(t,r)}static fromJsonString(t,r){return(new oA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oA,t,r)}static $(){return["GetBugbotTeamRulesResponse|1 rules #0*",sA]}}class aA extends T{constructor(t){super(),this.name="",this.content="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aA).fromBinary(t,r)}static fromJson(t,r){return(new aA).fromJson(t,r)}static fromJsonString(t,r){return(new aA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aA,t,r)}static $(){return["CreateBugbotTeamRuleRequest|1 name 9|2 content 9|3 is_active 8?|4 is_required 8?|5 team_id 5?"]}}class uA extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uA).fromBinary(t,r)}static fromJson(t,r){return(new uA).fromJson(t,r)}static fromJsonString(t,r){return(new uA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uA,t,r)}static $(){return["CreateBugbotTeamRuleResponse|1 rule #0",sA]}}class cA extends T{constructor(t){super(),this.ruleId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cA).fromBinary(t,r)}static fromJson(t,r){return(new cA).fromJson(t,r)}static fromJsonString(t,r){return(new cA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cA,t,r)}static $(){return["UpdateBugbotTeamRuleRequest|1 rule_id 9|2 name 9?|3 content 9?|4 is_active 8?|5 is_required 8?|6 team_id 5?"]}}class lA extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lA).fromBinary(t,r)}static fromJson(t,r){return(new lA).fromJson(t,r)}static fromJsonString(t,r){return(new lA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lA,t,r)}static $(){return["UpdateBugbotTeamRuleResponse|1 rule #0",sA]}}class mA extends T{constructor(t){super(),this.ruleId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mA).fromBinary(t,r)}static fromJson(t,r){return(new mA).fromJson(t,r)}static fromJsonString(t,r){return(new mA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mA,t,r)}static $(){return["DeleteBugbotTeamRuleRequest|1 rule_id 9|2 team_id 5?"]}}class fA extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fA).fromBinary(t,r)}static fromJson(t,r){return(new fA).fromJson(t,r)}static fromJsonString(t,r){return(new fA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fA,t,r)}static $(){return["DeleteBugbotTeamRuleResponse"]}}class dA extends T{constructor(t){super(),this.installationId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dA).fromBinary(t,r)}static fromJson(t,r){return(new dA).fromJson(t,r)}static fromJsonString(t,r){return(new dA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dA,t,r)}static $(){return["GetBugbotLearnedRulesRequest|1 installation_id 3|2 ghe_application 9?|3 repo_node_id_filter 9?"]}}class pA extends T{constructor(t){super(),this.rules=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pA).fromBinary(t,r)}static fromJson(t,r){return(new pA).fromJson(t,r)}static fromJsonString(t,r){return(new pA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pA,t,r)}static $(){return["GetBugbotLearnedRulesResponse|1 rules #0*",hA]}}class hA extends T{constructor(t){super(),this.id="",this.name="",this.content="",this.repoNodeId="",this.repoName="",this.status="",this.createdAt="",this.updatedAt="",this.examplePrNumbers=[],this.repoOwner="",this.scopedPaths=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hA).fromBinary(t,r)}static fromJson(t,r){return(new hA).fromJson(t,r)}static fromJsonString(t,r){return(new hA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hA,t,r)}static $(){return["BugbotLearnedRule|1 id 9|2 name 9|3 content 9|4 repo_node_id 9|5 repo_name 9|6 status 9|7 created_at 9|8 updated_at 9|9 example_pr_numbers 5*|11 repo_owner 9|12 scoped_paths 9*"]}}class gA extends T{constructor(t){super(),this.ruleId="",this.installationId=n.protoInt64.zero,this.scopedPaths=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gA).fromBinary(t,r)}static fromJson(t,r){return(new gA).fromJson(t,r)}static fromJsonString(t,r){return(new gA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gA,t,r)}static $(){return["UpdateBugbotLearnedRuleRequest|1 rule_id 9|2 installation_id 3|3 ghe_application 9?|4 name 9?|5 content 9?|6 status 9?|7 scoped_paths 9*"]}}class _A extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _A).fromBinary(t,r)}static fromJson(t,r){return(new _A).fromJson(t,r)}static fromJsonString(t,r){return(new _A).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_A,t,r)}static $(){return["UpdateBugbotLearnedRuleResponse|1 rule #0",hA]}}class JA extends T{constructor(t){super(),this.ruleId="",this.installationId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new JA).fromBinary(t,r)}static fromJson(t,r){return(new JA).fromJson(t,r)}static fromJsonString(t,r){return(new JA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(JA,t,r)}static $(){return["DeleteBugbotLearnedRuleRequest|1 rule_id 9|2 installation_id 3|3 ghe_application 9?"]}}class wA extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wA).fromBinary(t,r)}static fromJson(t,r){return(new wA).fromJson(t,r)}static fromJsonString(t,r){return(new wA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wA,t,r)}static $(){return["DeleteBugbotLearnedRuleResponse"]}}class yA extends T{constructor(t){super(),this.id="",this.name="",this.content="",this.repoNodeId="",this.repoName="",this.status="",this.createdAt="",this.updatedAt="",this.repoOwner="",this.scopedPaths=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yA).fromBinary(t,r)}static fromJson(t,r){return(new yA).fromJson(t,r)}static fromJsonString(t,r){return(new yA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yA,t,r)}static $(){return["BugbotManualRepositoryRule|1 id 9|2 name 9|3 content 9|4 repo_node_id 9|5 repo_name 9|6 status 9|7 created_at 9|8 updated_at 9|9 repo_owner 9|10 scoped_paths 9*"]}}class SA extends T{constructor(t){super(),this.installationId=n.protoInt64.zero,this.repoNodeId="",this.name="",this.content="",this.scopedPaths=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new SA).fromBinary(t,r)}static fromJson(t,r){return(new SA).fromJson(t,r)}static fromJsonString(t,r){return(new SA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(SA,t,r)}static $(){return["CreateBugbotManualRepositoryRuleRequest|1 installation_id 3|2 ghe_application 9?|3 repo_node_id 9|4 name 9|5 content 9|6 status 9?|7 scoped_paths 9*"]}}class qA extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qA).fromBinary(t,r)}static fromJson(t,r){return(new qA).fromJson(t,r)}static fromJsonString(t,r){return(new qA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qA,t,r)}static $(){return["CreateBugbotManualRepositoryRuleResponse|1 rule #0",yA]}}class BA extends T{constructor(t){super(),this.installationId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new BA).fromBinary(t,r)}static fromJson(t,r){return(new BA).fromJson(t,r)}static fromJsonString(t,r){return(new BA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(BA,t,r)}static $(){return["GetBugbotManualRepositoryRulesRequest|1 installation_id 3|2 ghe_application 9?|3 repo_node_id_filter 9?"]}}class IA extends T{constructor(t){super(),this.rules=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new IA).fromBinary(t,r)}static fromJson(t,r){return(new IA).fromJson(t,r)}static fromJsonString(t,r){return(new IA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(IA,t,r)}static $(){return["GetBugbotManualRepositoryRulesResponse|1 rules #0*",yA]}}class PA extends T{constructor(t){super(),this.ruleId="",this.installationId=n.protoInt64.zero,this.scopedPaths=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new PA).fromBinary(t,r)}static fromJson(t,r){return(new PA).fromJson(t,r)}static fromJsonString(t,r){return(new PA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(PA,t,r)}static $(){return["UpdateBugbotManualRepositoryRuleRequest|1 rule_id 9|2 installation_id 3|3 ghe_application 9?|4 name 9?|5 content 9?|6 status 9?|7 scoped_paths 9*"]}}class bA extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bA).fromBinary(t,r)}static fromJson(t,r){return(new bA).fromJson(t,r)}static fromJsonString(t,r){return(new bA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bA,t,r)}static $(){return["UpdateBugbotManualRepositoryRuleResponse|1 rule #0",yA]}}class RA extends T{constructor(t){super(),this.ruleId="",this.installationId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new RA).fromBinary(t,r)}static fromJson(t,r){return(new RA).fromJson(t,r)}static fromJsonString(t,r){return(new RA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(RA,t,r)}static $(){return["DeleteBugbotManualRepositoryRuleRequest|1 rule_id 9|2 installation_id 3|3 ghe_application 9?"]}}class vA extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vA).fromBinary(t,r)}static fromJson(t,r){return(new vA).fromJson(t,r)}static fromJsonString(t,r){return(new vA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vA,t,r)}static $(){return["DeleteBugbotManualRepositoryRuleResponse"]}}class xA extends T{constructor(t){super(),this.teamId=0,this.installationId=n.protoInt64.zero,this.graphiteWorkspaceId="",this.mode=be.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xA).fromBinary(t,r)}static fromJson(t,r){return(new xA).fromJson(t,r)}static fromJsonString(t,r){return(new xA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xA,t,r)}static $(){return["RunDiamondToBugbotMigrationRequest|1 team_id 5|2 installation_id 3|3 ghe_application 9?|4 graphite_workspace_id 9|5 mode #0|6 approved_preview_hash 9?|7 extracted_settings #1",be,n.Struct]}}class kA extends T{constructor(t){super(),this.status="",this.previewHash="",this.previewJson="",this.repositoryRulesJson="",this.applyPlanJson="",this.auditJson="",this.warnings=[],this.blockers=[],this.appliedOperationIds=[],this.skippedOperationIds=[],this.resolvedTeamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kA).fromBinary(t,r)}static fromJson(t,r){return(new kA).fromJson(t,r)}static fromJsonString(t,r){return(new kA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kA,t,r)}static $(){return["RunDiamondToBugbotMigrationResponse|1 status 9|2 preview_hash 9|3 preview_json 9|4 repository_rules_json 9|5 apply_plan_json 9|6 audit_json 9|7 warnings 9*|8 blockers 9*|9 applied_operation_ids 9*|10 skipped_operation_ids 9*|11 resolved_team_id 5"]}}class EA extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new EA).fromBinary(t,r)}static fromJson(t,r){return(new EA).fromJson(t,r)}static fromJsonString(t,r){return(new EA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(EA,t,r)}static $(){return["GetBugbotRuleAnalyticsRequest|1 date_range_start 9?|2 date_range_end 9?|3 team_id 5?"]}}class CA extends T{constructor(t){super(),this.rules=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new CA).fromBinary(t,r)}static fromJson(t,r){return(new CA).fromJson(t,r)}static fromJsonString(t,r){return(new CA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(CA,t,r)}static $(){return["GetBugbotRuleAnalyticsResponse|1 rules #0*",TA]}}class TA extends T{constructor(t){super(),this.ruleId="",this.ruleType="",this.name="",this.content="",this.repositories=[],this.issuesFound=0,this.prsReviewed=0,this.acceptedIssues=0,this.acceptanceRate=0,this.upvoteRate=0,this.downvoteRate=0,this.status="",this.createdAt="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new TA).fromBinary(t,r)}static fromJson(t,r){return(new TA).fromJson(t,r)}static fromJsonString(t,r){return(new TA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(TA,t,r)}static $(){return["BugbotRuleAnalytics|1 rule_id 9|2 rule_type 9|3 name 9|4 content 9|5 repositories 9*|6 issues_found 5|7 prs_reviewed 5|8 accepted_issues 5|9 acceptance_rate 1|10 upvote_rate 1|11 downvote_rate 1|12 status 9|13 created_at 9"]}}class UA extends T{constructor(t){super(),this.ruleId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new UA).fromBinary(t,r)}static fromJson(t,r){return(new UA).fromJson(t,r)}static fromJsonString(t,r){return(new UA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(UA,t,r)}static $(){return["GetBugbotRuleByIdRequest|1 rule_id 9|2 team_id 5?"]}}class AA extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new AA).fromBinary(t,r)}static fromJson(t,r){return(new AA).fromJson(t,r)}static fromJsonString(t,r){return(new AA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(AA,t,r)}static $(){return["GetBugbotRuleByIdResponse|1 team_rule #0?|2 learned_rule #1?|3 analytics #2|4 manual_rule #3?",sA,hA,TA,yA]}}class $A extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $A).fromBinary(t,r)}static fromJson(t,r){return(new $A).fromJson(t,r)}static fromJsonString(t,r){return(new $A).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($A,t,r)}static $(){return["SharedConversationCreator|1 user_id 5?|2 first_name 9?"]}}class MA extends T{constructor(t){super(),this.id="",this.title="",this.visibility=Re.UNSPECIFIED,this.createdAt="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new MA).fromBinary(t,r)}static fromJson(t,r){return(new MA).fromJson(t,r)}static fromJsonString(t,r){return(new MA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(MA,t,r)}static $(){return["SharedConversationMetadata|1 id 9|2 title 9|3 visibility #0|4 created_at 9|5 creator #1|6 conversation_id 9?",Re,$A]}}class OA extends T{constructor(t){super(),this.planId="",this.title="",this.content="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new OA).fromBinary(t,r)}static fromJson(t,r){return(new OA).fromJson(t,r)}static fromJsonString(t,r){return(new OA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(OA,t,r)}static $(){return["SharedConversationLatestPlan|1 plan_id 9|2 title 9|3 content 9"]}}class DA extends T{constructor(t){super(),this.userId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new DA).fromBinary(t,r)}static fromJson(t,r){return(new DA).fromJson(t,r)}static fromJsonString(t,r){return(new DA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(DA,t,r)}static $(){return["SharedCanvasCreator|1 user_id 9|2 first_name 9?"]}}class NA extends T{constructor(t){super(),this.id="",this.title="",this.visibility=ve.UNSPECIFIED,this.createdAt="",this.updatedAt="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new NA).fromBinary(t,r)}static fromJson(t,r){return(new NA).fromJson(t,r)}static fromJsonString(t,r){return(new NA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(NA,t,r)}static $(){return["SharedCanvasMetadata|1 id 9|2 title 9|3 visibility #0|4 created_at 9|5 creator #1|7 updated_at 9",ve,DA]}}class GA extends T{constructor(t){super(),this.title="",this.visibility=ve.UNSPECIFIED,this.appJs=new Uint8Array(0),this.dataJson=new Uint8Array(0),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new GA).fromBinary(t,r)}static fromJson(t,r){return(new GA).fromJson(t,r)}static fromJsonString(t,r){return(new GA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(GA,t,r)}static $(){return["ShareCanvasRequest|1 title 9|2 visibility #0|3 app_js 12|4 data_json 12|6 canvas_key 9?",ve]}}class LA extends T{constructor(t){super(),this.shareId="",this.shareUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new LA).fromBinary(t,r)}static fromJson(t,r){return(new LA).fromJson(t,r)}static fromJsonString(t,r){return(new LA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(LA,t,r)}static $(){return["ShareCanvasResponse|1 share_id 9|2 share_url 9"]}}class FA extends T{constructor(t){super(),this.shareId="",this.metadataOnly=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new FA).fromBinary(t,r)}static fromJson(t,r){return(new FA).fromJson(t,r)}static fromJsonString(t,r){return(new FA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(FA,t,r)}static $(){return["GetSharedCanvasRequest|1 share_id 9|2 metadata_only 8"]}}class KA extends T{constructor(t){super(),this.appJs=new Uint8Array(0),this.dataJson=new Uint8Array(0),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new KA).fromBinary(t,r)}static fromJson(t,r){return(new KA).fromJson(t,r)}static fromJsonString(t,r){return(new KA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(KA,t,r)}static $(){return["GetSharedCanvasResponse|1 metadata #0|2 app_js 12|3 data_json 12",NA]}}class zA extends T{constructor(t){super(),this.shareId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zA).fromBinary(t,r)}static fromJson(t,r){return(new zA).fromJson(t,r)}static fromJsonString(t,r){return(new zA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zA,t,r)}static $(){return["GetPublicSharedCanvasRequest|1 share_id 9"]}}class jA extends T{constructor(t){super(),this.title="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jA).fromBinary(t,r)}static fromJson(t,r){return(new jA).fromJson(t,r)}static fromJsonString(t,r){return(new jA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jA,t,r)}static $(){return["PublicSharedCanvasPreview|1 title 9"]}}class HA extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new HA).fromBinary(t,r)}static fromJson(t,r){return(new HA).fromJson(t,r)}static fromJsonString(t,r){return(new HA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(HA,t,r)}static $(){return["GetPublicSharedCanvasResponse|1 preview #0",jA]}}class WA extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new WA).fromBinary(t,r)}static fromJson(t,r){return(new WA).fromJson(t,r)}static fromJsonString(t,r){return(new WA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(WA,t,r)}static $(){return["ListSharedCanvasesRequest|1 limit 13?|2 created_before 9?|3 creator_id 9?|4 team_id 9?|5 created_before_id 9?"]}}class QA extends T{constructor(t){super(),this.canvases=[],this.hasMore=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new QA).fromBinary(t,r)}static fromJson(t,r){return(new QA).fromJson(t,r)}static fromJsonString(t,r){return(new QA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(QA,t,r)}static $(){return["ListSharedCanvasesResponse|1 canvases #0*|2 has_more 8",NA]}}class VA extends T{constructor(t){super(),this.shareId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new VA).fromBinary(t,r)}static fromJson(t,r){return(new VA).fromJson(t,r)}static fromJsonString(t,r){return(new VA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(VA,t,r)}static $(){return["DeleteSharedCanvasRequest|1 share_id 9"]}}class XA extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new XA).fromBinary(t,r)}static fromJson(t,r){return(new XA).fromJson(t,r)}static fromJsonString(t,r){return(new XA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(XA,t,r)}static $(){return["DeleteSharedCanvasResponse"]}}class YA extends T{constructor(t){super(),this.canvasKey="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new YA).fromBinary(t,r)}static fromJson(t,r){return(new YA).fromJson(t,r)}static fromJsonString(t,r){return(new YA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(YA,t,r)}static $(){return["LookupSharedCanvasByKeyRequest|1 canvas_key 9"]}}class ZA extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ZA).fromBinary(t,r)}static fromJson(t,r){return(new ZA).fromJson(t,r)}static fromJsonString(t,r){return(new ZA).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ZA,t,r)}static $(){return["LookupSharedCanvasByKeyResponse|1 share_id 9?|2 visibility #0?|3 share_url 9?|4 updated_at 9?",ve]}}class t$ extends T{constructor(t){super(),this.storeId="",this.canvasId="",this.createdAt="",this.updatedAt="",this.grokBotContributorAgentIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new t$).fromBinary(t,r)}static fromJson(t,r){return(new t$).fromJson(t,r)}static fromJsonString(t,r){return(new t$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(t$,t,r)}static $(){return["CloudCanvasMetadata|1 store_id 9|2 canvas_id 9|3 title 9?|4 created_at 9|5 updated_at 9|6 visibility #0?|7 can_share_to_team 8?|15 team_share_requires_access_list 8?|8 page_url 9?|9 page_slug 9?|10 can_share_public 8?|11 brand #1?|12 team_share_blocked_by_admin 8?|13 public_share_withheld_for_enterprise 8?|14 can_rename_page 8?|17 grok_bot_contributor_agent_ids 9*|18 project_share #2?",ke,xe,r$]}}class r$ extends T{constructor(t){super(),this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new r$).fromBinary(t,r)}static fromJson(t,r){return(new r$).fromJson(t,r)}static fromJsonString(t,r){return(new r$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(r$,t,r)}static $(){return["CanvasProjectShare|1 name 9"]}}class e$ extends T{constructor(t){super(),this.pageSize=0,this.pageToken="",this.sharedOnly=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new e$).fromBinary(t,r)}static fromJson(t,r){return(new e$).fromJson(t,r)}static fromJsonString(t,r){return(new e$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(e$,t,r)}static $(){return["ListUserCanvasesRequest|1 page_size 5|2 page_token 9|3 shared_only 8"]}}class n$ extends T{constructor(t){super(),this.canvases=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new n$).fromBinary(t,r)}static fromJson(t,r){return(new n$).fromJson(t,r)}static fromJsonString(t,r){return(new n$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(n$,t,r)}static $(){return["ListUserCanvasesResponse|1 store_id 9?|2 canvases #0*|3 next_page_token 9?",t$]}}class s$ extends T{constructor(t){super(),this.storeId="",this.canvasId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new s$).fromBinary(t,r)}static fromJson(t,r){return(new s$).fromJson(t,r)}static fromJsonString(t,r){return(new s$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(s$,t,r)}static $(){return["GetCanvasMetadataRequest|1 store_id 9|2 canvas_id 9"]}}class i$ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new i$).fromBinary(t,r)}static fromJson(t,r){return(new i$).fromJson(t,r)}static fromJsonString(t,r){return(new i$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(i$,t,r)}static $(){return["GetCanvasMetadataResponse|1 metadata #0",t$]}}class o$ extends T{constructor(t){super(),this.storeId="",this.canvasId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o$).fromBinary(t,r)}static fromJson(t,r){return(new o$).fromJson(t,r)}static fromJsonString(t,r){return(new o$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o$,t,r)}static $(){return["GetCanvasPageBrandRequest|1 store_id 9|2 canvas_id 9"]}}class a$ extends T{constructor(t){super(),this.brand=xe.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a$).fromBinary(t,r)}static fromJson(t,r){return(new a$).fromJson(t,r)}static fromJsonString(t,r){return(new a$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a$,t,r)}static $(){return["GetCanvasPageBrandResponse|1 brand #0",xe]}}class u$ extends T{constructor(t){super(),this.storeId="",this.canvasId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u$).fromBinary(t,r)}static fromJson(t,r){return(new u$).fromJson(t,r)}static fromJsonString(t,r){return(new u$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u$,t,r)}static $(){return["GetCanvasPayloadRequest|1 store_id 9|2 canvas_id 9"]}}class c$ extends T{constructor(t){super(),this.name="",this.url="",this.expiresAtMs=n.protoInt64.zero,this.contentType="",this.sizeBytes=n.protoInt64.zero,this.expiresInMs=n.protoInt64.zero,this.width=0,this.height=0,this.placeholder="",this.etag="",this.previews=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c$).fromBinary(t,r)}static fromJson(t,r){return(new c$).fromJson(t,r)}static fromJsonString(t,r){return(new c$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c$,t,r)}static $(){return["CanvasPayloadAssetUrl|1 name 9|2 url 9|3 expires_at_ms 3|4 content_type 9|5 size_bytes 3|6 expires_in_ms 3|7 width 5|8 height 5|9 placeholder 9|10 etag 9|11 previews #0*",k]}}class l$ extends T{constructor(t){super(),this.renderBundleGzip=new Uint8Array(0),this.assets=[],this.visualizationRuntimes=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l$).fromBinary(t,r)}static fromJson(t,r){return(new l$).fromJson(t,r)}static fromJsonString(t,r){return(new l$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l$,t,r)}static $(){return["GetCanvasPayloadResponse|1 metadata #0|2 render_bundle_gzip 12|3 data_json 12?|4 assets #1*|5 visualization_runtimes #2*",t$,c$,w]}}class m$ extends T{constructor(t){super(),this.storeId="",this.canvasId="",this.sourceIds=[],this.now=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m$).fromBinary(t,r)}static fromJson(t,r){return(new m$).fromJson(t,r)}static fromJsonString(t,r){return(new m$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m$,t,r)}static $(){return["RefreshCanvasSourcesRequest|1 store_id 9|2 canvas_id 9|3 source_ids 9*|4 now 8"]}}class f$ extends T{constructor(t){super(),this.sourcesJson="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f$).fromBinary(t,r)}static fromJson(t,r){return(new f$).fromJson(t,r)}static fromJsonString(t,r){return(new f$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f$,t,r)}static $(){return["RefreshCanvasSourcesResponse|1 sources_json 9"]}}class d$ extends T{constructor(t){super(),this.storeId="",this.canvasId="",this.connector="",this.tool="",this.slotId="",this.slotValueJson="",this.agentId="",this.pressId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d$).fromBinary(t,r)}static fromJson(t,r){return(new d$).fromJson(t,r)}static fromJsonString(t,r){return(new d$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d$,t,r)}static $(){return["RunCanvasConnectorActionRequest|1 store_id 9|2 canvas_id 9|3 connector 9|4 tool 9|5 args #0|6 slot_id 9|7 slot_value_json 9|8 agent_id 9|9 press_id 9",n.Struct]}}class p$ extends T{constructor(t){super(),this.outcome=h$.UNSPECIFIED,this.detail="",this.asOf="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p$).fromBinary(t,r)}static fromJson(t,r){return(new p$).fromJson(t,r)}static fromJsonString(t,r){return(new p$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p$,t,r)}static $(){return["RunCanvasConnectorActionResponse|1 outcome #0|2 detail 9|3 as_of 9",h$]}}var h$=(0,a.QT)(n.proto3,C,"RunCanvasConnectorActionResponse.Outcome",[[0,"UNSPECIFIED"],[1,"DONE"],[2,"SENT_NOT_RECORDED"],[3,"FAILED"],[4,"NOT_CONNECTED"],[5,"REFUSED"],[6,"UNCONFIRMED"]],1);class g$ extends T{constructor(t){super(),this.storeId="",this.documentId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g$).fromBinary(t,r)}static fromJson(t,r){return(new g$).fromJson(t,r)}static fromJsonString(t,r){return(new g$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g$,t,r)}static $(){return["GetDocumentPayloadRequest|1 store_id 9|2 document_id 9"]}}class _$ extends T{constructor(t){super(),this.name="",this.url="",this.expiresAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _$).fromBinary(t,r)}static fromJson(t,r){return(new _$).fromJson(t,r)}static fromJsonString(t,r){return(new _$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_$,t,r)}static $(){return["DocumentPayloadAssetUrl|1 name 9|2 url 9|3 expires_at_ms 3"]}}class J$ extends T{constructor(t){super(),this.content="",this.assets=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new J$).fromBinary(t,r)}static fromJson(t,r){return(new J$).fromJson(t,r)}static fromJsonString(t,r){return(new J$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(J$,t,r)}static $(){return["GetDocumentPayloadResponse|1 content 9|2 assets #0*",_$]}}class w$ extends T{constructor(t){super(),this.storeId="",this.canvasId="",this.visibility=ke.UNSPECIFIED,this.principals=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new w$).fromBinary(t,r)}static fromJson(t,r){return(new w$).fromJson(t,r)}static fromJsonString(t,r){return(new w$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(w$,t,r)}static $(){return["SetCanvasVisibilityRequest|1 store_id 9|2 canvas_id 9|3 visibility #0|4 open_to_team 8?|5 principals #1*",ke,S$]}}class y$ extends T{constructor(t){super(),this.visibility=ke.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new y$).fromBinary(t,r)}static fromJson(t,r){return(new y$).fromJson(t,r)}static fromJsonString(t,r){return(new y$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(y$,t,r)}static $(){return["SetCanvasVisibilityResponse|1 visibility #0|2 page_url 9?|3 page_slug 9?",ke]}}class S$ extends T{constructor(t){super(),this.principal={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new S$).fromBinary(t,r)}static fromJson(t,r){return(new S$).fromJson(t,r)}static fromJsonString(t,r){return(new S$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(S$,t,r)}static $(){return["CanvasAccessPrincipal|1 user_id 5 principal|2 group_id 3 principal|3 team_id 5 principal"]}}class q$ extends T{constructor(t){super(),this.principals=[],this.openToTeam=!1,this.expectedStateToken="",this.owningTeamId=0,this.openToOrganization=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new q$).fromBinary(t,r)}static fromJson(t,r){return(new q$).fromJson(t,r)}static fromJsonString(t,r){return(new q$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(q$,t,r)}static $(){return["CanvasShareAccessState|1 principals #0*|2 open_to_team 8|3 expected_state_token 9|4 owning_team_id 5|5 open_to_organization 8|6 organization_audience #1?",S$,B$]}}class B$ extends T{constructor(t){super(),this.label="",this.teams=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new B$).fromBinary(t,r)}static fromJson(t,r){return(new B$).fromJson(t,r)}static fromJsonString(t,r){return(new B$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(B$,t,r)}static $(){return["CanvasShareOrganizationAudience|1 label 9|2 teams #0*",I$]}}class I$ extends T{constructor(t){super(),this.teamId=0,this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new I$).fromBinary(t,r)}static fromJson(t,r){return(new I$).fromJson(t,r)}static fromJsonString(t,r){return(new I$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(I$,t,r)}static $(){return["CanvasShareAudienceTeam|1 team_id 5|2 name 9"]}}class P$ extends T{constructor(t){super(),this.storeId="",this.canvasId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new P$).fromBinary(t,r)}static fromJson(t,r){return(new P$).fromJson(t,r)}static fromJsonString(t,r){return(new P$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(P$,t,r)}static $(){return["GetCanvasShareAccessRequest|1 store_id 9|2 canvas_id 9"]}}class b$ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new b$).fromBinary(t,r)}static fromJson(t,r){return(new b$).fromJson(t,r)}static fromJsonString(t,r){return(new b$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(b$,t,r)}static $(){return["GetCanvasShareAccessResponse|1 state #0",q$]}}class R$ extends T{constructor(t){super(),this.storeId="",this.canvasId="",this.principals=[],this.expectedStateToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new R$).fromBinary(t,r)}static fromJson(t,r){return(new R$).fromJson(t,r)}static fromJsonString(t,r){return(new R$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(R$,t,r)}static $(){return["UpdateCanvasShareAccessRequest|1 store_id 9|2 canvas_id 9|3 principals #0*|4 expected_state_token 9|5 open_to_team 8?|6 open_to_organization 8?",S$]}}class v$ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new v$).fromBinary(t,r)}static fromJson(t,r){return(new v$).fromJson(t,r)}static fromJsonString(t,r){return(new v$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(v$,t,r)}static $(){return["UpdateCanvasShareAccessResponse|1 state #0",q$]}}class x$ extends T{constructor(t){super(),this.storeId="",this.canvasId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new x$).fromBinary(t,r)}static fromJson(t,r){return(new x$).fromJson(t,r)}static fromJsonString(t,r){return(new x$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(x$,t,r)}static $(){return["DeleteCanvasRequest|1 store_id 9|2 canvas_id 9"]}}class k$ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new k$).fromBinary(t,r)}static fromJson(t,r){return(new k$).fromJson(t,r)}static fromJsonString(t,r){return(new k$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(k$,t,r)}static $(){return["DeleteCanvasResponse"]}}class E$ extends T{constructor(t){super(),this.storeId="",this.canvasId="",this.title="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new E$).fromBinary(t,r)}static fromJson(t,r){return(new E$).fromJson(t,r)}static fromJsonString(t,r){return(new E$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(E$,t,r)}static $(){return["RenameCanvasRequest|1 store_id 9|2 canvas_id 9|3 title 9"]}}class C$ extends T{constructor(t){super(),this.title="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new C$).fromBinary(t,r)}static fromJson(t,r){return(new C$).fromJson(t,r)}static fromJsonString(t,r){return(new C$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(C$,t,r)}static $(){return["RenameCanvasResponse|1 title 9"]}}class T$ extends T{constructor(t){super(),this.conversationId="",this.title="",this.visibility=Re.UNSPECIFIED,this.messages=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new T$).fromBinary(t,r)}static fromJson(t,r){return(new T$).fromJson(t,r)}static fromJsonString(t,r){return(new T$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(T$,t,r)}static $(){return["ShareConversationRequest|1 conversation_id 9|2 title 9|3 visibility #0|4 messages #1*|5 latest_plan #2?",Re,_.hS,OA]}}class U$ extends T{constructor(t){super(),this.shareId="",this.shareUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new U$).fromBinary(t,r)}static fromJson(t,r){return(new U$).fromJson(t,r)}static fromJsonString(t,r){return(new U$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(U$,t,r)}static $(){return["ShareConversationResponse|1 share_id 9|2 share_url 9|3 redactions 5?"]}}class A$ extends T{constructor(t){super(),this.shareId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new A$).fromBinary(t,r)}static fromJson(t,r){return(new A$).fromJson(t,r)}static fromJsonString(t,r){return(new A$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(A$,t,r)}static $(){return["GetSharedConversationRequest|1 share_id 9"]}}class $$ extends T{constructor(t){super(),this.messages=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $$).fromBinary(t,r)}static fromJson(t,r){return(new $$).fromJson(t,r)}static fromJsonString(t,r){return(new $$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($$,t,r)}static $(){return["GetSharedConversationResponse|1 metadata #0|2 messages #1*|3 latest_plan #2?",MA,_.hS,OA]}}class M$ extends T{constructor(t){super(),this.visibilities=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new M$).fromBinary(t,r)}static fromJson(t,r){return(new M$).fromJson(t,r)}static fromJsonString(t,r){return(new M$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(M$,t,r)}static $(){return["ListSharedConversationsRequest|1 visibility #0?|2 creator_id 5?|3 created_before 9?|4 visibilities #0*|5 team_id 5?|6 conversation_id 9?|7 created_before_id 9?",Re]}}class O$ extends T{constructor(t){super(),this.shares=[],this.hasMore=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new O$).fromBinary(t,r)}static fromJson(t,r){return(new O$).fromJson(t,r)}static fromJsonString(t,r){return(new O$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(O$,t,r)}static $(){return["ListSharedConversationsResponse|1 shares #0*|2 has_more 8",MA]}}class D$ extends T{constructor(t){super(),this.shareId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new D$).fromBinary(t,r)}static fromJson(t,r){return(new D$).fromJson(t,r)}static fromJsonString(t,r){return(new D$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(D$,t,r)}static $(){return["DeleteSharedConversationRequest|1 share_id 9"]}}class N$ extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new N$).fromBinary(t,r)}static fromJson(t,r){return(new N$).fromJson(t,r)}static fromJsonString(t,r){return(new N$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(N$,t,r)}static $(){return["DeleteSharedConversationResponse|1 success 8"]}}class G$ extends T{constructor(t){super(),this.shareId="",this.visibility=Re.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new G$).fromBinary(t,r)}static fromJson(t,r){return(new G$).fromJson(t,r)}static fromJsonString(t,r){return(new G$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(G$,t,r)}static $(){return["UpdateSharedConversationVisibilityRequest|1 share_id 9|2 visibility #0",Re]}}class L$ extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new L$).fromBinary(t,r)}static fromJson(t,r){return(new L$).fromJson(t,r)}static fromJsonString(t,r){return(new L$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(L$,t,r)}static $(){return["UpdateSharedConversationVisibilityResponse|1 success 8"]}}class F$ extends T{constructor(t){super(),this.shareId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new F$).fromBinary(t,r)}static fromJson(t,r){return(new F$).fromJson(t,r)}static fromJsonString(t,r){return(new F$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(F$,t,r)}static $(){return["GetPublicSharedConversationRequest|1 share_id 9"]}}class K$ extends T{constructor(t){super(),this.messages=[],this.allowIndexing=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new K$).fromBinary(t,r)}static fromJson(t,r){return(new K$).fromJson(t,r)}static fromJsonString(t,r){return(new K$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(K$,t,r)}static $(){return["GetPublicSharedConversationResponse|1 metadata #0|2 messages #1*|3 allow_indexing 8|4 latest_plan #2?",MA,_.hS,OA]}}class z$ extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new z$).fromBinary(t,r)}static fromJson(t,r){return(new z$).fromJson(t,r)}static fromJsonString(t,r){return(new z$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(z$,t,r)}static $(){return["GetTeamSharedConversationSettingsRequest|1 team_id 5"]}}class j$ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new j$).fromBinary(t,r)}static fromJson(t,r){return(new j$).fromJson(t,r)}static fromJsonString(t,r){return(new j$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(j$,t,r)}static $(){return["GetTeamSharedConversationSettingsResponse|1 settings #0",$J]}}class H$ extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new H$).fromBinary(t,r)}static fromJson(t,r){return(new H$).fromJson(t,r)}static fromJsonString(t,r){return(new H$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(H$,t,r)}static $(){return["UpdateTeamSharedConversationSettingsRequest|1 team_id 5|2 settings #0",$J]}}class W$ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new W$).fromBinary(t,r)}static fromJson(t,r){return(new W$).fromJson(t,r)}static fromJsonString(t,r){return(new W$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(W$,t,r)}static $(){return["UpdateTeamSharedConversationSettingsResponse"]}}class Q$ extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Q$).fromBinary(t,r)}static fromJson(t,r){return(new Q$).fromJson(t,r)}static fromJsonString(t,r){return(new Q$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Q$,t,r)}static $(){return["SmartAutoSettings|1 enabled 8?|2 optimize_for #0?|3 show_routed_model 8?|4 router_model_grants #1?|5 router_model_pool #2?",Y$,V$,X$]}}class V$ extends T{constructor(t){super(),this.mcids=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new V$).fromBinary(t,r)}static fromJson(t,r){return(new V$).fromJson(t,r)}static fromJsonString(t,r){return(new V$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(V$,t,r)}static $(){return["RouterModelGrants|1 mcids 9*"]}}class X$ extends T{constructor(t){super(),this.type="",this.list=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new X$).fromBinary(t,r)}static fromJson(t,r){return(new X$).fromJson(t,r)}static fromJsonString(t,r){return(new X$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(X$,t,r)}static $(){return["RouterModelPool|1 type 9|2 list 9*"]}}class Y$ extends T{constructor(t){super(),this.allowedValues=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Y$).fromBinary(t,r)}static fromJson(t,r){return(new Y$).fromJson(t,r)}static fromJsonString(t,r){return(new Y$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Y$,t,r)}static $(){return["SmartAutoOptimizeForSettings|1 allowed_values 9*"]}}class Z$ extends T{constructor(t){super(),this.model=Ee.UNSPECIFIED,this.mode=Ce.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Z$).fromBinary(t,r)}static fromJson(t,r){return(new Z$).fromJson(t,r)}static fromJsonString(t,r){return(new Z$).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Z$,t,r)}static $(){return["ImposedModelPolicy|1 model #0|2 mode #1",Ee,Ce]}}class tM extends T{constructor(t){super(),this.modelId="",this.displayName="",this.severity=Te.UNSPECIFIED,this.blocked=!1,this.mcid="",this.routerGranted=!1,this.routerNickname="",this.routerProvider="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tM).fromBinary(t,r)}static fromJson(t,r){return(new tM).fromJson(t,r)}static fromJsonString(t,r){return(new tM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tM,t,r)}static $(){return["SmartAutoRequiredModel|1 model_id 9|2 display_name 9|3 severity #0|4 blocked 8|5 mcid 9|6 router_granted 8|7 router_nickname 9|8 router_provider 9",Te]}}class rM extends T{constructor(t){super(),this.teamNames=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rM).fromBinary(t,r)}static fromJson(t,r){return(new rM).fromJson(t,r)}static fromJsonString(t,r){return(new rM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rM,t,r)}static $(){return["SmartAutoMemberTeamConflict|1 model #0|2 team_names 9*",tM]}}class eM extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eM).fromBinary(t,r)}static fromJson(t,r){return(new eM).fromJson(t,r)}static fromJsonString(t,r){return(new eM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eM,t,r)}static $(){return["GetTeamSmartAutoSettingsRequest|1 team_id 5"]}}class nM extends T{constructor(t){super(),this.canEnable=!1,this.requiredModels=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nM).fromBinary(t,r)}static fromJson(t,r){return(new nM).fromJson(t,r)}static fromJsonString(t,r){return(new nM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nM,t,r)}static $(){return["GetTeamSmartAutoSettingsResponse|1 settings #0|2 can_enable 8|3 required_models #1*|4 new_chat_nudge_all_to_smart_auto 8?|5 models_auto_only 8?|6 new_chat_nudge_all_to_smart_auto_optimize_for 9?|7 imposed_model_policy #2",Q$,tM,Z$]}}class sM extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sM).fromBinary(t,r)}static fromJson(t,r){return(new sM).fromJson(t,r)}static fromJsonString(t,r){return(new sM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sM,t,r)}static $(){return["UpdateTeamSmartAutoSettingsRequest|1 team_id 5|2 settings #0|3 new_chat_nudge_all_to_smart_auto 8?|4 models_auto_only 8?|5 new_chat_nudge_all_to_smart_auto_optimize_for 9?|6 imposed_model_policy #1",Q$,Z$]}}class iM extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iM).fromBinary(t,r)}static fromJson(t,r){return(new iM).fromJson(t,r)}static fromJsonString(t,r){return(new iM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iM,t,r)}static $(){return["UpdateTeamSmartAutoSettingsResponse"]}}class oM extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oM).fromBinary(t,r)}static fromJson(t,r){return(new oM).fromJson(t,r)}static fromJsonString(t,r){return(new oM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oM,t,r)}static $(){return["GetTeamPromptCachingSettingsRequest|1 team_id 5"]}}class aM extends T{constructor(t){super(),this.claudeCacheTtl=Ue.UNSPECIFIED,this.canConfigure=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aM).fromBinary(t,r)}static fromJson(t,r){return(new aM).fromJson(t,r)}static fromJsonString(t,r){return(new aM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aM,t,r)}static $(){return["GetTeamPromptCachingSettingsResponse|1 claude_cache_ttl #0|2 can_configure 8",Ue]}}class uM extends T{constructor(t){super(),this.teamId=0,this.claudeCacheTtl=Ue.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uM).fromBinary(t,r)}static fromJson(t,r){return(new uM).fromJson(t,r)}static fromJsonString(t,r){return(new uM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uM,t,r)}static $(){return["UpdateTeamPromptCachingSettingsRequest|1 team_id 5|2 claude_cache_ttl #0",Ue]}}class cM extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cM).fromBinary(t,r)}static fromJson(t,r){return(new cM).fromJson(t,r)}static fromJsonString(t,r){return(new cM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cM,t,r)}static $(){return["UpdateTeamPromptCachingSettingsResponse"]}}class lM extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lM).fromBinary(t,r)}static fromJson(t,r){return(new lM).fromJson(t,r)}static fromJsonString(t,r){return(new lM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lM,t,r)}static $(){return["ResetTeamAgentRunModeToAutoReviewRequest|1 team_id 5"]}}class mM extends T{constructor(t){super(),this.issuedAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mM).fromBinary(t,r)}static fromJson(t,r){return(new mM).fromJson(t,r)}static fromJsonString(t,r){return(new mM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mM,t,r)}static $(){return["ResetTeamAgentRunModeToAutoReviewResponse|1 issued_at_ms 3"]}}class fM extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fM).fromBinary(t,r)}static fromJson(t,r){return(new fM).fromJson(t,r)}static fromJsonString(t,r){return(new fM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fM,t,r)}static $(){return["GetUserSmartAutoSettingsRequest"]}}class dM extends T{constructor(t){super(),this.canEnable=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dM).fromBinary(t,r)}static fromJson(t,r){return(new dM).fromJson(t,r)}static fromJsonString(t,r){return(new dM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dM,t,r)}static $(){return["GetUserSmartAutoSettingsResponse|1 settings #0|2 can_enable 8",Q$]}}class pM extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pM).fromBinary(t,r)}static fromJson(t,r){return(new pM).fromJson(t,r)}static fromJsonString(t,r){return(new pM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pM,t,r)}static $(){return["UpdateUserSmartAutoSettingsRequest|1 settings #0",Q$]}}class hM extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hM).fromBinary(t,r)}static fromJson(t,r){return(new hM).fromJson(t,r)}static fromJsonString(t,r){return(new hM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hM,t,r)}static $(){return["UpdateUserSmartAutoSettingsResponse|1 settings #0",Q$]}}class gM extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gM).fromBinary(t,r)}static fromJson(t,r){return(new gM).fromJson(t,r)}static fromJsonString(t,r){return(new gM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gM,t,r)}static $(){return["GetTeamSharedCanvasSettingsRequest|1 team_id 5"]}}class _M extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _M).fromBinary(t,r)}static fromJson(t,r){return(new _M).fromJson(t,r)}static fromJsonString(t,r){return(new _M).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_M,t,r)}static $(){return["GetTeamSharedCanvasSettingsResponse|1 settings #0",MJ]}}class JM extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new JM).fromBinary(t,r)}static fromJson(t,r){return(new JM).fromJson(t,r)}static fromJsonString(t,r){return(new JM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(JM,t,r)}static $(){return["UpdateTeamSharedCanvasSettingsRequest|1 team_id 5|2 settings #0",MJ]}}class wM extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wM).fromBinary(t,r)}static fromJson(t,r){return(new wM).fromJson(t,r)}static fromJsonString(t,r){return(new wM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wM,t,r)}static $(){return["UpdateTeamSharedCanvasSettingsResponse"]}}class yM extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yM).fromBinary(t,r)}static fromJson(t,r){return(new yM).fromJson(t,r)}static fromJsonString(t,r){return(new yM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yM,t,r)}static $(){return["GetTeamProjectsSettingsRequest|1 team_id 5"]}}class SM extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new SM).fromBinary(t,r)}static fromJson(t,r){return(new SM).fromJson(t,r)}static fromJsonString(t,r){return(new SM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(SM,t,r)}static $(){return["GetTeamProjectsSettingsResponse|1 settings #0",NJ]}}class qM extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qM).fromBinary(t,r)}static fromJson(t,r){return(new qM).fromJson(t,r)}static fromJsonString(t,r){return(new qM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qM,t,r)}static $(){return["UpdateTeamProjectsSettingsRequest|1 team_id 5|2 settings #0",NJ]}}class BM extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new BM).fromBinary(t,r)}static fromJson(t,r){return(new BM).fromJson(t,r)}static fromJsonString(t,r){return(new BM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(BM,t,r)}static $(){return["UpdateTeamProjectsSettingsResponse"]}}class IM extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new IM).fromBinary(t,r)}static fromJson(t,r){return(new IM).fromJson(t,r)}static fromJsonString(t,r){return(new IM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(IM,t,r)}static $(){return["GetTeamAppsSettingsRequest|1 team_id 5"]}}class PM extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new PM).fromBinary(t,r)}static fromJson(t,r){return(new PM).fromJson(t,r)}static fromJsonString(t,r){return(new PM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(PM,t,r)}static $(){return["GetTeamAppsSettingsResponse|1 settings #0|2 terms #1",GJ,bM]}}class bM extends T{constructor(t){super(),this.covered=!1,this.blockedPapered=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bM).fromBinary(t,r)}static fromJson(t,r){return(new bM).fromJson(t,r)}static fromJsonString(t,r){return(new bM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bM,t,r)}static $(){return["TeamAppsTerms|1 covered 8|2 terms_to_accept #0|3 blocked_papered 8",b]}}class RM extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new RM).fromBinary(t,r)}static fromJson(t,r){return(new RM).fromJson(t,r)}static fromJsonString(t,r){return(new RM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(RM,t,r)}static $(){return["UpdateTeamAppsSettingsRequest|1 team_id 5|2 settings #0|3 accepted_terms #1",GJ,R]}}class vM extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vM).fromBinary(t,r)}static fromJson(t,r){return(new vM).fromJson(t,r)}static fromJsonString(t,r){return(new vM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vM,t,r)}static $(){return["UpdateTeamAppsSettingsResponse"]}}class xM extends T{constructor(t){super(),this.id="",this.charCount=0,this.sha256Prefix="",this.createdByUserId=0,this.createdByName="",this.createdAtMs=n.protoInt64.zero,this.active=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xM).fromBinary(t,r)}static fromJson(t,r){return(new xM).fromJson(t,r)}static fromJsonString(t,r){return(new xM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xM,t,r)}static $(){return["TeamAppsReviewRulesVersion|1 id 9|2 char_count 5|3 sha256_prefix 9|4 created_by_user_id 5|5 created_by_name 9|6 created_at_ms 3|7 active 8"]}}class kM extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kM).fromBinary(t,r)}static fromJson(t,r){return(new kM).fromJson(t,r)}static fromJsonString(t,r){return(new kM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kM,t,r)}static $(){return["GetTeamAppsReviewRulesRequest|1 team_id 5"]}}class EM extends T{constructor(t){super(),this.rules="",this.maxChars=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new EM).fromBinary(t,r)}static fromJson(t,r){return(new EM).fromJson(t,r)}static fromJsonString(t,r){return(new EM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(EM,t,r)}static $(){return["GetTeamAppsReviewRulesResponse|1 active #0?|2 rules 9|3 max_chars 5",xM]}}class CM extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new CM).fromBinary(t,r)}static fromJson(t,r){return(new CM).fromJson(t,r)}static fromJsonString(t,r){return(new CM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(CM,t,r)}static $(){return["ListTeamAppsReviewRulesVersionsRequest|1 team_id 5"]}}class TM extends T{constructor(t){super(),this.versions=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new TM).fromBinary(t,r)}static fromJson(t,r){return(new TM).fromJson(t,r)}static fromJsonString(t,r){return(new TM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(TM,t,r)}static $(){return["ListTeamAppsReviewRulesVersionsResponse|1 versions #0*",xM]}}class UM extends T{constructor(t){super(),this.teamId=0,this.versionId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new UM).fromBinary(t,r)}static fromJson(t,r){return(new UM).fromJson(t,r)}static fromJsonString(t,r){return(new UM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(UM,t,r)}static $(){return["GetTeamAppsReviewRulesVersionRequest|1 team_id 5|2 version_id 9"]}}class AM extends T{constructor(t){super(),this.rules="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new AM).fromBinary(t,r)}static fromJson(t,r){return(new AM).fromJson(t,r)}static fromJsonString(t,r){return(new AM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(AM,t,r)}static $(){return["GetTeamAppsReviewRulesVersionResponse|1 version #0|2 rules 9",xM]}}class $M extends T{constructor(t){super(),this.teamId=0,this.rules="",this.expectedActiveVersionId="",this.acknowledgedWarnings=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $M).fromBinary(t,r)}static fromJson(t,r){return(new $M).fromJson(t,r)}static fromJsonString(t,r){return(new $M).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($M,t,r)}static $(){return["SaveTeamAppsReviewRulesRequest|1 team_id 5|2 rules 9|3 expected_active_version_id 9|4 acknowledged_warnings 8"]}}class MM extends T{constructor(t){super(),this.warnings=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new MM).fromBinary(t,r)}static fromJson(t,r){return(new MM).fromJson(t,r)}static fromJsonString(t,r){return(new MM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(MM,t,r)}static $(){return["SaveTeamAppsReviewRulesResponse|1 version #0?|2 warnings 9*",xM]}}class OM extends T{constructor(t){super(),this.teamId=0,this.versionId="",this.expectedActiveVersionId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new OM).fromBinary(t,r)}static fromJson(t,r){return(new OM).fromJson(t,r)}static fromJsonString(t,r){return(new OM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(OM,t,r)}static $(){return["ActivateTeamAppsReviewRulesVersionRequest|1 team_id 5|2 version_id 9|3 expected_active_version_id 9"]}}class DM extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new DM).fromBinary(t,r)}static fromJson(t,r){return(new DM).fromJson(t,r)}static fromJsonString(t,r){return(new DM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(DM,t,r)}static $(){return["ActivateTeamAppsReviewRulesVersionResponse|1 active #0?",xM]}}class NM extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new NM).fromBinary(t,r)}static fromJson(t,r){return(new NM).fromJson(t,r)}static fromJsonString(t,r){return(new NM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(NM,t,r)}static $(){return["GetTeamPublicProfileSettingsRequest|1 team_id 5"]}}class GM extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new GM).fromBinary(t,r)}static fromJson(t,r){return(new GM).fromJson(t,r)}static fromJsonString(t,r){return(new GM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(GM,t,r)}static $(){return["GetTeamPublicProfileSettingsResponse|1 settings #0",OJ]}}class LM extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new LM).fromBinary(t,r)}static fromJson(t,r){return(new LM).fromJson(t,r)}static fromJsonString(t,r){return(new LM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(LM,t,r)}static $(){return["UpdateTeamPublicProfileSettingsRequest|1 team_id 5|2 settings #0",OJ]}}class FM extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new FM).fromBinary(t,r)}static fromJson(t,r){return(new FM).fromJson(t,r)}static fromJsonString(t,r){return(new FM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(FM,t,r)}static $(){return["UpdateTeamPublicProfileSettingsResponse"]}}class KM extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new KM).fromBinary(t,r)}static fromJson(t,r){return(new KM).fromJson(t,r)}static fromJsonString(t,r){return(new KM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(KM,t,r)}static $(){return["GetTeamBackgroundAgentSettingsRequest|1 team_id 5"]}}class zM extends T{constructor(t){super(),this.grokBotCustomerHostedAvailable=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zM).fromBinary(t,r)}static fromJson(t,r){return(new zM).fromJson(t,r)}static fromJsonString(t,r){return(new zM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zM,t,r)}static $(){return["GetTeamBackgroundAgentSettingsResponse|1 settings #0|2 grok_bot_customer_hosted_available 8|3 cloud_agent_inference_hooks_available 8?|4 personal_machines_allowed 8?",cJ]}}class jM extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jM).fromBinary(t,r)}static fromJson(t,r){return(new jM).fromJson(t,r)}static fromJsonString(t,r){return(new jM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jM,t,r)}static $(){return["UpdateTeamBackgroundAgentSettingsRequest|1 team_id 5|2 settings #0",cJ]}}class HM extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new HM).fromBinary(t,r)}static fromJson(t,r){return(new HM).fromJson(t,r)}static fromJsonString(t,r){return(new HM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(HM,t,r)}static $(){return["UpdateTeamBackgroundAgentSettingsResponse"]}}class WM extends T{constructor(t){super(),this.id="",this.teamId=0,this.targetType="",this.targetScope="",this.thresholdCents=0,this.notificationMode="",this.enabled=!1,this.createdAt=n.protoInt64.zero,this.notifyAdminUserIds=[],this.notificationChannels=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new WM).fromBinary(t,r)}static fromJson(t,r){return(new WM).fromJson(t,r)}static fromJsonString(t,r){return(new WM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(WM,t,r)}static $(){return["UsageAlert|1 id 9|2 team_id 5|3 target_type 9|4 target_scope 9|5 threshold_cents 5|6 notification_mode 9|7 enabled 8|8 created_at 3|9 notify_all_admins 8?|10 notify_admin_user_ids 5*|11 notify_member 8?|12 group_id 5?|13 group_name 9?|14 threshold_type 9?|15 threshold_bps 5?|16 resource_threshold_id 9?|17 resource_threshold_cents 5?|18 resource_threshold_level 9?|19 notification_channels 9*|20 spend_bucket 9?"]}}class QM extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new QM).fromBinary(t,r)}static fromJson(t,r){return(new QM).fromJson(t,r)}static fromJsonString(t,r){return(new QM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(QM,t,r)}static $(){return["ListUsageAlertsRequest|1 team_id 5"]}}class VM extends T{constructor(t){super(),this.alerts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new VM).fromBinary(t,r)}static fromJson(t,r){return(new VM).fromJson(t,r)}static fromJsonString(t,r){return(new VM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(VM,t,r)}static $(){return["ListUsageAlertsResponse|1 alerts #0*",WM]}}class XM extends T{constructor(t){super(),this.teamId=0,this.targetType="",this.targetScope="",this.thresholdCents=[],this.notificationMode="",this.notifyAdminUserIds=[],this.thresholdBps=[],this.notificationChannels=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new XM).fromBinary(t,r)}static fromJson(t,r){return(new XM).fromJson(t,r)}static fromJsonString(t,r){return(new XM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(XM,t,r)}static $(){return["CreateUsageAlertsRequest|1 team_id 5|2 target_type 9|3 target_scope 9|4 threshold_cents 5*|5 notification_mode 9|6 notify_all_admins 8?|7 notify_admin_user_ids 5*|8 notify_member 8?|9 group_id 5?|10 threshold_type 9?|11 threshold_bps 5*|12 resource_threshold_cents 5?|13 resource_threshold_id 9?|14 resource_threshold_level 9?|15 notification_channels 9*|16 spend_bucket 9?"]}}class YM extends T{constructor(t){super(),this.createdAlerts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new YM).fromBinary(t,r)}static fromJson(t,r){return(new YM).fromJson(t,r)}static fromJsonString(t,r){return(new YM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(YM,t,r)}static $(){return["CreateUsageAlertsResponse|1 created_alerts #0*",WM]}}class ZM extends T{constructor(t){super(),this.teamId=0,this.alertIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ZM).fromBinary(t,r)}static fromJson(t,r){return(new ZM).fromJson(t,r)}static fromJsonString(t,r){return(new ZM).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ZM,t,r)}static $(){return["DeleteUsageAlertsRequest|1 team_id 5|2 alert_ids 9*"]}}class tO extends T{constructor(t){super(),this.deletedCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tO).fromBinary(t,r)}static fromJson(t,r){return(new tO).fromJson(t,r)}static fromJsonString(t,r){return(new tO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tO,t,r)}static $(){return["DeleteUsageAlertsResponse|1 deleted_count 5"]}}class rO extends T{constructor(t){super(),this.teamId=0,this.alertIds=[],this.notificationMode="",this.notifyAdminUserIds=[],this.notificationChannels=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rO).fromBinary(t,r)}static fromJson(t,r){return(new rO).fromJson(t,r)}static fromJsonString(t,r){return(new rO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rO,t,r)}static $(){return["UpdateUsageAlertsRequest|1 team_id 5|2 alert_ids 9*|3 notification_mode 9|4 notify_all_admins 8?|5 notify_admin_user_ids 5*|6 notify_member 8?|7 notification_channels 9*"]}}class eO extends T{constructor(t){super(),this.updatedCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eO).fromBinary(t,r)}static fromJson(t,r){return(new eO).fromJson(t,r)}static fromJsonString(t,r){return(new eO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eO,t,r)}static $(){return["UpdateUsageAlertsResponse|1 updated_count 5"]}}class nO extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nO).fromBinary(t,r)}static fromJson(t,r){return(new nO).fromJson(t,r)}static fromJsonString(t,r){return(new nO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nO,t,r)}static $(){return["RequestIndividualLimitsOptOutRequest"]}}class sO extends T{constructor(t){super(),this.teamResults=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sO).fromBinary(t,r)}static fromJson(t,r){return(new sO).fromJson(t,r)}static fromJsonString(t,r){return(new sO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sO,t,r)}static $(){return["RequestIndividualLimitsOptOutResponse|1 team_results #0*",iO]}}class iO extends T{constructor(t){super(),this.teamId=0,this.teamName="",this.outcome=Ae.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iO).fromBinary(t,r)}static fromJson(t,r){return(new iO).fromJson(t,r)}static fromJsonString(t,r){return(new iO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iO,t,r)}static $(){return["IndividualLimitsOptOutTeamResult|1 team_id 5|2 team_name 9|3 outcome #0",Ae]}}class oO extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oO).fromBinary(t,r)}static fromJson(t,r){return(new oO).fromJson(t,r)}static fromJsonString(t,r){return(new oO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oO,t,r)}static $(){return["ListSlackConversationsRequest|1 search 9?|2 include_private 8?|3 skip_cache 8?|4 allow_partial 8?"]}}class aO extends T{constructor(t){super(),this.conversations=[],this.hasSlackAuth=!1,this.isPartial=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aO).fromBinary(t,r)}static fromJson(t,r){return(new aO).fromJson(t,r)}static fromJsonString(t,r){return(new aO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aO,t,r)}static $(){return["ListSlackConversationsResponse|1 conversations #0*|2 has_slack_auth 8|3 is_partial 8",dO]}}class uO extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uO).fromBinary(t,r)}static fromJson(t,r){return(new uO).fromJson(t,r)}static fromJsonString(t,r){return(new uO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uO,t,r)}static $(){return["ListMicrosoftTeamsChannelsRequest|1 search 9?"]}}class cO extends T{constructor(t){super(),this.channels=[],this.hasMicrosoftTeamsAuth=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cO).fromBinary(t,r)}static fromJson(t,r){return(new cO).fromJson(t,r)}static fromJsonString(t,r){return(new cO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cO,t,r)}static $(){return["ListMicrosoftTeamsChannelsResponse|1 channels #0*|2 has_microsoft_teams_auth 8",lO]}}class lO extends T{constructor(t){super(),this.tenantId="",this.teamId="",this.teamDisplayName="",this.channelId="",this.displayName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lO).fromBinary(t,r)}static fromJson(t,r){return(new lO).fromJson(t,r)}static fromJsonString(t,r){return(new lO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lO,t,r)}static $(){return["MicrosoftTeamsChannel|1 tenant_id 9|2 team_id 9|3 team_display_name 9|4 channel_id 9|5 display_name 9|6 description 9?"]}}class mO extends T{constructor(t){super(),this.conversationIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mO).fromBinary(t,r)}static fromJson(t,r){return(new mO).fromJson(t,r)}static fromJsonString(t,r){return(new mO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mO,t,r)}static $(){return["GetSlackConversationsByIdsRequest|1 conversation_ids 9*"]}}class fO extends T{constructor(t){super(),this.conversations=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fO).fromBinary(t,r)}static fromJson(t,r){return(new fO).fromJson(t,r)}static fromJsonString(t,r){return(new fO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fO,t,r)}static $(){return["GetSlackConversationsByIdsResponse|1 conversations #0*",dO]}}class dO extends T{constructor(t){super(),this.id="",this.name="",this.type=$e.UNSPECIFIED,this.isPrivate=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dO).fromBinary(t,r)}static fromJson(t,r){return(new dO).fromJson(t,r)}static fromJsonString(t,r){return(new dO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dO,t,r)}static $(){return["SlackConversation|1 id 9|2 name 9|3 type #0|4 is_private 8|5 is_bot_in_channel 8?",$e]}}class pO extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pO).fromBinary(t,r)}static fromJson(t,r){return(new pO).fromJson(t,r)}static fromJsonString(t,r){return(new pO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pO,t,r)}static $(){return["SendDownloadEmailRequest"]}}class hO extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hO).fromBinary(t,r)}static fromJson(t,r){return(new hO).fromJson(t,r)}static fromJsonString(t,r){return(new hO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hO,t,r)}static $(){return["SendDownloadEmailResponse|1 success 8"]}}class gO extends T{constructor(t){super(),this.id=n.protoInt64.zero,this.name="",this.displayName="",this.isUserOwned=!1,this.isVerified=!1,this.createdAt=n.protoInt64.zero,this.updatedAt=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gO).fromBinary(t,r)}static fromJson(t,r){return(new gO).fromJson(t,r)}static fromJsonString(t,r){return(new gO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gO,t,r)}static $(){return["Publisher|1 id 3|2 name 9|3 display_name 9|4 description 9?|5 owner_user_id 5?|6 owner_team_id 5?|15 is_user_owned 8|7 is_verified 8|8 verified_at 3?|9 verified_domain 9?|10 logo_url 9?|11 website_url 9?|12 support_url 9?|13 created_at 3|14 updated_at 3"]}}class _O extends T{constructor(t){super(),this.pluginId=n.protoInt64.zero,this.directoryGroupIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _O).fromBinary(t,r)}static fromJson(t,r){return(new _O).fromJson(t,r)}static fromJsonString(t,r){return(new _O).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_O,t,r)}static $(){return["MarketplaceRequiredPluginInstall|1 plugin_id 3|2 directory_group_ids 3*"]}}class JO extends T{constructor(t){super(),this.id=n.protoInt64.zero,this.name="",this.gitUrl="",this.createdAt=n.protoInt64.zero,this.updatedAt=n.protoInt64.zero,this.requiredPluginInstalls=[],this.autoReindex=!1,this.isDefault=!1,this.allowUserPublish=!1,this.grokBotLinked=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new JO).fromBinary(t,r)}static fromJson(t,r){return(new JO).fromJson(t,r)}static fromJsonString(t,r){return(new JO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(JO,t,r)}static $(){return["Marketplace|1 id 3|2 name 9|3 display_name 9?|4 description 9?|5 git_url 9|6 git_ref 9?|7 user_id 5?|8 team_id 5?|9 logo_url 9?|10 created_at 3|11 updated_at 3|12 last_indexed_at 3?|13 last_indexed_commit_sha 9?|14 team_config #0?|15 required_plugin_installs #1*|16 auto_reindex 8|17 distribution_git_url 9?|18 is_default 8|19 allow_user_publish 8|20 grok_bot_linked 8",IG,_O]}}class wO extends T{constructor(t){super(),this.name="",this.environments=[],this.disabledEnvironments=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wO).fromBinary(t,r)}static fromJson(t,r){return(new wO).fromJson(t,r)}static fromJsonString(t,r){return(new wO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wO,t,r)}static $(){return["SkillDescriptor|1 name 9|2 description 9?|3 source_path 9?|4 source_url 9?|5 environments 9*|6 disabled_environments 9*|7 custom_mode #0?|8 display_name 9?|9 icon 9?|10 color 9?|11 content 9?|12 source_repo_url 9?",E.o7L]}}class yO extends T{constructor(t){super(),this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yO).fromBinary(t,r)}static fromJson(t,r){return(new yO).fromJson(t,r)}static fromJsonString(t,r){return(new yO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yO,t,r)}static $(){return["SubagentDescriptor|1 name 9|2 description 9?|3 source_path 9?|4 source_url 9?"]}}class SO extends T{constructor(t){super(),this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new SO).fromBinary(t,r)}static fromJson(t,r){return(new SO).fromJson(t,r)}static fromJsonString(t,r){return(new SO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(SO,t,r)}static $(){return["HookDescriptor|1 name 9|2 description 9?|3 source_path 9?|4 source_url 9?"]}}class qO extends T{constructor(t){super(),this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qO).fromBinary(t,r)}static fromJson(t,r){return(new qO).fromJson(t,r)}static fromJsonString(t,r){return(new qO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qO,t,r)}static $(){return["RuleDescriptor|1 name 9|2 description 9?|3 source_path 9?|4 source_url 9?"]}}class BO extends T{constructor(t){super(),this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new BO).fromBinary(t,r)}static fromJson(t,r){return(new BO).fromJson(t,r)}static fromJsonString(t,r){return(new BO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(BO,t,r)}static $(){return["McpDescriptor|1 name 9|2 description 9?|3 source_path 9?|4 source_url 9?"]}}class IO extends T{constructor(t){super(),this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new IO).fromBinary(t,r)}static fromJson(t,r){return(new IO).fromJson(t,r)}static fromJsonString(t,r){return(new IO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(IO,t,r)}static $(){return["CommandDescriptor|1 name 9|2 description 9?|3 source_path 9?|4 source_url 9?|5 source_repo_url 9?"]}}class PO extends T{constructor(t){super(),this.id=n.protoInt64.zero,this.name="",this.displayName="",this.description="",this.status=Me.UNSPECIFIED,this.tags=[],this.isPublished=!1,this.createdAt=n.protoInt64.zero,this.updatedAt=n.protoInt64.zero,this.isDeprecated=!1,this.gitUrl="",this.fullRef="",this.skills=[],this.subagents=[],this.hooks=[],this.rules=[],this.mcpServers=[],this.commands=[],this.curatedCategoryKeys=[],this.lifecycleState=Oe.UNSPECIFIED,this.publishedByUser=!1,this.teamMarketplaceConfiguredSecretNames=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new PO).fromBinary(t,r)}static fromJson(t,r){return(new PO).fromJson(t,r)}static fromJsonString(t,r){return(new PO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(PO,t,r)}static $(){return["Plugin|1 id 3|2 name 9|3 display_name 9|4 description 9|6 status #0|8 repository_url 9?|9 tags 9*|10 logo_url 9?|11 primary_color 9?|12 is_published 8|13 created_at 3|14 updated_at 3|16 publisher_id 3?|17 publisher #1?|18 is_deprecated 8|19 deprecation_message 9?|20 deprecated_at 3?|21 replaced_by_plugin_id 3?|22 marketplace_id 3?|23 marketplace #2?|24 git_url 9|25 git_ref 9?|26 git_path 9?|27 full_ref 9|28 skills #3*|29 subagents #4*|30 hooks #5*|31 rules #6*|32 mcp_servers #7*|33 commands #8*|34 release_repo 9?|35 release_asset 9?|36 release_tag 9?|37 curated_category_keys 9*|38 variables #9|39 team_marketplace_install_mode #10?|40 team_marketplace_configured_variables #9|41 lifecycle_state #11|42 min_client_versions #12?|43 published_by_user 8|44 popularity_rank 5?|45 team_admin_install_block_reason #13?|46 account_unavailable_reason #14?|47 sharepoint_install_block_detail #15?|48 team_marketplace_configured_secret_names 9*|49 backend_content #16?",Me,gO,JO,wO,yO,SO,qO,BO,IO,n.Struct,rn,Oe,bO,Ge,Ne,De,CN]}}class bO extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bO).fromBinary(t,r)}static fromJson(t,r){return(new bO).fromJson(t,r)}static fromJsonString(t,r){return(new bO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bO,t,r)}static $(){return["PluginMinClientVersions|1 cursor 9?|2 sand 9?|3 sand_mobile 9?"]}}class RO extends T{constructor(t){super(),this.userId=0,this.pluginId=n.protoInt64.zero,this.isEnabled=!1,this.createdAt=n.protoInt64.zero,this.updatedAt=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new RO).fromBinary(t,r)}static fromJson(t,r){return(new RO).fromJson(t,r)}static fromJsonString(t,r){return(new RO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(RO,t,r)}static $(){return["UserPluginInstall|1 user_id 5|2 plugin_id 3|4 is_enabled 8|6 created_at 3|7 updated_at 3|8 plugin #0|10 pinned_git_ref 9?",PO]}}class vO extends T{constructor(t){super(),this.teamId=0,this.pluginId=n.protoInt64.zero,this.isRequired=!1,this.createdAt=n.protoInt64.zero,this.updatedAt=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vO).fromBinary(t,r)}static fromJson(t,r){return(new vO).fromJson(t,r)}static fromJsonString(t,r){return(new vO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vO,t,r)}static $(){return["TeamPluginInstall|1 team_id 5|2 plugin_id 3|3 added_by_user_id 5?|4 is_required 8|6 created_at 3|7 updated_at 3|8 plugin #0|10 pinned_git_ref 9?",PO]}}class xO extends T{constructor(t){super(),this.tags=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xO).fromBinary(t,r)}static fromJson(t,r){return(new xO).fromJson(t,r)}static fromJsonString(t,r){return(new xO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xO,t,r)}static $(){return["ListMarketplacePluginsRequest|1 search 9?|2 tags 9*|3 page_size 5?|4 page_token 9?|5 marketplace_id 3?|6 publisher_id 3?|7 skip_team_admin_filter 8?|8 exclude_cloud_agent_plugins 8?|9 include_team_admin_blocked 8?|10 supports_backend_content 8?"]}}class kO extends T{constructor(t){super(),this.plugins=[],this.hasMore=!1,this.supersededPluginPopularityRanks={},this.teamAdminBlockedShown=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kO).fromBinary(t,r)}static fromJson(t,r){return(new kO).fromJson(t,r)}static fromJsonString(t,r){return(new kO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kO,t,r)}static $(){return["ListMarketplacePluginsResponse|1 plugins #0*|2 next_page_token 9?|3 has_more 8|4 superseded_plugin_popularity_ranks 9,5|5 team_admin_blocked_shown 8",PO]}}class EO extends T{constructor(t){super(),this.stage=Le.UNSPECIFIED,this.client=Fe.UNSPECIFIED,this.pluginIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new EO).fromBinary(t,r)}static fromJson(t,r){return(new EO).fromJson(t,r)}static fromJsonString(t,r){return(new EO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(EO,t,r)}static $(){return["RecordConnectorPolicyBlockedRequest|1 stage #0|2 client #1|3 plugin_ids 3*",Le,Fe]}}class CO extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new CO).fromBinary(t,r)}static fromJson(t,r){return(new CO).fromJson(t,r)}static fromJsonString(t,r){return(new CO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(CO,t,r)}static $(){return["RecordConnectorPolicyBlockedResponse"]}}class TO extends T{constructor(t){super(),this.publisherId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new TO).fromBinary(t,r)}static fromJson(t,r){return(new TO).fromJson(t,r)}static fromJsonString(t,r){return(new TO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(TO,t,r)}static $(){return["ListPublisherPublicPluginsRequest|1 publisher_id 3|2 page_size 5?|3 page_token 9?"]}}class UO extends T{constructor(t){super(),this.plugins=[],this.hasMore=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new UO).fromBinary(t,r)}static fromJson(t,r){return(new UO).fromJson(t,r)}static fromJsonString(t,r){return(new UO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(UO,t,r)}static $(){return["ListPublisherPublicPluginsResponse|1 plugins #0*|2 next_page_token 9?|3 has_more 8",PO]}}class AO extends T{constructor(t){super(),this.visibility="",this.links={},this.createdAt="",this.updatedAt="",this.badges=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new AO).fromBinary(t,r)}static fromJson(t,r){return(new AO).fromJson(t,r)}static fromJsonString(t,r){return(new AO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(AO,t,r)}static $(){return["UserProfile|1 handle 9?|2 visibility 9|3 links 9,9|4 created_at 9|5 updated_at 9|6 display_name 9?|7 avatar_url 9?|8 badges 9*|9 show_private_origin_contributions 8?"]}}class $O extends T{constructor(t){super(),this.date="",this.agentCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $O).fromBinary(t,r)}static fromJson(t,r){return(new $O).fromJson(t,r)}static fromJsonString(t,r){return(new $O).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($O,t,r)}static $(){return["PublicProfileDailyAgentCount|1 date 9|2 agent_count 5"]}}class MO extends T{constructor(t){super(),this.date="",this.count=0,this.value=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new MO).fromBinary(t,r)}static fromJson(t,r){return(new MO).fromJson(t,r)}static fromJsonString(t,r){return(new MO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(MO,t,r)}static $(){return["PublicProfileActivityCount|1 date 9|2 count 5|3 value 3"]}}class OO extends T{constructor(t){super(),this.date="",this.tokens=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new OO).fromBinary(t,r)}static fromJson(t,r){return(new OO).fromJson(t,r)}static fromJsonString(t,r){return(new OO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(OO,t,r)}static $(){return["PublicProfileTokensPerDay|1 date 9|2 tokens 3"]}}class DO extends T{constructor(t){super(),this.date="",this.localCount=0,this.cloudCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new DO).fromBinary(t,r)}static fromJson(t,r){return(new DO).fromJson(t,r)}static fromJsonString(t,r){return(new DO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(DO,t,r)}static $(){return["PublicProfileAgentsPerDay|1 date 9|2 local_count 5|3 cloud_count 5"]}}class NO extends T{constructor(t){super(),this.date="",this.pullRequests=0,this.reviews=0,this.commits=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new NO).fromBinary(t,r)}static fromJson(t,r){return(new NO).fromJson(t,r)}static fromJsonString(t,r){return(new NO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(NO,t,r)}static $(){return["PublicProfileOriginContributionsPerDay|1 date 9|2 pull_requests 5|3 reviews 5|4 commits 5"]}}class GO extends T{constructor(t){super(),this.days=[],this.activityYears=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new GO).fromBinary(t,r)}static fromJson(t,r){return(new GO).fromJson(t,r)}static fromJsonString(t,r){return(new GO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(GO,t,r)}static $(){return["PublicProfileOriginActivity|1 days #0*|2 activity_years 5*",NO]}}class LO extends T{constructor(t){super(),this.mostActiveMonth="",this.mostActiveDay="",this.longestStreak=0,this.currentStreak=0,this.activeDates=[],this.dailyAgentCounts=[],this.activityCounts=[],this.agentsLocal=0,this.agentsCloud=0,this.longestAgentSeconds=n.protoInt64.zero,this.tokensOverTime=[],this.agentsOverTime=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new LO).fromBinary(t,r)}static fromJson(t,r){return(new LO).fromJson(t,r)}static fromJsonString(t,r){return(new LO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(LO,t,r)}static $(){return["PublicProfileActivitySummary|1 most_active_month 9|2 most_active_day 9|3 longest_streak 5|4 current_streak 5|5 active_dates 9*|6 daily_agent_counts #0*|7 activity_counts #1*|10 agents_local 5|11 agents_cloud 5|12 longest_agent_seconds 3|13 tokens_over_time #2*|14 agents_over_time #3*|16 origin_activity #4",$O,MO,OO,DO,GO]}}class FO extends T{constructor(t){super(),this.includeActivitySummary=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new FO).fromBinary(t,r)}static fromJson(t,r){return(new FO).fromJson(t,r)}static fromJsonString(t,r){return(new FO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(FO,t,r)}static $(){return["GetUserProfileRequest|1 include_activity_summary 8"]}}class KO extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new KO).fromBinary(t,r)}static fromJson(t,r){return(new KO).fromJson(t,r)}static fromJsonString(t,r){return(new KO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(KO,t,r)}static $(){return["GetUserProfileResponse|1 profile #0?|3 activity_summary #1|4 public_visibility_allowed 8?|5 max_visibility 9?",AO,LO]}}class zO extends T{constructor(t){super(),this.links={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zO).fromBinary(t,r)}static fromJson(t,r){return(new zO).fromJson(t,r)}static fromJsonString(t,r){return(new zO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zO,t,r)}static $(){return["UpdateUserProfileRequest|1 visibility 9?|2 links 9,9|3 metadata #0?|4 show_private_origin_contributions 8?",n.Struct]}}class jO extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jO).fromBinary(t,r)}static fromJson(t,r){return(new jO).fromJson(t,r)}static fromJsonString(t,r){return(new jO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jO,t,r)}static $(){return["UpdateUserProfileResponse|1 profile #0",AO]}}class HO extends T{constructor(t){super(),this.handle="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new HO).fromBinary(t,r)}static fromJson(t,r){return(new HO).fromJson(t,r)}static fromJsonString(t,r){return(new HO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(HO,t,r)}static $(){return["ClaimUserProfileHandleRequest|1 handle 9"]}}class WO extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new WO).fromBinary(t,r)}static fromJson(t,r){return(new WO).fromJson(t,r)}static fromJsonString(t,r){return(new WO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(WO,t,r)}static $(){return["ClaimUserProfileHandleResponse|1 profile #0",AO]}}class QO extends T{constructor(t){super(),this.handle="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new QO).fromBinary(t,r)}static fromJson(t,r){return(new QO).fromJson(t,r)}static fromJsonString(t,r){return(new QO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(QO,t,r)}static $(){return["GetPublicProfileByHandleRequest|1 handle 9"]}}class VO extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new VO).fromBinary(t,r)}static fromJson(t,r){return(new VO).fromJson(t,r)}static fromJsonString(t,r){return(new VO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(VO,t,r)}static $(){return["GetPublicProfileByHandleResponse|1 profile #0|2 activity_summary #1",AO,LO]}}class XO extends T{constructor(t){super(),this.handle="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new XO).fromBinary(t,r)}static fromJson(t,r){return(new XO).fromJson(t,r)}static fromJsonString(t,r){return(new XO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(XO,t,r)}static $(){return["GetViewableProfileByHandleRequest|1 handle 9"]}}class YO extends T{constructor(t){super(),this.viewedAs="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new YO).fromBinary(t,r)}static fromJson(t,r){return(new YO).fromJson(t,r)}static fromJsonString(t,r){return(new YO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(YO,t,r)}static $(){return["GetViewableProfileByHandleResponse|1 profile #0|2 activity_summary #1|3 viewed_as 9",AO,LO]}}class ZO extends T{constructor(t){super(),this.handle="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ZO).fromBinary(t,r)}static fromJson(t,r){return(new ZO).fromJson(t,r)}static fromJsonString(t,r){return(new ZO).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ZO,t,r)}static $(){return["GetTeamMemberProfileByHandleRequest|1 handle 9"]}}class tD extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tD).fromBinary(t,r)}static fromJson(t,r){return(new tD).fromJson(t,r)}static fromJsonString(t,r){return(new tD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tD,t,r)}static $(){return["GetTeamMemberProfileByHandleResponse|1 profile #0|2 activity_summary #1",AO,LO]}}class rD extends T{constructor(t){super(),this.year=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rD).fromBinary(t,r)}static fromJson(t,r){return(new rD).fromJson(t,r)}static fromJsonString(t,r){return(new rD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rD,t,r)}static $(){return["GetProfileOriginContributionsRequest|1 handle 9?|2 year 5"]}}class eD extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eD).fromBinary(t,r)}static fromJson(t,r){return(new eD).fromJson(t,r)}static fromJsonString(t,r){return(new eD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eD,t,r)}static $(){return["GetProfileOriginContributionsResponse|1 origin_activity #0",GO]}}class nD extends T{constructor(t){super(),this.pluginId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nD).fromBinary(t,r)}static fromJson(t,r){return(new nD).fromJson(t,r)}static fromJsonString(t,r){return(new nD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nD,t,r)}static $(){return["GetPluginRequest|1 plugin_id 3|2 supports_backend_content 8?"]}}class sD extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sD).fromBinary(t,r)}static fromJson(t,r){return(new sD).fromJson(t,r)}static fromJsonString(t,r){return(new sD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sD,t,r)}static $(){return["GetPluginResponse|1 plugin #0|2 mcp_server_links #1?",PO,iD]}}class iD extends T{constructor(t){super(),this.servers=[],this.viewerIsTeamAdmin=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iD).fromBinary(t,r)}static fromJson(t,r){return(new iD).fromJson(t,r)}static fromJsonString(t,r){return(new iD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iD,t,r)}static $(){return["PluginMcpServerLinks|1 servers #0*|2 viewer_is_team_admin 8|3 manage_team_connectors_url 9?",oD]}}class oD extends T{constructor(t){super(),this.name="",this.description="",this.serverUrl="",this.state={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oD).fromBinary(t,r)}static fromJson(t,r){return(new oD).fromJson(t,r)}static fromJsonString(t,r){return(new oD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oD,t,r)}static $(){return["PluginMcpServerLink|1 name 9|2 description 9|3 server_url 9|4 ready #0 state|5 needs_connect #0 state|6 needs_reauth #0 state|7 disabled #0 state|8 ambiguous #1 state|9 not_approved #2 state|10 unknown #3 state|11 local #2 state|12 unusable #2 state|13 blocked_by_team_policy #0 state",aD,uD,lD,cD]}}class aD extends T{constructor(t){super(),this.connectorId="",this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aD).fromBinary(t,r)}static fromJson(t,r){return(new aD).fromJson(t,r)}static fromJsonString(t,r){return(new aD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aD,t,r)}static $(){return["PluginMcpServerLink.Connector|1 connector_id 9|2 name 9|3 server_identifier 9?"]}}class uD extends T{constructor(t){super(),this.connectors=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uD).fromBinary(t,r)}static fromJson(t,r){return(new uD).fromJson(t,r)}static fromJsonString(t,r){return(new uD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uD,t,r)}static $(){return["PluginMcpServerLink.Connectors|1 connectors #0*",aD]}}class cD extends T{constructor(t){super(),this.cause=Ke.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cD).fromBinary(t,r)}static fromJson(t,r){return(new cD).fromJson(t,r)}static fromJsonString(t,r){return(new cD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cD,t,r)}static $(){return["PluginMcpServerLink.Unknown|1 cause #0",Ke]}}class lD extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lD).fromBinary(t,r)}static fromJson(t,r){return(new lD).fromJson(t,r)}static fromJsonString(t,r){return(new lD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lD,t,r)}static $(){return["PluginMcpServerLink.Empty"]}}class mD extends T{constructor(t){super(),this.pluginId=n.protoInt64.zero,this.connectorId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mD).fromBinary(t,r)}static fromJson(t,r){return(new mD).fromJson(t,r)}static fromJsonString(t,r){return(new mD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mD,t,r)}static $(){return["StartPluginMcpConnectorSignInRequest|1 plugin_id 3|2 connector_id 9"]}}class fD extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fD).fromBinary(t,r)}static fromJson(t,r){return(new fD).fromJson(t,r)}static fromJsonString(t,r){return(new fD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fD,t,r)}static $(){return["StartPluginMcpConnectorSignInResponse|1 auth_url 9?"]}}class dD extends T{constructor(t){super(),this.name="",this.content="",this.environments=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dD).fromBinary(t,r)}static fromJson(t,r){return(new dD).fromJson(t,r)}static fromJsonString(t,r){return(new dD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dD,t,r)}static $(){return["TeamSkill|1 name 9|2 description 9?|3 content 9|4 source_path 9?|5 environments 9*"]}}class pD extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pD).fromBinary(t,r)}static fromJson(t,r){return(new pD).fromJson(t,r)}static fromJsonString(t,r){return(new pD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pD,t,r)}static $(){return["TeamSubagent"]}}class hD extends T{constructor(t){super(),this.name="",this.displayName="",this.description="",this.tags=[],this.inlineRules=[],this.inlineHooks=[],this.inlineCommands=[],this.mcpConfigJson="",this.inlineSkills=[],this.inlineSubagents=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hD).fromBinary(t,r)}static fromJson(t,r){return(new hD).fromJson(t,r)}static fromJsonString(t,r){return(new hD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hD,t,r)}static $(){return["CreatePluginRequest|2 name 9|3 display_name 9|4 description 9|5 tags 9*|6 git_url 9?|7 git_ref 9?|8 repository_url 9?|9 logo_url 9?|16 inline_rules #0*|17 inline_hooks #1*|18 inline_commands #2*|19 mcp_config_json 9|20 variables #3|21 inline_skills #4*|22 inline_subagents #5*|23 marketplace_id 3?|24 team_id 5?",fU,xU,OU,n.Struct,dD,pD]}}class gD extends T{constructor(t){super(),this.mcpServers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gD).fromBinary(t,r)}static fromJson(t,r){return(new gD).fromJson(t,r)}static fromJsonString(t,r){return(new gD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gD,t,r)}static $(){return["CreatePluginResponse|1 plugin #0|2 mcp_servers #1*",PO,qN]}}class _D extends T{constructor(t){super(),this.teamId=0,this.name="",this.displayName="",this.description="",this.pluginTarGz=new Uint8Array(0),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _D).fromBinary(t,r)}static fromJson(t,r){return(new _D).fromJson(t,r)}static fromJsonString(t,r){return(new _D).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_D,t,r)}static $(){return["PublishPluginRequest|1 team_id 5|2 name 9|3 display_name 9|4 description 9|5 plugin_tar_gz 12|6 commit_message 9?|7 expected_plugin_id 3?"]}}class JD extends T{constructor(t){super(),this.pluginId=n.protoInt64.zero,this.marketplaceId=n.protoInt64.zero,this.commitSha="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new JD).fromBinary(t,r)}static fromJson(t,r){return(new JD).fromJson(t,r)}static fromJsonString(t,r){return(new JD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(JD,t,r)}static $(){return["PublishPluginResponse|1 plugin_id 3|2 marketplace_id 3|3 commit_sha 9"]}}class wD extends T{constructor(t){super(),this.pluginId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wD).fromBinary(t,r)}static fromJson(t,r){return(new wD).fromJson(t,r)}static fromJsonString(t,r){return(new wD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wD,t,r)}static $(){return["UnpublishPluginRequest|1 plugin_id 3|2 team_id 5?|3 commit_message 9?|4 publisher_only 8?"]}}class yD extends T{constructor(t){super(),this.commitSha="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yD).fromBinary(t,r)}static fromJson(t,r){return(new yD).fromJson(t,r)}static fromJsonString(t,r){return(new yD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yD,t,r)}static $(){return["UnpublishPluginResponse|1 commit_sha 9"]}}class SD extends T{constructor(t){super(),this.gitUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new SD).fromBinary(t,r)}static fromJson(t,r){return(new SD).fromJson(t,r)}static fromJsonString(t,r){return(new SD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(SD,t,r)}static $(){return["ParseGitHubRepoForPluginRequest|1 git_url 9|2 git_ref 9?|3 enforce_auth 8?"]}}class qD extends T{constructor(t){super(),this.name="",this.displayName="",this.description="",this.gitPath="",this.skills=[],this.subagents=[],this.hooks=[],this.rules=[],this.mcpServers=[],this.commands=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qD).fromBinary(t,r)}static fromJson(t,r){return(new qD).fromJson(t,r)}static fromJsonString(t,r){return(new qD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qD,t,r)}static $(){return["ParsedPluginEntry|1 name 9|2 display_name 9|3 description 9|4 git_path 9|5 skills #0*|6 subagents #1*|7 hooks #2*|8 rules #3*|9 mcp_servers #4*|10 commands #5*|11 logo_url 9?|12 variables #6|13 source_git_url 9?|14 source_git_ref 9?|15 parse_error 9?|16 min_client_versions #7?",wO,yO,SO,qO,BO,IO,n.Struct,bO]}}class BD extends T{constructor(t){super(),this.marketplaceName="",this.marketplaceDescription="",this.defaultBranch="",this.repositoryUrl="",this.plugins=[],this.commitSha="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new BD).fromBinary(t,r)}static fromJson(t,r){return(new BD).fromJson(t,r)}static fromJsonString(t,r){return(new BD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(BD,t,r)}static $(){return["ParseGitHubRepoForPluginsResponse|1 marketplace_name 9|2 marketplace_description 9|3 default_branch 9|4 repository_url 9|5 plugins #0*|6 commit_sha 9",qD]}}class ID extends T{constructor(t){super(),this.gitUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ID).fromBinary(t,r)}static fromJson(t,r){return(new ID).fromJson(t,r)}static fromJsonString(t,r){return(new ID).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ID,t,r)}static $(){return["ParsePluginPublisherRepoInternalRequest|1 git_url 9|2 git_ref 9?|3 release_tag 9?|4 release_asset 9?"]}}class PD extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new PD).fromBinary(t,r)}static fromJson(t,r){return(new PD).fromJson(t,r)}static fromJsonString(t,r){return(new PD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(PD,t,r)}static $(){return["ParsePluginPublisherRepoInternalResponse|1 parsed_repo #0|2 release_repo 9?|3 release_asset 9?|4 release_tag 9?",BD]}}class bD extends T{constructor(t){super(),this.type="",this.added=[],this.removed=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bD).fromBinary(t,r)}static fromJson(t,r){return(new bD).fromJson(t,r)}static fromJsonString(t,r){return(new bD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bD,t,r)}static $(){return["ReindexComponentDiff|1 type 9|2 added 9*|3 removed 9*"]}}class RD extends T{constructor(t){super(),this.name="",this.displayName="",this.status="",this.componentChanges=[],this.metadataChanges=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new RD).fromBinary(t,r)}static fromJson(t,r){return(new RD).fromJson(t,r)}static fromJsonString(t,r){return(new RD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(RD,t,r)}static $(){return["ReindexPluginDiff|1 name 9|2 display_name 9|3 status 9|4 component_changes #0*|5 metadata_changes 9*",bD]}}class vD extends T{constructor(t){super(),this.newPlugins=0,this.removedPlugins=0,this.updatedPlugins=0,this.unchangedPlugins=0,this.totalNewComponents=0,this.totalRemovedComponents=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vD).fromBinary(t,r)}static fromJson(t,r){return(new vD).fromJson(t,r)}static fromJsonString(t,r){return(new vD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vD,t,r)}static $(){return["ReindexSummary|1 new_plugins 5|2 removed_plugins 5|3 updated_plugins 5|4 unchanged_plugins 5|5 total_new_components 5|6 total_removed_components 5"]}}class xD extends T{constructor(t){super(),this.publisherName="",this.gitUrl="",this.gitRef="",this.commitSha="",this.pluginDiffs=[],this.newCommitCount=0,this.conflictingNames=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xD).fromBinary(t,r)}static fromJson(t,r){return(new xD).fromJson(t,r)}static fromJsonString(t,r){return(new xD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xD,t,r)}static $(){return["PreviewReindexPluginRepoResponse|1 publisher_name 9|2 git_url 9|3 git_ref 9|4 commit_sha 9|5 plugin_diffs #0*|6 summary #1|7 new_commit_count 5|8 conflicting_names 9*",RD,vD]}}class kD extends T{constructor(t){super(),this.publisherId=n.protoInt64.zero,this.gitUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kD).fromBinary(t,r)}static fromJson(t,r){return(new kD).fromJson(t,r)}static fromJsonString(t,r){return(new kD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kD,t,r)}static $(){return["PreviewReindexPluginRepoInternalRequest|1 publisher_id 3|2 git_url 9|3 git_ref 9?|4 pinned_git_ref 9?|5 release_tag 9?"]}}class ED extends T{constructor(t){super(),this.publisherId=n.protoInt64.zero,this.gitUrl="",this.deprecateRemoved=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ED).fromBinary(t,r)}static fromJson(t,r){return(new ED).fromJson(t,r)}static fromJsonString(t,r){return(new ED).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ED,t,r)}static $(){return["ApplyReindexPluginRepoInternalRequest|1 publisher_id 3|2 git_url 9|3 git_ref 9?|4 deprecate_removed 8|5 release_tag 9?"]}}class CD extends T{constructor(t){super(),this.createdCount=0,this.updatedCount=0,this.deprecatedCount=0,this.createdPluginNames=[],this.updatedPluginNames=[],this.deprecatedPluginNames=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new CD).fromBinary(t,r)}static fromJson(t,r){return(new CD).fromJson(t,r)}static fromJsonString(t,r){return(new CD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(CD,t,r)}static $(){return["ApplyReindexPluginRepoResponse|1 created_count 5|2 updated_count 5|3 deprecated_count 5|4 created_plugin_names 9*|5 updated_plugin_names 9*|6 deprecated_plugin_names 9*"]}}class TD extends T{constructor(t){super(),this.marketplaceId=n.protoInt64.zero,this.distributionGitUrl="",this.originRepoUuid="",this.acknowledgeDistributionRisk=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new TD).fromBinary(t,r)}static fromJson(t,r){return(new TD).fromJson(t,r)}static fromJsonString(t,r){return(new TD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(TD,t,r)}static $(){return["UpdateTeamMarketplaceOriginDistributionInternalRequest|1 marketplace_id 3|2 distribution_git_url 9|3 origin_repo_uuid 9|4 acknowledge_distribution_risk 8"]}}class UD extends T{constructor(t){super(),this.changed=!1,this.distributionGitUrl="",this.originRepoUuid="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new UD).fromBinary(t,r)}static fromJson(t,r){return(new UD).fromJson(t,r)}static fromJsonString(t,r){return(new UD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(UD,t,r)}static $(){return["UpdateTeamMarketplaceOriginDistributionInternalResponse|1 changed 8|2 distribution_git_url 9|3 origin_repo_uuid 9"]}}class AD extends T{constructor(t){super(),this.cursorUserId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new AD).fromBinary(t,r)}static fromJson(t,r){return(new AD).fromJson(t,r)}static fromJsonString(t,r){return(new AD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(AD,t,r)}static $(){return["GetUserServedPlanInternalRequest|1 cursor_user_id 3"]}}class $D extends T{constructor(t){super(),this.kind=ze.UNSPECIFIED,this.membershipType="",this.target="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $D).fromBinary(t,r)}static fromJson(t,r){return(new $D).fromJson(t,r)}static fromJsonString(t,r){return(new $D).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($D,t,r)}static $(){return["GetUserServedPlanInternalResponse|1 kind #0|2 membership_type 9|3 target 9|4 team_id 3?|5 merged_team_seat_tier 9?",ze]}}class MD extends T{constructor(t){super(),this.publisherId=n.protoInt64.zero,this.fromGitUrl="",this.toGitUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new MD).fromBinary(t,r)}static fromJson(t,r){return(new MD).fromJson(t,r)}static fromJsonString(t,r){return(new MD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(MD,t,r)}static $(){return["PreviewMigrateReindexPluginRepoInternalRequest|1 publisher_id 3|2 from_git_url 9|3 to_git_url 9|4 git_ref 9?|5 release_tag 9?"]}}class OD extends T{constructor(t){super(),this.publisherName="",this.fromGitUrl="",this.toGitUrl="",this.gitUrl="",this.gitRef="",this.commitSha="",this.pluginDiffs=[],this.conflictingNames=[],this.targetRepoNameConflicts=[],this.deprecatedSourceNameConflicts=[],this.canApply=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new OD).fromBinary(t,r)}static fromJson(t,r){return(new OD).fromJson(t,r)}static fromJsonString(t,r){return(new OD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(OD,t,r)}static $(){return["PreviewMigrateReindexPluginRepoResponse|1 publisher_name 9|2 from_git_url 9|3 to_git_url 9|4 git_url 9|5 git_ref 9|6 commit_sha 9|7 plugin_diffs #0*|8 summary #1|9 conflicting_names 9*|10 target_repo_name_conflicts 9*|11 deprecated_source_name_conflicts 9*|12 can_apply 8",RD,vD]}}class DD extends T{constructor(t){super(),this.publisherId=n.protoInt64.zero,this.fromGitUrl="",this.toGitUrl="",this.deprecateRemoved=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new DD).fromBinary(t,r)}static fromJson(t,r){return(new DD).fromJson(t,r)}static fromJsonString(t,r){return(new DD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(DD,t,r)}static $(){return["ApplyMigrateReindexPluginRepoInternalRequest|1 publisher_id 3|2 from_git_url 9|3 to_git_url 9|4 git_ref 9?|5 release_tag 9?|6 deprecate_removed 8"]}}class ND extends T{constructor(t){super(),this.migratedCount=0,this.createdCount=0,this.updatedCount=0,this.deprecatedCount=0,this.createdPluginNames=[],this.updatedPluginNames=[],this.deprecatedPluginNames=[],this.toGitUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ND).fromBinary(t,r)}static fromJson(t,r){return(new ND).fromJson(t,r)}static fromJsonString(t,r){return(new ND).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ND,t,r)}static $(){return["ApplyMigrateReindexPluginRepoResponse|1 migrated_count 5|2 created_count 5|3 updated_count 5|4 deprecated_count 5|5 created_plugin_names 9*|6 updated_plugin_names 9*|7 deprecated_plugin_names 9*|8 to_git_url 9"]}}class GD extends T{constructor(t){super(),this.targetUserId=n.protoInt64.zero,this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new GD).fromBinary(t,r)}static fromJson(t,r){return(new GD).fromJson(t,r)}static fromJsonString(t,r){return(new GD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(GD,t,r)}static $(){return["CreateSupportImpersonationSessionInternalRequest|1 target_user_id 3|2 reason 9"]}}class LD extends T{constructor(t){super(),this.redemptionCode="",this.targetEmail="",this.targetAuthId="",this.redemptionExpiresAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new LD).fromBinary(t,r)}static fromJson(t,r){return(new LD).fromJson(t,r)}static fromJsonString(t,r){return(new LD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(LD,t,r)}static $(){return["CreateSupportImpersonationSessionInternalResponse|1 redemption_code 9|2 target_email 9|3 target_auth_id 9|4 redemption_expires_at_ms 3"]}}class FD extends T{constructor(t){super(),this.targetUserId=n.protoInt64.zero,this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new FD).fromBinary(t,r)}static fromJson(t,r){return(new FD).fromJson(t,r)}static fromJsonString(t,r){return(new FD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(FD,t,r)}static $(){return["RevokeSupportImpersonationSessionsInternalRequest|1 target_user_id 3|2 reason 9"]}}class KD extends T{constructor(t){super(),this.revokedCount=0,this.targetAuthId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new KD).fromBinary(t,r)}static fromJson(t,r){return(new KD).fromJson(t,r)}static fromJsonString(t,r){return(new KD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(KD,t,r)}static $(){return["RevokeSupportImpersonationSessionsInternalResponse|1 revoked_count 5|2 target_auth_id 9"]}}class zD extends T{constructor(t){super(),this.organizationPublicId="",this.userId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zD).fromBinary(t,r)}static fromJson(t,r){return(new zD).fromJson(t,r)}static fromJsonString(t,r){return(new zD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zD,t,r)}static $(){return["RemoveOrganizationMemberInternalRequest|1 organization_public_id 9|2 user_id 5"]}}class jD extends T{constructor(t){super(),this.removed=!1,this.removedTeamIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jD).fromBinary(t,r)}static fromJson(t,r){return(new jD).fromJson(t,r)}static fromJsonString(t,r){return(new jD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jD,t,r)}static $(){return["RemoveOrganizationMemberInternalResponse|1 removed 8|2 removed_team_ids 5*"]}}class HD extends T{constructor(t){super(),this.organizationPublicId="",this.teamId=0,this.ownerUserId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new HD).fromBinary(t,r)}static fromJson(t,r){return(new HD).fromJson(t,r)}static fromJsonString(t,r){return(new HD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(HD,t,r)}static $(){return["LinkOrganizationTeamToXaiInternalRequest|1 organization_public_id 9|2 team_id 5|3 owner_user_id 5"]}}class WD extends T{constructor(t){super(),this.outcome=je.UNSPECIFIED,this.xaiTeamId="",this.enterprise="",this.step="",this.xaiStatus=0,this.wellKnownCode="",this.code="",this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new WD).fromBinary(t,r)}static fromJson(t,r){return(new WD).fromJson(t,r)}static fromJsonString(t,r){return(new WD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(WD,t,r)}static $(){return["LinkOrganizationTeamToXaiInternalResponse|1 outcome #0|2 xai_team_id 9|3 enterprise 9|4 step 9|5 xai_status 5|6 well_known_code 9|7 code 9|8 message 9",je]}}class QD extends T{constructor(t){super(),this.pluginId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new QD).fromBinary(t,r)}static fromJson(t,r){return(new QD).fromJson(t,r)}static fromJsonString(t,r){return(new QD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(QD,t,r)}static $(){return["SubmitPluginForApprovalRequest|1 plugin_id 3"]}}class VD extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new VD).fromBinary(t,r)}static fromJson(t,r){return(new VD).fromJson(t,r)}static fromJsonString(t,r){return(new VD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(VD,t,r)}static $(){return["SubmitPluginForApprovalResponse|1 plugin #0",PO]}}class XD extends T{constructor(t){super(),this.pluginId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new XD).fromBinary(t,r)}static fromJson(t,r){return(new XD).fromJson(t,r)}static fromJsonString(t,r){return(new XD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(XD,t,r)}static $(){return["ApprovePluginRequest|1 plugin_id 3"]}}class YD extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new YD).fromBinary(t,r)}static fromJson(t,r){return(new YD).fromJson(t,r)}static fromJsonString(t,r){return(new YD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(YD,t,r)}static $(){return["ApprovePluginResponse|1 plugin #0",PO]}}class ZD extends T{constructor(t){super(),this.pluginId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ZD).fromBinary(t,r)}static fromJson(t,r){return(new ZD).fromJson(t,r)}static fromJsonString(t,r){return(new ZD).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ZD,t,r)}static $(){return["RejectPluginRequest|1 plugin_id 3|2 reason 9?"]}}class tN extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tN).fromBinary(t,r)}static fromJson(t,r){return(new tN).fromJson(t,r)}static fromJsonString(t,r){return(new tN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tN,t,r)}static $(){return["RejectPluginResponse|1 plugin #0",PO]}}class rN extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rN).fromBinary(t,r)}static fromJson(t,r){return(new rN).fromJson(t,r)}static fromJsonString(t,r){return(new rN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rN,t,r)}static $(){return["ListUserPluginInstallsRequest|1 use_replica 8?"]}}class eN extends T{constructor(t){super(),this.installs=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eN).fromBinary(t,r)}static fromJson(t,r){return(new eN).fromJson(t,r)}static fromJsonString(t,r){return(new eN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eN,t,r)}static $(){return["ListUserPluginInstallsResponse|1 installs #0*",RO]}}class nN extends T{constructor(t){super(),this.pluginId=n.protoInt64.zero,this.allowMissingSecrets=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nN).fromBinary(t,r)}static fromJson(t,r){return(new nN).fromJson(t,r)}static fromJsonString(t,r){return(new nN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nN,t,r)}static $(){return["InstallUserPluginRequest|1 plugin_id 3|4 pinned_git_ref 9?|5 variables #0|6 allow_missing_secrets 8|7 supports_backend_content 8?",n.Struct]}}class sN extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sN).fromBinary(t,r)}static fromJson(t,r){return(new sN).fromJson(t,r)}static fromJsonString(t,r){return(new sN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sN,t,r)}static $(){return["InstallUserPluginResponse|1 install #0",RO]}}class iN extends T{constructor(t){super(),this.pluginId=n.protoInt64.zero,this.mergeWithStored=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iN).fromBinary(t,r)}static fromJson(t,r){return(new iN).fromJson(t,r)}static fromJsonString(t,r){return(new iN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iN,t,r)}static $(){return["UpdateUserPluginInstallRequest|1 plugin_id 3|3 is_enabled 8?|5 pinned_git_ref 9?|6 variables #0|7 merge_with_stored 8",n.Struct]}}class oN extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oN).fromBinary(t,r)}static fromJson(t,r){return(new oN).fromJson(t,r)}static fromJsonString(t,r){return(new oN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oN,t,r)}static $(){return["UpdateUserPluginInstallResponse|1 install #0",RO]}}class aN extends T{constructor(t){super(),this.pluginId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aN).fromBinary(t,r)}static fromJson(t,r){return(new aN).fromJson(t,r)}static fromJsonString(t,r){return(new aN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aN,t,r)}static $(){return["UninstallUserPluginRequest|1 plugin_id 3"]}}class uN extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uN).fromBinary(t,r)}static fromJson(t,r){return(new uN).fromJson(t,r)}static fromJsonString(t,r){return(new uN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uN,t,r)}static $(){return["UninstallUserPluginResponse|1 success 8"]}}class cN extends T{constructor(t){super(),this.pluginId=n.protoInt64.zero,this.memberInstallCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cN).fromBinary(t,r)}static fromJson(t,r){return(new cN).fromJson(t,r)}static fromJsonString(t,r){return(new cN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cN,t,r)}static $(){return["TeamPluginPopularityCount|1 plugin_id 3|2 member_install_count 5"]}}class lN extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lN).fromBinary(t,r)}static fromJson(t,r){return(new lN).fromJson(t,r)}static fromJsonString(t,r){return(new lN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lN,t,r)}static $(){return["GetTeamPluginPopularityRequest|1 team_id 5|2 use_replica 8?"]}}class mN extends T{constructor(t){super(),this.counts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mN).fromBinary(t,r)}static fromJson(t,r){return(new mN).fromJson(t,r)}static fromJsonString(t,r){return(new mN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mN,t,r)}static $(){return["GetTeamPluginPopularityResponse|1 counts #0*",cN]}}class fN extends T{constructor(t){super(),this.teamId=0,this.primitiveType=He.UNSPECIFIED,this.interval=We.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fN).fromBinary(t,r)}static fromJson(t,r){return(new fN).fromJson(t,r)}static fromJsonString(t,r){return(new fN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fN,t,r)}static $(){return["GetTeamPluginPrimitiveUsageRequest|1 team_id 5|2 primitive_type #0|3 interval #1|4 limit 5?|5 page_number 5?",He,We]}}class dN extends T{constructor(t){super(),this.primitiveName="",this.pluginId=n.protoInt64.zero,this.primitiveType=He.UNSPECIFIED,this.usageCount=n.protoInt64.zero,this.humanUsageCount=n.protoInt64.zero,this.agentUsageCount=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dN).fromBinary(t,r)}static fromJson(t,r){return(new dN).fromJson(t,r)}static fromJsonString(t,r){return(new dN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dN,t,r)}static $(){return["TeamPluginPrimitiveUsageRow|1 primitive_name 9|2 plugin_id 3|3 primitive_type #0|4 usage_count 4|5 human_usage_count 4|6 agent_usage_count 4",He]}}class pN extends T{constructor(t){super(),this.rows=[],this.hasMore=!1,this.pageSize=0,this.pageNumber=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pN).fromBinary(t,r)}static fromJson(t,r){return(new pN).fromJson(t,r)}static fromJsonString(t,r){return(new pN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pN,t,r)}static $(){return["GetTeamPluginPrimitiveUsageResponse|1 rows #0*|2 has_more 8|3 page_size 5|4 page_number 5",dN]}}class hN extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hN).fromBinary(t,r)}static fromJson(t,r){return(new hN).fromJson(t,r)}static fromJsonString(t,r){return(new hN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hN,t,r)}static $(){return["ListTeamAvailableMarketplacePluginsRequest|1 team_id 5|2 search 9?|3 page_size 5?|4 page_token 9?|5 sort_by_team_popularity 8?|6 offset 5?"]}}class gN extends T{constructor(t){super(),this.plugins=[],this.hasMore=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gN).fromBinary(t,r)}static fromJson(t,r){return(new gN).fromJson(t,r)}static fromJsonString(t,r){return(new gN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gN,t,r)}static $(){return["ListTeamAvailableMarketplacePluginsResponse|1 plugins #0*|2 next_page_token 9?|3 has_more 8|4 total_count 5?",PO]}}class _N extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _N).fromBinary(t,r)}static fromJson(t,r){return(new _N).fromJson(t,r)}static fromJsonString(t,r){return(new _N).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_N,t,r)}static $(){return["GetTeamPinnedMarketplacePluginsRequest|1 team_id 5"]}}class JN extends T{constructor(t){super(),this.plugins=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new JN).fromBinary(t,r)}static fromJson(t,r){return(new JN).fromJson(t,r)}static fromJsonString(t,r){return(new JN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(JN,t,r)}static $(){return["GetTeamPinnedMarketplacePluginsResponse|1 plugins #0*",PO]}}class wN extends T{constructor(t){super(),this.teamId=0,this.pluginIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wN).fromBinary(t,r)}static fromJson(t,r){return(new wN).fromJson(t,r)}static fromJsonString(t,r){return(new wN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wN,t,r)}static $(){return["UpdateTeamPinnedMarketplacePluginsRequest|1 team_id 5|2 plugin_ids 3*"]}}class yN extends T{constructor(t){super(),this.plugins=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yN).fromBinary(t,r)}static fromJson(t,r){return(new yN).fromJson(t,r)}static fromJsonString(t,r){return(new yN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yN,t,r)}static $(){return["UpdateTeamPinnedMarketplacePluginsResponse|1 plugins #0*",PO]}}class SN extends T{constructor(t){super(),this.teamId=0,this.pluginId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new SN).fromBinary(t,r)}static fromJson(t,r){return(new SN).fromJson(t,r)}static fromJsonString(t,r){return(new SN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(SN,t,r)}static $(){return["InstallTeamPluginRequest|1 team_id 5|2 plugin_id 3|4 is_required 8?|5 pinned_git_ref 9?"]}}class qN extends T{constructor(t){super(),this.serverId=n.protoInt64.zero,this.name="",this.type="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qN).fromBinary(t,r)}static fromJson(t,r){return(new qN).fromJson(t,r)}static fromJsonString(t,r){return(new qN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qN,t,r)}static $(){return["TeamPluginMcpServer|1 server_id 3|2 name 9|3 type 9|4 local #0|5 cloud #0",BN]}}class BN extends T{constructor(t){super(),this.blocked=!1,this.blockedBy=Qe.UNSPECIFIED,this.byOffRule=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new BN).fromBinary(t,r)}static fromJson(t,r){return(new BN).fromJson(t,r)}static fromJsonString(t,r){return(new BN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(BN,t,r)}static $(){return["McpServerAddSurfaceCheck|1 blocked 8|2 blocked_by #0|3 by_off_rule 8",Qe]}}class IN extends T{constructor(t){super(),this.mcpServers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new IN).fromBinary(t,r)}static fromJson(t,r){return(new IN).fromJson(t,r)}static fromJsonString(t,r){return(new IN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(IN,t,r)}static $(){return["InstallTeamPluginResponse|1 install #0|2 mcp_servers #1*",vO,qN]}}class PN extends T{constructor(t){super(),this.teamId=0,this.pluginId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new PN).fromBinary(t,r)}static fromJson(t,r){return(new PN).fromJson(t,r)}static fromJsonString(t,r){return(new PN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(PN,t,r)}static $(){return["UpdateTeamPluginInstallRequest|1 team_id 5|2 plugin_id 3|4 is_required 8?|5 pinned_git_ref 9?"]}}class bN extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bN).fromBinary(t,r)}static fromJson(t,r){return(new bN).fromJson(t,r)}static fromJsonString(t,r){return(new bN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bN,t,r)}static $(){return["UpdateTeamPluginInstallResponse|1 install #0",vO]}}class RN extends T{constructor(t){super(),this.teamId=0,this.pluginId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new RN).fromBinary(t,r)}static fromJson(t,r){return(new RN).fromJson(t,r)}static fromJsonString(t,r){return(new RN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(RN,t,r)}static $(){return["UninstallTeamPluginRequest|1 team_id 5|2 plugin_id 3"]}}class vN extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vN).fromBinary(t,r)}static fromJson(t,r){return(new vN).fromJson(t,r)}static fromJsonString(t,r){return(new vN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vN,t,r)}static $(){return["UninstallTeamPluginResponse|1 success 8"]}}class xN extends T{constructor(t){super(),this.excludeConfiguredVariables=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xN).fromBinary(t,r)}static fromJson(t,r){return(new xN).fromJson(t,r)}static fromJsonString(t,r){return(new xN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xN,t,r)}static $(){return["GetEffectiveUserPluginsRequest|1 use_replica 8?|2 team_id 5?|4 exclude_configured_variables 8|5 supports_backend_content 8?"]}}class kN extends T{constructor(t){super(),this.isTeamRequired=!1,this.isEnabled=!1,this.hasTeamConfiguredVariables=!1,this.installMode=Ve.UNSPECIFIED,this.configuredVariableKeys=[],this.servedBy=tt.UNSPECIFIED,this.viewerCanUnpublish=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kN).fromBinary(t,r)}static fromJson(t,r){return(new kN).fromJson(t,r)}static fromJsonString(t,r){return(new kN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kN,t,r)}static $(){return["EffectivePlugin|1 plugin #0|3 is_team_required 8|4 is_enabled 8|6 pinned_git_ref 9?|7 configured_variables #1|8 has_team_configured_variables 8|9 inline_content_json 9?|10 install_mode #2|11 configured_variable_keys 9*|12 served_by #3|13 viewer_can_unpublish 8",PO,n.Struct,Ve,tt]}}class EN extends T{constructor(t){super(),this.plugins=[],this.marketplaces=[],this.bitbucketServerHostsNeedingLink=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new EN).fromBinary(t,r)}static fromJson(t,r){return(new EN).fromJson(t,r)}static fromJsonString(t,r){return(new EN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(EN,t,r)}static $(){return["GetEffectiveUserPluginsResponse|1 plugins #0*|2 marketplaces #1*|3 bitbucket_server_hosts_needing_link 9*",kN,JO]}}class CN extends T{constructor(t){super(),this.revision="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new CN).fromBinary(t,r)}static fromJson(t,r){return(new CN).fromJson(t,r)}static fromJsonString(t,r){return(new CN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(CN,t,r)}static $(){return["PluginBackendContent|1 revision 9"]}}class TN extends T{constructor(t){super(),this.pluginId=n.protoInt64.zero,this.revision="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new TN).fromBinary(t,r)}static fromJson(t,r){return(new TN).fromJson(t,r)}static fromJsonString(t,r){return(new TN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(TN,t,r)}static $(){return["DownloadPluginContentRequest|1 plugin_id 3|2 revision 9"]}}class UN extends T{constructor(t){super(),this.sha256="",this.sizeBytes=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new UN).fromBinary(t,r)}static fromJson(t,r){return(new UN).fromJson(t,r)}static fromJsonString(t,r){return(new UN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(UN,t,r)}static $(){return["DownloadPluginContentHeader|1 sha256 9|2 size_bytes 3"]}}class AN extends T{constructor(t){super(),this.part={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new AN).fromBinary(t,r)}static fromJson(t,r){return(new AN).fromJson(t,r)}static fromJsonString(t,r){return(new AN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(AN,t,r)}static $(){return["DownloadPluginContentResponse|2 header #0 part|1 data 12 part",UN]}}class $N extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $N).fromBinary(t,r)}static fromJson(t,r){return(new $N).fromJson(t,r)}static fromJsonString(t,r){return(new $N).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($N,t,r)}static $(){return["ListInstalledPluginsRequest|1 use_replica 8?|2 team_id 5?"]}}class MN extends T{constructor(t){super(),this.id=n.protoInt64.zero,this.name="",this.displayName="",this.description="",this.installMode=Ve.UNSPECIFIED,this.ownedByCaller=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new MN).fromBinary(t,r)}static fromJson(t,r){return(new MN).fromJson(t,r)}static fromJsonString(t,r){return(new MN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(MN,t,r)}static $(){return["InstalledPluginSummary|1 id 3|2 name 9|3 display_name 9|4 description 9|5 publisher_display_name 9?|6 publisher_logo_url 9?|7 logo_url 9?|8 mcp_server_name 9?|9 install_mode #0|10 owned_by_caller 8",Ve]}}class ON extends T{constructor(t){super(),this.plugins=[],this.ownedByCallerKnown=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ON).fromBinary(t,r)}static fromJson(t,r){return(new ON).fromJson(t,r)}static fromJsonString(t,r){return(new ON).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ON,t,r)}static $(){return["ListInstalledPluginsResponse|1 plugins #0*|2 owned_by_caller_known 8",MN]}}class DN extends T{constructor(t){super(),this.pluginId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new DN).fromBinary(t,r)}static fromJson(t,r){return(new DN).fromJson(t,r)}static fromJsonString(t,r){return(new DN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(DN,t,r)}static $(){return["GetInstalledPluginDetailRequest|1 plugin_id 3|2 use_replica 8?|3 team_id 5?"]}}class NN extends T{constructor(t){super(),this.ownedByCallerKnown=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new NN).fromBinary(t,r)}static fromJson(t,r){return(new NN).fromJson(t,r)}static fromJsonString(t,r){return(new NN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(NN,t,r)}static $(){return["GetInstalledPluginDetailResponse|1 plugin #0|2 owned_by_caller_known 8",VN]}}class GN extends T{constructor(t){super(),this.teamId=0,this.page=0,this.pageSize=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new GN).fromBinary(t,r)}static fromJson(t,r){return(new GN).fromJson(t,r)}static fromJsonString(t,r){return(new GN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(GN,t,r)}static $(){return["ListTeamPluginsTableRequest|1 team_id 5|2 team_marketplace_id 3?|3 page 5|4 page_size 5"]}}class LN extends T{constructor(t){super(),this.rows=[],this.totalCount=0,this.allowlistEnabled=!1,this.cloudAgentAllowlistEnabled=!1,this.viewerCanManage=!1,this.teamMarketplaces=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new LN).fromBinary(t,r)}static fromJson(t,r){return(new LN).fromJson(t,r)}static fromJsonString(t,r){return(new LN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(LN,t,r)}static $(){return["ListTeamPluginsTableResponse|1 rows #0*|2 total_count 5|3 allowlist_enabled 8|4 cloud_agent_allowlist_enabled 8|5 viewer_can_manage 8|6 team_marketplaces #1*",QN,FN]}}class FN extends T{constructor(t){super(),this.id=n.protoInt64.zero,this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new FN).fromBinary(t,r)}static fromJson(t,r){return(new FN).fromJson(t,r)}static fromJsonString(t,r){return(new FN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(FN,t,r)}static $(){return["TeamPluginsTableMarketplace|1 id 3|2 name 9"]}}class KN extends T{constructor(t){super(),this.state=Ye.UNSPECIFIED,this.toolCountIncomplete=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new KN).fromBinary(t,r)}static fromJson(t,r){return(new KN).fromJson(t,r)}static fromJsonString(t,r){return(new KN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(KN,t,r)}static $(){return["TeamPluginsTableToolAccess|1 state #0|2 allowed_tool_count 5?|3 tool_count_incomplete 8",Ye]}}class zN extends T{constructor(t){super(),this.mcpServers=0,this.skills=0,this.rules=0,this.commands=0,this.subagents=0,this.hooks=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zN).fromBinary(t,r)}static fromJson(t,r){return(new zN).fromJson(t,r)}static fromJsonString(t,r){return(new zN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zN,t,r)}static $(){return["TeamPluginsTableIncludes|1 mcp_servers 5|2 skills 5|3 rules 5|4 commands 5|5 subagents 5|6 hooks 5"]}}class jN extends T{constructor(t){super(),this.kind=Ze.UNSPECIFIED,this.toolAccess="",this.tools=[],this.coversOtherServers=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jN).fromBinary(t,r)}static fromJson(t,r){return(new jN).fromJson(t,r)}static fromJsonString(t,r){return(new jN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jN,t,r)}static $(){return["TeamPluginsTableRule|1 kind #0|2 name 9?|3 server_url_pattern 9?|4 command_pattern 9?|5 tool_access 9|6 tools 9*|7 covers_other_servers 8",Ze]}}class HN extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new HN).fromBinary(t,r)}static fromJson(t,r){return(new HN).fromJson(t,r)}static fromJsonString(t,r){return(new HN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(HN,t,r)}static $(){return["TeamPluginsTableServerAccess|1 access #0|2 rule #1",KN,jN]}}class WN extends T{constructor(t){super(),this.serverId=n.protoInt64.zero,this.name="",this.type="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new WN).fromBinary(t,r)}static fromJson(t,r){return(new WN).fromJson(t,r)}static fromJsonString(t,r){return(new WN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(WN,t,r)}static $(){return["TeamPluginsTableServer|1 server_id 3|2 name 9|3 type 9|4 url 9?|5 total_tool_count 5?|6 local #0|7 cloud #0",HN]}}class QN extends T{constructor(t){super(),this.key="",this.kind=Xe.UNSPECIFIED,this.title="",this.servers=[],this.totalToolCountIncomplete=!1,this.teamMarketplaceIds=[],this.installMode=Ve.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new QN).fromBinary(t,r)}static fromJson(t,r){return(new QN).fromJson(t,r)}static fromJsonString(t,r){return(new QN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(QN,t,r)}static $(){return["TeamPluginsTableRow|1 key 9|2 kind #0|3 plugin_id 3?|4 server_id 3?|5 title 9|6 logo_url 9?|7 includes #1|8 servers #2*|9 local #3|10 cloud #3|11 total_tool_count 5?|12 total_tool_count_incomplete 8|13 team_marketplace_ids 3*|14 install_mode #4",Xe,zN,WN,KN,Ve]}}class VN extends T{constructor(t){super(),this.description="",this.mcpServers=[],this.skills=[],this.subagents=[],this.rules=[],this.commands=[],this.hooks=[],this.variableNames=[],this.hasConfiguredVariables=!1,this.hasTeamConfiguredVariables=!1,this.teamScopeInstalled=!1,this.canManageTeamPlugins=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new VN).fromBinary(t,r)}static fromJson(t,r){return(new VN).fromJson(t,r)}static fromJsonString(t,r){return(new VN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(VN,t,r)}static $(){return["InstalledPluginDetail|1 summary #0|2 description 9|3 publisher #1|4 mcp_servers #2*|5 skills #3*|6 subagents #4*|7 rules #5*|8 commands #6*|9 hooks #7*|10 repository_url 9?|11 variable_names 9*|12 has_configured_variables 8|13 has_team_configured_variables 8|14 team_scope_installed 8|15 can_manage_team_plugins 8",MN,XN,BO,wO,yO,qO,IO,SO]}}class XN extends T{constructor(t){super(),this.isVerified=!1,this.isUserOwned=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new XN).fromBinary(t,r)}static fromJson(t,r){return(new XN).fromJson(t,r)}static fromJsonString(t,r){return(new XN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(XN,t,r)}static $(){return["InstalledPluginPublisher|1 is_verified 8|2 is_user_owned 8"]}}class YN extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new YN).fromBinary(t,r)}static fromJson(t,r){return(new YN).fromJson(t,r)}static fromJsonString(t,r){return(new YN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(YN,t,r)}static $(){return["ListStorefrontPluginsRequest"]}}class ZN extends T{constructor(t){super(),this.id=n.protoInt64.zero,this.name="",this.pluginIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ZN).fromBinary(t,r)}static fromJson(t,r){return(new ZN).fromJson(t,r)}static fromJsonString(t,r){return(new ZN).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ZN,t,r)}static $(){return["StorefrontMarketplace|1 id 3|2 name 9|3 display_name 9?|4 user_id 5?|5 team_id 5?|6 plugin_ids 3*"]}}class tG extends T{constructor(t){super(),this.id=n.protoInt64.zero,this.name="",this.displayName="",this.description="",this.publisherIsUserOwned=!1,this.marketplaceId=n.protoInt64.zero,this.curatedCategoryKeys=[],this.tags=[],this.updatedAt=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tG).fromBinary(t,r)}static fromJson(t,r){return(new tG).fromJson(t,r)}static fromJsonString(t,r){return(new tG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tG,t,r)}static $(){return["StorefrontPlugin|1 id 3|2 name 9|3 display_name 9|4 description 9|5 logo_url 9?|6 publisher_name 9?|7 publisher_display_name 9?|8 publisher_logo_url 9?|9 publisher_is_user_owned 8|10 marketplace_id 3|11 curated_category_keys 9*|12 tags 9*|13 updated_at 3"]}}class rG extends T{constructor(t){super(),this.marketplaces=[],this.plugins=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rG).fromBinary(t,r)}static fromJson(t,r){return(new rG).fromJson(t,r)}static fromJsonString(t,r){return(new rG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rG,t,r)}static $(){return["ListStorefrontPluginsResponse|1 marketplaces #0*|2 plugins #1*",ZN,tG]}}class eG extends T{constructor(t){super(),this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eG).fromBinary(t,r)}static fromJson(t,r){return(new eG).fromJson(t,r)}static fromJsonString(t,r){return(new eG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eG,t,r)}static $(){return["PluginRef|1 name 9|2 marketplace_name 9?"]}}class nG extends T{constructor(t){super(),this.refs=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nG).fromBinary(t,r)}static fromJson(t,r){return(new nG).fromJson(t,r)}static fromJsonString(t,r){return(new nG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nG,t,r)}static $(){return["ResolvePluginsByRefRequest|1 refs #0*|2 supports_backend_content 8?",eG]}}class sG extends T{constructor(t){super(),this.plugins=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sG).fromBinary(t,r)}static fromJson(t,r){return(new sG).fromJson(t,r)}static fromJsonString(t,r){return(new sG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sG,t,r)}static $(){return["ResolvePluginsByRefResponse|1 plugins #0*",PO]}}class iG extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iG).fromBinary(t,r)}static fromJson(t,r){return(new iG).fromJson(t,r)}static fromJsonString(t,r){return(new iG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iG,t,r)}static $(){return["ListMarketplacesRequest"]}}class oG extends T{constructor(t){super(),this.marketplaces=[],this.bitbucketDataCenterImportAvailable=!1,this.bitbucketServerHostsNeedingLink=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oG).fromBinary(t,r)}static fromJson(t,r){return(new oG).fromJson(t,r)}static fromJsonString(t,r){return(new oG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oG,t,r)}static $(){return["ListMarketplacesResponse|1 marketplaces #0*|2 bitbucket_data_center_import_available 8|3 bitbucket_server_hosts_needing_link 9*",JO]}}class aG extends T{constructor(t){super(),this.name="",this.gitUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aG).fromBinary(t,r)}static fromJson(t,r){return(new aG).fromJson(t,r)}static fromJsonString(t,r){return(new aG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aG,t,r)}static $(){return["AddMarketplaceRequest|1 name 9|2 git_url 9|3 git_ref 9?|4 display_name 9?|5 description 9?|6 team_id 5?|7 auto_reindex 8?"]}}class uG extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uG).fromBinary(t,r)}static fromJson(t,r){return(new uG).fromJson(t,r)}static fromJsonString(t,r){return(new uG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uG,t,r)}static $(){return["AddMarketplaceResponse|1 marketplace #0",JO]}}class cG extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cG).fromBinary(t,r)}static fromJson(t,r){return(new cG).fromJson(t,r)}static fromJsonString(t,r){return(new cG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cG,t,r)}static $(){return["GetOrCreateDefaultTeamMarketplaceRequest|1 team_id 5"]}}class lG extends T{constructor(t){super(),this.marketplaceId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lG).fromBinary(t,r)}static fromJson(t,r){return(new lG).fromJson(t,r)}static fromJsonString(t,r){return(new lG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lG,t,r)}static $(){return["GetOrCreateDefaultTeamMarketplaceResponse|1 marketplace_id 3"]}}class mG extends T{constructor(t){super(),this.marketplaceId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mG).fromBinary(t,r)}static fromJson(t,r){return(new mG).fromJson(t,r)}static fromJsonString(t,r){return(new mG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mG,t,r)}static $(){return["UpdateMarketplaceRequest|1 marketplace_id 3|2 name 9?|3 description 9?|4 auto_reindex 8?|5 team_id 5?|6 display_name 9?|7 allow_user_publish 8?"]}}class fG extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fG).fromBinary(t,r)}static fromJson(t,r){return(new fG).fromJson(t,r)}static fromJsonString(t,r){return(new fG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fG,t,r)}static $(){return["UpdateMarketplaceResponse|1 marketplace #0",JO]}}class dG extends T{constructor(t){super(),this.marketplaceId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dG).fromBinary(t,r)}static fromJson(t,r){return(new dG).fromJson(t,r)}static fromJsonString(t,r){return(new dG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dG,t,r)}static $(){return["RemoveMarketplaceRequest|1 marketplace_id 3|2 team_id 5?"]}}class pG extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pG).fromBinary(t,r)}static fromJson(t,r){return(new pG).fromJson(t,r)}static fromJsonString(t,r){return(new pG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pG,t,r)}static $(){return["RemoveMarketplaceResponse|1 success 8"]}}class hG extends T{constructor(t){super(),this.marketplaceId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hG).fromBinary(t,r)}static fromJson(t,r){return(new hG).fromJson(t,r)}static fromJsonString(t,r){return(new hG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hG,t,r)}static $(){return["RefreshMarketplaceRequest|1 marketplace_id 3|2 team_id 5?"]}}class gG extends T{constructor(t){super(),this.pluginsIndexed=0,this.pluginsUpdated=0,this.pluginsDeprecated=0,this.deprecatedPluginNames=[],this.errors=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gG).fromBinary(t,r)}static fromJson(t,r){return(new gG).fromJson(t,r)}static fromJsonString(t,r){return(new gG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gG,t,r)}static $(){return["RefreshMarketplaceResponse|1 marketplace #0|2 plugins_indexed 5|3 plugins_updated 5|4 plugins_deprecated 5|5 deprecated_plugin_names 9*|6 errors 9*",JO]}}class _G extends T{constructor(t){super(),this.marketplaceId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _G).fromBinary(t,r)}static fromJson(t,r){return(new _G).fromJson(t,r)}static fromJsonString(t,r){return(new _G).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_G,t,r)}static $(){return["ReindexAndApplyTeamMarketplaceChangesRequest|1 marketplace_id 3|2 git_ref 9?|3 commit_sha 9?|4 team_id 5?"]}}class JG extends T{constructor(t){super(),this.marketplaceId=n.protoInt64.zero,this.plugins=[],this.removedPluginNames=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new JG).fromBinary(t,r)}static fromJson(t,r){return(new JG).fromJson(t,r)}static fromJsonString(t,r){return(new JG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(JG,t,r)}static $(){return["ReindexAndApplyTeamMarketplaceChangesResponse|1 marketplace_id 3|2 plugins #0*|3 removed_plugin_names 9*",qG]}}class wG extends T{constructor(t){super(),this.gitUrl="",this.gitRef="",this.marketplaceName="",this.plugins=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wG).fromBinary(t,r)}static fromJson(t,r){return(new wG).fromJson(t,r)}static fromJsonString(t,r){return(new wG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wG,t,r)}static $(){return["RegisterMarketplaceAndPluginsRequest|1 git_url 9|2 git_ref 9|3 marketplace_name 9|4 plugins #0*|5 team_id 5?|6 commit_sha 9?",yG]}}class yG extends T{constructor(t){super(),this.name="",this.description="",this.version="",this.gitPath="",this.gitUrl="",this.gitRef="",this.displayName="",this.skills=[],this.subagents=[],this.hooks=[],this.rules=[],this.mcpServers=[],this.commands=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yG).fromBinary(t,r)}static fromJson(t,r){return(new yG).fromJson(t,r)}static fromJsonString(t,r){return(new yG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yG,t,r)}static $(){return["RegisterPluginEntry|1 name 9|2 description 9|3 version 9|4 git_path 9|5 git_url 9|6 git_ref 9|7 display_name 9|8 skills #0*|9 subagents #1*|10 hooks #2*|11 rules #3*|12 mcp_servers #4*|13 commands #5*|14 logo_url 9?|15 variables #6|16 min_client_versions #7?",wO,yO,SO,qO,BO,IO,n.Struct,bO]}}class SG extends T{constructor(t){super(),this.marketplaceId=n.protoInt64.zero,this.plugins=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new SG).fromBinary(t,r)}static fromJson(t,r){return(new SG).fromJson(t,r)}static fromJsonString(t,r){return(new SG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(SG,t,r)}static $(){return["RegisterMarketplaceAndPluginsResponse|1 marketplace_id 3|2 plugins #0*",qG]}}class qG extends T{constructor(t){super(),this.pluginId=n.protoInt64.zero,this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qG).fromBinary(t,r)}static fromJson(t,r){return(new qG).fromJson(t,r)}static fromJsonString(t,r){return(new qG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qG,t,r)}static $(){return["RegisteredPlugin|1 plugin_id 3|2 name 9"]}}class BG extends T{constructor(t){super(),this.principalKind=tn.UNSPECIFIED,this.principalId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new BG).fromBinary(t,r)}static fromJson(t,r){return(new BG).fromJson(t,r)}static fromJsonString(t,r){return(new BG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(BG,t,r)}static $(){return["MarketplaceAccessGrant|1 principal_kind #0|2 principal_id 9",tn]}}class IG extends T{constructor(t){super(),this.directoryGroupIds=[],this.createdAt=n.protoInt64.zero,this.updatedAt=n.protoInt64.zero,this.accessGrants=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new IG).fromBinary(t,r)}static fromJson(t,r){return(new IG).fromJson(t,r)}static fromJsonString(t,r){return(new IG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(IG,t,r)}static $(){return["TeamMarketplaceConfig|1 directory_group_ids 3*|2 configured_by 5?|3 created_at 3|4 updated_at 3|5 access_grants #0*",BG]}}class PG extends T{constructor(t){super(),this.marketplaceId=n.protoInt64.zero,this.directoryGroupIds=[],this.accessGrants=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new PG).fromBinary(t,r)}static fromJson(t,r){return(new PG).fromJson(t,r)}static fromJsonString(t,r){return(new PG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(PG,t,r)}static $(){return["UpdateTeamMarketplaceConfigRequest|1 marketplace_id 3|2 directory_group_ids 3*|3 team_id 5?|4 access_grants #0*|5 sync_access_grants 8?",BG]}}class bG extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bG).fromBinary(t,r)}static fromJson(t,r){return(new bG).fromJson(t,r)}static fromJsonString(t,r){return(new bG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bG,t,r)}static $(){return["UpdateTeamMarketplaceConfigResponse|1 marketplace #0",JO]}}class RG extends T{constructor(t){super(),this.marketplaceId=n.protoInt64.zero,this.gitUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new RG).fromBinary(t,r)}static fromJson(t,r){return(new RG).fromJson(t,r)}static fromJsonString(t,r){return(new RG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(RG,t,r)}static $(){return["SetTeamMarketplaceRepositoryRequest|1 marketplace_id 3|2 git_url 9|3 git_ref 9?"]}}class vG extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vG).fromBinary(t,r)}static fromJson(t,r){return(new vG).fromJson(t,r)}static fromJsonString(t,r){return(new vG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vG,t,r)}static $(){return["SetTeamMarketplaceRepositoryResponse|1 marketplace #0",JO]}}class xG extends T{constructor(t){super(),this.marketplaceId=n.protoInt64.zero,this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xG).fromBinary(t,r)}static fromJson(t,r){return(new xG).fromJson(t,r)}static fromJsonString(t,r){return(new xG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xG,t,r)}static $(){return["SetMarketplaceOriginDistributionRequest|1 marketplace_id 3|2 team_id 5?|3 enabled 8"]}}class kG extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kG).fromBinary(t,r)}static fromJson(t,r){return(new kG).fromJson(t,r)}static fromJsonString(t,r){return(new kG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kG,t,r)}static $(){return["SetMarketplaceOriginDistributionResponse|1 enabled 8"]}}class EG extends T{constructor(t){super(),this.marketplaceId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new EG).fromBinary(t,r)}static fromJson(t,r){return(new EG).fromJson(t,r)}static fromJsonString(t,r){return(new EG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(EG,t,r)}static $(){return["GetMarketplaceOriginDistributionStatusRequest|1 marketplace_id 3|2 team_id 5?"]}}class CG extends T{constructor(t){super(),this.enabled=!1,this.initialSyncComplete=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new CG).fromBinary(t,r)}static fromJson(t,r){return(new CG).fromJson(t,r)}static fromJsonString(t,r){return(new CG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(CG,t,r)}static $(){return["GetMarketplaceOriginDistributionStatusResponse|1 enabled 8|2 initial_sync_complete 8"]}}class TG extends T{constructor(t){super(),this.pluginId=n.protoInt64.zero,this.installMode=rn.OPTIONAL,this.createdAt=n.protoInt64.zero,this.updatedAt=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new TG).fromBinary(t,r)}static fromJson(t,r){return(new TG).fromJson(t,r)}static fromJsonString(t,r){return(new TG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(TG,t,r)}static $(){return["TeamMarketplacePluginPolicy|1 plugin_id 3|2 install_mode #0|3 configured_by 5?|4 created_at 3|5 updated_at 3",rn]}}class UG extends T{constructor(t){super(),this.marketplaceId=n.protoInt64.zero,this.policies=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new UG).fromBinary(t,r)}static fromJson(t,r){return(new UG).fromJson(t,r)}static fromJsonString(t,r){return(new UG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(UG,t,r)}static $(){return["SetTeamMarketplacePluginPoliciesRequest|1 marketplace_id 3|2 policies #0*|3 team_id 5?|4 mcp_server_plugin_id 3?",AG]}}class AG extends T{constructor(t){super(),this.pluginId=n.protoInt64.zero,this.installMode=rn.OPTIONAL,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new AG).fromBinary(t,r)}static fromJson(t,r){return(new AG).fromJson(t,r)}static fromJsonString(t,r){return(new AG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(AG,t,r)}static $(){return["SetTeamMarketplacePluginPoliciesRequest.Policy|1 plugin_id 3|2 install_mode #0",rn]}}class $G extends T{constructor(t){super(),this.policies=[],this.mcpServers=[],this.addedTeamServers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $G).fromBinary(t,r)}static fromJson(t,r){return(new $G).fromJson(t,r)}static fromJsonString(t,r){return(new $G).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($G,t,r)}static $(){return["SetTeamMarketplacePluginPoliciesResponse|1 policies #0*|2 mcp_servers #1*|3 added_team_servers #1*",TG,qN]}}class MG extends T{constructor(t){super(),this.marketplaceId=n.protoInt64.zero,this.pluginId=n.protoInt64.zero,this.clearedSecretNames=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new MG).fromBinary(t,r)}static fromJson(t,r){return(new MG).fromJson(t,r)}static fromJsonString(t,r){return(new MG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(MG,t,r)}static $(){return["SetTeamMarketplacePluginPolicyVariablesRequest|1 marketplace_id 3|2 plugin_id 3|3 variables #0|4 team_id 5?|5 cleared_secret_names 9*",n.Struct]}}class OG extends T{constructor(t){super(),this.code="",this.state="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new OG).fromBinary(t,r)}static fromJson(t,r){return(new OG).fromJson(t,r)}static fromJsonString(t,r){return(new OG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(OG,t,r)}static $(){return["CompleteSharepointOauthRequest|1 code 9|2 state 9"]}}class DG extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new DG).fromBinary(t,r)}static fromJson(t,r){return(new DG).fromJson(t,r)}static fromJsonString(t,r){return(new DG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(DG,t,r)}static $(){return["CompleteSharepointOauthResponse"]}}class NG extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new NG).fromBinary(t,r)}static fromJson(t,r){return(new NG).fromJson(t,r)}static fromJsonString(t,r){return(new NG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(NG,t,r)}static $(){return["GetTeamSharepointConnectorRequest|1 team_id 5?"]}}class GG extends T{constructor(t){super(),this.connected=!1,this.signedIn=!1,this.applicationPermissions=!1,this.connectorId="",this.writeExists=!1,this.writeConnectorId="",this.writeNeedsSignIn=!1,this.writeConnected=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new GG).fromBinary(t,r)}static fromJson(t,r){return(new GG).fromJson(t,r)}static fromJsonString(t,r){return(new GG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(GG,t,r)}static $(){return["GetTeamSharepointConnectorResponse|1 connected 8|2 signed_in 8|3 application_permissions 8|4 connector_id 9|5 write_exists 8|6 write_connector_id 9|7 write_needs_sign_in 8|8 write_connected 8"]}}class LG extends T{constructor(t){super(),this.connectorId="",this.allowedSiteIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new LG).fromBinary(t,r)}static fromJson(t,r){return(new LG).fromJson(t,r)}static fromJsonString(t,r){return(new LG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(LG,t,r)}static $(){return["SetTeamSharepointAllowedSitesRequest|1 team_id 5?|2 connector_id 9|3 allowed_site_ids 9*"]}}class FG extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new FG).fromBinary(t,r)}static fromJson(t,r){return(new FG).fromJson(t,r)}static fromJsonString(t,r){return(new FG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(FG,t,r)}static $(){return["SetTeamSharepointAllowedSitesResponse"]}}class KG extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new KG).fromBinary(t,r)}static fromJson(t,r){return(new KG).fromJson(t,r)}static fromJsonString(t,r){return(new KG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(KG,t,r)}static $(){return["DisconnectTeamSharepointRequest|1 team_id 5?"]}}class zG extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zG).fromBinary(t,r)}static fromJson(t,r){return(new zG).fromJson(t,r)}static fromJsonString(t,r){return(new zG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zG,t,r)}static $(){return["DisconnectTeamSharepointResponse"]}}class jG extends T{constructor(t){super(),this.teamId=0,this.marketplaceId=n.protoInt64.zero,this.pluginId=n.protoInt64.zero,this.clearedSecretNames=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jG).fromBinary(t,r)}static fromJson(t,r){return(new jG).fromJson(t,r)}static fromJsonString(t,r){return(new jG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jG,t,r)}static $(){return["SaveTeamPluginServerSettingsRequest|1 team_id 5|2 marketplace_id 3|3 plugin_id 3|4 variables #0?|5 access #1?|6 cleared_secret_names 9*",n.Struct,HG]}}class HG extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new HG).fromBinary(t,r)}static fromJson(t,r){return(new HG).fromJson(t,r)}static fromJsonString(t,r){return(new HG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(HG,t,r)}static $(){return["TeamPluginServerAccess|1 server_url 9?|2 command 9?|3 local #0?|4 cloud #0?",Q_]}}class WG extends T{constructor(t){super(),this.clearedSecretNames=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new WG).fromBinary(t,r)}static fromJson(t,r){return(new WG).fromJson(t,r)}static fromJsonString(t,r){return(new WG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(WG,t,r)}static $(){return["SaveTeamPluginServerSettingsResponse|1 variables #0?|2 cleared_secret_names 9*",QG]}}class QG extends T{constructor(t){super(),this.mcpServers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new QG).fromBinary(t,r)}static fromJson(t,r){return(new QG).fromJson(t,r)}static fromJsonString(t,r){return(new QG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(QG,t,r)}static $(){return["SetTeamMarketplacePluginPolicyVariablesResponse|1 auth_url 9?|2 admin_consent_url 9?|3 connector_id 9?|4 mcp_servers #0*",qN]}}class VG extends T{constructor(t){super(),this.pluginIds=[],this.marketplaceId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new VG).fromBinary(t,r)}static fromJson(t,r){return(new VG).fromJson(t,r)}static fromJsonString(t,r){return(new VG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(VG,t,r)}static $(){return["LinkPluginsToTeamMarketplaceRequest|1 plugin_ids 9*|2 marketplace_id 3"]}}class XG extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new XG).fromBinary(t,r)}static fromJson(t,r){return(new XG).fromJson(t,r)}static fromJsonString(t,r){return(new XG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(XG,t,r)}static $(){return["LinkPluginsToTeamMarketplaceResponse|1 success 8"]}}class YG extends T{constructor(t){super(),this.pluginIds=[],this.marketplaceId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new YG).fromBinary(t,r)}static fromJson(t,r){return(new YG).fromJson(t,r)}static fromJsonString(t,r){return(new YG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(YG,t,r)}static $(){return["UnlinkPluginsFromTeamMarketplaceRequest|1 plugin_ids 9*|2 marketplace_id 3"]}}class ZG extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ZG).fromBinary(t,r)}static fromJson(t,r){return(new ZG).fromJson(t,r)}static fromJsonString(t,r){return(new ZG).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ZG,t,r)}static $(){return["UnlinkPluginsFromTeamMarketplaceResponse|1 success 8"]}}class tL extends T{constructor(t){super(),this.repoUrl="",this.branchName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tL).fromBinary(t,r)}static fromJson(t,r){return(new tL).fromJson(t,r)}static fromJsonString(t,r){return(new tL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tL,t,r)}static $(){return["GetPullRequestForBranchRequest|1 repo_url 9|2 branch_name 9|3 skip_cache 8?"]}}class rL extends T{constructor(t){super(),this.prUrl="",this.prUrls=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rL).fromBinary(t,r)}static fromJson(t,r){return(new rL).fromJson(t,r)}static fromJsonString(t,r){return(new rL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rL,t,r)}static $(){return["GetPullRequestForBranchResponse|1 pr_url 9|2 pr_urls 9*"]}}class eL extends T{constructor(t){super(),this.supportedCanvasKits=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eL).fromBinary(t,r)}static fromJson(t,r){return(new eL).fromJson(t,r)}static fromJsonString(t,r){return(new eL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eL,t,r)}static $(){return["GetManagedSkillsRequest|1 supported_canvas_kits 9*|2 bc_id 9?"]}}class nL extends T{constructor(t){super(),this.id="",this.description="",this.content="",this.disableModelInvocation=!1,this.environments=[],this.disabledEnvironments=[],this.resources={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nL).fromBinary(t,r)}static fromJson(t,r){return(new nL).fromJson(t,r)}static fromJsonString(t,r){return(new nL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nL,t,r)}static $(){return["ManagedSkill|1 id 9|2 description 9|3 content 9|4 disable_model_invocation 8|5 environments 9*|6 disabled_environments 9*|7 enabled 8?|8 custom_mode #0?|9 resources 9,9",E.o7L]}}class sL extends T{constructor(t){super(),this.skills=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sL).fromBinary(t,r)}static fromJson(t,r){return(new sL).fromJson(t,r)}static fromJsonString(t,r){return(new sL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sL,t,r)}static $(){return["GetManagedSkillsResponse|1 skills #0*",nL]}}class iL extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iL).fromBinary(t,r)}static fromJson(t,r){return(new iL).fromJson(t,r)}static fromJsonString(t,r){return(new iL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iL,t,r)}static $(){return["GetCursorUserStateRequest"]}}class oL extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oL).fromBinary(t,r)}static fromJson(t,r){return(new oL).fromJson(t,r)}static fromJsonString(t,r){return(new oL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oL,t,r)}static $(){return["GetCursorUserStateResponse|1 state #0",n.Struct]}}class aL extends T{constructor(t){super(),this.jobRole="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aL).fromBinary(t,r)}static fromJson(t,r){return(new aL).fromJson(t,r)}static fromJsonString(t,r){return(new aL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aL,t,r)}static $(){return["SetJobDataRequest|1 job_role 9|2 use_case 9?"]}}class uL extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uL).fromBinary(t,r)}static fromJson(t,r){return(new uL).fromJson(t,r)}static fromJsonString(t,r){return(new uL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uL,t,r)}static $(){return["SetJobDataResponse"]}}class cL extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cL).fromBinary(t,r)}static fromJson(t,r){return(new cL).fromJson(t,r)}static fromJsonString(t,r){return(new cL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cL,t,r)}static $(){return["GetJiraInstallUrlRequest"]}}class lL extends T{constructor(t){super(),this.installUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lL).fromBinary(t,r)}static fromJson(t,r){return(new lL).fromJson(t,r)}static fromJsonString(t,r){return(new lL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lL,t,r)}static $(){return["GetJiraInstallUrlResponse|1 install_url 9"]}}class mL extends T{constructor(t){super(),this.installationId="",this.teamId=0,this.installToken="",this.setupCode="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mL).fromBinary(t,r)}static fromJson(t,r){return(new mL).fromJson(t,r)}static fromJsonString(t,r){return(new mL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mL,t,r)}static $(){return["LinkJiraInstallationRequest|1 installation_id 9|2 team_id 5|3 install_token 9|4 setup_code 9"]}}class fL extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fL).fromBinary(t,r)}static fromJson(t,r){return(new fL).fromJson(t,r)}static fromJsonString(t,r){return(new fL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fL,t,r)}static $(){return["LinkJiraInstallationResponse|1 success 8"]}}class dL extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dL).fromBinary(t,r)}static fromJson(t,r){return(new dL).fromJson(t,r)}static fromJsonString(t,r){return(new dL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dL,t,r)}static $(){return["GetJiraStatusRequest|1 team_id 5"]}}class pL extends T{constructor(t){super(),this.status="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pL).fromBinary(t,r)}static fromJson(t,r){return(new pL).fromJson(t,r)}static fromJsonString(t,r){return(new pL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pL,t,r)}static $(){return["GetJiraStatusResponse|1 status 9|2 site_name 9?|3 base_url 9?"]}}class hL extends T{constructor(t){super(),this.installationId="",this.cloudId="",this.siteName="",this.baseUrl="",this.linkedUserCount=0,this.activeTaskCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hL).fromBinary(t,r)}static fromJson(t,r){return(new hL).fromJson(t,r)}static fromJsonString(t,r){return(new hL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hL,t,r)}static $(){return["JiraInstallation|1 installation_id 9|2 cloud_id 9|3 site_name 9|4 base_url 9|5 linked_user_count 13|6 active_task_count 13"]}}class gL extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gL).fromBinary(t,r)}static fromJson(t,r){return(new gL).fromJson(t,r)}static fromJsonString(t,r){return(new gL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gL,t,r)}static $(){return["ListJiraInstallationsRequest|1 team_id 5"]}}class _L extends T{constructor(t){super(),this.installations=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _L).fromBinary(t,r)}static fromJson(t,r){return(new _L).fromJson(t,r)}static fromJsonString(t,r){return(new _L).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_L,t,r)}static $(){return["ListJiraInstallationsResponse|1 installations #0*",hL]}}class JL extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new JL).fromBinary(t,r)}static fromJson(t,r){return(new JL).fromJson(t,r)}static fromJsonString(t,r){return(new JL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(JL,t,r)}static $(){return["GetBitbucketForgeStatusRequest|1 team_id 5"]}}class wL extends T{constructor(t){super(),this.status="",this.workspaces=[],this.multiWorkspaceEnabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wL).fromBinary(t,r)}static fromJson(t,r){return(new wL).fromJson(t,r)}static fromJsonString(t,r){return(new wL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wL,t,r)}static $(){return["GetBitbucketForgeStatusResponse|1 status 9|2 workspace_name 9?|3 base_url 9?|4 workspace_settings_url 9?|5 pending_workspace_name 9?|6 pending_workspace_settings_url 9?|7 workspaces #0*|8 multi_workspace_enabled 8|9 access_role 9?|10 can_disconnect 8?|11 can_share 8?|12 cloud_id 9?",yL]}}class yL extends T{constructor(t){super(),this.cloudId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yL).fromBinary(t,r)}static fromJson(t,r){return(new yL).fromJson(t,r)}static fromJsonString(t,r){return(new yL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yL,t,r)}static $(){return["BitbucketForgeWorkspace|1 workspace_name 9?|2 base_url 9?|3 cloud_id 9|4 access_role 9?|5 can_disconnect 8?|6 can_share 8?"]}}class SL extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new SL).fromBinary(t,r)}static fromJson(t,r){return(new SL).fromJson(t,r)}static fromJsonString(t,r){return(new SL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(SL,t,r)}static $(){return["DisconnectJiraRequest|1 team_id 5|2 cloud_id 9?"]}}class qL extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qL).fromBinary(t,r)}static fromJson(t,r){return(new qL).fromJson(t,r)}static fromJsonString(t,r){return(new qL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qL,t,r)}static $(){return["DisconnectJiraResponse"]}}class BL extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new BL).fromBinary(t,r)}static fromJson(t,r){return(new BL).fromJson(t,r)}static fromJsonString(t,r){return(new BL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(BL,t,r)}static $(){return["DisconnectBitbucketForgeRequest|1 team_id 5|2 cloud_id 9?"]}}class IL extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new IL).fromBinary(t,r)}static fromJson(t,r){return(new IL).fromJson(t,r)}static fromJsonString(t,r){return(new IL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(IL,t,r)}static $(){return["DisconnectBitbucketForgeResponse"]}}class PL extends T{constructor(t){super(),this.teamId=0,this.cloudId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new PL).fromBinary(t,r)}static fromJson(t,r){return(new PL).fromJson(t,r)}static fromJsonString(t,r){return(new PL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(PL,t,r)}static $(){return["GetBitbucketForgeInstallationGrantsRequest|1 team_id 5|2 cloud_id 9"]}}class bL extends T{constructor(t){super(),this.teams=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bL).fromBinary(t,r)}static fromJson(t,r){return(new bL).fromJson(t,r)}static fromJsonString(t,r){return(new bL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bL,t,r)}static $(){return["GetBitbucketForgeInstallationGrantsResponse|1 teams #0*",RL]}}class RL extends T{constructor(t){super(),this.teamId=0,this.teamName="",this.granted=!1,this.stale=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new RL).fromBinary(t,r)}static fromJson(t,r){return(new RL).fromJson(t,r)}static fromJsonString(t,r){return(new RL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(RL,t,r)}static $(){return["GetBitbucketForgeInstallationGrantsResponse.Team|1 team_id 5|2 team_name 9|3 granted 8|4 stale 8"]}}class vL extends T{constructor(t){super(),this.teamId=0,this.cloudId="",this.targetTeamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vL).fromBinary(t,r)}static fromJson(t,r){return(new vL).fromJson(t,r)}static fromJsonString(t,r){return(new vL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vL,t,r)}static $(){return["GrantBitbucketForgeInstallationRequest|1 team_id 5|2 cloud_id 9|3 target_team_id 5"]}}class xL extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xL).fromBinary(t,r)}static fromJson(t,r){return(new xL).fromJson(t,r)}static fromJsonString(t,r){return(new xL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xL,t,r)}static $(){return["GrantBitbucketForgeInstallationResponse"]}}class kL extends T{constructor(t){super(),this.teamId=0,this.cloudId="",this.targetTeamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kL).fromBinary(t,r)}static fromJson(t,r){return(new kL).fromJson(t,r)}static fromJsonString(t,r){return(new kL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kL,t,r)}static $(){return["RevokeBitbucketForgeInstallationRequest|1 team_id 5|2 cloud_id 9|3 target_team_id 5"]}}class EL extends T{constructor(t){super(),this.revoked=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new EL).fromBinary(t,r)}static fromJson(t,r){return(new EL).fromJson(t,r)}static fromJsonString(t,r){return(new EL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(EL,t,r)}static $(){return["RevokeBitbucketForgeInstallationResponse|1 revoked 8"]}}class CL extends T{constructor(t){super(),this.id="",this.key="",this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new CL).fromBinary(t,r)}static fromJson(t,r){return(new CL).fromJson(t,r)}static fromJsonString(t,r){return(new CL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(CL,t,r)}static $(){return["JiraProject|1 id 9|2 key 9|3 name 9"]}}class TL extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new TL).fromBinary(t,r)}static fromJson(t,r){return(new TL).fromJson(t,r)}static fromJsonString(t,r){return(new TL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(TL,t,r)}static $(){return["GetJiraProjectsRequest|1 team_id 5|2 cloud_id 9?"]}}class UL extends T{constructor(t){super(),this.projects=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new UL).fromBinary(t,r)}static fromJson(t,r){return(new UL).fromJson(t,r)}static fromJsonString(t,r){return(new UL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(UL,t,r)}static $(){return["GetJiraProjectsResponse|1 projects #0*|2 error 9?",CL]}}class AL extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new AL).fromBinary(t,r)}static fromJson(t,r){return(new AL).fromJson(t,r)}static fromJsonString(t,r){return(new AL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(AL,t,r)}static $(){return["GetJiraTeamSettingsRequest|1 team_id 5|2 cloud_id 9?"]}}class $L extends T{constructor(t){super(),this.requireUserAuth=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $L).fromBinary(t,r)}static fromJson(t,r){return(new $L).fromJson(t,r)}static fromJsonString(t,r){return(new $L).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($L,t,r)}static $(){return["GetJiraTeamSettingsResponse|1 require_user_auth 8"]}}class ML extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ML).fromBinary(t,r)}static fromJson(t,r){return(new ML).fromJson(t,r)}static fromJsonString(t,r){return(new ML).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ML,t,r)}static $(){return["UpdateJiraTeamSettingsRequest|1 team_id 5|2 require_user_auth 8?|7 cloud_id 9?"]}}class OL extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new OL).fromBinary(t,r)}static fromJson(t,r){return(new OL).fromJson(t,r)}static fromJsonString(t,r){return(new OL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(OL,t,r)}static $(){return["UpdateJiraTeamSettingsResponse"]}}class DL extends T{constructor(t){super(),this.id=n.protoInt64.zero,this.repo="",this.ruleText="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new DL).fromBinary(t,r)}static fromJson(t,r){return(new DL).fromJson(t,r)}static fromJsonString(t,r){return(new DL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(DL,t,r)}static $(){return["JiraRoutingRule|1 id 3|2 repo 9|3 rule_text 9"]}}class NL extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new NL).fromBinary(t,r)}static fromJson(t,r){return(new NL).fromJson(t,r)}static fromJsonString(t,r){return(new NL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(NL,t,r)}static $(){return["GetJiraRoutingRulesRequest|1 team_id 5"]}}class GL extends T{constructor(t){super(),this.rules=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new GL).fromBinary(t,r)}static fromJson(t,r){return(new GL).fromJson(t,r)}static fromJsonString(t,r){return(new GL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(GL,t,r)}static $(){return["GetJiraRoutingRulesResponse|1 rules #0*",DL]}}class LL extends T{constructor(t){super(),this.teamId=0,this.repo="",this.ruleText="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new LL).fromBinary(t,r)}static fromJson(t,r){return(new LL).fromJson(t,r)}static fromJsonString(t,r){return(new LL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(LL,t,r)}static $(){return["CreateJiraRoutingRuleRequest|1 team_id 5|2 repo 9|3 rule_text 9"]}}class FL extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new FL).fromBinary(t,r)}static fromJson(t,r){return(new FL).fromJson(t,r)}static fromJsonString(t,r){return(new FL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(FL,t,r)}static $(){return["CreateJiraRoutingRuleResponse|1 rule #0",DL]}}class KL extends T{constructor(t){super(),this.teamId=0,this.ruleId=n.protoInt64.zero,this.repo="",this.ruleText="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new KL).fromBinary(t,r)}static fromJson(t,r){return(new KL).fromJson(t,r)}static fromJsonString(t,r){return(new KL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(KL,t,r)}static $(){return["UpdateJiraRoutingRuleRequest|1 team_id 5|2 rule_id 3|3 repo 9|4 rule_text 9"]}}class zL extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zL).fromBinary(t,r)}static fromJson(t,r){return(new zL).fromJson(t,r)}static fromJsonString(t,r){return(new zL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zL,t,r)}static $(){return["UpdateJiraRoutingRuleResponse|1 rule #0",DL]}}class jL extends T{constructor(t){super(),this.teamId=0,this.ruleId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jL).fromBinary(t,r)}static fromJson(t,r){return(new jL).fromJson(t,r)}static fromJsonString(t,r){return(new jL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jL,t,r)}static $(){return["DeleteJiraRoutingRuleRequest|1 team_id 5|2 rule_id 3"]}}class HL extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new HL).fromBinary(t,r)}static fromJson(t,r){return(new HL).fromJson(t,r)}static fromJsonString(t,r){return(new HL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(HL,t,r)}static $(){return["DeleteJiraRoutingRuleResponse"]}}class WL extends T{constructor(t){super(),this.cloudId="",this.jiraAccountId="",this.linkToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new WL).fromBinary(t,r)}static fromJson(t,r){return(new WL).fromJson(t,r)}static fromJsonString(t,r){return(new WL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(WL,t,r)}static $(){return["LinkJiraUserRequest|1 cloud_id 9|2 jira_account_id 9|3 link_token 9"]}}class QL extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new QL).fromBinary(t,r)}static fromJson(t,r){return(new QL).fromJson(t,r)}static fromJsonString(t,r){return(new QL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(QL,t,r)}static $(){return["LinkJiraUserResponse|1 success 8"]}}class VL extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new VL).fromBinary(t,r)}static fromJson(t,r){return(new VL).fromJson(t,r)}static fromJsonString(t,r){return(new VL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(VL,t,r)}static $(){return["ListJiraUserLinksRequest"]}}class XL extends T{constructor(t){super(),this.links=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new XL).fromBinary(t,r)}static fromJson(t,r){return(new XL).fromJson(t,r)}static fromJsonString(t,r){return(new XL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(XL,t,r)}static $(){return["ListJiraUserLinksResponse|1 links #0*",YL]}}class YL extends T{constructor(t){super(),this.cloudId="",this.jiraAccountId="",this.siteName="",this.baseUrl="",this.linkedAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new YL).fromBinary(t,r)}static fromJson(t,r){return(new YL).fromJson(t,r)}static fromJsonString(t,r){return(new YL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(YL,t,r)}static $(){return["JiraUserLink|1 cloud_id 9|2 jira_account_id 9|3 site_name 9|4 base_url 9|5 linked_at_ms 3"]}}class ZL extends T{constructor(t){super(),this.cloudId="",this.jiraAccountId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ZL).fromBinary(t,r)}static fromJson(t,r){return(new ZL).fromJson(t,r)}static fromJsonString(t,r){return(new ZL).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ZL,t,r)}static $(){return["UnlinkJiraUserRequest|1 cloud_id 9|2 jira_account_id 9"]}}class tF extends T{constructor(t){super(),this.success=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tF).fromBinary(t,r)}static fromJson(t,r){return(new tF).fromJson(t,r)}static fromJsonString(t,r){return(new tF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tF,t,r)}static $(){return["UnlinkJiraUserResponse|1 success 8"]}}class rF extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rF).fromBinary(t,r)}static fromJson(t,r){return(new rF).fromJson(t,r)}static fromJsonString(t,r){return(new rF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rF,t,r)}static $(){return["ListFinancialConnectionsRequest"]}}class eF extends T{constructor(t){super(),this.connectionId="",this.provider="",this.providerConnectionId="",this.status="",this.hasSynced=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eF).fromBinary(t,r)}static fromJson(t,r){return(new eF).fromJson(t,r)}static fromJsonString(t,r){return(new eF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eF,t,r)}static $(){return["FinancialConnection|1 connection_id 9|2 provider 9|3 provider_connection_id 9|4 status 9|5 created_at #0|6 updated_at #0|7 has_synced 8|8 institution_id 9?|9 institution_name 9?|10 institution_logo 9?|11 institution_primary_color 9?|12 institution_icon_url 9?",n.Timestamp]}}class nF extends T{constructor(t){super(),this.connections=[],this.pendingLinkSessions=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nF).fromBinary(t,r)}static fromJson(t,r){return(new nF).fromJson(t,r)}static fromJsonString(t,r){return(new nF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nF,t,r)}static $(){return["ListFinancialConnectionsResponse|1 connections #0*|2 pending_link_sessions 13|3 connect_url 9?",eF]}}class sF extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sF).fromBinary(t,r)}static fromJson(t,r){return(new sF).fromJson(t,r)}static fromJsonString(t,r){return(new sF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sF,t,r)}static $(){return["ListFinancialAccountsRequest"]}}class iF extends T{constructor(t){super(),this.accountId="",this.connectionId="",this.accountClass="",this.connectionStatus="",this.hasSynced=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iF).fromBinary(t,r)}static fromJson(t,r){return(new iF).fromJson(t,r)}static fromJsonString(t,r){return(new iF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iF,t,r)}static $(){return["FinancialAccount|1 account_id 9|2 connection_id 9|3 account_class 9|4 name 9?|5 official_name 9?|6 mask 9?|7 type 9?|8 subtype 9?|9 current_balance 9?|10 available_balance 9?|11 currency 9?|12 institution_id 9?|13 institution_name 9?|14 connection_status 9|15 has_synced 8"]}}class oF extends T{constructor(t){super(),this.accounts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oF).fromBinary(t,r)}static fromJson(t,r){return(new oF).fromJson(t,r)}static fromJsonString(t,r){return(new oF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oF,t,r)}static $(){return["ListFinancialAccountsResponse|1 accounts #0*",iF]}}class aF extends T{constructor(t){super(),this.connectionId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aF).fromBinary(t,r)}static fromJson(t,r){return(new aF).fromJson(t,r)}static fromJsonString(t,r){return(new aF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aF,t,r)}static $(){return["DeleteFinancialConnectionRequest|1 connection_id 9"]}}class uF extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uF).fromBinary(t,r)}static fromJson(t,r){return(new uF).fromJson(t,r)}static fromJsonString(t,r){return(new uF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uF,t,r)}static $(){return["DeleteFinancialConnectionResponse"]}}class cF extends T{constructor(t){super(),this.returnTo="",this.repairLinkedBank=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cF).fromBinary(t,r)}static fromJson(t,r){return(new cF).fromJson(t,r)}static fromJsonString(t,r){return(new cF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cF,t,r)}static $(){return["StartFinancialLinkRequest|1 return_to 9|2 repair_linked_bank 8"]}}class lF extends T{constructor(t){super(),this.hostedLinkUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lF).fromBinary(t,r)}static fromJson(t,r){return(new lF).fromJson(t,r)}static fromJsonString(t,r){return(new lF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lF,t,r)}static $(){return["StartFinancialLinkResponse|1 hosted_link_url 9|2 expires_at #0?",n.Timestamp]}}class mF extends T{constructor(t){super(),this.uuid="",this.action={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mF).fromBinary(t,r)}static fromJson(t,r){return(new mF).fromJson(t,r)}static fromJsonString(t,r){return(new mF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mF,t,r)}static $(){return["UpdateBitbucketServerInstanceOauthAppRequest|1 uuid 9|2 set_oauth_app #0 action|3 clear_oauth_app #1 action",fF,dF]}}class fF extends T{constructor(t){super(),this.clientId="",this.clientSecret="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fF).fromBinary(t,r)}static fromJson(t,r){return(new fF).fromJson(t,r)}static fromJsonString(t,r){return(new fF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fF,t,r)}static $(){return["UpdateBitbucketServerInstanceOauthAppRequest.SetOauthApp|1 client_id 9|2 client_secret 9"]}}class dF extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dF).fromBinary(t,r)}static fromJson(t,r){return(new dF).fromJson(t,r)}static fromJsonString(t,r){return(new dF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dF,t,r)}static $(){return["UpdateBitbucketServerInstanceOauthAppRequest.ClearOauthApp"]}}class pF extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pF).fromBinary(t,r)}static fromJson(t,r){return(new pF).fromJson(t,r)}static fromJsonString(t,r){return(new pF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pF,t,r)}static $(){return["UpdateBitbucketServerInstanceOauthAppResponse"]}}class hF extends T{constructor(t){super(),this.uuid="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hF).fromBinary(t,r)}static fromJson(t,r){return(new hF).fromJson(t,r)}static fromJsonString(t,r){return(new hF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hF,t,r)}static $(){return["DisconnectBitbucketServerAccountRequest|1 uuid 9"]}}class gF extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gF).fromBinary(t,r)}static fromJson(t,r){return(new gF).fromJson(t,r)}static fromJsonString(t,r){return(new gF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gF,t,r)}static $(){return["DisconnectBitbucketServerAccountResponse"]}}class _F extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _F).fromBinary(t,r)}static fromJson(t,r){return(new _F).fromJson(t,r)}static fromJsonString(t,r){return(new _F).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_F,t,r)}static $(){return["ListUnpaidUsageInvoicesRequest|1 team_id 5?"]}}class JF extends T{constructor(t){super(),this.invoices=[],this.needsTeamAdmin=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new JF).fromBinary(t,r)}static fromJson(t,r){return(new JF).fromJson(t,r)}static fromJsonString(t,r){return(new JF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(JF,t,r)}static $(){return["ListUnpaidUsageInvoicesResponse|1 invoices #0*|2 needs_team_admin 8",aR]}}class wF extends T{constructor(t){super(),this.clientSecret="",this.publishableKey="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wF).fromBinary(t,r)}static fromJson(t,r){return(new wF).fromJson(t,r)}static fromJsonString(t,r){return(new wF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wF,t,r)}static $(){return["XaiPaymentChallenge|1 client_secret 9|2 publishable_key 9"]}}class yF extends T{constructor(t){super(),this.checkId="",this.joinerName="",this.cardholderUnknown=!1,this.expiresAt="",this.approved=!1,this.adminChange=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yF).fromBinary(t,r)}static fromJson(t,r){return(new yF).fromJson(t,r)}static fromJsonString(t,r){return(new yF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yF,t,r)}static $(){return["XaiSeatPaymentCheck|1 check_id 9|2 joiner_name 9|3 payment_challenge #0|4 cardholder_unknown 8|5 expires_at 9|6 approved 8|7 admin_change 8",wF]}}class SF extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new SF).fromBinary(t,r)}static fromJson(t,r){return(new SF).fromJson(t,r)}static fromJsonString(t,r){return(new SF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(SF,t,r)}static $(){return["ListGrokApiKeyAclOptionsRequest|1 team_id 5"]}}class qF extends T{constructor(t){super(),this.modelsStatus=BF.UNSPECIFIED,this.chatModels=[],this.imageModels=[],this.videoModels=[],this.embeddingModels=[],this.endpointsStatus=BF.UNSPECIFIED,this.endpoints=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qF).fromBinary(t,r)}static fromJson(t,r){return(new qF).fromJson(t,r)}static fromJsonString(t,r){return(new qF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qF,t,r)}static $(){return["ListGrokApiKeyAclOptionsResponse|1 models_status #0|2 chat_models 9*|3 image_models 9*|4 video_models 9*|5 embedding_models 9*|6 endpoints_status #0|7 endpoints 9*",BF]}}var BF=(0,a.QT)(n.proto3,C,"ListGrokApiKeyAclOptionsResponse.CatalogStatus",[[0,"UNSPECIFIED"],[1,"AVAILABLE"],[2,"NOT_OFFERED"],[3,"FAILED"]],1);class IF extends T{constructor(t){super(),this.batchId="",this.name="",this.createApiKeyId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new IF).fromBinary(t,r)}static fromJson(t,r){return(new IF).fromJson(t,r)}static fromJsonString(t,r){return(new IF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(IF,t,r)}static $(){return["GrokBatch|1 batch_id 9|2 name 9|3 create_time #0|4 expire_time #0|5 create_api_key_id 9|6 cancel_time #0|7 cancel_by_xai_message 9?|8 state #1|9 cost_breakdown #2|10 input_file_id 9?",n.Timestamp,PF,bF]}}class PF extends T{constructor(t){super(),this.numRequests=n.protoInt64.zero,this.numPending=n.protoInt64.zero,this.numSuccess=n.protoInt64.zero,this.numError=n.protoInt64.zero,this.numCancelled=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new PF).fromBinary(t,r)}static fromJson(t,r){return(new PF).fromJson(t,r)}static fromJsonString(t,r){return(new PF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(PF,t,r)}static $(){return["GrokBatchState|1 num_requests 3|2 num_pending 3|3 num_success 3|4 num_error 3|5 num_cancelled 3"]}}class bF extends T{constructor(t){super(),this.totalCostUsdTicks=n.protoInt64.zero,this.endpointCosts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bF).fromBinary(t,r)}static fromJson(t,r){return(new bF).fromJson(t,r)}static fromJsonString(t,r){return(new bF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bF,t,r)}static $(){return["GrokBatchCostBreakdown|1 total_cost_usd_ticks 3|2 endpoint_costs #0*|3 calculation_time #1",RF,n.Timestamp]}}class RF extends T{constructor(t){super(),this.endpoint="",this.costUsdTicks=n.protoInt64.zero,this.requestCount=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new RF).fromBinary(t,r)}static fromJson(t,r){return(new RF).fromJson(t,r)}static fromJsonString(t,r){return(new RF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(RF,t,r)}static $(){return["GrokBatchEndpointCost|1 endpoint 9|2 cost_usd_ticks 3|3 request_count 3"]}}class vF extends T{constructor(t){super(),this.teamId=0,this.limit=0,this.filter="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vF).fromBinary(t,r)}static fromJson(t,r){return(new vF).fromJson(t,r)}static fromJsonString(t,r){return(new vF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vF,t,r)}static $(){return["ListGrokBatchesRequest|1 team_id 5|2 limit 5|3 pagination_token 9?|4 filter 9"]}}class xF extends T{constructor(t){super(),this.teamLinked=!1,this.userLinked=!1,this.batches=[],this.canManage=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xF).fromBinary(t,r)}static fromJson(t,r){return(new xF).fromJson(t,r)}static fromJsonString(t,r){return(new xF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xF,t,r)}static $(){return["ListGrokBatchesResponse|1 team_linked 8|2 user_linked 8|3 batches #0*|4 pagination_token 9?|5 can_manage 8",IF]}}class kF extends T{constructor(t){super(),this.teamId=0,this.batchId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kF).fromBinary(t,r)}static fromJson(t,r){return(new kF).fromJson(t,r)}static fromJsonString(t,r){return(new kF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kF,t,r)}static $(){return["GetGrokBatchRequest|1 team_id 5|2 batch_id 9"]}}class EF extends T{constructor(t){super(),this.canManage=!1,this.teamLinked=!1,this.userLinked=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new EF).fromBinary(t,r)}static fromJson(t,r){return(new EF).fromJson(t,r)}static fromJsonString(t,r){return(new EF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(EF,t,r)}static $(){return["GetGrokBatchResponse|1 batch #0|2 can_manage 8|3 team_linked 8|4 user_linked 8",IF]}}class CF extends T{constructor(t){super(),this.batchRequestId="",this.endpoint="",this.model="",this.state=en.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new CF).fromBinary(t,r)}static fromJson(t,r){return(new CF).fromJson(t,r)}static fromJsonString(t,r){return(new CF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(CF,t,r)}static $(){return["GrokBatchRequestMetadata|1 batch_request_id 9|2 endpoint 9|3 model 9|4 state #0|5 create_time #1|6 finish_time #1|7 request_preview 9?|8 cost_usd_ticks 3?",en,n.Timestamp]}}class TF extends T{constructor(t){super(),this.teamId=0,this.batchId="",this.limit=0,this.status=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new TF).fromBinary(t,r)}static fromJson(t,r){return(new TF).fromJson(t,r)}static fromJsonString(t,r){return(new TF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(TF,t,r)}static $(){return["ListGrokBatchRequestsRequest|1 team_id 5|2 batch_id 9|3 limit 5|4 pagination_token 9?|5 status #0*",en]}}class UF extends T{constructor(t){super(),this.batchRequestMetadata=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new UF).fromBinary(t,r)}static fromJson(t,r){return(new UF).fromJson(t,r)}static fromJsonString(t,r){return(new UF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(UF,t,r)}static $(){return["ListGrokBatchRequestsResponse|1 batch_request_metadata #0*|2 pagination_token 9?",CF]}}class AF extends T{constructor(t){super(),this.teamId=0,this.batchId="",this.batchRequestId="",this.format=nn.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new AF).fromBinary(t,r)}static fromJson(t,r){return(new AF).fromJson(t,r)}static fromJsonString(t,r){return(new AF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(AF,t,r)}static $(){return["GetGrokBatchRequestResultRequest|1 team_id 5|2 batch_id 9|3 batch_request_id 9|4 format #0",nn]}}class $F extends T{constructor(t){super(),this.data={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $F).fromBinary(t,r)}static fromJson(t,r){return(new $F).fromJson(t,r)}static fromJsonString(t,r){return(new $F).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($F,t,r)}static $(){return["GrokFormattedBatchRequest|1 json 9 data|2 request_b64 9 data"]}}class MF extends T{constructor(t){super(),this.data={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new MF).fromBinary(t,r)}static fromJson(t,r){return(new MF).fromJson(t,r)}static fromJsonString(t,r){return(new MF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(MF,t,r)}static $(){return["GrokFormattedBatchResult|1 json 9 data|2 result_b64 9 data"]}}class OF extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new OF).fromBinary(t,r)}static fromJson(t,r){return(new OF).fromJson(t,r)}static fromJsonString(t,r){return(new OF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(OF,t,r)}static $(){return["GetGrokBatchRequestResultResponse|1 request #0|2 result #1",$F,MF]}}class DF extends T{constructor(t){super(),this.name="",this.inputFileId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new DF).fromBinary(t,r)}static fromJson(t,r){return(new DF).fromJson(t,r)}static fromJsonString(t,r){return(new DF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(DF,t,r)}static $(){return["GrokCreateBatchParams|1 name 9|2 input_file_id 9"]}}class NF extends T{constructor(t){super(),this.teamId=0,this.apiKeyId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new NF).fromBinary(t,r)}static fromJson(t,r){return(new NF).fromJson(t,r)}static fromJsonString(t,r){return(new NF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(NF,t,r)}static $(){return["CreateGrokBatchRequest|1 team_id 5|2 api_key_id 9|3 request #0",DF]}}class GF extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new GF).fromBinary(t,r)}static fromJson(t,r){return(new GF).fromJson(t,r)}static fromJsonString(t,r){return(new GF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(GF,t,r)}static $(){return["CreateGrokBatchResponse|1 batch #0",IF]}}class LF extends T{constructor(t){super(),this.teamId=0,this.batchId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new LF).fromBinary(t,r)}static fromJson(t,r){return(new LF).fromJson(t,r)}static fromJsonString(t,r){return(new LF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(LF,t,r)}static $(){return["CancelGrokBatchRequest|1 team_id 5|2 batch_id 9"]}}class FF extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new FF).fromBinary(t,r)}static fromJson(t,r){return(new FF).fromJson(t,r)}static fromJsonString(t,r){return(new FF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(FF,t,r)}static $(){return["CancelGrokBatchResponse|1 batch #0",IF]}}class KF extends T{constructor(t){super(),this.voiceId="",this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new KF).fromBinary(t,r)}static fromJson(t,r){return(new KF).fromJson(t,r)}static fromJsonString(t,r){return(new KF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(KF,t,r)}static $(){return["GrokBuiltInVoice|1 voice_id 9|2 name 9|3 language 9?|4 gender 9?|5 age 9?"]}}class zF extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zF).fromBinary(t,r)}static fromJson(t,r){return(new zF).fromJson(t,r)}static fromJsonString(t,r){return(new zF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zF,t,r)}static $(){return["ListGrokBuiltInVoicesRequest|1 team_id 5"]}}class jF extends T{constructor(t){super(),this.teamLinked=!1,this.userLinked=!1,this.voices=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jF).fromBinary(t,r)}static fromJson(t,r){return(new jF).fromJson(t,r)}static fromJsonString(t,r){return(new jF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jF,t,r)}static $(){return["ListGrokBuiltInVoicesResponse|1 team_linked 8|2 user_linked 8|3 voices #0*",KF]}}class HF extends T{constructor(t){super(),this.voiceId="",this.createdAt="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new HF).fromBinary(t,r)}static fromJson(t,r){return(new HF).fromJson(t,r)}static fromJsonString(t,r){return(new HF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(HF,t,r)}static $(){return["GrokCustomVoice|1 voice_id 9|2 name 9?|3 description 9?|4 gender 9?|5 accent 9?|6 age 9?|7 language 9?|8 use_case 9?|9 tone 9?|10 created_at 9"]}}class WF extends T{constructor(t){super(),this.teamId=0,this.limit=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new WF).fromBinary(t,r)}static fromJson(t,r){return(new WF).fromJson(t,r)}static fromJsonString(t,r){return(new WF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(WF,t,r)}static $(){return["ListGrokCustomVoicesRequest|1 team_id 5|2 limit 5|3 pagination_token 9?"]}}class QF extends T{constructor(t){super(),this.teamLinked=!1,this.userLinked=!1,this.voices=[],this.totalCount=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new QF).fromBinary(t,r)}static fromJson(t,r){return(new QF).fromJson(t,r)}static fromJsonString(t,r){return(new QF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(QF,t,r)}static $(){return["ListGrokCustomVoicesResponse|1 team_linked 8|2 user_linked 8|3 voices #0*|4 pagination_token 9?|5 total_count 3|6 cap 3?",HF]}}class VF extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new VF).fromBinary(t,r)}static fromJson(t,r){return(new VF).fromJson(t,r)}static fromJsonString(t,r){return(new VF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(VF,t,r)}static $(){return["GrokCustomVoicePatch|1 name 9?|2 gender 9?|3 age 9?|4 tone 9?|5 language 9?"]}}class XF extends T{constructor(t){super(),this.teamId=0,this.voiceId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new XF).fromBinary(t,r)}static fromJson(t,r){return(new XF).fromJson(t,r)}static fromJsonString(t,r){return(new XF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(XF,t,r)}static $(){return["UpdateGrokCustomVoiceRequest|1 team_id 5|2 voice_id 9|3 patch #0",VF]}}class YF extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new YF).fromBinary(t,r)}static fromJson(t,r){return(new YF).fromJson(t,r)}static fromJsonString(t,r){return(new YF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(YF,t,r)}static $(){return["UpdateGrokCustomVoiceResponse|1 voice #0",HF]}}class ZF extends T{constructor(t){super(),this.teamId=0,this.voiceId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ZF).fromBinary(t,r)}static fromJson(t,r){return(new ZF).fromJson(t,r)}static fromJsonString(t,r){return(new ZF).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ZF,t,r)}static $(){return["DeleteGrokCustomVoiceRequest|1 team_id 5|2 voice_id 9"]}}class tK extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tK).fromBinary(t,r)}static fromJson(t,r){return(new tK).fromJson(t,r)}static fromJsonString(t,r){return(new tK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tK,t,r)}static $(){return["DeleteGrokCustomVoiceResponse"]}}class rK extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rK).fromBinary(t,r)}static fromJson(t,r){return(new rK).fromJson(t,r)}static fromJsonString(t,r){return(new rK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rK,t,r)}static $(){return["GetGrokVoiceCloningAccessRequest|1 team_id 5"]}}class eK extends T{constructor(t){super(),this.teamLinked=!1,this.userLinked=!1,this.allowed=!1,this.restriction=sn.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eK).fromBinary(t,r)}static fromJson(t,r){return(new eK).fromJson(t,r)}static fromJsonString(t,r){return(new eK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(eK,t,r)}static $(){return["GetGrokVoiceCloningAccessResponse|1 team_linked 8|2 user_linked 8|3 allowed 8|4 restriction #0",sn]}}class nK extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nK).fromBinary(t,r)}static fromJson(t,r){return(new nK).fromJson(t,r)}static fromJsonString(t,r){return(new nK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nK,t,r)}static $(){return["GetGrokVoiceClonePassphraseRequest|1 team_id 5"]}}class sK extends T{constructor(t){super(),this.passphrase="",this.passphraseToken="",this.expiresInSeconds=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sK).fromBinary(t,r)}static fromJson(t,r){return(new sK).fromJson(t,r)}static fromJsonString(t,r){return(new sK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sK,t,r)}static $(){return["GetGrokVoiceClonePassphraseResponse|1 passphrase 9|2 passphrase_token 9|3 expires_in_seconds 5"]}}class iK extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iK).fromBinary(t,r)}static fromJson(t,r){return(new iK).fromJson(t,r)}static fromJsonString(t,r){return(new iK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iK,t,r)}static $(){return["GrokVoiceCloneDetails|1 name 9?|2 description 9?|3 gender 9?|4 age 9?|5 tone 9?|6 accent 9?|7 language 9?|8 use_case 9?"]}}class oK extends T{constructor(t){super(),this.data=new Uint8Array(0),this.contentType="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oK).fromBinary(t,r)}static fromJson(t,r){return(new oK).fromJson(t,r)}static fromJsonString(t,r){return(new oK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oK,t,r)}static $(){return["GrokVoiceCloneAudio|1 data 12|2 content_type 9"]}}class aK extends T{constructor(t){super(),this.teamId=0,this.passphraseToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aK).fromBinary(t,r)}static fromJson(t,r){return(new aK).fromJson(t,r)}static fromJsonString(t,r){return(new aK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aK,t,r)}static $(){return["CloneGrokCustomVoiceRequest|1 team_id 5|2 passphrase_audio #0|3 voice_audio #0|4 passphrase_token 9|5 details #1",oK,iK]}}class uK extends T{constructor(t){super(),this.failure=on.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uK).fromBinary(t,r)}static fromJson(t,r){return(new uK).fromJson(t,r)}static fromJsonString(t,r){return(new uK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uK,t,r)}static $(){return["CloneGrokCustomVoiceResponse|1 voice #0|2 failure #1",HF,on]}}class cK extends T{constructor(t){super(),this.fileId="",this.name="",this.sizeBytes=n.protoInt64.zero,this.contentType="",this.hash="",this.collections=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cK).fromBinary(t,r)}static fromJson(t,r){return(new cK).fromJson(t,r)}static fromJsonString(t,r){return(new cK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cK,t,r)}static $(){return["GrokFile|1 file_id 9|2 name 9|3 size_bytes 3|4 content_type 9|5 created_at #0|6 expires_at #0|7 hash 9|8 upload_status 9?|9 upload_error_message 9?|10 processing_status 9?|11 file_path 9?|12 public_url 9?|13 public_url_expires_at #0?|14 description 9?|15 collections #1*",n.Timestamp,lK]}}class lK extends T{constructor(t){super(),this.collectionId="",this.collectionName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lK).fromBinary(t,r)}static fromJson(t,r){return(new lK).fromJson(t,r)}static fromJsonString(t,r){return(new lK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lK,t,r)}static $(){return["GrokFileCollectionInfo|1 collection_id 9|2 collection_name 9"]}}class mK extends T{constructor(t){super(),this.teamId=0,this.limit=0,this.order=un.UNSPECIFIED,this.sortBy=an.UNSPECIFIED,this.filter="",this.includeCollections=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mK).fromBinary(t,r)}static fromJson(t,r){return(new mK).fromJson(t,r)}static fromJsonString(t,r){return(new mK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mK,t,r)}static $(){return["ListGrokFilesRequest|1 team_id 5|2 limit 5|3 next_token 9?|4 order #0|5 sort_by #1|6 filter 9|7 include_collections 8",un,an]}}class fK extends T{constructor(t){super(),this.teamLinked=!1,this.userLinked=!1,this.files=[],this.canManage=!1,this.zeroDataRetention=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fK).fromBinary(t,r)}static fromJson(t,r){return(new fK).fromJson(t,r)}static fromJsonString(t,r){return(new fK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fK,t,r)}static $(){return["ListGrokFilesResponse|1 team_linked 8|2 user_linked 8|3 files #0*|4 next_token 9?|5 can_manage 8|6 zero_data_retention 8",cK]}}class dK extends T{constructor(t){super(),this.teamId=0,this.fileId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dK).fromBinary(t,r)}static fromJson(t,r){return(new dK).fromJson(t,r)}static fromJsonString(t,r){return(new dK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dK,t,r)}static $(){return["GetGrokFileRequest|1 team_id 5|2 file_id 9"]}}class pK extends T{constructor(t){super(),this.canManage=!1,this.teamLinked=!1,this.userLinked=!1,this.zeroDataRetention=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pK).fromBinary(t,r)}static fromJson(t,r){return(new pK).fromJson(t,r)}static fromJsonString(t,r){return(new pK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pK,t,r)}static $(){return["GetGrokFileResponse|1 file #0|2 can_manage 8|3 team_linked 8|4 user_linked 8|5 zero_data_retention 8",cK]}}class hK extends T{constructor(t){super(),this.teamId=0,this.fileId="",this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hK).fromBinary(t,r)}static fromJson(t,r){return(new hK).fromJson(t,r)}static fromJsonString(t,r){return(new hK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hK,t,r)}static $(){return["UpdateGrokFileRequest|1 team_id 5|2 file_id 9|3 name 9"]}}class gK extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gK).fromBinary(t,r)}static fromJson(t,r){return(new gK).fromJson(t,r)}static fromJsonString(t,r){return(new gK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gK,t,r)}static $(){return["UpdateGrokFileResponse|1 file #0",cK]}}class _K extends T{constructor(t){super(),this.teamId=0,this.fileId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _K).fromBinary(t,r)}static fromJson(t,r){return(new _K).fromJson(t,r)}static fromJsonString(t,r){return(new _K).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_K,t,r)}static $(){return["DeleteGrokFileRequest|1 team_id 5|2 file_id 9"]}}class JK extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new JK).fromBinary(t,r)}static fromJson(t,r){return(new JK).fromJson(t,r)}static fromJsonString(t,r){return(new JK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(JK,t,r)}static $(){return["DeleteGrokFileResponse"]}}class wK extends T{constructor(t){super(),this.teamId=0,this.fileId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wK).fromBinary(t,r)}static fromJson(t,r){return(new wK).fromJson(t,r)}static fromJsonString(t,r){return(new wK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wK,t,r)}static $(){return["CreateGrokFilePublicUrlRequest|1 team_id 5|2 file_id 9|3 expires_after_seconds 3?"]}}class yK extends T{constructor(t){super(),this.publicUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yK).fromBinary(t,r)}static fromJson(t,r){return(new yK).fromJson(t,r)}static fromJsonString(t,r){return(new yK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yK,t,r)}static $(){return["CreateGrokFilePublicUrlResponse|1 public_url 9|2 expires_at #0?",n.Timestamp]}}class SK extends T{constructor(t){super(),this.teamId=0,this.fileId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new SK).fromBinary(t,r)}static fromJson(t,r){return(new SK).fromJson(t,r)}static fromJsonString(t,r){return(new SK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(SK,t,r)}static $(){return["RevokeGrokFilePublicUrlRequest|1 team_id 5|2 file_id 9"]}}class qK extends T{constructor(t){super(),this.fileId="",this.revoked=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qK).fromBinary(t,r)}static fromJson(t,r){return(new qK).fromJson(t,r)}static fromJsonString(t,r){return(new qK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qK,t,r)}static $(){return["RevokeGrokFilePublicUrlResponse|1 file_id 9|2 revoked 8|3 public_url 9?"]}}class BK extends T{constructor(t){super(),this.modelName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new BK).fromBinary(t,r)}static fromJson(t,r){return(new BK).fromJson(t,r)}static fromJsonString(t,r){return(new BK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(BK,t,r)}static $(){return["GrokCollectionIndexConfiguration|1 model_name 9"]}}class IK extends T{constructor(t){super(),this.maxChunkSizeTokens=0,this.chunkOverlapTokens=0,this.encodingName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new IK).fromBinary(t,r)}static fromJson(t,r){return(new IK).fromJson(t,r)}static fromJsonString(t,r){return(new IK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(IK,t,r)}static $(){return["GrokCollectionTokensConfiguration|1 max_chunk_size_tokens 5|2 chunk_overlap_tokens 5|3 encoding_name 9"]}}class PK extends T{constructor(t){super(),this.maxChunkSizeChars=0,this.chunkOverlapChars=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new PK).fromBinary(t,r)}static fromJson(t,r){return(new PK).fromJson(t,r)}static fromJsonString(t,r){return(new PK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(PK,t,r)}static $(){return["GrokCollectionCharsConfiguration|1 max_chunk_size_chars 5|2 chunk_overlap_chars 5"]}}class bK extends T{constructor(t){super(),this.maxChunkSizeBytes=0,this.chunkOverlapBytes=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bK).fromBinary(t,r)}static fromJson(t,r){return(new bK).fromJson(t,r)}static fromJsonString(t,r){return(new bK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bK,t,r)}static $(){return["GrokCollectionBytesConfiguration|1 max_chunk_size_bytes 5|2 chunk_overlap_bytes 5"]}}class RK extends T{constructor(t){super(),this.stripWhitespace=!1,this.injectNameIntoChunks=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new RK).fromBinary(t,r)}static fromJson(t,r){return(new RK).fromJson(t,r)}static fromJsonString(t,r){return(new RK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(RK,t,r)}static $(){return["GrokCollectionChunkConfiguration|1 tokens_configuration #0|2 strip_whitespace 8|3 inject_name_into_chunks 8|4 bytes_configuration #1|5 chars_configuration #2",IK,bK,PK]}}class vK extends T{constructor(t){super(),this.key="",this.required=!1,this.injectIntoChunk=!1,this.unique=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vK).fromBinary(t,r)}static fromJson(t,r){return(new vK).fromJson(t,r)}static fromJsonString(t,r){return(new vK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vK,t,r)}static $(){return["GrokCollectionFieldDefinition|1 key 9|2 required 8|3 inject_into_chunk 8|4 unique 8|5 description 9?"]}}class xK extends T{constructor(t){super(),this.operation=cn.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xK).fromBinary(t,r)}static fromJson(t,r){return(new xK).fromJson(t,r)}static fromJsonString(t,r){return(new xK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xK,t,r)}static $(){return["GrokCollectionFieldDefinitionUpdate|1 field_definition #0|2 operation #1",vK,cn]}}class kK extends T{constructor(t){super(),this.collectionId="",this.collectionName="",this.documentsCount=0,this.fieldDefinitions=[],this.totalFileSize=n.protoInt64.zero,this.disableRagLookup=!1,this.effectivePrivilege=0,this.isOwned=!1,this.ownerTeamId="",this.isEstimated=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kK).fromBinary(t,r)}static fromJson(t,r){return(new kK).fromJson(t,r)}static fromJsonString(t,r){return(new kK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kK,t,r)}static $(){return["GrokCollection|1 collection_id 9|2 collection_name 9|3 created_at #0|4 index_configuration #1|5 chunk_configuration #2|6 documents_count 5|7 field_definitions #3*|8 collection_description 9?|9 total_file_size 3|10 cloned_from_id 9?|11 lineage_group_id 9?|12 clone_version 9?|13 disable_rag_lookup 8|14 effective_privilege 5|15 is_owned 8|16 owner_team_id 9|17 is_estimated 8",n.Timestamp,BK,RK,vK]}}class EK extends T{constructor(t){super(),this.fields={},this.status=mn.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new EK).fromBinary(t,r)}static fromJson(t,r){return(new EK).fromJson(t,r)}static fromJsonString(t,r){return(new EK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(EK,t,r)}static $(){return["GrokCollectionDocument|1 file_metadata #0|2 fields 9,9|3 status #1|4 error_message 9?|5 last_indexed_at #2|6 chunk_count 5?|7 chunks_processed_count 3?",cK,mn,n.Timestamp]}}class CK extends T{constructor(t){super(),this.teamId=0,this.limit=0,this.order=un.UNSPECIFIED,this.sortBy=ln.UNSPECIFIED,this.filter="",this.includeShared=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new CK).fromBinary(t,r)}static fromJson(t,r){return(new CK).fromJson(t,r)}static fromJsonString(t,r){return(new CK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(CK,t,r)}static $(){return["ListGrokCollectionsRequest|1 team_id 5|2 limit 5|3 pagination_token 9?|4 order #0|5 sort_by #1|6 filter 9|7 include_shared 8",un,ln]}}class TK extends T{constructor(t){super(),this.teamLinked=!1,this.userLinked=!1,this.collections=[],this.canManage=!1,this.zeroDataRetention=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new TK).fromBinary(t,r)}static fromJson(t,r){return(new TK).fromJson(t,r)}static fromJsonString(t,r){return(new TK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(TK,t,r)}static $(){return["ListGrokCollectionsResponse|1 team_linked 8|2 user_linked 8|3 collections #0*|4 pagination_token 9?|5 can_manage 8|6 zero_data_retention 8",kK]}}class UK extends T{constructor(t){super(),this.teamId=0,this.collectionId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new UK).fromBinary(t,r)}static fromJson(t,r){return(new UK).fromJson(t,r)}static fromJsonString(t,r){return(new UK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(UK,t,r)}static $(){return["GetGrokCollectionRequest|1 team_id 5|2 collection_id 9"]}}class AK extends T{constructor(t){super(),this.canManage=!1,this.teamLinked=!1,this.userLinked=!1,this.zeroDataRetention=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new AK).fromBinary(t,r)}static fromJson(t,r){return(new AK).fromJson(t,r)}static fromJsonString(t,r){return(new AK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(AK,t,r)}static $(){return["GetGrokCollectionResponse|1 collection #0|2 can_manage 8|3 team_linked 8|4 user_linked 8|5 zero_data_retention 8",kK]}}class $K extends T{constructor(t){super(),this.teamId=0,this.collectionName="",this.fieldDefinitions=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $K).fromBinary(t,r)}static fromJson(t,r){return(new $K).fromJson(t,r)}static fromJsonString(t,r){return(new $K).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($K,t,r)}static $(){return["CreateGrokCollectionRequest|1 team_id 5|2 collection_name 9|3 collection_description 9?|4 index_configuration #0|5 chunk_configuration #1|6 field_definitions #2*",BK,RK,vK]}}class MK extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new MK).fromBinary(t,r)}static fromJson(t,r){return(new MK).fromJson(t,r)}static fromJsonString(t,r){return(new MK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(MK,t,r)}static $(){return["CreateGrokCollectionResponse|1 collection #0",kK]}}class OK extends T{constructor(t){super(),this.teamId=0,this.collectionId="",this.disableRagLookup=!1,this.fieldDefinitionUpdates=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new OK).fromBinary(t,r)}static fromJson(t,r){return(new OK).fromJson(t,r)}static fromJsonString(t,r){return(new OK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(OK,t,r)}static $(){return["UpdateGrokCollectionRequest|1 team_id 5|2 collection_id 9|3 collection_name 9?|4 collection_description 9?|5 disable_rag_lookup 8|6 field_definition_updates #0*|7 chunk_configuration #1",xK,RK]}}class DK extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new DK).fromBinary(t,r)}static fromJson(t,r){return(new DK).fromJson(t,r)}static fromJsonString(t,r){return(new DK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(DK,t,r)}static $(){return["UpdateGrokCollectionResponse|1 collection #0",kK]}}class NK extends T{constructor(t){super(),this.teamId=0,this.collectionId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new NK).fromBinary(t,r)}static fromJson(t,r){return(new NK).fromJson(t,r)}static fromJsonString(t,r){return(new NK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(NK,t,r)}static $(){return["DeleteGrokCollectionRequest|1 team_id 5|2 collection_id 9"]}}class GK extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new GK).fromBinary(t,r)}static fromJson(t,r){return(new GK).fromJson(t,r)}static fromJsonString(t,r){return(new GK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(GK,t,r)}static $(){return["DeleteGrokCollectionResponse"]}}class LK extends T{constructor(t){super(),this.teamId=0,this.collectionId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new LK).fromBinary(t,r)}static fromJson(t,r){return(new LK).fromJson(t,r)}static fromJsonString(t,r){return(new LK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(LK,t,r)}static $(){return["CloneGrokCollectionRequest|1 team_id 5|2 collection_id 9|3 collection_name 9?"]}}class FK extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new FK).fromBinary(t,r)}static fromJson(t,r){return(new FK).fromJson(t,r)}static fromJsonString(t,r){return(new FK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(FK,t,r)}static $(){return["CloneGrokCollectionResponse|1 collection #0",kK]}}class KK extends T{constructor(t){super(),this.teamId=0,this.collectionId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new KK).fromBinary(t,r)}static fromJson(t,r){return(new KK).fromJson(t,r)}static fromJsonString(t,r){return(new KK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(KK,t,r)}static $(){return["GenerateGrokCollectionDescriptionRequest|1 team_id 5|2 collection_id 9"]}}class zK extends T{constructor(t){super(),this.collectionDescription="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zK).fromBinary(t,r)}static fromJson(t,r){return(new zK).fromJson(t,r)}static fromJsonString(t,r){return(new zK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zK,t,r)}static $(){return["GenerateGrokCollectionDescriptionResponse|1 collection_description 9"]}}class jK extends T{constructor(t){super(),this.collectionId="",this.collectionName="",this.documentsCount=0,this.disableRagLookup=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jK).fromBinary(t,r)}static fromJson(t,r){return(new jK).fromJson(t,r)}static fromJsonString(t,r){return(new jK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jK,t,r)}static $(){return["GrokRelatedCollection|1 collection_id 9|2 collection_name 9|3 created_at #0|4 cloned_from_id 9?|5 documents_count 5|6 clone_version 9?|7 disable_rag_lookup 8",n.Timestamp]}}class HK extends T{constructor(t){super(),this.teamId=0,this.collectionId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new HK).fromBinary(t,r)}static fromJson(t,r){return(new HK).fromJson(t,r)}static fromJsonString(t,r){return(new HK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(HK,t,r)}static $(){return["ListRelatedGrokCollectionsRequest|1 team_id 5|2 collection_id 9"]}}class WK extends T{constructor(t){super(),this.lineageGroupId="",this.collections=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new WK).fromBinary(t,r)}static fromJson(t,r){return(new WK).fromJson(t,r)}static fromJsonString(t,r){return(new WK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(WK,t,r)}static $(){return["ListRelatedGrokCollectionsResponse|1 lineage_group_id 9|2 collections #0*",jK]}}class QK extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new QK).fromBinary(t,r)}static fromJson(t,r){return(new QK).fromJson(t,r)}static fromJsonString(t,r){return(new QK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(QK,t,r)}static $(){return["ListGrokCollectionEmbeddingModelsRequest|1 team_id 5"]}}class VK extends T{constructor(t){super(),this.embeddingModels=[],this.chunkConfigEditable=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new VK).fromBinary(t,r)}static fromJson(t,r){return(new VK).fromJson(t,r)}static fromJsonString(t,r){return(new VK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(VK,t,r)}static $(){return["ListGrokCollectionEmbeddingModelsResponse|1 embedding_models 9*|2 chunk_config_editable 8"]}}class XK extends T{constructor(t){super(),this.teamId=0,this.collectionId="",this.limit=0,this.order=un.UNSPECIFIED,this.sortBy=an.UNSPECIFIED,this.filter="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new XK).fromBinary(t,r)}static fromJson(t,r){return(new XK).fromJson(t,r)}static fromJsonString(t,r){return(new XK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(XK,t,r)}static $(){return["ListGrokCollectionDocumentsRequest|1 team_id 5|2 collection_id 9|3 limit 5|4 pagination_token 9?|5 order #0|6 sort_by #1|7 filter 9",un,an]}}class YK extends T{constructor(t){super(),this.teamLinked=!1,this.userLinked=!1,this.documents=[],this.canManage=!1,this.zeroDataRetention=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new YK).fromBinary(t,r)}static fromJson(t,r){return(new YK).fromJson(t,r)}static fromJsonString(t,r){return(new YK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(YK,t,r)}static $(){return["ListGrokCollectionDocumentsResponse|1 team_linked 8|2 user_linked 8|3 documents #0*|4 pagination_token 9?|5 can_manage 8|6 zero_data_retention 8",EK]}}class ZK extends T{constructor(t){super(),this.teamId=0,this.collectionId="",this.fileIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ZK).fromBinary(t,r)}static fromJson(t,r){return(new ZK).fromJson(t,r)}static fromJsonString(t,r){return(new ZK).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ZK,t,r)}static $(){return["BatchGetGrokCollectionDocumentsRequest|1 team_id 5|2 collection_id 9|3 file_ids 9*"]}}class tz extends T{constructor(t){super(),this.documents=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tz).fromBinary(t,r)}static fromJson(t,r){return(new tz).fromJson(t,r)}static fromJsonString(t,r){return(new tz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tz,t,r)}static $(){return["BatchGetGrokCollectionDocumentsResponse|1 documents #0*",EK]}}class rz extends T{constructor(t){super(),this.teamId=0,this.collectionId="",this.fileId="",this.fields={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rz).fromBinary(t,r)}static fromJson(t,r){return(new rz).fromJson(t,r)}static fromJsonString(t,r){return(new rz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rz,t,r)}static $(){return["AddGrokCollectionDocumentRequest|1 team_id 5|2 collection_id 9|3 file_id 9|4 fields 9,9"]}}class ez extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ez).fromBinary(t,r)}static fromJson(t,r){return(new ez).fromJson(t,r)}static fromJsonString(t,r){return(new ez).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ez,t,r)}static $(){return["AddGrokCollectionDocumentResponse"]}}class nz extends T{constructor(t){super(),this.teamId=0,this.collectionId="",this.fileId="",this.fields={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nz).fromBinary(t,r)}static fromJson(t,r){return(new nz).fromJson(t,r)}static fromJsonString(t,r){return(new nz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nz,t,r)}static $(){return["UpdateGrokCollectionDocumentRequest|1 team_id 5|2 collection_id 9|3 file_id 9|4 name 9?|5 fields 9,9"]}}class sz extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sz).fromBinary(t,r)}static fromJson(t,r){return(new sz).fromJson(t,r)}static fromJsonString(t,r){return(new sz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sz,t,r)}static $(){return["UpdateGrokCollectionDocumentResponse|1 document #0",EK]}}class iz extends T{constructor(t){super(),this.teamId=0,this.collectionId="",this.fileId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new iz).fromBinary(t,r)}static fromJson(t,r){return(new iz).fromJson(t,r)}static fromJsonString(t,r){return(new iz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(iz,t,r)}static $(){return["RemoveGrokCollectionDocumentRequest|1 team_id 5|2 collection_id 9|3 file_id 9"]}}class oz extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oz).fromBinary(t,r)}static fromJson(t,r){return(new oz).fromJson(t,r)}static fromJsonString(t,r){return(new oz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oz,t,r)}static $(){return["RemoveGrokCollectionDocumentResponse"]}}class az extends T{constructor(t){super(),this.teamId=0,this.collectionId="",this.fileId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new az).fromBinary(t,r)}static fromJson(t,r){return(new az).fromJson(t,r)}static fromJsonString(t,r){return(new az).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(az,t,r)}static $(){return["ReindexGrokCollectionDocumentRequest|1 team_id 5|2 collection_id 9|3 file_id 9"]}}class uz extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uz).fromBinary(t,r)}static fromJson(t,r){return(new uz).fromJson(t,r)}static fromJsonString(t,r){return(new uz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uz,t,r)}static $(){return["ReindexGrokCollectionDocumentResponse"]}}class cz extends T{constructor(t){super(),this.teamId=0,this.cluster="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cz).fromBinary(t,r)}static fromJson(t,r){return(new cz).fromJson(t,r)}static fromJsonString(t,r){return(new cz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cz,t,r)}static $(){return["ListGrokModelsRequest|1 team_id 5|2 cluster 9"]}}class lz extends T{constructor(t){super(),this.teamLinked=!1,this.userLinked=!1,this.clusters=[],this.groups=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lz).fromBinary(t,r)}static fromJson(t,r){return(new lz).fromJson(t,r)}static fromJsonString(t,r){return(new lz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lz,t,r)}static $(){return["ListGrokModelsResponse|1 team_linked 8|2 user_linked 8|3 clusters 9*|4 groups #0*|5 team_tier 5?",mz]}}class mz extends T{constructor(t){super(),this.type=fn.UNSPECIFIED,this.models=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mz).fromBinary(t,r)}static fromJson(t,r){return(new mz).fromJson(t,r)}static fromJsonString(t,r){return(new mz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mz,t,r)}static $(){return["GrokModelGroup|1 type #0|2 models #1*",fn,pz]}}class fz extends T{constructor(t){super(),this.resolution="",this.usdCents=0,this.price=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fz).fromBinary(t,r)}static fromJson(t,r){return(new fz).fromJson(t,r)}static fromJsonString(t,r){return(new fz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fz,t,r)}static $(){return["GrokModelResolutionPrice|1 resolution 9|2 usd_cents 1|3 price 3"]}}class dz extends T{constructor(t){super(),this.outputByResolution=[],this.longContextPricing=!1,this.longContextThresholdTokens=n.protoInt64.zero,this.promptTextTokenPrice=n.protoInt64.zero,this.cachedPromptTokenPrice=n.protoInt64.zero,this.promptTextTokenPriceLongContext=n.protoInt64.zero,this.cachedPromptTokenPriceLongContext=n.protoInt64.zero,this.completionTextTokenPrice=n.protoInt64.zero,this.completionTokenPriceLongContext=n.protoInt64.zero,this.promptTokenPrice=n.protoInt64.zero,this.completionTokenPrice=n.protoInt64.zero,this.imagePrice=n.protoInt64.zero,this.pricePerInputImage=n.protoInt64.zero,this.pricePerInputVideoSecond=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dz).fromBinary(t,r)}static fromJson(t,r){return(new dz).fromJson(t,r)}static fromJsonString(t,r){return(new dz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dz,t,r)}static $(){return["GrokModelPricing|1 input_usd_cents 1?|2 cached_input_usd_cents 1?|3 output_usd_cents 1?|4 image_input_usd_cents 1?|5 video_input_usd_cents 1?|6 output_by_resolution #0*|7 long_context_pricing 8|8 long_context_threshold_tokens 3|9 prompt_text_token_price 3|10 cached_prompt_token_price 3|11 prompt_text_token_price_long_context 3|12 cached_prompt_token_price_long_context 3|13 completion_text_token_price 3|14 completion_token_price_long_context 3|15 prompt_token_price 3|16 completion_token_price 3|17 image_price 3|18 price_per_input_image 3|19 price_per_input_video_second 3",fz]}}class pz extends T{constructor(t){super(),this.name="",this.cluster="",this.showsCluster=!1,this.inputModalities=[],this.outputModalities=[],this.functionCalling=!1,this.structuredOutputs=!1,this.reasoning=!1,this.contextTokens=0,this.rps=n.protoInt64.zero,this.rpm=n.protoInt64.zero,this.tpm=n.protoInt64.zero,this.rph=n.protoInt64.zero,this.rpd=n.protoInt64.zero,this.tier=0,this.batchEnabled=!1,this.voiceEndpoints=[],this.aliases=[],this.supportedReasoningEfforts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pz).fromBinary(t,r)}static fromJson(t,r){return(new pz).fromJson(t,r)}static fromJsonString(t,r){return(new pz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pz,t,r)}static $(){return["GrokModel|1 name 9|2 cluster 9|3 shows_cluster 8|4 input_modalities #0*|5 output_modalities #0*|6 function_calling 8|7 structured_outputs 8|8 reasoning 8|9 context_tokens 5|10 pricing #1|11 rps 3|12 rpm 3|13 tpm 3|14 rph 3|15 rpd 3|16 tier 5|17 rate_limit_config #2|18 batch_enabled 8|19 batch_discount_percent 5?|20 voice_endpoints #3*|21 aliases 9*|22 supported_reasoning_efforts 9*|23 default_reasoning_effort 9?",dn,dz,gz,hz]}}class hz extends T{constructor(t){super(),this.kind=pn.UNSPECIFIED,this.rps=n.protoInt64.zero,this.rpm=n.protoInt64.zero,this.concurrentSessions=n.protoInt64.zero,this.perCharacter=n.protoInt64.zero,this.perAudioSecond=n.protoInt64.zero,this.perAudioSecondStreaming=n.protoInt64.zero,this.realtimeAudioSecondPrice=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hz).fromBinary(t,r)}static fromJson(t,r){return(new hz).fromJson(t,r)}static fromJsonString(t,r){return(new hz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hz,t,r)}static $(){return["GrokVoiceEndpoint|1 kind #0|2 rps 3|3 rpm 3|4 concurrent_sessions 3|5 per_character 3|6 per_audio_second 3|7 per_audio_second_streaming 3|8 realtime_audio_second_price 3",pn]}}class gz extends T{constructor(t){super(),this.queryOffset=n.protoInt64.zero,this.queryBaseRate=n.protoInt64.zero,this.queryMultiplier=n.protoInt64.zero,this.tokenOffset=n.protoInt64.zero,this.tokenBaseRate=n.protoInt64.zero,this.tokenMultiplier=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gz).fromBinary(t,r)}static fromJson(t,r){return(new gz).fromJson(t,r)}static fromJsonString(t,r){return(new gz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gz,t,r)}static $(){return["GrokModelRateLimitConfig|1 query_offset 3|2 query_base_rate 3|3 query_multiplier 3|4 token_offset 3|5 token_base_rate 3|6 token_multiplier 3"]}}class _z extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _z).fromBinary(t,r)}static fromJson(t,r){return(new _z).fromJson(t,r)}static fromJsonString(t,r){return(new _z).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_z,t,r)}static $(){return["GetGrokApiKeyAccessRequest|1 team_id 5"]}}class Jz extends T{constructor(t){super(),this.teamId=0,this.apiKeyId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jz).fromBinary(t,r)}static fromJson(t,r){return(new Jz).fromJson(t,r)}static fromJsonString(t,r){return(new Jz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jz,t,r)}static $(){return["GetGrokApiKeyPropagationRequest|1 team_id 5|2 api_key_id 9"]}}class wz extends T{constructor(t){super(),this.status=yz.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wz).fromBinary(t,r)}static fromJson(t,r){return(new wz).fromJson(t,r)}static fromJsonString(t,r){return(new wz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wz,t,r)}static $(){return["GetGrokApiKeyPropagationResponse|1 status #0",yz]}}var yz=(0,a.QT)(n.proto3,C,"GetGrokApiKeyPropagationResponse.Status",[[0,"UNSPECIFIED"],[1,"PENDING"],[2,"PROPAGATED"],[3,"UNKNOWN"]],1);class Sz extends T{constructor(t){super(),this.known=!1,this.canViewApiKeys=!1,this.canCreateApiKeys=!1,this.canViewManagementKeys=!1,this.canCreateManagementKeys=!1,this.canManageFiles=!1,this.allowAllModels=!1,this.allowAllEndpoints=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sz).fromBinary(t,r)}static fromJson(t,r){return(new Sz).fromJson(t,r)}static fromJsonString(t,r){return(new Sz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sz,t,r)}static $(){return["GetGrokApiKeyAccessResponse|1 known 8|2 can_view_api_keys 8|3 can_create_api_keys 8|4 can_view_management_keys 8|5 can_create_management_keys 8|6 can_manage_files 8|7 allow_all_models 8|8 allow_all_endpoints 8|9 personal_plan 8?"]}}class qz extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qz).fromBinary(t,r)}static fromJson(t,r){return(new qz).fromJson(t,r)}static fromJsonString(t,r){return(new qz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qz,t,r)}static $(){return["GetGrokTeamWatermarkingRequest|1 team_id 5"]}}class Bz extends T{constructor(t){super(),this.model="",this.state=Iz.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bz).fromBinary(t,r)}static fromJson(t,r){return(new Bz).fromJson(t,r)}static fromJsonString(t,r){return(new Bz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bz,t,r)}static $(){return["GrokWatermarkModel|1 model 9|2 state #0",Iz]}}var Iz=(0,a.QT)(n.proto3,C,"GrokWatermarkModel.State",[[0,"UNSPECIFIED"],[1,"ON"],[2,"OFF"],[3,"STAFF_LOCKED"]],1);class Pz extends T{constructor(t){super(),this.teamLinked=!1,this.userLinked=!1,this.canAdminister=!1,this.textModels=[],this.audioModels=[],this.canChange=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pz).fromBinary(t,r)}static fromJson(t,r){return(new Pz).fromJson(t,r)}static fromJsonString(t,r){return(new Pz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pz,t,r)}static $(){return["GetGrokTeamWatermarkingResponse|1 team_linked 8|2 user_linked 8|3 can_administer 8|4 text_models #0*|5 audio_models #0*|6 can_change 8",Bz]}}class bz extends T{constructor(t){super(),this.model="",this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bz).fromBinary(t,r)}static fromJson(t,r){return(new bz).fromJson(t,r)}static fromJsonString(t,r){return(new bz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bz,t,r)}static $(){return["GrokWatermarkModelChoice|1 model 9|2 enabled 8"]}}class Rz extends T{constructor(t){super(),this.teamId=0,this.textModels=[],this.audioModels=[],this.attestationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rz).fromBinary(t,r)}static fromJson(t,r){return(new Rz).fromJson(t,r)}static fromJsonString(t,r){return(new Rz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rz,t,r)}static $(){return["SetGrokTeamWatermarkingRequest|1 team_id 5|2 text_models #0*|3 audio_models #0*|4 attestation_id 9",bz]}}class vz extends T{constructor(t){super(),this.textModels=[],this.audioModels=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vz).fromBinary(t,r)}static fromJson(t,r){return(new vz).fromJson(t,r)}static fromJsonString(t,r){return(new vz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vz,t,r)}static $(){return["SetGrokTeamWatermarkingResponse|1 text_models #0*|2 audio_models #0*",Bz]}}class xz extends T{constructor(t){super(),this.teamId=0,this.statusOnly=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xz).fromBinary(t,r)}static fromJson(t,r){return(new xz).fromJson(t,r)}static fromJsonString(t,r){return(new xz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xz,t,r)}static $(){return["GetGrokTeamZdrRequest|1 team_id 5|2 status_only 8"]}}class kz extends T{constructor(t){super(),this.status=Ez.UNSPECIFIED,this.selfServeEligible=!1,this.legacyLocked=!1,this.storedData=Cz.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kz).fromBinary(t,r)}static fromJson(t,r){return(new kz).fromJson(t,r)}static fromJsonString(t,r){return(new kz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kz,t,r)}static $(){return["GrokTeamZdr|1 status #0|2 self_serve_eligible 8|3 legacy_locked 8|4 stored_data #1",Ez,Cz]}}var Ez=(0,a.QT)(n.proto3,C,"GrokTeamZdr.Status",[[0,"UNSPECIFIED"],[1,"OFF"],[2,"SELF_SERVE"],[3,"STAFF"]],1),Cz=(0,a.QT)(n.proto3,C,"GrokTeamZdr.StoredData",[[0,"UNSPECIFIED"],[1,"NONE"],[2,"FILES"],[3,"COLLECTIONS"],[4,"FILES_AND_COLLECTIONS"],[5,"CHECK_FAILED"]],1);class Tz extends T{constructor(t){super(),this.teamLinked=!1,this.userLinked=!1,this.canAdminister=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tz).fromBinary(t,r)}static fromJson(t,r){return(new Tz).fromJson(t,r)}static fromJsonString(t,r){return(new Tz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tz,t,r)}static $(){return["GetGrokTeamZdrResponse|1 team_linked 8|2 user_linked 8|3 can_administer 8|4 zdr #0",kz]}}class Uz extends T{constructor(t){super(),this.teamId=0,this.enabled=!1,this.termsId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Uz).fromBinary(t,r)}static fromJson(t,r){return(new Uz).fromJson(t,r)}static fromJsonString(t,r){return(new Uz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Uz,t,r)}static $(){return["SetGrokTeamZdrRequest|1 team_id 5|2 enabled 8|3 terms_id 9"]}}class Az extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Az).fromBinary(t,r)}static fromJson(t,r){return(new Az).fromJson(t,r)}static fromJsonString(t,r){return(new Az).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Az,t,r)}static $(){return["SetGrokTeamZdrResponse|1 zdr #0",kz]}}class $z extends T{constructor(t){super(),this.serviceAccountId="",this.name="",this.serviceType="",this.owningTeamId=0,this.joinedAt=n.protoInt64.zero,this.archived=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $z).fromBinary(t,r)}static fromJson(t,r){return(new $z).fromJson(t,r)}static fromJsonString(t,r){return(new $z).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($z,t,r)}static $(){return["TeamGroupServiceAccountMember|1 service_account_id 9|2 name 9|3 service_type 9|4 owning_team_id 5|5 owning_team_name 9?|6 joined_at 3|7 archived 8"]}}class Mz extends T{constructor(t){super(),this.teamId=0,this.groupPublicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mz).fromBinary(t,r)}static fromJson(t,r){return(new Mz).fromJson(t,r)}static fromJsonString(t,r){return(new Mz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mz,t,r)}static $(){return["GetTeamGroupServiceAccountMembersRequest|1 team_id 5|2 group_public_id 9"]}}class Oz extends T{constructor(t){super(),this.serviceAccounts=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Oz).fromBinary(t,r)}static fromJson(t,r){return(new Oz).fromJson(t,r)}static fromJsonString(t,r){return(new Oz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Oz,t,r)}static $(){return["GetTeamGroupServiceAccountMembersResponse|1 service_accounts #0*",$z]}}class Dz extends T{constructor(t){super(),this.teamId=0,this.groupId=n.protoInt64.zero,this.serviceAccountIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dz).fromBinary(t,r)}static fromJson(t,r){return(new Dz).fromJson(t,r)}static fromJsonString(t,r){return(new Dz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dz,t,r)}static $(){return["AddTeamGroupServiceAccountsRequest|1 team_id 5|2 group_id 3|3 service_account_ids 9*"]}}class Nz extends T{constructor(t){super(),this.addedCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nz).fromBinary(t,r)}static fromJson(t,r){return(new Nz).fromJson(t,r)}static fromJsonString(t,r){return(new Nz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nz,t,r)}static $(){return["AddTeamGroupServiceAccountsResponse|1 added_count 5"]}}class Gz extends T{constructor(t){super(),this.teamId=0,this.groupId=n.protoInt64.zero,this.serviceAccountIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gz).fromBinary(t,r)}static fromJson(t,r){return(new Gz).fromJson(t,r)}static fromJsonString(t,r){return(new Gz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gz,t,r)}static $(){return["RemoveTeamGroupServiceAccountsRequest|1 team_id 5|2 group_id 3|3 service_account_ids 9*"]}}class Lz extends T{constructor(t){super(),this.removedCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lz).fromBinary(t,r)}static fromJson(t,r){return(new Lz).fromJson(t,r)}static fromJsonString(t,r){return(new Lz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Lz,t,r)}static $(){return["RemoveTeamGroupServiceAccountsResponse|1 removed_count 5"]}}class Fz extends T{constructor(t){super(),this.title="",this.body="",this.supportUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fz).fromBinary(t,r)}static fromJson(t,r){return(new Fz).fromJson(t,r)}static fromJsonString(t,r){return(new Fz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fz,t,r)}static $(){return["SuperGrokHeavyUltraEndedNotice|1 title 9|2 body 9|3 continue_unification_url 9?|4 support_url 9"]}}class Kz extends T{constructor(t){super(),this.allTeams=!1,this.teamIds=[],this.groupIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kz).fromBinary(t,r)}static fromJson(t,r){return(new Kz).fromJson(t,r)}static fromJsonString(t,r){return(new Kz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Kz,t,r)}static $(){return["PrivateInferenceAssignment|1 all_teams 8|2 team_ids 5*|3 group_ids 3*"]}}class zz extends T{constructor(t){super(),this.bugReportsAllowed=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zz).fromBinary(t,r)}static fromJson(t,r){return(new zz).fromJson(t,r)}static fromJsonString(t,r){return(new zz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zz,t,r)}static $(){return["PrivateInferencePolicy|1 enrolled #0|2 can_switch #0|3 bug_reports_allowed 8",Kz]}}class jz extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jz).fromBinary(t,r)}static fromJson(t,r){return(new jz).fromJson(t,r)}static fromJsonString(t,r){return(new jz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jz,t,r)}static $(){return["GetOrganizationPrivateInferencePolicyRequest|1 organization_id 9"]}}class Hz extends T{constructor(t){super(),this.enabled=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hz).fromBinary(t,r)}static fromJson(t,r){return(new Hz).fromJson(t,r)}static fromJsonString(t,r){return(new Hz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hz,t,r)}static $(){return["GetOrganizationPrivateInferencePolicyResponse|4 enabled 8|3 policy #0",zz]}}class Wz extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wz).fromBinary(t,r)}static fromJson(t,r){return(new Wz).fromJson(t,r)}static fromJsonString(t,r){return(new Wz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wz,t,r)}static $(){return["UpdateOrganizationPrivateInferencePolicyRequest|1 organization_id 9|2 policy #0",zz]}}class Qz extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qz).fromBinary(t,r)}static fromJson(t,r){return(new Qz).fromJson(t,r)}static fromJsonString(t,r){return(new Qz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qz,t,r)}static $(){return["UpdateOrganizationPrivateInferencePolicyResponse|1 policy #0",zz]}}class Vz extends T{constructor(t){super(),this.organizationId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vz).fromBinary(t,r)}static fromJson(t,r){return(new Vz).fromJson(t,r)}static fromJsonString(t,r){return(new Vz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vz,t,r)}static $(){return["GetOrganizationPrivateInferenceTeamGroupsRequest|1 organization_id 9"]}}class Xz extends T{constructor(t){super(),this.id=n.protoInt64.zero,this.name="",this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xz).fromBinary(t,r)}static fromJson(t,r){return(new Xz).fromJson(t,r)}static fromJsonString(t,r){return(new Xz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xz,t,r)}static $(){return["PrivateInferenceTeamGroup|1 id 3|2 name 9|3 team_id 5"]}}class Yz extends T{constructor(t){super(),this.groups=[],this.unavailableTeamIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yz).fromBinary(t,r)}static fromJson(t,r){return(new Yz).fromJson(t,r)}static fromJsonString(t,r){return(new Yz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yz,t,r)}static $(){return["GetOrganizationPrivateInferenceTeamGroupsResponse|1 groups #0*|2 unavailable_team_ids 5*",Xz]}}class Zz extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zz).fromBinary(t,r)}static fromJson(t,r){return(new Zz).fromJson(t,r)}static fromJsonString(t,r){return(new Zz).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zz,t,r)}static $(){return["GetTeamPrivateInferencePolicyRequest|1 team_id 5"]}}class tj extends T{constructor(t){super(),this.enabled=!1,this.managedByOrganization=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tj).fromBinary(t,r)}static fromJson(t,r){return(new tj).fromJson(t,r)}static fromJsonString(t,r){return(new tj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tj,t,r)}static $(){return["GetTeamPrivateInferencePolicyResponse|5 enabled 8|3 managed_by_organization 8|4 policy #0?",zz]}}class rj extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rj).fromBinary(t,r)}static fromJson(t,r){return(new rj).fromJson(t,r)}static fromJsonString(t,r){return(new rj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rj,t,r)}static $(){return["UpdateTeamPrivateInferencePolicyRequest|1 team_id 5|2 policy #0",zz]}}class ej extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ej).fromBinary(t,r)}static fromJson(t,r){return(new ej).fromJson(t,r)}static fromJsonString(t,r){return(new ej).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ej,t,r)}static $(){return["UpdateTeamPrivateInferencePolicyResponse|1 policy #0",zz]}}class nj extends T{constructor(t){super(),this.storeId="",this.canvasId="",this.slug="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nj).fromBinary(t,r)}static fromJson(t,r){return(new nj).fromJson(t,r)}static fromJsonString(t,r){return(new nj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nj,t,r)}static $(){return["SetPageAddressRequest|1 store_id 9|2 canvas_id 9|3 slug 9"]}}class sj extends T{constructor(t){super(),this.slug="",this.pageUrl="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sj).fromBinary(t,r)}static fromJson(t,r){return(new sj).fromJson(t,r)}static fromJsonString(t,r){return(new sj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sj,t,r)}static $(){return["SetPageAddressResponse|1 slug 9|2 page_url 9"]}}class ij extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ij).fromBinary(t,r)}static fromJson(t,r){return(new ij).fromJson(t,r)}static fromJsonString(t,r){return(new ij).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ij,t,r)}static $(){return["SetSlackCursorTeamRequest|1 cursor_team_id 5?"]}}class oj extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oj).fromBinary(t,r)}static fromJson(t,r){return(new oj).fromJson(t,r)}static fromJsonString(t,r){return(new oj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oj,t,r)}static $(){return["SetSlackCursorTeamResponse"]}}class aj extends T{constructor(t){super(),this.userId=n.protoInt64.zero,this.name="",this.email="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aj).fromBinary(t,r)}static fromJson(t,r){return(new aj).fromJson(t,r)}static fromJsonString(t,r){return(new aj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(aj,t,r)}static $(){return["DashboardAppOwner|1 user_id 3|2 name 9|3 email 9"]}}class uj extends T{constructor(t){super(),this.slug="",this.apex="",this.displayName="",this.url="",this.visibility=P.UNSPECIFIED,this.updatedAtMs=n.protoInt64.zero,this.status=I.UNSPECIFIED,this.lastDeployedAtMs=n.protoInt64.zero,this.teamId=n.protoInt64.zero,this.teamName="",this.projectDir="",this.id="",this.needsReview=!1,this.lastPublishBlockedByReview=!1,this.draft=!1,this.retentionUnpublishAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uj).fromBinary(t,r)}static fromJson(t,r){return(new uj).fromJson(t,r)}static fromJsonString(t,r){return(new uj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(uj,t,r)}static $(){return["DashboardApp|1 slug 9|2 apex 9|3 display_name 9|4 url 9|5 visibility #0|6 owner #1|7 updated_at_ms 3|8 status #2|9 last_deployed_at_ms 3|10 team_id 3|11 team_name 9|12 project_dir 9|13 id 9|14 disabled_by_cursor #3|15 needs_review 8|16 last_publish_blocked_by_review 8|17 draft 8|18 retention_unpublish_at_ms 3",P,aj,I,x]}}class cj extends T{constructor(t){super(),this.scope=hn.UNSPECIFIED,this.search="",this.pageSize=0,this.pageToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cj).fromBinary(t,r)}static fromJson(t,r){return(new cj).fromJson(t,r)}static fromJsonString(t,r){return(new cj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cj,t,r)}static $(){return["ListDashboardAppsRequest|1 scope #0|2 search 9|3 page_size 5|4 page_token 9",hn]}}class lj extends T{constructor(t){super(),this.apps=[],this.nextPageToken="",this.totalCount=0,this.teamScopeAvailable=!1,this.disabledByCursorCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lj).fromBinary(t,r)}static fromJson(t,r){return(new lj).fromJson(t,r)}static fromJsonString(t,r){return(new lj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lj,t,r)}static $(){return["ListDashboardAppsResponse|1 apps #0*|2 next_page_token 9|3 total_count 5|4 team_scope_available 8|5 disabled_by_cursor_count 5",uj]}}class mj extends T{constructor(t){super(),this.publishId="",this.url="",this.status=I.UNSPECIFIED,this.commitSha="",this.dirty=!1,this.bcId="",this.errorMessage="",this.createdAtMs=n.protoInt64.zero,this.publishedByUserId=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mj).fromBinary(t,r)}static fromJson(t,r){return(new mj).fromJson(t,r)}static fromJsonString(t,r){return(new mj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mj,t,r)}static $(){return["DashboardAppDeployment|1 publish_id 9|2 url 9|3 status #0|4 commit_sha 9|5 dirty 8|6 bc_id 9|7 error_message 9|8 created_at_ms 3|9 published_by_user_id 3",I]}}class fj extends T{constructor(t){super(),this.name="",this.state=q.UNSPECIFIED,this.deployed=!1,this.updatedAtMs=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fj).fromBinary(t,r)}static fromJson(t,r){return(new fj).fromJson(t,r)}static fromJsonString(t,r){return(new fj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fj,t,r)}static $(){return["DashboardAppSecret|1 name 9|2 state #0|3 deployed 8|4 updated_at_ms 3",q]}}class dj extends T{constructor(t){super(),this.slug="",this.apex="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dj).fromBinary(t,r)}static fromJson(t,r){return(new dj).fromJson(t,r)}static fromJsonString(t,r){return(new dj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dj,t,r)}static $(){return["GetDashboardAppRequest|1 slug 9|2 apex 9"]}}class pj extends T{constructor(t){super(),this.previewUrl="",this.repoUrl="",this.deployments=[],this.secrets=[],this.viewerRole=gn.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pj).fromBinary(t,r)}static fromJson(t,r){return(new pj).fromJson(t,r)}static fromJsonString(t,r){return(new pj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pj,t,r)}static $(){return["GetDashboardAppResponse|1 app #0|2 preview_url 9|3 repo_url 9|4 deployments #1*|5 secrets #2*|6 security_review #3|7 viewer_role #4",uj,mj,fj,hj,gn]}}class hj extends T{constructor(t){super(),this.overridesAllowed=!1,this.overrides=[],this.lastBlockedFindings=[],this.viewerCanDecide=!1,this.approvableOverrideId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hj).fromBinary(t,r)}static fromJson(t,r){return(new hj).fromJson(t,r)}static fromJsonString(t,r){return(new hj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hj,t,r)}static $(){return["DashboardAppSecurityReview|1 overrides_allowed 8|2 overrides #0*|3 last_blocked_findings #1*|4 viewer_can_decide 8|5 approvable_override_id 9",gj,v]}}class gj extends T{constructor(t){super(),this.id="",this.state=B.UNSPECIFIED,this.slug="",this.apex="",this.visibility=P.UNSPECIFIED,this.findings=[],this.requestReason="",this.decisionReason="",this.selfApproved=!1,this.createdAtMs=n.protoInt64.zero,this.decidedAtMs=n.protoInt64.zero,this.expiresAtMs=n.protoInt64.zero,this.revokeReason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gj).fromBinary(t,r)}static fromJson(t,r){return(new gj).fromJson(t,r)}static fromJsonString(t,r){return(new gj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gj,t,r)}static $(){return["DashboardAppReviewOverride|1 id 9|2 state #0|3 slug 9|4 apex 9|5 owner #1|6 visibility #2|7 findings #3*|8 request_reason 9|9 decided_by #1|10 decision_reason 9|11 self_approved 8|12 created_at_ms 3|13 decided_at_ms 3|14 expires_at_ms 3|15 revoked_by #1|16 revoke_reason 9",B,aj,P,v]}}class _j extends T{constructor(t){super(),this.states=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _j).fromBinary(t,r)}static fromJson(t,r){return(new _j).fromJson(t,r)}static fromJsonString(t,r){return(new _j).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_j,t,r)}static $(){return["ListAppReviewOverridesRequest|1 states #0*",B]}}class Jj extends T{constructor(t){super(),this.overrides=[],this.overridesAllowed=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jj).fromBinary(t,r)}static fromJson(t,r){return(new Jj).fromJson(t,r)}static fromJsonString(t,r){return(new Jj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jj,t,r)}static $(){return["ListAppReviewOverridesResponse|1 overrides #0*|2 overrides_allowed 8",gj]}}class wj extends T{constructor(t){super(),this.overrideId="",this.approve=!1,this.reason="",this.confirmSlug="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wj).fromBinary(t,r)}static fromJson(t,r){return(new wj).fromJson(t,r)}static fromJsonString(t,r){return(new wj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wj,t,r)}static $(){return["DecideAppReviewOverrideRequest|1 override_id 9|2 approve 8|3 reason 9|4 confirm_slug 9"]}}class yj extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yj).fromBinary(t,r)}static fromJson(t,r){return(new yj).fromJson(t,r)}static fromJsonString(t,r){return(new yj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yj,t,r)}static $(){return["DecideAppReviewOverrideResponse|1 override #0",gj]}}class Sj extends T{constructor(t){super(),this.overrideId="",this.reason="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sj).fromBinary(t,r)}static fromJson(t,r){return(new Sj).fromJson(t,r)}static fromJsonString(t,r){return(new Sj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sj,t,r)}static $(){return["RevokeAppReviewOverrideRequest|1 override_id 9|2 reason 9"]}}class qj extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qj).fromBinary(t,r)}static fromJson(t,r){return(new qj).fromJson(t,r)}static fromJsonString(t,r){return(new qj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qj,t,r)}static $(){return["RevokeAppReviewOverrideResponse|1 override #0",gj]}}class Bj extends T{constructor(t){super(),this.overrideId="",this.reason="",this.confirmSlug="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bj).fromBinary(t,r)}static fromJson(t,r){return(new Bj).fromJson(t,r)}static fromJsonString(t,r){return(new Bj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bj,t,r)}static $(){return["GrantAppReviewOverrideRequest|1 override_id 9|2 reason 9|3 confirm_slug 9"]}}class Ij extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ij).fromBinary(t,r)}static fromJson(t,r){return(new Ij).fromJson(t,r)}static fromJsonString(t,r){return(new Ij).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ij,t,r)}static $(){return["GrantAppReviewOverrideResponse|1 override #0",gj]}}class Pj extends T{constructor(t){super(),this.owner={case:void 0},this.publicId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pj).fromBinary(t,r)}static fromJson(t,r){return(new Pj).fromJson(t,r)}static fromJsonString(t,r){return(new Pj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pj,t,r)}static $(){return["ListServiceTokenAppsRequest|1 current_user 8 owner|2 team_id 5 owner|3 organization_id 9 owner|4 public_id 9"]}}class bj extends T{constructor(t){super(),this.apps=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bj).fromBinary(t,r)}static fromJson(t,r){return(new bj).fromJson(t,r)}static fromJsonString(t,r){return(new bj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bj,t,r)}static $(){return["ListServiceTokenAppsResponse|1 apps #0*",uj]}}class Rj extends T{constructor(t){super(),this.owner={case:void 0},this.publicId="",this.appIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rj).fromBinary(t,r)}static fromJson(t,r){return(new Rj).fromJson(t,r)}static fromJsonString(t,r){return(new Rj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rj,t,r)}static $(){return["SetServiceTokenAppsRequest|1 current_user 8 owner|2 team_id 5 owner|3 organization_id 9 owner|4 public_id 9|5 app_ids 9*|6 castle_request_token 9?"]}}class vj extends T{constructor(t){super(),this.apps=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vj).fromBinary(t,r)}static fromJson(t,r){return(new vj).fromJson(t,r)}static fromJsonString(t,r){return(new vj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vj,t,r)}static $(){return["SetServiceTokenAppsResponse|1 apps #0*",uj]}}class xj extends T{constructor(t){super(),this.userId=0,this.name="",this.maskedKey="",this.createdAt=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xj).fromBinary(t,r)}static fromJson(t,r){return(new xj).fromJson(t,r)}static fromJsonString(t,r){return(new xj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xj,t,r)}static $(){return["MemberAppsApiKey|1 user_id 5|2 name 9|3 masked_key 9|4 created_at 3|5 expires_at 3?|6 revocable_service_token_public_id 9?"]}}class kj extends T{constructor(t){super(),this.teamId=0,this.slug="",this.apex="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kj).fromBinary(t,r)}static fromJson(t,r){return(new kj).fromJson(t,r)}static fromJsonString(t,r){return(new kj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kj,t,r)}static $(){return["ListAppMemberAppsApiKeysRequest|1 team_id 5|2 slug 9|3 apex 9"]}}class Ej extends T{constructor(t){super(),this.enabled=!1,this.keyAccess=_n.UNSPECIFIED,this.publicApp=!1,this.keys=[],this.truncated=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ej).fromBinary(t,r)}static fromJson(t,r){return(new Ej).fromJson(t,r)}static fromJsonString(t,r){return(new Ej).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ej,t,r)}static $(){return["ListAppMemberAppsApiKeysResponse|1 enabled 8|2 key_access #0|3 public_app 8|4 keys #1*|5 truncated 8",_n,xj]}}class Cj extends T{constructor(t){super(),this.teamId=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cj).fromBinary(t,r)}static fromJson(t,r){return(new Cj).fromJson(t,r)}static fromJsonString(t,r){return(new Cj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cj,t,r)}static $(){return["ListTeamAppsApiKeysRequest|1 team_id 5"]}}class Tj extends T{constructor(t){super(),this.enabled=!1,this.keyAccess=_n.UNSPECIFIED,this.keys=[],this.truncated=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tj).fromBinary(t,r)}static fromJson(t,r){return(new Tj).fromJson(t,r)}static fromJsonString(t,r){return(new Tj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tj,t,r)}static $(){return["ListTeamAppsApiKeysResponse|1 enabled 8|2 key_access #0|3 keys #1*|4 truncated 8",_n,xj]}}class Uj extends T{constructor(t){super(),this.list="",this.name="",this.reason="",this.allowedServerIdentifiers=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Uj).fromBinary(t,r)}static fromJson(t,r){return(new Uj).fromJson(t,r)}static fromJsonString(t,r){return(new Uj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Uj,t,r)}static $(){return["McpAllowlistInUse|1 list 9|2 name 9|3 reason 9|4 allowed_server_identifiers 9*"]}}class Aj extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Aj).fromBinary(t,r)}static fromJson(t,r){return(new Aj).fromJson(t,r)}static fromJsonString(t,r){return(new Aj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Aj,t,r)}static $(){return["ListXaiSessionsRequest"]}}class $j extends T{constructor(t){super(),this.sessions=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $j).fromBinary(t,r)}static fromJson(t,r){return(new $j).fromJson(t,r)}static fromJsonString(t,r){return(new $j).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($j,t,r)}static $(){return["ListXaiSessionsResponse|1 sessions #0*",Mj]}}class Mj extends T{constructor(t){super(),this.sessionId="",this.createdAt="",this.userAgent="",this.city="",this.country="",this.createdByCursor=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mj).fromBinary(t,r)}static fromJson(t,r){return(new Mj).fromJson(t,r)}static fromJsonString(t,r){return(new Mj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mj,t,r)}static $(){return["XaiSession|1 session_id 9|2 created_at 9|3 user_agent 9|4 city 9|5 country 9|6 created_by_cursor 8"]}}class Oj extends T{constructor(t){super(),this.sessionId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Oj).fromBinary(t,r)}static fromJson(t,r){return(new Oj).fromJson(t,r)}static fromJsonString(t,r){return(new Oj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Oj,t,r)}static $(){return["RevokeXaiSessionRequest|1 session_id 9"]}}class Dj extends T{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dj).fromBinary(t,r)}static fromJson(t,r){return(new Dj).fromJson(t,r)}static fromJsonString(t,r){return(new Dj).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dj,t,r)}static $(){return["RevokeXaiSessionResponse"]}}},"../proto/dist/generated/aiserver/v1/dashboard_service_connect.js"(t,r,e){e.d(r,{I:()=>zp});var n=e("../proto/dist/generated/aiserver/v1/dashboard_pb.js"),s=e("@bufbuild/protobuf"),i=e("../proto/dist/runtime/compact.js");const o="aiserver.v1.";class a extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",s.proto3)}static $p(){return o}}var u=(0,i.QT)(s.proto3,o,"UnifyEligibilityReason",[[0,"UNSPECIFIED"],[1,"BLOCKLISTED"],[2,"ENTERPRISE"],[3,"REQUEST_BASED_PRICING"],[4,"OUTSTANDING_INVOICE"],[5,"STRIPE_CREDIT_BALANCE"],[7,"UNSAFE_SUBSCRIPTION_STATUS"],[8,"ALIPAY_PAYMENT_METHOD"],[9,"SSO"]],1),c=(0,i.QT)(s.proto3,o,"UnifyPendingMergeState",[[0,"UNSPECIFIED"],[1,"IN_PROGRESS"],[2,"DELAYED"]],1);class l extends a{constructor(t){super(),this.freeUpgradeCard=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(l,t,r)}static $(){return["IndividualUnifyEligibilitySubject|1 free_upgrade_card 8"]}}class m extends a{constructor(t){super(),this.subject={case:void 0},s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(m,t,r)}static $(){return["GetUnifyEligibilityRequest|1 individual #0 subject|2 cursor_team_id 5 subject",l]}}class f extends a{constructor(t){super(),this.eligible=!1,this.reason=u.UNSPECIFIED,this.userFacingMessage="",this.reasons=[],this.canOptInToNewPricing=!1,this.outstandingInvoiceUrl="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(f,t,r)}static $(){return["GetUnifyEligibilityResponse|1 eligible 8|2 reason #0|3 user_facing_message 9|4 reasons #0*|5 can_opt_in_to_new_pricing 8|7 outstanding_invoice_url 9|8 pending_merge #1?|9 free_upgrade_card #2?",u,p,d]}}class d extends a{constructor(t){super(),this.grokStepSkipEnabled=!1,this.foundGrokAccountModalEnabled=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(d,t,r)}static $(){return["UnifyFreeUpgradeCard|1 grok_step_skip_enabled 8|2 found_grok_account_modal_enabled 8"]}}class p extends a{constructor(t){super(),this.state=c.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(p,t,r)}static $(){return["UnifyPendingMerge|1 state #0",c]}}class h extends a{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(h,t,r)}static $(){return["GetUnifyPendingMergeRequest"]}}class g extends a{constructor(t){super(),this.pendingMergeUnread=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(g,t,r)}static $(){return["GetUnifyPendingMergeResponse|1 pending_merge #0?|2 pending_merge_unread 8",p]}}var _=(0,i.QT)(s.proto3,"aiserver.v1.","UnifyWaitlistStatus",[[0,"UNSPECIFIED"],[1,"NONE"],[2,"ON_WAITLIST"],[3,"HAS_ACCESS"]],1);const J="aiserver.v1.";class w extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",s.proto3)}static $p(){return J}}var y=(0,i.QT)(s.proto3,J,"CollapseCandidateMatchReason",[[0,"UNSPECIFIED"],[1,"SESSION"],[2,"PREVIOUSLY_LINKED"],[3,"MATCHING_EMAIL"],[4,"SAME_WORKOS_ID"],[5,"OWNERSHIP_PROVEN"]],1),S=(0,i.QT)(s.proto3,J,"CollapseCandidateMergeability",[[0,"UNSPECIFIED"],[1,"ELIGIBLE"],[2,"BLOCKED"]],1),q=(0,i.QT)(s.proto3,J,"CollapseCandidateBlockReason",[[0,"UNSPECIFIED"],[1,"ACTIVE_TEAM"],[2,"SSO_SCIM"],[3,"ENTERPRISE"],[4,"IDENTITY_JOIN_CONFLICT"],[5,"TOMBSTONED"],[6,"DOMAIN_CAPTURE"],[7,"ACTIVE_ORGANIZATION"],[8,"UNPROVEN_EMAIL_MATCH"],[9,"UNIFY_BLOCKLISTED"],[10,"REQUEST_BASED_PRICING"],[11,"ALIPAY_PAYMENT_METHOD"],[12,"OUTSTANDING_INVOICE"],[13,"STRIPE_CREDIT_BALANCE"],[14,"UNSAFE_SUBSCRIPTION_STATUS"]],1),B=(0,i.QT)(s.proto3,J,"CollapseCandidateSuggestionReason",[[0,"UNSPECIFIED"],[1,"CANONICAL_ACCOUNT_HEURISTIC"]],1),I=(0,i.QT)(s.proto3,J,"UnificationIntentStep",[[0,"UNSPECIFIED"],[1,"DRAFT"],[2,"AWAITING_PAYMENT"],[3,"COLLAPSING"],[4,"FINALIZING"],[5,"DONE"],[6,"MERGING_IDENTITY_JOINS"],[7,"MERGING_MAPPINGS"],[8,"SETTLING_LEGACY_BILLING"]],1),P=(0,i.QT)(s.proto3,J,"LegacyBillingSettlementStatus",[[0,"UNSPECIFIED"],[1,"NOT_STARTED"],[2,"PROCESSING"],[3,"PAYMENT_REQUIRED"],[4,"SETTLED"],[5,"BYPASSED"],[6,"EXEMPT"],[7,"MANUAL_REVIEW_REQUIRED"],[8,"PAYMENT_PROCESSING"]],1),b=(0,i.QT)(s.proto3,J,"IndividualUnificationMergeStatus",[[0,"UNSPECIFIED"],[1,"NOT_READY"],[2,"READY"],[3,"MERGED"],[4,"CONFLICT"]],1),R=(0,i.QT)(s.proto3,J,"IndividualUnificationEmailUpdateStatus",[[0,"UNSPECIFIED"],[1,"UPDATED"],[2,"ALREADY_CURRENT"],[3,"SKIPPED_CONFLICT"],[4,"SKIPPED_NO_GROK_EMAIL"],[5,"NOT_UPDATED"],[6,"SKIPPED_SCIM_MANAGED"]],1),v=(0,i.QT)(s.proto3,J,"UnificationIntentXaiSelectionKind",[[0,"UNSPECIFIED"],[1,"CREATED_BY_CURSOR"],[2,"DESELECTABLE"],[3,"LOCKED"]],1),x=(0,i.QT)(s.proto3,J,"UnificationIntentXLinkState",[[0,"UNSPECIFIED"],[1,"ALREADY_LINKED"],[2,"WILL_LINK"],[3,"NEEDS_GROK_CONFIRMATION"],[4,"LINK_PENDING"]],1),k=(0,i.QT)(s.proto3,J,"UpgradeGrokStep",[[0,"UNSPECIFIED"],[1,"SKIP"],[2,"FOUND_GROK_ACCOUNT"]],1),E=(0,i.QT)(s.proto3,J,"UnifyAppSheetHost",[[0,"UNSPECIFIED"],[1,"GROK_BOT"],[2,"CURSOR_IOS"]],1),C=(0,i.QT)(s.proto3,J,"CompleteUnifyGrokOAuthOutcome",[[0,"UNSPECIFIED"],[1,"SELECTED"],[2,"CONFLICT"],[3,"ENTERPRISE_ACCOUNT"],[4,"SHADOW_REPLACEMENT_BLOCKED"]],1),T=(0,i.QT)(s.proto3,J,"CompleteUnifyGrokOAuthShadowReplacementBlockReason",[[0,"UNSPECIFIED"],[1,"OPEN_USER_INTENT"],[2,"OPEN_TEAM_INTENT"],[3,"UNSETTLED_BILLING"],[4,"MANAGED_ACCOUNT"],[5,"COLLAPSE_CONFLICT"],[6,"SHADOW_CHANGED"],[7,"UNAVAILABLE"]],1),U=(0,i.QT)(s.proto3,J,"CompleteUnifyGrokOAuthConflictReason",[[0,"UNSPECIFIED"],[1,"HELD_BY_ANOTHER_UNIFICATION"],[2,"LINKED_TO_ANOTHER_CURSOR_ACCOUNT"],[3,"GROK_ACCOUNT_ALREADY_UNIFIED"]],1),A=(0,i.QT)(s.proto3,J,"UnifyAlreadyUnifiedMergeRefusal",[[0,"UNSPECIFIED"],[1,"STORE_SUBSCRIPTION"],[2,"SOURCE_ON_TEAM"],[3,"SOURCE_MANAGED_BY_ORGANIZATION"],[4,"SOURCE_NEEDS_SIGN_IN"],[5,"GROK_BOT_TRANSFER_BLOCKED"],[6,"DESTINATION_ON_TEAM"],[7,"DESTINATION_MANAGED_BY_ORGANIZATION"]],1),$=(0,i.QT)(s.proto3,J,"CompleteUnifyXLoginOutcome",[[0,"UNSPECIFIED"],[1,"RECORDED"],[2,"SELECTED_BY_X"],[3,"NO_GROK_ACCOUNT"],[4,"NEEDS_GROK_CONFIRMATION"],[5,"WILL_LINK"],[6,"AUTHKIT_REQUIRED"],[7,"EMAIL_VERIFICATION_REQUIRED"]],1),M=(0,i.QT)(s.proto3,J,"CollapseSourceProofOutcome",[[0,"UNSPECIFIED"],[1,"OWNERSHIP_PROVEN"],[2,"SELF"],[3,"NO_ACCOUNT"]],1),O=(0,i.QT)(s.proto3,J,"ProvisionUnifyGrokAccountOutcome",[[0,"UNSPECIFIED"],[1,"SELECTED"],[2,"GROK_ACCOUNT_EXISTS"],[3,"ENTERPRISE_GROK_ACCOUNT"],[4,"EXISTING_ACCOUNT_SELECTED"]],1),D=(0,i.QT)(s.proto3,J,"UnifyCtaAudience",[[0,"UNSPECIFIED"],[1,"INDIVIDUAL"],[2,"TEAM_ADMIN"]],1),N=(0,i.QT)(s.proto3,J,"SelectXaiUnificationCursorAccountOutcome",[[0,"UNSPECIFIED"],[1,"SELECTED"],[2,"CONFLICT"],[3,"INVALID_STATE"],[4,"BLOCKED"]],1),G=(0,i.QT)(s.proto3,J,"UnlinkGrokAccountOutcome",[[0,"UNSPECIFIED"],[1,"UNLINKED"],[2,"NOT_LINKED"],[3,"REFUSED_MERGED"],[4,"RATE_LIMITED"],[5,"REFUSED_IN_PROGRESS"],[6,"REFUSED_ENTITLEMENT_GRANTED"]],1),L=(0,i.QT)(s.proto3,J,"DeselectXaiUnificationCursorAccountOutcome",[[0,"UNSPECIFIED"],[1,"DESELECTED"],[2,"UNCHANGED"],[3,"LOCKED"],[4,"INVALID_STATE"]],1),F=(0,i.QT)(s.proto3,J,"XaiUnificationCursorAccountProofOutcome",[[0,"UNSPECIFIED"],[1,"OWNERSHIP_PROVEN"],[2,"NO_ACCOUNT"],[3,"CANCELLED"],[4,"CALLBACK_READY"]],1),K=(0,i.QT)(s.proto3,J,"XaiCursorAccountLinkOutcome",[[0,"UNSPECIFIED"],[1,"CALLBACK_READY"],[2,"LINKED"],[3,"NO_ACCOUNT"],[4,"CANCELLED"],[5,"CONFLICT"],[6,"REFUSED"],[7,"CONSENT_REQUIRED"],[8,"INDIVIDUAL_ACCOUNT"]],1),z=(0,i.QT)(s.proto3,J,"EnterpriseGrokMigrationStatus",[[0,"UNSPECIFIED"],[1,"QUEUED"],[2,"CHECKING"],[3,"INELIGIBLE"],[4,"RUNNING"],[5,"RETRYING"],[6,"SUCCEEDED"],[7,"FAILED"]],1),j=(0,i.QT)(s.proto3,J,"EnterpriseGrokMigrationWorkflowState",[[0,"UNSPECIFIED"],[1,"RUNNING"],[2,"PAUSED"],[3,"NOT_RUNNING"]],1),H=(0,i.QT)(s.proto3,J,"EnterpriseGrokMigrationEligibilityStatus",[[0,"UNSPECIFIED"],[1,"CHECKING"],[2,"ELIGIBLE"],[3,"INELIGIBLE"],[4,"UNAVAILABLE"]],1),W=(0,i.QT)(s.proto3,J,"TeamUnifiedStatus",[[0,"UNSPECIFIED"],[1,"NOT_UNIFIED"],[2,"UNIFIED"]],1),Q=(0,i.QT)(s.proto3,J,"UnifiedTeamTrialState",[[0,"UNSPECIFIED"],[1,"PENDING"],[2,"ACTIVE"],[3,"ENDING"],[4,"CONVERTING"],[5,"ENDED"],[6,"CONVERTED"]],1),V=(0,i.QT)(s.proto3,J,"UnifiedTeamTrialSource",[[0,"UNSPECIFIED"],[1,"ACCOUNTINGSPHERE"],[2,"ANYTOOL"],[3,"SALESFORCE"]],1),X=(0,i.QT)(s.proto3,J,"UnifiedTeamTrialOutcome",[[0,"UNSPECIFIED"],[1,"DONE"],[2,"ALREADY_STARTED"],[3,"REFUSED"]],1),Y=(0,i.QT)(s.proto3,J,"GrokCreditPackReportOutcome",[[0,"UNSPECIFIED"],[1,"GRANTED"],[2,"RETRYABLE"],[3,"REJECTED"]],1),Z=(0,i.QT)(s.proto3,J,"MergedTeamSeatChangeRefusalReason",[[0,"UNSPECIFIED"],[1,"NOT_MERGED_RAIL"],[2,"MEMBER_NOT_FOUND"],[3,"MEMBER_NOT_MERGED"],[4,"UNCHANGED"],[5,"NOT_CONFIGURED"],[6,"FREE_NOT_OFFERED"]],1),tt=(0,i.QT)(s.proto3,J,"MergedTeamSeatChangeOutcome",[[0,"UNSPECIFIED"],[1,"CHANGED"],[2,"SCHEDULED"],[3,"DOWNGRADE_WITHDRAWN"],[4,"MANAGE_ON_GROK"],[5,"TRY_AGAIN"],[6,"PAYMENT_FAILED"],[7,"PLAN_CANCELLING"],[8,"CHARGE_IN_FLIGHT"],[9,"REQUIRES_ACTION"],[10,"ADD_PAYMENT_METHOD"],[11,"GROK_SECURITY_BLOCKED"],[12,"GROK_SIGN_IN_REQUIRED"],[13,"GROK_OTHER_ACCOUNT"]],1),rt=(0,i.QT)(s.proto3,J,"UnifiedInvoiceKind",[[0,"UNSPECIFIED"],[1,"SUBSCRIPTION"],[2,"TOP_UP"]],1),et=(0,i.QT)(s.proto3,J,"UnifiedInvoiceStatus",[[0,"UNSPECIFIED"],[1,"PAID"],[2,"PENDING"],[3,"FAILED"]],1),nt=(0,i.QT)(s.proto3,J,"UnifiedInvoiceSource",[[0,"UNSPECIFIED"],[1,"COMMERCE_PLATFORM"],[2,"MC_BILLING"],[3,"STRIPE"]],1),st=(0,i.QT)(s.proto3,J,"XaiCursorTeamMergeCheckoutState",[[0,"UNSPECIFIED"],[1,"NOT_STARTED"],[2,"AWAITING_PAYMENT"],[3,"PAID"],[4,"MERGED"]],1),it=(0,i.QT)(s.proto3,J,"XaiCursorTeamMemberRole",[[0,"UNSPECIFIED"],[1,"MEMBER"],[2,"ADMIN"]],1),ot=(0,i.QT)(s.proto3,J,"XaiCursorTeamMergeGrokTeamsState",[[0,"UNSPECIFIED"],[1,"NOT_SIGNED_IN"],[2,"AVAILABLE"],[3,"MISSING_SCOPE"],[4,"UNAVAILABLE"]],1),at=(0,i.QT)(s.proto3,J,"EnsureXaiCursorTeamForMergeOutcome",[[0,"UNSPECIFIED"],[1,"ENSURED"],[2,"GROK_ACCOUNT_EXISTS"]],1),ut=(0,i.QT)(s.proto3,J,"XaiEmailEligibilityResultKind",[[0,"UNSPECIFIED"],[1,"OK"],[2,"MISSING_EMAIL"],[3,"NOT_CONFIGURED"],[4,"UNAVAILABLE"],[5,"REFUSED"]],1),ct=(0,i.QT)(s.proto3,J,"XaiEmailUnificationStatus",[[0,"UNSPECIFIED"],[1,"AVAILABLE"],[2,"ALREADY_UNIFIED_WITH_CALLER"],[3,"UNIFIED_WITH_OTHER_CURSOR_USER"]],1),lt=(0,i.QT)(s.proto3,J,"GrokAccountsByXUserResultKind",[[0,"UNSPECIFIED"],[1,"OK"],[2,"NOT_CONFIGURED"],[3,"UNAVAILABLE"],[4,"REFUSED"]],1),mt=(0,i.QT)(s.proto3,J,"UnifyAlreadyUnifiedMergeDestinationKind",[[0,"UNSPECIFIED"],[1,"EMAIL"],[2,"GENERIC"]],1);class ft extends w{constructor(t){super(),this.publicId="",this.targetUserId=0,this.status="",this.sources=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ft).fromBinary(t,r)}static fromJson(t,r){return(new ft).fromJson(t,r)}static fromJsonString(t,r){return(new ft).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ft,t,r)}static $(){return["AccountCollapseRun|1 public_id 9|2 target_user_id 5|3 status 9|4 sources #0*|5 created_at #1|6 updated_at #1",dt,s.Timestamp]}}class dt extends w{constructor(t){super(),this.sourceUserId=0,this.status="",this.steps=[],this.totalSteps=0,this.doneSteps=0,this.progressPercent=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dt).fromBinary(t,r)}static fromJson(t,r){return(new dt).fromJson(t,r)}static fromJsonString(t,r){return(new dt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(dt,t,r)}static $(){return["AccountCollapseRunSource|1 source_user_id 5|2 status 9|3 steps #0*|4 total_steps 5|5 done_steps 5|6 progress_percent 5",pt]}}class pt extends w{constructor(t){super(),this.stepKey="",this.status="",this.attemptCount=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pt).fromBinary(t,r)}static fromJson(t,r){return(new pt).fromJson(t,r)}static fromJsonString(t,r){return(new pt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(pt,t,r)}static $(){return["AccountCollapseStep|1 step_key 9|2 status 9|3 attempt_count 5"]}}class ht extends w{constructor(t){super(),this.targetUserId=0,this.sourceUserIds=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ht).fromBinary(t,r)}static fromJson(t,r){return(new ht).fromJson(t,r)}static fromJsonString(t,r){return(new ht).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ht,t,r)}static $(){return["StartAccountCollapseRunRequest|1 target_user_id 5|2 source_user_ids 5*"]}}class gt extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gt).fromBinary(t,r)}static fromJson(t,r){return(new gt).fromJson(t,r)}static fromJsonString(t,r){return(new gt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(gt,t,r)}static $(){return["StartAccountCollapseRunResponse|1 run #0",ft]}}class _t extends w{constructor(t){super(),this.publicId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _t).fromBinary(t,r)}static fromJson(t,r){return(new _t).fromJson(t,r)}static fromJsonString(t,r){return(new _t).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(_t,t,r)}static $(){return["GetAccountCollapseRunRequest|1 public_id 9"]}}class Jt extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jt).fromBinary(t,r)}static fromJson(t,r){return(new Jt).fromJson(t,r)}static fromJsonString(t,r){return(new Jt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Jt,t,r)}static $(){return["GetAccountCollapseRunResponse|1 run #0",ft]}}class wt extends w{constructor(t){super(),this.targetCursorUserId=0,this.sourceCursorUserIds=[],this.legacyPrivacyAcknowledged=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wt).fromBinary(t,r)}static fromJson(t,r){return(new wt).fromJson(t,r)}static fromJsonString(t,r){return(new wt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(wt,t,r)}static $(){return["StartCursorAccountCollapseRequest|1 target_cursor_user_id 5|2 source_cursor_user_ids 5*|3 legacy_privacy_acknowledged 8"]}}class yt extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yt).fromBinary(t,r)}static fromJson(t,r){return(new yt).fromJson(t,r)}static fromJsonString(t,r){return(new yt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(yt,t,r)}static $(){return["StartCursorAccountCollapseResponse|1 run #0",ft]}}class St extends w{constructor(t){super(),this.targetCursorUserId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new St).fromBinary(t,r)}static fromJson(t,r){return(new St).fromJson(t,r)}static fromJsonString(t,r){return(new St).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(St,t,r)}static $(){return["GetCursorAccountCollapseByTargetRequest|1 target_cursor_user_id 5"]}}class qt extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qt).fromBinary(t,r)}static fromJson(t,r){return(new qt).fromJson(t,r)}static fromJsonString(t,r){return(new qt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(qt,t,r)}static $(){return["GetCursorAccountCollapseByTargetResponse|1 run #0?",ft]}}class Bt extends w{constructor(t){super(),this.sourceCursorUserIds=[],this.legacyPrivacyAcknowledged=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bt).fromBinary(t,r)}static fromJson(t,r){return(new Bt).fromJson(t,r)}static fromJsonString(t,r){return(new Bt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Bt,t,r)}static $(){return["StartCursorSessionAccountCollapseRequest|1 source_cursor_user_ids 5*|2 legacy_privacy_acknowledged 8"]}}class It extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new It).fromBinary(t,r)}static fromJson(t,r){return(new It).fromJson(t,r)}static fromJsonString(t,r){return(new It).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(It,t,r)}static $(){return["GetCursorSessionAccountCollapseRequest"]}}class Pt extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pt).fromBinary(t,r)}static fromJson(t,r){return(new Pt).fromJson(t,r)}static fromJsonString(t,r){return(new Pt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Pt,t,r)}static $(){return["ListCursorSessionAccountCollapseCandidatesRequest"]}}class bt extends w{constructor(t){super(),this.redirectUri="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bt).fromBinary(t,r)}static fromJson(t,r){return(new bt).fromJson(t,r)}static fromJsonString(t,r){return(new bt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(bt,t,r)}static $(){return["StartCursorSessionAccountCollapseProofRequest|1 redirect_uri 9|2 candidate_reference 9?"]}}class Rt extends w{constructor(t){super(),this.code="",this.state="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rt).fromBinary(t,r)}static fromJson(t,r){return(new Rt).fromJson(t,r)}static fromJsonString(t,r){return(new Rt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Rt,t,r)}static $(){return["CompleteCursorSessionAccountCollapseProofRequest|1 code 9|2 state 9"]}}class vt extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vt).fromBinary(t,r)}static fromJson(t,r){return(new vt).fromJson(t,r)}static fromJsonString(t,r){return(new vt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(vt,t,r)}static $(){return["GetUnificationLegacySuperGrokPlanRequest"]}}class xt extends w{constructor(t){super(),this.plan="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xt).fromBinary(t,r)}static fromJson(t,r){return(new xt).fromJson(t,r)}static fromJsonString(t,r){return(new xt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(xt,t,r)}static $(){return["GetUnificationLegacySuperGrokPlanResponse|1 plan 9"]}}class kt extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kt).fromBinary(t,r)}static fromJson(t,r){return(new kt).fromJson(t,r)}static fromJsonString(t,r){return(new kt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(kt,t,r)}static $(){return["ListCollapseCandidatesRequest"]}}class Et extends w{constructor(t){super(),this.individualPlan="",this.activeTeamCount=0,this.hasEnterpriseMembership=!1,this.hasSsoOrScimMembership=!1,this.activeOrganizationCount=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Et).fromBinary(t,r)}static fromJson(t,r){return(new Et).fromJson(t,r)}static fromJsonString(t,r){return(new Et).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Et,t,r)}static $(){return["CollapseCandidateMembershipSummary|1 individual_plan 9|2 active_team_count 5|3 has_enterprise_membership 8|4 has_sso_or_scim_membership 8|5 active_organization_count 5"]}}class Ct extends w{constructor(t){super(),this.name="",this.maskedKey="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ct).fromBinary(t,r)}static fromJson(t,r){return(new Ct).fromJson(t,r)}static fromJsonString(t,r){return(new Ct).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ct,t,r)}static $(){return["CollapseCandidateApiKey|1 name 9|2 masked_key 9"]}}class Tt extends w{constructor(t){super(),this.matchReasons=[],this.mergeability=S.UNSPECIFIED,this.blockReasons=[],this.suggestedTarget=!1,this.requiresProof=!1,this.xaiJitShadow=!1,this.apiKeys=[],this.ownershipProofLapsed=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tt).fromBinary(t,r)}static fromJson(t,r){return(new Tt).fromJson(t,r)}static fromJsonString(t,r){return(new Tt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Tt,t,r)}static $(){return["CollapseCandidate|1 cursor_user_id 5?|2 auth_id 9?|3 email 9?|4 display_name 9?|5 workos_id 9?|6 membership #0|7 last_sign_in_at #1?|8 match_reasons #2*|9 mergeability #3|10 block_reasons #4*|11 suggested_target 8|12 suggestion_reason #5?|13 requires_proof 8|14 candidate_reference 9?|15 xai_jit_shadow 8|16 api_keys #6*|17 ownership_proof_lapsed 8",Et,s.Timestamp,y,S,q,B,Ct]}}class Ut extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ut).fromBinary(t,r)}static fromJson(t,r){return(new Ut).fromJson(t,r)}static fromJsonString(t,r){return(new Ut).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ut,t,r)}static $(){return["CollapseLinkedGrokAccount|1 email 9?"]}}class At extends w{constructor(t){super(),this.candidates=[],this.legacyPrivacyAcknowledgementRequired=!1,this.grokBotDataTransferBlocked=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new At).fromBinary(t,r)}static fromJson(t,r){return(new At).fromJson(t,r)}static fromJsonString(t,r){return(new At).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(At,t,r)}static $(){return["ListCollapseCandidatesResponse|1 candidates #0*|2 linked_grok_account #1?|3 session_account_created_by_unification 8?|4 legacy_privacy_acknowledgement_required 8|6 grok_bot_data_transfer_blocked 8",Tt,Ut]}}class $t extends w{constructor(t){super(),this.status=P.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $t).fromBinary(t,r)}static fromJson(t,r){return(new $t).fromJson(t,r)}static fromJsonString(t,r){return(new $t).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals($t,t,r)}static $(){return["LegacyBillingSettlement|1 status #0|2 hosted_invoice_url 9?|3 amount_cents 3?|4 currency 9?",P]}}class Mt extends w{constructor(t){super(),this.publicId="",this.initiatedFrom="",this.subjectType="",this.step=I.UNSPECIFIED,this.xLinkState=x.UNSPECIFIED,this.xaiSelectionKind=v.UNSPECIFIED,this.backgroundGrokAccountSelected=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mt).fromBinary(t,r)}static fromJson(t,r){return(new Mt).fromJson(t,r)}static fromJsonString(t,r){return(new Mt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Mt,t,r)}static $(){return["UnificationIntent|1 public_id 9|2 initiated_from 9|4 subject_type 9|5 intended_xai_email 9?|6 created_at #0|7 updated_at #0|8 intended_cursor_resource_id 9?|9 intended_xai_resource_id 9?|10 joined_id 9?|11 step #1|12 collapse_run_id 9?|13 x_hosted_flow_returned_at #0?|14 x_link_state #2|15 pending_x_username 9?|16 xai_selection_kind #3|17 background_grok_account_selected 8|18 cursor_stripe_credit_balance_cents 3?|19 x_account_refusal #4?",s.Timestamp,I,x,v,Hn]}}class Ot extends w{constructor(t){super(),this.checkUpgradeGrokStep=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ot).fromBinary(t,r)}static fromJson(t,r){return(new Ot).fromJson(t,r)}static fromJsonString(t,r){return(new Ot).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ot,t,r)}static $(){return["GetUnificationIntentRequest|1 check_upgrade_grok_step 8"]}}class Dt extends w{constructor(t){super(),this.forDuplicateSubscriptionReminder=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dt).fromBinary(t,r)}static fromJson(t,r){return(new Dt).fromJson(t,r)}static fromJsonString(t,r){return(new Dt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Dt,t,r)}static $(){return["GetStoreSubscriptionsToCancelRequest|1 for_duplicate_subscription_reminder 8"]}}class Nt extends w{constructor(t){super(),this.store=Gt.UNSPECIFIED,this.app="",this.appName="",this.planLabel="",this.manageUrl="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nt).fromBinary(t,r)}static fromJson(t,r){return(new Nt).fromJson(t,r)}static fromJsonString(t,r){return(new Nt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Nt,t,r)}static $(){return["StoreSubscriptionToCancel|1 store #0|2 app 9|3 app_name 9|4 plan_label 9|5 manage_url 9",Gt]}}var Gt=(0,i.QT)(s.proto3,J,"StoreSubscriptionToCancel.Store",[[0,"UNSPECIFIED"],[1,"APPLE"],[2,"GOOGLE"]],1);class Lt extends w{constructor(t){super(),this.subscriptions=[],this.duplicateSubscriptionReminderEligible=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lt).fromBinary(t,r)}static fromJson(t,r){return(new Lt).fromJson(t,r)}static fromJsonString(t,r){return(new Lt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Lt,t,r)}static $(){return["GetStoreSubscriptionsToCancelResponse|1 subscriptions #0*|2 duplicate_subscription_reminder_eligible 8",Nt]}}class Ft extends w{constructor(t){super(),this.enabled=!1,this.mergeStatus=b.UNSPECIFIED,this.emailUpdateStatus=R.UNSPECIFIED,this.grokReselectionAllowed=!1,this.cursorAccountLinkingEligible=!1,this.linkedGrokAccountHasGrokBotEntitlement=!1,this.hasPreviouslySelectedGrokAccount=!1,this.continueWithFreeEligible=!1,this.xFirstLinkingAvailable=!1,this.blockedByCursorTeam=!1,this.sameEmailGrokAccountLinked=!1,this.legacyPrivacyAcknowledgementRequired=!1,this.heldUnifiedPlanCarryOverEligible=!1,this.xWaitsForGrokSignIn=!1,this.grokBotDataTransferBlocked=!1,this.heldUnifiedPlanSignInRequired=!1,this.previousSubscriptionRefundRefusal="",this.paidMergeAwaitsLegacyPrivacyAcknowledgement=!1,this.paidMergeInProgress=!1,this.prePaymentCursorAccountsListAvailable=!1,this.upgradeGrokStep=k.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ft).fromBinary(t,r)}static fromJson(t,r){return(new Ft).fromJson(t,r)}static fromJsonString(t,r){return(new Ft).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ft,t,r)}static $(){return["GetUnificationIntentResponse|1 enabled 8|2 intent #0?|3 merge_status #1|4 merged_at #2?|5 email_update_status #3|6 linked_grok_account #4?|7 grok_reselection_allowed 8|8 cursor_account_linking_eligible 8|9 linked_grok_account_has_grok_bot_entitlement 8|10 has_previously_selected_grok_account 8|11 continue_with_free_eligible 8|12 legacy_billing_settlement #5?|13 x_first_linking_available 8|14 blocked_by_cursor_team 8|15 same_email_grok_account_linked 8|16 grok_email_account_exists 8?|17 grok_email_can_proceed_without_suggestion 8?|18 legacy_privacy_acknowledgement_required 8|19 grok_email_linked_to_different_email 8?|20 held_unified_plan_carry_over_eligible 8|21 x_waits_for_grok_sign_in 8|23 grok_bot_data_transfer_blocked 8|24 held_unified_plan_sign_in_required 8|25 previous_subscription_refund_refusal 9|26 paid_merge_awaits_legacy_privacy_acknowledgement 8|27 paid_merge_in_progress 8|28 pre_payment_cursor_accounts_list_available 8|29 held_unified_grant #6?|30 upgrade_grok_step #7",Mt,b,s.Timestamp,R,Ut,$t,Kt,k]}}class Kt extends w{constructor(t){super(),this.subscriptionId="",this.skuId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kt).fromBinary(t,r)}static fromJson(t,r){return(new Kt).fromJson(t,r)}static fromJsonString(t,r){return(new Kt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Kt,t,r)}static $(){return["HeldUnifiedGrant|1 subscription_id 9|2 sku_id 9"]}}class zt extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zt).fromBinary(t,r)}static fromJson(t,r){return(new zt).fromJson(t,r)}static fromJsonString(t,r){return(new zt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(zt,t,r)}static $(){return["GetIndividualUnificationPrepaidPreviewRequest"]}}class jt extends w{constructor(t){super(),this.available=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jt).fromBinary(t,r)}static fromJson(t,r){return(new jt).fromJson(t,r)}static fromJsonString(t,r){return(new jt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(jt,t,r)}static $(){return["GetIndividualUnificationPrepaidPreviewResponse|1 available 8|2 prepaid_balance_cents 3?|3 grok_auto_top_up #0?|4 xai_team_id 9?|5 grok_monthly_cap_cents 3?",n.xYM]}}class Ht extends w{constructor(t){super(),this.deselectXaiAccount=!1,this.clearPendingXAccount=!1,this.acknowledgeXAccountRefusal=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ht).fromBinary(t,r)}static fromJson(t,r){return(new Ht).fromJson(t,r)}static fromJsonString(t,r){return(new Ht).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ht,t,r)}static $(){return["UpsertUnificationIntentRequest|1 deselect_xai_account 8|2 clear_pending_x_account 8|3 acknowledge_x_account_refusal 8"]}}class Wt extends w{constructor(t){super(),this.enabled=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wt).fromBinary(t,r)}static fromJson(t,r){return(new Wt).fromJson(t,r)}static fromJsonString(t,r){return(new Wt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Wt,t,r)}static $(){return["UpsertUnificationIntentResponse|1 enabled 8|2 intent #0?",Mt]}}class Qt extends w{constructor(t){super(),this.redirectUri="",this.appSheetVerifierHash="",this.appSheetHost=E.UNSPECIFIED,this.unlinkExistingLink=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qt).fromBinary(t,r)}static fromJson(t,r){return(new Qt).fromJson(t,r)}static fromJsonString(t,r){return(new Qt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Qt,t,r)}static $(){return["StartUnifyGrokOAuthRequest|1 redirect_uri 9|2 app_sheet_verifier_hash 9|3 app_sheet_host #0|4 unlink_existing_link 8",E]}}class Vt extends w{constructor(t){super(),this.authorizeUrl="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vt).fromBinary(t,r)}static fromJson(t,r){return(new Vt).fromJson(t,r)}static fromJsonString(t,r){return(new Vt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Vt,t,r)}static $(){return["StartUnifyGrokOAuthResponse|1 authorize_url 9"]}}class Xt extends w{constructor(t){super(),this.code="",this.state="",this.unlinkConfirmation="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xt).fromBinary(t,r)}static fromJson(t,r){return(new Xt).fromJson(t,r)}static fromJsonString(t,r){return(new Xt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Xt,t,r)}static $(){return["CompleteUnifyGrokOAuthRequest|1 code 9|2 state 9|3 unlink_confirmation 9"]}}class Yt extends w{constructor(t){super(),this.inviteCode="",this.redirectUri="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yt).fromBinary(t,r)}static fromJson(t,r){return(new Yt).fromJson(t,r)}static fromJsonString(t,r){return(new Yt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Yt,t,r)}static $(){return["StartTeamInviteGrokBindRequest|1 invite_code 9|2 redirect_uri 9"]}}class Zt extends w{constructor(t){super(),this.authorizeUrl="",this.alreadyLinked=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zt).fromBinary(t,r)}static fromJson(t,r){return(new Zt).fromJson(t,r)}static fromJsonString(t,r){return(new Zt).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Zt,t,r)}static $(){return["StartTeamInviteGrokBindResponse|1 authorize_url 9|2 already_linked 8"]}}class tr extends w{constructor(t){super(),this.inviteCode="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tr).fromBinary(t,r)}static fromJson(t,r){return(new tr).fromJson(t,r)}static fromJsonString(t,r){return(new tr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(tr,t,r)}static $(){return["GetTeamInviteGrokBindStatusRequest|1 invite_code 9"]}}class rr extends w{constructor(t){super(),this.proven=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rr).fromBinary(t,r)}static fromJson(t,r){return(new rr).fromJson(t,r)}static fromJsonString(t,r){return(new rr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(rr,t,r)}static $(){return["GetTeamInviteGrokBindStatusResponse|1 proven 8"]}}class er extends w{constructor(t){super(),this.outcome=C.UNSPECIFIED,this.returnPath="",this.continueUrl="",this.shadowReplacementBlockReason=T.UNSPECIFIED,this.conflictReason=U.UNSPECIFIED,this.alreadyUnifiedMergeOffered=!1,this.alreadyUnifiedMergeRefusal=A.UNSPECIFIED,this.linkedCursorEmailIsSynthetic=!1,this.unlinkConfirmation="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new er).fromBinary(t,r)}static fromJson(t,r){return(new er).fromJson(t,r)}static fromJsonString(t,r){return(new er).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(er,t,r)}static $(){return["CompleteUnifyGrokOAuthResponse|1 outcome #0|2 intent #1?|3 return_path 9|4 continue_url 9|5 xai_email 9?|6 shadow_replacement_block_reason #2|7 conflict_reason #3|8 linked_cursor_email_masked 9?|9 already_unified_merge_offered 8|10 already_unified_merge_refusal #4|11 linked_cursor_email_is_synthetic 8|12 unlink #5|13 unlink_confirmation 9",C,Mt,T,U,A,nr]}}class nr extends w{constructor(t){super(),this.state={case:void 0},s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nr).fromBinary(t,r)}static fromJson(t,r){return(new nr).fromJson(t,r)}static fromJsonString(t,r){return(new nr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(nr,t,r)}static $(){return["UnifyGrokConflictUnlink|1 offered #0 state|2 refused #1 state",sr,ir]}}class sr extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sr).fromBinary(t,r)}static fromJson(t,r){return(new sr).fromJson(t,r)}static fromJsonString(t,r){return(new sr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(sr,t,r)}static $(){return["UnifyGrokConflictUnlink.Offered"]}}class ir extends w{constructor(t){super(),this.reason=or.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ir).fromBinary(t,r)}static fromJson(t,r){return(new ir).fromJson(t,r)}static fromJsonString(t,r){return(new ir).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ir,t,r)}static $(){return["UnifyGrokConflictUnlink.Refused|1 reason #0|2 next_unlink_allowed_at #1?",or,s.Timestamp]}}var or=(0,i.QT)(s.proto3,J,"UnifyGrokConflictUnlink.Refused.Reason",[[0,"UNSPECIFIED"],[1,"MERGED"],[2,"IN_PROGRESS"],[3,"RATE_LIMITED"],[4,"ENTITLEMENT_GRANTED"]],1);class ar extends w{constructor(t){super(),this.redirectUri="",this.appSheetVerifierHash="",this.appSheetHost=E.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ar).fromBinary(t,r)}static fromJson(t,r){return(new ar).fromJson(t,r)}static fromJsonString(t,r){return(new ar).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ar,t,r)}static $(){return["StartUnifyXLoginRequest|1 redirect_uri 9|2 app_sheet_verifier_hash 9|3 app_sheet_host #0",E]}}class ur extends w{constructor(t){super(),this.authorizeUrl="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ur).fromBinary(t,r)}static fromJson(t,r){return(new ur).fromJson(t,r)}static fromJsonString(t,r){return(new ur).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ur,t,r)}static $(){return["StartUnifyXLoginResponse|1 authorize_url 9"]}}class cr extends w{constructor(t){super(),this.code="",this.state="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cr).fromBinary(t,r)}static fromJson(t,r){return(new cr).fromJson(t,r)}static fromJsonString(t,r){return(new cr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(cr,t,r)}static $(){return["CompleteUnifyXLoginRequest|1 code 9|2 state 9"]}}class lr extends w{constructor(t){super(),this.outcome=$.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lr).fromBinary(t,r)}static fromJson(t,r){return(new lr).fromJson(t,r)}static fromJsonString(t,r){return(new lr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(lr,t,r)}static $(){return["CompleteUnifyXLoginResponse|1 intent #0|2 outcome #1|3 authkit_authorize_url 9?|4 email_verification_state 9?",Mt,$]}}class mr extends w{constructor(t){super(),this.emailVerificationState="",this.code="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mr).fromBinary(t,r)}static fromJson(t,r){return(new mr).fromJson(t,r)}static fromJsonString(t,r){return(new mr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(mr,t,r)}static $(){return["VerifyUnifyXLoginEmailRequest|1 email_verification_state 9|2 code 9"]}}class fr extends w{constructor(t){super(),this.redirectUri="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fr).fromBinary(t,r)}static fromJson(t,r){return(new fr).fromJson(t,r)}static fromJsonString(t,r){return(new fr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(fr,t,r)}static $(){return["StartCollapseSourceProofRequest|1 redirect_uri 9|2 login_hint 9?|3 candidate_reference 9?"]}}class dr extends w{constructor(t){super(),this.authorizeUrl="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dr).fromBinary(t,r)}static fromJson(t,r){return(new dr).fromJson(t,r)}static fromJsonString(t,r){return(new dr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(dr,t,r)}static $(){return["StartCollapseSourceProofResponse|1 authorize_url 9"]}}class pr extends w{constructor(t){super(),this.code="",this.state="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pr).fromBinary(t,r)}static fromJson(t,r){return(new pr).fromJson(t,r)}static fromJsonString(t,r){return(new pr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(pr,t,r)}static $(){return["CompleteCollapseSourceProofRequest|1 code 9|2 state 9"]}}class hr extends w{constructor(t){super(),this.outcome=M.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hr).fromBinary(t,r)}static fromJson(t,r){return(new hr).fromJson(t,r)}static fromJsonString(t,r){return(new hr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(hr,t,r)}static $(){return["CompleteCollapseSourceProofResponse|1 outcome #0",M]}}class gr extends w{constructor(t){super(),this.cursorUserId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gr).fromBinary(t,r)}static fromJson(t,r){return(new gr).fromJson(t,r)}static fromJsonString(t,r){return(new gr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(gr,t,r)}static $(){return["RevokeCollapseSourceProofRequest|1 cursor_user_id 5"]}}class _r extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _r).fromBinary(t,r)}static fromJson(t,r){return(new _r).fromJson(t,r)}static fromJsonString(t,r){return(new _r).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(_r,t,r)}static $(){return["RevokeCollapseSourceProofResponse"]}}class Jr extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jr).fromBinary(t,r)}static fromJson(t,r){return(new Jr).fromJson(t,r)}static fromJsonString(t,r){return(new Jr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Jr,t,r)}static $(){return["ProvisionUnifyGrokAccountRequest"]}}class wr extends w{constructor(t){super(),this.outcome=O.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wr).fromBinary(t,r)}static fromJson(t,r){return(new wr).fromJson(t,r)}static fromJsonString(t,r){return(new wr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(wr,t,r)}static $(){return["ProvisionUnifyGrokAccountResponse|1 intent #0|2 outcome #1",Mt,O]}}class yr extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yr).fromBinary(t,r)}static fromJson(t,r){return(new yr).fromJson(t,r)}static fromJsonString(t,r){return(new yr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(yr,t,r)}static $(){return["GetUnifyCtaRequest"]}}class Sr extends w{constructor(t){super(),this.show=!1,this.audience=D.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sr).fromBinary(t,r)}static fromJson(t,r){return(new Sr).fromJson(t,r)}static fromJsonString(t,r){return(new Sr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Sr,t,r)}static $(){return["GetUnifyCtaResponse|1 show 8|2 audience #0|3 href 9?",D]}}class qr extends w{constructor(t){super(),this.continueWithFree=!1,this.legacyPrivacyAcknowledged=!1,this.carryOverHeldPlan=!1,this.heldGrantSubscriptionId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qr).fromBinary(t,r)}static fromJson(t,r){return(new qr).fromJson(t,r)}static fromJsonString(t,r){return(new qr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(qr,t,r)}static $(){return["FinalizeIndividualUnificationRequest|1 checkout_outcome #0?|2 continue_with_free 8|3 marketing_opted_out 8?|4 legacy_privacy_acknowledged 8|5 carry_over_held_plan 8|6 held_grant_subscription_id 9",Br]}}class Br extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Br).fromBinary(t,r)}static fromJson(t,r){return(new Br).fromJson(t,r)}static fromJsonString(t,r){return(new Br).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Br,t,r)}static $(){return["IndividualUnificationCheckoutOutcome|1 purchase_id 9?|2 subscription_id 9?"]}}class Ir extends w{constructor(t){super(),this.mergeStatus=b.UNSPECIFIED,this.emailUpdateStatus=R.UNSPECIFIED,this.previousSubscriptionRefundRefusal="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ir).fromBinary(t,r)}static fromJson(t,r){return(new Ir).fromJson(t,r)}static fromJsonString(t,r){return(new Ir).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ir,t,r)}static $(){return["FinalizeIndividualUnificationResponse|1 merge_status #0|2 merged_at #1?|3 email_update_status #2|4 legacy_billing_settlement #3?|5 x_account_refusal #4?|6 previous_subscription_refund_refusal 9|7 xai_team_id 9?",b,s.Timestamp,R,$t,Hn]}}class Pr extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pr).fromBinary(t,r)}static fromJson(t,r){return(new Pr).fromJson(t,r)}static fromJsonString(t,r){return(new Pr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Pr,t,r)}static $(){return["GetOrCreateXaiUnificationIntentRequest|1 surface 9?"]}}class br extends w{constructor(t){super(),this.created=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new br).fromBinary(t,r)}static fromJson(t,r){return(new br).fromJson(t,r)}static fromJsonString(t,r){return(new br).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(br,t,r)}static $(){return["GetOrCreateXaiUnificationIntentResponse|1 intent #0|2 created 8",Mt]}}class Rr extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rr).fromBinary(t,r)}static fromJson(t,r){return(new Rr).fromJson(t,r)}static fromJsonString(t,r){return(new Rr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Rr,t,r)}static $(){return["GetXaiUnificationIntentRequest"]}}class vr extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vr).fromBinary(t,r)}static fromJson(t,r){return(new vr).fromJson(t,r)}static fromJsonString(t,r){return(new vr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(vr,t,r)}static $(){return["XaiUnificationLinkedCursorAccount|1 cursor_user_id 5?|2 email 9?"]}}class xr extends w{constructor(t){super(),this.mergeStatus=b.UNSPECIFIED,this.legacyPrivacyAcknowledgementRequired=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xr).fromBinary(t,r)}static fromJson(t,r){return(new xr).fromJson(t,r)}static fromJsonString(t,r){return(new xr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(xr,t,r)}static $(){return["GetXaiUnificationIntentResponse|1 intent #0?|2 merge_status #1|3 merged_at #2?|4 linked_cursor_account #3?|5 legacy_privacy_acknowledgement_required 8|6 pending_merge #4?",Mt,b,s.Timestamp,vr,p]}}class kr extends w{constructor(t){super(),this.cursorUserId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kr).fromBinary(t,r)}static fromJson(t,r){return(new kr).fromJson(t,r)}static fromJsonString(t,r){return(new kr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(kr,t,r)}static $(){return["SelectXaiUnificationCursorAccountRequest|1 cursor_user_id 5|2 surface 9?"]}}class Er extends w{constructor(t){super(),this.outcome=N.UNSPECIFIED,this.blockReasons=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Er).fromBinary(t,r)}static fromJson(t,r){return(new Er).fromJson(t,r)}static fromJsonString(t,r){return(new Er).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Er,t,r)}static $(){return["SelectXaiUnificationCursorAccountResponse|1 outcome #0|2 intent #1?|3 block_reasons #2*|4 outstanding_invoice_url 9?",N,Mt,q]}}class Cr extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cr).fromBinary(t,r)}static fromJson(t,r){return(new Cr).fromJson(t,r)}static fromJsonString(t,r){return(new Cr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Cr,t,r)}static $(){return["UnlinkGrokAccountRequest|1 reason 9?"]}}class Tr extends w{constructor(t){super(),this.outcome=G.UNSPECIFIED,this.message="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tr).fromBinary(t,r)}static fromJson(t,r){return(new Tr).fromJson(t,r)}static fromJsonString(t,r){return(new Tr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Tr,t,r)}static $(){return["UnlinkGrokAccountResponse|1 outcome #0|2 message 9|3 next_unlink_allowed_at #1?",G,s.Timestamp]}}class Ur extends w{constructor(t){super(),this.cursorUserId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ur).fromBinary(t,r)}static fromJson(t,r){return(new Ur).fromJson(t,r)}static fromJsonString(t,r){return(new Ur).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ur,t,r)}static $(){return["DeselectXaiUnificationCursorAccountRequest|1 cursor_user_id 5"]}}class Ar extends w{constructor(t){super(),this.outcome=L.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ar).fromBinary(t,r)}static fromJson(t,r){return(new Ar).fromJson(t,r)}static fromJsonString(t,r){return(new Ar).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ar,t,r)}static $(){return["DeselectXaiUnificationCursorAccountResponse|1 outcome #0|2 intent #1?",L,Mt]}}class $r extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $r).fromBinary(t,r)}static fromJson(t,r){return(new $r).fromJson(t,r)}static fromJsonString(t,r){return(new $r).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals($r,t,r)}static $(){return["ListXaiUnificationCollapseCandidatesRequest"]}}class Mr extends w{constructor(t){super(),this.redirectUri="",this.returnUri="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mr).fromBinary(t,r)}static fromJson(t,r){return(new Mr).fromJson(t,r)}static fromJsonString(t,r){return(new Mr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Mr,t,r)}static $(){return["StartXaiUnificationCursorAccountProofRequest|1 redirect_uri 9|2 return_uri 9|3 login_hint 9?"]}}class Or extends w{constructor(t){super(),this.authorizeUrl="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Or).fromBinary(t,r)}static fromJson(t,r){return(new Or).fromJson(t,r)}static fromJsonString(t,r){return(new Or).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Or,t,r)}static $(){return["StartXaiUnificationCursorAccountProofResponse|1 authorize_url 9"]}}class Dr extends w{constructor(t){super(),this.state="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dr).fromBinary(t,r)}static fromJson(t,r){return(new Dr).fromJson(t,r)}static fromJsonString(t,r){return(new Dr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Dr,t,r)}static $(){return["CompleteXaiUnificationCursorAccountProofRequest|1 code 9?|2 state 9|3 oauth_error 9?"]}}class Nr extends w{constructor(t){super(),this.outcome=F.UNSPECIFIED,this.returnUri="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nr).fromBinary(t,r)}static fromJson(t,r){return(new Nr).fromJson(t,r)}static fromJsonString(t,r){return(new Nr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Nr,t,r)}static $(){return["CompleteXaiUnificationCursorAccountProofResponse|1 outcome #0|2 return_uri 9|3 continuation_state 9?",F]}}class Gr extends w{constructor(t){super(),this.continueWithFree=!1,this.legacyPrivacyAcknowledged=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gr).fromBinary(t,r)}static fromJson(t,r){return(new Gr).fromJson(t,r)}static fromJsonString(t,r){return(new Gr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Gr,t,r)}static $(){return["AdvanceXaiUnificationIntentRequest|1 checkout_outcome #0?|2 continue_with_free 8|3 existing_subscription_id 9?|4 legacy_privacy_acknowledged 8|5 surface 9?",Br]}}class Lr extends w{constructor(t){super(),this.mergeStatus=b.UNSPECIFIED,this.legacyPrivacyAcknowledgementRequired=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lr).fromBinary(t,r)}static fromJson(t,r){return(new Lr).fromJson(t,r)}static fromJsonString(t,r){return(new Lr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Lr,t,r)}static $(){return["AdvanceXaiUnificationIntentResponse|1 intent #0|2 merge_status #1|3 merged_at #2?|4 legacy_privacy_acknowledgement_required 8|5 pending_merge #3?",Mt,b,s.Timestamp,p]}}class Fr extends w{constructor(t){super(),this.redirectUri="",this.returnUri="",this.replaceLinkedShadow=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fr).fromBinary(t,r)}static fromJson(t,r){return(new Fr).fromJson(t,r)}static fromJsonString(t,r){return(new Fr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Fr,t,r)}static $(){return["StartXaiCursorAccountLinkRequest|1 redirect_uri 9|2 return_uri 9|3 login_hint 9?|4 replace_linked_shadow 8"]}}class Kr extends w{constructor(t){super(),this.authorizeUrl="",this.legacyPrivacyAcknowledgementRequired=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kr).fromBinary(t,r)}static fromJson(t,r){return(new Kr).fromJson(t,r)}static fromJsonString(t,r){return(new Kr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Kr,t,r)}static $(){return["StartXaiCursorAccountLinkResponse|1 authorize_url 9|2 legacy_privacy_acknowledgement_required 8|3 replaced_shadow_email 9?|4 replaced_shadow_created_at #0?",s.Timestamp]}}class zr extends w{constructor(t){super(),this.state="",this.legacyPrivacyAcknowledged=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zr).fromBinary(t,r)}static fromJson(t,r){return(new zr).fromJson(t,r)}static fromJsonString(t,r){return(new zr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(zr,t,r)}static $(){return["CompleteXaiCursorAccountLinkRequest|1 code 9?|2 state 9|3 oauth_error 9?|4 legacy_privacy_acknowledged 8|5 consent_token 9?"]}}class jr extends w{constructor(t){super(),this.outcome=K.UNSPECIFIED,this.returnUri="",this.legacyPrivacyAcknowledgementRequired=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jr).fromBinary(t,r)}static fromJson(t,r){return(new jr).fromJson(t,r)}static fromJsonString(t,r){return(new jr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(jr,t,r)}static $(){return["CompleteXaiCursorAccountLinkResponse|1 outcome #0|2 return_uri 9|3 continuation_state 9?|4 cursor_user_id 5?|5 cursor_email 9?|6 legacy_privacy_acknowledgement_required 8|7 consent_token 9?|8 xai_email 9?|9 replaced_shadow_email 9?",K]}}class Hr extends w{constructor(t){super(),this.state="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hr).fromBinary(t,r)}static fromJson(t,r){return(new Hr).fromJson(t,r)}static fromJsonString(t,r){return(new Hr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Hr,t,r)}static $(){return["PeekXaiCursorAccountLinkContinuationRequest|1 state 9"]}}class Wr extends w{constructor(t){super(),this.cursorEmail="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wr).fromBinary(t,r)}static fromJson(t,r){return(new Wr).fromJson(t,r)}static fromJsonString(t,r){return(new Wr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Wr,t,r)}static $(){return["PeekXaiCursorAccountLinkContinuationResponse|1 cursor_email 9|2 replaced_shadow_email 9?|3 replaced_shadow_created_at #0?",s.Timestamp]}}class Qr extends w{constructor(t){super(),this.id="",this.status=z.UNSPECIFIED,this.reason="",this.reasonCode="",this.issues=[],this.workflowState=j.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qr).fromBinary(t,r)}static fromJson(t,r){return(new Qr).fromJson(t,r)}static fromJsonString(t,r){return(new Qr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Qr,t,r)}static $(){return["EnterpriseGrokMigration|1 id 9|2 status #0|3 reason 9|4 reason_code 9|5 consented_at #1|6 completed_at #1?|7 issues #2*|8 workflow_state #3",z,s.Timestamp,Vr,j]}}class Vr extends w{constructor(t){super(),this.code="",this.message="",this.members=[],this.memberCount=0,this.teamNames=[],this.accounts=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vr).fromBinary(t,r)}static fromJson(t,r){return(new Vr).fromJson(t,r)}static fromJsonString(t,r){return(new Vr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Vr,t,r)}static $(){return["EnterpriseGrokMigrationIssue|1 code 9|2 message 9|3 members 9*|4 member_count 5|5 team_names 9*|6 accounts #0*",Xr]}}class Xr extends w{constructor(t){super(),this.cursorUserId=0,this.email="",this.xaiUserId="",this.reason="",this.xaiTeamId="",this.xaiTeamName="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xr).fromBinary(t,r)}static fromJson(t,r){return(new Xr).fromJson(t,r)}static fromJsonString(t,r){return(new Xr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Xr,t,r)}static $(){return["EnterpriseGrokMigrationRefusedAccount|1 cursor_user_id 5|2 email 9|3 xai_user_id 9|4 reason 9|5 xai_team_id 9|6 xai_team_name 9"]}}class Yr extends w{constructor(t){super(),this.cursorUserId=0,this.name="",this.email="",this.xaiPlan="",this.additionalXaiUserIds=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yr).fromBinary(t,r)}static fromJson(t,r){return(new Yr).fromJson(t,r)}static fromJsonString(t,r){return(new Yr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Yr,t,r)}static $(){return["EnterpriseGrokConflictingAccount|1 cursor_user_id 5|2 xai_user_id 9?|3 name 9|4 email 9|5 xai_plan 9|6 last_active_at #0?|7 additional_xai_user_ids 9*",s.Timestamp]}}class Zr extends w{constructor(t){super(),this.status=H.UNSPECIFIED,this.issues=[],this.reason="",this.conflictingAccounts=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zr).fromBinary(t,r)}static fromJson(t,r){return(new Zr).fromJson(t,r)}static fromJsonString(t,r){return(new Zr).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Zr,t,r)}static $(){return["EnterpriseGrokMigrationEligibility|1 status #0|2 issues #1*|3 reason 9|4 started_at #2?|5 completed_at #2?|6 conflicting_accounts #3*",H,Vr,s.Timestamp,Yr]}}class te extends w{constructor(t){super(),this.organizationId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new te).fromBinary(t,r)}static fromJson(t,r){return(new te).fromJson(t,r)}static fromJsonString(t,r){return(new te).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(te,t,r)}static $(){return["CheckEnterpriseGrokMigrationEligibilityRequest|1 organization_id 9"]}}class re extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new re).fromBinary(t,r)}static fromJson(t,r){return(new re).fromJson(t,r)}static fromJsonString(t,r){return(new re).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(re,t,r)}static $(){return["CheckEnterpriseGrokMigrationEligibilityResponse|1 eligibility #0",Zr]}}class ee extends w{constructor(t){super(),this.organizationId="",this.acknowledgments=[],this.termsVersion="",this.legacyPrivacyAcknowledged=!1,this.consentedDeleteCursorUserIds=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ee).fromBinary(t,r)}static fromJson(t,r){return(new ee).fromJson(t,r)}static fromJsonString(t,r){return(new ee).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ee,t,r)}static $(){return["StartEnterpriseGrokMigrationRequest|1 organization_id 9|2 acknowledgments 9*|3 terms_version 9|4 marketing_opted_out 8?|5 legacy_privacy_acknowledged 8|6 consented_delete_cursor_user_ids 5*"]}}class ne extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ne).fromBinary(t,r)}static fromJson(t,r){return(new ne).fromJson(t,r)}static fromJsonString(t,r){return(new ne).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ne,t,r)}static $(){return["StartEnterpriseGrokMigrationResponse|1 migration #0",Qr]}}class se extends w{constructor(t){super(),this.organizationId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new se).fromBinary(t,r)}static fromJson(t,r){return(new se).fromJson(t,r)}static fromJsonString(t,r){return(new se).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(se,t,r)}static $(){return["GetEnterpriseGrokMigrationStatusRequest|1 organization_id 9"]}}class ie extends w{constructor(t){super(),this.legacyPrivacyAcknowledgementRequired=!1,this.conflictingAccounts=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ie).fromBinary(t,r)}static fromJson(t,r){return(new ie).fromJson(t,r)}static fromJsonString(t,r){return(new ie).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ie,t,r)}static $(){return["GetEnterpriseGrokMigrationStatusResponse|1 migration #0?|2 legacy_privacy_acknowledgement_required 8|3 eligibility #1?|4 conflicting_accounts #2*",Qr,Zr,Yr]}}class oe extends w{constructor(t){super(),this.teamId=0,this.userId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oe).fromBinary(t,r)}static fromJson(t,r){return(new oe).fromJson(t,r)}static fromJsonString(t,r){return(new oe).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(oe,t,r)}static $(){return["RetryTeamXaiMembershipHoldRequest|1 team_id 5|2 user_id 5"]}}class ae extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ae).fromBinary(t,r)}static fromJson(t,r){return(new ae).fromJson(t,r)}static fromJsonString(t,r){return(new ae).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ae,t,r)}static $(){return["RetryTeamXaiMembershipHoldResponse|1 migration #0",Qr]}}class ue extends w{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ue).fromBinary(t,r)}static fromJson(t,r){return(new ue).fromJson(t,r)}static fromJsonString(t,r){return(new ue).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ue,t,r)}static $(){return["GetTeamUnifiedStatusInternalRequest|1 team_id 5"]}}class ce extends w{constructor(t){super(),this.status=W.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ce).fromBinary(t,r)}static fromJson(t,r){return(new ce).fromJson(t,r)}static fromJsonString(t,r){return(new ce).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ce,t,r)}static $(){return["GetTeamUnifiedStatusInternalResponse|1 status #0",W]}}class le extends w{constructor(t){super(),this.trialId=s.protoInt64.zero,this.teamId=0,this.state=Q.UNSPECIFIED,this.startsAtMs=s.protoInt64.zero,this.endsAtMs=s.protoInt64.zero,this.complatGrantSkipped=!1,this.startedBy="",this.source=V.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new le).fromBinary(t,r)}static fromJson(t,r){return(new le).fromJson(t,r)}static fromJsonString(t,r){return(new le).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(le,t,r)}static $(){return["UnifiedTeamTrial|1 trial_id 3|2 team_id 5|3 state #0|4 starts_at_ms 3|5 ends_at_ms 3|6 target_ends_at_ms 3?|7 complat_grant_skipped 8|8 complat_subscription_id 9?|9 seat_quantity 5?|10 credit_cents 3?|11 credit_expires_at_ms 3?|12 started_by 9|13 source #1|14 closed_at_ms 3?",Q,V]}}class me extends w{constructor(t){super(),this.outcome=X.UNSPECIFIED,this.refusalReason="",this.message="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new me).fromBinary(t,r)}static fromJson(t,r){return(new me).fromJson(t,r)}static fromJsonString(t,r){return(new me).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(me,t,r)}static $(){return["UnifiedTeamTrialInternalResponse|1 outcome #0|2 trial #1?|3 refusal_reason 9|4 message 9",X,le]}}class fe extends w{constructor(t){super(),this.teamId=0,this.targetEndsAtMs=s.protoInt64.zero,this.creditCents=s.protoInt64.zero,this.seatQuantity=0,this.startedBy="",this.source=V.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fe).fromBinary(t,r)}static fromJson(t,r){return(new fe).fromJson(t,r)}static fromJsonString(t,r){return(new fe).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(fe,t,r)}static $(){return["StartUnifiedTeamTrialInternalRequest|1 team_id 5|2 target_ends_at_ms 3|3 credit_cents 3|4 seat_quantity 5|5 started_by 9|6 source #0",V]}}class de extends w{constructor(t){super(),this.teamId=0,this.extendedBy="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new de).fromBinary(t,r)}static fromJson(t,r){return(new de).fromJson(t,r)}static fromJsonString(t,r){return(new de).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(de,t,r)}static $(){return["ExtendUnifiedTeamTrialInternalRequest|1 team_id 5|2 target_ends_at_ms 3?|3 credit_cents 3?|4 seat_quantity 5?|5 extended_by 9"]}}class pe extends w{constructor(t){super(),this.teamId=0,this.endedBy="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pe).fromBinary(t,r)}static fromJson(t,r){return(new pe).fromJson(t,r)}static fromJsonString(t,r){return(new pe).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(pe,t,r)}static $(){return["EndUnifiedTeamTrialInternalRequest|1 team_id 5|2 ended_by 9"]}}class he extends w{constructor(t){super(),this.teamId=0,this.contractEndsAtMs=s.protoInt64.zero,this.seatQuantity=0,this.convertedBy="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new he).fromBinary(t,r)}static fromJson(t,r){return(new he).fromJson(t,r)}static fromJsonString(t,r){return(new he).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(he,t,r)}static $(){return["ConvertUnifiedTeamTrialInternalRequest|1 team_id 5|2 contract_ends_at_ms 3|3 seat_quantity 5|4 converted_by 9"]}}class ge extends w{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ge).fromBinary(t,r)}static fromJson(t,r){return(new ge).fromJson(t,r)}static fromJsonString(t,r){return(new ge).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ge,t,r)}static $(){return["GetUnifiedTeamTrialInternalRequest|1 team_id 5"]}}class _e extends w{constructor(t){super(),this.startEnabled=!1,this.activeSeatCount=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _e).fromBinary(t,r)}static fromJson(t,r){return(new _e).fromJson(t,r)}static fromJsonString(t,r){return(new _e).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(_e,t,r)}static $(){return["GetUnifiedTeamTrialInternalResponse|1 trial #0?|2 start_enabled 8|3 active_seat_count 5",le]}}class Je extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Je).fromBinary(t,r)}static fromJson(t,r){return(new Je).fromJson(t,r)}static fromJsonString(t,r){return(new Je).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Je,t,r)}static $(){return["GetGrokCreditPackPurchaseAccountRequest"]}}class we extends w{constructor(t){super(),this.eligible=!1,this.xaiUserId="",this.ineligibleReason="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new we).fromBinary(t,r)}static fromJson(t,r){return(new we).fromJson(t,r)}static fromJsonString(t,r){return(new we).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(we,t,r)}static $(){return["GetGrokCreditPackPurchaseAccountResponse|1 eligible 8|2 xai_user_id 9|3 ineligible_reason 9"]}}class ye extends w{constructor(t){super(),this.purchase={case:void 0},s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ye).fromBinary(t,r)}static fromJson(t,r){return(new ye).fromJson(t,r)}static fromJsonString(t,r){return(new ye).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ye,t,r)}static $(){return["ReportGrokCreditPackPurchaseRequest|1 apple #0 purchase|2 google #1 purchase",Se,qe]}}class Se extends w{constructor(t){super(),this.transactionId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Se).fromBinary(t,r)}static fromJson(t,r){return(new Se).fromJson(t,r)}static fromJsonString(t,r){return(new Se).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Se,t,r)}static $(){return["ReportGrokCreditPackPurchaseRequest.Apple|1 transaction_id 9"]}}class qe extends w{constructor(t){super(),this.purchaseToken="",this.productId="",this.packageName="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qe).fromBinary(t,r)}static fromJson(t,r){return(new qe).fromJson(t,r)}static fromJsonString(t,r){return(new qe).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(qe,t,r)}static $(){return["ReportGrokCreditPackPurchaseRequest.Google|1 purchase_token 9|2 product_id 9|3 package_name 9"]}}class Be extends w{constructor(t){super(),this.outcome=Y.UNSPECIFIED,this.productId="",this.amountCents=s.protoInt64.zero,this.reason="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Be).fromBinary(t,r)}static fromJson(t,r){return(new Be).fromJson(t,r)}static fromJsonString(t,r){return(new Be).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Be,t,r)}static $(){return["ReportGrokCreditPackPurchaseResponse|1 outcome #0|2 product_id 9|3 amount_cents 3|4 reason 9",Y]}}class Ie extends w{constructor(t){super(),this.teamId=0,this.userId=0,this.targetTier=n.tE_.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ie).fromBinary(t,r)}static fromJson(t,r){return(new Ie).fromJson(t,r)}static fromJsonString(t,r){return(new Ie).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ie,t,r)}static $(){return["StartMergedTeamSeatChangeRequest|1 team_id 5|2 user_id 5|3 target_tier #0",n.tE_]}}class Pe extends w{constructor(t){super(),this.reason=Z.UNSPECIFIED,this.message="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pe).fromBinary(t,r)}static fromJson(t,r){return(new Pe).fromJson(t,r)}static fromJsonString(t,r){return(new Pe).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Pe,t,r)}static $(){return["MergedTeamSeatChangeRefusal|1 reason #0|2 message 9",Z]}}class be extends w{constructor(t){super(),this.result={case:void 0},s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new be).fromBinary(t,r)}static fromJson(t,r){return(new be).fromJson(t,r)}static fromJsonString(t,r){return(new be).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(be,t,r)}static $(){return["StartMergedTeamSeatChangeResponse|1 checkout_url 9 result|2 refusal #0 result",Pe]}}class Re extends w{constructor(t){super(),this.teamId=0,this.userId=0,this.targetTier=n.tE_.UNSPECIFIED,this.idempotencyKey="",this.direct=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Re).fromBinary(t,r)}static fromJson(t,r){return(new Re).fromJson(t,r)}static fromJsonString(t,r){return(new Re).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Re,t,r)}static $(){return["ChangeMergedTeamSeatRequest|1 team_id 5|2 user_id 5|3 target_tier #0|4 idempotency_key 9|5 direct 8",n.tE_]}}class ve extends w{constructor(t){super(),this.outcome=tt.UNSPECIFIED,this.message="",this.effectiveAt="",this.manageOnGrokUrl="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ve).fromBinary(t,r)}static fromJson(t,r){return(new ve).fromJson(t,r)}static fromJsonString(t,r){return(new ve).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ve,t,r)}static $(){return["MergedTeamSeatChangeAnswer|1 outcome #0|2 message 9|3 effective_at 9|4 manage_on_grok_url 9|5 payment_challenge #1",tt,n._P7]}}class xe extends w{constructor(t){super(),this.result={case:void 0},s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xe).fromBinary(t,r)}static fromJson(t,r){return(new xe).fromJson(t,r)}static fromJsonString(t,r){return(new xe).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(xe,t,r)}static $(){return["ChangeMergedTeamSeatResponse|1 checkout_url 9 result|2 refusal #0 result|3 answer #1 result",Pe,ve]}}class ke extends w{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ke).fromBinary(t,r)}static fromJson(t,r){return(new ke).fromJson(t,r)}static fromJsonString(t,r){return(new ke).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ke,t,r)}static $(){return["GetMergedTeamSeatChangesRequest|1 team_id 5"]}}class Ee extends w{constructor(t){super(),this.userId=0,this.pendingTier=n.tE_.UNSPECIFIED,this.effectiveAt="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ee).fromBinary(t,r)}static fromJson(t,r){return(new Ee).fromJson(t,r)}static fromJsonString(t,r){return(new Ee).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ee,t,r)}static $(){return["MergedTeamPendingSeatChange|1 user_id 5|2 pending_tier #0|3 effective_at 9",n.tE_]}}class Ce extends w{constructor(t){super(),this.directChangeEnabled=!1,this.pendingChangesAvailable=!1,this.pendingChanges=[],this.seatAvailabilityAvailable=!1,this.availablePaidSeatTiers=[],this.unavailablePaidSeatTiers=[],this.singleSeatPlan=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ce).fromBinary(t,r)}static fromJson(t,r){return(new Ce).fromJson(t,r)}static fromJsonString(t,r){return(new Ce).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ce,t,r)}static $(){return["GetMergedTeamSeatChangesResponse|1 direct_change_enabled 8|2 pending_changes_available 8|3 pending_changes #0*|4 seat_availability_available 8|5 available_paid_seat_tiers #1*|6 unavailable_paid_seat_tiers #1*|7 single_seat_plan 8",Ee,n.tE_]}}class Te extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Te).fromBinary(t,r)}static fromJson(t,r){return(new Te).fromJson(t,r)}static fromJsonString(t,r){return(new Te).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Te,t,r)}static $(){return["ListUnifiedInvoicesRequest|1 team_id 5?"]}}class Ue extends w{constructor(t){super(),this.invoiceId="",this.invoiceReference="",this.kind=rt.UNSPECIFIED,this.status=et.UNSPECIFIED,this.source=nt.UNSPECIFIED,this.issuedAtMs=s.protoInt64.zero,this.amountCents=s.protoInt64.zero,this.currency="",this.description="",this.pdfUrl="",this.pdfAssetKey="",this.hostedInvoiceUrl="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ue).fromBinary(t,r)}static fromJson(t,r){return(new Ue).fromJson(t,r)}static fromJsonString(t,r){return(new Ue).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ue,t,r)}static $(){return["UnifiedInvoice|1 invoice_id 9|2 invoice_reference 9|3 kind #0|4 status #1|5 source #2|6 issued_at_ms 3|7 period_start_ms 3?|8 period_end_ms 3?|9 amount_cents 3|10 currency 9|11 description 9|12 pdf_url 9|13 pdf_asset_key 9|14 hosted_invoice_url 9",rt,et,nt]}}class Ae extends w{constructor(t){super(),this.invoices=[],this.unavailableSources=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ae).fromBinary(t,r)}static fromJson(t,r){return(new Ae).fromJson(t,r)}static fromJsonString(t,r){return(new Ae).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ae,t,r)}static $(){return["ListUnifiedInvoicesResponse|1 invoices #0*|2 unavailable_sources #1*",Ue,nt]}}class $e extends w{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $e).fromBinary(t,r)}static fromJson(t,r){return(new $e).fromJson(t,r)}static fromJsonString(t,r){return(new $e).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals($e,t,r)}static $(){return["GetXaiCursorTeamMergeStatusRequest|1 team_id 5"]}}class Me extends w{constructor(t){super(),this.enabled=!1,this.merged=!1,this.xaiTeamId="",this.hasPendingProposal=!1,this.proposedXaiTeamId="",this.canConfirmProposal=!1,this.checkoutState=st.UNSPECIFIED,this.cart=[],this.hasPendingPurchase=!1,this.canCreateXaiTeam=!1,this.proposedXaiTeamName="",this.actingAdminGrokEmail="",this.adminReady=!1,this.legacyPrivacyAcknowledgementRequired=!1,this.intentPublicId="",this.processingBlockCode="",this.unifyBlocklisted=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Me).fromBinary(t,r)}static fromJson(t,r){return(new Me).fromJson(t,r)}static fromJsonString(t,r){return(new Me).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Me,t,r)}static $(){return["GetXaiCursorTeamMergeStatusResponse|1 enabled 8|2 merged 8|3 xai_team_id 9|4 merged_at_ms 3?|5 has_pending_proposal 8|6 proposed_xai_team_id 9|7 proposal_expires_at_ms 3?|8 can_confirm_proposal 8|9 checkout_state #0|10 cart #1*|11 has_pending_purchase 8|12 can_create_xai_team 8|13 proposed_xai_team_name 9|14 acting_admin_grok_linked 8?|15 legacy_billing_settlement #2?|16 acting_admin_grok_email 9|17 cursor_stripe_credit_balance_cents 3?|18 admin_ready 8|19 legacy_privacy_acknowledgement_required 8|20 wallet_ready 8?|21 intent_public_id 9|22 processing_block_code 9|23 unify_blocklisted 8",st,Oe,$t]}}class Oe extends w{constructor(t){super(),this.skuId="",this.quantity=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Oe).fromBinary(t,r)}static fromJson(t,r){return(new Oe).fromJson(t,r)}static fromJsonString(t,r){return(new Oe).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Oe,t,r)}static $(){return["XaiCursorTeamCheckoutCartLine|1 sku_id 9|2 quantity 5"]}}class De extends w{constructor(t){super(),this.teamId=0,this.pageSize=0,this.offset=0,this.searchQuery="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new De).fromBinary(t,r)}static fromJson(t,r){return(new De).fromJson(t,r)}static fromJsonString(t,r){return(new De).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(De,t,r)}static $(){return["GetXaiCursorTeamMembershipPreviewRequest|1 team_id 5|2 page_size 5|3 offset 5|4 search_query 9"]}}class Ne extends w{constructor(t){super(),this.userId=0,this.email="",this.name="",this.currentRole=it.UNSPECIFIED,this.intendedRole=it.UNSPECIFIED,this.cursorTeamRole=n.acM.UNSPECIFIED,this.cursorBillingTier=n.Xvt.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ne).fromBinary(t,r)}static fromJson(t,r){return(new Ne).fromJson(t,r)}static fromJsonString(t,r){return(new Ne).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ne,t,r)}static $(){return["XaiCursorTeamMembershipPreviewCursorMember|1 user_id 5|2 email 9|3 name 9|4 selected_sku_id 9?|5 current_role #0|6 intended_role #0|7 cursor_team_role #1|8 cursor_billing_tier #2|9 effective_sku_id 9?",it,n.acM,n.Xvt]}}class Ge extends w{constructor(t){super(),this.userId="",this.email="",this.givenName="",this.familyName="",this.previousSkuId="",this.currentRole=it.UNSPECIFIED,this.intendedRole=it.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ge).fromBinary(t,r)}static fromJson(t,r){return(new Ge).fromJson(t,r)}static fromJsonString(t,r){return(new Ge).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ge,t,r)}static $(){return["XaiCursorTeamMembershipPreviewGrokMember|1 user_id 9|2 email 9|3 given_name 9|4 family_name 9|5 selected_sku_id 9?|6 previous_sku_id 9|7 current_role #0|8 intended_role #0|9 effective_sku_id 9?",it]}}class Le extends w{constructor(t){super(),this.email="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Le).fromBinary(t,r)}static fromJson(t,r){return(new Le).fromJson(t,r)}static fromJsonString(t,r){return(new Le).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Le,t,r)}static $(){return["XaiCursorTeamMembershipPreviewMatch|1 email 9|2 cursor_member #0|3 grok_member #1",Ne,Ge]}}class Fe extends w{constructor(t){super(),this.enabled=!1,this.xaiRosterAvailable=!1,this.matched=[],this.cursorOnly=[],this.grokOnly=[],this.xaiSeatAssignmentsAvailable=!1,this.totalMemberCount=0,this.filteredMemberCount=0,this.nextOffset=0,this.hasMore=!1,this.skuCounts=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fe).fromBinary(t,r)}static fromJson(t,r){return(new Fe).fromJson(t,r)}static fromJsonString(t,r){return(new Fe).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Fe,t,r)}static $(){return["GetXaiCursorTeamMembershipPreviewResponse|1 enabled 8|2 xai_roster_available 8|3 matched #0*|4 cursor_only #1*|5 grok_only #2*|6 xai_seat_assignments_available 8|7 total_member_count 5|8 filtered_member_count 5|9 next_offset 5|10 has_more 8|11 sku_counts #3*|12 monthly_total_micros 3?",Le,Ne,Ge,Ke]}}class Ke extends w{constructor(t){super(),this.skuId="",this.memberCount=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ke).fromBinary(t,r)}static fromJson(t,r){return(new Ke).fromJson(t,r)}static fromJsonString(t,r){return(new Ke).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ke,t,r)}static $(){return["XaiCursorTeamMembershipPreviewSkuCount|1 sku_id 9|2 member_count 5"]}}class ze extends w{constructor(t){super(),this.cursorUserId=0,this.xaiUserId="",this.role=it.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ze).fromBinary(t,r)}static fromJson(t,r){return(new ze).fromJson(t,r)}static fromJsonString(t,r){return(new ze).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ze,t,r)}static $(){return["XaiCursorTeamMemberRoleSelection|1 cursor_user_id 5|2 xai_user_id 9|3 role #0",it]}}class je extends w{constructor(t){super(),this.teamId=0,this.roleSelections=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new je).fromBinary(t,r)}static fromJson(t,r){return(new je).fromJson(t,r)}static fromJsonString(t,r){return(new je).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(je,t,r)}static $(){return["UpdateXaiCursorTeamMemberRolesRequest|1 team_id 5|2 role_selections #0*",ze]}}class He extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new He).fromBinary(t,r)}static fromJson(t,r){return(new He).fromJson(t,r)}static fromJsonString(t,r){return(new He).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(He,t,r)}static $(){return["UpdateXaiCursorTeamMemberRolesResponse"]}}class We extends w{constructor(t){super(),this.teamId=0,this.redirectUri="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new We).fromBinary(t,r)}static fromJson(t,r){return(new We).fromJson(t,r)}static fromJsonString(t,r){return(new We).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(We,t,r)}static $(){return["StartXaiCursorTeamMergeRequest|1 team_id 5|2 redirect_uri 9"]}}class Qe extends w{constructor(t){super(),this.connectUrl="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qe).fromBinary(t,r)}static fromJson(t,r){return(new Qe).fromJson(t,r)}static fromJsonString(t,r){return(new Qe).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Qe,t,r)}static $(){return["StartXaiCursorTeamMergeResponse|1 connect_url 9"]}}class Ve extends w{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ve).fromBinary(t,r)}static fromJson(t,r){return(new Ve).fromJson(t,r)}static fromJsonString(t,r){return(new Ve).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ve,t,r)}static $(){return["GetXaiCursorTeamMergeGrokTeamsRequest|1 team_id 5"]}}class Xe extends w{constructor(t){super(),this.xaiTeamId="",this.name="",this.planTier="",this.memberCount=0,this.isBillingAdmin=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xe).fromBinary(t,r)}static fromJson(t,r){return(new Xe).fromJson(t,r)}static fromJsonString(t,r){return(new Xe).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Xe,t,r)}static $(){return["XaiCursorTeamMergeGrokTeam|1 xai_team_id 9|2 name 9|3 plan_tier 9|4 member_count 5|5 is_billing_admin 8"]}}class Ye extends w{constructor(t){super(),this.state=ot.UNSPECIFIED,this.signedInEmail="",this.eligibleTeams=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ye).fromBinary(t,r)}static fromJson(t,r){return(new Ye).fromJson(t,r)}static fromJsonString(t,r){return(new Ye).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ye,t,r)}static $(){return["GetXaiCursorTeamMergeGrokTeamsResponse|1 state #0|2 signed_in_email 9|3 eligible_teams #1*",ot,Xe]}}class Ze extends w{constructor(t){super(),this.teamId=0,this.xaiTeamId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ze).fromBinary(t,r)}static fromJson(t,r){return(new Ze).fromJson(t,r)}static fromJsonString(t,r){return(new Ze).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ze,t,r)}static $(){return["SelectXaiCursorTeamMergeGrokTeamRequest|1 team_id 5|2 xai_team_id 9"]}}class tn extends w{constructor(t){super(),this.success=!1,this.intentPublicId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tn).fromBinary(t,r)}static fromJson(t,r){return(new tn).fromJson(t,r)}static fromJsonString(t,r){return(new tn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(tn,t,r)}static $(){return["SelectXaiCursorTeamMergeGrokTeamResponse|1 success 8|2 selected_team #0|3 intent_public_id 9",Xe]}}class rn extends w{constructor(t){super(),this.teamId=0,this.xaiTeamId="",this.skuSelections=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rn).fromBinary(t,r)}static fromJson(t,r){return(new rn).fromJson(t,r)}static fromJsonString(t,r){return(new rn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(rn,t,r)}static $(){return["ConfirmXaiCursorTeamMergeRequest|1 team_id 5|2 xai_team_id 9|3 sku_selections #0*|4 checkout_outcome #1?",en,Br]}}class en extends w{constructor(t){super(),this.cursorUserId=0,this.skuId="",this.xaiUserId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new en).fromBinary(t,r)}static fromJson(t,r){return(new en).fromJson(t,r)}static fromJsonString(t,r){return(new en).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(en,t,r)}static $(){return["XaiCursorTeamMemberSkuSelection|1 cursor_user_id 5|2 sku_id 9|3 xai_user_id 9"]}}class nn extends w{constructor(t){super(),this.cursorUserId=0,this.xaiUserId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nn).fromBinary(t,r)}static fromJson(t,r){return(new nn).fromJson(t,r)}static fromJsonString(t,r){return(new nn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(nn,t,r)}static $(){return["XaiCursorTeamMemberRemoval|1 cursor_user_id 5|2 xai_user_id 9"]}}class sn extends w{constructor(t){super(),this.cursorUserId=0,this.xaiUserId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sn).fromBinary(t,r)}static fromJson(t,r){return(new sn).fromJson(t,r)}static fromJsonString(t,r){return(new sn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(sn,t,r)}static $(){return["XaiCursorTeamMemberPair|1 cursor_user_id 5|2 xai_user_id 9"]}}class on extends w{constructor(t){super(),this.merged=!1,this.xaiTeamId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new on).fromBinary(t,r)}static fromJson(t,r){return(new on).fromJson(t,r)}static fromJsonString(t,r){return(new on).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(on,t,r)}static $(){return["ConfirmXaiCursorTeamMergeResponse|1 merged 8|2 xai_team_id 9"]}}class an extends w{constructor(t){super(),this.teamId=0,this.xaiTeamId="",this.skuSelections=[],this.removals=[],this.pairs=[],this.legacyPrivacyAcknowledged=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new an).fromBinary(t,r)}static fromJson(t,r){return(new an).fromJson(t,r)}static fromJsonString(t,r){return(new an).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(an,t,r)}static $(){return["PrepareXaiCursorTeamMergeCheckoutRequest|1 team_id 5|2 xai_team_id 9|3 sku_selections #0*|4 marketing_opted_out 8?|5 default_sku_id 9?|6 removals #1*|7 pairs #2*|8 legacy_privacy_acknowledged 8",en,nn,sn]}}class un extends w{constructor(t){super(),this.xaiTeamId="",this.cart=[],this.checkoutState=st.UNSPECIFIED,this.legacyPrivacyAcknowledgementRequired=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new un).fromBinary(t,r)}static fromJson(t,r){return(new un).fromJson(t,r)}static fromJsonString(t,r){return(new un).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(un,t,r)}static $(){return["PrepareXaiCursorTeamMergeCheckoutResponse|1 xai_team_id 9|2 cart #0*|3 checkout_state #1|4 legacy_privacy_acknowledgement_required 8",Oe,st]}}class cn extends w{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cn).fromBinary(t,r)}static fromJson(t,r){return(new cn).fromJson(t,r)}static fromJsonString(t,r){return(new cn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(cn,t,r)}static $(){return["UnprepareXaiCursorTeamMergeCheckoutRequest|1 team_id 5"]}}class ln extends w{constructor(t){super(),this.xaiTeamId="",this.checkoutState=st.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ln).fromBinary(t,r)}static fromJson(t,r){return(new ln).fromJson(t,r)}static fromJsonString(t,r){return(new ln).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ln,t,r)}static $(){return["UnprepareXaiCursorTeamMergeCheckoutResponse|1 xai_team_id 9|2 checkout_state #0",st]}}class mn extends w{constructor(t){super(),this.teamId=0,this.legacyPrivacyAcknowledged=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mn).fromBinary(t,r)}static fromJson(t,r){return(new mn).fromJson(t,r)}static fromJsonString(t,r){return(new mn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(mn,t,r)}static $(){return["FinalizeXaiCursorTeamMergeCheckoutRequest|1 team_id 5|2 checkout_outcome #0?|3 legacy_privacy_acknowledged 8",Br]}}class fn extends w{constructor(t){super(),this.checkoutState=st.UNSPECIFIED,this.xaiTeamId="",this.legacyPrivacyAcknowledgementRequired=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fn).fromBinary(t,r)}static fromJson(t,r){return(new fn).fromJson(t,r)}static fromJsonString(t,r){return(new fn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(fn,t,r)}static $(){return["FinalizeXaiCursorTeamMergeCheckoutResponse|1 checkout_state #0|2 xai_team_id 9|3 legacy_billing_settlement #1?|4 legacy_privacy_acknowledgement_required 8",st,$t]}}class dn extends w{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dn).fromBinary(t,r)}static fromJson(t,r){return(new dn).fromJson(t,r)}static fromJsonString(t,r){return(new dn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(dn,t,r)}static $(){return["EnsureXaiCursorTeamForMergeRequest|1 team_id 5"]}}class pn extends w{constructor(t){super(),this.outcome=at.UNSPECIFIED,this.xaiTeamId="",this.created=!1,this.intentPublicId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pn).fromBinary(t,r)}static fromJson(t,r){return(new pn).fromJson(t,r)}static fromJsonString(t,r){return(new pn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(pn,t,r)}static $(){return["EnsureXaiCursorTeamForMergeResponse|3 outcome #0|1 xai_team_id 9|2 created 8|4 intent_public_id 9",at]}}class hn extends w{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hn).fromBinary(t,r)}static fromJson(t,r){return(new hn).fromJson(t,r)}static fromJsonString(t,r){return(new hn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(hn,t,r)}static $(){return["GetXaiCursorTeamMergePrepaidPreviewRequest|1 team_id 5"]}}class gn extends w{constructor(t){super(),this.available=!1,this.grokBusinessSeats=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gn).fromBinary(t,r)}static fromJson(t,r){return(new gn).fromJson(t,r)}static fromJsonString(t,r){return(new gn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(gn,t,r)}static $(){return["GetXaiCursorTeamMergePrepaidPreviewResponse|1 available 8|2 prepaid_balance_cents 3?|3 grok_auto_top_up #0?|4 grok_monthly_cap_cents 3?|5 grok_business_seats 8",n.xYM]}}class _n extends w{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _n).fromBinary(t,r)}static fromJson(t,r){return(new _n).fromJson(t,r)}static fromJsonString(t,r){return(new _n).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(_n,t,r)}static $(){return["CancelXaiCursorTeamMergeProposalRequest|1 team_id 5"]}}class Jn extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jn).fromBinary(t,r)}static fromJson(t,r){return(new Jn).fromJson(t,r)}static fromJsonString(t,r){return(new Jn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Jn,t,r)}static $(){return["CancelXaiCursorTeamMergeProposalResponse"]}}class wn extends w{constructor(t){super(),this.cursorUserId=s.protoInt64.zero,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wn).fromBinary(t,r)}static fromJson(t,r){return(new wn).fromJson(t,r)}static fromJsonString(t,r){return(new wn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(wn,t,r)}static $(){return["GetXaiEmailEligibilityInternalRequest|1 cursor_user_id 3"]}}class yn extends w{constructor(t){super(),this.kind=ut.UNSPECIFIED,this.accountExists=!1,this.xaiUserId="",this.shouldBeSuggested=!1,this.unificationStatus=ct.UNSPECIFIED,this.isLinkedToDifferentEmail=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yn).fromBinary(t,r)}static fromJson(t,r){return(new yn).fromJson(t,r)}static fromJsonString(t,r){return(new yn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(yn,t,r)}static $(){return["GetXaiEmailEligibilityInternalResponse|1 kind #0|2 account_exists 8|3 xai_user_id 9|4 should_be_suggested 8|5 unification_status #1|6 is_linked_to_different_email 8",ut,ct]}}class Sn extends w{constructor(t){super(),this.xUserId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sn).fromBinary(t,r)}static fromJson(t,r){return(new Sn).fromJson(t,r)}static fromJsonString(t,r){return(new Sn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Sn,t,r)}static $(){return["LookupGrokAccountsByXUserInternalRequest|1 x_user_id 9"]}}class qn extends w{constructor(t){super(),this.xaiSubject="",this.blocked=!1,this.isShadow=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qn).fromBinary(t,r)}static fromJson(t,r){return(new qn).fromJson(t,r)}static fromJsonString(t,r){return(new qn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(qn,t,r)}static $(){return["GrokAccountByXUser|1 xai_subject 9|2 blocked 8|3 is_shadow 8"]}}class Bn extends w{constructor(t){super(),this.kind=lt.UNSPECIFIED,this.accounts=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bn).fromBinary(t,r)}static fromJson(t,r){return(new Bn).fromJson(t,r)}static fromJsonString(t,r){return(new Bn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Bn,t,r)}static $(){return["LookupGrokAccountsByXUserInternalResponse|1 kind #0|2 accounts #1*",lt,qn]}}class In extends w{constructor(t){super(),this.tier="",this.yearly=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new In).fromBinary(t,r)}static fromJson(t,r){return(new In).fromJson(t,r)}static fromJsonString(t,r){return(new In).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(In,t,r)}static $(){return["StartUnifiedCheckoutRequest|1 tier 9|2 yearly 8"]}}class Pn extends w{constructor(t){super(),this.outcome=bn.UNSPECIFIED,this.checkoutUrl="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pn).fromBinary(t,r)}static fromJson(t,r){return(new Pn).fromJson(t,r)}static fromJsonString(t,r){return(new Pn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Pn,t,r)}static $(){return["StartUnifiedCheckoutResponse|1 outcome #0|2 checkout_url 9",bn]}}var bn=(0,i.QT)(s.proto3,J,"StartUnifiedCheckoutResponse.Outcome",[[0,"UNSPECIFIED"],[1,"CHECKOUT"],[2,"UNIFY_REQUIRED"],[3,"ALREADY_SUBSCRIBED"],[4,"NOT_AVAILABLE"],[5,"UNAVAILABLE"]],1);class Rn extends w{constructor(t){super(),this.code="",this.state="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rn).fromBinary(t,r)}static fromJson(t,r){return(new Rn).fromJson(t,r)}static fromJsonString(t,r){return(new Rn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Rn,t,r)}static $(){return["ParkUnifyGrokOAuthForAppSheetRequest|1 code 9|2 state 9"]}}class vn extends w{constructor(t){super(),this.handle="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vn).fromBinary(t,r)}static fromJson(t,r){return(new vn).fromJson(t,r)}static fromJsonString(t,r){return(new vn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(vn,t,r)}static $(){return["ParkUnifyGrokOAuthForAppSheetResponse|1 handle 9"]}}class xn extends w{constructor(t){super(),this.handle="",this.verifier="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xn).fromBinary(t,r)}static fromJson(t,r){return(new xn).fromJson(t,r)}static fromJsonString(t,r){return(new xn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(xn,t,r)}static $(){return["CompleteUnifyGrokOAuthFromAppSheetRequest|1 handle 9|2 verifier 9"]}}class kn extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kn).fromBinary(t,r)}static fromJson(t,r){return(new kn).fromJson(t,r)}static fromJsonString(t,r){return(new kn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(kn,t,r)}static $(){return["GetUnifyAlreadyUnifiedMergeOfferRequest"]}}class En extends w{constructor(t){super(),this.offered=!1,this.offerId="",this.destinationEmail="",this.destinationKind=mt.UNSPECIFIED,this.legacyPrivacyAcknowledgementRequired=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new En).fromBinary(t,r)}static fromJson(t,r){return(new En).fromJson(t,r)}static fromJsonString(t,r){return(new En).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(En,t,r)}static $(){return["GetUnifyAlreadyUnifiedMergeOfferResponse|1 offered 8|2 offer_id 9|3 destination_email 9|4 destination_kind #0|5 legacy_privacy_acknowledgement_required 8",mt]}}class Cn extends w{constructor(t){super(),this.offerId="",this.legacyPrivacyAcknowledged=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cn).fromBinary(t,r)}static fromJson(t,r){return(new Cn).fromJson(t,r)}static fromJsonString(t,r){return(new Cn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Cn,t,r)}static $(){return["StartUnifyAlreadyUnifiedMergeRequest|1 offer_id 9|2 legacy_privacy_acknowledged 8"]}}class Tn extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tn).fromBinary(t,r)}static fromJson(t,r){return(new Tn).fromJson(t,r)}static fromJsonString(t,r){return(new Tn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Tn,t,r)}static $(){return["StartUnifyAlreadyUnifiedMergeResponse"]}}class Un extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Un).fromBinary(t,r)}static fromJson(t,r){return(new Un).fromJson(t,r)}static fromJsonString(t,r){return(new Un).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Un,t,r)}static $(){return["CancelUnifyAlreadyUnifiedMergeRequest"]}}class An extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new An).fromBinary(t,r)}static fromJson(t,r){return(new An).fromJson(t,r)}static fromJsonString(t,r){return(new An).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(An,t,r)}static $(){return["CancelUnifyAlreadyUnifiedMergeResponse"]}}class $n extends w{constructor(t){super(),this.name="",this.privacyModeForced=!1,this.tier="",this.yearly=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $n).fromBinary(t,r)}static fromJson(t,r){return(new $n).fromJson(t,r)}static fromJsonString(t,r){return(new $n).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals($n,t,r)}static $(){return["UnifiedTeamStartDraft|1 name 9|2 privacy_mode_forced 8|3 tier 9|4 yearly 8"]}}class Mn extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mn).fromBinary(t,r)}static fromJson(t,r){return(new Mn).fromJson(t,r)}static fromJsonString(t,r){return(new Mn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Mn,t,r)}static $(){return["ResolveUnifiedTeamStartRequest"]}}class On extends w{constructor(t){super(),this.state=Dn.UNSPECIFIED,this.message="",this.tiers=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new On).fromBinary(t,r)}static fromJson(t,r){return(new On).fromJson(t,r)}static fromJsonString(t,r){return(new On).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(On,t,r)}static $(){return["ResolveUnifiedTeamStartResponse|1 state #0|2 team_id 5?|3 draft #1|4 message 9|5 tiers 9*",Dn,$n]}}var Dn=(0,i.QT)(s.proto3,J,"ResolveUnifiedTeamStartResponse.State",[[0,"UNSPECIFIED"],[1,"STRIPE"],[2,"TEAM_READY"],[3,"ALREADY_ON_TEAM"],[4,"NAME_TEAM"],[5,"CHECKOUT"],[6,"AWAITING_PAYMENT"],[7,"CREATING_TEAM"],[8,"UNIFY_REQUIRED"],[9,"ALREADY_ON_PLAN"],[10,"NOT_AVAILABLE"],[11,"UNAVAILABLE"],[12,"CREATE_FAILED"]],1);class Nn extends w{constructor(t){super(),this.tier="",this.yearly=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nn).fromBinary(t,r)}static fromJson(t,r){return(new Nn).fromJson(t,r)}static fromJsonString(t,r){return(new Nn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Nn,t,r)}static $(){return["StartUnifiedTeamCheckoutRequest|1 tier 9|2 yearly 8|3 team #0",n.nxO]}}class Gn extends w{constructor(t){super(),this.state=Dn.UNSPECIFIED,this.checkoutUrl="",this.message="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gn).fromBinary(t,r)}static fromJson(t,r){return(new Gn).fromJson(t,r)}static fromJsonString(t,r){return(new Gn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Gn,t,r)}static $(){return["StartUnifiedTeamCheckoutResponse|1 state #0|2 team_id 5?|3 checkout_url 9|4 message 9",Dn]}}class Ln extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ln).fromBinary(t,r)}static fromJson(t,r){return(new Ln).fromJson(t,r)}static fromJsonString(t,r){return(new Ln).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ln,t,r)}static $(){return["CreateGrokSignInLinkRequest|1 return_to 9?|2 cursor_return_path 9?"]}}class Fn extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fn).fromBinary(t,r)}static fromJson(t,r){return(new Fn).fromJson(t,r)}static fromJsonString(t,r){return(new Fn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Fn,t,r)}static $(){return["CreateGrokSignInLinkResponse|1 sign_in_url 9?"]}}class Kn extends w{constructor(t){super(),this.code="",this.state="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kn).fromBinary(t,r)}static fromJson(t,r){return(new Kn).fromJson(t,r)}static fromJsonString(t,r){return(new Kn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Kn,t,r)}static $(){return["ParkUnifyXLoginForAppSheetRequest|1 code 9|2 state 9"]}}class zn extends w{constructor(t){super(),this.handle="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zn).fromBinary(t,r)}static fromJson(t,r){return(new zn).fromJson(t,r)}static fromJsonString(t,r){return(new zn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(zn,t,r)}static $(){return["ParkUnifyXLoginForAppSheetResponse|1 handle 9"]}}class jn extends w{constructor(t){super(),this.handle="",this.verifier="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jn).fromBinary(t,r)}static fromJson(t,r){return(new jn).fromJson(t,r)}static fromJsonString(t,r){return(new jn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(jn,t,r)}static $(){return["CompleteUnifyXLoginFromAppSheetRequest|1 handle 9|2 verifier 9"]}}class Hn extends w{constructor(t){super(),this.reason="",this.stage=Wn.UNSPECIFIED,this.alreadyLinkedToSelectedGrok=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hn).fromBinary(t,r)}static fromJson(t,r){return(new Hn).fromJson(t,r)}static fromJsonString(t,r){return(new Hn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Hn,t,r)}static $(){return["UnificationIntentXAccountRefusal|1 reason 9|2 x_username 9?|3 stage #0|4 already_linked_to_selected_grok 8",Wn]}}var Wn=(0,i.QT)(s.proto3,J,"UnificationIntentXAccountRefusal.Stage",[[0,"UNSPECIFIED"],[1,"SIGN_IN"],[2,"FINALIZE"]],1);class Qn extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qn).fromBinary(t,r)}static fromJson(t,r){return(new Qn).fromJson(t,r)}static fromJsonString(t,r){return(new Qn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Qn,t,r)}static $(){return["GetUnifyWaitlistStatusRequest"]}}class Vn extends w{constructor(t){super(),this.status=_.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vn).fromBinary(t,r)}static fromJson(t,r){return(new Vn).fromJson(t,r)}static fromJsonString(t,r){return(new Vn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Vn,t,r)}static $(){return["GetUnifyWaitlistStatusResponse|1 status #0|2 joined_at #1?|3 granted_at #1?",_,s.Timestamp]}}class Xn extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xn).fromBinary(t,r)}static fromJson(t,r){return(new Xn).fromJson(t,r)}static fromJsonString(t,r){return(new Xn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Xn,t,r)}static $(){return["JoinUnifyWaitlistRequest"]}}class Yn extends w{constructor(t){super(),this.status=_.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yn).fromBinary(t,r)}static fromJson(t,r){return(new Yn).fromJson(t,r)}static fromJsonString(t,r){return(new Yn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Yn,t,r)}static $(){return["JoinUnifyWaitlistResponse|1 status #0|2 joined_at #1?",_,s.Timestamp]}}class Zn extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zn).fromBinary(t,r)}static fromJson(t,r){return(new Zn).fromJson(t,r)}static fromJsonString(t,r){return(new Zn).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Zn,t,r)}static $(){return["GetPostPurchaseMergeOfferRequest"]}}class ts extends w{constructor(t){super(),this.offered=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ts).fromBinary(t,r)}static fromJson(t,r){return(new ts).fromJson(t,r)}static fromJsonString(t,r){return(new ts).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ts,t,r)}static $(){return["GetPostPurchaseMergeOfferResponse|1 offered 8|2 super_grok_heavy_ultra_ended_notice #0",n.qKw]}}class rs extends w{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rs).fromBinary(t,r)}static fromJson(t,r){return(new rs).fromJson(t,r)}static fromJsonString(t,r){return(new rs).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(rs,t,r)}static $(){return["GetUnifyMergeNowBannerRequest"]}}class es extends w{constructor(t){super(),this.show=!1,this.cursorPlanStillBilled=!1,this.paidPlanNotice=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new es).fromBinary(t,r)}static fromJson(t,r){return(new es).fromJson(t,r)}static fromJsonString(t,r){return(new es).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(es,t,r)}static $(){return["GetUnifyMergeNowBannerResponse|1 show 8|2 cursor_plan_still_billed 8|3 paid_plan_notice 8"]}}var ns=e("../proto/dist/generated/agent/v1/mcp_pb.js"),ss=e("../proto/dist/generated/agent/v1/mcp_exec_pb.js");const is="aiserver.v1.";class os extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",s.proto3)}static $p(){return is}}class as extends os{constructor(t){super(),this.clientId="",this.redirectUris=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new as).fromBinary(t,r)}static fromJson(t,r){return(new as).fromJson(t,r)}static fromJsonString(t,r){return(new as).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(as,t,r)}static $(){return["McpOAuthStoredData|1 refresh_token 9?|2 client_id 9|3 client_secret 9?|4 redirect_uris 9*|5 access_token 9?"]}}class us extends os{constructor(t){super(),this.state=cs.UNSPECIFIED,this.reason=ls.UNSPECIFIED,this.nextStep=ms.UNSPECIFIED,this.retryAfterSeconds=0,this.missingSetupFields=[],this.owner=fs.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new us).fromBinary(t,r)}static fromJson(t,r){return(new us).fromJson(t,r)}static fromJsonString(t,r){return(new us).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(us,t,r)}static $(){return["McpConnectorStatus|1 state #0|2 reason #1|3 next_step #2|4 retry_after_seconds 5|5 missing_setup_fields 9*|6 owner #3|7 placement #4",cs,ls,ms,fs,ds]}}var cs=(0,i.QT)(s.proto3,is,"McpConnectorStatus.State",[[0,"UNSPECIFIED"],[1,"CONNECTED"],[2,"NEEDS_SIGN_IN"],[3,"SIGN_IN_ENDED"],[4,"NEEDS_SETUP"],[5,"BLOCKED"],[6,"OFF"],[7,"UNAVAILABLE"],[8,"NOT_ON_THIS_SURFACE"],[9,"CHECKING"],[10,"ERROR"]],1),ls=(0,i.QT)(s.proto3,is,"McpConnectorStatus.Reason",[[0,"UNSPECIFIED"],[1,"SIGN_OUT_EXPIRED"],[2,"SIGN_OUT_REVOKED"],[3,"SIGN_OUT_ORGANIZATION_POLICY"],[4,"SIGN_OUT_MFA_REQUIRED"],[5,"SIGN_OUT_ADMIN_BLOCKED"],[6,"SIGN_OUT_ACCOUNT_DISABLED"],[7,"SIGN_OUT_CLIENT_INVALID"],[8,"SIGN_OUT_ACCOUNT_RESTRICTED"],[9,"SIGN_OUT_PROVIDER_UNAVAILABLE"],[10,"SIGN_OUT_PROVIDER_ERROR"],[20,"BLOCKED_MCP_SERVERS_OFF"],[21,"BLOCKED_MCP_ALLOWLIST"],[22,"BLOCKED_CLOUD_AGENT_ALLOWLIST"],[23,"BLOCKED_DENYLIST"],[24,"BLOCKED_APPLIES_TO"],[25,"BLOCKED_NETWORK_ALLOWLIST"],[30,"SETUP_FIELDS"],[31,"SETUP_OAUTH_CLIENT"],[32,"SETUP_CREDENTIAL"],[33,"SETUP_INVALID_CONFIG"],[34,"SETUP_PROVIDER_ACCESS_OFF"],[40,"RUNS_ON_YOUR_COMPUTER"],[41,"COMMAND"],[42,"SERVERS_BLOCKED"],[43,"SERVERS_SIGN_IN_REFUSED"],[50,"RATE_LIMITED"],[51,"SIGN_IN_RENEWAL"],[52,"UNREACHABLE"],[53,"SIGN_IN_DISCOVERY"],[60,"NOT_FOUND"]],1),ms=(0,i.QT)(s.proto3,is,"McpConnectorStatus.NextStep",[[0,"UNSPECIFIED"],[1,"NONE"],[2,"SIGN_IN"],[3,"SIGN_IN_AGAIN"],[4,"FINISH_SETUP"],[5,"ASK_ADMIN"],[6,"OPEN_CURSOR_APP"],[7,"WAIT"],[8,"SHOW_DETAILS"],[9,"MOVE_TO_CLOUD"],[10,"TURN_ON"]],1),fs=(0,i.QT)(s.proto3,is,"McpConnectorStatus.Owner",[[0,"UNSPECIFIED"],[1,"YOU"],[2,"TEAM"],[3,"PLUGIN"],[4,"THIS_COMPUTER"],[5,"THIS_PROJECT"]],1);class ds extends os{constructor(t){super(),this.runsOn=ps.UNSPECIFIED,this.chosenBy=hs.UNSPECIFIED,this.viewerMayChange=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ds).fromBinary(t,r)}static fromJson(t,r){return(new ds).fromJson(t,r)}static fromJsonString(t,r){return(new ds).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ds,t,r)}static $(){return["McpConnectorStatus.Placement|1 runs_on #0|2 chosen_by #1|3 viewer_may_change 8",ps,hs]}}var ps=(0,i.QT)(s.proto3,is,"McpConnectorStatus.Placement.RunsOn",[[0,"UNSPECIFIED"],[1,"SERVERS"],[2,"YOUR_COMPUTER"]],1),hs=(0,i.QT)(s.proto3,is,"McpConnectorStatus.Placement.ChosenBy",[[0,"UNSPECIFIED"],[1,"CURSOR"],[2,"YOU"],[3,"TEAM_ADMIN"],[4,"TEAM_SETTING"],[5,"CONFIG_FILE"],[6,"UNREACHABLE"]],1);const gs="aiserver.v1.";class _s extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",s.proto3)}static $p(){return gs}}var Js=(0,i.QT)(s.proto3,gs,"McpAllowlistImportList",[[0,"UNSPECIFIED"],[1,"ALLOWED"],[2,"DENIED"]],1),ws=(0,i.QT)(s.proto3,gs,"McpAllowlistImportSurface",[[0,"UNSPECIFIED"],[1,"LOCAL"],[2,"CLOUD"],[3,"LOCAL_AND_CLOUD"]],1),ys=(0,i.QT)(s.proto3,gs,"McpAllowlistImportRowStatus",[[0,"UNSPECIFIED"],[1,"NEW"],[2,"UNCHANGED"],[3,"CONFLICT"]],1),Ss=(0,i.QT)(s.proto3,gs,"McpToolAccess",[[0,"UNSPECIFIED"],[1,"ALL"],[2,"READ_ONLY"],[3,"SPECIFIC"]],1),qs=(0,i.QT)(s.proto3,gs,"TeamMcpPlacementDefault",[[0,"UNSPECIFIED"],[1,"UNSET"],[2,"CLIENT"]],1),Bs=(0,i.QT)(s.proto3,gs,"McpOAuthRefreshLockExecutorKind",[[0,"UNSPECIFIED"],[1,"LOCAL_IDE"],[2,"REMOTE_EXTENSION_HOST"]],1),Is=(0,i.QT)(s.proto3,gs,"McpOAuthRefreshLockBeginOutcome",[[0,"UNSPECIFIED"],[1,"SKIPPED"],[2,"WOULD_ACQUIRE"],[3,"WOULD_WAIT"],[4,"REDIS_ERROR"]],1),Ps=(0,i.QT)(s.proto3,gs,"McpOAuthRefreshLockReleaseReason",[[0,"UNSPECIFIED"],[1,"COMPLETE"],[2,"ERROR"],[3,"ABANDONED"]],1),bs=(0,i.QT)(s.proto3,gs,"ConnectorSuiteId",[[0,"UNSPECIFIED"],[1,"GOOGLE_WORKSPACE"],[2,"MICROSOFT_365"]],1),Rs=(0,i.QT)(s.proto3,gs,"ConnectorSuiteMemberOutcome",[[0,"UNSPECIFIED"],[1,"CONNECTED"],[2,"NOT_GRANTED"],[3,"INSTALL_REFUSED"],[4,"CLIENT_PLACED"],[5,"INSTALL_FAILED"],[6,"ALREADY_CONNECTED"],[7,"NOT_CONNECTED"],[8,"DISABLED"],[9,"STORE_FAILED"]],1),vs=(0,i.QT)(s.proto3,gs,"ConnectorSuiteCoverage",[[0,"UNSPECIFIED"],[1,"FULL"],[2,"PARTIAL"],[3,"NONE"]],1),xs=(0,i.QT)(s.proto3,gs,"ConnectorSuiteExposure",[[0,"NONE"],[1,"PASS"],[2,"FAIL"]],1),ks=(0,i.QT)(s.proto3,gs,"McpCloudVerdict",[[0,"UNSPECIFIED"],[1,"USABLE"],[2,"SIGN_IN"],[3,"MOVE_TO_CLOUD"],[4,"LOCAL_ONLY"],[5,"NEEDS_SETUP"],[6,"RETRY"]],1),Es=(0,i.QT)(s.proto3,gs,"McpSignInRefusalKind",[[0,"UNSPECIFIED"],[1,"STDIO"],[2,"CLIENT_ONLY"],[3,"SETUP_REQUIRED"],[4,"OAUTH_CLIENT_UNCONFIGURED"],[5,"REGISTRATION_UNAVAILABLE"],[6,"REGISTRATION_REJECTED"],[7,"RATE_LIMITED"],[8,"OAUTH_WEB_PAGE"],[9,"EGRESS_BLOCKED"],[10,"STATIC_CREDENTIAL"],[11,"ACCESS_DISABLED"],[12,"REFRESH_UNAVAILABLE"],[13,"REFRESH_RACE"],[14,"FRESH_TOKEN_REJECTED"],[15,"TRANSPORT_FAILURE"],[16,"INVALID_CONFIG"],[17,"NOT_FOUND"],[18,"PROBE_FAILED"]],1),Cs=(0,i.QT)(s.proto3,gs,"McpTransportFailureReason",[[0,"UNSPECIFIED"],[1,"DNS"],[2,"REFUSED"],[3,"TLS"],[4,"TIMEOUT"],[5,"HTTP_5XX"]],1),Ts=(0,i.QT)(s.proto3,gs,"McpConnectorAuthState",[[0,"UNSPECIFIED"],[1,"SIGNED_IN"],[2,"SIGNED_OUT"],[3,"UNAVAILABLE"]],1);class Us extends _s{constructor(t){super(),this.organizationId="",this.groupPublicId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Us).fromBinary(t,r)}static fromJson(t,r){return(new Us).fromJson(t,r)}static fromJsonString(t,r){return(new Us).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Us,t,r)}static $(){return["GetOrganizationGroupMcpSettingsRequest|1 organization_id 9|2 group_public_id 9"]}}class As extends _s{constructor(t){super(),this.separate=!1,this.allowedMcpServers=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new As).fromBinary(t,r)}static fromJson(t,r){return(new As).fromJson(t,r)}static fromJsonString(t,r){return(new As).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(As,t,r)}static $(){return["GroupCloudMcpRules|1 separate 8|2 allowed_mcp_servers #0*",n.ufl]}}class $s extends _s{constructor(t){super(),this.mcpRuleSurfacesAvailable=!1,this.firstRuleAddsGrokConnectorsRule=!1,this.firstCloudRuleAddsGrokConnectorsRule=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $s).fromBinary(t,r)}static fromJson(t,r){return(new $s).fromJson(t,r)}static fromJsonString(t,r){return(new $s).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals($s,t,r)}static $(){return["GetOrganizationGroupMcpSettingsResponse|1 allowed_mcp_configuration #0|2 cloud_mcp_rules #1|3 mcp_rule_surfaces_available 8|4 first_rule_adds_grok_connectors_rule 8|5 first_cloud_rule_adds_grok_connectors_rule 8",n.ZM7,As]}}class Ms extends _s{constructor(t){super(),this.organizationId="",this.groupId=s.protoInt64.zero,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ms).fromBinary(t,r)}static fromJson(t,r){return(new Ms).fromJson(t,r)}static fromJsonString(t,r){return(new Ms).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ms,t,r)}static $(){return["UpdateOrganizationGroupMcpSettingsRequest|1 organization_id 9|2 group_id 3|3 allowed_mcp_configuration #0|4 cloud_mcp_rules #1?",n.ZM7,As]}}class Os extends _s{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Os).fromBinary(t,r)}static fromJson(t,r){return(new Os).fromJson(t,r)}static fromJsonString(t,r){return(new Os).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Os,t,r)}static $(){return["UpdateOrganizationGroupMcpSettingsResponse"]}}class Ds extends _s{constructor(t){super(),this.organizationId="",this.groupPublicId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ds).fromBinary(t,r)}static fromJson(t,r){return(new Ds).fromJson(t,r)}static fromJsonString(t,r){return(new Ds).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ds,t,r)}static $(){return["ExportOrganizationGroupMcpAllowlistRequest|1 organization_id 9|2 group_public_id 9"]}}class Ns extends _s{constructor(t){super(),this.fileJson="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ns).fromBinary(t,r)}static fromJson(t,r){return(new Ns).fromJson(t,r)}static fromJsonString(t,r){return(new Ns).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ns,t,r)}static $(){return["ExportOrganizationGroupMcpAllowlistResponse|1 file_json 9"]}}class Gs extends _s{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gs).fromBinary(t,r)}static fromJson(t,r){return(new Gs).fromJson(t,r)}static fromJsonString(t,r){return(new Gs).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Gs,t,r)}static $(){return["ExportTeamMcpAllowlistRequest|1 team_id 5"]}}class Ls extends _s{constructor(t){super(),this.fileJson="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ls).fromBinary(t,r)}static fromJson(t,r){return(new Ls).fromJson(t,r)}static fromJsonString(t,r){return(new Ls).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ls,t,r)}static $(){return["ExportTeamMcpAllowlistResponse|1 file_json 9"]}}class Fs extends _s{constructor(t){super(),this.path="",this.message="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fs).fromBinary(t,r)}static fromJson(t,r){return(new Fs).fromJson(t,r)}static fromJsonString(t,r){return(new Fs).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Fs,t,r)}static $(){return["McpAllowlistImportIssue|1 path 9|2 message 9"]}}class Ks extends _s{constructor(t){super(),this.key="",this.list=Js.UNSPECIFIED,this.status=ys.UNSPECIFIED,this.existingList=Js.UNSPECIFIED,this.surface=ws.UNSPECIFIED,this.firstRuleSurface=ws.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ks).fromBinary(t,r)}static fromJson(t,r){return(new Ks).fromJson(t,r)}static fromJsonString(t,r){return(new Ks).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ks,t,r)}static $(){return["McpAllowlistImportRow|1 key 9|2 list #0|3 status #1|4 incoming #2|5 existing #2?|6 existing_list #0|7 surface #3|8 first_rule_surface #3",Js,ys,n.ufl,ws]}}class zs extends _s{constructor(t){super(),this.rows=[],this.baseFingerprint="",this.targetInheritsTeamPolicy=!1,this.groupListsNarrowTeamPolicy=!1,this.addsGrokConnectorsRule=!1,this.cloudDropsGrokConnectorRules=!1,this.addedBuiltinRulePatterns=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zs).fromBinary(t,r)}static fromJson(t,r){return(new zs).fromJson(t,r)}static fromJsonString(t,r){return(new zs).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(zs,t,r)}static $(){return["McpAllowlistImportPlan|1 rows #0*|2 base_fingerprint 9|3 target_inherits_team_policy 8|4 group_lists_narrow_team_policy 8|5 adds_grok_connectors_rule 8|6 cloud_drops_grok_connector_rules 8|7 added_builtin_rule_patterns 9*",Ks]}}class js extends _s{constructor(t){super(),this.issues=[],this.applied=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new js).fromBinary(t,r)}static fromJson(t,r){return(new js).fromJson(t,r)}static fromJsonString(t,r){return(new js).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(js,t,r)}static $(){return["McpAllowlistImportResult|1 issues #0*|2 plan #1|3 applied 8",Fs,zs]}}class Hs extends _s{constructor(t){super(),this.organizationId="",this.groupPublicId="",this.fileJson="",this.dryRun=!1,this.baseFingerprint="",this.useFileRowKeys=[],this.acknowledgeReplacesTeamPolicy=!1,this.acknowledgeFirstRuleSurface=ws.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hs).fromBinary(t,r)}static fromJson(t,r){return(new Hs).fromJson(t,r)}static fromJsonString(t,r){return(new Hs).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Hs,t,r)}static $(){return["ImportOrganizationGroupMcpAllowlistRequest|1 organization_id 9|2 group_public_id 9|3 file_json 9|4 dry_run 8|5 base_fingerprint 9|6 use_file_row_keys 9*|7 acknowledge_replaces_team_policy 8|8 acknowledge_first_rule_surface #0",ws]}}class Ws extends _s{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ws).fromBinary(t,r)}static fromJson(t,r){return(new Ws).fromJson(t,r)}static fromJsonString(t,r){return(new Ws).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ws,t,r)}static $(){return["ImportOrganizationGroupMcpAllowlistResponse|1 result #0",js]}}class Qs extends _s{constructor(t){super(),this.teamId=0,this.fileJson="",this.dryRun=!1,this.baseFingerprint="",this.useFileRowKeys=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qs).fromBinary(t,r)}static fromJson(t,r){return(new Qs).fromJson(t,r)}static fromJsonString(t,r){return(new Qs).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Qs,t,r)}static $(){return["ImportTeamMcpAllowlistRequest|1 team_id 5|2 file_json 9|3 dry_run 8|4 base_fingerprint 9|5 use_file_row_keys 9*"]}}class Vs extends _s{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vs).fromBinary(t,r)}static fromJson(t,r){return(new Vs).fromJson(t,r)}static fromJsonString(t,r){return(new Vs).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Vs,t,r)}static $(){return["ImportTeamMcpAllowlistResponse|1 result #0",js]}}class Xs extends _s{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xs).fromBinary(t,r)}static fromJson(t,r){return(new Xs).fromJson(t,r)}static fromJsonString(t,r){return(new Xs).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Xs,t,r)}static $(){return["GetTeamCloudAgentMcpAllowlistRequest|1 team_id 5"]}}class Ys extends _s{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ys).fromBinary(t,r)}static fromJson(t,r){return(new Ys).fromJson(t,r)}static fromJsonString(t,r){return(new Ys).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ys,t,r)}static $(){return["GetTeamCloudAgentMcpAllowlistResponse|1 mcp_allowlist_cloud_mirrors_local 8?|2 cloud_allowed_mcp_configuration #0?|3 cloud_allowed_mcp_configuration_draft #0?",n.ZM7]}}class Zs extends _s{constructor(t){super(),this.teamId=0,this.startsWithDefaultRules=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zs).fromBinary(t,r)}static fromJson(t,r){return(new Zs).fromJson(t,r)}static fromJsonString(t,r){return(new Zs).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Zs,t,r)}static $(){return["UpdateTeamCloudAgentMcpAllowlistRequest|1 team_id 5|2 mcp_allowlist_cloud_mirrors_local 8?|3 cloud_allowed_mcp_configuration #0?|4 saved_mcp_allowlist #0?|5 starts_with_default_rules 8",n.ZM7]}}class ti extends _s{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ti).fromBinary(t,r)}static fromJson(t,r){return(new ti).fromJson(t,r)}static fromJsonString(t,r){return(new ti).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ti,t,r)}static $(){return["UpdateTeamCloudAgentMcpAllowlistResponse|1 mcp_allowlist_cloud_mirrors_local 8?|2 cloud_allowed_mcp_configuration #0?",n.ZM7]}}class ri extends _s{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ri).fromBinary(t,r)}static fromJson(t,r){return(new ri).fromJson(t,r)}static fromJsonString(t,r){return(new ri).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ri,t,r)}static $(){return["McpAllowlistRulePattern|1 server_url 9?|2 command 9?|3 off 8?"]}}class ei extends _s{constructor(t){super(),this.teamId=0,this.rules=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ei).fromBinary(t,r)}static fromJson(t,r){return(new ei).fromJson(t,r)}static fromJsonString(t,r){return(new ei).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ei,t,r)}static $(){return["ListMcpAllowlistRuleMatchesRequest|1 team_id 5|2 rules #0*|3 include_member_servers 8?",ri]}}class ni extends _s{constructor(t){super(),this.kind=si.UNSPECIFIED,this.serverId=s.protoInt64.zero,this.serverName="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ni).fromBinary(t,r)}static fromJson(t,r){return(new ni).fromJson(t,r)}static fromJsonString(t,r){return(new ni).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ni,t,r)}static $(){return["McpAllowlistRuleMatch|1 kind #0|2 server_id 3|3 server_name 9|4 plugin_id 3?|5 plugin_name 9?",si]}}var si=(0,i.QT)(s.proto3,gs,"McpAllowlistRuleMatch.Kind",[[0,"UNSPECIFIED"],[1,"PLUGIN"],[2,"TEAM_MCP"]],1);class ii extends _s{constructor(t){super(),this.host="",this.memberCount=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ii).fromBinary(t,r)}static fromJson(t,r){return(new ii).fromJson(t,r)}static fromJsonString(t,r){return(new ii).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ii,t,r)}static $(){return["McpAllowlistMemberServerMatch|1 host 9|2 member_count 5"]}}class oi extends _s{constructor(t){super(),this.matches=[],this.memberMatches=[],this.memberServersMatched=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oi).fromBinary(t,r)}static fromJson(t,r){return(new oi).fromJson(t,r)}static fromJsonString(t,r){return(new oi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(oi,t,r)}static $(){return["McpAllowlistRuleMatches|1 matches #0*|2 match_count 5?|3 member_matches #1*|4 member_servers_matched 8",ni,ii]}}class ai extends _s{constructor(t){super(),this.rules=[],this.memberServersIncluded=!1,this.memberServersPartial=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ai).fromBinary(t,r)}static fromJson(t,r){return(new ai).fromJson(t,r)}static fromJsonString(t,r){return(new ai).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ai,t,r)}static $(){return["ListMcpAllowlistRuleMatchesResponse|1 rules #0*|2 member_servers_included 8|3 member_servers_partial 8",oi]}}class ui extends _s{constructor(t){super(),this.teamId=0,this.groupPublicId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ui).fromBinary(t,r)}static fromJson(t,r){return(new ui).fromJson(t,r)}static fromJsonString(t,r){return(new ui).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ui,t,r)}static $(){return["GetTeamGroupMcpSettingsRequest|1 team_id 5|2 group_public_id 9"]}}class ci extends _s{constructor(t){super(),this.baseList=li.UNSPECIFIED,this.groupEffect=mi.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ci).fromBinary(t,r)}static fromJson(t,r){return(new ci).fromJson(t,r)}static fromJsonString(t,r){return(new ci).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ci,t,r)}static $(){return["MemberEffectiveMcpPolicySurface|1 allowed_mcp_configuration #0|2 base_list #1|3 group_effect #2",n.ZM7,li,mi]}}var li=(0,i.QT)(s.proto3,gs,"MemberEffectiveMcpPolicySurface.BaseList",[[0,"UNSPECIFIED"],[1,"MCP_ALLOWLIST"],[2,"CLOUD_AGENT_ALLOWLIST"]],1),mi=(0,i.QT)(s.proto3,gs,"MemberEffectiveMcpPolicySurface.GroupEffect",[[0,"UNSPECIFIED"],[1,"NONE"],[2,"NARROWS"],[3,"REPLACES"]],1);class fi extends _s{constructor(t){super(),this.kind=di.UNSPECIFIED,this.teamGroupId=s.protoInt64.zero,this.directoryGroupId=0,this.owningTeamId=0,this.appliesToLocal=!1,this.appliesToCloud=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fi).fromBinary(t,r)}static fromJson(t,r){return(new fi).fromJson(t,r)}static fromJsonString(t,r){return(new fi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(fi,t,r)}static $(){return["MemberMcpPolicyGroup|1 kind #0|2 team_group_id 3|3 directory_group_id 5|4 owning_team_id 5|5 applies_to_local 8|6 applies_to_cloud 8",di]}}var di=(0,i.QT)(s.proto3,gs,"MemberMcpPolicyGroup.Kind",[[0,"UNSPECIFIED"],[1,"TEAM_GROUP"],[2,"DIRECTORY_GROUP"]],1);class pi extends _s{constructor(t){super(),this.teamId=0,this.userId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pi).fromBinary(t,r)}static fromJson(t,r){return(new pi).fromJson(t,r)}static fromJsonString(t,r){return(new pi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(pi,t,r)}static $(){return["GetTeamMemberEffectiveMcpPolicyRequest|1 team_id 5|2 user_id 5"]}}class hi extends _s{constructor(t){super(),this.groups=[],this.withheld=gi.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hi).fromBinary(t,r)}static fromJson(t,r){return(new hi).fromJson(t,r)}static fromJsonString(t,r){return(new hi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(hi,t,r)}static $(){return["GetTeamMemberEffectiveMcpPolicyResponse|1 local #0|2 cloud #0|3 groups #1*|4 withheld #2",ci,fi,gi]}}var gi=(0,i.QT)(s.proto3,gs,"GetTeamMemberEffectiveMcpPolicyResponse.Withheld",[[0,"UNSPECIFIED"],[1,"ORGANIZATION_GROUP_RULES"],[2,"DIRECTORY_GROUP_RULES"]],1);class _i extends _s{constructor(t){super(),this.mcpRuleSurfacesAvailable=!1,this.firstRuleAddsGrokConnectorsRule=!1,this.firstCloudRuleAddsGrokConnectorsRule=!1,this.cloudDropsGrokConnectorRules=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _i).fromBinary(t,r)}static fromJson(t,r){return(new _i).fromJson(t,r)}static fromJsonString(t,r){return(new _i).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(_i,t,r)}static $(){return["GetTeamGroupMcpSettingsResponse|1 allowed_mcp_configuration #0|2 cloud_mcp_rules #1|3 mcp_rule_surfaces_available 8|4 first_rule_adds_grok_connectors_rule 8|5 first_cloud_rule_adds_grok_connectors_rule 8|6 cloud_drops_grok_connector_rules 8",n.ZM7,As]}}class Ji extends _s{constructor(t){super(),this.teamId=0,this.groupId=s.protoInt64.zero,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ji).fromBinary(t,r)}static fromJson(t,r){return(new Ji).fromJson(t,r)}static fromJsonString(t,r){return(new Ji).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ji,t,r)}static $(){return["UpdateTeamGroupMcpSettingsRequest|1 team_id 5|2 group_id 3|3 allowed_mcp_configuration #0|4 cloud_mcp_rules #1?",n.ZM7,As]}}class wi extends _s{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wi).fromBinary(t,r)}static fromJson(t,r){return(new wi).fromJson(t,r)}static fromJsonString(t,r){return(new wi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(wi,t,r)}static $(){return["UpdateTeamGroupMcpSettingsResponse"]}}class yi extends _s{constructor(t){super(),this.teamId=0,this.builtinServer="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yi).fromBinary(t,r)}static fromJson(t,r){return(new yi).fromJson(t,r)}static fromJsonString(t,r){return(new yi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(yi,t,r)}static $(){return["ListBuiltinMcpServerToolsRequest|1 team_id 5|2 builtin_server 9"]}}class Si extends _s{constructor(t){super(),this.tools=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Si).fromBinary(t,r)}static fromJson(t,r){return(new Si).fromJson(t,r)}static fromJsonString(t,r){return(new Si).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Si,t,r)}static $(){return["ListBuiltinMcpServerToolsResponse|1 tools #0*",ns.gd]}}class qi extends _s{constructor(t){super(),this.teamId=0,this.groupPublicId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qi).fromBinary(t,r)}static fromJson(t,r){return(new qi).fromJson(t,r)}static fromJsonString(t,r){return(new qi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(qi,t,r)}static $(){return["ExportTeamGroupMcpAllowlistRequest|1 team_id 5|2 group_public_id 9"]}}class Bi extends _s{constructor(t){super(),this.fileJson="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bi).fromBinary(t,r)}static fromJson(t,r){return(new Bi).fromJson(t,r)}static fromJsonString(t,r){return(new Bi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Bi,t,r)}static $(){return["ExportTeamGroupMcpAllowlistResponse|1 file_json 9"]}}class Ii extends _s{constructor(t){super(),this.teamId=0,this.groupPublicId="",this.fileJson="",this.dryRun=!1,this.baseFingerprint="",this.useFileRowKeys=[],this.acknowledgeReplacesTeamPolicy=!1,this.acknowledgeFirstRuleSurface=ws.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ii).fromBinary(t,r)}static fromJson(t,r){return(new Ii).fromJson(t,r)}static fromJsonString(t,r){return(new Ii).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ii,t,r)}static $(){return["ImportTeamGroupMcpAllowlistRequest|1 team_id 5|2 group_public_id 9|3 file_json 9|4 dry_run 8|5 base_fingerprint 9|6 use_file_row_keys 9*|7 acknowledge_replaces_team_policy 8|8 acknowledge_first_rule_surface #0",ws]}}class Pi extends _s{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pi).fromBinary(t,r)}static fromJson(t,r){return(new Pi).fromJson(t,r)}static fromJsonString(t,r){return(new Pi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Pi,t,r)}static $(){return["ImportTeamGroupMcpAllowlistResponse|1 result #0",js]}}class bi extends _s{constructor(t){super(),this.teamScope=!1,this.teamId=0,this.redactSecrets=!1,this.expandPluginVariables=!1,this.localOverrideRowsOnly=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bi).fromBinary(t,r)}static fromJson(t,r){return(new bi).fromJson(t,r)}static fromJsonString(t,r){return(new bi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(bi,t,r)}static $(){return["GetMcpConfigRequest|1 team_scope 8|2 team_id 5|3 redact_secrets 8|4 expand_plugin_variables 8|5 local_override_rows_only 8"]}}class Ri extends _s{constructor(t){super(),this.serverId=s.protoInt64.zero,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ri).fromBinary(t,r)}static fromJson(t,r){return(new Ri).fromJson(t,r)}static fromJsonString(t,r){return(new Ri).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ri,t,r)}static $(){return["McpServerMetadata|1 plugin_id 3?|2 server_id 3|3 team_list_client_skip_reason 9?"]}}class vi extends _s{constructor(t){super(),this.configJson="",this.serverMetadataByName={},s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vi).fromBinary(t,r)}static fromJson(t,r){return(new vi).fromJson(t,r)}static fromJsonString(t,r){return(new vi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(vi,t,r)}static $(){return["GetMcpConfigResponse|1 config_json 9|2 server_metadata_by_name 9,#0",Ri]}}class xi extends _s{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xi).fromBinary(t,r)}static fromJson(t,r){return(new xi).fromJson(t,r)}static fromJsonString(t,r){return(new xi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(xi,t,r)}static $(){return["GetEffectiveMcpConfigForUserRequest"]}}class ki extends _s{constructor(t){super(),this.configJson="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ki).fromBinary(t,r)}static fromJson(t,r){return(new ki).fromJson(t,r)}static fromJsonString(t,r){return(new ki).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ki,t,r)}static $(){return["GetEffectiveMcpConfigForUserResponse|1 config_json 9"]}}class Ei extends _s{constructor(t){super(),this.teamTailnetRowsPerTeam=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ei).fromBinary(t,r)}static fromJson(t,r){return(new Ei).fromJson(t,r)}static fromJsonString(t,r){return(new Ei).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ei,t,r)}static $(){return["GetAvailableMcpServersRequest|1 grok_bot_plugin_scope #0?|2 grok_bot_agent_id 9?|3 team_tailnet_rows_per_team 8|4 service_account_id 9?|5 grok_bot_session_id 9?",n.q0X]}}class Ci extends _s{constructor(t){super(),this.servers=[],this.teamTailnetRowsPerTeam=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ci).fromBinary(t,r)}static fromJson(t,r){return(new Ci).fromJson(t,r)}static fromJsonString(t,r){return(new Ci).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ci,t,r)}static $(){return["GetAvailableMcpServersResponse|1 servers #0*|2 team_tailnet_rows_per_team 8",Ti]}}class Ti extends _s{constructor(t){super(),this.id=0,this.name="",this.isTeamServer=!1,this.enabled=!1,this.type="",this.args=[],this.isUnseen=!1,this.isRequired=!1,this.managedByTeamPluginPolicy=!1,this.disabledByTeamAdminPolicy=!1,this.accounts=[],this.hasStaticCredentialHeaders=!1,this.servedBy=n.JLr.UNSPECIFIED,this.needsGrant=!1,this.credentialIsCursorAccount=!1,this.singleAccount=!1,this.needsPluginSetup=!1,this.dataCenters=[],this.serverIdentifierAliases=[],this.grokSsoSignIn=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ti).fromBinary(t,r)}static fromJson(t,r){return(new Ti).fromJson(t,r)}static fromJsonString(t,r){return(new Ti).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ti,t,r)}static $(){return["GetAvailableMcpServersResponse.McpServerInfo|1 id 5|2 name 9|3 is_team_server 8|4 enabled 8|5 type 9|6 command 9?|7 args 9*|8 url 9?|9 plugin_id 3?|10 is_unseen 8|11 user_has_access_token 8?|12 is_required 8|13 managed_by_team_plugin_policy 8|14 disabled_by_team_admin_policy 8|15 server_identifier 9?|16 owning_team_id 5?|17 accounts #0*|18 has_static_credential_headers 8|19 served_by #1|20 cursor_scm_provider 9?|21 logo_url 9?|22 needs_grant 8|23 credential_is_cursor_account 8|24 merge_connector_id 9?|25 grok_connector_id 9?|26 single_account 8|27 needs_plugin_setup 8|28 data_centers #2*|29 server_identifier_aliases 9*|30 plugin_display_name 9?|31 plugin_team 8?|32 disabled_by_cloud_agent_mcp_allowlist 8?|33 access #3?|34 blocked_reason #4?|35 grok_sso_sign_in 8|36 blocked_reason_text #5?|37 connector_status #6",Ai,n.JLr,Ui,Oi,ss.Zl,$i,us]}}class Ui extends _s{constructor(t){super(),this.id="",this.label="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ui).fromBinary(t,r)}static fromJson(t,r){return(new Ui).fromJson(t,r)}static fromJsonString(t,r){return(new Ui).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ui,t,r)}static $(){return["GetAvailableMcpServersResponse.McpDataCenter|1 id 9|2 label 9"]}}class Ai extends _s{constructor(t){super(),this.accountKey="",this.serverIdentifier="",this.userHasAccessToken=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ai).fromBinary(t,r)}static fromJson(t,r){return(new Ai).fromJson(t,r)}static fromJsonString(t,r){return(new Ai).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ai,t,r)}static $(){return["GetAvailableMcpServersResponse.McpAccountInfo|1 account_key 9|2 server_identifier 9|3 user_has_access_token 8|4 account_email 9?|5 display_name 9?|6 display_detail 9?"]}}class $i extends _s{constructor(t){super(),this.shortLine="",this.detailLine="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $i).fromBinary(t,r)}static fromJson(t,r){return(new $i).fromJson(t,r)}static fromJsonString(t,r){return(new $i).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals($i,t,r)}static $(){return["McpBlockedReasonText|1 short_line 9|2 detail_line 9"]}}class Mi extends _s{constructor(t){super(),this.allowed=!1,this.blockedReason=ss.Zl.UNSPECIFIED,this.toolAccess=Ss.UNSPECIFIED,this.allowedToolNames=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mi).fromBinary(t,r)}static fromJson(t,r){return(new Mi).fromJson(t,r)}static fromJsonString(t,r){return(new Mi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Mi,t,r)}static $(){return["McpSurfaceAccess|1 allowed 8|2 blocked_reason #0|3 tool_access #1|4 allowed_tool_names 9*",ss.Zl,Ss]}}class Oi extends _s{constructor(t){super(),this.appliesTo=n.Vsr.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Oi).fromBinary(t,r)}static fromJson(t,r){return(new Oi).fromJson(t,r)}static fromJsonString(t,r){return(new Oi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Oi,t,r)}static $(){return["McpServerAccess|1 applies_to #0|2 local #1|3 cloud #1",n.Vsr,Mi]}}class Di extends _s{constructor(t){super(),this.teamScope=!1,this.teamId=0,this.serverIds=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Di).fromBinary(t,r)}static fromJson(t,r){return(new Di).fromJson(t,r)}static fromJsonString(t,r){return(new Di).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Di,t,r)}static $(){return["GetMcpServerUsageSummaryRequest|1 team_scope 8|2 team_id 5|3 server_ids 3*"]}}class Ni extends _s{constructor(t){super(),this.serverId=s.protoInt64.zero,this.enabledUserCount=0,this.automationCount=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ni).fromBinary(t,r)}static fromJson(t,r){return(new Ni).fromJson(t,r)}static fromJsonString(t,r){return(new Ni).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ni,t,r)}static $(){return["McpServerUsageSummary|1 server_id 3|2 enabled_user_count 5|3 automation_count 5"]}}class Gi extends _s{constructor(t){super(),this.summaries=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gi).fromBinary(t,r)}static fromJson(t,r){return(new Gi).fromJson(t,r)}static fromJsonString(t,r){return(new Gi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Gi,t,r)}static $(){return["GetMcpServerUsageSummaryResponse|1 summaries #0*",Ni]}}class Li extends _s{constructor(t){super(),this.teamScope=!1,this.teamId=0,this.configJson="",this.serverRenames={},this.serverIdsByName={},s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Li).fromBinary(t,r)}static fromJson(t,r){return(new Li).fromJson(t,r)}static fromJsonString(t,r){return(new Li).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Li,t,r)}static $(){return["SetMcpConfigRequest|1 team_scope 8|2 team_id 5|3 config_json 9|4 server_renames 9,9|5 server_ids_by_name 9,3"]}}class Fi extends _s{constructor(t){super(),this.addedTeamServers=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fi).fromBinary(t,r)}static fromJson(t,r){return(new Fi).fromJson(t,r)}static fromJsonString(t,r){return(new Fi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Fi,t,r)}static $(){return["SetMcpConfigResponse|1 added_team_servers #0*",sa]}}class Ki extends _s{constructor(t){super(),this.serverName="",this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ki).fromBinary(t,r)}static fromJson(t,r){return(new Ki).fromJson(t,r)}static fromJsonString(t,r){return(new Ki).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ki,t,r)}static $(){return["MoveUserMcpServerToTeamRequest|1 server_name 9|2 team_id 5"]}}class zi extends _s{constructor(t){super(),this.addedTeamServers=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zi).fromBinary(t,r)}static fromJson(t,r){return(new zi).fromJson(t,r)}static fromJsonString(t,r){return(new zi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(zi,t,r)}static $(){return["MoveUserMcpServerToTeamResponse|1 added_team_servers #0*",sa]}}class ji extends _s{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ji).fromBinary(t,r)}static fromJson(t,r){return(new ji).fromJson(t,r)}static fromJsonString(t,r){return(new ji).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ji,t,r)}static $(){return["GetTeamMcpPlacementDefaultRequest|1 team_id 5"]}}class Hi extends _s{constructor(t){super(),this.placementDefault=qs.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hi).fromBinary(t,r)}static fromJson(t,r){return(new Hi).fromJson(t,r)}static fromJsonString(t,r){return(new Hi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Hi,t,r)}static $(){return["GetTeamMcpPlacementDefaultResponse|1 placement_default #0",qs]}}class Wi extends _s{constructor(t){super(),this.teamId=0,this.placementDefault=qs.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wi).fromBinary(t,r)}static fromJson(t,r){return(new Wi).fromJson(t,r)}static fromJsonString(t,r){return(new Wi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Wi,t,r)}static $(){return["UpdateTeamMcpPlacementDefaultRequest|1 team_id 5|2 placement_default #0",qs]}}class Qi extends _s{constructor(t){super(),this.placementDefault=qs.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qi).fromBinary(t,r)}static fromJson(t,r){return(new Qi).fromJson(t,r)}static fromJsonString(t,r){return(new Qi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Qi,t,r)}static $(){return["UpdateTeamMcpPlacementDefaultResponse|1 placement_default #0",qs]}}class Vi extends _s{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vi).fromBinary(t,r)}static fromJson(t,r){return(new Vi).fromJson(t,r)}static fromJsonString(t,r){return(new Vi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Vi,t,r)}static $(){return["MigrateTeamMcpServersToDefaultMarketplaceRequest|1 team_id 5"]}}class Xi extends _s{constructor(t){super(),this.migratedCount=0,this.skippedCount=0,this.defaultMarketplaceId=s.protoInt64.zero,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xi).fromBinary(t,r)}static fromJson(t,r){return(new Xi).fromJson(t,r)}static fromJsonString(t,r){return(new Xi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Xi,t,r)}static $(){return["MigrateTeamMcpServersToDefaultMarketplaceResponse|1 migrated_count 5|2 skipped_count 5|3 default_marketplace_id 3"]}}class Yi extends _s{constructor(t){super(),this.enabledServerIds=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yi).fromBinary(t,r)}static fromJson(t,r){return(new Yi).fromJson(t,r)}static fromJsonString(t,r){return(new Yi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Yi,t,r)}static $(){return["UpdateUserDefaultMcpSettingsRequest|1 enabled_server_ids 5*"]}}class Zi extends _s{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zi).fromBinary(t,r)}static fromJson(t,r){return(new Zi).fromJson(t,r)}static fromJsonString(t,r){return(new Zi).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Zi,t,r)}static $(){return["UpdateUserDefaultMcpSettingsResponse"]}}class to extends _s{constructor(t){super(),this.serverKey="",this.reads=ro.UNSPECIFIED,this.writes=ro.UNSPECIFIED,this.disabledTools=[],this.onlyIfAbsent=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new to).fromBinary(t,r)}static fromJson(t,r){return(new to).fromJson(t,r)}static fromJsonString(t,r){return(new to).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(to,t,r)}static $(){return["UserMcpToolChoice|1 server_key 9|2 reads #0|3 writes #0|4 disabled_tools 9*|5 only_if_absent 8",ro]}}var ro=(0,i.QT)(s.proto3,gs,"UserMcpToolChoice.GroupSelector",[[0,"UNSPECIFIED"],[1,"ALL"],[2,"OFF"],[3,"CUSTOM"]],1);class eo extends _s{constructor(t){super(),this.choices=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new eo).fromBinary(t,r)}static fromJson(t,r){return(new eo).fromJson(t,r)}static fromJsonString(t,r){return(new eo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(eo,t,r)}static $(){return["SetUserMcpToolChoicesRequest|1 choices #0*",to]}}class no extends _s{constructor(t){super(),this.results=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new no).fromBinary(t,r)}static fromJson(t,r){return(new no).fromJson(t,r)}static fromJsonString(t,r){return(new no).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(no,t,r)}static $(){return["SetUserMcpToolChoicesResponse|1 results #0*",so]}}var so=(0,i.QT)(s.proto3,gs,"SetUserMcpToolChoicesResponse.Result",[[0,"UNSPECIFIED"],[1,"STORED"],[2,"REMOVED"],[3,"KEPT"],[4,"REFUSED"]],1);class io extends _s{constructor(t){super(),this.serverIds=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new io).fromBinary(t,r)}static fromJson(t,r){return(new io).fromJson(t,r)}static fromJsonString(t,r){return(new io).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(io,t,r)}static $(){return["MarkMcpServersSeenRequest|1 server_ids 5*"]}}class oo extends _s{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oo).fromBinary(t,r)}static fromJson(t,r){return(new oo).fromJson(t,r)}static fromJsonString(t,r){return(new oo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(oo,t,r)}static $(){return["MarkMcpServersSeenResponse"]}}class ao extends _s{constructor(t){super(),this.serverUrl="",this.accountKey="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ao).fromBinary(t,r)}static fromJson(t,r){return(new ao).fromJson(t,r)}static fromJsonString(t,r){return(new ao).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ao,t,r)}static $(){return["StoreMcpOAuthTokenRequest|1 server_url 9|2 refresh_token 9?|3 client_id 9?|4 client_secret 9?|5 redirect_uri 9?|6 access_token 9?|7 service_account_id 9?|8 client_token_created_at_ms 3?|9 source 9?|10 account_key 9"]}}class uo extends _s{constructor(t){super(),this.applied=!1,this.skippedBecauseBackendNewer=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uo).fromBinary(t,r)}static fromJson(t,r){return(new uo).fromJson(t,r)}static fromJsonString(t,r){return(new uo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(uo,t,r)}static $(){return["StoreMcpOAuthTokenResponse|1 updated_at_ms 3?|2 applied 8|3 skipped_because_backend_newer 8"]}}class co extends _s{constructor(t){super(),this.serverUrls=[],this.accountKey="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new co).fromBinary(t,r)}static fromJson(t,r){return(new co).fromJson(t,r)}static fromJsonString(t,r){return(new co).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(co,t,r)}static $(){return["GetMcpOAuthTokensRequest|1 server_urls 9*|2 service_account_id 9?|3 account_key 9"]}}class lo extends _s{constructor(t){super(),this.entries=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lo).fromBinary(t,r)}static fromJson(t,r){return(new lo).fromJson(t,r)}static fromJsonString(t,r){return(new lo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(lo,t,r)}static $(){return["GetMcpOAuthTokensResponse|1 entries #0*",mo]}}class mo extends _s{constructor(t){super(),this.serverUrl="",this.updatedAtMs=s.protoInt64.zero,this.accountKey="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mo).fromBinary(t,r)}static fromJson(t,r){return(new mo).fromJson(t,r)}static fromJsonString(t,r){return(new mo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(mo,t,r)}static $(){return["GetMcpOAuthTokensResponse.Entry|1 server_url 9|2 token_data #0|3 updated_at_ms 3|4 account_key 9",as]}}class fo extends _s{constructor(t){super(),this.teamId=0,this.serverId=s.protoInt64.zero,this.oauthRedirectUri="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fo).fromBinary(t,r)}static fromJson(t,r){return(new fo).fromJson(t,r)}static fromJsonString(t,r){return(new fo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(fo,t,r)}static $(){return["PreviewTeamMcpToolsRequest|1 team_id 5|2 server_id 3|3 oauth_redirect_uri 9"]}}class po extends _s{constructor(t){super(),this.status="",this.tools=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new po).fromBinary(t,r)}static fromJson(t,r){return(new po).fromJson(t,r)}static fromJsonString(t,r){return(new po).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(po,t,r)}static $(){return["PreviewTeamMcpToolsResponse|1 status 9|2 auth_url 9?|3 error 9?|4 tools #0*",ns.gd]}}class ho extends _s{constructor(t){super(),this.serverUrl="",this.executorKind=Bs.UNSPECIFIED,this.executorId="",this.accountKey="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ho).fromBinary(t,r)}static fromJson(t,r){return(new ho).fromJson(t,r)}static fromJsonString(t,r){return(new ho).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ho,t,r)}static $(){return["McpOAuthRefreshLockBeginRequest|1 server_url 9|2 executor_kind #0|3 executor_id 9|4 observed_updated_at_ms 3?|5 service_account_id 9?|6 account_key 9",Bs]}}class go extends _s{constructor(t){super(),this.outcome=Is.UNSPECIFIED,this.shouldEnforce=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new go).fromBinary(t,r)}static fromJson(t,r){return(new go).fromJson(t,r)}static fromJsonString(t,r){return(new go).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(go,t,r)}static $(){return["McpOAuthRefreshLockBeginResponse|1 outcome #0|2 lease_handle 9?|3 should_enforce 8",Is]}}class _o extends _s{constructor(t){super(),this.leaseHandle="",this.reason=Ps.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _o).fromBinary(t,r)}static fromJson(t,r){return(new _o).fromJson(t,r)}static fromJsonString(t,r){return(new _o).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(_o,t,r)}static $(){return["McpOAuthRefreshLockReleaseRequest|1 lease_handle 9|2 reason #0",Ps]}}class Jo extends _s{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jo).fromBinary(t,r)}static fromJson(t,r){return(new Jo).fromJson(t,r)}static fromJsonString(t,r){return(new Jo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Jo,t,r)}static $(){return["McpOAuthRefreshLockReleaseResponse"]}}class wo extends _s{constructor(t){super(),this.serverUrl="",this.accountKey="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wo).fromBinary(t,r)}static fromJson(t,r){return(new wo).fromJson(t,r)}static fromJsonString(t,r){return(new wo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(wo,t,r)}static $(){return["DeleteMcpOAuthTokenRequest|1 server_url 9|2 service_account_id 9?|3 source 9?|4 account_key 9|5 server_identifier 9?"]}}class yo extends _s{constructor(t){super(),this.outcome=So.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yo).fromBinary(t,r)}static fromJson(t,r){return(new yo).fromJson(t,r)}static fromJsonString(t,r){return(new yo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(yo,t,r)}static $(){return["DeleteMcpOAuthTokenResponse|1 outcome #0",So]}}var So=(0,i.QT)(s.proto3,gs,"DeleteMcpOAuthTokenResponse.Outcome",[[0,"UNSPECIFIED"],[1,"DELETED"],[2,"NOT_FOUND"]],1);class qo extends _s{constructor(t){super(),this.serverUrls=[],this.targets=[],this.serverIdentifiers=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qo).fromBinary(t,r)}static fromJson(t,r){return(new qo).fromJson(t,r)}static fromJsonString(t,r){return(new qo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(qo,t,r)}static $(){return["ValidateMcpOAuthTokensRequest|1 server_urls 9*|2 service_account_id 9?|3 targets #0*|4 server_identifiers 9*",Bo]}}class Bo extends _s{constructor(t){super(),this.serverUrl="",this.accountKey="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bo).fromBinary(t,r)}static fromJson(t,r){return(new Bo).fromJson(t,r)}static fromJsonString(t,r){return(new Bo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Bo,t,r)}static $(){return["ValidateMcpOAuthTokensRequest.Target|1 server_url 9|2 account_key 9"]}}class Io extends _s{constructor(t){super(),this.results=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Io).fromBinary(t,r)}static fromJson(t,r){return(new Io).fromJson(t,r)}static fromJsonString(t,r){return(new Io).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Io,t,r)}static $(){return["ValidateMcpOAuthTokensResponse|1 results #0*",Po]}}class Po extends _s{constructor(t){super(),this.serverUrl="",this.hasValidToken=!1,this.accountKey="",this.servedBy=n.JLr.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Po).fromBinary(t,r)}static fromJson(t,r){return(new Po).fromJson(t,r)}static fromJsonString(t,r){return(new Po).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Po,t,r)}static $(){return["ValidateMcpOAuthTokensResponse.Result|1 server_url 9|2 has_valid_token 8|3 account_key 9|4 server_identifier 9?|5 served_by #0|6 auth_state #1?",n.JLr,Ts]}}class bo extends _s{constructor(t){super(),this.suiteId=bs.UNSPECIFIED,this.memberPluginIds=[],this.driveCoversEditors=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bo).fromBinary(t,r)}static fromJson(t,r){return(new bo).fromJson(t,r)}static fromJsonString(t,r){return(new bo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(bo,t,r)}static $(){return["ConnectorSuiteOffer|1 suite_id #0|2 member_plugin_ids 3*|3 drive_covers_editors 8",bs]}}class Ro extends _s{constructor(t){super(),this.suiteId=bs.UNSPECIFIED,this.memberPluginIds=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ro).fromBinary(t,r)}static fromJson(t,r){return(new Ro).fromJson(t,r)}static fromJsonString(t,r){return(new Ro).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ro,t,r)}static $(){return["ConnectorSuiteSelection|1 suite_id #0|2 member_plugin_ids 3*",bs]}}class vo extends _s{constructor(t){super(),this.pluginId=s.protoInt64.zero,this.serverUrl="",this.outcome=Rs.UNSPECIFIED,this.coverage=vs.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vo).fromBinary(t,r)}static fromJson(t,r){return(new vo).fromJson(t,r)}static fromJsonString(t,r){return(new vo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(vo,t,r)}static $(){return["ConnectorSuiteMemberResult|1 plugin_id 3|2 server_url 9|3 outcome #0|4 coverage #1",Rs,vs]}}class xo extends _s{constructor(t){super(),this.serverIds=[],this.oauthRedirectUri="",this.forceReauth=!1,this.accountKey="",this.serverIdentifiers=[],this.statusOnly=!1,this.showMcpAccessDisabledStatus=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xo).fromBinary(t,r)}static fromJson(t,r){return(new xo).fromJson(t,r)}static fromJsonString(t,r){return(new xo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(xo,t,r)}static $(){return["CheckHttpMcpStatusRequest|1 server_ids 5*|2 oauth_redirect_uri 9|3 team_id 5?|4 service_account_id 9?|5 force_reauth 8|6 service_account_type 9?|7 post_auth_return_url 9?|8 account_key 9|9 server_identifiers 9*|10 grok_bot_plugin_scope #0?|11 grok_bot_agent_id 9?|12 status_only 8|13 show_mcp_access_disabled_status 8|14 user_initiated 8?|15 data_center 9?|16 share_with_bot_agent_id 9?|17 share_with_bot_plugin_id 3?|18 share_acknowledged_warning_version 5?|19 texted_sign_in 8?|20 grok_bot_session_id 9?|21 connector_suite_capable 8?|22 connector_suite #1?",n.q0X,Ro]}}class ko extends _s{constructor(t){super(),this.statuses=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ko).fromBinary(t,r)}static fromJson(t,r){return(new ko).fromJson(t,r)}static fromJsonString(t,r){return(new ko).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ko,t,r)}static $(){return["CheckHttpMcpStatusResponse|1 statuses #0*",Eo]}}class Eo extends _s{constructor(t){super(),this.id=0,this.isAvailable=!1,this.requiresAuth=!1,this.hasValidToken=!1,this.servedBy=n.JLr.UNSPECIFIED,this.signedIn=!1,this.cloudVerdict=ks.UNSPECIFIED,this.connectorSuiteExposure=xs.NONE,this.grokSsoSignIn=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Eo).fromBinary(t,r)}static fromJson(t,r){return(new Eo).fromJson(t,r)}static fromJsonString(t,r){return(new Eo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Eo,t,r)}static $(){return["CheckHttpMcpStatusResponse.ServerStatus|1 id 5|2 is_available 8|3 requires_auth 8|4 auth_url 9?|5 error 9?|6 has_valid_token 8|7 server_identifier 9?|8 served_by #0|9 sign_out #1?|10 sign_in_refusal #2?|11 signed_in 8|12 cloud_verdict #3|13 connector_suite_offer #4?|14 connector_suite_exposure #5|15 grok_sso_sign_in 8|16 connector_status #6",n.JLr,n.eJC,Co,ks,bo,xs,us]}}class Co extends _s{constructor(t){super(),this.kind=Es.UNSPECIFIED,this.missingSetupFields=[],this.sharedBackoff=!1,this.transportFailureReason=Cs.UNSPECIFIED,this.runsLocally=!1,this.retryAfterSeconds=0,this.quietReconnect=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Co).fromBinary(t,r)}static fromJson(t,r){return(new Co).fromJson(t,r)}static fromJsonString(t,r){return(new Co).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Co,t,r)}static $(){return["McpSignInRefusal|1 kind #0|2 missing_setup_fields 9*|3 shared_backoff 8|4 transport_failure_reason #1|5 runs_locally 8|6 retry_after_seconds 5|7 sign_in_start_held_seconds 5?|8 quiet_reconnect 8",Es,Cs]}}class To extends _s{constructor(t){super(),this.serverUrl="",this.codeVerifier="",this.accountKey="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new To).fromBinary(t,r)}static fromJson(t,r){return(new To).fromJson(t,r)}static fromJsonString(t,r){return(new To).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(To,t,r)}static $(){return["StoreMcpOAuthPendingStateRequest|1 server_url 9|2 code_verifier 9|3 client_id 9?|4 client_secret 9?|5 redirect_uri 9?|6 service_account_id 9?|7 account_key 9"]}}class Uo extends _s{constructor(t){super(),this.stateId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Uo).fromBinary(t,r)}static fromJson(t,r){return(new Uo).fromJson(t,r)}static fromJsonString(t,r){return(new Uo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Uo,t,r)}static $(){return["StoreMcpOAuthPendingStateResponse|1 state_id 9"]}}class Ao extends _s{constructor(t){super(),this.stateId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ao).fromBinary(t,r)}static fromJson(t,r){return(new Ao).fromJson(t,r)}static fromJsonString(t,r){return(new Ao).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ao,t,r)}static $(){return["GetMcpOAuthPendingStateRequest|1 state_id 9"]}}class $o extends _s{constructor(t){super(),this.serverUrl="",this.codeVerifier="",this.accountKey="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $o).fromBinary(t,r)}static fromJson(t,r){return(new $o).fromJson(t,r)}static fromJsonString(t,r){return(new $o).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals($o,t,r)}static $(){return["GetMcpOAuthPendingStateResponse|1 server_url 9|2 code_verifier 9|3 client_id 9?|4 client_secret 9?|5 redirect_uri 9?|6 service_account_id 9?|7 post_auth_return_url 9?|8 account_key 9"]}}class Mo extends _s{constructor(t){super(),this.stateId="",this.authorizationCode="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mo).fromBinary(t,r)}static fromJson(t,r){return(new Mo).fromJson(t,r)}static fromJsonString(t,r){return(new Mo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Mo,t,r)}static $(){return["CompleteMcpOAuthRequest|1 state_id 9|2 authorization_code 9|3 oauth_error 9?"]}}class Oo extends _s{constructor(t){super(),this.postAuthReturnUrl="",this.accountKey="",this.connectorSuiteResult=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Oo).fromBinary(t,r)}static fromJson(t,r){return(new Oo).fromJson(t,r)}static fromJsonString(t,r){return(new Oo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Oo,t,r)}static $(){return["CompleteMcpOAuthResponse|1 post_auth_return_url 9|2 account_key 9|3 tailnet_pending_reason 9?|4 tailnet_pending_detail 9?|5 connector_suite_result #0*|6 continue_authorization_url 9?",vo]}}class Do extends _s{constructor(t){super(),this.stateId="",this.authorizationCode="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Do).fromBinary(t,r)}static fromJson(t,r){return(new Do).fromJson(t,r)}static fromJsonString(t,r){return(new Do).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Do,t,r)}static $(){return["HandOffMcpOAuthCodeRequest|1 state_id 9|2 authorization_code 9"]}}class No extends _s{constructor(t){super(),this.codeHandle="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new No).fromBinary(t,r)}static fromJson(t,r){return(new No).fromJson(t,r)}static fromJsonString(t,r){return(new No).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(No,t,r)}static $(){return["HandOffMcpOAuthCodeResponse|1 code_handle 9"]}}class Go extends _s{constructor(t){super(),this.serverId=0,this.accountKey="",this.newAccountKey="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Go).fromBinary(t,r)}static fromJson(t,r){return(new Go).fromJson(t,r)}static fromJsonString(t,r){return(new Go).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Go,t,r)}static $(){return["RenameMcpOAuthAccountRequest|1 server_id 5|2 account_key 9|3 new_account_key 9|4 grok_bot_plugin_scope #0?|5 grok_bot_agent_id 9?|6 grok_bot_session_id 9?",n.q0X]}}class Lo extends _s{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lo).fromBinary(t,r)}static fromJson(t,r){return(new Lo).fromJson(t,r)}static fromJsonString(t,r){return(new Lo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Lo,t,r)}static $(){return["RenameMcpOAuthAccountResponse"]}}class Fo extends _s{constructor(t){super(),this.serverId=0,this.accountKey="",this.serverUrl="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fo).fromBinary(t,r)}static fromJson(t,r){return(new Fo).fromJson(t,r)}static fromJsonString(t,r){return(new Fo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Fo,t,r)}static $(){return["DeleteMcpOAuthAccountRequest|1 server_id 5|2 account_key 9|3 server_url 9|4 grok_bot_plugin_scope #0?|5 grok_bot_agent_id 9?|6 grok_bot_session_id 9?",n.q0X]}}class Ko extends _s{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ko).fromBinary(t,r)}static fromJson(t,r){return(new Ko).fromJson(t,r)}static fromJsonString(t,r){return(new Ko).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ko,t,r)}static $(){return["DeleteMcpOAuthAccountResponse"]}}class zo extends _s{constructor(t){super(),this.pluginId=s.protoInt64.zero,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zo).fromBinary(t,r)}static fromJson(t,r){return(new zo).fromJson(t,r)}static fromJsonString(t,r){return(new zo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(zo,t,r)}static $(){return["GetPluginMcpConfigRequest|1 plugin_id 3"]}}class jo extends _s{constructor(t){super(),this.configJson="",this.commitSha="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jo).fromBinary(t,r)}static fromJson(t,r){return(new jo).fromJson(t,r)}static fromJsonString(t,r){return(new jo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(jo,t,r)}static $(){return["GetPluginMcpConfigResponse|1 config_json 9|2 commit_sha 9"]}}class Ho extends _s{constructor(t){super(),this.pluginIds=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ho).fromBinary(t,r)}static fromJson(t,r){return(new Ho).fromJson(t,r)}static fromJsonString(t,r){return(new Ho).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ho,t,r)}static $(){return["BatchGetPluginMcpConfigRequest|1 plugin_ids 3*"]}}class Wo extends _s{constructor(t){super(),this.configJson="",this.commitSha="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wo).fromBinary(t,r)}static fromJson(t,r){return(new Wo).fromJson(t,r)}static fromJsonString(t,r){return(new Wo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Wo,t,r)}static $(){return["PluginMcpConfigEntry|1 config_json 9|2 commit_sha 9"]}}class Qo extends _s{constructor(t){super(),this.configs={},s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qo).fromBinary(t,r)}static fromJson(t,r){return(new Qo).fromJson(t,r)}static fromJsonString(t,r){return(new Qo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Qo,t,r)}static $(){return["BatchGetPluginMcpConfigResponse|1 configs 3,#0",Wo]}}class Vo extends _s{constructor(t){super(),this.pluginId=s.protoInt64.zero,this.scope="",this.substitutions={},s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vo).fromBinary(t,r)}static fromJson(t,r){return(new Vo).fromJson(t,r)}static fromJsonString(t,r){return(new Vo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Vo,t,r)}static $(){return["AddMcpServersFromPluginRequest|1 plugin_id 3|2 scope 9|3 team_id 5?|4 commit_sha 9?|5 server_name 9?|6 substitutions 9,9|7 oauth_redirect_uri 9?"]}}class Xo extends _s{constructor(t){super(),this.addedServerIds=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xo).fromBinary(t,r)}static fromJson(t,r){return(new Xo).fromJson(t,r)}static fromJsonString(t,r){return(new Xo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Xo,t,r)}static $(){return["AddMcpServersFromPluginResponse|1 added_server_ids 3*"]}}class Yo extends _s{constructor(t){super(),this.url="",this.headers={},s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yo).fromBinary(t,r)}static fromJson(t,r){return(new Yo).fromJson(t,r)}static fromJsonString(t,r){return(new Yo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Yo,t,r)}static $(){return["ProbeMcpUrlRequest|1 url 9|2 headers 9,9|3 oauth_redirect_uri 9?|4 auth_client_id 9?|5 auth_client_secret 9?"]}}class Zo extends _s{constructor(t){super(),this.isAvailable=!1,this.requiresAuth=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zo).fromBinary(t,r)}static fromJson(t,r){return(new Zo).fromJson(t,r)}static fromJsonString(t,r){return(new Zo).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Zo,t,r)}static $(){return["ProbeMcpUrlResponse|1 is_available 8|2 requires_auth 8|3 auth_url 9?|4 error 9?"]}}class ta extends _s{constructor(t){super(),this.serverUrl="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ta).fromBinary(t,r)}static fromJson(t,r){return(new ta).fromJson(t,r)}static fromJsonString(t,r){return(new ta).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ta,t,r)}static $(){return["GetMcpBackendAccessTokenRequest|1 server_url 9"]}}class ra extends _s{constructor(t){super(),this.needsAuth=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ra).fromBinary(t,r)}static fromJson(t,r){return(new ra).fromJson(t,r)}static fromJsonString(t,r){return(new ra).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ra,t,r)}static $(){return["GetMcpBackendAccessTokenResponse|1 needs_auth 8|2 access_token 9?"]}}class ea extends _s{constructor(t){super(),this.pluginId=s.protoInt64.zero,this.mcpConfigJson="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ea).fromBinary(t,r)}static fromJson(t,r){return(new ea).fromJson(t,r)}static fromJsonString(t,r){return(new ea).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ea,t,r)}static $(){return["UpdatePluginMcpConfigRequest|1 plugin_id 3|2 mcp_config_json 9|3 team_id 5?"]}}class na extends _s{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new na).fromBinary(t,r)}static fromJson(t,r){return(new na).fromJson(t,r)}static fromJsonString(t,r){return(new na).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(na,t,r)}static $(){return["UpdatePluginMcpConfigResponse|1 plugin #0",n.k_1]}}class sa extends _s{constructor(t){super(),this.serverId=s.protoInt64.zero,this.name="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sa).fromBinary(t,r)}static fromJson(t,r){return(new sa).fromJson(t,r)}static fromJsonString(t,r){return(new sa).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(sa,t,r)}static $(){return["TeamMcpServerAddCheck|1 server_id 3|2 name 9|3 local #0|4 cloud #0",n.mne]}}class ia extends _s{constructor(t){super(),this.marketplaceId=s.protoInt64.zero,this.action={case:void 0},s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ia).fromBinary(t,r)}static fromJson(t,r){return(new ia).fromJson(t,r)}static fromJsonString(t,r){return(new ia).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ia,t,r)}static $(){return["PreviewTeamMarketplaceMcpImpactRequest|1 marketplace_id 3|2 team_id 5?|3 set_policies #0 action|4 remove_marketplace #1 action|5 set_policies_across_marketplaces #2 action",oa,aa,ua]}}class oa extends _s{constructor(t){super(),this.policies=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oa).fromBinary(t,r)}static fromJson(t,r){return(new oa).fromJson(t,r)}static fromJsonString(t,r){return(new oa).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(oa,t,r)}static $(){return["PreviewTeamMarketplaceMcpImpactRequest.SetPoliciesPreview|1 policies #0*",n.G_8]}}class aa extends _s{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new aa).fromBinary(t,r)}static fromJson(t,r){return(new aa).fromJson(t,r)}static fromJsonString(t,r){return(new aa).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(aa,t,r)}static $(){return["PreviewTeamMarketplaceMcpImpactRequest.RemoveMarketplacePreview"]}}class ua extends _s{constructor(t){super(),this.marketplaces=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ua).fromBinary(t,r)}static fromJson(t,r){return(new ua).fromJson(t,r)}static fromJsonString(t,r){return(new ua).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ua,t,r)}static $(){return["PreviewTeamMarketplaceMcpImpactRequest.SetPoliciesAcrossMarketplacesPreview|1 marketplaces #0*",ca]}}class ca extends _s{constructor(t){super(),this.marketplaceId=s.protoInt64.zero,this.policies=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ca).fromBinary(t,r)}static fromJson(t,r){return(new ca).fromJson(t,r)}static fromJsonString(t,r){return(new ca).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ca,t,r)}static $(){return["PreviewTeamMarketplaceMcpImpactRequest.SetPoliciesAcrossMarketplacesPreview.MarketplacePolicies|1 marketplace_id 3|2 policies #0*",n.G_8]}}class la extends _s{constructor(t){super(),this.impactedPlugins=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new la).fromBinary(t,r)}static fromJson(t,r){return(new la).fromJson(t,r)}static fromJsonString(t,r){return(new la).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(la,t,r)}static $(){return["PreviewTeamMarketplaceMcpImpactResponse|1 impacted_plugins #0*",ma]}}class ma extends _s{constructor(t){super(),this.pluginId=s.protoInt64.zero,this.pluginName="",this.mcpServerNames=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ma).fromBinary(t,r)}static fromJson(t,r){return(new ma).fromJson(t,r)}static fromJsonString(t,r){return(new ma).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ma,t,r)}static $(){return["PreviewTeamMarketplaceMcpImpactResponse.ImpactedPlugin|1 plugin_id 3|2 plugin_name 9|3 mcp_server_names 9*"]}}var fa=e("../proto/dist/generated/agent/v1/smart_mode_classifier_exec_pb.js");const da="aiserver.v1.";class pa extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",s.proto3)}static $p(){return da}}var ha=(0,i.QT)(s.proto3,da,"GrokBotAccessRole",[[0,"UNSPECIFIED"],[1,"USER"],[2,"MANAGER"]],1);class ga extends pa{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ga).fromBinary(t,r)}static fromJson(t,r){return(new ga).fromJson(t,r)}static fromJsonString(t,r){return(new ga).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ga,t,r)}static $(){return["GrokBotAccessTeamPrincipal"]}}class _a extends pa{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _a).fromBinary(t,r)}static fromJson(t,r){return(new _a).fromJson(t,r)}static fromJsonString(t,r){return(new _a).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(_a,t,r)}static $(){return["GrokBotAccessOrganizationPrincipal"]}}class Ja extends pa{constructor(t){super(),this.principal={case:void 0},this.role=ha.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ja).fromBinary(t,r)}static fromJson(t,r){return(new Ja).fromJson(t,r)}static fromJsonString(t,r){return(new Ja).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ja,t,r)}static $(){return["GrokBotAccessPrincipal|1 team #0 principal|2 user_id 5 principal|3 group_id 3 principal|5 other_team_id 5 principal|6 organization #1 principal|4 role #2|7 invited_as_email 9?",ga,_a,ha]}}class wa extends pa{constructor(t){super(),this.principals=[],this.teamRowOn=!1,this.availableRoles=[],this.expectedStateToken="",this.groupsEnabled=!1,this.teamRowOffAllowed=!1,this.crossTeamSharingEnabled=!1,this.callerMayEditCrossTeamRows=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wa).fromBinary(t,r)}static fromJson(t,r){return(new wa).fromJson(t,r)}static fromJsonString(t,r){return(new wa).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(wa,t,r)}static $(){return["GrokBotAgentAccessState|1 principals #0*|2 team_row_on 8|3 available_roles #1*|4 expected_state_token 9|5 groups_enabled 8|6 team_row_off_allowed 8|7 cross_team_sharing_enabled 8|8 caller_may_edit_cross_team_rows 8",Ja,ha]}}class ya extends pa{constructor(t){super(),this.principals=[],this.expectedStateToken="",this.listsCrossTierPrincipals=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ya).fromBinary(t,r)}static fromJson(t,r){return(new ya).fromJson(t,r)}static fromJsonString(t,r){return(new ya).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ya,t,r)}static $(){return["GrokBotAgentAccessUpdate|1 principals #0*|2 expected_state_token 9|3 lists_cross_tier_principals 8",Ja]}}const Sa="aiserver.v1.";class qa extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",s.proto3)}static $p(){return Sa}}var Ba=(0,i.QT)(s.proto3,Sa,"GrokBotTransferRole",[[0,"UNSPECIFIED"],[1,"VIEWER"],[2,"USER"],[3,"MANAGER"]],1),Ia=(0,i.QT)(s.proto3,Sa,"GrokBotTransferActorRole",[[0,"UNSPECIFIED"],[1,"OWNER"],[2,"SOURCE_ADMIN"],[3,"ORG_ADMIN"],[4,"CURSOR_SUPPORT"]],1),Pa=(0,i.QT)(s.proto3,Sa,"GrokBotTransferGroupDropReason",[[0,"UNSPECIFIED"],[1,"MANUAL"],[2,"NOT_LINKED_ON_DESTINATION"],[3,"CURSOR_GROUP_SOURCE"]],1),ba=(0,i.QT)(s.proto3,Sa,"GrokBotTransferTeamRowSource",[[0,"UNSPECIFIED"],[1,"SOURCE_TEAM_ROW"],[2,"OTHER_TEAM_SHARE"],[3,"BOTH"]],1),Ra=(0,i.QT)(s.proto3,Sa,"GrokBotTransferWarningKind",[[0,"UNSPECIFIED"],[1,"CROSS_TEAM_SHARING_MISMATCH"],[2,"TEAMS_ADMIN_GRANT_MISSING"],[3,"DESTINATION_TEAM_ROW_MANAGER"],[4,"OWNER_NOT_ON_DESTINATION"]],1),va=(0,i.QT)(s.proto3,Sa,"GrokBotTransferOutcome",[[0,"UNSPECIFIED"],[1,"TRANSFERRED"],[2,"ALREADY_ON_TEAM"],[3,"NOT_PERMITTED"],[4,"NOT_ELIGIBLE"],[5,"DESTINATION_NOT_READY"],[6,"PLAN_STALE"],[7,"BUSY"],[8,"STARTED"],[9,"FAILED"]],1),xa=(0,i.QT)(s.proto3,Sa,"GrokBotTransferState",[[0,"UNSPECIFIED"],[1,"RUNNING"],[2,"DONE"],[3,"FAILED"],[4,"ROLLED_BACK"]],1);class ka extends qa{constructor(t){super(),this.teamId=0,this.name="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ka).fromBinary(t,r)}static fromJson(t,r){return(new ka).fromJson(t,r)}static fromJsonString(t,r){return(new ka).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ka,t,r)}static $(){return["GrokBotTransferTeamRef|1 team_id 5|2 name 9"]}}class Ea extends qa{constructor(t){super(),this.userId=0,this.name="",this.email="",this.role=Ba.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ea).fromBinary(t,r)}static fromJson(t,r){return(new Ea).fromJson(t,r)}static fromJsonString(t,r){return(new Ea).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ea,t,r)}static $(){return["GrokBotTransferUserRef|1 user_id 5|2 name 9|3 email 9|4 role #0",Ba]}}class Ca extends qa{constructor(t){super(),this.groupId=s.protoInt64.zero,this.name="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ca).fromBinary(t,r)}static fromJson(t,r){return(new Ca).fromJson(t,r)}static fromJsonString(t,r){return(new Ca).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ca,t,r)}static $(){return["GrokBotTransferGroupRef|1 group_id 3|2 name 9"]}}class Ta extends qa{constructor(t){super(),this.destinationGroups=[],this.role=Ba.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ta).fromBinary(t,r)}static fromJson(t,r){return(new Ta).fromJson(t,r)}static fromJsonString(t,r){return(new Ta).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ta,t,r)}static $(){return["GrokBotTransferCarriedGroup|1 source_group #0|2 destination_groups #0*|3 role #1",Ca,Ba]}}class Ua extends qa{constructor(t){super(),this.role=Ba.UNSPECIFIED,this.reason=Pa.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ua).fromBinary(t,r)}static fromJson(t,r){return(new Ua).fromJson(t,r)}static fromJsonString(t,r){return(new Ua).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ua,t,r)}static $(){return["GrokBotTransferDroppedGroup|1 group #0|2 role #1|3 reason #2",Ca,Ba,Pa]}}class Aa extends qa{constructor(t){super(),this.role=Ba.UNSPECIFIED,this.destinationMemberCount=0,this.from=ba.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Aa).fromBinary(t,r)}static fromJson(t,r){return(new Aa).fromJson(t,r)}static fromJsonString(t,r){return(new Aa).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Aa,t,r)}static $(){return["GrokBotTransferDestinationTeamRow|1 role #0|2 destination_member_count 5|3 from #1",Ba,ba]}}class $a extends qa{constructor(t){super(),this.role=Ba.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $a).fromBinary(t,r)}static fromJson(t,r){return(new $a).fromJson(t,r)}static fromJsonString(t,r){return(new $a).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals($a,t,r)}static $(){return["GrokBotTransferShareRow|1 role #0",Ba]}}class Ma extends qa{constructor(t){super(),this.otherTeams=[],this.managedByOrgAdmins=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ma).fromBinary(t,r)}static fromJson(t,r){return(new Ma).fromJson(t,r)}static fromJsonString(t,r){return(new Ma).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ma,t,r)}static $(){return["GrokBotTransferOrgWideShares|1 organization_row #0|2 destination_team_row_from_share #0|3 other_teams #1*|4 managed_by_org_admins 8",$a,ka]}}class Oa extends qa{constructor(t){super(),this.roomId="",this.name="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Oa).fromBinary(t,r)}static fromJson(t,r){return(new Oa).fromJson(t,r)}static fromJsonString(t,r){return(new Oa).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Oa,t,r)}static $(){return["GrokBotTransferRoomRef|1 room_id 9|2 name 9"]}}class Da extends qa{constructor(t){super(),this.linked=!1,this.slackTeamId="",this.workspaceName="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Da).fromBinary(t,r)}static fromJson(t,r){return(new Da).fromJson(t,r)}static fromJsonString(t,r){return(new Da).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Da,t,r)}static $(){return["GrokBotTransferSlack|1 linked 8|2 slack_team_id 9|3 workspace_name 9"]}}class Na extends qa{constructor(t){super(),this.installed=!1,this.tenantId="",this.destinationAdminGrantPresent=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Na).fromBinary(t,r)}static fromJson(t,r){return(new Na).fromJson(t,r)}static fromJsonString(t,r){return(new Na).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Na,t,r)}static $(){return["GrokBotTransferTeamsInstall|1 installed 8|2 tenant_id 9|3 destination_admin_grant_present 8"]}}class Ga extends qa{constructor(t){super(),this.kind=Ra.UNSPECIFIED,this.message="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ga).fromBinary(t,r)}static fromJson(t,r){return(new Ga).fromJson(t,r)}static fromJsonString(t,r){return(new Ga).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ga,t,r)}static $(){return["GrokBotTransferWarning|1 kind #0|2 message 9",Ra]}}class La extends qa{constructor(t){super(),this.agentId="",this.agentName="",this.ownerOnDestination=!1,this.keptUsers=[],this.droppedUsers=[],this.carriedGroups=[],this.droppedGroups=[],this.autoAddRemoved=0,this.routinesMoved=0,this.roomsUnseated=[],this.pluginsMoved=0,this.teamMcpMoved=0,this.warnings=[],this.planHash="",this.actorRole=Ia.UNSPECIFIED,this.notifiesSourceAdmins=!1,this.organizationName="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new La).fromBinary(t,r)}static fromJson(t,r){return(new La).fromJson(t,r)}static fromJsonString(t,r){return(new La).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(La,t,r)}static $(){return["GrokBotTransferPlan|1 agent_id 9|2 agent_name 9|3 source_team #0|4 destination_team #0|5 owner #1|6 owner_on_destination 8|7 kept_users #1*|8 dropped_users #1*|9 destination_team_row #2|10 carried_groups #3*|11 dropped_groups #4*|12 org_wide_shares #5|13 auto_add_removed 5|14 routines_moved 5|15 rooms_unseated #6*|16 plugins_moved 5|17 team_mcp_moved 5|18 slack #7|19 teams #8|20 warnings #9*|21 plan_hash 9|22 actor_role #10|23 notifies_source_admins 8|24 organization_name 9",ka,Ea,Aa,Ta,Ua,Ma,Oa,Da,Na,Ga,Ia]}}class Fa extends qa{constructor(t){super(),this.agentId="",this.refusal=va.UNSPECIFIED,this.message="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fa).fromBinary(t,r)}static fromJson(t,r){return(new Fa).fromJson(t,r)}static fromJsonString(t,r){return(new Fa).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Fa,t,r)}static $(){return["GrokBotTransferPreviewItem|1 agent_id 9|2 refusal #0|3 message 9|4 plan #1",va,La]}}class Ka extends qa{constructor(t){super(),this.agentId="",this.planHash="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ka).fromBinary(t,r)}static fromJson(t,r){return(new Ka).fromJson(t,r)}static fromJsonString(t,r){return(new Ka).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ka,t,r)}static $(){return["GrokBotTransferPlanRef|1 agent_id 9|2 plan_hash 9"]}}class za extends qa{constructor(t){super(),this.agentId="",this.outcome=va.UNSPECIFIED,this.transferId="",this.message="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new za).fromBinary(t,r)}static fromJson(t,r){return(new za).fromJson(t,r)}static fromJsonString(t,r){return(new za).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(za,t,r)}static $(){return["GrokBotTransferItemResult|1 agent_id 9|2 outcome #0|3 transfer_id 9|4 message 9",va]}}class ja extends qa{constructor(t){super(),this.transferId="",this.agentId="",this.sourceTeamId=0,this.destinationTeamId=0,this.state=xa.UNSPECIFIED,this.step="",this.errorCode="",this.createdAtMs=s.protoInt64.zero,this.updatedAtMs=s.protoInt64.zero,this.bulkOperationId="",this.actorRole=Ia.UNSPECIFIED,this.moved=!1,this.resumable=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ja).fromBinary(t,r)}static fromJson(t,r){return(new ja).fromJson(t,r)}static fromJsonString(t,r){return(new ja).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ja,t,r)}static $(){return["GrokBotTransferStatus|1 transfer_id 9|2 agent_id 9|3 source_team_id 5|4 destination_team_id 5|5 state #0|6 step 9|7 error_code 9|8 created_at_ms 3|9 updated_at_ms 3|10 bulk_operation_id 9|11 actor_role #1|12 moved 8|13 resumable 8",xa,Ia]}}class Ha extends qa{constructor(t){super(),this.memberCount=0,this.ready=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ha).fromBinary(t,r)}static fromJson(t,r){return(new Ha).fromJson(t,r)}static fromJsonString(t,r){return(new Ha).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ha,t,r)}static $(){return["GrokBotTransferDestination|1 team #0|2 member_count 5|3 ready 8",ka]}}var Wa=e("../proto/dist/generated/aiserver/v1/utils_pb.js");const Qa="aiserver.v1.";class Va extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",s.proto3)}static $p(){return Qa}}var Xa=(0,i.QT)(s.proto3,Qa,"SandEgressHttpHeaderOp",[[0,"UNSPECIFIED"],[1,"SET"],[2,"APPEND"],[3,"REMOVE"]],1),Ya=(0,i.QT)(s.proto3,Qa,"GrokBotRoiPreviewSort",[[0,"UNSPECIFIED"],[1,"OUTPUTS"],[2,"USAGE"],[3,"COST_PER_OUTPUT"]],1),Za=(0,i.QT)(s.proto3,Qa,"TeamGrokBotRoiBotPersonRole",[[0,"UNSPECIFIED"],[1,"OWNER"],[2,"MANAGER"],[3,"COLLABORATOR"]],1),tu=(0,i.QT)(s.proto3,Qa,"GrokBotGroupTriState",[[0,"UNSPECIFIED"],[1,"INHERIT"],[2,"ON"],[3,"OFF"]],1),ru=(0,i.QT)(s.proto3,Qa,"GrokBotSlackWorkspaceAccessScope",[[0,"UNSPECIFIED"],[1,"ORGANIZATION"],[2,"TEAM"]],1),eu=(0,i.QT)(s.proto3,Qa,"SandSetupChecklistItemState",[[0,"UNSPECIFIED"],[1,"CHECKED"],[2,"SKIPPED"],[3,"CLEARED"]],1),nu=(0,i.QT)(s.proto3,Qa,"SandOnboardingCompletionSource",[[0,"UNSPECIFIED"],[1,"DASHBOARD_SETTINGS"],[2,"PORTAL_ONBOARDING"]],1),su=(0,i.QT)(s.proto3,Qa,"SandBillingBrand",[[0,"UNSPECIFIED"],[1,"CURSOR"],[2,"GROK"]],1),iu=(0,i.QT)(s.proto3,Qa,"SandSeatTierUpgradeRequestOrigin",[[0,"UNSPECIFIED"],[1,"USAGE_WARNING"],[2,"USAGE_LIMIT"]],1),ou=(0,i.QT)(s.proto3,Qa,"GrokBotUsageSource",[[0,"UNSPECIFIED"],[1,"USER"],[2,"AUTOMATION"],[3,"AGENT"],[4,"GROUP"],[5,"OTHER"]],1),au=(0,i.QT)(s.proto3,Qa,"GrokBotIdpClientAuthMethod",[[0,"UNSPECIFIED"],[1,"CLIENT_SECRET_BASIC"],[2,"CLIENT_SECRET_POST"],[3,"PRIVATE_KEY_JWT"],[4,"NONE"]],1),uu=(0,i.QT)(s.proto3,Qa,"GrokBotIdJagConnectorPolicyMode",[[0,"UNSPECIFIED"],[1,"ALL"],[2,"LISTED"]],1),cu=(0,i.QT)(s.proto3,Qa,"TeamGrokBotScimOktaSignInMethod",[[0,"UNSPECIFIED"],[1,"SAML_HOP"],[2,"SAML_BEARER"]],1),lu=(0,i.QT)(s.proto3,Qa,"TeamGrokBotScimOktaClientAuthMethod",[[0,"UNSPECIFIED"],[1,"CLIENT_SECRET_BASIC"],[2,"CLIENT_SECRET_POST"]],1),mu=(0,i.QT)(s.proto3,Qa,"GrokBotPublishedWorkerImageState",[[0,"UNSPECIFIED"],[1,"UNAVAILABLE"],[2,"NONE_YET"],[3,"PUBLISHED"],[4,"UNREACHABLE"],[5,"UNREADABLE"]],1),fu=(0,i.QT)(s.proto3,Qa,"GrokBotPublishedWorkerImageFailure",[[0,"UNSPECIFIED"],[1,"UNREACHABLE"],[2,"UNREADABLE"]],1),du=(0,i.QT)(s.proto3,Qa,"GrokBotCustomerHostedWorkerSetupState",[[0,"UNSPECIFIED"],[1,"IDLE"],[2,"OK"],[3,"APPLYING"],[4,"DEGRADED"],[5,"FAILED"],[6,"KILLED"],[7,"UNAVAILABLE"]],1),pu=(0,i.QT)(s.proto3,Qa,"GrokBotCustomerHostedWorkerSetupUnavailableReason",[[0,"UNSPECIFIED"],[1,"NOT_DESIGNATED"],[2,"POOL_MISMATCH"],[3,"POOL_PURPOSE"],[4,"POOL_NOT_TRANSPORTABLE"],[5,"SETUP_TOO_LARGE"],[6,"SETUP_INVALID"]],1),hu=(0,i.QT)(s.proto3,Qa,"TeamGrokBotDashboardRole",[[0,"UNSPECIFIED"],[1,"VIEWER"],[2,"MANAGER"]],1);class gu extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gu).fromBinary(t,r)}static fromJson(t,r){return(new gu).fromJson(t,r)}static fromJsonString(t,r){return(new gu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(gu,t,r)}static $(){return["GetTeamSandNetworkSettingsRequest|1 team_id 5"]}}class _u extends Va{constructor(t){super(),this.emptyAllowlistGuardEnabled=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _u).fromBinary(t,r)}static fromJson(t,r){return(new _u).fromJson(t,r)}static fromJsonString(t,r){return(new _u).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(_u,t,r)}static $(){return["GetTeamSandNetworkSettingsResponse|1 sand_network_controls #0|3 organization_network_blocklist #1|4 empty_allowlist_guard_enabled 8",n.JE6,n.cxP]}}class Ju extends Va{constructor(t){super(),this.op=Xa.UNSPECIFIED,this.name="",this.value="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ju).fromBinary(t,r)}static fromJson(t,r){return(new Ju).fromJson(t,r)}static fromJsonString(t,r){return(new Ju).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ju,t,r)}static $(){return["SandEgressHttpHeaderTransform|1 op #0|2 name 9|3 value 9",Xa]}}class wu extends Va{constructor(t){super(),this.name="",this.hosts=[],this.transforms=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wu).fromBinary(t,r)}static fromJson(t,r){return(new wu).fromJson(t,r)}static fromJsonString(t,r){return(new wu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(wu,t,r)}static $(){return["SandEgressHttpRule|1 name 9|2 hosts 9*|3 transforms #0*",Ju]}}class yu extends Va{constructor(t){super(),this.rules=[],this.allTrafficTransforms=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yu).fromBinary(t,r)}static fromJson(t,r){return(new yu).fromJson(t,r)}static fromJsonString(t,r){return(new yu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(yu,t,r)}static $(){return["SandEgressHttpRules|1 rules #0*|2 all_traffic_transforms #1*",wu,Ju]}}class Su extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Su).fromBinary(t,r)}static fromJson(t,r){return(new Su).fromJson(t,r)}static fromJsonString(t,r){return(new Su).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Su,t,r)}static $(){return["GetTeamSandEgressHttpRulesRequest|1 team_id 5"]}}class qu extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qu).fromBinary(t,r)}static fromJson(t,r){return(new qu).fromJson(t,r)}static fromJsonString(t,r){return(new qu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(qu,t,r)}static $(){return["GetTeamSandEgressHttpRulesResponse|1 rules #0",yu]}}class Bu extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bu).fromBinary(t,r)}static fromJson(t,r){return(new Bu).fromJson(t,r)}static fromJsonString(t,r){return(new Bu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Bu,t,r)}static $(){return["UpdateTeamSandEgressHttpRulesRequest|1 team_id 5|2 rules #0",yu]}}class Iu extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Iu).fromBinary(t,r)}static fromJson(t,r){return(new Iu).fromJson(t,r)}static fromJsonString(t,r){return(new Iu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Iu,t,r)}static $(){return["UpdateTeamSandEgressHttpRulesResponse"]}}class Pu extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pu).fromBinary(t,r)}static fromJson(t,r){return(new Pu).fromJson(t,r)}static fromJsonString(t,r){return(new Pu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Pu,t,r)}static $(){return["GetTeamGrokBotTrialRequest|1 team_id 5"]}}class bu extends Va{constructor(t){super(),this.active=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bu).fromBinary(t,r)}static fromJson(t,r){return(new bu).fromJson(t,r)}static fromJsonString(t,r){return(new bu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(bu,t,r)}static $(){return["GetTeamGrokBotTrialResponse|1 active 8|2 expires_at #0",s.Timestamp]}}class Ru extends Va{constructor(t){super(),this.state=vu.UNSPECIFIED,this.shareability=xu.UNSPECIFIED,this.ownerUserId=0,this.kind=ku.UNSPECIFIED,this.nameQuery="",this.agentId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ru).fromBinary(t,r)}static fromJson(t,r){return(new Ru).fromJson(t,r)}static fromJsonString(t,r){return(new Ru).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ru,t,r)}static $(){return["TeamGrokBotAdminAgentFilter|1 state #0|2 shareability #1|3 owner_user_id 5|4 kind #2|5 name_query 9|6 agent_id 9",vu,xu,ku]}}var vu=(0,i.QT)(s.proto3,Qa,"TeamGrokBotAdminAgentFilter.State",[[0,"UNSPECIFIED"],[1,"ACTIVE"],[2,"DELETED"]],1),xu=(0,i.QT)(s.proto3,Qa,"TeamGrokBotAdminAgentFilter.Shareability",[[0,"UNSPECIFIED"],[1,"PERSONAL"],[2,"TEAM_SHARED"]],1),ku=(0,i.QT)(s.proto3,Qa,"TeamGrokBotAdminAgentFilter.Kind",[[0,"UNSPECIFIED"],[1,"AGENT"],[2,"ROOM"]],1);class Eu extends Va{constructor(t){super(),this.teamId=0,this.pageSize=0,this.pageToken="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Eu).fromBinary(t,r)}static fromJson(t,r){return(new Eu).fromJson(t,r)}static fromJsonString(t,r){return(new Eu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Eu,t,r)}static $(){return["ListTeamGrokBotAgentsAdminRequest|1 team_id 5|2 page_size 5|3 page_token 9|4 filter #0",Ru]}}class Cu extends Va{constructor(t){super(),this.roomId="",this.name="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cu).fromBinary(t,r)}static fromJson(t,r){return(new Cu).fromJson(t,r)}static fromJsonString(t,r){return(new Cu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Cu,t,r)}static $(){return["TeamGrokBotAdminRoomRef|1 room_id 9|2 name 9"]}}class Tu extends Va{constructor(t){super(),this.agentId="",this.name="",this.description="",this.ownerUserEmail="",this.ownerUserId=0,this.isTeamAgent=!1,this.kind="",this.rooms=[],this.ownerDisplayName="",this.avatarUrl="",this.avatarShape="",this.avatarColor="",this.isPublished=!1,this.deletable=!1,this.teamApprovedByUserId=0,this.transferable=!1,this.transferringToUserId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tu).fromBinary(t,r)}static fromJson(t,r){return(new Tu).fromJson(t,r)}static fromJsonString(t,r){return(new Tu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Tu,t,r)}static $(){return["TeamGrokBotAdminAgentRow|1 agent_id 9|2 name 9|3 description 9|4 owner_user_email 9|5 owner_user_id 5|6 is_team_agent 8|7 kind 9|8 created_at #0|9 deleted_at #0|10 rooms #1*|11 owner_display_name 9|12 avatar_url 9|13 avatar_shape 9|14 avatar_color 9|15 audience #2|16 is_published 8|17 deletable 8|18 team_approved_at #0|19 team_approved_by_user_id 5|20 transferable 8|21 transferring_to_user_id 5",s.Timestamp,Cu,el]}}class Uu extends Va{constructor(t){super(),this.rows=[],this.nextPageToken="",this.teamDefaultBotsEnabled=!1,this.ownershipTransferEnabled=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Uu).fromBinary(t,r)}static fromJson(t,r){return(new Uu).fromJson(t,r)}static fromJsonString(t,r){return(new Uu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Uu,t,r)}static $(){return["ListTeamGrokBotAgentsAdminResponse|1 rows #0*|2 next_page_token 9|3 team_default_bots_enabled 8|4 ownership_transfer_enabled 8",Tu]}}class Au extends Va{constructor(t){super(),this.teamId=0,this.page=0,this.pageSize=0,this.summaryOnly=!1,this.sort=Ya.UNSPECIFIED,this.ascending=!1,this.usageIncludesUntracked=!1,this.search="",this.reuseOrCoinShadow=!1,this.skipUsage=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Au).fromBinary(t,r)}static fromJson(t,r){return(new Au).fromJson(t,r)}static fromJsonString(t,r){return(new Au).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Au,t,r)}static $(){return["GetTeamGrokBotRoiPreviewRequest|1 team_id 5|3 page 5|4 page_size 5|5 summary_only 8|6 sort #0|7 ascending 8|8 usage_includes_untracked 8|9 search 9|10 reuse_or_coin_shadow 8|11 skip_usage 8",Ya]}}class $u extends Va{constructor(t){super(),this.label="",this.count=s.protoInt64.zero,this.primary=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $u).fromBinary(t,r)}static fromJson(t,r){return(new $u).fromJson(t,r)}static fromJsonString(t,r){return(new $u).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals($u,t,r)}static $(){return["TeamGrokBotRoiPreviewNoun|1 label 9|2 count 3|3 primary 8"]}}class Mu extends Va{constructor(t){super(),this.agentId="",this.name="",this.ownerUserEmail="",this.isTeamAgent=!1,this.nouns=[],this.generationStatus="",this.roiNotRead=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mu).fromBinary(t,r)}static fromJson(t,r){return(new Mu).fromJson(t,r)}static fromJsonString(t,r){return(new Mu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Mu,t,r)}static $(){return["TeamGrokBotRoiPreviewRow|1 agent_id 9|2 name 9|3 owner_user_email 9|4 is_team_agent 8|5 nouns #0*|6 generation_status 9|7 usage_cents 3?|8 tracking_started_at_ms 3?|9 untracked_usage_cents 3?|10 roi_not_read 8|11 output_count 3?",$u]}}class Ou extends Va{constructor(t){super(),this.enabled=!1,this.rows=[],this.windowDays=0,this.roiBotCount=0,this.allBotCount=0,this.page=0,this.pageSize=0,this.inventoryTruncated=!1,this.usageShown=!1,this.usageFailed=!1,this.memberScope=!1,this.windowStartMs=s.protoInt64.zero,this.cohortTruncated=!1,this.appliedSort=Ya.UNSPECIFIED,this.ownerSearchFailed=!1,this.reuseOrCoinShadow=!1,this.botDrilldownEnabled=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ou).fromBinary(t,r)}static fromJson(t,r){return(new Ou).fromJson(t,r)}static fromJsonString(t,r){return(new Ou).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ou,t,r)}static $(){return["GetTeamGrokBotRoiPreviewResponse|1 enabled 8|2 rows #0*|3 window_days 5|4 roi_bot_count 5|5 all_bot_count 5|6 page 5|7 page_size 5|8 inventory_truncated 8|9 usage_shown 8|10 usage_failed 8|11 member_scope 8|12 tracking_started_at_ms 3?|13 window_start_ms 3|14 cohort_truncated 8|15 applied_sort #1|16 owner_search_failed 8|17 reuse_or_coin_shadow 8|18 bot_drilldown_enabled 8",Mu,Ya]}}class Du extends Va{constructor(t){super(),this.teamId=0,this.agentId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Du).fromBinary(t,r)}static fromJson(t,r){return(new Du).fromJson(t,r)}static fromJsonString(t,r){return(new Du).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Du,t,r)}static $(){return["GetTeamGrokBotRoiBotRequest|1 team_id 5|2 agent_id 9"]}}class Nu extends Va{constructor(t){super(),this.day="",this.count=s.protoInt64.zero,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nu).fromBinary(t,r)}static fromJson(t,r){return(new Nu).fromJson(t,r)}static fromJsonString(t,r){return(new Nu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Nu,t,r)}static $(){return["TeamGrokBotRoiBotOutputDay|1 day 9|2 count 3"]}}class Gu extends Va{constructor(t){super(),this.label="",this.level="",this.primary=!1,this.days=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gu).fromBinary(t,r)}static fromJson(t,r){return(new Gu).fromJson(t,r)}static fromJsonString(t,r){return(new Gu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Gu,t,r)}static $(){return["TeamGrokBotRoiBotOutput|1 label 9|2 level 9|3 primary 8|4 days #0*",Nu]}}class Lu extends Va{constructor(t){super(),this.day="",this.activeUsers=0,this.trailingSevenDayActiveUsers=0,this.userTurns=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lu).fromBinary(t,r)}static fromJson(t,r){return(new Lu).fromJson(t,r)}static fromJsonString(t,r){return(new Lu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Lu,t,r)}static $(){return["TeamGrokBotRoiBotUsageDay|1 day 9|2 active_users 5|3 trailing_seven_day_active_users 5|4 user_turns 5"]}}class Fu extends Va{constructor(t){super(),this.userId=0,this.displayName="",this.userTurns=0,this.isExternal=!1,this.activeDays=0,this.role=Za.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fu).fromBinary(t,r)}static fromJson(t,r){return(new Fu).fromJson(t,r)}static fromJsonString(t,r){return(new Fu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Fu,t,r)}static $(){return["TeamGrokBotRoiBotPerson|1 user_id 5|2 display_name 9|3 user_turns 5|4 is_external 8|5 active_days 5|6 role #0",Za]}}class Ku extends Va{constructor(t){super(),this.windowDays=0,this.people=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ku).fromBinary(t,r)}static fromJson(t,r){return(new Ku).fromJson(t,r)}static fromJsonString(t,r){return(new Ku).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ku,t,r)}static $(){return["TeamGrokBotRoiBotPeopleWindow|1 window_days 5|2 people #0*",Fu]}}class zu extends Va{constructor(t){super(),this.enabled=!1,this.agentId="",this.name="",this.ownerDisplayName="",this.ownerUserEmail="",this.isTeamAgent=!1,this.windowDays=0,this.windowStartMs=s.protoInt64.zero,this.outputs=[],this.generationStatus="",this.outputsFailed=!1,this.usageDays=[],this.peopleShown=!1,this.people=[],this.usageFailed=!1,this.usageHidden=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zu).fromBinary(t,r)}static fromJson(t,r){return(new zu).fromJson(t,r)}static fromJsonString(t,r){return(new zu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(zu,t,r)}static $(){return["GetTeamGrokBotRoiBotResponse|1 enabled 8|2 agent_id 9|3 name 9|4 owner_display_name 9|5 owner_user_email 9|6 is_team_agent 8|7 window_days 5|8 window_start_ms 3|9 outputs #0*|10 generation_status 9|11 tracking_started_at_ms 3?|12 outputs_failed 8|13 usage_days #1*|14 people_shown 8|15 people #2*|16 usage_failed 8|18 usage_hidden 8",Gu,Lu,Ku]}}class ju extends Va{constructor(t){super(),this.teamId=0,this.confirmEmptyAllowlist=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ju).fromBinary(t,r)}static fromJson(t,r){return(new ju).fromJson(t,r)}static fromJsonString(t,r){return(new ju).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ju,t,r)}static $(){return["UpdateTeamSandNetworkSettingsRequest|1 team_id 5|2 sand_network_controls #0|3 confirm_empty_allowlist 8",n.JE6]}}class Hu extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hu).fromBinary(t,r)}static fromJson(t,r){return(new Hu).fromJson(t,r)}static fromJsonString(t,r){return(new Hu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Hu,t,r)}static $(){return["UpdateTeamSandNetworkSettingsResponse"]}}class Wu extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wu).fromBinary(t,r)}static fromJson(t,r){return(new Wu).fromJson(t,r)}static fromJsonString(t,r){return(new Wu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Wu,t,r)}static $(){return["GetTeamSandTrustedCaCertificatesRequest|1 team_id 5"]}}class Qu extends Va{constructor(t){super(),this.certificates=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qu).fromBinary(t,r)}static fromJson(t,r){return(new Qu).fromJson(t,r)}static fromJsonString(t,r){return(new Qu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Qu,t,r)}static $(){return["GetTeamSandTrustedCaCertificatesResponse|1 certificates 9*"]}}class Vu extends Va{constructor(t){super(),this.teamId=0,this.certificates=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vu).fromBinary(t,r)}static fromJson(t,r){return(new Vu).fromJson(t,r)}static fromJsonString(t,r){return(new Vu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Vu,t,r)}static $(){return["UpdateTeamSandTrustedCaCertificatesRequest|1 team_id 5|2 certificates 9*"]}}class Xu extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xu).fromBinary(t,r)}static fromJson(t,r){return(new Xu).fromJson(t,r)}static fromJsonString(t,r){return(new Xu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Xu,t,r)}static $(){return["UpdateTeamSandTrustedCaCertificatesResponse"]}}class Yu extends Va{constructor(t){super(),this.hosts=[],this.cidrs=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yu).fromBinary(t,r)}static fromJson(t,r){return(new Yu).fromJson(t,r)}static fromJsonString(t,r){return(new Yu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Yu,t,r)}static $(){return["SandLocalEgressPrivateDestinationRule|1 hosts 9*|2 cidrs 9*"]}}class Zu extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zu).fromBinary(t,r)}static fromJson(t,r){return(new Zu).fromJson(t,r)}static fromJsonString(t,r){return(new Zu).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Zu,t,r)}static $(){return["GetTeamSandLocalEgressPrivateDestinationsRequest|1 team_id 5"]}}class tc extends Va{constructor(t){super(),this.rules=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tc).fromBinary(t,r)}static fromJson(t,r){return(new tc).fromJson(t,r)}static fromJsonString(t,r){return(new tc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(tc,t,r)}static $(){return["GetTeamSandLocalEgressPrivateDestinationsResponse|1 rules #0*",Yu]}}class rc extends Va{constructor(t){super(),this.teamId=0,this.rules=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rc).fromBinary(t,r)}static fromJson(t,r){return(new rc).fromJson(t,r)}static fromJsonString(t,r){return(new rc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(rc,t,r)}static $(){return["UpdateTeamSandLocalEgressPrivateDestinationsRequest|1 team_id 5|2 rules #0*",Yu]}}class ec extends Va{constructor(t){super(),this.rules=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ec).fromBinary(t,r)}static fromJson(t,r){return(new ec).fromJson(t,r)}static fromJsonString(t,r){return(new ec).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ec,t,r)}static $(){return["UpdateTeamSandLocalEgressPrivateDestinationsResponse|1 rules #0*",Yu]}}class nc extends Va{constructor(t){super(),this.teamId=0,this.groupPublicId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nc).fromBinary(t,r)}static fromJson(t,r){return(new nc).fromJson(t,r)}static fromJsonString(t,r){return(new nc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(nc,t,r)}static $(){return["GetTeamGroupSandNetworkSettingsRequest|1 team_id 5|2 group_public_id 9"]}}class sc extends Va{constructor(t){super(),this.emptyAllowlistGuardEnabled=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sc).fromBinary(t,r)}static fromJson(t,r){return(new sc).fromJson(t,r)}static fromJsonString(t,r){return(new sc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(sc,t,r)}static $(){return["GetTeamGroupSandNetworkSettingsResponse|1 sand_network_controls #0|2 team_sand_network_controls #0|4 organization_network_blocklist #1|5 empty_allowlist_guard_enabled 8",n.JE6,n.cxP]}}class ic extends Va{constructor(t){super(),this.teamId=0,this.groupId=s.protoInt64.zero,this.confirmEmptyAllowlist=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ic).fromBinary(t,r)}static fromJson(t,r){return(new ic).fromJson(t,r)}static fromJsonString(t,r){return(new ic).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ic,t,r)}static $(){return["UpdateTeamGroupSandNetworkSettingsRequest|1 team_id 5|2 group_id 3|3 sand_network_controls #0|4 confirm_empty_allowlist 8",n.JE6]}}class oc extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oc).fromBinary(t,r)}static fromJson(t,r){return(new oc).fromJson(t,r)}static fromJsonString(t,r){return(new oc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(oc,t,r)}static $(){return["UpdateTeamGroupSandNetworkSettingsResponse"]}}class ac extends Va{constructor(t){super(),this.cloudAgents=tu.UNSPECIFIED,this.localExecutionCeiling=n.odJ.UNSPECIFIED,this.localEgressAllowed=tu.UNSPECIFIED,this.enforceAutoReview=tu.UNSPECIFIED,this.agentEmail=tu.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ac).fromBinary(t,r)}static fromJson(t,r){return(new ac).fromJson(t,r)}static fromJsonString(t,r){return(new ac).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ac,t,r)}static $(){return["GrokBotGroupCapabilities|1 cloud_agents #0|2 local_execution_ceiling #1|3 local_egress_allowed #0|4 enforce_auto_review #0|5 auto_review_rules #2|6 agent_email #0",tu,n.odJ,Fc]}}class uc extends Va{constructor(t){super(),this.cloudAgentsAllowed=!1,this.localExecutionCeiling=n.odJ.UNSPECIFIED,this.localEgressAllowed=!1,this.enforceAutoReview=!1,this.agentEmailAllowed=!1,this.localEgressMode=n.SDZ.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uc).fromBinary(t,r)}static fromJson(t,r){return(new uc).fromJson(t,r)}static fromJsonString(t,r){return(new uc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(uc,t,r)}static $(){return["GrokBotTeamCapabilities|1 cloud_agents_allowed 8|2 local_execution_ceiling #0|3 local_egress_allowed 8|4 enforce_auto_review 8|5 auto_review_rules #1|6 agent_email_allowed 8|7 local_egress_mode #2",n.odJ,Fc,n.SDZ]}}class cc extends Va{constructor(t){super(),this.teamId=0,this.groupPublicId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cc).fromBinary(t,r)}static fromJson(t,r){return(new cc).fromJson(t,r)}static fromJsonString(t,r){return(new cc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(cc,t,r)}static $(){return["GetTeamGroupGrokBotCapabilitiesRequest|1 team_id 5|2 group_public_id 9"]}}class lc extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lc).fromBinary(t,r)}static fromJson(t,r){return(new lc).fromJson(t,r)}static fromJsonString(t,r){return(new lc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(lc,t,r)}static $(){return["GetTeamGroupGrokBotCapabilitiesResponse|1 capabilities #0|2 team_capabilities #1",ac,uc]}}class mc extends Va{constructor(t){super(),this.teamId=0,this.groupId=s.protoInt64.zero,this.cloudAgents=tu.UNSPECIFIED,this.localEgressAllowed=tu.UNSPECIFIED,this.enforceAutoReview=tu.UNSPECIFIED,this.agentEmail=tu.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mc).fromBinary(t,r)}static fromJson(t,r){return(new mc).fromJson(t,r)}static fromJsonString(t,r){return(new mc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(mc,t,r)}static $(){return["UpdateTeamGroupGrokBotCapabilitiesRequest|1 team_id 5|2 group_id 3|3 cloud_agents #0|4 local_execution_ceiling #1?|5 local_egress_allowed #0|6 enforce_auto_review #0|7 auto_review_rules #2|8 agent_email #0",tu,n.odJ,Fc]}}class fc extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fc).fromBinary(t,r)}static fromJson(t,r){return(new fc).fromJson(t,r)}static fromJsonString(t,r){return(new fc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(fc,t,r)}static $(){return["UpdateTeamGroupGrokBotCapabilitiesResponse"]}}class dc extends Va{constructor(t){super(),this.serverIdentifiers=[],this.teamTailnetRowsPerTeam=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dc).fromBinary(t,r)}static fromJson(t,r){return(new dc).fromJson(t,r)}static fromJsonString(t,r){return(new dc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(dc,t,r)}static $(){return["ListSandMcpToolsRequest|1 server_identifiers 9*|2 mcp_config_json 9?|3 grok_bot_plugin_scope #0?|4 team_tailnet_rows_per_team 8",n.q0X]}}class pc extends Va{constructor(t){super(),this.servers=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pc).fromBinary(t,r)}static fromJson(t,r){return(new pc).fromJson(t,r)}static fromJsonString(t,r){return(new pc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(pc,t,r)}static $(){return["ListSandMcpToolsResponse|1 servers #0*|2 mcp_allowlist #1?",hc,n.YUq]}}class hc extends Va{constructor(t){super(),this.serverIdentifier="",this.status="",this.tools=[],this.accountLabel="",this.rowServerIdentifier="",this.servedBy=n.JLr.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hc).fromBinary(t,r)}static fromJson(t,r){return(new hc).fromJson(t,r)}static fromJsonString(t,r){return(new hc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(hc,t,r)}static $(){return["ListSandMcpToolsResponse.Server|1 server_identifier 9|2 status 9|3 tools #0*|4 account_label 9|5 row_server_identifier 9|6 served_by #1|7 status_detail 9?|8 grok_connector_id 9?|9 sign_out #2?|10 status_reason 9?",ns.gd,n.JLr,n.eJC]}}class gc extends Va{constructor(t){super(),this.serverIdentifier="",this.toolName="",this.toolCallId="",this.agentId="",this.turnId="",this.eventSequence=s.protoInt64.zero,this.mcpAnalyticsReportedByCaller=!1,this.modelName="",this.refuseSharedPaymentTokenArguments=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gc).fromBinary(t,r)}static fromJson(t,r){return(new gc).fromJson(t,r)}static fromJsonString(t,r){return(new gc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(gc,t,r)}static $(){return["ExecuteSandMcpToolRequest|1 server_identifier 9|2 tool_name 9|3 args #0|4 tool_call_id 9|5 agent_id 9|6 turn_id 9|7 mcp_config_json 9?|8 grok_bot_plugin_scope #1?|9 event_sequence 3|10 mcp_analytics_reported_by_caller 8|11 model_name 9|12 refuse_shared_payment_token_arguments 8",s.Struct,n.q0X]}}class _c extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _c).fromBinary(t,r)}static fromJson(t,r){return(new _c).fromJson(t,r)}static fromJsonString(t,r){return(new _c).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(_c,t,r)}static $(){return["ClassifySandAutoReviewRequest|1 args #0|2 attempt_index 13?|3 mode 9?",fa.Th]}}class Jc extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jc).fromBinary(t,r)}static fromJson(t,r){return(new Jc).fromJson(t,r)}static fromJsonString(t,r){return(new Jc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Jc,t,r)}static $(){return["ClassifySandAutoReviewResponse|1 result #0",fa.bN]}}class wc extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wc).fromBinary(t,r)}static fromJson(t,r){return(new wc).fromJson(t,r)}static fromJsonString(t,r){return(new wc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(wc,t,r)}static $(){return["ExecuteSandMcpToolResponse|1 result #0|2 credential_owner_user_id 5?",ss.iz]}}class yc extends Va{constructor(t){super(),this.serverIdentifier="",this.uri="",this.agentId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yc).fromBinary(t,r)}static fromJson(t,r){return(new yc).fromJson(t,r)}static fromJsonString(t,r){return(new yc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(yc,t,r)}static $(){return["ReadSandMcpResourceRequest|1 server_identifier 9|2 uri 9|3 agent_id 9|4 mcp_config_json 9?|5 grok_bot_plugin_scope #0?",n.q0X]}}class Sc extends Va{constructor(t){super(),this.contents=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sc).fromBinary(t,r)}static fromJson(t,r){return(new Sc).fromJson(t,r)}static fromJsonString(t,r){return(new Sc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Sc,t,r)}static $(){return["ReadSandMcpResourceResponse|1 contents #0*|2 error 9?",qc]}}class qc extends Va{constructor(t){super(),this.uri="",this.body={case:void 0},s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qc).fromBinary(t,r)}static fromJson(t,r){return(new qc).fromJson(t,r)}static fromJsonString(t,r){return(new qc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(qc,t,r)}static $(){return["ReadSandMcpResourceResponse.Content|1 uri 9|2 mime_type 9?|3 text 9 body|4 blob 12 body|5 meta_json 9?"]}}class Bc extends Va{constructor(t){super(),this.eventId="",this.occurredAtMs=s.protoInt64.zero,this.agentId="",this.turnId="",this.boxId="",this.eventSequence=s.protoInt64.zero,this.toolCallId="",this.initiatedBy="",this.action={case:void 0},this.rootTurnId="",this.subagentId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bc).fromBinary(t,r)}static fromJson(t,r){return(new Bc).fromJson(t,r)}static fromJsonString(t,r){return(new Bc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Bc,t,r)}static $(){return["SandAuditEvent|1 event_id 9|2 occurred_at_ms 3|3 agent_id 9|4 turn_id 9|5 box_id 9|10 event_sequence 3|11 tool_call_id 9|19 initiated_by 9|6 mcp_tool_call #0 action|7 shell_command #1 action|8 browser_navigation #2 action|9 computer_use_session #3 action|12 tool_result #4 action|15 message_delivery #5 action|21 file_transfer #6 action|22 guardrail #7 action|14 automation_run #8 action|23 skill_activated #9 action|13 tool_decision #10 action|20 delegation #11 action|16 root_turn_id 9|17 subagent_id 9",Ic,Pc,bc,Rc,vc,xc,kc,Ec,Cc,Tc,Uc,Ac]}}class Ic extends Va{constructor(t){super(),this.toolCallId="",this.serverIdentifier="",this.serverName="",this.toolName="",this.status="",this.durationMs=s.protoInt64.zero,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ic).fromBinary(t,r)}static fromJson(t,r){return(new Ic).fromJson(t,r)}static fromJsonString(t,r){return(new Ic).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ic,t,r)}static $(){return["SandAuditEvent.McpToolCall|1 tool_call_id 9|2 server_identifier 9|3 server_name 9|4 tool_name 9|5 status 9|6 duration_ms 3"]}}class Pc extends Va{constructor(t){super(),this.command="",this.kind="",this.target="",this.allowed=!1,this.blockedReason="",this.classificationReasons=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pc).fromBinary(t,r)}static fromJson(t,r){return(new Pc).fromJson(t,r)}static fromJsonString(t,r){return(new Pc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Pc,t,r)}static $(){return["SandAuditEvent.ShellCommand|1 command 9|2 kind 9|3 target 9|4 allowed 8|5 blocked_reason 9|6 classification_reasons 9*|7 machine_id 9?|8 exit_code 5?|9 duration_ms 3?"]}}class bc extends Va{constructor(t){super(),this.url="",this.pageTitle="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bc).fromBinary(t,r)}static fromJson(t,r){return(new bc).fromJson(t,r)}static fromJsonString(t,r){return(new bc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(bc,t,r)}static $(){return["SandAuditEvent.BrowserNavigation|1 url 9|2 page_title 9"]}}class Rc extends Va{constructor(t){super(),this.toolCallId="",this.actionCount=s.protoInt64.zero,this.actionCounts={},this.durationMs=s.protoInt64.zero,this.screenshotCount=s.protoInt64.zero,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rc).fromBinary(t,r)}static fromJson(t,r){return(new Rc).fromJson(t,r)}static fromJsonString(t,r){return(new Rc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Rc,t,r)}static $(){return["SandAuditEvent.ComputerUseSession|1 tool_call_id 9|2 action_count 3|3 action_counts 9,3|4 duration_ms 3|5 screenshot_count 3"]}}class vc extends Va{constructor(t){super(),this.toolName="",this.outcome="",this.durationMs=s.protoInt64.zero,this.errorCategory="",this.targetHost="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vc).fromBinary(t,r)}static fromJson(t,r){return(new vc).fromJson(t,r)}static fromJsonString(t,r){return(new vc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(vc,t,r)}static $(){return["SandAuditEvent.ToolResult|1 tool_name 9|2 outcome 9|3 duration_ms 3|4 error_category 9|5 target_host 9"]}}class xc extends Va{constructor(t){super(),this.destinationType="",this.destinationId="",this.result="",this.failureCategory="",this.messageId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xc).fromBinary(t,r)}static fromJson(t,r){return(new xc).fromJson(t,r)}static fromJsonString(t,r){return(new xc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(xc,t,r)}static $(){return["SandAuditEvent.MessageDelivery|1 destination_type 9|2 destination_id 9|3 result 9|4 failure_category 9|5 message_id 9"]}}class kc extends Va{constructor(t){super(),this.direction="",this.target="",this.outcome="",this.errorCategory="",this.machineId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kc).fromBinary(t,r)}static fromJson(t,r){return(new kc).fromJson(t,r)}static fromJsonString(t,r){return(new kc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(kc,t,r)}static $(){return["SandAuditEvent.FileTransfer|1 direction 9|2 target 9|3 byte_count 3?|4 outcome 9|5 error_category 9|6 machine_id 9"]}}class Ec extends Va{constructor(t){super(),this.kind="",this.detector="",this.action="",this.count=s.protoInt64.zero,this.targetHost="",this.source="",this.toolName="",this.resolution="",this.decisionId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ec).fromBinary(t,r)}static fromJson(t,r){return(new Ec).fromJson(t,r)}static fromJsonString(t,r){return(new Ec).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ec,t,r)}static $(){return["SandAuditEvent.Guardrail|1 kind 9|2 detector 9|3 action 9|4 count 3|5 target_host 9|6 source 9|7 tool_name 9|8 resolution 9|9 duration_ms 3?|10 decision_id 9"]}}class Cc extends Va{constructor(t){super(),this.automationId="",this.runId="",this.trigger="",this.outcome="",this.durationMs=s.protoInt64.zero,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cc).fromBinary(t,r)}static fromJson(t,r){return(new Cc).fromJson(t,r)}static fromJsonString(t,r){return(new Cc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Cc,t,r)}static $(){return["SandAuditEvent.AutomationRun|1 automation_id 9|2 run_id 9|3 trigger 9|4 outcome 9|5 duration_ms 3"]}}class Tc extends Va{constructor(t){super(),this.skillName="",this.trigger="",this.source="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tc).fromBinary(t,r)}static fromJson(t,r){return(new Tc).fromJson(t,r)}static fromJsonString(t,r){return(new Tc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Tc,t,r)}static $(){return["SandAuditEvent.SkillActivated|1 skill_name 9|2 trigger 9|3 source 9"]}}class Uc extends Va{constructor(t){super(),this.decisionId="",this.toolName="",this.source="",this.approvalMode="",this.outcome="",this.ruleId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Uc).fromBinary(t,r)}static fromJson(t,r){return(new Uc).fromJson(t,r)}static fromJsonString(t,r){return(new Uc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Uc,t,r)}static $(){return["SandAuditEvent.ToolDecision|1 decision_id 9|2 tool_name 9|3 source 9|4 approval_mode 9|5 outcome 9|6 rule_id 9"]}}class Ac extends Va{constructor(t){super(),this.direction="",this.target="",this.targetId="",this.outcome="",this.kind="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ac).fromBinary(t,r)}static fromJson(t,r){return(new Ac).fromJson(t,r)}static fromJsonString(t,r){return(new Ac).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ac,t,r)}static $(){return["SandAuditEvent.Delegation|1 direction 9|2 target 9|3 target_id 9|4 outcome 9|5 duration_ms 3?|6 kind 9"]}}class $c extends Va{constructor(t){super(),this.events=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $c).fromBinary(t,r)}static fromJson(t,r){return(new $c).fromJson(t,r)}static fromJsonString(t,r){return(new $c).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals($c,t,r)}static $(){return["RecordSandAuditEventsRequest|1 events #0*",Bc]}}class Mc extends Va{constructor(t){super(),this.recordedCount=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mc).fromBinary(t,r)}static fromJson(t,r){return(new Mc).fromJson(t,r)}static fromJsonString(t,r){return(new Mc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Mc,t,r)}static $(){return["RecordSandAuditEventsResponse|1 recorded_count 5"]}}class Oc extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Oc).fromBinary(t,r)}static fromJson(t,r){return(new Oc).fromJson(t,r)}static fromJsonString(t,r){return(new Oc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Oc,t,r)}static $(){return["SandShareBotExportSettings|1 policy 9?"]}}class Dc extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dc).fromBinary(t,r)}static fromJson(t,r){return(new Dc).fromJson(t,r)}static fromJsonString(t,r){return(new Dc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Dc,t,r)}static $(){return["GetTeamSandShareBotExportSettingsRequest|1 team_id 5"]}}class Nc extends Va{constructor(t){super(),this.effectivePolicy="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nc).fromBinary(t,r)}static fromJson(t,r){return(new Nc).fromJson(t,r)}static fromJsonString(t,r){return(new Nc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Nc,t,r)}static $(){return["GetTeamSandShareBotExportSettingsResponse|1 settings #0|2 effective_policy 9",Oc]}}class Gc extends Va{constructor(t){super(),this.teamId=0,this.policy="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gc).fromBinary(t,r)}static fromJson(t,r){return(new Gc).fromJson(t,r)}static fromJsonString(t,r){return(new Gc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Gc,t,r)}static $(){return["UpdateTeamSandShareBotExportSettingsRequest|1 team_id 5|2 policy 9"]}}class Lc extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lc).fromBinary(t,r)}static fromJson(t,r){return(new Lc).fromJson(t,r)}static fromJsonString(t,r){return(new Lc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Lc,t,r)}static $(){return["UpdateTeamSandShareBotExportSettingsResponse"]}}class Fc extends Va{constructor(t){super(),this.allowInstructions=[],this.blockInstructions=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fc).fromBinary(t,r)}static fromJson(t,r){return(new Fc).fromJson(t,r)}static fromJsonString(t,r){return(new Fc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Fc,t,r)}static $(){return["GrokBotAutoReviewRules|1 allow_instructions 9*|2 block_instructions 9*"]}}class Kc extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kc).fromBinary(t,r)}static fromJson(t,r){return(new Kc).fromJson(t,r)}static fromJsonString(t,r){return(new Kc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Kc,t,r)}static $(){return["UpdateTeamGrokBotCapabilitiesRequest|1 team_id 5|2 action_recording 8?|3 enforce_auto_review 8?|4 auto_review_rules #0|5 local_execution_ceiling #1?|6 local_egress_allowed 8?|7 agent_email_allowed 8?|8 box_sudo_disallowed 8?|24 box_vnc_disallowed 8?|9 cloud_agent_secret_forwarding_allowed 8?|10 meetings_allowed 8?|11 pages_team_sharing_allowed 8?|12 bot_messaging_allowed 8?|13 pages_team_sharing_level #2?|14 connector_writes_need_approval 8?|15 connector_write_trust #3|16 team_bot_sharing #4?|17 delegated_auth_allowed 8?|18 texting_allowed 8?|19 wall_snapshots_allowed 8?|20 local_execution_controls #5|21 local_egress_mode #6?|22 proactivity_allowed 8?|23 designated_bot_sharers #7",Fc,n.odJ,n.wfI,jc,n.Rq9,n.WEP,n.SDZ,zc]}}class zc extends Va{constructor(t){super(),this.userIds=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zc).fromBinary(t,r)}static fromJson(t,r){return(new zc).fromJson(t,r)}static fromJsonString(t,r){return(new zc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(zc,t,r)}static $(){return["GrokBotDesignatedBotSharers|1 user_ids 3*"]}}class jc extends Va{constructor(t){super(),this.serverUrl="",this.trusted=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jc).fromBinary(t,r)}static fromJson(t,r){return(new jc).fromJson(t,r)}static fromJsonString(t,r){return(new jc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(jc,t,r)}static $(){return["GrokBotConnectorWriteTrust|1 server_url 9|2 trusted 8"]}}class Hc extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hc).fromBinary(t,r)}static fromJson(t,r){return(new Hc).fromJson(t,r)}static fromJsonString(t,r){return(new Hc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Hc,t,r)}static $(){return["UpdateTeamGrokBotCapabilitiesResponse"]}}class Wc extends Va{constructor(t){super(),this.kind={case:void 0},s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wc).fromBinary(t,r)}static fromJson(t,r){return(new Wc).fromJson(t,r)}static fromJsonString(t,r){return(new Wc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Wc,t,r)}static $(){return["GrokBotConnectorAudience|1 everyone #0 kind|2 members #1 kind",Qc,Vc]}}class Qc extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qc).fromBinary(t,r)}static fromJson(t,r){return(new Qc).fromJson(t,r)}static fromJsonString(t,r){return(new Qc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Qc,t,r)}static $(){return["GrokBotConnectorAudience.Everyone"]}}class Vc extends Va{constructor(t){super(),this.emails=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vc).fromBinary(t,r)}static fromJson(t,r){return(new Vc).fromJson(t,r)}static fromJsonString(t,r){return(new Vc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Vc,t,r)}static $(){return["GrokBotConnectorAudience.Members|1 emails 9*"]}}class Xc extends Va{constructor(t){super(),this.connectorName="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xc).fromBinary(t,r)}static fromJson(t,r){return(new Xc).fromJson(t,r)}static fromJsonString(t,r){return(new Xc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Xc,t,r)}static $(){return["GrokBotConnectorAudienceEntry|1 connector_name 9|2 audience #0",Wc]}}class Yc extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yc).fromBinary(t,r)}static fromJson(t,r){return(new Yc).fromJson(t,r)}static fromJsonString(t,r){return(new Yc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Yc,t,r)}static $(){return["GetTeamGrokBotConnectorAudiencesRequest|1 team_id 5"]}}class Zc extends Va{constructor(t){super(),this.connectors=[],this.adminControlsAvailable=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zc).fromBinary(t,r)}static fromJson(t,r){return(new Zc).fromJson(t,r)}static fromJsonString(t,r){return(new Zc).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Zc,t,r)}static $(){return["GetTeamGrokBotConnectorAudiencesResponse|1 connectors #0*|2 admin_controls_available 8",Xc]}}class tl extends Va{constructor(t){super(),this.teamId=0,this.connectorName="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tl).fromBinary(t,r)}static fromJson(t,r){return(new tl).fromJson(t,r)}static fromJsonString(t,r){return(new tl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(tl,t,r)}static $(){return["UpdateTeamGrokBotConnectorAudienceRequest|1 team_id 5|2 connector_name 9|3 audience #0",Wc]}}class rl extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rl).fromBinary(t,r)}static fromJson(t,r){return(new rl).fromJson(t,r)}static fromJsonString(t,r){return(new rl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(rl,t,r)}static $(){return["UpdateTeamGrokBotConnectorAudienceResponse"]}}class el extends Va{constructor(t){super(),this.allTeam=!1,this.groupIds=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new el).fromBinary(t,r)}static fromJson(t,r){return(new el).fromJson(t,r)}static fromJsonString(t,r){return(new el).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(el,t,r)}static $(){return["TeamGrokBotDefaultAudience|1 all_team 8|2 group_ids 3*"]}}class nl extends Va{constructor(t){super(),this.agentId="",this.name="",this.description="",this.avatarShape="",this.avatarColor="",this.ownerDisplayName="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nl).fromBinary(t,r)}static fromJson(t,r){return(new nl).fromJson(t,r)}static fromJsonString(t,r){return(new nl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(nl,t,r)}static $(){return["TeamGrokBotDefaultAgent|1 agent_id 9|2 name 9|3 description 9|4 avatar_url 9?|5 avatar_shape 9|6 avatar_color 9|7 owner_display_name 9|8 audience #0",el]}}class sl extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sl).fromBinary(t,r)}static fromJson(t,r){return(new sl).fromJson(t,r)}static fromJsonString(t,r){return(new sl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(sl,t,r)}static $(){return["GetTeamGrokBotSlackWorkspaceAccessRequest|1 team_id 5"]}}class il extends Va{constructor(t){super(),this.allowed=!1,this.scope=ru.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new il).fromBinary(t,r)}static fromJson(t,r){return(new il).fromJson(t,r)}static fromJsonString(t,r){return(new il).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(il,t,r)}static $(){return["GetTeamGrokBotSlackWorkspaceAccessResponse|1 allowed 8|2 scope #0",ru]}}class ol extends Va{constructor(t){super(),this.teamId=0,this.allowed=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ol).fromBinary(t,r)}static fromJson(t,r){return(new ol).fromJson(t,r)}static fromJsonString(t,r){return(new ol).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ol,t,r)}static $(){return["SetTeamGrokBotSlackWorkspaceAccessRequest|1 team_id 5|2 allowed 8"]}}class al extends Va{constructor(t){super(),this.allowed=!1,this.scope=ru.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new al).fromBinary(t,r)}static fromJson(t,r){return(new al).fromJson(t,r)}static fromJsonString(t,r){return(new al).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(al,t,r)}static $(){return["SetTeamGrokBotSlackWorkspaceAccessResponse|1 allowed 8|2 scope #0",ru]}}class ul extends Va{constructor(t){super(),this.teamId=0,this.pageToken="",this.query="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ul).fromBinary(t,r)}static fromJson(t,r){return(new ul).fromJson(t,r)}static fromJsonString(t,r){return(new ul).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ul,t,r)}static $(){return["ListTeamGrokBotDefaultAgentsRequest|1 team_id 5|2 page_size 5?|3 page_token 9|4 query 9"]}}class cl extends Va{constructor(t){super(),this.agents=[],this.nextPageToken="",this.enabled=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cl).fromBinary(t,r)}static fromJson(t,r){return(new cl).fromJson(t,r)}static fromJsonString(t,r){return(new cl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(cl,t,r)}static $(){return["ListTeamGrokBotDefaultAgentsResponse|1 agents #0*|2 next_page_token 9|3 enabled 8",nl]}}class ll extends Va{constructor(t){super(),this.teamId=0,this.agentId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ll).fromBinary(t,r)}static fromJson(t,r){return(new ll).fromJson(t,r)}static fromJsonString(t,r){return(new ll).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ll,t,r)}static $(){return["SetTeamGrokBotDefaultAudienceRequest|1 team_id 5|2 agent_id 9|3 audience #0",el]}}class ml extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ml).fromBinary(t,r)}static fromJson(t,r){return(new ml).fromJson(t,r)}static fromJsonString(t,r){return(new ml).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ml,t,r)}static $(){return["SetTeamGrokBotDefaultAudienceResponse|1 audience #0",el]}}class fl extends Va{constructor(t){super(),this.teamId=0,this.agentId="",this.teamApproved=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fl).fromBinary(t,r)}static fromJson(t,r){return(new fl).fromJson(t,r)}static fromJsonString(t,r){return(new fl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(fl,t,r)}static $(){return["SetTeamGrokBotAgentTeamApprovedRequest|1 team_id 5|2 agent_id 9|3 team_approved 8"]}}class dl extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dl).fromBinary(t,r)}static fromJson(t,r){return(new dl).fromJson(t,r)}static fromJsonString(t,r){return(new dl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(dl,t,r)}static $(){return["SetTeamGrokBotAgentTeamApprovedResponse|1 team_approved_at #0",s.Timestamp]}}class pl extends Va{constructor(t){super(),this.agentId="",this.creatorUserId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pl).fromBinary(t,r)}static fromJson(t,r){return(new pl).fromJson(t,r)}static fromJsonString(t,r){return(new pl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(pl,t,r)}static $(){return["TeamGrokBotAgentAccess|1 agent_id 9|2 state #0|3 creator_user_id 5",wa]}}class hl extends Va{constructor(t){super(),this.teamId=0,this.agentIds=[],this.listsCrossTierPrincipals=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hl).fromBinary(t,r)}static fromJson(t,r){return(new hl).fromJson(t,r)}static fromJsonString(t,r){return(new hl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(hl,t,r)}static $(){return["ListTeamGrokBotAgentAccessRequest|1 team_id 5|2 agent_ids 9*|3 lists_cross_tier_principals 8"]}}class gl extends Va{constructor(t){super(),this.agents=[],this.enabled=!1,this.settingUpAgentIds=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gl).fromBinary(t,r)}static fromJson(t,r){return(new gl).fromJson(t,r)}static fromJsonString(t,r){return(new gl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(gl,t,r)}static $(){return["ListTeamGrokBotAgentAccessResponse|1 agents #0*|2 enabled 8|3 setting_up_agent_ids 9*",pl]}}class _l extends Va{constructor(t){super(),this.teamId=0,this.agentId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _l).fromBinary(t,r)}static fromJson(t,r){return(new _l).fromJson(t,r)}static fromJsonString(t,r){return(new _l).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(_l,t,r)}static $(){return["SetTeamGrokBotAgentAccessRequest|1 team_id 5|2 agent_id 9|3 update #0",ya]}}class Jl extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jl).fromBinary(t,r)}static fromJson(t,r){return(new Jl).fromJson(t,r)}static fromJsonString(t,r){return(new Jl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Jl,t,r)}static $(){return["SetTeamGrokBotAgentAccessResponse|1 access #0",pl]}}class wl extends Va{constructor(t){super(),this.teamId=0,this.name="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wl).fromBinary(t,r)}static fromJson(t,r){return(new wl).fromJson(t,r)}static fromJsonString(t,r){return(new wl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(wl,t,r)}static $(){return["TeamGrokBotAccessTeam|1 team_id 5|2 name 9|3 icon_url 9?"]}}class yl extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yl).fromBinary(t,r)}static fromJson(t,r){return(new yl).fromJson(t,r)}static fromJsonString(t,r){return(new yl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(yl,t,r)}static $(){return["ListTeamGrokBotAccessTeamsRequest|1 team_id 5"]}}class Sl extends Va{constructor(t){super(),this.enabled=!1,this.organizationName="",this.teams=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sl).fromBinary(t,r)}static fromJson(t,r){return(new Sl).fromJson(t,r)}static fromJsonString(t,r){return(new Sl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Sl,t,r)}static $(){return["ListTeamGrokBotAccessTeamsResponse|1 enabled 8|2 organization_name 9|3 teams #0*",wl]}}class ql extends Va{constructor(t){super(),this.teamId=0,this.agentIds=[],this.destinationTeamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ql).fromBinary(t,r)}static fromJson(t,r){return(new ql).fromJson(t,r)}static fromJsonString(t,r){return(new ql).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ql,t,r)}static $(){return["PreviewTeamGrokBotAgentTransferRequest|1 team_id 5|2 agent_ids 9*|3 destination_team_id 5"]}}class Bl extends Va{constructor(t){super(),this.items=[],this.enabled=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bl).fromBinary(t,r)}static fromJson(t,r){return(new Bl).fromJson(t,r)}static fromJsonString(t,r){return(new Bl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Bl,t,r)}static $(){return["PreviewTeamGrokBotAgentTransferResponse|1 items #0*|2 enabled 8",Fa]}}class Il extends Va{constructor(t){super(),this.teamId=0,this.items=[],this.destinationTeamId=0,this.idempotencyKey="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Il).fromBinary(t,r)}static fromJson(t,r){return(new Il).fromJson(t,r)}static fromJsonString(t,r){return(new Il).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Il,t,r)}static $(){return["TransferTeamGrokBotAgentsRequest|1 team_id 5|2 items #0*|3 destination_team_id 5|4 idempotency_key 9",Ka]}}class Pl extends Va{constructor(t){super(),this.items=[],this.bulkOperationId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pl).fromBinary(t,r)}static fromJson(t,r){return(new Pl).fromJson(t,r)}static fromJsonString(t,r){return(new Pl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Pl,t,r)}static $(){return["TransferTeamGrokBotAgentsResponse|1 items #0*|2 bulk_operation_id 9",za]}}class bl extends Va{constructor(t){super(),this.teamId=0,this.transferIds=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bl).fromBinary(t,r)}static fromJson(t,r){return(new bl).fromJson(t,r)}static fromJsonString(t,r){return(new bl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(bl,t,r)}static $(){return["GetTeamGrokBotAgentTransfersRequest|1 team_id 5|2 transfer_ids 9*"]}}class Rl extends Va{constructor(t){super(),this.transfers=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rl).fromBinary(t,r)}static fromJson(t,r){return(new Rl).fromJson(t,r)}static fromJsonString(t,r){return(new Rl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Rl,t,r)}static $(){return["GetTeamGrokBotAgentTransfersResponse|1 transfers #0*",ja]}}class vl extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vl).fromBinary(t,r)}static fromJson(t,r){return(new vl).fromJson(t,r)}static fromJsonString(t,r){return(new vl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(vl,t,r)}static $(){return["ListTeamGrokBotTransferDestinationsRequest|1 team_id 5"]}}class xl extends Va{constructor(t){super(),this.destinations=[],this.enabled=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xl).fromBinary(t,r)}static fromJson(t,r){return(new xl).fromJson(t,r)}static fromJsonString(t,r){return(new xl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(xl,t,r)}static $(){return["ListTeamGrokBotTransferDestinationsResponse|1 destinations #0*|2 enabled 8",Ha]}}class kl extends Va{constructor(t){super(),this.teamId=0,this.agentId="",this.newOwnerUserId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kl).fromBinary(t,r)}static fromJson(t,r){return(new kl).fromJson(t,r)}static fromJsonString(t,r){return(new kl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(kl,t,r)}static $(){return["StartTeamGrokBotOwnershipTransferRequest|1 team_id 5|2 agent_id 9|3 new_owner_user_id 5"]}}class El extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new El).fromBinary(t,r)}static fromJson(t,r){return(new El).fromJson(t,r)}static fromJsonString(t,r){return(new El).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(El,t,r)}static $(){return["StartTeamGrokBotOwnershipTransferResponse"]}}class Cl extends Va{constructor(t){super(),this.teamId=0,this.completed=!1,this.source=nu.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cl).fromBinary(t,r)}static fromJson(t,r){return(new Cl).fromJson(t,r)}static fromJsonString(t,r){return(new Cl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Cl,t,r)}static $(){return["UpdateTeamSandOnboardingCompletedRequest|1 team_id 5|2 completed 8|3 source #0",nu]}}class Tl extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tl).fromBinary(t,r)}static fromJson(t,r){return(new Tl).fromJson(t,r)}static fromJsonString(t,r){return(new Tl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Tl,t,r)}static $(){return["UpdateTeamSandOnboardingCompletedResponse"]}}class Ul extends Va{constructor(t){super(),this.teamId=0,this.itemId="",this.state=eu.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ul).fromBinary(t,r)}static fromJson(t,r){return(new Ul).fromJson(t,r)}static fromJsonString(t,r){return(new Ul).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ul,t,r)}static $(){return["UpdateTeamSandSetupChecklistItemRequest|1 team_id 5|2 item_id 9|3 state #0",eu]}}class Al extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Al).fromBinary(t,r)}static fromJson(t,r){return(new Al).fromJson(t,r)}static fromJsonString(t,r){return(new Al).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Al,t,r)}static $(){return["UpdateTeamSandSetupChecklistItemResponse"]}}class $l extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $l).fromBinary(t,r)}static fromJson(t,r){return(new $l).fromJson(t,r)}static fromJsonString(t,r){return(new $l).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals($l,t,r)}static $(){return["MarkTeamSandOnboardingSeenRequest|1 team_id 5"]}}class Ml extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ml).fromBinary(t,r)}static fromJson(t,r){return(new Ml).fromJson(t,r)}static fromJsonString(t,r){return(new Ml).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ml,t,r)}static $(){return["MarkTeamSandOnboardingSeenResponse"]}}class Ol extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ol).fromBinary(t,r)}static fromJson(t,r){return(new Ol).fromJson(t,r)}static fromJsonString(t,r){return(new Ol).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ol,t,r)}static $(){return["GetTeamGrokBotEligibleUserIdsRequest|1 team_id 5"]}}class Dl extends Va{constructor(t){super(),this.userIds=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dl).fromBinary(t,r)}static fromJson(t,r){return(new Dl).fromJson(t,r)}static fromJsonString(t,r){return(new Dl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Dl,t,r)}static $(){return["GetTeamGrokBotEligibleUserIdsResponse|1 user_ids 5*"]}}class Nl extends Va{constructor(t){super(),this.teamId=0,this.userIds=[],this.groupPublicIds=[],this.directoryGroupIds=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nl).fromBinary(t,r)}static fromJson(t,r){return(new Nl).fromJson(t,r)}static fromJsonString(t,r){return(new Nl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Nl,t,r)}static $(){return["SendTeamSandOnboardingInvitesRequest|1 team_id 5|2 user_ids 5*|3 group_public_ids 9*|4 directory_group_ids 5*"]}}class Gl extends Va{constructor(t){super(),this.sentCount=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gl).fromBinary(t,r)}static fromJson(t,r){return(new Gl).fromJson(t,r)}static fromJsonString(t,r){return(new Gl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Gl,t,r)}static $(){return["SendTeamSandOnboardingInvitesResponse|1 sent_count 5"]}}class Ll extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ll).fromBinary(t,r)}static fromJson(t,r){return(new Ll).fromJson(t,r)}static fromJsonString(t,r){return(new Ll).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ll,t,r)}static $(){return["GetEnterpriseGrokBotTeamTrialInternalRequest|1 team_id 5"]}}class Fl extends Va{constructor(t){super(),this.trialTeam=!1,this.live=!1,this.grantCount=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fl).fromBinary(t,r)}static fromJson(t,r){return(new Fl).fromJson(t,r)}static fromJsonString(t,r){return(new Fl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Fl,t,r)}static $(){return["GetEnterpriseGrokBotTeamTrialInternalResponse|1 trial_team 8|2 eligible_at #0?|3 expires_at #0?|4 revoked_at #0?|5 live 8|6 grant_count 5",s.Timestamp]}}class Kl extends Va{constructor(t){super(),this.teamId=0,this.requestedBy="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kl).fromBinary(t,r)}static fromJson(t,r){return(new Kl).fromJson(t,r)}static fromJsonString(t,r){return(new Kl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Kl,t,r)}static $(){return["SetEnterpriseGrokBotTeamTrialExpirationInternalRequest|1 team_id 5|2 expires_at #0|3 requested_by 9",s.Timestamp]}}class zl extends Va{constructor(t){super(),this.grantsUpdated=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zl).fromBinary(t,r)}static fromJson(t,r){return(new zl).fromJson(t,r)}static fromJsonString(t,r){return(new zl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(zl,t,r)}static $(){return["SetEnterpriseGrokBotTeamTrialExpirationInternalResponse|1 expires_at #0|2 grants_updated 5",s.Timestamp]}}class jl extends Va{constructor(t){super(),this.expectedCurrentPeriodStartMs=s.protoInt64.zero,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jl).fromBinary(t,r)}static fromJson(t,r){return(new jl).fromJson(t,r)}static fromJsonString(t,r){return(new jl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(jl,t,r)}static $(){return["UseSandBankedResetRequest|1 expected_current_period_start_ms 3"]}}class Hl extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hl).fromBinary(t,r)}static fromJson(t,r){return(new Hl).fromJson(t,r)}static fromJsonString(t,r){return(new Hl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Hl,t,r)}static $(){return["UseSandBankedResetResponse|1 new_current_period_start #0",s.Timestamp]}}class Wl extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wl).fromBinary(t,r)}static fromJson(t,r){return(new Wl).fromJson(t,r)}static fromJsonString(t,r){return(new Wl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Wl,t,r)}static $(){return["ListSandBankedResetsRequest"]}}class Ql extends Va{constructor(t){super(),this.id=s.protoInt64.zero,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ql).fromBinary(t,r)}static fromJson(t,r){return(new Ql).fromJson(t,r)}static fromJsonString(t,r){return(new Ql).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ql,t,r)}static $(){return["SandBankedReset|1 id 3|2 created_at #0|3 expires_at #0?",s.Timestamp]}}class Vl extends Va{constructor(t){super(),this.resets=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vl).fromBinary(t,r)}static fromJson(t,r){return(new Vl).fromJson(t,r)}static fromJsonString(t,r){return(new Vl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Vl,t,r)}static $(){return["ListSandBankedResetsResponse|1 resets #0*",Ql]}}class Xl extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xl).fromBinary(t,r)}static fromJson(t,r){return(new Xl).fromJson(t,r)}static fromJsonString(t,r){return(new Xl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Xl,t,r)}static $(){return["GetSandAccessStatusRequest"]}}class Yl extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yl).fromBinary(t,r)}static fromJson(t,r){return(new Yl).fromJson(t,r)}static fromJsonString(t,r){return(new Yl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Yl,t,r)}static $(){return["ShouldShowGrokBotTrainingOptInPopupRequest"]}}class Zl extends Va{constructor(t){super(),this.show=!1,this.promptSeen=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zl).fromBinary(t,r)}static fromJson(t,r){return(new Zl).fromJson(t,r)}static fromJsonString(t,r){return(new Zl).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Zl,t,r)}static $(){return["ShouldShowGrokBotTrainingOptInPopupResponse|1 show 8|2 upgrade_option #0?|3 prompt_seen 8",tm]}}class tm extends Va{constructor(t){super(),this.show=!1,this.reason=rm.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tm).fromBinary(t,r)}static fromJson(t,r){return(new tm).fromJson(t,r)}static fromJsonString(t,r){return(new tm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(tm,t,r)}static $(){return["SandUpgradeOption|1 show 8|2 reason #0",rm]}}var rm=(0,i.QT)(s.proto3,Qa,"SandUpgradeOption.Reason",[[0,"UNSPECIFIED"],[1,"AVAILABLE"],[2,"TOP_TIER"],[3,"TEAM_MANAGED"],[4,"NO_UPGRADE_PATH"],[5,"UNKNOWN"]],1);class em extends Va{constructor(t){super(),this.kind=nm.UNSPECIFIED,this.planName="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new em).fromBinary(t,r)}static fromJson(t,r){return(new em).fromJson(t,r)}static fromJsonString(t,r){return(new em).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(em,t,r)}static $(){return["SandUpgradeOffer|1 kind #0|2 plan_name 9|3 percent_off 5?|4 redeem_by_ms 3?|5 currency_code 9?|6 pay_upfront #1?",nm,sm]}}var nm=(0,i.QT)(s.proto3,Qa,"SandUpgradeOffer.Kind",[[0,"UNSPECIFIED"],[1,"FREE_TRIAL"],[2,"PAY_UPFRONT"],[3,"DISCOUNT"]],1);class sm extends Va{constructor(t){super(),this.period=im.UNSPECIFIED,this.periodsCovered=0,this.amountMicros=s.protoInt64.zero,this.listPriceMicros=s.protoInt64.zero,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sm).fromBinary(t,r)}static fromJson(t,r){return(new sm).fromJson(t,r)}static fromJsonString(t,r){return(new sm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(sm,t,r)}static $(){return["SandUpgradeOffer.PayUpfront|1 period #0|2 periods_covered 5|3 amount_micros 3|4 list_price_micros 3|5 periods_paid 5?",im]}}var im=(0,i.QT)(s.proto3,Qa,"SandUpgradeOffer.PayUpfront.Period",[[0,"UNSPECIFIED"],[1,"MONTH"],[2,"YEAR"]],1);class om extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new om).fromBinary(t,r)}static fromJson(t,r){return(new om).fromJson(t,r)}static fromJsonString(t,r){return(new om).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(om,t,r)}static $(){return["GetSandUpgradeOfferRequest"]}}class am extends Va{constructor(t){super(),this.readFailed=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new am).fromBinary(t,r)}static fromJson(t,r){return(new am).fromJson(t,r)}static fromJsonString(t,r){return(new am).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(am,t,r)}static $(){return["GetSandUpgradeOfferResponse|1 offer #0|2 read_failed 8",em]}}class um extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new um).fromBinary(t,r)}static fromJson(t,r){return(new um).fromJson(t,r)}static fromJsonString(t,r){return(new um).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(um,t,r)}static $(){return["MarkGrokBotTrainingOptInPromptSeenRequest"]}}class cm extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cm).fromBinary(t,r)}static fromJson(t,r){return(new cm).fromJson(t,r)}static fromJsonString(t,r){return(new cm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(cm,t,r)}static $(){return["MarkGrokBotTrainingOptInPromptSeenResponse"]}}class lm extends Va{constructor(t){super(),this.amountCents=0,this.grantTtlDays=0,this.challenge="",this.platform="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lm).fromBinary(t,r)}static fromJson(t,r){return(new lm).fromJson(t,r)}static fromJsonString(t,r){return(new lm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(lm,t,r)}static $(){return["AttestedTrialOffer|1 amount_cents 5|2 grant_ttl_days 5|3 challenge 9|4 platform 9"]}}class mm extends Va{constructor(t){super(),this.state=fm.UNSPECIFIED,this.purchaseChannel=dm.UNSPECIFIED,this.blockReason=pm.UNSPECIFIED,this.purchasableTiers=[],this.unpaidAdminNeedsPaidSeat=!1,this.privacyDisclaimerRequired=!1,this.canSkipOnboarding=!1,this.proAndSuperGrokPlansGrantAccess=!1,this.isUnified=!1,this.billingBrand=su.UNSPECIFIED,this.speechUiHidden=!1,this.grokConnectorsOnly=!1,this.grokConnectorsOnlyAllows=[],this.grokConnectorsOnlyBuiltinEntries=[],this.grokConnectorsOnlyTeamPlugins=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mm).fromBinary(t,r)}static fromJson(t,r){return(new mm).fromJson(t,r)}static fromJsonString(t,r){return(new mm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(mm,t,r)}static $(){return["GetSandAccessStatusResponse|1 state #0|2 purchase_channel #1|3 block_reason #2|4 purchasable_tiers 9*|6 is_paid_trial_plan 8?|7 unpaid_admin_needs_paid_seat 8|9 privacy_disclaimer_required 8|10 can_skip_onboarding 8|11 pro_and_super_grok_plans_grant_access 8|12 is_unified 8|13 billing_brand #3|14 attested_trial_offer #4|15 unified_access_paywall #5|16 unified_trial_plans_offer #6|17 super_grok_heavy_ultra_ended_notice #7|18 speech_ui_hidden 8|19 post_sign_in_step #8|20 grok_connectors_only 8|21 account_merge_prompt #9|22 grok_connectors_only_allows 9*|23 grok_connectors_only_builtin_entries #10*|24 grok_connectors_only_team_plugins 8",fm,dm,pm,su,lm,Jm,wm,n.qKw,_m,gm,hm]}}var fm=(0,i.QT)(s.proto3,Qa,"GetSandAccessStatusResponse.SandAccessState",[[0,"UNSPECIFIED"],[1,"GRANTED"],[2,"UNAVAILABLE"],[3,"PAYMENT_REQUIRED"]],1),dm=(0,i.QT)(s.proto3,Qa,"GetSandAccessStatusResponse.SandPurchaseChannel",[[0,"UNSPECIFIED"],[1,"IN_APP"],[2,"MANAGE_IN_CURSOR"],[3,"MANAGE_ON_WEB"]],1),pm=(0,i.QT)(s.proto3,Qa,"GetSandAccessStatusResponse.SandAccessBlockReason",[[0,"UNSPECIFIED"],[1,"NONE"],[2,"TEAM_PRIVACY_MODE"],[3,"TEAM_SETUP_REQUIRED"],[4,"TEAM_ACCESS_REQUIRED"],[5,"NOT_OFFERED"],[6,"FREE_TRIAL_AVAILABLE"],[7,"PAYWALL_INDIVIDUAL"],[8,"PAYWALL_TEAM_MEMBER"],[9,"PAYWALL_TEAM_ADMIN"],[10,"UNDER_MINIMUM_AGE"]],1);class hm extends Va{constructor(t){super(),this.serverIdentifier="",this.displayName="",this.description="",this.categoryKey="",this.websiteUrl="",this.supersedesMarketplacePluginNames=[],this.iconUrl="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hm).fromBinary(t,r)}static fromJson(t,r){return(new hm).fromJson(t,r)}static fromJsonString(t,r){return(new hm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(hm,t,r)}static $(){return["SandBuiltinCatalogEntry|1 server_identifier 9|2 display_name 9|3 description 9|4 category_key 9|5 website_url 9|6 supersedes_marketplace_plugin_names 9*|7 icon_url 9"]}}class gm extends Va{constructor(t){super(),this.title="",this.body="",this.actionLabel="",this.href="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gm).fromBinary(t,r)}static fromJson(t,r){return(new gm).fromJson(t,r)}static fromJsonString(t,r){return(new gm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(gm,t,r)}static $(){return["SandAccountMergePrompt|1 title 9|2 body 9|3 action_label 9|4 href 9"]}}class _m extends Va{constructor(t){super(),this.path="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _m).fromBinary(t,r)}static fromJson(t,r){return(new _m).fromJson(t,r)}static fromJsonString(t,r){return(new _m).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(_m,t,r)}static $(){return["SandPostSignInStep|1 path 9"]}}class Jm extends Va{constructor(t){super(),this.title="",this.body="",this.actionLabel="",this.href="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jm).fromBinary(t,r)}static fromJson(t,r){return(new Jm).fromJson(t,r)}static fromJsonString(t,r){return(new Jm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Jm,t,r)}static $(){return["SandUnifiedAccessPaywall|1 title 9|2 body 9|3 action_label 9|4 href 9"]}}class wm extends Va{constructor(t){super(),this.title="",this.price="",this.features=[],this.actionLabel="",this.href="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wm).fromBinary(t,r)}static fromJson(t,r){return(new wm).fromJson(t,r)}static fromJsonString(t,r){return(new wm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(wm,t,r)}static $(){return["SandUnifiedTrialPlansOffer|1 title 9|2 price 9|3 features 9*|4 action_label 9|5 href 9|6 action #0?",Wa.bV]}}class ym extends Va{constructor(t){super(),this.toolId="",this.state="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ym).fromBinary(t,r)}static fromJson(t,r){return(new ym).fromJson(t,r)}static fromJsonString(t,r){return(new ym).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ym,t,r)}static $(){return["SandMachineLocalTool|1 tool_id 9|2 state 9"]}}class Sm extends Va{constructor(t){super(),this.label="",this.kind="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sm).fromBinary(t,r)}static fromJson(t,r){return(new Sm).fromJson(t,r)}static fromJsonString(t,r){return(new Sm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Sm,t,r)}static $(){return["RegisterSandMachineRequest|1 label 9|2 local_tool_permission 9?|3 messages_enabled 8?|4 kind 9"]}}class qm extends Va{constructor(t){super(),this.credential="",this.expiresAtMs=s.protoInt64.zero,this.credentialHeld=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qm).fromBinary(t,r)}static fromJson(t,r){return(new qm).fromJson(t,r)}static fromJsonString(t,r){return(new qm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(qm,t,r)}static $(){return["RegisterSandMachineResponse|1 credential 9|2 expires_at_ms 3|3 credential_held 8"]}}class Bm extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bm).fromBinary(t,r)}static fromJson(t,r){return(new Bm).fromJson(t,r)}static fromJsonString(t,r){return(new Bm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Bm,t,r)}static $(){return["ListSandMachinesRequest"]}}class Im extends Va{constructor(t){super(),this.machineId="",this.label="",this.messagesEnabled=!1,this.kind="",this.connected=!1,this.lastRegisteredAtMs=s.protoInt64.zero,this.mobileLocalTools=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Im).fromBinary(t,r)}static fromJson(t,r){return(new Im).fromJson(t,r)}static fromJsonString(t,r){return(new Im).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Im,t,r)}static $(){return["SandMachine|1 machine_id 9|2 label 9|3 local_tool_permission 9?|4 messages_enabled 8|5 kind 9|6 connected 8|7 last_heartbeat_at_ms 3?|8 last_registered_at_ms 3|9 mobile_local_tools #0*",ym]}}class Pm extends Va{constructor(t){super(),this.machines=[],this.currentMachineRemoved=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pm).fromBinary(t,r)}static fromJson(t,r){return(new Pm).fromJson(t,r)}static fromJsonString(t,r){return(new Pm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Pm,t,r)}static $(){return["ListSandMachinesResponse|1 machines #0*|2 current_machine_removed 8",Im]}}class bm extends Va{constructor(t){super(),this.machineId="",this.label="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bm).fromBinary(t,r)}static fromJson(t,r){return(new bm).fromJson(t,r)}static fromJsonString(t,r){return(new bm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(bm,t,r)}static $(){return["UpdateSandMachineLabelRequest|1 machine_id 9|2 label 9"]}}class Rm extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rm).fromBinary(t,r)}static fromJson(t,r){return(new Rm).fromJson(t,r)}static fromJsonString(t,r){return(new Rm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Rm,t,r)}static $(){return["UpdateSandMachineLabelResponse|1 machine #0",Im]}}class vm extends Va{constructor(t){super(),this.machineId="",this.localToolPermission="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vm).fromBinary(t,r)}static fromJson(t,r){return(new vm).fromJson(t,r)}static fromJsonString(t,r){return(new vm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(vm,t,r)}static $(){return["UpdateSandMachineLocalToolPermissionRequest|1 machine_id 9|2 local_tool_permission 9"]}}class xm extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xm).fromBinary(t,r)}static fromJson(t,r){return(new xm).fromJson(t,r)}static fromJsonString(t,r){return(new xm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(xm,t,r)}static $(){return["UpdateSandMachineLocalToolPermissionResponse|1 machine #0",Im]}}class km extends Va{constructor(t){super(),this.machineId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new km).fromBinary(t,r)}static fromJson(t,r){return(new km).fromJson(t,r)}static fromJsonString(t,r){return(new km).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(km,t,r)}static $(){return["GetSandMachineMessagesEnabledRequest|1 machine_id 9"]}}class Em extends Va{constructor(t){super(),this.messagesEnabled=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Em).fromBinary(t,r)}static fromJson(t,r){return(new Em).fromJson(t,r)}static fromJsonString(t,r){return(new Em).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Em,t,r)}static $(){return["GetSandMachineMessagesEnabledResponse|1 messages_enabled 8"]}}class Cm extends Va{constructor(t){super(),this.machineId="",this.messagesEnabled=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cm).fromBinary(t,r)}static fromJson(t,r){return(new Cm).fromJson(t,r)}static fromJsonString(t,r){return(new Cm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Cm,t,r)}static $(){return["UpdateSandMachineMessagesEnabledRequest|1 machine_id 9|2 messages_enabled 8"]}}class Tm extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tm).fromBinary(t,r)}static fromJson(t,r){return(new Tm).fromJson(t,r)}static fromJsonString(t,r){return(new Tm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Tm,t,r)}static $(){return["UpdateSandMachineMessagesEnabledResponse|1 machine #0",Im]}}class Um extends Va{constructor(t){super(),this.agentId="",this.entryId="",this.tryAgain=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Um).fromBinary(t,r)}static fromJson(t,r){return(new Um).fromJson(t,r)}static fromJsonString(t,r){return(new Um).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Um,t,r)}static $(){return["RetrySandMessagesPermissionRequest|1 agent_id 9|2 entry_id 9|3 try_again 8"]}}class Am extends Va{constructor(t){super(),this.woken=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Am).fromBinary(t,r)}static fromJson(t,r){return(new Am).fromJson(t,r)}static fromJsonString(t,r){return(new Am).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Am,t,r)}static $(){return["RetrySandMessagesPermissionResponse|1 woken 8"]}}class $m extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $m).fromBinary(t,r)}static fromJson(t,r){return(new $m).fromJson(t,r)}static fromJsonString(t,r){return(new $m).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals($m,t,r)}static $(){return["RequestSandTeamAccessRequest|1 team_id 5"]}}class Mm extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mm).fromBinary(t,r)}static fromJson(t,r){return(new Mm).fromJson(t,r)}static fromJsonString(t,r){return(new Mm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Mm,t,r)}static $(){return["RequestSandTeamAccessResponse"]}}class Om extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Om).fromBinary(t,r)}static fromJson(t,r){return(new Om).fromJson(t,r)}static fromJsonString(t,r){return(new Om).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Om,t,r)}static $(){return["GetSandMarketingIdentityRequest"]}}class Dm extends Va{constructor(t){super(),this.xaiUserId="",this.workspace=Nm.UNSPECIFIED,this.externalId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dm).fromBinary(t,r)}static fromJson(t,r){return(new Dm).fromJson(t,r)}static fromJsonString(t,r){return(new Dm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Dm,t,r)}static $(){return["GetSandMarketingIdentityResponse|1 xai_user_id 9|2 workspace #0|3 external_id 9",Nm]}}var Nm=(0,i.QT)(s.proto3,Qa,"GetSandMarketingIdentityResponse.SandMarketingWorkspace",[[0,"UNSPECIFIED"],[1,"NONE"],[2,"LEGACY"],[3,"UNIFIED"]],1);class Gm extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gm).fromBinary(t,r)}static fromJson(t,r){return(new Gm).fromJson(t,r)}static fromJsonString(t,r){return(new Gm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Gm,t,r)}static $(){return["GetSandUsageStatusRequest"]}}class Lm extends Va{constructor(t){super(),this.origin=iu.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lm).fromBinary(t,r)}static fromJson(t,r){return(new Lm).fromJson(t,r)}static fromJsonString(t,r){return(new Lm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Lm,t,r)}static $(){return["RequestSandSeatTierUpgradeRequest|1 origin #0",iu]}}class Fm extends Va{constructor(t){super(),this.success=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fm).fromBinary(t,r)}static fromJson(t,r){return(new Fm).fromJson(t,r)}static fromJsonString(t,r){return(new Fm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Fm,t,r)}static $(){return["RequestSandSeatTierUpgradeResponse|1 success 8|2 error_message 9?"]}}class Km extends Va{constructor(t){super(),this.disabled=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Km).fromBinary(t,r)}static fromJson(t,r){return(new Km).fromJson(t,r)}static fromJsonString(t,r){return(new Km).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Km,t,r)}static $(){return["SandUpgradeRecommendation|1 cta #0|2 disabled 8|3 supporting_text 9?|4 kind 9?",Wa.Bo]}}class zm extends Va{constructor(t){super(),this.includedLimitZero=!1,this.availableBankedResetCount=s.protoInt64.zero,this.usesPooledEnterpriseAllowance=!1,this.hasAvailableUsage=!1,this.hasNonZeroIncludedLimit=!1,this.sandTrialCancelable=!1,this.upgradeRecommendations=[],this.isTeamSeat=!1,this.cursorPlanName="",this.isUnified=!1,this.billingBrand=su.UNSPECIFIED,this.unifiedUpsellButtons=[],this.accountMergePausingBots=!1,this.unifyPendingMergeUnread=!1,this.prepaidBalanceUnknown=!1,this.managedByTeamAdmin=!1,this.planUpgrades=[],this.additionalUsageLimitUnknown=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zm).fromBinary(t,r)}static fromJson(t,r){return(new zm).fromJson(t,r)}static fromJsonString(t,r){return(new zm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(zm,t,r)}static $(){return["GetSandUsageStatusResponse|1 current_period_start #0|2 next_reset_timestamp_utc #0|3 usage_percent 1?|4 included_limit_zero 8|5 available_banked_reset_count 3|6 uses_pooled_enterprise_allowance 8|7 has_available_usage 8|8 has_non_zero_included_limit 8|9 upgrade_recommendation #1?|10 sand_trial_expires_at #0?|11 sand_trial_cancelable 8|12 upgrade_recommendations #1*|13 on_demand_settings #2?|14 included_usage_super_grok_plan 9?|15 grok_plan_label 9?|16 is_team_seat 8|17 cursor_plan_name 9|18 is_unified 8|19 billing_brand #3|20 unified_plan_migration #4?|21 unified_billing_url 9?|22 unified_upsell_buttons #5*|23 unify_pending_merge #6?|24 account_merge_pausing_bots 8|25 unify_pending_merge_unread 8|26 next_banked_reset_redeem_at #0?|27 upgrade_option #7?|28 prepaid_available_cents 3?|29 prepaid_balance_unknown 8|30 managed_by_team_admin 8|32 would_refuse_send 8?|31 plan_upgrades #8*|40 additional_usage_limit #9?|41 additional_usage_limit_unknown 8",s.Timestamp,Km,af,su,of,Wa.Bo,p,tm,Wm,jm]}}class jm extends Va{constructor(t){super(),this.state=Hm.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jm).fromBinary(t,r)}static fromJson(t,r){return(new jm).fromJson(t,r)}static fromJsonString(t,r){return(new jm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(jm,t,r)}static $(){return["SandAdditionalUsageLimit|1 state #0|2 limit_cents 3?|3 spent_cents 3?|4 resets_at #1",Hm,s.Timestamp]}}var Hm=(0,i.QT)(s.proto3,Qa,"SandAdditionalUsageLimit.State",[[0,"UNSPECIFIED"],[1,"NONE"],[2,"OFF"],[3,"LIMITED"]],1);class Wm extends Va{constructor(t){super(),this.planName="",this.planId="",this.url="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wm).fromBinary(t,r)}static fromJson(t,r){return(new Wm).fromJson(t,r)}static fromJsonString(t,r){return(new Wm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Wm,t,r)}static $(){return["SandPlanUpgrade|1 plan_name 9|2 plan_id 9|3 url 9"]}}class Qm extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qm).fromBinary(t,r)}static fromJson(t,r){return(new Qm).fromJson(t,r)}static fromJsonString(t,r){return(new Qm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Qm,t,r)}static $(){return["GetGrokBotUsageBreakdownRequest|1 enterprise_team_id 5?"]}}class Vm extends Va{constructor(t){super(),this.dayMs=s.protoInt64.zero,this.source=ou.UNSPECIFIED,this.ppm=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vm).fromBinary(t,r)}static fromJson(t,r){return(new Vm).fromJson(t,r)}static fromJsonString(t,r){return(new Vm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Vm,t,r)}static $(){return["GrokBotUsageSourcePpm|1 day_ms 3|2 source #0|3 ppm 5",ou]}}class Xm extends Va{constructor(t){super(),this.dayMs=s.protoInt64.zero,this.ppm=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xm).fromBinary(t,r)}static fromJson(t,r){return(new Xm).fromJson(t,r)}static fromJsonString(t,r){return(new Xm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Xm,t,r)}static $(){return["GrokBotUsageBotPpm|1 day_ms 3|2 bot_id 9?|3 ppm 5"]}}class Ym extends Va{constructor(t){super(),this.periodStartMs=s.protoInt64.zero,this.periodEndMs=s.protoInt64.zero,this.bySource=[],this.byBot=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ym).fromBinary(t,r)}static fromJson(t,r){return(new Ym).fromJson(t,r)}static fromJsonString(t,r){return(new Ym).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ym,t,r)}static $(){return["GrokBotUsagePpmSplits|1 period_start_ms 3|2 period_end_ms 3|3 by_source #0*|4 by_bot #1*",Vm,Xm]}}class Zm extends Va{constructor(t){super(),this.dayMs=s.protoInt64.zero,this.source=ou.UNSPECIFIED,this.cents=s.protoInt64.zero,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zm).fromBinary(t,r)}static fromJson(t,r){return(new Zm).fromJson(t,r)}static fromJsonString(t,r){return(new Zm).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Zm,t,r)}static $(){return["GrokBotUsageSourceCents|1 day_ms 3|2 source #0|3 cents 3",ou]}}class tf extends Va{constructor(t){super(),this.dayMs=s.protoInt64.zero,this.cents=s.protoInt64.zero,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tf).fromBinary(t,r)}static fromJson(t,r){return(new tf).fromJson(t,r)}static fromJsonString(t,r){return(new tf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(tf,t,r)}static $(){return["GrokBotUsageBotCents|1 day_ms 3|2 bot_id 9?|3 cents 3"]}}class rf extends Va{constructor(t){super(),this.periodStartMs=s.protoInt64.zero,this.periodEndMs=s.protoInt64.zero,this.bySource=[],this.byBot=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rf).fromBinary(t,r)}static fromJson(t,r){return(new rf).fromJson(t,r)}static fromJsonString(t,r){return(new rf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(rf,t,r)}static $(){return["GrokBotUsageCentsSplits|1 period_start_ms 3|2 period_end_ms 3|3 by_source #0*|4 by_bot #1*",Zm,tf]}}class ef extends Va{constructor(t){super(),this.breakdown={case:void 0},s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ef).fromBinary(t,r)}static fromJson(t,r){return(new ef).fromJson(t,r)}static fromJsonString(t,r){return(new ef).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ef,t,r)}static $(){return["GetGrokBotUsageBreakdownResponse|1 billed_cents #0 breakdown|2 weekly_limit_ppm #1 breakdown|3 billing_cycle_ppm #1 breakdown",rf,Ym]}}class nf extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nf).fromBinary(t,r)}static fromJson(t,r){return(new nf).fromJson(t,r)}static fromJsonString(t,r){return(new nf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(nf,t,r)}static $(){return["GetSandEnterpriseSpendLimitRequest|1 team_id 5"]}}class sf extends Va{constructor(t){super(),this.periodStartMs=s.protoInt64.zero,this.periodEndMs=s.protoInt64.zero,this.spentCents=s.protoInt64.zero,this.onDemandOnly=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sf).fromBinary(t,r)}static fromJson(t,r){return(new sf).fromJson(t,r)}static fromJsonString(t,r){return(new sf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(sf,t,r)}static $(){return["GetSandEnterpriseSpendLimitResponse|1 period_start_ms 3|2 period_end_ms 3|3 spent_cents 3|4 limit_cents 3?|5 on_demand_only 8"]}}class of extends Va{constructor(t){super(),this.href="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new of).fromBinary(t,r)}static fromJson(t,r){return(new of).fromJson(t,r)}static fromJsonString(t,r){return(new of).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(of,t,r)}static $(){return["SandUnifiedPlanMigrationOffer|1 href 9"]}}class af extends Va{constructor(t){super(),this.visible=!1,this.eligible=!1,this.enabled=!1,this.dashboardUrl="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new af).fromBinary(t,r)}static fromJson(t,r){return(new af).fromJson(t,r)}static fromJsonString(t,r){return(new af).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(af,t,r)}static $(){return["SandOnDemandSettings|1 visible 8|2 eligible 8|3 enabled 8|4 dashboard_url 9"]}}class uf extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new uf).fromBinary(t,r)}static fromJson(t,r){return(new uf).fromJson(t,r)}static fromJsonString(t,r){return(new uf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(uf,t,r)}static $(){return["StartSandTrialRequest"]}}class cf extends Va{constructor(t){super(),this.challenge="",this.attestation={case:void 0},s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cf).fromBinary(t,r)}static fromJson(t,r){return(new cf).fromJson(t,r)}static fromJsonString(t,r){return(new cf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(cf,t,r)}static $(){return["ClaimSandTrialWithDeviceAttestationRequest|1 challenge 9|2 ios_device_check #0 attestation|3 android_play_integrity #1 attestation",lf,mf]}}class lf extends Va{constructor(t){super(),this.deviceToken="",this.bundleId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lf).fromBinary(t,r)}static fromJson(t,r){return(new lf).fromJson(t,r)}static fromJsonString(t,r){return(new lf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(lf,t,r)}static $(){return["ClaimSandTrialIosDeviceCheck|1 device_token 9|2 bundle_id 9"]}}class mf extends Va{constructor(t){super(),this.integrityToken="",this.packageName="",this.deviceIdHash="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mf).fromBinary(t,r)}static fromJson(t,r){return(new mf).fromJson(t,r)}static fromJsonString(t,r){return(new mf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(mf,t,r)}static $(){return["ClaimSandTrialAndroidPlayIntegrity|1 integrity_token 9|2 package_name 9|3 device_id_hash 9"]}}class ff extends Va{constructor(t){super(),this.outcome=df.UNSPECIFIED,this.amountCents=0,this.grantExpiresAtMs=s.protoInt64.zero,this.retryAfterSeconds=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ff).fromBinary(t,r)}static fromJson(t,r){return(new ff).fromJson(t,r)}static fromJsonString(t,r){return(new ff).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ff,t,r)}static $(){return["ClaimSandTrialWithDeviceAttestationResponse|1 outcome #0|2 amount_cents 5|3 grant_expires_at_ms 3|4 retry_after_seconds 5",df]}}var df=(0,i.QT)(s.proto3,Qa,"ClaimSandTrialWithDeviceAttestationResponse.ClaimSandTrialOutcome",[[0,"UNSPECIFIED"],[1,"GRANTED"],[2,"ALREADY_GRANTED"],[3,"REJECTED_DUPLICATE_DEVICE"],[4,"REJECTED_ATTESTATION"],[5,"INELIGIBLE"],[6,"RETRY_LATER"]],1);class pf extends Va{constructor(t){super(),this.attestation={case:void 0},s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pf).fromBinary(t,r)}static fromJson(t,r){return(new pf).fromJson(t,r)}static fromJsonString(t,r){return(new pf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(pf,t,r)}static $(){return["ResetSandTrialDeviceAttestationRequest|1 ios_device_check #0 attestation|2 android_play_integrity #1 attestation",lf,mf]}}class hf extends Va{constructor(t){super(),this.result=gf.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hf).fromBinary(t,r)}static fromJson(t,r){return(new hf).fromJson(t,r)}static fromJsonString(t,r){return(new hf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(hf,t,r)}static $(){return["ResetSandTrialDeviceAttestationResponse|1 result #0",gf]}}var gf=(0,i.QT)(s.proto3,Qa,"ResetSandTrialDeviceAttestationResponse.ResetSandTrialDeviceResult",[[0,"UNSPECIFIED"],[1,"OK"],[2,"REFUSED_BUNDLE"],[3,"REFUSED_GATE"],[4,"ERROR"]],1);class _f extends Va{constructor(t){super(),this.outcome={case:void 0},s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _f).fromBinary(t,r)}static fromJson(t,r){return(new _f).fromJson(t,r)}static fromJsonString(t,r){return(new _f).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(_f,t,r)}static $(){return["StartSandTrialResponse|1 activated #0 outcome|2 card_verification_required #1 outcome",Jf,wf]}}class Jf extends Va{constructor(t){super(),this.amountCents=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jf).fromBinary(t,r)}static fromJson(t,r){return(new Jf).fromJson(t,r)}static fromJsonString(t,r){return(new Jf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Jf,t,r)}static $(){return["StartSandTrialResponse.Activated|1 amount_cents 5|2 expires_at #0",s.Timestamp]}}class wf extends Va{constructor(t){super(),this.checkoutUrl="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wf).fromBinary(t,r)}static fromJson(t,r){return(new wf).fromJson(t,r)}static fromJsonString(t,r){return(new wf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(wf,t,r)}static $(){return["StartSandTrialResponse.CardVerificationRequired|1 checkout_url 9"]}}class yf extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yf).fromBinary(t,r)}static fromJson(t,r){return(new yf).fromJson(t,r)}static fromJsonString(t,r){return(new yf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(yf,t,r)}static $(){return["IsEligibleForSandTrialRequest"]}}class Sf extends Va{constructor(t){super(),this.isEligible=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sf).fromBinary(t,r)}static fromJson(t,r){return(new Sf).fromJson(t,r)}static fromJsonString(t,r){return(new Sf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Sf,t,r)}static $(){return["IsEligibleForSandTrialResponse|1 is_eligible 8"]}}class qf extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qf).fromBinary(t,r)}static fromJson(t,r){return(new qf).fromJson(t,r)}static fromJsonString(t,r){return(new qf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(qf,t,r)}static $(){return["CancelSandTrialRequest"]}}class Bf extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bf).fromBinary(t,r)}static fromJson(t,r){return(new Bf).fromJson(t,r)}static fromJsonString(t,r){return(new Bf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Bf,t,r)}static $(){return["CancelSandTrialResponse"]}}class If extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new If).fromBinary(t,r)}static fromJson(t,r){return(new If).fromJson(t,r)}static fromJsonString(t,r){return(new If).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(If,t,r)}static $(){return["GetSandTrialClaimStatusRequest"]}}class Pf extends Va{constructor(t){super(),this.status=bf.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pf).fromBinary(t,r)}static fromJson(t,r){return(new Pf).fromJson(t,r)}static fromJsonString(t,r){return(new Pf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Pf,t,r)}static $(){return["GetSandTrialClaimStatusResponse|1 status #0",bf]}}var bf=(0,i.QT)(s.proto3,Qa,"GetSandTrialClaimStatusResponse.SandTrialClaimStatus",[[0,"UNSPECIFIED"],[1,"NONE"],[2,"PENDING_CARD"],[3,"GRANTED"],[4,"REJECTED_DUPLICATE_CARD"],[5,"BLOCKED"]],1);class Rf extends Va{constructor(t){super(),this.organizationId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rf).fromBinary(t,r)}static fromJson(t,r){return(new Rf).fromJson(t,r)}static fromJsonString(t,r){return(new Rf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Rf,t,r)}static $(){return["GetOrganizationGrokBotWallSnapshotControlsRequest|1 organization_id 9"]}}class vf extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vf).fromBinary(t,r)}static fromJson(t,r){return(new vf).fromJson(t,r)}static fromJsonString(t,r){return(new vf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(vf,t,r)}static $(){return["GetOrganizationGrokBotWallSnapshotControlsResponse|1 controls #0",n.lgO]}}class xf extends Va{constructor(t){super(),this.organizationId="",this.allowed=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xf).fromBinary(t,r)}static fromJson(t,r){return(new xf).fromJson(t,r)}static fromJsonString(t,r){return(new xf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(xf,t,r)}static $(){return["UpdateOrganizationGrokBotWallSnapshotControlsRequest|1 organization_id 9|2 allowed 8"]}}class kf extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kf).fromBinary(t,r)}static fromJson(t,r){return(new kf).fromJson(t,r)}static fromJsonString(t,r){return(new kf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(kf,t,r)}static $(){return["UpdateOrganizationGrokBotWallSnapshotControlsResponse|1 controls #0",n.lgO]}}class Ef extends Va{constructor(t){super(),this.automationId="",this.slackTeamId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ef).fromBinary(t,r)}static fromJson(t,r){return(new Ef).fromJson(t,r)}static fromJsonString(t,r){return(new Ef).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ef,t,r)}static $(){return["SetSandAutomationSlackWorkspaceRequest|1 automation_id 9|2 slack_team_id 9"]}}class Cf extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cf).fromBinary(t,r)}static fromJson(t,r){return(new Cf).fromJson(t,r)}static fromJsonString(t,r){return(new Cf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Cf,t,r)}static $(){return["SetSandAutomationSlackWorkspaceResponse"]}}class Tf extends Va{constructor(t){super(),this.resource="",this.authorizationServerIssuer="",this.clientId="",this.clientAuthMethod=au.UNSPECIFIED,this.clientSecretSet=!1,this.audience="",this.scope="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tf).fromBinary(t,r)}static fromJson(t,r){return(new Tf).fromJson(t,r)}static fromJsonString(t,r){return(new Tf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Tf,t,r)}static $(){return["GrokBotIdJagAllowedConnector|1 resource 9|2 authorization_server_issuer 9|3 client_id 9|4 client_auth_method #0|5 client_secret 9?|6 client_secret_set 8|7 client_secret_updated_at_ms 3?|8 audience 9|9 scope 9",au]}}class Uf extends Va{constructor(t){super(),this.issuerUrl="",this.clientId="",this.clientAuthMethod=au.UNSPECIFIED,this.clientSecretSet=!1,this.idJagConnectorPolicyMode=uu.UNSPECIFIED,this.idJagAllowedConnectors=[],this.idJagConsentFallbackAllowed=!1,this.configVersion=s.protoInt64.zero,this.updatedAtMs=s.protoInt64.zero,this.connectionId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Uf).fromBinary(t,r)}static fromJson(t,r){return(new Uf).fromJson(t,r)}static fromJsonString(t,r){return(new Uf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Uf,t,r)}static $(){return["GrokBotIdpConnection|1 issuer_url 9|2 client_id 9|3 client_auth_method #0|4 client_secret_set 8|5 client_secret_updated_at_ms 3?|10 id_jag_connector_policy_mode #1|11 id_jag_allowed_connectors #2*|7 id_jag_consent_fallback_allowed 8|8 config_version 3|9 updated_at_ms 3|12 connection_id 9",au,uu,Tf]}}class Af extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Af).fromBinary(t,r)}static fromJson(t,r){return(new Af).fromJson(t,r)}static fromJsonString(t,r){return(new Af).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Af,t,r)}static $(){return["GetTeamGrokBotIdpConnectionRequest|1 team_id 5"]}}class $f extends Va{constructor(t){super(),this.available=!1,this.privateKeyJwtAvailable=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $f).fromBinary(t,r)}static fromJson(t,r){return(new $f).fromJson(t,r)}static fromJsonString(t,r){return(new $f).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals($f,t,r)}static $(){return["GetTeamGrokBotIdpConnectionResponse|1 available 8|2 connection #0|3 private_key_jwt_available 8",Uf]}}class Mf extends Va{constructor(t){super(),this.teamId=0,this.issuerUrl="",this.clientId="",this.clientAuthMethod=au.UNSPECIFIED,this.idJagConnectorPolicyMode=uu.UNSPECIFIED,this.idJagAllowedConnectors=[],this.idJagConsentFallbackAllowed=!1,this.sendsConnectorClients=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mf).fromBinary(t,r)}static fromJson(t,r){return(new Mf).fromJson(t,r)}static fromJsonString(t,r){return(new Mf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Mf,t,r)}static $(){return["UpdateTeamGrokBotIdpConnectionRequest|1 team_id 5|2 issuer_url 9|3 client_id 9|4 client_auth_method #0|5 client_secret 9?|9 id_jag_connector_policy_mode #1|10 id_jag_allowed_connectors #2*|7 id_jag_consent_fallback_allowed 8|8 expected_config_version 3?|11 expected_connection_id 9?|12 sends_connector_clients 8",au,uu,Tf]}}class Of extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Of).fromBinary(t,r)}static fromJson(t,r){return(new Of).fromJson(t,r)}static fromJsonString(t,r){return(new Of).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Of,t,r)}static $(){return["UpdateTeamGrokBotIdpConnectionResponse|1 connection #0",Uf]}}class Df extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Df).fromBinary(t,r)}static fromJson(t,r){return(new Df).fromJson(t,r)}static fromJsonString(t,r){return(new Df).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Df,t,r)}static $(){return["DeleteTeamGrokBotIdpConnectionRequest|1 team_id 5"]}}class Nf extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nf).fromBinary(t,r)}static fromJson(t,r){return(new Nf).fromJson(t,r)}static fromJsonString(t,r){return(new Nf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Nf,t,r)}static $(){return["DeleteTeamGrokBotIdpConnectionResponse"]}}class Gf extends Va{constructor(t){super(),this.id="",this.prefix="",this.createdByUserId=s.protoInt64.zero,this.createdAtEpochMillis=s.protoInt64.zero,this.expiresAtEpochMillis=s.protoInt64.zero,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gf).fromBinary(t,r)}static fromJson(t,r){return(new Gf).fromJson(t,r)}static fromJsonString(t,r){return(new Gf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Gf,t,r)}static $(){return["TeamGrokBotScimToken|1 id 9|2 prefix 9|3 created_by_user_id 3|4 created_at_epoch_millis 3|5 expires_at_epoch_millis 3|6 last_used_at_epoch_millis 3?"]}}class Lf extends Va{constructor(t){super(),this.id="",this.enabled=!1,this.baseUrl="",this.ipAllowlist=[],this.tokens=[],this.createdAtEpochMillis=s.protoInt64.zero,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lf).fromBinary(t,r)}static fromJson(t,r){return(new Lf).fromJson(t,r)}static fromJsonString(t,r){return(new Lf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Lf,t,r)}static $(){return["TeamGrokBotScimDirectory|1 id 9|2 enabled 8|3 base_url 9|4 ip_allowlist 9*|5 last_request_at_epoch_millis 3?|6 last_error_at_epoch_millis 3?|7 last_error_detail 9?|8 tokens #0*|9 created_at_epoch_millis 3",Gf]}}class Ff extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ff).fromBinary(t,r)}static fromJson(t,r){return(new Ff).fromJson(t,r)}static fromJsonString(t,r){return(new Ff).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ff,t,r)}static $(){return["GetTeamGrokBotScimDirectoryRequest|1 team_id 5"]}}class Kf extends Va{constructor(t){super(),this.available=!1,this.tokensAvailable=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kf).fromBinary(t,r)}static fromJson(t,r){return(new Kf).fromJson(t,r)}static fromJsonString(t,r){return(new Kf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Kf,t,r)}static $(){return["GetTeamGrokBotScimDirectoryResponse|1 available 8|2 directory #0?|3 tokens_available 8",Lf]}}class zf extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zf).fromBinary(t,r)}static fromJson(t,r){return(new zf).fromJson(t,r)}static fromJsonString(t,r){return(new zf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(zf,t,r)}static $(){return["EnableTeamGrokBotScimDirectoryRequest|1 team_id 5"]}}class jf extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jf).fromBinary(t,r)}static fromJson(t,r){return(new jf).fromJson(t,r)}static fromJsonString(t,r){return(new jf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(jf,t,r)}static $(){return["EnableTeamGrokBotScimDirectoryResponse|1 directory #0",Lf]}}class Hf extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hf).fromBinary(t,r)}static fromJson(t,r){return(new Hf).fromJson(t,r)}static fromJsonString(t,r){return(new Hf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Hf,t,r)}static $(){return["DisableTeamGrokBotScimDirectoryRequest|1 team_id 5"]}}class Wf extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wf).fromBinary(t,r)}static fromJson(t,r){return(new Wf).fromJson(t,r)}static fromJsonString(t,r){return(new Wf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Wf,t,r)}static $(){return["DisableTeamGrokBotScimDirectoryResponse|1 directory #0",Lf]}}class Qf extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qf).fromBinary(t,r)}static fromJson(t,r){return(new Qf).fromJson(t,r)}static fromJsonString(t,r){return(new Qf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Qf,t,r)}static $(){return["CreateTeamGrokBotScimTokenRequest|1 team_id 5|2 expires_in_days 5?"]}}class Vf extends Va{constructor(t){super(),this.plaintextToken="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vf).fromBinary(t,r)}static fromJson(t,r){return(new Vf).fromJson(t,r)}static fromJsonString(t,r){return(new Vf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Vf,t,r)}static $(){return["CreateTeamGrokBotScimTokenResponse|1 directory #0|2 token #1|3 plaintext_token 9",Lf,Gf]}}class Xf extends Va{constructor(t){super(),this.teamId=0,this.tokenId="",this.rotation=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xf).fromBinary(t,r)}static fromJson(t,r){return(new Xf).fromJson(t,r)}static fromJsonString(t,r){return(new Xf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Xf,t,r)}static $(){return["RevokeTeamGrokBotScimTokenRequest|1 team_id 5|2 token_id 9|3 rotation 8"]}}class Yf extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yf).fromBinary(t,r)}static fromJson(t,r){return(new Yf).fromJson(t,r)}static fromJsonString(t,r){return(new Yf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Yf,t,r)}static $(){return["RevokeTeamGrokBotScimTokenResponse|1 directory #0",Lf]}}class Zf extends Va{constructor(t){super(),this.teamId=0,this.ipAllowlist=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zf).fromBinary(t,r)}static fromJson(t,r){return(new Zf).fromJson(t,r)}static fromJsonString(t,r){return(new Zf).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Zf,t,r)}static $(){return["UpdateTeamGrokBotScimIpAllowlistRequest|1 team_id 5|2 ip_allowlist 9*"]}}class td extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new td).fromBinary(t,r)}static fromJson(t,r){return(new td).fromJson(t,r)}static fromJsonString(t,r){return(new td).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(td,t,r)}static $(){return["UpdateTeamGrokBotScimIpAllowlistResponse|1 directory #0",Lf]}}class rd extends Va{constructor(t){super(),this.agentId="",this.name="",this.userName="",this.hidden=!1,this.createdAtEpochMillis=s.protoInt64.zero,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rd).fromBinary(t,r)}static fromJson(t,r){return(new rd).fromJson(t,r)}static fromJsonString(t,r){return(new rd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(rd,t,r)}static $(){return["TeamGrokBotScimBot|1 agent_id 9|2 name 9|3 user_name 9|4 manager 9?|5 hidden 8|6 created_at_epoch_millis 3|7 hidden_at_epoch_millis 3?"]}}class ed extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ed).fromBinary(t,r)}static fromJson(t,r){return(new ed).fromJson(t,r)}static fromJsonString(t,r){return(new ed).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ed,t,r)}static $(){return["ListTeamGrokBotScimBotsRequest|1 team_id 5"]}}class nd extends Va{constructor(t){super(),this.bots=[],this.activeCount=0,this.hiddenCount=0,this.truncated=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nd).fromBinary(t,r)}static fromJson(t,r){return(new nd).fromJson(t,r)}static fromJsonString(t,r){return(new nd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(nd,t,r)}static $(){return["ListTeamGrokBotScimBotsResponse|1 bots #0*|2 active_count 5|3 hidden_count 5|4 truncated 8",rd]}}class sd extends Va{constructor(t){super(),this.teamId=0,this.agentId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sd).fromBinary(t,r)}static fromJson(t,r){return(new sd).fromJson(t,r)}static fromJsonString(t,r){return(new sd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(sd,t,r)}static $(){return["DeleteTeamGrokBotScimBotRequest|1 team_id 5|2 agent_id 9"]}}class id extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new id).fromBinary(t,r)}static fromJson(t,r){return(new id).fromJson(t,r)}static fromJsonString(t,r){return(new id).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(id,t,r)}static $(){return["DeleteTeamGrokBotScimBotResponse"]}}class od extends Va{constructor(t){super(),this.pem="",this.sha256Fingerprint="",this.notBeforeEpochMillis=s.protoInt64.zero,this.notAfterEpochMillis=s.protoInt64.zero,this.subject="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new od).fromBinary(t,r)}static fromJson(t,r){return(new od).fromJson(t,r)}static fromJsonString(t,r){return(new od).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(od,t,r)}static $(){return["TeamGrokBotScimSigningCertificate|1 pem 9|2 sha256_fingerprint 9|3 not_before_epoch_millis 3|4 not_after_epoch_millis 3|5 subject 9"]}}class ad extends Va{constructor(t){super(),this.identityId="",this.oktaOrgUrl="",this.oidcClientId="",this.oidcClientSecretSet=!1,this.samlIdpId="",this.samlAudience="",this.samlIssuer="",this.signingKeySet=!1,this.configVersion=0,this.updatedAtEpochMillis=s.protoInt64.zero,this.oktaSignInMethod=cu.UNSPECIFIED,this.oktaClientAuthMethod=lu.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ad).fromBinary(t,r)}static fromJson(t,r){return(new ad).fromJson(t,r)}static fromJsonString(t,r){return(new ad).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ad,t,r)}static $(){return["TeamGrokBotScimIdpIdentity|1 identity_id 9|2 okta_org_url 9|3 oidc_client_id 9|4 oidc_client_secret_set 8|5 saml_idp_id 9|6 saml_audience 9|7 saml_issuer 9|8 signing_key_set 8|9 signing_certificate #0?|10 config_version 5|11 updated_at_epoch_millis 3|12 okta_sign_in_method #1|13 okta_client_auth_method #2",od,cu,lu]}}class ud extends Va{constructor(t){super(),this.serverUrl="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ud).fromBinary(t,r)}static fromJson(t,r){return(new ud).fromJson(t,r)}static fromJsonString(t,r){return(new ud).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ud,t,r)}static $(){return["TeamGrokBotScimIdJagServer|1 server_url 9|2 client_id 9?"]}}class cd extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cd).fromBinary(t,r)}static fromJson(t,r){return(new cd).fromJson(t,r)}static fromJsonString(t,r){return(new cd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(cd,t,r)}static $(){return["GetTeamGrokBotScimIdpIdentityRequest|1 team_id 5"]}}class ld extends Va{constructor(t){super(),this.available=!1,this.oktaRedirectUri="",this.idJagServers=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ld).fromBinary(t,r)}static fromJson(t,r){return(new ld).fromJson(t,r)}static fromJsonString(t,r){return(new ld).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ld,t,r)}static $(){return["GetTeamGrokBotScimIdpIdentityResponse|1 available 8|2 identity #0?|3 okta_redirect_uri 9|4 id_jag_servers #1*",ad,ud]}}class md extends Va{constructor(t){super(),this.teamId=0,this.oktaOrgUrl="",this.oidcClientId="",this.samlIdpId="",this.samlAudience="",this.samlIssuer="",this.expectedConfigVersion=0,this.expectedIdentityId="",this.oktaSignInMethod=cu.UNSPECIFIED,this.oktaClientAuthMethod=lu.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new md).fromBinary(t,r)}static fromJson(t,r){return(new md).fromJson(t,r)}static fromJsonString(t,r){return(new md).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(md,t,r)}static $(){return["UpdateTeamGrokBotScimIdpIdentityRequest|1 team_id 5|2 okta_org_url 9|3 oidc_client_id 9|4 oidc_client_secret 9?|5 saml_idp_id 9|6 saml_audience 9|7 saml_issuer 9|8 signing_certificate_pem 9?|9 signing_private_key_pem 9?|10 expected_config_version 5|11 expected_identity_id 9|12 okta_sign_in_method #0|13 okta_client_auth_method #1",cu,lu]}}class fd extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fd).fromBinary(t,r)}static fromJson(t,r){return(new fd).fromJson(t,r)}static fromJsonString(t,r){return(new fd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(fd,t,r)}static $(){return["UpdateTeamGrokBotScimIdpIdentityResponse|1 identity #0",ad]}}class dd extends Va{constructor(t){super(),this.teamId=0,this.expectedConfigVersion=0,this.expectedIdentityId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dd).fromBinary(t,r)}static fromJson(t,r){return(new dd).fromJson(t,r)}static fromJsonString(t,r){return(new dd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(dd,t,r)}static $(){return["GenerateTeamGrokBotScimIdpSigningKeyRequest|1 team_id 5|2 expected_config_version 5|3 expected_identity_id 9"]}}class pd extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pd).fromBinary(t,r)}static fromJson(t,r){return(new pd).fromJson(t,r)}static fromJsonString(t,r){return(new pd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(pd,t,r)}static $(){return["GenerateTeamGrokBotScimIdpSigningKeyResponse|1 identity #0",ad]}}class hd extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hd).fromBinary(t,r)}static fromJson(t,r){return(new hd).fromJson(t,r)}static fromJsonString(t,r){return(new hd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(hd,t,r)}static $(){return["DeleteTeamGrokBotScimIdpIdentityRequest|1 team_id 5"]}}class gd extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gd).fromBinary(t,r)}static fromJson(t,r){return(new gd).fromJson(t,r)}static fromJsonString(t,r){return(new gd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(gd,t,r)}static $(){return["DeleteTeamGrokBotScimIdpIdentityResponse"]}}class _d extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _d).fromBinary(t,r)}static fromJson(t,r){return(new _d).fromJson(t,r)}static fromJsonString(t,r){return(new _d).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(_d,t,r)}static $(){return["GetTeamGrokBotPublishedWorkerImageRequest|1 team_id 5"]}}class Jd extends Va{constructor(t){super(),this.workerImageVersion=s.protoInt64.zero,this.imageTag="",this.gitCommit="",this.fromLastKnown=!1,this.failure=fu.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jd).fromBinary(t,r)}static fromJson(t,r){return(new Jd).fromJson(t,r)}static fromJsonString(t,r){return(new Jd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Jd,t,r)}static $(){return["GrokBotPublishedWorkerImage|1 worker_image_version 3|2 image_tag 9|3 git_commit 9|4 from_last_known 8|5 read_at_ms 3?|6 failure #0",fu]}}class wd extends Va{constructor(t){super(),this.state=mu.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wd).fromBinary(t,r)}static fromJson(t,r){return(new wd).fromJson(t,r)}static fromJsonString(t,r){return(new wd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(wd,t,r)}static $(){return["GetTeamGrokBotPublishedWorkerImageResponse|1 state #0|2 image #1",mu,Jd]}}class yd extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yd).fromBinary(t,r)}static fromJson(t,r){return(new yd).fromJson(t,r)}static fromJsonString(t,r){return(new yd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(yd,t,r)}static $(){return["ListTeamGrokBotCustomerHostedWorkersRequest|1 team_id 5"]}}class Sd extends Va{constructor(t){super(),this.poolName="",this.workers=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sd).fromBinary(t,r)}static fromJson(t,r){return(new Sd).fromJson(t,r)}static fromJsonString(t,r){return(new Sd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Sd,t,r)}static $(){return["ListTeamGrokBotCustomerHostedWorkersResponse|1 pool_name 9|2 workers #0*",Id]}}class qd extends Va{constructor(t){super(),this.manifestId="",this.revision="",this.ok=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qd).fromBinary(t,r)}static fromJson(t,r){return(new qd).fromJson(t,r)}static fromJsonString(t,r){return(new qd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(qd,t,r)}static $(){return["GrokBotCustomerHostedWorkerSetupManifest|1 manifest_id 9|2 revision 9|3 ok 8"]}}class Bd extends Va{constructor(t){super(),this.state=du.UNSPECIFIED,this.manifests=[],this.truncatedCount=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bd).fromBinary(t,r)}static fromJson(t,r){return(new Bd).fromJson(t,r)}static fromJsonString(t,r){return(new Bd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Bd,t,r)}static $(){return["GrokBotCustomerHostedWorkerSetup|1 state #0|2 unavailable_reason #1?|3 manifests #2*|4 truncated_count 5|5 reported_at_ms 1?",du,pu,qd]}}class Id extends Va{constructor(t){super(),this.workerId="",this.name="",this.connectedAtMs=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Id).fromBinary(t,r)}static fromJson(t,r){return(new Id).fromJson(t,r)}static fromJsonString(t,r){return(new Id).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Id,t,r)}static $(){return["GrokBotCustomerHostedWorker|1 worker_id 9|2 name 9|3 connected_at_ms 1|4 image_digest 9?|5 customer_version 9?|6 worker_image_tag 9?|7 worker_image_version 9?|8 setup #0?",Bd]}}class Pd extends Va{constructor(t){super(),this.machineId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pd).fromBinary(t,r)}static fromJson(t,r){return(new Pd).fromJson(t,r)}static fromJsonString(t,r){return(new Pd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Pd,t,r)}static $(){return["RemoveSandMachineRequest|1 machine_id 9"]}}class bd extends Va{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bd).fromBinary(t,r)}static fromJson(t,r){return(new bd).fromJson(t,r)}static fromJsonString(t,r){return(new bd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(bd,t,r)}static $(){return["RemoveSandMachineResponse"]}}class Rd extends Va{constructor(t){super(),this.userId=0,this.email="",this.name="",this.role=hu.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rd).fromBinary(t,r)}static fromJson(t,r){return(new Rd).fromJson(t,r)}static fromJsonString(t,r){return(new Rd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Rd,t,r)}static $(){return["TeamGrokBotDashboardAccessEntry|1 user_id 5|2 email 9|3 name 9|4 role #0",hu]}}class vd extends Va{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vd).fromBinary(t,r)}static fromJson(t,r){return(new vd).fromJson(t,r)}static fromJsonString(t,r){return(new vd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(vd,t,r)}static $(){return["ListTeamGrokBotDashboardAccessRequest|1 team_id 5"]}}class xd extends Va{constructor(t){super(),this.enabled=!1,this.entries=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xd).fromBinary(t,r)}static fromJson(t,r){return(new xd).fromJson(t,r)}static fromJsonString(t,r){return(new xd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(xd,t,r)}static $(){return["ListTeamGrokBotDashboardAccessResponse|1 enabled 8|2 entries #0*",Rd]}}class kd extends Va{constructor(t){super(),this.teamId=0,this.userId=0,this.role=hu.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kd).fromBinary(t,r)}static fromJson(t,r){return(new kd).fromJson(t,r)}static fromJsonString(t,r){return(new kd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(kd,t,r)}static $(){return["SetTeamGrokBotDashboardAccessRequest|1 team_id 5|2 user_id 5|3 role #0",hu]}}class Ed extends Va{constructor(t){super(),this.entries=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ed).fromBinary(t,r)}static fromJson(t,r){return(new Ed).fromJson(t,r)}static fromJsonString(t,r){return(new Ed).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ed,t,r)}static $(){return["SetTeamGrokBotDashboardAccessResponse|1 entries #0*",Rd]}}class Cd extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",s.proto3)}static $p(){return"aiserver.v1."}}class Td extends Cd{constructor(t){super(),this.teamId=0,this.allTeams=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Td).fromBinary(t,r)}static fromJson(t,r){return(new Td).fromJson(t,r)}static fromJsonString(t,r){return(new Td).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Td,t,r)}static $(){return["GetTeamTailnetRequest|1 team_id 5|2 all_teams 8"]}}class Ud extends Cd{constructor(t){super(),this.enabled=!1,this.magicDnsSuffix="",this.enabledAtMs=s.protoInt64.zero,this.available=!1,this.canManage=!1,this.teams=[],this.companyCaAvailable=!1,this.companyCas=[],this.magicDnsSuffixes=[],this.multipleAvailable=!1,this.tailnetNames={},s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ud).fromBinary(t,r)}static fromJson(t,r){return(new Ud).fromJson(t,r)}static fromJsonString(t,r){return(new Ud).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ud,t,r)}static $(){return["GetTeamTailnetResponse|1 enabled 8|2 magic_dns_suffix 9|3 enabled_at_ms 3|4 available 8|5 can_manage 8|8 member_device_count 5?|10 teams #0*|11 company_ca_available 8|12 company_cas #1*|13 magic_dns_suffixes 9*|14 multiple_available 8|15 active #2|16 tailnet_names 9,9|17 box_access #3|18 allow_unlabeled 8?|19 exit_nodes #4",Gd,Ld,Od,Md,Ad]}}class Ad extends Cd{constructor(t){super(),this.exitNodes=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ad).fromBinary(t,r)}static fromJson(t,r){return(new Ad).fromJson(t,r)}static fromJsonString(t,r){return(new Ad).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ad,t,r)}static $(){return["TeamTailnetExitNodes|1 exit_nodes #0*",$d]}}class $d extends Cd{constructor(t){super(),this.magicDnsSuffix="",this.nodeId="",this.nodeName="",this.cidrs=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $d).fromBinary(t,r)}static fromJson(t,r){return(new $d).fromJson(t,r)}static fromJsonString(t,r){return(new $d).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals($d,t,r)}static $(){return["TeamTailnetExitNode|1 magic_dns_suffix 9|2 node_id 9|3 node_name 9|4 cidrs 9*"]}}class Md extends Cd{constructor(t){super(),this.magicDnsSuffixes=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Md).fromBinary(t,r)}static fromJson(t,r){return(new Md).fromJson(t,r)}static fromJsonString(t,r){return(new Md).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Md,t,r)}static $(){return["TeamTailnetBoxAccess|1 magic_dns_suffixes 9*"]}}class Od extends Cd{constructor(t){super(),this.choice={case:void 0},this.chosen=!1,this.personalAccountKey="",this.magicDnsSuffix="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Od).fromBinary(t,r)}static fromJson(t,r){return(new Od).fromJson(t,r)}static fromJsonString(t,r){return(new Od).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Od,t,r)}static $(){return["ActiveTailnet|1 personal 8 choice|2 team_id 5 choice|3 chosen 8|4 personal_account_key 9|5 magic_dns_suffix 9"]}}class Dd extends Cd{constructor(t){super(),this.choice={case:void 0},this.personalAccountKey="",this.magicDnsSuffix="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dd).fromBinary(t,r)}static fromJson(t,r){return(new Dd).fromJson(t,r)}static fromJsonString(t,r){return(new Dd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Dd,t,r)}static $(){return["SetActiveTailnetRequest|1 personal 8 choice|2 team_id 5 choice|3 personal_account_key 9|4 magic_dns_suffix 9"]}}class Nd extends Cd{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nd).fromBinary(t,r)}static fromJson(t,r){return(new Nd).fromJson(t,r)}static fromJsonString(t,r){return(new Nd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Nd,t,r)}static $(){return["SetActiveTailnetResponse"]}}class Gd extends Cd{constructor(t){super(),this.teamId=0,this.teamName="",this.enabled=!1,this.magicDnsSuffix="",this.enabledAtMs=s.protoInt64.zero,this.available=!1,this.canManage=!1,this.companyCaAvailable=!1,this.companyCas=[],this.magicDnsSuffixes=[],this.multipleAvailable=!1,this.tailnetNames={},s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gd).fromBinary(t,r)}static fromJson(t,r){return(new Gd).fromJson(t,r)}static fromJsonString(t,r){return(new Gd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Gd,t,r)}static $(){return["TeamTailnetTeamView|1 team_id 5|2 team_name 9|3 enabled 8|4 magic_dns_suffix 9|5 enabled_at_ms 3|6 available 8|7 can_manage 8|10 member_device_count 5?|12 company_ca_available 8|13 company_cas #0*|14 magic_dns_suffixes 9*|15 multiple_available 8|16 tailnet_names 9,9|17 box_access #1|18 allow_unlabeled 8?|19 exit_nodes #2",Ld,Md,Ad]}}class Ld extends Cd{constructor(t){super(),this.subject="",this.sha256Fingerprint="",this.notAfterMs=s.protoInt64.zero,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ld).fromBinary(t,r)}static fromJson(t,r){return(new Ld).fromJson(t,r)}static fromJsonString(t,r){return(new Ld).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ld,t,r)}static $(){return["TeamTailnetCompanyCa|1 subject 9|2 sha256_fingerprint 9|3 not_after_ms 3"]}}class Fd extends Cd{constructor(t){super(),this.teamId=0,this.enabled=!1,this.magicDnsSuffix="",this.consent=!1,this.magicDnsSuffixes=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fd).fromBinary(t,r)}static fromJson(t,r){return(new Fd).fromJson(t,r)}static fromJsonString(t,r){return(new Fd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Fd,t,r)}static $(){return["UpdateTeamTailnetRequest|1 team_id 5|2 enabled 8|3 magic_dns_suffix 9|4 consent 8|5 magic_dns_suffixes 9*|6 allow_unlabeled 8?"]}}class Kd extends Cd{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kd).fromBinary(t,r)}static fromJson(t,r){return(new Kd).fromJson(t,r)}static fromJsonString(t,r){return(new Kd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Kd,t,r)}static $(){return["UpdateTeamTailnetResponse"]}}class zd extends Cd{constructor(t){super(),this.teamId=0,this.companyCaBundle="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zd).fromBinary(t,r)}static fromJson(t,r){return(new zd).fromJson(t,r)}static fromJsonString(t,r){return(new zd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(zd,t,r)}static $(){return["UpdateTeamTailnetCompanyCaRequest|1 team_id 5|2 company_ca_bundle 9"]}}class jd extends Cd{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jd).fromBinary(t,r)}static fromJson(t,r){return(new jd).fromJson(t,r)}static fromJsonString(t,r){return(new jd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(jd,t,r)}static $(){return["UpdateTeamTailnetCompanyCaResponse"]}}class Hd extends Cd{constructor(t){super(),this.teamId=0,this.magicDnsSuffix="",this.enabled=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hd).fromBinary(t,r)}static fromJson(t,r){return(new Hd).fromJson(t,r)}static fromJsonString(t,r){return(new Hd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Hd,t,r)}static $(){return["UpdateTeamTailnetBoxAccessRequest|1 team_id 5|2 magic_dns_suffix 9|3 enabled 8"]}}class Wd extends Cd{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wd).fromBinary(t,r)}static fromJson(t,r){return(new Wd).fromJson(t,r)}static fromJsonString(t,r){return(new Wd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Wd,t,r)}static $(){return["UpdateTeamTailnetBoxAccessResponse"]}}class Qd extends Cd{constructor(t){super(),this.teamId=0,this.magicDnsSuffix="",this.nodeId="",this.nodeName="",this.cidrs=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qd).fromBinary(t,r)}static fromJson(t,r){return(new Qd).fromJson(t,r)}static fromJsonString(t,r){return(new Qd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Qd,t,r)}static $(){return["UpdateTeamTailnetExitNodeRequest|1 team_id 5|2 magic_dns_suffix 9|3 node_id 9|4 node_name 9|5 cidrs 9*"]}}class Vd extends Cd{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vd).fromBinary(t,r)}static fromJson(t,r){return(new Vd).fromJson(t,r)}static fromJsonString(t,r){return(new Vd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Vd,t,r)}static $(){return["UpdateTeamTailnetExitNodeResponse"]}}class Xd extends Cd{constructor(t){super(),this.teamId=0,this.start=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xd).fromBinary(t,r)}static fromJson(t,r){return(new Xd).fromJson(t,r)}static fromJsonString(t,r){return(new Xd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Xd,t,r)}static $(){return["DiscoverTeamTailnetSuffixRequest|1 team_id 5|2 start 8"]}}class Yd extends Cd{constructor(t){super(),this.signInUrl="",this.magicDnsSuffix="",this.failureReason="",this.tailnetName="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yd).fromBinary(t,r)}static fromJson(t,r){return(new Yd).fromJson(t,r)}static fromJsonString(t,r){return(new Yd).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Yd,t,r)}static $(){return["DiscoverTeamTailnetSuffixResponse|1 sign_in_url 9|2 magic_dns_suffix 9|3 failure_reason 9|4 tailnet_name 9"]}}class Zd extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",s.proto3)}static $p(){return"aiserver.v1."}}class tp extends Zd{constructor(t){super(),this.subjectKey="",this.score=0,this.sampleCount=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tp).fromBinary(t,r)}static fromJson(t,r){return(new tp).fromJson(t,r)}static fromJsonString(t,r){return(new tp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(tp,t,r)}static $(){return["SubjectScore|1 subject_key 9|2 score 1|3 sample_count 1"]}}class rp extends Zd{constructor(t){super(),this.sourceWatermarkMs=s.protoInt64.zero,this.generatedAtMs=s.protoInt64.zero,this.expiresAtMs=s.protoInt64.zero,this.scores=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rp).fromBinary(t,r)}static fromJson(t,r){return(new rp).fromJson(t,r)}static fromJsonString(t,r){return(new rp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(rp,t,r)}static $(){return["ProjectionScoreSet|1 source_watermark_ms 3|2 generated_at_ms 3|3 expires_at_ms 3|4 scores #0*",tp]}}class ep extends Zd{constructor(t){super(),this.policyId="",this.knownSnapshotVersion=s.protoInt64.zero,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ep).fromBinary(t,r)}static fromJson(t,r){return(new ep).fromJson(t,r)}static fromJsonString(t,r){return(new ep).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ep,t,r)}static $(){return["GetProjectionSnapshotRequest|1 policy_id 9|2 known_snapshot_version 4"]}}class np extends Zd{constructor(t){super(),this.policyId="",this.policyVersion=0,this.snapshotVersion=s.protoInt64.zero,this.notModified=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new np).fromBinary(t,r)}static fromJson(t,r){return(new np).fromJson(t,r)}static fromJsonString(t,r){return(new np).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(np,t,r)}static $(){return["GetProjectionSnapshotResponse|1 policy_id 9|2 policy_version 13|3 snapshot_version 4|4 team #0|5 not_modified 8",rp]}}class sp extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",s.proto3)}static $p(){return"aiserver.v1."}}class ip extends sp{constructor(t){super(),this.teamId=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ip).fromBinary(t,r)}static fromJson(t,r){return(new ip).fromJson(t,r)}static fromJsonString(t,r){return(new ip).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ip,t,r)}static $(){return["ListRepoLearnedRulesRequest|1 team_id 5"]}}class op extends sp{constructor(t){super(),this.enabled=!1,this.items=[],this.truncated=!1,this.hiddenCount=0,this.live=!1,this.canEdit=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new op).fromBinary(t,r)}static fromJson(t,r){return(new op).fromJson(t,r)}static fromJsonString(t,r){return(new op).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(op,t,r)}static $(){return["ListRepoLearnedRulesResponse|1 enabled 8|2 items #0*|3 truncated 8|4 hidden_count 5|5 live 8|6 can_edit 8",ap]}}class ap extends sp{constructor(t){super(),this.id="",this.repoId="",this.gitRemoteOrigin="",this.title="",this.appliesWhen="",this.content="",this.kind="",this.scopedPaths=[],this.status="",this.importance=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ap).fromBinary(t,r)}static fromJson(t,r){return(new ap).fromJson(t,r)}static fromJsonString(t,r){return(new ap).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(ap,t,r)}static $(){return["RepoLearnedRule|1 id 9|2 repo_id 9|3 git_remote_origin 9|4 title 9|5 applies_when 9|6 content 9|7 kind 9|8 item_class 9?|9 scoped_paths 9*|10 status 9|11 importance 5|12 would_promote_at #0|13 archived_at #0|14 archived_reason 9?|15 created_at #0|16 updated_at #0|17 source 9?",s.Timestamp]}}class up extends sp{constructor(t){super(),this.teamId=0,this.id="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new up).fromBinary(t,r)}static fromJson(t,r){return(new up).fromJson(t,r)}static fromJsonString(t,r){return(new up).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(up,t,r)}static $(){return["RemoveRepoLearnedRuleRequest|1 team_id 5|2 id 9"]}}class cp extends sp{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cp).fromBinary(t,r)}static fromJson(t,r){return(new cp).fromJson(t,r)}static fromJsonString(t,r){return(new cp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(cp,t,r)}static $(){return["RemoveRepoLearnedRuleResponse"]}}const lp="aiserver.v1.";class mp extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",s.proto3)}static $p(){return lp}}var fp=(0,i.QT)(s.proto3,lp,"RsiRecordKind",[[0,"UNSPECIFIED"],[1,"CONTROL"],[2,"BREAKER"],[3,"TICK"],[4,"META_RUN"],[5,"HARNESS"],[6,"JUDGEMENT"],[7,"SNAPSHOT"],[8,"DAY"],[9,"REPLY"]],1),dp=(s.proto3,(0,i.QT)(s.proto3,lp,"RsiLoop",[[0,"UNSPECIFIED"],[1,"TICK"],[2,"META"],[3,"FOLLOWUP"]],1));class pp extends mp{constructor(t){super(),this.org="",this.name="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pp).fromBinary(t,r)}static fromJson(t,r){return(new pp).fromJson(t,r)}static fromJsonString(t,r){return(new pp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(pp,t,r)}static $(){return["RsiRepo|1 org 9|2 name 9"]}}class hp extends mp{constructor(t){super(),this.id="",this.kind=fp.UNSPECIFIED,this.recordKey="",this.day="",this.writerBcId="",this.createdAt="",this.updatedAt="",this.bodyJson="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hp).fromBinary(t,r)}static fromJson(t,r){return(new hp).fromJson(t,r)}static fromJsonString(t,r){return(new hp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(hp,t,r)}static $(){return["RsiRecord|1 id 9|2 kind #0|3 record_key 9|4 day 9|5 writer_bc_id 9|6 created_at 9|7 updated_at 9|8 body_json 9",fp]}}class gp extends mp{constructor(t){super(),this.teamId=0,this.kind=fp.UNSPECIFIED,this.recordKey="",this.day="",this.bodyJson="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gp).fromBinary(t,r)}static fromJson(t,r){return(new gp).fromJson(t,r)}static fromJsonString(t,r){return(new gp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(gp,t,r)}static $(){return["AppendRsiRecordRequest|1 team_id 5|2 repo #0|3 kind #1|4 record_key 9|5 day 9|6 body_json 9",pp,fp]}}class _p extends mp{constructor(t){super(),this.id="",this.created=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _p).fromBinary(t,r)}static fromJson(t,r){return(new _p).fromJson(t,r)}static fromJsonString(t,r){return(new _p).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(_p,t,r)}static $(){return["AppendRsiRecordResponse|1 id 9|2 created 8"]}}class Jp extends mp{constructor(t){super(),this.teamId=0,this.kind=fp.UNSPECIFIED,this.recordKey="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jp).fromBinary(t,r)}static fromJson(t,r){return(new Jp).fromJson(t,r)}static fromJsonString(t,r){return(new Jp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Jp,t,r)}static $(){return["GetRsiRecordRequest|1 team_id 5|2 repo #0|3 kind #1|4 record_key 9",pp,fp]}}class wp extends mp{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wp).fromBinary(t,r)}static fromJson(t,r){return(new wp).fromJson(t,r)}static fromJsonString(t,r){return(new wp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(wp,t,r)}static $(){return["GetRsiRecordResponse|1 record #0",hp]}}class yp extends mp{constructor(t){super(),this.teamId=0,this.kind=fp.UNSPECIFIED,this.dayFrom="",this.dayTo="",this.pageSize=0,this.pageToken="",this.includeBody=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yp).fromBinary(t,r)}static fromJson(t,r){return(new yp).fromJson(t,r)}static fromJsonString(t,r){return(new yp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(yp,t,r)}static $(){return["ListRsiRecordsRequest|1 team_id 5|2 repo #0|3 kind #1|4 day_from 9|5 day_to 9|6 page_size 5|7 page_token 9|8 include_body 8",pp,fp]}}class Sp extends mp{constructor(t){super(),this.records=[],this.nextPageToken="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sp).fromBinary(t,r)}static fromJson(t,r){return(new Sp).fromJson(t,r)}static fromJsonString(t,r){return(new Sp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Sp,t,r)}static $(){return["ListRsiRecordsResponse|1 records #0*|2 next_page_token 9",hp]}}class qp extends mp{constructor(t){super(),this.teamId=0,this.day="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qp).fromBinary(t,r)}static fromJson(t,r){return(new qp).fromJson(t,r)}static fromJsonString(t,r){return(new qp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(qp,t,r)}static $(){return["GetRsiSnapshotRequest|1 team_id 5|2 repo #0|3 day 9",pp]}}class Bp extends mp{constructor(t){super(),this.snapshotJson="",this.dayJson="",this.snapshotUpdatedAt="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bp).fromBinary(t,r)}static fromJson(t,r){return(new Bp).fromJson(t,r)}static fromJsonString(t,r){return(new Bp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Bp,t,r)}static $(){return["GetRsiSnapshotResponse|1 snapshot_json 9|2 day_json 9|3 snapshot_updated_at 9"]}}class Ip extends mp{constructor(t){super(),this.workflowId="",this.scheduledAt="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ip).fromBinary(t,r)}static fromJson(t,r){return(new Ip).fromJson(t,r)}static fromJsonString(t,r){return(new Ip).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ip,t,r)}static $(){return["RsiAdminScheduleRun|1 workflow_id 9|2 scheduled_at 9"]}}class Pp extends mp{constructor(t){super(),this.loop=dp.UNSPECIFIED,this.scheduleId="",this.launchEnabled=!1,this.scheduleFound=!1,this.paused=!1,this.note="",this.nextFireTimes=[],this.recentRuns=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pp).fromBinary(t,r)}static fromJson(t,r){return(new Pp).fromJson(t,r)}static fromJsonString(t,r){return(new Pp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Pp,t,r)}static $(){return["RsiAdminLoop|1 loop #0|2 schedule_id 9|3 launch_enabled 8|4 schedule_found 8|5 paused 8|6 note 9|7 next_fire_times 9*|8 recent_runs #1*",dp,Ip]}}class bp extends mp{constructor(t){super(),this.kind=fp.UNSPECIFIED,this.recordKey="",this.day="",this.writerBcId="",this.updatedAt="",this.summaryJson="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bp).fromBinary(t,r)}static fromJson(t,r){return(new bp).fromJson(t,r)}static fromJsonString(t,r){return(new bp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(bp,t,r)}static $(){return["RsiAdminRecord|1 kind #0|2 record_key 9|3 day 9|4 writer_bc_id 9|5 updated_at 9|6 summary_json 9",fp]}}class Rp extends mp{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rp).fromBinary(t,r)}static fromJson(t,r){return(new Rp).fromJson(t,r)}static fromJsonString(t,r){return(new Rp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Rp,t,r)}static $(){return["GetRsiAdminStatusInternalRequest"]}}class vp extends mp{constructor(t){super(),this.controlConfigJson="",this.controlRefusal="",this.controlError="",this.loops=[],this.records=[],s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vp).fromBinary(t,r)}static fromJson(t,r){return(new vp).fromJson(t,r)}static fromJsonString(t,r){return(new vp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(vp,t,r)}static $(){return["GetRsiAdminStatusInternalResponse|1 repo #0|2 control_config_json 9|3 control_refusal 9|4 control_error 9|5 loops #1*|6 records #2*",pp,Pp,bp]}}class xp extends mp{constructor(t){super(),this.loop=dp.UNSPECIFIED,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xp).fromBinary(t,r)}static fromJson(t,r){return(new xp).fromJson(t,r)}static fromJsonString(t,r){return(new xp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(xp,t,r)}static $(){return["RunRsiLoopNowInternalRequest|1 loop #0",dp]}}class kp extends mp{constructor(t){super(),this.workflowId="",this.outcome="",this.slot="",this.bcId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kp).fromBinary(t,r)}static fromJson(t,r){return(new kp).fromJson(t,r)}static fromJsonString(t,r){return(new kp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(kp,t,r)}static $(){return["RunRsiLoopNowInternalResponse|1 workflow_id 9|2 outcome 9|3 slot 9|4 bc_id 9"]}}class Ep extends mp{constructor(t){super(),this.loop=dp.UNSPECIFIED,this.paused=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ep).fromBinary(t,r)}static fromJson(t,r){return(new Ep).fromJson(t,r)}static fromJsonString(t,r){return(new Ep).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ep,t,r)}static $(){return["SetRsiLoopPausedInternalRequest|1 loop #0|2 paused 8",dp]}}class Cp extends mp{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cp).fromBinary(t,r)}static fromJson(t,r){return(new Cp).fromJson(t,r)}static fromJsonString(t,r){return(new Cp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Cp,t,r)}static $(){return["SetRsiLoopPausedInternalResponse|1 loop #0",Pp]}}class Tp extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",s.proto3)}static $p(){return"aiserver.v1."}}class Up extends Tp{constructor(t){super(),this.teamId=0,this.serviceAccountId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Up).fromBinary(t,r)}static fromJson(t,r){return(new Up).fromJson(t,r)}static fromJsonString(t,r){return(new Up).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Up,t,r)}static $(){return["SuspendTeamServiceAccountRequest|1 team_id 5|2 service_account_id 9"]}}class Ap extends Tp{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ap).fromBinary(t,r)}static fromJson(t,r){return(new Ap).fromJson(t,r)}static fromJsonString(t,r){return(new Ap).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Ap,t,r)}static $(){return["SuspendTeamServiceAccountResponse"]}}class $p extends Tp{constructor(t){super(),this.teamId=0,this.serviceAccountId="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $p).fromBinary(t,r)}static fromJson(t,r){return(new $p).fromJson(t,r)}static fromJsonString(t,r){return(new $p).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals($p,t,r)}static $(){return["ResumeTeamServiceAccountRequest|1 team_id 5|2 service_account_id 9"]}}class Mp extends Tp{constructor(t){super(),s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mp).fromBinary(t,r)}static fromJson(t,r){return(new Mp).fromJson(t,r)}static fromJsonString(t,r){return(new Mp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Mp,t,r)}static $(){return["ResumeTeamServiceAccountResponse"]}}const Op="aiserver.v1.";class Dp extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",s.proto3)}static $p(){return Op}}var Np=(0,i.QT)(s.proto3,Op,"XaiSubscriptionPlan",[[0,"UNSPECIFIED"],[1,"XPASS_PLUS"],[2,"XPASS_PREMIUM"],[3,"XPASS_SUPER"],[4,"XPASS_ULTRA"]],1);class Gp extends Dp{constructor(t){super(),this.cursorUserId=0,this.plan=Np.UNSPECIFIED,this.endsAt="",this.idempotencyKey="",this.grantedBy="",this.reason="",this.cursorTeamId=0,this.seats=0,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gp).fromBinary(t,r)}static fromJson(t,r){return(new Gp).fromJson(t,r)}static fromJsonString(t,r){return(new Gp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Gp,t,r)}static $(){return["GrantSubscriptionRequest|1 cursor_user_id 5|2 plan #0|3 ends_at 9|4 idempotency_key 9|5 granted_by 9|6 reason 9|7 cursor_team_id 5|8 seats 5",Np]}}class Lp extends Dp{constructor(t){super(),this.outcome={case:void 0},s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lp).fromBinary(t,r)}static fromJson(t,r){return(new Lp).fromJson(t,r)}static fromJsonString(t,r){return(new Lp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Lp,t,r)}static $(){return["GrantSubscriptionResponse|1 result #0 outcome|2 error #1 outcome",Fp,Kp]}}class Fp extends Dp{constructor(t){super(),this.xaiUserId="",this.subscriptionId="",this.alreadyGranted=!1,s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fp).fromBinary(t,r)}static fromJson(t,r){return(new Fp).fromJson(t,r)}static fromJsonString(t,r){return(new Fp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Fp,t,r)}static $(){return["GrantSubscriptionResult|1 xai_user_id 9|2 subscription_id 9|3 already_granted 8"]}}class Kp extends Dp{constructor(t){super(),this.code="",this.message="",s.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kp).fromBinary(t,r)}static fromJson(t,r){return(new Kp).fromJson(t,r)}static fromJsonString(t,r){return(new Kp).fromJsonString(t,r)}static equals(t,r){return s.proto3.util.equals(Kp,t,r)}static $(){return["GrantSubscriptionError|1 code 9|2 message 9"]}}const zp={typeName:"aiserver.v1.DashboardService",methods:{getTeams:{name:"GetTeams",I:n.EZo,O:n.m0q,kind:s.MethodKind.Unary},getMe:{name:"GetMe",I:n.Ewt,O:n.S7I,kind:s.MethodKind.Unary},getUnificationLegacySuperGrokPlan:{name:"GetUnificationLegacySuperGrokPlan",I:vt,O:xt,kind:s.MethodKind.Unary},getUnifyEligibility:{name:"GetUnifyEligibility",I:m,O:f,kind:s.MethodKind.Unary},getUnifyPendingMerge:{name:"GetUnifyPendingMerge",I:h,O:g,kind:s.MethodKind.Unary},getPostPurchaseMergeOffer:{name:"GetPostPurchaseMergeOffer",I:Zn,O:ts,kind:s.MethodKind.Unary},getUnifyMergeNowBanner:{name:"GetUnifyMergeNowBanner",I:rs,O:es,kind:s.MethodKind.Unary},getUnifyWaitlistStatus:{name:"GetUnifyWaitlistStatus",I:Qn,O:Vn,kind:s.MethodKind.Unary},joinUnifyWaitlist:{name:"JoinUnifyWaitlist",I:Xn,O:Yn,kind:s.MethodKind.Unary},listCollapseCandidates:{name:"ListCollapseCandidates",I:kt,O:At,kind:s.MethodKind.Unary},getUnificationIntent:{name:"GetUnificationIntent",I:Ot,O:Ft,kind:s.MethodKind.Unary},getStoreSubscriptionsToCancel:{name:"GetStoreSubscriptionsToCancel",I:Dt,O:Lt,kind:s.MethodKind.Unary},getIndividualUnificationPrepaidPreview:{name:"GetIndividualUnificationPrepaidPreview",I:zt,O:jt,kind:s.MethodKind.Unary},upsertUnificationIntent:{name:"UpsertUnificationIntent",I:Ht,O:Wt,kind:s.MethodKind.Unary},startUnifyGrokOAuth:{name:"StartUnifyGrokOAuth",I:Qt,O:Vt,kind:s.MethodKind.Unary},completeUnifyGrokOAuth:{name:"CompleteUnifyGrokOAuth",I:Xt,O:er,kind:s.MethodKind.Unary},confirmUnifyGrokUnlinkAtConflict:{name:"ConfirmUnifyGrokUnlinkAtConflict",I:Xt,O:er,kind:s.MethodKind.Unary},startTeamInviteGrokBind:{name:"StartTeamInviteGrokBind",I:Yt,O:Zt,kind:s.MethodKind.Unary},getTeamInviteGrokBindStatus:{name:"GetTeamInviteGrokBindStatus",I:tr,O:rr,kind:s.MethodKind.Unary},parkUnifyGrokOAuthForAppSheet:{name:"ParkUnifyGrokOAuthForAppSheet",I:Rn,O:vn,kind:s.MethodKind.Unary},completeUnifyGrokOAuthFromAppSheet:{name:"CompleteUnifyGrokOAuthFromAppSheet",I:xn,O:er,kind:s.MethodKind.Unary},getUnifyAlreadyUnifiedMergeOffer:{name:"GetUnifyAlreadyUnifiedMergeOffer",I:kn,O:En,kind:s.MethodKind.Unary},startUnifyAlreadyUnifiedMerge:{name:"StartUnifyAlreadyUnifiedMerge",I:Cn,O:Tn,kind:s.MethodKind.Unary},cancelUnifyAlreadyUnifiedMerge:{name:"CancelUnifyAlreadyUnifiedMerge",I:Un,O:An,kind:s.MethodKind.Unary},startUnifyXLogin:{name:"StartUnifyXLogin",I:ar,O:ur,kind:s.MethodKind.Unary},completeUnifyXLogin:{name:"CompleteUnifyXLogin",I:cr,O:lr,kind:s.MethodKind.Unary},verifyUnifyXLoginEmail:{name:"VerifyUnifyXLoginEmail",I:mr,O:lr,kind:s.MethodKind.Unary},parkUnifyXLoginForAppSheet:{name:"ParkUnifyXLoginForAppSheet",I:Kn,O:zn,kind:s.MethodKind.Unary},completeUnifyXLoginFromAppSheet:{name:"CompleteUnifyXLoginFromAppSheet",I:jn,O:lr,kind:s.MethodKind.Unary},startCollapseSourceProof:{name:"StartCollapseSourceProof",I:fr,O:dr,kind:s.MethodKind.Unary},completeCollapseSourceProof:{name:"CompleteCollapseSourceProof",I:pr,O:hr,kind:s.MethodKind.Unary},revokeCollapseSourceProof:{name:"RevokeCollapseSourceProof",I:gr,O:_r,kind:s.MethodKind.Unary},provisionUnifyGrokAccount:{name:"ProvisionUnifyGrokAccount",I:Jr,O:wr,kind:s.MethodKind.Unary},finalizeIndividualUnification:{name:"FinalizeIndividualUnification",I:qr,O:Ir,kind:s.MethodKind.Unary},getUnifyCta:{name:"GetUnifyCta",I:yr,O:Sr,kind:s.MethodKind.Unary},startUnifiedCheckout:{name:"StartUnifiedCheckout",I:In,O:Pn,kind:s.MethodKind.Unary},resolveUnifiedTeamStart:{name:"ResolveUnifiedTeamStart",I:Mn,O:On,kind:s.MethodKind.Unary},startUnifiedTeamCheckout:{name:"StartUnifiedTeamCheckout",I:Nn,O:Gn,kind:s.MethodKind.Unary},createGrokSignInLink:{name:"CreateGrokSignInLink",I:Ln,O:Fn,kind:s.MethodKind.Unary},getOrCreateXaiUnificationIntent:{name:"GetOrCreateXaiUnificationIntent",I:Pr,O:br,kind:s.MethodKind.Unary},getXaiUnificationIntent:{name:"GetXaiUnificationIntent",I:Rr,O:xr,kind:s.MethodKind.Unary},selectXaiUnificationCursorAccount:{name:"SelectXaiUnificationCursorAccount",I:kr,O:Er,kind:s.MethodKind.Unary},deselectXaiUnificationCursorAccount:{name:"DeselectXaiUnificationCursorAccount",I:Ur,O:Ar,kind:s.MethodKind.Unary},unlinkXaiUnificationCursorAccount:{name:"UnlinkXaiUnificationCursorAccount",I:Cr,O:Tr,kind:s.MethodKind.Unary},listXaiUnificationCollapseCandidates:{name:"ListXaiUnificationCollapseCandidates",I:$r,O:At,kind:s.MethodKind.Unary},startXaiUnificationCursorAccountProof:{name:"StartXaiUnificationCursorAccountProof",I:Mr,O:Or,kind:s.MethodKind.Unary},completeXaiUnificationCursorAccountProof:{name:"CompleteXaiUnificationCursorAccountProof",I:Dr,O:Nr,kind:s.MethodKind.Unary},advanceXaiUnificationIntent:{name:"AdvanceXaiUnificationIntent",I:Gr,O:Lr,kind:s.MethodKind.Unary},startXaiCursorAccountLink:{name:"StartXaiCursorAccountLink",I:Fr,O:Kr,kind:s.MethodKind.Unary},completeXaiCursorAccountLink:{name:"CompleteXaiCursorAccountLink",I:zr,O:jr,kind:s.MethodKind.Unary},peekXaiCursorAccountLinkContinuation:{name:"PeekXaiCursorAccountLinkContinuation",I:Hr,O:Wr,kind:s.MethodKind.Unary},getAgenticOnboardingConfig:{name:"GetAgenticOnboardingConfig",I:n.CQB,O:n.WQf,kind:s.MethodKind.Unary},getUserOrganizations:{name:"GetUserOrganizations",I:n.V2d,O:n.NjL,kind:s.MethodKind.Unary},getTeamLinkedOrganization:{name:"GetTeamLinkedOrganization",I:n.Pxo,O:n.RR2,kind:s.MethodKind.Unary},setUserDefaultTeam:{name:"SetUserDefaultTeam",I:n.tol,O:n.b0C,kind:s.MethodKind.Unary},getOrganizationMembers:{name:"GetOrganizationMembers",I:n.cF_,O:n.SY0,kind:s.MethodKind.Unary},getOrganizationMember:{name:"GetOrganizationMember",I:n.lN3,O:n.vBH,kind:s.MethodKind.Unary},listOrganizationIdentityProviders:{name:"ListOrganizationIdentityProviders",I:n.rq6,O:n.dSe,kind:s.MethodKind.Unary},updateOrganizationIdentityProviderSsoSettings:{name:"UpdateOrganizationIdentityProviderSsoSettings",I:n.XwO,O:n.BDH,kind:s.MethodKind.Unary},setOrganizationIdentityProviderAllowDomainJoin:{name:"SetOrganizationIdentityProviderAllowDomainJoin",I:n.bpP,O:n.BDH,kind:s.MethodKind.Unary},addOrganizationIdentityProviderDomainJoin:{name:"AddOrganizationIdentityProviderDomainJoin",I:n.$n5,O:n.BDH,kind:s.MethodKind.Unary},removeOrganizationIdentityProviderDomainJoin:{name:"RemoveOrganizationIdentityProviderDomainJoin",I:n.SFI,O:n.BDH,kind:s.MethodKind.Unary},mergeOrganizationIdentityProvider:{name:"MergeOrganizationIdentityProvider",I:n.SAH,O:n.mOD,kind:s.MethodKind.Unary},preflightMergeOrganizationIdentityProvider:{name:"PreflightMergeOrganizationIdentityProvider",I:n.FMO,O:n.PUH,kind:s.MethodKind.Unary},getOrganizationMergeIdpRequest:{name:"GetOrganizationMergeIdpRequest",I:n.bXT,O:n.TQ7,kind:s.MethodKind.Unary},listOrganizationMergeIdpRequests:{name:"ListOrganizationMergeIdpRequests",I:n.Y1Y,O:n.G2s,kind:s.MethodKind.Unary},moveOrganizationMemberToTeam:{name:"MoveOrganizationMemberToTeam",I:n.kiI,O:n.gqE,kind:s.MethodKind.Unary},setOrganizationMemberTeams:{name:"SetOrganizationMemberTeams",I:n.NW8,O:n.tP0,kind:s.MethodKind.Unary},removeOrganizationMember:{name:"RemoveOrganizationMember",I:n.rLu,O:n.Puo,kind:s.MethodKind.Unary},bulkMoveOrganizationMembers:{name:"BulkMoveOrganizationMembers",I:n.VN4,O:n.nPy,kind:s.MethodKind.Unary},startBulkMoveOrganizationMembers:{name:"StartBulkMoveOrganizationMembers",I:n.piC,O:n.T_o,kind:s.MethodKind.Unary},getBackgroundJob:{name:"GetBackgroundJob",I:n.Nbg,O:n.xel,kind:s.MethodKind.Unary},setOrganizationMemberRole:{name:"SetOrganizationMemberRole",I:n.xBJ,O:n.jFq,kind:s.MethodKind.Unary},updateOrganization:{name:"UpdateOrganization",I:n.SC0,O:n.kz1,kind:s.MethodKind.Unary},uploadOrganizationIcon:{name:"UploadOrganizationIcon",I:n.Jt2,O:n.Fmo,kind:s.MethodKind.Unary},updateOrganizationIcon:{name:"UpdateOrganizationIcon",I:n.DqU,O:n.X99,kind:s.MethodKind.Unary},updateOrganizationTeam:{name:"UpdateOrganizationTeam",I:n.Dmk,O:n.RAD,kind:s.MethodKind.Unary},createOrganizationTeam:{name:"CreateOrganizationTeam",I:n.iQx,O:n.uYE,kind:s.MethodKind.Unary},startEnterpriseGrokMigration:{name:"StartEnterpriseGrokMigration",I:ee,O:ne,kind:s.MethodKind.Unary},getEnterpriseGrokMigrationStatus:{name:"GetEnterpriseGrokMigrationStatus",I:se,O:ie,kind:s.MethodKind.Unary},getOrganizationScimSource:{name:"GetOrganizationScimSource",I:n._J0,O:n.OBE,kind:s.MethodKind.Unary},checkEnterpriseGrokMigrationEligibility:{name:"CheckEnterpriseGrokMigrationEligibility",I:te,O:re,kind:s.MethodKind.Unary},previewOrganizationTeamSettingsCopy:{name:"PreviewOrganizationTeamSettingsCopy",I:n.CrG,O:n.YQr,kind:s.MethodKind.Unary},copyOrganizationTeamSettingsToTeam:{name:"CopyOrganizationTeamSettingsToTeam",I:n.ign,O:n.WSJ,kind:s.MethodKind.Unary},listOrganizationTeamSettingsCopySources:{name:"ListOrganizationTeamSettingsCopySources",I:n.YNI,O:n.yaP,kind:s.MethodKind.Unary},getOrganizationTeamAdminCandidates:{name:"GetOrganizationTeamAdminCandidates",I:n.rgp,O:n.xa_,kind:s.MethodKind.Unary},getDirectoryGroups:{name:"GetDirectoryGroups",I:n.LYo,O:n.PJy,kind:s.MethodKind.Unary},updateDirectoryGroupSettings:{name:"UpdateDirectoryGroupSettings",I:n.kFu,O:n.Mpk,kind:s.MethodKind.Unary},getOrganizationGroups:{name:"GetOrganizationGroups",I:n.f5k,O:n.ZJV,kind:s.MethodKind.Unary},getOrganizationGroup:{name:"GetOrganizationGroup",I:n.wH4,O:n.uwp,kind:s.MethodKind.Unary},getOrganizationGroupMembers:{name:"GetOrganizationGroupMembers",I:n.nQH,O:n.rd8,kind:s.MethodKind.Unary},createOrganizationGroup:{name:"CreateOrganizationGroup",I:n.ed4,O:n.urU,kind:s.MethodKind.Unary},updateOrganizationGroup:{name:"UpdateOrganizationGroup",I:n.Bhj,O:n.LBR,kind:s.MethodKind.Unary},deleteOrganizationGroup:{name:"DeleteOrganizationGroup",I:n.pe4,O:n.Huq,kind:s.MethodKind.Unary},addOrganizationGroupMembers:{name:"AddOrganizationGroupMembers",I:n.U8V,O:n.mf3,kind:s.MethodKind.Unary},removeOrganizationGroupMembers:{name:"RemoveOrganizationGroupMembers",I:n.xQP,O:n.TGX,kind:s.MethodKind.Unary},updateOrganizationGroupMember:{name:"UpdateOrganizationGroupMember",I:n.rj1,O:n.jWT,kind:s.MethodKind.Unary},getOrganizationGroupServiceAccountMembers:{name:"GetOrganizationGroupServiceAccountMembers",I:n.bPz,O:n.H0j,kind:s.MethodKind.Unary},getOrganizationServiceAccounts:{name:"GetOrganizationServiceAccounts",I:n.Exr,O:n.aYg,kind:s.MethodKind.Unary},addOrganizationGroupServiceAccounts:{name:"AddOrganizationGroupServiceAccounts",I:n.ggo,O:n.aHm,kind:s.MethodKind.Unary},removeOrganizationGroupServiceAccounts:{name:"RemoveOrganizationGroupServiceAccounts",I:n.dSX,O:n.nS1,kind:s.MethodKind.Unary},getOrganizationGroupAutorunSettings:{name:"GetOrganizationGroupAutorunSettings",I:n.ZKL,O:n.f43,kind:s.MethodKind.Unary},updateOrganizationGroupAutorunSettings:{name:"UpdateOrganizationGroupAutorunSettings",I:n.Cwp,O:n._i8,kind:s.MethodKind.Unary},getOrganizationGroupMcpSettings:{name:"GetOrganizationGroupMcpSettings",I:Us,O:$s,kind:s.MethodKind.Unary},updateOrganizationGroupMcpSettings:{name:"UpdateOrganizationGroupMcpSettings",I:Ms,O:Os,kind:s.MethodKind.Unary},exportOrganizationGroupMcpAllowlist:{name:"ExportOrganizationGroupMcpAllowlist",I:Ds,O:Ns,kind:s.MethodKind.Unary},importOrganizationGroupMcpAllowlist:{name:"ImportOrganizationGroupMcpAllowlist",I:Hs,O:Ws,kind:s.MethodKind.Unary},exportTeamMcpAllowlist:{name:"ExportTeamMcpAllowlist",I:Gs,O:Ls,kind:s.MethodKind.Unary},importTeamMcpAllowlist:{name:"ImportTeamMcpAllowlist",I:Qs,O:Vs,kind:s.MethodKind.Unary},getTeamCloudAgentMcpAllowlist:{name:"GetTeamCloudAgentMcpAllowlist",I:Xs,O:Ys,kind:s.MethodKind.Unary},updateTeamCloudAgentMcpAllowlist:{name:"UpdateTeamCloudAgentMcpAllowlist",I:Zs,O:ti,kind:s.MethodKind.Unary},listMcpAllowlistRuleMatches:{name:"ListMcpAllowlistRuleMatches",I:ei,O:ai,kind:s.MethodKind.Unary,idempotency:s.MethodIdempotency.NoSideEffects},resetOrganizationGroupAgentRunModeToAutoReview:{name:"ResetOrganizationGroupAgentRunModeToAutoReview",I:n.ePV,O:n.EuD,kind:s.MethodKind.Unary},getOrganizationGroupModelAllowlist:{name:"GetOrganizationGroupModelAllowlist",I:n.M89,O:n.qlA,kind:s.MethodKind.Unary},updateOrganizationGroupModelAllowlist:{name:"UpdateOrganizationGroupModelAllowlist",I:n.$bH,O:n.nCl,kind:s.MethodKind.Unary},getOrganizationGroupAutoReviewSettings:{name:"GetOrganizationGroupAutoReviewSettings",I:n.QOh,O:n.qbQ,kind:s.MethodKind.Unary},updateOrganizationGroupAutoReviewSettings:{name:"UpdateOrganizationGroupAutoReviewSettings",I:n.DtR,O:n.dDc,kind:s.MethodKind.Unary},getOrganizationGroupSmartAutoSettings:{name:"GetOrganizationGroupSmartAutoSettings",I:n.H8G,O:n.rt0,kind:s.MethodKind.Unary},updateOrganizationGroupSmartAutoSettings:{name:"UpdateOrganizationGroupSmartAutoSettings",I:n.Yir,O:n.GDG,kind:s.MethodKind.Unary},createOrganizationGroupAnthropicCyberEnrollmentUrl:{name:"CreateOrganizationGroupAnthropicCyberEnrollmentUrl",I:n.C1F,O:n.wqi,kind:s.MethodKind.Unary},requestOrganizationGroupAnthropicEfs:{name:"RequestOrganizationGroupAnthropicEfs",I:n.rF_,O:n.DmQ,kind:s.MethodKind.Unary},requestOrganizationAnthropicEfs:{name:"RequestOrganizationAnthropicEfs",I:n.Y6P,O:n.QeE,kind:s.MethodKind.Unary},getOrganizationAnthropicEfsStatus:{name:"GetOrganizationAnthropicEfsStatus",I:n.BHf,O:n.lqZ,kind:s.MethodKind.Unary},reviewAnthropicEfsRequestInternal:{name:"ReviewAnthropicEfsRequestInternal",I:n.ovZ,O:n.gdR,kind:s.MethodKind.Unary},getTeamGroups:{name:"GetTeamGroups",I:n.JbB,O:n.nrv,kind:s.MethodKind.Unary},getTeamGroup:{name:"GetTeamGroup",I:n.UQh,O:n.cUB,kind:s.MethodKind.Unary},getTeamGroupMembers:{name:"GetTeamGroupMembers",I:n.J67,O:n.VBR,kind:s.MethodKind.Unary},getTeamGroupServiceAccountMembers:{name:"GetTeamGroupServiceAccountMembers",I:n.DWT,O:n.hSD,kind:s.MethodKind.Unary},createTeamGroup:{name:"CreateTeamGroup",I:n.cbD,O:n.CiW,kind:s.MethodKind.Unary},updateTeamGroup:{name:"UpdateTeamGroup",I:n.NS0,O:n.JL8,kind:s.MethodKind.Unary},deleteTeamGroup:{name:"DeleteTeamGroup",I:n.p9b,O:n.VyS,kind:s.MethodKind.Unary},addTeamGroupMembers:{name:"AddTeamGroupMembers",I:n.yqO,O:n.Gc8,kind:s.MethodKind.Unary},removeTeamGroupMembers:{name:"RemoveTeamGroupMembers",I:n.rA4,O:n.lER,kind:s.MethodKind.Unary},addTeamGroupServiceAccounts:{name:"AddTeamGroupServiceAccounts",I:n.Ipj,O:n.a0c,kind:s.MethodKind.Unary},removeTeamGroupServiceAccounts:{name:"RemoveTeamGroupServiceAccounts",I:n.X6C,O:n.$Fl,kind:s.MethodKind.Unary},updateTeamGroupMember:{name:"UpdateTeamGroupMember",I:n.jG,O:n.jFj,kind:s.MethodKind.Unary},getTeamGroupAutorunSettings:{name:"GetTeamGroupAutorunSettings",I:n.bK1,O:n.bJ,kind:s.MethodKind.Unary},updateTeamGroupAutorunSettings:{name:"UpdateTeamGroupAutorunSettings",I:n.KTu,O:n._$O,kind:s.MethodKind.Unary},getTeamGroupMcpSettings:{name:"GetTeamGroupMcpSettings",I:ui,O:_i,kind:s.MethodKind.Unary},updateTeamGroupMcpSettings:{name:"UpdateTeamGroupMcpSettings",I:Ji,O:wi,kind:s.MethodKind.Unary},getTeamMemberEffectiveMcpPolicy:{name:"GetTeamMemberEffectiveMcpPolicy",I:pi,O:hi,kind:s.MethodKind.Unary},listBuiltinMcpServerTools:{name:"ListBuiltinMcpServerTools",I:yi,O:Si,kind:s.MethodKind.Unary},exportTeamGroupMcpAllowlist:{name:"ExportTeamGroupMcpAllowlist",I:qi,O:Bi,kind:s.MethodKind.Unary},importTeamGroupMcpAllowlist:{name:"ImportTeamGroupMcpAllowlist",I:Ii,O:Pi,kind:s.MethodKind.Unary},resetTeamGroupAgentRunModeToAutoReview:{name:"ResetTeamGroupAgentRunModeToAutoReview",I:n.I3c,O:n.Qnc,kind:s.MethodKind.Unary},getTeamGroupModelAllowlist:{name:"GetTeamGroupModelAllowlist",I:n.s$M,O:n.MJ,kind:s.MethodKind.Unary},updateTeamGroupModelAllowlist:{name:"UpdateTeamGroupModelAllowlist",I:n.pbs,O:n.PD$,kind:s.MethodKind.Unary},getTeamGroupAutoReviewSettings:{name:"GetTeamGroupAutoReviewSettings",I:n.Mx4,O:n.gDX,kind:s.MethodKind.Unary},updateTeamGroupAutoReviewSettings:{name:"UpdateTeamGroupAutoReviewSettings",I:n.dXc,O:n.zF8,kind:s.MethodKind.Unary},getTeamSandNetworkSettings:{name:"GetTeamSandNetworkSettings",I:gu,O:_u,kind:s.MethodKind.Unary},getTeamGrokBotTrial:{name:"GetTeamGrokBotTrial",I:Pu,O:bu,kind:s.MethodKind.Unary},listTeamGrokBotAgentsAdmin:{name:"ListTeamGrokBotAgentsAdmin",I:Eu,O:Uu,kind:s.MethodKind.Unary},getTeamGrokBotRoiPreview:{name:"GetTeamGrokBotRoiPreview",I:Au,O:Ou,kind:s.MethodKind.Unary},getTeamGrokBotRoiBot:{name:"GetTeamGrokBotRoiBot",I:Du,O:zu,kind:s.MethodKind.Unary},updateTeamSandNetworkSettings:{name:"UpdateTeamSandNetworkSettings",I:ju,O:Hu,kind:s.MethodKind.Unary},getTeamSandTrustedCaCertificates:{name:"GetTeamSandTrustedCaCertificates",I:Wu,O:Qu,kind:s.MethodKind.Unary},updateTeamSandTrustedCaCertificates:{name:"UpdateTeamSandTrustedCaCertificates",I:Vu,O:Xu,kind:s.MethodKind.Unary},getTeamSandLocalEgressPrivateDestinations:{name:"GetTeamSandLocalEgressPrivateDestinations",I:Zu,O:tc,kind:s.MethodKind.Unary},updateTeamSandLocalEgressPrivateDestinations:{name:"UpdateTeamSandLocalEgressPrivateDestinations",I:rc,O:ec,kind:s.MethodKind.Unary},getTeamIngressIpAllowlist:{name:"GetTeamIngressIpAllowlist",I:n.Y44,O:n.kE_,kind:s.MethodKind.Unary},updateTeamIngressIpAllowlist:{name:"UpdateTeamIngressIpAllowlist",I:n.vq0,O:n.npe,kind:s.MethodKind.Unary},getOrganizationIngressIpAllowlist:{name:"GetOrganizationIngressIpAllowlist",I:n.UvC,O:n.SkP,kind:s.MethodKind.Unary},updateOrganizationIngressIpAllowlist:{name:"UpdateOrganizationIngressIpAllowlist",I:n.vvr,O:n.J3N,kind:s.MethodKind.Unary},getOrganizationNetworkBlocklist:{name:"GetOrganizationNetworkBlocklist",I:n.YtZ,O:n.UZr,kind:s.MethodKind.Unary},createOrganizationNetworkBlocklistUpload:{name:"CreateOrganizationNetworkBlocklistUpload",I:n.JoU,O:n.vU,kind:s.MethodKind.Unary},commitOrganizationNetworkBlocklistUpload:{name:"CommitOrganizationNetworkBlocklistUpload",I:n.KBr,O:n.EAu,kind:s.MethodKind.Unary},createOrganizationNetworkBlocklistExport:{name:"CreateOrganizationNetworkBlocklistExport",I:n.Cqw,O:n.mk5,kind:s.MethodKind.Unary},setOrganizationNetworkBlocklistEnabled:{name:"SetOrganizationNetworkBlocklistEnabled",I:n.$VK,O:n.tfN,kind:s.MethodKind.Unary},getTeamSandEgressHttpRules:{name:"GetTeamSandEgressHttpRules",I:Su,O:qu,kind:s.MethodKind.Unary},updateTeamSandEgressHttpRules:{name:"UpdateTeamSandEgressHttpRules",I:Bu,O:Iu,kind:s.MethodKind.Unary},getTeamTailnet:{name:"GetTeamTailnet",I:Td,O:Ud,kind:s.MethodKind.Unary},updateTeamTailnet:{name:"UpdateTeamTailnet",I:Fd,O:Kd,kind:s.MethodKind.Unary},updateTeamTailnetCompanyCa:{name:"UpdateTeamTailnetCompanyCa",I:zd,O:jd,kind:s.MethodKind.Unary},updateTeamTailnetBoxAccess:{name:"UpdateTeamTailnetBoxAccess",I:Hd,O:Wd,kind:s.MethodKind.Unary},updateTeamTailnetExitNode:{name:"UpdateTeamTailnetExitNode",I:Qd,O:Vd,kind:s.MethodKind.Unary},discoverTeamTailnetSuffix:{name:"DiscoverTeamTailnetSuffix",I:Xd,O:Yd,kind:s.MethodKind.Unary},setActiveTailnet:{name:"SetActiveTailnet",I:Dd,O:Nd,kind:s.MethodKind.Unary},getTeamGroupSandNetworkSettings:{name:"GetTeamGroupSandNetworkSettings",I:nc,O:sc,kind:s.MethodKind.Unary},updateTeamGroupSandNetworkSettings:{name:"UpdateTeamGroupSandNetworkSettings",I:ic,O:oc,kind:s.MethodKind.Unary},getTeamGroupGrokBotCapabilities:{name:"GetTeamGroupGrokBotCapabilities",I:cc,O:lc,kind:s.MethodKind.Unary},updateTeamGroupGrokBotCapabilities:{name:"UpdateTeamGroupGrokBotCapabilities",I:mc,O:fc,kind:s.MethodKind.Unary},getTeamGroupSmartAutoSettings:{name:"GetTeamGroupSmartAutoSettings",I:n.hu7,O:n.BPt,kind:s.MethodKind.Unary},updateTeamGroupSmartAutoSettings:{name:"UpdateTeamGroupSmartAutoSettings",I:n.Gor,O:n.WWO,kind:s.MethodKind.Unary},createTeamGroupAnthropicCyberEnrollmentUrl:{name:"CreateTeamGroupAnthropicCyberEnrollmentUrl",I:n.oJv,O:n.UPX,kind:s.MethodKind.Unary},requestTeamGroupAnthropicEfs:{name:"RequestTeamGroupAnthropicEfs",I:n.be7,O:n.THz,kind:s.MethodKind.Unary},getTeamAnthropicEfsStatus:{name:"GetTeamAnthropicEfsStatus",I:n.TdK,O:n.v6H,kind:s.MethodKind.Unary},listTeamGroupScimDirectories:{name:"ListTeamGroupScimDirectories",I:n.DEE,O:n.xUt,kind:s.MethodKind.Unary},listTeamGroupScimGroupsFromUpstream:{name:"ListTeamGroupScimGroupsFromUpstream",I:n.nsd,O:n.xYI,kind:s.MethodKind.Unary},listTeamGroupScimTargetMappings:{name:"ListTeamGroupScimTargetMappings",I:n.QE,O:n.gsU,kind:s.MethodKind.Unary},createTeamGroupScimTargetMapping:{name:"CreateTeamGroupScimTargetMapping",I:n.lW,O:n.$a1,kind:s.MethodKind.Unary},deleteTeamGroupScimTargetMapping:{name:"DeleteTeamGroupScimTargetMapping",I:n.mA,O:n.U1k,kind:s.MethodKind.Unary},getGroups:{name:"GetGroups",I:n.CY$,O:n.WsC,kind:s.MethodKind.Unary},getGroupMembers:{name:"GetGroupMembers",I:n.i$e,O:n.StO,kind:s.MethodKind.Unary},createGroup:{name:"CreateGroup",I:n.p8r,O:n.Dsz,kind:s.MethodKind.Unary},updateGroup:{name:"UpdateGroup",I:n.Eh9,O:n.wrT,kind:s.MethodKind.Unary},deleteGroup:{name:"DeleteGroup",I:n.SBx,O:n.uDb,kind:s.MethodKind.Unary},addGroupMembers:{name:"AddGroupMembers",I:n.Hcr,O:n.he9,kind:s.MethodKind.Unary},removeGroupMembers:{name:"RemoveGroupMembers",I:n.im6,O:n.SSe,kind:s.MethodKind.Unary},bulkAssignGroupMembers:{name:"BulkAssignGroupMembers",I:n.t3S,O:n.PXK,kind:s.MethodKind.Unary},previewAttachGroupToDirectory:{name:"PreviewAttachGroupToDirectory",I:n.OeX,O:n.Wow,kind:s.MethodKind.Unary},detachGroupFromDirectory:{name:"DetachGroupFromDirectory",I:n.tm2,O:n.prK,kind:s.MethodKind.Unary},getScimConflicts:{name:"GetScimConflicts",I:n.l9M,O:n.nPZ,kind:s.MethodKind.Unary},listScimDirectories:{name:"ListScimDirectories",I:n.Dxu,O:n.LM8,kind:s.MethodKind.Unary},getOrganizationScimConfigurationLinks:{name:"GetOrganizationScimConfigurationLinks",I:n.Dxu,O:n.C61,kind:s.MethodKind.Unary},createScimDirectory:{name:"CreateScimDirectory",I:n.BwS,O:n.dnd,kind:s.MethodKind.Unary},updateScimDirectorySyncSettings:{name:"UpdateScimDirectorySyncSettings",I:n.Spq,O:n.YCH,kind:s.MethodKind.Unary},deleteScimDirectory:{name:"DeleteScimDirectory",I:n.gwk,O:n.CN_,kind:s.MethodKind.Unary},listScimGroupsFromUpstream:{name:"ListScimGroupsFromUpstream",I:n.lmw,O:n.na4,kind:s.MethodKind.Unary},listScimTargetMappings:{name:"ListScimTargetMappings",I:n.OWn,O:n.c3u,kind:s.MethodKind.Unary},listOrganizationGroupTargetMappings:{name:"ListOrganizationGroupTargetMappings",I:n.UTl,O:n.i4X,kind:s.MethodKind.Unary},createScimTargetMapping:{name:"CreateScimTargetMapping",I:n.PwZ,O:n.vFW,kind:s.MethodKind.Unary},deleteScimTargetMapping:{name:"DeleteScimTargetMapping",I:n.gFI,O:n.c7s,kind:s.MethodKind.Unary},getActivationCheckoutUrl:{name:"GetActivationCheckoutUrl",I:n.hWx,O:n.dr7,kind:s.MethodKind.Unary},checkPromotionEligibility:{name:"CheckPromotionEligibility",I:n.yD0,O:n.MEI,kind:s.MethodKind.Unary},activatePromotion:{name:"ActivatePromotion",I:n.uHx,O:n.yDS,kind:s.MethodKind.Unary},getTeamCustomerPortalUrl:{name:"GetTeamCustomerPortalUrl",I:n.qjo,O:n.M_,kind:s.MethodKind.Unary},cancelPendingTeamSubscriptionNow:{name:"CancelPendingTeamSubscriptionNow",I:n.v_r,O:n.$n,kind:s.MethodKind.Unary},createPendingTeamProCheckout:{name:"CreatePendingTeamProCheckout",I:n.PTe,O:n.pF3,kind:s.MethodKind.Unary},getTeamPrepaidBilling:{name:"GetTeamPrepaidBilling",I:n.FcH,O:n.$qn,kind:s.MethodKind.Unary},setTeamPrepaidAutoTopUp:{name:"SetTeamPrepaidAutoTopUp",I:n.$ty,O:n.VN6,kind:s.MethodKind.Unary},createPrepaidTopUp:{name:"CreatePrepaidTopUp",I:n.XAW,O:n.bTQ,kind:s.MethodKind.Unary},getUserPrepaidBilling:{name:"GetUserPrepaidBilling",I:n.b4u,O:n.$H_,kind:s.MethodKind.Unary},setUserPrepaidAutoTopUp:{name:"SetUserPrepaidAutoTopUp",I:n.h3x,O:n.D9s,kind:s.MethodKind.Unary},createUserPrepaidTopUp:{name:"CreateUserPrepaidTopUp",I:n.uDD,O:n.EO4,kind:s.MethodKind.Unary},getTeamMembers:{name:"GetTeamMembers",I:n.Imd,O:n.QI7,kind:s.MethodKind.Unary},sendTeamInvite:{name:"SendTeamInvite",I:n.cn,O:n.YBJ,kind:s.MethodKind.Unary},sendTeamInvites:{name:"SendTeamInvites",I:n.Naf,O:n.pF$,kind:s.MethodKind.Unary},getTeamInviteLink:{name:"GetTeamInviteLink",I:n.C4p,O:n.gRj,kind:s.MethodKind.Unary},acceptInvite:{name:"AcceptInvite",I:n.LRJ,O:n.bCe,kind:s.MethodKind.Unary},getTeamInviteMetadata:{name:"GetTeamInviteMetadata",I:n.h1G,O:n.doQ,kind:s.MethodKind.Unary},listContactImportConnections:{name:"ListContactImportConnections",I:n.Ezc,O:n.cDB,kind:s.MethodKind.Unary},getGoogleContactImportAuthUrl:{name:"GetGoogleContactImportAuthUrl",I:n.$7Y,O:n.LoC,kind:s.MethodKind.Unary},connectGoogleContactImportCallback:{name:"ConnectGoogleContactImportCallback",I:n.X38,O:n.tZA,kind:s.MethodKind.Unary},listContactImportContacts:{name:"ListContactImportContacts",I:n.gNW,O:n.SuV,kind:s.MethodKind.Unary},getContactImportAvatar:{name:"GetContactImportAvatar",I:n.mPq,O:n.i5j,kind:s.MethodKind.Unary},disconnectContactImportConnection:{name:"DisconnectContactImportConnection",I:n.jzf,O:n.zu1,kind:s.MethodKind.Unary},createTeam:{name:"CreateTeam",I:n.nxO,O:n.vgA,kind:s.MethodKind.Unary},getJoinableTeamsByDomain:{name:"GetJoinableTeamsByDomain",I:n.ND4,O:n.Rkv,kind:s.MethodKind.Unary},joinTeamByDomain:{name:"JoinTeamByDomain",I:n.E2N,O:n.iX6,kind:s.MethodKind.Unary},updateTeamDomainJoinSetting:{name:"UpdateTeamDomainJoinSetting",I:n.yog,O:n.K_o,kind:s.MethodKind.Unary},getTeamMemberDomains:{name:"GetTeamMemberDomains",I:n.Obu,O:n.S5H,kind:s.MethodKind.Unary},getTeamIdForReactivation:{name:"GetTeamIdForReactivation",I:n._CN,O:n.Kww,kind:s.MethodKind.Unary},changeSeat:{name:"ChangeSeat",I:n.HZm,O:n.lRG,kind:s.MethodKind.Unary},changeTeamSubscription:{name:"ChangeTeamSubscription",I:n.oOo,O:n.MIx,kind:s.MethodKind.Unary},connectGithubCallback:{name:"ConnectGithubCallback",I:n.SH9,O:n._$M,kind:s.MethodKind.Unary},registerGithubCursorCode:{name:"RegisterGithubCursorCode",I:n.H1p,O:n.DUo,kind:s.MethodKind.Unary},prepareGithubConnectFlow:{name:"PrepareGithubConnectFlow",I:n.uif,O:n.EJq,kind:s.MethodKind.Unary},completeGithubConnectFlow:{name:"CompleteGithubConnectFlow",I:n.OjU,O:n.Ohd,kind:s.MethodKind.Unary},disconnectGithub:{name:"DisconnectGithub",I:n.D57,O:n.llV,kind:s.MethodKind.Unary},prepareSetupGithubEnterpriseApp:{name:"PrepareSetupGithubEnterpriseApp",I:n.jPV,O:n.lP,kind:s.MethodKind.Unary},finishSetupGithubEnterpriseApp:{name:"FinishSetupGithubEnterpriseApp",I:n.jiB,O:n.Z48,kind:s.MethodKind.Unary},listGithubEnterpriseApps:{name:"ListGithubEnterpriseApps",I:n.k6E,O:n.a$2,kind:s.MethodKind.Unary},deleteGithubEnterpriseApp:{name:"DeleteGithubEnterpriseApp",I:n.mZ$,O:n.WBx,kind:s.MethodKind.Unary},setupGitlabEnterpriseInstance:{name:"SetupGitlabEnterpriseInstance",I:n.MS0,O:n.k09,kind:s.MethodKind.Unary},listGitlabEnterpriseInstances:{name:"ListGitlabEnterpriseInstances",I:n.gvC,O:n.WaG,kind:s.MethodKind.Unary},setGitlabEnterpriseHostControlledServiceAccountToken:{name:"SetGitlabEnterpriseHostControlledServiceAccountToken",I:n.Rns,O:n.PFp,kind:s.MethodKind.Unary},rotateGitlabEnterpriseWebhookSecret:{name:"RotateGitlabEnterpriseWebhookSecret",I:n.eor,O:n.oTi,kind:s.MethodKind.Unary},deleteGitlabEnterpriseInstance:{name:"DeleteGitlabEnterpriseInstance",I:n.iVu,O:n.wuD,kind:s.MethodKind.Unary},setupBitbucketServerInstance:{name:"SetupBitbucketServerInstance",I:n.w9j,O:n.c1o,kind:s.MethodKind.Unary},listBitbucketServerInstances:{name:"ListBitbucketServerInstances",I:n.Q3t,O:n.Oef,kind:s.MethodKind.Unary},updateBitbucketServerInstanceToken:{name:"UpdateBitbucketServerInstanceToken",I:n.fKS,O:n.tkR,kind:s.MethodKind.Unary},deleteBitbucketServerInstance:{name:"DeleteBitbucketServerInstance",I:n.opt,O:n.ABq,kind:s.MethodKind.Unary},syncGitlabRepos:{name:"SyncGitlabRepos",I:n.ZrD,O:n.ffl,kind:s.MethodKind.Unary},getGitlabReposSyncStatus:{name:"GetGitlabReposSyncStatus",I:n.jp5,O:n.dpH,kind:s.MethodKind.Unary},updateRole:{name:"UpdateRole",I:n.$ht,O:n.BrS,kind:s.MethodKind.Unary},removeMember:{name:"RemoveMember",I:n.mig,O:n.sX9,kind:s.MethodKind.Unary},retryTeamXaiMembershipHold:{name:"RetryTeamXaiMembershipHold",I:oe,O:ae,kind:s.MethodKind.Unary},getMemberRemovalInsights:{name:"GetMemberRemovalInsights",I:n.BF8,O:n.t__,kind:s.MethodKind.Unary},getSignUpType:{name:"GetSignUpType",I:n.u_Q,O:n.WsA,kind:s.MethodKind.Unary},getHardLimit:{name:"GetHardLimit",I:n.g6R,O:n.oyU,kind:s.MethodKind.Unary},setHardLimit:{name:"SetHardLimit",I:n.yL5,O:n.se9,kind:s.MethodKind.Unary},getSpendLimitPolicy:{name:"GetSpendLimitPolicy",I:n.zEV,O:n.pig,kind:s.MethodKind.Unary},setSpendLimitPolicy:{name:"SetSpendLimitPolicy",I:n.LMY,O:n.LLB,kind:s.MethodKind.Unary},getOrgTeamBudgets:{name:"GetOrgTeamBudgets",I:n.DXb,O:n.D42,kind:s.MethodKind.Unary},setOrgTeamBudget:{name:"SetOrgTeamBudget",I:n.yWy,O:n.as5,kind:s.MethodKind.Unary},getOrgDailySpendByCategory:{name:"GetOrgDailySpendByCategory",I:n.ubJ,O:n.GlZ,kind:s.MethodKind.Unary},enableOnDemandSpend:{name:"EnableOnDemandSpend",I:n.toG,O:n.V$m,kind:s.MethodKind.Unary},deleteAccount:{name:"DeleteAccount",I:n.gqj,O:n.wER,kind:s.MethodKind.Unary},getAccountSettings:{name:"GetAccountSettings",I:n.oNu,O:n.Hdf,kind:s.MethodKind.Unary},getAccountDeletionSummary:{name:"GetAccountDeletionSummary",I:n.RwL,O:n.MSh,kind:s.MethodKind.Unary},createAccountHandoff:{name:"CreateAccountHandoff",I:n.vaB,O:n.rzz,kind:s.MethodKind.Unary},startAccountCollapseRun:{name:"StartAccountCollapseRun",I:ht,O:gt,kind:s.MethodKind.Unary},getAccountCollapseRun:{name:"GetAccountCollapseRun",I:_t,O:Jt,kind:s.MethodKind.Unary},startAccountCollapseRunInternal:{name:"StartAccountCollapseRunInternal",I:ht,O:gt,kind:s.MethodKind.Unary},getAccountCollapseRunInternal:{name:"GetAccountCollapseRunInternal",I:_t,O:Jt,kind:s.MethodKind.Unary},startCursorAccountCollapse:{name:"StartCursorAccountCollapse",I:wt,O:yt,kind:s.MethodKind.Unary},getCursorAccountCollapseByTarget:{name:"GetCursorAccountCollapseByTarget",I:St,O:qt,kind:s.MethodKind.Unary},startCursorSessionAccountCollapse:{name:"StartCursorSessionAccountCollapse",I:Bt,O:yt,kind:s.MethodKind.Unary},getCursorSessionAccountCollapse:{name:"GetCursorSessionAccountCollapse",I:It,O:qt,kind:s.MethodKind.Unary},listCursorSessionAccountCollapseCandidates:{name:"ListCursorSessionAccountCollapseCandidates",I:Pt,O:At,kind:s.MethodKind.Unary},startCursorSessionAccountCollapseProof:{name:"StartCursorSessionAccountCollapseProof",I:bt,O:dr,kind:s.MethodKind.Unary},completeCursorSessionAccountCollapseProof:{name:"CompleteCursorSessionAccountCollapseProof",I:Rt,O:hr,kind:s.MethodKind.Unary},sendDownloadEmail:{name:"SendDownloadEmail",I:n.e5r,O:n.C3d,kind:s.MethodKind.Unary},getMonthlyInvoice:{name:"GetMonthlyInvoice",I:n.yO3,O:n.Si_,kind:s.MethodKind.Unary},listInvoiceCycles:{name:"ListInvoiceCycles",I:n.yMo,O:n.G8V,kind:s.MethodKind.Unary},getDailySpendByCategory:{name:"GetDailySpendByCategory",I:n.irI,O:n.GlZ,kind:s.MethodKind.Unary},getPricingHistory:{name:"GetPricingHistory",I:n.Akd,O:n.i7t,kind:s.MethodKind.Unary},listBackgroundComposerSecrets:{name:"ListBackgroundComposerSecrets",I:n.$F$,O:n.dnq,kind:s.MethodKind.Unary},createBackgroundComposerSecret:{name:"CreateBackgroundComposerSecret",I:n.sJl,O:n.ukh,kind:s.MethodKind.Unary},createBackgroundComposerSecretBatch:{name:"CreateBackgroundComposerSecretBatch",I:n.S3E,O:n.o6Z,kind:s.MethodKind.Unary},revokeBackgroundComposerSecret:{name:"RevokeBackgroundComposerSecret",I:n.AU3,O:n.keR,kind:s.MethodKind.Unary},updateBackgroundComposerSecret:{name:"UpdateBackgroundComposerSecret",I:n.zYv,O:n.FmW,kind:s.MethodKind.Unary},getMcpConfig:{name:"GetMcpConfig",I:bi,O:vi,kind:s.MethodKind.Unary},getEffectiveMcpConfigForUser:{name:"GetEffectiveMcpConfigForUser",I:xi,O:ki,kind:s.MethodKind.Unary},getAvailableMcpServers:{name:"GetAvailableMcpServers",I:Ei,O:Ci,kind:s.MethodKind.Unary},getMcpServerUsageSummary:{name:"GetMcpServerUsageSummary",I:Di,O:Gi,kind:s.MethodKind.Unary},setMcpConfig:{name:"SetMcpConfig",I:Li,O:Fi,kind:s.MethodKind.Unary},updateUserDefaultMcpSettings:{name:"UpdateUserDefaultMcpSettings",I:Yi,O:Zi,kind:s.MethodKind.Unary},setGrokConnectorEnabled:{name:"SetGrokConnectorEnabled",I:n.$ZN,O:n.NtP,kind:s.MethodKind.Unary},setUserMcpToolChoices:{name:"SetUserMcpToolChoices",I:eo,O:no,kind:s.MethodKind.Unary},markMcpServersSeen:{name:"MarkMcpServersSeen",I:io,O:oo,kind:s.MethodKind.Unary},storeMcpOAuthToken:{name:"StoreMcpOAuthToken",I:ao,O:uo,kind:s.MethodKind.Unary},getMcpOAuthTokens:{name:"GetMcpOAuthTokens",I:co,O:lo,kind:s.MethodKind.Unary},listSandMcpTools:{name:"ListSandMcpTools",I:dc,O:pc,kind:s.MethodKind.Unary},previewTeamMcpTools:{name:"PreviewTeamMcpTools",I:fo,O:po,kind:s.MethodKind.Unary},executeSandMcpTool:{name:"ExecuteSandMcpTool",I:gc,O:wc,kind:s.MethodKind.Unary},readSandMcpResource:{name:"ReadSandMcpResource",I:yc,O:Sc,kind:s.MethodKind.Unary},classifySandAutoReview:{name:"ClassifySandAutoReview",I:_c,O:Jc,kind:s.MethodKind.Unary},recordSandAuditEvents:{name:"RecordSandAuditEvents",I:$c,O:Mc,kind:s.MethodKind.Unary},mcpOAuthRefreshLockBegin:{name:"McpOAuthRefreshLockBegin",I:ho,O:go,kind:s.MethodKind.Unary},mcpOAuthRefreshLockRelease:{name:"McpOAuthRefreshLockRelease",I:_o,O:Jo,kind:s.MethodKind.Unary},deleteMcpOAuthToken:{name:"DeleteMcpOAuthToken",I:wo,O:yo,kind:s.MethodKind.Unary},validateMcpOAuthTokens:{name:"ValidateMcpOAuthTokens",I:qo,O:Io,kind:s.MethodKind.Unary},checkHttpMcpStatus:{name:"CheckHttpMcpStatus",I:xo,O:ko,kind:s.MethodKind.Unary},storeMcpOAuthPendingState:{name:"StoreMcpOAuthPendingState",I:To,O:Uo,kind:s.MethodKind.Unary},getMcpOAuthPendingState:{name:"GetMcpOAuthPendingState",I:Ao,O:$o,kind:s.MethodKind.Unary},renameMcpOAuthAccount:{name:"RenameMcpOAuthAccount",I:Go,O:Lo,kind:s.MethodKind.Unary},deleteMcpOAuthAccount:{name:"DeleteMcpOAuthAccount",I:Fo,O:Ko,kind:s.MethodKind.Unary},completeMcpOAuth:{name:"CompleteMcpOAuth",I:Mo,O:Oo,kind:s.MethodKind.Unary},handOffMcpOAuthCode:{name:"HandOffMcpOAuthCode",I:Do,O:No,kind:s.MethodKind.Unary},getPluginMcpConfig:{name:"GetPluginMcpConfig",I:zo,O:jo,kind:s.MethodKind.Unary},batchGetPluginMcpConfig:{name:"BatchGetPluginMcpConfig",I:Ho,O:Qo,kind:s.MethodKind.Unary},addMcpServersFromPlugin:{name:"AddMcpServersFromPlugin",I:Vo,O:Xo,kind:s.MethodKind.Unary},moveUserMcpServerToTeam:{name:"MoveUserMcpServerToTeam",I:Ki,O:zi,kind:s.MethodKind.Unary},getTeamMcpPlacementDefault:{name:"GetTeamMcpPlacementDefault",I:ji,O:Hi,kind:s.MethodKind.Unary},updateTeamMcpPlacementDefault:{name:"UpdateTeamMcpPlacementDefault",I:Wi,O:Qi,kind:s.MethodKind.Unary},migrateTeamMcpServersToDefaultMarketplace:{name:"MigrateTeamMcpServersToDefaultMarketplace",I:Vi,O:Xi,kind:s.MethodKind.Unary},probeMcpUrl:{name:"ProbeMcpUrl",I:Yo,O:Zo,kind:s.MethodKind.Unary},getMcpBackendAccessToken:{name:"GetMcpBackendAccessToken",I:ta,O:ra,kind:s.MethodKind.Unary},createTeamWithFreeTrial:{name:"CreateTeamWithFreeTrial",I:n.LAq,O:n.x2A,kind:s.MethodKind.Unary},createTeamWithOrg:{name:"CreateTeamWithOrg",I:n.BlC,O:n.Dd7,kind:s.MethodKind.Unary},getTeamHasValidPaymentMethod:{name:"GetTeamHasValidPaymentMethod",I:n.MrA,O:n.gJp,kind:s.MethodKind.Unary},getTeamPrivacyModeForced:{name:"GetTeamPrivacyModeForced",I:n.lKh,O:n.rsP,kind:s.MethodKind.Unary},getTeamXaiDataRetention:{name:"GetTeamXaiDataRetention",I:n.rcf,O:n.Jcx,kind:s.MethodKind.Unary},switchTeamPrivacyMode:{name:"SwitchTeamPrivacyMode",I:n.SmK,O:n.kjp,kind:s.MethodKind.Unary},updateFastRequests:{name:"UpdateFastRequests",I:n.rjZ,O:n.FFm,kind:s.MethodKind.Unary},getFastRequests:{name:"GetFastRequests",I:n.iSm,O:n.aUJ,kind:s.MethodKind.Unary},getDownloadLink:{name:"GetDownloadLink",I:n.Upy,O:n.AlS,kind:s.MethodKind.Unary},getCliDownloadUrl:{name:"GetCliDownloadUrl",I:n.Xhp,O:n.JRd,kind:s.MethodKind.Unary},getSsoConfigurationLinks:{name:"GetSsoConfigurationLinks",I:n._$o,O:n.Opj,kind:s.MethodKind.Unary},getScimConfigurationLinks:{name:"GetScimConfigurationLinks",I:n.n$I,O:n.fMg,kind:s.MethodKind.Unary},setAdminOnlyUsagePricing:{name:"SetAdminOnlyUsagePricing",I:n.SAF,O:n.Ix8,kind:s.MethodKind.Unary},getYearlyUpgradeEligibility:{name:"GetYearlyUpgradeEligibility",I:n.DLp,O:n.R$$,kind:s.MethodKind.Unary},upgradeToYearly:{name:"UpgradeToYearly",I:n.bBp,O:n.rk2,kind:s.MethodKind.Unary},getEnterpriseCTAEligibility:{name:"GetEnterpriseCTAEligibility",I:n.i6G,O:n.i0P,kind:s.MethodKind.Unary},getUsageBasedPremiumRequests:{name:"GetUsageBasedPremiumRequests",I:n.nDb,O:n.n8L,kind:s.MethodKind.Unary},setUsageBasedPremiumRequests:{name:"SetUsageBasedPremiumRequests",I:n.ZU_,O:n.X8H,kind:s.MethodKind.Unary},getReferrals:{name:"GetReferrals",I:n.Gch,O:n.gBX,kind:s.MethodKind.Unary},getReferralCodes:{name:"GetReferralCodes",I:n.bT6,O:n.D2n,kind:s.MethodKind.Unary},createP2PReferralLink:{name:"CreateP2PReferralLink",I:n.bhY,O:n.XEQ,kind:s.MethodKind.Unary},getP2PReferralStatus:{name:"GetP2PReferralStatus",I:n.pGh,O:n.XWY,kind:s.MethodKind.Unary},sendP2PReferralInvites:{name:"SendP2PReferralInvites",I:n.ZKX,O:n.tZb,kind:s.MethodKind.Unary},getP2PReferralHistory:{name:"GetP2PReferralHistory",I:n.EcQ,O:n.nd7,kind:s.MethodKind.Unary},checkReferralAllowlist:{name:"CheckReferralAllowlist",I:n.ukN,O:n.cRU,kind:s.MethodKind.Unary},checkReferralCode:{name:"CheckReferralCode",I:n.MRM,O:n.wb2,kind:s.MethodKind.Unary},redeemGiftCode:{name:"RedeemGiftCode",I:n.ziV,O:n.lme,kind:s.MethodKind.Unary},getGiftCodeInfo:{name:"GetGiftCodeInfo",I:n.Nmm,O:n.Xa_,kind:s.MethodKind.Unary},getEventCodeInfo:{name:"GetEventCodeInfo",I:n.RiQ,O:n.XUY,kind:s.MethodKind.Unary},redeemEventCode:{name:"RedeemEventCode",I:n.VF8,O:n.Djf,kind:s.MethodKind.Unary},getTeamRepos:{name:"GetTeamRepos",I:n.aYW,O:n.k1F,kind:s.MethodKind.Unary},getTeamReposOrEmptyIfNotInTeam:{name:"GetTeamReposOrEmptyIfNotInTeam",I:n.aYW,O:n.k1F,kind:s.MethodKind.Unary},getTeamRules:{name:"GetTeamRules",I:n.yds,O:n.KZ$,kind:s.MethodKind.Unary},createTeamRule:{name:"CreateTeamRule",I:n.J7F,O:n.vZv,kind:s.MethodKind.Unary},updateTeamRule:{name:"UpdateTeamRule",I:n.qEG,O:n.CMB,kind:s.MethodKind.Unary},deleteTeamRule:{name:"DeleteTeamRule",I:n.Ch8,O:n.uzD,kind:s.MethodKind.Unary},getTeamGroupRules:{name:"GetTeamGroupRules",I:n.vdM,O:n.Xu9,kind:s.MethodKind.Unary},createTeamGroupRule:{name:"CreateTeamGroupRule",I:n.WxI,O:n.AkX,kind:s.MethodKind.Unary},updateTeamGroupRule:{name:"UpdateTeamGroupRule",I:n.dpZ,O:n.Lxb,kind:s.MethodKind.Unary},deleteTeamGroupRule:{name:"DeleteTeamGroupRule",I:n.lIO,O:n.jqE,kind:s.MethodKind.Unary},getTeamHooks:{name:"GetTeamHooks",I:n.$kg,O:n.PtB,kind:s.MethodKind.Unary},createTeamHook:{name:"CreateTeamHook",I:n.wT7,O:n.a4I,kind:s.MethodKind.Unary},updateTeamHook:{name:"UpdateTeamHook",I:n.TeW,O:n.$lk,kind:s.MethodKind.Unary},deleteTeamHook:{name:"DeleteTeamHook",I:n.x4u,O:n.FNs,kind:s.MethodKind.Unary},getTeamCommands:{name:"GetTeamCommands",I:n.XDt,O:n.lzR,kind:s.MethodKind.Unary},createTeamCommand:{name:"CreateTeamCommand",I:n.Ctq,O:n.CXw,kind:s.MethodKind.Unary},updateTeamCommand:{name:"UpdateTeamCommand",I:n.XQ_,O:n.DZr,kind:s.MethodKind.Unary},deleteTeamCommand:{name:"DeleteTeamCommand",I:n.xo6,O:n.atP,kind:s.MethodKind.Unary},getGlobalCommands:{name:"GetGlobalCommands",I:n.YSR,O:n.rL_,kind:s.MethodKind.Unary},getRepoSlashCommands:{name:"GetRepoSlashCommands",I:n.LM4,O:n.hcQ,kind:s.MethodKind.Unary},getBackgroundComposerSlashCommands:{name:"GetBackgroundComposerSlashCommands",I:n.T1q,O:n.RNi,kind:s.MethodKind.Unary},getCloudAgentPluginsSnapshot:{name:"GetCloudAgentPluginsSnapshot",I:n.G24,O:n.gNl,kind:s.MethodKind.Unary},getBugbotTeamRules:{name:"GetBugbotTeamRules",I:n.N8K,O:n.RP_,kind:s.MethodKind.Unary},createBugbotTeamRule:{name:"CreateBugbotTeamRule",I:n.CHh,O:n.GL9,kind:s.MethodKind.Unary},updateBugbotTeamRule:{name:"UpdateBugbotTeamRule",I:n.rtb,O:n.v0c,kind:s.MethodKind.Unary},deleteBugbotTeamRule:{name:"DeleteBugbotTeamRule",I:n.pj7,O:n.rP9,kind:s.MethodKind.Unary},getBugbotLearnedRules:{name:"GetBugbotLearnedRules",I:n.hp9,O:n.z7W,kind:s.MethodKind.Unary},updateBugbotLearnedRule:{name:"UpdateBugbotLearnedRule",I:n.BIT,O:n.Xmf,kind:s.MethodKind.Unary},deleteBugbotLearnedRule:{name:"DeleteBugbotLearnedRule",I:n.hnR,O:n.Ld4,kind:s.MethodKind.Unary},createBugbotManualRepositoryRule:{name:"CreateBugbotManualRepositoryRule",I:n.Bdx,O:n.Zk6,kind:s.MethodKind.Unary},getBugbotManualRepositoryRules:{name:"GetBugbotManualRepositoryRules",I:n.qF$,O:n.azW,kind:s.MethodKind.Unary},updateBugbotManualRepositoryRule:{name:"UpdateBugbotManualRepositoryRule",I:n.UBx,O:n.ead,kind:s.MethodKind.Unary},deleteBugbotManualRepositoryRule:{name:"DeleteBugbotManualRepositoryRule",I:n.ONG,O:n.YYN,kind:s.MethodKind.Unary},runDiamondToBugbotMigration:{name:"RunDiamondToBugbotMigration",I:n.rb7,O:n.DkK,kind:s.MethodKind.Unary},getBugbotRuleAnalytics:{name:"GetBugbotRuleAnalytics",I:n.lvI,O:n.RK5,kind:s.MethodKind.Unary},getBugbotRuleById:{name:"GetBugbotRuleById",I:n.TOm,O:n.tkD,kind:s.MethodKind.Unary},createTeamRepo:{name:"CreateTeamRepo",I:n.J4c,O:n.fCO,kind:s.MethodKind.Unary},deleteTeamRepo:{name:"DeleteTeamRepo",I:n.m0x,O:n.Cw0,kind:s.MethodKind.Unary},addRepoPattern:{name:"AddRepoPattern",I:n.pji,O:n.D3c,kind:s.MethodKind.Unary},removeRepoPattern:{name:"RemoveRepoPattern",I:n.MEU,O:n.U0s,kind:s.MethodKind.Unary},setTeamRepoType:{name:"SetTeamRepoType",I:n.HeY,O:n.V_5,kind:s.MethodKind.Unary},getTeamAdminSettings:{name:"GetTeamAdminSettings",I:n.Byz,O:n.V5U,kind:s.MethodKind.Unary},getTeamAdminSettingsOrEmptyIfNotInTeam:{name:"GetTeamAdminSettingsOrEmptyIfNotInTeam",I:n.Byz,O:n.V5U,kind:s.MethodKind.Unary},getBaseTeamAdminSettings:{name:"GetBaseTeamAdminSettings",I:n.Qrr,O:n.V5U,kind:s.MethodKind.Unary},getTeamOriginDisabled:{name:"GetTeamOriginDisabled",I:n.NES,O:n.Fj9,kind:s.MethodKind.Unary},listUnlistedMemberServers:{name:"ListUnlistedMemberServers",I:n.esR,O:n.eiD,kind:s.MethodKind.Unary},updateTeamAdminSettings:{name:"UpdateTeamAdminSettings",I:n.sCz,O:n.aP5,kind:s.MethodKind.Unary},getCloudAgentStartupScript:{name:"GetCloudAgentStartupScript",I:n.ISZ,O:n.yTE,kind:s.MethodKind.Unary},updateCloudAgentStartupScript:{name:"UpdateCloudAgentStartupScript",I:n.PvX,O:n.JPA,kind:s.MethodKind.Unary},getTeamCustomerTelemetryDestinations:{name:"GetTeamCustomerTelemetryDestinations",I:n.n$w,O:n.R9K,kind:s.MethodKind.Unary},createTeamCustomerTelemetryDestination:{name:"CreateTeamCustomerTelemetryDestination",I:n.qxp,O:n.uts,kind:s.MethodKind.Unary},updateTeamCustomerTelemetryDestination:{name:"UpdateTeamCustomerTelemetryDestination",I:n.LJ3,O:n.Hen,kind:s.MethodKind.Unary},deleteTeamCustomerTelemetryDestination:{name:"DeleteTeamCustomerTelemetryDestination",I:n.t1u,O:n.rFi,kind:s.MethodKind.Unary},testTeamCustomerTelemetryDestinationConnection:{name:"TestTeamCustomerTelemetryDestinationConnection",I:n.ybE,O:n.YiF,kind:s.MethodKind.Unary},getTeamCustomerTelemetryDestinationHealth:{name:"GetTeamCustomerTelemetryDestinationHealth",I:n.mD_,O:n.wGo,kind:s.MethodKind.Unary},getTeamCustomerTelemetryContentExportOptIn:{name:"GetTeamCustomerTelemetryContentExportOptIn",I:n.LWe,O:n.F8Y,kind:s.MethodKind.Unary},updateTeamCustomerTelemetryContentExportOptIn:{name:"UpdateTeamCustomerTelemetryContentExportOptIn",I:n.UvX,O:n.G8P,kind:s.MethodKind.Unary},getTeamInferenceHookConfig:{name:"GetTeamInferenceHookConfig",I:n.TB_,O:n.nE8,kind:s.MethodKind.Unary},updateTeamInferenceHookConfig:{name:"UpdateTeamInferenceHookConfig",I:n.qJd,O:n.IIB,kind:s.MethodKind.Unary},rotateTeamInferenceHookSigningSecret:{name:"RotateTeamInferenceHookSigningSecret",I:n.B8P,O:n.HQR,kind:s.MethodKind.Unary},getTeamInferenceHookHealth:{name:"GetTeamInferenceHookHealth",I:n.lax,O:n.rM7,kind:s.MethodKind.Unary},resetTeamInferenceHookBreaker:{name:"ResetTeamInferenceHookBreaker",I:n._dj,O:n.Mob,kind:s.MethodKind.Unary},getTeamGrokBotIdpConnection:{name:"GetTeamGrokBotIdpConnection",I:Af,O:$f,kind:s.MethodKind.Unary},updateTeamGrokBotIdpConnection:{name:"UpdateTeamGrokBotIdpConnection",I:Mf,O:Of,kind:s.MethodKind.Unary},deleteTeamGrokBotIdpConnection:{name:"DeleteTeamGrokBotIdpConnection",I:Df,O:Nf,kind:s.MethodKind.Unary},getTeamGrokBotScimDirectory:{name:"GetTeamGrokBotScimDirectory",I:Ff,O:Kf,kind:s.MethodKind.Unary},enableTeamGrokBotScimDirectory:{name:"EnableTeamGrokBotScimDirectory",I:zf,O:jf,kind:s.MethodKind.Unary},disableTeamGrokBotScimDirectory:{name:"DisableTeamGrokBotScimDirectory",I:Hf,O:Wf,kind:s.MethodKind.Unary},createTeamGrokBotScimToken:{name:"CreateTeamGrokBotScimToken",I:Qf,O:Vf,kind:s.MethodKind.Unary},revokeTeamGrokBotScimToken:{name:"RevokeTeamGrokBotScimToken",I:Xf,O:Yf,kind:s.MethodKind.Unary},updateTeamGrokBotScimIpAllowlist:{name:"UpdateTeamGrokBotScimIpAllowlist",I:Zf,O:td,kind:s.MethodKind.Unary},listTeamGrokBotScimBots:{name:"ListTeamGrokBotScimBots",I:ed,O:nd,kind:s.MethodKind.Unary},deleteTeamGrokBotScimBot:{name:"DeleteTeamGrokBotScimBot",I:sd,O:id,kind:s.MethodKind.Unary},getTeamGrokBotScimIdpIdentity:{name:"GetTeamGrokBotScimIdpIdentity",I:cd,O:ld,kind:s.MethodKind.Unary},updateTeamGrokBotScimIdpIdentity:{name:"UpdateTeamGrokBotScimIdpIdentity",I:md,O:fd,kind:s.MethodKind.Unary},generateTeamGrokBotScimIdpSigningKey:{name:"GenerateTeamGrokBotScimIdpSigningKey",I:dd,O:pd,kind:s.MethodKind.Unary},deleteTeamGrokBotScimIdpIdentity:{name:"DeleteTeamGrokBotScimIdpIdentity",I:hd,O:gd,kind:s.MethodKind.Unary},getTeamLlmGatewayCredentialStatus:{name:"GetTeamLlmGatewayCredentialStatus",I:n.v8R,O:n.dsv,kind:s.MethodKind.Unary},setTeamLlmGatewayCredential:{name:"SetTeamLlmGatewayCredential",I:n.JQv,O:n.LQe,kind:s.MethodKind.Unary},replaceTeamLlmGatewayCredential:{name:"ReplaceTeamLlmGatewayCredential",I:n.Bwq,O:n.nUL,kind:s.MethodKind.Unary},clearTeamLlmGatewayCredential:{name:"ClearTeamLlmGatewayCredential",I:n.uBx,O:n._rf,kind:s.MethodKind.Unary},updateTeamLlmGatewayModelDiscovery:{name:"UpdateTeamLlmGatewayModelDiscovery",I:n.i_X,O:n.wBS,kind:s.MethodKind.Unary},updateTeamLlmGatewayProviderEndpoints:{name:"UpdateTeamLlmGatewayProviderEndpoints",I:n.moj,O:n.k3$,kind:s.MethodKind.Unary},setTeamNoZdrModelConsent:{name:"SetTeamNoZdrModelConsent",I:n.HOq,O:n.xEn,kind:s.MethodKind.Unary},setOrganizationNoZdrModelConsent:{name:"SetOrganizationNoZdrModelConsent",I:n.xO$,O:n.b07,kind:s.MethodKind.Unary},getOrganizationPrivateInferencePolicy:{name:"GetOrganizationPrivateInferencePolicy",I:n.Vie,O:n.vsf,kind:s.MethodKind.Unary},updateOrganizationPrivateInferencePolicy:{name:"UpdateOrganizationPrivateInferencePolicy",I:n.Tjf,O:n.eWF,kind:s.MethodKind.Unary},getOrganizationPrivateInferenceTeamGroups:{name:"GetOrganizationPrivateInferenceTeamGroups",I:n.Ok7,O:n.Ajm,kind:s.MethodKind.Unary},getTeamPrivateInferencePolicy:{name:"GetTeamPrivateInferencePolicy",I:n.VNQ,O:n.NYc,kind:s.MethodKind.Unary},updateTeamPrivateInferencePolicy:{name:"UpdateTeamPrivateInferencePolicy",I:n.Ozh,O:n.wcT,kind:s.MethodKind.Unary},getOrganizationOnDemandSpendDisabled:{name:"GetOrganizationOnDemandSpendDisabled",I:n.Twg,O:n.$H2,kind:s.MethodKind.Unary},setOrganizationOnDemandSpendDisabled:{name:"SetOrganizationOnDemandSpendDisabled",I:n.zYy,O:n.dwD,kind:s.MethodKind.Unary},getOrganizationCreditRequestButtonHidden:{name:"GetOrganizationCreditRequestButtonHidden",I:n.jIe,O:n.JEj,kind:s.MethodKind.Unary},setOrganizationCreditRequestButtonHidden:{name:"SetOrganizationCreditRequestButtonHidden",I:n.v_8,O:n.VgQ,kind:s.MethodKind.Unary},getOrganizationSsoJitAutoEnrollment:{name:"GetOrganizationSsoJitAutoEnrollment",I:n._v$,O:n.yj0,kind:s.MethodKind.Unary},setOrganizationSsoJitAutoEnrollment:{name:"SetOrganizationSsoJitAutoEnrollment",I:n.yjV,O:n.c4k,kind:s.MethodKind.Unary},getTeamSsoJitAutoEnrollment:{name:"GetTeamSsoJitAutoEnrollment",I:n.WsN,O:n.Afl,kind:s.MethodKind.Unary},setTeamSsoJitAutoEnrollment:{name:"SetTeamSsoJitAutoEnrollment",I:n.O8H,O:n.wDw,kind:s.MethodKind.Unary},getTeamXAccountLinking:{name:"GetTeamXAccountLinking",I:n.ScF,O:n.bZb,kind:s.MethodKind.Unary},setTeamXAccountLinking:{name:"SetTeamXAccountLinking",I:n.WUm,O:n.bZb,kind:s.MethodKind.Unary},getOrganizationRemoteControlSettings:{name:"GetOrganizationRemoteControlSettings",I:n.ZPB,O:n.vfT,kind:s.MethodKind.Unary},updateOrganizationRemoteControlSettings:{name:"UpdateOrganizationRemoteControlSettings",I:n.AL,O:n.EDv,kind:s.MethodKind.Unary},getOrganizationSlackManagedWorkspaces:{name:"GetOrganizationSlackManagedWorkspaces",I:n.kxz,O:n.wFu,kind:s.MethodKind.Unary},updateOrganizationSlackManagedWorkspaces:{name:"UpdateOrganizationSlackManagedWorkspaces",I:n.pmc,O:n.PW,kind:s.MethodKind.Unary},getOrganizationSlackInboundInstallPolicy:{name:"GetOrganizationSlackInboundInstallPolicy",I:n.pPB,O:n.DxY,kind:s.MethodKind.Unary},updateOrganizationSlackInboundInstallPolicy:{name:"UpdateOrganizationSlackInboundInstallPolicy",I:n.aam,O:n.AF,kind:s.MethodKind.Unary},getOrganizationGrokBotWallSnapshotControls:{name:"GetOrganizationGrokBotWallSnapshotControls",I:Rf,O:vf,kind:s.MethodKind.Unary},updateOrganizationGrokBotWallSnapshotControls:{name:"UpdateOrganizationGrokBotWallSnapshotControls",I:xf,O:kf,kind:s.MethodKind.Unary},getOrganizationGoogleDriveBlockedSharedDrives:{name:"GetOrganizationGoogleDriveBlockedSharedDrives",I:n.iS1,O:n._ax,kind:s.MethodKind.Unary},updateOrganizationGoogleDriveBlockedSharedDrives:{name:"UpdateOrganizationGoogleDriveBlockedSharedDrives",I:n.b3B,O:n.vym,kind:s.MethodKind.Unary},getOrganizationConnectorAccountOwnership:{name:"GetOrganizationConnectorAccountOwnership",I:n.GoS,O:n.O8k,kind:s.MethodKind.Unary},updateOrganizationConnectorAccountOwnership:{name:"UpdateOrganizationConnectorAccountOwnership",I:n.fS9,O:n.EvY,kind:s.MethodKind.Unary},getTeamRemoteControlSettings:{name:"GetTeamRemoteControlSettings",I:n.DVl,O:n.V$7,kind:s.MethodKind.Unary},updateTeamRemoteControlSettings:{name:"UpdateTeamRemoteControlSettings",I:n.ORt,O:n.yL9,kind:s.MethodKind.Unary},listOrganizationRemoteControlDevices:{name:"ListOrganizationRemoteControlDevices",I:n.jrM,O:n.ERl,kind:s.MethodKind.Unary},revokeOrganizationRemoteControlDevice:{name:"RevokeOrganizationRemoteControlDevice",I:n.CdP,O:n.lvC,kind:s.MethodKind.Unary},listTeamRemoteControlDevices:{name:"ListTeamRemoteControlDevices",I:n.P0D,O:n.ERl,kind:s.MethodKind.Unary},revokeTeamRemoteControlDevice:{name:"RevokeTeamRemoteControlDevice",I:n.Apo,O:n.lvC,kind:s.MethodKind.Unary},setUserNoZdrModelConsent:{name:"SetUserNoZdrModelConsent",I:n.hk4,O:n.ZpC,kind:s.MethodKind.Unary},setTeamMemberNoZdrModelConsent:{name:"SetTeamMemberNoZdrModelConsent",I:n.npU,O:n.PGd,kind:s.MethodKind.Unary},getNoZdrModelConsentStatus:{name:"GetNoZdrModelConsentStatus",I:n.Udp,O:n._am,kind:s.MethodKind.Unary},updateTeamInviteLinkTTLSetting:{name:"UpdateTeamInviteLinkTTLSetting",I:n.Lr1,O:n.Bpu,kind:s.MethodKind.Unary},updateTeamMemberInviteSetting:{name:"UpdateTeamMemberInviteSetting",I:n.tdz,O:n.N4Y,kind:s.MethodKind.Unary},updateTeamInviteLinkJoinApprovalSetting:{name:"UpdateTeamInviteLinkJoinApprovalSetting",I:n.cCB,O:n.mFP,kind:s.MethodKind.Unary},updateTeamPersonalApiKeyCreationSetting:{name:"UpdateTeamPersonalApiKeyCreationSetting",I:n.izj,O:n.Qul,kind:s.MethodKind.Unary},updateTeamVoiceChatSetting:{name:"UpdateTeamVoiceChatSetting",I:n.WL_,O:n.SPf,kind:s.MethodKind.Unary},updateTeamDefaultMemberBillingTier:{name:"UpdateTeamDefaultMemberBillingTier",I:n.gPk,O:n.wZY,kind:s.MethodKind.Unary},updateTeamSandOnboardingCompleted:{name:"UpdateTeamSandOnboardingCompleted",I:Cl,O:Tl,kind:s.MethodKind.Unary},updateTeamSandSetupChecklistItem:{name:"UpdateTeamSandSetupChecklistItem",I:Ul,O:Al,kind:s.MethodKind.Unary},markTeamSandOnboardingSeen:{name:"MarkTeamSandOnboardingSeen",I:$l,O:Ml,kind:s.MethodKind.Unary},getTeamGrokBotEligibleUserIds:{name:"GetTeamGrokBotEligibleUserIds",I:Ol,O:Dl,kind:s.MethodKind.Unary},sendTeamSandOnboardingInvites:{name:"SendTeamSandOnboardingInvites",I:Nl,O:Gl,kind:s.MethodKind.Unary},getProtectedGitScopes:{name:"GetProtectedGitScopes",I:n.TXH,O:n.P_k,kind:s.MethodKind.Unary},createProtectedGitScope:{name:"CreateProtectedGitScope",I:n.IW3,O:n.wmn,kind:s.MethodKind.Unary},deleteProtectedGitScope:{name:"DeleteProtectedGitScope",I:n.tE7,O:n.R1c,kind:s.MethodKind.Unary},createTeamFreeTrialCode:{name:"CreateTeamFreeTrialCode",I:n.Qx5,O:n.M3e,kind:s.MethodKind.Unary},createTeamFreeTrialCodeInternal:{name:"CreateTeamFreeTrialCodeInternal",I:n.Qx5,O:n.M3e,kind:s.MethodKind.Unary},setTrialSpendLimitOverrideInternal:{name:"SetTrialSpendLimitOverrideInternal",I:n.IHq,O:n.qks,kind:s.MethodKind.Unary},getTrialSpendLimitInternal:{name:"GetTrialSpendLimitInternal",I:n.yIy,O:n.C2K,kind:s.MethodKind.Unary},getOrganizationEnterpriseTrialExtendContextInternal:{name:"GetOrganizationEnterpriseTrialExtendContextInternal",I:n.Yeg,O:n.eBq,kind:s.MethodKind.Unary},applyOrganizationEnterpriseTrialEndInternal:{name:"ApplyOrganizationEnterpriseTrialEndInternal",I:n.mi9,O:n.Izq,kind:s.MethodKind.Unary},getTeamUnifiedStatusInternal:{name:"GetTeamUnifiedStatusInternal",I:ue,O:ce,kind:s.MethodKind.Unary},startUnifiedTeamTrialInternal:{name:"StartUnifiedTeamTrialInternal",I:fe,O:me,kind:s.MethodKind.Unary},extendUnifiedTeamTrialInternal:{name:"ExtendUnifiedTeamTrialInternal",I:de,O:me,kind:s.MethodKind.Unary},endUnifiedTeamTrialInternal:{name:"EndUnifiedTeamTrialInternal",I:pe,O:me,kind:s.MethodKind.Unary},convertUnifiedTeamTrialInternal:{name:"ConvertUnifiedTeamTrialInternal",I:he,O:me,kind:s.MethodKind.Unary},getUnifiedTeamTrialInternal:{name:"GetUnifiedTeamTrialInternal",I:ge,O:_e,kind:s.MethodKind.Unary},getEnterpriseGrokBotTeamTrialInternal:{name:"GetEnterpriseGrokBotTeamTrialInternal",I:Ll,O:Fl,kind:s.MethodKind.Unary},setEnterpriseGrokBotTeamTrialExpirationInternal:{name:"SetEnterpriseGrokBotTeamTrialExpirationInternal",I:Kl,O:zl,kind:s.MethodKind.Unary},getXaiUserUsageSnapshot:{name:"GetXaiUserUsageSnapshot",I:n.WAE,O:n.qSX,kind:s.MethodKind.Unary},getXaiUserPrepaidBilling:{name:"GetXaiUserPrepaidBilling",I:n.b4u,O:n.$H_,kind:s.MethodKind.Unary},setXaiUserPrepaidAutoTopUp:{name:"SetXaiUserPrepaidAutoTopUp",I:n.h3x,O:n.D9s,kind:s.MethodKind.Unary},getXaiCommerceBearerToken:{name:"GetXaiCommerceBearerToken",I:n.hD2,O:n.ZoF,kind:s.MethodKind.Unary},getTeamOffboardingConfigInternal:{name:"GetTeamOffboardingConfigInternal",I:n.XRZ,O:n.pv1,kind:s.MethodKind.Unary},updateTeamOffboardingConfigInternal:{name:"UpdateTeamOffboardingConfigInternal",I:n.AKO,O:n.C7S,kind:s.MethodKind.Unary},createTeamCreditGrantInternal:{name:"CreateTeamCreditGrantInternal",I:n.BEg,O:n.Rz7,kind:s.MethodKind.Unary},listTeamCreditGrantsInternal:{name:"ListTeamCreditGrantsInternal",I:n.CAc,O:n.GYk,kind:s.MethodKind.Unary},createTeamsTrialV2ReferralCode:{name:"CreateTeamsTrialV2ReferralCode",I:n.cj_,O:n.SyP,kind:s.MethodKind.Unary},getTeamAnalytics:{name:"GetTeamAnalytics",I:n.FFq,O:n.LLA,kind:s.MethodKind.Unary},getUserAnalytics:{name:"GetUserAnalytics",I:n.dcL,O:n.n24,kind:s.MethodKind.Unary},getTeamRawData:{name:"GetTeamRawData",I:n.hUh,O:n.dZ5,kind:s.MethodKind.Unary},getClientUsageData:{name:"GetClientUsageData",I:n.u_0,O:n.gHM,kind:s.MethodKind.Unary},getCurrentPeriodUsage:{name:"GetCurrentPeriodUsage",I:n.Dl4,O:n.bO3,kind:s.MethodKind.Unary},useSandBankedReset:{name:"UseSandBankedReset",I:jl,O:Hl,kind:s.MethodKind.Unary},listSandBankedResets:{name:"ListSandBankedResets",I:Wl,O:Vl,kind:s.MethodKind.Unary},getSandUsageStatus:{name:"GetSandUsageStatus",I:Gm,O:zm,kind:s.MethodKind.Unary},getSandUpgradeOffer:{name:"GetSandUpgradeOffer",I:om,O:am,kind:s.MethodKind.Unary},getGrokBotUsageBreakdown:{name:"GetGrokBotUsageBreakdown",I:Qm,O:ef,kind:s.MethodKind.Unary},getSandEnterpriseSpendLimit:{name:"GetSandEnterpriseSpendLimit",I:nf,O:sf,kind:s.MethodKind.Unary},requestSandSeatTierUpgrade:{name:"RequestSandSeatTierUpgrade",I:Lm,O:Fm,kind:s.MethodKind.Unary},listBankedUsageResets:{name:"ListBankedUsageResets",I:n.kCx,O:n.izO,kind:s.MethodKind.Unary},redeemTeamBankedUsageReset:{name:"RedeemTeamBankedUsageReset",I:n.J_n,O:n.BLE,kind:s.MethodKind.Unary},redeemUserBankedUsageReset:{name:"RedeemUserBankedUsageReset",I:n.J_n,O:n.BLE,kind:s.MethodKind.Unary},startSandTrial:{name:"StartSandTrial",I:uf,O:_f,kind:s.MethodKind.Unary},claimSandTrialWithDeviceAttestation:{name:"ClaimSandTrialWithDeviceAttestation",I:cf,O:ff,kind:s.MethodKind.Unary},resetSandTrialDeviceAttestation:{name:"ResetSandTrialDeviceAttestation",I:pf,O:hf,kind:s.MethodKind.Unary},isEligibleForSandTrial:{name:"IsEligibleForSandTrial",I:yf,O:Sf,kind:s.MethodKind.Unary},getSandTrialClaimStatus:{name:"GetSandTrialClaimStatus",I:If,O:Pf,kind:s.MethodKind.Unary},cancelSandTrial:{name:"CancelSandTrial",I:qf,O:Bf,kind:s.MethodKind.Unary},getSandAccessStatus:{name:"GetSandAccessStatus",I:Xl,O:mm,kind:s.MethodKind.Unary},shouldShowGrokBotTrainingOptInPopup:{name:"ShouldShowGrokBotTrainingOptInPopup",I:Yl,O:Zl,kind:s.MethodKind.Unary},markGrokBotTrainingOptInPromptSeen:{name:"MarkGrokBotTrainingOptInPromptSeen",I:um,O:cm,kind:s.MethodKind.Unary},getSandMarketingIdentity:{name:"GetSandMarketingIdentity",I:Om,O:Dm,kind:s.MethodKind.Unary},getBonfireStatus:{name:"GetBonfireStatus",I:n.DrQ,O:n.ZhM,kind:s.MethodKind.Unary},createBonfireInvite:{name:"CreateBonfireInvite",I:n._do,O:n.EAb,kind:s.MethodKind.Unary},sendBonfireInvite:{name:"SendBonfireInvite",I:n.EiN,O:n.e0Y,kind:s.MethodKind.Unary},registerSandMachine:{name:"RegisterSandMachine",I:Sm,O:qm,kind:s.MethodKind.Unary},listSandMachines:{name:"ListSandMachines",I:Bm,O:Pm,kind:s.MethodKind.Unary},updateSandMachineLabel:{name:"UpdateSandMachineLabel",I:bm,O:Rm,kind:s.MethodKind.Unary},updateSandMachineLocalToolPermission:{name:"UpdateSandMachineLocalToolPermission",I:vm,O:xm,kind:s.MethodKind.Unary},getSandMachineMessagesEnabled:{name:"GetSandMachineMessagesEnabled",I:km,O:Em,kind:s.MethodKind.Unary},updateSandMachineMessagesEnabled:{name:"UpdateSandMachineMessagesEnabled",I:Cm,O:Tm,kind:s.MethodKind.Unary},retrySandMessagesPermission:{name:"RetrySandMessagesPermission",I:Um,O:Am,kind:s.MethodKind.Unary},removeSandMachine:{name:"RemoveSandMachine",I:Pd,O:bd,kind:s.MethodKind.Unary},requestSandTeamAccess:{name:"RequestSandTeamAccess",I:$m,O:Mm,kind:s.MethodKind.Unary},listPendingUserAccessRequests:{name:"ListPendingUserAccessRequests",I:n._YH,O:n._i_,kind:s.MethodKind.Unary},getUsageSignalsProjectionSnapshot:{name:"GetUsageSignalsProjectionSnapshot",I:ep,O:np,kind:s.MethodKind.Unary},getPlanInfo:{name:"GetPlanInfo",I:n.V4G,O:n.noV,kind:s.MethodKind.Unary},verifyAppleTransaction:{name:"VerifyAppleTransaction",I:n.Ll_,O:n.rKG,kind:s.MethodKind.Unary},verifyGooglePlayPurchase:{name:"VerifyGooglePlayPurchase",I:n.rG0,O:n.lWs,kind:s.MethodKind.Unary},getGooglePlayBillingAccountId:{name:"GetGooglePlayBillingAccountId",I:n.wcH,O:n.cQ7,kind:s.MethodKind.Unary},inventoryGooglePlayPurchaseTokens:{name:"InventoryGooglePlayPurchaseTokens",I:n.WCl,O:n.GYE,kind:s.MethodKind.Unary},restoreCommerceStorePurchases:{name:"RestoreCommerceStorePurchases",I:n.Eg0,O:n.c6S,kind:s.MethodKind.Unary},getGrokCreditPackPurchaseAccount:{name:"GetGrokCreditPackPurchaseAccount",I:Je,O:we,kind:s.MethodKind.Unary},reportGrokCreditPackPurchase:{name:"ReportGrokCreditPackPurchase",I:ye,O:Be,kind:s.MethodKind.Unary},inspectGooglePlaySubscriptionInternal:{name:"InspectGooglePlaySubscriptionInternal",I:n.NNb,O:n.Zm8,kind:s.MethodKind.Unary},inspectGooglePlayTransactionsInternal:{name:"InspectGooglePlayTransactionsInternal",I:n.B5B,O:n.bh8,kind:s.MethodKind.Unary},sendTestPushNotificationInternal:{name:"SendTestPushNotificationInternal",I:n.wQX,O:n.izm,kind:s.MethodKind.Unary},listTeamInviteLinksInternal:{name:"ListTeamInviteLinksInternal",I:n.sbK,O:n.ofK,kind:s.MethodKind.Unary},revokeTeamInviteLinksInternal:{name:"RevokeTeamInviteLinksInternal",I:n.kwX,O:n.WRC,kind:s.MethodKind.Unary},getCursorReviewEntitlement:{name:"GetCursorReviewEntitlement",I:n.pmk,O:n.LwP,kind:s.MethodKind.Unary},searchOriginReviewPeople:{name:"SearchOriginReviewPeople",I:n.PBS,O:n.JZ6,kind:s.MethodKind.Unary},getOriginReviewPreferences:{name:"GetOriginReviewPreferences",I:n.q9G,O:n.MQS,kind:s.MethodKind.Unary},setOriginReviewPreferences:{name:"SetOriginReviewPreferences",I:n.CLT,O:n.q5s,kind:s.MethodKind.Unary},getMergeBotSettings:{name:"GetMergeBotSettings",I:n._GX,O:n.Q50,kind:s.MethodKind.Unary},setMergeBotConsent:{name:"SetMergeBotConsent",I:n.Ldy,O:n.BDC,kind:s.MethodKind.Unary},syncClientSettings:{name:"SyncClientSettings",I:n.L7H,O:n.jGg,kind:s.MethodKind.Unary},listRepoLearnedRules:{name:"ListRepoLearnedRules",I:ip,O:op,kind:s.MethodKind.Unary},removeRepoLearnedRule:{name:"RemoveRepoLearnedRule",I:up,O:cp,kind:s.MethodKind.Unary},appendRsiRecord:{name:"AppendRsiRecord",I:gp,O:_p,kind:s.MethodKind.Unary},getRsiRecord:{name:"GetRsiRecord",I:Jp,O:wp,kind:s.MethodKind.Unary},listRsiRecords:{name:"ListRsiRecords",I:yp,O:Sp,kind:s.MethodKind.Unary},getRsiSnapshot:{name:"GetRsiSnapshot",I:qp,O:Bp,kind:s.MethodKind.Unary},getRsiAdminStatusInternal:{name:"GetRsiAdminStatusInternal",I:Rp,O:vp,kind:s.MethodKind.Unary},runRsiLoopNowInternal:{name:"RunRsiLoopNowInternal",I:xp,O:kp,kind:s.MethodKind.Unary},setRsiLoopPausedInternal:{name:"SetRsiLoopPausedInternal",I:Ep,O:Cp,kind:s.MethodKind.Unary},getUsageLimitPolicyStatus:{name:"GetUsageLimitPolicyStatus",I:n.qhH,O:n.I_D,kind:s.MethodKind.Unary},getUsageLimitStatusAndActiveGrants:{name:"GetUsageLimitStatusAndActiveGrants",I:n.S9t,O:n._ty,kind:s.MethodKind.Unary},getCreditGrantsBalance:{name:"GetCreditGrantsBalance",I:n.MjR,O:n.CkD,kind:s.MethodKind.Unary},getClientVisibleCreditGrants:{name:"GetClientVisibleCreditGrants",I:n.V8e,O:n.Pqo,kind:s.MethodKind.Unary},getAdvancedAnalyticsEnabled:{name:"GetAdvancedAnalyticsEnabled",I:n.P1T,O:n.VxL,kind:s.MethodKind.Unary},getTokenUsage:{name:"GetTokenUsage",I:n.SK5,O:n.I9h,kind:s.MethodKind.Unary},validateBedrockIamRole:{name:"ValidateBedrockIamRole",I:n.Z8m,O:n.VbN,kind:s.MethodKind.Unary},getTeamSpend:{name:"GetTeamSpend",I:n.$Sc,O:n.R2E,kind:s.MethodKind.Unary},getTeamSeatUpgradeRecommendations:{name:"GetTeamSeatUpgradeRecommendations",I:n.Y$T,O:n.o35,kind:s.MethodKind.Unary},getPendingSeatTierUpgradeRequests:{name:"GetPendingSeatTierUpgradeRequests",I:n.qWG,O:n.YJY,kind:s.MethodKind.Unary},getTeamSeatCapacity:{name:"GetTeamSeatCapacity",I:n.e6P,O:n.SuY,kind:s.MethodKind.Unary},startMergedTeamSeatChange:{name:"StartMergedTeamSeatChange",I:Ie,O:be,kind:s.MethodKind.Unary},changeMergedTeamSeat:{name:"ChangeMergedTeamSeat",I:Re,O:xe,kind:s.MethodKind.Unary},getMergedTeamSeatChanges:{name:"GetMergedTeamSeatChanges",I:ke,O:Ce,kind:s.MethodKind.Unary},getXaiTeamPlanManagement:{name:"GetXaiTeamPlanManagement",I:n.jq0,O:n.f1t,kind:s.MethodKind.Unary},changeXaiTeamPlan:{name:"ChangeXaiTeamPlan",I:n.IV$,O:n.yW5,kind:s.MethodKind.Unary},getCurrentBillingCycle:{name:"GetCurrentBillingCycle",I:n.yI7,O:n.cTj,kind:s.MethodKind.Unary},getMonthlyBillingCycle:{name:"GetMonthlyBillingCycle",I:n.iaP,O:n.KuC,kind:s.MethodKind.Unary},getBugbotSettings:{name:"GetBugbotSettings",I:n.Ioc,O:n.GNy,kind:s.MethodKind.Unary},getBugbotAnalyticsV2:{name:"GetBugbotAnalyticsV2",I:n.JWI,O:n.NXG,kind:s.MethodKind.Unary},getBugBotPRAnalytics:{name:"GetBugBotPRAnalytics",I:n.Jns,O:n.Fkp,kind:s.MethodKind.Unary},getGithubInstallations:{name:"GetGithubInstallations",I:n.kcC,O:n.UYU,kind:s.MethodKind.Unary},getGithubInstallationTenantGrants:{name:"GetGithubInstallationTenantGrants",I:n.Owv,O:n.yq_,kind:s.MethodKind.Unary},grantGithubInstallationTenant:{name:"GrantGithubInstallationTenant",I:n.hvD,O:n.p84,kind:s.MethodKind.Unary},revokeGithubInstallationTenant:{name:"RevokeGithubInstallationTenant",I:n.Rig,O:n.neC,kind:s.MethodKind.Unary},getBugbotSuggestedRepos:{name:"GetBugbotSuggestedRepos",I:n.nTs,O:n.ZJ6,kind:s.MethodKind.Unary},getSecurityAgentSuggestedRepos:{name:"GetSecurityAgentSuggestedRepos",I:n.ZPw,O:n.ZOX,kind:s.MethodKind.Unary},getScmConnectionStatus:{name:"GetScmConnectionStatus",I:n.Lys,O:n.VS9,kind:s.MethodKind.Unary},getGithubRepoAccessStatus:{name:"GetGithubRepoAccessStatus",I:n.XT3,O:n.HyV,kind:s.MethodKind.Unary},getScmConnectionStatuses:{name:"GetScmConnectionStatuses",I:n.tJ9,O:n.lIF,kind:s.MethodKind.Unary},getInstallationRepos:{name:"GetInstallationRepos",I:n.L$Y,O:n.ljc,kind:s.MethodKind.Unary},fetchAllInstallationRepos:{name:"FetchAllInstallationRepos",I:n.UfC,O:n.gJO,kind:s.MethodKind.Unary},getInstallationGithubUsers:{name:"GetInstallationGithubUsers",I:n.toQ,O:n.P4d,kind:s.MethodKind.Unary},getUserAdminOrganizations:{name:"GetUserAdminOrganizations",I:n._V,O:n.KLX,kind:s.MethodKind.Unary},getTeamGithubUsers:{name:"GetTeamGithubUsers",I:n.yk8,O:n.ecN,kind:s.MethodKind.Unary},addGithubUsersToTeam:{name:"AddGithubUsersToTeam",I:n.gMg,O:n.yD7,kind:s.MethodKind.Unary},resolveGithubIdentities:{name:"ResolveGithubIdentities",I:n.lpG,O:n.LlT,kind:s.MethodKind.Unary},getUserPullRequests:{name:"GetUserPullRequests",I:n.Mq,O:n.M2w,kind:s.MethodKind.Unary},getUserReviewRequests:{name:"GetUserReviewRequests",I:n.Jjk,O:n.$DS,kind:s.MethodKind.Unary},getPullRequestForBranch:{name:"GetPullRequestForBranch",I:n.xGV,O:n.$EH,kind:s.MethodKind.Unary},updateGithubRepoSettings:{name:"UpdateGithubRepoSettings",I:n.NZ_,O:n.l8$,kind:s.MethodKind.Unary},updateGithubInstallationSettings:{name:"UpdateGithubInstallationSettings",I:n.J9i,O:n.T1W,kind:s.MethodKind.Unary},updateAllGithubRepoSettings:{name:"UpdateAllGithubRepoSettings",I:n.CNn,O:n.QOJ,kind:s.MethodKind.Unary},updateGithubInstallationTeamScope:{name:"UpdateGithubInstallationTeamScope",I:n.hxG,O:n.Lre,kind:s.MethodKind.Unary},updateSelfGithubAllowlist:{name:"UpdateSelfGithubAllowlist",I:n.pNh,O:n.vTx,kind:s.MethodKind.Unary},getTeamBugbotSettings:{name:"GetTeamBugbotSettings",I:n.LRN,O:n.Lg7,kind:s.MethodKind.Unary},updateTeamBugbotSettings:{name:"UpdateTeamBugbotSettings",I:n.sNl,O:n.Mlf,kind:s.MethodKind.Unary},migrateTeamBugbotToUsageBasedBilling:{name:"MigrateTeamBugbotToUsageBasedBilling",I:n.LIs,O:n.lW1,kind:s.MethodKind.Unary},getBugbotMergedPrScanSummary:{name:"GetBugbotMergedPrScanSummary",I:n.wS2,O:n.sWv,kind:s.MethodKind.Unary},getBugbotMode:{name:"GetBugbotMode",I:n.sVJ,O:n.YHh,kind:s.MethodKind.Unary},updateBugbotMode:{name:"UpdateBugbotMode",I:n.NQP,O:n.LK4,kind:s.MethodKind.Unary},getBugBotProUserMode:{name:"GetBugBotProUserMode",I:n.meH,O:n.ym8,kind:s.MethodKind.Unary},updateBugBotProUserMode:{name:"UpdateBugBotProUserMode",I:n.dj5,O:n.PFI,kind:s.MethodKind.Unary},getBugbotUserSettings:{name:"GetBugbotUserSettings",I:n.BHX,O:n.DLm,kind:s.MethodKind.Unary},updateBugbotUserSettings:{name:"UpdateBugbotUserSettings",I:n.QWx,O:n.Qsl,kind:s.MethodKind.Unary},getFullSelfDrivingUserSettings:{name:"GetFullSelfDrivingUserSettings",I:n.y$W,O:n.Ik0,kind:s.MethodKind.Unary},updateFullSelfDrivingUserSettings:{name:"UpdateFullSelfDrivingUserSettings",I:n.DrI,O:n.BRX,kind:s.MethodKind.Unary},listFullSelfDrivingRepoSettings:{name:"ListFullSelfDrivingRepoSettings",I:n.LdP,O:n.l1H,kind:s.MethodKind.Unary},setFullSelfDrivingRepoEnabled:{name:"SetFullSelfDrivingRepoEnabled",I:n.V6X,O:n.tJA,kind:s.MethodKind.Unary},getFullSelfDrivingTeamSettings:{name:"GetFullSelfDrivingTeamSettings",I:n.i20,O:n.M7A,kind:s.MethodKind.Unary},updateFullSelfDrivingTeamSettings:{name:"UpdateFullSelfDrivingTeamSettings",I:n.zuZ,O:n.Dfi,kind:s.MethodKind.Unary},listFullSelfDrivingTeamRepoSettings:{name:"ListFullSelfDrivingTeamRepoSettings",I:n.CXL,O:n.ybH,kind:s.MethodKind.Unary},setFullSelfDrivingTeamRepoEnabled:{name:"SetFullSelfDrivingTeamRepoEnabled",I:n.YBO,O:n.Soi,kind:s.MethodKind.Unary},listFullSelfDrivingActiveAgents:{name:"ListFullSelfDrivingActiveAgents",I:n.KHx,O:n.GPC,kind:s.MethodKind.Unary},listFullSelfDrivingTeamActiveAgents:{name:"ListFullSelfDrivingTeamActiveAgents",I:n.Hrn,O:n.pxf,kind:s.MethodKind.Unary},updateFullSelfDrivingPrConfig:{name:"UpdateFullSelfDrivingPrConfig",I:n.DWR,O:n.pGw,kind:s.MethodKind.Unary},getBugBotProUserSettings:{name:"GetBugBotProUserSettings",I:n.I6A,O:n.aBI,kind:s.MethodKind.Unary},updateBugBotProUserSettings:{name:"UpdateBugBotProUserSettings",I:n.hSh,O:n.P8G,kind:s.MethodKind.Unary},migrateBugBotProUserToUsageBasedBilling:{name:"MigrateBugBotProUserToUsageBasedBilling",I:n.E3$,O:n.MPB,kind:s.MethodKind.Unary},getGlassEarlyPreviewEnrollment:{name:"GetGlassEarlyPreviewEnrollment",I:n.Ryr,O:n.FPs,kind:s.MethodKind.Unary},enrollInGlassEarlyPreview:{name:"EnrollInGlassEarlyPreview",I:n.Cul,O:n.Y9v,kind:s.MethodKind.Unary},unenrollFromGlassEarlyPreview:{name:"UnenrollFromGlassEarlyPreview",I:n.UHP,O:n.UBK,kind:s.MethodKind.Unary},recordBugbotDeeplinkEvent:{name:"RecordBugbotDeeplinkEvent",I:n.sDp,O:n.Uj4,kind:s.MethodKind.Unary},recordBugbotDeeplinkEventUnauthenticated:{name:"RecordBugbotDeeplinkEventUnauthenticated",I:n.sDp,O:n.Uj4,kind:s.MethodKind.Unary},revokeBugBotLicenses:{name:"RevokeBugBotLicenses",I:n.H5R,O:n.Tcn,kind:s.MethodKind.Unary},revokeUserBugbotLicense:{name:"RevokeUserBugbotLicense",I:n.Z$K,O:n.FOE,kind:s.MethodKind.Unary},startBugbotBackfillLearning:{name:"StartBugbotBackfillLearning",I:n.NS4,O:n.xx6,kind:s.MethodKind.Unary},getBugbotBackfillStatus:{name:"GetBugbotBackfillStatus",I:n.Nux,O:n.hxv,kind:s.MethodKind.Unary},setSlackAuth:{name:"SetSlackAuth",I:n.WKP,O:n.mys,kind:s.MethodKind.Unary},getSlackTeamSettings:{name:"GetSlackTeamSettings",I:n.YAE,O:n.YyD,kind:s.MethodKind.Unary},updateSlackTeamSettings:{name:"UpdateSlackTeamSettings",I:n.HFD,O:n.Fr4,kind:s.MethodKind.Unary},getSlackSettings:{name:"GetSlackSettings",I:n.tcG,O:n.no,kind:s.MethodKind.Unary},getDeploymentIntegrationAvailability:{name:"GetDeploymentIntegrationAvailability",I:n.aPV,O:n.w_Q,kind:s.MethodKind.Unary},getSlackModelOptions:{name:"GetSlackModelOptions",I:n.lym,O:n.ddf,kind:s.MethodKind.Unary},getSlackInstallUrl:{name:"GetSlackInstallUrl",I:n.St,O:n.QKj,kind:s.MethodKind.Unary},getSlackInstallUrlPublic:{name:"GetSlackInstallUrlPublic",I:n.Xoe,O:n.ZoZ,kind:s.MethodKind.Unary},getSlackInstallUrlPublicWithUserScopes:{name:"GetSlackInstallUrlPublicWithUserScopes",I:n.Vqj,O:n.pty,kind:s.MethodKind.Unary},getFilteredUsageEvents:{name:"GetFilteredUsageEvents",I:n.FHO,O:n.TpA,kind:s.MethodKind.Unary},getAggregatedUsageEvents:{name:"GetAggregatedUsageEvents",I:n.l4W,O:n.JZY,kind:s.MethodKind.Unary},getAuditLogs:{name:"GetAuditLogs",I:n.Mq$,O:n.mTp,kind:s.MethodKind.Unary},getOrganizationAuditLogs:{name:"GetOrganizationAuditLogs",I:n.dIX,O:n.fIK,kind:s.MethodKind.Unary},listTeamDataExports:{name:"ListTeamDataExports",I:n.qC3,O:n.wHV,kind:s.MethodKind.Unary},createTeamDataExportDownloadUrl:{name:"CreateTeamDataExportDownloadUrl",I:n.eW$,O:n.eQk,kind:s.MethodKind.Unary},getUserPrivacyMode:{name:"GetUserPrivacyMode",I:n.KoG,O:n.mWk,kind:s.MethodKind.Unary},setUserPrivacyMode:{name:"SetUserPrivacyMode",I:n.eWf,O:n.Wig,kind:s.MethodKind.Unary},webAcknowledgeGracePeriodDisclaimer:{name:"WebAcknowledgeGracePeriodDisclaimer",I:n.sRz,O:n.mEf,kind:s.MethodKind.Unary},skipPrivacyModeGracePeriod:{name:"SkipPrivacyModeGracePeriod",I:n.jOB,O:n.dGI,kind:s.MethodKind.Unary},needsPrivacyModeMigration:{name:"NeedsPrivacyModeMigration",I:n.WWi,O:n.U5k,kind:s.MethodKind.Unary},updateTeamPrivacyModeMigrationOptOut:{name:"UpdateTeamPrivacyModeMigrationOptOut",I:n.es2,O:n.CKk,kind:s.MethodKind.Unary},shareConversation:{name:"ShareConversation",I:n.kHo,O:n.QhI,kind:s.MethodKind.Unary},getSharedConversation:{name:"GetSharedConversation",I:n.MyJ,O:n.mvz,kind:s.MethodKind.Unary},getPublicSharedConversation:{name:"GetPublicSharedConversation",I:n.ROu,O:n.xfP,kind:s.MethodKind.Unary},listSharedConversations:{name:"ListSharedConversations",I:n.R28,O:n.nMz,kind:s.MethodKind.Unary},deleteSharedConversation:{name:"DeleteSharedConversation",I:n.FUz,O:n.Z36,kind:s.MethodKind.Unary},updateSharedConversationVisibility:{name:"UpdateSharedConversationVisibility",I:n.NPW,O:n.JAL,kind:s.MethodKind.Unary},shareCanvas:{name:"ShareCanvas",I:n.tE3,O:n.lL7,kind:s.MethodKind.Unary},getSharedCanvas:{name:"GetSharedCanvas",I:n.JF,O:n.B2G,kind:s.MethodKind.Unary},getPublicSharedCanvas:{name:"GetPublicSharedCanvas",I:n.aE$,O:n.OCF,kind:s.MethodKind.Unary},listSharedCanvases:{name:"ListSharedCanvases",I:n.xos,O:n.xTz,kind:s.MethodKind.Unary},deleteSharedCanvas:{name:"DeleteSharedCanvas",I:n.shm,O:n._Md,kind:s.MethodKind.Unary},lookupSharedCanvasByKey:{name:"LookupSharedCanvasByKey",I:n.ptC,O:n.$bK,kind:s.MethodKind.Unary},listUserCanvases:{name:"ListUserCanvases",I:n.P_7,O:n.H1r,kind:s.MethodKind.Unary},getCanvasMetadata:{name:"GetCanvasMetadata",I:n.zyT,O:n.hcJ,kind:s.MethodKind.Unary},getCanvasPayload:{name:"GetCanvasPayload",I:n.gDx,O:n.K6f,kind:s.MethodKind.Unary},refreshCanvasSources:{name:"RefreshCanvasSources",I:n.TGZ,O:n.d6S,kind:s.MethodKind.Unary},runCanvasConnectorAction:{name:"RunCanvasConnectorAction",I:n.Ebu,O:n.E7l,kind:s.MethodKind.Unary},getCanvasPageBrand:{name:"GetCanvasPageBrand",I:n.SNZ,O:n.wEJ,kind:s.MethodKind.Unary},getDocumentPayload:{name:"GetDocumentPayload",I:n.r$m,O:n.ZB$,kind:s.MethodKind.Unary},setCanvasVisibility:{name:"SetCanvasVisibility",I:n.uKx,O:n._w7,kind:s.MethodKind.Unary},getCanvasShareAccess:{name:"GetCanvasShareAccess",I:n.dAQ,O:n.$sY,kind:s.MethodKind.Unary},updateCanvasShareAccess:{name:"UpdateCanvasShareAccess",I:n.YG,O:n.uNt,kind:s.MethodKind.Unary},setPageAddress:{name:"SetPageAddress",I:n.rhB,O:n.p5Q,kind:s.MethodKind.Unary},deleteCanvas:{name:"DeleteCanvas",I:n.J5_,O:n.xQH,kind:s.MethodKind.Unary},renameCanvas:{name:"RenameCanvas",I:n.k5b,O:n.icQ,kind:s.MethodKind.Unary},getTeamSharedConversationSettings:{name:"GetTeamSharedConversationSettings",I:n._b6,O:n.yTb,kind:s.MethodKind.Unary},updateTeamSharedConversationSettings:{name:"UpdateTeamSharedConversationSettings",I:n.TIw,O:n.rRJ,kind:s.MethodKind.Unary},getTeamSharedCanvasSettings:{name:"GetTeamSharedCanvasSettings",I:n.LWu,O:n.fZU,kind:s.MethodKind.Unary},updateTeamSharedCanvasSettings:{name:"UpdateTeamSharedCanvasSettings",I:n.iXm,O:n.k8Q,kind:s.MethodKind.Unary},getTeamProjectsSettings:{name:"GetTeamProjectsSettings",I:n.aJE,O:n.SRO,kind:s.MethodKind.Unary},updateTeamProjectsSettings:{name:"UpdateTeamProjectsSettings",I:n.xvP,O:n.nhk,kind:s.MethodKind.Unary},getTeamAppsSettings:{name:"GetTeamAppsSettings",I:n.OmT,O:n.GoT,kind:s.MethodKind.Unary},updateTeamAppsSettings:{name:"UpdateTeamAppsSettings",I:n.da6,O:n.zwl,kind:s.MethodKind.Unary},getTeamAppsReviewRules:{name:"GetTeamAppsReviewRules",I:n.CNw,O:n.iR7,kind:s.MethodKind.Unary},listTeamAppsReviewRulesVersions:{name:"ListTeamAppsReviewRulesVersions",I:n.pbO,O:n.xim,kind:s.MethodKind.Unary},getTeamAppsReviewRulesVersion:{name:"GetTeamAppsReviewRulesVersion",I:n.kfB,O:n.iwy,kind:s.MethodKind.Unary},saveTeamAppsReviewRules:{name:"SaveTeamAppsReviewRules",I:n.XRd,O:n.joE,kind:s.MethodKind.Unary},activateTeamAppsReviewRulesVersion:{name:"ActivateTeamAppsReviewRulesVersion",I:n.fdV,O:n.VVb,kind:s.MethodKind.Unary},getTeamPublicProfileSettings:{name:"GetTeamPublicProfileSettings",I:n.K$9,O:n.yVw,kind:s.MethodKind.Unary},updateTeamPublicProfileSettings:{name:"UpdateTeamPublicProfileSettings",I:n.VIg,O:n.lxh,kind:s.MethodKind.Unary},getTeamSandShareBotExportSettings:{name:"GetTeamSandShareBotExportSettings",I:Dc,O:Nc,kind:s.MethodKind.Unary},updateTeamSandShareBotExportSettings:{name:"UpdateTeamSandShareBotExportSettings",I:Gc,O:Lc,kind:s.MethodKind.Unary},updateTeamGrokBotCapabilities:{name:"UpdateTeamGrokBotCapabilities",I:Kc,O:Hc,kind:s.MethodKind.Unary},getTeamGrokBotConnectorAudiences:{name:"GetTeamGrokBotConnectorAudiences",I:Yc,O:Zc,kind:s.MethodKind.Unary},updateTeamGrokBotConnectorAudience:{name:"UpdateTeamGrokBotConnectorAudience",I:tl,O:rl,kind:s.MethodKind.Unary},getTeamDataRetentionPolicy:{name:"GetTeamDataRetentionPolicy",I:n.ZvO,O:n.bhm,kind:s.MethodKind.Unary},updateTeamDataRetentionPolicy:{name:"UpdateTeamDataRetentionPolicy",I:n.bLK,O:n.YbK,kind:s.MethodKind.Unary},getTeamGrokBotSlackWorkspaceAccess:{name:"GetTeamGrokBotSlackWorkspaceAccess",I:sl,O:il,kind:s.MethodKind.Unary},setTeamGrokBotSlackWorkspaceAccess:{name:"SetTeamGrokBotSlackWorkspaceAccess",I:ol,O:al,kind:s.MethodKind.Unary},listTeamGrokBotDefaultAgents:{name:"ListTeamGrokBotDefaultAgents",I:ul,O:cl,kind:s.MethodKind.Unary},setTeamGrokBotDefaultAudience:{name:"SetTeamGrokBotDefaultAudience",I:ll,O:ml,kind:s.MethodKind.Unary},setTeamGrokBotAgentTeamApproved:{name:"SetTeamGrokBotAgentTeamApproved",I:fl,O:dl,kind:s.MethodKind.Unary},listTeamGrokBotAgentAccess:{name:"ListTeamGrokBotAgentAccess",I:hl,O:gl,kind:s.MethodKind.Unary},setTeamGrokBotAgentAccess:{name:"SetTeamGrokBotAgentAccess",I:_l,O:Jl,kind:s.MethodKind.Unary},listTeamGrokBotDashboardAccess:{name:"ListTeamGrokBotDashboardAccess",I:vd,O:xd,kind:s.MethodKind.Unary},setTeamGrokBotDashboardAccess:{name:"SetTeamGrokBotDashboardAccess",I:kd,O:Ed,kind:s.MethodKind.Unary},listTeamGrokBotAccessTeams:{name:"ListTeamGrokBotAccessTeams",I:yl,O:Sl,kind:s.MethodKind.Unary},previewTeamGrokBotAgentTransfer:{name:"PreviewTeamGrokBotAgentTransfer",I:ql,O:Bl,kind:s.MethodKind.Unary},transferTeamGrokBotAgents:{name:"TransferTeamGrokBotAgents",I:Il,O:Pl,kind:s.MethodKind.Unary},getTeamGrokBotAgentTransfers:{name:"GetTeamGrokBotAgentTransfers",I:bl,O:Rl,kind:s.MethodKind.Unary},listTeamGrokBotTransferDestinations:{name:"ListTeamGrokBotTransferDestinations",I:vl,O:xl,kind:s.MethodKind.Unary},startTeamGrokBotOwnershipTransfer:{name:"StartTeamGrokBotOwnershipTransfer",I:kl,O:El,kind:s.MethodKind.Unary},getTeamSmartAutoSettings:{name:"GetTeamSmartAutoSettings",I:n.WjG,O:n.OBF,kind:s.MethodKind.Unary},updateTeamSmartAutoSettings:{name:"UpdateTeamSmartAutoSettings",I:n.Xtc,O:n.bIg,kind:s.MethodKind.Unary},getTeamPromptCachingSettings:{name:"GetTeamPromptCachingSettings",I:n.H1L,O:n.P8_,kind:s.MethodKind.Unary},updateTeamPromptCachingSettings:{name:"UpdateTeamPromptCachingSettings",I:n.omy,O:n.wgB,kind:s.MethodKind.Unary},resetTeamAgentRunModeToAutoReview:{name:"ResetTeamAgentRunModeToAutoReview",I:n.L2q,O:n.Jiu,kind:s.MethodKind.Unary},getUserSmartAutoSettings:{name:"GetUserSmartAutoSettings",I:n.c$y,O:n.cHR,kind:s.MethodKind.Unary},updateUserSmartAutoSettings:{name:"UpdateUserSmartAutoSettings",I:n.ZVF,O:n.zri,kind:s.MethodKind.Unary},getTeamBackgroundAgentSettings:{name:"GetTeamBackgroundAgentSettings",I:n.fQ,O:n.bNb,kind:s.MethodKind.Unary},getTeamGrokBotPublishedWorkerImage:{name:"GetTeamGrokBotPublishedWorkerImage",I:_d,O:wd,kind:s.MethodKind.Unary},updateTeamBackgroundAgentSettings:{name:"UpdateTeamBackgroundAgentSettings",I:n.QRZ,O:n.Iz5,kind:s.MethodKind.Unary},listTeamGrokBotCustomerHostedWorkers:{name:"ListTeamGrokBotCustomerHostedWorkers",I:yd,O:Sd,kind:s.MethodKind.Unary},getRepoSourcePreference:{name:"GetRepoSourcePreference",I:n.qc8,O:n.Mtj,kind:s.MethodKind.Unary},updateUserRepoSourcePreference:{name:"UpdateUserRepoSourcePreference",I:n.G6u,O:n._E_,kind:s.MethodKind.Unary},updateTeamRepoSourcePreference:{name:"UpdateTeamRepoSourcePreference",I:n.gez,O:n.MYI,kind:s.MethodKind.Unary},resolvePrCreationForge:{name:"ResolvePrCreationForge",I:n.OaX,O:n.MX_,kind:s.MethodKind.Unary},revokeTeamInviteLink:{name:"RevokeTeamInviteLink",I:n.yKm,O:n.mmN,kind:s.MethodKind.Unary},listTeamInviteLinks:{name:"ListTeamInviteLinks",I:n.$WS,O:n.Rc0,kind:s.MethodKind.Unary},listTeamPendingInvites:{name:"ListTeamPendingInvites",I:n.E7o,O:n.MLT,kind:s.MethodKind.Unary},revokeTeamPendingInvite:{name:"RevokeTeamPendingInvite",I:n.BaU,O:n.tRU,kind:s.MethodKind.Unary},resendTeamPendingInvite:{name:"ResendTeamPendingInvite",I:n.Y53,O:n.Ip9,kind:s.MethodKind.Unary},listTeamJoinRequests:{name:"ListTeamJoinRequests",I:n.ryS,O:n.rV_,kind:s.MethodKind.Unary},approveTeamJoinRequest:{name:"ApproveTeamJoinRequest",I:n.flK,O:n.Pqr,kind:s.MethodKind.Unary},denyTeamJoinRequest:{name:"DenyTeamJoinRequest",I:n.c9k,O:n.gTH,kind:s.MethodKind.Unary},updateUserName:{name:"UpdateUserName",I:n.bjc,O:n.lLB,kind:s.MethodKind.Unary},uploadUserProfilePicture:{name:"UploadUserProfilePicture",I:n.J3_,O:n.jzZ,kind:s.MethodKind.Unary},updateUserProfilePicture:{name:"UpdateUserProfilePicture",I:n.hLX,O:n.lYk,kind:s.MethodKind.Unary},listInvoices:{name:"ListInvoices",I:n.WXZ,O:n.YeS,kind:s.MethodKind.Unary},listUnifiedInvoices:{name:"ListUnifiedInvoices",I:Te,O:Ae,kind:s.MethodKind.Unary},getComplatCreditBalance:{name:"GetComplatCreditBalance",I:n.Hdt,O:n.F9z,kind:s.MethodKind.Unary},listBlockingCheckoutInvoices:{name:"ListBlockingCheckoutInvoices",I:n.hHX,O:n.D7O,kind:s.MethodKind.Unary},listPayableTeamInvoices:{name:"ListPayableTeamInvoices",I:n.Z_i,O:n.jiy,kind:s.MethodKind.Unary},listUnpaidUsageInvoices:{name:"ListUnpaidUsageInvoices",I:n.QBt,O:n.SQ3,kind:s.MethodKind.Unary},getRemainingRefunds:{name:"GetRemainingRefunds",I:n.Xdv,O:n.hzd,kind:s.MethodKind.Unary},getServiceAccountSpendLimit:{name:"GetServiceAccountSpendLimit",I:n.f_r,O:n.bJx,kind:s.MethodKind.Unary},setServiceAccountSpendLimit:{name:"SetServiceAccountSpendLimit",I:n.bkm,O:n.Vau,kind:s.MethodKind.Unary},setUserHardLimit:{name:"SetUserHardLimit",I:n.H16,O:n.Tw9,kind:s.MethodKind.Unary},setUserMonthlyLimit:{name:"SetUserMonthlyLimit",I:n.lEN,O:n.Z1Y,kind:s.MethodKind.Unary},toggleMarketingEmailOpt:{name:"ToggleMarketingEmailOpt",I:n.bQB,O:n.Z6E,kind:s.MethodKind.Unary},getMarketingEmailOpt:{name:"GetMarketingEmailOpt",I:n.fZH,O:n.hBo,kind:s.MethodKind.Unary},getGlobalLeaderboardOptIn:{name:"GetGlobalLeaderboardOptIn",I:n.A9x,O:n.u01,kind:s.MethodKind.Unary},setGlobalLeaderboardOptIn:{name:"SetGlobalLeaderboardOptIn",I:n.AB3,O:n.IXm,kind:s.MethodKind.Unary},createTeamApiKey:{name:"CreateTeamApiKey",I:n._C2,O:n.Mdl,kind:s.MethodKind.Unary},revokeTeamApiKey:{name:"RevokeTeamApiKey",I:n._Rg,O:n.ubM,kind:s.MethodKind.Unary},listTeamApiKeys:{name:"ListTeamApiKeys",I:n.dMs,O:n.Tsf,kind:s.MethodKind.Unary},listGrokApiKeys:{name:"ListGrokApiKeys",I:n.V5S,O:n.lc$,kind:s.MethodKind.Unary},getPersonalGrokApiKeyTeam:{name:"GetPersonalGrokApiKeyTeam",I:n.jWS,O:n.J41,kind:s.MethodKind.Unary},listGrokApiKeyAclOptions:{name:"ListGrokApiKeyAclOptions",I:n.yeW,O:n.ANW,kind:s.MethodKind.Unary},listGrokModels:{name:"ListGrokModels",I:n.flG,O:n.fMA,kind:s.MethodKind.Unary},listGrokBatches:{name:"ListGrokBatches",I:n.rih,O:n.dKG,kind:s.MethodKind.Unary},getGrokBatch:{name:"GetGrokBatch",I:n.jRA,O:n.RhX,kind:s.MethodKind.Unary},listGrokBatchRequests:{name:"ListGrokBatchRequests",I:n.Zav,O:n.DyZ,kind:s.MethodKind.Unary},getGrokBatchRequestResult:{name:"GetGrokBatchRequestResult",I:n.N2o,O:n.X26,kind:s.MethodKind.Unary},createGrokBatch:{name:"CreateGrokBatch",I:n.d7o,O:n.LRW,kind:s.MethodKind.Unary},cancelGrokBatch:{name:"CancelGrokBatch",I:n.Vi2,O:n.lXe,kind:s.MethodKind.Unary},listGrokBuiltInVoices:{name:"ListGrokBuiltInVoices",I:n.FFN,O:n.dO8,kind:s.MethodKind.Unary},listGrokCustomVoices:{name:"ListGrokCustomVoices",I:n.ned,O:n.R6h,kind:s.MethodKind.Unary},updateGrokCustomVoice:{name:"UpdateGrokCustomVoice",I:n.F5S,O:n.PTw,kind:s.MethodKind.Unary},deleteGrokCustomVoice:{name:"DeleteGrokCustomVoice",I:n.Pzk,O:n.n2r,kind:s.MethodKind.Unary},getGrokVoiceCloningAccess:{name:"GetGrokVoiceCloningAccess",I:n.dt7,O:n.p0o,kind:s.MethodKind.Unary},getGrokVoiceClonePassphrase:{name:"GetGrokVoiceClonePassphrase",I:n.Mly,O:n.QJW,kind:s.MethodKind.Unary},cloneGrokCustomVoice:{name:"CloneGrokCustomVoice",I:n.n$8,O:n.VxM,kind:s.MethodKind.Unary},listGrokFiles:{name:"ListGrokFiles",I:n.udh,O:n.ahg,kind:s.MethodKind.Unary},getGrokFile:{name:"GetGrokFile",I:n.Vt$,O:n.$X0,kind:s.MethodKind.Unary},updateGrokFile:{name:"UpdateGrokFile",I:n.gSd,O:n.Egt,kind:s.MethodKind.Unary},deleteGrokFile:{name:"DeleteGrokFile",I:n.yqI,O:n.YxF,kind:s.MethodKind.Unary},createGrokFilePublicUrl:{name:"CreateGrokFilePublicUrl",I:n.Vbl,O:n.lQ7,kind:s.MethodKind.Unary},revokeGrokFilePublicUrl:{name:"RevokeGrokFilePublicUrl",I:n.$lB,O:n.XSC,kind:s.MethodKind.Unary},listGrokCollections:{name:"ListGrokCollections",I:n.a_n,O:n.g$E,kind:s.MethodKind.Unary},getGrokCollection:{name:"GetGrokCollection",I:n.VGL,O:n.lj2,kind:s.MethodKind.Unary},createGrokCollection:{name:"CreateGrokCollection",I:n.Z9k,O:n.rxf,kind:s.MethodKind.Unary},updateGrokCollection:{name:"UpdateGrokCollection",I:n.kZD,O:n.U$g,kind:s.MethodKind.Unary},deleteGrokCollection:{name:"DeleteGrokCollection",I:n.W5o,O:n.c0r,kind:s.MethodKind.Unary},cloneGrokCollection:{name:"CloneGrokCollection",I:n.wKn,O:n.wIY,kind:s.MethodKind.Unary},generateGrokCollectionDescription:{name:"GenerateGrokCollectionDescription",I:n.ke0,O:n.q1P,kind:s.MethodKind.Unary},listRelatedGrokCollections:{name:"ListRelatedGrokCollections",I:n.zdO,O:n.HwU,kind:s.MethodKind.Unary},listGrokCollectionEmbeddingModels:{name:"ListGrokCollectionEmbeddingModels",I:n.Q_u,O:n.Sj7,kind:s.MethodKind.Unary},listGrokCollectionDocuments:{name:"ListGrokCollectionDocuments",I:n.RAf,O:n.nYQ,kind:s.MethodKind.Unary},batchGetGrokCollectionDocuments:{name:"BatchGetGrokCollectionDocuments",I:n.bJ2,O:n.TOY,kind:s.MethodKind.Unary},addGrokCollectionDocument:{name:"AddGrokCollectionDocument",I:n.zyk,O:n.LLT,kind:s.MethodKind.Unary},updateGrokCollectionDocument:{name:"UpdateGrokCollectionDocument",I:n.X0z,O:n.zxO,kind:s.MethodKind.Unary},removeGrokCollectionDocument:{name:"RemoveGrokCollectionDocument",I:n.GsS,O:n.YjQ,kind:s.MethodKind.Unary},reindexGrokCollectionDocument:{name:"ReindexGrokCollectionDocument",I:n.h$Z,O:n.lWu,kind:s.MethodKind.Unary},getGrokApiKeyAccess:{name:"GetGrokApiKeyAccess",I:n.Muw,O:n.OFG,kind:s.MethodKind.Unary},getGrokTeamWatermarking:{name:"GetGrokTeamWatermarking",I:n.Il7,O:n.SMz,kind:s.MethodKind.Unary},setGrokTeamWatermarking:{name:"SetGrokTeamWatermarking",I:n.iiN,O:n.Qdp,kind:s.MethodKind.Unary},getGrokTeamZdr:{name:"GetGrokTeamZdr",I:n.sLc,O:n.CC0,kind:s.MethodKind.Unary},setGrokTeamZdr:{name:"SetGrokTeamZdr",I:n.S8y,O:n.QjN,kind:s.MethodKind.Unary},getGrokApiKeyPropagation:{name:"GetGrokApiKeyPropagation",I:n.yED,O:n._2X,kind:s.MethodKind.Unary},createGrokApiKey:{name:"CreateGrokApiKey",I:n.m5V,O:n.MSw,kind:s.MethodKind.Unary},deleteGrokApiKey:{name:"DeleteGrokApiKey",I:n.nG3,O:n.T78,kind:s.MethodKind.Unary},updateGrokApiKey:{name:"UpdateGrokApiKey",I:n.laE,O:n.TCm,kind:s.MethodKind.Unary},setGrokApiKeyAcls:{name:"SetGrokApiKeyAcls",I:n.RDD,O:n.lmF,kind:s.MethodKind.Unary},rotateGrokApiKey:{name:"RotateGrokApiKey",I:n.pTw,O:n.DZc,kind:s.MethodKind.Unary},getGrokAdminFeatureControls:{name:"GetGrokAdminFeatureControls",I:n._NS,O:n.eTm,kind:s.MethodKind.Unary},updateGrokAdminFeatureControls:{name:"UpdateGrokAdminFeatureControls",I:n.XKz,O:n.H7s,kind:s.MethodKind.Unary},getGrokUserDataControls:{name:"GetGrokUserDataControls",I:n.eNQ,O:n.efP,kind:s.MethodKind.Unary},updateGrokUserDataControls:{name:"UpdateGrokUserDataControls",I:n.$yS,O:n.XrM,kind:s.MethodKind.Unary},listGrokRequestLogs:{name:"ListGrokRequestLogs",I:n.dU3,O:n.pxp,kind:s.MethodKind.Unary},listGrokRequestLogBodies:{name:"ListGrokRequestLogBodies",I:n._Yf,O:n.g9i,kind:s.MethodKind.Unary},listGrokVoiceConversations:{name:"ListGrokVoiceConversations",I:n.Vg9,O:n.xXb,kind:s.MethodKind.Unary},getGrokAdminTeamSettings:{name:"GetGrokAdminTeamSettings",I:n.SuU,O:n.yms,kind:s.MethodKind.Unary},updateGrokAdminTeamSettings:{name:"UpdateGrokAdminTeamSettings",I:n.rCL,O:n.nbk,kind:s.MethodKind.Unary},getGrokAdminOrganizationControls:{name:"GetGrokAdminOrganizationControls",I:n.lxC,O:n.nxh,kind:s.MethodKind.Unary},updateGrokAdminOrganizationControls:{name:"UpdateGrokAdminOrganizationControls",I:n.GKl,O:n.GIW,kind:s.MethodKind.Unary},listGrokAdminGuardrails:{name:"ListGrokAdminGuardrails",I:n.OOr,O:n.iwb,kind:s.MethodKind.Unary},getGrokAdminGuardrail:{name:"GetGrokAdminGuardrail",I:n.nxD,O:n.Hux,kind:s.MethodKind.Unary},createGrokAdminGuardrail:{name:"CreateGrokAdminGuardrail",I:n.ZN0,O:n.DdV,kind:s.MethodKind.Unary},updateGrokAdminGuardrail:{name:"UpdateGrokAdminGuardrail",I:n.uuc,O:n.eo$,kind:s.MethodKind.Unary},removeGrokAdminGuardrail:{name:"RemoveGrokAdminGuardrail",I:n.RJA,O:n.$ph,kind:s.MethodKind.Unary},setGrokAdminGuardrailActive:{name:"SetGrokAdminGuardrailActive",I:n.dhe,O:n.PjD,kind:s.MethodKind.Unary},deactivateGrokAdminGuardrail:{name:"DeactivateGrokAdminGuardrail",I:n.rhR,O:n.RVM,kind:s.MethodKind.Unary},getGrokAdminBlockedUrls:{name:"GetGrokAdminBlockedUrls",I:n.ovf,O:n._oI,kind:s.MethodKind.Unary},uploadGrokAdminBlockedUrls:{name:"UploadGrokAdminBlockedUrls",I:n.fRF,O:n.TkS,kind:s.MethodKind.Unary},deleteGrokAdminBlockedUrls:{name:"DeleteGrokAdminBlockedUrls",I:n.nc6,O:n.Hdd,kind:s.MethodKind.Unary},listGrokAdminOnboardingPrompts:{name:"ListGrokAdminOnboardingPrompts",I:n.cl3,O:n.cf9,kind:s.MethodKind.Unary},createGrokAdminOnboardingPrompt:{name:"CreateGrokAdminOnboardingPrompt",I:n.byf,O:n.vXf,kind:s.MethodKind.Unary},updateGrokAdminOnboardingPrompt:{name:"UpdateGrokAdminOnboardingPrompt",I:n.wOq,O:n.M2G,kind:s.MethodKind.Unary},deleteGrokAdminOnboardingPrompt:{name:"DeleteGrokAdminOnboardingPrompt",I:n.aW7,O:n._yh,kind:s.MethodKind.Unary},listXaiManagementApiKeys:{name:"ListXaiManagementApiKeys",I:n.ruw,O:n.xAe,kind:s.MethodKind.Unary},createXaiManagementApiKey:{name:"CreateXaiManagementApiKey",I:n.azC,O:n.cSQ,kind:s.MethodKind.Unary},updateXaiManagementApiKey:{name:"UpdateXaiManagementApiKey",I:n.dR6,O:n.P1K,kind:s.MethodKind.Unary},deleteXaiManagementApiKey:{name:"DeleteXaiManagementApiKey",I:n.hSg,O:n.rGX,kind:s.MethodKind.Unary},listXaiManagementApiKeyEndpointAcls:{name:"ListXaiManagementApiKeyEndpointAcls",I:n._Br,O:n.ylO,kind:s.MethodKind.Unary},createOrganizationApiKey:{name:"CreateOrganizationApiKey",I:n.KFb,O:n.WRW,kind:s.MethodKind.Unary},revokeOrganizationApiKey:{name:"RevokeOrganizationApiKey",I:n.W6d,O:n.G0c,kind:s.MethodKind.Unary},listOrganizationApiKeys:{name:"ListOrganizationApiKeys",I:n.bC9,O:n.Xtv,kind:s.MethodKind.Unary},createAutomationWebhookApiKey:{name:"CreateAutomationWebhookApiKey",I:n.nL6,O:n.rEt,kind:s.MethodKind.Unary},createTeamServiceAccount:{name:"CreateTeamServiceAccount",I:n.HYO,O:n.loJ,kind:s.MethodKind.Unary},listTeamServiceAccounts:{name:"ListTeamServiceAccounts",I:n.SMM,O:n.AhK,kind:s.MethodKind.Unary},deleteTeamServiceAccount:{name:"DeleteTeamServiceAccount",I:n.IaO,O:n.WLQ,kind:s.MethodKind.Unary},archiveTeamServiceAccount:{name:"ArchiveTeamServiceAccount",I:n.X2v,O:n.B6m,kind:s.MethodKind.Unary},updateTeamServiceAccount:{name:"UpdateTeamServiceAccount",I:n.Ca8,O:n.m6C,kind:s.MethodKind.Unary},suspendTeamServiceAccount:{name:"SuspendTeamServiceAccount",I:Up,O:Ap,kind:s.MethodKind.Unary},resumeTeamServiceAccount:{name:"ResumeTeamServiceAccount",I:$p,O:Mp,kind:s.MethodKind.Unary},rotateServiceAccountApiKey:{name:"RotateServiceAccountApiKey",I:n.OCy,O:n.sJP,kind:s.MethodKind.Unary},getTeamRepositoriesForServiceAccountScope:{name:"GetTeamRepositoriesForServiceAccountScope",I:n.EwB,O:n.Eav,kind:s.MethodKind.Unary},updateServiceAccountRepoScope:{name:"UpdateServiceAccountRepoScope",I:n.RZf,O:n.d6k,kind:s.MethodKind.Unary},startStepUp:{name:"StartStepUp",I:n.PZt,O:n.tJL,kind:s.MethodKind.Unary},getStepUpStatus:{name:"GetStepUpStatus",I:n.Din,O:n.BMV,kind:s.MethodKind.Unary},describeStepUpLink:{name:"DescribeStepUpLink",I:n._mp,O:n.sX6,kind:s.MethodKind.Unary},confirmStepUpLink:{name:"ConfirmStepUpLink",I:n.$bV,O:n.boh,kind:s.MethodKind.Unary},createUserApiKey:{name:"CreateUserApiKey",I:n.cEg,O:n.Aa9,kind:s.MethodKind.Unary},revokeUserApiKey:{name:"RevokeUserApiKey",I:n.GOY,O:n.yQR,kind:s.MethodKind.Unary},listUserApiKeys:{name:"ListUserApiKeys",I:n.juR,O:n.ZCs,kind:s.MethodKind.Unary},listMemberPersonalApiKeys:{name:"ListMemberPersonalApiKeys",I:n.Cl5,O:n.UEj,kind:s.MethodKind.Unary},revokeMemberPersonalApiKeys:{name:"RevokeMemberPersonalApiKeys",I:n.Gci,O:n.K_N,kind:s.MethodKind.Unary},searchApiKeys:{name:"SearchApiKeys",I:n.C4E,O:n.ya8,kind:s.MethodKind.Unary},listTeamCredentialsFromFormerMembers:{name:"ListTeamCredentialsFromFormerMembers",I:n.F70,O:n.$bL,kind:s.MethodKind.Unary},staffSearchApiKeys:{name:"StaffSearchApiKeys",I:n.S2v,O:n.w9I,kind:s.MethodKind.Unary},staffRevokeApiKey:{name:"StaffRevokeApiKey",I:n.vxR,O:n.bOn,kind:s.MethodKind.Unary},staffSuspendServiceAccount:{name:"StaffSuspendServiceAccount",I:n.MGn,O:n.ISK,kind:s.MethodKind.Unary},staffResumeServiceAccount:{name:"StaffResumeServiceAccount",I:n.MGn,O:n.ISK,kind:s.MethodKind.Unary},staffArchiveServiceAccount:{name:"StaffArchiveServiceAccount",I:n.MGn,O:n.ISK,kind:s.MethodKind.Unary},staffDeleteServiceAccount:{name:"StaffDeleteServiceAccount",I:n.MGn,O:n.ISK,kind:s.MethodKind.Unary},staffListOwnerApiKeys:{name:"StaffListOwnerApiKeys",I:n.Ja4,O:n.yY2,kind:s.MethodKind.Unary},staffListServiceAccountApiKeys:{name:"StaffListServiceAccountApiKeys",I:n.ogM,O:n.yY2,kind:s.MethodKind.Unary},listTeamMemberSessions:{name:"ListTeamMemberSessions",I:n.Ifk,O:n.NsN,kind:s.MethodKind.Unary},revokeTeamMemberSession:{name:"RevokeTeamMemberSession",I:n.vDi,O:n.ElN,kind:s.MethodKind.Unary},listOrganizationMemberSessions:{name:"ListOrganizationMemberSessions",I:n.AUt,O:n.NsN,kind:s.MethodKind.Unary},revokeOrganizationMemberSession:{name:"RevokeOrganizationMemberSession",I:n.fOQ,O:n.ElN,kind:s.MethodKind.Unary},createServiceToken:{name:"CreateServiceToken",I:n.C10,O:n.e7b,kind:s.MethodKind.Unary},listServiceTokens:{name:"ListServiceTokens",I:n.v0n,O:n.X1$,kind:s.MethodKind.Unary},listCursorApiKeys:{name:"ListCursorApiKeys",I:n.UkG,O:n.S$9,kind:s.MethodKind.Unary},updateServiceTokenPermissions:{name:"UpdateServiceTokenPermissions",I:n.Fo6,O:n.rA8,kind:s.MethodKind.Unary},revokeServiceToken:{name:"RevokeServiceToken",I:n.yYY,O:n.w$r,kind:s.MethodKind.Unary},rotateServiceToken:{name:"RotateServiceToken",I:n.Rbl,O:n.t8U,kind:s.MethodKind.Unary},listOAuthApplications:{name:"ListOAuthApplications",I:n._2n,O:n.WAf,kind:s.MethodKind.Unary},createOAuthApplication:{name:"CreateOAuthApplication",I:n.XQi,O:n.FGN,kind:s.MethodKind.Unary},updateOAuthApplication:{name:"UpdateOAuthApplication",I:n.yoo,O:n.fzp,kind:s.MethodKind.Unary},rotateOAuthApplicationSecret:{name:"RotateOAuthApplicationSecret",I:n.wid,O:n.MwB,kind:s.MethodKind.Unary},setOAuthApplicationEnabled:{name:"SetOAuthApplicationEnabled",I:n.sy,O:n.uV,kind:s.MethodKind.Unary},deleteOAuthApplication:{name:"DeleteOAuthApplication",I:n.qtO,O:n.eVU,kind:s.MethodKind.Unary},uploadOAuthApplicationLogo:{name:"UploadOAuthApplicationLogo",I:n.P1X,O:n.VxX,kind:s.MethodKind.Unary},listTrustedIssuers:{name:"ListTrustedIssuers",I:n.rd_,O:n.rkz,kind:s.MethodKind.Unary},getAuthApplicationsOwnerGate:{name:"GetAuthApplicationsOwnerGate",I:n.rav,O:n.$bx,kind:s.MethodKind.Unary},createTrustedIssuer:{name:"CreateTrustedIssuer",I:n._Qn,O:n.UzA,kind:s.MethodKind.Unary},updateTrustedIssuer:{name:"UpdateTrustedIssuer",I:n.Ebf,O:n.Huz,kind:s.MethodKind.Unary},setTrustedIssuerEnabled:{name:"SetTrustedIssuerEnabled",I:n.DEp,O:n.zBo,kind:s.MethodKind.Unary},revokeTrustedIssuer:{name:"RevokeTrustedIssuer",I:n.kUF,O:n.OV9,kind:s.MethodKind.Unary},registerTrustedIssuerPublicKey:{name:"RegisterTrustedIssuerPublicKey",I:n.hEC,O:n.XUz,kind:s.MethodKind.Unary},revokeTrustedIssuerPublicKey:{name:"RevokeTrustedIssuerPublicKey",I:n.g7r,O:n.A7H,kind:s.MethodKind.Unary},revokeTrustedIssuerGrants:{name:"RevokeTrustedIssuerGrants",I:n.VDS,O:n.nRh,kind:s.MethodKind.Unary},getOAuthAuthorizationRequest:{name:"GetOAuthAuthorizationRequest",I:n.NEG,O:n.dtn,kind:s.MethodKind.Unary},approveOAuthAuthorizationRequest:{name:"ApproveOAuthAuthorizationRequest",I:n.Wew,O:n.AZo,kind:s.MethodKind.Unary},listAuthorizedApplications:{name:"ListAuthorizedApplications",I:n.aul,O:n.c$T,kind:s.MethodKind.Unary},revokeAuthorizedApplication:{name:"RevokeAuthorizedApplication",I:n.X58,O:n.tXQ,kind:s.MethodKind.Unary},confirmGithubInstallation:{name:"ConfirmGithubInstallation",I:n.tI8,O:n.xpT,kind:s.MethodKind.Unary},updateTeamName:{name:"UpdateTeamName",I:n.l5I,O:n.FsH,kind:s.MethodKind.Unary},uploadTeamIcon:{name:"UploadTeamIcon",I:n.DLo,O:n.zQx,kind:s.MethodKind.Unary},updateTeamIcon:{name:"UpdateTeamIcon",I:n.Hdl,O:n.hHL,kind:s.MethodKind.Unary},updateTeamDashboardAnalyticsSetting:{name:"UpdateTeamDashboardAnalyticsSetting",I:n.CoZ,O:n.YZV,kind:s.MethodKind.Unary},updateTeamOriginSetting:{name:"UpdateTeamOriginSetting",I:n.YgU,O:n.G3W,kind:s.MethodKind.Unary},updateTeamScimRequireUserDirectorySetting:{name:"UpdateTeamScimRequireUserDirectorySetting",I:n.zul,O:n.L5U,kind:s.MethodKind.Unary},getTeamScimRequireUserDirectoryPreview:{name:"GetTeamScimRequireUserDirectoryPreview",I:n.Uto,O:n.EHd,kind:s.MethodKind.Unary},getEffectiveUserAgentStoreSkillsSettings:{name:"GetEffectiveUserAgentStoreSkillsSettings",I:n.hVj,O:n.b$E,kind:s.MethodKind.Unary},updateUserAgentStoreSkillsSettings:{name:"UpdateUserAgentStoreSkillsSettings",I:n.Vry,O:n.nNe,kind:s.MethodKind.Unary},getSlackUserSettings:{name:"GetSlackUserSettings",I:n.e0r,O:n.ewI,kind:s.MethodKind.Unary},updateSlackUserSettings:{name:"UpdateSlackUserSettings",I:n.F5_,O:n.Lt9,kind:s.MethodKind.Unary},setSlackCursorTeam:{name:"SetSlackCursorTeam",I:n.GLj,O:n.deZ,kind:s.MethodKind.Unary},getSlackRepoRoutingRules:{name:"GetSlackRepoRoutingRules",I:n.hE5,O:n.LGY,kind:s.MethodKind.Unary},createSlackRepoRoutingRule:{name:"CreateSlackRepoRoutingRule",I:n.EMn,O:n.QEY,kind:s.MethodKind.Unary},updateSlackRepoRoutingRule:{name:"UpdateSlackRepoRoutingRule",I:n.xcI,O:n.hbx,kind:s.MethodKind.Unary},deleteSlackRepoRoutingRule:{name:"DeleteSlackRepoRoutingRule",I:n.Bz7,O:n.Tfn,kind:s.MethodKind.Unary},getSlackDefaultWorkerRules:{name:"GetSlackDefaultWorkerRules",I:n.eOv,O:n.gpX,kind:s.MethodKind.Unary},setSlackDefaultWorkerRule:{name:"SetSlackDefaultWorkerRule",I:n.dn0,O:n.P7l,kind:s.MethodKind.Unary},deleteSlackDefaultWorkerRule:{name:"DeleteSlackDefaultWorkerRule",I:n.CGB,O:n.sHT,kind:s.MethodKind.Unary},isOnNewPricing:{name:"IsOnNewPricing",I:n.HxK,O:n.jAL,kind:s.MethodKind.Unary},getLinearAuthUrl:{name:"GetLinearAuthUrl",I:n._9N,O:n.wet,kind:s.MethodKind.Unary},connectLinearCallback:{name:"ConnectLinearCallback",I:n.wlK,O:n.Adp,kind:s.MethodKind.Unary},getMicrosoftTeamsLinkContext:{name:"GetMicrosoftTeamsLinkContext",I:n.vDB,O:n.bIf,kind:s.MethodKind.Unary},setMicrosoftTeamsAuth:{name:"SetMicrosoftTeamsAuth",I:n.ak0,O:n.YrR,kind:s.MethodKind.Unary},getLinearStatus:{name:"GetLinearStatus",I:n.xGO,O:n.zOq,kind:s.MethodKind.Unary},disconnectLinear:{name:"DisconnectLinear",I:n.Xqi,O:n.vXd,kind:s.MethodKind.Unary},getLinearTeams:{name:"GetLinearTeams",I:n.v5z,O:n.HMD,kind:s.MethodKind.Unary},getLinearSettings:{name:"GetLinearSettings",I:n.MFi,O:n.C0g,kind:s.MethodKind.Unary},updateLinearTeamSetting:{name:"UpdateLinearTeamSetting",I:n.$H8,O:n.XMd,kind:s.MethodKind.Unary},updateLinearProjectSetting:{name:"UpdateLinearProjectSetting",I:n.tJW,O:n.RYJ,kind:s.MethodKind.Unary},getLinearLabels:{name:"GetLinearLabels",I:n.a3w,O:n.eZU,kind:s.MethodKind.Unary},getLinearIssues:{name:"GetLinearIssues",I:n.PG$,O:n.bBu,kind:s.MethodKind.Unary},batchGetLinearIssueSummaries:{name:"BatchGetLinearIssueSummaries",I:n.aFD,O:n.W5r,kind:s.MethodKind.Unary},getXaiTeamLinkStatus:{name:"GetXaiTeamLinkStatus",I:n.$TS,O:n.$0p,kind:s.MethodKind.Unary},startXaiTeamLink:{name:"StartXaiTeamLink",I:n.ptw,O:n.zlM,kind:s.MethodKind.Unary},confirmXaiTeamLink:{name:"ConfirmXaiTeamLink",I:n.bWR,O:n.FQR,kind:s.MethodKind.Unary},cancelXaiTeamLinkProposal:{name:"CancelXaiTeamLinkProposal",I:n.pAq,O:n.LOM,kind:s.MethodKind.Unary},unlinkXaiTeam:{name:"UnlinkXaiTeam",I:n.GTA,O:n.ev7,kind:s.MethodKind.Unary},getXaiCursorTeamMergeStatus:{name:"GetXaiCursorTeamMergeStatus",I:$e,O:Me,kind:s.MethodKind.Unary},getXaiCursorTeamMembershipPreview:{name:"GetXaiCursorTeamMembershipPreview",I:De,O:Fe,kind:s.MethodKind.Unary},updateXaiCursorTeamMemberRoles:{name:"UpdateXaiCursorTeamMemberRoles",I:je,O:He,kind:s.MethodKind.Unary},startXaiCursorTeamMerge:{name:"StartXaiCursorTeamMerge",I:We,O:Qe,kind:s.MethodKind.Unary},getXaiCursorTeamMergeGrokTeams:{name:"GetXaiCursorTeamMergeGrokTeams",I:Ve,O:Ye,kind:s.MethodKind.Unary},selectXaiCursorTeamMergeGrokTeam:{name:"SelectXaiCursorTeamMergeGrokTeam",I:Ze,O:tn,kind:s.MethodKind.Unary},confirmXaiCursorTeamMerge:{name:"ConfirmXaiCursorTeamMerge",I:rn,O:on,kind:s.MethodKind.Unary},prepareXaiCursorTeamMergeCheckout:{name:"PrepareXaiCursorTeamMergeCheckout",I:an,O:un,kind:s.MethodKind.Unary},unprepareXaiCursorTeamMergeCheckout:{name:"UnprepareXaiCursorTeamMergeCheckout",I:cn,O:ln,kind:s.MethodKind.Unary},finalizeXaiCursorTeamMergeCheckout:{name:"FinalizeXaiCursorTeamMergeCheckout",I:mn,O:fn,kind:s.MethodKind.Unary},ensureXaiCursorTeamForMerge:{name:"EnsureXaiCursorTeamForMerge",I:dn,O:pn,kind:s.MethodKind.Unary},getXaiCursorTeamMergePrepaidPreview:{name:"GetXaiCursorTeamMergePrepaidPreview",I:hn,O:gn,kind:s.MethodKind.Unary},cancelXaiCursorTeamMergeProposal:{name:"CancelXaiCursorTeamMergeProposal",I:_n,O:Jn,kind:s.MethodKind.Unary},transferXaiCredits:{name:"TransferXaiCredits",I:n.hDl,O:n.hWK,kind:s.MethodKind.Unary},grantXaiSubscription:{name:"GrantXaiSubscription",I:Gp,O:Lp,kind:s.MethodKind.Unary},getXaiCreditTransferStatus:{name:"GetXaiCreditTransferStatus",I:n.yq2,O:n.hWK,kind:s.MethodKind.Unary},listXaiCreditTransfers:{name:"ListXaiCreditTransfers",I:n.R_i,O:n.hN$,kind:s.MethodKind.Unary},getPagerDutyAuthUrl:{name:"GetPagerDutyAuthUrl",I:n.Ig_,O:n.Esv,kind:s.MethodKind.Unary},connectPagerDutyCallback:{name:"ConnectPagerDutyCallback",I:n.ecT,O:n.YdR,kind:s.MethodKind.Unary},getPagerDutyStatus:{name:"GetPagerDutyStatus",I:n.JmO,O:n.bUD,kind:s.MethodKind.Unary},getPagerDutyServices:{name:"GetPagerDutyServices",I:n.bo4,O:n.twU,kind:s.MethodKind.Unary},disconnectPagerDuty:{name:"DisconnectPagerDuty",I:n.dBq,O:n.VS,kind:s.MethodKind.Unary},getJiraInstallUrl:{name:"GetJiraInstallUrl",I:n.m8H,O:n.G4o,kind:s.MethodKind.Unary},linkJiraInstallation:{name:"LinkJiraInstallation",I:n.Uao,O:n.Gdv,kind:s.MethodKind.Unary},getJiraStatus:{name:"GetJiraStatus",I:n.CJ0,O:n.qZs,kind:s.MethodKind.Unary},listJiraInstallations:{name:"ListJiraInstallations",I:n.LuE,O:n.VG3,kind:s.MethodKind.Unary},getBitbucketForgeStatus:{name:"GetBitbucketForgeStatus",I:n.y90,O:n.YmN,kind:s.MethodKind.Unary},disconnectJira:{name:"DisconnectJira",I:n.KQv,O:n.S0I,kind:s.MethodKind.Unary},disconnectBitbucketForge:{name:"DisconnectBitbucketForge",I:n.I5D,O:n.e0h,kind:s.MethodKind.Unary},getBitbucketForgeInstallationGrants:{name:"GetBitbucketForgeInstallationGrants",I:n.DfW,O:n.lpX,kind:s.MethodKind.Unary},grantBitbucketForgeInstallation:{name:"GrantBitbucketForgeInstallation",I:n.UEe,O:n.I67,kind:s.MethodKind.Unary},revokeBitbucketForgeInstallation:{name:"RevokeBitbucketForgeInstallation",I:n.Eh$,O:n.aIo,kind:s.MethodKind.Unary},getJiraProjects:{name:"GetJiraProjects",I:n.k0s,O:n.EGh,kind:s.MethodKind.Unary},getJiraTeamSettings:{name:"GetJiraTeamSettings",I:n.WCk,O:n.CyC,kind:s.MethodKind.Unary},updateJiraTeamSettings:{name:"UpdateJiraTeamSettings",I:n.Fuf,O:n.HCj,kind:s.MethodKind.Unary},getJiraRoutingRules:{name:"GetJiraRoutingRules",I:n.XUt,O:n.ZU4,kind:s.MethodKind.Unary},createJiraRoutingRule:{name:"CreateJiraRoutingRule",I:n.OoP,O:n.gZI,kind:s.MethodKind.Unary},updateJiraRoutingRule:{name:"UpdateJiraRoutingRule",I:n.zFs,O:n.bQQ,kind:s.MethodKind.Unary},deleteJiraRoutingRule:{name:"DeleteJiraRoutingRule",I:n.XeB,O:n.zNr,kind:s.MethodKind.Unary},linkJiraUser:{name:"LinkJiraUser",I:n.DWb,O:n.Fi2,kind:s.MethodKind.Unary},listJiraUserLinks:{name:"ListJiraUserLinks",I:n.KaV,O:n.ySt,kind:s.MethodKind.Unary},unlinkJiraUser:{name:"UnlinkJiraUser",I:n.ceB,O:n.WXO,kind:s.MethodKind.Unary},deleteBedrockIamRole:{name:"DeleteBedrockIamRole",I:n.o0f,O:n.mTO,kind:s.MethodKind.Unary},unlinkSlackAccess:{name:"UnlinkSlackAccess",I:n.h0F,O:n.dTt,kind:s.MethodKind.Unary},listSlackLinkedWorkspaces:{name:"ListSlackLinkedWorkspaces",I:n.N8I,O:n.pZm,kind:s.MethodKind.Unary},setSandAutomationSlackWorkspace:{name:"SetSandAutomationSlackWorkspace",I:Ef,O:Cf,kind:s.MethodKind.Unary},getSlackLinkPreview:{name:"GetSlackLinkPreview",I:n.aew,O:n.gjm,kind:s.MethodKind.Unary},listSlackConversations:{name:"ListSlackConversations",I:n.iHk,O:n.gsv,kind:s.MethodKind.Unary},listSlackConnectedWorkspaces:{name:"ListSlackConnectedWorkspaces",I:n.vV7,O:n.vcR,kind:s.MethodKind.Unary},listOrganizationSlackConnectedWorkspaces:{name:"ListOrganizationSlackConnectedWorkspaces",I:n.quH,O:n.eK8,kind:s.MethodKind.Unary},listMicrosoftTeamsChannels:{name:"ListMicrosoftTeamsChannels",I:n.wLf,O:n.Sot,kind:s.MethodKind.Unary},getSlackConversationsByIds:{name:"GetSlackConversationsByIds",I:n.BaG,O:n.zYR,kind:s.MethodKind.Unary},logSlackbotAuthConversionFunnel:{name:"LogSlackbotAuthConversionFunnel",I:n.HOD,O:n.pQL,kind:s.MethodKind.Unary},logClickedConnectSlack:{name:"LogClickedConnectSlack",I:n.Not,O:n.T0x,kind:s.MethodKind.Unary},checkUserApiKeyAccess:{name:"CheckUserApiKeyAccess",I:n.QKN,O:n.wmq,kind:s.MethodKind.Unary},isAllowedFreeTrialUsage:{name:"IsAllowedFreeTrialUsage",I:n.p$r,O:n.Jag,kind:s.MethodKind.Unary},isNextSetupRunFree:{name:"IsNextSetupRunFree",I:n.vfb,O:n.$8m,kind:s.MethodKind.Unary},completedLinkSlackAccount:{name:"CompletedLinkSlackAccount",I:n.wm7,O:n.O$A,kind:s.MethodKind.Unary},notifyBugbotTeamAdmins:{name:"NotifyBugbotTeamAdmins",I:n.anf,O:n.WJW,kind:s.MethodKind.Unary},getAdminNotificationStatus:{name:"GetAdminNotificationStatus",I:n.gJU,O:n.mib,kind:s.MethodKind.Unary},optOutNewPricing:{name:"OptOutNewPricing",I:n.P4,O:n.HdK,kind:s.MethodKind.Unary},submitFeedback:{name:"SubmitFeedback",I:n.h5c,O:n.b9h,kind:s.MethodKind.Unary},submitFeedbackAnon:{name:"SubmitFeedbackAnon",I:n.h5c,O:n.b9h,kind:s.MethodKind.Unary},submitRepositoryProtectionClaim:{name:"SubmitRepositoryProtectionClaim",I:n.zuj,O:n.NMG,kind:s.MethodKind.Unary},activateRepositoryProtectionInvite:{name:"ActivateRepositoryProtectionInvite",I:n.bo5,O:n.xWW,kind:s.MethodKind.Unary},getActiveOffboardingBanner:{name:"GetActiveOffboardingBanner",I:n.pg$,O:n.fSY,kind:s.MethodKind.Unary},clientAction:{name:"ClientAction",I:n.H5i,O:n.zah,kind:s.MethodKind.Unary},listUsageAlerts:{name:"ListUsageAlerts",I:n.wfW,O:n.UB9,kind:s.MethodKind.Unary},createUsageAlerts:{name:"CreateUsageAlerts",I:n.Q1P,O:n.kJb,kind:s.MethodKind.Unary},deleteUsageAlerts:{name:"DeleteUsageAlerts",I:n.LME,O:n.rJY,kind:s.MethodKind.Unary},updateUsageAlerts:{name:"UpdateUsageAlerts",I:n.D3G,O:n.rew,kind:s.MethodKind.Unary},requestIndividualLimitsOptOut:{name:"RequestIndividualLimitsOptOut",I:n.JrS,O:n.HJo,kind:s.MethodKind.Unary},listMarketplacePlugins:{name:"ListMarketplacePlugins",I:n.ZMX,O:n.vEP,kind:s.MethodKind.Unary},listPublisherPublicPlugins:{name:"ListPublisherPublicPlugins",I:n.nMU,O:n.lqq,kind:s.MethodKind.Unary},getUserProfile:{name:"GetUserProfile",I:n.mH6,O:n.CZF,kind:s.MethodKind.Unary},updateUserProfile:{name:"UpdateUserProfile",I:n.LjR,O:n.Hoz,kind:s.MethodKind.Unary},claimUserProfileHandle:{name:"ClaimUserProfileHandle",I:n.iOH,O:n.g5C,kind:s.MethodKind.Unary},getPublicProfileByHandle:{name:"GetPublicProfileByHandle",I:n.dwF,O:n.t5n,kind:s.MethodKind.Unary},getViewableProfileByHandle:{name:"GetViewableProfileByHandle",I:n.hsE,O:n.vuk,kind:s.MethodKind.Unary},getTeamMemberProfileByHandle:{name:"GetTeamMemberProfileByHandle",I:n.jcw,O:n.X5_,kind:s.MethodKind.Unary},getProfileOriginContributions:{name:"GetProfileOriginContributions",I:n.kSp,O:n.O5b,kind:s.MethodKind.Unary},getPlugin:{name:"GetPlugin",I:n.vVx,O:n.fAb,kind:s.MethodKind.Unary},startPluginMcpConnectorSignIn:{name:"StartPluginMcpConnectorSignIn",I:n.sGA,O:n.MmU,kind:s.MethodKind.Unary},createPlugin:{name:"CreatePlugin",I:n.hzU,O:n.rfl,kind:s.MethodKind.Unary},updatePluginMcpConfig:{name:"UpdatePluginMcpConfig",I:ea,O:na,kind:s.MethodKind.Unary},publishPlugin:{name:"PublishPlugin",I:n.qkO,O:n.YPJ,kind:s.MethodKind.Unary},unpublishPlugin:{name:"UnpublishPlugin",I:n.VJo,O:n.ZuH,kind:s.MethodKind.Unary},parseGitHubRepoForPlugins:{name:"ParseGitHubRepoForPlugins",I:n.ggh,O:n.nXe,kind:s.MethodKind.Unary},parsePluginPublisherRepoInternal:{name:"ParsePluginPublisherRepoInternal",I:n.VWM,O:n.HiH,kind:s.MethodKind.Unary},previewReindexPluginRepoInternal:{name:"PreviewReindexPluginRepoInternal",I:n.dOz,O:n.smL,kind:s.MethodKind.Unary},applyReindexPluginRepoInternal:{name:"ApplyReindexPluginRepoInternal",I:n.flJ,O:n.SZm,kind:s.MethodKind.Unary},previewMigrateReindexPluginRepoInternal:{name:"PreviewMigrateReindexPluginRepoInternal",I:n.Q66,O:n.b48,kind:s.MethodKind.Unary},applyMigrateReindexPluginRepoInternal:{name:"ApplyMigrateReindexPluginRepoInternal",I:n.GJd,O:n.LmS,kind:s.MethodKind.Unary},updateTeamMarketplaceOriginDistributionInternal:{name:"UpdateTeamMarketplaceOriginDistributionInternal",I:n.WFw,O:n.gqu,kind:s.MethodKind.Unary},getXaiEmailEligibilityInternal:{name:"GetXaiEmailEligibilityInternal",I:wn,O:yn,kind:s.MethodKind.Unary},getUserServedPlanInternal:{name:"GetUserServedPlanInternal",I:n.SC5,O:n._kg,kind:s.MethodKind.Unary},lookupGrokAccountsByXUserInternal:{name:"LookupGrokAccountsByXUserInternal",I:Sn,O:Bn,kind:s.MethodKind.Unary},createSupportImpersonationSessionInternal:{name:"CreateSupportImpersonationSessionInternal",I:n.Cbz,O:n.Gf$,kind:s.MethodKind.Unary},revokeSupportImpersonationSessionsInternal:{name:"RevokeSupportImpersonationSessionsInternal",I:n.$qF,O:n.JUz,kind:s.MethodKind.Unary},removeOrganizationMemberInternal:{name:"RemoveOrganizationMemberInternal",I:n.sw6,O:n.qVu,kind:s.MethodKind.Unary},linkOrganizationTeamToXaiInternal:{name:"LinkOrganizationTeamToXaiInternal",I:n.AkD,O:n.w2N,kind:s.MethodKind.Unary},submitPluginForApproval:{name:"SubmitPluginForApproval",I:n.vCC,O:n.D7h,kind:s.MethodKind.Unary},approvePlugin:{name:"ApprovePlugin",I:n.c2n,O:n.ISv,kind:s.MethodKind.Unary},rejectPlugin:{name:"RejectPlugin",I:n.WZo,O:n.oGE,kind:s.MethodKind.Unary},listUserPluginInstalls:{name:"ListUserPluginInstalls",I:n.OHt,O:n.UgB,kind:s.MethodKind.Unary},installUserPlugin:{name:"InstallUserPlugin",I:n.Bi3,O:n.jsr,kind:s.MethodKind.Unary},updateUserPluginInstall:{name:"UpdateUserPluginInstall",I:n.__V,O:n.c3q,kind:s.MethodKind.Unary},uninstallUserPlugin:{name:"UninstallUserPlugin",I:n.w66,O:n.Mmr,kind:s.MethodKind.Unary},getTeamPluginPopularity:{name:"GetTeamPluginPopularity",I:n.LGu,O:n.PnF,kind:s.MethodKind.Unary},recordConnectorPolicyBlocked:{name:"RecordConnectorPolicyBlocked",I:n.QL_,O:n.iMY,kind:s.MethodKind.Unary},getTeamPluginPrimitiveUsage:{name:"GetTeamPluginPrimitiveUsage",I:n.i9d,O:n.sev,kind:s.MethodKind.Unary},listTeamAvailableMarketplacePlugins:{name:"ListTeamAvailableMarketplacePlugins",I:n.$_i,O:n.B0l,kind:s.MethodKind.Unary},getTeamPinnedMarketplacePlugins:{name:"GetTeamPinnedMarketplacePlugins",I:n.ax8,O:n._lt,kind:s.MethodKind.Unary},updateTeamPinnedMarketplacePlugins:{name:"UpdateTeamPinnedMarketplacePlugins",I:n.hLv,O:n.VCH,kind:s.MethodKind.Unary},installTeamPlugin:{name:"InstallTeamPlugin",I:n.Jjf,O:n.hsS,kind:s.MethodKind.Unary},updateTeamPluginInstall:{name:"UpdateTeamPluginInstall",I:n.iRP,O:n.y13,kind:s.MethodKind.Unary},uninstallTeamPlugin:{name:"UninstallTeamPlugin",I:n.m,O:n.E3F,kind:s.MethodKind.Unary},getEffectiveUserPlugins:{name:"GetEffectiveUserPlugins",I:n.EwF,O:n.KhO,kind:s.MethodKind.Unary},downloadPluginContent:{name:"DownloadPluginContent",I:n.m_x,O:n.EPm,kind:s.MethodKind.ServerStreaming},listInstalledPlugins:{name:"ListInstalledPlugins",I:n.AB7,O:n.g7m,kind:s.MethodKind.Unary,idempotency:s.MethodIdempotency.NoSideEffects},getInstalledPluginDetail:{name:"GetInstalledPluginDetail",I:n.E8o,O:n.C17,kind:s.MethodKind.Unary,idempotency:s.MethodIdempotency.NoSideEffects},listTeamPluginsTable:{name:"ListTeamPluginsTable",I:n.IJt,O:n.pNK,kind:s.MethodKind.Unary,idempotency:s.MethodIdempotency.NoSideEffects},listStorefrontPlugins:{name:"ListStorefrontPlugins",I:n.W22,O:n.SwX,kind:s.MethodKind.Unary,idempotency:s.MethodIdempotency.NoSideEffects},resolvePluginsByRef:{name:"ResolvePluginsByRef",I:n.WvV,O:n.UgI,kind:s.MethodKind.Unary},listMarketplaces:{name:"ListMarketplaces",I:n.iPX,O:n.A8F,kind:s.MethodKind.Unary},addMarketplace:{name:"AddMarketplace",I:n.Y9_,O:n.CeW,kind:s.MethodKind.Unary},getOrCreateDefaultTeamMarketplace:{name:"GetOrCreateDefaultTeamMarketplace",I:n.q$3,O:n.mht,kind:s.MethodKind.Unary},updateMarketplace:{name:"UpdateMarketplace",I:n.UJO,O:n.Cel,kind:s.MethodKind.Unary},removeMarketplace:{name:"RemoveMarketplace",I:n.Bqo,O:n.PQd,kind:s.MethodKind.Unary},refreshMarketplace:{name:"RefreshMarketplace",I:n.YDo,O:n.cBR,kind:s.MethodKind.Unary},reindexAndApplyTeamMarketplaceChanges:{name:"ReindexAndApplyTeamMarketplaceChanges",I:n.BRM,O:n.loc,kind:s.MethodKind.Unary},registerMarketplaceAndPlugins:{name:"RegisterMarketplaceAndPlugins",I:n.Dxc,O:n.ZHm,kind:s.MethodKind.Unary},updateTeamMarketplaceConfig:{name:"UpdateTeamMarketplaceConfig",I:n.Vpq,O:n.vfz,kind:s.MethodKind.Unary},setTeamMarketplaceRepository:{name:"SetTeamMarketplaceRepository",I:n.kMn,O:n.YOY,kind:s.MethodKind.Unary},setMarketplaceOriginDistribution:{name:"SetMarketplaceOriginDistribution",I:n.xHb,O:n.fxk,kind:s.MethodKind.Unary},getMarketplaceOriginDistributionStatus:{name:"GetMarketplaceOriginDistributionStatus",I:n.pUz,O:n.hHr,kind:s.MethodKind.Unary},setTeamMarketplacePluginPolicies:{name:"SetTeamMarketplacePluginPolicies",I:n.rJW,O:n.RZJ,kind:s.MethodKind.Unary},completeSharepointOauth:{name:"CompleteSharepointOauth",I:n.vJq,O:n.PaT,kind:s.MethodKind.Unary},getTeamSharepointConnector:{name:"GetTeamSharepointConnector",I:n.FO$,O:n.hFv,kind:s.MethodKind.Unary},disconnectTeamSharepoint:{name:"DisconnectTeamSharepoint",I:n.sg4,O:n.a3K,kind:s.MethodKind.Unary},setTeamSharepointAllowedSites:{name:"SetTeamSharepointAllowedSites",I:n.kau,O:n.YMP,kind:s.MethodKind.Unary},setTeamMarketplacePluginPolicyVariables:{name:"SetTeamMarketplacePluginPolicyVariables",I:n.sst,O:n.Kfp,kind:s.MethodKind.Unary},saveTeamPluginServerSettings:{name:"SaveTeamPluginServerSettings",I:n.v35,O:n.pdK,kind:s.MethodKind.Unary},linkPluginsToTeamMarketplace:{name:"LinkPluginsToTeamMarketplace",I:n.PuH,O:n.n1r,kind:s.MethodKind.Unary},unlinkPluginsFromTeamMarketplace:{name:"UnlinkPluginsFromTeamMarketplace",I:n.nun,O:n.bzo,kind:s.MethodKind.Unary},previewTeamMarketplaceMcpImpact:{name:"PreviewTeamMarketplaceMcpImpact",I:ia,O:la,kind:s.MethodKind.Unary},getManagedSkills:{name:"GetManagedSkills",I:n.X8g,O:n.p_E,kind:s.MethodKind.Unary},getCursorUserState:{name:"GetCursorUserState",I:n.y4P,O:n.WY9,kind:s.MethodKind.Unary},setJobData:{name:"SetJobData",I:n.B$8,O:n.JgL,kind:s.MethodKind.Unary},listFinancialConnections:{name:"ListFinancialConnections",I:n.mbE,O:n.y5v,kind:s.MethodKind.Unary},listFinancialAccounts:{name:"ListFinancialAccounts",I:n.bHh,O:n.jWD,kind:s.MethodKind.Unary},deleteFinancialConnection:{name:"DeleteFinancialConnection",I:n.Yiy,O:n.YY6,kind:s.MethodKind.Unary},startFinancialLink:{name:"StartFinancialLink",I:n.tVV,O:n.zHj,kind:s.MethodKind.Unary},updateBitbucketServerInstanceOauthApp:{name:"UpdateBitbucketServerInstanceOauthApp",I:n.KEO,O:n.qA0,kind:s.MethodKind.Unary},disconnectBitbucketServerAccount:{name:"DisconnectBitbucketServerAccount",I:n.ru_,O:n.dyp,kind:s.MethodKind.Unary},listDashboardApps:{name:"ListDashboardApps",I:n.CCH,O:n.EdW,kind:s.MethodKind.Unary},getDashboardApp:{name:"GetDashboardApp",I:n.hst,O:n.zUO,kind:s.MethodKind.Unary},listAppReviewOverrides:{name:"ListAppReviewOverrides",I:n.upR,O:n.U2t,kind:s.MethodKind.Unary},decideAppReviewOverride:{name:"DecideAppReviewOverride",I:n.ndP,O:n.FRR,kind:s.MethodKind.Unary},revokeAppReviewOverride:{name:"RevokeAppReviewOverride",I:n.HCf,O:n.x6X,kind:s.MethodKind.Unary},grantAppReviewOverride:{name:"GrantAppReviewOverride",I:n.Pt$,O:n.Tmx,kind:s.MethodKind.Unary},listServiceTokenApps:{name:"ListServiceTokenApps",I:n.A_u,O:n.IWi,kind:s.MethodKind.Unary},setServiceTokenApps:{name:"SetServiceTokenApps",I:n.gNG,O:n.QNN,kind:s.MethodKind.Unary},listAppMemberAppsApiKeys:{name:"ListAppMemberAppsApiKeys",I:n.pVr,O:n.jNM,kind:s.MethodKind.Unary},listTeamAppsApiKeys:{name:"ListTeamAppsApiKeys",I:n.l2q,O:n.Lsm,kind:s.MethodKind.Unary},listXaiSessions:{name:"ListXaiSessions",I:n.DJN,O:n.X4T,kind:s.MethodKind.Unary},revokeXaiSession:{name:"RevokeXaiSession",I:n.QAx,O:n._Hq,kind:s.MethodKind.Unary}}}},"../proto/dist/generated/aiserver/v1/docs_pb.js"(t,r,e){e.d(r,{KC:()=>o,ci:()=>a});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");class i extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return"aiserver.v1."}}class o extends i{constructor(t){super(),this.prefixUrl="",this.docName="",this.isDifferentPrefixOrigin=!1,this.truePrefixUrl="",this.public=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new o).fromBinary(t,r)}static fromJson(t,r){return(new o).fromJson(t,r)}static fromJsonString(t,r){return(new o).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(o,t,r)}static $(){return["DocumentationMetadata|1 prefix_url 9|2 doc_name 9|3 is_different_prefix_origin 8|4 true_prefix_url 9|5 public 8|6 team_id 5?"]}}class a extends i{constructor(t){super(),this.docName="",this.pageUrl="",this.documentationChunk="",this.score=0,this.pageTitle="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["DocumentationChunk|1 doc_name 9|2 page_url 9|3 documentation_chunk 9|4 score 2|5 page_title 9"]}}n.proto3},"../proto/dist/generated/aiserver/v1/privacy_mode_pb.js"(t,r,e){e.d(r,{Y:()=>s});var n=e("@bufbuild/protobuf"),s=(0,e("../proto/dist/runtime/compact.js").QT)(n.proto3,"aiserver.v1.","PrivacyMode",[[0,"UNSPECIFIED"],[1,"NO_STORAGE"],[2,"NO_TRAINING"],[3,"USAGE_DATA_TRAINING_ALLOWED"],[4,"USAGE_CODEBASE_TRAINING_ALLOWED"]],1)},"../proto/dist/generated/aiserver/v1/repository_pb.js"(t,r,e){e.d(r,{PT:()=>h,yX:()=>g,bq:()=>p,xq:()=>d,bn:()=>_,se:()=>m,bD:()=>y});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/aiserver/v1/utils_pb.js"),i=e("../proto/dist/runtime/compact.js");class o extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",n.proto3)}static $p(){return"aiserver.v1."}}class a extends o{constructor(t){super(),this.indexId="",this.id="",this.summary="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new a).fromBinary(t,r)}static fromJson(t,r){return(new a).fromJson(t,r)}static fromJsonString(t,r){return(new a).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(a,t,r)}static $(){return["ReflectionData|1 index_id 9|2 id 9|3 summary 9"]}}class u extends o{constructor(t){super(),this.nodeId="",this.stage="",this.content="",this.summary="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["IndexFileData.NodeData|1 node_id 9|2 stage 9|3 content 9|4 summary 9"]}}n.proto3;const c="aiserver.v1.";class l extends i.HL{static get runtime(){return(0,i.kU)(this,"runtime",n.proto3)}static $p(){return c}}n.proto3,n.proto3,n.proto3;var m=(0,i.QT)(n.proto3,c,"RerankerAlgorithm",[[0,"UNSPECIFIED"],[1,"LULEA"],[2,"UMEA"],[3,"NONE"],[4,"LLAMA"],[5,"STARCODER_V1"],[6,"GPT_3_5_LOGPROBS"],[7,"LULEA_HAIKU"],[8,"COHERE"],[9,"VOYAGE"],[10,"VOYAGE_EMBEDS"],[11,"IDENTITY"],[12,"ADA_EMBEDS"]],1),f=(0,i.QT)(n.proto3,c,"DatabaseProvider",[[0,"UNSPECIFIED"],[1,"AURORA"],[2,"PLANETSCALE"]],1),d=(0,i.QT)(n.proto3,c,"RechunkerChoice",[[0,"RECHUNKER_CHOICE_UNSPECIFIED"],[1,"RECHUNKER_CHOICE_IDENTITY"],[2,"RECHUNKER_CHOICE_600_TOKS"],[3,"RECHUNKER_CHOICE_2400_TOKS"],[4,"RECHUNKER_CHOICE_4000_TOKS"]]);n.proto3,n.proto3,n.proto3,n.proto3,n.proto3,n.proto3,n.proto3,n.proto3,n.proto3,n.proto3,n.proto3,n.proto3,n.proto3,n.proto3,n.proto3,n.proto3,n.proto3,n.proto3;class p extends l{constructor(t){super(),this.ownerAuthId="",this.accessToken="",this.userRepoOwner="",this.userRepoName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["QueryOnlyRepoAccess|1 owner_auth_id 9|2 access_token 9|3 user_repo_owner 9|4 user_repo_name 9"]}}class h extends l{constructor(t){super(),this.score=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["CodeResult|1 code_block #0|2 score 2",s.NG]}}class g extends l{constructor(t){super(),this.score=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["FileResult|1 file #0|2 score 2",s.ZH]}}n.proto3,n.proto3,n.proto3;class _ extends l{constructor(t){super(),this.relativeWorkspacePath="",this.remoteUrls=[],this.remoteNames=[],this.repoName="",this.repoOwner="",this.isTracked=!1,this.isLocal=!1,this.workspaceUri="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _).fromBinary(t,r)}static fromJson(t,r){return(new _).fromJson(t,r)}static fromJsonString(t,r){return(new _).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_,t,r)}static $(){return["RepositoryInfo|1 relative_workspace_path 9|2 remote_urls 9*|3 remote_names 9*|4 repo_name 9|5 repo_owner 9|6 is_tracked 8|7 is_local 8|8 num_files 5?|9 orthogonal_transform_seed 1?|10 preferred_embedding_model #0?|11 workspace_uri 9|12 preferred_db_provider #1?",s.Nj,f]}}class J extends l{constructor(t){super(),this.score=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new J).fromBinary(t,r)}static fromJson(t,r){return(new J).fromJson(t,r)}static fromJsonString(t,r){return(new J).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(J,t,r)}static $(){return["NodeResult|1 node #0|2 file #1|3 score 2",u,s.ZH]}}class w extends l{constructor(t){super(),this.score=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new w).fromBinary(t,r)}static fromJson(t,r){return(new w).fromJson(t,r)}static fromJsonString(t,r){return(new w).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(w,t,r)}static $(){return["ReflectionResult|1 reflection #0|2 score 2",a]}}class y extends l{constructor(t){super(),this.topNodes=[],this.reflections=[],this.indexId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new y).fromBinary(t,r)}static fromJson(t,r){return(new y).fromJson(t,r)}static fromJsonString(t,r){return(new y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(y,t,r)}static $(){return["SearchRepositoryDeepContextResponse|1 top_nodes #0*|2 reflections #1*|3 index_id 9",J,w]}}n.proto3,n.proto3,n.proto3,n.proto3,n.proto3,n.proto3,n.proto3},"../proto/dist/generated/aiserver/v1/tools_pb.js"(t,r,e){e.d(r,{$PL:()=>ut,$rP:()=>Wn,AUe:()=>O,Dm_:()=>ur,Faf:()=>D,I8K:()=>cr,KRm:()=>W,MtQ:()=>x,PfC:()=>q,TE4:()=>C,Ue3:()=>T,XaY:()=>y,bR2:()=>N,kWq:()=>Gn,q20:()=>be});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/generated/aiserver/v1/utils_pb.js"),i=e("../proto/dist/generated/agent/v1/background_shell_exec_pb.js"),o=e("../proto/dist/generated/agent/v1/record_screen_exec_pb.js"),a=e("../proto/dist/generated/agent/v1/apply_agent_diff_tool_pb.js"),u=e("../proto/dist/generated/agent/v1/generate_image_tool_pb.js"),c=e("../proto/dist/generated/agent/v1/ai_attribution_tool_pb.js"),l=e("../proto/dist/generated/aiserver/v1/repository_pb.js"),m=e("../proto/dist/generated/agent/v1/sandbox_pb.js"),f=e("../proto/dist/generated/agent/v1/shell_exec_pb.js"),d=e("../proto/dist/generated/agent/v1/subagents_pb.js"),p=e("../proto/dist/generated/agent/v1/ls_exec_pb.js"),h=e("../proto/dist/generated/agent/v1/computer_use_tool_pb.js"),g=e("../proto/dist/generated/agent/v1/report_bugfix_results_tool_pb.js"),_=e("../proto/dist/runtime/compact.js");const J="aiserver.v1.";class w extends _.HL{static get runtime(){return(0,_.kU)(this,"runtime",n.proto3)}static $p(){return J}}var y=(0,_.QT)(n.proto3,J,"ClientSideToolV2",[[0,"UNSPECIFIED"],[1,"READ_SEMSEARCH_FILES"],[3,"RIPGREP_SEARCH"],[5,"READ_FILE"],[6,"LIST_DIR"],[7,"EDIT_FILE"],[8,"FILE_SEARCH"],[9,"SEMANTIC_SEARCH_FULL"],[11,"DELETE_FILE"],[12,"REAPPLY"],[15,"RUN_TERMINAL_COMMAND_V2"],[16,"FETCH_RULES"],[18,"WEB_SEARCH"],[19,"MCP"],[23,"SEARCH_SYMBOLS"],[24,"BACKGROUND_COMPOSER_FOLLOWUP"],[25,"KNOWLEDGE_BASE"],[26,"FETCH_PULL_REQUEST"],[27,"DEEP_SEARCH"],[28,"CREATE_DIAGRAM"],[29,"FIX_LINTS"],[30,"READ_LINTS"],[31,"GO_TO_DEFINITION"],[32,"TASK"],[33,"AWAIT_TASK"],[34,"TODO_READ"],[35,"TODO_WRITE"],[38,"EDIT_FILE_V2"],[39,"LIST_DIR_V2"],[40,"READ_FILE_V2"],[41,"RIPGREP_RAW_SEARCH"],[42,"GLOB_FILE_SEARCH"],[43,"CREATE_PLAN"],[44,"LIST_MCP_RESOURCES"],[45,"READ_MCP_RESOURCE"],[46,"READ_PROJECT"],[47,"UPDATE_PROJECT"],[48,"TASK_V2"],[49,"CALL_MCP_TOOL"],[50,"APPLY_AGENT_DIFF"],[51,"ASK_QUESTION"],[52,"SWITCH_MODE"],[53,"GENERATE_IMAGE"],[54,"COMPUTER_USE"],[55,"WRITE_SHELL_STDIN"],[56,"RECORD_SCREEN"],[57,"WEB_FETCH"],[58,"REPORT_BUGFIX_RESULTS"],[59,"AI_ATTRIBUTION"],[60,"MCP_AUTH"],[61,"REFLECT"],[62,"AWAIT"],[63,"GET_MCP_TOOLS"],[65,"SEND_TO_USER"],[66,"CONNECT_SCM"]],1),S=(0,_.QT)(n.proto3,J,"BuiltinTool",[[0,"UNSPECIFIED"],[1,"SEARCH"],[2,"READ_CHUNK"],[3,"GOTODEF"],[4,"EDIT"],[5,"UNDO_EDIT"],[6,"END"],[7,"NEW_FILE"],[8,"ADD_TEST"],[9,"RUN_TEST"],[10,"DELETE_TEST"],[11,"SAVE_FILE"],[12,"GET_TESTS"],[13,"GET_SYMBOLS"],[14,"SEMANTIC_SEARCH"],[15,"GET_PROJECT_STRUCTURE"],[16,"CREATE_RM_FILES"],[17,"RUN_TERMINAL_COMMANDS"],[18,"NEW_EDIT"],[19,"READ_WITH_LINTER"]],1),q=(0,_.QT)(n.proto3,J,"RunTerminalCommandEndedReason",[[0,"UNSPECIFIED"],[1,"EXECUTION_COMPLETED"],[2,"EXECUTION_ABORTED"],[3,"EXECUTION_FAILED"],[4,"ERROR_OCCURRED_CHECKING_REASON"],[5,"IDLE_TIMEOUT"]],1);class B extends w{constructor(t){super(),this.relativeWorkspacePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new B).fromBinary(t,r)}static fromJson(t,r){return(new B).fromJson(t,r)}static fromJsonString(t,r){return(new B).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(B,t,r)}static $(){return["ReapplyParams|1 relative_workspace_path 9"]}}class I extends w{constructor(t){super(),this.agentId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new I).fromBinary(t,r)}static fromJson(t,r){return(new I).fromJson(t,r)}static fromJsonString(t,r){return(new I).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(I,t,r)}static $(){return["ApplyAgentDiffParams|1 agent_id 9"]}}class P extends w{constructor(t){super(),this.isApplied=!1,this.applyFailed=!1,this.linterErrors=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new P).fromBinary(t,r)}static fromJson(t,r){return(new P).fromJson(t,r)}static fromJsonString(t,r){return(new P).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(P,t,r)}static $(){return["ReapplyResult|1 diff #0|2 is_applied 8|3 apply_failed 8|4 linter_errors #1*|5 rejected 8?",W,s.bO]}}class b extends w{constructor(t){super(),this.ruleNames=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new b).fromBinary(t,r)}static fromJson(t,r){return(new b).fromJson(t,r)}static fromJsonString(t,r){return(new b).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(b,t,r)}static $(){return["FetchRulesParams|1 rule_names 9*"]}}class R extends w{constructor(t){super(),this.rules=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new R).fromBinary(t,r)}static fromJson(t,r){return(new R).fromJson(t,r)}static fromJsonString(t,r){return(new R).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(R,t,r)}static $(){return["FetchRulesResult|1 rules #0*",s.DX]}}class v extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new v).fromBinary(t,r)}static fromJson(t,r){return(new v).fromJson(t,r)}static fromJsonString(t,r){return(new v).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(v,t,r)}static $(){return["ReapplyStream"]}}class x extends w{constructor(t){super(),this.clientVisibleErrorMessage="",this.modelVisibleErrorMessage="",this.errorDetails={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new x).fromBinary(t,r)}static fromJson(t,r){return(new x).fromJson(t,r)}static fromJsonString(t,r){return(new x).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(x,t,r)}static $(){return["ToolResultError|1 client_visible_error_message 9|2 model_visible_error_message 9|3 actual_error_message_only_send_from_client_to_server_never_the_other_way_around_because_that_may_be_a_security_risk 9?|5 edit_file_error_details #0 error_details|6 search_replace_error_details #1 error_details",k,E]}}class k extends w{constructor(t){super(),this.numLinesInFileBeforeEdit=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new k).fromBinary(t,r)}static fromJson(t,r){return(new k).fromJson(t,r)}static fromJsonString(t,r){return(new k).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(k,t,r)}static $(){return["ToolResultError.EditFileError|1 num_lines_in_file_before_edit 5"]}}class E extends w{constructor(t){super(),this.numLinesInFileBeforeEdit=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new E).fromBinary(t,r)}static fromJson(t,r){return(new E).fromJson(t,r)}static fromJsonString(t,r){return(new E).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(E,t,r)}static $(){return["ToolResultError.SearchReplaceError|1 num_lines_in_file_before_edit 5"]}}class C extends w{constructor(t){super(),this.tool=y.UNSPECIFIED,this.params={case:void 0},this.toolCallId="",this.name="",this.isStreaming=!1,this.isLastMessage=!1,this.internal=!1,this.rawArgs="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new C).fromBinary(t,r)}static fromJson(t,r){return(new C).fromJson(t,r)}static fromJsonString(t,r){return(new C).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(C,t,r)}static $(){return["ClientSideToolV2Call|1 tool #0|2 read_semsearch_files_params #1 params|5 ripgrep_search_params #2 params|8 read_file_params #3 params|12 list_dir_params #4 params|13 edit_file_params #5 params|16 file_search_params #6 params|17 semantic_search_full_params #7 params|19 delete_file_params #8 params|20 reapply_params #9 params|23 run_terminal_command_v2_params #10 params|24 fetch_rules_params #11 params|26 web_search_params #12 params|27 mcp_params #13 params|31 search_symbols_params #14 params|41 gotodef_params #15 params|32 background_composer_followup_params #16 params|33 knowledge_base_params #17 params|34 fetch_pull_request_params #18 params|35 deep_search_params #19 params|36 create_diagram_params #20 params|37 fix_lints_params #21 params|38 read_lints_params #22 params|42 task_params #23 params|43 await_task_params #24 params|44 todo_read_params #25 params|45 todo_write_params #26 params|50 edit_file_v2_params #27 params|52 list_dir_v2_params #28 params|53 read_file_v2_params #29 params|54 ripgrep_raw_search_params #30 params|55 glob_file_search_params #31 params|56 create_plan_params #32 params|57 list_mcp_resources_params #33 params|58 read_mcp_resource_params #34 params|59 read_project_params #35 params|60 update_project_params #36 params|61 task_v2_params #37 params|62 call_mcp_tool_params #38 params|63 apply_agent_diff_params #39 params|64 ask_question_params #40 params|65 switch_mode_params #41 params|66 computer_use_params #42 params|67 write_shell_stdin_params #43 params|68 record_screen_params #44 params|69 web_fetch_params #45 params|70 report_bugfix_results_params #46 params|71 mcp_auth_params #47 params|72 get_mcp_tools_params #48 params|73 connect_scm_params #49 params|3 tool_call_id 9|6 timeout_ms 1?|9 name 9|14 is_streaming 8|15 is_last_message 8|51 internal 8|10 raw_args 9|48 tool_index 13?|49 model_call_id 9?",y,Ft,pt,mt,at,j,nt,Vt,Zt,B,he,b,Se,Pe,De,Or,Fe,je,Qe,tn,nn,an,mn,hn,$n,Nn,Kn,G,Hn,Yn,Bn,rs,ms,ke,Te,_s,Ss,yn,Ae,I,Is,ks,Ts,i.LL,o.zH,Ms,Ns,Fs,Me,js]}}class T extends w{constructor(t){super(),this.tool=y.UNSPECIFIED,this.result={case:void 0},this.toolCallId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new T).fromBinary(t,r)}static fromJson(t,r){return(new T).fromJson(t,r)}static fromJsonString(t,r){return(new T).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(T,t,r)}static $(){return["ClientSideToolV2Result|1 tool #0|2 read_semsearch_files_result #1 result|4 ripgrep_search_result #2 result|6 read_file_result #3 result|9 list_dir_result #4 result|10 edit_file_result #5 result|11 file_search_result #6 result|18 semantic_search_full_result #7 result|20 delete_file_result #8 result|21 reapply_result #9 result|24 run_terminal_command_v2_result #10 result|25 fetch_rules_result #11 result|27 web_search_result #12 result|28 mcp_result #13 result|32 search_symbols_result #14 result|33 background_composer_followup_result #15 result|34 knowledge_base_result #16 result|36 fetch_pull_request_result #17 result|37 deep_search_result #18 result|38 create_diagram_result #19 result|39 fix_lints_result #20 result|40 read_lints_result #21 result|41 gotodef_result #22 result|42 task_result #23 result|43 await_task_result #24 result|44 todo_read_result #25 result|45 todo_write_result #26 result|51 edit_file_v2_result #27 result|52 list_dir_v2_result #28 result|53 read_file_v2_result #29 result|54 ripgrep_raw_search_result #30 result|55 glob_file_search_result #31 result|56 create_plan_result #32 result|57 list_mcp_resources_result #33 result|58 read_mcp_resource_result #34 result|59 read_project_result #35 result|60 update_project_result #36 result|61 task_v2_result #37 result|62 call_mcp_tool_result #38 result|63 apply_agent_diff_result #39 result|64 ask_question_result #40 result|65 switch_mode_result #41 result|66 computer_use_result #42 result|67 generate_image_result #43 result|68 write_shell_stdin_result #44 result|69 record_screen_result #45 result|70 web_fetch_result #46 result|71 report_bugfix_results_result #47 result|72 ai_attribution_result #48 result|73 mcp_auth_result #49 result|74 get_mcp_tools_result #50 result|75 connect_scm_result #51 result|35 tool_call_id 9|8 error #52?|48 model_call_id 9?|49 tool_index 13?|50 attachments #53?",y,Wt,It,ft,ut,H,it,Xt,tr,P,Je,R,qe,ve,Ne,Ke,He,Ve,rn,sn,un,fn,Nr,gn,Mn,Ln,zn,K,Wn,Zn,In,es,fs,Ee,Ue,Js,qs,Sn,$e,a.y$,Rs,Es,Us,u.k4,i.nt,o.Tj,Os,Gs,c.Zc,Ks,Oe,Qs,x,A]}}class U extends w{constructor(t){super(),this.rawMessage="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new U).fromBinary(t,r)}static fromJson(t,r){return(new U).fromJson(t,r)}static fromJsonString(t,r){return(new U).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(U,t,r)}static $(){return["NudgeMessage|1 raw_message 9"]}}class A extends w{constructor(t){super(),this.originalTodos=[],this.updatedTodos=[],this.nudgeMessages=[],this.shouldShowTodoWriteReminder=!1,this.todoReminderType=$.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new A).fromBinary(t,r)}static fromJson(t,r){return(new A).fromJson(t,r)}static fromJsonString(t,r){return(new A).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(A,t,r)}static $(){return["ToolResultAttachments|1 original_todos #0*|2 updated_todos #0*|3 nudge_messages #1*|4 should_show_todo_write_reminder 8|5 todo_reminder_type #2|6 discovery_budget_reminder #3?",Gn,U,$,M]}}var $=(0,_.QT)(n.proto3,J,"ToolResultAttachments.TodoReminderType",[[0,"UNSPECIFIED"],[1,"EVERY_10_TURNS"],[2,"AFTER_EDIT"]],1);class M extends w{constructor(t){super(),this.discoveryRoundsRemaining=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new M).fromBinary(t,r)}static fromJson(t,r){return(new M).fromJson(t,r)}static fromJsonString(t,r){return(new M).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(M,t,r)}static $(){return["ToolResultAttachments.DiscoveryBudgetReminder|1 discovery_rounds_remaining 5|2 discovery_effort 9?"]}}class O extends w{constructor(t){super(),this.tool=y.UNSPECIFIED,this.toolCallId="",this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new O).fromBinary(t,r)}static fromJson(t,r){return(new O).fromJson(t,r)}static fromJsonString(t,r){return(new O).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(O,t,r)}static $(){return["StreamedBackPartialToolCall|1 tool #0|2 tool_call_id 9|3 name 9|4 tool_index 13?|5 model_call_id 9?",y]}}class D extends w{constructor(t){super(),this.tool=y.UNSPECIFIED,this.toolCallId="",this.params={case:void 0},this.name="",this.rawArgs="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new D).fromBinary(t,r)}static fromJson(t,r){return(new D).fromJson(t,r)}static fromJsonString(t,r){return(new D).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(D,t,r)}static $(){return["StreamedBackToolCall|1 tool #0|2 tool_call_id 9|3 read_semsearch_files_stream #1 params|5 ripgrep_search_stream #2 params|7 read_file_stream #3 params|12 list_dir_stream #4 params|13 edit_file_stream #5 params|14 file_search_stream #6 params|19 semantic_search_full_stream #7 params|21 delete_file_stream #8 params|22 reapply_stream #9 params|25 run_terminal_command_v2_stream #10 params|26 fetch_rules_stream #11 params|28 web_search_stream #12 params|29 mcp_stream #13 params|33 search_symbols_stream #14 params|41 gotodef_stream #15 params|34 background_composer_followup_stream #16 params|35 knowledge_base_stream #17 params|36 fetch_pull_request_stream #18 params|37 deep_search_stream #19 params|38 create_diagram_stream #20 params|39 fix_lints_stream #21 params|40 read_lints_stream #22 params|42 task_stream #23 params|43 await_task_stream #24 params|44 todo_read_stream #25 params|45 todo_write_stream #26 params|52 edit_file_v2_stream #27 params|53 list_dir_v2_stream #28 params|54 read_file_v2_stream #29 params|55 ripgrep_raw_search_stream #30 params|56 glob_file_search_stream #31 params|57 create_plan_stream #32 params|58 list_mcp_resources_stream #33 params|59 read_mcp_resource_stream #34 params|60 read_project_stream #35 params|61 update_project_stream #36 params|62 task_v2_stream #37 params|63 call_mcp_tool_stream #38 params|64 ask_question_stream #39 params|65 switch_mode_stream #40 params|66 computer_use_stream #41 params|67 write_shell_stdin_stream #42 params|68 web_fetch_stream #43 params|69 report_bugfix_results_stream #44 params|70 mcp_auth_stream #45 params|71 connect_scm_stream #46 params|8 name 9|9 raw_args 9|10 error #47?|50 tool_index 13?|51 model_call_id 9?",y,Qt,Lt,dt,lt,et,st,Yt,rr,v,we,ye,Ie,xe,Le,pn,ze,We,Ye,en,on,ln,dn,wn,Dn,Fn,jn,z,Xn,ts,An,is,gs,os,us,ws,Bs,qn,as,xs,Cs,As,$s,Ds,Ls,zs,Vs,x]}}class N extends w{constructor(t){super(),this.tool=y.UNSPECIFIED,this.toolCallId="",this.params={case:void 0},this.name="",this.rawArgs="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new N).fromBinary(t,r)}static fromJson(t,r){return(new N).fromJson(t,r)}static fromJsonString(t,r){return(new N).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(N,t,r)}static $(){return["StreamedBackToolCallV2|1 tool #0|2 tool_call_id 9|3 read_semsearch_files_params #1 params|5 ripgrep_search_params #2 params|9 read_file_params #3 params|12 list_dir_params #4 params|13 edit_file_params #5 params|16 file_search_params #6 params|17 semantic_search_full_params #7 params|19 delete_file_params #8 params|20 reapply_params #9 params|23 run_terminal_command_v2_params #10 params|24 fetch_rules_params #11 params|26 web_search_params #12 params|27 mcp_params #13 params|31 search_symbols_params #14 params|41 gotodef_params #15 params|32 background_composer_followup_params #16 params|33 knowledge_base_params #17 params|34 fetch_pull_request_params #18 params|35 deep_search_params #19 params|36 create_diagram_params #20 params|37 fix_lints_params #21 params|38 read_lints_params #22 params|42 task_params #23 params|43 await_task_params #24 params|44 todo_read_params #25 params|45 todo_write_params #26 params|48 edit_file_v2_params #27 params|49 list_dir_v2_params #28 params|61 read_file_v2_params #29 params|62 ripgrep_raw_search_params #30 params|63 glob_file_search_params #31 params|64 create_plan_params #32 params|65 list_mcp_resources_params #33 params|66 read_mcp_resource_params #34 params|67 read_project_params #35 params|68 update_project_params #36 params|69 task_v2_params #37 params|70 call_mcp_tool_params #38 params|71 apply_agent_diff_params #39 params|72 ask_question_params #40 params|73 switch_mode_params #41 params|74 computer_use_params #42 params|75 write_shell_stdin_params #43 params|76 record_screen_params #44 params|77 web_fetch_params #45 params|78 report_bugfix_results_params #46 params|79 mcp_auth_params #47 params|80 get_mcp_tools_params #48 params|81 connect_scm_params #49 params|8 name 9|10 raw_args 9|11 error #50?|50 tool_index 13?|51 model_call_id 9?",y,Ft,pt,mt,at,j,nt,Vt,Zt,B,he,b,Se,Pe,De,Or,Fe,je,Qe,tn,nn,an,mn,hn,$n,Nn,Kn,G,Hn,Yn,Bn,rs,ms,ke,Te,_s,Ss,yn,Ae,I,Is,ks,Ts,i.LL,o.zH,Ms,Ns,Fs,Me,js,x]}}class G extends w{constructor(t){super(),this.relativeWorkspacePath="",this.streamingEdit={case:void 0},this.shouldSendBackLinterErrors=!1,this.resultForModel="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new G).fromBinary(t,r)}static fromJson(t,r){return(new G).fromJson(t,r)}static fromJsonString(t,r){return(new G).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(G,t,r)}static $(){return["EditFileV2Params|1 relative_workspace_path 9|2 contents_after_edit 9?|3 waiting_for_file_contents 8?|4 text #0 streaming_edit|5 code #1 streaming_edit|6 should_send_back_linter_errors 8|7 diff #2?|8 result_for_model 9|9 streaming_content 9?|10 no_codeblock 8?|11 cloud_agent_edit 8?",L,F,W]}}class L extends w{constructor(t){super(),this.text="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new L).fromBinary(t,r)}static fromJson(t,r){return(new L).fromJson(t,r)}static fromJsonString(t,r){return(new L).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(L,t,r)}static $(){return["EditFileV2Params.StreamingEditText|1 text 9"]}}class F extends w{constructor(t){super(),this.code="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new F).fromBinary(t,r)}static fromJson(t,r){return(new F).fromJson(t,r)}static fromJsonString(t,r){return(new F).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(F,t,r)}static $(){return["EditFileV2Params.StreamingEditCode|1 code 9"]}}class K extends w{constructor(t){super(),this.fileWasCreated=!1,this.linterErrors=[],this.sentBackLinterErrors=!1,this.shouldAutoFixLints=!1,this.resultForModel="",this.afterContentId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new K).fromBinary(t,r)}static fromJson(t,r){return(new K).fromJson(t,r)}static fromJsonString(t,r){return(new K).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(K,t,r)}static $(){return["EditFileV2Result|1 contents_before_edit 9?|9 eol_sequence 9?|11 detected_language 9?|2 file_was_created 8|3 diff #0?|4 rejected 8?|5 linter_errors #1*|6 sent_back_linter_errors 8|8 should_auto_fix_lints 8|7 human_review_v2 #2?|10 result_for_model 9|12 contents_after_edit 9?|13 before_content_id 9?|14 after_content_id 9",W,s.bO,rt]}}class z extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new z).fromBinary(t,r)}static fromJson(t,r){return(new z).fromJson(t,r)}static fromJsonString(t,r){return(new z).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(z,t,r)}static $(){return["EditFileV2Stream"]}}class j extends w{constructor(t){super(),this.relativeWorkspacePath="",this.language="",this.blocking=!1,this.contents="",this.lineRanges=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new j).fromBinary(t,r)}static fromJson(t,r){return(new j).fromJson(t,r)}static fromJsonString(t,r){return(new j).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(j,t,r)}static $(){return["EditFileParams|1 relative_workspace_path 9|2 language 9|4 blocking 8|3 contents 9|5 instructions 9?|12 should_edit_file_fail_for_large_files 8?|6 old_string 9?|7 new_string 9?|8 allow_multiple_matches 8?|10 use_whitespace_insensitive_fallback 8?|11 use_did_you_mean_fuzzy_match 8?|16 gracefully_handle_recoverable_errors 8?|9 line_ranges #0*|13 notebook_cell_idx 5?|14 is_new_cell 8?|15 cell_language 9?|17 edit_category 9?|18 should_eagerly_process_lints 8?",s.MT]}}class H extends w{constructor(t){super(),this.isApplied=!1,this.applyFailed=!1,this.linterErrors=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new H).fromBinary(t,r)}static fromJson(t,r){return(new H).fromJson(t,r)}static fromJsonString(t,r){return(new H).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(H,t,r)}static $(){return["EditFileResult|1 diff #0|2 is_applied 8|3 apply_failed 8|4 linter_errors #1*|5 rejected 8?|6 num_matches 5?|7 whitespace_insensitive_fallback_found_match 8?|8 no_match_found_in_line_ranges 8?|11 recoverable_error #2?|9 num_lines_in_file 5?|10 is_subagent_edit 8?|12 diff_became_no_op_due_to_on_save_fixes 8?|13 human_review #3?|14 human_feedback #4?|15 should_eagerly_process_lints 8?|16 human_review_v2 #5?|17 were_all_new_linter_errors_resolved_by_this_edit 8?",W,s.bO,X,Z,tt,rt]}}class W extends w{constructor(t){super(),this.chunks=[],this.editor=Q.UNSPECIFIED,this.hitTimeout=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new W).fromBinary(t,r)}static fromJson(t,r){return(new W).fromJson(t,r)}static fromJsonString(t,r){return(new W).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(W,t,r)}static $(){return["EditFileResult.FileDiff|1 chunks #0*|2 editor #1|3 hit_timeout 8",V,Q]}}var Q=(0,_.QT)(n.proto3,J,"EditFileResult.FileDiff.Editor",[[0,"UNSPECIFIED"],[1,"AI"],[2,"HUMAN"]],1);class V extends w{constructor(t){super(),this.diffString="",this.oldStart=0,this.newStart=0,this.oldLines=0,this.newLines=0,this.linesRemoved=0,this.linesAdded=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new V).fromBinary(t,r)}static fromJson(t,r){return(new V).fromJson(t,r)}static fromJsonString(t,r){return(new V).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(V,t,r)}static $(){return["EditFileResult.FileDiff.ChunkDiff|1 diff_string 9|2 old_start 5|3 new_start 5|4 old_lines 5|5 new_lines 5|6 lines_removed 5|7 lines_added 5"]}}class X extends w{constructor(t){super(),this.errorType=Y.UNSPECIFIED,this.modelMessage="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new X).fromBinary(t,r)}static fromJson(t,r){return(new X).fromJson(t,r)}static fromJsonString(t,r){return(new X).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(X,t,r)}static $(){return["EditFileResult.RecoverableError|1 error_type #0|2 model_message 9",Y]}}var Y=(0,_.QT)(n.proto3,J,"EditFileResult.RecoverableError.RecoverableErrorType",[[0,"UNSPECIFIED"],[1,"SEARCH_STRING_NOT_FOUND"],[2,"AMBIGUOUS_SEARCH_STRING"]],1);class Z extends w{constructor(t){super(),this.isEditAccepted=!1,this.textResult="",this.stopAndGetNewUserInput=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Z).fromBinary(t,r)}static fromJson(t,r){return(new Z).fromJson(t,r)}static fromJsonString(t,r){return(new Z).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Z,t,r)}static $(){return["EditFileResult.EditFileHumanReview|1 is_edit_accepted 8|2 text_result 9|3 stop_and_get_new_user_input 8"]}}class tt extends w{constructor(t){super(),this.selectedOption="",this.feedbackText="",this.submitFeedbackAsNewMessage=!1,this.bubbleId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tt).fromBinary(t,r)}static fromJson(t,r){return(new tt).fromJson(t,r)}static fromJsonString(t,r){return(new tt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tt,t,r)}static $(){return["EditFileResult.HumanFeedback|1 selected_option 9|2 feedback_text 9|3 submit_feedback_as_new_message 8|4 bubble_id 9"]}}class rt extends w{constructor(t){super(),this.selectedOption="",this.feedbackText="",this.submitFeedbackAsNewMessage=!1,this.bubbleId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rt).fromBinary(t,r)}static fromJson(t,r){return(new rt).fromJson(t,r)}static fromJsonString(t,r){return(new rt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rt,t,r)}static $(){return["HumanReview|1 selected_option 9|2 feedback_text 9|3 submit_feedback_as_new_message 8|4 bubble_id 9"]}}class et extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new et).fromBinary(t,r)}static fromJson(t,r){return(new et).fromJson(t,r)}static fromJsonString(t,r){return(new et).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(et,t,r)}static $(){return["EditFileStream"]}}class nt extends w{constructor(t){super(),this.query="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nt).fromBinary(t,r)}static fromJson(t,r){return(new nt).fromJson(t,r)}static fromJsonString(t,r){return(new nt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nt,t,r)}static $(){return["ToolCallFileSearchParams|1 query 9"]}}class st extends w{constructor(t){super(),this.query="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new st).fromBinary(t,r)}static fromJson(t,r){return(new st).fromJson(t,r)}static fromJsonString(t,r){return(new st).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(st,t,r)}static $(){return["ToolCallFileSearchStream|1 query 9"]}}class it extends w{constructor(t){super(),this.files=[],this.numResults=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new it).fromBinary(t,r)}static fromJson(t,r){return(new it).fromJson(t,r)}static fromJsonString(t,r){return(new it).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(it,t,r)}static $(){return["ToolCallFileSearchResult|1 files #0*|2 limit_hit 8?|3 num_results 5",ot]}}class ot extends w{constructor(t){super(),this.uri="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ot).fromBinary(t,r)}static fromJson(t,r){return(new ot).fromJson(t,r)}static fromJsonString(t,r){return(new ot).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ot,t,r)}static $(){return["ToolCallFileSearchResult.File|1 uri 9"]}}class at extends w{constructor(t){super(),this.directoryPath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new at).fromBinary(t,r)}static fromJson(t,r){return(new at).fromJson(t,r)}static fromJsonString(t,r){return(new at).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(at,t,r)}static $(){return["ListDirParams|1 directory_path 9"]}}class ut extends w{constructor(t){super(),this.files=[],this.directoryRelativeWorkspacePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ut).fromBinary(t,r)}static fromJson(t,r){return(new ut).fromJson(t,r)}static fromJsonString(t,r){return(new ut).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ut,t,r)}static $(){return["ListDirResult|1 files #0*|2 directory_relative_workspace_path 9",ct]}}class ct extends w{constructor(t){super(),this.name="",this.isDirectory=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ct).fromBinary(t,r)}static fromJson(t,r){return(new ct).fromJson(t,r)}static fromJsonString(t,r){return(new ct).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ct,t,r)}static $(){return["ListDirResult.File|1 name 9|2 is_directory 8|3 size 3?|4 last_modified #0?|5 num_children 5?|6 num_lines 5?",n.Timestamp]}}class lt extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lt).fromBinary(t,r)}static fromJson(t,r){return(new lt).fromJson(t,r)}static fromJsonString(t,r){return(new lt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lt,t,r)}static $(){return["ListDirStream"]}}class mt extends w{constructor(t){super(),this.relativeWorkspacePath="",this.readEntireFile=!1,this.fileIsAllowedToBeReadEntirely=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mt).fromBinary(t,r)}static fromJson(t,r){return(new mt).fromJson(t,r)}static fromJsonString(t,r){return(new mt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mt,t,r)}static $(){return["ReadFileParams|1 relative_workspace_path 9|2 read_entire_file 8|3 start_line_one_indexed 5?|4 end_line_one_indexed_inclusive 5?|5 file_is_allowed_to_be_read_entirely 8|6 max_lines 5?|7 max_chars 5?|8 min_lines 5?"]}}class ft extends w{constructor(t){super(),this.contents="",this.didDowngradeToLineRange=!1,this.didShortenLineRange=!1,this.didSetDefaultLineRange=!1,this.relativeWorkspacePath="",this.didShortenCharRange=!1,this.matchingCursorRules=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ft).fromBinary(t,r)}static fromJson(t,r){return(new ft).fromJson(t,r)}static fromJsonString(t,r){return(new ft).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ft,t,r)}static $(){return["ReadFileResult|1 contents 9|2 did_downgrade_to_line_range 8|3 did_shorten_line_range 8|4 did_set_default_line_range 8|5 full_file_contents 9?|6 outline 9?|7 start_line_one_indexed 5?|8 end_line_one_indexed_inclusive 5?|9 relative_workspace_path 9|10 did_shorten_char_range 8|11 read_full_file 8?|12 total_lines 5?|13 matching_cursor_rules #0*|14 file_git_context #1",s.DX,s.fL]}}class dt extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dt).fromBinary(t,r)}static fromJson(t,r){return(new dt).fromJson(t,r)}static fromJsonString(t,r){return(new dt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dt,t,r)}static $(){return["ReadFileStream"]}}class pt extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pt).fromBinary(t,r)}static fromJson(t,r){return(new pt).fromJson(t,r)}static fromJsonString(t,r){return(new pt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pt,t,r)}static $(){return["RipgrepSearchParams|1 options #0|2 pattern_info #1",_t,ht]}}class ht extends w{constructor(t){super(),this.pattern="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ht).fromBinary(t,r)}static fromJson(t,r){return(new ht).fromJson(t,r)}static fromJsonString(t,r){return(new ht).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ht,t,r)}static $(){return["RipgrepSearchParams.IPatternInfoProto|1 pattern 9|2 is_reg_exp 8?|3 is_word_match 8?|4 word_separators 9?|5 is_multiline 8?|6 is_unicode 8?|7 is_case_sensitive 8?|8 notebook_info #0|9 pattern_was_escaped 8?",gt]}}class gt extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gt).fromBinary(t,r)}static fromJson(t,r){return(new gt).fromJson(t,r)}static fromJsonString(t,r){return(new gt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gt,t,r)}static $(){return["RipgrepSearchParams.IPatternInfoProto.INotebookPatternInfoProto|1 is_in_notebook_markdown_input 8?|2 is_in_notebook_markdown_preview 8?|3 is_in_notebook_cell_input 8?|4 is_in_notebook_cell_output 8?"]}}class _t extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _t).fromBinary(t,r)}static fromJson(t,r){return(new _t).fromJson(t,r)}static fromJsonString(t,r){return(new _t).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_t,t,r)}static $(){return["RipgrepSearchParams.ITextQueryBuilderOptionsProto|1 preview_options #0|2 file_encoding 9?|3 surrounding_context 5?|4 is_smart_case 8?|5 notebook_search_config #1|6 exclude_pattern #2|7 include_pattern #3|8 expand_patterns 8?|9 max_results 5?|10 max_file_size 5?|11 disregard_ignore_files 8?|12 disregard_global_ignore_files 8?|13 disregard_parent_ignore_files 8?|14 disregard_exclude_settings 8?|15 disregard_search_exclude_settings 8?|16 ignore_symlinks 8?|17 only_open_editors 8?|18 only_file_scheme 8?|19 reason 9?|20 extra_file_resources #4",qt,Bt,wt,St,Jt]}}class Jt extends w{constructor(t){super(),this.extraFileResources=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jt).fromBinary(t,r)}static fromJson(t,r){return(new Jt).fromJson(t,r)}static fromJsonString(t,r){return(new Jt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jt,t,r)}static $(){return["RipgrepSearchParams.ITextQueryBuilderOptionsProto.ExtraFileResourcesProto|1 extra_file_resources 9*"]}}class wt extends w{constructor(t){super(),this.excludePattern=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wt).fromBinary(t,r)}static fromJson(t,r){return(new wt).fromJson(t,r)}static fromJsonString(t,r){return(new wt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wt,t,r)}static $(){return["RipgrepSearchParams.ITextQueryBuilderOptionsProto.ExcludePatternProto|1 exclude_pattern #0*",yt]}}class yt extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yt).fromBinary(t,r)}static fromJson(t,r){return(new yt).fromJson(t,r)}static fromJsonString(t,r){return(new yt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yt,t,r)}static $(){return["RipgrepSearchParams.ITextQueryBuilderOptionsProto.ISearchPatternBuilderProto|1 uri 9?|2 pattern #0",St]}}class St extends w{constructor(t){super(),this.patterns=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new St).fromBinary(t,r)}static fromJson(t,r){return(new St).fromJson(t,r)}static fromJsonString(t,r){return(new St).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(St,t,r)}static $(){return["RipgrepSearchParams.ITextQueryBuilderOptionsProto.ISearchPathPatternBuilderProto|1 pattern 9?|2 patterns 9*"]}}class qt extends w{constructor(t){super(),this.matchLines=0,this.charsPerLine=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qt).fromBinary(t,r)}static fromJson(t,r){return(new qt).fromJson(t,r)}static fromJsonString(t,r){return(new qt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qt,t,r)}static $(){return["RipgrepSearchParams.ITextQueryBuilderOptionsProto.ITextSearchPreviewOptionsProto|1 match_lines 5|2 chars_per_line 5"]}}class Bt extends w{constructor(t){super(),this.includeMarkupInput=!1,this.includeMarkupPreview=!1,this.includeCodeInput=!1,this.includeOutput=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bt).fromBinary(t,r)}static fromJson(t,r){return(new Bt).fromJson(t,r)}static fromJsonString(t,r){return(new Bt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bt,t,r)}static $(){return["RipgrepSearchParams.ITextQueryBuilderOptionsProto.INotebookSearchConfigProto|1 include_markup_input 8|2 include_markup_preview 8|3 include_code_input 8|4 include_output 8"]}}class It extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new It).fromBinary(t,r)}static fromJson(t,r){return(new It).fromJson(t,r)}static fromJsonString(t,r){return(new It).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(It,t,r)}static $(){return["RipgrepSearchResult|1 internal #0",Pt]}}class Pt extends w{constructor(t){super(),this.results=[],this.messages=[],this.stats={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pt).fromBinary(t,r)}static fromJson(t,r){return(new Pt).fromJson(t,r)}static fromJsonString(t,r){return(new Pt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pt,t,r)}static $(){return["RipgrepSearchResultInternal|1 results #0*|2 exit #1?|3 limit_hit 8?|4 messages #2*|5 file_search_stats #3 stats|6 text_search_stats #4 stats",vt,Rt,Ut,At,Mt]}}var bt=(0,_.QT)(n.proto3,J,"RipgrepSearchResultInternal.TextSearchCompleteMessageType",[[0,"UNSPECIFIED"],[1,"INFORMATION"],[2,"WARNING"]],1),Rt=(0,_.QT)(n.proto3,J,"RipgrepSearchResultInternal.SearchCompletionExitCode",[[0,"UNSPECIFIED"],[1,"NORMAL"],[2,"NEW_SEARCH_STARTED"]],1);class vt extends w{constructor(t){super(),this.resource="",this.results=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vt).fromBinary(t,r)}static fromJson(t,r){return(new vt).fromJson(t,r)}static fromJsonString(t,r){return(new vt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vt,t,r)}static $(){return["RipgrepSearchResultInternal.IFileMatch|1 resource 9|2 results #0*",xt]}}class xt extends w{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xt).fromBinary(t,r)}static fromJson(t,r){return(new xt).fromJson(t,r)}static fromJsonString(t,r){return(new xt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xt,t,r)}static $(){return["RipgrepSearchResultInternal.ITextSearchResult|1 match #0 result|2 context #1 result",kt,Et]}}class kt extends w{constructor(t){super(),this.rangeLocations=[],this.previewText="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kt).fromBinary(t,r)}static fromJson(t,r){return(new kt).fromJson(t,r)}static fromJsonString(t,r){return(new kt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kt,t,r)}static $(){return["RipgrepSearchResultInternal.ITextSearchMatch|1 uri 9?|2 range_locations #0*|3 preview_text 9|4 webview_index 5?|5 cell_fragment 9?",Ct]}}class Et extends w{constructor(t){super(),this.text="",this.lineNumber=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Et).fromBinary(t,r)}static fromJson(t,r){return(new Et).fromJson(t,r)}static fromJsonString(t,r){return(new Et).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Et,t,r)}static $(){return["RipgrepSearchResultInternal.ITextSearchContext|1 uri 9?|2 text 9|3 line_number 5"]}}class Ct extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ct).fromBinary(t,r)}static fromJson(t,r){return(new Ct).fromJson(t,r)}static fromJsonString(t,r){return(new Ct).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ct,t,r)}static $(){return["RipgrepSearchResultInternal.ISearchRangeSetPairing|1 source #0|2 preview #0",Tt]}}class Tt extends w{constructor(t){super(),this.startLineNumber=0,this.startColumn=0,this.endLineNumber=0,this.endColumn=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tt).fromBinary(t,r)}static fromJson(t,r){return(new Tt).fromJson(t,r)}static fromJsonString(t,r){return(new Tt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tt,t,r)}static $(){return["RipgrepSearchResultInternal.ISearchRange|1 start_line_number 5|2 start_column 5|3 end_line_number 5|4 end_column 5"]}}class Ut extends w{constructor(t){super(),this.text="",this.type=bt.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ut).fromBinary(t,r)}static fromJson(t,r){return(new Ut).fromJson(t,r)}static fromJsonString(t,r){return(new Ut).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ut,t,r)}static $(){return["RipgrepSearchResultInternal.ITextSearchCompleteMessage|1 text 9|2 type #0|3 trusted 8?",bt]}}class At extends w{constructor(t){super(),this.fromCache=!1,this.detailStats={case:void 0},this.resultCount=0,this.type=$t.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new At).fromBinary(t,r)}static fromJson(t,r){return(new At).fromJson(t,r)}static fromJsonString(t,r){return(new At).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(At,t,r)}static $(){return["RipgrepSearchResultInternal.IFileSearchStats|1 from_cache 8|2 search_engine_stats #0 detail_stats|3 cached_search_stats #1 detail_stats|4 file_search_provider_stats #2 detail_stats|5 result_count 5|6 type #3|7 sorting_time 5?",Dt,Nt,Gt,$t]}}var $t=(0,_.QT)(n.proto3,J,"RipgrepSearchResultInternal.IFileSearchStats.FileSearchProviderType",[[0,"UNSPECIFIED"],[1,"FILE_SEARCH_PROVIDER"],[2,"SEARCH_PROCESS"]],1);class Mt extends w{constructor(t){super(),this.type=Ot.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mt).fromBinary(t,r)}static fromJson(t,r){return(new Mt).fromJson(t,r)}static fromJsonString(t,r){return(new Mt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mt,t,r)}static $(){return["RipgrepSearchResultInternal.ITextSearchStats|1 type #0",Ot]}}var Ot=(0,_.QT)(n.proto3,J,"RipgrepSearchResultInternal.ITextSearchStats.TextSearchProviderType",[[0,"UNSPECIFIED"],[1,"TEXT_SEARCH_PROVIDER"],[2,"SEARCH_PROCESS"],[3,"AI_TEXT_SEARCH_PROVIDER"]],1);class Dt extends w{constructor(t){super(),this.fileWalkTime=0,this.directoriesWalked=0,this.filesWalked=0,this.cmdTime=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dt).fromBinary(t,r)}static fromJson(t,r){return(new Dt).fromJson(t,r)}static fromJsonString(t,r){return(new Dt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dt,t,r)}static $(){return["RipgrepSearchResultInternal.ISearchEngineStats|1 file_walk_time 5|2 directories_walked 5|3 files_walked 5|4 cmd_time 5|5 cmd_result_count 5?"]}}class Nt extends w{constructor(t){super(),this.cacheWasResolved=!1,this.cacheLookupTime=0,this.cacheFilterTime=0,this.cacheEntryCount=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nt).fromBinary(t,r)}static fromJson(t,r){return(new Nt).fromJson(t,r)}static fromJsonString(t,r){return(new Nt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nt,t,r)}static $(){return["RipgrepSearchResultInternal.ICachedSearchStats|1 cache_was_resolved 8|2 cache_lookup_time 5|3 cache_filter_time 5|4 cache_entry_count 5"]}}class Gt extends w{constructor(t){super(),this.providerTime=0,this.postProcessTime=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gt).fromBinary(t,r)}static fromJson(t,r){return(new Gt).fromJson(t,r)}static fromJsonString(t,r){return(new Gt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gt,t,r)}static $(){return["RipgrepSearchResultInternal.IFileSearchProviderStats|1 provider_time 5|2 post_process_time 5"]}}class Lt extends w{constructor(t){super(),this.query="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lt).fromBinary(t,r)}static fromJson(t,r){return(new Lt).fromJson(t,r)}static fromJsonString(t,r){return(new Lt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Lt,t,r)}static $(){return["RipgrepSearchStream|1 query 9"]}}class Ft extends w{constructor(t){super(),this.codeResults=[],this.query="",this.prReferences=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ft).fromBinary(t,r)}static fromJson(t,r){return(new Ft).fromJson(t,r)}static fromJsonString(t,r){return(new Ft).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ft,t,r)}static $(){return["ReadSemsearchFilesParams|1 repository_info #0|2 code_results #1*|3 query 9|4 pr_references #2*|5 pr_search_on 8?",l.bn,l.PT,Ze]}}class Kt extends w{constructor(t){super(),this.relativeWorkspacePath="",this.missingReason=zt.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kt).fromBinary(t,r)}static fromJson(t,r){return(new Kt).fromJson(t,r)}static fromJsonString(t,r){return(new Kt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Kt,t,r)}static $(){return["MissingFile|1 relative_workspace_path 9|2 missing_reason #0|3 num_lines 5?",zt]}}var zt=(0,_.QT)(n.proto3,J,"MissingFile.MissingReason",[[0,"UNSPECIFIED"],[1,"TOO_LARGE"],[2,"NOT_FOUND"]],1);class jt extends w{constructor(t){super(),this.knowledge="",this.title="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jt).fromBinary(t,r)}static fromJson(t,r){return(new jt).fromJson(t,r)}static fromJsonString(t,r){return(new jt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jt,t,r)}static $(){return["Knowledge|1 knowledge 9|2 title 9"]}}class Ht extends w{constructor(t){super(),this.sha="",this.fullPrContents="",this.score=0,this.changedFiles=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ht).fromBinary(t,r)}static fromJson(t,r){return(new Ht).fromJson(t,r)}static fromJsonString(t,r){return(new Ht).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ht,t,r)}static $(){return["ToolPullRequestResult|1 sha 9|2 full_pr_contents 9|3 score 2|4 title 9?|5 summary 9?|6 pr_number 13?|7 changed_files 9*|8 author 9?|9 date 9?"]}}class Wt extends w{constructor(t){super(),this.codeResults=[],this.allFiles=[],this.missingFiles=[],this.knowledgeResults=[],this.prResults=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wt).fromBinary(t,r)}static fromJson(t,r){return(new Wt).fromJson(t,r)}static fromJsonString(t,r){return(new Wt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wt,t,r)}static $(){return["ReadSemsearchFilesResult|1 code_results #0*|2 all_files #1*|3 missing_files #2*|4 knowledge_results #3*|5 pr_results #4*|6 git_remote_url 9?|7 pr_hydration_timed_out 8?",l.PT,s.ZH,Kt,jt,Ht]}}class Qt extends w{constructor(t){super(),this.numFiles=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qt).fromBinary(t,r)}static fromJson(t,r){return(new Qt).fromJson(t,r)}static fromJsonString(t,r){return(new Qt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qt,t,r)}static $(){return["ReadSemsearchFilesStream|1 num_files 5"]}}class Vt extends w{constructor(t){super(),this.query="",this.topK=0,this.prReferences=[],this.codeResults=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vt).fromBinary(t,r)}static fromJson(t,r){return(new Vt).fromJson(t,r)}static fromJsonString(t,r){return(new Vt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vt,t,r)}static $(){return["SemanticSearchFullParams|1 repository_info #0|2 query 9|3 include_pattern 9?|4 exclude_pattern 9?|5 top_k 5|6 pr_references #1*|7 pr_search_on 8?|8 explanation 9?|9 code_results #2*",l.bn,Ze,l.PT]}}class Xt extends w{constructor(t){super(),this.codeResults=[],this.allFiles=[],this.missingFiles=[],this.knowledgeResults=[],this.prResults=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xt).fromBinary(t,r)}static fromJson(t,r){return(new Xt).fromJson(t,r)}static fromJsonString(t,r){return(new Xt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xt,t,r)}static $(){return["SemanticSearchFullResult|1 code_results #0*|2 all_files #1*|3 missing_files #2*|4 knowledge_results #3*|5 pr_results #4*|6 git_remote_url 9?|7 pr_hydration_timed_out 8?",l.PT,s.ZH,Kt,jt,Ht]}}class Yt extends w{constructor(t){super(),this.numFiles=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yt).fromBinary(t,r)}static fromJson(t,r){return(new Yt).fromJson(t,r)}static fromJsonString(t,r){return(new Yt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yt,t,r)}static $(){return["SemanticSearchFullStream|1 num_files 5"]}}class Zt extends w{constructor(t){super(),this.relativeWorkspacePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zt).fromBinary(t,r)}static fromJson(t,r){return(new Zt).fromJson(t,r)}static fromJsonString(t,r){return(new Zt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zt,t,r)}static $(){return["DeleteFileParams|1 relative_workspace_path 9"]}}class tr extends w{constructor(t){super(),this.rejected=!1,this.fileNonExistent=!1,this.fileDeletedSuccessfully=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tr).fromBinary(t,r)}static fromJson(t,r){return(new tr).fromJson(t,r)}static fromJsonString(t,r){return(new tr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tr,t,r)}static $(){return["DeleteFileResult|1 rejected 8|2 file_non_existent 8|3 file_deleted_successfully 8"]}}class rr extends w{constructor(t){super(),this.relativeWorkspacePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rr).fromBinary(t,r)}static fromJson(t,r){return(new rr).fromJson(t,r)}static fromJsonString(t,r){return(new rr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rr,t,r)}static $(){return["DeleteFileStream|1 relative_workspace_path 9"]}}class er extends w{constructor(t){super(),this.tool=S.UNSPECIFIED,this.params={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new er).fromBinary(t,r)}static fromJson(t,r){return(new er).fromJson(t,r)}static fromJsonString(t,r){return(new er).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(er,t,r)}static $(){return["BuiltinToolCall|1 tool #0|2 search_params #1 params|3 read_chunk_params #2 params|4 gotodef_params #3 params|5 edit_params #4 params|6 undo_edit_params #5 params|7 end_params #6 params|8 new_file_params #7 params|9 add_test_params #8 params|10 run_test_params #9 params|11 delete_test_params #10 params|12 save_file_params #11 params|13 get_tests_params #12 params|14 get_symbols_params #13 params|15 semantic_search_params #14 params|16 get_project_structure_params #15 params|17 create_rm_files_params #16 params|18 run_terminal_commands_params #17 params|19 new_edit_params #18 params|20 read_with_linter_params #19 params|21 add_ui_step_params #20 params|23 read_semsearch_files_params #21 params|26 delete_file_params #22 params|22 tool_call_id 9?",S,Pr,xr,Or,Kr,Er,Cr,wr,Qr,Zr,se,oe,re,ue,yr,gr,pr,fr,Lr,lr,sr,Ft,Zt]}}class nr extends w{constructor(t){super(),this.tool=S.UNSPECIFIED,this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nr).fromBinary(t,r)}static fromJson(t,r){return(new nr).fromJson(t,r)}static fromJsonString(t,r){return(new nr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nr,t,r)}static $(){return["BuiltinToolResult|1 tool #0|2 search_result #1 result|3 read_chunk_result #2 result|4 gotodef_result #3 result|5 edit_result #4 result|6 undo_edit_result #5 result|7 end_result #6 result|8 new_file_result #7 result|9 add_test_result #8 result|10 run_test_result #9 result|11 delete_test_result #10 result|12 save_file_result #11 result|13 get_tests_result #12 result|14 get_symbols_result #13 result|15 semantic_search_result #14 result|16 get_project_structure_result #15 result|17 create_rm_files_result #16 result|18 run_terminal_commands_result #17 result|19 new_edit_result #18 result|20 read_with_linter_result #19 result|21 add_ui_step_result #20 result|22 read_semsearch_files_result #21 result|24 delete_file_result #22 result",S,vr,kr,Nr,jr,Ur,Ar,Tr,Vr,te,ie,ae,ee,le,Br,_r,hr,dr,Fr,mr,ar,Wt,tr]}}class sr extends w{constructor(t){super(),this.conversationId="",this.step={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sr).fromBinary(t,r)}static fromJson(t,r){return(new sr).fromJson(t,r)}static fromJsonString(t,r){return(new sr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sr,t,r)}static $(){return["AddUiStepParams|1 conversation_id 9|2 search_results #0 step",or]}}class ir extends w{constructor(t){super(),this.relativeWorkspacePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ir).fromBinary(t,r)}static fromJson(t,r){return(new ir).fromJson(t,r)}static fromJsonString(t,r){return(new ir).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ir,t,r)}static $(){return["AddUiStepParams.SearchResult|1 relative_workspace_path 9"]}}class or extends w{constructor(t){super(),this.searchResults=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new or).fromBinary(t,r)}static fromJson(t,r){return(new or).fromJson(t,r)}static fromJsonString(t,r){return(new or).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(or,t,r)}static $(){return["AddUiStepParams.SearchResults|1 search_results #0*",ir]}}class ar extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ar).fromBinary(t,r)}static fromJson(t,r){return(new ar).fromJson(t,r)}static fromJsonString(t,r){return(new ar).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ar,t,r)}static $(){return["AddUiStepResult"]}}class ur extends w{constructor(t){super(),this.toolCall={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ur).fromBinary(t,r)}static fromJson(t,r){return(new ur).fromJson(t,r)}static fromJsonString(t,r){return(new ur).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ur,t,r)}static $(){return["ToolCall|1 builtin_tool_call #0 tool_call|2 custom_tool_call #1 tool_call",er,$r]}}class cr extends w{constructor(t){super(),this.toolResult={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cr).fromBinary(t,r)}static fromJson(t,r){return(new cr).fromJson(t,r)}static fromJsonString(t,r){return(new cr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cr,t,r)}static $(){return["ToolResult|1 builtin_tool_result #0 tool_result|2 custom_tool_result #1 tool_result|3 error_tool_result #2 tool_result",nr,Mr,Gr]}}class lr extends w{constructor(t){super(),this.relativeWorkspacePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new lr).fromBinary(t,r)}static fromJson(t,r){return(new lr).fromJson(t,r)}static fromJsonString(t,r){return(new lr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(lr,t,r)}static $(){return["ReadWithLinterParams|1 relative_workspace_path 9"]}}class mr extends w{constructor(t){super(),this.contents="",this.diagnostics=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mr).fromBinary(t,r)}static fromJson(t,r){return(new mr).fromJson(t,r)}static fromJsonString(t,r){return(new mr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mr,t,r)}static $(){return["ReadWithLinterResult|1 contents 9|2 diagnostics #0*",s.oQ]}}class fr extends w{constructor(t){super(),this.commands=[],this.commandsUuid="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fr).fromBinary(t,r)}static fromJson(t,r){return(new fr).fromJson(t,r)}static fromJsonString(t,r){return(new fr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fr,t,r)}static $(){return["RunTerminalCommandsParams|1 commands 9*|2 commands_uuid 9"]}}class dr extends w{constructor(t){super(),this.outputs=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dr).fromBinary(t,r)}static fromJson(t,r){return(new dr).fromJson(t,r)}static fromJsonString(t,r){return(new dr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dr,t,r)}static $(){return["RunTerminalCommandsResult|1 outputs 9*"]}}class pr extends w{constructor(t){super(),this.removedFilePaths=[],this.createdFilePaths=[],this.createdDirectoryPaths=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pr).fromBinary(t,r)}static fromJson(t,r){return(new pr).fromJson(t,r)}static fromJsonString(t,r){return(new pr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pr,t,r)}static $(){return["CreateRmFilesParams|1 removed_file_paths 9*|2 created_file_paths 9*|3 created_directory_paths 9*"]}}class hr extends w{constructor(t){super(),this.createdFilePaths=[],this.removedFilePaths=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hr).fromBinary(t,r)}static fromJson(t,r){return(new hr).fromJson(t,r)}static fromJsonString(t,r){return(new hr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hr,t,r)}static $(){return["CreateRmFilesResult|1 created_file_paths 9*|2 removed_file_paths 9*"]}}class gr extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gr).fromBinary(t,r)}static fromJson(t,r){return(new gr).fromJson(t,r)}static fromJsonString(t,r){return(new gr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gr,t,r)}static $(){return["GetProjectStructureParams"]}}class _r extends w{constructor(t){super(),this.files=[],this.rootWorkspacePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _r).fromBinary(t,r)}static fromJson(t,r){return(new _r).fromJson(t,r)}static fromJsonString(t,r){return(new _r).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_r,t,r)}static $(){return["GetProjectStructureResult|1 files #0*|2 root_workspace_path 9",Jr]}}class Jr extends w{constructor(t){super(),this.relativeWorkspacePath="",this.outline="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jr).fromBinary(t,r)}static fromJson(t,r){return(new Jr).fromJson(t,r)}static fromJsonString(t,r){return(new Jr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jr,t,r)}static $(){return["GetProjectStructureResult.File|1 relative_workspace_path 9|2 outline 9"]}}class wr extends w{constructor(t){super(),this.relativeWorkspacePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wr).fromBinary(t,r)}static fromJson(t,r){return(new wr).fromJson(t,r)}static fromJsonString(t,r){return(new wr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wr,t,r)}static $(){return["NewFileParams|1 relative_workspace_path 9"]}}class yr extends w{constructor(t){super(),this.query="",this.topK=0,this.grabWholeFile=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yr).fromBinary(t,r)}static fromJson(t,r){return(new yr).fromJson(t,r)}static fromJsonString(t,r){return(new yr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yr,t,r)}static $(){return["SemanticSearchParams|1 query 9|2 include_pattern 9?|3 exclude_pattern 9?|4 top_k 5|5 index_id 9?|6 grab_whole_file 8"]}}class Sr extends w{constructor(t){super(),this.startLine=0,this.startCharacter=0,this.endLine=0,this.endCharacter=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sr).fromBinary(t,r)}static fromJson(t,r){return(new Sr).fromJson(t,r)}static fromJsonString(t,r){return(new Sr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sr,t,r)}static $(){return["Range|1 start_line 5|2 start_character 5|3 end_line 5|4 end_character 5"]}}class qr extends w{constructor(t){super(),this.start=0,this.end=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qr).fromBinary(t,r)}static fromJson(t,r){return(new qr).fromJson(t,r)}static fromJsonString(t,r){return(new qr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qr,t,r)}static $(){return["MatchRange|1 start 5|2 end 5"]}}class Br extends w{constructor(t){super(),this.results=[],this.files={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Br).fromBinary(t,r)}static fromJson(t,r){return(new Br).fromJson(t,r)}static fromJsonString(t,r){return(new Br).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Br,t,r)}static $(){return["SemanticSearchResult|1 results #0*|2 files 9,9",Ir]}}class Ir extends w{constructor(t){super(),this.relativeWorkspacePath="",this.score=0,this.content="",this.detailedLines=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ir).fromBinary(t,r)}static fromJson(t,r){return(new Ir).fromJson(t,r)}static fromJsonString(t,r){return(new Ir).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ir,t,r)}static $(){return["SemanticSearchResult.Item|1 relative_workspace_path 9|2 score 2|3 content 9|4 range #0|5 original_content 9?|6 detailed_lines #1*",s._u,s.d7]}}class Pr extends w{constructor(t){super(),this.query="",this.regex=!1,this.includePattern="",this.excludePattern="",this.filenameSearch=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pr).fromBinary(t,r)}static fromJson(t,r){return(new Pr).fromJson(t,r)}static fromJsonString(t,r){return(new Pr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pr,t,r)}static $(){return["SearchParams|1 query 9|2 regex 8|3 include_pattern 9|4 exclude_pattern 9|5 filename_search 8"]}}class br extends w{constructor(t){super(),this.relativeWorkspacePath="",this.numMatches=0,this.potentiallyRelevantLines=[],this.cropped=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new br).fromBinary(t,r)}static fromJson(t,r){return(new br).fromJson(t,r)}static fromJsonString(t,r){return(new br).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(br,t,r)}static $(){return["SearchToolFileSearchResult|1 relative_workspace_path 9|2 num_matches 5|3 potentially_relevant_lines #0*|4 cropped 8",Rr]}}class Rr extends w{constructor(t){super(),this.lineNumber=0,this.text="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rr).fromBinary(t,r)}static fromJson(t,r){return(new Rr).fromJson(t,r)}static fromJsonString(t,r){return(new Rr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rr,t,r)}static $(){return["SearchToolFileSearchResult.Line|1 line_number 5|2 text 9"]}}class vr extends w{constructor(t){super(),this.fileResults=[],this.numTotalMatches=0,this.numTotalMatchedFiles=0,this.numTotalMayBeIncomplete=!1,this.filesOnly=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vr).fromBinary(t,r)}static fromJson(t,r){return(new vr).fromJson(t,r)}static fromJsonString(t,r){return(new vr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vr,t,r)}static $(){return["SearchResult|1 file_results #0*|2 num_total_matches 5|3 num_total_matched_files 5|4 num_total_may_be_incomplete 8|5 files_only 8",br]}}class xr extends w{constructor(t){super(),this.relativeWorkspacePath="",this.startLineNumber=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xr).fromBinary(t,r)}static fromJson(t,r){return(new xr).fromJson(t,r)}static fromJsonString(t,r){return(new xr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xr,t,r)}static $(){return["ReadChunkParams|1 relative_workspace_path 9|2 start_line_number 5|3 num_lines 5?"]}}class kr extends w{constructor(t){super(),this.relativeWorkspacePath="",this.startLineNumber=0,this.lines=[],this.totalNumLines=0,this.cropped=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kr).fromBinary(t,r)}static fromJson(t,r){return(new kr).fromJson(t,r)}static fromJsonString(t,r){return(new kr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kr,t,r)}static $(){return["ReadChunkResult|1 relative_workspace_path 9|2 start_line_number 5|3 lines 9*|4 total_num_lines 5|5 cropped 8"]}}class Er extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Er).fromBinary(t,r)}static fromJson(t,r){return(new Er).fromJson(t,r)}static fromJsonString(t,r){return(new Er).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Er,t,r)}static $(){return["UndoEditParams"]}}class Cr extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cr).fromBinary(t,r)}static fromJson(t,r){return(new Cr).fromJson(t,r)}static fromJsonString(t,r){return(new Cr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cr,t,r)}static $(){return["EndParams"]}}class Tr extends w{constructor(t){super(),this.relativeWorkspacePath="",this.fileTotalLines=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tr).fromBinary(t,r)}static fromJson(t,r){return(new Tr).fromJson(t,r)}static fromJsonString(t,r){return(new Tr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tr,t,r)}static $(){return["NewFileResult|1 relative_workspace_path 9|2 file_total_lines 5"]}}class Ur extends w{constructor(t){super(),this.feedback=[],this.relativeWorkspacePath="",this.contextStartLineNumber=0,this.contextLines=[],this.contextTotalNumLines=0,this.fileTotalLines=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ur).fromBinary(t,r)}static fromJson(t,r){return(new Ur).fromJson(t,r)}static fromJsonString(t,r){return(new Ur).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ur,t,r)}static $(){return["UndoEditResult|1 feedback 9*|4 relative_workspace_path 9|2 context_start_line_number 5|3 context_lines 9*|5 context_total_num_lines 5|6 file_total_lines 5"]}}class Ar extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ar).fromBinary(t,r)}static fromJson(t,r){return(new Ar).fromJson(t,r)}static fromJsonString(t,r){return(new Ar).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ar,t,r)}static $(){return["EndResult"]}}class $r extends w{constructor(t){super(),this.toolId="",this.params="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $r).fromBinary(t,r)}static fromJson(t,r){return(new $r).fromJson(t,r)}static fromJsonString(t,r){return(new $r).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($r,t,r)}static $(){return["CustomToolCall|1 tool_id 9|2 params 9"]}}class Mr extends w{constructor(t){super(),this.toolId="",this.result="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mr).fromBinary(t,r)}static fromJson(t,r){return(new Mr).fromJson(t,r)}static fromJsonString(t,r){return(new Mr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mr,t,r)}static $(){return["CustomToolResult|1 tool_id 9|2 result 9"]}}class Or extends w{constructor(t){super(),this.relativeWorkspacePath="",this.symbol="",this.startLine=0,this.endLine=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Or).fromBinary(t,r)}static fromJson(t,r){return(new Or).fromJson(t,r)}static fromJsonString(t,r){return(new Or).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Or,t,r)}static $(){return["GotodefParams|1 relative_workspace_path 9|2 symbol 9|3 start_line 5|4 end_line 5"]}}class Dr extends w{constructor(t){super(),this.relativeWorkspacePath="",this.startLine=0,this.endLine=0,this.codeContextLines=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dr).fromBinary(t,r)}static fromJson(t,r){return(new Dr).fromJson(t,r)}static fromJsonString(t,r){return(new Dr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dr,t,r)}static $(){return["GotodefDefinition|1 relative_workspace_path 9|2 fully_qualified_name 9?|3 symbol_kind 9?|4 start_line 5|5 end_line 5|6 code_context_lines 9*"]}}class Nr extends w{constructor(t){super(),this.definitions=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nr).fromBinary(t,r)}static fromJson(t,r){return(new Nr).fromJson(t,r)}static fromJsonString(t,r){return(new Nr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nr,t,r)}static $(){return["GotodefResult|1 definitions #0*",Dr]}}class Gr extends w{constructor(t){super(),this.errorMessage="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gr).fromBinary(t,r)}static fromJson(t,r){return(new Gr).fromJson(t,r)}static fromJsonString(t,r){return(new Gr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gr,t,r)}static $(){return["ErrorToolResult|1 error_message 9"]}}class Lr extends w{constructor(t){super(),this.relativeWorkspacePath="",this.text="",this.editId="",this.firstEdit=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Lr).fromBinary(t,r)}static fromJson(t,r){return(new Lr).fromJson(t,r)}static fromJsonString(t,r){return(new Lr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Lr,t,r)}static $(){return["NewEditParams|1 relative_workspace_path 9|2 start_line_number 5?|3 end_line_number 5?|4 text 9|5 edit_id 9|6 first_edit 8"]}}class Fr extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fr).fromBinary(t,r)}static fromJson(t,r){return(new Fr).fromJson(t,r)}static fromJsonString(t,r){return(new Fr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fr,t,r)}static $(){return["NewEditResult"]}}class Kr extends w{constructor(t){super(),this.relativeWorkspacePath="",this.replaceNumLines=0,this.newLines=[],this.editId="",this.frontendEditType=zr.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kr).fromBinary(t,r)}static fromJson(t,r){return(new Kr).fromJson(t,r)}static fromJsonString(t,r){return(new Kr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Kr,t,r)}static $(){return["EditParams|1 relative_workspace_path 9|2 line_number 5?|3 replace_num_lines 5|4 new_lines 9*|7 replace_whole_file 8?|5 edit_id 9|6 frontend_edit_type #0|8 auto_fix_all_linter_errors_in_file 8?",zr]}}var zr=(0,_.QT)(n.proto3,J,"EditParams.FrontendEditType",[[0,"UNSPECIFIED"],[1,"INLINE_DIFFS"],[2,"SIMPLE"]],1);class jr extends w{constructor(t){super(),this.feedback=[],this.contextStartLineNumber=0,this.contextLines=[],this.file="",this.fileTotalLines=0,this.structuredFeedback=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jr).fromBinary(t,r)}static fromJson(t,r){return(new jr).fromJson(t,r)}static fromJsonString(t,r){return(new jr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jr,t,r)}static $(){return["EditResult|1 feedback 9*|2 context_start_line_number 5|3 context_lines 9*|4 file 9|5 file_total_lines 5|6 structured_feedback #0*",Wr]}}class Hr extends w{constructor(t){super(),this.message="",this.startLineNumber=0,this.endLineNumber=0,this.relativeWorkspacePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hr).fromBinary(t,r)}static fromJson(t,r){return(new Hr).fromJson(t,r)}static fromJsonString(t,r){return(new Hr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hr,t,r)}static $(){return["EditResult.RelatedInformation|1 message 9|2 start_line_number 5|3 end_line_number 5|4 relative_workspace_path 9"]}}class Wr extends w{constructor(t){super(),this.message="",this.severity="",this.startLineNumber=0,this.endLineNumber=0,this.relatedInformation=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wr).fromBinary(t,r)}static fromJson(t,r){return(new Wr).fromJson(t,r)}static fromJsonString(t,r){return(new Wr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wr,t,r)}static $(){return["EditResult.Feedback|1 message 9|2 severity 9|3 start_line_number 5|4 end_line_number 5|5 related_information #0*",Hr]}}class Qr extends w{constructor(t){super(),this.relativeWorkspacePath="",this.testName="",this.testCode="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qr).fromBinary(t,r)}static fromJson(t,r){return(new Qr).fromJson(t,r)}static fromJsonString(t,r){return(new Qr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qr,t,r)}static $(){return["AddTestParams|1 relative_workspace_path 9|2 test_name 9|3 test_code 9"]}}class Vr extends w{constructor(t){super(),this.feedback=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vr).fromBinary(t,r)}static fromJson(t,r){return(new Vr).fromJson(t,r)}static fromJsonString(t,r){return(new Vr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vr,t,r)}static $(){return["AddTestResult|1 feedback #0*",Yr]}}class Xr extends w{constructor(t){super(),this.message="",this.startLineNumber=0,this.endLineNumber=0,this.relativeWorkspacePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xr).fromBinary(t,r)}static fromJson(t,r){return(new Xr).fromJson(t,r)}static fromJsonString(t,r){return(new Xr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xr,t,r)}static $(){return["AddTestResult.RelatedInformation|1 message 9|2 start_line_number 5|3 end_line_number 5|4 relative_workspace_path 9"]}}class Yr extends w{constructor(t){super(),this.message="",this.severity="",this.startLineNumber=0,this.endLineNumber=0,this.relatedInformation=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yr).fromBinary(t,r)}static fromJson(t,r){return(new Yr).fromJson(t,r)}static fromJsonString(t,r){return(new Yr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yr,t,r)}static $(){return["AddTestResult.Feedback|1 message 9|2 severity 9|3 start_line_number 5|4 end_line_number 5|5 related_information #0*",Xr]}}class Zr extends w{constructor(t){super(),this.relativeWorkspacePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zr).fromBinary(t,r)}static fromJson(t,r){return(new Zr).fromJson(t,r)}static fromJsonString(t,r){return(new Zr).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zr,t,r)}static $(){return["RunTestParams|1 relative_workspace_path 9|2 test_name 9?"]}}class te extends w{constructor(t){super(),this.result="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new te).fromBinary(t,r)}static fromJson(t,r){return(new te).fromJson(t,r)}static fromJsonString(t,r){return(new te).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(te,t,r)}static $(){return["RunTestResult|1 result 9"]}}class re extends w{constructor(t){super(),this.relativeWorkspacePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new re).fromBinary(t,r)}static fromJson(t,r){return(new re).fromJson(t,r)}static fromJsonString(t,r){return(new re).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(re,t,r)}static $(){return["GetTestsParams|1 relative_workspace_path 9"]}}class ee extends w{constructor(t){super(),this.tests=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ee).fromBinary(t,r)}static fromJson(t,r){return(new ee).fromJson(t,r)}static fromJsonString(t,r){return(new ee).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ee,t,r)}static $(){return["GetTestsResult|1 tests #0*",ne]}}class ne extends w{constructor(t){super(),this.name="",this.lines=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ne).fromBinary(t,r)}static fromJson(t,r){return(new ne).fromJson(t,r)}static fromJsonString(t,r){return(new ne).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ne,t,r)}static $(){return["GetTestsResult.Test|1 name 9|2 lines 9*"]}}class se extends w{constructor(t){super(),this.relativeWorkspacePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new se).fromBinary(t,r)}static fromJson(t,r){return(new se).fromJson(t,r)}static fromJsonString(t,r){return(new se).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(se,t,r)}static $(){return["DeleteTestParams|1 relative_workspace_path 9|2 test_name 9?"]}}class ie extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ie).fromBinary(t,r)}static fromJson(t,r){return(new ie).fromJson(t,r)}static fromJsonString(t,r){return(new ie).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ie,t,r)}static $(){return["DeleteTestResult"]}}class oe extends w{constructor(t){super(),this.relativeWorkspacePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new oe).fromBinary(t,r)}static fromJson(t,r){return(new oe).fromJson(t,r)}static fromJsonString(t,r){return(new oe).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(oe,t,r)}static $(){return["SaveFileParams|1 relative_workspace_path 9"]}}class ae extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ae).fromBinary(t,r)}static fromJson(t,r){return(new ae).fromJson(t,r)}static fromJsonString(t,r){return(new ae).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ae,t,r)}static $(){return["SaveFileResult"]}}class ue extends w{constructor(t){super(),this.relativeWorkspacePath="",this.includeChildren=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ue).fromBinary(t,r)}static fromJson(t,r){return(new ue).fromJson(t,r)}static fromJsonString(t,r){return(new ue).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ue,t,r)}static $(){return["GetSymbolsParams|1 relative_workspace_path 9|2 line_range #0?|3 include_children 8",ce]}}class ce extends w{constructor(t){super(),this.startLineNumber=0,this.endLineNumberInclusive=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ce).fromBinary(t,r)}static fromJson(t,r){return(new ce).fromJson(t,r)}static fromJsonString(t,r){return(new ce).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ce,t,r)}static $(){return["GetSymbolsParams.LineRange|1 start_line_number 5|2 end_line_number_inclusive 5"]}}class le extends w{constructor(t){super(),this.symbols=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new le).fromBinary(t,r)}static fromJson(t,r){return(new le).fromJson(t,r)}static fromJsonString(t,r){return(new le).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(le,t,r)}static $(){return["GetSymbolsResult|1 symbols #0*",s.Az]}}class me extends w{constructor(t){super(),this.parsingFailed=!1,this.executableCommands=[],this.hasRedirects=!1,this.hasCommandSubstitution=!1,this.redirects=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new me).fromBinary(t,r)}static fromJson(t,r){return(new me).fromJson(t,r)}static fromJsonString(t,r){return(new me).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(me,t,r)}static $(){return["ShellCommandParsingResult|1 parsing_failed 8|2 executable_commands #0*|3 has_redirects 8|4 has_command_substitution 8|5 all_redirects_are_dev_null 8?|6 redirects #1*",de,pe]}}class fe extends w{constructor(t){super(),this.type="",this.value="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fe).fromBinary(t,r)}static fromJson(t,r){return(new fe).fromJson(t,r)}static fromJsonString(t,r){return(new fe).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fe,t,r)}static $(){return["ShellCommandParsingResult.ExecutableCommandArg|1 type 9|2 value 9"]}}class de extends w{constructor(t){super(),this.name="",this.args=[],this.fullText="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new de).fromBinary(t,r)}static fromJson(t,r){return(new de).fromJson(t,r)}static fromJsonString(t,r){return(new de).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(de,t,r)}static $(){return["ShellCommandParsingResult.ExecutableCommand|1 name 9|2 args #0*|3 full_text 9",fe]}}class pe extends w{constructor(t){super(),this.operator="",this.destinationFds=[],this.targetNodeType="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pe).fromBinary(t,r)}static fromJson(t,r){return(new pe).fromJson(t,r)}static fromJsonString(t,r){return(new pe).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pe,t,r)}static $(){return["ShellCommandParsingResult.Redirect|1 operator 9|2 destination_fds 13*|3 target_node_type 9|4 target_text 9?"]}}class he extends w{constructor(t){super(),this.command="",this.isBackground=!1,this.requireUserApproval=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new he).fromBinary(t,r)}static fromJson(t,r){return(new he).fromJson(t,r)}static fromJsonString(t,r){return(new he).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(he,t,r)}static $(){return["RunTerminalCommandV2Params|1 command 9|2 cwd 9?|3 new_session 8?|4 options #0?|5 is_background 8|6 require_user_approval 8|7 parsing_result #1?|8 idle_timeout_seconds 5?|9 requested_sandbox_policy #2?|10 file_output_threshold_bytes 3?|11 command_description 9?|12 classifier_result #3?",ge,me,m.Mw,f.E4]}}class ge extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ge).fromBinary(t,r)}static fromJson(t,r){return(new ge).fromJson(t,r)}static fromJsonString(t,r){return(new ge).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ge,t,r)}static $(){return["RunTerminalCommandV2Params.ExecutionOptions|1 timeout 5?|2 skip_ai_check 8?|3 command_run_timeout_ms 5?|4 command_change_check_interval_ms 5?|5 ai_finish_check_max_attempts 5?|6 ai_finish_check_interval_ms 5?|7 delayer_interval_ms 5?|8 ai_check_for_hangs 8?"]}}class _e extends w{constructor(t){super(),this.filePath="",this.sizeBytes=n.protoInt64.zero,this.lineCount=n.protoInt64.zero,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _e).fromBinary(t,r)}static fromJson(t,r){return(new _e).fromJson(t,r)}static fromJsonString(t,r){return(new _e).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_e,t,r)}static $(){return["OutputLocation|1 file_path 9|2 size_bytes 3|3 line_count 3"]}}class Je extends w{constructor(t){super(),this.output="",this.exitCode=0,this.poppedOutIntoBackground=!1,this.isRunningInBackground=!1,this.notInterrupted=!1,this.resultingWorkingDirectory="",this.didUserChange=!1,this.endedReason=q.UNSPECIFIED,this.outputRaw="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Je).fromBinary(t,r)}static fromJson(t,r){return(new Je).fromJson(t,r)}static fromJsonString(t,r){return(new Je).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Je,t,r)}static $(){return["RunTerminalCommandV2Result|1 output 9|2 exit_code 5|3 rejected 8?|4 popped_out_into_background 8|5 is_running_in_background 8|6 not_interrupted 8|7 resulting_working_directory 9|8 did_user_change 8|9 ended_reason #0|10 exit_code_v2 5?|11 updated_command 9?|12 output_raw 9|13 human_review_v2 #1?|14 effective_sandbox_policy #2?|15 terminal_instance_id 5?|16 output_location #3?|17 terminal_instance_path 9?|18 background_shell_id 13?",q,rt,m.Mw,_e]}}class we extends w{constructor(t){super(),this.command="",this.isBackground=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new we).fromBinary(t,r)}static fromJson(t,r){return(new we).fromJson(t,r)}static fromJsonString(t,r){return(new we).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(we,t,r)}static $(){return["RunTerminalCommandV2Stream|1 command 9|2 is_background 8|7 parsing_result #0?|8 idle_timeout_seconds 5?|9 requested_sandbox_policy #1?",me,m.Mw]}}class ye extends w{constructor(t){super(),this.ruleNames=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ye).fromBinary(t,r)}static fromJson(t,r){return(new ye).fromJson(t,r)}static fromJsonString(t,r){return(new ye).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ye,t,r)}static $(){return["FetchRulesStream|1 rule_names 9*"]}}class Se extends w{constructor(t){super(),this.searchTerm="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Se).fromBinary(t,r)}static fromJson(t,r){return(new Se).fromJson(t,r)}static fromJsonString(t,r){return(new Se).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Se,t,r)}static $(){return["WebSearchParams|1 search_term 9"]}}class qe extends w{constructor(t){super(),this.references=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qe).fromBinary(t,r)}static fromJson(t,r){return(new qe).fromJson(t,r)}static fromJsonString(t,r){return(new qe).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qe,t,r)}static $(){return["WebSearchResult|1 references #0*|2 is_final 8?|3 rejected 8?",Be]}}class Be extends w{constructor(t){super(),this.title="",this.url="",this.chunk="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Be).fromBinary(t,r)}static fromJson(t,r){return(new Be).fromJson(t,r)}static fromJsonString(t,r){return(new Be).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Be,t,r)}static $(){return["WebSearchResult.WebReference|1 title 9|2 url 9|3 chunk 9"]}}class Ie extends w{constructor(t){super(),this.searchTerm="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ie).fromBinary(t,r)}static fromJson(t,r){return(new Ie).fromJson(t,r)}static fromJsonString(t,r){return(new Ie).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ie,t,r)}static $(){return["WebSearchStream|1 search_term 9"]}}class Pe extends w{constructor(t){super(),this.tools=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pe).fromBinary(t,r)}static fromJson(t,r){return(new Pe).fromJson(t,r)}static fromJsonString(t,r){return(new Pe).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pe,t,r)}static $(){return["MCPParams|1 tools #0*|2 file_output_threshold_bytes 3?",be]}}class be extends w{constructor(t){super(),this.name="",this.description="",this.parameters="",this.serverName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new be).fromBinary(t,r)}static fromJson(t,r){return(new be).fromJson(t,r)}static fromJsonString(t,r){return(new be).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(be,t,r)}static $(){return["MCPParams.Tool|1 name 9|2 description 9|3 parameters 9|4 server_name 9|5 transcript_display #0?",Re]}}class Re extends w{constructor(t){super(),this.loading="",this.success="",this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Re).fromBinary(t,r)}static fromJson(t,r){return(new Re).fromJson(t,r)}static fromJsonString(t,r){return(new Re).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Re,t,r)}static $(){return["MCPParams.TranscriptDisplay|1 loading 9|2 success 9|3 error 9"]}}class ve extends w{constructor(t){super(),this.selectedTool="",this.result="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ve).fromBinary(t,r)}static fromJson(t,r){return(new ve).fromJson(t,r)}static fromJsonString(t,r){return(new ve).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ve,t,r)}static $(){return["MCPResult|1 selected_tool 9|2 result 9"]}}class xe extends w{constructor(t){super(),this.tools=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xe).fromBinary(t,r)}static fromJson(t,r){return(new xe).fromJson(t,r)}static fromJsonString(t,r){return(new xe).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xe,t,r)}static $(){return["MCPStream|1 tools #0*",be]}}class ke extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ke).fromBinary(t,r)}static fromJson(t,r){return(new ke).fromJson(t,r)}static fromJsonString(t,r){return(new ke).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ke,t,r)}static $(){return["ListMcpResourcesParams|1 server 9?"]}}class Ee extends w{constructor(t){super(),this.resources=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ee).fromBinary(t,r)}static fromJson(t,r){return(new Ee).fromJson(t,r)}static fromJsonString(t,r){return(new Ee).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ee,t,r)}static $(){return["ListMcpResourcesResult|1 resources #0*",Ce]}}class Ce extends w{constructor(t){super(),this.uri="",this.server="",this.annotations={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ce).fromBinary(t,r)}static fromJson(t,r){return(new Ce).fromJson(t,r)}static fromJsonString(t,r){return(new Ce).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ce,t,r)}static $(){return["ListMcpResourcesResult.MCPResource|1 uri 9|2 name 9?|3 description 9?|4 mime_type 9?|5 server 9|6 annotations 9,9"]}}class Te extends w{constructor(t){super(),this.server="",this.uri="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Te).fromBinary(t,r)}static fromJson(t,r){return(new Te).fromJson(t,r)}static fromJsonString(t,r){return(new Te).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Te,t,r)}static $(){return["ReadMcpResourceParams|1 server 9|2 uri 9|3 download_path 9?"]}}class Ue extends w{constructor(t){super(),this.uri="",this.content={case:void 0},this.annotations={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ue).fromBinary(t,r)}static fromJson(t,r){return(new Ue).fromJson(t,r)}static fromJsonString(t,r){return(new Ue).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ue,t,r)}static $(){return["ReadMcpResourceResult|1 uri 9|2 name 9?|3 description 9?|4 mime_type 9?|5 text 9 content|6 blob 12 content|7 annotations 9,9"]}}class Ae extends w{constructor(t){super(),this.server="",this.toolName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ae).fromBinary(t,r)}static fromJson(t,r){return(new Ae).fromJson(t,r)}static fromJsonString(t,r){return(new Ae).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ae,t,r)}static $(){return["CallMcpToolParams|1 server 9|2 tool_name 9|3 tool_args #0",n.Struct]}}class $e extends w{constructor(t){super(),this.server="",this.toolName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $e).fromBinary(t,r)}static fromJson(t,r){return(new $e).fromJson(t,r)}static fromJsonString(t,r){return(new $e).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($e,t,r)}static $(){return["CallMcpToolResult|1 server 9|2 tool_name 9|3 result #0",n.Struct]}}class Me extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Me).fromBinary(t,r)}static fromJson(t,r){return(new Me).fromJson(t,r)}static fromJsonString(t,r){return(new Me).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Me,t,r)}static $(){return["GetMcpToolsParams|1 server 9?|2 tool_name 9?|3 pattern 9?"]}}class Oe extends w{constructor(t){super(),this.content="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Oe).fromBinary(t,r)}static fromJson(t,r){return(new Oe).fromJson(t,r)}static fromJsonString(t,r){return(new Oe).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Oe,t,r)}static $(){return["GetMcpToolsResult|1 content 9|2 output_file_path 9?"]}}class De extends w{constructor(t){super(),this.query="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new De).fromBinary(t,r)}static fromJson(t,r){return(new De).fromJson(t,r)}static fromJsonString(t,r){return(new De).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(De,t,r)}static $(){return["SearchSymbolsParams|1 query 9"]}}class Ne extends w{constructor(t){super(),this.matches=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ne).fromBinary(t,r)}static fromJson(t,r){return(new Ne).fromJson(t,r)}static fromJsonString(t,r){return(new Ne).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ne,t,r)}static $(){return["SearchSymbolsResult|1 matches #0*|2 rejected 8?",Ge]}}class Ge extends w{constructor(t){super(),this.name="",this.uri="",this.secondaryText="",this.labelMatches=[],this.descriptionMatches=[],this.score=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ge).fromBinary(t,r)}static fromJson(t,r){return(new Ge).fromJson(t,r)}static fromJsonString(t,r){return(new Ge).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ge,t,r)}static $(){return["SearchSymbolsResult.SymbolMatch|1 name 9|2 uri 9|3 range #0|4 secondary_text 9|5 label_matches #1*|6 description_matches #1*|7 score 1",Sr,qr]}}class Le extends w{constructor(t){super(),this.query="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Le).fromBinary(t,r)}static fromJson(t,r){return(new Le).fromJson(t,r)}static fromJsonString(t,r){return(new Le).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Le,t,r)}static $(){return["SearchSymbolsStream|1 query 9"]}}class Fe extends w{constructor(t){super(),this.proposedFollowup="",this.bcId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fe).fromBinary(t,r)}static fromJson(t,r){return(new Fe).fromJson(t,r)}static fromJsonString(t,r){return(new Fe).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fe,t,r)}static $(){return["BackgroundComposerFollowupParams|1 proposed_followup 9|2 bc_id 9"]}}class Ke extends w{constructor(t){super(),this.proposedFollowup="",this.isSent=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ke).fromBinary(t,r)}static fromJson(t,r){return(new Ke).fromJson(t,r)}static fromJsonString(t,r){return(new Ke).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ke,t,r)}static $(){return["BackgroundComposerFollowupResult|1 proposed_followup 9|2 is_sent 8"]}}class ze extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ze).fromBinary(t,r)}static fromJson(t,r){return(new ze).fromJson(t,r)}static fromJsonString(t,r){return(new ze).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ze,t,r)}static $(){return["BackgroundComposerFollowupStream"]}}class je extends w{constructor(t){super(),this.knowledgeToStore="",this.title="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new je).fromBinary(t,r)}static fromJson(t,r){return(new je).fromJson(t,r)}static fromJsonString(t,r){return(new je).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(je,t,r)}static $(){return["KnowledgeBaseParams|1 knowledge_to_store 9|2 title 9|3 existing_knowledge_id 9?|4 action 9?"]}}class He extends w{constructor(t){super(),this.success=!1,this.confirmationMessage="",this.id="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new He).fromBinary(t,r)}static fromJson(t,r){return(new He).fromJson(t,r)}static fromJsonString(t,r){return(new He).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(He,t,r)}static $(){return["KnowledgeBaseResult|1 success 8|2 confirmation_message 9|3 id 9"]}}class We extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new We).fromBinary(t,r)}static fromJson(t,r){return(new We).fromJson(t,r)}static fromJsonString(t,r){return(new We).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(We,t,r)}static $(){return["KnowledgeBaseStream"]}}class Qe extends w{constructor(t){super(),this.pullNumberOrCommitHash="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qe).fromBinary(t,r)}static fromJson(t,r){return(new Qe).fromJson(t,r)}static fromJsonString(t,r){return(new Qe).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qe,t,r)}static $(){return["FetchPullRequestParams|1 pull_number_or_commit_hash 9|2 repo 9?|3 is_github 8?"]}}class Ve extends w{constructor(t){super(),this.content="",this.prNumber=0,this.title="",this.body="",this.author="",this.date="",this.diff="",this.comments=[],this.labels=[],this.assignees=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ve).fromBinary(t,r)}static fromJson(t,r){return(new Ve).fromJson(t,r)}static fromJsonString(t,r){return(new Ve).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ve,t,r)}static $(){return["FetchPullRequestResult|1 content 9|2 pr_number 13|3 title 9|4 body 9|5 author 9|6 date 9|7 diff 9|8 sha 9?|9 external_link 9?|10 url 9?|11 comments #0*|12 labels 9*|13 assignees 9*|14 is_issue 8?|15 state 9?|16 prompt_connect_github 8?",Xe]}}class Xe extends w{constructor(t){super(),this.id=0,this.body="",this.createdAt="",this.updatedAt="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xe).fromBinary(t,r)}static fromJson(t,r){return(new Xe).fromJson(t,r)}static fromJsonString(t,r){return(new Xe).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xe,t,r)}static $(){return["IssueComment|1 id 13|2 body 9|3 author 9?|4 created_at 9|5 updated_at 9|6 author_association 9?"]}}class Ye extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ye).fromBinary(t,r)}static fromJson(t,r){return(new Ye).fromJson(t,r)}static fromJsonString(t,r){return(new Ye).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ye,t,r)}static $(){return["FetchPullRequestStream"]}}class Ze extends w{constructor(t){super(),this.sha="",this.score=0,this.changedFiles=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ze).fromBinary(t,r)}static fromJson(t,r){return(new Ze).fromJson(t,r)}static fromJsonString(t,r){return(new Ze).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ze,t,r)}static $(){return["PullRequestReference|1 sha 9|2 score 2|3 title 9?|4 summary 9?|5 pr_number 13?|6 author 9?|7 date 9?|8 changed_files 9*"]}}class tn extends w{constructor(t){super(),this.query="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tn).fromBinary(t,r)}static fromJson(t,r){return(new tn).fromJson(t,r)}static fromJsonString(t,r){return(new tn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tn,t,r)}static $(){return["DeepSearchParams|1 query 9"]}}class rn extends w{constructor(t){super(),this.success=!1,this.result="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rn).fromBinary(t,r)}static fromJson(t,r){return(new rn).fromJson(t,r)}static fromJsonString(t,r){return(new rn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rn,t,r)}static $(){return["DeepSearchResult|1 success 8|2 result 9"]}}class en extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new en).fromBinary(t,r)}static fromJson(t,r){return(new en).fromJson(t,r)}static fromJsonString(t,r){return(new en).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(en,t,r)}static $(){return["DeepSearchStream"]}}class nn extends w{constructor(t){super(),this.content="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nn).fromBinary(t,r)}static fromJson(t,r){return(new nn).fromJson(t,r)}static fromJsonString(t,r){return(new nn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nn,t,r)}static $(){return["CreateDiagramParams|1 content 9"]}}class sn extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new sn).fromBinary(t,r)}static fromJson(t,r){return(new sn).fromJson(t,r)}static fromJsonString(t,r){return(new sn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(sn,t,r)}static $(){return["CreateDiagramResult|1 error 9?"]}}class on extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new on).fromBinary(t,r)}static fromJson(t,r){return(new on).fromJson(t,r)}static fromJsonString(t,r){return(new on).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(on,t,r)}static $(){return["CreateDiagramStream"]}}class an extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new an).fromBinary(t,r)}static fromJson(t,r){return(new an).fromJson(t,r)}static fromJsonString(t,r){return(new an).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(an,t,r)}static $(){return["FixLintsParams"]}}class un extends w{constructor(t){super(),this.fileResults=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new un).fromBinary(t,r)}static fromJson(t,r){return(new un).fromJson(t,r)}static fromJsonString(t,r){return(new un).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(un,t,r)}static $(){return["FixLintsResult|1 file_results #0*",cn]}}class cn extends w{constructor(t){super(),this.filePath="",this.isApplied=!1,this.applyFailed=!1,this.linterErrors=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cn).fromBinary(t,r)}static fromJson(t,r){return(new cn).fromJson(t,r)}static fromJsonString(t,r){return(new cn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cn,t,r)}static $(){return["FixLintsResult.FileResult|1 file_path 9|2 diff #0|3 is_applied 8|4 apply_failed 8|5 error 9?|6 linter_errors #1*",W,s.bO]}}class ln extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ln).fromBinary(t,r)}static fromJson(t,r){return(new ln).fromJson(t,r)}static fromJsonString(t,r){return(new ln).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ln,t,r)}static $(){return["FixLintsStream"]}}class mn extends w{constructor(t){super(),this.path="",this.paths=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mn).fromBinary(t,r)}static fromJson(t,r){return(new mn).fromJson(t,r)}static fromJsonString(t,r){return(new mn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mn,t,r)}static $(){return["ReadLintsParams|1 path 9|2 paths 9*"]}}class fn extends w{constructor(t){super(),this.path="",this.linterErrors=[],this.linterErrorsByFile=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fn).fromBinary(t,r)}static fromJson(t,r){return(new fn).fromJson(t,r)}static fromJsonString(t,r){return(new fn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fn,t,r)}static $(){return["ReadLintsResult|1 path 9|2 linter_errors #0*|3 linter_errors_by_file #1*",s.bO,s.wZ]}}class dn extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dn).fromBinary(t,r)}static fromJson(t,r){return(new dn).fromJson(t,r)}static fromJsonString(t,r){return(new dn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dn,t,r)}static $(){return["ReadLintsStream"]}}class pn extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pn).fromBinary(t,r)}static fromJson(t,r){return(new pn).fromJson(t,r)}static fromJsonString(t,r){return(new pn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pn,t,r)}static $(){return["GotodefStream"]}}class hn extends w{constructor(t){super(),this.taskDescription="",this.taskTitle="",this.allowedWriteDirectories=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hn).fromBinary(t,r)}static fromJson(t,r){return(new hn).fromJson(t,r)}static fromJsonString(t,r){return(new hn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hn,t,r)}static $(){return["TaskParams|1 task_description 9|4 task_title 9|2 async 8?|3 allowed_write_directories 9*|5 model_override 9?|6 max_mode_override 8?|7 default_expanded_while_running 8?"]}}class gn extends w{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gn).fromBinary(t,r)}static fromJson(t,r){return(new gn).fromJson(t,r)}static fromJsonString(t,r){return(new gn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gn,t,r)}static $(){return["TaskResult|1 completed_task_result #0 result|2 async_task_result #1 result",_n,Jn]}}class _n extends w{constructor(t){super(),this.summary="",this.fileResults=[],this.userAborted=!1,this.subagentErrored=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _n).fromBinary(t,r)}static fromJson(t,r){return(new _n).fromJson(t,r)}static fromJsonString(t,r){return(new _n).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_n,t,r)}static $(){return["TaskResult.CompletedTaskResult|1 summary 9|2 file_results #0*|3 user_aborted 8|4 subagent_errored 8",cn]}}class Jn extends w{constructor(t){super(),this.taskId="",this.userAborted=!1,this.subagentErrored=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jn).fromBinary(t,r)}static fromJson(t,r){return(new Jn).fromJson(t,r)}static fromJsonString(t,r){return(new Jn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jn,t,r)}static $(){return["TaskResult.AsyncTaskResult|1 task_id 9|2 user_aborted 8|3 subagent_errored 8"]}}class wn extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wn).fromBinary(t,r)}static fromJson(t,r){return(new wn).fromJson(t,r)}static fromJsonString(t,r){return(new wn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wn,t,r)}static $(){return["TaskStream"]}}class yn extends w{constructor(t){super(),this.description="",this.prompt="",this.subagentType="",this.name="",this.mode=d.FL.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yn).fromBinary(t,r)}static fromJson(t,r){return(new yn).fromJson(t,r)}static fromJsonString(t,r){return(new yn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yn,t,r)}static $(){return["TaskV2Params|1 description 9|2 prompt 9|3 subagent_type 9|4 model 9?|5 name 9|6 mode #0",d.FL]}}class Sn extends w{constructor(t){super(),this.isBackground=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Sn).fromBinary(t,r)}static fromJson(t,r){return(new Sn).fromJson(t,r)}static fromJsonString(t,r){return(new Sn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Sn,t,r)}static $(){return["TaskV2Result|1 agent_id 9?|2 is_background 8|3 cloud_agent_bc_id 9?"]}}class qn extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qn).fromBinary(t,r)}static fromJson(t,r){return(new qn).fromJson(t,r)}static fromJsonString(t,r){return(new qn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qn,t,r)}static $(){return["TaskV2Stream"]}}class Bn extends w{constructor(t){super(),this.pattern="",this.ignoreGlobs=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bn).fromBinary(t,r)}static fromJson(t,r){return(new Bn).fromJson(t,r)}static fromJsonString(t,r){return(new Bn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bn,t,r)}static $(){return["RipgrepRawSearchParams|1 pattern 9|2 path 9?|3 glob 9?|4 output_mode 9?|5 context_before 5?|6 context_after 5?|7 context 5?|8 case_insensitive 8?|9 type 9?|10 head_limit 5?|11 multiline 8?|12 sort 9?|13 sort_ascending 8?|14 ignore_globs 9*|15 offset 5?"]}}class In extends w{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new In).fromBinary(t,r)}static fromJson(t,r){return(new In).fromJson(t,r)}static fromJsonString(t,r){return(new In).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(In,t,r)}static $(){return["RipgrepRawSearchResult|1 success #0 result|2 error #1 result",bn,Pn]}}class Pn extends w{constructor(t){super(),this.error="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pn).fromBinary(t,r)}static fromJson(t,r){return(new Pn).fromJson(t,r)}static fromJsonString(t,r){return(new Pn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pn,t,r)}static $(){return["RipgrepRawSearchError|1 error 9"]}}class bn extends w{constructor(t){super(),this.pattern="",this.path="",this.outputMode="",this.workspaceResults={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bn).fromBinary(t,r)}static fromJson(t,r){return(new bn).fromJson(t,r)}static fromJsonString(t,r){return(new bn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bn,t,r)}static $(){return["RipgrepRawSearchSuccess|1 pattern 9|2 path 9|3 output_mode 9|4 workspace_results 9,#0|5 active_editor_result #0?",Rn]}}class Rn extends w{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rn).fromBinary(t,r)}static fromJson(t,r){return(new Rn).fromJson(t,r)}static fromJsonString(t,r){return(new Rn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rn,t,r)}static $(){return["RipgrepRawSearchUnionResult|1 count #0 result|2 files #1 result|3 content #2 result",vn,kn,Cn]}}class vn extends w{constructor(t){super(),this.counts=[],this.totalFiles=0,this.totalMatches=0,this.clientTruncated=!1,this.ripgrepTruncated=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vn).fromBinary(t,r)}static fromJson(t,r){return(new vn).fromJson(t,r)}static fromJsonString(t,r){return(new vn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vn,t,r)}static $(){return["RipgrepRawSearchCountResult|1 counts #0*|2 total_files 5|3 total_matches 5|4 client_truncated 8|6 head_limit_applied 5?|7 offset_applied 5?|5 ripgrep_truncated 8",xn]}}class xn extends w{constructor(t){super(),this.file="",this.count=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xn).fromBinary(t,r)}static fromJson(t,r){return(new xn).fromJson(t,r)}static fromJsonString(t,r){return(new xn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xn,t,r)}static $(){return["RipgrepRawSearchFileCount|1 file 9|2 count 5|3 is_dirty 8?|4 is_out_of_workspace 8?|5 absolute_path 9?"]}}class kn extends w{constructor(t){super(),this.files=[],this.totalFiles=0,this.clientTruncated=!1,this.ripgrepTruncated=!1,this.filesWithMeta=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kn).fromBinary(t,r)}static fromJson(t,r){return(new kn).fromJson(t,r)}static fromJsonString(t,r){return(new kn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kn,t,r)}static $(){return["RipgrepRawSearchFilesResult|1 files 9*|2 total_files 5|3 client_truncated 8|4 ripgrep_truncated 8|5 files_with_meta #0*|6 head_limit_applied 5?|7 offset_applied 5?",En]}}class En extends w{constructor(t){super(),this.file="",this.isDirty=!1,this.isOutOfWorkspace=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new En).fromBinary(t,r)}static fromJson(t,r){return(new En).fromJson(t,r)}static fromJsonString(t,r){return(new En).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(En,t,r)}static $(){return["RipgrepRawSearchFilesResult.FileEntry|1 file 9|2 is_dirty 8|3 is_out_of_workspace 8|4 absolute_path 9?"]}}class Cn extends w{constructor(t){super(),this.matches=[],this.totalLines=0,this.totalMatchedLines=0,this.clientTruncated=!1,this.ripgrepTruncated=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cn).fromBinary(t,r)}static fromJson(t,r){return(new Cn).fromJson(t,r)}static fromJsonString(t,r){return(new Cn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cn,t,r)}static $(){return["RipgrepRawSearchContentResult|1 matches #0*|2 total_lines 5|3 total_matched_lines 5|4 client_truncated 8|5 ripgrep_truncated 8|6 head_limit_applied 5?|7 offset_applied 5?",Tn]}}class Tn extends w{constructor(t){super(),this.file="",this.matches=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tn).fromBinary(t,r)}static fromJson(t,r){return(new Tn).fromJson(t,r)}static fromJsonString(t,r){return(new Tn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tn,t,r)}static $(){return["RipgrepRawSearchFileMatch|1 file 9|2 matches #0*|3 is_dirty 8?|4 is_out_of_workspace 8?|5 absolute_path 9?",Un]}}class Un extends w{constructor(t){super(),this.lineNumber=0,this.content="",this.contentTruncated=!1,this.isContextLine=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Un).fromBinary(t,r)}static fromJson(t,r){return(new Un).fromJson(t,r)}static fromJsonString(t,r){return(new Un).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Un,t,r)}static $(){return["RipgrepRawSearchContentMatch|1 line_number 5|2 content 9|3 content_truncated 8|4 is_context_line 8"]}}class An extends w{constructor(t){super(),this.pattern="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new An).fromBinary(t,r)}static fromJson(t,r){return(new An).fromJson(t,r)}static fromJsonString(t,r){return(new An).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(An,t,r)}static $(){return["RipgrepRawSearchStream|1 pattern 9"]}}class $n extends w{constructor(t){super(),this.ids=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $n).fromBinary(t,r)}static fromJson(t,r){return(new $n).fromJson(t,r)}static fromJsonString(t,r){return(new $n).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($n,t,r)}static $(){return["AwaitTaskParams|1 ids 9*"]}}class Mn extends w{constructor(t){super(),this.taskResults=[],this.missingTaskIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mn).fromBinary(t,r)}static fromJson(t,r){return(new Mn).fromJson(t,r)}static fromJsonString(t,r){return(new Mn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mn,t,r)}static $(){return["AwaitTaskResult|1 task_results #0*|2 missing_task_ids 9*",On]}}class On extends w{constructor(t){super(),this.taskId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new On).fromBinary(t,r)}static fromJson(t,r){return(new On).fromJson(t,r)}static fromJsonString(t,r){return(new On).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(On,t,r)}static $(){return["AwaitTaskResult.TaskResultItem|1 task_id 9|2 result #0",_n]}}class Dn extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dn).fromBinary(t,r)}static fromJson(t,r){return(new Dn).fromJson(t,r)}static fromJsonString(t,r){return(new Dn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dn,t,r)}static $(){return["AwaitTaskStream"]}}class Nn extends w{constructor(t){super(),this.read=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Nn).fromBinary(t,r)}static fromJson(t,r){return(new Nn).fromJson(t,r)}static fromJsonString(t,r){return(new Nn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Nn,t,r)}static $(){return["TodoReadParams|1 read 8"]}}class Gn extends w{constructor(t){super(),this.content="",this.status="",this.id="",this.dependencies=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gn).fromBinary(t,r)}static fromJson(t,r){return(new Gn).fromJson(t,r)}static fromJsonString(t,r){return(new Gn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gn,t,r)}static $(){return["TodoItem|1 content 9|2 status 9|3 id 9|4 dependencies 9*"]}}class Ln extends w{constructor(t){super(),this.todos=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ln).fromBinary(t,r)}static fromJson(t,r){return(new Ln).fromJson(t,r)}static fromJsonString(t,r){return(new Ln).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ln,t,r)}static $(){return["TodoReadResult|1 todos #0*",Gn]}}class Fn extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fn).fromBinary(t,r)}static fromJson(t,r){return(new Fn).fromJson(t,r)}static fromJsonString(t,r){return(new Fn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fn,t,r)}static $(){return["TodoReadStream"]}}class Kn extends w{constructor(t){super(),this.todos=[],this.merge=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Kn).fromBinary(t,r)}static fromJson(t,r){return(new Kn).fromJson(t,r)}static fromJsonString(t,r){return(new Kn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Kn,t,r)}static $(){return["TodoWriteParams|1 todos #0*|2 merge 8",Gn]}}class zn extends w{constructor(t){super(),this.success=!1,this.readyTaskIds=[],this.needsInProgressTodos=!1,this.finalTodos=[],this.initialTodos=[],this.wasMerge=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zn).fromBinary(t,r)}static fromJson(t,r){return(new zn).fromJson(t,r)}static fromJsonString(t,r){return(new zn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zn,t,r)}static $(){return["TodoWriteResult|1 success 8|2 ready_task_ids 9*|3 needs_in_progress_todos 8|4 final_todos #0*|5 initial_todos #0*|6 was_merge 8",Gn]}}class jn extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new jn).fromBinary(t,r)}static fromJson(t,r){return(new jn).fromJson(t,r)}static fromJsonString(t,r){return(new jn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(jn,t,r)}static $(){return["TodoWriteStream"]}}class Hn extends w{constructor(t){super(),this.targetDirectory="",this.ignoreGlobs=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hn).fromBinary(t,r)}static fromJson(t,r){return(new Hn).fromJson(t,r)}static fromJsonString(t,r){return(new Hn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hn,t,r)}static $(){return["ListDirV2Params|1 target_directory 9|2 ignore_globs 9*|3 should_enrich_terminal_metadata 8?"]}}class Wn extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Wn).fromBinary(t,r)}static fromJson(t,r){return(new Wn).fromJson(t,r)}static fromJsonString(t,r){return(new Wn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Wn,t,r)}static $(){return["ListDirV2Result|1 directory_tree_root #0",Qn]}}class Qn extends w{constructor(t){super(),this.absPath="",this.childrenDirs=[],this.childrenFiles=[],this.childrenWereProcessed=!1,this.fullSubtreeExtensionCounts={},this.numFiles=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qn).fromBinary(t,r)}static fromJson(t,r){return(new Qn).fromJson(t,r)}static fromJsonString(t,r){return(new Qn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qn,t,r)}static $(){return["ListDirV2Result.DirectoryTreeNode|1 abs_path 9|2 children_dirs #0*|3 children_files #1*|4 children_were_processed 8|5 full_subtree_extension_counts 9,5|6 num_files 5",Qn,Vn]}}class Vn extends w{constructor(t){super(),this.name="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vn).fromBinary(t,r)}static fromJson(t,r){return(new Vn).fromJson(t,r)}static fromJsonString(t,r){return(new Vn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vn,t,r)}static $(){return["ListDirV2Result.DirectoryTreeNode.File|1 name 9|2 terminal_metadata #0?",p.Y$]}}class Xn extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Xn).fromBinary(t,r)}static fromJson(t,r){return(new Xn).fromJson(t,r)}static fromJsonString(t,r){return(new Xn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Xn,t,r)}static $(){return["ListDirV2Stream"]}}class Yn extends w{constructor(t){super(),this.targetFile="",this.charsLimit=0,this.effectiveUri="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Yn).fromBinary(t,r)}static fromJson(t,r){return(new Yn).fromJson(t,r)}static fromJsonString(t,r){return(new Yn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Yn,t,r)}static $(){return["ReadFileV2Params|1 target_file 9|2 offset 5?|3 limit 5?|4 chars_limit 5|5 effective_uri 9|6 enable_line_numbers 8?"]}}class Zn extends w{constructor(t){super(),this.numCharactersInRequestedRange=0,this.matchingCursorRules=[],this.images=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Zn).fromBinary(t,r)}static fromJson(t,r){return(new Zn).fromJson(t,r)}static fromJsonString(t,r){return(new Zn).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Zn,t,r)}static $(){return["ReadFileV2Result|1 contents 9?|2 num_characters_in_requested_range 5|3 offset_is_bigger_than_number_of_lines_in_file 8?|4 total_lines_in_file 5?|5 matching_cursor_rules #0*|6 images #1*",s.DX,s.UR]}}class ts extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ts).fromBinary(t,r)}static fromJson(t,r){return(new ts).fromJson(t,r)}static fromJsonString(t,r){return(new ts).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ts,t,r)}static $(){return["ReadFileV2Stream|1 params #0?",Yn]}}class rs extends w{constructor(t){super(),this.targetDirectory="",this.globPattern="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rs).fromBinary(t,r)}static fromJson(t,r){return(new rs).fromJson(t,r)}static fromJsonString(t,r){return(new rs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rs,t,r)}static $(){return["GlobFileSearchParams|1 target_directory 9|2 glob_pattern 9"]}}class es extends w{constructor(t){super(),this.directories=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new es).fromBinary(t,r)}static fromJson(t,r){return(new es).fromJson(t,r)}static fromJsonString(t,r){return(new es).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(es,t,r)}static $(){return["GlobFileSearchResult|1 directories #0*",ss]}}class ns extends w{constructor(t){super(),this.relPath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ns).fromBinary(t,r)}static fromJson(t,r){return(new ns).fromJson(t,r)}static fromJsonString(t,r){return(new ns).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ns,t,r)}static $(){return["GlobFileSearchResult.File|1 rel_path 9"]}}class ss extends w{constructor(t){super(),this.absPath="",this.files=[],this.totalFiles=0,this.ripgrepTruncated=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ss).fromBinary(t,r)}static fromJson(t,r){return(new ss).fromJson(t,r)}static fromJsonString(t,r){return(new ss).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ss,t,r)}static $(){return["GlobFileSearchResult.Directory|1 abs_path 9|2 files #0*|3 total_files 5|4 ripgrep_truncated 8",ns]}}class is extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new is).fromBinary(t,r)}static fromJson(t,r){return(new is).fromJson(t,r)}static fromJsonString(t,r){return(new is).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(is,t,r)}static $(){return["GlobFileSearchStream"]}}class os extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new os).fromBinary(t,r)}static fromJson(t,r){return(new os).fromJson(t,r)}static fromJsonString(t,r){return(new os).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(os,t,r)}static $(){return["ListMcpResourcesStream"]}}class as extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new as).fromBinary(t,r)}static fromJson(t,r){return(new as).fromJson(t,r)}static fromJsonString(t,r){return(new as).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(as,t,r)}static $(){return["CallMcpToolStream"]}}class us extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new us).fromBinary(t,r)}static fromJson(t,r){return(new us).fromJson(t,r)}static fromJsonString(t,r){return(new us).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(us,t,r)}static $(){return["ReadMcpResourceStream"]}}class cs extends w{constructor(t){super(),this.id="",this.title="",this.description="",this.instructions="",this.prerequisites=[],this.subComposerId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new cs).fromBinary(t,r)}static fromJson(t,r){return(new cs).fromJson(t,r)}static fromJsonString(t,r){return(new cs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(cs,t,r)}static $(){return["Step|1 id 9|2 title 9|3 description 9|4 instructions 9|5 prerequisites 9*|6 sub_composer_id 9"]}}class ls extends w{constructor(t){super(),this.name="",this.todos=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ls).fromBinary(t,r)}static fromJson(t,r){return(new ls).fromJson(t,r)}static fromJsonString(t,r){return(new ls).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ls,t,r)}static $(){return["PlanPhase|1 name 9|2 todos #0*",Gn]}}class ms extends w{constructor(t){super(),this.plan="",this.title="",this.summary="",this.steps=[],this.oldStr="",this.newStr="",this.name="",this.todos=[],this.overview="",this.isSpec=!1,this.isProject=!1,this.phases=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ms).fromBinary(t,r)}static fromJson(t,r){return(new ms).fromJson(t,r)}static fromJsonString(t,r){return(new ms).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ms,t,r)}static $(){return["CreatePlanParams|1 plan 9|2 title 9|3 summary 9|4 steps #0*|5 old_str 9|6 new_str 9|7 name 9|8 todos #1*|9 overview 9|10 is_spec 8|11 is_project 8|12 phases #2*",cs,Gn,ls]}}class fs extends w{constructor(t){super(),this.result={case:void 0},this.planUri="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new fs).fromBinary(t,r)}static fromJson(t,r){return(new fs).fromJson(t,r)}static fromJsonString(t,r){return(new fs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(fs,t,r)}static $(){return["CreatePlanResult|1 accepted #0 result|2 rejected #1 result|3 modified #2 result|4 plan_uri 9",ds,ps,hs]}}class ds extends w{constructor(t){super(),this.finalTodos=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ds).fromBinary(t,r)}static fromJson(t,r){return(new ds).fromJson(t,r)}static fromJsonString(t,r){return(new ds).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ds,t,r)}static $(){return["CreatePlanResult.Accepted|1 final_todos #0*",Gn]}}class ps extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ps).fromBinary(t,r)}static fromJson(t,r){return(new ps).fromJson(t,r)}static fromJsonString(t,r){return(new ps).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ps,t,r)}static $(){return["CreatePlanResult.Rejected"]}}class hs extends w{constructor(t){super(),this.newPlan="",this.finalTodos=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new hs).fromBinary(t,r)}static fromJson(t,r){return(new hs).fromJson(t,r)}static fromJsonString(t,r){return(new hs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(hs,t,r)}static $(){return["CreatePlanResult.Modified|1 new_plan 9|2 final_todos #0*",Gn]}}class gs extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gs).fromBinary(t,r)}static fromJson(t,r){return(new gs).fromJson(t,r)}static fromJsonString(t,r){return(new gs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gs,t,r)}static $(){return["CreatePlanStream"]}}class _s extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _s).fromBinary(t,r)}static fromJson(t,r){return(new _s).fromJson(t,r)}static fromJsonString(t,r){return(new _s).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_s,t,r)}static $(){return["ReadProjectParams"]}}class Js extends w{constructor(t){super(),this.plan="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Js).fromBinary(t,r)}static fromJson(t,r){return(new Js).fromJson(t,r)}static fromJsonString(t,r){return(new Js).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Js,t,r)}static $(){return["ReadProjectResult|1 plan 9"]}}class ws extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ws).fromBinary(t,r)}static fromJson(t,r){return(new ws).fromJson(t,r)}static fromJsonString(t,r){return(new ws).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ws,t,r)}static $(){return["ReadProjectStream"]}}class ys extends w{constructor(t){super(),this.oldString="",this.newString="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ys).fromBinary(t,r)}static fromJson(t,r){return(new ys).fromJson(t,r)}static fromJsonString(t,r){return(new ys).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ys,t,r)}static $(){return["UpdateProjectStringReplacement|1 old_string 9|2 new_string 9"]}}class Ss extends w{constructor(t){super(),this.stringReplacements=[],this.summary="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ss).fromBinary(t,r)}static fromJson(t,r){return(new Ss).fromJson(t,r)}static fromJsonString(t,r){return(new Ss).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ss,t,r)}static $(){return["UpdateProjectParams|1 string_replacements #0*|2 summary 9",ys]}}class qs extends w{constructor(t){super(),this.success=!1,this.updatedPlan="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qs).fromBinary(t,r)}static fromJson(t,r){return(new qs).fromJson(t,r)}static fromJsonString(t,r){return(new qs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qs,t,r)}static $(){return["UpdateProjectResult|1 success 8|2 updated_plan 9"]}}class Bs extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bs).fromBinary(t,r)}static fromJson(t,r){return(new Bs).fromJson(t,r)}static fromJsonString(t,r){return(new Bs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bs,t,r)}static $(){return["UpdateProjectStream"]}}class Is extends w{constructor(t){super(),this.title="",this.questions=[],this.runAsync=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Is).fromBinary(t,r)}static fromJson(t,r){return(new Is).fromJson(t,r)}static fromJsonString(t,r){return(new Is).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Is,t,r)}static $(){return["AskQuestionParams|1 title 9|2 questions #0*|3 run_async 8",Ps]}}class Ps extends w{constructor(t){super(),this.id="",this.prompt="",this.options=[],this.allowMultiple=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ps).fromBinary(t,r)}static fromJson(t,r){return(new Ps).fromJson(t,r)}static fromJsonString(t,r){return(new Ps).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ps,t,r)}static $(){return["AskQuestionParams.Question|1 id 9|2 prompt 9|3 options #0*|4 allow_multiple 8|5 prompt_markdown 9?",bs]}}class bs extends w{constructor(t){super(),this.id="",this.label="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bs).fromBinary(t,r)}static fromJson(t,r){return(new bs).fromJson(t,r)}static fromJsonString(t,r){return(new bs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bs,t,r)}static $(){return["AskQuestionParams.Option|1 id 9|2 label 9"]}}class Rs extends w{constructor(t){super(),this.answers=[],this.isAsync=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rs).fromBinary(t,r)}static fromJson(t,r){return(new Rs).fromJson(t,r)}static fromJsonString(t,r){return(new Rs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rs,t,r)}static $(){return["AskQuestionResult|1 answers #0*|2 is_async 8",vs]}}class vs extends w{constructor(t){super(),this.questionId="",this.selectedOptionIds=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vs).fromBinary(t,r)}static fromJson(t,r){return(new vs).fromJson(t,r)}static fromJsonString(t,r){return(new vs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vs,t,r)}static $(){return["AskQuestionResult.Answer|1 question_id 9|2 selected_option_ids 9*|3 freeform_text 9?"]}}class xs extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xs).fromBinary(t,r)}static fromJson(t,r){return(new xs).fromJson(t,r)}static fromJsonString(t,r){return(new xs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xs,t,r)}static $(){return["AskQuestionStream|1 params #0",Is]}}class ks extends w{constructor(t){super(),this.fromModeId="",this.toModeId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ks).fromBinary(t,r)}static fromJson(t,r){return(new ks).fromJson(t,r)}static fromJsonString(t,r){return(new ks).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ks,t,r)}static $(){return["SwitchModeParams|1 from_mode_id 9|2 to_mode_id 9|3 explanation 9?"]}}class Es extends w{constructor(t){super(),this.fromModeId="",this.toModeId="",this.autoApproved=!1,this.userApproved=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Es).fromBinary(t,r)}static fromJson(t,r){return(new Es).fromJson(t,r)}static fromJsonString(t,r){return(new Es).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Es,t,r)}static $(){return["SwitchModeResult|1 from_mode_id 9|2 to_mode_id 9|3 auto_approved 8|4 user_approved 8"]}}class Cs extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Cs).fromBinary(t,r)}static fromJson(t,r){return(new Cs).fromJson(t,r)}static fromJsonString(t,r){return(new Cs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Cs,t,r)}static $(){return["SwitchModeStream|1 params #0",ks]}}class Ts extends w{constructor(t){super(),this.actions=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ts).fromBinary(t,r)}static fromJson(t,r){return(new Ts).fromJson(t,r)}static fromJsonString(t,r){return(new Ts).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ts,t,r)}static $(){return["ComputerUseParams|1 actions #0*",h.ho]}}class Us extends w{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Us).fromBinary(t,r)}static fromJson(t,r){return(new Us).fromJson(t,r)}static fromJsonString(t,r){return(new Us).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Us,t,r)}static $(){return["ComputerUseResult|1 success #0 result|2 error #1 result",h.Wd,h.Jb]}}class As extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new As).fromBinary(t,r)}static fromJson(t,r){return(new As).fromJson(t,r)}static fromJsonString(t,r){return(new As).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(As,t,r)}static $(){return["ComputerUseStream|1 params #0",Ts]}}class $s extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $s).fromBinary(t,r)}static fromJson(t,r){return(new $s).fromJson(t,r)}static fromJsonString(t,r){return(new $s).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($s,t,r)}static $(){return["WriteShellStdinStream|1 params #0",i.LL]}}class Ms extends w{constructor(t){super(),this.url="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ms).fromBinary(t,r)}static fromJson(t,r){return(new Ms).fromJson(t,r)}static fromJsonString(t,r){return(new Ms).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ms,t,r)}static $(){return["WebFetchParams|1 url 9"]}}class Os extends w{constructor(t){super(),this.url="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Os).fromBinary(t,r)}static fromJson(t,r){return(new Os).fromJson(t,r)}static fromJsonString(t,r){return(new Os).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Os,t,r)}static $(){return["WebFetchResult|1 url 9|2 markdown 9?|3 error 9?"]}}class Ds extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ds).fromBinary(t,r)}static fromJson(t,r){return(new Ds).fromJson(t,r)}static fromJsonString(t,r){return(new Ds).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ds,t,r)}static $(){return["WebFetchStream|1 params #0",Ms]}}class Ns extends w{constructor(t){super(),this.summary="",this.results=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ns).fromBinary(t,r)}static fromJson(t,r){return(new Ns).fromJson(t,r)}static fromJsonString(t,r){return(new Ns).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ns,t,r)}static $(){return["ReportBugfixResultsParams|1 summary 9|2 results #0*",g.Y6]}}class Gs extends w{constructor(t){super(),this.result={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Gs).fromBinary(t,r)}static fromJson(t,r){return(new Gs).fromJson(t,r)}static fromJsonString(t,r){return(new Gs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Gs,t,r)}static $(){return["ReportBugfixResultsResult|1 success #0 result|2 error #1 result",g.RH,g.q3]}}class Ls extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ls).fromBinary(t,r)}static fromJson(t,r){return(new Ls).fromJson(t,r)}static fromJsonString(t,r){return(new Ls).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ls,t,r)}static $(){return["ReportBugfixResultsStream|1 params #0",Ns]}}class Fs extends w{constructor(t){super(),this.serverIdentifier="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Fs).fromBinary(t,r)}static fromJson(t,r){return(new Fs).fromJson(t,r)}static fromJsonString(t,r){return(new Fs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Fs,t,r)}static $(){return["McpAuthParams|1 server_identifier 9"]}}class Ks extends w{constructor(t){super(),this.success=!1,this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ks).fromBinary(t,r)}static fromJson(t,r){return(new Ks).fromJson(t,r)}static fromJsonString(t,r){return(new Ks).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ks,t,r)}static $(){return["McpAuthResult|1 success 8|2 message 9"]}}class zs extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new zs).fromBinary(t,r)}static fromJson(t,r){return(new zs).fromJson(t,r)}static fromJsonString(t,r){return(new zs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(zs,t,r)}static $(){return["McpAuthStream"]}}class js extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new js).fromBinary(t,r)}static fromJson(t,r){return(new js).fromJson(t,r)}static fromJsonString(t,r){return(new js).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(js,t,r)}static $(){return["ConnectScmParams|1 github #0|2 provider 9?|3 provider_instance 9?|4 reconnect 8?|5 instance_host 9?",Hs]}}class Hs extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Hs).fromBinary(t,r)}static fromJson(t,r){return(new Hs).fromJson(t,r)}static fromJsonString(t,r){return(new Hs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Hs,t,r)}static $(){return["ConnectScmGithub|1 repository #0|2 ghe_application 9?",Ws]}}class Ws extends w{constructor(t){super(),this.owner="",this.repo="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ws).fromBinary(t,r)}static fromJson(t,r){return(new Ws).fromJson(t,r)}static fromJsonString(t,r){return(new Ws).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ws,t,r)}static $(){return["ConnectScmGithubRepository|1 owner 9|2 repo 9"]}}class Qs extends w{constructor(t){super(),this.success=!1,this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Qs).fromBinary(t,r)}static fromJson(t,r){return(new Qs).fromJson(t,r)}static fromJsonString(t,r){return(new Qs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Qs,t,r)}static $(){return["ConnectScmResult|1 success 8|2 message 9"]}}class Vs extends w{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Vs).fromBinary(t,r)}static fromJson(t,r){return(new Vs).fromJson(t,r)}static fromJsonString(t,r){return(new Vs).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Vs,t,r)}static $(){return["ConnectScmStream"]}}},"../proto/dist/generated/aiserver/v1/usage_pb.js"(t,r,e){e.d(r,{GF:()=>R,aq:()=>b,kK:()=>l});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");const i="aiserver.v1.";class o extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return i}}var a=(0,s.QT)(n.proto3,i,"UsageEventKind",[[0,"UNSPECIFIED"],[1,"USAGE_BASED"],[2,"USER_API_KEY"],[3,"INCLUDED_IN_PRO"],[4,"INCLUDED_IN_BUSINESS"],[5,"ERRORED_NOT_CHARGED"],[6,"ABORTED_NOT_CHARGED"],[7,"CUSTOM_SUBSCRIPTION"],[8,"INCLUDED_IN_PRO_PLUS"],[9,"INCLUDED_IN_ULTRA"],[10,"FREE_CREDIT"]],1);class u extends o{constructor(t){super(),this.modelId="",this.maxMode=!1,this.parameters=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new u).fromBinary(t,r)}static fromJson(t,r){return(new u).fromJson(t,r)}static fromJsonString(t,r){return(new u).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(u,t,r)}static $(){return["ModelSelectionSnapshot|1 model_id 9|2 max_mode 8|3 parameters #0*",c]}}class c extends o{constructor(t){super(),this.id="",this.value="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new c).fromBinary(t,r)}static fromJson(t,r){return(new c).fromJson(t,r)}static fromJsonString(t,r){return(new c).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(c,t,r)}static $(){return["ModelSelectionSnapshot.ModelParameterValue|1 id 9|2 value 9"]}}class l extends o{constructor(t){super(),this.feature={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["UsageEventDetails|1 chat #0 feature|2 context_chat #1 feature|3 cmd_k #2 feature|4 terminal_cmd_k #3 feature|5 ai_review_accepted_comment #4 feature|6 interpreter_chat #5 feature|7 slash_edit #6 feature|8 composer #7 feature|9 fast_apply #8 feature|10 warm_composer #9 feature|11 bug_finder_trigger_v1 #10 feature|12 tool_call_composer #11 feature|14 bug_bot #12 feature|15 prompt_hook #13 feature|20 agent_sdk_managed #14?|13 override_num_requests_counted 5?|16 override_num_requests_counted_millis 5?|17 routed_model 9?|18 requested_model_selection #15?|19 effective_model_selection #15?",p,w,y,S,q,B,I,g,h,J,f,_,d,m,P,u]}}class m extends o{constructor(t){super(),this.modelIntent="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["UsageEventDetails.PromptHook|1 model_intent 9|2 token_usage #0?|3 max_mode 8?|4 is_token_based_call 8?",v]}}class f extends o{constructor(t){super(),this.inBackgroundSubsidized=!1,this.costCents=0,this.isFast=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["UsageEventDetails.BugFinderTriggerV1|1 in_background_subsidized 8|2 cost_cents 5|3 is_fast 8"]}}class d extends o{constructor(t){super(),this.modelIntent="",this.isTokenBasedCall=!1,this.maxMode=!1,this.discount={case:void 0},this.billingMode="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["UsageEventDetails.BugBot|1 model_intent 9|2 token_usage #0|3 is_token_based_call 8|4 max_mode 8|5 no_discount #1 discount|6 free #1 discount|7 billing_mode 9",v,n.Empty]}}class p extends o{constructor(t){super(),this.modelIntent="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["UsageEventDetails.Chat|1 model_intent 9|2 override_num_requests_counted 5?|3 is_token_based_call 8?|4 token_usage #0?|5 max_mode 8?",v]}}class h extends o{constructor(t){super(),this.isOptimistic=!1,this.willingToPayExtraForSpeed=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["UsageEventDetails.FastApply|1 is_optimistic 8|2 willing_to_pay_extra_for_speed 8"]}}class g extends o{constructor(t){super(),this.modelIntent="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["UsageEventDetails.Composer|1 model_intent 9|2 override_num_requests_counted 5?|3 is_headless 8?|4 is_token_based_call 8?|5 token_usage #0?|6 max_mode 8?",v]}}class _ extends o{constructor(t){super(),this.modelIntent="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _).fromBinary(t,r)}static fromJson(t,r){return(new _).fromJson(t,r)}static fromJsonString(t,r){return(new _).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_,t,r)}static $(){return["UsageEventDetails.ToolCallComposer|1 model_intent 9|2 override_num_requests_counted 5?|3 is_headless 8?|4 is_token_based_call 8?|5 token_usage #0?|6 max_mode 8?",v]}}class J extends o{constructor(t){super(),this.modelIntent="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new J).fromBinary(t,r)}static fromJson(t,r){return(new J).fromJson(t,r)}static fromJsonString(t,r){return(new J).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(J,t,r)}static $(){return["UsageEventDetails.WarmComposer|1 model_intent 9|2 max_mode 8?"]}}class w extends o{constructor(t){super(),this.modelIntent="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new w).fromBinary(t,r)}static fromJson(t,r){return(new w).fromJson(t,r)}static fromJsonString(t,r){return(new w).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(w,t,r)}static $(){return["UsageEventDetails.ContextChat|1 model_intent 9|2 override_num_requests_counted 5?|3 is_token_based_call 8?|4 token_usage #0?|5 max_mode 8?",v]}}class y extends o{constructor(t){super(),this.modelIntent="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new y).fromBinary(t,r)}static fromJson(t,r){return(new y).fromJson(t,r)}static fromJsonString(t,r){return(new y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(y,t,r)}static $(){return["UsageEventDetails.CmdK|1 model_intent 9|2 override_num_requests_counted 5?|3 is_token_based_call 8?|4 token_usage #0?|5 max_mode 8?",v]}}class S extends o{constructor(t){super(),this.modelIntent="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new S).fromBinary(t,r)}static fromJson(t,r){return(new S).fromJson(t,r)}static fromJsonString(t,r){return(new S).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(S,t,r)}static $(){return["UsageEventDetails.TerminalCmdK|1 model_intent 9|2 override_num_requests_counted 5?|3 is_token_based_call 8?|4 token_usage #0?|5 max_mode 8?",v]}}class q extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new q).fromBinary(t,r)}static fromJson(t,r){return(new q).fromJson(t,r)}static fromJsonString(t,r){return(new q).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(q,t,r)}static $(){return["UsageEventDetails.AiReviewAcceptedComment"]}}class B extends o{constructor(t){super(),this.modelIntent="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new B).fromBinary(t,r)}static fromJson(t,r){return(new B).fromJson(t,r)}static fromJsonString(t,r){return(new B).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(B,t,r)}static $(){return["UsageEventDetails.InterpreterChat|1 model_intent 9|2 override_num_requests_counted 5?|3 is_token_based_call 8?|4 token_usage #0?|5 max_mode 8?",v]}}class I extends o{constructor(t){super(),this.modelIntent="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new I).fromBinary(t,r)}static fromJson(t,r){return(new I).fromJson(t,r)}static fromJsonString(t,r){return(new I).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(I,t,r)}static $(){return["UsageEventDetails.SlashEdit|1 model_intent 9|2 max_mode 8?"]}}class P extends o{constructor(t){super(),this.managedType="",this.applicationSlug="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new P).fromBinary(t,r)}static fromJson(t,r){return(new P).fromJson(t,r)}static fromJsonString(t,r){return(new P).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(P,t,r)}static $(){return["UsageEventDetails.AgentSdkManagedProduct|1 managed_type 9|2 application_slug 9"]}}class b extends o{constructor(t){super(),this.timestamp=n.protoInt64.zero,this.isSlow=!1,this.status="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new b).fromBinary(t,r)}static fromJson(t,r){return(new b).fromJson(t,r)}static fromJsonString(t,r){return(new b).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(b,t,r)}static $(){return["UsageEvent|1 timestamp 3|2 details #0|3 subscription_product_id 9?|4 usage_price_id 9?|5 is_slow 8|6 status 9|7 owning_user 9?|8 owning_team 9?|9 price_cents 2?|10 team_membership_type 9?",l]}}class R extends o{constructor(t){super(),this.timestamp=n.protoInt64.zero,this.model="",this.kind=a.UNSPECIFIED,this.maxMode=!1,this.requestsCosts=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new R).fromBinary(t,r)}static fromJson(t,r){return(new R).fromJson(t,r)}static fromJsonString(t,r){return(new R).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(R,t,r)}static $(){return["UsageEventDisplay|1 timestamp 3|2 model 9|3 kind #0|4 custom_subscription_name 9?|5 max_mode 8|6 requests_costs 2|7 usage_based_costs 9?|8 is_token_based_call 8?|9 token_usage #1?|10 owning_user 9?|11 owning_team 9?|12 user_email 9?|13 cursor_token_fee 2?|14 is_chargeable 8?|15 service_account_name 9?|16 service_account_id 9?|17 is_headless 8?|18 charged_cents 2?|19 cloud_agent_id 9?|20 automation_id 9?|21 automation_managed_type 9?|22 client_type 9?|23 conversation_id 9?|24 subscription_product_id 9?|25 pr_author 9?|26 repo 9?|27 pr_number 5?|28 usage_event_id 9?|29 usage_type 9?|30 credit_consumed_cents 2?",a,v]}}class v extends o{constructor(t){super(),this.inputTokens=0,this.outputTokens=0,this.cacheWriteTokens=0,this.cacheReadTokens=0,this.totalCents=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new v).fromBinary(t,r)}static fromJson(t,r){return(new v).fromJson(t,r)}static fromJsonString(t,r){return(new v).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(v,t,r)}static $(){return["TokenUsage|1 input_tokens 5|2 output_tokens 5|3 cache_write_tokens 5|4 cache_read_tokens 5|5 total_cents 2|6 discount_percent_off 5?|7 enterprise_usage_discount_percent 2?|8 enterprise_product_usage_discount_percent 2?"]}}},"../proto/dist/generated/aiserver/v1/utils_pb.js"(t,r,e){e.d(r,{Az:()=>ot,Bo:()=>pt,CX:()=>Y,DX:()=>nt,EZ:()=>Ot,Ei:()=>I,FY:()=>Tt,Gm:()=>W,LI:()=>xt,M6:()=>Q,MT:()=>E,NG:()=>U,Nj:()=>c,O2:()=>ht,Q9:()=>kt,QP:()=>B,Se:()=>f,U$:()=>et,U1:()=>L,UR:()=>It,Uf:()=>C,Us:()=>Ct,Vq:()=>g,Wf:()=>q,Wj:()=>X,Xr:()=>bt,Y1:()=>st,Yd:()=>l,ZH:()=>O,_u:()=>P,bO:()=>tt,bV:()=>_t,c5:()=>Dt,d7:()=>T,df:()=>J,e$:()=>m,ej:()=>mt,ek:()=>_,fL:()=>M,gO:()=>p,l2:()=>y,lo:()=>u,n6:()=>b,o$:()=>S,oQ:()=>D,ot:()=>vt,qW:()=>K,qv:()=>Et,sr:()=>Rt,vj:()=>ct,wZ:()=>rt,x$:()=>a,yM:()=>lt,zH:()=>h});var n=e("@bufbuild/protobuf"),s=e("../proto/dist/runtime/compact.js");const i="aiserver.v1.";class o extends s.HL{static get runtime(){return(0,s.kU)(this,"runtime",n.proto3)}static $p(){return i}}var a=(0,s.QT)(n.proto3,i,"LintSeverity",[[0,"UNSPECIFIED"],[1,"ERROR"],[2,"WARNING"],[3,"INFO"],[4,"HINT"],[5,"AI"]],1),u=(0,s.QT)(n.proto3,i,"FeatureType",[[0,"UNSPECIFIED"],[1,"EDIT"],[2,"GENERATE"],[3,"INLINE_LONG_COMPLETION"]],1),c=(0,s.QT)(n.proto3,i,"EmbeddingModel",[[0,"UNSPECIFIED"],[1,"VOYAGE_CODE_2"],[2,"TEXT_EMBEDDINGS_LARGE_3"],[3,"QWEN_1_5B_CUSTOM"],[4,"MOCK_CHUNKER_ERROR"],[5,"QWEN_1_5B_0618_CUSTOM"],[6,"QWEN_1_5B_0618_FP8_MM_CUSTOM"]],1);class l extends o{constructor(t){super(),this.line=0,this.column=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new l).fromBinary(t,r)}static fromJson(t,r){return(new l).fromJson(t,r)}static fromJsonString(t,r){return(new l).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(l,t,r)}static $(){return["CursorPosition|1 line 5|2 column 5"]}}class m extends o{constructor(t){super(),this.totalmem=0,this.freemem=0,this.loadavg=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new m).fromBinary(t,r)}static fromJson(t,r){return(new m).fromJson(t,r)}static fromJsonString(t,r){return(new m).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(m,t,r)}static $(){return["VscodeOSStatistics|1 totalmem 1|2 freemem 1|3 loadavg 1*"]}}class f extends o{constructor(t){super(),this.type="",this.release="",this.arch="",this.platform="",this.cpus=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new f).fromBinary(t,r)}static fromJson(t,r){return(new f).fromJson(t,r)}static fromJsonString(t,r){return(new f).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(f,t,r)}static $(){return["VscodeOSProperties|1 type 9|2 release 9|3 arch 9|4 platform 9|5 cpus #0*",d]}}class d extends o{constructor(t){super(),this.model="",this.speed=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new d).fromBinary(t,r)}static fromJson(t,r){return(new d).fromJson(t,r)}static fromJsonString(t,r){return(new d).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(d,t,r)}static $(){return["VscodeCPUProperties|1 model 9|2 speed 1"]}}class p extends o{constructor(t){super(),this.workspaceUris=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new p).fromBinary(t,r)}static fromJson(t,r){return(new p).fromJson(t,r)}static fromJsonString(t,r){return(new p).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(p,t,r)}static $(){return["EnvironmentInfo|1 exthost_platform 9?|2 exthost_arch 9?|3 exthost_release 9?|4 exthost_shell 9?|5 local_timestamp 9?|6 workspace_uris 9*|7 cursor_version 9?|8 is_remote 8?|9 local_os_type 9?|10 home_directory 9?|11 local_timezone 9?"]}}class h extends o{constructor(t){super(),this.selectionStartLineNumber=0,this.selectionStartColumn=0,this.positionLineNumber=0,this.positionColumn=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new h).fromBinary(t,r)}static fromJson(t,r){return(new h).fromJson(t,r)}static fromJsonString(t,r){return(new h).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(h,t,r)}static $(){return["SelectionWithOrientation|1 selection_start_line_number 5|2 selection_start_column 5|3 position_line_number 5|4 position_column 5"]}}class g extends o{constructor(t){super(),this.cwd="",this.ref="",this.baseRef="",this.mergeBase=!1,this.targetPaths=[],this.maxUntrackedFiles=0,this.submoduleRecurseDepth=0,this.includeSpaceChanges=!1,this.committedOnly=!1,this.computePatchId=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new g).fromBinary(t,r)}static fromJson(t,r){return(new g).fromJson(t,r)}static fromJsonString(t,r){return(new g).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(g,t,r)}static $(){return["GetDiffRequest|1 cwd 9|2 ref 9|3 base_ref 9|4 merge_base 8|5 target_paths 9*|6 unified_context_lines 5?|7 max_untracked_files 5|9 submodule_recurse_depth 5|10 include_space_changes 8|11 committed_only 8|12 compute_patch_id 8|13 return_head_sha 8?|14 max_response_bytes 5?|15 max_files_with_contents 13?|16 max_content_bytes 13?|8 output_format #0?",_]}}var _=(0,s.QT)(n.proto3,i,"GetDiffRequest.OutputFormat",[[0,"UNSPECIFIED"],[1,"NAME_STATUS"],[2,"NAME_STATUS_AND_NUMSTAT"],[3,"FILE_DIFFS"],[4,"DIFFS_WITH_BEFORE_AND_AFTER"]],1);class J extends o{constructor(t){super(),this.submoduleDiffs=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new J).fromBinary(t,r)}static fromJson(t,r){return(new J).fromJson(t,r)}static fromJsonString(t,r){return(new J).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(J,t,r)}static $(){return["GetDiffResponse|1 diff #0|2 submodule_diffs #1*|3 patch_id 9?|4 head_sha 9?|5 has_uncommitted_changes 8?",S,w]}}class w extends o{constructor(t){super(),this.relativePath="",this.errored=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new w).fromBinary(t,r)}static fromJson(t,r){return(new w).fromJson(t,r)}static fromJsonString(t,r){return(new w).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(w,t,r)}static $(){return["GetDiffResponse.SubmoduleDiff|1 relative_path 9|2 diff #0|3 errored 8",S]}}class y extends o{constructor(t){super(),this.startLine=0,this.endLineInclusive=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new y).fromBinary(t,r)}static fromJson(t,r){return(new y).fromJson(t,r)}static fromJsonString(t,r){return(new y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(y,t,r)}static $(){return["SimplestRange|1 start_line 5|2 end_line_inclusive 5"]}}class S extends o{constructor(t){super(),this.diffs=[],this.diffType=q.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new S).fromBinary(t,r)}static fromJson(t,r){return(new S).fromJson(t,r)}static fromJsonString(t,r){return(new S).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(S,t,r)}static $(){return["GitDiff|1 diffs #0*|2 diff_type #1|3 file_contents_omitted 8?",B,q]}}var q=(0,s.QT)(n.proto3,i,"GitDiff.DiffType",[[0,"UNSPECIFIED"],[1,"DIFF_TO_HEAD"],[2,"DIFF_FROM_BRANCH_TO_MAIN"]],1);class B extends o{constructor(t){super(),this.added=0,this.removed=0,this.from="",this.to="",this.chunks=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new B).fromBinary(t,r)}static fromJson(t,r){return(new B).fromJson(t,r)}static fromJsonString(t,r){return(new B).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(B,t,r)}static $(){return["FileDiff|4 added 5|5 removed 5|1 from 9|2 to 9|3 chunks #0*|6 before_file_contents 9?|7 after_file_contents 9?|8 is_generated 8?|9 old_mode 9?|10 new_mode 9?",I]}}class I extends o{constructor(t){super(),this.content="",this.lines=[],this.oldStart=0,this.oldLines=0,this.newStart=0,this.newLines=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new I).fromBinary(t,r)}static fromJson(t,r){return(new I).fromJson(t,r)}static fromJsonString(t,r){return(new I).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(I,t,r)}static $(){return["FileDiff.Chunk|1 content 9|2 lines 9*|3 old_start 5|4 old_lines 5|5 new_start 5|6 new_lines 5"]}}class P extends o{constructor(t){super(),this.startLineNumber=0,this.startColumn=0,this.endLineNumberInclusive=0,this.endColumn=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new P).fromBinary(t,r)}static fromJson(t,r){return(new P).fromJson(t,r)}static fromJsonString(t,r){return(new P).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(P,t,r)}static $(){return["SimpleRange|1 start_line_number 5|2 start_column 5|3 end_line_number_inclusive 5|4 end_column 5"]}}class b extends o{constructor(t){super(),this.remoteUrl="",this.commitId="",this.gitPatch="",this.unsavedFiles=[],this.unixTimestampMs=0,this.openEditors=[],this.fileDiffHistories=[],this.branchName="",this.branchNotes="",this.branchNotesRich="",this.globalNotes="",this.pastThoughts=[],this.baseBranchName="",this.baseBranchCommitId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new b).fromBinary(t,r)}static fromJson(t,r){return(new b).fromJson(t,r)}static fromJsonString(t,r){return(new b).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(b,t,r)}static $(){return["CmdKDebugInfo|1 remote_url 9|2 commit_id 9|3 git_patch 9|4 unsaved_files #0*|5 unix_timestamp_ms 1|6 open_editors #1*|7 file_diff_histories #2*|8 branch_name 9|9 branch_notes 9|12 branch_notes_rich 9|10 global_notes 9|11 past_thoughts #3*|13 base_branch_name 9|14 base_branch_commit_id 9",R,v,x,k]}}class R extends o{constructor(t){super(),this.relativeWorkspacePath="",this.contents="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new R).fromBinary(t,r)}static fromJson(t,r){return(new R).fromJson(t,r)}static fromJsonString(t,r){return(new R).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(R,t,r)}static $(){return["CmdKDebugInfo.UnsavedFiles|1 relative_workspace_path 9|2 contents 9"]}}class v extends o{constructor(t){super(),this.relativeWorkspacePath="",this.editorGroupIndex=0,this.editorGroupId=0,this.isActive=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new v).fromBinary(t,r)}static fromJson(t,r){return(new v).fromJson(t,r)}static fromJsonString(t,r){return(new v).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(v,t,r)}static $(){return["CmdKDebugInfo.OpenEditor|1 relative_workspace_path 9|2 editor_group_index 5|3 editor_group_id 5|4 is_active 8"]}}class x extends o{constructor(t){super(),this.fileName="",this.diffHistory=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new x).fromBinary(t,r)}static fromJson(t,r){return(new x).fromJson(t,r)}static fromJsonString(t,r){return(new x).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(x,t,r)}static $(){return["CmdKDebugInfo.CppFileDiffHistory|1 file_name 9|2 diff_history 9*"]}}class k extends o{constructor(t){super(),this.text="",this.timeInUnixSeconds=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new k).fromBinary(t,r)}static fromJson(t,r){return(new k).fromJson(t,r)}static fromJsonString(t,r){return(new k).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(k,t,r)}static $(){return["CmdKDebugInfo.PastThought|1 text 9|2 time_in_unix_seconds 1"]}}class E extends o{constructor(t){super(),this.startLineNumber=0,this.endLineNumberInclusive=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new E).fromBinary(t,r)}static fromJson(t,r){return(new E).fromJson(t,r)}static fromJsonString(t,r){return(new E).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(E,t,r)}static $(){return["LineRange|1 start_line_number 5|2 end_line_number_inclusive 5"]}}class C extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new C).fromBinary(t,r)}static fromJson(t,r){return(new C).fromJson(t,r)}static fromJsonString(t,r){return(new C).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(C,t,r)}static $(){return["CursorRange|1 start_position #0|2 end_position #0",l]}}class T extends o{constructor(t){super(),this.text="",this.lineNumber=0,this.isSignature=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new T).fromBinary(t,r)}static fromJson(t,r){return(new T).fromJson(t,r)}static fromJsonString(t,r){return(new T).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(T,t,r)}static $(){return["DetailedLine|1 text 9|2 line_number 2|3 is_signature 8"]}}class U extends o{constructor(t){super(),this.relativeWorkspacePath="",this.contents="",this.detailedLines=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new U).fromBinary(t,r)}static fromJson(t,r){return(new U).fromJson(t,r)}static fromJsonString(t,r){return(new U).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(U,t,r)}static $(){return["CodeBlock|1 relative_workspace_path 9|2 file_contents 9?|9 file_contents_length 5?|3 range #0|4 contents 9|5 signatures #1|6 override_contents 9?|7 original_contents 9?|8 detailed_lines #2*|10 file_git_context #3",C,A,T,M]}}class A extends o{constructor(t){super(),this.ranges=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new A).fromBinary(t,r)}static fromJson(t,r){return(new A).fromJson(t,r)}static fromJsonString(t,r){return(new A).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(A,t,r)}static $(){return["CodeBlock.Signatures|1 ranges #0*",C]}}class $ extends o{constructor(t){super(),this.commit="",this.author="",this.date="",this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $).fromBinary(t,r)}static fromJson(t,r){return(new $).fromJson(t,r)}static fromJsonString(t,r){return(new $).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($,t,r)}static $(){return["GitCommit|1 commit 9|2 author 9|3 date 9|4 message 9"]}}class M extends o{constructor(t){super(),this.commits=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new M).fromBinary(t,r)}static fromJson(t,r){return(new M).fromJson(t,r)}static fromJsonString(t,r){return(new M).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(M,t,r)}static $(){return["FileGit|1 commits #0*",$]}}class O extends o{constructor(t){super(),this.relativeWorkspacePath="",this.contents="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new O).fromBinary(t,r)}static fromJson(t,r){return(new O).fromJson(t,r)}static fromJsonString(t,r){return(new O).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(O,t,r)}static $(){return["File|1 relative_workspace_path 9|2 contents 9|3 file_git_context #0",M]}}class D extends o{constructor(t){super(),this.message="",this.severity=N.UNSPECIFIED,this.relatedInformation=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new D).fromBinary(t,r)}static fromJson(t,r){return(new D).fromJson(t,r)}static fromJsonString(t,r){return(new D).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(D,t,r)}static $(){return["Diagnostic|1 message 9|2 range #0|3 severity #1|4 related_information #2*",C,N,G]}}var N=(0,s.QT)(n.proto3,i,"Diagnostic.DiagnosticSeverity",[[0,"UNSPECIFIED"],[1,"ERROR"],[2,"WARNING"],[3,"INFORMATION"],[4,"HINT"]],1);class G extends o{constructor(t){super(),this.message="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new G).fromBinary(t,r)}static fromJson(t,r){return(new G).fromJson(t,r)}static fromJsonString(t,r){return(new G).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(G,t,r)}static $(){return["Diagnostic.RelatedInformation|1 message 9|2 range #0",C]}}class L extends o{constructor(t){super(),this.message="",this.severity=a.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new L).fromBinary(t,r)}static fromJson(t,r){return(new L).fromJson(t,r)}static fromJsonString(t,r){return(new L).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(L,t,r)}static $(){return["Lint|1 message 9|2 range #0|3 severity #1",P,a]}}class F extends o{constructor(t){super(),this.content="",this.score=0,this.relativePath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new F).fromBinary(t,r)}static fromJson(t,r){return(new F).fromJson(t,r)}static fromJsonString(t,r){return(new F).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(F,t,r)}static $(){return["BM25Chunk|1 content 9|2 range #0|3 score 5|4 relative_path 9",y]}}class K extends o{constructor(t){super(),this.relativeWorkspacePath="",this.contents="",this.relyOnFilesync=!1,this.cells=[],this.topChunks=[],this.contentsStartAtLine=0,this.dataframes=[],this.totalNumberOfLines=0,this.languageId="",this.diagnostics=[],this.cellStartLines=[],this.workspaceRootPath="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new K).fromBinary(t,r)}static fromJson(t,r){return(new K).fromJson(t,r)}static fromJsonString(t,r){return(new K).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(K,t,r)}static $(){return["CurrentFileInfo|1 relative_workspace_path 9|2 contents 9|18 rely_on_filesync 8|17 sha_256_hash 9?|16 cells #0*|10 top_chunks #1*|9 contents_start_at_line 5|3 cursor_position #2|4 dataframes #3*|8 total_number_of_lines 5|5 language_id 9|6 selection #4|11 alternative_version_id 5?|7 diagnostics #5*|14 file_version 5?|15 cell_start_lines 5*|19 workspace_root_path 9|20 line_ending 9?",z,F,l,Y,C,D]}}class z extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new z).fromBinary(t,r)}static fromJson(t,r){return(new z).fromJson(t,r)}static fromJsonString(t,r){return(new z).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(z,t,r)}static $(){return["CurrentFileInfo.NotebookCell"]}}class j extends o{constructor(t){super(),this.apiKey="",this.baseUrl="",this.deployment="",this.useAzure=!1,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new j).fromBinary(t,r)}static fromJson(t,r){return(new j).fromJson(t,r)}static fromJsonString(t,r){return(new j).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(j,t,r)}static $(){return["AzureState|1 api_key 9|2 base_url 9|3 deployment 9|4 use_azure 8"]}}class H extends o{constructor(t){super(),this.accessKey="",this.secretKey="",this.region="",this.useBedrock=!1,this.sessionToken="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new H).fromBinary(t,r)}static fromJson(t,r){return(new H).fromJson(t,r)}static fromJsonString(t,r){return(new H).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(H,t,r)}static $(){return["BedrockState|1 access_key 9|2 secret_key 9|3 region 9|4 use_bedrock 8|5 session_token 9"]}}class W extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new W).fromBinary(t,r)}static fromJson(t,r){return(new W).fromJson(t,r)}static fromJsonString(t,r){return(new W).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(W,t,r)}static $(){return["ModelDetails|1 model_name 9?|2 api_key 9?|3 enable_ghost_mode 8?|4 azure_state #0?|5 enable_slow_pool 8?|6 openai_api_base_url 9?|7 bedrock_state #1?|8 max_mode 8?",j,H]}}class Q extends o{constructor(t){super(),this.modelId="",this.parameters=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Q).fromBinary(t,r)}static fromJson(t,r){return(new Q).fromJson(t,r)}static fromJsonString(t,r){return(new Q).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Q,t,r)}static $(){return["CloudAgentModelSelection|1 model_id 9|2 parameters #0*|3 max_mode 8?",V]}}class V extends o{constructor(t){super(),this.id="",this.value="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new V).fromBinary(t,r)}static fromJson(t,r){return(new V).fromJson(t,r)}static fromJsonString(t,r){return(new V).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(V,t,r)}static $(){return["CloudAgentModelSelection.ParameterValue|1 id 9|2 value 9"]}}class X extends o{constructor(t){super(),this.modelName="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new X).fromBinary(t,r)}static fromJson(t,r){return(new X).fromJson(t,r)}static fromJsonString(t,r){return(new X).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(X,t,r)}static $(){return["ModelInfo|1 model_name 9"]}}class Y extends o{constructor(t){super(),this.name="",this.shape="",this.dataDimensionality=0,this.columns=[],this.rowCount=0,this.indexColumn="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Y).fromBinary(t,r)}static fromJson(t,r){return(new Y).fromJson(t,r)}static fromJsonString(t,r){return(new Y).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Y,t,r)}static $(){return["DataframeInfo|1 name 9|2 shape 9|3 data_dimensionality 5|6 columns #0*|7 row_count 5|8 index_column 9",Z]}}class Z extends o{constructor(t){super(),this.key="",this.type="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Z).fromBinary(t,r)}static fromJson(t,r){return(new Z).fromJson(t,r)}static fromJsonString(t,r){return(new Z).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Z,t,r)}static $(){return["DataframeInfo.Column|1 key 9|2 type 9"]}}class tt extends o{constructor(t){super(),this.message="",this.relatedInformation=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new tt).fromBinary(t,r)}static fromJson(t,r){return(new tt).fromJson(t,r)}static fromJsonString(t,r){return(new tt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(tt,t,r)}static $(){return["LinterError|1 message 9|2 range #0|3 source 9?|4 related_information #1*|5 severity #2?|6 is_stale 8?",C,G,N]}}class rt extends o{constructor(t){super(),this.relativeWorkspacePath="",this.errors=[],this.fileContents="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new rt).fromBinary(t,r)}static fromJson(t,r){return(new rt).fromJson(t,r)}static fromJsonString(t,r){return(new rt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(rt,t,r)}static $(){return["LinterErrors|1 relative_workspace_path 9|2 errors #0*|3 file_contents 9",tt]}}class et extends o{constructor(t){super(),this.relativeWorkspacePath="",this.errors=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new et).fromBinary(t,r)}static fromJson(t,r){return(new et).fromJson(t,r)}static fromJsonString(t,r){return(new et).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(et,t,r)}static $(){return["LinterErrorsWithoutFileContents|1 relative_workspace_path 9|2 errors #0*",tt]}}class nt extends o{constructor(t){super(),this.name="",this.description="",this.environments=[],this.disabledEnvironments=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new nt).fromBinary(t,r)}static fromJson(t,r){return(new nt).fromJson(t,r)}static fromJsonString(t,r){return(new nt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(nt,t,r)}static $(){return["CursorRule|1 name 9|2 description 9|3 body 9?|4 is_from_glob 8?|5 always_apply 8?|6 attach_to_background_agents 8?|7 full_path 9?|8 environments 9*|9 disabled_environments 9*|10 plugin 9?|11 marketplace 9?"]}}class st extends o{constructor(t){super(),this.context="",this.rules=[],this.mcpInstructions=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new st).fromBinary(t,r)}static fromJson(t,r){return(new st).fromJson(t,r)}static fromJsonString(t,r){return(new st).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(st,t,r)}static $(){return["ExplicitContext|1 context 9|2 repo_context 9?|3 rules #0*|4 mode_specific_context 9?|5 mcp_instructions #1*",nt,it]}}class it extends o{constructor(t){super(),this.serverName="",this.serverIdentifier="",this.instructions="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new it).fromBinary(t,r)}static fromJson(t,r){return(new it).fromJson(t,r)}static fromJsonString(t,r){return(new it).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(it,t,r)}static $(){return["MCPInstructions|1 server_name 9|2 server_identifier 9|3 instructions 9"]}}n.proto3;class ot extends o{constructor(t){super(),this.name="",this.detail="",this.kind=at.UNSPECIFIED,this.containerName="",this.children=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ot).fromBinary(t,r)}static fromJson(t,r){return(new ot).fromJson(t,r)}static fromJsonString(t,r){return(new ot).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ot,t,r)}static $(){return["DocumentSymbol|1 name 9|2 detail 9|3 kind #0|5 container_name 9|6 range #1|7 selection_range #1|8 children #2*",at,ut,ot]}}var at=(0,s.QT)(n.proto3,i,"DocumentSymbol.SymbolKind",[[0,"UNSPECIFIED"],[1,"FILE"],[2,"MODULE"],[3,"NAMESPACE"],[4,"PACKAGE"],[5,"CLASS"],[6,"METHOD"],[7,"PROPERTY"],[8,"FIELD"],[9,"CONSTRUCTOR"],[10,"ENUM"],[11,"INTERFACE"],[12,"FUNCTION"],[13,"VARIABLE"],[14,"CONSTANT"],[15,"STRING"],[16,"NUMBER"],[17,"BOOLEAN"],[18,"ARRAY"],[19,"OBJECT"],[20,"KEY"],[21,"NULL"],[22,"ENUM_MEMBER"],[23,"STRUCT"],[24,"EVENT"],[25,"OPERATOR"],[26,"TYPE_PARAMETER"]],1);class ut extends o{constructor(t){super(),this.startLineNumber=0,this.startColumn=0,this.endLineNumber=0,this.endColumn=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ut).fromBinary(t,r)}static fromJson(t,r){return(new ut).fromJson(t,r)}static fromJsonString(t,r){return(new ut).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ut,t,r)}static $(){return["DocumentSymbol.Range|1 start_line_number 5|2 start_column 5|3 end_line_number 5|4 end_column 5"]}}class ct extends o{constructor(t){super(),this.error=lt.UNSPECIFIED,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ct).fromBinary(t,r)}static fromJson(t,r){return(new ct).fromJson(t,r)}static fromJsonString(t,r){return(new ct).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ct,t,r)}static $(){return["ErrorDetails|1 error #0|2 details #1|3 is_expected 8?",lt,mt]}}var lt=(0,s.QT)(n.proto3,i,"ErrorDetails.Error",[[0,"UNSPECIFIED"],[1,"BAD_API_KEY"],[42,"BAD_USER_API_KEY"],[2,"NOT_LOGGED_IN"],[3,"INVALID_AUTH_ID"],[4,"NOT_HIGH_ENOUGH_PERMISSIONS"],[18,"AGENT_REQUIRES_LOGIN"],[5,"BAD_MODEL_NAME"],[39,"NOT_FOUND"],[40,"DEPRECATED"],[6,"USER_NOT_FOUND"],[7,"FREE_USER_RATE_LIMIT_EXCEEDED"],[8,"PRO_USER_RATE_LIMIT_EXCEEDED"],[9,"FREE_USER_USAGE_LIMIT"],[10,"PRO_USER_USAGE_LIMIT"],[41,"RESOURCE_EXHAUSTED"],[11,"AUTH_TOKEN_NOT_FOUND"],[12,"AUTH_TOKEN_EXPIRED"],[13,"OPENAI"],[14,"OPENAI_RATE_LIMIT_EXCEEDED"],[20,"MAX_TOKENS"],[23,"PRO_USER_ONLY"],[21,"USER_ABORTED_REQUEST"],[25,"TIMEOUT"],[22,"GENERIC_RATE_LIMIT_EXCEEDED"],[28,"GPT_4_VISION_PREVIEW_RATE_LIMIT"],[29,"CUSTOM_MESSAGE"],[30,"OUTDATED_CLIENT"],[31,"CLAUDE_IMAGE_TOO_LARGE"],[33,"FILE_NOT_FOUND"],[34,"API_KEY_RATE_LIMIT"],[35,"DEBOUNCED"],[36,"BAD_REQUEST"],[37,"REPOSITORY_SERVICE_REPOSITORY_IS_NOT_INITIALIZED"],[38,"UNAUTHORIZED"],[43,"CONVERSATION_TOO_LONG"],[44,"USAGE_PRICING_REQUIRED"],[45,"USAGE_PRICING_REQUIRED_CHANGEABLE"],[46,"GITHUB_NO_USER_CREDENTIALS"],[47,"GITHUB_USER_NO_ACCESS"],[48,"GITHUB_APP_NO_ACCESS"],[49,"GITHUB_MULTIPLE_OWNERS"],[50,"RATE_LIMITED"],[51,"RATE_LIMITED_CHANGEABLE"],[52,"CUSTOM"],[53,"HOOKS_BLOCKED"],[54,"SUSPICIOUS_USAGE_BLOCKED"],[55,"EXTENSION_HOST_TIMEOUT"],[56,"NETWORK_ERROR"],[57,"PROVIDER_ERROR"],[58,"MODEL_BLOCKED"],[59,"INTERNAL"],[60,"MAX_MODE_REQUIRED"],[61,"MODEL_NO_LONGER_SUPPORTED"],[62,"PRICING_WARNING"],[63,"SLOW_POOL"],[64,"UNSUPPORTED_REGION"],[65,"ACCOUNT_CLOSED"],[66,"TENANT_RESTRICTION_VIOLATION"]],1);class mt extends o{constructor(t){super(),this.title="",this.detail="",this.buttons=[],this.additionalInfo={},this.planChoices=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new mt).fromBinary(t,r)}static fromJson(t,r){return(new mt).fromJson(t,r)}static fromJsonString(t,r){return(new mt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(mt,t,r)}static $(){return["CustomErrorDetails|1 title 9|2 detail 9|3 allow_command_links_potentially_unsafe_please_only_use_for_handwritten_trusted_markdown 8?|4 is_retryable 8?|5 show_request_id 8?|6 should_show_immediate_error 8?|8 buttons #0*|7 additional_info 9,9|9 plan_choices #1*|10 analytics_metadata #2?",pt,dt,ft]}}class ft extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ft).fromBinary(t,r)}static fromJson(t,r){return(new ft).fromJson(t,r)}static fromJsonString(t,r){return(new ft).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ft,t,r)}static $(){return["ErrorAnalyticsMetadata|1 action_required 9?"]}}class dt extends o{constructor(t){super(),this.label="",this.value="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new dt).fromBinary(t,r)}static fromJson(t,r){return(new dt).fromJson(t,r)}static fromJsonString(t,r){return(new dt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(dt,t,r)}static $(){return["PlanChoice|1 label 9|2 sublabel 9?|3 description 9?|4 value 9"]}}class pt extends o{constructor(t){super(),this.label="",this.action={case:void 0},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new pt).fromBinary(t,r)}static fromJson(t,r){return(new pt).fromJson(t,r)}static fromJsonString(t,r){return(new pt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(pt,t,r)}static $(){return["ErrorButton|1 label 9|2 upgrade #0 action|3 switch_model #1 action|4 configure_spend_limit #2 action|5 url #3 action|6 upgrade_choice #4 action|7 dashboard_action #5 action|8 reload_window #6 action|9 client_action #7 action",wt,yt,qt,Bt,Jt,_t,gt,ht]}}class ht extends o{constructor(t){super(),this.commandId="",this.args={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new ht).fromBinary(t,r)}static fromJson(t,r){return(new ht).fromJson(t,r)}static fromJsonString(t,r){return(new ht).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(ht,t,r)}static $(){return["ClientAction|1 command_id 9|2 args 9,9"]}}class gt extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new gt).fromBinary(t,r)}static fromJson(t,r){return(new gt).fromJson(t,r)}static fromJsonString(t,r){return(new gt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(gt,t,r)}static $(){return["ReloadWindowAction"]}}class _t extends o{constructor(t){super(),this.action="",this.args={},n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new _t).fromBinary(t,r)}static fromJson(t,r){return(new _t).fromJson(t,r)}static fromJsonString(t,r){return(new _t).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(_t,t,r)}static $(){return["DashboardAction|1 action 9|2 args 9,9|3 success_message 9?"]}}class Jt extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Jt).fromBinary(t,r)}static fromJson(t,r){return(new Jt).fromJson(t,r)}static fromJsonString(t,r){return(new Jt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Jt,t,r)}static $(){return["UpgradeChoice"]}}class wt extends o{constructor(t){super(),this.membershipToUpgradeTo="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new wt).fromBinary(t,r)}static fromJson(t,r){return(new wt).fromJson(t,r)}static fromJsonString(t,r){return(new wt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(wt,t,r)}static $(){return["UpgradeAction|1 membership_to_upgrade_to 9|2 try_immediate_upgrade 8?|3 allow_trial 8?|4 dashboard_action #0?",_t]}}class yt extends o{constructor(t){super(),this.parameters=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new yt).fromBinary(t,r)}static fromJson(t,r){return(new yt).fromJson(t,r)}static fromJsonString(t,r){return(new yt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(yt,t,r)}static $(){return["SwitchModelAction|1 suggested_model 9?|2 parameters #0*|3 max_mode 8?",St]}}class St extends o{constructor(t){super(),this.id="",this.value="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new St).fromBinary(t,r)}static fromJson(t,r){return(new St).fromJson(t,r)}static fromJsonString(t,r){return(new St).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(St,t,r)}static $(){return["SwitchModelAction.ModelParameterValue|1 id 9|2 value 9"]}}class qt extends o{constructor(t){super(),this.confirmLabel="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new qt).fromBinary(t,r)}static fromJson(t,r){return(new qt).fromJson(t,r)}static fromJsonString(t,r){return(new qt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(qt,t,r)}static $(){return["ConfigureSpendLimitAction|1 confirm_label 9"]}}class Bt extends o{constructor(t){super(),this.url="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Bt).fromBinary(t,r)}static fromJson(t,r){return(new Bt).fromJson(t,r)}static fromJsonString(t,r){return(new Bt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Bt,t,r)}static $(){return["UrlAction|1 url 9"]}}class It extends o{constructor(t){super(),this.data=new Uint8Array(0),this.uuid="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new It).fromBinary(t,r)}static fromJson(t,r){return(new It).fromJson(t,r)}static fromJsonString(t,r){return(new It).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(It,t,r)}static $(){return["ImageProto|1 data 12|2 dimension #0|3 uuid 9|4 task_specific_description 9?",Pt]}}class Pt extends o{constructor(t){super(),this.width=0,this.height=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Pt).fromBinary(t,r)}static fromJson(t,r){return(new Pt).fromJson(t,r)}static fromJsonString(t,r){return(new Pt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Pt,t,r)}static $(){return["ImageProto.Dimension|1 width 5|2 height 5"]}}class bt extends o{constructor(t){super(),this.markdown="",this.bubbleId="",this.sectionIndex=0,n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new bt).fromBinary(t,r)}static fromJson(t,r){return(new bt).fromJson(t,r)}static fromJsonString(t,r){return(new bt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(bt,t,r)}static $(){return["ChatQuote|1 markdown 9|2 bubble_id 9|3 section_index 5"]}}class Rt extends o{constructor(t){super(),this.url="",this.uuid="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Rt).fromBinary(t,r)}static fromJson(t,r){return(new Rt).fromJson(t,r)}static fromJsonString(t,r){return(new Rt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Rt,t,r)}static $(){return["ChatExternalLink|1 url 9|2 uuid 9|3 pdf_content 9?|4 is_pdf 8?|5 filename 9?"]}}class vt extends o{constructor(t){super(),this.url="",this.uuid="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new vt).fromBinary(t,r)}static fromJson(t,r){return(new vt).fromJson(t,r)}static fromJsonString(t,r){return(new vt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(vt,t,r)}static $(){return["ComposerExternalLink|1 url 9|2 uuid 9|3 pdf_content 9?|4 is_pdf 8?|5 filename 9?"]}}class xt extends o{constructor(t){super(),this.url="",this.uuid="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new xt).fromBinary(t,r)}static fromJson(t,r){return(new xt).fromJson(t,r)}static fromJsonString(t,r){return(new xt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(xt,t,r)}static $(){return["CmdKExternalLink|1 url 9|2 uuid 9"]}}class kt extends o{constructor(t){super(),this.note="",this.commitHash="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new kt).fromBinary(t,r)}static fromJson(t,r){return(new kt).fromJson(t,r)}static fromJsonString(t,r){return(new kt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(kt,t,r)}static $(){return["CommitNote|1 note 9|2 commit_hash 9"]}}class Et extends o{constructor(t){super(),this.note="",this.commitHash="",this.embeddings=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Et).fromBinary(t,r)}static fromJson(t,r){return(new Et).fromJson(t,r)}static fromJsonString(t,r){return(new Et).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Et,t,r)}static $(){return["CommitNoteWithEmbeddings|1 note 9|2 commit_hash 9|3 embeddings 1*"]}}class Ct extends o{constructor(t){super(),this.diff="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ct).fromBinary(t,r)}static fromJson(t,r){return(new Ct).fromJson(t,r)}static fromJsonString(t,r){return(new Ct).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ct,t,r)}static $(){return["CommitDiffString|1 diff 9"]}}class Tt extends o{constructor(t){super(),this.relativeWorkspacePath="",this.startLineNumber=0,this.lines=[],this.languageIdentifier="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Tt).fromBinary(t,r)}static fromJson(t,r){return(new Tt).fromJson(t,r)}static fromJsonString(t,r){return(new Tt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Tt,t,r)}static $(){return["CodeChunk|1 relative_workspace_path 9|2 start_line_number 5|3 lines 9*|4 summarization_strategy #0?|5 language_identifier 9|6 intent #1?|7 is_final_version 8?|8 is_first_version 8?",At,Ut]}}var Ut=(0,s.QT)(n.proto3,i,"CodeChunk.Intent",[[0,"UNSPECIFIED"],[1,"COMPOSER_FILE"],[2,"COMPRESSED_COMPOSER_FILE"]],1),At=(0,s.QT)(n.proto3,i,"CodeChunk.SummarizationStrategy",[[0,"NONE_UNSPECIFIED"],[1,"SUMMARIZED"],[2,"EMBEDDED"]],1);class $t extends o{constructor(t){super(),n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new $t).fromBinary(t,r)}static fromJson(t,r){return(new $t).fromJson(t,r)}static fromJsonString(t,r){return(new $t).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals($t,t,r)}static $(){return["RCPCallFrame|1 function_name 9?|2 url 9?|3 line_number 5?|4 column_number 5?"]}}class Mt extends o{constructor(t){super(),this.callFrames=[],n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Mt).fromBinary(t,r)}static fromJson(t,r){return(new Mt).fromJson(t,r)}static fromJsonString(t,r){return(new Mt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Mt,t,r)}static $(){return["RCPStackTrace|1 call_frames #0*|2 raw_stack_trace 9?",$t]}}class Ot extends o{constructor(t){super(),this.message="",this.timestamp=0,this.level="",this.clientName="",this.sessionId="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Ot).fromBinary(t,r)}static fromJson(t,r){return(new Ot).fromJson(t,r)}static fromJsonString(t,r){return(new Ot).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Ot,t,r)}static $(){return["RCPLogEntry|1 message 9|2 timestamp 1|3 level 9|4 client_name 9|5 session_id 9|6 stack_trace #0?|7 object_data_json 9?",Mt]}}class Dt extends o{constructor(t){super(),this.element="",this.xpath="",this.textContent="",this.extra="",n.proto3.util.initPartial(t,this)}static fromBinary(t,r){return(new Dt).fromBinary(t,r)}static fromJson(t,r){return(new Dt).fromJson(t,r)}static fromJsonString(t,r){return(new Dt).fromJsonString(t,r)}static equals(t,r){return n.proto3.util.equals(Dt,t,r)}static $(){return["RCPUIElementPicked|1 element 9|2 xpath 9|3 text_content 9|4 extra 9|5 component 9?|6 component_props_json 9?"]}}},"../proto/dist/runtime/compact.js"(t,r,e){e.d(r,{HL:()=>u,QT:()=>l,kU:()=>i});var n=e("@bufbuild/protobuf");const s={};function i(t,r,e){return Object.defineProperty(t,r,{value:e,writable:!0,enumerable:!0,configurable:!0}),e}function o(t,r,e){if("#"!==e.charAt(0))return{kind:"scalar",T:Number(e)};const n=r[Number(e.slice(1))];return"function"==typeof n?{kind:"message",T:n}:{kind:"enum",T:t.getEnumType(n)}}function a(t){return"?"===t?{opt:!0}:"*"===t?{repeated:!0}:void 0===t?s:{oneof:t}}class u extends n.Message{static get typeName(){const t=c(this);return i(t,"typeName",t.$p()+function(t){const r=t[0],e=r.indexOf("|");return-1===e?r:r.slice(0,e)}(t.$()))}static get fields(){const t=c(this),r=t.$(),e=t.runtime;return i(t,"fields",e.util.newFieldList((()=>function(t,r){const[e,...n]=r,s=e.split("|"),i=[];for(let r=1;r"_"+t))).toUpperCase()+"_"}(i);a=n.map((t=>t[1])),o=a.map((r=>t+r))}else o=n.map((t=>t[1])),a=void 0===s?function(t,r){const e=(t.charAt(0)+t.slice(1).replace(/[A-Z]/g,(t=>"_"+t))).toLowerCase()+"_",n=[];for(const t of r){if(!t.toLowerCase().startsWith(e))return r.slice();const s=t.slice(e.length);if(""===s||/^[0-9]/.test(s))return r.slice();n.push(s)}return n}(i,o):s;const u={},c=[];for(let t=0;tn});class n{}},"../utils/dist/fresh-uuid.js"(t,r,e){e.d(r,{C:()=>a});var n=e("node:crypto"),s=e("node:fs");let i,o=!1;function a(){const t=function(){if(!o)try{void 0===i&&(i=(0,s.openSync)("/dev/urandom","r"));const t=Buffer.alloc(16);let r=0;for(;r<16;){const e=(0,s.readSync)(i,t,r,16-r,null);if(e<=0)return;r+=e}return t}catch{if(o=!0,void 0!==i){try{(0,s.closeSync)(i)}catch{}i=void 0}return}}();return void 0===t?(0,n.randomUUID)({disableEntropyCache:!0}):function(t){const r=t[6]??0,e=t[8]??0;t[6]=15&r|64,t[8]=63&e|128;const n=t.toString("hex");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}(t)}},"../utils/dist/private-file.js"(t,r,e){e.d(r,{Pl:()=>l,rV:()=>m});var n=e("node:crypto"),s=e("node:fs/promises"),i=e("node:path"),o=e("../utils/dist/promise-extras.js");const a=[10,25,50,100,200],u=new Set(["EPERM","EACCES","EBUSY"]),c=new Set(["ENOSYS","ENOTSUP","EOPNOTSUPP","EINVAL","EPERM"]);async function l(t,r,e={}){const c=(0,i.dirname)(t);await async function(t){await(0,s.mkdir)((0,i.dirname)(t),{recursive:!0});try{await(0,s.mkdir)(t,{mode:448})}catch(t){if("EEXIST"!==p(t))throw t}}(c),!1!==e.privateDirectory&&await f(c,"directory").catch(d);const l=(0,i.join)(c,`.${(0,i.basename)(t)}.${(0,n.randomBytes)(6).toString("hex")}.tmp`),m=await(0,s.open)(l,"wx",384);try{try{await m.chmod(384).catch(d),await m.writeFile(r),await m.sync()}finally{await m.close()}await async function(t,r){if("win32"===process.platform){for(const e of a)try{return void await(0,s.rename)(t,r)}catch(t){const r=p(t);if(void 0===r||!u.has(r))throw t;await(0,o.cb)(e)}await(0,s.rename)(t,r)}else await(0,s.rename)(t,r)}(l,t)}catch(t){throw await(0,s.rm)(l,{force:!0}),t}}async function m(t,r={}){"win32"!==process.platform&&(!1!==r.privateDirectory&&await f((0,i.dirname)(t),"directory").catch((()=>{})),await f(t,"file").catch((()=>{})))}async function f(t,r){if("win32"===process.platform)return;let e;try{e="file"===r?await(0,s.lstat)(t):await(0,s.stat)(t)}catch(t){if("ENOENT"===p(t))return;throw t}if(e.isSymbolicLink())return;const{mode:n,uid:i}=e;63&n&&(void 0!==process.getuid&&i!==process.getuid()||await(0,s.chmod)(t,511&n&-64))}function d(t){const r=p(t);if(!("win32"===process.platform||void 0!==r&&c.has(r)))throw t}function p(t){return t instanceof Error&&"code"in t&&"string"==typeof t.code?t.code:void 0}},"../utils/dist/promise-extras.js"(t,r,e){function n({array:t,selector:r,max:e,settleRejections:n,onSettled:s}){const i=Math.min(t.length,e>=1?e:1);return new Promise(((e,o)=>{let a=0,u=0,c=!1;const l=t=>{c=!0,o(t)},m=()=>{for(;!c&&u{u--,c||(s(e,{status:"fulfilled",value:t}),m())}),(t=>{u--,c||(n?(s(e,{status:"rejected",reason:t}),m()):l(t))}))}c||0!==u||a!==t.length||e()};m()}))}async function s(t,r,e){const{max:s=4}=e??{},i=new Map;return await n({array:t,selector:r,max:s,settleRejections:!1,onSettled:(r,e)=>{"fulfilled"===e.status&&i.set(t[r],e.value)}}),i}async function i(t,r,e){const{max:s=4}=e??{},i=[];return await n({array:t,selector:r,max:s,settleRejections:!1,onSettled:(t,r)=>{"fulfilled"===r.status&&(i[t]=r.value)}}),i}async function o(t,r,e){const{max:s=4}=e??{},i=[];return await n({array:t,selector:r,max:s,settleRejections:!0,onSettled:(t,r)=>{i[t]=r}}),i}function a(t){return new Promise((r=>{setTimeout(r,t)}))}function u(t,r){return new Promise((e=>{if(r.aborted)return void e();const n=()=>{clearTimeout(s),e()},s=setTimeout((()=>{r.removeEventListener("abort",n),e()}),t);r.addEventListener("abort",n,{once:!0})}))}e.d(r,{MU:()=>c,O$:()=>m,PH:()=>i,TJ:()=>f,cb:()=>a,st:()=>u,up:()=>o,wj:()=>l,xb:()=>s});class c extends Error{constructor(t){super(t),this.name="TimeoutError"}}function l(t,r,e){return new Promise(((n,s)=>{const i=setInterval((()=>{clearInterval(i),s(new c(e??`Promise timed out after ${r}ms`))}),r);t.then((t=>{clearInterval(i),n(t)}),(t=>{clearInterval(i),s(t)}))}))}async function m(t,r=3){for(let e=0;;e++)try{return await t()}catch(t){if(e>=r)throw t}}class f{constructor(t){this.running=0,this.closed=!1,this.idleWaiters=[];const{max:r=4}=t??{};this.max=r}enqueue(t){return this.closed?Promise.reject(new Error("PromiseQueue is closed")):new Promise(((r,e)=>{const n=()=>{let n;this.running++;try{n=Promise.resolve(t())}catch(t){n=Promise.reject(t)}n.then((t=>{this.settle(),r(t)}),(t=>{this.settle(),e(t)}))};if(this.runningthis.enqueue((()=>r(t))).then((r=>{e.set(t,r)}))))),e}close(){return this.closed=!0,0===this.running&&void 0===this.waitingHead?Promise.resolve():new Promise((t=>{this.idleWaiters.push(t)}))}settle(){this.running--;const t=this.waitingHead;if(void 0!==t)return this.waitingHead=t.next,void 0===this.waitingHead&&(this.waitingTail=void 0),void t.start();if(0===this.running)for(const t of this.idleWaiters.splice(0))t()}}},"../utils/dist/workspace-paths.js"(t,r,e){e.d(r,{O2:()=>n,Rv:()=>i,r_:()=>s,sh:()=>o});const n="agent-transcripts";function s(t){return t.replace(/[^a-zA-Z0-9]/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function i(t,r){return function(t,...r){if(!function(t){return/^[A-Za-z]:[\\/]/.test(t)||t.startsWith("\\\\")||t.startsWith("//")}(t))return[t.replace(/\/+$/,""),...r].join("/");const e=t.replace(/\//g,"\\").replace(/\\+$/,""),n=r.map((t=>t.replace(/\//g,"\\")));return 0===e.length?["","",...n].join("\\"):[e,...n].join("\\")}(t,".cursor","projects",s(r))}function o(t){let r=encodeURIComponent(t);return r=r.replace(/%/g,"_"),r.length>200&&(r=r.slice(0,200)),r}},"./package.json"(t){t.exports={rE:"1.4.2"}}},s={};function i(t){var r=s[t];if(void 0!==r)return r.exports;var e=s[t]={exports:{}};return n[t].call(e.exports,e,e.exports,i),e.exports}i.m=n,i.n=t=>{var r=t&&t.__esModule?()=>t.default:()=>t;return i.d(r,{a:r}),r},r=Object.getPrototypeOf?t=>Object.getPrototypeOf(t):t=>t.__proto__,i.t=function(e,n){if(1&n&&(e=this(e)),8&n)return e;if("object"==typeof e&&e){if(4&n&&e.__esModule)return e;if(16&n&&"function"==typeof e.then)return e}var s=Object.create(null);i.r(s);var o={};t=t||[null,r({}),r([]),r(r)];for(var a=2&n&&e;("object"==typeof a||"function"==typeof a)&&!~t.indexOf(a);a=r(a))Object.getOwnPropertyNames(a).forEach((t=>o[t]=()=>e[t]));return o.default=()=>e,i.d(s,o),s},i.d=(t,r)=>{for(var e in r)i.o(r,e)&&!i.o(t,e)&&Object.defineProperty(t,e,{enumerable:!0,get:r[e]})},i.f={},i.e=t=>Promise.all(Object.keys(i.f).reduce(((r,e)=>(i.f[e](t,r),r)),[])),i.u=t=>t+".js",i.o=(t,r)=>Object.prototype.hasOwnProperty.call(t,r),i.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},i.j=57,e={18:1,57:1},i.f.require=(t,r)=>{if(!e[t]){var n=require("./"+i.u(t));e[t]||(t=>{var r=t.modules,n=t.ids,s=t.runtime;for(var o in r)i.o(r,o)&&(i.m[o]=r[o]);s&&s(i);for(var a=0;a$e,AgentBusyError:()=>a.J1,AgentConversationTurnSchema:()=>je,AgentNotFoundError:()=>a.XB,AssistantMessageSchema:()=>Xe.lK,AuthenticationError:()=>a.v3,ConfigurationError:()=>a.j1,ConversationStepSchema:()=>ze,ConversationTurnSchema:()=>We,Cursor:()=>Me,CursorAgentError:()=>a.ud,CursorAgentPlatform:()=>or,CursorSdkError:()=>a.LF,DEFAULT_LOGIN_API_KEY_TTL_MS:()=>w,DeleteNotSupportedError:()=>B.x$,EditError:()=>B.F,FILE_SYSTEM_SCAN_LIMIT:()=>H.H,FeatureUnavailableError:()=>a.zz,FileCredentialStore:()=>u.Tg,FileNotFoundError:()=>B.kG,ImageSchema:()=>Xe.JY,InMemoryCredentialStore:()=>u.fZ,InMemoryRunEventNotifier:()=>Cr,IntegrationNotConnectedError:()=>a.VW,InteractionUpdateSchema:()=>Qe.Zs,InvalidGrepPatternError:()=>B.kp,JSONL_LOCAL_AGENT_STORE_FILES:()=>ge,JsonlLocalAgentStore:()=>we,LOCAL_RUN_STREAM_EVENT_TYPE:()=>W.do,LOCAL_RUN_STREAM_SCHEMA_VERSION:()=>W.MV,LocalRunEventNotifier:()=>kr,LocalRunEventNotifierServer:()=>Er,MessageSchema:()=>Xe.RB,ModelCallCompletedUpdateSchema:()=>Qe.Dx,NestedTaskUpdateSchema:()=>Qe.tq,NetworkError:()=>a.Dr,NoMountError:()=>B.VV,PartialToolCallUpdateSchema:()=>Qe.ON,PathError:()=>B.ER,RateLimitError:()=>a.OE,ReadOnlyMountError:()=>B.QK,SdkAssistantMessageSchema:()=>Ne,SdkThinkingMessageSchema:()=>Ge,SdkUserMessageSchema:()=>Le,ShellCommandSchema:()=>Fe,ShellConversationTurnSchema:()=>He,ShellOutputDeltaUpdateSchema:()=>Qe.M7,ShellOutputSchema:()=>Ke,SummaryCompletedUpdateSchema:()=>Qe.uj,SummaryStartedUpdateSchema:()=>Qe.Wf,SummaryUpdateSchema:()=>Qe.XP,TextDeltaUpdateSchema:()=>Qe.yP,ThinkingCompletedUpdateSchema:()=>Qe.Y3,ThinkingDeltaUpdateSchema:()=>Qe.p$,TokenDeltaUpdateSchema:()=>Qe.IO,ToolCallCompletedUpdateSchema:()=>Qe.EC,ToolCallDeltaUpdateSchema:()=>Qe.fr,ToolCallStartedUpdateSchema:()=>Qe.a7,TurnEndedUpdateSchema:()=>Qe.Ed,UnknownAgentError:()=>a.c$,UnsupportedRunOperationError:()=>_t,UserMessageAppendedUpdateSchema:()=>Qe.Sb,UserMessageSchema:()=>Xe.Kx,WriteFailedError:()=>B.JA,childOverlayFs:()=>q.w1,composeLocalAgentStore:()=>Rt.In,configureCursorSdk:()=>$r.xP,convertConnectError:()=>a.e_,convertError:()=>a.q3,createAgentPlatform:()=>cr,createFileSystemTools:()=>D,createInMemoryRunEventNotifier:()=>Ar,createLocalRunEventNotifier:()=>Tr,createSdkMessageRunStreamEvent:()=>W.Nk,decodeLocalRunStreamEvent:()=>W.LN,decodeSdkMessageRunStreamEvent:()=>W.bM,emptyFs:()=>O.f1,getDefaultSdkAuthPath:()=>u.rJ,getDefaultSdkStateRoot:()=>Ct.V,getTurnType:()=>Ve,isAssistantMessage:()=>Xe.mj,isFileNotFoundError:()=>B.Wp,isInvalidGrepPatternError:()=>B.q_,isMessage:()=>Xe.K8,isTerminalLocalRunStreamEvent:()=>W.J5,isUserMessage:()=>Xe.d0,localRunStreamEventToSdkMessage:()=>W.xc,overlayFs:()=>q.Mb,paginateAgentDocuments:()=>Rt.tg,paginateCheckpointBlobIds:()=>Rt.Jg,paginateRunDocuments:()=>Rt.f1,readOnlyFs:()=>O.iK,remapPathError:()=>B.Zu,startLocalRunEventNotifierServer:()=>Ur,strReplaceOnFileSystem:()=>O.i$,tempFs:()=>O.Om,unionFs:()=>q.VL,wrapSdkError:()=>a.Nt});var a=i("./src/agent/errors.ts"),u=i("./src/agent/auth/credential-store.ts"),c=i("node:os"),l=i("./src/agent/auth/login-flow.ts"),m=i("../proto/dist/generated/aiserver/v1/dashboard_service_connect.js"),f=i("../proto/dist/generated/aiserver/v1/dashboard_pb.js"),d=i("@connectrpc/connect"),p=i("./src/agent/transport.ts");var h=i("node:child_process"),g=i("node:path");function _(t){try{const r=new URL(t);return"http:"===r.protocol||"https:"===r.protocol}catch{return!1}}var J=i("./src/agent/auth/stored-credentials.ts");const w=7776e6;function y(){return new u.Tg}function S(){let t;try{t=(0,c.hostname)()}catch{t="unknown-host"}return`Cursor SDK login (${t})`}var q=i("./src/agent/filesystem/compose.ts"),B=i("./src/agent/filesystem/errors.ts"),I=i("../context/dist/core.js"),P=i("../proto/dist/generated/agent/v1/delete_exec_pb.js"),b=i("../proto/dist/generated/agent/v1/grep_exec_pb.js"),R=i("../proto/dist/generated/agent/v1/ls_exec_pb.js"),v=i("../proto/dist/generated/agent/v1/read_exec_pb.js"),x=i("../proto/dist/generated/agent/v1/write_exec_pb.js"),k=i("./src/agent/filesystem/executors.ts"),E=i("./src/agent/filesystem/walk.ts");const C=5,T=200;function U(t){const r="/"===t.parent?"/":`${t.parent}/`;if(!t.entryPath.startsWith(r))return;const e=t.entryPath.slice(r.length),n=e.indexOf("/"),s=-1===n?e:e.slice(0,n);return""===s?void 0:s}function A(t){const r=g.posix.basename(t.replace(/\/$/,"")),e=r.lastIndexOf(".");return e>0?r.slice(0,e):r}function $(t,r){return t.startsWith(r)||r.startsWith(t)}function M(t,r){const e=Array.from({length:r.length+1},((t,r)=>r));for(let n=0;nasync function({executors:t,fs:r},e){const n=e.requiredString(["path","target_file","file_path"]),s=e.optionalInteger(["offset"]),i=e.optionalInteger(["limit"]);void 0!==i&&i<1&&e.invalid("limit must be at least 1");const o={type:"read",args:{path:n}},a=(await t.read.execute(N,new v.a2({path:n,offset:0===s?1:s,limit:i}))).result;switch(a.case){case"success":{const{value:t}=a;return(void 0!==s||void 0!==i)&&!t.rangeApplied&&"content"===t.output.case&&t.totalLines>0?{...o,result:K({message:`Offset ${s} is beyond file length (${t.totalLines} lines)`,path:t.path})}:{...o,result:{status:"success",value:{content:"content"===t.output.case?t.output.value:"",totalLines:t.totalLines,fileSize:Number(t.fileSize)}}}}case"error":return{...o,result:K({message:a.value.error,path:a.value.path})};case"fileNotFound":{const t=await async function(t,r){const e=(0,E.eI)(r),n=function(t){const r=g.posix.dirname(t);return"."===r||r===t?"/":r}(e),s=g.posix.basename(e),i=new Set;try{for await(const r of t.list(n,{maxDepth:1,limit:T})){const t=U({entryPath:(0,E.eI)(r.path),parent:n});void 0!==t&&t!==s&&i.add("directory"===r.kind?`${t}/`:t)}}catch{return}const o=function(t){const r=A(t.query);return[...t.names].sort(((t,e)=>{const n=A(t),s=A(e),i=$(r,n)?0:1,o=$(r,s)?0:1;if(i!==o)return i-o;const a=M(r,n)-M(r,s);return 0!==a?a:t.localeCompare(e)}))}({query:s,names:[...i]}).slice(0,C);if(0!==o.length)return`not found: ${e}. nearest: ${o.join(", ")}. do not retry.`}(r,a.value.path);return{...o,result:K({message:t??"File not found",path:a.value.path})}}case"permissionDenied":return{...o,result:K({message:"Permission denied",path:a.value.path})};case"invalidFile":return{...o,result:K({message:`${a.value.reason}: ${n}`,path:a.value.path})};case"rejected":return{...o,result:K({message:a.value.reason,path:a.value.path})};case void 0:return{...o,result:K({message:"read failed",path:n})};default:return a}}({executors:n,fs:t},new z("Read",r))},Write:{name:"Write",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},execute:t=>async function(t,r){const e=r.requiredString(["path","file_path","target_file"]),n=r.requiredString(["contents","fileText","file_text","content"],{allowEmpty:!0}),s={type:"edit",args:{path:e}},i=(await t.write.execute(N,new x.hY({path:e,fileText:n}))).result;switch(i.case){case"success":return{...s,result:{status:"success",value:{}}};case"error":case"permissionDenied":return{...s,result:K({message:i.value.error,path:i.value.path})};case"rejected":return{...s,result:K({message:i.value.reason,path:i.value.path})};case"noSpace":return{...s,result:K({message:"No space left",path:i.value.path})};case void 0:return{...s,result:K({message:"write failed",path:e})};default:return i}}(n,new z("Write",t))},StrReplace:{name:"StrReplace",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},execute:r=>async function({fs:t,workspace:r},e){const n=(0,k.mv)({workspace:r,path:e.requiredString(["path","file_path","target_file"])}),s=e.requiredString(["old_string","oldText"],{allowEmpty:!0}),i=e.requiredString(["new_string","newText"],{allowEmpty:!0}),o=e.optionalBoolean(["replace_all","replaceAll"]),a={type:"edit",args:{path:n}};try{await(0,O.i$)(t,{path:n,oldText:s,newText:i,replaceAll:o})}catch(t){if(t instanceof B.ER)return{...a,result:K({message:t.message,path:t.path})};throw t}return{...a,result:{status:"success",value:{}}}}({fs:t,workspace:e},new z("StrReplace",r))},LS:{name:"LS",annotations:{readOnlyHint:!0,openWorldHint:!1},execute:t=>async function({executors:t,workspace:r},e){const n=e.optionalString(["target_directory","path"])??r,s=e.optionalStringArray(["ignore_globs","ignore"])??[],i=await t.ls.execute(N,new R.xe({path:n,ignore:s})),o={type:"ls",args:s.length>0?{path:n,ignore:s}:{path:n}},a=i.result;if("success"===a.case&&void 0!==a.value.directoryTreeRoot)return{...o,result:{status:"success",value:{directoryTreeRoot:G(a.value.directoryTreeRoot)}}};const u="error"===a.case?a.value.error:"rejected"===a.case?a.value.reason:"list failed";return{...o,result:K({message:u})}}({executors:n,workspace:e},new z("LS",t))},Grep:{name:"Grep",annotations:{readOnlyHint:!0,openWorldHint:!1},execute:t=>async function(t,r){const e={pattern:r.requiredString(["pattern"],{allowEmpty:!0}),path:r.optionalString(["path"]),glob:r.optionalString(["glob"]),outputMode:r.optionalString(["output_mode","outputMode"]),contextBefore:r.optionalInteger(["-B","contextBefore"]),contextAfter:r.optionalInteger(["-A","contextAfter"]),context:r.optionalInteger(["-C","context"]),caseInsensitive:r.optionalBoolean(["-i","caseInsensitive"]),type:r.optionalString(["type"]),headLimit:r.optionalInteger(["head_limit","headLimit"]),offset:r.optionalInteger(["offset"]),multiline:r.optionalBoolean(["multiline"])},n=await t.grep.execute(N,new b.Qj(e));return{type:"grep",args:(s=e,Object.fromEntries(Object.entries(s).filter((([,t])=>void 0!==t)))),result:L(n)};var s}(n,new z("Grep",t))},Glob:{name:"Glob",annotations:{readOnlyHint:!0,openWorldHint:!1},execute:t=>async function({executors:t,workspace:r},e){const n=e.requiredString(["glob_pattern","globPattern"]),s=e.optionalString(["target_directory","targetDirectory","path"]),i={type:"glob",args:void 0===s?{globPattern:n}:{globPattern:n,targetDirectory:s}},o=function(t){let r=t.replace(/\\/g,"/");return r.startsWith("/")&&(r=r.slice(1)),r.endsWith("/")&&(r=r.slice(0,-1)),r.startsWith("**/")?r:`**/${r}`}(n);if("**/"===o)return{...i,result:K({message:'glob_pattern is empty. Pass "*" to match every file.'})};const a=(await t.grep.execute(N,new b.Qj({pattern:"",path:s,glob:o,outputMode:"files_with_matches"}))).result;if("success"!==a.case)return{...i,result:K({message:"error"===a.case?a.value.error:"glob failed"})};const u=Object.values(a.value.workspaceResults)[0]?.result;if("files"!==u?.case)return{...i,result:K({message:"glob failed"})};const c=void 0===s?void 0:(0,k.mv)({workspace:r,path:s});return{...i,result:{status:"success",value:{files:u.value.files.map((t=>void 0===c?t:g.posix.relative(c,t)||g.posix.basename(t))),totalFiles:u.value.totalFiles,clientTruncated:u.value.clientTruncated,ripgrepTruncated:u.value.ripgrepTruncated}}}}({executors:n,workspace:e},new z("Glob",t))},Delete:{name:"Delete",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},execute:t=>async function(t,r){const e=r.requiredString(["path","target_file"]),n={type:"delete",args:{path:e}},s=(await t.delete.execute(N,new P.dn({path:e}))).result;switch(s.case){case"success":return{...n,result:{status:"success",value:{fileSize:Number(s.value.fileSize)}}};case"fileNotFound":return{...n,result:K({message:"File not found",path:s.value.path})};case"notFile":return{...n,result:K({message:`Path is a ${s.value.actualType}, not a file`,path:s.value.path})};case"permissionDenied":return{...n,result:K({message:s.value.clientVisibleError,path:s.value.path})};case"fileBusy":return{...n,result:K({message:"File is busy",path:s.value.path})};case"rejected":return{...n,result:K({message:s.value.reason,path:s.value.path})};case"error":return{...n,result:K({message:s.value.error,path:s.value.path})};case void 0:return{...n,result:K({message:"delete failed",path:e})};default:return s}}(n,new z("Delete",t))}}}const N=(0,I.q6)();function G(t){return{absPath:t.absPath,childrenDirs:t.childrenDirs.map(G),childrenFiles:t.childrenFiles.map((t=>({name:t.name}))),childrenWereProcessed:t.childrenWereProcessed,fullSubtreeExtensionCounts:{...t.fullSubtreeExtensionCounts},numFiles:t.numFiles}}function L(t){const r=t.result;if("success"!==r.case)return K({message:"error"===r.case?r.value.error:"grep failed"});const e={};for(const[t,n]of Object.entries(r.value.workspaceResults)){const r=F(n);void 0!==r&&(e[t]=r)}return{status:"success",value:{workspaceResults:e}}}function F(t){const r=t.result;switch(r.case){case"content":return{type:"content",output:{matches:r.value.matches.flatMap((t=>function(t){const r=t.matches,e=[];return r.forEach(((n,s)=>{if(n.isContextLine)return;const i=j({rows:r,from:s,step:-1}),o=j({rows:r,from:s,step:1});e.push({file:t.file,lineNumber:n.lineNumber,line:n.content,...i.length>0?{beforeContext:i}:{},...o.length>0?{afterContext:o}:{}})})),e}(t))),totalMatches:r.value.totalMatchedLines}};case"files":return{type:"files",output:{files:r.value.files,count:r.value.totalFiles}};case"count":return{type:"count",output:{counts:r.value.counts.map((t=>({file:t.file,count:t.count}))),total:r.value.totalMatches}};case void 0:return;default:return r}}function K(t){return{status:"error",error:t}}class z{constructor(t,r){this.toolName=t,this.input=r}invalid(t){throw new a.j1(`Invalid ${this.toolName} input: ${t}`,{isRetryable:!1})}requiredString(t,r){const e=this.optionalString(t);return void 0===e||""===e&&!0!==r?.allowEmpty?this.invalid(`${t[0]} is required`):e}optionalString(t){return this.read(t,"a string",(t=>"string"==typeof t?t:void 0))}optionalInteger(t){return this.read(t,"an integer",(t=>"number"==typeof t&&Number.isInteger(t)?t:void 0))}optionalBoolean(t){return this.read(t,"a boolean",(t=>"boolean"==typeof t?t:void 0))}optionalStringArray(t){return this.read(t,"an array of strings",(t=>Array.isArray(t)&&t.every((t=>"string"==typeof t))?t.map(String):void 0))}read(t,r,e){for(const n of t){const t=this.input[n];if(null==t)continue;const s=e(t);return void 0===s?this.invalid(`${n} must be ${r}`):s}}}function j(t){const r=[];let e=(t.rows[t.from]?.lineNumber??0)+t.step;for(let n=t.from+t.step;n>=0&&n{(0,h.execFile)(t,r,{cwd:e,timeout:1e4},((r,e)=>{if(r){const e=function(t){if("code"in t)return"string"==typeof t.code?t.code:void 0}(r);return"ENOENT"!==e&&"127"!==e||at.set(t,Date.now()+3e4),void n(null)}n({stdout:e})}))}))}function lt(t,r){try{const r=new URL(t),e=r.host.toLowerCase();if(ut.has(e))return r.pathname.startsWith("/github/")?"github":"origin";if(e.includes("github"))return"github"}catch{}return r}async function mt(t){if(function(t){const r=at.get(t);return void 0!==r&&Date.now()async function(t){const r=await async function(t){const r=await ct("git",["rev-parse","--abbrev-ref","HEAD"],t),e=r?.stdout.trim();return e&&"HEAD"!==e?e:null}(t);return r?(await Promise.all([ft({cwd:t,branch:r}),dt({cwd:t,branch:r})])).filter((t=>null!==t)):[]}(t)))),e=new Map;for(const t of r.flat())e.has(t.url)||e.set(t.url,t);return[...e.values()]}catch{return[]}}(t.cwds);for(const e of r){const r=`${t.agentId}\0${e.url}`;ht.has(r)||(ht.add(r),(0,rt.id)(t.apiKey,{agent_id:t.agentId,run_id:t.runId,request_id:t.requestId,runtime:t.runtime,pr_url:e.url,pr_number:e.number,branch:e.branch,code_forge:e.codeForge,creation_path:"shell_cli",pr_created_at:e.createdAt}))}}catch{}}class _t extends a.j1{constructor(t,r){super(r??`Run operation "${t}" is not supported`,{operation:`run.${t}`,isRetryable:!1}),this.name="UnsupportedRunOperationError"}}var Jt=i("./src/agent/utils/logger.ts");class wt{constructor(t){this.eventStore=t.eventStore,this.eventStreamStore=t.eventStreamStore??(t.eventNotifier?new yt(t.eventStore,t.eventNotifier):void 0),this.eventNotifier=t.eventNotifier,this.loadRunStatus=t.loadRunStatus,this.defaultPollIntervalMs=t.defaultPollIntervalMs??250}async*streamRunEvents(t,r={}){const e=r.mode??"replay";r.limit,It(r.signal),"replay"!==e&&this.eventStreamStore?yield*this.streamAttachedRunEvents(t,r):yield*this.streamPolledRunEvents(t,r)}async*streamAttachedRunEvents(t,r){const e=r.mode??"replay-and-tail",n=r.limit,s=r.signal;let i=r.afterOffset;"tail"!==e||i||(i=await this.drainExistingEvents(t,n,s));try{for await(const r of this.eventStreamStore.attachRunEvents({runId:t,afterOffset:i,signal:s})){It(s),i=r.offset;const t=this.decodeRunEventRecord(r);if(!t)continue;const e=(0,W.xc)(t);if(e&&(yield e),(0,W.J5)(t))return}}catch(t){if(s?.aborted)throw Pt(s);if(!this.eventNotifier)throw t}await this.isTerminalAndDrained(t,i,n)||(yield*this.streamPolledRunEvents(t,{...r,afterOffset:i}))}async*streamPolledRunEvents(t,r){const e=r.mode??"replay",n=r.limit,s=r.pollIntervalMs??this.defaultPollIntervalMs,i=r.signal;It(i);let o,a,u=r.afterOffset;"tail"!==e||u||(u=await this.drainExistingEvents(t,n,i));try{for("replay"!==e&&this.eventNotifier&&(o=Bt(i),a=function(t){if(!t)return;t.ready?.catch((()=>{}));const r=t[Symbol.asyncIterator](),e=()=>r.next().then((t=>t.done?"closed":"wakeup"),(()=>"error"));let n=e();return{async wait(){const t=n;return n=t.then((()=>e())),t},async close(){o?.abort(),await n.catch((()=>{})),await(r.return?.().catch((()=>{})))}}}(this.eventNotifier.subscribeRunEvents({runId:t,signal:o.signal})));;){It(i);const r=await this.listAvailableEvents({runId:t,afterOffset:u,pageLimit:n,signal:i});u=r.afterOffset;for(const t of r.events)yield t;if(r.sawTerminalEvent)return;if("replay"===e)return;if(await this.isTerminalAndDrained(t,u,n))return;"wakeup"!==await qt({wakeups:a,pollIntervalMs:s,signal:i})&&(await(a?.close()),a=void 0)}}finally{await(a?.close()),o?.abort()}}async drainExistingEvents(t,r,e){let n;for(;;){It(e);const s=await this.eventStore.listRunEvents({runId:t,afterOffset:n,limit:r});for(const t of s.events)n=t.offset;if(!s.nextOffset)return n}}async listAvailableEvents(t){const r=[];let e=!1,n=t.afterOffset;for(;;){It(t.signal);const s=await this.eventStore.listRunEvents({runId:t.runId,afterOffset:n,limit:t.pageLimit});for(const t of s.events){n=t.offset;const s=this.decodeRunEventRecord(t);if(!s)continue;const i=(0,W.xc)(s);i&&r.push(i),e||=(0,W.J5)(s)}if(!s.nextOffset)return{afterOffset:n,events:r,sawTerminalEvent:e}}}decodeRunEventRecord(t){try{return(0,W.LN)(t.payload)}catch(r){return void Jt.v.log(`Skipping unsupported local run event for run ${t.runId} at offset ${t.offset}: ${r instanceof Error?r.message:String(r)}`)}}async isTerminalAndDrained(t,r,e){if((await this.eventStore.listRunEvents({runId:t,afterOffset:r,limit:e})).events.length>0)return!1;const n=await this.loadRunStatus(t);return!(!n||!(0,Y.Qb)(n))}}class yt{constructor(t,r){this.eventStore=t,this.eventNotifier=r}appendRunEvent(t){return this.eventStore.appendRunEvent(t)}listRunEvents(t){return this.eventStore.listRunEvents(t)}async*attachRunEvents(t){const r=Bt(t.signal),e=this.eventNotifier.subscribeRunEvents({runId:t.runId,signal:r.signal}),n=e[Symbol.asyncIterator]();let s,i=t.afterOffset??void 0;try{for(;;){It(t.signal),i=yield*St(this.eventStore,t.runId,i,t.signal);const r=(s??=n.next(),s);await e.ready,i=yield*St(this.eventStore,t.runId,i,t.signal);const o=await r;if(s=void 0,o.done)return}}finally{r.abort(),await(s?.catch((()=>{}))),await(n.return?.().catch((()=>{})))}}}async function*St(t,r,e,n){let s=e;for(;;){It(n);const e=await t.listRunEvents({runId:r,afterOffset:s});for(const t of e.events)s=t.offset,yield t;if(!e.nextOffset)return s}}async function qt(t){It(t.signal);const r=Bt(t.signal),e=[(n=t.pollIntervalMs,s=r.signal,n<=0?Promise.resolve():new Promise(((t,r)=>{const e=setTimeout((function(){o(),t()}),n),i=()=>{clearTimeout(e),o(),r(Pt(s))};function o(){s?.removeEventListener("abort",i)}s?.addEventListener("abort",i,{once:!0})}))).then((()=>"poll"))];var n,s;t.wakeups&&e.push(t.wakeups.wait());try{const r=await Promise.race(e);return It(t.signal),"poll"===r?"wakeup":r}finally{r.abort()}}function Bt(t){const r=new AbortController;if(!t)return r;if(t.aborted)return r.abort(t.reason),r;const e=()=>{r.abort(t.reason)};return t.addEventListener("abort",e,{once:!0}),r.signal.addEventListener("abort",(()=>{t.removeEventListener("abort",e)}),{once:!0}),r}function It(t){if(t?.aborted)throw Pt(t)}function Pt(t){const r=t?.reason;return r instanceof Error?r:new Error("Run event stream aborted")}var bt=i("./src/agent/run-interaction-accumulator.ts"),Rt=i("./src/agent/store/local-agent-store.ts");const vt="Default local agent storage requires the built-in node:sqlite module (Node >= 22.13, or another runtime that implements node:sqlite). Upgrade Node, or configure a custom store: Cursor.configure({ local: { store: new JsonlLocalAgentStore(rootDir) } }) or pass local.store / store on Agent.create and Agent.resume.";function xt(t){if("NoSqliteDriverError"===function(t){if("object"==typeof t&&null!==t&&"name"in t)return"string"==typeof t.name?t.name:void 0}(t))return!0;if("ERR_UNKNOWN_BUILTIN_MODULE"===function(t){if("object"==typeof t&&null!==t&&"code"in t)return"string"==typeof t.code?t.code:void 0}(t))return!0;const r=function(t){return t instanceof Error||"object"==typeof t&&null!==t&&"message"in t&&"string"==typeof t.message?t.message:void 0}(t)?.toLowerCase();return r?.includes("node:sqlite")??!1}function kt(t){return new a.j1(vt,{isRetryable:!1,cause:t})}var Et=i("./src/agent/store/sdk-local-defaults.ts"),Ct=i("./src/agent/store/sdk-state-root.ts"),Tt=i("./src/agent/subagent-conversion.ts"),Ut=i("./src/agent/team-id.ts"),At=i("./src/agent/tool-call-utils.ts"),$t=i("./src/agent/tools-option.ts"),Mt=i("./src/agent/filesystem/local-fs.ts");const Ot={read_tool_call:"fs",edit_tool_call:"fs",delete_tool_call:"fs",ls_tool_call:"fs",grep_tool_call:"fs",glob_tool_call:"fs",task_tool_call:"fs",await_tool_call:"fs",generate_image_tool_call:"fs",update_todos_tool_call:"file-free",read_todos_tool_call:"file-free",ask_question_tool_call:"file-free",create_plan_tool_call:"file-free",switch_mode_tool_call:"file-free",web_search_tool_call:"file-free",web_fetch_tool_call:"file-free",fetch_tool_call:"file-free",mcp_tool_call:"file-free",get_mcp_tools_tool_call:"file-free",list_mcp_resources_tool_call:"file-free",read_mcp_resource_tool_call:"file-free",mcp_auth_tool_call:"file-free"},Dt={shell_tool_call:"it runs host processes",write_shell_stdin_tool_call:"it drives host shells",read_lints_tool_call:"it reads host diagnostics",sem_search_tool_call:"semantic search is not available to local agents",apply_agent_diff_tool_call:"it applies a subagent's changes to the host working tree",record_screen_tool_call:"it records the host display",computer_use_tool_call:"it drives the host display and input devices"};let Nt;var Gt=i("./src/agent/usage-types.ts");class Lt{constructor(){this.queue=[],this.waiters=[],this.closed=!1}push(t){if(this.closed)return;const r=this.waiters.shift();if(!r)return this.queue.length>=8192?(this.overflow=new a.LF("Live run event buffer overflow; consumer is too slow",{code:"stream_buffer_overflow",errorName:"CursorSdkError"}),void(this.closed=!0)):void this.queue.push(t);r({value:t,done:!1})}close(){if(!this.closed)for(this.closed=!0;this.waiters.length>0;){const t=this.waiters.shift();t?.({value:void 0,done:!0})}}async*stream(){for(;;){const t=this.queue.shift();if(t){yield t;continue}if(this.overflow)throw this.overflow;if(this.closed)return;const r=await new Promise((t=>{this.waiters.push(t)}));if(r.done)return;yield r.value}}}class Ft{constructor(t,r,e,n,s,i,o={}){this.id=t,this.agentId=r,this.controller=e,this.eventBuffer=n,this.store=s,this.emitStatus=i,this.git=void 0,this.terminalMetadataHydrated=!1,this.listeners=new Set,this.requestId=o.requestId??void 0,this.model=o.model,this.currentStatus=o.initialStatus??"running",this.createdAt=o.createdAt?.getTime(),this._result=void 0,this._error=void 0,this._durationMs=void 0,this.liveTerminal=o.liveTerminal??{},this.cancellationState=o.cancellationState??{cancelled:!1},this.waitForTerminalStatus=o.waitForTerminalStatus,this.conversationPromise=o.conversation??Promise.resolve([]),this.waitForTerminalStatus?this.waitForTerminalStatus.then((async t=>{this.setStatus(t),this.captureLiveUsage(),await this.refreshTerminalMetadataFromStore()})).catch((async t=>{this.cancellationState.cancelled||"cancelled"===this.currentStatus||(this._error=(0,a.D7)(t),this.setStatus("error")),this.captureLiveUsage(),await this.refreshTerminalMetadataFromStore()})).finally((()=>this.eventBuffer.close())):o.trackController??1?this.controller.done.then((async()=>{this.cancellationState.cancelled||"cancelled"===this.currentStatus||this.setStatus("finished"),this.captureLiveUsage(),await this.refreshTerminalMetadataFromStore()})).catch((async t=>{this.cancellationState.cancelled||"cancelled"===this.currentStatus||(this._error=(0,a.D7)(t),this.setStatus("error")),this.captureLiveUsage(),await this.refreshTerminalMetadataFromStore()})).finally((()=>this.eventBuffer.close())):"running"!==this.currentStatus&&this.eventBuffer.close()}supports(t){return"stream"===t||"wait"===t||"conversation"===t||"cancel"===t}unsupportedReason(t){if(!this.supports(t))return`Unknown run operation "${t}"`}stream(){try{return this.eventBuffer.stream()}catch(t){throw(0,a.Nt)(t,{operation:"run.stream"})}}async conversation(){try{return await this.conversationPromise}catch(t){throw(0,a.Nt)(t,{operation:"run.conversation"})}}async wait(){try{const t=t=>(this.captureLiveUsage(),{id:this.id,...void 0!==this.requestId?{requestId:this.requestId}:{},status:t,...void 0!==this._result?{result:this._result}:{},..."error"===t&&void 0!==this._error?{error:this._error}:{},...void 0!==this.model?{model:this.model}:{},...void 0!==this._durationMs?{durationMs:this._durationMs}:{},...void 0!==this._usage?{usage:this._usage}:{}});if("running"!==this.currentStatus)return await this.controller.done.catch((()=>{})),await this.refreshTerminalMetadataFromStore(),t(this.currentStatus);if(this.waitForTerminalStatus){const r=await this.waitForTerminalStatus;return await this.refreshTerminalMetadataFromStore(),t(r)}try{return await this.controller.done,await this.refreshTerminalMetadataFromStore(),void 0===this._result&&await this.refreshTerminalMetadataFromStore(),t("running"!==this.currentStatus?this.currentStatus:"finished")}catch(r){return this.cancellationState.cancelled?(await this.refreshTerminalMetadataFromStore(),this._error=void 0,t("cancelled")):(this._error??=(0,a.D7)(r),await this.refreshTerminalMetadataFromStore(),t("error"))}}catch(t){throw(0,a.Nt)(t,{operation:"run.wait"})}}async steer(t){try{return await(this.controller.steer?.(t))??"revert_to_followup"}catch(t){throw(0,a.Nt)(t,{operation:"run.steer"})}}async cancel(){try{if("running"!==this.currentStatus)return;this.cancellationState.cancelled=!0,this.setStatus("cancelled"),await this.emitStatus("CANCELLED"),this.controller.abort(),await this.store.cancelRun(this.agentId,this.id),await this.refreshTerminalMetadataFromStore()}catch(t){throw(0,a.Nt)(t,{operation:"run.cancel"})}}get status(){return this.currentStatus}get result(){return this._result}get error(){return"error"===this.currentStatus?this._error:void 0}get durationMs(){return this._durationMs}get usage(){return this.captureLiveUsage(),this._usage}onDidChangeStatus(t){return this.listeners.add(t),()=>this.listeners.delete(t)}setStatus(t){this.currentStatus!==t&&(this.currentStatus=t,this.listeners.forEach((r=>{r(t)})))}captureLiveUsage(){void 0===this._usage&&void 0!==this.liveTerminal.usage&&(this._usage=this.liveTerminal.usage)}async refreshTerminalMetadataFromStore(){if(!this.terminalMetadataHydrated)try{const t=await this.store.getRun(this.agentId,this.id),r=t?.result??null;null!=r&&(this._result=r),void 0===this._error&&t?.errorCode&&(this._error=(0,a.vg)(t.errorCode));const e=t?Rr(t):void 0;if(void 0!==e&&(this._durationMs=e),void 0===this._usage){const r=t?.usage??null;null!=r&&(this._usage=r)}const n=t?.status;"FINISHED"===n&&null==r||"FINISHED"!==n&&"ERROR"!==n&&"CANCELLED"!==n&&"EXPIRED"!==n||(this.terminalMetadataHydrated=!0)}catch(t){Jt.v.log(`Failed to hydrate terminal metadata for run ${this.id}: ${t instanceof Error?t.message:String(t)}`)}}}class Kt{constructor(t,r,e,n,s,i,o,a,u,c,l,m){this.id=t,this.agentId=e,this.currentStatus=n,this.result=o,this.error=a,this.durationMs=u,this.store=l,this.streamFactory=m,this.git=void 0,this.requestId=r??void 0,this.createdAt=s?.getTime(),this.model=i,this.usage=c??void 0}supports(t){return"stream"===t?void 0!==this.streamFactory:"wait"===t?"running"!==this.currentStatus:"conversation"===t?void 0!==this.streamFactory:"cancel"===t&&"running"===this.currentStatus}unsupportedReason(t){if(!this.supports(t))return"stream"===t?"Cannot stream this run because no run event store is configured":"wait"===t?"Cannot wait on a detached running run":"cancel"===t?"Cannot cancel a detached run that is already terminal":"conversation"===t?"Cannot reconstruct this run conversation because no run event store is configured":"Unknown run operation"}stream(){try{if(!this.streamFactory)throw new _t("stream",this.unsupportedReason("stream"));return this.streamFactory()}catch(t){throw(0,a.Nt)(t,{operation:"run.stream"})}}async conversation(){try{if(!this.streamFactory)throw new _t("conversation",this.unsupportedReason("conversation"));return(0,bt.KG)(this.streamFactory())}catch(t){throw(0,a.Nt)(t,{operation:"run.conversation"})}}async wait(){try{if("running"===this.currentStatus)throw new _t("wait",this.unsupportedReason("wait"));return{id:this.id,...void 0!==this.requestId?{requestId:this.requestId}:{},status:this.currentStatus,...void 0!==this.result?{result:this.result}:{},...void 0!==this.error?{error:this.error}:{},...void 0!==this.model?{model:this.model}:{},...void 0!==this.durationMs?{durationMs:this.durationMs}:{},...void 0!==this.usage?{usage:this.usage}:{}}}catch(t){throw(0,a.Nt)(t,{operation:"run.wait"})}}async steer(t){return"revert_to_followup"}async cancel(){try{if("running"!==this.currentStatus)return;await this.store.cancelRun(this.agentId,this.id),this.currentStatus="cancelled"}catch(t){throw(0,a.Nt)(t,{operation:"run.cancel"})}}get status(){return this.currentStatus}onDidChangeStatus(t){return()=>{}}}function zt(t){const r=Ir(t)??process.cwd(),e=Pr(t,r),n=(0,Ut.E)(t.teamId);return{workingDirectory:r,...void 0!==e?{dirs:e}:{},apiKey:t.apiKey,...void 0!==n?{teamId:n}:{},settingSources:t.local?.settingSources,sandboxOptions:t.local?.sandboxOptions,autoReview:t.local?.autoReview,enableAgentRetries:t.local?.enableAgentRetries,...void 0!==t.local?.hostMcpBridgeUrls?{hostMcpBridgeUrls:t.local.hostMcpBridgeUrls}:{},devForceNextSmartModeClassifierBlockToken:process.env.CURSOR_SDK_DEV_FORCE_NEXT_SMART_MODE_CLASSIFIER_BLOCK_TOKEN,mcpServers:t.mcpServers,customSubagents:t.customSubagents??(0,Tt.DB)(t.agents)}}function jt(t,r){const e=r?.resourceProviderOptions??t?.resourceProviderOptions,n=r?.reportedWorkspacePath??t?.reportedWorkspacePath;return void 0===e&&void 0===n?{}:{sessionResources:{...void 0!==e?{resourceProviderOptions:e}:{},...void 0!==n?{reportedWorkspacePath:n}:{}}}}function Ht(t,r){const e=r?.reportedWorkspacePath??t?.reportedWorkspacePath;return void 0===e?{}:{fileSystemWorkspace:(0,Mt.xh)(e)}}function Wt(t){const r=void 0===t.fileSystem?{allowedTools:t.allowedTools,disallowedTools:t.disallowedTools}:function(t){if(void 0===t.allowedTools){const r=new Set(t.disallowedTools??[]);return{allowedTools:Object.keys(Ot).filter((t=>!r.has(t))),disallowedTools:t.disallowedTools}}const r=t.allowedTools.filter((t=>!(void 0!==Ot[t])));if(r.length>0){const t=r.map((t=>{const r=Dt[t]??"it is not backed by local.fs";return`${function(t){if(void 0===Nt){Nt=new Map;for(const t of Z.Dm_.fields.list())"tool"===t.oneof?.localName&&Nt.set(t.name,t.localName.replace(/ToolCall$/,""))}return Nt.get(t)??t}(t)} (${r})`}));throw new a.j1(`\`tools\` names tools a local.fs agent cannot run: ${t.join(", ")}. Remove them from \`tools\` or omit local.fs.`,{isRetryable:!1})}return{allowedTools:[...t.allowedTools],disallowedTools:t.disallowedTools}}({allowedTools:t.allowedTools,disallowedTools:t.disallowedTools});return{...void 0!==r.allowedTools?{allowedTools:r.allowedTools}:{},...void 0!==r.disallowedTools?{disallowedTools:r.disallowedTools}:{}}}const Qt=new Map,Vt="CURSOR_SDK_LOCAL_MODEL_CATALOG_JSON";function Xt(t){return Array.isArray(t)?t.map(Xt):(0,At.u)(t)?Object.fromEntries(Object.keys(t).sort().map((r=>[r,Xt(t[r])]))):t}function Yt(t){if(!Array.isArray(t))return;const r=[];for(const e of t){if(!(0,At.u)(e)||"string"!=typeof e.displayName||!Array.isArray(e.params))continue;const t=[];for(const r of e.params)(0,At.u)(r)&&"string"==typeof r.id&&"string"==typeof r.value&&t.push({id:r.id,value:r.value});r.push({params:t,displayName:e.displayName,..."string"==typeof e.description?{description:e.description}:{},...!0===e.isDefault?{isDefault:!0}:{},...!0===e.isMaxMode?{isMaxMode:!0}:{}})}return r.length>0?r:void 0}async function Zt(t){(0,ot.configureVendoredTreeSitterWorkspaceDir)(t.workingDirectory);for(const r of t.dirs??[])(0,ot.configureVendoredTreeSitterWorkspaceDir)(r);const r=function(t){return(0,Q.createHash)("sha256").update((r={workingDirectory:t.workingDirectory,dirs:t.dirs,apiKeyHash:void 0===t.apiKey?void 0:(0,Q.createHash)("sha256").update(t.apiKey).digest("hex"),teamId:(0,Ut.E)(t.teamId),settingSources:t.settingSources,mcpServers:t.mcpServers,sandboxOptions:t.sandboxOptions,autoReview:t.autoReview,devForceNextSmartModeClassifierBlockTokenHash:void 0===t.devForceNextSmartModeClassifierBlockToken?void 0:(0,Q.createHash)("sha256").update(t.devForceNextSmartModeClassifierBlockToken).digest("hex"),customSubagents:t.customSubagents,enableAgentRetries:t.enableAgentRetries,hostMcpBridgeUrls:t.hostMcpBridgeUrls},JSON.stringify(Xt(r)))).digest("hex");var r}(t);let e=Qt.get(r),n=!1;if(!e){n=!0;const s={refs:0,promise:Promise.all([i.e(82),i.e(977)]).then(i.bind(i,"./src/agent/local-executor.ts")).then((({createLocalExecutor:r})=>r(t))).catch((t=>{throw Qt.get(r)===s&&Qt.delete(r),t}))};e=s,Qt.set(r,e)}e.refs+=1;let s=!1;try{return{handle:await e.promise,cacheMiss:n,release:async()=>{s||(s=!0,await async function(t,r){if(r.refs-=1,!(r.refs>0||Qt.get(t)!==r)){Qt.delete(t);try{const t=await r.promise;await(t.dispose?.())}catch{}}}(r,e))}}}catch(t){throw e.refs-=1,e.refs<=0&&Qt.get(r)===e&&Qt.delete(r),t}}function tr(t){if("string"!=typeof t)return t.images?.map((t=>{if("url"in t)throw new a.j1("URL images are only supported for cloud SDK agents",{isRetryable:!1});return{type:"base64",data:t.data}}))}const rr="customSubagents",er="initialMode",nr="blobEncryptionKey";function sr(t){const r=t?.[nr];if((0,V.TU)(r))return r;const e=(0,V.sh)("").blobEncryptionKey;if(void 0===e)throw new Error("Failed to generate a blob encryption key");return e}class ir{constructor(t,r,e,n,s){this.agentId=t,this.platform=r,this.options=e,this.firstSendCompletedAfterResume=!1,this._pendingPrAttributions=new Set,this.checkpointPersistChain=Promise.resolve(),this.pendingInitialRunId=n,this._model=e.model,this.catalogResolvedModel=s?.catalogResolvedModel,this.resumedAgent=s?.resumedAgent??!1}get model(){return this._model}async send(t,r={}){let e=!1;try{return await this.sendImpl({text:"string"==typeof t?t:t.text,images:tr(t)},r,(()=>{e=!0}))}catch(t){const r=(0,a.Nt)(t,{operation:"agent.send"});throw e||(0,rt.CI)({apiKey:this.options.apiKey,operation:"agent.send",runtime:"local",error:r}),r}}async resume(__t3o={}){try{const t=await this.platform.store.getAgent(this.agentId);if(null===t)throw new a.XB(`Agent ${this.agentId} not found`,{isRetryable:!1});if(null===t.latestCheckpointRef)throw new a.j1(`Agent ${this.agentId} has no saved conversation to resume yet.`,{isRetryable:!1});return await this.sendImpl({text:"",resume:!0},__t3o,(()=>{}))}catch(t){const r=(0,a.Nt)(t,{operation:"agent.resume"});throw(0,rt.CI)({apiKey:this.options.apiKey,operation:"agent.resume",runtime:"local",error:r}),r}}async summarize(){try{const t=await this.platform.store.getAgent(this.agentId);if(null===t)throw new a.XB(`Agent ${this.agentId} not found`,{isRetryable:!1});if(null===t.latestCheckpointRef)throw new a.j1(`Agent ${this.agentId} has no saved conversation to summarize yet.`,{isRetryable:!1});return await this.sendImpl({summarize:!0},{},(()=>{}))}catch(t){const r=(0,a.Nt)(t,{operation:"agent.summarize"});throw(0,rt.CI)({apiKey:this.options.apiKey,operation:"agent.summarize",runtime:"local",error:r}),r}}async sendImpl(t,r,e){if(void 0!==r.cloud)throw new a.j1("Cloud send options are only supported for cloud SDK agents. Create the agent with cloud options or use local.* send options.",{isRetryable:!1});const n=performance.now(),s=!0===t.summarize,i=r.model??this._model;if(void 0===i)throw new a.j1('Local SDK agents require an explicit `model`. Pass `model: { id: "" }` to Agent.create() or to send(), or run this agent in cloud mode.',{isRetryable:!1});let o;try{o=await this.platform.resolveLocalModelSelection(i,this.options.apiKey,this.options.teamId),this.catalogResolvedModel=it({requested:i,resolved:o})}catch(t){const e=function(t){const r=t.resolved;if(void 0!==r&&r.ids.includes(t.requested.id)&&function(t,r){const e=t.params??[],n=r.params??[];return e.length===n.length&&e.every((t=>n.some((r=>r.id.trim()===t.id.trim()&&r.value.trim()===t.value.trim()))))}(r.selection,t.requested))return r.selection}({requested:i,resolved:this.catalogResolvedModel});if(void 0!==e)o=e;else{if(void 0!==r.model||t instanceof a.j1)throw t;if((i.params?.length??0)>0&&!0!==i.maxMode)throw new a.j1(`The model catalog is unavailable, so ${i.id} could not be checked for max mode. Try again.`,{isRetryable:!0,cause:t});o=i}}const u=this.resumedAgent&&!this.firstSendCompletedAfterResume,c=null===this.pendingInitialRunId,l=!c||u,m=r.mode??(l?this.options.mode:void 0),f=r.local?.fs??this.options.local?.fs;(0,Mt.I2)({fs:f,subagentInherit:r.local?.subagentInherit??this.options.local?.subagentInherit,resourceProviderOptions:r.local?.resourceProviderOptions??this.options.local?.resourceProviderOptions,reportedWorkspacePath:r.local?.reportedWorkspacePath??this.options.local?.reportedWorkspacePath});const d=Wt({fileSystem:f,allowedTools:this.options.allowedProtoTools,disallowedTools:this.options.disallowedProtoTools}),p=(0,tt.C)(),h=await this.getRunForSend(r,o,p),g=r.mcpServers,_=g??this.options.mcpServers,J=(0,et.o)(this.options.name),w=s?void 0:(0,nt.E)(t.text);s||(0,rt.Zn)(this.options.apiKey,{agent_id:this.agentId,run_id:h.runId,...void 0!==J?{agent_name:J}:{},request_id:p,runtime:"local",model:o.id,...o.params&&o.params.length>0?{model_params:JSON.stringify(o.params)}:{},prompt_length:t.text.length,...void 0!==w?{prompt_hash:w}:{},has_images:(t.images?.length??0)>0,is_resume:c,mcp_server_count:Object.keys(_??{}).length}),e();const y={executor_acquire_ms:0,load_latest_ms:0,get_blob_store_ms:0,pre_send_ms:0,time_to_first_message_ms:void 0,cold_executor:!1,turn_count:0};let S=!1;const q=t=>{if(S)return;S=!0;const r={agent_id:this.agentId,run_id:h.runId,request_id:p,runtime:"local",is_resume:this.resumedAgent,is_first_send_after_resume:u,cold_executor:y.cold_executor,executor_acquire_ms:y.executor_acquire_ms,load_latest_ms:y.load_latest_ms,get_blob_store_ms:y.get_blob_store_ms,pre_send_ms:y.pre_send_ms,terminated_reason:t,turn_count:y.turn_count};void 0!==y.time_to_first_message_ms&&(r.time_to_first_message_ms=y.time_to_first_message_ms),(0,rt.pL)(this.options.apiKey,r),u&&(this.firstSendCompletedAfterResume=!0)};let B=!1;const I=(t,r)=>{s||B||(B=!0,(0,rt.G5)(this.options.apiKey,{agent_id:this.agentId,run_id:h.runId,...void 0!==J?{agent_name:J}:{},request_id:p,runtime:"local",end_reason:t,error_code:r,...void 0!==w?{prompt_hash:w}:{}}),q(t))};await this.platform.store.markRunStarting(this.agentId,h.runId,{requestId:p});const P=new Lt,b=new bt.e4({onDelta:r.onDelta,onStep:r.onStep}),R={};let v;const x=async(t,r)=>{!1!==r?.emitLive&&P.push(t);try{await this.platform.appendRunMessage(t)}catch(r){Jt.v.log(`Failed to persist stream event ${t.type} for run ${h.runId}: ${r instanceof Error?r.message:String(r)}`)}},k=async(t,r)=>{const e={type:"status",agent_id:this.agentId,run_id:h.runId,status:t,...void 0!==r?{message:r.message}:{}};await x(e)};let E;await(async()=>{const t={type:"request",agent_id:this.agentId,run_id:h.runId,request_id:p};await x(t,{emitLive:!1})})(),await k("RUNNING");let C,T=()=>{};try{const e=performance.now(),i=await this.platform.checkpointStore.loadLatest(this.agentId),u=i instanceof Z.Y9z?i:new Z.Y9z({});y.load_latest_ms=performance.now()-e;const c=performance.now(),l=await this.platform.checkpointStore.getBlobStore(this.agentId);if("object"!=typeof(U=l)||null===U||!("getBlob"in U)||"function"!=typeof U.getBlob||!("setBlob"in U)||"function"!=typeof U.setBlob)throw new a.j1("Local checkpoint store did not return a blob store",{isRetryable:!1});const _=l;T=(0,X.B_)(_,(t=>{void 0===E&&(E=t,Jt.v.log(t),x({type:"status",agent_id:this.agentId,run_id:h.runId,status:"RUNNING",message:t}))})),y.get_blob_store_ms=performance.now()-c,y.turn_count=u.turns.length;const J=performance.now(),w=void 0!==this.executorLease,S=await this.getExecutor();y.executor_acquire_ms=performance.now()-J,y.cold_executor=!w&&(this.executorLease?.cacheMiss??!1),y.pre_send_ms=performance.now()-n,C=await S.run(t,{apiKey:this.options.apiKey??"",model:o,sessionId:this.agentId,requestId:p,initialState:u,blobStore:_,blobEncryptionKey:this.options.blobEncryptionKey,mcpServersOverride:g,customTools:r.local?.customTools??this.options.local?.customTools,...void 0!==(r.local?.onMcpAuthRequest??this.options.local?.onMcpAuthRequest)?{onMcpAuthRequest:r.local?.onMcpAuthRequest??this.options.local?.onMcpAuthRequest}:{},onConnectionStateChange:r.local?.onConnectionStateChange??this.options.local?.onConnectionStateChange,...void 0!==(r.local?.subagentInherit??this.options.local?.subagentInherit)?{subagentInherit:r.local?.subagentInherit??this.options.local?.subagentInherit}:{},...void 0===f?jt(this.options.local,r.local):{fileSystem:f,...Ht(this.options.local,r.local)},...d,...void 0!==this.options.systemPrompt?{systemPrompt:this.options.systemPrompt}:{},...void 0!==m?{mode:m}:{},onMcpAdminToolLimitCounts:t=>{(0,rt.GY)(this.options.apiKey,{run_id:h.runId,runtime:"local",...t})},onCheckpoint:async t=>{const r=async()=>{try{const r=await this.platform.checkpointStore.saveCheckpoint(this.agentId,t);await this.platform.store.patchCheckpoint(this.agentId,h.runId,r)}catch(t){Jt.v.log(`Failed to persist checkpoint for run ${h.runId}: ${t instanceof Error?t.message:String(t)}`)}},e=this.checkpointPersistChain.then((()=>r()),(()=>r()));this.checkpointPersistChain=e,await e}},{sendUpdate:async t=>{void 0===y.time_to_first_message_ms&&(y.time_to_first_message_ms=performance.now()-n),await b.apply(t),s&&"summary"===t.type&&(v=t.summary);const r=function(t,r,e){switch(t.type){case"user-message-appended":return{type:"user",agent_id:r,run_id:e,message:{role:"user",content:[{type:"text",text:t.userMessage.text}]}};case"text-delta":return{type:"assistant",agent_id:r,run_id:e,message:{role:"assistant",content:[{type:"text",text:t.text}]}};case"thinking-delta":return{type:"thinking",agent_id:r,run_id:e,text:t.text};case"thinking-completed":return{type:"thinking",agent_id:r,run_id:e,text:"",thinking_duration_ms:t.thinkingDurationMs};case"tool-call-started":case"partial-tool-call":case"tool-call-completed":{const n=function(t){const r=(0,At.u)(t)?t:{},e="string"==typeof r.name?r.name:"string"==typeof r.type?r.type:"unknown",n=(0,At.D)(r.truncated)?r.truncated:void 0;return{name:e,..."args"in r?{args:r.args}:{},..."result"in r?{result:r.result}:{},...n?{truncated:n}:{}}}(t.toolCall);return{type:"tool_call",agent_id:r,run_id:e,call_id:t.callId,name:n.name,status:Br(t),...void 0!==n.args?{args:n.args}:{},...void 0!==n.result?{result:n.result}:{},...void 0!==n.truncated?{truncated:n.truncated}:{}}}case"summary-started":case"summary-completed":return(0,W.cD)(t,r,e);case"turn-ended":{const n=(0,Gt.qI)(t.usage);if(!n)return;return{type:"usage",agent_id:r,run_id:e,usage:n}}default:return}}(t,this.agentId,h.runId);r&&await x(r)}})}catch(t){T();const r=(0,a.D7)(t);try{await k("ERROR",r);try{await this.platform.store.markRunTerminal(this.agentId,h.runId,{status:"ERROR",errorCode:(0,a.W_)(r)})}catch{}}finally{P.close(),I("error",r.code)}throw t}var U;const A={cancelled:!1},$=async(t,r={})=>{await(async()=>{await b.flushPendingStep(),R.usage=b.usage()})();try{await this.platform.store.markRunTerminal(this.agentId,h.runId,{status:t,...r,...void 0!==R.usage?{usage:R.usage}:{}})}catch(r){"CANCELLED"===t&&(e=r,Jt.v.log(`Failed to persist cancellation for run ${h.runId}: ${e instanceof Error?e.message:String(e)}`))}var e};let M,O;const D=C.done.then((async()=>{if(A.cancelled)return O="cancelled",void await $("CANCELLED");O="finished",await this.checkpointPersistChain,await k("FINISHED",void 0===E?void 0:{message:E});const t=v??b.finalAssistantText();await $("FINISHED",{result:t})}),(async t=>{if(A.cancelled)return O="cancelled",void await $("CANCELLED");const r=function(t,r){if(void 0!==r&&0!==r.trim().length&&(0,X.hI)(t))return{result:r,warning:X.rZ}}(t,v??b.finalAssistantText());if(void 0!==r)return O="finished",await this.checkpointPersistChain,await k("FINISHED",{message:E??r.warning}),void await $("FINISHED",{result:r.result});O="error";const e=(0,a.D7)(t);throw M=e.code,await this.checkpointPersistChain,await k("ERROR",e),await $("ERROR",{errorCode:(0,a.W_)(e)}),t}));D.then((()=>{T()}),(()=>{T()}));const N=async()=>(await b.flushPendingStep(),b.conversation()),G=D.then(N,N);G.catch((()=>{})),D.then((()=>I("cancelled"===O?"abort":"success")),(t=>I("cancelled"===O?"abort":"error","cancelled"===O?void 0:M??(0,a.D7)(t).code)));const L=()=>{if(s||"finished"!==O&&"error"!==O)return;const t=this._attributePrOpened({runId:h.runId,requestId:p});this._pendingPrAttributions.add(t),t.finally((()=>{this._pendingPrAttributions.delete(t)}))};return D.then(L,L),void 0===r.model&&!0!==o.maxMode||(this._model=o),new Ft(h.runId,this.agentId,{abort:()=>{C.abort()},done:D,steer:s?void 0:C.steer?.bind(C)},P,this.platform.store,k,{cancellationState:A,createdAt:h.createdAt,requestId:p,model:o,conversation:G,liveTerminal:R})}async _attributePrOpened(t){const r=function(t){const r=Ir(t)??process.cwd(),e=Pr(t,r);return void 0!==e?[...e]:[r]}(this.options);await gt({apiKey:this.options.apiKey,agentId:this.agentId,runId:t.runId,requestId:t.requestId,runtime:"local",cwds:r.length>0?r:[process.cwd()]})}async awaitPendingPrAttributions(){for(;this._pendingPrAttributions.size>0;)await Promise.allSettled([...this._pendingPrAttributions])}close(){this.awaitPendingPrAttributions().finally((()=>{(0,rt.rd)()})),this.releaseExecutorLease()}async reload(){try{await(this.executorLease?.handle.reload?.())}catch(t){throw(0,a.Nt)(t,{operation:"agent.reload"})}}async[Symbol.asyncDispose](){try{await this.awaitPendingPrAttributions(),await(0,rt.rd)(),await this.releaseExecutorLease()}catch(t){throw(0,a.Nt)(t,{operation:"agent.[Symbol.asyncDispose]"})}}async listArtifacts(){return[]}async downloadArtifact(t){try{throw new a.j1("Artifacts are not implemented for local SDK agents yet",{isRetryable:!1})}catch(t){throw(0,a.Nt)(t,{operation:"agent.downloadArtifact"})}}async getUsage(t){try{if(gr(t?.runId))throw new a.j1(hr,{isRetryable:!1});return await _r(this.agentId,{apiKey:this.options.apiKey,teamId:this.options.teamId,runId:t?.runId})}catch(t){throw(0,a.Nt)(t,{operation:"agent.getUsage"})}}async getExecutor(){if(this.executorLeasePromise||(this.executorLeasePromise=this.platform.acquireLocalExecutor(zt(this.options))),!this.executorLease)try{this.executorLease=await this.executorLeasePromise}catch(t){throw this.executorLeasePromise=void 0,t}return this.executorLease.handle}async releaseExecutorLease(){const t=this.executorLease,r=this.executorLeasePromise;this.executorLease=void 0,this.executorLeasePromise=void 0;let e=t;if(!e&&void 0!==r)try{e=await r}catch{return}e&&await e.release()}async getRunForSend(t,r,e){if(this.pendingInitialRunId){const t=await this.platform.store.getRun(this.agentId,this.pendingInitialRunId);if(this.pendingInitialRunId=null,t&&"QUEUED"===t.status)return t}return t.local?.force&&await this.expireActiveRunForForceSend(),this.platform.store.createFollowUpRun(this.agentId,{requestId:e,model:r,metadata:{[nr]:this.options.blobEncryptionKey}})}async expireActiveRunForForceSend(){const t=await this.platform.store.getAgent(this.agentId),r=t?.activeRunId;if(!r)return;const e=await this.platform.store.getRun(this.agentId,r);if(e&&!(0,Y.Qb)(e.status)){await this.platform.store.markRunTerminal(this.agentId,r,{status:"EXPIRED",errorCode:"force_send"});try{await this.platform.appendRunMessage({type:"status",agent_id:this.agentId,run_id:r,status:"EXPIRED"})}catch(t){Jt.v.log(`Failed to persist force-expire status event for run ${r}: ${t instanceof Error?t.message:String(t)}`)}}}}class or{constructor(t,r,e,n,s){this.store=t,this.checkpointStore=r,this.eventStore=e,this.eventNotifier=n,this.workspaceRef=s,this.localModelListCache=new Map}acquireLocalExecutor(t){return Zt(t)}async prewarmLocalWorkspace(t){const r=await Zt(zt(t));return()=>r.release()}async resolveLocalModelSelection(t,r,e){const n=(0,J.Lc)(r)?.trim();return async function(t,r={}){if(void 0===r.listModels)return t;const e=await r.listModels(),n=function(t,r){return r.find((r=>r.id===t.id||!0===r.aliases?.includes(t.id)))}(t,e);if(void 0===n)throw new a.j1(`Cannot use this model: ${t.id}. Available models: ${e.map((t=>t.id)).join(", ")}. Use Cursor.models.list() to discover valid selections.`,{isRetryable:!1});const s=!0===t.maxMode||function(t,r){const e=r.params??[];if(0===e.length)return!1;const n=(t.variants??[]).filter((t=>e.every((r=>t.params.some((t=>t.id.trim()===r.id.trim()&&t.value.trim()===r.value.trim()))))));return n.length>0&&n.every((t=>!0===t.isMaxMode))}(n,t);return{...t,id:n.id,...s?{maxMode:!0}:{}}}(t,{listModels:void 0!==n&&n.length>0?()=>this.listModelsForLocalValidation(n,e,t.id):void 0})}async listModelsForLocalValidation(t,r,__t3id){const e=function(){const t=process.env[Vt]?.trim();if(!t)return;let r;try{r=JSON.parse(t)}catch(t){throw new a.j1(`${Vt} must be valid JSON`,{isRetryable:!1,cause:t})}const e=Array.isArray(r)?r:(0,At.u)(r)&&Array.isArray(r.items)?r.items:void 0;if(void 0===e)throw new a.j1(`${Vt} must be a model array or an object with an items array`,{isRetryable:!1});const n=[];for(const t of e){if(!(0,At.u)(t)||"string"!=typeof t.id)throw new a.j1(`${Vt} contains an invalid model entry`,{isRetryable:!1});const r=Array.isArray(t.aliases)?t.aliases.filter((t=>"string"==typeof t)):void 0,e=Yt(t.variants);n.push({id:t.id,displayName:"string"==typeof t.displayName?t.displayName:t.id,..."string"==typeof t.description?{description:t.description}:{},...void 0!==r&&r.length>0?{aliases:r}:{},...void 0!==e?{variants:e}:{}})}return n}();if(void 0!==e)return e;const n=JSON.stringify([t,(0,Ut.E)(r)??null]);let s=this.localModelListCache.get(n);const __t3miss=s===void 0;void 0===s&&(s=new st.N_(t,void 0,r).listModels().then((t=>t.items)),this.localModelListCache.set(n,s));let __t3models;try{__t3models=await s}catch(t){throw this.localModelListCache.delete(n),t}if(__t3miss||__t3id===void 0||__t3models.some((__t3m)=>__t3m.id===__t3id||__t3m.aliases?.includes(__t3id)===!0))return __t3models;if(this.localModelListCache.get(n)===s)this.localModelListCache.delete(n);return this.listModelsForLocalValidation(t,r);}async createAgent(t){const r=void 0!==t.model?await this.resolveLocalModelSelection(t.model,t.apiKey,t.teamId):void 0,e=(0,Tt.DB)(t.agents),n=(0,$t.TX)(t.tools),s=(0,$t.db)(t.disallowedTools);dr(t.systemPrompt),(0,Mt.I2)(t.local??{}),void 0!==t.local?.fs&&Wt({fileSystem:t.local.fs,allowedTools:n,disallowedTools:s});const i=sr(void 0),o={...r!==t.model?{...t,model:r}:t,...void 0!==e?{agents:void 0,customSubagents:e}:{},...void 0!==n?{allowedProtoTools:n}:{},...void 0!==s?{disallowedProtoTools:s}:{},blobEncryptionKey:i},a={[nr]:i};void 0!==e&&(a[rr]=e),void 0!==t.mode&&(a[er]=t.mode),void 0!==t.local?.fs&&(a[Mt.rK]=!0);const{agent:u,run:c}=await this.store.createAgent({agentId:t.agentId,workspaceRef:this.workspaceRef,model:r,name:t.name?.trim()||"New Agent",metadata:a});return new ir(u.agentId,this,o,c.runId,{catalogResolvedModel:void 0!==t.model&&void 0!==r&&r!==t.model?it({requested:t.model,resolved:r}):void 0})}async resumeAgent(t,r){const e=await this.store.getAgent(t);if(!e)throw new a.XB(`Agent ${t} not found`,{isRetryable:!1});const n=function(t){return{...t}}(r),s=void 0!==n.model?await this.resolveLocalModelSelection(n.model,n.apiKey,n.teamId):void 0,i=(0,Tt.DB)(n.agents)??function(t){const r=t[rr];if(!Array.isArray(r))return;const e=[];for(const t of r){if("object"!=typeof t||null===t)return;if(!("name"in t&&"string"==typeof t.name&&"description"in t&&"string"==typeof t.description&&"prompt"in t&&"string"==typeof t.prompt&&"model"in t&&"string"==typeof t.model))return;e.push({name:t.name,description:t.description,prompt:t.prompt,model:t.model})}return e.length>0?e:void 0}(e.metadata),o=(0,$t.TX)(n.tools),u=(0,$t.db)(n.disallowedTools);if(dr(n.systemPrompt),(0,Mt.I2)(n.local??{}),!0===e.metadata[Mt.rK]&&void 0===n.local?.fs)throw new a.j1(`Agent ${t} was created with local.fs. Pass local.fs to Agent.resume() so it does not run on the host disk.`,{isRetryable:!1});void 0!==n.local?.fs&&Wt({fileSystem:n.local.fs,allowedTools:o,disallowedTools:u});const c=null!==e.latestCheckpointRef,l=n.mode??(c?void 0:function(t){const r=t[er];return function(t){return"agent"===t||"plan"===t}(r)?r:void 0}(e.metadata)),m={...s!==n.model?{...n,model:s}:n,...void 0!==i?{agents:void 0,customSubagents:i}:{},...void 0!==o?{allowedProtoTools:o}:{},...void 0!==u?{disallowedProtoTools:u}:{},...void 0!==l?{mode:l}:{},blobEncryptionKey:sr(e.metadata)};return new ir(e.agentId,this,m,null,{resumedAgent:!0,catalogResolvedModel:void 0!==n.model&&void 0!==s&&s!==n.model?it({requested:n.model,resolved:s}):void 0})}async listAgents(t){const r=await this.store.listAgents(t);return{items:r.items.map(br),nextCursor:r.nextCursor}}async getAgent(t){const r=await this.store.getAgent(t);if(!r)throw new a.XB(`Agent ${t} not found`,{isRetryable:!1});return br(r)}async archiveAgent(t){await this.store.archiveAgent(t)}async unarchiveAgent(t){await this.store.unarchiveAgent(t)}async deleteAgent(t){const r=await async function(t,r){const e=[];let n;do{const s=await t.listRuns(r,{cursor:n});for(const t of s.items)e.push(t.runId);n=s.nextCursor}while(n);return e}(this.store,t);if(await this.store.deleteAgent(t),this.eventStore?.deleteRunEvents)for(const e of r)try{await this.eventStore.deleteRunEvents({runId:e})}catch(r){Jt.v.log(`Run-event cleanup failed for run ${e} (agent ${t}): ${r instanceof Error?r.message:String(r)}`)}if(this.checkpointStore!==this.store)try{await(this.checkpointStore.deleteAgent?.(t))}catch(r){Jt.v.log(`Checkpoint cleanup failed for deleted agent ${t}: ${r instanceof Error?r.message:String(r)}`)}}async listRuns(t,r){if(!await this.store.getAgent(t))throw new a.XB(`Agent ${t} not found`,{isRetryable:!1});const e=await this.store.listRuns(t,r);return{items:e.items.map((t=>this.toDetachedStoreRun(t))),nextCursor:e.nextCursor}}async getRun(t){const r=await this.findRunById(t);return this.toDetachedStoreRun(r)}async cancelRun(t){const r=await this.findRunById(t);await this.store.cancelRun(r.agentId,r.runId)}async getAgentMessages(t,r){const e=await this.checkpointStore.getFullConversation(t),n="object"==typeof e&&null!==e&&"turns"in e&&Array.isArray(e.turns)?e.turns:void 0;if(!n||0===n.length)return[];const s=r?.offset??0,i=r?.limit?s+r.limit:void 0;return n.slice(s,i).map(((r,e)=>({type:vr(r),uuid:`${t}:${s+e}`,agent_id:t,message:r})))}async appendRunMessage(t){if(!this.eventStore)return;const r=await this.eventStore.appendRunEvent({runId:t.run_id,eventType:W.do,payload:(0,W.Nk)(t)}),e=this.eventNotifier;if(e)try{e.publishRunEventAppended({runId:r.runId,offset:r.offset}).catch((t=>{Jt.v.log(`Failed to publish run event notification for run ${r.runId} at offset ${r.offset}: ${t instanceof Error?t.message:String(t)}`)}))}catch(t){Jt.v.log(`Failed to publish run event notification for run ${r.runId} at offset ${r.offset}: ${t instanceof Error?t.message:String(t)}`)}}toDetachedStoreRun(t){const r=this.createRunEventTailer(t.agentId),e=function(t){switch(t){case"QUEUED":case"CREATING":case"RUNNING":return"running";case"FINISHED":return"finished";case"ERROR":case"EXPIRED":return"error";case"CANCELLED":return"cancelled";default:throw new Error("unexpected run lifecycle status")}}(t.status);return new Kt(t.runId,t.requestId,t.agentId,e,t.createdAt,t.model??void 0,t.result??void 0,"error"===e&&t.errorCode?(0,a.vg)(t.errorCode):void 0,Rr(t),(0,Gt.g8)(t.usage),this.store,r?()=>r.streamRunEvents(t.runId,{mode:"running"===e?"replay-and-tail":"replay"}):void 0)}createRunEventTailer(t){var r;if(this.eventStore)return new wt({eventStore:this.eventStore,eventStreamStore:(r=this.eventStore,"attachRunEvents"in r&&"function"==typeof r.attachRunEvents?this.eventStore:void 0),eventNotifier:this.eventNotifier,loadRunStatus:async r=>{const e=await this.store.getRun(t,r);return e?.status}})}async findRunById(t){let r;do{const e=await this.store.listAgents({cursor:r});for(const r of e.items){const e=await this.store.getRun(r.agentId,t);if(e)return e}r=e.nextCursor}while(r);throw new a.j1(`Run ${t} not found`,{isRetryable:!1})}}const ar=new Map;async function ur(){const{createDefaultLocalRunEventNotifier:t}=await i.e(400).then(i.bind(i,"../cursor-sdk-local-runtime/dist/run-store/default-local-agent-stores.js"));return t()}function cr(t={}){if(t.localStore){const{workspaceRef:r,scopedWorkspaceRef:e}=wr({localStore:t.localStore,workspaceRef:t.workspaceRef,scopedWorkspaceRef:t.scopedWorkspaceRef}),n=(0,Rt.oc)({localStore:t.localStore,workspaceRef:r,scopedWorkspaceRef:e});return(t.eventNotifier?Promise.resolve(t.eventNotifier):ur()).then((t=>new or(n.store,n.checkpointStore,n.eventStore,t,r)))}if(t.store&&t.checkpointStore){const r=t.store,e=t.checkpointStore;return(t.eventNotifier?Promise.resolve(t.eventNotifier):ur()).then((n=>new or(r,e,t.eventStore,n,t.workspaceRef??process.cwd())))}const r=t.workspaceRef??process.cwd(),{scopedWorkspaceRef:e}=wr({workspaceRef:r,scopedWorkspaceRef:t.scopedWorkspaceRef}),n=t.stateRoot??(0,Ct.V)(r);if(t.store||t.checkpointStore){const e=t.store?void 0:async function(t){try{const{createDefaultLocalAgentRunStore:r}=await i.e(400).then(i.bind(i,"../cursor-sdk-local-runtime/dist/run-store/default-local-agent-stores.js"));return await r(t)}catch(t){if(xt(t))throw kt(t);throw t}}({stateRoot:n,workspaceRef:r}),s=t.checkpointStore?Promise.resolve(t.checkpointStore):async function(t){try{const{createDefaultLocalAgentCheckpointStore:r}=await i.e(400).then(i.bind(i,"../cursor-sdk-local-runtime/dist/run-store/default-local-agent-stores.js"));return await r(t)}catch(t){if(xt(t))throw kt(t);throw t}}({stateRoot:n}),o=t.eventStore?Promise.resolve(t.eventStore):async function(t){try{const{createDefaultLocalRunEventStore:r}=await i.e(400).then(i.bind(i,"../cursor-sdk-local-runtime/dist/run-store/default-local-agent-stores.js"));return await r(t)}catch(t){if(xt(t))throw kt(t);throw t}}({stateRoot:n}),u=t.eventNotifier?Promise.resolve(t.eventNotifier):ur();return Promise.all([e,s,o,u]).then((([e,n,s,i])=>{const o=t.store??e;if(!o)throw new a.j1("Agent run store is required",{isRetryable:!1});return new or(o,n,s,i,r)}))}const s=`${r}:${e}:${n}`,o=ar.get(s);if(o)return o;const u=async function(t){try{const{SqliteLocalAgentStore:r}=await i.e(52).then(i.bind(i,"./src/agent/store/sqlite-local-agent-store.ts"));return await r.open(t)}catch(t){if(xt(t))throw kt(t);throw t}}({stateRoot:n,workspaceRef:r}).then((n=>{const s=(0,Rt.oc)({localStore:n,workspaceRef:r,scopedWorkspaceRef:e});return(t.eventNotifier?Promise.resolve(t.eventNotifier):ur()).then((e=>new or(s.store,t.checkpointStore??s.checkpointStore,t.eventStore??s.eventStore,e,r)))})).catch((t=>{throw ar.delete(s),t}));return ar.set(s,u),u}function lr(t){const r=(0,J.Lc)(t.apiKey);return r===t.apiKey?t:{...t,apiKey:r}}async function mr(t){const r=lr(t);if(r.cloud){fr(r);const{createCloudAgent:t,validateCloudModelAvailability:e}=await i.e(448).then(i.bind(i,"./src/agent/cloud-agent.ts"));return void 0!==r.model&&await e({apiKey:r.apiKey,model:r.model,teamId:r.teamId}),t(r)}return(await cr(Jr(r))).createAgent(r)}function fr(t){(0,Mt.VP)(t.local);for(const r of["tools","disallowedTools","systemPrompt"])if(void 0!==t[r])throw new a.j1(`\`${r}\` is not supported for cloud agents yet; it currently applies to local agents only.`,{isRetryable:!1})}function dr(t){if(void 0!==t&&""===t.trim())throw new a.j1("`systemPrompt` must be non-empty; omit it to keep the default system prompt.",{isRetryable:!1})}function pr(t){return t.startsWith("bc-")}const hr="Local agent usage cannot be filtered by a client-minted `run-` run ID because the backend never receives it. Pass a usage UUID from `getUsage().runs[].runId` instead.";function gr(t){return!0===t?.startsWith("run-")}async function _r(t,r){if(""===r.apiKey)throw new a.j1("API key is required for cloud operations. Caller passed an empty apiKey explicitly; refusing to fall back to CURSOR_API_KEY.",{isRetryable:!1,code:"unauthenticated"});const e=(0,J.Lc)(r.apiKey);if(void 0===e||0===e.length)throw new a.j1("API key is required for cloud operations. Set CURSOR_API_KEY, pass apiKey, or run Cursor.auth.login().",{isRetryable:!1,code:"unauthenticated"});const n=new st.N_(e,void 0,r.teamId),s=await n.getAgentUsage(t,{runId:r.runId});return(0,st.nu)(s)}function Jr(t){const r=(0,Et.kP)(t),{workspaceRef:e,scopedWorkspaceRef:n}=r?wr({...t,localStore:r}):{workspaceRef:qr(t),scopedWorkspaceRef:Sr(t)};return{workspaceRef:e,localStore:r,scopedWorkspaceRef:n}}function wr(t){const r=t.workspaceRef??t.scopedWorkspaceRef??qr(t),e=t.scopedWorkspaceRef;if(void 0!==e&&void 0!==t.workspaceRef&&e!==t.workspaceRef)throw new a.j1(`workspaceRef "${t.workspaceRef}" does not match scopedWorkspaceRef "${e}"`,{isRetryable:!1});return{workspaceRef:r,scopedWorkspaceRef:e??r}}function yr(t){if(Array.isArray(t))throw new a.j1("local.cwd must be a single path; use local.dirs for multi-root workspaces",{isRetryable:!1});return t}function Sr(t){return yr(t?.cwd??t?.local?.cwd)}function qr(t){return Sr(t)??process.cwd()}function Br(t){const r="status"in t?t.status:void 0;return"running"===r||"completed"===r||"error"===r?r:"tool-call-completed"===t.type?"completed":"running"}function Ir(t){return yr(t.local?.cwd)}function Pr(t,r){const e=[],n=new Set;for(const s of[r,...t.local?.dirs??[]]){const t=(0,g.resolve)(s);n.has(t)||(n.add(t),e.push(s))}return e.length>1?e:void 0}function br(t){const r="ARCHIVED"===t.status?void 0:"RUNNING"===t.status?"running":"ERROR"===t.status?"error":"finished";return{agentId:t.agentId,name:t.name??t.agentId,summary:"",lastModified:t.updatedAt.getTime(),createdAt:t.createdAt.getTime(),...r?{status:r}:{},archived:"ARCHIVED"===t.status,runtime:"local",cwd:t.workspaceRef}}function Rr(t){if(!(0,Y.Qb)(t.status))return;if(null===t.startedAt)return;const r=t.finishedAt??t.cancelledAt??t.expiredAt??t.updatedAt;return Math.max(0,r.getTime()-t.startedAt.getTime())}function vr(t){const r=function(t){if(t&&"object"==typeof t){if("turn"in t&&"object"==typeof t.turn&&null!==t.turn&&"case"in t.turn){const r=t.turn.case;if("agentConversationTurn"===r||"shellConversationTurn"===r)return r}return"agentConversationTurn"in t?"agentConversationTurn":"shellConversationTurn"in t?"shellConversationTurn":void 0}}(t);if("agentConversationTurn"===r){const r=function(t){if(t&&"object"==typeof t)return"turn"in t&&"object"==typeof t.turn&&null!==t.turn&&"value"in t.turn?t.turn.value:"agentConversationTurn"in t?t.agentConversationTurn:"shellConversationTurn"in t?t.shellConversationTurn:void 0}(t);if(e=r,Boolean(e&&"object"==typeof e&&("userMessage"in e||"user_message"in e)))return"user"}var e;return"assistant"}var xr=i("../cursor-sdk-local-runtime/dist/run-store/index.js");class kr{constructor(t){this.impl=new xr.tY(t)}async publishRunEventAppended(t){return this.impl.publishRunEventAppended(t)}subscribeRunEvents(t){return this.impl.subscribeRunEvents(t)}}class Er{constructor(t){this.impl=t}static async listen(t){const r=await xr.w.listen(t);return new Er(r)}async close(){return this.impl.close()}}class Cr{constructor(){this.impl=new xr.U1}async publishRunEventAppended(t){return this.impl.publishRunEventAppended(t)}subscribeRunEvents(t){return this.impl.subscribeRunEvents(t)}}function Tr(t){return new kr(t)}function Ur(t){return Er.listen(t)}function Ar(){return new Cr}var $r=i("./src/agent/sdk-config.ts"),Mr=i("node:fs/promises"),Or=i("node:fs"),Dr=i("node:util");const Nr={"target-link":"a symbolic link at the target path","parent-link":"a symbolic link at the parent path","not-a-file":"a non-regular file at the target path"};class Gr extends Error{constructor(t,r){super(`refused ${Nr[t]} ${r}`),this.name="NoFollowRefusedError",this.reason=t,this.path=r}}const Lr="function"==typeof process.getBuiltinModule?process.getBuiltinModule("node:fs"):Or,{O_RDONLY:Fr,O_WRONLY:Kr,O_CREAT:zr,O_EXCL:jr,O_DIRECTORY:Hr=0,O_NOFOLLOW:Wr=0,O_NONBLOCK:Qr=0}=Lr.constants,Vr=Kr|zr|jr|Wr,Xr=Fr|Hr|Wr,Yr=(new Set(["ENXIO","ENODEV","EOPNOTSUPP"]),2**32),Zr=new Map;async function te(t,r,e={}){const{noFollow:n}=e;void 0===n&&function(t){Lr.mkdirSync((0,g.dirname)(t),{recursive:!0})}(t);const s=function(t){const r=Zr.get(t)??[];Zr.set(t,r);const e=new Promise((t=>{r.push(t)}));return 1===r.length&&r[0]?.(),{ready:e,leave:()=>{r.shift(),0===r.length?Zr.delete(t):r[0]?.()}}}((0,g.resolve)(t));await s.ready;try{void 0===n?await re(await async function(t,r){const e=await async function(t){try{return await(0,Dr.promisify)(Lr.realpath)(t)}catch(r){if(le(r))return t;throw r}}(t),n=r??await async function(t){try{return(await(0,Dr.promisify)(Lr.stat)(t)).mode}catch(t){if(le(t))return;throw t}}(e);return{temp:ue(e),target:e,mode:n}}(t,e.mode),r):await async function(t,r,e){try{await re(function(t,r){const e=t.entry(t.name);return ee(t),{temp:ue(e),target:e,mode:r??384,checkTarget:()=>ee(t)}}(t,e),r)}finally{t.close()}}(function(t,r,e){const n=(0,g.resolve)(r),s=(0,g.resolve)(t),i=(0,g.relative)(n,s);if(""===i||".."===i||i.startsWith(`..${g.sep}`)||(0,g.isAbsolute)(i))throw new RangeError(`${s} is not below the no-follow root ${n}`);e&&Lr.mkdirSync(n,{recursive:!0});const o="."===(0,g.dirname)(i)?[]:(0,g.dirname)(i).split(g.sep);return{...("linux"===process.platform?ne:oe)(n,o,e),name:(0,g.basename)(i),shown:s}}(t,n.root,!0),r,e.mode)}finally{s.leave()}}async function re({temp:t,target:r,mode:e,checkTarget:n},s){const i=await(0,Dr.promisify)(Lr.open)(t,Vr,e??438);try{try{await(0,Dr.promisify)(Lr.writeFile)(i,s),void 0!==e&&await(0,Dr.promisify)(Lr.fchmod)(i,e).catch(me),await(0,Dr.promisify)(Lr.fsync)(i)}finally{await(0,Dr.promisify)(Lr.close)(i)}n?.(),await(0,Dr.promisify)(Lr.rename)(t,r)}catch(r){throw await(0,Dr.promisify)(Lr.rm)(t,{force:!0}),r}}function ee(t){const r=Lr.lstatSync(t.entry(t.name),{throwIfNoEntry:!1});if(!0===r?.isSymbolicLink())throw new Gr("target-link",t.shown)}function ne(t,r,e){let n=Lr.openSync(t,Fr|Hr),s=t;try{for(const t of r){s=(0,g.join)(s,t);const r=ie(se(n,t),s,e);Lr.closeSync(n),n=r}}catch(t){throw Lr.closeSync(n),t}const i=n;return{entry:t=>se(i,t),close:()=>Lr.closeSync(i)}}function se(t,r){return`/proc/self/fd/${t}/${r}`}function ie(t,r,e){e&&ae(t);try{return Lr.openSync(t,Xr)}catch(e){throw function(t,r,e){const n=ce(t),s="ELOOP"===n||"ENOTDIR"===n&&!function(t){const r=Lr.lstatSync(t,{throwIfNoEntry:!1});return void 0!==r&&!r.isSymbolicLink()&&!r.isDirectory()}(r);return s?new Gr("parent-link",e):t}(e,t,r)}}function oe(t,r,e){const n=r.reduce(((t,r)=>{const n=(0,g.join)(t,r);if(e&&ae(n),!0===Lr.lstatSync(n,{throwIfNoEntry:!1})?.isSymbolicLink())throw new Gr("parent-link",n);return n}),t);return{entry:t=>(0,g.join)(n,t),close:()=>{}}}function ae(t){try{Lr.mkdirSync(t)}catch(t){if("EEXIST"!==ce(t))throw t}}function ue(t){return`${t}.${(0,Q.randomInt)(Yr)}`}function ce(t){return t instanceof Error&&"code"in t&&"string"==typeof t.code?t.code:void 0}function le(t){return"ENOENT"===ce(t)}function me(t){const r=ce(t);if("ENOSYS"!==r&&(void 0!==process.getuid&&0===process.getuid()||"EINVAL"!==r&&"EPERM"!==r))throw t}Error,"function"==typeof process.getBuiltinModule&&process.getBuiltinModule("node:fs");const fe="agents.ndjson",de="runs.ndjson",pe="run_events.ndjson",he="checkpoints.ndjson",ge={agents:fe,runs:de,runEvents:pe,checkpoints:he};let _e=Promise.resolve();function Je(t){const r=_e.then(t,t);return _e=r.then((()=>{}),(()=>{})),r}class we{constructor(t){this.rootDir=t,this.agents=new ye(t),this.checkpoints=new Be(t),this.runEvents=new qe(t),this.runs=new Se(t,this.runEvents)}}class ye{constructor(t){this.rootDir=t}agentsPath(){return(0,g.join)(this.rootDir,fe)}async get(t){return(await be(this.agentsPath(),ve)).find((r=>r.agentId===t.agentId))??null}async create(t){const{agent:r}=t;return Je((async()=>{const t=await be(this.agentsPath(),ve);if(t.some((t=>t.agentId===r.agentId)))throw new Error(`Agent ${r.agentId} already exists`);const e=structuredClone(r);return t.push(e),await Te(this.agentsPath(),t),structuredClone(e)}))}async update(t){const{agent:r}=t;return Je((async()=>{const t=await be(this.agentsPath(),ve),e=t.findIndex((t=>t.agentId===r.agentId));if(e<0)throw new Error(`Agent ${r.agentId} not found`);const n=structuredClone(r);return t[e]=n,await Te(this.agentsPath(),t),structuredClone(n)}))}async delete(t){return Je((async()=>{const r=await be(this.agentsPath(),ve),e=r.filter((r=>!function(t,r){return!(r.agentIds?.length&&!r.agentIds.includes(t.agentId))&&(void 0===r.cwd||t.cwd===r.cwd)}(r,t.filter)));if(e.length===r.length)throw new Error("No agents matched delete filter");await Te(this.agentsPath(),e)}))}async list(t){const r=t?.filter,e=await be(this.agentsPath(),ve);return(0,Rt.tg)(e,r)}}class Se{constructor(t,r){this.rootDir=t,this.runEvents=r}runsPath(){return(0,g.join)(this.rootDir,de)}async get(t){return(await be(this.runsPath(),xe)).find((r=>r.agentId===t.agentId&&r.runId===t.runId))??null}async create(t){const{run:r}=t;return Je((async()=>{const t=await be(this.runsPath(),xe);if(t.some((t=>t.agentId===r.agentId&&t.runId===r.runId)))throw new Error(`Run ${r.runId} already exists for agent ${r.agentId}`);const e=structuredClone(r);return t.push(e),await Te(this.runsPath(),t),structuredClone(e)}))}async update(t){const{run:r}=t;return Je((async()=>{const t=await be(this.runsPath(),xe),e=t.findIndex((t=>t.agentId===r.agentId&&t.runId===r.runId));if(e<0)throw new Error(`Run ${r.runId} not found for agent ${r.agentId}`);const n=structuredClone(r);return t[e]=n,await Te(this.runsPath(),t),structuredClone(n)}))}async delete(t){const r=t.filter,e=await Je((async()=>{const t=await be(this.runsPath(),xe),e=t.filter((t=>Pe(t,r)));if(0===e.length)return[];const n=t.filter((t=>!Pe(t,r)));return await Te(this.runsPath(),n),e}));for(const t of e)await this.runEvents.delete({filter:{runIds:[t.runId]}})}async list(t){const r=t?.filter,e=(await be(this.runsPath(),xe)).filter((t=>Pe(t,r)));return(0,Rt.f1)(e,r)}}class qe{constructor(t){this.rootDir=t}eventsPath(){return(0,g.join)(this.rootDir,pe)}async append(t){return Je((async()=>{const r=await be(this.eventsPath(),ke),e=t.idempotencyKey?r.find((r=>r.runId===t.runId&&r.idempotencyKey===t.idempotencyKey)):void 0;if(e)return Ue(e);const n=r.filter((r=>r.runId===t.runId)).reduce(((t,r)=>Math.max(t,r.seq)),0)+1,s={runId:t.runId,seq:n,offset:String(n),eventType:t.eventType,payload:t.payload??null,payloadRef:t.payloadRef??null,idempotencyKey:t.idempotencyKey??null,createdAt:(new Date).toISOString()};return r.push(s),await Te(this.eventsPath(),r),Ue(s)}))}async list(t){const r=await be(this.eventsPath(),ke),e=Number.parseInt(t.afterOffset??"0",10),n=t.limit??100,s=r.filter((r=>r.runId===t.runId&&r.seq>e)).sort(((t,r)=>t.seq-r.seq)),i=s.slice(0,n).map(Ue);return{items:i,...s.length>i.length&&i.length>0?{nextOffset:i.at(-1)?.offset}:{}}}async delete(t){return Je((async()=>{const r=await be(this.eventsPath(),ke),e=t.filter.runIds&&t.filter.runIds.length>0?new Set(t.filter.runIds):null,n=e?r.filter((t=>!e.has(t.runId))):[];await Te(this.eventsPath(),n)}))}}class Be{constructor(t){this.rootDir=t}checkpointsPath(){return(0,g.join)(this.rootDir,he)}async get(t){const r=(await be(this.checkpointsPath(),Ee)).find((r=>r.agentId===t.agentId&&r.blobId===t.blobId));return r?Buffer.from(r.dataBase64,"base64"):null}async create(t){const{agentId:r,blobId:e,data:n}=t;return Je((async()=>{const t=await be(this.checkpointsPath(),Ee);if(t.some((t=>t.agentId===r&&t.blobId===e)))throw new Error(`Checkpoint blob ${e} already exists for agent ${r}`);t.push({agentId:r,blobId:e,dataBase64:Buffer.from(n).toString("base64")}),await Te(this.checkpointsPath(),t)}))}async update(t){const{agentId:r,blobId:e,data:n}=t;return Je((async()=>{const t=await be(this.checkpointsPath(),Ee),s=t.findIndex((t=>t.agentId===r&&t.blobId===e));if(s<0)throw new Error(`Checkpoint blob ${e} not found for agent ${r}`);t[s]={agentId:r,blobId:e,dataBase64:Buffer.from(n).toString("base64")},await Te(this.checkpointsPath(),t)}))}async list(t){const r=t?.filter,e=(await be(this.checkpointsPath(),Ee)).filter((t=>Ie(t,r))).map((t=>t.blobId));return(0,Rt.Jg)(e,r)}async delete(t){const r=t.filter;return Je((async()=>{const t=(await be(this.checkpointsPath(),Ee)).filter((t=>!Ie(t,r)));await Te(this.checkpointsPath(),t)}))}}function Ie(t,r){return!((r?.agentIds?.length||r?.blobIds?.length)&&(r.agentIds?.length&&!r.agentIds.includes(t.agentId)||r.blobIds?.length&&!r.blobIds.includes(t.blobId)))}function Pe(t,r){return!(r?.agentIds&&r.agentIds.length>0&&!r.agentIds.includes(t.agentId)||r?.runIds&&r.runIds.length>0&&!r.runIds.includes(t.runId))}async function be(t,r){let e;try{e=await(0,Mr.readFile)(t,"utf8")}catch(t){if(function(t){return"object"==typeof t&&null!==t&&"code"in t&&"ENOENT"===t.code}(t))return[];throw t}const n=e.split("\n").filter((t=>t.trim().length>0)),s=[];for(const[e,i]of n.entries()){let o;try{o=JSON.parse(i)}catch{if(e===n.length-1)break;throw Ce(t,e+1)}if(!r(o)){if(e===n.length-1)break;throw Ce(t,e+1)}s.push(o)}return s}function Re(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function ve(t){return Re(t)&&"string"==typeof t.agentId&&"string"==typeof t.cwd&&function(t){return"idle"===t||"running"===t||"error"===t||"archived"===t}(t.status)&&"number"==typeof t.createdAt&&"number"==typeof t.updatedAt}function xe(t){return Re(t)&&"string"==typeof t.runId&&"string"==typeof t.agentId&&"number"==typeof t.turnNumber&&function(t){return"queued"===t||"running"===t||"finished"===t||"error"===t||"cancelled"===t||"expired"===t}(t.status)&&"number"==typeof t.createdAt&&"number"==typeof t.updatedAt}function ke(t){return Re(t)&&"string"==typeof t.runId&&"number"==typeof t.seq&&"string"==typeof t.offset&&"string"==typeof t.eventType&&"string"==typeof t.createdAt&&(null===t.payloadRef||"string"==typeof t.payloadRef)&&(null===t.idempotencyKey||"string"==typeof t.idempotencyKey)}function Ee(t){return Re(t)&&"string"==typeof t.agentId&&"string"==typeof t.blobId&&"string"==typeof t.dataBase64}function Ce(t,r){return new Error(`Corrupt local agent store: failed to parse record ${r} of ${t}`)}async function Te(t,r){const e=r.map((t=>JSON.stringify(t))).join("\n");await te(t,e.length>0?`${e}\n`:"")}function Ue(t){return{...t,createdAt:new Date(t.createdAt).getTime()}}async function Ae(t,r){try{return await r()}catch(r){throw(0,a.Nt)(r,{operation:t})}}Symbol.asyncDispose;class $e{constructor(){}static async create(t){return Ae("Agent.create",(async()=>{if(void 0===t.agentId&&void 0!==t.cloud?.envVars)return mr(t);const r=t.agentId??(t.cloud?(0,xr.M2)():(0,xr.WQ)());return mr({...t,agentId:r})}))}static async resume(t,r){return Ae("Agent.resume",(()=>async function(t,r){const e=lr(r??{});if(e.cloud||t.startsWith("bc-")){fr(e);const{resumeCloudAgent:r}=await i.e(448).then(i.bind(i,"./src/agent/cloud-agent.ts"));return r(t,e)}return(await cr(Jr(e))).resumeAgent(t,e)}(t,r)))}static async prompt(t,r){return Ae("Agent.prompt",(async()=>{const e=await $e.create(r??{});try{const r=await e.send(t);return await r.wait()}finally{await e[Symbol.asyncDispose]()}}))}static async list(t){return Ae("Agent.list",(()=>async function(t){if("cloud"===t?.runtime){const{listCloudAgents:r}=await i.e(448).then(i.bind(i,"./src/agent/cloud-agent.ts"));return r(t)}return(await cr(Jr(t))).listAgents(t)}(t)))}static async listRuns(t,r){return Ae("Agent.listRuns",(()=>async function(t,r){if("cloud"===r?.runtime){const{listCloudRuns:e}=await i.e(448).then(i.bind(i,"./src/agent/cloud-agent.ts"));return e(t,r)}return(await cr(Jr(r))).listRuns(t,r)}(t,r)))}static async getRun(t,r){return Ae("Agent.getRun",(()=>async function(t,r){if("cloud"===r?.runtime){const{getCloudRun:e}=await i.e(448).then(i.bind(i,"./src/agent/cloud-agent.ts"));return e(t,r)}return(await cr(Jr(r))).getRun(t)}(t,r)))}static async cancelRun(t,r){return Ae("Agent.cancelRun",(()=>async function(t,r){if("cloud"===r?.runtime){const{cancelCloudRun:e}=await i.e(448).then(i.bind(i,"./src/agent/cloud-agent.ts"));return e(t,r)}return(await cr(Jr(r))).cancelRun(t)}(t,r)))}static async get(t,r){return Ae("Agent.get",(()=>async function(t,r){if(pr(t)){const{getCloudAgent:e}=await i.e(448).then(i.bind(i,"./src/agent/cloud-agent.ts"));return e(t,r??{})}return(await cr(Jr(r))).getAgent(t)}(t,r)))}static async archive(t,r){return Ae("Agent.archive",(()=>async function(t,r){if(pr(t)){const{archiveCloudAgent:e}=await i.e(448).then(i.bind(i,"./src/agent/cloud-agent.ts"));return e(t,r??{})}return(await cr(Jr(r))).archiveAgent(t)}(t,r)))}static async unarchive(t,r){return Ae("Agent.unarchive",(()=>async function(t,r){if(pr(t)){const{unarchiveCloudAgent:e}=await i.e(448).then(i.bind(i,"./src/agent/cloud-agent.ts"));return e(t,r??{})}return(await cr(Jr(r))).unarchiveAgent(t)}(t,r)))}static async delete(t,r){return Ae("Agent.delete",(()=>async function(t,r){if(pr(t)){const{deleteCloudAgent:e}=await i.e(448).then(i.bind(i,"./src/agent/cloud-agent.ts"));return e(t,r??{})}return(await cr(Jr(r))).deleteAgent(t)}(t,r)))}static async getUsage(t,r){return Ae("Agent.getUsage",(()=>async function(t,r){if(!pr(t)&&gr(r?.runId))throw(0,a.Nt)(new a.j1(hr,{isRetryable:!1}),{operation:"Agent.getUsage"});return _r(t,r??{})}(t,r)))}}$e.messages={list:(t,r)=>Ae("Agent.messages.list",(()=>async function(t,r){return(await cr(Jr(r))).getAgentMessages(t,r)}(t,r)))};class Me{constructor(){}static configure(t){(0,$r.xP)(t)}static async me(t){return Ae("Cursor.me",(()=>async function(t){const{getCloudMe:r}=await i.e(448).then(i.bind(i,"./src/agent/cloud-agent.ts"));return r(t??{})}(t)))}}Me.models={list:t=>Ae("Cursor.models.list",(()=>async function(t){const{listCloudModels:r}=await i.e(448).then(i.bind(i,"./src/agent/cloud-agent.ts"));return r(t??{})}(t)))},Me.repositories={list:t=>Ae("Cursor.repositories.list",(()=>async function(t){const{listCloudRepositories:r}=await i.e(448).then(i.bind(i,"./src/agent/cloud-agent.ts"));return r(t??{})}(t)))},Me.auth={login:t=>Ae("Cursor.auth.login",(()=>async function(t={}){const r=(0,l.pi)(t.backendUrl),e=(0,l.Fw)(t.websiteUrl),n=(0,l.bi)(e);t.onLoginUrl?.(n.loginUrl);let s=void 0!==t.onLoginUrl;const i=t.openBrowser??!0;if("function"==typeof i)await i(n.loginUrl),s=!0;else if(i&&(o=n.loginUrl,!process.env.NO_OPEN_BROWSER&&!Boolean(process.env.SSH_CONNECTION??process.env.SSH_CLIENT??process.env.SSH_TTY)&&_(o)))try{await function(t){return _(t)?new Promise(((r,e)=>{const{cmd:n,args:s}=function(t){const r=process.platform;return"darwin"===r?{cmd:"open",args:[t]}:"win32"===r?{cmd:g.join(process.env.SYSTEMROOT??"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe"),args:["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",`Start-Process '${t.replace(/'/g,"''")}'`]}:{cmd:"xdg-open",args:[t]}}(t),i=(0,h.spawn)(n,s,{stdio:"ignore",windowsHide:!0});i.once("error",(t=>{e(new Error(`Failed to open browser: ${t.message}`))})),i.once("spawn",(()=>r())),i.unref()})):Promise.reject(new Error(`Invalid URL: only http:// and https:// links can be opened. Received: ${t}`))}(n.loginUrl),s=!0}catch{}var o;s||process.stderr.write(`Could not open a browser. Open this URL to sign in to Cursor:\n\n ${n.loginUrl}\n\n`);const u=await(0,l.er)({apiUrl:r,uuid:n.uuid,verifier:n.verifier,signal:t.signal,onWarning:t=>{process.stderr.write(`warning: ${t}\n`)}});if(null===u)throw new a.v3(t.signal?.aborted?"Login was cancelled.":"Login failed or timed out. Please try again.",{code:"unauthenticated",isRetryable:!0});const c=t.apiKeyTtlMs??w;if(!Number.isFinite(c)||c<=0)throw new a.v3(`apiKeyTtlMs must be a positive number of milliseconds, got ${c}`,{code:"invalid_argument",isRetryable:!1});const q=Date.now()+c,B=await async function(t,r){const e=r??function({backendUrl:t,accessToken:r}){const e=(0,p.cf)({baseUrl:t,httpVersion:"1.1",interceptors:[t=>async e=>(e.header.set("authorization",`Bearer ${r}`),t(e))]});return(0,d.createClient)(m.I,e)}({backendUrl:t.backendUrl,accessToken:t.accessToken});let n,s;try{n=(await e.createUserApiKey(new f.cEg({name:t.name,expiresAt:void 0!==t.expiresAtMs?BigInt(Math.floor(t.expiresAtMs)):void 0}))).apiKey}catch(t){if(t instanceof d.ConnectError){const r=(0,a.e_)(t);throw new a.v3(`Login succeeded, but creating an SDK API key failed: ${r.message} (your team's settings may restrict user API keys — ask a team admin, or pass an existing API key directly)`,{code:r.code,isRetryable:r.isRetryable,cause:t})}throw t}if(""===n)throw new a.v3("Login succeeded, but the server returned an empty API key.",{code:"internal",isRetryable:!0});try{const t=await e.getMe(new f.Ewt({}));s=""!==t.email?t.email:void 0}catch{s=void 0}return{apiKey:n,email:s}}({backendUrl:r,accessToken:u.accessToken,name:t.apiKeyName??S(),expiresAtMs:q});if(null!==t.store){const e=t.store??y(),n={version:1,backendUrl:r,apiKey:B.apiKey,apiKeyExpiresAtMs:q,email:B.email,createdAtMs:Date.now()};await e.save(n),(0,J.s1)()}return{apiKey:B.apiKey,email:B.email,apiKeyExpiresAtMs:q}}(t))),logout:t=>Ae("Cursor.auth.logout",(()=>async function(t={}){const r=t.store??y();await r.clear(),(0,J.s1)()}(t))),status:t=>Ae("Cursor.auth.status",(()=>async function(t={}){const r=t.store??y(),e=await r.load();return void 0===e||void 0!==e.apiKeyExpiresAtMs&&e.apiKeyExpiresAtMs<=Date.now()?{status:"logged-out"}:{status:"logged-in",backendUrl:e.backendUrl,email:e.email,apiKeyExpiresAtMs:e.apiKeyExpiresAtMs}}(t)))};var Oe=i("zod/v3"),De=i("../cursor-sdk-shared/dist/tool-call-types.js");const Ne=Oe.object({text:Oe.string()}),Ge=Oe.object({text:Oe.string(),thinkingDurationMs:Oe.number().optional()}),Le=Oe.object({text:Oe.string()}),Fe=Oe.object({command:Oe.string(),workingDirectory:Oe.string().optional()}),Ke=Oe.object({stdout:Oe.string(),stderr:Oe.string(),exitCode:Oe.number()}),ze=Oe.discriminatedUnion("type",[Oe.object({type:Oe.literal("assistantMessage"),message:Ne}),Oe.object({type:Oe.literal("toolCall"),message:De.C6}),Oe.object({type:Oe.literal("thinkingMessage"),message:Ge})]),je=Oe.object({userMessage:Le.optional(),steps:Oe.array(ze)}),He=Oe.object({shellCommand:Fe.optional(),shellOutput:Ke.optional()}),We=Oe.discriminatedUnion("type",[Oe.object({type:Oe.literal("agentConversationTurn"),turn:je}),Oe.object({type:Oe.literal("shellConversationTurn"),turn:He})]);var Qe=i("./src/agent/types/delta-types.ts");function Ve(t){return t.type}var Xe=i("../cursor-sdk-shared/dist/message-schemas.js");module.exports=o})(); \ No newline at end of file diff --git a/dist/esm/977.js b/dist/esm/977.js -index 3bc50aaa257cda261cef797a5026b00dc5b977a7..09035ac75b4b90c0fe7250105d3c64431da5d43c 100644 +index 3bc50aaa257cda261cef797a5026b00dc5b977a7..0bc348e6ee229979047b61c06c5eaaf82d9a011d 100644 --- a/dist/esm/977.js +++ b/dist/esm/977.js @@ -1,4 +1,4 @@ -import{createRequire as e}from"node:module";const t=e(import.meta.url);export const __webpack_esm_id__=977;export const __webpack_esm_ids__=[977];export const __webpack_esm_modules__={"./src/agent/local-executor.ts"(e,t,r){r.d(t,{createLocalExecutor:()=>xH});var n=r("node:buffer"),o=r("node:os"),s=r("node:path"),i=r("../proto/dist/generated/agent/v1/agent_pb.js");const a={textDelta:(e,t)=>new i.Uq({messageStartedAtMs:t,message:{case:"textDelta",value:new i.PtE({text:e})}}),toolCallStarted:(e,t,r)=>new i.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"toolCallStarted",value:new i.xuG({callId:e,toolCall:t,modelCallId:r})}}),toolCallCompleted:(e,t,r)=>new i.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"toolCallCompleted",value:new i.LLS({callId:e,toolCall:t,modelCallId:r})}}),toolCallDelta:(e,t,r,n)=>new i.Uq({messageStartedAtMs:n,message:{case:"toolCallDelta",value:new i.I0n({callId:e,toolCallDelta:t,modelCallId:r})}}),thinkingDelta:(e,t,r)=>new i.Uq({messageStartedAtMs:r,message:{case:"thinkingDelta",value:new i.cHB({text:e,thinkingStyle:t})}}),thinkingCompleted:(e,t,r)=>new i.Uq({messageStartedAtMs:t,message:{case:"thinkingCompleted",value:new i.tr3({thinkingDurationMs:e,...!0===r?{narration:!0}:{}})}}),thinkingNote:e=>new i.Uq({message:{case:"thinkingNote",value:new i.Y$k({text:e})}}),taskChild:(e,t,r)=>"thinkingNote"===t.message.case?t:a.toolCallDelta(e,new i.V1v({delta:{case:"taskToolCallDelta",value:new i.aon({interactionUpdate:t})}}),r),userMessageAppended:e=>new i.Uq({messageStartedAtMs:e.startedAtMs,message:{case:"userMessageAppended",value:new i.v$T({userMessage:e})}}),partialToolCall:(e,t,r)=>new i.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"partialToolCall",value:new i.fxF({callId:e,toolCall:t,modelCallId:r})}}),tokenDelta:e=>new i.Uq({message:{case:"tokenDelta",value:new i.Fyz({tokens:e})}}),summary:e=>new i.Uq({message:{case:"summary",value:new i.ECk({summary:e})}}),summaryStarted:()=>new i.Uq({message:{case:"summaryStarted",value:new i.lWT}}),heartbeat:()=>new i.Uq({message:{case:"heartbeat",value:new i.ih1}}),summaryCompleted:(e,t,r)=>new i.Uq({message:{case:"summaryCompleted",value:new i.ZM9({hookMessage:e,failed:t,fallback:r})}}),shellOutputDelta:e=>new i.Uq({message:{case:"shellOutputDelta",value:new i.Nn_({event:e})}}),modelCallCompleted:(e,t)=>new i.Uq({message:{case:"modelCallCompleted",value:new i.c2D({modelCallId:e,inputTokens:BigInt(t.inputTokens),outputTokens:BigInt(t.outputTokens),cacheReadTokens:BigInt(t.cacheReadTokens),cacheWriteTokens:BigInt(t.cacheWriteTokens),...void 0!==t.reasoningTokens?{reasoningTokens:BigInt(t.reasoningTokens)}:{}})}}),turnEnded(e,t){const r=e?.catalogCostCents;return new i.Uq({message:{case:"turnEnded",value:new i.lJj({...e?{inputTokens:BigInt(e.inputTokens),outputTokens:BigInt(e.outputTokens),cacheReadTokens:BigInt(e.cacheReadTokens),cacheWriteTokens:BigInt(e.cacheWriteTokens),reasoningTokens:BigInt(e.reasoningTokens??0)}:{},...void 0!==t?{endedAtMs:t}:{},...void 0!==r&&Number.isFinite(r)?{estimatedCost:new i.QVp({rawCostCents:r,chargedCents:r,source:i.nnk.CATALOG})}:{}})}})},stepStarted:e=>new i.Uq({message:{case:"stepStarted",value:new i.dwJ({stepId:BigInt(e)})}}),toolRequestsListed:e=>new i.Uq({message:{case:"toolRequestsListed",value:new i.BU$({callCount:Math.max(0,e)})}}),voiceCallUtterance:e=>new i.Uq({message:{case:"voiceCallUtterance",value:e}}),stepCompleted:(e,t)=>new i.Uq({message:{case:"stepCompleted",value:new i.Lrv({stepId:BigInt(e),stepDurationMs:BigInt(t)})}}),activeBranchChange:(e,t)=>new i.Uq({message:{case:"activeBranchChange",value:new i.PSN({path:e,branchName:t})}}),feedbackRequest:(e,t,r,n=[],o={})=>new i.Uq({message:{case:"feedbackRequest",value:new i.apn({requestId:e,canonicalModelName:t,categories:[...r],categoryGroups:[...n],title:o.title,negativeTitle:o.negativeTitle,commentPlaceholder:o.commentPlaceholder})}})};class c{constructor(e=0){this.nextId=e}next(){return this.nextId++}peekNext(){return this.nextId}observe(e){Number.isSafeInteger(e)&&e>=this.nextId&&(this.nextId=e+1)}}var l=r("../context/dist/logger.js"),u=r("../metrics/dist/index.js"),d=r("../proto/dist/generated/agent/v1/exec_pb.js"),h=r("../utils/dist/writable-iterable.js");const p=/https?:\/\/\S+/gi,f=/[)"'<>,.;:\]}]$/;function m(e){const{url:t,wrappers:r}=function(e){let t=e.length;for(;t>0&&f.test(e.slice(t-1,t));)t-=1;return{url:e.slice(0,t),wrappers:e.slice(t)}}(e),n=t.search(/[?#]/),o=-1===n?t:t.slice(0,n),s=o.indexOf("//")+2,i=o.slice(s).search(/[/?#]/),a=-1===i?o.length:s+i,c=o.lastIndexOf("@",a-1);return c0&&o.push(`gitErrorCode=${n.gitErrorCode}`),"number"==typeof n.exitCode&&Number.isFinite(n.exitCode)&&o.push(`exitCode=${n.exitCode}`),0===o.length)return e;let s=`${e} [git: ${o.join(" ")}]`;var i,a;return!0===r?.includeStderr&&"string"==typeof n.stderr&&n.stderr.length>0&&(s+=`\n--- git stderr ---\n${a=n.stderr,i=a.replace(p,m),i.length<=2048?i:`${i.slice(0,2048)}… [truncated to 2048 chars]`}`),s}var y=r("../context/dist/core.js");const v=(0,y.cF)(Symbol("machineProfile"),void 0),b=(0,l.h)("SimpleControlledExecManager"),S=(0,u.v5)("agent_exec.controlled.exec.duration_ms",{description:"Duration of controlled exec operations in milliseconds",labelNames:["exec_case"]}),k=(0,u.v5)("agent_exec.controlled.exec.machine_duration_ms",{description:"Duration of grep, shell and hook execs by coarse machine profile",labelNames:["exec_case","cpu_cores","ram_gb","defender_rt"]}),_=new Set(["grepArgs","shellStreamArgs","executeHookArgs"]),C=(0,u.Pu)("agent_exec.controlled.exec.success",{description:"Count of successful controlled exec operations",labelNames:["exec_case"]}),E=(0,u.Pu)("agent_exec.controlled.exec.error",{description:"Count of failed controlled exec operations",labelNames:["exec_case"]}),x={computerUseArgs:"Computer use is not enabled for this environment, so the Computer tool and the computerUse subagent cannot run here. Do not retry computer actions; verify with non-GUI methods (automated tests, shell commands) instead. (No computer-use handler is registered on this exec daemon.)",recordScreenArgs:"Screen recording is not enabled for this environment, so recordings cannot be captured here. Do not retry; skip the recording and present other evidence instead. (No record-screen handler is registered on this exec daemon.)"};class P extends Error{constructor(e){super(e),this.name="ControlledExecDisposedError"}}function R(e){return e instanceof P?"EXEC_BACKEND_UNAVAILABLE":e instanceof Error&&"AgentExecStreamStartTimeoutError"===e.name?"AGENT_EXEC_STREAM_START_TIMEOUT":void 0}class I{constructor(e,t,r){this.exec=e,this.deserializeArgs=t,this.serializeResult=r}handle(e,t){const r=this.deserializeArgs(t);if(void 0===r)return;const{id:n,args:o}=r;return async function*(r){const s=performance.now(),i=[],a=await r.exec.execute(e,o,{execId:t.execId,hookContextCollector:i,deliverAgentStoreConflictNotices:!0===t.acceptHookAdditionalContexts,recordAgentView:!0===t.recordAgentView,refuseUnreadChanges:!0===t.refuseUnreadChanges}),c=r.serializeResult(n,a);c.localExecutionTimeMs=Math.round(Math.max(0,performance.now()-s)),i.length>0&&(c.hookAdditionalContexts=i),yield c}(this)}}class T{constructor(e,t,r){this.exec=e,this.deserializeArgs=t,this.serializeStream=r}handle(e,t){const r=this.deserializeArgs(t);if(void 0===r)return;const{id:n,args:o}=r;return async function*(r){const s=performance.now(),i=[],a=r.exec.execute(e,o,{execId:t.execId,hookContextCollector:i,deliverAgentStoreConflictNotices:!0===t.acceptHookAdditionalContexts});try{for await(const e of a){const t=r.serializeStream(n,e);t.localExecutionTimeMs=Math.round(Math.max(0,performance.now()-s)),yield t}}finally{const e=i.filter((e=>"agentStoreConflict"===e.hookEventName));e.length>0&&(yield new d.yT({id:n,hookAdditionalContexts:e}))}}(this)}}class A{constructor(e){this.handlers=[],this.runningExecs=new Map;const t=e?.includeGitStderrInThrows??!1;this.includeGitStderrInThrows="function"==typeof t?t:()=>t,this.observeResults=e?.observeResults}startResultObserver(e,t,r){if(void 0!==this.observeResults)try{return this.observeResults(e,t,r)}catch{return}}register(e){this.handlers.push(e)}handleControlMessage(e){if("abort"===e.message.case){const t=e.message.value.id,r=this.runningExecs.get(t);r&&r()}}handle(e,t){const[r,n]=e.withCancel();this.runningExecs.set(t.id,n);const o=t.message.case??"unknown";for(const e of this.handlers){const s=e.handle(r,t);if(void 0===s)continue;const i=s,a=(0,h.Jt)();let c;const l=()=>{c=setTimeout((()=>{a.write(new d.$Y({message:{case:"heartbeat",value:new d.VA({id:t.id})}})).then(l).catch((()=>{}))}),3e3)};l();const u=performance.now(),p=this.startResultObserver(r,o,t);return(async()=>{try{for await(const e of i){if(void 0!==p&&e instanceof d.yT)try{p.message(e)}catch{}await a.write(e)}await a.write(new d.$Y({message:{case:"streamClose",value:new d.D9({id:t.id})}})),C.increment(r,1,{exec_case:o})}catch(e){if(e instanceof h.W2)return;E.increment(r,1,{exec_case:o}),await a.write(new d.$Y({message:{case:"throw",value:new d.Fu({id:t.id,error:e instanceof Error?w(e.message,e,{includeStderr:this.includeGitStderrInThrows()}):"Unknown error",stackTrace:e instanceof Error?e.stack:void 0,errorCode:R(e)})}}))}finally{if(void 0!==p)try{p.done()}catch{}const e=performance.now()-u;if(S.histogram(r,e,{exec_case:o}),_.has(o)){const t=r.get(v)?.();void 0!==t&&k.histogram(r,e,{exec_case:o,...t})}clearTimeout(c),a.close(),this.runningExecs.delete(t.id),n()}})(),a}this.runningExecs.delete(t.id),n();const s=t.message.case,i=(void 0===s?void 0:x[s])??`No handler found for server message of type ${s}`;return b.error(e,i,{messageCase:s}),E.increment(e,1,{exec_case:o}),async function*(){yield new d.$Y({message:{case:"throw",value:new d.Fu({id:t.id,error:i})}}),yield new d.$Y({message:{case:"streamClose",value:new d.D9({id:t.id})}})}()}static fromResources(e,t){const r=new A(t);for(const[t,n]of e.entries())t.registerControlledImplementation(n,r);return r}}var $=r("../context/dist/otel.js");async function M(e){const t=e[Symbol.asyncIterator](),r=await t.next();if(r.done)return;const n={async*[Symbol.asyncIterator](){for(;;){const e=await t.next();if(e.done)return;yield e.value}}};return{firstItem:r.value,rest:n}}const D=(0,y.cF)(Symbol("agentExec.remoteExecResultObserverFactory"),void 0),O={message(){},[Symbol.dispose](){}};function F(e){const t=e.get(D);if(void 0===t)return O;let r;try{r=t(e)}catch{return O}return void 0===r?O:{message(e){try{r?.message(e)}catch{r=void 0}},[Symbol.dispose](){const e=r;r=void 0;try{e?.end()}catch{}}}}var N=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},L=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const j=(0,l.h)("ExecutorResource"),U=(0,u.Pu)("agent_exec.hook_additional_context.delivered",{description:"Hook additional_context carriers drained into the caller collector",labelNames:["hook_event_name"]});class B{constructor(e,t,r){this.execManager=e,this.serializeArgs=t,this.deserializeResult=r}async execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=N(n,(0,$.VI)(e.withName("ExecutorResource.execute")),!1),s=o.ctx;void 0!==r?.execId&&o.span.setAttribute("exec.id",r.execId);const i=(0,$.mJ)(s),a=i?new d.Kg(i):void 0,c=this.execManager.createExecInstance(s,(e=>{const n=this.serializeArgs(e,t);return new d.Ye({id:n.id,message:n.message,execId:r?.execId,machineId:r?.machineId,spanContext:a,acceptHookAdditionalContexts:void 0!==r?.hookContextCollector,recordAgentView:r?.recordAgentView,refuseUnreadChanges:r?.refuseUnreadChanges})})),l=await M(c);if(void 0===l)throw new Error("No exec result");let{firstItem:u,rest:h}=l;const p=N(n,F(s),!1),f=e=>{if(p.message(e),void 0!==r?.hookContextCollector&&e.hookAdditionalContexts.length>0){r.hookContextCollector.push(...e.hookAdditionalContexts);for(const t of e.hookAdditionalContexts)U.increment(s,1,{hook_event_name:t.hookEventName})}};f(u);let m=this.deserializeResult(u);for(;void 0===m;){const e=await M(h);if(void 0===e)throw new Error("No result value");u=e.firstItem,h=e.rest,f(u),m=this.deserializeResult(u)}return(async()=>{try{for await(const e of h)f(e)}catch(e){j.info(s,"Ignoring exec stream shutdown during detached drain",{error:e})}})().catch((()=>{})),m}catch(e){n.error=e,n.hasError=!0}finally{L(n)}}}class W{constructor(e,t,r){this.execManager=e,this.serializeArgs=t,this.deserializeStream=r}async*execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=N(n,(0,$.VI)(e.withName("StreamExecutorResource.execute")),!1).ctx,s=(0,$.mJ)(o),i=s?new d.Kg(s):void 0,a=this.execManager.createExecInstance(o,(e=>{const n=this.serializeArgs(e,t);return new d.Ye({id:n.id,message:n.message,execId:r?.execId,machineId:r?.machineId,spanContext:i,acceptHookAdditionalContexts:void 0!==r?.hookContextCollector||!0===r?.deliverAgentStoreConflictNotices})})),c=N(n,F(o),!1);for await(const e of a){c.message(e),void 0!==r?.hookContextCollector&&e.hookAdditionalContexts.length>0&&r.hookContextCollector.push(...e.hookAdditionalContexts);const t=this.deserializeStream(e);void 0!==t&&(yield t)}}catch(e){n.error=e,n.hasError=!0}finally{L(n)}}}function H(e){return Symbol.for(`@anysphere/agent-exec/resource/${e}`)}function q(e,t,r){return{name:e,symbol:H(e),remoteImplementation:t,registerControlledImplementation:r}}class z{constructor(e,t){this.resource=e,this.value=t}}function G(e,t){return[e,t]}function V(e,t){return t}class K{constructor(){this.resources=new Map}register(e,t){this.resources.set(e.symbol,new z(e,t))}get(e){return V(0,this.resources.get(e.symbol)?.value)}entries(){return Array.from(this.resources.values()).map((e=>[e.resource,e.value]))}}class J{constructor(e,t){this.remoteAccessor=e,this.localResources=new Map;for(const[e,r]of t)this.localResources.set(e.symbol,{resource:e,implementation:r})}get(e){const t=this.localResources.get(e.symbol);return t?V(0,t.implementation):this.remoteAccessor.get(e)}*entries(){for(const{resource:e,implementation:t}of this.localResources.values())yield[e,t];for(const e of this.remoteAccessor.entries())this.localResources.has(e[0].symbol)||(yield e)}}function Z(e){return function(t,r){return new d.Ye({id:t,message:{case:e,value:r}})}}function X(e){return t=>{if(t.message.case===e)return t.message.value}}function Q(e){return function(t,r){const n={case:e,value:r};return new d.yT({id:t,message:n})}}function Y(e){return function(t){if(t.message.case===e)return{id:t.id,args:t.message.value}}}const ee=q("shell-stream-executor",(e=>new W(e,Z("shellStreamArgs"),X("shellStream"))),((e,t)=>{t.register(new T(e,Y("shellStreamArgs"),Q("shellStream")))}));var te=r("../proto/dist/generated/agent/v1/kv_pb.js"),re=r("../agent-kv/dist/blob-store.js"),ne=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const oe=(0,l.h)("ControlledKvManager");function se(e,t,r){return e?(0,$.F)({traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags??1},t,r):r}function ie(e,t,r,n,o){o<=r||(0,$.xd)(e.withName(`${t}.slow`),{startTime:n,attributes:{durationMs:o,slowThresholdMs:r}},n+o)}const ae=(0,u.v5)("agent_kv.controlled.get_blob.duration_ms",{description:"Duration of ControlledKvManager getBlob operations in milliseconds"}),ce=(0,u.v5)("agent_kv.controlled.set_blob.duration_ms",{description:"Duration of ControlledKvManager setBlob operations in milliseconds"});class le{constructor(e,t,r,n={}){this.serverStream=e,this.clientStream=t,this.blobStore=r,this.options=n}async run(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,$.VI)(e.withName("ControlledKvManager.run")),!1).ctx,n=new Set,o=e=>{n.add(e),e.finally((()=>{n.delete(e)}))};try{for await(const e of this.serverStream){const t=performance.now(),n=Date.now();switch(e.message.case){case"getBlobArgs":{const s=e.message.value.blobId;o((async()=>{const o=se(e.spanContext,"ControlledKvManager.getBlob",r);try{await(this.options.beforeGetBlob?.(o,s));const t=await this.blobStore.getBlob(o,s);await this.clientStream.write(new te.gm({id:e.id,message:{case:"getBlobResult",value:{blobData:t?(0,re.Fo)(t):void 0}}}))}catch(t){oe.error(o,"Error handling getBlob",t);const r=t instanceof Error?t.message:String(t);try{await this.clientStream.write(new te.gm({id:e.id,message:{case:"getBlobResult",value:{blobData:void 0,error:{message:r}}}}))}catch(e){oe.error(o,"Error writing failed getBlobResult",e)}}finally{const e=performance.now()-t;ae.histogram(o,e),ie(o,"ControlledKvManager.getBlob",50,n,e)}})());break}case"setBlobArgs":{const s=e.message.value.blobId,i=e.message.value.blobData;o((async()=>{const o=se(e.spanContext,"ControlledKvManager.setBlob",r);try{await this.blobStore.setBlob(o,s,i),await this.clientStream.write(new te.gm({id:e.id,message:{case:"setBlobResult",value:{error:void 0}}}))}catch(t){const r=t instanceof Error?t.message:String(t);try{await this.clientStream.write(new te.gm({id:e.id,message:{case:"setBlobResult",value:{error:{message:r}}}}))}catch(e){oe.error(o,"Error writing setBlobResult",e)}}finally{const e=performance.now()-t;ce.histogram(o,e),ie(o,"ControlledKvManager.setBlob",100,n,e)}})());break}}}}finally{await Promise.allSettled(n)}}catch(e){t.error=e,t.hasError=!0}finally{ne(t)}}}function ue(e){return e instanceof Error?{abortReasonType:"error",abortReasonName:e.name,abortReasonMessage:e.message}:"string"==typeof e?{abortReasonType:"string",abortReasonMessage:e}:void 0===e?{abortReasonType:"undefined"}:{abortReasonType:typeof e}}var de=r("../proto/dist/generated/agent/v1/agent_service_pb.js"),he=r("../proto/dist/generated/agent/v1/shell_exec_pb.js");Error;const pe={stateRestoreMs:"client_prep_state_restore_ms",rootPromptRestoreMs:"client_prep_root_prompt_restore_ms",requestContextMs:"client_prep_request_context_ms",systemPromptMs:"client_prep_system_prompt_ms",preTurnSnapshotMs:"client_prep_pre_turn_snapshot_ms",preTurnSnapshotWaitMs:"client_prep_pre_turn_snapshot_wait_ms",preTurnSnapshotBlobWritesMs:"client_prep_pre_turn_snapshot_blob_writes_ms",preTurnSnapshotSerializeMs:"client_prep_pre_turn_snapshot_serialize_ms",firstStepToFirstInvocationMs:"client_prep_first_step_to_first_invocation_ms",promptMessageCount:"client_prep_prompt_message_count",turnCount:"client_prep_turn_count"},fe=Object.keys(pe).filter((e=>e in pe));function me(e){const t={};for(const r of fe){const n=e[r];void 0!==n&&(t[r]=n)}return t}new WeakMap;var ge=r("../utils/dist/fresh-uuid.js"),we=r("@bufbuild/protobuf"),ye=r("@connectrpc/connect"),ve=r("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/protocol/async-iterable.js"),be=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class Se{constructor(e,t,r){this.checkpointStream=e,this.checkpointHandler=t,this.ctx=r}async run(){const e={stack:[],error:void 0,hasError:!1};try{const t=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(e,(0,$.VI)(this.ctx.withName("CheckpointController.run")),!1).ctx,r=[];for await(const e of this.checkpointStream){let n;try{n=this.checkpointHandler.handleCheckpoint(t,e.checkpoint,e.metadata)}catch(t){throw e.onSettled?.(),t}r.push(n),void 0!==e.onSettled&&n.then(e.onSettled,e.onSettled)}await Promise.all(r)}catch(t){e.error=t,e.hasError=!0}finally{be(e)}}}const ke=(0,l.h)("@anysphere/agent-client:checkpoint-store-waits");class _e{constructor(e={}){this.options=e,this.inFlight=new Map}noteRouted(e){const t=Ee(e.pendingToolCalls);if(0===t.size)return Ce;let r;const n=new Promise((e=>{r=e}));for(const e of t){let t=this.inFlight.get(e);void 0===t&&(t=new Set,this.inFlight.set(e,t)),t.add(n)}return()=>{for(const e of t){const t=this.inFlight.get(e);t?.delete(n),0===t?.size&&this.inFlight.delete(e)}r()}}storedBefore(e,t){const r=this.inFlight.get(t);if(void 0!==r){try{this.options.onExecHeld?.(t)}catch(t){ke.warn(e,"onExecHeldForCheckpointStore callback failed",{error:String(t)})}return Promise.all(r).then(Ce)}}}function Ce(){}function Ee(e){const t=new Set;for(const r of e){let e;try{e=JSON.parse(r)}catch{continue}const n=Pe(e)?e.content:void 0;if(!Array.isArray(n))continue;const o=n;for(const e of o)Pe(e)&&"tool-call"===e.type&&"string"==typeof e.toolCallId&&t.add(e.toolCallId)}return t}function xe(e){if("executeHookArgs"===e.message.case)return function(e){const t=e.request?.request;switch(t?.case){case"preToolUse":case"postToolUse":case"postToolUseFailure":return""===t.value.toolUseId?void 0:t.value.toolUseId;case"subagentStart":return""===t.value.toolCallId?void 0:t.value.toolCallId;default:return}}(e.message.value);const t=e.message.value;return Pe(t)&&"string"==typeof t.toolCallId&&""!==t.toolCallId?t.toolCallId:void 0}function Pe(e){return"object"==typeof e&&null!==e}const Re=(0,l.h)("@anysphere/agent-client:exec-checkpoint-gate"),Ie=new Set(["shellArgs","shellStreamArgs","backgroundShellSpawnArgs","forceBackgroundShellArgs","miniSweAgentBashArgs","writeArgs","deleteArgs","mcpArgs","readMcpResourceExecArgs","computerUseArgs","recordScreenArgs","subagentArgs","forceBackgroundSubagentArgs","executeHookArgs"]),Te=new Set(["userMessageAction","resumeAction","backgroundTaskCompletionAction","goalContinuationAction","subscriptionNotificationAction","executePlanAction","asyncAskQuestionCompletionAction"]);function Ae(e){const t=e.message.case;return void 0!==t&&Ie.has(t)?xe(e):void 0}const $e=e=>e.replace(/[\r\n]/g,"");function Me(e){return{...void 0!==e.parentRequestId?{"x-parent-request-id":$e(e.parentRequestId)}:{},...void 0!==e.rootParentRequestId?{"x-root-parent-request-id":$e(e.rootParentRequestId)}:{},...void 0!==e.parentAgentToolCallId?{"x-parent-agent-tool-call-id":$e(e.parentAgentToolCallId)}:{},...!0===e.directMetaParentChildSubagent?{"x-direct-meta-parent-child-subagent":"true"}:{}}}const De="x-inference-authentication-jwt";function Oe(){const e=globalThis.process?.env,t=e?.INFERENCE_PROXY_JWT?.trim();return void 0===t||""===t||t.startsWith("$")?{}:{[De]:t}}class Fe extends Error{constructor(e,t){super(`This conversation's data is missing and can't be restored. Start a new chat to continue.${function(e){if(0===e.length)return"";const t=e.slice(0,3).map((e=>e.slice(0,12)));return` (${1===e.length?`missing blob ${t[0]}`:`${e.length} missing blobs: ${t.join(", ")}${e.length>t.length?", …":""}`})`}(e)}`,void 0!==t?.cause?{cause:t.cause}:void 0),this.isUsageError=!0,this.isBlobNotFound=!0,this.name="BlobNotFoundError",this.blobIdHexes=[...e]}}function Ne(e){return e instanceof Error&&(e instanceof Fe||"isBlobNotFound"in e&&!0===e.isBlobNotFound||"BlobNotFoundError"===e.name)}var Le=r("../proto/dist/generated/aiserver/v1/utils_pb.js"),je=r("zod/v4");const Ue="relayedAttemptFailure",Be=je.object({transport:je.boolean(),stallAborted:je.boolean(),errorName:je.string(),connectCode:je.number().optional(),connectCodeName:je.string().optional(),connectCause:je.object({code:je.union([je.string(),je.number()]).optional(),name:je.string().optional()}).optional(),transportFailureKind:je.string().optional(),loop:je.string().optional(),transportMode:je.string().optional()});function We(e){const t=e?.details?.additionalInfo[Ue];if(void 0!==t)try{const e=Be.safeParse(JSON.parse(t));return e.success?e.data:void 0}catch{return}}class He extends Error{constructor(e,t={}){super(e),Object.setPrototypeOf(this,new.target.prototype),this.cause=t.cause,this.requestId=t.requestId,this.displayInfo=t.displayInfo,this.isTransport=t.isTransport}get name(){return this.kind}}class qe extends He{get kind(){return"RetriableError"}}class ze extends He{constructor(e,t,r={}){super(e,r),this.action=t}get kind(){return"ActionRequiredError"}}class Ge extends He{get kind(){return"NonRetriableError"}}class Ve extends Ge{constructor(e){const t=`This turn's step limit (${e}) needs an in-process agent loop; the network client cannot send it.`;super(t,{displayInfo:{title:"Step limit not supported",detail:t,isRetryable:!1}}),this.maxSteps=e}}class Ke extends He{get kind(){return"CancelledError"}}const Je=new Set([Le.yM.NOT_LOGGED_IN,Le.yM.AGENT_REQUIRES_LOGIN,Le.yM.AUTH_TOKEN_NOT_FOUND,Le.yM.AUTH_TOKEN_EXPIRED,Le.yM.INVALID_AUTH_ID,Le.yM.UNAUTHORIZED,Le.yM.GITHUB_NO_USER_CREDENTIALS,Le.yM.GITHUB_USER_NO_ACCESS]),Ze=new Set([Le.yM.FREE_USER_USAGE_LIMIT,Le.yM.FREE_USER_RATE_LIMIT_EXCEEDED,Le.yM.PRO_USER_ONLY,Le.yM.PRO_USER_USAGE_LIMIT,Le.yM.PRO_USER_RATE_LIMIT_EXCEEDED,Le.yM.RATE_LIMITED,Le.yM.RATE_LIMITED_CHANGEABLE,Le.yM.GENERIC_RATE_LIMIT_EXCEEDED]),Xe=new Set([Le.yM.USAGE_PRICING_REQUIRED,Le.yM.USAGE_PRICING_REQUIRED_CHANGEABLE]),Qe=new Set([Le.yM.BAD_API_KEY,Le.yM.BAD_USER_API_KEY,Le.yM.OUTDATED_CLIENT]),Ye=new Set([Le.yM.USER_ABORTED_REQUEST,Le.yM.DEBOUNCED]),et=new Set([Le.yM.CUSTOM_MESSAGE]),tt=new Map([[ye.Code.PermissionDenied,"Permission Denied"]]),rt=["NGHTTP2","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE","socket hang up","Premature close","UND_ERR_SOCKET","ERR_STREAM","protocol error","http/2 stream","ERR_HTTP2_SESSION_ERROR","Session closed with error code","connection aborted","PING timed out","HTTP/2 session not established","HTTP/2 peer not answering","refused to tunnel to","HTTP CONNECT through proxy","Could not connect to proxy"],nt=new Set(["ENOTFOUND","EAI_AGAIN","EAI_FAIL","ENODATA","ESERVFAIL","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ECONNABORTED"]),ot=new RegExp(`\\b(${[...nt].join("|")})\\b`),st=["IMAGE_TOO_LARGE","MAX_TOKENS","CONVERSATION_TOO_LONG","CONTENT_POLICY","DEPRECATED","MAX_MODE_REQUIRED","MODEL_NO_LONGER_SUPPORTED","UNSUPPORTED_REGION","OUTDATED_CLIENT"],it="x-cursor-inference-request-error-type",at="AgentWebSocketDeliveryAmbiguousError";function ct(e,t={}){const{requestId:r}=t;if(e instanceof He)return e;if(lt(e))return function(e,t){const r=dt(e),n=r.code,o=ht(e),s=void 0===o?void 0:function(e){if(void 0===e.details?.additionalInfo[Ue])return e;const t=e.clone();return void 0!==t.details&&(delete t.details.additionalInfo[Ue],t.details.equals(new Le.ej)&&(t.details=void 0)),t}(o),i={title:s?.details?.title,detail:s?.details?.detail,isRetryable:s?.details?.isRetryable,connectCode:n,errorCode:s?.error,inferenceRequestErrorType:pt(r,it)??pt(e,it),errorDetails:s},a={cause:e,requestId:t,displayInfo:i,...!0===We(o)?.transport?{isTransport:!0}:{}};if(n===ye.Code.Canceled||n===ye.Code.Aborted)return bt(e)?new qe(e.message,a):new Ke(e.message,a);if(void 0!==s?.error){const t=s.error;if(Ye.has(t))return new Ke(wt(e,s),a);const r=s.details?.analyticsMetadata?.actionRequired;if(void 0!==r&&""!==r)return new ze(wt(e,s),r,a);if(void 0!==At(s))return new qe(wt(e,s),a);if(Je.has(t))return new ze(wt(e,s),"login",a);if(Ze.has(t))return new ze(wt(e,s),"upgrade",a);if(Xe.has(t))return new ze(wt(e,s),"payment",a);if(Qe.has(t))return new ze(wt(e,s),"config",a);if(et.has(t)&&!0!==s.details?.isRetryable)return new Ge(wt(e,s),a);if(!1===s.details?.isRetryable)return new Ge(wt(e,s),a)}if(n===ye.Code.Unauthenticated)return new ze(e.message,"login",{...a,displayInfo:ut(i,"Sign in required",r)});const c=gt(r);if(Rt.test(c))return new ze(e.message,"proxy_sign_in",{...a,displayInfo:{...i,title:"Proxy sign-in required",detail:`${c}. Please check your sign-in for this proxy and try again.`,isRetryable:!0}});if(It.test(c))return new ze(e.message,"proxy_blocked",{...a,displayInfo:{...i,title:"Connection blocked by proxy",detail:`${c}. Your proxy doesn't allow this connection. Please ask your network administrator to allow it and try again.`,isRetryable:!0}});const l=tt.get(n);return void 0===l||!0===s?.details?.isRetryable||bt(e)?new qe(e.message,a):new Ge(wt(e,s),{...a,displayInfo:ut(i,l,r)})}(e,r);const n=function(e){let t=e;for(let e=0;e<10;e++){if(null==t)return;if(Ne(t))return t;if("object"!=typeof t||!("cause"in t))return;t=t.cause}}(e);if(void 0!==n)return new Ge(n.message,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Conversation data missing",detail:n.message,isRetryable:!1}});const o=function(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){if(r.name===yt)return r;t.add(r),r=r.cause}}(e);if(void 0!==o)return new Ge(o.message,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Context summarization failed",detail:o.message,isRetryable:!1}});if(function(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){const e="code"in r?r.code:void 0,n="errcode"in r?r.errcode:void 0;if("ENOSPC"===e||"ERR_SQLITE_ERROR"===e&&"number"==typeof n&&13==(255&n))return!0;t.add(r),r=r.cause}return!1}(e))return new Ge(vt,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Out of disk space",detail:vt,isRetryable:!1}});if(e instanceof Error){if("AbortError"===e.name)return new Ke(e.message,{cause:e,requestId:r});if(e.name===at)return new qe(e.message,{cause:e,requestId:r,isTransport:!0});if(bt(e))return new qe(e.message,{cause:e,requestId:r})}const s=e instanceof Error?e.message:String(e);return new qe(s,{cause:e instanceof Error?e:void 0,requestId:r})}function lt(e){return null!==e&&"object"==typeof e&&"code"in e&&"name"in e&&("ConnectError"===e.name||"rawMessage"in e&&"string"==typeof e.rawMessage&&"details"in e&&Array.isArray(e.details)&&"findDetails"in e&&"function"==typeof e.findDetails)}function ut(e,t,r){return{...e,title:e.title||t,detail:e.detail||gt(r),isRetryable:e.isRetryable??!1}}function dt(e){let t=e;for(let e=0;e<10&&t.code===ye.Code.Unknown;e++){const e=t.cause;if(!lt(e))break;t=e}return t}function ht(e){let t=e;for(let e=0;e<10&<(t);e++){try{const e=t.findDetails?.(Le.vj);if(void 0!==e&&e.length>0)return e[0]}catch{}t=t.cause}}function pt(e,t){const r=e.metadata;if(null===r||"object"!=typeof r||!("get"in r)||"function"!=typeof r.get)return;const n=r.get(t);return"string"==typeof n?n:void 0}function ft(e){let t=e;for(let e=0;e<10&&"object"==typeof t&&null!==t;e++){if(lt(t))return t;t="cause"in t?t.cause:void 0}}function mt(e){const t=ft(e);return void 0===t?void 0:dt(t)}function gt(e){const t=e.rawMessage;return"string"==typeof t?t:e.message.replace(/^\[[a-z_]+\] /,"")}function wt(e,t){if(t?.details){const{title:r,detail:n}=t.details;return r&&n?`${r} ${n}`:r||n||e.message}return e.message}const yt="SummaryPlaceholderRejectedError",vt="Out of disk space. Free some space and try again.";function bt(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){t.add(r);const e=`${r.name}: ${r.message}`;if(rt.some((t=>e.includes(t)))||ot.test(e))return!0;const n=r.code;if("string"==typeof n&&(rt.some((e=>n.includes(e)))||nt.has(n)))return!0;r=r.cause}return!1}function St(e){return rt.some((t=>e.includes(t)))||ot.test(e)}function kt(e){return e instanceof He&&e.cause instanceof Error?bt(e.cause):e instanceof Error?bt(e):"string"==typeof e&&St(e)}function _t(e){return void 0!==e&&e>0}function Ct(e){return e+1}function Et(e){return Object.defineProperty(e,"code",{value:"connection_stalled",enumerable:!0,configurable:!0}),e}function xt(e){const{cause:t,requestId:r,transportErrorRetries:n,connectCode:o}=e;return _t(n)?Et(new qe("Connection stalled repeatedly",{cause:t,requestId:r,displayInfo:{title:"Connection stalled",detail:`The connection stalled ${Ct(n)} times. Please check your network connection and try again.`,isRetryable:!0,connectCode:o}})):Et(new qe("Connection stalled",{cause:t,requestId:r,displayInfo:{title:"Connection stalled",detail:"The connection stalled. Please try again.",isRetryable:!0,connectCode:o}}))}const Pt=/^(?:Proxy \S+ refused to tunnel to |HTTP CONNECT through proxy \S+ failed: |Could not connect to proxy \S+: )/,Rt=/^Proxy \S+ refused to tunnel to \S+: 407\b/,It=/^Proxy \S+ refused to tunnel to \S+: 403\b/;function Tt(e){let t=e.cause;for(let e=0;e<10&&void 0!==t;e++){if(t instanceof Error&&"AbortError"===t.name)return!0;if(lt(t)&&(t.code===ye.Code.Canceled||t.code===ye.Code.Aborted))return!0;t=null!==t&&"object"==typeof t&&"cause"in t?t.cause:void 0}return!1}function At(e){const t=e?.details?.additionalInfo;if(e?.error!==Le.yM.RATE_LIMITED||"run_inference_novel_tokens"!==t?.kind||void 0===t.retryAfterMs)return;const r=Number(t.retryAfterMs);return Number.isFinite(r)&&r>=0?r:void 0}var $t=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Mt=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Dt=(0,l.h)("@anysphere/agent-client:exec-controller");class Ot extends Error{constructor(e){super(e),this.name="LostConnection"}}class Ft{constructor(e,t,r,n){this.serverStream=e,this.clientStream=t,this.controlledExecManager=r,this.checkpointStoreWaits=n}async run(e){const t={stack:[],error:void 0,hasError:!1};try{$t(t,(0,$.VI)(e.withName("ClientExecController.run")),!1);const r=[],n=t=>{if((0,we.isMessage)(t,d.Nv))this.controlledExecManager.handleControlMessage(t);else{const n=this.execute(e,t);n.catch((()=>{})),r.push(n)}};let o,s,i=!1;try{try{for await(const t of this.serverStream){const r=(0,we.isMessage)(t,d.Nv)?void 0:xe(t),a=void 0===r?void 0:this.checkpointStoreWaits?.storedBefore(e,r);if(void 0===o&&void 0===a){n(t);continue}const c=(o??Promise.resolve()).then((async()=>{await a,(0,we.isMessage)(t,d.Nv)||!i&&!e.canceled?n(t):Dt.info(e,"Dropped an exec queued behind a checkpoint's store",{toolCallId:r})})).catch((e=>{s??={error:e}}));o=c,c.then((()=>{o===c&&(o=void 0)}))}}finally{i=!0}if(await o,void 0!==s)throw s.error;await Promise.all(r)}catch(e){if(e instanceof ye.ConnectError&&"protocol error: missing EndStreamResponse"===e.rawMessage)throw new Ot(e.message);if(e instanceof ye.ConnectError&&e.code===ye.Code.Aborted){const t=e.cause;if(t instanceof Error&&"code"in t&&"string"==typeof t.code&&t.code.includes("ERR_STREAM_WRITE_AFTER_END"))throw new Ot(e.message)}else{if(e instanceof h.W2)throw new Ot(e.message);if(e instanceof ye.ConnectError&&e.code===ye.Code.Internal){const t=e.cause;if(t instanceof Error&&t.message.includes("NGHTTP2_PROTOCOL_ERROR"))throw new Ot(e.message)}}throw e}}catch(e){t.error=e,t.hasError=!0}finally{Mt(t)}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{let n,o;if(t.spanContext){const r=t.spanContext;n=(0,$.V5)({traceId:r.traceId,spanId:r.spanId,traceFlags:r.traceFlags??1},"exec.handle",e),o=(0,$.fU)(n)}else n=e;$t(r,o?new $.r2(n,o):void 0,!1);const s=this.controlledExecManager.handle(n,t);for await(const e of s)await this.clientStream.write(e)}catch(e){r.error=e,r.hasError=!0}finally{Mt(r)}}}const Nt=(0,l.h)("@anysphere/agent-client:stall-detector"),Lt=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,jt={nal:"[NAL client stall detector]",local_loop:"[local-loop client stall detector]",module:"[module client stall detector]"},Ut=new Set(["http2","http1_sse","http1_poll","websocket"]);function Bt(e){return void 0===e?"unknown":Ut.has(e)?e:"other"}const Wt=(0,u.Pu)("agent_client.stream.stall.count",{description:"Number of bidirectional stream stalls detected",labelNames:["activity_type","message_type","loop","transport_mode"]}),Ht=(0,u.v5)("agent_client.stream.stall.duration_ms",{description:"Duration of stream stalls in milliseconds",labelNames:["activity_type","loop","transport_mode"]}),qt=(0,u.Pu)("agent_client.stream.did_stall",{description:"Number of streams that experienced at least one stall",labelNames:["loop","transport_mode"]}),zt=(0,u.Pu)("agent_client.stream.total",{description:"Total number of streams monitored",labelNames:["loop","transport_mode"]});class Gt{constructor(){this.handlers=new Map}track(e,t){return this.handlers.set(e,{name:e,state:"started",startedAt:Date.now()}),t.then((t=>{const r=this.handlers.get(e);return r&&(r.state="completed",r.endedAt=Date.now()),t})).catch((t=>{const r=this.handlers.get(e);throw r&&(r.state="errored",r.endedAt=Date.now(),r.error=t instanceof Error?t.message:String(t)),t}))}getHandlerStates(){const e=Date.now(),t={};for(const[r,n]of this.handlers)t[r]={state:n.state,durationMs:(n.endedAt??e)-n.startedAt,error:n.error};return t}}class Vt{constructor(e,t,r){this.lastActivityTime=performance.now(),this.lastMeaningfulActivityTime=performance.now(),this.hasLogged=!1,this.hasLoggedAdvisory=!1,this.hasLoggedHeartbeatOnly=!1,this.hasEverStalled=!1,this.paused=!1,this.disposed=!1,this.activityHistory=[],this.ctx=e,"number"==typeof t?(this.thresholdMs=t,this.advisoryThresholdMs=void 0,this.heartbeatOnlyThresholdMs=3*t,this.onStall=r,this.onStallCallback=void 0,this.handlerTracker=void 0,this.loop="nal",this.readTransportMode=void 0):(this.thresholdMs=t.thresholdMs,this.advisoryThresholdMs=t.advisoryThresholdMs,this.heartbeatOnlyThresholdMs=t.heartbeatOnlyThresholdMs??3*t.thresholdMs,this.onStall=t.onStall,this.onStallCallback=t.onStallCallback,this.handlerTracker=t.handlerTracker,this.loop=t.loop??"nal",this.readTransportMode=t.transportMode),this.logPrefix=jt[this.loop],this.startTimer(),this.startAdvisoryTimer(),this.startHeartbeatOnlyTimer(),this.onCtxSignalAbort=()=>{this.trackActivity("ctx.signal","abort"),this.abortedAt=performance.now(),this.emitLifecycleLog(`${this.logPrefix} Stream aborted while stall detector active`,"aborted")},e.signal.addEventListener("abort",this.onCtxSignalAbort)}metricLabels(){return{loop:this.loop,transport_mode:Bt(this.readTransportMode?.())}}trackActivity(e,t){const r={type:e,messageType:t};this.lastActivity=r,"inbound_message"===e?this.lastInboundMessage=r:"outbound_write"===e&&(this.lastOutboundMessage=r);const n=this.activityHistory.at(-1);n?.type===e&&n.messageType===t?n.repeat=(n.repeat??1)+1:(this.activityHistory.push(r),this.activityHistory.length>10&&this.activityHistory.shift())}reset(e="inbound_message",t,r=!0){if(this.trackActivity(e,t),"inbound_message"===e){const e=this.hasLogged,t=this.hasLoggedAdvisory,n=this.hasLoggedHeartbeatOnly;e&&(this.hasLogged=!1,this.emitLogAndMetric()),n&&r&&(this.hasLoggedHeartbeatOnly=!1),t&&(this.hasLoggedAdvisory=!1),this.lastActivityTime=performance.now(),r&&(this.lastMeaningfulActivityTime=performance.now()),void 0===this.timer&&this.startTimer(),void 0===this.advisoryTimer&&this.startAdvisoryTimer(),r&&void 0===this.heartbeatOnlyTimer&&this.startHeartbeatOnlyTimer()}}onStreamEnded(){this.trackActivity("stream","ended"),this.streamEndedAt=performance.now()}onClientSentHeartbeat(){this.lastClientSentHeartbeatAt=performance.now()}onServerSentHeartbeat(){this.lastServerSentHeartbeatAt=performance.now()}setPaused(e){if(!this.disposed&&e!==this.paused&&(this.paused=e,!e)){const e=performance.now();this.lastActivityTime=e,this.lastMeaningfulActivityTime=e,void 0===this.timer&&this.startTimer(),void 0===this.advisoryTimer&&this.startAdvisoryTimer(),void 0===this.heartbeatOnlyTimer&&this.startHeartbeatOnlyTimer()}}restartedAfterLoopGap(e,t){const r=performance.now(),n=r-e;return!(n<5e3||t>=e||(this.reportLoopGap(n,r-t),this.lastActivityTime=r,this.lastMeaningfulActivityTime=r,0))}reportLoopGap(e,t){try{Nt.info(this.ctx,`${this.logPrefix} Stall check ran late - the process was not running, its windows restart`,this.buildLogMetadata({late_ms:e,window_ms:t,stall_type:"loop_gap"}))}catch(e){console.error("Error in stall detection:",e)}}startTimer(){if(this.disposed||this.thresholdMs<=0||void 0!==this.timer)return;let e=0;const t=t=>{e=performance.now()+t,this.timer=setTimeout(r,t)},r=()=>{if(this.paused||this.restartedAfterLoopGap(e,this.lastActivityTime))return void t(this.thresholdMs);const r=this.thresholdMs-(performance.now()-this.lastActivityTime);if(r<=0)return this.timer=void 0,void this.onStallDetected("no_activity");t(r)};t(this.thresholdMs)}startAdvisoryTimer(){if(this.disposed||void 0===this.advisoryThresholdMs||this.advisoryThresholdMs<=0||void 0!==this.advisoryTimer)return;const e=this.advisoryThresholdMs;let t=0;const r=e=>{t=performance.now()+e,this.advisoryTimer=setTimeout(n,e)},n=()=>{if(this.paused||this.restartedAfterLoopGap(t,this.lastActivityTime))return void r(e);const n=e-(performance.now()-this.lastActivityTime);if(n<=0)return this.advisoryTimer=void 0,void this.onAdvisoryDetected();r(n)};r(e)}startHeartbeatOnlyTimer(){if(this.disposed||this.thresholdMs<=0||this.heartbeatOnlyThresholdMs<=0||void 0!==this.heartbeatOnlyTimer)return;let e=0;const t=t=>{e=performance.now()+t,this.heartbeatOnlyTimer=setTimeout(r,t)},r=()=>{if(this.paused||this.restartedAfterLoopGap(e,this.lastMeaningfulActivityTime))return void t(this.heartbeatOnlyThresholdMs);const r=this.heartbeatOnlyThresholdMs-(performance.now()-this.lastMeaningfulActivityTime);if(r<=0)return this.heartbeatOnlyTimer=void 0,void this.onStallDetected("heartbeat_only");t(r)};t(this.heartbeatOnlyThresholdMs)}buildLogMetadata(e){const t=this.ctx.get(Mn),r={...e};t?.modelDetails?.displayName&&(r.model_name=t.modelDetails.displayName);const n=performance.now();void 0!==this.abortedAt&&(r.aborted_ago_ms=n-this.abortedAt),void 0!==this.disposedAt&&(r.disposed_ago_ms=n-this.disposedAt),void 0!==this.lastClientSentHeartbeatAt&&(r.last_client_sent_heartbeat_ago_ms=n-this.lastClientSentHeartbeatAt),void 0!==this.lastServerSentHeartbeatAt&&(r.last_server_sent_heartbeat_ago_ms=n-this.lastServerSentHeartbeatAt),void 0!==this.streamEndedAt&&(r.stream_ended_ago_ms=n-this.streamEndedAt),this.lastInboundMessage&&(r.last_inbound_message_type=this.lastInboundMessage.messageType),this.lastOutboundMessage&&(r.last_outbound_message_type=this.lastOutboundMessage.messageType);const o=[];let s;for(let e=this.activityHistory.length-1;e>=0;e--){const{type:t,messageType:r,repeat:n}=this.activityHistory[e];s!==t&&(s?o.push(`[${t}]`):o.push(`[${t}] (MOST RECENT)`),s=t),o.push(`${r}${n?` (x${n})`:""}`)}return r.activities=o.join("\n"),{reqId:t?.requestId,loop:this.loop,stall:r}}onAdvisoryDetected(){if(this.hasLogged||this.hasLoggedAdvisory)return;if(void 0===this.advisoryThresholdMs||this.advisoryThresholdMs<=0)return;const e=performance.now()-this.lastActivityTime;e=this.heartbeatOnlyThresholdMs){if(this.hasLoggedHeartbeatOnly)return;this.hasLoggedHeartbeatOnly=!0,this.reportStall(e,n)}return}if(this.hasLogged)return;this.hasLogged=!0,this.hasLoggedAdvisory=!0;const t=performance.now()-this.lastActivityTime;this.reportStall(e,t)}reportStall(e,t){const r=this.lastActivity,n=this.lastInboundMessage,o=this.lastOutboundMessage,s=this.ctx.get(Mn);try{const i=this.buildLogMetadata({duration_ms:t,threshold_ms:"heartbeat_only"===e?this.heartbeatOnlyThresholdMs:this.thresholdMs,stall_type:e}),a="heartbeat_only"===e?`${this.logPrefix} Stream receiving heartbeats only - no meaningful data for threshold period`:`${this.logPrefix} Bidirectional stream stall detected - no activity for threshold period`;if(Nt.warn(this.ctx,a,i),Wt.increment(this.ctx,1,{activity_type:r?.type??"unknown",message_type:r?.messageType??"unknown",...this.metricLabels()}),this.hasEverStalled||(this.hasEverStalled=!0,qt.increment(this.ctx,1,this.metricLabels())),this.onStallCallback){const t=performance.now(),i={type:e,lastActivityAgoMs:t-this.lastActivityTime,lastMeaningfulActivityAgoMs:t-this.lastMeaningfulActivityTime,lastActivityType:r?.messageType,lastInboundMessageType:n?.messageType,lastOutboundMessageType:o?.messageType,requestId:s?.requestId,modelName:s?.modelDetails?.displayName,streamEnded:void 0!==this.streamEndedAt,aborted:void 0!==this.abortedAt,lastServerHeartbeatAgoMs:void 0!==this.lastServerSentHeartbeatAt?t-this.lastServerSentHeartbeatAt:void 0,lastClientHeartbeatAgoMs:void 0!==this.lastClientSentHeartbeatAt?t-this.lastClientSentHeartbeatAt:void 0,thresholdMs:"heartbeat_only"===e?this.heartbeatOnlyThresholdMs:this.thresholdMs,handlers:this.handlerTracker?.getHandlerStates(),loop:this.loop};try{this.onStallCallback(i)}catch(e){console.error("Error in stall callback:",e)}}}catch(e){console.error("Error in stall detection:",e)}try{this.onStall?.(function(e){const t=new DOMException(`the stall detector cut the stream: ${e}`,"AbortError");return Object.defineProperty(t,"cursorStallCut",{value:!0}),t}("heartbeat_only"===e?`heartbeats alone for ${this.heartbeatOnlyThresholdMs} ms`:`no activity for ${this.thresholdMs} ms`))}catch(e){console.error("Error in onStall callback:",e)}}emitLifecycleLog(e,t){const r=performance.now()-this.lastActivityTime;try{const n=this.buildLogMetadata({duration_ms:r,event_type:t});Nt.info(this.ctx,e,n)}catch(e){console.error("Error logging stream lifecycle:",e)}}emitLogAndMetric(){const e=performance.now()-this.lastActivityTime;this.emitLifecycleLog(`${this.logPrefix} Stream activity resumed after stall`,"recovered"),Ht.histogram(this.ctx,e,{activity_type:this.lastActivity?.type??"unknown",...this.metricLabels()})}[Symbol.dispose](){this.disposed||zt.increment(this.ctx,1,this.metricLabels()),this.disposed=!0,this.paused=!1,void 0!==this.timer&&(clearTimeout(this.timer),this.timer=void 0),void 0!==this.advisoryTimer&&(clearTimeout(this.advisoryTimer),this.advisoryTimer=void 0),void 0!==this.heartbeatOnlyTimer&&(clearTimeout(this.heartbeatOnlyTimer),this.heartbeatOnlyTimer=void 0),this.ctx.signal.removeEventListener("abort",this.onCtxSignalAbort),this.trackActivity("disposed","disposed"),this.disposedAt=performance.now(),this.emitLifecycleLog(`${this.logPrefix} Stream stall detector disposed`,"disposed")}}const Kt={now:()=>performance.now(),setTimeout(e,t){const r=setTimeout(e,t);return r.unref?.(),r},clearTimeout(e){clearTimeout(e)}},Jt=(0,u.v5)("agent_client.first_message.event_loop_max_lag_ms",{description:"Longest event-loop block between the network phase start and the first server message of a run's first attempt",labelNames:["loop","transport_mode","first_message_slow"]}),Zt=(0,u.v5)("agent_client.first_message.event_loop_total_lag_ms",{description:"Summed event-loop blocking between the network phase start and the first server message of a run's first attempt",labelNames:["loop","transport_mode","first_message_slow"]}),Xt=(0,u.v5)("agent_client.first_message.network_ms",{description:"Time from the network phase start to the first server message of a run's first attempt, on attempts that sampled event-loop lag",labelNames:["loop","transport_mode","first_message_slow"]});var Qt=r("../proto/dist/generated/agent/v1/ask_question_tool_pb.js"),Yt=r("../proto/dist/generated/agent/v1/create_plan_tool_pb.js"),er=r("../proto/dist/generated/agent/v1/pr_management_tool_pb.js"),tr=r("../proto/dist/generated/agent/v1/replace_env_tool_pb.js"),rr=r("../proto/dist/generated/agent/v1/setup_vm_environment_tool_pb.js"),nr=r("../proto/dist/generated/agent/v1/connect_scm_tool_pb.js"),or=r("../proto/dist/generated/agent/v1/generate_image_tool_pb.js"),sr=r("../proto/dist/generated/agent/v1/mcp_auth_tool_pb.js"),ir=r("../proto/dist/generated/agent/v1/switch_mode_tool_pb.js"),ar=r("../proto/dist/generated/agent/v1/web_fetch_tool_pb.js"),cr=r("../proto/dist/generated/agent/v1/web_search_tool_pb.js");class lr extends Error{constructor(e){super(`Deferred interaction response requested for query ${e.id} (${e.query.case??"unknown"})`),this.query=e,this.name="DeferredInteractionResponseError",Object.setPrototypeOf(this,new.target.prototype)}}const ur=e=>new i.Y5({id:e,result:{case:"webSearchRequestResponse",value:new cr.lI({result:{case:"approved",value:new cr.XJ}})}}),dr=(e,t)=>new i.Y5({id:e,result:{case:"webSearchRequestResponse",value:new cr.lI({result:{case:"rejected",value:new cr.yc({reason:t??""})}})}}),hr=e=>new i.Y5({id:e,result:{case:"webFetchRequestResponse",value:new ar.fS({result:{case:"approved",value:new ar.Hs}})}}),pr=(e,t)=>new i.Y5({id:e,result:{case:"webFetchRequestResponse",value:new ar.fS({result:{case:"rejected",value:new ar.m$({reason:t??""})}})}}),fr=(e,t)=>new i.Y5({id:e,result:{case:"askQuestionInteractionResponse",value:new i.zT({result:t})}}),mr=e=>new i.Y5({id:e,result:{case:"switchModeRequestResponse",value:new ir.w$({result:{case:"approved",value:new ir.q5}})}}),gr=(e,t)=>new i.Y5({id:e,result:{case:"switchModeRequestResponse",value:new ir.w$({result:{case:"rejected",value:new ir.rA({reason:t??""})}})}}),wr=(e,t)=>new i.Y5({id:e,result:{case:"createPlanRequestResponse",value:new Yt.gz({result:t})}}),yr=(e,t)=>new i.Y5({id:e,result:{case:"setupVmEnvironmentResult",value:t}}),vr=(e,t)=>new i.Y5({id:e,result:{case:"replaceEnvResult",value:t}}),br=(e,t)=>new i.Y5({id:e,result:{case:"prManagementResult",value:t}}),Sr=e=>new i.Y5({id:e,result:{case:"mcpAuthRequestResponse",value:new sr.h({result:{case:"approved",value:new sr.D5}})}}),kr=(e,t)=>new i.Y5({id:e,result:{case:"mcpAuthRequestResponse",value:new sr.h({result:{case:"rejected",value:new sr.OI({reason:t??"Authentication was rejected"})}})}}),_r=(e,t)=>new i.Y5({id:e,result:{case:"connectScmRequestResponse",value:new nr.qG({result:{case:"rejected",value:new nr.lB({reason:t??"Connecting GitHub was skipped"})}})}}),Cr=(e,t)=>new i.Y5({id:e,result:{case:"generateImageRequestResponse",value:new or.vW({result:{case:"approved",value:new or.l3({description:t??""})}})}}),Er=(e,t)=>new i.Y5({id:e,result:{case:"generateImageRequestResponse",value:new or.vW({result:{case:"rejected",value:new or.Uq({reason:t??""})}})}});class xr extends Error{constructor(e,t={}){super(e),this.name="InteractionListenerStreamClosedError",this.cause=t.cause,Object.setPrototypeOf(this,new.target.prototype)}}xr.telemetryName="InteractionListenerStreamClosedError";var Pr=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Rr=(0,l.h)("ClientInteractionController"),Ir=new Set(["askQuestionInteractionQuery","switchModeRequestQuery","mcpAuthRequestQuery","connectScmRequestQuery"]);class Tr{constructor(e,t,r,n){this.interactionStream=e,this.interactionListener=t,this.queryResponseStream=r,this.stallSuspender=n,this.pendingHumanQueries=0}async run(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,$.VI)(e.withName("ClientInteractionController.run")),!1);e=r.ctx;let n,o=Promise.resolve();for await(const t of this.interactionStream){const r=()=>"interactionQuery"===t.case?this.handleInteractionQuery(e,t.value):this.handleInteractionUpdate(e,t.value);o=o.then(r).catch((r=>{Rr.error(e,"Error handling interaction message",r,{messageCase:t.case}),n??=r}))}if(await o,void 0!==n)throw n}catch(e){t.error=e,t.hasError=!0}finally{Pr(t)}}async handleInteractionUpdate(e,t){await this.interactionListener.sendUpdate(e,t)}handleInteractionQuery(e,t){const r=void 0!==t.query.case&&Ir.has(t.query.case);let n=!1;const o=()=>{r&&!n&&(n=!0,this.pendingHumanQueries--,0===this.pendingHumanQueries&&this.stallSuspender?.setPaused(!1))};r&&(this.pendingHumanQueries++,1===this.pendingHumanQueries&&this.stallSuspender?.setPaused(!0)),(async()=>this.interactionListener.query(e,t))().catch((r=>{const n=function(e,t){switch(e.query.case){case"webSearchRequestQuery":return dr(e.id,t);case"webFetchRequestQuery":return pr(e.id,t);case"askQuestionInteractionQuery":return fr(e.id,new Qt.tz({result:{case:"rejected",value:new Qt.ox({reason:t})}}));case"switchModeRequestQuery":return gr(e.id,t);case"createPlanRequestQuery":return wr(e.id,new Yt.bK({result:{case:"error",value:new Yt.iY({error:t})}}));case"setupVmEnvironmentArgs":return yr(e.id,new rr.r$({result:{case:"success",value:new rr.JH({})}}));case"replaceEnvArgs":return vr(e.id,new tr.dV({result:{case:"failure",value:new tr.uq({errorMessage:t,setupLogs:""})}}));case"prManagementRequestQuery":return br(e.id,new er.HL({result:{case:"error",value:new er.K$({error:t})}}));case"mcpAuthRequestQuery":return kr(e.id,t);case"connectScmRequestQuery":return _r(e.id,t);case"generateImageRequestQuery":return Er(e.id,t);case void 0:return;default:return e.query}}(t,"The client could not show this request to the user");if(!(n instanceof i.Y5))throw r;return Rr.error(e,"Error handling interaction query; answering with a fail-closed response",{queryCase:t.query.case,error:r}),n})).then((e=>(o(),this.queryResponseStream.write(e)))).catch((t=>{Rr.error(e,"Error handling interaction query",t)})).finally(o)}}async function Ar(e,t){let r;try{r=await e(t.signal)}catch(e){if(t.isCanceled())throw new Ke("User aborted request");throw new Ge("Failed to mint LLM Gateway credential",{cause:e instanceof Error?e:void 0,requestId:t.requestId})}if(void 0===r)throw new Ge("LLM Gateway credential minter returned no credential",{requestId:t.requestId});if(""===r.bearerToken.trim())throw new Ge("LLM Gateway credential minter returned an empty bearer token",{requestId:t.requestId});return new i.Ibo({bearerToken:r.bearerToken})}const $r=q("request-context-executor",(e=>new B(e,Z("requestContextArgs"),X("requestContextResult"))),((e,t)=>{t.register(new I(e,Y("requestContextArgs"),Q("requestContextResult")))}));var Mr=r("../agent-kv/dist/serde.js"),Dr=r("../proto/dist/generated/agent/v1/request_context_exec_pb.js"),Or=r("../utils/dist/promise-extras.js");const Fr=15728640,Nr=(0,u.Pu)("agent_client.request_context_blob.prepared",{description:"Prepared RequestContext blob references"}),Lr=(0,u.v5)("agent_client.request_context_blob.bytes",{description:"Serialized RequestContext bytes staged by the client"}),jr=(0,u.v5)("agent_client.request_context_blob.preparation_ms",{description:"Time to hydrate, serialize, and hash RequestContext"});function Ur(e){switch(e.action.case){case"userMessageAction":case"subscriptionNotificationAction":case"resumeAction":case"executePlanAction":return e.action.value;default:return}}class Br{constructor(e,t=62914560){this.parent=e,this.maxTransientBytes=t,this.transientBlobs=new Map,this.persistedBlobIds=new Set,this.transientBytes=0}seed(e,t){return this.seedAll([{blobId:e,blobData:t}])}seedAll(e){const t=new Map;for(const{blobId:r,blobData:n}of e)t.set((0,Mr.nj)(r),n.byteLength);let r=this.transientBytes;for(const[e,n]of t)r-=this.transientBlobs.get(e)?.byteLength??0,r+=n;if(r>this.maxTransientBytes)return!1;for(const{blobId:t,blobData:r}of e)this.transientBlobs.set((0,Mr.nj)(t),r);return this.transientBytes=r,!0}has(e){return this.transientBlobs.has((0,Mr.nj)(e))}hasAll(e){return e.every((e=>this.has(e)))}async getBlob(e,t){const r=(0,Mr.nj)(t),n=this.transientBlobs.get(r);return void 0===n?await this.parent.getBlob(e,t):n}async persistForRemoteRead(e,t){const r=(0,Mr.nj)(t),n=this.transientBlobs.get(r);void 0===n||this.persistedBlobIds.has(r)||(await(0,Or.O$)((()=>this.parent.setBlob(e,t,n)),2),this.persistedBlobIds.add(r))}async setBlob(e,t,r){await this.parent.setBlob(e,t,r)}async setBlobLocallyOnly(e,t,r){await this.parent.setBlobLocallyOnly(e,t,r)}async flush(e){await this.parent.flush(e)}}async function Wr({ctx:e,action:t,resources:r,blobStore:n,mode:o,maxBlobBytes:s,maxInlineDynamicBytes:i=1048576,notesSessionId:a}){const c=performance.now(),l=Ur(t);if(void 0===l)return{kind:"not_applicable"};if("legacy"===o)return t.requestContextParts=void 0,{kind:"legacy"};if(void 0!==t.requestContextParts){const e=void 0===(u=t.requestContextParts)?[]:[u.rulesBlobId,u.skillsBlobId,u.subagentsBlobId,u.mcpsBlobId],r=void 0!==l.requestContext,s=e.length>0&&n.hasAll(e);if(r||s){const e=t.requestContextParts;return"ref_only"===o&&r&&s&&void 0!==e?.dynamicContext&&(l.requestContext=void 0),{kind:"already_prepared"}}}var u;t.requestContextParts=void 0;const d=void 0===l.requestContext,h=l.requestContext??await async function({ctx:e,resources:t,notesSessionId:r}){const n=t.get($r),o=await n.execute(e,new Dr._K({notesSessionId:r})),s="success"===o.result.case?o.result.value.requestContext:void 0;if(void 0===s)throw new Error(`Failed to compute request context: ${o.result.case}`);return s}({ctx:e,resources:r,notesSessionId:a}),p=Math.min(Math.max(0,s),Fr),f=await async function({requestContext:e,mode:t,maxBlobBytes:r,maxInlineDynamicBytes:n}){const o=function(e){const t=e.clone();return t.rules=[],t.nonFileRules=[],t.cloudRule=void 0,t.agentSkills=[],t.skillOptions=void 0,t.customSubagents=[],t.tools=[],t.mcpInstructions=[],t.mcpFileSystemOptions=void 0,t.mcpMetaToolOptions=void 0,{dynamicContext:t,rules:new Dr.T3({rules:e.rules.map((e=>e.clone())),nonFileRules:e.nonFileRules.map((e=>e.clone())),cloudRule:e.cloudRule}),skills:new Dr.CB({agentSkills:e.agentSkills.map((e=>e.clone())),skillOptions:e.skillOptions?.clone()}),subagents:new Dr.yb({customSubagents:e.customSubagents.map((e=>e.clone()))}),mcps:new Dr.vB({tools:e.tools.map((e=>e.clone())),mcpInstructions:e.mcpInstructions.map((e=>e.clone())),mcpFileSystemOptions:e.mcpFileSystemOptions?.clone(),mcpMetaToolOptions:e.mcpMetaToolOptions?.clone()})}}(e),s="ref_only"===t?o.dynamicContext.toBinary().byteLength:void 0;if(void 0!==s&&s>n)return;const i=o.rules.toBinary(),a=o.skills.toBinary(),c=o.subagents.toBinary(),l=o.mcps.toBinary(),u=i.byteLength+a.byteLength+c.byteLength+l.byteLength;if(u>r)return;const[d,h,p,f]=await Promise.all([(0,re.Bk)(i),(0,re.Bk)(a),(0,re.Bk)(c),(0,re.Bk)(l)]),m=[{blobId:d,blobData:i},{blobId:h,blobData:a},{blobId:p,blobData:c},{blobId:f,blobData:l}],g=new Dr.sG({rulesBlobId:d,rulesByteLength:i.byteLength,skillsBlobId:h,skillsByteLength:a.byteLength,subagentsBlobId:p,subagentsByteLength:c.byteLength,mcpsBlobId:f,mcpsByteLength:l.byteLength,dynamicContext:"ref_only"===t?o.dynamicContext:void 0});if("dual"===t)return{kind:"dual",inlineContext:e,byteLength:u,parts:g};if(void 0===s)throw new Error("ref_only request context did not measure dynamic bytes");return{kind:"ref_only",stagedBlobs:m,byteLength:u,parts:g,dynamicByteLength:s}}({requestContext:h,mode:o,maxBlobBytes:p,maxInlineDynamicBytes:Math.min(Math.max(0,i),p)});if(void 0===f)return l.requestContext=h,t.requestContextParts=void 0,Nr.increment(e,1,{mode:o,outcome:"oversized"}),{kind:"oversized"};if("ref_only"===f.kind&&!n.seedAll(f.stagedBlobs))return l.requestContext=h,t.requestContextParts=void 0,Nr.increment(e,1,{mode:o,outcome:"transient_budget_exceeded"}),{kind:"transient_budget_exceeded"};l.requestContext="dual"===f.kind?f.inlineContext:void 0,t.requestContextParts=f.parts;const m=f.byteLength;return Nr.increment(e,1,{mode:o,outcome:d?"hydrated":"inline"}),Lr.histogram(e,m,{mode:o}),jr.histogram(e,performance.now()-c,{mode:o}),{kind:"prepared",byteLength:m,hydrated:d,rulesByteLength:f.parts.rulesByteLength,skillsByteLength:f.parts.skillsByteLength,subagentsByteLength:f.parts.subagentsByteLength,mcpsByteLength:f.parts.mcpsByteLength,dynamicByteLength:"ref_only"===f.kind?f.dynamicByteLength:void 0}}function Hr(e){return Object.keys(e.fileContents).length>0}function qr(e,t){return Object.assign(new(e.getType()),e,t)}function zr(e){return qr(e,{fileContents:{}})}function Gr(e){for(const[t]of e.entries())if(t.symbol===$r.symbol)return e.get($r)}var Vr=r("../proto/dist/generated/agent/v1/cursor_rules_pb.js");const Kr=102400;function Jr(e){return"AGENTS.md"===e||"CLAUDE.md"===e||"CLAUDE.local.md"===e}function Zr({content:e,filename:t}){return Buffer.byteLength(e,"utf8")>Kr?function({content:e,filename:t}){const r=Buffer.from(e,"utf8");let n=Kr;for(;128==(192&r.readUInt8(n));)n--;const o=`[truncated: ${t} is ${Math.round(r.length/1024)} KB; only the first 100 KB is included]`;return`${r.subarray(0,n).toString("utf8")}\n\n${o}`}({content:e,filename:t}):e}function Xr(e){const t=/^\s*("(?:[^"\\]|\\.)*"|'(?:[^']|'')*')\s+#/.exec(e);return null!==t?t[1]:/^\s*["']/.test(e)?e.trim():e.replace(/\s#.*$/,"").trim()}function Qr(e,t){return"description"===e?t.trim():Xr(t)}function Yr(e){const t=e.trim();return"true"===t||"false"!==t&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t)}function en(e){const t=e.trimStart();if(!t.startsWith("---"))return null;const r=t.split("---").filter(Boolean);if(r.length<2)return null;const n=r[0].trim(),o=r.slice(1).join("---").trim(),s={};let i=null,a=null;for(const e of n.split("\n")){const t=e.replace(/\r$/,"");if(/^\s*#/.test(t))continue;const r=t.match(/^\s+-\s+(.*)$/);if(r&&a){let e=Xr(r[1]);(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1));const t=s[a];Array.isArray(t)&&t.push(e);continue}const n=t.startsWith(" ")||t.startsWith("\t");if(i&&n){const e=t.trim(),r=e.indexOf(":");if(-1===r)continue;const n=e.slice(0,r).trim(),o=Xr(e.slice(r+1)),c=Yr(o),l=`${i}.${n}`;""===o?(s[l]=[],a=l):"metadata.environments"===l||"metadata.disabledEnvironments"===l||"metadata.scopedTo"===l?(s[l]=String(c).split(",").map((e=>e.trim())).filter(Boolean),a=null):(s[l]=c,a=null);continue}i=null,a=null;const o=t.indexOf(":");if(-1===o)continue;const c=t.slice(0,o).trim(),l=Qr(c,t.slice(o+1));if(""===l&&"metadata"===c){i=c;continue}if("globs"===c&&""===l){s.globs=[],a="globs";continue}const u=Yr(l);s[c]="metadata.environments"!==c&&"metadata.disabledEnvironments"!==c&&"metadata.scopedTo"!==c?u:String(u).split(",").map((e=>e.trim())).filter(Boolean)}return{frontmatter:s,rawFrontmatter:`---\n${n}\n---`,body:o}}function tn(e){const t=e.replace(/\\/g,"/").replace(/^[A-Za-z]:/,(e=>e.toLowerCase())),r=[];for(const e of t.split("/"))""!==e&&"."!==e&&(".."!==e?r.push(e):r.pop());return`${t.startsWith("/")?"/":""}${r.join("/")}`}function rn(e,t){return"/"===t?e.length>1:e.startsWith(`${t}/`)}const nn=[[".cursor","skills"],[".cursor","skills-cursor"],[".claude","skills"],[".claude","plugins"],[".codex","skills"],[".grok","skills"],[".agents","skills"],[".cursor","plugins"]];class on{constructor(){this.allowed=!1}observeHeaders(e){this.allowed="1"===e.get("x-cursor-lazy-rule-bodies")}isAllowed(){return this.allowed}}function sn(e){if("success"!==e.result.case)return e;const t=e.result.value,r=t.requestContext;if(void 0===r)return e;const n=function(e){const t=e.env?.workspacePaths??[];let r=!1;const n=e.rules.map((e=>{if(!function(e,t){if(!0===e.bodyOmitted||0===e.content.length||void 0!==e.parseError||e.source!==Vr.gv.UNSPECIFIED||void 0!==e.plugin||void 0!==e.marketplace||void 0!==e.pluginId||void 0!==e.marketplaceId)return!1;if(0===e.scopedTo.length&&0===e.frontmatter.length&&e.content.trimStart().startsWith("---"))return!1;const r=tn(e.fullPath),n=r.startsWith("/"),o=r.split("/").filter((e=>e.length>0)),s=o.at(-1);if(void 0===s||function(e){return"SKILL.md"===e.at(-1)||e.some(((t,r)=>nn.some((([n,o])=>t===n&&e[r+1]===o))))}(o))return!1;const i=t.map(tn);if(!i.some((e=>rn(r,e))))return!1;const a=function(e,t){let r=e.length-1;for(let t=e.length-2;t>=0;t--)if(".cursor"===e[t]&&"rules"===e[t+1]){r=t;break}return`${t?"/":""}${e.slice(0,r).join("/")}`}(o,n),c=a!==`${n?"/":""}${o.slice(0,-1).join("/")}`,l=e.type?.type.case;return"fileGlobbed"===l?s.endsWith(".mdc")&&c:"global"===l&&!!(Jr(s)||s.endsWith(".mdc")&&c)&&!i.includes(a)&&i.some((e=>rn(a,e)))}(e,t))return e;r=!0;const n=Object.assign(new(e.getType()),e);return n.content=e.content.split("\n").find((e=>e.trim().length>0))??"",n.bodyOmitted=!0,n}));return r?Object.assign(new(e.getType()),e,{rules:n}):e}(r);return n===r?e:new Dr._G({result:{case:"success",value:Object.assign(new(t.getType()),t,{requestContext:n})}})}function an(e){return void 0!==e&&Number.isFinite(e)&&Number.isInteger(e)}function cn(e,t){const{rulesByteLength:r,skillsByteLength:n}=e,{subagentsByteLength:o,mcpsByteLength:s}=e;if(!(an(r)&&an(n)&&an(o)&&an(s)))return;const i=t?.dynamicByteLength;return{bytes:r+n+o+s+(i??0),bytesSource:"blob_parts",rulesBytes:r,skillsBytes:n,mcpBytes:s,subagentsBytes:o,...an(i)?{dynamicBytes:i}:{}}}const ln=["alpn_failure","poll_seqno_gap","append_fatal","http_464","http_404_unimplemented","socket_reset","stream_closed_early","idle_deadline","stall","other"],un=/\bHTTP (\d{3})\b/;function dn(e){const t=e.message;return"string"==typeof t?t:""}function hn(e){return e instanceof Error&&("AbortError"===e.name||e.name===at)}const pn={serverCap:3,transportCap:10},fn={alpn_failure:"server",poll_seqno_gap:"server",append_fatal:"by_signature",http_464:"server",http_404_unimplemented:"server",socket_reset:"transport",stream_closed_early:"server",idle_deadline:"server",stall:"transport",other:"server"};function mn(e){return{action:"retry",countAsServerError:!0,countAsTransportError:!1,transportFailureKind:e}}function gn(e,t,r){const n=r.attemptRequestId,o=!0===t.endless,s=r.retriesEnabled||o,i=(e,n)=>!o&&(e>=n||void 0!==t.sharedCap&&r.serverErrorRetries+r.transportErrorRetries>=t.sharedCap);let a=e instanceof He?e:ct(e,{requestId:n});const c=a instanceof Ke&&("owner"===r.abortOrigin||function(e){const t=e.displayInfo?.errorCode;return void 0!==t&&Ye.has(t)}(a)),l="stall_detector"===r.abortOrigin&&!c&&(a instanceof Ke||a instanceof qe),u="owner"===r.abortOrigin&&a instanceof qe&&Tt(a),d=function(e,t,r){return t.stalled?"stall":t.userStop?"other":function(e,t={}){const r=function(e){const t=[],r=new Set;let n=e;for(;"object"==typeof n&&null!==n&&!r.has(n);)r.add(n),t.push(n),n="cause"in n?n.cause:void 0;return t}(e);if(r.some((e=>"cursorBidiAppendFatal"in e)))return"append_fatal";const n=r.map(dn),o=e=>n.some((t=>t.includes(e))),s=function(e){return mt(e)?.code}(e),i=void 0===t.transportMode;if(i&&s===ye.Code.Unavailable&&o("ALPN protocol failed to negotiate"))return"alpn_failure";if((i||"http1_poll"===t.transportMode)&&s===ye.Code.Unavailable&&o("Unexpected seqno"))return"poll_seqno_gap";const a=n.map((e=>un.exec(e)?.[1])).find((e=>void 0!==e));return i&&s===ye.Code.Unknown&&"464"===a?"http_464":i&&s===ye.Code.Unimplemented&&"404"===a?"http_404_unimplemented":s===ye.Code.DeadlineExceeded&&function(e){const t=ft(e);return void 0===t?void 0:ht(t)?.error}(e)===Le.yM.TIMEOUT?"idle_deadline":i&&s===ye.Code.Unknown&&o("unsupported content type null")?"stream_closed_early":kt(e)||function(e){return e instanceof Error&&"isTransport"in e&&!0===e.isTransport}(e)||r.some(hn)?"socket_reset":"other"}(e,r)}(e,{stalled:l,userStop:c||u},{transportMode:r.attemptTransportMode}),h=(e,t={})=>({action:"throw",error:e,...t,transportFailureKind:d}),p=(e,n,{immediateFirstRetry:o})=>s?i(r.transportErrorRetries,t.transportCap)?h(e(),{countAsTransportError:!0}):function(e,t){return{action:"retry",countAsServerError:!1,countAsTransportError:!0,transportFailureKind:e,...t?{noBackoff:!0}:{}}}(d,o&&0===r.transportErrorRetries):h(n(),{countAsTransportError:!0}),f=()=>({cause:a.cause,requestId:n,transportErrorRetries:r.transportErrorRetries,connectCode:a.displayInfo?.connectCode});if(l){if(s&&void 0!==r.stallRetryElapsedMs&&r.stallRetryElapsedMs>=18e4)return h(xt(f()),{countAsTransportError:!0});const e=p((()=>xt(f())),(()=>xt({...f(),transportErrorRetries:void 0})),{immediateFirstRetry:!1});return"retry"===e.action?{...e,stall:!0}:e}if(a instanceof Ke&&!c&&Tt(a)&&(a=new qe(a.message,{cause:a.cause,requestId:n,displayInfo:a.displayInfo,isTransport:!0})),u)return h(new Ke(a.message,{cause:a.cause,requestId:n,displayInfo:a.displayInfo}));if(!0===t.retryAllInference&&(a instanceof ze||a instanceof Ge)&&function(e){const t=e.displayInfo?.inferenceRequestErrorType;return void 0!==t&&!st.some((e=>e===t))}(a))return i(r.serverErrorRetries,t.serverCap)?h(a):mn(d);if(a instanceof Ke||a instanceof ze||a instanceof Ge)return h(a);const m=function(e){return At(e.displayInfo?.errorDetails)}(a);if(a instanceof qe&&void 0!==m){const e=(r.rateLimitRetryElapsedMs??0)+m;return!s||!o&&e>3e5?h(a):{action:"retry",countAsServerError:!1,countAsTransportError:!1,transportFailureKind:d,retryAfterMs:m,rateLimit:!0}}if(a instanceof qe&&(!0===a.isTransport||function(e,t){const r=fn[e];return"by_signature"===r?kt(t):"transport"===r}(d,a)||"owner"!==r.abortOrigin&&Tt(a))){const e=function(e){const t=e.displayInfo,r=t?.title,n=t?.detail;return r&&n?{...t,title:r,detail:n}:void 0}(a);return p((()=>function(e){const{cause:t,requestId:r,transportErrorRetries:n,connectCode:o,ownCopy:s}=e;if(void 0!==s)return new qe(_t(n)?"Connection failed repeatedly":"Connection failed",{cause:t,requestId:r,displayInfo:{...s,isRetryable:!0,connectCode:o??s.connectCode}});const i=function(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){t.add(r);const e=lt(r)?gt(r):r.message;if(Pt.test(e))return e;r=r.cause}}(t),a=void 0===i?"Please check your network connection and try again.":"Please check your proxy settings and try again.";return _t(n)?new qe("Connection failed repeatedly",{cause:t,requestId:r,displayInfo:{title:"Connection failed",detail:`${void 0===i?"":`${i}. `}The connection failed ${Ct(n)} times. ${a}`,isRetryable:!0,connectCode:o}}):new qe("Connection failed",{cause:t,requestId:r,displayInfo:{title:"Connection failed",detail:`${i??"The connection was interrupted"}. ${a}`,isRetryable:!0,connectCode:o}})}({...f(),...void 0===e?{}:{ownCopy:e}})),(()=>a),{immediateFirstRetry:!0})}return s?i(r.serverErrorRetries,t.serverCap)?h(function(e){const{classified:t,requestId:r,serverErrorRetries:n}=e,o=t.displayInfo;return new qe(t.message,{cause:t.cause,requestId:r,displayInfo:{...o,title:o?.title||"Server error",detail:o?.detail||`The server failed ${Ct(n)} times. Please try again, or contact support if the issue persists.`,isRetryable:!0}})}({classified:a,requestId:n,serverErrorRetries:r.serverErrorRetries})):mn(d):h(a)}var wn=r("../proto/dist/generated/agent/v1/mcp_pb.js");const yn=(0,y.cF)(Symbol("agentTransportTimingRecorder"),void 0),vn=(0,l.h)("@anysphere/agent-client:turn-runner"),bn=1e3,Sn=6e4,kn=(0,u.Pu)("agent_client.turn.retry",{description:"Turn attempts retried by the turn runner",labelNames:["attempt","reason","loop"]});function _n(e){return e<=1?"1":2===e?"2":e<=5?"3_5":"gt5"}function Cn(e){return!0===e.stall?"stall":!0===e.rateLimit?"rate_limit":e.countAsTransportError?"transport":e.countAsServerError?"server":!0===e.immediate?"speculative":"other"}const En=new Set(["textDelta","thinkingDelta","thinkingCompleted","partialToolCall","toolCallDelta","toolCallStarted","toolCallCompleted","tokenDelta"]);function xn(e){const{message:t}=e;return("textDelta"!==t.case||void 0===t.value||!("isServerNotice"in t.value)||!0!==t.value.isServerNotice)&&En.has(t.case??"")}async function Pn(e,t,r){await new Promise(((n,o)=>{if(t?.aborted)return void o(new Ke("Cancelled during backoff"));const s=new AbortController,i=setTimeout(a,e);function a(){clearTimeout(i),t?.removeEventListener("abort",c),s.abort(),n()}function c(){clearTimeout(i),s.abort(),o(new Ke("Cancelled during backoff"))}t?.addEventListener("abort",c,{once:!0});try{r?.(s.signal)?.then(a,(()=>{}))}catch{}}))}function Rn(e,t){return e.length===t.length&&e.every(((e,r)=>{const n=t[r];return void 0!==n&&e.byteLength===n.byteLength&&e.every(((e,t)=>e===n[t]))}))}function In(e){const{connectCode:t,connectCodeName:r,...n}=e;return void 0===r?n:{...n,connectCode:r}}async function Tn(e){const{ctx:t,checkpointHandler:r,runOptions:n,requestId:o,hooks:s,cancellation:a}=e,c=e.originalRequestId??o;let l=bn;const u=async(r,o,s,i,a)=>{if(s||(l=bn),void 0!==e.backoff)return void await e.backoff(r,o,i.retryAfterMs);if(!0===i.rateLimit&&void 0!==i.retryAfterMs){const n=i.retryAfterMs+1e3*Math.random();return e.logging&&vn.info(t,`[${e.logging.tag}] Waiting out a rate limit`,{attempt:r,retryAfterMs:i.retryAfterMs,selectedDelayMs:n}),void await Pn(n,o)}const c=s?function(e,t){const r=Math.min(3e5,3*e);return t??bn+(r-bn)*Math.random()}(l,n.fixedRetryDelayMs):function(e,t,r){const n=t?100:bn,o=r??Math.min(n*2**e,Sn);return o+(void 0===r?.2*o*Math.random():0)}(r,n.isRunningInTest,n.fixedRetryDelayMs),u=function(e,t){if(void 0===t||t<=e)return e;const r=Math.min(t,Sn),n=Math.min(r+.2*r*Math.random(),Sn);return Math.max(e,n)}(c,i.retryAfterMs);u!==c&&e.logging&&vn.info(t,`[${e.logging.tag}] Waiting for Retry-After`,{attempt:r,retryAfterMs:i.retryAfterMs,computedDelayMs:c,selectedDelayMs:u,endlessRetries:s}),s&&(l=c,e.logging&&vn.info(t,`[${e.logging.tag}] Endless retry delay selected`,{selectedDelayMs:u,attempt:r,retryCategory:i.countAsServerError?"server":"transport",endlessRetries:s}));const{retryWake:d}=n;await Pn(u,o,void 0===d?void 0:e=>d({error:a,delayMs:u,waitEnded:e}))};let d,h,p,f,m,g,w=e.state,y=e.action,v=0,b=o,S=0,k=0,_=!1,C=0;const E=()=>{_&&(n.onConnectionStateChange?.({state:"connected"}),_=!1)},x=(e,t)=>()=>{e===v&&("progress"===t?m=!0:g=!0,E())},P=e=>({handleCheckpoint:async(t,n,o)=>{e===v&&(m=!0),await r.handleCheckpoint(t,n,o),e===v&&(d=n,h=o?.resumeEligibility??"eligible",E())},getLatestCheckpoint:()=>r.getLatestCheckpoint()});for(;;){if(t.canceled)throw a.toCancelledError(void 0,b);if(d=void 0,h=void 0,m=!1,g=!1,s.beginAttempt?.({attempt:v,originalRequestId:c}),v>0?(b=(0,ge.C)(),await(n.onRetryStarting?.(v,{actionCase:y.action.case,conversationState:w,isResume:"resumeAction"===y.action.case,attemptRequestId:b})),e.logging&&vn.info(t,`[${e.logging.tag}] Retrying attempt ${v}`,{attempt:v,actionCase:y.action.case,requestId:b,originalRequestId:c}),"resumeAction"===y.action.case&&(await(n.onRetryResuming?.({checkpointState:w,nextAttempt:v,reason:"resume_action"})),e.logging&&vn.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:v,reason:"resume_action"}))):(e.logging&&vn.info(t,`[${e.logging.tag}] Initial request`,{attempt:v,actionCase:y.action.case,requestId:b}),!0===e.notifyInitialResume&&"resumeAction"===y.action.case&&(await(n.onRetryResuming?.({checkpointState:w,nextAttempt:v,reason:"resume_action"})),e.logging&&vn.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:v,reason:"resume_action"}))),t.canceled)throw a.toCancelledError(void 0,b);try{return await s.runAttempt({state:w,action:y,checkpointHandler:P(v),attempt:v,attemptRequestId:b,notifyConnected:E,notifyApplicationProgress:x(v,"progress"),notifyApplicationActivity:x(v,"activity")}),E(),void(e.logging&&vn.info(t,`[${e.logging.tag}] Request successful`,{attempt:v,actionCase:y.action.case,requestId:b,originalRequestId:c}))}catch(r){if(!0===a.shortCircuit?.(r))throw a.toCancelledError(r,b);const o=!0===n.endlessRetries?.(),E=e.nowMs?.()??Date.now();(m||g)&&(p=void 0,f=void 0);const x=void 0===p?void 0:E-p,P=void 0===f?void 0:E-f;let T=s.classify(r,{attempt:v,attemptRequestId:b,originalRequestId:c,serverErrorRetries:S,transportErrorRetries:k,stallRetryElapsedMs:x,rateLimitRetryElapsedMs:P,endlessRetries:o});if("retry"===T.action){const n=!("resumeAction"===y.action.case&&w.pendingToolCalls.length>0)&&("resumeAction"===y.action.case||!0===e.noProgressGuardCountsReplays&&v>0);void 0!==d?C=0:n&&m&&(C++,C>=2&&(e.logging&&vn.warn(t,`[${e.logging.tag}] Resume attempts are streaming but not producing checkpoints; stopping automatic resume`,{noProgressResumeFailures:C,attempt:v,requestId:b,originalRequestId:c,errorName:r instanceof Error?r.name:typeof r}),T={action:"throw",error:new qe("Agent turn stopped after repeated resume attempts made no progress",{cause:r instanceof Error?r:void 0,requestId:b,displayInfo:{title:"Agent stopped retrying",detail:"The connection was interrupted repeatedly without saving progress, so the agent stopped to avoid repeating the same work. Retry to continue from the last saved state.",isRetryable:!0}}),transportFailureKind:T.transportFailureKind}))}const A={...void 0===T.transportFailureKind?{}:{transportFailureKind:T.transportFailureKind},...void 0===e.loop?{}:{loop:e.loop}},$=e.logging?.diagnostics?.(r);if(e.logging){const e="retry"===T.action?`RETRY (countAsServerError=${T.countAsServerError}, countAsTransportError=${T.countAsTransportError})`:`THROW ${T.error.kind}`;vn.warn(t,`[AGENT_ERROR_DIAGNOSTICS] requestId=${b} originalRequestId=${c} decision=${e}`,{decision:e,willRetry:"retry"===T.action,enableAgentRetries:n.enableAgentRetries??!1,endlessRetries:o,isRunningInTest:n.isRunningInTest??!1,serverErrorRetries:S,transportErrorRetries:k,attempt:v,requestId:b,originalRequestId:c,...A,...$})}if("throw"===T.action){if(0===v){const r={attempt:0,actionCase:y.action.case,error:T.error,requestId:b,originalRequestId:c,enableAgentRetries:!0===n.enableAgentRetries,endlessRetries:o,stallAborted:!1,abortSources:[]};try{await(n.onErrorNotRetried?.(s.buildNonRetriedErrorInfo?.(r)??r))}catch(r){e.logging&&vn.warn(t,`[${e.logging.tag}] onErrorNotRetried callback failed`,{error:String(r),requestId:b,originalRequestId:c})}}throw e.logging&&vn.warn(t,`[${e.logging.tag}] Error not retryable`,{...A,...$,attempt:v,actionCase:y.action.case,requestId:b,originalRequestId:c,errorName:T.error.name,...!0===e.logging.includeErrorObjects?{error:T.error}:{},serverErrorRetries:S,transportErrorRetries:k}),T.error}const M=v+1;if("ineligible_terminal_turn"===h)return void(e.logging&&vn.warn(t,`[${e.logging.tag}] Terminal checkpoint received before retryable error; completing without automatic resume`,{errorName:r instanceof Error?r.name:typeof r,errorMessage:r instanceof Error?r.message:String(r)}));!0!==T.immediate&&(n.onConnectionStateChange?.({state:"reconnecting",attempt:M,trigger:{...A,...s.reconnectTrigger?.(r,T,{originalRequestId:c,failedAttemptRequestId:b,nextAttempt:M})??{originatingRequestId:c,attemptRequestId:b}}}),_=!0),T.countAsServerError&&S++,T.countAsTransportError&&k++,!0===T.stall?p??=E:p=void 0,!0===T.rateLimit?f??=E:f=void 0,v=M;try{kn.increment(t,1,{attempt:_n(M),reason:Cn(T),loop:e.loop??"nal"})}catch{}void 0!==d&&(I=d,Rn((R=w).turns,I.turns)&&Rn(R.rootPromptMessagesJson,I.rootPromptMessagesJson)||(l=bn),w=d,y=new i.QFf({action:{case:"resumeAction",value:new i.qKo}})),s.onRetryCommitted?.(),!0===T.immediate||!0===T.noBackoff&&void 0===T.retryAfterMs||await u(v,t.signal,o,T,r)}}var R,I}var An=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},$n=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Mn=(0,y.cF)(Symbol("agentStreamMetadata"),void 0),Dn=(0,l.h)("@anysphere/agent-client:abort"),On=(0,l.h)("@anysphere/agent-client:retry"),Fn=(0,l.h)("@anysphere/agent-client:request-context-blob");async function Nn({ctx:e,action:t,resources:r,blobStore:n,options:o,source:s,transportMode:i,notifyBytes:a}){!0===o.omitRequestContextFileContents&&function(e){const t=Ur(e);if(void 0===t)return;const r=t.requestContext;void 0!==r&&Hr(r)&&(t.requestContext=zr(r));const n=e.requestContextParts,o=n?.dynamicContext;void 0!==n&&void 0!==o&&Hr(o)&&(e.requestContextParts=qr(n,{dynamicContext:zr(o)}))}(t);try{const s=await Wr({ctx:e,action:t,resources:r,blobStore:n,mode:i??o.requestContextBlobTransportMode??"legacy",maxBlobBytes:o.requestContextBlobMaxBytes??Fr,maxInlineDynamicBytes:o.requestContextDynamicInlineMaxBytes??1048576,notesSessionId:o.conversationId});if(!0===a){const e=function({prepared:e,parts:t}){return"prepared"===e.kind?cn(e,{dynamicByteLength:e.dynamicByteLength}):"already_prepared"===e.kind&&void 0!==t?cn(t):void 0}({prepared:s,parts:t.requestContextParts});void 0!==e&&o.onRequestContextBytes?.(e)}}catch(r){t.requestContextParts=void 0,Fn.warn(e,"Failed to prepare request context blob; using legacy fallback",{actionCase:t.action.case,errorName:r instanceof Error?r.name:typeof r,source:s})}}const Ln=e=>{const t=[];switch(t.push(e.message.case),e.message.case){case"conversationAction":t.push(e.message.value.action.case);break;case"execClientMessage":case"execClientControlMessage":case"kvClientMessage":case"execServerMessage":case"execServerControlMessage":t.push(e.message.value.message.case);break;case"interactionResponse":t.push(e.message.value.result.case);break;case"interactionUpdate":switch(t.push(e.message.value.message.case),e.message.value.message.case){case"partialToolCall":case"toolCallCompleted":case"toolCallStarted":t.push(e.message.value.message.value.toolCall?.tool.case);break;case"toolCallDelta":t.push(e.message.value.message.value.toolCallDelta?.delta.case)}break;case"interactionQuery":t.push(e.message.value.query.case)}return t.filter((e=>void 0!==e)).join(":")};function jn(e){if(e instanceof Error)return`${e.name}: ${e.message}`;if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e||"bigint"==typeof e)return String(e);if(null==e)return String(e);try{const t=JSON.stringify(e);return"string"==typeof t?t:"unserializable error"}catch{return"unserializable error"}}async function Un(e,t,r){for await(const n of t)switch(n.event.case){case"stdout":await r.sendUpdate(e,a.shellOutputDelta({case:"stdout",value:new he.o0({data:n.event.value.data})}));break;case"stderr":await r.sendUpdate(e,a.shellOutputDelta({case:"stderr",value:new he.Db({data:n.event.value.data})}));break;case"exit":await r.sendUpdate(e,a.shellOutputDelta({case:"exit",value:new he.vb({code:n.event.value.code,aborted:n.event.value.aborted})}))}}function Bn(e){return e instanceof Error?e.name:void 0}class Wn{constructor(e,t,r={}){this.client=e,this.endpointUrl=t,this.options=r,this.hasStartedStream=!1}async run(e,t,r,n,o,s,i,a,l,u,d){const h={stack:[],error:void 0,hasError:!1};try{if(void 0!==d.maxSteps)throw new Ve(d.maxSteps);const g=!0===d.omitRequestContextFileContents?function(e){const t=Gr(e);return void 0===t?e:new J(e,[G($r,{execute:async(e,r,n)=>function(e){if("success"!==e.result.case)return e;const t=e.result.value,r=t.requestContext;return void 0!==r&&Hr(r)?new Dr._G({result:{case:"success",value:qr(t,{requestContext:zr(r)})}}):e}(await t.execute(e,r,n))})])}(s):s,w=!0===d.lazyFileScopedRuleBodies?new on:void 0,y=void 0===w?g:function(e,t){const r=Gr(e);return void 0===r?e:new J(e,[G($r,{execute:async(e,n,o)=>{const s=await r.execute(e,n,o);return void 0!==o?.execId&&t.isAllowed()?sn(s):s}})])}(g,w),v=void 0===w?d:{...d,onHeader:e=>{w.observeHeaders(e),d.onHeader?.(e)}},b=new Br(i),S=d.generationUUID??(0,ge.C)(),k=new c,_=(m=k,p=o,f=e=>{m.observe(e.id)},{sendUpdate:(e,t)=>p.sendUpdate(e,t),query:(e,t)=>(f(t),p.query(e,t)),enqueuePostTurnEndedWork:p.enqueuePostTurnEndedWork?.bind(p),flushPostTurnEndedWork:p.flushPostTurnEndedWork?.bind(p)}),C={sources:[],abortReasonName:void 0,abortReasonMessage:void 0},E=e=>{const t=function(e){const t=ft(e);return void 0===t?void 0:We(ht(t))}(e),r=C.sources.includes("stall_detector")||!0===t?.stallAborted,n=(o=C.sources).some((e=>"stall_detector"!==e))?"owner":o.includes("stall_detector")?"stall_detector":"none";var o;const s=function(e){const t={errorName:Bn(e)},r=mt(e);if(void 0===r)return t;const n=function(e){if(null!==e&&"object"==typeof e&&"cause"in e)return e.cause}(r),o=function(e){if(null===e||"object"!=typeof e||!("code"in e))return;const t=e.code;return"string"==typeof t||"number"==typeof t?t:void 0}(n),s=Bn(n);return{...t,underlyingConnectError:{code:r.code,codeName:ye.Code[r.code],cause:void 0!==o||void 0!==s?{code:o,name:s}:void 0}}}(e),i=s.underlyingConnectError;return{relayed:t,stallAborted:r,abortOrigin:"none"===n&&r?"stall_detector":n,reading:void 0===t?{errorName:s.errorName,connectCode:i?.code,connectCodeName:i?.codeName,connectCause:i?.cause,abortSources:[...C.sources],abortReasonName:C.abortReasonName,...void 0===i?{}:{underlyingConnectError:i}}:{errorName:t.errorName,connectCode:t.connectCode,connectCodeName:t.connectCodeName,connectCause:t.connectCause,...(a=t.loop,"nal"===a||"local_loop"===a||"module"===a?{loop:t.loop}:{}),...void 0===t.transportMode?{}:{transportMode:t.transportMode}}};var a};let x=0,P=0;const R={networkPhaseStartedAt:performance.now()};try{d.onNetworkPhaseStart?.()}catch(t){On.warn(e,"onNetworkPhaseStart callback failed",{error:String(t)})}const I=An(h,(0,$.VI)(e.withName("networkPhase")),!1);e=I.ctx,await(0,$.MG)(I.span,(()=>Tn({ctx:e,state:t,action:r,checkpointHandler:l,runOptions:d,requestId:S,loop:this.options.loop??"nal",notifyInitialResume:!0,logging:{...this.options.retryLogging??{tag:"nal_agent_retries",includeErrorObjects:!0},diagnostics:e=>{const{stallAborted:t,abortOrigin:r,reading:n}=E(e);return{stallAborted:t,abortOrigin:r,...In(n)}}},cancellation:{toCancelledError:()=>new Ke("Request cancelled")},hooks:{beginAttempt:()=>{C.sources=[],C.abortReasonName=void 0,C.abortReasonMessage=void 0,P=++x},runAttempt:async({state:t,action:r,checkpointHandler:o,attempt:s,attemptRequestId:i,notifyConnected:c,notifyApplicationProgress:l,notifyApplicationActivity:d})=>{const h=function(e,t,r){return{sendUpdate:async(n,o)=>{if(t===r())return e.sendUpdate(n,o);"toolCallCompleted"===o.message?.case&&On.warn(n,"nal.await_stall.stale_completion_dropped",{attemptGen:t,currentGen:r()})},query:async(n,o)=>{if(t!==r())throw new Ke("Stale query from previous attempt");return e.query(n,o)},enqueuePostTurnEndedWork:e.enqueuePostTurnEndedWork?t=>e.enqueuePostTurnEndedWork(t):void 0,flushPostTurnEndedWork:e.flushPostTurnEndedWork?t=>e.flushPostTurnEndedWork(t):void 0}}(_,P,(()=>x));await this.runInternal(e,t,r,n,h,y,b,a,o,u,v,i,S,k,C,c,l,d,s,R)},classify:(e,t)=>{const{abortOrigin:r,relayed:n}=E(e),o=gn(e,function(e,t,r=pn){const n=function(e){if(void 0!==e&&Number.isFinite(e))return Math.min(Math.max(Math.floor(e),1),100)-1}(e.maxRetries),o=void 0===n?r:{serverCap:n,transportCap:n};return{serverCap:o.serverCap,transportCap:!0===e.isRunningInTest?Math.min(o.transportCap,2):o.transportCap,...void 0===n?{}:{sharedCap:n},endless:t.endlessRetries,retryAllInference:!0===e.retryAllInferenceErrors}}(d,t),{...t,retriesEnabled:d.enableAgentRetries??!1,abortOrigin:r}),s=n?.transportFailureKind;return"string"==typeof(i=s)&&ln.includes(i)?{...o,transportFailureKind:s}:o;var i},buildNonRetriedErrorInfo:e=>({...e,enableAgentRetries:d.enableAgentRetries??!1,stallAborted:E(e.error).stallAborted,abortSources:[...C.sources],abortReasonName:C.abortReasonName,abortReasonMessage:C.abortReasonMessage}),reconnectTrigger:(e,t,r)=>{const{relayed:n,stallAborted:o,reading:s}=E(e),i=e instanceof He?e:ct(e,{requestId:r.failedAttemptRequestId});return{errorClass:n?.errorName??i.name,connectCode:s.connectCode,connectCodeName:s.connectCodeName,errorCode:i.displayInfo?.errorCode,countAsServerError:t.countAsServerError,countAsTransportError:t.countAsTransportError,stallAborted:o,originatingRequestId:r.originalRequestId,attemptRequestId:r.failedAttemptRequestId,...void 0===s.transportMode?{}:{transportMode:s.transportMode},endpointUrl:this.endpointUrl}},onRetryCommitted:()=>a.reopen()}})))}catch(e){h.error=e,h.hasError=!0}finally{$n(h)}var p,f,m}async runInternal(e,t,r,n,o,s,a,c,l,u,p,f,m,g,w,y,v,b,S,k,_="agent.request.attempt"){const C={stack:[],error:void 0,hasError:!1};try{const P=e;e=this.options.prepareAttemptContext?.(e,{attempt:S,attemptRequestId:f,originalRequestId:m,runOptions:p})??e;const R=An(C,(0,$.VI)(e.withName(_)),!1);R.span.setAttribute("agent.attempt",S),R.span.setAttribute("agent.request_id",f),R.span.setAttribute("agent.original_request_id",m),e=R.ctx,e=(0,$.Mf)(e,"agent.request_id",f),e=(e=(0,$.Mf)(e,"agent.original_request_id",m)).with(Mn,{requestId:f,rootParentRequestId:p.rootParentRequestId,modelDetails:n});const I=new Set(w.sources);let T=void 0!==w.abortReasonName||void 0!==w.abortReasonMessage;const M=(t,r)=>{if(I.has(t))return;I.add(t),w.sources=[...I];const n=(e=>{const t="string"==typeof e?.abortReasonName?e.abortReasonName:void 0,r="string"==typeof e?.abortReasonMessage?e.abortReasonMessage:void 0;if(void 0!==t||void 0!==r)return{abortReasonName:t,abortReasonMessage:r}})(r);T||void 0===n||(T=!0,w.abortReasonName=n.abortReasonName,w.abortReasonMessage=n.abortReasonMessage),Dn.error(e,"Agent client stream abort",new Error(t),{abortSource:t,requestId:f,conversationId:p.conversationId,...r??{}})};if(e.signal.aborted){const t=e.signal.reason;M("ctx_signal_abort",ue(t))}else e.signal.addEventListener("abort",(()=>{const t=e.signal.reason;M("ctx_signal_abort",ue(t))}),{once:!0});const[D,O]=e.withCancel();if(c.signal?.aborted){const e=c.signal?.reason;M("conversation_action_abort",ue(e)),O()}else c.signal?.addEventListener("abort",(()=>{const e=c.signal?.reason;M("conversation_action_abort",ue(e)),O()}),{once:!0});if(e.canceled||D.canceled){const t={ctxCanceled:e.canceled,softCancel:D.canceled};throw M("pre_run_cancel",t),new Ke("User aborted request")}const F=(0,$.VI)(e.withName("createControlledExecManager")),N=A.fromResources(s);F[Symbol.dispose]();const[L,j]=e.withCancel(),U=new Gt,{failThresholdMs:B,advisoryThresholdMs:W}=function(e,t){const r=Lt(e?.failTimeoutMs)??3e4,n=r>0&&!0!==t?.isRunningInTest?Math.max(r,2e4):r,o=Lt(e?.advisoryTimeoutMs);return{failThresholdMs:n,advisoryThresholdMs:void 0!==o&&o>0&&(n<=0||oH,onStall:e=>{M("stall_detector",{thresholdMs:B,advisoryThresholdMs:W}),j(e)},onStallCallback:p.onStall,handlerTracker:U}),!1);let z,G,V;const K=(0,ve.Jt)(),J=new h.F8(K,(e=>(q.reset("outbound_write",Ln(e)),e))),Z=An(C,(0,$.VI)(e.withName("writeInitialRequest")),!1);let X;const Q=function(e){return new wn.Or({mcpTools:e.map((e=>({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?we.Value.fromJson(e.inputSchema):void 0,outputSchemaJson:void 0!==e.outputSchema?JSON.stringify(e.outputSchema):void 0})))})}(u),Y=p.requestContextBlobTransportMode??"legacy",te=0===S&&"userMessageAction"===r.action.case&&0===t.turns.length,re="ref_only"===Y&&te?"dual":Y,[,ne]=await Promise.all([Nn({ctx:e,action:r,resources:s,blobStore:a,options:p,source:"run_request",transportMode:re,notifyBytes:0===S}),void 0===p.mintLlmGatewayCredential?Promise.resolve(void 0):Ar(p.mintLlmGatewayCredential,{signal:D.signal,isCanceled:()=>D.canceled,requestId:f})]),oe={action:r,headers:p.headers??{}},se=this.options.decorateAttempt?.(oe,p)??oe,ie=new i.Mpn({conversationState:t,action:se.action,modelDetails:n,requestedModel:p.requestedModel,clientLlmGatewayCredential:ne,mcpTools:Q,conversationGroupId:p.conversationGroupId,conversationId:p.conversationId,agentSessionId:p.agentSessionId,mcpFileSystemOptions:p.mcpFileSystemOptions,customSystemPrompt:p.customSystemPrompt,systemPromptSpec:p.systemPromptSpec,harness:p.harness,computerUseCoordinateMode:p.computerUseCoordinateMode,subagentTypeName:p.subagentTypeName,excludeWorkspaceContext:p.excludeWorkspaceContext,devRawModelSlug:p.devRawModelSlug,selectedSubagentModels:p.selectedSubagentModels,subagentModelOverrides:p.subagentModelOverrides??[],selectedSubagentModelDetails:p.selectedSubagentModelsLegacy,clientSupportsInlineImages:p.clientSupportsInlineImages,clientSupportsPreviewCard:p.clientSupportsPreviewCard,startedAsNewProject:p.startedAsNewProject,firstProjectOnboarding:p.firstProjectOnboarding,clientSupportsSendToUser:p.clientSupportsSendToUser,clientSupportsRoutedModelUpdate:p.clientSupportsRoutedModelUpdate,emitModelCallUsage:p.emitModelCallUsage,canCreateCloudSubagents:p.canCreateCloudSubagents,suppressSubagentProgressUpdateTool:p.suppressSubagentProgressUpdateTool,transcriptParentConversationId:p.transcriptParentConversationId,runId:m,nextInteractionQueryId:g.peekNext(),voiceCallNotes:p.voiceCallNotes});if(X=J.write(new de.KS({message:{case:"runRequest",value:ie}})),D.canceled){const t={ctxCanceled:e.canceled,softCancel:D.canceled};throw M("post_write_cancel",t),Z[Symbol.dispose](),new Ke("User aborted request")}const ae={...se.headers,"x-request-id":f,"x-original-request-id":m,...Me(p),...Oe()};z=(0,$.VI)(e.withName("handshakeEstablishment")),z.span.setAttribute("handshake.firstStreamOnClient",!this.hasStartedStream),this.hasStartedStream=!0;const ce=function(e){return e?.get(yn)}(e)?.startTransportRun(),pe=void 0===ce?z.ctx:function(e,t){return e.with(yn,t)}(z.ctx,ce),fe=0===S&&void 0!==p.onTtftBreakdown?k?.networkPhaseStartedAt:void 0;let ge;const ye=void 0===ce&&void 0===fe?K:(E=K,x=()=>{ge=performance.now(),ce?.markFirstRequestSent(ge)},{[Symbol.asyncIterator](){const e=E[Symbol.asyncIterator]();let t=!1;const r={next:()=>(t||(t=!0,x()),e.next())};return void 0!==e.return&&(r.return=t=>e.return(t)),void 0!==e.throw&&(r.throw=t=>e.throw(t)),r}}),be=this.client.run(pe,ye,{signal:L.signal,headers:ae,onHeader:e=>{H=e.get("x-cursor-agent-transport-mode")??void 0,p.onHeader?.(e)},onNetworkStarted:()=>{void 0===G&&(G=performance.now(),0===S&&(V=function(e=Kt,t=25){let r,n=0,o=0,s=e.now()+t;const i=e=>{e<=0||(o+=e,e>n&&(n=e))},a=()=>{const r=e.now();i(r-s),s=r+t,c=e.setTimeout(a,t)};let c=e.setTimeout(a,t);return{stop:()=>(void 0===r&&(e.clearTimeout(c),i(e.now()-s),r={maxLagMs:n,totalLagMs:o}),r)}}()))}}),ke=performance.now();let Ce;const xe=t=>{z&&(z.span.setAttribute("handshake.firstMessageHeartbeat",t),void 0!==G&&z.span.setAttribute("handshake.preNetworkMs",G-ke),z[Symbol.dispose](),z=void 0),y();const r=performance.now();Ce=r,p.onFirstMessage?.(r-ke),void 0!==G&&(p.onFirstMessageNetwork?.(r-G),void 0!==V&&(function(e,t){const r={loop:t.loop??"nal",transport_mode:Bt(t.transportMode),first_message_slow:t.firstMessageNetworkMs>=1e3?"true":"false"};Jt.histogram(e,t.reading.maxLagMs,r),Zt.histogram(e,t.reading.totalLagMs,r),Xt.histogram(e,t.firstMessageNetworkMs,r)}(e,{loop:this.options.loop,transportMode:H,firstMessageNetworkMs:r-G,reading:V.stop()}),V=void 0))},Pe=()=>{b(),p.onFirstNonHeartbeatResponse?.(performance.now()-ke,S)},Ie=p.onTtftBreakdown?e=>{const t=performance.now(),r=void 0===fe||void 0===ge||"server"!==e.clock?void 0:function(e){const t=Math.min(e.firstRequestTakenAt,e.firstMessageAt);return{requestBuildMs:Math.max(0,e.transportRunCalledAt-e.networkPhaseStartedAt),connectMs:Math.max(0,t-e.transportRunCalledAt),roundTripMs:Math.max(0,e.firstMessageAt-t),firstByteToOutputMs:Math.max(0,e.firstOutputAt-e.firstMessageAt),firstOutputReceivedAtEpochMs:e.firstOutputAtEpochMs}}({networkPhaseStartedAt:fe,transportRunCalledAt:ke,firstRequestTakenAt:ge,firstMessageAt:Ce??t,firstOutputAt:t,firstOutputAtEpochMs:Date.now()});p.onTtftBreakdown(void 0===r?e:{...e,transit:r},S)}:void 0,$e=!0===this.options.execCheckpointGate?function(e,t,r,n={}){return Te.has(r.action.action.case)?async function*(e,t,r,n){const o=[];let s=0;const i=()=>o.flatMap((e=>void 0===e.toolCallId?[]:[e.toolCallId])),a=e=>{const t=[];for(;o.length>0;){const n=o[0];if(!e&&void 0!==n.toolCallId&&!r.has(n.toolCallId))break;t.push(n.message),o.shift()}return t.length>0&&o.length>0&&(s=n.now()),t},c=()=>{const e=o.filter((e=>"execServerControlMessage"===e.message.message.case)),t=o.filter((e=>"execServerControlMessage"!==e.message.message.case));return o.splice(0,o.length,...t),e.map((e=>e.message))},l=t[Symbol.asyncIterator]();let u=!0;try{for(;;){let t;try{t=await l.next()}catch(e){throw u=!1,yield*c(),e}if(!0===t.done)return u=!1,void(yield*c());const d=t.value,h=d.message;if("execServerMessage"!==h.case&&"execServerControlMessage"!==h.case)if("conversationCheckpointUpdate"!==h.case){if(yield d,o.length>0&&n.now()-s>=n.holdMs){Re.info(e,"No checkpoint named held tool calls on a stream still delivering: handed on as they came",{toolCallIds:i().join(", "),waitedMs:Math.round(n.now()-s)});for(const e of i())r.add(e);yield*a(!0)}}else{for(const e of Ee(h.value.pendingToolCalls))r.add(e);if(yield d,o.length>0){const t=Math.round(n.now()-s),r=a(!1);r.length>0&&Re.debug(e,"Handed held execs on after their checkpoint",{count:r.length,waitedMs:t}),yield*r}}else{const t="execServerMessage"===h.case?Ae(h.value):void 0,i=void 0!==t&&!r.has(t);if(0===o.length&&!i){yield d;continue}if(0===o.length&&(s=n.now()),o.push({message:d,toolCallId:i?t:void 0}),i){Re.debug(e,"Held a tool call's exec for the checkpoint that names it",{toolCallId:t});try{n.onHeld?.(t)}catch(t){Re.warn(e,"onExecHeldForCheckpoint callback failed",{error:String(t)})}}}}}catch(e){if(u){u=!1;try{await(l.return?.())}catch{}}throw e}finally{o.length>0&&Re.info(e,"The stream ended before a checkpoint named held tool calls: dropped, never run",{toolCallIds:i().join(", ")}),u&&await(l.return?.())}}(e,t,Ee(r.state.pendingToolCalls),{holdMs:n.holdMs??5e3,now:n.now??(()=>performance.now()),onHeld:n.onHeld}):t}(e,be,{action:se.action,state:t},void 0===this.options.onExecHeldForCheckpoint?{}:{onHeld:this.options.onExecHeldForCheckpoint}):be,De=!0===this.options.execAfterCheckpointStored||!0===this.options.execCheckpointGate?new _e(void 0===this.options.onExecHeldForCheckpointStore?{}:{onExecHeld:this.options.onExecHeldForCheckpointStore}):void 0,{interactionStream:Fe,execStream:Ne,checkpointStream:Le,kvStream:je,done:Ue}=function(e,t,r,n,o,s,i,a,c,l){const u=(0,ve.Jt)(),d=(0,ve.Jt)(),h=(0,ve.Jt)(),p=(0,ve.Jt)();let f=!1,m=!1,g=!1;return{interactionStream:u,execStream:d,checkpointStream:h,kvStream:p,done:async function(){let w,y,v=!1,b=!1;try{for await(const o of t){if(void 0!==o.ttftBreakdown){const t=o.ttftBreakdown;try{a?.({serverFirstTokenMs:t.serverFirstTokenMs,preStreamSetupMs:t.preStreamSetupMs,waitForFirstEventMs:t.waitForFirstEventMs,providerTtftMs:t.providerTtftMs,slowPoolWaitMs:t.slowPoolWaitMs,...void 0===t.clientPrepMs?{}:{clientPrepMs:t.clientPrepMs},...void 0===t.clientPrepLegs?{}:{clientPrepLegs:me(t.clientPrepLegs)},...void 0===t.preHandlerMs?{}:{preHandlerMs:t.preHandlerMs},clock:t.clientClock?"client":"server"})}catch(t){On.warn(e,"onTtftBreakdown callback failed",{error:String(t)})}}const t="interactionUpdate"===o.message.case&&"heartbeat"===o.message.value.message.case;if(f||(f=!0,n(t)),t)r.onServerSentHeartbeat(),r.reset("inbound_message","heartbeat");else{if(!m){m=!0;try{i?.()}catch(t){On.warn(e,"onFirstNonHeartbeatMessage callback failed",{error:String(t)})}}if(!g&&"interactionUpdate"===o.message.case&&xn(o.message.value)){g=!0;try{l?.()}catch(t){On.warn(e,"onFirstModelOutput callback failed",{error:String(t)})}}r.reset("inbound_message",Ln(o))}if("interactionUpdate"===o.message.case&&"turnEnded"===o.message.value.message.case&&(v=!0),"interactionUpdate"!==o.message.case&&"interactionQuery"!==o.message.case||await u.write(o.message).catch((()=>{})),"execServerMessage"!==o.message.case&&"execServerControlMessage"!==o.message.case||await d.write(o.message.value),"conversationCheckpointUpdate"===o.message.case){const e=v?"ineligible_terminal_turn":"eligible";"ineligible_terminal_turn"===e&&(b=!0);const t=c?.noteRouted(o.message.value);try{await h.write({checkpoint:o.message.value,metadata:{resumeEligibility:e},...void 0===t?{}:{onSettled:t}})}catch(e){throw t?.(),e}}"kvServerMessage"===o.message.case&&await p.write(o.message.value)}r.onStreamEnded()}catch(e){w=e}finally{if(y=w,v&&b&&void 0!==w&&!o?.aborted&&!s?.aborted&&function(e){const t=e instanceof He?e:ct(e);return t instanceof qe&&function(e){return!0===e.isTransport||(e.cause instanceof Error?bt(e.cause):St(e.message))}(t)}(w)&&(On.debug(e,"Ignoring transport close after terminal agent stream",{caughtError:w instanceof Error?`${w.name}: ${w.message}`:String(w)}),r.onStreamEnded(),y=void 0),v||o?.aborted||s?.aborted){if(!v&&!o?.aborted){const t=`Stream ended without turnEnded, abort signals: signal.aborted=${o?.aborted}, parentSignal.aborted=${s?.aborted}; firstMessageFired=${f}`;On.warn(e,t)}}else{const t="Stream ended without turnEnded — connection likely dropped mid-stream";void 0===w?(On.warn(e,t),y=new qe(t,{isTransport:!0})):w instanceof Error&&"[aborted] aborted"===w.message?(On.warn(e,`${t}; retrying caught [aborted] aborted error`),y=new qe(t,{cause:w,isTransport:!0})):On.warn(e,`${t}; caught non-retriable stream error, rethrowing as-is`,{caughtError:jn(w)})}u.close(),d.close(),h.close(),p.close()}if(void 0!==y)throw y}()}}(e,$e,q,xe,D.signal,e.signal,Pe,Ie,De,v);let Be;const We={handleCheckpoint:async(e,t,r)=>{await l.handleCheckpoint(e,t,r),Be=r?.resumeEligibility??"eligible"},getLatestCheckpoint:()=>l.getLatestCheckpoint()};Z[Symbol.dispose]();const ze=5e3;let Ve;const Je=()=>{Ve=setTimeout((()=>{J.write(new de.KS({message:{case:"clientHeartbeat",value:new de.kA}})).then((()=>q.onClientSentHeartbeat()),(()=>{})),Je()}),ze)},Ze=()=>{void 0!==Ve&&(clearTimeout(Ve),Ve=void 0)};Je();try{let t;if("shellCommandAction"===r.action.case&&r.action.value.execId){const n=r.action.value,i=new he.a({command:n.shellCommand?.command||"",parsingResult:new he.HO,skipApproval:!0}),a=s.get(ee).execute(e,i,{execId:n.execId}),c=new Tr(Fe,o,new h.F8(J,(e=>new de.KS({message:{case:"interactionResponse",value:e}}))),q);t={run:async e=>{await Promise.all([U.track("handleShellStream",Un(e,a,o)),U.track("interactionController",c.run(e))])}}}else{const e=new Tr(Fe,o,new h.F8(J,(e=>new de.KS({message:{case:"interactionResponse",value:e}}))),q);t={run:async t=>{await U.track("interactionController",e.run(t))}}}void 0!==X&&await Promise.race([X,Ue.catch((()=>{}))]);const i=new h.F8(J,(e=>{if((0,we.isMessage)(e,d.yT))return new de.KS({message:{case:"execClientMessage",value:e}});if((0,we.isMessage)(e,d.$Y))return new de.KS({message:{case:"execClientControlMessage",value:e}});throw new Error(`Unknown exec message (type: ${(0,we.isMessage)(e)?e.getType().typeName:typeof e})`)})),l=new Ft(Ne,i,N,De),S=new le(je,new h.F8(J,(e=>new de.KS({message:{case:"kvClientMessage",value:e}}))),a,{beforeGetBlob:async(e,t)=>a.persistForRemoteRead(e,t)}),k=new Se(Le,We,e);let _,C;const E={promise:new Promise(((e,t)=>{_=e,C=t})),resolve:_,reject:C};D.canceled?(E.resolve(),Fe.close()):D.signal.addEventListener("abort",(()=>{E.resolve(),Fe.close()}),{once:!0}),l.run(D).then(E.resolve).catch(E.reject);const x=Promise.allSettled([U.track("streamSplitter",Ue.finally((()=>{Ze(),c.close(),i.close()}))),U.track("execHandler",E.promise),t.run(e),U.track("checkpointController",k.run()),U.track("kvHandler",S.run(e)),U.track("conversationActionManager",c.run(e,{write:async t=>{await Nn({ctx:e,action:t,resources:s,blobStore:a,options:p,source:"queued_action"}),await J.write(new de.KS({message:{case:"conversationAction",value:t}}))}}))]);let R,I;const T={promise:new Promise(((e,t)=>{R=e,I=t})),resolve:R,reject:I};x.then(T.resolve).catch(T.reject),e.canceled?T.reject(new Ke("User aborted request")):e.signal.addEventListener("abort",(()=>T.reject(new Ke("User aborted request"))),{once:!0});const A=()=>{e.signal.aborted?j():function(e){const t=e.lingerMs??6e3;return new Promise((r=>{let n=!1;const o=e=>{n||(n=!0,clearTimeout(s),r(e))},s=setTimeout((()=>o("linger_timed_out")),t);e.done.then((()=>o("stream_ended")),(()=>o("stream_ended")))}))}({done:Ue,lingerMs:p.softCancelLingerMs}).then((t=>{On.info(e,"Soft-cancel transport linger finished",{outcome:t,requestId:f}),j()}))};D.canceled?(A(),T.reject(new Ke("User aborted request"))):D.signal.addEventListener("abort",(()=>{A(),T.reject(new Ke("User aborted request"))}),{once:!0});const $=await T.promise,M=$[0],O=$[1],F=$[3],L=e=>e.reason instanceof Error?`${e.reason.name}: ${e.reason.message}`:String(e.reason);if("rejected"===F.status)throw new Ge("Checkpoint persistence failed",{cause:F.reason instanceof Error?F.reason:void 0,requestId:f,displayInfo:{title:"Checkpoint persistence failed",detail:L(F),isRetryable:!1}});const B="ineligible_terminal_turn"===Be;if(B){const t={..."rejected"===M.status?{streamSplitter:L(M)}:{},..."rejected"===O.status?{execHandler:L(O)}:{}};Object.keys(t).length>0&&On.debug(e,"Ignoring handler errors after terminal checkpoint",t)}if("rejected"===M.status&&!B)throw M.reason;if("rejected"===O.status&&!B)throw O.reason;D.canceled||await this.processUnprocessedMessages(P,c,We,n,o,s,a,u,p,f,m,g,w,q,y,v,b)}finally{Ze(),V?.stop(),V=void 0,z&&(z[Symbol.dispose](),z=void 0)}}catch(e){C.error=e,C.hasError=!0}finally{$n(C)}var E,x}async processUnprocessedMessages(e,t,r,n,o,s,a,c,l,u,d,h,p,f,m,g,w){if(!t.hasUnprocessedMessages())return;const y=t.getUnprocessedUserMessages(),v=r.getLatestCheckpoint();if(!v||0===y.length)return;const b=y[0];t.markMessageAsProcessed(b),t.resetStream(),f[Symbol.dispose]();const S=r.getLatestCheckpoint();try{await this.runInternal(e,v,new i.QFf({action:{case:"userMessageAction",value:new i.Vtf({userMessage:b})}}),n,o,s,a,t,r,c,l,u,d,h,p,m,g,w,0,void 0,"agent.request.queuedMessage")}catch(e){throw S===r.getLatestCheckpoint()&&t.requeueMessage(b),e}}}const Hn="cursor-ide-browser",qn="cursor-dev-control",zn="custom-user-tools",Gn=new Set(["cursor-app-control","cursor-backend-control","cursor-browser-extension",Hn,qn,zn,"fsd","cursor-subscriptions","cursor-cloud","suggestions","Cursor Slack Tools","Cursor Automation Tools"]);function Vn(e){return!Gn.has(e)}const Kn=new Set([qn,Hn]);function Jn(e){if(void 0!==e&&0!==Object.keys(e).length)try{return JSON.stringify(e)}catch{return}}function Zn(e){return{name:e.toolName,description:e.description,arguments:e.inputSchema,outputSchema:e.outputSchema,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId}}var Xn;function Qn(e){return void 0===e||void 0===e.serverIdentifiers}function Yn(e){switch(e.kind){case"ready":return void 0===e.toolListError?"connected":"error";case"requires_authentication":return"needsAuth";case"error":return"error";default:return"loading"}}(0,y.cF)(Symbol("mcpHostFilledArguments"),[]),function(e){e.Snapshots="cursor_mcp_lease_snapshot_store",e.Status="cursor_mcp_lease_server_status",e.Settings="cursor_mcp_lease_settings",e.Providers="cursor_mcp_lease_providers",e.Unknown="cursor_mcp_lease_unknown"}(Xn||(Xn={}));const eo=q("mcp-executor",(e=>new B(e,Z("mcpArgs"),X("mcpResult"))),((e,t)=>{t.register(new I(e,Y("mcpArgs"),Q("mcpResult")))})),to=q("list-mcp-resources-executor",(e=>new B(e,Z("listMcpResourcesExecArgs"),X("listMcpResourcesExecResult"))),((e,t)=>{t.register(new I(e,Y("listMcpResourcesExecArgs"),Q("listMcpResourcesExecResult")))})),ro=q("read-mcp-resource-executor",(e=>new B(e,Z("readMcpResourceExecArgs"),X("readMcpResourceExecResult"))),((e,t)=>{t.register(new I(e,Y("readMcpResourceExecArgs"),Q("readMcpResourceExecResult")))})),no=q("mcp-state-executor",(e=>new B(e,Z("mcpStateExecArgs"),X("mcpStateExecResult"))),((e,t)=>{t.register(new I(e,Y("mcpStateExecArgs"),Q("mcpStateExecResult")))}));var oo=r("../proto/dist/generated/agent/v1/subagent_exec_pb.js");(0,y.cF)(Symbol("pendingSubagentReplay"),void 0);class so extends Error{constructor(e,t){super(e),this.name="SubagentHostError",this.agentId=t?.agentId,this.cause=t?.cause}}const io=q("subagent-executor",(e=>new B(e,Z("subagentArgs"),X("subagentResult"))),((e,t)=>{t.register(new I(e,Y("subagentArgs"),Q("subagentResult")))})),ao=q("subagent-await-executor",(e=>new B(e,Z("subagentAwaitArgs"),X("subagentAwaitResult"))),((e,t)=>{t.register(new I(e,Y("subagentAwaitArgs"),Q("subagentAwaitResult")))})),co=q("force-background-subagent-executor",(e=>new B(e,Z("forceBackgroundSubagentArgs"),X("forceBackgroundSubagentResult"))),((e,t)=>{t.register(new I(e,Y("forceBackgroundSubagentArgs"),Q("forceBackgroundSubagentResult")))}));var lo=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/status.js"),uo=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js");const ho=(0,ye.createContextKey)(void 0,{description:"anysphere.callerContext"}),po=(0,y.cF)(Symbol("context-rpc.expected_error"),void 0);function fo(e,t,r){!0===t.get(po)?.(r)?e?.setAttribute("rpc.expected_error",!0):(e?.recordException(go(r)),e?.setStatus({code:lo.s.ERROR,message:r instanceof Error?r.message:"RPC call failed"})),e?.end()}function mo(e){return null!==e&&"object"==typeof e&&Symbol.asyncIterator in e}function go(e){return e instanceof Error?e:new Error(String(e))}function wo(e,t,r){return{[Symbol.asyncIterator](){const n=e[Symbol.asyncIterator]();let o=!1;const s=e=>{o||(o=!0,e?(t?.recordException(go(e)),t?.setStatus({code:lo.s.ERROR,message:e instanceof Error?e.message:"Stream failed"})):t?.setStatus({code:lo.s.OK}),t?.end(),r?.())};return{async next(){try{const e=await n.next();return e.done&&s(),e}catch(e){throw s(e),e}},return:async e=>(s(),n.return?n.return(e):{done:!0,value:void 0}),async throw(e){if(s(e),n.throw)return n.throw(e);throw e}}}}}function yo(...e){const t=new Headers;for(const r of e)r&&(r instanceof Headers?r:new Headers(r)).forEach(((e,r)=>{t.set(r,e)}));return t}function vo(e,t){const{injectTraceHeaders:r=!0,extractHeaders:n}=t;return new Proxy(e,{get(e,o){const s=e[o];return"function"!=typeof s?s:(i,a,c={})=>{const l=(0,$.fR)(i.withName(`rpc.${String(o)}`),{kind:uo.v.CLIENT,attributes:{"rpc.method":String(o),"rpc.system":"connect"}}),u=(0,$.fU)(l);let d;try{let o;if(r&&(o=function(e){const t=new Headers;try{const r=(0,$.fU)(e),n=r?.spanContext?.();if(n?.traceId&&n.spanId){const e=n.traceFlags??0,r=`00-${n.traceId}-${n.spanId}-${e.toString(16).padStart(2,"0")}`;t.set("traceparent",r),t.set("backend-traceparent",r),n.traceState&&t.set("tracestate",n.traceState.serialize())}}catch{}return t}(l)),n){const e=n(l);e&&(o=yo(o,e))}const i=yo(c.headers,o),{signal:p,cleanup:f}=!0===t.enableAbortSignal?function(e,t){if(void 0===t||t===e)return{signal:e};const r=new AbortController,n=()=>{r.abort(e.reason)},o=()=>{r.abort(t.reason)};e.addEventListener("abort",n,{once:!0}),t.addEventListener("abort",o,{once:!0}),e.aborted?n():t.aborted&&o();return{signal:r.signal,cleanup:()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",o)}}}(l.signal,c.signal):{signal:c.signal,cleanup:void 0};d=f;const m=(c.contextValues??(0,ye.createContextValues)()).set(ho,l),g={...c,headers:i,signal:p,contextValues:m},w=s.call(e,a,g);return mo(w)?wo(w,u,d):null!==(h=w)&&"object"==typeof h&&"then"in h&&"function"==typeof h.then?Promise.resolve(w).then((e=>mo(e)?wo(e,u,d):(u?.setStatus({code:lo.s.OK}),u?.end(),d?.(),e))).catch((e=>{throw fo(u,l,e),d?.(),e})):(u?.setStatus({code:lo.s.OK}),u?.end(),d?.(),w)}catch(e){throw fo(u,l,e),d?.(),e}var h}}})}var bo=r("node:crypto?8af2"),So=r("../utils/dist/workspace-paths.js");function ko(){return(0,s.join)(function(){const e=process.env.CURSOR_DATA_DIR;return e?.trim()?e:(0,s.join)((0,o.homedir)(),".cursor")}(),"projects")}function _o(e){return(0,s.join)(ko(),(0,So.r_)(e))}var Co=r("node:fs/promises"),Eo=r("../../node_modules/.pnpm/lru-cache@11.2.5/node_modules/lru-cache/dist/esm/index.js"),xo=r("node:fs");const Po="local";function Ro(e,t){return`${e}:task_progress:${t}`}function Io(e){const t={};return"string"==typeof e.title&&e.title.trim().length>0&&(t.title=e.title),"string"==typeof e.cwd&&e.cwd.trim().length>0&&(t.cwd=e.cwd),"number"==typeof e.startTimeMs&&Number.isFinite(e.startTimeMs)&&e.startTimeMs>0&&(t.startTimeMs=String(Math.floor(e.startTimeMs))),Object.keys(t).length>0?t:void 0}function To(e,t){e.hookApprovalRequirement=void 0!==t?new he.In(t):void 0}function Ao(e){return e.hookApprovalRequirement}function $o(e){return e?.kind===he.b.FORCE_PROMPT}function Mo(e){return!(!e.skipApproval||e.smartModeClassifierAllowed&&$o(e.hookApprovalRequirement))}var Do=r("../proto/dist/generated/agent/v1/background_shell_exec_pb.js"),Oo=r("../shell-exec/dist/api/index.js"),Fo=r("./src/agent/native/tree-sitter.webpack.cjs"),No=r("./src/agent/native/tree-sitter-bash.webpack.cjs");const Lo=function(e,t=console.warn){let r;return()=>{if(void 0!==r)return r;try{const t=e();t.setLanguage(No),r=t}catch(e){if(!function(e){return"object"==typeof e&&null!==e&&"CURSOR_TREE_SITTER_STUBBED"===e.code}(e))throw e;r=null,t("shell-parser: tree-sitter natives are unavailable in this artifact; shell command analysis degrades to parsingFailed")}return r}}((()=>new Fo)),jo=new Set(["file_redirect","heredoc_redirect","herestring_redirect","heredoc","here_string","redirect","redirection"]),Uo=new Set(["<",">",">>",">|","<>","<&",">&","&>","&>>"]);function Bo(e,t){if(null===e)return{legacy:{simpleCommands:[],hasInputRedirect:!1,hasOutputRedirect:!1},structured:{parsingFailed:!0,executableCommands:[],hasRedirects:!1,hasCommandSubstitution:!1,redirects:[]}};const r=e.parse(t),n=new WeakSet;let o=!1,s=!0;const i={simpleCommands:[],hasInputRedirect:!1,hasOutputRedirect:!1},a={parsingFailed:!1,executableCommands:[],hasRedirects:!1,hasCommandSubstitution:!1,redirects:[]},c=e=>{o=!0,a.hasRedirects=!0,s=s&&e},l=e=>{if(e&&/^\d+$/.test(e.text))return Number.parseInt(e.text,10)},u=()=>({fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}),d=(e,t)=>{const r=(e=>{const t=e.children,r=t.findIndex((e=>Uo.has(e.type)));if(-1!==r)return{operator:t[r]?.type??"",target:t.slice(r+1).find((e=>"comment"!==e.type))}})(e);if(!r)return!1;const{operator:n,target:o}=r,s=((e,t)=>{if("&>"===t||"&>>"===t)return[1,2];const r=(e=>l(e.children.find((e=>"file_descriptor"===e.type))))(e);return void 0!==r?[r]:t.startsWith("<")?[0]:[1]})(e,n),i=(e=>{if(e){if("word"===e.type)return 0===e.namedChildren.length?e.text:void 0;if("number"===e.type)return e.text;if("raw_string"===e.type){if(e.text.length<2)return;return e.text.slice(1,-1)}if("string"===e.type){const t=e.namedChildren;if(0===t.length||t.some((e=>"string_content"!==e.type)))return;return t.map((e=>e.text)).join("")}}})(o),c={operator:n,destinationFds:s,targetNodeType:o?.type??""};if(void 0!==i&&(c.targetText=i),a.redirects.push(c),">&"===n){const e=l(o),r=void 0===e?void 0:t.fdTargets.get(e);if(!(e=>"original-stdout"===e||"original-stderr"===e||"dev-null"===e)(r)){for(const e of s)t.fdTargets.set(e,"unsafe");return!1}for(const e of s)t.fdTargets.set(e,r);return!0}if("<&"===n){const e=l(o),r=void 0===e?void 0:t.fdTargets.get(e);if("dev-null"!==r){for(const e of s)t.fdTargets.set(e,"unsafe");return!1}for(const e of s)t.fdTargets.set(e,r);return!0}if(!(e=>{if(!e)return!1;if("word"===e.type)return"/dev/null"===e.text;if("raw_string"===e.type)return"'/dev/null'"===e.text;if("string"===e.type){const t=e.namedChildren;return 1===t.length&&"string_content"===t[0]?.type&&"/dev/null"===t[0].text}return!1})(o)){for(const e of s)t.fdTargets.set(e,"unsafe");return!1}for(const e of s)t.fdTargets.set(e,"dev-null");return!0},h=(e,t)=>{if(!n.has(e)){if(n.add(e),(e=>{var t;t=e.text,/(^|\s)[0-9]*<>/.test(t)||/(^|\s)[0-9]*>(\||&)?/.test(t)||/(^|\s)&>/.test(t)||/(^|\s)[0-9]+>&[0-9]+/.test(t))&&(i.hasOutputRedirect=!0),"heredoc_redirect"!==e.type&&"herestring_redirect"!==e.type||(i.hasInputRedirect=!0)})(e),"heredoc_redirect"===e.type){const{redirect:t,isAllowlistSafe:r}=(e=>{const t=(e=>{const t=e.parent;if("redirected_statement"!==t?.type)return;const r=t.children.find((e=>"command"===e.type)),n=r?.childForFieldName("name");return n?.text})(e),r=void 0!==t&&!(e=>{let t=e.parent;for(;t;){if("command_substitution"===t.type&&"string"!==t.parent?.type)return!0;t=t.parent}return!1})(e),n={operator:r?"<<":"",destinationFds:r?[0]:[],targetNodeType:e.type};return r&&(n.targetText=t),{redirect:n,isAllowlistSafe:r}})(e);return a.redirects.push(t),void c(r)}if("file_redirect"!==e.type)return a.redirects.push({operator:"",destinationFds:[],targetNodeType:e.type}),void c(!1);c(d(e,t))}};return function e(t){const r=t.type;if((e=>{const t=u();for(const r of e.children)jo.has(r.type)&&h(r,t)})(t),jo.has(r)&&!n.has(t)&&h(t,u()),"command"===r){const e=t.childForFieldName("name");if(null===e)a.parsingFailed=!0;else{i.simpleCommands.push(e.text);let r=e.text;const n=[];for(const e of function(e){const t=[],r=e.walk();if(r.gotoFirstChild())do{"argument"===r.currentFieldName&&t.push(r.currentNode)}while(r.gotoNextSibling());return t}(t))n.push({type:e.type,value:e.text}),r+=` ${e.text}`;a.executableCommands.push({name:e.text,args:n,fullText:r})}}if("command_name"===r||"simple_command"===r)if("command_name"!==r||i.simpleCommands.includes(t.text)){if("simple_command"===r){const e=t.firstNamedChild;e&&"command_name"===e.type?i.simpleCommands.includes(e.text)||i.simpleCommands.push(e.text):i.simpleCommands.push(t.text)}}else i.simpleCommands.push(t.text);"command_substitution"!==r&&"process_substitution"!==r||(a.hasCommandSubstitution=!0);for(const r of t.children)e(r)}(r.rootNode),o&&(a.allRedirectsAreDevNull=s),{legacy:i,structured:a}}function Wo(e){return Bo(Lo(),e)}function Ho(e,t){return t>0&&t=55296&&r<=56319)&&function(e){return e>=56320&&e<=57343}(e.charCodeAt(t));var r}function qo(e,t){return t>0?t>=e.length?e.length:Math.trunc(t):0}function zo(e,t){const r=qo(e,t);return Ho(e,r)?r-1:r}function Go(e,t){const r=qo(e,t);return Ho(e,r)?r+1:r}function Vo(e,t){return t>0?e.length<=t?e:e.slice(0,zo(e,t)):""}function Ko(e,t){return t>0?e.length<=t?e:e.slice(Go(e,e.length-Math.trunc(t))):""}let Jo,Zo;function Xo(e,t){Jo??=new TextEncoder,Zo??=new Uint8Array(65536);let r=0,n=0;for(;r{const t=(0,Yo.o1)(e);try{return await(0,Co.realpath)(t)}catch{return t}},rs=1048576,ns=52428800;var os=r("../proto/dist/generated/agent/v1/sandbox_pb.js");function ss(e){if(!e)return;let t;return"allow"===e.default?t=os.h1.ALLOW:"deny"===e.default&&(t=os.h1.DENY),new os.RB({version:e.version,defaultAction:t,deny:e.deny??[],allow:e.allow??[],logging:e.logging?(r=e.logging,new os.Qq({decisionLogPath:r.decisionLogPath,logFormat:r.logFormat})):void 0});var r}function is(e){const t=function(e){if(!e)return;const t={};if(1===e.version&&(t.version=1),void 0!==e.defaultAction)switch(e.defaultAction){case os.h1.ALLOW:t.default="allow";break;case os.h1.DENY:t.default="deny"}return e.deny&&e.deny.length>0&&(t.deny=e.deny),e.allow&&e.allow.length>0&&(t.allow=e.allow),e.logging&&(t.logging=function(e){const t={};return e.decisionLogPath&&(t.decisionLogPath=e.decisionLogPath),"jsonl"===e.logFormat&&(t.logFormat="jsonl"),t}(e.logging)),t}(e.networkPolicy);return t||(e.networkAccess?(0,Oo.T6)():(0,Oo.Po)())}function as(e){switch(e){case"system":return os.Sz.SYSTEM;case"workspace":return os.Sz.WORKSPACE;default:return os.Sz.UNSPECIFIED}}function cs(e){const t=function(e){switch(e){case os.Sz.SYSTEM:return"system";case os.Sz.WORKSPACE:return"workspace";case os.Sz.UNSPECIFIED:default:return}}(e.readBoundary),r=e.additionalReadPaths??[];return{readBoundary:t,additionalReadPaths:"workspace"===t&&r.length>0?r:void 0,privateTmp:e.privateTmp}}function ls(e){if(!e)return{type:"insecure_none"};switch(e.type){case os.vc.INSECURE_NONE:case os.vc.UNSPECIFIED:return{type:"insecure_none",allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies};case os.vc.WORKSPACE_READWRITE:return{type:"workspace_readwrite",networkPolicy:is(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadwritePaths:e.additionalReadwritePaths,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict,...cs(e)};case os.vc.WORKSPACE_READONLY:return{type:"workspace_readonly",networkPolicy:is(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict,...cs(e)};default:return{type:"insecure_none"}}}function us(e){if(e)return"insecure_none"===e.type?new os.Mw({type:os.vc.INSECURE_NONE,allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies}):"workspace_readwrite"===e.type?new os.Mw({type:os.vc.WORKSPACE_READWRITE,networkAccess:(0,Oo.$b)(e.networkPolicy),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadwritePaths:e.additionalReadwritePaths??[],additionalReadonlyPaths:e.additionalReadonlyPaths??[],disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicy:ss(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:as(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[],privateTmp:e.privateTmp}):"workspace_readonly"===e.type?new os.Mw({type:os.vc.WORKSPACE_READONLY,networkAccess:(0,Oo.$b)(e.networkPolicy),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths??[],disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicy:ss(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:as(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[],privateTmp:e.privateTmp}):new os.Mw({type:os.vc.INSECURE_NONE})}function ds(e){return" "===e||"\t"===e||"\n"===e||"\r"===e||" "===e||"​"===e||"‌"===e||"‍"===e||"\ufeff"===e}function hs(e){let t="",r=!1;for(const n of e)ds(n)?r=!0:(r&&t.length>0&&(t+=" "),r=!1,t+=n);return t}function ps(e){if(0===e.length)return!1;for(let t=0;te.fullText))])]}const ws={a:"",b:"\b",e:"",E:"",f:"\f",n:"\n",r:"\r",t:"\t",v:"\v","\\":"\\","'":"'",'"':'"',"?":"?"};function ys(e){let t="",r="plain",n=0;for(;n=e.length){t+=o,n++;continue}const s=e[n+1],i=ws[s];if(void 0!==i){t+=i,n+=2;continue}const a="x"===s?e.slice(n+2).match(/^[0-9a-fA-F]{1,2}/)?.[0]:"u"===s?e.slice(n+2).match(/^[0-9a-fA-F]{1,4}/)?.[0]:"U"===s?e.slice(n+2).match(/^[0-9a-fA-F]{1,8}/)?.[0]:e.slice(n+1).match(/^[0-7]{1,3}/)?.[0],c="u"===s||"U"===s,l="x"===s||c?16:8;if(void 0!==a){const e=Number.parseInt(a,l);if(!c||e<=1114111){t+=c?String.fromCodePoint(e):String.fromCharCode(e),n+=a.length+(16===l?2:1);continue}}t+=s,n+=2}return hs(t)}function vs({rule:e,command:t}){const r=hs(e).trim();return 0!==r.length&&(null!==function(e){const t=hs(e).trim();if(0===t.length)return"Rule cannot be empty";if(t.length>512)return"Rule cannot exceed 512 characters";if(ps(t))return"Rule cannot match every command; be more specific than wildcards alone";if(t.startsWith(":"))return"Colon rules need an executable before `:` (e.g. `aws:*s3 rm*`)";const r=fs(t);if(void 0!==r){const{executablePattern:e,argsPattern:t}=r;if(ps(e)&&(0===t.length||ps(t)))return"Rule cannot match every command; narrow the executable or argument pattern"}return null}(r)||[t.trim(),hs(t).trim(),ys(t).trim()].some((e=>function(e,t){const r=fs(e);if(void 0!==r){const{executablePattern:e,argsPattern:n}=r,o=t.indexOf(" "),s=-1===o?t:t.slice(0,o),i=-1===o?"":t.slice(o+1).trim();if((0,ms.T)(e,s)&&(0,ms.T)(n,i))return!0}return e.includes("*")?(0,ms.T)(e,t):t===e||t.startsWith(`${e} `)}(r,e))))}function bs({matchForms:e,blockedCommands:t}){const r=t.map((e=>e.trim())).filter((e=>e.length>0));if(0===r.length)return;const n=e.map((e=>e.trim())).filter((e=>e.length>0)),o=n.length>0?n:[""];for(const e of r)if(o.some((t=>vs({rule:e,command:t}))))return e}function Ss(e){return`Denied: this command was blocked by administrator policy (denylist rule: ${e}) and was not executed. It cannot be approved from this conversation; only a user can run it manually outside the agent. You may continue working on the task.`}function ks({command:e,parsingResult:t,blockedCommands:r}){if(0===r.length)return;if(t.parsingFailed||0===t.executableCommands.length)return"Denied: this command could not be conclusively analyzed against your team's administrator command denylist, so it was blocked (fail-closed) and was not executed. It cannot be approved from this conversation; only a user can run it manually outside the agent. You may continue working on the task.";const n=bs({matchForms:gs({command:e,parsingResult:t}),blockedCommands:r});return void 0===n?void 0:Ss(n)}var _s=r("../utils/dist/test-resets.js");const Cs="CURSOR_FORCED_SHELL_EGRESS_NETWORK_DEFAULT",Es="CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_DENY_DOMAINS",xs=/\$\(|`|<\(|>\(/,Ps=/[;&|]/;let Rs,Is,Ts,As;function $s(){if(void 0===Rs){const e=(process.env.CURSOR_FORCED_SHELL_EGRESS??"").trim().toLowerCase();Rs=""!==e&&"0"!==e&&"false"!==e&&"off"!==e}return Rs}function Ms(e){const t=(process.env[e]??"").trim();if(t)try{return new RegExp(t,"i"),t}catch(t){throw new Error(`[forced-egress] invalid regex in ${e}: ${String(t)}`)}}function Ds(e){return(process.env[e]??"").split(",").map((e=>e.trim())).filter((e=>e.length>0))}function Os(e){const t=(process.env[e]??"").split(":").map((e=>e.trim())).filter((e=>e.length>0)),r=t.filter((e=>e.startsWith("/"))),n=t.length-r.length;return n>0&&console.error(`[forced-egress] ignoring ${n} non-absolute path(s) in ${e}.`),r}function Fs(){if(void 0===As){const e=(process.env[Cs]??"").trim().toLowerCase();let t="deny";"allow"===e||"deny"===e?t=e:""!==e&&console.error(`[forced-egress] ignoring invalid value in ${Cs} (expected "allow" or "deny"); using "deny".`);const r=Ds("CURSOR_FORCED_SHELL_EGRESS_DENY_DOMAINS"),n=(process.env[Es]??"").trim();let o=r;"none"===n.toLowerCase()?o=[]:""!==n&&(o=Ds(Es)),As={networkDefault:t,denyDomains:r,dependencyDenyDomains:o,allowDomains:Ds("CURSOR_FORCED_SHELL_EGRESS_ALLOW_DOMAINS"),writablePaths:Os("CURSOR_FORCED_SHELL_EGRESS_WRITABLE_PATHS")}}return As}function Ns(e,t,r={}){const n=[Ms(e),Ms(t)].filter((e=>void 0!==e)).map((e=>`(?:${e})`));if(0===n.length)return null;const o=n.join("|"),s=r.anchorToExecutable?`^\\s*(?:[A-Za-z_][A-Za-z0-9_]*=[^\\s]*\\s+)*(?:${o})`:o;return new RegExp(s,"i")}function Ls(e,t){const r=function(){const e=Fs();return{type:"workspace_readwrite",...e.writablePaths.length>0?{additionalReadwritePaths:e.writablePaths}:{},networkPolicy:{version:1,default:e.networkDefault,allow:["127.0.0.0/8","::1/128","localhost",...e.allowDomains],...e.denyDomains.length>0?{deny:e.denyDomains}:{}},networkPolicyStrict:!0,skipStatsigDefaults:!0,enableSharedBuildCache:!0}}(),n=(void 0===Is&&(Is=Ns("CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_DEPENDENCY_REGEX",{anchorToExecutable:!0})),Is);if(null===n)return r;const o=t?.executableCommands??[];if(t?.parsingFailed||0===o.length)return r;if(xs.test(e))return r;const s=(void 0===Ts&&(Ts=Ns("CURSOR_FORCED_SHELL_EGRESS_SOURCE_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_SOURCE_REGEX")),Ts);for(const e of o){const t=e.fullText?.trim()||e.name?.trim()||"";if(!t||s?.test(t)||Ps.test(t))return r}return o.every((e=>n.test(e.fullText?.trim()||e.name?.trim()||"")))?function(){const e=Fs();return{type:"workspace_readwrite",...e.writablePaths.length>0?{additionalReadwritePaths:e.writablePaths}:{},networkPolicy:{version:1,default:"allow",...e.dependencyDenyDomains.length>0?{deny:e.dependencyDenyDomains}:{}},skipStatsigDefaults:!0,enableSharedBuildCache:!0}}():r}(0,_s.J)((function(){Rs=void 0,Is=void 0,Ts=void 0,As=void 0}));var js=r("../utils/dist/lru-cache.js");const Us=["Desktop","Documents","Downloads","Music","Movies","Pictures","Library",".Trash"],Bs="/Volumes";function Ws(e){const t=e.replace(/\/{2,}/g,"/");return t.length>1&&t.endsWith("/")?t.slice(0,-1):t}function Hs(e,t){if("darwin"!==t.platform)return[];const r=Ws(e),n=r.toLowerCase(),o=Ws(t.homeDirectory),s="/"===r?1:r.split("/").length;return[...Us.map((e=>`${o}/${e}`)),Bs].filter((e=>function(e,t){return e!==t&&e.startsWith(t.endsWith("/")?t:`${t}/`)}(e.toLowerCase(),n))).map((e=>{const t=e.split("/").slice(s).join("/");return`${"/"===r?"":r}/${t}`}))}var qs=r("../utils/dist/safe-spawn-cwd.js"),zs=r("node:util");const Gs=8388608;var Vs=r("../../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/lib/index.js"),Ks=r("../../node_modules/.pnpm/jschardet@3.1.4/node_modules/jschardet/index.js");function Js(e){let t=1,r=0;for(;;){const n=e.indexOf("\n",r);if(-1===n)return t;t++,r=n+1}}const Zs="utf8",Xs="utf8bom",Qs="latin1",Ys={"windows-1250":"cp1250","windows-1251":"cp1251","windows-1252":"cp1252","windows-1253":"cp1253","windows-1254":"cp1254","windows-1255":"cp1255","windows-1256":"cp1256","windows-1257":"cp1257","windows-1258":"cp1258","iso-8859-1":"iso88591","iso-8859-2":"iso88592","iso-8859-5":"iso88595","iso-8859-6":"iso88596","iso-8859-7":"iso88597","iso-8859-8":"iso88598","iso-8859-9":"iso88599","iso-8859-15":"iso885915","iso-8859-16":"iso885916",shift_jis:"shiftjis","euc-jp":"eucjp","euc-kr":"euckr","iso-2022-jp":"iso2022jp","iso-2022-kr":"iso2022kr",gb2312:"gb2312",gbk:"gbk",gb18030:"gb18030",big5:"big5","big5-hkscs":"big5hkscs","koi8-r":"koi8r","koi8-u":"koi8u",ibm855:"cp855",ibm866:"cp866",maccyrillic:"maccyrillic","x-mac-cyrillic":"maccyrillic","utf-16le":"utf16le","utf-16be":"utf16be","utf-32le":"utf32le","utf-32be":"utf32be",johab:"johab",cp949:"cp949",cp932:"cp932"};function ei(e){return Ys[e]||e}function ti(e){return e.startsWith("\ufeff")?e.slice(1):e}function ri(e){const t=e.toLowerCase();return"latin-1"===t?Qs:"utf-8"===t?Zs:"utf-8-bom"===t||"utf-8 bom"===t?Xs:t}function ni(e){const t=[],r=[];let n=0;for(let o=e.indexOf("\n");-1!==o;o=e.indexOf("\n",n)){const s=13===e.charCodeAt(o-1);t.push(e.slice(n,s?o-1:o)),r.push(s?"\r\n":"\n"),n=o+1}return t.push(e.slice(n)),r.push(""),{lines:t,ends:r}}const oi=new zs.TextDecoder("utf-8",{fatal:!1}),si=new zs.TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),ii="�";function ai(e){return oi.decode(e)}function ci(e){let t=0,r=0,n=0,o=0;for(let s=0;s0?o--:n++}return r+=n,r>t}function li(e,t=1/0){let r=0,n=0;for(;r=194&&r<=223)n=2;else if(r>=224&&r<=239)n=3,224===r&&(o=160),237===r&&(s=159);else{if(!(r>=240&&r<=244))return 1;n=4,240===r&&(o=144),244===r&&(s=143)}let i=1;for(;i(1===i?s:191))break;i++}return i===n?void 0:i}function di(e){return e<128?1:e<2048?2:e<65536?3:4}var hi;!function(e){e.CRLF="CRLF",e.LF="LF"}(hi||(hi={}));const pi=[".mp4",".webm",".mov",".avi",".mkv",".wmv",".flv",".m4v"],fi=new Set(pi),mi=new zs.TextDecoder("utf-8",{fatal:!0}),gi=new zs.TextDecoder("latin1"),wi=Buffer.from([239,187,191]),yi={utf16le:Buffer.from([255,254]),utf16be:Buffer.from([254,255]),utf32le:Buffer.from([255,254,0,0]),utf32be:Buffer.from([0,0,254,255])},vi=8192,bi="UTF-8",Si="windows-1252",ki=/[^\u0000-\u007f\ufffd]/u,_i=/(?:\p{Script=Cyrillic}\p{M}*){3,}/gu,Ci=/(?:\p{Script=Greek}\p{M}*){3,}/gu,Ei=/(?:\p{Script=Hebrew}\p{M}*){3,}/gu,xi=new Map([["windows-1251",_i],["ISO-8859-5",_i],["KOI8-R",_i],["x-mac-cyrillic",_i],["IBM866",_i],["IBM855",_i],["ISO-8859-7",Ci],["windows-1253",Ci],["windows-1255",Ei],["ISO-8859-8",Ei],["TIS-620",/(?:\p{Script=Thai}\p{M}*){3,}/gu]]),Pi=/\p{Script=Latin}\p{M}*[\p{Script=Cyrillic}\p{Script=Greek}\p{Script=Hebrew}\p{Script=Thai}]|[\p{Script=Cyrillic}\p{Script=Greek}\p{Script=Hebrew}\p{Script=Thai}]\p{M}*\p{Script=Latin}/u,Ri=/[\p{L}\p{M}]+/gu,Ii=String.raw`[\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF\u0152\u0153\u0160\u0161\u017D\u017E\u0178]`,Ti=new RegExp(`[A-Za-z]${Ii}{1,2}(?!${Ii})|^${Ii}{1,2}[A-Za-z]`,"u"),Ai=new Map,$i=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".pdf",".zip",".tar",".gz",".exe",".dll",".so",".dylib",".bin",...pi]),Mi=/\.(png|jpg|jpeg|gif|webp|ico|bmp)$/i,Di=new Set([".ps1",".psm1",".psd1"]),Oi=/[^\u0000-\u007f]/u;function Fi(e){const t=e.toLowerCase(),r=t.lastIndexOf(".");return-1===r?"":t.substring(r)}function Ni(e){const t=Fi(e);return fi.has(t)}function Li(e){const t=Fi(e);return{encoding:"binary",lineEnding:hi.LF,isBinaryFile:!0,isImageFile:Mi.test(t),isVideoFile:fi.has(t)}}async function ji(e,t){return(await Ui(e,t)).text}async function Ui(e,t){const{stamp:r,buf:n}=await async function(e){const t=await(0,Co.open)(e,"r");try{return{stamp:await t.stat(),buf:await t.readFile()}}finally{await t.close()}}(e),o=qi(n);if(o.isBinaryFile)throw new Error("Binary file cannot be decoded as text");const s=Qi(e,r);let i;i=t||s||o.encoding;const{text:a,encoding:c}=ta(n,i),l=ti(a),u=c===Zs&&ra(n)?Xs:c;Yi(e,r,u);const d=function(e,t){if(t===Xs)return ra(e);const r=yi[ei(ri(t))];return void 0!==r&&e.subarray(0,r.length).equals(r)}(n,u);if(o.lineEnding===hi.CRLF){const e=l.match(/\r\n/g)?.length??0,t=(l.match(/\n/g)?.length??0)-e;return{text:l.replaceAll("\r\n","\n"),encoding:u,bom:d,lineEnding:e>t?"CRLF":"LF"}}return{text:l,encoding:u,bom:d,lineEnding:"LF"}}async function Bi(e,t){if("binary"===t.encoding)return void Xi(e);let r;try{r=await(0,Co.stat)(e)}catch{return void Xi(e)}r.size===t.buffer.byteLength?Yi(e,r,t.encoding):Xi(e)}async function Wi(e,t,r,o){let s,i;try{s=r?await async function(e,t){try{return await Hi(e)}catch{}const r=Fi(e);if($i.has(r))return Li(e);try{return await async function(e){const t=new Map;let r=0;for await(const n of Ji(e)){if(r>=100)break;try{const e=await Hi(n);if(!e.isBinaryFile){const r=`${e.encoding}:${e.lineEnding}`,n=t.get(r);if(n){if(n.count++,n.count>=3)return n.format}else t.set(r,{format:e,count:1})}r++}catch(e){}}let n;for(const e of t.values())(!n||e.count>n.count)&&(n=e);return n?n.format:Zi()}(t)}catch{return Zi()}}(e,r):await Hi(e)}catch{const t=Fi(e);s=$i.has(t)?Li(e):Zi()}const a=()=>i??=async function(e){try{const t=await(0,Co.stat)(e);if(!t.isFile()||t.size>Gs)return;return await(0,Co.readFile)(e)}catch{return}}(e),c=Qi(e,await async function(e){try{return await(0,Co.stat)(e)}catch{return}}(e));let l;if(!s.isBinaryFile){let r;o?r=ri(o):c?r=ri(c):(r=ri(s.encoding),r===Xs||Vs.encodingExists(ei(r))||(r=Zs),r!==Zs&&r!==Xs||(r=await async function(e,t){const r=await t();return void 0===r||(0,n.isUtf8)(r)?e:ea(r).encoding===Qs?Qs:e}(r,a))),r===Zs&&!o&&function(e,t){return"win32"===process.platform&&Di.has(Fi(e))&&Oi.test(t)&&!t.startsWith("#!")}(e,t)&&(await async function(e){try{return await(0,Co.stat)(e),!1}catch(e){return e instanceof Error&&"code"in e&&"ENOENT"===e.code}}(e)||await async function(e){const t=await e();return void 0!==t&&(0,n.isAscii)(t)}(a))&&(r=Xs);const i=r===Xs||r===Zs&&!o&&await na(e,wi),u=yi[ei(r)];i?l=wi:u&&await na(e,u)&&(l=u),s={...s,encoding:i?Xs:r}}const u=Js(t),d=t.includes("\r\n")?void 0:await async function(e,t){if(t.isBinaryFile)return;const r=await e();if(void 0===r||!r.includes(13))return;const n=ti(ta(r,t.encoding).text);return function(e){let t=!1,r=!1;for(let n=e.indexOf("\n");-1!==n;n=e.indexOf("\n",n+1))if(13===e.charCodeAt(n-1)?t=!0:r=!0,t&&r)return!0;return!1}(n)?n:void 0}(a,s);if(void 0!==d?t=function({content:e,existing:t,defaultEnding:r}){const n=ni(t),o=ni(e),s=function({before:e,after:t}){const r=new Int32Array(t.length).fill(-1);let n=0;for(;n0&&i>0&&(s+1)*(i+1)<=4e6){const o=i+1,a=new Uint16Array((s+1)*o);for(let r=s-1;r>=0;r--)for(let s=i-1;s>=0;s--)a[r*o+s]=e[n+r]===t[n+s]?a[(r+1)*o+s+1]+1:Math.max(a[(r+1)*o+s],a[r*o+s+1]);for(let c=0,l=0;c=a[c*o+l+1]?c++:l++}let a=-1,c=-1;for(let n=0;n<=t.length;n++){const o=n===t.length?e.length:r[n];if(-1!==o){if(o-a==n-c)for(let e=1;e50&&/^[A-Za-z0-9+/]*={0,2}$/.test(t))try{const e=Buffer.from(t,"base64");if(e.length>0){const r=Math.floor(.5*t.length);if(e.length>=r)return e}}catch{}return Buffer.from(e,"latin1")}(t);return{lines:u,buffer:e,format:s}}const h=l?ti(t):t,p=s.encoding===Xs?Zs:s.encoding,f=p===Zs?await async function(e,t){if(!t.includes(ii))return;const r=await e();return void 0===r?void 0:function(e,t){if(!e.includes(ii)||(0,n.isUtf8)(t))return;const r=function(e){const t=[];let r=0;for(const n of si.decode(e)){const o=n.codePointAt(0)??0;if(65533!==o){r+=di(o);continue}const s=ui(e,r);void 0===s?(t.push(void 0),r+=3):(t.push(e.subarray(r,r+s)),r+=s)}return r===e.length?t:void 0}(t),o=e.split(ii);if(void 0===r||o.length-1!==r.length)return;const s=[];for(let e=0;e=Math.max(0,e.length-3);t--){const r=e[t];if(r<128)return e;if(r>=192){const n=r>=240?4:r>=224?3:2;return e.length-t=e.length);o+=2){if(0===e[o+1]){const r=e[o];(r>=32&&r<=126||9===r||10===r||13===r)&&t++}if(0===e[o]){const t=e[o+1];(t>=32&&t<=126||9===t||10===t||13===t)&&r++}}return t>.8*n?"UTF-16LE":r>.8*n?"UTF-16BE":null}(e)??function(e){if(e.length<8)return null;if(0===e[0]&&0===e[1]&&254===e[2]&&255===e[3])return"UTF-32BE";if(255===e[0]&&254===e[1]&&0===e[2]&&0===e[3])return"UTF-32LE";let t=0,r=0;const n=Math.min(50,Math.floor(e.length/4));for(let o=0;o<4*n&&!(o+3>=e.length);o+=4){if(0===e[o]&&0===e[o+1]&&0===e[o+2]){const r=e[o+3];(r>=32&&r<=126||9===r||10===r||13===r)&&t++}if(0===e[o+1]&&0===e[o+2]&&0===e[o+3]){const t=e[o];(t>=32&&t<=126||9===t||10===t||13===t)&&r++}}return t>.8*n?"UTF-32BE":r>.8*n?"UTF-32LE":null}(e);if(t)return{encoding:t,lineEnding:Gi(Vs.decode(e.subarray(0,vi),ei(ri(t)))),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};if(!function(e){const t=Math.min(vi,e.length);if(0===t)return!0;for(let r=0;r=8&&137===r[0]&&80===r[1]&&78===r[2]&&71===r[3]&&13===r[4]&&10===r[5]&&26===r[6]&&10===r[7]||255===r[0]&&216===r[1]&&255===r[2]||r.length>=12&&82===r[0]&&73===r[1]&&70===r[2]&&70===r[3]&&87===r[8]&&69===r[9]&&66===r[10]&&80===r[11]||r.length>=6&&71===r[0]&&73===r[1]&&70===r[2]&&56===r[3]&&(55===r[4]||57===r[4])&&97===r[5])),isVideoFile:!1};var r,o,s;if((0,n.isUtf8)(e)&&(!e.includes(27)||!(0,n.isAscii)(e)))return{encoding:bi,lineEnding:zi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};if(!(0,n.isUtf8)(e)&&(o=ai(e),s=e.length,ci(o)||1024*li(o)<=s&&!ki.test(o)))return{encoding:bi,lineEnding:zi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};const i=Ks.detect(e);let a=i.confidence>.7?i.encoding:"utf-8";"ascii"===a&&(a="utf-8");const c=xi.get(a);return void 0!==c&&(a=function(e,t,r){const n=ei(ri(t));if(!Vs.encodingExists(n))return t;const o=Vs.decode(e,n);return Pi.test(o)&&function(e,t,r){const n=t.match(r)?.length??0;let o=0;for(const[t]of Vs.decode(e,Si).matchAll(Ri))Ti.test(t)&&o++;return o>n}(e,o,r)?Si:t}(e,a,c)),a!==Si||function(e,t){const r=ei(ri(t));return!Vs.getDecoder(r).write(e).includes(ii)}(e,a)||(a="utf-8"),{encoding:a??"utf-8",lineEnding:zi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function zi(e){let t=0,r=0;for(let n=0;n0&&13===e[n-1]?t++:r++);return Vi(t,r)}function Gi(e){const t=e.match(/\n/g)?.length??0,r=e.match(/\r\n/g)?.length??0;return Vi(r,t-r)}function Vi(e,t){return 0===e&&0===t?hi.LF:e/(e+t)*100>=5?hi.CRLF:hi.LF}async function Ki(e){const t=await(0,Co.open)(e,"r");try{const e=Buffer.allocUnsafe(vi),{bytesRead:r}=await t.read(e,0,vi,0);return e.subarray(0,r)}finally{await t.close()}}async function*Ji(e){const t=new Set(["node_modules",".git",".svn",".hg","dist","build","out",".next",".cache","coverage","__pycache__",".venv","venv",".turbo"]);try{const r=await(0,Co.readdir)(e,{withFileTypes:!0});for(const n of r){if(n.name.startsWith(".")&&".gitignore"!==n.name)continue;const r=(0,s.join)(e,n.name);n.isDirectory()?t.has(n.name)||(yield*Ji(r)):n.isFile()&&(yield r)}}catch(e){return}}function Zi(){return{encoding:Zs,lineEnding:"win32"===process.platform?hi.CRLF:hi.LF,isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function Xi(e){Ai.delete(e)}function Qi(e,t){const r=Ai.get(e);if(void 0!==r)return void 0!==t&&r.size===t.size&&r.mtimeMs===t.mtimeMs?r.encoding:void Ai.delete(e)}function Yi(e,t,r){if(Ai.has(e)&&Ai.delete(e),Ai.set(e,{encoding:r,size:t.size,mtimeMs:t.mtimeMs}),Ai.size<=100)return;const n=Ai.keys().next().value;void 0!==n&&Ai.delete(n)}function ea(e){try{return{text:mi.decode(e),encoding:Zs}}catch{const t=ai(e);return ci(t)?{text:t,encoding:Zs}:{text:gi.decode(e),encoding:Qs}}}function ta(e,t){const r=ri(t);if(r===Zs||r===Xs||"ascii"===r){const t=ea(e);return r===Xs&&t.encoding===Zs?{text:t.text,encoding:Xs}:t}if(r===Qs)return{text:gi.decode(e),encoding:Qs};try{const t=ei(r);if(Vs.encodingExists(t))return{text:Vs.decode(e,t),encoding:r}}catch{}return ea(e)}function ra(e){return e.length>=wi.length&&e[0]===wi[0]&&e[1]===wi[1]&&e[2]===wi[2]}async function na(e,t){try{return(await Ki(e)).subarray(0,t.length).equals(t)}catch{return!1}}var oa=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js");class sa{constructor({ttlMs:e,now:t=Date.now}){this.entries=new Map,this.nextSweepAtMs=0,this.ttlMs="function"==typeof e?e:sa.validated(e),this.now=t}static validated(e){if(!Number.isFinite(e)||e<=0)throw new Error(`TTL cache requires a positive ttlMs, got ${e}`);return()=>e}get(e){const t=this.entries.get(e);if(void 0!==t){if(!(t.expiresAtMs<=this.now()))return t.value;this.entries.delete(e)}}has(e){const t=this.entries.get(e);return!(void 0===t||t.expiresAtMs<=this.now()&&(this.entries.delete(e),1))}get size(){return this.entries.size}set(e,t){const r=this.now(),n=this.ttlMs();if(this.entries.set(e,{value:t,expiresAtMs:r+n}),!(r1048576?e:await async function(e,t){const r=function(e){const t=Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=qi(t);return r.isBinaryFile?ai(t):ti(ta(t,r.encoding).text)}(t);return function(e,t){if(!(0,n.isUtf8)(e))return!1;const r=e.toString("utf8");return(r.startsWith("\ufeff")?r.slice(1):r)===t}(t,r)?e:async function(e,t){const r=await(la??=(0,Co.mkdtemp)((0,s.join)((0,o.tmpdir)(),"cursorignore-utf8-")).then((e=>(process.once("exit",(()=>{try{(0,xo.rmSync)(e,{recursive:!0,force:!0})}catch{}})),e))),la),n=(0,s.join)(r,`cursorignore-${ua(e)}-${ua(t)}.txt`);if(await da(n))return n;const i=`${n}.${process.pid}.${Date.now()}.tmp`;return await(0,Co.writeFile)(i,t,"utf8"),await(0,Co.rename)(i,n),n}(e,r)}(e,await(0,Co.readFile)(e));return aa.set(e,{mtimeMs:t.mtimeMs,size:t.size,ripgrepPath:i}),i}function pa(e){return Promise.all(e.map((e=>async function(e){const t=ca.get(e);if(void 0!==t)return t;const r=ha(e).catch((()=>e)).finally((()=>{ca.delete(e)}));return ca.set(e,r),r}(e))))}(0,_s.J)((function(){aa.clear(),ca.clear()}));var fa=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function ma(e){if(e.aborted)return{aborted:Promise.resolve("aborted"),[Symbol.dispose](){}};let t=()=>{};const r=new Promise((e=>{t=()=>e("aborted")}));return e.addEventListener("abort",t,{once:!0}),{aborted:r,[Symbol.dispose](){e.removeEventListener("abort",t)}}}function ga(e,{root:t,searchPaths:r=[],includeGlobs:n=[],excludeGlobs:s=[],caseSensitive:i=!1,cursorIgnoreFiles:a=[],sandboxPolicy:c={type:"insecure_none"},noIgnoreVcs:l=!1,followSymlinks:u=!1,source:d="ripwalk"}){const h=["--files","--hidden","--no-require-git","--no-config","--color=never"],p=function(e=process.env){const t=e.CURSOR_RIPWALK_THREADS?.trim();if(void 0!==t&&""!==t){const e=Number(t);if(Number.isInteger(e)&&e>=0)return 0===e?void 0:e}return Math.min(2,(0,o.availableParallelism)())}();void 0!==p&&h.push("--threads",String(p)),u&&h.push("--follow"),l&&h.push("--no-ignore-vcs"),i&&h.push("--case-sensitive");for(const e of n)h.push("--iglob",e);for(const e of s)h.push("--iglob",`!${e}`);const f=r.length>0?["--",...r]:[];let m,g=!1;const w=new Promise((e=>{m=e}));return{lines:async function*(){const r={stack:[],error:void 0,hasError:!1};try{const n=[];for(const e of await pa(a))n.push("--cursor-ignore",e);const o=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,function(e,t,r,n){const o=(0,Oo.spawnInSandbox)((0,Oo.Ko)(),t,{cwd:r},n),s=[];o.stderr?.on("data",(e=>{s.push(e)}));const i=new Promise(((e,t)=>{o.on("error",t),o.on("close",(t=>e(t??0)))}));if(i.catch((()=>{})),!o.stdout)throw new Error("No stdout from ripgrep process");const a=ma(e.signal);return{stdout:o.stdout,processExit:i,stderr:()=>Buffer.concat(s).toString(),aborted:a.aborted,[Symbol.dispose](){a[Symbol.dispose](),o.kill()}}}(e,[...h,...n,...f],t,c),!1);let s=0;const i=async function*(e){const t=new ia.StringDecoder("utf8");let r="";for await(const n of e){r+=t.write(n);const e=r.split("\n");r=e.pop()??"",e.length>0&&(yield e)}r+=t.end(),r&&(yield[r])}(o.stdout)[Symbol.asyncIterator]();e:for(;;){const t=await Promise.race([i.next(),o.aborted]);if("aborted"===t){g=!0,m(!0);break}if(t.done)break;for(const r of t.value){if(e.signal.aborted){g=!0,m(!0);break e}s++,yield r}}if(s>0);else if(!g){const e=await o.processExit;if(0!==e&&1!==e){const t=o.stderr();throw new Error(`Ripgrep failed (exit ${e}) with no results${t?`: ${t}`:""}`)}}g||m(!1)}catch(e){r.error=e,r.hasError=!0}finally{fa(r)}}(),didTimeout:w}}var wa=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});let ya;function va(e=process.env){if(void 0!==ya)return ya;const t=e.CURSOR_RIPWALK_CACHE_TTL_MS?.trim();if(void 0!==t&&""!==t){const e=Number(t);if(Number.isFinite(e)&&e>0)return e}return 2e4}function ba({root:e,searchPaths:t=[],includeGlobs:r=[],excludeGlobs:n=[],caseSensitive:o=!1,cursorIgnoreFiles:s=[],sandboxPolicy:i={type:"insecure_none"},noIgnoreVcs:a=!1,followSymlinks:c=!1}){return JSON.stringify({root:e,searchPaths:t,includeGlobs:r,excludeGlobs:n,caseSensitive:o,cursorIgnoreFiles:s,sandboxPolicy:i,noIgnoreVcs:a,followSymlinks:c})}class Sa{constructor(e=()=>va()){this.cache=new sa({ttlMs:e})}get size(){return this.cache.size}clear(){this.cache.clear()}delete(e){this.cache.delete(ba(e))}walk(e,t){const r=ba(t);let n,o=!1,s=!1;const i=new Promise((e=>{n=e})),a=e=>{s||(s=!0,n(e))};return{lines:async function*(){const n=this.cache.get(r);if(void 0!==n){const t={stack:[],error:void 0,hasError:!1};try{const s=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,ma(e.signal),!1),i=await Promise.race([n.linesPromise.then((e=>({type:"lines",lines:e})),(e=>({type:"error",error:e}))),s.aborted.then((()=>({type:"aborted"})))]);if("aborted"===i.type)return o=!0,void a(!0);if("lines"===i.type)return a(!1),void(yield*i.lines);this.cache.get(r)===n&&this.cache.delete(r)}catch(e){t.error=e,t.hasError=!0}finally{wa(t)}}let s,i;const c={linesPromise:new Promise(((e,t)=>{s=e,i=t}))};c.linesPromise.catch((()=>{})),this.cache.set(r,c);const l=[];let u,d=!1;try{const r=ga(e,t);for await(const e of r.lines)l.push(e),yield e;if(await r.didTimeout)return o=!0,u=new Error("Ripwalk aborted before cacheable result was available"),void a(!0);d=!0}catch(e){throw u=e,e}finally{d?s?.(l):(this.cache.get(r)===c&&this.cache.delete(r),i?.(u??new Error("Ripwalk terminated before cacheable result was available"))),o||a(!1)}}.bind(this)(),didTimeout:i}}}const ka=16777216,_a=new Set([32,9,10,13]),Ca="a path through /proc or /dev/fd",Ea={kind:"none"},xa={kind:"stop"};function Pa(e,t){return{kind:"refused",refused:{name:e,reason:t}}}async function Ra(e){const t=await async function(e){if(void 0===await(0,Co.lstat)(e).catch((()=>{})))return Ea;if(await Aa(Buffer.from(e)))return Pa(".git",Ca);const t=await(0,Co.stat)(e).catch((()=>{}));if(void 0===t)return Ea;if(!t.isFile())return Ia(e);const r=await Oa(e,{whole:1048576});if("not-regular"===r.kind)return Pa(".git","not a regular file");if("bytes"!==r.kind)return xa;const n=Buffer.from("gitdir: "),o=ja(r.bytes);if(!o.subarray(0,n.length).equals(n)||o.length<=n.length)return xa;const i=La({dir:(0,s.dirname)(e),target:Ua(o.subarray(n.length))});if(await Aa(i))return Pa(".git",Ca);const a=await Ia(i);return"none"===a.kind?xa:a}(Na(e,".git").toString());return"none"!==t.kind?t:Ia(e)}async function Ia(e){const t=await async function(e){const t=await(0,Co.lstat)(e).catch((()=>{}));if(void 0===t||t.isDirectory())return Ea;if(t.isSymbolicLink()){const t=await(0,Co.readlink)(e,{encoding:"buffer"}).catch((()=>{}));return"refs/"===t?.subarray(0,5).toString("latin1")?"valid":Ea}if(!t.isFile())return Pa("HEAD","not a regular file");const r=await Oa(e,{prefix:255});if("not-regular"===r.kind)return Pa("HEAD","not a regular file");if("bytes"!==r.kind)return Ea;const n=Ua(r.bytes.subarray(0,255)).toString("latin1");if(n.startsWith("ref:")){let e=4;for(;e{}))){if(await Aa(n))return Pa("commondir",Ca);const t=await Oa(n,{whole:ka});switch(t.kind){case"bytes":{if(0===t.bytes.length)return xa;const n=La({dir:e,target:Ua(ja(t.bytes))});if(await Aa(n))return Pa("commondir",Ca);const o=await(0,Co.realpath)(n,{encoding:"buffer"}).catch((()=>{}));if(void 0===o)return Ea;r=o;break}case"too-large":return Pa("commondir","over the size cap");case"not-regular":return Pa("commondir","not a regular file");case"directory":case"unreadable":return xa;default:throw new Error(`unhandled read ${String(t)}`)}}for(const e of["objects","refs"]){const t=Na(r,e);if(await Aa(t))return Pa(e,Ca);if(!await Fa(t))return Ea}return{kind:"repository",gitDir:e,commonDir:r}}async function Ta({gitDir:e,commonDir:t}){const r=[["HEAD",Na(e,"HEAD")],["config.worktree",Na(e,"config.worktree")],["config",Na(t,"config")],["info/exclude",Na(Na(t,"info"),"exclude")]];for(const[e,t]of r){if(await Aa(t))return{name:e,reason:Ca};const r=await(0,Co.stat)(t).catch((()=>{}));if(void 0!==r&&!r.isDirectory()&&!await Da(r)){if(!r.isFile())return{name:e,reason:"not a regular file"};if(r.size>ka)return{name:e,reason:"over the size cap"}}}}async function Aa(e){if("win32"===process.platform)return!1;const t=$a(e.toString("latin1")).reverse();let r="/",n=0;for(let e=t.pop();void 0!==e;e=t.pop()){if(".."===e){r=(0,s.dirname)(r);continue}const o=(0,s.join)(r,e),i="darwin"===process.platform?o.toLowerCase():o;if(["/proc","/dev/fd"].some((e=>i===e||i.startsWith(`${e}/`))))return!0;const a=await(0,Co.readlink)(Buffer.from(o,"latin1"),{encoding:"buffer"}).catch((()=>{}));if(void 0===a){r=o;continue}if(++n>40)return!1;const c=a.toString("latin1");(0,s.isAbsolute)(c)&&(r="/"),t.push(...$a(c).reverse())}return!1}function $a(e){return e.split("/").filter((e=>""!==e&&"."!==e))}let Ma;async function Da(e){if(!e.isCharacterDevice())return!1;Ma??=(0,Co.stat)("/dev/null").catch((()=>{}));const t=await Ma;return void 0!==t&&e.dev===t.dev&&e.ino===t.ino}async function Oa(e,t){const r=xo.constants.O_RDONLY|(xo.constants.O_NONBLOCK??0)|(xo.constants.O_NOCTTY??0),n=await(0,Co.open)(e,r).catch((()=>{}));if(void 0===n)return{kind:"unreadable"};try{const e=await n.stat();if(e.isDirectory())return{kind:"directory"};if(!e.isFile())return{kind:"not-regular"};if("whole"in t&&e.size>t.whole)return{kind:"too-large"};const r="whole"in t?t.whole:t.prefix,o=Buffer.alloc(Math.min(r+1,e.size+1));let s=0;for(;st.whole?{kind:"too-large"}:{kind:"bytes",bytes:o.subarray(0,s)}}catch{return{kind:"unreadable"}}finally{await n.close().catch((()=>{}))}}function Fa(e){return(0,Co.access)(e,xo.constants.X_OK).then((()=>!0),(()=>!1))}function Na(e,t){const r=Buffer.isBuffer(e)?e:Buffer.from(e),n=r.toString("latin1").endsWith(s.sep)?"":s.sep;return Buffer.concat([r,Buffer.from(`${n}${t}`)])}function La({dir:e,target:t}){return(0,s.isAbsolute)(t.toString("latin1"))?t:Buffer.concat([Na(e,""),t])}function ja(e){let t=e.length;for(;t>0&&(10===e[t-1]||13===e[t-1]);)t--;return e.subarray(0,t)}function Ua(e){const t=e.indexOf(0);return-1===t?e:e.subarray(0,t)}const Ba=[{stage:"prod",gitHost:"origin.cursor.com",gitCdnHost:"gitcdn.origin.cursor.com",cloneKitS3Host:"git-forge-prod-bundles.s3.us-east-1.amazonaws.com",rawUserContentHost:"raw.cursorusercontent.com",apiHost:"api.origin.cursor.com",internalHost:"origin-prod.internal.cursor.com"},{stage:"staging",gitHost:"origin-staging.cursor.com",gitCdnHost:"gitcdn.origin-staging.cursor.com",cloneKitS3Host:"git-forge-staging-bundles.s3.us-east-1.amazonaws.com",rawUserContentHost:"raw.staging.cursorusercontent.com",apiHost:"api.origin-staging.cursor.com",internalHost:"origin-staging.internal.cursor.com"},{stage:"test",gitHost:"origin-test.cursor.com",gitCdnHost:"gitcdn.origin-test.cursor.com",cloneKitS3Host:"git-forge-test-bundles.s3.us-east-1.amazonaws.com",rawUserContentHost:"raw.test.cursorusercontent.com",apiHost:"api.origin-test.cursor.com",internalHost:"origin-test.internal.cursor.com"}];function Wa(e){let t=e.length;for(;t>0&&47===e.charCodeAt(t-1);)t--;const r=e.slice(0,t).replace(/\.git$/i,"");return r&&"/"!==r?r.startsWith("/")?r:`/${r}`:""}function Ha(e,t){const r=Wa(t);return r?`${e}${r}`.toLowerCase():""}new Map(Ba.map((e=>[e.gitHost,e.apiHost]))),new Map(Ba.map((e=>[e.gitHost,e.gitCdnHost]))),new Map(Ba.map((e=>[e.gitHost,e.cloneKitS3Host]))),new Map(Ba.map((e=>[e.gitHost,e.rawUserContentHost]))),new Map(Ba.map((e=>[e.apiHost,e.gitHost]))),new Map(Ba.map((e=>[e.apiHost,e.internalHost])));const qa=new Map;function za(e){const t=qa.get(e);if(void 0!==t)return t;const r=function(e){const t=e.trim();if(!t)return"";try{const e=function(e){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(e))return e;const t=`https://${e}`;try{return new URL(t),t}catch{const r=e.match(/^([^@/\s]+@)?([^:/\s]+):(.+)$/);return r?`ssh://${r[1]??""}${r[2]}/${r[3]}`:t}}(t),r=new URL(e);return Ha(r.hostname,r.pathname)}catch{const e=t.replace(/^(?:https?|ssh|git):\/\//i,""),r=e.indexOf("/"),n=-1===r?e:e.slice(0,r),o=-1===r?"":e.slice(r);return Ha(n.includes("@")?n.slice(n.lastIndexOf("@")+1):n,o)}}(e);return qa.size>=16384&&qa.clear(),qa.set(e,r),r}function Ga(e){return/^origin(-[a-z0-9]+)?\.cursor\.com$/i.test(e)}(function(e){const t=Ba.find((t=>t.stage===e));if(void 0===t)throw new Error(`unknown Origin stage: ${e}`);return t})("prod").gitHost;const Va=new Map;function Ka(e){if(void 0===e)return;if(Va.has(e))return Va.get(e);const t=function(e){const t=e?function(e){let t=e.trim();if(""!==t){t.startsWith("git@")?t=`https://${t.slice(4).replace(":","/")}`:/^[a-z][a-z0-9+.-]*:\/\//i.test(t)&&!/^https?:\/\//i.test(t)?t=t.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"https://"):/^https?:\/\//i.test(t)||(t=`https://${t}`);try{return new URL(t)}catch{return}}}(e):void 0;if(void 0===t||!Ga(t.hostname))return;const r=Wa(t.pathname).split("/").filter(Boolean),n=3===r.length&&"git"===r[0]?.toLowerCase(),o=2===r.length&&"git"!==r[0]?.toLowerCase();if(!n&&!o)return;const s=n?r[1]:r[0],i=n?r[2]:r[1];return s&&i?Object.freeze({hostname:t.hostname,owner:s,name:i}):void 0}(e);return Va.size>=16384&&Va.clear(),Va.set(e,t),t}function Ja(e){return void 0!==function(e){const t=Ka(e);return void 0===t?void 0:{owner:t.owner,name:t.name}}(e)}new Set(["github.com","www.github.com"]),new RegExp("^tmp-[0-9a-f]{16}$");const Za=(0,l.h)("local-exec:git-root"),Xa=new WeakMap,Qa=new Map;function Ya(e,t,r){return ec(e,t,r).then((e=>"repository"===e.kind?e.root:null))}function ec(e,t,r){const n=performance.now();let o=Xa.get(t);void 0===o&&(o=new Map,Xa.set(t,o));const s=o.get(r);if(void 0!==s&&tc(s,n))return s.result;for(const[e,t]of o)tc(t,n)||o.delete(e);const i=t.guardedRootLookup,a=void 0===i?{result:oc(e,t,r,void 0),windowStart:n}:{result:rc(e,t,r,i.timeoutMs),windowStart:void 0};return void 0===a.windowStart&&a.result.then((()=>{a.windowStart=performance.now()})),o.set(r,a),a.result}function tc(e,t){return void 0===e.windowStart||t-e.windowStart<5e3}async function rc(e,t,r,n){const o=new AbortController,i=performance.now()+n,a=await(0,Or.wj)(async function({ctx:e,gitExecutor:t,startPath:r,deadline:n,settled:o}){const i=await function(e){let t=Qa.get(e);if(void 0===t){t=async function(e){const t=await(0,Co.realpath)(e).catch((()=>{}));if(void 0===t)return;const r=function(){const e=(process.env.GIT_DISCOVERY_ACROSS_FILESYSTEM??"").toLowerCase();return!["","0","false","no","off"].includes(e)}()?void 0:(await(0,Co.stat)(t).catch((()=>{})))?.dev;for(let e=t;;){const t=await Ra(e);switch(t.kind){case"refused":return t.refused;case"stop":return;case"repository":return Ta(t);case"none":break;default:throw new Error(`unhandled probe ${String(t)}`)}const n=(0,s.dirname)(e);if(n===e||void 0!==r&&(await(0,Co.stat)(n).catch((()=>{})))?.dev!==r)return;e=n}}(e),Qa.set(e,t);const r=()=>{Qa.delete(e)};t.then(r,r)}return t}(r);if(o.aborted)return{kind:"unknown",reason:"timed-out"};if(void 0!==i)return Za.warn(e,"findGitRoot: not starting git; its answer is unknown",{adminFile:i.name,reason:i.reason}),{kind:"unknown",reason:"refused"};const a=Math.ceil(n-performance.now());return a<=0?{kind:"unknown",reason:"timed-out"}:oc(e,t,r,a)}({ctx:e,gitExecutor:t,startPath:r,deadline:i,settled:o.signal}),n).catch((t=>t instanceof Or.MU?{kind:"unknown",reason:"timed-out"}:(Za.warn(e,"findGitRoot: the admin file check failed; not starting git",{code:nc(t)}),{kind:"unknown",reason:"refused"}))).finally((()=>{o.abort()}));return"unknown"===a.kind&&"timed-out"===a.reason&&Za.warn(e,"findGitRoot: the lookup ran past its bound; its answer is unknown",{timeoutMs:n}),a}function nc(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:void 0}async function oc(e,t,r,n){try{return{kind:"repository",root:(await t.exec(e,r,["rev-parse","--show-toplevel"],{...void 0===n?{}:{timeout:n},caller:"findGitRoot"})).stdout.trim()}}catch(e){return void 0!==n&&function(e){return"object"==typeof e&&null!==e&&"killed"in e&&!0===e.killed}(e)?{kind:"unknown",reason:"timed-out"}:{kind:"none"}}}async function sc(e,t,r){try{return(await t.exec(e,r,["config","--get","remote.origin.url"],{caller:"getGitRemoteUrl"})).stdout.trim()}catch{return}}function ic(e){const t=e.trim();if(""===t)return t;try{const e=new URL(t);return""===e.host?cc(t)??e.toString():(e.username="",e.password="",e.toString())}catch{return function(e){const t=e.replace(/^[\u0000-\u0020]+|[\u0000-\u0020]+$/g,"").replace(/[\t\n\r]/g,""),r=t.indexOf(":"),n=t.slice(0,r);if(r<0||!/^[A-Za-z][A-Za-z0-9+.-]*$/.test(n))return;const o=t.slice(r+1),s=ac.has(n.toLowerCase());let i;if(s)i=o.replace(/^[/\\]+/,"");else{if(!o.startsWith("//"))return;i=o.slice(2)}const a=i.search(s?/[/?#\\]/:/[/?#]/),c=a<0?i.length:a,l=i.slice(0,c),u=l.lastIndexOf("@");return u<0?void 0:`${t.slice(0,t.length-i.length)}${l.slice(u+1)}${i.slice(c)}`}(t)??cc(t)??t}}const ac=new Set(["ftp","file","http","https","ws","wss"]);function cc(e){const t=e.indexOf("/"),r=t<0?e:e.slice(0,t),n=r.indexOf(":"),o=r.lastIndexOf("@",r.lastIndexOf(":"));if(!(n<0||o<0||r.indexOf("@")`/${s.posix.relative(e,t)}`))}var dc=r("../../node_modules/.pnpm/picomatch@4.0.5/node_modules/picomatch/index.js");function hc(e,t){return e.some((e=>{return"*"===e.url.trim()?(e.patterns??[]).some((e=>mc(e.pattern,t))):!((r=e.url).includes("://")||r.includes("github.com")||r.includes("gitlab.com")||r.includes("bitbucket.org")||r.includes("@"))&&mc(e.url,t);var r}))}function pc(e,t,r){return fc(e.url,t)&&(e.patterns??[]).some((e=>mc(e.pattern,r)))}function fc(e,t){return e.includes("*")?"*"===e.trim()||function(e,t){const r=e.trim();return!!mc(r,t)||!!r.startsWith("*/")&&mc(`**/${r.slice(2)}`,t)}(bc(e),bc(t)):bc(e)===bc(t)}function mc(e,t){const r=e.trim();return!("."!==t&&""!==t||"**"!==r&&"**/*"!==r)||function(e){const t=yc.get(e);if(void 0!==t)return t;let r;try{const t=dc(e,{dot:!0});r=r=>{try{return t(r)}catch{return e===r}}}catch{r=t=>e===t}return vc(yc,gc,e,r)}(r)(t)}const gc=2048,wc=new Map,yc=new Map;function vc(e,t,r,n){if(e.set(r,n),e.size>t){const t=e.keys().next().value;void 0!==t&&e.delete(t)}return n}function bc(e){const t=wc.get(e);if(void 0!==t)return t;const r=(function(e){const t=Ka(e);if(void 0!==t)return`${t.hostname}/git/${t.owner}/${t.name}`.toLowerCase()}(n=e)??za(n))||function(e){let t=e.trim();t.startsWith("git@")&&(t=`https://${t.slice(4).replace(":","/")}`),/^[a-z][a-z0-9+.-]*:\/\//i.test(t)&&!/^https?:\/\//i.test(t)&&(t=t.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"https://")),/^https?:\/\//i.test(t)||(t=`https://${t}`);try{const e=new URL(t),r=e.pathname.replace(/\/+$/,"").replace(/\.git$/i,"").replace(/\/+$/,"");return e.hostname+r}catch{return t=t.replace(/^https?:\/\//i,""),t=t.replace(/[?#].*$/,""),t=t.replace(/\/+$/,""),t=t.replace(/\.git$/i,""),t=t.replace(/\/+$/,""),t}}(e).toLowerCase();var n;return vc(wc,2048,e,r)}function Sc(e){if("object"==typeof e&&null!==e&&"code"in e){const t=e.code;if("string"==typeof t)return t}}function kc(e){if(e instanceof Error)return e.message;if("object"==typeof e&&null!==e&&"message"in e){const t=e.message;if("string"==typeof t)return t}return""}(0,_s.J)((function(){wc.clear(),yc.clear()}));const _c=[".gitignore",".cursorignore"];async function Cc(e){if(!(0,s.isAbsolute)(e))return null;const t=await(0,Yo.DN)(e);return null===t?null:t}function Ec(e,t){if(!e||0===e.length)return[...t];const r=new Set(e);for(const e of t)r.has(e)&&r.delete(e),r.add(e);return[...r]}class xc{constructor(e,t,r,n={}){this.disposeRequested=!1,this.initIgnoreService=()=>Ic.init((0,y.q6)(),e,r??[process.cwd()],t),!0!==n.deferInit&&this.ensureStarted()}ensureStarted(){if(void 0===this.ignoreServicePromise){if(this.disposeRequested)return Promise.reject(new Error("LazyIgnoreService was disposed before its ignore-file scan started"));this.ignoreServicePromise=this.initIgnoreService()}return this.ignoreServicePromise}isIgnoredByAny(e){return this.ensureStarted().then((t=>t.isIgnoredByAny(e)))}isGitIgnored(e){return this.ensureStarted().then((t=>t.isGitIgnored(e)))}isCursorIgnored(e,t){return this.ensureStarted().then((r=>r.isCursorIgnored(e,t)))}isRepoBlocked(e){return this.ensureStarted().then((t=>t.isRepoBlocked(e)))}listCursorIgnoreFilesByRoot(e){return this.ensureStarted().then((t=>t.listCursorIgnoreFilesByRoot(e)))}getCursorIgnoreMapping(){return this.ensureStarted().then((e=>e.getCursorIgnoreMapping()))}getShellSandboxIgnoreMapping(e){return this.ensureStarted().then((t=>t.getShellSandboxIgnoreMapping(e)))}getGitIgnoreMapping(){return this.ensureStarted().then((e=>e.getGitIgnoreMapping()))}getRepoBlockExcludeGlobs(e){return this.ensureStarted().then((t=>t.getRepoBlockExcludeGlobs(e)))}handleCursorIgnoreCreated(e){return this.ensureStarted().then((t=>t.handleCursorIgnoreCreated(e)))}handleCursorIgnoreChanged(e){return this.ensureStarted().then((t=>t.handleCursorIgnoreChanged(e)))}handleCursorIgnoreDeleted(e){return this.ensureStarted().then((t=>t.handleCursorIgnoreDeleted(e)))}dispose(){this.disposeRequested||(this.disposeRequested=!0,this.ignoreServicePromise?.then((e=>{e.dispose()})).catch((()=>{})))}}const Pc=Math.min(8,Math.max(1,Math.floor(o.default.availableParallelism()/2)));class Rc{constructor(e){this.maxLookups=e,this.instances=new Map,this.lookups=0}get(e,t){this.lookups>=this.maxLookups&&this.clear(),this.lookups++;let r=this.instances.get(e);return void 0===r&&(r=oa().add(t),this.instances.set(e,r)),r}delete(e){this.instances.delete(e)}clear(){this.instances.clear(),this.lookups=0}}class Ic{constructor(e,t,r,n,o,s){this.gitExecutor=e,this.gitIgnoreMapping=t,this.cursorIgnoreMapping=r,this.teamSettingsService=n,this.rootDirectories=o,this.scanEnvironment=s,this.gitIgnoreCache=new js.q({max:2e3}),this.cursorIgnoreCache=new js.q({max:2e3}),this.gitRootCache=new js.q({max:1e4}),this.gitRemoteUrlCache=new js.q({max:200}),this.hasGitDirCache=new js.q({max:1e3}),this.gitParsedIgnoreCache=new Rc(1e4),this.cursorParsedIgnoreCache=new Rc(1e4),this.ignoreMappingsHaveEntries=!1,this.directoryWalkPlacementCache=new js.q({max:1e4}),this.extraRootCursorIgnoreCache=new js.q({max:32}),this.extraGitRepoMappingCache=new js.q({max:32}),this.unwalkedFolders=o.flatMap((e=>Hs(e,s)))}static getRipwalkCache(){return Ic.ripwalkCache??=new Sa,Ic.ripwalkCache}hasNoWorkspaceFolders(){return!this.ignoreMappingsHaveEntries&&(this.ignoreMappingsHaveEntries=Object.keys(this.gitIgnoreMapping).length>0||Object.keys(this.cursorIgnoreMapping).length>0,!this.ignoreMappingsHaveEntries)}async resolveLookupRoot(e){return await(0,Yo.DN)(e)??(0,Yo.o1)(e)}static async init(e,t,r,n,s={platform:process.platform,homeDirectory:o.default.homedir()}){const i={...s,homeDirectory:await(0,Yo.DN)(s.homeDirectory)??s.homeDirectory},a=await(0,Or.PH)(r,(async e=>{const t=await(0,Yo.DN)(e);return null===t?(console.warn(`[IgnoreService] Cannot resolve workspace root, using as-is: ${e}`),e):t})),c={},l={},u=await(0,Or.PH)(a,(async r=>({root:r,lookup:await ec(e,t,r)}))),d=u.map((({root:e,lookup:t})=>"none"===t.kind?null:"unknown"===t.kind||Hs(t.root,i).length>0?e:t.root)).filter((e=>null!==e)),h=u.filter((({lookup:e})=>"unknown"===e.kind)).map((({root:e})=>(0,Yo.o1)(e)));return d.length>0&&await Promise.all([Ic.initializeIgnoreMapping({rootDirectories:d,ignoreFileName:".gitignore",mapping:c,scanEnvironment:i,unknownRoots:h}),Ic.initializeIgnoreMapping({rootDirectories:a,ignoreFileName:".cursorignore",mapping:l,scanEnvironment:i,unknownRoots:h})]),new Ic(t,c,l,n,a,i)}static async preloadHierarchy(e,t,r,n){let o=(0,Yo.o1)(e);const i=(0,s.parse)(o).root;for(;o!==i;){if(n?.has(o)){const e=(0,s.dirname)(o);if(e===o)break;o=e;continue}void 0===r[o]&&await Ic.handleHierarchyIgnore(o,t,r),n?.add(o);const e=(0,s.dirname)(o);if(e===o)break;o=e}}static async handleHierarchyIgnore(e,t,r){const n=(0,s.join)(e,t);try{await(0,Co.access)(n,Co.default.constants.F_OK);const t=await ji(n),o=Ic.parseIgnoreRules(t);r[e]=o}catch(o){"ENOENT"===Sc(o)||console.error(`Error reading ${t} file at ${n}:`,o),r[e]=[]}}static async initializeIgnoreMapping({rootDirectories:e,ignoreFileName:t,mapping:r,scanEnvironment:n,unknownRoots:o}){try{const i=Ic.deduplicateRootDirectories(e),a=await Ic.promiseQueue.enqueueList(i,(e=>Ic.findFilesWithRipgrep({rootDirectory:e,fileName:t,scanEnvironment:n,noIgnoreVcs:o.some((t=>(0,Yo.ZU)({basePath:e,targetPath:t})))}))),c=Array.from(a.values()).flat();await Promise.all(c.map((async e=>{try{const t=await ji(e),n=Ic.parseIgnoreRules(t),o=(0,s.dirname)(e);r[o]=n}catch(r){console.error(`Error processing ${t} file at ${e}:`,r)}})));const l=new Set;for(const e of i)await Ic.preloadHierarchy(e,t,r,l)}catch(e){console.error(`Error initializing ignore mapping for ${t}:`,e)}}static async findFilesWithRipgrep({rootDirectory:e,fileName:t,scanEnvironment:r,noIgnoreVcs:n}){const o=(0,y.q6)(),i=[],a={root:e,includeGlobs:_c.map((e=>`**/${e}`)),excludeGlobs:[...lc,...uc(e,r)],noIgnoreVcs:n,source:"ignore_scan"},c=Ic.getRipwalkCache().walk(o,a);for await(const r of c.lines)(0,s.basename)(r)===t&&i.push((0,s.join)(e,r));return i}async handleManualLookupWhenNoWorkspaceDirs(e,t,r){const n={};let o=(0,s.dirname)(e);const i=(0,s.parse)(o).root;for(;;){let e=r?.get(o);if(void 0===e){try{e=Ic.parseIgnoreRules(await ji((0,s.join)(o,t)))}catch{e=[]}r?.set(o,e)}if(e.length>0&&(n[o]=e),o===i)break;o=(0,s.dirname)(o)}return this.testIgnored(e,n,((e,t)=>oa().add(t)))}async isIgnoredByAny(e){const[t,r,n]=await Promise.all([this.checkGitIgnored(e),this.checkCursorIgnored(e),this.checkRepoBlocked(e)]);return t||r||n}async isGitIgnored(e){return this.checkGitIgnored(e)}async isCursorIgnored(e,t){return this.checkCursorIgnored(e,t)}async checkGitIgnored(e){if(this.hasNoWorkspaceFolders())return this.handleManualLookupWhenNoWorkspaceDirs(e,".gitignore");const t=this.gitIgnoreCache.get(e);if(void 0!==t)return t;await this.populateHierarchyIfNeeded(e,".gitignore",this.gitIgnoreMapping);const r=this.checkIgnored(e,this.gitIgnoreMapping,this.gitParsedIgnoreCache);return this.gitIgnoreCache.set(e,r),r}async checkCursorIgnored(e,t){if(this.hasNoWorkspaceFolders())return this.handleManualLookupWhenNoWorkspaceDirs(e,".cursorignore",t);const r=this.cursorIgnoreCache.get(e);if(void 0!==r)return r;await this.populateHierarchyIfNeeded(e,".cursorignore",this.cursorIgnoreMapping);const n=this.checkIgnored(e,this.cursorIgnoreMapping,this.cursorParsedIgnoreCache);return this.cursorIgnoreCache.set(e,n),n}isInUnwalkedFolder(e){const t="darwin"===this.scanEnvironment.platform,r=t?e.toLowerCase():e;return this.unwalkedFolders.some((e=>(0,Yo.ZU)({basePath:t?e.toLowerCase():e,targetPath:r})))}directoryWalkPlacement(e){const t=this.directoryWalkPlacementCache.get(e);if(void 0!==t)return t;let r;return r=this.isInUnwalkedFolder(e)?"unwalked":this.rootDirectories.some((t=>(0,Yo.ZU)({basePath:t,targetPath:e})))?"walked":"outside",this.directoryWalkPlacementCache.set(e,r),r}async populateHierarchyIfNeeded(e,t,r){let n=(0,s.dirname)((0,Yo.o1)(e));const o=[],i=(0,s.parse)(n).root;for(;n!==i;){const e=this.directoryWalkPlacement(n),t="unwalked"===e;if("walked"===e){n=(0,s.dirname)(n);continue}if(void 0===r[n])o.push(n);else if(!t)break;const i=(0,s.dirname)(n);if(i===n)break;n=i}o.length>0&&(await Ic.promiseQueue.enqueueList(o,(e=>Ic.handleHierarchyIgnore(e,t,r))),".gitignore"===t?this.gitIgnoreCache.clear():this.cursorIgnoreCache.clear())}testIgnored(e,t,r){for(const[n,o]of Object.entries(t)){if(0===o.length)continue;if(!(0,Yo.ZU)({basePath:n,targetPath:e}))continue;const t=(0,s.relative)(n,e);if(""===t)continue;const i=r(n,o),a=(0,Yo.oL)(t),c=i.test(a);if(c.ignored&&!c.unignored)return!0;const l=i.test(`${a}/`);if(l.ignored&&!l.unignored)return!0}return!1}checkIgnored(e,t,r){return this.testIgnored(e,t,((e,t)=>r.get(e,t)))}async listCursorIgnoreFilesByRoot(e){const t=await this.resolveLookupRoot(e),r=[];for(const[e,n]of Object.entries(this.cursorIgnoreMapping)){if(0===n.length)continue;if(!(0,Yo.ZU)({basePath:t,targetPath:e}))continue;const o=(0,s.join)(e,".cursorignore");try{await(0,Co.access)(o),r.push(o)}catch{}}return r}async getCursorIgnoreMapping(){return{...this.cursorIgnoreMapping}}async getShellSandboxIgnoreMapping(e=[]){const t={...this.cursorIgnoreMapping},r=[];for(const t of e){if((0,qs.$f)(t))continue;const e=await(0,Yo.DN)(t);if(null===e||".git"===(0,s.basename)(e)||this.rootDirectories.some((t=>(0,Yo.ZU)({basePath:t,targetPath:e})))||r.includes(e))continue;const n=await Co.default.stat(e).catch((e=>{if(void 0===Sc(e))throw e}));n?.isDirectory()&&r.push(e)}const n=Date.now();for(const e of r){let r=this.extraRootCursorIgnoreCache.get(e);if(void 0===r||r.expiresAt<=n){const t={},o=void 0===this.gitExecutor.guardedRootLookup?void 0:await ec((0,y.q6)(),this.gitExecutor,e);await Ic.initializeIgnoreMapping({rootDirectories:[e],ignoreFileName:".cursorignore",mapping:t,scanEnvironment:this.scanEnvironment,unknownRoots:"unknown"===o?.kind?[e]:[]}),r={mapping:t,expiresAt:n+va()},this.extraRootCursorIgnoreCache.set(e,r)}for(const[e,n]of Object.entries(r.mapping))t[e]=Ec(t[e],n)}for(const e of[...this.rootDirectories,...r]){const r=await this.getRepoBlockExcludeGlobs(e);0!==r.length&&(t[e]=Ec(t[e],r))}return t}async getGitIgnoreMapping(){return{...this.gitIgnoreMapping}}static deduplicateRootDirectories(e){const t=[...e.map((e=>(0,Yo.o1)(e)))].sort(((e,t)=>e.length-t.length)),r=[];for(const e of t)r.some((t=>e.startsWith(`${t}/`)||e.startsWith(`${t}\\`)))||r.push(e);return r}static parseIgnoreRules(e){return e.split("\n").map((e=>e.replace(/\r$/,"").trimStart())).filter((e=>""!==e&&!e.startsWith("#")))}clearCaches(){this.gitIgnoreCache.clear(),this.cursorIgnoreCache.clear(),this.gitRootCache.clear(),this.gitRemoteUrlCache.clear(),this.hasGitDirCache.clear(),this.gitParsedIgnoreCache.clear(),this.cursorParsedIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear(),this.extraGitRepoMappingCache.clear()}dispose(){this.gitIgnoreCache=new js.q({max:1}),this.cursorIgnoreCache=new js.q({max:1}),this.gitRootCache=new js.q({max:1}),this.gitRemoteUrlCache=new js.q({max:1}),this.hasGitDirCache=new js.q({max:1}),this.directoryWalkPlacementCache=new js.q({max:1}),this.extraRootCursorIgnoreCache=new js.q({max:1}),this.extraGitRepoMappingCache=new js.q({max:1}),this.gitParsedIgnoreCache.clear(),this.cursorParsedIgnoreCache.clear(),this.gitRepoMappingPromise=void 0}async handleCursorIgnoreCreated(e){const t=(0,s.dirname)(e),r=await ji(e),n=Ic.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear()}async handleCursorIgnoreChanged(e){const t=(0,s.dirname)(e),r=await ji(e),n=Ic.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear()}handleCursorIgnoreDeleted(e){const t=(0,s.dirname)(e);this.cursorIgnoreMapping[t]=[],this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear()}async findGitRootsForFile(e){const t=(0,Yo.o1)(e),r=this.gitRootCache.get(t);if(void 0!==r)return r;const n=[],o=[],i=[];let a=t;const c=(0,s.parse)(a).root;for(;a!==c;){o.push(a),void 0===this.hasGitDirCache.get(a)&&i.push(a);const e=(0,s.dirname)(a);if(e===a)break;a=e}if(i.length>0){const e=i.map((e=>(0,Co.access)((0,s.join)(e,".git"),Co.default.constants.F_OK).then((()=>[e,!0])).catch((()=>[e,!1])))),t=await Promise.all(e);for(const[e,r]of t)this.hasGitDirCache.set(e,r)}for(const e of o)!0===this.hasGitDirCache.get(e)&&n.push(e);return this.gitRootCache.set(t,n),n}async isRepoBlocked(e){return this.checkRepoBlocked(e)}async checkRepoBlocked(e){const t=function(e){if(void 0===e)return;const t=e.repos??[],r=e.disableLocalExecAllowlistEnforcement?[]:e.allowedRepos??[];return 0===t.length&&0===r.length?void 0:{blocked:t,allowed:r}}(await(this.teamSettingsService?.getTeamRepos()));if(void 0===t)return!1;const r=await this.findGitRootsForFile(e);if(0===r.length)return 0!==t.allowed.length&&!(0,Yo.ZU)({basePath:await this.getCursorDataDir(),targetPath:e})&&function(e,t){return 0!==e.allowed.length&&!hc(e.allowed,t)}(t,this.getWorkspaceRelativePath(e));const n=[];for(const t of r)n.push({url:await this.remoteUrlOf(t),relativePath:(0,s.relative)(t,e)||"."});return function(e,t){let r=0===e.allowed.length,n=!1;for(const{url:o,relativePath:s}of t)if(void 0!==o){if(e.blocked.some((e=>pc(e,o,s))))return!0;e.allowed.length>0&&!n&&(n=!0,r=e.allowed.some((e=>pc(e,o,s))))}else 0;return!r}(t,n)}async remoteUrlOf(e){if(this.gitRemoteUrlCache.has(e))return this.gitRemoteUrlCache.get(e);const t=await sc((0,y.q6)(),this.gitExecutor,e);return void 0!==t&&this.gitRemoteUrlCache.set(e,t),t}getWorkspaceRelativePath(e){let t;for(const r of this.rootDirectories)(0,Yo.ZU)({basePath:r,targetPath:e})&&(void 0===t||r.length>t.length)&&(t=r);return void 0!==t?(0,Yo.oL)((0,s.relative)(t,e)):(0,Yo.oL)(e)}getCursorDataDir(){return this.cursorDataDirPromise??=(async()=>{const e=(0,s.join)(o.default.homedir(),".cursor");return await(0,Yo.DN)(e)??e})(),this.cursorDataDirPromise}async getRepoBlockExcludeGlobs(e){const t=await(this.teamSettingsService?.getTeamRepos());if(!t?.repos?.length)return[];const r=await this.resolveLookupRoot(e);let n;if(this.rootDirectories.some((e=>(0,Yo.ZU)({basePath:e,targetPath:r}))))n=await this.getGitRepoMapping();else{const e=this.extraGitRepoMappingCache.get(r);void 0!==e?n=e:(n=await this.initializeGitRepoMapping([r]),this.extraGitRepoMappingCache.set(r,n))}if(0===n.size)return[];const o=[];for(const[e,i]of n){if(void 0===i)continue;const n=this.normalizePathForComparison(e),a=this.normalizePathForComparison(r);let c=!1,l="";if(a.startsWith(n)?(c=!0,l=""):n.startsWith(a)&&(c=!0,l=(0,s.relative)(r,e)),!c)continue;const u=t.repos.filter((e=>fc(e.url,i)));if(0!==u.length)for(const e of u)for(const t of e.patterns||[]){const e=t.pattern.trim();if(!e)continue;let r;r=l?(0,s.join)(l,e).replace(/\\/g,"/"):e,o.push(r),r.endsWith("/**")||o.push(`${r}/**`)}}return o}normalizePathForComparison(e){let t=e.replace(/\\/g,"/");return t.startsWith("/")&&t.length>2&&":"===t[2]&&(t=t.substring(1)),"win32"===process.platform&&(t=t.toLowerCase()),t}getGitRepoMapping(){return this.gitRepoMappingPromise||(this.gitRepoMappingPromise=this.initializeGitRepoMapping()),this.gitRepoMappingPromise}async initializeGitRepoMapping(e=this.rootDirectories){const t=new Map,r=[],n=["**/node_modules/**","**/.turbo/**","**/.next/**","**/.cache/**","**/.pnpm/**","**/.yarn/**","**/dist/**","**/build/**","**/out/**","**/target/**","**/.vscode/**","**/.idea/**","**/venv/**","**/__pycache__/**","**/logs/**","**/tmp/**","**/temp/**"],o=(0,y.q6)();for(const t of e){const e=(0,Yo.o1)(t);try{await(0,Co.access)((0,s.join)(e,".git"),Co.default.constants.F_OK),r.includes(e)||r.push(e)}catch{}let i=(0,s.dirname)(e);const a=(0,s.parse)(i).root;for(;i!==a&&""!==i;){try{await(0,Co.access)((0,s.join)(i,".git"),Co.default.constants.F_OK),r.includes(i)||r.push(i)}catch{}const e=(0,s.dirname)(i);if(e===i)break;i=e}try{const t={root:e,includeGlobs:["**/.git/config"],excludeGlobs:[...n,...uc(e,this.scanEnvironment)],noIgnoreVcs:!0,source:"ignore_scan"},i=Ic.getRipwalkCache().walk(o,t);for await(const t of i.lines){const n=(0,s.join)(e,t),o=(0,s.dirname)(n),i=(0,s.dirname)(o);r.includes(i)||r.push(i)}}catch{}}return await Promise.all(r.map((async e=>{try{const r=await sc(o,this.gitExecutor,e);t.set(e,r)}catch{t.set(e,void 0)}}))),t}}async function Tc(e,t){let r=e;if($s()&&(r=Ls(t.command,t.parsingResult)),!r||"insecure_none"===r.type)return r;const n="workspace_readwrite"===r.type&&t.permissionsService.resolveLinkedWorktreeSandboxGrants?await t.permissionsService.resolveLinkedWorktreeSandboxGrants(r,{command:t.command,workingDirectory:t.workingDirectory}):void 0,o=function(e,t){if(!e)return t;const r={...e};for(const[e,n]of Object.entries(t))r[e]=Ec(r[e],n);return r}(r.ignoreMapping,await async function(e,t){return e.getShellSandboxIgnoreMapping?e.getShellSandboxIgnoreMapping(t):e.getCursorIgnoreMapping()}(t.ignoreService,n?.roots));if("workspace_readwrite"===r.type&&void 0!==n){const e=(0,Oo.s9)(r.additionalReadwritePaths,[...n.roots,...n.commonDirs]);return{...r,additionalReadwritePaths:e.length>0?e:void 0,ignoreMapping:o}}return{...r,ignoreMapping:o}}Ic.promiseQueue=new Or.TJ({max:Pc});var Ac=r("../proto/dist/generated/agent/v1/mcp_exec_pb.js");const $c="agent-tools",Mc=51380224;var Dc=r("../proto/dist/generated/agent/v1/utils_pb.js");const Oc=/^v?(\d{1,9})\.(\d{1,9})(?:\.\d{1,9})?(?:[-+][0-9A-Za-z.+-]*)?$/,Fc=["unknown","other","older","3.24","3.25","3.26","3.27","3.28","3.29","3.30","3.31","3.32","3.33","3.34","3.35","3.36","3.37","3.38","3.39","3.40","newer"].flatMap((e=>{const t=/^(\d+)\.(\d+)$/.exec(e);return null===t?[]:[{major:Number(t[1]),minor:Number(t[2]),bucket:e}]})),Nc=Fc[0].major,Lc=Fc[0].minor;function jc(e){if(null==e)return"unknown";const t=e.trim();if(0===t.length||t.length>128)return"unknown";const r=Oc.exec(t);if(null===r)return"unknown";const n=Number(r[1]),o=Number(r[2]);if(n!==Nc)return"other";const s=Fc.find((e=>e.minor===o));return void 0!==s?s.bucket:o=128&&t<=191?t:Vc.get(e)}function rl(e,t){const r=e.charCodeAt(t),n=function(e){return e>=194&&e<=222?201===e?0:2:e>=224&&e<=239?3:240===e?4:0}(r);if(0===n||t+n>e.length)return;const o=new Uint8Array(n);o[0]=r;for(let r=1;r0&&Jc.test(e[t-1]))return}else{if(Zc.has(s))return;if(!0===Qc.get(r)?.has(s))return;if(3===n&&Yc.has(s)&&Zc.has(e[t+2]))return}let i;try{i=Gc.decode(o)}catch{return}return el.test(i)?void 0:{index:t,text:e.slice(t,t+n),repaired:i}}function nl(e,t=Number.POSITIVE_INFINITY){const r=[];let n=0;for(;n240){n++;continue}const o=rl(e,n);void 0!==o?(r.push(o),n+=o.text.length):n++}return r}const ol=`[\\u00c2-\\u00f0][\\u0080-\\u00bf${[...Vc.keys()].join("")}]`,sl=new RegExp(ol),il=/\p{L}/u;function al(e,t){const r=e.charCodeAt(t);let n;if(r>=194&&r<=223)n=2;else if(r>=224&&r<=239)n=3;else{if(!(r>=240&&r<=244))return 0;n=4}if(t+n>e.length)return 0;for(let r=1;r=128&&n<=191)&&(n<128||!Vc.has(e[t+r])))return 0}return n}function cl(e,t){if(t.text.length>2)return!0;const r=t.text.charCodeAt(1);if(r>=128&&r<=159)return!0;if(0===t.index||!Jc.test(e[t.index-1]))return!0;const n=t.index+t.text.length;return n0)return"damaged";const n=yl(r);return"utf8"!==n&&"utf8_bom"!==n?"other_encoding":"intact"}function pl(e,t){return e<=t?"existing_only":"new_damage"}function fl(e,t){const r=new Set(t.map((e=>e.text))),n=e.filter((e=>!r.has(e.text))),o=n.length>0?n:e;if(function(e){let t="",r=-1;for(const n of e){if(n.index!==r){if(nl(t,1).length>0)return!0;t=""}t+=n.repaired,r=n.index+n.text.length}return nl(t,1).length>0}(o))return"double";if(1!==new Set(o.map((e=>e.text.length))).size)return"mixed";switch(o[0].text.length){case 2:return"two_byte";case 3:return"three_byte";default:return"four_byte"}}function ml(e){return{detector:e,outcome:"clean",afterCount:0,beforeCount:0}}function gl(e,t,r){const n=nl(r,1e3);if(0===n.length)return ml("mojibake");const o=void 0===e?[]:nl(e,Math.max(n.length,6));return{detector:"mojibake",outcome:pl(n.length,o.length),file:hl(e,o.length,t),afterCount:n.length,beforeCount:o.length,pattern:fl(n,o)}}function wl(e,t,r){const n=li(r);if(0===n)return ml("replacement_chars");const o=void 0===e?0:li(e);return{detector:"replacement_chars",outcome:pl(n,o),file:hl(e,o,t),afterCount:n,beforeCount:o}}function yl(e){if(void 0===e)return"none";const t=e.toLowerCase().replace(/[^a-z0-9]/g,"");return"utf8"===t||"ascii"===t?"utf8":"utf8bom"===t?"utf8_bom":t.startsWith("utf16")?"utf16":"latin1"===t||"iso88591"===t?"latin1":"windows1252"===t||"cp1252"===t?"windows_1252":"gbk"===t||"gb2312"===t||"gb18030"===t||"cp936"===t?"gbk":"shiftjis"===t||"sjis"===t||"cp932"===t||"windows31j"===t?"shift_jis":"euckr"===t||"cp949"===t?"euc_kr":"big5"===t||"big5hkscs"===t||"cp950"===t?"big5":"other"}const vl=new Map([["md",["md","mdx","markdown"]],["txt",["txt","text","log","rst","adoc","asciidoc","tex"]],["js_ts",["js","jsx","mjs","cjs","ts","tsx","mts","cts"]],["web",["html","htm","xhtml","css","scss","sass","less","vue","svelte","astro"]],["py",["py","pyi","pyw","ipynb"]],["jvm",["java","kt","kts","scala","groovy","gradle"]],["dotnet",["cs","csx","vb","fs","fsx","razor","cshtml","xaml"]],["c_cpp",["c","h","cc","cpp","cxx","c++","hpp","hh","hxx","h++","m","mm"]],["other_code",["go","rs","rb","erb","php","swift","dart","lua","pl","pm","r","ex","exs","erl","hs","clj","cljs","zig","nim","jl","sol","elm","ml","mli","pas","bas"]],["shell",["sh","bash","zsh","fish","ps1","psm1","psd1","bat","cmd"]],["sql",["sql","psql","ddl","dml"]],["config",["json","jsonc","json5","yaml","yml","toml","ini","cfg","conf","env","properties","editorconfig"]],["xml",["xml","xsl","xslt","xsd","svg","csproj","vbproj","fsproj","props","targets","nuspec","plist","storyboard","xib"]],["i18n",["po","pot","strings","stringsdict","arb","xlf","xliff","ftl","resx"]],["csv",["csv","tsv"]]].flatMap((([e,t])=>t.map((t=>[t,e])))));function bl(e){const t=(0,s.extname)(e).slice(1).toLowerCase();return""===t?"none":vl.get(t)??"other"}const Sl=new Map([[1252,"1252"],[1250,"1250"],[1251,"1251"],[874,"874"],[932,"932"],[936,"936"],[949,"949"],[950,"950"],[65001,"65001"]]);function kl(e){if("string"==typeof e)return e;const t=void 0===e.acp?void 0:Sl.get(e.acp);return void 0===t?"other":e.oemcp===e.acp?t:`${t}_split`}function _l(e,t){if("clean"===e.outcome)return{detector:e.detector,outcome:"clean",file:"unclassified"};const r={outcome:e.outcome,file:e.file,ext:bl(t.path),encoding:yl(t.encoding),code_page:kl(t.pages),run_count:ul(e.afterCount),delta:(n=e.afterCount-e.beforeCount,n<0?"neg":dl(n)),before_count:dl(e.beforeCount)};var n;return"mojibake"===e.detector?{detector:"mojibake",pattern:e.pattern,...r}:{detector:"replacement_chars",...r}}class Cl{constructor(){this.counts={stdout:0,stderr:0},this.produced={stdout:!1,stderr:!1}}note(e,t){if(0===t.length)return;this.produced[e]=!0;const r=this.counts[e];r>=6||(this.counts[e]=r+li(t,6-r))}labels(e,t){const r=kl(t),n=[];for(const t of["stdout","stderr"]){if(!this.produced[t])continue;const o=this.counts[t];n.push({detector:"replacement_chars",outcome:o>0?"damaged":"clean",run_count:dl(o),branch:e[t],stream:t,code_page:r})}return n}}const El=/[\ud800-\udbff](?![\udc00-\udfff])|(?=e.length||e.startsWith(Al,r))&&e.startsWith(Al,r+Fl(e,r)))return!0}return!1}(e)}(e,o))return"utf16";if(r)return"clean";if(!Tl.test(e))return"clean";const s=function(e){if(!sl.test(e))return;let t=0,r=!1,n=!0,o=0;for(;o=194&&s<=240?rl(e,o):void 0;if(void 0!==i){if(t++,r=cl(e,i),o+=i.text.length,!n||!r&&t>=256)return"medium";continue}const a=n?al(e,o):0;if(0===a){if(n=!1,t>0)return"medium";o++}else o+=a}return 0!==t?r&&n?"high":"medium":void 0}(e);return void 0!==s?"high"===s?"mojibake_high":"mojibake_medium":Il.test(e)?"c1":"clean"}const Ll=(0,l.h)("local-exec:encoding-slices");function jl(e,t){if(void 0===e)return!1;try{return"function"==typeof e?e(t):e}catch{return!1}}function Ul(e,t){return jl(e?.enabled,t)}function Bl(e,t,r=!1){if("clean"===e)return"clean";switch(t){case"utf8_valid":return"lone_surrogate"===e?"new_damage_cut":"existing_only";case"utf8_invalid":return"lone_surrogate"===e?"new_damage_cut":"replacement"!==e?"existing_only":r?"unknown":"not_text";case"utf8_cut":return"lone_surrogate"===e?"new_damage_cut":"replacement"!==e?"existing_only":r?"unknown":"new_damage_cut";case"utf8_as_other":return"new_damage_decode";case"declared_other":return"replacement"!==e||r?"unknown":"new_damage_decode";case"other_encoding":case"unseen":return"unknown";default:return t}}function Wl(e){for(let t=1;t<=Math.min(3,e.length);t++){const r=e[e.length-t]??0;if(128!=(192&r))return(r>=240?4:r>=224?3:r>=192?2:1)>t?t:0}return 0}class Hl{constructor(){this.seen=!1,this.invalid=!1,this.carry=new Uint8Array(0)}write(e){if(0===e.length)return;if(this.seen=!0,this.invalid)return;const t=this.carry.length>0?Buffer.concat([this.carry,e]):e,r=Wl(t);if(!(0,n.isUtf8)(t.subarray(0,t.length-r)))return this.invalid=!0,void(this.carry=new Uint8Array(0));this.carry=r>0?Uint8Array.from(t.subarray(t.length-r)):t.subarray(0,0)}evidence(){return this.seen?this.invalid?"utf8_invalid":this.carry.length>0?"utf8_cut":"utf8_valid":"unseen"}}const ql=new Map(Object.entries({zsh:"zsh",zsh_light:"zsh_light",bash:"bash",pwsh:"pwsh",powershell51:"powershell51",naive_pwsh:"naive_pwsh",naive_powershell51:"naive_powershell51",naive_bash:"naive_bash",naive_zsh:"naive_zsh",naive_other:"naive_other"})),zl=(0,u.Pu)("local_exec.encoding_slice",{description:"Results a local executor returned, and results about to be encoded for the wire, by the boundary they were counted at, the kind of encoding damage their text holds (one kind per result, clean included), whose the damage is as far as the bytes at that boundary say, which executor the result came from, the client's version bucket, for a shell result counted on Windows how the code page lookup stood, and for a shell result which shell ran the command",labelNames:["layer","kind","origin","source","version_bucket","code_page_lookup","shell_kind"]}),Gl=Pl[0],Vl=new Map(Pl.map(((e,t)=>[e,t])));function Kl(e){return Vl.get(e)??Pl.length}class Jl{constructor(){this.worst="clean",this.remaining=262144}note(e){this.walk(e,0)}kind(){return this.worst}capped(){return this.remaining<=0}settled(){return this.remaining<=0||this.worst===Gl}noteText(e){if(0===e.length)return;const t=e.length>this.remaining?Vo(e,this.remaining):e;this.remaining-=Math.max(t.length,1);const r=Nl(t);Kl(r)=16)return;if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer)return;if(Array.isArray(e)){for(const r of e)if(this.walk(r,t+1),this.settled())return;return}const r=Object.values(e);for(const e of r)if(this.walk(e,t+1),this.settled())return}}class Zl{constructor(e=1024){this.capacity=e,this.counted=new Set}firstRead(e,t){if(""===e)return!0;const r=`${e}\n${t}`,n=this.counted.delete(r);if(this.counted.add(r),this.counted.size>this.capacity)for(const e of this.counted){this.counted.delete(e);break}return!n}}function Xl(e,t,r,n){const o={layer:r.layer,kind:n,origin:Bl(n,r.evidence??"unseen",!0===r.partial),source:r.source??r.layer,version_bucket:jc(e.clientVersion)};void 0!==r.codePageLookup&&(o.code_page_lookup=r.codePageLookup),void 0!==r.shellKind&&(o.shell_kind=r.shellKind),zl.increment(t,1,o)}function Ql(e,t){Ll.warn(e,"encoding slice was not counted (result unaffected)",{error:t instanceof Error?t.name:"unknown"})}function Yl(e,t,r,n){if(void 0!==e&&Ul(e,t))try{const o=new Jl;o.note(n),Xl(e,t,r,o.kind())}catch(e){Ql(t,e)}}function eu(e,t,r,n){if(void 0!==e&&Ul(e,t))try{Xl(e,t,r,n)}catch(e){Ql(t,e)}}class tu{constructor(){this.seen=!1,this.invalid=!1}note(e){this.seen=!0,this.invalid||(0,n.isUtf8)(e)||(this.invalid=!0)}evidence(){return this.seen?this.invalid?"utf8_invalid":"utf8_valid":"unseen"}}function ru(e,t,r,n){return void 0===t?e:{execute:async(o,s,i)=>{const a=await e.execute(o,s,i);if(Ul(t,o))try{n(a)&&Yl(t,o,{layer:r},a)}catch(e){Ql(o,e)}return a}}}new Map([["readArgs","exec_read"],["redactedReadArgs","exec_read"],["grepArgs","exec_grep"],["mcpArgs","exec_mcp"],["readMcpResourceExecArgs","exec_mcp"],["executeHookArgs","exec_hooks"],["fetchArgs","exec_web_fetch"],["shellArgs","exec_shell"],["shellStreamArgs","exec_shell"],["backgroundShellSpawnArgs","exec_shell"],["miniSweAgentBashArgs","exec_shell"],["writeArgs","exec_write"]]);class nu{constructor(){this.text={stdout:new Jl,stderr:new Jl},this.bytes={stdout:new Hl,stderr:new Hl},this.produced={stdout:!1,stderr:!1},this.dropped={stdout:!1,stderr:!1},this.shellKind="unknown"}noteBytes(e,t){this.bytes[e].write(t)}noteText(e,t){0!==t.length&&(this.produced[e]=!0,this.text[e].note(t))}noteDropped(e){this.dropped[e]=!0}noteShell(e){this.shellKind=function(e){return"string"!=typeof e?"unknown":ql.get(e)??"unknown"}(e)}record(e,t,r,n){for(const o of["stdout","stderr"])this.produced[o]&&eu(e,t,{layer:"exec_shell",evidence:this.evidence(o,r[o]),partial:this.dropped[o]||this.text[o].capped(),codePageLookup:n,shellKind:this.shellKind},this.text[o].kind())}evidence(e,t){if("utf8"!==t)return"other_encoding";const r=this.bytes[e].evidence();return"utf8_cut"===r?"utf8_invalid":r}}var ou=r("node:child_process"),su=r("../utils/dist/workload-spawn.js");const iu=(0,l.h)("local-exec:shell-output-encoding"),au=(0,zs.promisify)(ou.execFile),cu=/^\s*OEMCP\s+REG_\w+\s+(\d+)\s*$/m,lu=/^\s*ACP\s+REG_\w+\s+(\d+)\s*$/m;function uu(e,t){const r=t.exec(e);return null===r?void 0:Number(r[1])}const du="㐀-䶿一-鿿豈-﫿",hu=" -〿㈀-㏿︰-﹯＀-￯",pu="‐-※←-⇿─-◿★☆",fu="぀-ヿ",mu=new Map([["cp932",{script:new RegExp(`[${du}${hu}${pu}${fu}]`),doubleByte:!0}],["cp936",{script:new RegExp(`[${du}${hu}${pu}${fu}㄀-ㄯ]`),doubleByte:!0}],["cp949",{script:new RegExp(`[${du}${hu}${pu}${fu}㄰-㆏가-힯]`),doubleByte:!0}],["cp950",{script:new RegExp(`[${du}${hu}${pu}㄀-ㄯ]`),doubleByte:!0}],["cp874",{script:new RegExp("[฀-๿]"),doubleByte:!1}]]);const gu=function(e){let t,r,n,o,s=!1,i=0;const a=()=>{i+=1;const e=i;n=async function(){const{stdout:e}=await(0,su.D9)(au,"\\\\.\\GLOBALROOT\\SystemRoot\\System32\\reg.exe",["query","HKLM\\SYSTEM\\CurrentControlSet\\Control\\Nls\\CodePage"],{encoding:"buffer",timeout:3e3,windowsHide:!0});return e}().then((e=>{const i=function(e){const t=Buffer.isBuffer(e)?function(e){return e.length>=2&&255===e[0]&&254===e[1]?e.subarray(2).toString("utf16le"):e.includes(0)?e.toString("utf16le"):e.toString("latin1")}(e):e,r={},n=uu(t,cu),o=uu(t,lu);return void 0!==n&&(r.oemcp=n),void 0!==o&&(r.acp=o),r}(e);t=function(e){const{oemcp:t,acp:r}=e;if(void 0===t||void 0===r||t!==r)return;const n=function(e){if(65001===e)return;const t=`cp${e}`;return Vs.encodingExists(t)?t:void 0}(t);return void 0!==n&&mu.has(n)?n:void 0}(i),r=i,s=!0,n=void 0,o=void 0===i.oemcp&&void 0===i.acp?"unparsed":"answered",iu.info((0,y.q6)(),"Resolved the fallback encoding for shell output",{encoding:t??"none",oemcp:i.oemcp??"none",acp:i.acp??"none"})}),(t=>{n=void 0,o=function(e){try{if("object"!=typeof e||null===e)return"spawn_error";const t="code"in e?e.code:void 0;return"killed"in e&&!0===e.killed&&"string"!=typeof t?"timeout":"number"==typeof t?"nonzero_exit":"spawn_error"}catch{return"spawn_error"}}(t),iu.warn((0,y.q6)(),"Could not read the Windows code pages; shell output stays UTF-8 only",{error:t instanceof Error?t.message:String(t),attempt:e})}))};return"win32"===e&&a(),{current:()=>("win32"===e&&!s&&void 0===n&&i<3&&a(),t),pages:()=>void 0!==r?r:"win32"!==e?"none":i>=3&&void 0===n?"failed":"pending",lastOutcome:()=>"win32"===e?o??"pending":void 0,settled:()=>n??Promise.resolve()}}(process.platform),wu=Buffer.alloc(0),yu=/[\u0080-\uffff]/;function vu(e){const t=Math.max(0,e.length-3);for(let r=e.length-1;r>=t;r--){const t=e[r];if(128==(192&t))continue;const n=t>=248?1:t>=240?4:t>=224?3:t>=192?2:1,o=e.length-r;return n>o?o:0}return 0}function bu(){const e=new ia.StringDecoder("utf8");return{write:t=>e.write(t),end:()=>e.end()}}function Su(e,t){return Vs.decode(t,e,{stripBOM:!1})}const ku=/[\xe0-\xef][\x80-\xbf]\?/;const _u=10,Cu=Buffer.alloc(0),Eu=new Set([7,8,9,10,11,12,13,27]);function xu(e,t,r){for(let n=0;n+1(r=void 0,t.end())}}const Iu={encoding:"utf8",skip:0};function Tu(e){const t=e();let r="utf8";const n={};let o=!1;const s=()=>"utf8"===r?t:n[r]??=Ru(r),i=e=>("utf8"!==r&&e.length>0&&(o=!0),e);let a,c=!0,l=Cu,u=!1,d=0;const h=(e,t)=>{const n=function(e){if(!(e.length<2))return 255===e[0]&&254===e[1]?"utf16le":254===e[0]&&255===e[1]?"utf16be":void 0}(e);if(void 0!==n)return{encoding:n,skip:2};if("utf8"===r){if(e.length<2)return t?Iu:void 0;const r=0===e[0]?"utf16be":0===e[1]?"utf16le":void 0;if(void 0===r)return Iu;const n=Pu(e,r);if(-1!==n)return xu(e,r,n)?{encoding:r,skip:0}:Iu;if(!t)return;const o=e.length-e.length%2;return function(e,t){const r="utf16le"===t?1:0;for(let t=0;te.length?t?o:void 0:xu(e,r,n)?o:Iu}if(-1===i)return t?Iu:void 0;if("utf16le"===r&&i%2==0){if(i+1>=e.length)return t?Iu:void 0;if(0===e[i+1])return o}return Iu},p=e=>{if(e===r)return"";const t=i(s().end());return r=e,t},f=e=>"utf8"===r&&0!==e&&e<128,m=(e,n)=>{let o="",m=e;for(;;){if(c){const e=Math.min(m.length,512-l.length);let r;if(r=l.length>0?Buffer.concat([l,m.subarray(0,e)]):e===m.length?m:m.subarray(0,e),0===r.length)return o;const s=h(r,n||r.length>=512);if(void 0===s)return 1===r.length&&f(r[0])&&(o+=t.write(r),u=!0),l=Buffer.from(r),o;let i=s.skip,g=!1;if(u&&(i="utf8"===s.encoding?1:2,g=r[0]===_u,u=!1),0===l.length)i>0&&(m=m.subarray(i));else{const t=r.subarray(i);m=m.subarray(e),m=0===m.length?t:0===t.length?m:Buffer.concat([t,m]),l=Cu}if(c=g,d=0,a=void 0,o+=p(s.encoding),g)continue}if(0===m.length)return o;if("utf8"===r&&!m.includes(0)&&!m.includes(254)&&!m.includes(255)){const e=m.lastIndexOf(_u),r=-1===e?-1:m.length-e-1;if(-1===r||r>=2)return o+t.write(m);if(c=!0,0===r)return e>0&&m[e-1]===_u&&(l=Buffer.of(_u),u=!0),o+t.write(m);const n=m[m.length-1];return l=Buffer.of(n),u=f(n),o+t.write(u?m:m.subarray(0,e+1))}const e=Pu(m,r,d,a);if(-1===e)return d+=m.length,a=m[m.length-1],o+i(s().write(m));o+=i(s().write(m.subarray(0,e))),m=m.subarray(e),c=!0}};return{write:e=>0===e.length?s().write(e):m(e,!1),peek(){if(!c||0===l.length)return"";const t=h(l,!0);if(void 0===t)return"";const r=u?"utf8"===t.encoding?1:2:t.skip,n=l.subarray(r);return 0===n.length?"":"utf8"===t.encoding?e().write(n):Ru(t.encoding).write(n)},end(){const e=m(Cu,!0)+i(s().end());return c=!0,l=Cu,u=!1,d=0,a=void 0,e},branch:()=>!0===t.usedCodePage?.()?"code_page":o?"utf16":"utf8"}}var Au=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},$u=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Mu=(0,l.h)("local-exec:shell-core"),Du=(0,u.Pu)("local_exec.shell.encoding_check",{description:"Shell command output streams that produced text, per encoding detector (U+FFFD): whether the decoded text holds the pattern and how much, which decode path (UTF-8, Windows code page, UTF-16) produced it, which stream, and the machine's Windows code page",labelNames:["detector","outcome","run_count","branch","stream","code_page"]}),Ou="win32"===process.platform,Fu=["CURSOR_CONVERSATION_ID","CURSOR_REQUEST_ID","CURSOR_AGENT_STORE_FILES_DIR","CURSOR_AGENT_STORE_SHARED_PATHS"];function Nu(e){return`'${e.replace(/'/g,"'\\''")}'`}async function Lu(e){try{return(await(0,Co.stat)(e)).isDirectory()}catch(e){const t=Sc(e);if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}const ju=["eval-cursorbench","cursorbench","sand-eval","eval-harness"];function Uu(e){return ju.some((t=>e.includes(t)))?(0,bo.createHash)("sha256").update(e).digest("hex"):e}function Bu(e,t){return e[t]??process.env[t]}const Wu=/^[A-Za-z_][A-Za-z0-9_]*$/,Hu=/CURSOR_SANDBOX/i;function qu(e){return Wu.test(e)&&!Hu.test(e)}function zu(e){return"function"==typeof e?e():e}function Gu(e,t){const r=void 0===e?[]:[...e];return r.includes(t)||r.push(t),r}function Vu(e){let t=0,r=0;const n=e.length;for(;r"insecure_none"===e?.type?void 0:e?.privateTmp)).find((e=>void 0!==e));if("linux"!==process.platform||!0!==n||void 0===r||!(0,Yo.ZU)({basePath:"/tmp",targetPath:e}))return!1;const o=(0,Oo.W1)(r);return void 0!==o&&await Lu(s.default.join(o,"tmp",s.default.relative("/tmp",e)))}(c,t.sandboxPolicy,this.workspacePath))){if(c!==(0,Yo.o1)(await i.getCwd(),this.workspacePath))throw new Ku(c);return yield{type:"stderr",data:`The shell's working directory no longer exists: ${c}. The command did not run. Re-run it with working_directory set to an existing directory.\n`},void(yield{type:"exit",code:1,aborted:!1,localExecutionTimeMs:Math.round(performance.now()-o)})}let l,u,d=0,h=0,p=!1,f=!1,m=!1;t.fileOutputThresholdBytes&&this.projectDir&&(l={buffer:"",lineCount:0,size:0,threshold:Number(t.fileOutputThresholdBytes)});const g=t.signal,w={CURSOR_AGENT:"1"};t.conversationId&&(w.CURSOR_CONVERSATION_ID=(0,So.sh)(t.conversationId)),t.requestId&&(w.CURSOR_REQUEST_ID=t.requestId),this.projectDir&&(w.AGENT_TRANSCRIPTS=s.default.join(this.projectDir,So.O2));const y=this.options.extraEnvProvider?.(e,t);void 0!==y&&Object.assign(w,y);const v=t.requestScopedEnv??{};for(const[e,t]of Object.entries(v))void 0!==t&&qu(e)&&(w[e]=t);const b=w.CURSOR_REQUEST_ID;void 0!==b&&(w.CURSOR_REQUEST_ID=Uu(b)),function(e,t){const r=Fu,n=Object.keys(t).filter((e=>qu(e)&&!r.includes(e))),o=`builtin unset ${[...Fu,...n].join(" ")} 2>/dev/null || true`,s=[];for(const t of Fu){const r=Bu(e,t);void 0!==r&&s.push(`builtin export ${t}=${Nu(r)}`)}for(const e of n){const r=t[e];void 0!==r&&s.push(`builtin export ${e}=${Nu(r)}`)}const i=e.__CURSOR_SANDBOX_ENV_RESTORE?.trim(),a=process.env.__CURSOR_SANDBOX_ENV_RESTORE?.trim();e.__CURSOR_SANDBOX_ENV_RESTORE=[o,a,i,...s].filter((e=>void 0!==e&&""!==e)).join("; ")}(w,v),void 0!==w.__CURSOR_SANDBOX_ENV_RESTORE&&(w.__CURSOR_SANDBOX_ENV_RESTORE=function(e,t){let r=e;for(const e of t){if(null==e||0===e.length)continue;const t=Uu(e);t!==e&&(r=r.split(e).join(t))}return r}(w.__CURSOR_SANDBOX_ENV_RESTORE,[t.requestId,b,v.CURSOR_REQUEST_ID,process.env.CURSOR_REQUEST_ID]));const S=function(e,t){const r=Bu(t,"CURSOR_AGENT_STORE_FILES_DIR"),n=function(e){if(void 0===e)return[];try{const t=JSON.parse(e);if("object"!=typeof t||null===t)return[];const r=[];for(const e of Object.values(t))"object"==typeof e&&null!==e&&"path"in e&&"readOnly"in e&&"string"==typeof e.path&&"boolean"==typeof e.readOnly&&r.push({path:e.path,readOnly:e.readOnly});return r}catch{return[]}}(Bu(t,"CURSOR_AGENT_STORE_SHARED_PATHS"));if(void 0===r&&0===n.length)return e;const o=e?.perUser,s=e?.perRepo??e?.perUser??e?.teamAdmin;if("workspace_readwrite"!==s?.type&&"workspace_readonly"!==s?.type)return e;const i=o?.type===s.type?{...o}:{type:s.type};var a;void 0!==r&&(a=r,"workspace_readwrite"!==i.type?i.additionalReadonlyPaths=Gu(i.additionalReadonlyPaths,a):i.additionalReadwritePaths=Gu(i.additionalReadwritePaths,a));for(const e of n)e.readOnly||"workspace_readwrite"!==i.type?i.additionalReadonlyPaths=Gu(i.additionalReadonlyPaths,e.path):i.additionalReadwritePaths=Gu(i.additionalReadwritePaths,e.path);return{...e,perUser:i}}(t.sandboxPolicy,w),k=(0,Oo.CG)(S??Oo.BM);let _,C,E,x;S&&(yield{type:"start",sandboxed:"workspace_readonly"===k||"workspace_readwrite"===k}),t.askpassConfig&&!Ou&&(w.SUDO_ASKPASS=t.askpassConfig.helperPath,w.CURSOR_ASKPASS_SOCKET=t.askpassConfig.socketPath,w.CURSOR_ASKPASS_SECRET=t.askpassConfig.secret);const P=this.options.codePageLookup??gu,R=(this.options.outputFallbackEncoding??(()=>P.current()))(),I=()=>function(e){if(void 0===e)return bu();const t=mu.get(e);return void 0!==t&&Vs.encodingExists(e)?function(e,t){const{script:r}=t,o=function(e){const{script:t}=e,r=new RegExp(`${t.source}{2}`);let n=!1,o=!1,s=!1;return{note(i,a){if(!s&&0!==i.length){if(!n){const e=yu.exec(i);null!==e&&(n=!0,s=t.test(e[0]))}s||=o&&t.test(i[0])||r.test(i)||e.doubleByte&&void 0!==a&&ku.test(a.toString("latin1")),o=t.test(i[i.length-1])}},isUtf8Text:()=>s,reset(){n=!1,o=!1,s=!1}}}(t);let s=wu,i=0,a="utf8",c=!1;const l=()=>{a="utf8",o.reset(),i=0},u=(t,n)=>{const s=n?vu(t):0,l=t.subarray(0,t.length-s),u=l.toString("utf8");if("replacement"!==a){const t=l.subarray(i);if(i=0,o.note(t.toString("utf8"),t),o.isUtf8Text())a="replacement";else{const t=0===u.length?"":u[u.length-1],o=n&&r.test(t)?Buffer.byteLength(t):0,d=function(e,t,r){let n=Su(e,t);if(!r)return{text:n,keep:0};const o=Math.min(3,t.length);let s=0;for(;s0&&(c=!0),{text:d.text,keep:i+s}}}return{text:u,keep:s}};return{write:e=>{const t=0===s.length?e:Buffer.concat([s,e]);if(s=wu,"utf8"===a){const e=t.subarray(0,t.length-vu(t));if((0,n.isUtf8)(e)){e.length{const t=e.lastIndexOf("\n");-1===t?o.note(e):(l(),o.note(e.slice(t+1)))})(r),r}}let r="",i=0;for(;i0&&(s=Buffer.from(d.subarray(u.length))),-1===e?o.note(n):l(),i=c;continue}a="undecided"}const{text:h,keep:p}=u(d,-1===e);r+=h,p>0&&(s=Buffer.from(d.subarray(d.length-p))),-1!==e&&l(),i=c}return r},end:()=>{const e=s;s=wu;const t=0===e.length?"":"utf8"===a?e.toString("utf8"):u(e,!1).text;return l(),t},usedCodePage:()=>c}}(e,t):bu()}(R),T={stdout:Tu(I),stderr:Tu(I)},A=new Cl,M=Ul(this.options.encodingSlices,e)?new nu:void 0,D=void 0===M?void 0:function(e,t,r){return n=>{try{const o=function(e,t,r){if(!(Object.hasOwn(Bc,e.shell)&&Object.hasOwn(Wc,e.parse)&&Object.hasOwn(Hc,e.stateFile)&&Object.hasOwn(qc,e.exit)))return;let n="withheld";if(r){if("function"!=typeof e.callsExit)return;n=!0===e.callsExit()?"yes":"no"}return{shell_kind:e.shell,parse:e.parse,calls_exit:n,state_file:e.stateFile,exit:e.exit,version_bucket:jc(t)}}(n,t,r);if(void 0===o)return;zc.increment(e,1,{...o})}catch(t){Uc.warn(e,"PowerShell run was not counted (command unaffected)",{error:t instanceof Error?t.name:"unknown"})}}}(e,this.options.encodingSlices?.clientVersion,function(e,t){return!0===jl(e?.commandTextReadable,t)}(this.options.encodingSlices,e));let O=!1;const F=()=>{if(!O){O=!0;try{const t={stdout:T.stdout.branch(),stderr:T.stderr.branch()};for(const r of A.labels(t,P.pages()))Du.increment(e,1,r);M?.record(this.options.encodingSlices,e,t,P.lastOutcome())}catch(t){Mu.warn(e,"shell output encoding check failed (command result unaffected)",{error:t instanceof Error?t.message:String(t)})}}},N=e=>{void 0!==l&&0!==e.length&&(l.file?l.file.write(e):l.buffer+=e)},L=function*(){const e={stdout:p,stderr:f};for(const t of["stdout","stderr"]){const r=T[t].end();if(0===r.length)continue;const n=void 0!==l&&!0!==l.truncated;n&&N(r),!n&&e[t]||(A.note(t,r),M?.noteText(t,r)),e[t]||(yield{type:t,data:r})}F()};try{for await(const r of i.execute(e,t.command,{signal:g,workingDirectory:c,env:w,sandboxPolicy:S,sandboxWorkspaceRoot:this.workspacePath,pipeStdin:t.pipeStdin??!1,keepBackgroundJobs:this.options.keepBackgroundJobs??!1,bufferOutputEvents:this.options.shellOutputBackpressureOptions?.bufferOutputEvents,outputLimiterOptions:this.options.shellOutputBackpressureOptions?.outputLimiterOptions,powershellUtf8Console:zu(this.options.powershellUtf8Console),powershellUtf8ChildEnv:zu(this.options.powershellUtf8ChildEnv),powershellParseAfterUtf8Switch:zu(this.options.powershellParseAfterUtf8Switch),powershellWebRequestUtf8:zu(this.options.powershellWebRequestUtf8),powershellPerLineStateDump:zu(this.options.powershellPerLineStateDump),...void 0===D?{}:{powershellRunObserver:D}})){_=0,C="",E="",x="";let e=!1,t=!1;if("stdout"===r.type||"stderr"===r.type){const n=T[r.type],o="stdout"===r.type?p:f,i=void 0===l||!0===l.truncated;let a=!1;if(!o||!i){_=r.data.length;const c="stdout"===r.type?d:h,p=!o&&c+_<=rs,f=void 0!==l&&!0!==l.truncated&&l.size+_<=Mc;"stdout"===r.type?e=p:t=p;const m=!o&&!p,g=!i&&!f;if((m||g)&&(x=n.peek(),g&&N(x),m&&(E=x)),(p||f)&&(C=n.write(r.data),a=!0,A.note(r.type,C),M?.noteBytes(r.type,r.data),M?.noteText(r.type,C)),void 0!==l&&l.size+_>Mc)l.truncated=!0;else if(f&&void 0!==l)if(l.size+=_,l.lineCount+=Vu(r.data),l.file)l.file.write(C);else if(l.buffer+=C,l.size>l.threshold){const e=s.default.join(this.projectDir,$c);l.path=s.default.join(e,`${(0,bo.randomUUID)()}.txt`);try{await(0,Co.mkdir)(e,{recursive:!0}),l.file=(0,xo.createWriteStream)(l.path),l.file.on("error",(e=>{u??=e})),l.file.write(l.buffer)}catch(e){u??=e instanceof Error?e:new Error(String(e)),l.truncated=!0}l.buffer=""}}a||(n.end(),A.note(r.type,x),M?.noteDropped(r.type),M?.noteText(r.type,x))}switch(r.type){case"stdout":e?(d+=_,C&&(yield{type:"stdout",data:C})):p||(E&&(yield{type:"stdout",data:E}),p=!0,yield{type:"stdout_trimmed"});break;case"suppressed_output":m||(m=!0,yield{type:"stdout",data:Oo.Ls});break;case"stderr":t?(h+=_,C&&(yield{type:"stderr",data:C})):f||(E&&(yield{type:"stderr",data:E}),f=!0,yield{type:"stderr_trimmed"});break;case"exit":{yield*L();const e=Math.max(0,Math.round(performance.now()-o));let t;if(l?.file){if(l.truncated){const e=`\n... (output truncated at ${l.size} bytes) ...\n`;l.file.write(e),l.size+=e.length,l.lineCount+=Js(e)-1}const e=await new Promise((e=>l.file.end(e)));u??=e??void 0,u?await(0,Co.rm)(l.path,{force:!0}):t=new Dc.pV({filePath:l.path,sizeBytes:BigInt(l.size),lineCount:BigInt(l.lineCount)})}u&&void 0!==l?.path&&(yield{type:"stderr",data:`\nThe full output could not be saved to ${l.path}: ${u.message}\n`}),yield{type:"exit",code:r.code,signal:r.signal,aborted:r.aborted,outputLocation:t,localExecutionTimeMs:e};break}case"stdin_ready":M?.noteShell(r.shell),yield{type:"stdin_ready",stdin:r.stdin,pid:r.pid};break;case"sandbox_denies":yield{type:"sandbox_denies",events:r.events}}}yield*L()}catch(t){if("ENOENT"===Sc(t)&&(0,qs.$f)(c))try{Mu.warn(e,"shell failed with ENOENT in an agent store working directory",{...await(0,qs.KZ)(c)})}catch{}throw t}finally{F()}}catch(e){r.error=e,r.hasError=!0}finally{$u(r)}}async getCwd(e){return this.executorFor(e).getCwd()}getWorkspacePath(){if(!this.workspacePath)throw new Error("Workspace path is not configured");return this.workspacePath}}class Zu{constructor(e,t){this.innerExecutor=e,this.shellManager=t}async*execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{Au(r,(0,$.VI)(e.withName("ManagedShellCoreExecutor.execute")),!1),Mu.info(e,"Executing shell command",{command:t.command,workingDirectory:t.workingDirectory,toolCallId:t.toolCallId});let n=null;t.toolCallId&&(n=this.shellManager.getOrCreateShellEmitter(t.toolCallId));for await(const r of this.innerExecutor.execute(e,t)){if(n)switch(r.type){case"stdin_ready":n.emit({type:"stdin_ready",stdin:r.stdin,pid:r.pid});break;case"start":n.emit({type:"start",sandboxed:r.sandboxed});break;case"stdout":n.emit({type:"stdout",data:r.data});break;case"stderr":n.emit({type:"stderr",data:r.data});break;case"exit":n.emit({type:"exit",code:r.code??-1,aborted:r.aborted})}yield r}}catch(e){r.error=e,r.hasError=!0}finally{$u(r)}}async getCwd(e){return this.innerExecutor.getCwd(e)}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}class Xu{constructor(e,t){this.innerExecutor=e,this.askpassConfig=t}async*execute(e,t){const r={...t,askpassConfig:t.askpassConfig??this.askpassConfig};yield*this.innerExecutor.execute(e,r)}async getCwd(e){return this.innerExecutor.getCwd(e)}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}async function Qu(e,t){switch(e.type){case"needsApproval":return t.onNeedsApproval(e.approvalReason,e.approvalDetails);case"userRejected":return t.onUserRejected(e.reason);case"cursorIgnore":return t.onPermissionDenied("Blocked by cursor ignore");case"permissionsConfig":return t.onPermissionDenied("Blocked by permissions configuration",{isReadonly:e.isReadonly});case"cursorFiles":return t.onPermissionDenied("Blocked by cursor files protection");case"adminBlock":return t.onPermissionDenied("Blocked by admin repository block");case"adminCommandDenylist":return t.onPermissionDenied(Ss(e.pattern));case"unsafeResolution":return t.onPermissionDenied(e.message);default:{const t=e;throw new Error(`Unhandled block reason type: ${JSON.stringify(t)}`)}}}function Yu(e){switch(e.type){case"userRejected":return e.reason;case"unsafeResolution":return e.message;case"adminCommandDenylist":return Ss(e.pattern);case"needsApproval":case"cursorIgnore":case"adminBlock":case"permissionsConfig":case"cursorFiles":return"Command is not allowed";default:{const t=e;return`Command is not allowed (${JSON.stringify(t)})`}}}function ed(e,t,r){return"permissionsConfig"===r.type?{case:"permissionDenied",value:new he.jn({command:e,workingDirectory:t,error:"Command blocked by permissions configuration",isReadonly:r.isReadonly??!1})}:{case:"rejected",value:new he.pZ({command:e,workingDirectory:t,reason:Yu(r)})}}var td=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const rd=(0,l.h)("local-exec:background-shell");function nd(e,t,r){return new Do.Lt({result:ed(e,t,r)})}class od{constructor(e,t){this.id=e,this.abortController=t,this.disposed=!1,this.completed=!1,this.completionListeners=[]}abort(){this.abortController.abort()}dispose(){this.disposed||(this.disposed=!0,this.abortController.signal.aborted||this.abortController.abort())}get signal(){return this.abortController.signal}isDisposed(){return this.disposed}onComplete(e){this.completed&&this.completion?e(this.completion):this.completionListeners.push(e)}markCompleted(e){if(this.completed)return;this.completed=!0,this.completion=e;const t=[...this.completionListeners];this.completionListeners=[];for(const r of t)r(e)}}async function sd(e,t){let r;try{for(let n=await t.next();!n.done;n=await t.next())"stdin_ready"===n.value.type?(e.stdin=n.value.stdin,e.pid=n.value.pid):"exit"===n.value.type&&(r={code:n.value.code,signal:n.value.signal,aborted:n.value.aborted,outputPath:n.value.outputLocation?.filePath})}catch(e){}finally{e.markCompleted(r??{code:null,aborted:e.signal.aborted})}}function id(e){e().catch((()=>{}))}class ad{constructor(e){if(this.args=e,this.carryover="",this.matchedOccurrences=0,this.emittedNotifications=0,this.finished=!1,this.monotonicStartMs=performance.now(),this.limit=e.config.notificationLimit??100,e.config.pattern.length>500)throw new Error("Output notification pattern exceeds 500 characters");this.regex=Qo.L3.compile(e.config.pattern,Qo.L3.MULTILINE)}observe(e){if(this.finished||this.matchedOccurrences>=this.limit||0===e.length)return;if(e.length>65536){for(const t of function(e){if(0===e.length)return[];const t=Math.max(1,Math.trunc(65536)||1),r=[];let n=0;for(;n=this.limit)break;this.observe(t)}return}const t=this.carryover.length,r=`${this.carryover}${e}`,n=this.regex.matcher(r);for(;this.matchedOccurrencest&&this.queueMatch(e)}this.carryover=Ko(r,1024)}finish(){this.finished||(this.finished=!0,this.flushPendingBatch("finish"),this.clearFlushTimer(),0===this.matchedOccurrences&&this.recordWatchOutcome("silent",{silent_ms:ud(this.monotonicStartMs)}))}queueMatch(e){if(this.matchedOccurrences>=this.limit)return;this.matchedOccurrences+=1;const t=this.matchedOccurrences,r=function(e,t){return e.length<=5e3?`${t}: ${e}`:`${t} is ${e.length} characters; omitted from notification detail.`}(e,1===t?"Matched text":"Latest match");return 1===t?(this.emitNotification({startOccurrence:t,endOccurrence:t,count:1,matchedTextDetail:r}),this.recordWatchOutcome("matched",{first_match_ms:ud(this.monotonicStartMs)}),void(t===this.limit&&this.emitLimitReachedNotification())):(this.pendingBatch?(this.pendingBatch.endOccurrence=t,this.pendingBatch.count+=1,this.pendingBatch.matchedTextDetail=r):this.pendingBatch={startOccurrence:t,endOccurrence:t,count:1,matchedTextDetail:r},t===this.limit?(this.flushPendingBatch("limit"),void this.emitLimitReachedNotification()):void this.scheduleFlush())}scheduleFlush(){if(void 0!==this.flushTimer)return;const e=this.getDebounceMs();this.flushTimer=setTimeout((()=>{this.flushPendingBatch("debounce")}),e)}getDebounceMs(){const e=this.args.debounceMs??function(e){const t=e.debounce;if(void 0!==t&&Number.isFinite(t))return Math.ceil(1e3*t)}(this.args.config)??5e3;return Math.max(e,5e3)}clearFlushTimer(){void 0!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0)}flushPendingBatch(e){const t=this.pendingBatch;t&&(this.pendingBatch=void 0,this.clearFlushTimer(),this.emitNotification(t))}emitNotification(e){this.emittedNotifications+=1;const t=this.args.config.reason.trim()||`Shell output contains /${this.args.config.pattern}/`,r=this.args.config.pattern,n=void 0!==e.matchedTextDetail?` ${e.matchedTextDetail}.`:"",o=1===e.count?`Shell output has pattern /${r}/. This is occurrence number ${e.startOccurrence}.${n} The title message is being displayed to the user.`:`Shell output matched /${r}/ ${e.count} more times since the previous notification. The title message is being displayed to the user.${n}`,s=Ro(String(this.args.shellId),this.emittedNotifications);var i;this.args.registry.enqueue({conversationId:this.args.conversationId,id:s,source:"shell",payload:{taskId:s,...void 0!==this.args.toolCallId?{toolCallId:this.args.toolCallId}:{},kind:"shell",status:"success",title:(i=t,i.length<=500?i:`${Vo(i,500)}...`),detail:o,outputPath:this.args.outputPath,reason:"task_progress"}})}emitLimitReachedNotification(){this.emittedNotifications+=1;const e=this.args.config.pattern,t=Ro(String(this.args.shellId),this.emittedNotifications);this.args.registry.enqueue({conversationId:this.args.conversationId,id:t,source:"shell",payload:{taskId:t,...void 0!==this.args.toolCallId?{toolCallId:this.args.toolCallId}:{},kind:"shell",status:"success",title:`Notification limit reached (${this.limit})`,detail:`Shell output matched /${e}/ ${this.limit} times and has reached the notification limit. No further notifications will be sent for this pattern. To continue monitoring, read the output file directly at the output path.`,outputPath:this.args.outputPath,reason:"task_progress"}}),this.recordWatchOutcome("limit_reached")}recordWatchOutcome(e,t){void 0!==this.args.ctx&&rd.info(this.args.ctx,"agent.shell_output_notification_match",{event:"agent.shell_output_notification_match",outcome:e,shell_id:this.args.shellId,conversation_id:this.args.conversationId,tool_call_id:this.args.toolCallId,limit:this.limit,...t})}}class cd{constructor(e,t,r){this.innerFactory=e,this.projectDir=t,this.backgroundWorkRegistry=r}async spawn(e,t){const r=this.createObserver(e.ctx,e.shellId,e.conversationId,e.toolCallId,e.outputNotification);if(!r)return this.innerFactory.spawn(e,t);try{return await this.innerFactory.spawn(e,this.createObservingExecutor(t,r))}catch(e){throw r.finish(),e}}async adopt(e){const t=this.createObserver(e.ctx,e.shellId,void 0,e.toolCallId,e.outputNotification);if(!t)return this.innerFactory.adopt(e);e.initialOutput.length>0&&t.observe(e.initialOutput);try{return await this.innerFactory.adopt({...e,eventIterator:this.createObservingIterator(e.eventIterator,t)})}catch(e){throw t.finish(),e}}createObserver(e,t,r,n,o){if(!this.backgroundWorkRegistry||!o)return;if(0===o.pattern.trim().length)return;const i=s.join(this.projectDir,"terminals",`${t}.txt`);try{return new ad({shellId:t,outputPath:i,config:o,conversationId:r??Po,toolCallId:n,registry:this.backgroundWorkRegistry,ctx:e})}catch(r){return void(void 0!==e&&rd.warn(e,"Invalid shell output notification pattern",{shellId:t,error:r instanceof Error?r.message:String(r)}))}}createObservingExecutor(e,t){const r=e.execute.bind(e);return{...e,execute:async function*(e,n){try{for await(const o of r(e,n))"stdout"===o.type||"stderr"===o.type?t.observe(o.data):"exit"===o.type&&t.finish(),yield o}finally{t.finish()}}}}createObservingIterator(e,t){const r=e.return?.bind(e);return{next:async()=>{try{const r=await e.next();if(r.done)t.finish();else{const e=r.value;"stdout"===e.type||"stderr"===e.type?t.observe(e.data):"exit"===e.type&&t.finish()}return r}catch(e){throw t.finish(),e}},return:async e=>(t.finish(),r?r(e):{done:!0,value:void 0})}}}class ld{async spawn(e,t){const r=new AbortController,n=new od(e.shellId,r),o=t.execute(e.ctx,{command:e.command,workingDirectory:e.workingDirectory,signal:r.signal,toolCallId:e.toolCallId,conversationId:e.conversationId,requestId:e.requestId,secretScopeId:e.secretScopeId,sandboxPolicy:e.sandboxPolicy,pipeStdin:e.enableWriteShellStdinTool,showElapsedTime:!0})[Symbol.asyncIterator]();try{for(let e=await o.next();!e.done;e=await o.next())if("stdin_ready"===e.value.type){n.stdin=e.value.stdin,n.pid=e.value.pid;break}}catch(e){if(e instanceof Oo.SandboxUnsupportedError||e instanceof Ku)throw e}return id((()=>sd(n,o))),n}async adopt(e){const t=new od(e.shellId,e.abortController);return t.stdin=e.stdin,t.pid=e.pid,id((()=>sd(t,e.eventIterator))),t}}function ud(e){return Math.round(performance.now()-e)}function dd(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}function hd(e){const t=String(e.runningForMs).padEnd(9," "),r=e.status.padEnd(9," ");let n="---\n";return void 0!==e.pid&&0!==e.pid&&(n+=`pid: ${e.pid}\n`),n+=`cwd: ${dd(e.cwd)}\n`,n+=`command: ${dd(e.command)}\n`,void 0!==e.title&&e.title.trim().length>0&&(n+=`title: ${dd(e.title)}\n`),n+=`status: ${r}\n`,n+=`started_at: ${e.startedAt}\n`,n+=`running_for_ms: ${t}\n`,n+="---\n",n}function pd(e){return`\n[${e} truncated by cursor: the command wrote more than 1048576 characters to ${e}; only the first 1048576 were captured and the rest was dropped from this file]\n`}class fd{constructor(e,t){this.innerFactory=e,this.projectDir=t}async spawn(e,t){const r=s.join(this.projectDir,"terminals");await(0,Co.mkdir)(r,{recursive:!0});const n=this.createLoggingExecutor(t,e,r);return this.innerFactory.spawn(e,n)}createLoggingExecutor(e,t,r){const o=e.execute.bind(e);return{...e,execute:async function*(e,i){let a,c,l,u=!1,d=!1,h=!1,p=!1;const f=Date.now(),m=new Date(f).toISOString(),g=performance.now();let w,y="running",v=!1,b=Promise.resolve();const S=async e=>{if(c)try{await c.write(e)}catch(e){}},k=t.shellId,_=s.join(r,`${k}.txt`),C=async()=>{if(!a)return;const e=ud(g),r=hd({pid:w,cwd:t.workingDirectory,command:t.command,title:t.description,status:y,startedAt:m,runningForMs:e});try{await a.write(r,0,"utf8")}catch(e){}},E=()=>(b=b.then(C).catch((()=>{})),b),x=()=>{void 0!==l&&(clearInterval(l),l=void 0)},P=async e=>{if(p)return;p=!0,w=e;const r=ud(g),n=hd({pid:e,cwd:t.workingDirectory,command:t.command,title:t.description,status:y,startedAt:m,runningForMs:r});await(0,Co.writeFile)(_,n,"utf8"),l=setInterval((()=>{E()}),5e3)},R=async()=>{a||(a=await xo.promises.open(_,"r+")),c||(c=await xo.promises.open(_,"a"))},I=async(e,t)=>{if(!v){if(v=!0,x(),p||await P(),await R(),void 0!==t){const e=ud(g),r=`\n---\n${t}\n`+(i.showElapsedTime?`elapsed_ms: ${e}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await S(r)}y=e,await E()}};try{for await(const r of o(e,i)){if("stdout"===r.type)p||(await P(),await R()),await S(r.data);else if("stderr"===r.type)p||(await P(),await R()),await S(r.data);else if("stdout_trimmed"!==r.type||d)if("stderr_trimmed"!==r.type||h)if("stdin_ready"!==r.type||u)"exit"===r.type&&await I(r.aborted?"aborted":0===r.code?"succeeded":"failed",`exit_code: ${r.code??"unknown"}`);else{u=!0,p||(await P(r.pid),await R());const e=r.stdin;if(e&&!0!==t.suppressStdinLogging){const t=e=>{if(null==e)return;const t="string"==typeof e?e:n.Buffer.isBuffer(e)||e instanceof Uint8Array?n.Buffer.from(e).toString():"";if(!t)return;const r=t.endsWith("\n")?t:`${t}\n`;S(`[stdin] ${r}`)},r=e.write.bind(e);if(e.write=(e,n,o)=>(t(e),r(e,n,o)),"function"==typeof e.end){const r=e.end.bind(e);e.end=(e,n,o)=>(void 0!==e&&t(e),r(e,n,o))}}}else h=!0,p||await P(),await R(),await S(pd("stderr"));else d=!0,p||await P(),await R(),await S(pd("stdout"));yield r}if(!v){const e=i.signal?.aborted??!1;await I(e?"aborted":"failed")}}catch(e){const t=i.signal?.aborted??!1,r=dd(e instanceof Error?e.message:"Unknown error");if(await I(t?"aborted":"failed",t?void 0:`error: ${r}`),!t)throw e}finally{if(x(),await b,a)try{await a.close()}catch{}if(c)try{await c.close()}catch{}}}}}async adopt(e){const t=s.join(this.projectDir,"terminals");await(0,Co.mkdir)(t,{recursive:!0});const r=s.join(t,`${e.shellId}.txt`),n=e.startTime,o=new Date(n).toISOString(),i=e.monotonicStartMs;let a="running";const c=ud(i),l=hd({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:a,startedAt:o,runningForMs:c})+(e.initialOutput??"");await(0,Co.writeFile)(r,l,"utf8");const u=await xo.promises.open(r,"r+");let d;try{d=await xo.promises.open(r,"a")}catch(e){throw await u.close(),e}let h=!1,p=!1,f=!1,m=!1,g=Promise.resolve();const w=async()=>{const t=ud(i),r=hd({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:a,startedAt:o,runningForMs:t});try{await u.write(r,0,"utf8")}catch{}},y=()=>(g=g.then(w).catch((()=>{})),g);let v=setInterval((()=>{y()}),5e3);const b=()=>{void 0!==v&&(clearInterval(v),v=void 0)},S=async()=>{if(!h){h=!0,b(),await g;try{await u.close()}catch{}try{await d.close()}catch{}}},k=async e=>{try{await d.write(e)}catch(e){}},_=async(t,r)=>{if(!p){if(p=!0,b(),void 0!==r){const t=ud(i),n=`\n---\n${r}\n`+(e.showElapsedTime?`elapsed_ms: ${t}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await k(n)}a=t,await y()}},C={next:async()=>{try{const t=await e.eventIterator.next();if(t.done){if(!p){const t=e.abortController.signal.aborted;await _(t?"aborted":"failed")}}else{const e=t.value;"stdout"===e.type||"stderr"===e.type?await k(e.data):"stdout_trimmed"!==e.type||f?"stderr_trimmed"!==e.type||m?"exit"===e.type&&(await _(e.aborted?"aborted":0===e.code?"succeeded":"failed",`exit_code: ${e.code??"unknown"}`),await S()):(m=!0,await k(pd("stderr"))):(f=!0,await k(pd("stdout")))}return t.done&&await S(),t}catch(t){const r=e.abortController.signal.aborted;throw await _(r?"aborted":"failed"),await S(),t}},return:async()=>{if(!p){const t=e.abortController.signal.aborted;await _(t?"aborted":"failed")}return await S(),e.eventIterator.return?e.eventIterator.return():{done:!0,value:void 0}}};return this.innerFactory.adopt({...e,eventIterator:C})}}class md{constructor(e,t){this.factory=e,this.backgroundWorkRegistry=t,this.runningShells=new Map,this.nextShellId=1e3+Math.floor(999e3*Math.random())}registerShellWork(e,t){const r=String(e.id);this.backgroundWorkRegistry?.upsertWork({id:r,kind:"shell",state:"running",metadata:Io(t),abort:()=>{this.abort(e.id)}})}clearShellWork(e){this.backgroundWorkRegistry?.clearWork(String(e))}cleanupShell(e){this.runningShells.has(e)&&(this.runningShells.delete(e),this.clearShellWork(e))}enqueueShellCompletion(e,t,r,n,o,s){if(!this.backgroundWorkRegistry)return;const i=s.aborted?"aborted":0===s.code?"success":"error",a=function(e){if(!e.aborted)return void 0!==e.signal?`signal=${e.signal}`:null!==e.code&&0!==e.code?`exit_code=${e.code}`:void 0}(s),c=function(e){if(!e.aborted)return void 0!==e.signal?{kind:"signal",signal:e.signal}:null!==e.code?{kind:"exit",code:e.code}:void 0}(s),l=n.description?.trim()?n.description:void 0,u=String(e);this.backgroundWorkRegistry.enqueue({conversationId:r??Po,id:u,source:"shell",payload:{taskId:u,...void 0!==t?{toolCallId:t}:{},kind:"shell",status:i,title:n.description||n.command,...a?{detail:a}:{},...s.outputPath?{outputPath:s.outputPath}:{},reason:"task_finished",durationMs:ud(o),...c?{shellEnd:c}:{},...l?{description:l}:{}}})}async spawn(e,t){const r=await this.factory.spawn(e,t),n=Date.now(),o=performance.now();return this.runningShells.set(r.id,r),this.registerShellWork(r,{title:e.description||e.command,cwd:e.workingDirectory,startTimeMs:n}),r.signal.addEventListener("abort",(()=>{this.cleanupShell(r.id)})),r.onComplete?.((t=>{this.enqueueShellCompletion(r.id,e.toolCallId,e.conversationId,{command:e.command,description:e.description},o,t),this.cleanupShell(r.id)})),{shellId:r.id,pid:r.pid}}async adopt(e){const t=await this.factory.adopt(e);return this.runningShells.set(t.id,t),this.registerShellWork(t,{title:e.description||e.command,cwd:e.workingDirectory,startTimeMs:e.startTime}),t.signal.addEventListener("abort",(()=>{this.cleanupShell(t.id),e.onCleanup?.()})),t.onComplete?.((r=>{this.enqueueShellCompletion(t.id,e.toolCallId,void 0,{command:e.command,description:e.description},e.monotonicStartMs,r),this.cleanupShell(t.id),e.onCleanup?.()})),{shellId:t.id,pid:e.pid}}generateShellId(){for(let e=0;e<=998999;e++){this.nextShellId>999999&&(this.nextShellId=1e3);const e=this.nextShellId;if(this.nextShellId+=1,!this.runningShells.has(e))return e}throw new Error("No available background shell id in range")}abort(e){const t=this.runningShells.get(e);return!!t&&(t.abort(),this.runningShells.delete(e),this.clearShellWork(e),!0)}isRunning(e){return this.runningShells.has(e)}dispose(){for(const[e,t]of this.runningShells)t.dispose(),this.clearShellWork(e);this.runningShells.clear()}async writeStdin(e,t){const r=this.runningShells.get(e);if(!r)throw new Error("Shell not found");if(!r.stdin)throw new Error("Shell stdin not available");const n=t.indexOf(""),o=-1!==n?n:t.indexOf("\\u0004");if(-1!==o){const e=t.substring(0,o);e.length>0&&await new Promise(((t,n)=>{r.stdin.write(e,(e=>{e?n(e):t(void 0)}))})),r.stdin.end()}else await new Promise(((e,n)=>{r.stdin.write(t,(t=>{t?n(t):e(void 0)}))}))}}new WeakMap;class gd{constructor(e,t){this.inner=e,this.ownerConversationId=t}enqueue(e){this.inner.enqueue({...e,conversationId:this.ownerConversationId})}enqueueCompletion(e){this.enqueue({conversationId:this.ownerConversationId,id:e.taskId,source:e.kind,payload:e})}pull(e){return this.inner.pull(e)}ack(e){return this.inner.ack(e)}nack(e,t){this.inner.nack(e,t)}suppress(e,t){this.inner.suppress(e,t)}upsertWork(e){this.inner.upsertWork(e)}clearWork(e){return this.inner.clearWork(e)}abortWork(e){return this.inner.abortWork(e)}hasRunningWork(e){return this.inner.hasRunningWork(e)}abortAllWork(e){return this.inner.abortAllWork(e)}listWork(e){return this.inner.listWork(e)}drainCompletions(){return this.inner.drainCompletions()}hasPendingCompletions(e){return this.inner.hasPendingCompletions(e)}markAwaitedCompletion(e){this.inner.suppress(this.ownerConversationId,e)}}class wd{constructor(e,t,r,n,o,s,i,a){if(this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r,void 0!==a)return this.backgroundShellManager=a,void(this.ownsBackgroundShellManager=!1);const c=s&&void 0!==i?new gd(s,i):s,l=o??function(e){const t=new ld;return new fd(t,e)}(n),u=new cd(l,n,c);this.backgroundShellManager=new md(u,c),this.ownsBackgroundShellManager=!0}getManager(){return this.backgroundShellManager}dispose(){this.ownsBackgroundShellManager&&this.backgroundShellManager.dispose()}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,$.VI)(e.withName("LocalBackgroundShellExecutor.execute")),!1);const n=t.command,o=t.sandboxPolicy?ls(t.sandboxPolicy):void 0,s=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),i=(0,Yo.o1)(s),a=new he.HO(Wo(n).structured),c=ks({command:n,parsingResult:a,blockedCommands:t.adminCommandDenylist});if(void 0!==c)return new Do.Lt({result:{case:"rejected",value:new he.pZ({command:n,workingDirectory:i,reason:c})}});let l;if(rd.info(e,"Background shell: approval gate reached",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,hasSmartModeApproval:void 0!==t.smartModeApproval,hasSmartModeApprovalReason:void 0!==t.smartModeApproval?.reason,hasSmartModeApprovalRequestId:void 0!==t.smartModeApproval?.requestId,requestedPolicyType:o?.type??"undefined",parserCommandCount:a.executableCommands.length,classifierCommandCount:t.classifierResult?.commands.length??0,commandLength:n.length}),Mo(t)){const r=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:i,skipUnsafeWorkingDirectoryBlock:!0,command:n,parsingResult:a,toolCallId:t.toolCallId,resolveSkippedApprovalPolicy:!0},o);if("block"===r.kind)return rd.info(e,"Background shell: invariant blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,skipApproval:t.skipApproval}),nd(n,i,r.reason);l=r.policy??o,rd.info(e,"Background shell: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:o?.type??"undefined",effectivePolicyType:l?.type??"undefined"})}else{const r=await this.permissionsService.shouldBlockShellCommand(e,n,{workingDirectory:i,timeout:0,parsingResult:a,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Ao(t)},o);if("block"===r.kind)return rd.info(e,"Background shell: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),nd(n,i,r.reason);l=r.policy,rd.info(e,"Background shell: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:l.type})}l=await Tc(l,{command:n,workingDirectory:i,parsingResult:a,permissionsService:this.permissionsService,ignoreService:this.ignoreService});try{const r=this.backgroundShellManager.generateShellId(),o=l?{perUser:l}:void 0,s={ctx:e,command:n,workingDirectory:i,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:o,shellId:r,enableWriteShellStdinTool:t.enableWriteShellStdinTool,suppressStdinLogging:t.suppressStdinLogging,description:t.description,outputNotification:t.outputNotification},a=await this.backgroundShellManager.spawn(s,this.coreExecutor);return new Do.Lt({result:{case:"success",value:new Do.Po({shellId:r,command:n,workingDirectory:i,pid:a.pid})}})}catch(r){if(r instanceof Oo.SandboxUnsupportedError){const o=l?.type??"unknown";return rd.debug(e,"Background shell: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:o,reason:r.reason}),new Do.Lt({result:{case:"sandboxUnsupported",value:new he.rI({command:n,workingDirectory:i,sandboxPolicyType:o,reason:r.reason??r.message,isReadonly:"workspace_readonly"===o})}})}return new Do.Lt({result:{case:"error",value:new Do.Of({command:n,workingDirectory:i,error:r instanceof Error?r.message:"Unknown error"})}})}}catch(e){r.error=e,r.hasError=!0}finally{td(r)}}writeStdin(e,t){return this.backgroundShellManager.writeStdin(e,t)}}var yd=r("node:async_hooks");r("../../node_modules/.pnpm/minimatch@10.2.5/node_modules/minimatch/dist/esm/index.js");function vd(e){return e instanceof Error?e.message:String(e)}function bd(e){return"Failed to read skill file: "+vd(e)}function Sd(e){return"Invalid skill frontmatter: "+vd(e)}function kd(e,t){return e||t?void 0:"Description is required"}new Set(["EACCES","EPERM","ENOENT","ENOTDIR","EISDIR","ELOOP","ENAMETOOLONG"]);const _d=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function Cd(e){return e.toLocaleString("en-US")}var Ed=r("node:url");const xd={beforeShellExecution:"beforeShellExecution",beforeMCPExecution:"beforeMCPExecution",afterShellExecution:"afterShellExecution",afterMCPExecution:"afterMCPExecution",beforeReadFile:"beforeReadFile",afterFileEdit:"afterFileEdit",beforeTabFileRead:"beforeTabFileRead",afterTabFileEdit:"afterTabFileEdit",stop:"stop",beforeSubmitPrompt:"beforeSubmitPrompt",afterAgentResponse:"afterAgentResponse",afterAgentThought:"afterAgentThought",sessionStart:"sessionStart",sessionEnd:"sessionEnd",preCompact:"preCompact",subagentStart:"subagentStart",subagentStop:"subagentStop",preToolUse:"preToolUse",postToolUse:"postToolUse",postToolUseFailure:"postToolUseFailure",workspaceOpen:"workspaceOpen"},Pd=e=>"string"==typeof e,Rd=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),Id=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),Td=(e,t=[])=>({isValid:e,errors:t});function Ad(e,t,r){void 0===e||Pd(e)||r.push(`${t} must be a string if provided`)}const $d=e=>{const t=[];if(!Rd(e))return t.push("Hook script must be an object with either a 'command' property (command hook) or 'type: \"prompt\"' with a 'prompt' property (prompt hook)"),Td(!1,t);const r=e.type;return"prompt"===r?((e,t)=>{Pd(e.prompt)?""===e.prompt.trim()&&t.push("Prompt hook 'prompt' property cannot be empty"):t.push("Prompt hook must have a 'prompt' property (string)"),void 0!==e.model&&(Pd(e.model)?""===e.model.trim()&&t.push("Prompt hook 'model' cannot be an empty string"):t.push("Prompt hook 'model' must be a string if provided"))})(e,t):"command"===r||void 0===r?((e,t)=>{Pd(e.command)||t.push("Hook script command must be a string")})(e,t):t.push(`Invalid hook type: "${r}". Must be "command", "prompt", or omitted (defaults to "command")`),((e,t)=>{if(void 0!==e.matcher)if(Pd(e.matcher)){if(""!==e.matcher&&"*"!==e.matcher)try{new RegExp(e.matcher)}catch(r){t.push(`Hook script matcher "${e.matcher}" is not a valid regex: ${r?.message??String(r)}`)}}else t.push("Hook script matcher must be a string if provided");if(void 0!==e.timeout&&("number"!=typeof e.timeout?t.push("Hook script timeout must be a number (seconds)"):e.timeout<=0?t.push("Hook script timeout must be a positive number"):e.timeout>3600&&console.warn(`[hooks] Hook timeout of ${e.timeout}s is very long (>1 hour)`)),void 0!==e.loop_limit){const r=e.loop_limit;null!==r&&("number"!=typeof r?t.push("Hook script loop_limit must be a positive integer or null"):Number.isInteger(r)?r<=0&&t.push("Hook script loop_limit must be a positive integer (use null for no limit)"):t.push("Hook script loop_limit must be an integer"))}void 0!==e.failClosed&&"boolean"!=typeof e.failClosed&&t.push("Hook script failClosed must be a boolean")})(e,t),Td(0===t.length,t)},Md=(e,t)=>{const r=[];if(!Array.isArray(e))return r.push(`${t} must be an array of hook scripts`),Td(!1,r);for(let n=0;n{const t=[];if(!Rd(e))return t.push("Hooks config must be an object"),Td(!1,t);if("number"!=typeof e.version?t.push("Config version must be a number"):(!Number.isInteger(e.version)||e.version<1)&&t.push("Config version must be a positive integer"),!Rd(e.hooks))return t.push("Config hooks must be an object"),Td(!1,t);void 0!==e.stop_hook_loop_limit&&console.warn("[hooks] DEPRECATION WARNING: 'stop_hook_loop_limit' is deprecated. Use 'loop_limit' on individual hook scripts instead. The configured value is being ignored.");const r=Object.values(xd),n=e.hooks;for(const[e,o]of Object.entries(n))if(r.includes(e)){if(void 0!==o){const r=Md(o,e);r.isValid||t.push(...r.errors)}}else t.push(`Unknown hook type: ${e}. Valid types are: ${r.join(", ")}`);return Td(0===t.length,t)},Od={PreToolUse:xd.preToolUse,PermissionRequest:null,PostToolUse:xd.postToolUse,UserPromptSubmit:xd.beforeSubmitPrompt,Stop:xd.stop,SubagentStop:xd.subagentStop,SessionStart:xd.sessionStart,SessionEnd:xd.sessionEnd,PreCompact:xd.preCompact,Notification:null},Fd=Object.fromEntries(Object.entries(Od).filter((e=>Nd(e[0])&&null!==e[1])).map((([e,t])=>[t,e])));function Nd(e){return Object.prototype.hasOwnProperty.call(Od,e)}const Ld={Bash:"Shell",Read:"Read",Write:"Write",Edit:"Write",Glob:null,Grep:"Grep",WebFetch:"WebFetch",WebSearch:"WebSearch",Task:"Task"},jd=["Glob"],Ud=["Notification","PermissionRequest"],Bd=/^[A-Za-z0-9_./:=+-]+$/,Wd=/^=|^-.*\./,Hd=/\$\{(?:CLAUDE_PROJECT_DIR|CURSOR_PROJECT_DIR|CLAUDE_PLUGIN_ROOT|CURSOR_PLUGIN_ROOT)\}/g,qd=/^[^\p{Cc}$`"]*$/u,zd=/\\(?:[$`"\\]|$)/;function Gd(e){return`'${e.replace(/'/g,"'\\''")}'`}function Vd(e){if(Bd.test(e)&&!Wd.test(e))return e;const t=e.replace(Hd,"");if((t!==e||e.includes("'"))&&qd.test(t)&&!zd.test(e))return`"${e}"`;const r=[];let n=0;for(const t of e.matchAll(Hd))t.index>n&&r.push(Gd(e.slice(n,t.index))),r.push(`"${t[0]}"`),n=t.index+t[0].length;return(n{},info:()=>{}};function Jd(e,t,r=Kd){const n={loop_limit:null,failClosed:!1};if(t&&"*"!==t&&(n.matcher=t),void 0!==e.timeout&&(n.timeout=e.timeout),"prompt"===e.type)return e.prompt?{type:"prompt",prompt:e.prompt,...n}:null;const o=function(e,t){const r=e.command;if(!r)return null;const n=e.args;return null==n?(void 0!==e.shell&&t.warn(`Hook "${r}" sets shell "${e.shell}", which Cursor does not support; the platform default shell will be used`),r):(o=n,Array.isArray(o)&&o.every((e=>"string"==typeof e))?function(e,t){return[e,...t].map(Vd).join(" ")}(r,n):(t.warn(`Hook "${r}" has invalid "args" (expected an array of strings), skipping`),null));var o}(e,r);return null===o?null:{type:"command",command:o,...n}}function Zd(e,t,r=Kd){const n=[];let o;if("PreToolUse"===t||"PostToolUse"===t){const t=function(e,t=Kd){if(!e||"*"===e)return"*";const r=e.split("|"),n=[],o=[];for(const e of r){const t=e.trim();if(t.startsWith("mcp__")){const e=t.split("__");if(e.length>=3){const t=e.slice(2).join("__");n.push(`MCP:${t}`);continue}}const r=Ld[t];null!==r?void 0!==r?n.includes(r)||n.push(r):n.push(t):jd.includes(t)&&o.push(`Tool "${t}" is not supported in Cursor and will be ignored`)}for(const e of o)t.warn(e);return 0===n.length?null:n.join("|")}(e.matcher,r);if(null===t)return r.warn(`All tools in matcher "${e.matcher}" are unsupported, skipping hooks`),[];o="*"===t?void 0:t}else"SessionStart"===t||"PreCompact"===t?(e.matcher&&"*"!==e.matcher&&""!==e.matcher&&("SessionStart"===t?["startup","resume","clear","compact"].includes(e.matcher):["manual","auto"].includes(e.matcher))&&r.warn(`${t} trigger matcher "${e.matcher}" is not supported in Cursor, hooks will fire for all triggers`),o=void 0):o=void 0;for(const t of e.hooks){const e=Jd(t,o,r);e&&n.push(e)}return n}function Xd(e,t=Kd){const r={};for(const[n,o]of Object.entries(e)){if(!Nd(n)){t.warn(`Unknown Claude Code event "${n}", skipping`);continue}if(Ud.includes(n)){t.warn(`Claude Code event "${n}" is not supported in Cursor and will be ignored`);continue}const e=Od[n];if(!e){t.warn(`Unknown Claude Code event "${n}", skipping`);continue}const s=[];if(Array.isArray(o))for(const e of o){const r=Zd(e,n,t);s.push(...r)}else void 0!==o&&t.warn(`Claude Code event "${n}" has invalid value (expected array), skipping`);if(s.length>0){const t=r[e]||[];r[e]=[...t,...s]}}return{version:1,hooks:r}}var Qd=r("../../node_modules/.pnpm/gray-matter@4.0.3/node_modules/gray-matter/index.js");const Yd=()=>({});function eh(e,t){return Qd(e,{...t,engines:{...t?.engines,js:Yd,javascript:Yd}})}function th(e,t,r){return Qd.stringify({content:e,data:{}},t,r)}var rh=r("node:zlib");function nh(e,t){const r=function(e){return e.split(/[/\\]/).filter((e=>e))}(e);for(let e=0;ee.isDirectory())).map((e=>e.name))}catch{return[]}}async removeVersion(e){const t=this.getCacheDir(e);try{await(0,Co.rm)(t,{recursive:!0,force:!0})}catch{}}async removeAllVersions(e){const t=dh(this.cacheRoot,e);await(0,Co.rm)(t,{recursive:!0,force:!0})}async pruneOldVersions(e){const t=await this.listCachedVersions({marketplaceSlug:e.marketplaceSlug,pluginId:e.pluginId}),r=new Set(e.keepVersions.map((e=>lh(e))));for(const n of t)r.has(n)||await this.removeVersion({marketplaceSlug:e.marketplaceSlug,pluginId:e.pluginId,version:n})}async markCacheComplete(e){const t=this.getCacheDir(e);await(0,Co.writeFile)(uh({parent:t,name:ch}),"")}}class ph extends Error{constructor(e,t){super(t),this.reason=e,this.name="PluginContentInstallError"}}const fh=(0,zs.promisify)(rh.gunzip),mh=/^[A-Za-z0-9._-]{1,128}$/,gh=/^[0-9a-f]{64}$/,wh=/^[1-9]\d{0,18}$/,yh="backend-content://",vh="backend-content/",bh=new Map([[3,"request_refused"],[5,"not_found"],[9,"account_not_connected"],[10,"revision_superseded"],[12,"unsupported_server"],[14,"unavailable"]]),Sh=new Set(["unavailable","revision_superseded","timeout","download_failed","integrity"]);function kh(e){return e instanceof ph&&Sh.has(e.reason)}class _h{constructor(){this.awaited=new Map}forListing(e){return{startLoad:()=>{for(const[t,r]of this.awaited)r.listing===e&&(r.attemptedThisLoad?r.attemptedThisLoad=!1:this.awaited.delete(t))},heldFailure:({pluginDbId:e,revision:t})=>{const r=this.awaited.get(e);if(void 0!==r&&r.revision===t)return r.attemptedThisLoad=!0,Date.now(){kh(n)?this.awaited.set(t,{revision:r,reason:n.reason,retryAtMs:Date.now()+6e4,listing:e,attemptedThisLoad:!0}):this.awaited.delete(t)},isRetryDue:()=>this.isRetryDue(),allowImmediateRetry:()=>this.allowImmediateRetry()}}isRetryDue(){const e=Date.now();return[...this.awaited.values()].some((t=>e>=t.retryAtMs))}allowImmediateRetry(){for(const e of this.awaited.values())e.retryAtMs=0}}function Ch(e){if("bigint"!=typeof e&&"number"!=typeof e&&"string"!=typeof e)return;const t=String(e);return wh.test(t)?t:void 0}function Eh(e){return e.startsWith(yh)}function xh(e){return`${vh}${e}`}function Ph(e,t){return new ph(e,function(e,t){const r=JSON.stringify(t);switch(e){case"unsupported_client":return`Plugin ${r} could not be downloaded: this client cannot install plugins whose files the server provides.`;case"not_found":return`Plugin ${r} could not be downloaded: it no longer exists or you no longer have access to it.`;case"account_not_connected":return`Plugin ${r} could not be downloaded: connect your account on the host of its source repository first.`;case"revision_superseded":return`Plugin ${r} changed while it was downloading. The new version installs on the next plugin refresh.`;case"unavailable":return`Plugin ${r} could not be downloaded: its files cannot be served right now. It installs on a later plugin refresh.`;case"unsupported_server":return`Plugin ${r} could not be downloaded: this server does not provide plugin files.`;case"request_refused":return`Plugin ${r} could not be downloaded: the server refused the request.`;case"download_failed":return`Plugin ${r} could not be downloaded.`;case"timeout":return`Downloading plugin ${r} timed out.`;case"integrity":return`The download of plugin ${r} did not match the size or hash the server gave for it, so it was discarded.`;case"too_large":return`Plugin ${r} could not be downloaded: its files are larger than this client accepts.`;case"unsafe_archive":return`The download of plugin ${r} could not be unpacked safely, so it was discarded.`;case"unpack_failed":return`The download of plugin ${r} could not be written to the plugin cache.`;default:return e}}(e,t))}function Rh(e){if("File"!==e.type&&"OldFile"!==e.type&&"Directory"!==e.type)return!0;const t=e.path;return!(0!==t.length&&!t.includes("\0")&&!/^([/\\]|[A-Za-z]:)/.test(t))||t.split(/[/\\]/).includes("..")}async function Ih(e){const{download:t,pluginName:r,content:n,targetDir:o}=e;if(void 0===t)throw Ph("unsupported_client",r);const s=new AbortController;let i;try{i=await async function(e){const t=e[Symbol.asyncIterator](),r=()=>(0,Or.wj)(t.next(),12e4);try{const e=await r();if(!0===e.done||"header"!==e.value.part.case)return"integrity";const{sha256:t}=e.value.part.value,n=function(e){let t;if("bigint"==typeof e||"number"==typeof e)t=Number(e);else{if("string"!=typeof e||!/^\d{1,15}$/.test(e))return;t=Number(e)}return Number.isSafeInteger(t)&&t>0?t:void 0}(e.value.part.value.sizeBytes);if(void 0===n||"string"!=typeof t||!gh.test(t))return"integrity";if(n>16777216)return"too_large";const o=[];let s=0;for(;;){const e=await r();if(!0===e.done)break;const{part:t}=e.value;if(void 0!==t.case){if("data"!==t.case||0===t.value.byteLength)return"integrity";if(s+=t.value.byteLength,s>n)return"integrity";o.push(t.value)}}const i=Buffer.concat(o,s);return s===n&&(0,bo.createHash)("sha256").update(i).digest("hex")===t?i:"integrity"}finally{Promise.resolve(t.return?.()).catch((()=>{}))}}(t({pluginId:BigInt(e.pluginDbId),revision:n.revision},{signal:s.signal}))}catch(e){throw Ph(function(e){return e instanceof Or.MU?"timeout":"object"==typeof e&&null!==e&&"code"in e?"number"!=typeof e.code?"download_failed":bh.get(e.code)??"download_failed":"download_failed"}(e),r)}finally{s.abort()}if("string"==typeof i)throw Ph(i,r);const a=await async function(e){let t;try{t=await fh(e,{maxOutputLength:268435456})}catch{return}const r=t.byteLength>=512,n=r&&31===t[0]&&139===t[1],o=r&&682962941===t.readUInt32BE(0);if(r&&!n&&!o)return t}(i);if(void 0===a||!await function(e){return new Promise((t=>{let r=0;const n=(0,sh.p_)({strict:!0,onReadEntry:e=>{r+=1,(r>5e4||Rh(e))&&(t(!1),n.abort(new Error("unsafe entry")))}});n.once("end",(()=>t(r>0))),n.once("error",(()=>t(!1))),n.end(e)}))}(a))throw Ph("unsafe_archive",r);try{await async function(e,t){const r=(0,sh.o6)({cwd:t,strict:!0,preserveOwner:!1,filter:(e,t)=>{if(!("type"in t)||Rh(t))return!1;const r=!!(64&(t.mode??0));return t.mode="Directory"===t.type||r?493:420,!0}});await new Promise(((t,n)=>{r.once("close",t),r.once("error",n),r.end(e)}))}(a,o)}catch{throw Ph("unpack_failed",r)}}function Th(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")||"/"}function Ah(e,t){if(Object.hasOwn(e,t))return e[t]}function $h(e,t,r,n){const o=e?.plugins;if(!o||"object"!=typeof o)return[];const s=t?.enabledPlugins??{},i={};r?.enabledPlugins&&Object.assign(i,r.enabledPlugins);const a=void 0!==n?Th(n):void 0,c=new Set,l=[];for(const[e,t]of Object.entries(o)){if(!Array.isArray(t)||0===t.length)continue;if(void 0!==a&&!1===Ah(i,e))continue;let r;void 0!==a&&(r=t.find((t=>!("project"!==t.scope&&"local"!==t.scope||!t.projectPath)&&(Th(t.projectPath)===a&&!0===Ah(i,e))))),r||!0!==Ah(s,e)||(r=t.find((e=>"user"===e.scope))),r?.installPath&&!c.has(e)&&(l.push({pluginId:e,installPath:r.installPath}),c.add(e))}return l}var Mh=r("../../node_modules/.pnpm/js-yaml@4.3.1/node_modules/js-yaml/dist/js-yaml.mjs");const Dh=je.enum(["canvas"]),Oh=je.array(Dh).transform((e=>[...new Set(e)].sort())),Fh=new Set(["https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","https://agent-plugins.org/schemas/1.0.0/mcp.schema.json"]),Nh=/^v?(\d+\.\d+(?:\.\d+)?)$/;function Lh(e){if("object"!=typeof(t=e)||null===t||Array.isArray(t))return;var t;const r=e.$schema;return"string"==typeof r&&r.length>0?r:void 0}function jh(e){let t;try{t=new URL(e).pathname.split("/")}catch{t=e.split("/")}for(const e of t){const t=Nh.exec(e);if(null!==t)return t[1]}}function Uh(e){return void 0===e?{kind:"absent"}:Fh.has(e)?{kind:"supported",id:e,version:jh(e)??e}:{kind:"unsupported",id:e}}const Bh=10485760,Wh=/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/,Hh=[".cursor-plugin/plugin.json",".claude-plugin/plugin.json","plugin.json"],qh=[".cursor-plugin",".claude-plugin"],zh=[".cursor-plugin/marketplace.json",".claude-plugin/marketplace.json"],Gh=je.object({source:je.literal("github"),repo:je.string().regex(/^[^/]+\/[^/]+$/,"Must be in owner/repo format"),ref:je.string().optional(),sha:je.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Vh=je.object({source:je.literal("url"),url:je.string().url().endsWith(".git","URL must end with .git"),ref:je.string().optional(),sha:je.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Kh=je.object({source:je.literal("git-subdir"),url:je.string().url().endsWith(".git","URL must end with .git"),path:je.string().min(1),ref:je.string().optional(),sha:je.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Jh=je.union([je.string(),Gh,Vh,Kh]),Zh=/^(\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?|never)$/,Xh='Must be a semver version (X.Y.Z) or "never"',Qh=je.object({cursor:je.string().regex(Zh,Xh).optional(),sand:je.string().regex(Zh,Xh).optional(),sandMobile:je.string().regex(Zh,Xh).optional()}),Yh=je.object({name:je.string().min(1,"Author name is required"),email:je.string().email().optional()}),ep=je.enum(["string","number","integer","boolean","object","array","null"]),tp=je.union([ep,je.array(ep).nonempty().superRefine(((e,t)=>{new Set(e).size!==e.length&&t.addIssue({code:je.ZodIssueCode.custom,message:"Schema type arrays must not contain duplicates"})}))]);function rp(e,t){if(void 0!==e.required)if(void 0===e.properties)for(const r of e.required)t.addIssue({code:je.ZodIssueCode.custom,message:`Required property "${r}" must be declared in properties`,path:["required"]});else for(const r of e.required)r in e.properties||t.addIssue({code:je.ZodIssueCode.custom,message:`Required property "${r}" must be declared in properties`,path:["required"]});void 0!==e.minLength&&void 0!==e.maxLength&&e.minLength>e.maxLength&&t.addIssue({code:je.ZodIssueCode.custom,message:"minLength must be less than or equal to maxLength",path:["minLength"]}),void 0!==e.minimum&&void 0!==e.maximum&&e.minimum>e.maximum&&t.addIssue({code:je.ZodIssueCode.custom,message:"minimum must be less than or equal to maximum",path:["minimum"]}),void 0!==e.exclusiveMinimum&&void 0!==e.exclusiveMaximum&&e.exclusiveMinimum>=e.exclusiveMaximum&&t.addIssue({code:je.ZodIssueCode.custom,message:"exclusiveMinimum must be less than exclusiveMaximum",path:["exclusiveMinimum"]}),void 0!==e.minItems&&void 0!==e.maxItems&&e.minItems>e.maxItems&&t.addIssue({code:je.ZodIssueCode.custom,message:"minItems must be less than or equal to maxItems",path:["minItems"]}),void 0!==e.minProperties&&void 0!==e.maxProperties&&e.minProperties>e.maxProperties&&t.addIssue({code:je.ZodIssueCode.custom,message:"minProperties must be less than or equal to maxProperties",path:["minProperties"]})}const np=je.lazy((()=>je.object({type:tp.optional(),title:je.string().optional(),description:je.string().optional(),format:je.string().optional(),writeOnly:je.boolean().optional(),placeholder:je.string().optional(),default:je.unknown().optional(),enum:je.array(je.any()).nonempty().optional(),const:je.unknown().optional(),properties:je.record(je.string(),np).optional(),required:je.array(je.string()).optional(),additionalProperties:je.union([je.boolean(),np]).optional(),items:je.union([np,je.array(np)]).optional(),minLength:je.number().int().nonnegative().optional(),maxLength:je.number().int().nonnegative().optional(),minimum:je.number().optional(),maximum:je.number().optional(),exclusiveMinimum:je.number().optional(),exclusiveMaximum:je.number().optional(),multipleOf:je.number().positive().optional(),minItems:je.number().int().nonnegative().optional(),maxItems:je.number().int().nonnegative().optional(),uniqueItems:je.boolean().optional(),minProperties:je.number().int().nonnegative().optional(),maxProperties:je.number().int().nonnegative().optional()}).strict().superRefine(rp)));function op(e){const t=np.superRefine(((e,t)=>{ap(e)&&"object"===e.type||t.addIssue({code:je.ZodIssueCode.custom,message:'Plugin variable schemas must declare type "object"',path:["type"]})})).safeParse(e);return t.success?cp(t.data)?{success:!0,data:t.data}:{success:!1,error:new je.ZodError([{code:"custom",path:["type"],message:'Plugin variable schemas must declare type "object"'}])}:{success:!1,error:t.error}}const sp=je.unknown().superRefine(((e,t)=>{const r=op(e);if(!r.success)for(const e of r.error.issues)t.addIssue({code:"custom",message:e.message,path:e.path})})).transform((e=>{if(!cp(e))throw new Error('Plugin variable schema must declare type "object"');return e})),ip=(je.object({name:je.string().min(1).transform((e=>e.toLowerCase())).refine((e=>Wh.test(e)),"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:je.string().optional(),source:Jh,description:je.string().optional(),version:je.string().optional(),author:Yh.optional(),publisher:je.string().min(1).optional(),homepage:je.string().url().optional(),repository:je.string().url().optional(),license:je.string().optional(),keywords:je.array(je.string()).optional(),capabilities:Oh.optional(),logo:je.string().optional(),category:je.string().optional(),tags:je.array(je.string()).optional(),minClientVersions:Qh.optional(),strict:je.boolean().default(!0),commands:je.union([je.string(),je.array(je.string())]).optional(),agents:je.union([je.string(),je.array(je.string())]).optional(),skills:je.union([je.string(),je.array(je.string())]).optional(),rules:je.union([je.string(),je.array(je.string())]).optional(),hooks:je.union([je.string(),je.record(je.string(),je.unknown())]).optional(),variables:sp.optional(),mcpServers:je.union([je.string(),je.record(je.string(),je.unknown()),je.array(je.union([je.string(),je.record(je.string(),je.unknown())]))]).optional()}),je.object({description:je.string().optional(),version:je.string().optional(),pluginRoot:je.string().optional()}),je.object({name:je.string().min(1).regex(Wh,"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:je.string().optional(),description:je.string().optional(),version:je.string().optional(),author:Yh.optional(),publisher:je.string().min(1).optional(),homepage:je.string().url().optional(),repository:je.string().url().optional(),license:je.string().optional(),logo:je.string().optional(),keywords:je.array(je.string()).optional(),capabilities:Oh.optional(),minClientVersions:Qh.optional(),commands:je.union([je.string(),je.array(je.string())]).optional(),agents:je.union([je.string(),je.array(je.string())]).optional(),skills:je.union([je.string(),je.array(je.string())]).optional(),rules:je.union([je.string(),je.array(je.string())]).optional(),hooks:je.union([je.string(),je.record(je.string(),je.unknown())]).optional(),variables:sp.optional(),mcpServers:je.union([je.string(),je.record(je.string(),je.unknown()),je.array(je.union([je.string(),je.record(je.string(),je.unknown())]))]).optional()}));function ap(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function cp(e){return ap(e)&&"object"===e.type}function lp(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function up(e,t){if(ap(e)&&"string"==typeof e.name){const t=lp(e.name);if(t.length>0)return t}return function(e){const t=void 0!==e.repoName?lp(e.repoName):"";return t.length>0?t:`cursor-marketplace-${e.fallbackId??(0,bo.randomUUID)()}`}(t)}function dp(e){if(ap(e)&&ap(e.owner)){const t="string"==typeof e.owner.name&&e.owner.name.trim().length>0?e.owner.name:"Unknown",r="string"==typeof e.owner.email&&e.owner.email.trim().length>0?e.owner.email:void 0;return{name:t,...void 0!==r?{email:r}:{}}}return{name:"Unknown"}}function hp(e){return"string"==typeof e?e:void 0}function pp(e){if(!Array.isArray(e))return;const t=e.filter((e=>"string"==typeof e));return t.length>0?t:void 0}function fp(e){return"string"==typeof e?e:pp(e)}function mp(e){if(!ap(e)||!ap(e.metadata))return;const t={description:hp(e.metadata.description),version:hp(e.metadata.version),pluginRoot:hp(e.metadata.pluginRoot)};return void 0!==t.description||void 0!==t.version||void 0!==t.pluginRoot?t:void 0}function gp(e){if(!ap(e))return;const t=hp(e.name);if(void 0===t||0===t.length)return;const r=hp(e.email);return{name:t,...void 0!==r?{email:r}:{}}}function wp(e){if("string"==typeof e||ap(e))return e;if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e||ap(e)));return t.length>0?t:void 0}}function yp(e){if("string"==typeof e||ap(e))return e}function vp(e){if(void 0===e)return;const t=op(e);return t.success?t.data:void 0}function bp(e,t={}){if(e.length>Bh)return{success:!1,error:"Manifest exceeds maximum size of 10485760 bytes"};let r;try{r=JSON.parse(e)}catch(e){return{success:!1,error:`Invalid JSON: ${e instanceof Error?e.message:"Unknown error"}`}}if(!ap(r))return{success:!1,error:"Invalid marketplace manifest: expected a JSON object"};const n=[],o=[],i=new Set;return(Array.isArray(r.plugins)?r.plugins:[]).forEach(((e,t)=>{const r=function(e,t){if(!ap(e))return{skippedEntry:{index:t,error:`Plugin entry at index ${t} is not an object`}};const r="string"==typeof(n=e.source)?n:ap(n)?"github"===n.source&&"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:hp(n.ref),sha:hp(n.sha)}:("url"===n.source||void 0===n.source)&&"string"==typeof n.url&&n.url.length>0?{source:"url",url:n.url,ref:hp(n.ref),sha:hp(n.sha)}:"git-subdir"===n.source&&"string"==typeof n.url&&n.url.length>0&&"string"==typeof n.path&&n.path.length>0?{source:"git-subdir",url:n.url,path:n.path,ref:hp(n.ref),sha:hp(n.sha)}:"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:hp(n.ref),sha:hp(n.sha)}:void 0:void 0;var n;if(void 0===r){const r=hp(e.name);return{skippedEntry:{index:t,...void 0!==r&&r.length>0?{name:r}:{},error:`Plugin entry at index ${t} has no usable source`}}}const o=("string"==typeof e.name?lp(e.name):"")||function(e){if("string"==typeof e){const t=lp((0,s.basename)(e));return t.length>0?t:void 0}if("github"===e.source){const t=lp(e.repo.split("/").at(-1)??"");return t.length>0?t:void 0}if("git-subdir"===e.source){const t=lp((0,s.basename)(e.path));return t.length>0?t:void 0}let t=e.url;try{t=new URL(e.url).pathname}catch{}for(;t.endsWith("/");)t=t.slice(0,-1);t.toLowerCase().endsWith(".git")&&(t=t.slice(0,-4));const r=lp((0,s.basename)(t));return r.length>0?r:void 0}(r);if(void 0===o)return{skippedEntry:{index:t,error:`Plugin entry at index ${t} has no usable name`}};const i=Oh.safeParse(e.capabilities);if(void 0!==e.capabilities&&!i.success)return{skippedEntry:{index:t,name:o,error:`Plugin entry at index ${t} has invalid capabilities: ${i.error.issues.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`}};const a=i.success?i.data:void 0,c=function(e){const t=Qh.safeParse(e);if(t.success&&(void 0!==t.data.cursor||void 0!==t.data.sand||void 0!==t.data.sandMobile))return t.data}(e.minClientVersions);return{entry:{name:o,displayName:hp(e.displayName),source:r,description:hp(e.description),version:hp(e.version),author:gp(e.author),publisher:hp(e.publisher),homepage:hp(e.homepage),repository:hp(e.repository),license:hp(e.license),keywords:pp(e.keywords),logo:hp(e.logo),category:hp(e.category),tags:pp(e.tags),strict:"boolean"!=typeof e.strict||e.strict,commands:fp(e.commands),agents:fp(e.agents),skills:fp(e.skills),rules:fp(e.rules),hooks:yp(e.hooks),variables:vp(e.variables),mcpServers:wp(e.mcpServers),...void 0!==a&&{capabilities:a},...void 0!==c&&{minClientVersions:c}}}}(e,t);"skippedEntry"in r?o.push(r.skippedEntry):i.has(r.entry.name)?o.push({index:t,name:r.entry.name,error:`Duplicate plugin name "${r.entry.name}" at index ${t}`}):(i.add(r.entry.name),n.push(r.entry))})),{success:!0,data:{name:up(r,t),owner:dp(r),description:hp(r.description),plugins:n,metadata:mp(r),skippedPluginEntries:o}}}function Sp(e){if(e.length>Bh)return{success:!1,error:"Manifest exceeds maximum size of 10485760 bytes"};let t;try{t=JSON.parse(e)}catch(e){return{success:!1,error:`Invalid JSON: ${e instanceof Error?e.message:"Unknown error"}`}}const r=Uh(Lh(t)),n=ip.safeParse(t);return n.success?{success:!0,data:n.data,..."unsupported"===r.kind&&{unrecognizedSchemaId:r.id}}:{success:!1,error:`Invalid plugin manifest: ${n.error.issues.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`,details:n.error}}function kp(e,t){if("string"!=typeof e)return null;let r=e;if(r.startsWith("./")&&(r=r.slice(2)),void 0!==t){let e=t;e.startsWith("./")&&(e=e.slice(2)),e.endsWith("/")&&(e=e.slice(0,-1)),r=`${e}/${r}`}return r||"."}function _p(e){return!e.includes("..")&&!(0,s.isAbsolute)(e)&&!e.includes("://")}var Cp=r("../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js");const Ep=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g,xp=/\$%7B([^%/?#]+?)%7D/gi;function Pp(e,t){return Rp(e,"function"==typeof t?t:function(e){const t=new Map(Object.entries(e).map((([e,t])=>[e.toLowerCase(),t])));return r=>e[r]??t.get(r.toLowerCase())}(t))}function Rp(e,t){if("string"==typeof e)return function(e,t){return e.replace(xp,"${$1}").replace(Ep,((e,r,n,o)=>{if(void 0!==r)return t(r)??e;if(void 0===n)return e;const s=t(n);return void 0!==s?s:void 0!==o?o:e}))}(e,t);if(Array.isArray(e))return e.map((e=>Rp(e,t)));if(function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e)){const r={};for(const[n,o]of Object.entries(e))r[n]=Rp(o,t);return r}return e}function Ip(e,t){return e.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g,(()=>t)).replace(/\$\{CURSOR_PLUGIN_ROOT\}/g,(()=>t))}const Tp={log:()=>{},increment:()=>{},distribution:()=>{},captureException:()=>{}},Ap=je.object({command:je.string().optional(),args:je.array(je.string()).optional(),env:je.record(je.string(),je.string()).optional(),url:je.string().optional(),headers:je.record(je.string(),je.string()).optional(),cwd:je.string().optional(),envFile:je.string().optional(),auth:je.object({CLIENT_ID:je.string(),CLIENT_SECRET:je.string().optional(),scopes:je.array(je.string()).optional()}).optional(),enabledTools:je.array(je.string()).optional(),placement:je.enum(["server","client"]).optional(),tls:je.object({caBundle:je.string().trim().min(1).max(131072)}).optional()}),$p=je.object({mcpServers:je.record(je.string(),Ap).optional()}),Mp=[".mcp.json","mcp.json"],Dp=new Set(["author","owner","source","metadata"].map((e=>e.toLowerCase())));function Op(e,t){if(!function(e){return Dp.has(e.toLowerCase())}(e))return!1;if(!function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(t))return!1;const r=t;switch(e.toLowerCase()){case"author":case"owner":return"string"==typeof r.name;case"source":return"string"==typeof r.source||"string"==typeof r.repo||"string"==typeof r.path||"string"==typeof r.ref||"string"==typeof r.sha;case"metadata":return"string"==typeof r.description||"string"==typeof r.version||"string"==typeof r.pluginRoot;default:return!1}}function Fp(e){return"object"==typeof e&&null!==e&&("command"in e||"url"in e)}function Np(e){const t=void 0!==e&&e.length>0?e.replace(/\/+$/,""):void 0;return Mp.map((e=>void 0!==t?`${t}/${e}`:e))}function Lp(e,t,r){if(!e.mcpServers)return e;const n={};for(const[r,o]of Object.entries(e.mcpServers)){const e={...o};if("string"==typeof o.command&&(e.command=Ip(o.command,t)),Array.isArray(o.args)&&(e.args=o.args.map((e=>"string"==typeof e?Ip(e,t):e))),o.env&&"object"==typeof o.env){const r={};for(const[e,n]of Object.entries(o.env))r[e]="string"==typeof n?Ip(n,t):n;e.env=r}"string"==typeof o.cwd&&(e.cwd=Ip(o.cwd,t)),n[r]=e}return function(e,t){const r=t?.cloudAgentEnvLookup,n=t?.configuredVariables;if(void 0!==r)return Pp(e,r);const o=new Map(Object.keys(n??{}).map((e=>[e.toLowerCase(),e])));return Pp(e,(e=>{const t=process.env[e];if(void 0!==t)return t;const r=void 0!==n&&Object.hasOwn(n,e)?e:o.get(e.toLowerCase()),s=void 0!==r?n?.[r]:void 0;return null!=s?"string"==typeof s?s:"number"==typeof s||"boolean"==typeof s||"bigint"==typeof s?String(s):JSON.stringify(s):void 0}))}({...e,mcpServers:n},r)}function jp(e,t,r){try{const n=(0,Cp.qg)(e),o=Lh(n);if(void 0!==o){const e=r?.log??Tp;"unsupported"===Uh(o).kind?e.log("debug",`mcp.json declares an unrecognized $schema, loading anyway: ${o}`):function(e,t){if(void 0===e||void 0===t)return!1;const r=jh(e),n=jh(t);return void 0!==r&&void 0!==n&&r!==n}(r?.pluginSchemaId,o)&&e.log("debug",`mcp.json $schema ${o} disagrees with plugin.json $schema ${r?.pluginSchemaId}, loading anyway`)}const s=$p.safeParse(n),i=!0===r?.skipExpansion;if(s.success&&s.data.mcpServers&&Object.keys(s.data.mcpServers).length>0)return i?s.data:Lp(s.data,t,r);const a={};for(const[e,t]of Object.entries(n))"mcpServers"!==e&&!Op(e,t)&&Fp(t)&&(a[e]=t);if(Object.keys(a).length>0){const e=$p.safeParse({mcpServers:a});if(e.success)return i?e.data:Lp(e.data,t,r)}return null}catch{return null}}function Up(e,t,r){for(const[n,o]of Object.entries(t))e.mcpServers[n]=o,e.mcpServerSourcePaths[n]=r}async function Bp(e,t,r,n={}){const o=n.toSourcePath??(e=>e),s=n.installPathForExpansion??"",i=n.fallbackFileNames??Mp,a=n.manifestPrecedence??"override",c={},l={};for(const t of i){const r=await e(t);if(null===r)continue;const i=jp(r,s,n.parserOptions);if(i?.mcpServers)for(const[e,r]of Object.entries(i.mcpServers))void 0===c[e]&&(c[e]=r,l[e]=o(t))}if(void 0!==t){const i=await async function(e,t,r={}){const n=r.toSourcePath??(e=>e),o=r.installPathForExpansion??"",s={mcpServers:{},mcpServerSourcePaths:{}},i=async e=>{const i=e.replace(/^\.\//,"");if(!_p(i))return;const a=await t(i);if(null===a)return;const c=jp(a,o,r.parserOptions);c?.mcpServers&&Object.keys(c.mcpServers).length>0&&Up(s,c.mcpServers,n(i))},a=e=>{const t=jp(JSON.stringify(e),o,r.parserOptions);t?.mcpServers&&Object.keys(t.mcpServers).length>0&&Up(s,t.mcpServers,r.manifestSourcePath??"manifest")};if("string"==typeof e)await i(e);else if(Array.isArray(e))for(const t of e)"string"==typeof t?await i(t):"object"==typeof t&&null!==t&&a(t);else"object"==typeof e&&null!==e&&a(e);return s}(t,e,{toSourcePath:o,manifestSourcePath:r,installPathForExpansion:s,parserOptions:n.parserOptions});for(const[e,t]of Object.entries(i.mcpServers))"fill"===a&&void 0!==c[e]||(c[e]=t,l[e]=i.mcpServerSourcePaths[e])}return 0===Object.keys(c).length?null:{mcpServers:c,...Object.keys(l).length>0&&{mcpServerSourcePaths:l}}}const Wp=new Set(["CREDENTIAL","CREDENTIALS","KEY","PASSPHRASE","PASSWORD","SECRET","TOKEN"]);function Hp(e){return function(e){return e.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/[^a-z\d]+/gi,"_").toUpperCase().split("_").filter((e=>e.length>0))}(e).some((e=>Wp.has(e)))}const qp=/\$\{(?:env:([A-Z][A-Z0-9_]*)|([A-Z][A-Z0-9_]*)(?::-([^}]*))?)\}/g,zp=new Set(["CURSOR_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT"]),Gp=new Set(["api","aws","db","dd","gcp","http","https","id","mcp","ssl","tls","uri","url"]);function Vp(e){return e.split("_").filter((e=>e.length>0)).map((e=>{const t=e.toLowerCase();return Gp.has(t)?e.toUpperCase():e.charAt(0).toUpperCase()+t.slice(1)})).join(" ")}function Kp(e,t){if("string"!=typeof e){if(Array.isArray(e))for(const r of e)Kp(r,t);else if(null!==e&&"object"==typeof e)for(const r of Object.values(e))Kp(r,t)}else for(const[,r,n,o]of e.matchAll(qp)){const e=r??n;if(void 0===e||zp.has(e)||t.has(e))continue;const s=void 0===r?`\${${e}}`:`\${env:${e}}`;t.set(e,{reference:s,defaultValue:o})}}function Jp(e){if(void 0===e?.mcpServers)return;const t=new Map;if(Kp(e.mcpServers,t),0===t.size)return;const r={};for(const e of[...t.keys()].sort()){const n=t.get(e);if(void 0===n)continue;const{reference:o,defaultValue:s}=n;r[e]={type:"string",title:Vp(e),description:void 0===s||0===s.length?`Referenced as \`${o}\` in this plugin's MCP configuration.`:`Referenced as \`${o}\` in this plugin's MCP configuration. Defaults to \`${s}\` when left blank.`,...Hp(e)?{writeOnly:!0}:{}}}return{type:"object",properties:r}}const Zp=[".md",".mdc",".markdown"],Xp=[...Zp,".txt"],Qp=/^---\s*\n([\s\S]*?)\n---/;function Yp(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ef(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9.-]/g,"")}function tf(e){const t=e.match(Qp);if(!t)return{};try{const e=Mh.Ay.load(t[1],{schema:Mh.Ay.JSON_SCHEMA});if(!Yp(e))return{};const r=Yp(e.metadata)?e.metadata:void 0,n=rf(e.environments??r?.environments);return{disabledEnvironments:rf(e["disabled-environments"]??r?.disabledEnvironments),environments:n,name:"string"==typeof e.name?e.name:void 0,description:"string"==typeof e.description?e.description:void 0}}catch{const e=t[1],r=e.match(/^name:\s*(.+)$/m),n=e.match(/^description:\s*(.+)$/m);return r||n?{name:r?r[1].trim():void 0,description:n?n[1].trim():void 0}:{}}}function rf(e){if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e&&e.length>0));return 0===t.length?void 0:t}if("string"==typeof e){const t=e.split(",").map((e=>e.trim())).filter((e=>e.length>0));return 0===t.length?void 0:t}}function nf(e){return ef((0,s.basename)(e).replace(/\.(md|mdc|markdown|txt)$/i,""))}function of(e){const t=new Set,r=[];for(const n of e)t.has(n.name)||(t.add(n.name),r.push(n));return r}class sf{constructor(e){this.fetcher=e}async discoverComponents(e={}){const t=e.basePath??"",r=t?`${t}/`:"",n=e.manifest;let o;try{o=await this.fetcher.listDirectory(t)}catch{o=[]}const s=new Set(o.filter((e=>"dir"===e.type)).map((e=>e.name.toLowerCase()))),i=Mp.filter((e=>o.some((t=>"file"===t.type&&t.name===e)))),a=o.some((e=>"file"===e.type&&"SKILL.md"===e.name)),[c,l,u,d,h,p,f]=await Promise.all([a&&void 0===n?.skills?this.discoverRootSkill(r):Promise.resolve(null),void 0!==n?.skills?this.discoverFromManifestPaths(r,n.skills,!0,Zp):s.has("skills")?this.discoverSkills(`${r}skills`):Promise.resolve([]),void 0!==n?.agents?this.discoverFromManifestPaths(r,n.agents,!1,Zp):s.has("agents")?this.discoverMarkdownComponents(`${r}agents`,Zp):Promise.resolve([]),void 0!==n?.hooks?this.discoverHooksFromManifest(r,n.hooks):s.has("hooks")?this.discoverHooksFromJson(`${r}hooks/hooks.json`):Promise.resolve([]),void 0!==n?.commands?this.discoverFromManifestPaths(r,n.commands,!1,Xp):s.has("commands")?this.discoverMarkdownComponents(`${r}commands`,Xp):Promise.resolve([]),void 0!==n?.rules?this.discoverFromManifestPaths(r,n.rules,!1,Zp):s.has("rules")?this.discoverMarkdownComponents(`${r}rules`,Zp):Promise.resolve([]),this.discoverMcpServers(r,n?.mcpServers,i)]);return{skills:of(c?[c,...l]:l),agents:of(u),hooks:d,commands:of(h),rules:of(p),mcpServers:f.servers,mcpVariables:f.variables,mcpConfigs:f.configs}}async discoverHooksFromJson(e){try{if(!await this.fetcher.fileExists(e))return[];const{content:t}=await this.fetcher.fetchFile(e),r=JSON.parse(t);return Yp(r)&&Yp(r.hooks)?Object.keys(r.hooks).map((t=>({name:ef(t),path:e,description:`Hook: ${t}`}))):[]}catch{return[]}}async discoverHooksFromManifest(e,t){if("string"==typeof t){if(!_p(t))return[];const r=`${e}${t.replace(/^\.\//,"")}`;return r.endsWith(".json")?this.discoverHooksFromJson(r):this.discoverHooksFromJson(`${r}/hooks.json`)}const r=t.hooks??t;return!r||"object"!=typeof r||Array.isArray(r)?[]:Object.keys(r).map((e=>({name:ef(e),path:"manifest",description:`Hook: ${e}`})))}async discoverFromManifestPaths(e,t,r=!1,n=Zp){if("string"==typeof t){if(!_p(t))return[];const o=`${e}${t.replace(/^\.\//,"")}`.replace(/\/$/,"");return r?this.discoverSkills(o):this.discoverMarkdownComponents(o,n)}const o=[];for(const n of t)try{if(!_p(n))continue;const t=`${e}${n.replace(/^\.\//,"")}`;if(r){const e=t.endsWith("SKILL.md")?t:`${t.replace(/\/$/,"")}/SKILL.md`;if(!await this.fetcher.fileExists(e)){const e=t.replace(/\/$/,""),r=await this.discoverSkills(e);o.push(...r);continue}let r=nf(t.endsWith("SKILL.md")?t.slice(0,-8).replace(/\/$/,""):t);const{content:n}=await this.fetcher.fetchFile(e),s=tf(n);if(r=s.name??r,r){const t={disabledEnvironments:s.disabledEnvironments,environments:s.environments,name:ef(r),path:e};void 0!==s.description&&(t.description=s.description),o.push(t)}}else{if(!await this.fetcher.fileExists(t))continue;let e=nf(t);const{content:r}=await this.fetcher.fetchFile(t),n=tf(r);e=n.name??e;const s=n.description;if(e){const r={name:ef(e),path:t};void 0!==s&&(r.description=s),o.push(r)}}}catch{}return o}async discoverMarkdownComponents(e,t=Zp,r=new Set){let n;try{n=await this.fetcher.listDirectory(e,r)}catch{return[]}const o=n.filter((e=>"file"===e.type&&t.some((t=>e.name.endsWith(t))))),s=n.filter((e=>"dir"===e.type)),[i,a]=await Promise.all([Promise.all(o.map((async e=>{try{let t=nf(e.name);const{content:r}=await this.fetcher.fetchFile(e.path),n=tf(r);t=n.name?ef(n.name):t;const o=n.description;if(!t)return null;const s={name:t,path:e.path};return void 0!==o&&(s.description=o),s}catch{return null}}))),Promise.all(s.map((e=>this.discoverMarkdownComponents(e.path,t,r))))]);return[...i.filter((e=>null!==e)),...a.flat()]}async discoverRootSkill(e){try{const t=`${e}SKILL.md`;let r=ef((0,s.basename)(e.replace(/[\\/]+$/,"")));const{content:n}=await this.fetcher.fetchFile(t),o=tf(n);if(r=o.name?ef(o.name):r,!r)return null;const i={disabledEnvironments:o.disabledEnvironments,environments:o.environments,name:r,path:t};return void 0!==o.description&&(i.description=o.description),i}catch{return null}}async discoverSkills(e){let t;try{t=await this.fetcher.listDirectory(e)}catch{return[]}const r=t.filter((e=>"dir"===e.type));return(await Promise.all(r.map((async e=>{try{const t=`${e.path}/SKILL.md`;if(!await this.fetcher.fileExists(t))return null;const{content:r}=await this.fetcher.fetchFile(t),n=tf(r),o=n.name?ef(n.name):ef(e.name);if(!o)return null;const s={disabledEnvironments:n.disabledEnvironments,environments:n.environments,name:o,path:t};return void 0!==n.description&&(s.description=n.description),s}catch{return null}})))).filter((e=>null!==e))}async discoverMcpServers(e,t,r){const n=new Map,o=async t=>{const r=n.get(t);if(void 0!==r)return r;const o=this.fetcher.fetchFile(`${e}${t}`).then((({content:e})=>e)).catch((()=>null));return n.set(t,o),o},s=async n=>Bp(o,t,void 0!==t?"manifest":void 0,{fallbackFileNames:r,manifestPrecedence:n,toSourcePath:t=>`${e}${t}`,parserOptions:{skipExpansion:!0}}),i=await s("fill");if(void 0===i?.mcpServers)return{servers:[],variables:void 0,configs:void 0};const a=void 0===t?i:await s("override"),c=a?.mcpServers??i.mcpServers,l={};for(const[e,t]of Object.entries(c))l[e]=t;return{servers:Object.keys(i.mcpServers).map((e=>({name:ef(e),path:i.mcpServerSourcePaths?.[e]??"manifest"}))),variables:Jp(a??i),configs:l}}}class af extends Error{constructor(e,t){super(`Invalid Claude Code plugin identifier "${t}": ${e}`),this.raw=t,this.name="CCPluginIdentifierError"}}function cf(e){const t=e.trim();if(!t)throw new af("Empty identifier",e);const r=/^[a-zA-Z0-9_-]+$/,n=t.indexOf("@");if(n!==t.lastIndexOf("@"))throw new af("Plugin identifier cannot contain multiple @ symbols",e);if(-1===n){if(!r.test(t))throw new af("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(t.length>100)throw new af("Plugin name must be 100 characters or less",e);return{name:t,sourceType:"marketplace",marketplace:"claude-plugins-official",raw:e}}const o=t.slice(0,n).trim(),s=t.slice(n+1).trim();if(!o)throw new af("Missing plugin name before @",e);if(!s)throw new af("Missing source after @",e);if(!r.test(o))throw new af("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(o.length>100)throw new af("Plugin name must be 100 characters or less",e);if(s.startsWith("github:")){const t=s.slice(7).trim();if(!t||!/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(t))throw new af("Invalid GitHub repo format, expected 'org/repo' (e.g., 'anthropics/claude-plugins')",e);return{name:o,sourceType:"github",githubRepo:t,raw:e}}if(s.startsWith("local:")){const t=s.slice(6).trim();if(!t)throw new af("Missing path after 'local:'",e);return{name:o,sourceType:"local",localPath:t,raw:e}}if(s.startsWith("url:")){const t=s.slice(4).trim();if(!t)throw new af("Missing Git URL after 'url:'",e);try{new URL(t)}catch{throw new af("Invalid Git URL format",e)}return{name:o,sourceType:"url",gitUrl:t,raw:e}}const i=s.indexOf("#");let a,c;if(-1!==i?(a=s.slice(0,i).trim(),c=s.slice(i+1).trim()):a=s,!a)throw new af("Missing marketplace name",e);if(!r.test(a))throw new af("Marketplace name must contain only alphanumeric characters, dashes, and underscores",e);return{name:o,sourceType:"marketplace",marketplace:a,version:c,raw:e}}function lf(e){if("claude-plugin"===e.source)return e.sourceInfo.raw;if("user-local"===e.source)return`user-local:${e.sourceInfo.name}`;if("extension"===e.source){const t=e.sourceInfo;return`extension:${t.extensionId}:${t.localPath}`}const t=e.sourceInfo;return`${t.name}-${t.version}`}function uf(e){return e.sourceInfo.name}function df(e){switch(e.source){case"claude-plugin":case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplace;default:return}}function hf(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.pluginDbId;default:return}}function pf(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplaceDbId;default:return}}function ff(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function mf(e){return!!ff(e)&&(void 0===e.enabledPlugins||ff(e.enabledPlugins))}function gf(e){return JSON.parse(e)}function wf(e){const t=e??process.env.HOME??"";return(0,s.join)(t,".claude")}async function yf(e){const t={enabledPlugins:{}};let r=!1;const n=(0,s.join)(e,".claude","settings.json");try{const e=gf(await(0,Co.readFile)(n,"utf-8"));mf(e)&&e.enabledPlugins&&(Object.assign(t.enabledPlugins,e.enabledPlugins),r=!0)}catch{}const o=(0,s.join)(e,".claude","settings.local.json");try{const e=gf(await(0,Co.readFile)(o,"utf-8"));mf(e)&&e.enabledPlugins&&(Object.assign(t.enabledPlugins,e.enabledPlugins),r=!0)}catch{}return r?t:null}function vf(e,t){const r=(0,s.resolve)(e),n=(0,s.resolve)(e,t),o=(0,s.relative)(r,n);if(o.startsWith("..")||(0,s.isAbsolute)(o))throw new Error(`Invalid subPath: path traversal not allowed (${JSON.stringify(t)})`);return n}async function bf(e){try{return(await(0,Co.lstat)(e)).isSymbolicLink()}catch{return!1}}async function Sf(e){if(await bf(e))throw new Error(`Refusing to read symlink: ${e}`);return(0,Co.readFile)(e,"utf-8")}async function kf(e){if((await(0,Co.stat)(e)).size>10485760)throw new Error(`File ${e} exceeds maximum size of 10485760 bytes`)}function _f(e){const t=e instanceof Error?e.message:String(e);return/timed?\s*out/i.test(t)?"timeout":/clone|fetch|git/i.test(t)?"clone":/manifest|marketplace\.json/i.test(t)?"manifest":/parse|invalid|malformed/i.test(t)?"parse":/install|download|copy/i.test(t)?"install":"unknown"}async function Cf({installPath:e,logo:t}){const r=t?.trim();if(r&&!(0,s.isAbsolute)(r)&&!r.includes("://"))try{const t=await(0,Co.realpath)(e),n=vf(t,r),o=await(0,Co.realpath)(n);if(vf(t,o),!(await(0,Co.stat)(o)).isFile())return;return await kf(o),(0,Ed.pathToFileURL)(o).href}catch{return}}function Ef(e){const t={};return void 0!==e.version&&(t.version=e.version),void 0!==e.homepage&&(t.homepage=e.homepage),void 0!==e.repository&&(t.repository=e.repository),t}function xf(e){return void 0!==e.version||void 0!==e.homepage||void 0!==e.repository}function Pf(e,t){return Ef({version:e.version??t?.version,homepage:e.homepage??t?.homepage,repository:e.repository??t?.repository})}async function Rf(e,t,r){let n;for(const o of Hh){const i=(0,s.join)(e,o);let a;try{if(await bf(i))continue;if(!(await(0,Co.stat)(i)).isFile())continue;await kf(i),a=await Sf(i)}catch{continue}const c=Sp(a);if(!c.success)continue;const l=c.data,u=l.commands,d=l.agents,h=l.skills,p=l.rules,f=l.hooks,m=l.mcpServers,g=void 0!==u||void 0!==d||void 0!==h||void 0!==p||void 0!==f||void 0!==m,w="string"==typeof l.displayName?l.displayName:void 0,y="string"==typeof l.description?l.description:void 0,v=l.author?.name,b=await Cf({installPath:e,logo:l.logo}),S=Ef(l),k=l.variables,_=l.capabilities,C=void 0!==w||void 0!==y||void 0!==v||void 0!==b||void 0!==k||void 0!==_;if(!g&&!C&&!xf(S))continue;if(!g&&!C){n=n?{...n,fields:Pf(n.fields,S)}:{fields:S,path:i,relPath:o,unrecognizedSchemaId:c.unrecognizedSchemaId};continue}void 0!==c.unrecognizedSchemaId&&r.log("debug",`${t}: ${o} declares an unrecognized $schema, loading anyway: ${c.unrecognizedSchemaId}`);const E=Pf(S,n?.fields);return{manifestFilePath:i,...g&&{manifestOptions:{commands:u,agents:d,skills:h,rules:p,hooks:f,mcpServers:m}},...(C||xf(E))&&{metadata:{displayName:w,description:y,authorName:v,logoUrl:b,...E,variables:k,capabilities:_}}}}if(void 0!==n)return void 0!==n.unrecognizedSchemaId&&r.log("debug",`${t}: ${n.relPath} declares an unrecognized $schema, loading anyway: ${n.unrecognizedSchemaId}`),{manifestFilePath:n.path,metadata:n.fields}}async function If(e,t){const r=function(e,t){const r=new Map,n=(0,s.resolve)(e),o=(0,s.resolve)(t?.symlinkTargetRoot??n),i=(0,Co.realpath)(o).catch((()=>o));function a(e){const t=(0,s.resolve)(e);try{return vf(n,t)}catch{throw new Error(`Path escapes plugin directory: ${e}`)}}async function c(e){const t=a(e),r=await i,n=await(0,Co.realpath)(t);try{return vf(r,n)}catch{throw new Error(`Path escapes plugin directory via symlink: ${e}`)}}return{async listDirectory(t,r){const n=a(t?(0,s.join)(e,t):e);try{const e=await c(n);if(r?.has(e))return[];r?.add(e);const o=await(0,Co.readdir)(e,{withFileTypes:!0}),i=[];for(const e of o){const r=(0,s.join)(n,e.name);let o=e.isDirectory()?"dir":"file";if(e.isSymbolicLink())try{const e=await c(r);o=(await(0,Co.stat)(e)).isDirectory()?"dir":"file"}catch{continue}i.push({name:e.name,type:o,path:t?`${t}/${e.name}`:e.name})}return i}catch{return[]}},async fetchFile(t){const n=r.get(t);if(void 0!==n)return{content:n};const o=a((0,s.join)(e,t)),i=await c(o);await kf(i);const l=await(0,Co.readFile)(i,"utf-8");return r.set(t,l),{content:l}},async fileExists(t){try{const r=a((0,s.join)(e,t)),n=await c(r);return(await(0,Co.stat)(n)).isFile()}catch{return!1}}}}(e),n=new sf(r),o=await n.discoverComponents({manifest:t}),[i,a,c,l]=await Promise.all([Tf(r,o.skills,e),$f(r,o.agents,e),Mf(r,o.commands,e),Af(r,o.rules,e)]);return{skills:i,agents:a,commands:c,rules:l}}async function Tf(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Of({content:Ip(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}async function Af(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Of({content:Ip(t,r),relativePath:o.path});s&&n.push({...s,name:o.name})}catch{}return n}async function $f(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Ff({content:Ip(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}async function Mf(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Nf({content:Ip(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}function Df(e){if("string"==typeof e){const t=function(e){const t=[];let r=0,n=0;for(let o=0;o0)n--;else if(","===s&&0===n){const n=e.slice(r,o).trim();n&&t.push(n),r=o+1}}if(n>0){for(const n of e.slice(r).split(",")){const e=n.trim();e&&t.push(e)}return t}const o=e.slice(r).trim();return o&&t.push(o),t}(e);return t.length>0?t:void 0}if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e)).map((e=>e.trim())).filter(Boolean);return t.length>0?t:void 0}}function Of({content:e,relativePath:t}){try{const r=eh(e),n=t.replace(/\\/g,"/"),o=n.split("/").filter((e=>e.length>0)),s=o.length>=2?o[o.length-2]:void 0,i=o[o.length-1]??n,a=s??i.replace(/\.md$/i,""),c="string"==typeof r.data.name?r.data.name.trim():void 0,l=rf(r.data.environments??r.data.metadata?.environments),u=rf(r.data["disabled-environments"]??r.data.metadata?.disabledEnvironments);return{path:t,name:c&&c.length>0?c:a,description:"string"==typeof r.data.description?r.data.description:void 0,globs:Df(r.data.globs),alwaysApply:!0===r.data.alwaysApply,content:e,environments:l,disabledEnvironments:u}}catch{return null}}function Ff({content:e,relativePath:t}){try{const n=eh(e),o=n.content.trim();if(!o)return null;let i;"string"==typeof n.data.tools?i=n.data.tools.split(",").map((e=>e.trim())).filter(Boolean):Array.isArray(n.data.tools)&&(i=n.data.tools.map((e=>"string"==typeof e?e.trim():String(e))).filter(Boolean));const a=n.data.permissionMode??n.data.permissionmode,c=(0,s.basename)(t);return{path:t,name:"string"==typeof n.data.name?n.data.name:(0,s.basename)(c,(0,s.extname)(c)).replace(/[\s_]+/g,"-"),description:"string"==typeof n.data.description?n.data.description:void 0,tools:i,model:"string"==typeof n.data.model?n.data.model:"inherit",prompt:o,permissionMode:(r=a,"readonly"===(r??"").trim().toLowerCase()?"readonly":"default")}}catch{return null}var r}function Nf({content:e,relativePath:t}){try{const r=eh(e);let n;const o=r.data["argument-hint"];"string"==typeof o?n=o:Array.isArray(o)&&(n=`[${o.join(" ")}]`);const i=(0,s.basename)(t);return{path:t,name:"string"==typeof r.data.name?r.data.name:(0,s.basename)(i,(0,s.extname)(i)),description:"string"==typeof r.data.description?r.data.description:void 0,argumentHint:n,content:r.content.trim()}}catch{return null}}function Lf(e){if(void 0!==e)return{configuredVariables:e.configuredVariables}}async function jf(e,t,r){const n=r??Lf(t);return async function(e,t={}){const r=t.toSourcePath??(e=>e);let n,o,s;for(const t of Hh){const i=await e(t);if(null===i)continue;let a;try{a=JSON.parse(i)}catch{continue}s=Lh(a);const c=Sp(i);if(c.success){void 0!==c.data.mcpServers&&(n=c.data.mcpServers,o=r(t));break}}return Bp(e,n,o,void 0===s?t:{...t,parserOptions:{...t.parserOptions,pluginSchemaId:s}})}(function(e){return async t=>{if(!_p(t))return null;const r=(0,s.join)(e,t);try{return await bf(r)?null:(await(0,Co.stat)(r)).isFile()?(await kf(r),await Sf(r)):null}catch{return null}}}(e),{fallbackFileNames:Np(),manifestPrecedence:"override",toSourcePath:t=>(0,s.join)(e,t),installPathForExpansion:e,parserOptions:n})}async function Uf(e,t,r){const n=await jf(e,void 0,{log:r});if(n)return n;for(const n of zh){const o=(0,s.join)(e,n);try{if(!(await(0,Co.stat)(o)).isFile())continue;const n=await(0,Co.readFile)(o,"utf-8"),i=JSON.parse(n);if(!Hf(i)||!Array.isArray(i.plugins))continue;const a=i.plugins.filter(qf),c=t.name,l=a.find((e=>e.name===c));if(!l?.mcpServers?.length)continue;for(const t of l.mcpServers){const n=t.replace(/^\.\//,"");if(!_p(n))continue;const o=(0,s.join)(e,n);try{await kf(o);const t=jp(await Sf(o),e,{log:r});if(t?.mcpServers&&Object.keys(t.mcpServers).length>0){const e=Object.fromEntries(Object.keys(t.mcpServers).map((e=>[e,o])));return{...t,mcpServerSourcePaths:e}}}catch{}}return null}catch{}}return null}Error;const Bf=new Set(Object.values(xd));function Wf(e){return Bf.has(e)}function Hf(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function qf(e){return!(!Hf(e)||"string"!=typeof e.name)&&(void 0===e.mcpServers||Array.isArray(e.mcpServers)&&e.mcpServers.every((e=>"string"==typeof e)))}function zf(e,t){const r={};for(const[n,o]of Object.entries(e.hooks))Array.isArray(o)&&Wf(n)&&(r[n]=o.map((e=>"command"in e&&"string"==typeof e.command?{...e,command:Ip(e.command,t)}:"prompt"in e&&"string"==typeof e.prompt?{...e,prompt:Ip(e.prompt,t)}:e)));return{...e,hooks:r}}async function Gf(e,t,r,n,o){if("object"==typeof n){const s=Vf(n,t,r);return s&&"config"in s?{config:zf(s.config,e),...void 0!==o&&{sourcePath:o}}:s}let i,a,c;if("string"==typeof n){const t=n.replace(/^\.\//,"");if(!_p(t))return;i=t.endsWith(".json")?(0,s.join)(e,t):(0,s.join)(e,t,"hooks.json")}else i=(0,s.join)(e,"hooks","hooks.json");try{if(await bf(i))return;if(!(await(0,Co.stat)(i)).isFile())return}catch{return}try{await kf(i),a=await(0,Co.readFile)(i,"utf-8")}catch{return}try{c=JSON.parse(a)}catch{return{error:{source:"claude-plugin",message:`Plugin ${t} ${i}: invalid JSON`}}}const l=Vf(c,t,r);return l&&"config"in l?{config:zf(l.config,e),sourcePath:i}:l}function Vf(e,t,r){const n=function(e){if(!Id(e))return"unknown";const t=e,r="object"==typeof t.hooks&&null!==t.hooks?t.hooks:null;if(!r)return"unknown";for(const e of Object.values(r)){if(!Array.isArray(e)||0===e.length)continue;const t=e[0];if(Id(t)){if("hooks"in t&&Array.isArray(t.hooks))return"claude-code";if("command"in t||"prompt"in t||"type"in t)return"cursor"}}return"unknown"}(e);if("cursor"===n){const r=Dd(e);return r.isValid&&Dd(e).isValid?{config:e}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${r.errors.join("; ")}`}}}if("claude-code"===n){if(!(Hf(o=e)&&Hf(o.hooks)&&Object.keys(o.hooks).length>0))return;const n=Xd(e.hooks,{warn:e=>r.log("warn",`Plugin ${t} hooks: ${e}`),info:e=>r.log("info",`Plugin ${t} hooks: ${e}`)}),s=Dd(n);return s.isValid?{config:n}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${s.errors.join("; ")}`}}}var o}async function Kf(e,t,r,n){const o=n?.log??Tp,s=await Rf(e,t,o),i={...Lf(r)??(n?.configuredVariables?{configuredVariables:n.configuredVariables}:void 0),log:o},[a,c,l]=await Promise.all([If(e,s?.manifestOptions),jf(e,r,i),Gf(e,t,o,s?.manifestOptions?.hooks,s?.manifestFilePath)]);return{...a,...void 0!==s?.metadata?.displayName&&{displayName:s.metadata.displayName},...void 0!==s?.metadata?.description&&{description:s.metadata.description},...void 0!==s?.metadata?.authorName&&{authorName:s.metadata.authorName},...void 0!==s?.metadata?.logoUrl&&{logoUrl:s.metadata.logoUrl},...void 0!==s?.metadata?.version&&{version:s.metadata.version},...void 0!==s?.metadata?.homepage&&{homepage:s.metadata.homepage},...void 0!==s?.metadata?.repository&&{repository:s.metadata.repository},variablesSchema:s?.metadata?.variables,mcpConfig:c,capabilities:s?.metadata?.capabilities??[],hooks:l}}async function Jf(e,t,r){const n=r?.log??Tp,o=await Rf(e,t.raw,n),[s,i,a]=await Promise.all([If(e,o?.manifestOptions),Uf(e,t,n),Gf(e,t.raw,n,o?.manifestOptions?.hooks,o?.manifestFilePath)]);return{identifier:{source:"claude-plugin",sourceInfo:t},installPath:e,...void 0!==o?.metadata?.displayName&&{displayName:o.metadata.displayName},...void 0!==o?.metadata?.description&&{description:o.metadata.description},...void 0!==o?.metadata?.authorName&&{authorName:o.metadata.authorName},...void 0!==o?.metadata?.logoUrl&&{logoUrl:o.metadata.logoUrl},...void 0!==o?.metadata?.version&&{version:o.metadata.version},...void 0!==o?.metadata?.homepage&&{homepage:o.metadata.homepage},...void 0!==o?.metadata?.repository&&{repository:o.metadata.repository},...s,mcpConfig:i??void 0,capabilities:o?.metadata?.capabilities??[],hooks:a}}async function Zf(e,t,r,n){const o=`${r.name}@${r.version}`,{displayName:s,description:i,authorName:a,logoUrl:c,version:l,homepage:u,repository:d,variablesSchema:h,skills:p,rules:f,agents:m,commands:g,mcpConfig:w,capabilities:y,hooks:v}=await Kf(e,o,r,{log:n?.log});return{identifier:{source:t,sourceInfo:r},installPath:e,...void 0!==s&&{displayName:s},...void 0!==i&&{description:i},...void 0!==a&&{authorName:a},...void 0!==c&&{logoUrl:c},...void 0!==l&&{version:l},...void 0!==u&&{homepage:u},...void 0!==d&&{repository:d},variablesSchema:h,skills:p,rules:f,agents:m,commands:g,mcpConfig:w??void 0,capabilities:y,hooks:v}}async function Xf(e,t,r={}){const n=r.log??Tp,o=performance.now(),i=await async function(e){const t=wf(e),r=(0,s.join)(t,"plugins","installed_plugins.json");try{const e=gf(await(0,Co.readFile)(r,"utf-8"));return ff(n=e)&&ff(n.plugins)?e:null}catch{return null}var n}(r.userHomeDir);if(!i?.plugins)return n.log("info",`loadAllEnabledPlugins: no installed plugins metadata found (${(performance.now()-o).toFixed(1)}ms)`),[];const a=await async function(e){const t=wf(e),r=(0,s.join)(t,"settings.json");try{const e=gf(await(0,Co.readFile)(r,"utf-8"));return mf(e)?e:null}catch{return null}}(r.userHomeDir),c=function(e){if(void 0===e)return[];const t="string"==typeof e?[e]:e,r=new Set,n=[];for(const e of t){if(!e)continue;const t=(0,s.resolve)(e);r.has(t)||(r.add(t),n.push(t))}return n}(e),l=function(e,t,r){if(0===r.length)return $h(e,t,null,void 0);const n=new Set;for(const{settings:e}of r)for(const[t,r]of Object.entries(e?.enabledPlugins??{}))!1===r&&n.add(t);const o=new Set,s=[];for(const{workspacePath:i,settings:a}of r){const r=$h(e,t,a,i);for(const e of r)o.has(e.pluginId)||n.has(e.pluginId)||(o.add(e.pluginId),s.push(e))}return s}(i,a,await(0,Or.PH)(c,(async e=>({workspacePath:e,settings:await yf(e)})),{max:8})),u=[],d=r.onError;for(const{pluginId:e,installPath:t}of l)try{const r=performance.now(),o=cf(e),s=await Jf(t,o,{log:n});u.push(s),n.log("info",`loadClaudePlugin ${e} loaded in ${(performance.now()-r).toFixed(1)}ms`)}catch(t){const r=t instanceof Error?t:new Error(String(t));if(d)try{d(cf(e),r)}catch{d({name:e.split("@")[0]??e,sourceType:"marketplace",marketplace:"unknown",raw:e},r)}}return n.log("info",`loadAllEnabledPlugins completed in ${(performance.now()-o).toFixed(1)}ms (${l.length} resolved, ${u.length} loaded)`),u}const Qf=new Map;async function Yf(e){const{entry:t,slug:r,cacheManager:n}=e;if(void 0===t.backendContent&&!Eh(t.downloadUrl))return em(e);const o=n.getCacheDir({marketplaceSlug:r,pluginId:t.pluginId,version:t.version}),s=Qf.get(o);if(void 0!==s)return s;const i=em(e).finally((()=>{Qf.delete(o)}));return Qf.set(o,i),i}async function em(e){const{entry:t,slug:r,client:n,cacheManager:o,pluginLogger:s}=e;if(await o.isCached({marketplaceSlug:r,pluginId:t.pluginId,version:t.version})){const e=o.getCacheDir({marketplaceSlug:r,pluginId:t.pluginId,version:t.version});return s.log("info",`loadFromMarketplaceSource: Found cached plugin: ${t.pluginId} at ${e}`,{marketplaceSlug:r,pluginId:t.pluginId,gitRef:t.version,marketplaceId:t.marketplace?.id}),e}const i=o.getCacheDir({marketplaceSlug:r,pluginId:t.pluginId,version:t.version});s.log("info",`loadFromMarketplaceSource: Plugin missing from cache, installing: ${t.pluginId} at ${i}`,{marketplaceSlug:r,pluginId:t.pluginId,gitRef:t.version,marketplaceId:t.marketplace?.id}),await(0,Co.mkdir)(i,{recursive:!0});try{await n.installPlugin(t,i),await o.markCacheComplete({marketplaceSlug:r,pluginId:t.pluginId,version:t.version})}catch(e){try{await(0,Co.rm)(i,{recursive:!0,force:!0})}catch{}throw e}return i}async function tm(e){const{error:t,entry:r,slug:n,client:o,cacheManager:s,pluginLogger:i}=e;if(!kh(t))return;if("revision_superseded"===t.reason){const t=await(o.relistPlugin?.(r).catch((()=>{})));if(void 0!==t)try{return{entry:t,installPath:await Yf({...e,entry:t})}}catch(e){if(!kh(e))throw e}}const a=await async function(e){const{cacheManager:t,marketplaceSlug:r,pluginId:n,exceptVersion:o}=e,s=oh(vh),i=await t.listCachedVersions({marketplaceSlug:r,pluginId:n});let a;for(const e of i){if(!e.startsWith(s))continue;const i=xh(e.slice(s.length));if(i===o)continue;const c=uh({parent:t.getCacheDir({marketplaceSlug:r,pluginId:n,version:i}),name:ch}),l=await(0,Co.stat)(c).then((e=>e.mtimeMs),(()=>{}));void 0!==l&&(void 0===a||l>a.installedAtMs)&&(a={version:i,installedAtMs:l})}return a?.version}({cacheManager:s,marketplaceSlug:n,pluginId:r.pluginId,exceptVersion:r.version});return void 0!==a?(i.log("warn",`Plugin ${r.pluginId} keeps its installed version until the listed one can be downloaded`,{pluginId:r.pluginId,reason:t.reason}),{entry:{...r,version:a},installPath:s.getCacheDir({marketplaceSlug:n,pluginId:r.pluginId,version:a})}):void 0}async function rm(e){const t=e.log??Tp,r=performance.now(),{client:n,userId:o,teamId:s,onCursorError:i,pruneOldVersions:a,pluginFilter:c,onPluginsListed:l}=e,u=[],d=e.cacheManager??new hh(e.userHomeDir),h=performance.now();let p;try{p=await n.listEnabledPlugins(o,s)}catch(e){return t.captureException(e,{error_type:"list_enabled_plugins"}),t.increment("marketplace.source_unavailable",1),t.log("error",`marketplace listEnabledPlugins failed after ${(performance.now()-h).toFixed(1)}ms; treating source as unavailable: ${e instanceof Error?e.message:String(e)}`),{plugins:[],failures:[],sourceUnavailable:!0}}t.log("info",`marketplace listEnabledPlugins completed in ${(performance.now()-h).toFixed(1)}ms (${p.plugins.length} plugins)`),l&&await l(p.plugins);const f=[];if(p.listFailures){u.push(...p.listFailures);for(const e of p.listFailures)f.push({identifier:{source:e.marketplaceName&&"cursor-public"!==e.marketplaceName?"cursor-third-party":"cursor-first-party",sourceInfo:{name:e.pluginName,version:"",...void 0!==e.pluginDbId&&{pluginDbId:e.pluginDbId},marketplace:e.marketplaceName}},installPath:"",loadError:e.errorMessage,skills:[],rules:[],agents:[],commands:[],capabilities:[]})}const m=new Map;for(const e of p.plugins){if(c&&!c(e))continue;let r=e;try{const e=r.marketplace?.name;if(!e){const e=new Error(`Plugin ${r.name} has no marketplace metadata — cannot determine cache path`);u.push({pluginName:r.name,pluginId:r.pluginId,marketplaceName:void 0,errorMessage:e.message,errorType:"manifest"}),i&&i(r,e);continue}const o=`${e}/${r.pluginId}`;let s,a=m.get(o);a||(a={slug:e,pluginId:r.pluginId,versions:[]},m.set(o,a)),a.versions.push(r.version);try{s=await Yf({entry:r,slug:e,client:n,cacheManager:d,pluginLogger:t})}catch(o){const i=await tm({error:o,entry:r,slug:e,client:n,cacheManager:d,pluginLogger:t});if(void 0===i)throw o;({entry:r,installPath:s}=i),a.versions.push(r.version)}const c=r.marketplace?.name,l=void 0!==c&&"cursor-public"!==c&&c.length>0?"cursor-third-party":"cursor-first-party",h={name:r.name,version:r.version,pluginDbId:r.pluginDbId,configuredVariables:r.configuredVariables,marketplace:c,marketplaceDbId:r.marketplaceDbId,isTeamRequired:r.isTeamRequired},p=await Zf(s,l,h,{log:t});f.push(p);try{await d.pruneOldVersions({marketplaceSlug:e,pluginId:r.pluginId,keepVersions:[r.version]})}catch{}}catch(e){t.captureException(e,{error_type:"load_plugin_from_marketplace"});const n=e instanceof Error?e:new Error(String(e));u.push({pluginName:r.name,pluginId:r.pluginId,marketplaceName:r.marketplace?.name,errorMessage:n.message,errorType:_f(n)});const o=r.marketplace?.name,s=void 0!==o&&"cursor-public"!==o&&o.length>0;f.push({identifier:{source:s?"cursor-third-party":"cursor-first-party",sourceInfo:{name:r.name,version:r.version,pluginDbId:r.pluginDbId,marketplace:o,marketplaceDbId:r.marketplaceDbId,isTeamRequired:r.isTeamRequired}},installPath:"",loadError:n.message||"Plugin load failed",skills:[],rules:[],agents:[],commands:[],capabilities:[]}),i&&i(r,n)}}if(a)for(const{slug:e,pluginId:t,versions:r}of m.values())try{await d.pruneOldVersions({marketplaceSlug:e,pluginId:t,keepVersions:r})}catch{}return t.log("info",`loadFromMarketplaceSource completed in ${(performance.now()-r).toFixed(1)}ms (${f.length} plugins loaded, ${u.length} failures)`),{plugins:f,failures:u,sourceUnavailable:!1}}function nm(e){const{identifier:t}=e;switch(t.source){case"claude-plugin":return"marketplace"===t.sourceInfo.sourceType&&t.sourceInfo.marketplace?`${t.sourceInfo.marketplace}/${t.sourceInfo.name}`:void 0;case"cursor-first-party":case"cursor-third-party":return t.sourceInfo.marketplace?`${t.sourceInfo.marketplace}/${t.sourceInfo.name}`:void 0;default:return}}function om(e){return nm(e)??`path:${e.installPath}`}function sm(e,t={}){return{...e,model:t.stripModel?void 0:e.model,tools:t.stripTools?void 0:e.tools}}function im(e,t){const r=[];for(const o of e){const e=lf(o.identifier),i=`plugin:${e}`,a=uf(o.identifier),c=df(o.identifier),l=hf(o.identifier),u=pf(o.identifier);for(const d of t(o)){const t=(0,s.join)(o.installPath,d.path),{type:h,globs:p,description:f}=(n=d).alwaysApply?{type:"global"}:n.globs&&n.globs.length>0?{type:"fileGlobbed",globs:n.globs}:n.description?{type:"agentFetched",description:n.description}:{type:"manuallyAttached"};r.push({fullPath:t,content:d.content,type:h,globs:p,description:f,pluginIdentifier:e,gitRemoteOrigin:i,plugin:a,marketplace:c,pluginId:l,marketplaceId:u,environments:d.environments,disabledEnvironments:d.disabledEnvironments})}}var n;return r}var am=r("../proto/dist/generated/agent/v1/agent_skills_pb.js");const cm=(0,zs.debuglog)("agent-skills-catalog-cache");function lm(e){return(0,bo.createHash)("sha256").update(JSON.stringify({v:1,...e})).digest("hex")}async function um(e){try{return(await(0,Co.stat)(e)).mtimeMs}catch{return}}function dm(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const hm=[".kits","cursor-pages"],pm={configDir:".cursor",subdir:"skills-cursor",thirdParty:!1,builtin:!0},fm=[{configDir:".cursor",subdir:"skills",thirdParty:!1,builtin:!1},{configDir:".claude",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".codex",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".grok",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".agents",subdir:"skills",thirdParty:!1,builtin:!1},pm],mm=(new Set(fm.map((e=>e.configDir))),new Set(["imagegen","openai-docs","opneai-docs","plugin-creator","skill-creator","skill-installer"]));function gm(e){return e.replace(/\\/g,"/").split("/").filter(Boolean)}function wm(e){const t=gm(e);if(function(e){const t=e.findIndex(((t,r)=>function(e,t){return fm.some((r=>r.configDir===e&&r.subdir===t))}(t,e[r+1])));return-1!==t&&e.slice(t+2).some((e=>e.startsWith(".")))}(t))return!0;const r=t.lastIndexOf(".codex");if(-1===r||"skills"!==t[r+1])return!1;const n=t.at(-1),o="SKILL.md"===n?t.at(-2):n;return void 0!==o&&mm.has(o)}function ym(e){return{dirPath:(0,s.join)(e,pm.configDir,pm.subdir),scope:"builtin",source:"builtin"}}const vm="canvas";function bm(e,t){return{dirPath:(0,s.join)(ym(e).dirPath,...hm),scope:"builtin",source:"builtin"}}function Sm(e,t){const r=e.replace(/\\/g,"/"),n=t.replace(/\\/g,"/").replace(/\/+$/,"");if(r.startsWith(`${n}/`))return gm(r.slice(n.length+1))}function km(e,t){const r=Sm(e,t);return void 0!==r&&!r.some((e=>e.startsWith(".")))}function _m(e){return fm.filter((t=>!t.builtin&&(e||!t.thirdParty)))}function Cm(e,t){return _m(t).map((t=>({dirPath:(0,s.join)(e,t.configDir,t.subdir),scope:"project",source:"workspace"})))}function Em(e,t){return _m(t).map((t=>({dirPath:(0,s.join)(e,t.configDir,t.subdir),scope:"user",source:"user"})))}var xm=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function Pm(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const Rm=fm.map((({configDir:e,subdir:t,thirdParty:r})=>({pattern:new RegExp(`[/\\\\]${Pm(e)}[/\\\\]${Pm(t)}[/\\\\]`,"i"),requiresThirdParty:r}))),Im=/[/\\]\.cursor[/\\]rules[/\\]/i,Tm=[{pattern:/[/\\]\.cursor[/\\]agents[/\\]/i,requiresThirdParty:!1},{pattern:/[/\\]\.claude[/\\]agents[/\\]/i,requiresThirdParty:!0}],Am=new Set(["AGENTS.md","CLAUDE.md","CLAUDE.local.md"]);function $m(e,t){const r=e.replace(/\\/g,"/"),n=(0,s.basename)(r);if(Am.has(n))return"AGENTS.md"===n||t&&("CLAUDE.md"===n||"CLAUDE.local.md"===n)?"markdown":void 0;if(Im.test(r)&&n.endsWith(".mdc"))return"rules";if("SKILL.md"===n)for(const{pattern:e,requiresThirdParty:n}of Rm)if(e.test(r)){if(n&&!t)continue;return"skills"}if(n.endsWith(".md"))for(const{pattern:e,requiresThirdParty:n}of Tm)if(e.test(r)){if(n&&!t)continue;return"agents"}}class Mm{constructor(e,t,r,n){this.root=e,this.gitExecutor=t,this.userHomeDirectory=r,this.getThirdPartyExtensibilityEnabled=n}static getRipwalkCache(){return Mm.ripwalkCache??=new Sa,Mm.ripwalkCache}async discover(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,$.VI)(e.withName("NestedExtensibilityService.discover")),!1),n={rules:[],skills:[],markdown:[],agents:[]},o=(0,s.resolve)(this.root),i=(0,s.resolve)(this.userHomeDirectory);if(o===i||Hs(o,{platform:process.platform,homeDirectory:i}).length>0)return r.span.setAttribute("nested_extensibility.rules",0),r.span.setAttribute("nested_extensibility.skills",0),r.span.setAttribute("nested_extensibility.markdown",0),r.span.setAttribute("nested_extensibility.agents",0),n;if(!await Ya(e,this.gitExecutor,(0,s.resolve)(this.root)))return r.span.setAttribute("nested_extensibility.rules",0),r.span.setAttribute("nested_extensibility.skills",0),r.span.setAttribute("nested_extensibility.markdown",0),r.span.setAttribute("nested_extensibility.agents",0),n;const a=this.getThirdPartyExtensibilityEnabled(),c=this.buildIncludeGlobs(a),l={root:this.root,includeGlobs:c,excludeGlobs:lc,followSymlinks:!0,source:"nested_extensibility"},u={rules:[],skills:[],markdown:[],agents:[]},d=Mm.getRipwalkCache();try{const e=d.walk(r.ctx,l);try{for await(const t of e.lines){const e=$m(t,a);e&&u[e].push((0,s.resolve)(this.root,t))}}finally{d.delete(l)}}catch{}return r.span.setAttribute("nested_extensibility.rules",u.rules.length),r.span.setAttribute("nested_extensibility.skills",u.skills.length),r.span.setAttribute("nested_extensibility.markdown",u.markdown.length),r.span.setAttribute("nested_extensibility.agents",u.agents.length),u}catch(e){t.error=e,t.hasError=!0}finally{xm(t)}}buildIncludeGlobs(e){const t=["*/**/.cursor/**","*/**/.agents/**","*/**/AGENTS.md"];return e&&t.push("*/**/.claude/**","*/**/.codex/**","*/**/.grok/**","*/**/CLAUDE.md","*/**/CLAUDE.local.md"),t}}const Dm=new Set(["node_modules","__pycache__","dist","build"]);async function Om({rootDir:e,includeFile:t,maxDepth:r=10,containmentRootDir:n}){const o=[],i=[{dir:e,depth:0}],a=new Set,c=void 0!==n?await(0,Co.realpath)(n):null,l=e=>{if(null===c)return!0;const t=(0,s.relative)(c,e);return""===t||!t.startsWith("..")&&!(0,s.isAbsolute)(t)};for(;i.length>0;){const e=i.pop();if(void 0===e)continue;const{dir:n,depth:c}=e;if(c>r)continue;try{const e=await(0,Co.realpath)(n);if(!l(e))continue;if(a.has(e))continue;a.add(e)}catch{continue}const d=await(0,Co.readdir)(n,{withFileTypes:!0,encoding:"utf8"}).catch((()=>null));if(null!==d)for(const e of d){const r=(0,s.join)(n,e.name);let a=e.isDirectory(),l=e.isFile();if(e.isSymbolicLink())try{const e=await(0,Co.stat)(r);a=e.isDirectory(),l=e.isFile()}catch{continue}if(a){if((u=e.name).startsWith(".")||Dm.has(u))continue;i.push({dir:r,depth:c+1})}else l&&t(e.name)&&o.push(r)}}var u;return o.sort(((e,t)=>e.localeCompare(t))),o}const Fm={agentStoreSkillsDirs:[],userHomeDirectory:""};function Nm(e){const t=e.replace(/\\/g,"/");return t.endsWith("/")?t.slice(0,-1):t}function Lm(e,t){const r=Nm(t.userHomeDirectory),n=e.replace(/\\/g,"/");if(r.length>0)for(const e of t.agentStoreSkillsDirs){const t=Nm(e);if(t.length>0&&n.startsWith(`${t}/`))return{key:`${r}::skills/${n.slice(t.length+1)}`,inAgentStore:!0}}return{key:jm(e),inAgentStore:!1}}function jm(e){const t=e.replace(/\\/g,"/"),r=t.toLowerCase(),n=r.indexOf("/.cursor/"),o=r.indexOf("/.claude/"),s=r.indexOf("/.codex/"),i=r.indexOf("/.grok/"),a=r.indexOf("/.agents/");return-1!==n?`${t.slice(0,n)}::${t.slice(n+9)}`:-1!==o?`${t.slice(0,o)}::${t.slice(o+9)}`:-1!==s?`${t.slice(0,s)}::${t.slice(s+8)}`:-1!==i?`${t.slice(0,i)}::${t.slice(i+7)}`:-1!==a?`${t.slice(0,a)}::${t.slice(a+9)}`:e}function Um(e,t){const r=new Map,n=[];for(const o of e){const{key:e,inAgentStore:s}=Lm(o.fullPath,t),i=r.get(e);void 0!==i?s&&!n[i].inAgentStore&&(n[i]={item:o,inAgentStore:s}):(r.set(e,n.length),n.push({item:o,inAgentStore:s}))}return n.map((e=>e.item))}var Bm=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Wm=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Hm=(0,l.h)("local-exec:cursor-rules");function qm(e){return"/"===e||"\\"===e}function zm(e){return e.split(/[\\/]+/).filter((e=>e.length>0)).length}async function Gm(e){return await Om({rootDir:e,includeFile:e=>"SKILL.md"===e})}async function Vm(e){let t;try{t=await ji(e)}catch(t){return{skillFilePath:e,error:bd(t)}}try{return{skillFilePath:e,content:t,parsed:eh(t)}}catch(t){return{skillFilePath:e,error:Sd(t)}}}async function Km(e){const t=await ts(e);return{...await Vm(e),realSkillFilePath:t}}function Jm(e){return Qm(e.data?.environments??e.data?.metadata?.environments)??[]}function Zm(e){return Qm(e.data?.["disabled-environments"]??e.data?.metadata?.disabledEnvironments)??[]}function Xm(e){return Qm(e.data?.metadata?.scopedTo??e.data?.["metadata.scopedTo"])??[]}function Qm(e){if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e&&e.length>0));return 0===t.length?void 0:t}if("string"==typeof e){const t=e.split(",").map((e=>e.trim())).filter((e=>e.length>0));return 0===t.length?void 0:t}}function Ym(e,t,r){const n=function(e){const t=e.data?.metadata?.surfaces;return Array.isArray(t)?t:"string"==typeof t?t.split(",").map((e=>e.trim())).filter(Boolean):[]}(e);return n.length>0&&!n.includes(t)&&!r.includes(e.data?.name)}function eg(e){return Vo(e,1536)}function tg(e){return!0===e.data?.alwaysApply}function rg(e){return!0===e.data?.["disable-model-invocation"]}function ng({skillFilePath:e,content:t,parsed:r}){const n=function(e){return function(e){const t=(e.matter??"").trim(),r=e.language?.toLowerCase();return t.length>0&&"js"!==r&&"javascript"!==r?`---\n${t}\n---`:th("",e.data??{}).trim()}(e)}(r),o=function({fullPath:e,name:t,description:r,body:n}){const o=[],s=function(e){const t=e.replace(/\\/g,"/").split("/"),r=t[t.length-1]??"";return"SKILL.md"===r&&t.length>=2?t[t.length-2]??"":r}(e);s.length>64&&o.push(`Name is ${Cd(s.length)} characters; the limit is 64. Rename the skill's folder.`),_d.test(s)||o.push('Name should be lowercase letters and numbers joined by single hyphens, like "pdf-helper". Rename the skill\'s folder.'),void 0!==t&&t!==s&&o.push(`Frontmatter name ${JSON.stringify(t)} doesn't match the folder name ${JSON.stringify(s)}, which is the name the skill goes by. Make them the same.`);const i=r?.trim().length??0;i>1024&&o.push(`Description is ${Cd(i)} characters; the limit is ${Cd(1024)}.`);const a=Math.round(n.length/4);return a>5e3&&o.push(`Body is about ${Cd(a)} tokens; the recommended limit is ${Cd(5e3)}. Move details into reference files that SKILL.md links to.`),o}({fullPath:e,name:"string"==typeof r.data?.name?r.data.name:void 0,description:"string"==typeof r.data?.description?r.data.description:void 0,body:r.content});if(tg(r))return new Vr.DX({fullPath:e,content:t,frontmatter:n,type:new Vr.f5({type:{case:"global",value:new Vr.i9}}),environments:Jm(r),disabledEnvironments:Zm(r),scopedTo:Xm(r),warnings:o});const s="string"==typeof r.data?.description?eg(r.data.description):void 0,i=kd(s,rg(r));return i?new Vr.DX({fullPath:e,parseError:i,frontmatter:n,scopedTo:Xm(r),type:new Vr.f5({type:{case:"agentFetched",value:new Vr.Xo}})}):new Vr.DX({fullPath:e,content:t,frontmatter:n,type:new Vr.f5({type:{case:"agentFetched",value:new Vr.Xo({description:s})}}),environments:Jm(r),disabledEnvironments:Zm(r),scopedTo:Xm(r),warnings:o})}function og({skillFilePath:e,content:t,parsed:r}){const n="string"==typeof r.data?.description?eg(r.data.description):"",o=Df(r.data?.paths??r.data?.globs),s=rg(r);return new am.N({fullPath:e,content:t,description:n,globs:o??[],parseError:kd(n,s),environments:Jm(r),disabledEnvironments:Zm(r),scopedTo:Xm(r),disableModelInvocation:s})}function sg({rules:e,agentSkills:t,skillFilePath:r,errorMessage:n}){e.push(function({skillFilePath:e,errorMessage:t}){return new Vr.DX({fullPath:e,parseError:t,type:new Vr.f5({type:{case:"agentFetched",value:new Vr.Xo}})})}({skillFilePath:r,errorMessage:n})),t.push(function({skillFilePath:e,errorMessage:t}){return new am.N({fullPath:e,parseError:t})}({skillFilePath:r,errorMessage:n}))}function ig(e,t,r,n){if("error"in t)return e.realSkillFilePathsByFullPath.set(t.skillFilePath,t.realSkillFilePath),void sg({rules:e.rules,agentSkills:e.agentSkills,skillFilePath:t.skillFilePath,errorMessage:t.error});Ym(t.parsed,r,n)||(e.realSkillFilePathsByFullPath.set(t.skillFilePath,t.realSkillFilePath),e.rules.push(ng(t)),tg(t.parsed)||e.agentSkills.push(og(t)))}const ag=(0,zs.debuglog)("cursor-rules-service");function cg(){return{rules:[],agentSkills:[],realSkillFilePathsByFullPath:new Map}}function lg(e){return t=>(ag("%s: %O",e,t),cg())}function ug(e,t){return lm({kind:"agent-store",surface:e,roots:[...t].sort()})}function dg(e,t){const r=t.replace(/\\/g,"/").replace(/\/+$/,"");return""!==r&&e.replace(/\\/g,"/").startsWith(`${r}/`)}function hg(e){let t;if(!0===e.frontmatter.alwaysApply)t={case:"global",value:new Vr.i9};else{const r=Df(e.frontmatter.globs);t=r&&r.length>0?{case:"fileGlobbed",value:new Vr.uT({globs:r})}:"string"==typeof e.frontmatter.description&&e.frontmatter.description.trim().length>0?{case:"agentFetched",value:new Vr.Xo({description:eg(e.frontmatter.description)})}:{case:"manuallyAttached",value:new Vr._u}}const r=e.frontmatter["metadata.environments"],n=Array.isArray(r)?r:[],o=e.frontmatter["metadata.disabledEnvironments"],s=Array.isArray(o)?o:[],i=e.frontmatter["metadata.scopedTo"],a=Array.isArray(i)?i:[];return new Vr.DX({fullPath:e.path,content:e.body,type:new Vr.f5({type:t}),environments:n,disabledEnvironments:s,scopedTo:a,frontmatter:e.rawFrontmatter??""})}class pg{constructor(e,t){this.cursorRulesServices=e,this.getAgentStoreSkillsContext=t,this.onChangeCallbacks=new Set}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Bm(t,(0,$.VI)(e.withName("MergedCursorRulesService.getAllCursorRules")),!1),n=this.cursorRulesServices.map((e=>e.getAllCursorRules(r.ctx).catch((e=>((0,zs.debuglog)("Failed to load cursor rules from service:",e),[])))));return Um((await Promise.all(n)).flat(),this.getAgentStoreSkillsContext())}catch(e){t.error=e,t.hasError=!0}finally{Wm(t)}}reload(e){for(const t of this.cursorRulesServices)t.reload(e)}scheduleDidChangeRules(){void 0===this.changeTimer&&(this.changeTimer=setTimeout((()=>{this.changeTimer=void 0;for(const e of Array.from(this.onChangeCallbacks))e()}),pg.CHANGE_COALESCE_MS))}ensureChangeListenersRegistered(){void 0===this.disposeChangeListeners&&(this.disposeChangeListeners=this.cursorRulesServices.map((e=>e.onDidChangeRules((()=>this.scheduleDidChangeRules())))))}disposeChangeListenersIfUnused(){if(!(this.onChangeCallbacks.size>0||void 0===this.disposeChangeListeners)){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0,void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0)}}onDidChangeRules(e){return this.onChangeCallbacks.add(e),this.ensureChangeListenersRegistered(),()=>{this.onChangeCallbacks.delete(e),this.disposeChangeListenersIfUnused()}}dispose(){if(void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0),this.onChangeCallbacks.clear(),void 0!==this.disposeChangeListeners){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0}for(const e of this.cursorRulesServices)e.dispose&&e.dispose()}}pg.CHANGE_COALESCE_MS=1e3;class fg{constructor(e,t,r,n,i,a,c,l){this.gitExecutor=t,this.rootDirectory=r,this.loadNestedRules=n,this.getThirdPartyExtensibilityEnabled=i,this.loadTraceId=void 0,this.onChangeCallbacks=new Set,this.nestedExtensibilityService=new Mm(r,t,(0,o.homedir)(),i),this.ignoreService=c??new xc(t,void 0,[this.rootDirectory]);const u=performance.now();if(this._rules=this.load(e,l).then((t=>{try{Hm.info(e,"LocalCursorRulesService load completed",{durationMs:Math.round(performance.now()-u),ruleCount:t.length})}catch{}return t})).catch((e=>((0,zs.debuglog)("Failed to load cursor rules:",e),[]))),a){const e=[".cursor/rules/**/*.mdc","AGENTS.md","CLAUDE.md","CLAUDE.local.md",".cursorrules",".cursorignore"];this.unsubscribeWatcher=a.subscribe(this.rootDirectory,e,(e=>{const t={stack:[],error:void 0,hasError:!1};try{const r=(0,y.q6)(),n=Bm(t,(0,$.VI)(r.withName("LocalCursorRulesService.fileWatcher.subscribe")),!1);if(".cursorignore"===(0,s.basename)(e))return fg.getRipwalkCache().clear(),void this.reload(n.ctx);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{Wm(t)}}))}}reload(e){this._rules=this.load(e).catch((e=>((0,zs.debuglog)("Failed to load cursor rules:",e),[])));for(const e of this.onChangeCallbacks)e()}static getRipwalkCache(){return fg.ripwalkCache??=new Sa,fg.ripwalkCache}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.reloadAtPath")),!1);if(Jr((0,s.basename)(t)))return void this.reload(n.ctx);const o=this._rules;this._rules=(async()=>{const e=(await o).filter((e=>e.fullPath!==t));const r=(await this.readRulesAtPath(n.ctx,t)).map((e=>this.toCursorRule(e)));return[...e,...r]})().catch((e=>((0,zs.debuglog)("Failed to load cursor rules at path:",e),[])));for(const e of this.onChangeCallbacks)e()}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}isRuleMarkdownFile(e){return Jr(e)}async readRulesAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.readRulesAtPath")),!1),o=(0,s.basename)(t);if(".cursorrules"===o){const e=(0,s.resolve)(this.rootDirectory),t=await Ya(n.ctx,this.gitExecutor,e)||e,r=await this.loadCursorRulesRule(n.ctx,t);return r?[r]:[]}if(o.endsWith(".mdc"))return await mg(t);if(this.isRuleMarkdownFile(o))try{return await this.loadRulesFromMarkdownFile(n.ctx,(0,s.dirname)(t),o)}catch{}return[]}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}dispose(){this.unsubscribeWatcher&&(this.unsubscribeWatcher(),this.unsubscribeWatcher=void 0)}async load(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.load")),!1);this.loadTraceId=n.span.spanContext().traceId;const o=(0,s.resolve)(this.rootDirectory),i=await Ya(n.ctx,this.gitExecutor,o)||o,a=this.loadCursorRulesRule(n.ctx,i).then((e=>e?[e]:[])),c=this.loadRulesFromDirAndAncestors(n.ctx,o);let l,u;if(this.loadNestedRules){const e=t??this.nestedExtensibilityService.discover(n.ctx);l=e.then((e=>this.parseNestedRuleFiles(n.ctx,e.rules))),u=e.then((e=>this.parseNestedMarkdownFiles(n.ctx,e.markdown)))}else l=[],u=[];const d=(await Promise.all([a,c,l,u])).flat(),h=new Map;for(const e of d)h.set(e.path,e);const p=[...h.values()];return(await async function(e){const t=e.filter((e=>Jr((0,s.basename)(e.fullPath))));if(t.length<=1)return[...e];const r=await(0,Or.PH)(t,(e=>async function(e){try{const t=await(0,Co.stat)(e,{bigint:!0});if(0n!==t.ino)return`ino:${String(t.dev)}:${String(t.ino)}`}catch{}return await ts(e)}(e.fullPath)),{max:16}),n=t.map(((e,t)=>({item:e,identity:r[t],dir:(0,s.dirname)(e.fullPath),content:e.content.trim()}))).sort(((e,t)=>{const r=zm(e.dir)-zm(t.dir);if(0!==r)return r;const n="AGENTS.md"===(0,s.basename)(e.item.fullPath);return n===("AGENTS.md"===(0,s.basename)(t.item.fullPath))?0:n?-1:1})),o=[];for(const e of n)o.some((t=>{return((r=t.dir)===(n=e.dir)||!!n.startsWith(r)&&(qm(r.at(-1))||qm(n[r.length])))&&(t.identity===e.identity||t.content===e.content);var r,n}))||o.push(e);const i=new Set(o.map((e=>e.item)));return e.filter((e=>!Jr((0,s.basename)(e.fullPath))||i.has(e)))}(p.map((e=>({fullPath:e.path,content:e.body,rule:e}))))).map((e=>this.toCursorRule(e.rule)))}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}async loadCursorRulesRule(e,t){const r={stack:[],error:void 0,hasError:!1};try{Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.loadCursorrules")),!1);try{const e=(0,s.join)(t,".cursorrules");if((await(0,Co.stat)(e)).isFile())return{filename:".cursorrules",path:e,frontmatter:{alwaysApply:!0},body:await ji(e)}}catch{}return null}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{return Bm(t,(0,$.VI)(e.withName("LocalCursorRulesService.getAllCursorRules")),!1).span.setAttribute("cacheTraceId",this.loadTraceId??"undefined"),await this._rules}catch(e){t.error=e,t.hasError=!0}finally{Wm(t)}}toCursorRule(e){return hg({path:e.path,body:e.body,frontmatter:e.frontmatter,rawFrontmatter:e.rawFrontmatter})}async loadRulesFromDirAndAncestors(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirAndAncestors")),!1),o=[];let i=t;const a=this.getThirdPartyExtensibilityEnabled();for(;;){const e=(0,s.join)(i,".cursor","rules"),t=i;o.push((async()=>await this.dirIsDirectory(n.ctx,e)?this.loadRulesFromDirectory(n.ctx,t):[])());const r=[];a&&r.push("CLAUDE.md","CLAUDE.local.md"),r.push("AGENTS.md");for(const e of r)o.push(this.loadRulesFromMarkdownFile(n.ctx,i,e));const c=(0,s.dirname)(i);if(c===i)break;i=c}const c=(await Promise.all(o)).flat();return n.span.setAttribute("rules",c.length),c}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}async loadRulesFromMarkdownFile(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{Bm(n,(0,$.VI)(e.withName("LocalCursorRulesService.loadRulesFromMarkdownFile")),!1).span.setAttribute("filename",r);try{const e=(0,s.join)(t,r);if(await this.isCursorIgnored(e))return[];if((await(0,Co.stat)(e)).isFile()){const t=Zr({content:await ji(e),filename:r});return[{filename:(0,s.basename)(e,".md"),path:e,frontmatter:{alwaysApply:!0},body:t}]}}catch{}return[]}catch(e){n.error=e,n.hasError=!0}finally{Wm(n)}}async isCursorIgnored(e){try{const t=await Cc((0,s.resolve)(this.rootDirectory,e));return null===t||await this.ignoreService.isCursorIgnored(t)}catch{return!1}}async parseNestedRuleFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.parseNestedRuleFiles")),!1),o=(await Promise.all(t.map((async e=>{try{const t=en(await ji(e));if(t)return{filename:(0,s.basename)(e,".mdc"),path:e,frontmatter:t.frontmatter,rawFrontmatter:t.rawFrontmatter,body:t.body}}catch{}})))).filter((e=>void 0!==e));return n.span.setAttribute("ruleFiles",o.length),o}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}async parseNestedMarkdownFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.parseNestedMarkdownFiles")),!1),o=(await Promise.all(t.map((async e=>{try{const t=(0,s.basename)(e);if(!this.isRuleMarkdownFile(t))return[];const r=(0,s.dirname)(e);return await this.loadRulesFromMarkdownFile(n.ctx,r,t)}catch{}return[]})))).flat();return n.span.setAttribute("markdownFiles",o.length),o}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}async loadRulesFromDirectory(e,t){return await async function(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=Bm(n,(0,$.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirectory")),!1),i=[];try{(0,s.join)(t,".cursorignore");const e={root:(0,s.join)(t,".cursor","rules"),includeGlobs:["**/*.mdc"],followSymlinks:!0,source:"cursor_rules"},n=r.walk(o.ctx,e);for await(const t of n.lines){const r=(0,s.join)(e.root,t);i.push(...await mg(r))}}catch{}return o.span.setAttribute("rules",i.length),i}catch(e){n.error=e,n.hasError=!0}finally{Wm(n)}}(e,t,fg.getRipwalkCache())}async dirIsDirectory(e,t){const r={stack:[],error:void 0,hasError:!1};try{Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.dirIsDirectory")),!1);try{return(await(0,Co.stat)(t)).isDirectory()}catch{return!1}}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}}async function mg(e){try{const t=en(await ji(e));if(t)return[{filename:(0,s.basename)(e,".mdc"),path:e,frontmatter:t.frontmatter,rawFrontmatter:t.rawFrontmatter,body:t.body}]}catch{}return[]}class gg{constructor(e,t,r,n,o,s,i=()=>!0,a=Promise.resolve(),c="ide",l,u=()=>[],d,h,p=()=>[],f){if(this.workspacePaths=t,this.userHomeDirectory=r,this.gitExecutor=n,this.getEnabledSkills=p,this.ignoreService=f,this.agentStoreLoadRequestedWhileInFlight=!1,this.agentStoreLoadGeneration=0,this.watchersByFolder=new Map,this.onChangeCallbacks=new Set,this.reloadRequestedDuringSeed=!1,this.surface=c,this.waitBeforeSkillLoad="function"==typeof a?a:()=>a,this.getAgentStoreSkillRoots=u,this.fileWatcher=s,this.getThirdPartyExtensibilityEnabled=i,this.catalogCache=d,this.builtinSkillRootDir=ym(r).dirPath,this.canvasKitSkillRootDir=void 0===h?void 0:bm(r).dirPath,this.workspaceCatalogKey=lm({kind:"workspace",surface:c,loadNestedSkills:o,thirdPartyExtensibility:i(),workspacePaths:[...t].sort(),userHomeDirectory:r,...void 0===h?{}:{canvasKit:h}}),void 0!==l&&l.length!==t.length)throw new Error(`initialNestedExtensibilityResults length (${l.length}) must match workspacePaths length (${t.length})`);this.nestedExtensibilityEntries=o?t.map((e=>new Mm(e,n,r,i))):[],this.foldersToWatch=this.computeFoldersToWatch();const m=performance.now();let g=!1,w=!1,y=!1;const v=this.loadAll(e,l).then((t=>{try{Hm.info(e,"AgentSkillsCursorRulesService load completed",{durationMs:Math.round(performance.now()-m),ruleCount:t.rules.length,skillCount:t.agentSkills.length,servedFromCache:g})}catch{}return t})).catch((e=>(w=!0,lg("Failed to load Agent Skills")(e))));if(void 0===this.catalogCache)this._loaded=v;else{const t=this.readCatalog(this.workspaceCatalogKey).then((r=>(y=!0,this._loaded!==t?this._loaded:(w&&this.closeSeedWindow(e),void 0===r?v:(g=!0,r)))));this.seededLoaded=t,this._loaded=t,v.then((r=>{this._loaded===t?w?y&&this.closeSeedWindow(e):(this._loaded=v,g&&this.notifyChanged(),this.persistCatalog(this.workspaceCatalogKey,r),this.closeSeedWindow(e)):this.seededLoaded=void 0}))}this.refreshAgentStoreSkills(),this.setupWatchers(this.foldersToWatch)}closeSeedWindow(e){this.seededLoaded=void 0,this.reloadRequestedDuringSeed&&(this.reloadRequestedDuringSeed=!1,this.reload(e))}async readCatalog(e){if(void 0!==this.catalogCache)try{const t=await this.catalogCache.read(e);return void 0===t?void 0:await async function(e){if(!function(e){if(!dm(e))return!1;const t=e.fileMtimesMs;return 1===e.version&&Array.isArray(e.rules)&&Array.isArray(e.agentSkills)&&Array.isArray(e.realSkillFilePathsByFullPath)&&e.realSkillFilePathsByFullPath.every((e=>Array.isArray(e)&&2===e.length&&"string"==typeof e[0]&&"string"==typeof e[1]))&&dm(t)&&Object.values(t).every((e=>"number"==typeof e&&Number.isFinite(e)))}(e))return;const t=new Map;if(await Promise.all(e.realSkillFilePathsByFullPath.map((async([r,n])=>{const o=e.fileMtimesMs[n];void 0!==o&&await um(r)===o&&t.set(r,n)}))),0===t.size)return;const r=e=>void 0!==e&&t.has(e);try{return{rules:e.rules.map((e=>Vr.DX.fromJson(e,{ignoreUnknownFields:!0}))).filter((e=>r(e.fullPath))),agentSkills:e.agentSkills.map((e=>am.N.fromJson(e,{ignoreUnknownFields:!0}))).filter((e=>r(e.fullPath))),realSkillFilePathsByFullPath:t}}catch(e){return void cm("snapshot failed to decode: %O",e)}}(t)}catch(e){return void ag("Failed to read the skills catalog cache: %O",e)}}persistCatalog(e,t){const r=this.catalogCache;void 0!==r&&async function(e){const t=new Set(e.realSkillFilePathsByFullPath.values()),r={};return await Promise.all(Array.from(t,(async e=>{const t=await um(e);void 0!==t&&(r[e]=t)}))),{version:1,rules:e.rules.map((e=>e.toJson())),agentSkills:e.agentSkills.map((e=>e.toJson())),realSkillFilePathsByFullPath:Array.from(e.realSkillFilePathsByFullPath),fileMtimesMs:r}}(t).then((t=>r.write(e,t))).catch((e=>{ag("Failed to persist the skills catalog cache: %O",e)}))}computeFoldersToWatch(){const e=this.getThirdPartyExtensibilityEnabled(),t=new Set;for(const r of this.workspacePaths){t.add((0,s.join)(r,".cursor","rules"));for(const n of Cm(r,e))t.add(n.dirPath)}for(const r of Em(this.userHomeDirectory,e))t.add(r.dirPath);for(const e of this.getAgentStoreSkillRoots())t.add(e);return t.add(this.builtinSkillRootDir),void 0!==this.canvasKitSkillRootDir&&t.add(this.canvasKitSkillRootDir),Array.from(t)}isIgnoredSkillPath(e){if(void 0!==this.canvasKitSkillRootDir){if(km(e,this.canvasKitSkillRootDir))return!1;if(function(e,t){const r=Sm(e,t);return void 0!==r&&2===r.length&&r[0]===vm&&"SKILL.md"===r[1]}(e,this.builtinSkillRootDir))return!0}return wm(e)}setupWatchers(e){if(!this.fileWatcher)return;const t=["**"];for(const r of e){if(this.watchersByFolder.has(r))continue;const e=this.fileWatcher.subscribe(r,t,(e=>{const t={stack:[],error:void 0,hasError:!1};try{const r=(0,y.q6)(),n=Bm(t,(0,$.VI)(r.withName("AgentSkillsCursorRulesService.fileWatcher.subscribe")),!1);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{Wm(t)}}));this.watchersByFolder.set(r,e)}}removeWatchers(e){for(const t of e){const e=this.watchersByFolder.get(t);e&&(e(),this.watchersByFolder.delete(t))}}async getAllCursorRules(e){const[t]=await Promise.all([this._loaded,this.awaitAgentStoreSeed()]);return this.withAgentStoreSkills(t).rules}async awaitAgentStoreSeed(){void 0!==this.agentStoreSeedInFlight&&await(0,Or.wj)(this.agentStoreSeedInFlight,250,"Agent Store skills cache read timed out").catch((()=>{}))}reload(e){this.syncWatchers(),this.seededLoaded=void 0,this.reloadRequestedDuringSeed=!1;const t=this.loadAll(e),r=t.catch(lg("Failed to load Agent Skills"));this._loaded=r,t.then((e=>{this._loaded===r&&this.persistCatalog(this.workspaceCatalogKey,e)}),(()=>{})),this.refreshAgentStoreSkills(),this.notifyChanged()}reloadSkillRoots(){try{this.syncWatchers()}finally{this.refreshAgentStoreSkills()}}async agentStoreSkillsSettled(){for(let e=this.agentStoreWalk;void 0!==e;e=this.agentStoreWalk)await e}syncWatchers(){const e=this.computeFoldersToWatch(),t=new Set(this.foldersToWatch),r=new Set(e);this.removeWatchers(this.foldersToWatch.filter((e=>!r.has(e)))),this.setupWatchers(e.filter((e=>!t.has(e)))),this.foldersToWatch=e}isPrunedByExtensibilityScan(e){if(void 0!==this.canvasKitSkillRootDir&&km(e,this.canvasKitSkillRootDir))return!1;const t=e.replace(/\\/g,"/");for(const e of this.foldersToWatch){const r=e.replace(/\\/g,"/");if(t.startsWith(`${r}/`))return t.slice(r.length+1).split("/").slice(0,-1).some((e=>e.startsWith(".")))}return!1}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("AgentSkillsCursorRulesService.reloadAtPath")),!1),o=function(e,t,r=s){for(const n of t){const t=r.relative(n,e);if(""!==t&&".."!==t&&!t.startsWith(`..${r.sep}`)&&!r.isAbsolute(t))return r.join(n,t)}return e}(t,this.foldersToWatch),i=o.endsWith("SKILL.md")?o:(0,s.join)(o,"SKILL.md");if(void 0!==this.seededLoaded&&this._loaded===this.seededLoaded&&!this.getAgentStoreSkillRoots().some((e=>dg(i,e))))return void(this.reloadRequestedDuringSeed=!0);if(this.getAgentStoreSkillRoots().some((e=>dg(i,e))))return void this.refreshAgentStoreSkills();if(this.foldersToWatch.some((e=>""===(0,s.relative)(e,o))))return void this.reload(n.ctx);const a=this._loaded,c=(async()=>{const e=await a,{realSkillFilePathsByFullPath:t}=e,r=function(e,t){const r=new Map(e.realSkillFilePathsByFullPath);for(const e of t)r.delete(e);return{rules:e.rules.filter((e=>!t.has(e.fullPath))),agentSkills:e.agentSkills.filter((e=>!t.has(e.fullPath))),realSkillFilePathsByFullPath:r}}(e,new Set([i]));if(this.isIgnoredSkillPath(i)||this.isPrunedByExtensibilityScan(i))return r;const o=t.get(i);if(void 0===o){try{await(0,Co.stat)(i)}catch{return r}return await this.loadAll(n.ctx)}let s;try{s=await(0,Co.realpath)(i)}catch{return await this.loadAll(n.ctx)}if(s!==o)return await this.loadAll(n.ctx);try{return ig(r,{...await async function(e){const t=await ji(e);return{skillFilePath:e,content:t,parsed:eh(t)}}(i),realSkillFilePath:s},this.surface,this.getEnabledSkills()),r}catch{return await this.loadAll(n.ctx)}})().catch(lg("Failed to load Agent Skills at path"));this._loaded=c,this.notifyChanged()}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}async getAllAgentSkills(e){const[t]=await Promise.all([this._loaded,this.awaitAgentStoreSeed()]);return this.withAgentStoreSkills(t).agentSkills}withAgentStoreSkills(e){const t=this.settledAgentStoreSkills?.loaded;if(void 0===t||0===t.realSkillFilePathsByFullPath.size)return e;const r=new Set(e.realSkillFilePathsByFullPath.values()),n={rules:[...e.rules],agentSkills:[...e.agentSkills],realSkillFilePathsByFullPath:new Map(e.realSkillFilePathsByFullPath)},o=new Set;for(const[e,s]of t.realSkillFilePathsByFullPath)n.realSkillFilePathsByFullPath.has(e)||r.has(s)?o.add(e):n.realSkillFilePathsByFullPath.set(e,s);for(const e of t.rules)o.has(e.fullPath)||n.rules.push(e);for(const e of t.agentSkills)o.has(e.fullPath)||n.agentSkills.push(e);return n}refreshAgentStoreSkills(){const e=this.getAgentStoreSkillRoots().filter((e=>""!==e.trim())),t=++this.agentStoreLoadGeneration;var r,n;if(void 0===this.settledAgentStoreSkills||(r=this.settledAgentStoreSkills.roots,n=e,r.length===n.length&&r.every(((e,t)=>e===n[t])))||(this.settledAgentStoreSkills=void 0,this.notifyChanged()),0!==e.length){if(void 0===this.settledAgentStoreSkills){const r=this.seedAgentStoreSkills(e,t).finally((()=>{this.agentStoreSeedInFlight===r&&(this.agentStoreSeedInFlight=void 0)}));this.agentStoreSeedInFlight=r}void 0===this.agentStoreWalk?this.agentStoreWalk=(0,Or.wj)(this.loadAgentStoreSkills(e),3e4,"Agent Store skills walk timed out").then((r=>{t===this.agentStoreLoadGeneration&&(this.settledAgentStoreSkills={roots:e,loaded:r},this.notifyChanged(),(r.rules.length>0||r.agentSkills.length>0)&&this.persistCatalog(ug(this.surface,e),r))}),(e=>{ag("Failed to load Agent Store skills: %O",e)})).finally((()=>{this.agentStoreWalk=void 0,this.agentStoreLoadRequestedWhileInFlight&&(this.agentStoreLoadRequestedWhileInFlight=!1,this.refreshAgentStoreSkills())})):this.agentStoreLoadRequestedWhileInFlight=!0}}async seedAgentStoreSkills(e,t){const r=await this.readCatalog(ug(this.surface,e));void 0!==r&&t===this.agentStoreLoadGeneration&&void 0===this.settledAgentStoreSkills&&(this.settledAgentStoreSkills={roots:e,loaded:r},this.notifyChanged())}async loadAgentStoreSkills(e){const t=cg(),r=(await Promise.all(e.map((e=>Gm(e))))).flat().filter((e=>!wm(e))),n=await Promise.all(r.map((e=>Km(e)))),o=new Set;for(const e of n)o.has(e.realSkillFilePath)||(o.add(e.realSkillFilePath),ig(t,e,this.surface,this.getEnabledSkills()));return t}notifyChanged(){for(const e of Array.from(this.onChangeCallbacks))e()}onDidChangeSkills(e){return this.onDidChangeRules(e)}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}dispose(){for(const e of this.watchersByFolder.values())e();this.watchersByFolder.clear()}async loadAll(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("AgentSkillsCursorRulesService.loadAll")),!1);await this.waitBeforeSkillLoad();const o=[],s=[],i=new Map,a=Promise.all(this.nestedExtensibilityEntries.map(((e,r)=>(t?.[r]??e.discover(n.ctx)).catch((e=>{ag("Failed to discover nested agent skills: %O",e)}))))),c=new Set(this.getAgentStoreSkillRoots()),l=await Promise.all(this.foldersToWatch.filter((e=>!c.has(e))).map((async e=>{const t=(await Gm(e)).filter((e=>!this.isIgnoredSkillPath(e)));return Promise.all(t.map((e=>Km(e))))}))),u=new Set;for(const e of l)for(const t of e)if(!u.has(t.realSkillFilePath))if(u.add(t.realSkillFilePath),"error"in t)i.set(t.skillFilePath,t.realSkillFilePath),sg({rules:o,agentSkills:s,skillFilePath:t.skillFilePath,errorMessage:t.error});else{if(Ym(t.parsed,this.surface,this.getEnabledSkills()))continue;i.set(t.skillFilePath,t.realSkillFilePath),o.push(ng(t)),tg(t.parsed)||s.push(og(t))}const d=(await a).flatMap((e=>e?.skills??[])).filter((e=>!wm(e))),h=await Promise.all(d.map((e=>ts(e)))),p=[];for(const[e,t]of d.entries()){const r=h[e];u.has(r)||(u.add(r),p.push(t))}const f=await Promise.all(p.map((e=>Km(e))));for(const e of f)if("error"in e)i.set(e.skillFilePath,e.realSkillFilePath),sg({rules:o,agentSkills:s,skillFilePath:e.skillFilePath,errorMessage:e.error});else{if(Ym(e.parsed,this.surface,this.getEnabledSkills()))continue;i.set(e.skillFilePath,e.realSkillFilePath),o.push(ng(e)),tg(e.parsed)||s.push(og(e))}return n.span.setAttribute("agent_skills.total",o.length),n.span.setAttribute("agent_skills_proto.total",s.length),{rules:o,agentSkills:s,realSkillFilePathsByFullPath:i}}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}}function wg(e){let t;switch(e.type){case"global":t=new Vr.f5({type:{case:"global",value:new Vr.i9}});break;case"fileGlobbed":t=new Vr.f5({type:{case:"fileGlobbed",value:new Vr.uT({globs:e.globs??[]})}});break;case"agentFetched":t=new Vr.f5({type:{case:"agentFetched",value:new Vr.Xo({description:eg(e.description??"")})}});break;case"manuallyAttached":t=new Vr.f5({type:{case:"manuallyAttached",value:new Vr._u}});break;default:e.type,t=new Vr.f5({type:{case:"manuallyAttached",value:new Vr._u}})}return new Vr.DX({fullPath:e.fullPath,content:e.content,type:t,gitRemoteOrigin:e.gitRemoteOrigin,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,environments:e.environments??[],disabledEnvironments:e.disabledEnvironments??[],scopedTo:[]})}class yg{constructor(e,t,r,n){this.getImportSettings=t,this.pluginsService=n,this._rules=Promise.resolve([]),this._agentSkills=Promise.resolve([]),this._lastLoaded={rules:[],agentSkills:[]},this._loadGeneration=0,this.onChangeCallbacks=new Set,this.currentImportSettings=this.getImportSettings();const o=performance.now();this.startLoad(e,!1,(t=>{try{Hm.info(e,"CursorPluginsAgentSkillsService load completed",{durationMs:Math.round(performance.now()-o),ruleCount:t.rules.length,skillCount:t.agentSkills.length})}catch{}}))}startLoad(e,t,r){const n=++this._loadGeneration,o=this.loadAll(e,t).catch((e=>((0,zs.debuglog)("cursor-plugins-agent-skills")("Failed to load Cursor Plugins Agent Skills: %s",e instanceof Error?e.message:String(e)),{rules:[],agentSkills:[]}))).then((e=>(n===this._loadGeneration&&(this._lastLoaded=e,r?.(e)),e))),s=()=>(o.then((e=>{n===this._loadGeneration&&(this._rules=Promise.resolve(e.rules),this._agentSkills=Promise.resolve(e.agentSkills),this.notifyChange())})),this._lastLoaded),i=void 0!==this._overBudgetLoad?Promise.resolve(s()):(0,Or.wj)(o,5e3,"Cursor plugin load did not finish within the rules wait budget").catch((t=>(Hm.warn(e,"Serving rules without plugin primitives while plugins load",{error:t instanceof Error?t.message:String(t),waitMs:5e3}),this._overBudgetLoad=o,o.then((()=>{this._overBudgetLoad===o&&(this._overBudgetLoad=void 0)})),s())));this._rules=i.then((e=>e.rules)),this._agentSkills=i.then((e=>e.agentSkills))}notifyChange(){for(const e of Array.from(this.onChangeCallbacks))e()}async getAllCursorRules(e){return await this._rules}async getAllAgentSkills(e){return await this._agentSkills}reload(e){const t=this.getImportSettings();this.currentImportSettings=t,this.startLoad(e,!0),this.notifyChange()}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}onDidChangeSkills(e){return this.onDidChangeRules(e)}dispose(){this.onChangeCallbacks.clear()}async loadAll(e,t=!1){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("CursorPluginsAgentSkillsService.loadAll")),!1),o=[],i=[];try{let e=t?await this.pluginsService.reload():await this.pluginsService.getAllEnabledPlugins();this.currentImportSettings.importThirdPartyPlugins||(e=e.filter((e=>"claude-plugin"!==e.identifier.source))),n.span.setAttribute("cursor_plugins.loaded",e.length);const r=function(e){return im(e,(e=>e.skills))}(e),a=function(e){return im(e,(e=>e.rules))}(e);for(const e of[...r,...a])o.push(wg(e));for(const t of e){const e=`plugin:${lf(t.identifier)}`,r=uf(t.identifier),n=df(t.identifier),o=hf(t.identifier),a=pf(t.identifier);for(const c of t.skills){if(!0===c.alwaysApply)continue;let l=!1;if(c.content?.includes("disable-model-invocation"))try{l=!0===eh(c.content).data?.["disable-model-invocation"]}catch{}i.push(new am.N({fullPath:(0,s.join)(t.installPath,c.path),content:c.content,description:eg(c.description??""),environments:c.environments??[],disabledEnvironments:c.disabledEnvironments??[],gitRemoteOrigin:e,plugin:r,marketplace:n,pluginId:o,marketplaceId:a,disableModelInvocation:l}))}}}catch(e){n.span.setAttribute("cursor_plugins.error",String(e))}return n.span.setAttribute("cursor_plugins.total",o.length),n.span.setAttribute("cursor_plugins_proto.total",i.length),{rules:o,agentSkills:i}}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}}var vg=r("../proto/dist/generated/agent/v1/subagents_pb.js");const bg=(0,zs.debuglog)("local-subagents");class Sg{async getAllSubagents(){return[]}async reload(){return[]}}function kg(e){return"true"===(e??"").trim().toLowerCase()}function _g(e){const t=e.match(/^---\s*\n([\s\S]*?)\n---\s*\n?([\s\S]*)$/m);if(!t)return null;const r=t[1]??"",n=(t[2]??"").trim();if(0===n.length)return null;const o={};for(const e of r.split("\n")){const t=e.trim();if(0===t.length||t.startsWith("#"))continue;const r=t.indexOf(":");if(-1===r)continue;const n=t.slice(0,r).trim().toLowerCase(),s=t.slice(r+1).trim();0!==n.length&&(o[n]=s)}const s=o.name??"",i=o.description,a=o.model,c=kg(o["force-default-model"]),l="true"===(o.readonly??"").trim().toLowerCase()?vg.b$.READONLY:vg.b$.DEFAULT,u=kg(o.background??o.is_background),d=o.tools;return{name:s,description:i,tools:void 0!==d&&d.length>0?d.split(",").map((e=>e.trim())).filter((e=>e.length>0)):[],model:a,forceDefaultModel:c,prompt:n,permissionMode:l,isBackground:u}}function Cg(e){const t=(0,s.extname)(e).toLowerCase();return".md"===t||".mdc"===t||".markdown"===t}function Eg(e){return(0,s.basename)(e,(0,s.extname)(e)).replace(/[\s_]+/g,"-")}async function xg(e,t){return await Om({rootDir:e,includeFile:Cg,containmentRootDir:t})}class Pg{constructor(e,t,r="workspace",n=!1,o){this.workspacePath=e,this.cursorAgentsSource=r,this.allowExternalAgentSymlinks=n,this.ignoreService=o,this.getThirdPartyExtensibilityEnabled=t??(()=>!0),this.subagents=this.load().catch((e=>(bg("Failed to load subagents: %o",e),[])))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents=this.load().catch((e=>(bg("Failed to load subagents: %o",e),[]))),await this.subagents}computeAgentsDirs(){const e=(0,s.resolve)(this.workspacePath),t=[{dirPath:(0,s.join)(e,".cursor","agents"),source:this.cursorAgentsSource}];return this.getThirdPartyExtensibilityEnabled()&&(t.push({dirPath:(0,s.join)(e,".claude","agents"),source:"claude"}),t.push({dirPath:(0,s.join)(e,".grok","agents"),source:"grok"})),t}async load(){const e=this.computeAgentsDirs(),t=[];for(const{dirPath:r,source:n}of e){const e=await xg(r,this.allowExternalAgentSymlinks?void 0:this.workspacePath);for(const r of e){const e=(0,s.basename)(r);try{if(!(await(0,Co.stat)(r)).isFile())continue}catch(e){bg("Skipping subagent file %s due to stat error: %o",r,e);continue}try{const o=_g(await ji(r));if(!o)continue;t.push(new vg.zz({fullPath:r,name:o.name||Eg(e),description:o.description??"",tools:o.tools,model:o.model??"inherit",forceDefaultModel:o.forceDefaultModel,prompt:o.prompt,permissionMode:o.permissionMode,isBackground:o.isBackground,source:n}))}catch(e){bg("Failed to parse subagent file %s: %o",r,e)}}}return t}}const Rg=new Set(["claude-code-tutor"]);class Ig{constructor(e){this.subagentsServices=e}async getAllSubagents(){const e=await Promise.all(this.subagentsServices.map((e=>e.getAllSubagents().catch((e=>(bg("Failed to load subagents from merged service: %o",e),[])))))),t=new Map;for(const r of e)for(const e of r)Rg.has(e.name)||t.has(e.name)||t.set(e.name,e);return Array.from(t.values())}async reload(){return await Promise.all(this.subagentsServices.map((e=>e.reload()))),this.getAllSubagents()}}class Tg{constructor(e,t){this.getSettings=e,this.pluginsService=t,this._subagentsCache=[],this._loadId=0,this._loadPromise=null,this._loadedOnce=!1,this.runLoadInBackground()}async getAllSubagents(){return this._loadPromise&&await this._loadPromise,this._loadedOnce||await this.reload(),[...this._subagentsCache]}async reload(){return this.runLoadInBackground(!0),this._loadPromise&&await this._loadPromise,this._subagentsCache}runLoadInBackground(e=!1){const t=++this._loadId;this._loadPromise=this.load(e).then((e=>{t===this._loadId&&(this._subagentsCache=e,this._loadedOnce=!0)})).catch((e=>{t===this._loadId&&(bg("Failed to load Cursor plugin subagents: %o",e),this._subagentsCache=[],this._loadedOnce=!0)})).finally((()=>{t===this._loadId&&(this._loadPromise=null)}))}dispose(){}async load(e){const t=[];try{let r=e?await this.pluginsService.reload():await this.pluginsService.getAllEnabledPlugins();this.getSettings().importThirdPartyPlugins||(r=r.filter((e=>"claude-plugin"!==e.identifier.source)));const n=function(e,t={stripModel:!0,stripTools:!0}){const r=[];for(const n of e){const e=uf(n.identifier),o=df(n.identifier),i=hf(n.identifier),a=pf(n.identifier);for(const c of n.agents){const l=sm(c,t),u=(0,s.join)(n.installPath,l.path);r.push({name:l.name,description:l.description??"",prompt:l.prompt,fullPath:u,permissionMode:"readonly"===l.permissionMode?"readonly":"default",plugin:e,marketplace:o,pluginId:i,marketplaceId:a})}}return r}(r,{stripModel:!0,stripTools:!0});for(const e of n){const r="readonly"===e.permissionMode?vg.b$.READONLY:vg.b$.DEFAULT;t.push(new vg.zz({name:e.name,description:e.description,tools:[],model:"inherit",prompt:e.prompt,fullPath:e.fullPath,permissionMode:r,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,source:"plugin"}))}}catch{}return t}}class Ag{constructor(e){this.pastElements=[],this.closed=!1,this.forks=new Set,this.consume(e)}async consume(e){try{for await(const t of e){this.pastElements.push(t);const e=[];for(const r of this.forks)e.push(r.write(t).catch((()=>{})));await Promise.allSettled(e)}}catch(e){this.error=e instanceof Error?e:new Error(String(e))}finally{this.closed=!0;for(const e of this.forks)this.error?e.throw(this.error):e.close();this.forks.clear()}}fork(){if(this.closed){const e=this.pastElements,t=this.error;return async function*(){for(const t of e)yield t;if(t)throw t}()}const e=(0,h.Jt)(),t=this.pastElements.slice();this.forks.add(e);const r=this;return async function*(){for(const e of t)yield e;try{for await(const t of e)yield t}finally{r.forks.delete(e)}}()}}function $g(e,t){return`${e}:${(0,bo.createHash)("sha256").update(t.toBinary()).digest("hex")}`}function Mg(e){return new Eo.q({max:e?.max??10,ttl:e?.ttl})}function Dg(e,t,r=Mg(t)){return{async execute(t,n,o){if(!o?.execId)return e.execute(t,n,o);const s=$g(o.execId,n),i=r.get(s);if(void 0!==i)return i;const a=await e.execute(t,n,o);return r.set(s,a),a}}}var Og=r("../proto/dist/generated/agent/v1/computer_use_tool_pb.js");r("node:readline"),Error;var Fg=r("node:timers/promises");const Ng=ou.execFile;function Lg(e,t,r){return new Promise(((n,o)=>{r?.signal?.throwIfAborted();const s={timeout:r?.timeoutMs??3e4,env:r?.env?{...process.env,...r.env}:void 0,signal:r?.signal};(0,su.D9)(Ng,e,t.map(String),{...s,encoding:"utf8"},((e,t)=>{e?o(e):n(t)}))}))}Og.w3.UNSPECIFIED,Og.w3.LEFT,Og.w3.MIDDLE,Og.w3.RIGHT,Og.w3.BACK,Og.w3.FORWARD,Og.Dh.UNSPECIFIED,Og.Dh.UP,Og.Dh.DOWN,Og.Dh.LEFT,Og.Dh.RIGHT;const jg=(0,zs.promisify)(ou.execFile);function Ug(e){const t=e.lastIndexOf(":");if(-1===t)throw new Error(`Invalid X11 display string: ${e} (missing ':')`);const r=e.slice(t+1).split(".")[0],n=parseInt(r,10);if(!Number.isFinite(n)||n<0)throw new Error(`Invalid X11 display number in: ${e} (parsed: ${r})`);return n}function Bg(e,t,r,n){const o=function(e={}){const t=e.displayWidth??1920,r=e.displayHeight??1200,n=e.apiWidth??1280;return{width:n,height:Math.round(n*r/t)}}({displayWidth:e,displayHeight:t,apiWidth:r});return{display:{width:e,height:t},api:{width:o.width,height:n??o.height}}}async function Wg(e){const{stdout:t}=await(0,su.D9)(jg,"xrandr",["--display",e],{timeout:5e3,encoding:"utf8"}),r=function(e){let t,r,n;for(const o of e.split("\n"))if(o.includes("*")){const e=o.trim().match(/^(\d+)x(\d+)/);e&&(t=parseInt(e[1],10),r=parseInt(e[2],10));const s=o.match(/(\d+(?:\.\d+)?)\*(?:\+)?/);if(s){const e=parseFloat(s[1]);e>0&&e<=500&&(n=Math.round(e))}if(t&&r)break}if(!t||!r){const n=e.match(/current\s+(\d+)\s*x\s*(\d+)/i);n&&(t=parseInt(n[1],10),r=parseInt(n[2],10))}if(!t||!r)throw new Error(`Could not detect display resolution from xrandr output.\nExpected a line with '*' indicating active mode, or 'current WxH'.\nxrandr output:\n${e}`);return n||(n=60),{width:t,height:r,refreshRate:n}}(t);return{display:r,resolution:Bg(r.width,r.height),resolutionString:`${r.width}x${r.height}`}}Og.w3.UNSPECIFIED,Og.w3.LEFT,Og.w3.MIDDLE,Og.w3.RIGHT,Og.w3.BACK,Og.w3.FORWARD,Og.Dh.UNSPECIFIED,Og.Dh.UP,Og.Dh.DOWN,Og.Dh.LEFT,Og.Dh.RIGHT;const Hg={pattern:"[\\w-]{1,64}",next:e=>e},qg={pattern:"[0-9a-f-]{36}",next:()=>bo.randomUUID()},zg={pattern:"webp",next:()=>"webp"},Gg={native:[qg,zg],agent:[Hg,qg,zg],legacyNative:[qg,{pattern:"png",next:()=>"png"}]};new RegExp(`^(?:${Object.values(Gg).map((e=>e.map((e=>e.pattern)).join("\\."))).join("|")})$`),new RegExp(`^${Hg.pattern}$`),Og.Z8.NATIVE_X11,Og.Z8.XDOTOOL,(0,u.v5)("computer_use.session.duration_ms",{description:"Duration of computer-use session in milliseconds"}),(0,u.v5)("computer_use.session.action_count",{description:"Number of actions executed in a computer-use session"}),(0,u.Pu)("computer_use.session.result",{description:"Result status of computer-use session",labelNames:["outcome"]}),(0,u.Pu)("computer_use.session.action_kind",{description:"Requested computer-use actions by bounded kind",labelNames:["kind"]}),(0,l.h)("computer-use"),Math.floor(35927136),["Skip changes that cannot affect what runs in any deployed environment:","- documentation-only changes (Markdown, docs sites, code comments, changelogs)","- formatting, lint, or typo fixes with no behavior change","- test-only changes (test files, fixtures, snapshots)","Monitor everything else, including dependency bumps, configuration, and infrastructure changes."].join("\n"),Error,(0,u.Pu)("computer_use.desktop_lease.check",{description:"Desktop lease action-gate outcomes",labelNames:["outcome","reason"]});var Vg=r("../proto/dist/runtime/compact.js");Vg.HL;var Kg=(0,Vg.QT)(we.proto3,"agent.v1.","CursorType",[[0,"UNSPECIFIED"],[1,"ARROW"],[2,"POINTER"],[3,"TEXT"],[4,"WAIT"],[5,"CROSSHAIR"],[6,"MOVE"],[7,"RESIZE_NS"],[8,"RESIZE_EW"],[9,"RESIZE_NWSE"],[10,"RESIZE_NESW"],[11,"NOT_ALLOWED"],[12,"GRAB"],[13,"GRABBING"]],1);we.proto3,we.proto3,we.proto3,we.proto3;class Jg{constructor(e){this.config=e;const t=e.display.width/e.display.height,r=e.api.width/e.api.height;if(Math.abs(t-r)>.02)throw new Error(`Aspect ratio mismatch: display=${t.toFixed(3)}, api=${r.toFixed(3)}`);this.xScaleUp=e.display.width/e.api.width,this.yScaleUp=e.display.height/e.api.height,this.xScaleDown=e.api.width/e.display.width,this.yScaleDown=e.api.height/e.display.height}apiToDisplay(e,t){return{x:Math.round(e*this.xScaleUp),y:Math.round(t*this.yScaleUp)}}displayToApi(e,t){return{x:Math.round(e*this.xScaleDown),y:Math.round(t*this.yScaleDown)}}get apiWidth(){return this.config.api.width}get apiHeight(){return this.config.api.height}get displayWidth(){return this.config.display.width}get displayHeight(){return this.config.display.height}}const Zg={left_ptr:Kg.ARROW,arrow:Kg.ARROW,default:Kg.ARROW,top_left_arrow:Kg.ARROW,hand:Kg.POINTER,hand1:Kg.POINTER,hand2:Kg.POINTER,pointer:Kg.POINTER,pointing_hand:Kg.POINTER,xterm:Kg.TEXT,ibeam:Kg.TEXT,text:Kg.TEXT,watch:Kg.WAIT,wait:Kg.WAIT,progress:Kg.WAIT,left_ptr_watch:Kg.WAIT,crosshair:Kg.CROSSHAIR,cross:Kg.CROSSHAIR,tcross:Kg.CROSSHAIR,move:Kg.MOVE,fleur:Kg.MOVE,size_all:Kg.MOVE,sb_v_double_arrow:Kg.RESIZE_NS,v_double_arrow:Kg.RESIZE_NS,ns_resize:Kg.RESIZE_NS,row_resize:Kg.RESIZE_NS,top_side:Kg.RESIZE_NS,bottom_side:Kg.RESIZE_NS,sb_h_double_arrow:Kg.RESIZE_EW,h_double_arrow:Kg.RESIZE_EW,ew_resize:Kg.RESIZE_EW,col_resize:Kg.RESIZE_EW,left_side:Kg.RESIZE_EW,right_side:Kg.RESIZE_EW,top_left_corner:Kg.RESIZE_NWSE,bottom_right_corner:Kg.RESIZE_NWSE,nwse_resize:Kg.RESIZE_NWSE,size_fdiag:Kg.RESIZE_NWSE,top_right_corner:Kg.RESIZE_NESW,bottom_left_corner:Kg.RESIZE_NESW,nesw_resize:Kg.RESIZE_NESW,size_bdiag:Kg.RESIZE_NESW,not_allowed:Kg.NOT_ALLOWED,no_drop:Kg.NOT_ALLOWED,forbidden:Kg.NOT_ALLOWED,circle:Kg.NOT_ALLOWED,grab:Kg.GRAB,openhand:Kg.GRAB,grabbing:Kg.GRABBING,closedhand:Kg.GRABBING};class Xg{constructor(e){this.events=[],this.recordingStartTime=0,this.lastKnownPosition={x:0,y:0},this.isRunning=!1,this.pending=Promise.resolve();const t=e.displayNum??1;this.env={DISPLAY:`:${t}`},this.scaler=new Jg(e.resolution)}async start(){this.events=[],this.recordingStartTime=Date.now(),this.isRunning=!0,this.pending=Promise.resolve();try{this.lastKnownPosition=await this.captureCurrentPosition()}catch{this.lastKnownPosition={x:Math.floor(this.scaler.apiWidth/2),y:Math.floor(this.scaler.apiHeight/2)}}}logEvent(e,t,r){if(!this.isRunning)return;const n={...this.lastKnownPosition},o=this.getExpectedPositionAfterAction(e,n);this.lastKnownPosition=o;const s=async()=>{let s,i;try{[s,i]=await Promise.all([this.captureCurrentPosition(),this.detectCursorType()]),this.lastKnownPosition=s}catch{s=o,i=Kg.ARROW}const a={executionTimestampMs:r-this.recordingStartTime,action:e,commandDurationMs:r-t,positionBefore:n,positionAfter:s,cursorTypeAfter:i};this.events.push(a)};this.pending=this.pending.then((()=>s())).catch((()=>{}))}async stop(){return this.isRunning=!1,await this.pending,[...this.events]}getEvents(){return[...this.events]}getRecordingStartTime(){return this.recordingStartTime}getIsRunning(){return this.isRunning}async captureCurrentPosition(){const e=await Lg("xdotool",["getmouselocation","--shell"],{env:this.env}),t=e.match(/X=(\d+)/),r=e.match(/Y=(\d+)/);if(!t||!r)throw new Error(`Failed to parse cursor position: ${e}`);const n=parseInt(t[1],10),o=parseInt(r[1],10);return this.scaler.displayToApi(n,o)}async detectCursorType(){try{const e=(await Lg("xdotool",["getmouselocation","--shell"],{env:this.env})).match(/CURSOR=(\S+)/i);if(e){const t=e[1].toLowerCase();return Zg[t]??Kg.ARROW}try{const e=await Lg("xprop",["-root","_XSERVER_CURSOR"],{env:this.env,timeoutMs:500});for(const[t,r]of Object.entries(Zg))if(e.toLowerCase().includes(t))return r}catch{}return Kg.ARROW}catch{return Kg.ARROW}}getExpectedPositionAfterAction(e,t){const r=e.action;if(!r)return t;switch(r.case){case"mouseMove":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}case"click":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}case"drag":{const e=r.value.path;if(e.length>0){const t=e[e.length-1];return{x:t.x,y:t.y}}break}case"scroll":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}}return t}}(0,l.h)("computer-use-lazy");var Qg=r("node:net");function Yg(e){return!!e.includes(o.homedir())||e.includes("node_modules")||e.includes("Application Support")||/\.wasm\b/.test(e)||/(?:^|[\s'`"(=])(?:\/|\.{1,2}\/)/.test(e)||/(?:^|[\s'`"(=:])(?:[A-Za-z]:[\\/]|\\\\)/.test(e)||/\bS-1-5-21(?:-\d+){3,}/i.test(e)}class ew extends Error{constructor(e){super(e),this.name="MacRPCProtocolError"}}const tw=je.object({rpcSocketPath:je.string().min(1).optional(),appControlSocketPath:je.string().min(1).optional(),pid:je.number().int().positive().optional().catch(void 0),protocolMajor:je.number().int().positive().optional().catch(void 0)}).passthrough(),rw=je.object({data:je.string(),mimeType:je.string().min(1)}).strip(),nw=je.object({message:je.string(),screenshot:rw.optional(),screenshotBefore:rw.optional(),structuredContent:je.unknown().optional(),isError:je.boolean()}).strip(),ow=je.object({accessibilityTrusted:je.boolean(),screenRecordingGranted:je.boolean()}).strip(),sw=je.union([je.object({id:je.number().int(),result:nw,ok:je.never().optional(),error:je.never().optional(),errorCode:je.never().optional(),permissionStatus:je.never().optional(),sessionId:je.never().optional()}).strip(),je.object({id:je.number().int(),sessionId:je.string().min(1),ok:je.literal(!0).optional(),result:je.never().optional(),error:je.never().optional(),errorCode:je.never().optional(),permissionStatus:je.never().optional()}).strip(),je.object({id:je.number().int(),ok:je.literal(!0),result:je.never().optional(),error:je.never().optional(),errorCode:je.never().optional(),permissionStatus:je.never().optional(),sessionId:je.never().optional()}).strip(),je.object({id:je.number().int().nullable().optional(),error:je.string().min(1),errorCode:je.string().min(1).optional(),result:je.never().optional(),ok:je.never().optional(),permissionStatus:je.never().optional(),sessionId:je.never().optional()}).strip(),je.object({id:je.number().int(),permissionStatus:ow,result:je.never().optional(),ok:je.never().optional(),error:je.never().optional(),errorCode:je.never().optional(),sessionId:je.never().optional()}).strip()]);function iw(e,t){try{return JSON.parse(e)}catch{throw new ew(`local-cua ${t} is not valid JSON`)}}const aw={responseMaxBytes:33554432,parseServiceState(e){const t=tw.safeParse(iw(e,"service state")),r=t.success?t.data.rpcSocketPath??t.data.appControlSocketPath:void 0;if(!t.success||void 0===r)throw new ew("local-cua service state is malformed");return{...t.data,rpcSocketPath:r}},parseResponse({line:e,expectedID:t}){const r=sw.safeParse(iw(e.toString("utf8"),"RPC response"));if(!r.success)throw new ew("local-cua RPC response is malformed");if(void 0!==r.data.id&&null!==r.data.id&&r.data.id!==t)throw new ew("local-cua RPC response ID did not match");return r.data}};class cw extends Error{constructor(e,t){super(e),this.name="MacComputerUseRPCError",this.code=t?.code,this.userFacing=!0===t?.userFacing,this.tool=t?.tool}}function lw(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:e instanceof Error?Yg(e.message)?e.name:e.message.length>0?`${e.name}: ${e.message}`:e.name:"unknown"}const uw=new Map([["co.anysphere.cursor-computer-use","cursor-computer-use"],["co.anysphere.cursor-computer-use.dev","cursor-computer-use-dev"]]),dw=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;class hw{constructor(e){this.mode=e}static isInstalled(){if((0,xo.existsSync)(hw.serviceExecutablePath()))return!0;let e;try{e=aw.parseServiceState((0,xo.readFileSync)(hw.serviceStatePath(),"utf8"))}catch{return!1}return void 0===e.pid||hw.isProcessAlive(e.pid)}static async runningHelperPid(){const e=await hw.readServiceState(),t=e?.pid;return void 0!==t&&hw.isProcessAlive(t)?t:void 0}static isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}static isExitedIncompatibleHelper(e){return void 0!==e.protocolMajor&&e.protocolMajor!==hw.protocolMajor&&void 0!==e.pid&&!hw.isProcessAlive(e.pid)}screenshot(e){return this.callTool(e,"computer_use_screenshot",{})}click(e,t){return this.callTool(e,"computer_use_click",{method:"coordinate",...void 0!==t.coordinate&&{x:t.coordinate.x,y:t.coordinate.y},button:t.button,count:t.count,modifier_keys:t.modifierKeys})}scroll(e,t){return this.callTool(e,"computer_use_scroll",{x:t.coordinate?.x,y:t.coordinate?.y,direction:t.direction,amount:t.amount,modifier_keys:t.modifierKeys})}move(e,t){return this.callTool(e,"computer_use_mouse_move",{x:t.x,y:t.y})}mouseButton(e,t){return this.callTool(e,"computer_use_mouse_button",{button:t.button,action:t.action})}drag(e,t){return this.callTool(e,"computer_use_drag",{button:t.button,path:t.path,modifier_keys:t.modifierKeys})}typeText(e,t){return this.callTool(e,"computer_use_typing",{value:t})}pressKey(e,t){return this.callTool(e,"computer_use_press_key",{key:t.key,hold_duration_ms:t.holdDurationMs})}checkPermissions(e){return this.callTool(e,"computer_use_check_permissions",{})}async startControl(e){if("remote"!==this.mode||void 0!==this.activeSessionId)return;hw.throwIfAborted(e.signal);const t=(0,bo.randomUUID)(),r=await this.sendWithRelaunchRetry(e,(()=>({id:hw.requestID,method:"control/start",requestID:t,mode:this.mode})),"control/start");if(void 0!==r.error)throw hw.rpcError(r);if(void 0===r.sessionId)throw new cw("local-cua control/start returned no session");this.activeSessionId=r.sessionId}async releaseControl(e){const t=this.activeSessionId;if(void 0!==t){this.activeSessionId=void 0;try{const e=await hw.readServiceState();if(void 0===e)return;const r=await hw.sendOnce(hw.socketPathFrom(e),{id:hw.requestID,method:"control/release",requestID:(0,bo.randomUUID)(),mode:this.mode,sessionId:t},hw.defaultCallTimeoutMs);if(void 0!==r.error)throw hw.rpcError(r)}catch(t){hw.logger.warn(e,"local-cua control release failed",{error:lw(t)})}}}async callTool(e,t,r){hw.throwIfAborted(e.signal);const n=hw.defaultCallTimeoutMs,o=await this.sendWithRelaunchRetry(e,(()=>{const e=Date.now()/1e3,o=this.activeSessionId;return{id:hw.requestID,method:"tools/call",requestID:(0,bo.randomUUID)(),name:t,arguments:r,timeoutSeconds:n/1e3,startedAtEpochSeconds:e,deadlineEpochSeconds:e+n/1e3,mode:this.mode,...void 0!==o&&{sessionId:o}}}),t);if(void 0!==o.error)throw hw.rpcError(o,t);const s=o.result;if(void 0===s)throw new cw(`local-cua tool ${t} returned no result`,{tool:t});if(s.isError){const e=s.message.trim();throw new cw(e.length>0?e:`local-cua tool ${t} reported an error`,{tool:t,userFacing:e.length>0})}return s}async sendWithRelaunchRetry(e,t,r){const n=hw.defaultCallTimeoutMs,o=await this.ensureSocketPath(e);hw.throwIfAborted(e.signal);try{return await hw.sendOnce(o,t(),n,e.signal)}catch(o){if(!hw.isPreDeliveryConnectionError(o))throw o;hw.logger.warn(e,"local-cua callTool failed; relaunching and retrying",{tool:r,error:hw.spawnErrorCode(o)});const s=await this.ensureSocketPath(e,!0);return hw.throwIfAborted(e.signal),void 0!==this.activeSessionId&&(this.activeSessionId=void 0,await this.startControl(e)),await hw.sendOnce(s,t(),n,e.signal)}}static rpcError(e,t){return new cw(e.error,{code:e.errorCode,userFacing:!0,tool:t})}async ensureSocketPath(e,t=!1){if(hw.throwIfAborted(e.signal),!t){const e=await hw.readServiceState();if(e&&!hw.isExitedIncompatibleHelper(e))return hw.socketPathFrom(e)}await this.launchAndWait(e);const r=await hw.readServiceState();if(!r)throw new cw("local-cua sidecar did not publish service.json after launch");return hw.socketPathFrom(r)}static setLaunchGuard(e){hw.launchGuard=e}async launchAndWait(e){const t=hw.serviceAppPath(),r=hw.launchGuard,n=()=>this.launchAppAndWait(e,t);await(void 0===r?n():r(t,n,e.signal))}async launchAppAndWait(e,t){hw.logger.info(e,"launching local-cua sidecar",hw.sidecarLaunchLogFields(t)),"1"===process.env[hw.directLaunchEnv]?await hw.spawnSidecarProcess(e,hw.serviceExecutablePath(),[],{detached:!0}):await hw.spawnSidecarProcess(e,"/usr/bin/open",["-g",t]);const r=Date.now()+hw.launchReadyTimeoutMs;for(;Date.now()0?e:s.join(o.homedir(),...hw.sharedInstallRelativePath,`${hw.serviceAppBundleName}.app`)}static helperIdentity(){const e=hw.serviceAppPath(),t=process.env[hw.appSupportOverrideEnv],r=`${e}\0${t??""}`,n=hw.identityCache;if(n?.key===r)return n.identity;const i=function(e){let t;try{t=(0,xo.readFileSync)(s.join(e,"Contents","Info.plist"),"utf8")}catch{return{}}const r=e=>{const r=new RegExp(`${e}\\s*([^<]*)`).exec(t)?.[1];return void 0!==r&&dw.test(r.trim())?r.trim():void 0};return{executableName:r("CFBundleExecutable"),bundleIdentifier:r("CFBundleIdentifier")}}(e),a=s.join(e,"Contents","MacOS",i.executableName??hw.productionExecutableName),c={appPath:e,executablePath:a,appSupportDirectory:void 0!==t&&t.length>0?t:s.join(o.homedir(),"Library","Application Support",(void 0===i.bundleIdentifier?void 0:uw.get(i.bundleIdentifier))??hw.appSupportFolder)};return(0,xo.existsSync)(a)&&(hw.identityCache={key:r,identity:c}),c}static sidecarLaunchLogFields(e){const t=`${hw.serviceAppBundleName}.app`;return{appName:s.basename(e)===t?t:"custom",appPathHash:(0,bo.createHash)("sha256").update(e).digest("hex"),usingOverride:Boolean(process.env[hw.serviceAppOverrideEnv])}}static spawnErrorCode(e){return lw(e)}static socketError(e){const t=lw(e);return new cw(`local-cua RPC connection failed: ${t}`,{code:t})}static serviceExecutablePath(){return hw.helperIdentity().executablePath}static spawnSidecarProcess(e,t,r,n){return new Promise(((o,s)=>{const i=(0,ou.spawn)(t,[...r],{detached:!0===n?.detached,stdio:"ignore"}),a=e=>{s(new cw(`local-cua sidecar launch failed: ${hw.spawnErrorCode(e)}`))};i.once("error",a),i.once("spawn",(()=>{i.removeListener("error",a),i.on("error",(t=>{hw.logger.warn(e,"local-cua sidecar process error after launch",{error:hw.spawnErrorCode(t)})})),i.unref(),o()}))}))}static async readServiceState(){try{const e=await(0,Co.readFile)(hw.serviceStatePath(),"utf8");return aw.parseServiceState(e)}catch(e){if(e instanceof Error&&"code"in e&&"ENOENT"===e.code)return;if(e instanceof ew)return;throw new cw("local-cua service state could not be read")}}static socketPathFrom(e){if(void 0!==e.protocolMajor&&e.protocolMajor!==hw.protocolMajor)throw new cw(`The running Cursor Computer Use speaks protocol ${e.protocolMajor}, and this Cursor CLI speaks protocol ${hw.protocolMajor}. Update the Cursor CLI.`,{userFacing:!0});return e.rpcSocketPath}static abortError(e){return e.reason instanceof Error?e.reason:new cw("local-cua RPC aborted")}static throwIfAborted(e){if(e.aborted)throw hw.abortError(e)}static sendOnce(e,t,r,n){return n?.aborted?Promise.reject(hw.abortError(n)):new Promise(((o,s)=>{let i=!1,a=[],c=0,l=!1;const u=(0,Qg.createConnection)({path:e}),d=e=>{i||(i=!0,clearTimeout(p),n?.removeEventListener("abort",h),u.destroy(),e())},h=()=>{d((()=>s(void 0===n?new cw("local-cua RPC aborted"):hw.abortError(n))))},p=setTimeout((()=>{d((()=>s(new cw(`local-cua RPC timed out after ${r}ms`))))}),r);n?.addEventListener("abort",h,{once:!0}),n?.aborted?h():(u.on("connect",(()=>{u.write(`${JSON.stringify(t)}\n`,(e=>{null==e?l=!0:d((()=>s(hw.socketError(e))))}))})),u.on("data",(e=>{const t=e.indexOf(10),r=c+(t<0?e.length:t);if(r>aw.responseMaxBytes)return void d((()=>s(new cw("local-cua RPC response exceeded the size limit"))));if(t<0)return a.push(e),void(c+=e.length);a.push(e.subarray(0,t));const n=Buffer.concat(a,r);a=[],c=0;try{const e=aw.parseResponse({line:n,expectedID:hw.requestID});d((()=>o(e)))}catch(e){d((()=>s(e)))}})),u.on("error",(e=>{d(l?()=>s(new cw("local-cua RPC connection failed after request delivery")):()=>s(hw.socketError(e)))})),u.on("close",(()=>{const e=c>0?"local-cua RPC response ended without a newline":l?"local-cua RPC connection closed after request delivery":"local-cua RPC connection closed";d((()=>s(new cw(e))))})))}))}}let pw;function fw(){if(void 0===pw){const e=async function(){const[{createJimp:e},{default:t},{default:n},{default:o,msBmp:s},{default:i},{default:a},{methods:c}]=await Promise.all([Promise.all([r.e(731),r.e(250)]).then(r.bind(r,"../../node_modules/.pnpm/@jimp+core@1.6.0/node_modules/@jimp/core/dist/esm/index.js")),r.e(690).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-png@1.6.0/node_modules/@jimp/js-png/dist/esm/index.js")),r.e(831).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-jpeg@1.6.0/node_modules/@jimp/js-jpeg/dist/esm/index.js")),Promise.all([r.e(731),r.e(284)]).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-bmp@1.6.0/node_modules/@jimp/js-bmp/dist/esm/index.js")),r.e(295).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-gif@1.6.0/node_modules/@jimp/js-gif/dist/esm/index.js")),r.e(181).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-tiff@1.6.0/node_modules/@jimp/js-tiff/dist/esm/index.js")),r.e(162).then(r.bind(r,"../../node_modules/.pnpm/@jimp+plugin-resize@1.6.0/node_modules/@jimp/plugin-resize/dist/esm/index.js"))]);return e({formats:[t,n,o,s,i,a],plugins:[c]})}().catch((t=>{throw pw===e&&(pw=void 0),t}));pw=e}return pw}hw.logger=(0,l.h)("local-cua:rpc"),hw.serviceAppBundleName="Cursor Computer Use",hw.appSupportFolder="cursor-computer-use",hw.productionExecutableName="CUCursorService",hw.sharedInstallRelativePath=[".cursor","computer-use-sidecar"],hw.appSupportOverrideEnv="CUA_APP_SUPPORT_DIR",hw.serviceAppOverrideEnv="CUA_SERVICE_APP",hw.directLaunchEnv="CUA_DIRECT_LAUNCH",hw.protocolMajor=1,hw.defaultCallTimeoutMs=45e3,hw.launchReadyTimeoutMs=8e3,hw.launchPollIntervalMs=200,hw.requestID=1;var mw=r("node:module");const gw="mac-webp-runtime.cjs";function ww(e){return"function"==typeof e}function yw(e){return"object"==typeof e&&null!==e&&"getFileName"in e&&"function"==typeof e.getFileName}function vw(){const e=(new Error).stack;return Array.isArray(e)?e.filter(yw):[]}let bw,Sw;function kw(){return bw??=(()=>{const e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;const e=vw()[0]?.getFileName();return function(){const e=mw;if("createRequire"in e&&ww(e.createRequire))return e.createRequire;if("default"in e&&"object"==typeof e.default&&null!==e.default&&"createRequire"in e.default&&ww(e.default.createRequire))return e.default.createRequire;throw new Error("node:module createRequire is unavailable")}()("string"==typeof e&&e.length>0?e:(0,s.join)(process.cwd(),"package.json"))}finally{Error.prepareStackTrace=e}})(),bw}function _w(){const e=globalThis.__MAC_WEBP_IMPORT__;return"function"==typeof e?t=>Promise.resolve(e(t)):(Sw??=function(){const e=[],t=new Set,r=r=>{t.has(r)||(t.add(r),e.push(r))};for(const e of function(){const e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;const e=[];for(const t of vw()){const r=t.getFileName();"string"==typeof r&&r.length>0&&e.push(r)}return e}finally{Error.prepareStackTrace=e}}()){const t=(0,s.dirname)((n=e).startsWith("file:")?(0,Ed.fileURLToPath)(n):n);r((0,s.join)(t,gw)),r((0,s.join)(t,"..","..","src","computer-use",gw))}var n;"string"==typeof process.argv[1]&&process.argv[1].length>0&&r((0,s.join)((0,s.dirname)(process.argv[1]),gw)),r((0,s.join)(process.cwd(),"src","computer-use",gw)),r((0,s.join)(process.cwd(),"computer-use",gw));try{const e=(0,s.dirname)(kw().resolve("@anysphere/local-exec/package.json"));r((0,s.join)(e,"src","computer-use",gw)),r((0,s.join)(e,"dist","computer-use",gw))}catch{}for(const t of e)try{const e=kw()(t);if("object"==typeof e&&null!==e&&"importFile"in e&&"function"==typeof e.importFile)return e.importFile.bind(e)}catch{}throw new Error("mac-webp runtime importer was not found next to the bundle")}(),Sw)}function Cw(...e){return t=["@jsquash","webp",...e].join("/"),kw().resolve(t);var t}async function Ew(...e){var t;return await(t=(0,Ed.pathToFileURL)(Cw(...e)).href,_w()(t))}const xw=e=>{let t;return()=>{if(void 0===t){const r=e();r.catch((()=>{t===r&&(t=void 0)})),t=r}return t}},Pw=(xw((async()=>{const e=await Ew("decode.js");return await e.init({wasmBinary:await xo.promises.readFile(Cw("codec","dec","webp_dec.wasm"))}),e})),xw((async()=>{const[e,t,r]=await Promise.all([Ew("utils.js"),Ew("meta.js"),Ew("codec","enc","webp_enc.js")]);return{module:await e.initEmscriptenModule(r.default,void 0,{wasmBinary:await xo.promises.readFile(Cw("codec","enc","webp_enc.wasm"))}),defaultOptions:t.defaultOptions}}))),Rw="image/png",Iw={async normalize(e){if(e.mimeType!==Rw)throw new Error(`Mac screenshot must be ${Rw}, received ${e.mimeType}`);const t=await fw(),r=await t.read(Buffer.from(e.data,"base64"));return(await(n={data:r.bitmap.data,width:r.bitmap.width,height:r.bitmap.height},(async e=>{const{module:t,defaultOptions:r}=await Pw(),n=new Uint8ClampedArray(e.data.buffer,e.data.byteOffset,e.data.byteLength);return Buffer.from(t.encode(n,e.width,e.height,{...r,lossless:1,exact:1}))})(n))).toString("base64");var n}},Tw={userFacing:function(e){if(e instanceof cw&&e.userFacing&&e.message.trim().length>0&&!Yg(e.message))return e.message.trim()},isCaptureBlocked:function(e){return e instanceof cw&&("computer_use_screenshot"===e.tool||"permission_required"===e.code)}},Aw=new Set(["keys"]),$w=new Set(["matched","mismatch","unchecked"]),Mw=new Set(["no_text","password","control_keys","too_long","unreadable","moved","chromium","gecko"]),Dw=new Set(["matched"]),Ow=new Set(["too_long"]),Fw=new Set(["watched","fell_back","unavailable","over_budget"]);class Nw{constructor({ctx:e,actions:t,sidecar:r,errors:n,reportTyping:o}){this.startTime=Date.now(),this.typingNotes=[],this.typing=[],this.geometryPrimed=!1,this.actionCount=0,this.hasCompletedActuation=!1,this.staleAfterWait=!1,this.ctx=e,this.actions=t,this.sidecar=r,this.errors=n??Tw,this.reportTyping=!0===o}async execute(){const e=this.actions.some((e=>Nw.isInputAction(e.action.case)));try{this.throwIfAborted(),e&&await this.sidecar.startControl(this.ctx);for(const e of this.actions){this.throwIfAborted();const t=e.action;if(void 0===t.case)throw new Error("Computer use action case is undefined");switch(this.actionCount+=1,t.case){case"screenshot":case"cursorPosition":await this.captureScreen();break;case"click":void 0!==t.value.coordinate&&await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.click(this.ctx,{coordinate:t.value.coordinate,button:Nw.mouseButtonName(t.value.button),count:t.value.count>0?t.value.count:1,modifierKeys:t.value.modifierKeys}),t.value.coordinate);break;case"scroll":void 0!==t.value.coordinate&&await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.scroll(this.ctx,{coordinate:t.value.coordinate,direction:Nw.scrollDirectionName(t.value.direction),amount:t.value.amount>0?t.value.amount:3,modifierKeys:t.value.modifierKeys}),t.value.coordinate);break;case"mouseMove":if(void 0===t.value.coordinate)throw new Error("MouseMoveAction requires coordinate");await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.move(this.ctx,{x:t.value.coordinate.x,y:t.value.coordinate.y}),t.value.coordinate);break;case"mouseDown":this.recordActuation(await this.sidecar.mouseButton(this.ctx,{button:Nw.mouseButtonName(t.value.button),action:"down"}));break;case"mouseUp":this.recordActuation(await this.sidecar.mouseButton(this.ctx,{button:Nw.mouseButtonName(t.value.button),action:"up"}));break;case"drag":{const e=t.value.path.map((e=>({x:e.x,y:e.y})));await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.drag(this.ctx,{button:Nw.mouseButtonName(t.value.button),path:e,modifierKeys:t.value.modifierKeys}),e.at(-1));break}case"type":{const e=await this.sidecar.typeText(this.ctx,t.value.text);this.recordActuation(e),this.recordTyping(e);break}case"key":if(t.value.stroke===Og.EB.DOWN||t.value.stroke===Og.EB.UP)throw new Error("Held keys (KeyAction.stroke DOWN/UP) are not supported by the computer-use sidecar; use hold_duration_ms");this.recordActuation(await this.sidecar.pressKey(this.ctx,{key:t.value.key,holdDurationMs:t.value.holdDurationMs}));break;case"wait":await this.delay(Math.max(0,t.value.durationMs)),this.staleAfterWait=!0;break;default:{const e=t;throw new Error(`Unknown computer use action: ${JSON.stringify(e)}`)}}}this.throwIfAborted(),(void 0===this.screenshot||this.staleAfterWait)&&await this.captureScreen(),this.throwIfAborted();const t=await this.normalizeRetainedScreenshots();return t.screenshotFailed&&!this.hasCompletedActuation?this.screenshotUnavailableResult(t.failureReason):(this.throwIfAborted(),new Og.ks({result:{case:"success",value:new Og.Wd({actionCount:this.actionCount,durationMs:Date.now()-this.startTime,screenshot:t.screenshot,cursorPosition:this.cursor,log:this.log(t.screenshotFailed?"Screenshot unavailable":void 0),typing:this.typing})}}))}catch(e){return this.ctx.signal.aborted?this.abortedResult():this.errorResult(e)}finally{e&&await this.sidecar.releaseControl(this.ctx)}}static isInputAction(e){switch(e){case"click":case"scroll":case"mouseMove":case"mouseDown":case"mouseUp":case"drag":case"type":case"key":return!0;default:return!1}}async captureScreen(){const e=await this.sidecar.screenshot(this.ctx);this.screenshot=e.screenshot,this.cursor=Nw.cursorFromResult(e)??this.cursor,this.geometryPrimed=!0,this.staleAfterWait=!1}async ensureGeometryCached(){this.geometryPrimed||await this.captureScreen()}recordActuation(e,t){this.screenshot=e.screenshot,this.hasCompletedActuation=!0,this.staleAfterWait=!1,void 0!==e.screenshot&&(this.geometryPrimed=!0),this.cursor=Nw.cursorFromResult(e)??Nw.coordinateFromPoint(t)??this.cursor}recordTyping(e){if(!this.reportTyping)return;const t=e.message.trim();""!==t&&this.typingNotes.push(t);const r=Nw.typingFromResult(e);void 0!==r&&this.typing.push(r)}log(e){const t=void 0===e?this.typingNotes:[...this.typingNotes,e];return 0===t.length?void 0:t.join("\n")}static typingFromResult(e){const t=e.structuredContent;if("object"!=typeof t||null===t||!("type"in t))return;const r=t.type;if("object"!=typeof r||null===r)return;const n=new Map(Object.entries(r)),o=(e,t)=>{const r=n.get(e);return"string"==typeof r&&t.has(r)?r:void 0},s=e=>{const t=n.get(e);return"number"==typeof t&&Number.isInteger(t)&&t>=0?t:void 0},i=o("check",$w),a=o("unchecked",Mw),c=void 0!==n.get("unchecked")&&null!==n.get("unchecked"),l=void 0!==i&&Dw.has(i)&&!c||"unchecked"===i&&void 0!==a&&Ow.has(a);return new Og.qA({method:o("method",Aw)??"",chars:l?s("chars")??0:0,atoms:l?s("atoms")??0:0,typedAtoms:l?s("typedAtoms")??0:0,aborted:!0===n.get("aborted"),check:i,verified:l?s("verified"):void 0,unchecked:a,landing:o("landing",Fw)})}async errorResult(e){let t;if(Nw.logger.error(this.ctx,"local-cua execute failed",void 0,{error:lw(e)}),!this.errors.isCaptureBlocked(e))try{const e=await this.sidecar.screenshot(this.ctx);t=(await this.normalizeScreenshot(e.screenshot,"error")).data}catch(e){Nw.logger.warn(this.ctx,"local-cua error screenshot capture failed",{error:lw(e)})}const r=this.errors.userFacing(e);return new Og.ks({result:{case:"error",value:new Og.Jb({error:void 0===r?"Computer use failed":`Computer use failed: ${r}`,actionCount:this.actionCount,durationMs:Date.now()-this.startTime,screenshot:t,log:this.log(),typing:this.typing})}})}screenshotUnavailableResult(e){return new Og.ks({result:{case:"error",value:new Og.Jb({error:"Screenshot unavailable",actionCount:this.actionCount,durationMs:Date.now()-this.startTime,log:e})}})}abortedResult(){return new Og.ks({result:{case:"error",value:new Og.Jb({error:"Computer use aborted",actionCount:this.actionCount,durationMs:Date.now()-this.startTime,log:this.log(),typing:this.typing})}})}static mouseButtonName(e){return Nw.mouseButtonNames[e]??"left"}static scrollDirectionName(e){return Nw.scrollDirectionNames[e]??"down"}async normalizeRetainedScreenshots(){const e=await this.normalizeScreenshot(this.screenshot,"post-action");return{screenshot:e.data,screenshotFailed:void 0===this.screenshot||e.failed,failureReason:void 0===this.screenshot?"sidecar returned no image":e.reason}}async normalizeScreenshot(e,t){if(void 0===e)return{failed:!1};try{return{data:await Iw.normalize(e),failed:!1}}catch(r){const n=lw(r);return Nw.logger.error(this.ctx,"local-cua screenshot conversion failed",void 0,{frame:t,error:n}),"image/png"===e.mimeType&&e.data.length>0?{data:e.data,failed:!1}:{failed:!0,reason:n}}}static coordinateFromPoint(e){if(void 0!==e&&Number.isFinite(e.x)&&Number.isFinite(e.y))return new Og.xp({x:Math.round(e.x),y:Math.round(e.y)})}static cursorFromResult(e){const t=e.structuredContent;if("object"!=typeof t||null===t||!("cursor"in t))return;const r=t.cursor;return"object"==typeof r&&null!==r&&"x"in r&&"y"in r&&"number"==typeof r.x&&"number"==typeof r.y&&Number.isFinite(r.x)&&Number.isFinite(r.y)?new Og.xp({x:Math.round(r.x),y:Math.round(r.y)}):void 0}throwIfAborted(){if(this.ctx.signal.aborted)throw this.ctx.signal.reason??new Error("Computer use aborted")}delay(e){return this.throwIfAborted(),new Promise(((t,r)=>{const n=()=>{clearTimeout(o),r(this.ctx.signal.reason??new Error("Computer use aborted"))},o=setTimeout((()=>{this.ctx.signal.removeEventListener("abort",n),t()}),e);this.ctx.signal.addEventListener("abort",n,{once:!0}),this.ctx.signal.aborted&&n()}))}}Nw.logger=(0,l.h)("local-cua:actions"),Nw.mouseButtonNames={[Og.w3.UNSPECIFIED]:"left",[Og.w3.LEFT]:"left",[Og.w3.RIGHT]:"right",[Og.w3.MIDDLE]:"middle",[Og.w3.BACK]:"left",[Og.w3.FORWARD]:"left"},Nw.scrollDirectionNames={[Og.Dh.UNSPECIFIED]:"down",[Og.Dh.UP]:"up",[Og.Dh.DOWN]:"down",[Og.Dh.LEFT]:"left",[Og.Dh.RIGHT]:"right"},s.default.join(o.default.tmpdir(),"computer-use"),(0,l.h)("local-cua:windows");Error,Buffer.from([137,80,78,71,13,10,26,10]),new Set(["capture_failed","secure_desktop","input_desktop_unavailable","sidecar_unavailable","user_aborted","session_busy","canvas_mismatch"]);var Lw,jw=r("../proto/dist/generated/agent/v1/delete_exec_pb.js");function Uw({encoding:e,bom:t,lineEnding:r}){return{encoding:e,bom:t,lineEnding:r}}class Bw{constructor(e){this.workspacePath=e,this.changes=new Map,this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){for(const t of this.listeners)t(e)}async trackChange(e,t,r,n,o){const s=this.changes.get(e);if(s){const t=s.before,o=n||s.metadata;if(t===r||void 0===t&&void 0===r)this.changes.delete(e),this.notify();else{const n={path:e,before:t,after:r,metadata:o,...void 0===s.beforeFormat?{}:{beforeFormat:s.beforeFormat}};this.changes.set(e,n),this.notify(n)}}else{const s={path:e,before:t,after:r,metadata:n,...void 0===o?{}:{beforeFormat:o}};this.changes.set(e,s),this.notify(s)}}getChanges(){return Array.from(this.changes.values())}getChange(e){return this.changes.get(e)}hasChange(e){return this.changes.has(e)}accept(e){const t=this.changes.get(e);this.changes.delete(e),this.notify(t)}acceptAll(){this.changes.clear(),this.notify()}async reject(e){const t=this.changes.get(e);if(t)try{void 0===t.before&&void 0!==t.after?await(0,Co.unlink)(e):(void 0!==t.before&&void 0===t.after||void 0!==t.before&&void 0!==t.after)&&await async function(e,t,r,n){const{buffer:o,format:s}=await Wi(e,t,r,n);await(0,Co.writeFile)(e,o),await Bi(e,{buffer:o,encoding:s.encoding})}(e,t.before,this.workspacePath)}catch{}finally{this.changes.delete(e),this.notify(t)}}async rejectAll(){const e=Array.from(this.changes.keys());await Promise.all(e.map((e=>this.reject(e))))}clear(){const e=this.changes.values().next().value;this.changes.clear(),this.notify(e)}get size(){return this.changes.size}dispose(){this.changes.clear(),this.listeners.clear()}}!function(e){e.Write="write",e.Read="read",e.Shell="shell",e.Delete="delete",e.Mcp="mcp"}(Lw||(Lw={}));var Ww=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class Hw{constructor(e,t,r,n,o,s){this.pendingDecisionProvider=e,this.fileChangeTracker=t,this.permissionsService=r,this.workspacePath=n,this.onDeleteForAiTracking=o,this.agentFileViews=s}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,$.VI)(e.withName("LocalDeleteExecutor.execute")),!1);const n=t.path;if(""===n.trim())return new jw.Pi({result:{case:"error",value:new jw.GU({path:n,error:es})}});const o=(0,Yo.o1)(n,this.workspacePath),i=await this.permissionsService.shouldBlockWrite(e,o,"");if(i){const e=await Qu(i,{onNeedsApproval:async(e,t)=>null,onUserRejected:e=>new jw.Pi({result:{case:"rejected",value:new jw.iq({path:o,reason:e||""})}}),onPermissionDenied:(e,t)=>new jw.Pi({result:{case:"permissionDenied",value:new jw.QG({path:o,clientVisibleError:e,isReadonly:t?.isReadonly??!1})}})});if(null!==e)return e}const a=await async function(e,t){const r=await(0,Co.realpath)((0,s.dirname)(e)).catch((()=>{}));if(void 0===r)return e;if(void 0!==t){const n=await(0,Co.realpath)(t).catch((()=>{}));if(void 0!==n&&(0,Yo.BJ)(r,n))return(0,s.resolve)(t,(0,s.relative)(n,r),(0,s.basename)(e))}return(0,s.join)(r,(0,s.basename)(e))}(o,this.workspacePath),c=await this.pendingDecisionProvider.requestApproval({type:Lw.Delete,details:{path:a},toolCallId:t.toolCallId});if(!c.approved)return new jw.Pi({result:{case:"rejected",value:new jw.iq({path:o,reason:c.reason||""})}});let l;try{l=await(0,Co.stat)(o)}catch(e){return"ENOENT"===Sc(e)?new jw.Pi({result:{case:"fileNotFound",value:new jw.n0({path:o})}}):new jw.Pi({result:{case:"error",value:new jw.GU({path:o,error:kc(e)})}})}if(!l.isFile()){const e=l.isDirectory()?"directory":"other";return new jw.Pi({result:{case:"notFile",value:new jw.LX({path:o,actualType:e})}})}const u=l.size;let d,h;if(u<=ns)try{const e=await Ui(o);d=e.text,h=Uw(e)}catch{}const p=d??"",f=await(0,Co.realpath)(o).catch((()=>o)),m=await(0,Co.stat)(o).catch((()=>{}));if(m?.dev!==l.dev||m.ino!==l.ino)return new jw.Pi({result:{case:"error",value:new jw.GU({path:o,error:"File changed while deleting; nothing was removed"})}});e.signal.throwIfAborted();try{await(0,Co.unlink)(o),this.agentFileViews?.recordDelete(o)}catch(e){return"EACCES"===Sc(e)?new jw.Pi({result:{case:"permissionDenied",value:new jw.QG({path:o,clientVisibleError:"Permission denied"})}}):"EBUSY"===Sc(e)?new jw.Pi({result:{case:"fileBusy",value:new jw.vX({path:o})}}):new jw.Pi({result:{case:"error",value:new jw.GU({path:o,error:kc(e)})}})}if(this.fileChangeTracker&&void 0!==d){const e={...t.toolCallId?{toolCallId:t.toolCallId}:{},...f===o?{}:{writtenPath:f},beforeMode:511&l.mode};await this.fileChangeTracker.trackChange(o,d,void 0,e,h)}return this.onDeleteForAiTracking&&this.onDeleteForAiTracking({path:o}).catch((()=>{})),new jw.Pi({result:{case:"success",value:new jw.fl({path:o,deletedFile:o,fileSize:BigInt(u),prevContent:p})}})}catch(e){r.error=e,r.hasError=!0}finally{Ww(r)}}}class qw{constructor(e,t){this.inner=e,this.extraTools=t}async getTools(e){return[...await this.inner.getTools(e).catch((()=>[])),...this.extraTools]}async getToolsForServers(e,t){const r=await this.inner.getToolsForServers(e,t).catch((()=>[])),n=new Set(t);return[...r,...this.extraTools.filter((e=>n.has(e.clientKey)||n.has(e.providerIdentifier)))]}async getClients(e){return this.inner.getClients(e)}async getClient(e,t){return this.inner.getClient(e,t)}async getInstructions(e){const t=await this.inner.getInstructions(e).catch((()=>[])),r=this.extraTools.filter((e=>e.providerIdentifier===zn));if(0===r.length)return t;const n=r.map((e=>{const t="string"==typeof e.description&&e.description.length>0?e.description:"(no description provided)";return`- ${e.toolName}: ${t}`})).join("\n");return[...t,new wn.I0({serverIdentifier:zn,serverName:zn,instructions:`User-defined tools for this session (server "${zn}"). Discover schemas via MCP meta-tool discovery for that server, then invoke via the MCP invocation meta-tool.\n\nAvailable tools:\n${n}`})]}async getToolSet(e){return this.inner.getToolSet(e)}}class zw extends qw{constructor(e,t){super(e,t),this.observableInner=e}onDidChange(e){return this.observableInner.onDidChange(e)}}var Gw=r("../proto/dist/generated/agent/v1/fetch_exec_pb.js"),Vw=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Kw=/;\s*charset\s*=\s*"?([^";\s]+)/i;class Jw{constructor(e){this.encodingSlices=e?.encodingSlices}async readText(e,t){if(!Ul(this.encodingSlices,e))return await t.text();const r=async function(e,t){if(void 0===e)return"unseen";try{return(0,n.isUtf8)(await e.arrayBuffer())?"utf8_valid":t?"declared_other":"utf8_invalid"}catch{return"unseen"}}(function(e){try{return e.clone()}catch{return}}(t),function(e){const t=Kw.exec(e.headers.get("content-type")??"")?.[1];return void 0!==t&&!/^utf-?8$/i.test(t)}(t)),o=await t.text();return this.recordFetched(e,o,r),o}async recordFetched(e,t,r){try{Yl(this.encodingSlices,e,{layer:"exec_web_fetch",evidence:await r},t)}catch{}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,$.VI)(e.withName("LocalFetchExecutor.execute")),!1);const n=t.url;try{const t=await fetch(n),r=await this.readText(e,t),o=t.headers.get("content-type")||"text/plain";return new Gw.uN({result:{case:"success",value:new Gw.Uk({url:n,content:r,statusCode:t.status,contentType:o})}})}catch(e){return new Gw.uN({result:{case:"error",value:new Gw.fk({url:n,error:kc(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{Vw(r)}}}const Zw=[["safe.bareRepository","explicit"]],Xw=[["core.fsmonitor","false"],["core.hooksPath",o.devNull],["core.attributesFile",o.devNull]],Qw=[["core.quotePath","false"]];function Yw(e){const t="allow-hooks"===e?Xw.filter((([e])=>"core.hooksPath"!==e)):Xw;return[...Zw,...t]}const ey=(0,zs.promisify)(ou.execFile),ty=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env","--attr-source"]),ry=new Set(["diff","show","blame","log","whatchanged"]);function ny(e){for(let t=0;t["-c",`${e}=${t}`]))}const gy=my([...Yw("block"),["submodule.recurse","false"],["fetch.recurseSubmodules","false"],["diff.submodule","short"],["status.submoduleSummary","false"],["log.showSignature","false"],["log.diffMerges","separate"],["gpg.openpgp.program",o.devNull],["gpg.x509.program",o.devNull],["gpg.ssh.program",o.devNull]]);function wy(e){const t=e?.timeout??0,r=Number.isFinite(t)&&t>0?Math.min(t,2147483647):6e4;return performance.now()+r}function yy(e,t=2147483647){return Math.max(1,Math.ceil(Math.min(t,e-performance.now())))}function vy(){const e=new Map;return{async exec(t,r,n){const o=wy(n);return ay("git",await by(e,t,r,o),{cwd:t,env:fy,windowsHide:!0,killSignal:"SIGTERM",timeout:yy(o)})},async run(t,r,n){const o=wy(n);return function(e,t,r,n){return new Promise(((o,s)=>{const i=function(e,t,r){const{env:n,...o}=r??{},s=sy(t);return(0,ou.spawn)("git",s,{...o,env:iy(s,n)})}(0,t,{cwd:e,env:fy,windowsHide:!0,stdio:[void 0===n?"ignore":"pipe","pipe","pipe"]}),a=[],c=[];let l=!1;const u=()=>{const e=!l;return l=!0,clearTimeout(d),e},d=setTimeout((()=>{u()&&(i.kill("SIGTERM"),i.stdin?.destroy(),i.stdout?.destroy(),i.stderr?.destroy(),s(Object.assign(new Error("git timed out"),{code:null,killed:!0,signal:"SIGTERM"})))}),yy(r));i.stdout?.on("data",(e=>{a.push(e)})),i.stderr?.on("data",(e=>{c.push(e)}));for(const e of[i.stdout,i.stderr])e?.on("error",(e=>{u()&&(i.kill("SIGTERM"),s(e))}));i.on("error",(e=>{u()&&s(e)})),i.on("close",((e,t)=>{u()&&(null!==e?o({exitCode:e,stdout:Buffer.concat(a).toString("utf8"),stderr:Buffer.concat(c).toString("utf8")}):s(Object.assign(new Error(`git was killed by ${String(t)}`),{code:e,killed:!1,signal:t})))})),void 0!==n&&null!==i.stdin&&(i.stdin.on("error",(()=>{})),i.stdin.end(n))}))}(t,await by(e,t,r,o),o,n?.input)}}}async function by(e,t,r,n){const{prefix:o,tail:s,readsConfig:i}=function(e){const t=sy(e),r=ny(t),n=t.findIndex(((e,t)=>t>r&&("--"===e||"--end-of-options"===e))),o=t.slice(0,-1===n?t.length:n);if(o.includes("--help")||o.includes("-h"))throw new TypeError("git help is refused: it starts the repository's man viewer");if(-1===r)return{prefix:[],tail:t,readsConfig:!1};const s=t[r],i=ly.get(s);if(void 0===i)throw new TypeError(`git ${s} is refused: the pins cover only a fixed set of verbs`);const[a,c]=i,l=o.find((e=>function(e,t,r){const n=r.startsWith("--")?r.slice(2).split("=",1)[0]:"",o=[...uy,..."status"===e?["verbose"]:[],..."worktree"===e?["checkout","no-force"]:[],...t?["ignore-submodules","no-ignore-submodules"]:[]];return""!==n&&o.some((e=>e.startsWith(n)))||"status"===e&&/^-[^-]*v/.test(r)}(s,c,e)));if(void 0!==l)throw new TypeError(`git ${s} ${l} is refused: it can start a program the pins miss`);const u=t.slice(r+1),d="worktree"===s?u.find((e=>!e.startsWith("-"))):void 0;if("remove"===d&&!o.includes("--force")&&!o.includes("-f"))throw new TypeError("git worktree remove is refused without --force");if("add"===d&&"--no-checkout"!==u[u.indexOf("add")+1])throw new TypeError("git worktree add is refused unless --no-checkout follows add");return{prefix:[...t.slice(0,r),...gy],tail:[s,...c?["--ignore-submodules=dirty"]:[],...u],readsConfig:a}}(r),a=i?await function(e,t,r,n){const o=`${t}\0${r.join("\0")}`,s=e.get(o);if(void 0!==s)return s;const i=async function(e,t,r){let n;try{n=(await ay("git",[...t,"config","--list","--show-scope","--includes","-z"],{cwd:e,env:fy,windowsHide:!0,killSignal:"SIGTERM",timeout:yy(r,1e4),maxBuffer:16777216})).stdout}catch(e){throw function(e){if(!(e instanceof Error))return new cy("read-failed");if("syscall"in e&&"string"==typeof e.syscall&&e.syscall.startsWith("spawn"))return e;if("killed"in e&&!0===e.killed)return new cy("timed-out");const t="code"in e&&"number"==typeof e.code?e.code:void 0;return new cy("read-failed",t)}(e)}if(performance.now()>=r)throw new cy("timed-out");return function(e){if(""===e)return[];const t=e.split("\0");if(""!==t.pop()||t.length%2!=0)throw new cy("read-failed");const r=new Set;for(let e=0;emy([[`filter.${e}.clean`,""],[`filter.${e}.smudge`,""],[`filter.${e}.process`,""],[`filter.${e}.required`,"false"]])))}(n)}(t,r,n);return e.set(o,i),i}(e,t,o,n):[];return[...o,...a,...s]}function Sy(e,t,r){return vy().exec(e,t,r)}var ky=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class _y{constructor(e={}){void 0!==e.guardedRootLookup&&(this.guardedRootLookup=e.guardedRootLookup)}async exec(e,t,r,n){return Cy(e,t,r,n,Sy)}forRequest(){const e=vy();return{exec:(t,r,n,o)=>Cy(t,r,n,o,((t,r,n)=>e.exec(t,r,n))),...void 0===this.guardedRootLookup?{}:{guardedRootLookup:this.guardedRootLookup}}}}async function Cy(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(s,(0,$.VI)(e.withName("LocalGitExecutor.exec"),{attributes:{"git.cwd":t,"git.args":r,"git.caller":n?.caller}}),!1);const{stdout:i,stderr:a}=await o(t,r,{timeout:n?.timeout});return{exitCode:0,stdout:i,stderr:a}}catch(e){s.error=e,s.hasError=!0}finally{ky(s)}}var Ey=r("../proto/dist/generated/agent/v1/grep_exec_pb.js");class xy{constructor(){this.lineEnd=0,this.nextStart=0}}function Py(e,t,r){const n=e.length;if(t>=n)return!1;const o=e.indexOf("\n",t);if(-1!==o){const n=o>t&&13===e.charCodeAt(o-1);return r.lineEnd=n?o-1:o,r.nextStart=o+1,!0}return r.lineEnd=n,r.nextStart=n,!0}function Ry(e,t,r,n,o,s){const i=e.indexOf("\0",t);if(-1===i||i>=r)return;let a=i+1;for(;a=48&&e.charCodeAt(a)<=57;)a++;if(a===i+1||a>=r)return;const c=e.charCodeAt(a);if(58!==c&&45!==c)return;const l=n.indexOf(0,o);if(-1===l||l>=s)return;const u=l+(a-i);return u>=s||n.toString("latin1",l+1,u+1)!==e.slice(i+1,a+1)?void 0:{file:e.slice(t,i),contentStart:a+1,contentEnd:r,contentBytesStart:u+1,contentBytesEnd:s}}const Iy=-(2**31),Ty=2**31-1;function Ay(e){return Number.isNaN(e)?0:eTy?Ty:e}function $y(e){if("number"==typeof e&&Number.isFinite(e)&&!(e<0))return Ay(Math.trunc(e))}function My(e){const t=e.replace(/\s/g,"_").replace(/[^a-zA-Z0-9_.-]/g,"").replace(/\.+/g,".");return"."===t||".."===t?t.replace(/\./g,"_"):0===t.length?"_":t}async function Dy(e,t){const r=My(t),n=(0,s.join)(e,"mcps",r,"tools");let o;try{o=await(0,Co.readdir)(n)}catch(e){if("ENOENT"===Sc(e))return{toolNames:[],toolsDirExists:!1};throw e}const i=await Promise.all(o.map((async e=>{if(e.endsWith(".json"))try{return function(e){try{const t=JSON.parse(e);return"string"==typeof t.name&&t.name.length>0?t.name:"string"==typeof t.toolName&&t.toolName.length>0?t.toolName:void 0}catch{return}}(await(0,Co.readFile)((0,s.join)(n,e),"utf8"))}catch{return}}))),a=new Set;for(const e of i)e&&a.add(e);return{toolNames:Array.from(a).sort(((e,t)=>e.localeCompare(t))),toolsDirExists:!0}}const Oy=(0,l.h)("local-exec:mcp-disk-freshness-on-access"),Fy="/mcps/",Ny=(0,u.Pu)("mcp.discovery_freshness.check",{description:"MCP discovery surface freshness comparison outcome against canonical live tools",labelNames:["surface","outcome"]}),Ly=(0,u.v5)("mcp.discovery_freshness.missing_tools",{description:"Number of tools present in canonical live state but missing from the observed discovery surface",labelNames:["surface"]}),jy=(0,u.v5)("mcp.discovery_freshness.extra_tools",{description:"Number of tools present on the observed discovery surface but absent from canonical live state",labelNames:["surface"]}),Uy=(0,u.v5)("mcp.discovery_freshness.symmetric_difference",{description:"Total symmetric difference between canonical live tools and the observed discovery surface",labelNames:["surface"]}),By=new Map;function Wy(e){const t=e.replace(/\\/g,"/");return t.endsWith("/mcps")?`${t}/`:t}async function Hy({ctx:e,mcpStateAccessor:t,projectDir:r,sanitizedServerFolder:n,readDiskCatalog:o,state:s}){let i=s;if(void 0===i)try{i=await t.getState(e)}catch(t){return void Oy.warn(e,"mcp_disk_state_read_failed",{error_type:t instanceof Error?t.name:typeof t})}const a=i.servers.find((e=>My(e.serverIdentifier)===n));if(void 0===a)return;let c;try{c=await o(r,a.serverIdentifier)}catch(t){return void Oy.warn(e,"mcp_disk_catalog_read_failed",{error_type:t instanceof Error?t.name:typeof t})}if(!c.toolsDirExists)return;const l=a.tools.map((e=>e.toolName)).filter((e=>e.length>0)).sort(((e,t)=>e.localeCompare(t)));!function({ctx:e,serverIdentifier:t,canonicalToolNames:r,observedToolNames:n}){const o=new Set(n),s=new Set(r),i=r.filter((e=>!o.has(e))),a=n.filter((e=>!s.has(e))),c=0===i.length&&0===a.length?"match":"mismatch",l={surface:"disk"};Ny.increment(e,1,{...l,outcome:c}),Ly.histogram(e,i.length,l),jy.histogram(e,a.length,l),Uy.histogram(e,i.length+a.length,l),"mismatch"===c&&Oy.warn(e,"mcp_disk_discovery_freshness_mismatch",{server_identifier:t,missing_tool_count:i.length,extra_tool_count:a.length})}({ctx:e,serverIdentifier:a.serverIdentifier,canonicalToolNames:l,observedToolNames:c.toolNames})}function qy(e,t,r,n=Dy){if(void 0===r||(void 0===(o=r)||!Wy(o).includes(Fy)))return;var o;const s=function(e){const t=Wy(e),r=t.indexOf(Fy);if(-1===r)return;const n=t.slice(0,r),o=t.slice(r+6).split("/").filter(Boolean);return 0!==n.length?0===o.length?{projectDir:n,kind:"mcps_root"}:{projectDir:n,kind:"server",sanitizedServerFolder:o[0]}:void 0}(r);if(void 0===s)return;let i,a;const c="mcps_root"===s.kind;"mcps_root"===s.kind?(i=`${s.projectDir}\0__mcps_root__`,a=void 0):(i=`${s.projectDir}\0${s.sanitizedServerFolder}`,a=s.sanitizedServerFolder);const l=By.get(i);void 0!==l&&clearTimeout(l);const u=e,d=setTimeout((()=>{By.delete(i),(async()=>{if(c){const e=await t.getState(u);for(const r of e.servers){const o=My(r.serverIdentifier);await Hy({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:o,readDiskCatalog:n,state:e})}}else void 0!==a&&await Hy({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:a,readDiskCatalog:n})})().catch((e=>{Oy.warn(u,"mcp_disk_discovery_freshness_schedule_failed",{error_type:e instanceof Error?e.name:typeof e})}))}),2e3);By.set(i,d)}async function zy(e){try{return(await(0,Co.stat)(e,{bigint:!0})).mtimeNs}catch{return}}function Gy(e,t,r){const n=e.map(((e,n)=>({file:e,mtime:t[n],segments:e.path.split(r)})));return n.sort(((e,t)=>e.mtime!==t.mtime?void 0===e.mtime?1:void 0===t.mtime||e.mtime>t.mtime?-1:1:function({left:e,right:t}){const r=Math.min(e.length,t.length);for(let n=0;ne.file))}async function Vy(e,t,r=zy){const n=e.map((e=>({item:e,path:t(e)})));let o;try{o=await(0,Or.wj)(Promise.all(n.map((({path:e})=>r(e)))),2e3,"stat timed out")}catch(t){if(t instanceof Or.MU)return{items:[...e],statTimedOut:!0};throw t}return{items:Gy(n,o,s.sep).map((({item:e})=>e)),statTimedOut:!1}}var Ky=r("../proto/dist/generated/agent/v1/read_exec_pb.js");const Jy=Buffer.from([137,80,78,71,13,10,26,10]),Zy=Buffer.from([0,0,0,0,73,69,78,68,174,66,96,130]),Xy=e=>{if(e.lengthe.subarray(e.length-Zy.length).equals(Zy)||(e=>{let t=Jy.length+25;for(;t+Zy.length<=e.length;){const r=e.readUInt32BE(t);if(r>e.length-t-Zy.length)return!1;if("IEND"===e.toString("ascii",t+4,t+8))return e.subarray(t,t+Zy.length).equals(Zy);t+=Zy.length+r}return!1})(e))(e))return;const t=e.readUInt32BE(16),r=e.readUInt32BE(20);return t<1||r<1?void 0:{width:t,height:r,colorType:e.readUInt8(25)}},Qy=e=>1===e||e>=208&&e<=216,Yy=e=>192===e||193===e||194===e,ev=e=>e>=195&&e<=207&&196!==e&&200!==e&&204!==e,tv=e=>0===e||e>=208&&e<=215,rv=(e,t)=>{let r=e.indexOf(255,t);for(;-1!==r&&r+1(e=>{const t=Xy(e);if(void 0!==t)return{mimeType:"image/png",width:t.width,height:t.height}})(e)??(e=>{if(e.length<4||255!==e[0]||216!==e[1]||!(e=>255===e[e.length-2]&&217===e[e.length-1]||(e=>{let t=2;for(;t+2<=e.length;){if(255!==e[t])return!1;const r=e[t+1];if(255===r){t+=1;continue}if(217===r)return!0;if(Qy(r)){t+=2;continue}if(t+4>e.length)return!1;const n=e.readUInt16BE(t+2);if(n<2)return!1;const o=t+2+n;if(218!==r){t=o;continue}const s=rv(e,o);if(void 0===s)return!1;t=s}return!1})(e))(e))return;let t=2;for(;t+4<=e.length;){if(255!==e[t])return;const r=e[t+1];if(255===r){t+=1;continue}if(Qy(r)){t+=2;continue}if(218===r||217===r||ev(r))return;const n=e.readUInt16BE(t+2);if(n<2)return;if(Yy(r)){if(n<8||t+9>e.length)return;const r=e.readUInt16BE(t+5),o=e.readUInt16BE(t+7);if(o<1||r<1)return;return{mimeType:"image/jpeg",width:o,height:r}}t+=2+n}})(e),ov=(e,t)=>({width:Math.max(e?.width??0,t.width),height:Math.max(e?.height??0,t.height)}),sv=(e,t)=>{for(;t{const t=e.toString("latin1",0,6);return e.subarray(0,Jy.length).equals(Jy)?"png":t.startsWith("ÿØÿ")?"jpeg":"GIF87a"===t||"GIF89a"===t?"gif":t.startsWith("BM")?"bmp":t.startsWith("II*\0")||t.startsWith("MM\0*")?"tiff":t.startsWith("ID3")?"id3":void 0},av={0:1,2:3,4:2,6:4},cv=async({data:e,width:t,height:r})=>{const n=lv(e);if(void 0===n||t>n.width||r>n.height)return;const o=n.width*n.channels,s=new Uint32Array(n.width);for(let e=0;e{let t;const r=[];let n=8;for(;n+12<=e.length;){const o=e.readUInt32BE(n),s=e.toString("ascii",n+4,n+8),i=e.subarray(n+8,n+8+o);if(i.length!==o)return;if("IHDR"===s){const e=av[i[9]];if(void 0!==t||13!==o||8!==i[8]||0!==i[12]||void 0===e)return;t={width:i.readUInt32BE(0),height:i.readUInt32BE(4),channels:e}}else if("IDAT"===s)r.push(i);else{if("tRNS"===s)return;if("IEND"===s)break}n+=o+12}return void 0===t||0===r.length?void 0:{...t,idat:r}},uv=({filter:e,row:t,previous:r,bytesPerPixel:n})=>{if(0!==e)for(let o=0;o=n?t[o-n]:0,i=r[o];switch(e){case 1:t[o]+=s;break;case 2:t[o]+=i;break;case 3:t[o]+=s+i>>1;break;case 4:{const e=o>=n?r[o-n]:0,a=s+i-e,c=Math.abs(a-s),l=Math.abs(a-i),u=Math.abs(a-e);t[o]+=c<=l&&c<=u?s:l<=u?i:e;break}default:throw new Error(`unknown PNG filter type ${e}`)}}},dv=({row:e,channels:t,columnOf:r,sums:n,counts:o})=>{const s=t<3;for(let i=0,a=0;i{for(let s=0;s0&&(e[c]=Math.round(n[i]/a),e[c+1]=Math.round(n[i+1]/a),e[c+2]=Math.round(n[i+2]/a),e[c+3]=Math.round(a/o[s]))}n.fill(0),o.fill(0)},pv={0:1,2:3,3:1,4:2,6:4},fv=[1,2,4,8,16],mv=[[0,0,8,8],[4,0,8,8],[0,4,4,8],[2,0,4,4],[0,2,2,4],[1,0,2,2],[0,1,1,2]],gv=async e=>{const t=wv(e);if(void 0===t)return;const r=yv(t);let n=0;const o=ih.Readable.from(t.idat).pipe((0,rh.createInflate)());for await(const e of o)if(n+=e.length,n>=r)return void o.destroy();throw new Error(`PNG pixel data ends after ${n} of ${r} bytes`)},wv=e=>{let t;const r=[];let n=8;for(;n+12<=e.length;){const o=e.readUInt32BE(n),s=e.toString("ascii",n+4,n+8),i=e.subarray(n+8,n+8+o);if("IHDR"===s&&void 0===t&&13===i.length){const e=pv[i[9]];if(void 0===e||!fv.includes(i[8])||i[12]>1)return;t={width:i.readUInt32BE(0),height:i.readUInt32BE(4),bitsPerPixel:e*i[8],interlaced:1===i[12]}}else if("IDAT"===s)r.push(i);else if("IEND"===s)break;n+=o+12}return void 0===t||0===r.length?void 0:{...t,idat:r}},yv=({width:e,height:t,bitsPerPixel:r,interlaced:n})=>{const o=(e,t)=>e<=0||t<=0?0:t*(1+Math.ceil(e*r/8));return n?mv.reduce(((r,[n,s,i,a])=>r+o(Math.ceil((e-n)/i),Math.ceil((t-s)/a))),0):o(e,t)};const vv=()=>{throw new Error("webp codec not registered: registerWebpCodec() must be called by a Node server before decoding/encoding webp")},bv=e=>e.length>=12&&"RIFF"===e.toString("ascii",0,4)&&"WEBP"===e.toString("ascii",8,12),Sv=e=>{if(!bv(e)||e.length<16)return;const t=e.toString("ascii",12,16);if("VP8 "===t){if(e.length<30||157!==e[23]||1!==e[24]||42!==e[25])return;return{width:16383&(e[26]|e[27]<<8),height:16383&(e[28]|e[29]<<8)}}if("VP8L"===t){if(e.length<25||47!==e[20])return;const t=(e[21]|e[22]<<8|e[23]<<16|e[24]<<24)>>>0;return{width:1+(16383&t),height:1+(t>>14&16383)}}if("VP8X"===t){if(e.length<30)return;return{width:1+(e[24]|e[25]<<8|e[26]<<16),height:1+(e[27]|e[28]<<8|e[29]<<16)}}},kv=e=>vv().decode(e);async function _v(e){((e,t)=>{if(!Number.isSafeInteger(e)||e<1||e>t)throw new Error("pngByteBudgetBytes must be a positive integer at most MAX_IMAGE_SIZE_BYTES")})(e.budgetBytes,e.maxImageBytes);nv(e.data);return e.resizeWithoutBudget(e.data)}const Cv=[{width:1280,height:800},{width:1456,height:840}],Ev=e=>void 0!==e&&Cv.some((t=>t.width===e.width&&t.height===e.height)),xv=1048576,Pv=e=>{const t=e.buffer;return t instanceof ArrayBuffer?new Uint8Array(t,e.byteOffset,e.byteLength):Uint8Array.from(e)};function Rv(e,t,r=1024){if(e<1||t<1)return{width:e,height:t,needsResize:!1};const n=Math.max(e,t);if(n<=r)return{width:e,height:t,needsResize:!1};const o=Math.min(e,t);if(o<8)return{width:e,height:t,needsResize:!1};let s=r/n,i=Math.max(1,Math.round(e*s)),a=Math.max(1,Math.round(t*s));return(i<8||a<8)&&(s=8/o,i=Math.max(8,Math.round(e*s)),a=Math.max(8,Math.round(t*s))),{width:i,height:a,needsResize:i!==e||a!==t}}const Iv=(e,t,r=1024)=>Rv(e,t,r),Tv=(e,t)=>Ev({width:e,height:t})?{width:e,height:t,needsResize:!1}:Rv(e,t),Av=(e,t,r)=>{e.resize({w:t,h:r})};function $v(e){if(void 0===e)throw new Error("image dimensions could not be read before decoding");const{width:t,height:r}=e;if(!(t*r<=178956970))throw new Error(`image dimensions ${t}x${r} exceed the 178956970 pixel decode limit`);if(!(Math.max(t,r)<=1e6))throw new Error(`image dimensions ${t}x${r} exceed the 1000000 pixel side limit`)}const Mv=(e,t)=>{switch(t){case"tiff":throw new Error("TIFF images are not supported; convert the image to PNG or JPEG");case"id3":throw new Error("images that start with an ID3 tag are not supported");case"jpeg":return;default:$v(((e,t)=>{switch(t){case"png":return(e=>{let t,r=Jy.length;for(;r+16<=e.length;)"IHDR"===e.toString("ascii",r+4,r+8)&&(t=ov(t,{width:e.readUInt32BE(r+8),height:e.readUInt32BE(r+12)})),r+=12+e.readUInt32BE(r);return t})(e);case"gif":return(e=>{if(e.length<13)return;const t={width:e.readUInt16LE(6),height:e.readUInt16LE(8)};let r=13+(128&(n=e[10])?3<<1+(7&n):0);for(var n;re.length<26?void 0:{width:e.readUInt32LE(18),height:Math.abs(e.readInt32LE(22))})(e)}})(e,t))}},Dv=e=>{const{width:t,height:r}=Iv(e.width,e.height,1280);return{width:t,height:r}},Ov=async(e,t)=>{let{width:r,height:n}=e,o=await t({width:r,height:n});for(;o.length>xv&&r>8&&n>8;)r=Math.max(8,Math.round(.8*r)),n=Math.max(8,Math.round(.8*n)),o=await t({width:r,height:n});return{data:Pv(o),mimeType:"image/webp",reencoded:!0}},Fv=async(e,t)=>{const r=(await fw()).fromBitmap({data:Buffer.from(e.data),width:e.width,height:e.height});return Ov(t,(async e=>(r.bitmap.width===e.width&&r.bitmap.height===e.height||Av(r,e.width,e.height),(e=>vv().encode(e))({data:r.bitmap.data,width:r.bitmap.width,height:r.bitmap.height}))))};let Nv;const Lv=async(e,t)=>{if(void 0!==t?.pngByteBudgetBytes){const{pngByteBudgetBytes:r,...n}=t,o=nv(e);return"image/png"===o?.mimeType&&Ev(o)&&await gv(e),_v({data:e,budgetBytes:r,maxImageBytes:xv,fitImage:Tv,resizeWithoutBudget:e=>Lv(e,n)})}const r=await(async(e,t)=>{const r=bv(e);if(r&&!0===t?.preserveWebpDimensions)return;const n=r?void 0:nv(e),o=r?Sv(e):n;if(void 0===o||!Ev(o))return;const s=Nv;if(void 0!==n&&void 0!==s&&!Ev(await s.readOrientedDimensions(e)))return;const i="image/png"===n?.mimeType;if(i&&await gv(e),e.length<=xv)return{data:Pv(e),mimeType:n?.mimeType??"image/webp"};const a=s?.resizeWebp;if(void 0!==a)return Ov(o,(t=>a({data:e,...t})))})(e,t);if(void 0!==r)return r;if(bv(e))return(async(e,t)=>{const r=Sv(e);if(!0===t?.preserveWebpDimensions&&void 0!==r)return{data:Pv(e),mimeType:"image/webp"};if(void 0!==r&&!Iv(r.width,r.height,1280).needsResize&&e.length<=xv)return{data:Pv(e),mimeType:"image/webp"};if("passthrough"===t?.webpWithoutCodec)return{data:Pv(e),mimeType:"image/webp"};$v(r);const n=undefined;if(void 0!==n)return Ov(Dv(r),(t=>n({data:e,...t})));const o=await kv(e);return Fv(o,Dv(o))})(e,t);const n=nv(e);if(void 0!==n&&e.length<=xv&&!Iv(n.width,n.height).needsResize)return{data:Pv(e),mimeType:n.mimeType};const o=iv(e);void 0!==o&&Mv(e,o);const s=void 0===n?void 0:Iv(n.width,n.height),i="image/png"===n?.mimeType&&!0===s?.needsResize?await cv({data:e,width:s.width,height:s.height}).catch((()=>{})):void 0;void 0===i&&"png"===o&&await gv(e);const a=await fw(),c=void 0===i?await a.read(e):a.fromBitmap(i),l=(e=>{switch(e.mime){case"image/png":default:return"image/png";case"image/bmp":return"image/bmp";case"image/tiff":return"image/tiff";case"image/x-ms-bmp":return"image/x-ms-bmp";case"image/gif":return"image/gif";case"image/jpeg":return"image/jpeg"}})(c),u=!0===t?.convertUnsupportedModelFormatsToPng&&"image/png"!==l&&"image/jpeg"!==l?"image/png":l,{width:d,height:h,needsResize:p}=Iv(c.width,c.height);if(void 0===i&&!p&&e.length<=xv&&u===l)return{data:Pv(e),mimeType:l};let f=d,m=h;p&&Av(c,f,m);let g=await c.getBuffer(u);for(;g.length>xv&&f>8&&m>8;)f=Math.max(8,Math.round(.8*f)),m=Math.max(8,Math.round(.8*m)),Av(c,f,m),g=await c.getBuffer(u);return{data:Pv(g),mimeType:u,reencoded:!0}},jv=async e=>{const t=Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=iv(t);let n;if(bv(t))return{kind:"unchecked"};if(void 0===r)return{kind:"unchecked"};{Mv(t,r);const e=await fw();n=async()=>("png"===r&&await gv(t),e.read(t))}try{return await n(),{kind:"decodes"}}catch(e){return{kind:"undecodable",reason:e instanceof Error?e.message:String(e)}}},Uv=BigInt(0),Bv=BigInt(8),Wv=BigInt(16),Hv=BigInt(65535);function qv(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function zv(e){const t=e.split(".");if(4!==t.length)return;let r=Uv;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<>Wv&Hv)),t.push(Number(o.value&Hv))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function Vv(e){return zv(e)??function(e){const t=qv(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=Gv(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<7?void 0:{version:6,value:[...s,...new Array(8-a).fill(0),...i].reduce(((e,t)=>e<i)return!1;const a=BigInt(i-s);return o.value>>a==n.value>>a}(r,n);if(n.startsWith("*.")){const e=n.slice(2);return r===e||r.endsWith(`.${e}`)}return r===n}function Jv(e,t){const r=function(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch{return}}(e);return!!r&&function(e,t){return t.some((t=>Kv(e,t)))}(r.hostname,t)}var Zv=r("../constants/dist/commercial-cursor-hosts.js");new Set([1,2]);const Xv="cursor/requiresConfirmation",Qv="https://grok.com/connectors-oauth-exchange-code/",Yv="https://x.com/i/connectors/oauth_callback",eb="https://chat.x.com/connectors/oauth_callback",tb="https://lite.x.com/i/connectors/oauth_callback",rb={provider:"google-workspace",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0,authorizationParams:{access_type:"offline",prompt:"select_account consent"}},nb={provider:"x-money",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,registeredAppRedirectUris:[Qv,Yv]},ob="x-cursor-auth";function sb(e,t){return function({serverUrl:e,restMcpHost:t}){if(void 0===e)return;let r;try{r=new URL(e)}catch{return}return"https:"===r.protocol&&r.hostname.toLowerCase()===t.toLowerCase()&&""===r.port?ib(e):void 0}({serverUrl:e,restMcpHost:t})}function ib(e){if(void 0===e)return;let t;try{t=new URL(e)}catch{return}const r=/^\/rest-mcp\/([^/]+)\/mcp\/?$/.exec(t.pathname);return r?.[1]}new Set(Object.values({notConnected:"scm_not_connected",tokenUnavailable:"scm_token_unavailable",tokenRejected:"scm_token_rejected",repoNotAccessible:"scm_repo_not_accessible",orgBlocked:"scm_org_blocked"})),new Set(Object.values({originNotEnabled:"origin_not_enabled",teamDisabled:"team_disabled",admissionRejected:"admission_rejected"}));const ab="https://mcp.shop.com",cb={provider:"grok-connectors",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,scopes:["grok-plugins:access","offline_access"]},lb=new Map([["mcp.slack.com",{displayName:"Slack",baseScopes:["canvases:read","canvases:write","channels:history","channels:read","channels:write","chat:write","emoji:read","files:read","files:write","groups:history","groups:read","im:history","im:read","im:write","lists:read","lists:write","mpim:history","mpim:read","mpim:write","reactions:read","reactions:write","search:read.files","search:read.im","search:read.mpim","search:read.private","search:read.public","search:read.users","users:read","users:read.email"],stepUpScopes:{"groups:write":{action:"create private channels",tools:[{name:"slack_create_conversation",args:{is_private:!0}}]}},missingScopeAnswer:/\bmissing_scope\b/}]]),ub=new Map([["gmailmcp.googleapis.com",{...rb,scopes:["https://www.googleapis.com/auth/gmail.readonly","https://www.googleapis.com/auth/gmail.compose","https://www.googleapis.com/auth/gmail.modify"]}],["drivemcp.googleapis.com",{...rb,scopes:["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/drive.file"]}],["calendarmcp.googleapis.com",{...rb,scopes:["https://www.googleapis.com/auth/calendar.events","https://www.googleapis.com/auth/calendar.calendarlist.readonly","https://www.googleapis.com/auth/calendar.events.readonly","https://www.googleapis.com/auth/calendar.events.freebusy"]}],["docsmcp.googleapis.com",{...rb,scopes:["https://www.googleapis.com/auth/documents"]}],["sheetsmcp.googleapis.com",{...rb,scopes:["https://www.googleapis.com/auth/spreadsheets"]}],["slidesmcp.googleapis.com",{...rb,scopes:["https://www.googleapis.com/auth/presentations"]}],["bigquery.googleapis.com",{...rb,scopes:["https://www.googleapis.com/auth/bigquery"]}],["api.x.com",{provider:"x",clientRegistration:"static",unauthenticatedConnect:!1,rejectsCustomSchemeRedirects:!1,pinsScopesOverConfiguredScopes:!0}],["mcp.money-dev.x.com",nb],["mcp.money-staging.x.com",nb],["mcp.money.x.com",nb],["connectors-gateway.grok.gcp.mouseion.dev",cb],["connectors-gateway.grok.com",cb],["mcp.hubspot.com",{provider:"hubspot",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0}],["mcp.box.com",{provider:"box",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0}],["mcp.asana.com",{provider:"asana",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,configuredSecretStaysOnBackend:!0}],["mcp.strava.com",{provider:"strava",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,scopes:["read","activity:read_all","profile:read_all"]}],["mcp.quickbooks.intuit.com",{provider:"quickbooks-online",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,unauthenticatedEndpointBlocked:!0,backendOnlyTokenExchange:!0,scopes:["com.intuit.quickbooks.accounting","foundations.tools.businessreports.read","foundations.tools.bi-dashboard","foundations.tools.transactions.write","foundations.tools.companyprofile.read","foundations.tools.companyprofile.write","payroll.tools.tax.read","payroll.tools.employer.read","payroll.tools.employer.manage","payroll.tools.run.read","payroll.tools.run.manage","payroll.tools.employee.read","payroll.tools.employee.manage","worker-mgmt.tools.employee.read","worker-mgmt.tools.employee.manage","time-tracking.tools.timeentry.read","sales.tools.invoice.read","sales.tools.invoice","sales.tools.estimate.read","sales.tools.estimate","sales.tools.payment-link.read","sales.tools.payment-link","sales.tools.settings.read","sales.tools.settings","sales.tools.salesorder.read","sales.tools.salesorder","contact.tools.customer.read","contact.tools.customer","catalog.tools.item.read","catalog.tools.item","lending.tools.servicing.read","money-onboarding.tools.application"]}],["setup.shopify.com",{provider:"shopify",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!1}],["mcp.cloudflare.com",{provider:"cloudflare",clientRegistration:"dynamic",unauthenticatedConnect:!1,rejectsCustomSchemeRedirects:!1,scopes:["user:read","account:read","offline_access","d1.metadata_read","d1.read","d1.write","workers-scripts.read","workers-scripts.write","workers-routes.read","workers-routes.write","workers-tail.read","workers-kv-storage.metadata_read","workers-kv-storage.read","workers-kv-storage.write","workers-r2.metadata_read","workers-r2.read","workers-r2.write","workers-r2-bucket-item.read","workers-r2-bucket-item.write","workers-observability.read","workers-observability.write","dns.read","dns.write","zone.read","zone.write"],pinsScopesOverConfiguredScopes:!0,scopesPinGate:"mcp_cloudflare_api_oauth_scopes"}],["mcp.shop.com",{provider:"shop",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,backendOnlyTokenExchange:!0,scopes:["openid","personal_agent"],pinsScopesOverConfiguredScopes:!0,authorizationParams:{resource:ab}}],["api.elections.kalshi.com",{provider:"kalshi",clientRegistration:"dynamic",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0}],["mcp.squarespace.com",{provider:"squarespace",clientRegistration:"dynamic",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0}]]),db=[".databricks.com",".azuredatabricks.net"];const hb=/^\/sncapps\/mcp-server\/mcp\/[^/]+$/,pb={provider:"databricks",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,scopes:["ai-gateway","offline_access"],pinsScopesOverConfiguredScopes:!0},fb={provider:"servicenow",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,unauthenticatedEndpointBlocked:!0,backendOnlyTokenExchange:!0,ownMcpJsonClientMayExchange:!0};function mb(e){if(void 0===e)return;let t;try{t=new URL(e)}catch{return}return function(e){return"https:"===e.protocol&&""===e.port&&""===e.username&&""===e.password&&function(e){const t=e.toLowerCase();return!(!/^[a-z0-9.-]+$/.test(t)||t.includes("..")||t.startsWith("."))&&db.some((e=>t.endsWith(e)&&t.length>e.length))}(e.hostname)&&"/ai-gateway/mcp-services/system.ai.genie_one_mcp"===e.pathname.replace(/\/+$/,"")}(t)?pb:function(e){return"https:"===e.protocol&&""===e.port&&""===e.username&&""===e.password&&hb.test(e.pathname.replace(/\/+$/,""))}(t)?fb:(r=t.hostname,ub.get(r.toLowerCase()));var r}function gb(e){return e.endsWith("/")?e:`${e}/`}async function wb(e,t){if(void 0===t)return;const r=new URL(e),n=new URL(t);if(r.origin!==n.origin||!gb(r.pathname).startsWith(gb(n.pathname)))throw new Error(`Protected resource ${t} does not match expected ${r.href} (or origin)`);return n}const yb=/^\/shops\/[A-Za-z0-9-]+\/mcp$/;function vb(e){if(void 0!==e)try{return new URL(e)}catch{return}}async function bb(e,t){if(void 0===t)return;const r=new URL(e),n=vb(t);if(void 0===n||n.origin!==r.origin||n.pathname!==r.pathname&&!yb.test(n.pathname))throw new Error(`Protected resource ${t} does not match expected ${r.href} (or origin)`);return n}function Sb(e){const t=vb(e);return void 0===t?void 0:lb.get(t.hostname.toLowerCase())}const kb=new Set([...ub].filter((([,e])=>"google-workspace"===e.provider)).map((([e])=>e))),_b="https://www.cursor.com/bot/mcp/oauth/callback",Cb={portal:"https://www.cursor.com/agents/mcp/oauth/callback",grokBotBounce:_b},Eb="tailnet_";new Set([`${Eb}waiting_for_approval`,`${Eb}tailnet_locked`,`${Eb}joining`]);const xb="grokbot://mcp/oauth/callback",Pb="http://localhost:8787/callback",Rb="gb";function Ib(e){const t=new URL(Pb);return t.port=String(e),t.toString()}function Tb(e){try{const t=new URL(e);if("http:"!==t.protocol)return!1;const r=t.hostname;return"localhost"===r||"127.0.0.1"===r||"[::1]"===r}catch{return!1}}function Ab(e){const t=e.redirectUrl??Pb;if(!0!==e.loopbackIpv4||!Tb(t))return t;const r=new URL(t);return r.hostname="127.0.0.1",r.toString()}function $b(e,t=Cb){const r=new Set,n=void 0!==e&&Tb(e);return e&&!n&&r.add(e),r.add(t.portal),e===xb&&r.add(t.grokBotBounce),r.add(Pb),e&&n&&r.add(e),Array.from(r)}function Mb(e){var t;if(void 0!==e&&0!==e.length)try{const r=JSON.parse(e);if("object"==typeof(t=r)&&null!==t&&!Array.isArray(t))return r}catch{}}function Db(e){if(void 0===e)return{};const t={};"string"==typeof e.title&&e.title.length>0&&(t.title=Vo(e.title,256));for(const r of["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"])"boolean"==typeof e[r]&&(t[r]=e[r]);return function(e){return!0===e?.[Xv]}(e)&&(t[Xv]=!0),0===Object.keys(t).length?{}:{annotationsJson:JSON.stringify(t)}}new Map([[Rb,xb],["gw",Qv],["gd",Pb],["xa",Yv],["xc",eb],["xl",tb],...[18787,28787,31787].map((e=>[`gd${e}`,Ib(e)]))]),new Map([[xb,Rb],[_b,Rb],[Qv,"gw"],[Yv,"xa"],[eb,"xc"],[tb,"xl"]]),Ab({loopbackIpv4:!0});var Ob=r("../mcp-core/dist/transport/mcp-url-utils.js");function Fb(e){return e.trim().toLowerCase()}const Nb="";function Lb({mode:e,tools:t}){const r=(t??[]).map(Fb).filter((e=>e.length>0)),n=void 0===e?void 0:Fb(e);return"all"===n?{mode:"all"}:"reads"===n?{mode:"reads"}:r.length>0?{mode:"custom",tools:r}:{mode:"all"}}function jb(e,t){switch(e.mode){case"all":return!0;case"custom":return function(e,t){const r=Fb(e);return 0!==r.length&&r!==Nb&&t.some((e=>Fb(e)===r))}(t.name,e.tools);case"reads":return void 0!==(r=t.annotations)&&!0!==r.destructiveHint&&!0===r.readOnlyHint;default:return e}var r}function Ub(e,t){switch(t.mode){case"all":return[`${e}:*`];case"custom":return t.tools.filter((e=>Fb(e)!==Nb)).map((t=>`${e}:${t}`));case"reads":return[];default:return t}}const Bb=new Set(["ash","bash","csh","dash","fish","ksh","powershell","pwsh","sh","tcsh","zsh","cmd"]);function Wb(e){return e.trim().split(/\s+/).filter(Boolean)}function Hb(e){const t=function(e){const t=e.trim(),r=t[0];if('"'===r||"'"===r){const e=t.indexOf(r,1);if(-1!==e)return t.slice(0,e+1)}return Wb(t)[0]}(e);if(!t)return!1;const r=t.replace(/^["']|["']$/g,"").replaceAll("\\","/").split("/"),n=(r[r.length-1]??"").replace(/\.exe$/i,"").toLowerCase();return Bb.has(n)}function qb(e,t){if(e.length>t.length)return!1;for(let r=0;r=t.tokenCount)continue;let a=!0;for(const t of e.tokens)if(!n.has(t)){a=!1;break}if(!a)continue;const c=qb(e.tokens,t.tokens);void 0!==o?e.tokenCount>o.tokenCount?(o=e,s=c):e.tokenCount===o.tokenCount&&c&&!s&&(o=e,s=!0):(o=e,s=c)}void 0!==o&&(t.indentLevel=o.indentLevel+1,t.ancestorIds=[...o.ancestorIds,t.id])}const n=r.filter((e=>!r.some((t=>t.id!==e.id&&t.tokenCounte.id));return{options:r,defaultSelectedOptionIds:n}}(e),n=[...r.defaultSelectedOptionIds];if(!t||0===t.length)return{defaultSelectedOptionIds:n,hasClassifierSuggestions:!1};const o=[],s=new Set;for(const e of t){const t=r.options.find((t=>t.id===e));if(t){o.push(t.id),s.add(Gb(t.id));continue}const n=r.options.filter((t=>t.id.startsWith(`${e} `)||t.id===e)),i=r.options.filter((t=>e.startsWith(`${t.id} `)||e===t.id));if(i.length>0){const e=i.reduce(((e,t)=>e.id.length>t.id.length?e:t));o.push(e.id),s.add(Gb(e.id))}else if(n.length>0){const e=n.reduce(((e,t)=>e.id.length!s.has(Gb(e))));return{defaultSelectedOptionIds:[...new Set([...i,...o])],hasClassifierSuggestions:!0}}(e,t).defaultSelectedOptionIds}const Kb=["com.todesktop.230313mzl4w4u92","co.anysphere.cursor","com.anysphere.molten-glass"],Jb=["cursor","molten glass"];function Zb(e){return Kb.some((t=>e===t||e.startsWith(`${t}.`)))}const Xb=[{bundleId:"com.apple.scripteditor2",name:"Script Editor"},{bundleId:"com.apple.automator",name:"Automator"},{bundleId:"com.apple.shortcuts",name:"Shortcuts"}],Qb=[{bundleId:"com.apple.terminal",name:"Terminal"},{bundleId:"com.googlecode.iterm2",name:"iTerm",aliases:["iTerm2"]},{bundleId:"dev.warp.warp-stable",name:"Warp"},{bundleId:"dev.warp.warp-preview",name:"WarpPreview",aliases:["Warp Preview"]},{bundleId:"com.mitchellh.ghostty",name:"Ghostty"},{bundleId:"org.alacritty",name:"Alacritty"},{bundleId:"net.kovidgoyal.kitty",name:"kitty"},{bundleId:"com.github.wez.wezterm",name:"WezTerm"},{bundleId:"co.zeit.hyper",name:"Hyper"},{bundleId:"org.tabby",name:"Tabby"},...Xb,{bundleId:Kb[0],name:"Cursor"}];function Yb(e){const t=e.toLowerCase(),r=(0,s.basename)(e,".app").toLowerCase(),n=Qb.find((({bundleId:e,name:n,aliases:o=[]})=>e===t||[n,...o].some((e=>{const n=e.toLowerCase();return n===t||n===r}))));return void 0!==n?{bundleId:n.bundleId,name:n.name}:Zb(t)?{bundleId:t,name:"Cursor"}:[t,r].some((e=>Jb.some((t=>e===t||e.startsWith(`${t} `)))))?{bundleId:Kb[0],name:"Cursor"}:void 0}const eS=new Set(["com.apple.systempreferences","com.apple.keychainaccess","com.apple.passwords","com.1password.1password","com.agilebits.onepassword7","com.bitwarden.desktop","com.lastpass.lastpass","org.keepassxc.keepassxc"]);function tS(e){return eS.has(e.toLowerCase())}function rS(e){return`app/${e}`}function nS(e){return"object"==typeof e&&null!==e}function oS(e){return iS.includes(e)}function sS(e){if(!nS(e))return;const{appArg:t,appSelectorArgs:r,capturesScreen:n}=e;if("boolean"==typeof n){if(void 0!==r){if(void 0!==t||!nS(r))return;const e={};for(const[t,n]of Object.entries(r)){if(!oS(t)||"string"!=typeof n||0===n.length)return;e[t]=n}if(0===Object.keys(e).length)return;return{appSelectorArgs:e,capturesScreen:n}}return void 0===t?{capturesScreen:n}:"string"==typeof t&&t.length>0?{appArg:t,capturesScreen:n}:void 0}}const iS=["pid","bundleId","path","appName"],aS=/^[+-]?\d+$/;var cS=r("../../node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/create.js");const lS=".cursor/worktrees",uS=".grok/build-desktop/worktrees",dS="win32"===process.platform||"darwin"===process.platform,hS=new Map;function pS(e,t){if(!(0,Yo.BJ)(t,e))return;const r=(dS?(0,s.relative)(e.toLowerCase(),t.toLowerCase()):(0,s.relative)(e,t)).split(s.sep).filter(Boolean);return r.length>0?r:void 0}function fS(e,t){const r=pS(e,t);if(void 0!==r)return r;const n=function(e){if(hS.has(e))return hS.get(e);const t=[];let r,n=e;for(;;)try{const e=xo.realpathSync.native(n);r=0===t.length?e:(0,s.join)(e,...t);break}catch(e){const r=Sc(e);if("ENOENT"!==r&&"ENOTDIR"!==r)break;const o=(0,s.dirname)(n);if(o===n)break;t.unshift((0,s.basename)(n)),n=o}return hS.size>=64&&hS.clear(),hS.set(e,r),r}(e);var o,i;return void 0!==n&&(o=n,i=e,dS?o.toLowerCase()!==i.toLowerCase():o!==i)?pS(n,t):void 0}function mS(e){const t=e?.trim();return t&&".cursor"!==t?[".cursor",t]:[".cursor"]}function gS(e,t){const r=(0,o.homedir)();return mS(t?.dataFolderName).some((t=>void 0!==fS((0,s.join)(r,t,"projects"),e)))}function wS(e){const t=(0,o.homedir)();return[lS,uS].some((r=>void 0!==fS((0,s.join)(t,...r.split("/")),e)))}function yS(e,t,r){const n=function(e,t){const r=(0,o.homedir)();for(const n of mS(t?.dataFolderName)){const t=fS((0,s.join)(r,n,"projects"),e);if(void 0!==t&&t.length>=2)return t[1]}}(e,r);return void 0!==n&&(dS?t.some((e=>e.toLowerCase()===n.toLowerCase())):t.includes(n))}function vS(e,t,r){const n=fS(e,t);if(void 0===n)return!1;const o=n[0];return dS?r.some((e=>e.toLowerCase()===o.toLowerCase())):r.includes(o)}const bS=/[\s"'`=/\\:;()[\]{},&|<>]/,SS="win32"===process.platform||"darwin"===process.platform;async function kS(e,t,r,n){const o=RS(await PS((0,s.join)(e,"gitdir")),"");if(void 0===o)return;const i=(0,s.resolve)(e,o);if(".git"!==(0,s.basename)(i)||(0,qs.$f)(i))return;const a=(0,s.dirname)(i);if(r&&wS(a))return;const c=await IS(i);if(void 0===c)return;const l=(0,s.dirname)(c);if(r&&wS(l))return;if(void 0!==n&&(u=AS(a,l)?[l]:[a,l],d=n.command,!(void 0!==(h=n.realWorkingDirectory)&&u.some((e=>(0,Yo.BJ)(h,e)))||void 0!==d&&u.some((e=>{const t=(0,s.basename)(e);return t.length>0&&function(e,t){const r=SS?e.toLowerCase():e,n=SS?t.toLowerCase():t;let o=0;for(;;){const e=r.indexOf(n,o);if(-1===e)return!1;const t=0===e||bS.test(r[e-1]),s=e+n.length,i=s===r.length||bS.test(r[s]);if(t&&i)return!0;o=e+1}}(d,t)})))))return;var u,d,h;const p=await xS(i,c);return void 0!==p&&AS(p.commonDir,t)?l:void 0}async function _S(e,t){const r=await(0,Co.readdir)(e).catch(TS);return void 0===r?[]:r.sort().slice(0,t)}function CS(e,t){return t.some((t=>(0,Yo.BJ)(t,e)))}async function ES(e){for(let t=e;;t=(0,s.dirname)(t)){if((0,qs.$f)(t))return;const e=(0,s.join)(t,".git"),r=await(0,Co.lstat)(e).catch(TS);if(r?.isFile())return(await xS(e))?.commonDir;if(r?.isDirectory())return e;if(void 0!==r||(0,s.dirname)(t)===t)return}}async function xS(e,t){const r=RS(await PS(e),"gitdir: ");if(void 0===r)return;const n=await IS((0,s.resolve)((0,s.dirname)(e),r));if(void 0===n||"worktrees"!==(0,s.basename)((0,s.dirname)(n)))return;const o=(0,s.dirname)((0,s.dirname)(n));if(".git"!==(0,s.basename)(o))return;const i=RS(await PS((0,s.join)(n,"commondir")),"");if(void 0===i)return;const a=await IS((0,s.resolve)(n,i));if(void 0===a||!AS(a,o))return;const c=RS(await PS((0,s.join)(n,"gitdir")),"");if(void 0===c)return;const[l,u]=await Promise.all([IS((0,s.resolve)(n,c)),t??IS(e)]);return void 0!==l&&void 0!==u&&AS(l,u)?{commonDir:o,realDotGit:u}:void 0}async function PS(e){const t=await(0,Co.lstat)(e).catch(TS);if(void 0!==t&&t.isFile()&&!(t.size>4096))return(0,Co.readFile)(e,"utf8").catch(TS)}function RS(e,t){const r=e?.split("\n",1)[0]?.replace(/\r$/,"");if(void 0===r||!r.startsWith(t))return;const n=r.slice(t.length);return n.length>0&&!n.includes("\0")?n:void 0}async function IS(e){if(!(0,qs.$f)(e))return(0,Co.realpath)(e).catch(TS)}function TS(e){const t=Sc(e);if(void 0===t||t.startsWith("ERR_"))throw e}function AS(e,t){return SS?e.toLowerCase()===t.toLowerCase():e===t}function $S(e,t,r){return{resolvedPath:e,originalPath:t,resolution:r}}function MS(e){const t=Sc(e);switch(t){case"ENOENT":return{status:"newFile"};case"EACCES":case"EPERM":return{status:"permissionDenied",errno:t};case"ELOOP":return{status:"symlinkLoop",errno:t};default:return{status:"unknownError",errno:t??"UNKNOWN",message:kc(e)}}}async function DS(e,t){const r=(0,Yo.o1)(e,t);try{return $S(await(0,Co.realpath)(r),r,{status:"resolved"})}catch(e){if("ENOENT"!==Sc(e))return $S(r,r,MS(e));try{if((await(0,Co.lstat)(r)).isSymbolicLink()){let e=null;try{e=await(0,Co.readlink)(r)}catch{}return $S(r,r,{status:"danglingSymlink",symlinkTarget:e})}try{return $S(await(0,Co.realpath)(r),r,{status:"resolved"})}catch(e){if("ENOENT"!==Sc(e))return $S(r,r,MS(e))}return $S(r,r,{status:"unknownError",errno:"ENOENT",message:"realpath returned ENOENT but lstat found a non-symlink entry"})}catch(e){return"ENOENT"===Sc(e)?async function(e){let t=(0,s.dirname)(e);const r=[(0,s.basename)(e)];for(;(0,s.dirname)(t)!==t;){try{const n=await(0,Co.realpath)(t);return $S((0,s.join)(n,...r),e,{status:"newFile"})}catch(t){if("ENOENT"!==Sc(t))return $S(e,e,MS(t))}r.unshift((0,s.basename)(t)),t=(0,s.dirname)(t)}return $S(e,e,{status:"newFile"})}(r):$S(r,r,MS(e))}}}function OS(e){return"resolved"===e.status||"newFile"===e.status}function FS(e,t){switch(t.status){case"resolved":case"newFile":return"";case"danglingSymlink":return`Write blocked: \`${e}\` is a dangling symlink${t.symlinkTarget?` (target: ${t.symlinkTarget})`:""}. Cannot verify it does not point to a protected file.`;case"permissionDenied":return`Write blocked: cannot verify \`${e}\` -- permission denied resolving symlinks (${t.errno}).`;case"symlinkLoop":return`Write blocked: \`${e}\` has a symlink loop (${t.errno}). Cannot verify target.`;case"unknownError":return`Write blocked: cannot verify \`${e}\` -- ${t.errno}: ${t.message}.`;default:return`Write blocked: unknown resolution status for \`${e}\`.`}}function NS({realAbsolutePath:e,setting:t,resolvedWorkspaceRoots:r,resolvedAllowFolders:n,resolvedAllowGlobs:o}){return!("workspace"!==t.boundary||LS(e,r)||LS(e,n)||US(e,t.allowPaths)||US(e,o))}function LS(e,t){return t.some((t=>(0,Yo.BJ)(e,t)))}function jS(e){return e.flatMap((e=>{const t=(0,Yo.jl)(e.trim());return!t.includes("*")&&(0,s.isAbsolute)(t)?[(0,s.resolve)(t)]:[]}))}function US(e,t){const r="win32"===process.platform?Yo.oL:e=>e,n=r(e);return t.some((e=>{const t=(0,Yo.jl)(e.trim());return!(!t.includes("*")&&(0,s.isAbsolute)(t))&&(0,ms.T)(r(t),n)}))}const BS={caffeinate:{flags:["-d","-i","-m","-s","-u"],valueOptions:["-t","-w"]},command:{flags:["-p"],valueOptions:[],lookupFlags:["-v","-V"]},env:{flags:["-","-i","-0","-v","--ignore-environment","--null","--debug"],valueOptions:["-u","-C","--unset","--chdir"],assignments:!0,directoryOptions:["-C","--chdir"]},nice:{flags:[],valueOptions:["-n","--adjustment"],numericOption:!0},nohup:{flags:[],valueOptions:[]},stdbuf:{flags:[],valueOptions:["-i","-o","-e","--input","--output","--error"]},time:{flags:["-p"],valueOptions:[]},timeout:{flags:["-f","-p","-v","--foreground","--preserve-status","--verbose"],valueOptions:["-k","-s","--kill-after","--signal"],operands:1},xargs:{flags:["-0","-o","-p","-r","-t","-x","--null","--open-tty","--interactive","--no-run-if-empty","--verbose","--exit","--show-limits"],valueOptions:["-a","-d","-E","-I","-J","-L","-n","-P","-R","-S","-s","--arg-file","--delimiter","--max-args","--max-procs","--max-chars","--process-slot-var"],attachedValueOptions:["-e","-i","-l","--eof","--replace","--max-lines"],readsArguments:!0}};function WS(e){const t=[];let r=!0,n=!1,o=e;for(;;){const e=BS[s.posix.basename(o.name)];if(void 0===e)return{command:o,wrapperForms:t,allowlistable:r,readsArguments:n};const i=HS(o.args,e);if("unreadable"===i)return{command:o,wrapperForms:t,allowlistable:!1,readsArguments:n};if("none"===i)return{command:o,wrapperForms:t,allowlistable:r,readsArguments:n};const[a,...c]=o.args.slice(i);if(void 0===a||!KS(a))return{command:o,wrapperForms:t,allowlistable:!1,readsArguments:n};(o.name.includes("/")||o.args.slice(0,i).some((t=>qS(t,e)||zS(t.value,e))))&&(r=!1),n||=!0===e.readsArguments,t.push(o.fullText.trim()),o=new he.Pv({name:a.value,args:c,fullText:[a.value,...c.map((e=>e.value))].join(" ")})}}function HS(e,t){let r=0;for(;rt.startsWith("--")?e===t||e.startsWith(`${t}=`):/^-[^-]/.test(e)&&e.includes(t.slice(1))))}function GS(e,t,r){const n=e=>!0===r.attachedValueOptions?.includes(e);if(r.flags.includes(e)||n(e))return 1;if(e.startsWith("--")){const o=e.indexOf("=");if(-1!==o){const t=e.slice(0,o);return r.valueOptions.includes(t)||n(t)?1:void 0}if(!r.valueOptions.includes(e))return;return void 0===t?void 0:2}for(let o=1;o{const t=await DS(e);return OS(t.resolution)?t.resolvedPath:(0,Yo.o1)(e)})))}function uk(e,t,r){return`${e} blocked: cannot verify ${t} \`${r}\` while resolving symlinks. This can happen when access is denied or the path contains a symlink loop.`}function dk(e){return[...new Set(e)]}function hk(){return{fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}}function pk({basePath:e,targetPath:t,pathModule:r}){const n=r.resolve(e),o=r.resolve(t),s=r.relative(n,o);return""===s||".."!==s&&!s.startsWith(`..${r.sep}`)&&!r.isAbsolute(s)}function fk(e){return">"===e||">>"===e||">|"===e||"&>"===e||"&>>"===e}function mk(e){return"<"!==e.operator&&"<&"!==e.operator}function gk(e){if(void 0===e||e.trim()!==e)return;const t=Number(e);return Number.isInteger(t)&&t>=0?t:void 0}function wk(e){return"<<"===e.operator&&"heredoc_redirect"===e.targetNodeType&&1===e.destinationFds.length&&0===Number(e.destinationFds[0])&&void 0!==e.targetText}function yk(e,t){return!(/^=|[~*?[{(#^`]/.test(e)||"\\"!==t.sep&&e.includes("\\"))}function vk(e){return"word"===e.type||"number"===e.type?yk(e.value,s)?e.value:void 0:"raw_string"===e.type||"string"===e.type&&!/[$`\\]/.test(e.value)?e.value.slice(1,-1):void 0}function bk({command:e,readsArguments:t}){if(!function(e){const t=e.replace(/["']/g,"");return[t,t.replace(/\\/g,"")].some((e=>/^tee(?:-object)?(?:\.exe)?$/i.test(e.slice(Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"))+1))))}(e.name))return[];const r=e.args.map(vk);return t?[...r,void 0]:r}const Sk=new Set(["cd","chdir","pushd"]),kk=new Set(["popd","eval","source",".","trap","set-location","sl","push-location","pop-location"]);function _k(e){const t=e.replace(/["'\\]/g,"");return t.slice(t.lastIndexOf("/")+1).toLowerCase()}function Ck(e,t){return new he.Pv({name:e,args:t,fullText:[e,...t.map((e=>e.value))].join(" ")})}function Ek(e){let t=e;for(;;){const e=_k(t.name);if("command"===e){const e=Ck("command",t.args),r=WS(e).command;if(r!==e){t=r;continue}const n=t.args[0]?.value;return void 0===n||"-v"===n||"-V"===n?t:"unreadable"}if("builtin"!==e)return t;const r="--"===t.args[0]?.value?t.args.slice(1):t.args,[n,...o]=r;if(void 0===n)return t;const s=vk(n);if(void 0===s||s.startsWith("-"))return"unreadable";t=Ck(s,o)}}function xk(e,t){return!(!t.isAbsolute(e)||"/"!==t.sep&&/^[\\/]$/.test(t.parse(e).root))}async function Pk({parsingResult:e,workingDirectory:t,resolvePathForPermissions:r,pathModule:n}){const o=[t];for(const t of e.executableCommands.map(WS)){const e=Ek(t.command);if("unreadable"===e)return;const i=_k(e.name),a=e.args;if(kk.has(i)||/^cd\.\./.test(s=i)||/^[a-z]:$/.test(s))return;if(!Sk.has(i))continue;const c=1===a.length&&void 0!==a[0]?vk(a[0]):void 0;if(void 0===c||!xk(c,n))return;const l=await r(c);if(!OS(l.resolution))return;o.push(l.resolvedPath)}var s;return o}async function Rk({targetText:e,workingDirectory:t,workingDirectories:r,...n}){const o=xk(e,n.pathModule)?[t]:r;if(void 0===o)return;let s;for(const t of o)if(s=await Ik({...n,targetText:e,workingDirectory:t}),void 0===s)return;return s}async function Ik({targetText:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:o,pathModule:s,tempPathOptions:i}){if(""!==s.parse(e).root&&!s.isAbsolute(e))return;const a=await o(e,t);if(!OS(a.resolution))return;const c=[];for(const e of r){const t=await o(e);OS(t.resolution)&&c.push(t.resolvedPath)}return await async function({targetPath:e,rootPaths:t,pathModule:r}){if(e.split(r.sep).some((e=>".git"===e.toLowerCase())))return!0;for(const r of t)if(await(0,Oo.OK)(e,r).catch((()=>!0)))return!0;return!1}({targetPath:a.resolvedPath,rootPaths:c,pathModule:s})?void 0:c.some((e=>pk({basePath:e,targetPath:a.resolvedPath,pathModule:s})))?"workspace-file":n&&!(0,Oo.dA)(a.originalPath)&&Wk(a.resolvedPath,i)?"tmp-file":void 0}async function Tk({parsingResult:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n}){const i=await Pk({parsingResult:e,workingDirectory:t,resolvePathForPermissions:DS,pathModule:s});for(const a of e.executableCommands.map(WS).flatMap(bk))if("/dev/null"!==a&&(void 0===a||!await Rk({targetText:a,workingDirectory:t,workingDirectories:i,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:DS,pathModule:s,tempPathOptions:{platform:process.platform,env:process.env,pathModule:s,homeDirectory:(0,o.homedir)()}})))return!1;return!0}function Ak(e){return dk(e.map((e=>e.trim())).filter(Boolean))}function $k(e){const t=e.name.trim();if(!t)return[];const r=e.arguments.map((e=>e.trim())).filter(Boolean),n=r.length>0?`${t} ${r.join(" ")}`:t,o=e.subcommandTokens.map((e=>e.trim())).filter(Boolean);if(0===o.length)return[n];const s=`${t} ${o.join(" ")}`;return s===n?[n]:[n,s]}function Mk(e,t){const r=t.trim();return!!r&&e.some((e=>e===r||e.startsWith(`${r} `)))}function Dk(e){const t=e.name.trim(),r=e.arguments.map((e=>e.trim())).filter(Boolean).map((e=>new he.r6({type:"word",value:e})));return new he.Pv({name:t,args:r,fullText:[t,...r.map((e=>e.value))].join(" ").trim()})}function Ok(e,t={}){return{type:e,...t}}function Fk(e){return void 0!==e&&("deny"===e.default||void 0!==e.allow&&e.allow.length>0||void 0!==e.deny&&e.deny.length>0)}function Nk(...e){return e.filter((e=>void 0!==e)).join(" • ")}function Lk(e){const t=[];for(const r of e){const e=r.match(/^\s*Read\s*\((.*)\)\s*$/);e&&t.push((e[1]??"").trim())}return t}function jk(e,t){if("workspace"===e&&void 0!==t)return t}const Uk={workspace:0,system:1};function Bk(e){const t=e.match(/^\s*(Shell|Bash)\s*\((.*)\)\s*$/);if(!t)return null;const r=t[1];if("Shell"!==r&&"Bash"!==r)return null;const n=t[2]?.trim()??"",o=n.indexOf(":");return-1!==o?{shellType:r,fullPattern:n,commandPattern:n.slice(0,o).trim(),argsPattern:n.slice(o+1).trim()}:{shellType:r,fullPattern:n,commandPattern:n,argsPattern:null}}function Wk(e,{platform:t,env:r,pathModule:n,homeDirectory:o}){if((0,Oo.dA)(e))return!1;if("win32"===t){const t=r.TEMP??r.TMP;if(t){const r=n.normalize(t).toLowerCase(),o=n.normalize(e).toLowerCase(),s=r.endsWith(n.sep)?r:r+n.sep;return o===r||o.startsWith(s)}return!1}const s=e=>{const r=n.normalize(e);return"darwin"!==t?r:"/tmp"===r||r.startsWith("/tmp/")||"/var"===r||r.startsWith("/var/")?`/private${r}`:r},i=s(e);return(void 0===o||!pk({basePath:s(o),targetPath:i,pathModule:n}))&&("darwin"===t?["/private/tmp/","/private/var/folders/"].some((e=>i.startsWith(e))):["/tmp/","/private/tmp/","/var/folders/","/private/var/folders/","/var/tmp/"].some((e=>i.startsWith(e))))}function Hk(e,t){if("insecure_none"===t.type)return!0;if("insecure_none"===e.type)return!1;const r=(0,Oo.$b)(e.networkPolicy),n=(0,Oo.$b)(t.networkPolicy);if(r&&!n)return!1;const o=(0,Oo._B)(e.networkPolicy),s=(0,Oo._B)(t.networkPolicy);if(o&&n&&!s)return!1;if("workspace_readonly"===e.type&&"workspace_readwrite"===t.type)return!0;if("workspace_readwrite"===e.type&&"workspace_readonly"===t.type)return!1;const i=e.readBoundary??"system",a=t.readBoundary??"system";return!(Uk[i]>Uk[a])}function qk(e){return{wrapperForms:e.flatMap((e=>e.wrapperForms)),allowlistable:e.every((e=>e.allowlistable)),readsArguments:e.some((e=>e.readsArguments))}}function zk(e){return[...e.wrapperForms,e.command.fullText.trim()].filter(Boolean)}class Gk{constructor(e,t,r,n,o){this.command=e,this.requestedPolicy=t,this.wrapperForms=o?.wrapperForms??[],this.allowlistable=o?.allowlistable??!0,this.readsArguments=o?.readsArguments??!1;const s=void 0!==r&&Hk(t,r);this.state=s?"preapproved":"approvable";const i=[e.fullText.trim()].filter(Boolean);this.matchForms=n&&n.length>0?[...n]:i}approveWithPolicy(e){"approvable"!==this.state&&"preapproved"!==this.state||!Hk(this.requestedPolicy,e)||(this.state="allowlisted")}deny(){this.state="denied"}isRunnable(){return"preapproved"===this.state||"allowlisted"===this.state}}function Vk(e){return e?.type??"undefined"}const Kk=["skills","skills-cursor","rules","plugins"],Jk=["assets","agent-notes","agent-tools","swarm-agents"];async function Zk(e,t,r){return e.shouldBlockFileRead?.(t,r)??e.shouldBlockRead(t,r)}function Xk(e){const t=e.lastIndexOf("::mcpScope:");return-1===t?e:e.slice(0,t)}function Qk({server:e,tool:t}){const r=e=>e.length>0&&e.length<=256&&!/[:*]/.test(e),n=e.trim().toLowerCase(),o=t.trim().toLowerCase();return r(n)&&r(o)?`${n}:${o}`:void 0}const Yk=/^\s*Read\s*\((.*)\)\s*$/,e_=/^\s*Write\s*\((.*)\)\s*$/;class t_{constructor(e,t,r,n,i,a=!1,c){this.ignoreService=e,this.pendingDecisionStore=t,this.permissionsProvider=r,this.teamSettingsService=n,this.adminNetworkControlsEnabled=a,this.computerUseAppsAllowedForSession=[],this.rootDirectories=Array.isArray(i)?i:[i??process.cwd()],this.projectDir=c?.projectDir,this.perUserSandboxConfigPath=c?.perUserSandboxConfigPath??(0,s.join)((0,o.homedir)(),".cursor","sandbox.json"),this.mcpAllowlistLog=c?.mcpAllowlistLog,this.computerUse=c?.computerUse,this.computerUseAdminPolicy=c?.computerUseAdminPolicy,this.enforceMcpAdminToolLimits=c?.enforceMcpAdminToolLimits,this.onMcpAdminToolLimitCheck=c?.onMcpAdminToolLimitCheck}async shouldBlockRead(e,t={}){return this.shouldBlockReadInternal(e,t,!1)}async shouldBlockFileRead(e,t={}){return this.shouldBlockReadInternal(e,t,!0)}async getFileReadBoundaryBlocker(){const{perms:e,setting:t}=await this.readControlSetting(),r=e.deny.filter((e=>this.isPathEntry("Read",e))),n="workspace"===t.boundary&&"unrestricted"!==e.approvalMode;if(!n&&0===r.length)return;const[o,s,i]=n?await Promise.all([this.resolveWorkspaceReadRoots(e.userSandboxDataFolderName),this.resolvedReadAllowFolders(t.allowPaths),this.resolvedReadAllowGlobs(t.allowPaths)]):[[],[],[]],a=r.map((e=>this.compileReadDenyMatcher(e))),c=e=>a.some((t=>t(e)));return async(e,r)=>c(e)||c(r)||n&&NS({realAbsolutePath:r,setting:t,resolvedWorkspaceRoots:o,resolvedAllowFolders:s,resolvedAllowGlobs:i})}async readControlSetting(){const e=await this.getPermissions(),{enabled:t,...r}=await this.adminReadControls(e);return{perms:e,setting:function(e){if(!e.enabled)return{boundary:"system",allowPaths:[],enforcedByAdmin:!1};const t="workspace"===e.admin.boundary,r=t||"workspace"===e.local.boundary?"workspace":"system",n=t?e.admin.allowPaths:[];return{boundary:r,allowPaths:t&&!1===e.admin.allowUserOverride?[...n]:[...new Set([...n,...e.local.allowPaths])],enforcedByAdmin:t}}({enabled:t,admin:r,local:{boundary:e.readBoundary,allowPaths:Lk(e.allow)}})}}async adminReadControls(e){const t=e.teamAdminPolicy,r=this.teamSettingsService.isReadControlEnabled?.()??!0;if(void 0!==t&&"unavailable"!==t){const e=await r;return"workspace"!==t.readBoundary?{enabled:e,boundary:void 0,allowPaths:[],allowUserOverride:void 0}:{enabled:e,boundary:"workspace",allowPaths:t.additionalReadPaths??[],allowUserOverride:t.allowUserOverrideReadPaths}}const[n,o]=await Promise.all([r,this.teamSettingsService.getSandboxingControls()]);return{enabled:n,boundary:o.readBoundary,allowPaths:o.readAllowlistPaths??[],allowUserOverride:o.allowUserOverrideReadAllowlist}}resolvedReadAllowFolders(e){return lk([...jS(e),...(0,Oo.r5)()])}async resolvedReadAllowGlobs(e){const t=function(e){return e.flatMap((e=>{const t=(0,Yo.jl)(e.trim()),r=t.indexOf("*");if(r<0||!(0,s.isAbsolute)(t))return[];const n="win32"===process.platform?Math.max(t.lastIndexOf("/",r),t.lastIndexOf("\\",r)):t.lastIndexOf("/",r);return n>=(0,s.parse)(t).root.length?[{folder:t.slice(0,n),rest:t.slice(n)}]:[]}))}(e),r=await lk(t.map((({folder:e})=>e)));return t.map((({rest:e},t)=>function(e,t,r={parse:s.parse}){return r.parse(e).root===e&&/[\\/]$/.test(e)?`${e}${t.slice(1)}`:`${e}${t}`}(r[t],e)))}async resolveWorkspaceReadRoots(e){const t=(0,s.join)((0,o.homedir)(),void 0!==e&&e.length>0?e:".cursor"),r=[...this.rootDirectories.map((e=>(0,s.join)(t,"projects",(0,So.r_)(e)))),...Kk.map((e=>(0,s.join)(t,e)))],n=this.rootDirectories.flatMap((e=>(0,Oo.W1)(e)??[]));return lk([...this.rootDirectories,...r,...n,...void 0===this.projectDir?[]:[this.projectDir]])}async shouldBlockReadInternal(e,{cursorIgnoreChecked:t=!1},r){const n=(0,Yo.o1)(e),o=await Cc(n);if(null===o)return{type:"unsafeResolution",message:uk("Read","path",n)};if(await this.ignoreService.isRepoBlocked(o))return{type:"adminBlock",source:"Team repo blocklist"};if(await this.isPathExplicitlyDenied("Read",n))return{type:"permissionsConfig"};if(!t&&!wS(o)&&!gS(o,{dataFolderName:(await this.getPermissions()).userSandboxDataFolderName})&&await this.ignoreService.isCursorIgnored(o))return{type:"cursorIgnore"};if(r){const e=await this.shouldBlockReadForBoundary(o);if(e)return e}return!1}async shouldBlockReadForBoundary(e){const{perms:t,setting:r}=await this.readControlSetting();if("workspace"!==r.boundary||"unrestricted"===t.approvalMode)return!1;const n=await this.resolveWorkspaceReadRoots(t.userSandboxDataFolderName);if(LS(e,n))return!1;const[o,s]=await Promise.all([this.resolvedReadAllowFolders(r.allowPaths),this.resolvedReadAllowGlobs(r.allowPaths)]);return!!NS({realAbsolutePath:e,setting:r,resolvedWorkspaceRoots:n,resolvedAllowFolders:o,resolvedAllowGlobs:s})&&{type:"needsApproval",approvalReason:r.enforcedByAdmin?"This reads a file outside your workspace and requires approval under your team's read policy.":"This reads a file outside your workspace.",approvalDetails:{type:"fileRead",path:e}}}async isProjectDirInternalPath(e,t){if(void 0===this.projectDir)return!1;const r=await DS(this.projectDir);return!!OS(r.resolution)&&vS(r.resolvedPath,e,t)}async isFreelyWritableOutsideWorkspace(e,t){return function(e){return Wk(e,{platform:process.platform,env:process.env,pathModule:s,homeDirectory:(0,o.homedir)()})}(e)||yS(e,Jk,{dataFolderName:t})||await this.isProjectDirInternalPath(e,Jk)}async shouldBlockWrite(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{QS(n,(0,$.VI)(e.withName("InteractivePermissionsService.shouldBlockWrite")),!1).ctx;const i=await DS(t);if(!OS(i.resolution))return{type:"unsafeResolution",message:FS(i.originalPath,i.resolution)};const a=i.resolvedPath,c=a;if(await this.ignoreService.isRepoBlocked(c))return{type:"adminBlock",source:"Team repo blocklist"};if(await this.isPathExplicitlyDenied("Write",a))return{type:"permissionsConfig"};const l=i.originalPath.split(s.sep).pop()?.toLowerCase()??"",u=a.split(s.sep).pop()?.toLowerCase()??"";if(".cursorignore"===l||".cursorignore"===u)return{type:"permissionsConfig"};if((0,Oo.dA)(i.originalPath)||(0,Oo.dA)(a))return{type:"permissionsConfig"};const d=await this.getPermissions();if(!wS(c)&&!gS(c,{dataFolderName:d.userSandboxDataFolderName})&&await this.ignoreService.isCursorIgnored(c))return{type:"cursorIgnore"};if("workspace_readonly"===d.userConfiguredPolicy.type)return{type:"permissionsConfig",isReadonly:!0};if(await this.isPathExplicitlyAllowed("Write",a))return!1;if("unrestricted"===d.approvalMode)return!1;const h=async()=>{let e,t,n="";try{n=await ji(a),e=!1}catch{e=!0}if(e)t=r;else{const e=e=>e.endsWith("\n")?e:`${e}\n`,{hunks:o}=(0,cS.YB)("a","b",e(n),e(r),"","",{context:2});t=o.map((e=>e.lines.map((e=>e.length>0?`${e[0]} ${e.slice(1)}`:e)).join("\n"))).join("\n...\n")}return{isNewFile:e,diffString:t}};let p;const f=[];for(const e of this.rootDirectories){const t=await DS(e);if(OS(t.resolution)){if((0,Yo.BJ)(a,t.resolvedPath)){p=t.resolvedPath;break}f.push(t.resolvedPath)}}const m=void 0===p?await async function(e,t,r={}){if(0===t.length)return;let n;for(let o=(0,s.dirname)(e);;o=(0,s.dirname)(o)){if((0,qs.$f)(o))return;const e=(0,s.join)(o,".git"),i=await(0,Co.lstat)(e).catch(TS);if(i?.isFile()){const s=await xS(e);if(void 0!==s){const{commonDir:e}=s;if(CS(o,t))return;if(t.some((t=>(0,Yo.BJ)(e,t))))return{root:o,commonDir:e};if(!await(r.isUntrustedExternalGitDir?.(e))&&(await(n??=Promise.all(t.map((e=>ES(e)))),n)).some((t=>void 0!==t&&AS(t,e))))return{root:o,commonDir:e}}}if((0,s.dirname)(o)===o)return}}(a,f,{isUntrustedExternalGitDir:e=>this.isFreelyWritableOutsideWorkspace(e,d.userSandboxDataFolderName)}):void 0;let g=!1;const w=p??m?.root;if(void 0!==w){const e=(0,s.relative)(w,a),t=e.split(s.sep).map((e=>"win32"===process.platform&&e.includes(":")?e.split(":")[0]:e));if(g=function(e){const t=e.replace(/\\/g,"/");return/(^|\/)\.cursor\/debug(?:-[a-zA-Z0-9-]+)?\.log$/i.test(t)}(e),!g){const e=await this.checkCursorFileProtection(t);if(e)return e}if("win32"===process.platform&&t.some((e=>e.includes("~")))){const{isNewFile:e,diffString:r}=await h();return{type:"needsApproval",approvalReason:`Protected config file: ${t[t.length-1]??""}`,approvalDetails:{type:"fileEdit",isNewFile:e,diffString:r,blockReason:"protectedConfig"}}}if(await(0,Oo.OK)(a,w)){const e=t[t.length-1]?.toLowerCase()??"",{isNewFile:r,diffString:n}=await h();return{type:"needsApproval",approvalReason:`Protected config file: ${e}`,approvalDetails:{type:"fileEdit",isNewFile:r,diffString:n,blockReason:"protectedConfig"}}}}if(void 0===p&&(void 0===m||"workspace"===(await this.readControlSetting()).setting.boundary)){if(await this.isFreelyWritableOutsideWorkspace(a,d.userSandboxDataFolderName))return!1;const e=`${(0,o.homedir)()}${s.sep}.cursor${s.sep}`;if(a.startsWith(e)){const e=a.split(s.sep).pop()?.toLowerCase()??"";if(e.endsWith(".md")||e.endsWith(".mdc")||".cursorrules"===e)return!1}const{isNewFile:t,diffString:r}=await h();return{type:"needsApproval",approvalReason:"Out of workspace",approvalDetails:{type:"fileEdit",isNewFile:t,diffString:r,blockReason:"outOfWorkspace"}}}if(g)return!1;if(!0===d.promptWorkspaceWrites){const{isNewFile:e,diffString:t}=await h();return{type:"needsApproval",approvalReason:"Workspace write",approvalDetails:{type:"fileEdit",isNewFile:e,diffString:t,blockReason:"workspaceWrite"}}}return!1}catch(e){n.error=e,n.hasError=!0}finally{YS(n)}}async shouldEnforceShellInvariantBlocks(e,t,r){const n=await this.getAdminCommandDenylistBlock(e,{command:t.command,parsingResult:t.parsingResult,toolCallId:t.toolCallId});if(void 0!==n)return{kind:"block",reason:n};const o=await Cc(t.workingDirectory);if(null===o){if(!0!==t.skipUnsafeWorkingDirectoryBlock)return{kind:"block",reason:{type:"unsafeResolution",message:uk("Command","working directory",t.workingDirectory)}}}else if(await this.ignoreService.isRepoBlocked(o))return{kind:"block",reason:{type:"adminBlock",source:"Team repo blocklist"}};const s=(await this.getPermissions()).userConfiguredPolicy,i=r??s;return"workspace_readonly"===s.type&&"workspace_readonly"!==i.type?{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}}:void 0!==r?{kind:"allow",policy:r}:!0!==t.resolveSkippedApprovalPolicy||"workspace_readonly"!==s.type?{kind:"allow",policy:void 0}:{kind:"allow",policy:await this.applyServerAndAdminPolicies({...s,skipStatsigDefaults:s.skipStatsigDefaults??!0})}}async shouldBlockShellCommand(e,t,r,n){const o="insecure_none"===n?.type,s=await this.shouldEnforceShellInvariantBlocks(e,{workingDirectory:r.workingDirectory,command:t,parsingResult:r.parsingResult,toolCallId:r.toolCallId},n);if("block"===s.kind)return s;const i=await this.getPermissions(),a=i.approvalMode,c="unrestricted"===a,l=i.userConfiguredPolicy,u=!i.dashboardTerminalAllowlistOverriddenByPermissionsFile;if(ek.info(e,"Shell permissions: evaluating shell command",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:Vk(l),requestedPolicyType:Vk(n),effectiveRequestedPolicyType:Vk(n??l),smartAllowlistEnabled:!0===i.smartAllowlistEnabled,hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId,hookForcesPrompt:$o(r.hookApprovalRequirement),classifierClassificationFailed:!0===r.classifierResult?.classificationFailed,classifierCommandCount:r.classifierResult?.commands.length??0,parserCommandCount:r.parsingResult.executableCommands.length,parsingFailed:r.parsingResult.parsingFailed,hasRedirects:r.parsingResult.hasRedirects,commandLength:t.length}),await this.shouldPromptForEmptyPlainShellAllowlist(t,i))return ek.info(e,"Shell permissions: prompting for empty allowlist",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:Vk(l),requestedPolicyType:Vk(n),hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId}),await this.requestApprovalForEmptyShellAllowlist(t,r,n??l);const d=r.parsingResult.executableCommands,h=r.parsingResult.parsingFailed,p=r.classifierResult,f=r.smartModeApprovalReason,m=r.smartModeApprovalRequestId,g=void 0!==p&&!p.classificationFailed&&p.commands.length>0?p:void 0,w="allowlist"===a&&i.smartAllowlistEnabled?g?.commands:void 0,y=void 0!==w,v=d.map(WS),b=w?w.map(Dk):v.map((e=>e.command)),S=void 0!==w?w.map($k):b.map((e=>[e.fullText.trim()].filter(Boolean))),k=void 0!==g?g.commands.map($k):v.map(zk);if(n||(n=i.userConfiguredPolicy),"insecure_none"!==n.type&&void 0===n.skipStatsigDefaults&&"insecure_none"!==l.type&&(n={...n,skipStatsigDefaults:l.skipStatsigDefaults??!0}),"insecure_none"!==l.type&&(0,Oo.$b)(l.networkPolicy)&&"insecure_none"!==n.type&&!(0,Oo._B)(n.networkPolicy)){const e=l.networkPolicy,t=n.networkPolicy?.allow;if(void 0!==t&&t.length>0&&e){const r=[...new Set([...e.allow??[],...t])];n={...n,networkPolicy:{...e,allow:r}}}else n={...n,networkPolicy:e}}let _;n=function({requestedPolicy:e,userConfiguredPolicy:t}){if("insecure_none"===e.type||"insecure_none"===t.type)return e;const r=(0,Oo.XX)(e.readBoundary,t.readBoundary),n="workspace"===r?(0,Oo.wG)(jk(e.readBoundary,e.additionalReadPaths),jk(t.readBoundary,t.additionalReadPaths)):void 0;return{...e,readBoundary:r,additionalReadPaths:n}}({requestedPolicy:n,userConfiguredPolicy:l}),p&&ek.info(e,"Smart allowlist: classifier result received",{classificationFailed:p.classificationFailed,suggestedSandboxMode:p.suggestedSandboxMode,commandCount:p.commands.length,suggestedAllowlistEntryCount:p.commands.filter((e=>e.suggestedAllowlistEntry)).length});const C=[],E=[];let x=[],P=[],R=[];const I=Ak(i.smartAllowlistDenylist??[]);if(I.length>0){P=[];const t=k.map((e=>e[0]??""));for(let e=0;eMk(r,e)))){const r=t[e];r&&P.push(r)}}P.length>0&&(ek.info(e,"Command blocklist: commands require approval",{count:P.length}),C.push(`In blocklist: ${P.join(", ")}`))}if(y&&p){const t=S.map((e=>e[0]??"")),r=i.allow.filter((e=>this.isShellEntry(e)));ek.info(e,"Smart allowlist: checking commands against lists",{commandCount:t.length,allowlistCount:r.length,commandBlocklistCount:I.length});const n=S.map((e=>r.some((t=>e.some((e=>this.matchesShell(t,e))))))),o=n.every(Boolean),s=[];for(let e=0;efunction(e){const t=e.name.trim();if(!t)return[];if(Hb(t))return[];const r=e.subcommandTokens.map((e=>e.trim())).filter(Boolean),n=e.arguments.map((e=>e.trim())).filter(Boolean),o=[t],s=[t];for(const e of r)s.push(e),o.push(s.join(" "));const i=[t,...n].join(" ");return o.includes(i)||o.push(i),Ak(o)}(e)))),R=s.map((e=>e.suggestedAllowlistEntry)).filter((e=>"string"==typeof e)).filter((e=>x.includes(e))),x.length>0){const e=Vb(x,R),t=e.length>0?e.join(", "):x.join(", ");E.push(`Not in allowlist: ${t}`)}_=o&&0===P.length,_&&ek.info(e,"Smart allowlist: all commands in allowlist, will check security",{commandCount:t.length})}const T="ask-every-time"===a||"insecure_none"===n.type&&"allowlist"===a?void 0:l,A=qk(v),$=b.map(((e,t)=>new Gk(e,n,T,S[t],y?A:v[t])));if((0===b.length||h&&!y)&&!c){ek.info(e,"Shell permissions: prompting after parser miss",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:Vk(n),userConfiguredPolicyType:Vk(l),isSmartAllowlistActive:y,parsingFailed:h,parserCommandCount:b.length,hasSmartModeApprovalReason:void 0!==f,hasSmartModeApprovalRequestId:void 0!==m});const o={type:Lw.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:Nk(f??(h?"Parser failed to parse command (possible bypass)":"Parser found no commands (possible bypass)"),await this.adminNetworkLimitReason(n)),isSandboxAvailable:!1,isSandboxEnabled:!1,canAllowlist:!1,notAllowedCommands:[],smartModeApprovalReason:f,smartModeApprovalRequestId:m}};r.onApprovalRequested?.();const s=await this.pendingDecisionStore.requestApproval(o);return s.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(n)}:{kind:"block",reason:{type:"userRejected",reason:s.reason}}}if(await this.hasHardDeny(e,$))return{kind:"block",reason:{type:"permissionsConfig",..."workspace_readonly"===l.type?{isReadonly:!0}:{}}};const{allowlistOfferSafe:M,redirectsAllowlistSafe:D}=await this.computeRedirectAllowlistSafety(r.parsingResult,r.workingDirectory,"insecure_none"===l.type||"workspace"!==l.readBoundary),O=await this.teamSettingsService.getAutoRunControls(),F={type:"insecure_none"};for(const e of $)await this.cmdIsAllowedByAllowlist(e,{redirectsAllowlistSafe:D,autoRunControls:O,applyTeamAllowlist:u})&&e.approveWithPolicy(F);for(const e of $)O&&this.isInTeamBlocklist(O,e)&&e.deny();const N=await this.teamSettingsService.getDeleteFileProtection();if(N)for(const e of $)"rm"===e.command.name&&e.deny();const L=this.buildShellApprovalDecisionFacts({commands:$,autoRunControls:O,shouldApplyTeamShellAllowlist:u,deleteProtectionEnabled:N,softDenylistedCommands:P});if("workspace_readonly"===l.type&&"workspace_readonly"!==n.type)return ek.info(e,"Shell permissions: blocked by readonly mode"),{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}};const j=$o(r.hookApprovalRequirement),U=r.hookApprovalRequirement?.reason,B=o&&"insecure_none"!==l.type&&function(e){if(/\brimraf\b/i.test(e))return!0;for(const t of e.replace(/[\\`^]\r?\n/g," ").split(/(?|])&|\|\||[;\n]/)){let e=!1;for(const r of t.split("|")){if(e&&JS.test(r)||XS(r,JS,ZS)||XS(r,/(?0&&(L.hasSecurityDenies||L.hasSoftDenies||!L.allCommandsRunnable);if(void 0!==f&&G.push(f),j&&(V||G.push(U?`Hook requested approval: ${U}`:"Hook requested approval"),z=!1),B&&(V||G.push("Recursive delete outside the sandbox"),z=!1),C.length>0&&(V||G.push(...C),z=!1),!V)if(y&&E.length>0)G.push(...E);else if(L.unapprovedCommands.length>0){const e=Vb(this.generateAllowlistPatterns(L.unapprovedCommands)),t=e.length>0?e.join(", "):L.unapprovedCommands.map((e=>e.command.fullText)).join(", ");G.push(`Not in allowlist: ${t}`)}if(L.hasSecurityDenies&&(V||(L.rmDeniedByDeleteProtection.length>0&&G.push("Delete protection is enabled"),L.teamBlocklistedCommands.length>0&&G.push(`In team blocklist: ${L.teamBlocklistedCommands.map((e=>e.command.name)).join(", ")}`)),z=!1),K){const t=L.notInTeamAllowlist.map((e=>e.command.fullText)).join(", ");ek.info(e,"Shell permissions: commands not in team allowlist",{commandCount:L.notInTeamAllowlist.length}),V||G.push(`Not in team allowlist: ${t}`),z=!1}const J="unrestricted"===a&&"workspace_readonly"===n.type,Z="unrestricted"!==a||J?n:{type:"insecure_none"},X=Nk(...G,await this.adminNetworkLimitReason(Z)),Q=[];if(z){const e=void 0!==f?$.filter((e=>"allowlisted"!==e.state)):L.unapprovedCommands;Q.push(...this.generateAllowlistPatterns(e))}const Y=y&&E.length>0,ee=Y?x:Q,te=Y&&R.length>0?R:void 0,re="insecure_none"!==n.type&&"insecure_none"!==l.type,ne="insecure_none"!==n.type,oe=[void 0!==f?"smart_mode_approval":void 0,j?"hook_forces_prompt":void 0,B?"unsandboxed_recursive_delete":void 0,C.length>0?"command_blocklist":void 0,y&&E.length>0?"smart_allowlist_miss":void 0,L.unapprovedCommands.length>0?"unapproved_commands":void 0,L.hasSecurityDenies?"security_denies":void 0,K?"team_allowlist_miss":void 0].filter((e=>void 0!==e));ek.info(e,"Shell permissions: requesting shell approval",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:Vk(n),userConfiguredPolicyType:Vk(l),isSandboxAvailable:re,isSandboxEnabled:ne,canAllowlist:z,isSmartAllowlistActive:y,hasSmartModeApprovalReason:void 0!==f,hasSmartModeApprovalRequestId:void 0!==m,hookForcesPrompt:j,approvalReasonTypes:oe,commandCount:$.length,unapprovedCommandCount:L.unapprovedCommands.length,deniedCommandCount:L.deniedCommands.length,notInTeamAllowlistCount:L.notInTeamAllowlist.length,notAllowedCommandCount:ee.length,suggestedAllowlistEntryCount:te?.length??0,allCommandsRunnable:L.allCommandsRunnable,allCommandsAllowlisted:L.allCommandsAllowlisted,allCommandsPreapproved:L.allCommandsPreapproved,hasSecurityDenies:L.hasSecurityDenies,hasSoftDenies:L.hasSoftDenies});const se={type:Lw.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:X,isSandboxAvailable:"allowlist"===a&&re,isSandboxEnabled:!("allowlist"!==a&&!J)&&ne,canAllowlist:z,notAllowedCommands:ee,suggestedAllowlistEntries:te,smartModeApprovalReason:f,smartModeApprovalRequestId:m}};r.onApprovalRequested?.();const ie=await this.pendingDecisionStore.requestApproval(se);return ie.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(Z)}:{kind:"block",reason:{type:"userRejected",reason:ie.reason}}}async isShellCommandFullyAllowlisted(e,t,r){const n=e.withName("InteractivePermissionsService.isShellCommandFullyAllowlisted"),o=await this.getPermissions(),s=!o.dashboardTerminalAllowlistOverriddenByPermissionsFile;if("allowlist"!==o.approvalMode)return!1;if("workspace_readonly"===o.userConfiguredPolicy.type)return!1;const{redirectsAllowlistSafe:i}=await this.computeRedirectAllowlistSafety(r.parsingResult,r.workingDirectory,"insecure_none"===o.userConfiguredPolicy.type||"workspace"!==o.userConfiguredPolicy.readBoundary);if(!i)return!1;const a=r.classifierResult,c=void 0!==a&&!a.classificationFailed&&a.commands.length>0?a:void 0,l=(o.smartAllowlistEnabled??!1)&&void 0!==c;if(r.parsingResult.parsingFailed&&!l)return!1;const u=r.parsingResult.executableCommands.map(WS),d=l?c.commands.map(Dk):u.map((e=>e.command));if(0===d.length)return!1;const h=l?c.commands.map($k):d.map((e=>[e.fullText.trim()].filter(Boolean))),p=void 0!==c?c.commands.map($k):u.map(zk),f={type:"insecure_none"},m=qk(u),g=d.map(((e,t)=>new Gk(e,f,void 0,h[t],l?m:u[t])));if(await this.hasHardDeny(n,g))return!1;const w=Ak(o.smartAllowlistDenylist??[]);if(w.length>0)for(const e of p)if(e&&0!==e.length&&w.some((t=>Mk(e,t))))return!1;if(await this.teamSettingsService.getDeleteFileProtection()&&g.some((e=>"rm"===e.command.name)))return!1;const y=await this.teamSettingsService.getAutoRunControls();if(void 0!==y&&g.some((e=>this.isInTeamBlocklist(y,e))))return!1;for(const e of g)if(!await this.cmdIsAllowedByAllowlist(e,{redirectsAllowlistSafe:i,autoRunControls:y,applyTeamAllowlist:s}))return!1;return!0}async applyServerAndAdminPolicies(e){if("insecure_none"===e.type)return e;const t=this.rootDirectories.at(0)??(0,o.homedir)(),{userSandboxDataFolderName:r,teamAdminPolicy:n}=await this.getPermissions(),i=void 0!==r&&r.length>0?(0,s.join)((0,o.homedir)(),r,"sandbox.json"):this.perUserSandboxConfigPath,a=await this.foldPerUserFilePolicy(e,i),c=a.skipStatsigDefaults?a:await this.applyStatsigDefaults(a),l=await this.loadPerRepoFilePolicy(c,t),u=await this.resolveTeamAdminLayer(n);if("unavailable"===u){const{policy:e}=await(0,Oo.resolveSandboxPolicyForWorkspace)(t,{perUser:c,perRepo:l});return function(e){return"insecure_none"===e.type?e:{...e,networkPolicy:(0,Oo.Po)(),readBoundary:"workspace",additionalReadPaths:[]}}(e)}const d=void 0===u?void 0:Ok(c.type,u),h=(0,Oo._B)(e.networkPolicy)&&!Fk(d?.networkPolicy),{policy:p}=await(0,Oo.resolveSandboxPolicyForWorkspace)(t,{perUser:c,perRepo:l,teamAdmin:d});return h?{...p,networkPolicy:(0,Oo.T6)()}:p}async resolveLinkedWorktreeSandboxGrants(e,t){if("workspace_readwrite"!==e.type||"workspace"===e.readBoundary)return;const{perms:r,setting:n}=await this.readControlSetting();if("workspace"===n.boundary||"unavailable"===r.teamAdminPolicy)return;const i=r.userSandboxDataFolderName;if(void 0===e.readBoundary){const t=this.rootDirectories.at(0)??(0,o.homedir)(),n=void 0!==i&&i.length>0?(0,s.join)((0,o.homedir)(),i,"sandbox.json"):this.perUserSandboxConfigPath,a="readBoundary"in r.userConfiguredPolicy&&void 0!==r.userConfiguredPolicy.readBoundary?{...e,readBoundary:r.userConfiguredPolicy.readBoundary}:e,c=await this.foldPerUserFilePolicy(a,n),l=await this.loadPerRepoFilePolicy(c,t);if("workspace"===(l?.readBoundary??c.readBoundary))return}const a=[];for(const e of this.rootDirectories){if((0,qs.$f)(e))continue;const t=await DS(e);OS(t.resolution)&&!wS(t.resolvedPath)&&a.push(t.resolvedPath)}if(0===a.length)return;let c;if(!(0,qs.$f)(t.workingDirectory)){const e=await DS(t.workingDirectory);OS(e.resolution)&&(c=e.resolvedPath)}return async function(e,t={}){if(0===e.length)return;const r=await Promise.all(e.map((e=>ES(e)))),n=[];for(const o of r)void 0===o||n.some((e=>AS(e,o)))||!e.some((e=>(0,Yo.BJ)(o,e)))&&await(t.isUntrustedExternalGitDir?.(o))||n.push(o);if(0===n.length)return;const o=[],i=[],a=void 0!==t.command||void 0!==t.realWorkingDirectory;for(const r of n){const n=await _S((0,s.join)(r,"worktrees"),256),c=await(0,Or.PH)(n,(e=>kS((0,s.join)(r,"worktrees",e),r,!0===t.excludeAgentWorktrees,a?{command:t.command,realWorkingDirectory:t.realWorkingDirectory}:void 0)),{max:16});let l=!1;for(const r of c){if(o.length>=16)break;void 0===r||o.some((e=>AS(e,r)))||e.some((e=>(0,Yo.BJ)(r,e)))||CS(r,e)||await(t.isExcludedWorktreeRoot?.(r))||(o.push(r),l=!0)}l&&i.push(r)}return 0===o.length?void 0:{roots:o,commonDirs:i}}(a,{command:t.command,realWorkingDirectory:c,excludeAgentWorktrees:!0,isUntrustedExternalGitDir:e=>this.isFreelyWritableOutsideWorkspace(e,i),isExcludedWorktreeRoot:async e=>await this.isFreelyWritableOutsideWorkspace(e,i)||await this.ignoreService.isRepoBlocked(e)})}async foldPerUserFilePolicy(e,t=this.perUserSandboxConfigPath){const r=await(0,Oo.tv)(t,(0,o.homedir)());if(!r||"insecure_none"===r.type)return e;let n=(0,Oo.fZ)(r.networkPolicy,e.networkPolicy);n&&void 0!==e.networkPolicy?.default&&(n={...n,default:e.networkPolicy.default});const s=(0,Oo.s9)(r.additionalReadonlyPaths,e.additionalReadonlyPaths),i={...e,networkPolicy:n,additionalReadonlyPaths:s.length>0?s:void 0,readBoundary:r.readBoundary??e.readBoundary,additionalReadPaths:void 0!==r.additionalReadPaths?r.additionalReadPaths:e.additionalReadPaths,privateTmp:r.privateTmp??e.privateTmp};if("workspace_readwrite"===e.type&&"workspace_readwrite"===r.type){const t=(0,Oo.s9)(r.additionalReadwritePaths,e.additionalReadwritePaths);return{...i,additionalReadwritePaths:t.length>0?t:void 0}}return i}async applyStatsigDefaults(e){const t=await this.teamSettingsService.getDefaultNetworkAllowlist();if(!t.available||0===t.allowlist.length)return e;if((0,Oo._B)(e.networkPolicy))return e;const r={default:"deny",allow:dk(t.allowlist)};return{...e,networkPolicy:(0,Oo.fZ)(e.networkPolicy,r)}}async loadPerRepoFilePolicy(e,t){const r=await(0,Oo.tv)((0,s.join)(t,".cursor","sandbox.json"),t);if(r){if("1"===process.env[Zv.K4]){const n=(0,Oo.fB)({perUser:e,perRepo:r},t).perRepo;return"insecure_none"===n?.type?void 0:n}if("insecure_none"!==r.type)return r.type!==e.type?Ok(e.type,{networkPolicy:r.networkPolicy,additionalReadonlyPaths:r.additionalReadonlyPaths,..."additionalReadwritePaths"in r?{additionalReadwritePaths:r.additionalReadwritePaths}:{},disableTmpWrite:r.disableTmpWrite,networkPolicyStrict:r.networkPolicyStrict,readBoundary:r.readBoundary,additionalReadPaths:r.additionalReadPaths,privateTmp:r.privateTmp}):r}}async resolveTeamAdminLayer(e){return void 0!==e?"unavailable"===e?"unavailable":"workspace"===(t=e).readBoundary?t:void 0===t.networkPolicy?{}:{networkPolicy:t.networkPolicy}:async function(e){const{teamSettings:t}=e,r=e.adminNetworkControlsEnabled?(i=await t.getNetworkAccessControls()).available?0!==i.allowlist.length||0!==i.denylist.length?{...i.allowlist.length>0?{default:"deny",allow:dk(i.allowlist)}:{},...i.denylist.length>0?{deny:dk(i.denylist)}:{}}:void 0:(0,Oo.Po)():void 0,[n,o]=await Promise.all([t.isReadControlEnabled?.()??!0,t.getSandboxingControls()]),s=void 0===r?{}:{networkPolicy:r};var i;return n&&"workspace"===o.readBoundary?{...s,readBoundary:"workspace",additionalReadPaths:o.readAllowlistPaths??[],allowUserOverrideReadPaths:o.allowUserOverrideReadAllowlist}:void 0===r?void 0:s}({teamSettings:this.teamSettingsService,adminNetworkControlsEnabled:this.adminNetworkControlsEnabled});var t}async adminNetworkLimitReason(e){if("insecure_none"===e.type||!(0,Oo._B)(e.networkPolicy))return;const{teamAdminPolicy:t}=await this.getPermissions(),r=await this.resolveTeamAdminLayer(t);return function(e){if(Fk(e))return void 0!==e.allow&&e.allow.length>0?"Network access limited to your admin's allowlist":"deny"===e.default?"Network access limited by your admin":"Network access excludes domains your admin blocks"}("unavailable"===r?(0,Oo.Po)():r?.networkPolicy)}async getAdminReadSandboxing(){const e=await this.getPermissions();if("unavailable"===e.teamAdminPolicy)return{readBoundary:"workspace"};const{enabled:t,boundary:r}=await this.adminReadControls(e);return{readBoundary:t&&"workspace"===r?"workspace":void 0}}async isInShellAllowlist(e){if(!e.allowlistable)return!1;const t=await this.getPermissions(),r=e.readsArguments?e.matchForms.map((e=>`${e} \0`)):e.matchForms;return t.allow.some((e=>this.isShellEntry(e)&&r.some((t=>this.matchesShell(e,t)))))}isInTeamBlocklist(e,t){const r=[...t.wrapperForms,t.command.fullText];return e.blocked.some((e=>r.some((t=>this.matchesAutoRunCommand(t,e)))))}isInTeamAllowlist(e,t){return!!t.allowlistable&&e.allowed.some((e=>this.matchesAutoRunCommand(t.command.fullText,e)))}async computeRedirectAllowlistSafety(e,t,r){const n=e.hasRedirects,i=e.parsingFailed,a=!0===e.allRedirectsAreDevNull,c=!(!n||a||i)&&await async function({parsingResult:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n=!0,resolvePathForPermissions:i=DS,pathModule:a=s,tempPathOptions:c={platform:process.platform,env:process.env,pathModule:a,homeDirectory:(0,o.homedir)()}}){if(!e.hasRedirects)return!0;const l=e.redirects;if(0===l.length)return!1;const u=e.executableCommands.length>1,d=await Pk({parsingResult:e,workingDirectory:t,resolvePathForPermissions:i,pathModule:a}),h=hk();for(const e of l){if(wk(e))continue;const o=u?hk():h,{operator:s,targetText:l}=e,f=e.destinationFds;if(">&"===s){const e=gk(l),t=void 0===e?void 0:o.fdTargets.get(e);if("original-stdout"!==(p=t)&&"original-stderr"!==p&&"dev-null"!==p&&"workspace-file"!==p&&"tmp-file"!==p){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}for(const e of f)o.fdTargets.set(e,t);continue}if("<&"===s){const e=gk(l),t=void 0===e?void 0:o.fdTargets.get(e);if("dev-null"!==t){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}for(const e of f)o.fdTargets.set(e,t);continue}if("/dev/null"===l){for(const e of f)o.fdTargets.set(e,"dev-null");continue}if(!fk(s)||void 0===l||"word"===e.targetNodeType&&!yk(l,a)){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}const m=await Rk({targetText:l,workingDirectory:t,workingDirectories:d,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:i,pathModule:a,tempPathOptions:c});if(!m){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}for(const e of f)o.fdTargets.set(e,m)}var p;return!0}({parsingResult:e,workingDirectory:t,rootDirectories:this.rootDirectories,allowTmpRedirects:r}),l=await Tk({parsingResult:e,workingDirectory:t,rootDirectories:this.rootDirectories,allowTmpRedirects:r}),u=!function({parsingResult:e,hasRedirects:t,parsingFailed:r,allRedirectsAreAllowlistSafe:n,allRedirectsAreWorkspaceFileSafe:o}){return!(!t||r||n||o)&&(0===e.redirects.length||e.redirects.some(mk))}({parsingResult:e,hasRedirects:n,parsingFailed:i,allRedirectsAreAllowlistSafe:a,allRedirectsAreWorkspaceFileSafe:c})&&l;return{allowlistOfferSafe:(!n||a||c)&&l&&!i,redirectsAllowlistSafe:u}}async cmdIsAllowedByAllowlist(e,t){return!!t.redirectsAllowlistSafe&&(!!await this.isInShellAllowlist(e)||t.applyTeamAllowlist&&void 0!==t.autoRunControls&&this.isInTeamAllowlist(t.autoRunControls,e))}buildShellApprovalDecisionFacts({commands:e,softDenylistedCommands:t,autoRunControls:r,shouldApplyTeamShellAllowlist:n,deleteProtectionEnabled:o}){const s=e.filter((e=>"denied"===e.state)),i=e.filter((e=>"approvable"===e.state)),a=n&&r?.enabled?e.filter((e=>!this.isInTeamAllowlist(r,e))):[],c=s.filter((e=>void 0!==r&&this.isInTeamBlocklist(r,e))),l=o?s.filter((e=>"rm"===e.command.name)):[];return{hasSecurityDenies:s.length>0,hasSoftDenies:t.length>0,hasTeamAllowlistMisses:a.length>0,allCommandsRunnable:e.every((e=>e.isRunnable())),allCommandsAllowlisted:e.every((e=>"allowlisted"===e.state)),allCommandsPreapproved:e.every((e=>"preapproved"===e.state)),canAllowlistInPrompt:0===s.length&&0===a.length,unapprovedCommands:i,deniedCommands:s,notInTeamAllowlist:a,teamBlocklistedCommands:c,rmDeniedByDeleteProtection:l}}getShellAutoApprovalPolicy({approvalMode:e,isUnrestricted:t,requestedPolicy:r,facts:n,preserveRequestedPolicyForAllowlistedCommands:o}){if(!n.hasSecurityDenies&&!n.hasSoftDenies&&n.allCommandsRunnable){if(t)return"workspace_readonly"===r.type?r:{type:"insecure_none"};if("allowlist"===e)return n.allCommandsAllowlisted&&!o&&"workspace_readonly"!==r.type?{type:"insecure_none",allowlistEscalated:!0}:r}}async getPermissions(){return await this.permissionsProvider.getPermissions()}hasLocalShellControls(e){return e.allow.some((e=>this.isShellEntry(e)))||e.deny.some((e=>this.isShellEntry(e)))||(e.smartAllowlistDenylist?.length??0)>0}hasTeamShellControls(e,t=!0){return void 0!==e&&(t&&(e.enabled||e.allowed.length>0)||e.blocked.length>0)}async shouldPromptForEmptyPlainShellAllowlist(e,t){if("allowlist"!==t.approvalMode||"insecure_none"!==t.userConfiguredPolicy.type||0===e.trim().length||this.hasLocalShellControls(t))return!1;const[r,n]=await Promise.all([this.teamSettingsService.getAutoRunControls(),this.teamSettingsService.getDeleteFileProtection()]);return!this.hasTeamShellControls(r,!t.dashboardTerminalAllowlistOverriddenByPermissionsFile)&&!n}async requestApprovalForEmptyShellAllowlist(e,t,r){const n=await this.getEmptyShellAllowlistCandidates(t);t.onApprovalRequested?.();const o=await this.pendingDecisionStore.requestApproval({type:Lw.Shell,toolCallId:t.toolCallId,details:{command:e,workingDirectory:t.workingDirectory,timeout:t.timeout,reason:Nk(t.smartModeApprovalReason??"Shell allowlist is empty",await this.adminNetworkLimitReason(r)),isSandboxAvailable:!1,isSandboxEnabled:!1,canAllowlist:n.length>0,notAllowedCommands:n,smartModeApprovalReason:t.smartModeApprovalReason,smartModeApprovalRequestId:t.smartModeApprovalRequestId}});return o.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(r)}:{kind:"block",reason:{type:"userRejected",reason:o.reason}}}async getEmptyShellAllowlistCandidates(e){const t=e.parsingResult;return t.parsingFailed||0===t.executableCommands.length||t.hasRedirects&&!0!==t.allRedirectsAreDevNull||!await Tk({parsingResult:t,workingDirectory:e.workingDirectory,rootDirectories:this.rootDirectories,allowTmpRedirects:!0})?[]:this.generateAllowlistPatterns(t.executableCommands.map(WS))}async getAdminCommandDenylistBlock(e,t){const r=(await this.teamSettingsService.getAdminCommandDenylist()).rules;if(0===r.length)return;const n=bs({matchForms:t.parsingResult?gs({command:t.command,parsingResult:t.parsingResult}):[t.command],blockedCommands:r});return void 0!==n?(ek.info(e,"Admin command denylist hard-blocked shell at execution time",{toolCallId:t.toolCallId,parsingFailed:t.parsingResult?.parsingFailed??!0,parserCommandCount:t.parsingResult?.executableCommands.length??0}),{type:"adminCommandDenylist",pattern:n}):void 0}async hasHardDeny(e,t){const r=await this.getPermissions();return t.some((e=>r.deny.some((t=>this.isShellEntry(t)&&[...e.wrapperForms,...e.matchForms].some((e=>this.matchesShell(t,e)))))))}isShellEntry(e){return null!==Bk(e)}isPathEntry(e,t){return new RegExp(`^\\s*${e}\\s*\\(`).test(t)}matchesShell(e,t){const r=Bk(e);if(!r)return!1;const n=t.trim(),o=this.extractBaseCommand(n);if(null!==r.argsPattern){const e=n.includes(" ")?n.slice(n.indexOf(" ")+1).trim():"",t=this.matchGlob(r.commandPattern,o)||this.matchGlob(r.commandPattern,n),s=this.matchGlob(r.argsPattern,e);if(t&&s)return!0}return!!this.matchGlob(r.fullPattern,n)||!!n.startsWith(`${r.fullPattern} `)||!!this.matchGlob(r.fullPattern,o)||o===r.fullPattern}async checkCursorFileProtection(e){if(!e.some((e=>".cursor"===e.toLowerCase()||".vscode"===e.toLowerCase())))return null;const t=e[e.length-1]?.toLowerCase()??"";return t.endsWith(".md")||t.endsWith(".mdc")||".cursorrules"===t?null:await this.teamSettingsService.getDotCursorProtection()?{type:"permissionsConfig"}:null}extractBaseCommand(e){const t=e.trim(),r=t.indexOf(" ");return-1===r?t:t.substring(0,r)}generateAllowlistPatterns(e){const t=[],r=["git","npm","yarn","pnpm","docker","pip","systemctl","uv","cargo","bun","npx"];for(const{command:n,allowlistable:o}of e)o&&!Hb(n.name)&&(r.includes(n.name)&&n.args.length>0&&"word"===n.args[0].type?t.push(`${n.name} ${n.args[0].value}`):t.push(n.name));return[...new Set(t)]}pathEntryRawPattern(e,t){const r=t.match(function(e){return"Read"===e?Yk:e_}(e));if(r)return(r[1]??"").trim()}compileReadDenyMatcher(e){try{const t=this.pathEntryRawPattern("Read",e);if(void 0===t)return()=>!1;const r=(0,ms.b)((0,Yo.jl)(t));return e=>r(e)}catch(e){return()=>{throw e}}}matchesPathEntry(e,t,r){const n=this.pathEntryRawPattern(e,t);return void 0!==n&&this.matchGlob((0,Yo.jl)(n),r)}async isPathExplicitlyDenied(e,t){return(await this.getPermissions()).deny.some((r=>this.isPathEntry(e,r)&&this.matchesPathEntry(e,r,t)))}async isPathExplicitlyAllowed(e,t){return(await this.getPermissions()).allow.some((r=>this.isPathEntry(e,r)&&this.matchesPathEntry(e,r,t)))}matchGlob(e,t){return(0,ms.T)(e,t)}async addToAllowList(e,t,r){const n=`${t}(${r})`;await this.permissionsProvider.updatePermissions((e=>{const t=e.allow.includes(n)?e.allow:[...e.allow,n];return{...e,allow:t}}))}async addToDenyList(e,t,r){const n=`${t}(${r})`;await this.permissionsProvider.updatePermissions((e=>{const t=e.deny.includes(n)?e.deny:[...e.deny,n];return{...e,deny:t}}))}async shouldBlockMcp(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{QS(o,(0,$.VI)(e.withName("InteractivePermissionsService.shouldBlockMcp")),!1);const{name:s,toolName:i,providerIdentifier:a,args:c}=t,l=function(e,t){if(void 0!==t)return t;const r=e;return void 0!==r.annotations?r.annotations:Mb(r.annotationsJson)}(t,r?.annotations),u=e=>{this.mcpAllowlistLog?.(e)};if(u(`[permissions-service] shouldBlockMcp: toolName="${i}", providerIdentifier="${a}"`),await this.isComputerUseDisabledByAdminFor(a))return u(`[permissions-service] shouldBlockMcp: BLOCKED (Computer Use off for team) toolName="${i}", providerIdentifier="${a}"`),{type:"unsafeResolution",message:"Computer Use is turned off by your team admin. Ask the user to do it instead."};const d=await this.mcpAdminToolLimitRefusal(e,{resolvedTool:n?.resolvedTool,toolName:i});if(void 0!==d)return u(`[permissions-service] shouldBlockMcp: BLOCKED (team tool limit) toolName="${i}", providerIdentifier="${a}"`),{type:"unsafeResolution",message:d};const h=await this.computerUseDecision(t,r);if(await this.isMcpExplicitlyDenied(e,a,i))return u(`[permissions-service] shouldBlockMcp: BLOCKED (explicitly denied) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig"};const p=await this.getPermissions(),f="workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode;if(!0===n?.alreadyApproved&&!f&&"block"!==h.kind&&"askEachCall"!==h.kind)return!1;const m=await this.teamSettingsService.getMcpToolControls(),g=!0===m?.enabled&&!(void 0!==n?.client&&!0===await(this.teamSettingsService.isHostMcpBridgeClient?.(n.client))),w=g&&"block"!==h.kind?{kind:"notComputerUse"}:h,y=void 0!==t.smartModeApproval?.reason&&f,v=Qk({server:Xk(a),tool:i});let b,S,k;switch(w.kind){case"block":return u(`[permissions-service] shouldBlockMcp: BLOCKED (Computer Use app) toolName="${i}", providerIdentifier="${a}"`),{type:"unsafeResolution",message:w.message};case"noAccess":if(!f&&!await this.teamSettingsService.getShouldBlockMcp())return u(`[permissions-service] shouldBlockMcp: ALLOWED (Computer Use no access) toolName="${i}", providerIdentifier="${a}"`),!1;b=v,k=!0;break;case"app":if(!y&&(this.computerUseAppsAllowedForSession.includes(w.entry)||await this.isComputerUseAppSaved(w.entry)))return u(`[permissions-service] shouldBlockMcp: ALLOWED (Computer Use app grant) toolName="${i}", providerIdentifier="${a}"`),!1;b=w.entry,S=w.app,k=!1;break;case"askEachCall":b=void 0,S=w.app&&{...w.app,allowOnce:!0},k=!1;break;case"notComputerUse":b=v,k=!0}const _=k||void 0!==b,C=t.smartModeApproval?.reason;if(void 0!==C)return"workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode?(u(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode, Smart Mode forced approval) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig",isReadonly:!0}):(u(`[permissions-service] shouldBlockMcp: needsApproval (Smart Mode) toolName="${i}", providerIdentifier="${a}"`),!(g?this.isMcpInTeamAllowlist(m,{providerIdentifier:a,toolName:i,annotations:l}):k&&await this.isMcpExplicitlyAllowed(e,a,i))&&!("unrestricted"===p.approvalMode&&!await this.teamSettingsService.getShouldBlockMcp())&&{type:"needsApproval",approvalReason:C,approvalDetails:{type:"mcp",name:s,toolName:i,...ck(r,l),providerIdentifier:a,args:c,reason:"smartMode",canAllowlist:_&&!this.isComputerUseServer(a),smartModeApprovalReason:C,smartModeApprovalRequestId:t.smartModeApproval?.requestId,allowlistEntry:b,computerUseApp:S}});if(g){const t=this.isMcpInTeamAllowlist(m,{providerIdentifier:a,toolName:i,annotations:l});if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"team",outcome:t?"pass":"fail"}),t)return u(`[permissions-service] shouldBlockMcp: ALLOWED (in admin MCP allowlist) toolName="${i}", providerIdentifier="${a}"`),!1}else if(k){const t=await this.isMcpExplicitlyAllowed(e,a,i);if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"user",outcome:t?"pass":"fail"}),t)return u(`[permissions-service] shouldBlockMcp: ALLOWED (explicitly in allowlist) toolName="${i}", providerIdentifier="${a}"`),!1}if("workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode)return u(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig",isReadonly:!0};if("unrestricted"===p.approvalMode){if(!await this.teamSettingsService.getShouldBlockMcp())return u(`[permissions-service] shouldBlockMcp: ALLOWED (auto-run, no team block) toolName="${i}", providerIdentifier="${a}"`),!1;u(`[permissions-service] shouldBlockMcp: needsApproval (auto-run but team blocks MCP) toolName="${i}", providerIdentifier="${a}"`)}return u(`[permissions-service] shouldBlockMcp: needsApproval (not in allowlist) toolName="${i}", providerIdentifier="${a}", approvalMode="${p.approvalMode}"`),{type:"needsApproval",approvalReason:`MCP tool: ${i}`,approvalDetails:{type:"mcp",name:s,toolName:i,...ck(r,l),providerIdentifier:a,args:c,canAllowlist:_,allowlistEntry:b,computerUseApp:S}}}catch(e){o.error=e,o.hasError=!0}finally{YS(o)}}async mcpAdminToolLimitRefusal(e,{resolvedTool:t,toolName:r}){if(void 0===t||void 0===this.enforceMcpAdminToolLimits)return;if(!await this.enforcesMcpAdminToolLimits())return void(void 0!==this.onMcpAdminToolLimitCheck&&this.judgeMcpAdminToolLimit(t,r).then((e=>this.reportMcpAdminToolLimitCheck("shadow",e)),(()=>{})));const n=await this.judgeMcpAdminToolLimit(t,r);this.reportMcpAdminToolLimitCheck("enforce",n);const o=n?.outcome;switch(o){case void 0:case"within_limit":return;case"outside_limit":return rk.increment(e,1,{reason:"outside_limit"}),"Your team's admin limits this MCP tool";case"settings_unavailable":if(!0===n?.ranWithoutLimit)return;return rk.increment(e,1,{reason:"settings_unavailable"}),"Your team's MCP settings could not be read, so this MCP tool can't run right now";case"unknown_server":return rk.increment(e,1,{reason:"unknown_server"}),nk;default:return o}}async judgeMcpAdminToolLimit(e,t){if("unresolved"===e)return{outcome:"unknown_server"};const r=await(this.teamSettingsService.getMcpAdminToolLimit?.(e.client));if(void 0!==r)switch(r.kind){case"none":return;case"settings_unavailable":return{outcome:"settings_unavailable",...void 0===r.failure?{}:{settingsFailure:r.failure},...!0===r.noLimitApplies?{ranWithoutLimit:!0}:{}};case"unknown_server":return{outcome:"unknown_server"};case"limit":return{outcome:jb(r.policy,{name:t,annotations:e.annotations})?"within_limit":"outside_limit"};default:return r}}reportMcpAdminToolLimitCheck(e,t){if(void 0!==t)try{this.onMcpAdminToolLimitCheck?.({mode:e,...t})}catch{}}async enforcesMcpAdminToolLimits(){if(void 0===this.enforceMcpAdminToolLimits)return!1;try{return await this.enforceMcpAdminToolLimits()}catch{return!1}}async computerUseDecision(e,t){const r=this.computerUse;if(void 0===r||!this.isComputerUseServer(e.providerIdentifier))return{kind:"notComputerUse"};const n=await r.isOwnServer(Xk(e.serverIdentifier||e.providerIdentifier),t);if(!1===n)return{kind:"notComputerUse"};const o=await async function(e,t){const r=sS(e.meta?.["cursor/computerUseScope"])??sS(t.toolScopes?.[e.toolName]);if(void 0===r)return{kind:"screen"};let n;if(void 0!==r.appSelectorArgs){const t=Object.entries(r.appSelectorArgs).flatMap((([t,r])=>oS(t)&&void 0!==r&&void 0!==e.args[r]&&null!==e.args[r]?[{selector:t,value:e.args[r]}]:[]));if(0===t.length){const t=new Intl.ListFormat("en",{type:"disjunction"}).format(Object.values(r.appSelectorArgs).filter((e=>void 0!==e)));return{kind:"noAppSelector",message:`${e.toolName} needs exactly one of ${t} to name the app. Call it again with one of them.`}}const o=t.filter((({selector:e,value:t})=>function(e,t){return"pid"===e?"number"==typeof t&&Number.isInteger(t)||"string"==typeof t&&aS.test(t):"string"==typeof t&&t.length>0}(e,t)));if(1!==o.length){for(const{value:e}of t){const t="string"==typeof e?Yb(e.trim()):void 0;if(void 0!==t)return{kind:"app",app:t}}return{kind:"unknownApp"}}n=function(e,t){if("pid"===e){const e="string"==typeof t&&aS.test(t)?Number(t):t;return"number"==typeof e&&Number.isSafeInteger(e)&&e>0?{pid:e}:void 0}const r="string"==typeof t?t.trim():"";if(0!==r.length)return"bundleId"===e?{bundleId:r}:"path"===e?{path:r}:{appName:r}}(o[0].selector,o[0].value)}else{if(void 0===r.appArg)return r.capturesScreen?{kind:"screen"}:{kind:"none"};{const t=e.args[r.appArg];if(null==t||function(e){return"object"==typeof e&&null!==e&&"screen"===e.scope}(t))return{kind:"screen"};n=function(e){if("string"==typeof e){const t=e.trim();return t.length>0?{name:t}:void 0}if("object"!=typeof e||null===e)return;const{scope:t,pid:r}=e;return"app"===t&&"number"==typeof r&&Number.isInteger(r)&&r>0?{pid:r}:void 0}(t)}}if(void 0===n)return{kind:"unknownApp"};const o=function(e){return"pid"in e?void 0:"name"in e?e.name:"bundleId"in e?e.bundleId:"path"in e?e.path:e.appName}(n),s=await t.describeApp(n)??(void 0===o?void 0:Yb(o));return void 0===s?{kind:"unknownApp"}:{kind:"app",app:s}}({toolName:e.toolName,args:Object.fromEntries(Object.entries(e.args).map((([e,t])=>[e,t.toJson()]))),meta:t?._meta},r);if(void 0===n&&"app"!==o.kind)return{kind:"askEachCall"};switch(o.kind){case"none":return{kind:"noAccess"};case"screen":return{kind:"notComputerUse"};case"unknownApp":return{kind:"askEachCall"};case"noAppSelector":return{kind:"block",message:o.message};case"app":{const e=function(e){const t=e.toLowerCase();return Zb(t)?"Computer Use doesn't control Cursor itself, including its approval cards. Ask the user to do it instead.":Xb.some((e=>e.bundleId===t))?"Computer Use doesn't control apps that run scripts, such as Script Editor, Automator and Shortcuts. Ask the user to do it instead.":Qb.some((e=>e.bundleId===t))?"Computer Use doesn't control terminal apps. Use your shell tool to run commands instead.":void 0}(o.app.bundleId);if(void 0!==e)return{kind:"block",message:e};if(void 0===n)return{kind:"askEachCall"};const t=tS(o.app.bundleId)?void 0:Qk({server:r.serverId,tool:rS(o.app.bundleId)});return void 0===t?{kind:"askEachCall",app:o.app}:{kind:"app",app:o.app,entry:t}}}throw new Error("unreachable computer-use subject")}isComputerUseServer(e){const t=Xk(e);return!0===this.computerUse?.providerIdentifiers.has(t)}async isComputerUseDisabledByAdminFor(e){const t=this.computerUseAdminPolicy;return t?.providerIdentifiers.has(Xk(e))?await t.isDisabledByAdmin():!!this.isComputerUseServer(e)&&!0===await(this.teamSettingsService.isComputerUseDisabledByAdmin?.())}allowComputerUseAppForSession({bundleId:e}){const t=void 0===this.computerUse||tS(e)?void 0:Qk({server:this.computerUse.serverId,tool:rS(e)});void 0!==t&&this.computerUseAppsAllowedForSession.push(t)}async isMcpFullyAllowlisted(e,t){const r=e.withName("InteractivePermissionsService.isMcpFullyAllowlisted"),{providerIdentifier:n,toolName:o}=t,s=t.annotations??Mb(t.annotationsJson);if(await this.isMcpExplicitlyDenied(r,n,o)||await this.isComputerUseDisabledByAdminFor(n))return!1;const i=await this.teamSettingsService.getMcpToolControls();return!0===i?.enabled?!!this.isMcpInTeamAllowlist(i,{providerIdentifier:n,toolName:o,annotations:s}):!this.isComputerUseServer(n)&&await this.isMcpExplicitlyAllowed(r,n,o)}async isWebFetchFullyAllowlisted(e,t){const r=await this.getPermissions();if("allowlist"!==r.approvalMode)return!1;let n;try{n=new URL(t.url)}catch{return!1}const o=n.hostname;return!r.deny.some((e=>this.matchesWebFetchEntry(e,o)))&&r.allow.some((e=>this.matchesWebFetchEntry(e,o)))}matchesAutoRunCommand(e,t){const r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^${r}(\\s|$)`).test(e.trim())}matchesMcpPattern({pattern:e,providerIdentifier:t,toolName:r,logLabel:n}){const o=e.indexOf(":");if(-1===o)return!1;const s=e.slice(0,o).trim().toLowerCase(),i=e.slice(o+1).trim().toLowerCase(),a=Xk(t).toLowerCase().trim(),c=r.toLowerCase().trim(),l="*"===s||this.matchGlob(s,a),u="*"===i||this.matchGlob(i,c),d=l&&u,h=`[permissions-service] ${n}: serverPattern="${s}", toolPattern="${i}", normalizedProviderIdentifier="${a}", normalizedToolName="${c}", serverMatches=${l}, toolMatches=${u}, result=${d}`;return this.mcpAllowlistLog?.(h),d}recordMcpAllowlistCheckResult(e,{allowlistScope:t,outcome:r}){tk.increment(e,1,{allowlist_scope:t,outcome:r})}matchesMcpEntry(e,t,r){const n=e.match(/^\s*Mcp\s*\((.*)\)\s*$/);if(!n)return!1;const o=n[1]?.trim()??"";return this.matchesMcpPattern({pattern:o,providerIdentifier:t,toolName:r,logLabel:"matchesMcpEntry"})}matchesWebFetchEntry(e,t){const r=e.match(/^\s*WebFetch\s*\((.*)\)\s*$/);return!!r&&Kv(t,r[1]?.trim()??"")}matchesMcpEntryBare({pattern:e,providerIdentifier:t,toolName:r}){return this.matchesMcpPattern({pattern:e,providerIdentifier:t,toolName:r,logLabel:"matchesMcpEntryBare"})}isMcpInTeamAllowlist(e,{providerIdentifier:t,toolName:r,annotations:n}){if(e.mcpToolAllowlist.some((e=>this.matchesMcpEntryBare({pattern:e,providerIdentifier:t,toolName:r}))))return!0;const o=this.findTeamMcpServerPolicy(e,t);return void 0!==o&&"reads"===o.mode&&jb(o,{name:r,annotations:n})}findTeamMcpServerPolicy(e,t){for(const r of e.serverPolicies??[])if(this.matchesMcpEntryBare({pattern:`${r.name}:*`,providerIdentifier:t,toolName:""}))return r.policy}async isMcpExplicitlyDenied(e,t,r){return(await this.getPermissions()).deny.some((e=>this.matchesMcpEntry(e,t,r)))}async isComputerUseAppSaved(e){return(await this.getPermissions()).allow.some((t=>t.match(/^\s*Mcp\s*\((.*)\)\s*$/)?.[1]?.trim().toLowerCase()===e))}async isMcpExplicitlyAllowed(e,t,r){return(await this.getPermissions()).allow.some((e=>this.matchesMcpEntry(e,t,r)))}}var r_=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const n_=65536,o_=1048576,s_=(0,l.h)("LocalReadExecutor"),i_=async(e,t,r,n)=>{const o=setTimeout((()=>{s_.warn(e,`[watchdog, LocalReadExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function a_(e){return BigInt(Math.min(e,4294967295))}async function c_(e,t){if(0===t)return(0,Co.readFile)(e);if(t>2147483647)throw new RangeError(`File size (${t}) is greater than 2 GiB`);const r=await(0,Co.open)(e,"r");try{const e=Buffer.allocUnsafe(t);let n=0;for(;n=32&&e<=126||9===e||10===e||13===e}function d_(e){if(e.length>=2){if(255===e[0]&&254===e[1])return"utf-16le";if(254===e[0]&&255===e[1])return"utf-16be"}const t=Math.min(4096,e.length);if(t<16)return"utf-8";let r=0,n=0;for(let o=0;o+1=8&&r>=4*Math.max(1,n)?"utf-16le":n>=8&&n>=4*Math.max(1,r)?"utf-16be":"utf-8"}const h_=Buffer.from("\n---\n");function p_(e,t){const r=e.length;if(r<2*h_.length)return r;if(10!==e[r-1]||45!==e[r-2]||45!==e[r-3]||45!==e[r-4]||10!==e[r-5])return r;const n=Math.max(t,r-4096),o=e.lastIndexOf(h_,r-h_.length-1);return-1===o||o126))return!1}const t=e.split("\n").filter((e=>e.length>0));if(t.length<2||t.length>3)return!1;const r=t[0],n=t[t.length-1];return!(!/^(exit_code: (?:-?\d+|unknown)|error: .+)$/.test(r)||!n.startsWith("ended_at: ")||3===t.length&&!/^elapsed_ms: \d+$/.test(t[1]))}(e.subarray(o+h_.length,r-4).toString("utf-8"))?o:r}const f_=[Buffer.from("%PDF-","ascii"),Buffer.from([208,207,17,224,161,177,26,225]),Buffer.from([80,75,3,4]),Buffer.from([80,75,5,6]),Buffer.from([80,75,7,8]),Buffer.from([127,69,76,70]),Buffer.from([254,237,250,206]),Buffer.from([254,237,250,207]),Buffer.from([206,250,237,254]),Buffer.from([207,250,237,254]),Buffer.from([77,90,144]),Buffer.from([0,97,115,109]),Buffer.from([137,80,78,71,13,10,26,10]),Buffer.from([255,216,255]),Buffer.from("GIF87a","ascii"),Buffer.from("GIF89a","ascii"),Buffer.from("SQLite format 3\0","ascii"),Buffer.from([31,139]),Buffer.from("BZh","ascii"),Buffer.from([253,55,122,88,90,0]),Buffer.from([40,181,47,253]),Buffer.from([55,122,188,175,39,28]),Buffer.from([82,97,114,33,26,7,0]),Buffer.from([82,97,114,33,26,7,1,0])];function m_(e){return new Ky.sV({result:{case:"invalidFile",value:new Ky.cW({path:e,reason:"File content is binary data, not text"})}})}function g_(e,t,r){if(void 0===r.offset&&void 0===r.limit)return{applied:!1};if(t)return{applied:!1};const n=r.offset??1,o=r.limit??(n<0?Math.abs(n):e),s=n<0?Math.max(0,e+n):Math.max(0,n-1);if(s>=e)return{applied:!1};const i=Math.min(e,s+o),a=w_(s,e),c=w_(i,e);return{applied:!0,start:a,end:Math.max(a,c)}}function w_(e,t){if(Number.isNaN(e)||0===e)return 0;if(e===Number.POSITIVE_INFINITY)return t;if(e===Number.NEGATIVE_INFINITY)return 0;const r=Math.trunc(e);return r<0?Math.max(t+r,0):Math.min(r,t)}function y_(e){return-1===e.indexOf("\r\n")?e:e.replaceAll("\r\n","\n")}function v_(e,t,r,n,o,s){if(n>=o)return{from:0,to:0};let i=0,a=0,c=0===n,l=0;for(;ia&&13===r(t)?t-1:t};l=t+1}return c?{from:a,to:t}:{from:t,to:t}}function b_(e,t,r){const n=v_((t=>e.indexOf("\n",t)),e.length,(t=>e.charCodeAt(t-1)),t,r,!1);return 0===n.from&&n.to===e.length?e:n.from>=n.to?"":e.slice(n.from,n.to)}function S_(e,t,r,n,o){if(t>=r)return{text:"",truncated:!1};const s=n>=0?n+3:-1;let i=t;if(n>=0&&i>=n&&i=r)return{text:"",truncated:!1};const a=function(e,t,r,n){if(r>=n)return n;if(r<=t)return t;const o=Math.max(t,r-3);let s=r;for(;s>o;){if(128!=(192&(e[s]??0)))return s;s--}return 192&~(e[s]??0)?r:s}(e,i,Math.min(r,i+3*(o+1)+3),r);let c=y_(function(e,t,r,n){if(t>=r)return"";if(n<0)return e.toString("utf8",t,r);const o=n+3;return r<=n||t>=o?e.toString("utf8",t,r):t>=n&&r<=o?"":(to?e.toString("utf8",Math.max(t,o),r):"")}(e,i,a,n));const l=c.length>o||ao&&(c=Vo(c,o)),{text:c,truncated:l}}function k_(e,t,r,n){if(t>=r)return{text:"",truncated:!1};const o=Math.min(r,t+2*n+1);let s=y_(e.slice(t,o));const i=s.length>n||on&&(s=Vo(s,n)),s.lengthn?{text:e.text+Vo(t,n),truncated:!0}:{text:e.text+t,truncated:e.truncated}}function C_(e,t){if(e.truncated)return e;const r=__(e,t);return{text:r.text,truncated:r.truncated}}function E_(e,t,r){let n=e;return t.forEach(((e,t)=>{const o=function(e,t){const{line:r,hasNewline:n}=e;return t&&n&&r.text.endsWith("\r")?{...r,text:r.text.slice(0,-1)}:r}(e,r);t>0&&(n=__(n,"\n")),n=__(n,o.text),o.truncated&&(n={text:n.text,truncated:!0})})),n}function x_(e){const t=e.toLowerCase();return"utf-8"===t?"utf8":"utf-8-bom"===t||"utf-8 bom"===t?"utf8bom":"latin-1"===t?"latin1":t}function P_(e){return void 0===e.maxChars||void 0!==e.offset||void 0!==e.limit?Gs:Math.min(Gs,e.maxChars+2)}function R_(e,t,r){if(!t||void 0===r.maxChars||e.length-1<=r.maxChars)return e;const n=e.charCodeAt(e.length-1);return n>=55296&&n<=56319?e.slice(0,-1):e}class I_ extends Error{constructor(){super("Invalid UTF-8 while streaming read"),this.name="InvalidUtf8Error"}}function T_(e){for(let t=1;t<=Math.min(3,e.length);t++){const r=e[e.length-t]??0;if(128!=(192&r))return A_(r)>t?t:0}return 0}function A_(e){return e>=240?4:e>=224?3:e>=192?2:1}class $_{constructor(e,t,r){this.previousEndsWithCr=e,this.carry=t,this.strict=r,this.lines=0,this.crlfCount=0,this.lfOnlyCount=0,this.continuesLine=t.length>0}count(e){this.strict&&this.validate(e),0===this.lines&&e.length>0&&10!==e[0]&&(this.continuesLine=!0);for(let t=e.indexOf(10);-1!==t;t=e.indexOf(10,t+1))(t>0?13===e[t-1]:this.previousEndsWithCr)?this.crlfCount++:this.lfOnlyCount++,this.lines++;e.length>0&&(this.previousEndsWithCr=13===e[e.length-1])}finish(){if(this.strict&&this.carry.length>0)throw new I_}validate(e){let t=e;if(this.carry.length>0){const r=A_(this.carry[0]??0)-this.carry.length;if(e.length0&&(0,n.isUtf8)(e.subarray(0,e.length-t))?"utf8_cut":"utf8_invalid"}(e)}async function O_(e,t){const r=t>0?Math.min(t,o_):o_,o=await c_(e,r);return o.length===t&&(0,n.isUtf8)(o)||ci(new zs.TextDecoder("utf-8",{fatal:!1}).decode(o,{stream:o.length===o_&&o.length!==t}))?{kind:"lossyUtf8",cacheEncoding:"utf8"}:{kind:"iconv",decoderEncoding:"latin1",cacheEncoding:"latin1"}}async function F_(e){const t=await(0,Co.stat)(e),r=await Hi(e);if(r.isBinaryFile)return;const n=M_({file:e,stats:t,format:r},void 0);if("iconv"===n.kind)return n.decoderEncoding;const o=await O_(e,t.size);return"iconv"===o.kind?o.decoderEncoding:void 0}async function N_(e,{file:t,stats:r},n,o,s){const i=r.size,a=void 0!==n.offset||void 0!==n.limit,c=(n.offset??1)<0,l=n.offset??1,u=Math.max(0,l-1),d=void 0===n.limit?void 0:u+n.limit,h=c?Math.abs(l):0,p=a?1/0:n.maxChars??1/0,f=a&&!c?n.maxChars??1/0:1/0;let m=[],g=0,w=!1,y=0,v=!1,b=!(c||a&&u<=0),S=!1;const k=[];let _,C=0,E=!1,x=0,P=!1,R=[],I=0,T=0,A=0,$=!1,M={text:"",truncated:!1},D=!1,O=!1,F=0,N=0,L=0,j=!1,U=!1;const B=e=>{let t=e;return!j&&t.length>0&&(j=!0,65279===t.charCodeAt(0)&&(U=!0,t=t.slice(1))),t},W=(e,t)=>t&&13===e.text.charCodeAt(e.text.length-1),H=()=>P||E&&C>=Gs,q=()=>v||w&&g>=Gs,z=(e,t)=>{if(H())return;const r=k.length>0?1:0;let n=Gs-C;if(r>0){if(n<=0)return void(E=!0);n--}const o=e.text.length>n?{line:{text:Vo(e.text,n),truncated:!0},hasNewline:t}:{line:e,hasNewline:t};k.push(o),C+=r+(o.line.truncated?n:o.line.text.length),e.truncated&&(E=!0),o.line.truncated&&(E=!0),W(o.line,t)&&x++,C-x>f&&(P=!0,_=F)},G=(e,t)=>{if(q())return;const r=m.length>0?1:0;let n=Gs-g;if(r>0){if(n<=0)return void(w=!0);n--}const o=e.text.length>n?{line:{text:Vo(e.text,n),truncated:!0},hasNewline:t}:{line:e,hasNewline:t};m.push(o),g+=r+(o.line.truncated?n:o.line.text.length),(e.truncated||o.line.truncated)&&(w=!0),W(o.line,t)&&y++,g-y>p&&(v=!0,_=F)},V=(e,t)=>{e&&(t?N++:L++),F++},K=()=>{const e=R[I];void 0!==e&&(A-=e.line.text.length+1),R[I]=void 0,I=(I+1)%R.length,T--},J=(e,t,r)=>{const n=F;if(0===n&&(S=0===e.text.length),!c&&a&&b&&n>=u&&(b=!1,m=[]),b&&G(e,t),c){if(h>0)for(T===h&&K(),(e=>{if(T===R.length){const e=new Array(Math.min(h,Math.max(16,2*R.length)));for(let t=0;t1&&A>Gs;)K(),$=!0}else a&&n>=u&&(void 0===d||n!(D||(!b||q())&&(!a||0!==F)&&!(c?h>0:!(!a||H())&&F>=u&&F<(d??1/0))),X=()=>{const e=M.text.length-1;if(a){const t=!c&&F>=u&&F<(d??1/0),r=k.length>0?1:0;if(!t||C-x+r+e<=f)return;z(M,!1)}else{const t=m.length>0?1:0;if(g-y+t+e<=p)return;G(M,!1)}M={text:"",truncated:!1},D=!0};let Q;const Y=e=>{if(void 0===n.maxChars||c)return;if(!(a?H()||F>=(d??1/0):q()))return;const t=e.subarray(e.length-T_(e));return Q=new $_(ee,Buffer.from(t),"strictUtf8"===o.kind),Q};let ee=!1;for await(const r of async function*(e,t,r,n,o){const s=function(e){return e>0?{start:0,end:e-1}:{}}(n);if("strictUtf8"===r.kind||"lossyUtf8"===r.kind){const n=new zs.TextDecoder("utf-8",{fatal:"strictUtf8"===r.kind,ignoreBOM:!0}),i=(0,xo.createReadStream)(t,{highWaterMark:n_,signal:e.signal,...s});let a;try{for await(const e of i){if(void 0!==a){a.count(e);continue}const t=n.decode(e,{stream:!0});t.length>0&&(yield t),e.length>=4&&(a=o?.(e))}if(void 0!==a)return void a.finish();const e=n.decode();e.length>0&&(yield e)}catch(e){if(e instanceof TypeError)throw new I_;throw e}return}const i=(0,xo.createReadStream)(t,{highWaterMark:n_,signal:e.signal,...s}).pipe(Vs.decodeStream(r.decoderEncoding));for await(const e of i)yield"string"==typeof e?e:String(e)}(e,t,o,i,Y)){const e=B(r);let t=0,n=e.indexOf("\n",t);for(;-1!==n;){const r=n>t?13===e.charCodeAt(n-1):ee;Z()?(M=C_(M,e.slice(t,n)),J(M,!0,r)):(D&&n>t&&(O=!0),V(!0,r)),M={text:"",truncated:!1},D=!1,ee=!1,t=n+1,n=e.indexOf("\n",t)}t0&&N/te*100>=5,ne="utf8"===o.cacheEncoding&&U?"utf8bom":o.cacheEncoding;s&&Yi(t,r,ne);const oe=Math.min(F,a?d??1/0:1/0),se=void 0!==_&&(O||oe>_+1),ie=(n.maxChars??1/0)+n_,ae=e=>e.text.length>ie?{text:Vo(e.text,ie),truncated:!0}:e,ce=()=>E_({text:"",truncated:w||se},m,re);if(!a){const e=ae(ce());return{content:e.text,totalLines:F,truncated:e.truncated,rangeApplied:!1}}if(F<=1&&S)return{content:"",totalLines:F,truncated:!1,rangeApplied:!1};if(c){const e=n.limit??h,t=[];for(let e=0;e=F){const e=ce();return{content:e.text,totalLines:F,truncated:e.truncated,rangeApplied:!1}}const le=ae(E_({text:"",truncated:E||se},k,re));return{content:le.text,totalLines:F,truncated:le.truncated,rangeApplied:!0}}class L_{constructor(e,t,r){this.permissionsService=e,this.workspacePath=t,this.terminalReads=new Zl,this.mcpStateAccessor=r?.mcpStateAccessor,this.useStreamingRead=r?.useStreamingRead,this.pendingDecisionProvider=r?.pendingDecisionProvider,this.encodingSlices=r?.encodingSlices}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,$.VI)(e.withName("LocalReadExecutor.execute")),!1);const o=t.path;if(""===o.trim())return new Ky.sV({result:{case:"error",value:new Ky.F_({path:o,error:es})}});const i=(0,Yo.o1)(o,this.workspacePath),a=await i_(e,"permissionsService.shouldBlockFileRead",3e3,(()=>Zk(this.permissionsService,i)));if(a){const r=await i_(e,"resolveFileReadBlock",3e3,(()=>async function(e,t){return await Qu(e,{onNeedsApproval:async(e,r)=>{const n=t.pendingDecisionProvider?.requestReadApproval?.bind(t.pendingDecisionProvider);if("fileRead"!==r.type||!n)return{kind:"denied",message:"Blocked by permissions configuration"};const o=await n({type:Lw.Read,details:{path:r.path,reason:e},toolCallId:t.toolCallId});return o.approved?null:{kind:"rejected",reason:o.reason}},onUserRejected:e=>({kind:"rejected",reason:e}),onPermissionDenied:e=>({kind:"denied",message:e})})??{kind:"proceed"}}(a,{pendingDecisionProvider:this.pendingDecisionProvider,toolCallId:t.toolCallId})));if("rejected"===r.kind)return new Ky.sV({result:{case:"rejected",value:new Ky.f4({path:i,reason:r.reason??""})}});if("denied"===r.kind)return new Ky.sV({result:{case:"permissionDenied",value:new Ky.lW({path:i})}})}void 0!==this.mcpStateAccessor&&qy(e,this.mcpStateAccessor,i);try{const r=await i_(e,"stat",3e3,(()=>(0,Co.stat)(i)));if(r.isDirectory())return new Ky.sV({result:{case:"invalidFile",value:new Ky.cW({path:i,reason:"Path is a directory, not a file"})}});if(!r.isFile())return new Ky.sV({result:{case:"invalidFile",value:new Ky.cW({path:i,reason:"Path is neither a file nor a directory"})}});const o=function(e){return null!==function(e){const t=nh(e,"terminals");if(!t||1!==t.remainingPath.length)return null;const r=t.remainingPath[0],n=/^(\d+)\.txt$/.exec(r);if(!n)return null;const o=Number.parseInt(n[1],10);return Number.isNaN(o)?null:{id:o}}(e)}(i),a=function(e){const t=nh(e,"agent-tools");return null!==t&&1===t.remainingPath.length&&t.remainingPath[0].endsWith(".txt")}(i);if(o||a)return await this.readTerminalFile(e,i,r,t,a&&!o);const c=await i_(e,"getFormatForFile",3e3,(()=>Hi(i))),l=c.isImageFile,u=function(e){return".pdf"===(0,s.extname)(e).toLowerCase()}(i),d=Ni(i);if(l){const t=await i_(e,"prepareImageForModel",3e3,(async()=>(async e=>{let t;try{t=await Lv(e)}catch(t){const r=await jv(e);if("undecodable"===r.kind)return r;throw t}if(!0===t.reencoded)return{kind:"image",image:t};const r=await jv(t.data);return"undecodable"===r.kind?r:{kind:"image",image:t}})(await(0,Co.readFile)(i))));return"undecodable"===t.kind?new Ky.sV({result:{case:"invalidFile",value:new Ky.cW({path:i,reason:(n=t.reason,`File is not a valid image: its data could not be decoded (${n}). A truncated or hand-copied file does this; write it again from the original bytes with code.`)})}}):new Ky.sV({result:{case:"success",value:new Ky.mE({path:i,output:{case:"data",value:t.image.data},totalLines:0,fileSize:a_(r.size),truncated:!1})}})}if(u){const t=await i_(e,"readPdfBinary",3e3,(()=>(0,Co.readFile)(i)));return new Ky.sV({result:{case:"success",value:new Ky.mE({path:i,output:{case:"data",value:t},totalLines:0,fileSize:a_(r.size),truncated:!1})}})}if(c.isBinaryFile&&d){if(void 0!==t.maxVideoBytes&&r.size>t.maxVideoBytes)return new Ky.sV({result:{case:"success",value:new Ky.mE({path:i,totalLines:0,fileSize:a_(r.size),truncated:!0})}});const n=await i_(e,"readBinaryFile",3e3,(()=>(0,Co.readFile)(i)));return new Ky.sV({result:{case:"success",value:new Ky.mE({path:i,output:{case:"data",value:n},totalLines:0,fileSize:a_(r.size),truncated:!1})}})}if(c.isBinaryFile)return m_(i);{const n=this.useStreamingRead,o=!n||await i_(e,"useStreamingRead",3e3,(()=>n()));if(o||r.size>Gs){const n=await i_(e,"readTextStreaming",7e3,(()=>async function(e,t,r,n){const o=M_(t,r.encodingHint);try{return{...await N_(e,t,r,o,n),decoder:o.kind}}catch(o){if(o instanceof I_){const o=await O_(t.file,t.stats.size);return{...await N_(e,t,r,o,n),decoder:o.kind}}throw o}}(e,{file:i,stats:r,format:c},t,o))),s=R_(n.content,n.truncated,t);return Ul(this.encodingSlices,e)&&this.recordStreamedRead(e,i,r.size,n,s),new Ky.sV({result:{case:"success",value:new Ky.mE({path:i,output:{case:"content",value:s},totalLines:n.totalLines,fileSize:a_(r.size),truncated:n.truncated,rangeApplied:n.rangeApplied})}})}const s=await i_(e,"readText",3e3,(()=>ji(i,t.encodingHint))),a=await i_(e,"countLines",3e3,(()=>Js(s))),l=function(e,t,r){const n=g_(t,""===e,r);return n.applied?n.start>=n.end?{content:"",rangeApplied:!0}:{content:b_(e,n.start,n.end),rangeApplied:!0}:{content:e,rangeApplied:!1}}(s,a,t);let u=l.content,d=!1;const h=P_(t);return u.length>h&&(u=R_(u.substring(0,h),!0,t),d=!0),u.length16777216)return"other_encoding";try{return r=await c_(e,t),!(0,n.isAscii)(r)&&(0,n.isUtf8)(r)?"utf8_as_other":"other_encoding"}catch{return"other_encoding"}var r}(t,r)),eu(this.encodingSlices,e,{layer:"exec_read",evidence:a,partial:o.rangeApplied||o.truncated},i)}catch{}}async readTerminalFile(e,t,r,n,o){const s=await i_(e,"readTerminalFile",3e3,(()=>c_(t,r.size)));if(o&&(i=s,f_.some((e=>function(e,t){return e.length>=t.length&&e.subarray(0,t.length).equals(t)}(i,e)))))return m_(t);var i;const a=function(e,t,r=8388608){if(0===e.length)return{content:"",totalLines:1,rangeApplied:!1,truncated:!1};const n=l_(e),o=p_(e,n);if("utf-8"!==d_(e.subarray(n,o)))return function(e,t,r){const n=0===e.length,o=function(e){let t=0,r=0;const n=e.length;for(;r=s.end)return{content:"",totalLines:o,rangeApplied:!0,truncated:!1};const i=v_((t=>e.indexOf("\n",t)),e.length,(t=>e.charCodeAt(t-1)),s.start,s.end,!0),a=k_(e,i.from,i.to,r);return{content:a.text,totalLines:o,rangeApplied:!0,truncated:a.truncated}}(function(e){const t=l_(e),r=t>0?e.subarray(0,t).toString("utf-8"):"",n=p_(e,t),o=nr?-1:239===e[t]&&187===e[t+1]&&191===e[t+2]?t:-1}(e,n,o);return function(e,t,r,n){const o=e.length-(t>=0?3:0)==0,s=function(e){let t=0,r=0;const n=e.length;for(;r=i.end)return{content:"",totalLines:s,rangeApplied:!0,truncated:!1};const a=v_((t=>e.indexOf(10,t)),e.length,(t=>e[t-1]??0),i.start,i.end,!0),c=S_(e,a.from,a.to,t,n);return{content:c.text,totalLines:s,rangeApplied:!0,truncated:c.truncated}}(e,s,t,r)}(s,n,P_(n)),c=R_(a.content,a.truncated,n);return Ul(this.encodingSlices,e)&&(o||this.terminalReads.firstRead(n.toolCallId,t))&&Yl(this.encodingSlices,e,{layer:o?"exec_read":"exec_terminal_context",evidence:D_(s),partial:a.rangeApplied||a.truncated},c),new Ky.sV({result:{case:"success",value:new Ky.mE({path:t,output:{case:"content",value:c},totalLines:a.totalLines,fileSize:a_(r.size),truncated:a.truncated,rangeApplied:a.rangeApplied})}})}}function j_(e){return Buffer.from(e,"utf16le").toString("utf16le")}var U_=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},B_=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function W_(e){return`Path '${e}' could not be verified while resolving symlinks. This can happen when access is denied or the path contains a symlink loop.`}function H_(e){return`Path '${e}' is neither a file nor a directory`}async function q_(e){const t=await(0,Co.stat)(e).catch((()=>{}));return void 0!==t&&!t.isFile()&&!t.isDirectory()}function z_(e,t,r){const n=function(e,t){let r;for(const n of t)(0,Yo.ZU)({basePath:n,targetPath:e})&&(void 0===r||n.length>r.length)&&(r=n);return r}((0,s.resolve)(e,t),r);return void 0===n||n===e}class G_ extends Error{}function V_(e){const t=new AbortController,r=setTimeout((()=>t.abort()),e);return{signal:t.signal,clear:()=>clearTimeout(r)}}function K_(e){switch(e.result.case){case"content":return e.result.value.matches.length>0;case"files":return e.result.value.files.length>0;case"count":return e.result.value.counts.length>0;case void 0:return!1;default:{const t=e.result;throw new Error(`Unknown grep result: ${String(t)}`)}}}function J_(e){switch(e){case"content":return new Ey.vD({result:{case:"content",value:new Ey.Zp({ripgrepTruncated:!0})}});case"files_with_matches":return new Ey.vD({result:{case:"files",value:new Ey.T7({ripgrepTruncated:!0})}});case"count":return new Ey.vD({result:{case:"count",value:new Ey.xA({ripgrepTruncated:!0})}});default:throw new Error(`Unknown output mode: ${String(e)}`)}}function Z_(e){return"success"===e.result.case&&Object.values(e.result.value.workspaceResults).some((e=>!0===e.result.value?.clientTruncated))}function X_(e,t,r){let n=Buffer.concat(e);t&&(n=n.subarray(0,n.lastIndexOf(10)+1)),r?.note(n);const o=n.toString("utf8");return o.includes("�")?{stdout:o,stdoutBytes:n}:{stdout:o}}function Q_(e){return/^(utf-?16|ucs-?2)/i.test(e)}const Y_=(0,l.h)("local-exec/grep"),eC=(0,u.Pu)("local_exec.grep.deadline_reached",{description:"Grep and Glob searches the search deadline stopped, by whether they kept what was found",labelNames:["output_mode","outcome","streaming"]}),tC=(0,u.Pu)("local_exec.grep.newest_first_stat_fallback",{description:"Grep and Glob results left in ripgrep's order because stat was too slow to sort them",labelNames:["output_mode"]}),rC=(0,u.v5)("local_exec.grep.rg.spawn_ms",{description:"Time to start the ripgrep process for one Grep or Glob search",labelNames:["sandboxed"]}),nC=(0,u.v5)("local_exec.grep.rg.search_ms",{description:"Time ripgrep took to search and exit after it started, for runs it finished",labelNames:["output_mode","sandboxed"]});function oC(e){return e instanceof Error&&e.message.includes("ENOENT")&&e.message.includes("spawn")}function sC(e){try{return(0,xo.existsSync)(e)}catch{return"check_failed"}}function iC(e){if("object"==typeof e&&null!==e&&"errno"in e){const t=e.errno;if("number"==typeof t)return t}}function aC(e,t){if("object"==typeof e&&null!==e)return"syscall"===t&&"syscall"in e&&"string"==typeof e.syscall?e.syscall:"path"===t&&"path"in e&&"string"==typeof e.path?e.path:void 0}function cC(e,t,r,n){return{...uC(e),...n,cwd:t,cwdExists:sC(t),errorMessage:kc(r),errorCode:Sc(r),errno:iC(r),syscall:aC(r,"syscall"),errorPath:aC(r,"path")}}function lC(e){return new Error(`Path does not exist: ${e}`)}function uC(e){const t={rgPath:e,platform:process.platform,arch:process.arch,pid:process.pid,uptimeSeconds:Math.round(process.uptime()),execPath:process.execPath};try{t.rgPathExists=(0,xo.existsSync)(e)}catch(e){t.rgPathExists=!1,t.rgPathExistsError=e instanceof Error?e.message:String(e)}try{const r=(0,xo.lstatSync)(e);t.rgIsSymlink=r.isSymbolicLink(),r.isSymbolicLink()&&!t.rgPathExists&&(t.rgBrokenSymlink=!0)}catch{t.rgLstatFailed=!0}const r=(0,s.dirname)(e);try{t.parentDirExists=(0,xo.existsSync)(r),t.parentDirExists&&(t.parentDirContents=(0,xo.readdirSync)(r).slice(0,50))}catch(e){t.parentDirError=e instanceof Error?e.message:String(e)}const n=(0,s.dirname)(r);try{t.grandparentDirExists=(0,xo.existsSync)(n),t.grandparentDirExists&&(t.grandparentDirContents=(0,xo.readdirSync)(n).slice(0,50))}catch(e){t.grandparentDirError=e instanceof Error?e.message:String(e)}if(t.rgPathExists)try{const r=(0,xo.statSync)(e);t.rgFileSize=r.size,t.rgFileMode=r.mode.toString(8),t.rgIsFile=r.isFile(),t.rgModifiedMs=r.mtimeMs}catch(e){t.rgStatError=e instanceof Error?e.message:String(e)}const o="node_modules.asar.unpacked";if(e.includes(o)){const r=e.split(o)[0];if(r){const n=r.concat("node_modules.asar");try{t.asarExists=(0,xo.existsSync)(n)}catch{t.asarExists="check_failed"}const i=r.concat(o);try{if(t.asarUnpackedDirExists=(0,xo.existsSync)(i),t.asarUnpackedDirExists){const r=(0,s.dirname)((0,s.dirname)(e));t.ripgrepPkgDirExists=(0,xo.existsSync)(r)}}catch{t.asarUnpackedDirExists="check_failed"}}}return t}class dC{constructor(e,t,r,n){this.ignoreService=e,this.grepProvider=t,this.workspacePath=r,this.stdoutDecodes=new WeakMap;const o=Array.isArray(this.workspacePath)?this.workspacePath[0]:this.workspacePath;this.singleWorkspacePath=Array.isArray(this.workspacePath)&&this.workspacePath.length>1?void 0:o,this.mcpStateAccessor=n?.mcpStateAccessor,this.permissionsService=n?.permissionsService,this.useStreamingGrep=n?.useStreamingGrep,this.encodingSlices=n?.encodingSlices}computeRelativeTarget(e,t){const r=(0,Yo.o1)(e,this.singleWorkspacePath??t);return r===t?".":(0,s.relative)(t,r)}isRootIndependentSearchPath(e){return(0,s.isAbsolute)(e)||/^~(?=$|[/\\])/.test(e)||e.startsWith("file://")}resolveSearchTargets(e,t){const r=this.isRootIndependentSearchPath(e);return t.map((t=>{const n=(0,s.resolve)(t);return{root:t,resolvedRoot:n,target:(0,Yo.o1)(e,r?void 0:n)}}))}findOutsideTargets(e,t){if(void 0===e||""===e)return;const r=this.resolveSearchTargets(e,t);return r.some((({resolvedRoot:e,target:t})=>(0,Yo.BJ)(t,e)))?void 0:[...new Set(r.map((({target:e})=>e)))]}searchTarget(e,t){if(!t.path)return".";const r=(0,Yo.o1)(t.path,this.singleWorkspacePath??e);return(0,Yo.BJ)(r,(0,s.resolve)(e))?this.computeRelativeTarget(t.path,e):r}sortsAfterRipgrep(e,t,r){return void 0===t.sort&&(r?!0!==t.sortAscending:(0,s.isAbsolute)(this.searchTarget(e,t)))}async buildArgs(e,t,r,n){const o=[],s=function(e,t){return"files_with_matches"===t&&""===e.pattern&&Boolean(e.glob)}(t,r),i=await pa(await this.ignoreService.listCursorIgnoreFilesByRoot(e));for(const e of i)o.push("--cursor-ignore",e);if("content"===r)o.push("--line-number","--with-filename","--no-heading","-0"),void 0!==t.contextBefore&&o.push("--before-context",String(t.contextBefore)),void 0!==t.contextAfter&&o.push("--after-context",String(t.contextAfter)),o.push("--max-columns",String(1e3),"--max-columns-preview"),void 0!==t.context&&void 0===t.contextBefore&&void 0===t.contextAfter&&o.push("--before-context",String(t.context),"--after-context",String(t.context));else if("files_with_matches"===r)o.push(s?"--files":"-l");else{if("count"!==r)throw new Error(`Unknown output mode: ${String(r)}`);o.push("-c","--with-filename")}!0===t.caseInsensitive?o.push("--ignore-case"):o.push("--case-sensitive"),t.type&&o.push("--type",t.type),t.glob&&(o.push("--iglob",t.glob),s&&o.push("--iglob","!**/.git")),t.multiline&&o.push("--multiline","--multiline-dotall");const a=n?"none":t.sort??"modified";if(n&&o.push("--line-buffered"),"none"!==a){const e=!0===t.sortAscending?"--sort":"--sortr";o.push(e,a)}o.push("--no-config","--color=never"),o.push("--hidden"),o.push("--follow");const c=this.searchTarget(e,t);if(t.path){const t=await async function(e){try{if(!(await(0,Co.stat)(e)).isFile())return;const{encoding:t}=await Hi(e);return Q_(t)?t.toLowerCase():void 0}catch{return}}((0,Yo.o1)(c,e));void 0!==t&&o.push("--encoding",t)}return s||o.push("--regexp",t.pattern),o.push("--"),o.push(c),o}async filterBlockedFiles(e,t){const r=new Map,n=await(this.permissionsService?.getFileReadBoundaryBlocker?.()),o=[];for(const s of e){const e=(0,Yo.o1)(s.file,t),i=await Cc(e);null===i||await this.isPostRipgrepBlocked(i,r)||void 0!==n&&await n(e,i)||o.push(s)}return o}async isPostRipgrepBlocked(e,t){const[r,n]=await Promise.all([this.ignoreService.isCursorIgnored(e,t),this.ignoreService.isRepoBlocked(e)]);return r||n}throwOnRipgrepFailure(e,t,r){if((""!==e.stderr||2===e.exitCode)&&""===e.stdout.trim()&&!function({stderr:e,target:t}){return e.trim().split(/\r?\n/).every((e=>{if(/^rg: .+: line \d+: /.test(e))return!0;const r=/^rg: (.+?): .*\(os error (?:13|5|2|1)\)$/.exec(e)?.[1]??/^rg: File system loop found: (.+) points to an ancestor /.exec(e)?.[1];return void 0!==r&&r!==t}))}({stderr:e.stderr,target:this.searchTarget(t,r)}))throw new Error(e.stderr||`ripgrep exited with code ${e.exitCode}`)}async orderNewestFirst(e,t,r,n,o){const s=await Vy(t,(e=>(0,Yo.o1)(n(e),r)));return s.statTimedOut&&(Y_.info(e,"newest_first.stat_timeout_fallback",{toolCallId:o.toolCallId,execId:o.execId,outputMode:o.outputMode,fileCount:t.length}),tC.increment(e,1,{output_mode:o.outputMode})),s.items}async keepNewestPage(e,t,r,n,o){return(await this.orderNewestFirst(e,t,r,n,o)).slice(0,dC.CLIENT_LIMIT_LINES)}async runFilesMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const d=U_(a,(0,$.VI)(e.withName("LocalGrepExecutor.runFilesMode")),!1),h=await this.buildArgs(t,r,"files_with_matches",n),p=await this.executeRg(d.ctx,t,h,void 0,o,s,i);this.throwOnRipgrepFailure(p,t,r);const f=(c=p.stdout,l=n?dC.HARD_MAX_OUTPUT_LINES:dC.CLIENT_LIMIT_LINES,u=dC.HARD_MAX_OUTPUT_LINES,function(e,t,r){const n=e.trim();if(""===n)return{files:[],totalFiles:0,clientTruncated:!1,ripgrepTruncated:!1};const o=new xy;let s=0,i=0,a=0;for(;Py(n,a,o);)a=o.nextStart,st?Buffer.from(n.slice(0,i)).toString():n,l=[];for(a=0;l.lengtht,ripgrepTruncated:s>=r}}(c,l,u)),m=f.totalFiles>dC.CLIENT_LIMIT_LINES;let g=f.files;n&&(g=await this.keepNewestPage(d.ctx,g,t,(e=>e),i),m&&(g=g.join("\0").split("\0")));const w=(await this.filterBlockedFiles(g.map((e=>({file:e}))),t)).map((({file:e})=>e)),y=g.length-w.length,v=new Ey.T7({files:w,totalFiles:Ay(f.totalFiles-y),clientTruncated:m,ripgrepTruncated:f.ripgrepTruncated||p.timedOut||p.stdoutByteCapped});return{result:new Ey.vD({result:{case:"files",value:v}}),timedOut:p.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{B_(a)}var c,l,u}async runCountMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const d=U_(a,(0,$.VI)(e.withName("LocalGrepExecutor.runCountMode")),!1),h=await this.buildArgs(t,r,"count",n),p=await this.executeRg(d.ctx,t,h,void 0,o,s,i);this.throwOnRipgrepFailure(p,t,r);const f=(c=p.stdout,l=n?dC.HARD_MAX_OUTPUT_LINES:dC.CLIENT_LIMIT_LINES,u=dC.HARD_MAX_OUTPUT_LINES,function(e,t,r){const n=e.trim();if(""===n)return{counts:[],totalFiles:0,totalMatches:0,clientTruncated:!1,ripgrepTruncated:!1};const o=[],s=new xy;let i=0;for(;Py(n,i,s);){const e=i,t=s.lineEnd;if(i=s.nextStart,t===e)continue;const r=n.lastIndexOf(":",t-1);if(rt,ripgrepTruncated:a>=r}}(c,l,u)),m=n?await this.keepNewestPage(d.ctx,f.counts,t,(e=>e.file),i):f.counts,g=await this.filterBlockedFiles(m,t),w=g.reduce(((e,t)=>e+t.count),0),y=m.length-g.length,v=m.reduce(((e,t)=>e+t.count),0)-w,b=new Ey.xA({counts:g.map((e=>new Ey.sS({file:e.file,count:Ay(e.count)}))),totalFiles:Ay(f.totalFiles-y),totalMatches:Ay(f.totalMatches-v),clientTruncated:f.totalFiles>dC.CLIENT_LIMIT_LINES,ripgrepTruncated:f.ripgrepTruncated||p.timedOut||p.stdoutByteCapped});return{result:new Ey.vD({result:{case:"count",value:b}}),timedOut:p.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{B_(a)}var c,l,u}async runContentMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const c=U_(a,(0,$.VI)(e.withName("LocalGrepExecutor.runContentMode")),!1),l=await this.buildArgs(t,r,"content",n),u=void 0!==r.context||void 0!==r.contextBefore||void 0!==r.contextAfter,d=dC.CLIENT_LIMIT_LINES*(u?2:1),h=await this.executeRg(c.ctx,t,l,d,o,s,i);this.throwOnRipgrepFailure(h,t,r);const p=await this.decodeLinesAsRead(c.ctx,h,t,i),{byFile:f,totalLines:m,totalMatchedLines:g,clientTruncated:w,ripgrepTruncated:y}=function(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{return U_(o,(0,$.VI)(n.withName("parseContentOutput")),!1),function(e,t,r){const n={byFile:new Map,totalLines:0,totalMatchedLines:0,totalFiles:0,clientTruncated:!1,ripgrepTruncated:!1};if(""===e.trim())return n;const o=new Map,s=new Set,i=new xy;let a=0,c=0,l=0,u=0;for(;Py(e,u,i);){const r=u,n=i.lineEnd;if(u=i.nextStart,l++,d=e,n-(h=r)==2&&45===d.charCodeAt(h)&&45===d.charCodeAt(h+1))continue;let p=-1;for(let t=r;t=n)continue;let m=0,g=0;for(;f57)break;m=10*m+(t-48),g++,f++}if(0===g||f>=n||!Number.isFinite(m))continue;const w=e.charCodeAt(f);if(58!==w&&45!==w)continue;const y=45===w;y||a++;const v=e.slice(r,p);if(s.has(v)||s.add(v),c>=t)continue;const b=e.slice(f+1,n);let S=o.get(v);void 0===S&&(S={file:v,matches:[]},o.set(v,S)),S.matches.push({lineNumber:m,content:b,isContextLine:y}),c++}var d,h;return{byFile:o,totalLines:Ay(l),totalMatchedLines:Ay(a),totalFiles:Ay(s.size),clientTruncated:c>=t,ripgrepTruncated:l>=r}}(e,t,r)}catch(e){o.error=e,o.hasError=!0}finally{B_(o)}}(p,dC.CLIENT_LIMIT_LINES,d,c.ctx),v=Array.from(f.values()),b=await this.filterBlockedFiles(v,t),S=v.filter((e=>!b.includes(e))),k=S.reduce(((e,t)=>e+t.matches.length),0),_=S.reduce(((e,t)=>e+t.matches.filter((e=>!e.isContextLine)).length),0),C=n?await this.orderNewestFirst(c.ctx,b,t,(e=>e.file),i):b,E=new Ey.Zp({matches:C.map((e=>new Ey.uI({file:e.file,matches:e.matches.map((e=>new Ey.dx({lineNumber:e.lineNumber,content:e.content,isContextLine:e.isContextLine})))}))),totalLines:Ay(m-k),totalMatchedLines:Ay(g-_),clientTruncated:w,ripgrepTruncated:y||h.timedOut||h.stdoutByteCapped});return{result:new Ey.vD({result:{case:"content",value:E}}),timedOut:h.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{B_(a)}}async decodeLinesAsRead(e,t,r,o){const s={stack:[],error:void 0,hasError:!1};try{const i=t.stdoutBytes;if(void 0===i)return t.stdout;const a=U_(s,(0,$.VI)(e.withName("LocalGrepExecutor.decodeLinesAsRead")),!1),c=function(e,t){const r=[],o=new xy;let s=0,i=0,a=e.indexOf("�");for(;-1!==a&&Py(e,s,o);){const{lineEnd:c,nextStart:l}=o,u=t.indexOf(10,i),d=-1===u?t.length:u+1;let h=-1===u?t.length:u;if(h>i&&-1!==u&&13===t[h-1]&&h--,ae.file)))],u=new Map,d=performance.now()+dC.LINE_ENCODING_TIMEOUT_MS;let h=0;for(;h{let d=!1,h=!1;const p=()=>{h||(h=!0,a.span.end())};if(e.signal.aborted)return p(),void u(new Error("Grep was cancelled"));if(o.aborted)return p(),void u(dC.ripgrepTimeoutError());let f;const m="insecure_none"===s.type?"false":"true",g=performance.now();let w=g;try{const e=s;f=(0,Oo.spawnInSandbox)((0,Oo.Ko)(),r,{cwd:t},e),w=performance.now(),0}catch(r){if(p(),oC(r)){const n=(0,Oo.Ko)();if(Y_.error(e,"rg_diagnostics.spawn_throw",void 0,cC(n,t,r,i)),!1===sC(t))return u(lC(t))}return u(r)}const y=[],v=[];let b=0,S=0,k=0,_=!1,C=!1,E=!1;const x=()=>{if(!d)try{p(),E=!0;const e=X_(y,!0,this.stdoutDecodes.get(i));""===e.stdout?u(dC.ripgrepTimeoutError()):l({...e,stderr:"",exitCode:0,timedOut:!0,stdoutByteCapped:C}),f.kill()}catch{}};o.addEventListener("abort",x,{once:!0});const P=()=>{o.removeEventListener("abort",x),p(),u(new Error("Grep was cancelled"));try{f.kill()}catch{}};e.signal.addEventListener("abort",P,{once:!0}),f.stdout?.on("data",(e=>{if(!C&&!_)if(b+=e.length,b>c){C=!0;try{f.kill()}catch{}}else if(void 0!==n){let t=-1,r=0;for(let o=0;o=n)){t=o+1,_=!0;try{f.kill()}catch{}break}k+=r;const o=t>=0?e.subarray(0,t):e;y.push(o)}else y.push(e)})),f.stderr?.on("data",(e=>{S+=e.length,S<=c&&v.push(e)})),f.on("error",(r=>{if(o.removeEventListener("abort",x),e.signal.removeEventListener("abort",P),p(),oC(r)){const n=(0,Oo.Ko)();if(Y_.error(e,"rg_diagnostics.spawn_enoent",void 0,cC(n,t,r,i)),!1===sC(t))return void u(lC(t))}u(r)})),f.on("close",(t=>{const r=performance.now()-w;d=!0,o.removeEventListener("abort",x),e.signal.removeEventListener("abort",P);const n=X_(y,C,E?void 0:this.stdoutDecodes.get(i)),s=Buffer.concat(v).toString("utf8");p(),l({...n,stderr:s,exitCode:t??0,timedOut:!1,stdoutByteCapped:C}),rC.histogram(e,w-g,{sandboxed:m}),C||_||o.aborted||e.signal.aborted||0!==t&&1!==t||nC.histogram(e,r,{output_mode:i.outputMode,sandboxed:m})}))}))}async checkOutsideTarget(e,t){if(1!==t.length||void 0===t[0])return{error:`Path '${e}' points to a different folder from each workspace root; use an absolute path`};const r=await Cc(t[0]);return null===r?{error:W_(e)}:await this.ignoreService.isCursorIgnored(r)?{error:`Path '${e}' is filtered out by .cursorignore`}:await q_(t[0])?{error:H_(e)}:{resolvedTarget:r}}async execute(e,t,r){if(!Ul(this.encodingSlices,e))return this.search(e,t,r,void 0);const n=new tu,o=await this.search(e,t,r,n);return"success"===o.result.case&&Yl(this.encodingSlices,e,{layer:"exec_grep",evidence:n.evidence(),partial:Z_(o)},o),o}async search(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{const a=U_(o,(0,$.VI)(e.withName("LocalGrepExecutor.execute")),!1),c=Array.isArray(this.workspacePath)?this.workspacePath:[this.workspacePath??process.cwd()],l=t.outputMode??"content";if("content"!==(i=l)&&"files_with_matches"!==i&&"count"!==i)throw new Error(`Unknown output mode: ${l}`);const u=l,d={toolCallId:t.toolCallId,execId:r?.execId,outputMode:u,targetPath:t.path,workspacePaths:c};void 0!==n&&this.stdoutDecodes.set(d,n);const h=ls(t.sandboxPolicy),p=this.grepProvider.getWorktreeGuardInfo?.(c);if((0,Yo.fl)({targetPath:t.path,workspacePaths:c,mainWorktreePath:p?.mainWorktreePath}))return new Ey.Ud({result:{case:"error",value:new Ey.ts({error:Yo.PS})}});const f=this.findOutsideTargets(t.path,c);let m=t,g=c;try{if(t.path&&void 0!==f){const r=await this.checkOutsideTarget(t.path,f);if("error"in r)return new Ey.Ud({result:{case:"error",value:new Ey.ts({error:r.error})}});void 0!==this.mcpStateAccessor&&qy(e,this.mcpStateAccessor,r.resolvedTarget),g=c.slice(0,1),m=t.clone(),m.path=f[0]}else if(m.path){const t=[];let r=!1;for(const{root:n,resolvedRoot:o,target:s}of this.resolveSearchTargets(m.path,c)){if(!(0,Yo.BJ)(s,o))continue;const i=await Cc(s);if(null!==i)if(await this.ignoreService.isCursorIgnored(i))r=!0;else{if(await q_(s))return new Ey.Ud({result:{case:"error",value:new Ey.ts({error:H_(m.path)})}});t.push(n),void 0!==this.mcpStateAccessor&&qy(e,this.mcpStateAccessor,i)}}if(0===t.length){const e=r?`Path '${m.path}' is filtered out by .cursorignore`:W_(m.path);return new Ey.Ud({result:{case:"error",value:new Ey.ts({error:e})}})}g=t}let r={};const n=void 0===f?await this.executeIndexedGrepWithTimeout(a.ctx,g,m,d):void 0;if(void 0!==n){r=n;for(const[e,t]of Object.entries(r)){const r=t.result;switch(r.case){case"content":r.value.matches=await this.filterBlockedFiles(r.value.matches,e);break;case"files":r.value.files=(await this.filterBlockedFiles(r.value.files.map((e=>({file:e}))),e)).map((({file:e})=>e));break;case"count":r.value.counts=await this.filterBlockedFiles(r.value.counts,e)}}}else{const e=await this.streamingEnabled(a.ctx,d),t=e?V_(dC.MAIN_TIMEOUT_MS):void 0;let n=0,o=!1;try{for(const s of g){if(!0===t?.signal.aborted){r[s]=J_(u),n++,o=!0;continue}if(!1===sC(s))return new Ey.Ud({result:{case:"error",value:new Ey.ts({error:`Path does not exist: ${s}`})}});const i=t??V_(dC.MAIN_TIMEOUT_MS);try{const t=await this.runMode(a.ctx,u,s,m,e,i.signal,h,d);r[s]=t.result,t.timedOut&&n++}catch(t){if(!(t instanceof G_))throw t;if(r[s]=J_(u),n++,o=!0,!e)break}finally{i!==t&&i.clear()}}}finally{t?.clear()}if(n>0){const t=o&&(!e||!Object.values(r).some(K_));if(this.reportDeadlineReached(a.ctx,d,{streaming:e,folderCount:g.length,stoppedFolderCount:n,outcome:t?"failed":"partial"}),t)throw dC.ripgrepTimeoutError()}}const o=function(e,t){if(t.length<=1)return e;const r=[...new Set(t.map((e=>(0,s.resolve)(e))))],n={};for(const[t,o]of Object.entries(e)){const e=(0,s.resolve)(t),i=t=>z_(e,t,r),a=o.result;switch(a.case){case"content":{const e=a.value,r=[];let o=0,s=0;for(const t of e.matches)i(t.file)?r.push(t):(o+=t.matches.length,s+=t.matches.filter((e=>!e.isContextLine)).length);const c=e.clone();c.matches=r,c.totalLines=Math.max(0,e.totalLines-o),c.totalMatchedLines=Math.max(0,e.totalMatchedLines-s),n[t]=new Ey.vD({result:{case:"content",value:c}});break}case"files":{const e=a.value,r=e.files.filter((e=>i(e))),o=e.clone();o.files=r,o.totalFiles=Math.max(0,e.totalFiles-(e.files.length-r.length)),n[t]=new Ey.vD({result:{case:"files",value:o}});break}case"count":{const e=a.value,r=[];let o=0;for(const t of e.counts)i(t.file)?r.push(t):o+=t.count;const s=e.clone();s.counts=r,s.totalFiles=Math.max(0,e.totalFiles-(e.counts.length-r.length)),s.totalMatches=Math.max(0,e.totalMatches-o),n[t]=new Ey.vD({result:{case:"count",value:s}});break}default:n[t]=o}}return n}(r,g),i=new Ey._0({pattern:m.pattern,path:void 0!==m.path&&this.isRootIndependentSearchPath(m.path)?(0,Yo.o1)(m.path):m.path,outputMode:u,workspaceResults:o});return new Ey.Ud({result:{case:"success",value:i}})}catch(e){if(m.path){const e=(0,Yo.o1)(m.path,this.singleWorkspacePath);try{await(0,Co.stat)(e)}catch(t){return new Ey.Ud({result:{case:"error",value:new Ey.ts({error:`Path does not exist: ${e}`})}})}}return new Ey.Ud({result:{case:"error",value:new Ey.ts({error:e instanceof Error?e.message:String(e)})}})}}catch(e){o.error=e,o.hasError=!0}finally{B_(o)}var i}}dC.MAIN_TIMEOUT_MS=25e3,dC.INDEXED_GREP_TIMEOUT_MS=25e3,dC.INDEXED_GREP_CONTEXT_TIMEOUT_MS=dC.INDEXED_GREP_TIMEOUT_MS+100,dC.HARD_MAX_OUTPUT_LINES=1e4,dC.CLIENT_LIMIT_LINES=2e3,dC.LINE_ENCODING_TIMEOUT_MS=2e3,je.object({record_v:je.number().int().nullish(),pid:je.number().int().nonnegative().nullish(),version:je.string().nullish(),started_at:je.number().nullish(),control_sock:je.string().nullish(),runtime_dir:je.string().nullish(),data_dir:je.string().nullish(),config_path:je.string().nullish(),log_path:je.string().nullish(),metrics_addr:je.string().nullish(),exe:je.string().nullish()}),je.object({mountpoint:je.string().nullish(),capabilities:je.array(je.string()).nullish(),nfs_transport:je.string().nullish(),bind_ignored:je.object({active:je.array(je.string()).nullish()}).passthrough().nullish()});const hC=je.object({daemon_alive:je.boolean().nullish(),mounts:je.array(je.unknown()).nullish(),data_plane:je.object({enabled:je.boolean().nullish()}).passthrough().nullish()});je.object({daemon_alive:je.boolean().nullish(),daemon_version:je.string().nullish(),capabilities:je.array(je.string()).nullish()}),hC.extend({memory:je.object({anon_bytes:je.number()}).nullish().catch(null)});const pC=je.number().int().nonnegative(),fC=je.object({line_no:je.number().int().positive(),kind:je.enum(["match","before","after"]),text:je.string().optional(),bytes:je.string().regex(/^(?:[0-9a-fA-F]{2})*$/).optional(),truncated:je.boolean().default(!1)}).refine((e=>void 0!==e.text||void 0!==e.bytes));je.object({type:je.literal("file"),path:je.string(),lines:je.array(fC)}),je.object({type:je.literal("summary"),files_searched:pC,more:je.boolean(),stop_reason:je.string().nullable(),skipped:je.object({over_size:pC,size_unknown:pC,budget_exhausted:pC,fetch_failed:pC,unreadable:pC})}),je.object({type:je.string()}),(0,l.h)("local-exec/grove-grep"),(0,u.Pu)("local_exec.grep.grove",{description:"Grep searches Grove served, or declined to ripgrep, by decline reason",labelNames:["outcome","reason"]}),(0,u.v5)("local_exec.grep.grove.served_ms",{description:"Time Grove took to answer a Grep search it served"});var mC=r("../proto/dist/generated/agent/v1/ls_exec_pb.js"),gC=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},wC=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class yC{constructor(e,t,r){this.permissionsService=e,this.ignoreService=t,this.workspacePath=r}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{gC(r,(0,$.VI)(e.withName("LocalLsExecutor.execute")),!1).ctx;const n=(0,Yo.o1)(t.path,this.workspacePath);try{let r;try{r=await(0,Co.stat)(n)}catch(e){return"ENOENT"===Sc(e)?function(e){const t=nh(e,"terminals");return null!==t&&0===t.remainingPath.length}(n)?new mC.fv({result:{case:"error",value:new mC.uj({path:n,error:"No active terminals."})}}):new mC.fv({result:{case:"error",value:new mC.uj({path:n,error:`Path does not exist: ${n}`})}}):new mC.fv({result:{case:"error",value:new mC.uj({path:n,error:kc(e)})}})}if(!r.isDirectory())return new mC.fv({result:{case:"error",value:new mC.uj({path:n,error:`Path is not a directory: ${n}`})}});const o=ls(t.sandboxPolicy),s=t.timeoutMs??5e3,i=e.withTimeout(s),{tree:a,didTimeout:c}=await this.getDirectoryTree(i,n,t.ignore,o);return c?new mC.fv({result:{case:"timeout",value:new mC.ze({directoryTreeRoot:a})}}):new mC.fv({result:{case:"success",value:new mC.PC({directoryTreeRoot:a})}})}catch(e){return new mC.fv({result:{case:"error",value:new mC.uj({path:n,error:e instanceof Error?e.message:"Unknown error occurred"})}})}}catch(e){r.error=e,r.hasError=!0}finally{wC(r)}}async getDirectoryTree(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{return gC(o,(0,$.VI)(e.withName("LocalLsExecutor.getDirectoryTree")),!1),await this.buildTreeFromRipgrepStream(e,t,r,n,2500)}catch(e){o.error=e,o.hasError=!0}finally{wC(o)}}async buildTreeFromRipgrepStream(e,t,r,n,o){const i={stack:[],error:void 0,hasError:!1};try{gC(i,(0,$.VI)(e.withName("LocalLsExecutor.buildTreeFromRipgrepStream")),!1);const a=(0,s.resolve)(t),c=new mC.vq({absPath:a,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!0,fullSubtreeExtensionCounts:{}}),l=new Map;l.set(a,c);const u={charactersUsed:a.length,budgetExceeded:!1},[d,h]=await Promise.all([this.ignoreService.listCursorIgnoreFilesByRoot(t),this.ignoreService.getRepoBlockExcludeGlobs(t)]),p=[...r,...h],{lines:f,didTimeout:m}=ga(e,{root:t,excludeGlobs:p,caseSensitive:!0,cursorIgnoreFiles:d,sandboxPolicy:n,source:"ls"});for await(const e of f){if(!e)continue;const r=(0,s.resolve)(t,e),n=await Cc(r);null===n||await this.ignoreService.isCursorIgnored(n)||await this.ignoreService.isRepoBlocked(n)||this.addPathToTree(r,a,l,u,o)}return this.sortTreeChildren(c),{tree:c,didTimeout:await m}}catch(e){i.error=e,i.hasError=!0}finally{wC(i)}}addPathToTree(e,t,r,n,o){const i=(0,s.basename)(e),a=(0,s.dirname)(e);this.ensureDirectoryPath(a,t,r,n.budgetExceeded);const c=r.get(a);if(!c)return;const l=i.length;if(!n.budgetExceeded&&n.charactersUsed+l<=o){const e=new mC.ur({name:i});c.childrenFiles.push(e),n.charactersUsed+=l}else{if(!n.budgetExceeded){n.budgetExceeded=!0;let e=a;for(;e.startsWith(t);){const t=r.get(e);t&&(t.childrenWereProcessed=!1);const n=(0,s.dirname)(e);if(n===e)break;e=n}}let o=n.overflowChain;if(n.overflowDir!==a||void 0===o){o=[];let e=a;for(;e.startsWith(t);){const t=r.get(e);t&&o.push(t);const n=(0,s.dirname)(e);if(n===e)break;e=n}n.overflowDir=a,n.overflowChain=o}const i=(0,s.extname)(e);for(const e of o)e.fullSubtreeExtensionCounts[i]??=0,e.fullSubtreeExtensionCounts[i]=Ay(e.fullSubtreeExtensionCounts[i]+1),e.numFiles??=0,e.numFiles=Ay(e.numFiles+1)}}ensureDirectoryPath(e,t,r,n){if(r.has(e)||e===t)return;const o=(0,s.dirname)(e);o!==e&&o.startsWith(t)&&this.ensureDirectoryPath(o,t,r,n);const i=new mC.vq({absPath:e,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!n,fullSubtreeExtensionCounts:{}});r.set(e,i);const a=r.get(o);a&&a.childrenDirs.push(i)}sortTreeChildren(e){e.childrenDirs.sort(((e,t)=>(0,s.basename)(e.absPath).localeCompare((0,s.basename)(t.absPath)))),e.childrenFiles.sort(((e,t)=>e.name.localeCompare(t.name)));for(const t of e.childrenDirs)this.sortTreeChildren(t)}}class vC extends Error{constructor(e,t){super(`Tool ${e} not found, available tools: ${t.join(", ")}`),this.toolName=e,this.availableTools=t,this.name="McpToolNotFoundError"}}function bC(e){if(e instanceof vC)return!0;if(!(e instanceof Error)||"McpToolNotFoundError"!==e.name)return!1;const t=e;return"string"==typeof t.toolName&&Array.isArray(t.availableTools)}function SC(e){return!0===e.url?.startsWith("mcp-provider://")}function kC(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function _C(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function CC(e,t){return(t??[]).some((t=>{const r=kC(t.command),n=_C(t.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==e.command&&(0,Ob.mD)(r,e.command),s=void 0===n||void 0!==e.url&&(0,Ob.eA)(n,e.url);return o&&s}))}function EC(e,t){if(SC(e))return!1;const r=t?.rules??[];if(0===r.length)return!1;if(CC(e,r))return!0;const n=function(e){return e.flatMap((e=>{if(void 0===e.serverUrl)return[];const t=function(e){if(e.includes("*"))return e;const t=e.search(/[?#]/);return-1===t?e:e.slice(0,t)}(e.serverUrl);return t===e.serverUrl?[]:[{...e,serverUrl:t}]}))}(r);return n.length>0&&CC(e,n)}function xC(e,t){const{command:r,url:n}=e;return void 0!==r&&t.commandPatterns.some((e=>(0,Ob.mD)(e.trim(),r)))||void 0!==n&&t.serverUrlPatterns.some((e=>(0,Ob.eA)(e.trim(),n)))}var PC=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class RC extends Error{constructor(e){super(`MCP server "${e}" is disabled`),this.name="McpServerDisabledError"}}class IC extends Error{constructor(e){super(`MCP server "${e}" has not been approved`),this.serverName=e,this.name="McpServerNotApprovedError"}}class TC extends Error{constructor(e,t){super(`MCP server "${e}" is overridden by ${t}`),this.serverName=e,this.overridingConfigPath=t,this.name="McpServerOverriddenError"}}class AC{constructor(e){this.disabledService=e}async load(e,t,r,n,o){if(await this.disabledService.isServerDisabled(t))throw new RC(t);return await o(e,r)}}class $C{constructor(e){this.approvalService=e}async load(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{if(function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(s,(0,$.VI)(e.withName("ServerApprovalMiddleware.load")),!1),!await this.approvalService.isServerApproved(t,r,n))throw new IC(t);return await o(e,r)}catch(e){s.error=e,s.hasError=!0}finally{PC(s)}}}class MC{constructor(e,t){this.approvalsPath=e,this.cwd=t,this.approvalsPromise=this.loadApprovals()}async isServerApproved(e,t,r){const n=function(e,t,r){const n={path:r,server:t};return`${e}-${(0,bo.createHash)("sha256").update(JSON.stringify(n)).digest("hex").substring(0,16)}`}(e,t,this.cwd);return(await this.getApprovals()).includes(n)}async loadApprovals(){try{const e=await(0,Co.readFile)(this.approvalsPath,"utf8"),t=JSON.parse(e);return Array.isArray(t)?t:(await this.saveApprovalsToFile([]),[])}catch(e){if(e instanceof Error&&e.message.includes("ENOENT"))return[];throw e}}async getApprovals(){return this.approvalsPromise}async addApproval(e){const t=await this.approvalsPromise;t.includes(e)||(t.push(e),await this.saveApprovals(t))}async addApprovals(e){const t=await this.approvalsPromise,r=e.filter((e=>!t.includes(e)));r.length>0&&(t.push(...r),await this.saveApprovals(t))}async removeApproval(e){const t=await this.approvalsPromise,r=t.filter((t=>t!==e));r.length!==t.length&&await this.saveApprovals(r)}async clearApprovals(e){const t=await this.approvalsPromise,r=e?t.filter((t=>!e(t))):[];r.length!==t.length&&await this.saveApprovals(r)}async saveApprovalsToFile(e){await(0,Co.mkdir)(s.default.dirname(this.approvalsPath),{recursive:!0}),await(0,Co.writeFile)(this.approvalsPath,JSON.stringify(e,null,2))}async saveApprovals(e){await this.saveApprovalsToFile(e),this.approvalsPromise=Promise.resolve(e)}}const DC=["https://api.cursor.com","https://api2.cursor.sh"],OC=["CURSOR_API_BASE_URL","CURSOR_BACKEND_URL"],FC=/^MCP server ".+" is blocked by \S/u;function NC(e){if(void 0!==e&&""!==e)try{return new URL(e).origin}catch{return}}function LC(e,t=process.env){if(void 0===e)return!1;let r;try{r=new URL(e)}catch{return!1}if("/v1/agent/mcp"!==r.pathname.replace(/\/+$/,"")&&!r.pathname.startsWith("/internal/agent-serve/agent-sdk-mcp-relay/"))return!1;const n=new Set(DC);for(const e of OC){const r=NC(t[e]);void 0!==r&&n.add(r)}return n.has(r.origin)}function jC(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function UC(e,t){if("string"!=typeof e)return;const r=e.trim();return""===r||r.length>t||/\p{Cc}/u.test(r)?void 0:r}function BC(e){if(!Array.isArray(e))return;const t=[];for(const r of e.slice(0,200)){const e=UC(r,200);void 0!==e&&t.push(e)}return t}function WC(e,t){const r=t.slice(0,20).join(", "),n=t.length-20;return n>0?` ${e}: ${r}, and ${n} more.`:` ${e}: ${r}.`}var HC=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},qC=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class zC{async load(e,t,r,n,o){const s=o(e,r);return new VC(e,t,s,r)}}function GC(e){let t;return e.then((e=>{t=e})).catch((()=>{})),t}class VC{constructor(e,t,r,n){this.serverName=t,this.clientPromise=r,this.config=n,this.clientPromiseTraceId=(0,$.fU)(e)?.spanContext()?.traceId,this.toolsPromise=this.clientPromise.then((async t=>null===t?[]:await t.getTools(e))),this.resourcesPromise=this.clientPromise.then((async t=>null===t?[]:(await t.listResources(e)).resources)),this.promptsPromise=this.clientPromise.then((async t=>null===t?[]:await t.listPrompts(e))),this.toolsPromise.catch((()=>{})),this.resourcesPromise.catch((()=>{})),this.promptsPromise.catch((()=>{}))}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=HC(t,(0,$.VI)(e.withName("CachedMcpClient.getTools")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=GC(this.toolsPromise);return void 0!==n?n:await this.toolsPromise}catch(e){t.error=e,t.hasError=!0}finally{qC(t)}}async callTool(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{const i=HC(s,(0,$.VI)(e.withName("CachedMcpClient.callTool")),!1),a=await this.getClient(i.ctx);if(null===a)throw new Error("Client is not ready");return a.callTool(i.ctx,t,r,n,o)}catch(e){s.error=e,s.hasError=!0}finally{qC(s)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=HC(t,(0,$.VI)(e.withName("CachedMcpClient.getInstructions")),!1),n=await this.getClient(r.ctx);if(null===n)return;return await n.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{qC(t)}}async getClient(e){const t={stack:[],error:void 0,hasError:!1};try{const r=HC(t,(0,$.VI)(e.withName("CachedMcpClient.getClient")),!1);return r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined"),await this.clientPromise}catch(e){t.error=e,t.hasError=!0}finally{qC(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{const r=HC(t,(0,$.VI)(e.withName("CachedMcpClient.listResources")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=GC(this.resourcesPromise);return void 0!==n?{resources:n}:{resources:await this.resourcesPromise}}catch(e){t.error=e,t.hasError=!0}finally{qC(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=HC(r,(0,$.VI)(e.withName("CachedMcpClient.readResource")),!1),o=await this.getClient(n.ctx);return null===o?{contents:[]}:o.readResource(n.ctx,t)}catch(e){r.error=e,r.hasError=!0}finally{qC(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{const r=HC(t,(0,$.VI)(e.withName("CachedMcpClient.listPrompts")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=GC(this.promptsPromise);return void 0!==n?n:await this.promptsPromise}catch(e){t.error=e,t.hasError=!0}finally{qC(t)}}async getPrompt(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=HC(n,(0,$.VI)(e.withName("CachedMcpClient.getPrompt")),!1),s=await this.getClient(o.ctx);return null===s?{messages:[]}:s.getPrompt(o.ctx,t,r)}catch(e){n.error=e,n.hasError=!0}finally{qC(n)}}async getState(e){const t={stack:[],error:void 0,hasError:!1};try{const r=HC(t,(0,$.VI)(e.withName("CachedMcpClient.getState")),!1);r.span.setAttribute("serverName",this.serverName);const n=await this.getClient(r.ctx);if(null===n)throw new Error("Client is not ready");return await n.getState(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{qC(t)}}async getAllowlistInUse(){try{await this.toolsPromise;const e=await this.clientPromise;return await(e?.getAllowlistInUse?.())}catch{return}}async getAllowlistRefusal(){if(void 0!==this.config&&"url"in this.config&&LC(this.config.url))try{return void await this.toolsPromise}catch(e){return function(e){const t=e instanceof Error?e.message:"string"==typeof e?e:void 0;if(void 0===t)return;const r=t.indexOf("{");if(-1===r)return;let n;try{n=JSON.parse(t.slice(r))}catch{return}if(!jC(n))return;const o=UC(n.error,700);return void 0!==o&&FC.test(o)?o:void 0}(e)}}async close(){try{const e=await this.clientPromise;await(e?.close?.())}catch{}}}function KC(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function JC(e,t){if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e||"bigint"==typeof e)return String(e);if(null==e)return t;try{const r=JSON.stringify(e);return"string"==typeof r?r:t}catch{return t}}function ZC(e){return e?` (${JC(e,"")})`:""}function XC(e){if(null===e||"string"==typeof e||"boolean"==typeof e)return e;if("number"==typeof e)return Number.isFinite(e)?e:void 0;if(Array.isArray(e)){const t=[];for(const r of e){if(void 0===r){t.push(null);continue}const e=XC(r);if(void 0===e)return;t.push(e)}return t}if("object"!=typeof e)return;const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&null!==t)return;const r={};for(const[t,n]of Object.entries(e)){if(void 0===n)continue;const e=XC(n);if(void 0===e)return;r[t]=e}return r}function QC(e){const t=XC(e);if(null!=t&&"object"==typeof t&&!Array.isArray(t))return t}const YC=new TextDecoder("utf-8",{fatal:!0});function eE(e){return"string"==typeof e?e.split(";")[0]?.trim().toLowerCase()??"":""}function tE(e,t){const r=Buffer.from(t,"base64"),n=function(e){try{const t=YC.decode(e);return t.includes("\0")?void 0:t}catch{return}}(r)??(function(e){const t=eE(e);return t.startsWith("text/")||"application/xml"===t||t.endsWith("+xml")}(e.mimeType)?r.toString("utf8").replace(/^\uFEFF/,""):void 0);if(void 0!==n)return{text:n,binary:!1};const o="string"==typeof e.mimeType&&e.mimeType.length>0?e.mimeType:"unknown type";return{text:`[Binary resource: ${JC(e.uri,"unknown")} (${o}, ${r.byteLength} bytes). The file is not text, so its contents are not included.]`,binary:!0}}const rE=new Set(["image/png","image/jpeg","image/jpg","image/gif","image/webp"]);function nE(e){return"string"==typeof e.text&&e.text.length>0?e.text:void 0}function oE(e){if(!KC(e))return;const t=e.resource;return KC(t)&&void 0===nE(t)&&"string"==typeof t.blob&&rE.has(eE(t.mimeType))?t.blob:void 0}function sE(e){const t=e,r=t.resource;if(KC(r)){const e=nE(r);return void 0!==e?e:"string"==typeof r.blob?tE(r,r.blob).text:`Resource: ${JC(r.uri,"unknown")}${ZC(r.name)}`}return t.uri?`Resource: ${JC(t.uri,"unknown")}${ZC(t.name)}`:`Unsupported content type "${e.type}": ${JSON.stringify(e)}`}function iE(e){const t=QC(e);if(void 0!==t&&0!==Object.keys(t).length)try{return Buffer.byteLength(JSON.stringify(t))<=262144?t:void 0}catch{return}}var aE=r("zod/v4-mini");const cE=aE.object({CLIENT_ID:aE.string(),CLIENT_SECRET:aE.optional(aE.string()),scopes:aE.optional(aE.array(aE.string()))}),lE=aE.strictObject({caBundle:aE.string().check(aE.trim(),aE.minLength(1),aE.maxLength(131072))}),uE=aE.object({type:aE.optional(aE.literal("stdio")),command:aE.string(),args:aE.optional(aE.array(aE.string())),env:aE.optional(aE.record(aE.string(),aE.string())),envFile:aE.optional(aE.string()),cwd:aE.optional(aE.string()),enabledTools:aE.optional(aE.array(aE.string())),startupTimeoutSec:aE.catch(aE.optional(aE.number().check(aE.positive())),void 0)}),dE=aE.object({type:aE.optional(aE.enum(["http","sse"])),url:aE.string(),headers:aE.optional(aE.record(aE.string(),aE.string())),auth:aE.optional(cE),tls:aE.optional(lE),placement:aE.optional(aE.enum(["server","client"])),enabledTools:aE.optional(aE.array(aE.string()))}),hE=aE.union([uE,dE]),pE=aE.object({mcpServers:aE.record(aE.string(),hE)});Error;const fE=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g;function mE(e,t){if("string"==typeof e)return function(e,t){return e.replace(fE,((e,r,n,o)=>{if(void 0!==r){const n=t(r);return void 0!==n?n:e}if(void 0===n)return e;const s=t(n);return void 0!==s?s:void 0!==o?o:e}))}(e,t);if(Array.isArray(e))return e.map((e=>mE(e,t)));if(null!==e&&"object"==typeof e){const r={};for(const[n,o]of Object.entries(e))r[n]=mE(o,t);return r}return e}r("../../node_modules/.pnpm/smol-toml@1.9.0/node_modules/smol-toml/dist/index.js");Symbol("invalid");function gE(e){const t=Object.entries(e);return{jsonKeyOf:new Map(t.map((([e,t])=>[t,e]))),tomlKeyOf:new Map(t)}}const wE=gE({CLIENT_ID:"client_id",CLIENT_SECRET:"client_secret",scopes:"scopes"}),yE=gE({caBundle:"ca_bundle"}),vE=gE({type:"type",command:"command",args:"args",env:"env",envFile:"env_file",cwd:"cwd",enabledTools:"enabled_tools",startupTimeoutSec:"startup_timeout_sec"}),bE=gE({type:"type",url:"url",headers:"http_headers",auth:"auth",tls:"tls",placement:"placement",enabledTools:"enabled_tools"}),SE=(new Map([["auth",{keys:wE,unknownKeyIsError:!1}],["tls",{keys:yE,unknownKeyIsError:!0}]]),"enabled");new Set([...vE.jsonKeyOf.keys(),...bE.jsonKeyOf.keys(),SE]);Symbol("disabled");const kE=(0,l.h)("McpConfig");async function _E(e,t=e=>process.env[e]){try{const r=await(0,Co.readFile)(e,"utf8"),n=mE((0,Cp.qg)(r),t);return pE.parse(n)}catch{return{mcpServers:{}}}}async function CE(e,t=e=>process.env[e]){const r={config:{mcpServers:{}},diagnostics:[]};return r}async function EE(e,t=e=>process.env[e]){const{config:r,diagnostics:n}=await CE(0,t);return n.length>0&&kE.warn((0,y.q6)(),"[mcp config] problems in MCP config; `agent mcp list` shows them",{errorCount:n.filter((e=>"error"===e.severity)).length,warningCount:n.filter((e=>"warning"===e.severity)).length,fileNames:[...new Set(n.map((e=>s.default.basename(e.file))))]}),r}const xE=["enterprise","project","user","env"];function PE(e){return"project"===e||"env"===e}const RE=["0.0.0.0/0","::/0"];function IE(e){const t=(e??[]).filter((e=>e.trim().length>0)),r=t.flatMap((e=>{const t=(0,Ob.bi)(e);return void 0===t?[]:[t]}));return{hasInvalidEntries:r.length!==t.length,entries:r}}function TE(e){const t=!0===e.enabled,r=IE(e.mcpNetworkDenylist),n="deny_all"===e.mcpNetworkMode||r.entries.includes("*")||r.hasInvalidEntries,o=t?function(e){if("allow_all"===e.mcpNetworkMode)return[...RE];const t=IE(e.mcpNetworkAllowlist);if("allowlist"===e.mcpNetworkMode)return t.entries.includes("*")?[...RE]:t.entries;if(!function(e){return(e.mcpNetworkAllowlist??[]).some((e=>e.trim().length>0))}(e))return[...RE];const r=(0,Ob.b6)(e);return r.includes("*")?[...RE]:r}(e):[],s=t?n?["*"]:r.entries:[];return JSON.stringify({enabled:t,mode:e.mcpNetworkMode,allow:n?[]:o,deny:s})}class AE extends Error{constructor(e,t){super(`MCP server "${e}" wasn't started: your team's MCP settings require it to run in a sandbox, and the sandbox isn't supported on this machine. Ask a team admin to review the team's MCP settings for this server.`),this.serverName=e,this.name="McpSandboxUnavailableError",void 0!==t&&(this.cause=t)}}const $E=new Set(["invalid_auth","not_authed","account_inactive","token_revoked","token_expired"]);class ME extends Error{constructor(){super("Your organization admin only allows Slack workspaces your company manages. Connect your company Slack workspace instead."),this.name="SlackWorkspaceNotManagedError"}}class DE extends Error{constructor(){super("Slack couldn't confirm which workspace this connection is for, and your organization admin only allows the Slack workspaces your company manages. Try again in a moment."),this.name="SlackWorkspaceUnconfirmedError"}}function OE(e){return URL.canParse(e)&&"mcp.slack.com"===new URL(e).hostname.toLowerCase()}function FE(e,t){const r=new Map,n=t.lookUpWorkspace??(t=>async function(e,t){let r;try{const n=await e("https://slack.com/api/auth.test",{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/x-www-form-urlencoded"},signal:AbortSignal.timeout(5e3)});r=await n.json()}catch{return{kind:"unavailable"}}if("object"!=typeof r||null===r)return{kind:"unavailable"};if("object"!=typeof(n=r)||null===n||Array.isArray(n))return{kind:"unavailable"};var n;const o=r;return!0!==o.ok?"string"==typeof o.error&&$E.has(o.error)?{kind:"dead"}:{kind:"unavailable"}:"string"!=typeof o.team_id||0===o.team_id.length?{kind:"unavailable"}:"string"==typeof o.enterprise_id&&o.enterprise_id.length>0?{kind:"found",slackTeamId:o.team_id,slackEnterpriseId:o.enterprise_id}:{kind:"found",slackTeamId:o.team_id}}(e,t));let o,s=[];return async(i,a)=>{if(!OE(function(e){return"string"==typeof e?e:e instanceof URL?e.href:e.url}(i)))return e(i,a);const c=function(e,t){const r=new Headers(t?.headers??(e instanceof Request?e.headers:void 0)),n=/^Bearer\s+(.+)$/i.exec(r.get("authorization")??"");return n?.[1]?.trim()||void 0}(i,a);if(void 0===c)return e(i,a);const l=await((void 0===o||Date.now()-o.atMs>=3e4)&&(o={atMs:Date.now(),lists:t.managedSlackWorkspaceLists().then((e=>"unconfirmed"===e?e:(s=e.filter((e=>e.length>0)).map((e=>e.map((e=>e.toUpperCase())))),s)),(()=>s))}),o.lists);if("unconfirmed"===l)throw new DE;if(0===l.length)return e(i,a);let u=r.get(c);if(void 0===u){const t=await n(c);if("dead"===t.kind)return e(i,a);if("unavailable"===t.kind)throw new DE;r.size>=64&&r.clear(),r.set(c,t),u=t}const d=[u.slackTeamId,u.slackEnterpriseId].flatMap((e=>void 0===e?[]:[e.toUpperCase()]));if(!l.every((e=>d.some((t=>e.includes(t))))))throw new ME;return e(i,a)}}function NE(e,t,r){if("string"==typeof e)return t(e);if(!(e instanceof Error))return e;if(r.results.has(e))return r.results.get(e)===e&&r.cycled.add(e),r.results.get(e);r.results.set(e,e);const n=Object.isFrozen(e)&&GE(e,t)?new Error:void 0;void 0!==n&&r.results.set(e,n);const o=t(e.message),s="string"==typeof e.stack?t(e.stack):void 0,i=Object.keys(e).flatMap((n=>{if("cause"===n)return[];const o=UE(e,n),s=qE(o,t,r);return Object.is(s,o)?[]:[[n,s]]})),a=Object.getOwnPropertyDescriptor(e,"cause"),c=void 0===a?void 0:UE(e,"cause"),l=qE(c,t,r),u=e instanceof AggregateError?UE(e,"errors"):void 0,d=function(e,t,r){if(!Array.isArray(e))return e;const n=e.map((e=>qE(e,t,r)));if(n.every(((t,r)=>Object.is(t,e[r]))))return e;try{return n.forEach(((t,r)=>{e[r]=t})),e}catch{return n}}(u,t,r),h=[...i,...Object.is(l,c)?[]:[["cause",l]],...Object.is(d,u)?[]:[["errors",d]]];let p=!1;if(void 0===n)try{o!==e.message&&(e.message=o),void 0!==s&&s!==e.stack&&(e.stack=s),p=e.message===o&&(void 0===s||e.stack===s)&&h.every((([t,r])=>jE(e,t,r)))}catch{}if(p)return e;const f=Object.defineProperties(n??new Error,{message:{value:o,writable:!0,enumerable:!1,configurable:!0},...Object.getOwnPropertyDescriptors(WE(e,new Map(i)))});Array.isArray(d)&&Object.defineProperty(f,"errors",{value:d,writable:!0,enumerable:!1,configurable:!0}),void 0!==a&&Object.defineProperty(f,"cause",{value:l,writable:!0,enumerable:!0===a.enumerable,configurable:!0});const m=Object.getPrototypeOf(e);null!==m&&"object"==typeof m&&m!==Error.prototype&&(Object.setPrototypeOf(f,m),function(e){try{let t=Object.getPrototypeOf(e);for(let r=0;r<8&&null!==t&&"object"==typeof t&&t!==Error.prototype&&t!==Object.prototype;r++){for(const r of Reflect.ownKeys(t)){const n=Object.getOwnPropertyDescriptor(t,r)?.get;void 0!==n&&Reflect.apply(n,e,[])}t=Object.getPrototypeOf(t)}String(e);const r=e;"function"==typeof r.toJSON&&Reflect.apply(r.toJSON,e,[""]);const n=r[BE];return"function"==typeof n&&Reflect.apply(n,e,[0,{depth:0,stylize:String},String]),!0}catch{return!1}}(f)||Object.setPrototypeOf(f,Error.prototype));const g=JE(e);return void 0!==g&&JE(f)!==g&&Object.defineProperty(f,"name",{value:g,writable:!0,configurable:!0,enumerable:!1}),void 0!==s&&(f.stack=s),r.results.set(e,f),f}function LE(e,t){if(e instanceof Error)return t.get(e)??e;if(!Array.isArray(e)||!Object.isFrozen(e))return e;const r=e.map((e=>e instanceof Error?t.get(e)??e:e));return r.every(((t,r)=>Object.is(t,e[r])))?e:r}function jE(e,t,r){const n=Object.getOwnPropertyDescriptor(e,t);return!0===n?.writable&&Reflect.defineProperty(e,t,{...n,value:r})}function UE(e,t){try{const r=Object.getOwnPropertyDescriptor(e,t);return void 0===r?.get?r?.value:r.get.call(e)}catch{return}}const BE=Symbol.for("nodejs.util.inspect.custom");function WE(e,t){const r={};for(const n of Object.keys(e))try{const o=Object.getOwnPropertyDescriptor(e,n),s=void 0===o?.get?o?.value:o.get.call(e);Object.defineProperty(r,n,{value:t.has(n)?t.get(n):s,writable:!0,enumerable:!0,configurable:!0})}catch{}return r}function HE(e,t,r,n){if("string"==typeof e)return t(e);if("object"!=typeof e||null===e)return e;if(e instanceof Error)return NE(e,t,n);if(Array.isArray(e)){if(r>=4)return;return e.slice(0,64).map((e=>HE(e,t,r+1,n)))}const o=Object.getPrototypeOf(e);return o!==Object.prototype&&null!==o?e:r>=4?void 0:function(e,t,r,n){const o={};for(const s of Object.keys(e).slice(0,64))try{const i=Object.getOwnPropertyDescriptor(e,s),a=void 0===i?.get?i?.value:i.get.call(e);Object.defineProperty(o,s,{value:HE(a,t,r,n),writable:!0,enumerable:!0,configurable:!0})}catch{}return o}(e,t,r+1,n)}function qE(e,t,r){if(e instanceof Error)return NE(e,t,r);try{return GE(e,t)?HE(e,t,1,r):e}catch{return}}const zE=4096;function GE(e,t){const r=new Set,n=[e];for(let o=0;n.length>0;o++){if(o>=zE||n.length>zE)return VE(e,t);const s=n.pop();if("string"==typeof s){if(t(s)!==s)return!0}else if((KE(s)||s instanceof Error)&&!r.has(s)){r.add(s),s instanceof Error&&(n.push(UE(s,"message"),UE(s,"stack"),UE(s,"cause")),s instanceof AggregateError&&n.push(UE(s,"errors")));for(const e of Object.keys(s))n.push(UE(s,e))}}return!1}function VE(e,t){const r=new Set;let n;try{n=JSON.stringify(e,((e,t)=>{return"bigint"==typeof t?t.toString():"object"!=typeof t||null===t?t:r.has(t)?void 0:(r.add(t),t instanceof Error?(n=t,{...Object.fromEntries(Object.keys(n).map((e=>[e,UE(n,e)]))),message:UE(n,"message"),stack:UE(n,"stack"),cause:UE(n,"cause"),...n instanceof AggregateError?{errors:UE(n,"errors")}:{}}):t);var n}))}catch{return!0}return void 0!==n&&t(n)!==n}function KE(e){if(Array.isArray(e))return!0;if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function JE(e){try{return"string"==typeof e.name?e.name:void 0}catch{return}}const ZE=/spt_[A-Za-z0-9_]{6,}/g,XE=/[A-Z0-9]/;function QE(e){return function(e){return e.replace(ZE,(e=>function(e){return e.slice(4).split("_").some((e=>e.length>=8&&XE.test(e)))}(e)?"[redacted Link shared payment token]":e))}(e)}var YE=r("../../node_modules/.pnpm/string-argv@0.3.2/node_modules/string-argv/index.js");new Set(["EAI_AGAIN","ECONNABORTED","ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ENOTFOUND","EPIPE","ETIMEDOUT","EADDRNOTAVAIL","UND_ERR_CONNECT_TIMEOUT"]),new Set(["ECONNRESET","EPIPE"]);const ex=new Set([429,502,503,504]);function tx(e){return"object"==typeof e&&null!==e}function rx(e){const t=tx(e)?e.code:void 0,r=(e instanceof Error||tx(e)&&"string"==typeof e.message?e.message:"").match(/\(HTTP (\d+)\)|Non-200 status code \((\d+)\)|\bHTTP\s+(\d{3})\b/i),n=r?.[1]??r?.[2]??r?.[3],o=void 0!==n?parseInt(n,10):void 0;if("number"==typeof t&&t>=100)return void 0!==o&&ex.has(o)&&!ex.has(t)?o:t;if("string"==typeof t&&/^\d{3}$/.test(t)){const e=Number.parseInt(t,10);return e>=100&&e<=599?e:o}return o}new Set(["UND_ERR_SOCKET","UND_ERR_CLOSED","ECONNRESET"]);const nx=8192;function ox(e){return void 0===e?"unknown":"url"in e&&e.url.length>0?void 0!==ib(e.url)?"rest_mcp":"streamable_http":"command"in e?"stdio":"unknown"}new Set(["ENOENT","EACCES","ENOTDIR","EPERM"]);const sx=/\$\{[^}]*\}/;function ix(e){if(void 0!==function(e){if(void 0===e)return;const t=e.trim();return 0!==t.length&&sx.test(t)?t:void 0}(e))return;const t=e?.trim();return t&&t.length>0?t:void 0}const ax=new Map;async function cx(e,t=fetch){if(void 0===ib(e))return;const r=new URL(e),n=`${r.origin}/.well-known/oauth-protected-resource${r.pathname.replace(/\/+$/,"")}`,o=ax.get(n);if(void 0!==o&&o.expiresAtMs>Date.now())return o.metadata;let s;try{const e=await t(n);if(!e.ok)return;s=function(e){if("object"!=typeof(t=e)||null===t)return{};var t;const r=e,n="string"==typeof r.cursor_client_id&&r.cursor_client_id.length>0?r.cursor_client_id:void 0;let o;if("object"==typeof r.cursor_authorization_params&&null!==r.cursor_authorization_params){const e=Object.entries(r.cursor_authorization_params).filter((e=>"string"==typeof e[1]));e.length>0&&(o=Object.fromEntries(e))}return{...void 0!==n?{clientId:n}:{},...!0===r.cursor_omit_resource_indicator?{omitResourceIndicator:!0}:{},...!0===r.cursor_omit_consent_prompt?{omitConsentPrompt:!0}:{},...void 0!==o?{authorizationParams:o}:{},...!0===r.cursor_rejects_custom_scheme_redirects?{rejectsCustomSchemeRedirects:!0}:{},...!0===r.cursor_unauthenticated_connect?{unauthenticatedConnect:!0}:{},...!0===r.cursor_loopback_ipv4?{loopbackIpv4:!0}:{},...!0===r.cursor_backend_only_token_exchange?{backendOnlyTokenExchange:!0}:{}}}(await e.json())}catch{return}return ax.set(n,{metadata:s,expiresAtMs:Date.now()+3e5}),s}(0,_s.J)((function(){ax.clear()}));const lx={info:()=>{},warn:()=>{},error:()=>{},debug:()=>{}};function ux(e){return lx}const dx=/^[\x21\x23-\x5B\x5D-\x7E]+$/,hx=["invalid_request","invalid_token","insufficient_scope"];function px(e){return hx.some((t=>t===e))}function fx(e){const t=new Set;for(const r of e)r.length<=200&&dx.test(r)&&t.add(r);return[...t]}const mx=/[!#$%&'*+.^_`|~0-9A-Za-z-]+/y,gx=/"((?:[^"\\]|\\.)*)"?/y,wx=/[^\s,]*/y;function yx(e,t){let r,n=0;const o=t=>{t.lastIndex=n;const r=t.exec(e);return null!==r&&(n=t.lastIndex),r};for(;n"string"==typeof e&&e.length>0)):void 0}function Sx(e){if("object"!=typeof e||null===e||Array.isArray(e))return vx;const t=bx("grantedScopes"in e?e.grantedScopes:void 0),r=bx("requestedScopes"in e?e.requestedScopes:void 0);return{...void 0!==t?{grantedScopes:t}:{},stepUpScopes:bx("stepUpScopes"in e?e.stepUpScopes:void 0)??[],signInMissing:bx("signInMissing"in e?e.signInMissing:void 0)??[],...void 0!==r?{requestedScopes:r}:{}}}function kx(e){return(e??"").split(/\s+/).filter((e=>e.length>0))}function _x(e,t){return e.filter((e=>!t.has(e)))}function Cx(e){const t=Sb(e.serverUrl),r=e.connectorName??t?.displayName??e.accountKey,n=ux(e.accountKey);let o;const s=async()=>Sx(await e.readRecord()),i=async t=>{if(void 0!==t.grantedScopes)return t.grantedScopes;const r=kx(await e.readTokenScope());return r.length>0?r:void 0},a=(e,t)=>{n.info(`MCP OAuth scope step-up: ${e}`,{event:`mcp_oauth_scope_step_up_${e}`,...t})};return{accountKey:e.accountKey,connectorName:r,async decide(r){if(401!==r.status&&403!==r.status)return;const n=function(e){const t=e??"",r=yx(t,"error")?.toLowerCase(),n=yx(t,"resource_metadata");return{error:void 0===r||""===r?"none":px(r)?r:"other",scopes:fx((yx(t,"scope")??"").split(/\s+/)),resourceMetadata:void 0===n||""===n?void 0:n}}(r.wwwAuthenticate);if("insufficient_scope"!==n.error||0===n.scopes.length)return;if(function(e){try{return kb.has(new URL(e).hostname.toLowerCase())}catch{return!1}}(e.serverUrl))return;const o=function(e,t){if(void 0!==t)try{return new URL(t).origin===new URL(e).origin?t:void 0}catch{return}}(e.serverUrl,n.resourceMetadata),c=void 0===t?await e.readScopesSupported(o).catch((()=>{})):void 0,l=await s(),u=await i(l),{accepted:d,dropped:h}=function(e){const t=new Set(e.granted??[]),r=[],n=[];for(const o of fx(e.named))e.allowlist.has(o)?t.has(o)||r.push(o):n.push(o);return{accepted:r,dropped:n}}({named:n.scopes,allowlist:(p={policy:t,scopesSupported:c,configuredScopes:e.configuredScopes},void 0!==p.policy?new Set([...p.policy.baseScopes,...Object.keys(p.policy.stepUpScopes)]):new Set([...p.scopesSupported??[],...p.configuredScopes??[]])),granted:u});var p;if(0===d.length)return void a("none_accepted",{status:r.status,namedCount:n.scopes.length,droppedCount:h.length});const f=new Set(l.signInMissing),m=d.every((e=>f.has(e)))?"blocked":"offer";return"offer"===m&&await e.writeRecord({...l,...void 0!==u?{grantedScopes:u}:{},stepUpScopes:[...new Set([...l.stepUpScopes,...d])]}),a(m,{status:r.status,acceptedCount:d.length,droppedCount:h.length}),{kind:m,status:r.status,scopes:d,dropped:h,toolName:r.toolName,resourceMetadataUrl:o}},signIn:async e=>(void 0===o&&(o=Promise.resolve().then(e).finally((()=>{o=void 0}))),o),get isSigningIn(){return void 0!==o},tokensForSdk(e){if(void 0===o||void 0===e?.refresh_token)return e;const{refresh_token:t,...r}=e;return r},async prepareAuthorization(){const t=await s();return{stepUpScopes:t.stepUpScopes.length>0?[...new Set([...await i(t)??[],...t.stepUpScopes])]:[],recordRequestedScopes:async t=>{await e.writeRecord({...await s(),requestedScopes:kx(t.searchParams.get("scope"))})}}},async recordTokens(t,{isRefresh:r}){const n=await e.readRecord();if(void 0===n)return;const o=Sx(n),s=kx(t.scope);if(r)return void(s.length>0&&await e.writeRecord({...o,grantedScopes:s}));if(void 0===o.requestedScopes)return;const i=s.length>0?s:o.requestedScopes,c=new Set(i),l=_x(o.requestedScopes,c);await e.writeRecord({grantedScopes:i,stepUpScopes:_x(o.stepUpScopes,c),signInMissing:l}),a("sign_in_recorded",{grantedCount:i.length,signInMissingCount:l.length,scopeReported:s.length>0})},async clear(t){await e.writeRecord(!0===t?.keepPendingScopes?function(e){const{stepUpScopes:t}=Sx(e);return t.length>0?{stepUpScopes:t,signInMissing:[]}:void 0}(await e.readRecord()):void 0)}}}function Ex(e){const t=Sb(e.serverUrl);for(const r of e.scopes){const e=t?.stepUpScopes[r]?.action;if(void 0!==e)return e}return e.toolTitle}function xx(e){const t=function(e){return void 0===e.action?`${e.connectorName} needs a permission its sign-in did not grant.`:`${e.connectorName} needs one more permission to ${e.action}.`}({connectorName:e.connectorName,action:Ex(e)}),r="offer"===e.kind?`Authorize ${e.connectorName} again to approve it; the turn can continue once it's granted.`:`Its last sign-in did not grant ${1===e.scopes.length?"it":"them"}, so an admin or your consent is blocking this. Reconnect ${e.connectorName} from its MCP settings to ask again.`,n=function(e){if(0===e.length)return;const t=e.slice(0,3).join(", "),r=e.length-3;return`${1===e.length?"Permission":"Permissions"}: ${t}${r>0?` and ${r} more`:""}`}(e.scopes);return void 0===n?`${t} ${r}`:`${t} ${r}\n${n}`}class Px extends Error{constructor(e,t,r){super(xx({kind:e.kind,serverUrl:t,connectorName:r,scopes:e.scopes,toolTitle:e.toolName})),this.decision=e,this.serverUrl=t,this.connectorName=r,this.name="McpOAuthScopeStepUpError"}answerWithToolTitle(e){return xx({kind:this.decision.kind,serverUrl:this.serverUrl,connectorName:this.connectorName,scopes:this.decision.scopes,toolTitle:e??this.decision.toolName})}}function Rx(e){if("string"!=typeof e)return;let t;try{t=JSON.parse(e)}catch{return}const r=Array.isArray(t)?t:[t];for(const e of r){if("object"!=typeof e||null===e||!("method"in e)||"tools/call"!==e.method)continue;const t="params"in e?e.params:void 0,r="object"==typeof t&&null!==t&&"name"in t?t.name:void 0;return"string"==typeof r?r:void 0}}function Ix(e){return e instanceof Error&&/does not support dynamic client registration/i.test(e.message)}Error,Error;const Tx=new Set(["UnauthorizedError","InvalidGrantError","InvalidTokenError","InvalidClientError","UnauthorizedClientError"]),Ax=new Set(["invalid_grant","invalid_token","invalid_client","unauthorized_client"]),$x=[/\btoken (?:has |is )?expired\b/i,/\btoken (?:was|is) invalid\b/i,/\binvalid (?:refresh[ _]?)?token\b/i,/\btoken (?:has been |was )?revoked\b/i];var Mx=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js");const Dx="2026-07-28",Ox=-32022,Fx="io.modelcontextprotocol/protocolVersion",Nx="io.modelcontextprotocol/clientCapabilities",Lx="io.modelcontextprotocol/clientInfo",jx="io.modelcontextprotocol/serverInfo",Ux={name:"cursor",version:"1.0.0"},Bx=new Map;function Wx(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Hx(e){const t=new URL(String(e));return t.hash="",t.href}function qx(e,t){const r=Bx.get(e);return!(void 0===r||r<=t()&&(Bx.delete(e),1))}function zx(e,t){try{return Hx(e)===t}catch{return!1}}function Gx(e){return(e.headers.get("content-type")??"").toLowerCase().includes("application/json")}const Vx=new Set(["events/subscribe","events/unsubscribe","events/poll","events/stream"]);function Kx(e,t,r,n,o=t.message){const s=new Headers(e?.headers);if(s.set("mcp-protocol-version",Dx),s.set("mcp-method",r),s.delete("mcp-session-id"),!t.isRequest&&o===t.message)return{...e,headers:s};const i=Wx(o.params)?o.params:{},a=Wx(i._meta)?i._meta:{},c=function(e,t){const r="tools/call"===e||"prompts/get"===e||Vx.has(e)?"name":"resources/read"===e?"uri":void 0,n=void 0===r?void 0:t[r];return"string"==typeof n?n:void 0}(r,i);void 0!==c&&s.set("mcp-name",c);const l=JSON.stringify({...o,params:{...i,_meta:{...a,[Fx]:Dx,[Nx]:n.capabilities,[Lx]:n.clientInfo}}});return{...e,headers:s,body:l}}function Jx(e){return new Response(JSON.stringify({jsonrpc:"2.0",...e}),{status:200,headers:{"content-type":"application/json"}})}function Zx(e,t){const r=Hx(t.serverUrl),n=t.now??Date.now;let o={capabilities:{},clientInfo:{...Ux}},s=!1;const i=()=>s||qx(r,n),a=async(t,i,a)=>{const{method:c,message:l}=t;if(void 0===c)return e(i,a);if("notifications/initialized"===c)return new Response(null,{status:202});if(t.isRequest&&"initialize"===c){const c={jsonrpc:"2.0",id:l.id,method:"server/discover",params:{}},u=await e(i,Kx(a,t,"server/discover",o,c)),d=await async function(e,t,r){if(!e.ok||!Gx(e))return e;let n;try{n=await e.clone().json()}catch{return e}if(!Wx(n)||!Wx(n.result))return e;const o=n.result,s=o.supportedVersions;if(!Array.isArray(s)||!s.includes(Dx))return Jx({id:t,error:{code:Ox,message:"Unsupported protocol version",data:{requested:Dx,supported:s??[]}}});const i=Wx(o._meta)?o._meta:{},a=Wx(i[jx])?i[jx]:{name:new URL(r).hostname,version:"unknown"};return Jx({id:t,result:{protocolVersion:Mx.aE,capabilities:Wx(o.capabilities)?o.capabilities:{},serverInfo:a,..."string"==typeof o.instructions?{instructions:o.instructions}:{}}})}(u,l.id,r);return d!==u&&(s=!0,function(e,t){Bx.set(e,t()+6e5)}(r,n)),d}return e(i,Kx(a,t,c,o))};return async(t,c)=>{const l=function(e,t,r){if("POST"!==(t?.method??"GET").toUpperCase()||"string"!=typeof t?.body||!zx(e,r))return;let n;try{n=JSON.parse(t.body)}catch{return}if(!Wx(n)||"2.0"!==n.jsonrpc)return;const o="string"==typeof n.method?n.method:void 0;return{message:n,method:o,isRequest:void 0!==o&&"id"in n}}(t,c,r);if(void 0===l)return function(e,t,r){return"GET"===(t?.method??"GET").toUpperCase()&&zx(e,r)}(t,c,r)&&i()?new Response(null,{status:405}):e(t,c);if(l.isRequest&&"initialize"===l.method){const e=Wx(l.message.params)?l.message.params:{};o={capabilities:Wx(e.capabilities)?e.capabilities:{},clientInfo:Wx(e.clientInfo)?e.clientInfo:o.clientInfo}}const u=l.isRequest&&"initialize"===l.method;if(u?qx(r,n):i())return a(l,t,c);if(u&&(s=!1),!l.isRequest)return e(t,c);const d=await e(t,c);if(u&&await async function(e){if(e.status>=500||!Gx(e))return!1;const t=Number(e.headers.get("content-length"));if(Number.isFinite(t)&&t>4096)return!1;let r;try{r=await e.clone().json()}catch{return!1}if(!Wx(r)||!Wx(r.error))return!1;const n=r.error;if(n.code!==Ox||!Wx(n.data))return!1;const o=n.data.supported;return Array.isArray(o)&&o.includes(Dx)}(d)){const e=await a(l,t,c);return s?e:d}return d}}function Xx(e,t){if(void 0===t)return{headers:t,cursorAuthHeaderValue:void 0,cursorAuthOrigin:void 0};const r=Object.entries(t),n=r.find((([e])=>e.toLowerCase()===ob));if(void 0===n)return{headers:t,cursorAuthHeaderValue:void 0,cursorAuthOrigin:void 0};let o;try{o=new URL(e).origin}catch{o=void 0}return{headers:Object.fromEntries(r.filter((([e])=>e.toLowerCase()!==ob))),cursorAuthHeaderValue:n[1],cursorAuthOrigin:o}}function Qx(e,t,r){return async(n,o)=>{let s;try{s=new URL("string"==typeof n?n:n.toString()).origin}catch{return r(n,o)}if(s!==t)return r(n,o);const i=await e();if(void 0===i||0===i.length)return r(n,o);const a=new Headers(o?.headers);return a.set(ob,i),r(n,{...o,headers:a,redirect:"manual"})}}class Yx{constructor(e=864e5){this.ttl=e,this.staleDirty=!1,this.refreshGeneration=0}async get(e){const t=performance.now();if(this.state&&this.state.expiresAt>t&&!this.staleDirty)return this.state.value;if(this.staleDirty&&this.state){const t=this.state.value;if(!this.refreshInFlight){const t=this.refreshGeneration;let r;r=(async()=>{try{const r=await e();if(t!==this.refreshGeneration)return;this.state={expiresAt:performance.now()+this.ttl,value:r},this.staleDirty=!1}catch{}finally{r&&this.refreshInFlight===r&&(this.refreshInFlight=void 0)}})(),this.refreshInFlight=r}return t}const r=this.refreshGeneration,n=await e();return r!==this.refreshGeneration||(this.state={expiresAt:performance.now()+this.ttl,value:n},this.staleDirty=!1),n}invalidate(){this.refreshGeneration++,this.state=void 0,this.staleDirty=!1,this.refreshInFlight=void 0}invalidateKeepingStale(){this.state&&(this.staleDirty=!0)}}var eP=r("crypto");function tP(e){const t={};for(const[r,n]of Object.entries(e))void 0!==n&&(t[r]=n);return t}function rP(e,t){const r=function(e){try{const t=new URL(e);return{host:t.host,origin:t.origin,pathname:t.pathname}}catch{return{host:null,origin:null,pathname:null}}}(e),n=!1!==t?.includePath;return{host:r.host,origin:r.origin,path:n?r.pathname:null}}function nP(e,t){return rP(e,t)}function oP(e){if(e)return(0,eP.createHash)("sha256").update(e).digest("hex").slice(0,12)}function sP(e){if(e&&0!==e.length)return oP(JSON.stringify([...e].sort()))}function iP(e){return{clientIdHash:oP(e?.client_id),hasClientSecret:(e?.client_secret??"").length>0,redirectUrisHash:sP(e?.redirect_uris),redirectUriCount:e?.redirect_uris?.length??0}}function aP(e){return"object"==typeof e&&null!==e}function cP(e,t){let r=e;for(const e of t){if(!aP(r)||!(e in r))return;r=r[e]}return r}function lP(e,t){for(const r of t){const t=cP(e,r.split("."));if("string"==typeof t)return t}}function uP(e){if(!e||"object"!=typeof e)return;const t=e.errorCode;return"string"==typeof t?t:void 0}function dP(e){if(!e)return;const t=e.match(/\(HTTP (\d+)\)|Non-200 status code \((\d+)\)|\bHTTP\s+(\d{3})\b/i),r=t?.[1]??t?.[2]??t?.[3];if(!r)return;const n=Number.parseInt(r,10);return Number.isNaN(n)?void 0:n}const hP=e=>e;function pP(e,t){if(e instanceof Error){const r=e.message;return r&&r!==e.name?bP(t(r)):void 0}if("string"==typeof e||"number"==typeof e||"boolean"==typeof e){const r=String(e);return r?bP(t(r)):void 0}}function fP(e){if(e&&"object"==typeof e)return aP(e)?e.cause:void 0}function mP(e,t,r=4){const n=[];let o=e;for(let e=0;e1?n.join(" > "):void 0}const gP="[REDACTED]",wP=/(^|_|-)(token|secret|password|assertion|authorization|verifier|challenge|code)(_|-|$)/i;function yP(e){return e.replace(/(authorization[^:=\r\n]{0,32}[:=]\s*["']?)(?:[A-Za-z][\w.~+/-]*[ \t]+)?[^"',\s&}]+/gi,`$1${gP}`).replace(/((?:access_token|refresh_token|id_token|client_secret|code|password|assertion|token|secret)[^:=\r\n]{0,32}[:=]\s*["']?)([^"',\s&}]+)/gi,`$1${gP}`).replace(/(\bBearer\s+)([A-Za-z0-9\-._~+/]+=*)/gi,`$1${gP}`)}function vP(e,t=256){return e.length>t?`${e.slice(0,Math.max(0,t-3))}...`:e}function bP(e,t){return vP(yP(e),t?.maxLength)}function SP(e,t=hP){if("string"==typeof e)return vP(yP(t(e)));if(void 0!==e)try{const r=JSON.stringify(e,((e,r)=>e&&function(e){const t=e.toLowerCase();return"code"===t||"authorization"===t||t.includes("token")||t.includes("secret")||t.includes("password")||t.includes("assertion")||t.includes("verifier")||t.includes("challenge")||wP.test(t)}(e)?gP:"string"==typeof r?yP(t(r)):r));if(!r)return;return vP(r)}catch{return}}function kP(e,t=hP){const r=fP(e),n=e instanceof Error?e.name:null!=e?typeof e:void 0,o=r instanceof Error?r.name:void 0,s=pP(r,t),i=pP(e,t)??s,a=lP(e,["code","cause.code"]),c=uP(e)??uP(r)??lP(e,["errorCode","error","cause.errorCode","cause.error","body.error","response.body.error"]),l=void 0===c?void 0:bP(t(c)),u=function(e){for(const t of["status","statusCode","response.status","response.statusCode","cause.status","cause.statusCode","cause.response.status","cause.response.statusCode"]){const r=cP(e,t.split("."));if("number"==typeof r&&Number.isFinite(r))return r}}(e)??dP(i)??dP(s),d=SP(cP(e,["response","body"])??cP(e,["body"])??cP(e,["data"])??cP(e,["cause","body"])??cP(e,["cause","response","body"]),t),h=function(e){const t=e.message?.toLowerCase(),r=e.code?.toLowerCase();return t?.includes("timed out")||t?.includes("timeout")||t?.includes("etimedout")||"etimedout"===r?"timeout":t?.includes("enotfound")||t?.includes("eai_again")||t?.includes("dns")||"enotfound"===r||"eai_again"===r?"dns":t?.includes("certificate")||t?.includes("tls")||t?.includes("ssl")?"tls":t?.includes("econnreset")||t?.includes("connection reset")||"econnreset"===r?"connection_reset":t?.includes("econnrefused")||t?.includes("connection refused")||"econnrefused"===r?"connection_refused":void 0}({message:i,code:a}),p=l?"oauth_error":h?"auth_transport_error":i?"generic_error":void 0;return tP({errorName:n,errorMessage:i,errorType:null!=e?typeof e:void 0,httpStatus:u,oauthErrorCode:l,errorResponseSummary:d,networkClassification:h,causeName:o,causeMessage:s,causeChain:mP(e,t),sdkErrorKind:p})}const _P={mcp_oauth_provider_initialized:"MCP OAuth provider initialized",mcp_oauth_tokens_loaded:"MCP OAuth tokens loaded",mcp_oauth_tokens_saved:"MCP OAuth tokens saved",mcp_oauth_callback_completion:"MCP OAuth callback exchange completed",mcp_oauth_client_info_loaded:"MCP OAuth client information loaded",mcp_oauth_client_info_saved:"MCP OAuth client information saved",mcp_oauth_refresh_prepare:"MCP OAuth refresh prepared",mcp_oauth_refresh_error_release:"MCP OAuth refresh error released",mcp_oauth_state_transition:"MCP OAuth state transition",mcp_oauth_credentials_invalidated:"MCP OAuth credentials invalidated"};function CP(e){const t=e.message??_P[e.event],r={event:e.event,cursorMcp:{oauth:tP({...e.metadata})}},n=e.level??"info";"error"!==n?"warn"!==n?"debug"!==n?e.logger.info?.(t,r):e.logger.debug?.(t,r):e.logger.warn?.(t,r):e.logger.error?.(t,e.error,r)}const EP=new Map(["AWS4-HMAC-SHA256","Api-Key","ApiKey","Basic","Bearer","Bot","DPoP","Digest","GNAP","HOBA","Key","Mutual","NTLM","Negotiate","OAuth","PrivateToken","SCRAM-SHA-1","SCRAM-SHA-256","Token","vapid"].map((e=>[e.toLowerCase(),e]))),xP=4096;function PP(e){return"object"==typeof e&&null!==e&&"url"in e&&"string"==typeof e.url}function RP(e){return"string"==typeof e?e:e instanceof URL?e.toString():e.url}function IP(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function TP(e){if(e instanceof Headers)return e;if(Array.isArray(e)){const t=[];for(const r of e){if(!Array.isArray(r)||"string"!=typeof r[0]||"string"!=typeof r[1])return;t.push([r[0],r[1]])}return t}if(IP(e)){const t={};for(const[r,n]of Object.entries(e)){if("string"!=typeof n)return;t[r]=n}return t}}function AP(e,t){const r=new Headers(TP(PP(e)?e.headers:void 0));return new Headers(TP(t?.headers)).forEach(((e,t)=>{r.set(t,e)})),r}function $P(e){const t=[];return e.forEach(((e,r)=>{t.push(r)})),t.sort()}function MP(e){if(null===e)return null;const t=Number.parseInt(e,10);return Number.isNaN(t)?null:t}function DP(e,t){if(null==e)return{kind:"none",bytes:0,contentLength:MP(t.get("content-length"))};if("string"==typeof e){const r=(new TextEncoder).encode(e).length;return{kind:"text",bytes:r,contentLength:MP(t.get("content-length"))??r}}if(e instanceof URLSearchParams){const r=e.toString(),n=(new TextEncoder).encode(r).length;return{kind:"text",bytes:n,contentLength:MP(t.get("content-length"))??n}}return e instanceof Blob?{kind:"blob",bytes:e.size,contentLength:MP(t.get("content-length"))??e.size}:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?{kind:"binary",bytes:e.byteLength,contentLength:MP(t.get("content-length"))??e.byteLength}:"object"==typeof e&&null!==e&&("getReader"in e||Symbol.asyncIterator in e)?{kind:"stream",bytes:null,contentLength:MP(t.get("content-length"))}:{kind:"unknown",bytes:null,contentLength:MP(t.get("content-length"))}}function OP(e,t){if(null===e||!e.toLowerCase().startsWith("application/x-www-form-urlencoded"))return;const r="string"==typeof t?function(e){for(const t of e.split("&")){const e=t.indexOf("="),r=e>=0?t.slice(0,e):t;let n;try{n=decodeURIComponent(r.replaceAll("+"," "))}catch{return}if("grant_type"!==n)continue;const o=e>=0?t.slice(e+1):"";try{return decodeURIComponent(o.replaceAll("+"," "))}catch{return}}}(t):t instanceof URLSearchParams?t.get("grant_type")??void 0:void 0;return r?function(e){switch(e){case"authorization_code":case"refresh_token":case"client_credentials":case"urn:ietf:params:oauth:grant-type:jwt-bearer":case"urn:ietf:params:oauth:grant-type:token-exchange":return e;default:return"other"}}(r):void 0}function FP(e){const{input:t,init:r}=e,n=rP(RP(t)),o=AP(t,r),s=$P(o),i=o.get("content-type"),a=oP(o.get("mcp-session-id")??void 0),c=function(e){if(!e)return null;const t=e.trim().split(/\s+/,1)[0]??"";return EP.get(t.toLowerCase())??"unrecognized"}(o.get("authorization"));return{method:(r?.method??(PP(t)?t.method:void 0)??"GET").toUpperCase(),url:n,headers:{names:s,count:s.length},contentType:i,body:DP(r?.body,o),sessionIdHash:a??null,authorizationScheme:c}}function NP(e,t){const r=$P(e.headers),n=MP(e.headers.get("content-length"));return{status:e.status,ok:e.ok,headers:{names:r,count:r.length},contentType:e.headers.get("content-type"),body:{kind:null===e.body?"none":"stream",bytes:null===e.body?0:n,contentLength:n,...void 0!==t?{errorSummary:t}:{}},sessionIdHash:oP(e.headers.get("mcp-session-id")??void 0)??null,wwwAuthenticateHash:oP(e.headers.get("www-authenticate")??void 0)??null,mcpProtocolVersion:e.headers.get("mcp-protocol-version")??null,requestId:e.headers.get("x-request-id")??null,retryAfter:LP(e.headers,"retry-after"),slackRateLimitType:LP(e.headers,"x-slack-ratelimit-type")}}function LP(e,t){return e.get(t)?.slice(0,64)??null}function jP(e){const t={};return void 0!==e.errorName&&(t.name=e.errorName),void 0!==e.errorMessage&&(t.message=e.errorMessage),void 0!==e.errorType&&(t.type=e.errorType),void 0!==e.oauthErrorCode&&(t.oauthErrorCode=e.oauthErrorCode),void 0!==e.errorResponseSummary&&(t.responseSummary=e.errorResponseSummary),void 0!==e.networkClassification&&(t.networkClassification=e.networkClassification),void 0!==e.sdkErrorKind&&(t.sdkErrorKind=e.sdkErrorKind),t}function UP(e,t){const r=FP({input:e,init:t});if(void 0!==OP(r.contentType,t?.body))return!0;const n=r.url.path?.toLowerCase()??"";return n.endsWith("/token")||n.includes("/oauth/token")||n.includes("/connect/token")}const BP=e=>e,WP="REDACTED_SESSION_ID",HP=/\b00D[A-Za-z0-9]{12,15}![A-Za-z0-9._]{20,512}/g;async function qP(e,t,r){try{const n=r(await e.clone().text());return n.length>t?n.slice(0,t):n}catch{return}}async function zP(e){if(!UP(e.input,e.init))return;const t=await qP(e.response,xP,e.redact);if(void 0!==t)try{return SP(JSON.parse(t))}catch{return bP(t,{maxLength:xP})}}async function GP(e){const t=await async function(e,t,r){try{if(t.ok)return;const n=t.headers.get("content-type")?.toLowerCase()??"";if(!n.includes("json")&&!n.includes("text"))return;const o=await qP(t,xP,r);if(void 0===o)return;return function(e){if("/mcp"!==(t=rP(RP(e.input)).path)&&!0!==t?.endsWith("/mcp"))return bP(e.rawText,{maxLength:xP});var t;try{const t=JSON.parse(e.rawText);return IP(t)?function(e){const t=e.error;if("string"==typeof t)return JSON.stringify({error:t});if("object"!=typeof t||null===t)return;if(!IP(t))return;const r=t,n="number"==typeof r.code||"string"==typeof r.code?r.code:void 0,o="string"==typeof r.message?bP(r.message,{maxLength:xP}):void 0;return void 0!==n||void 0!==o?JSON.stringify({...void 0!==n?{code:n}:{},...void 0!==o?{message:o}:{}}):void 0}(t):void 0}catch{return}}({input:e,rawText:o})}catch{return}}(e.input,e.response,e.redact);return{responseErrorSummary:t,oauthTokenErrorBodySummary:void 0===t?await zP({input:e.input,response:e.response,init:e.init,redact:e.redact}):void 0}}function VP(e,t,r){try{e()}catch{t.warn?.("MCP HTTP exchange logging failed",{event:"mcp_http_exchange_logging_failure",phase:r})}}function KP(e,t,r){if("string"==typeof e)return t(e);if("object"!=typeof e||null===e||r>12)return e;if(Array.isArray(e))return e.map((e=>KP(e,t,r+1)));const n=Object.getPrototypeOf(e);return n!==Object.prototype&&null!==n?e:Object.fromEntries(Object.entries(e).map((([e,n])=>[e,KP(n,t,r+1)])))}function JP(e,t){const r=e=>{const r=KP(e,t,0);return IP(r)?r:void 0};return{debug:(t,n)=>e.debug?.(t,r(n)),info:(t,n)=>e.info?.(t,r(n)),warn:(t,n)=>e.warn?.(t,r(n))}}function ZP(e){const{fetch:t,logSuccessfulExchanges:r=!0,redactLogText:n}=e,o=void 0===n?e.logger:JP(e.logger,n);return async(s,i)=>{const a=Date.now(),c="function"==typeof e.metadata?e.metadata(s):e.metadata,l=!0===e.redactEchoedSessionId?function(e,t,r){const n=AP(e,t).get("mcp-session-id")?.trim()??"";return e=>{const t=n.length>=8?e.split(n).join(WP):e;return r(t.replace(HP,WP))}}(s,i,n??BP):n??BP;try{const e=await t(s,i),{responseErrorSummary:n,oauthTokenErrorBodySummary:u}=e.ok?{}:await GP({input:s,init:i,response:e,redact:l});return!r&&e.ok||VP((()=>{!function(e){const{logger:t,response:r}=e,n=function(e){const{input:t,init:r,response:n,durationMs:o,metadata:s,responseErrorSummary:i,oauthTokenErrorBodySummary:a}=e,c=FP({input:t,init:r}),l=OP(c.contentType,r?.body);return{event:"mcp_http_exchange",outcome:n.ok?"success":"http_error",durationMs:o,cursorMcp:{transport:{...s,request:c,response:NP(n,i),...void 0!==l?{oauth:{grantType:l}}:{},...void 0!==a?{oauthTokenErrorBodySummary:a}:{}}}}}(e);r.ok?t.info?.("MCP HTTP exchange completed",n):function(e){return 401===e.response.status&&null===e.request.authorizationScheme&&e.response.headers.has("www-authenticate")&&!UP(e.input,e.init)}({response:r,request:n.cursorMcp.transport.request,input:e.input,init:e.init})?t.debug?.("MCP HTTP exchange completed",n):t.warn?.("MCP HTTP exchange completed",n)}({logger:o,input:s,init:i,response:e,durationMs:Date.now()-a,metadata:c,responseErrorSummary:n,oauthTokenErrorBodySummary:u})}),o,"success"),e}catch(t){const r=function(e){if(!aP(e))return;const t=aP(e.cause)?e.cause:void 0,r=[e.response,t?.response];for(const e of r)if("object"==typeof(n=e)&&null!==n&&"status"in n&&"number"==typeof n.status&&"headers"in n&&"object"==typeof n.headers&&null!==n.headers&&"get"in n.headers&&"function"==typeof n.headers.get)return e;var n}(t),{responseErrorSummary:u,oauthTokenErrorBodySummary:d}=r?await GP({input:s,init:i,response:r,redact:l}):{};throw VP((()=>{!function(e){const{logger:t}=e;t.warn?.("MCP HTTP exchange failed",function(e){const{input:t,init:r,error:n,durationMs:o,metadata:s,responseFromError:i,responseErrorSummary:a,oauthTokenErrorBodySummary:c}=e,l=kP(n,e.redactLogText),u=FP({input:t,init:r}),d=OP(u.contentType,r?.body);return{event:"mcp_http_exchange",outcome:"error",durationMs:o,cursorMcp:{transport:{...s,request:u,response:void 0!==i?NP(i,a):{status:l.httpStatus??null,ok:null,headers:{names:[],count:0},contentType:null,body:{kind:"none",bytes:null,contentLength:null,...void 0!==a?{errorSummary:a}:{}},requestId:null,sessionIdHash:null,wwwAuthenticateHash:null,mcpProtocolVersion:null,retryAfter:null,slackRateLimitType:null},...void 0!==d?{oauth:{grantType:d}}:{},...void 0!==c?{oauthTokenErrorBodySummary:c}:{},error:jP(l)}}}}(e))}({logger:o,input:s,init:i,error:t,durationMs:Date.now()-a,metadata:c,responseFromError:r,responseErrorSummary:u,oauthTokenErrorBodySummary:d,redactLogText:!0===e.redactEchoedSessionId?l:n})}),o,"failure"),t}}}function XP(e,t){const r=e?.access_token,n="string"==typeof r?r.length:0,o=Boolean(e?.refresh_token),s="number"==typeof e?.expires_in&&Number.isFinite(e.expires_in)?e.expires_in:null;return{accessTokenLen:n,refreshTokenPresent:o,expiresAtTimestamp:t?.expiresInIsFresh&&null!==s?Date.now()+Math.round(1e3*s):null,grantedScope:"string"==typeof e?.scope&&e.scope.length>0?e.scope:null}}function QP(e){const t=function(e){if(!e||"object"!=typeof e)return;const t=e.code;if("number"==typeof t&&t>=100&&t<=599)return t;if("string"==typeof t&&/^\d{3}$/.test(t)&&Number(t)>=100&&Number(t)<=599)return Number(t);const r=e instanceof Error||"object"==typeof e&&null!==e&&"message"in e&&"string"==typeof e.message?e.message:void 0;if(!r)return;const n=r.match(/\bHTTP\s+(\d{3})\b/i);if(!n?.[1])return;const o=Number.parseInt(n[1],10);return Number.isNaN(o)?void 0:o}(e);return void 0!==t?400===t||404===t||405===t:!!(e instanceof Error&&e.message.toLowerCase().includes("sessionid must be provided"))||function(e){if(!(e instanceof Error))return!1;const t="code"in e&&"string"==typeof e.code?e.code:void 0,r="cause"in e&&"object"==typeof e.cause&&null!==e.cause&&"code"in e.cause&&"string"==typeof e.cause.code?e.cause.code:void 0;return"ECONNREFUSED"===t||"ECONNREFUSED"===r||e.message.includes("ECONNREFUSED")}(e)}function YP(e,t=process.env){const r=t.TMPDIR,n={...void 0===r?{}:{TMPDIR:r},...e},{NODE_COMPILE_CACHE:o,...s}=n;return{...s,NODE_DISABLE_COMPILE_CACHE:"1"}}const eR=["PYTHONIOENCODING","PYTHONUTF8","PYTHONLEGACYWINDOWSSTDIO"],tR=[".exe",".cmd",".bat"],rR=/^pythonw?(?:\d+(?:\.\d+)*t?)?$/,nR=new Set(["py","pyw"]),oR=new Set(["--cache-dir","--color","--allow-insecure-host","--directory","--project","--config-file"]),sR=new Set;function iR(e){return eR.some((t=>function(e,t){const r=t.toUpperCase();return Object.entries(e).some((([e,t])=>void 0!==t&&e.toUpperCase()===r))}(e,t)))}function aR(e,t){for(let r=0;r=2&&e.endsWith(t)?e.slice(1,-1):e}(e.trim())).toLowerCase();for(const e of tR)if(t.endsWith(e))return t.slice(0,-e.length);return t}(e);if(rR.test(r)||nR.has(r)||"uvx"===r)return!0;if("uv"===r){const e=aR(t,oR);return"run"===e?.value||"tool"===e?.value&&"run"===aR(e.rest,oR)?.value}return"pipx"===r&&"run"===aR(t,sR)?.value}(n,o)?iR(i)||iR(r)?i:{...i,PYTHONIOENCODING:"utf-8:surrogateescape"}:i}async function lR(e){const t=[],r=new Set;let n;for(let o=1;;o++){const s=await e.fetchPage(n),i=e.itemsOf(s);t.push(...i);const a=e.nextCursorOf(s);if(!a||r.has(a))return t;if(o>=1e3)throw new Error("MCP list did not end after 1000 pages; refusing to keep paging");r.add(a),n=a}}var uR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"),dR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js"),hR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js"),pR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js");var fR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js");function mR(e){return`${typeof e}:${String(e)}`}function gR(e){const t=new Map,r=new Set,n=new Set,o=e=>{for(const t of n)t(e)},s=e=>{t.delete(e),r.delete(e)},i=e.send.bind(e);e.send=(e,n)=>((e=>{if("method"in e)if("tools/call"===e.method&&"id"in e){const r=e.params?.name;"string"==typeof r&&t.set(mR(e.id),r)}else if("notifications/cancelled"===e.method){const n=e.params?.requestId;if("string"!=typeof n&&"number"!=typeof n)return;const o=mR(n);if(!t.has(o))return;if(r.add(o),r.size>64){const e=r.values().next().value;void 0!==e&&s(e)}}})(e),i(e,n));const a=e.onmessage;return e.onmessage=(e,n)=>{(e=>{if("method"in e)return void("notifications/tools/list_changed"===e.method&&o({kind:"tools_list_changed"}));if(!("id"in e))return;const n=e.id;if("string"!=typeof n&&"number"!=typeof n)return;const i=mR(n),a=t.get(i);if(void 0===a)return;const c=r.has(i);if(s(i),!c)return;const l="error"in e||"object"==typeof e.result&&null!==e.result&&"isError"in e.result&&!0===e.result.isError;o({kind:"late_tool_result",toolName:a,isError:l})})(e),a?.(e,n)},{subscribe:e=>(n.add(e),()=>{n.delete(e)})}}function wR(e){const t=Object.entries(e.headers??{}).map((([e,t])=>[e.toLowerCase(),t])).sort((([e],[t])=>et?1:0));return(0,bo.createHash)("sha256").update(JSON.stringify([e.url,t,e.accessToken??null])).digest("hex")}class yR{constructor(e,t){this.inner=e,this.initializeResult=t,e.onclose=()=>this.onclose?.(),e.onerror=e=>this.onerror?.(e),e.onmessage=e=>this.onmessage?.(e)}get sessionId(){return this.inner.sessionId}setProtocolVersion(e){this.inner.setProtocolVersion(e)}start(){return this.inner.start()}close(){return this.inner.close()}async send(e,t){if((0,Mx.vo)(e)&&(0,Mx.eK)(e)){const t={jsonrpc:"2.0",id:e.id,result:this.initializeResult};queueMicrotask((()=>this.onmessage?.(t)))}else(0,Mx.wU)(e)||await this.inner.send(e,t)}}const vR=je.object({tools:je.array(je.unknown()),nextCursor:je.unknown().optional(),_meta:je.unknown().optional()}),bR={typeFilled:0,toolDropped:0,outputStripped:0};function SR(e){if(PR(e))return"string"==typeof e.name?e.name:void 0}function kR(e){return _R(e.issues.filter((e=>"outputSchema"===e.path[0])))}function _R(e){return e.map((e=>`${e.path.map(String).join(".")}: ${e.message}`))}function CR(e){if(!PR(e))return e;const t={...e};return delete t.outputSchema,t}function ER(e){return PR(e)&&!("type"in e)}function xR(e,t){return{...e,inputSchema:{type:"object",...t}}}function PR(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var RR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js");const IR=new class{constructor({maxSchemasPerCompiler:e=2048,createCompiler:t=()=>new RR.p}={}){this.compiled=new Map,this.maxSchemasPerCompiler=e,this.createCompiler=t,this.compiler=t()}get compiledSchemaCount(){return this.compiled.size}getValidator(e){let t;return r=>(t??=this.compile(e),t(r))}compile(e){const t=JSON.stringify(e),r=(0,bo.createHash)("sha256").update(t).digest("base64url"),n=this.compiled.get(r);if(void 0!==n)return n;this.compiled.size>=this.maxSchemasPerCompiler&&(this.compiler=this.createCompiler(),this.compiled.clear());const o=(t.includes('"$id"')?this.createCompiler():this.compiler).getValidator(e);return this.compiled.set(r,o),o}};class TR{constructor(){this.decoder=new TextDecoder("utf-8"),this.captured="",this.capturedBytes=0}push(e){const t="string"==typeof e?e:this.decoder.decode(e,{stream:!0});return this.append(t),t}end(){const e=this.decoder.decode();return this.append(e),e}get text(){return this.captured}get full(){return this.capturedBytes>=nx}append(e){const t=nx-this.capturedBytes;if(t<=0||0===e.length)return;const r=function(e,t){if(!(t>0))return"";if(3*e.length<=t)return e;const{read:r}=Xo(e,Math.trunc(t));return r>=e.length?e:e.slice(0,r)}(e,t);this.captured+=r,this.capturedBytes=r.length=100&&t<=599?{error_class:"http",error_code:String(t),transport:e.transport}:void 0!==e.error||!0===e.failed?{error_class:"other",error_code:"exception",transport:e.transport}:!0===e.isError?{error_class:"payload",error_code:"is_error",transport:e.transport}:{error_class:"none",error_code:"none",transport:e.transport}}({transport:ox(t),...r}))}catch{}}const NR=(0,u.Pu)("mcp_tool.oauth_scope_step_up",{description:"A tools/call refused for a missing OAuth scope, by step-up decision",labelNames:["decision","dropped"]});function LR(e){return void 0===e?"unknown":"url"in e?"http":"stdio"}const jR=["authorization_code","refresh_token"],UR=["code"];class BR{constructor(e){this._refreshInProgress=!1,this._identifier=e.identifier,this._redirectUrl=e.redirectUrl,this._serverUrl=e.serverUrl,this._restMcpProviderMetadata=e.restMcpProviderMetadata,this.validateResourceURL=!0===e.restMcpProviderMetadata?.omitResourceIndicator?async()=>{}:function(e,t){if(function(e,t){const r=t.gtmApiOrigin;if(void 0===e||void 0===r)return!1;let n,o;try{n=new URL(e),o=new URL(r)}catch{return!1}return n.protocol===o.protocol&&n.hostname===o.hostname&&""===n.port&&"/mcp"===n.pathname}(e,t))return async()=>{};const r=vb(e);return void 0!==r&&function(e){return"https:"===e.protocol&&e.hostname===new URL(ab).hostname}(r)?async()=>{}:void 0!==r&&function(e){return"https:"===e.protocol&&"setup.shopify.com"===e.hostname&&""===e.port&&"/mcp"===e.pathname}(r)?bb:wb}(e.serverUrl,e.gtmMcpMatch),this._clientMetadata=e.clientMetadata,this._scopes=e.scopes,this._isScopePinGateEnabled=e.isScopePinGateEnabled,this.scopeStepUp=e.scopeStepUp,this._tokens=e.tokens,this._clientInformation=e.clientInformation,this._saveTokens=e.saveTokens,this._prepareForRefresh=e.prepareForRefresh,this._releaseRefreshLeaseOnError=e.releaseRefreshLeaseOnError,this._invalidateCredentials=e.invalidateCredentials,this._saveClientInformation=e.saveClientInformation,this.addClientAuthentication=e.addClientAuthentication}get redirectUrl(){return this._redirectUrl}get clientMetadata(){return this._clientMetadata}state(){return this._oauthAttemptId=(0,bo.randomUUID)(),this._oauthState=function(e,t,r){const n={id:e,owner:t,...r?{attemptId:r}:{}};return Buffer.from(JSON.stringify(n),"utf8").toString("base64url")}(this._identifier,{workspaceId:this._redirectUrl},this._oauthAttemptId),this._oauthState}clientInformation(){return this._clientInformation}hasClientInformation(){return void 0!==this._clientInformation}async saveClientInformation(e){this._clientInformation=e,await this._saveClientInformation(e)}tokens(){return this.scopeStepUp?.tokensForSdk(this._tokens)??this._tokens}async saveTokens(e){const t=this._refreshInProgress;this._refreshInProgress=!1,this._tokens=e,await this._saveTokens(e),await(this.scopeStepUp?.recordTokens(e,{isRefresh:t}))}async prepareForRefresh(){await(this._prepareForRefresh?.()),this._refreshInProgress=!0}async releaseRefreshLeaseOnError(e){this._refreshInProgress=!1,await(this._releaseRefreshLeaseOnError?.(e))}async invalidateCredentials(e){switch(this._refreshInProgress=!1,e){case"tokens":this._tokens=void 0;break;case"client":this._clientInformation=void 0;break;case"verifier":this._codeVerifier=void 0,this._oauthState=void 0,this._oauthAttemptId=void 0;break;case"all":this._tokens=void 0,this._clientInformation=void 0,this._codeVerifier=void 0,this._oauthState=void 0,this._oauthAttemptId=void 0,this._lastRedirectUrl=void 0,await(this.scopeStepUp?.clear({keepPendingScopes:!0}));break;default:return e}await(this._invalidateCredentials?.(e))}async redirectToAuthorization(e){const t=await(this.scopeStepUp?.prepareAuthorization());(function(e,t,r={}){const n=r.stepUpScopes??[],o=void 0!==t&&t.length>0?t:n.length>0?(e.searchParams.get("scope")??"").split(" ").filter((e=>e.length>0)):void 0;var s;void 0!==o&&e.searchParams.set("scope",(s={scopes:o,stepUpScopes:n},[...new Set([...s.scopes,...s.stepUpScopes])]).join(" "))})(e,function(e,t,r){const n=mb(e);return!0!==n?.pinsScopesOverConfiguredScopes?void 0!==t&&t.length>0||void 0===r?t:Sb(e)?.baseScopes??t:void 0!==n.scopesPinGate&&!0!==r?.(n.scopesPinGate)?t:n.scopes??t}(this._serverUrl??"",this._scopes,this._isScopePinGateEnabled),{stepUpScopes:t?.stepUpScopes}),void 0!==this._serverUrl&&function(e,t){const r=mb(t)?.authorizationParams;if(void 0!==r)for(const[t,n]of Object.entries(r))e.searchParams.set(t,n)}(e,this._serverUrl);for(const[t,r]of Object.entries(this._restMcpProviderMetadata?.authorizationParams??{}))e.searchParams.set(t,r);(!0===this._restMcpProviderMetadata?.omitConsentPrompt||function(e){return"login.microsoftonline.com"===e.hostname}(e))&&function(e){const t=new Set(e.searchParams.getAll("prompt").flatMap((e=>e.split(" "))).filter((e=>""!==e&&"consent"!==e)));e.searchParams.delete("prompt"),t.size>0&&e.searchParams.set("prompt",[...t].join(" "))}(e),await(t?.recordRequestedScopes(e)),this._lastRedirectUrl=e}get lastRedirectUrl(){return this._lastRedirectUrl}async saveCodeVerifier(e){this._codeVerifier=e}codeVerifier(){if(!this._codeVerifier)throw new Error("No code verifier saved");return this._codeVerifier}}async function WR(e){const{serverName:t,config:n,tokenStorage:o}=e,s=await cx(n.url,e.fetchImpl),i=Ab({loopbackIpv4:s?.loopbackIpv4,redirectUrl:e.authRedirectUrl}),a=function(e,t){const r=ix(e?.CLIENT_ID);if(void 0!==r)return{client_id:r,...e?.CLIENT_SECRET?{client_secret:e.CLIENT_SECRET}:{},redirect_uris:$b(t),grant_types:[...jR],response_types:[...UR],token_endpoint_auth_method:"none"}}(n.auth,i),c=function({storedClientInformation:e,staticClientInformation:t}){return t?e&&e.client_id===t.client_id?{...t,...e,client_secret:t.client_secret??e.client_secret,redirect_uris:t.redirect_uris,grant_types:e.grant_types??t.grant_types,response_types:e.response_types??t.response_types,token_endpoint_auth_method:e.token_endpoint_auth_method??t.token_endpoint_auth_method}:t:e}({storedClientInformation:await o.loadClientInformation(),staticClientInformation:a});return new BR({identifier:t,redirectUrl:i,serverUrl:n.url,restMcpProviderMetadata:s,gtmMcpMatch:e.gtmMcpMatch??{gtmApiOrigin:void 0},clientMetadata:{redirect_uris:$b(i),token_endpoint_auth_method:"none",grant_types:[...jR],response_types:[...UR],client_name:"Cursor",logo_uri:"https://ptht05hbb1ssoooe.public.blob.vercel-storage.com/assets/uploads/cursorlogomcpv3.svg"},scopes:n.auth?.scopes,isScopePinGateEnabled:e.isScopePinGateEnabled,...!0===e.scopeChallengeStepUp&&void 0!==o.loadScopeStepUpRecord&&void 0!==o.saveScopeStepUpRecord?{scopeStepUp:Cx({serverUrl:n.url,accountKey:t,configuredScopes:n.auth?.scopes,readTokenScope:async()=>void 0!==o.loadGrantedScope?o.loadGrantedScope():(await o.loadTokens())?.scope,readRecord:async()=>o.loadScopeStepUpRecord?.(),writeRecord:async e=>o.saveScopeStepUpRecord?.(e),readScopesSupported:t=>async function(e){try{const{discoverAuthorizationServerMetadata:t,discoverOAuthProtectedResourceMetadata:n}=await Promise.resolve().then(r.bind(r,"../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js")),o=await n(e.serverUrl,void 0!==e.resourceMetadataUrl?{resourceMetadataUrl:new URL(e.resourceMetadataUrl)}:void 0,e.fetch),s=await t(o.authorization_servers?.[0]??new URL("/",e.serverUrl),{fetchFn:e.fetch}).catch((()=>{}));if(void 0===s&&!0===e.requireAuthorizationServerMetadata)return;const i=new Set([...o.scopes_supported??[],...s?.scopes_supported??[]]);return i.size>0?[...i]:void 0}catch{return}}({serverUrl:n.url,resourceMetadataUrl:t,fetch:e.fetchImpl})})}:{},tokens:await o.loadTokens(),clientInformation:c,saveTokens:e=>o.saveTokens(e),prepareForRefresh:()=>o.prepareForRefresh?.()??Promise.resolve(),releaseRefreshLeaseOnError:e=>o.releaseRefreshLeaseOnError?.(e)??Promise.resolve(),invalidateCredentials:o.invalidateCredentials?e=>o.invalidateCredentials(e):void 0,saveClientInformation:e=>o.saveClientInformation(e),addClientAuthentication:o.tokenEndpointAuth?.({clientId:c?.client_id})})}const HR=new Set;let qR=!1;function zR(){for(const e of HR)try{process.kill(e,"SIGKILL")}catch{}}function GR(e){return Ix(e)?new uR.D_:e}function VR(e,t){return Zx(e??globalThis.fetch.bind(globalThis),{serverUrl:t})}function KR(e,t,r){const n=Xx(e,t),o=r??(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),s=void 0!==n.cursorAuthHeaderValue&&void 0!==n.cursorAuthOrigin&&void 0!==o?Qx((()=>n.cursorAuthHeaderValue),n.cursorAuthOrigin,o):o;return{transportHeaders:n.headers,baseFetch:s}}class JR{constructor(e,t,r){this._toolListGeneration=0,this._toolListSuccessGeneration=0,this._toolListStateGeneration=0,this._callToolLock=Promise.resolve(),this._callToolQueueDepth=0,this._stateEnteredAtMs=Date.now(),this._terminatingSession=!1,this._closeRequested=!1,this.serverName=e,this.client=t,this.tools=new Yx,this.stateValue=r.initialState,this._authProvider=r.authProvider,this._authCodeExchange=r.authCodeExchange,this._sessionId=r.sessionId,this._protocolVersion=r.protocolVersion,this._resumedInstructions=r.resumedInstructions,this._sessionlessInitialize=r.sessionlessInitialize,this.config=r.config,this._oauthLifecycleLogger=r.oauthLifecycleLogger,this._serverSignals=r.serverSignals,this._redactLogText=r.redactLogText,this.setupElicitationHandler(),!0===r.stdioServer&&(t.onclose=()=>{this._closeRequested||(this.updateState({kind:"error",message:"MCP server exited"},"stdio_exited"),this.tools.invalidate())})}_stateKindLabel(e){return"requires_authentication"===e.kind?"needsAuth":e.kind}_logStateTransition(e,t,r,n){if(!this._oauthLifecycleLogger)return;const o=this._stateKindLabel(e),s=this._stateKindLabel(t);if(o===s)return;const i=Date.now()-this._stateEnteredAtMs,a=(()=>{try{const e=this.config&&"url"in this.config?this.config.url:void 0;return e?new URL(e).host:void 0}catch{return}})();CP({logger:this._oauthLifecycleLogger,event:"mcp_oauth_state_transition",metadata:{identifier:this.serverName,from:o,to:s,cause:r,serverUrlHost:a,previousStateDurationMs:i,...n}})}static createClient(e={}){const t={elicitation:{form:{}},...!1===e.mcpAppsUi?{}:{extensions:{"io.modelcontextprotocol/ui":{mimeTypes:["text/html;profile=mcp-app"]}}}};return new fR.K({name:"Cursor",version:"1.0.0"},{capabilities:t,jsonSchemaValidator:IR})}setupElicitationHandler(){this.client.setRequestHandler(Mx.$9,(async e=>{if(!this._currentElicitationProvider)return{action:"decline"};if(!("requestedSchema"in e.params))return{action:"decline"};try{const t=e.params.requestedSchema,r=await this._currentElicitationProvider.elicit({message:e.params.message,requestedSchema:t});return{action:r.action,content:r.content}}catch(e){return{action:"decline"}}}))}static async fromStreamableHttp(e,t,r,n,o,s,i,a,c,l,u,d=!1,h={}){const p=new URL(t.url);o=o??Pb;const f=await WR({serverName:e,config:t,tokenStorage:r,authRedirectUrl:o,fetchImpl:s,gtmMcpMatch:c,isScopePinGateEnabled:l,scopeChallengeStepUp:u}),m=f.tokens(),g=Xx(t.url,n),w=g.headers,y=d&&function(e){return Object.entries(e??{}).some((([e,t])=>"authorization"===e.toLowerCase()&&t.trim().length>0))}(w)?void 0:f,v=s??(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),b=void 0!==g.cursorAuthHeaderValue&&void 0!==g.cursorAuthOrigin&&void 0!==v?Qx((()=>g.cursorAuthHeaderValue),g.cursorAuthOrigin,v):v,S=e=>void 0===b||void 0===i?b:ZP({fetch:b,logger:i.logger,metadata:{...i.metadata,transportType:e},redactLogText:i.redactLogText});let k;const _=e=>{const r=f.scopeStepUp,n=e??v;return void 0===r||void 0===n?e:(o={fetch:n,scopeStepUp:r,serverUrl:t.url,startSignIn:async e=>{const t=void 0!==e.resourceMetadataUrl&&URL.canParse(e.resourceMetadataUrl)?new URL(e.resourceMetadataUrl):void 0;await(0,uR.j2)(f,{serverUrl:p.toString(),...void 0!==t?{resourceMetadataUrl:t}:{},...void 0!==b?{fetchFn:b}:{}});const r=f.lastRedirectUrl;k=void 0!==r&&void 0!==t?{redirectUrl:r,resourceMetadataUrl:t}:void 0}},async(e,t)=>{const r=await o.fetch(e,t);if(401!==r.status&&403!==r.status||!function(e){if("string"!=typeof e)return!1;let t;try{t=JSON.parse(e)}catch{return!1}return(Array.isArray(t)?t:[t]).some((e=>"object"==typeof e&&null!==e&&"method"in e&&"tools/call"===e.method))}(t?.body))return r;const n=await o.scopeStepUp.decide({status:r.status,wwwAuthenticate:r.headers.get("www-authenticate"),toolName:Rx(t?.body)});if(void 0===n)return r;if(o.onDecision?.(n),await(r.body?.cancel().catch((()=>{}))),"offer"===n.kind)try{await o.scopeStepUp.signIn((()=>o.startSignIn(n)))}catch(e){ux(o.scopeStepUp.accountKey).warn("MCP OAuth scope step-up: could not start the sign-in",{event:"mcp_oauth_scope_step_up_sign_in_failed",errorName:e instanceof Error?e.name:typeof e})}throw new Px(n,o.serverUrl,o.scopeStepUp.connectorName)});var o},C=JR.createClient(h),E=e=>e instanceof uR.D_||function(e){if(null===e||"object"!=typeof e)return!1;const t=e.name;if("string"==typeof t&&Tx.has(t))return!0;const r=e.errorCode;return!("string"!=typeof r||!Ax.has(r.toLowerCase()))||function(e){if(null===e||"object"!=typeof e)return!1;const t=e.name,r=e.errorCode;if("InvalidRequestError"!==t&&("string"!=typeof r||"invalid_request"!==r.toLowerCase()))return!1;const n=e.message;return"string"==typeof n&&$x.some((e=>e.test(n)))}(e)}(e)||Ix(e),x=async t=>{if(!f.hasClientInformation())throw new Error("OAuth client registration has not completed. The MCP server may not support dynamic client registration or the registration failed.");const r=void 0!==k&&k.redirectUrl===f.lastRedirectUrl?k.resourceMetadataUrl:void 0;await(0,uR.j2)(f,{serverUrl:p.toString(),authorizationCode:t,...void 0!==r?{resourceMetadataUrl:r}:{},...void 0!==b?{fetchFn:b}:{}}),a&&CP({logger:a,event:"mcp_oauth_callback_completion",metadata:{identifier:e,...nP(p.toString()),...XP(f.tokens(),{expiresInIsFresh:!0})}})},P=r=>{const n=f.lastRedirectUrl?.toString?.()??"",o=new JR(e,C,{oauthLifecycleLogger:a,redactLogText:i?.redactLogText,initialState:{kind:"requires_authentication",url:n,callback:async e=>{try{await x(e),o.updateState({kind:"ready"})}catch(e){const t=e instanceof Error?e.message:"Authentication failed";throw new Error(`Authentication callback failed: ${t}`)}}},authProvider:f,authCodeExchange:x,sessionId:r,config:t});return o},R=async r=>{const n=new dR.A(p,{authProvider:y,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...w??{}}},fetch:_(S("sse"))});try{return await C.connect(n),new JR(e,C,{initialState:{kind:"ready"},authProvider:f,authCodeExchange:x,config:t,oauthLifecycleLogger:a,redactLogText:i?.redactLogText})}catch(t){if(await n.close().catch((()=>{})),E(t))return a&&CP({logger:a,event:"mcp_oauth_state_transition",metadata:{identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"sse",refreshTokenPresent:Boolean(m?.refresh_token),...nP(p.toString()),...kP(t,i?.redactLogText)}}),P();if(void 0!==r&&QP(t)&&t instanceof dR._)throw function(e,t){let r=e;for(let e=0;e<8&&r instanceof Error&&r.cause instanceof Error;e++)r=r.cause;return r instanceof Error&&void 0===r.cause&&Reflect.defineProperty(r,"cause",{value:t,writable:!0,configurable:!0,enumerable:!1}),e}(r,t);throw t}};if("sse"===t.type)return R();const I=new pR.j(p,{authProvider:y,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...w??{}}},fetch:_(VR(S("streamableHttp"),p))});try{await C.connect(I);const r=function(e,t=Date.now){return qx(Hx(e),t)}(t.url)?void 0:function(e,r){const o=r.protocolVersion;if(void 0!==r.sessionId||void 0===o)return;const s=e.getServerCapabilities(),i=e.getServerVersion();if(void 0===s||void 0===i)return;const a=e.getInstructions();return{result:{protocolVersion:o,capabilities:s,serverInfo:i,...void 0===a?{}:{instructions:a}},credentialFingerprint:wR({url:t.url,headers:n,accessToken:f.tokens()?.access_token})}}(C,I);return new JR(e,C,{initialState:{kind:"ready"},authProvider:f,authCodeExchange:x,sessionId:I.sessionId,protocolVersion:I.protocolVersion,...void 0===r?{}:{sessionlessInitialize:r},config:t,oauthLifecycleLogger:a,redactLogText:i?.redactLogText})}catch(t){if(E(t))return a&&CP({logger:a,event:"mcp_oauth_state_transition",metadata:{identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"streamableHttp",refreshTokenPresent:Boolean(m?.refresh_token),...nP(p.toString()),...kP(t,i?.redactLogText)}}),P(I.sessionId);if(QP(t))return R(t);throw t}}static async fromStreamableHttpWithoutOAuth(e,t,r){const n=JR.createClient(),o=new pR.j(new URL(t.url),{requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...t.headers}},fetch:r});return await n.connect(o),new JR(e,n,{initialState:{kind:"ready"},sessionId:o.sessionId,protocolVersion:o.protocolVersion,config:t})}static async fromCachedSession(e,t,r,n,o,s=Pb,i,a,c,l,u){const d=new URL(t.url),h=await WR({serverName:e,config:t,tokenStorage:n,authRedirectUrl:s,fetchImpl:i,gtmMcpMatch:l,isScopePinGateEnabled:u}),{transportHeaders:p,baseFetch:f}=KR(t.url,o,i),m=new pR.j(d,{authProvider:h,sessionId:r.sessionId,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...p??{}}},fetch:void 0!==f&&void 0!==a?ZP({fetch:f,logger:a.logger,metadata:{...a.metadata,transportType:"streamableHttp"},redactLogText:a.redactLogText}):f});m.setProtocolVersion(r.protocolVersion);const g=function(e){return e._requestMessageId=(0,bo.randomInt)(1048576,2146435072),e}(JR.createClient());return await g.connect(m),new JR(e,g,{initialState:{kind:"ready"},authProvider:h,sessionId:m.sessionId,protocolVersion:r.protocolVersion,...void 0===r.instructions?{}:{resumedInstructions:r.instructions},config:t,oauthLifecycleLogger:c,redactLogText:a?.redactLogText})}static async fromSessionlessInitialize(e,t,r,n,o,s=Pb,i,a,c,l){const u=await WR({serverName:e,config:t,tokenStorage:n,authRedirectUrl:s,fetchImpl:i,gtmMcpMatch:a,isScopePinGateEnabled:c});if(wR({url:t.url,headers:o,accessToken:u.tokens()?.access_token})!==r.credentialFingerprint)return;const{transportHeaders:d,baseFetch:h}=KR(t.url,o,i),p=new pR.j(new URL(t.url),{authProvider:u,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...d??{}}},fetch:h}),f=JR.createClient();return await f.connect(new yR(p,r.result)),new JR(e,f,{initialState:{kind:"ready"},authProvider:u,sessionlessInitialize:r,config:t,redactLogText:l})}get sessionId(){return this._sessionId}get protocolVersion(){return this._protocolVersion}get sessionlessInitialize(){return this._sessionlessInitialize}get holdsOAuthAccessToken(){return Boolean(this._authProvider?.tokens()?.access_token)}async openStandaloneStream(){const e=this.client.transport;e instanceof pR.j&&await e.resumeStream("")}static async fromCommand(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{$R(s,(0,$.VI)(e.withName("McpSdkClient.fromCommand")),!1);const l=(c=o?.spawn,void 0!==c||"linux"!==process.platform?c:(e,t,r)=>(0,su.D9)(ou.spawn,e,t,r)),u=r.args??[],d=new hR.oQ({command:r.command,args:u,env:YP(cR({command:r.command,args:u,env:n})),cwd:r.cwd,stderr:"pipe",...l&&{spawn:l}}),h=function(e){const t=new TR;let r=null===e;return null!==e&&(e.on("data",(e=>{t.full||t.push(e)})),e.once("end",(()=>{t.end(),r=!0}))),{read:()=>bP(t.text.replace(/\s+/g," ").trim(),{maxLength:nx}),waitForFlush:async()=>{r||null===e||await new Promise((t=>{let r;const n=()=>{void 0!==r&&clearTimeout(r),e.off("end",n),t()};r=setTimeout(n,250),r.unref(),e.once("end",n)}))}}}(d.stderr),p=JR.createClient({mcpAppsUi:o?.mcpAppsUi}),f=o?.connectTimeoutMs??(void 0!==(a=r.startupTimeoutSec)&&Number.isFinite(a)&&a>0?Math.min(1e3*a,3e5):6e4);let m;d.onclose=()=>{var e;void 0!==m&&(e=m,HR.delete(e))};let g=0,w=!0;d.onerror=e=>{w&&function(e){return e instanceof SyntaxError||"ZodError"===e.name}(e)&&(g+=1)};const y=new AbortController,v=p.connect(d,{timeout:f,signal:y.signal});let b;m=d.pid??void 0,void 0!==m&&(i=m,HR.add(i),qR||(qR=!0,process.on("exit",zR)));const S=new Promise(((e,r)=>{b=setTimeout((()=>r(new Error(`MCP server connection timed out after ${f}ms: ${t}`))),f)}));try{await Promise.race([v,S])}catch(e){throw y.abort(),v.catch((()=>{})),await d.close().catch((()=>{})),await h.waitForFlush(),g>0&&e instanceof Error&&(e.message=`${e.message}; non-JSON-RPC output on stdout before initialize (${String(g)} line${1===g?"":"s"})`),function(e,t){if(""===t)return e;const r=e instanceof Error?e:new Error(String(e));return r.message=`${r.message}; stderr: ${t}`,AR.set(r,t),r}(e,h.read())}finally{w=!1,void 0!==b&&clearTimeout(b)}return new JR(t,p,{initialState:{kind:"ready"},config:r,stdioServer:void 0!==m,serverSignals:gR(d)})}catch(e){s.error=e,s.hasError=!0}finally{MR(s)}var i,a,c}terminateSessionOnClose(e){this._sessionTermination=e}setToolCallRequestOptions(e){this._toolCallRequestOptions=e}failToolCallInFlight(e){const t=this._toolCallInFlight;return void 0!==t&&!t.signal.aborted&&(t.abort(e),!0)}onServerSignal(e){return this._serverSignals?.subscribe(e)??(()=>{})}setToolCallOutputSchemaPassthrough(e){this._toolCallOutputSchemaPassthrough=e}async close(){if(this._closeRequested=!0,this._terminatingSession)return;const e=this._sessionTermination,t=this.client.transport;if(void 0!==e&&t instanceof pR.j)return this._terminatingSession=!0,void(async()=>{await async function(e,t){const r=await async function(e,t){if(void 0===e.sessionId)return{outcome:"no_session",durationMs:0};const r=Date.now(),n=e.terminateSession();n.catch((()=>{}));try{await(0,Or.wj)(n,t.timeoutMs)}catch(e){const t=Date.now()-r;return e instanceof Or.MU?{outcome:"timeout",durationMs:t}:e instanceof pR.b&&void 0!==e.code&&e.code>0?{outcome:"rejected",durationMs:t,httpStatus:e.code,error:e.message}:{outcome:"failed",durationMs:t,error:String(e)}}const o=t.deleteObserver?.lastDeleteStatus;return{outcome:405===o?"unsupported":"terminated",durationMs:Date.now()-r,...void 0!==o?{httpStatus:o}:{}}}(e,t);try{t.onResult?.(r)}catch{}return r}(t,e),await this.client.close()})().catch((()=>{}));await this.client.close()}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=$R(t,(0,$.VI)(e.withName("McpSdkClient.getTools")),!1);if(r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("mcp.transport",LR(this.config)),"requires_authentication"===this.stateValue.kind)return r.span.setAttribute("mcp.tools.requires_authentication",!0),[];if("error"===this.stateValue.kind)return[];const n=++this._toolListGeneration;let o=0,s=0;try{const e=await this.tools.get((async()=>{let e;const t=await lR({fetchPage:async t=>{o++;const n=await async function(e,t,r){try{const r=await e.listTools({cursor:t});return{tools:r.tools,nextCursor:r.nextCursor,meta:r._meta,...bR}}catch(c){if(!(c instanceof Error&&"issues"in c&&Array.isArray(c.issues)))throw c}const n=await e.request({method:"tools/list",params:{cursor:t}},vR),o=[];let s=0,i=0,a=0;for(const e of n.tools){let t=e;if(PR(e)){const r=e.inputSchema;ER(r)&&(t=xR(e,r),s++)}let n=Mx.Dn.safeParse(t);if(!n.success&&(c=n.error).issues.some((e=>"outputSchema"===e.path[0]))){const o=Mx.Dn.safeParse(CR(t));o.success&&(a++,r(SR(e),kR(n.error),"output_stripped"),n=o)}n.success?o.push(n.data):(i++,r(SR(e),_R(n.error.issues),"dropped"))}var c;return{tools:o,nextCursor:"string"==typeof n.nextCursor?n.nextCursor:void 0,meta:n._meta,typeFilled:s,toolDropped:i,outputStripped:a}}(this.client,t,((e,t,n)=>{(function(e,t,r){const n=JSON.stringify([e,t,r]);if(XR.has(n))return XR.delete(n),XR.add(n),!1;if(XR.add(n),XR.size>256){const e=XR.keys().next().value;void 0!==e&&XR.delete(e)}return!0})(n,this.serverName,e??"")&&DR.warn(r.ctx,"output_stripped"===n?"Removed an MCP tool output schema the client rejected":"Left out an MCP tool whose definition is invalid",{serverName:this.serverName,..."string"==typeof e?{toolName:e}:{},issues:t})}));return s+=n.typeFilled,QR(r.ctx,"type_filled",n.typeFilled),QR(r.ctx,"tool_dropped",n.toolDropped),QR(r.ctx,"output_stripped",n.outputStripped),e??=function(e){if(!jC(e))return;const t=e.mcpAllowlist;if(!jC(t)||"string"!=typeof t.list)return;const r=UC(t.name,200),n=UC(t.reason,200);if(void 0===r||void 0===n)return;const o={list:"local"===t.list||"cloud"===t.list?t.list:"other",name:r,reason:n},s=BC(t.allowedServerNames)??BC(t.allowedServers);void 0!==s&&(o.allowedServers=s);const i=BC(t.blockedServers);return void 0!==i&&(o.blockedServers=i),o}(n.meta),n},itemsOf:e=>e.tools,nextCursorOf:e=>e.nextCursor});return this._allowlistInUse=this.reportsCursorMcpAllowlist()?e:void 0,t.map((e=>({...e,inputSchema:XC(e.inputSchema),outputSchema:void 0===e.outputSchema?void 0:XC(e.outputSchema)})))}));return this.noteToolListSuccess(),r.span.setAttribute("mcp.tools.fetched",o>0),r.span.setAttribute("mcp.tools.pages",o),o>0&&r.span.setAttribute("mcp.tools.type_filled",s),r.span.setAttribute("mcp.tools.count",e.length),e}catch(e){const t=GR(e);if(r.span.setAttribute("mcp.tools.fetched",o>0),r.span.setAttribute("mcp.tools.pages",o),o>0&&r.span.setAttribute("mcp.tools.type_filled",s),this.noteToolListFailure(r.ctx,t,n),t instanceof uR.D_&&n===this._toolListGeneration&&n>this._toolListStateGeneration&&"ready"===this.stateValue.kind){const e=this.stateValue,r=this._authProvider?.lastRedirectUrl?.toString()??"";this.stateValue={kind:"requires_authentication",url:r,callback:e=>this.completeRuntimeAuthorization(e)},this.discardToolListError(),this._logStateTransition(e,this.stateValue,"runtime_unauthorized",{...kP(t,this._redactLogText)}),this._stateEnteredAtMs=Date.now()}throw t}}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async getAllowlistInUse(){return this._allowlistInUse}reportsCursorMcpAllowlist(){return void 0!==this.config&&"url"in this.config&&LC(this.config.url)}toolListAttemptIsCurrent(e){return e>this._toolListSuccessGeneration&&e>this._toolListStateGeneration}noteToolListSuccess(){this._toolListError=void 0,this._toolListSuccessGeneration=this._toolListGeneration}discardToolListError(){this._toolListError=void 0,this._toolListStateGeneration=this._toolListGeneration}noteToolListFailure(e,t,r){const n=Mx.O4.MethodNotFound;if(t instanceof Mx.Nh&&t.code===n&&void 0===this.client.getServerCapabilities()?.tools)return void this.noteToolListSuccess();if(t instanceof uR.D_||!this.toolListAttemptIsCurrent(r))return;const o=function(e){if(e instanceof Mx.Nh)return{descriptor:`McpError ${e.code}`,errorClass:"McpError",jsonRpcCode:e.code};if(e instanceof pR.b||e instanceof dR._){const t=e instanceof pR.b?"StreamableHTTPError":"SseError",r="number"==typeof e.code?e.code:void 0;return{descriptor:void 0===r?t:`${t} ${r}`,errorClass:t,...void 0===r?{}:{httpStatus:r}}}return e instanceof Error?{descriptor:"Error",errorClass:"Error"}:{descriptor:"unknown",errorClass:"unknown"}}(t);o.descriptor!==this._toolListError&&DR.warn(e,"MCP server failed to list its tools",{serverName:this.serverName,errorClass:o.errorClass,...void 0!==o.jsonRpcCode?{jsonRpcCode:o.jsonRpcCode}:{},...void 0!==o.httpStatus?{httpStatus:o.httpStatus}:{}}),this._toolListError=o.descriptor}async callTool(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{const a=$R(s,(0,$.VI)(e.withName("McpSdkClient.callTool")),!1);a.span.setAttribute("toolName",t),a.span.setAttribute("serverName",this.serverName),a.span.setAttribute("mcp.transport",LR(this.config));const c=this._callToolLock,l=this._callToolQueueDepth;let u;this._callToolQueueDepth++,this._callToolLock=new Promise((e=>{u=e}));try{{const e={stack:[],error:void 0,hasError:!1};try{const t=$R(e,(0,$.VI)(a.ctx.withName("McpSdkClient.callTool.lockWait")),!1);t.span.setAttribute("serverName",this.serverName),t.span.setAttribute("mcp.call_tool.queued_ahead",l);const r=performance.now();await c;const n=performance.now()-r;t.span.setAttribute("mcp.call_tool.lock_wait_ms",n),a.span.setAttribute("mcp.call_tool.lock_wait_ms",n),a.span.setAttribute("mcp.call_tool.queued_ahead",l)}catch(t){e.error=t,e.hasError=!0}finally{MR(e)}}if("requires_authentication"===this.stateValue.kind)throw new uR.D_(`MCP server "${this.serverName}" requires authentication`);this._currentToolCallId=n,this._currentToolName=t,this._currentElicitationProvider=o;const s=new AbortController;this._toolCallInFlight=s;const u=this._authProvider?.lastRedirectUrl;try{const n={stack:[],error:void 0,hasError:!1};try{const o=$R(n,(0,$.VI)(a.ctx.withName("McpSdkClient.callTool.sdk")),!1);o.span.setAttribute("toolName",t),o.span.setAttribute("serverName",this.serverName);const c=await this.sendToolCall({name:t,arguments:r},s.signal);return o.span.setAttribute("mcp.call_tool.is_error",!0===c.isError),FR(e,this.config,{isError:!0===c.isError}),{content:c.content,isError:!0===c.isError,structuredContent:(i=c.structuredContent,QC(i)),_meta:iE(c._meta)}}catch(e){n.error=e,n.hasError=!0}finally{MR(n)}}catch(t){const r=GR(t);r instanceof Px?(FR(e,this.config,{error:r,httpStatus:r.decision.status}),function(e,t){try{NR.increment(e,1,{decision:t.decision.kind,dropped:String(t.decision.dropped.length>0)})}catch{}}(e,r)):FR(e,this.config,{error:r});const n=r instanceof Px&&"offer"===r.decision.kind&&void 0!==this._authProvider?.lastRedirectUrl&&this._authProvider.lastRedirectUrl!==u;if((r instanceof uR.D_||n)&&"ready"===this.stateValue.kind){const e=this.stateValue,t=this._authProvider?.lastRedirectUrl?.toString()??"";this.stateValue={kind:"requires_authentication",url:t,callback:e=>this.completeRuntimeAuthorization(e)},this.discardToolListError(),this._logStateTransition(e,this.stateValue,n?"scope_step_up":"runtime_unauthorized",{...kP(r,this._redactLogText)}),this._stateEnteredAtMs=Date.now()}throw r}finally{this._toolCallInFlight=void 0,this._currentElicitationProvider=void 0,this._currentToolCallId=void 0,this._currentToolName=void 0}}finally{this._callToolQueueDepth--,c.then(u)}}catch(e){s.error=e,s.hasError=!0}finally{MR(s)}var i}sendToolCall(e,t){const r=this._toolCallRequestOptions?.(e.name),n={...r,signal:void 0===r?.signal?t:AbortSignal.any([r.signal,t])};return!0===this._toolCallOutputSchemaPassthrough?.()?this.client.request({method:"tools/call",params:e},Mx.TF,n):this.client.callTool(e,void 0,n)}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{if($R(t,(0,$.VI)(e.withName("McpSdkClient.getInstructions")),!1).span.setAttribute("serverName",this.serverName),"requires_authentication"===this.stateValue.kind)return;return this.client.getInstructions()??this._resumedInstructions}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{if($R(t,(0,$.VI)(e.withName("McpSdkClient.listResources")),!1),"requires_authentication"===this.stateValue.kind||"error"===this.stateValue.kind)return{resources:[]};const r=this.client.getServerCapabilities();return r?.resources?{resources:await lR({fetchPage:e=>this.client.listResources({cursor:e}),itemsOf:e=>e.resources,nextCursorOf:e=>e.nextCursor})}:{resources:[]}}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{return $R(r,(0,$.VI)(e.withName("McpSdkClient.readResource")),!1),"requires_authentication"===this.stateValue.kind?{contents:[]}:{contents:(await this.client.readResource({uri:t.uri})).contents}}catch(e){r.error=e,r.hasError=!0}finally{MR(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{return $R(t,(0,$.VI)(e.withName("McpSdkClient.listPrompts")),!1),"requires_authentication"===this.stateValue.kind||"error"===this.stateValue.kind?[]:(this.client.getServerCapabilities()??{prompts:!1}).prompts?(await lR({fetchPage:e=>this.client.listPrompts({cursor:e}),itemsOf:e=>e.prompts,nextCursorOf:e=>e.nextCursor})).map((e=>({name:e.name,description:e.description,arguments:e.arguments?.map((e=>({name:e.name,description:e.description,required:e.required})))}))):[]}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async getPrompt(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{return $R(n,(0,$.VI)(e.withName("McpSdkClient.getPrompt")),!1),"requires_authentication"===this.stateValue.kind?{messages:[]}:{messages:(await this.client.getPrompt({name:t,arguments:r})).messages.map((e=>({role:e.role,content:Array.isArray(e.content)?e.content.map((e=>"text"===e.type?{type:"text",text:e.text}:"image"===e.type?{type:"image",data:e.data,mimeType:e.mimeType}:{type:"text",text:JSON.stringify(e)})):[{type:"text",text:"string"==typeof e.content?e.content:JSON.stringify(e.content)}]})))}}catch(e){n.error=e,n.hasError=!0}finally{MR(n)}}getCurrentToolCallContext(){if(this._currentToolName)return{toolName:this._currentToolName,toolCallId:this._currentToolCallId}}async getState(e){return"ready"===this.stateValue.kind&&void 0!==this._toolListError?{kind:"ready",toolListError:this._toolListError}:this.stateValue}async completeRuntimeAuthorization(e){if(!this._authCodeExchange)throw new Error(`MCP server "${this.serverName}" cannot complete authorization: no code exchange is configured for this client.`);try{await this._authCodeExchange(e)}catch(e){const t=e instanceof Error?e.message:"Authentication failed";throw new Error(`Authentication callback failed: ${t}`)}this.updateState({kind:"ready"},"runtime_authorization_completed")}updateState(e,t){const r=this.stateValue;this.discardToolListError(),this.stateValue=e,this._logStateTransition(r,e,t??"explicit_update"),this._stateEnteredAtMs=Date.now()}}const ZR=(0,u.Pu)("mcp_tool.schema",{description:"One MCP tool definition a tools/list repair touched",labelNames:["outcome"]}),XR=new Set;function QR(e,t,r){if(0!==r)try{ZR.increment(e,r,{outcome:t})}catch{}}class YR extends Error{constructor(e,t){super(`MCP server ${e} not found, available servers: ${t.join(", ")}`),this.serverName=e,this.availableServers=t,this.name="McpServerNotFoundError"}}Error,Error;class eI{constructor(e){this.tools=e}async execute(e,t,r,n){const o=this.tools[e];if(!o)throw new vC(e,Object.keys(this.tools));return o.execute(t,r,n)}async executeOn(e,t,r,n,o){const s=this.tools[t];if(!s)throw new vC(t,Object.keys(this.tools));if(s.client===e)return s.execute(r,n,o)}getTools(){return Object.entries(this.tools).map((([e,t])=>({...t.definition,name:e})))}}class tI{async getClients(e){return{}}async getClient(e,t){}async getInstructions(e){return[]}async getToolSet(e){return new eI({})}async getTools(e){return[]}async getToolsForServers(e,t){return[]}}class rI{constructor(e){this.manager=e}async getClients(e){return this.manager.getClients()}async getClient(e,t){return this.manager.getClient(t)}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=$R(t,(0,$.VI)(e.withName("ManagerMcpLease.getInstructions")),!1);return await this.manager.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async getToolSet(e){const t={stack:[],error:void 0,hasError:!1};try{const r=$R(t,(0,$.VI)(e.withName("ManagerMcpLease.getToolSet")),!1);return await this.manager.getToolSet(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=$R(t,(0,$.VI)(e.withName("ManagerMcpLease.getTools")),!1);return(await this.getToolSet(r.ctx)).getTools()}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async getToolsForServers(e,t){const r=new Set(t);return(await this.getTools(e)).filter((e=>r.has(e.clientKey)))}onDidChange(e){return{dispose:this.manager.onDidChange((()=>e(void 0)))}}async reconcileSelection(e,t,r){for(const e of t.removed){const t=this.manager.getClient(e);this.manager.deleteClient(e);try{await(t?.close?.())}catch{}}for(const n of t.added){if(this.manager.getClient(n))continue;const t=await r(e,n);this.manager.setClient(n,t)}}}class nI{constructor(e,t){this.clients=e,this.elicitationFactory=t,this.changeListeners=new Set,this.warnedToolNameCollisions=new Set}onDidChange(e){return this.changeListeners.add(e),()=>{this.changeListeners.delete(e)}}fireDidChange(){for(const e of this.changeListeners)try{e()}catch(e){console.error("Error in McpManager change listener:",e)}}getClients(){return this.clients}getClient(e){return this.clients[e]}setClient(e,t){this.clients[e]=t,this.fireDidChange()}deleteClient(e){delete this.clients[e],this.fireDidChange()}setListingDeadline(e){this.listingDeadlineAt=void 0===e?void 0:performance.now()+e}async closeAllClients(){const e=Object.values(this.clients);await Promise.all(e.map((async e=>{try{await(e.close?.())}catch{}})))}async getToolSet(e){const t={stack:[],error:void 0,hasError:!1};try{const r=$R(t,(0,$.VI)(e.withName("McpManager.getToolSet")),!1),n=$R(t,oI(this.listingDeadlineAt),!1),o=await(0,Or.PH)(Object.entries(this.clients),(([e,t])=>n.within(t,r.ctx,(()=>t.getTools(r.ctx))).then((r=>(r??[]).map((r=>({...r,clientKey:e,clientName:t.serverName,client:t}))))).catch((()=>[]))),{max:n.concurrency}),s=Array.from(o.values()).flat(),i=new Map;for(const e of s){const t=`${e.clientName}-${e.name}`,r=i.get(t);void 0===r?i.set(t,[e]):r.push(e)}const a={};for(const[e,t]of i){const n=t[0];if(void 0===n)continue;if(t.some((e=>e.clientName!==n.clientName||e.name!==n.name))){if(!this.warnedToolNameCollisions.has(e)){this.warnedToolNameCollisions.add(e);const r=t.map((e=>`${e.clientName}/${e.name}`)).join(", ");console.warn("Colliding MCP tool name; exposing neither:",`${e} (${r})`)}continue}const o=t[t.length-1]?.clientKey,s=t.filter((e=>e.clientKey===o)),i=s[0]??n;s.length>1&&!this.warnedToolNameCollisions.has(e)&&(this.warnedToolNameCollisions.add(e),console.warn("MCP server lists a tool name more than once; using the first:",`${i.clientName}/${i.name}`)),a[e]={definition:{...i,clientKey:i.clientKey,providerIdentifier:i.clientName,toolName:i.name},client:i.client,execute:async(e,t,n)=>{const o=n?.createProvider(i.clientName,i.name,t);return await i.client.callTool(r.ctx,i.name,e,t,o)}}}return new eI(a)}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=$R(t,(0,$.VI)(e.withName("McpManager.getInstructions")),!1),n=$R(t,oI(this.listingDeadlineAt),!1),o=await(0,Or.PH)(Object.entries(this.clients),(([e,t])=>n.within(t,r.ctx,(()=>t.getInstructions(r.ctx))).then((e=>e&&0!==e.trim().length?new wn.I0({serverName:t.serverName,instructions:e.trim()}):null)).catch((()=>null))),{max:n.concurrency});return Array.from(o.values()).filter((e=>null!==e))}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}}function oI(e){if(void 0===e)return{concurrency:4,within:(e,t,r)=>r(),[Symbol.dispose]:()=>{}};let t;const r=new Promise((r=>{t=setTimeout((()=>r(void 0)),Math.max(0,e-performance.now()))}));return{concurrency:Number.POSITIVE_INFINITY,within:async(t,n,o)=>{const s=await Promise.race([t.getState(n).catch((()=>{})),r]);if("ready"!==s?.kind)return Promise.race([o(),r]);let i;try{return await Promise.race([o(),new Promise((t=>{i=setTimeout((()=>t(void 0)),Math.max(2e3,e-performance.now()))}))])}finally{clearTimeout(i)}},[Symbol.dispose]:()=>clearTimeout(t)}}function sI(e,t){return function(e){const{logger:t,ctx:r}=e;return{debug:(e,n)=>t.debug(r,e,n),info:(e,n)=>t.info(r,e,n),warn:(e,n)=>t.warn(r,e,n),error:(e,n,o)=>t.error(r,e,n,o)}}({ctx:e,logger:t})}Error;class iI{constructor(e){this.options=e,CP({logger:e.logger,event:"mcp_oauth_provider_initialized",metadata:this.baseMetadata})}get baseMetadata(){return{identifier:this.options.identifier,...this.options.serverUrl?{serverUrl:nP(this.options.serverUrl)}:{}}}async loadTokens(){const e=await this.options.inner.loadTokens();return CP({logger:this.options.logger,event:"mcp_oauth_tokens_loaded",level:"debug",metadata:{...this.baseMetadata,...XP(e)}}),e}async saveTokens(e){await this.options.inner.saveTokens(e),CP({logger:this.options.logger,event:"mcp_oauth_tokens_saved",metadata:{...this.baseMetadata,...XP(e,{expiresInIsFresh:!0})}})}async prepareForRefresh(){CP({logger:this.options.logger,event:"mcp_oauth_refresh_prepare",metadata:this.baseMetadata}),await(this.options.inner.prepareForRefresh?.())}async releaseRefreshLeaseOnError(e){CP({logger:this.options.logger,event:"mcp_oauth_refresh_error_release",level:"warn",error:e,metadata:{...this.baseMetadata,...kP(e,this.options.redactLogText)}}),await(this.options.inner.releaseRefreshLeaseOnError?.(e))}async loadClientInformation(){const e=await this.options.inner.loadClientInformation();return CP({logger:this.options.logger,event:"mcp_oauth_client_info_loaded",level:"debug",metadata:{...this.baseMetadata,...iP(e)}}),e}async saveClientInformation(e){await this.options.inner.saveClientInformation(e),CP({logger:this.options.logger,event:"mcp_oauth_client_info_saved",metadata:{...this.baseMetadata,...iP(e)}})}async invalidateCredentials(e){void 0!==this.options.inner.invalidateCredentials&&(CP({logger:this.options.logger,event:"mcp_oauth_credentials_invalidated",level:"warn",metadata:{...this.baseMetadata,scope:e}}),await this.options.inner.invalidateCredentials(e))}tokenEndpointAuth(e){return this.options.inner.tokenEndpointAuth?.(e)}get loadScopeStepUpRecord(){return this.options.inner.loadScopeStepUpRecord?.bind(this.options.inner)}get saveScopeStepUpRecord(){return this.options.inner.saveScopeStepUpRecord?.bind(this.options.inner)}}class aI{constructor(e,t){this.storage=e,this.identifier=t}async loadTokens(){return this.storage.loadTokens(this.identifier)}async saveTokens(e){return this.storage.saveTokens(this.identifier,e)}async loadClientInformation(){return this.storage.loadClientInformation(this.identifier)}async saveClientInformation(e){return this.storage.saveClientInformation(this.identifier,e)}get loadScopeStepUpRecord(){const{storage:e,identifier:t}=this;return void 0===e.loadScopeStepUpRecord?void 0:()=>e.loadScopeStepUpRecord(t)}get saveScopeStepUpRecord(){const{storage:e,identifier:t}=this;return void 0===e.saveScopeStepUpRecord?void 0:r=>e.saveScopeStepUpRecord(t,r)}}class cI{constructor(e){this.inner=e}async loadTokens(){}async loadClientInformation(){}async saveTokens(e){return this.inner.saveTokens(e)}async saveClientInformation(e){return this.inner.saveClientInformation(e)}async invalidateCredentials(e){await(this.inner.invalidateCredentials?.(e))}get loadScopeStepUpRecord(){return this.inner.loadScopeStepUpRecord?.bind(this.inner)}get saveScopeStepUpRecord(){return this.inner.saveScopeStepUpRecord?.bind(this.inner)}async loadGrantedScope(){return void 0!==this.inner.loadGrantedScope?this.inner.loadGrantedScope():(await this.inner.loadTokens())?.scope}}var lI=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},uI=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const dI=(0,l.h)("DefinitionMcpLoader"),hI=(0,u.Pu)("connector_policy.blocked",{description:"MCP servers a team or org policy refused to load, once per loader and server.",labelNames:["surface","stage","reason"]});function pI(e){const{filePath:t,baseDir:r}=e;return"~"===t||t.startsWith("~/")?s.default.join(o.default.homedir(),t.slice(1)):t.startsWith("./")||"."===t?s.default.resolve(r??process.cwd(),t):t}function fI(e){return"getManagedSlackWorkspaceLists"in e&&"function"==typeof e.getManagedSlackWorkspaceLists}function mI(e){return"getMcpNetworkControlsConfig"in e&&"function"==typeof e.getMcpNetworkControlsConfig}function gI(e){return e?.length??0}function wI(e){if(void 0!==e)return(0,bo.createHash)("sha256").update(TE(e)).digest("hex")}function yI(e){if(void 0===e)return;let t;return r=>(void 0===t&&(t=e(),queueMicrotask((()=>{t=void 0}))),t?QE(r):r)}async function vI(e,t,n,o,s={middlewares:[],configPath:""},i,a,c={},l={}){const u={stack:[],error:void 0,hasError:!1};try{const{middlewares:d,configPath:h}=s,p=lI(u,(0,$.VI)(e.withName("mcp-agent-exec.loadServer")),!1);p.span.setAttribute("serverName",t);const f=!1!==l.mcpAppsUi;p.span.setAttribute("mcpAppsUi",f),dI.info(p.ctx,`Loading MCP server "${t}" ${f?"declaring":"without declaring"} the MCP Apps UI extension`,{event:"mcp_apps_ui_capability",serverName:t,mcpAppsUi:f,transport:"command"in n?"stdio":"http"});let m=async(e,n)=>{const s={stack:[],error:void 0,hasError:!1};try{const u=lI(s,(0,$.VI)(e.withName("loadServer.next")),!1);u.span.setAttribute("serverName",t);const h=u.ctx;if("command"in n){u.span.setAttribute("kind","command");const e=d.find(mI);return await async function(e,t,n,o,s={}){const i=n.cwd?pI({filePath:n.cwd}):void 0;let a,c;if(n.args&&n.args.length>0)a=pI({filePath:n.command,baseDir:i}),c=n.args.map((e=>pI({filePath:e,baseDir:i})));else{const e=(0,YE.A)(n.command);a=pI({filePath:e[0],baseDir:i}),c=e.slice(1).map((e=>pI({filePath:e,baseDir:i})))}const l=n.env??{},{startupTimeoutSec:u}=n,d=await(o?.getMcpNetworkControlsConfig?.({command:[n.command,...n.args??[]].join(" ")})),h=(0,Ob.$H)(d);if(void 0!==h){const{buildMcpSandboxPolicy:n}=await r.e(449).then(r.bind(r,"../mcp-agent-exec/dist/mcp-sandbox-policy.js")),{SandboxUnsupportedError:o,spawnInSandbox:p}=await Promise.resolve().then(r.bind(r,"../shell-exec/dist/api/index.js")),f=i??process.cwd(),m=await n(h,f);dI.info(e,function(e){return`Sandboxing local MCP server "${e.serverName}" with network controls: networkControlsEnabled=${String(!0===e.networkControlsConfig?.enabled)}, mcpNetworkMode=${e.networkControlsConfig?.mcpNetworkMode??"unset"}, mcpNetworkAllowlistCount=${gI(e.networkControlsConfig?.mcpNetworkAllowlist)}, mcpNetworkDenylistCount=${gI(e.networkControlsConfig?.mcpNetworkDenylist)}, localAgentNetworkAllowlistCount=${gI(e.networkControlsConfig?.localAgentNetworkAllowlist)}, sandboxPolicyHash=${wI(e.sandboxNetworkControlsConfig)??"none"}`}({serverName:t,networkControlsConfig:d,sandboxNetworkControlsConfig:h}),function(e){return{event:"mcp_stdio_sandbox_policy",serverName:e.serverName,networkControlsEnabled:!0===e.networkControlsConfig?.enabled,mcpNetworkMode:e.networkControlsConfig?.mcpNetworkMode,mcpNetworkAllowlistCount:gI(e.networkControlsConfig?.mcpNetworkAllowlist),mcpNetworkDenylistCount:gI(e.networkControlsConfig?.mcpNetworkDenylist),localAgentNetworkAllowlistCount:gI(e.networkControlsConfig?.localAgentNetworkAllowlist),sandboxPolicyHash:wI(e.sandboxNetworkControlsConfig)}}({serverName:t,networkControlsConfig:d,sandboxNetworkControlsConfig:h}));try{return await JR.fromCommand(e,t,{command:a,args:c,cwd:i,startupTimeoutSec:u},l,{...s,spawn:(e,t,r)=>p(e,t,r,m)})}catch(e){if(e instanceof o)throw new AE(t,e);throw e}}return!0===d?.enabled&&"no_sandbox"===d.mcpNetworkMode&&(!0===d.win32UserExtensionUnsandbox?dI.info(e,`Starting local MCP server "${t}" without MCP sandboxing`,{event:"mcp_stdio_win32_user_extension_unsandbox",serverName:t}):dI.info(e,`Starting local MCP server "${t}" without MCP sandboxing`)),JR.fromCommand(e,t,{command:a,args:c,cwd:i,startupTimeoutSec:u},l,s)}(h,t,n,e,l)}if("url"in n){u.span.setAttribute("kind","url");const e=i?.(t);return await async function(e,t,r,n,o,s,i,a,c={}){const l=sI(e,dI),u=function(e,t,r){return{logger:{debug:(t,r)=>dI.debug(e,t,r),info:(t,r)=>dI.info(e,t,r),warn:(t,r)=>dI.warn(e,t,r),error:(t,r,n)=>dI.error(e,t,r,n)},metadata:{identifier:t,source:"mcp-agent-exec"},redactLogText:yI(r)}}(e,t,a),d=void 0!==s&&OE(r.url)?FE(globalThis.fetch.bind(globalThis),{managedSlackWorkspaceLists:()=>s.getManagedSlackWorkspaceLists()}):void 0;return JR.fromStreamableHttp(t,r,n,r.headers,o,d,u,l,void 0,void 0,i,!1,c)}(h,t,n,o,e,d.find(fI),a,c.isLinkSharedPaymentTokenLogRedactionEnabled,l)}throw new Error(`Invalid server: ${JSON.stringify(n)}`)}catch(e){s.error=e,s.hasError=!0}finally{uI(s)}};for(const e of d){const r=m;m=async(n,o)=>await e.load(n,t,o,h,r)}try{return await m(p.ctx,n)}catch(e){throw function(e,t){if(void 0===t)return e;!function(e,t){if("object"!=typeof e||null===e)return;const r=AR.get(e);void 0!==r&&AR.set(e,t(r))}(e,t);const r=function(e,t){if(void 0===t)return e;const r={results:new Map,cycled:new Set},n=NE(e,t,r),o=new Map([...r.cycled].flatMap((e=>{const t=r.results.get(e);return t===e?[]:[[e,t]]})));return o.size>0&&function(e,t){const r=new Set,n=[e];for(let e=0;n.length>0&&e({identifier:e,serverConfig:t,configPath:this.configPath})))}}class SI{constructor(e,t,r=[],n={}){this.source=e,this.tokenStorage=t,this.middlewares=r,this.options=n,this.clientCache=new Map}async load(e,t=!0){const r={stack:[],error:void 0,hasError:!1};try{lI(r,(0,$.VI)(e.withName("DefinitionMcpLoader.load")),!1),t||(await this.closeAllCachedClients(),this.source.clearCache?.());const n=await this.source.getDefinitions(e,t);await this.evictClientsOnSandboxPolicyChange(e,n);const o={};return await(0,Or.PH)([...n],(async r=>{try{const n=t?this.clientCache.get(r.identifier):void 0,s=n??await this.loadDefinitionClient(e,r);n||this.clientCache.set(r.identifier,s),o[r.identifier]=s}catch(t){if(this.handleDefinitionLoadError(e,r,t))return;!function(e,t,r,n){const o=yI(n)??(e=>e),s=function(e){if("object"==typeof e&&null!==e)return AR.get(e)}(r);dI.warn(e,"Failed to load MCP server",{identifier:t.identifier,source:t.source,configPath:t.configPath,metadata:t.metadata,errorMessage:o(r instanceof Error?r.message:String(r)),stderrTail:void 0===s?void 0:o(s)})}(e,r,t,this.options.isLinkSharedPaymentTokenLogRedactionEnabled)}}),{max:this.options.maxConcurrency??Math.max(n.length,1)}),new nI(o,this.options.elicitationFactory)}catch(e){r.error=e,r.hasError=!0}finally{uI(r)}}clearClient(e){this.clientCache.delete(e)}clearAllMcpCaches(){this.clientCache.clear()}async evictClientsOnSandboxPolicyChange(e,t){const r=this.middlewares.find(mI);if(!r)return;let n;try{n=JSON.stringify(await Promise.all([...t].sort(((e,t)=>e.identifier.localeCompare(t.identifier))).map((async e=>{const t=await(r.getMcpNetworkControlsConfig?.((n=e.serverConfig,"url"in n?{url:n.url}:{command:[n.command,...n.args??[]].join(" ")})))??{};var n;return[e.identifier,TE(t)]}))))}catch{return}const o=this.sandboxPolicyFingerprint;this.sandboxPolicyFingerprint=n,void 0!==o&&o!==n&&(dI.info(e,"MCP network-controls policy changed; reloading MCP clients to apply the new egress policy"),await this.closeAllCachedClients())}async closeAllCachedClients(){const e=[...this.clientCache.values()];this.clientCache.clear(),await(0,Or.PH)(e,(async e=>{try{await(e.close?.())}catch{}}),{max:Math.max(e.length,1)})}async loadClient(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{lI(n,(0,$.VI)(e.withName("DefinitionMcpLoader.loadClient")),!1);const o=await this.source.getDefinitions(e);if(await this.evictClientsOnSandboxPolicyChange(e,o),!r){const e=this.clientCache.get(t);if(e)return e}const s=o.find((e=>e.identifier===t));if(!s)throw new Error(`MCP server "${t}" not found in config`);let i;try{i=await this.loadDefinitionClient(e,s,r)}catch(t){throw this.handleDefinitionLoadError(e,s,t),t}return r||this.clientCache.set(t,i),i}catch(e){n.error=e,n.hasError=!0}finally{uI(n)}}async loadDefinitionClient(e,t,r){const n=t.authStorageKey??t.identifier,o=new aI(this.tokenStorage,n),s=sI(e,dI),i=new iI({inner:o,logger:s,redactLogText:yI(this.options.isLinkSharedPaymentTokenLogRedactionEnabled),identifier:n,serverUrl:"url"in t.serverConfig?t.serverConfig.url:void 0}),a=r?new cI(i):i;return vI(e,t.identifier,t.serverConfig,a,{middlewares:this.middlewares,configPath:t.configPath??""},this.options.authRedirectUrlGenerator,this.options.scopeChallengeStepUp,{isLinkSharedPaymentTokenLogRedactionEnabled:this.options.isLinkSharedPaymentTokenLogRedactionEnabled})}handleDefinitionLoadError(e,t,r){let n=!1;try{n="handled"===this.options.onDefinitionLoadError?.(e,t,r)}catch(r){dI.warn(e,"MCP definition load error hook failed",{identifier:t.identifier,source:t.source,configPath:t.configPath,metadata:t.metadata,errorMessage:r instanceof Error?r.message:String(r)})}return n||function(e){return e instanceof RC||e instanceof IC||e instanceof TC||e instanceof kI}(r)}}class kI extends Error{constructor(e,t,r){super(r??("teamNetworkAllowlist"===t?`MCP server "${e}" is not on the team network allowlist`:`MCP server "${e}" is blocked by team policy`)),this.serverName=e,this.reason=t,this.name="McpServerBlockedError"}}const _I=[1e3,3e3];class CI{constructor(e){this.blockingService=e,this.countedPolicyBlocks=new Set}async getMcpNetworkControlsConfig(e){return await(this.blockingService.getMcpNetworkControlsConfig?.(e))??{}}async getManagedSlackWorkspaceLists(){return await(this.blockingService.getManagedSlackWorkspaceLists?.())??[]}async load(e,t,r,n,o){const s=function(e){return{command:"command"in e?[e.command,...e.args??[]].join(" "):void 0,url:"url"in e?e.url:void 0}}(r),i=await(this.blockingService.getMcpServerBlockInfo?.(s))??{blocked:await this.blockingService.isServerBlocked(s)};if(i.blocked){const r=i.reason??"teamPolicy";throw"teamPolicy"!==r||this.countedPolicyBlocks.has(t)||(this.countedPolicyBlocks.add(t),hI.increment(e,1,{surface:"desktop",stage:"tool_call",reason:"server_not_allowed"})),new kI(t,r,i.message)}for(let n=0;;n++)try{const t=await o(e,r);return!0===i.hostMcpBridge&&this.blockingService.recordHostMcpBridgeClient?.(t),this.blockingService.recordMcpServerClient?.(t,s),t}catch(e){if(e instanceof ME)throw new kI(t,"teamPolicy",e.message);const r=e instanceof DE?_I[n]:void 0;if(void 0===r)throw e;await(0,Or.cb)(r)}}}class EI extends SI{constructor(e,t,r=[],n={}){super(new bI(e),t,r,n),this.configPath=e}static init(e,t,r=[]){return new EI(t,e,r)}}function xI(e){return"stdio"===e.type&&e.command?{command:e.command,args:e.args??[],env:e.env,cwd:e.cwd}:"streamableHttp"===e.type&&e.url?{url:e.url,headers:e.headers,auth:e.auth,...void 0!==e.tls?{tls:e.tls}:{},...void 0!==e.placement?{placement:e.placement}:{}}:void 0}var PI=r("../utils/dist/private-file.js"),RI=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js");function II(e){const t=RI.VE.safeParse(e);return t.success?t.data:void 0}function TI(e){const t=RI.H5.safeParse(e);return t.success?t.data:void 0}class AI{constructor(e){this.mcpAuthPath=e;const t=AI.mcpAuthPromises.get(e);if(t)this.mcpAuthPromise=t;else{const t=this.loadMcpAuth();this.mcpAuthPromise=t,AI.mcpAuthPromises.set(e,t),t.catch((()=>{AI.mcpAuthPromises.get(e)===t&&AI.mcpAuthPromises.delete(e)}))}AI.saveLocks.has(e)||AI.saveLocks.set(e,Promise.resolve())}async loadMcpAuth(){try{await(0,PI.rV)(this.mcpAuthPath);const e=await(0,Co.readFile)(this.mcpAuthPath,"utf8"),t=JSON.parse(e);if(t&&"object"==typeof t){if(Object.values(t).some((e=>e&&"object"==typeof e&&null!==e&&("access_token"in e||"refresh_token"in e)&&!("tokens"in e)&&!("clientInfo"in e)))){const e={};for(const[r,n]of Object.entries(t)){const t=II(n);void 0!==t&&(e[r]={tokens:t})}return e}const e={};for(const[r,n]of Object.entries(t))n&&"object"==typeof n&&null!==n&&(e[r]={tokens:"tokens"in n?II(n.tokens):void 0,clientInfo:"clientInfo"in n?TI(n.clientInfo):void 0,..."scopeStepUp"in n?{scopeStepUp:n.scopeStepUp}:{}});return e}return{}}catch(e){if(e instanceof Error&&e.message.includes("ENOENT"))return{};throw e}}async loadTokens(e){const t=await this.mcpAuthPromise;return t[e]?.tokens}async saveTokens(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),r[e].tokens=t,await this.saveMcpAuth(r)}))}async loadClientInformation(e){const t=await this.mcpAuthPromise;return t[e]?.clientInfo}async withSaveLock(e){const t=AI.saveLocks.get(this.mcpAuthPath)??Promise.resolve();let r;AI.saveLocks.set(this.mcpAuthPath,new Promise((e=>{r=e})));try{return await t,await e()}finally{r()}}async saveClientInformation(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),r[e].clientInfo=t,await this.saveMcpAuth(r)}))}async loadScopeStepUpRecord(e){const t=await this.mcpAuthPromise;return t[e]?.scopeStepUp}async saveScopeStepUpRecord(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),void 0===t?delete r[e].scopeStepUp:r[e].scopeStepUp=t,await this.saveMcpAuth(r)}))}async deleteCredentials(e){await this.withSaveLock((async()=>{const t=await this.mcpAuthPromise;e in t&&(delete t[e],await this.saveMcpAuth(t))}))}async saveMcpAuth(e){await(0,PI.Pl)(this.mcpAuthPath,JSON.stringify(e,null,2))}}AI.mcpAuthPromises=new Map,AI.saveLocks=new Map,(0,y.cF)(Symbol("execHookConversationId"),void 0),(0,y.cF)(Symbol("execHookGenerationId"),void 0),(0,y.cF)(Symbol("execHookModel"),void 0);const $I=(0,y.cF)(Symbol("execHookWorkspaceRoots"),void 0);var MI=r("../proto/dist/generated/agent/v1/write_exec_pb.js"),DI=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},OI=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const FI=(0,u.Pu)("mcp.filesystem.divergence",{description:"Divergence detected between MCP lease state and filesystem state",labelNames:["divergence_type","mcp_source","configured_servers","mcp_version"]}),NI=(0,u.Pu)("mcp.filesystem.sync_check",{description:"MCP filesystem sync check executed",labelNames:["synced","mcp_source","configured_servers","mcp_version"]}),LI=(0,u.wt)("mcp.filesystem.sync_check.expected_servers",{description:"Number of expected MCP servers at last sync check",labelNames:["mcp_source","mcp_version"]}),jI=(0,u.wt)("mcp.filesystem.sync_check.actual_servers",{description:"Number of actual MCP servers on disk at last sync check",labelNames:["mcp_source","mcp_version"]}),UI=(0,u.wt)("mcp.filesystem.sync_check.servers_missing",{description:"Number of expected MCP servers missing from disk at last sync check",labelNames:["mcp_source","mcp_version"]}),BI=(0,u.wt)("mcp.filesystem.sync_check.tool_mismatches",{description:"Number of MCP servers with tool count mismatches at last sync check",labelNames:["mcp_source","mcp_version"]}),WI=(0,l.h)("McpFileSystemWriter"),HI="mcpFsStructuredLogOptIn";function qI(e,t){return t?.includeStructuredLogs?{...e??{},[HI]:!0}:e}const zI={debug(e,t,r,n){WI.debug(e,t,qI(r,n))},info(e,t,r,n){WI.info(e,t,qI(r,n))},warn(e,t,r,n){WI.warn(e,t,qI(r,n))},error(e,t,r,n,o){WI.error(e,t,r,qI(n,o))}},GI="mcps",VI="tools",KI="~staging",JI="~prev",ZI=[25,50,100,200],XI=new Set(["EPERM","EBUSY","EACCES"]),QI=new Map;function YI(e){return e.slice(0,e.indexOf("~"))}function eT(e,t){return`${e}~${Date.now()}-${process.pid}-${(0,bo.randomBytes)(4).toString("hex")}${t}`}const tT=/~(\d+)-\d+-[0-9a-f]+~(?:staging|prev)$/;async function rT(e,t){const r=tT.exec(t),n=r?Number(r[1]):0;try{const{mtimeMs:r}=await(0,Co.stat)((0,s.join)(e,t));return Date.now()-Math.max(n,r)>6e4}catch{return!1}}const nT="mcp_auth",oT="Authenticate this MCP server so its tools can be used. Call this tool through your MCP tool-calling interface when STATUS.md indicates this server needs authentication.",sT="# >>> CURSOR MANAGED BLOCK >>>",iT="# <<< CURSOR MANAGED BLOCK <<<",aT=["# Ignore everything in .cursor","*","# Un-ignore projects so we can descend to allowlisted subdirs","!projects/","projects/*","!projects/*/","projects/*/*","# MCP tool descriptors, resources, prompts","!projects/*/mcps/","!projects/*/mcps/**","# Agent transcripts for citation","!projects/*/agent-transcripts/","!projects/*/agent-transcripts/**","# Terminal output files","!projects/*/terminals/","!projects/*/terminals/**","# Conversation notes (shared scratchpad)","!projects/*/agent-notes/","!projects/*/agent-notes/**","# Large tool output files","!projects/*/agent-tools/","!projects/*/agent-tools/**","# Plugin cache (rules, skills, agents)","!plugins/","!plugins/**","# Built-in Cursor skills","!skills-cursor/","!skills-cursor/**","# User's personal skills","!skills/","!skills/**","# User's personal slash commands","!commands/","!commands/**","# User's plan files","!plans/","!plans/**","# Subagent state/transcripts","!subagents/","!subagents/**","# User-level cursor rules","!rules/","!rules/**"].join("\n");function cT(e,t,r=15e3){let n;return Promise.race([e.catch((()=>t)),new Promise((e=>{n=setTimeout((()=>e(t)),r)}))]).finally((()=>clearTimeout(n)))}function lT(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function uT(e){if(void 0===e)return;const t=e.trim();return t.length>0?t:void 0}function dT(e){switch(e.kind){case"loading":return"initializing";case"requires_authentication":return"needsAuth";case"ready":return"connected";case"error":return"error";default:return"disconnected"}}function hT(e){if(Array.isArray(e))return e.map((e=>hT(e)));if(function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e)){const t=Object.entries(e).filter((([,e])=>void 0!==e)).sort((([e],[t])=>et?1:0)).map((([e,t])=>[e,hT(t)]));return Object.fromEntries(t)}return e}function pT(e){return JSON.stringify(hT(e))}function fT(e){const t=e.map((e=>({value:e,key:pT(e)})));return t.sort(((e,t)=>e.keyt.key?1:0)),t.map((e=>e.value))}function mT(e){const t=fT(e.tools.map((e=>({name:e.toolName,description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema})))),r=fT(e.resources.map((e=>({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType})))),n=fT(e.prompts.map((e=>({name:e.name,description:e.description,arguments:e.arguments}))));return pT({id:e.serverIdentifier,name:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,tools:t,resources:r,prompts:n,instructions:e.instructions,status:e.status})}class gT{constructor(e,t,r){this.cachedFingerprints=new Map,this.disposed=!1,this.hasPendingLeaseChangeEvent=!1,this.lastDivergenceCheckMs=0,this.mcpLease=e,this.projectDir=t,this.debounceMs=r?.debounceMs??100,this.mcpAuthCopyOverrides=r?.mcpAuthCopyOverrides,this.exposeVirtualMcpAuthTool=r?.exposeVirtualMcpAuthTool??!0,this.alwaysExposeVirtualMcpAuthTool=r?.alwaysExposeVirtualMcpAuthTool??!1,this.snapshotProvider=r?.snapshotProvider,this.mcpVersion=r?.mcpVersion??(this.snapshotProvider?"snapshots":"v1"),this.onDidWrite=r?.onDidWrite,this.ctx=this.getContext(r?.loggerBackend),this.startupCleanupPromise=this.cleanupStaleStagingDirs(this.ctx),this.leaseChangeDisposable=this.mcpLease.onDidChange((e=>{zI.info(this.ctx,"Lease change event received",{serverIdentifiers:e?.serverIdentifiers,reason:e?.reason}),this.onLeaseChanged(this.ctx,e)})),zI.info(this.ctx,"Constructor: scheduling initial write"),this.scheduleWrite(this.ctx),this.ensureCursorDirGitignore()}ensureCursorDirGitignore(){(async function(e){const t=(0,s.join)(e,".gitignore"),r=`${sT}\n${aT}\n${iT}\n`;let n;await(0,Co.mkdir)(e,{recursive:!0});try{n=await(0,Co.readFile)(t,"utf-8")}catch(e){if("ENOENT"!==Sc(e))throw e}if(void 0===n)return void await(0,Co.writeFile)(t,r);const o=n.indexOf(sT),i=n.indexOf(iT,o+30);if(-1===o||-1===i)await(0,Co.writeFile)(t,r);else{const e=`${n.slice(0,o)}${r}${n.slice(i+30).replace(/^\n/,"")}`;e!==n&&await(0,Co.writeFile)(t,e)}})((0,s.join)((0,o.homedir)(),".cursor")).catch((e=>{zI.warn(this.ctx,"Failed to ensure ~/.cursor/.gitignore",e)}))}async cleanupStaleStagingDirs(e){const t=this.getLogContext(e),r=(0,s.join)(this.projectDir,GI);try{const e=await(0,Co.readdir)(r);await Promise.allSettled(e.filter((e=>e.endsWith(KI))).map((async e=>{await rT(r,e)&&await(0,Co.rm)((0,s.join)(r,e),{recursive:!0,force:!0})})))}catch(e){"ENOENT"!==Sc(e)&&zI.error(t,"Error clearing stale mcps staging dirs",e)}}onLeaseChanged(e,t){if(this.disposed)return;const r=t??{serverIdentifiers:void 0};this.hasPendingLeaseChangeEvent?this.pendingLeaseChangeEvent=function(...e){const[t,r]=e;return e.length<2?t:Qn(r)?{serverIdentifiers:void 0,reason:t?.reason??r?.reason}:void 0===t?r:Qn(t)?{serverIdentifiers:void 0,reason:t.reason??r?.reason}:{serverIdentifiers:[...new Set([...t.serverIdentifiers??[],...r?.serverIdentifiers??[]])],reason:t.reason??r?.reason}}(this.pendingLeaseChangeEvent??{serverIdentifiers:void 0},r):(this.pendingLeaseChangeEvent=r,this.hasPendingLeaseChangeEvent=!0),void 0!==this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout((()=>{this.debounceTimer=void 0;const t=this.takePendingLeaseChangeEvent();this.scheduleWrite(e,t)}),this.debounceMs)}takePendingLeaseChangeEvent(){if(!this.hasPendingLeaseChangeEvent)return;const e=this.pendingLeaseChangeEvent??{serverIdentifiers:void 0};return this.pendingLeaseChangeEvent=void 0,this.hasPendingLeaseChangeEvent=!1,e}scheduleWrite(e,t){const r=this.getLogContext(e);if(this.disposed)return;const n=this.writePromise;this.writePromise=(async()=>{if(n)try{await n}catch(e){zI.error(r,"Error waiting for previous write",e)}this.disposed||(await this.startupCleanupPromise,this.disposed||await this.fetchAndWrite(e,t))})()}getContext(e){let t=(0,y.q6)();return e&&(t=t.with(l._O,e)),t}getLogContext(e){return e.with(l._O,this.ctx.get(l._O))}getMetricTags(e){return{...e,mcp_version:this.mcpVersion}}getMcpAuthToolDescription(){return uT(this.mcpAuthCopyOverrides?.authToolDescription)??oT}shouldExposeVirtualMcpAuthToolForStatus(e,t){return this.exposeVirtualMcpAuthTool&&Vn(e)&&(this.alwaysExposeVirtualMcpAuthTool||"needsAuth"===t)}getErrorStatusMessage(){return uT(this.mcpAuthCopyOverrides?.errorStatusMessage)??"The MCP server errored. If this server is important for completing the task, concisely inform the user and ask them to check the MCP status in Cursor's Customize page > MCPs; otherwise continue with a different approach."}getNeedsAuthStatusMessage(e){return t=uT(this.mcpAuthCopyOverrides?.needsAuthStatusMessageWithAuthTool)??'The MCP server needs authentication. Authenticate it by calling the `{authToolName}` tool for server "{serverIdentifier}" through your MCP tool-calling interface using an empty arguments object. If this server is important for completing the task, authenticate it first; otherwise continue with a different approach.',r={serverIdentifier:e,authToolName:nT},t.replace(/\{serverIdentifier\}/g,r.serverIdentifier).replace(/\{authToolName\}/g,r.authToolName);var t,r}getNeedsAuthStatusMessageForWrite(e){return this.exposeVirtualMcpAuthTool&&Vn(e)?this.getNeedsAuthStatusMessage(e):uT(this.mcpAuthCopyOverrides?.needsAuthStatusMessageWithoutVirtualTool)??"This MCP server requires authentication before its tools can be used. Open Cursor's Customize page > MCPs, select this server, and use Authenticate/Reopen, or refresh credentials in your MCP configuration (for example mcp.json), then restart this environment. If this server is not required for the task, continue without it."}async getToolsForServers(e,t){if(0===t.length)return[];const r=this.getLogContext(e);try{return await this.mcpLease.getToolsForServers(e,t)}catch(n){zI.warn(r,`getToolsForServers() threw, falling back to filtered getTools(): ${kc(n)}`);const o=await this.mcpLease.getTools(e).catch((e=>(zI.warn(r,`getTools() threw during scoped-tool fallback, defaulting to []: ${e}`),[]))),s=new Set(t);return o.filter((e=>s.has(e.clientKey)))}}async fetchClientDataForServer(e,t,r,n){const o=await cT(r.getState(e),{kind:"error"}).then((r=>("error"!==r.kind||"message"in r||zI.warn(e,`getState() timed out for "${t}", defaulting to error`),r))),s="ready"===o.kind||"requires_authentication"===o.kind,[i,a,c]=await Promise.all([s?cT(r.listResources(e),{resources:[]}):Promise.resolve({resources:[]}),s?cT(r.listPrompts(e),[]):Promise.resolve([]),s&&n?.fetchInstructions?cT(r.getInstructions(e),void 0):Promise.resolve(void 0)]);return{clientKey:t,serverName:r.serverName,plugin:r.plugin,marketplace:r.marketplace,pluginId:r.pluginId,marketplaceId:r.marketplaceId,resources:i.resources.map((e=>({...e,serverIdentifier:t,serverName:r.serverName}))),prompts:a.map((e=>({...e,serverIdentifier:t,serverName:r.serverName}))),instructions:c,status:dT(o)}}buildServerDataMap(e,t,r){const n=new Map;for(const e of t){const t=My(e.clientKey);n.set(e.clientKey,{serverIdentifier:e.clientKey,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,sanitizedId:t,folderPath:(0,s.join)(this.projectDir,GI,t),tools:[],resources:e.resources,prompts:e.prompts,instructions:e.instructions,status:e.status})}for(const t of e){let e=n.get(t.clientKey);if(!e){const r=My(t.clientKey);e={serverIdentifier:t.clientKey,serverName:t.providerIdentifier,plugin:t.plugin,marketplace:t.marketplace,pluginId:t.pluginId,marketplaceId:t.marketplaceId,sanitizedId:r,folderPath:(0,s.join)(this.projectDir,GI,r),tools:[],resources:[],prompts:[],instructions:void 0,status:void 0},n.set(t.clientKey,e)}e.tools.push(t)}if(void 0!==r)for(const e of r){const t=e.serverIdentifier?.trim();let r=t?Array.from(n.values()).find((e=>e.serverIdentifier===t)):void 0;if(!r){const t=e.serverName?.trim();r=t?Array.from(n.values()).find((e=>e.serverName===t)):void 0}r&&e.instructions&&(r.instructions=e.instructions)}if(this.exposeVirtualMcpAuthTool)for(const e of n.values())this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&(e.tools.some((e=>e.toolName===nT))||e.tools.push({clientKey:(o={serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,authToolDescription:this.getMcpAuthToolDescription()}).serverIdentifier,providerIdentifier:o.serverName,plugin:o.plugin,marketplace:o.marketplace,pluginId:o.pluginId,marketplaceId:o.marketplaceId,toolName:nT,name:nT,description:o.authToolDescription,inputSchema:{type:"object",properties:{},additionalProperties:!1}}));var o;return n}buildServersToWrite(e,t){const r=[],n=new Set;for(const o of t.values()){const t=o.tools.length>0||o.resources.length>0||o.prompts.length>0||o.instructions,s="error"===o.status||"needsAuth"===o.status||"initializing"===o.status;t||s?n.has(o.sanitizedId)?zI.warn(e,`Skipping server "${o.serverIdentifier}" — sanitizedId "${o.sanitizedId}" collides with another server`):(n.add(o.sanitizedId),r.push(o)):zI.info(e,`Server "${o.serverIdentifier}" excluded from write: tools=${o.tools.length}, resources=${o.resources.length}, prompts=${o.prompts.length}, hasInstructions=${!!o.instructions}, status=${o.status}`)}return r}mergeScopedRefreshWithCachedServerData(e,t){const r=[...t.tools];if(this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&!r.some((e=>e.toolName===nT))){const t=e.tools.find((e=>e.toolName===nT));void 0!==t&&r.push(t)}return{...e,...t,tools:r,resources:e.resources,prompts:e.prompts,instructions:e.instructions,status:e.status,plugin:t.plugin??e.plugin,marketplace:t.marketplace??e.marketplace,pluginId:t.pluginId??e.pluginId,marketplaceId:t.marketplaceId??e.marketplaceId}}async refreshServersFromLease(e,t){const r=this.getLogContext(e),n=[...new Set(t.serverIdentifiers??[])];zI.info(r,`fetchAndWrite: refreshing ${n.length} targeted servers`,{serverIdentifiers:n});const o=await this.getToolsForServers(e,n),s=await this.mcpLease.getInstructions(e).catch((e=>(zI.warn(r,`getInstructions() threw during scoped refresh, defaulting to []: ${e}`),[]))),i=await Promise.all(n.map((async t=>{try{const r=await this.mcpLease.getClient(e,t);return void 0===r?{serverIdentifier:t,kind:"missing"}:{serverIdentifier:t,kind:"client",client:r}}catch(e){return zI.warn(r,`getClient("${t}") threw during scoped refresh, preserving cached data: ${kc(e)}`),{serverIdentifier:t,kind:"error",error:e}}}))),a=i.filter((e=>"missing"===e.kind)).map((e=>e.serverIdentifier));let c=new Set;if(a.length>0){const t=await this.mcpLease.getClients(e).catch((e=>{zI.warn(r,`getClients() threw while confirming targeted server removal, preserving cached data: ${e}`)}));void 0!==t&&(c=new Set(a.filter((e=>void 0===t[e]))))}const l=await Promise.all(i.filter((e=>"client"===e.kind)).map((({serverIdentifier:t,client:r})=>this.fetchClientDataForServer(e,t,r,{fetchInstructions:!0})))),u=new Map((this.cachedServerData??[]).map((e=>[e.serverIdentifier,e]))),d=this.buildServerDataMap(o,l,s),h=new Set(n),p=new Set(i.filter((e=>"error"===e.kind||"missing"===e.kind&&!c.has(e.serverIdentifier))).map((e=>e.serverIdentifier)));for(const e of n){const t=u.get(e),n=d.get(e);if(void 0===n)c.has(e)?u.delete(e):zI.warn(r,`refreshServersFromLease: preserving cached data for "${e}" because targeted refresh returned no replacement`);else{if(p.has(e)&&void 0!==t){u.set(e,this.mergeScopedRefreshWithCachedServerData(t,n)),zI.warn(r,`refreshServersFromLease: preserving cached metadata for "${e}" because the client was unavailable during targeted refresh`);continue}u.set(e,n)}}const f=new Map(Array.from(u.values()).map((e=>[e.sanitizedId,e.serverIdentifier])));for(const[e,t]of this.cachedFingerprints)if(!h.has(e)&&!u.has(e)){const t=My(e);f.set(t,e)}const m=this.buildServersToWrite(e,u);await this.writeServerData(e,m,f),this.cachedServerData=m,this.fireOnDidWrite(m)}async fetchAndWrite(e,t){const r={stack:[],error:void 0,hasError:!1};try{DI(r,(0,$.VI)(e.withName("McpFileSystemWriter.fetchAndWrite")),!1);const n=this.getLogContext(e);try{if(void 0!==this.cachedServerData&&void 0!==t&&!Qn(t)&&[...new Set(t.serverIdentifiers??[])].length>0)return void await this.refreshServersFromLease(e,t);const[r,o,s]=await Promise.all([this.mcpLease.getTools(e).catch((e=>(zI.warn(n,`getTools() threw, defaulting to []: ${e}`),[]))),this.mcpLease.getInstructions(e).catch((()=>[])),this.mcpLease.getClients(e).catch((e=>(zI.warn(n,`getClients() threw, defaulting to {}: ${e}`),{})))]),i=Object.keys(s);zI.info(n,`fetchAndWrite: lease returned ${r.length} tools across ${i.length} clients`);const a=Object.entries(s).map((([t,r])=>this.fetchClientDataForServer(e,t,r))),c=await Promise.all(a),l=this.buildServerDataMap(r,c,o),u=this.buildServersToWrite(e,l),d=new Map(Array.from(l.values()).map((e=>[e.sanitizedId,e.serverIdentifier])));await this.writeServerData(e,u,d),this.cachedServerData=u,this.fireOnDidWrite(u)}catch(e){zI.error(n,"Error fetching/writing MCP state",e)}}catch(e){r.error=e,r.hasError=!0}finally{OI(r)}}fireOnDidWrite(e){if(this.onDidWrite)try{const t=e.map((e=>({serverIdentifier:e.serverIdentifier,folderPath:e.folderPath,tools:e.tools.map((t=>({toolName:t.toolName,definitionPath:(0,s.join)(e.folderPath,VI,`${lT(t.toolName)}.json`)})))})));this.onDidWrite(t)}catch{}}async writeServerData(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{DI(n,(0,$.VI)(e.withName("McpFileSystemWriter.writeServerData")),!1);const o=this.getLogContext(e),i=(0,s.join)(this.projectDir,GI);await(0,Co.mkdir)(i,{recursive:!0});const a=new Map;for(const e of t)try{a.set(e.serverIdentifier,mT(e))}catch(t){zI.error(o,"Error computing server fingerprint, will force write",t,{serverIdentifier:e.serverIdentifier}),a.set(e.serverIdentifier,`__error_${Date.now()}_${Math.random()}`)}const c=[];for(const e of t){const t=this.cachedFingerprints.get(e.serverIdentifier);t!==a.get(e.serverIdentifier)&&(c.push(e),void 0!==t&&zI.info(o,`Server "${e.serverIdentifier}" fingerprint changed: tools=${e.tools.length}, status=${e.status}`))}for(const e of t)if(!c.includes(e))try{await(0,Co.stat)((0,s.join)(i,e.sanitizedId))}catch{zI.info(o,`Server "${e.serverIdentifier}" directory missing on disk, forcing write`),c.push(e)}const l=new Set;for(const[e]of this.cachedFingerprints)if(!a.has(e)){const t=this.cachedServerData?.find((t=>t.serverIdentifier===e)),n=t?.sanitizedId??My(e);r.has(n)?(zI.info(o,`Server "${e}" (sanitized="${n}") still in lease but excluded from write, preserving directory`),a.set(e,this.cachedFingerprints.get(e))):(zI.info(o,`Server "${e}" (sanitized="${n}") left the lease, scheduling directory removal`),l.add(n))}const u=void 0===this.cachedServerData;if(u)try{const e=await(0,Co.readdir)(i),t=new Set(e.filter((e=>!e.endsWith(KI)&&!e.endsWith(JI))));for(const r of e){const e=r.endsWith(KI),n=r.endsWith(JI);if((e||n)&&await rT(i,r))if(e)await(0,Co.rm)((0,s.join)(i,r),{recursive:!0,force:!0});else{const e=YI(r);if(t.has(e))await(0,Co.rm)((0,s.join)(i,r),{recursive:!0,force:!0});else try{await(0,Co.rename)((0,s.join)(i,r),(0,s.join)(i,e)),t.add(e)}catch{await(0,Co.rm)((0,s.join)(i,r),{recursive:!0,force:!0}).catch((()=>{}))}}}for(const e of t)if(r.has(e)){const t=r.get(e);a.has(t)||a.set(t,`__preserved_${e}`)}else l.add(e)}catch(e){zI.error(o,"Error clearing mcps directory",e)}const d=Array.from(l);if(c.length>0||l.size>0){const e=c.map((e=>({serverIdentifier:e.serverIdentifier,sanitizedId:e.sanitizedId,toolCount:e.tools.length})));zI.info(o,`Incremental write: ${c.length} changed, ${l.size} removed, ${t.length-c.length} unchanged`,{changedServerCount:c.length,changedServers:e,removedServerCount:l.size,removedServerSanitizedIds:d,unchangedServerCount:t.length-c.length,totalServerCount:t.length,leaseServerCount:r.size,coldStartReconcile:u,projectDirHash:(0,bo.createHash)("sha256").update(this.projectDir).digest("hex")},{includeStructuredLogs:!0})}const h=await Promise.allSettled(c.map((t=>this.writeServerAtomic(e,t,i))));for(let t=0;t(0,Co.rm)((0,s.join)(i,e),{recursive:!0,force:!0}))));for(let r=0;r{await(i?.catch((()=>{}))),await this.swapServerDirectory(e,t,r)})();QI.set(o,a);try{await a}finally{QI.get(o)===a&&QI.delete(o)}}catch(e){n.error=e,n.hasError=!0}finally{OI(n)}}async swapServerDirectory(e,t,r){const n=eT(t.sanitizedId,KI),o=(0,s.join)(r,n),i=(0,s.join)(r,t.sanitizedId);try{await this.writeServerDirectory(e,t,{basePath:r,dirName:n})}catch(e){throw await(0,Co.rm)(o,{recursive:!0,force:!0}).catch((()=>{})),e}const a=(0,s.join)(r,eT(t.sanitizedId,JI));let c=!1;try{try{await this.renameWithRetry(i,a),c=!0}catch(e){if("ENOENT"!==Sc(e))throw e}await this.renameWithRetry(o,i)}catch(r){if(zI.error(e,"Per-server swap failed",r,{serverIdentifier:t.serverIdentifier,sanitizedId:t.sanitizedId},{includeStructuredLogs:!0}),c)try{await this.renameWithRetry(a,i)}catch{await(0,Co.stat)(i).then((()=>!0),(()=>!1))&&await(0,Co.rm)(a,{recursive:!0,force:!0}).catch((()=>{}))}throw await(0,Co.rm)(o,{recursive:!0,force:!0}).catch((()=>{})),r}await(0,Co.rm)(a,{recursive:!0,force:!0}).catch((()=>{}))}async renameWithRetry(e,t){for(let r=0;;r++)try{return void await(0,Co.rename)(e,t)}catch(e){const t=Sc(e);if(r>=ZI.length||void 0===t||!XI.has(t))throw e;await(0,Or.cb)(ZI[r])}}async writeServerDirectory(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{DI(n,(0,$.VI)(e.withName("McpFileSystemWriter.writeServerDirectory")),!1);const o=(0,s.join)(r.basePath,r.dirName??t.sanitizedId);await(0,Co.mkdir)(o,{recursive:!0});const i=[];if(t.tools.length>0){const e=(0,s.join)(o,VI);await(0,Co.mkdir)(e,{recursive:!0});for(const r of t.tools){const t=lT(r.toolName);i.push({path:(0,s.join)(e,`${t}.json`),content:JSON.stringify(Zn(r),null,2)})}}if(t.resources.length>0){const e=(0,s.join)(o,"resources");await(0,Co.mkdir)(e,{recursive:!0});for(const r of t.resources){const t=lT(r.name||r.uri.replace(/[^a-zA-Z0-9_-]/g,"_")),n={uri:r.uri,name:r.name,description:r.description,mimeType:r.mimeType};i.push({path:(0,s.join)(e,`${t}.json`),content:JSON.stringify(n,null,2)})}}if(t.prompts.length>0){const e=(0,s.join)(o,"prompts");await(0,Co.mkdir)(e,{recursive:!0});for(const r of t.prompts){const t=lT(r.name),n={name:r.name,description:r.description,arguments:r.arguments};i.push({path:(0,s.join)(e,`${t}.json`),content:JSON.stringify(n,null,2)})}}t.instructions&&t.instructions.trim().length>0&&i.push({path:(0,s.join)(o,"INSTRUCTIONS.md"),content:t.instructions.trim()}),"error"!==t.status&&"needsAuth"!==t.status||i.push({path:(0,s.join)(o,"STATUS.md"),content:"error"===t.status?this.getErrorStatusMessage():this.getNeedsAuthStatusMessageForWrite(t.serverIdentifier)});const a={serverIdentifier:t.serverIdentifier,serverName:t.serverName};i.push({path:(0,s.join)(o,"SERVER_METADATA.json"),content:JSON.stringify(a,null,2)});if(new Set(i.map((e=>e.path.toLowerCase()))).size!==i.length){for(const e of i)await(0,Co.writeFile)(e.path,e.content);return}const c=(await(0,Or.up)(i,(e=>(0,Co.writeFile)(e.path,e.content)),{max:8})).find((e=>"rejected"===e.status));if(c)throw c.reason}catch(e){n.error=e,n.hasError=!0}finally{OI(n)}}async getMcpFileSystemOptions(e,t){const r={stack:[],error:void 0,hasError:!1};try{if(this.disposed)return;DI(r,(0,$.VI)(e.withName("McpFileSystemWriter.getMcpFileSystemOptions")),!1);const n=this.getLogContext(e),o=await this.ensureWritesSettled(e,t?.timeoutMs);if(this.snapshotProvider&&!o)return this.buildOptionsFromSnapshots(e);this.snapshotProvider&&o&&zI.warn(n,"Snapshot mode write barrier timed out; falling back to cached descriptors",{timeoutMs:t?.timeoutMs},{includeStructuredLogs:!0});const i=(this.cachedServerData??[]).map((e=>{const t=e.tools.map((t=>{const r=lT(t.toolName),n=(0,s.join)(e.folderPath,VI,`${r}.json`);return new wn.E$({toolName:t.toolName,definitionPath:n,...Db(t.annotations)})}));return new wn.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,folderPath:e.folderPath,serverUseInstructions:e.instructions,tools:t})}));return this.checkDescriptorsVsFilesystem(e,i,"workbench_lease"),new wn.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:i})}catch(e){r.error=e,r.hasError=!0}finally{OI(r)}}async ensureWritesSettled(e,t){const r=this.getLogContext(e),n=void 0!==this.debounceTimer;if(void 0!==this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0,this.scheduleWrite(e,this.takePendingLeaseChangeEvent())),n&&zI.info(r,"getMcpFileSystemOptions force-fired pending debounce"),!this.writePromise)return!1;if(void 0!==t){let e,n=!1;try{await Promise.race([this.writePromise,new Promise((r=>{e=setTimeout((()=>{n=!0,r()}),t)}))])}catch(e){zI.error(r,"Error waiting for pending write to complete",e)}finally{clearTimeout(e)}return n&&zI.warn(r,`getMcpFileSystemOptions timed out after ${t}ms waiting for write; returning stale cache`),n}try{await this.writePromise}catch(e){zI.error(r,"Error waiting for pending write to complete",e)}return!1}async buildOptionsFromSnapshots(e){const t={stack:[],error:void 0,hasError:!1};try{DI(t,(0,$.VI)(e.withName("McpFileSystemWriter.buildOptionsFromSnapshots")),!1);const r=this.getLogContext(e),n=Date.now(),o=await this.snapshotProvider.getAllSnapshots(e),i=(0,s.join)(this.projectDir,GI),a=o.filter((e=>e.tools.length>0||e.resources.length>0||e.prompts.length>0||void 0!==e.instructions||this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)||"needsAuth"===e.status||"error"===e.status)).map((e=>{const t=My(e.serverIdentifier),r=(0,s.join)(i,t),n=e.tools.map((e=>{const t=lT(e.name);return new wn.E$({toolName:e.name,definitionPath:(0,s.join)(r,VI,`${t}.json`),...Db(e.annotations)})}));if(this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&!e.tools.some((e=>e.name===nT))){const e=lT(nT);n.push(new wn.E$({toolName:nT,definitionPath:(0,s.join)(r,VI,`${e}.json`)}))}return new wn.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,folderPath:r,serverUseInstructions:e.instructions,tools:n})})),c=a.reduce(((e,t)=>e+t.tools.length),0);return zI.info(r,`buildOptionsFromSnapshots completed in ${Date.now()-n}ms: ${o.length} snapshots, ${a.length} descriptors, ${c} tools`),this.checkDescriptorsVsFilesystem(e,a,"snapshot"),new wn.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:a})}catch(e){t.error=e,t.hasError=!0}finally{OI(t)}}async waitForPendingWrites(){if(void 0!==this.debounceTimer&&await new Promise((e=>{const t=()=>{void 0===this.debounceTimer?e():setTimeout(t,10)};t()})),this.writePromise)try{await this.writePromise}catch{}}getCachedServerData(){return this.cachedServerData}checkDescriptorsVsFilesystem(e,t,r){const n=this.getLogContext(e),o=Date.now();o-this.lastDivergenceCheckMs{zI.warn(n,"Divergence check failed",e)})))}async _checkDescriptorsVsFilesystemAsync(e,t,r){const n=this.getLogContext(e),o=(0,s.join)(this.projectDir,GI),i=new Set,a=new Map;for(const e of t){const t=My(e.serverIdentifier);i.add(t),a.set(t,e.tools.length)}let c=[];try{c=await(0,Co.readdir)(o),c=c.filter((e=>!e.endsWith(KI)&&!e.endsWith(JI)))}catch(e){if("ENOENT"!==Sc(e))throw e}const l=new Set(c);let u=!0,d=0,h=0,p=0;const f=function(e){return 0===e?"0":e<=3?"1-3":e<=6?"4-6":e<=10?"7-10":"11+"}(i.size);for(const t of i)l.has(t)||(u=!1,d++,FI.increment(e,1,this.getMetricTags({divergence_type:"server_missing",mcp_source:r,configured_servers:f})),zI.warn(n,"Divergence detected: server missing from filesystem",{mcpFileSystemMeta:{divergenceType:"server_missing",serverId:t,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}));for(const t of l)i.has(t)||(u=!1,h++,FI.increment(e,1,this.getMetricTags({divergence_type:"server_stale",mcp_source:r,configured_servers:f})));for(const t of i){if(!l.has(t))continue;const c=a.get(t)??0,d=(0,s.join)(o,t,VI);let h=0;try{h=(await(0,Co.readdir)(d)).filter((e=>e.endsWith(".json"))).length}catch{}h!==c&&(u=!1,p++,FI.increment(e,1,this.getMetricTags({divergence_type:"tool_count_mismatch",mcp_source:r,configured_servers:f})),zI.warn(n,"Divergence detected: tool count mismatch",{mcpFileSystemMeta:{divergenceType:"tool_count_mismatch",serverId:t,expected:c,actual:h,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}))}NI.increment(e,1,this.getMetricTags({synced:String(u),mcp_source:r,configured_servers:f})),LI.gauge(e,i.size,this.getMetricTags({mcp_source:r})),jI.gauge(e,l.size,this.getMetricTags({mcp_source:r})),UI.gauge(e,d,this.getMetricTags({mcp_source:r})),BI.gauge(e,p,this.getMetricTags({mcp_source:r})),zI.info(n,"MCP filesystem sync check",{mcpFileSystemMeta:{synced:u,expectedServers:i.size,actualServers:l.size,serversMissing:d,serversStale:h,toolMismatches:p,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}),u||zI.warn(n,"MCP filesystem divergence summary",{mcpFileSystemMeta:{synced:u,expectedServers:i.size,actualServers:l.size,serversMissing:d,serversStale:h,toolMismatches:p,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0})}dispose(){this.disposed||(this.disposed=!0,void 0!==this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.leaseChangeDisposable&&(this.leaseChangeDisposable.dispose(),this.leaseChangeDisposable=void 0),this.cachedServerData=void 0,this.cachedFingerprints.clear())}}gT.DIVERGENCE_CHECK_COOLDOWN_MS=1e4;var wT=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},yT=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function vT(e){if("object"!=typeof e||null===e||Array.isArray(e))return;const t={};for(const[r,n]of Object.entries(e))"string"==typeof n&&(t[r]=n);return t}const bT=(0,l.h)("local-exec:mcp");function ST(e,t){const r=s.default.relative(e,t);return""===r||!s.default.isAbsolute(r)&&".."!==r&&!r.startsWith(`..${s.default.sep}`)}function kT(e){return e instanceof Error&&"code"in e&&"string"==typeof e.code?e.code:void 0}function _T(e){return new Ac._Z({content:{case:"image",value:new Ac.do({data:e.data,mimeType:e.mimeType})}})}function CT(e){return new Ac._Z({content:{case:"text",value:new Ac.zN({text:e})}})}async function ET(e,t,r){const n=await r.permissionsService.shouldBlockMcp(e,t,r.toolDef,{alreadyApproved:t.skipApproval,...void 0===r.client?{}:{client:r.client},...void 0===r.resolvedTool?{}:{resolvedTool:r.resolvedTool}});if(!n)return;const o=await Qu(n,{onNeedsApproval:async(e,n)=>{if("mcp"!==n.type)return new Ac.iz({result:{case:"error",value:new Ac.Nh({error:"Invalid approval details type for MCP execution"})}});const o=await r.pendingDecisionProvider.requestApproval({type:Lw.Mcp,details:{name:n.name,toolName:n.toolName,toolTitle:n.toolTitle,destructiveHint:n.destructiveHint,providerIdentifier:n.providerIdentifier,source:r.toolDef?.source,args:n.args,reason:n.reason??e,canAllowlist:n.canAllowlist,smartModeApprovalReason:n.smartModeApprovalReason,smartModeApprovalRequestId:n.smartModeApprovalRequestId,allowlistEntry:n.allowlistEntry,computerUseApp:n.computerUseApp},toolCallId:t.toolCallId});return o.approved&&void 0!==n.computerUseApp&&!0!==n.computerUseApp.allowOnce&&r.permissionsService.allowComputerUseAppForSession?.({bundleId:n.computerUseApp.bundleId}),o.approved?t.smartModeApprovalOnly?new Ac.iz({result:{case:"approved",value:new Ac.Ke}}):null:new Ac.iz({result:{case:"rejected",value:new Ac.xo({reason:`User rejected MCP: ${t.name}${o.reason?` - ${o.reason}`:""}`})}})},onUserRejected:e=>new Ac.iz({result:{case:"error",value:new Ac.Nh({error:`User rejected MCP: ${t.name}${e?` - ${e}`:""}`})}}),onPermissionDenied:(e,r)=>xT({name:t.name,reason:e,isReadonly:r?.isReadonly??!1})});return o??void 0}function xT({name:e,reason:t,isReadonly:r}){return new Ac.iz({result:{case:"permissionDenied",value:new Ac.HQ({error:`MCP tool execution blocked: ${e} - ${t}`,isReadonly:r})}})}class PT{constructor(e,t,r,n,o=4e4,s,i,a={}){this.toolSet=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.projectDir=n,this.fileOutputThresholdBytes=o,this.elicitationFactory=s,this.ensureMcpServersLoaded=i,this.spillOptions=a}async describeDisconnectedServer(e,t){const r=new Set(t.filter((e=>""!==e)));if(0===r.size)return;let n;try{n=await this.toolSet.getClients(e)}catch{return}const o=Object.entries(n).find((([e,t])=>r.has(e)||r.has(t.serverName)));if(void 0===o)return;const[s,i]=o;let a;try{a=await i.getState(e)}catch{return}if("ready"===a.kind&&void 0===a.toolListError)return;const c=function(e){switch(e){case"needsAuth":return"This MCP server requires authentication before its tools can be used.";case"error":return"This MCP server failed during live tool discovery. Its tools are unavailable until the connection is fixed.";case"loading":return"This MCP server is still loading; tools may not be available yet.";default:return}}(Yn(a));return void 0!==c?`MCP server "${s}" has no callable tools right now. ${c}${"error"===a.kind&&a.message?` (${a.message})`:""}`:void 0}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=wT(r,(0,$.VI)(e.withName("LocalMcpToolExecutor.execute")),!1).ctx,i=t.serverIdentifier||t.providerIdentifier;await(this.ensureMcpServersLoaded?.(o,[i]));const a=await this.toolSet.getTools(o),c=Array.from(new Set(a.map((e=>e.clientKey)))).sort(),l=a.find((e=>e.clientKey===i&&e.toolName===t.toolName)),u=a.find((e=>e.name===t.name));if(void 0!==u&&(void 0!==l?u!==l:u.toolName!==t.toolName||u.clientKey!==i&&u.providerIdentifier!==i))return new Ac.iz({result:{case:"error",value:new Ac.Nh({error:`MCP tool "${t.name}" is not the tool "${t.toolName}" on server "${i}" that the call names.`})}});const d=void 0===l?void 0:await this.toolSet.getClient(o,l.clientKey).catch((()=>{})),h=l??u,p=void 0===h?void 0:h===l?d:await this.toolSet.getClient(o,h.clientKey).catch((()=>{})),f=await ET(o,t,{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionProvider,toolDef:l,...void 0===d?{}:{client:d},...void 0===h?{}:{resolvedTool:void 0===p?"unresolved":{client:p,annotations:h.annotations}}});if(void 0!==f)return f;const m=await this.toolSet.getToolSet(o),g=!0===await(this.permissionsService.enforcesMcpAdminToolLimits?.());let w;try{if(g&&void 0===h)throw new vC(t.name,a.map((e=>e.name)));const e=l?.name??t.name,r=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()])));if(g){const n=void 0===p?void 0:await(m.executeOn?.(p,e,r,t.toolCallId,this.elicitationFactory));if(void 0===n)return bT.warn(o,"Refusing an MCP tool whose client was not judged",{toolName:t.toolName,toolSetNamesClients:void 0!==m.executeOn}),xT({name:t.name,reason:nk,isReadonly:!1});w=n}else w=await m.execute(e,r,t.toolCallId,this.elicitationFactory)}catch(e){let r=e;if(bC(r)&&t.providerIdentifier.length>0&&!a.some((e=>e.clientKey===t.providerIdentifier||e.providerIdentifier===t.providerIdentifier))&&(r=new YR(t.providerIdentifier,c)),r instanceof YR){const e=await this.describeDisconnectedServer(o,[i,t.providerIdentifier]);return void 0!==e?new Ac.iz({result:{case:"error",value:new Ac.Nh({error:e})}}):new Ac.iz({result:{case:"serverNotFound",value:new Ac.JL({name:r.serverName,availableServers:r.availableServers})}})}if(bC(r))return new Ac.iz({result:{case:"toolNotFound",value:new Ac.WV({name:r.toolName,availableTools:r.availableTools})}});throw r}const y=[];for(const e of w.content){const r=e.type;if("text"===r&&"object"==typeof e&&null!==e&&"text"in e&&"string"==typeof e.text)y.push(CT(e.text));else if("resource"===r){const r=oE(e),n=void 0===r?void 0:Buffer.from(r,"base64"),s=void 0===n?void 0:await Lv(n).then(_T,(e=>{bT.warn(o,"Describing an undecodable MCP resource image",{toolName:t.toolName,bytes:n.byteLength,error:e instanceof Error?e.message:String(e)})}));y.push(s??CT(sE(e)))}else if("image"===r){const r=e,s="string"==typeof r.data?Buffer.from(r.data,"base64"):Buffer.alloc(0);let i;try{i=await Lv(s)}catch(e){bT.warn(o,"Omitting undecodable MCP tool image",{toolName:t.toolName,mimeType:"string"==typeof r.mimeType?r.mimeType.slice(0,100):typeof r.mimeType,bytes:s.byteLength,error:e instanceof Error?e.message:String(e)}),y.push(CT(`[Image omitted: the tool returned ${n=r.mimeType,"string"==typeof n&&/^image\/[\w.+-]{1,40}$/.test(n)?n:"image"} data (${s.byteLength} bytes) that could not be decoded.]`));continue}y.push(_T(i))}else if("image"!==r){const t=sE(e);y.push(CT(t))}}const v=await async function({contentItems:e,thresholdBytes:t,write:r}){const n=e.filter((e=>"text"===e.content.case&&void 0===e.content.value.outputLocation)).map((e=>"text"===e.content.case?e.content.value.text:"")).join("\n\n");if(t<=0||Buffer.byteLength(n,"utf8")<=t)return e;const o=await r(n);if(void 0===o)return;const s=[];let i=!1;for(const t of e)"text"===t.content.case&&void 0===t.content.value.outputLocation?i||(s.push(new Ac._Z({content:{case:"text",value:new Ac.zN({text:"",outputLocation:o})}})),i=!0):s.push(t);return s}({contentItems:y,thresholdBytes:this.fileOutputThresholdBytes,write:e=>async function(e,t,r){const n=s.default.join(t,$c),o=s.default.join(n,`${(0,bo.randomUUID)()}.txt`);await(0,Co.mkdir)(s.default.dirname(o),{recursive:!0});const i=Vo(!0===r.blankSharedPaymentTokens?QE(e):e,Mc),a=Js(i),c=Buffer.byteLength(i,"utf8");return await(0,Co.writeFile)(o,i,"utf8"),new Dc.pV({filePath:o,sizeBytes:BigInt(c),lineCount:BigInt(a)})}(e,this.projectDir,this.spillOptions)});if(void 0===v)throw new Error("Failed to materialize MCP text output");const b=w.structuredContent&&"object"==typeof w.structuredContent&&!Array.isArray(w.structuredContent)?we.Struct.fromJson(w.structuredContent):void 0,S=new Ac.QW({content:v,isError:w.isError,structuredContent:b,resultMeta:void 0===w._meta?void 0:we.Struct.fromJson(w._meta)});return new Ac.iz({result:{case:"success",value:S}})}catch(e){r.error=e,r.hasError=!0}finally{yT(r)}var n}}class RT{constructor(e,t){this.mcpLease=e,this.ensureMcpServersLoaded=t}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=wT(r,(0,$.VI)(e.withName("LocalListMcpResourcesExecutor.execute")),!1).ctx;try{if(t.server){await(this.ensureMcpServersLoaded?.(n,[t.server]));const e=await this.mcpLease.getClients(n),r=e[t.server]??Object.values(e).find((e=>e.serverName===t.server));if(!r)return new Ac.kP({result:{case:"error",value:new Ac.w2({error:`Server "${t.server}" not found`})}});const o=await this.listResourcesFromClient(n,r,t.server,!0);return new Ac.kP({result:{case:"success",value:new Ac.T2({resources:o})}})}const e=await this.mcpLease.getClients(n),r=new Set,o=await this.mcpLease.getTools(n);for(const e of o)r.add(e.providerIdentifier),r.add(`user-${e.providerIdentifier}`);const s=[];for(const[t,o]of Object.entries(e)){if(r.size>0&&!r.has(t))continue;const e=await this.listResourcesFromClient(n,o,t);s.push(...e)}return new Ac.kP({result:{case:"success",value:new Ac.T2({resources:s})}})}catch(e){const t=e instanceof Error?e.message:String(e);return new Ac.kP({result:{case:"error",value:new Ac.w2({error:`Failed to list MCP resources: ${t}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{yT(r)}}async listResourcesFromClient(e,t,r,n=!1){const o=await t.getState(e);if("ready"!==o.kind&&(!n||"loading"!==o.kind))return[];const s=await t.listResources(e);return s&&s.resources?s.resources.map((e=>new Ac.X2({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType,server:r,annotations:vT(e.annotations)}))):[]}}class IT{constructor(e,t=".",r,n=[],o,s,i){this.mcpLease=e,this.projectDir=t,this.pendingDecisionProvider=o,this.ensureMcpServersLoaded=s,this.writeExecutor=i,this.workspacePaths=n.filter((e=>e.length>0))}resolveProjectDir(e){const t=e.get($I),r=t?.find((e=>"string"==typeof e&&e.length>0));return r||(this.workspacePaths.length>0?this.workspacePaths[0]:this.projectDir)}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=wT(r,(0,$.VI)(e.withName("LocalReadMcpResourceExecutor.execute")),!1).ctx,o=t.smartModeApproval?.reason;if(void 0!==o){if(void 0===this.pendingDecisionProvider)return new Ac.ZD({result:{case:"error",value:new Ac.Jx({uri:t.uri,error:"Auto-review approval provider is not configured"})}});const e=await this.pendingDecisionProvider.requestApproval({type:Lw.Mcp,details:{name:"FetchMcpResource",toolName:"FetchMcpResource",providerIdentifier:t.server,args:{server:we.Value.fromJson(t.server),uri:we.Value.fromJson(t.uri),...void 0!==t.downloadPath?{downloadPath:we.Value.fromJson(t.downloadPath)}:{}},reason:"smartMode",canAllowlist:!1,smartModeApprovalReason:o,smartModeApprovalRequestId:t.smartModeApproval?.requestId},toolCallId:t.toolCallId});if(!e.approved)return new Ac.ZD({result:{case:"rejected",value:new Ac.Dh({reason:"User rejected MCP resource fetch"+(e.reason?` - ${e.reason}`:"")})}})}await(this.ensureMcpServersLoaded?.(n,[t.server]));const i=await this.mcpLease.getClients(n),a=i[t.server]??Object.values(i).find((e=>e.serverName===t.server));if(!a)return new Ac.ZD({result:{case:"error",value:new Ac.Jx({uri:t.uri,error:`Server "${t.server}" not found`})}});try{if("ready"!==(await a.getState(n)).kind)return new Ac.ZD({result:{case:"error",value:new Ac.Jx({uri:t.uri,error:`Server "${t.server}" is not ready`})}});const e=await a.readResource(n,{uri:t.uri});if(!e||!e.contents||0===e.contents.length)return new Ac.ZD({result:{case:"notFound",value:new Ac.ov({uri:t.uri})}});const r=e.contents[0];if(t.downloadPath){const e=await async function(e,t){const r=s.default.resolve(e),n=await(0,Co.realpath)(r),o=s.default.isAbsolute(t)?s.default.resolve(t):s.default.resolve(r,t),i=ST(r,o),a=s.default.isAbsolute(t)&&ST(n,o);if(!i&&!a)throw new Error("downloadPath must stay within the workspace");let c=s.default.dirname(o);for(;;)try{if(!ST(n,await(0,Co.realpath)(c)))throw new Error("downloadPath must stay within the workspace");break}catch(e){if("ENOENT"!==kT(e))throw e;const t=s.default.dirname(c);if(t===c)throw e;c=t}try{if((await(0,Co.lstat)(o)).isSymbolicLink())throw new Error("downloadPath must stay within the workspace")}catch(e){if("ENOENT"!==kT(e))throw e}return o}(this.resolveProjectDir(n),t.downloadPath);let o=e;if(r.text||r.blob){if(void 0===this.writeExecutor)throw new Error("File-write executor is not configured");const s=await this.writeExecutor.execute(n,new MI.hY({path:e,fileText:r.text??"",fileBytes:r.text||void 0===r.blob?new Uint8Array:new Uint8Array(Buffer.from(r.blob,"base64")),toolCallId:t.toolCallId,confineToWorkspace:!0}));if("rejected"===s.result.case)return new Ac.ZD({result:{case:"rejected",value:new Ac.Dh({uri:t.uri,reason:s.result.value.reason})}});if("success"!==s.result.case)return new Ac.ZD({result:{case:"error",value:new Ac.Jx({uri:t.uri,error:TT(s)})}});o=s.result.value.path}return new Ac.ZD({result:{case:"success",value:new Ac.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,downloadPath:o})}})}if(r.text)return new Ac.ZD({result:{case:"success",value:new Ac.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:vT(r.annotations),metaJson:Jn(r._meta),content:{case:"text",value:r.text}})}});if(r.blob){const e=Buffer.from(r.blob,"base64");return new Ac.ZD({result:{case:"success",value:new Ac.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:vT(r.annotations),metaJson:Jn(r._meta),content:{case:"blob",value:e}})}})}return new Ac.ZD({result:{case:"error",value:new Ac.Jx({uri:t.uri,error:"Failed to read resource"})}})}catch(e){const r=e instanceof Error?e.message:String(e);return bT.warn(n,"LocalReadMcpResourceExecutor.execute failed",{server:t.server,hasDownloadPath:Boolean(t.downloadPath),errorName:e instanceof Error?e.name:typeof e,errorMessage:r}),new Ac.ZD({result:{case:"error",value:new Ac.Jx({uri:t.uri,error:`Failed to read MCP resource: ${r}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{yT(r)}}}function TT(e){switch(e.result.case){case"error":return e.result.value.error;case"permissionDenied":return e.result.value.error||"Permission denied";case"noSpace":return"No space left on device";case"rejected":return e.result.value.reason||"Write rejected";case"success":return"";case void 0:return"Write executor returned result without case";default:{const t=e.result;return String(t)}}}var AT=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const $T=1e4,MT=5e3,DT={PAGER:"cat",MANPAGER:"cat",LESS:"-R",PIP_PROGRESS_BAR:"off",TQDM_DISABLE:"1"};class OT{constructor(){this.fullOutput="",this.outputHead="",this.outputTail="",this.totalChars=0}append(e){if(0===e.length)return;const t=this.totalChars;if(this.totalChars+=e.length,t$T&&(this.fullOutput="")}getOutput(){return this.totalChars<=$T?this.fullOutput:void 0}getTruncation(){if(!(this.totalChars<=$T))return{outputHead:this.outputHead,outputTail:this.outputTail,elidedChars:this.totalChars-this.outputHead.length-this.outputTail.length}}}class FT{constructor(){this.kept="",this.full=!1}append(e){if(this.full)return;const t=rs-this.kept.length;this.full=e.length>=t,this.kept+=Vo(e,t)}get text(){return this.kept}}function NT(e,t){return null!==e?e:null===t?-1:-o.constants.signals[t]}class LT{constructor(e,t,r){this.permissionsService=e,this.ignoreService=t,this.defaultCwd=r}buildResult({args:e,workingDirectory:t,processResult:r,sandboxPolicy:n}){const o={command:e.command,workingDirectory:t,exitCode:r.returncode,signal:r.signal,stdout:r.stdout,stderr:r.exceptionInfo||r.stderr,interleavedOutput:r.output,outputHead:r.outputTruncation?.outputHead,outputTail:r.outputTruncation?.outputTail,elidedChars:r.outputTruncation?.elidedChars,executionTime:r.localExecutionTimeMs??0,localExecutionTimeMs:r.localExecutionTimeMs},s=r.exceptionInfo.length>0,i=0!==r.returncode||s?{case:"failure",value:new he.xC({...o,aborted:s,abortReason:r.abortReason})}:{case:"success",value:new he.QR(o)};return new he.W4({result:i,sandboxPolicy:us(n)})}async runProcess({ctx:e,args:t,workingDirectory:r,sandboxPolicy:n,timeoutMs:o}){const s=performance.now(),i=this.defaultCwd,a=(await(0,Oo.resolveSandboxPolicyForWorkspace)(i,n?{perUser:n}:void 0)).policy,c="insecure_none"!==a.type?{...a,sandboxWorkspaceRoot:i}:a;return await new Promise((n=>{const i=new OT,a=new FT,l=new FT;let u,d,h=!1,p=!1,f="",m=()=>{};const g=(0,Oo.Qw)((0,Oo.ue)((0,Oo.Xw)({...process.env,...DT,CURSOR_AGENT:"1"}))),w={cwd:r,env:g,stdio:["pipe","pipe","pipe"],detached:"win32"!==process.platform,windowsVerbatimArguments:"win32"===process.platform},y="win32"===process.platform?{executable:process.env.ComSpec??"cmd.exe",args:(v=t.command,["/d","/s","/c",`"${v}"`])}:{executable:"/bin/sh",args:["-c",t.command]};var v;const b="insecure_none"===c.type?(0,su.D9)(ou.spawn,y.executable,y.args,w):(0,Oo.spawnInSandbox)(y.executable,y.args,w,c);b.stdin?.end();const S=e=>{h||(h=!0,clearTimeout(d),m(),n({...e,output:i.getOutput(),outputTruncation:i.getTruncation(),localExecutionTimeMs:$y(performance.now()-s)}))};d=setTimeout((()=>{if(p=!0,void 0===u&&(f=`An error occurred while executing the command: Command timed out after ${o}ms`,u=he.Lv.TIMEOUT,m()),void 0!==b.pid&&"win32"!==process.platform)try{return void process.kill(-b.pid,"SIGKILL")}catch{}b.kill("SIGKILL")}),o);const k=()=>{if(void 0===u){if(f="An error occurred while executing the command: Command aborted",u=he.Lv.USER_ABORT,void 0!==b.pid&&"win32"!==process.platform)try{return void process.kill(-b.pid,"SIGTERM")}catch{}b.kill("SIGTERM")}};e.signal.aborted?k():(e.signal.addEventListener("abort",k,{once:!0}),m=()=>{e.signal.removeEventListener("abort",k)}),b.stdout?.setEncoding("utf8"),b.stdout?.on("data",(e=>{a.append(e),i.append(e)})),b.stderr?.setEncoding("utf8"),b.stderr?.on("data",(e=>{l.append(e),i.append(e)})),b.on("error",(e=>{S({stdout:a.text,stderr:l.text,returncode:-1,signal:"",exceptionInfo:`An error occurred while executing the command: ${e.message}`})})),b.on("close",((e,t)=>{S({stdout:a.text,stderr:l.text,returncode:f.length>0?-1:NT(e,t),signal:t??(p?"SIGKILL":""),exceptionInfo:f,abortReason:u})}))}))}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,$.VI)(e.withName("LocalMiniSweAgentBashExecutor.execute")),!1).ctx;(0,$.HF)(n,"LocalMiniSweAgentBashExecutor.execute");const o=t.command,s=(0,Yo.o1)(t.workingDirectory||this.defaultCwd),i=t.timeout>0?t.timeout:3e4;if(!t.parsingResult)return new he.W4({result:{case:"spawnError",value:new he.mJ({command:o,workingDirectory:s,error:"Parsing result is required"})}});let a=t.requestedSandboxPolicy?ls(t.requestedSandboxPolicy):void 0;const c=await this.permissionsService.shouldBlockShellCommand(n,o,{workingDirectory:s,timeout:i,parsingResult:t.parsingResult,toolCallId:t.toolCallId},a);if("block"===c.kind)return"permissionsConfig"===c.reason.type&&c.reason.isReadonly?new he.W4({result:{case:"permissionDenied",value:new he.jn({command:o,workingDirectory:s,error:"Command blocked by permissions configuration",isReadonly:!0})}}):new he.W4({result:{case:"rejected",value:new he.pZ({command:o,workingDirectory:s,reason:Yu(c.reason)})}});a=c.policy,$s()&&(a=Ls(o,t.parsingResult)),a&&"insecure_none"!==a.type&&(a={...a,ignoreMapping:await this.ignoreService.getCursorIgnoreMapping()});const l=await this.runProcess({ctx:n,args:t,workingDirectory:s,sandboxPolicy:a,timeoutMs:i});return this.buildResult({args:t,workingDirectory:s,processResult:l,sandboxPolicy:a})}catch(e){r.error=e,r.hasError=!0}finally{AT(r)}}}const jT=q("shell-executor",(e=>new B(e,Z("shellArgs"),X("shellResult"))),((e,t)=>{t.register(new I(e,Y("shellArgs"),Q("shellResult")))})),UT=q("mini-swe-agent-bash-executor",(e=>new B(e,Z("miniSweAgentBashArgs"),X("miniSweAgentBashResult"))),((e,t)=>{t.register(new I(e,Y("miniSweAgentBashArgs"),Q("miniSweAgentBashResult")))}));function BT(e){return`${e} changed on disk after this tool call read it. Nothing was written. Read the file again and retry.`}function WT(e){return`${e} changed on disk after you last read or wrote it. Nothing was written. Read the file again and retry.`}(0,y.cF)(Symbol("optionalPendingPodWrite"),!1);const HT=q("write-executor",(e=>new B(e,Z("writeArgs"),X("writeResult"))),((e,t)=>{t.register(new I(e,Y("writeArgs"),Q("writeResult")))})),qT=q("delete-executor",(e=>new B(e,Z("deleteArgs"),X("deleteResult"))),((e,t)=>{t.register(new I(e,Y("deleteArgs"),Q("deleteResult")))})),zT=q("fetch-executor",(e=>new B(e,Z("fetchArgs"),X("fetchResult"))),((e,t)=>{t.register(new I(e,Y("fetchArgs"),Q("fetchResult")))})),GT=q("git-diff-executor",(e=>new B(e,Z("gitDiffRequest"),X("gitDiffResponse"))),((e,t)=>{t.register(new I(e,Y("gitDiffRequest"),Q("gitDiffResponse")))})),VT=q("grep-executor",(e=>new B(e,Z("grepArgs"),X("grepResult"))),((e,t)=>{t.register(new I(e,Y("grepArgs"),Q("grepResult")))})),KT="[REDACTED]",JT=new TextEncoder;async function ZT(e){const t=JT.encode(e),r=await crypto.subtle.digest("SHA-256",t);return{sha256:[...new Uint8Array(r)].map((e=>e.toString(16).padStart(2,"0"))).join(""),bytes:t.byteLength}}class XT{constructor(e){this.inner=e}async execute(e,t,r){if(!0!==t.digestOnly)return this.inner.execute(e,t,r);const n=t.clone();return n.digestOnly=void 0,n.maxChars=void 0,async function(e){if("success"!==e.result.case)return e;const t=e.result.value;if("content"!==t.output.case)return e;const{sha256:r,bytes:n}=await ZT(t.output.value),o=t.clone();return o.output={case:void 0},o.outputBlobId=void 0,o.sha256=r,o.sizeBytes=BigInt(n),new Ky.sV({result:{case:"success",value:o}})}(await this.inner.execute(e,n,r))}}const QT=q("read-executor",(e=>new B(e,Z("readArgs"),X("readResult"))),((e,t)=>{t.register(new I(e,Y("readArgs"),Q("readResult")))})),YT=q("redacted-read-executor",(e=>new B(e,Z("redactedReadArgs"),X("redactedReadResult"))),((e,t)=>{t.register(new I(e,Y("redactedReadArgs"),Q("redactedReadResult")))})),eA=q("ls-executor",(e=>new B(e,Z("lsArgs"),X("lsResult"))),((e,t)=>{t.register(new I(e,Y("lsArgs"),Q("lsResult")))})),tA=q("diagnostics-executor",(e=>new B(e,Z("diagnosticsArgs"),X("diagnosticsResult"))),((e,t)=>{t.register(new I(e,Y("diagnosticsArgs"),Q("diagnosticsResult")))})),rA=q("canvas-diagnostics-executor",(e=>new B(e,Z("canvasDiagnosticsArgs"),X("canvasDiagnosticsResult"))),((e,t)=>{t.register(new I(e,Y("canvasDiagnosticsArgs"),Q("canvasDiagnosticsResult")))})),nA="$file:";const oA=(0,u.Pu)("mcp.symbolic_args.expansion",{description:"Outcome of late-binding $file:/abs/path MCP argument expansion at the executor boundary. The call is refused rather than carrying a placeholder to the server when the read reports having replaced a saved secret (`redacted`), or, from a read executor too old to report that, when its text still carries the redaction marker (`redacted_marker`)",labelNames:["route","outcome"]}),sA=(0,u.v5)("mcp.symbolic_args.bytes",{description:"Total bytes substituted into one MCP tool call by $file:/abs/path arguments",labelNames:["route"]}),iA=(0,u.Pu)("mcp.symbolic_args.describe",{description:"Per-file $file:/abs/path describe reads: `vm_digest` when the read executor hashed the file where it lives, `outdated_executor` when it returned the text instead (it predates $file: expansion, so the call is refused)",labelNames:["source"]}),aA=(0,u.v5)("mcp.symbolic_args.paths",{description:"Number of distinct $file:/abs/path arguments expanded in one MCP tool call",labelNames:["route"]});function cA(e,t,r){return{kind:e,message:`Could not resolve the symbolic argument "${nA}${t}": ${r} A string argument of the form "${nA}/absolute/path" is replaced with that file's contents before the tool runs; pass the literal text instead if you did not intend that.`}}const lA={redacted:e=>`${e} contains a saved secret, and a saved secret is never sent through a "${nA}/absolute/path" argument, so this call was not made. Do not retry it, and do not read the file to pass the value yourself. Tell the user that this file holds a saved secret and that they have to enter it in the tool's service themselves.`,redacted_marker:e=>`${e} may contain a saved secret: its text includes the placeholder "${KT}", and the computer that read it is too old to say whether a saved secret stood there, so this call was not made. Do not retry it, and do not read the file to pass the value yourself. Tell the user that this file may hold a saved secret and that they have to enter it in the tool's service themselves.`};function uA(e,t){return{kind:e,message:`Could not resolve the symbolic argument "${nA}${t}": ${lA[e](t)}`}}class dA extends Error{constructor(e){super(e.message),this.failure=e}}let hA;async function pA(e,t,r,n,o,{maxFileBytes:s=8388608,maxTotalBytes:i=16777216,refuseSavedSecrets:a=!1}){if(t.length>4)throw new dA(cA("too_many",t[4]??"",`at most 4 symbolic arguments may be used in one call (${t.length} given). Split the call or pass paths to tools that accept them.`));const c=r();if(void 0===c)throw new dA(cA("no_read_executor",t[0]??"","this environment cannot read files on behalf of a tool call."));const l=await(0,Or.xb)(t,(t=>async function(e,t,r,n,o){const s=await t.execute(e,new Ky.a2({path:r,toolCallId:n,...o.digestOnly?{digestOnly:!0}:{}}));if("success"!==s.result.case)throw new dA(function(e,t,r){switch(e.result.case){case"fileNotFound":return cA("not_found",t,"the file does not exist.");case"permissionDenied":return cA("permission_denied",t,"reading it was not permitted.");case"rejected":return cA("rejected",t,`${e.result.value.reason||"the read was rejected"}. Only files the Read tool can read without approval can be substituted; read it with Read instead.`);case"invalidFile":return cA("not_text",t,"the file cannot be read as text.");case"error":return r?{kind:"read_error",message:`Could not resolve the symbolic argument "${nA}${t}": ${e.result.value.error}`}:cA("read_error",t,e.result.value.error);default:return cA("read_error",t,"the read returned no result.")}}(s,r,o.refuseSavedSecrets));return await async function(e,t,r,{maxFileBytes:n,digestOnly:o,refuseSavedSecrets:s}){const i=function(e,t,r,n){const o=n&&void 0!==t.sha256&&void 0!==t.sizeBytes?{sha256:t.sha256,bytes:Number(t.sizeBytes)}:void 0;if(void 0===o&&"content"!==t.output.case)throw new dA(cA("not_text",r,"the file is not a text file."));if(n){if(iA.increment(e,1,{source:void 0!==o?"vm_digest":"outdated_executor"}),void 0===o)throw new dA(cA("outdated_executor",r,"the computer that would run this tool has an older tool runner that cannot substitute files. Read the file and pass its contents instead."));return o}}(e,t,r,o),a="content"===t.output.case?t.output.value:void 0,{sha256:c,bytes:l}=i??await ZT(a??""),u={content:a,bytes:l,sha256:c};if(t.truncated||l>n)throw new dA(cA("too_large",r,`the file is too large to inline (${Number(t.fileSize)||l} bytes; at most ${n} bytes per file may be substituted). Pass the path to a tool that accepts one, or read a range of it.`));return await async function(e,t,r,n){if(n){if(!0===e.redacted)throw new dA(uA("redacted",r));if(void 0===e.redacted&&await async function(e){return void 0!==e.content?e.content.includes(KT):(await(hA??=Promise.all([KT,`${KT}\n`,`${KT}\r\n`].map((async e=>(await ZT(e)).sha256))).then((e=>new Set(e))),hA)).has(e.sha256)}(t))throw new dA(uA("redacted_marker",r))}}(t,u,r,s),u}(e,s.result.value,r,o)}(e,c,t,n,{maxFileBytes:s,digestOnly:o,refuseSavedSecrets:a})),{max:4});let u=0;for(const[e,r]of l)if(u+=r.bytes,u>i)throw new dA(cA("over_budget",e,`together the ${t.length} symbolic arguments exceed the ${i} bytes that may be substituted per call. Pass paths to tools that accept them instead.`));return l}async function fA(e,t,{route:r,getReadExecutor:n,...o}){if(0===t.symbolicPathArguments.length)return{kind:"none"};const s=new Map(t.symbolicPathArguments.map((e=>[e.path,e]))),i=[...s.keys()],a=t=>(oA.increment(e,1,{route:r,outcome:t.kind}),{kind:"failed",failure:t,result:new Ac.iz({result:{case:"error",value:new Ac.Nh({error:t.message})}})});let c;try{c=await pA(e,i,n,t.toolCallId,!1,o)}catch(e){return a(function(e,t){return e instanceof dA?e.failure:cA("read_error",t,e instanceof Error?e.message:String(e))}(e,i[0]??""))}let l=0;for(const[e,t]of c){l+=t.bytes;const r=s.get(e);if(r?.sha256!==t.sha256)return a(cA("content_changed",e,`the file changed after the call was reviewed (${r?.sizeBytes??0} bytes then, ${t.bytes} bytes now), so its new contents were not sent. Re-run the call to review the current contents.`))}const u=new Map([...c].map((([e,t])=>[e,t.content??""]))),d=function(e,t){const r=e=>{const n=function(e){if("string"!=typeof e||!e.startsWith(nA))return;const t=e.slice(6);return(r=t).startsWith("/")||/^[a-zA-Z]:[\\/]/.test(r)||r.startsWith("\\\\")?t:void 0;var r}(e);return void 0!==n?t.get(n)??e:Array.isArray(e)?e.map(r):null!==e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map((([e,t])=>[e,r(t)]))):e};return Object.fromEntries(Object.entries(e).map((([e,t])=>[e,r(t)])))}(Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()]))),u),h=t.clone();return h.args=Object.fromEntries(Object.entries(d).map((([e,t])=>[e,we.Value.fromJson(t)]))),h.symbolicPathArguments=[],h.argumentsRepaired=!1,oA.increment(e,1,{route:r,outcome:"expanded"}),sA.record(e,l,{route:r}),aA.record(e,i.length,{route:r}),{kind:"expanded",expansion:{args:h,files:[...c].map((([e,t])=>({path:e,bytes:t.bytes}))),paths:i.length,bytes:l}}}const mA=/\b413\b|payload too large|request entity too large|body.*too large|too large.*body|ECONNRESET|EPIPE|socket hang up|max(?:imum)? (?:body|payload|request|content) (?:size|length)/i;function gA(e,t,r,n){return mA.test(t)?(oA.increment(e,1,{route:n,outcome:"server_rejected_body"}),`${t}\n\nThe request carried ${r.bytes} bytes of file contents substituted from ${r.paths} "${nA}/abs/path" argument(s), and the server appears to have rejected the request body as too large. Do not retry the same call: pass a smaller file or a range of it, or use a tool that accepts a path or upload instead.`):t}function wA(e){return e.files.map((e=>`"${nA}${e.path}" was replaced with the contents of ${e.path} (${e.bytes} bytes) before the call.`)).join("\n")}class yA{constructor(e,t,r={}){this.inner=e,this.getReadExecutor=t,this.options=r}isBackendRouted(e){return this.inner.isBackendRouted?.(e)??!1}async execute(e,t,r){if(0===t.symbolicPathArguments.length)return this.inner.execute(e,t,r);const n=await fA(e,t,{route:"local",getReadExecutor:this.getReadExecutor,refuseSavedSecrets:!0===this.options.refuseSavedSecrets&&t.refuseSavedSecrets});if("none"===n.kind)return this.inner.execute(e,t,r);if("failed"===n.kind)return n.result;let o;try{o=await this.inner.execute(e,n.expansion.args,r)}catch(t){throw t instanceof Error&&(t.message=gA(e,t.message,n.expansion,"local")),t}return function(e,t,r){const n=t.clone();return"success"===n.result.case?n.result.value.content.push(new Ac._Z({content:{case:"text",value:new Ac.zN({text:wA(r)})}})):"error"===n.result.case&&(n.result.value.error=gA(e,n.result.value.error,r,"local")),n}(e,o,n.expansion)}}const vA=q("background-shell-executor",(e=>new B(e,Z("backgroundShellSpawnArgs"),X("backgroundShellSpawnResult"))),((e,t)=>{t.register(new I(e,Y("backgroundShellSpawnArgs"),Q("backgroundShellSpawnResult")))})),bA=q("write-background-shell-input-executor",(e=>new B(e,Z("writeShellStdinArgs"),X("writeShellStdinResult"))),((e,t)=>{t.register(new I(e,Y("writeShellStdinArgs"),Q("writeShellStdinResult")))})),SA=q("agent-store-conflict-executor",(e=>new B(e,Z("agentStoreConflictArgs"),X("agentStoreConflictResult"))),((e,t)=>{t.register(new I(e,Y("agentStoreConflictArgs"),Q("agentStoreConflictResult")))})),kA=q("shell-allowlist-precheck-executor",(e=>new B(e,Z("shellAllowlistPrecheckArgs"),X("shellAllowlistPrecheckResult"))),((e,t)=>{t.register(new I(e,Y("shellAllowlistPrecheckArgs"),Q("shellAllowlistPrecheckResult")))})),_A=q("mcp-allowlist-precheck-executor",(e=>new B(e,Z("mcpAllowlistPrecheckArgs"),X("mcpAllowlistPrecheckResult"))),((e,t)=>{t.register(new I(e,Y("mcpAllowlistPrecheckArgs"),Q("mcpAllowlistPrecheckResult")))})),CA=q("web-fetch-allowlist-precheck-executor",(e=>new B(e,Z("webFetchAllowlistPrecheckArgs"),X("webFetchAllowlistPrecheckResult"))),((e,t)=>{t.register(new I(e,Y("webFetchAllowlistPrecheckArgs"),Q("webFetchAllowlistPrecheckResult")))})),EA=q("force-background-shell-executor",(e=>new B(e,Z("forceBackgroundShellArgs"),X("forceBackgroundShellResult"))),((e,t)=>{t.register(new I(e,Y("forceBackgroundShellArgs"),Q("forceBackgroundShellResult")))})),xA=q("computer-use-executor",(e=>new B(e,Z("computerUseArgs"),X("computerUseResult"))),((e,t)=>{t.register(new I(e,Y("computerUseArgs"),Q("computerUseResult")))})),PA=q("computer-use-end-turn-executor",(e=>new B(function(e){return{createExecInstance:(t,r)=>e.createExecInstance(t,(e=>{if(t.signal.aborted)throw new Error("computer-use turn end not sent: its caller stopped waiting");return r(e)}))}}(e),Z("computerUseEndTurnArgs"),X("computerUseEndTurnResult"))),((e,t)=>{t.register(new I(e,Y("computerUseEndTurnArgs"),Q("computerUseEndTurnResult")))})),RA=q("record-screen-executor",(e=>new B(e,Z("recordScreenArgs"),X("recordScreenResult"))),((e,t)=>{t.register(new I(e,Y("recordScreenArgs"),Q("recordScreenResult")))}));var IA=r("../proto/dist/generated/agent/v1/agent_store_conflict_exec_pb.js");function TA(e){if(void 0!==e)return{journalEpoch:e.journalEpoch,seq:Number(e.seq),lastEventId:e.lastEventId}}class AA{constructor(e){this.drainer=e}async execute(e,t){try{void 0!==t.includeQuotaNotices&&this.drainer.setIncludeQuotaNoticesOverride(t.includeQuotaNotices);const e=await this.drainer.drain({cursor:TA(t.cursor),advance:!1!==t.advance});return new IA.Ev({result:{case:"success",value:new IA.iS({events:e.events.map((e=>new IA.RZ({v:e.v,eventId:e.event_id,journalEpoch:e.journal_epoch,seq:BigInt(e.seq),tsMs:BigInt(e.ts_ms),kind:e.kind,storeId:e.store_id,originalRelPath:e.original_rel_path,conflictRelPath:e.conflict_rel_path,originalAbsPath:e.original_abs_path,conflictAbsPath:e.conflict_abs_path,preservedBytes:void 0===e.preserved_bytes?void 0:BigInt(e.preserved_bytes),scopeKind:e.scope_kind,limitBytes:void 0===e.limit_bytes?void 0:BigInt(e.limit_bytes),usageBytes:void 0===e.usage_bytes?void 0:BigInt(e.usage_bytes)}))),nextCursor:(r=e.nextCursor,new IA.LK({journalEpoch:r.journalEpoch,seq:BigInt(r.seq),lastEventId:r.lastEventId})),gap:e.gap})}})}catch(e){return new IA.Ev({result:{case:"error",value:new IA.h6({error:e instanceof Error?e.message:String(e)})}})}var r}}class $A{constructor(e){this.shellStdinWriter=e}async execute(e,t){const r=t.shellId;try{await this.shellStdinWriter(r,t.chars)}catch(e){return new Do.nt({result:{case:"error",value:new Do.Gv({error:`Failed to write to shell ${r} stdin: ${e instanceof Error?e.message:"Unknown error"}`})}})}return new Do.nt({result:{case:"success",value:new Do.tR({shellId:r,terminalFileLengthBeforeInputWritten:0})}})}}var MA=r("../proto/dist/generated/agent/v1/canvas_diagnostics_exec_pb.js"),DA=r("../proto/dist/generated/agent/v1/diagnostics_exec_pb.js");class OA{constructor(e,t){this.getCanvasDiagnostics=e,this.beginCanvasSave=t}async execute(e,t){let r=()=>{};const n=new Promise((e=>{r=e}));let o;if(void 0===this.beginCanvasSave)o=Promise.resolve(void 0);else try{o=this.beginCanvasSave(t.path,{typecheckOutcome:n}).catch((()=>{}))}catch{o=Promise.resolve(void 0)}try{const e=await this.getCanvasDiagnostics(t.path);return void 0===e?(r("unavailable"),FA(NA(t.path,"diagnostics unavailable"),await o)):(r(e.some((e=>1===e.severity))?"failed":"passed"),FA(new MA.GL({result:{case:"success",value:new MA.uX({path:t.path,diagnostics:e.map(LA)})}}),await o))}catch(e){return r("unavailable"),FA(NA(t.path,e instanceof Error?e.message:String(e)),await o)}}}function FA(e,t){return void 0===t||(e.saveState=t.saveState,e.canvasId=t.canvasId,e.title=t.title,e.saveDetail=t.saveDetail),e}function NA(e,t){return new MA.GL({result:{case:"error",value:new MA.HW({path:e,error:t})}})}function LA(e){return new DA.oQ({severity:jA(e.severity),range:new Dc.Q6({start:new Dc.yX({line:e.range.start.line+1,column:e.range.start.character+1}),end:new Dc.yX({line:e.range.end.line+1,column:e.range.end.character+1})}),message:e.message,source:"ts",code:e.code??""})}function jA(e){switch(e){case 1:return DA.h_.ERROR;case 2:return DA.h_.WARNING;case 3:return DA.h_.INFORMATION;case 4:return DA.h_.HINT;default:return DA.h_.UNSPECIFIED}}class UA{constructor(e){if(e.startsWith("file://")){if(!this.isValidFileUrl(e))throw new Error(`Invalid file URL: ${e}`);this.urlString=e}else{const t=this.resolvePath(e);this.urlString=this.pathToFileUrl(t)}}isValidFileUrl(e){try{return"file:"===new URL(e).protocol}catch{return!1}}resolvePath(e){if(e.includes("\\")&&(e=e.replace(/\\/g,"/")),/^[a-zA-Z]:\//.test(e)||/^\//.test(e))return e;const t=e.split("/"),r=[];for(let e=0;ethis.convertDiagnostic(e)));return new DA.Ek({result:{case:"success",value:new DA.a1({path:t.path,diagnostics:s,totalDiagnostics:s.length})}})}catch(r){return e.canceled?new DA.Ek({result:{case:"error",value:new DA.Ho({path:t.path,error:"Request timed out after 10 seconds"})}}):new DA.Ek({result:{case:"error",value:new DA.Ho({path:t.path,error:r instanceof Error?r.message:String(r)})}})}finally{n()}}catch(e){r.error=e,r.hasError=!0}finally{BA(r)}}convertDiagnostic(e){const t=e.message,r="string"==typeof t?t:t&&"object"==typeof t&&"value"in t&&"string"==typeof t.value?t.value:"";return new DA.oQ({severity:this.convertSeverity(e.severity),range:e.range?new Dc.Q6({start:new Dc.yX({line:e.range.start.line,column:e.range.start.character}),end:new Dc.yX({line:e.range.end.line,column:e.range.end.character})}):void 0,message:r,source:e.source,code:e.code?String(e.code):void 0})}convertSeverity(e){switch(e){case 1:return DA.h_.ERROR;case 2:return DA.h_.WARNING;case 3:return DA.h_.INFORMATION;case 4:return DA.h_.HINT;default:return DA.h_.UNSPECIFIED}}}async function HA(e){const{repoRoot:t,filePaths:r,getContent:n}=e,o=new Map;if(0===r.length)return o;const s=await async function(e,t){const r=new Map;if(0===t.length)return r;try{const{stdout:n}=await vy().run(e,["check-attr","linguist-generated","--stdin"],{input:`${t.join("\n")}\n`});for(const e of n.trim().split("\n")){const t=e.match(/^(.+): linguist-generated: (.+)$/);if(t){const e=t[1],n=t[2];"true"===n||"set"===n?r.set(e,!0):"false"!==n&&"unset"!==n||r.set(e,!1)}}}catch{}return r}(t,r);return await Promise.all(r.map((async e=>{const t=s.get(e);if(!0!==t)if(!1!==t)if(function(e){return new qA(e).isGeneratedByPath()}(e))o.set(e,{isGenerated:!0,source:"path-heuristic"});else{if(n){const t=await n(e);if(void 0!==t&&function(e,t){return new qA(e,(()=>t)).isGeneratedByContent()}(e,t))return void o.set(e,{isGenerated:!0,source:"content-heuristic"})}o.set(e,{isGenerated:!1,source:"none"})}else o.set(e,{isGenerated:!1,source:"gitattributes"});else o.set(e,{isGenerated:!0,source:"gitattributes"})}))),o}class qA{constructor(e,t){this.name=e,this.extname=s.extname(e).toLowerCase(),this.getContent=t}get lines(){if(void 0===this.cachedLines){const e=this.getContent?.();this.cachedLines=e?e.split("\n"):[]}return this.cachedLines}get data(){return this.getContent?.()}isGeneratedByPath(){return this.xcodeFile()||this.intellijFile()||this.cocoapods()||this.carthageBuild()||this.generatedGraphqlRelay()||this.generatedNetDesignerFile()||this.generatedNetSpecflowFeatureFile()||this.composerLock()||this.cargoLock()||this.cargoOrig()||this.denoLock()||this.flakeLock()||this.bazelLock()||this.nodeModules()||this.goVendor()||this.goLock()||this.packageResolved()||this.poetryLock()||this.pdmLock()||this.uvLock()||this.pixiLock()||this.esyLock()||this.npmShrinkwrapOrPackageLock()||this.pnpmLock()||this.bunLock()||this.terraformLock()||this.generatedYarnPlugnplay()||this.godeps()||this.generatedByZephir()||this.htmlcov()||this.gradleWrapper()||this.mavenWrapper()||this.pipenvLock()||this.generatedPascalTlb()||this.generatedSqlxQuery()||this.sourceMapByName()}isGeneratedByContent(){return!!this.getContent&&(this.minifiedFiles()||this.hasSourceMap()||this.sourceMap()||this.compiledCoffeescript()||this.generatedParser()||this.generatedNetDocfile()||this.generatedPostscript()||this.compiledCythonFile()||this.generatedGo()||this.generatedProtocolBufferFromGo()||this.generatedProtocolBuffer()||this.generatedJavascriptProtocolBuffer()||this.generatedTypescriptProtocolBuffer()||this.generatedApacheThrift()||this.generatedJniHeader()||this.vcrCassette()||this.generatedAntlr()||this.generatedModule()||this.generatedUnity3dMeta()||this.generatedRacc()||this.generatedJflex()||this.generatedGrammarkit()||this.generatedRoxygen2()||this.generatedHtml()||this.generatedJison()||this.generatedGrpcCpp()||this.generatedDart()||this.generatedPerlPpportHeader()||this.generatedGamemakerstudio()||this.generatedGimp()||this.generatedVisualstudio6()||this.generatedHaxe()||this.generatedJooq()||this.generatedSorbetRbi()||this.generatedMysqlViewDefinitionFormat())}xcodeFile(){return[".nib",".xcworkspacedata",".xcuserstate"].includes(this.extname)}intellijFile(){return/(?:^|\/)\.idea\//.test(this.name)}cocoapods(){return/(^Pods|\/Pods)\//.test(this.name)}carthageBuild(){return/(^|\/)Carthage\/Build\//.test(this.name)}generatedGraphqlRelay(){return/__generated__\//.test(this.name)}generatedNetDesignerFile(){return/\.designer\.(cs|vb)$/i.test(this.name)}generatedNetSpecflowFeatureFile(){return/\.feature\.cs$/i.test(this.name)}composerLock(){return/composer\.lock/.test(this.name)}cargoLock(){return/Cargo\.lock/.test(this.name)}cargoOrig(){return/Cargo\.toml\.orig/.test(this.name)}denoLock(){return/deno\.lock/.test(this.name)}flakeLock(){return/(^|\/)flake\.lock$/.test(this.name)}bazelLock(){return/(^|\/)MODULE\.bazel\.lock$/.test(this.name)}nodeModules(){return/node_modules\//.test(this.name)}goVendor(){return/vendor\/((?!-)[-0-9A-Za-z]+(?e+t.length),0)/this.lines.length>110}hasSourceMap(){return!!this.maybeMinified()&&this.lines.slice(-2).some((e=>/^\/[*/][#@] source(?:Mapping)?URL|sourceURL=/.test(e)))}sourceMap(){if(".map"!==this.extname)return!1;if(/\.(css|js)\.map$/i.test(this.name))return!0;const e=this.lines[0]||"";return/^{"version":\d+,/.test(e)||/^\/\*\* Begin line maps\. \*\*\/{/.test(e)}compiledCoffeescript(){if(".js"!==this.extname)return!1;const e=this.lines[0]||"";if(/^\/\/ Generated by /.test(e))return!0;if("(function() {"===e&&"}).call(this);"===(this.lines[this.lines.length-2]||"")&&""===(this.lines[this.lines.length-1]||"")){let e=0;for(const t of this.lines)if(/var /.test(t)){const r=t.match(/_fn|_i|_len|_ref|_results/g);e+=1*(r?.length||0);const n=t.match(/__bind|__extends|__hasProp|__indexOf|__slice/g);e+=3*(n?.length||0)}return e>=3}return!1}generatedNetDocfile(){return".xml"===this.extname&&!(this.lines.length<=3)&&(this.lines[1]||"").includes("")&&(this.lines[2]||"").includes("")&&(this.lines[this.lines.length-2]||"").includes("")}generatedParser(){if(".js"!==this.extname)return!1;const e=this.lines.slice(0,5).join("");return/^(?:[^/]|\/[^*])*\/\*(?:[^*]|\*[^/])*Generated by PEG\.js/.test(e)}generatedPostscript(){if(![".ps",".eps",".pfa"].includes(this.extname))return!1;const e=this.data;if(!e)return!1;if(/^\s*(?:currentfile eexec\s+|\/sfnts\s+\[\s<)/.test(e))return!0;const t=this.lines.slice(0,10).find((e=>/^%%Creator: /.test(e)));return!!t&&(!(!/[0-9]|draw|mpage|ImageMagick|inkscape|MATLAB/.test(t)&&!/PCBNEW|pnmtops|\(Unknown\)|Serif Affinity|Filterimage -tops/.test(t))||!!t.includes("EAGLE")&&this.lines.slice(0,5).some((e=>/^%%Title: EAGLE Drawing /.test(e))))}generatedGo(){return".go"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,40).some((e=>/^\/\/ Code generated .*/.test(e)))}generatedProtocolBufferFromGo(){return".proto"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,20).some((e=>e.includes("This file was autogenerated by go-to-protobuf")))}generatedProtocolBuffer(){return!![".py",".java",".h",".cc",".cpp",".m",".rb",".php"].includes(this.extname)&&!(this.lines.length<=1)&&this.lines.slice(0,3).some((e=>e.includes("Generated by the protocol buffer compiler. DO NOT EDIT!")))}generatedJavascriptProtocolBuffer(){return".js"===this.extname&&!(this.lines.length<=6)&&(this.lines[5]||"").includes("GENERATED CODE -- DO NOT EDIT!")}generatedTypescriptProtocolBuffer(){return".ts"===this.extname&&!(this.lines.length<=4)&&(this.lines[0]||"").includes("Code generated by protoc-gen-ts_proto. DO NOT EDIT.")}generatedApacheThrift(){return!![".rb",".py",".go",".js",".m",".java",".h",".cc",".cpp",".php"].includes(this.extname)&&this.lines.slice(0,6).some((e=>e.includes("Autogenerated by Thrift Compiler")))}generatedJniHeader(){return".h"===this.extname&&!(this.lines.length<=2)&&(this.lines[0]||"").includes("/* DO NOT EDIT THIS FILE - it is machine generated */")&&(this.lines[1]||"").includes("#include ")}vcrCassette(){return".yml"===this.extname&&!(this.lines.length<=2)&&(this.lines[this.lines.length-2]||"").includes("recorded_with: VCR")}generatedAntlr(){return".g"===this.extname&&!(this.lines.length<=2)&&(this.lines[1]||"").includes("generated by Xtest")}compiledCythonFile(){return!![".c",".cpp"].includes(this.extname)&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("Generated by Cython")}generatedModule(){if(".mod"!==this.extname)return!1;if(this.lines.length<=1)return!1;const e=this.lines[0]||"";return e.includes("PCBNEW-LibModule-V")||e.includes("GFORTRAN module version '")}generatedUnity3dMeta(){return".meta"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("fileFormatVersion: ")}generatedRacc(){return".rb"===this.extname&&!(this.lines.length<=2)&&(this.lines[2]||"").startsWith("# This file is automatically generated by Racc")}generatedJflex(){return".java"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("/* The following code was generated by JFlex ")}generatedGrammarkit(){return".java"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("// This is a generated file. Not intended for manual editing.")}generatedRoxygen2(){return".rd"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("% Generated by roxygen2: do not edit by hand")}generatedHtml(){if(![".html",".htm",".xhtml"].includes(this.extname))return!1;if(this.lines.length<=1)return!1;if(this.lines.slice(0,2).some((e=>//.test(e))))return!0;if(this.lines.length>2&&(this.lines[2]||"").startsWith("\x3c!-- This is an automatically generated file."))return!0;if(this.lines.slice(0,31).some((e=>//i.test(e))))return!0;const e=this.lines.slice(0,31).join(" ").match(/]+)>/gi);if(!e)return!1;for(const t of e){const e=this.extractHtmlMeta(t);if("generator"===e.name?.toLowerCase()&&(e.content||e.value)){const t=e.content||e.value||"";if(/^(org\s+mode|j?latex2html|groff|makeinfo|texi2html|ronn)\b/i.test(t))return!0}}return!1}extractHtmlMeta(e){const t={},r=e.matchAll(/(?<=^|\s)(name|content|value)\s*=\s*("[^"]+"|'[^']+'|[^\s"']+)/gi);for(const e of r){const r=e[1].toLowerCase();let n=e[2];(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'"))&&(n=n.slice(1,-1)),t[r]=n}return t}generatedJison(){if(".js"!==this.extname)return!1;if(this.lines.length<=1)return!1;const e=this.lines[0]||"";return e.startsWith("/* parser generated by jison ")||e.startsWith("/* generated by jison-lex ")}generatedGrpcCpp(){return!![".cpp",".hpp",".h",".cc"].includes(this.extname)&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("// Generated by the gRPC")}generatedDart(){return".dart"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,3).some((e=>/generated code\W{2,3}do not modify/i.test(e)))}generatedPerlPpportHeader(){return!!/ppport\.h$/.test(this.name)&&!(this.lines.length<=10)&&(this.lines[8]||"").includes("Automatically created by Devel::PPPort")}generatedGamemakerstudio(){if(![".yy",".yyp"].includes(this.extname))return!1;if(this.lines.length<=3)return!1;const e=this.lines.slice(0,3).join("");return/^\s*[{[]/.test(e)||/^\d\.\d\.\d.+\|\{/.test(this.lines[0]||"")}generatedGimp(){if(![".c",".h"].includes(this.extname))return!1;if(0===this.lines.length)return!1;const e=this.lines[0]||"";return/^\/\* GIMP [a-zA-Z0-9- ]+ C-Source image dump \(.+?\.c\) \*\//.test(e)||/^\/\* {2}GIMP header image file format \([a-zA-Z0-9- ]+\): .+?\.h {2}\*\//.test(e)}generatedVisualstudio6(){return".dsp"===this.extname&&this.lines.slice(0,3).some((e=>e.includes("# Microsoft Developer Studio Generated Build File")))}generatedHaxe(){return!![".js",".py",".lua",".cpp",".h",".java",".cs",".php"].includes(this.extname)&&this.lines.slice(0,3).some((e=>e.includes("Generated by Haxe")))}generatedJooq(){return".java"===this.extname&&this.lines.slice(0,2).some((e=>e.includes("This file is generated by jOOQ.")))}generatedSorbetRbi(){return".rbi"===this.extname&&!(this.lines.length<5)&&/^# typed:/.test(this.lines[0]||"")&&(this.lines[2]||"").includes("DO NOT EDIT MANUALLY")&&/^# Please (run|instead update this file by running) `bin\/tapioca/.test(this.lines[4]||"")}generatedMysqlViewDefinitionFormat(){return".frm"===this.extname&&(this.lines[0]||"").includes("TYPE=VIEW")}}const zA=e=>{if(!e)return[];if("string"!=typeof e||e.match(/^\s+$/))return[];const t=e.split("\n");if(0===t.length)return[];const r=[];let n=null,o=null,s=0,i=0,a=null;const c=e=>{o?.changes.push({type:"normal",normal:!0,ln1:s++,ln2:i++,content:e}),a.oldLines--,a.newLines--},l=e=>{const[t,o]=KA(e)??[];n={chunks:[],deletions:0,additions:0,from:t,to:o},r.push(n)},u=()=>{n&&!n.chunks.length||l()},d=e=>+(e||1),h=e=>{o&&(o.changes.push({type:"del",del:!0,ln:s++,content:e}),n.deletions++,a.oldLines--)},p=e=>{o&&(o.changes.push({type:"add",add:!0,ln:i++,content:e}),n.additions++,a.newLines--)},f=e=>{if(!o)return;const[t]=o.changes.slice(-1);o.changes.push({type:t.type,[t.type]:!0,ln1:t.ln1,ln2:t.ln2,ln:t.ln,content:e})},m=[[/^diff\s/,l],[/^new file mode (\d+)$/,(e,t)=>{u(),n.new=!0,n.newMode=t[1],n.from="/dev/null"}],[/^deleted file mode (\d+)$/,(e,t)=>{u(),n.deleted=!0,n.oldMode=t[1],n.to="/dev/null"}],[/^old mode (\d+)$/,(e,t)=>{u(),n.oldMode=t[1]}],[/^new mode (\d+)$/,(e,t)=>{u(),n.newMode=t[1]}],[/^index\s[\da-zA-Z]+\.\.[\da-zA-Z]+(\s(\d+))?$/,(e,t)=>{u(),n.index=e.split(" ").slice(1),t[1]&&(n.oldMode=n.newMode=t[1].trim())}],[/^---\s/,e=>{u(),n.from=ZA(e)}],[/^\+\+\+\s/,e=>{u(),n.to=ZA(e)}],[/^@@\s+-(\d+),?(\d+)?\s+\+(\d+),?(\d+)?\s@@/,(e,t)=>{n||l(e);const[r,c,u,h]=t.slice(1);s=+r,i=+u,o={content:e,changes:[],oldStart:+r,oldLines:d(c),newStart:+u,newLines:d(h)},a={oldLines:d(c),newLines:d(h)},n.chunks.push(o)}],[/^\\ No newline at end of file$/,f]],g=[[/^\\ No newline at end of file$/,f],[/^-/,h],[/^\+/,p],[/^\s+/,c]],w=e=>{a?(e=>{const t=e.charCodeAt(0);if(43===t)p(e);else if(45===t)h(e);else if(32===t)c(e);else if(92===t&&/^\\ No newline at end of file$/.test(e))f(e);else for(const[t,r]of g){const n=e.match(t);if(n){r(e,n);break}}0===a.oldLines&&0===a.newLines&&(a=null)})(e):(e=>{for(const[t,r]of m){const n=e.match(t);if(n){r(e,n);break}}})(e)};for(const e of t)w(e);return r},GA=/(a|i|w|c|o|1|2)\/.*(?=["']? ["']?(b|i|w|c|o|1|2)\/)|(b|i|w|c|o|1|2)\/.*$/g,VA=/^(a|b|i|w|c|o|1|2)\//,KA=e=>{const t=e?.match(GA);return t?.map((e=>e.replace(VA,"").replace(/("|')$/,"")))},JA=/^\\?['"]|\\?['"]$/g,ZA=e=>{let t=XA(e,"-+").trim();return t=YA(t),t.replace(JA,"").replace(VA,"")},XA=(e,t)=>{if(e=t$(e),!t&&String.prototype.trimLeft)return e.trimLeft();const r=e$(t);return e.replace(new RegExp(`^${r}+`),"")},QA=/\t.*|\d{4}-\d\d-\d\d\s\d\d:\d\d:\d\d(.\d+)?\s(\+|-)\d\d\d\d/,YA=e=>{const t=QA.exec(e);return t&&(e=e.substring(0,t.index).trim()),e},e$=e=>null==e?"\\s":e instanceof RegExp?e.source:`[${t$(e).replace(/([.*+?^=!:${}()|[\]/\\])/g,"\\$1")}]`,t$=e=>`${e??""}`,r$=(0,l.h)("local-mercurial-diff"),n$=5242880,o$="0000000000000000000000000000000000000000";let s$,i$;async function a$(e,t,r={}){const n=await async function(){if(void 0===s$&&(s$=await async function(e){const t="win32"===process.platform?["hg.com","hg.exe"]:["hg"];for(const r of e.split(s.default.delimiter))if(s.default.isAbsolute(r))for(const e of t){const t=s.default.join(r,e);try{if(!(await Co.stat(t)).isFile())continue;return"win32"!==process.platform&&await Co.access(t,xo.constants.X_OK),t}catch{}}}(process.env.PATH??"")??null),null===s$){const e=new Error("hg executable not found");throw e.code="ENOENT",e}return s$}(),o=await new Promise(((o,s)=>{const i=(0,ou.spawn)(n,t,{cwd:e,env:{...process.env,HGPLAIN:"+strictflags",HGRCPATH:"",HGRCSKIPREPO:"1"},shell:!1}),a=new ia.StringDecoder("utf8");let c="";i.stdout.on("data",(e=>{c+=a.write(e)})),i.stderr.on("data",(()=>{})),i.on("error",(e=>{!0===r.allowFailure?o(""):s(e)})),i.on("close",(e=>{if(0===e||!0===r.allowFailure)o(c+a.end());else{const r=t.find((e=>!e.startsWith("-")))??"hg";s(new Error(`MercurialDiffFailed: hg ${r} exited ${e??"unknown"}`))}}))}));return o}async function c$(e){const t=await async function(e){let t=s.default.resolve(e);for(;;){try{if((await Co.stat(s.default.join(t,".hg"))).isDirectory())return!0}catch{}const e=s.default.dirname(t);if(e===t)return!1;t=e}}(e);if(!t)return;const r=function(e,t){return e&&"absent"!==t?"skips-repo-config"!==t?"unsafe":"proceed":"not-mercurial"}(t,await async function(){if(void 0!==i$)return i$;const e=await Co.mkdtemp(s.default.join((0,o.tmpdir)(),"hg-probe-"));try{const t=await a$(e,["help","environment"]);i$=/\bHGRCSKIPREPO\b/.test(t)?"skips-repo-config":"reads-repo-config"}catch(e){i$=function(e){return"object"==typeof e&&null!==e&&"code"in e&&"ENOENT"===e.code}(e)?"absent":"reads-repo-config"}finally{await Co.rm(e,{recursive:!0,force:!0})}return i$}());if("not-mercurial"===r)return;if("unsafe"===r)throw new Error("MercurialClientUnsafe: hg would read repository config");let n;try{n=(await a$(e,["root"])).trim()}catch{return}if(0!==n.length)try{return(await Co.stat(s.default.join(n,".hg"))).isDirectory()?n:void 0}catch{return}}function l$(e,t){return"win32"===process.platform?s.default.win32.normalize(e).toLowerCase()===s.default.win32.normalize(t).toLowerCase():s.default.resolve(e)===s.default.resolve(t)}function u$(e,t){const r=s.default.relative(s.default.resolve(t),s.default.resolve(e));return 0===r.length||!s.default.isAbsolute(r)&&!r.split(s.default.sep).includes("..")}async function d$(e){const t=s.default.resolve(e);try{return await Co.realpath(t)}catch{return t}}function h$(e){if(0===e.length)return[];const t=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),r=t.split("\n");return t.endsWith("\n")&&r.pop(),r}function p$(e){if(e.includes("\0")||/[\r\n]/.test(e))throw new Error("MercurialDiffFailed: base ref contains a newline")}async function f$({repositoryRoot:e,rev:t,filePath:r}){const n=await async function({repositoryRoot:e,rev:t,filePath:r}){let n;try{n=await a$(e,["files","-r",t,"-T","{size}","--",r])}catch{return}const o=n.trim();if(!/^\d+$/.test(o))return;const s=Number(o);return Number.isFinite(s)?s:void 0}({repositoryRoot:e,rev:t,filePath:r});return void 0===n||n>n$?"":a$(e,["cat","-r",t,"--",r])}async function m$(e,t,r){const n=function(e){switch(e){case Le.ek.NAME_STATUS:return Le.ek.NAME_STATUS;case Le.ek.NAME_STATUS_AND_NUMSTAT:return Le.ek.NAME_STATUS_AND_NUMSTAT;case Le.ek.FILE_DIFFS:return Le.ek.FILE_DIFFS;case Le.ek.DIFFS_WITH_BEFORE_AND_AFTER:return Le.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return Le.ek.FILE_DIFFS}}(r.outputFormat),o=["root"],i=(await a$(t,["root"])).trim();if(0===i.length)throw new Error("MercurialDiffFailed: hg root did not resolve");let a,c;if(0!==r.ref.length||"HEAD"!==r.baseRef&&(r.mergeBase||0!==r.baseRef.length)){if(r.mergeBase||0===r.baseRef.length)a=await async function({cwd:e,baseRef:t,commands:r}){if(t.length>0&&"HEAD"!==t){p$(t),r.push("log");const n=(await a$(e,["log","-r",`ancestor(., (${t}))`,"-T","{node}"])).trim();if(0===n.length||n===o$)throw new Error("MercurialDiffFailed: base ref did not resolve");return n}r.push("log");const n=(await a$(e,["log","-r","max(::. and public())","-T","{node}"],{allowFailure:!0})).trim();if(n.length>0&&n!==o$)return n;const o=(await a$(e,["log","-r","ancestor(., default)","-T","{node}"],{allowFailure:!0})).trim();if(o.length>0&&o!==o$)return o;const s=(await a$(e,["log","-r",".","-T","{node}"],{allowFailure:!0})).trim();return s.length>0?s:o$}({cwd:t,baseRef:r.baseRef,commands:o});else if(p$(r.baseRef),o.push("log"),a=(await a$(t,["log","-r",r.baseRef,"-T","{node}"])).trim(),0===a.length)throw new Error("MercurialDiffFailed: base ref did not resolve");r.ref.length>0&&(p$(r.ref),o.push("log"),c=(await a$(t,["log","-r",r.ref,"-T","{node}"])).trim())}const l=["diff","--git"];r.includeSpaceChanges||l.push("-b"),void 0!==r.unifiedContextLines&&l.push(`-U${r.unifiedContextLines}`),void 0!==a&&l.push("-r",a),void 0!==c&&l.push("-r",c),r.targetPaths.length>0&&l.push("--",...r.targetPaths),o.push("diff");const u=await a$(t,l),d=function(e){const t=e.replace(/\r\n/g,"\n");return new Le.o$({diffs:zA(t).map((e=>function(e){const t=new Le.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new Le.Ei({content:e.content,lines:e.changes.map((e=>e.content)),oldStart:e.oldStart,oldLines:e.oldLines,newStart:e.newStart,newLines:e.newLines})))});return t.added=e.additions,t.removed=e.deletions,t}(e))),diffType:Le.Wf.UNSPECIFIED})}(u);let h=[];if(r.maxUntrackedFiles>0&&(o.push("status"),h=await async function({cwd:e,repositoryRoot:t,maxUnknownFiles:r}){let n=(await a$(e,["status","-un0"])).split("\0").filter((e=>e.length>0));return n.length>r&&(n=n.slice(0,r)),(await Promise.all(n.map((async e=>{try{const r=s.default.join(t,e),n=await Co.stat(r);if(n.size>n$){const t=await async function(e){const t=(0,bo.createHash)("sha256"),r=await Co.open(e,"r");try{const e=Buffer.alloc(65536);let n=0;for(;;){const{bytesRead:o}=await r.read(e,0,e.length,n);if(0===o)break;t.update(e.subarray(0,o)),n+=o}}finally{await r.close()}return t.digest("hex")}(r);return{contents:"",path:e,omittedDueToSize:!0,byteSize:n.size,contentHash:t}}return{contents:await Co.readFile(r,"utf8"),path:e}}catch{return}})))).filter((e=>void 0!==e))}({cwd:t,repositoryRoot:i,maxUnknownFiles:r.maxUntrackedFiles}),d.diffs.push(...h.map((e=>function(e){if(!0===e.omittedDueToSize)return new Le.QP({from:"/dev/null",to:e.path,chunks:[],added:0,removed:0});const t=h$(e.contents);if(0===t.length)return new Le.QP({from:"/dev/null",to:e.path,chunks:[],added:0,removed:0});const r=t.length;return new Le.QP({from:"/dev/null",to:e.path,chunks:[new Le.Ei({content:`@@ -0,0 +1${1===r?"":`,${r}`} @@`,lines:t.map((e=>`+${e}`)),oldStart:0,oldLines:0,newStart:1,newLines:r})],added:r,removed:0})}(e))))),n!==Le.ek.FILE_DIFFS)for(const e of d.diffs)e.chunks=[];if(n===Le.ek.DIFFS_WITH_BEFORE_AND_AFTER){const e=a??".";await Promise.all(d.diffs.map((async t=>{if("/dev/null"!==t.from)try{t.beforeFileContents=await f$({repositoryRoot:i,rev:e,filePath:t.from})}catch{t.beforeFileContents=""}else t.beforeFileContents="";if("/dev/null"!==t.to)if(void 0===c)try{const e=s.default.join(i,t.to),r=await Co.stat(e);t.afterFileContents=r.size>n$?"":await Co.readFile(e,"utf8")}catch{t.afterFileContents=""}else try{t.afterFileContents=await f$({repositoryRoot:i,rev:c,filePath:t.to})}catch{t.afterFileContents=""}else t.afterFileContents=""})))}const p=[u,function(e){const t=[];for(const r of e){const e=h$(r.contents);if(t.push(`diff --git a/${r.path} b/${r.path}`),t.push("new file mode 100644"),t.push("--- /dev/null"),t.push(`+++ b/${r.path}`),0===e.length)continue;const n=e.length;t.push(`@@ -0,0 +1${1===n?"":`,${n}`} @@`),t.push(...e.map((e=>`+${e}`)))}return t.join("\n")}(h.filter((e=>!0!==e.omittedDueToSize))),h.filter((e=>!0===e.omittedDueToSize)).map((e=>`omitted-untracked ${e.byteSize??0} ${e.contentHash??""} ${JSON.stringify(e.path)}`)).join("\n")].filter((e=>e.length>0)).join("\n"),f=r.computePatchId?function(e){if(0!==e.length)return`hg:${(0,bo.createHash)("sha256").update(e).digest("hex")}`}(p.length>0?`${p}\n`:""):void 0;let m,g;if(!0===r.returnHeadSha){o.push("log","status");const e=(await a$(t,["log","-r",".","-T","{node}"],{allowFailure:!0})).trim();m=e.length>0?e:o$,g=(await a$(t,["status","-0"])).length>0}r$.info(e,"Local mercurial diff commands",{sourceControl:"mercurial",commands:o});const w=new Le.df({diff:d,submoduleDiffs:[],patchId:f,headSha:m,hasUncommittedChanges:g}),y=r.maxResponseBytes??0;if(y>0){const t=w.toBinary().byteLength;if(t>y)throw r$.info(e,"Local diff outcome",{sourceControl:"mercurial",outcome:"too_large"}),new Error(`GetDiffResponseTooLarge: ${t} bytes exceeds the ${y} byte limit`)}return r$.info(e,"Local diff outcome",{sourceControl:"mercurial",outcome:"ok",fileCount:d.diffs.length,patchIdPrefixed:!0===f?.startsWith("hg:")}),w}const g$=(0,l.h)("local-git-diff");function w$({exitCode:e,stderr:t}){return new Error(`Git command failed with code ${e}: ${t}`)}async function y$(e,t,r={}){let n;try{n=await e(t)}catch(e){if(!0===r.ignoreErrors)return"";throw e}if(0!==n.exitCode&&!0!==r.ignoreErrors)throw w$(n);return!0===r.shouldNotTrimOutput?n.stdout:n.stdout.trim()}function v$(e){const t=zA(e);return new Le.o$({diffs:t.map((e=>function(e){const t=new Le.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new Le.Ei({content:e.content,lines:e.changes.map((e=>e.content)),oldStart:e.oldStart,oldLines:e.oldLines,newStart:e.newStart,newLines:e.newLines})))});return t.added=e.additions,t.removed=e.deletions,t}(e))),diffType:Le.Wf.UNSPECIFIED})}function b$(e){const t=[];for(const n of e){const e={body:`+${(r=n.contents).replaceAll("\n","\n+")}`,numLines:Js(r)},o=1===e.numLines?"@@ -0,0 +1 @@":`@@ -0,0 +1,${e.numLines} @@`;t.push(`diff --git a/${n.path} b/${n.path}\n--- /dev/null\n+++ b/${n.path}\n${o}\n${e.body}`)}var r;return t.join("\n")}const S$=["main","master","develop"];async function k$(e,t){const r=s.default.join(e,t),n=await Co.lstat(r);if(n.isSymbolicLink())return{contents:await Co.readlink(r),path:t,isSymlink:!0};if(!n.isFile())throw new Error("Not a regular file or symlink");return{contents:await Co.readFile(r,"utf8"),path:t,isSymlink:!1}}async function _$(e,t,r){const n=vy(),o=(e,r)=>n.run(t,e,r),i=await async function(e,t){let r;try{const e=(await y$(t,["rev-parse","--show-toplevel"])).trim();e.length>0&&(r=e)}catch{}if(void 0!==r){const t=await async function({cwd:e,gitRoot:t}){const r=await d$(t);let n=await d$(e);if(l$(n,r))return;let o=!1;for(;u$(n,r)&&!l$(n,r);){try{if((await Co.stat(s.default.join(n,".hg"))).isDirectory()){o=!0;break}}catch{}const e=s.default.dirname(n);if(e===n)break;n=e}return o?c$(e):void 0}({cwd:e,gitRoot:r});return void 0!==t?"mercurial":"git"}return void 0===await c$(e)?"none":"mercurial"}(t,o);if(g$.info(e,"Local diff source control",{sourceControl:i}),"none"===i)throw g$.info(e,"Local diff outcome",{sourceControl:i,outcome:"no_version_control"}),new Error("NoVersionControl: no git or mercurial repository");if("mercurial"===i)return m$(e,t,r);const a=function(e){switch(e){case Le.ek.NAME_STATUS:return Le.ek.NAME_STATUS;case Le.ek.NAME_STATUS_AND_NUMSTAT:return Le.ek.NAME_STATUS_AND_NUMSTAT;case Le.ek.FILE_DIFFS:return Le.ek.FILE_DIFFS;case Le.ek.DIFFS_WITH_BEFORE_AND_AFTER:return Le.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return Le.ek.FILE_DIFFS}}(r.outputFormat),c=await(async()=>{let e=r.baseRef.length>0?r.baseRef:await async function(e){try{const t=await y$(e,["symbolic-ref","--short","refs/remotes/origin/HEAD"]);if(t)return t.trim()}catch{}for(const t of S$){const r=`origin/${t}`;try{return await y$(e,["rev-parse","--verify",r]),r}catch{}}try{const t=(await y$(e,["branch","-r"])).split("\n").map((e=>e.trim())).find((e=>e.startsWith("origin/")));if(t)return t}catch{}try{const t=await y$(e,["config","--get","init.defaultBranch"]);if(t)return t.trim()}catch{}throw new Error("Could not determine default branch")}(o);if(r.mergeBase){const t=r.ref.length>0?r.ref:"HEAD";e=(await y$(o,["merge-base","--end-of-options",e,t])).trim()}return e})(),l=["diff","--no-color"];r.includeSpaceChanges||l.push("--ignore-space-change"),void 0!==r.unifiedContextLines&&l.push(`-U${r.unifiedContextLines}`);const u=["--end-of-options",c];r.ref.length>0&&u.push(r.ref),r.targetPaths.length>0&&u.push("--",...r.targetPaths);const d=await o([...l,...u]);let h,p;if(0===d.exitCode)h=d.stdout,p=v$(h);else{const t=w$(d);if(r.computePatchId||!await async function(e){return(await y$(e,["config","--get-regexp","^(extensions\\.partialclone|remote\\..+\\.promisor)$"],{ignoreErrors:!0})).split("\n").some((e=>/^(extensions\.partialclone \S|remote\..+\.promisor( (true|yes|on|1))?$)/i.test(e)))}(o))throw t;p=await async function(e,t){const r=(await y$(e,["diff","--name-status","--no-renames","-z",...t])).split("\0"),n=[];for(let e=1;e{throw t})),g$.info(e,"Local diff outcome",{sourceControl:i,outcome:"partial_clone_names_only"})}let f=[];if(r.maxUntrackedFiles>0){f=await async function(e,t,r){let n=(await y$(t,["ls-files","--others","--exclude-standard"])).split("\n").map((e=>e.trim())).filter((e=>e.length>0));return n.length>r&&(n=n.slice(0,r)),(await Promise.all(n.map((async t=>{try{return await k$(e,t)}catch{return}})))).filter((e=>void 0!==e))}(t,o,r.maxUntrackedFiles);for(const e of f){const t=e.isSymlink?`${b$([e])}\n\\ No newline at end of file`:await y$(o,["diff","--no-color","--no-index","--","/dev/null",e.path],{ignoreErrors:!0,shouldNotTrimOutput:!0});p.diffs.push(...v$(t).diffs)}}if(a!==Le.ek.FILE_DIFFS||!0===p.fileContentsOmitted)for(const e of p.diffs)e.chunks=[];if(a===Le.ek.DIFFS_WITH_BEFORE_AND_AFTER&&!0!==p.fileContentsOmitted){const n=r.ref.length>0?r.ref:"HEAD";await Promise.all(p.diffs.map((async s=>{try{if("/dev/null"!==s.from)try{s.beforeFileContents=await y$(o,["show","--end-of-options",`${c}:${s.from}`],{shouldNotTrimOutput:!0})}catch{s.beforeFileContents=""}else s.beforeFileContents="";if("/dev/null"!==s.to)if(r.ref.length>0)try{s.afterFileContents=await y$(o,["show","--end-of-options",`${n}:${s.to}`],{shouldNotTrimOutput:!0})}catch{s.afterFileContents=""}else try{s.afterFileContents=(await k$(t,s.to)).contents}catch{try{s.afterFileContents=await y$(o,["show","--end-of-options",`${n}:${s.to}`],{shouldNotTrimOutput:!0})}catch{s.afterFileContents=""}}else s.afterFileContents=""}catch(t){g$.error(e,"Error fetching file contents for diff",t)}})))}const m=new Map;for(const e of p.diffs){const t="/dev/null"!==e.to?e.to:e.from;t&&m.set(t,e)}const g=[...m.keys()],w=r.ref.length>0?r.ref:"HEAD";try{const e=await HA({repoRoot:t,filePaths:g,getContent:async e=>{const t=m.get(e);if(t){if(void 0!==t.afterFileContents)return t.afterFileContents;try{if(t.to&&"/dev/null"!==t.to)return await y$(o,["show","--end-of-options",`${w}:${t.to}`],{shouldNotTrimOutput:!0})}catch{}}}});for(const[t,r]of e){const e=m.get(t);e&&(e.isGenerated=r.isGenerated)}}catch(t){g$.warn(e,"Generated-file detection failed; continuing without it",{error:t instanceof Error?t.message:String(t)})}const y=r.computePatchId&&void 0!==h?await async function(e,t){if(0===t.length)return;const{exitCode:r,stdout:n,stderr:o}=await e(["patch-id","--stable"],{input:t});if(0!==r)throw new Error(`git patch-id failed with code ${r}: ${o}`);return n.trim().split(/\s+/)[0]||void 0}(o,function(...e){const t=e.filter((e=>e.length>0));return 0===t.length?"":`${t.join("\n")}\n`}(h,b$(f))):void 0,v=!0===r.returnHeadSha?(await y$(o,["rev-parse","HEAD"])).trim():void 0,b=!0===r.returnHeadSha?(await y$(o,["status","--porcelain=v1","--untracked-files=all"])).trim().length>0:void 0,S=new Le.df({diff:p,submoduleDiffs:[],patchId:y,headSha:v,hasUncommittedChanges:b}),k=r.maxResponseBytes??0;if(k>0){const e=S.toBinary().byteLength;if(e>k)throw new Error(`GetDiffResponseTooLarge: ${e} bytes exceeds the ${k} byte limit`)}return S}class C${async execute(e,t){return _$(e,t.cwd,t)}}var E$=r("../proto/dist/generated/agent/v1/mcp_allowlist_precheck_exec_pb.js");class x${constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isMcpFullyAllowlisted(e,{providerIdentifier:t.providerIdentifier,toolName:t.toolName,annotationsJson:t.annotationsJson});return new E$.M({allowlisted:r})}}var P$=r("../proto/dist/generated/agent/v1/record_screen_exec_pb.js"),R$=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function I$(e){return null!==e.exitCode||null!==e.signalCode||e.killed}function T$(e,t){return"object"==typeof e&&null!==e&&"code"in e&&e.code===t}function A$(e){return e instanceof Error?e.message:String(e)}function $$(e,t){return new P$.Tj({result:{case:"failure",value:new P$.yH({error:t,kind:e})}})}function M$(e){return e instanceof Error?e.message.startsWith("Failed to load polished-renderer native binding")?"binding_load_failed":"code"in e&&"string"==typeof e.code?e.code:e.name:typeof e}function D$(e,t,r,n){const o=[],s=function(e,t){const r=e.ffmpegExitCode??e.childProcess.exitCode,n=e.ffmpegExitSignal??e.childProcess.signalCode;if(e.ffmpegDiedEarly||null!==e.ffmpegDiedTime||null!==r||null!==n)return`ffmpeg exited code=${r} signal=${n}${null!==e.ffmpegDiedTime?` ${Math.max(0,Math.round((t-e.ffmpegDiedTime)/1e3))}s before SAVE`:""}`}(t,n);return void 0!==s&&o.push(s),void 0!==r&&o.push(`stop failed: ${A$(r)}`),o.length>0?`${e} (${o.join("; ")})`:e}const O$=(0,zs.promisify)(ou.execFile);class F${constructor(e){if(this.activeRecording=null,this.inFlightSaves=[],this.onRecordingStartedCallback=null,this.onRecordingStoppedCallback=null,this.recordingStoppedCallbackInvoked=!1,this.artifactsDir=e.artifactsDir,this.stagingDir=e.stagingDir??"/opt/cursor/recording-staging/",this.display=e.display,this.disablePolishedRendering=e.disablePolishedRendering??!1,this.polishedRenderer=e.polishedRenderer,!this.disablePolishedRendering){if(!this.polishedRenderer)throw new Error("record_screen requires a polished recording renderer when polished rendering is enabled. This tool should run via exec-daemon where that dependency is bundled.");this.polishedRenderer.assertAvailable()}}setOnRecordingStarted(e){this.onRecordingStartedCallback=e}setOnRecordingStopped(e){this.onRecordingStoppedCallback=e}invokeStoppedCallbackOnce(){!this.recordingStoppedCallbackInvoked&&this.onRecordingStoppedCallback&&(this.recordingStoppedCallbackInvoked=!0,this.onRecordingStoppedCallback())}async cleanupRecording(e){try{await(e.inputEventLogger?.stop())}catch{}if(!I$(e.childProcess)&&e.childProcess.pid)try{await this.stopFfmpegRecording(e)}catch{try{process.kill(e.childProcess.pid,"SIGKILL")}catch{}}}getActiveInputEventLogger(){return this.activeRecording?.inputEventLogger??null}async dispose(){const e=this.inFlightSaves.map((e=>e.promise));if(e.length>0)try{await(0,Or.wj)(Promise.all(e),F$.IN_FLIGHT_SAVE_DISPOSE_TIMEOUT_MS,"Timed out waiting for in-flight recording save")}catch{}if(this.activeRecording){await this.cleanupRecording(this.activeRecording),this.invokeStoppedCallbackOnce();try{await Co.rm(this.activeRecording.sessionDir,{force:!0,recursive:!0})}catch{}this.activeRecording=null}}findInFlightSave(e){return this.inFlightSaves.find((t=>t.state===e))}clearActiveRecordingIfCurrent(e){this.activeRecording===e&&(this.activeRecording=null)}invokeStoppedCallbackIfCurrent(e){this.activeRecording===e&&this.invokeStoppedCallbackOnce()}sanitizeToolCallId(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}async ensureRecordingDirectoryExists(){await Co.mkdir(this.stagingDir,{recursive:!0}),await Co.mkdir(this.artifactsDir,{recursive:!0})}buildSessionDir(e){const t=this.sanitizeToolCallId(e),r=`session-${(new Date).toISOString().replace(/[:.]/g,"-")}-${t}`;return s.join(this.stagingDir,r)}validateAndNormalizeSaveAsFilename(e){let t=e.trim();return t.startsWith(this.artifactsDir)&&(t=t.slice(this.artifactsDir.length),t.startsWith("/")&&(t=t.slice(1))),t=t.trim(),0===t.length?{success:!1,reason:P$.y.UNSPECIFIED}:t.includes("/")||t.includes("\\")?{success:!1,reason:P$.y.SLASHES_NOT_ALLOWED}:(t=t.replace(/[^a-zA-Z0-9 ._-]/g,"_"),t=t.trim(),0===t.length?{success:!1,reason:P$.y.UNSPECIFIED}:(t.length>128&&(t=t.slice(0,128).trim()),t.toLowerCase().endsWith(".mp4")||(t=`${t}.mp4`),{success:!0,filename:t}))}async movePolishedVideo(e,t){try{return void await Co.rename(e,t)}catch(e){if(!T$(e,"EXDEV"))throw e}try{await Co.copyFile(e,t)}catch(e){throw await Co.rm(t,{force:!0}).catch((()=>{})),e}try{await Co.unlink(e)}catch(e){throw await Co.rm(t,{force:!0}).catch((()=>{})),e}}async getUniqueArtifactVideoPath(e){const t=s.parse(e),r=t.name||"recording",n=t.ext||".mp4";let o=`${r}${n}`,i=2;for(;;){const e=s.join(this.artifactsDir,o);try{const t=await Co.open(e,"wx");return await t.close(),e}catch(e){if(!T$(e,"EEXIST"))throw e;o=`${r}-${i}${n}`,i++}}}async resolveArtifactVideoPath(e){const{saveAsFilename:t,stagingSessionDir:r}=e;let n,o;if(t){const e=this.validateAndNormalizeSaveAsFilename(t);e.success?o=e.filename:(n=e.reason,o=`${s.basename(r)}.mp4`)}else o=`${s.basename(r)}.mp4`;return{finalVideoPath:await this.getUniqueArtifactVideoPath(o),requestedFilePathRejectedReason:n}}async getVideoDurationMs(e){const{stdout:t}=await(0,su.D9)(O$,"ffprobe",["-v","error","-show_entries","format=duration","-of","default=noprint_wrappers=1:nokey=1",e],{encoding:"utf8"}),r=parseFloat(t.trim());if(!Number.isFinite(r)||r<0)throw new Error(`Invalid video duration from ffprobe: ${t.trim()}`);return Math.floor(1e3*r)}async getVideoDimensions(e){const{stdout:t}=await(0,su.D9)(O$,"ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=width,height","-of","csv=p=0:s=x",e],{encoding:"utf8"}),[r,n]=t.trim().split("x"),o=Number.parseInt(r,10),s=Number.parseInt(n,10);if(!Number.isFinite(o)||!Number.isFinite(s))throw new Error(`Invalid video dimensions from ffprobe: ${t.trim()}`);if(o<=0||s<=0)throw new Error(`Invalid non-positive video dimensions from ffprobe: ${t.trim()}`);return{width:o,height:s}}async renderPolished(e,t){const r=s.join(t,"recording"),n=s.join(r,"recording_full.mp4");try{await this.polishedRenderer.renderRecordingSession({stagingSessionDir:t,outputVideoPath:n,fps:F$.PROXY_TARGET_FPS,includeBrandTag:!0}),await Co.access(n,Co.constants.R_OK)}catch(t){const r=(0,$.fU)(e);throw r?.setAttribute("error.type",M$(t)),r?.setStatus({code:2}),t}return n}async getVideoFramerate(e){try{const{stdout:t}=await(0,su.D9)(O$,"ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=r_frame_rate","-of","default=noprint_wrappers=1:nokey=1",e],{encoding:"utf8"}),r=t.trim();if(r.includes("/")){const[e,t]=r.split("/"),n=Number.parseFloat(e),o=Number.parseFloat(t);if(Number.isFinite(n)&&Number.isFinite(o)&&0!==o){const e=n/o;if(e>0&&e<500)return Math.round(e)}}else{const e=Number.parseFloat(r);if(Number.isFinite(e)&&e>0&&e<500)return Math.round(e)}console.warn(`[record-screen] Unexpected ffprobe r_frame_rate output "${r}", defaulting to ${F$.PROXY_TARGET_FPS}fps`)}catch(e){console.warn(`[record-screen] Failed to read video framerate: ${e instanceof Error?e.message:String(e)}, defaulting to ${F$.PROXY_TARGET_FPS}fps`)}return F$.PROXY_TARGET_FPS}async startFfmpegRecording(e,t){const r=s.join(t,"recording");await Co.mkdir(r,{recursive:!0});const n=s.join(r,"recording_render_proxy_1080p.mp4"),o="windowsDesktop"===e.kind?["-f","gdigrab","-i","desktop"]:["-video_size",e.resolution,"-framerate",String(await this.detectRefreshRate(e.display)),"-draw_mouse","0","-f","x11grab","-i",e.display],i=["-vf",`scale=${F$.PROXY_TARGET_WIDTH}:-2:flags=lanczos,fps=${F$.PROXY_TARGET_FPS}`,"-c:v","libx264","-preset",F$.PROXY_PRESET,"-crf",String(F$.PROXY_CRF),"-pix_fmt","yuv420p","-profile:v","high","-x264-params","keyint=1:min-keyint=1:scenecut=0:bframes=0","-movflags","+faststart","-tune","fastdecode"],a=["-vf",`scale=${F$.PROXY_TARGET_WIDTH}:-2:flags=lanczos`,"-c:v","libx264","-preset",F$.PROXY_PRESET,"-pix_fmt","yuv420p","-movflags","+faststart"],c=this.disablePolishedRendering?a:i,l=(0,su.D9)(ou.spawn,"ffmpeg",[...o,...c,"-y",n],{stdio:["win32"===process.platform?"pipe":"ignore","pipe","pipe"],detached:"win32"!==process.platform,windowsHide:!0}),u=new Promise(((e,t)=>{let r="",n=!1;l.stderr?.on("data",(t=>{r+=t.toString(),!n&&r.includes("frame=")&&(n=!0,e(Date.now()))}));const o=setTimeout((()=>{n||t(new Error("ffmpeg did not start encoding within 5 seconds"))}),5e3);l.once("exit",((e,r)=>{clearTimeout(o),n||t(new Error(`ffmpeg exited before starting: code=${e} signal=${r}`))})),l.once("error",(e=>{clearTimeout(o),n||t(new Error(`ffmpeg failed to start: ${e.message}`))}))}));return await new Promise(((e,t)=>{const r=setTimeout(e,300);l.once("error",(e=>{clearTimeout(r),t(new Error(`Failed to start ffmpeg: ${e.message}`))})),l.once("exit",((e,n)=>{clearTimeout(r),t(null!==e&&0!==e?new Error(`ffmpeg exited with code ${e}`):null!==n?new Error(`ffmpeg killed by signal ${n}`):new Error("ffmpeg exited unexpectedly during startup"))}))})),{process:l,videoStartedPromise:u}}async detectRefreshRate(e){try{return(await Wg(e)).display.refreshRate}catch(e){return console.warn(`[record-screen] Failed to detect refresh rate: ${e instanceof Error?e.message:String(e)}, using default ${F$.DEFAULT_REFRESH_RATE}Hz`),F$.DEFAULT_REFRESH_RATE}}async runFfmpegCommand(e,t){return await new Promise(((r,n)=>{const o=(0,su.D9)(ou.spawn,"ffmpeg",t,{stdio:["ignore","ignore","pipe"]});let s="";o.stderr?.on("data",(e=>{s.length<2e4&&(s+=e.toString())})),o.once("error",(t=>{n(new Error(`ffmpeg ${e} failed to start: ${t instanceof Error?t.message:String(t)}`))})),o.once("close",(t=>{0===t?r():n(new Error(`ffmpeg ${e} exited with code ${t}: ${s.trim()}`))}))}))}async saveRecordingDataPackage(e){const{sessionDir:t,durationMs:r,recordingStartEpochMs:n,ffmpegStartedEpochMs:o,inputEvents:i,resolution:a,renderProxies:c}=e,l=s.join(t,"recording"),u=s.join(l,"recording-data.json"),d=o-n,h=i.map((e=>({executionTimestampMs:e.executionTimestampMs,commandDurationMs:e.commandDurationMs,positionBefore:e.positionBefore,positionAfter:e.positionAfter,cursorTypeAfter:e.cursorTypeAfter,action:{action:this.serializeAction(e.action)}}))),p={version:3,durationMs:r,recordingStartEpochMs:n,ffmpegStartedEpochMs:o,eventToVideoOffsetMs:d,displayWidth:a.display.width,displayHeight:a.display.height,apiWidth:a.api.width,apiHeight:a.api.height,inputEvents:h,renderProxies:c??null};await Co.writeFile(u,JSON.stringify(p,null,2))}serializeAction(e){const{action:t}=e,r={case:t.case};switch(t.case){case"click":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null,button:t.value.button,count:t.value.count,modifierKeys:t.value.modifierKeys};break;case"mouseMove":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null};break;case"type":r.value={text:t.value.text};break;case"key":r.value={key:t.value.key,holdDurationMs:t.value.holdDurationMs};break;case"scroll":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null,direction:t.value.direction,amount:t.value.amount,modifierKeys:t.value.modifierKeys};break;case"drag":r.value={path:t.value.path.map((e=>({x:e.x,y:e.y}))),button:t.value.button};break;case"wait":r.value={durationMs:t.value.durationMs};break;case"screenshot":case"cursorPosition":case"mouseDown":case"mouseUp":r.value=t.value;break;default:r.value={}}return r}async stopFfmpegRecording(e){const{childProcess:t}=e;if(I$(t)||!t.pid)return;const r=t.pid;return new Promise(((e,n)=>{const o=setTimeout((()=>{try{try{process.kill(-r,"SIGKILL")}catch{process.kill(r,"SIGKILL")}}catch{}n(new Error("Timeout waiting for ffmpeg to stop"))}),2e4);t.once("exit",(()=>{clearTimeout(o),e()})),t.once("error",(e=>{clearTimeout(o),n(new Error(`Error stopping ffmpeg: ${e.message}`))}));try{if(t.stdin)return t.stdin.on("error",(()=>{})),void t.stdin.end("q");try{process.kill(-r,"SIGTERM")}catch{process.kill(r,"SIGTERM")}}catch(t){if(clearTimeout(o),T$(t,"ESRCH"))return void e();n(new Error(`Failed to send SIGTERM: ${t instanceof Error?t.message:String(t)}`))}}))}async performSave(e,t,r){const n=Date.now();let o=P$.Wg.INTERNAL;try{const i=await(r.inputEventLogger?.stop())??[],a=r.inputEventLogger?.getRecordingStartTime()??r.startTime;let c;this.invokeStoppedCallbackIfCurrent(r);try{!I$(r.childProcess)&&r.childProcess.pid&&await this.stopFfmpegRecording(r)}catch(e){c=e,console.warn(`[record-screen] Failed to stop ffmpeg: ${A$(e)}`)}const l=r.ffmpegStartedEpochMs??a,u=r.sessionDir,d=s.join(u,"recording"),h=s.join(d,"recording_render_proxy_1080p.mp4");let p,f,m;try{await Co.access(h,Co.constants.R_OK)}catch(e){await this.cleanupRecording(r),this.clearActiveRecordingIfCurrent(r);const t=T$(e,"ENOENT"),o=t?`Recording proxy not found at ${h}`:`Recording proxy at ${h} could not be validated: ${A$(e)}`;return $$(t?P$.Wg.PROXY_MISSING:P$.Wg.STAGING_IO,D$(o,r,c,n))}try{if([p,f,m]=await Promise.all([this.getVideoDurationMs(h),this.getVideoDimensions(h),this.getVideoFramerate(h)]),p<=0)throw new Error(`Recording proxy has zero duration at ${h}`)}catch(e){await this.cleanupRecording(r);const t=A$(e),o=t.includes(h)?t:`Recording proxy at ${h} could not be validated: ${t}`;return $$(P$.Wg.PROXY_INVALID,D$(o,r,c,n))}const g={profileVersion:F$.PROXY_PROFILE_VERSION,generatedAtEpochMs:Date.now(),source:{width:f.width,height:f.height,durationMs:p,fps:m},artifacts:[{name:"render_proxy_1080p",path:"recording_render_proxy_1080p.mp4",width:f.width,height:f.height,fps:F$.PROXY_TARGET_FPS,codec:"h264",profile:F$.PROXY_PROFILE_VERSION,keyint:1,status:"success",elapsedMs:0}]};o=P$.Wg.STAGING_IO,void 0!==r.resolution&&await this.saveRecordingDataPackage({sessionDir:u,durationMs:p,recordingStartEpochMs:a,ffmpegStartedEpochMs:l,inputEvents:i,resolution:r.resolution,renderProxies:g}),o=P$.Wg.ARTIFACT_WRITE_FAILED;const{finalVideoPath:w,requestedFilePathRejectedReason:y}=await this.resolveArtifactVideoPath({saveAsFilename:t.saveAsFilename,stagingSessionDir:u});try{if(this.disablePolishedRendering)await Co.copyFile(h,w);else{o=P$.Wg.RENDER_FAILED;const t=await this.renderPolished(e,u);o=P$.Wg.ARTIFACT_WRITE_FAILED,await this.movePolishedVideo(t,w)}}catch(e){throw await Co.rm(w,{force:!0}).catch((()=>{})),e}try{await Co.rm(u,{force:!0,recursive:!0})}catch(e){console.warn(`[record-screen] Failed to remove staging session ${u}: ${A$(e)}`)}return this.clearActiveRecordingIfCurrent(r),new P$.Tj({result:{case:"saveSuccess",value:new P$.ol({path:w,recordingDurationMs:we.protoInt64.parse(p.toString()),requestedFilePathRejectedReason:y})}})}catch(e){return await this.cleanupRecording(r),this.invokeStoppedCallbackIfCurrent(r),$$("binding_load_failed"===M$(e)?P$.Wg.RENDERER_UNAVAILABLE:o,A$(e))}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,$.VI)(e.withName("LocalRecordScreenExecutor.execute")),!1);try{await this.ensureRecordingDirectoryExists()}catch(e){return $$(P$.Wg.STAGING_IO,`Failed to create recording directory: ${e instanceof Error?e.message:String(e)}. Ensure the parent directory exists and has write permissions, or run: sudo mkdir -p ${this.stagingDir} ${this.artifactsDir} && sudo chmod 777 ${this.stagingDir} ${this.artifactsDir}`)}if(t.mode===P$.$u.UNSPECIFIED)return $$(P$.Wg.INVALID_MODE,"Mode must be one of START_RECORDING, SAVE_RECORDING, DISCARD_RECORDING");switch(t.mode){case P$.$u.START_RECORDING:{this.recordingStoppedCallbackInvoked=!1;let e=!1;if(this.activeRecording){const t=this.activeRecording;if(!this.inFlightSaves.some((e=>e.state===t))){e=!0;try{await this.cleanupRecording(t),await Co.rm(t.sessionDir,{force:!0,recursive:!0}).catch((()=>{}))}catch{}}this.activeRecording=null}let r,n=null,o=null,s=P$.Wg.STAGING_IO;try{o=this.buildSessionDir(t.toolCallId||"recording"),await Co.mkdir(o,{recursive:!0}),s=P$.Wg.DISPLAY_UNAVAILABLE;const i="win32"===process.platform?void 0:await Wg(this.display),a=void 0===i?{kind:"windowsDesktop"}:{kind:"x11",display:this.display,resolution:i.resolutionString};s=P$.Wg.FFMPEG_START_FAILED;const{process:c,videoStartedPromise:l}=await this.startFfmpegRecording(a,o);n=c;const u=this.disablePolishedRendering?void 0:i?.resolution;void 0!==u&&(s=P$.Wg.INTERNAL,r=new Xg({displayNum:Ug(this.display),resolution:u}),await r.start());const d=r?.getRecordingStartTime()??Date.now();let h;s=P$.Wg.FFMPEG_START_FAILED;try{h=await l}catch(e){throw new Error(`ffmpeg failed to start encoding: ${e instanceof Error?e.message:String(e)}`)}const p={childProcess:n,sessionDir:o,startTime:d,inputEventLogger:r,resolution:u,ffmpegStartedEpochMs:h,ffmpegDiedEarly:!1,ffmpegDiedTime:null,ffmpegExitCode:null,ffmpegExitSignal:null};this.activeRecording=p,this.onRecordingStartedCallback&&r&&this.onRecordingStartedCallback(r),n.once("exit",((e,t)=>{p.ffmpegDiedEarly=!0,p.ffmpegDiedTime=Date.now(),p.ffmpegExitCode=e,p.ffmpegExitSignal=t}));const f=!!t.saveAsFilename;return new P$.Tj({result:{case:"startSuccess",value:new P$.T4({wasPriorRecordingCancelled:e,wasSaveAsFilenameIgnored:f})}})}catch(e){if(r)try{await r.stop()}catch{}if(n&&!n.killed&&n.pid)try{process.kill(n.pid,"SIGKILL")}catch{}return o&&await Co.rm(o,{force:!0,recursive:!0}).catch((()=>{})),this.activeRecording=null,$$(s,A$(e))}}case P$.$u.SAVE_RECORDING:{if(!this.activeRecording)return 1===this.inFlightSaves.length?await this.inFlightSaves[0].promise:$$(P$.Wg.NO_ACTIVE_RECORDING,"No active recording to save");const e=this.activeRecording,r=this.findInFlightSave(e);if(r)return await r.promise;const o=Promise.resolve().then((()=>this.performSave(n.ctx,t,e))),s={state:e,promise:o};this.inFlightSaves.push(s);try{return await o}finally{this.inFlightSaves=this.inFlightSaves.filter((e=>e!==s))}}case P$.$u.DISCARD_RECORDING:{if(!this.activeRecording)return $$(P$.Wg.NO_ACTIVE_RECORDING,"No active recording to discard");const e=this.activeRecording;if(this.findInFlightSave(e))return $$(P$.Wg.SAVE_IN_PROGRESS,"Save in progress for this recording; wait for it or start a new recording");let t=P$.Wg.INTERNAL;try{return await(e.inputEventLogger?.stop()),this.invokeStoppedCallbackOnce(),!I$(e.childProcess)&&e.childProcess.pid&&(t=P$.Wg.FFMPEG_STOP_FAILED,await this.stopFfmpegRecording(e)),t=P$.Wg.STAGING_IO,await Co.rm(e.sessionDir,{force:!0,recursive:!0}),this.activeRecording=null,new P$.Tj({result:{case:"discardSuccess",value:new P$.N8}})}catch(r){await this.cleanupRecording(e),this.invokeStoppedCallbackOnce();const n=e.sessionDir;let o=!1;try{await Co.rm(n,{force:!0,recursive:!0}),o=!0}catch{}this.activeRecording=null;return $$(t,`Failed to discard recording: ${r instanceof Error?r.message:String(r)}${o?"":`. Session may remain at: ${n}`}`)}}default:{const e=t.mode;return $$(P$.Wg.INVALID_MODE,`Unhandled recording mode: ${String(e)}`)}}}catch(e){r.error=e,r.hasError=!0}finally{R$(r)}}}async function N$(e){const t=await(0,Co.readdir)(e,{withFileTypes:!0}).catch((()=>[])),r=[];for(const n of t){const t=s.join(e,n.name),o={name:n.name,path:t,isDirectory:n.isDirectory()};n.isDirectory()&&(o.children=await N$(t)),r.push(o)}return r.sort(((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)))}function L$(e,t="",r=!0){const n=[`${t}${r?"└── ":"├── "}${e.isDirectory?`${e.name}/`:e.name}`],o=e.children;if(o?.length){const e=t+(r?" ":"│ ");o.forEach(((t,r)=>{const s=r===o.length-1;n.push(...L$(t,e,s))}))}return n}async function j$(e){if(!await(0,Co.access)(e,Co.constants.R_OK).then((()=>!0),(()=>!1)))return"(No notes directory yet - will be created when you write your first note)";const t=await N$(e);return 0===t.length?"(Notes directory is empty)":t.flatMap(((e,r)=>L$(e,"",r===t.length-1))).join("\n")}async function U$(e,t){return j$(s.join(e,"agent-notes",t))}async function B$(e){return j$(s.join(e,"agent-notes","shared"))}F$.IN_FLIGHT_SAVE_DISPOSE_TIMEOUT_MS=3e4,F$.PROXY_TARGET_WIDTH=1920,F$.PROXY_TARGET_FPS=60,F$.PROXY_CRF=17,F$.PROXY_PRESET="veryfast",F$.PROXY_PROFILE_VERSION="render-proxy-h264-all-i-v1",F$.DEFAULT_REFRESH_RATE=60;var W$=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},H$=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const q$=3e3,z$=(0,l.h)("local-exec:request-context"),G$=Symbol("sectionLoadTimedOut");function V$(e,t){if(void 0===t)return e;let r;const n=new Promise((e=>{r=setTimeout((()=>e(G$)),t)}));return e.catch((()=>{})),Promise.race([e,n]).finally((()=>{clearTimeout(r)}))}class K${async read(e,t){const r=this.inFlight??this.begin(e),n=this.last;if(void 0===n)return r;const o=await V$(r,t).catch((()=>G$));return o===G$?n.value:o}prefetch(e){void 0===this.inFlight&&this.begin(e).catch((()=>{}))}begin(e){const t=e();this.inFlight=t;const r=()=>{this.inFlight===t&&(this.inFlight=void 0)};return t.then((e=>{this.last={value:e},r()}),r),t}}async function J$(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{W$(o,(0,$.VI)(e.withName("LocalRequestContextExecutor.getGitStatusForRepoPath")),!1);try{return(await t.exec(e,r,["--no-optional-locks","status","--short","--branch"],{timeout:n,caller:"getGitStatusForRepoPath"})).stdout}catch{return}}catch(e){o.error=e,o.hasError=!0}finally{H$(o)}}async function Z$(e,t,r,n){try{const o=(await t.exec(e,r,["rev-parse","--abbrev-ref","HEAD"],{timeout:n,caller:"getGitBranchForRepoPath"})).stdout.trim();if("HEAD"===o||0===o.length)return;return o}catch{return}}async function X$(e,t,r,n){const o=e=>{let t;const r=new Promise((e=>{t=setTimeout((()=>{e(void 0)}),n)}));return Promise.race([e.catch((()=>{})),r]).finally((()=>{void 0!==t&&clearTimeout(t)}))},[s,i]=await Promise.all([o(J$(e,t,r,n)),o(Z$(e,t,r,n))]);return{status:s,branchName:i}}async function Q$(e,t,r={}){const{projectDir:n,notesSessionId:s,agentNotesEnabled:i,reportProcessWorkingDirectory:a,getSmartModeClassifierAutoModeEnabled:c,devForceNextSmartModeClassifierBlockToken:l,isWorkingDirHomeDir:u,getSandboxEnabled:d,getSandboxSupported:h,getNetworkAllowlistInfo:p,userTerminalHint:f,artifactsFolder:m,secretRedactionEnabled:g,getComputerUseSupported:w,getComputerUseDesktop:y,getMockPromptTime:v}=r,b=y?.(),S=`${o.default.platform()} ${o.default.release()}`,k=(0,Oo.G6)(f),_=v?.(),C=(()=>{try{return(new Intl.DateTimeFormat).resolvedOptions().timeZone??void 0}catch{return}})(),E=n,x=n?`${n}/terminals`:void 0,P=n&&!1!==i?`${n}/agent-notes/shared`:void 0,R=n&&s&&!1!==i?`${n}/agent-notes/${s}`:void 0,I=n?`${n}/agent-transcripts`:void 0,T=!!d&&d(),A=h?.(),$=c?.();let M;if(p)try{const e=await V$(p(),3e3);e!==G$&&(M=e)}catch{M=void 0}return new Dr.GE({osVersion:S,workspacePaths:t,shell:k,sandboxEnabled:T,projectFolder:E,terminalsFolder:x,agentSharedNotesFolder:P,agentConversationNotesFolder:R,agentTranscriptsFolder:I,timeZone:C,...!1!==a&&{processWorkingDirectory:process.cwd()},artifactsFolder:m,...void 0!==$&&{smartModeClassifierAutoModeEnabled:$},...void 0!==l&&{devForceNextSmartModeClassifierBlockToken:l},...void 0!==_&&{devMockPromptTime:we.Timestamp.fromDate(_)},...void 0!==g&&{secretRedactionEnabled:g},...void 0!==A&&{sandboxSupported:A},...void 0!==M?.hasDefaults&&{sandboxNetworkHasDefaults:M.hasDefaults},...M?.explicitEntries&&M.explicitEntries.length>0&&{sandboxNetworkExplicitAllowlist:M.explicitEntries},...void 0!==w&&{computerUseSupported:w()},...void 0!==b&&{computerUseDesktop:b},...void 0!==u&&{isWorkingDirHomeDir:u}})}const Y$={type:"object",properties:{},additionalProperties:!1};function eM(e,t){return{tools:(!0===t?.internalBrowserProvidersOnly?e.servers.filter((e=>Kn.has(e.serverIdentifier))):e.servers).flatMap((e=>e.tools)).map((e=>new wn.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,...!0===t?.inputSchemaJson?{inputSchemaJson:void 0===e.inputSchema?void 0:JSON.stringify(e.inputSchema)}:{inputSchema:e.inputSchema?we.Value.fromJson(e.inputSchema):void 0}}))),mcpInstructions:e.servers.flatMap((e=>e.instructions))}}function tM(e,t){const r=!0===t?.slimDescriptors,n=e.servers.map((e=>{const n=e.instructions.map((e=>e.instructions)).filter(Boolean).join("\n"),o=e.tools.map((e=>new wn.E$({toolName:e.toolName,...Db(e.annotations),...r?{}:{description:e.description,...!0===t?.inputSchemaJson?{inputSchemaJson:void 0===e.inputSchema?void 0:JSON.stringify(e.inputSchema)}:{inputSchema:void 0!==e.inputSchema?we.Value.fromJson(e.inputSchema):void 0}}})));return!Vn(e.serverIdentifier)||!0!==t?.alwaysExposeVirtualMcpAuthTool&&"needsAuth"!==e.status||o.some((e=>e.toolName===nT))||o.push(new wn.E$({toolName:nT,...r?{}:{description:oT,...!0===t?.inputSchemaJson?{inputSchemaJson:JSON.stringify(Y$)}:{inputSchema:we.Value.fromJson(Y$)}}})),new wn.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,serverUseInstructions:n||void 0,tools:o})}));return new wn.U_({enabled:!0,mcpDescriptors:n})}function rM(e){const t=e?.trim();return t||void 0}function nM(e,t){const r=function(e){return rM(e.serverIdentifier)}(e);if(r)return r;const n=rM(e.serverName);return n?t.get(n)??n:void 0}class oM{constructor(e){this.mcpLease=e}async getState(e){const[t,r]=await Promise.all([this.mcpLease.getTools(e).catch((t=>(z$.warn(e,"Error fetching MCP tools",{error:t}),[]))),this.mcpLease.getInstructions(e).catch((t=>(z$.warn(e,"Error fetching MCP instructions",{error:t}),[])))]);return function(e,t,r,n=!1){const o=new Map;for(const t of e)o.has(t.providerIdentifier)||o.set(t.providerIdentifier,t.clientKey);const s=t.map((e=>nM(e,o))).filter((e=>Boolean(e))),i=[...new Set([...e.map((e=>e.clientKey)),...s,...Array.from(r?.entries()??[]).filter((([,e])=>"connected"!==e.status)).map((([e])=>e))])];if(n&&void 0!==r){const e=new Map(Array.from(r.keys(),((e,t)=>[e,t])));i.sort(((t,r)=>(e.get(t)??e.size)-(e.get(r)??e.size)))}return{servers:i.map((n=>{const s=e.filter((e=>e.clientKey===n));return{serverName:s[0]?.providerIdentifier??n,serverIdentifier:n,plugin:s[0]?.plugin,marketplace:s[0]?.marketplace,tools:s,instructions:t.filter((e=>nM(e,o)===n)),status:r?.get(n)?.status,errorMessage:r?.get(n)?.errorMessage}}))}}(t,r,await async function(e,t){const r=await t.getClients(e).catch((t=>(z$.warn(e,"Error fetching MCP clients",{error:t}),{}))),n=await Promise.all(Object.entries(r).map((async([t,r])=>{const n=await r.getState(e).catch((()=>({kind:"error",message:"Failed to fetch MCP client state"})));return[t,{status:Yn(n),errorMessage:"error"===n.kind&&void 0!==n.message?n.message:void 0}]})));return new Map(n)}(e,this.mcpLease))}}function sM(e){return new Ac._W({result:{case:"success",value:new Ac.pv({servers:e.servers.map((e=>new Ac.XE({serverName:e.serverName,serverIdentifier:e.serverIdentifier,plugin:e.plugin,marketplace:e.marketplace,tools:e.tools.map((e=>new wn.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?we.Value.fromJson(e.inputSchema):void 0,metaJson:Jn(e._meta),...Db(e.annotations)}))),instructions:e.instructions,status:e.status,errorMessage:e.errorMessage})))})}})}class iM{constructor(e,t,r){this.mcpStateAccessor=e,this.ensureMcpServersLoaded=t,this.options=r}async execute(e,t){if(void 0!==t.ruleSubjects&&void 0!==this.options?.serverRuleSubjects)return function(e,t){const r={commandPatterns:t.commandPatterns,serverUrlPatterns:t.serverUrlPatterns},n=[];for(const[t,o]of e){const e=void 0!==o.command?{transport:Ac.zj.STDIO,value:o.command,matched:{command:o.command}}:void 0!==o.url?{transport:Ac.zj.HTTP,value:o.url,matched:{url:o.url}}:void 0;void 0!==e&&n.push(new Ac.XE({serverName:t,serverIdentifier:t,ruleSubject:new Ac.D0({transport:e.transport,...xC(e.matched,r)?{value:e.value}:{}})}))}return new Ac._W({result:{case:"success",value:new Ac.pv({servers:n})}})}(this.options.serverRuleSubjects(),t.ruleSubjects);try{await(this.ensureMcpServersLoaded?.(e,t.serverIdentifiers,{wait:!t.kickOnly}))}catch{}t.refreshPolicy!==Ac.ew.FORCE_IF_MISSING&&t.refreshPolicy!==Ac.ew.FORCE||await(this.mcpStateAccessor.refreshNow?.(e));const r=await this.mcpStateAccessor.getState(e);if(!0===this.options?.filterToRequestedServers&&t.serverIdentifiers.length>0){const e=new Set(t.serverIdentifiers),n=r.servers.filter((t=>e.has(t.serverIdentifier)));if(n.length>0)return sM({...r,servers:n})}return sM(r)}}class aM{constructor(e,t,r,n,o,s,i,a,c={}){this.cursorRulesService=e,this.cloudRulesService=t,this.subagentsService=r,this.repositoryProvider=n,this.grepProvider=o,this.mcpStateAccessor=s,this.gitExecutor=i,this.workspacePaths=a,this.reusedGitInfo=new Map,this.reusedMcpState=new K$,this.reusedAgentSkills=new K$,this.reusedAdminCommandDenylist=new K$,this.cachedWorkspaces=new Map,this.inFlightWorkspaceWarms=new Map;const{projectDir:l,getSmartModeClassifierAutoModeEnabled:u,getAdminCommandDenylist:d,devForceNextSmartModeClassifierBlockToken:h,isWorkingDirHomeDir:p,agentNotesEnabled:f,reportProcessWorkingDirectory:m,createFileWatcher:g,getSandboxEnabled:w,getSandboxSupported:y,getNetworkAllowlistInfo:v,userTerminalHint:b,getMcpFileSystemOptions:S,mcpMetaToolEnabled:k,mcpMetaToolSlimDescriptors:_,mcpInputSchemaJson:C,alwaysExposeVirtualMcpAuthTool:E,getArtifactsFolder:x,secretRedactionEnabled:P,attributionConfigProvider:R,isAttributionDisabledByAdmin:I,getAgentSkills:T,additionalRules:A,getComputerUseSupported:$,getComputerUseDesktop:M,getMockPromptTime:D}=c;this.projectDir=l,this.isWorkingDirHomeDir=p,this.agentNotesEnabled=f??!0,this.reportProcessWorkingDirectory=m??!0,this.getSandboxEnabled=w,this.getSandboxSupported=y,this.getNetworkAllowlistInfo=v,this.getSmartModeClassifierAutoModeEnabled=u,this.getAdminCommandDenylist=d,this.devForceNextSmartModeClassifierBlockToken=h,this.getMockPromptTime=D,this.userTerminalHint=b,this.getMcpFileSystemOptions=S,this.mcpMetaToolEnabled=k??!1,this.mcpMetaToolSlimDescriptors=_??!1,this.mcpInputSchemaJson=C??!1,this.alwaysExposeVirtualMcpAuthTool=E??!1,this.getArtifactsFolder=x,this.secretRedactionEnabled=P,this.attributionConfigProvider=R,this.isAttributionDisabledByAdmin=I,this.getAgentSkills=T,this.additionalRules=A??[],this.getComputerUseSupported=$,this.getComputerUseDesktop=M,this.reduceContextHotPath=c.reduceContextHotPath??!1,this.sectionLoadTimeoutMs=c.sectionLoadTimeoutMs,this.reportSectionCompleteness=c.reportSectionCompleteness??!1,this.freshSectionWaitMs=c.freshSectionWaitMs,this.onRequestContext=c.onRequestContext,this.mcpFieldsFromCaller=c.mcpFieldsFromCaller??!1,!0!==c.deferWarmup&&this.warm(),void 0!==g&&(this.fileWatcher=g(),this.fileWatcher.onDidChange((e=>{this.onWorkspacePathChanged(e)})),this.fileWatcher.onDidCreate((e=>{this.onWorkspacePathChanged(e)})),this.fileWatcher.onDidDelete((e=>{this.onWorkspacePathChanged(e)})))}warm(){this.warmWorkspaceCaches(),void 0===this.globalCache&&this.rebuildGlobalCache()}onWorkspacePathChanged(e){this.rebuildAllCaches()}getWorkspaceCache(e){return this.cachedWorkspaces.get(e)}warmWorkspaceCaches(){const e=(0,y.q6)();Promise.all(this.workspacePaths.map((t=>this.ensureWorkspaceCacheWarm(e,t))))}ensureWorkspaceCacheWarm(e,t){if(this.cachedWorkspaces.has(t))return Promise.resolve();const r=this.inFlightWorkspaceWarms.get(t);if(void 0!==r)return r;const n=this.warmWorkspaceCache(e,t).finally((()=>{this.inFlightWorkspaceWarms.delete(t)}));return this.inFlightWorkspaceWarms.set(t,n),n}async warmWorkspaceCache(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=W$(r,(0,$.VI)(e.withName("LocalRequestContextExecutor.warmWorkspaceCache")),!1),o=await Ya(n.ctx,this.gitExecutor,t),s=o?await sc(n.ctx,this.gitExecutor,o):void 0,i={repoPath:o??void 0,remoteUrl:void 0!==s?ic(s):void 0};if(this.cachedWorkspaces.set(t,i),void 0!==this.freshSectionWaitMs&&void 0!==i.repoPath){const e=i.repoPath;this.gitInfoSection(e).prefetch((()=>X$((0,y.q6)(),this.gitExecutor,e,q$)))}}catch(e){r.error=e,r.hasError=!0}finally{H$(r)}}gitInfoSection(e){let t=this.reusedGitInfo.get(e);return void 0===t&&(t=new K$,this.reusedGitInfo.set(e,t)),t}rebuildAllCaches(){this.cacheDebounceTimeout&&clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=setTimeout((()=>{this.cacheDebounceTimeout=void 0,this.rebuildGlobalCache()}),5e3)}invalidateGlobalCache(){this.globalCache=void 0,this.lastGoodGlobalCache=void 0,this.globalCacheTraceId=void 0}refreshGlobalCache(){this.cacheDebounceTimeout&&(clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=void 0),this.rebuildGlobalCache()}rebuildGlobalCache(){const e={stack:[],error:void 0,hasError:!1};try{const t=(0,y.q6)(),r=W$(e,(0,$.VI)(t.withName("LocalRequestContextExecutor.rebuildGlobalCache")),!1);this.globalCacheTraceId=r.span.spanContext().traceId;const n=this.computeGlobalCache(r.ctx);return this.globalCache=n,(this.reduceContextHotPath||void 0!==this.sectionLoadTimeoutMs||void 0!==this.freshSectionWaitMs)&&n.then((e=>{this.globalCache===n&&(this.lastGoodGlobalCache=e)}),(()=>{this.globalCache===n&&(this.globalCache=void 0)})),n}catch(t){e.error=t,e.hasError=!0}finally{H$(e)}}async computeGlobalCache(e){const t={stack:[],error:void 0,hasError:!1};try{const r=W$(t,(0,$.VI)(e.withName("LocalRequestContextExecutor.computeGlobalCache")),!1),n=AbortSignal.timeout(1e3),o=performance.now(),s={},i=(e,t)=>{const r=performance.now();return t.finally((()=>{s[e]=Math.round(performance.now()-r)}))},[a,c,l,u]=await Promise.all([i("cursorRules",this.cursorRulesService.getAllCursorRules(r.ctx)),i("cloudRule",this.cloudRulesService?this.cloudRulesService.getCloudRule(r.ctx):Promise.resolve(null)),i("codebaseRef",this.repositoryProvider.getCodebaseReference(r.ctx,n).catch((()=>{}))),i("subagents",this.subagentsService?this.subagentsService.getAllSubagents().catch((()=>[])):Promise.resolve([]))]),d=Math.round(performance.now()-o);return d>1e3&&z$.warn(r.ctx,"computeGlobalCache: slow",{totalMs:d,...s,ruleCount:a.length}),{rules:[...this.additionalRules,...a],cloudRule:c,codebaseReference:l,customSubagents:u}}catch(e){t.error=e,t.hasError=!0}finally{H$(t)}}dispose(){this.cacheDebounceTimeout&&(clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=void 0),this.fileWatcher&&(this.fileWatcher.dispose(),this.fileWatcher=void 0),this.globalCache=void 0,this.lastGoodGlobalCache=void 0}async collectWorkspaceCaches(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=W$(r,(0,$.VI)(e.withName("LocalRequestContextExecutor.collectWorkspaceCaches")),!1);let o;if(this.grepProvider.getTrackedState)try{o=await this.grepProvider.getTrackedState(this.workspacePaths)}catch{o=void 0}let s=!0,i=!0;return{gitRepos:(await Promise.all(this.workspacePaths.map((async e=>{let r=this.getWorkspaceCache(e);if(void 0===r){if(!t.waitForWorkspaceCache)return s=!1,void this.ensureWorkspaceCacheWarm(n.ctx,e);if(await this.ensureWorkspaceCacheWarm(n.ctx,e),r=this.getWorkspaceCache(e),void 0===r)return void(s=!1)}const a=o?.[e];if(void 0!==a)return void 0!==r.repoPath&&void 0===a.gitStatus&&(i=!1),new Dr.DS({path:r.repoPath,status:a.gitStatus,branchName:a.gitBranchName,remoteUrl:r.remoteUrl,isOriginBacked:Ja(r.remoteUrl)});if(void 0===r.repoPath)return;const c=r.repoPath,{status:l,branchName:u}=void 0===this.freshSectionWaitMs?await X$(n.ctx,t.gitExecutor,c,q$):await this.gitInfoSection(c).read((()=>X$((0,y.q6)(),t.gitExecutor,c,q$)),this.freshSectionWaitMs);return void 0===l&&(i=!1),new Dr.DS({path:r.repoPath,status:l,branchName:u,remoteUrl:r.remoteUrl,isOriginBacked:Ja(r.remoteUrl)})})))).filter((e=>void 0!==e)),gitRepoInfoComplete:s,gitStatusInfoComplete:s&&i}}catch(e){r.error=e,r.hasError=!0}finally{H$(r)}}shareBoundedSectionLoad(e,t,r){if(void 0===this.sectionLoadTimeoutMs)return r();const n=e();if(void 0!==n)return n;const o=r();t(o);const s=()=>{e()===o&&t(void 0)};return o.then(s,s),o}async computeCachedRequestContext(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=W$(n,(0,$.VI)(e.withName("LocalRequestContextExecutor.computeCachedRequestContext")),!1),s=this.projectDir,i=async()=>{const e={stack:[],error:void 0,hasError:!1};try{const t=W$(e,(0,$.VI)(o.ctx.withName("LocalRequestContextExecutor.computeCachedRequestContext.getGlobalData")),!1);if(this.globalCacheTraceId&&t.span.setAttribute("cacheTraceId",this.globalCacheTraceId),!this.reduceContextHotPath&&void 0===this.freshSectionWaitMs){if(void 0===this.globalCache){const e=this.computeGlobalCache(o.ctx);this.globalCache=e,e.catch((()=>{this.globalCache===e&&(this.globalCache=void 0)})),void 0!==this.sectionLoadTimeoutMs&&e.then((t=>{this.globalCache===e&&(this.lastGoodGlobalCache=t)}),(()=>{}))}return this.globalCache}return void 0!==this.lastGoodGlobalCache?this.lastGoodGlobalCache:this.globalCache??this.rebuildGlobalCache()}catch(t){e.error=t,e.hasError=!0}finally{H$(e)}},a=performance.now(),c={},l=(e,t)=>{const r=performance.now();return t.finally((()=>{c[e]=Math.round(performance.now()-r)}))},u=e=>V$(e,this.sectionLoadTimeoutMs),d=(e,t,r)=>this.shareBoundedSectionLoad(e,t,r),h=this.freshSectionWaitMs,p=(e,t)=>void 0===h?t():e.read(t,h),f=void 0===h?o.ctx:(0,y.q6)(),[m,g,w,{gitRepos:v,gitRepoInfoComplete:b,gitStatusInfoComplete:S},k,_,C,E,x,P]=await Promise.all([l("globalCache",u(i())),l("mcpState",this.mcpFieldsFromCaller?Promise.resolve({servers:[]}):u(p(this.reusedMcpState,(()=>d((()=>this.inFlightMcpState),(e=>{this.inFlightMcpState=e}),(()=>this.mcpStateAccessor.getState(f))))))),l("env",Q$(o.ctx,this.workspacePaths,{projectDir:s,notesSessionId:t.notesSessionId,agentNotesEnabled:this.agentNotesEnabled,reportProcessWorkingDirectory:this.reportProcessWorkingDirectory,getSmartModeClassifierAutoModeEnabled:this.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:this.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:this.getMockPromptTime,isWorkingDirHomeDir:this.isWorkingDirHomeDir,getSandboxEnabled:this.getSandboxEnabled,getSandboxSupported:this.getSandboxSupported,getNetworkAllowlistInfo:this.getNetworkAllowlistInfo,userTerminalHint:this.userTerminalHint,artifactsFolder:this.getArtifactsFolder?.(o.ctx),secretRedactionEnabled:this.secretRedactionEnabled,getComputerUseSupported:this.getComputerUseSupported,getComputerUseDesktop:this.getComputerUseDesktop})),l("git",this.collectWorkspaceCaches(o.ctx,{waitForWorkspaceCache:!0===t.waitForWorkspaceCache,gitExecutor:r})),l("conversationNotes",this.agentNotesEnabled&&s&&t.notesSessionId?U$(s,t.notesSessionId):Promise.resolve(void 0)),l("sharedNotes",this.agentNotesEnabled&&s?B$(s):Promise.resolve(void 0)),l("mcpFileSystemOptions",this.getMcpFileSystemOptions?this.getMcpFileSystemOptions(o.ctx,{timeoutMs:3e3}):Promise.resolve(void 0)),l("attribution",this.isAttributionDisabledByAdmin?this.isAttributionDisabledByAdmin().catch((()=>!0)):Promise.resolve(!1)),l("agentSkills",u(p(this.reusedAgentSkills,(()=>d((()=>this.inFlightAgentSkills),(e=>{this.inFlightAgentSkills=e}),(()=>this.getAgentSkills?this.getAgentSkills(f):Promise.resolve([]))))))),l("adminCommandDenylist",u(p(this.reusedAdminCommandDenylist,(()=>d((()=>this.inFlightAdminCommandDenylist),(e=>{this.inFlightAdminCommandDenylist=e}),(()=>this.getAdminCommandDenylist?this.getAdminCommandDenylist():Promise.resolve(void 0)))))))]),R=m===G$,I=g===G$,T=x===G$,A=P===G$,M=R?this.lastGoodGlobalCache??{rules:[...this.additionalRules],cloudRule:null,codebaseReference:void 0,customSubagents:[]}:m,D=I?{servers:[]}:g,O=T?[]:x,F=A?void 0:P;(R||I||T||A)&&z$.warn(o.ctx,"computeCachedRequestContext: section load timed out",{timeoutMs:this.sectionLoadTimeoutMs,rulesAndSubagents:R,mcpState:I,agentSkills:T,adminCommandDenylist:A});const N=performance.now()-a;for(const[e,t]of Object.entries(c))o.span.setAttribute(`requestContext.timing.${e}Ms`,t);o.span.setAttribute("requestContext.timing.totalMs",Math.round(N)),N>1e3&&z$.warn(o.ctx,"computeCachedRequestContext: slow parallel data collection",{durationMs:Math.round(N),...c});const L=this.mcpMetaToolEnabled?tM(D,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,slimDescriptors:this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}):void 0,j=this.attributionConfigProvider?.get(),U=!E&&(j?.attribution?.attributeCommitsToAgent??!0),B=!E&&(j?.attribution?.attributePRsToAgent??!0),W=new Dr.bb({rules:M.rules,env:w,gitRepos:v,gitRepoInfoComplete:b,repositoryInfo:M.codebaseReference?[{relativeWorkspacePath:M.codebaseReference.relativeWorkspacePath,repoName:M.codebaseReference.repoName,repoOwner:M.codebaseReference.repoOwner,isTracked:M.codebaseReference.isTracked,isLocal:M.codebaseReference.isLocal,orthogonalTransformSeed:M.codebaseReference.orthogonalTransformSeed,pathEncryptionKey:M.codebaseReference.pathEncryptionKey}]:[],...eM(D,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}),conversationNotesListing:k,sharedNotesListing:_,customSubagents:M.customSubagents,mcpFileSystemOptions:C,mcpMetaToolOptions:L,supportsMcpAuth:!0,commitAttributionMessage:U?"enabled":void 0,prAttributionMessage:B?"enabled":void 0,agentSkills:O,adminCommandDenylist:F?.rules??[]});return null!==M.cloudRule&&void 0!==M.cloudRule&&(W.cloudRule=M.cloudRule),this.reportSectionCompleteness&&(W.rulesInfoComplete=!R,W.customSubagentsInfoComplete=!R,W.agentSkillsInfoComplete=!T,W.mcpInfoComplete=!I,W.mcpFileSystemInfoComplete=this.mcpMetaToolEnabled||void 0!==C,W.envInfoComplete=!0,W.gitStatusInfoComplete=S),W}catch(e){n.error=e,n.hasError=!0}finally{H$(n)}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{this.onRequestContext?.();const n=W$(r,(0,$.VI)(e.withName("LocalRequestContextExecutor.execute")),!1);n.span.setAttribute("enableCaching",void 0!==this.fileWatcher),n.span.setAttribute("hasGlobalCache",!!this.globalCache);try{const e=this.gitExecutor.forRequest?.()??this.gitExecutor,r=await this.computeCachedRequestContext(n.ctx,t,e);return new Dr._G({result:{case:"success",value:new Dr.yW({requestContext:r})}})}catch(e){return e instanceof Error||"string"==typeof e?n.span.recordException(e):n.span.recordException(kc(e)),new Dr._G({result:{case:"error",value:new Dr.nf({error:e instanceof Error?e.message:String(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{H$(r)}}}function cM(e){return 0!==e.timeout?e.timeout:e.isBackground||e.timeoutBehavior===he._d.BACKGROUND||void 0!==e.hardTimeout&&e.hardTimeout>0?0:3e4}var lM=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class uM{constructor(e,t,r,n){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r}buildResultFromExit(e){return 0===(e.exitCode??-1)?new he.W4({result:{case:"success",value:new he.QR({...e,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:us(e.sandboxPolicy)}):new he.W4({result:{case:"failure",value:new he.xC({...e,aborted:void 0!==e.abortReason,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:us(e.sandboxPolicy)})}async executeWithPolicy(e,t,r,n,o){const s=Date.now(),i=new AbortController,a=e.signal?AbortSignal.any([e.signal,i.signal]):i.signal,c=setTimeout((()=>{i.abort()}),n);try{let n,l,u,d="",h="",p=null;const f=o?{perUser:o}:void 0;for await(const o of this.coreExecutor.execute(e,{command:t.command,workingDirectory:r,signal:a,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:f,fileOutputThresholdBytes:t.fileOutputThresholdBytes,pipeStdin:!1}))"stdout"===o.type?d+=o.data:"stderr"===o.type?h+=o.data:"exit"===o.type&&(p=null!=o.code?0|o.code:null,l=o.outputLocation,n=o.aborted?a.aborted?i.signal.aborted&&a.reason===i.signal.reason?he.Lv.TIMEOUT:he.Lv.USER_ABORT:he.Lv.UNSPECIFIED:void 0,u=$y(o.localExecutionTimeMs));clearTimeout(c);const m=Date.now()-s,g={command:t.command,workingDirectory:r,exitCode:void 0!==n?-1:p??-1,signal:void 0!==n?"SIGTERM":"",abortReason:n,stdout:d,stderr:h,executionTime:m,localExecutionTimeMs:u,sandboxPolicy:o,outputLocation:l};return this.buildResultFromExit(g)}catch(s){return clearTimeout(c),i.signal.aborted&&!e.signal.aborted?new he.W4({result:{case:"timeout",value:new he.eG({command:t.command,workingDirectory:r,timeoutMs:n})},sandboxPolicy:us(o)}):e.signal.aborted?new he.W4({result:{case:"rejected",value:new he.pZ({command:t.command,workingDirectory:r,reason:"Command aborted"})},sandboxPolicy:us(o)}):new he.W4({result:{case:"spawnError",value:new he.mJ({command:t.command,workingDirectory:r,error:s instanceof Error?s.message:"Unknown error"})},sandboxPolicy:us(o)})}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,$.VI)(e.withName("LocalShellExecutor.execute")),!1).ctx;(0,$.HF)(n,"LocalShellExecutor.execute");const o=t.command,s=t.requestedSandboxPolicy?ls(t.requestedSandboxPolicy):void 0,i=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),a=cM(t),c=(0,Yo.o1)(i);if(!t.parsingResult)return new he.W4({result:{case:"spawnError",value:new he.mJ({command:o,workingDirectory:c,error:"Parsing result is required"})}});let l;if(Mo(t)){const e=await this.permissionsService.shouldEnforceShellInvariantBlocks(n,{workingDirectory:c,skipUnsafeWorkingDirectoryBlock:!0,command:o,parsingResult:t.parsingResult,toolCallId:t.toolCallId,resolveSkippedApprovalPolicy:!0},s);if("block"===e.kind)return new he.W4({result:ed(o,c,e.reason)});l=e.policy??s}else{const e=await this.permissionsService.shouldBlockShellCommand(n,o,{workingDirectory:c,timeout:a,parsingResult:t.parsingResult,toolCallId:t.toolCallId,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Ao(t)},s);if("block"===e.kind)return new he.W4({result:ed(o,c,e.reason)});l=e.policy}return l=await Tc(l,{command:o,workingDirectory:c,parsingResult:t.parsingResult,permissionsService:this.permissionsService,ignoreService:this.ignoreService}),this.executeWithPolicy(n,t,i,a,l)}catch(e){r.error=e,r.hasError=!0}finally{lM(r)}}}var dM=r("../proto/dist/generated/agent/v1/shell_allowlist_precheck_exec_pb.js");class hM{constructor(e){this.permissionsService=e}async execute(e,t){const r=t.parsingResult??new he.HO,n=await this.permissionsService.isShellCommandFullyAllowlisted(e,t.command,{workingDirectory:t.workingDirectory,parsingResult:r,classifierResult:t.classifierResult,toolCallId:t.toolCallId});return new dM.e({allowlisted:n})}}class pM{constructor(e){this.shellStreamExecutor=e}async execute(e,t,r){return""===t.toolCallId.trim()?new he.jK({status:he.iA.NOT_FOUND}):this.shellStreamExecutor.forceBackgroundByToolCallId(e,t.toolCallId)}}var fM=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const mM=(0,l.h)("local-exec:shell-stream");class gM{constructor(e,t){this.iterator=e,this.timeoutMs=t,this.pendingPromise=null,this.stopPromise=new Promise((e=>{this.stopResolve=e}))}stop(e){return void 0===this.stopReason&&(this.stopReason=e,this.stopResolve?.(),!0)}get timedOut(){return"background"===this.stopReason?.kind&&this.stopReason.reason===he.Jg.TIMEOUT}get backgroundRequested(){return"background"===this.stopReason?.kind}get backgroundReasonValue(){return"background"===this.stopReason?.kind?this.stopReason.reason:void 0}get stopReasonValue(){return this.stopReason}async*iterate(){this.timer=setTimeout((()=>{this.stop({kind:"background",reason:he.Jg.TIMEOUT})}),this.timeoutMs);try{for(;;){if(void 0!==this.stopReason)return;this.pendingPromise=this.iterator.next();const e=await Promise.race([this.pendingPromise.then((e=>({kind:"result",result:e}))),this.stopPromise.then((()=>({kind:"stopped"})))]);if("stopped"===e.kind)return;if(this.pendingPromise=null,e.result.done)return;yield e.result.value}}finally{clearTimeout(this.timer)}}requestBackground(){return this.stop({kind:"background",reason:he.Jg.USER_REQUEST})}abort(){this.stop({kind:"abort"})}getHandoffIterator(){if(this.pendingPromise){const e=this.pendingPromise;this.pendingPromise=null;let t=!1;return{next:async()=>t?this.iterator.next():(t=!0,e)}}return this.iterator}}function wM(){let e=()=>{};return{promise:new Promise((t=>{e=t})),resolve:e}}class yM{constructor(e,t,r,n){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r,this.backgroundShellManager=n,this.activeForegroundExecutions=new Map,this.pendingShells=new Map}hasForegroundWork(){return this.activeForegroundExecutions.size>0||this.pendingShells.size>0}async forceBackgroundByToolCallId(e,t){const r=this.pendingShells.get(t),n=void 0===r||r.awaitingApproval?this.activeForegroundExecutions.get(t):await async function(e,t){const[r,n]=e.withCancel();try{return await Promise.race([t.registered.promise,(0,y.uk)(r).then((()=>{}))])}finally{n()}}(e,r),o=n?.requestBackground();return o?new he.jK({status:he.iA.ACCEPTED,shellResult:o}):new he.jK({status:he.iA.NOT_FOUND})}pendingFrom(e){return{execute:(t,r,n)=>this.whilePending(r,(()=>e.get(ee).execute(t,r,n)))}}execute(e,t){return this.whilePending(t,(r=>this.run(e,t,r)))}async*whilePending(e,t){let r=this.pendingShells.get(e.toolCallId);void 0===r&&(r={awaitingApproval:!1,registered:wM()},""!==e.toolCallId&&e.timeoutBehavior===he._d.BACKGROUND&&this.pendingShells.set(e.toolCallId,r));try{yield*t(r)}finally{this.settle(e.toolCallId,r,void 0)}}settle(e,t,r){this.pendingShells.get(e)===t&&this.pendingShells.delete(e),t.registered.resolve(r)}async*run(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{e.signal?.throwIfAborted(),function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(n,(0,$.VI)(e.withName("LocalShellStreamExecutor.execute")),!1);const o=t.command;let s=t.requestedSandboxPolicy?ls(t.requestedSandboxPolicy):void 0;const i=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),a=cM(t),c=(0,Yo.o1)(i),l=Date.now(),u=performance.now(),d=new he.HO(Wo(o).structured),h=ks({command:o,parsingResult:d,blockedCommands:t.adminCommandDenylist});if(void 0!==h)return void(yield new he.FI({event:{case:"rejected",value:new he.pZ({command:o,workingDirectory:c,reason:h})}}));const p=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:c,skipUnsafeWorkingDirectoryBlock:!0,command:o,parsingResult:d,toolCallId:t.toolCallId,resolveSkippedApprovalPolicy:Mo(t)},s);if("block"===p.kind)return"permissionsConfig"===p.reason.type?void(yield new he.FI({event:{case:"permissionDenied",value:new he.jn({command:o,workingDirectory:c,error:"Command blocked by permissions configuration",isReadonly:p.reason.isReadonly??!1})}})):void(yield new he.FI({event:{case:"rejected",value:new he.pZ({command:o,workingDirectory:c,reason:Yu(p.reason)})}}));if(mM.info(e,"Shell stream: approval gate reached",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,hasSmartModeApproval:void 0!==t.smartModeApproval,hasSmartModeApprovalReason:void 0!==t.smartModeApproval?.reason,hasSmartModeApprovalRequestId:void 0!==t.smartModeApproval?.requestId,requestedPolicyType:s?.type??"undefined",parserCommandCount:d.executableCommands.length,classifierCommandCount:t.classifierResult?.commands.length??0,commandLength:o.length}),Mo(t)){const r=p.policy??s;mM.info(e,"Shell stream: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:s?.type??"undefined",effectivePolicyType:r?.type??"undefined"}),s=r}else{r.awaitingApproval=!0;const n=await this.permissionsService.shouldBlockShellCommand(e,o,{workingDirectory:c,timeout:a,parsingResult:d,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Ao(t),onApprovalRequested:()=>{r.registered.resolve(void 0),r.registered=wM()}},s);if(r.awaitingApproval=!1,"block"===n.kind){if(mM.info(e,"Shell stream: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:n.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),"permissionsConfig"===n.reason.type)return void(yield new he.FI({event:{case:"permissionDenied",value:new he.jn({command:o,workingDirectory:c,error:"Command blocked by permissions configuration",isReadonly:n.reason.isReadonly??!1})}}));const r=Yu(n.reason);return void(yield new he.FI({event:{case:"rejected",value:new he.pZ({command:o,workingDirectory:c,reason:r})}}))}s=n.policy,mM.info(e,"Shell stream: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:s.type})}s=await Tc(s,{command:o,workingDirectory:c,parsingResult:d,permissionsService:this.permissionsService,ignoreService:this.ignoreService}),yield new he.FI({event:{case:"start",value:new he.tD({sandboxPolicy:us(s)})}});const f=t.timeoutBehavior===he._d.BACKGROUND,m=f&&!t.closeStdin&&void 0===t.smartModeApproval,g=new AbortController,w=f?g.signal:e.signal?AbortSignal.any([e.signal,g.signal]):g.signal,y=!0,v=s?{perUser:s}:void 0,b=this.coreExecutor.execute(e,{command:o,workingDirectory:i,signal:w,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:v,fileOutputThresholdBytes:t.fileOutputThresholdBytes,pipeStdin:m,showElapsedTime:y});let S;f||(S=setTimeout((()=>g.abort()),a));const k=f?new gM(b[Symbol.asyncIterator](),a):null;let _,C,E,x="",P=!1,R=!1;const I=t.toolCallId&&k?{requestBackground:()=>{if(k.requestBackground())return E=E??this.backgroundShellManager.generateShellId(),new he.W4({result:{case:"success",value:new he.QR({shellId:E,pid:C,command:o,workingDirectory:c,msToWait:$y(performance.now()-u),backgroundReason:he.Jg.USER_REQUEST,interleavedOutput:x})}})}}:void 0;t.toolCallId&&I&&this.activeForegroundExecutions.set(t.toolCallId,I),this.settle(t.toolCallId,r,I);const T=()=>{t.toolCallId&&this.activeForegroundExecutions.get(t.toolCallId)===I&&this.activeForegroundExecutions.delete(t.toolCallId)},A=()=>{k&&!k.backgroundRequested&&(g.abort(),k.abort())};let M;k&&e.signal&&(e.signal.aborted?A():e.signal.addEventListener("abort",A,{once:!0}));const D=t.hardTimeout;void 0!==D&&D>0&&(M=setTimeout((()=>{void 0!==E?this.backgroundShellManager.abort(E)||g.abort():(P=!0,g.abort(),k?.abort())}),D));const O=k?.iterate()??b;try{for await(const r of O)if("stdout"===r.type)x+=r.data,yield new he.FI({event:{case:"stdout",value:new he.o0({data:r.data})}});else if("stderr"===r.type)x+=r.data,yield new he.FI({event:{case:"stderr",value:new he.Db({data:r.data})}});else if("stdin_ready"===r.type)_=r.stdin,C=r.pid;else if("exit"===r.type){let n;R=!0,r.aborted&&(n=e.signal?.aborted?he.Lv.USER_ABORT:k?.timedOut||g.signal.aborted?he.Lv.TIMEOUT:he.Lv.USER_ABORT),yield new he.FI({event:{case:"exit",value:new he.vb({code:(r.code??-1)>>>0,cwd:await this.coreExecutor.getCwd(t.conversationId),outputLocation:r.outputLocation,aborted:r.aborted,abortReason:n,localExecutionTimeMs:$y(r.localExecutionTimeMs)})}})}}catch(r){if(!(r instanceof Oo.SandboxUnsupportedError))throw r;const n=s?.type??"unknown";return mM.debug(e,"Shell stream: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:n,reason:r.reason}),void(yield new he.FI({event:{case:"sandboxUnsupported",value:new he.rI({command:o,workingDirectory:c,sandboxPolicyType:n,reason:r.reason??r.message,isReadonly:"workspace_readonly"===n})}}))}finally{clearTimeout(S),k?.backgroundRequested||clearTimeout(M),T(),!k||k.backgroundRequested||R||g.abort(),e.signal?.removeEventListener("abort",A)}if(k?.backgroundRequested&&!P){const r=E??this.backgroundShellManager.generateShellId();E=r;const n=k.backgroundReasonValue===he.Jg.USER_REQUEST?he.Jg.USER_REQUEST:he.Jg.TIMEOUT,s=n===he.Jg.USER_REQUEST?Math.round(performance.now()-u):a;await this.backgroundShellManager.adopt({ctx:e,shellId:r,command:o,workingDirectory:c,toolCallId:t.toolCallId,sandboxPolicy:v,initialOutput:x,stdin:_,pid:C,abortController:g,eventIterator:k.getHandoffIterator(),startTime:l,monotonicStartMs:u,showElapsedTime:y,description:t.description,outputNotification:t.outputNotification,onCleanup:()=>clearTimeout(M)}),yield new he.FI({event:{case:"backgrounded",value:new he.Y9({shellId:r,command:o,workingDirectory:c,pid:C,msToWait:y?s:void 0,reason:n})}})}else e.signal?.aborted&&void 0!==k?.stopReasonValue?(clearTimeout(M),yield new he.FI({event:{case:"exit",value:new he.vb({code:4294967295,cwd:await this.coreExecutor.getCwd(t.conversationId),aborted:!0,abortReason:he.Lv.USER_ABORT})}})):clearTimeout(M)}catch(e){n.error=e,n.hasError=!0}finally{fM(n)}}}const vM={kind:"absent"};class bM{constructor(e){this.cells=new Map,this.takenCells=new WeakMap,this.collectedCells=new FinalizationRegistry((e=>{void 0===this.cells.get(e)?.deref()&&this.cells.delete(e)})),this.claims=new Map,this.nextGeneration=0,this.entries=new Eo.q({max:1e3,ttl:6e4,ttlResolution:0,perf:e})}begin(e){this.entries.purgeStale();const t=++this.nextGeneration;return this.claims.set(PM(e),t),t}record(e,t,r){if(!this.claim(e,r))return;const n=PM(e);this.entries.set(n,{recorded:t,generation:r}),this.commitGeneration(n,r)}forget(e,t){if(!this.claim(e,t))return;const r=PM(e);this.entries.delete(r),this.commitGeneration(r,t)}end(e,t){this.claim(e,t)}take(e){const t=PM(e),r=this.entries.get(t);if(void 0===r)return;const n=this.entries.getRemainingTTL(t);this.entries.delete(t);let o=this.cells.get(t)?.deref();void 0===o&&(o={committed:r.generation},this.cells.set(t,new WeakRef(o)),this.collectedCells.register(o,t));const s={read:e,recorded:r.recorded,remainingTtlMs:n,generation:r.generation};return this.takenCells.set(s,o),s}restore(e){const t=this.takenCells.get(e);if(void 0===t||t.committed!==e.generation)return;const r=PM(e.read);this.entries.has(r)||!Number.isFinite(e.remainingTtlMs)||e.remainingTtlMs<=0||this.entries.set(r,{recorded:e.recorded,generation:e.generation},{ttl:e.remainingTtlMs})}commitGeneration(e,t){const r=this.cells.get(e)?.deref();void 0!==r&&(r.committed=t)}claim(e,t){const r=PM(e);return this.claims.get(r)===t&&(this.claims.delete(r),!0)}}class SM{constructor(){this.views=new Eo.q({max:1e3})}get(e){return this.views.get(e)}set(e,t){this.views.set(e,t)}forget(e){this.views.delete(e)}recordWrite(e,t){if(t.length>Gs)return void this.views.delete(e);const r=(0,bo.createHash)("sha256").update(t).digest("hex");this.views.set(e,{kind:"fingerprint",byteLength:t.length,sha256:r})}recordDelete(e){this.views.set(e,vM)}}async function kM(e,t){if(void 0===e)return!1;try{if("absent"===e.kind)return await xM(t);const r=await EM(t);return void 0===r||r.byteLength!==e.byteLength||r.sha256!==e.sha256}catch{return!1}}async function _M(e,t){if("fingerprint"!==e?.kind)return!1;try{return!await xM(t)}catch{return!1}}class CM{constructor(e,t,r,n,o){this.inner=e,this.reads=t,this.permissionsService=r,this.workspacePath=n,this.views=o}async execute(e,t,r){const n=!0===r?.recordAgentView?(0,Yo.o1)(t.path,this.workspacePath):void 0,o=function(e,t){if(""!==e.toolCallId&&void 0===e.offset&&void 0===e.limit)return{toolCallId:e.toolCallId,resolvedPath:(0,Yo.o1)(e.path,t)}}(t,this.workspacePath);if(void 0===o){const o=await this.inner.execute(e,t,r);return this.forgetViewReadPast(n,o),o}const s=this.reads.begin(o);try{let i,a;try{i=await Zk(this.permissionsService,o.resolvedPath)}catch{return await this.readAndForget(e,t,r,o,s,n)}if(!1!==i&&"needsApproval"!==i.type)return await this.readAndForget(e,t,r,o,s,n);if(!1!==i){const i=await this.inner.execute(e,t,r),a=await async function(e,t){if("success"===e.result.case&&"content"===e.result.value.output.case)try{return await EM(t)}catch{return}}(i,o.resolvedPath);return this.commit(o,s,i,a,n),i}try{a=await EM(o.resolvedPath)}catch{return await this.readAndForget(e,t,r,o,s,n)}const c=await this.inner.execute(e,t,r);return this.commit(o,s,c,a,n),c}finally{this.reads.end(o,s)}}commit(e,t,r,n,o){let s;if("fileNotFound"===r.result.case?s=vM:void 0!==n&&"success"===r.result.case&&"content"===r.result.value.output.case&&(s={kind:"fingerprint",...n}),void 0===s)return this.reads.forget(e,t),void this.forgetViewReadPast(o,r);this.reads.record(e,s,t),void 0!==o&&this.views?.set(o,s)}async readAndForget(e,t,r,n,o,s){const i=await this.inner.execute(e,t,r);return this.reads.forget(n,o),this.forgetViewReadPast(s,i),i}forgetViewReadPast(e,t){void 0===e||"success"!==t.result.case&&"fileNotFound"!==t.result.case||this.views?.forget(e)}}async function EM(e){try{const t=await(0,Co.stat)(e);if(!t.isFile()||t.size>Gs)return}catch(e){return RM(e)}let t;try{t=await(0,Co.open)(e,function(){const e=xo.constants;return e.O_RDONLY|(e.O_NONBLOCK??0)}());const r=await t.stat();if(!r.isFile()||r.size>Gs)return;const n=(0,bo.createHash)("sha256");let o=0;const s=Buffer.alloc(65536);for(;o<=Gs;){const{bytesRead:e}=await t.read(s,0,s.length,o);if(0===e)break;o+=e,n.update(s.subarray(0,e))}if(o>Gs)return;return{byteLength:o,sha256:n.digest("hex")}}catch(e){return RM(e)}finally{await(t?.close())}}async function xM(e){try{return await(0,Co.stat)(e),!0}catch(e){if(IM(e))return!1;throw e}}function PM({toolCallId:e,resolvedPath:t}){return`${e}\0${t}`}function RM(e){if(!IM(e))throw e}function IM(e){const t=Sc(e);return"ENOENT"===t||"ENOTDIR"===t}var TM=r("../proto/dist/generated/agent/v1/web_fetch_allowlist_precheck_exec_pb.js");class AM{constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isWebFetchFullyAllowlisted(e,{url:t.url});return new TM.M({allowlisted:r})}}var $M=r("node:constants");const MM=[".md",".markdown",".mdown",".mkd",".mkdn",".mdx"];function DM(e){const t=e.trim().toLowerCase();return MM.some((e=>t.endsWith(e)))}function OM(e,t){const r=e.trim().toLowerCase().split("win32"===t?/[\\/]/:"/");if(r.some((e=>"."===e||".."===e)))return!1;const[n,o,s,i,a]=r.slice(-5);return r.length>=5&&".cursor"===n&&"projects"===o&&void 0!==s&&""!==s&&"canvases"===i&&void 0!==a&&a.length>11&&a.endsWith(".canvas.tsx")}const FM="win32"===process.platform;process.platform;const NM="\\"===s.sep?"win32":"posix",LM={allowed:!1};class jM extends Error{constructor(e,t){super(t),this.name="SymlinkRefusedError",this.path=e}}function UM(e,{nonBlocking:t}){const r=xo.constants;let n=e;return"number"==typeof r.O_NOFOLLOW&&(n|=r.O_NOFOLLOW),t&&"number"==typeof r.O_NONBLOCK&&(n|=r.O_NONBLOCK),"number"==typeof r.O_CLOEXEC&&(n|=r.O_CLOEXEC),n}const BM=[20,40,80],WM=new Set(["UNKNOWN","EBUSY"]);async function HM(e,t){try{const[r,n]=await Promise.all([t.stat({bigint:!0}),(0,Co.lstat)(e,{bigint:!0})]);r.dev===n.dev&&r.ino===n.ino&&await(0,Co.unlink)(e)}catch{}}async function qM(e,t,r,{removeOnRefusal:n=!1}={}){let o;try{o=await async function(e,t){try{return await(0,Co.open)(e,UM(t,{nonBlocking:!0}),438)}catch(r){const n=Sc(r);if(("EAGAIN"===n||"EWOULDBLOCK"===n)&&await async function(e){try{return(await(0,Co.lstat)(e)).isFile()}catch{return!1}}(e))return await(0,Co.open)(e,UM(t,{nonBlocking:!1}),438);throw r}}(e,t)}catch(t){if(function(e){const t=Sc(e);return"ELOOP"===t||"EMLINK"===t||"EPERM"===t&&"number"==typeof xo.constants.O_NOFOLLOW}(t))throw new jM(e,`Refusing to ${r} through a symlink at ${e}`);throw t}try{let t;try{t=(0,xo.realpathSync)(e)}catch{throw new jM(e,`Cannot verify canonical path before ${r}: ${e}`)}if(t!==e)throw new jM(e,`Refusing ${r}: ${e} now resolves through a symlinked parent to ${t}`);const n=await o.stat();if(!n.isFile())throw new jM(e,`Refusing to ${r} non-regular file at ${e}`);return{fd:o,stats:n}}catch(t){throw n&&await HM(e,o),await o.close(),t}}var zM=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const GM=(0,l.h)("LocalWriteExecutor"),VM=(0,u.Pu)("local_exec.write.encoding_check",{description:"Text writes that landed, per encoding detector (mojibake, U+FFFD): whether the written text holds the pattern and holds more of it than the file did, and for a detection what the file held, its extension family, encoding and the machine's Windows code page",labelNames:["detector","outcome","file","ext","encoding","code_page","run_count","delta","before_count","pattern"]}),KM=async(e,t,r,n)=>{const o=setTimeout((()=>{GM.warn(e,`[watchdog, LocalWriteExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function JM(e){return new Error(`Could not create ${e}: directory creation exceeded the path depth and was stopped.`)}async function ZM(e){try{return(await(0,Co.stat)(e)).isDirectory()?"directory":"present"}catch(e){if("ENOENT"===Sc(e))return"missing";throw e}}async function XM(e,t){const r=[];let n=e;for(let o=0;o<=t;o+=1){const t=await ZM(n);if("directory"===t)return r.reverse(),r;if("present"===t)return await(0,Co.mkdir)(n,{recursive:!1}),r.reverse(),r;r.push(n);const o=(0,s.dirname)(n);if(o===n){const t=new Error(`ENOENT: no such file or directory, mkdir '${e}'`);throw t.code="ENOENT",t.syscall="mkdir",t.path=e,t}n=o}throw JM(e)}class QM{constructor(e,t,r,{workspacePaths:n,workspacePath:o,worktreeMainPath:s,projectDir:i,onWriteForAiTracking:a,writeFileMutationGuard:c,toolCallReads:l,agentFileViews:u}){this.fileChangeTracker=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.workspacePaths=n,this.workspacePath=o,this.worktreeMainPath=s,this.projectDir=i,this.onWriteForAiTracking=a,this.writeFileMutationGuard=c,this.toolCallReads=l,this.agentFileViews=u}async execute(e,t,r){if(function(e){if(!e.startsWith("file://"))return!1;try{return(0,Ed.fileURLToPath)(e),!1}catch{return!0}}(t.path))return new MI.v3({result:{case:"error",value:new MI.QM({path:t.path,error:`${t.path} is not a valid file URL. Use an absolute path instead.`})}});const n=(0,Yo.o1)(t.path,this.workspacePath),o=this.toolCallReads,s=void 0!==o&&""!==t.toolCallId?o.take({toolCallId:t.toolCallId,resolvedPath:n}):void 0,i=!0===r?.refuseUnreadChanges?this.agentFileViews?.get(n):void 0,a={writeStarted:!1},c=()=>{void 0===s||a.writeStarted||o?.restore(s)};try{const r=await this.executeWithRecord(e,t,n,s?.recorded,i,a);return tD(r)&&c(),r}catch(e){throw c(),e}}async executeWithRecord(e,t,r,n,o,i){const a={stack:[],error:void 0,hasError:!1};try{const c=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(a,(0,$.VI)(e.withName("LocalWriteExecutor.execute")),!1).ctx,l=(t.path,t.fileText),u=t.fileBytes.length>0?t.fileBytes:void 0,d=["assets","agent-tools","swarm-agents"],h=yS(r,d)||void 0!==this.projectDir&&!this.workspacePaths.some((e=>{return t=e,n=r,FM&&(t=t.toLowerCase(),n=n.toLowerCase()),t===n||(t.charAt(t.length-1)!==s.sep&&(t+=s.sep),n.startsWith(t));var t,n}))&&vS(this.projectDir,r,d);if((0,Yo.fl)({targetPath:r,workspacePaths:this.workspacePaths,mainWorktreePath:this.worktreeMainPath}))return new MI.v3({result:{case:"error",value:new MI.QM({path:r,error:Yo.PS})}});let p,f,m,g,w=!1;try{const e=await(0,Co.stat)(r);if(g=511&e.mode,e.size<=ns){const e=await KM(c,"readText before write",3e3,(()=>Ui(r,t.encodingHint)));p=e.text,f=e.encoding,m=Uw(e)}else w=!0}catch(e){w="ENOENT"!==Sc(e)}const y=await DS(r),v=y.resolvedPath;if(t.confineToWorkspace){let e=(await Promise.all(this.workspacePaths.map((e=>(0,Co.realpath)(e).catch((()=>{})))))).filter((e=>void 0!==e));if(0===e.length&&void 0!==this.projectDir){const t=await(0,Co.realpath)(this.projectDir).catch((()=>{}));void 0!==t&&(e=[t])}if(!e.some((e=>(0,Yo.BJ)(v,e))))return new MI.v3({result:{case:"error",value:new MI.QM({path:r,error:"downloadPath must stay within the workspace"})}})}const b=async()=>{return await kM(n,v)?BT(r):(t=n,void 0!==(e=o)&&void 0!==t&&e.kind===t.kind&&("absent"===e.kind||"fingerprint"===t.kind&&e.byteLength===t.byteLength&&e.sha256===t.sha256)||!await kM(o,v)?void 0:WT(r));var e,t},S=t.planMode?await KM(c,"checkPlanModeWriteTarget",3e3,(()=>async function(e,t){switch(t.resolution.status){case"resolved":case"newFile":return DM(t.resolvedPath)?{allowed:!0}:await async function(e,t){if(!(OM(t.resolvedPath,NM)||OM(e,NM)&&t.resolvedPath===await async function(e){const t=(0,s.dirname)((0,s.dirname)((0,s.dirname)((0,s.dirname)(e)))),r=await DS(t);if(OS(r.resolution))return(0,s.join)(r.resolvedPath,(0,s.relative)(t,e))}(e)))return LM;if("newFile"===t.resolution.status)return{allowed:!0,singleLink:{kind:"create"}};const r=await async function(e){try{const t=await(0,Co.lstat)(e,{bigint:!0});return t.isFile()&&1n===t.nlink?{kind:"existing",dev:t.dev,ino:t.ino}:void 0}catch{return}}(t.resolvedPath);return void 0===r?LM:{allowed:!0,singleLink:r}}(e,t);case"danglingSymlink":{const e=await async function(e){let t=e;for(let e=0;e<40;e++){let e;try{e=await(0,Co.readlink)(t)}catch(e){const r=Sc(e);return"ENOENT"===r||"EINVAL"===r?t:void 0}t=(0,s.resolve)((0,s.dirname)(t),e)}}(t.resolvedPath);return void 0!==e&&DM(e)?{allowed:!0}:LM}case"permissionDenied":case"symlinkLoop":case"unknownError":return LM;default:return t.resolution,LM}}(r,y))):void 0;if(void 0!==S&&!S.allowed)return new MI.v3({result:{case:"rejected",value:new MI.en({path:r,reason:"Cannot edit non markdown files in plan mode"})}});const k=(".cursorignore"===(r.split(s.sep).pop()?.toLowerCase()??"")?{type:"permissionsConfig"}:void 0)??await KM(c,"permissionsService.shouldBlockWrite",3e3,(()=>this.permissionsService.shouldBlockWrite(c,v,l)));if(k){const e=await KM(c,"handleBlockReason",3e3,(()=>Qu(k,{onNeedsApproval:async(e,n)=>{const o="fileEdit"!==n?.type||n.isNewFile,s="fileEdit"===n?.type?n.diffString:l,i="fileEdit"===n?.type?n.blockReason:void 0,a=await b();if(void 0!==a)return YM(r,a);const c=await this.pendingDecisionProvider.requestApproval({type:Lw.Write,details:{path:r,reason:e,isNewFile:o,diffString:s,before:p,after:l,blockReason:i},toolCallId:t.toolCallId});return c.approved?null:new MI.v3({result:{case:"rejected",value:new MI.en({path:r,reason:c.reason||""})}})},onUserRejected:e=>new MI.v3({result:{case:"rejected",value:new MI.en({path:r,reason:e||""})}}),onPermissionDenied:(e,t)=>new MI.v3({result:{case:"permissionDenied",value:new MI.U7({path:r,error:e,isReadonly:t?.isReadonly??!1})}})})));if(null!==e)return e}const _=await KM(c,"anotherSpellingRefusal",3e3,(()=>async function(e){const t=(0,s.basename)(e);let r;try{if(!(await(0,Co.stat)(e)).isFile())return;const n=await(0,Co.readdir)((0,s.dirname)(e));if(n.includes(t))return;const o=t.normalize("NFC");if(n.some((e=>e.normalize("NFC")===o)))return;const i=t.toLowerCase(),a=n.filter((e=>e.toLowerCase()===i)),c=o.toLowerCase();r=a.length>0?a:n.filter((e=>e.normalize("NFC").toLowerCase()===c))}catch{return}const n=1===r.length?r[0]:void 0;return void 0===n?`${t} names an existing file that this folder lists under another name, so writing it would replace that file. Nothing was written. List the folder and write the file by its listed name to change it; for a new file, choose a different name.`:`${t} names the existing file ${n}: this volume does not tell names apart by case, so writing it would replace ${n}. Nothing was written. To change that file, write ${n}; for a new file, choose a name no file in this folder has in any case.`}(r)));if(void 0!==_)return new MI.v3({result:{case:"error",value:new MI.QM({path:r,error:_})}});const C=(0,s.dirname)(v);if(await _M(n,C))return YM(r,BT(r));if(await _M(o,C))return YM(r,WT(r));let E,x,P,R;try{E=await KM(c,"mkdir",3e3,(()=>async function(e){const t=function(e){let t=0,r=e;for(;;){const e=(0,s.dirname)(r);if(e===r)return t;t+=1,r=e}}(e),r=t+4;let n=0,o=0,i=await XM(e,t),a=0;for(;ar)throw JM(e);try{await(0,Co.mkdir)(c,{recursive:!1})}catch(r){const n=Sc(r);if("EEXIST"===n){if("directory"!==await ZM(c))throw r;a+=1;continue}if("ENOENT"===n){const n=(0,s.dirname)(c);if(n===c||"missing"!==await ZM(n))throw r;i=await XM(e,t),a=0,o=0;continue}throw r}o+=1,a+=1}return o}(C)))}catch(e){const t=Sc(e);return"EACCES"===t||"EPERM"===t?new MI.v3({result:{case:"permissionDenied",value:new MI.U7({path:r,directory:C,operation:"create_directory",error:"Permission denied"})}}):new MI.v3({result:{case:"error",value:new MI.QM({path:r,error:kc(e)})}})}if(void 0!==u)x=u,P=0;else{const e=await KM(c,"getBufferForWrite",3e3,(()=>Wi(r,l,this.workspacePath,t.encodingHint)));x=e.buffer,P=e.lines,R=e.format.encoding}const I=()=>KM(c,"writeFile",3e3,(async()=>{const e=await b();if(void 0!==e)throw new Error(e);let t;c.signal.throwIfAborted(),i.writeStarted=!0,await async function(e,t,r){const n=r?.singleLink,{fd:o}=void 0===n?await qM(e,xo.constants.O_WRONLY|xo.constants.O_CREAT,"write"):await async function(e,t){const r="create"===t.kind,n=r?xo.constants.O_WRONLY|xo.constants.O_CREAT|xo.constants.O_EXCL:xo.constants.O_WRONLY;let o;try{o=await qM(e,n,"write",{removeOnRefusal:r})}catch(t){const r=Sc(t);if("EEXIST"===r||"ENOENT"===r)throw new jM(e,`Refusing to write: ${e} was ${"EEXIST"===r?"created":"removed"} after it was checked`);throw t}const{fd:s}=o;try{const r=await s.stat({bigint:!0});if(1n!==r.nlink)throw new jM(e,`Refusing to write: ${e} has ${r.nlink} hard links`);if("existing"===t.kind&&(r.dev!==t.dev||r.ino!==t.ino))throw new jM(e,`Refusing to write: ${e} was replaced after it was checked`);return o}catch(t){throw r&&await HM(e,s),await s.close(),t}}(e,n);try{await async function(e){for(let t=0;;t++)try{return void await e.truncate(0)}catch(e){const r=Sc(e);if(t>=BM.length||void 0===r||!WM.has(r))throw e;await(0,Fg.setTimeout)(BM[t])}}(o);const e=function(e){return Buffer.isBuffer(e)?e:Buffer.from(e)}(t);let n=0;for(;n{try{await I()}catch(e){throw T=e,A=!0,e}};try{void 0===this.writeFileMutationGuard?await I():await this.writeFileMutationGuard.runExclusive(v,M)}catch(e){if(void 0!==this.writeFileMutationGuard&&(!A||e!==T))return new MI.v3({result:{case:"error",value:new MI.QM({path:r,error:e instanceof Error?e.message:String(e)})}});if(e instanceof jM)return new MI.v3({result:{case:"permissionDenied",value:new MI.U7({path:r,directory:"",operation:"create_file",error:e.message})}});const t=Sc(e);return"EACCES"===t||"EPERM"===t?new MI.v3({result:{case:"permissionDenied",value:new MI.U7({path:r,directory:"",operation:"create_file",error:"Permission denied"})}}):"ENOSPC"===Sc(e)?new MI.v3({result:{case:"noSpace",value:new MI.bM({path:r})}}):"EDQUOT"===t?new MI.v3({result:{case:"error",value:new MI.QM({path:r,error:"Agent-store quota exceeded: this write was rejected because the storage quota is full. Nothing was written; your local copy is intact. Delete or truncate files to free space (including resolved *.conflict* files), then retry. Do not retry the same write without freeing space first."})}}):new MI.v3({result:{case:"error",value:new MI.QM({path:r,error:kc(e)})}})}if(this.fileChangeTracker&&void 0===u&&!h&&!w){const e={...t.toolCallId?{toolCallId:t.toolCallId}:{},...v===r?{}:{writtenPath:v},...void 0===g?{}:{beforeMode:g},...E>0?{createdDirectories:E}:{}};await this.fileChangeTracker.trackChange(r,p,l,e,m)}if(this.onWriteForAiTracking&&void 0===u&&!h){const e=t.toolCallId?{toolCallId:t.toolCallId}:{};try{await this.onWriteForAiTracking({path:r,beforeContent:p,afterContent:l,metadata:e})}catch(e){GM.warn(c,"onWriteForAiTracking failed (write succeeded)",{path:r,error:e instanceof Error?e.message:String(e)})}}const D=x.byteLength;let O;if(void 0!==u||w||h||this.recordEncodingChecks(c,r,p,f,l),t.returnFileContentAfterWrite)try{O=await KM(c,"readText after write",3e3,(()=>ji(r,t.encodingHint)))}catch{}return new MI.v3({result:{case:"success",value:new MI.j6({path:r,linesCreated:P,fileSize:D,...void 0!==O&&{fileContentAfterWrite:O}})}})}catch(e){a.error=e,a.hasError=!0}finally{zM(a)}}recordEncodingChecks(e,t,r,n,o){try{const i={path:t,encoding:n,pages:(s=gu.pages(),"failed"===s?"none":s)};for(const t of function(e,t,r){return[gl(e,t,r),wl(e,t,r)]}(r,n,o))VM.increment(e,1,_l(t,i))}catch(t){for(const t of ll)VM.increment(e,1,{detector:t,outcome:"error",file:"unclassified"});GM.warn(e,"encoding check failed (write succeeded)",{error:t instanceof Error?t.message:String(t)})}var s}}function YM(e,t){return new MI.v3({result:{case:"error",value:new MI.QM({path:e,error:t})}})}class eD extends Error{constructor(e){super("stale write refusal"),this.result=e,this.name="StaleWriteRefusal"}}function tD(e){if("error"!==e.result.case)return!1;const{error:t,path:r}=e.result.value;return t===BT(r)||t===WT(r)}const rD=(0,l.h)("local-exec:provider"),nD=new Set,oD=new yd.AsyncLocalStorage;class sD extends K{getMcpExecutionPolicyDeps(){return{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionStore}}static dropOwnedRequestContextCaches(){for(const e of nD)e.ownedRequestContextExecutor?.invalidateGlobalCache()}static rebuildRequestContextCachesFor(e){for(const t of nD)t.cursorRulesService===e&&t.ownedRequestContextExecutor?.refreshGlobalCache()}constructor(e){super(),this.pendingDecisionStore=e.pendingDecisionStore,this.fileChangeTracker=e.fileChangeTracker,this.gitExecutor=e.gitExecutor,this.ignoreService=e.ignoreService,this.grepProvider=e.grepProvider,this.permissionsService=e.permissionsService,this.workspacePaths=e.workspacePaths,this.worktreeMainPath=e.worktreeMainPath,this.diagnosticsProvider=e.diagnosticsProvider,this.mcpLease=e.mcpLease,this.mcpStateAccessor=e.mcpStateAccessor,this.cursorRulesService=e.cursorRulesService,this.cloudRulesService=e.cloudRulesService,this.subagentsService=e.subagentsService,this.repositoryProvider=e.repositoryProvider,this.projectDir=e.projectDir,this.shellManager=e.shellManager,this._sandboxPolicyResolver=e._sandboxPolicyResolver,this._defaultSandboxPolicy=e._defaultSandboxPolicy??{type:"insecure_none"};const t=e.workspacePaths[0],r=t?function(e){const t=(0,s.join)(e,".cursor/sandbox.json");try{const r=(0,xo.readFileSync)(t,"utf-8"),n=JSON.parse(r),o=(0,Oo.$6)(n);return(0,Oo.l7)(o,e)}catch{return}}(t):void 0,n=e._defaultSandboxPolicySources;this._defaultSandboxPolicySources=r||n?{perUser:n?.perUser,perRepo:r??n?.perRepo,teamAdmin:n?.teamAdmin}:void 0,this.mcpFileOutputThresholdBytes=e.mcpFileOutputThresholdBytes,this.blankSharedPaymentTokensInMcpOutputFiles=!0===e.blankSharedPaymentTokensInMcpOutputFiles,this.backgroundShellFactory=e.backgroundShellFactory,this.backgroundWorkRegistry=e.backgroundWorkRegistry,this.wakeupOwnerConversationId=e.wakeupOwnerConversationId,this.mcpElicitationFactory=e.mcpElicitationFactory,this.createFileWatcher=e.createFileWatcher,this.sharedRequestContextExecutor=e.sharedRequestContextExecutor,this.terminalExecutor=e.terminalExecutor,this.mcpMetaToolEnabled=e.mcpMetaToolEnabled??!1,this.mcpMetaToolSlimDescriptors=e.mcpMetaToolSlimDescriptors??!1,this.mcpInputSchemaJson=e.mcpInputSchemaJson??!1,this.alwaysExposeVirtualMcpAuthTool=e.alwaysExposeVirtualMcpAuthTool??!1,this.enableRecordScreen=e.enableRecordScreen??!1,this.recordScreenArtifactsDir=e.recordScreenArtifactsDir,this.recordScreenDisplay=e.recordScreenDisplay,this.disableRecordScreenRendering=e.disableRecordScreenRendering??!1,this.userTerminalHint=e.userTerminalHint,this.attributionConfigProvider=e.attributionConfigProvider,this.isAttributionDisabledByAdmin=e.isAttributionDisabledByAdmin,this.getAgentSkills=e.getAgentSkills,this.getSmartModeClassifierAutoModeEnabled=e.getSmartModeClassifierAutoModeEnabled,this.getAdminCommandDenylist=e.getAdminCommandDenylist,this.devForceNextSmartModeClassifierBlockToken=e.devForceNextSmartModeClassifierBlockToken,this.getMockPromptTime=e.getMockPromptTime,this.additionalRules=e.additionalRules??[],this.askpassConfig=e.askpassConfig,this.rebuildRequestContextOnRulesChange=!0===e.rebuildRequestContextOnRulesChange;const i=this.terminalExecutor??(0,Oo.Fn)({env:{CURSOR_AGENT:"1"},userTerminalHint:this.userTerminalHint,isLoginShellEnabled:e.isLoginShellEnabled});let a;if(this.workspacePaths.length>1){const e=this.workspacePaths.map((e=>(0,s.dirname)(e)));a=e.every((t=>t===e[0]))?e[0]:void 0}else a=t;let c=new Ju(i,t??(0,o.homedir)(),this.projectDir,{shellOutputBackpressureOptions:e.shellOutputBackpressureOptions,extraEnvProvider:e.shellExtraEnvProvider,powershellUtf8Console:e.powershellUtf8Console,powershellUtf8ChildEnv:e.powershellUtf8ChildEnv,powershellParseAfterUtf8Switch:e.powershellParseAfterUtf8Switch,powershellWebRequestUtf8:e.powershellWebRequestUtf8,powershellPerLineStateDump:e.powershellPerLineStateDump,encodingSlices:e.encodingSlices,keepBackgroundJobs:e.keepShellBackgroundJobs});e.shellCoreWrapper&&(c=e.shellCoreWrapper(c)),this.askpassConfig&&(c=new Xu(c,this.askpassConfig)),this.shellManager&&(c=new Zu(c,this.shellManager));const l=e.overrideShellExecutor??(!0===e.suppressDefaultShellExecutor?void 0:new uM(this.permissionsService,c,this.ignoreService,this.pendingDecisionStore));void 0!==l&&this.register(jT,Dg(l)),this.register(UT,Dg(new LT(this.permissionsService,this.ignoreService,a??t??this.projectDir)));const u=new bM,d=new SM,h=e.overrideWriteExecutor??new QM(this.fileChangeTracker,this.permissionsService,this.pendingDecisionStore,{workspacePaths:this.workspacePaths,workspacePath:a,worktreeMainPath:this.worktreeMainPath,projectDir:this.projectDir,onWriteForAiTracking:e.onWriteForAiTracking,writeFileMutationGuard:e.writeFileMutationGuard,toolCallReads:u,agentFileViews:d});this.register(HT,function(e){const t=(r={execute:(t,r,n)=>e.execute(t,r,n).then((e=>{if(tD(e))throw new eD(e);return e}))},Dg(r));var r;return{async execute(e,r,n){try{return await t.execute(e,r,n)}catch(e){if(e instanceof eD)return e.result;throw e}}}}(h));const p=e.overrideDeleteExecutor??new Hw(this.pendingDecisionStore,this.fileChangeTracker,this.permissionsService,a,e.onDeleteForAiTracking,d);this.register(qT,Dg(p)),this.register(zT,Dg(new Jw({encodingSlices:e.encodingSlices}))),this.register(GT,new C$);const f=this.mcpStateAccessor??new oM(this.mcpLease),m=e.overrideGrepExecutor??new dC(this.ignoreService,this.grepProvider,this.workspacePaths,{mcpStateAccessor:f,permissionsService:this.permissionsService,useStreamingGrep:e.useStreamingGrep,encodingSlices:e.encodingSlices});this.register(VT,Dg(m));const g=e.overrideReadExecutor??new CM(new L_(this.permissionsService,a,{mcpStateAccessor:f,useStreamingRead:e.useStreamingRead,pendingDecisionProvider:this.pendingDecisionStore,encodingSlices:e.encodingSlices}),u,this.permissionsService,a,d),w=new XT(g);this.register(QT,w),e.registerRedactedReadExecutor&&this.register(YT,w);const y=e.overrideLsExecutor??new yC(this.permissionsService,this.ignoreService,a);this.register(eA,Dg(y)),this.register(tA,Dg(new WA(a,this.diagnosticsProvider))),e.getCanvasDiagnostics&&this.register(rA,Dg(new OA(e.getCanvasDiagnostics,e.beginCanvasSave))),this.register(eo,Dg(new yA(ru(new PT(this.mcpLease,this.permissionsService,this.pendingDecisionStore,this.projectDir,this.mcpFileOutputThresholdBytes,this.mcpElicitationFactory,e.ensureMcpServersLoaded,{blankSharedPaymentTokens:this.blankSharedPaymentTokensInMcpOutputFiles}),e.encodingSlices,"exec_mcp",(e=>"success"===e.result.case)),(()=>this.get(QT))))),this.register(to,Dg(new RT(this.mcpLease,e.ensureMcpServersLoaded))),this.register(ro,Dg(ru(new IT(this.mcpLease,a||this.projectDir,this.permissionsService,this.workspacePaths,this.pendingDecisionStore,e.ensureMcpServersLoaded,h),e.encodingSlices,"exec_mcp",(e=>"success"===e.result.case)))),this.register(no,Dg(new iM(f,e.ensureMcpServersLoaded,{filterToRequestedServers:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,...void 0===e.mcpServerRuleSubjects?{}:{serverRuleSubjects:e.mcpServerRuleSubjects}})));const v=this.sharedRequestContextExecutor??this.createOwnedRequestContextExecutor(f,t,e),b=Dg({execute:(e,t,r)=>{const n=oD.getStore();return void 0!==n&&(n.ran=!0),v.execute(e,t,r)}});this.register($r,{execute:async(t,r,n)=>{const o={ran:!1},s=await oD.run(o,(()=>b.execute(t,r,n)));if("success"!==s.result.case||void 0===s.result.value.requestContext)return s;const i=s.clone();if("success"!==i.result.case)return s;const a=i.result.value.requestContext;if(void 0===a)return i;const c=await f.getState(t),l=eM(c,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson});if(a.tools=l.tools,a.mcpInstructions=l.mcpInstructions,a.mcpMetaToolOptions=this.mcpMetaToolEnabled?tM(c,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,slimDescriptors:this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}):void 0,o.ran&&void 0!==e.getMcpFileSystemOptions||(a.mcpFileSystemOptions=await(e.getMcpFileSystemOptions?.(t))),void 0!==a.env&&(a.env.artifactsFolder=e.getArtifactsFolder?.(t),void 0!==e.getSandboxEnabled&&(a.env.sandboxEnabled=e.getSandboxEnabled()),void 0!==e.getSessionSandboxSupported&&(a.env.sandboxSupported=e.getSessionSandboxSupported())),void 0!==e.getMountedAgentStores&&void 0!==a.env)try{const r=await e.getMountedAgentStores(t);a.env.mountedAgentStores=r.map((e=>e.clone()))}catch{a.env.mountedAgentStores=[],rD.warn(t,"Failed to get mounted agent stores; continuing without prompt inventory")}return i}}),this.backgroundShellExecutor=new wd(this.permissionsService,c,this.ignoreService,this.projectDir,this.backgroundShellFactory,this.backgroundWorkRegistry,this.wakeupOwnerConversationId,e.backgroundShellManager),this.shellRedeliveryCaches=e.shellRedeliveryCaches??{backgroundShell:Mg(),shellStream:Mg(),writeStdin:Mg()},this.register(vA,Dg(this.backgroundShellExecutor,void 0,this.shellRedeliveryCaches.backgroundShell)),this.shellStreamExecutor=new yM(this.permissionsService,c,this.ignoreService,this.backgroundShellExecutor.getManager()),this.register(ee,function(e,t,r=Mg(t)){return{async*execute(t,n,o){if(!o?.execId)return void(yield*e.execute(t,n,o));const s=$g(o.execId,n),i=r.get(s);if(i)return void(yield*i.fork());const a=e.execute(t,n,o),c=new Ag(a);r.set(s,c),yield*c.fork()}}}(this.shellStreamExecutor,void 0,this.shellRedeliveryCaches.shellStream)),void 0!==e.agentStoreConflictDrainer&&this.register(SA,new AA(e.agentStoreConflictDrainer)),this.register(kA,new hM(this.permissionsService)),this.register(_A,new x$(this.permissionsService)),this.register(CA,new AM(this.permissionsService));const S=new pM(this.shellStreamExecutor);this.register(EA,Dg(S));const k=!1===e.enableWriteBackgroundShellStdin?new $A((async()=>{throw new Error(e.writeBackgroundShellStdinDisabledReason??"write_shell_stdin is disabled for this session")})):new $A(((e,t)=>this.backgroundShellExecutor.writeStdin(e,t)));if(this.register(bA,Dg(k,void 0,this.shellRedeliveryCaches.writeStdin)),e.computerUseExecutor&&(this.computerUseExecutor=e.computerUseExecutor,this.register(xA,Dg(this.computerUseExecutor)),void 0!==e.computerUseEndTurnExecutor&&this.register(PA,e.computerUseEndTurnExecutor)),this.enableRecordScreen){if(!this.recordScreenArtifactsDir||!this.recordScreenDisplay)throw new Error("recordScreenArtifactsDir and recordScreenDisplay are required when enableRecordScreen is true");this.recordScreenExecutor=new F$({artifactsDir:this.recordScreenArtifactsDir,display:this.recordScreenDisplay,disablePolishedRendering:this.disableRecordScreenRendering,polishedRenderer:e.polishedRecordingRenderer}),this.register(RA,Dg(this.recordScreenExecutor))}}createOwnedRequestContextExecutor(e,t,r){const n=new aM(this.cursorRulesService,this.cloudRulesService,this.subagentsService,this.repositoryProvider,this.grepProvider,e,this.gitExecutor,void 0===r.requestContextWorkspacePaths?this.workspacePaths:[...r.requestContextWorkspacePaths],{projectDir:this.projectDir,isWorkingDirHomeDir:r.requestContextIsWorkingDirHomeDir??(0,Yo.yn)(t,(0,o.homedir)()),agentNotesEnabled:r.agentNotesEnabled,reportProcessWorkingDirectory:r.reportProcessWorkingDirectory,sectionLoadTimeoutMs:r.requestContextSectionLoadTimeoutMs,reportSectionCompleteness:r.reportRequestContextSectionCompleteness,freshSectionWaitMs:r.requestContextFreshSectionWaitMs,createFileWatcher:this.createFileWatcher,getSandboxEnabled:r.getSandboxEnabled,getSandboxSupported:r.getSandboxSupported,getNetworkAllowlistInfo:r.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:this.getSmartModeClassifierAutoModeEnabled,getAdminCommandDenylist:this.getAdminCommandDenylist,devForceNextSmartModeClassifierBlockToken:this.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:this.getMockPromptTime,userTerminalHint:this.userTerminalHint,getMcpFileSystemOptions:r.getMcpFileSystemOptions,mcpMetaToolEnabled:this.mcpMetaToolEnabled,mcpMetaToolSlimDescriptors:this.mcpMetaToolSlimDescriptors,mcpInputSchemaJson:this.mcpInputSchemaJson,alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,getArtifactsFolder:r.getArtifactsFolder,secretRedactionEnabled:r.secretRedactionEnabled,attributionConfigProvider:this.attributionConfigProvider,isAttributionDisabledByAdmin:this.isAttributionDisabledByAdmin,getAgentSkills:this.getAgentSkills,additionalRules:this.additionalRules,getComputerUseSupported:()=>void 0!==this.computerUseExecutor,getComputerUseDesktop:r.getComputerUseDesktop,onRequestContext:r.onRequestContext,mcpFieldsFromCaller:!0===r.requestContextMcpFieldsFromOverlay,deferWarmup:!0===r.deferRequestContextWarmup});return!0===r.deferRequestContextWarmup&&(this.requestContextExecutorAwaitingWarmup=n),this.rebuildRequestContextOnRulesChange&&(this.ownedRequestContextExecutor=n,nD.add(this),this.disposeRulesChangeListener=this.cursorRulesService.onDidChangeRules?.((()=>{n.rebuildAllCaches()}))),n}warmRequestContext(){const e=this.requestContextExecutorAwaitingWarmup;this.requestContextExecutorAwaitingWarmup=void 0,e?.warm()}getRecordScreenExecutor(){return this.recordScreenExecutor}getBackgroundShellManager(){return this.backgroundShellExecutor.getManager()}getShellRedeliveryCaches(){return this.shellRedeliveryCaches}hasForegroundShells(){return this.shellStreamExecutor.hasForegroundWork()}withPendingShells(e){return new J(e,[G(ee,this.shellStreamExecutor.pendingFrom(e))])}async dispose(){this.requestContextExecutorAwaitingWarmup=void 0,this.rebuildRequestContextOnRulesChange&&(nD.delete(this),this.disposeRulesChangeListener?.(),this.disposeRulesChangeListener=void 0,this.ownedRequestContextExecutor?.dispose(),this.ownedRequestContextExecutor=void 0),this.backgroundShellExecutor.dispose(),this.recordScreenExecutor&&await this.recordScreenExecutor.dispose()}}function iD(e){return e.replace(/\\/g,"/")}function aD(e,t){for(const r of t){const t=iD(r);if(e===t||e.startsWith(`${t}/`))return!0}return!1}var cD;function lD(e,t,r){if(function(e){return Boolean(e.plugin?.trim()||e.pluginId?.trim()||e.marketplaceId?.trim())}(e))return cD.Plugin;const n=iD(e.fullPath);return aD(n,r.builtinDirs)?cD.Builtin:Lm(e.fullPath,t).inAgentStore?cD.UserStore:aD(n,r.userDirs)?cD.UserHome:(aD(n,r.workspaceDirs),cD.Workspace)}"function"==typeof SuppressedError&&SuppressedError,function(e){e[e.Builtin=0]="Builtin",e[e.UserStore=1]="UserStore",e[e.UserHome=2]="UserHome",e[e.Workspace=3]="Workspace",e[e.Plugin=4]="Plugin"}(cD||(cD={}));var uD=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const dD=(0,zs.debuglog)("merged-agent-skills"),hD=(0,l.h)("merged-agent-skills");class pD{constructor(e,t=()=>[],r){this.services=e,this.getDisabledManagedSkillPaths=t,this.getPromptSortContext=r,this.onChangeCallbacks=new Set}async getAllAgentSkills(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,$.VI)(e.withName("MergedAgentSkillsService.getAllAgentSkills")),!1),n=this.services.map((e=>e.getAllAgentSkills(r.ctx).catch((e=>(dD("Failed to load agent skills from service: %s",e instanceof Error?e.message:String(e)),[]))))),o=async()=>{try{return{ok:!0,paths:await this.getDisabledManagedSkillPaths()}}catch(e){return hD.warn(r.ctx,"getDisabledManagedSkillPaths failed; failing closed by dropping all managed skills for this call",{error:e instanceof Error?e.message:String(e)}),{ok:!1}}},[i,a]=await Promise.all([Promise.all(n),o()]),c=i.flat(),l=this.getPromptSortContext?.(),u=Um(c,l??Fm);let d=u;return a.ok?a.paths.length>0&&(d=u.filter((e=>!function(e,t){if(!e)return!1;const r=e.replace(/\\/g,"/");return t.some((e=>r.endsWith(e)))}(e.fullPath,a.paths)))):d=u.filter((e=>{return!((t=e.fullPath)&&t.replace(/\\/g,"/").includes(fD));var t})),void 0!==l?function(e,t){if(e.length<=1)return e;const r=function(e){const t=[ym(e.userHomeDirectory).dirPath],r=Em(e.userHomeDirectory,!0).map((e=>e.dirPath)),n=[];for(const t of e.workspacePaths){n.push((0,s.join)(t,".cursor","rules"));for(const e of Cm(t,!0))n.push(e.dirPath)}return{builtinDirs:t,userDirs:r,workspaceDirs:n}}(t),n=e.map(((e,n)=>({skill:e,index:n,tier:lD(e,t,r)})));return n.sort(((e,t)=>e.tier-t.tier||e.index-t.index)),n.map((e=>e.skill))}(d,l):d}catch(e){t.error=e,t.hasError=!0}finally{uD(t)}}reload(e){for(const t of this.services)t.reload(e)}scheduleDidChangeSkills(){void 0===this.changeTimer&&(this.changeTimer=setTimeout((()=>{this.changeTimer=void 0;for(const e of Array.from(this.onChangeCallbacks))e()}),pD.CHANGE_COALESCE_MS))}ensureChangeListenersRegistered(){void 0===this.disposeChangeListeners&&(this.disposeChangeListeners=this.services.map((e=>e.onDidChangeSkills((()=>this.scheduleDidChangeSkills())))))}disposeChangeListenersIfUnused(){if(!(this.onChangeCallbacks.size>0||void 0===this.disposeChangeListeners)){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0,void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0)}}onDidChangeSkills(e){return this.onChangeCallbacks.add(e),this.ensureChangeListenersRegistered(),()=>{this.onChangeCallbacks.delete(e),this.disposeChangeListenersIfUnused()}}dispose(){if(void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0),this.onChangeCallbacks.clear(),void 0!==this.disposeChangeListeners){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0}for(const e of this.services)e.dispose()}}pD.CHANGE_COALESCE_MS=1500;const fD=`/${pm.configDir}/${pm.subdir}/`;function mD(e,t){if((e.disabledEnvironments??[]).includes(t))return!1;const r=e.environments??[];return 0===r.length||r.includes(t)}const gD=(0,l.h)("skill-sync-manifest"),wD=".sync-manifest.json",yD=new Set(["EPERM","EBUSY"]),vD=[20,50,100],bD=new Map;async function SD(e,t){try{const r=await(0,Co.readFile)((0,s.join)(e,wD),"utf-8"),n=JSON.parse(r);return function(e){if(!function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e))return!1;const t=e;return"number"==typeof t.version&&"object"==typeof t.skills&&null!==t.skills&&!Array.isArray(t.skills)&&(void 0===t.lastInventoryAt||"number"==typeof t.lastInventoryAt)}(n)?n:(gD.warn(t,"Manifest failed schema validation, resetting",{skillDir:e}),{version:1,skills:{}})}catch(r){return r instanceof Error&&"ENOENT"===Sc(r)||gD.debug(t,"Failed to read sync manifest, resetting",{skillDir:e,error:String(r)}),{version:1,skills:{}}}}function kD(e,t,r){e.skills[t]={lastSyncedAt:r}}function _D(e,t){delete e.skills[t]}var CD=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const ED=(0,l.h)("builtin-skills-sync");function xD(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function PD(e){for(const t of Object.keys(e.resources??{}))if(0===t.length||t.includes("\\")||t.includes("\0")||s.posix.isAbsolute(t)||s.posix.normalize(t)!==t||t.split("/").includes("..")||"SKILL.md"===s.posix.basename(t)||!t.endsWith(".md"))throw new Error(`Unsafe managed skill resource path: ${JSON.stringify(t)}`)}function RD(e){const t=eh(e.content),r=xD(t.data)?t.data:{};return th(`${t.content.trim()}\n`,function(e,t){const r={...t??{},name:e.id,description:e.description};delete r.disabledEnvironments,e.disableModelInvocation?r["disable-model-invocation"]=!0:delete r["disable-model-invocation"],e.environments&&e.environments.length>0?r.environments=e.environments:delete r.environments,e.disabledEnvironments&&e.disabledEnvironments.length>0?r["disabled-environments"]=e.disabledEnvironments:delete r["disabled-environments"];const n={...xD(r.metadata)?r.metadata:{}};return delete n.environments,delete n.disabledEnvironments,delete n["disabled-environments"],Object.keys(n).length>0?r.metadata=n:delete r.metadata,r}(e,r))}async function ID(e,t,r){const n=(0,s.join)(t,r.id),o=(0,s.join)(n,"SKILL.md"),i=r.fileContent,a=Object.keys(r.resources),c=await TD(n);if(a.length>0||c.length>0){const e=new Map([["SKILL.md",i],...Object.entries(r.resources)]),o=new Set(["SKILL.md",...c]);if(o.size===e.size&&[...e.keys()].every((e=>o.has(e)))){let t=!0;for(const[r,o]of e)try{if(await(0,Co.readFile)((0,s.join)(n,...r.split("/")),"utf-8")!==o){t=!1;break}}catch{t=!1;break}if(t)return!1}return await async function(e,t){const r=(0,s.join)(e,t.id),n=await(0,Co.mkdtemp)((0,s.join)(e,`.${t.id}-staging-`)),o=`${n}-backup`;let i=!1;try{await(0,Co.writeFile)((0,s.join)(n,"SKILL.md"),t.fileContent,"utf-8");for(const[e,r]of Object.entries(t.resources)){const t=(0,s.join)(n,...e.split("/"));await(0,Co.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,Co.writeFile)(t,r,"utf-8")}try{await(0,Co.rename)(r,o),i=!0}catch(e){if(!(e instanceof Error)||"ENOENT"!==Sc(e))throw e}try{await(0,Co.rename)(n,r)}catch(e){throw i&&(await(0,Co.rename)(o,r),i=!1),e}i&&(await(0,Co.rm)(o,{recursive:!0,force:!0}),i=!1)}finally{await(0,Co.rm)(n,{recursive:!0,force:!0})}}(t,r),!0}try{if(await(0,Co.readFile)(o,"utf-8")===i)return!1}catch(t){t instanceof Error&&"ENOENT"===Sc(t)||ED.warn(e,"Unexpected error reading skill file",{skillId:r.id,error:String(t)})}return await(0,Co.mkdir)(n,{recursive:!0}),await(0,Co.writeFile)(o,i,"utf-8"),!0}async function TD(e,t=""){const r=t?(0,s.join)(e,...t.split("/")):e;let n;try{n=await(0,Co.readdir)(r,{withFileTypes:!0})}catch(e){if(e instanceof Error&&"ENOENT"===Sc(e))return[];throw e}const o=[];for(const r of n){const n=t?`${t}/${r.name}`:r.name;r.isDirectory()?o.push(...await TD(e,n)):r.isFile()&&r.name.endsWith(".md")&&"SKILL.md"!==n&&o.push(n)}return o}async function AD(e,t){try{return(await(0,Co.readdir)(t,{withFileTypes:!0})).filter((e=>e.isDirectory()&&!e.name.startsWith("."))).map((e=>e.name))}catch(r){return r instanceof Error&&"ENOENT"===Sc(r)||ED.warn(e,"Failed to list skills directory, skipping cleanup",{skillDir:t,error:String(r)}),[]}}async function $D(e,t={}){const r={stack:[],error:void 0,hasError:!1};try{const i=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,$.VI)(e.withName("syncBuiltinSkills")),!1).ctx,a=Date.now(),c=t.userHome??(0,o.homedir)(),l=t.skillDir??ym(c).dirPath;await(0,Co.mkdir)(l,{recursive:!0});const[u,d]=await Promise.all([SD(l,i),AD(i,l)]),h=u.lastInventoryAt;(void 0===h||a-h>=864e5)&&(await async function(e,t,r,n){try{const o=await Promise.all(r.map((async e=>{const r=(0,s.join)(t,e),[o,i]=await Promise.all([MD((0,s.join)(r,"SKILL.md")),"canvas"===e?MD((0,s.join)(r,"sdk")):Promise.resolve(!1)]);return{skill_id:e,has_skill_md:o,has_sdk_dir:i,last_synced_at:n.skills[e]?.lastSyncedAt??null}})));ED.info(e,"managed_skills.startup_inventory",{skills_on_disk:o,manifest_present:Object.keys(n.skills).length>0})}catch(t){ED.warn(e,"Failed to emit managed skills startup inventory",{error:String(t)})}}(i,l,d,u),u.lastInventoryAt=a);const p=new Map;for(const e of t.managedSkills??[])(n=e.id)&&n===n.trim()&&!(n.includes("..")||n.includes("/")||n.includes("\\"))?p.set(e.id,e):ED.warn(i,"Skipping managed skill with unsafe id",{skillId:e.id});const f=void 0===t.canvasKit?void 0:bm(c,t.canvasKit).dirPath,m=void 0!==f&&await MD((0,s.join)(f,vm)),g=new Set([...p.keys(),...d,...m?[vm]:[]]),w=e=>void 0!==f&&e===vm?f:l,y=e=>void 0!==f&&e===vm?m:d.includes(e);let v=0,b=0;const S=[];for(const e of g)try{const t=p.get(e),r=u.skills[e],n=r?a-r.lastSyncedAt:0,o=void 0!==r&&n>2592e5,c=void 0!==t&&mD(t,"local"),d=void 0!==t&&!c,h=void 0!==r||y(e),f=w(e);if(t&&!1!==t.enabled&&c)PD(t),f!==l&&await(0,Co.mkdir)(f,{recursive:!0}),await ID(i,f,{id:e,fileContent:RD(t),resources:t.resources??{}})?v++:b++,kD(u,e,a);else if(!1===t?.enabled||d||o){const n=!1===t?.enabled?"enabled_false":d?"environment_ineligible":"grace_expired";await(0,Co.rm)((0,s.join)(f,e),{recursive:!0,force:!0}),_D(u,e),h&&(S.push(e),ED.info(i,"managed_skills.removed",{skill_id:e,reason:n,server_enabled:t?.enabled??null,had_manifest_entry:void 0!==r,last_synced_ms_ago:r?a-r.lastSyncedAt:null}))}else r||kD(u,e,a)}catch(t){ED.warn(i,"Failed to apply skill, will retry next sync",{skillId:e,error:String(t)})}try{await function(e,t){const r=(bD.get(e)??Promise.resolve()).then((()=>async function(e,t){const r=(0,s.join)(e,`${wD}.${process.pid}.${(0,bo.randomBytes)(6).toString("hex")}.tmp`);await(0,Co.mkdir)(e,{recursive:!0});try{await(0,Co.writeFile)(r,JSON.stringify(t,null,2),"utf-8"),await async function(e,t){for(let r=0;;r++)try{return void await(0,Co.rename)(e,t)}catch(e){const t=Sc(e),n=vD[r];if(void 0===n||void 0===t||!yD.has(t))throw e;await(0,Or.cb)(n)}}(r,(0,s.join)(e,wD))}catch(e){throw await(0,Co.rm)(r,{force:!0}).catch((()=>{})),e}}(e,t))),n=r.catch((()=>{}));return bD.set(e,n),n.then((()=>{bD.get(e)===n&&bD.delete(e)})),r}(l,u)}catch(e){!function(e){if(e instanceof Error&&"ENOENT"===Sc(e))return!0;const t=String(e);return t.includes("ENOENT")||t.includes("no such file or directory")}(e)?ED.warn(i,"Failed to persist sync manifest",{skillDir:l,error:String(e)}):ED.debug(i,"Skipped persisting sync manifest, path removed concurrently",{skillDir:l,error:String(e)})}return{synced:v,upToDate:b,removed:S}}catch(e){r.error=e,r.hasError=!0}finally{CD(r)}var n}async function MD(e){try{return await(0,Co.stat)(e),!0}catch(e){const t=Sc(e);if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}const DD=(0,l.h)("managed-skills-sync");function OD(e,t,r,n,o,s){const i=[],a=e.mcpServers;if(!a)return i;for(const[e,c]of Object.entries(a)){const a=c,l=`plugin-${n}-${e}`,u=e;a.url?i.push({identifier:l,name:u,marketplace:t,marketplaceId:r,pluginName:n,pluginId:o,pluginSource:s,type:"streamableHttp",url:a.url,headers:a.headers,auth:a.auth,tls:a.tls,enabledTools:a.enabledTools,placement:a.placement,projectManaged:!1,pluginManaged:!0}):a.command&&i.push({identifier:l,name:u,marketplace:t,marketplaceId:r,pluginName:n,pluginId:o,pluginSource:s,type:"stdio",command:a.command,args:a.args??[],env:a.env??{},cwd:a.cwd,envFile:a.envFile,enabledTools:a.enabledTools,projectManaged:!1,pluginManaged:!0})}return i}function FD(e){try{const t=new URL(e),r=new URL(t.pathname,t.origin);return r.search=t.search,r.pathname.endsWith("/")&&r.pathname.length>1&&(r.pathname=r.pathname.slice(0,-1)),"/"===r.pathname?r.origin+r.search:r.toString()}catch{return e.toLowerCase().trim()}}class ND{constructor(e){this.pluginsService=e}async getPluginMcpServers(){const e=await this.pluginsService.reload(),t=[];for(const r of e){const e="marketplace"in r.identifier.sourceInfo?r.identifier.sourceInfo.marketplace:void 0,n="marketplaceDbId"in r.identifier.sourceInfo?r.identifier.sourceInfo.marketplaceDbId:void 0,o=r.identifier.sourceInfo.name,s="pluginDbId"in r.identifier.sourceInfo?r.identifier.sourceInfo.pluginDbId:void 0,i=r.mcpConfig;i&&t.push(...OD(i,e,n,o,s,r.identifier.source))}return function(e){const t=[],r=new Set;for(const n of e){if("streamableHttp"!==n.type||!n.url){t.push(n);continue}const e=FD(n.url);r.has(e)||(r.add(e),t.push(n))}return t}(t)}}var LD=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function jD(e,t){return void 0===e?[]:(Array.isArray(e)?e:[e]).map((e=>({...e,userHomeDir:t})))}class UD{constructor(e,t,r,n,o,s){this.workspacePaths=e,this.userHomeDirectory=t,this.getSettings=r,this.marketplaceOptions=n,this.localPluginVariablesLookup=s,this.plugins=[],this._loadFailures=[],this._pluginSetIncomplete=!0,this._retainedFromPreviousLoad=0,this._wasFirstLoad=!0,this.loadedOnce=!1,this._extensionPlugins=new Map,this._extensionPluginOriginalPaths=new Map,this.pluginLogger=o??Tp,this.reload()}async getAllEnabledPlugins(){return await this.ensureLoaded(),[...this.plugins]}getLoadFailures(){return[...this._loadFailures]}isPluginSetIncomplete(){return this._pluginSetIncomplete}getLoadDiagnostics(){return{userHomeDirectory:this.userHomeDirectory,pluginsLoaded:this.plugins.length,retainedFromPreviousLoad:this._retainedFromPreviousLoad,wasFirstLoad:this._wasFirstLoad,sourceUnavailable:this._pluginSetIncomplete}}async reload(){return this.loadPromise||(this.loadPromise=this.load().then((async e=>{const t=!this.loadedOnce;let r=[];try{r=await this._reloadExtensionPlugins()}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugins after base load success: ${kc(e)}`)}const n=e.sourceUnavailable?this._retainPluginsMissingFromPartialLoad(e.plugins):[],o=[...e.plugins,...n],s=new Set(o.map((e=>e.installPath))),i=r.filter((e=>!s.has(e.installPath)));return this.plugins=[...o,...i],e.sourceUnavailable||(this._loadFailures=e.failures),this._pluginSetIncomplete=e.sourceUnavailable,this._retainedFromPreviousLoad=n.length,this._wasFirstLoad=t,this.loadedOnce=!0,this.pluginLogger.log("info",`Plugins reload completed: ${this.plugins.length} plugins loaded (${i.length} extension, ${n.length} retained), ${e.failures.length} failures`),this.plugins})).catch((async e=>{const t=!this.loadedOnce;this.pluginLogger.log("error",`Failed to load plugins: ${e}`),this._pluginSetIncomplete=!0,this._retainedFromPreviousLoad=0,this._wasFirstLoad=t;try{const e=await this._reloadExtensionPlugins(),t=new Set(this.plugins.map((e=>e.installPath)));this.plugins=[...this.plugins,...e.filter((e=>!t.has(e.installPath)))]}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugins after base load failure: ${kc(e)}`)}return this.loadedOnce=!0,this.plugins})).finally((()=>{this.loadPromise=void 0}))),this.loadPromise}_retainPluginsMissingFromPartialLoad(e){if(!this.loadedOnce)return[];const t=new Set(e.map(om));return this.plugins.filter((e=>"extension"!==e.identifier.source&&void 0===e.loadError&&e.installPath.length>0&&!t.has(om(e))))}async reloadPlugin(e){this.loadPromise&&await this.loadPromise;const t=jD(this.marketplaceOptions,this.userHomeDirectory);if(0===t.length)return;if(!(this.getSettings().loadCursorFirstParty??t.length>0))return;const r=t=>t.pluginDbId===e.pluginDbId,n=e=>"cursor-first-party"===e.identifier.source||"cursor-third-party"===e.identifier.source?e.identifier.sourceInfo:void 0,o=t=>n(t)?.pluginDbId===e.pluginDbId,s=(t,r)=>void 0!==t.pluginDbId?t.pluginDbId===e.pluginDbId:t.pluginName===r?.name&&t.marketplaceName===r?.marketplace;let i,a,c;for(const l of t){let t;try{t=await rm({...l,log:l.log??this.pluginLogger,pluginFilter:r})}catch(t){this.pluginLogger.log("error",`reloadPlugin: source load failed for ${e.name}: ${kc(t)}`);continue}const u=t.plugins.find((e=>o(e)&&void 0===e.loadError));if(void 0!==u){i=u;break}const d=t.plugins.find(o);if(void 0!==d&&void 0===a){const e=n(d);a=d,c=t.failures.find((t=>s(t,e)))}}if(void 0===i){if(void 0!==a){const t=n(a),r={...c??{pluginName:t?.name??e.name,errorMessage:a.loadError??"Plugin load failed",errorType:"unknown",...void 0!==t?.marketplace&&{marketplaceName:t.marketplace}},pluginDbId:e.pluginDbId};this._loadFailures=[...this._loadFailures.filter((e=>!s(e,t))),r]}return}const l=this.plugins.findIndex(o);if(-1===l)this.plugins=[...this.plugins,i];else{const e=[...this.plugins];e[l]=i,this.plugins=e}this.loadedOnce=!0;const u=n(i);return this._loadFailures=this._loadFailures.filter((e=>!s(e,u))),i}async registerExtensionPlugin({path:e,extensionId:t}){const r=(0,s.resolve)(e),n=await(0,Co.realpath)(r);if(!(await(0,Co.stat)(n)).isDirectory())throw new Error(`Extension plugin path is not a directory: ${n}`);const i=o.homedir();if(n.split(s.sep).filter(Boolean).length<3||n===i||"/"===n)throw new Error(`Extension plugin path is too broad (must be a specific subdirectory, not root or home): ${n}`);for(const[e,r]of this._extensionPlugins)if(e!==t&&r.has(n))throw new Error(`Plugin path ${n} is already registered by extension ${e}`);let a=this._extensionPlugins.get(t);if(a||(a=new Map,this._extensionPlugins.set(t,a)),a.has(n))return void this._rememberExtensionPluginOriginalPath({extensionId:t,originalPath:r,canonicalPath:n});const c=(0,s.basename)(n),l=await this._loadExtensionPluginContent(n,t);a.set(n,l),this._rememberExtensionPluginOriginalPath({extensionId:t,originalPath:r,canonicalPath:n}),this.pluginLogger.log("info",`Registered extension plugin: ${c} from ${n} (extension: ${t})`)}async unregisterExtensionPlugin({path:e,extensionId:t}){const r=this._extensionPlugins.get(t);if(!r)return!1;const n=(0,s.resolve)(e);let o;try{o=await(0,Co.realpath)(n)}catch{const e=this._extensionPluginOriginalPaths.get(t);o=e?.get(n)??n}const i=r.delete(o);return 0===r.size?(this._extensionPlugins.delete(t),this._extensionPluginOriginalPaths.delete(t)):i&&this._forgetExtensionPluginOriginalPath(t,o),i&&this.pluginLogger.log("info",`Unregistered extension plugin: ${o} (extension: ${t})`),i}async _loadExtensionPluginContent(e,t){const r=(0,s.basename)(e),n={name:r,localPath:e,extensionId:t},o=await Kf(e,r,{name:r,version:"0.0.0"});return o.displayName&&(n.name=o.displayName),{identifier:{source:"extension",sourceInfo:n},installPath:e,...void 0!==o.displayName&&{displayName:o.displayName},...void 0!==o.description&&{description:o.description},...void 0!==o.authorName&&{authorName:o.authorName},...void 0!==o.logoUrl&&{logoUrl:o.logoUrl},...void 0!==o.version&&{version:o.version},...void 0!==o.homepage&&{homepage:o.homepage},...void 0!==o.repository&&{repository:o.repository},skills:o.skills,rules:o.rules,agents:o.agents,commands:o.commands,mcpConfig:o.mcpConfig??void 0,capabilities:o.capabilities,hooks:o.hooks}}_rememberExtensionPluginOriginalPath(e){let t=this._extensionPluginOriginalPaths.get(e.extensionId);t||(t=new Map,this._extensionPluginOriginalPaths.set(e.extensionId,t)),t.set(e.originalPath,e.canonicalPath)}_forgetExtensionPluginOriginalPath(e,t){const r=this._extensionPluginOriginalPaths.get(e);if(r){for(const[e,n]of r)n===t&&r.delete(e);0===r.size&&this._extensionPluginOriginalPaths.delete(e)}}_getExtensionPluginPaths(){const e=[];for(const[t,r]of this._extensionPlugins)for(const n of r.keys())e.push({canonicalPath:n,extensionId:t});return e}async _reloadExtensionPlugins(){const e=this._getExtensionPluginPaths(),t=[];for(const{canonicalPath:r,extensionId:n}of e)try{const e=await this._loadExtensionPluginContent(r,n),o=this._extensionPlugins.get(n);o&&o.set(r,e),t.push(e)}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugin ${r}: ${kc(e)}`);const o=this._extensionPlugins.get(n),s=o?.get(r);s&&t.push(s)}return t}async ensureLoaded(){this.loadPromise?await this.loadPromise:this.loadedOnce||await this.reload()}async load(){const e={stack:[],error:void 0,hasError:!1};try{const t=(0,y.q6)().withName("LocalPluginsService.load"),r=(function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(e,(0,$.VI)(t),!1),performance.now()),n=e=>{this.pluginLogger.increment(`local_plugins_service.load.${e}`,1),this.pluginLogger.distribution("local_plugins_service.load.duration",performance.now()-r,{outcome:e})},o=this.getSettings(),i=jD(this.marketplaceOptions,this.userHomeDirectory),a=o.importThirdPartyPlugins,c=o.loadUserLocalPlugins??!0,l=o.loadCursorFirstParty??i.length>0;if(!a&&!l&&!c)return this.pluginLogger.log("info","Skipping plugin loading, cursor 1p, 3p, and user-local plugins are disabled"),{plugins:[],failures:[],sourceUnavailable:!1};this.pluginLogger.increment("local_plugins_service.load.start",1);const u=(e,t)=>{this.pluginLogger.increment("local_plugins_service.load_plugin.error",1),this.pluginLogger.log("error",`Cursor plugin load error ${e.name}@${e.version}: ${t?.message??String(t)}`)};try{const e=await async function(e,t={}){const r=t.log??Tp,n=performance.now(),o=t.loadClaude??!0,i=t.loadUserLocal??!0,a=t.marketplaceSources??[],c=t.loadCursorFirstParty??a.length>0,l=[],u=[];let d;o&&l.push(Xf(e,0,{userHomeDir:t.userHomeDir,onError:t.onError,log:r})),c&&a.length>0&&(d=Promise.allSettled(a.map((e=>rm({...e,userHomeDir:e.userHomeDir??t.userHomeDir,log:e.log??r}))))),i&&l.push(async function(e={}){const t=e.log??Tp,r=performance.now(),n=e.userHomeDir??process.env.HOME;if(!n)return t.log("info","loadUserLocalPlugins: no home directory available, skipping"),[];const o=(0,s.join)(n,".cursor","plugins","local");let i;try{i=await(0,Co.readdir)(o,{withFileTypes:!0})}catch{return t.log("info",`loadUserLocalPlugins: ${o} not found or not readable (${(performance.now()-r).toFixed(1)}ms)`),[]}const a=await(0,Co.realpath)(o).catch((()=>(0,s.resolve)(o))),c=[];for(const r of i){if(!r.isDirectory()&&!r.isSymbolicLink())continue;if(r.name.startsWith("."))continue;const n=(0,s.join)(o,r.name);try{if(r.isSymbolicLink()){let e;try{e=await(0,Co.realpath)(n)}catch(e){t.log("warn",`loadUserLocalPlugin ${r.name} rejected: failed to resolve symlink (${e instanceof Error?e.message:String(e)})`);continue}try{vf(a,e)}catch{t.log("warn",`loadUserLocalPlugin ${r.name} rejected: symlink target ${e} is outside ${o}`);continue}}if(!(await(0,Co.stat)(n)).isDirectory()){r.isSymbolicLink()&&t.log("warn",`loadUserLocalPlugin ${r.name} rejected: symlink target is not a directory`);continue}const s=performance.now(),i=await(e.localPluginVariablesLookup?.(r.name)),{displayName:l,description:u,authorName:d,logoUrl:h,version:p,homepage:f,repository:m,variablesSchema:g,skills:w,rules:y,agents:v,commands:b,mcpConfig:S,capabilities:k,hooks:_}=await Kf(n,r.name,void 0,{configuredVariables:i,log:t}),C={source:"user-local",sourceInfo:{name:r.name,localPath:n}};c.push({identifier:C,installPath:n,...void 0!==l&&{displayName:l},...void 0!==u&&{description:u},...void 0!==d&&{authorName:d},...void 0!==h&&{logoUrl:h},...void 0!==p&&{version:p},...void 0!==f&&{homepage:f},...void 0!==m&&{repository:m},variablesSchema:g,skills:w,rules:y,agents:v,commands:b,mcpConfig:S??void 0,capabilities:k,hooks:_}),t.log("info",`loadUserLocalPlugin ${r.name} loaded in ${(performance.now()-s).toFixed(1)}ms`)}catch(e){t.log("error",`loadUserLocalPlugin ${r.name} failed: ${e instanceof Error?e.message:String(e)}`)}}return t.log("info",`loadUserLocalPlugins completed in ${(performance.now()-r).toFixed(1)}ms (${c.length} plugins loaded)`),c}({userHomeDir:t.userHomeDir,log:r,localPluginVariablesLookup:t.localPluginVariablesLookup}));const[h,p]=await Promise.all([Promise.allSettled(l),d??Promise.resolve([])]);let f=!1;const m=[];for(const e of p)"rejected"!==e.status?(e.value.sourceUnavailable&&(f=!0),m.push(...e.value.plugins),u.push(...e.value.failures)):(f=!0,r.log("error",`marketplace source threw while loading; treating it as unavailable: ${String(e.reason)}`));for(const e of h)"rejected"!==e.status?m.push(...e.value):(f=!0,r.log("error",`plugin source threw while loading; treating it as unavailable: ${String(e.reason)}`));const g=new Set,w=[];for(const e of m){if(!e.installPath){w.push(e);continue}const t=await(0,Co.realpath)(e.installPath).catch((()=>e.installPath));g.has(t)||(g.add(t),w.push(e))}const y=new Map,v=[];for(const e of w){const t=nm(e);if(void 0!==t){const r=y.get(t),n=!e.loadError;if(!0===r)continue;if(!1===r&&n){const r=v.findIndex((e=>nm(e)===t&&e.loadError));-1!==r&&v.splice(r,1),y.set(t,!0),v.push(e);continue}y.set(t,n)}v.push(e)}const b=performance.now()-n;return r.log("info",`loadAllPlugins completed in ${b.toFixed(1)}ms (claude=${o}, userLocal=${i}, marketplace=${a.length} sources, total=${v.length} plugins, failures=${u.length}, sourceUnavailable=${f})`),{plugins:v,failures:u,sourceUnavailable:f}}(this.workspacePaths,{userHomeDir:this.userHomeDirectory,loadClaude:a,loadUserLocal:c,loadCursorFirstParty:l&&i.length>0,marketplaceSources:i.length>0?i.map((e=>({...e,onCursorError:u}))):void 0,onError:(e,t)=>{this.pluginLogger.log("error",`Claude plugin load error ${e.raw}: ${t?.message??String(t)}`)},log:this.pluginLogger,localPluginVariablesLookup:this.localPluginVariablesLookup});return n("success"),this.pluginLogger.log("info",`Plugins loaded in ${(performance.now()-r).toFixed(1)}ms`),e}catch(e){return n("error"),this.pluginLogger.log("error",`Failed to load all plugins: ${kc(e)}`),{plugins:[],failures:[],sourceUnavailable:!0}}}catch(t){e.error=t,e.hasError=!0}finally{LD(e)}}}const BD=["parse binary","parse json"],WD=["decompression failed","unsupported response encoding","unsupported content type","protocol error: promised"],HD=new Set([1,4,10,14]),qD=new Set(["AbortError","TimeoutError"]),zD=["ECONN","ENOT","ETIMEDOUT","EPIPE","EAI_","EHOST","ENET","ERR_HTTP2","ERR_SSL","ERR_TLS","UND_ERR","CERT_","DEPTH_ZERO_SELF_SIGNED_CERT","SELF_SIGNED_CERT","UNABLE_TO_"];function GD(e,t){return t.some((t=>e.startsWith(t)))}function VD(e){if(e instanceof Error&&qD.has(e.name))return!0;const t=function(e){if("object"==typeof e&&null!==e&&"code"in e)return"string"==typeof e.code?e.code:void 0}(e);return void 0!==t&&GD(t,zD)}function KD(e){const t=function(e){if(e instanceof Error&&"ConnectError"===e.name&&"code"in e&&"number"==typeof e.code&&"rawMessage"in e&&"string"==typeof e.rawMessage)return{code:e.code,text:e.rawMessage,cause:e.cause}}(e);if(void 0===t)return VD(e)?"transport":"other";const{code:r,text:n,cause:o}=t;return GD(n,BD)?"reply_schema":GD(n,WD)?"reply_encoding":n.startsWith("http/2 stream closed with error code")||HD.has(r)||VD(o)?"transport":"other"}var JD=r("../proto/dist/generated/aiserver/v1/dashboard_pb.js");const ZD=BigInt(0),XD=BigInt(8),QD=BigInt(16),YD=BigInt(65535);function eO(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch{return}}function tO(e){let t=e.trim().replace(/\.+$/,"").toLowerCase();if(t.startsWith("[")){const e=t.indexOf("]");-1!==e&&(t=t.slice(1,e))}else if(t.split(":").length-1==1){const e=t.lastIndexOf(":"),r=t.slice(e+1);Array.from(r).every((e=>/\d/.test(e)))&&(t=t.slice(0,e))}return t}function rO(e){const t=e.split(".");if(4!==t.length)return;let r=ZD;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<>QD&YD)),t.push(Number(o.value&YD))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function oO(e){return rO(e)??function(e){const t=tO(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=nO(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<7?void 0:{version:6,value:[...n,...new Array(8-s).fill(0),...o].reduce(((e,t)=>e<i)return!1;const a=BigInt(i-s);return o.value>>a==n.value>>a}(r,n);if(n.startsWith("*.")){const e=n.slice(2);return r===e||r.endsWith(`.${e}`)}return r===n}function iO(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}function aO(e,t){if(iO(e,t))return!0;if(e.includes("://")){let r,n;try{r=new URL(e),n=new URL(t)}catch{return!1}if(""!==r.username||""!==r.password||""!==n.username||""!==n.password||r.protocol!==n.protocol||r.port!==n.port)return!1;const o=tO(r.hostname);return!!sO(tO(n.hostname),o)&&iO(`${r.pathname}${r.search}`,`${n.pathname}${n.search}`)}const r=function(e){const t=function(e){const t=e.trim(),r=t.indexOf("["),n=t.indexOf("]");if(-1!==r&&n>r){const e=t.slice(r+1,n);if(t.slice(n+1).startsWith("("))return`${t.slice(0,r)}${e}`}return t}(e).trim();if(0===t.length)return;const r=t.lastIndexOf("/");if(!t.includes("://")&&r>0&&/^\d+$/.test(t.slice(r+1).trim())){const e=tO(t.slice(0,r));if(e.length>0)return`${e}/${t.slice(r+1).trim()}`}const n=eO(t);if(n)return tO(n.hostname);let o=t;const s=o.indexOf("://");-1!==s&&(o=o.slice(s+3));const i=o.indexOf("/");-1!==i&&(o=o.slice(0,i));const a=tO(function(e){if(e.startsWith("[")){const t=e.indexOf("]");return-1!==t?e.slice(1,t):e}const t=e.split(":");return 2===t.length&&Array.from(t[1]??"").every((e=>/\d/.test(e)))?t[0]:e}(o));if(0!==a.length){if(a.startsWith("*.")){const e=a.slice(2);if(0===e.length||e.includes("*")||e.includes("?"))return;return a}if(!a.includes("*")&&!a.includes("?"))return a}}(e),n=function(e){const t=eO(e);if(t)return tO(t.hostname);const r=tO(e);return r.length>0?r:void 0}(t);return!(!r||!n)&&sO(n,r)}async function cO(e){try{return await e.current()}catch{return}}function lO(e){try{const t=new URL(e);return`${t.protocol}//${t.host}${t.pathname}`}catch{return}}function uO({failOpenWhenEmpty:e,server:t,settings:r}){if(!0!==r?.allowedMcpConfiguration?.requireMcpServersInTeamNetworkAllowlist||void 0===t.url)return{blocked:!1};const n=function(e){return!0===e.cloudAgentMcpAllowlistApplied&&!1===e.mirrorSandboxAllowlistForEgress?e.cloudAgentEgressAllowlist??[]:e.networkAllowlist??[]}(r).map((e=>e.trim())).filter((e=>e.length>0));return 0===n.length&&e||Jv(t.url,n)?{blocked:!1}:{blocked:!0,reason:"teamNetworkAllowlist",message:"Not on the team network allowlist"}}function dO(e){const t=e?.trim();return t&&t.length>0?t:void 0}function hO(e,t,r){if(!0===r?.useCorePolicy)return!function(e,t){if(void 0===t)return!0;if(!0===t.disableAll)return!1;if(SC(e))return!0;if(EC(e,t.offMcpServerRules))return!1;const r=t.allowedMcpServers??[];return 0===r.length&&!0!==t.allowUserOverrideMcpServers||!!function(e,t){return t.length>0&&function(e,t){return t.some((t=>{const r=kC(t.command),n=_C(t.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==e.command&&(0,Ob.mD)(r,e.command),s=void 0===n||void 0!==e.url&&(0,Ob.vc)(n,e.url);return o&&s}))}(e,t)}(e,r)||!0===t.allowUserOverrideMcpServers&&!CC(e,t.deniedMcpServers)}(e,t);if(void 0===t)return!1;if(!0===t.disableAll)return!0;const n=t.allowedMcpServers;return 0!==n.length&&!n.some((t=>function(e,t){const r=dO(e.command),n=dO(e.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==t.command&&function(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}(r,t.command),s=void 0===n||void 0!==t.url&&aO(n,t.url);return o&&s}(t,e)))}class pO{constructor(e,t={}){this.dashboardClient=e,this.options=t}getTeamAdminSettings(){return this.dashboardClient.getTeamAdminSettingsOrEmptyIfNotInTeam(new JD.Byz(!0===this.options.supportsHostMcpBridgeExemption?{supportsHostMcpBridgeExemption:!0}:{}))}getTeamRepos(){return this.dashboardClient.getTeamReposOrEmptyIfNotInTeam(new JD.aYW({}))}}function fO(e,t){if("workspace"!==e)return[];const r=[],n=new Set;for(const e of t??[]){const t=e.trim();0===t.length||n.has(t)||(n.add(t),r.push(t))}return r}class mO{constructor(e){this.fetch=e}get(){const e=this.cached,t=void 0===e?1/0:Date.now()-e.fetchedAt;return void 0===e||t>6e5?(this.cached=void 0,this.refresh()):(t>3e5&&this.refresh().catch((()=>{})),Promise.resolve(e.value))}invalidate(){this.cached=void 0,this.inFlight=void 0}refresh(){if(void 0===this.inFlight){const e=this.fetch().then((t=>(this.inFlight!==e||void 0===t&&void 0!==this.cached||(this.cached={value:t,fetchedAt:Date.now()}),t))).finally((()=>{this.inFlight===e&&(this.inFlight=void 0)}));this.inFlight=e}return this.inFlight}}class gO{constructor(e,t,r={}){this.teamAdminSettingsProvider=e,this.defaultAllowlistProvider=t,this.options=r,this.lastFetchSucceeded=!0,this.lastFetchFailure="other",this.settingsGeneration=0,this.lastFetchedGeneration=0,this.settings=new mO((()=>this.fetchSettings())),this.droppedReplies=new WeakSet,this.hostMcpBridgeClients=new WeakSet,this.mcpServerByClient=new WeakMap,this.teamRepos=new mO((()=>this.teamAdminSettingsProvider.getTeamRepos())),this.defaultAllowlist=new mO((()=>this.fetchDefaultAllowlist())),this.getTeamAdminSettings(),this.prefetchTeamRepos()}async prefetchTeamRepos(){try{await this.teamRepos.get()}catch{}}invalidateCache(){this.settingsGeneration+=1,this.settings.invalidate(),!0!==this.options.preserveTeamReposOnInvalidate&&this.teamRepos.invalidate(),this.defaultAllowlist.invalidate()}invalidateTeamRepos(){this.teamRepos.invalidate()}async refreshTeamAdminSettings(){try{await this.settings.refresh()}catch{}}async fetchSettings(){const{fetchIdentity:e}=this.options;if(void 0!==e)return this.fetchSettingsFor(e);const t=this.settingsGeneration;try{const e=await this.teamAdminSettingsProvider.getTeamAdminSettings();return this.lastFetchSucceeded=!0,t>=this.lastFetchedGeneration&&(this.lastFetchedSettings=e,this.lastFetchedGeneration=t),e}catch(e){throw this.lastFetchSucceeded=!1,this.lastFetchFailure=KD(e),e}}async fetchSettingsFor(e){const t=await cO(e),r=this.settingsGeneration;if(void 0===t)throw this.lastFetchSucceeded=!1,this.lastFetchFailure="other",new Error("No one is named whose team settings a fetch would read");try{const e=await this.teamAdminSettingsProvider.getTeamAdminSettings();return void 0!==e&&this.droppedReplies.delete(e),this.isSentFor(e,t)?(this.lastFetchSucceeded=!0,r>=this.lastFetchedGeneration&&(this.lastFetchedSettings=e,this.lastFetchedGeneration=r),e):e}catch(e){throw this.lastFetchSucceeded=!1,this.lastFetchFailure=KD(e),e}}getTeamAdminSettings(){const{fetchIdentity:e}=this.options;return void 0!==e?this.getTeamAdminSettingsFor(e):this.settings.get().catch((()=>{}))}async getTeamAdminSettingsFor(e){const t=await this.settings.get().catch((()=>{})),r=await cO(e);if(void 0===t)return void(this.isSentFor(this.lastFetchedSettings,r)||(this.settingsGeneration+=1));if(void 0===r)return this.answerAsFailedRead();if(this.isSentFor(t,r))return t;let n=t,o=r;const s=await this.settings.get().catch((()=>{}));if(s!==t){if(void 0===s)return this.answerAsFailedRead();if(this.isSentFor(s,r))return s;if(o=await cO(e),void 0===o)return this.answerAsFailedRead();if(this.isSentFor(s,o))return s;n=s}this.droppedReplies.has(n)||(this.droppedReplies.add(n),this.settingsGeneration+=1,this.settings.invalidate());const i=await this.settings.get().catch((()=>{}));return void 0!==i?this.isSentFor(i,r)||this.isSentFor(i,o)||this.isSentFor(i,await cO(e))?i:this.answerAsFailedRead():void 0}answerAsFailedRead(){this.settingsGeneration+=1,this.lastFetchSucceeded=!1,this.lastFetchFailure="other"}isSentFor(e,t){return void 0!==e&&void 0!==t&&this.options.fetchIdentity?.sentFor(e)===t}async getDotCursorProtection(){const e=await this.getTeamAdminSettings();return e?.dotCursorProtection??!0}async getShouldBlockMcp(){const e=await this.getTeamAdminSettings();return!(!e?.autoRunControls?.enabled||!e?.autoRunControls?.disableMcpAutoRun)}async getDeleteFileProtection(){const e=await this.getTeamAdminSettings();return!(!e?.autoRunControls?.enabled||!e?.autoRunControls?.deleteFileProtection)}async getIsHeadlessDisabled(){return"disabled"===(await this.getHeadlessCliPolicy()).kind}async getHeadlessCliPolicy(){const e=await this.getTeamAdminSettings();return void 0!==e||this.lastFetchSucceeded?!0===e?.cliSettings?.disableHeadless?{kind:"disabled"}:{kind:"enabled"}:{kind:"unavailable"}}async getMcpServerBlockInfo(e){const t=await this.getTeamAdminSettings(),r=t?.allowedMcpConfiguration,n=await this.isMcpSettingsOverhaulEnabled({disableExposureLog:!0});if(!0===r?.disableAll)return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};if(this.isHostMcpBridge(t,e))return{blocked:!1,hostMcpBridge:!0};if(EC(e,r?.offMcpServerRules))return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};if(n){if(hO(e,r,{useCorePolicy:!0}))return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};const n=await this.getMcpNetworkControlsConfig(e),o=void 0===e.url?{allowed:!0}:(0,Ob.ME)(e.url,n);if(!o.allowed)return{blocked:!0,reason:"teamNetworkAllowlist",message:o.message};const s=uO({failOpenWhenEmpty:!1,server:e,settings:t});if(s.blocked)return s}if(!n){const r=function({isMcpAccessNetworkAllowlistEnabled:e,server:t,settings:r}){return e&&!0===r?.allowedMcpConfiguration?.requireMcpServersInTeamNetworkAllowlist?uO({failOpenWhenEmpty:!0,server:t,settings:r}):{blocked:!1}}({isMcpAccessNetworkAllowlistEnabled:await this.isMcpAccessNetworkAllowlistEnabled(),server:e,settings:t});if(r.blocked)return r}return void 0!==t||this.lastFetchSucceeded?{blocked:!1}:{blocked:!1,settingsUnavailable:!0}}async getManagedSlackWorkspaceLists(){const e=await this.getTeamAdminSettings()??this.lastFetchedSettings;return void 0===e?[]:function(e){return e.memberSlackManagedWorkspacesUnreadable?"unconfirmed":e.memberSlackManagedWorkspaces.map((e=>e.slackTeamIds)).filter((e=>e.length>0))}(e)}async getMcpNetworkControlsConfig(e){const t=await this.getTeamAdminSettings(),r=t?.allowedMcpConfiguration;if(await this.isMcpSettingsOverhaulEnabled()&&(void 0===e||!this.isHostMcpBridge(t,e))){const n="win32"===process.platform&&await this.isWin32UserExtensionStdioUnsandboxEnabled();return(0,Ob._N)({allowedMcpConfiguration:r,server:e,localAgentNetworkAllowlist:t?.networkAllowlist,blockMessage:"Not on the team network allowlist",aggregateManagedServerNetworkAllowlists:!1,stdioPlatform:process.platform,unsandboxUserExtensionStdio:n})}return{enabled:!1,localAgentNetworkAllowlist:t?.networkAllowlist,blockMessage:"Not on the team network allowlist"}}isHostMcpBridge(e,t){const r=this.options.hostMcpBridgeUrls;if(!0!==e?.cloudAgentMcpAllowlistApplied||void 0===r||void 0!==t.command||void 0===t.url)return!1;const n=lO(t.url);return void 0!==n&&r.some((e=>lO(e)===n))}recordHostMcpBridgeClient(e){this.hostMcpBridgeClients.add(e)}async isHostMcpBridgeClient(e){if(!this.hostMcpBridgeClients.has(e))return!1;const t=await this.getTeamAdminSettings();return!0===t?.cloudAgentMcpAllowlistApplied&&!0!==t.allowedMcpConfiguration?.disableAll}recordMcpServerClient(e,t){this.mcpServerByClient.set(e,t)}async getMcpAdminToolLimit(e){if(await this.isHostMcpBridgeClient(e))return{kind:"none"};const t=this.mcpServerByClient.get(e);if(void 0===t)return{kind:"unknown_server"};const r=!0===this.options.mcpAdminToolLimitSurvivesFailedRead;let n=await this.getTeamAdminSettings();if(void 0===n&&!this.lastFetchSucceeded&&r&&(n=await this.getTeamAdminSettings()),void 0===n){if(this.lastFetchSucceeded)return{kind:"none"};if(!r)return{kind:"settings_unavailable"};const e=this.lastFetchFailure,t=this.lastFetchedGeneration===this.settingsGeneration?this.lastFetchedSettings:void 0;if(void 0===t)return{kind:"settings_unavailable",failure:e,noLimitApplies:!0};n=t}const o=function(e,t){const r=e?.find((e=>(0,Ob.rM)(e,t)));if(void 0!==r)return Lb({mode:r.toolAllowlistMode,tools:r.toolAllowlist})}(n.allowedMcpConfiguration?.allowedMcpServers,t);return void 0===o?{kind:"none"}:{kind:"limit",policy:o}}async isServerBlocked(e){return(await this.getMcpServerBlockInfo(e)).blocked}async getAutoRunControls(){const e=await this.getTeamAdminSettings();if(e?.autoRunControls?.enabled)return{enabled:e.autoRunControls.enabled,allowed:e.autoRunControls.allowed??[],blocked:e.autoRunControls.blocked??[],enableAllowlistMode:e.autoRunControls.enableAllowlistMode??!0,enableRunEverything:e.autoRunControls.enableRunEverything??!1,enableSmartAuto:e.autoRunControls.enableSmartAuto??!0,mcpToolAllowlist:e.autoRunControls.mcpToolAllowlist??[]}}async isReadControlEnabled(){try{return await(this.options.isReadControlEnabled?.())??!0}catch{return!1}}async isDenylistEnforcementKilled(){try{return!0===await(this.options.isAdminCommandDenylistEnforcementKilled?.())}catch{return!1}}async getAdminCommandDenylist(){if(await this.isDenylistEnforcementKilled())return{rules:[]};const e=await this.getTeamAdminSettings();return{rules:e?.autoRunControls?.adminCommandDenylist?.rules??[]}}async isMcpSettingsOverhaulEnabled(e){const t=this.options.isMcpSettingsOverhaulEnabled?.(e);return void 0!==t&&await t}async isWin32UserExtensionStdioUnsandboxEnabled(){try{const e=this.options.isWin32UserExtensionStdioUnsandboxEnabled?.();return void 0!==e&&await e}catch{return!1}}async getMcpToolControls(){const e=await this.getTeamAdminSettings(),t=e?.allowedMcpConfiguration;if(void 0===t)return;const r=function({autoRunControls:e,allowedMcpServers:t}){const r=!0===e?.enabled?e.mcpToolAllowlist??[]:[],n=function(e){return(e??[]).flatMap((e=>{const t=void 0===e.name?"":Fb(e.name);if(0===t.length)return[];const r=Lb({mode:e.toolAllowlistMode,tools:e.toolAllowlist});return[{name:t,policy:r,flattened:Ub(t,r)}]}))}(t);return{tools:(o=[...n.flatMap((e=>[...e.flattened])),...r],[...new Set(o)]),policies:n.map((e=>({name:e.name,policy:e.policy})))};var o}({autoRunControls:e?.autoRunControls,allowedMcpServers:t?.allowedMcpServers});return r.policies.length>0||r.tools.length>0?{enabled:!0,mcpToolAllowlist:r.tools,allowUserOverride:t?.allowUserOverrideMcpServers??!1,serverPolicies:r.policies}:void 0}async getNetworkAccessControls(){const e=await this.getTeamAdminSettings();return void 0!==e||this.lastFetchSucceeded?{allowlist:e?.networkAllowlist??[],denylist:e?.networkDenylist??[],available:!0}:{allowlist:[],denylist:[],available:!1}}async getSandboxingControls(){const e=await this.getTeamAdminSettings(),t=e?.autoRunControls?.sandboxingControls,r=(n=t?.sandboxReadBoundary,n===JD.h0i.WORKSPACE?"workspace":"system");var n;return{sandboxingDisabled:t?.sandboxing===JD.faf.DISABLED,networkingDisabled:t?.sandboxNetworking===JD._mX.ALWAYS_DISABLED,gitDisabled:t?.sandboxGit===JD.i24.ALWAYS_DISABLED,readBoundary:r,readAllowlistPaths:fO(r,t?.sandboxReadAllowlistPaths),allowUserOverrideReadAllowlist:!1!==t?.allowUserOverrideSandboxReadAllowlist}}async isAttributionDisabledByAdmin(){const e=await this.getTeamAdminSettings();return void 0===e&&!this.lastFetchSucceeded||(e?.attributionControls?.disableAttribution??!1)}async isComputerUseDisabledByAdmin(){const e=await this.getTeamAdminSettings();return void 0!==e?!1===e.computerUse:this.lastFetchedGeneration!==this.settingsGeneration||void 0===this.lastFetchedSettings&&!this.lastFetchSucceeded||!1===this.lastFetchedSettings?.computerUse}getDefaultNetworkAllowlist(){return this.defaultAllowlist.get().catch((()=>({allowlist:[],available:!1})))}async fetchDefaultAllowlist(){return this.defaultAllowlistProvider?{allowlist:await this.defaultAllowlistProvider.getDefaultNetworkAllowlist(),available:!0}:{allowlist:[],available:!0}}getTeamRepos(){return this.teamRepos.get()}async isMcpAccessNetworkAllowlistEnabled(){return await(this.options.isMcpAccessNetworkAllowlistEnabled?.())??!1}}const wO=new _y,yO={async resolveWorkspaceState(e){const t=e.workingDirectory??e.projectRoot??e.workspaceRoots?.[0],r=e.projectRoot??(void 0!==t?await Ya((0,y.q6)(),wO,t)??t:void 0),n=e.workspaceRoots??(void 0!==r?[r]:void 0!==t?[t]:[]);return{workingDirectory:t,projectRoot:r,projectDirectory:e.projectDirectory??(void 0!==r?_o(r):void 0),workspaceRoots:n,createdAt:new Date}}},vO=(0,l.h)("ControlledConversationActionManager");class bO{get signal(){return this.abortController.signal}get abortRequested(){return this.abortCalled}constructor(){this.abortCallbacks=[],this.abortController=new AbortController,this.acceptsActions=!0,this.disposed=!1,this.abortStarted=!1,this.abortCalled=!1,this.runActive=!1,this.unprocessedUserMessages=[],this.clientStream=(0,h.Jt)()}addAbortCallback(e){this.abortCallbacks.push(e)}abort(e,t){if(this.abortCalled=!0,this.abortController.signal.aborted||this.abortStarted)return;const r=t?.interruptedPendingToolCallResolutions;if(this.abortStarted=!0,!this.runActive){this.abortController.abort(e);for(const e of this.abortCallbacks)e();return void(this.abortCallbacks.length=0)}const n=this.abortController,o=[...this.abortCallbacks];this.abortCallbacks.length=0,this.submitConversationAction(new i.QFf({action:{case:"cancelAction",value:new i.TTG({reason:e,interruptedPendingToolCallResolutions:r})}})).catch((()=>{})).finally((()=>{n.abort(e);for(const e of o)e();if(this.abortController===n){const e=[...this.abortCallbacks];this.abortCallbacks.length=0;for(const t of e)t()}}))}async submitConversationAction(e){if(!this.acceptsActions)throw new h.W2("ControlledConversationActionManager is not accepting actions");if("userMessageAction"===e.action.case){const t=e.action.value.userMessage;t&&this.unprocessedUserMessages.push(t)}await this.clientStream.write(e)}queueFollowUpUserMessage(e){if(this.disposed||this.abortStarted)throw new h.W2("ControlledConversationActionManager run was aborted or disposed");this.unprocessedUserMessages.push(e)}async enqueueReplayableConversationAction(e){if("asyncAskQuestionCompletionAction"!==e.action.case)throw new TypeError("Only asyncAskQuestionCompletionAction can use enqueue acknowledgement");if(!this.acceptsActions)throw new h.W2("ControlledConversationActionManager is not accepting actions");this.clientStream.write(e).catch((()=>{}))}markMessageAsProcessed(e){this.unprocessedUserMessages=this.unprocessedUserMessages.filter((t=>t.messageId!==e.messageId))}requeueMessage(e){this.unprocessedUserMessages.some((t=>t.messageId===e.messageId))||this.unprocessedUserMessages.unshift(e)}getUnprocessedUserMessages(){return[...this.unprocessedUserMessages]}hasUnprocessedMessages(){return this.unprocessedUserMessages.length>0}close(){this.acceptsActions=!1,this.clientStream.close()}reopen(){this.disposed||this.acceptsActions||this.resetStream()}resetStream(){if(this.disposed)throw new h.W2("ControlledConversationActionManager disposed");this.acceptsActions=!1,this.clientStream.close(),this.clientStream=(0,h.Jt)(),this.acceptsActions=!0,this.abortController=new AbortController,this.abortStarted=!1;for(const e of this.unprocessedUserMessages)this.clientStream.write(new i.QFf({action:{case:"userMessageAction",value:new i.Vtf({userMessage:e})}})).catch((()=>{}))}async run(e,t){const r=this.clientStream;this.runActive=!0;try{for await(const n of r)try{await t.write(n)}catch(t){vO.error(e,"Error writing conversation action",t)}}catch(e){if(!(e instanceof h.W2))throw e}finally{this.clientStream===r&&(this.runActive=!1)}}dispose(){this.disposed||(this.disposed=!0,this.abortCallbacks.length=0,this.acceptsActions=!1,this.clientStream.throw(new h.W2("ControlledConversationActionManager disposed")))}}var SO=r("../cursor-sdk-local-runtime/dist/utils/logger.js"),kO=r("../agent-kv/dist/agent-store.js");const _O="x-blob-encryption-key";function CO(e,t){const r={...t};return void 0!==r[_O]||(0,kO.TU)(e)&&(r[_O]=e),r}const EO=new Map;function xO(e){if("userMessageAction"===e.action.case)return e.action.value.userMessage?.text}function PO(e,t,r){const n=e.runOptions?.requestedModel;return{conversationId:e.conversationId,generationId:e.conversationId,model:n?.modelId??"unknown",modelId:n?.modelId,modelParams:n?.parameters.map((e=>({id:e.id,value:e.value}))),loopCount:t,promptText:r}}function RO(e){return new i.QFf({action:{case:"userMessageAction",value:new i.Vtf({userMessage:new i.RGk({text:e})})}})}function IO(e){return e instanceof DOMException&&"AbortError"===e.name||e instanceof Error&&("AbortError"===e.name||"The operation was aborted"===e.message)}function TO(e){e?.catch((e=>{SO.Jz.warn("[agent-session-runner] fire-and-forget hook failed:",e)}))}class AO{constructor(e,t,r){this.inner=e,this.getToken=t,this.restMcpHost=r}async getDefinitions(e,t=!0){const r=await this.inner.getDefinitions(e,t);return Promise.all(r.map((async e=>{const t=await async function(e,t,r){if(!("url"in e)||!e.url||void 0===sb(e.url,r)||Object.keys(e.headers??{}).some((e=>e.toLowerCase()===ob)))return e;const n=await t();return void 0===n||0===n.length?e:{...e,headers:{...e.headers??{},[ob]:`Bearer ${n}`}}}(e.serverConfig,this.getToken,this.restMcpHost);return t===e.serverConfig?e:{...e,serverConfig:t}})))}clearCache(){this.inner.clearCache?.()}}const $O=new Set(["mcp.slack.com","setup.shopify.com"]);class MO{constructor(e,t){this.inner=e,this.resolver=t}async getDefinitions(e,t=!0){const r=await this.inner.getDefinitions(e,t);return Promise.all(r.map((async e=>{const t=await async function(e,t){if(!("url"in e)||!e.url)return e;const r=await async function(e,t,r,n=fetch){let o;try{o=new URL(e).hostname}catch{return t}const s=void 0!==sb(e,r.restMcpHost);if(!$O.has(o)&&!s)return t;let i=await r.resolve(e);if(!i&&s){const t=(await cx(e,n))?.clientId;void 0!==t&&(i={CLIENT_ID:t})}return i?t?void 0===ix(t.CLIENT_ID)?{...i,...t,CLIENT_ID:i.CLIENT_ID}:{...i,...t}:i:t}(e.url,e.auth,t);return r===e.auth?e:{...e,auth:r}}(e.serverConfig,this.resolver);return t===e.serverConfig?e:{...e,serverConfig:t}})))}clearCache(){this.inner.clearCache?.()}}class DO{constructor(e,t){this.storage=e,this.prefix=t}async loadTokens(e){return this.storage.loadTokens(this.prefix+e)}async saveTokens(e,t){return this.storage.saveTokens(this.prefix+e,t)}async loadClientInformation(e){return this.storage.loadClientInformation(this.prefix+e)}async saveClientInformation(e,t){return this.storage.saveClientInformation(this.prefix+e,t)}}class OO{constructor(e,t){this.storage=e,this.prefix=t}async isServerApproved(e,t,r){return this.storage.isServerApproved(this.prefix+e,t,r)}}class FO{constructor(e){this.higherPrecedenceSources=e}async load(e,t,r,n,o){for(const r of this.higherPrecedenceSources){const n=(await r.getDefinitions(e)).find((e=>e.identifier===t));if(void 0!==n)throw new TC(t,n.configPath??"another config")}return await o(e,r)}}class NO extends nI{constructor(e,t){super(e),this.shadowedClientsClosed=t}async closeAllClients(){await Promise.all([super.closeAllClients(),this.shadowedClientsClosed])}}async function LO(e){try{await(e.close?.())}catch{}}class jO{constructor(e){this.loaders=e}async load(e,t=!0){const r=await Promise.allSettled(this.loaders.map((({loader:r})=>r.load(e,t)))),n=r.find((e=>"rejected"===e.status));if(n)throw await Promise.allSettled(r.flatMap((e=>"fulfilled"===e.status?[e.value.closeAllClients()]:[]))),n.reason;const o=r.filter((e=>"fulfilled"===e.status)).map((e=>e.value)),s={},i=[];for(let e=0;e{})))}async loadClient(e,t,r=!1){for(const{loader:n,prefix:o}of this.loaders)if(t.startsWith(o)){t=t.slice(o.length);try{return await n.loadClient(e,t,r)}catch(e){if(e instanceof Error&&e.message.includes("not found in config"))continue;throw e}}throw new Error(`MCP client "${t}" not found in config`)}clearClient(e){for(const{loader:t,prefix:r}of this.loaders){if(!e.startsWith(r))continue;const n=e.slice(r.length);t.clearClient?.(n)}}clearAllMcpCaches(){for(const{loader:e}of this.loaders)e.clearAllMcpCaches?.()}}class UO{constructor(e,t,r,n,i=!1,a,c,l=s.join((0,o.homedir)(),".cursor","mcp.json"),u,d,h){const p=Array.isArray(e)?e:[e],f={}.location,m=[];"enterprise"===f?.source&&m.push({path:f.path,prefix:"enterprise-",scope:"enterprise"});for(let e=0;e({prefix:t,scope:r,fileSource:new bI(e,"enterprise"===r||"env"===r?EE:void 0)}))),y=[];for(const{prefix:e,scope:o,fileSource:s}of w){const l=i?"":e,d=new DO(t,l),p=new OO(n,l),f=w.flatMap((e=>{return t=e.scope,r=o,xE.indexOf(t)0?[new FO(f)]:[]],g=new SI(u?new MO(s,u):s,d,m,{authRedirectUrlGenerator:a,isLinkSharedPaymentTokenLogRedactionEnabled:h});y.push({prefix:l,loader:g})}this.loader=new jO(y)}static init(e,t,r,n=!1,o,i={}){const a=new AI(s.join(r,"mcp-auth.json"));(async function(e){await(0,Co.rm)(s.join(e,"mcp-cache.json"),{force:!0})})(r).catch((()=>{}));const c=n?{isServerApproved:()=>Promise.resolve(!0)}:new MC(s.join(r,"mcp-approvals.json"),t);return new UO(t,a,e,c,!0,void 0,o,void 0,i.defaultAuthResolver,void 0,i.isLinkSharedPaymentTokenLogRedactionEnabled)}async load(e,t=!0){return this.loader.load(e,t)}async loadClient(e,t,r=!1){return this.loader.loadClient(e,t,r)}clearClient(e){this.loader.clearClient(e)}clearAllMcpCaches(){this.loader.clearAllMcpCaches()}}const BO="cursor-plugins/local";function WO(e){var t;if(e)for(const r of e)if("object"==typeof(t=r)&&null!==t&&t.kind===BO)return r}class HO extends rI{constructor(e){super(e),this.runtimeManager=e,this.disposed=!1}async dispose(){this.disposed||(this.disposed=!0,await this.runtimeManager.closeAllClients())}}class qO{constructor(e){this.storagePath=e}async isServerDisabled(e){try{const t=await(0,Co.readFile)(this.storagePath,"utf8"),r=JSON.parse(t);return Array.isArray(r)?r.includes(e):(await this.writeDisabledServers([]),!1)}catch(e){if("object"==typeof e&&null!==e&&"code"in e&&"ENOENT"===e.code)return!1;throw e}}async writeDisabledServers(e){await(0,Co.mkdir)((0,s.dirname)(this.storagePath),{recursive:!0}),await(0,Co.writeFile)(this.storagePath,JSON.stringify(e,null,2))}}class zO{constructor(e,t){this.pluginMcpService=e,this.importThirdPartyPlugins=t}async getDefinitions(){let e;try{e=await this.pluginMcpService.getPluginMcpServers()}catch(e){return SO.Jz.warn("[cursor-config-mcp] Failed to enumerate plugin MCP servers:",e),[]}const t=[];for(const r of e){if(!this.importThirdPartyPlugins&&ZO(r))continue;const e=xI(r);e?t.push({identifier:r.identifier,authStorageKey:r.identifier,serverConfig:e,configPath:"",source:"plugin",metadata:{identifier:r.identifier,pluginName:r.pluginName,pluginSource:r.pluginSource}}):SO.Jz.warn("[cursor-config-mcp] Failed to initialize plugin MCP client:",{identifier:r.identifier,pluginName:r.pluginName,pluginSource:r.pluginSource,result:"invalid-config",errorMessage:"pluginMcpDescriptorToServerConfig returned undefined"})}return t}}class GO{constructor(e){this.servers=e}async getDefinitions(){return Object.entries(this.servers).map((([e,t])=>({identifier:e,authStorageKey:`inline:${e}`,serverConfig:JO(e,t),source:"inline",metadata:{source:"cursor-sdk"}})))}}function VO(e={}){const t=e.teamSettingsService??{getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getAdminCommandDenylist:async()=>({rules:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}},r=e.ignoreApprovals??!1,n=e.importThirdPartyPlugins??!1,i=void 0===e.isLinkSharedPaymentTokenLogRedactionEnabled?{}:{isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled},a=e.restMcpCursorAuthTokenSupplier,c=e=>void 0===a?e:new AO(e,a,"api.cursor.com");return{async createLease(a){const l=a.workspaceState,u=l.projectRoot??l.workingDirectory,d=l.projectDirectory;if(!u||!d)return new tI;const h=new qO((0,s.join)(d,"mcp-disabled.json")),p=function(e){const{teamSettingsService:t,projectRoot:r,projectDirectory:n,ignoreApprovals:i,disabledStore:a,includeProjectMcp:c,includeUserMcp:l,isLinkSharedPaymentTokenLogRedactionEnabled:u}=e;if(c&&l)return UO.init(t,r,n,i,a,{isLinkSharedPaymentTokenLogRedactionEnabled:u});if(!c&&!l)return;const d=new AI((0,s.join)(n,"mcp-auth.json")),h=i?{isServerApproved:()=>Promise.resolve(!0)}:new MC((0,s.join)(n,"mcp-approvals.json"),r),p=[new zC,new $C(h),new CI(t),new AC(a)],f=[];return c&&f.push({prefix:"",loader:new EI((0,s.join)(r,".cursor","mcp.json"),d,p,{isLinkSharedPaymentTokenLogRedactionEnabled:u})}),l&&f.push({prefix:"",loader:new EI((0,s.join)((0,o.homedir)(),".cursor","mcp.json"),d,p,{isLinkSharedPaymentTokenLogRedactionEnabled:u})}),KO(f)}({teamSettingsService:t,projectRoot:u,projectDirectory:d,ignoreApprovals:r,disabledStore:h,includeProjectMcp:e.includeProjectMcp??!0,includeUserMcp:e.includeUserMcp??!0,isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled}),f=[],m=e.inlineMcpServers??{};if(Object.keys(m).length>0){const e=new AI((0,s.join)(d,"mcp-auth.json")),r=[new zC,new CI(t)];f.push({prefix:"",loader:new SI(c(new GO(m)),e,r,i)})}const g=WO(a.services.pluginBootstrapOutputs);if(g&&(e.includePluginMcp??1)){const e=new MC((0,s.join)(d,"mcp-approvals.json"),u),o=new AI((0,s.join)(d,"mcp-auth.json")),a=[new zC];r||a.push(new $C(e)),a.push(new CI(t),new AC(h));const l=new ND(g.pluginsService),p=new SI(c(new zO(l,n)),o,a,i);f.push({prefix:"",loader:p})}if(p&&f.push({prefix:"",loader:p}),0===f.length)return new tI;const w=KO(f),v=await w.load(e.initializationCtx??(0,y.q6)(),e.cache);return new HO(v)}}}function KO(e){return 1===e.length?e[0].loader:new jO(e)}function JO(e,t){if("command"in t){if(void 0!==t.type&&"stdio"!==t.type)throw new Error(`Unsupported MCP server type "${String(t.type)}" for "${e}"`);return{command:t.command,args:t.args?[...t.args]:void 0,env:t.env,cwd:t.cwd,startupTimeoutSec:t.startupTimeoutSec}}if("url"in t){if(void 0!==t.type&&"http"!==t.type&&"sse"!==t.type)throw new Error(`Unsupported MCP server type "${String(t.type)}" for "${e}"`);const r={url:t.url,headers:t.headers,auth:t.auth?{CLIENT_ID:t.auth.CLIENT_ID,CLIENT_SECRET:t.auth.CLIENT_SECRET,scopes:t.auth.scopes?[...t.auth.scopes]:void 0}:void 0};return"sse"===t.type?{...r,type:"sse"}:r}throw new Error(`Invalid inline MCP server config for "${e}"`)}function ZO(e){return"claude-plugin"===e.pluginSource}const XO=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass"];function QO(e){let t=e.trim();t.startsWith("&")&&(t=t.slice(1).trim());const r=t.charAt(0);if("'"!==r&&'"'!==r)return t.split(/\s/)[0]??"";let n="";for(let e=1;e0)return{...n,followup_message:n.reason.trim()};if(!sF(t))return n;const o=aF(e),s=cF(o,r)?o:void 0,i=void 0!==s?{...n,...s}:n;return"block"===i.decision&&"string"==typeof i.reason&&i.reason.trim().length>0?{...i,followup_message:i.reason.trim()}:n}const uF=e=>{const t=[];return Rd(e)?Td(!0):(t.push("Expected an object"),Td(!1,t))},dF=e=>{const t=[],r=uF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny","ask"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("Invalid user_message value. Expected a string if provided"),void 0!==e.agent_message&&"string"!=typeof e.agent_message&&t.push("Invalid agent_message value. Expected a string if provided"),Td(0===t.length,t)};function hF(e){const t=e.modelId,r=e.modelParams;return{...void 0!==t&&{model_id:t},...void 0!==r&&r.length>0?{model_params:r.map((e=>({id:e.id,value:e.value})))}:{}}}const pF=new Set([xd.sessionStart,xd.beforeSubmitPrompt,xd.preToolUse,xd.postToolUse,xd.postToolUseFailure]);function fF(e){return"prompt"===e.type}function mF(e){return"command"===e.type||void 0===e.type}const gF={[xd.beforeShellExecution]:dF,[xd.beforeMCPExecution]:dF,[xd.afterShellExecution]:e=>{const t=uF(e);return t.isValid,t},[xd.afterMCPExecution]:e=>{const t=uF(e);return t.isValid,t},[xd.beforeReadFile]:e=>{const t=[],r=uF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("user_message must be a string if provided"),Td(0===t.length,t)},[xd.afterFileEdit]:e=>{const t=uF(e);return t.isValid,t},[xd.beforeTabFileRead]:e=>{const t=[],r=uF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("user_message must be a string if provided"),Td(0===t.length,t)},[xd.afterTabFileEdit]:e=>uF(e),[xd.beforeSubmitPrompt]:e=>{const t=uF(e);if(!t.isValid)return t;const r=[];return void 0!==e.continue&&"boolean"!=typeof e.continue&&r.push("continue must be a boolean if provided"),void 0!==e.user_message&&"string"!=typeof e.user_message&&r.push("user_message must be a string if provided"),void 0===e.additional_context||Pd(e.additional_context)||r.push("additional_context must be a string if provided"),Td(0===r.length,r)},[xd.stop]:e=>{const t=uF(e);if(!t.isValid)return t;const r=[];return void 0!==e.followup_message&&"string"!=typeof e.followup_message&&r.push("followup_message must be a string if provided"),Td(0===r.length,r)},[xd.afterAgentResponse]:e=>{const t=uF(e);return t.isValid,t},[xd.afterAgentThought]:e=>{const t=uF(e);return t.isValid,t},[xd.sessionStart]:e=>{const t=uF(e);if(!t.isValid)return t;const r=[];if(void 0!==e.env)if(Rd(e.env))for(const[t,n]of Object.entries(e.env))Pd(t)||r.push(`env key "${t}" must be a string`),Pd(n)||r.push(`env value for "${t}" must be a string`);else r.push("env must be an object if provided");return void 0===e.additional_context||Pd(e.additional_context)||r.push("additional_context must be a string if provided"),void 0!==e.continue&&"boolean"!=typeof e.continue&&r.push("continue must be a boolean if provided"),void 0===e.user_message||Pd(e.user_message)||r.push("user_message must be a string if provided"),Td(0===r.length,r)},[xd.sessionEnd]:e=>{const t=uF(e);return t.isValid?Td(!0,[]):t},[xd.preCompact]:e=>{const t=uF(e);if(!t.isValid)return t;if(null==e||0===Object.keys(e).length)return Td(!0,[]);const r=[];if(!Id(e))return r.push("PreCompact response must be an object"),Td(!1,r);const n=e;return void 0===n.user_message||(e=>"string"==typeof e)(n.user_message)||r.push("user_message must be a string"),Td(0===r.length,r)},[xd.subagentStart]:e=>{const t=uF(e);if(!t.isValid)return t;if(!Id(e))return Td(!1,["Expected an object"]);const r=[],n=e;if(void 0!==n.permission){const e=["allow","deny","ask"];"string"==typeof n.permission&&e.includes(n.permission)||r.push(`Invalid permission value. Expected one of: ${e.join(", ")}, or undefined`)}return void 0===n.user_message||Pd(n.user_message)||r.push("user_message must be a string if provided"),Td(0===r.length,r)},[xd.subagentStop]:e=>{const t=uF(e);if(!t.isValid)return t;const r=[];return Id(e)&&void 0!==e.followup_message&&"string"!=typeof e.followup_message&&r.push("followup_message must be a string if provided"),Td(0===r.length,r)},[xd.preToolUse]:e=>{const t=[],r=uF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny","ask"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("Invalid user_message value. Expected a string if provided"),void 0!==e.agent_message&&"string"!=typeof e.agent_message&&t.push("Invalid agent_message value. Expected a string if provided"),void 0!==e.updated_input&&("object"!=typeof e.updated_input||null===e.updated_input||Array.isArray(e.updated_input))&&t.push("Invalid updated_input value. Expected a plain object if provided"),Ad(e.additional_context,"additional_context",t),Td(0===t.length,t)},[xd.postToolUse]:e=>{const t=[],r=uF(e);return r.isValid?(Ad(e.additional_context,"additional_context",t),Td(0===t.length,t)):r},[xd.postToolUseFailure]:e=>{const t=uF(e);if(!t.isValid)return t;const r=[];return Ad(e.additional_context,"additional_context",r),Td(0===r.length,r)},[xd.workspaceOpen]:e=>{const t=uF(e);if(!t.isValid)return t;const r=[];return void 0!==e.pluginPaths&&(Array.isArray(e.pluginPaths)?e.pluginPaths.forEach(((e,t)=>{"string"==typeof e?0===e.trim().length&&r.push(`pluginPaths[${t}] must be a non-empty string`):r.push(`pluginPaths[${t}] must be a string`)})):r.push("pluginPaths must be an array of strings if provided")),Td(0===r.length,r)}},wF=(e,t,r)=>{const n=function(e,t,r){let n;return n=e===xd.preToolUse?function(e,t){if(!iF(e))return e;const r=e;if(void 0!==r.permission||void 0!==r.user_message||void 0!==r.agent_message||void 0!==r.updated_input)return r;if(!sF(t))return r;const n=aF(e);if(!cF(n,"PreToolUse"))return r;const o={...r};let s=!1;return void 0!==n.permissionDecision&&(o.permission=n.permissionDecision,s=!0),"string"==typeof n.permissionDecisionReason&&(o.user_message=n.permissionDecisionReason,s=!0),iF(n.updatedInput)&&(o.updated_input=n.updatedInput,s=!0),s?o:r}(t,r):e===xd.stop?lF(t,r,"Stop"):e===xd.subagentStop?lF(t,r,"SubagentStop"):t,function(e,t,r,n){if(!pF.has(e)||!iF(r)||void 0!==r.additional_context)return r;const o=iF(t)?function(e){return"string"==typeof e.additionalContext?e.additionalContext:void 0}(t)??function(e,t,r){if(!sF(r))return;const n=Fd[e];if(void 0===n)return;const o=aF(t);return cF(o,n)&&"string"==typeof o.additionalContext?o.additionalContext:void 0}(e,t,n):void 0;return void 0===o?r:{...r,additional_context:o}}(e,t,n,r)}(e,t,r),o=(0,gF[e])(n);return o.isValid?{success:!0,data:n}:{success:!1,errors:o.errors}},yF=[xd.beforeShellExecution,xd.beforeMCPExecution,xd.beforeReadFile,xd.beforeTabFileRead,xd.subagentStart,xd.preToolUse],vF=[xd.workspaceOpen];function bF(e,t){const r=[];return"string"==typeof e&&e.trim()&&r.push(e.trim()),"string"==typeof t&&t.trim()&&r.push(t.trim()),r.length>0?r.join("\n\n---\n\n"):void 0}function SF(e,t){return{..."object"==typeof e&&null!==e?e:{},...t}}function kF(e){return yF.includes(e)}function _F({step:e,command:t,failClosed:r,kind:n}){const o=kF(e);if(!r&&!o)return{shouldNotifyUser:!1};const s=r?"Tool blocked because this hook is configured to fail closed (block when it fails). "+("invalid_json"===n?`Hook "${t}" returned invalid JSON.`:`Hook "${t}" returned invalid response.`):"invalid_json"===n?`Hook "${t}" returned invalid JSON. The command was blocked for safety.`:`Hook "${t}" returned an invalid response for this hook step. The command was blocked for safety.`;return{blockResponse:EF(e,s),cause:r?"script_fail_closed":"permission_hook_invalid_output",reason:s,shouldNotifyUser:o&&!r}}function CF(e,t){return t}function EF(e,t){return kF(e)?CF(0,{permission:"deny",user_message:t}):e===xd.beforeSubmitPrompt||e===xd.sessionStart?CF(0,{continue:!1,user_message:t}):e===xd.stop?CF(0,{}):void 0}function xF(e){try{return{value:JSON.parse(e)}}catch{return}}function PF(e){if("object"!=typeof e||null===e)return!1;const t=e.event;return"backgrounded"===t?.case}function RF(e){if("object"!=typeof e||null===e)return;const t=e.path;return"string"==typeof t&&t.length>0?t:void 0}class IF{cacheCarriersForExecId(e,t){const r=this.carriersByExecId.get(e);if(!(void 0!==r&&r.length>0&&0===t.length))for(this.carriersByExecId.has(e)&&this.carriersByExecId.delete(e),this.carriersByExecId.set(e,t);this.carriersByExecId.size>IF.CARRIERS_BY_EXEC_ID_MAX;){const e=this.carriersByExecId.keys().next().value;if(void 0===e)break;this.carriersByExecId.delete(e)}}constructor(e,t,r,n){this.inner=e,this.wake=r,this.carriersByExecId=new Map,this.inFlightByExecId=new Map,this.resolveDrain="function"==typeof t?t:e=>t,this.skipPathWriteDrain=n?.skipPathWriteDrain,this.onWakeWrittenPath=n?.onWakeWrittenPath,this.forceWrittenPathBeforeDrain=n?.forceWrittenPathBeforeDrain,this.writeBarrierTimeoutMs=n?.writeBarrierTimeoutMs??2e3,this.resolveWriteBarrierTimeoutMs=n?.resolveWriteBarrierTimeoutMs,this.onWriteBarrier=n?.onWriteBarrier}resolveTimeoutMs(){if(void 0!==this.resolveWriteBarrierTimeoutMs)try{const e=this.resolveWriteBarrierTimeoutMs();if("number"==typeof e&&Number.isFinite(e))return e}catch{}return this.writeBarrierTimeoutMs}get(e){return this.wrapImpl(e.symbol,this.inner.get(e))}*entries(){for(const[e,t]of this.inner.entries())yield[e,this.wrapImpl(e.symbol,t)]}wrapImpl(e,t){if(!function(e){return"object"==typeof e&&null!==e&&"execute"in e&&"function"==typeof e.execute}(t))return t;const r=function(e){return e===HT.symbol||e===qT.symbol?{kind:"path"}:e===jT.symbol||e===ee.symbol||e===vA.symbol?{kind:"exposed"}:void 0}(e),n=this.resolveDrain,o=this.wake,s=this.skipPathWriteDrain,i=this.forceWrittenPathBeforeDrain,a=()=>this.resolveTimeoutMs(),c=this.onWriteBarrier,l=this.onWakeWrittenPath,u=(e,t)=>{if(void 0!==r&&void 0!==o)try{if("path"===r.kind){const r=RF(e);void 0!==r&&(o.wakeForWrittenPath(r),l?.(r,t))}else o.wakeExposedMounts()}catch{}},d=this.cacheCarriersForExecId.bind(this),h=this.carriersByExecId,p=this.inFlightByExecId,f=async(e,t)=>{const r=t?.hookContextCollector;if(void 0===r)return[];if(!1===t?.deliverAgentStoreConflictNotices)return[];const o=void 0!==t?.execId&&t.execId.length>0?t.execId:void 0;if(void 0!==o){const e=h.get(o);if(void 0!==e)return e.length>0&&r.push(...e),e;const t=p.get(o);if(void 0!==t){const e=await t;return e.length>0&&r.push(...e),e}}const s=async t=>{const r=n(e);let s=[];try{const e=await r.peek();if(s=e.eventIds,e.carriers.length>0)return t.push(...e.carriers),r.ack(e.eventIds),void 0!==o&&d(o,e.carriers),e.carriers;s.length>0&&r.ack(s);const n=[];return void 0!==o&&d(o,n),n}catch{return s.length>0&&r.release(s),[]}};if(void 0===o)return await s(r);const i=s(r);p.set(o,i);try{return await i}finally{p.get(o)===i&&p.delete(o)}};return new Proxy(t,{get:(t,n,o)=>"execute"!==n?Reflect.get(t,n,o):(n,o,l)=>{const d=t.execute.call(t,n,o,l);return"object"==typeof(h=d)&&null!==h&&Symbol.asyncIterator in h&&"function"==typeof h[Symbol.asyncIterator]?async function*(){let t=!1,r=!1,s=!1;try{for await(const r of d)if(e===ee.symbol&&PF(r)){if(!t){u(o,n);const e=await f(n,l);t=!0,e.length>0&&(yield new he.FI({event:{case:"hookContext",value:new he.Ng({hookAdditionalContexts:[...e]})}}))}yield r}else yield r;s=!0}catch(e){throw r=!0,e}finally{u(o,n),t||r||!s||await f(n,l)}}():function(e){return"object"==typeof e&&null!==e&&"then"in e&&"function"==typeof e.then}(d)?(async()=>{try{const t=await d;return u(o,n),e===HT.symbol&&!0===s?.()&&!0===l?.enableAgentStoreConflictNotices||(await async function(e,t,r,n){const o=e=>{try{n.onWriteBarrier?.(e)}catch{}};if(void 0===e||"path"!==r?.kind)return;const s=RF(t);if(void 0===s)return;if(!(n.timeoutMs>0))return void o({durationMs:0,outcome:"skipped"});const i=Date.now(),a=e(s).then((e=>e),(()=>"error")),c=await Promise.race([a,(0,Or.cb)(n.timeoutMs).then((()=>"timeout"))]);"not_store_path"!==c&&o({durationMs:Date.now()-i,outcome:c})}(i,o,r,{timeoutMs:a(),onWriteBarrier:c}),await f(n,l)),t}catch(e){throw u(o,n),e}})():(u(o,n),d);var h}})}}function TF(e){return new RegExp(`<${e}(?:\\s[^>]*)?>[\\s\\S]*?`,"gi")}IF.CARRIERS_BY_EXEC_ID_MAX=32,Error,ou.execFileSync,new Map,xo.constants.O_NOFOLLOW,new Set(["write_conflict","create_conflict","truncate_conflict_failed","conflict_fallback_failed","quota_exceeded","gap"]),new Set(["write_conflict","create_conflict","truncate_conflict_failed","conflict_fallback_failed","quota_exceeded"]),Math.max(1,Math.floor(8192));const AF=["user_info","project_layout","rules","always_applied_workspace_rules","agent_requestable_workspace_rules","user_rules","agent_skills","available_skills","cloud_instructions","cloud_task_instructions","open_and_recently_viewed_files","system_reminder","system-reminder","instructions_update","mcp_instructions","mcp_file_system","mcp_file_system_servers","git_status","agent_transcripts","cursor_rules_context","attached_files","system_notification","task_notification","agent_notification"].map(TF);function $F(e){return function(e,t){let r=e;if(r.includes("<"))for(const e of t)r=r.replace(e,"");return(r.includes("\n\n\n")?r.replace(MF,"\n\n"):r).trim()}(e,AF)}["system_reminder","system-reminder"].map(TF);const MF=/\n{3,}/g;function DF(e){const t=(0,So.sh)(e.conversationId);if("subagent"===e.kind&&e.parentConversationId){const r=(0,So.sh)(e.parentConversationId);return`${So.O2}/${r}/subagents/${t}.${e.ext}`}return`${So.O2}/${t}/${t}.${e.ext}`}function OF(e){const t=(0,So.sh)(e.conversationId);return`${So.O2}/${t}.${e.ext}`}function FF(e){const t=e.exts??["jsonl","txt"],r=e.includeLegacy??!0,n=[],o=e=>{n.includes(e)||n.push(e)};for(const n of t)o(DF({conversationId:e.conversationId,ext:n,kind:e.kind,parentConversationId:e.parentConversationId})),"subagent"===e.kind&&e.parentConversationId&&o(DF({conversationId:e.conversationId,ext:n,kind:"primary"})),r&&o(OF({conversationId:e.conversationId,ext:n}));return n}var NF;!function(e){e.INTERNAL="INTERNAL",e.EXTERNAL="EXTERNAL",e.NO_PREAMBLE="NO_PREAMBLE"}(NF||(NF={}));var LF=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},jF=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function UF(e){switch(e){case i.xyI.AGENT:return"agent";case i.xyI.ASK:return"ask";case i.xyI.PLAN:return"plan";case i.xyI.DEBUG:return"debug";case i.xyI.TRIAGE:return"triage";case i.xyI.MULTITASK:return"multitask";case i.xyI.CUSTOM:return"custom";case i.xyI.UNSPECIFIED:default:return"agent"}}function BF(e,t){return t instanceof Uint8Array?{__type:"Uint8Array",hex:(r=t,Array.from(r).map((e=>e.toString(16).padStart(2,"0"))).join(""))}:"bigint"==typeof t?t.toString():t;var r}function WF(e,t){return function(e){return"object"==typeof e&&null!==e&&"__type"in e&&"Uint8Array"===e.__type&&"hex"in e&&"string"==typeof e.hex}(t)?`[Binary data omitted from transcript: ${t.hex.length/2} bytes]`:t}const HF=new TextEncoder,qF=new TextDecoder,zF=new class{serialize(e){const t=JSON.stringify(e,BF);return HF.encode(t)}deserialize(e){const t=qF.decode(e);return t.includes('"__type":"Uint8Array"')?JSON.parse(t,WF):JSON.parse(t)}};function GF(e){const t=e.providerOptions;return!0===t?.cursor?.isSummary}function VF(e){return"system"!==e.role&&!GF(e)}function KF(e,t){return"user"===e.role&&"user"===t.role}async function JF(e,t,r){const n=await t.getBlob(e,r);return n?i.Anz.fromBinary(n).summarizedMessages:[]}async function ZF(e,t,r,n){const o=await t.getBlob(e,r);if(o){if(o.length>5e6)return n.omittedOversizeBlobCount++,n.omittedOversizeBlobBytes+=o.length,n.largestOmittedOversizeBlobBytes=Math.max(n.largestOmittedOversizeBlobBytes,o.length),{role:"assistant",content:`[Oversize transcript blob omitted: ${s=o.length,`${(s/1e6).toFixed(1)} MB`}]`};var s;try{const e=performance.now(),t=zF.deserialize(o);return n.totalDeserializeDurationMs+=performance.now()-e,n.hydratedBlobCount++,n.hydratedBlobBytes+=o.length,n.largestHydratedBlobBytes=Math.max(n.largestHydratedBlobBytes,o.length),t}catch{return}}}async function XF(e,t,r){const n={messages:[],hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0};for(const o of r){const r=await ZF(e,t,o,n);r&&n.messages.push(r)}return n}async function QF(e,t,r,n,o){const s=[];let i=0;const a=()=>{const o=ZF(e,t,r[i++],n);o.catch((()=>{})),s.push(o)};for(;i{let r;return r="string"==typeof t?t:"object"==typeof t&&null!==t?JSON.stringify(t):String(t),` ${e}: ${r}`})).join("\n")}`}(e.args)}`;case"tool-result":return`[Tool result] ${e.toolName}`;default:return""}}function eN(e){return $F(e)}const tN=/[\s\S]*?<\/think>/gi,rN=/[\s\S]*?<\/thinking>/gi,nN=/\n{3,}/g;function oN(e){let t=e;return t.includes("<")&&(t=t.replace(tN,"").replace(rN,"")),(t.includes("\n\n\n")?t.replace(nN,"\n\n"):t).trim()}function sN(e,t,r){if(void 0===e)return"";if("string"==typeof e){const n=t?eN(e):e;return r?oN(n):n}return e.map((e=>{if(r&&"text"===e.type){const r=oN(t?eN(e.text):e.text);return YF({...e,text:r},!1)}return YF(e,t)})).filter(Boolean).join("\n")}function iN(e,t){const r={role:e.role},n=e.content;if("string"==typeof n){const o=t?eN(n):n,s="assistant"===e.role?oN(o):o;s.trim()&&(r.text=s)}else if(Array.isArray(n)){const o=[],s=[],i=[];let a;for(const r of n)switch(r.type){case"text":{const n=t?eN(r.text):r.text,s="assistant"===e.role?oN(n):n;s.trim()&&o.push(s);break}case"reasoning":r.text.trim()&&s.push(r.text);break;case"redacted-reasoning":s.push("[REDACTED]");break;case"image":o.push("[Image]");break;case"file":o.push(r.filename?`[File: ${r.filename}]`:"[File]");break;case"tool-call":i.push({toolName:r.toolName,args:r.args});break;case"tool-result":a={toolName:r.toolName}}o.length>0&&(r.text=o.join("\n")),s.length>0&&(r.thinking=s.join("\n")),i.length>0&&(r.toolCalls=i),a&&(r.toolResult=a)}return r}function aN(e){return e.endsWith("\n")?e:`${e}\n`}function cN(e){const{turnEnded:t}=e,r=[],n={},o=[];return void 0!==t&&(r.push(function(e){switch(e.status){case"success":return"Turn ended: success.";case"error":return`Turn ended: error: ${e.error}`;case"aborted":return e.error?`Turn ended: aborted: ${e.error}`:"Turn ended: aborted.";default:return e}}(t)),n.turnEnded=t,o.push(JSON.stringify({type:"turn_ended",...t}))),{textSuffixes:r,jsonFields:n,jsonlLines:o}}function lN(e){if("system"===e.role||GF(e))return;const t=iN(e,"user"===e.role),r=[],n=[];if(t.text&&n.push(t.text),t.thinking&&n.push(t.thinking),n.length>0&&r.push({type:"text",text:n.join("\n\n")}),t.toolCalls)for(const e of t.toolCalls)r.push({type:"tool_use",name:e.toolName,input:e.args});if(0===r.length)return;const o={role:e.role,message:{content:r}};return JSON.stringify(o)}class uN{constructor(e,t,r,n={}){this.projectDir=e,this.blobStore=t,this.writeFile=r,this.options={writeText:n.writeText??!0,writeJson:n.writeJson??!1,writeJsonl:n.writeJsonl??!1,pathResolver:n.pathResolver,appendFile:n.appendFile,streamFullJsonlWrites:n.streamFullJsonlWrites??!1,fallbackToFullWriteOnIncrementalFailure:n.fallbackToFullWriteOnIncrementalFailure??!0}}resolveFilePath(e,t){if(this.options.pathResolver)return this.options.pathResolver(e,t);const r=DF({conversationId:e,ext:t,kind:"primary"});return`${this.projectDir}/${r}`}async writeFromStateFull(e,t,r,n={}){const o={stack:[],error:void 0,hasError:!1};try{const s=LF(o,(0,$.VI)(e.withName("writeFromState")),!1);try{const{overviewFactory:e}=n,o=cN(n),{appendFile:i,streamFullJsonlWrites:a,writeJsonl:c,writeText:l,writeJson:u}=this.options;if(i&&a&&c&&!l&&!u&&!e)try{return await this.writeJsonlStreamed(s,{state:t,filePath:this.resolveFilePath(r,"jsonl"),appendFile:i,terminalLines:o.jsonlLines}),!0}catch(e){console.error("[TranscriptStore] Streamed transcript write failed, retrying as a single write:",e)}const d=await async function(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=LF(n,(0,$.VI)(e.withName("hydrateSummaryArchives")),!1);let s=0;const i=(0,$.OA)(o.ctx),a=[];let c=0,l=0,u=0,d=0,h=0,p=0,f=0;const m=await Promise.all(r.summaryArchives.map((async e=>{s++;try{const r=await JF(i,t,e);return s+=r.length,await XF(i,t,r)}catch{return{messages:[],hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0}}})));for(const e of m)a.push(...e.messages),c+=e.hydratedBlobCount,l+=e.hydratedBlobBytes,u=Math.max(u,e.largestHydratedBlobBytes),d+=e.totalDeserializeDurationMs,h+=e.omittedOversizeBlobCount,p+=e.omittedOversizeBlobBytes,f=Math.max(f,e.largestOmittedOversizeBlobBytes);o.span.setAttribute("getBlobCount",s),o.span.setAttribute("hydratedBlobCount",c),o.span.setAttribute("hydratedBlobBytes",l),o.span.setAttribute("largestHydratedBlobBytes",u),o.span.setAttribute("totalDeserializeDurationMs",d),o.span.setAttribute("omittedOversizeBlobCount",h),o.span.setAttribute("omittedOversizeBlobBytes",p),o.span.setAttribute("largestOmittedOversizeBlobBytes",f);const g=LF(n,(0,$.VI)(e.withName("hydratePromptMessages")),!1),w=await XF(i,t,r.rootPromptMessagesJson);g.span.setAttribute("getBlobCount",r.rootPromptMessagesJson.length),g.span.setAttribute("hydratedBlobCount",w.hydratedBlobCount),g.span.setAttribute("hydratedBlobBytes",w.hydratedBlobBytes),g.span.setAttribute("largestHydratedBlobBytes",w.largestHydratedBlobBytes),g.span.setAttribute("totalDeserializeDurationMs",w.totalDeserializeDurationMs),g.span.setAttribute("omittedOversizeBlobCount",w.omittedOversizeBlobCount),g.span.setAttribute("omittedOversizeBlobBytes",w.omittedOversizeBlobBytes),g.span.setAttribute("largestOmittedOversizeBlobBytes",w.largestOmittedOversizeBlobBytes);const y=w.messages.filter(VF);return a.push(...y),a}catch(e){n.error=e,n.hasError=!0}finally{jF(n)}}(s.ctx,this.blobStore,t);if(0===d.length&&0===o.jsonlLines.length)return!0;let h;if((this.options.writeText||e)&&(h=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&"user"===t[0].role&&"user"===t[1].role&&(t=t.slice(1));const r=[];for(const e of t){const t="user"===e.role,n="assistant"===e.role,o=sN(e.content,t,n);o.trim()&&("tool"===e.role?r.push(o):r.push(`${e.role}:\n${o}`))}return r.join("\n\n")}(d)),this.options.writeText){const e=h??"",t=o.textSuffixes.length>0?e.trim().length>0?`${e}\n\n${o.textSuffixes.join("\n")}`:o.textSuffixes.join("\n"):e;t.trim()&&await this.writeFile(this.resolveFilePath(r,"txt"),t)}if(this.options.writeJson){const e=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&"user"===t[0].role&&"user"===t[1].role&&(t=t.slice(1));const r=[];for(const e of t){const t=iN(e,"user"===e.role);(t.text||t.thinking||t.toolCalls||t.toolResult)&&r.push(t)}return 0===r.length?"":JSON.stringify(r,null,2)}(d);if(e||o.jsonlLines.length>0){const n={mode:UF(t.mode),messages:e?JSON.parse(e):[],...o.jsonFields};await this.writeFile(this.resolveFilePath(r,"json"),JSON.stringify(n,null,2))}}if(this.options.writeJsonl){const t=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&KF(t[0],t[1])&&(t=t.slice(1));const r=[];for(const e of t){const t=lN(e);t&&r.push(t)}return r.join("\n")}(d);let n=[t,...o.jsonlLines].filter((e=>e.length>0)).join("\n");if(n&&e&&h?.trim())try{const t=(await e(h)).trim();t&&(n=function(e,t){const r={type:"metadata",metadata:{overview:t}};return`${JSON.stringify(r)}\n${e}`}(n,t))}catch(e){console.error("[TranscriptStore] Failed to generate transcript overview:",e)}n&&await this.writeFile(this.resolveFilePath(r,"jsonl"),aN(n))}return!0}catch(e){return console.error("[TranscriptStore] Failed to write transcript:",e),!1}}catch(e){o.error=e,o.hasError=!0}finally{jF(o)}}async writeJsonlStreamed(e,t){const{filePath:r,appendFile:n}=t;let o=[],s=0,i=0,a=0;const c=async()=>{if(0===o.length)return;const e=`${o.join("\n")}\n`;o=[],s=0,0===i?await this.writeFile(r,e):await n(r,e),i++,a+=e.length},l=async e=>{e&&(o.push(e),s+=e.length+1,s>=1e6&&await c())};let u,d=0;const h=await async function(e,t,r,n){const o={hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0};for(const s of r.summaryArchives){let r;try{r=await JF(e,t,s)}catch{continue}await QF(e,t,r,o,{skipFailedReads:!0,visit:n})}return await QF(e,t,r.rootPromptMessagesJson,o,{skipFailedReads:!1,visit:async e=>{VF(e)&&await n(e)}}),o}((0,$.OA)(e.ctx),this.blobStore,t.state,(async e=>{"system"!==e.role&&(d++,1!==d?(2===d&&u&&(KF(u,e)||await l(lN(u)),u=void 0),await l(lN(e))):u=e)}));u&&await l(lN(u));for(const e of t.terminalLines)await l(e);await c(),e.span.setAttribute("streamed",!0),e.span.setAttribute("chunkCount",i),e.span.setAttribute("writtenChars",a),e.span.setAttribute("hydratedBlobCount",h.hydratedBlobCount),e.span.setAttribute("hydratedBlobBytes",h.hydratedBlobBytes),e.span.setAttribute("largestHydratedBlobBytes",h.largestHydratedBlobBytes),e.span.setAttribute("totalDeserializeDurationMs",h.totalDeserializeDurationMs),e.span.setAttribute("omittedOversizeBlobCount",h.omittedOversizeBlobCount),e.span.setAttribute("omittedOversizeBlobBytes",h.omittedOversizeBlobBytes),e.span.setAttribute("largestOmittedOversizeBlobBytes",h.largestOmittedOversizeBlobBytes)}async writeFromStateIncremental(e,t,r,n,o={}){const s={stack:[],error:void 0,hasError:!1};try{const i=t.rootPromptMessagesJson.length,a=cN(o),c=a.jsonlLines.length>0;if(i===n&&!c&&!o.overviewFactory)return i;const l=this.options.appendFile;if(!(l&&this.options.writeJsonl&&!this.options.writeText&&!this.options.writeJson&&n>0&&i>=n&&(i>n||c))||o.overviewFactory)return await this.writeFromStateFull(e,t,r,o)?i:0;const u=LF(s,(0,$.VI)(e.withName("writeFromStateIncremental")),!1);if(i===n&&c)try{return await l(this.resolveFilePath(r,"jsonl"),aN(a.jsonlLines.join("\n"))),i}catch(n){return console.error(this.options.fallbackToFullWriteOnIncrementalFailure?"[TranscriptStore] Failed to append transcript, falling back to full write:":"[TranscriptStore] Failed to append transcript:",n),this.options.fallbackToFullWriteOnIncrementalFailure?await this.writeFromStateFull(e,t,r,o)?i:0:0}try{const e=t.rootPromptMessagesJson.slice(n),o=await XF(u.ctx,this.blobStore,e);u.span.setAttribute("hydratedBlobCount",o.hydratedBlobCount),u.span.setAttribute("hydratedBlobBytes",o.hydratedBlobBytes),u.span.setAttribute("largestHydratedBlobBytes",o.largestHydratedBlobBytes),u.span.setAttribute("totalDeserializeDurationMs",o.totalDeserializeDurationMs),u.span.setAttribute("omittedOversizeBlobCount",o.omittedOversizeBlobCount),u.span.setAttribute("omittedOversizeBlobBytes",o.omittedOversizeBlobBytes),u.span.setAttribute("largestOmittedOversizeBlobBytes",o.largestOmittedOversizeBlobBytes);const s=[];for(const e of o.messages){const t=lN(e);t&&s.push(t)}if(s.push(...a.jsonlLines),s.length>0){const e=aN(s.join("\n"));await l(this.resolveFilePath(r,"jsonl"),e)}return i}catch(n){return console.error(this.options.fallbackToFullWriteOnIncrementalFailure?"[TranscriptStore] Failed to append transcript, falling back to full write:":"[TranscriptStore] Failed to append transcript:",n),this.options.fallbackToFullWriteOnIncrementalFailure?await this.writeFromStateFull(e,t,r,o)?i:0:0}}catch(e){s.error=e,s.hasError=!0}finally{jF(s)}}}function dN(e,t){const r=function(e){return"object"==typeof e&&null!==e}(e)&&t in e?e[t]:void 0;return"string"==typeof r&&""!==r?r:void 0}function hN(e,t){return e.filter((e=>function(e,t){if(!e.matcher||""===e.matcher||"*"===e.matcher)return!0;if(void 0===t)return!0;try{return new RegExp(e.matcher).test(t)}catch{return!0}}(e,t)))}function pN(e){return`Tool blocked because this hook is configured to fail closed (block when it fails). ${e}`}function fN(e){return Object.values(xd).some((t=>t===e))}function mN(e){switch(e??(0,o.platform)()){case"darwin":return s.default.join("/Library","Application Support","Cursor","hooks.json");case"win32":return s.default.join("C:\\","ProgramData","Cursor","hooks.json");default:return s.default.join("/etc","cursor","hooks.json")}}function gN(e){return fF(e)?`prompt:${e.prompt}`:`command:${e.command}`}function wN(e){return(e.repoHooks??[]).flatMap((e=>[e.projectHooks,e.claudeProjectHooks,e.claudeProjectLocalHooks]))}class yN{constructor(e,t,r){this.fileReader=e,this.paths=t,this.logger=r||{warn:e=>console.warn(`[hooks] ${e}`),info:e=>{}}}async load(e={}){const{loadProjectHooks:t=!0}=e,r={errors:[],configDirs:{}},n=this.paths.projectConfigPath??this.paths.claudeProjectConfigPath??this.paths.claudeProjectLocalConfigPath,o=n?s.default.dirname(s.default.dirname(n)):void 0,i=(e,t)=>{if(!e||!o)return;if(t)return o;const r=s.default.relative(s.default.resolve(o),s.default.resolve(e));return".."===r||r.startsWith(`..${s.default.sep}`)||s.default.isAbsolute(r)?void 0:o},a=async(e,t,n,o,i,a,c,l)=>{if(e)try{if(!await this.fileReader.exists(e))return;if(c&&this.fileReader.pathContainsSymlink&&await this.fileReader.pathContainsSymlink(e,c))return r.errors.push({source:t,message:`${i} at ${e}: refusing to load config path that contains a symlink`}),void this.logger.warn(`Refusing to load ${a} config via symlink path: ${e}`);const u=await this.fileReader.readFile(e);if(!u)return;const{config:d,error:h}=l(u);if(d){switch(n){case"enterpriseHooks":r.enterpriseHooks=d;break;case"teamHooks":r.teamHooks=d;break;case"userHooks":r.userHooks=d;break;case"projectHooks":r.projectHooks=d;break;case"claudeUserHooks":r.claudeUserHooks=d;break;case"claudeProjectHooks":r.claudeProjectHooks=d;break;case"claudeProjectLocalHooks":r.claudeProjectLocalHooks=d;break;default:return}((e,t)=>{r.configDirs[e]=s.default.dirname(t)})(o,e)}else h&&r.errors.push({source:t,message:`${i} at ${e}: ${h}`})}catch(e){r.errors.push({source:t,message:`Error accessing ${a} config file: ${String(e)}`})}},c=[{path:this.paths.enterpriseConfigPath,source:"enterprise",resultKey:"enterpriseHooks",configDirKey:"enterprise",parsePrefix:"Enterprise hooks.json",accessLabel:"enterprise",symlinkCheckRoot:i(this.paths.enterpriseConfigPath,!1)},{path:this.paths.teamConfigPath,source:"team",resultKey:"teamHooks",configDirKey:"team",parsePrefix:"Team hooks.json",accessLabel:"team",symlinkCheckRoot:i(this.paths.teamConfigPath,!1)},{path:this.paths.userConfigPath,source:"user",resultKey:"userHooks",configDirKey:"user",parsePrefix:"User hooks.json",accessLabel:"user",symlinkCheckRoot:i(this.paths.userConfigPath,!1)},{path:t?this.paths.projectConfigPath:void 0,source:"project",resultKey:"projectHooks",configDirKey:"project",parsePrefix:"Project hooks.json",accessLabel:"project",symlinkCheckRoot:i(this.paths.projectConfigPath,!0)}];for(const e of c)await a(e.path,e.source,e.resultKey,e.configDirKey,e.parsePrefix,e.accessLabel,e.symlinkCheckRoot,(t=>this.parseAndValidate(t,e.source)));const l=[{path:this.paths.claudeUserConfigPath,source:"claude-user",resultKey:"claudeUserHooks",configDirKey:"claudeUser",label:"user",symlinkCheckRoot:i(this.paths.claudeUserConfigPath,!1)},{path:t?this.paths.claudeProjectConfigPath:void 0,source:"claude-project",resultKey:"claudeProjectHooks",configDirKey:"claudeProject",label:"project",symlinkCheckRoot:i(this.paths.claudeProjectConfigPath,!0)},{path:t?this.paths.claudeProjectLocalConfigPath:void 0,source:"claude-project-local",resultKey:"claudeProjectLocalHooks",configDirKey:"claudeProjectLocal",label:"project local",symlinkCheckRoot:i(this.paths.claudeProjectLocalConfigPath,!0)}];for(const e of l)await a(e.path,e.source,e.resultKey,e.configDirKey,`Claude ${e.label} settings.json`,`Claude ${e.label}`,e.symlinkCheckRoot,(t=>this.parseClaudeConfig(t,e.source)));return function(e){const{cursorConfigs:t,claudeConfigs:r,logger:n}=e,o=new Map;for(const e of t)if(e?.hooks)for(const[t,r]of Object.entries(e.hooks)){if(!r)continue;let e=o.get(t);e||(e=new Set,o.set(t,e));for(const t of r)e.add(gN(t))}for(const{config:e,source:t}of r)if(e?.hooks)for(const[r,s]of Object.entries(e.hooks)){if(!s)continue;const i=o.get(r);if(!i||0===i.size)continue;const a=s.filter((e=>{const o=gN(e);return!i.has(o)||(n?.info(`Removed duplicate ${t} hook for ${r}: ${o}`),!1)}));a.length!==s.length&&(e.hooks[r]=a)}}({cursorConfigs:[r.enterpriseHooks,r.teamHooks,r.userHooks,r.projectHooks],claudeConfigs:[{config:r.claudeUserHooks,source:"claude-user"},{config:r.claudeProjectHooks,source:"claude-project"},{config:r.claudeProjectLocalHooks,source:"claude-project-local"}],logger:this.logger}),r}parseClaudeConfig(e,t){try{const t=JSON.parse(e);if(!function(e,t={}){if(!Id(e))return!1;if(!("hooks"in e))return!1;const r=e.hooks;if(!Id(r))return!1;const n=r;for(const[e,r]of Object.entries(n))if(e in Od&&Array.isArray(r)){const n=!0===t.allowMatcherlessStop&&"Stop"===e;for(const e of r)if(Id(e)&&"hooks"in e&&Array.isArray(e.hooks)&&("matcher"in e||n))return!0}return!1}(t))return{};const r=t.hooks;if(!r||0===Object.keys(r).length)return{};const n=Xd(r,this.logger),o=Dd(n);return o.isValid?{config:n}:{error:`Invalid transformed config: ${o.errors.join("; ")}`}}catch(e){return{error:`Failed to parse JSON: ${String(e)}`}}}parseAndValidate(e,t){try{const n=this.parseJSONC(e),o=Dd(n);return o.isValid?"object"==typeof(r=n)&&null!==r&&"version"in r&&"number"==typeof r.version&&"hooks"in r&&"object"==typeof r.hooks&&null!==r.hooks&&!Array.isArray(r.hooks)?{config:n}:{error:`Invalid ${t} config: missing 'hooks' property`}:{error:`Invalid ${t} config: ${o.errors.join("; ")}`}}catch(e){return{error:`Failed to parse ${t} config JSON: ${String(e)}`}}var r}parseJSONC(e){let t=e.replace(/\/\/.*$/gm,"");return t=t.replace(/\/\*[\s\S]*?\*\//g,""),JSON.parse(t)}static getConfiguredSteps(e){const t=new Set,r=[e.enterpriseHooks,e.teamHooks,e.userHooks,e.projectHooks,e.claudeUserHooks,e.claudeProjectHooks,e.claudeProjectLocalHooks,...wN(e)];for(const e of r)if(e?.hooks)for(const r of Object.keys(e.hooks))fN(r)&&t.add(r);for(const r of e.pluginHooks??[])for(const e of Object.keys(r.config.hooks))fN(e)&&t.add(e);return t}}const vN="Read",bN="Write",SN="Delete",kN="List",_N="Grep",CN="Shell",EN="ReadLints";function xN(e,t){if("object"==typeof e&&null!==e)return Object.getOwnPropertyDescriptor(e,t)?.value}const PN=new Set([vN,bN,SN,kN,_N,EN]);function RN(e){const t=xN(e,"tool_name"),r=[xN(e,"file_path"),"string"==typeof t&&PN.has(t)?xN(xN(e,"tool_input"),"file_path"):void 0];for(const e of r)if("string"==typeof e&&e.length>0)return e}const IN=(0,l.h)("cli-hooks-executor");function TN(e){try{return(0,xo.statSync)(e).isFile()}catch{return!1}}const AN="\nJSON Parse Error: Error: Failed to parse hook stdout as JSON";function $N(e,t){for(const[r,n]of Object.entries(e))if(r===t)return n}function MN(e,t){const r=$N(e,t);if("string"==typeof r||null===r)return r}class DN{constructor(e,t,r,n,o,s,i,a){this.workspacePath=t,this.globalContext=r,this.shellExecutor=n,this.promptHookClient=o,this.onHookExecution=i,this.options=a,this.sessionEnvById=new Map,this.sessionUserEmailById=new Map,this.activeSessionIdsByConversationId=new Map,this.transcriptParentConversationIdById=new Map,this.configReadyPromises=[],this.config=e,s&&this.addConfigReadyPromise(s)}addConfigReadyPromise(e){this.configReadyPromises.push(e.catch((()=>{})))}reportCommandFailure(e,t){if(void 0!==e)try{e(t)}catch{}}finishHookRun(e,t,r,n){const o=e.transportMode??("prompt"===e.hookType?"prompt":this.getCommandHookPayloadTransportMode());try{this.onHookExecution?.({...e,transportMode:o})}catch{}const s=this.options?.onHookRun;if(void 0===s)return;const i=n.exitCode??e.exitCode,a="spawn_error"===(c=e.errorClass)?"shell_exec_transport_error":"prompt_error"===c?"prompt_execution_error":void 0;var c;try{s({step:e.hookStep,script:t,source:e.hookSource,...void 0===e.pluginId?{}:{pluginId:e.pluginId},request:r,response:n.response??null,status:e.status,durationMs:e.latencyMs,...void 0===i?{}:{exitCode:i},stderr:n.stderr,transportMode:o,configuredTimeoutSec:t.timeout??60,timedOut:!0===e.timedOut,...void 0===a?{}:{failureType:a}})}catch{}}getCommandHookPayloadTransportMode(){return"stdin"===this.options?.commandHookPayloadTransport?"win32"===process.platform?"windows_temp_file":"stdin":"argv_heredoc"}shouldUseCommandHookDirectStdinTransport(){return"stdin"===this.getCommandHookPayloadTransportMode()}async writeCommandHookStdinPayload(e,t){if(!e)throw new Error("Hook stdin transport was requested, but the executor did not provide stdin");try{e.end(Buffer.from(t,"utf8"))}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;if("EPIPE"===t||"ERR_STREAM_DESTROYED"===t||"ERR_STREAM_PREMATURE_CLOSE"===t)return;throw e}try{await(0,ah.finished)(e)}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;if("EPIPE"===t||"ERR_STREAM_DESTROYED"===t||"ERR_STREAM_PREMATURE_CLOSE"===t)return;throw e}}updateConfig(e){this.config=e}beginSessionEnvironment(e,t){this.sessionEnvById.delete(e.sessionId),this.sessionUserEmailById.delete(e.sessionId);const r=this.activeSessionIdsByConversationId.get(e.conversationId)??[];this.activeSessionIdsByConversationId.set(e.conversationId,r.filter((t=>t!==e.sessionId)).concat(e.sessionId));const n=t?.userEmail?.trim()??"";n.length>0&&this.sessionUserEmailById.set(e.sessionId,n)}setSessionUserEmail(e,t){const r=t?.trim()??"";0!==r.length&&this.sessionUserEmailById.set(e.sessionId,r)}setSessionEnvironment(e,t){void 0===t?this.sessionEnv={...this.sessionEnv,...e}:this.sessionEnvById.set(t.sessionId,{...this.sessionEnvById.get(t.sessionId),...e})}clearSessionEnvironment(e){if(void 0===e)this.sessionEnv=void 0;else{this.sessionEnvById.delete(e.sessionId),this.sessionUserEmailById.delete(e.sessionId);const t=(this.activeSessionIdsByConversationId.get(e.conversationId)??[]).filter((t=>t!==e.sessionId));0===t.length?this.activeSessionIdsByConversationId.delete(e.conversationId):this.activeSessionIdsByConversationId.set(e.conversationId,t)}}resolveUserEmail(e){const{conversation_id:t,session_id:r}=e;if(void 0!==r&&this.sessionUserEmailById.has(r))return this.sessionUserEmailById.get(r)??null;if(void 0!==t){const e=this.activeSessionIdsByConversationId.get(t)?.at(-1);if(void 0!==e){const t=this.sessionUserEmailById.get(e);if(void 0!==t)return t}}return this.globalContext.user_email}setTranscriptParentConversationId(e,t){this.transcriptParentConversationIdById.set(e,t)}async getTranscriptPathIfExists(e){try{const t=(0,So.Rv)((0,o.homedir)(),this.workspacePath),r=this.transcriptParentConversationIdById.get(e),n=FF(r?{conversationId:e,kind:"subagent",parentConversationId:r}:{conversationId:e,kind:"primary"}).map((e=>(0,s.join)(t,e)));for(const e of n)try{return await(0,Co.access)(e),e}catch{}return null}catch{return null}}async getSubagentTranscriptPathIfExists(e){const{subagentId:t,parentConversationId:r}=e;try{const e=(0,So.Rv)((0,o.homedir)(),this.workspacePath),n=FF({conversationId:t,kind:"subagent",parentConversationId:r}).map((t=>(0,s.join)(e,t)));for(const e of n)try{return await(0,Co.access)(e),e}catch{}return null}catch{return null}}hasHooksForStep(e){return[this.config.enterpriseHooks,this.config.teamHooks,this.config.userHooks,this.config.projectHooks,this.options?.runtimeHooks,this.config.claudeUserHooks,this.config.claudeProjectHooks,this.config.claudeProjectLocalHooks,...wN(this.config),...(this.config.pluginHooks??[]).map((e=>e.config))].some((t=>{const r=t?.hooks[e];return void 0!==r&&r.length>0}))}hasFailClosedHooksForStep(e,t){const r=[this.config.enterpriseHooks,this.config.teamHooks,this.config.projectHooks,...(this.config.repoHooks??[]).map((e=>e.projectHooks)),this.config.userHooks,this.options?.runtimeHooks];for(const n of r){const r=n?.hooks[e];if(r&&(t?hN(r,t):r).some((e=>!0===e.failClosed)))return!0}for(const r of this.config.pluginHooks??[]){const n=r.config.hooks[e];if(n&&(t?hN(n,t):n).some((e=>mF(e)&&!0===e.failClosed)))return!0}return!1}configuredHookDirectory(e){const t=this.config.configDirs;switch(e){case"enterprise":return t?.enterprise;case"team":return t?.team;case"user":return t?.user;case"claude-user":return t?.claudeUser;default:return}}cwdForHookSource(e,t){if(void 0!==e?.cwd&&e.cwd.length>0)return e.cwd;const r=this.configuredHookDirectory(t.source);if(void 0!==r&&r.length>0)return r;const n=e?.cwdForSource?.(t.source);return void 0!==n&&n.length>0?n:t.fallback}getCwdForSource(e){const t=this.config.configDirs;switch(e){case"enterprise":return t?.enterprise??this.workspacePath;case"team":return t?.team??this.workspacePath;case"project":case"claude-project":case"claude-project-local":case"claude-plugin":case"runtime":default:return this.workspacePath;case"user":return t?.user??this.workspacePath;case"claude-user":return t?.claudeUser??this.workspacePath}}buildHookEnvironment(e){const{transcriptPath:t,sessionId:r,conversationId:n,executionEnv:o}=e,s=this.resolveUserEmail({conversation_id:n,session_id:r});return{CURSOR_PROJECT_DIR:this.workspacePath,CURSOR_VERSION:this.globalContext.cursor_version,...s&&{CURSOR_USER_EMAIL:s},...t&&{CURSOR_TRANSCRIPT_PATH:t},CLAUDE_PROJECT_DIR:this.workspacePath,...this.sessionEnv,...void 0!==r?this.sessionEnvById.get(r):void 0,...o}}shouldSkipHookDueToLoopLimit(e,t,r){if("stop"!==e&&"subagentStop"!==e)return!1;const n=$N(r,"loop_count");if("number"!=typeof n)return!1;const o=n,s=t.loop_limit;return null!==s&&(void 0===s?o>=5:o>=s)}async executeHookForStep(e,t,r){this.configReadyPromises.length>0&&await this.whenConfigReady();const n=function(e){return vF.includes(e)}(e),o=t,i=n?null:o.conversation_id?await this.getTranscriptPathIfExists(o.conversation_id):null;let a;if(e===xd.subagentStop){const e=MN(t,"subagent_id"),r=MN(t,"parent_conversation_id");a=e?await this.getSubagentTranscriptPathIfExists({subagentId:e,parentConversationId:r??void 0}):null}const c=n?void 0:o.session_id??o.conversation_id,l={...t,...void 0!==c&&{session_id:c},hook_event_name:e,cursor_version:this.globalContext.cursor_version,workspace_roots:[...new Set([this.workspacePath,...(this.config.repoHooks??[]).map((e=>e.repoPath))])],user_email:this.resolveUserEmail(o),...!n&&{transcript_path:i},...e===xd.subagentStop&&{agent_transcript_path:a??null}},u=function(e,t){switch(e){case"beforeShellExecution":case"afterShellExecution":return dN(t,"command");case"beforeMCPExecution":case"afterMCPExecution":{const e=dN(t,"tool_name");return e?`MCP:${e}`:void 0}case"beforeReadFile":return"Read";case"afterFileEdit":return"Write";case"beforeTabFileRead":return"TabRead";case"afterTabFileEdit":return"TabWrite";case"beforeSubmitPrompt":return"UserPromptSubmit";case"stop":return"Stop";case"afterAgentResponse":return"AgentResponse";case"afterAgentThought":return"AgentThought";case"subagentStart":case"subagentStop":return dN(t,"subagent_type");case"preToolUse":case"postToolUse":case"postToolUseFailure":return dN(t,"tool_name");default:return}}(e,l),d=[],h=(e,t,n)=>{if(!e)return;const o=hN(e,u),s=this.cwdForHookSource(r,{source:t,fallback:n??this.getCwdForSource(t)}),i=void 0===n?r?.env:{CURSOR_PROJECT_DIR:n,CLAUDE_PROJECT_DIR:n,...r?.env};for(const e of o)fF(e)?this.promptHookClient&&d.push({type:"prompt",script:e,source:t}):mF(e)&&d.push({type:"command",script:e,cwd:s,env:i,source:t})},p=await async function({repoHooks:e,targetPath:t,workspacePath:r}){if(e.length<2||void 0===t||0===t.length)return e;const n=(0,Yo.o1)(t,r),[o,i,a]=await Promise.all([(0,Yo.DN)(n),(0,Yo.DN)(s.default.dirname(n)),Promise.all(e.map((async e=>await(0,Yo.DN)(e.repoPath)??s.default.resolve(e.repoPath))))]);if(null===o||null===i)return e;const c=t=>{let r;return e.forEach(((e,n)=>{const o=a[n],i=s.default.relative(o,t);(""===i||".."!==i&&!i.startsWith(`..${s.default.sep}`)&&!s.default.isAbsolute(i))&&(void 0===r||o.length>r.repoPath.length)&&(r={repo:e,repoPath:o})})),r?.repo},l=new Set;for(const t of[o,s.default.join(i,s.default.basename(n))]){const r=c(t);if(void 0===r)return e;l.add(r)}return e.filter((e=>l.has(e)))}({repoHooks:this.config.repoHooks??[],targetPath:RN(t),workspacePath:this.workspacePath});h(this.config.enterpriseHooks?.hooks[e],"enterprise"),h(this.config.teamHooks?.hooks[e],"team"),h(this.config.projectHooks?.hooks[e],"project");for(const t of p)h(t.projectHooks?.hooks[e],"project",t.repoPath);h(this.config.userHooks?.hooks[e],"user"),h(this.options?.runtimeHooks?.hooks[e],"runtime"),h(this.config.claudeProjectLocalHooks?.hooks[e],"claude-project-local"),h(this.config.claudeProjectHooks?.hooks[e],"claude-project");for(const t of p)h(t.claudeProjectLocalHooks?.hooks[e],"claude-project-local",t.repoPath),h(t.claudeProjectHooks?.hooks[e],"claude-project",t.repoPath);h(this.config.claudeUserHooks?.hooks[e],"claude-user");for(const t of this.config.pluginHooks??[]){const n=t.config.hooks[e];if(!n?.length)continue;const o=r?.cwd??(e===xd.stop||e===xd.subagentStop?this.workspacePath:t.installPath),s={...void 0!==t.plugin&&{plugin:t.plugin},...void 0!==t.marketplace&&{marketplace:t.marketplace},...void 0!==t.pluginId&&{pluginId:t.pluginId},...void 0!==t.marketplaceId&&{marketplaceId:t.marketplaceId}};for(const e of hN(n,u))mF(e)&&d.push({type:"command",script:e,cwd:o,env:r?.env,source:"claude-plugin",attribution:s,pluginInstallPath:t.installPath})}if(0!==d.length)return this.executeAllAndMerge(e,d,l,r?.onCommandFailure)}async whenConfigReady(){await Promise.all(this.configReadyPromises)}async executeAllAndMerge(e,t,r,n){let o;const s=()=>o??=function(e){const t=JSON.stringify(e);return{json:t,payloadSizeBytes:Buffer.byteLength(t,"utf8")}}(r),i=t.map((async(t,o)=>{const{source:i,attribution:a}=t;try{return"prompt"===t.type?await this.executePromptHook(e,t.script,r,i,o,s,a):await this.executeCommandHook(e,t.script,t.cwd,t.env,r,i,o,s,a,t.pluginInstallPath,n)}catch(r){const n=r instanceof Error?r.message:String(r);if(!0===t.script.failClosed){const t=pN(`Hook execution failed: ${n}`),r=EF(e,t);if(r)return{success:!0,data:r,source:i,index:o}}return IN.warn((0,y.q6)(),`${e} hook error`,{source:i,index:o,error:n}),{success:!1,source:i,index:o}}})),a=await Promise.all(i),c=[];for(const e of a)e.success&&void 0!==e.data&&c.push(e.data);return function(e,t){if(0===t.length)return;const[r]=t;if(!(1!==t.length||Id(n=r)&&Id(n.updated_input)&&0===Object.keys(n.updated_input).length))return r;var n;const o=yF.includes(e),s=e===xd.sessionStart,i=e===xd.workspaceOpen,a=pF.has(e),c={};for(const e of t){const t=e;for(const[e,r]of Object.entries(t))if(void 0!==r)if(i&&"pluginPaths"===e&&Array.isArray(r)){const t=c[e],n=Array.isArray(t)?t:[],o=new Set(n),s=[...n];for(const e of r)"string"!=typeof e||o.has(e)||(o.add(e),s.push(e));c[e]=s}else"permission"===e&&o?c[e]=(u=r,"deny"===(l=c[e])||"deny"===u?"deny":"ask"===l||"ask"===u?"ask":"allow"===l||"allow"===u?"allow":void 0):"user_message"!==e&&"agent_message"!==e?"updated_input"!==e?a&&"additional_context"===e&&"string"==typeof r?c[e]=bF(c[e],r):"continue"!==e||"boolean"!=typeof r?c[e]=s&&"env"===e&&"object"==typeof r&&null!==r?SF(c[e],r):r:void 0===c[e]?c[e]=r:c[e]=c[e]&&r:void 0===c[e]&&Id(r)&&Object.keys(r).length>0&&(c[e]=r):c[e]=bF(c[e],r)}var l,u;return c}(e,c)}async executeCommandHook(e,t,r,n,o,s,i,a,c,l,u){if(this.shouldSkipHookDueToLoopLimit(e,t,o))return{success:!1,source:s,index:i};const d=Date.now(),h=a(),p=h.payloadSizeBytes,f=(e,r)=>this.finishHookRun(e,t,o,r);let m;try{m=await this.executeCommandScript({script:t,cwd:r,request:o,jsonPayload:h.json,env:n,...void 0!==l&&{pluginInstallPath:l}})}catch(r){const n=r instanceof Error?r.message:String(r),o=n.toLowerCase().includes("timed out");this.reportCommandFailure(u,{command:t.command,source:s,exitCode:null,stderr:"",errorMessage:n});const a=Date.now()-d,l=o?"timeout":"spawn_error";if(!0===t.failClosed){const u=EF(e,pN(`Hook "${t.command}" execution failed: ${n}`));if(u)return f({hookStep:e,hookSource:s,hookType:"command",status:o?"timeout":"blocked",latencyMs:a,payloadSizeBytes:p,errorClass:l,failClosed:!0,timedOut:o,...c},{response:null,stderr:String(r)}),{success:!0,data:u,source:s,index:i}}return f({hookStep:e,hookSource:s,hookType:"command",status:o?"timeout":"failed",latencyMs:a,payloadSizeBytes:p,errorClass:l,failClosed:!0===t.failClosed,timedOut:o,...c},{response:null,stderr:String(r)}),{success:!1,source:s,index:i}}if(2===m.exitCode){const r=function(e,t,r){const n=e.trim(),o=t.trim();return n||(o?`Hook blocked with message: ${o}`:`Hook "${r}" blocked this action (exit code 2) but provided no reason.`)}(m.stdout,m.stderr,t.command),n=EF(e,r);return n?(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,failClosed:!0===t.failClosed,exitCode:m.exitCode,...c},{response:n,stderr:m.stderr}),{success:!0,data:n,source:s,index:i}):(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,failClosed:!0===t.failClosed,exitCode:m.exitCode,...c},{response:null,stderr:m.stderr}),{success:!1,source:s,index:i})}if(0!==m.exitCode&&null!==m.exitCode){if(this.reportCommandFailure(u,{command:t.command,source:s,exitCode:m.exitCode,stderr:m.stderr}),!0===t.failClosed){const r=EF(e,pN(`Hook "${t.command}" failed with exit code ${m.exitCode}${m.stderr?`: ${m.stderr.trim()}`:""}`));if(r)return f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"exit_nonzero",failClosed:!0,exitCode:m.exitCode,...c},{response:null,stderr:m.stderr}),{success:!0,data:r,source:s,index:i}}return f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"exit_nonzero",failClosed:!0===t.failClosed,exitCode:m.exitCode,...c},{response:null,stderr:m.stderr}),{success:!1,source:s,index:i}}const g=m.stdout.trim();if(!g){if(!0===t.failClosed){const r=EF(e,pN(`Hook "${t.command}" returned no output.`));if(r)return f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"empty_stdout",failClosed:!0,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr}),{success:!0,data:r,source:s,index:i}}return f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"empty_stdout",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr}),{success:!1,source:s,index:i}}const w=function(e){const t=e.trim();if(0===t.length)return;const r=xF(t);if(void 0!==r)return r.value;if(t.endsWith("}"))for(let e=t.length-1;e>=0;e--){if("{"!==t[e])continue;const r=xF(t.slice(e));if(void 0!==r)return r.value}}(g);if(void 0===w){const r=_F({step:e,command:t.command,failClosed:!0===t.failClosed,kind:"invalid_json"});return r.blockResponse?(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_json",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr+AN}),{success:!0,data:r.blockResponse,source:s,index:i}):(f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_json",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr+AN}),{success:!1,source:s,index:i})}const y=wF(e,w,{enableClaudeNestedHookSpecificOutputCompatibility:this.options?.enableClaudeNestedHookSpecificOutputCompatibility});if(y.success&&null!=y.data){const r=y.data,n="object"==typeof r&&"permission"in r?r.permission:void 0;return f({hookStep:e,hookSource:s,hookType:"command",status:"deny"===n||"ask"===n?"blocked":"success",latencyMs:m.duration,payloadSizeBytes:p,failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:r,stderr:m.stderr}),{success:!0,data:r,source:s,index:i}}const v=_F({step:e,command:t.command,failClosed:!0===t.failClosed,kind:"invalid_response"});return v.blockResponse?(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_response",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:w,stderr:m.stderr}),{success:!0,data:v.blockResponse,source:s,index:i}):(f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_response",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:w,stderr:m.stderr}),{success:!1,source:s,index:i})}async executePromptHook(e,t,r,n,o,s,i){if(this.shouldSkipHookDueToLoopLimit(e,t,r))return{success:!1,source:n,index:o};if(!this.promptHookClient)return{success:!1,source:n,index:o};const a=1e3*(t.timeout??60),c=Date.now(),l=s(),u=l.payloadSizeBytes,d=(e,n)=>this.finishHookRun(e,t,r,n),h=(0,y.q6)(),[p,f]=h.withTimeoutAndCancel(a);try{const r=JSON.parse(l.json),s=await this.promptHookClient.evaluatePromptHook(p,{prompt:t.prompt,hookInputJson:r,modelName:t.model});if(s.ok){const r=function(e){return kF(e)?CF(0,{permission:"allow"}):e===xd.beforeSubmitPrompt||e===xd.sessionStart?CF(0,{continue:!0}):e===xd.stop?CF(0,{}):void 0}(e);return d({hookStep:e,hookSource:n,hookType:"prompt",status:"success",latencyMs:Date.now()-c,payloadSizeBytes:u,failClosed:!0===t.failClosed,...i},{response:r,stderr:"",exitCode:0}),r?{success:!0,data:r,source:n,index:o}:{success:!1,source:n,index:o}}{const r=EF(e,s.reason??"Prompt hook blocked this action");return d({hookStep:e,hookSource:n,hookType:"prompt",status:"blocked",latencyMs:Date.now()-c,payloadSizeBytes:u,failClosed:!0===t.failClosed,...i},{response:r,stderr:"",exitCode:2}),r?{success:!0,data:r,source:n,index:o}:{success:!1,source:n,index:o}}}catch(r){const s=r instanceof Error?r.message:String(r),a=s.toLowerCase().includes("abort")||s.toLowerCase().includes("timed out"),l=a?"timeout":"prompt_error";if(!0===t.failClosed){const t=EF(e,pN(`Prompt hook failed: ${s}`));if(t)return d({hookStep:e,hookSource:n,hookType:"prompt",status:a?"timeout":"blocked",latencyMs:Date.now()-c,payloadSizeBytes:u,errorClass:l,failClosed:!0,timedOut:a,...i},{response:null,stderr:String(r)}),{success:!0,data:t,source:n,index:o}}return d({hookStep:e,hookSource:n,hookType:"prompt",status:a?"timeout":"failed",latencyMs:Date.now()-c,payloadSizeBytes:u,errorClass:l,failClosed:!0===t.failClosed,timedOut:a,...i},{response:null,stderr:String(r)}),{success:!1,source:n,index:o}}finally{f()}}async executeCommandScript(e){const{script:t,cwd:r,request:n,env:i,pluginInstallPath:a,jsonPayload:c}=e,l=1e3*(t.timeout??60),u=Date.now();let d;const h=new AbortController,p=setTimeout((()=>{h.abort()}),l);try{const e="win32"===process.platform,f=this.getCommandHookPayloadTransportMode(),m=this.shouldUseCommandHookDirectStdinTransport(),g=e?function(e,t){const r=function(e){let t=0;for(;t0&&!/^\s/.test(i))return e;if(/[$`{}()|;,<>]/.test(s)||""===o&&/['"]/.test(s))return e;const a=s.slice(Math.max(s.lastIndexOf("\\"),s.lastIndexOf("/"))+1);if(0===a.length||a.includes("."))return e;const c="'"===o?s.replace(/''/g,"'"):s,l=/^[A-Za-z]:[\\/]/.test(u=c)||u.startsWith("\\")||u.startsWith("/")?c:`${t.cwd.replace(/[\\/]+$/,"")}\\${c}`;var u;const d=nF.find((e=>t.isFile(l+e)));return void 0===d?e:""!==o?`${n}${o}${s}${d}${o}${i}`:`${n}'${s}${d}'${i}`}(t.command,{cwd:r,isFile:TN}):t.command;let w;if(m)w=e?oF(g):g;else if("windows_temp_file"===f){d=await(0,Co.mkdtemp)((0,s.join)((0,o.tmpdir)(),"cursor-hooks-"));const e=(0,s.join)(d,"payload.json");await(0,Co.writeFile)(e,c,{encoding:"utf8",flag:"wx"}),w=function(e,t){return`$OutputEncoding = [System.Text.UTF8Encoding]::new($false); try { $global:cursorHookConsoleInputEncoding = [Console]::InputEncoding; $null = Register-EngineEvent -SourceIdentifier PowerShell.Exiting -Action { try { [Console]::InputEncoding = $global:cursorHookConsoleInputEncoding } catch { } }; [Console]::InputEncoding = $OutputEncoding } catch { }; Get-Content -LiteralPath '${e.replace(/'/g,"''")}' -Raw -Encoding UTF8 | & { $input | ${oF(t)} }`+rF(t)}(e,g)}else w=e?`@'\n${c.replace(/'/g,"''")}\n'@ | & ${g}`+rF(g):`${t.command} <<'CURSOR_HOOK_EOF'\n${c}\nCURSOR_HOOK_EOF`;const v=MN(n,"conversation_id")??void 0,b=MN(n,"session_id")??void 0,S=MN(n,"transcript_path"),k=void 0===v?void 0:this.activeSessionIdsByConversationId.get(v),_=void 0===b||b===v&&!this.sessionEnvById.has(b)?void 0===v?void 0:k?.at(-1)??v:b,C=this.buildHookEnvironment({transcriptPath:S,sessionId:_,conversationId:v,executionEnv:i}),E={};for(const[e,t]of Object.entries(C))void 0!==t&&(E[e]=t);void 0!==a&&(E.CURSOR_PLUGIN_ROOT=a,E.CLAUDE_PLUGIN_ROOT=a);const x=(0,y.q6)(),P=new ia.StringDecoder("utf8"),R=new ia.StringDecoder("utf8");let I,T="",A="",$=null,M=!1;for await(const e of this.shellExecutor.execute(x,w,{workingDirectory:r,signal:h.signal,sandboxPolicy:{perUser:{type:"insecure_none"}},env:E,pipeStdin:m}))switch(e.type){case"stdin_ready":m&&(await this.writeCommandHookStdinPayload(e.stdin,c),M=!0);break;case"stdout":T+=P.write(e.data);break;case"stderr":A+=R.write(e.data);break;case"exit":$=e.code,I=e.aborted}if(T+=P.end(),A+=R.end(),m&&!M)throw new Error("Hook stdin transport was requested, but the executor did not signal stdin readiness");clearTimeout(p);const D=Date.now()-u;if(I??h.signal.aborted)throw new Error(`Hook script timed out after ${l}ms`);return{stdout:T,stderr:A,exitCode:$,duration:D}}catch(e){if(clearTimeout(p),Date.now(),h.signal.aborted)throw new Error(`Hook script timed out after ${l}ms`);throw e}finally{if(d)try{await(0,Co.rm)(d,{recursive:!0,force:!0})}catch{}}}}class ON{constructor(e){this.config=e,this.configuredSteps=yN.getConfiguredSteps(e)}getConfig(){return this.config}hasHookForStep(e){return this.configuredSteps.has(e)}getConfiguredSteps(){return new Set(this.configuredSteps)}}var FN=r("node:perf_hooks");const NN=(0,y.cF)(Symbol.for("@anysphere/agent-exec/toolCallHooks"),{kind:"none"});function LN(e){return"inExecute"!==e.get(NN).kind}function jN(e,t){const r=e.get(NN);return"inExecute"!==r.kind||!r.toolStepsInPreToolUse.includes(t)}(0,y.cF)(Symbol.for("@anysphere/agent-exec/hookAsk"),void 0),(0,y.cF)(Symbol.for("@anysphere/agent-exec/hookAllow"),void 0),new WeakMap,new WeakMap,(0,y.cF)(Symbol.for("@anysphere/agent-exec/toolCallRefusal"),void 0),new WeakMap,new WeakMap,new WeakMap,(0,y.cF)(Symbol.for("@anysphere/agent-exec/approvalWaits"),void 0),new WeakMap;const UN=(0,y.cF)(Symbol.for("@anysphere/agent-exec/hookStepTime"),void 0),BN=new yd.AsyncLocalStorage;function WN(e,t){return BN.run(e,t)}function HN(e,t){void 0!==e&&t.length>0&&e.push(...t)}class qN extends Error{constructor(e){super(`Hook additional_context for ${e.hookEventName} is ${e.actualLength} chars (max ${e.maxLength}).`),this.name="HookAdditionalContextTooLargeError",this.hookEventName=e.hookEventName,this.actualLength=e.actualLength,this.maxLength=e.maxLength}}var zN=r("../proto/dist/generated/agent/v1/hook_additional_context_pb.js");function GN({hookEventName:e,additionalContext:t}){const r=function(e){const t=e?.trim();return void 0!==t&&t.length>0?t:void 0}(t);if(void 0===r)return[];if(r.length>1e4)throw new qN({hookEventName:e,actualLength:r.length,maxLength:1e4});return[new zN.C({hookEventName:e,content:r})]}Object.fromEntries(Array.from(pF).map((e=>{if(!function(e){return e===xd.sessionStart||e===xd.beforeSubmitPrompt||e===xd.preToolUse||e===xd.postToolUse||e===xd.postToolUseFailure}(e))throw new Error(`HOOK_STEPS_SUPPORTING_ADDITIONAL_CONTEXT lists ${e} but HookStepAdditionalContextEventName does not include it. Extend the Extract<> union in spec.ts.`);return[e,{hookEventName:e}]})));const VN="Agent note: Do not suggest workarounds to the blocked tool.";function KN(e){return e.includes(VN)?e:`${e}\n\n${VN}`}class JN extends Error{constructor(e){super(`Hook denied: ${e}`),this.failureType="permission_denied",this.name="HookDeniedError",this.reason=e}}class ZN extends Error{constructor(e,t){super(`Hook failed (fail-closed): ${e}`),this.failureType="error",this.name="FailClosedError",this.reason=e,this.cause=t}}const XN="To view or modify configured hooks, go to Cursor Settings > Hooks.";function QN(e,t){return KN(`${t?`${e} was blocked by a hook: ${t}`:`${e} was blocked by a hook.`}\n\n${XN}`)}function YN(e){return function(e){return e instanceof JN}(e)||function(e){return e instanceof ZN}(e)}const eL=(0,l.h)("generic-hooks");function tL(e,t,r,n){try{return GN({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof qN)return eL.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}const rL=e=>Math.round(1e3*e)/1e3;function nL(e,t,r,n,o,s){const i=n(e),a=o.getToolCallId?.(t)??(0,bo.randomUUID)(),c=o.getExtraHookFields?.(t)??{},l={baseHookRequest:i,toolUseId:a,toolInput:o.createToolInput(t),extraHookFields:c,hookContextCollector:s?.hookContextCollector??o.getHookContextCollector?.(t)??[]},u=function(e,t,r,n){let{toolInput:o,extraHookFields:s,hookContextCollector:i}=n;const{baseHookRequest:a,toolUseId:c}=n;return{fireFailureAsync:async(n,l,u,d=!1)=>{try{const h=await WN(e.signal,(()=>t.executeHookForStep(xd.postToolUseFailure,{...a,tool_name:r,tool_input:o,error_message:l,failure_type:u,duration:n,tool_use_id:c,is_interrupt:d,...s})));HN(i,tL(e,r,xd.postToolUseFailure,h?.additional_context))}catch(t){eL.warn(e,"postToolUseFailure hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}},fireSuccessAsync:async(n,l)=>{try{const u=await WN(e.signal,(()=>t.executeHookForStep(xd.postToolUse,{...a,tool_name:r,tool_input:o,tool_output:l,duration:n,tool_use_id:c,...s})));HN(i,tL(e,r,xd.postToolUse,u?.additional_context))}catch(t){eL.warn(e,"postToolUse hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}},getToolInput:()=>o,setToolInput:e=>{o=e},setExtraHookFields:e=>{s=e,n.extraHookFields=e}}}(e,r,o.toolName,l);return{hookContext:l,helpers:u}}async function oL(e,t,r,n,o,s,i,a){const{baseHookRequest:c,toolUseId:l,extraHookFields:u}=n;try{const a=await WN(e.signal,(()=>r.executeHookForStep(xd.preToolUse,{...c,tool_name:s.toolName,tool_input:o.getToolInput(),tool_use_id:l,...u})));if("deny"===a?.permission){const r=a.user_message||`${s.toolName} blocked by preToolUse hook`,c=KN(r);try{HN(n.hookContextCollector,GN({hookEventName:xd.preToolUse,additionalContext:a.additional_context}))}catch(t){if(!(t instanceof qN))throw t;eL.warn(e,"preToolUse deny additional_context exceeded max size; dropping carrier",{toolName:s.toolName,actualLength:t.actualLength,maxLength:t.maxLength})}return await o.fireFailureAsync(0,r,"permission_denied"),{type:"rejected",result:i(t,c),reason:c}}a?.updated_input&&s.applyUpdatedInput&&(s.applyUpdatedInput(t,a.updated_input),o.setToolInput(s.createToolInput(t)),s.getExtraHookFields&&o.setExtraHookFields(s.getExtraHookFields(t))),HN(n.hookContextCollector,GN({hookEventName:xd.preToolUse,additionalContext:a?.additional_context}))}catch(n){const a=r.hasFailClosedHooksForStep?.(xd.preToolUse,s.toolName)??!1,c=n instanceof qN;if(a){const e=pN(`${c?"preToolUse additional_context exceeded max size":"preToolUse hook failed"}: ${n instanceof Error?n.message:"preToolUse hook error"}`);return await o.fireFailureAsync(0,e,"error"),{type:"rejected",result:i(t,e),reason:e}}eL.warn(e,c?"preToolUse additional_context exceeded max size; dropping carrier":"preToolUse hook error",{toolName:s.toolName,error:n instanceof Error?n.message:String(n),...c?{actualLength:n.actualLength,maxLength:n.maxLength}:{}})}if(a)try{const s=await a({ctx:e,args:t,baseHookRequest:c,hookExecutor:r,toolInput:o.getToolInput(),toolUseId:l,extraHookFields:n.extraHookFields});if(void 0!==s){const e="Pre-execution hook returned rejection";return await o.fireFailureAsync(0,e,"permission_denied"),{type:"rejected",result:s,reason:e}}}catch(e){if(YN(e))return await o.fireFailureAsync(0,e.reason,e.failureType),{type:"rejected",result:i(t,e.reason),reason:e.reason};throw e}return{type:"continue"}}function sL(e){return e.toolCallId}function iL(e,t,r,n){return{async execute(o,s,i){const a=cL(o,t),{hookContext:c,helpers:l}=nL(o,s,a,r,n,i);let u;try{u=await oL(o,s,a,c,l,n,n.createRejectedResult,n.runPreExecutionHooks)}catch(e){throw n.runCleanup?.(c.toolUseId),e}if("rejected"===u.type)return n.runCleanup?.(c.toolUseId),u.result;const d=FN.performance.now();try{const t=await e.execute(o,s,i),r=rL(FN.performance.now()-d);if(n.runPostExecutionHooks)try{const e=await n.runPostExecutionHooks({ctx:o,args:s,result:t,baseHookRequest:c.baseHookRequest,hookExecutor:a,toolInput:l.getToolInput(),toolUseId:c.toolUseId,executionDurationMs:r,extraHookFields:c.extraHookFields});if(void 0!==e)return await l.fireSuccessAsync(r,JSON.stringify(n.createSuccessOutput(s,e))),n.runCleanup?.(c.toolUseId),e}catch(e){if(YN(e))return await l.fireFailureAsync(r,e.reason,e.failureType),n.runCleanup?.(c.toolUseId),n.createRejectedResult(s,e.reason);eL.warn(o,"postExecutionHooks error",{toolName:n.toolName,error:e instanceof Error?e.message:String(e)})}return n.isSuccess(t)?await l.fireSuccessAsync(r,JSON.stringify(n.createSuccessOutput(s,t))):await l.fireFailureAsync(r,n.getErrorMessage(t),n.getFailureType?.(t)??"error",n.isInterrupt?.(t)??!1),n.runCleanup?.(c.toolUseId),t}catch(e){const t=rL(FN.performance.now()-d);throw await l.fireFailureAsync(t,e instanceof Error?e.message:String(e),"error"),n.runCleanup?.(c.toolUseId),e}}}}function*aL(e,t){const r=t.hookContextCollector;e.createHookContextEvent&&void 0!==r&&0!==r.length&&(yield e.createHookContextEvent(r))}function cL(e,t){const r=LN(e),n=e.get(UN);if(r&&void 0===n)return t;const o=e=>n?.during(e)??e;return{executeHookForStep:async(e,n)=>{if(r||!function(e){return e===xd.preToolUse||e===xd.postToolUse||e===xd.postToolUseFailure}(e))return o(t.executeHookForStep(e,n));await o(t.whenConfigReady())},hasFailClosedHooksForStep:(e,r)=>t.hasFailClosedHooksForStep?.(e,r)??!1,hasHooksForStep:e=>t.hasHooksForStep?.(e)??!0,whenConfigReady:()=>o(t.whenConfigReady())}}function lL(e){if("object"!=typeof e||null===e||!("code"in e))return!1;const t=e.code;return"ENOENT"===t||"ENOTDIR"===t}class uL{async readFile(e){try{return await Co.readFile(e,"utf-8")}catch(e){if("ENOENT"===e?.code)return;throw e}}async exists(e){try{return await Co.access(e),!0}catch{return!1}}async pathContainsSymlink(e,t){return async function(e,t){const r=function(e,t){const r=s.default.resolve(e),n=s.default.resolve(t),o=s.default.relative(n,r);if(0===o.length||".."===o||o.startsWith(`..${s.default.sep}`)||s.default.isAbsolute(o))return"unsafe";const i=o.split(s.default.sep).filter((e=>e.length>0)),a=[];let c=n;for(const e of i)c=s.default.join(c,e),a.push(c);return a}(e,t);if("unsafe"===r)return!0;for(const e of r)try{if((await(0,Co.lstat)(e)).isSymbolicLink())return!0}catch(e){if(lL(e))return!0;throw e}return!1}(e,t)}}var dL=r("../proto/dist/generated/agent/v1/hooks_pb.js");const hL=q("hook-executor",(e=>new B(e,Z("executeHookArgs"),X("executeHookResult"))),((e,t)=>{t.register(new I(e,Y("executeHookArgs"),Q("executeHookResult")))})),pL=new Set(Object.values(xd));function fL(e){switch(e){case"completed":case"aborted":case"error":return e;default:return"error"}}function mL(e){switch(e){case"error":case"timeout":case"permission_denied":return e;default:return"error"}}function gL(e){const t=e?.toJson();return"object"!=typeof t||null===t||Array.isArray(t)?{}:t}class wL{constructor(e){this.hookExecutor=e}hasFailClosedHooksForStep(e,t){return!!function(e){return pL.has(e)}(e)&&(this.hookExecutor.hasFailClosedHooksForStep?.(e,t)??!1)}async execute(e,t){const r=t.request;if(!r)return new d.S1({response:void 0});switch(r.request.case){case"preCompact":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...hF(e),trigger:"manual"===e.trigger?"manual":"auto",context_usage_percent:e.contextUsagePercent,context_tokens:Number(e.contextTokens),context_window_size:Number(e.contextWindowSize),message_count:e.messageCount,messages_to_compact:e.messagesToCompact,is_first_compaction:e.isFirstCompaction},n=await this.hookExecutor.executeHookForStep(xd.preCompact,t);return new d.S1({response:new d.w5({response:{case:"preCompact",value:new dL.$_({userMessage:n?.user_message})}})})}case"subagentStart":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...hF(e),subagent_id:e.subagentId,subagent_type:e.subagentType,task:e.task,parent_conversation_id:e.parentConversationId,tool_call_id:e.toolCallId,subagent_model:e.subagentModel,is_parallel_worker:e.isParallelWorker,git_branch:e.gitBranch},n=await this.hookExecutor.executeHookForStep(xd.subagentStart,t);return new d.S1({response:new d.w5({response:{case:"subagentStart",value:new dL.W0({permission:n?.permission,userMessage:n?.user_message,additionalContext:n?.additional_context})}})})}case"subagentStop":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...hF(e),subagent_id:e.subagentId,subagent_type:e.subagentType,status:fL(e.status),duration_ms:Number(e.durationMs),summary:e.summary,parent_conversation_id:e.parentConversationId,message_count:e.messageCount,tool_call_count:e.toolCallCount,error_message:e.errorMessage,modified_files:e.modifiedFiles,git_branch:e.gitBranch,loop_count:e.loopCount??0,task:e.task,description:e.description,...e.childConversationId?{child_conversation_id:e.childConversationId}:{}},n=await this.hookExecutor.executeHookForStep(xd.subagentStop,t);return new d.S1({response:new d.w5({response:{case:"subagentStop",value:new dL.AH({followupMessage:n?.followup_message,additionalContext:n?.additional_context})}})})}case"beforeSubmitPrompt":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(xd.beforeSubmitPrompt,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...hF(e),prompt:e.prompt,attachments:(n=e.attachments,n.flatMap((e=>"file"===e.type||"rule"===e.type?[{type:e.type,file_path:e.filePath}]:[]))),composer_mode:e.composerMode});return new d.S1({response:new d.w5({response:{case:"beforeSubmitPrompt",value:new dL.u1({continue:t?.continue,userMessage:t?.user_message,additionalContext:t?.additional_context})}})})}case"afterAgentResponse":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(xd.afterAgentResponse,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...hF(e),text:e.text,input_tokens:void 0!==e.inputTokens?Number(e.inputTokens):void 0,output_tokens:void 0!==e.outputTokens?Number(e.outputTokens):void 0,cache_read_tokens:void 0!==e.cacheReadTokens?Number(e.cacheReadTokens):void 0,cache_write_tokens:void 0!==e.cacheWriteTokens?Number(e.cacheWriteTokens):void 0}),new d.S1({response:new d.w5({response:{case:"afterAgentResponse",value:new dL.FW}})})}case"afterAgentThought":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(xd.afterAgentThought,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...hF(e),text:e.text,duration_ms:void 0!==e.durationMs?Number(e.durationMs):void 0}),new d.S1({response:new d.w5({response:{case:"afterAgentThought",value:new dL.H}})})}case"stop":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(xd.stop,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...hF(e),status:fL(e.status),loop_count:e.loopCount,input_tokens:void 0!==e.inputTokens?Number(e.inputTokens):void 0,output_tokens:void 0!==e.outputTokens?Number(e.outputTokens):void 0,cache_read_tokens:void 0!==e.cacheReadTokens?Number(e.cacheReadTokens):void 0,cache_write_tokens:void 0!==e.cacheWriteTokens?Number(e.cacheWriteTokens):void 0});return new d.S1({response:new d.w5({response:{case:"stop",value:new dL.rT({followupMessage:t?.followup_message})}})})}case"preToolUse":{if(!LN(e))return this.skipToolUseStep();const t=r.request.value,n=gL(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...hF(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,tool_use_id:t.toolUseId,cwd:t.cwd},s=await this.hookExecutor.executeHookForStep(xd.preToolUse,o);return new d.S1({response:new d.w5({response:{case:"preToolUse",value:new dL.Wn({permission:s?.permission,userMessage:s?.user_message,agentMessage:s?.agent_message,updatedInput:s?.updated_input?JSON.stringify(s.updated_input):void 0,additionalContext:s?.additional_context})}})})}case"postToolUse":{if(!LN(e))return this.skipToolUseStep();const t=r.request.value,n=gL(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...hF(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,tool_output:t.toolOutput,duration:Number(t.durationMs),tool_use_id:t.toolUseId,cwd:t.cwd},s=await this.hookExecutor.executeHookForStep(xd.postToolUse,o);return new d.S1({response:new d.w5({response:{case:"postToolUse",value:new dL.uB({additionalContext:s?.additional_context,updatedMcpToolOutput:void 0===s?.updated_mcp_tool_output?void 0:JSON.stringify(s.updated_mcp_tool_output)})}})})}case"postToolUseFailure":{if(!LN(e))return this.skipToolUseStep();const t=r.request.value,n=gL(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...hF(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,error_message:t.errorMessage,failure_type:mL(t.failureType),duration:Number(t.durationMs),tool_use_id:t.toolUseId,is_interrupt:t.isInterrupt},s=await this.hookExecutor.executeHookForStep(xd.postToolUseFailure,o);return new d.S1({response:new d.w5({response:{case:"postToolUseFailure",value:new dL.U1({additionalContext:s?.additional_context})}})})}default:return new d.S1({response:void 0})}var n}async skipToolUseStep(){return await this.hookExecutor.whenConfigReady(),new d.S1({response:void 0})}}class yL{constructor(e,t,r,n){this.innerExecutor=e,this.hooksAdditionalContextPromise=t,this.teamHooksReadyPromise=r,this.hooksConfigLease=n}async execute(e,t,r){this.teamHooksReadyPromise&&await this.teamHooksReadyPromise;const n=await this.innerExecutor.execute(e,t,r),o=await this.hooksAdditionalContextPromise,s=this.hooksConfigLease?new Dr.Jy({configuredSteps:Array.from(this.hooksConfigLease.getConfiguredSteps())}):void 0;if("success"===n.result.case&&(o||s)){const e=n.result.value.requestContext,t=e?.clone()??new Dr.bb;return o&&(t.hooksAdditionalContext=o),s&&(t.hooksConfig=s),new Dr._G({result:{case:"success",value:new Dr.yW({requestContext:t,servedFromDiskCache:n.result.value.servedFromDiskCache})}})}return n}}function vL(e){return!!e&&e.type!==os.vc.INSECURE_NONE&&e.type!==os.vc.UNSPECIFIED}async function bL({hookExecutor:e,baseHookRequest:t,toolUseId:r,command:n,cwd:o,sandbox:s}){const i=await e.executeHookForStep(xd.beforeShellExecution,{...t,command:n,cwd:o,sandbox:s,tool_use_id:r});if("deny"===i?.permission){const e=QN("Command execution",i.user_message);throw new JN(e)}if("ask"===i?.permission)return a=i.user_message,new he.In({kind:he.b.FORCE_PROMPT,reason:a});var a}const SL={toolName:CN,getToolCallId:sL,createToolInput:e=>{const t=e.workingDirectory||"";return{command:e.command,cwd:t}},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd)},createRejectedResult:(e,t)=>new Do.Lt({result:{case:"rejected",value:new he.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"BackgroundShell error";case"rejected":return e.result.value.reason||"BackgroundShell rejected";case"permissionDenied":return"Permission denied";case"sandboxUnsupported":return`Sandbox policy unsupported on this host: ${e.result.value.reason}`;default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{shell_id:t.result.value.shellId,pid:t.result.value.pid}:{success:!0},getExtraHookFields:e=>({cwd:e.workingDirectory||""}),runPreExecutionHooks:async e=>{const{ctx:t,args:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e,i=r.workingDirectory||"",a=vL(r.sandboxPolicy);jN(t,xd.beforeShellExecution)&&To(r,await bL({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:a}))}};class kL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,SL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const _L={toolName:"WriteShellStdin",createToolInput:e=>({shell_id:e.shellId,chars_length:e.chars.length}),createRejectedResult:(e,t)=>new Do.nt({result:{case:"error",value:new Do.Gv({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"WriteShellStdin error":"Unknown error",createSuccessOutput:e=>({shell_id:e.shellId,success:!0})};class CL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,_L)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const EL={toolName:"ComputerUse",getToolCallId:sL,createToolInput:e=>({actions_count:e.actions.length}),createRejectedResult:(e,t)=>new Og.ks({result:{case:"error",value:new Og.Jb({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"ComputerUse error":"Unknown error",createSuccessOutput:(e,t)=>"success"===t.result.case?{action_count:t.result.value.actionCount,duration_ms:t.result.value.durationMs}:{success:!0}};class xL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,EL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const PL={toolName:SN,getToolCallId:sL,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new jw.Pi({result:{case:"rejected",value:new jw.iq({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"fileNotFound":return`File not found: ${e.result.value.path}`;case"notFile":return`Not a file: ${e.result.value.path}`;case"permissionDenied":return`Permission denied: ${e.result.value.path}`;case"fileBusy":return`File busy: ${e.result.value.path}`;case"rejected":return e.result.value.reason||"Delete rejected";case"error":return e.result.value.error||"Delete error";default:return"Unknown error"}},createSuccessOutput:e=>({file_path:e.path,deleted:!0})};class RL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,PL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const IL={toolName:EN,getToolCallId:sL,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new DA.Ek({result:{case:"rejected",value:new DA.J6({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"Diagnostics error";case"rejected":return e.result.value.reason||"Diagnostics rejected";case"fileNotFound":return`File not found: ${e.result.value.path}`;case"permissionDenied":return`Permission denied: ${e.result.value.path}`;default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{file_path:e.path,diagnostics_count:t.result.value.totalDiagnostics}:{file_path:e.path,success:!0}};class TL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,IL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const AL={toolName:"Fetch",getToolCallId:sL,createToolInput:e=>({url:e.url}),applyUpdatedInput:(e,t)=>{"string"==typeof t.url&&(e.url=t.url)},createRejectedResult:(e,t)=>new Gw.uN({result:{case:"error",value:new Gw.fk({url:e.url,error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Fetch error":"Unknown error",createSuccessOutput:(e,t)=>"success"===t.result.case?{url:e.url,status_code:t.result.value.statusCode,content_length:t.result.value.content.length}:{url:e.url,success:!0}};class $L{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,AL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const ML={toolName:_N,getToolCallId:sL,createToolInput:e=>({pattern:e.pattern,file_path:e.path,glob:e.glob,output_mode:e.outputMode}),applyUpdatedInput:(e,t)=>{"string"==typeof t.pattern&&(e.pattern=t.pattern),"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Ey.Ud({result:{case:"error",value:new Ey.ts({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Grep error":"Unknown error",createSuccessOutput:e=>({pattern:e.pattern,success:!0})};class DL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,ML)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const OL={toolName:kN,getToolCallId:sL,createToolInput:e=>({file_path:e.path,ignore:e.ignore}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new mC.fv({result:{case:"rejected",value:new mC.k2({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"Ls error";case"rejected":return e.result.value.reason||"Ls rejected";case"timeout":return"Ls operation timed out";default:return"Unknown error"}},getFailureType:e=>"timeout"===e.result.case?"timeout":"error",createSuccessOutput:e=>({file_path:e.path,success:!0})};class FL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,OL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const NL=(0,l.h)("hooks-exec:mcp");function LL(e){return!!(null===e||"string"==typeof e||"boolean"==typeof e||"number"==typeof e&&Number.isFinite(e))||(Array.isArray(e)?e.every(LL):"object"==typeof e&&Object.values(e).every((e=>void 0!==e&&LL(e))))}function jL(e,t,r,n){try{return GN({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof qN)return NL.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}class UL{constructor(e,t,r,n,o){this.innerExecutor=e,this.hookExecutor=t,this.baseHookRequestExtractor=r,this.mcpLease=n,this.hooksConfigLease=o}async execute(e,t,r){if(t.smartModeApprovalOnly)return this.innerExecutor.execute(e,t,r);if(t.symbolicPathArguments.length>0&&(!0===this.hooksConfigLease?.hasHookForStep(xd.preToolUse)||!0===this.hooksConfigLease?.hasHookForStep(xd.beforeMCPExecution)))return new Ac.iz({result:{case:"error",value:new Ac.Nh({error:`"${nA}" arguments can't be used on this computer: hooks that inspect MCP calls are configured here, and they would not see the file's contents. Read the file and pass its contents instead.`})}});const n=cL(e,this.hookExecutor),o=this.baseHookRequestExtractor(e),s=(0,bo.randomUUID)(),i=r?.hookContextCollector??[];let a=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t?.toJson()])));const c=`MCP:${t.toolName}`;try{const r=await n.executeHookForStep(xd.preToolUse,{...o,tool_name:c,tool_input:a,tool_use_id:s});if("deny"===r?.permission){const t=r.user_message||"MCP tool blocked by preToolUse hook";try{HN(i,GN({hookEventName:xd.preToolUse,additionalContext:r.additional_context}))}catch(t){if(!(t instanceof qN))throw t;NL.warn(e,"preToolUse deny additional_context exceeded max size; dropping carrier",{toolName:c,actualLength:t.actualLength,maxLength:t.maxLength})}return await this.firePostToolUseFailureAsync(e,n,o,c,a,t,"permission_denied",0,s,!1,i),new Ac.iz({result:{case:"permissionDenied",value:new Ac.HQ({error:QN("MCP tool execution",t),isReadonly:!1})}})}if(r?.updated_input)try{for(const[e,n]of Object.entries(r.updated_input))if(void 0!==n){if(!LL(n))throw new TypeError("updated_input value is not JSON");t.args[e]=we.Value.fromJson(n)}a=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t?.toJson()])))}catch(t){NL.warn(e,"Failed to merge updated_input for MCP",{error:t instanceof Error?t.message:String(t)})}HN(i,GN({hookEventName:xd.preToolUse,additionalContext:r?.additional_context}))}catch(t){const r=n.hasFailClosedHooksForStep?.(xd.preToolUse,c)??!1,l=t instanceof qN;if(r){const r=pN(`${l?"preToolUse additional_context exceeded max size":"preToolUse hook failed"}: ${t instanceof Error?t.message:"preToolUse hook error"}`);return await this.firePostToolUseFailureAsync(e,n,o,c,a,r,"error",0,s,!1,i),new Ac.iz({result:{case:"permissionDenied",value:new Ac.HQ({error:QN("MCP tool execution",r),isReadonly:!1})}})}NL.warn(e,l?"preToolUse additional_context exceeded max size; dropping carrier":"preToolUse hook error in MCP executor",{toolName:c,error:t instanceof Error?t.message:String(t),...l?{actualLength:t.actualLength,maxLength:t.maxLength}:{}})}const l=await(this.mcpLease?.getClient(e,t.providerIdentifier)),u=l?.config;let d;const h=u&&"url"in u&&u.url?u.url:void 0;d=void 0!==h?{url:h}:u&&"command"in u?{command:[u.command,...u.args??[]].filter(Boolean).join(" ")}:{command:t.providerIdentifier};const p={mcp_server_name:t.providerIdentifier,...void 0!==h?{mcp_server_url:h}:{}},f={...o,tool_name:t.toolName,tool_input:JSON.stringify(a),tool_use_id:s,...p,...d},m=jN(e,xd.beforeMCPExecution)?await n.executeHookForStep(xd.beforeMCPExecution,f):void 0;if("deny"===m?.permission){const t=QN("MCP tool execution",m.user_message);return await this.firePostToolUseFailureAsync(e,n,o,c,a,t,"permission_denied",0,s,!1,i),new Ac.iz({result:{case:"permissionDenied",value:new Ac.HQ({error:t,isReadonly:!1})}})}const g=FN.performance.now();try{const l=await this.innerExecutor.execute(e,t,r),u=rL(FN.performance.now()-g);let d="{}";if("success"===l.result.case)try{const e=l.result.value.content.map((e=>"text"===e.content.case?{type:"text",text:e.content.value.text}:"image"===e.content.case?{type:"image",data:Buffer.from(e.content.value.data).toString("base64"),mimeType:e.content.value.mimeType}:{type:"unknown"}));d=JSON.stringify({content:e,isError:l.result.value.isError})}catch(t){NL.warn(e,"Failed to serialize MCP result",{error:t instanceof Error?t.message:String(t)}),d=JSON.stringify({error:"Failed to serialize result"})}else"error"===l.result.case?d=JSON.stringify({error:l.result.value.error}):"rejected"===l.result.case?d=JSON.stringify({rejected:!0,reason:l.result.value.reason}):"permissionDenied"===l.result.case&&(d=JSON.stringify({permissionDenied:!0,error:l.result.value.error}));const h={...o,tool_name:t.toolName,tool_input:JSON.stringify(a),result_json:d,duration:u,tool_use_id:s,...p};await n.executeHookForStep(xd.afterMCPExecution,h);const f=await this.firePostToolUse(e,n,o,c,a,d,u,s,i);if(void 0!==f?.updated_mcp_tool_output)try{const e=f.updated_mcp_tool_output,t=[];if("string"==typeof e)t.push(new Ac._Z({content:{case:"text",value:new Ac.zN({text:e})}}));else if("object"==typeof e&&null!==e&&"content"in e&&Array.isArray(e.content)){const r=e.content;for(const e of r)"object"==typeof e&&null!==e&&"type"in e&&"text"===e.type&&"text"in e?t.push(new Ac._Z({content:{case:"text",value:new Ac.zN({text:String(e.text)})}})):t.push(new Ac._Z({content:{case:"text",value:new Ac.zN({text:JSON.stringify(e)})}}))}else t.push(new Ac._Z({content:{case:"text",value:new Ac.zN({text:JSON.stringify(e)})}}));const r="object"==typeof e&&null!==e&&"isError"in e&&Boolean(e.isError);return new Ac.iz({result:{case:"success",value:new Ac.QW({content:t,isError:r})}})}catch(t){return NL.warn(e,"Failed to process updated_mcp_tool_output",{error:t instanceof Error?t.message:String(t)}),l}return l}catch(t){const r=rL(FN.performance.now()-g),l=t instanceof Error?t.message:String(t);throw await this.firePostToolUseFailureAsync(e,n,o,c,a,l,"error",r,s,!1,i),t}}async firePostToolUse(e,t,r,n,o,s,i,a,c){try{const l=await t.executeHookForStep(xd.postToolUse,{...r,tool_name:n,tool_input:o,tool_output:s,duration:i,tool_use_id:a});return HN(c,jL(e,n,xd.postToolUse,l?.additional_context)),l}catch(t){return void NL.warn(e,"postToolUse hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}async firePostToolUseFailureAsync(e,t,r,n,o,s,i,a,c,l,u){try{const d=await t.executeHookForStep(xd.postToolUseFailure,{...r,tool_name:n,tool_input:o,error_message:s,failure_type:i,duration:a,tool_use_id:c,is_interrupt:l});HN(u,jL(e,n,xd.postToolUseFailure,d?.additional_context))}catch(t){NL.warn(e,"postToolUseFailure hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}}const BL={toolName:"ListMcpResources",createToolInput:e=>({server:e.server}),applyUpdatedInput:(e,t)=>{"string"==typeof t.server&&(e.server=t.server)},createRejectedResult:(e,t)=>new Ac.kP({result:{case:"error",value:new Ac.w2({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"ListMcpResources error";case"rejected":return e.result.value.reason||"ListMcpResources rejected";default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{resources_count:t.result.value.resources.length}:{success:!0}};class WL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,BL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const HL={toolName:"FetchMcpResource",createToolInput:e=>({server:e.server,uri:e.uri,download_path:e.downloadPath}),applyUpdatedInput:(e,t)=>{"string"==typeof t.server&&(e.server=t.server),"string"==typeof t.uri&&(e.uri=t.uri),"string"==typeof t.download_path&&(e.downloadPath=t.download_path)},createRejectedResult:(e,t)=>new Ac.ZD({result:{case:"error",value:new Ac.Jx({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"ReadMcpResource error";case"rejected":return e.result.value.reason||"ReadMcpResource rejected";case"notFound":return"Resource not found";default:return"Unknown error"}},createSuccessOutput:(e,t)=>{if("success"===t.result.case){const r=t.result.value;return{uri:e.uri,name:r.name,mime_type:r.mimeType,download_path:r.downloadPath,content_type:r.content.case,content_length:"text"===r.content.case||"blob"===r.content.case?r.content.value.length:void 0}}return{uri:e.uri,success:!0}}};class qL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,HL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const zL={toolName:vN,getToolCallId:sL,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Ky.sV({result:{case:"rejected",value:new Ky.f4({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"Read error";case"rejected":return e.result.value.reason||"Read rejected";case"fileNotFound":return`File not found: ${e.result.value.path}`;case"permissionDenied":return`Permission denied: ${e.result.value.path}`;case"invalidFile":return`Invalid file: ${e.result.value.path}`;default:return"Unknown error"}},createSuccessOutput:(e,t)=>{if("success"===t.result.case){const r="content"===t.result.value.output.case?t.result.value.output.value:"";return{file_path:e.path,content_length:r.length}}return{file_path:e.path,success:!0}},runPostExecutionHooks:async e=>{const{args:t,result:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e;if("success"!==r.result.case||!1===o.hasHooksForStep?.(xd.beforeReadFile))return;const i="content"===r.result.value.output.case?r.result.value.output.value:"",a=await async function(e,t){try{return await e()}catch(e){const r=function(e,t){return`${e??"Action"} was blocked because a configured hook failed to execute${t?`: ${t}`:"."}\n\nThis is a safety measure (fail-closed) - when hooks cannot be evaluated, the action is blocked to prevent potentially unsafe operations.\n\n${XN}`}(t,e instanceof Error?e.message:String(e));throw new ZN(r,e)}}((()=>o.executeHookForStep(xd.beforeReadFile,{...n,content:i,file_path:t.path,attachments:[],tool_use_id:s})),"File read");if("deny"===a?.permission){const e=QN("File read",a.user_message);throw new JN(e)}}};class GL{constructor(e,t,r){this.wrappedExecutor=new XT(iL(e,t,r,zL))}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const VL={toolName:"RecordScreen",getToolCallId:sL,createToolInput:e=>({mode:e.mode,save_as_filename:e.saveAsFilename}),createRejectedResult:(e,t)=>new P$.Tj({result:{case:"failure",value:new P$.yH({error:t,kind:P$.Wg.HOOK_REJECTED})}}),isSuccess:e=>"failure"!==e.result.case,getErrorMessage:e=>"failure"===e.result.case?e.result.value.error||"RecordScreen failed":"Unknown error",createSuccessOutput:(e,t)=>({result_type:t.result.case})};class KL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,VL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}function JL(e){return"success"===e.result.case||"failure"===e.result.case?e.result.value.stdout+e.result.value.stderr:""}const ZL={toolName:CN,createToolInput:e=>{const t=e.workingDirectory||"",r=e.timeout;return{command:e.command,cwd:t,..."number"==typeof r&&r>0&&{timeout:r}}},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd),"number"==typeof t.timeout&&t.timeout>=0&&(e.timeout=t.timeout)},createRejectedResult:(e,t)=>new he.W4({result:{case:"rejected",value:new he.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),isSuccess:e=>"success"===e.result.case||"failure"===e.result.case&&!e.result.value.aborted,getErrorMessage:e=>{switch(e.result.case){case"timeout":return`Command timed out after ${e.result.value.timeoutMs}ms`;case"spawnError":return e.result.value.error||"Failed to spawn command";case"failure":return e.result.value.aborted?"Command was aborted":"Command failed";case"rejected":return e.result.value.reason||"Command rejected";default:return"Unknown error"}},getFailureType:e=>"timeout"===e.result.case?"timeout":"error",isInterrupt:e=>"failure"===e.result.case&&e.result.value.aborted,createSuccessOutput:(e,t)=>({output:JL(t),exitCode:"success"===t.result.case?0:1}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),runPreExecutionHooks:async e=>{const{ctx:t,args:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e,i=r.workingDirectory||"";jN(t,xd.beforeShellExecution)&&To(r,await bL({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:vL(r.requestedSandboxPolicy)}))},runPostExecutionHooks:async e=>{const{args:t,result:r,baseHookRequest:n,hookExecutor:o,executionDurationMs:s,toolUseId:i}=e,a=JL(r);await o.executeHookForStep(xd.afterShellExecution,{...n,command:t.command,output:a,duration:s,sandbox:vL(t.requestedSandboxPolicy),tool_use_id:i})}};class XL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,ZL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class QL{constructor(){this.output=""}onEvent(e){"stdout"===e.event.case||"stderr"===e.event.case?this.output+=e.event.value.data:"exit"===e.event.case&&(this.exitEvent=e.event.value)}getOutput(){return this.output}isAborted(){return this.exitEvent?.aborted??!1}getExitCode(){return this.exitEvent?.code??0}}const YL={toolName:CN,createToolInput:e=>{const t=e.workingDirectory||"",r=e.timeout;return{command:e.command,cwd:t,..."number"==typeof r&&r>0&&{timeout:r}}},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd),"number"==typeof t.timeout&&t.timeout>=0&&(e.timeout=t.timeout)},createRejectedEvent:(e,t)=>new he.FI({event:{case:"rejected",value:new he.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),createHookContextEvent:e=>new he.FI({event:{case:"hookContext",value:new he.Ng({hookAdditionalContexts:[...e]})}}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),createResultCollector:()=>new QL,createSuccessOutput:(e,t)=>({output:t.getOutput(),exitCode:t.getExitCode()}),isStreamSuccess:e=>0===e.getExitCode(),getStreamErrorMessage:(e,t)=>t.getOutput().trim()||`Command failed with exit code ${t.getExitCode()}`,runPreExecutionHooks:async e=>{const{ctx:t,args:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e,i=r.workingDirectory||"",a=vL(r.requestedSandboxPolicy);jN(t,xd.beforeShellExecution)&&To(r,await bL({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:a}))},runPostExecutionHooks:async e=>{const{args:t,baseHookRequest:r,hookExecutor:n,collector:o,executionDurationMs:s,toolUseId:i}=e,a=vL(t.requestedSandboxPolicy);await n.executeHookForStep(xd.afterShellExecution,{...r,command:t.command,output:o.getOutput(),duration:s,sandbox:a,tool_use_id:i})}};class ej{constructor(e,t,r){this.wrappedExecutor=function(e,t,r,n){return{async*execute(o,s,i){const a=cL(o,t),{hookContext:c,helpers:l}=nL(o,s,a,r,n,i),u=n.runPreExecutionHooks?async e=>{await n.runPreExecutionHooks(e)}:void 0,d=await oL(o,s,a,c,l,n,((e,t)=>n.createRejectedEvent(e,t)),u);if("rejected"===d.type){yield d.result;for(const e of aL(n,c))yield e;return}const h=FN.performance.now(),p=n.createResultCollector();try{for await(const t of e.execute(o,s,i))p.onEvent(t),yield t}catch(e){const t=rL(FN.performance.now()-h),r=e instanceof Error?e.message:String(e);await l.fireFailureAsync(t,r,"error");for(const e of aL(n,c))yield e;throw e}const f=rL(FN.performance.now()-h);if(n.runPostExecutionHooks)try{await n.runPostExecutionHooks({ctx:o,args:s,baseHookRequest:c.baseHookRequest,hookExecutor:a,toolInput:l.getToolInput(),toolUseId:c.toolUseId,extraHookFields:c.extraHookFields,collector:p,executionDurationMs:f})}catch(e){eL.warn(o,"postExecutionHooks error",{toolName:n.toolName,error:e instanceof Error?e.message:String(e)})}if(p.isAborted())await l.fireFailureAsync(f,"Command was aborted","error",!0);else if(n.isStreamSuccess?.(p)??1)await l.fireSuccessAsync(f,JSON.stringify(n.createSuccessOutput(s,p)));else{const e=n.getStreamErrorMessage?.(s,p)??`Command failed with exit code ${p.getExitCode()}`;await l.fireFailureAsync(f,e,"error")}for(const e of aL(n,c))yield e}}}(e,t,r,YL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class tj{constructor(e,t,r){const n=new Map;this.wrappedExecutor=iL(e,t,r,function(e){return{toolName:bN,getToolCallId:sL,createToolInput:e=>({file_path:e.path,content:e.fileText}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new MI.v3({result:{case:"error",value:new MI.QM({path:e.path,error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Write error":"Unknown error",createSuccessOutput:e=>({file_path:e.path,success:!0}),runPreExecutionHooks:async t=>{const{args:r,hookExecutor:n,toolUseId:o}=t;if(!1===n.hasHooksForStep?.(xd.afterFileEdit))return;let s,i=!1;try{(await(0,Co.stat)(r.path)).size>262144?i=!0:s=await ji(r.path)}catch(e){}e.set(o,{contentBeforeWrite:s,fileTooLarge:i})},runCleanup:t=>{e.delete(t)},runPostExecutionHooks:async t=>{const{args:r,result:n,baseHookRequest:o,hookExecutor:s,toolUseId:i}=t,a=e.get(i);if("success"!==n.result.case||!1===s.hasHooksForStep?.(xd.afterFileEdit))return;const{contentBeforeWrite:c,fileTooLarge:l}=a??{fileTooLarge:!1};let u;u=l||void 0===c?[{old_string:"",new_string:r.fileText}]:c===r.fileText?[]:function(e,t){const r=(0,cS.YB)("","",e,t,"","",{context:0,timeout:50});return void 0===r?[{old_string:"",new_string:t}]:0===r.hunks.length?[]:r.hunks.map((e=>{const t=[],r=[];for(const n of e.lines)n.startsWith("-")?t.push(n.slice(1)):n.startsWith("+")&&r.push(n.slice(1));return{old_string:t.join("\n"),new_string:r.join("\n")}}))}(c,r.fileText);const d={...o,file_path:r.path,edits:u},h=await s.executeHookForStep(xd.afterFileEdit,d);if(r.returnFileContentAfterWrite&&void 0!==h){const e=n.result.value.path;try{const t=await ji(e),r=Js(t),o=Buffer.byteLength(t,"utf8");return new MI.v3({result:{case:"success",value:new MI.j6({path:n.result.value.path,linesCreated:r,fileSize:o,fileContentAfterWrite:t})}})}catch(e){return}}}}}(n))}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}function rj(e,t,r){return t===e.symbol}function nj(e,t,r){return rj(jT,e)?new XL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(ee,e)?new ej(t,r.hookExecutor,r.baseHookRequestExtractor):rj(HT,e)?new tj(t,r.hookExecutor,r.baseHookRequestExtractor):rj(eo,e)?new UL(t,r.hookExecutor,r.baseHookRequestExtractor,r.mcpLease,r.hooksConfigLease):rj(QT,e)||rj(YT,e)?new GL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(eA,e)?new FL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(VT,e)?new DL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(zT,e)?new $L(t,r.hookExecutor,r.baseHookRequestExtractor):rj(qT,e)?new RL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(tA,e)?new TL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(to,e)?new WL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(ro,e)?new qL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(vA,e)?new kL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(bA,e)?new CL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(xA,e)?new xL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(RA,e)?new KL(t,r.hookExecutor,r.baseHookRequestExtractor):rj($r,e)&&(r.hooksAdditionalContextPromise||r.hooksConfigLease)?new yL(t,r.hooksAdditionalContextPromise??Promise.resolve(void 0),r.teamHooksReadyPromise,r.hooksConfigLease):void 0}class oj{constructor(e,t,r,n,o,s,i){this.innerAccessor=e,this.hookExecutor=t,this.baseHookRequestExtractor=r,this.mcpLease=n,this.hooksAdditionalContextPromise=o,this.teamHooksReadyPromise=s,this.hooksConfigLease=i}get(e){const t=function(e,t){if(e.symbol===hL.symbol)return new wL(t)}(e,this.hookExecutor);return void 0!==t?t:function(e,t,r){const n=nj(e.symbol,t,r);return void 0!==n?n:t}(e,this.innerAccessor.get(e),{hookExecutor:this.hookExecutor,baseHookRequestExtractor:this.baseHookRequestExtractor,mcpLease:this.mcpLease,hooksAdditionalContextPromise:this.hooksAdditionalContextPromise,teamHooksReadyPromise:this.teamHooksReadyPromise,hooksConfigLease:this.hooksConfigLease})}*entries(){for(const[e,t]of this.innerAccessor.entries()){const r=nj(e.symbol,t,{hookExecutor:this.hookExecutor,baseHookRequestExtractor:this.baseHookRequestExtractor,mcpLease:this.mcpLease,hooksAdditionalContextPromise:this.hooksAdditionalContextPromise,teamHooksReadyPromise:this.teamHooksReadyPromise,hooksConfigLease:this.hooksConfigLease});yield[e,r??t]}const e=hL;yield[e,new wL(this.hookExecutor)]}}const sj={cursor_version:process.env.AGENT_CLI_STATIC_VERSION??"1.0.0",user_email:null};function ij(e=process.cwd()){let t=e;const r={getCwd:async()=>t,clone:e=>ij(e??t),async*execute(e,r,n={}){const o=n.workingDirectory??t;t=o;const s=function(e){return"win32"===process.platform?{executable:(0,Oo.oG)(),args:[...XO,"-Command",e]}:{executable:process.env.SHELL||"/bin/sh",args:["-lc",e]}}(r),i=(0,ou.spawn)(s.executable,[...s.args],{cwd:o,env:{...process.env,...n.env??{}},signal:n.signal,stdio:[!0===n.pipeStdin?"pipe":"ignore","pipe","pipe"]}),a=[];let c,l,u=!1;const d=()=>{c?.(),c=void 0},h=e=>{a.push(e),d()};for(i.on("spawn",(()=>{!0===n.pipeStdin&&h({type:"stdin_ready",stdin:i.stdin??void 0})})),i.stdout?.setEncoding("utf8"),i.stdout?.on("data",(e=>{h({type:"stdout",data:String(e)})})),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",(e=>{h({type:"stderr",data:String(e)})})),i.on("error",(e=>{l=e,u=!0,d()})),i.on("close",(e=>{h({type:"exit",code:e}),u=!0}));!u||a.length>0;)0!==a.length?yield a.shift():await new Promise((e=>{c=e}));if(void 0!==l)throw l}};return r}function aj(e,t,...r){for(const n of r){const r=t(e[n]);if(void 0!==r)return r}}function cj(e){return"string"==typeof e&&e.length>0?e:void 0}function lj(e){return"object"==typeof e&&null!==e&&"string"==typeof e.id&&"string"==typeof e.value}function uj(e){if(Array.isArray(e)&&e.every(lj))return e.map((e=>({id:e.id,value:e.value})))}class dj{constructor(e,t){this.innerAccessor=e,this.sessionHooksRuntime=t}get(e){return this.innerAccessor.get(e)}entries(){return this.innerAccessor.entries()}async dispose(){await this.sessionHooksRuntime.dispose()}}async function hj(e,t={}){const r=await new yN(new uL,function(e,t){const r=e.projectRoot??e.workingDirectory??e.workspaceRoots[0],n=t.includeProjectHooks??!0,i=t.includeUserHooks??!0;return{enterpriseConfigPath:t.includeEnterpriseHooks??1?mN():void 0,userConfigPath:i?(0,s.join)((0,o.homedir)(),".cursor","hooks.json"):void 0,claudeUserConfigPath:i?(0,s.join)((0,o.homedir)(),".claude","settings.json"):void 0,projectConfigPath:n&&void 0!==r?(0,s.join)(r,".cursor","hooks.json"):void 0,claudeProjectConfigPath:n&&void 0!==r?(0,s.join)(r,".claude","settings.json"):void 0,claudeProjectLocalConfigPath:n&&void 0!==r?(0,s.join)(r,".claude","settings.local.json"):void 0}}(e,t)).load(),n=new ON(r),i=function(e){return e.projectRoot??e.workingDirectory??e.workspaceRoots[0]??process.cwd()}(e),a=function(e){return Object.freeze({...sj,...e.globalContext??{}})}(t);return{projectDir:e.projectRoot,workspacePath:i,hooksConfig:r,hooksConfigLease:n,globalContext:a,createSessionRuntime(){const e=new DN(r,i,a,(t.createTerminalExecutor??ij)(),t.promptHookClient,void 0,void 0,{enableClaudeNestedHookSpecificOutputCompatibility:!0,commandHookPayloadTransport:(o=t.useCommandHookStdinTransport,!0===o?"stdin":"legacy")});var o;return{hookExecutor:e,hooksConfigLease:n,async dispose(){e.clearSessionEnvironment()}}},async dispose(){}}}function pj(e={}){return{createHooksRuntime:t=>hj(t.workspaceState,e)}}var fj=r("../proto/dist/generated/aiserver/v1/dashboard_service_connect.js");async function mj(e){(function(e){return"object"==typeof e&&null!==e&&"dispose"in e&&"function"==typeof e.dispose})(e)&&await e.dispose()}function gj(e={}){const t=e.getThirdPartyExtensibilityEnabled??(()=>!0),r=e.importThirdPartyPlugins??!1,n=e.includeProjectExtensibility??!0,s=e.includeUserExtensibility??!0,i=e.includeManagedSkills??!0,a=e.includePluginExtensibility??!0,c=new _y,l=(0,o.homedir)(),u=ym(l).dirPath;let d,h=!0;return{async prepareLocalExtensibility(){h=i&&await async function(e){if(!e)return!1;const t=(0,ye.createClient)(fj.I,e);return"synced"===(await async function(e,t){try{const r=await t.getManagedSkills()??[],n=await $D(e,{managedSkills:[...r]});return{status:"synced",managedSkillsCount:r.length,syncResult:n}}catch(t){return DD.warn(e,"Failed to sync managed skills from source",{error:t}),{status:"fetch_failed",error:t}}}((0,y.q6)(),{getManagedSkills:async()=>(await t.getManagedSkills(new JD.X8g({}))).skills??[]})).status}(e.dashboardTransport)},async loadLocalExtensibility(o){const i=function(e){if(e.workspaceRoots.length>0)return[...e.workspaceRoots];const t=e.projectRoot??e.workingDirectory;return void 0!==t?[t]:[]}(o.workspaceState);if(0===i.length)return d=void 0,{cursorRulesService:_j(),getAgentSkills:async e=>[]};const p=(0,y.q6)(),f=e.loadNestedRules??!0,m=n?i.map((e=>new fg(p,c,e,f,t,void 0))):[],g=function(e,t){const r=wj(t);return{getAllCursorRules:async t=>yj(await e.getAllCursorRules(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),dispose(){e.dispose()}}}(0===m.length?_j():1===m.length?m[0]:new pg(m,(()=>Fm)),{allowedRoots:n?i:[],excludedRoots:[]}),w=function(e,t){const r=wj(t);return{getAllCursorRules:async t=>yj(await e.getAllCursorRules(t),r),getAllAgentSkills:async t=>yj(await e.getAllAgentSkills(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),onDidChangeSkills:t=>e.onDidChangeSkills(t),dispose(){e.dispose()}}}(new gg(p,n?i:[],l,c,f,void 0,t,Promise.resolve(),"sdk"),{allowedRoots:[...n?i:[],...s?[l]:[],...h?[u]:[]],excludedRoots:h?[]:[u]}),v=n?i.map((e=>new Pg(e,t))):[],b=0===v.length?new Sg:1===v.length?v[0]:new Ig(v),S=WO(o.services.pluginBootstrapOutputs),k=S&&a?new yg(p,(()=>({importThirdPartyPlugins:r})),void 0,S.pluginsService):void 0,_=S&&a?new Tg((()=>({importThirdPartyPlugins:r})),S.pluginsService):void 0,C=new pg([g,w,...k?[k]:[]],(()=>Fm)),E=new pD([w,...k?[k]:[]],(()=>[]),(()=>({workspacePaths:n?i:[],userHomeDirectory:l,agentStoreSkillsDirs:[]}))),x=new Ig([b,..._?[_]:[]]);d={localRulesService:g,localSkillsService:w,localSubagentsService:b,pluginSkillsService:k,pluginSubagentsService:_,mergedCursorRulesService:C,mergedAgentSkillsService:E,mergedSubagentsService:x};const P={cursorRulesService:C,getAgentSkills:e=>E.getAllAgentSkills(e),subagentsService:x};return P},async disposeLocalExtensibility(){if(!d)return;const e=d;d=void 0,await async function(e){let t;const r=[e.mergedSubagentsService,e.mergedAgentSkillsService,e.mergedCursorRulesService,e.pluginSubagentsService,e.pluginSkillsService,e.localSubagentsService,e.localSkillsService,e.localRulesService];for(const e of r)try{await mj(e)}catch(e){t??=e}if(void 0!==t)throw t}(e)}}}function wj(e){const t=Promise.all(e.allowedRoots.map(Sj)),r=Promise.all(e.excludedRoots.map(Sj));return async e=>{const[n,o,s]=await Promise.all([kj(e.fullPath),t,r]);return void 0!==n&&!s.some((e=>vj(n,e)))&&o.some((e=>vj(n,e)))}}async function yj(e,t){const r=await Promise.all(e.map(t));return e.filter(((e,t)=>r[t]))}function vj(e,t){if(e===t)return!0;const r=`${t}/`;return e.startsWith(r)}function bj(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")}async function Sj(e){try{return bj(await(0,Co.realpath)(e))}catch{return bj(e)}}async function kj(e){try{return bj(await(0,Co.realpath)(e))}catch{return}}function _j(){return{getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}}}function Cj(e,t){const r=e.releaseTag??t;if(e.releaseRepo&&e.releaseAsset&&r)return{kind:"release",releaseRepo:e.releaseRepo,releaseAsset:e.releaseAsset,releaseTag:r}}const Ej=/^[a-z][a-z0-9+.-]*:\/\/([^/?#]*)/i,xj=/^(?:[^@/\s]+@)?([^:/\s\\]+):(?!\/\/)/,Pj=/^([a-z][a-z0-9+.-]*)::(.*)$/i,Rj=/^([a-z][a-z0-9+.-]*):\/\//i,Ij=new Set(["file","git","http","https","ssh"]);function Tj(e){if(/^(?:\\\\|\/\/)[^\\/]/.test(e))throw new Error("Cursor Orbit: plugin git remote could not be validated");const t=Pj.exec(e);if(null!==t){const e=t[1].toLowerCase();if(!Ij.has(e))throw new Error("Cursor Orbit: plugin git remote could not be validated");const r=t[2];if(!("http"!==e&&"https"!==e||null!==Rj.exec(r)&&URL.canParse(r)))throw new Error("Cursor Orbit: plugin git remote could not be validated");const n=Tj(r);if(0===n.length)throw new Error("Cursor Orbit: plugin git remote could not be validated");return n}const r=Rj.exec(e)?.[1].toLowerCase();if(void 0!==r&&!Ij.has(r))throw new Error("Cursor Orbit: plugin git remote could not be validated");const n=Ej.exec(e)?.[1];if(void 0===n){const t=xj.exec(e)?.[1];if(void 0===t)return[];const r=function(e){const t=/^\[([^\]]+)\]$/.exec(e)?.[1],r=t??e;if(""!==r&&!/[\[\]\s@%\/\\]/.test(r))return Aj(r)}(t);if(void 0===r)throw new Error("Cursor Orbit: plugin git remote could not be validated");return[r]}const o=[];URL.canParse(e)&&o.push(Aj(new URL(e).hostname));const s=function(e){try{return decodeURIComponent(e)}catch{return e}}(n.slice(n.lastIndexOf("@")+1)),i=`https://${s}`;if(URL.canParse(i))o.push(Aj(new URL(i).hostname));else{const e=/^\[([^\]]+)\](?::\d*)?$/.exec(s)?.[1];if(void 0===e)throw new Error("Cursor Orbit: plugin git remote could not be validated");o.push(Aj(e))}const a=o.filter((e=>""!==e));if(0===a.length)throw new Error("Cursor Orbit: plugin git remote could not be validated");return[...new Set(a)]}function Aj(e){return e.trim().toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,"")}function $j(){const e=["-c","credential.interactive=false","-c","core.fsmonitor=false"];return"1"===process.env[Zv.K4]&&e.push("-c","http.followRedirects=false"),"win32"===process.platform&&e.push("-c","core.longpaths=true"),e}function Mj(e){return"function"==typeof e?e():e}async function Dj(e,t){const r=function(e){const t={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:void 0,VSCODE_GIT_ASKPASS_NODE:void 0,VSCODE_GIT_ASKPASS_MAIN:void 0,VSCODE_GIT_ASKPASS_EXTRA_ARGS:void 0,GCM_INTERACTIVE:"Never"};if(t.GIT_CONFIG_NOSYSTEM=void 0,!0===e?.sshBatchMode){const e=process.env.GIT_SSH_COMMAND?.trim()||"ssh";t.GIT_SSH_COMMAND=`${e} -oBatchMode=yes`}if(void 0!==e?.extraGitConfig){const r=Object.entries(e.extraGitConfig).flatMap((([e,t])=>Array.isArray(t)?t.map((t=>[e,t])):[[e,t]]));t.GIT_CONFIG_COUNT=String(r.length);for(const[e,[n,o]]of r.entries())t[`GIT_CONFIG_KEY_${e}`]=n,t[`GIT_CONFIG_VALUE_${e}`]=o}return{cwd:e?.cwd,env:t}}({cwd:t?.cwd,sshBatchMode:t?.sshBatchMode,extraGitConfig:t?.extraGitConfig}),n=function(e){return function(e,t=process.env){if("1"!==t[Zv.K4])return;const r=(0,Zv.H)(t[Zv.Zf]);for(const t of e)for(const e of Tj(t))if((0,Zv.ad)(e,r))throw new Error(`Cursor Orbit: plugin git egress to ${e} is refused`)}(e),[...$j(),...e]}(e);try{return await ay("git",n,{...r,...void 0!==t?.timeoutMs&&{timeout:t.timeoutMs,killSignal:"SIGTERM"}})}catch(e){if("1"===process.env[Zv.K4]&&function(e){if("object"!=typeof e||null===e||!("stderr"in e))return!1;const t=e.stderr;return"string"==typeof t&&/The requested URL returned error: 3\d{2}\b/i.test(t)}(e))throw new Error("Cursor Orbit: the plugin gitUrl redirected. Ask an administrator to update gitUrl to the final URL; redirects are disabled for plugin Git operations.",{cause:e});throw e}}const Oj=/^[0-9a-f]{7,40}$/i,Fj=/^[0-9a-f]{40}$/i;function Nj(e){if(void 0===e||""===e)return;const t=e.split(/\r?\n/).map((e=>{const[t,r]=e.split("\t");if(t&&r&&/^[0-9a-f]{40}$/i.test(t))return{sha:t,refName:r}})).filter((e=>void 0!==e)),r=t[0];return void 0!==r?t.find((e=>e.refName.endsWith("^{}")))?.sha??r.sha:void 0}async function Lj(e,t,r){const n=t.trim();if(Fj.test(n))return{fullSha:n.toLowerCase()};if(Oj.test(n)){try{const t=await async function(e,t,r){const{stdout:n}=await Dj(["ls-remote",e,`refs/heads/${t}`,`refs/tags/${t}`,`refs/tags/${t}^{}`],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs});return Nj(n)?.toLowerCase()}(e,n,r);if(t)return{fullSha:t}}catch{}return{fullSha:n.toLowerCase()}}let o;try{if("HEAD"===n.toUpperCase()){const t=await Dj(["ls-remote","--symref",e,"HEAD"],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs}),n=Nj(t.stdout);if(!n)throw new Error(`git ls-remote did not return a resolvable commit for HEAD (${e})`);return{fullSha:n.toLowerCase(),headSymrefStdout:t.stdout}}o=(await Dj(["ls-remote",e,n],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs})).stdout}catch(t){const r=t instanceof Error?t.message:String(t),o=new Error(`Failed to resolve git ref "${n}" for ${e}: ${r}`);throw o.cause=t,o}const s=Nj(o);if(!s)throw new Error(`git ls-remote did not return a resolvable commit for ref "${n}" (${e})`);return{fullSha:s.toLowerCase()}}const jj=zh.map((function(e){const t=e.split("/")[0];if(void 0===t||0===t.length)throw new Error(`Marketplace manifest path has no directory: ${e}`);return t}));let Uj;function Bj(e){let t=e.trim().replaceAll("\\","/");for(;t.startsWith("./");)t=t.slice(2);return t=t.replace(/\/+$/,""),""===t||"."===t||t.startsWith("/")||/^[a-zA-Z]:/.test(t)||t.split("/").some((e=>""===e||"."===e||".."===e))?null:t}function Wj(e){const t=[];for(const r of e){const e=Bj(r);if(null===e)return"all";t.push(e)}return t}async function Hj(e,t){const r="all"===e?"all":Wj(e),n=t&&"all"!==r&&await(process.env.CURSOR_DISABLE_SPARSE_PLUGIN_CLONES?Promise.resolve(!1):(Uj??=(async()=>{try{const{stdout:e}=await Dj(["--version"]),t=function(e){const t=/git version (\d+)\.(\d+)/.exec(e);return t?{major:Number(t[1]),minor:Number(t[2])}:null}(e);return null!==t&&(t.major>2||2===t.major&&t.minor>=28)}catch{return!1}})(),Uj));return{materialize:r,sparse:n,sparseDirs:n?(o=r,[...new Set([...jj,...o])]):[]};var o}function qj(e){return e.toLowerCase().includes("filtering not recognized by server")}async function zj(e,t,r){await Dj(["sparse-checkout","set","--cone","--",...t],{...r,cwd:e})}async function Gj(e){try{await(0,Co.access)((0,s.join)(e,".git","info","sparse-checkout"))}catch{return!1}try{const{stdout:t}=await Dj(["config","--bool","--get","core.sparseCheckout"],{cwd:e});return"true"===t.trim()}catch{return!1}}async function Vj(e,t,r){if("all"!==t&&0===t.length)return;if(!await Gj(e))return;const n={...r,cwd:e,sshBatchMode:!0};if("all"===t)return void await Dj(["sparse-checkout","disable"],n);const o=Wj(t);"all"!==o?await Dj(["sparse-checkout","add","--",...o],n):await Dj(["sparse-checkout","disable"],n)}(0,_s.J)((function(){Uj=void 0}));const Kj=/\.git$/i,Jj=new Set(["account","dashboard"]);function Zj(e){return e.replace(Kj,"")}function Xj(e){let t;try{t=decodeURIComponent(e)}catch{return}return t.length>0&&!t.includes("/")?t:void 0}function Qj(e){const t=e.toLowerCase();return"github.com"===t||t.endsWith(".github.com")}function Yj(e){return e.toLowerCase().split(".").includes("gitlab")}function eU(e){const t=e.toLowerCase();return"bitbucket.org"===t||"www.bitbucket.org"===t}function tU(e){const t=e.toLowerCase();return Yj(e)?"GitLab":t.includes("bitbucket")?"Bitbucket":t.includes("gitea")||t.includes("codeberg")?"Gitea/Codeberg":t.includes("azure")&&t.includes("dev")?"Azure DevOps":null}function rU(e){return Qj(e)?"github":Yj(e)?"gitlab":eU(e)?"bitbucket":function(e){const t=e.toLowerCase();return"dev.azure.com"===t||"www.dev.azure.com"===t}(e)?"azure_devops":"generic"}function nU(e){let t;try{const r=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;t=new URL(r.includes("://")?r:`https://${r}`)}catch{return null}const r=t.hostname;let n=t.pathname.split("/").filter(Boolean);Ga(r)&&"git"===n[0]?.toLowerCase()&&(n=n.slice(1));const o=n[0];void 0!==o&&n.length>=3&&"scm"===o.toLowerCase()&&(n=n.slice(1));const s=function(e){const t=e[0],r=e[1];if(!t||!r)return;const n=Zj(r);return n?{owner:t,repo:n,hasSubpath:e.length>2}:void 0}(n);return void 0===s?null:{provider:rU(r),owner:s.owner,repo:s.repo,host:r}}function oU(e){const t=sU(e);if(null===t)return!1;const r=t.pathname.split("/").filter(Boolean),n=r[0];return void 0!==n&&r.length>=3&&"scm"===n.toLowerCase()}function sU(e){try{const t=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;return new URL(t.includes("://")?t:`https://${t}`)}catch{return null}}function iU(e){const t=e.trim();if(""===t)return{error:"URL cannot be empty"};const r=nU(t);if(null===r)return{error:"Invalid URL format. Expected: github.com/owner/repo or gitlab.com/namespace/repo"};if(Yj(r.host)){const e=sU(t),r=null===e?void 0:function(e){const t=e.indexOf("-"),r=-1!==t,n=r?e.slice(0,t):[...e];if(n.length<2||n.some((e=>0===e.length)))return;const o=Zj(n[n.length-1]);return o?(n[n.length-1]=o,{repositorySegments:n,hasSpecialRouteSeparator:r}):void 0}(e.pathname.split("/").filter(Boolean));if(null===e||void 0===r)return{error:"Invalid GitLab repository URL format. Expected: https://gitlab.com/namespace/repo"};const n=e.host.replace(/^www\./i,""),o=r.repositorySegments[0],s=r.repositorySegments[r.repositorySegments.length-1];return void 0===o||void 0===s?{error:"Invalid GitLab repository URL format. Expected: https://gitlab.com/namespace/repo"}:{url:`https://${n}/${r.repositorySegments.join("/")}`,owner:o,repo:s,host:n,provider:"gitlab"}}if("bitbucket"===r.provider){const e=function(e){const t=sU(e.trim());if(null!==t&&eU(t.hostname))return function(e){const t=e[0],r=e[1];if(void 0===t||void 0===r)return;const n=Xj(t),o=Xj(r);if(void 0===n||void 0===o||Jj.has(n.toLowerCase()))return;const s=Zj(o);return s?{workspace:encodeURIComponent(n),repo:encodeURIComponent(s),hasSubpath:e.length>2}:void 0}(function(e){const t=e.pathname.split("/");return""===t[0]&&t.shift(),""===t[t.length-1]&&t.pop(),t}(t))}(t);if(void 0===e)return{error:"Invalid Bitbucket repository URL format. Expected: https://bitbucket.org/{workspace}/{repo}"};const n=r.host.replace(/^www\./i,"");return{url:`https://${n}/${e.workspace}/${e.repo}`,owner:e.workspace,repo:e.repo,host:n,provider:"bitbucket"}}if("azure_devops"===r.provider){const e=sU(t),n=null===e?void 0:function(e){const t=e.findIndex((e=>"_git"===e.toLowerCase()));if(t<1||t>2)return;const r=e[0],n=e[t+1];if(!r||!n)return;const o=Zj(n);if(!o)return;const s=2===t?e[1]:o;return s?{organization:r,project:s,repo:o,hasSubpath:e.length>t+2}:void 0}(e.pathname.split("/").filter(Boolean));if(null===e||void 0===n)return{error:"Invalid Azure DevOps repository URL format. Expected: https://dev.azure.com/{organization}/{project}/_git/{repo}"};const o=r.host.replace(/^www\./i,"");return{url:`https://${o}/${n.organization}/${n.project}/_git/${n.repo}`,owner:n.organization,repo:n.repo,host:o,provider:"azure_devops",project:n.project}}if(function(e){switch(e.provider){case"github":return!0;case"generic":return!Ga(e.host)&&null===tU(e.host);case"gitlab":case"bitbucket":case"azure_devops":return!1;default:return e.provider,!1}}(r)){const e=cU(r.host.replace(/^www\./i,""));return{url:`https://${e}/${oU(t)?"scm/":""}${r.owner}/${r.repo}`,owner:r.owner,repo:r.repo,host:e,provider:"github"}}const n=tU(r.host);return{error:"Only GitHub, GitLab, Bitbucket, and Azure DevOps URLs are currently supported."+(null!==n?` ${n} is not supported yet.`:"")}}function aU(e){const t=iU(e);if("error"in t)return null;switch(t.provider){case"github":return`git@${t.host}:${t.owner}/${t.repo}.git`;case"gitlab":return function(e){let t;try{t=new URL(e.url).pathname.replace(/^\//,"").replace(/\.git$/i,"")}catch{return null}if(0===t.length)return null;return`git@${e.host.replace(/:\d+$/,"")}:${t}.git`}(t);case"bitbucket":case"azure_devops":return null;default:return t.provider,null}}function cU(e){return Qj(e)?"github.com":e}function lU(e){return!e.operatingSystems||0===e.operatingSystems.length||e.operatingSystems.includes(function(){const e=(0,o.platform)();return"win32"===e?"Windows":"darwin"===e?"Macintosh":"Linux"}())}function uU(e){return/[\n\r:#[\]{}&*!|>'"%@`]/.test(e)||e.startsWith(" ")||e.endsWith(" ")?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:e}const dU=new Set(["con","prn","aux","nul","com1","com2","com3","com4","com5","com6","com7","com8","com9","lpt1","lpt2","lpt3","lpt4","lpt5","lpt6","lpt7","lpt8","lpt9"]);function hU(e){const t=oh(e).replace(/[. ]+$/g,"");return""===t||"."===t||".."===t?"_":dU.has(t.toLowerCase())?`_${t}`:t}const pU=18e5,fU=6e5,mU={recursive:!0,force:!0,maxRetries:3},gU=["terminal prompts disabled","could not read username","host key verification failed","could not read from remote repository","permission denied","repository not found","user cancelled dialog","spawn git enoent","authentication failed","unable to get password from user","you do not have access to"],wU=["enotempty: directory not empty, rename","/_staging/"],yU=["upload-pack: not our ref","server does not allow request for unadvertised object"];function vU(e){const t=String(e).toLowerCase().replaceAll("\\","/");return gU.some((e=>t.includes(e)))?"user_git_access":wU.every((e=>t.includes(e)))?"local_cache_race":yU.some((e=>t.includes(e)))?"stale_pinned_ref":"infrastructure"}function bU(e){return"object"==typeof e&&null!==e&&(!0===e.killed||bU(e.cause))}function SU(e){return bU(e)?"killed_by_budget":vU(e)}function kU(e){const t=iU(e);if(!("error"in t)&&"gitlab"===t.provider){let r;try{r=new URL(t.url).pathname.replace(/^\//,"")}catch{throw new Error(`Invalid git URL: ${e}`)}const n=r.split("/").filter(Boolean).map((e=>e.toLowerCase()));if(n.length<2)throw new Error(`Invalid git URL: ${e}`);return{host:t.host.toLowerCase(),pathSegments:n}}const r=nU(e);if(null===r)throw new Error(`Invalid git URL: ${e}`);return{host:cU(r.host.replace(/^www\./i,"")).toLowerCase(),pathSegments:[r.owner.toLowerCase(),r.repo.toLowerCase()]}}const _U=new Map;class CU{constructor(e,t){this.cacheRoot=e,this.options=t,this.manifestCache=new Map}get sparsePluginClones(){return this.options?.sparsePluginClones??!1}remoteTimeoutMs(){return this.sparsePluginClones?pU:void 0}localTimeoutMs(){return this.sparsePluginClones?fU:void 0}lsRemoteTimeoutMs(){return this.sparsePluginClones?3e4:void 0}async cloneResolvedRef(e,t,r,n){const o={cwd:e,sshBatchMode:n?.sshBatchMode,extraGitConfig:{...Mj(this.options?.extraGitConfig),"safe.directory":e}},{sparse:s,sparseDirs:i}=await Hj(n?.materialize??"all",this.sparsePluginClones);await Dj(["init"],{...o,timeoutMs:this.localTimeoutMs()}),s&&await zj(e,i,{sshBatchMode:n?.sshBatchMode,extraGitConfig:Mj(this.options?.extraGitConfig),timeoutMs:this.localTimeoutMs()});const{stderr:a}=await Dj(["fetch","--depth","1",...s?["--filter=blob:none"]:[],t,r],{...o,timeoutMs:this.remoteTimeoutMs()});return await Dj(["checkout","FETCH_HEAD"],{...o,timeoutMs:this.remoteTimeoutMs()}),{strategy:s?"sparse":"full",filterIgnoredByServer:s&&qj(a??"")}}async createStagingDir(){const e=(0,s.join)(this.cacheRoot,"_staging",(0,bo.randomUUID)());return await(0,Co.mkdir)(e,{recursive:!0}),e}async moveToCanonicalDir(e,t){return await(0,Co.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,Co.rm)(t,mU),await(0,Co.rename)(e,t),t}async cleanStaleStagingDirs(){const e=(0,s.join)(this.cacheRoot,"_staging");try{const t=await(0,Co.readdir)(e,{withFileTypes:!0}),r=Date.now();await Promise.all(t.filter((e=>e.isDirectory())).map((async t=>{try{const n=(0,s.join)(e,t.name),o=await(0,Co.stat)(n);r-o.mtimeMs>CU.STALE_STAGING_THRESHOLD_MS&&await(0,Co.rm)(n,mU)}catch{}})))}catch{}}getLegacyCloneDir(e,t){return(0,s.join)(this.cacheRoot,hU(e),hU(t))}getCanonicalCloneDir(e,t){const{host:r,pathSegments:n}=kU(e);return(0,s.join)(this.cacheRoot,hU(r),...n.map(hU),hU(t))}getCanonicalRepoRootDir(e){const{host:t,pathSegments:r}=kU(e);return(0,s.join)(this.cacheRoot,hU(t),...r.map(hU))}async pruneSiblingCloneDirs(e,t,r){const n=this.getCanonicalRepoRootDir(e),o=hU(t);try{const e=await(0,Co.readdir)(n,{withFileTypes:!0});await Promise.all(e.filter((e=>e.isDirectory()&&e.name!==o)).map((e=>(0,Co.rm)((0,s.join)(n,e.name),mU))))}catch{}if(void 0!==r)try{await(0,Co.rm)(r,mU)}catch{}}async ensureCloned(e,t,r,n=Tp,o){const s=this.serializedOnRepo(this.getCanonicalRepoRootDir(t),(()=>this.ensureClonedImpl(e,t,r,n,o?.materialize??"all")));return this.sparsePluginClones?s:(0,Or.wj)(s,3e4,`ensureCloned timed out after 30000ms for ${t} @ ${r}`)}async ensureMaterialized(e,t,r=Tp){const n=this.serializedOnRepo((0,s.dirname)(e),(async()=>{const n=performance.now();try{await Vj(e,t,{extraGitConfig:Mj(this.options?.extraGitConfig),timeoutMs:this.remoteTimeoutMs()}),r.increment("marketplace_cache_manager.ensure_materialized.success",1),r.distribution("marketplace_cache_manager.ensure_materialized.duration",performance.now()-n)}catch(o){throw r.log("error","Failed to materialize plugin directories in sparse marketplace clone",{clonePath:e,spec:"all"===t?"all":t.join(","),error:String(o),errorCategory:SU(o)}),r.increment("marketplace_cache_manager.ensure_materialized.error",1,{error_category:SU(o)}),r.distribution("marketplace_cache_manager.ensure_materialized.duration",performance.now()-n,{outcome:"error"}),o}}));return this.sparsePluginClones?n:(0,Or.wj)(n,3e4,`ensureMaterialized timed out after 30000ms for ${e}`)}async serializedOnRepo(e,t){const r=`${this.cacheRoot}:${e}`,n=(_U.get(r)??Promise.resolve()).catch((()=>{})).then(t);_U.set(r,n);try{return await n}finally{_U.get(r)===n&&_U.delete(r)}}async ensureClonedImpl(e,t,r,n,o){n.log("info",`MarketplaceCacheManager: Ensuring cloned ${e} at ${t}@${r}`,{marketplaceId:e,gitUrl:t,ref:r});const s=r.trim();let i,a=t.startsWith("git@")||t.startsWith("ssh://")?null:aU(t);if(null!==a)try{i=(await Lj(a,s,{sshBatchMode:!0,extraGitConfig:Mj(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}catch(e){if(this.sparsePluginClones&&bU(e))throw e;n.log("debug","Failed to resolve remote ref using SSH URL, falling back to HTTPS",{gitUrl:t,ref:r,error:String(e),errorCategory:vU(e)}),a=null,i=(await Lj(t,s,{extraGitConfig:Mj(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}else i=(await Lj(t,s,{extraGitConfig:Mj(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha;const c=this.getCanonicalCloneDir(t,i),l=this.getLegacyCloneDir(e,s);n.log("info",`MarketplaceCacheManager: Resolved clone directory for ${e} at ${t}@${r} to ${c}`,{marketplaceId:e,resolvedRef:i,originalRef:s});const u=performance.now(),d=(e,t)=>{n.increment(`marketplace_cache_manager.ensure_cloned.${e}`,1,t),n.distribution(`marketplace_cache_manager.ensure_cloned.${e}.duration`,performance.now()-u,t)};if(await this.isCloneComplete(c)){await this.pruneSiblingCloneDirs(t,i,l);const e=await Gj(c);return e&&await Vj(c,o,{extraGitConfig:Mj(this.options?.extraGitConfig),timeoutMs:this.remoteTimeoutMs()}),d("cache_hit",{strategy:e?"sparse":"full"}),c}return n.increment("marketplace_cache_manager.ensure_cloned.cache_miss",1),this.cloneViaStaging(c,t,a,i,l,r,n,d,o)}async cloneViaStaging(e,t,r,n,o,s,i,a,c){await this.cleanStaleStagingDirs();const l=await this.createStagingDir();i.log("info",`MarketplaceCacheManager: Cloning ${t}@${s} into staging directory: ${l}`,{gitUrl:t,ref:s,cloneDir:e});const u=this.sparsePluginClones?setInterval((()=>{const e=new Date;(0,Co.utimes)(l,e,e).catch((()=>{}))}),CU.STAGING_HEARTBEAT_INTERVAL_MS):void 0;u?.unref?.();try{let u;if(null!==r)try{u=await this.cloneResolvedRef(l,r,n,{sshBatchMode:!0,materialize:c})}catch(e){if(this.sparsePluginClones&&bU(e))throw e;i.log("debug","Falling back to HTTPS clone due to SSH clone failure",{gitUrl:t,ref:s,error:String(e),errorCategory:SU(e)}),await(0,Co.rm)(l,mU),await(0,Co.mkdir)(l,{recursive:!0}),u=await this.cloneResolvedRef(l,t,n,{materialize:c})}else u=await this.cloneResolvedRef(l,t,n,{materialize:c});u.filterIgnoredByServer&&(i.log("warn","Server ignored --filter=blob:none; sparse clone downloaded a full pack",{gitUrl:t,ref:s}),i.increment("marketplace_cache_manager.ensure_cloned.filter_ignored_by_server",1));const d=await this.moveToCanonicalDir(l,e);return await this.pruneSiblingCloneDirs(t,n,o),a("cache_write_success",{strategy:u.strategy}),d}catch(e){const r=SU(e);throw a("error",{error_category:r}),i.log("error","Failed to clone marketplace repository via staging clone",{gitUrl:t,ref:s,error:String(e),errorCategory:r}),i.captureException(e,{error_type:"clone_marketplace_repository",error_category:r}),e}finally{void 0!==u&&clearInterval(u);try{await(0,Co.rm)(l,mU)}catch{}}}async isCloneComplete(e){try{if(!(await(0,Co.stat)(e)).isDirectory())return!1;const t=await(0,Co.readdir)(e);if(!t.includes(".git"))return!1;if(t.length>1)return!0;try{return(await(0,Co.stat)((0,s.join)(e,".git","info","sparse-checkout"))).isFile()}catch{return!1}}catch{return!1}}getPluginDir(e,t){return vf(e,t)}async copyPluginToDir(e,t){await(0,Co.mkdir)(t,{recursive:!0}),await(0,Co.cp)(e,t,{recursive:!0,verbatimSymlinks:!0})}async readManifest(e,t={}){const r=function(e,t){return JSON.stringify({clonePath:e,repoName:t.repoName??null,fallbackId:t.fallbackId??null})}(e,t);if(this.manifestCache.has(r))return this.manifestCache.get(r)??null;const n=await async function(e,t={}){for(const r of zh){const n=(0,s.join)(e,r);let o;try{o=await(0,Co.readFile)(n,"utf-8")}catch{continue}const i=bp(o,t);if(i.success)return i.data}return null}(e,t);return this.manifestCache.set(r,n),n}async resolvePluginPath(e,t){const r=await this.readManifest(e);if(!r)return null;const n=r.plugins.find((e=>e.name===t.toLowerCase()));if(!n)return null;const o=kp(n.source,r.metadata?.pluginRoot);return o&&_p(o)?o:null}async discoverPlugins(e){const t=await this.readManifest(e);return t?function(e){const t=[],r=function(e,t){const r=[];for(const n of e){const e=n.source;if("string"!=typeof e)switch(e.source){case"github":r.push({entry:n,kind:"external-github",externalUrl:`https://github.com/${e.repo}.git`,externalRef:e.ref,externalSha:e.sha,effectiveRef:e.sha??e.ref});break;case"url":r.push({entry:n,kind:"external-url",externalUrl:e.url,externalRef:e.ref,externalSha:e.sha,effectiveRef:e.sha??e.ref});break;case"git-subdir":r.push({entry:n,kind:"external-git-subdir",externalUrl:e.url,externalRef:e.ref,externalSha:e.sha,effectiveRef:e.sha??e.ref,subdirPath:e.path})}else{const o=kp(e,t);null!==o?r.push({entry:n,kind:"local",localPath:o}):r.push({entry:n,kind:"unresolvable",rawSource:e})}}return r}(e.plugins,e.metadata?.pluginRoot);for(const e of r){const{name:r,displayName:n,description:o,version:s}=e.entry,i={name:r,displayName:n,description:o,version:s};switch(e.kind){case"local":_p(e.localPath)&&t.push({...i,sourceType:"local",gitPath:e.localPath});break;case"external-github":t.push({...i,sourceType:"github",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha});break;case"external-url":t.push({...i,sourceType:"url",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha});break;case"external-git-subdir":t.push({...i,sourceType:"git-subdir",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha,subdirPath:e.subdirPath})}}return t}(t):[]}}CU.STALE_STAGING_THRESHOLD_MS=3e5,CU.STAGING_HEARTBEAT_INTERVAL_MS=6e4;const EU=(0,zs.debuglog)("cursor-plugins");function xU(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function PU(e){return xU(e)?e:void 0}function RU(e){const t=e.name?.trim();return void 0!==t&&t.length>0?t:e.pluginId}function IU(e,t){return void 0!==e?.marketplace?e.marketplace:void 0!==e?.marketplaceId?(t??[]).find((t=>void 0!==t.id&&String(t.id)===String(e.marketplaceId))):void 0}function TU(e,t){const r=t?.distributionGitUrl?.trim();return r?t?.gitUrl&&!BU(e,t.gitUrl)?e:r:e}function AU(e){return e?.distributionGitUrl?.trim()||e?.gitUrl}function $U(e,t){if(e.pinnedGitRef)return e.pinnedGitRef;if(e.plugin?.gitRef)return e.plugin.gitRef;const r=IU(e.plugin,t),n=e.plugin?.gitUrl,o=r?.gitUrl;return n&&o&&n!==o||!r?.gitRef?"main":r.gitRef}const MU="backend-git://";function DU(e,t,r){const n=r?`#${encodeURIComponent(r)}`:"";return`${MU}${encodeURIComponent(e)}@${encodeURIComponent(t)}${n}`}function OU(e){if(!e.startsWith(MU))return null;const t=e.slice(14),r=t.indexOf("#"),n=r>=0?t.slice(0,r):t,o=r>=0?t.slice(r+1):void 0,s=n.lastIndexOf("@");return s<0?null:{gitUrl:decodeURIComponent(n.slice(0,s)),ref:decodeURIComponent(n.slice(s+1)),gitPath:o?decodeURIComponent(o):void 0}}const FU="backend-release://";function NU(e){const t=e.tag?`@${encodeURIComponent(e.tag)}`:"";return`${FU}${encodeURIComponent(e.repo)}#${encodeURIComponent(e.asset)}${t}`}function LU(e){if(!e.startsWith(FU))return null;const t=e.slice(18),r=t.indexOf("#");if(r<0)return null;const n=decodeURIComponent(t.slice(0,r)),o=t.slice(r+1),s=o.lastIndexOf("@");return{repo:n,asset:s>=0?decodeURIComponent(o.slice(0,s)):decodeURIComponent(o),tag:s>=0?decodeURIComponent(o.slice(s+1)):void 0}}const jU=/^[0-9a-f]{7,40}$/i;function UU(e){let t;try{t=kU(e)}catch{return null}return`${t.host}\0${t.pathSegments.join("\0")}`}function BU(e,t){if(e.trim()===t.trim())return!0;const r=UU(e),n=UU(t);return null!==r&&r===n}const WU=104857600;async function HU(e,t,r,n,i,a){const c=await async function(e){const{repo:t,asset:r,tag:n}=e,{apiBase:o,ownerRepo:s,host:i}=function(e){const t=e.split("/"),r=t[0],n=t[1],o=t[2];if(3===t.length&&void 0!==r&&void 0!==n&&void 0!==o)return{apiBase:`https://${r}/api/v3`,ownerRepo:`${n}/${o}`,host:r};if(2===t.length)return{apiBase:"https://api.github.com",ownerRepo:e,host:"github.com"};throw new Error(`Invalid release repo format: ${e}`)}(t),a="github.com"===i&&void 0!==e.githubToken&&e.githubToken.length>0?{Authorization:`token ${e.githubToken}`}:{},c=n?`${o}/repos/${s}/releases/tags/${encodeURIComponent(n)}`:`${o}/repos/${s}/releases/latest`,l=await fetch(c,{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"CursorPluginInstaller",...a}});if(!l.ok)throw new Error(`Failed to fetch release from ${c}: ${l.status} ${l.statusText}`);const u=await l.json();if(!(xU(d=u)&&Array.isArray(d.assets)&&d.assets.every((e=>xU(e)&&"string"==typeof e.name&&"string"==typeof e.browser_download_url&&"number"==typeof e.size))))throw new Error(`Release payload from ${c} did not include assets`);var d;const h=u,p=h.assets.find((e=>e.name===r));if(!p){const e=h.assets.map((e=>e.name)).join(", ");throw new Error(`Release asset "${r}" not found. Available assets: ${e}`)}if(p.size>WU)throw new Error(`Release asset "${r}" exceeds maximum size of 104857600 bytes (actual: ${p.size})`);const f=new URL(p.browser_download_url);if("https:"!==f.protocol||!qU(f.hostname,i))throw new Error(`Refusing to download release asset from untrusted host: ${f.hostname}`);const m=await fetch(p.browser_download_url,{headers:{"User-Agent":"CursorPluginInstaller",Accept:"application/octet-stream",...a}});if(!m.ok)throw new Error(`Failed to download release asset: ${m.status} ${m.statusText}`);if(m.url){const e=new URL(m.url);if("https:"!==e.protocol||!qU(e.hostname,i))throw new Error(`Refusing to download release asset: redirected to untrusted host: ${e.hostname}`)}const g=Buffer.from(await m.arrayBuffer());if(g.byteLength>WU)throw new Error(`Release asset "${r}" actual download size exceeds maximum of 104857600 bytes (actual: ${g.byteLength})`);if(e.expectedSha256){const t=(0,bo.createHash)("sha256").update(g).digest("hex");if(t!==e.expectedSha256)throw new Error(`Release asset "${r}" integrity check failed: expected SHA-256 ${e.expectedSha256}, got ${t}`)}return g}({repo:e,asset:t,tag:r,expectedSha256:i,githubToken:a}),l=c.byteLength;await(0,Co.mkdir)(n,{recursive:!0});const u=await(0,Co.mkdtemp)((0,s.join)((0,o.tmpdir)(),"release-asset-")),d=(0,s.join)(u,"asset.tar.gz"),h=(0,s.join)(u,"extracted");try{await(0,Co.writeFile)(d,c),await(0,Co.mkdir)(h,{recursive:!0});let e=0,t=0;await sh.x({file:d,cwd:h,onReadEntry:r=>{if(t++,t>5e4)throw new Error("Release archive contains too many files (>50000).");if(e+=r.size,e>524288e3)throw new Error("Release archive uncompressed size exceeds maximum of 524288000 bytes.");if(l>0&&e/l>100)throw new Error("Release archive has suspicious compression ratio (>100x).")}});const r=await(0,Co.readdir)(h,{withFileTypes:!0}),o=r.filter((e=>e.isDirectory())),i=r.filter((e=>e.isFile()));let a=h;const u=o[0];if(1===o.length&&0===i.length&&void 0!==u){const e=(0,s.join)(h,u.name);(await(0,Co.readdir)(e)).some((e=>qh.includes(e)))&&(a=e)}const p=await(0,Co.readdir)(a);await Promise.all(p.map((e=>(0,Co.cp)((0,s.join)(a,e),(0,s.join)(n,e),{recursive:!0,verbatimSymlinks:!0}))))}finally{await(0,Co.rm)(u,{recursive:!0,force:!0}).catch((()=>{}))}}function qU(e,t){return!(e!==t&&!e.endsWith(".githubusercontent.com"))||("github.com"===t?"github.com"===e:e.endsWith(`.${t}`))}class zU{constructor(e,t,r,n,o){this.getEffectiveUserPlugins=e;const s="string"==typeof t||void 0===t?{marketplaceCacheRoot:t,pluginLogger:r,marketplaceCacheOptions:n,listOptions:o}:t,i=s.marketplaceCacheOptions??n;this.pluginLogger=s.pluginLogger??r??Tp,this.extraGitConfig=s.extraGitConfig,this.awaitAuthReady=s.awaitAuthReady,this.githubToken=s.githubToken,this.downloadPluginContent=s.downloadPluginContent,this.contentRetries=s.contentRetries??(new _h).forListing(""),this.sparsePluginClones=s.sparsePluginClones??!1,this.marketplaceCache=s.marketplaceCacheRoot?new CU(s.marketplaceCacheRoot,{...i,extraGitConfig:i?.extraGitConfig??s.extraGitConfig,sparsePluginClones:this.sparsePluginClones}):void 0;const a=s.listOptions??o;this.allowedMarketplaceNames=a?.allowedMarketplaceNames?new Set(a.allowedMarketplaceNames):void 0,this.enableInlinePlugins=a?.enableInlinePlugins??!1}isMarketplaceAllowed(e){return void 0===this.allowedMarketplaceNames||void 0!==e?.name&&this.allowedMarketplaceNames.has(e.name)}async listEnabledPlugins(e,t){const r=await this.getEffectiveUserPlugins(),n=r.plugins??[],o=r.marketplaces??[],s=[],i=[],a=new Map,c=async(e,t)=>{const r=`${e}\0${t}`;let n=a.get(r);if(!n){const o=Mj(this.extraGitConfig),s=this.sparsePluginClones?3e4:void 0,i=e.startsWith("git@")||e.startsWith("ssh://")?null:aU(e),c=async(e,r)=>{const n={};return r&&(n.sshBatchMode=!0),void 0!==o&&(n.extraGitConfig=o),void 0!==s&&(n.timeoutMs=s),(Object.keys(n).length>0?await Lj(e,t,n):await Lj(e,t)).fullSha};if(null!==i)try{n=await c(i,!0)}catch(t){if(this.sparsePluginClones&&bU(t))throw t;n=await c(e,!1)}else n=await c(e,!1);a.set(r,n)}return n},l=async e=>{const{preferredGitUrl:t,sourceGitUrl:r,gitRef:n,pluginId:o}=e;if(t!==r){void 0!==this.awaitAuthReady&&await this.awaitAuthReady();const e=`${t}\0${n}`,s=!a.has(e);let i;s&&this.pluginLogger.increment("marketplace.origin_distribution.fetch",1);try{i={sha:await c(t,n),gitUrl:t}}catch(e){s&&this.pluginLogger.increment("marketplace.origin_distribution.fetch.error",1),this.pluginLogger.captureException(e,{error_type:"distribution_url_fallback"}),this.pluginLogger.log("warn",`Distribution mirror ${t}@${n} unavailable (not synced yet or unreachable); falling back to source ${r}`,{pluginId:o,preferredGitUrl:t,sourceGitUrl:r,gitRef:n,error:String(e)})}if(void 0!==i){if(s)try{this.pluginLogger.log("info",`Resolved plugin ${o} from Origin distribution mirror ${t}@${n}`,{pluginId:o,preferredGitUrl:t,gitRef:n})}catch{}return i}}return{sha:await c(r,n),gitUrl:r}};this.contentRetries.startLoad();for(const e of n){if(!e.isEnabled||!e.plugin?.name)continue;const t=e.plugin,r=IU(t,o);if(!this.isMarketplaceAllowed(r)){this.pluginLogger.log("info",`Skipping plugin ${t.name} because marketplace ${r?.name??""} is not allowed`,{pluginId:t.name,marketplaceName:r?.name,allowedMarketplaceNames:void 0!==this.allowedMarketplaceNames?Array.from(this.allowedMarketplaceNames):void 0});continue}const n=RU({name:t.name,pluginId:void 0!==t.id?String(t.id):t.name??""}),a=n;if(void 0!==t.backendContent&&null!==t.backendContent){const t=this.listBackendContentPlugin(e,r,n);"entry"in t?s.push(t.entry):i.push(t.failure);continue}if(!t.gitUrl){if(!this.enableInlinePlugins){this.pluginLogger.log("info",`Skipping plugin ${n} without gitUrl (enableInlinePlugins=false)`,{pluginId:a});continue}const o=e.inlineContentJson;if(!o){this.pluginLogger.log("info",`Skipping DB-inline plugin ${n}: no inline content provided`,{pluginId:a});continue}const i=(0,bo.createHash)("sha256").update(`${t.id??"0"}:${t.updatedAt??"0"}`).digest("hex").slice(0,40),c=r?.name?{id:void 0!==r.id?`${r.name}-${r.id}`:`${r.name}-inline`,name:r.name}:void 0;this.pluginLogger.log("info",`BackendMarketplaceClient: Adding DB-inline plugin: ${a}`,{pluginId:a,marketplaceId:c?.id??"unknown",version:i}),s.push({pluginId:a,pluginDbId:void 0!==t.id?String(t.id):void 0,configuredVariables:PU(e.configuredVariables),isTeamRequired:e.isTeamRequired,name:n,version:i,downloadUrl:`inline://${t.id??a}`,marketplaceDbId:void 0!==r?.id?String(r.id):void 0,marketplace:c,inlineContentJson:o});continue}const c=t.gitUrl,u=TU(c,r),d=$U(e,o),h=Cj(t,d),p=r?.gitRef??d;let f,m,g=u;try{if(void 0!==h)f=`release/${h.releaseTag}`;else{const e=await l({preferredGitUrl:u,sourceGitUrl:c,gitRef:d,pluginId:a});f=e.sha,g=e.gitUrl}}catch(e){this.pluginLogger.captureException(e,{error_type:"resolve_version_sha"}),this.pluginLogger.log("error",`Failed to resolve version for plugin ${n}@${d}, skipping plugin`,{pluginId:a,ref:d,error:String(e)});const o=e instanceof Error?e.message:String(e);i.push({pluginName:n,pluginId:a,pluginDbId:void 0!==t.id?String(t.id):void 0,marketplaceName:r?.name,errorMessage:o,errorType:/timed?\s*out/i.test(o)?"timeout":"clone"});continue}m=void 0!==h?NU({repo:h.releaseRepo,asset:h.releaseAsset,tag:h.releaseTag}):DU(g,d,t.gitPath??void 0);const w=AU(r);let y=w,v=r?.gitUrl,b=p;if(r?.gitUrl&&w){const e=BU(c,r.gitUrl),t=e?g:w,o=e?c:r.gitUrl,s=e?d:p;v=o;try{const e=await l({preferredGitUrl:t,sourceGitUrl:o,gitRef:s,pluginId:a});b=e.sha,y=e.gitUrl}catch(e){this.pluginLogger.captureException(e,{error_type:"resolve_marketplace_cache_ref"}),this.pluginLogger.log("warn",`Failed to resolve marketplace cache ref for plugin ${n} from ${t}@${s}, falling back to raw ref`,{pluginId:a,cacheRepoUrl:t,cacheRef:s,error:String(e)}),y=o}}const S=r?.name?{id:void 0!==r.id?`${r.name}-${r.id}`:`${r.name}-${encodeURIComponent(r.gitUrl??"project")}`,name:r.name,...y&&{gitUrl:y,gitRef:b}}:void 0,k=void 0!==h||g===c&&y===v?void 0:{downloadUrl:DU(c,d,t.gitPath??void 0),marketplaceGitUrl:v};this.pluginLogger.log("info",`BackendMarketplaceClient: Adding enabled plugin: ${a} from ${b} at ${t.gitPath}`,{pluginId:a,marketplaceId:S?.id??"unknown",gitPath:t.gitPath??void 0,gitRef:b}),s.push({pluginId:a,pluginDbId:void 0!==t.id?String(t.id):void 0,configuredVariables:PU(e.configuredVariables),isTeamRequired:e.isTeamRequired,name:n,version:f,downloadUrl:m,marketplaceDbId:void 0!==r?.id?String(r.id):void 0,marketplace:S,gitPath:t.gitPath??void 0,isOriginBacked:void 0===h&&g!==c||void 0,originSourceFallback:k})}return{plugins:s,listFailures:i}}isBackendContentRetryDue(){return this.contentRetries.isRetryDue()}allowImmediateBackendContentRetry(){this.contentRetries.allowImmediateRetry()}listBackendContentPlugin(e,t,r){const n=Ch(e.plugin?.id),o=function(e){const{revision:t}=e;return"string"==typeof t&&mh.test(t)?{revision:t}:{invalid:"revision"}}(e.plugin?.backendContent??{}),s=void 0===n?"plugin_id":"invalid"in o?o.invalid:void 0;if(void 0===n||"invalid"in o)return this.pluginLogger.log("error",`Skipping plugin ${r}: the listing's backend content has an unusable ${s}`,{pluginId:r,invalidField:s}),this.pluginLogger.increment("backend_marketplace_client.backend_content.list.invalid",1),{failure:{pluginName:r,pluginId:r,pluginDbId:n,marketplaceName:t?.name,errorMessage:`Plugin ${JSON.stringify(r)} could not be installed: the server listed it with details this client does not accept.`,errorType:"install"}};const i=t?.name?{id:void 0!==t.id?`${t.name}-${t.id}`:`${t.name}-backend-content`,name:t.name}:void 0;return this.pluginLogger.log("info",`BackendMarketplaceClient: Adding backend-served plugin: ${r}`,{pluginId:r,marketplaceId:i?.id??"unknown",revision:o.revision}),{entry:{pluginId:r,pluginDbId:n,configuredVariables:PU(e.configuredVariables),isTeamRequired:e.isTeamRequired,name:r,version:xh(o.revision),downloadUrl:(a={pluginDbId:n,revision:o.revision},`${yh}${a.pluginDbId}@${a.revision}`),marketplaceDbId:void 0!==t?.id?String(t.id):void 0,marketplace:i,backendContent:o}};var a}async relistPlugin(e){if(void 0===e.backendContent||void 0===e.pluginDbId)return;const t=await this.getEffectiveUserPlugins(),r=(t.plugins??[]).find((t=>!0===t.isEnabled&&Ch(t.plugin?.id)===e.pluginDbId)),n=r?.plugin;if(void 0===r||!n?.name||void 0===n.backendContent||null===n.backendContent)return;const o=IU(n,t.marketplaces??[]);if(!this.isMarketplaceAllowed(o))return;const s=this.listBackendContentPlugin(r,o,e.name);return"entry"in s&&s.entry.version!==e.version?s.entry:void 0}async installBackendContentPlugin(e,t){const r=e.backendContent,n=Ch(e.pluginDbId);if(void 0===r||void 0===n)throw new Error(`Plugin ${JSON.stringify(e.name)} has no backend content to install`);const o={pluginDbId:n,revision:r.revision},s=this.contentRetries.heldFailure(o);if(void 0!==s)throw Ph(s,e.name);const i=performance.now();let a="success";try{await Ih({download:this.downloadPluginContent,pluginDbId:n,pluginName:e.name,content:r,targetDir:t}),this.contentRetries.recordAttempt(o)}catch(e){throw a=e instanceof ph?e.reason:"unknown",this.contentRetries.recordAttempt({...o,error:e}),e}finally{this.pluginLogger.increment("backend_marketplace_client.backend_content.install",1,{outcome:a}),this.pluginLogger.distribution("backend_marketplace_client.backend_content.install.duration",performance.now()-i,{outcome:a})}this.pluginLogger.log("info",`Installed backend-served plugin ${e.pluginId}`,{pluginId:e.pluginId,revision:r.revision})}isDirectInstallSameFetch(e){const t=e.marketplace;if(!t?.gitUrl||!t.gitRef)return!1;const r=OU(e.downloadUrl);return!(!r||!BU(r.gitUrl,t.gitUrl)||r.ref!==t.gitRef&&e.version!==t.gitRef)}async installPlugin(e,t){if(void 0!==e.backendContent||Eh(e.downloadUrl))await this.installBackendContentPlugin(e,t);else if(e.inlineContentJson)await async function(e){const{targetDir:t,inlineContentJson:r,pluginName:n}=e,o=JSON.parse(r);await(0,Co.mkdir)(t,{recursive:!0});const i={};if(o.rules&&o.rules.length>0){const e=(0,s.join)(t,"rules");await(0,Co.mkdir)(e,{recursive:!0});const r=[];for(const t of o.rules){if(!t.content)continue;if(!1===t.isActive)continue;const n=`${oh(t.name)}.md`,o=[];o.push(`description: ${uU(t.name)}`),t.globs&&t.globs.length>0&&o.push(`globs: ${uU(t.globs.join(", "))}`),o.push(`alwaysApply: ${!0===t.isRequired}`);const i=`---\n${o.join("\n")}\n---\n\n`;await(0,Co.writeFile)((0,s.join)(e,n),i+t.content,"utf-8"),r.push(`rules/${n}`)}r.length>0&&(i.rules=r)}if(o.commands&&o.commands.length>0){const e=(0,s.join)(t,"commands");await(0,Co.mkdir)(e,{recursive:!0});const r=[];for(const t of o.commands){if(!t.content)continue;if(!1===t.isActive)continue;const n=`${oh(t.name)}.md`,o=t.description?`---\ndescription: ${uU(t.description)}\n---\n\n`:"";await(0,Co.writeFile)((0,s.join)(e,n),o+t.content,"utf-8"),r.push(`commands/${n}`)}r.length>0&&(i.commands=r)}if(o.hooks&&o.hooks.length>0){const e=(0,s.join)(t,"hooks");await(0,Co.mkdir)(e,{recursive:!0});const r={};for(const e of o.hooks){const t=e.hookStep;t&&!1!==e.isActive&&lU(e)&&(r[t]||(r[t]=[]),"prompt"===e.hookType?r[t].push({type:"prompt",prompt:e.promptContent??"",...e.promptModel?{model:e.promptModel}:{}}):r[t].push({type:"command",command:e.scriptContent??""}))}await(0,Co.writeFile)((0,s.join)(e,"hooks.json"),JSON.stringify({version:1,hooks:r},null,2),"utf-8")}if(o.mcpServers&&o.mcpServers.length>0){const e={};for(const t of o.mcpServers)t.config&&(e[t.name]=t.config);Object.keys(e).length>0&&await(0,Co.writeFile)((0,s.join)(t,".mcp.json"),JSON.stringify({mcpServers:e},null,2),"utf-8")}const a={name:n,...i},c=(0,s.join)(t,".cursor-plugin");await(0,Co.mkdir)(c,{recursive:!0}),await(0,Co.writeFile)((0,s.join)(c,"plugin.json"),JSON.stringify(a,null,2),"utf-8")}({targetDir:t,inlineContentJson:e.inlineContentJson,pluginName:e.name});else{e.isOriginBacked&&void 0!==this.awaitAuthReady&&await this.awaitAuthReady();try{return void await this.installFromEntryUrls(e,t)}catch(r){const n=function(e){const t=e.originSourceFallback;if(void 0===t)return;let r=e.marketplace;if(void 0!==r)if(void 0!==t.marketplaceGitUrl)r={...r,gitUrl:t.marketplaceGitUrl};else{const{gitUrl:e,gitRef:t,...n}=r;r=n}return{...e,downloadUrl:t.downloadUrl,marketplace:r,isOriginBacked:void 0,originSourceFallback:void 0}}(e);if(void 0===n)throw r;this.pluginLogger.captureException(r,{error_type:"install_plugin_from_origin_distribution"}),this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from the Origin distribution mirror, falling back to the source repo`,{pluginId:e.pluginId,version:e.version,sourceDownloadUrl:n.downloadUrl,sourceMarketplaceGitUrl:n.marketplace?.gitUrl,error:String(r)}),this.pluginLogger.increment("marketplace.origin_distribution.install.source_fallback",1),await(0,Co.rm)(t,{recursive:!0,force:!0});try{await this.installFromEntryUrls(n,t)}catch(e){throw this.pluginLogger.increment("marketplace.origin_distribution.install.source_fallback.error",1),e}}}}async installFromEntryUrls(e,t){if(null===LU(e.downloadUrl))try{if(await this.tryInstallFromMarketplaceCache(e,t))return void this.emitOriginLoadIfApplicable(e)}catch(t){if(this.pluginLogger.captureException(t,{error_type:"install_plugin_from_marketplace_cache"}),this.sparsePluginClones&&this.isDirectInstallSameFetch(e)&&bU(t))throw this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from marketplace cache; skipping direct install fallback because it would repeat the identical fetch`,{pluginId:e.pluginId,version:e.version,error:String(t)}),t;this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from marketplace cache, falling back to direct install`,{pluginId:e.pluginId,version:e.version,error:String(t)})}await async function(e,t,r=Tp,n,i){const a=i?.sparsePluginClones??!1,c=a?pU:void 0,l=LU(e.downloadUrl);if(l){if(e.gitPath){const r=await(0,Co.mkdtemp)((0,s.join)((0,o.tmpdir)(),"release-plugin-"));try{await HU(l.repo,l.asset,l.tag,r,i?.expectedReleaseAssetSha256,i?.githubToken);const n=vf(r,e.gitPath);await(0,Co.mkdir)(t,{recursive:!0}),await(0,Co.cp)(n,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,Co.rm)(r,{recursive:!0,force:!0}).catch((()=>{}))}}else await HU(l.repo,l.asset,l.tag,t,i?.expectedReleaseAssetSha256,i?.githubToken);return}const u=OU(e.downloadUrl);if(!u)throw new Error(`Invalid download URL format for plugin ${e.pluginId}: ${e.downloadUrl}`);const d=await(0,Co.mkdtemp)((0,s.join)((0,o.tmpdir)(),"backend-plugin-"));try{let o;if(await async function(e,t,r,n=Tp,o,s="all",i=!1){const a=performance.now(),c=jU.test(t),l="HEAD"===t.toUpperCase(),u={...o,"safe.directory":r},d=i?pU:void 0,h=i?fU:void 0,{sparse:p,sparseDirs:f}=await Hj(s,i),m=p?["--filter=blob:none","--sparse"]:[],g=!!p||void 0,w=async e=>{p&&await zj(r,f,{extraGitConfig:u,timeoutMs:e,sshBatchMode:!0})},y=async(e,n)=>{let o;return l?(({stderr:o}=await Dj(["clone","--depth","1",...m,e,r],{extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await w(d)):c?(await Dj(["init"],{cwd:r,extraGitConfig:u,timeoutMs:h}),await Dj(["remote","add","origin",e],{cwd:r,extraGitConfig:u,timeoutMs:h}),await w(h),({stderr:o}=await Dj(["fetch","--depth","1",...p?["--filter=blob:none"]:[],"origin",t],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await Dj(["checkout","FETCH_HEAD"],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})):(({stderr:o}=await Dj(["clone","--depth","1","--branch",t,...m,e,r],{extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await w(d)),o},v=e.startsWith("git@")||e.startsWith("ssh://")?null:aU(e);let b;if(null!==v)try{b=await y(v,!0)}catch(t){if(i&&bU(t))throw t;await(0,Co.rm)(r,{recursive:!0,force:!0}),await(0,Co.mkdir)(r,{recursive:!0}),b=await y(e,g)}else b=await y(e,g);p&&qj(b)&&(n.log("warn",`shallowClone: server ignored --filter=blob:none for ${e}; sparse clone downloaded a full pack`),n.increment("backend_marketplace_client.shallow_clone.filter_ignored_by_server",1));const S=(performance.now()-a).toFixed(1);EU("shallowClone %s@%s completed in %sms",e,t,S),n.log("info",`shallowClone ${e}@${t} completed in ${S}ms (${p?"sparse":"full"})`)}(u.gitUrl,u.ref,d,r,n,u.gitPath?Wj([u.gitPath]):[],a),u.gitPath)o=vf(d,u.gitPath);else{const t=await async function(e,t){for(const r of zh){const n=(0,s.join)(e,r);let o;try{o=await(0,Co.readFile)(n,"utf-8")}catch{continue}const i=bp(o);if(!i.success)return{type:"manifest-unresolved",reason:`Invalid marketplace manifest at ${r}: ${i.error}`};const a=i.data,c=a.plugins.find((e=>e.name===t.toLowerCase()));if(!c)return{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} not found in ${r}`};if("string"!=typeof c.source&&"git-subdir"===c.source.source)return{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} uses unsupported git-subdir source`};const l=kp(c.source,a.metadata?.pluginRoot);return l&&_p(l)?{type:"resolved",gitPath:l}:{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} has unresolved or unsafe source path`}}return{type:"no-manifest"}}(d,e.name);if("resolved"===t.type)await Vj(d,Wj([t.gitPath]),{extraGitConfig:n,timeoutMs:c}),o=vf(d,t.gitPath);else{if("manifest-unresolved"===t.type)throw new Error(`Unable to install plugin ${JSON.stringify(e.name)} without gitPath: ${t.reason}`);await Vj(d,"all",{extraGitConfig:n,timeoutMs:c}),o=d}}await(0,Co.mkdir)(t,{recursive:!0}),await(0,Co.cp)(o,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,Co.rm)(d,{recursive:!0,force:!0}).catch((()=>{}))}}(e,t,this.pluginLogger,Mj(this.extraGitConfig),{githubToken:this.githubToken,sparsePluginClones:this.sparsePluginClones}),this.emitOriginLoadIfApplicable(e)}emitOriginLoadIfApplicable(e){if(e.isOriginBacked)try{this.pluginLogger.increment("marketplace.origin_distribution.load",1),this.pluginLogger.log("info",`Loaded plugin ${e.pluginId} from Origin distribution (fetch complete)`,{pluginId:e.pluginId})}catch{}}async prewarmMarketplaceClones(e){const t=this.marketplaceCache;if(!t)return;const r=new Map;for(const t of e){const e=t.marketplace;if(!e?.gitUrl)continue;const n=e.gitRef??"main",o=`${e.id}\0${e.gitUrl}\0${n}`;let s=r.get(o);void 0===s&&(s={marketplaceId:e.id,gitUrl:e.gitUrl,gitRef:n,gitPaths:[]},r.set(o,s)),t.gitPath&&s.gitPaths.push(t.gitPath)}for(const e of r.values()){const r=Wj(e.gitPaths),n=performance.now();try{await t.ensureCloned(e.marketplaceId,e.gitUrl,e.gitRef,this.pluginLogger,{materialize:r}),this.pluginLogger.log("info",`Prewarmed marketplace clone ${e.gitUrl}@${e.gitRef} for ${e.gitPaths.length} plugin directories`,{marketplaceId:e.marketplaceId,gitUrl:e.gitUrl,gitRef:e.gitRef,requestedDirs:e.gitPaths.length,materialize:"all"===r?"all":r.length}),this.pluginLogger.increment("marketplace_cache_manager.prewarm.success",1,{materialize:"all"===r?"all":"dirs"})}catch(t){this.pluginLogger.captureException(t,{error_type:"prewarm_marketplace_clone"}),this.pluginLogger.log("warn",`Failed to prewarm marketplace clone ${e.gitUrl}@${e.gitRef}; falling back to per-plugin materialization`,{marketplaceId:e.marketplaceId,gitUrl:e.gitUrl,gitRef:e.gitRef,error:String(t)}),this.pluginLogger.increment("marketplace_cache_manager.prewarm.error",1)}this.pluginLogger.distribution("marketplace_cache_manager.prewarm.duration",performance.now()-n)}}async tryInstallFromMarketplaceCache(e,t){const r=this.marketplaceCache,n=e.marketplace;if(!r||!n||!n.gitUrl)return this.pluginLogger.log("info","No marketplace cache or marketplace metadata, skipping cache check",{pluginId:e.pluginId,name:e.name,version:e.version,marketplaceId:e.marketplace?.id}),!1;const o=await r.ensureCloned(n.id,n.gitUrl,n.gitRef??"main",this.pluginLogger,{materialize:e.gitPath?Wj([e.gitPath]):[]}),s=e.gitPath??await r.resolvePluginPath(o,e.name);if(!s)return this.pluginLogger.log("info","No git path found for plugin, skipping cache check",{pluginId:e.pluginId,name:e.name,version:e.version,marketplaceId:e.marketplace?.id}),!1;void 0===e.gitPath&&await r.ensureMaterialized(o,Wj([s]),this.pluginLogger);const i=r.getPluginDir(o,s);return await r.copyPluginToDir(i,t),!0}async discoverMarketplacePlugins(e,t,r){const n=this.marketplaceCache;if(!n)throw new Error("discoverMarketplacePlugins requires a MarketplaceCacheManager (marketplaceCacheRoot)");const o=await n.ensureCloned(e,t,r,this.pluginLogger,{materialize:[]});return n.discoverPlugins(o)}}function GU(e,t,r,n,o){return new zU(e,t,r,n,o)}function VU(e){const t=e.trim();if(!t)return!1;if(t.startsWith("git@"))return/^git@[a-zA-Z0-9.-]+:[a-zA-Z0-9._~\-/]+(?:\.git)?$/.test(t);try{const e=new URL(t);return"https:"===e.protocol&&""===e.username&&""===e.password&&""===e.search&&""===e.hash}catch{return!1}}class KU extends Error{constructor(e){super(e),this.name="SettingsParseError"}}function JU(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ZU(e){return 65279===e.charCodeAt(0)?e.slice(1):e}async function XU(e){try{return ZU(await(0,Co.readFile)(function(e){return(0,s.join)(e,".cursor","settings.json")}(e),"utf-8"))}catch(e){if(function(e){return e instanceof Error&&"code"in e}(e)&&("ENOENT"===e.code||"ENOTDIR"===e.code))return;throw e}}async function QU(e){const t=await XU(e);return void 0===t?[]:function(e){const t=function(e){const t=ZU(e);if(0===t.trim().length)return{};const r=[],n=(0,Cp.qg)(t,r,{allowTrailingComma:!0});if(r.length>0){const e=r.slice(0,3).map((e=>`${(0,Cp._n)(e.error)} at offset ${e.offset}`)).join("; ");throw new KU(`.cursor/settings.json contains syntax errors: ${e}`)}if(!JU(n))return{};const o=n.plugins;if(void 0===o)return{};if(!JU(o))return{};const s={};for(const[e,t]of Object.entries(o))JU(t)&&(s[e]=t);return{plugins:s}}(e);return t.plugins?Object.entries(t.plugins).filter((([,e])=>!0===e.enabled)).filter((([,e])=>!e.gitUrl||VU(e.gitUrl))).map((([e,t])=>({key:e,entry:t}))):[]}(t)}function YU(e){const t=e.indexOf("/");return-1===t?{name:e}:{name:e.slice(t+1),marketplaceName:e.slice(0,t)}}const eB={supportsBackendContent:!0};function tB(e={}){const t=e.userHomeDirectory??(0,o.homedir)(),r=e.importThirdPartyPlugins??!1,n=e.pluginLogger??{log(e,t,r){switch(e){case"warn":SO.Jz.warn("[local-plugins-bootstrap]",t,r??{});break;case"error":SO.Jz.error("[local-plugins-bootstrap]",t,r??{})}},increment(){},distribution(){},captureException(e,t){SO.Jz.error("[local-plugins-bootstrap] Unexpected plugin exception:",e,t??{})}},i=rB(e.marketplaceOptions),a=void 0!==e.dashboardTransport,c=e.loadCursorFirstParty??(i||a);return{async loadPluginBootstrapOutputs(o){const i=(a=o.workspaceState).projectRoot??a.workspaceRoots[0]??a.workingDirectory;var a;const{discoveredEntries:l,failures:u}=await async function(e){if(void 0===e)return{discoveredEntries:[],failures:[]};try{return{discoveredEntries:(await QU(e)).map((({key:t,entry:r})=>({source:"project-settings",workspacePath:e,key:t,entry:r}))),failures:[]}}catch(e){return{discoveredEntries:[],failures:[{stage:"discovery",source:"project-settings",message:e instanceof Error?`Failed to read project plugin settings: ${e.message}`:`Failed to read project plugin settings: ${String(e)}`,detail:e}]}}}(i),d=e.marketplaceOptions??(e.dashboardTransport?function(e){const t=(0,s.join)(e.userHomeDirectory,".cursor","plugins","marketplaces"),r=(0,ye.createClient)(fj.I,e.dashboardTransport),n=(e,{signal:t})=>r.downloadPluginContent(e,{signal:t}),o=new _h,i=GU((async()=>{try{return await r.getEffectiveUserPlugins(new JD.EwF(eB))}catch{return{plugins:[]}}}),{marketplaceCacheRoot:t,listOptions:{allowedMarketplaceNames:["cursor-public"]},downloadPluginContent:n,contentRetries:o.forListing("account")}),a=e.workspacePath,c=GU((async()=>{if(void 0===a)return{plugins:[]};try{const e=await QU(a);if(0===e.length)return{plugins:[]};const t=e.filter((e=>e.entry.gitUrl)),n=e.filter((e=>!e.entry.gitUrl)),o=t.filter((({entry:e})=>{const t=e.gitUrl;return!t||VU(t)})).map((({key:e,entry:t})=>{const r=YU(e),n=t.gitUrl;return{plugin:{name:r.name,gitUrl:n,gitRef:t.gitRef,gitPath:t.gitPath,marketplace:{name:r.marketplaceName,gitUrl:n,gitRef:t.gitRef}},isEnabled:!0}}));let s=[];if(n.length>0)try{const e=n.map((e=>{const t=YU(e.key);return new JD.vwy({name:t.name,marketplaceName:t.marketplaceName})})),t=await r.resolvePluginsByRef(new JD.WvV({refs:e,...eB}));s=t.plugins?.map((e=>({plugin:e,isEnabled:!0})))??[]}catch{}return{plugins:[...o,...s]}}catch{return{plugins:[]}}}),{marketplaceCacheRoot:t,listOptions:{allowedMarketplaceNames:["cursor-public"]},downloadPluginContent:n,contentRetries:o.forListing("project")});return[{client:i,userId:"",cacheManager:new hh(e.userHomeDirectory),pruneOldVersions:!0},{client:c,userId:"",cacheManager:new hh(e.userHomeDirectory),pruneOldVersions:!0}]}({dashboardTransport:e.dashboardTransport,workspacePath:i,userHomeDirectory:t}):void 0),h=rB(d),p=new UD(void 0!==i?[i]:[],t,(()=>({importThirdPartyPlugins:r,loadCursorFirstParty:c})),d,n);let f=[];const m=[...u];try{f=await p.getAllEnabledPlugins()}catch(e){m.push({stage:"resolution",source:"plugin-loader",message:e instanceof Error?`Failed to load plugins: ${e.message}`:`Failed to load plugins: ${String(e)}`,detail:e})}l.length>0&&!h&&m.push({stage:"resolution",source:"plugin-loader",message:"Project plugin entries were discovered, but no marketplace-backed project plugin source was configured. Those entries remain available through discoveredEntries only.",detail:{workspacePath:i,discoveredEntryCount:l.length}});const g={kind:BO,discoveredEntries:l,loadedPlugins:f,loadFailures:p.getLoadFailures(),bootstrapFailures:m,pluginsService:p,async dispose(){}};for(const e of m)SO.Jz.warn("[local-plugins-bootstrap] Plugin bootstrap failure:",{workspacePath:i,stage:e.stage,source:e.source,message:e.message,detail:e.detail});for(const e of g.loadFailures)SO.Jz.warn("[local-plugins-bootstrap] Plugin load failure:",{workspacePath:i,pluginName:e.pluginName,pluginId:e.pluginId,marketplaceName:e.marketplaceName,errorType:e.errorType,errorMessage:e.errorMessage});return[g]}}}function rB(e){return void 0!==e&&(!Array.isArray(e)||e.length>0)}class nB{async getAllCursorRules(e){return[]}reload(e){}dispose(){}onDidChangeRules(e){return()=>{}}}const oB=["projectFolder","terminalsFolder","agentSharedNotesFolder","agentConversationNotesFolder","agentTranscriptsFolder","processWorkingDirectory","artifactsFolder"];function sB(e){if(e.length<=1)return e;let t=e.length;for(;t>1&&("/"===(r=e[t-1])||"\\"===r)&&(3!==t||":"!==e[1]);)t-=1;var r;return e.slice(0,t)}function iB(e){const t=sB(e).replaceAll("\\","/");return/^[A-Za-z]:\/$/.test(t)?t.slice(0,-1):t}function aB(e){const t=sB(e.reportedWorkspacePath);if(""===e.suffix)return t;const r=t.replaceAll("\\","/"),n="/"===r?e.suffix:`${r}${e.suffix}`;return t.includes("\\")?n.replaceAll("/","\\"):n}function cB(e){const t=iB(e.value),r=e.roots.filter((e=>e.host.length>0)).sort(((e,t)=>iB(t.host).length-iB(e.host).length));for(const e of r){const r=iB(e.host);if(t===r)return aB({reportedWorkspacePath:e.reported,suffix:""});const n="/"===r?"/":`${r}/`;if(t.startsWith(n)){const n="/"===r?t:t.slice(r.length);return aB({reportedWorkspacePath:e.reported,suffix:n})}}}const lB={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1};class uB extends sD{constructor(e,t){super(e),this.sessionMcpLease=t}async dispose(){try{await super.dispose()}finally{await mj(this.sessionMcpLease)}}}function dB(e){const t=new _y;return{async createResources(r){const n=e.createSessionDependencies?.(r)??{pendingDecisionStore:e.pendingDecisionStore,fileChangeTracker:e.fileChangeTracker,permissionsService:e.permissionsService};if(!n.pendingDecisionStore||!n.fileChangeTracker||!n.permissionsService)throw new Error("Local resource provider factory requires either shared dependencies or a per-session dependency factory.");const o=r.workspaceServices.cursorRulesService??new nB,s=r.workspaceServices.subagentsService??new Sg,i=r.workspaceServices.mcpLease??new tI,a=!0===r.options.excludeProjectMcp,c=void 0!==r.options.mcpServersOverride||a?void 0!==e.createSessionMcpLease?await e.createSessionMcpLease(r,r.options.mcpServersOverride):a?new tI:void 0:void 0,l=(u=c??i,0===(d=r.options.extraMcpTools??[]).length?u:"onDidChange"in(h=u)&&"function"==typeof h.onDidChange?new zw(u,d):new qw(u,d));var u,d,h;try{const i=await async function(e,t){return void 0===e?{}:"function"==typeof e?await e({sessionId:t.sessionState.sessionId,metadata:t.metadata}):e}(r.options.localResourceProviderOptions,r),a=await async function(e){if(void 0===e)return lB;try{const t=await e();return{powershellUtf8Console:t.powershellUtf8Console,powershellUtf8ChildEnv:t.powershellUtf8ChildEnv}}catch{return lB}}(e.getPowershellUtf8Options),u={pendingDecisionStore:n.pendingDecisionStore,fileChangeTracker:n.fileChangeTracker,gitExecutor:t,ignoreService:e.ignoreService,grepProvider:e.grepProvider,permissionsService:n.permissionsService,workspacePaths:e.workspacePaths,diagnosticsProvider:e.diagnosticsProvider,mcpLease:l,mcpStateAccessor:e.createMcpStateAccessor?.(l,r.options),cursorRulesService:o,subagentsService:s,repositoryProvider:e.repositoryProvider,projectDir:e.projectDir,shellManager:e.shellManager,_defaultSandboxPolicy:e.defaultSandboxPolicy??{type:"insecure_none"},_defaultSandboxPolicySources:e.defaultSandboxPolicySources,getSandboxEnabled:e.getSandboxEnabled,getSandboxSupported:e.getSandboxSupported,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:e.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:e.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:e.getMockPromptTime,mcpFileOutputThresholdBytes:e.mcpFileOutputThresholdBytes,mcpMetaToolEnabled:e.mcpMetaToolEnabled,getAgentSkills:r.workspaceServices.getAgentSkills,powershellUtf8Console:a.powershellUtf8Console,powershellUtf8ChildEnv:a.powershellUtf8ChildEnv,...i},d=void 0===c?new sD(u):new uB(u,c);return void 0===r.options.reportedWorkspacePath&&void 0===r.options.reportedProjectFolder||function(e,t){const r=e.get($r);if(void 0===r)return;const{reportedWorkspacePath:n,reportedProjectFolder:o}=t,s=void 0===n?[]:t.workspacePaths.map((e=>({host:e,reported:n}))),i=o??n;void 0!==i&&s.push({host:t.projectDir,reported:i}),e.register($r,{execute:async(e,t,o)=>function(e,t){if("success"!==e.result.case||void 0===e.result.value.requestContext?.env)return e;const r=e.clone();if("success"!==r.result.case)return e;const n=r.result.value.requestContext?.env;if(void 0===n)return r;const{roots:o,reportedWorkspacePath:s}=t;n.workspacePaths=n.workspacePaths.map((e=>cB({value:e,roots:o})??e));for(const e of oB){const t=n[e];if(void 0===t||""===t)continue;const r=cB({value:t,roots:o});n[e]="processWorkingDirectory"===e&&void 0!==s?r??sB(s):r??t}return r}(await r.execute(e,t,o),{roots:s,reportedWorkspacePath:n})})}(d,{reportedWorkspacePath:r.options.reportedWorkspacePath,reportedProjectFolder:r.options.reportedProjectFolder,workspacePaths:u.workspacePaths,projectDir:u.projectDir}),d}catch(e){throw await mj(c),e}}}}const hB=["cursorRulesService","getAgentSkills","subagentsService"],pB=new WeakSet;function fB(e){("object"==typeof e&&null!==e||"function"==typeof e)&&pB.add(e)}function mB(e){return("object"==typeof e&&null!==e||"function"==typeof e)&&pB.has(e)}function gB(e,t){const r=Object.keys(t).filter((e=>!hB.includes(e)));if(r.length>0)throw new Error(`Workspace service contributors may only provide ${hB.join(", ")}. Received unsupported service keys: ${r.join(", ")}.`);for(const r of hB)Object.hasOwn(t,r)&&(e[r]=t[r])}async function wB(e,t,r){const n={config:void 0,plugins:[],pluginBootstrapOutputs:[],cursorRulesService:void 0,getAgentSkills:void 0,subagentsService:void 0,mcpLease:void 0,hooksRuntime:void 0};try{n.config=e.config?await e.config.loadConfig(t):void 0,n.plugins=e.plugins?await e.plugins.loadPlugins(t):[];const o=()=>({workspaceState:t,policy:r,services:n});n.pluginBootstrapOutputs=e.pluginBootstrap?await e.pluginBootstrap.loadPluginBootstrapOutputs(o()):n.pluginBootstrapOutputs,n.mcpLease=e.mcp?await e.mcp.createLease(o()):void 0,n.hooksRuntime=e.hooks?await e.hooks.createHooksRuntime(o()):void 0,e.localExtensibility?.prepareLocalExtensibility&&await e.localExtensibility.prepareLocalExtensibility(o());const s=e.localExtensibility?await e.localExtensibility.loadLocalExtensibility(o()):void 0;void 0!==s&&(fB(s.cursorRulesService),fB(s.subagentsService),Object.assign(n,s));for(const t of e.workspaceServicesContributors??[]){const e=await t.contributeServices(o());void 0!==e&&gB(n,e)}return n}catch(t){try{await yB(n,{disposeLocalExtensibility:void 0===e.localExtensibility?void 0:()=>e.localExtensibility?.disposeLocalExtensibility?.()})}catch(e){throw function(e,t){return new AggregateError([t],"Workspace service loading failed and resource cleanup also failed.",{cause:e})}(t,e)}throw t}}async function yB(e,t){const r=t?.preserveSharedContributorsFrom;let n;const o=async e=>{try{await mj(e)}catch(e){n??=e}};if(e.subagentsService===r?.subagentsService||mB(e.subagentsService)||await o(e.subagentsService),e.cursorRulesService===r?.cursorRulesService||mB(e.cursorRulesService)||await o(e.cursorRulesService),t?.disposeLocalExtensibility)try{await t.disposeLocalExtensibility()}catch(e){n??=e}await o(e.hooksRuntime),await o(e.mcpLease);try{await async function(e){let t;for(let r=e.length-1;r>=0;r-=1)try{await mj(e[r])}catch(e){t??=e}if(void 0!==t)throw t}(e.pluginBootstrapOutputs)}catch(e){n??=e}if(void 0!==n)throw n}const vB=["project","user","team","mdm","plugins"],bB=new Set([...vB,"all"]);function SB(e){if(void 0===e||0===e.length)return _B([]);for(const t of e)if(!bB.has(t))throw new Error(`Unsupported setting source "${t}"`);if(e.includes("all")){if(e.length>1)throw new Error('settingSources cannot mix "all" with individual setting sources');return{..._B(vB),all:!0}}return _B(e.filter((e=>"all"!==e)))}function kB(e,t){return e[t]}function _B(e){const t=new Set(e);return{project:t.has("project"),user:t.has("user"),team:t.has("team"),mdm:t.has("mdm"),plugins:t.has("plugins"),all:!1}}const CB=Object.freeze({}),EB=Object.freeze({allowMcpServers:!0,allowPlugins:!0,allowBackgroundSessions:!0,requireMcpApproval:!1,maxParallelSessions:void 0,sandboxMode:void 0,metadata:CB});async function xB(e){const t=new Set;let r;for(let n=e.length-1;n>=0;n-=1){const o=e[n];if(!t.has(o)){t.add(o);try{await mj(o)}catch(e){r??=e}}}if(void 0!==r)throw r}async function PB(e={}){const t=function(e={}){return{workspace:e.workspace??yO,config:e.config,plugins:e.plugins,pluginBootstrap:e.pluginBootstrap,mcp:e.mcp,hooks:e.hooks,localExtensibility:e.localExtensibility,resourceFactory:e.resourceFactory,resourceWrappers:e.resourceWrappers,workspaceServicesContributors:e.workspaceServicesContributors,lifecycle:e.lifecycle}}(e.adapters),r=await t.workspace.resolveWorkspaceState({workingDirectory:e.workingDirectory,projectRoot:e.projectRoot,projectDirectory:e.projectDirectory,workspaceRoots:e.workspaceRoots}),n=await async function(e,t){return e.resolvePolicy(t)}(e.policyAdapter??function(e={}){const t=Object.freeze({...EB.metadata,...e.metadata}),r={...EB,...e,metadata:t};return{name:"permissive-sdk-local",resolvePolicy:()=>r}}(),{workspaceState:r});let o=await wB(t,r,n),s=!1,i=Promise.resolve();const a=e=>{const t=i.then(e);return i=t.catch((()=>{})),t},c=t.localExtensibility,l=void 0===c?void 0:()=>c.disposeLocalExtensibility?.();return{state:r,get services(){return o},policy:n,async createSessionRuntime(e={}){if(s)throw new Error("Cannot create a session runtime after the workspace runtime has been disposed.");return async function(e){const t={sessionId:e.options?.sessionId??(0,ge.C)(),createdAt:new Date},r=Object.freeze({...e.options?.metadata??{}}),n={options:e.options??{},workspaceState:e.workspaceState,workspaceServices:e.workspaceServices,policy:e.policy,sessionState:t,metadata:r,getAgentSkills:e.workspaceServices.getAgentSkills};let o,s;const i=[];try{o=e.adapters.resourceFactory?await e.adapters.resourceFactory.createResources(n):void 0,s=o,i.push(o);for(const t of e.adapters.resourceWrappers??[])s=await t.wrapResources({...n,baseResources:o,resources:s}),i.push(s);await(e.adapters.lifecycle?.onSessionCreated?.(t))}catch(e){try{await xB(i)}catch(t){throw function(e,t){return new AggregateError([t],"Session creation failed and resource cleanup also failed.",{cause:e})}(e,t)}throw e}let a=!1;return{state:t,resources:{base:o,wrapped:s},metadata:r,workspaceServices:e.workspaceServices,policy:e.policy,async dispose(){if(!a){a=!0;try{await xB(i)}finally{await(e.adapters.lifecycle?.onSessionDisposed?.(t))}}}}}({options:e,workspaceState:r,workspaceServices:o,policy:n,adapters:t})},async reload(){s||await a((async()=>{if(s)return;const e=o,i=await wB(t,r,n);s?await yB(i,{disposeLocalExtensibility:l}):(o=i,await yB(e,{preserveSharedContributorsFrom:i,disposeLocalExtensibility:l}),await(t.lifecycle?.onWorkspaceReload?.(r)))}))},async dispose(){s||(s=!0,await a((async()=>{try{await yB(o,{disposeLocalExtensibility:l})}finally{await(t.lifecycle?.dispose())}})))}}}class RB{async requestApproval(e){return{approved:!0}}}class IB{constructor(e,t,r,n){this.approvalMode=e,this.userConfiguredPolicy=t,this.teamSettingsService=r,this.respectAdminControls=n}async getPermissions(){const e=!(!this.respectAdminControls||"insecure_none"===this.userConfiguredPolicy.type)&&(await this.teamSettingsService.getSandboxingControls()).sandboxingDisabled;return{allow:[],deny:[],approvalMode:this.approvalMode,userConfiguredPolicy:e?{type:"insecure_none"}:this.userConfiguredPolicy}}async updatePermissions(){}}class TB{async open(e,t){}async getDiagnostics(e,t){return[]}}class AB{async getCodebaseReference(e,t){}}class $B{constructor(e,t){this.inner=e,this.allowlistReports=t}async getState(e){const t=await this.inner.getState(e);return await this.reportAllowlists(e),{...t,servers:t.servers.filter((e=>"needsAuth"!==e.status))}}async reportAllowlists(e){if(void 0===this.allowlistReports)return;const{mcpLease:t,onMcpAllowlistInUse:r,onMcpServerBlockedByAllowlist:n}=this.allowlistReports;let o;try{o=await t.getClients(e)}catch(e){return void SO.Jz.warn("[sdk-mcp-state] Could not read the MCP allowlist in use:",e)}for(const[e,t]of Object.entries(o))try{if(void 0!==r){const n=await(t.getAllowlistInUse?.());void 0!==n&&r({serverName:e,allowlist:n})}if(void 0!==n){const r=await(t.getAllowlistRefusal?.());void 0!==r&&n({serverName:e,refusal:r})}}catch(e){SO.Jz.warn("[sdk-mcp-state] Could not read the MCP allowlist in use:",e)}}}class MB{constructor(e){this.subagents=e.map((e=>new vg.zz({fullPath:`sdk-inline://${e.name}`,name:e.name,description:e.description,tools:[],model:e.model,prompt:e.prompt,permissionMode:vg.b$.DEFAULT,isBackground:!1,source:"sdk"})))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents}}class DB{constructor(e={}){this.options=e,this.states=new Map,this.runCounterBySession=new Map,this.dispatchQueueBySession=new Map,this.dispatchInProgress=new Set,this.releaseRequestedBySession=new Set}getState(e){return this.states.get(e)??{status:"idle"}}isBusy(e){return"idle"!==this.getState(e).status}startRun(e,t){const r=this.nextRunId(e);return this.enqueueEvent(e,{type:"startRun",runId:r,abort:t?.abort}),r}queueResume(e,t){this.enqueueEvent(e,{type:"queueResume",queuedResume:t.queuedResume,targetRunId:t.targetRunId,mergeQueuedResume:t.mergeQueuedResume})}finishRun(e,t){this.enqueueEvent(e,{type:"runFinished",runId:t})}clearQueuedResume(e){this.enqueueEvent(e,{type:"clearQueuedResume"})}abort(e){this.enqueueEvent(e,{type:"abort"})}release(e){this.enqueueEvent(e,{type:"release"})}nextRunId(e){const t=(this.runCounterBySession.get(e)??0)+1;return this.runCounterBySession.set(e,t),t}enqueueEvent(e,t){const r=this.dispatchQueueBySession.get(e)??[];r.push(t),this.dispatchQueueBySession.set(e,r),this.drainEventQueue(e)}drainEventQueue(e){if(this.dispatchInProgress.has(e))return;let t;this.dispatchInProgress.add(e);try{const r=this.dispatchQueueBySession.get(e);if(!r)return;for(;r.length>0;){const n=r.shift();if(n)try{this.processEvent(e,n)}catch(e){t??=e}}}finally{this.dispatchQueueBySession.delete(e),this.dispatchInProgress.delete(e)}if(t)throw t}processEvent(e,t){const r=this.getState(e),{nextState:n,effects:o}=function(e,t){switch(e.status){case"idle":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"running",runId:t.runId,abort:t.abort},effects:[]};case"queueResume":return void 0===t.targetRunId?{nextState:e,effects:[]}:{nextState:{status:"runningWithQueuedResume",runId:t.targetRunId,queuedResume:t.queuedResume},effects:[]};case"runFinished":case"clearQueuedResume":case"abort":case"release":return{nextState:e,effects:[]};default:throw new Error(`Unhandled idle-state event: ${String(t)}`)}}(e,t);case"running":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"running",runId:t.runId,abort:t.abort},effects:[{type:"abortActiveRun",abort:e.abort}]};case"queueResume":return{nextState:{status:"runningWithQueuedResume",runId:e.runId,abort:e.abort,queuedResume:t.queuedResume},effects:[]};case"runFinished":return t.runId!==e.runId?{nextState:e,effects:[]}:{nextState:{status:"idle"},effects:[]};case"clearQueuedResume":case"release":return{nextState:e,effects:[]};case"abort":return{nextState:{status:"idle"},effects:[{type:"abortActiveRun",abort:e.abort}]};default:throw new Error(`Unhandled running-state event: ${String(t)}`)}}(e,t);case"runningWithQueuedResume":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"runningWithQueuedResume",runId:t.runId,abort:t.abort,queuedResume:e.queuedResume},effects:[{type:"abortActiveRun",abort:e.abort}]};case"queueResume":return{nextState:{...e,queuedResume:t.mergeQueuedResume(e.queuedResume,t.queuedResume)},effects:[]};case"runFinished":return t.runId!==e.runId?{nextState:e,effects:[]}:{nextState:{status:"running",runId:e.runId,abort:e.abort},effects:[{type:"startQueuedRun",sourceRunId:e.runId,queuedResume:e.queuedResume}]};case"clearQueuedResume":return{nextState:{status:"running",runId:e.runId,abort:e.abort},effects:[]};case"abort":return{nextState:{status:"idle"},effects:[{type:"abortActiveRun",abort:e.abort}]};case"release":return{nextState:e,effects:[]};default:throw new Error(`Unhandled runningWithQueuedResume-state event: ${String(t)}`)}}(e,t);default:return{nextState:e,effects:[]}}}(r,t);this.states.set(e,n),this.options.onStateChange?.({sessionId:e,previousState:r,nextState:n});for(const t of o)switch(t.type){case"abortActiveRun":t.abort?.();break;case"startQueuedRun":this.options.onQueuedRunReady?.({sessionId:e,sourceRunId:t.sourceRunId,queuedResume:t.queuedResume});break;default:throw new Error(`Unhandled lifecycle manager effect: ${String(t)}`)}const s=this.getState(e);"release"===t.type&&"idle"!==s.status&&this.releaseRequestedBySession.add(e),"idle"!==s.status||"release"!==t.type&&!this.releaseRequestedBySession.has(e)||(this.states.delete(e),this.runCounterBySession.delete(e),this.releaseRequestedBySession.delete(e))}}function OB(e){return"string"==typeof e&&e.trim().length>0}function FB(e,t){return new he.jn({command:t.command??"",workingDirectory:t.workingDirectory??"",error:e,isReadonly:!0})}function NB(e){return{execute:async(t,r)=>new MI.v3({result:{case:"permissionDenied",value:new MI.U7({path:r.path,error:e,isReadonly:!0})}})}}function LB(e){return{execute:async(t,r)=>new jw.Pi({result:{case:"permissionDenied",value:new jw.QG({path:r.path,clientVisibleError:e,isReadonly:!0})}})}}function jB(e){return{execute:async(t,r)=>new Ac.iz({result:{case:"permissionDenied",value:new Ac.HQ({error:`${e} Tool: ${r.name}`,isReadonly:!0})}})}}var UB=r("../agent-kv/dist/subagent-states.js");let BB;function WB(e){const t=process.env.CURSOR_DATA_DIR;if(t?.trim())return _o(e);let r;try{r=(0,o.homedir)()}catch{r=void 0}return function(e){const t=e.cursorDataDir?.trim();return t?(0,s.join)(t,"projects",(0,So.r_)(e.workspacePath)):void 0!==e.homeDir&&function(e){if(""===e.trim())return!1;try{return!!(0,xo.statSync)(e).isDirectory()&&((0,xo.accessSync)(e,xo.constants.W_OK),!0)}catch{return!1}}(e.homeDir)?(0,s.join)(e.homeDir,".cursor","projects",(0,So.r_)(e.workspacePath)):(0,s.join)(e.ensureFallbackRoot(e.tempDir),(0,So.r_)(e.workspacePath))}({workspacePath:e,homeDir:r,tempDir:(0,o.tmpdir)(),ensureFallbackRoot:e=>(void 0===BB&&(BB=function(e){return(0,xo.mkdtempSync)((0,s.join)(e,"cursor-transcripts-"))}(e)),BB)})}async function HB(e,t){const r=(0,s.dirname)(e);await(0,Co.mkdir)(r,{recursive:!0}),await(0,Co.writeFile)(e,t,"utf-8")}class qB{constructor(e){this.writeChain=Promise.resolve(),this.workspacePath=e.workspacePath,this.conversationId=e.conversationId,this.parentConversationId=e.parentConversationId,this.blobStore=e.blobStore,this.projectDir=WB(this.workspacePath);const t=this.parentConversationId?(e,t)=>{const r=DF({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,r)}:void 0;this.transcriptStore=new uN(this.projectDir,e.blobStore,HB,{writeText:!1,writeJsonl:!0,...t?{pathResolver:t}:{}}),this.nestedSubagentTranscriptStore=new uN(this.projectDir,e.blobStore,HB,{writeText:!1,writeJsonl:!0,pathResolver:(e,t)=>{const r=DF({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.conversationId});return(0,s.join)(this.projectDir,r)}})}enqueueWrite(e,t){const r=this.writeChain;return this.writeChain=r.then((async()=>{try{await e()}catch(e){SO.Jz.warn(`${t} ${e instanceof Error?e.message:String(e)}`)}})),this.writeChain}async writeFromState(e,t){return this.enqueueWrite((async()=>{await this.transcriptStore.writeFromStateFull(e,t,this.conversationId);const r=await(0,UB.Vn)(e,t,this.blobStore);for(const[t,n]of Object.entries(r))n?.conversationState&&await this.nestedSubagentTranscriptStore.writeFromStateFull(e,n.conversationState,t)}),"[LocalTranscriptWriter] Failed to write transcript:")}async writeTurnEndedFromState(e,t,r){return this.enqueueWrite((async()=>{await this.transcriptStore.writeFromStateFull(e,t,this.conversationId,{turnEnded:r})}),"[LocalTranscriptWriter] Failed to write turn-ended transcript:")}waitForPendingWrites(){return this.writeChain}getTranscriptPath(){if(this.parentConversationId){const e=DF({conversationId:this.conversationId,ext:"jsonl",kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,e)}return function(e,t){const r=DF({conversationId:t,ext:"jsonl",kind:"primary"});return(0,s.join)(WB(e),r)}(this.workspacePath,this.conversationId)}getProjectDir(){return this.projectDir}}const zB=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,GB="User aborted/interrupted manually.";class VB{constructor(e){this.sessions=new Map,this.backgroundRuns=new Map,this.activeForegroundExecutions=new Map,this.backgroundPromises=new Set,this.pendingReleaseSessions=new Set,this.childParentIds=new Map,this.parentChildIds=new Map,this.queuedChildCompletions=new Map,this.childCompletionWaiters=new Map,this.childLineageRequestIds=new Map,this.untrackedParentRequestIds=new Map,this.agentClient=e.agentClient,this.getResources=e.getResources,this.mcpTools=e.mcpTools??[],this.workspacePath=e.workspacePath,this.parentConversationId=e.parentConversationId;const t=e.rootRequestId?.trim();this.rootLineageRequestId=void 0!==t&&t.length>0?t:(0,ge.C)(),this.headers=e.headers,this.endlessRetries=e.endlessRetries,this.onSessionCreated=e.onSessionCreated,this.onInteractionUpdate=e.onInteractionUpdate,this.onSessionCompleted=e.onSessionCompleted,this.onSessionReleased=e.onSessionReleased,this.onSubagentTokenDelta=e.onSubagentTokenDelta,this.lifecycleStore=new DB}async createOrResumeSession(e,t){if(t.forkAgentId)throw new Error("forkAgentId is not supported in local subagents.");const r=t.resumeAgentId;if(r&&function(e){if(!zB.test(e))throw new Error(`Invalid resumeAgentId format: ${e}`)}(r),r&&!t.prompt)return r;if(r&&OB(t.prompt)&&this.isBackgroundRunBusy(r))throw new Error("Sub-agent is currently running. You may send the follow-up message when it has completed.");if(r&&this.sessions.get(r))return r;const n=r??(0,ge.C)(),o=function(e){const t=new re.We,r=(0,kO.sh)(e),n=new kO.pH(new re.ve,t);return n.setMetadata("agentId",r.agentId),n.setMetadata("latestRootBlobId",r.latestRootBlobId),n.setMetadata("name",r.name),n.setMetadata("createdAt",r.createdAt),n.setMetadata("mode",r.mode),n.setMetadata("isRunEverything",r.isRunEverything),n.setMetadata("lastUsedModel",r.lastUsedModel),n.setMetadata("lastDebugServerPort",r.lastDebugServerPort),n.setMetadata("currentPlanUri",r.currentPlanUri),n.setMetadata("subagentInfo",r.subagentInfo),n.setMetadata("blobEncryptionKey",r.blobEncryptionKey),n}(n),s=new qB({workspacePath:this.workspacePath,conversationId:n,parentConversationId:this.parentConversationId,blobStore:o.getBlobStore()});return this.sessions.set(n,{agentStore:o,transcriptWriter:s,toolCallId:t.toolCallId}),this.onSessionCreated?.({agentId:n,toolCallId:t.toolCallId,subagentType:t.subagentType,parentAgentId:t.parentConversationId}),n}async runSession(e,t,r,n){if(this.isAwaitBackgroundMode(r))return this.awaitBackgroundRun(r.resumeAgentId,e.signal);const o=this.sessions.get(t);if(!o)return{status:"error",error:`Subagent session not found: ${t}`};if(r.runInBackground){const[n,s]=e.withDetached().withCancel();return this.registerBackgroundRun(t,this.executeSubagent(n,t,r,o),r.parentConversationId,s),{status:"background",backgroundReason:vg.qL.AGENT_REQUEST,toolCallCount:0}}const[s,i]=e.withDetached().withCancel();let a=!1;const c=()=>{a||i()};e.signal.addEventListener("abort",c,{once:!0}),e.signal.aborted&&c();let l=()=>{};const u=new Promise((e=>{l=e})),d={requestBackground:()=>!!a||!s.signal.aborted&&(a=!0,e.signal.removeEventListener("abort",c),l(),!0)};this.activeForegroundExecutions.set(r.toolCallId,d),this.activeForegroundExecutions.set(t,d);try{const e=this.executeSubagent(s,t,r,o),n=await Promise.race([e.then((e=>({handedOff:!1,outcome:e}))),u.then((()=>({handedOff:!0})))]);return n.handedOff?(this.registerBackgroundRun(t,e,r.parentConversationId,i),{status:"background",backgroundReason:vg.qL.USER_REQUEST,toolCallCount:0}):(this.onSessionCompleted?.(t,n.outcome),n.outcome)}finally{this.clearForegroundExecution(r.toolCallId,d),this.clearForegroundExecution(t,d),a||e.signal.removeEventListener("abort",c)}}forceBackgroundByToolCallId(e){const t=this.activeForegroundExecutions.get(e);return t?.requestBackground()?new oo.a3({status:oo.jh.ACCEPTED}):new oo.a3({status:oo.jh.NOT_FOUND})}clearForegroundExecution(e,t){this.activeForegroundExecutions.get(e)===t&&this.activeForegroundExecutions.delete(e)}releaseSession(e){this.lifecycleStore.release(e),this.isBackgroundRunBusy(e)?this.pendingReleaseSessions.add(e):this.cleanupSession(e)}async awaitBackgroundWorkers(){for(;this.backgroundPromises.size>0;)await Promise.allSettled([...this.backgroundPromises])}async waitForBackgroundCompletions(e,t){return this.collectAvailableChildCompletions(e,t)}isBackgroundRunBusy(e){return this.lifecycleStore.isBusy(e)||this.backgroundRuns.has(e)}registerBackgroundRun(e,t,r,n){this.registerParentChildLink(e,r);const o=this.lifecycleStore.startRun(e,{abort:n}),s=t.catch((e=>({status:"error",error:e instanceof Error?e.message:String(e)}))),i={runId:o,promise:s};this.backgroundRuns.set(e,i),this.backgroundPromises.add(s),s.then((t=>{this.lifecycleStore.finishRun(e,o);const r=this.backgroundRuns.get(e);if(r?.runId===o){this.backgroundRuns.delete(e),this.enqueueChildCompletion(e,o,t),this.maybeCleanupReleasedSession(e);try{this.onSessionCompleted?.(e,t)}catch(t){SO.Jz.error("[LocalSubagentHostAdapter] onSessionCompleted threw after background run",{agentId:e,error:t instanceof Error?t.message:String(t)})}}return t})).finally((()=>this.backgroundPromises.delete(s)))}maybeCleanupReleasedSession(e){this.pendingReleaseSessions.has(e)&&!this.isBackgroundRunBusy(e)&&this.cleanupSession(e)}cleanupSession(e){this.pendingReleaseSessions.delete(e);const t=this.sessions.get(e);if(!t)return;const r=this.parentChildIds.get(e);if(r)for(const e of r)this.childParentIds.delete(e);this.removeParentChildLink(e),this.parentChildIds.delete(e),this.queuedChildCompletions.delete(e),this.childCompletionWaiters.delete(e),t.transcriptWriter.waitForPendingWrites().catch((()=>{})),this.sessions.delete(e),this.onSessionReleased?.(e)}async executeSubagent(e,t,r,n){return r.continuationConfig?this.executeSubagentWithContinuation(e,t,r,n,r.continuationConfig):this.executeSubagentOnce(e,t,r,n)}async executeSubagentWithContinuation(e,t,r,n,o){const s=o.maxLoops>0?o.maxLoops:Number.POSITIVE_INFINITY;let i=await this.runContinuationLoop(e,t,r,n,o,s);if(!o.collectBackgroundChildren||"completed"!==i.status)return i;for(let a=0;a<500;a++){if(e.signal.aborted)return{status:"error",error:"Subagent was aborted by the user"};let a;try{a=await this.collectAvailableChildCompletions(t,e.signal)}catch{return{status:"error",error:"Subagent was aborted by the user"}}if(0===a.length)return i;const c=this.buildChildrenCompletedMessage(a,o.childrenCompletedMessageTemplate);if(i=await this.runContinuationLoop(e,t,new oo.Pw({...r,prompt:c,resumeAgentId:t,runInBackground:!1}),n,o,s),"completed"!==i.status)return i}return i}async runContinuationLoop(e,t,r,n,o,s){let i,a,c=0;for(let l=0;l0?(c=0,i=void 0):(c+=1,i=c>=o.idleThreshold?`DONE_${(0,ge.C)().replace(/-/g,"").slice(0,8)}`:void 0)}return a??{status:"error",error:"Subagent continuation exited unexpectedly"}}computeContinuationNudge(e,t,r){return t>=e.idleThreshold&&void 0!==r?e.escapeMessageTemplate.replace("{idle_count}",String(t)).replace("{escape_token}",r):e.nudgeMessage}lineageForChildRun(e){this.childLineageRequestIds.has(e.agentId)||this.childLineageRequestIds.set(e.agentId,(0,ge.C)());const t=e.parentConversationId?.trim()??"",r=e.toolCallId.trim();return{parentRequestId:""===t||t===this.parentConversationId?this.rootLineageRequestId:this.childLineageRequestIds.get(t)??this.untrackedParentRequestId(t),rootParentRequestId:this.rootLineageRequestId,...r.length>0?{parentAgentToolCallId:r}:{}}}untrackedParentRequestId(e){let t=this.untrackedParentRequestIds.get(e);return void 0===t&&(t=(0,ge.C)(),this.untrackedParentRequestIds.set(e,t)),t}async executeSubagentOnce(e,t,r,n){const o=this.lineageForChildRun({agentId:t,parentConversationId:r.parentConversationId,toolCallId:r.toolCallId});let s,a=0;const c=new i.QFf({action:{case:"userMessageAction",value:new i.Vtf({userMessage:new i.RGk({text:r.prompt})})}}),l=new i.Gmx({modelId:r.modelId,displayModelId:r.modelId,displayName:r.modelId});void 0!==r.credentials.case&&(l.credentials=r.credentials);const u=new bO,d={sendUpdate:async(e,r)=>{"tokenDelta"===r.message.case&&this.onSubagentTokenDelta?.(t,r.message.value.tokens),"toolCallStarted"!==r.message.case&&"toolCallCompleted"!==r.message.case&&"partialToolCall"!==r.message.case||this.onInteractionUpdate?.(t,r),"toolCallCompleted"===r.message.case&&a++,"textDelta"===r.message.case&&(s=(s??"")+r.message.value.text)},query:async(e,t)=>function(e){const t=e.query.case;switch(t){case"webSearchRequestQuery":return dr(e.id,"Web search is not supported in local subagent");case"webFetchRequestQuery":return pr(e.id,"Web fetch is not supported in local subagent");case"switchModeRequestQuery":return gr(e.id,"Subagent mode switches are not supported in local subagent");case"askQuestionInteractionQuery":{const t=new Qt.tz({result:{case:"rejected",value:new Qt.ox({reason:"Interactive questions are not supported in local subagent mode"})}});return fr(e.id,t)}default:throw new Error(`Unhandled interaction query type in local subagent: ${String(t)}`)}}(t)},h={handleCheckpoint:async(e,t)=>{await n.agentStore.handleCheckpoint(e,t),n.transcriptWriter.writeFromState(e,t)},getLatestCheckpoint:()=>n.agentStore.getLatestCheckpoint()};try{const i=r.rootParentConversationId?.trim(),p=r.parentConversationId?.trim(),f=void 0!==i&&""!==i?i:void 0!==p&&""!==p?p:t,m=await this.getResources({agentId:t,parentAgentId:r.parentConversationId}),g=r.readonly?new J(m,function(e){const t=[G(HT,NB(e.errorMessage)),G(qT,LB(e.errorMessage)),G(eo,jB(e.errorMessage))];return e.wrapShell&&t.push(G(jT,function(e){return{execute:async(t,r)=>new he.W4({result:{case:"permissionDenied",value:FB(e,r)}})}}(e.errorMessage)),G(ee,function(e){return{async*execute(t,r){yield new he.FI({event:{case:"permissionDenied",value:FB(e,r)}})}}}(e.errorMessage)),G(vA,function(e){return{execute:async(t,r)=>new Do.Lt({result:{case:"permissionDenied",value:FB(e,r)}})}}(e.errorMessage))),e.includeWriteBackgroundShellStdin&&t.push(G(bA,function(e){return{execute:async(t,r)=>new Do.nt({result:{case:"error",value:new Do.Gv({error:e})}})}}(e.errorMessage))),t}({errorMessage:"This operation is not allowed in readonly mode. The subagent was launched with readonly: true, which restricts shell, write, delete, and MCP operations.",wrapShell:!0,includeWriteBackgroundShellStdin:!0})):m;return await this.agentClient.run(e,n.agentStore.getConversationStateStructure(),c,l,d,g,n.agentStore.getBlobStore(),u,h,[...this.mcpTools],{conversationGroupId:f,conversationId:t,...n.transcriptWriter.parentConversationId?{transcriptParentConversationId:n.transcriptWriter.parentConversationId}:{},subagentTypeName:r.subagentType||void 0,...o,headers:CO(n.agentStore.getMetadata("blobEncryptionKey"),this.headers),endlessRetries:this.endlessRetries,subagentModelOverrides:[]}),await n.transcriptWriter.writeTurnEndedFromState(e,n.agentStore.getConversationStateStructure(),e.signal.aborted?{status:"aborted",error:GB}:{status:"success"}),{status:"completed",finalMessage:s,toolCallCount:a}}catch(r){const o=r instanceof Error?r.message:String(r);return SO.Jz.error("[LocalSubagentHostAdapter] Subagent session failed",{agentId:t,error:o}),await n.transcriptWriter.writeTurnEndedFromState(e,n.agentStore.getLatestCheckpoint()??n.agentStore.getConversationStateStructure(),this.getTurnEndedFromError(e,o)),e.signal.aborted?{status:"aborted",error:GB}:{status:"error",error:o}}}getTurnEndedFromError(e,t){return e.signal.aborted?{status:"aborted",error:GB}:{status:"error",error:t}}isAwaitBackgroundMode(e){if(!Boolean(e.resumeAgentId&&!OB(e.prompt)&&e.readonly&&!0!==e.runInBackground))return!1;if(0===(e.parentConversationId??"").trim().length)throw new Error(`Missing parentConversationId for subagent await/status check (subagentId: ${e.resumeAgentId})`);return!0}async awaitBackgroundRun(e,t){const r=this.backgroundRuns.get(e);return r?this.awaitBackgroundEntry(r,t):this.isBackgroundRunBusy(e)?this.awaitBusyLifecycleRun(e,t):{status:"error",error:`No background subagent found for id: ${e}`}}async awaitBackgroundRunBounded(e,t){const r=t.agentId;if(e.signal.aborted)return new oo.zJ({result:{case:"stillRunning",value:new oo.L5({agentId:r})}});const n=this.backgroundRuns.get(r);if(void 0===n){const e=this.takeQueuedChildCompletion(r);return void 0!==e?"success"===e.status?new oo.zJ({result:{case:"complete",value:new oo.bE({agentId:r,finalMessage:e.finalMessage,toolCallCount:e.toolCallCount??0})}}):new oo.zJ({result:{case:"error",value:new oo.Y({agentId:r,error:e.finalMessage||"Subagent was aborted"})}}):this.isBackgroundRunBusy(r)?new oo.zJ({result:{case:"stillRunning",value:new oo.L5({agentId:r})}}):new oo.zJ({result:{case:"notFound",value:new oo.Hq({agentId:r})}})}const[o,s]=e.withTimeoutAndCancel(Math.max(0,t.timeoutMs)),i=await new Promise((e=>{const t=()=>e(void 0);o.signal.addEventListener("abort",t,{once:!0}),n.promise.then(e).finally((()=>{o.signal.removeEventListener("abort",t),s()}))}));return void 0===i||"background"===i.status||e.signal.aborted?new oo.zJ({result:{case:"stillRunning",value:new oo.L5({agentId:r})}}):(this.takeQueuedChildCompletion(r,n.runId),"completed"===i.status?new oo.zJ({result:{case:"complete",value:new oo.bE({agentId:r,finalMessage:i.finalMessage,toolCallCount:i.toolCallCount??0})}}):new oo.zJ({result:{case:"error",value:new oo.Y({agentId:r,error:i.error??"Subagent was aborted"})}}))}takeQueuedChildCompletion(e,t){for(const[r,n]of this.queuedChildCompletions){const o=n.findIndex((r=>r.agentId===e&&(void 0===t||r.runId===t)));if(-1===o)continue;const[s]=n.splice(o,1);return 0===n.length&&this.queuedChildCompletions.delete(r),s}}async awaitBusyLifecycleRun(e,t){for(;this.isBackgroundRunBusy(e);){if(t.aborted)return{status:"error",error:"Await timed out while task is still running"};const r=this.backgroundRuns.get(e);if(r)return this.awaitBackgroundEntry(r,t);await new Promise((e=>setTimeout(e,50)))}return{status:"completed",toolCallCount:0}}async awaitBackgroundEntry(e,t){if(t.aborted)return{status:"error",error:"Await timed out while task is still running"};const r={status:"error",error:"Await timed out while task is still running"};return new Promise((n=>{const o=()=>{n(r)};t.addEventListener("abort",o,{once:!0}),e.promise.then(n).finally((()=>t.removeEventListener("abort",o)))}))}registerParentChildLink(e,t){const r=t?.trim();if(!r||r===e||!this.sessions.has(r)&&r!==this.parentConversationId)return;const n=this.childParentIds.get(e);if(n===r)return;n&&(this.parentChildIds.get(n)?.delete(e),0===(this.parentChildIds.get(n)?.size??0)&&this.parentChildIds.delete(n)),this.childParentIds.set(e,r);const o=this.parentChildIds.get(r)??new Set;o.add(e),this.parentChildIds.set(r,o)}removeParentChildLink(e){const t=this.childParentIds.get(e);if(!t)return;this.childParentIds.delete(e);const r=this.parentChildIds.get(t);r?.delete(e),0===(r?.size??0)&&this.parentChildIds.delete(t)}enqueueChildCompletion(e,t,r){const n=this.childParentIds.get(e);if(!n)return;const o=this.queuedChildCompletions.get(n)??[];o.push({agentId:e,runId:t,status:"completed"===r.status?"success":"error"===r.status?"error":"aborted",finalMessage:"completed"===r.status?r.finalMessage??"":"error"===r.status?r.error:"Subagent was aborted by the user",..."completed"===r.status&&void 0!==r.toolCallCount?{toolCallCount:r.toolCallCount}:{}}),this.queuedChildCompletions.set(n,o),this.removeParentChildLink(e);const s=this.childCompletionWaiters.get(n);if(s){this.childCompletionWaiters.delete(n);for(const e of s)e()}}async collectAvailableChildCompletions(e,t){const r=this.drainChildCompletions(e);return r.length>0?r:this.hasPendingChildSubagents(e)?(await this.waitForChildCompletion(e,t),this.drainChildCompletions(e)):[]}hasPendingChildSubagents(e){return(this.parentChildIds.get(e)?.size??0)>0}drainChildCompletions(e){const t=this.queuedChildCompletions.get(e)??[];return this.queuedChildCompletions.delete(e),t}async waitForChildCompletion(e,t){if(t.aborted)throw new Error("aborted");await new Promise(((r,n)=>{const o=this.childCompletionWaiters.get(e)??new Set,s=()=>{a(),r()},i=()=>{a(),n(new Error("aborted"))},a=()=>{o.delete(s),0===o.size&&this.childCompletionWaiters.delete(e),t.removeEventListener("abort",i)};o.add(s),this.childCompletionWaiters.set(e,o),t.addEventListener("abort",i,{once:!0})}))}buildChildrenCompletedMessage(e,t){const r=e.map((e=>{const t="success"===e.status?"SUCCESS":"FAILED";return`## Agent ${e.agentId} -- ${t}\n\n${e.finalMessage}`})).join("\n\n---\n\n");return t.replace("{summaries}",r)}}var KB=r("../proto/dist/generated/agent/v1/agent_service_connect.js"),JB=r("../proto/dist/generated/agent/v1/requested_model_pb.js"),ZB=r("../proto/dist/generated/agent/v1/selected_context_pb.js"),XB=r("./src/agent/analytics.ts"),QB=r("../proto/dist/generated/agent/v1/todo_tool_pb.js");const YB={[Og.w3.UNSPECIFIED]:"unspecified",[Og.w3.LEFT]:"left",[Og.w3.RIGHT]:"right",[Og.w3.MIDDLE]:"middle",[Og.w3.BACK]:"back",[Og.w3.FORWARD]:"forward"},eW={[Og.Dh.UNSPECIFIED]:"unspecified",[Og.Dh.UP]:"up",[Og.Dh.DOWN]:"down",[Og.Dh.LEFT]:"left",[Og.Dh.RIGHT]:"right"},tW={[Og.EB.UNSPECIFIED]:"unspecified",[Og.EB.TAP]:"tap",[Og.EB.DOWN]:"down",[Og.EB.UP]:"up"};function rW(e){return YB[e]??"unspecified"}function nW(e){return void 0===e?void 0:{x:e.x,y:e.y}}function oW({result:e}){switch(e.case){case"success":return{status:"success",value:{actionCount:e.value.actionCount,durationMs:e.value.durationMs,settleMs:e.value.settleMs,screenshotPath:e.value.screenshotPath,cursorPosition:nW(e.value.cursorPosition),log:e.value.log}};case"error":return{status:"error",error:{message:e.value.error,actionCount:e.value.actionCount,durationMs:e.value.durationMs,screenshotPath:e.value.screenshotPath,log:e.value.log}};default:return}}function sW(e,t){switch(e.message.case){case"textDelta":return{type:"text-delta",text:e.message.value.text};case"thinkingDelta":return{type:"thinking-delta",text:e.message.value.text};case"thinkingCompleted":return{type:"thinking-completed",thinkingDurationMs:e.message.value.thinkingDurationMs};case"userMessageAppended":return{type:"user-message-appended",userMessage:{type:"user_message",session_id:t,text:e.message.value.userMessage?.text??""}};case"tokenDelta":return{type:"token-delta",tokens:e.message.value.tokens};case"summary":return{type:"summary",summary:e.message.value.summary};case"summaryStarted":return{type:"summary-started"};case"summaryCompleted":{const{failed:t,fallback:r}=e.message.value;return{type:"summary-completed",...t?{failed:t}:{},...r?{fallback:r}:{}}}case"shellOutputDelta":return{type:"shell-output-delta",event:e.message.value.event.case?{case:e.message.value.event.case,value:e.message.value.event.value?.toJson?.()??e.message.value.event.value}:{}};case"toolCallStarted":return iW("tool-call-started",e.message.value);case"partialToolCall":return iW("partial-tool-call",e.message.value);case"toolCallCompleted":return iW("tool-call-completed",e.message.value);case"heartbeat":return null;case"turnEnded":{const t=e.message.value;return{type:"turn-ended",...(void 0!==t.inputTokens||void 0!==t.outputTokens||void 0!==t.cacheReadTokens||void 0!==t.cacheWriteTokens)&&{usage:{inputTokens:Number(t.inputTokens??BigInt(0)),outputTokens:Number(t.outputTokens??BigInt(0)),cacheReadTokens:Number(t.cacheReadTokens??BigInt(0)),cacheWriteTokens:Number(t.cacheWriteTokens??BigInt(0)),...t.reasoningTokens&&{reasoningTokens:Number(t.reasoningTokens)}}}}}case"modelCallCompleted":{const t=e.message.value;return{type:"model-call-completed",modelCallId:t.modelCallId,usage:{inputTokens:Number(t.inputTokens),outputTokens:Number(t.outputTokens),cacheReadTokens:Number(t.cacheReadTokens),cacheWriteTokens:Number(t.cacheWriteTokens),...t.reasoningTokens&&{reasoningTokens:Number(t.reasoningTokens)}}}}case"toolCallDelta":{const r=e.message.value,n=r.toolCallDelta;if("taskToolCallDelta"!==n?.delta.case)return null;const o=n.delta.value.interactionUpdate;if(void 0===o)return null;const s=sW(o,t);return null!==s&&function(e){switch(e.type){case"text-delta":case"thinking-delta":case"thinking-completed":case"tool-call-started":case"tool-call-completed":case"partial-tool-call":case"step-started":case"step-completed":case"tool-requests-listed":return!0;default:return!1}}(s)?{type:"tool-call-delta",callId:r.callId,modelCallId:r.modelCallId,taskUpdate:s}:null}case"stepStarted":return{type:"step-started",stepId:Number(e.message.value.stepId)};case"toolRequestsListed":return{type:"tool-requests-listed",callCount:e.message.value.callCount};case"stepCompleted":return{type:"step-completed",stepId:Number(e.message.value.stepId),stepDurationMs:Number(e.message.value.stepDurationMs)};case"postRequestPrompt":case"activeBranchChange":case"feedbackRequest":case"responseComparison":case"contextInjectionState":case"routedModel":case"grokBotNudge":case"thinkingNote":case"voiceCallUtterance":case void 0:return null;default:return e.message,null}}function iW(e,t){const r=function(e){if(!e?.tool)return null;switch(e.tool.case){case"shellToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"shell",args:{command:t.command,...t.workingDirectory?{workingDirectory:t.workingDirectory}:{},...t.timeout?{timeout:t.timeout}:{}},...r?{result:hW(r)}:{}}:null}case"deleteToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"delete",args:{path:t.path},...r?{result:pW(r)}:{}}:null}case"globToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"glob",args:{globPattern:t.globPattern,...t.targetDirectory?{targetDirectory:t.targetDirectory}:{}},...r?{result:fW(r)}:{}}:null}case"grepToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"grep",args:{pattern:t.pattern,...t.path?{path:t.path}:{},...t.glob?{glob:t.glob}:{},...t.outputMode?{outputMode:t.outputMode}:{},...t.contextBefore?{contextBefore:t.contextBefore}:{},...t.contextAfter?{contextAfter:t.contextAfter}:{},...t.context?{context:t.context}:{},...t.caseInsensitive?{caseInsensitive:t.caseInsensitive}:{},...t.type?{type:t.type}:{},...t.headLimit?{headLimit:t.headLimit}:{},...void 0!==t.offset?{offset:t.offset}:{},...t.multiline?{multiline:t.multiline}:{},...t.sort?{sort:t.sort}:{},...t.sortAscending?{sortAscending:t.sortAscending}:{}},...r?{result:mW(r)}:{}}:null}case"readToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"read",args:{path:t.path},...r?{result:wW(r)}:{}}:null}case"editToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"edit",args:{path:t.path},...r?{result:yW(r)}:{}}:null}case"lsToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"ls",args:{path:t.path,...t.ignore&&t.ignore.length>0?{ignore:t.ignore}:{}},...r?{result:vW(r)}:{}}:null}case"readLintsToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"readLints",args:{paths:t.paths},...r?{result:SW(r)}:{}}:null}case"mcpToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"mcp",args:{...t.providerIdentifier?{providerIdentifier:t.providerIdentifier}:{},...t.toolName?{toolName:t.toolName}:{},...t.args?{args:Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()])))}:{}},...r?{result:kW(r)}:{}}:null}case"generateImageToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"generateImage",args:{description:t.description,...t.filePath?{filePath:t.filePath}:{}},...r?{result:CW(r)}:{}}:null}case"recordScreenToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"recordScreen",args:{mode:EW(t.mode)},...r?{result:xW(r)}:{}}:null}case"semSearchToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"semSearch",args:{query:t.query,...t.targetDirectories&&t.targetDirectories.length>0?{targetDirectories:t.targetDirectories}:{},...t.explanation?{explanation:t.explanation}:{}},...r?{result:_W(r)}:{}}:null}case"createPlanToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"createPlan",args:{plan:t.plan},...r?{result:PW(r)}:{}}:null}case"updateTodosToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"updateTodos",args:{todos:t.todos.map((e=>({content:e.content,status:IW(e.status)})))},...r?{result:RW(r)}:{}}:null}case"fetchToolCall":case"switchModeToolCall":return null;case"computerUseToolCall":return function({args:e,result:t}){return e?{type:"computerUse",args:{actions:e.actions.flatMap((e=>function({action:e}){switch(e.case){case"mouseMove":return{type:"mouseMove",coordinate:nW(e.value.coordinate)};case"click":return{type:"click",coordinate:nW(e.value.coordinate),button:rW(e.value.button),count:e.value.count,modifierKeys:e.value.modifierKeys};case"mouseDown":case"mouseUp":return{type:e.case,button:rW(e.value.button)};case"drag":return{type:"drag",path:e.value.path.map((e=>({x:e.x,y:e.y}))),button:rW(e.value.button),modifierKeys:e.value.modifierKeys};case"scroll":return{type:"scroll",coordinate:nW(e.value.coordinate),direction:eW[e.value.direction]??"unspecified",amount:e.value.amount,modifierKeys:e.value.modifierKeys};case"type":return{type:"type",text:e.value.text};case"key":return{type:"key",key:e.value.key,holdDurationMs:e.value.holdDurationMs,stroke:tW[e.value.stroke]??"unspecified"};case"wait":return{type:"wait",durationMs:e.value.durationMs};case"screenshot":case"cursorPosition":return{type:e.case};default:return}}(e)??[])),description:e.description},result:t?oW(t):void 0}:null}(e.tool.value);case"readTodosToolCall":case"webSearchToolCall":case"listMcpResourcesToolCall":case"readMcpResourceToolCall":return null;case"taskToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"task",args:aW(t),...r?{result:uW(r)}:{}}:null}case"applyAgentDiffToolCall":case"askQuestionToolCall":case"writeShellStdinToolCall":case"reflectToolCall":case"setupVmEnvironmentToolCall":case"replaceEnvToolCall":case"startGrindExecutionToolCall":case"startGrindPlanningToolCall":case"truncatedToolCall":case"webFetchToolCall":case"reportBugfixResultsToolCall":case"aiAttributionToolCall":case"prManagementToolCall":case"editPrLabelsToolCall":case"fetchCloudAgentDataToolCall":case"mcpAuthToolCall":case"connectScmToolCall":case"searchConversationsToolCall":case"awaitToolCall":case"blameByFilePathToolCall":case"getMcpToolsToolCall":case"reportBugToolCall":case"setActiveBranchToolCall":case"communicateUpdateToolCall":case"sendFinalSummaryToolCall":case"updateOriginPrCodeTourToolCall":case"getOriginPrCodeTourToolCall":case"recordCiInvestigationFindingsToolCall":case"sendMessageToolCall":case"sendToUserToolCall":case"createGoalToolCall":case"updateGoalToolCall":case"getAgentStatusToolCall":case"sendToAgentToolCall":case"readAgentTranscriptToolCall":case"createAgentToolCall":case"createProjectToolCall":case"startProjectUpdatesToolCall":case"stopProjectUpdatesToolCall":case"manageAccessToolCall":case"stopAgentToolCall":case"listTrackedTasksToolCall":case"createTrackedTasksToolCall":case"updateTrackedTasksToolCall":case"deleteTrackedTasksToolCall":case"updateTrackedTaskStatusesToolCall":case"updateTrackedTaskTagsToolCall":case"writeCanvasToolCall":case"readCanvasToolCall":case"generateVideoToolCall":case"xSearchToolCall":case"executeToolCall":case void 0:return null;default:return e.tool}}(t.toolCall);return r?{type:e,callId:t.callId,toolCall:r,modelCallId:t.modelCallId}:null}function aW(e){return{description:e.description??"",prompt:e.prompt??"",...e.subagentType?{subagentType:cW(e.subagentType)}:{},...e.model?{model:e.model}:{},...e.resume?{resume:e.resume}:{},...e.agentId?{agentId:e.agentId}:{},...e.attachments&&e.attachments.length>0?{attachments:e.attachments}:{},...void 0!==e.mode?{mode:lW(e.mode)}:{},...e.respondingToMessageIds&&e.respondingToMessageIds.length>0?{respondingToMessageIds:e.respondingToMessageIds}:{}}}function cW(e){const t=e.type.case;return t?"custom"===t?{kind:t,name:e.type.value.name}:{kind:t}:{kind:"unspecified"}}function lW(e){switch(e){case vg.FL.AGENT:return"agent";case vg.FL.PLAN:return"plan";default:return"unspecified"}}function uW(e){if(e.result?.case)switch(e.result.case){case"success":{const t=e.result.value;return{status:"success",value:{...t.conversationSteps&&t.conversationSteps.length>0?{conversationSteps:t.conversationSteps.map((e=>e.toJson?.()??e))}:{},...t.agentId?{agentId:t.agentId}:{},isBackground:t.isBackground??!1,...void 0!==t.durationMs?{durationMs:Number(t.durationMs)}:{},...t.resultSuffix?{resultSuffix:t.resultSuffix}:{},backgroundReason:dW(t.backgroundReason),...t.transcriptPath?{transcriptPath:t.transcriptPath}:{}}}}case"error":return{status:"error",error:{message:e.result.value.error??"Task failed"}};default:return}}function dW(e){switch(e){case vg.qL.AGENT_REQUEST:return"agentRequest";case vg.qL.USER_REQUEST:return"userRequest";case vg.qL.QUEUED_FOLLOW_UP:return"queuedFollowUp";default:return"unspecified"}}function hW(e){if(e.result?.case)switch(e.result.case){case"success":case"failure":{const t=e.result.value;return{status:"success",value:{exitCode:t.exitCode??0,signal:t.signal??"",stdout:t.stdout??"",stderr:t.stderr??"",executionTime:t.executionTime??0}}}case"timeout":return{status:"error",error:{message:`Command timed out after ${e.result.value.timeoutMs}ms`,command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};case"rejected":return{status:"error",error:{message:e.result.value.reason??"Command rejected",command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};case"spawnError":return{status:"error",error:{message:e.result.value.error??"Failed to spawn command",command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};default:return}}function pW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{fileSize:Number(e.result.value.fileSize??0)}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.value.clientVisibleError??e.result.case,path:e.result.value.path}}}function fW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{files:e.result.value.files??[],totalFiles:e.result.value.totalFiles??0,clientTruncated:e.result.value.clientTruncated??!1,ripgrepTruncated:e.result.value.ripgrepTruncated??!1}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case}}}function mW(e){if(e.result?.case){if("success"===e.result.case){const t=e.result.value,r={};if(t.workspaceResults)for(const[e,n]of Object.entries(t.workspaceResults))r[e]=gW(n);return{status:"success",value:{...Object.keys(r).length>0?{workspaceResults:r}:{},...t.activeEditorResult?{activeEditorResult:gW(t.activeEditorResult)}:{}}}}return{status:"error",error:{message:e.result.value.error??e.result.case}}}}function gW(e){if(e?.result?.case)switch(e.result.case){case"content":return{type:"content",output:{matches:e.result.value.matches?.map((e=>({file:e.file,...void 0!==e.lineNumber?{lineNumber:e.lineNumber}:{},line:e.line,...e.beforeContext?{beforeContext:e.beforeContext}:{},...e.afterContext?{afterContext:e.afterContext}:{}})))??[],totalMatches:e.result.value.totalMatches??0}};case"files":return{type:"files",output:{files:e.result.value.files??[],count:e.result.value.count??0}};case"count":return{type:"count",output:{counts:e.result.value.counts?.map((e=>({file:e.file,count:e.count})))??[],total:e.result.value.total??0}};default:return}}function wW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{content:"content"===e.result.value.output.case?e.result.value.output.value:"",totalLines:e.result.value.totalLines??0,fileSize:Number(e.result.value.fileSize??0)}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case,path:e.result.value.path}}}function yW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{...void 0!==e.result.value.linesAdded?{linesAdded:e.result.value.linesAdded}:{},...void 0!==e.result.value.linesRemoved?{linesRemoved:e.result.value.linesRemoved}:{},...e.result.value.diffString?{diffString:e.result.value.diffString}:{}}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case,path:e.result.value.path}}}function vW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{directoryTreeRoot:bW(e.result.value.directoryTreeRoot)}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function bW(e){if(e)return{absPath:e.absPath??"",childrenDirs:e.childrenDirs?.map(bW)??[],childrenFiles:e.childrenFiles?.map((e=>({name:e.name})))??[],childrenWereProcessed:e.childrenWereProcessed??!1,fullSubtreeExtensionCounts:e.fullSubtreeExtensionCounts??{},numFiles:e.numFiles??0}}function SW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{fileDiagnostics:e.result.value.fileDiagnostics?.map((e=>({path:e.path,diagnostics:e.diagnostics?.map((e=>({severity:TW(e.severity),...e.range?{range:{...e.range.start?{start:{line:e.range.start.line,character:e.range.start.character}}:{},...e.range.end?{end:{line:e.range.end.line,character:e.range.end.character}}:{}}}:{},message:e.message,source:e.source,code:e.code})))??[],diagnosticsCount:e.diagnosticsCount??0})))??[],totalFiles:e.result.value.totalFiles??0,totalDiagnostics:e.result.value.totalDiagnostics??0}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function kW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{content:e.result.value.content?.map((e=>{const t={};return"text"===e.content?.case?t.text={text:e.content.value.text}:"image"===e.content?.case&&(t.image={data:e.content.value.data,...e.content.value.mimeType?{mimeType:e.content.value.mimeType}:{}}),t}))??[],isError:e.result.value.isError??!1}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case}}}function _W(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{results:e.result.value.results??""}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function CW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{filePath:e.result.value.filePath??""}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function EW(e){switch(e){case P$.$u.START_RECORDING:return"START_RECORDING";case P$.$u.SAVE_RECORDING:return"SAVE_RECORDING";case P$.$u.DISCARD_RECORDING:return"DISCARD_RECORDING";default:throw new Error(`Unknown RecordingMode: ${e}`)}}function xW(e){if(e.result?.case)switch(e.result.case){case"startSuccess":return{status:"success",value:{wasPriorRecordingCancelled:e.result.value.wasPriorRecordingCancelled??!1}};case"saveSuccess":return{status:"success",value:{path:e.result.value.path??"",recordingDurationMs:Number(e.result.value.recordingDurationMs??0)}};case"discardSuccess":return{status:"success",value:{}};case"failure":return{status:"error",error:{message:e.result.value.error??"Unknown error"}};default:return}}function PW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function RW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{todos:e.result.value.todos?.map((e=>({content:e.content,status:IW(e.status)})))??[],totalCount:e.result.value.totalCount??0}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function IW(e){switch(e){case QB.Vj.UNSPECIFIED:case QB.Vj.PENDING:return"pending";case QB.Vj.IN_PROGRESS:return"inProgress";case QB.Vj.COMPLETED:return"completed";case QB.Vj.CANCELLED:return"cancelled";default:return"pending"}}function TW(e){switch(e){case DA.h_.UNSPECIFIED:case DA.h_.ERROR:return"error";case DA.h_.WARNING:return"warning";case DA.h_.INFORMATION:return"information";case DA.h_.HINT:return"hint";default:return"error"}}const AW={type:"object",properties:{},additionalProperties:!0};function $W(e){const t={};for(const[r,n]of Object.entries(e))t[r]=n;return t}function MW(e){return"text"===e.type?new Ac._Z({content:{case:"text",value:new Ac.zN({text:e.text})}}):new Ac._Z({content:{case:"image",value:new Ac.do({data:n.Buffer.from(e.data,"base64"),mimeType:e.mimeType??""})}})}function DW(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var OW=r("./src/agent/errors.ts");const FW="Shell is not available when local.fs is set: the agent's files live in a FileSystem, and a shell would run on the host disk. Use Read, Grep, Glob, LS, and the edit tools instead.";function NW(e){return{async execute(){throw new Error(e)}}}function LW(e){var t;e.register(jT,NW(FW)),e.register(ee,(t=FW,{async*execute(){throw new Error(t)}})),e.register(vA,NW(FW)),e.register(EA,NW(FW)),e.register(bA,NW(FW)),e.register(UT,NW(FW)),e.register(tA,NW("ReadLints is not available when local.fs is set: lint diagnostics come from a host language service, not the FileSystem.")),e.register(GT,NW("Git is not available when local.fs is set: the agent's files live in a FileSystem, not a host git checkout."))}var jW=r("./src/agent/filesystem/executors.ts"),UW=r("./src/agent/filesystem/compose.ts"),BW=r("./src/agent/filesystem/trees.ts"),WW=r("./src/agent/filesystem/walk.ts");const HW="/tmp",qW=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.txt$/i;function zW(e){const{write:t,hostProjectDir:r}=e;return{async execute(e,n,o){const i=function(e){if(t=e.writePath,!/^([/\\]|[A-Za-z]:[/\\])/.test(t))return;var t;const r=function(e){if(void 0===e.hostProjectDir||""===e.hostProjectDir)return;const t=(0,WW.eI)(e.hostProjectDir),r=(0,WW.eI)(e.writePath);return"/"!==t&&(0,WW.hJ)({path:r,prefix:t})?r.slice(t.length):void 0}(e),n=void 0===r?(0,WW.eI)(e.writePath):(0,WW.eI)(`${HW}/${r}`);if(!(0,WW.hJ)({path:n,prefix:HW}))return;const o=s.default.posix.basename(n),i=s.default.posix.join(HW,$c);return s.default.posix.dirname(n)===i&&qW.test(o)?s.default.posix.join(HW,o):n}({writePath:n.path,hostProjectDir:r});if(void 0===i||i===n.path)return await t.execute(e,n,o);const a=n.clone();a.path=i;const c=await t.execute(e,a,o);return"success"===c.result.case&&(c.result.value.path=i),c}}}class GW{constructor(e,t="/"){this.fs=e,this.listeners=new Set,this.workspace=(0,WW.eI)(t)}getAllCursorRules(e){return this.rules??=async function(e,t){const[r,n]=await Promise.all([VW(e,s.posix.join(t,".cursor/rules")),KW(e,s.posix.join(t,"AGENTS.md"))]);return void 0===n?r:[...r,n]}(this.fs,this.workspace),this.rules}reload(e){this.rules=void 0;for(const e of this.listeners)e()}onDidChangeRules(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}dispose(){this.listeners.clear()}}async function VW(e,t){const r=[];try{for await(const n of e.list(t))"directory"!==n.kind&&n.path.endsWith(".mdc")&&r.push(n.path)}catch{return[]}return(await(0,Or.PH)(r,(async t=>{const r=await JW(e,t),n=void 0===r?null:en(r);if(null!==n)return hg({path:t,body:n.body,frontmatter:n.frontmatter,rawFrontmatter:n.rawFrontmatter})}),{max:8})).filter((e=>void 0!==e))}async function KW(e,t){const r=await JW(e,t);if(void 0!==r)return hg({path:t,body:Zr({content:r,filename:"AGENTS.md"}),frontmatter:{alwaysApply:!0}})}async function JW(e,t){try{const r=await e.read(t);return"string"==typeof r?r:(new TextDecoder).decode(r)}catch{return}}const ZW={getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}},XW={async exec(){throw new Error("git is not available in a FileSystem session")}},QW={isIgnoredByAny:async()=>!1,isGitIgnored:async()=>!1,isCursorIgnored:async()=>!1,isRepoBlocked:async()=>!1,listCursorIgnoreFilesByRoot:async()=>[],getCursorIgnoreMapping:async()=>({}),getShellSandboxIgnoreMapping:async()=>({}),getGitIgnoreMapping:async()=>({}),getRepoBlockExcludeGlobs:async()=>[]};function YW(e){return{cursorRulesService:!0===e.includeProjectRules?new GW(e.fs,e.workspace):ZW,getAgentSkills:async()=>[],subagentsService:e.subagentsService??new Sg,gitExecutor:XW,ignoreService:QW,requestContextIsWorkingDirHomeDir:!1,reportProcessWorkingDirectory:!1}}function eH(e,t){const r=t.workspace??"/",n=(0,jW.c9)(e,{workspace:r});return{localResourceProviderOptions:{overrideReadExecutor:n.read,overrideWriteExecutor:zW({write:n.write,hostProjectDir:t.hostProjectDir}),overrideGrepExecutor:n.grep,overrideLsExecutor:n.ls,overrideDeleteExecutor:n.delete,suppressDefaultShellExecutor:!0,...YW({...t.settings,fs:e,workspace:r})},reportedWorkspacePath:r,reportedProjectFolder:HW,excludeHooks:!0,excludeProjectMcp:!0}}var tH=r("./src/agent/executor-common.ts");class rH{constructor(){this.countsByMode=new Map,this.failureKindsByMode=new Map,this.record=e=>{let t=this.countsByMode.get(e.mode);switch(void 0===t&&(t={mode:e.mode,checked_calls:0,outside_limit_calls:0,settings_unavailable_calls:0,unknown_server_calls:0},this.countsByMode.set(e.mode,t)),e.outcome){case"within_limit":return void(t.checked_calls+=1);case"outside_limit":return t.checked_calls+=1,void(t.outside_limit_calls+=1);case"settings_unavailable":{t.settings_unavailable_calls+=1;const r=e.settingsFailure;if(void 0===r)return;let n=this.failureKindsByMode.get(e.mode);return void 0===n&&(n=new Map,this.failureKindsByMode.set(e.mode,n)),void n.set(r,(n.get(r)??0)+1)}case"unknown_server":return void(t.unknown_server_calls+=1);default:return e.outcome}}}take(){const e=[...this.countsByMode.values()].map((e=>{const t=function(e){let t;for(const[r,n]of e??[])(void 0===t||n>t.calls)&&(t={kind:r,calls:n});return t?.kind}(this.failureKindsByMode.get(e.mode));return void 0===t?e:{...e,settings_unavailable_kind:t}}));return this.countsByMode.clear(),this.failureKindsByMode.clear(),e}}class nH{constructor(e=e=>{console.warn(e)}){this.write=e,this.printed=new Set,this.report=e=>{if(!this.printed.has(e.serverName)){this.printed.add(e.serverName);try{this.write(function(e){return`[cursor-sdk] ${e.refusal}`}(e))}catch{}}}}}const oH=new class{constructor(e=e=>{console.warn(e)}){this.write=e,this.printed=new Set,this.report=e=>{const t=JSON.stringify([e.serverName,(r=e.allowlist,JSON.stringify([r.list,r.name,r.reason,r.allowedServers??null,r.blockedServers??null]))]);var r;if(!this.printed.has(t)){this.printed.size>=1e3&&this.printed.clear(),this.printed.add(t);try{this.write(function(e){return`[cursor-sdk] MCP server "${e.serverName}" is under ${function(e){return`${e.name}, which applies because ${e.reason}.${r=e.allowedServers,void 0===r?"":0===r.length?" Allowed servers: none.":WC("Allowed servers",r)}${t=e.blockedServers,void 0===t||0===t.length?"":WC("Blocked",t)}`;var t,r}(e.allowlist)}`}(e))}catch{}}}}};var sH=r("./src/agent/native/vendored-tree-sitter.ts"),iH=r("./src/agent/platform-package-locator.ts"),aH=r("./src/agent/sdk-config.ts"),cH=r("../../node_modules/.pnpm/@statsig+js-client@3.31.0/node_modules/@statsig/js-client/src/index.js"),lH=r("./src/agent/utils/logger.ts");const uH={checkFeatureGate:()=>!1,getDynamicConfigValue:({defaultValue:e})=>e},dH=new Map;async function hH(e){try{const t=await async function(e){const t=await(0,tH.dC)(e,tH.EV);if(!t)return;const r=tH.EV.endsWith("/")?tH.EV.slice(0,-1):tH.EV,n=await fetch(`${r}/aiserver.v1.AnalyticsService/BootstrapStatsig`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json","x-cursor-client-type":"sdk","x-cursor-client-version":(0,tH.tF)(),"x-ghost-mode":(0,tH.U)(e)},body:JSON.stringify({})});if(!n.ok)return void lH.v.log(`Failed to bootstrap SDK Statsig: ${n.status} ${n.statusText}`);const o=await n.json();return pH(o)&&"string"==typeof o.config&&o.config.length>0?o.config:void 0}(e);if(!t)return uH;const r=new cH.StatsigClient("client-Bm4HJ0aDjXHQVsoACMREyLNxm5p6zzuzhO50MgtoT5D",function(e){try{const r=JSON.parse(e);if(pH(r)&&"object"==typeof(t=r.user)&&null!==t&&!Array.isArray(t))return{...r.user,custom:{...r.user.custom,clientType:"sdk",clientVersion:(0,tH.tF)()}}}catch(e){lH.v.log(`Failed to parse SDK Statsig bootstrap user: ${e instanceof Error?e.message:String(e)}`)}var t;return{custom:{clientType:"sdk",clientVersion:(0,tH.tF)()}}}(t),{disableLogging:!0,disableStorage:!0,networkConfig:{preventAllNetworkTraffic:!0}});return r.dataAdapter.setData(t),r.initializeSync(),{checkFeatureGate:(e,t)=>{try{return r.checkGate(e,t)}catch{return!1}},getDynamicConfigValue({configName:e,paramName:t,defaultValue:n}){try{return r.getDynamicConfig(e).get(t,n)}catch{return n}}}}catch(e){return lH.v.log(`Failed to initialize SDK Statsig: ${e instanceof Error?e.message:String(e)}`),uH}}function pH(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function fH(e){let t;return e?.then((e=>{t=e}),(()=>{})),()=>t?.checkFeatureGate("grok_bot_mcp_app_payment_token_filter",{disableExposureLog:!0})??!1}var mH=r("./src/agent/tools-option.ts");class gH{async requestApproval(){return{approved:!0}}}function wH(e,t){if(!function(e){return void 0!==e&&Object.keys(e).length>0}(t))return;const r=e.resources.base;if(!(r instanceof sD))throw new OW.j1("SDK custom tools require the default local workspace resource provider.",{isRetryable:!1});const n=r.getMcpExecutionPolicyDeps(),o=r.get(eo),s=function(e,t){return{async execute(r,n,o){const s=n.toolName||function(e){const t=`${zn}-`;return e.startsWith(t)?e.slice(t.length):e}(n.name),i=e[s];if(void 0===i)return new Ac.iz({result:{case:"error",value:new Ac.Nh({error:`Unknown custom tool: ${s}`})}});try{return function(e){const t=function(e){return"object"==typeof(t=e)&&null!==t&&!Array.isArray(t)&&"content"in t&&Array.isArray(t.content)?{content:e.content,isError:e.isError,structuredContent:e.structuredContent}:"string"==typeof e?{content:[{type:"text",text:e}]}:{content:[{type:"text",text:JSON.stringify(e)}],structuredContent:DW(e)?e:void 0};var t}(e),r=void 0!==t.structuredContent?we.Struct.fromJson(t.structuredContent):void 0;return new Ac.iz({result:{case:"success",value:new Ac.QW({content:t.content.map(MW),isError:t.isError??!1,structuredContent:r})}})}(await i.execute(function(e){return Object.fromEntries(Object.entries(e.args).map((([e,t])=>[e,t.toJson()])))}(n),{toolCallId:n.toolCallId||void 0,...void 0===t||""===t?{}:{sessionId:t}}))}catch(e){return new Ac.iz({result:{case:"error",value:new Ac.Nh({error:e instanceof Error?e.message:String(e)})}})}}}}(t,e.state.sessionId),i=new gH;e.resources.base.register(eo,{async execute(e,t,r){if(function(e){return e.providerIdentifier===zn}(t)){const o=await ET(e,t,{...n,pendingDecisionProvider:i,toolDef:{source:"internal"}});return void 0!==o?o:s.execute(e,t,r)}return o.execute(e,t,r)}})}const yH=new Set(["127.0.0.1","localhost","[::1]"]);function vH(e){if(void 0===e)return{};const t=e.resourceProviderOptions;return{...void 0!==t?{localResourceProviderOptions:t}:{},...void 0!==e.reportedWorkspacePath?{reportedWorkspacePath:e.reportedWorkspacePath}:{}}}function bH(){const e=process.env.CURSOR_SDK_MOCK_PROMPT_TIME;if(void 0===e||""===e)return;const t=new Date(e);return Number.isNaN(t.getTime())?void 0:t}const SH={warn(){},error(){}},kH={log(){}};class _H{async requestApproval(e){return{approved:!1,reason:`Local SDK runs cannot request interactive approval for ${CH(e)}. Keep the action within the configured sandbox policy or Smart Auto Review's auto-approval boundary, or re-run without sandboxing/autoReview enabled.`}}}function CH(e){switch(e.type){case Lw.Shell:return"this shell command";case Lw.Mcp:return"this MCP tool call";case Lw.Write:return"this file edit";case Lw.Delete:return"this file deletion";default:return"this operation"}}function EH(e){return void 0!==e&&"insecure_none"!==e.type}async function xH(e,t){const r="string"==typeof e||void 0===e?{workingDirectory:e,apiKey:t}:e,a=(0,y.q6)().with(l._O,kH),c=SB(r.settingSources),u=void 0===r.hostMcpBridgeUrls?void 0:r.hostMcpBridgeUrls.filter((e=>{let t;try{t=new URL(e)}catch{t=void 0}const r=void 0!==t&&"http:"===t.protocol&&""===t.username&&""===t.password&&yH.has(t.hostname);return r||console.warn(`[cursor-sdk] ignoring local.hostMcpBridgeUrls entry ${e}: not an http URL on 127.0.0.1, localhost or [::1]`),r}));!function(e){if(void 0!==e&&(!Number.isFinite(e)||e<=0))throw new Error(`Workspace scan cache TTL must be a positive number of milliseconds, got ${e}`);ya=e}((0,aH.Mu)()),/:\/\/(localhost|127\.0\.0\.1)/.test(tH.EV)&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0");const d=performance.now();let h=0;if(r.apiKey){const e=performance.now();await Promise.all([(0,tH.ly)(r.apiKey),(0,tH.mU)(r.apiKey)]),h=performance.now()-e}const p=r.workingDirectory||process.cwd();(0,sH.configureVendoredTreeSitterWorkspaceDir)(p);for(const e of r.dirs??[])(0,sH.configureVendoredTreeSitterWorkspaceDir)(e);const f=(0,So.Rv)((0,o.homedir)(),p),m={hostProjectDir:f,settings:{includeProjectRules:kB(c,"project"),subagentsService:new MB(r.customSubagents??[])}};let g;const w="win32"===process.platform?"rg.exe":"rg",v=process.env.CURSOR_RIPGREP_PATH;g=v&&(0,s.isAbsolute)(v)?v:(0,iH.hQ)({binaryName:w,excludedWorkspaceDir:p}),g||(g=(0,Oo.xS)()),g&&(0,Oo.J)(g);let b,S,k,_={getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getAdminCommandDenylist:async()=>({rules:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}};if(r.apiKey)try{const e=(0,tH.qN)(r.apiKey,r.teamId);b=e.transport,S=e.getAccessToken;const t=(0,ye.createClient)(fj.I,b),n=function(e){let t=dH.get(e);return t||(t=hH(e),dH.set(e,t),t.then((r=>{r===uH&&dH.get(e)===t&&dH.delete(e)}),(()=>{dH.get(e)===t&&dH.delete(e)}))),t}(r.apiKey);k=n;const o={getDefaultNetworkAllowlist:async()=>(await n).getDynamicConfigValue({configName:"sandbox_default_network_allowlist",paramName:"allowlist",defaultValue:[]})};_=new gO(new pO(t,{supportsHostMcpBridgeExemption:!0}),o,{...void 0===u?{}:{hostMcpBridgeUrls:u},mcpAdminToolLimitSurvivesFailedRead:!0,isMcpAccessNetworkAllowlistEnabled:async()=>(await n).checkFeatureGate("mcp_access_network_allowlist"),isMcpSettingsOverhaulEnabled:async e=>(await n).checkFeatureGate("mcp_settings_overhaul",e),isWin32UserExtensionStdioUnsandboxEnabled:async e=>(await n).checkFeatureGate("mcp_user_extension_stdio_unsandboxed_win32",e),isAdminCommandDenylistEnforcementKilled:async()=>(await n).checkFeatureGate("admin_command_denylist_enforcement_killswitch")})}catch(e){lH.v.log(`Failed to initialize authenticated dashboard services: ${e instanceof Error?e.message:String(e)}`)}const C=performance.now(),E=r.apiKey?await(0,Oo.tv)(`${(0,o.homedir)()}/.cursor/sandbox.json`,(0,o.homedir)()):void 0,x=void 0!==r.apiKey?await async function(e){const{cwd:t,perUserSandboxPolicy:r,sandboxOptions:n}=e;if(!1===n?.enabled)return{defaultSandboxPolicy:{type:"insecure_none"},defaultSandboxPolicySources:void 0};const o=EH(r)?r:!0===n?.enabled?function(e,t={}){return{type:e,...t}}("workspace_readwrite",{networkPolicy:(0,Oo.Po)()}):void 0;if(void 0===o)return{defaultSandboxPolicy:{type:"insecure_none"},defaultSandboxPolicySources:void 0};if(function(e){const t="win32"===process.platform?"cursorsandbox.exe":"cursorsandbox",r=(0,iH.hQ)({binaryName:t,excludedWorkspaceDir:e});r&&(0,Oo.St)({sandboxBinaryPath:r})}(t),!(0,Oo.K3)(void 0,{ctx:e.initializationCtx}))throw new OW.j1("Local SDK sandboxing was requested, but sandboxing is not supported in this environment. Disable local.sandboxOptions.enabled or remove ~/.cursor/sandbox.json to run without sandboxing.",{isRetryable:!1});const s={};s.perUser=o;const{policy:i}=await(0,Oo.resolveSandboxPolicyForWorkspace)(t,s);return{defaultSandboxPolicy:i,defaultSandboxPolicySources:s}}({cwd:p,perUserSandboxPolicy:E,sandboxOptions:r.sandboxOptions,initializationCtx:a}):void 0,P=performance.now()-C,R=x?.defaultSandboxPolicy,I=x?.defaultSandboxPolicySources,T=EH(R),A=performance.now(),M=(()=>{const e=[],t=new Set;for(const n of[p,...r.dirs??[]]){const r=(0,s.resolve)(n);t.has(r)||(t.add(r),e.push(n))}return e.length>1?e:void 0})(),D={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1},O=await async function(e){const{workingDirectory:t,projectDir:r}=e,n=function(e,t){const r=[],n=new Set;for(const o of[e,...t??[]]){const e=(0,s.resolve)(o);n.has(e)||(n.add(e),r.push(o))}return r}(t,e.dirs),o=n.length>1?n:void 0,i=SB(e.settingSources),a=e.teamSettingsService??{getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getAdminCommandDenylist:async()=>({rules:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}},c=e.defaultSandboxPolicy??{type:"insecure_none"},l=e.getSandboxSupported??(()=>(0,Oo.K3)(c,{ctx:e.initializationCtx})),u=e.getSandboxEnabled??(()=>"insecure_none"!==c.type&&l()),d=new _y,h=new xc(d,a,n),p=new TB,f=new AB,m=e.getSmartModeClassifierAutoModeEnabled?.(),g=new IB(m?"allowlist":e.approvalMode??"unrestricted",c,a,e.respectAdminControls??!1),w=e.pendingDecisionProvider,y={executeIndexedGrep:void 0},v=()=>!0,b=kB(i,"plugins"),S=e.importThirdPartyPlugins??!1,k=e.mcpMetaToolEnabled??!0,_=void 0!==e.mcpServers&&Object.keys(e.mcpServers).length>0,C=void 0!==e.customSubagents&&e.customSubagents.length>0,E=_||kB(i,"project")||kB(i,"user")||b,x=kB(i,"project")||kB(i,"user")||kB(i,"mdm"),P=kB(i,"team"),R=P&&void 0!==e.dashboardTransport,I=kB(i,"project")||kB(i,"user")||P||R||b,T={teamSettingsService:a,initializationCtx:e.initializationCtx,importThirdPartyPlugins:S,ignoreApprovals:!0,includeProjectMcp:kB(i,"project"),includeUserMcp:kB(i,"user"),includePluginMcp:b,isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled,restMcpCursorAuthTokenSupplier:e.restMcpCursorAuthTokenSupplier},A=s=>PB({workingDirectory:t,...void 0!==o?{workspaceRoots:o}:{},adapters:{...s.includeMcp?{mcp:VO({...T,inlineMcpServers:e.mcpServers})}:{},...b?{pluginBootstrap:tB({importThirdPartyPlugins:S,dashboardTransport:e.dashboardTransport})}:{},...x?{hooks:pj({includeProjectHooks:kB(i,"project"),includeUserHooks:kB(i,"user"),includeEnterpriseHooks:kB(i,"mdm"),useCommandHookStdinTransport:e.useCommandHookStdinTransport})}:{},...I?{localExtensibility:gj({includeProjectExtensibility:kB(i,"project"),includeUserExtensibility:kB(i,"user"),includeManagedSkills:R,includeTeamExtensibility:P,includePluginExtensibility:b,teamSettingsService:a,getThirdPartyExtensibilityEnabled:v,dashboardTransport:e.dashboardTransport,importThirdPartyPlugins:S})}:{},resourceFactory:dB({ignoreService:h,grepProvider:y,workspacePaths:n,diagnosticsProvider:p,repositoryProvider:f,projectDir:r??t,shellManager:void 0,defaultSandboxPolicy:c,defaultSandboxPolicySources:e.defaultSandboxPolicySources,getSandboxEnabled:u,getSandboxSupported:l,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:e.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:e.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:e.getMockPromptTime,getPowershellUtf8Options:e.getPowershellUtf8Options,mcpFileOutputThresholdBytes:void 0,mcpMetaToolEnabled:k,createMcpStateAccessor:(e,t)=>new $B(new oM(e),void 0===t?.onMcpAllowlistInUse&&void 0===t?.onMcpServerBlockedByAllowlist?void 0:{mcpLease:e,onMcpAllowlistInUse:t.onMcpAllowlistInUse,onMcpServerBlockedByAllowlist:t.onMcpServerBlockedByAllowlist}),createSessionMcpLease:(t,r)=>VO({...T,includeProjectMcp:T.includeProjectMcp&&!0!==t.options.excludeProjectMcp,inlineMcpServers:r??e.mcpServers}).createLease({workspaceState:t.workspaceState,services:t.workspaceServices,policy:t.policy}),createSessionDependencies:r=>{const n=w??new RB;return{pendingDecisionStore:n,fileChangeTracker:new Bw(t),permissionsService:new t_(h,n,g,a,t,e.respectAdminControls??!1,{enforceMcpAdminToolLimits:e.isMcpAdminToolLimitEnforced,onMcpAdminToolLimitCheck:r.options.onMcpAdminToolLimitCheck})}}}),resourceWrappers:x?[{wrapResources(e){const t=e.workspaceServices.hooksRuntime;if(!0===e.options.excludeHooks||"object"!=typeof(r=t)||null===r||!("hooksConfigLease"in r)||!("createSessionRuntime"in r)||"function"!=typeof r.createSessionRuntime||!function(e){return"object"==typeof e&&null!==e&&"get"in e&&"function"==typeof e.get&&"entries"in e&&"function"==typeof e.entries}(e.resources))return e.resources;var r;const n=t.createSessionRuntime({sessionState:e.sessionState,metadata:e.metadata});return new dj(new oj(e.resources,n.hookExecutor,(()=>function(e,t){const r=aj(t,cj,"conversationId","conversation_id")??e.sessionId??"";return{conversation_id:r,generation_id:aj(t,cj,"generationId","generation_id")??r,model:aj(t,cj,"model")??"unknown",...hF({modelId:aj(t,cj,"modelId","model_id"),modelParams:aj(t,uj,"modelParams","model_params")})}}(e.sessionState,e.metadata)),e.workspaceServices.mcpLease,void 0,void 0,t.hooksConfigLease),n)}}]:[],...C?{workspaceServicesContributors:[{contributeServices:t=>{const r=new MB(e.customSubagents??[]),n=t.services.subagentsService;return{subagentsService:void 0===n?r:new Ig([r,n])}}}]}:{}}});if(!E)return A({includeMcp:!1});try{return await A({includeMcp:!0})}catch(e){return SO.Jz.warn("[default-local-workspace-runtime] Failed to initialize MCP-enabled runtime, retrying without MCP:",{error:e,workingDirectory:t,projectDir:r,enablePlugins:b,importThirdPartyPlugins:S}),A({includeMcp:!1})}}({workingDirectory:p,...void 0!==M?{dirs:M}:{},projectDir:f,teamSettingsService:_,initializationCtx:a,dashboardTransport:b,settingSources:r.settingSources,mcpServers:r.mcpServers,customSubagents:r.customSubagents,defaultSandboxPolicy:R,defaultSandboxPolicySources:I,approvalMode:T?"allowlist":void 0,pendingDecisionProvider:T||!0===r.autoReview?new _H:void 0,getNetworkAllowlistInfo:T?()=>async function(e,t,r){const[n,o]=await Promise.all([e.getDefaultNetworkAllowlist(),e.getNetworkAccessControls()]),s=[...o.allowlist],i=`${t}/.cursor/sandbox.json`,a=await(0,Oo.tv)(i,t);if(a&&"insecure_none"!==a.type&&a.networkPolicy?.allow&&s.push(...a.networkPolicy.allow),"1"!==process.env[Zv.K4]&&r){const e=await(0,Oo.tv)(`${r}/.cursor/sandbox.json`,r);e&&"insecure_none"!==e.type&&e.networkPolicy?.allow&&s.push(...e.networkPolicy.allow)}const c=[...new Set(s)];return{hasDefaults:n.available&&n.allowlist.length>0,explicitEntries:c}}(_,(0,o.homedir)(),p):void 0,getSmartModeClassifierAutoModeEnabled:()=>!0===r.autoReview,devForceNextSmartModeClassifierBlockToken:r.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:bH,getPowershellUtf8Options:async()=>{if(void 0===k)return D;try{const e=await k;return{powershellUtf8Console:e.checkFeatureGate("shell_exec_powershell_utf8_console"),powershellUtf8ChildEnv:e.checkFeatureGate("shell_exec_powershell_utf8_child_env")}}catch{return D}},isLinkSharedPaymentTokenLogRedactionEnabled:fH(k),restMcpCursorAuthTokenSupplier:S,respectAdminControls:void 0!==r.apiKey,isMcpAdminToolLimitEnforced:void 0===k?void 0:(F=k,async()=>{try{return(await F).checkFeatureGate("sdk_local_mcp_admin_tool_limits",{disableExposureLog:!0})}catch{return!1}}),useCommandHookStdinTransport:!0});var F;const N=performance.now()-A;let L,j;return(0,XB.ou)(r.apiKey,{runtime:"local",ensure_ghost_mode_ms:Math.round(h),bootstrap_statsig_ms:0,create_workspace_runtime_ms:Math.round(N),load_sandbox_policy_ms:Math.round(P),total_ms:Math.round(performance.now()-d)}),{run:async(e,t,o)=>(0,SO.ni)(SH,(async()=>{const s=(0,$.VI)((0,y.q6)().withName("sdk.run").with(l._O,kH)),[a,c]=s.ctx.withCancel(),u=t.sessionId??(0,ge.C)(),d=t.mcpServersOverride,h=void 0===(f=t.customTools)?[]:Object.entries(f).map((([e,t])=>({clientKey:zn,providerIdentifier:zn,toolName:e,name:`${zn}-${e}`,description:t.description??"",inputSchema:t.inputSchema??AW,...void 0===t.outputSchema?{}:{outputSchema:t.outputSchema},...void 0===t.annotations?{}:{annotations:$W(t.annotations)},source:"internal"})));var f;let g;const w={...m,workspace:t.fileSystemWorkspace},v=void 0===t.fileSystem?void 0:(_=await async function(e,t){return"function"==typeof e?await e(t):e}(t.fileSystem,{agentId:u,sessionId:u}),C=_,(0,UW.VL)({"/":C,[HW]:(0,BW.Om)()})),b=void 0===t.onMcpAdminToolLimitCounts?void 0:new rH,S=()=>{for(const e of b?.take()??[])try{t.onMcpAdminToolLimitCounts?.(e)}catch{}},k=new nH;var _,C;g=await O.createSessionRuntime({sessionId:u,mcpServersOverride:d,extraMcpTools:h,onMcpAdminToolLimitCheck:b?.record,onMcpAllowlistInUse:oH.report,onMcpServerBlockedByAllowlist:k.report,...void 0===v?vH(t.sessionResources):eH(v,w)});const E=new Map;try{const s=g.resources.wrapped;wH(g,t.customTools),void 0!==v&&LW(g.resources.base);const l=t.blobStore??new re.ve;let f=t.initialState??new i.Y9z({});const m=void 0!==t.model?new JB.G4({modelId:t.model.id,...!0===t.model.maxMode?{maxMode:!0}:{},parameters:(t.model.params??[]).map((e=>new JB.SR({id:e.id,value:e.value})))}):void 0,y=!0===e.summarize?void 0:e.images,_=Array.isArray(y)?y.map((e=>{const t=(0,ge.C)(),r=new Uint8Array(n.Buffer.from(e.data,"base64")),o=(0,tH.v8)(r);return new ZB.d({uuid:t,...o?{mimeType:o}:{},dataOrBlobId:{case:"data",value:r}})})):[],C=_.length>0?new ZB.xv({selectedImages:_}):void 0,R=function(e){switch(e){case"agent":return i.xyI.AGENT;case"plan":return i.xyI.PLAN;default:return}}(t.mode),I=!0===e.summarize?new i.QFf({action:{case:"summarizeAction",value:new i.Scs}}):new i.QFf({action:{case:"userMessageAction",value:new i.Vtf({userMessage:new i.RGk({text:e.text,selectedContext:C,...void 0!==R?{mode:R}:{}})})}}),T={sendUpdate:async(e,t)=>{const r=sW(t,u);null!==r&&await o.sendUpdate(r)},query:async(e,r)=>await async function(e,t){if("mcpAuthRequestQuery"===e.query.case&&void 0!==t){const r=await async function(e,t,r){let n;try{n=await e({serverName:r.args?.serverIdentifier??"",toolCallId:r.args?.toolCallId??""})}catch{return kr(t,"The MCP sign-in request failed.")}if(void 0!==n)switch(n.kind){case"approved":return Sr(t);case"rejected":return kr(t,n.reason);default:return n}}(t,e.id,e.query.value);if(void 0!==r)return r}return function(e){switch(e.query.case){case"webSearchRequestQuery":return ur(e.id);case"webFetchRequestQuery":return hr(e.id);case"switchModeRequestQuery":return mr(e.id);case"askQuestionInteractionQuery":return fr(e.id,new Qt.tz({result:{case:"rejected",value:new Qt.ox({reason:"Interactive questions are not supported in local SDK runs"})}}));case"createPlanRequestQuery":return wr(e.id,new Yt.bK({result:{case:"success",value:new Yt.Jo},planUri:""}));case"setupVmEnvironmentArgs":return yr(e.id,new rr.r$({result:{case:"success",value:new rr.JH}}));case"replaceEnvArgs":return vr(e.id,new tr.dV({result:{case:"failure",value:new tr.uq({errorMessage:"Environment replacement is not supported in local SDK runs",setupLogs:""})}}));case"prManagementRequestQuery":return br(e.id,new er.HL({result:{case:"error",value:new er.K$({error:"PR management is only available in cloud agents"})}}));case"mcpAuthRequestQuery":return kr(e.id,"MCP authentication is not supported in local SDK runs");case"connectScmRequestQuery":return _r(e.id,"Connecting GitHub is not supported in local SDK runs");case"generateImageRequestQuery":return Cr(e.id,e.query.value.args?.description);case void 0:throw new OW.j1("Missing interaction query type",{isRetryable:!1});default:throw e.query,new OW.j1("Unhandled interaction query type",{isRetryable:!1})}}(e)}(r,t.onMcpAuthRequest)};if(L!==t.apiKey||!j){await Promise.all([(0,tH.ly)(t.apiKey),(0,tH.mU)(t.apiKey)]);const e=(0,tH.KU)(t.apiKey,r.teamId),n=vo((0,ye.createClient)(KB.N,e),{injectTraceHeaders:!0});j=new Wn(n),L=t.apiKey}const A=(0,tH.Vh)(j,(()=>{const e=(0,tH.KU)(t.apiKey,r.teamId),n=vo((0,ye.createClient)(KB.N,e),{injectTraceHeaders:!0}),o=new Wn(n);return j=o,L=t.apiKey,o})),$=function(e){return{...void 0!==e.allowedTools?{[mH.$$]:e.allowedTools.join(",")}:{},...void 0!==e.disallowedTools&&e.disallowedTools.length>0?{[mH.VJ]:e.disallowedTools.join(",")}:{}}}(t),M=new VB({agentClient:A,rootRequestId:t.requestId,getResources:async({agentId:e})=>{let r=E.get(e);return r||(r=await O.createSessionRuntime({sessionId:e,mcpServersOverride:d,extraMcpTools:h,onMcpAdminToolLimitCheck:b?.record,onMcpAllowlistInUse:oH.report,onMcpServerBlockedByAllowlist:k.report,...void 0===v?vH(t.subagentInherit):eH(v,w)}),wH(r,t.customTools),void 0!==v&&LW(r.resources.base),r.resources.base.register(io,D),r.resources.base.register(ao,F),r.resources.base.register(co,N),E.set(e,r)),r.resources.wrapped},mcpTools:h,workspacePath:p,parentConversationId:u,...(void 0!==t.subagentInherit||void 0!==v)&&Object.keys($).length>0?{headers:$}:{},onSessionReleased:e=>{const t=E.get(e);t&&(t.dispose(),E.delete(e))}}),D=function(e){const t=new Map,r=new Map;async function n(t,r,n){let o;try{o=await e.createOrResumeSession(t,r);const s=await e.runSession(t,o,r,{execId:n?.execId});return"error"===s.status?new oo.vS({result:{case:"error",value:new oo.od({agentId:o,error:s.error})}}):"aborted"===s.status?new oo.vS({result:{case:"error",value:new oo.od({agentId:o,error:s.error??"Subagent was aborted by the user"})}}):"background"===s.status?new oo.vS({result:{case:"success",value:new oo.HJ({agentId:o,finalMessage:s.finalMessage,toolCallCount:s.toolCallCount??0,backgroundReason:s.backgroundReason,transcriptPath:s.transcriptPath})}}):new oo.vS({result:{case:"success",value:new oo.HJ({agentId:o,finalMessage:s.finalMessage,toolCallCount:s.toolCallCount??0})}})}catch(t){if(o&&e.releaseSession&&e.releaseSession(o),t instanceof lr)throw t;const n=t instanceof Error?t.message:String(t),s=o??function(e){return e instanceof so&&e.agentId||e&&"object"==typeof e&&"agentId"in e&&"string"==typeof e.agentId?e.agentId:void 0}(t)??r.resumeAgentId;return new oo.vS({result:{case:"error",value:new oo.od({...s?{agentId:s}:{},error:n})}})}}return{execute(e,o,s){const i=function(e){if(e.toolCallId&&e.parentConversationId)return[e.parentConversationId,e.toolCallId,e.resumeAgentId??"",e.forkAgentId??""].join("\0")}(o);if(void 0===i)return n(e,o,s);const a=r.get(i);if(void 0!==a)return Promise.resolve(a);const c=t.get(i);if(void 0!==c)return c;const l=n(e,o,s).then((e=>("success"===e.result.case&&(r.set(i,e),r.size>1e3&&r.delete(r.keys().next().value)),e))).finally((()=>{t.delete(i)}));return t.set(i,l),l}}}(M),F=(P=M,{execute:(e,t)=>P.awaitBackgroundRunBounded(e,t)}),N=function(e){return{execute:async(t,r)=>e.forceBackgroundByToolCallId(r.toolCallId)}}(M);g.resources.base.register(io,D),g.resources.base.register(ao,F),g.resources.base.register(co,N);const U=O.services.hooksRuntime,B="object"==typeof(x=U)&&null!==x&&"workspacePath"in x&&"string"==typeof x.workspacePath&&"createSessionRuntime"in x&&"function"==typeof x.createSessionRuntime?U:void 0,W=void 0!==B&&void 0===v&&!0!==e.summarize?function(e){const{workspaceRuntime:t}=e;if(!(t.hooksConfigLease.hasHookForStep(xd.sessionStart)||t.hooksConfigLease.hasHookForStep(xd.sessionEnd)||t.hooksConfigLease.hasHookForStep(xd.stop)||t.hooksConfigLease.hasHookForStep(xd.beforeSubmitPrompt)))return{};const r=t.createSessionRuntime({sessionState:e.sessionState,metadata:e.metadata}),{hookExecutor:n}=r;let o;return{async onSessionStart(e){if(o=e,n.hasHooksForStep(xd.sessionStart))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...hF(e),is_background_agent:!1},r=await n.executeHookForStep(xd.sessionStart,t);if(r)return r.env&&n.setSessionEnvironment(r.env),{env:r.env,additionalContext:r.additional_context,blocked:!1===r.continue,blockedReason:r.user_message}}catch(e){SO.Jz.warn("[hooks-adapter] sessionStart hook failed:",e)}},async onSessionEnd(e,t){if(n.hasHooksForStep(xd.sessionEnd))try{const r={conversation_id:o?.conversationId??"",generation_id:o?.generationId??"",model:o?.model??"unknown",...o?hF(o):{},reason:e,duration_ms:t,is_background_agent:!1,final_status:e};await n.executeHookForStep(xd.sessionEnd,r)}catch(e){SO.Jz.warn("[hooks-adapter] sessionEnd hook failed:",e)}finally{n.clearSessionEnvironment()}else n.clearSessionEnvironment()},async onBeforeSubmitPrompt(e){if(n.hasHooksForStep(xd.beforeSubmitPrompt))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...hF(e),prompt:e.promptText??"",attachments:[]};await n.executeHookForStep(xd.beforeSubmitPrompt,t)}catch(e){SO.Jz.warn("[hooks-adapter] beforeSubmitPrompt hook failed:",e)}},async onTurnCompleted(e){if(!n.hasHooksForStep(xd.stop))return;const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...hF(e),status:"completed",loop_count:e.loopCount},r=await n.executeHookForStep(xd.stop,t),o="string"==typeof r?.followup_message?r.followup_message.trim():"";return o.length>0?o:void 0},async onTurnError(e){if(n.hasHooksForStep(xd.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...hF(e),status:"error",loop_count:e.loopCount};await n.executeHookForStep(xd.stop,t)}catch(e){SO.Jz.warn("[hooks-adapter] onTurnError stop hook failed:",e)}},async onTurnAborted(e){if(n.hasHooksForStep(xd.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...hF(e),status:"aborted",loop_count:e.loopCount};await n.executeHookForStep(xd.stop,t)}catch(e){SO.Jz.warn("[hooks-adapter] onTurnAborted stop hook failed:",e)}},async dispose(){await r.dispose()}}}({workspaceRuntime:B,sessionState:g.state,metadata:g.metadata}):void 0,H=new qB({workspacePath:p,conversationId:u,blobStore:l}),q=function(e,t,r){const{hooks:n}=r,[o,s]=e.withCancel(),a=new bO;let c;const l=new Map,u=(e,t)=>{const r=l.get(e);void 0!==r&&(l.delete(e),clearTimeout(r.ackTimer),r.resolve(t))};let d;const h=[],p=e=>{for(const t of h.splice(0))t.resolve(e)},f=()=>{if(0===h.length)return;const e=h.map((e=>e.text)).join("\n\n");return p("complete_delivered"),RO(e)},m=r.interactionListener,g={async sendUpdate(e,t){const r=t.message;if("contextInjectionState"===r?.case){const e=r.value,t="object"==typeof e&&null!==e&&"injectionId"in e&&"string"==typeof e.injectionId?e.injectionId:void 0,n=function(e){if("object"!=typeof e||null===e||!("state"in e))return;const t=e.state;if("object"!=typeof t||null===t||!("state"in t))return;const r=t.state;return"object"==typeof r&&null!==r&&"case"in r&&"string"==typeof r.case?r.case:void 0}(e),o=function(e){switch(e){case"queued":return"queued";case"delivered":return"delivered";case"queuedForNextTurn":return"queued_for_next_turn";case"cancelled":return"cancelled";default:return"rejected"}}(n),s=void 0===t?void 0:l.get(t);if(void 0!==s&&void 0!==t){const e=function(e){switch(e){case"queued":return"confirm_steering";case"delivered":return"complete_delivered";case"queued_for_next_turn":case"cancelled":case"rejected":return"revert_to_followup";default:throw new Error(`Unknown steer ack state: ${String(e)}`)}}(o);"confirm_steering"===e?clearTimeout(s.ackTimer):(l.delete(t),s.resolve(e))}}await m.sendUpdate(e,t)},query:(e,t)=>m.query(e,t),...void 0!==m.enqueuePostTurnEndedWork?{enqueuePostTurnEndedWork:e=>m.enqueuePostTurnEndedWork?.(e)}:{},...void 0!==m.flushPostTurnEndedWork?{flushPostTurnEndedWork:e=>m.flushPostTurnEndedWork?.(e)??Promise.resolve()}:{}};let w=r.initialState;const y={async handleCheckpoint(e,t){w=t,await(r.onCheckpoint?.(t))},getLatestCheckpoint:()=>w};let v="completed";const b=Date.now(),S=CO(function(e,t){if((0,kO.TU)(t))return t;const r=EO.get(e);if(void 0!==r)return r;const n=(0,kO.sh)(e).blobEncryptionKey;if(void 0===n)throw new Error("getDefaultAgentMetadata did not seed a blobEncryptionKey");return EO.set(e,n),n}(r.conversationId,r.blobEncryptionKey),r.runOptions?.headers);return{done:(async()=>{const e=PO(r,0,xO(t));try{const t=await(n?.onSessionStart?.(e));if(t?.blocked)throw v="error",new Error(t.blockedReason??"Session blocked by sessionStart hook")}catch(e){if("completed"!==v)throw e;SO.Jz.warn("[agent-session-runner] sessionStart hook failed:",e)}let s=t,i=0;for(;s;){const e=PO(r,i,xO(s));try{await(n?.onBeforeSubmitPrompt?.(e))}catch(e){SO.Jz.warn("[agent-session-runner] beforeSubmitPrompt hook failed:",e)}c=r.runOptions?.generationUUID??(0,ge.C)();try{await r.agentClient.run(o,w,s,void 0,g,r.resources,r.blobStore,a,y,r.mcpTools??[],{conversationId:r.conversationId,...r.runOptions,generationUUID:c,headers:S,subagentModelOverrides:r.runOptions?.subagentModelOverrides??[]})}catch(t){throw v=IO(t)?"aborted":"error",TO("aborted"===v?n?.onTurnAborted?.(e):n?.onTurnError?.(e)),t}finally{c=void 0;for(const e of[...l.keys()])u(e,"revert_to_followup")}let t;try{t=await(n?.onTurnCompleted?.(e))}catch(e){throw v="error",e}const h="string"==typeof t?t.trim():"";let m;if(h.length>0)m=RO(h);else{const t=new AbortController;d=t;try{m=await(r.nextAction?.(e,AbortSignal.any([o.signal,t.signal])))}catch(r){if(o.signal.aborted||!t.signal.aborted)throw v=o.signal.aborted||IO(r)?"aborted":"error",TO("aborted"===v?n?.onTurnAborted?.(e):n?.onTurnError?.(e)),r}finally{d=void 0}void 0===m?m=f():p("revert_to_followup")}void 0!==m?(i+=1,a.resetStream(),s=m):s=void 0}})().finally((async()=>{p("revert_to_followup");const e=Date.now()-b;try{await(n?.onSessionEnd?.(v,e))}catch(e){SO.Jz.warn("[agent-session-runner] sessionEnd hook failed:",e)}try{await(n?.dispose?.())}catch(e){SO.Jz.warn("[agent-session-runner] hooks dispose failed:",e)}})),abort(){s()},async steer(e){if(""===e.trim())return"revert_to_followup";const t=c;if(void 0===t){const t=d;if(void 0===t)return"revert_to_followup";const r=new Promise((t=>{h.push({text:e,resolve:t})}));return t.abort(),await r}const r=(0,ge.C)(),n=new Promise((e=>{const t=setTimeout((()=>{u(r,"revert_to_followup")}),15e3);t.unref?.(),l.set(r,{resolve:e,ackTimer:t})}));try{return await a.submitConversationAction(new i.QFf({action:{case:"injectContextAction",value:new i.hGJ({injectionId:r,expectedRunId:t,payload:{case:"userContext",value:new i.oW$({userMessage:new i.RGk({messageId:(0,ge.C)(),text:e})})}})}})),await n}catch(e){return u(r,"revert_to_followup"),SO.Jz.warn("[agent-session-runner] context injection failed:",e),"revert_to_followup"}}}}(a,I,{agentClient:A,interactionListener:T,resources:s,blobStore:l,initialState:f,conversationId:u,mcpTools:h,blobEncryptionKey:t.blobEncryptionKey,runOptions:{generationUUID:t.requestId,requestedModel:m,enableAgentRetries:!1!==r.enableAgentRetries,emitModelCallUsage:!0,...void 0!==t.onConnectionStateChange?{onConnectionStateChange:e=>{!function(e,t){if(void 0!==e)try{e(function(e){switch(e.state){case"connected":return{state:"connected"};case"reconnecting":{const t=e.trigger?.errorClass,r=e.trigger?.stallAborted,n={...void 0!==t?{errorClass:t}:{},...void 0!==r?{stallAborted:r}:{}};return{state:"reconnecting",attempt:e.attempt,...Object.keys(n).length>0?{trigger:n}:{}}}default:return e}}(t))}catch(e){lH.v.warn(`onConnectionStateChange failed: ${e instanceof Error?e.message:String(e)}`)}}(t.onConnectionStateChange,e)}}:{},...Object.keys($).length>0?{headers:$}:{},...void 0!==t.systemPrompt?{customSystemPrompt:t.systemPrompt}:{}},hooks:W,async nextAction(e,t){const r=await M.waitForBackgroundCompletions(u,t);return r.length>0?function(e){return new i.QFf({action:{case:"backgroundTaskCompletionAction",value:new i.Kwc({completions:e.map((e=>new i.KFq({taskId:e.agentId,kind:i.aZc.SUBAGENT,status:"success"===e.status?i.uHL.SUCCESS:"aborted"===e.status?i.uHL.ABORTED:i.uHL.ERROR,...e.finalMessage.length>0?{detail:e.finalMessage}:{}})))})}})}(r):void 0},async onCheckpoint(e){f=e,H.writeFromState(a,e),await(t.onCheckpoint?.(e))}}),z=q.done.finally((async()=>{try{await M.awaitBackgroundWorkers()}finally{await H.waitForPendingWrites().catch((()=>{}));for(const e of E.values())try{await e.dispose()}catch(e){lH.v.log(`Failed to dispose subagent session runtime: ${e instanceof Error?e.message:String(e)}`)}E.clear();try{await g.dispose()}finally{S()}}})).catch((e=>{throw e}));return{abort(){q.abort(),c()},done:z,steer:e=>q.steer(e)}}catch(e){for(const e of E.values())try{await e.dispose()}catch{}E.clear();try{await g.dispose()}finally{S()}throw e}var x,P})),async reload(){await O.reload()},async dispose(){await O.dispose()}}}},"./src/agent/native/tree-sitter-bash.webpack.cjs"(e,r,n){const{loadVendoredTreeSitterModule:o}=n("./src/agent/native/vendored-tree-sitter.ts"),s=o({packageName:"tree-sitter-bash",nativeRequire:t});e.exports=s.available?s.module:{}},"./src/agent/native/tree-sitter.webpack.cjs"(e,r,n){const{createUnavailableParserClass:o,loadVendoredTreeSitterModule:s}=n("./src/agent/native/vendored-tree-sitter.ts"),i=s({packageName:"tree-sitter",nativeRequire:t});e.exports=i.available?i.module:o(i.reason)},"../constants/dist/commercial-cursor-hosts.js"(e,t,r){r.d(t,{H:()=>c,K4:()=>i,Zf:()=>a,ad:()=>l});const n=["cursor.sh","cursor.com","cursorapi.com","cursor.so","cursor-marketplace.com","cursorusercontent.com","anysphere.co"],o=["cursor.blob.core.windows.net"];function s(e){return e.trim().toLowerCase().replace(/\.+$/,"")}const i="CURSOR_ORBIT_BUILD",a="CURSOR_ORBIT_DEPLOYMENT_HOSTS";function c(e){return new Set((e??"").split(",").map(s).filter((e=>""!==e)))}function l(e,t){return function(e){const t=s(e);return o.includes(t)||n.some((e=>t===e||t.endsWith(`.${e}`)))}(e)&&!t.has(s(e))}},"../context/dist/otel.js"(e,t,r){r.d(t,{F:()=>E,HF:()=>_,MG:()=>k,Mf:()=>v,OA:()=>y,V5:()=>C,VI:()=>P,fR:()=>g,fU:()=>w,mJ:()=>b,r2:()=>x,xd:()=>R});var n=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js"),o=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/context-api.js"),s=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace-api.js"),i=r("../context/dist/core.js");const a=(0,i.cF)(Symbol("otel.span"),void 0),c=(0,i.cF)(Symbol("otel.root_span"),void 0),l=(0,i.cF)(Symbol("otel.root_start_ms"),void 0),u=(0,i.cF)(Symbol("otel.suppress_child_spans"),!1),d=(0,i.cF)(Symbol("otel.inheritable_span_attributes"),{});function h(e,t){const r=t.get(d);for(const t in r){const n=r[t];"string"!=typeof n&&"number"!=typeof n&&"boolean"!=typeof n||e.setAttribute(t,n)}}function p(e){return e.name||"anonymous-context"}function f(e,t){return!!t&&(e.get(u)||(p(e),!1))}function m(e="context-tracer"){return s.u.getTracer(e)}function g(e,t){const r=m(),n=e.get(a);if(f(e,n))return e;const i=p(e);let u;if(n){const e=s.u.setSpan(o._.active(),n);u=r.startSpan(i,t,e)}else u=r.startSpan(i,t);h(u,e);const d=Date.now();let g=e.with(a,u);return n||(g=g.with(c,u).with(l,d)),g}function w(e){return e.get(a)}function y(e){return e.with(u,!0)}function v(e,t,r){const n=e.get(d),o=w(e);return o&&null!==r&&o.setAttribute(t,r),e.with(d,{...n,[t]:r})}function b(e){try{const t=w(e);if(!t)return;const r=t.spanContext(),n=e.get(u);return{traceId:r.traceId,spanId:r.spanId,traceFlags:n?0:r.traceFlags,traceState:r.traceState?.serialize()}}catch{return}}const S=Symbol.for("anysphere.context.activeOtelSpanAls");function k(e,t){const r=()=>o._.with(s.u.setSpan(o._.active(),e),t),n=function(){const e=globalThis;if("object"!=typeof(t=e)||null===t||!(S in e))return;var t;const r=e[S];return function(e){return"object"==typeof e&&null!==e&&"run"in e&&"function"==typeof e.run&&"getStore"in e&&"function"==typeof e.getStore}(r)?r:void 0}();return void 0===n?r():n.run(e,r)}function _(e,t){try{const r=m(),n=w(e);if(!n)return;const i=s.u.setSpan(o._.active(),n),a=r.startSpan(t,void 0,i);h(a,e);const u=Date.now(),d=e.get(l),p="number"==typeof d?u-d:0,f=`event.${t}`;(e.get(c)??n).setAttribute(f,p),a.setAttribute(f,p),a.end()}catch{}}function C(e,t,r){const c=m(),l={traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags,isRemote:!0},u=s.u.setSpanContext(o._.active(),l),d=t||"child.span",h=c.startSpan(d,{kind:n.v.INTERNAL},u),p=r??(0,i.q6)();return(t?p.withName(t):p).with(a,h)}function E(e,t,r){const n=s.u.wrapSpanContext({traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags,isRemote:!0}),o=r??(0,i.q6)();return(t?o.withName(t):o).with(a,n)}class x{constructor(e,t,r=!0){this.disposed=!1,this.ctx=e,this.span=t,this.shouldEnd=r}[Symbol.dispose](){this.disposed||(this.disposed=!0,this.shouldEnd&&this.span.end())}}function P(e,t){const r=f(e,w(e)),n=g(e,t),o=w(n);return new x(n,o,!r)}function R(e,t,r){const n=w(e);if(!n||f(e,n))return;const o=w(g(e,t));return o.end(r),o}},"../mcp-core/dist/transport/mcp-url-utils.js"(e,t,r){r.d(t,{$H:()=>Q,ME:()=>G,_N:()=>X,b6:()=>z,bi:()=>P,eA:()=>j,mD:()=>A,rM:()=>J,vc:()=>L});const n=BigInt(0),o=BigInt(8),s=BigInt(16),i=BigInt(65535);function a(e){const t=e.split(".");if(4!==t.length)return;let r=n;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<>s&i)),t.push(Number(o.value&i))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function l(e){return a(e)??function(e){const t=H(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=c(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<7?void 0:{version:6,value:[...a,...new Array(8-u).fill(0),...l].reduce(((e,t)=>e<=R&&d.clear();const t=l(e);return d.set(e,t),t}(e);return void 0!==r&&r.version===t.version&&r.value>>t.shift===t.shiftedNetwork}case"subdomainOrBase":return e===t.suffix||e.endsWith(`.${t.suffix}`);case"exact":return e===t.value;default:return t}}(H(e),function(e){const t=u.get(e);if(t)return t;u.size>=R&&u.clear();const r=function(e){const t=H(e);if("*"===t)return{kind:"matchAll"};if(t.includes("/")){const e=t.lastIndexOf("/");if(e<=0||e===t.length-1)return{kind:"invalidCidr"};const r=l(t.slice(0,e));if(!r)return{kind:"invalidCidr"};const n=Number(t.slice(e+1)),o=4===r.version?32:128;if(!Number.isInteger(n)||n<0||n>o)return{kind:"invalidCidr"};const s=BigInt(o-n);return{kind:"cidr",version:r.version,shift:s,shiftedNetwork:r.value>>s}}return t.startsWith("*.")?{kind:"subdomainOrBase",suffix:t.slice(2)}:{kind:"exact",value:t}}(e);return u.set(e,r),r}(t))}new Set(["airtable.com","anysphere.co","api.aws","apify.com","asana.com","ashbyhq.com","atlassian.com","atlassian.net","azuredatabricks.net","box.com","buildkite.com","calendly.com","canva.com","clickhouse.cloud","clickup.com","cloudflare.com","composio.dev","context7.com","cursor.com","cursor.sh","cursorapi.com","databricks.com","datadoghq.com","datadoghq.eu","ddog-gov.com","dropbox.com","elevenlabs.io","exa.ai","figma.com","firecrawl.dev","github.com","githubcopilot.com","gitlab.com","google.com","googleapis.com","granola.ai","hex.tech","hubspot.com","huggingface.co","intercom.com","linear.app","monday.com","neon.tech","notion.com","plain.com","posthog.com","prisma.io","railway.com","ramp.com","render.com","salesforce.com","sentry.dev","sentry.io","slack.com","snowflakecomputing.com","spacelift.io","statsig.com","stripe.com","supabase.com","todoist.net","vercel.com","workos.com","x.ai","x.com","zapier.com"]);const p="Blocked by MCP Network Admin Server Controls";function f(e){return/\s/.test(e)}const m="[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?",g=new RegExp(`^(?:${m}\\.)*${m}$`),w=new RegExp(`^\\*\\.(?:${m}\\.)*${m}$`),y="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)",v=new RegExp(`^${y}(?:\\.${y}){3}$`),b=/^[0-9a-f:]+$/,S=new RegExp(`^(?:${y}(?:\\.${y}){3}|[0-9a-f:]+)\\/\\d{1,3}$`);function k(e){const t=H(e);return t.length>0&&t.length<=253&&g.test(t)}function _(e){const t=H(e);return v.test(t)||function(e){const t=H(e);if(!b.test(t))return!1;try{return new URL(`https://[${t}]`),!0}catch{return!1}}(t)}function C(e,t){return""===t||"http:"===e&&"80"===t||"https:"===e&&"443"===t}function E(e){const t=new URL(e.pathname||"/",e.origin);if(t.search=e.search,t.pathname.endsWith("/")&&t.pathname.length>1&&(t.pathname=t.pathname.slice(0,-1)),"/"===t.pathname&&""===t.search){const t=e.protocol.toLowerCase();let r=`${t}//${e.hostname.toLowerCase()}`;return C(t,e.port)||(r+=`:${e.port}`),r}const r=e.protocol.toLowerCase();let n=`${r}//${e.hostname.toLowerCase()}`;return C(r,e.port)||(n+=`:${e.port}`),`${n}${t.pathname}${t.search}`}function x(e){if(e.includes("://"))return function(e){try{const t=new URL(e);return("http:"===t.protocol||"https:"===t.protocol)&&!(0===t.hostname.length||t.username.length>0||t.password.length>0)&&""===t.hash&&function(e){const t=e.toLowerCase();return!t.includes("*")&&(k(t)||_(t))}(t.hostname)}catch{return!1}}(e);const t=H(e);return"*"===t||!!w.test(t)||(t.includes("/")?function(e){const t=H(e);if(!S.test(t))return!1;const[r]=t.split("/");return void 0!==r&&h(r,t)}(t):k(t)||_(t))}function P(e){if(I.has(e))return I.get(e);I.size>=R&&I.clear();const t=function(e){const t=e.trim();if(0===t.length)return;const r=t.lastIndexOf("/");if(!t.includes("://")&&r>0&&/^\d+$/.test(t.slice(r+1).trim())){const e=`${H(t.slice(0,r))}/${t.slice(r+1).trim()}`;return x(e)?e:void 0}if(f(t)||t.includes("#")||t.includes("@"))return;const n=t.indexOf("://");if(-1!==n){const e=t.slice(0,n).toLowerCase();if("http"!==e&&"https"!==e)return;try{const e=new URL(t);if(0===e.hostname.length||e.username.length>0||e.password.length>0)return;const r="/"!==e.pathname&&""!==e.pathname,n=""!==e.search;if(e.hostname.includes("*"))return;if(r||n){const t=E(e);if(!x(t))return;return t}{const t=E(e);if(!x(t))return;return t}}catch{return}}else if(t.includes("/"))return;const o=t.trim().toLowerCase(),s=function(e){const t=e.indexOf(":");if(-1===t)return e;const r=e.slice(t+1);return/^\d+$/.test(r)?e.slice(0,t):e}(o);return 0===s.length||!x(s)||s!==o&&"*"===s?void 0:s}(e);return I.set(e,t),t}const R=2048,I=new Map,T=new Map;function A(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}function $(e){return e.endsWith("/")&&e.length>1?e.slice(0,-1):e}function M(e,t){return function(e,t,r){const n=D(t);if(!n)return!1;let o;try{o=new URL(e)}catch{return!1}return""===o.username&&""===o.password&&""===n.username&&""===n.password&&o.protocol===n.protocol&&o.port===n.port&&(s=o.hostname,i=n.hostname,!s.includes("*")&&H(s)===H(i)&&(A(a=o.pathname,c=n.pathname)||A($(a),$(c)))&&function(e,t,r){return""===e?r.allowRequestQueryWhenPatternOmitsQuery||""===t:A(e,t)}(o.search,n.search,r));var s,i,a,c}(e,t,{allowRequestQueryWhenPatternOmitsQuery:!0})}function D(e){const t=e.trim();if(0===t.length||f(t))return;if(function(e){const t=e.indexOf("[");return-1!==t&&-1===e.indexOf("]",t)}(t))return;const r=q(t);if(r&&("http:"===r.protocol||"https:"===r.protocol)&&""===r.username&&""===r.password&&0!==r.hostname.length&&(!H(r.hostname).includes(":")||t.includes("["))){if(t.includes("[")){const e=t.indexOf("["),n=t.indexOf("]",e);if(-1===n)return;const o=t.slice(e+1,n);if(H(r.hostname)!==H(o))return}return r}}function O(e,t){const r=e.toLowerCase(),n=t.toLowerCase();if("*"===r)return!0;if(void 0!==a(n))return A(r,n);if(!r.includes("*"))return r===n;const o=r.slice(1);if(r.startsWith("*.")&&!o.includes("*"))return n.endsWith(o)&&n.length>o.length;const s=r.split("."),i=n.split(".");return s.length===i.length&&!s[s.length-1]?.includes("*")&&A(r,n)}const F=/^([^/?#]+\/\/[^/?#]*):\*(?=[/?#]|$)/,N=/^[^/?#]+\/\/[^/?#]*\*$/;function L(e,t){if("*"===e||e===t)return!0;let r;T.has(t)?r=T.get(t):(T.size>=R&&T.clear(),r=q(t),T.set(t,r));const n=function(e){if(void 0===e||!/[^.]\.$/.test(e.hostname))return;const t=new URL(e.href);return t.hostname=e.hostname.slice(0,-1),t.href}(r);if(void 0!==n&&L(e,n))return!0;const o=function(e){const t=e.trim(),r=t.indexOf("://");if(-1===r)return/^[^/?#]*[^.*/?#]\.$/.test(t)?t.slice(0,-1):void 0;if(!t.includes("*"))return;const n=r+3,o=n+(t.slice(n).split(/[/?#]/,1)[0]??"").replace(/:(?:\d+|\*)$/,"").length;return/[^.*]\.$/.test(t.slice(n,o))?`${t.slice(0,o-1)}${t.slice(o)}`:void 0}(e);return!(void 0===o||!L(o,t))||!!r&&(e.includes("://")?function(e,t){const r=N.test(e),n=r||F.test(e),o=e.indexOf("://"),s=e.slice(0,o).toLowerCase(),i=t.protocol.slice(0,-1),a=q((s.includes("*")&&A(s,i)?`${i}${e.slice(o)}`:e).replace(F,"$1"));if(void 0===a||""!==a.username||""!==a.password||""!==t.username||""!==t.password||a.protocol!==t.protocol||!n&&a.port!==t.port)return!1;const c=a.hostname.replace(/%2a/gi,"*");return(O(c,t.hostname)||r&&O(c.replace(/\*$/,""),t.hostname))&&(r||A(`${a.pathname}${a.search}`,`${t.pathname}${t.search}`))}(e,r):h(r.hostname,e))}function j(e,t){if(A(e,t)||L(e,t))return!0;const r=function(e){const t=e.trim();if(t.includes("*")||!t.includes("://"))return;const r=q(t);return void 0!==r&&""===r.search&&""===r.hash?W(r):void 0}(e);if(void 0===r)return!1;const n=q(t.trim());return void 0!==n&&W(n)===r}const U=/%[0-9a-f]{2}/gi,B=/^[A-Za-z0-9\-._~]$/;function W(e){const t="http:"===e.protocol||"https:"===e.protocol?"http(s):":e.protocol,r=e.hostname.endsWith(".")?e.hostname.slice(0,-1):e.hostname,n=""===e.port?"":`:${e.port}`,o=e.pathname.replace(U,(e=>{const t=String.fromCharCode(Number.parseInt(e.slice(1),16));return B.test(t)?t:e.toUpperCase()})).replace(/\/{2,}/g,"/");return`${t}//${r}${n}${o.endsWith("/")?o.slice(0,-1):o}`}function H(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function q(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch{return}}function z(e){return(e.mcpNetworkAllowlist??[]).flatMap((e=>{const t=P(e);return void 0===t?[]:[t]}))}function G(e,t){if(!0!==t.enabled)return{allowed:!0};if("no_sandbox"===t.mcpNetworkMode)return{allowed:!0};if(!D(e))return{allowed:!1,message:t.blockMessage??p};const r=z(t);return r.length>0&&r.some((t=>function(e,t){const r=D(t);if(!r)return!1;if(!e.includes("://"))return h(H(r.hostname),e);if(M(e,t))return!0;const n=function(e){try{const t=new URL(e);if(""!==t.username||""!==t.password||"/"!==t.pathname||""!==t.search||""!==t.hash)return;return`${t.protocol}//${t.host}/*`}catch{return}}(e);return void 0!==n&&M(n,t)}(t,e)))?{allowed:!0}:{allowed:!1,message:t.blockMessage??p}}function V(e){const t=e?.trim();return t&&t.length>0?t:void 0}function K(e){return V(e)?.toLowerCase()}function J(e,t){const r=K(e.builtinServer),n=K(t.builtinServer);if(void 0!==r||void 0!==n)return void 0!==r&&r===n;const o=V(e.command),s=V(e.serverUrl);if(void 0===o&&void 0===s)return!1;const i=void 0===o||void 0!==t.command&&A(o,t.command),a=void 0===s||void 0!==t.url&&L(s,t.url);return i&&a}function Z(e,t,r){return void 0!==r?.command&&void 0===r.url&&void 0===t&&!0===e?.allowUserOverrideMcpServers}function X({allowedMcpConfiguration:e,server:t,localAgentNetworkAllowlist:r,blockMessage:n,unmatchedServerAllowlist:o,aggregateManagedServerNetworkAllowlists:s=!0,stdioPlatform:i,unsandboxUserExtensionStdio:a}){const c=e?.allowedMcpServers,l=function(e){if(!0!==e?.allowUserOverrideMcpServers)return;const t=(e.deniedMcpServers??[]).flatMap((e=>{const t=V(e.serverUrl),r=void 0===t?void 0:function(e){const t=e.trim();if(0===t.length)return;if(function(e){const t=e.indexOf("://");if(-1===t)return!1;const r=e.slice(t+3),n=r.indexOf("/");return-1===n?r.includes("?"):r.slice(n).includes("*")}(t)){const e=t.indexOf("://");if(-1!==e){const r=t.slice(e+3).split(/[/?#]/,1)[0];if(r?.includes("*")){const e=P(r.replace(/:\d+$/,""));if(void 0!==e)return e}}return}if(!t.includes("://")&&t.includes("*")&&"*"!==t&&!t.startsWith("*."))return;const r=P(e);if(void 0!==r)return r;const n=e.indexOf("://");if(-1===n)return;const o=e.slice(0,n).toLowerCase();if("http"!==o&&"https"!==o)return;const s=e.slice(n+3).split(/[/?#]/,1)[0];if(void 0===s||s.includes("@"))return;const i=P(s.replace(/:\d+$/,""));if(void 0!==i)return i;try{return P(new URL(e).hostname)}catch{return}}(t);return void 0===r?[]:[r]}));return t.length>0?t:void 0}(e),u=void 0===t?void 0:function(e,t){return e?.find((e=>J(e,t)))}(c,t),d=Z(e,u,t),h=function({allowedMcpConfiguration:e,matchedServer:t,server:r}){return void 0===r?(e?.allowedMcpServers?.length??0)>0:void 0!==t||Z(e,t,r)}({allowedMcpConfiguration:e,matchedServer:u,server:t})||void 0===t&&void 0!==l,p=void 0===t?s?c?.flatMap((e=>e.networkAllowlist??[])):void 0:d?[]:function(e,t,r){return void 0===e?r:[...e.networkAllowlist??[],...void 0!==V(e.serverUrl)&&void 0!==t.url?[t.url]:[]]}(u,t,o),f=d&&"win32"===i&&!0===a;let m;m=void 0===t?void 0:f?"no_sandbox":d?"allow_all":function(e,t){var r;if(void 0!==V(e?.command)&&void 0!==t.command&&void 0===t.url)return r=e?.networkMode,("allow_all"===r||"allowlist"===r||"deny_all"===r||"no_sandbox"===r?r:void 0)??"no_sandbox"}(u,t);const g=void 0===t||d?l:void 0;return{enabled:h,mcpNetworkAllowlist:p,...void 0!==m?{mcpNetworkMode:m}:{},...void 0!==g?{mcpNetworkDenylist:g}:{},...void 0!==r?{localAgentNetworkAllowlist:r}:{},...void 0!==n?{blockMessage:n}:{},...f?{win32UserExtensionUnsandbox:!0}:{}}}function Q(e){if(!0===e?.enabled&&"no_sandbox"!==e.mcpNetworkMode)return e}},"../shell-exec/dist/api/index.js"(e,t,r){r.d(t,{BM:()=>Oo,Ls:()=>f,SandboxUnsupportedError:()=>_r,J:()=>x,St:()=>Er,Fn:()=>Do,Qw:()=>a,ue:()=>s,r5:()=>Ie,getLastSandboxFailureReason:()=>kr,oG:()=>no,Ko:()=>T,CG:()=>ht,W1:()=>Z,G6:()=>Mo,dA:()=>He,_B:()=>Qe,OK:()=>Ze,$b:()=>Xe,K3:()=>Rr,tv:()=>st,wG:()=>vt,fZ:()=>bt,s9:()=>mt,XX:()=>yt,T6:()=>et,Po:()=>Ye,$6:()=>nt,l7:()=>it,xS:()=>E,resolveSandboxPolicyForWorkspace:()=>Ct,fB:()=>Dt,spawnInSandbox:()=>xr,Xw:()=>I});var n=r("node:child_process");new Set;const o=["SSH_CLIENT","SSH2_CLIENT"];function s(e){const t=e||process.env,{ELECTRON_RUN_AS_NODE:r,...n}=t;for(const e of Object.keys(n))e.startsWith("AGENT_HOST_DAEMON_")&&delete n[e];for(const e of o)delete n[e];return n}const i="NODE_COMPILE_CACHE";function a(e){const{[i]:t,...r}=e;return r.NODE_DISABLE_COMPILE_CACHE="1",r}const c=["SSH_AUTH_SOCK","DBUS_SESSION_BUS_ADDRESS","XDG_RUNTIME_DIR","WAYLAND_DISPLAY"];function l(e){const t={...e};for(const e of c)delete t[e];return t}const u=[["core.quotePath","false"]];function d(e){const t=function(e){const t=e.GIT_CONFIG_COUNT;if(void 0===t||""===t)return 0;const r=Number.parseInt(t,10);return Number.isFinite(r)&&r>=0?r:0}(e),r=new Set;for(let n=0;no.endsWith(e)))){const n=S(e,r);if(g.existsSync(n))return k(n,t,r)}for(const o of n){const n=S(`${e}${o}`,r);if(g.existsSync(n))return k(n,t,r)}}return e.match(/\.ps1$/i)?{cmd:m.join(process.env.SYSTEMROOT,"System32","WindowsPowerShell","v1.0","PowerShell.exe"),args:["-ExecutionPolicy","Unrestricted","-NoLogo","-NonInteractive","-File",e].concat(t)}:e.match(/\.(bat|cmd)$/i)?{cmd:m.join(process.env.SYSTEMROOT,"System32","cmd.exe"),args:["/C",e,...t]}:e.match(/\.(js)$/i)?{cmd:process.execPath,args:[e].concat(t)}:{cmd:e,args:t}}let _;const C=["/usr/local/bin","/usr/bin","/bin"];function E(){const e=k("rg",[]).cmd;return"rg"!==e?e:void 0}function x(e){if(!e)throw new Error("configureRipgrepPath: path must not be empty");_=e}function P(e){const t=Object.keys(e).filter((e=>"path"===e.toLowerCase()));if(0!==t.length)return"win32"===process.platform?t.find((e=>"Path"===e))??t[0]:t.find((e=>"PATH"===e))??t[0]}function R(e,t){const r=(0,m.dirname)(t);if(!r||"."===r)return e;let n=function(e){const t=P(e);return void 0!==t?e[t]??"":""}(e).split(m.delimiter).filter(Boolean);return 0===n.length&&"win32"!==process.platform&&(n=C),function(e,t){const r=P(e)??("win32"===process.platform?"Path":"PATH"),n={...e};for(const e of Object.keys(n))e!==r&&"path"===e.toLowerCase()&&delete n[e];return n[r]=t,n}(e,[r,...n.filter((e=>e!==r))].join(m.delimiter))}function I(e){return _&&(0,m.isAbsolute)(_)?{...R(e,_),CURSOR_RIPGREP_PATH:_}:e}function T(){if(!_)throw new Error("Ripgrep path not configured. Call configureRipgrepPath() at startup.");return _}const A="win32"===process.platform;function $(e){return!A&&!!e?.SUDO_ASKPASS}function M(e){return $(e)?"alias sudo='sudo -A'; ":""}function D(e){const t=[];let r=0;for(;r=e.length||/\s/.test(e[n])){let o=n;for(;ovoid 0!==t&&e.toUpperCase()===r))}const F=["PYTHONIOENCODING","PYTHONUTF8","PYTHONLEGACYWINDOWSSTDIO"];function N(e){F.some((t=>O(e,t)))||(e.PYTHONIOENCODING="utf-8:surrogateescape")}function L(e){O(e,"WSL_UTF8")||(e.WSL_UTF8="1")}const j="-Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8 -Dstdout.encoding=UTF-8 -Dstderr.encoding=UTF-8",U=["sun.stdout.encoding","sun.stderr.encoding","stdout.encoding","stderr.encoding"],B=`case " \${MAVEN_OPTS-} \${JAVA_TOOL_OPTIONS-} \${JDK_JAVA_OPTIONS-} \${_JAVA_OPTIONS-} " in ${U.map((e=>`*[[:space:]]-D${e}=*`)).join("|")}) ;; *) builtin export MAVEN_OPTS="\${MAVEN_OPTS:+$MAVEN_OPTS }${j}";; esac; `,W=`if ("$env:MAVEN_OPTS $env:JAVA_TOOL_OPTIONS $env:JDK_JAVA_OPTIONS \${env:_JAVA_OPTIONS}" -cnotmatch '(^|\\s)-D(${U.map((e=>e.replace(/\./g,"\\."))).join("|")})=') {\n if ($env:MAVEN_OPTS) { $env:MAVEN_OPTS = "$env:MAVEN_OPTS ${j}" } else { $env:MAVEN_OPTS = '${j}' }\n}`;var H=r("node:crypto?8af2"),q=r("node:os"),z=r("../utils/dist/workspace-paths.js"),G=r("../utils/dist/test-resets.js");let V;function K(e,t){const r=(0,g.lstatSync)(e);return r.isDirectory()&&r.uid===t&&!(18&r.mode)}function J(e){try{(0,g.mkdirSync)(e,{mode:448})}catch(e){if(!(e instanceof Error&&"code"in e&&"EEXIST"===e.code))throw e}}function Z(e){return X(e,{create:!1})}function X(e,{create:t}){const r=process.getuid?.();if(void 0===r)return;const n=(0,m.join)((0,q.tmpdir)(),`cursor-sandbox-${(0,z.r_)((0,m.resolve)(e))}`);try{for(const e of[n,(0,m.join)(n,"tmp")])if(t&&J(e),!K(e,r))return;return n}catch{return}}(0,G.J)((function(){V=void 0}));const Q='builtin eval "${__CURSOR_SANDBOX_TEMP_RESTORE:-}" 2>/dev/null; ',Y=["TMPDIR","TMP","TEMP","TMPPREFIX","NODE_COMPILE_CACHE","NODE_DISABLE_COMPILE_CACHE"],ee="builtin export NODE_DISABLE_COMPILE_CACHE=1; builtin unset NODE_COMPILE_CACHE; ";function te(e){const t=(0,m.join)(e,"tmp");return{TMPDIR:t,TMP:t,TEMP:t,TMPPREFIX:(0,m.join)(t,"sh-")}}function re(e=(0,m.join)((0,q.tmpdir)(),"cursor-sandbox-cache",function(){return V||(V=(0,H.randomBytes)(16).toString("hex")),V}())){return{NPM_CONFIG_CACHE:(0,m.join)(e,"npm"),PNPM_STORE_PATH:(0,m.join)(e,"pnpm-store"),GOCACHE:(0,m.join)(e,"go-build"),GOMODCACHE:(0,m.join)(e,"go-mod"),CARGO_TARGET_DIR:(0,m.join)(e,"cargo-target"),PIP_CACHE_DIR:(0,m.join)(e,"pip"),UV_CACHE_DIR:(0,m.join)(e,"uv"),BUN_INSTALL_CACHE_DIR:(0,m.join)(e,"bun"),YARN_CACHE_FOLDER:(0,m.join)(e,"yarn"),npm_config_devdir:(0,m.join)(e,"node-gyp"),PLAYWRIGHT_BROWSERS_PATH:(0,m.join)(e,"playwright"),PUPPETEER_CACHE_DIR:(0,m.join)(e,"puppeteer"),TURBO_CACHE_DIR:(0,m.join)(e,"turbo"),GRADLE_USER_HOME:(0,m.join)(e,"gradle"),CONDA_PKGS_DIRS:(0,m.join)(e,"conda"),POETRY_CACHE_DIR:(0,m.join)(e,"poetry"),GEM_SPEC_CACHE:(0,m.join)(e,"gem-specs"),COMPOSER_HOME:(0,m.join)(e,"composer"),HOMEBREW_CACHE:(0,m.join)(e,"homebrew"),CYPRESS_CACHE_FOLDER:(0,m.join)(e,"cypress"),NX_CACHE_DIRECTORY:(0,m.join)(e,"nx"),NUGET_PACKAGES:(0,m.join)(e,"nuget"),CCACHE_DIR:(0,m.join)(e,"ccache"),CP_HOME_DIR:(0,m.join)(e,"cocoapods")}}var ne=r("node:fs/promises"),oe=r("../utils/dist/safe-spawn-cwd.js"),se=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js");function ie(){const e=process.env.CURSOR_SANDBOX_POLICY_DIR?.trim();return e?m.resolve(e):m.resolve(m.join(q.homedir(),".cursor","sandbox-policies"))}let ae=0;function ce(){const e=ie();g.mkdirSync(e,{recursive:!0,mode:448});try{g.chmodSync(e,448)}catch{}const t=Date.now();return t-ae>=9e5&&(ae=t,function(e){let t;try{t=g.readdirSync(e)}catch{return}const r=Date.now();for(const n of t){if(!n.startsWith("sandbox-policy-"))continue;const t=m.join(e,n);try{const e=g.statSync(t);if(!e.isFile())continue;r-e.mtimeMs>36e5&&g.unlinkSync(t)}catch{}}}(e)),e}function le(e){const t=ce(),r=H.randomBytes(8).toString("hex"),n=m.join(t,`sandbox-policy-${r}`);return g.writeFileSync(n,e,{encoding:"utf-8",mode:384}),n}const ue="/tmp/node-compile-cache",de="cursor-compile-cache",he=Symbol.for("cursor.startupNodeCompileCache"),pe=process.platform;function fe(e=q.tmpdir(),t=process.platform){if("win32"===t||0===e.length)return[];const r=m.posix.join(e,"node-compile-cache");return r===ue?[]:[r]}function me(e=q.tmpdir(),t=process.env,r=process.platform){if("win32"===r)return[];const n=new Set(fe(e,r));for(const e of["TMPDIR","TMP","TEMP"]){const o=t[e];if(void 0!==o&&m.posix.isAbsolute(o))for(const e of fe(m.posix.resolve(o),r))n.add(e)}return[...n]}function ge(e=process.env,t=q.homedir(),r=process.platform){if("darwin"===r)return t.length>0?m.posix.join(t,"Library/Caches",de):void 0;if("linux"!==r)return;const n=e.XDG_CACHE_HOME;return void 0!==n&&m.posix.isAbsolute(n)?m.posix.join(n,de):t.length>0?m.posix.join(t,".cache",de):void 0}function we(e=process.env,t=process.platform){if("win32"===t)return;const r=Object.getOwnPropertyDescriptor(globalThis,he)?.value,n="string"==typeof r?r:e.NODE_COMPILE_CACHE;if(void 0===n||!m.posix.isAbsolute(n))return;const o=m.posix.resolve(n);return"/"===o?void 0:o}function ye(e=q.homedir(),t=q.tmpdir(),r=process.env,n=process.platform){if("win32"===n)return[];const o=new Set([ue]);e.length>0&&(o.add(m.posix.join(e,".cache",de)),o.add(m.posix.join(e,"Library/Caches",de)));const s=[];for(const i of[...me(t,r,n),ge(r,e,n),we(r,n)])void 0===i||o.has(i)||(o.add(i),s.push(i));return s}function ve(e=q.homedir(),t=q.tmpdir(),r=process.platform,n=process.env){if("win32"===r)return[];const o=[ue,...me(t,n,r)],s=ge(n,e,r);return void 0===s||o.includes(s)||o.push(s),o}function be(e,t){return e.isSymbolicLink()?"a link, not followed":e.isDirectory()?e.uid!==t?`owned by uid ${e.uid}`:void 0:"not a folder"}function Se(e){return"object"!=typeof e||null===e?{}:Object.fromEntries(Object.entries(e).filter((e=>"string"==typeof e[1])))}function ke(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:"error"}const _e=[".local/bin",".local/share/mise",".local/share/pnpm",".nvm",".volta",".asdf",".pyenv",".rbenv",".rustup",".cargo/bin",".cargo/registry",".cargo/git"],Ce=["bin","sbin","lib","opt","Cellar","share","Frameworks","etc/gitconfig","etc/openssl@3/cert.pem","etc/openssl@3/openssl.cnf","etc/ca-certificates"],Ee=(e,t)=>t.flatMap((t=>Ce.map((r=>({platform:e,scope:"global",path:`${t}/${r}`}))))),xe={linux:[".cache/node",".cache/yarn"],darwin:[".cache/node","Library/Caches/Yarn"]},Pe=e=>[..._e,...xe[e]].map((t=>({platform:e,scope:"home-dir",path:t}))),Re=[{platform:"linux",scope:"global",path:"/bin"},{platform:"linux",scope:"global",path:"/sbin"},{platform:"linux",scope:"global",path:"/usr/bin"},{platform:"linux",scope:"global",path:"/usr/sbin"},{platform:"linux",scope:"global",path:"/lib"},{platform:"linux",scope:"global",path:"/lib64"},{platform:"linux",scope:"global",path:"/usr/lib"},{platform:"linux",scope:"global",path:"/usr/lib64"},{platform:"linux",scope:"global",path:"/usr/libexec"},{platform:"linux",scope:"global",path:"/usr/share"},{platform:"linux",scope:"global",path:"/etc/ld.so.cache"},{platform:"linux",scope:"global",path:"/etc/ld.so.conf"},{platform:"linux",scope:"global",path:"/etc/ld.so.conf.d"},{platform:"linux",scope:"global",path:"/etc/ssl/certs"},{platform:"linux",scope:"global",path:"/etc/ssl/openssl.cnf"},{platform:"linux",scope:"global",path:"/etc/ssl/cert.pem"},{platform:"linux",scope:"global",path:"/etc/ssl/ca-bundle.pem"},{platform:"linux",scope:"global",path:"/etc/ssl/certs/ca-certificates.crt"},{platform:"linux",scope:"global",path:"/etc/pki/tls/certs"},{platform:"linux",scope:"global",path:"/etc/pki/tls/openssl.cnf"},{platform:"linux",scope:"global",path:"/etc/pki/ca-trust/extracted"},{platform:"linux",scope:"global",path:"/etc/resolv.conf"},{platform:"linux",scope:"global",path:"/etc/hosts"},{platform:"linux",scope:"global",path:"/etc/nsswitch.conf"},{platform:"linux",scope:"global",path:"/etc/gai.conf"},{platform:"linux",scope:"global",path:"/etc/alternatives"},{platform:"linux",scope:"global",path:"/etc/mime.types"},{platform:"linux",scope:"global",path:"/etc/profile"},{platform:"linux",scope:"global",path:"/etc/bash.bashrc"},{platform:"linux",scope:"global",path:"/etc/zsh/zshenv"},{platform:"linux",scope:"global",path:"/etc/zsh/zprofile"},{platform:"linux",scope:"global",path:"/etc/zsh/zshrc"},{platform:"linux",scope:"global",path:"/etc/zsh/zlogin"},{platform:"linux",scope:"global",path:"/etc/gitconfig"},{platform:"linux",scope:"home",path:".bashrc"},{platform:"linux",scope:"home",path:".bash_profile"},{platform:"linux",scope:"home",path:".profile"},{platform:"linux",scope:"home",path:".zshenv"},{platform:"linux",scope:"home",path:".zprofile"},{platform:"linux",scope:"home",path:".zshrc"},{platform:"linux",scope:"home",path:".zlogin"},{platform:"linux",scope:"home",path:".gitconfig"},{platform:"linux",scope:"home",path:".ssh/known_hosts"},{platform:"linux",scope:"home",path:".config/mise/config.toml"},{platform:"linux",scope:"home-dir",path:".cache/dotslash"},...Pe("linux"),...Ee("linux",["/usr/local","/home/linuxbrew/.linuxbrew"]),{platform:"linux",scope:"global",path:"/usr/local/go"},{platform:"linux",scope:"global",path:"/nix/store"},{platform:"linux",scope:"global",path:"/nix/var/nix/profiles"},{platform:"linux",scope:"bundled",path:"ripgrep"},{platform:"darwin",scope:"global",path:"/bin"},{platform:"darwin",scope:"global",path:"/usr/bin"},{platform:"darwin",scope:"global",path:"/usr/lib"},{platform:"darwin",scope:"global",path:"/usr/libexec"},{platform:"darwin",scope:"global",path:"/usr/share"},{platform:"darwin",scope:"global",path:"/System/Library"},{platform:"darwin",scope:"global",path:"/System/Cryptexes"},{platform:"darwin",scope:"global",path:"/Library/Apple"},{platform:"darwin",scope:"global",path:"/Library/Developer/CommandLineTools"},{platform:"darwin",scope:"global",path:"/Applications/Xcode.app"},{platform:"darwin",scope:"global",path:"/Library/Preferences/com.apple.dt.Xcode.plist"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/cert.pem"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/certs"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/openssl.cnf"},{platform:"darwin",scope:"global",path:"/private/etc/hosts"},{platform:"darwin",scope:"global",path:"/private/etc/resolv.conf"},{platform:"darwin",scope:"global",path:"/private/etc/apache2/mime.types"},{platform:"darwin",scope:"global",path:"/etc/profile"},{platform:"darwin",scope:"global",path:"/etc/bashrc"},{platform:"darwin",scope:"global",path:"/etc/zshenv"},{platform:"darwin",scope:"global",path:"/etc/zprofile"},{platform:"darwin",scope:"global",path:"/etc/zshrc"},{platform:"darwin",scope:"global",path:"/etc/zlogin"},{platform:"darwin",scope:"global",path:"/etc/gitconfig"},{platform:"darwin",scope:"home",path:".bashrc"},{platform:"darwin",scope:"home",path:".bash_profile"},{platform:"darwin",scope:"home",path:".profile"},{platform:"darwin",scope:"home",path:".zshenv"},{platform:"darwin",scope:"home",path:".zprofile"},{platform:"darwin",scope:"home",path:".zshrc"},{platform:"darwin",scope:"home",path:".zlogin"},{platform:"darwin",scope:"home",path:".gitconfig"},{platform:"darwin",scope:"home",path:".ssh/known_hosts"},{platform:"darwin",scope:"home",path:"Library/Preferences/.GlobalPreferences.plist"},{platform:"darwin",scope:"home",path:".config/mise/config.toml"},{platform:"darwin",scope:"home-dir",path:"Library/Python"},{platform:"darwin",scope:"home-dir",path:"Library/Caches/dotslash"},...Pe("darwin"),...Ee("darwin",["/opt/homebrew","/usr/local"]),{platform:"darwin",scope:"global",path:"/nix/store"},{platform:"darwin",scope:"global",path:"/nix/var/nix/profiles"},{platform:"darwin",scope:"bundled",path:"ripgrep"},{platform:"darwin",scope:"global",path:"/dev/null"},{platform:"darwin",scope:"global",path:"/dev/zero"},{platform:"darwin",scope:"global",path:"/dev/random"},{platform:"darwin",scope:"global",path:"/dev/urandom"}];function Ie(e=process.platform,t=q.default.homedir(),r={}){const n=[];for(const o of Re){if(o.platform!==e)continue;if("global"===o.scope){n.push(o.path);continue}const s="bundled"===o.scope?r[o.path]:(0,m.join)(t,o.path);if(s)try{let e;switch(o.scope){case"home":e=(0,g.lstatSync)(s).isFile();break;case"home-dir":e=(0,g.lstatSync)(s).isDirectory();break;case"bundled":e=(0,g.statSync)(s).isFile()}e&&n.push(s)}catch{}}return n}const Te=[{type:"workspace",pattern:"**/.cursor/*.json"},{type:"workspace",pattern:"**/.cursor/**/*.json"},{type:"workspace",pattern:"**/.cursor/.workspace-trusted"},{type:"workspace",pattern:"!**/.cursor/rules"},{type:"workspace",pattern:"!**/.cursor/rules/**"},{type:"workspace",pattern:"!**/.cursor/commands"},{type:"workspace",pattern:"!**/.cursor/commands/**"},{type:"workspace",pattern:"!**/.cursor/worktrees"},{type:"workspace",pattern:"!**/.cursor/worktrees/**"},{type:"workspace",pattern:"!**/.cursor/skills"},{type:"workspace",pattern:"!**/.cursor/skills/**"},{type:"workspace",pattern:"!**/.cursor/agents"},{type:"workspace",pattern:"!**/.cursor/agents/**"},{type:"workspace",pattern:"**/.claude/*.json"},{type:"workspace",pattern:"**/.claude/**/*.json"},{type:"workspace",pattern:"**/.vscode/**"},{type:"workspace",pattern:"**/.idea/**"},{type:"workspace",pattern:"**/.venv/"},{type:"workspace",pattern:"**/venv/"},{type:"workspace",pattern:"**/*.code-workspace"},{type:"workspace",pattern:"**/.cursorignore"},{type:"workspace",pattern:"**/.workspace-trusted"},{type:"workspace",pattern:"**/.cursor/**/cli.json"},{type:"workspace",pattern:"**/.cursor/**/cli-config.json"},{type:"workspace",pattern:"**/.cursor/**/mcp.json"},{type:"workspace",pattern:"**/.cursor/**/mcp-approvals.json"},{type:"workspace",pattern:"**/.cursor/**/permissions.json"},{type:"git",pattern:"**/.git/hooks/**"},{type:"git",pattern:"**/.git/config"},{type:"git",pattern:"**/.git/config.worktree"},{type:"git",pattern:"**/.git/info/attributes"},{type:"git",pattern:"**/.git/commondir"},{type:"git",pattern:"**/.git/worktrees/*/commondir"},{type:"git",pattern:"**/.git/worktrees/*/gitdir"},{type:"worktree",pattern:".git"},{type:"absolute",pattern:"/etc/ssl/cert.pem"},{type:"absolute",pattern:"/etc/ssl/ca-bundle.pem"},{type:"absolute",pattern:"/private/etc/ssl/cert.pem"},{type:"absolute",pattern:"/etc/ssl/certs/ca-certificates.crt"},{type:"absolute",pattern:"/etc/pki/tls/certs/ca-bundle.crt"},{type:"absolute",pattern:"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem"},{type:"home",pattern:".cursor/sandbox-policies"},{type:"absolute",pattern:"/tmp/node-compile-cache"},{type:"home",pattern:".cache/cursor-compile-cache"},{type:"home",pattern:"Library/Caches/cursor-compile-cache"}];function Ae(e){const t=Te.filter((e=>"workspace"===e.type)).map((e=>e.pattern));return{[e]:t}}function $e(e){const t=Te.filter((e=>"git"===e.type)).map((e=>e.pattern));return{[e]:t}}function Me(e){const t=Te.filter((e=>"worktree"===e.type)).map((e=>e.pattern));return{[e]:t}}Te.filter((e=>"git"===e.type)).map((e=>e.pattern)),Te.filter((e=>"workspace"===e.type&&e.pattern.startsWith("!")&&!e.pattern.endsWith("/**"))).map((e=>e.pattern.replace(/^!(\*\*\/)?/,"")));const De=[];let Oe=null,Fe=null;function Ne(e){if(!(e instanceof Error&&"code"in e&&"string"==typeof e.code)||e.code.startsWith("ERR_"))throw e}async function Le(e,t=""){const r=await(0,ne.lstat)(e).catch(Ne);if(void 0===r||!r.isFile()||r.size>4096)return;const n=await(0,ne.readFile)(e,"utf8").catch(Ne),o=n?.split("\n",1)[0]?.replace(/\r$/,"");if(void 0===o||!o.startsWith(t))return;const s=o.slice(t.length);return s.length>0&&!s.includes("\0")?s:void 0}async function je(e){if(!(0,oe.$f)(e))return(0,ne.realpath)(e).catch(Ne)}async function Ue(e){const t=await Le((0,m.join)(e,".git"),"gitdir: ");if(void 0===t)return;const r=await je((0,m.resolve)(e,t));if(void 0===r)return;const n=await Le((0,m.join)(r,"commondir")),o=void 0===n?r:await je((0,m.resolve)(r,n));return void 0===o?void 0:{gitDir:r,commonDirLink:n,commonDir:o}}async function Be(e){const t=await Ue(e);if(void 0===t||void 0===t.commonDirLink||"worktrees"!==(0,m.basename)((0,m.dirname)(t.gitDir)))return;const r=(0,m.dirname)((0,m.dirname)(t.gitDir));if(".git"!==(0,m.basename)(r)||(ze?t.commonDir.toLowerCase()!==r.toLowerCase():t.commonDir!==r))return;const n=await Le((0,m.join)(t.gitDir,"gitdir"));if(void 0===n)return;const o=(0,m.join)(e,".git"),[s,i]=await Promise.all([je((0,m.resolve)(t.gitDir,n)),je(o)]);return void 0!==s&&void 0!==i&&(ze?s.toLowerCase()===i.toLowerCase():s===i)?r:void 0}let We=null;function He(e){return function(){const e=q.default.homedir();if(null===We){const t=[];for(const r of Te)switch(r.type){case"absolute":t.push(r.pattern);break;case"home":e.length>0&&t.push((0,m.join)(e,r.pattern))}We=t}return[...We,...ye(e)]}().some((t=>{if(Ke(e,t))return!0;const r=function(e){let t;try{t=g.realpathSync.native((0,m.dirname)(e))}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;return"ENOENT"===t||"ENOTDIR"===t?void 0:qe}const r=(0,m.join)(t,(0,m.basename)(e));return r===(0,m.dirname)(r)?void 0:r}(t);return r===qe||void 0!==r&&Ke(e,r)}))}const qe=Symbol("unresolved parent");const ze="win32"===process.platform||"darwin"===process.platform;function Ge(e){if(!e.endsWith(m.sep))return e;const t=e.slice(0,-1);return""===t||"win32"===process.platform&&/^[a-zA-Z]:$/.test(t)?e:t}function Ve(e){return e.endsWith(m.sep)?e:e+m.sep}function Ke(e,t){const r=Ge(t);if(ze){const t=e.toLowerCase(),n=r.toLowerCase();return t===n||t.startsWith(Ve(n))}return e===r||e.startsWith(Ve(r))}function Je(e,t){const r=Ge(e);return ze?(0,m.relative)(r.toLowerCase(),t.toLowerCase()).replace(/\\/g,"/"):(0,m.relative)(r,t).replace(/\\/g,"/")}async function Ze(e,t){if(Ke(e,t)){const r=Je(t,e);if((null===Oe&&(Oe=se({ignoreCase:!0}),Oe.add(Te.filter((e=>"workspace"===e.type)).map((e=>e.pattern)))),Oe).ignores(r))return!0}const{isWorktree:r,gitDirParent:n}=await async function(e){const t=await(0,ne.lstat)((0,m.join)(e,".git")).catch(Ne);if(!t?.isFile())return{isWorktree:!1,gitDirParent:e};const r=await async function(e){return(await Ue(e))?.commonDir}(e);return{isWorktree:!0,gitDirParent:void 0===r?e:(0,m.dirname)(r)}}(t);for(const r of new Set([n,t]))if(Ke(e,r)){const t=Je(r,e);if((null===Fe&&(Fe=se({ignoreCase:!0}),Fe.add(Te.filter((e=>"git"===e.type)).map((e=>e.pattern)))),Fe).ignores(t))return!0}return!(!r||!Ke(e,t)||".git"!==Je(t,e))||He(e)}function Xe(e){return void 0!==e&&("allow"===e.default||void 0!==e.allow&&e.allow.length>0)}function Qe(e){return void 0!==e&&"allow"===e.default}function Ye(){return{version:1,default:"deny"}}function et(){return{version:1,default:"allow"}}var tt=r("../utils/dist/path-utils.js");function rt(e){if(!e)return;const t={version:1};if("allow"!==e.default&&"deny"!==e.default||(t.default=e.default),Array.isArray(e.allow)&&e.allow.length>0&&(t.allow=e.allow.filter((e=>"string"==typeof e))),Array.isArray(e.deny)&&e.deny.length>0&&(t.deny=e.deny.filter((e=>"string"==typeof e))),e.logging){const r={};"string"==typeof e.logging.decisionLogPath&&(r.decisionLogPath=e.logging.decisionLogPath),"jsonl"===e.logging.logFormat&&(r.logFormat="jsonl"),Object.keys(r).length>0&&(t.logging=r)}return t}function nt(e){const t=e.type??"workspace_readwrite",r={debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,enableSharedBuildCache:e.enableSharedBuildCache};if("insecure_none"===t)return{type:"insecure_none",...r};let n;if(Array.isArray(e.additionalReadonlyPaths)){const t=e.additionalReadonlyPaths;n=t.length>0?t:void 0}const o={...r,networkAccess:e.networkAccess,networkPolicy:rt(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,additionalReadonlyPaths:n,readBoundary:e.readBoundary,additionalReadPaths:Array.isArray(e.additionalReadPaths)?e.additionalReadPaths:void 0,disableTmpWrite:e.disableTmpWrite,privateTmp:e.privateTmp};return"workspace_readonly"===t?{type:"workspace_readonly",...o}:{type:"workspace_readwrite",...o,additionalReadwritePaths:e.additionalReadwritePaths}}function ot(e){if("object"!=typeof e||null===e)return"Expected an object";const t=Object.fromEntries(Object.entries(e));if(void 0!==t.type){const e=["insecure_none","workspace_readwrite","workspace_readonly"];if("string"!=typeof t.type||!e.includes(t.type))return`Invalid type: expected one of ${e.join(", ")}`}const r=["networkAccess","networkPolicyStrict","disableTmpWrite","privateTmp","enableSharedBuildCache","captureDenies"];for(const e of r)if(void 0!==t[e]&&"boolean"!=typeof t[e])return`Invalid ${e}: expected boolean`;const n=["debugOutputDir"];for(const e of n)if(void 0!==t[e]&&"string"!=typeof t[e])return`Invalid ${e}: expected string`;const o=["additionalReadwritePaths","additionalReadonlyPaths","additionalReadPaths"];for(const e of o)if(void 0!==t[e]){if(!Array.isArray(t[e]))return`Invalid ${e}: expected array`;if(!t[e].every((e=>"string"==typeof e)))return`Invalid ${e}: expected array of strings`}if(void 0!==t.readBoundary&&"system"!==t.readBoundary&&"workspace"!==t.readBoundary)return'Invalid readBoundary: expected "system" or "workspace"';if(void 0!==t.networkPolicy){if("object"!=typeof t.networkPolicy||null===t.networkPolicy)return"Invalid networkPolicy: expected object";const e=Object.fromEntries(Object.entries(t.networkPolicy));if(void 0!==e.default&&"allow"!==e.default&&"deny"!==e.default)return'Invalid networkPolicy.default: expected "allow" or "deny"';if(void 0!==e.allow&&!Array.isArray(e.allow))return"Invalid networkPolicy.allow: expected array";if(void 0!==e.deny&&!Array.isArray(e.deny))return"Invalid networkPolicy.deny: expected array"}}async function st(e,t){const r=await async function(e,t){try{const r=await(0,ne.readFile)(e,"utf-8"),n=JSON.parse(r);if(void 0!==ot(n))return{success:!1,error:`Invalid sandbox policy: ${ot(n)??""}`};let o=nt(n);return t&&(o=it(o,t)),{success:!0,policy:o}}catch(e){return e instanceof Error?"code"in e&&"ENOENT"===e.code?{success:!1,error:"File not found"}:e instanceof SyntaxError?{success:!1,error:`Invalid JSON: ${e.message}`}:{success:!1,error:e.message}:{success:!1,error:"Unknown error"}}}(e,t);if(r.success)return r.policy}function it(e,t){if("insecure_none"===e.type)return e;const r=e.additionalReadonlyPaths?.map((e=>(0,tt.o1)(e,t))),n=e.additionalReadPaths?.map((e=>(0,tt.o1)(e,t)));if("workspace_readonly"===e.type)return{...e,additionalReadonlyPaths:r,additionalReadPaths:n};const o=e.additionalReadwritePaths?.map((e=>(0,tt.o1)(e,t)));return{...e,additionalReadonlyPaths:r,additionalReadPaths:n,additionalReadwritePaths:o}}var at=r("../constants/dist/commercial-cursor-hosts.js");function ct(e){const t=e.replace(/\\/g,"/").replace(/\/+$/,"");return""===t?"/":/^[a-zA-Z]:$/.test(t)?`${t}/`:t}function lt(e){const t=ct(e);return/^[a-zA-Z]:\//.test(t)||t.startsWith("//")?t.toLowerCase():t}const ut={insecure_none:0,workspace_readwrite:1,workspace_readonly:2};function dt(){return"1"===process.env[at.K4]}function ht(e){if(!dt())return e.teamAdmin?.type??e.perRepo?.type??e.perUser?.type??"insecure_none";const t=e.teamAdmin?.type??e.perUser?.type;return void 0===t&&void 0===e.perRepo?"insecure_none":Rt(t??"workspace_readwrite",e.perRepo?.type??"insecure_none")}function pt(...e){return e.some((e=>!0===e))}function ft(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return[];if(t.some((e=>0===e.length)))return[];if(1===t.length)return function(e){const t=new Set,r=[];for(const n of e){const e=lt(n);t.has(e)||(t.add(e),r.push(n))}return r}(t[0]).map(ct);let r=new Map(t[0].map((e=>{const t=ct(e);return[lt(t),t]})));for(let e=1;en.has(e))))}return[...r.values()]}function mt(...e){const t=new Map;for(const r of e)if(r)for(const e of r){const r=ct(e),n=lt(r);t.has(n)||t.set(n,r)}return[...t.values()]}const gt=function({defaultValue:e,rank:t}){return{defaultValue:e,merge:(...r)=>{const n=r.filter((e=>void 0!==e));return 0===n.length?e:n.reduce(((e,r)=>t[r]ft(...e);function yt(...e){return gt.merge(...e)}function vt(...e){return wt(...e)}function bt(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return;let r;for(const e of t){if("deny"===e.default){r="deny";break}"allow"===e.default&&void 0===r&&(r="allow")}const n=new Set;for(const e of t)if(e.deny)for(const t of e.deny)n.add(t);const o=new Set;for(const e of t)if(e.allow)for(const t of e.allow)o.add(t);const s=o.size>0?[...o]:void 0;let i;for(let e=t.length-1;e>=0;e--)if(void 0!==t[e].logging){i=t[e].logging;break}const a={version:1};return void 0!==r&&(a.default=r),void 0!==s&&(a.allow=s),n.size>0&&(a.deny=[...n]),void 0!==i&&(a.logging=i),void 0!==a.default||void 0!==a.allow&&0!==a.allow.length||void 0!==a.deny&&0!==a.deny.length||void 0!==a.logging?a:void 0}function St(e,t){if(!e||0===e.length)return[...t];const r=new Set(e);for(const e of t)r.has(e)&&r.delete(e),r.add(e);return[...r]}function kt(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return;const r={};for(const e of t)for(const[t,n]of Object.entries(e))r[t]=St(r[t],n);return 0!==Object.keys(r).length?r:void 0}function _t(...e){for(let t=e.length-1;t>=0;t--)if(void 0!==e[t])return e[t]}async function Ct(e,t,r={}){if(!t)return{policy:{type:"insecure_none"}};if(dt()&&(t=Mt(t,e)),(0,oe.$f)(e))return Ot(t,{workspaceDir:e});if("workspace_readwrite"!==(Pt(t)??"workspace_readwrite"))return Ot(t,{workspaceDir:e});const n=r.stat??ne.stat,o=await async function(e,t){for(let r=e;;r=(0,m.dirname)(r)){if((0,oe.$f)(r))return;const e=await Et(r,t);if(void 0!==e)return e;if((0,m.dirname)(r)===r)return}}(e,n);let s=o?.root??e;if(o?.isFile){const e=await Be(o.root);void 0!==e&&(s=(0,m.dirname)(e)),t=xt(t,void 0===e?[]:[e],Me(o.root))}return t=await async function(e,t,r){const n=Nt(e,"workspace_readwrite"),o=mt(n.perUser?.additionalReadwritePaths,n.perRepo?.additionalReadwritePaths,n.teamAdmin?.additionalReadwritePaths);if(0===o.length)return e;const s=(await Promise.all(o.map((async e=>{if(t.has(ct(e))||(0,oe.$f)(e))return[];const n=await Et(e,r);if(void 0===n)return[];const o=[Ae(e),$e(e)];if(n.isFile){o.push(Me(e));const t=await Be(e);void 0!==t&&o.push($e((0,m.dirname)(t)))}return o})))).flat();return 0===s.length?e:xt(e,[],...s)}(t,new Set([ct(e)]),n),Ot(t,{workspaceDir:e,gitDirParent:s})}async function Et(e,t){const r=await t((0,m.join)(e,".git")).catch(Ne);return r?.isFile()||r?.isDirectory()?{root:e,isFile:r.isFile()}:void 0}function xt(e,t,...r){const n=dt(),o=n?e.perUser:e.perRepo,s="workspace_readwrite"===o?.type||void 0===o?o:void 0,i={...s,type:"workspace_readwrite",additionalReadwritePaths:t.length>0?[...s?.additionalReadwritePaths??[],...t]:s?.additionalReadwritePaths,writeProtectionMapping:kt(s?.writeProtectionMapping,...r)};return n?{...e,perUser:i}:{...e,perRepo:i}}function Pt(e){const{perUser:t,perRepo:r,teamAdmin:n}=e,o=[t,r,n].filter((e=>void 0!==e));if(0===o.length)return;const s=o[0].type;for(const e of o)if(e.type!==s)throw new Error(`Cannot merge policies of different types: found "${s}" and "${e.type}". All policies must be of the same type (all workspace_readwrite, all workspace_readonly, or all insecure_none).`);return s}function Rt(e,t){return ut[e]>=ut[t]?e:t}function It(e,t){if(void 0===e||e.type===t)return e;if("insecure_none"===t)return{type:t,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,enableSharedBuildCache:e.enableSharedBuildCache};if("insecure_none"===e.type)return{...e,type:t};if("workspace_readonly"===t){if("workspace_readwrite"===e.type){const{additionalReadwritePaths:r,...n}=e;return{...n,type:t}}return e}return e}function Tt(e){if("deny"===e?.default||void 0!==e?.deny&&0!==e.deny.length)return{version:1,..."deny"===e.default?{default:"deny"}:{},...void 0!==e.deny&&e.deny.length>0?{deny:e.deny}:{}}}function At(e,t,r){if(void 0===e||"insecure_none"===t)return;const n="insecure_none"===e.type?void 0:e,o={captureDenies:!0===e.captureDenies||void 0,networkPolicy:Tt(n?.networkPolicy),networkPolicyStrict:!0===n?.networkPolicyStrict||void 0,readBoundary:"workspace"===n?.readBoundary?"workspace":void 0,additionalReadPaths:void 0===n?.additionalReadPaths?void 0:ft(n.additionalReadPaths,r),additionalReadonlyPaths:n?.additionalReadonlyPaths,disableTmpWrite:!0===n?.disableTmpWrite||void 0,ignoreMapping:n?.ignoreMapping,writeProtectionMapping:n?.writeProtectionMapping};return"workspace_readonly"===t?{type:t,...o}:{type:"workspace_readwrite",...o}}function $t(e,t){return void 0===e||"insecure_none"===e.type||void 0===t?e:{...e,additionalReadPaths:e.additionalReadPaths?.map((e=>ct((0,tt.o1)(e,t))))}}function Mt(e,t){const r=Pt({perUser:e.perUser,teamAdmin:e.teamAdmin})??"workspace_readwrite",n=void 0===e.perRepo?r:Rt(r,e.perRepo.type),o=$t(It(e.perUser,n),t),s=$t(It(e.teamAdmin,n),t),i=mt("insecure_none"===o?.type?void 0:o?.additionalReadPaths,"insecure_none"===s?.type?void 0:s?.additionalReadPaths);return{perUser:o,perRepo:At(e.perRepo,n,i),teamAdmin:s}}function Dt(e,t){return Mt(e,t)}function Ot(e,t){return function(e,t){dt()&&(e=Mt(e,t?.workspaceDir));const r=Pt(e);if(void 0===r)return Ut({},t);switch(r){case"workspace_readwrite":return Ut(Nt(e,r),t);case"workspace_readonly":return function(e,t){const r=t?.debug,n=Lt(e,t),o={policy:jt({type:"workspace_readonly",disableTmpWrite:n.disableTmpWrite,networkPolicyStrict:n.networkPolicyStrict,readBoundary:n.readBoundary,additionalReadPaths:n.additionalReadPaths,additionalReadonlyPaths:n.additionalReadonlyPaths,networkPolicy:n.networkPolicy,debugOutputDir:n.debugOutputDir,captureDenies:n.captureDenies,enableSharedBuildCache:n.enableSharedBuildCache,privateTmp:n.privateTmp,ignoreMapping:n.ignoreMapping,writeProtectionMapping:n.writeProtectionMapping},"workspace_readonly")};return r&&(o.debug={fieldSources:n.fieldSources}),o}(Nt(e,r),t);case"insecure_none":return function(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,s=t?.debug,i={policy:jt({type:"insecure_none",allowlistEscalated:pt(r?.allowlistEscalated,n?.allowlistEscalated,o?.allowlistEscalated)||void 0,debugOutputDir:_t(r?.debugOutputDir,n?.debugOutputDir,o?.debugOutputDir),captureDenies:pt(r?.captureDenies,n?.captureDenies,o?.captureDenies)||void 0,enableSharedBuildCache:_t(r?.enableSharedBuildCache,n?.enableSharedBuildCache,o?.enableSharedBuildCache)},"insecure_none")};return s&&(i.debug={fieldSources:{}}),i}(Nt(e,r),t);default:throw new Error(`Unknown policy type: ${String(r)}`)}}(e,t)}function Ft(e,t){return e?.type===t}function Nt(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e;return{perUser:Ft(r,t)?r:void 0,perRepo:Ft(n,t)?n:void 0,teamAdmin:Ft(o,t)?o:void 0}}function Lt(e,t){const r=t?.debug,{perUser:n,perRepo:o,teamAdmin:s}=e,i=t?.workspaceDir??process.cwd(),a=function(e){const t=function(){if(0!==De.length)return{version:1,deny:[...De]}}(),r=q.default.homedir(),n=[];for(const e of Te)switch(e.type){case"workspace":case"git":case"worktree":break;case"absolute":n.push(e.pattern);break;case"home":r.length>0&&n.push((0,m.join)(r,e.pattern));break;default:{const t=e.type;throw new Error(`Unknown entry type: ${String(t)}`)}}return n.push(...ye(r)),{type:"workspace_readwrite",additionalReadonlyPaths:n,writeProtectionMapping:Ae(e),...t&&{networkPolicy:t},networkPolicyStrict:!0}}(i),c={},l=[n,o,s],u=["perUser","perRepo","teamAdmin","hardcoded"],d=(e,t)=>{r&&(c[e]=u[t]??"unknown")},h=pt(n?.disableTmpWrite,o?.disableTmpWrite,s?.disableTmpWrite);for(let e=l.length-1;e>=0;e--)if(!0===l[e]?.disableTmpWrite){d("disableTmpWrite",e);break}const p=pt(n?.networkPolicyStrict,o?.networkPolicyStrict,s?.networkPolicyStrict,a.networkPolicyStrict);a.networkPolicyStrict&&d("networkPolicyStrict",3);const f=dt()?yt(_t(n?.readBoundary,s?.readBoundary)??"system",o?.readBoundary):_t(n?.readBoundary,o?.readBoundary,s?.readBoundary)??"system",g=_t(n?.additionalReadPaths,o?.additionalReadPaths),w=!1===s?.allowUserOverrideReadPaths?mt(s.additionalReadPaths):mt(g,s?.additionalReadPaths),y="workspace"===f?w:void 0,v=mt(n?.additionalReadonlyPaths,o?.additionalReadonlyPaths,s?.additionalReadonlyPaths,a.additionalReadonlyPaths),b=v.length>0?v:void 0;let S=bt(n?.networkPolicy,o?.networkPolicy,s?.networkPolicy,a.networkPolicy);const k=s?.networkPolicy?.allow;void 0!==k&&k.length>0&&void 0!==S&&(S={...S,allow:[...k]},r&&(c["networkPolicy.allow"]="teamAdmin (replace)"));const _=void 0!==(C=S)?C:{version:1,default:"deny"};var C;const E=_t(n?.debugOutputDir,o?.debugOutputDir,s?.debugOutputDir),x=pt(n?.captureDenies,o?.captureDenies,s?.captureDenies),P=_t(n?.enableSharedBuildCache,o?.enableSharedBuildCache,s?.enableSharedBuildCache),R=_t(n?.privateTmp,o?.privateTmp,s?.privateTmp),I=kt(n?.ignoreMapping,o?.ignoreMapping,s?.ignoreMapping,a.ignoreMapping),T=$e(t?.gitDirParent??i);return{disableTmpWrite:h||void 0,networkPolicyStrict:p,readBoundary:f,additionalReadPaths:y,additionalReadonlyPaths:b,networkPolicy:_,debugOutputDir:E,captureDenies:x||void 0,enableSharedBuildCache:P,privateTmp:R,ignoreMapping:I,writeProtectionMapping:kt(n?.writeProtectionMapping,o?.writeProtectionMapping,s?.writeProtectionMapping,a.writeProtectionMapping,T),fieldSources:c}}function jt(e,t){const r={...e,type:t};for(const[e,t]of Object.entries(r))void 0===t&&Reflect.deleteProperty(r,e);return r}function Ut(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,s=t?.debug,i=Lt(e,t),a=mt(r?.additionalReadwritePaths,n?.additionalReadwritePaths,o?.additionalReadwritePaths),c={policy:jt({type:"workspace_readwrite",disableTmpWrite:i.disableTmpWrite,networkPolicyStrict:i.networkPolicyStrict,readBoundary:i.readBoundary,additionalReadPaths:i.additionalReadPaths,additionalReadwritePaths:a.length>0?a:void 0,additionalReadonlyPaths:i.additionalReadonlyPaths,networkPolicy:i.networkPolicy,debugOutputDir:i.debugOutputDir,captureDenies:i.captureDenies,enableSharedBuildCache:i.enableSharedBuildCache,privateTmp:i.privateTmp,ignoreMapping:i.ignoreMapping,writeProtectionMapping:i.writeProtectionMapping},"workspace_readwrite")};return s&&(c.debug={fieldSources:i.fieldSources}),c}var Bt=r("../utils/dist/workload-spawn.js"),Wt=r("../context/dist/logger.js"),Ht=r("../context/dist/core.js"),qt=r("../utils/dist/command-glob.js");const zt=n.execFile,Gt=new WeakMap;function Vt(e,t,r){return e===t?"related":r?.has(e)?"probably_unrelated":"maybe_related"}const Kt="darwin"===process.platform,Jt="linux"===process.platform,Zt=(0,Wt.h)("shell-exec:sandbox");function Xt(e){const t=ce();return e&&0!==e.length?e.includes(t)?e:[...e,t]:[t]}let Qt,Yt=!0,er=!1;function tr(){return Qt}function rr(e){"linux"===process.platform&&Object.assign(e,I(e))}let nr=null,or=null,sr=null,ir=null,ar=!1,cr=null;function lr(e){return{...e,additionalReadonlyPaths:Xt(e.additionalReadonlyPaths)}}class ur extends Error{}function dr(e){return e instanceof Error&&"code"in e&&"string"==typeof e.code?e.code:"unknown"}function hr(e,t,r){let n;e.ignoreMapping&&(n=function(e){return vr(e)}(e.ignoreMapping));const o=function(e,t,r){const n=e&&e.length>0?function(...e){const t={};for(const r of e){let e=!1;try{e=(0,g.existsSync)(r)&&(0,g.statSync)(r).isDirectory()}catch{}if(e)t[r]||(t[r]=[]),t[r].push("**");else{const e=r.lastIndexOf("/"),n=e>0?r.slice(0,e):"/",o=e>=0?r.slice(e+1):r;t[n]||(t[n]=[]),o?t[n].push(o,`${o}/**`):t[n].push("**")}}return t}(...e):{},o=!Jt||yr(r),s={...n};for(const[e,r]of Object.entries(t??{})){const t=e.startsWith("file://")?br(e):e;(o||yr(t))&&(s[e]=St(s[e],r))}if(0!==Object.keys(s).length)return vr(s)}(e.additionalReadonlyPaths,e.writeProtectionMapping,t),s=(i=e.readBoundary,r?.workspaceReadEnabled??function(){const e=Yt;return"function"==typeof e?e():e}()?i??"system":"system");var i;const a=function(e=process.platform){const t=[],r=new Set,n={};try{n.ripgrep=T()}catch{}for(const o of Ie(e,q.homedir(),n))r.has(o)||(r.add(o),t.push(o));return t}(),c=[t,..."workspace_readwrite"===e.type&&e.additionalReadwritePaths||[],Z(t)].filter((e=>void 0!==e)),l="workspace"===s?(e.additionalReadPaths??[]).flatMap((e=>function(e,t){let r=e.trim();(r.startsWith("~/")||r.startsWith("~\\"))&&(r=m.join(q.homedir(),r.slice(2)));const n=e=>e.includes("*")||e.includes("?"),o=/[/\\]\*\*?$/;if(o.test(r)&&n(m.basename(r.replace(/(?:[/\\]\*\*?)+$/,""))))return Zt.warn((0,Ht.q6)(),"[additionalReadPathGrants] a Read Allowlist file-name glob followed by /* or /** grants nothing"),[];const s=m.basename(r);if(o.test(r)||!n(s))return function(e){const t=[],r=new Set;for(const n of e){let e=n.trim();if(!e)continue;"~"===e?e=q.homedir():(e.startsWith("~/")||e.startsWith("~\\"))&&(e=m.join(q.homedir(),e.slice(2))),e=e.replace(/\/\*\*$/,"").replace(/\/\*$/,""),e=e.replace(/\\\*\*$/,"").replace(/\\\*$/,"");const o=m.basename(e);if((o.includes("*")||o.includes("?"))&&(e=m.dirname(e)),!e||"."===e)continue;const s=m.normalize(e);r.has(s)||(r.add(s),t.push(s))}return t}([e]);const i=m.dirname(r);return m.isAbsolute(i)?function(e,t,r){const n=(0,qt.b)(t),o=[];let s;try{const t=(0,g.realpathSync)(e);if(r.filter((e=>g.existsSync(e))).map((e=>(0,g.realpathSync)(e))).some((e=>(0,tt.BJ)(t,e))))return[];s=g.opendirSync(t);for(let e=1;;e++){const r=s.readSync();if(null===r)return o;if(e>1e4)throw new ur("its folder has more than 10000 entries");if(!n(r.name))continue;const i=m.join(t,r.name);try{if(!g.lstatSync(i).isFile()||m.dirname((0,g.realpathSync)(i))!==t)continue}catch(e){Zt.info((0,Ht.q6)(),`[fileNameGlobMatches] skips a matching file: error ${dr(e)}`);continue}if(256===o.length)throw new ur("more than 256 files match");o.push(i)}}catch(e){const t=e instanceof ur?e.message:`error ${dr(e)}`;return Zt.warn((0,Ht.q6)(),`[fileNameGlobMatches] a Read Allowlist file-name glob grants nothing: ${t}`),[]}finally{s?.closeSync()}}(i,s,t):[]}(e,c))):[],u=[...a],d=new Set(a);for(const e of l)d.has(e)||(d.add(e),u.push(e));const h={cwd:t,readBoundary:s,hardcodedReadPaths:u,additionalReadonlyPaths:o,networkAccess:Xe(e.networkPolicy),ignoreMapping:n};return"workspace_readonly"===e.type?{type:e.type,...h}:{type:e.type,...h,additionalReadwritePaths:e.additionalReadwritePaths||[],disableTmpWrite:e.disableTmpWrite||!1}}function pr(e){const t={sandbox:e};return Jt&&function(){const e=er;return"function"==typeof e?e():e}()&&(t.kernelMountBudget=!0),t}function fr(e){if(null!==nr)return nr;try{const t=tr();return Zt.info(e,`[checkBinaryAvailable] Resolved binary path: ${t}`),t?(nr=g.existsSync(t),nr?Zt.info(e,`[checkBinaryAvailable] Binary path exists: ${String(nr)}`):(or=new Error(`Sandbox binary not found at ${t}`),Zt.info(e,`[checkBinaryAvailable] Binary not found at: ${t}`)),nr):(or=new Error("Sandbox binary path was not configured"),nr=!1,Zt.info(e,"[checkBinaryAvailable] Binary path not set, returning false"),!1)}catch(t){return or=t instanceof Error?t:new Error(String(t)),nr=!1,Zt.info(e,`[checkBinaryAvailable] Exception checking binary: ${String(t)}`),!1}}function mr(e){if(null!==ir)return ir;const t=e??(0,Ht.q6)();if(Zt.info(t,"[isSandboxHelperSupported] Starting sandbox support check..."),!fr(t)){const e=or?.message||"Binary check failed";return sr=e,Zt.info(t,`[isSandboxHelperSupported] Binary not available, returning false. Reason: ${e}`),ir=!1,ir}if("win32"===process.platform)return sr="Windows sandbox helper only provides network proxy, not filesystem isolation",Zt.info(t,"[isSandboxHelperSupported] win32: returning false (proxy-only, no filesystem sandbox)"),ir=!1,ir;if("darwin"===process.platform)return sr=null,Zt.info(t,`[isSandboxHelperSupported] ${process.platform} platform, binary available, sandbox supported!`),ir=!0,ir;const{binaryPath:r,args:o,env:s}=function(e,t){const r=pr(hr(lr({type:"workspace_readwrite"}),t)),n=String(tr());Zt.info(e,`[sandboxPreflight] Running preflight with binary: ${n}`),Zt.info(e,`[sandboxPreflight] CWD: ${t}`);const o={...process.env};return rr(o),{binaryPath:n,args:["--policy",le(JSON.stringify(r)),"--preflight-only","--","/bin/true"],env:o}}(t,process.cwd());try{const e=Date.now();(0,Bt.D9)(n.execFileSync,r,o,{stdio:["ignore","ignore","pipe"],timeout:gr,env:s,shell:!1});const i=Date.now()-e;return sr=null,Zt.info(t,`[isSandboxHelperSupported] Preflight succeeded in ${i}ms, sandbox supported!`),ir=!0,ir}catch(e){return function(e,t){const{message:r,status:n,stderrText:o}=t;return Zt.error(e,`[sandboxPreflight] Preflight failed: ${r}`),Zt.error(e,`[sandboxPreflight] Exit status: ${n}`),o&&Zt.error(e,`[sandboxPreflight] Stderr: ${o}`),sr=2===n?`Linux preflight failed with exit code 2 (unsupported kernel features). stderr: ${o||"none"}`:`Linux preflight failed: ${r||"unknown error"}. Exit status: ${n}. stderr: ${o||"none"}`,ir=!1,!1}(t,function(e){if("object"!=typeof e||null===e)return{stderrText:""};const t="message"in e&&"string"==typeof e.message?e.message:void 0,r=!("status"in e)||"number"!=typeof e.status&&null!==e.status?void 0:e.status,n="stderr"in e?e.stderr:void 0;return{message:t,status:r,stderrText:Buffer.isBuffer(n)||"string"==typeof n?n.toString():""}}(e))}}(0,G.J)((function(){ir=null,ar=!1,cr=null,sr=null,nr=null,or=null}));const gr=15e3;function wr(e,t=[],r={},o){const i=(0,Ht.q6)();if(r.env=a(s(r.env)),!fr(i))throw new Error(`Sandbox binary not available: ${or?.message||"binary not configured"}. Please build the binary or use 'insecure_none' policy.`);if("insecure_none"===o.type)return(0,Bt.D9)(n.spawn,e,t,{...r,windowsHide:!0});if("workspace_readwrite"===o.type||"workspace_readonly"===o.type)return function(e,t,r,o){if("workspace_readwrite"!==o.type&&"workspace_readonly"!==o.type)throw new Error("Expected workspace_readwrite or workspace_readonly policy");const i=String(r.cwd??process.cwd()),c=o.sandboxWorkspaceRoot??i;let u=e,d=t;r.shell&&("win32"===process.platform?(u="string"==typeof r.shell?r.shell:"cmd.exe",d=["/c",`${e} ${t.join(" ")}`]):(u="string"==typeof r.shell?r.shell:"/bin/sh",d=["-c",`${e} ${t.join(" ")}`]));const h=function({workspaceRoot:e,executionCwd:t}){const r=m.resolve(e),n=m.resolve(t),o=Sr(r);if(n===r||n===o)return;const s=e=>(0,tt.ZU)({basePath:o,targetPath:e})?m.join(r,m.relative(o,e)):void 0,i=(0,tt.ZU)({basePath:r,targetPath:n})?n:s(n)??n;return{directory:i,fallbackDirectory:s(Sr(n))??i}}({workspaceRoot:c,executionCwd:i});"win32"!==process.platform&&void 0!==h&&({command:u,args:d}=(0,oe.kO)(u,d,h));const p=hr(lr(o),c),f=(0,Ht.q6)();!function({log:e,dirs:t=ve(q.homedir(),q.tmpdir(),pe),createOnly:r=[we(process.env,pe)].filter((e=>void 0!==e)),policyDir:n=ie(),uid:o=process.getuid?.()??-1}){const s=m.join(n,"node-compile-cache-removed-1"),{record:i,problem:a}=function(e){const t=e=>({record:{cleaned:[],kept:{},failed:{}},problem:e});let r,n;try{r=g.readFileSync(e,"utf8")}catch(e){const r=ke(e);return t("ENOENT"===r?void 0:r)}try{n=JSON.parse(r)}catch(e){return t(e instanceof SyntaxError?"not JSON":ke(e))}if("object"!=typeof n||null===n)return t("not a record");const o="cleaned"in n?n.cleaned:void 0;return{record:{cleaned:Array.isArray(o)?o.filter((e=>"string"==typeof e)):[],kept:Se("kept"in n?n.kept:void 0),failed:Se("failed"in n?n.failed:void 0)}}}(s);void 0!==a&&e(`node compile cache: starting a new cleanup record (${a})`);const c=new Set(i.cleaned),l=new Set(t);let u=!1;for(const n of[...t,...r.filter((e=>!l.has(e)))])try{const t=g.lstatSync(n,{throwIfNoEntry:!1});if(void 0!==t){const r=be(t,o);if(void 0!==r){i.kept[n]!==r&&(e(`node compile cache: kept ${n} (${r})`),i.kept[n]=r,u=!0);continue}l.has(n)&&!c.has(n)&&(g.rmSync(n,{recursive:!0,force:!0}),e(`node compile cache: removed ${n}`))}g.mkdirSync(n,{recursive:!0,mode:448}),l.has(n)&&!c.has(n)&&(c.add(n),u=!0),void 0===i.kept[n]&&void 0===i.failed[n]||(delete i.kept[n],delete i.failed[n],u=!0)}catch(t){const r=ke(t);i.failed[n]!==r&&(e(`node compile cache: could not prepare ${n} (${r})`),i.failed[n]=r,u=!0)}u&&function(e,t){const r=`${e}.${process.pid}.tmp`;try{g.writeFileSync(r,`${JSON.stringify(t)}\n`,{mode:384}),g.renameSync(r,e)}catch{g.rmSync(r,{force:!0})}}(s,{...i,cleaned:[...c]})}({log:e=>Zt.info(f,e)});const w=function(e){if(!("workspace"!==e.readBoundary||"workspace_readwrite"===e.type&&e.disableTmpWrite||"win32"===process.platform))return X(e.cwd,{create:!0})}(p);let y;w&&(p.additionalReadwritePaths=[...p.additionalReadwritePaths??[],w],Jt&&!0===o.privateTmp&&(y=te(w).TMPDIR));const v=function(e){if("insecure_none"===e.type)return;const t=e.networkPolicy;if(void 0===t)return;if(!Xe(t))return;const r=void 0!==t.deny&&t.deny.length>0;return"allow"!==t.default||r?{version:1,...t}:void 0}(o),b=pr(p);void 0!==y&&(b.mapTmpTo=y),void 0!==v&&(b.networkPolicy=v),!1===o.networkPolicyStrict&&(b.networkPolicyStrict=!1);const S=["--policy",le(JSON.stringify(b)),"--",u,...d],k=s(process.env),_={..."linux"===process.platform?l(k):k,..."linux"===process.platform&&r.env?l(r.env):r.env,CURSOR_SANDBOX:"native"};rr(_);const C=new Set(Y);if(w){const e=function(e,t,r){const n=te(e);if(r){const r=re();for(const[o,s]of Object.entries(re(e)))t[o]===r[o]&&(n[o]=s)}return n}(w,_,o.enableSharedBuildCache);Object.assign(_,e);for(const t of Object.keys(e))C.add(t);_.__CURSOR_SANDBOX_TEMP_RESTORE=Object.entries(e).map((([e,t])=>`builtin export ${e}='${t.replace(/'/g,"'\\''")}'`)).join("; ")}_.__CURSOR_SANDBOX_OWNED_ENV=[...C].join(" ");const E={cwd:void 0!==y?p.cwd:r.cwd||i,env:a(_),stdio:r.stdio||["pipe","pipe","pipe"],detached:r.detached,windowsHide:!0};try{const e=new Date,t=(0,Bt.D9)(n.spawn,String(tr()),S,E);return Kt&&t.pid&&function(e,t){Gt.set(e,t)}(t,{startTime:e,pid:t.pid}),t}catch(e){throw new Error(`Failed to spawn sandboxed process: ${String(e)}`)}}(e,t,r,o);throw new Error(`Unsupported sandbox policy: ${String(o)}`)}function yr(e,t=e=>g.existsSync(e)){if((0,oe.$f)(e))return!0;let r=m.resolve(e);for(;;){try{if(t(m.join(r,".git")))return!0}catch{}const e=m.dirname(r);if(e===r)return!1;r=e}}function vr(e,t,r,n){const o={};for(const[t,r]of Object.entries(e)){const e=t.startsWith("file://")?br(t):t;o[e]=St(o[e],r);const n=Sr(e);n!==e&&(o[n]=St(o[n],r))}return o}function br(e){let t=e.replace(/^file:\/\//,"");return t=decodeURIComponent(t),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t}function Sr(e,t){if((0,oe.$f)(e))return e;try{return(t??g.realpathSync)(e)}catch{return e}}function kr(){return sr}class _r extends Error{reason;constructor(e,t){super(e),this.reason=t,this.name="SandboxUnsupportedError"}}const Cr="darwin"===process.platform;function Er(e){!function(e){T();const{sandboxBinaryPath:t,workspaceReadEnabled:r,kernelMountBudget:n}=e;Qt||(Qt=t),void 0!==r&&(Yt=r),void 0!==n&&(er=n)}(e)}function xr(e,t=[],r={},o){if(r.env=s(r.env),o.enableSharedBuildCache&&(r={...r,env:{...s(process.env),...re(),...r.env}}),"insecure_none"!==o.type){if(mr())return wr(e,t,r,o);const n=kr();throw new _r(`Sandbox policy '${o.type}' is not supported on this system. Ensure the sandbox helper binary is available, or use 'insecure_none'. Reason: ${n||"unknown"}`,n??void 0)}return function(e,t,r,o={spawn:n.spawn,spawnWorkload:Bt.D9}){return o.spawnWorkload(o.spawn,e,t,{...r,env:a(r.env??process.env),windowsHide:!0})}(e,t,r)}function Pr(e){return Cr?async function(e){const t=Gt.get(e);return t?(r=t.pid,n=t.startTime,o=t.unrelatedPids,new Promise((e=>{try{const t=new Date,s=["show","--style","ndjson","--predicate",'process=="kernel" AND eventMessage CONTAINS "Sandbox:" AND eventMessage contains "deny"',"--last",Math.ceil((t.getTime()-n.getTime())/1e3).toString()];(0,Bt.D9)(zt,"/usr/bin/log",s,((t,n)=>{if(t)return void e([{raw:t.message}]);const s=n.split(/\r?\n/).filter((e=>e.trim().length>0)),i=[];for(const e of s)try{const t=JSON.parse(e),n=t?.eventMessage??"";if(!n||"string"!=typeof n)continue;const s=/^Sandbox:\s+([^(]+)\((\d+)\)\s+([a-zA-Z-]+)\((\d+)\)\s+([^\s]+)\s+(.+)$/.exec(n);if(s){const[,e,a,c,l,u,d]=s,h=Number(a);i.push({timestamp:t.timestamp,processName:e.trim(),pid:h,decision:c.toLowerCase(),decisionCode:Number(l),operation:u,target:d,duplicateCount:1,raw:n,relationship:Vt(h,r,o)});continue}const a=/^(\d+) duplicate report for Sandbox: (.+)$/.exec(n);if(a){const e=Number(a[1]),s=a[2],c=/^([^(]+)\((\d+)\)\s+([a-zA-Z-]+)\((\d+)\)\s+([^\s]+)\s+(.+)$/.exec(s);if(c){const[,s,a,l,u,d,h]=c,p=Number(a);i.push({timestamp:t.timestamp,processName:s.trim(),pid:p,decision:l.toLowerCase(),decisionCode:Number(u),operation:d,target:h,duplicateCount:e,raw:n,relationship:Vt(p,r,o)})}else i.push({timestamp:t.timestamp,duplicateCount:e,raw:n});continue}i.push({timestamp:t.timestamp,raw:n})}catch{}e(i)}))}catch(t){e([{raw:String(t)}])}}))):(console.log("No sandbox metadata found on child process"),[]);var r,n,o}(e):Promise.resolve([])}function Rr(e,t){if(Cr)try{(0,g.accessSync)("/usr/bin/sandbox-exec",g.constants.X_OK)}catch{return!1}return mr(t?.ctx)}var Ir=r("node:stream"),Tr=r("../context/dist/otel.js"),Ar=r("../utils/dist/writable-iterable.js");const $r="--",Mr='builtin eval "$1" 3<&- 4>&-';var Dr=r("node:string_decoder");const Or=50,Fr=262144;class Nr{writable;pending=[];pendingBytes=0;flushTimeout;flushPromise;flushIntervalMs;maxBufferedBytes;constructor(e,t){this.writable=e,this.flushIntervalMs=t?.flushIntervalMs??Or,this.maxBufferedBytes=t?.maxBufferedBytes??Fr}async push(e,t){0!==t.length&&(this.pending.push({type:e,data:t}),this.pendingBytes+=t.length,this.pendingBytes>=this.maxBufferedBytes?await this.flush():this.scheduleFlush())}async flush(){if(this.clearFlushTimeout(),this.flushPromise)return await this.flushPromise,void(this.pendingBytes>0&&await this.flush());if(0===this.pendingBytes)return;const e=this.pending;this.pending=[],this.pendingBytes=0,this.flushPromise=this.writeBufferedOutput(e);try{await this.flushPromise}finally{this.flushPromise=void 0}}async close(){await this.flush()}scheduleFlush(){void 0===this.flushTimeout&&(this.flushTimeout=setTimeout((()=>{this.flushTimeout=void 0,this.flush()}),this.flushIntervalMs))}clearFlushTimeout(){void 0!==this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=void 0)}async writeBufferedOutput(e){for(const t of function(e){if(0===e.length)return[];const t=[];let r=e[0].type,n=[e[0].data];for(let o=1;o{e.writable.write({type:t,data:r}).catch((()=>{}))};return e.stdout?.on("data",(e=>{const n=t.note(e);void 0!==n&&n.length>0&&r("stdout",n)})),e.stderr?.on("data",(e=>{r("stderr",e)})),{get stdoutBytes(){return t.bytes},get stdoutPrefix(){return t.stdoutPrefix},async waitForOutput(){},async releaseHeldStdout(){const e=t.takeHeld();void 0!==e&&e.length>0&&r("stdout",e)},dropHeldStdout(){t.takeHeld()},async flush(){await this.releaseHeldStdout()}}}const r=new Nr(e.writable,e.outputLimiterOptions);let n;const o=Promise.all([jr(e.stdout,r,t),Ur(e.stderr,"stderr",r)]).then((()=>{})).catch((e=>{n=e}));return{get stdoutBytes(){return t.bytes},get stdoutPrefix(){return t.stdoutPrefix},async waitForOutput(){if(await o,void 0!==n)throw(e=n)instanceof Error?e:new Error(String(e));var e},async releaseHeldStdout(){const e=t.takeHeld();void 0!==e&&e.length>0&&await r.push("stdout",e)},dropHeldStdout(){t.takeHeld()},async flush(){await this.releaseHeldStdout(),await r.flush()}}}async function jr(e,t,r){if(e)for await(const n of e){const e=r.note(n);void 0!==e&&e.length>0&&await t.push("stdout",e)}}async function Ur(e,t,r,n){if(e)for await(const o of e)n?.(o),await r.push(t,o)}var Br;!function(e){e.Zsh="zsh",e.ZshLight="zsh-light",e.Bash="bash",e.PowerShell="powershell",e.Naive="naive"}(Br||(Br={}));const Wr={TERM:"dumb",NO_COLOR:"1",FORCE_COLOR:"0",_ZO_DOCTOR:"0"};function Hr(e){return"win32"===e.platform?"windows_tree":e.detached?"process_group":"single_process"}function qr(e,t,r,o={spawn:n.spawn,killPid:process.kill.bind(process)}){const s=e.pid;if(void 0===s)return;const i=()=>{try{e.kill(r)}catch{}};switch(t){case"process_group":try{o.killPid(-s,r)}catch{i()}return;case"windows_tree":try{o.spawn("taskkill",["/pid",String(s),"/t","/f"],{stdio:"ignore",windowsHide:!0}).on("error",i)}catch{i()}return;case"single_process":return void i();default:throw new Error(`Unknown process tree kill mode: ${String(t)}`)}}function zr(e,t=[],r={},n,o){const s=xr(e,t,{...r,env:I(r.env??process.env)},n);return o?Vr(s,{detached:!0===r.detached},o):Gr(s,!0===r.detached),s}function Gr(e,t){"single_process"!==Hr({platform:process.platform,detached:t})&&e.pid}function Vr(e,t,r){const n=Hr({platform:process.platform,detached:t.detached});Gr(e,t.detached);const o=()=>{if(!e.pid)return;qr(e,n,"SIGTERM");const t=setTimeout((()=>{!e.killed&&e.pid&&qr(e,n,"SIGKILL")}),1e3);"process_group"!==n&&e.once("exit",(()=>{clearTimeout(t)}))};r.aborted?o():(r.addEventListener("abort",o,{once:!0}),e.once("exit",(()=>{r.removeEventListener("abort",o)})))}function Kr(e,t,r){if(e){try{process.kill(-e,t)}catch{return}"SIGTERM"===t&&void 0!==r&&r>0&&setTimeout((()=>{try{process.kill(-e,"SIGKILL")}catch{}}),r)}}const Jr=new Set(["SIGTERM","SIGINT","SIGHUP","SIGQUIT","SIGKILL"]);function Zr(e,t,r){null!==t&&Jr.has(t)&&!r&&"win32"!==process.platform&&Kr(e,t)}function Xr(e,{shellName:t,closeGraceMs:r,timeoutMs:n}){const o=r??5e3,s=n??6e4;return new Promise((r=>{const n=[];let i;const a=e=>{n.push(e)},c=()=>{clearTimeout(d),o<=0||(i=setTimeout((()=>{console.warn(`[shell-exec] ${t} state init exited but its stdio did not close within ${o}ms; a startup file left a background process holding the output pipe. Proceeding with the dump received so far.`),u("exit_without_close")}),o))},l=()=>{u("closed")},u=t=>{clearTimeout(d),clearTimeout(i),e.off("exit",c),e.off("close",l),e.stdout?.off("data",a),e.stdout?.resume(),r({outcome:t,stdout:Buffer.concat(n).toString("utf8")})},d=s>0?setTimeout((()=>{console.warn(`[shell-exec] ${t} state init did not exit within ${s}ms; a startup file is blocking. Killing it and falling back to an empty state.`),qr(e,Hr({platform:process.platform,detached:!0}),"SIGKILL"),u("timed_out")}),s):void 0;e.stdout?.on("data",a),Qr(e.stdout),e.on("exit",c),e.on("close",l)}))}function Qr(e){e?.on("error",(()=>{}))}function Yr(e){e.removeAllListeners(),e.on("error",(()=>{})),e.stdout?.removeAllListeners("close"),e.stderr?.removeAllListeners("close");for(const t of e.stdio.slice(3))t?.destroy()}const en="IFS= builtin read -r -d '' __cursor_command <&5 2>/dev/null || { builtin printf '%s\\n' 'The command did not run: a shell startup file ($BASH_ENV or .zshenv) closed or replaced file descriptor 5, which carries the command. Run it again; this shell now passes commands as arguments.' >&2; builtin exit 126; }; exec 5<&-; builtin set -- \"$__cursor_command\"; builtin unset __cursor_command; ";function tn(e,t){return 126===e&&""===t}function rn(){return"win32"!==process.platform}function nn(e,t){const r=e.stdio.at(5);r instanceof Ir.default.Writable&&(Qr(r),r.end(`${t}\0`))}function on(e,t){e&&(Qr(e),e.write(t),e.end())}function sn(e,t){if(!e)return;Qr(e);const r=new Dr.StringDecoder("utf8");e.on("data",(e=>{const n=r.write(e);""!==n&&t(n)})),e.on("end",(()=>{const e=r.end();""!==e&&t(e)}))}function an(e){const t=e.indexOf("\n");return{cwd:Buffer.from(e.substring(0,t),"utf16le").toString("utf16le"),rest:e.substring(t)}}function cn(e,t){const r=t instanceof Error&&"code"in t&&"string"==typeof t.code?t.code:"unknown";console.warn(e,r)}function ln(e,t){const r=`${t}\n`,n=e.indexOf(r);return n>=0?e.slice(n+r.length):e}function un(e){return!1===e?.isLoginShellEnabled?"-ic":"-ilc"}function dn(e,t,r){const n=`${t}\n`;if(!e.startsWith(n))return;const o=e.indexOf(`\n${r}\n`,n.length-1);return o<0?void 0:e.slice(n.length,o+1)}const hn="__CURSOR_BASH_STATE_START__",pn="__CURSOR_BASH_STATE_END__",fn="\n Emit $PWD.Path\n #Log-Timing \"working_dir\"\n\n function ShouldPersistEnvVar {\n param([string]$Name)\n if ($Name -eq 'CURSOR_CONVERSATION_ID') {\n return $false\n }\n if ($Name -eq 'CURSOR_REQUEST_ID') {\n return $false\n }\n if ($Name -like 'CURSOR_AGENT_STORE*') {\n return $false\n }\n if ($Name -like '*CURSOR_SANDBOX*') {\n return $false\n }\n if ($Name -eq 'ELECTRON_RUN_AS_NODE') {\n return $false\n }\n return $true\n }\n\n $envVars = Get-ChildItem Env: | Sort-Object Name\n foreach ($var in $envVars) {\n if (-not (ShouldPersistEnvVar -Name $var.Name)) {\n continue\n }\n $encoded = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes([string]$var.Value))\n Emit ('Set-Item -LiteralPath ''Env:{0}'' -Value ([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String(''{1}'')))' -f $var.Name, $encoded)\n }\n #Log-Timing \"environment\"\n\n $aliases = Get-Alias | Sort-Object Name\n foreach ($alias in $aliases) {\n $definition = $alias.Definition\n\n if ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::ReadOnly) {\n }\n elseif ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::Constant) {\n }\n elseif ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::AllScope) {\n }\n else {\n Emit ('Set-Alias -Name \"{0}\" -Value \"{1}\"' -f $alias.Name, $definition)\n }\n }\n\n #Log-Timing \"finalize\"\n",mn=`\nfunction Dump-PowerShellState {\n param(\n [Parameter(Mandatory = $true)]\n [string]$OutputFile\n )\n\n function Emit {\n param([string]$Content)\n Add-Content -Path $OutputFile -Value $Content -Encoding UTF8\n }\n\n if (Test-Path $OutputFile) {\n Remove-Item $OutputFile -Force\n }\n New-Item -Path $OutputFile -ItemType File -Force | Out-Null\n #Log-Timing "file_init"\n${fn}}\n`,gn=`\nfunction Dump-PowerShellState {\n param(\n [Parameter(Mandatory = $true)]\n [string]$OutputFile,\n [string]$Trailer\n )\n\n $__cursorDumpText = New-Object System.Text.StringBuilder\n $__cursorDumpNewLine = [Environment]::NewLine\n function Emit {\n param([string]$Content)\n [void]$__cursorDumpText.Append($Content).Append($__cursorDumpNewLine)\n }\n${fn}\n if ($Trailer) {\n Emit $Trailer\n }\n [System.IO.File]::WriteAllText($OutputFile, $__cursorDumpText.ToString(), (New-Object System.Text.UTF8Encoding ($PSVersionTable.PSVersion.Major -lt 6)))\n}\n`,wn="# cursor-shell-timings ",yn="[long](([DateTime]::UtcNow.Ticks - 621355968000000000) / 10000)",vn="\ntry { [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\ntry { [Console]::InputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\ntry { $global:OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\n",bn=e=>e.map((e=>`'${e}'`)).join(", "),Sn=` # The body of the proxy for Set-Content and Export-Csv. Its param block comes from the\n # cmdlet itself. Every step of its own is guarded, so a failure in the proxy leaves the\n # file as the cmdlet writes it.\n $__cursorProxyBody = @'\nbegin {\n # The file system paths the call writes, each with its own 'bom' or 'nobom', and what each\n # held before the call; the call gets -Encoding only when every path has a decision.\n $__cursorFiles = $null\n $__cursorDecisions = @{}\n $__cursorBefore = @{}\n $__cursorDecided = $false\n # The command line asked for UTF8 by name, for files whose readers take it without a BOM.\n $__cursorAsked = $false\n $__cursorStrip = $false\n $__cursorStopped = $false\n $__cursorScopeBound = $null\n $__cursorInvoked = "$($MyInvocation.InvocationName)"\n # The first 8 KiB of the file and its length; $null for a file that does not exist.\n $__cursorHeadOf = {\n param([string]$__cursorFile)\n if (-not [System.IO.File]::Exists($__cursorFile)) { return $null }\n $__cursorHead = New-Object byte[] 8192\n $__cursorCount = 0\n $__cursorStream = [System.IO.File]::Open($__cursorFile, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite -bor [System.IO.FileShare]::Delete)\n try {\n $__cursorLength = $__cursorStream.Length\n while ($__cursorCount -lt $__cursorHead.Length) {\n $__cursorRead = $__cursorStream.Read($__cursorHead, $__cursorCount, $__cursorHead.Length - $__cursorCount)\n if ($__cursorRead -le 0) { break }\n $__cursorCount += $__cursorRead\n }\n } finally { $__cursorStream.Dispose() }\n return @{ Length = $__cursorLength; Head = $__cursorHead; Count = $__cursorCount }\n }\n # 'bom' or 'nobom' for a file the proxy writes in UTF-8, $null for one it leaves to the\n # cmdlet: the file's own bytes decide when it has content, its extension otherwise.\n $__cursorEncodingOf = {\n param([string]$__cursorFile, $__cursorWas)\n $__cursorExtension = [System.IO.Path]::GetExtension($__cursorFile).ToLowerInvariant()\n if ($__cursorExtension -in @(${bn([".bat",".cmd",".reg",".ini",".inf",".vbs",".vbe",".wsf"])})) { return $null }\n if ([System.IO.Directory]::Exists($__cursorFile)) { return $null }\n if ($null -ne $__cursorWas -and $__cursorWas.Count -gt 0) {\n $__cursorHead = $__cursorWas.Head\n $__cursorEnd = $__cursorWas.Count\n if ($__cursorEnd -ge 3 -and $__cursorHead[0] -eq 0xEF -and $__cursorHead[1] -eq 0xBB -and $__cursorHead[2] -eq 0xBF) { return 'bom' }\n if ($__cursorEnd -ge 2 -and (($__cursorHead[0] -eq 0xFF -and $__cursorHead[1] -eq 0xFE) -or ($__cursorHead[0] -eq 0xFE -and $__cursorHead[1] -eq 0xFF))) { return $null }\n if ($__cursorEnd -eq $__cursorHead.Length) {\n # A full header may end inside a character; that character is left out.\n $__cursorAt = $__cursorEnd - 1\n while ($__cursorAt -gt $__cursorEnd - 4 -and ($__cursorHead[$__cursorAt] -band 0xC0) -eq 0x80) { $__cursorAt-- }\n if ($__cursorHead[$__cursorAt] -ge 0xC0) {\n $__cursorNeed = if ($__cursorHead[$__cursorAt] -ge 0xF0) { 4 } elseif ($__cursorHead[$__cursorAt] -ge 0xE0) { 3 } else { 2 }\n if ($__cursorEnd - $__cursorAt -lt $__cursorNeed) { $__cursorEnd = $__cursorAt }\n }\n }\n # A strict decode throws on bytes that are not UTF-8; a character beyond ASCII takes\n # more bytes than code units, so all-ASCII content is the one that decodes to as many.\n try { $__cursorText = [System.Text.UTF8Encoding]::new($false, $true).GetString($__cursorHead, 0, $__cursorEnd) } catch { return $null }\n if ($__cursorText.Length -lt $__cursorEnd) { return 'nobom' }\n }\n if ($__cursorExtension -in @(${bn([".ps1",".psm1",".psd1"])})) { return 'bom' }\n if ($__cursorExtension -in @(${bn([".py",".pyw",".pyi",".js",".mjs",".cjs",".jsx",".ts",".tsx",".mts",".cts",".go",".rs",".kt",".kts",".scala",".swift",".dart",".rb",".cs",".fs",".fsx",".vb",".razor",".cshtml",".sh",".bash",".zsh",".html",".htm",".css",".scss",".sass",".less",".vue",".svelte",".json",".jsonc",".json5",".yaml",".yml",".toml",".xml",".xsd",".xsl",".xslt",".svg",".csproj",".props",".targets",".graphql",".gql",".proto",".tf",".hcl",".md",".markdown",".mdx",".rst",".adoc",".gitignore",".gitattributes",".gitmodules",".editorconfig",".cursorignore",".cursorindexingignore",".mdc"])})) { return 'nobom' }\n return $null\n }\n # Whether the -Encoding the call bound is the UTF-8 with a BOM that Windows PowerShell names\n # UTF8. PowerShell 7 binds the encoding object of that name, and reaches this only when a\n # test fakes the version.\n $__cursorIsUtf8Bom = {\n param($__cursorEncoding)\n if ($__cursorEncoding -is [System.Text.Encoding]) { return ($__cursorEncoding -is [System.Text.UTF8Encoding] -and $__cursorEncoding.GetPreamble().Length -gt 0) }\n return ("$__cursorEncoding" -eq 'UTF8')\n }\n # Whether a default under $PSDefaultParameterValues can reach this call's -Encoding: under\n # the cmdlet's name, an alias it had when the proxy was built, or the name the call used. A\n # value such a default put in $PSBoundParameters is not one the command line asked for.\n $__cursorHasEncodingDefault = {\n param([string]$__cursorInvoked)\n foreach ($__cursorKey in @($PSDefaultParameterValues.Keys)) {\n $__cursorKeyParts = "$__cursorKey" -split ':', 2\n if ($__cursorKeyParts.Count -ne 2 -or 'Encoding' -notlike $__cursorKeyParts[1].Trim()) { continue }\n foreach ($__cursorName in @(__CURSORNAMES__, $__cursorInvoked)) {\n if ($__cursorName -like $__cursorKeyParts[0].Trim()) { return $true }\n }\n }\n return $false\n }\n # Whether a UTF8 asked for by name is UTF-8 without a BOM for this file: one whose reader\n # rejects a BOM, and that is new, empty or starts with no BOM of any encoding.\n $__cursorTakesNoBom = {\n param([string]$__cursorFile, $__cursorWas)\n if ([System.IO.Directory]::Exists($__cursorFile)) { return $false }\n if ([System.IO.Path]::GetExtension($__cursorFile).ToLowerInvariant() -notin @(${bn([".json",".py",".js",".ts",".sh",".yaml",".toml",".mdc"])}) -and\n [System.IO.Path]::GetFileName($__cursorFile).ToLowerInvariant() -notin @(${bn([".gitignore",".editorconfig"])})) { return $false }\n if ($null -eq $__cursorWas -or $__cursorWas.Count -lt 2) { return $true }\n $__cursorHead = $__cursorWas.Head\n if ($__cursorWas.Count -ge 3 -and $__cursorHead[0] -eq 0xEF -and $__cursorHead[1] -eq 0xBB -and $__cursorHead[2] -eq 0xBF) { return $false }\n if (($__cursorHead[0] -eq 0xFF -and $__cursorHead[1] -eq 0xFE) -or ($__cursorHead[0] -eq 0xFE -and $__cursorHead[1] -eq 0xFF)) { return $false }\n if ($__cursorWas.Count -ge 4 -and $__cursorHead[0] -eq 0 -and $__cursorHead[1] -eq 0 -and $__cursorHead[2] -eq 0xFE -and $__cursorHead[3] -eq 0xFF) { return $false }\n return $true\n }\n # Takes a UTF-8 BOM off the front of the file in place, unless it is to stay and the\n # content has a character beyond ASCII. A file the cmdlet left as it was is not touched.\n $__cursorStripBom = {\n param([string]$__cursorFile, [bool]$__cursorKeepUnlessAscii, $__cursorWas)\n if (-not [System.IO.File]::Exists($__cursorFile)) { return }\n $__cursorStream = $null\n # The cmdlet may still hold the file for a moment after it returns.\n for ($__cursorAttempt = 0; $__cursorAttempt -lt 5 -and $null -eq $__cursorStream; $__cursorAttempt++) {\n try { $__cursorStream = [System.IO.File]::Open($__cursorFile, [System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None) }\n catch [System.IO.FileNotFoundException] { return }\n catch [System.IO.DirectoryNotFoundException] { return }\n catch [System.IO.IOException] { Start-Sleep -Milliseconds 20 }\n catch { return }\n }\n if ($null -eq $__cursorStream) { return }\n try {\n $__cursorBuffer = New-Object byte[] 65536\n if ($null -ne $__cursorWas -and $__cursorWas.Length -eq $__cursorStream.Length) {\n $__cursorCount = 0\n while ($__cursorCount -lt $__cursorWas.Count) {\n $__cursorRead = $__cursorStream.Read($__cursorBuffer, $__cursorCount, $__cursorWas.Count - $__cursorCount)\n if ($__cursorRead -le 0) { break }\n $__cursorCount += $__cursorRead\n }\n if ($__cursorCount -eq $__cursorWas.Count -and [System.Convert]::ToBase64String($__cursorBuffer, 0, $__cursorCount) -eq [System.Convert]::ToBase64String($__cursorWas.Head, 0, $__cursorCount)) { return }\n $__cursorStream.Position = 0\n }\n if ($__cursorStream.Read($__cursorBuffer, 0, 3) -ne 3 -or $__cursorBuffer[0] -ne 0xEF -or $__cursorBuffer[1] -ne 0xBB -or $__cursorBuffer[2] -ne 0xBF) { return }\n if ($__cursorKeepUnlessAscii) {\n while (($__cursorRead = $__cursorStream.Read($__cursorBuffer, 0, $__cursorBuffer.Length)) -gt 0) {\n if ([regex]::IsMatch([System.Text.Encoding]::UTF8.GetString($__cursorBuffer, 0, $__cursorRead), '[^\\x00-\\x7F]')) { return }\n }\n }\n $__cursorReadAt = 3L\n $__cursorWriteAt = 0L\n while ($__cursorReadAt -lt $__cursorStream.Length) {\n $__cursorStream.Position = $__cursorReadAt\n $__cursorRead = $__cursorStream.Read($__cursorBuffer, 0, $__cursorBuffer.Length)\n if ($__cursorRead -le 0) { break }\n $__cursorStream.Position = $__cursorWriteAt\n $__cursorStream.Write($__cursorBuffer, 0, $__cursorRead)\n $__cursorReadAt += $__cursorRead\n $__cursorWriteAt += $__cursorRead\n }\n $__cursorStream.SetLength($__cursorWriteAt)\n } catch { } finally { $__cursorStream.Dispose() }\n }\n try {\n $__cursorBound = $null\n if ($PSBoundParameters.ContainsKey('Path')) { $__cursorBound = @{ Path = $PSBoundParameters['Path'] } }\n elseif ($PSBoundParameters.ContainsKey('LiteralPath')) { $__cursorBound = @{ LiteralPath = $PSBoundParameters['LiteralPath'] } }\n if ($null -ne $__cursorBound) {\n # The file system paths that -Path or -LiteralPath names; none when one is on another\n # provider or a wildcard matches nothing.\n $__cursorLiteral = $__cursorBound.ContainsKey('LiteralPath')\n $__cursorFiles = New-Object System.Collections.Generic.List[string]\n foreach ($__cursorPath in @(@($__cursorBound.Values)[0])) {\n $__cursorProvider = $null\n $__cursorDrive = $null\n if ($__cursorLiteral -or -not [System.Management.Automation.WildcardPattern]::ContainsWildcardCharacters("$__cursorPath")) {\n $__cursorResolved = @($ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath("$__cursorPath", [ref]$__cursorProvider, [ref]$__cursorDrive))\n } else {\n $__cursorResolved = @($ExecutionContext.SessionState.Path.GetResolvedProviderPathFromPSPath("$__cursorPath", [ref]$__cursorProvider))\n }\n if ($null -ne $__cursorProvider -and $__cursorProvider.Name -in @('Variable', 'Function', 'Alias')) { $__cursorScopeBound = $__cursorProvider.Name }\n if ($null -eq $__cursorProvider -or $__cursorProvider.Name -ne 'FileSystem' -or $__cursorResolved.Count -eq 0) { $__cursorFiles = $null; break }\n $__cursorFiles.AddRange([string[]]$__cursorResolved)\n }\n }\n # -WhatIf sets $WhatIfPreference and -Confirm sets $ConfirmPreference in this scope.\n if ($null -ne $__cursorFiles -and $__cursorFiles.Count -gt 0 -and -not $PSBoundParameters.ContainsKey('Encoding') -and\n -not $WhatIfPreference -and $ConfirmPreference -notin @('Low', 'Medium') -and -not $PSBoundParameters.ContainsKey('Stream') -and\n -not $PSBoundParameters.ContainsKey('Filter') -and -not $PSBoundParameters.ContainsKey('Include') -and\n -not $PSBoundParameters.ContainsKey('Exclude')) {\n $__cursorAppend = ($PSBoundParameters.ContainsKey('Append') -and $PSBoundParameters['Append']) -or ($PSBoundParameters.ContainsKey('NoClobber') -and $PSBoundParameters['NoClobber'])\n $__cursorDecided = $true\n $__cursorStrip = $true\n foreach ($__cursorFile in $__cursorFiles) {\n $__cursorBefore[$__cursorFile] = & $__cursorHeadOf $__cursorFile\n $__cursorDecisions[$__cursorFile] = & $__cursorEncodingOf $__cursorFile $__cursorBefore[$__cursorFile]\n if ($null -eq $__cursorDecisions[$__cursorFile]) { $__cursorDecided = $false; break }\n # An append onto a file with content writes no BOM, so there is none to take off.\n if ($__cursorAppend -and $null -ne $__cursorBefore[$__cursorFile] -and $__cursorBefore[$__cursorFile].Length -gt 0) { $__cursorStrip = $false }\n }\n }\n elseif ($null -ne $__cursorFiles -and $__cursorFiles.Count -gt 0 -and $PSBoundParameters.ContainsKey('Encoding') -and\n (& $__cursorIsUtf8Bom $PSBoundParameters['Encoding']) -and -not (& $__cursorHasEncodingDefault $__cursorInvoked) -and\n -not $WhatIfPreference -and $ConfirmPreference -notin @('Low', 'Medium') -and -not $PSBoundParameters.ContainsKey('Stream') -and\n -not $PSBoundParameters.ContainsKey('Filter') -and -not $PSBoundParameters.ContainsKey('Include') -and\n -not $PSBoundParameters.ContainsKey('Exclude')) {\n # The UTF8 the command line asked for is UTF-8 with a BOM on this shell and without\n # one on PowerShell 7. For a file whose reader rejects a BOM, and that has none, it\n # means what it means there: the cmdlet writes its BOM, and the proxy takes it off.\n $__cursorAsked = $true\n foreach ($__cursorFile in $__cursorFiles) {\n $__cursorBefore[$__cursorFile] = & $__cursorHeadOf $__cursorFile\n if (-not (& $__cursorTakesNoBom $__cursorFile $__cursorBefore[$__cursorFile])) { $__cursorAsked = $false; break }\n $__cursorDecisions[$__cursorFile] = 'nobom'\n }\n $__cursorStrip = $__cursorAsked\n }\n } catch { $__cursorDecided = $false; $__cursorAsked = $false }\n if ($__cursorDecided) { $PSBoundParameters['Encoding'] = '__CURSORUTF8__' }\n if ($null -ne $__cursorScopeBound) {\n Write-Warning "__CURSORNAME__ runs through a function in this shell, so an item it writes to the $__cursorScopeBound provider lives in a scope that ends with the call. Use an assignment, a function definition or Set-Alias instead."\n }\n # An error the caller asked to stop on ends the caller too, as it does from the cmdlet: it\n # goes on as it is, as from the proxy PowerShell itself generates, which rethrows everything\n # with 'throw'. Any other terminating error of the cmdlet ends the statement and the caller\n # goes on; ThrowTerminatingError keeps that rule, where 'throw' would end the caller's whole\n # script, and the pipeline it ended is not stepped again. Of the two, only the cmdlet's own\n # terminating error names this function rather than the cmdlet's type in the suffix of its\n # FullyQualifiedErrorId; the record of an error the caller asked to stop on is the cmdlet's.\n try {\n $outBuffer = $null\n if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 }\n $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('__CURSORTARGET__', [System.Management.Automation.CommandTypes]::Cmdlet)\n $scriptCmd = { & $wrappedCmd @PSBoundParameters }\n $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)\n $steppablePipeline.Begin($PSCmdlet)\n } catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n}\nprocess {\n if ($__cursorStopped) { return }\n try { $steppablePipeline.Process($_) }\n catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n}\nend {\n if ($__cursorStopped) { return }\n try { $steppablePipeline.End() }\n catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n if (-not $__cursorStrip -or -not ($__cursorDecided -or $__cursorAsked)) { return }\n try {\n foreach ($__cursorFile in $__cursorFiles) { & $__cursorStripBom $__cursorFile ($__cursorDecisions[$__cursorFile] -eq 'bom') $__cursorBefore[$__cursorFile] }\n } catch { }\n}\n'@\n foreach ($__cursorWriter in @('Set-Content', 'Export-Csv')) {\n $__cursorWriterNames = @($__cursorWriter) + @(Get-Alias -Definition $__cursorWriter -ErrorAction Ignore | ForEach-Object { $_.Name })\n $__cursorHasWriterDefault = $false\n foreach ($__cursorKey in @($PSDefaultParameterValues.Keys)) {\n $__cursorKeyParts = "$__cursorKey" -split ':', 2\n if ($__cursorKeyParts.Count -ne 2 -or 'Encoding' -notlike $__cursorKeyParts[1].Trim()) { continue }\n foreach ($__cursorName in $__cursorWriterNames) {\n if ($__cursorName -like $__cursorKeyParts[0].Trim()) { $__cursorHasWriterDefault = $true }\n }\n }\n if ($__cursorHasWriterDefault) { continue }\n try {\n # A function of this name that a profile defined stays in charge; the proxy is built on the cmdlet alone.\n $__cursorCmdlet = @(Microsoft.PowerShell.Core\\Get-Command -Name $__cursorWriter -ErrorAction Stop)[0]\n if ($__cursorCmdlet.CommandType -eq 'Cmdlet') {\n $__cursorTarget = "$($__cursorCmdlet.ModuleName)\\$($__cursorCmdlet.Name)"\n $__cursorMetadata = New-Object System.Management.Automation.CommandMetadata $__cursorCmdlet\n $__cursorNamesList = @($__cursorWriterNames | ForEach-Object { "'" + $_.Replace("'", "''") + "'" }) -join ', '\n $__cursorProxyText = @(\n '<#', ".ForwardHelpTargetName $__cursorTarget", '.ForwardHelpCategory Cmdlet', '#>',\n [System.Management.Automation.ProxyCommand]::GetCmdletBindingAttribute($__cursorMetadata),\n 'param(', [System.Management.Automation.ProxyCommand]::GetParamBlock($__cursorMetadata), ')',\n 'dynamicparam {', [System.Management.Automation.ProxyCommand]::GetDynamicParam($__cursorMetadata), '}',\n $__cursorProxyBody.Replace('__CURSORTARGET__', $__cursorTarget).Replace('__CURSORNAMES__', $__cursorNamesList).Replace('__CURSORNAME__', $__cursorCmdlet.Name).Replace('__CURSORUTF8__', $__cursorUtf8)\n ) -join [Environment]::NewLine\n # Global, as a profile would define it, so that a module's code reaches it too.\n Microsoft.PowerShell.Management\\Set-Item -LiteralPath "function:global:$__cursorWriter" -Value ([scriptblock]::Create($__cursorProxyText)) -ErrorAction Stop\n }\n } catch { }\n }`,kn=String.raw` -+import{createRequire as e}from"node:module";const t=e(import.meta.url);export const __webpack_esm_id__=977;export const __webpack_esm_ids__=[977];export const __webpack_esm_modules__={"./src/agent/local-executor.ts"(e,t,r){r.d(t,{createLocalExecutor:()=>xH});var n=r("node:buffer"),o=r("node:os"),s=r("node:path"),i=r("../proto/dist/generated/agent/v1/agent_pb.js");const a={textDelta:(e,t)=>new i.Uq({messageStartedAtMs:t,message:{case:"textDelta",value:new i.PtE({text:e})}}),toolCallStarted:(e,t,r)=>new i.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"toolCallStarted",value:new i.xuG({callId:e,toolCall:t,modelCallId:r})}}),toolCallCompleted:(e,t,r)=>new i.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"toolCallCompleted",value:new i.LLS({callId:e,toolCall:t,modelCallId:r})}}),toolCallDelta:(e,t,r,n)=>new i.Uq({messageStartedAtMs:n,message:{case:"toolCallDelta",value:new i.I0n({callId:e,toolCallDelta:t,modelCallId:r})}}),thinkingDelta:(e,t,r)=>new i.Uq({messageStartedAtMs:r,message:{case:"thinkingDelta",value:new i.cHB({text:e,thinkingStyle:t})}}),thinkingCompleted:(e,t,r)=>new i.Uq({messageStartedAtMs:t,message:{case:"thinkingCompleted",value:new i.tr3({thinkingDurationMs:e,...!0===r?{narration:!0}:{}})}}),thinkingNote:e=>new i.Uq({message:{case:"thinkingNote",value:new i.Y$k({text:e})}}),taskChild:(e,t,r)=>"thinkingNote"===t.message.case?t:a.toolCallDelta(e,new i.V1v({delta:{case:"taskToolCallDelta",value:new i.aon({interactionUpdate:t})}}),r),userMessageAppended:e=>new i.Uq({messageStartedAtMs:e.startedAtMs,message:{case:"userMessageAppended",value:new i.v$T({userMessage:e})}}),partialToolCall:(e,t,r)=>new i.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"partialToolCall",value:new i.fxF({callId:e,toolCall:t,modelCallId:r})}}),tokenDelta:e=>new i.Uq({message:{case:"tokenDelta",value:new i.Fyz({tokens:e})}}),summary:e=>new i.Uq({message:{case:"summary",value:new i.ECk({summary:e})}}),summaryStarted:()=>new i.Uq({message:{case:"summaryStarted",value:new i.lWT}}),heartbeat:()=>new i.Uq({message:{case:"heartbeat",value:new i.ih1}}),summaryCompleted:(e,t,r)=>new i.Uq({message:{case:"summaryCompleted",value:new i.ZM9({hookMessage:e,failed:t,fallback:r})}}),shellOutputDelta:e=>new i.Uq({message:{case:"shellOutputDelta",value:new i.Nn_({event:e})}}),modelCallCompleted:(e,t)=>new i.Uq({message:{case:"modelCallCompleted",value:new i.c2D({modelCallId:e,inputTokens:BigInt(t.inputTokens),outputTokens:BigInt(t.outputTokens),cacheReadTokens:BigInt(t.cacheReadTokens),cacheWriteTokens:BigInt(t.cacheWriteTokens),...void 0!==t.reasoningTokens?{reasoningTokens:BigInt(t.reasoningTokens)}:{}})}}),turnEnded(e,t){const r=e?.catalogCostCents;return new i.Uq({message:{case:"turnEnded",value:new i.lJj({...e?{inputTokens:BigInt(e.inputTokens),outputTokens:BigInt(e.outputTokens),cacheReadTokens:BigInt(e.cacheReadTokens),cacheWriteTokens:BigInt(e.cacheWriteTokens),reasoningTokens:BigInt(e.reasoningTokens??0)}:{},...void 0!==t?{endedAtMs:t}:{},...void 0!==r&&Number.isFinite(r)?{estimatedCost:new i.QVp({rawCostCents:r,chargedCents:r,source:i.nnk.CATALOG})}:{}})}})},stepStarted:e=>new i.Uq({message:{case:"stepStarted",value:new i.dwJ({stepId:BigInt(e)})}}),toolRequestsListed:e=>new i.Uq({message:{case:"toolRequestsListed",value:new i.BU$({callCount:Math.max(0,e)})}}),voiceCallUtterance:e=>new i.Uq({message:{case:"voiceCallUtterance",value:e}}),stepCompleted:(e,t)=>new i.Uq({message:{case:"stepCompleted",value:new i.Lrv({stepId:BigInt(e),stepDurationMs:BigInt(t)})}}),activeBranchChange:(e,t)=>new i.Uq({message:{case:"activeBranchChange",value:new i.PSN({path:e,branchName:t})}}),feedbackRequest:(e,t,r,n=[],o={})=>new i.Uq({message:{case:"feedbackRequest",value:new i.apn({requestId:e,canonicalModelName:t,categories:[...r],categoryGroups:[...n],title:o.title,negativeTitle:o.negativeTitle,commentPlaceholder:o.commentPlaceholder})}})};class c{constructor(e=0){this.nextId=e}next(){return this.nextId++}peekNext(){return this.nextId}observe(e){Number.isSafeInteger(e)&&e>=this.nextId&&(this.nextId=e+1)}}var l=r("../context/dist/logger.js"),u=r("../metrics/dist/index.js"),d=r("../proto/dist/generated/agent/v1/exec_pb.js"),h=r("../utils/dist/writable-iterable.js");const p=/https?:\/\/\S+/gi,f=/[)"'<>,.;:\]}]$/;function m(e){const{url:t,wrappers:r}=function(e){let t=e.length;for(;t>0&&f.test(e.slice(t-1,t));)t-=1;return{url:e.slice(0,t),wrappers:e.slice(t)}}(e),n=t.search(/[?#]/),o=-1===n?t:t.slice(0,n),s=o.indexOf("//")+2,i=o.slice(s).search(/[/?#]/),a=-1===i?o.length:s+i,c=o.lastIndexOf("@",a-1);return c0&&o.push(`gitErrorCode=${n.gitErrorCode}`),"number"==typeof n.exitCode&&Number.isFinite(n.exitCode)&&o.push(`exitCode=${n.exitCode}`),0===o.length)return e;let s=`${e} [git: ${o.join(" ")}]`;var i,a;return!0===r?.includeStderr&&"string"==typeof n.stderr&&n.stderr.length>0&&(s+=`\n--- git stderr ---\n${a=n.stderr,i=a.replace(p,m),i.length<=2048?i:`${i.slice(0,2048)}… [truncated to 2048 chars]`}`),s}var y=r("../context/dist/core.js");const v=(0,y.cF)(Symbol("machineProfile"),void 0),b=(0,l.h)("SimpleControlledExecManager"),S=(0,u.v5)("agent_exec.controlled.exec.duration_ms",{description:"Duration of controlled exec operations in milliseconds",labelNames:["exec_case"]}),k=(0,u.v5)("agent_exec.controlled.exec.machine_duration_ms",{description:"Duration of grep, shell and hook execs by coarse machine profile",labelNames:["exec_case","cpu_cores","ram_gb","defender_rt"]}),_=new Set(["grepArgs","shellStreamArgs","executeHookArgs"]),C=(0,u.Pu)("agent_exec.controlled.exec.success",{description:"Count of successful controlled exec operations",labelNames:["exec_case"]}),E=(0,u.Pu)("agent_exec.controlled.exec.error",{description:"Count of failed controlled exec operations",labelNames:["exec_case"]}),x={computerUseArgs:"Computer use is not enabled for this environment, so the Computer tool and the computerUse subagent cannot run here. Do not retry computer actions; verify with non-GUI methods (automated tests, shell commands) instead. (No computer-use handler is registered on this exec daemon.)",recordScreenArgs:"Screen recording is not enabled for this environment, so recordings cannot be captured here. Do not retry; skip the recording and present other evidence instead. (No record-screen handler is registered on this exec daemon.)"};class P extends Error{constructor(e){super(e),this.name="ControlledExecDisposedError"}}function R(e){return e instanceof P?"EXEC_BACKEND_UNAVAILABLE":e instanceof Error&&"AgentExecStreamStartTimeoutError"===e.name?"AGENT_EXEC_STREAM_START_TIMEOUT":void 0}class I{constructor(e,t,r){this.exec=e,this.deserializeArgs=t,this.serializeResult=r}handle(e,t){const r=this.deserializeArgs(t);if(void 0===r)return;const{id:n,args:o}=r;return async function*(r){const s=performance.now(),i=[],a=await r.exec.execute(e,o,{execId:t.execId,hookContextCollector:i,deliverAgentStoreConflictNotices:!0===t.acceptHookAdditionalContexts,recordAgentView:!0===t.recordAgentView,refuseUnreadChanges:!0===t.refuseUnreadChanges}),c=r.serializeResult(n,a);c.localExecutionTimeMs=Math.round(Math.max(0,performance.now()-s)),i.length>0&&(c.hookAdditionalContexts=i),yield c}(this)}}class T{constructor(e,t,r){this.exec=e,this.deserializeArgs=t,this.serializeStream=r}handle(e,t){const r=this.deserializeArgs(t);if(void 0===r)return;const{id:n,args:o}=r;return async function*(r){const s=performance.now(),i=[],a=r.exec.execute(e,o,{execId:t.execId,hookContextCollector:i,deliverAgentStoreConflictNotices:!0===t.acceptHookAdditionalContexts});try{for await(const e of a){{const __t3h=globalThis[Symbol.for("@cursor/sdk.shellStreamOutput")];const __t3c=e.event?.case;if(typeof __t3h==="function"&&(__t3c==="stdout"||__t3c==="stderr"))try{__t3h({conversationId:o.conversationId,toolCallId:o.toolCallId,event:{case:__t3c,value:{data:e.event.value.data}}})}catch{}}const t=r.serializeStream(n,e);t.localExecutionTimeMs=Math.round(Math.max(0,performance.now()-s)),yield t}}finally{const e=i.filter((e=>"agentStoreConflict"===e.hookEventName));e.length>0&&(yield new d.yT({id:n,hookAdditionalContexts:e}))}}(this)}}class A{constructor(e){this.handlers=[],this.runningExecs=new Map;const t=e?.includeGitStderrInThrows??!1;this.includeGitStderrInThrows="function"==typeof t?t:()=>t,this.observeResults=e?.observeResults}startResultObserver(e,t,r){if(void 0!==this.observeResults)try{return this.observeResults(e,t,r)}catch{return}}register(e){this.handlers.push(e)}handleControlMessage(e){if("abort"===e.message.case){const t=e.message.value.id,r=this.runningExecs.get(t);r&&r()}}handle(e,t){const[r,n]=e.withCancel();this.runningExecs.set(t.id,n);const o=t.message.case??"unknown";for(const e of this.handlers){const s=e.handle(r,t);if(void 0===s)continue;const i=s,a=(0,h.Jt)();let c;const l=()=>{c=setTimeout((()=>{a.write(new d.$Y({message:{case:"heartbeat",value:new d.VA({id:t.id})}})).then(l).catch((()=>{}))}),3e3)};l();const u=performance.now(),p=this.startResultObserver(r,o,t);return(async()=>{try{for await(const e of i){if(void 0!==p&&e instanceof d.yT)try{p.message(e)}catch{}await a.write(e)}await a.write(new d.$Y({message:{case:"streamClose",value:new d.D9({id:t.id})}})),C.increment(r,1,{exec_case:o})}catch(e){if(e instanceof h.W2)return;E.increment(r,1,{exec_case:o}),await a.write(new d.$Y({message:{case:"throw",value:new d.Fu({id:t.id,error:e instanceof Error?w(e.message,e,{includeStderr:this.includeGitStderrInThrows()}):"Unknown error",stackTrace:e instanceof Error?e.stack:void 0,errorCode:R(e)})}}))}finally{if(void 0!==p)try{p.done()}catch{}const e=performance.now()-u;if(S.histogram(r,e,{exec_case:o}),_.has(o)){const t=r.get(v)?.();void 0!==t&&k.histogram(r,e,{exec_case:o,...t})}clearTimeout(c),a.close(),this.runningExecs.delete(t.id),n()}})(),a}this.runningExecs.delete(t.id),n();const s=t.message.case,i=(void 0===s?void 0:x[s])??`No handler found for server message of type ${s}`;return b.error(e,i,{messageCase:s}),E.increment(e,1,{exec_case:o}),async function*(){yield new d.$Y({message:{case:"throw",value:new d.Fu({id:t.id,error:i})}}),yield new d.$Y({message:{case:"streamClose",value:new d.D9({id:t.id})}})}()}static fromResources(e,t){const r=new A(t);for(const[t,n]of e.entries())t.registerControlledImplementation(n,r);return r}}var $=r("../context/dist/otel.js");async function M(e){const t=e[Symbol.asyncIterator](),r=await t.next();if(r.done)return;const n={async*[Symbol.asyncIterator](){for(;;){const e=await t.next();if(e.done)return;yield e.value}}};return{firstItem:r.value,rest:n}}const D=(0,y.cF)(Symbol("agentExec.remoteExecResultObserverFactory"),void 0),O={message(){},[Symbol.dispose](){}};function F(e){const t=e.get(D);if(void 0===t)return O;let r;try{r=t(e)}catch{return O}return void 0===r?O:{message(e){try{r?.message(e)}catch{r=void 0}},[Symbol.dispose](){const e=r;r=void 0;try{e?.end()}catch{}}}}var N=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},L=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const j=(0,l.h)("ExecutorResource"),U=(0,u.Pu)("agent_exec.hook_additional_context.delivered",{description:"Hook additional_context carriers drained into the caller collector",labelNames:["hook_event_name"]});class B{constructor(e,t,r){this.execManager=e,this.serializeArgs=t,this.deserializeResult=r}async execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=N(n,(0,$.VI)(e.withName("ExecutorResource.execute")),!1),s=o.ctx;void 0!==r?.execId&&o.span.setAttribute("exec.id",r.execId);const i=(0,$.mJ)(s),a=i?new d.Kg(i):void 0,c=this.execManager.createExecInstance(s,(e=>{const n=this.serializeArgs(e,t);return new d.Ye({id:n.id,message:n.message,execId:r?.execId,machineId:r?.machineId,spanContext:a,acceptHookAdditionalContexts:void 0!==r?.hookContextCollector,recordAgentView:r?.recordAgentView,refuseUnreadChanges:r?.refuseUnreadChanges})})),l=await M(c);if(void 0===l)throw new Error("No exec result");let{firstItem:u,rest:h}=l;const p=N(n,F(s),!1),f=e=>{if(p.message(e),void 0!==r?.hookContextCollector&&e.hookAdditionalContexts.length>0){r.hookContextCollector.push(...e.hookAdditionalContexts);for(const t of e.hookAdditionalContexts)U.increment(s,1,{hook_event_name:t.hookEventName})}};f(u);let m=this.deserializeResult(u);for(;void 0===m;){const e=await M(h);if(void 0===e)throw new Error("No result value");u=e.firstItem,h=e.rest,f(u),m=this.deserializeResult(u)}return(async()=>{try{for await(const e of h)f(e)}catch(e){j.info(s,"Ignoring exec stream shutdown during detached drain",{error:e})}})().catch((()=>{})),m}catch(e){n.error=e,n.hasError=!0}finally{L(n)}}}class W{constructor(e,t,r){this.execManager=e,this.serializeArgs=t,this.deserializeStream=r}async*execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=N(n,(0,$.VI)(e.withName("StreamExecutorResource.execute")),!1).ctx,s=(0,$.mJ)(o),i=s?new d.Kg(s):void 0,a=this.execManager.createExecInstance(o,(e=>{const n=this.serializeArgs(e,t);return new d.Ye({id:n.id,message:n.message,execId:r?.execId,machineId:r?.machineId,spanContext:i,acceptHookAdditionalContexts:void 0!==r?.hookContextCollector||!0===r?.deliverAgentStoreConflictNotices})})),c=N(n,F(o),!1);for await(const e of a){c.message(e),void 0!==r?.hookContextCollector&&e.hookAdditionalContexts.length>0&&r.hookContextCollector.push(...e.hookAdditionalContexts);const t=this.deserializeStream(e);void 0!==t&&(yield t)}}catch(e){n.error=e,n.hasError=!0}finally{L(n)}}}function H(e){return Symbol.for(`@anysphere/agent-exec/resource/${e}`)}function q(e,t,r){return{name:e,symbol:H(e),remoteImplementation:t,registerControlledImplementation:r}}class z{constructor(e,t){this.resource=e,this.value=t}}function G(e,t){return[e,t]}function V(e,t){return t}class K{constructor(){this.resources=new Map}register(e,t){this.resources.set(e.symbol,new z(e,t))}get(e){return V(0,this.resources.get(e.symbol)?.value)}entries(){return Array.from(this.resources.values()).map((e=>[e.resource,e.value]))}}class J{constructor(e,t){this.remoteAccessor=e,this.localResources=new Map;for(const[e,r]of t)this.localResources.set(e.symbol,{resource:e,implementation:r})}get(e){const t=this.localResources.get(e.symbol);return t?V(0,t.implementation):this.remoteAccessor.get(e)}*entries(){for(const{resource:e,implementation:t}of this.localResources.values())yield[e,t];for(const e of this.remoteAccessor.entries())this.localResources.has(e[0].symbol)||(yield e)}}function Z(e){return function(t,r){return new d.Ye({id:t,message:{case:e,value:r}})}}function X(e){return t=>{if(t.message.case===e)return t.message.value}}function Q(e){return function(t,r){const n={case:e,value:r};return new d.yT({id:t,message:n})}}function Y(e){return function(t){if(t.message.case===e)return{id:t.id,args:t.message.value}}}const ee=q("shell-stream-executor",(e=>new W(e,Z("shellStreamArgs"),X("shellStream"))),((e,t)=>{t.register(new T(e,Y("shellStreamArgs"),Q("shellStream")))}));var te=r("../proto/dist/generated/agent/v1/kv_pb.js"),re=r("../agent-kv/dist/blob-store.js"),ne=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const oe=(0,l.h)("ControlledKvManager");function se(e,t,r){return e?(0,$.F)({traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags??1},t,r):r}function ie(e,t,r,n,o){o<=r||(0,$.xd)(e.withName(`${t}.slow`),{startTime:n,attributes:{durationMs:o,slowThresholdMs:r}},n+o)}const ae=(0,u.v5)("agent_kv.controlled.get_blob.duration_ms",{description:"Duration of ControlledKvManager getBlob operations in milliseconds"}),ce=(0,u.v5)("agent_kv.controlled.set_blob.duration_ms",{description:"Duration of ControlledKvManager setBlob operations in milliseconds"});class le{constructor(e,t,r,n={}){this.serverStream=e,this.clientStream=t,this.blobStore=r,this.options=n}async run(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,$.VI)(e.withName("ControlledKvManager.run")),!1).ctx,n=new Set,o=e=>{n.add(e),e.finally((()=>{n.delete(e)}))};try{for await(const e of this.serverStream){const t=performance.now(),n=Date.now();switch(e.message.case){case"getBlobArgs":{const s=e.message.value.blobId;o((async()=>{const o=se(e.spanContext,"ControlledKvManager.getBlob",r);try{await(this.options.beforeGetBlob?.(o,s));const t=await this.blobStore.getBlob(o,s);await this.clientStream.write(new te.gm({id:e.id,message:{case:"getBlobResult",value:{blobData:t?(0,re.Fo)(t):void 0}}}))}catch(t){oe.error(o,"Error handling getBlob",t);const r=t instanceof Error?t.message:String(t);try{await this.clientStream.write(new te.gm({id:e.id,message:{case:"getBlobResult",value:{blobData:void 0,error:{message:r}}}}))}catch(e){oe.error(o,"Error writing failed getBlobResult",e)}}finally{const e=performance.now()-t;ae.histogram(o,e),ie(o,"ControlledKvManager.getBlob",50,n,e)}})());break}case"setBlobArgs":{const s=e.message.value.blobId,i=e.message.value.blobData;o((async()=>{const o=se(e.spanContext,"ControlledKvManager.setBlob",r);try{await this.blobStore.setBlob(o,s,i),await this.clientStream.write(new te.gm({id:e.id,message:{case:"setBlobResult",value:{error:void 0}}}))}catch(t){const r=t instanceof Error?t.message:String(t);try{await this.clientStream.write(new te.gm({id:e.id,message:{case:"setBlobResult",value:{error:{message:r}}}}))}catch(e){oe.error(o,"Error writing setBlobResult",e)}}finally{const e=performance.now()-t;ce.histogram(o,e),ie(o,"ControlledKvManager.setBlob",100,n,e)}})());break}}}}finally{await Promise.allSettled(n)}}catch(e){t.error=e,t.hasError=!0}finally{ne(t)}}}function ue(e){return e instanceof Error?{abortReasonType:"error",abortReasonName:e.name,abortReasonMessage:e.message}:"string"==typeof e?{abortReasonType:"string",abortReasonMessage:e}:void 0===e?{abortReasonType:"undefined"}:{abortReasonType:typeof e}}var de=r("../proto/dist/generated/agent/v1/agent_service_pb.js"),he=r("../proto/dist/generated/agent/v1/shell_exec_pb.js");Error;const pe={stateRestoreMs:"client_prep_state_restore_ms",rootPromptRestoreMs:"client_prep_root_prompt_restore_ms",requestContextMs:"client_prep_request_context_ms",systemPromptMs:"client_prep_system_prompt_ms",preTurnSnapshotMs:"client_prep_pre_turn_snapshot_ms",preTurnSnapshotWaitMs:"client_prep_pre_turn_snapshot_wait_ms",preTurnSnapshotBlobWritesMs:"client_prep_pre_turn_snapshot_blob_writes_ms",preTurnSnapshotSerializeMs:"client_prep_pre_turn_snapshot_serialize_ms",firstStepToFirstInvocationMs:"client_prep_first_step_to_first_invocation_ms",promptMessageCount:"client_prep_prompt_message_count",turnCount:"client_prep_turn_count"},fe=Object.keys(pe).filter((e=>e in pe));function me(e){const t={};for(const r of fe){const n=e[r];void 0!==n&&(t[r]=n)}return t}new WeakMap;var ge=r("../utils/dist/fresh-uuid.js"),we=r("@bufbuild/protobuf"),ye=r("@connectrpc/connect"),ve=r("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/protocol/async-iterable.js"),be=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class Se{constructor(e,t,r){this.checkpointStream=e,this.checkpointHandler=t,this.ctx=r}async run(){const e={stack:[],error:void 0,hasError:!1};try{const t=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(e,(0,$.VI)(this.ctx.withName("CheckpointController.run")),!1).ctx,r=[];for await(const e of this.checkpointStream){let n;try{n=this.checkpointHandler.handleCheckpoint(t,e.checkpoint,e.metadata)}catch(t){throw e.onSettled?.(),t}r.push(n),void 0!==e.onSettled&&n.then(e.onSettled,e.onSettled)}await Promise.all(r)}catch(t){e.error=t,e.hasError=!0}finally{be(e)}}}const ke=(0,l.h)("@anysphere/agent-client:checkpoint-store-waits");class _e{constructor(e={}){this.options=e,this.inFlight=new Map}noteRouted(e){const t=Ee(e.pendingToolCalls);if(0===t.size)return Ce;let r;const n=new Promise((e=>{r=e}));for(const e of t){let t=this.inFlight.get(e);void 0===t&&(t=new Set,this.inFlight.set(e,t)),t.add(n)}return()=>{for(const e of t){const t=this.inFlight.get(e);t?.delete(n),0===t?.size&&this.inFlight.delete(e)}r()}}storedBefore(e,t){const r=this.inFlight.get(t);if(void 0!==r){try{this.options.onExecHeld?.(t)}catch(t){ke.warn(e,"onExecHeldForCheckpointStore callback failed",{error:String(t)})}return Promise.all(r).then(Ce)}}}function Ce(){}function Ee(e){const t=new Set;for(const r of e){let e;try{e=JSON.parse(r)}catch{continue}const n=Pe(e)?e.content:void 0;if(!Array.isArray(n))continue;const o=n;for(const e of o)Pe(e)&&"tool-call"===e.type&&"string"==typeof e.toolCallId&&t.add(e.toolCallId)}return t}function xe(e){if("executeHookArgs"===e.message.case)return function(e){const t=e.request?.request;switch(t?.case){case"preToolUse":case"postToolUse":case"postToolUseFailure":return""===t.value.toolUseId?void 0:t.value.toolUseId;case"subagentStart":return""===t.value.toolCallId?void 0:t.value.toolCallId;default:return}}(e.message.value);const t=e.message.value;return Pe(t)&&"string"==typeof t.toolCallId&&""!==t.toolCallId?t.toolCallId:void 0}function Pe(e){return"object"==typeof e&&null!==e}const Re=(0,l.h)("@anysphere/agent-client:exec-checkpoint-gate"),Ie=new Set(["shellArgs","shellStreamArgs","backgroundShellSpawnArgs","forceBackgroundShellArgs","miniSweAgentBashArgs","writeArgs","deleteArgs","mcpArgs","readMcpResourceExecArgs","computerUseArgs","recordScreenArgs","subagentArgs","forceBackgroundSubagentArgs","executeHookArgs"]),Te=new Set(["userMessageAction","resumeAction","backgroundTaskCompletionAction","goalContinuationAction","subscriptionNotificationAction","executePlanAction","asyncAskQuestionCompletionAction"]);function Ae(e){const t=e.message.case;return void 0!==t&&Ie.has(t)?xe(e):void 0}const $e=e=>e.replace(/[\r\n]/g,"");function Me(e){return{...void 0!==e.parentRequestId?{"x-parent-request-id":$e(e.parentRequestId)}:{},...void 0!==e.rootParentRequestId?{"x-root-parent-request-id":$e(e.rootParentRequestId)}:{},...void 0!==e.parentAgentToolCallId?{"x-parent-agent-tool-call-id":$e(e.parentAgentToolCallId)}:{},...!0===e.directMetaParentChildSubagent?{"x-direct-meta-parent-child-subagent":"true"}:{}}}const De="x-inference-authentication-jwt";function Oe(){const e=globalThis.process?.env,t=e?.INFERENCE_PROXY_JWT?.trim();return void 0===t||""===t||t.startsWith("$")?{}:{[De]:t}}class Fe extends Error{constructor(e,t){super(`This conversation's data is missing and can't be restored. Start a new chat to continue.${function(e){if(0===e.length)return"";const t=e.slice(0,3).map((e=>e.slice(0,12)));return` (${1===e.length?`missing blob ${t[0]}`:`${e.length} missing blobs: ${t.join(", ")}${e.length>t.length?", …":""}`})`}(e)}`,void 0!==t?.cause?{cause:t.cause}:void 0),this.isUsageError=!0,this.isBlobNotFound=!0,this.name="BlobNotFoundError",this.blobIdHexes=[...e]}}function Ne(e){return e instanceof Error&&(e instanceof Fe||"isBlobNotFound"in e&&!0===e.isBlobNotFound||"BlobNotFoundError"===e.name)}var Le=r("../proto/dist/generated/aiserver/v1/utils_pb.js"),je=r("zod/v4");const Ue="relayedAttemptFailure",Be=je.object({transport:je.boolean(),stallAborted:je.boolean(),errorName:je.string(),connectCode:je.number().optional(),connectCodeName:je.string().optional(),connectCause:je.object({code:je.union([je.string(),je.number()]).optional(),name:je.string().optional()}).optional(),transportFailureKind:je.string().optional(),loop:je.string().optional(),transportMode:je.string().optional()});function We(e){const t=e?.details?.additionalInfo[Ue];if(void 0!==t)try{const e=Be.safeParse(JSON.parse(t));return e.success?e.data:void 0}catch{return}}class He extends Error{constructor(e,t={}){super(e),Object.setPrototypeOf(this,new.target.prototype),this.cause=t.cause,this.requestId=t.requestId,this.displayInfo=t.displayInfo,this.isTransport=t.isTransport}get name(){return this.kind}}class qe extends He{get kind(){return"RetriableError"}}class ze extends He{constructor(e,t,r={}){super(e,r),this.action=t}get kind(){return"ActionRequiredError"}}class Ge extends He{get kind(){return"NonRetriableError"}}class Ve extends Ge{constructor(e){const t=`This turn's step limit (${e}) needs an in-process agent loop; the network client cannot send it.`;super(t,{displayInfo:{title:"Step limit not supported",detail:t,isRetryable:!1}}),this.maxSteps=e}}class Ke extends He{get kind(){return"CancelledError"}}const Je=new Set([Le.yM.NOT_LOGGED_IN,Le.yM.AGENT_REQUIRES_LOGIN,Le.yM.AUTH_TOKEN_NOT_FOUND,Le.yM.AUTH_TOKEN_EXPIRED,Le.yM.INVALID_AUTH_ID,Le.yM.UNAUTHORIZED,Le.yM.GITHUB_NO_USER_CREDENTIALS,Le.yM.GITHUB_USER_NO_ACCESS]),Ze=new Set([Le.yM.FREE_USER_USAGE_LIMIT,Le.yM.FREE_USER_RATE_LIMIT_EXCEEDED,Le.yM.PRO_USER_ONLY,Le.yM.PRO_USER_USAGE_LIMIT,Le.yM.PRO_USER_RATE_LIMIT_EXCEEDED,Le.yM.RATE_LIMITED,Le.yM.RATE_LIMITED_CHANGEABLE,Le.yM.GENERIC_RATE_LIMIT_EXCEEDED]),Xe=new Set([Le.yM.USAGE_PRICING_REQUIRED,Le.yM.USAGE_PRICING_REQUIRED_CHANGEABLE]),Qe=new Set([Le.yM.BAD_API_KEY,Le.yM.BAD_USER_API_KEY,Le.yM.OUTDATED_CLIENT]),Ye=new Set([Le.yM.USER_ABORTED_REQUEST,Le.yM.DEBOUNCED]),et=new Set([Le.yM.CUSTOM_MESSAGE]),tt=new Map([[ye.Code.PermissionDenied,"Permission Denied"]]),rt=["NGHTTP2","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE","socket hang up","Premature close","UND_ERR_SOCKET","ERR_STREAM","protocol error","http/2 stream","ERR_HTTP2_SESSION_ERROR","Session closed with error code","connection aborted","PING timed out","HTTP/2 session not established","HTTP/2 peer not answering","refused to tunnel to","HTTP CONNECT through proxy","Could not connect to proxy"],nt=new Set(["ENOTFOUND","EAI_AGAIN","EAI_FAIL","ENODATA","ESERVFAIL","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ECONNABORTED"]),ot=new RegExp(`\\b(${[...nt].join("|")})\\b`),st=["IMAGE_TOO_LARGE","MAX_TOKENS","CONVERSATION_TOO_LONG","CONTENT_POLICY","DEPRECATED","MAX_MODE_REQUIRED","MODEL_NO_LONGER_SUPPORTED","UNSUPPORTED_REGION","OUTDATED_CLIENT"],it="x-cursor-inference-request-error-type",at="AgentWebSocketDeliveryAmbiguousError";function ct(e,t={}){const{requestId:r}=t;if(e instanceof He)return e;if(lt(e))return function(e,t){const r=dt(e),n=r.code,o=ht(e),s=void 0===o?void 0:function(e){if(void 0===e.details?.additionalInfo[Ue])return e;const t=e.clone();return void 0!==t.details&&(delete t.details.additionalInfo[Ue],t.details.equals(new Le.ej)&&(t.details=void 0)),t}(o),i={title:s?.details?.title,detail:s?.details?.detail,isRetryable:s?.details?.isRetryable,connectCode:n,errorCode:s?.error,inferenceRequestErrorType:pt(r,it)??pt(e,it),errorDetails:s},a={cause:e,requestId:t,displayInfo:i,...!0===We(o)?.transport?{isTransport:!0}:{}};if(n===ye.Code.Canceled||n===ye.Code.Aborted)return bt(e)?new qe(e.message,a):new Ke(e.message,a);if(void 0!==s?.error){const t=s.error;if(Ye.has(t))return new Ke(wt(e,s),a);const r=s.details?.analyticsMetadata?.actionRequired;if(void 0!==r&&""!==r)return new ze(wt(e,s),r,a);if(void 0!==At(s))return new qe(wt(e,s),a);if(Je.has(t))return new ze(wt(e,s),"login",a);if(Ze.has(t))return new ze(wt(e,s),"upgrade",a);if(Xe.has(t))return new ze(wt(e,s),"payment",a);if(Qe.has(t))return new ze(wt(e,s),"config",a);if(et.has(t)&&!0!==s.details?.isRetryable)return new Ge(wt(e,s),a);if(!1===s.details?.isRetryable)return new Ge(wt(e,s),a)}if(n===ye.Code.Unauthenticated)return new ze(e.message,"login",{...a,displayInfo:ut(i,"Sign in required",r)});const c=gt(r);if(Rt.test(c))return new ze(e.message,"proxy_sign_in",{...a,displayInfo:{...i,title:"Proxy sign-in required",detail:`${c}. Please check your sign-in for this proxy and try again.`,isRetryable:!0}});if(It.test(c))return new ze(e.message,"proxy_blocked",{...a,displayInfo:{...i,title:"Connection blocked by proxy",detail:`${c}. Your proxy doesn't allow this connection. Please ask your network administrator to allow it and try again.`,isRetryable:!0}});const l=tt.get(n);return void 0===l||!0===s?.details?.isRetryable||bt(e)?new qe(e.message,a):new Ge(wt(e,s),{...a,displayInfo:ut(i,l,r)})}(e,r);const n=function(e){let t=e;for(let e=0;e<10;e++){if(null==t)return;if(Ne(t))return t;if("object"!=typeof t||!("cause"in t))return;t=t.cause}}(e);if(void 0!==n)return new Ge(n.message,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Conversation data missing",detail:n.message,isRetryable:!1}});const o=function(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){if(r.name===yt)return r;t.add(r),r=r.cause}}(e);if(void 0!==o)return new Ge(o.message,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Context summarization failed",detail:o.message,isRetryable:!1}});if(function(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){const e="code"in r?r.code:void 0,n="errcode"in r?r.errcode:void 0;if("ENOSPC"===e||"ERR_SQLITE_ERROR"===e&&"number"==typeof n&&13==(255&n))return!0;t.add(r),r=r.cause}return!1}(e))return new Ge(vt,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Out of disk space",detail:vt,isRetryable:!1}});if(e instanceof Error){if("AbortError"===e.name)return new Ke(e.message,{cause:e,requestId:r});if(e.name===at)return new qe(e.message,{cause:e,requestId:r,isTransport:!0});if(bt(e))return new qe(e.message,{cause:e,requestId:r})}const s=e instanceof Error?e.message:String(e);return new qe(s,{cause:e instanceof Error?e:void 0,requestId:r})}function lt(e){return null!==e&&"object"==typeof e&&"code"in e&&"name"in e&&("ConnectError"===e.name||"rawMessage"in e&&"string"==typeof e.rawMessage&&"details"in e&&Array.isArray(e.details)&&"findDetails"in e&&"function"==typeof e.findDetails)}function ut(e,t,r){return{...e,title:e.title||t,detail:e.detail||gt(r),isRetryable:e.isRetryable??!1}}function dt(e){let t=e;for(let e=0;e<10&&t.code===ye.Code.Unknown;e++){const e=t.cause;if(!lt(e))break;t=e}return t}function ht(e){let t=e;for(let e=0;e<10&<(t);e++){try{const e=t.findDetails?.(Le.vj);if(void 0!==e&&e.length>0)return e[0]}catch{}t=t.cause}}function pt(e,t){const r=e.metadata;if(null===r||"object"!=typeof r||!("get"in r)||"function"!=typeof r.get)return;const n=r.get(t);return"string"==typeof n?n:void 0}function ft(e){let t=e;for(let e=0;e<10&&"object"==typeof t&&null!==t;e++){if(lt(t))return t;t="cause"in t?t.cause:void 0}}function mt(e){const t=ft(e);return void 0===t?void 0:dt(t)}function gt(e){const t=e.rawMessage;return"string"==typeof t?t:e.message.replace(/^\[[a-z_]+\] /,"")}function wt(e,t){if(t?.details){const{title:r,detail:n}=t.details;return r&&n?`${r} ${n}`:r||n||e.message}return e.message}const yt="SummaryPlaceholderRejectedError",vt="Out of disk space. Free some space and try again.";function bt(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){t.add(r);const e=`${r.name}: ${r.message}`;if(rt.some((t=>e.includes(t)))||ot.test(e))return!0;const n=r.code;if("string"==typeof n&&(rt.some((e=>n.includes(e)))||nt.has(n)))return!0;r=r.cause}return!1}function St(e){return rt.some((t=>e.includes(t)))||ot.test(e)}function kt(e){return e instanceof He&&e.cause instanceof Error?bt(e.cause):e instanceof Error?bt(e):"string"==typeof e&&St(e)}function _t(e){return void 0!==e&&e>0}function Ct(e){return e+1}function Et(e){return Object.defineProperty(e,"code",{value:"connection_stalled",enumerable:!0,configurable:!0}),e}function xt(e){const{cause:t,requestId:r,transportErrorRetries:n,connectCode:o}=e;return _t(n)?Et(new qe("Connection stalled repeatedly",{cause:t,requestId:r,displayInfo:{title:"Connection stalled",detail:`The connection stalled ${Ct(n)} times. Please check your network connection and try again.`,isRetryable:!0,connectCode:o}})):Et(new qe("Connection stalled",{cause:t,requestId:r,displayInfo:{title:"Connection stalled",detail:"The connection stalled. Please try again.",isRetryable:!0,connectCode:o}}))}const Pt=/^(?:Proxy \S+ refused to tunnel to |HTTP CONNECT through proxy \S+ failed: |Could not connect to proxy \S+: )/,Rt=/^Proxy \S+ refused to tunnel to \S+: 407\b/,It=/^Proxy \S+ refused to tunnel to \S+: 403\b/;function Tt(e){let t=e.cause;for(let e=0;e<10&&void 0!==t;e++){if(t instanceof Error&&"AbortError"===t.name)return!0;if(lt(t)&&(t.code===ye.Code.Canceled||t.code===ye.Code.Aborted))return!0;t=null!==t&&"object"==typeof t&&"cause"in t?t.cause:void 0}return!1}function At(e){const t=e?.details?.additionalInfo;if(e?.error!==Le.yM.RATE_LIMITED||"run_inference_novel_tokens"!==t?.kind||void 0===t.retryAfterMs)return;const r=Number(t.retryAfterMs);return Number.isFinite(r)&&r>=0?r:void 0}var $t=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Mt=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Dt=(0,l.h)("@anysphere/agent-client:exec-controller");class Ot extends Error{constructor(e){super(e),this.name="LostConnection"}}class Ft{constructor(e,t,r,n){this.serverStream=e,this.clientStream=t,this.controlledExecManager=r,this.checkpointStoreWaits=n}async run(e){const t={stack:[],error:void 0,hasError:!1};try{$t(t,(0,$.VI)(e.withName("ClientExecController.run")),!1);const r=[],n=t=>{if((0,we.isMessage)(t,d.Nv))this.controlledExecManager.handleControlMessage(t);else{const n=this.execute(e,t);n.catch((()=>{})),r.push(n)}};let o,s,i=!1;try{try{for await(const t of this.serverStream){const r=(0,we.isMessage)(t,d.Nv)?void 0:xe(t),a=void 0===r?void 0:this.checkpointStoreWaits?.storedBefore(e,r);if(void 0===o&&void 0===a){n(t);continue}const c=(o??Promise.resolve()).then((async()=>{await a,(0,we.isMessage)(t,d.Nv)||!i&&!e.canceled?n(t):Dt.info(e,"Dropped an exec queued behind a checkpoint's store",{toolCallId:r})})).catch((e=>{s??={error:e}}));o=c,c.then((()=>{o===c&&(o=void 0)}))}}finally{i=!0}if(await o,void 0!==s)throw s.error;await Promise.all(r)}catch(e){if(e instanceof ye.ConnectError&&"protocol error: missing EndStreamResponse"===e.rawMessage)throw new Ot(e.message);if(e instanceof ye.ConnectError&&e.code===ye.Code.Aborted){const t=e.cause;if(t instanceof Error&&"code"in t&&"string"==typeof t.code&&t.code.includes("ERR_STREAM_WRITE_AFTER_END"))throw new Ot(e.message)}else{if(e instanceof h.W2)throw new Ot(e.message);if(e instanceof ye.ConnectError&&e.code===ye.Code.Internal){const t=e.cause;if(t instanceof Error&&t.message.includes("NGHTTP2_PROTOCOL_ERROR"))throw new Ot(e.message)}}throw e}}catch(e){t.error=e,t.hasError=!0}finally{Mt(t)}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{let n,o;if(t.spanContext){const r=t.spanContext;n=(0,$.V5)({traceId:r.traceId,spanId:r.spanId,traceFlags:r.traceFlags??1},"exec.handle",e),o=(0,$.fU)(n)}else n=e;$t(r,o?new $.r2(n,o):void 0,!1);const s=this.controlledExecManager.handle(n,t);for await(const e of s)await this.clientStream.write(e)}catch(e){r.error=e,r.hasError=!0}finally{Mt(r)}}}const Nt=(0,l.h)("@anysphere/agent-client:stall-detector"),Lt=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,jt={nal:"[NAL client stall detector]",local_loop:"[local-loop client stall detector]",module:"[module client stall detector]"},Ut=new Set(["http2","http1_sse","http1_poll","websocket"]);function Bt(e){return void 0===e?"unknown":Ut.has(e)?e:"other"}const Wt=(0,u.Pu)("agent_client.stream.stall.count",{description:"Number of bidirectional stream stalls detected",labelNames:["activity_type","message_type","loop","transport_mode"]}),Ht=(0,u.v5)("agent_client.stream.stall.duration_ms",{description:"Duration of stream stalls in milliseconds",labelNames:["activity_type","loop","transport_mode"]}),qt=(0,u.Pu)("agent_client.stream.did_stall",{description:"Number of streams that experienced at least one stall",labelNames:["loop","transport_mode"]}),zt=(0,u.Pu)("agent_client.stream.total",{description:"Total number of streams monitored",labelNames:["loop","transport_mode"]});class Gt{constructor(){this.handlers=new Map}track(e,t){return this.handlers.set(e,{name:e,state:"started",startedAt:Date.now()}),t.then((t=>{const r=this.handlers.get(e);return r&&(r.state="completed",r.endedAt=Date.now()),t})).catch((t=>{const r=this.handlers.get(e);throw r&&(r.state="errored",r.endedAt=Date.now(),r.error=t instanceof Error?t.message:String(t)),t}))}getHandlerStates(){const e=Date.now(),t={};for(const[r,n]of this.handlers)t[r]={state:n.state,durationMs:(n.endedAt??e)-n.startedAt,error:n.error};return t}}class Vt{constructor(e,t,r){this.lastActivityTime=performance.now(),this.lastMeaningfulActivityTime=performance.now(),this.hasLogged=!1,this.hasLoggedAdvisory=!1,this.hasLoggedHeartbeatOnly=!1,this.hasEverStalled=!1,this.paused=!1,this.disposed=!1,this.activityHistory=[],this.ctx=e,"number"==typeof t?(this.thresholdMs=t,this.advisoryThresholdMs=void 0,this.heartbeatOnlyThresholdMs=3*t,this.onStall=r,this.onStallCallback=void 0,this.handlerTracker=void 0,this.loop="nal",this.readTransportMode=void 0):(this.thresholdMs=t.thresholdMs,this.advisoryThresholdMs=t.advisoryThresholdMs,this.heartbeatOnlyThresholdMs=t.heartbeatOnlyThresholdMs??3*t.thresholdMs,this.onStall=t.onStall,this.onStallCallback=t.onStallCallback,this.handlerTracker=t.handlerTracker,this.loop=t.loop??"nal",this.readTransportMode=t.transportMode),this.logPrefix=jt[this.loop],this.startTimer(),this.startAdvisoryTimer(),this.startHeartbeatOnlyTimer(),this.onCtxSignalAbort=()=>{this.trackActivity("ctx.signal","abort"),this.abortedAt=performance.now(),this.emitLifecycleLog(`${this.logPrefix} Stream aborted while stall detector active`,"aborted")},e.signal.addEventListener("abort",this.onCtxSignalAbort)}metricLabels(){return{loop:this.loop,transport_mode:Bt(this.readTransportMode?.())}}trackActivity(e,t){const r={type:e,messageType:t};this.lastActivity=r,"inbound_message"===e?this.lastInboundMessage=r:"outbound_write"===e&&(this.lastOutboundMessage=r);const n=this.activityHistory.at(-1);n?.type===e&&n.messageType===t?n.repeat=(n.repeat??1)+1:(this.activityHistory.push(r),this.activityHistory.length>10&&this.activityHistory.shift())}reset(e="inbound_message",t,r=!0){if(this.trackActivity(e,t),"inbound_message"===e){const e=this.hasLogged,t=this.hasLoggedAdvisory,n=this.hasLoggedHeartbeatOnly;e&&(this.hasLogged=!1,this.emitLogAndMetric()),n&&r&&(this.hasLoggedHeartbeatOnly=!1),t&&(this.hasLoggedAdvisory=!1),this.lastActivityTime=performance.now(),r&&(this.lastMeaningfulActivityTime=performance.now()),void 0===this.timer&&this.startTimer(),void 0===this.advisoryTimer&&this.startAdvisoryTimer(),r&&void 0===this.heartbeatOnlyTimer&&this.startHeartbeatOnlyTimer()}}onStreamEnded(){this.trackActivity("stream","ended"),this.streamEndedAt=performance.now()}onClientSentHeartbeat(){this.lastClientSentHeartbeatAt=performance.now()}onServerSentHeartbeat(){this.lastServerSentHeartbeatAt=performance.now()}setPaused(e){if(!this.disposed&&e!==this.paused&&(this.paused=e,!e)){const e=performance.now();this.lastActivityTime=e,this.lastMeaningfulActivityTime=e,void 0===this.timer&&this.startTimer(),void 0===this.advisoryTimer&&this.startAdvisoryTimer(),void 0===this.heartbeatOnlyTimer&&this.startHeartbeatOnlyTimer()}}restartedAfterLoopGap(e,t){const r=performance.now(),n=r-e;return!(n<5e3||t>=e||(this.reportLoopGap(n,r-t),this.lastActivityTime=r,this.lastMeaningfulActivityTime=r,0))}reportLoopGap(e,t){try{Nt.info(this.ctx,`${this.logPrefix} Stall check ran late - the process was not running, its windows restart`,this.buildLogMetadata({late_ms:e,window_ms:t,stall_type:"loop_gap"}))}catch(e){console.error("Error in stall detection:",e)}}startTimer(){if(this.disposed||this.thresholdMs<=0||void 0!==this.timer)return;let e=0;const t=t=>{e=performance.now()+t,this.timer=setTimeout(r,t)},r=()=>{if(this.paused||this.restartedAfterLoopGap(e,this.lastActivityTime))return void t(this.thresholdMs);const r=this.thresholdMs-(performance.now()-this.lastActivityTime);if(r<=0)return this.timer=void 0,void this.onStallDetected("no_activity");t(r)};t(this.thresholdMs)}startAdvisoryTimer(){if(this.disposed||void 0===this.advisoryThresholdMs||this.advisoryThresholdMs<=0||void 0!==this.advisoryTimer)return;const e=this.advisoryThresholdMs;let t=0;const r=e=>{t=performance.now()+e,this.advisoryTimer=setTimeout(n,e)},n=()=>{if(this.paused||this.restartedAfterLoopGap(t,this.lastActivityTime))return void r(e);const n=e-(performance.now()-this.lastActivityTime);if(n<=0)return this.advisoryTimer=void 0,void this.onAdvisoryDetected();r(n)};r(e)}startHeartbeatOnlyTimer(){if(this.disposed||this.thresholdMs<=0||this.heartbeatOnlyThresholdMs<=0||void 0!==this.heartbeatOnlyTimer)return;let e=0;const t=t=>{e=performance.now()+t,this.heartbeatOnlyTimer=setTimeout(r,t)},r=()=>{if(this.paused||this.restartedAfterLoopGap(e,this.lastMeaningfulActivityTime))return void t(this.heartbeatOnlyThresholdMs);const r=this.heartbeatOnlyThresholdMs-(performance.now()-this.lastMeaningfulActivityTime);if(r<=0)return this.heartbeatOnlyTimer=void 0,void this.onStallDetected("heartbeat_only");t(r)};t(this.heartbeatOnlyThresholdMs)}buildLogMetadata(e){const t=this.ctx.get(Mn),r={...e};t?.modelDetails?.displayName&&(r.model_name=t.modelDetails.displayName);const n=performance.now();void 0!==this.abortedAt&&(r.aborted_ago_ms=n-this.abortedAt),void 0!==this.disposedAt&&(r.disposed_ago_ms=n-this.disposedAt),void 0!==this.lastClientSentHeartbeatAt&&(r.last_client_sent_heartbeat_ago_ms=n-this.lastClientSentHeartbeatAt),void 0!==this.lastServerSentHeartbeatAt&&(r.last_server_sent_heartbeat_ago_ms=n-this.lastServerSentHeartbeatAt),void 0!==this.streamEndedAt&&(r.stream_ended_ago_ms=n-this.streamEndedAt),this.lastInboundMessage&&(r.last_inbound_message_type=this.lastInboundMessage.messageType),this.lastOutboundMessage&&(r.last_outbound_message_type=this.lastOutboundMessage.messageType);const o=[];let s;for(let e=this.activityHistory.length-1;e>=0;e--){const{type:t,messageType:r,repeat:n}=this.activityHistory[e];s!==t&&(s?o.push(`[${t}]`):o.push(`[${t}] (MOST RECENT)`),s=t),o.push(`${r}${n?` (x${n})`:""}`)}return r.activities=o.join("\n"),{reqId:t?.requestId,loop:this.loop,stall:r}}onAdvisoryDetected(){if(this.hasLogged||this.hasLoggedAdvisory)return;if(void 0===this.advisoryThresholdMs||this.advisoryThresholdMs<=0)return;const e=performance.now()-this.lastActivityTime;e=this.heartbeatOnlyThresholdMs){if(this.hasLoggedHeartbeatOnly)return;this.hasLoggedHeartbeatOnly=!0,this.reportStall(e,n)}return}if(this.hasLogged)return;this.hasLogged=!0,this.hasLoggedAdvisory=!0;const t=performance.now()-this.lastActivityTime;this.reportStall(e,t)}reportStall(e,t){const r=this.lastActivity,n=this.lastInboundMessage,o=this.lastOutboundMessage,s=this.ctx.get(Mn);try{const i=this.buildLogMetadata({duration_ms:t,threshold_ms:"heartbeat_only"===e?this.heartbeatOnlyThresholdMs:this.thresholdMs,stall_type:e}),a="heartbeat_only"===e?`${this.logPrefix} Stream receiving heartbeats only - no meaningful data for threshold period`:`${this.logPrefix} Bidirectional stream stall detected - no activity for threshold period`;if(Nt.warn(this.ctx,a,i),Wt.increment(this.ctx,1,{activity_type:r?.type??"unknown",message_type:r?.messageType??"unknown",...this.metricLabels()}),this.hasEverStalled||(this.hasEverStalled=!0,qt.increment(this.ctx,1,this.metricLabels())),this.onStallCallback){const t=performance.now(),i={type:e,lastActivityAgoMs:t-this.lastActivityTime,lastMeaningfulActivityAgoMs:t-this.lastMeaningfulActivityTime,lastActivityType:r?.messageType,lastInboundMessageType:n?.messageType,lastOutboundMessageType:o?.messageType,requestId:s?.requestId,modelName:s?.modelDetails?.displayName,streamEnded:void 0!==this.streamEndedAt,aborted:void 0!==this.abortedAt,lastServerHeartbeatAgoMs:void 0!==this.lastServerSentHeartbeatAt?t-this.lastServerSentHeartbeatAt:void 0,lastClientHeartbeatAgoMs:void 0!==this.lastClientSentHeartbeatAt?t-this.lastClientSentHeartbeatAt:void 0,thresholdMs:"heartbeat_only"===e?this.heartbeatOnlyThresholdMs:this.thresholdMs,handlers:this.handlerTracker?.getHandlerStates(),loop:this.loop};try{this.onStallCallback(i)}catch(e){console.error("Error in stall callback:",e)}}}catch(e){console.error("Error in stall detection:",e)}try{this.onStall?.(function(e){const t=new DOMException(`the stall detector cut the stream: ${e}`,"AbortError");return Object.defineProperty(t,"cursorStallCut",{value:!0}),t}("heartbeat_only"===e?`heartbeats alone for ${this.heartbeatOnlyThresholdMs} ms`:`no activity for ${this.thresholdMs} ms`))}catch(e){console.error("Error in onStall callback:",e)}}emitLifecycleLog(e,t){const r=performance.now()-this.lastActivityTime;try{const n=this.buildLogMetadata({duration_ms:r,event_type:t});Nt.info(this.ctx,e,n)}catch(e){console.error("Error logging stream lifecycle:",e)}}emitLogAndMetric(){const e=performance.now()-this.lastActivityTime;this.emitLifecycleLog(`${this.logPrefix} Stream activity resumed after stall`,"recovered"),Ht.histogram(this.ctx,e,{activity_type:this.lastActivity?.type??"unknown",...this.metricLabels()})}[Symbol.dispose](){this.disposed||zt.increment(this.ctx,1,this.metricLabels()),this.disposed=!0,this.paused=!1,void 0!==this.timer&&(clearTimeout(this.timer),this.timer=void 0),void 0!==this.advisoryTimer&&(clearTimeout(this.advisoryTimer),this.advisoryTimer=void 0),void 0!==this.heartbeatOnlyTimer&&(clearTimeout(this.heartbeatOnlyTimer),this.heartbeatOnlyTimer=void 0),this.ctx.signal.removeEventListener("abort",this.onCtxSignalAbort),this.trackActivity("disposed","disposed"),this.disposedAt=performance.now(),this.emitLifecycleLog(`${this.logPrefix} Stream stall detector disposed`,"disposed")}}const Kt={now:()=>performance.now(),setTimeout(e,t){const r=setTimeout(e,t);return r.unref?.(),r},clearTimeout(e){clearTimeout(e)}},Jt=(0,u.v5)("agent_client.first_message.event_loop_max_lag_ms",{description:"Longest event-loop block between the network phase start and the first server message of a run's first attempt",labelNames:["loop","transport_mode","first_message_slow"]}),Zt=(0,u.v5)("agent_client.first_message.event_loop_total_lag_ms",{description:"Summed event-loop blocking between the network phase start and the first server message of a run's first attempt",labelNames:["loop","transport_mode","first_message_slow"]}),Xt=(0,u.v5)("agent_client.first_message.network_ms",{description:"Time from the network phase start to the first server message of a run's first attempt, on attempts that sampled event-loop lag",labelNames:["loop","transport_mode","first_message_slow"]});var Qt=r("../proto/dist/generated/agent/v1/ask_question_tool_pb.js"),Yt=r("../proto/dist/generated/agent/v1/create_plan_tool_pb.js"),er=r("../proto/dist/generated/agent/v1/pr_management_tool_pb.js"),tr=r("../proto/dist/generated/agent/v1/replace_env_tool_pb.js"),rr=r("../proto/dist/generated/agent/v1/setup_vm_environment_tool_pb.js"),nr=r("../proto/dist/generated/agent/v1/connect_scm_tool_pb.js"),or=r("../proto/dist/generated/agent/v1/generate_image_tool_pb.js"),sr=r("../proto/dist/generated/agent/v1/mcp_auth_tool_pb.js"),ir=r("../proto/dist/generated/agent/v1/switch_mode_tool_pb.js"),ar=r("../proto/dist/generated/agent/v1/web_fetch_tool_pb.js"),cr=r("../proto/dist/generated/agent/v1/web_search_tool_pb.js");class lr extends Error{constructor(e){super(`Deferred interaction response requested for query ${e.id} (${e.query.case??"unknown"})`),this.query=e,this.name="DeferredInteractionResponseError",Object.setPrototypeOf(this,new.target.prototype)}}const ur=e=>new i.Y5({id:e,result:{case:"webSearchRequestResponse",value:new cr.lI({result:{case:"approved",value:new cr.XJ}})}}),dr=(e,t)=>new i.Y5({id:e,result:{case:"webSearchRequestResponse",value:new cr.lI({result:{case:"rejected",value:new cr.yc({reason:t??""})}})}}),hr=e=>new i.Y5({id:e,result:{case:"webFetchRequestResponse",value:new ar.fS({result:{case:"approved",value:new ar.Hs}})}}),pr=(e,t)=>new i.Y5({id:e,result:{case:"webFetchRequestResponse",value:new ar.fS({result:{case:"rejected",value:new ar.m$({reason:t??""})}})}}),fr=(e,t)=>new i.Y5({id:e,result:{case:"askQuestionInteractionResponse",value:new i.zT({result:t})}}),mr=e=>new i.Y5({id:e,result:{case:"switchModeRequestResponse",value:new ir.w$({result:{case:"approved",value:new ir.q5}})}}),gr=(e,t)=>new i.Y5({id:e,result:{case:"switchModeRequestResponse",value:new ir.w$({result:{case:"rejected",value:new ir.rA({reason:t??""})}})}}),wr=(e,t)=>new i.Y5({id:e,result:{case:"createPlanRequestResponse",value:new Yt.gz({result:t})}}),yr=(e,t)=>new i.Y5({id:e,result:{case:"setupVmEnvironmentResult",value:t}}),vr=(e,t)=>new i.Y5({id:e,result:{case:"replaceEnvResult",value:t}}),br=(e,t)=>new i.Y5({id:e,result:{case:"prManagementResult",value:t}}),Sr=e=>new i.Y5({id:e,result:{case:"mcpAuthRequestResponse",value:new sr.h({result:{case:"approved",value:new sr.D5}})}}),kr=(e,t)=>new i.Y5({id:e,result:{case:"mcpAuthRequestResponse",value:new sr.h({result:{case:"rejected",value:new sr.OI({reason:t??"Authentication was rejected"})}})}}),_r=(e,t)=>new i.Y5({id:e,result:{case:"connectScmRequestResponse",value:new nr.qG({result:{case:"rejected",value:new nr.lB({reason:t??"Connecting GitHub was skipped"})}})}}),Cr=(e,t)=>new i.Y5({id:e,result:{case:"generateImageRequestResponse",value:new or.vW({result:{case:"approved",value:new or.l3({description:t??""})}})}}),Er=(e,t)=>new i.Y5({id:e,result:{case:"generateImageRequestResponse",value:new or.vW({result:{case:"rejected",value:new or.Uq({reason:t??""})}})}});class xr extends Error{constructor(e,t={}){super(e),this.name="InteractionListenerStreamClosedError",this.cause=t.cause,Object.setPrototypeOf(this,new.target.prototype)}}xr.telemetryName="InteractionListenerStreamClosedError";var Pr=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Rr=(0,l.h)("ClientInteractionController"),Ir=new Set(["askQuestionInteractionQuery","switchModeRequestQuery","mcpAuthRequestQuery","connectScmRequestQuery"]);class Tr{constructor(e,t,r,n){this.interactionStream=e,this.interactionListener=t,this.queryResponseStream=r,this.stallSuspender=n,this.pendingHumanQueries=0}async run(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,$.VI)(e.withName("ClientInteractionController.run")),!1);e=r.ctx;let n,o=Promise.resolve();for await(const t of this.interactionStream){const r=()=>"interactionQuery"===t.case?this.handleInteractionQuery(e,t.value):this.handleInteractionUpdate(e,t.value);o=o.then(r).catch((r=>{Rr.error(e,"Error handling interaction message",r,{messageCase:t.case}),n??=r}))}if(await o,void 0!==n)throw n}catch(e){t.error=e,t.hasError=!0}finally{Pr(t)}}async handleInteractionUpdate(e,t){await this.interactionListener.sendUpdate(e,t)}handleInteractionQuery(e,t){const r=void 0!==t.query.case&&Ir.has(t.query.case);let n=!1;const o=()=>{r&&!n&&(n=!0,this.pendingHumanQueries--,0===this.pendingHumanQueries&&this.stallSuspender?.setPaused(!1))};r&&(this.pendingHumanQueries++,1===this.pendingHumanQueries&&this.stallSuspender?.setPaused(!0)),(async()=>this.interactionListener.query(e,t))().catch((r=>{const n=function(e,t){switch(e.query.case){case"webSearchRequestQuery":return dr(e.id,t);case"webFetchRequestQuery":return pr(e.id,t);case"askQuestionInteractionQuery":return fr(e.id,new Qt.tz({result:{case:"rejected",value:new Qt.ox({reason:t})}}));case"switchModeRequestQuery":return gr(e.id,t);case"createPlanRequestQuery":return wr(e.id,new Yt.bK({result:{case:"error",value:new Yt.iY({error:t})}}));case"setupVmEnvironmentArgs":return yr(e.id,new rr.r$({result:{case:"success",value:new rr.JH({})}}));case"replaceEnvArgs":return vr(e.id,new tr.dV({result:{case:"failure",value:new tr.uq({errorMessage:t,setupLogs:""})}}));case"prManagementRequestQuery":return br(e.id,new er.HL({result:{case:"error",value:new er.K$({error:t})}}));case"mcpAuthRequestQuery":return kr(e.id,t);case"connectScmRequestQuery":return _r(e.id,t);case"generateImageRequestQuery":return Er(e.id,t);case void 0:return;default:return e.query}}(t,"The client could not show this request to the user");if(!(n instanceof i.Y5))throw r;return Rr.error(e,"Error handling interaction query; answering with a fail-closed response",{queryCase:t.query.case,error:r}),n})).then((e=>(o(),this.queryResponseStream.write(e)))).catch((t=>{Rr.error(e,"Error handling interaction query",t)})).finally(o)}}async function Ar(e,t){let r;try{r=await e(t.signal)}catch(e){if(t.isCanceled())throw new Ke("User aborted request");throw new Ge("Failed to mint LLM Gateway credential",{cause:e instanceof Error?e:void 0,requestId:t.requestId})}if(void 0===r)throw new Ge("LLM Gateway credential minter returned no credential",{requestId:t.requestId});if(""===r.bearerToken.trim())throw new Ge("LLM Gateway credential minter returned an empty bearer token",{requestId:t.requestId});return new i.Ibo({bearerToken:r.bearerToken})}const $r=q("request-context-executor",(e=>new B(e,Z("requestContextArgs"),X("requestContextResult"))),((e,t)=>{t.register(new I(e,Y("requestContextArgs"),Q("requestContextResult")))}));var Mr=r("../agent-kv/dist/serde.js"),Dr=r("../proto/dist/generated/agent/v1/request_context_exec_pb.js"),Or=r("../utils/dist/promise-extras.js");const Fr=15728640,Nr=(0,u.Pu)("agent_client.request_context_blob.prepared",{description:"Prepared RequestContext blob references"}),Lr=(0,u.v5)("agent_client.request_context_blob.bytes",{description:"Serialized RequestContext bytes staged by the client"}),jr=(0,u.v5)("agent_client.request_context_blob.preparation_ms",{description:"Time to hydrate, serialize, and hash RequestContext"});function Ur(e){switch(e.action.case){case"userMessageAction":case"subscriptionNotificationAction":case"resumeAction":case"executePlanAction":return e.action.value;default:return}}class Br{constructor(e,t=62914560){this.parent=e,this.maxTransientBytes=t,this.transientBlobs=new Map,this.persistedBlobIds=new Set,this.transientBytes=0}seed(e,t){return this.seedAll([{blobId:e,blobData:t}])}seedAll(e){const t=new Map;for(const{blobId:r,blobData:n}of e)t.set((0,Mr.nj)(r),n.byteLength);let r=this.transientBytes;for(const[e,n]of t)r-=this.transientBlobs.get(e)?.byteLength??0,r+=n;if(r>this.maxTransientBytes)return!1;for(const{blobId:t,blobData:r}of e)this.transientBlobs.set((0,Mr.nj)(t),r);return this.transientBytes=r,!0}has(e){return this.transientBlobs.has((0,Mr.nj)(e))}hasAll(e){return e.every((e=>this.has(e)))}async getBlob(e,t){const r=(0,Mr.nj)(t),n=this.transientBlobs.get(r);return void 0===n?await this.parent.getBlob(e,t):n}async persistForRemoteRead(e,t){const r=(0,Mr.nj)(t),n=this.transientBlobs.get(r);void 0===n||this.persistedBlobIds.has(r)||(await(0,Or.O$)((()=>this.parent.setBlob(e,t,n)),2),this.persistedBlobIds.add(r))}async setBlob(e,t,r){await this.parent.setBlob(e,t,r)}async setBlobLocallyOnly(e,t,r){await this.parent.setBlobLocallyOnly(e,t,r)}async flush(e){await this.parent.flush(e)}}async function Wr({ctx:e,action:t,resources:r,blobStore:n,mode:o,maxBlobBytes:s,maxInlineDynamicBytes:i=1048576,notesSessionId:a}){const c=performance.now(),l=Ur(t);if(void 0===l)return{kind:"not_applicable"};if("legacy"===o)return t.requestContextParts=void 0,{kind:"legacy"};if(void 0!==t.requestContextParts){const e=void 0===(u=t.requestContextParts)?[]:[u.rulesBlobId,u.skillsBlobId,u.subagentsBlobId,u.mcpsBlobId],r=void 0!==l.requestContext,s=e.length>0&&n.hasAll(e);if(r||s){const e=t.requestContextParts;return"ref_only"===o&&r&&s&&void 0!==e?.dynamicContext&&(l.requestContext=void 0),{kind:"already_prepared"}}}var u;t.requestContextParts=void 0;const d=void 0===l.requestContext,h=l.requestContext??await async function({ctx:e,resources:t,notesSessionId:r}){const n=t.get($r),o=await n.execute(e,new Dr._K({notesSessionId:r})),s="success"===o.result.case?o.result.value.requestContext:void 0;if(void 0===s)throw new Error(`Failed to compute request context: ${o.result.case}`);return s}({ctx:e,resources:r,notesSessionId:a}),p=Math.min(Math.max(0,s),Fr),f=await async function({requestContext:e,mode:t,maxBlobBytes:r,maxInlineDynamicBytes:n}){const o=function(e){const t=e.clone();return t.rules=[],t.nonFileRules=[],t.cloudRule=void 0,t.agentSkills=[],t.skillOptions=void 0,t.customSubagents=[],t.tools=[],t.mcpInstructions=[],t.mcpFileSystemOptions=void 0,t.mcpMetaToolOptions=void 0,{dynamicContext:t,rules:new Dr.T3({rules:e.rules.map((e=>e.clone())),nonFileRules:e.nonFileRules.map((e=>e.clone())),cloudRule:e.cloudRule}),skills:new Dr.CB({agentSkills:e.agentSkills.map((e=>e.clone())),skillOptions:e.skillOptions?.clone()}),subagents:new Dr.yb({customSubagents:e.customSubagents.map((e=>e.clone()))}),mcps:new Dr.vB({tools:e.tools.map((e=>e.clone())),mcpInstructions:e.mcpInstructions.map((e=>e.clone())),mcpFileSystemOptions:e.mcpFileSystemOptions?.clone(),mcpMetaToolOptions:e.mcpMetaToolOptions?.clone()})}}(e),s="ref_only"===t?o.dynamicContext.toBinary().byteLength:void 0;if(void 0!==s&&s>n)return;const i=o.rules.toBinary(),a=o.skills.toBinary(),c=o.subagents.toBinary(),l=o.mcps.toBinary(),u=i.byteLength+a.byteLength+c.byteLength+l.byteLength;if(u>r)return;const[d,h,p,f]=await Promise.all([(0,re.Bk)(i),(0,re.Bk)(a),(0,re.Bk)(c),(0,re.Bk)(l)]),m=[{blobId:d,blobData:i},{blobId:h,blobData:a},{blobId:p,blobData:c},{blobId:f,blobData:l}],g=new Dr.sG({rulesBlobId:d,rulesByteLength:i.byteLength,skillsBlobId:h,skillsByteLength:a.byteLength,subagentsBlobId:p,subagentsByteLength:c.byteLength,mcpsBlobId:f,mcpsByteLength:l.byteLength,dynamicContext:"ref_only"===t?o.dynamicContext:void 0});if("dual"===t)return{kind:"dual",inlineContext:e,byteLength:u,parts:g};if(void 0===s)throw new Error("ref_only request context did not measure dynamic bytes");return{kind:"ref_only",stagedBlobs:m,byteLength:u,parts:g,dynamicByteLength:s}}({requestContext:h,mode:o,maxBlobBytes:p,maxInlineDynamicBytes:Math.min(Math.max(0,i),p)});if(void 0===f)return l.requestContext=h,t.requestContextParts=void 0,Nr.increment(e,1,{mode:o,outcome:"oversized"}),{kind:"oversized"};if("ref_only"===f.kind&&!n.seedAll(f.stagedBlobs))return l.requestContext=h,t.requestContextParts=void 0,Nr.increment(e,1,{mode:o,outcome:"transient_budget_exceeded"}),{kind:"transient_budget_exceeded"};l.requestContext="dual"===f.kind?f.inlineContext:void 0,t.requestContextParts=f.parts;const m=f.byteLength;return Nr.increment(e,1,{mode:o,outcome:d?"hydrated":"inline"}),Lr.histogram(e,m,{mode:o}),jr.histogram(e,performance.now()-c,{mode:o}),{kind:"prepared",byteLength:m,hydrated:d,rulesByteLength:f.parts.rulesByteLength,skillsByteLength:f.parts.skillsByteLength,subagentsByteLength:f.parts.subagentsByteLength,mcpsByteLength:f.parts.mcpsByteLength,dynamicByteLength:"ref_only"===f.kind?f.dynamicByteLength:void 0}}function Hr(e){return Object.keys(e.fileContents).length>0}function qr(e,t){return Object.assign(new(e.getType()),e,t)}function zr(e){return qr(e,{fileContents:{}})}function Gr(e){for(const[t]of e.entries())if(t.symbol===$r.symbol)return e.get($r)}var Vr=r("../proto/dist/generated/agent/v1/cursor_rules_pb.js");const Kr=102400;function Jr(e){return"AGENTS.md"===e||"CLAUDE.md"===e||"CLAUDE.local.md"===e}function Zr({content:e,filename:t}){return Buffer.byteLength(e,"utf8")>Kr?function({content:e,filename:t}){const r=Buffer.from(e,"utf8");let n=Kr;for(;128==(192&r.readUInt8(n));)n--;const o=`[truncated: ${t} is ${Math.round(r.length/1024)} KB; only the first 100 KB is included]`;return`${r.subarray(0,n).toString("utf8")}\n\n${o}`}({content:e,filename:t}):e}function Xr(e){const t=/^\s*("(?:[^"\\]|\\.)*"|'(?:[^']|'')*')\s+#/.exec(e);return null!==t?t[1]:/^\s*["']/.test(e)?e.trim():e.replace(/\s#.*$/,"").trim()}function Qr(e,t){return"description"===e?t.trim():Xr(t)}function Yr(e){const t=e.trim();return"true"===t||"false"!==t&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t)}function en(e){const t=e.trimStart();if(!t.startsWith("---"))return null;const r=t.split("---").filter(Boolean);if(r.length<2)return null;const n=r[0].trim(),o=r.slice(1).join("---").trim(),s={};let i=null,a=null;for(const e of n.split("\n")){const t=e.replace(/\r$/,"");if(/^\s*#/.test(t))continue;const r=t.match(/^\s+-\s+(.*)$/);if(r&&a){let e=Xr(r[1]);(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1));const t=s[a];Array.isArray(t)&&t.push(e);continue}const n=t.startsWith(" ")||t.startsWith("\t");if(i&&n){const e=t.trim(),r=e.indexOf(":");if(-1===r)continue;const n=e.slice(0,r).trim(),o=Xr(e.slice(r+1)),c=Yr(o),l=`${i}.${n}`;""===o?(s[l]=[],a=l):"metadata.environments"===l||"metadata.disabledEnvironments"===l||"metadata.scopedTo"===l?(s[l]=String(c).split(",").map((e=>e.trim())).filter(Boolean),a=null):(s[l]=c,a=null);continue}i=null,a=null;const o=t.indexOf(":");if(-1===o)continue;const c=t.slice(0,o).trim(),l=Qr(c,t.slice(o+1));if(""===l&&"metadata"===c){i=c;continue}if("globs"===c&&""===l){s.globs=[],a="globs";continue}const u=Yr(l);s[c]="metadata.environments"!==c&&"metadata.disabledEnvironments"!==c&&"metadata.scopedTo"!==c?u:String(u).split(",").map((e=>e.trim())).filter(Boolean)}return{frontmatter:s,rawFrontmatter:`---\n${n}\n---`,body:o}}function tn(e){const t=e.replace(/\\/g,"/").replace(/^[A-Za-z]:/,(e=>e.toLowerCase())),r=[];for(const e of t.split("/"))""!==e&&"."!==e&&(".."!==e?r.push(e):r.pop());return`${t.startsWith("/")?"/":""}${r.join("/")}`}function rn(e,t){return"/"===t?e.length>1:e.startsWith(`${t}/`)}const nn=[[".cursor","skills"],[".cursor","skills-cursor"],[".claude","skills"],[".claude","plugins"],[".codex","skills"],[".grok","skills"],[".agents","skills"],[".cursor","plugins"]];class on{constructor(){this.allowed=!1}observeHeaders(e){this.allowed="1"===e.get("x-cursor-lazy-rule-bodies")}isAllowed(){return this.allowed}}function sn(e){if("success"!==e.result.case)return e;const t=e.result.value,r=t.requestContext;if(void 0===r)return e;const n=function(e){const t=e.env?.workspacePaths??[];let r=!1;const n=e.rules.map((e=>{if(!function(e,t){if(!0===e.bodyOmitted||0===e.content.length||void 0!==e.parseError||e.source!==Vr.gv.UNSPECIFIED||void 0!==e.plugin||void 0!==e.marketplace||void 0!==e.pluginId||void 0!==e.marketplaceId)return!1;if(0===e.scopedTo.length&&0===e.frontmatter.length&&e.content.trimStart().startsWith("---"))return!1;const r=tn(e.fullPath),n=r.startsWith("/"),o=r.split("/").filter((e=>e.length>0)),s=o.at(-1);if(void 0===s||function(e){return"SKILL.md"===e.at(-1)||e.some(((t,r)=>nn.some((([n,o])=>t===n&&e[r+1]===o))))}(o))return!1;const i=t.map(tn);if(!i.some((e=>rn(r,e))))return!1;const a=function(e,t){let r=e.length-1;for(let t=e.length-2;t>=0;t--)if(".cursor"===e[t]&&"rules"===e[t+1]){r=t;break}return`${t?"/":""}${e.slice(0,r).join("/")}`}(o,n),c=a!==`${n?"/":""}${o.slice(0,-1).join("/")}`,l=e.type?.type.case;return"fileGlobbed"===l?s.endsWith(".mdc")&&c:"global"===l&&!!(Jr(s)||s.endsWith(".mdc")&&c)&&!i.includes(a)&&i.some((e=>rn(a,e)))}(e,t))return e;r=!0;const n=Object.assign(new(e.getType()),e);return n.content=e.content.split("\n").find((e=>e.trim().length>0))??"",n.bodyOmitted=!0,n}));return r?Object.assign(new(e.getType()),e,{rules:n}):e}(r);return n===r?e:new Dr._G({result:{case:"success",value:Object.assign(new(t.getType()),t,{requestContext:n})}})}function an(e){return void 0!==e&&Number.isFinite(e)&&Number.isInteger(e)}function cn(e,t){const{rulesByteLength:r,skillsByteLength:n}=e,{subagentsByteLength:o,mcpsByteLength:s}=e;if(!(an(r)&&an(n)&&an(o)&&an(s)))return;const i=t?.dynamicByteLength;return{bytes:r+n+o+s+(i??0),bytesSource:"blob_parts",rulesBytes:r,skillsBytes:n,mcpBytes:s,subagentsBytes:o,...an(i)?{dynamicBytes:i}:{}}}const ln=["alpn_failure","poll_seqno_gap","append_fatal","http_464","http_404_unimplemented","socket_reset","stream_closed_early","idle_deadline","stall","other"],un=/\bHTTP (\d{3})\b/;function dn(e){const t=e.message;return"string"==typeof t?t:""}function hn(e){return e instanceof Error&&("AbortError"===e.name||e.name===at)}const pn={serverCap:3,transportCap:10},fn={alpn_failure:"server",poll_seqno_gap:"server",append_fatal:"by_signature",http_464:"server",http_404_unimplemented:"server",socket_reset:"transport",stream_closed_early:"server",idle_deadline:"server",stall:"transport",other:"server"};function mn(e){return{action:"retry",countAsServerError:!0,countAsTransportError:!1,transportFailureKind:e}}function gn(e,t,r){const n=r.attemptRequestId,o=!0===t.endless,s=r.retriesEnabled||o,i=(e,n)=>!o&&(e>=n||void 0!==t.sharedCap&&r.serverErrorRetries+r.transportErrorRetries>=t.sharedCap);let a=e instanceof He?e:ct(e,{requestId:n});const c=a instanceof Ke&&("owner"===r.abortOrigin||function(e){const t=e.displayInfo?.errorCode;return void 0!==t&&Ye.has(t)}(a)),l="stall_detector"===r.abortOrigin&&!c&&(a instanceof Ke||a instanceof qe),u="owner"===r.abortOrigin&&a instanceof qe&&Tt(a),d=function(e,t,r){return t.stalled?"stall":t.userStop?"other":function(e,t={}){const r=function(e){const t=[],r=new Set;let n=e;for(;"object"==typeof n&&null!==n&&!r.has(n);)r.add(n),t.push(n),n="cause"in n?n.cause:void 0;return t}(e);if(r.some((e=>"cursorBidiAppendFatal"in e)))return"append_fatal";const n=r.map(dn),o=e=>n.some((t=>t.includes(e))),s=function(e){return mt(e)?.code}(e),i=void 0===t.transportMode;if(i&&s===ye.Code.Unavailable&&o("ALPN protocol failed to negotiate"))return"alpn_failure";if((i||"http1_poll"===t.transportMode)&&s===ye.Code.Unavailable&&o("Unexpected seqno"))return"poll_seqno_gap";const a=n.map((e=>un.exec(e)?.[1])).find((e=>void 0!==e));return i&&s===ye.Code.Unknown&&"464"===a?"http_464":i&&s===ye.Code.Unimplemented&&"404"===a?"http_404_unimplemented":s===ye.Code.DeadlineExceeded&&function(e){const t=ft(e);return void 0===t?void 0:ht(t)?.error}(e)===Le.yM.TIMEOUT?"idle_deadline":i&&s===ye.Code.Unknown&&o("unsupported content type null")?"stream_closed_early":kt(e)||function(e){return e instanceof Error&&"isTransport"in e&&!0===e.isTransport}(e)||r.some(hn)?"socket_reset":"other"}(e,r)}(e,{stalled:l,userStop:c||u},{transportMode:r.attemptTransportMode}),h=(e,t={})=>({action:"throw",error:e,...t,transportFailureKind:d}),p=(e,n,{immediateFirstRetry:o})=>s?i(r.transportErrorRetries,t.transportCap)?h(e(),{countAsTransportError:!0}):function(e,t){return{action:"retry",countAsServerError:!1,countAsTransportError:!0,transportFailureKind:e,...t?{noBackoff:!0}:{}}}(d,o&&0===r.transportErrorRetries):h(n(),{countAsTransportError:!0}),f=()=>({cause:a.cause,requestId:n,transportErrorRetries:r.transportErrorRetries,connectCode:a.displayInfo?.connectCode});if(l){if(s&&void 0!==r.stallRetryElapsedMs&&r.stallRetryElapsedMs>=18e4)return h(xt(f()),{countAsTransportError:!0});const e=p((()=>xt(f())),(()=>xt({...f(),transportErrorRetries:void 0})),{immediateFirstRetry:!1});return"retry"===e.action?{...e,stall:!0}:e}if(a instanceof Ke&&!c&&Tt(a)&&(a=new qe(a.message,{cause:a.cause,requestId:n,displayInfo:a.displayInfo,isTransport:!0})),u)return h(new Ke(a.message,{cause:a.cause,requestId:n,displayInfo:a.displayInfo}));if(!0===t.retryAllInference&&(a instanceof ze||a instanceof Ge)&&function(e){const t=e.displayInfo?.inferenceRequestErrorType;return void 0!==t&&!st.some((e=>e===t))}(a))return i(r.serverErrorRetries,t.serverCap)?h(a):mn(d);if(a instanceof Ke||a instanceof ze||a instanceof Ge)return h(a);const m=function(e){return At(e.displayInfo?.errorDetails)}(a);if(a instanceof qe&&void 0!==m){const e=(r.rateLimitRetryElapsedMs??0)+m;return!s||!o&&e>3e5?h(a):{action:"retry",countAsServerError:!1,countAsTransportError:!1,transportFailureKind:d,retryAfterMs:m,rateLimit:!0}}if(a instanceof qe&&(!0===a.isTransport||function(e,t){const r=fn[e];return"by_signature"===r?kt(t):"transport"===r}(d,a)||"owner"!==r.abortOrigin&&Tt(a))){const e=function(e){const t=e.displayInfo,r=t?.title,n=t?.detail;return r&&n?{...t,title:r,detail:n}:void 0}(a);return p((()=>function(e){const{cause:t,requestId:r,transportErrorRetries:n,connectCode:o,ownCopy:s}=e;if(void 0!==s)return new qe(_t(n)?"Connection failed repeatedly":"Connection failed",{cause:t,requestId:r,displayInfo:{...s,isRetryable:!0,connectCode:o??s.connectCode}});const i=function(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){t.add(r);const e=lt(r)?gt(r):r.message;if(Pt.test(e))return e;r=r.cause}}(t),a=void 0===i?"Please check your network connection and try again.":"Please check your proxy settings and try again.";return _t(n)?new qe("Connection failed repeatedly",{cause:t,requestId:r,displayInfo:{title:"Connection failed",detail:`${void 0===i?"":`${i}. `}The connection failed ${Ct(n)} times. ${a}`,isRetryable:!0,connectCode:o}}):new qe("Connection failed",{cause:t,requestId:r,displayInfo:{title:"Connection failed",detail:`${i??"The connection was interrupted"}. ${a}`,isRetryable:!0,connectCode:o}})}({...f(),...void 0===e?{}:{ownCopy:e}})),(()=>a),{immediateFirstRetry:!0})}return s?i(r.serverErrorRetries,t.serverCap)?h(function(e){const{classified:t,requestId:r,serverErrorRetries:n}=e,o=t.displayInfo;return new qe(t.message,{cause:t.cause,requestId:r,displayInfo:{...o,title:o?.title||"Server error",detail:o?.detail||`The server failed ${Ct(n)} times. Please try again, or contact support if the issue persists.`,isRetryable:!0}})}({classified:a,requestId:n,serverErrorRetries:r.serverErrorRetries})):mn(d):h(a)}var wn=r("../proto/dist/generated/agent/v1/mcp_pb.js");const yn=(0,y.cF)(Symbol("agentTransportTimingRecorder"),void 0),vn=(0,l.h)("@anysphere/agent-client:turn-runner"),bn=1e3,Sn=6e4,kn=(0,u.Pu)("agent_client.turn.retry",{description:"Turn attempts retried by the turn runner",labelNames:["attempt","reason","loop"]});function _n(e){return e<=1?"1":2===e?"2":e<=5?"3_5":"gt5"}function Cn(e){return!0===e.stall?"stall":!0===e.rateLimit?"rate_limit":e.countAsTransportError?"transport":e.countAsServerError?"server":!0===e.immediate?"speculative":"other"}const En=new Set(["textDelta","thinkingDelta","thinkingCompleted","partialToolCall","toolCallDelta","toolCallStarted","toolCallCompleted","tokenDelta"]);function xn(e){const{message:t}=e;return("textDelta"!==t.case||void 0===t.value||!("isServerNotice"in t.value)||!0!==t.value.isServerNotice)&&En.has(t.case??"")}async function Pn(e,t,r){await new Promise(((n,o)=>{if(t?.aborted)return void o(new Ke("Cancelled during backoff"));const s=new AbortController,i=setTimeout(a,e);function a(){clearTimeout(i),t?.removeEventListener("abort",c),s.abort(),n()}function c(){clearTimeout(i),s.abort(),o(new Ke("Cancelled during backoff"))}t?.addEventListener("abort",c,{once:!0});try{r?.(s.signal)?.then(a,(()=>{}))}catch{}}))}function Rn(e,t){return e.length===t.length&&e.every(((e,r)=>{const n=t[r];return void 0!==n&&e.byteLength===n.byteLength&&e.every(((e,t)=>e===n[t]))}))}function In(e){const{connectCode:t,connectCodeName:r,...n}=e;return void 0===r?n:{...n,connectCode:r}}async function Tn(e){const{ctx:t,checkpointHandler:r,runOptions:n,requestId:o,hooks:s,cancellation:a}=e,c=e.originalRequestId??o;let l=bn;const u=async(r,o,s,i,a)=>{if(s||(l=bn),void 0!==e.backoff)return void await e.backoff(r,o,i.retryAfterMs);if(!0===i.rateLimit&&void 0!==i.retryAfterMs){const n=i.retryAfterMs+1e3*Math.random();return e.logging&&vn.info(t,`[${e.logging.tag}] Waiting out a rate limit`,{attempt:r,retryAfterMs:i.retryAfterMs,selectedDelayMs:n}),void await Pn(n,o)}const c=s?function(e,t){const r=Math.min(3e5,3*e);return t??bn+(r-bn)*Math.random()}(l,n.fixedRetryDelayMs):function(e,t,r){const n=t?100:bn,o=r??Math.min(n*2**e,Sn);return o+(void 0===r?.2*o*Math.random():0)}(r,n.isRunningInTest,n.fixedRetryDelayMs),u=function(e,t){if(void 0===t||t<=e)return e;const r=Math.min(t,Sn),n=Math.min(r+.2*r*Math.random(),Sn);return Math.max(e,n)}(c,i.retryAfterMs);u!==c&&e.logging&&vn.info(t,`[${e.logging.tag}] Waiting for Retry-After`,{attempt:r,retryAfterMs:i.retryAfterMs,computedDelayMs:c,selectedDelayMs:u,endlessRetries:s}),s&&(l=c,e.logging&&vn.info(t,`[${e.logging.tag}] Endless retry delay selected`,{selectedDelayMs:u,attempt:r,retryCategory:i.countAsServerError?"server":"transport",endlessRetries:s}));const{retryWake:d}=n;await Pn(u,o,void 0===d?void 0:e=>d({error:a,delayMs:u,waitEnded:e}))};let d,h,p,f,m,g,w=e.state,y=e.action,v=0,b=o,S=0,k=0,_=!1,C=0;const E=()=>{_&&(n.onConnectionStateChange?.({state:"connected"}),_=!1)},x=(e,t)=>()=>{e===v&&("progress"===t?m=!0:g=!0,E())},P=e=>({handleCheckpoint:async(t,n,o)=>{e===v&&(m=!0),await r.handleCheckpoint(t,n,o),e===v&&(d=n,h=o?.resumeEligibility??"eligible",E())},getLatestCheckpoint:()=>r.getLatestCheckpoint()});for(;;){if(t.canceled)throw a.toCancelledError(void 0,b);if(d=void 0,h=void 0,m=!1,g=!1,s.beginAttempt?.({attempt:v,originalRequestId:c}),v>0?(b=(0,ge.C)(),await(n.onRetryStarting?.(v,{actionCase:y.action.case,conversationState:w,isResume:"resumeAction"===y.action.case,attemptRequestId:b})),e.logging&&vn.info(t,`[${e.logging.tag}] Retrying attempt ${v}`,{attempt:v,actionCase:y.action.case,requestId:b,originalRequestId:c}),"resumeAction"===y.action.case&&(await(n.onRetryResuming?.({checkpointState:w,nextAttempt:v,reason:"resume_action"})),e.logging&&vn.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:v,reason:"resume_action"}))):(e.logging&&vn.info(t,`[${e.logging.tag}] Initial request`,{attempt:v,actionCase:y.action.case,requestId:b}),!0===e.notifyInitialResume&&"resumeAction"===y.action.case&&(await(n.onRetryResuming?.({checkpointState:w,nextAttempt:v,reason:"resume_action"})),e.logging&&vn.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:v,reason:"resume_action"}))),t.canceled)throw a.toCancelledError(void 0,b);try{return await s.runAttempt({state:w,action:y,checkpointHandler:P(v),attempt:v,attemptRequestId:b,notifyConnected:E,notifyApplicationProgress:x(v,"progress"),notifyApplicationActivity:x(v,"activity")}),E(),void(e.logging&&vn.info(t,`[${e.logging.tag}] Request successful`,{attempt:v,actionCase:y.action.case,requestId:b,originalRequestId:c}))}catch(r){if(!0===a.shortCircuit?.(r))throw a.toCancelledError(r,b);const o=!0===n.endlessRetries?.(),E=e.nowMs?.()??Date.now();(m||g)&&(p=void 0,f=void 0);const x=void 0===p?void 0:E-p,P=void 0===f?void 0:E-f;let T=s.classify(r,{attempt:v,attemptRequestId:b,originalRequestId:c,serverErrorRetries:S,transportErrorRetries:k,stallRetryElapsedMs:x,rateLimitRetryElapsedMs:P,endlessRetries:o});if("retry"===T.action){const n=!("resumeAction"===y.action.case&&w.pendingToolCalls.length>0)&&("resumeAction"===y.action.case||!0===e.noProgressGuardCountsReplays&&v>0);void 0!==d?C=0:n&&m&&(C++,C>=2&&(e.logging&&vn.warn(t,`[${e.logging.tag}] Resume attempts are streaming but not producing checkpoints; stopping automatic resume`,{noProgressResumeFailures:C,attempt:v,requestId:b,originalRequestId:c,errorName:r instanceof Error?r.name:typeof r}),T={action:"throw",error:new qe("Agent turn stopped after repeated resume attempts made no progress",{cause:r instanceof Error?r:void 0,requestId:b,displayInfo:{title:"Agent stopped retrying",detail:"The connection was interrupted repeatedly without saving progress, so the agent stopped to avoid repeating the same work. Retry to continue from the last saved state.",isRetryable:!0}}),transportFailureKind:T.transportFailureKind}))}const A={...void 0===T.transportFailureKind?{}:{transportFailureKind:T.transportFailureKind},...void 0===e.loop?{}:{loop:e.loop}},$=e.logging?.diagnostics?.(r);if(e.logging){const e="retry"===T.action?`RETRY (countAsServerError=${T.countAsServerError}, countAsTransportError=${T.countAsTransportError})`:`THROW ${T.error.kind}`;vn.warn(t,`[AGENT_ERROR_DIAGNOSTICS] requestId=${b} originalRequestId=${c} decision=${e}`,{decision:e,willRetry:"retry"===T.action,enableAgentRetries:n.enableAgentRetries??!1,endlessRetries:o,isRunningInTest:n.isRunningInTest??!1,serverErrorRetries:S,transportErrorRetries:k,attempt:v,requestId:b,originalRequestId:c,...A,...$})}if("throw"===T.action){if(0===v){const r={attempt:0,actionCase:y.action.case,error:T.error,requestId:b,originalRequestId:c,enableAgentRetries:!0===n.enableAgentRetries,endlessRetries:o,stallAborted:!1,abortSources:[]};try{await(n.onErrorNotRetried?.(s.buildNonRetriedErrorInfo?.(r)??r))}catch(r){e.logging&&vn.warn(t,`[${e.logging.tag}] onErrorNotRetried callback failed`,{error:String(r),requestId:b,originalRequestId:c})}}throw e.logging&&vn.warn(t,`[${e.logging.tag}] Error not retryable`,{...A,...$,attempt:v,actionCase:y.action.case,requestId:b,originalRequestId:c,errorName:T.error.name,...!0===e.logging.includeErrorObjects?{error:T.error}:{},serverErrorRetries:S,transportErrorRetries:k}),T.error}const M=v+1;if("ineligible_terminal_turn"===h)return void(e.logging&&vn.warn(t,`[${e.logging.tag}] Terminal checkpoint received before retryable error; completing without automatic resume`,{errorName:r instanceof Error?r.name:typeof r,errorMessage:r instanceof Error?r.message:String(r)}));!0!==T.immediate&&(n.onConnectionStateChange?.({state:"reconnecting",attempt:M,trigger:{...A,...s.reconnectTrigger?.(r,T,{originalRequestId:c,failedAttemptRequestId:b,nextAttempt:M})??{originatingRequestId:c,attemptRequestId:b}}}),_=!0),T.countAsServerError&&S++,T.countAsTransportError&&k++,!0===T.stall?p??=E:p=void 0,!0===T.rateLimit?f??=E:f=void 0,v=M;try{kn.increment(t,1,{attempt:_n(M),reason:Cn(T),loop:e.loop??"nal"})}catch{}void 0!==d&&(I=d,Rn((R=w).turns,I.turns)&&Rn(R.rootPromptMessagesJson,I.rootPromptMessagesJson)||(l=bn),w=d,y=new i.QFf({action:{case:"resumeAction",value:new i.qKo}})),s.onRetryCommitted?.(),!0===T.immediate||!0===T.noBackoff&&void 0===T.retryAfterMs||await u(v,t.signal,o,T,r)}}var R,I}var An=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},$n=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Mn=(0,y.cF)(Symbol("agentStreamMetadata"),void 0),Dn=(0,l.h)("@anysphere/agent-client:abort"),On=(0,l.h)("@anysphere/agent-client:retry"),Fn=(0,l.h)("@anysphere/agent-client:request-context-blob");async function Nn({ctx:e,action:t,resources:r,blobStore:n,options:o,source:s,transportMode:i,notifyBytes:a}){!0===o.omitRequestContextFileContents&&function(e){const t=Ur(e);if(void 0===t)return;const r=t.requestContext;void 0!==r&&Hr(r)&&(t.requestContext=zr(r));const n=e.requestContextParts,o=n?.dynamicContext;void 0!==n&&void 0!==o&&Hr(o)&&(e.requestContextParts=qr(n,{dynamicContext:zr(o)}))}(t);try{const s=await Wr({ctx:e,action:t,resources:r,blobStore:n,mode:i??o.requestContextBlobTransportMode??"legacy",maxBlobBytes:o.requestContextBlobMaxBytes??Fr,maxInlineDynamicBytes:o.requestContextDynamicInlineMaxBytes??1048576,notesSessionId:o.conversationId});if(!0===a){const e=function({prepared:e,parts:t}){return"prepared"===e.kind?cn(e,{dynamicByteLength:e.dynamicByteLength}):"already_prepared"===e.kind&&void 0!==t?cn(t):void 0}({prepared:s,parts:t.requestContextParts});void 0!==e&&o.onRequestContextBytes?.(e)}}catch(r){t.requestContextParts=void 0,Fn.warn(e,"Failed to prepare request context blob; using legacy fallback",{actionCase:t.action.case,errorName:r instanceof Error?r.name:typeof r,source:s})}}const Ln=e=>{const t=[];switch(t.push(e.message.case),e.message.case){case"conversationAction":t.push(e.message.value.action.case);break;case"execClientMessage":case"execClientControlMessage":case"kvClientMessage":case"execServerMessage":case"execServerControlMessage":t.push(e.message.value.message.case);break;case"interactionResponse":t.push(e.message.value.result.case);break;case"interactionUpdate":switch(t.push(e.message.value.message.case),e.message.value.message.case){case"partialToolCall":case"toolCallCompleted":case"toolCallStarted":t.push(e.message.value.message.value.toolCall?.tool.case);break;case"toolCallDelta":t.push(e.message.value.message.value.toolCallDelta?.delta.case)}break;case"interactionQuery":t.push(e.message.value.query.case)}return t.filter((e=>void 0!==e)).join(":")};function jn(e){if(e instanceof Error)return`${e.name}: ${e.message}`;if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e||"bigint"==typeof e)return String(e);if(null==e)return String(e);try{const t=JSON.stringify(e);return"string"==typeof t?t:"unserializable error"}catch{return"unserializable error"}}async function Un(e,t,r){for await(const n of t)switch(n.event.case){case"stdout":await r.sendUpdate(e,a.shellOutputDelta({case:"stdout",value:new he.o0({data:n.event.value.data})}));break;case"stderr":await r.sendUpdate(e,a.shellOutputDelta({case:"stderr",value:new he.Db({data:n.event.value.data})}));break;case"exit":await r.sendUpdate(e,a.shellOutputDelta({case:"exit",value:new he.vb({code:n.event.value.code,aborted:n.event.value.aborted})}))}}function Bn(e){return e instanceof Error?e.name:void 0}class Wn{constructor(e,t,r={}){this.client=e,this.endpointUrl=t,this.options=r,this.hasStartedStream=!1}async run(e,t,r,n,o,s,i,a,l,u,d){const h={stack:[],error:void 0,hasError:!1};try{if(void 0!==d.maxSteps)throw new Ve(d.maxSteps);const g=!0===d.omitRequestContextFileContents?function(e){const t=Gr(e);return void 0===t?e:new J(e,[G($r,{execute:async(e,r,n)=>function(e){if("success"!==e.result.case)return e;const t=e.result.value,r=t.requestContext;return void 0!==r&&Hr(r)?new Dr._G({result:{case:"success",value:qr(t,{requestContext:zr(r)})}}):e}(await t.execute(e,r,n))})])}(s):s,w=!0===d.lazyFileScopedRuleBodies?new on:void 0,y=void 0===w?g:function(e,t){const r=Gr(e);return void 0===r?e:new J(e,[G($r,{execute:async(e,n,o)=>{const s=await r.execute(e,n,o);return void 0!==o?.execId&&t.isAllowed()?sn(s):s}})])}(g,w),v=void 0===w?d:{...d,onHeader:e=>{w.observeHeaders(e),d.onHeader?.(e)}},b=new Br(i),S=d.generationUUID??(0,ge.C)(),k=new c,_=(m=k,p=o,f=e=>{m.observe(e.id)},{sendUpdate:(e,t)=>p.sendUpdate(e,t),query:(e,t)=>(f(t),p.query(e,t)),enqueuePostTurnEndedWork:p.enqueuePostTurnEndedWork?.bind(p),flushPostTurnEndedWork:p.flushPostTurnEndedWork?.bind(p)}),C={sources:[],abortReasonName:void 0,abortReasonMessage:void 0},E=e=>{const t=function(e){const t=ft(e);return void 0===t?void 0:We(ht(t))}(e),r=C.sources.includes("stall_detector")||!0===t?.stallAborted,n=(o=C.sources).some((e=>"stall_detector"!==e))?"owner":o.includes("stall_detector")?"stall_detector":"none";var o;const s=function(e){const t={errorName:Bn(e)},r=mt(e);if(void 0===r)return t;const n=function(e){if(null!==e&&"object"==typeof e&&"cause"in e)return e.cause}(r),o=function(e){if(null===e||"object"!=typeof e||!("code"in e))return;const t=e.code;return"string"==typeof t||"number"==typeof t?t:void 0}(n),s=Bn(n);return{...t,underlyingConnectError:{code:r.code,codeName:ye.Code[r.code],cause:void 0!==o||void 0!==s?{code:o,name:s}:void 0}}}(e),i=s.underlyingConnectError;return{relayed:t,stallAborted:r,abortOrigin:"none"===n&&r?"stall_detector":n,reading:void 0===t?{errorName:s.errorName,connectCode:i?.code,connectCodeName:i?.codeName,connectCause:i?.cause,abortSources:[...C.sources],abortReasonName:C.abortReasonName,...void 0===i?{}:{underlyingConnectError:i}}:{errorName:t.errorName,connectCode:t.connectCode,connectCodeName:t.connectCodeName,connectCause:t.connectCause,...(a=t.loop,"nal"===a||"local_loop"===a||"module"===a?{loop:t.loop}:{}),...void 0===t.transportMode?{}:{transportMode:t.transportMode}}};var a};let x=0,P=0;const R={networkPhaseStartedAt:performance.now()};try{d.onNetworkPhaseStart?.()}catch(t){On.warn(e,"onNetworkPhaseStart callback failed",{error:String(t)})}const I=An(h,(0,$.VI)(e.withName("networkPhase")),!1);e=I.ctx,await(0,$.MG)(I.span,(()=>Tn({ctx:e,state:t,action:r,checkpointHandler:l,runOptions:d,requestId:S,loop:this.options.loop??"nal",notifyInitialResume:!0,logging:{...this.options.retryLogging??{tag:"nal_agent_retries",includeErrorObjects:!0},diagnostics:e=>{const{stallAborted:t,abortOrigin:r,reading:n}=E(e);return{stallAborted:t,abortOrigin:r,...In(n)}}},cancellation:{toCancelledError:()=>new Ke("Request cancelled")},hooks:{beginAttempt:()=>{C.sources=[],C.abortReasonName=void 0,C.abortReasonMessage=void 0,P=++x},runAttempt:async({state:t,action:r,checkpointHandler:o,attempt:s,attemptRequestId:i,notifyConnected:c,notifyApplicationProgress:l,notifyApplicationActivity:d})=>{const h=function(e,t,r){return{sendUpdate:async(n,o)=>{if(t===r())return e.sendUpdate(n,o);"toolCallCompleted"===o.message?.case&&On.warn(n,"nal.await_stall.stale_completion_dropped",{attemptGen:t,currentGen:r()})},query:async(n,o)=>{if(t!==r())throw new Ke("Stale query from previous attempt");return e.query(n,o)},enqueuePostTurnEndedWork:e.enqueuePostTurnEndedWork?t=>e.enqueuePostTurnEndedWork(t):void 0,flushPostTurnEndedWork:e.flushPostTurnEndedWork?t=>e.flushPostTurnEndedWork(t):void 0}}(_,P,(()=>x));await this.runInternal(e,t,r,n,h,y,b,a,o,u,v,i,S,k,C,c,l,d,s,R)},classify:(e,t)=>{const{abortOrigin:r,relayed:n}=E(e),o=gn(e,function(e,t,r=pn){const n=function(e){if(void 0!==e&&Number.isFinite(e))return Math.min(Math.max(Math.floor(e),1),100)-1}(e.maxRetries),o=void 0===n?r:{serverCap:n,transportCap:n};return{serverCap:o.serverCap,transportCap:!0===e.isRunningInTest?Math.min(o.transportCap,2):o.transportCap,...void 0===n?{}:{sharedCap:n},endless:t.endlessRetries,retryAllInference:!0===e.retryAllInferenceErrors}}(d,t),{...t,retriesEnabled:d.enableAgentRetries??!1,abortOrigin:r}),s=n?.transportFailureKind;return"string"==typeof(i=s)&&ln.includes(i)?{...o,transportFailureKind:s}:o;var i},buildNonRetriedErrorInfo:e=>({...e,enableAgentRetries:d.enableAgentRetries??!1,stallAborted:E(e.error).stallAborted,abortSources:[...C.sources],abortReasonName:C.abortReasonName,abortReasonMessage:C.abortReasonMessage}),reconnectTrigger:(e,t,r)=>{const{relayed:n,stallAborted:o,reading:s}=E(e),i=e instanceof He?e:ct(e,{requestId:r.failedAttemptRequestId});return{errorClass:n?.errorName??i.name,connectCode:s.connectCode,connectCodeName:s.connectCodeName,errorCode:i.displayInfo?.errorCode,countAsServerError:t.countAsServerError,countAsTransportError:t.countAsTransportError,stallAborted:o,originatingRequestId:r.originalRequestId,attemptRequestId:r.failedAttemptRequestId,...void 0===s.transportMode?{}:{transportMode:s.transportMode},endpointUrl:this.endpointUrl}},onRetryCommitted:()=>a.reopen()}})))}catch(e){h.error=e,h.hasError=!0}finally{$n(h)}var p,f,m}async runInternal(e,t,r,n,o,s,a,c,l,u,p,f,m,g,w,y,v,b,S,k,_="agent.request.attempt"){const C={stack:[],error:void 0,hasError:!1};try{const P=e;e=this.options.prepareAttemptContext?.(e,{attempt:S,attemptRequestId:f,originalRequestId:m,runOptions:p})??e;const R=An(C,(0,$.VI)(e.withName(_)),!1);R.span.setAttribute("agent.attempt",S),R.span.setAttribute("agent.request_id",f),R.span.setAttribute("agent.original_request_id",m),e=R.ctx,e=(0,$.Mf)(e,"agent.request_id",f),e=(e=(0,$.Mf)(e,"agent.original_request_id",m)).with(Mn,{requestId:f,rootParentRequestId:p.rootParentRequestId,modelDetails:n});const I=new Set(w.sources);let T=void 0!==w.abortReasonName||void 0!==w.abortReasonMessage;const M=(t,r)=>{if(I.has(t))return;I.add(t),w.sources=[...I];const n=(e=>{const t="string"==typeof e?.abortReasonName?e.abortReasonName:void 0,r="string"==typeof e?.abortReasonMessage?e.abortReasonMessage:void 0;if(void 0!==t||void 0!==r)return{abortReasonName:t,abortReasonMessage:r}})(r);T||void 0===n||(T=!0,w.abortReasonName=n.abortReasonName,w.abortReasonMessage=n.abortReasonMessage),Dn.error(e,"Agent client stream abort",new Error(t),{abortSource:t,requestId:f,conversationId:p.conversationId,...r??{}})};if(e.signal.aborted){const t=e.signal.reason;M("ctx_signal_abort",ue(t))}else e.signal.addEventListener("abort",(()=>{const t=e.signal.reason;M("ctx_signal_abort",ue(t))}),{once:!0});const[D,O]=e.withCancel();if(c.signal?.aborted){const e=c.signal?.reason;M("conversation_action_abort",ue(e)),O()}else c.signal?.addEventListener("abort",(()=>{const e=c.signal?.reason;M("conversation_action_abort",ue(e)),O()}),{once:!0});if(e.canceled||D.canceled){const t={ctxCanceled:e.canceled,softCancel:D.canceled};throw M("pre_run_cancel",t),new Ke("User aborted request")}const F=(0,$.VI)(e.withName("createControlledExecManager")),N=A.fromResources(s);F[Symbol.dispose]();const[L,j]=e.withCancel(),U=new Gt,{failThresholdMs:B,advisoryThresholdMs:W}=function(e,t){const r=Lt(e?.failTimeoutMs)??3e4,n=r>0&&!0!==t?.isRunningInTest?Math.max(r,2e4):r,o=Lt(e?.advisoryTimeoutMs);return{failThresholdMs:n,advisoryThresholdMs:void 0!==o&&o>0&&(n<=0||oH,onStall:e=>{M("stall_detector",{thresholdMs:B,advisoryThresholdMs:W}),j(e)},onStallCallback:p.onStall,handlerTracker:U}),!1);let z,G,V;const K=(0,ve.Jt)(),J=new h.F8(K,(e=>(q.reset("outbound_write",Ln(e)),e))),Z=An(C,(0,$.VI)(e.withName("writeInitialRequest")),!1);let X;const Q=function(e){return new wn.Or({mcpTools:e.map((e=>({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?we.Value.fromJson(e.inputSchema):void 0,outputSchemaJson:void 0!==e.outputSchema?JSON.stringify(e.outputSchema):void 0})))})}(u),Y=p.requestContextBlobTransportMode??"legacy",te=0===S&&"userMessageAction"===r.action.case&&0===t.turns.length,re="ref_only"===Y&&te?"dual":Y,[,ne]=await Promise.all([Nn({ctx:e,action:r,resources:s,blobStore:a,options:p,source:"run_request",transportMode:re,notifyBytes:0===S}),void 0===p.mintLlmGatewayCredential?Promise.resolve(void 0):Ar(p.mintLlmGatewayCredential,{signal:D.signal,isCanceled:()=>D.canceled,requestId:f})]),oe={action:r,headers:p.headers??{}},se=this.options.decorateAttempt?.(oe,p)??oe,ie=new i.Mpn({conversationState:t,action:se.action,modelDetails:n,requestedModel:p.requestedModel,clientLlmGatewayCredential:ne,mcpTools:Q,conversationGroupId:p.conversationGroupId,conversationId:p.conversationId,agentSessionId:p.agentSessionId,mcpFileSystemOptions:p.mcpFileSystemOptions,customSystemPrompt:p.customSystemPrompt,systemPromptSpec:p.systemPromptSpec,harness:p.harness,computerUseCoordinateMode:p.computerUseCoordinateMode,subagentTypeName:p.subagentTypeName,excludeWorkspaceContext:p.excludeWorkspaceContext,devRawModelSlug:p.devRawModelSlug,selectedSubagentModels:p.selectedSubagentModels,subagentModelOverrides:p.subagentModelOverrides??[],selectedSubagentModelDetails:p.selectedSubagentModelsLegacy,clientSupportsInlineImages:p.clientSupportsInlineImages,clientSupportsPreviewCard:p.clientSupportsPreviewCard,startedAsNewProject:p.startedAsNewProject,firstProjectOnboarding:p.firstProjectOnboarding,clientSupportsSendToUser:p.clientSupportsSendToUser,clientSupportsRoutedModelUpdate:p.clientSupportsRoutedModelUpdate,emitModelCallUsage:p.emitModelCallUsage,canCreateCloudSubagents:p.canCreateCloudSubagents,suppressSubagentProgressUpdateTool:p.suppressSubagentProgressUpdateTool,transcriptParentConversationId:p.transcriptParentConversationId,runId:m,nextInteractionQueryId:g.peekNext(),voiceCallNotes:p.voiceCallNotes});if(X=J.write(new de.KS({message:{case:"runRequest",value:ie}})),D.canceled){const t={ctxCanceled:e.canceled,softCancel:D.canceled};throw M("post_write_cancel",t),Z[Symbol.dispose](),new Ke("User aborted request")}const ae={...se.headers,"x-request-id":f,"x-original-request-id":m,...Me(p),...Oe()};z=(0,$.VI)(e.withName("handshakeEstablishment")),z.span.setAttribute("handshake.firstStreamOnClient",!this.hasStartedStream),this.hasStartedStream=!0;const ce=function(e){return e?.get(yn)}(e)?.startTransportRun(),pe=void 0===ce?z.ctx:function(e,t){return e.with(yn,t)}(z.ctx,ce),fe=0===S&&void 0!==p.onTtftBreakdown?k?.networkPhaseStartedAt:void 0;let ge;const ye=void 0===ce&&void 0===fe?K:(E=K,x=()=>{ge=performance.now(),ce?.markFirstRequestSent(ge)},{[Symbol.asyncIterator](){const e=E[Symbol.asyncIterator]();let t=!1;const r={next:()=>(t||(t=!0,x()),e.next())};return void 0!==e.return&&(r.return=t=>e.return(t)),void 0!==e.throw&&(r.throw=t=>e.throw(t)),r}}),be=this.client.run(pe,ye,{signal:L.signal,headers:ae,onHeader:e=>{H=e.get("x-cursor-agent-transport-mode")??void 0,p.onHeader?.(e)},onNetworkStarted:()=>{void 0===G&&(G=performance.now(),0===S&&(V=function(e=Kt,t=25){let r,n=0,o=0,s=e.now()+t;const i=e=>{e<=0||(o+=e,e>n&&(n=e))},a=()=>{const r=e.now();i(r-s),s=r+t,c=e.setTimeout(a,t)};let c=e.setTimeout(a,t);return{stop:()=>(void 0===r&&(e.clearTimeout(c),i(e.now()-s),r={maxLagMs:n,totalLagMs:o}),r)}}()))}}),ke=performance.now();let Ce;const xe=t=>{z&&(z.span.setAttribute("handshake.firstMessageHeartbeat",t),void 0!==G&&z.span.setAttribute("handshake.preNetworkMs",G-ke),z[Symbol.dispose](),z=void 0),y();const r=performance.now();Ce=r,p.onFirstMessage?.(r-ke),void 0!==G&&(p.onFirstMessageNetwork?.(r-G),void 0!==V&&(function(e,t){const r={loop:t.loop??"nal",transport_mode:Bt(t.transportMode),first_message_slow:t.firstMessageNetworkMs>=1e3?"true":"false"};Jt.histogram(e,t.reading.maxLagMs,r),Zt.histogram(e,t.reading.totalLagMs,r),Xt.histogram(e,t.firstMessageNetworkMs,r)}(e,{loop:this.options.loop,transportMode:H,firstMessageNetworkMs:r-G,reading:V.stop()}),V=void 0))},Pe=()=>{b(),p.onFirstNonHeartbeatResponse?.(performance.now()-ke,S)},Ie=p.onTtftBreakdown?e=>{const t=performance.now(),r=void 0===fe||void 0===ge||"server"!==e.clock?void 0:function(e){const t=Math.min(e.firstRequestTakenAt,e.firstMessageAt);return{requestBuildMs:Math.max(0,e.transportRunCalledAt-e.networkPhaseStartedAt),connectMs:Math.max(0,t-e.transportRunCalledAt),roundTripMs:Math.max(0,e.firstMessageAt-t),firstByteToOutputMs:Math.max(0,e.firstOutputAt-e.firstMessageAt),firstOutputReceivedAtEpochMs:e.firstOutputAtEpochMs}}({networkPhaseStartedAt:fe,transportRunCalledAt:ke,firstRequestTakenAt:ge,firstMessageAt:Ce??t,firstOutputAt:t,firstOutputAtEpochMs:Date.now()});p.onTtftBreakdown(void 0===r?e:{...e,transit:r},S)}:void 0,$e=!0===this.options.execCheckpointGate?function(e,t,r,n={}){return Te.has(r.action.action.case)?async function*(e,t,r,n){const o=[];let s=0;const i=()=>o.flatMap((e=>void 0===e.toolCallId?[]:[e.toolCallId])),a=e=>{const t=[];for(;o.length>0;){const n=o[0];if(!e&&void 0!==n.toolCallId&&!r.has(n.toolCallId))break;t.push(n.message),o.shift()}return t.length>0&&o.length>0&&(s=n.now()),t},c=()=>{const e=o.filter((e=>"execServerControlMessage"===e.message.message.case)),t=o.filter((e=>"execServerControlMessage"!==e.message.message.case));return o.splice(0,o.length,...t),e.map((e=>e.message))},l=t[Symbol.asyncIterator]();let u=!0;try{for(;;){let t;try{t=await l.next()}catch(e){throw u=!1,yield*c(),e}if(!0===t.done)return u=!1,void(yield*c());const d=t.value,h=d.message;if("execServerMessage"!==h.case&&"execServerControlMessage"!==h.case)if("conversationCheckpointUpdate"!==h.case){if(yield d,o.length>0&&n.now()-s>=n.holdMs){Re.info(e,"No checkpoint named held tool calls on a stream still delivering: handed on as they came",{toolCallIds:i().join(", "),waitedMs:Math.round(n.now()-s)});for(const e of i())r.add(e);yield*a(!0)}}else{for(const e of Ee(h.value.pendingToolCalls))r.add(e);if(yield d,o.length>0){const t=Math.round(n.now()-s),r=a(!1);r.length>0&&Re.debug(e,"Handed held execs on after their checkpoint",{count:r.length,waitedMs:t}),yield*r}}else{const t="execServerMessage"===h.case?Ae(h.value):void 0,i=void 0!==t&&!r.has(t);if(0===o.length&&!i){yield d;continue}if(0===o.length&&(s=n.now()),o.push({message:d,toolCallId:i?t:void 0}),i){Re.debug(e,"Held a tool call's exec for the checkpoint that names it",{toolCallId:t});try{n.onHeld?.(t)}catch(t){Re.warn(e,"onExecHeldForCheckpoint callback failed",{error:String(t)})}}}}}catch(e){if(u){u=!1;try{await(l.return?.())}catch{}}throw e}finally{o.length>0&&Re.info(e,"The stream ended before a checkpoint named held tool calls: dropped, never run",{toolCallIds:i().join(", ")}),u&&await(l.return?.())}}(e,t,Ee(r.state.pendingToolCalls),{holdMs:n.holdMs??5e3,now:n.now??(()=>performance.now()),onHeld:n.onHeld}):t}(e,be,{action:se.action,state:t},void 0===this.options.onExecHeldForCheckpoint?{}:{onHeld:this.options.onExecHeldForCheckpoint}):be,De=!0===this.options.execAfterCheckpointStored||!0===this.options.execCheckpointGate?new _e(void 0===this.options.onExecHeldForCheckpointStore?{}:{onExecHeld:this.options.onExecHeldForCheckpointStore}):void 0,{interactionStream:Fe,execStream:Ne,checkpointStream:Le,kvStream:je,done:Ue}=function(e,t,r,n,o,s,i,a,c,l){const u=(0,ve.Jt)(),d=(0,ve.Jt)(),h=(0,ve.Jt)(),p=(0,ve.Jt)();let f=!1,m=!1,g=!1;return{interactionStream:u,execStream:d,checkpointStream:h,kvStream:p,done:async function(){let w,y,v=!1,b=!1;try{for await(const o of t){if(void 0!==o.ttftBreakdown){const t=o.ttftBreakdown;try{a?.({serverFirstTokenMs:t.serverFirstTokenMs,preStreamSetupMs:t.preStreamSetupMs,waitForFirstEventMs:t.waitForFirstEventMs,providerTtftMs:t.providerTtftMs,slowPoolWaitMs:t.slowPoolWaitMs,...void 0===t.clientPrepMs?{}:{clientPrepMs:t.clientPrepMs},...void 0===t.clientPrepLegs?{}:{clientPrepLegs:me(t.clientPrepLegs)},...void 0===t.preHandlerMs?{}:{preHandlerMs:t.preHandlerMs},clock:t.clientClock?"client":"server"})}catch(t){On.warn(e,"onTtftBreakdown callback failed",{error:String(t)})}}const t="interactionUpdate"===o.message.case&&"heartbeat"===o.message.value.message.case;if(f||(f=!0,n(t)),t)r.onServerSentHeartbeat(),r.reset("inbound_message","heartbeat");else{if(!m){m=!0;try{i?.()}catch(t){On.warn(e,"onFirstNonHeartbeatMessage callback failed",{error:String(t)})}}if(!g&&"interactionUpdate"===o.message.case&&xn(o.message.value)){g=!0;try{l?.()}catch(t){On.warn(e,"onFirstModelOutput callback failed",{error:String(t)})}}r.reset("inbound_message",Ln(o))}if("interactionUpdate"===o.message.case&&"turnEnded"===o.message.value.message.case&&(v=!0),"interactionUpdate"!==o.message.case&&"interactionQuery"!==o.message.case||await u.write(o.message).catch((()=>{})),"execServerMessage"!==o.message.case&&"execServerControlMessage"!==o.message.case||await d.write(o.message.value),"conversationCheckpointUpdate"===o.message.case){const e=v?"ineligible_terminal_turn":"eligible";"ineligible_terminal_turn"===e&&(b=!0);const t=c?.noteRouted(o.message.value);try{await h.write({checkpoint:o.message.value,metadata:{resumeEligibility:e},...void 0===t?{}:{onSettled:t}})}catch(e){throw t?.(),e}}"kvServerMessage"===o.message.case&&await p.write(o.message.value)}r.onStreamEnded()}catch(e){w=e}finally{if(y=w,v&&b&&void 0!==w&&!o?.aborted&&!s?.aborted&&function(e){const t=e instanceof He?e:ct(e);return t instanceof qe&&function(e){return!0===e.isTransport||(e.cause instanceof Error?bt(e.cause):St(e.message))}(t)}(w)&&(On.debug(e,"Ignoring transport close after terminal agent stream",{caughtError:w instanceof Error?`${w.name}: ${w.message}`:String(w)}),r.onStreamEnded(),y=void 0),v||o?.aborted||s?.aborted){if(!v&&!o?.aborted){const t=`Stream ended without turnEnded, abort signals: signal.aborted=${o?.aborted}, parentSignal.aborted=${s?.aborted}; firstMessageFired=${f}`;On.warn(e,t)}}else{const t="Stream ended without turnEnded — connection likely dropped mid-stream";void 0===w?(On.warn(e,t),y=new qe(t,{isTransport:!0})):w instanceof Error&&"[aborted] aborted"===w.message?(On.warn(e,`${t}; retrying caught [aborted] aborted error`),y=new qe(t,{cause:w,isTransport:!0})):On.warn(e,`${t}; caught non-retriable stream error, rethrowing as-is`,{caughtError:jn(w)})}u.close(),d.close(),h.close(),p.close()}if(void 0!==y)throw y}()}}(e,$e,q,xe,D.signal,e.signal,Pe,Ie,De,v);let Be;const We={handleCheckpoint:async(e,t,r)=>{await l.handleCheckpoint(e,t,r),Be=r?.resumeEligibility??"eligible"},getLatestCheckpoint:()=>l.getLatestCheckpoint()};Z[Symbol.dispose]();const ze=5e3;let Ve;const Je=()=>{Ve=setTimeout((()=>{J.write(new de.KS({message:{case:"clientHeartbeat",value:new de.kA}})).then((()=>q.onClientSentHeartbeat()),(()=>{})),Je()}),ze)},Ze=()=>{void 0!==Ve&&(clearTimeout(Ve),Ve=void 0)};Je();try{let t;if("shellCommandAction"===r.action.case&&r.action.value.execId){const n=r.action.value,i=new he.a({command:n.shellCommand?.command||"",parsingResult:new he.HO,skipApproval:!0}),a=s.get(ee).execute(e,i,{execId:n.execId}),c=new Tr(Fe,o,new h.F8(J,(e=>new de.KS({message:{case:"interactionResponse",value:e}}))),q);t={run:async e=>{await Promise.all([U.track("handleShellStream",Un(e,a,o)),U.track("interactionController",c.run(e))])}}}else{const e=new Tr(Fe,o,new h.F8(J,(e=>new de.KS({message:{case:"interactionResponse",value:e}}))),q);t={run:async t=>{await U.track("interactionController",e.run(t))}}}void 0!==X&&await Promise.race([X,Ue.catch((()=>{}))]);const i=new h.F8(J,(e=>{if((0,we.isMessage)(e,d.yT))return new de.KS({message:{case:"execClientMessage",value:e}});if((0,we.isMessage)(e,d.$Y))return new de.KS({message:{case:"execClientControlMessage",value:e}});throw new Error(`Unknown exec message (type: ${(0,we.isMessage)(e)?e.getType().typeName:typeof e})`)})),l=new Ft(Ne,i,N,De),S=new le(je,new h.F8(J,(e=>new de.KS({message:{case:"kvClientMessage",value:e}}))),a,{beforeGetBlob:async(e,t)=>a.persistForRemoteRead(e,t)}),k=new Se(Le,We,e);let _,C;const E={promise:new Promise(((e,t)=>{_=e,C=t})),resolve:_,reject:C};D.canceled?(E.resolve(),Fe.close()):D.signal.addEventListener("abort",(()=>{E.resolve(),Fe.close()}),{once:!0}),l.run(D).then(E.resolve).catch(E.reject);const x=Promise.allSettled([U.track("streamSplitter",Ue.finally((()=>{Ze(),c.close(),i.close()}))),U.track("execHandler",E.promise),t.run(e),U.track("checkpointController",k.run()),U.track("kvHandler",S.run(e)),U.track("conversationActionManager",c.run(e,{write:async t=>{await Nn({ctx:e,action:t,resources:s,blobStore:a,options:p,source:"queued_action"}),await J.write(new de.KS({message:{case:"conversationAction",value:t}}))}}))]);let R,I;const T={promise:new Promise(((e,t)=>{R=e,I=t})),resolve:R,reject:I};x.then(T.resolve).catch(T.reject),e.canceled?T.reject(new Ke("User aborted request")):e.signal.addEventListener("abort",(()=>T.reject(new Ke("User aborted request"))),{once:!0});const A=()=>{e.signal.aborted?j():function(e){const t=e.lingerMs??6e3;return new Promise((r=>{let n=!1;const o=e=>{n||(n=!0,clearTimeout(s),r(e))},s=setTimeout((()=>o("linger_timed_out")),t);e.done.then((()=>o("stream_ended")),(()=>o("stream_ended")))}))}({done:Ue,lingerMs:p.softCancelLingerMs}).then((t=>{On.info(e,"Soft-cancel transport linger finished",{outcome:t,requestId:f}),j()}))};D.canceled?(A(),T.reject(new Ke("User aborted request"))):D.signal.addEventListener("abort",(()=>{A(),T.reject(new Ke("User aborted request"))}),{once:!0});const $=await T.promise,M=$[0],O=$[1],F=$[3],L=e=>e.reason instanceof Error?`${e.reason.name}: ${e.reason.message}`:String(e.reason);if("rejected"===F.status)throw new Ge("Checkpoint persistence failed",{cause:F.reason instanceof Error?F.reason:void 0,requestId:f,displayInfo:{title:"Checkpoint persistence failed",detail:L(F),isRetryable:!1}});const B="ineligible_terminal_turn"===Be;if(B){const t={..."rejected"===M.status?{streamSplitter:L(M)}:{},..."rejected"===O.status?{execHandler:L(O)}:{}};Object.keys(t).length>0&&On.debug(e,"Ignoring handler errors after terminal checkpoint",t)}if("rejected"===M.status&&!B)throw M.reason;if("rejected"===O.status&&!B)throw O.reason;D.canceled||await this.processUnprocessedMessages(P,c,We,n,o,s,a,u,p,f,m,g,w,q,y,v,b)}finally{Ze(),V?.stop(),V=void 0,z&&(z[Symbol.dispose](),z=void 0)}}catch(e){C.error=e,C.hasError=!0}finally{$n(C)}var E,x}async processUnprocessedMessages(e,t,r,n,o,s,a,c,l,u,d,h,p,f,m,g,w){if(!t.hasUnprocessedMessages())return;const y=t.getUnprocessedUserMessages(),v=r.getLatestCheckpoint();if(!v||0===y.length)return;const b=y[0];t.markMessageAsProcessed(b),t.resetStream(),f[Symbol.dispose]();const S=r.getLatestCheckpoint();try{await this.runInternal(e,v,new i.QFf({action:{case:"userMessageAction",value:new i.Vtf({userMessage:b})}}),n,o,s,a,t,r,c,l,u,d,h,p,m,g,w,0,void 0,"agent.request.queuedMessage")}catch(e){throw S===r.getLatestCheckpoint()&&t.requeueMessage(b),e}}}const Hn="cursor-ide-browser",qn="cursor-dev-control",zn="custom-user-tools",Gn=new Set(["cursor-app-control","cursor-backend-control","cursor-browser-extension",Hn,qn,zn,"fsd","cursor-subscriptions","cursor-cloud","suggestions","Cursor Slack Tools","Cursor Automation Tools"]);function Vn(e){return!Gn.has(e)}const Kn=new Set([qn,Hn]);function Jn(e){if(void 0!==e&&0!==Object.keys(e).length)try{return JSON.stringify(e)}catch{return}}function Zn(e){return{name:e.toolName,description:e.description,arguments:e.inputSchema,outputSchema:e.outputSchema,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId}}var Xn;function Qn(e){return void 0===e||void 0===e.serverIdentifiers}function Yn(e){switch(e.kind){case"ready":return void 0===e.toolListError?"connected":"error";case"requires_authentication":return"needsAuth";case"error":return"error";default:return"loading"}}(0,y.cF)(Symbol("mcpHostFilledArguments"),[]),function(e){e.Snapshots="cursor_mcp_lease_snapshot_store",e.Status="cursor_mcp_lease_server_status",e.Settings="cursor_mcp_lease_settings",e.Providers="cursor_mcp_lease_providers",e.Unknown="cursor_mcp_lease_unknown"}(Xn||(Xn={}));const eo=q("mcp-executor",(e=>new B(e,Z("mcpArgs"),X("mcpResult"))),((e,t)=>{t.register(new I(e,Y("mcpArgs"),Q("mcpResult")))})),to=q("list-mcp-resources-executor",(e=>new B(e,Z("listMcpResourcesExecArgs"),X("listMcpResourcesExecResult"))),((e,t)=>{t.register(new I(e,Y("listMcpResourcesExecArgs"),Q("listMcpResourcesExecResult")))})),ro=q("read-mcp-resource-executor",(e=>new B(e,Z("readMcpResourceExecArgs"),X("readMcpResourceExecResult"))),((e,t)=>{t.register(new I(e,Y("readMcpResourceExecArgs"),Q("readMcpResourceExecResult")))})),no=q("mcp-state-executor",(e=>new B(e,Z("mcpStateExecArgs"),X("mcpStateExecResult"))),((e,t)=>{t.register(new I(e,Y("mcpStateExecArgs"),Q("mcpStateExecResult")))}));var oo=r("../proto/dist/generated/agent/v1/subagent_exec_pb.js");(0,y.cF)(Symbol("pendingSubagentReplay"),void 0);class so extends Error{constructor(e,t){super(e),this.name="SubagentHostError",this.agentId=t?.agentId,this.cause=t?.cause}}const io=q("subagent-executor",(e=>new B(e,Z("subagentArgs"),X("subagentResult"))),((e,t)=>{t.register(new I(e,Y("subagentArgs"),Q("subagentResult")))})),ao=q("subagent-await-executor",(e=>new B(e,Z("subagentAwaitArgs"),X("subagentAwaitResult"))),((e,t)=>{t.register(new I(e,Y("subagentAwaitArgs"),Q("subagentAwaitResult")))})),co=q("force-background-subagent-executor",(e=>new B(e,Z("forceBackgroundSubagentArgs"),X("forceBackgroundSubagentResult"))),((e,t)=>{t.register(new I(e,Y("forceBackgroundSubagentArgs"),Q("forceBackgroundSubagentResult")))}));var lo=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/status.js"),uo=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js");const ho=(0,ye.createContextKey)(void 0,{description:"anysphere.callerContext"}),po=(0,y.cF)(Symbol("context-rpc.expected_error"),void 0);function fo(e,t,r){!0===t.get(po)?.(r)?e?.setAttribute("rpc.expected_error",!0):(e?.recordException(go(r)),e?.setStatus({code:lo.s.ERROR,message:r instanceof Error?r.message:"RPC call failed"})),e?.end()}function mo(e){return null!==e&&"object"==typeof e&&Symbol.asyncIterator in e}function go(e){return e instanceof Error?e:new Error(String(e))}function wo(e,t,r){return{[Symbol.asyncIterator](){const n=e[Symbol.asyncIterator]();let o=!1;const s=e=>{o||(o=!0,e?(t?.recordException(go(e)),t?.setStatus({code:lo.s.ERROR,message:e instanceof Error?e.message:"Stream failed"})):t?.setStatus({code:lo.s.OK}),t?.end(),r?.())};return{async next(){try{const e=await n.next();return e.done&&s(),e}catch(e){throw s(e),e}},return:async e=>(s(),n.return?n.return(e):{done:!0,value:void 0}),async throw(e){if(s(e),n.throw)return n.throw(e);throw e}}}}}function yo(...e){const t=new Headers;for(const r of e)r&&(r instanceof Headers?r:new Headers(r)).forEach(((e,r)=>{t.set(r,e)}));return t}function vo(e,t){const{injectTraceHeaders:r=!0,extractHeaders:n}=t;return new Proxy(e,{get(e,o){const s=e[o];return"function"!=typeof s?s:(i,a,c={})=>{const l=(0,$.fR)(i.withName(`rpc.${String(o)}`),{kind:uo.v.CLIENT,attributes:{"rpc.method":String(o),"rpc.system":"connect"}}),u=(0,$.fU)(l);let d;try{let o;if(r&&(o=function(e){const t=new Headers;try{const r=(0,$.fU)(e),n=r?.spanContext?.();if(n?.traceId&&n.spanId){const e=n.traceFlags??0,r=`00-${n.traceId}-${n.spanId}-${e.toString(16).padStart(2,"0")}`;t.set("traceparent",r),t.set("backend-traceparent",r),n.traceState&&t.set("tracestate",n.traceState.serialize())}}catch{}return t}(l)),n){const e=n(l);e&&(o=yo(o,e))}const i=yo(c.headers,o),{signal:p,cleanup:f}=!0===t.enableAbortSignal?function(e,t){if(void 0===t||t===e)return{signal:e};const r=new AbortController,n=()=>{r.abort(e.reason)},o=()=>{r.abort(t.reason)};e.addEventListener("abort",n,{once:!0}),t.addEventListener("abort",o,{once:!0}),e.aborted?n():t.aborted&&o();return{signal:r.signal,cleanup:()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",o)}}}(l.signal,c.signal):{signal:c.signal,cleanup:void 0};d=f;const m=(c.contextValues??(0,ye.createContextValues)()).set(ho,l),g={...c,headers:i,signal:p,contextValues:m},w=s.call(e,a,g);return mo(w)?wo(w,u,d):null!==(h=w)&&"object"==typeof h&&"then"in h&&"function"==typeof h.then?Promise.resolve(w).then((e=>mo(e)?wo(e,u,d):(u?.setStatus({code:lo.s.OK}),u?.end(),d?.(),e))).catch((e=>{throw fo(u,l,e),d?.(),e})):(u?.setStatus({code:lo.s.OK}),u?.end(),d?.(),w)}catch(e){throw fo(u,l,e),d?.(),e}var h}}})}var bo=r("node:crypto?8af2"),So=r("../utils/dist/workspace-paths.js");function ko(){return(0,s.join)(function(){const e=process.env.CURSOR_DATA_DIR;return e?.trim()?e:(0,s.join)((0,o.homedir)(),".cursor")}(),"projects")}function _o(e){return(0,s.join)(ko(),(0,So.r_)(e))}var Co=r("node:fs/promises"),Eo=r("../../node_modules/.pnpm/lru-cache@11.2.5/node_modules/lru-cache/dist/esm/index.js"),xo=r("node:fs");const Po="local";function Ro(e,t){return`${e}:task_progress:${t}`}function Io(e){const t={};return"string"==typeof e.title&&e.title.trim().length>0&&(t.title=e.title),"string"==typeof e.cwd&&e.cwd.trim().length>0&&(t.cwd=e.cwd),"number"==typeof e.startTimeMs&&Number.isFinite(e.startTimeMs)&&e.startTimeMs>0&&(t.startTimeMs=String(Math.floor(e.startTimeMs))),Object.keys(t).length>0?t:void 0}function To(e,t){e.hookApprovalRequirement=void 0!==t?new he.In(t):void 0}function Ao(e){return e.hookApprovalRequirement}function $o(e){return e?.kind===he.b.FORCE_PROMPT}function Mo(e){return!(!e.skipApproval||e.smartModeClassifierAllowed&&$o(e.hookApprovalRequirement))}var Do=r("../proto/dist/generated/agent/v1/background_shell_exec_pb.js"),Oo=r("../shell-exec/dist/api/index.js"),Fo=r("./src/agent/native/tree-sitter.webpack.cjs"),No=r("./src/agent/native/tree-sitter-bash.webpack.cjs");const Lo=function(e,t=console.warn){let r;return()=>{if(void 0!==r)return r;try{const t=e();t.setLanguage(No),r=t}catch(e){if(!function(e){return"object"==typeof e&&null!==e&&"CURSOR_TREE_SITTER_STUBBED"===e.code}(e))throw e;r=null,t("shell-parser: tree-sitter natives are unavailable in this artifact; shell command analysis degrades to parsingFailed")}return r}}((()=>new Fo)),jo=new Set(["file_redirect","heredoc_redirect","herestring_redirect","heredoc","here_string","redirect","redirection"]),Uo=new Set(["<",">",">>",">|","<>","<&",">&","&>","&>>"]);function Bo(e,t){if(null===e)return{legacy:{simpleCommands:[],hasInputRedirect:!1,hasOutputRedirect:!1},structured:{parsingFailed:!0,executableCommands:[],hasRedirects:!1,hasCommandSubstitution:!1,redirects:[]}};const r=e.parse(t),n=new WeakSet;let o=!1,s=!0;const i={simpleCommands:[],hasInputRedirect:!1,hasOutputRedirect:!1},a={parsingFailed:!1,executableCommands:[],hasRedirects:!1,hasCommandSubstitution:!1,redirects:[]},c=e=>{o=!0,a.hasRedirects=!0,s=s&&e},l=e=>{if(e&&/^\d+$/.test(e.text))return Number.parseInt(e.text,10)},u=()=>({fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}),d=(e,t)=>{const r=(e=>{const t=e.children,r=t.findIndex((e=>Uo.has(e.type)));if(-1!==r)return{operator:t[r]?.type??"",target:t.slice(r+1).find((e=>"comment"!==e.type))}})(e);if(!r)return!1;const{operator:n,target:o}=r,s=((e,t)=>{if("&>"===t||"&>>"===t)return[1,2];const r=(e=>l(e.children.find((e=>"file_descriptor"===e.type))))(e);return void 0!==r?[r]:t.startsWith("<")?[0]:[1]})(e,n),i=(e=>{if(e){if("word"===e.type)return 0===e.namedChildren.length?e.text:void 0;if("number"===e.type)return e.text;if("raw_string"===e.type){if(e.text.length<2)return;return e.text.slice(1,-1)}if("string"===e.type){const t=e.namedChildren;if(0===t.length||t.some((e=>"string_content"!==e.type)))return;return t.map((e=>e.text)).join("")}}})(o),c={operator:n,destinationFds:s,targetNodeType:o?.type??""};if(void 0!==i&&(c.targetText=i),a.redirects.push(c),">&"===n){const e=l(o),r=void 0===e?void 0:t.fdTargets.get(e);if(!(e=>"original-stdout"===e||"original-stderr"===e||"dev-null"===e)(r)){for(const e of s)t.fdTargets.set(e,"unsafe");return!1}for(const e of s)t.fdTargets.set(e,r);return!0}if("<&"===n){const e=l(o),r=void 0===e?void 0:t.fdTargets.get(e);if("dev-null"!==r){for(const e of s)t.fdTargets.set(e,"unsafe");return!1}for(const e of s)t.fdTargets.set(e,r);return!0}if(!(e=>{if(!e)return!1;if("word"===e.type)return"/dev/null"===e.text;if("raw_string"===e.type)return"'/dev/null'"===e.text;if("string"===e.type){const t=e.namedChildren;return 1===t.length&&"string_content"===t[0]?.type&&"/dev/null"===t[0].text}return!1})(o)){for(const e of s)t.fdTargets.set(e,"unsafe");return!1}for(const e of s)t.fdTargets.set(e,"dev-null");return!0},h=(e,t)=>{if(!n.has(e)){if(n.add(e),(e=>{var t;t=e.text,/(^|\s)[0-9]*<>/.test(t)||/(^|\s)[0-9]*>(\||&)?/.test(t)||/(^|\s)&>/.test(t)||/(^|\s)[0-9]+>&[0-9]+/.test(t))&&(i.hasOutputRedirect=!0),"heredoc_redirect"!==e.type&&"herestring_redirect"!==e.type||(i.hasInputRedirect=!0)})(e),"heredoc_redirect"===e.type){const{redirect:t,isAllowlistSafe:r}=(e=>{const t=(e=>{const t=e.parent;if("redirected_statement"!==t?.type)return;const r=t.children.find((e=>"command"===e.type)),n=r?.childForFieldName("name");return n?.text})(e),r=void 0!==t&&!(e=>{let t=e.parent;for(;t;){if("command_substitution"===t.type&&"string"!==t.parent?.type)return!0;t=t.parent}return!1})(e),n={operator:r?"<<":"",destinationFds:r?[0]:[],targetNodeType:e.type};return r&&(n.targetText=t),{redirect:n,isAllowlistSafe:r}})(e);return a.redirects.push(t),void c(r)}if("file_redirect"!==e.type)return a.redirects.push({operator:"",destinationFds:[],targetNodeType:e.type}),void c(!1);c(d(e,t))}};return function e(t){const r=t.type;if((e=>{const t=u();for(const r of e.children)jo.has(r.type)&&h(r,t)})(t),jo.has(r)&&!n.has(t)&&h(t,u()),"command"===r){const e=t.childForFieldName("name");if(null===e)a.parsingFailed=!0;else{i.simpleCommands.push(e.text);let r=e.text;const n=[];for(const e of function(e){const t=[],r=e.walk();if(r.gotoFirstChild())do{"argument"===r.currentFieldName&&t.push(r.currentNode)}while(r.gotoNextSibling());return t}(t))n.push({type:e.type,value:e.text}),r+=` ${e.text}`;a.executableCommands.push({name:e.text,args:n,fullText:r})}}if("command_name"===r||"simple_command"===r)if("command_name"!==r||i.simpleCommands.includes(t.text)){if("simple_command"===r){const e=t.firstNamedChild;e&&"command_name"===e.type?i.simpleCommands.includes(e.text)||i.simpleCommands.push(e.text):i.simpleCommands.push(t.text)}}else i.simpleCommands.push(t.text);"command_substitution"!==r&&"process_substitution"!==r||(a.hasCommandSubstitution=!0);for(const r of t.children)e(r)}(r.rootNode),o&&(a.allRedirectsAreDevNull=s),{legacy:i,structured:a}}function Wo(e){return Bo(Lo(),e)}function Ho(e,t){return t>0&&t=55296&&r<=56319)&&function(e){return e>=56320&&e<=57343}(e.charCodeAt(t));var r}function qo(e,t){return t>0?t>=e.length?e.length:Math.trunc(t):0}function zo(e,t){const r=qo(e,t);return Ho(e,r)?r-1:r}function Go(e,t){const r=qo(e,t);return Ho(e,r)?r+1:r}function Vo(e,t){return t>0?e.length<=t?e:e.slice(0,zo(e,t)):""}function Ko(e,t){return t>0?e.length<=t?e:e.slice(Go(e,e.length-Math.trunc(t))):""}let Jo,Zo;function Xo(e,t){Jo??=new TextEncoder,Zo??=new Uint8Array(65536);let r=0,n=0;for(;r{const t=(0,Yo.o1)(e);try{return await(0,Co.realpath)(t)}catch{return t}},rs=1048576,ns=52428800;var os=r("../proto/dist/generated/agent/v1/sandbox_pb.js");function ss(e){if(!e)return;let t;return"allow"===e.default?t=os.h1.ALLOW:"deny"===e.default&&(t=os.h1.DENY),new os.RB({version:e.version,defaultAction:t,deny:e.deny??[],allow:e.allow??[],logging:e.logging?(r=e.logging,new os.Qq({decisionLogPath:r.decisionLogPath,logFormat:r.logFormat})):void 0});var r}function is(e){const t=function(e){if(!e)return;const t={};if(1===e.version&&(t.version=1),void 0!==e.defaultAction)switch(e.defaultAction){case os.h1.ALLOW:t.default="allow";break;case os.h1.DENY:t.default="deny"}return e.deny&&e.deny.length>0&&(t.deny=e.deny),e.allow&&e.allow.length>0&&(t.allow=e.allow),e.logging&&(t.logging=function(e){const t={};return e.decisionLogPath&&(t.decisionLogPath=e.decisionLogPath),"jsonl"===e.logFormat&&(t.logFormat="jsonl"),t}(e.logging)),t}(e.networkPolicy);return t||(e.networkAccess?(0,Oo.T6)():(0,Oo.Po)())}function as(e){switch(e){case"system":return os.Sz.SYSTEM;case"workspace":return os.Sz.WORKSPACE;default:return os.Sz.UNSPECIFIED}}function cs(e){const t=function(e){switch(e){case os.Sz.SYSTEM:return"system";case os.Sz.WORKSPACE:return"workspace";case os.Sz.UNSPECIFIED:default:return}}(e.readBoundary),r=e.additionalReadPaths??[];return{readBoundary:t,additionalReadPaths:"workspace"===t&&r.length>0?r:void 0,privateTmp:e.privateTmp}}function ls(e){if(!e)return{type:"insecure_none"};switch(e.type){case os.vc.INSECURE_NONE:case os.vc.UNSPECIFIED:return{type:"insecure_none",allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies};case os.vc.WORKSPACE_READWRITE:return{type:"workspace_readwrite",networkPolicy:is(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadwritePaths:e.additionalReadwritePaths,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict,...cs(e)};case os.vc.WORKSPACE_READONLY:return{type:"workspace_readonly",networkPolicy:is(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict,...cs(e)};default:return{type:"insecure_none"}}}function us(e){if(e)return"insecure_none"===e.type?new os.Mw({type:os.vc.INSECURE_NONE,allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies}):"workspace_readwrite"===e.type?new os.Mw({type:os.vc.WORKSPACE_READWRITE,networkAccess:(0,Oo.$b)(e.networkPolicy),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadwritePaths:e.additionalReadwritePaths??[],additionalReadonlyPaths:e.additionalReadonlyPaths??[],disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicy:ss(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:as(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[],privateTmp:e.privateTmp}):"workspace_readonly"===e.type?new os.Mw({type:os.vc.WORKSPACE_READONLY,networkAccess:(0,Oo.$b)(e.networkPolicy),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths??[],disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicy:ss(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:as(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[],privateTmp:e.privateTmp}):new os.Mw({type:os.vc.INSECURE_NONE})}function ds(e){return" "===e||"\t"===e||"\n"===e||"\r"===e||" "===e||"​"===e||"‌"===e||"‍"===e||"\ufeff"===e}function hs(e){let t="",r=!1;for(const n of e)ds(n)?r=!0:(r&&t.length>0&&(t+=" "),r=!1,t+=n);return t}function ps(e){if(0===e.length)return!1;for(let t=0;te.fullText))])]}const ws={a:"",b:"\b",e:"",E:"",f:"\f",n:"\n",r:"\r",t:"\t",v:"\v","\\":"\\","'":"'",'"':'"',"?":"?"};function ys(e){let t="",r="plain",n=0;for(;n=e.length){t+=o,n++;continue}const s=e[n+1],i=ws[s];if(void 0!==i){t+=i,n+=2;continue}const a="x"===s?e.slice(n+2).match(/^[0-9a-fA-F]{1,2}/)?.[0]:"u"===s?e.slice(n+2).match(/^[0-9a-fA-F]{1,4}/)?.[0]:"U"===s?e.slice(n+2).match(/^[0-9a-fA-F]{1,8}/)?.[0]:e.slice(n+1).match(/^[0-7]{1,3}/)?.[0],c="u"===s||"U"===s,l="x"===s||c?16:8;if(void 0!==a){const e=Number.parseInt(a,l);if(!c||e<=1114111){t+=c?String.fromCodePoint(e):String.fromCharCode(e),n+=a.length+(16===l?2:1);continue}}t+=s,n+=2}return hs(t)}function vs({rule:e,command:t}){const r=hs(e).trim();return 0!==r.length&&(null!==function(e){const t=hs(e).trim();if(0===t.length)return"Rule cannot be empty";if(t.length>512)return"Rule cannot exceed 512 characters";if(ps(t))return"Rule cannot match every command; be more specific than wildcards alone";if(t.startsWith(":"))return"Colon rules need an executable before `:` (e.g. `aws:*s3 rm*`)";const r=fs(t);if(void 0!==r){const{executablePattern:e,argsPattern:t}=r;if(ps(e)&&(0===t.length||ps(t)))return"Rule cannot match every command; narrow the executable or argument pattern"}return null}(r)||[t.trim(),hs(t).trim(),ys(t).trim()].some((e=>function(e,t){const r=fs(e);if(void 0!==r){const{executablePattern:e,argsPattern:n}=r,o=t.indexOf(" "),s=-1===o?t:t.slice(0,o),i=-1===o?"":t.slice(o+1).trim();if((0,ms.T)(e,s)&&(0,ms.T)(n,i))return!0}return e.includes("*")?(0,ms.T)(e,t):t===e||t.startsWith(`${e} `)}(r,e))))}function bs({matchForms:e,blockedCommands:t}){const r=t.map((e=>e.trim())).filter((e=>e.length>0));if(0===r.length)return;const n=e.map((e=>e.trim())).filter((e=>e.length>0)),o=n.length>0?n:[""];for(const e of r)if(o.some((t=>vs({rule:e,command:t}))))return e}function Ss(e){return`Denied: this command was blocked by administrator policy (denylist rule: ${e}) and was not executed. It cannot be approved from this conversation; only a user can run it manually outside the agent. You may continue working on the task.`}function ks({command:e,parsingResult:t,blockedCommands:r}){if(0===r.length)return;if(t.parsingFailed||0===t.executableCommands.length)return"Denied: this command could not be conclusively analyzed against your team's administrator command denylist, so it was blocked (fail-closed) and was not executed. It cannot be approved from this conversation; only a user can run it manually outside the agent. You may continue working on the task.";const n=bs({matchForms:gs({command:e,parsingResult:t}),blockedCommands:r});return void 0===n?void 0:Ss(n)}var _s=r("../utils/dist/test-resets.js");const Cs="CURSOR_FORCED_SHELL_EGRESS_NETWORK_DEFAULT",Es="CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_DENY_DOMAINS",xs=/\$\(|`|<\(|>\(/,Ps=/[;&|]/;let Rs,Is,Ts,As;function $s(){if(void 0===Rs){const e=(process.env.CURSOR_FORCED_SHELL_EGRESS??"").trim().toLowerCase();Rs=""!==e&&"0"!==e&&"false"!==e&&"off"!==e}return Rs}function Ms(e){const t=(process.env[e]??"").trim();if(t)try{return new RegExp(t,"i"),t}catch(t){throw new Error(`[forced-egress] invalid regex in ${e}: ${String(t)}`)}}function Ds(e){return(process.env[e]??"").split(",").map((e=>e.trim())).filter((e=>e.length>0))}function Os(e){const t=(process.env[e]??"").split(":").map((e=>e.trim())).filter((e=>e.length>0)),r=t.filter((e=>e.startsWith("/"))),n=t.length-r.length;return n>0&&console.error(`[forced-egress] ignoring ${n} non-absolute path(s) in ${e}.`),r}function Fs(){if(void 0===As){const e=(process.env[Cs]??"").trim().toLowerCase();let t="deny";"allow"===e||"deny"===e?t=e:""!==e&&console.error(`[forced-egress] ignoring invalid value in ${Cs} (expected "allow" or "deny"); using "deny".`);const r=Ds("CURSOR_FORCED_SHELL_EGRESS_DENY_DOMAINS"),n=(process.env[Es]??"").trim();let o=r;"none"===n.toLowerCase()?o=[]:""!==n&&(o=Ds(Es)),As={networkDefault:t,denyDomains:r,dependencyDenyDomains:o,allowDomains:Ds("CURSOR_FORCED_SHELL_EGRESS_ALLOW_DOMAINS"),writablePaths:Os("CURSOR_FORCED_SHELL_EGRESS_WRITABLE_PATHS")}}return As}function Ns(e,t,r={}){const n=[Ms(e),Ms(t)].filter((e=>void 0!==e)).map((e=>`(?:${e})`));if(0===n.length)return null;const o=n.join("|"),s=r.anchorToExecutable?`^\\s*(?:[A-Za-z_][A-Za-z0-9_]*=[^\\s]*\\s+)*(?:${o})`:o;return new RegExp(s,"i")}function Ls(e,t){const r=function(){const e=Fs();return{type:"workspace_readwrite",...e.writablePaths.length>0?{additionalReadwritePaths:e.writablePaths}:{},networkPolicy:{version:1,default:e.networkDefault,allow:["127.0.0.0/8","::1/128","localhost",...e.allowDomains],...e.denyDomains.length>0?{deny:e.denyDomains}:{}},networkPolicyStrict:!0,skipStatsigDefaults:!0,enableSharedBuildCache:!0}}(),n=(void 0===Is&&(Is=Ns("CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_DEPENDENCY_REGEX",{anchorToExecutable:!0})),Is);if(null===n)return r;const o=t?.executableCommands??[];if(t?.parsingFailed||0===o.length)return r;if(xs.test(e))return r;const s=(void 0===Ts&&(Ts=Ns("CURSOR_FORCED_SHELL_EGRESS_SOURCE_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_SOURCE_REGEX")),Ts);for(const e of o){const t=e.fullText?.trim()||e.name?.trim()||"";if(!t||s?.test(t)||Ps.test(t))return r}return o.every((e=>n.test(e.fullText?.trim()||e.name?.trim()||"")))?function(){const e=Fs();return{type:"workspace_readwrite",...e.writablePaths.length>0?{additionalReadwritePaths:e.writablePaths}:{},networkPolicy:{version:1,default:"allow",...e.dependencyDenyDomains.length>0?{deny:e.dependencyDenyDomains}:{}},skipStatsigDefaults:!0,enableSharedBuildCache:!0}}():r}(0,_s.J)((function(){Rs=void 0,Is=void 0,Ts=void 0,As=void 0}));var js=r("../utils/dist/lru-cache.js");const Us=["Desktop","Documents","Downloads","Music","Movies","Pictures","Library",".Trash"],Bs="/Volumes";function Ws(e){const t=e.replace(/\/{2,}/g,"/");return t.length>1&&t.endsWith("/")?t.slice(0,-1):t}function Hs(e,t){if("darwin"!==t.platform)return[];const r=Ws(e),n=r.toLowerCase(),o=Ws(t.homeDirectory),s="/"===r?1:r.split("/").length;return[...Us.map((e=>`${o}/${e}`)),Bs].filter((e=>function(e,t){return e!==t&&e.startsWith(t.endsWith("/")?t:`${t}/`)}(e.toLowerCase(),n))).map((e=>{const t=e.split("/").slice(s).join("/");return`${"/"===r?"":r}/${t}`}))}var qs=r("../utils/dist/safe-spawn-cwd.js"),zs=r("node:util");const Gs=8388608;var Vs=r("../../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/lib/index.js"),Ks=r("../../node_modules/.pnpm/jschardet@3.1.4/node_modules/jschardet/index.js");function Js(e){let t=1,r=0;for(;;){const n=e.indexOf("\n",r);if(-1===n)return t;t++,r=n+1}}const Zs="utf8",Xs="utf8bom",Qs="latin1",Ys={"windows-1250":"cp1250","windows-1251":"cp1251","windows-1252":"cp1252","windows-1253":"cp1253","windows-1254":"cp1254","windows-1255":"cp1255","windows-1256":"cp1256","windows-1257":"cp1257","windows-1258":"cp1258","iso-8859-1":"iso88591","iso-8859-2":"iso88592","iso-8859-5":"iso88595","iso-8859-6":"iso88596","iso-8859-7":"iso88597","iso-8859-8":"iso88598","iso-8859-9":"iso88599","iso-8859-15":"iso885915","iso-8859-16":"iso885916",shift_jis:"shiftjis","euc-jp":"eucjp","euc-kr":"euckr","iso-2022-jp":"iso2022jp","iso-2022-kr":"iso2022kr",gb2312:"gb2312",gbk:"gbk",gb18030:"gb18030",big5:"big5","big5-hkscs":"big5hkscs","koi8-r":"koi8r","koi8-u":"koi8u",ibm855:"cp855",ibm866:"cp866",maccyrillic:"maccyrillic","x-mac-cyrillic":"maccyrillic","utf-16le":"utf16le","utf-16be":"utf16be","utf-32le":"utf32le","utf-32be":"utf32be",johab:"johab",cp949:"cp949",cp932:"cp932"};function ei(e){return Ys[e]||e}function ti(e){return e.startsWith("\ufeff")?e.slice(1):e}function ri(e){const t=e.toLowerCase();return"latin-1"===t?Qs:"utf-8"===t?Zs:"utf-8-bom"===t||"utf-8 bom"===t?Xs:t}function ni(e){const t=[],r=[];let n=0;for(let o=e.indexOf("\n");-1!==o;o=e.indexOf("\n",n)){const s=13===e.charCodeAt(o-1);t.push(e.slice(n,s?o-1:o)),r.push(s?"\r\n":"\n"),n=o+1}return t.push(e.slice(n)),r.push(""),{lines:t,ends:r}}const oi=new zs.TextDecoder("utf-8",{fatal:!1}),si=new zs.TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),ii="�";function ai(e){return oi.decode(e)}function ci(e){let t=0,r=0,n=0,o=0;for(let s=0;s0?o--:n++}return r+=n,r>t}function li(e,t=1/0){let r=0,n=0;for(;r=194&&r<=223)n=2;else if(r>=224&&r<=239)n=3,224===r&&(o=160),237===r&&(s=159);else{if(!(r>=240&&r<=244))return 1;n=4,240===r&&(o=144),244===r&&(s=143)}let i=1;for(;i(1===i?s:191))break;i++}return i===n?void 0:i}function di(e){return e<128?1:e<2048?2:e<65536?3:4}var hi;!function(e){e.CRLF="CRLF",e.LF="LF"}(hi||(hi={}));const pi=[".mp4",".webm",".mov",".avi",".mkv",".wmv",".flv",".m4v"],fi=new Set(pi),mi=new zs.TextDecoder("utf-8",{fatal:!0}),gi=new zs.TextDecoder("latin1"),wi=Buffer.from([239,187,191]),yi={utf16le:Buffer.from([255,254]),utf16be:Buffer.from([254,255]),utf32le:Buffer.from([255,254,0,0]),utf32be:Buffer.from([0,0,254,255])},vi=8192,bi="UTF-8",Si="windows-1252",ki=/[^\u0000-\u007f\ufffd]/u,_i=/(?:\p{Script=Cyrillic}\p{M}*){3,}/gu,Ci=/(?:\p{Script=Greek}\p{M}*){3,}/gu,Ei=/(?:\p{Script=Hebrew}\p{M}*){3,}/gu,xi=new Map([["windows-1251",_i],["ISO-8859-5",_i],["KOI8-R",_i],["x-mac-cyrillic",_i],["IBM866",_i],["IBM855",_i],["ISO-8859-7",Ci],["windows-1253",Ci],["windows-1255",Ei],["ISO-8859-8",Ei],["TIS-620",/(?:\p{Script=Thai}\p{M}*){3,}/gu]]),Pi=/\p{Script=Latin}\p{M}*[\p{Script=Cyrillic}\p{Script=Greek}\p{Script=Hebrew}\p{Script=Thai}]|[\p{Script=Cyrillic}\p{Script=Greek}\p{Script=Hebrew}\p{Script=Thai}]\p{M}*\p{Script=Latin}/u,Ri=/[\p{L}\p{M}]+/gu,Ii=String.raw`[\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF\u0152\u0153\u0160\u0161\u017D\u017E\u0178]`,Ti=new RegExp(`[A-Za-z]${Ii}{1,2}(?!${Ii})|^${Ii}{1,2}[A-Za-z]`,"u"),Ai=new Map,$i=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".pdf",".zip",".tar",".gz",".exe",".dll",".so",".dylib",".bin",...pi]),Mi=/\.(png|jpg|jpeg|gif|webp|ico|bmp)$/i,Di=new Set([".ps1",".psm1",".psd1"]),Oi=/[^\u0000-\u007f]/u;function Fi(e){const t=e.toLowerCase(),r=t.lastIndexOf(".");return-1===r?"":t.substring(r)}function Ni(e){const t=Fi(e);return fi.has(t)}function Li(e){const t=Fi(e);return{encoding:"binary",lineEnding:hi.LF,isBinaryFile:!0,isImageFile:Mi.test(t),isVideoFile:fi.has(t)}}async function ji(e,t){return(await Ui(e,t)).text}async function Ui(e,t){const{stamp:r,buf:n}=await async function(e){const t=await(0,Co.open)(e,"r");try{return{stamp:await t.stat(),buf:await t.readFile()}}finally{await t.close()}}(e),o=qi(n);if(o.isBinaryFile)throw new Error("Binary file cannot be decoded as text");const s=Qi(e,r);let i;i=t||s||o.encoding;const{text:a,encoding:c}=ta(n,i),l=ti(a),u=c===Zs&&ra(n)?Xs:c;Yi(e,r,u);const d=function(e,t){if(t===Xs)return ra(e);const r=yi[ei(ri(t))];return void 0!==r&&e.subarray(0,r.length).equals(r)}(n,u);if(o.lineEnding===hi.CRLF){const e=l.match(/\r\n/g)?.length??0,t=(l.match(/\n/g)?.length??0)-e;return{text:l.replaceAll("\r\n","\n"),encoding:u,bom:d,lineEnding:e>t?"CRLF":"LF"}}return{text:l,encoding:u,bom:d,lineEnding:"LF"}}async function Bi(e,t){if("binary"===t.encoding)return void Xi(e);let r;try{r=await(0,Co.stat)(e)}catch{return void Xi(e)}r.size===t.buffer.byteLength?Yi(e,r,t.encoding):Xi(e)}async function Wi(e,t,r,o){let s,i;try{s=r?await async function(e,t){try{return await Hi(e)}catch{}const r=Fi(e);if($i.has(r))return Li(e);try{return await async function(e){const t=new Map;let r=0;for await(const n of Ji(e)){if(r>=100)break;try{const e=await Hi(n);if(!e.isBinaryFile){const r=`${e.encoding}:${e.lineEnding}`,n=t.get(r);if(n){if(n.count++,n.count>=3)return n.format}else t.set(r,{format:e,count:1})}r++}catch(e){}}let n;for(const e of t.values())(!n||e.count>n.count)&&(n=e);return n?n.format:Zi()}(t)}catch{return Zi()}}(e,r):await Hi(e)}catch{const t=Fi(e);s=$i.has(t)?Li(e):Zi()}const a=()=>i??=async function(e){try{const t=await(0,Co.stat)(e);if(!t.isFile()||t.size>Gs)return;return await(0,Co.readFile)(e)}catch{return}}(e),c=Qi(e,await async function(e){try{return await(0,Co.stat)(e)}catch{return}}(e));let l;if(!s.isBinaryFile){let r;o?r=ri(o):c?r=ri(c):(r=ri(s.encoding),r===Xs||Vs.encodingExists(ei(r))||(r=Zs),r!==Zs&&r!==Xs||(r=await async function(e,t){const r=await t();return void 0===r||(0,n.isUtf8)(r)?e:ea(r).encoding===Qs?Qs:e}(r,a))),r===Zs&&!o&&function(e,t){return"win32"===process.platform&&Di.has(Fi(e))&&Oi.test(t)&&!t.startsWith("#!")}(e,t)&&(await async function(e){try{return await(0,Co.stat)(e),!1}catch(e){return e instanceof Error&&"code"in e&&"ENOENT"===e.code}}(e)||await async function(e){const t=await e();return void 0!==t&&(0,n.isAscii)(t)}(a))&&(r=Xs);const i=r===Xs||r===Zs&&!o&&await na(e,wi),u=yi[ei(r)];i?l=wi:u&&await na(e,u)&&(l=u),s={...s,encoding:i?Xs:r}}const u=Js(t),d=t.includes("\r\n")?void 0:await async function(e,t){if(t.isBinaryFile)return;const r=await e();if(void 0===r||!r.includes(13))return;const n=ti(ta(r,t.encoding).text);return function(e){let t=!1,r=!1;for(let n=e.indexOf("\n");-1!==n;n=e.indexOf("\n",n+1))if(13===e.charCodeAt(n-1)?t=!0:r=!0,t&&r)return!0;return!1}(n)?n:void 0}(a,s);if(void 0!==d?t=function({content:e,existing:t,defaultEnding:r}){const n=ni(t),o=ni(e),s=function({before:e,after:t}){const r=new Int32Array(t.length).fill(-1);let n=0;for(;n0&&i>0&&(s+1)*(i+1)<=4e6){const o=i+1,a=new Uint16Array((s+1)*o);for(let r=s-1;r>=0;r--)for(let s=i-1;s>=0;s--)a[r*o+s]=e[n+r]===t[n+s]?a[(r+1)*o+s+1]+1:Math.max(a[(r+1)*o+s],a[r*o+s+1]);for(let c=0,l=0;c=a[c*o+l+1]?c++:l++}let a=-1,c=-1;for(let n=0;n<=t.length;n++){const o=n===t.length?e.length:r[n];if(-1!==o){if(o-a==n-c)for(let e=1;e50&&/^[A-Za-z0-9+/]*={0,2}$/.test(t))try{const e=Buffer.from(t,"base64");if(e.length>0){const r=Math.floor(.5*t.length);if(e.length>=r)return e}}catch{}return Buffer.from(e,"latin1")}(t);return{lines:u,buffer:e,format:s}}const h=l?ti(t):t,p=s.encoding===Xs?Zs:s.encoding,f=p===Zs?await async function(e,t){if(!t.includes(ii))return;const r=await e();return void 0===r?void 0:function(e,t){if(!e.includes(ii)||(0,n.isUtf8)(t))return;const r=function(e){const t=[];let r=0;for(const n of si.decode(e)){const o=n.codePointAt(0)??0;if(65533!==o){r+=di(o);continue}const s=ui(e,r);void 0===s?(t.push(void 0),r+=3):(t.push(e.subarray(r,r+s)),r+=s)}return r===e.length?t:void 0}(t),o=e.split(ii);if(void 0===r||o.length-1!==r.length)return;const s=[];for(let e=0;e=Math.max(0,e.length-3);t--){const r=e[t];if(r<128)return e;if(r>=192){const n=r>=240?4:r>=224?3:2;return e.length-t=e.length);o+=2){if(0===e[o+1]){const r=e[o];(r>=32&&r<=126||9===r||10===r||13===r)&&t++}if(0===e[o]){const t=e[o+1];(t>=32&&t<=126||9===t||10===t||13===t)&&r++}}return t>.8*n?"UTF-16LE":r>.8*n?"UTF-16BE":null}(e)??function(e){if(e.length<8)return null;if(0===e[0]&&0===e[1]&&254===e[2]&&255===e[3])return"UTF-32BE";if(255===e[0]&&254===e[1]&&0===e[2]&&0===e[3])return"UTF-32LE";let t=0,r=0;const n=Math.min(50,Math.floor(e.length/4));for(let o=0;o<4*n&&!(o+3>=e.length);o+=4){if(0===e[o]&&0===e[o+1]&&0===e[o+2]){const r=e[o+3];(r>=32&&r<=126||9===r||10===r||13===r)&&t++}if(0===e[o+1]&&0===e[o+2]&&0===e[o+3]){const t=e[o];(t>=32&&t<=126||9===t||10===t||13===t)&&r++}}return t>.8*n?"UTF-32BE":r>.8*n?"UTF-32LE":null}(e);if(t)return{encoding:t,lineEnding:Gi(Vs.decode(e.subarray(0,vi),ei(ri(t)))),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};if(!function(e){const t=Math.min(vi,e.length);if(0===t)return!0;for(let r=0;r=8&&137===r[0]&&80===r[1]&&78===r[2]&&71===r[3]&&13===r[4]&&10===r[5]&&26===r[6]&&10===r[7]||255===r[0]&&216===r[1]&&255===r[2]||r.length>=12&&82===r[0]&&73===r[1]&&70===r[2]&&70===r[3]&&87===r[8]&&69===r[9]&&66===r[10]&&80===r[11]||r.length>=6&&71===r[0]&&73===r[1]&&70===r[2]&&56===r[3]&&(55===r[4]||57===r[4])&&97===r[5])),isVideoFile:!1};var r,o,s;if((0,n.isUtf8)(e)&&(!e.includes(27)||!(0,n.isAscii)(e)))return{encoding:bi,lineEnding:zi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};if(!(0,n.isUtf8)(e)&&(o=ai(e),s=e.length,ci(o)||1024*li(o)<=s&&!ki.test(o)))return{encoding:bi,lineEnding:zi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};const i=Ks.detect(e);let a=i.confidence>.7?i.encoding:"utf-8";"ascii"===a&&(a="utf-8");const c=xi.get(a);return void 0!==c&&(a=function(e,t,r){const n=ei(ri(t));if(!Vs.encodingExists(n))return t;const o=Vs.decode(e,n);return Pi.test(o)&&function(e,t,r){const n=t.match(r)?.length??0;let o=0;for(const[t]of Vs.decode(e,Si).matchAll(Ri))Ti.test(t)&&o++;return o>n}(e,o,r)?Si:t}(e,a,c)),a!==Si||function(e,t){const r=ei(ri(t));return!Vs.getDecoder(r).write(e).includes(ii)}(e,a)||(a="utf-8"),{encoding:a??"utf-8",lineEnding:zi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function zi(e){let t=0,r=0;for(let n=0;n0&&13===e[n-1]?t++:r++);return Vi(t,r)}function Gi(e){const t=e.match(/\n/g)?.length??0,r=e.match(/\r\n/g)?.length??0;return Vi(r,t-r)}function Vi(e,t){return 0===e&&0===t?hi.LF:e/(e+t)*100>=5?hi.CRLF:hi.LF}async function Ki(e){const t=await(0,Co.open)(e,"r");try{const e=Buffer.allocUnsafe(vi),{bytesRead:r}=await t.read(e,0,vi,0);return e.subarray(0,r)}finally{await t.close()}}async function*Ji(e){const t=new Set(["node_modules",".git",".svn",".hg","dist","build","out",".next",".cache","coverage","__pycache__",".venv","venv",".turbo"]);try{const r=await(0,Co.readdir)(e,{withFileTypes:!0});for(const n of r){if(n.name.startsWith(".")&&".gitignore"!==n.name)continue;const r=(0,s.join)(e,n.name);n.isDirectory()?t.has(n.name)||(yield*Ji(r)):n.isFile()&&(yield r)}}catch(e){return}}function Zi(){return{encoding:Zs,lineEnding:"win32"===process.platform?hi.CRLF:hi.LF,isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function Xi(e){Ai.delete(e)}function Qi(e,t){const r=Ai.get(e);if(void 0!==r)return void 0!==t&&r.size===t.size&&r.mtimeMs===t.mtimeMs?r.encoding:void Ai.delete(e)}function Yi(e,t,r){if(Ai.has(e)&&Ai.delete(e),Ai.set(e,{encoding:r,size:t.size,mtimeMs:t.mtimeMs}),Ai.size<=100)return;const n=Ai.keys().next().value;void 0!==n&&Ai.delete(n)}function ea(e){try{return{text:mi.decode(e),encoding:Zs}}catch{const t=ai(e);return ci(t)?{text:t,encoding:Zs}:{text:gi.decode(e),encoding:Qs}}}function ta(e,t){const r=ri(t);if(r===Zs||r===Xs||"ascii"===r){const t=ea(e);return r===Xs&&t.encoding===Zs?{text:t.text,encoding:Xs}:t}if(r===Qs)return{text:gi.decode(e),encoding:Qs};try{const t=ei(r);if(Vs.encodingExists(t))return{text:Vs.decode(e,t),encoding:r}}catch{}return ea(e)}function ra(e){return e.length>=wi.length&&e[0]===wi[0]&&e[1]===wi[1]&&e[2]===wi[2]}async function na(e,t){try{return(await Ki(e)).subarray(0,t.length).equals(t)}catch{return!1}}var oa=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js");class sa{constructor({ttlMs:e,now:t=Date.now}){this.entries=new Map,this.nextSweepAtMs=0,this.ttlMs="function"==typeof e?e:sa.validated(e),this.now=t}static validated(e){if(!Number.isFinite(e)||e<=0)throw new Error(`TTL cache requires a positive ttlMs, got ${e}`);return()=>e}get(e){const t=this.entries.get(e);if(void 0!==t){if(!(t.expiresAtMs<=this.now()))return t.value;this.entries.delete(e)}}has(e){const t=this.entries.get(e);return!(void 0===t||t.expiresAtMs<=this.now()&&(this.entries.delete(e),1))}get size(){return this.entries.size}set(e,t){const r=this.now(),n=this.ttlMs();if(this.entries.set(e,{value:t,expiresAtMs:r+n}),!(r1048576?e:await async function(e,t){const r=function(e){const t=Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=qi(t);return r.isBinaryFile?ai(t):ti(ta(t,r.encoding).text)}(t);return function(e,t){if(!(0,n.isUtf8)(e))return!1;const r=e.toString("utf8");return(r.startsWith("\ufeff")?r.slice(1):r)===t}(t,r)?e:async function(e,t){const r=await(la??=(0,Co.mkdtemp)((0,s.join)((0,o.tmpdir)(),"cursorignore-utf8-")).then((e=>(process.once("exit",(()=>{try{(0,xo.rmSync)(e,{recursive:!0,force:!0})}catch{}})),e))),la),n=(0,s.join)(r,`cursorignore-${ua(e)}-${ua(t)}.txt`);if(await da(n))return n;const i=`${n}.${process.pid}.${Date.now()}.tmp`;return await(0,Co.writeFile)(i,t,"utf8"),await(0,Co.rename)(i,n),n}(e,r)}(e,await(0,Co.readFile)(e));return aa.set(e,{mtimeMs:t.mtimeMs,size:t.size,ripgrepPath:i}),i}function pa(e){return Promise.all(e.map((e=>async function(e){const t=ca.get(e);if(void 0!==t)return t;const r=ha(e).catch((()=>e)).finally((()=>{ca.delete(e)}));return ca.set(e,r),r}(e))))}(0,_s.J)((function(){aa.clear(),ca.clear()}));var fa=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function ma(e){if(e.aborted)return{aborted:Promise.resolve("aborted"),[Symbol.dispose](){}};let t=()=>{};const r=new Promise((e=>{t=()=>e("aborted")}));return e.addEventListener("abort",t,{once:!0}),{aborted:r,[Symbol.dispose](){e.removeEventListener("abort",t)}}}function ga(e,{root:t,searchPaths:r=[],includeGlobs:n=[],excludeGlobs:s=[],caseSensitive:i=!1,cursorIgnoreFiles:a=[],sandboxPolicy:c={type:"insecure_none"},noIgnoreVcs:l=!1,followSymlinks:u=!1,source:d="ripwalk"}){const h=["--files","--hidden","--no-require-git","--no-config","--color=never"],p=function(e=process.env){const t=e.CURSOR_RIPWALK_THREADS?.trim();if(void 0!==t&&""!==t){const e=Number(t);if(Number.isInteger(e)&&e>=0)return 0===e?void 0:e}return Math.min(2,(0,o.availableParallelism)())}();void 0!==p&&h.push("--threads",String(p)),u&&h.push("--follow"),l&&h.push("--no-ignore-vcs"),i&&h.push("--case-sensitive");for(const e of n)h.push("--iglob",e);for(const e of s)h.push("--iglob",`!${e}`);const f=r.length>0?["--",...r]:[];let m,g=!1;const w=new Promise((e=>{m=e}));return{lines:async function*(){const r={stack:[],error:void 0,hasError:!1};try{const n=[];for(const e of await pa(a))n.push("--cursor-ignore",e);const o=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,function(e,t,r,n){const o=(0,Oo.spawnInSandbox)((0,Oo.Ko)(),t,{cwd:r},n),s=[];o.stderr?.on("data",(e=>{s.push(e)}));const i=new Promise(((e,t)=>{o.on("error",t),o.on("close",(t=>e(t??0)))}));if(i.catch((()=>{})),!o.stdout)throw new Error("No stdout from ripgrep process");const a=ma(e.signal);return{stdout:o.stdout,processExit:i,stderr:()=>Buffer.concat(s).toString(),aborted:a.aborted,[Symbol.dispose](){a[Symbol.dispose](),o.kill()}}}(e,[...h,...n,...f],t,c),!1);let s=0;const i=async function*(e){const t=new ia.StringDecoder("utf8");let r="";for await(const n of e){r+=t.write(n);const e=r.split("\n");r=e.pop()??"",e.length>0&&(yield e)}r+=t.end(),r&&(yield[r])}(o.stdout)[Symbol.asyncIterator]();e:for(;;){const t=await Promise.race([i.next(),o.aborted]);if("aborted"===t){g=!0,m(!0);break}if(t.done)break;for(const r of t.value){if(e.signal.aborted){g=!0,m(!0);break e}s++,yield r}}if(s>0);else if(!g){const e=await o.processExit;if(0!==e&&1!==e){const t=o.stderr();throw new Error(`Ripgrep failed (exit ${e}) with no results${t?`: ${t}`:""}`)}}g||m(!1)}catch(e){r.error=e,r.hasError=!0}finally{fa(r)}}(),didTimeout:w}}var wa=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});let ya;function va(e=process.env){if(void 0!==ya)return ya;const t=e.CURSOR_RIPWALK_CACHE_TTL_MS?.trim();if(void 0!==t&&""!==t){const e=Number(t);if(Number.isFinite(e)&&e>0)return e}return 2e4}function ba({root:e,searchPaths:t=[],includeGlobs:r=[],excludeGlobs:n=[],caseSensitive:o=!1,cursorIgnoreFiles:s=[],sandboxPolicy:i={type:"insecure_none"},noIgnoreVcs:a=!1,followSymlinks:c=!1}){return JSON.stringify({root:e,searchPaths:t,includeGlobs:r,excludeGlobs:n,caseSensitive:o,cursorIgnoreFiles:s,sandboxPolicy:i,noIgnoreVcs:a,followSymlinks:c})}class Sa{constructor(e=()=>va()){this.cache=new sa({ttlMs:e})}get size(){return this.cache.size}clear(){this.cache.clear()}delete(e){this.cache.delete(ba(e))}walk(e,t){const r=ba(t);let n,o=!1,s=!1;const i=new Promise((e=>{n=e})),a=e=>{s||(s=!0,n(e))};return{lines:async function*(){const n=this.cache.get(r);if(void 0!==n){const t={stack:[],error:void 0,hasError:!1};try{const s=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,ma(e.signal),!1),i=await Promise.race([n.linesPromise.then((e=>({type:"lines",lines:e})),(e=>({type:"error",error:e}))),s.aborted.then((()=>({type:"aborted"})))]);if("aborted"===i.type)return o=!0,void a(!0);if("lines"===i.type)return a(!1),void(yield*i.lines);this.cache.get(r)===n&&this.cache.delete(r)}catch(e){t.error=e,t.hasError=!0}finally{wa(t)}}let s,i;const c={linesPromise:new Promise(((e,t)=>{s=e,i=t}))};c.linesPromise.catch((()=>{})),this.cache.set(r,c);const l=[];let u,d=!1;try{const r=ga(e,t);for await(const e of r.lines)l.push(e),yield e;if(await r.didTimeout)return o=!0,u=new Error("Ripwalk aborted before cacheable result was available"),void a(!0);d=!0}catch(e){throw u=e,e}finally{d?s?.(l):(this.cache.get(r)===c&&this.cache.delete(r),i?.(u??new Error("Ripwalk terminated before cacheable result was available"))),o||a(!1)}}.bind(this)(),didTimeout:i}}}const ka=16777216,_a=new Set([32,9,10,13]),Ca="a path through /proc or /dev/fd",Ea={kind:"none"},xa={kind:"stop"};function Pa(e,t){return{kind:"refused",refused:{name:e,reason:t}}}async function Ra(e){const t=await async function(e){if(void 0===await(0,Co.lstat)(e).catch((()=>{})))return Ea;if(await Aa(Buffer.from(e)))return Pa(".git",Ca);const t=await(0,Co.stat)(e).catch((()=>{}));if(void 0===t)return Ea;if(!t.isFile())return Ia(e);const r=await Oa(e,{whole:1048576});if("not-regular"===r.kind)return Pa(".git","not a regular file");if("bytes"!==r.kind)return xa;const n=Buffer.from("gitdir: "),o=ja(r.bytes);if(!o.subarray(0,n.length).equals(n)||o.length<=n.length)return xa;const i=La({dir:(0,s.dirname)(e),target:Ua(o.subarray(n.length))});if(await Aa(i))return Pa(".git",Ca);const a=await Ia(i);return"none"===a.kind?xa:a}(Na(e,".git").toString());return"none"!==t.kind?t:Ia(e)}async function Ia(e){const t=await async function(e){const t=await(0,Co.lstat)(e).catch((()=>{}));if(void 0===t||t.isDirectory())return Ea;if(t.isSymbolicLink()){const t=await(0,Co.readlink)(e,{encoding:"buffer"}).catch((()=>{}));return"refs/"===t?.subarray(0,5).toString("latin1")?"valid":Ea}if(!t.isFile())return Pa("HEAD","not a regular file");const r=await Oa(e,{prefix:255});if("not-regular"===r.kind)return Pa("HEAD","not a regular file");if("bytes"!==r.kind)return Ea;const n=Ua(r.bytes.subarray(0,255)).toString("latin1");if(n.startsWith("ref:")){let e=4;for(;e{}))){if(await Aa(n))return Pa("commondir",Ca);const t=await Oa(n,{whole:ka});switch(t.kind){case"bytes":{if(0===t.bytes.length)return xa;const n=La({dir:e,target:Ua(ja(t.bytes))});if(await Aa(n))return Pa("commondir",Ca);const o=await(0,Co.realpath)(n,{encoding:"buffer"}).catch((()=>{}));if(void 0===o)return Ea;r=o;break}case"too-large":return Pa("commondir","over the size cap");case"not-regular":return Pa("commondir","not a regular file");case"directory":case"unreadable":return xa;default:throw new Error(`unhandled read ${String(t)}`)}}for(const e of["objects","refs"]){const t=Na(r,e);if(await Aa(t))return Pa(e,Ca);if(!await Fa(t))return Ea}return{kind:"repository",gitDir:e,commonDir:r}}async function Ta({gitDir:e,commonDir:t}){const r=[["HEAD",Na(e,"HEAD")],["config.worktree",Na(e,"config.worktree")],["config",Na(t,"config")],["info/exclude",Na(Na(t,"info"),"exclude")]];for(const[e,t]of r){if(await Aa(t))return{name:e,reason:Ca};const r=await(0,Co.stat)(t).catch((()=>{}));if(void 0!==r&&!r.isDirectory()&&!await Da(r)){if(!r.isFile())return{name:e,reason:"not a regular file"};if(r.size>ka)return{name:e,reason:"over the size cap"}}}}async function Aa(e){if("win32"===process.platform)return!1;const t=$a(e.toString("latin1")).reverse();let r="/",n=0;for(let e=t.pop();void 0!==e;e=t.pop()){if(".."===e){r=(0,s.dirname)(r);continue}const o=(0,s.join)(r,e),i="darwin"===process.platform?o.toLowerCase():o;if(["/proc","/dev/fd"].some((e=>i===e||i.startsWith(`${e}/`))))return!0;const a=await(0,Co.readlink)(Buffer.from(o,"latin1"),{encoding:"buffer"}).catch((()=>{}));if(void 0===a){r=o;continue}if(++n>40)return!1;const c=a.toString("latin1");(0,s.isAbsolute)(c)&&(r="/"),t.push(...$a(c).reverse())}return!1}function $a(e){return e.split("/").filter((e=>""!==e&&"."!==e))}let Ma;async function Da(e){if(!e.isCharacterDevice())return!1;Ma??=(0,Co.stat)("/dev/null").catch((()=>{}));const t=await Ma;return void 0!==t&&e.dev===t.dev&&e.ino===t.ino}async function Oa(e,t){const r=xo.constants.O_RDONLY|(xo.constants.O_NONBLOCK??0)|(xo.constants.O_NOCTTY??0),n=await(0,Co.open)(e,r).catch((()=>{}));if(void 0===n)return{kind:"unreadable"};try{const e=await n.stat();if(e.isDirectory())return{kind:"directory"};if(!e.isFile())return{kind:"not-regular"};if("whole"in t&&e.size>t.whole)return{kind:"too-large"};const r="whole"in t?t.whole:t.prefix,o=Buffer.alloc(Math.min(r+1,e.size+1));let s=0;for(;st.whole?{kind:"too-large"}:{kind:"bytes",bytes:o.subarray(0,s)}}catch{return{kind:"unreadable"}}finally{await n.close().catch((()=>{}))}}function Fa(e){return(0,Co.access)(e,xo.constants.X_OK).then((()=>!0),(()=>!1))}function Na(e,t){const r=Buffer.isBuffer(e)?e:Buffer.from(e),n=r.toString("latin1").endsWith(s.sep)?"":s.sep;return Buffer.concat([r,Buffer.from(`${n}${t}`)])}function La({dir:e,target:t}){return(0,s.isAbsolute)(t.toString("latin1"))?t:Buffer.concat([Na(e,""),t])}function ja(e){let t=e.length;for(;t>0&&(10===e[t-1]||13===e[t-1]);)t--;return e.subarray(0,t)}function Ua(e){const t=e.indexOf(0);return-1===t?e:e.subarray(0,t)}const Ba=[{stage:"prod",gitHost:"origin.cursor.com",gitCdnHost:"gitcdn.origin.cursor.com",cloneKitS3Host:"git-forge-prod-bundles.s3.us-east-1.amazonaws.com",rawUserContentHost:"raw.cursorusercontent.com",apiHost:"api.origin.cursor.com",internalHost:"origin-prod.internal.cursor.com"},{stage:"staging",gitHost:"origin-staging.cursor.com",gitCdnHost:"gitcdn.origin-staging.cursor.com",cloneKitS3Host:"git-forge-staging-bundles.s3.us-east-1.amazonaws.com",rawUserContentHost:"raw.staging.cursorusercontent.com",apiHost:"api.origin-staging.cursor.com",internalHost:"origin-staging.internal.cursor.com"},{stage:"test",gitHost:"origin-test.cursor.com",gitCdnHost:"gitcdn.origin-test.cursor.com",cloneKitS3Host:"git-forge-test-bundles.s3.us-east-1.amazonaws.com",rawUserContentHost:"raw.test.cursorusercontent.com",apiHost:"api.origin-test.cursor.com",internalHost:"origin-test.internal.cursor.com"}];function Wa(e){let t=e.length;for(;t>0&&47===e.charCodeAt(t-1);)t--;const r=e.slice(0,t).replace(/\.git$/i,"");return r&&"/"!==r?r.startsWith("/")?r:`/${r}`:""}function Ha(e,t){const r=Wa(t);return r?`${e}${r}`.toLowerCase():""}new Map(Ba.map((e=>[e.gitHost,e.apiHost]))),new Map(Ba.map((e=>[e.gitHost,e.gitCdnHost]))),new Map(Ba.map((e=>[e.gitHost,e.cloneKitS3Host]))),new Map(Ba.map((e=>[e.gitHost,e.rawUserContentHost]))),new Map(Ba.map((e=>[e.apiHost,e.gitHost]))),new Map(Ba.map((e=>[e.apiHost,e.internalHost])));const qa=new Map;function za(e){const t=qa.get(e);if(void 0!==t)return t;const r=function(e){const t=e.trim();if(!t)return"";try{const e=function(e){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(e))return e;const t=`https://${e}`;try{return new URL(t),t}catch{const r=e.match(/^([^@/\s]+@)?([^:/\s]+):(.+)$/);return r?`ssh://${r[1]??""}${r[2]}/${r[3]}`:t}}(t),r=new URL(e);return Ha(r.hostname,r.pathname)}catch{const e=t.replace(/^(?:https?|ssh|git):\/\//i,""),r=e.indexOf("/"),n=-1===r?e:e.slice(0,r),o=-1===r?"":e.slice(r);return Ha(n.includes("@")?n.slice(n.lastIndexOf("@")+1):n,o)}}(e);return qa.size>=16384&&qa.clear(),qa.set(e,r),r}function Ga(e){return/^origin(-[a-z0-9]+)?\.cursor\.com$/i.test(e)}(function(e){const t=Ba.find((t=>t.stage===e));if(void 0===t)throw new Error(`unknown Origin stage: ${e}`);return t})("prod").gitHost;const Va=new Map;function Ka(e){if(void 0===e)return;if(Va.has(e))return Va.get(e);const t=function(e){const t=e?function(e){let t=e.trim();if(""!==t){t.startsWith("git@")?t=`https://${t.slice(4).replace(":","/")}`:/^[a-z][a-z0-9+.-]*:\/\//i.test(t)&&!/^https?:\/\//i.test(t)?t=t.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"https://"):/^https?:\/\//i.test(t)||(t=`https://${t}`);try{return new URL(t)}catch{return}}}(e):void 0;if(void 0===t||!Ga(t.hostname))return;const r=Wa(t.pathname).split("/").filter(Boolean),n=3===r.length&&"git"===r[0]?.toLowerCase(),o=2===r.length&&"git"!==r[0]?.toLowerCase();if(!n&&!o)return;const s=n?r[1]:r[0],i=n?r[2]:r[1];return s&&i?Object.freeze({hostname:t.hostname,owner:s,name:i}):void 0}(e);return Va.size>=16384&&Va.clear(),Va.set(e,t),t}function Ja(e){return void 0!==function(e){const t=Ka(e);return void 0===t?void 0:{owner:t.owner,name:t.name}}(e)}new Set(["github.com","www.github.com"]),new RegExp("^tmp-[0-9a-f]{16}$");const Za=(0,l.h)("local-exec:git-root"),Xa=new WeakMap,Qa=new Map;function Ya(e,t,r){return ec(e,t,r).then((e=>"repository"===e.kind?e.root:null))}function ec(e,t,r){const n=performance.now();let o=Xa.get(t);void 0===o&&(o=new Map,Xa.set(t,o));const s=o.get(r);if(void 0!==s&&tc(s,n))return s.result;for(const[e,t]of o)tc(t,n)||o.delete(e);const i=t.guardedRootLookup,a=void 0===i?{result:oc(e,t,r,void 0),windowStart:n}:{result:rc(e,t,r,i.timeoutMs),windowStart:void 0};return void 0===a.windowStart&&a.result.then((()=>{a.windowStart=performance.now()})),o.set(r,a),a.result}function tc(e,t){return void 0===e.windowStart||t-e.windowStart<5e3}async function rc(e,t,r,n){const o=new AbortController,i=performance.now()+n,a=await(0,Or.wj)(async function({ctx:e,gitExecutor:t,startPath:r,deadline:n,settled:o}){const i=await function(e){let t=Qa.get(e);if(void 0===t){t=async function(e){const t=await(0,Co.realpath)(e).catch((()=>{}));if(void 0===t)return;const r=function(){const e=(process.env.GIT_DISCOVERY_ACROSS_FILESYSTEM??"").toLowerCase();return!["","0","false","no","off"].includes(e)}()?void 0:(await(0,Co.stat)(t).catch((()=>{})))?.dev;for(let e=t;;){const t=await Ra(e);switch(t.kind){case"refused":return t.refused;case"stop":return;case"repository":return Ta(t);case"none":break;default:throw new Error(`unhandled probe ${String(t)}`)}const n=(0,s.dirname)(e);if(n===e||void 0!==r&&(await(0,Co.stat)(n).catch((()=>{})))?.dev!==r)return;e=n}}(e),Qa.set(e,t);const r=()=>{Qa.delete(e)};t.then(r,r)}return t}(r);if(o.aborted)return{kind:"unknown",reason:"timed-out"};if(void 0!==i)return Za.warn(e,"findGitRoot: not starting git; its answer is unknown",{adminFile:i.name,reason:i.reason}),{kind:"unknown",reason:"refused"};const a=Math.ceil(n-performance.now());return a<=0?{kind:"unknown",reason:"timed-out"}:oc(e,t,r,a)}({ctx:e,gitExecutor:t,startPath:r,deadline:i,settled:o.signal}),n).catch((t=>t instanceof Or.MU?{kind:"unknown",reason:"timed-out"}:(Za.warn(e,"findGitRoot: the admin file check failed; not starting git",{code:nc(t)}),{kind:"unknown",reason:"refused"}))).finally((()=>{o.abort()}));return"unknown"===a.kind&&"timed-out"===a.reason&&Za.warn(e,"findGitRoot: the lookup ran past its bound; its answer is unknown",{timeoutMs:n}),a}function nc(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:void 0}async function oc(e,t,r,n){try{return{kind:"repository",root:(await t.exec(e,r,["rev-parse","--show-toplevel"],{...void 0===n?{}:{timeout:n},caller:"findGitRoot"})).stdout.trim()}}catch(e){return void 0!==n&&function(e){return"object"==typeof e&&null!==e&&"killed"in e&&!0===e.killed}(e)?{kind:"unknown",reason:"timed-out"}:{kind:"none"}}}async function sc(e,t,r){try{return(await t.exec(e,r,["config","--get","remote.origin.url"],{caller:"getGitRemoteUrl"})).stdout.trim()}catch{return}}function ic(e){const t=e.trim();if(""===t)return t;try{const e=new URL(t);return""===e.host?cc(t)??e.toString():(e.username="",e.password="",e.toString())}catch{return function(e){const t=e.replace(/^[\u0000-\u0020]+|[\u0000-\u0020]+$/g,"").replace(/[\t\n\r]/g,""),r=t.indexOf(":"),n=t.slice(0,r);if(r<0||!/^[A-Za-z][A-Za-z0-9+.-]*$/.test(n))return;const o=t.slice(r+1),s=ac.has(n.toLowerCase());let i;if(s)i=o.replace(/^[/\\]+/,"");else{if(!o.startsWith("//"))return;i=o.slice(2)}const a=i.search(s?/[/?#\\]/:/[/?#]/),c=a<0?i.length:a,l=i.slice(0,c),u=l.lastIndexOf("@");return u<0?void 0:`${t.slice(0,t.length-i.length)}${l.slice(u+1)}${i.slice(c)}`}(t)??cc(t)??t}}const ac=new Set(["ftp","file","http","https","ws","wss"]);function cc(e){const t=e.indexOf("/"),r=t<0?e:e.slice(0,t),n=r.indexOf(":"),o=r.lastIndexOf("@",r.lastIndexOf(":"));if(!(n<0||o<0||r.indexOf("@")`/${s.posix.relative(e,t)}`))}var dc=r("../../node_modules/.pnpm/picomatch@4.0.5/node_modules/picomatch/index.js");function hc(e,t){return e.some((e=>{return"*"===e.url.trim()?(e.patterns??[]).some((e=>mc(e.pattern,t))):!((r=e.url).includes("://")||r.includes("github.com")||r.includes("gitlab.com")||r.includes("bitbucket.org")||r.includes("@"))&&mc(e.url,t);var r}))}function pc(e,t,r){return fc(e.url,t)&&(e.patterns??[]).some((e=>mc(e.pattern,r)))}function fc(e,t){return e.includes("*")?"*"===e.trim()||function(e,t){const r=e.trim();return!!mc(r,t)||!!r.startsWith("*/")&&mc(`**/${r.slice(2)}`,t)}(bc(e),bc(t)):bc(e)===bc(t)}function mc(e,t){const r=e.trim();return!("."!==t&&""!==t||"**"!==r&&"**/*"!==r)||function(e){const t=yc.get(e);if(void 0!==t)return t;let r;try{const t=dc(e,{dot:!0});r=r=>{try{return t(r)}catch{return e===r}}}catch{r=t=>e===t}return vc(yc,gc,e,r)}(r)(t)}const gc=2048,wc=new Map,yc=new Map;function vc(e,t,r,n){if(e.set(r,n),e.size>t){const t=e.keys().next().value;void 0!==t&&e.delete(t)}return n}function bc(e){const t=wc.get(e);if(void 0!==t)return t;const r=(function(e){const t=Ka(e);if(void 0!==t)return`${t.hostname}/git/${t.owner}/${t.name}`.toLowerCase()}(n=e)??za(n))||function(e){let t=e.trim();t.startsWith("git@")&&(t=`https://${t.slice(4).replace(":","/")}`),/^[a-z][a-z0-9+.-]*:\/\//i.test(t)&&!/^https?:\/\//i.test(t)&&(t=t.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"https://")),/^https?:\/\//i.test(t)||(t=`https://${t}`);try{const e=new URL(t),r=e.pathname.replace(/\/+$/,"").replace(/\.git$/i,"").replace(/\/+$/,"");return e.hostname+r}catch{return t=t.replace(/^https?:\/\//i,""),t=t.replace(/[?#].*$/,""),t=t.replace(/\/+$/,""),t=t.replace(/\.git$/i,""),t=t.replace(/\/+$/,""),t}}(e).toLowerCase();var n;return vc(wc,2048,e,r)}function Sc(e){if("object"==typeof e&&null!==e&&"code"in e){const t=e.code;if("string"==typeof t)return t}}function kc(e){if(e instanceof Error)return e.message;if("object"==typeof e&&null!==e&&"message"in e){const t=e.message;if("string"==typeof t)return t}return""}(0,_s.J)((function(){wc.clear(),yc.clear()}));const _c=[".gitignore",".cursorignore"];async function Cc(e){if(!(0,s.isAbsolute)(e))return null;const t=await(0,Yo.DN)(e);return null===t?null:t}function Ec(e,t){if(!e||0===e.length)return[...t];const r=new Set(e);for(const e of t)r.has(e)&&r.delete(e),r.add(e);return[...r]}class xc{constructor(e,t,r,n={}){this.disposeRequested=!1,this.initIgnoreService=()=>Ic.init((0,y.q6)(),e,r??[process.cwd()],t),!0!==n.deferInit&&this.ensureStarted()}ensureStarted(){if(void 0===this.ignoreServicePromise){if(this.disposeRequested)return Promise.reject(new Error("LazyIgnoreService was disposed before its ignore-file scan started"));this.ignoreServicePromise=this.initIgnoreService()}return this.ignoreServicePromise}isIgnoredByAny(e){return this.ensureStarted().then((t=>t.isIgnoredByAny(e)))}isGitIgnored(e){return this.ensureStarted().then((t=>t.isGitIgnored(e)))}isCursorIgnored(e,t){return this.ensureStarted().then((r=>r.isCursorIgnored(e,t)))}isRepoBlocked(e){return this.ensureStarted().then((t=>t.isRepoBlocked(e)))}listCursorIgnoreFilesByRoot(e){return this.ensureStarted().then((t=>t.listCursorIgnoreFilesByRoot(e)))}getCursorIgnoreMapping(){return this.ensureStarted().then((e=>e.getCursorIgnoreMapping()))}getShellSandboxIgnoreMapping(e){return this.ensureStarted().then((t=>t.getShellSandboxIgnoreMapping(e)))}getGitIgnoreMapping(){return this.ensureStarted().then((e=>e.getGitIgnoreMapping()))}getRepoBlockExcludeGlobs(e){return this.ensureStarted().then((t=>t.getRepoBlockExcludeGlobs(e)))}handleCursorIgnoreCreated(e){return this.ensureStarted().then((t=>t.handleCursorIgnoreCreated(e)))}handleCursorIgnoreChanged(e){return this.ensureStarted().then((t=>t.handleCursorIgnoreChanged(e)))}handleCursorIgnoreDeleted(e){return this.ensureStarted().then((t=>t.handleCursorIgnoreDeleted(e)))}dispose(){this.disposeRequested||(this.disposeRequested=!0,this.ignoreServicePromise?.then((e=>{e.dispose()})).catch((()=>{})))}}const Pc=Math.min(8,Math.max(1,Math.floor(o.default.availableParallelism()/2)));class Rc{constructor(e){this.maxLookups=e,this.instances=new Map,this.lookups=0}get(e,t){this.lookups>=this.maxLookups&&this.clear(),this.lookups++;let r=this.instances.get(e);return void 0===r&&(r=oa().add(t),this.instances.set(e,r)),r}delete(e){this.instances.delete(e)}clear(){this.instances.clear(),this.lookups=0}}class Ic{constructor(e,t,r,n,o,s){this.gitExecutor=e,this.gitIgnoreMapping=t,this.cursorIgnoreMapping=r,this.teamSettingsService=n,this.rootDirectories=o,this.scanEnvironment=s,this.gitIgnoreCache=new js.q({max:2e3}),this.cursorIgnoreCache=new js.q({max:2e3}),this.gitRootCache=new js.q({max:1e4}),this.gitRemoteUrlCache=new js.q({max:200}),this.hasGitDirCache=new js.q({max:1e3}),this.gitParsedIgnoreCache=new Rc(1e4),this.cursorParsedIgnoreCache=new Rc(1e4),this.ignoreMappingsHaveEntries=!1,this.directoryWalkPlacementCache=new js.q({max:1e4}),this.extraRootCursorIgnoreCache=new js.q({max:32}),this.extraGitRepoMappingCache=new js.q({max:32}),this.unwalkedFolders=o.flatMap((e=>Hs(e,s)))}static getRipwalkCache(){return Ic.ripwalkCache??=new Sa,Ic.ripwalkCache}hasNoWorkspaceFolders(){return!this.ignoreMappingsHaveEntries&&(this.ignoreMappingsHaveEntries=Object.keys(this.gitIgnoreMapping).length>0||Object.keys(this.cursorIgnoreMapping).length>0,!this.ignoreMappingsHaveEntries)}async resolveLookupRoot(e){return await(0,Yo.DN)(e)??(0,Yo.o1)(e)}static async init(e,t,r,n,s={platform:process.platform,homeDirectory:o.default.homedir()}){const i={...s,homeDirectory:await(0,Yo.DN)(s.homeDirectory)??s.homeDirectory},a=await(0,Or.PH)(r,(async e=>{const t=await(0,Yo.DN)(e);return null===t?(console.warn(`[IgnoreService] Cannot resolve workspace root, using as-is: ${e}`),e):t})),c={},l={},u=await(0,Or.PH)(a,(async r=>({root:r,lookup:await ec(e,t,r)}))),d=u.map((({root:e,lookup:t})=>"none"===t.kind?null:"unknown"===t.kind||Hs(t.root,i).length>0?e:t.root)).filter((e=>null!==e)),h=u.filter((({lookup:e})=>"unknown"===e.kind)).map((({root:e})=>(0,Yo.o1)(e)));return d.length>0&&await Promise.all([Ic.initializeIgnoreMapping({rootDirectories:d,ignoreFileName:".gitignore",mapping:c,scanEnvironment:i,unknownRoots:h}),Ic.initializeIgnoreMapping({rootDirectories:a,ignoreFileName:".cursorignore",mapping:l,scanEnvironment:i,unknownRoots:h})]),new Ic(t,c,l,n,a,i)}static async preloadHierarchy(e,t,r,n){let o=(0,Yo.o1)(e);const i=(0,s.parse)(o).root;for(;o!==i;){if(n?.has(o)){const e=(0,s.dirname)(o);if(e===o)break;o=e;continue}void 0===r[o]&&await Ic.handleHierarchyIgnore(o,t,r),n?.add(o);const e=(0,s.dirname)(o);if(e===o)break;o=e}}static async handleHierarchyIgnore(e,t,r){const n=(0,s.join)(e,t);try{await(0,Co.access)(n,Co.default.constants.F_OK);const t=await ji(n),o=Ic.parseIgnoreRules(t);r[e]=o}catch(o){"ENOENT"===Sc(o)||console.error(`Error reading ${t} file at ${n}:`,o),r[e]=[]}}static async initializeIgnoreMapping({rootDirectories:e,ignoreFileName:t,mapping:r,scanEnvironment:n,unknownRoots:o}){try{const i=Ic.deduplicateRootDirectories(e),a=await Ic.promiseQueue.enqueueList(i,(e=>Ic.findFilesWithRipgrep({rootDirectory:e,fileName:t,scanEnvironment:n,noIgnoreVcs:o.some((t=>(0,Yo.ZU)({basePath:e,targetPath:t})))}))),c=Array.from(a.values()).flat();await Promise.all(c.map((async e=>{try{const t=await ji(e),n=Ic.parseIgnoreRules(t),o=(0,s.dirname)(e);r[o]=n}catch(r){console.error(`Error processing ${t} file at ${e}:`,r)}})));const l=new Set;for(const e of i)await Ic.preloadHierarchy(e,t,r,l)}catch(e){console.error(`Error initializing ignore mapping for ${t}:`,e)}}static async findFilesWithRipgrep({rootDirectory:e,fileName:t,scanEnvironment:r,noIgnoreVcs:n}){const o=(0,y.q6)(),i=[],a={root:e,includeGlobs:_c.map((e=>`**/${e}`)),excludeGlobs:[...lc,...uc(e,r)],noIgnoreVcs:n,source:"ignore_scan"},c=Ic.getRipwalkCache().walk(o,a);for await(const r of c.lines)(0,s.basename)(r)===t&&i.push((0,s.join)(e,r));return i}async handleManualLookupWhenNoWorkspaceDirs(e,t,r){const n={};let o=(0,s.dirname)(e);const i=(0,s.parse)(o).root;for(;;){let e=r?.get(o);if(void 0===e){try{e=Ic.parseIgnoreRules(await ji((0,s.join)(o,t)))}catch{e=[]}r?.set(o,e)}if(e.length>0&&(n[o]=e),o===i)break;o=(0,s.dirname)(o)}return this.testIgnored(e,n,((e,t)=>oa().add(t)))}async isIgnoredByAny(e){const[t,r,n]=await Promise.all([this.checkGitIgnored(e),this.checkCursorIgnored(e),this.checkRepoBlocked(e)]);return t||r||n}async isGitIgnored(e){return this.checkGitIgnored(e)}async isCursorIgnored(e,t){return this.checkCursorIgnored(e,t)}async checkGitIgnored(e){if(this.hasNoWorkspaceFolders())return this.handleManualLookupWhenNoWorkspaceDirs(e,".gitignore");const t=this.gitIgnoreCache.get(e);if(void 0!==t)return t;await this.populateHierarchyIfNeeded(e,".gitignore",this.gitIgnoreMapping);const r=this.checkIgnored(e,this.gitIgnoreMapping,this.gitParsedIgnoreCache);return this.gitIgnoreCache.set(e,r),r}async checkCursorIgnored(e,t){if(this.hasNoWorkspaceFolders())return this.handleManualLookupWhenNoWorkspaceDirs(e,".cursorignore",t);const r=this.cursorIgnoreCache.get(e);if(void 0!==r)return r;await this.populateHierarchyIfNeeded(e,".cursorignore",this.cursorIgnoreMapping);const n=this.checkIgnored(e,this.cursorIgnoreMapping,this.cursorParsedIgnoreCache);return this.cursorIgnoreCache.set(e,n),n}isInUnwalkedFolder(e){const t="darwin"===this.scanEnvironment.platform,r=t?e.toLowerCase():e;return this.unwalkedFolders.some((e=>(0,Yo.ZU)({basePath:t?e.toLowerCase():e,targetPath:r})))}directoryWalkPlacement(e){const t=this.directoryWalkPlacementCache.get(e);if(void 0!==t)return t;let r;return r=this.isInUnwalkedFolder(e)?"unwalked":this.rootDirectories.some((t=>(0,Yo.ZU)({basePath:t,targetPath:e})))?"walked":"outside",this.directoryWalkPlacementCache.set(e,r),r}async populateHierarchyIfNeeded(e,t,r){let n=(0,s.dirname)((0,Yo.o1)(e));const o=[],i=(0,s.parse)(n).root;for(;n!==i;){const e=this.directoryWalkPlacement(n),t="unwalked"===e;if("walked"===e){n=(0,s.dirname)(n);continue}if(void 0===r[n])o.push(n);else if(!t)break;const i=(0,s.dirname)(n);if(i===n)break;n=i}o.length>0&&(await Ic.promiseQueue.enqueueList(o,(e=>Ic.handleHierarchyIgnore(e,t,r))),".gitignore"===t?this.gitIgnoreCache.clear():this.cursorIgnoreCache.clear())}testIgnored(e,t,r){for(const[n,o]of Object.entries(t)){if(0===o.length)continue;if(!(0,Yo.ZU)({basePath:n,targetPath:e}))continue;const t=(0,s.relative)(n,e);if(""===t)continue;const i=r(n,o),a=(0,Yo.oL)(t),c=i.test(a);if(c.ignored&&!c.unignored)return!0;const l=i.test(`${a}/`);if(l.ignored&&!l.unignored)return!0}return!1}checkIgnored(e,t,r){return this.testIgnored(e,t,((e,t)=>r.get(e,t)))}async listCursorIgnoreFilesByRoot(e){const t=await this.resolveLookupRoot(e),r=[];for(const[e,n]of Object.entries(this.cursorIgnoreMapping)){if(0===n.length)continue;if(!(0,Yo.ZU)({basePath:t,targetPath:e}))continue;const o=(0,s.join)(e,".cursorignore");try{await(0,Co.access)(o),r.push(o)}catch{}}return r}async getCursorIgnoreMapping(){return{...this.cursorIgnoreMapping}}async getShellSandboxIgnoreMapping(e=[]){const t={...this.cursorIgnoreMapping},r=[];for(const t of e){if((0,qs.$f)(t))continue;const e=await(0,Yo.DN)(t);if(null===e||".git"===(0,s.basename)(e)||this.rootDirectories.some((t=>(0,Yo.ZU)({basePath:t,targetPath:e})))||r.includes(e))continue;const n=await Co.default.stat(e).catch((e=>{if(void 0===Sc(e))throw e}));n?.isDirectory()&&r.push(e)}const n=Date.now();for(const e of r){let r=this.extraRootCursorIgnoreCache.get(e);if(void 0===r||r.expiresAt<=n){const t={},o=void 0===this.gitExecutor.guardedRootLookup?void 0:await ec((0,y.q6)(),this.gitExecutor,e);await Ic.initializeIgnoreMapping({rootDirectories:[e],ignoreFileName:".cursorignore",mapping:t,scanEnvironment:this.scanEnvironment,unknownRoots:"unknown"===o?.kind?[e]:[]}),r={mapping:t,expiresAt:n+va()},this.extraRootCursorIgnoreCache.set(e,r)}for(const[e,n]of Object.entries(r.mapping))t[e]=Ec(t[e],n)}for(const e of[...this.rootDirectories,...r]){const r=await this.getRepoBlockExcludeGlobs(e);0!==r.length&&(t[e]=Ec(t[e],r))}return t}async getGitIgnoreMapping(){return{...this.gitIgnoreMapping}}static deduplicateRootDirectories(e){const t=[...e.map((e=>(0,Yo.o1)(e)))].sort(((e,t)=>e.length-t.length)),r=[];for(const e of t)r.some((t=>e.startsWith(`${t}/`)||e.startsWith(`${t}\\`)))||r.push(e);return r}static parseIgnoreRules(e){return e.split("\n").map((e=>e.replace(/\r$/,"").trimStart())).filter((e=>""!==e&&!e.startsWith("#")))}clearCaches(){this.gitIgnoreCache.clear(),this.cursorIgnoreCache.clear(),this.gitRootCache.clear(),this.gitRemoteUrlCache.clear(),this.hasGitDirCache.clear(),this.gitParsedIgnoreCache.clear(),this.cursorParsedIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear(),this.extraGitRepoMappingCache.clear()}dispose(){this.gitIgnoreCache=new js.q({max:1}),this.cursorIgnoreCache=new js.q({max:1}),this.gitRootCache=new js.q({max:1}),this.gitRemoteUrlCache=new js.q({max:1}),this.hasGitDirCache=new js.q({max:1}),this.directoryWalkPlacementCache=new js.q({max:1}),this.extraRootCursorIgnoreCache=new js.q({max:1}),this.extraGitRepoMappingCache=new js.q({max:1}),this.gitParsedIgnoreCache.clear(),this.cursorParsedIgnoreCache.clear(),this.gitRepoMappingPromise=void 0}async handleCursorIgnoreCreated(e){const t=(0,s.dirname)(e),r=await ji(e),n=Ic.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear()}async handleCursorIgnoreChanged(e){const t=(0,s.dirname)(e),r=await ji(e),n=Ic.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear()}handleCursorIgnoreDeleted(e){const t=(0,s.dirname)(e);this.cursorIgnoreMapping[t]=[],this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear()}async findGitRootsForFile(e){const t=(0,Yo.o1)(e),r=this.gitRootCache.get(t);if(void 0!==r)return r;const n=[],o=[],i=[];let a=t;const c=(0,s.parse)(a).root;for(;a!==c;){o.push(a),void 0===this.hasGitDirCache.get(a)&&i.push(a);const e=(0,s.dirname)(a);if(e===a)break;a=e}if(i.length>0){const e=i.map((e=>(0,Co.access)((0,s.join)(e,".git"),Co.default.constants.F_OK).then((()=>[e,!0])).catch((()=>[e,!1])))),t=await Promise.all(e);for(const[e,r]of t)this.hasGitDirCache.set(e,r)}for(const e of o)!0===this.hasGitDirCache.get(e)&&n.push(e);return this.gitRootCache.set(t,n),n}async isRepoBlocked(e){return this.checkRepoBlocked(e)}async checkRepoBlocked(e){const t=function(e){if(void 0===e)return;const t=e.repos??[],r=e.disableLocalExecAllowlistEnforcement?[]:e.allowedRepos??[];return 0===t.length&&0===r.length?void 0:{blocked:t,allowed:r}}(await(this.teamSettingsService?.getTeamRepos()));if(void 0===t)return!1;const r=await this.findGitRootsForFile(e);if(0===r.length)return 0!==t.allowed.length&&!(0,Yo.ZU)({basePath:await this.getCursorDataDir(),targetPath:e})&&function(e,t){return 0!==e.allowed.length&&!hc(e.allowed,t)}(t,this.getWorkspaceRelativePath(e));const n=[];for(const t of r)n.push({url:await this.remoteUrlOf(t),relativePath:(0,s.relative)(t,e)||"."});return function(e,t){let r=0===e.allowed.length,n=!1;for(const{url:o,relativePath:s}of t)if(void 0!==o){if(e.blocked.some((e=>pc(e,o,s))))return!0;e.allowed.length>0&&!n&&(n=!0,r=e.allowed.some((e=>pc(e,o,s))))}else 0;return!r}(t,n)}async remoteUrlOf(e){if(this.gitRemoteUrlCache.has(e))return this.gitRemoteUrlCache.get(e);const t=await sc((0,y.q6)(),this.gitExecutor,e);return void 0!==t&&this.gitRemoteUrlCache.set(e,t),t}getWorkspaceRelativePath(e){let t;for(const r of this.rootDirectories)(0,Yo.ZU)({basePath:r,targetPath:e})&&(void 0===t||r.length>t.length)&&(t=r);return void 0!==t?(0,Yo.oL)((0,s.relative)(t,e)):(0,Yo.oL)(e)}getCursorDataDir(){return this.cursorDataDirPromise??=(async()=>{const e=(0,s.join)(o.default.homedir(),".cursor");return await(0,Yo.DN)(e)??e})(),this.cursorDataDirPromise}async getRepoBlockExcludeGlobs(e){const t=await(this.teamSettingsService?.getTeamRepos());if(!t?.repos?.length)return[];const r=await this.resolveLookupRoot(e);let n;if(this.rootDirectories.some((e=>(0,Yo.ZU)({basePath:e,targetPath:r}))))n=await this.getGitRepoMapping();else{const e=this.extraGitRepoMappingCache.get(r);void 0!==e?n=e:(n=await this.initializeGitRepoMapping([r]),this.extraGitRepoMappingCache.set(r,n))}if(0===n.size)return[];const o=[];for(const[e,i]of n){if(void 0===i)continue;const n=this.normalizePathForComparison(e),a=this.normalizePathForComparison(r);let c=!1,l="";if(a.startsWith(n)?(c=!0,l=""):n.startsWith(a)&&(c=!0,l=(0,s.relative)(r,e)),!c)continue;const u=t.repos.filter((e=>fc(e.url,i)));if(0!==u.length)for(const e of u)for(const t of e.patterns||[]){const e=t.pattern.trim();if(!e)continue;let r;r=l?(0,s.join)(l,e).replace(/\\/g,"/"):e,o.push(r),r.endsWith("/**")||o.push(`${r}/**`)}}return o}normalizePathForComparison(e){let t=e.replace(/\\/g,"/");return t.startsWith("/")&&t.length>2&&":"===t[2]&&(t=t.substring(1)),"win32"===process.platform&&(t=t.toLowerCase()),t}getGitRepoMapping(){return this.gitRepoMappingPromise||(this.gitRepoMappingPromise=this.initializeGitRepoMapping()),this.gitRepoMappingPromise}async initializeGitRepoMapping(e=this.rootDirectories){const t=new Map,r=[],n=["**/node_modules/**","**/.turbo/**","**/.next/**","**/.cache/**","**/.pnpm/**","**/.yarn/**","**/dist/**","**/build/**","**/out/**","**/target/**","**/.vscode/**","**/.idea/**","**/venv/**","**/__pycache__/**","**/logs/**","**/tmp/**","**/temp/**"],o=(0,y.q6)();for(const t of e){const e=(0,Yo.o1)(t);try{await(0,Co.access)((0,s.join)(e,".git"),Co.default.constants.F_OK),r.includes(e)||r.push(e)}catch{}let i=(0,s.dirname)(e);const a=(0,s.parse)(i).root;for(;i!==a&&""!==i;){try{await(0,Co.access)((0,s.join)(i,".git"),Co.default.constants.F_OK),r.includes(i)||r.push(i)}catch{}const e=(0,s.dirname)(i);if(e===i)break;i=e}try{const t={root:e,includeGlobs:["**/.git/config"],excludeGlobs:[...n,...uc(e,this.scanEnvironment)],noIgnoreVcs:!0,source:"ignore_scan"},i=Ic.getRipwalkCache().walk(o,t);for await(const t of i.lines){const n=(0,s.join)(e,t),o=(0,s.dirname)(n),i=(0,s.dirname)(o);r.includes(i)||r.push(i)}}catch{}}return await Promise.all(r.map((async e=>{try{const r=await sc(o,this.gitExecutor,e);t.set(e,r)}catch{t.set(e,void 0)}}))),t}}async function Tc(e,t){let r=e;if($s()&&(r=Ls(t.command,t.parsingResult)),!r||"insecure_none"===r.type)return r;const n="workspace_readwrite"===r.type&&t.permissionsService.resolveLinkedWorktreeSandboxGrants?await t.permissionsService.resolveLinkedWorktreeSandboxGrants(r,{command:t.command,workingDirectory:t.workingDirectory}):void 0,o=function(e,t){if(!e)return t;const r={...e};for(const[e,n]of Object.entries(t))r[e]=Ec(r[e],n);return r}(r.ignoreMapping,await async function(e,t){return e.getShellSandboxIgnoreMapping?e.getShellSandboxIgnoreMapping(t):e.getCursorIgnoreMapping()}(t.ignoreService,n?.roots));if("workspace_readwrite"===r.type&&void 0!==n){const e=(0,Oo.s9)(r.additionalReadwritePaths,[...n.roots,...n.commonDirs]);return{...r,additionalReadwritePaths:e.length>0?e:void 0,ignoreMapping:o}}return{...r,ignoreMapping:o}}Ic.promiseQueue=new Or.TJ({max:Pc});var Ac=r("../proto/dist/generated/agent/v1/mcp_exec_pb.js");const $c="agent-tools",Mc=51380224;var Dc=r("../proto/dist/generated/agent/v1/utils_pb.js");const Oc=/^v?(\d{1,9})\.(\d{1,9})(?:\.\d{1,9})?(?:[-+][0-9A-Za-z.+-]*)?$/,Fc=["unknown","other","older","3.24","3.25","3.26","3.27","3.28","3.29","3.30","3.31","3.32","3.33","3.34","3.35","3.36","3.37","3.38","3.39","3.40","newer"].flatMap((e=>{const t=/^(\d+)\.(\d+)$/.exec(e);return null===t?[]:[{major:Number(t[1]),minor:Number(t[2]),bucket:e}]})),Nc=Fc[0].major,Lc=Fc[0].minor;function jc(e){if(null==e)return"unknown";const t=e.trim();if(0===t.length||t.length>128)return"unknown";const r=Oc.exec(t);if(null===r)return"unknown";const n=Number(r[1]),o=Number(r[2]);if(n!==Nc)return"other";const s=Fc.find((e=>e.minor===o));return void 0!==s?s.bucket:o=128&&t<=191?t:Vc.get(e)}function rl(e,t){const r=e.charCodeAt(t),n=function(e){return e>=194&&e<=222?201===e?0:2:e>=224&&e<=239?3:240===e?4:0}(r);if(0===n||t+n>e.length)return;const o=new Uint8Array(n);o[0]=r;for(let r=1;r0&&Jc.test(e[t-1]))return}else{if(Zc.has(s))return;if(!0===Qc.get(r)?.has(s))return;if(3===n&&Yc.has(s)&&Zc.has(e[t+2]))return}let i;try{i=Gc.decode(o)}catch{return}return el.test(i)?void 0:{index:t,text:e.slice(t,t+n),repaired:i}}function nl(e,t=Number.POSITIVE_INFINITY){const r=[];let n=0;for(;n240){n++;continue}const o=rl(e,n);void 0!==o?(r.push(o),n+=o.text.length):n++}return r}const ol=`[\\u00c2-\\u00f0][\\u0080-\\u00bf${[...Vc.keys()].join("")}]`,sl=new RegExp(ol),il=/\p{L}/u;function al(e,t){const r=e.charCodeAt(t);let n;if(r>=194&&r<=223)n=2;else if(r>=224&&r<=239)n=3;else{if(!(r>=240&&r<=244))return 0;n=4}if(t+n>e.length)return 0;for(let r=1;r=128&&n<=191)&&(n<128||!Vc.has(e[t+r])))return 0}return n}function cl(e,t){if(t.text.length>2)return!0;const r=t.text.charCodeAt(1);if(r>=128&&r<=159)return!0;if(0===t.index||!Jc.test(e[t.index-1]))return!0;const n=t.index+t.text.length;return n0)return"damaged";const n=yl(r);return"utf8"!==n&&"utf8_bom"!==n?"other_encoding":"intact"}function pl(e,t){return e<=t?"existing_only":"new_damage"}function fl(e,t){const r=new Set(t.map((e=>e.text))),n=e.filter((e=>!r.has(e.text))),o=n.length>0?n:e;if(function(e){let t="",r=-1;for(const n of e){if(n.index!==r){if(nl(t,1).length>0)return!0;t=""}t+=n.repaired,r=n.index+n.text.length}return nl(t,1).length>0}(o))return"double";if(1!==new Set(o.map((e=>e.text.length))).size)return"mixed";switch(o[0].text.length){case 2:return"two_byte";case 3:return"three_byte";default:return"four_byte"}}function ml(e){return{detector:e,outcome:"clean",afterCount:0,beforeCount:0}}function gl(e,t,r){const n=nl(r,1e3);if(0===n.length)return ml("mojibake");const o=void 0===e?[]:nl(e,Math.max(n.length,6));return{detector:"mojibake",outcome:pl(n.length,o.length),file:hl(e,o.length,t),afterCount:n.length,beforeCount:o.length,pattern:fl(n,o)}}function wl(e,t,r){const n=li(r);if(0===n)return ml("replacement_chars");const o=void 0===e?0:li(e);return{detector:"replacement_chars",outcome:pl(n,o),file:hl(e,o,t),afterCount:n,beforeCount:o}}function yl(e){if(void 0===e)return"none";const t=e.toLowerCase().replace(/[^a-z0-9]/g,"");return"utf8"===t||"ascii"===t?"utf8":"utf8bom"===t?"utf8_bom":t.startsWith("utf16")?"utf16":"latin1"===t||"iso88591"===t?"latin1":"windows1252"===t||"cp1252"===t?"windows_1252":"gbk"===t||"gb2312"===t||"gb18030"===t||"cp936"===t?"gbk":"shiftjis"===t||"sjis"===t||"cp932"===t||"windows31j"===t?"shift_jis":"euckr"===t||"cp949"===t?"euc_kr":"big5"===t||"big5hkscs"===t||"cp950"===t?"big5":"other"}const vl=new Map([["md",["md","mdx","markdown"]],["txt",["txt","text","log","rst","adoc","asciidoc","tex"]],["js_ts",["js","jsx","mjs","cjs","ts","tsx","mts","cts"]],["web",["html","htm","xhtml","css","scss","sass","less","vue","svelte","astro"]],["py",["py","pyi","pyw","ipynb"]],["jvm",["java","kt","kts","scala","groovy","gradle"]],["dotnet",["cs","csx","vb","fs","fsx","razor","cshtml","xaml"]],["c_cpp",["c","h","cc","cpp","cxx","c++","hpp","hh","hxx","h++","m","mm"]],["other_code",["go","rs","rb","erb","php","swift","dart","lua","pl","pm","r","ex","exs","erl","hs","clj","cljs","zig","nim","jl","sol","elm","ml","mli","pas","bas"]],["shell",["sh","bash","zsh","fish","ps1","psm1","psd1","bat","cmd"]],["sql",["sql","psql","ddl","dml"]],["config",["json","jsonc","json5","yaml","yml","toml","ini","cfg","conf","env","properties","editorconfig"]],["xml",["xml","xsl","xslt","xsd","svg","csproj","vbproj","fsproj","props","targets","nuspec","plist","storyboard","xib"]],["i18n",["po","pot","strings","stringsdict","arb","xlf","xliff","ftl","resx"]],["csv",["csv","tsv"]]].flatMap((([e,t])=>t.map((t=>[t,e])))));function bl(e){const t=(0,s.extname)(e).slice(1).toLowerCase();return""===t?"none":vl.get(t)??"other"}const Sl=new Map([[1252,"1252"],[1250,"1250"],[1251,"1251"],[874,"874"],[932,"932"],[936,"936"],[949,"949"],[950,"950"],[65001,"65001"]]);function kl(e){if("string"==typeof e)return e;const t=void 0===e.acp?void 0:Sl.get(e.acp);return void 0===t?"other":e.oemcp===e.acp?t:`${t}_split`}function _l(e,t){if("clean"===e.outcome)return{detector:e.detector,outcome:"clean",file:"unclassified"};const r={outcome:e.outcome,file:e.file,ext:bl(t.path),encoding:yl(t.encoding),code_page:kl(t.pages),run_count:ul(e.afterCount),delta:(n=e.afterCount-e.beforeCount,n<0?"neg":dl(n)),before_count:dl(e.beforeCount)};var n;return"mojibake"===e.detector?{detector:"mojibake",pattern:e.pattern,...r}:{detector:"replacement_chars",...r}}class Cl{constructor(){this.counts={stdout:0,stderr:0},this.produced={stdout:!1,stderr:!1}}note(e,t){if(0===t.length)return;this.produced[e]=!0;const r=this.counts[e];r>=6||(this.counts[e]=r+li(t,6-r))}labels(e,t){const r=kl(t),n=[];for(const t of["stdout","stderr"]){if(!this.produced[t])continue;const o=this.counts[t];n.push({detector:"replacement_chars",outcome:o>0?"damaged":"clean",run_count:dl(o),branch:e[t],stream:t,code_page:r})}return n}}const El=/[\ud800-\udbff](?![\udc00-\udfff])|(?=e.length||e.startsWith(Al,r))&&e.startsWith(Al,r+Fl(e,r)))return!0}return!1}(e)}(e,o))return"utf16";if(r)return"clean";if(!Tl.test(e))return"clean";const s=function(e){if(!sl.test(e))return;let t=0,r=!1,n=!0,o=0;for(;o=194&&s<=240?rl(e,o):void 0;if(void 0!==i){if(t++,r=cl(e,i),o+=i.text.length,!n||!r&&t>=256)return"medium";continue}const a=n?al(e,o):0;if(0===a){if(n=!1,t>0)return"medium";o++}else o+=a}return 0!==t?r&&n?"high":"medium":void 0}(e);return void 0!==s?"high"===s?"mojibake_high":"mojibake_medium":Il.test(e)?"c1":"clean"}const Ll=(0,l.h)("local-exec:encoding-slices");function jl(e,t){if(void 0===e)return!1;try{return"function"==typeof e?e(t):e}catch{return!1}}function Ul(e,t){return jl(e?.enabled,t)}function Bl(e,t,r=!1){if("clean"===e)return"clean";switch(t){case"utf8_valid":return"lone_surrogate"===e?"new_damage_cut":"existing_only";case"utf8_invalid":return"lone_surrogate"===e?"new_damage_cut":"replacement"!==e?"existing_only":r?"unknown":"not_text";case"utf8_cut":return"lone_surrogate"===e?"new_damage_cut":"replacement"!==e?"existing_only":r?"unknown":"new_damage_cut";case"utf8_as_other":return"new_damage_decode";case"declared_other":return"replacement"!==e||r?"unknown":"new_damage_decode";case"other_encoding":case"unseen":return"unknown";default:return t}}function Wl(e){for(let t=1;t<=Math.min(3,e.length);t++){const r=e[e.length-t]??0;if(128!=(192&r))return(r>=240?4:r>=224?3:r>=192?2:1)>t?t:0}return 0}class Hl{constructor(){this.seen=!1,this.invalid=!1,this.carry=new Uint8Array(0)}write(e){if(0===e.length)return;if(this.seen=!0,this.invalid)return;const t=this.carry.length>0?Buffer.concat([this.carry,e]):e,r=Wl(t);if(!(0,n.isUtf8)(t.subarray(0,t.length-r)))return this.invalid=!0,void(this.carry=new Uint8Array(0));this.carry=r>0?Uint8Array.from(t.subarray(t.length-r)):t.subarray(0,0)}evidence(){return this.seen?this.invalid?"utf8_invalid":this.carry.length>0?"utf8_cut":"utf8_valid":"unseen"}}const ql=new Map(Object.entries({zsh:"zsh",zsh_light:"zsh_light",bash:"bash",pwsh:"pwsh",powershell51:"powershell51",naive_pwsh:"naive_pwsh",naive_powershell51:"naive_powershell51",naive_bash:"naive_bash",naive_zsh:"naive_zsh",naive_other:"naive_other"})),zl=(0,u.Pu)("local_exec.encoding_slice",{description:"Results a local executor returned, and results about to be encoded for the wire, by the boundary they were counted at, the kind of encoding damage their text holds (one kind per result, clean included), whose the damage is as far as the bytes at that boundary say, which executor the result came from, the client's version bucket, for a shell result counted on Windows how the code page lookup stood, and for a shell result which shell ran the command",labelNames:["layer","kind","origin","source","version_bucket","code_page_lookup","shell_kind"]}),Gl=Pl[0],Vl=new Map(Pl.map(((e,t)=>[e,t])));function Kl(e){return Vl.get(e)??Pl.length}class Jl{constructor(){this.worst="clean",this.remaining=262144}note(e){this.walk(e,0)}kind(){return this.worst}capped(){return this.remaining<=0}settled(){return this.remaining<=0||this.worst===Gl}noteText(e){if(0===e.length)return;const t=e.length>this.remaining?Vo(e,this.remaining):e;this.remaining-=Math.max(t.length,1);const r=Nl(t);Kl(r)=16)return;if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer)return;if(Array.isArray(e)){for(const r of e)if(this.walk(r,t+1),this.settled())return;return}const r=Object.values(e);for(const e of r)if(this.walk(e,t+1),this.settled())return}}class Zl{constructor(e=1024){this.capacity=e,this.counted=new Set}firstRead(e,t){if(""===e)return!0;const r=`${e}\n${t}`,n=this.counted.delete(r);if(this.counted.add(r),this.counted.size>this.capacity)for(const e of this.counted){this.counted.delete(e);break}return!n}}function Xl(e,t,r,n){const o={layer:r.layer,kind:n,origin:Bl(n,r.evidence??"unseen",!0===r.partial),source:r.source??r.layer,version_bucket:jc(e.clientVersion)};void 0!==r.codePageLookup&&(o.code_page_lookup=r.codePageLookup),void 0!==r.shellKind&&(o.shell_kind=r.shellKind),zl.increment(t,1,o)}function Ql(e,t){Ll.warn(e,"encoding slice was not counted (result unaffected)",{error:t instanceof Error?t.name:"unknown"})}function Yl(e,t,r,n){if(void 0!==e&&Ul(e,t))try{const o=new Jl;o.note(n),Xl(e,t,r,o.kind())}catch(e){Ql(t,e)}}function eu(e,t,r,n){if(void 0!==e&&Ul(e,t))try{Xl(e,t,r,n)}catch(e){Ql(t,e)}}class tu{constructor(){this.seen=!1,this.invalid=!1}note(e){this.seen=!0,this.invalid||(0,n.isUtf8)(e)||(this.invalid=!0)}evidence(){return this.seen?this.invalid?"utf8_invalid":"utf8_valid":"unseen"}}function ru(e,t,r,n){return void 0===t?e:{execute:async(o,s,i)=>{const a=await e.execute(o,s,i);if(Ul(t,o))try{n(a)&&Yl(t,o,{layer:r},a)}catch(e){Ql(o,e)}return a}}}new Map([["readArgs","exec_read"],["redactedReadArgs","exec_read"],["grepArgs","exec_grep"],["mcpArgs","exec_mcp"],["readMcpResourceExecArgs","exec_mcp"],["executeHookArgs","exec_hooks"],["fetchArgs","exec_web_fetch"],["shellArgs","exec_shell"],["shellStreamArgs","exec_shell"],["backgroundShellSpawnArgs","exec_shell"],["miniSweAgentBashArgs","exec_shell"],["writeArgs","exec_write"]]);class nu{constructor(){this.text={stdout:new Jl,stderr:new Jl},this.bytes={stdout:new Hl,stderr:new Hl},this.produced={stdout:!1,stderr:!1},this.dropped={stdout:!1,stderr:!1},this.shellKind="unknown"}noteBytes(e,t){this.bytes[e].write(t)}noteText(e,t){0!==t.length&&(this.produced[e]=!0,this.text[e].note(t))}noteDropped(e){this.dropped[e]=!0}noteShell(e){this.shellKind=function(e){return"string"!=typeof e?"unknown":ql.get(e)??"unknown"}(e)}record(e,t,r,n){for(const o of["stdout","stderr"])this.produced[o]&&eu(e,t,{layer:"exec_shell",evidence:this.evidence(o,r[o]),partial:this.dropped[o]||this.text[o].capped(),codePageLookup:n,shellKind:this.shellKind},this.text[o].kind())}evidence(e,t){if("utf8"!==t)return"other_encoding";const r=this.bytes[e].evidence();return"utf8_cut"===r?"utf8_invalid":r}}var ou=r("node:child_process"),su=r("../utils/dist/workload-spawn.js");const iu=(0,l.h)("local-exec:shell-output-encoding"),au=(0,zs.promisify)(ou.execFile),cu=/^\s*OEMCP\s+REG_\w+\s+(\d+)\s*$/m,lu=/^\s*ACP\s+REG_\w+\s+(\d+)\s*$/m;function uu(e,t){const r=t.exec(e);return null===r?void 0:Number(r[1])}const du="㐀-䶿一-鿿豈-﫿",hu=" -〿㈀-㏿︰-﹯＀-￯",pu="‐-※←-⇿─-◿★☆",fu="぀-ヿ",mu=new Map([["cp932",{script:new RegExp(`[${du}${hu}${pu}${fu}]`),doubleByte:!0}],["cp936",{script:new RegExp(`[${du}${hu}${pu}${fu}㄀-ㄯ]`),doubleByte:!0}],["cp949",{script:new RegExp(`[${du}${hu}${pu}${fu}㄰-㆏가-힯]`),doubleByte:!0}],["cp950",{script:new RegExp(`[${du}${hu}${pu}㄀-ㄯ]`),doubleByte:!0}],["cp874",{script:new RegExp("[฀-๿]"),doubleByte:!1}]]);const gu=function(e){let t,r,n,o,s=!1,i=0;const a=()=>{i+=1;const e=i;n=async function(){const{stdout:e}=await(0,su.D9)(au,"\\\\.\\GLOBALROOT\\SystemRoot\\System32\\reg.exe",["query","HKLM\\SYSTEM\\CurrentControlSet\\Control\\Nls\\CodePage"],{encoding:"buffer",timeout:3e3,windowsHide:!0});return e}().then((e=>{const i=function(e){const t=Buffer.isBuffer(e)?function(e){return e.length>=2&&255===e[0]&&254===e[1]?e.subarray(2).toString("utf16le"):e.includes(0)?e.toString("utf16le"):e.toString("latin1")}(e):e,r={},n=uu(t,cu),o=uu(t,lu);return void 0!==n&&(r.oemcp=n),void 0!==o&&(r.acp=o),r}(e);t=function(e){const{oemcp:t,acp:r}=e;if(void 0===t||void 0===r||t!==r)return;const n=function(e){if(65001===e)return;const t=`cp${e}`;return Vs.encodingExists(t)?t:void 0}(t);return void 0!==n&&mu.has(n)?n:void 0}(i),r=i,s=!0,n=void 0,o=void 0===i.oemcp&&void 0===i.acp?"unparsed":"answered",iu.info((0,y.q6)(),"Resolved the fallback encoding for shell output",{encoding:t??"none",oemcp:i.oemcp??"none",acp:i.acp??"none"})}),(t=>{n=void 0,o=function(e){try{if("object"!=typeof e||null===e)return"spawn_error";const t="code"in e?e.code:void 0;return"killed"in e&&!0===e.killed&&"string"!=typeof t?"timeout":"number"==typeof t?"nonzero_exit":"spawn_error"}catch{return"spawn_error"}}(t),iu.warn((0,y.q6)(),"Could not read the Windows code pages; shell output stays UTF-8 only",{error:t instanceof Error?t.message:String(t),attempt:e})}))};return"win32"===e&&a(),{current:()=>("win32"===e&&!s&&void 0===n&&i<3&&a(),t),pages:()=>void 0!==r?r:"win32"!==e?"none":i>=3&&void 0===n?"failed":"pending",lastOutcome:()=>"win32"===e?o??"pending":void 0,settled:()=>n??Promise.resolve()}}(process.platform),wu=Buffer.alloc(0),yu=/[\u0080-\uffff]/;function vu(e){const t=Math.max(0,e.length-3);for(let r=e.length-1;r>=t;r--){const t=e[r];if(128==(192&t))continue;const n=t>=248?1:t>=240?4:t>=224?3:t>=192?2:1,o=e.length-r;return n>o?o:0}return 0}function bu(){const e=new ia.StringDecoder("utf8");return{write:t=>e.write(t),end:()=>e.end()}}function Su(e,t){return Vs.decode(t,e,{stripBOM:!1})}const ku=/[\xe0-\xef][\x80-\xbf]\?/;const _u=10,Cu=Buffer.alloc(0),Eu=new Set([7,8,9,10,11,12,13,27]);function xu(e,t,r){for(let n=0;n+1(r=void 0,t.end())}}const Iu={encoding:"utf8",skip:0};function Tu(e){const t=e();let r="utf8";const n={};let o=!1;const s=()=>"utf8"===r?t:n[r]??=Ru(r),i=e=>("utf8"!==r&&e.length>0&&(o=!0),e);let a,c=!0,l=Cu,u=!1,d=0;const h=(e,t)=>{const n=function(e){if(!(e.length<2))return 255===e[0]&&254===e[1]?"utf16le":254===e[0]&&255===e[1]?"utf16be":void 0}(e);if(void 0!==n)return{encoding:n,skip:2};if("utf8"===r){if(e.length<2)return t?Iu:void 0;const r=0===e[0]?"utf16be":0===e[1]?"utf16le":void 0;if(void 0===r)return Iu;const n=Pu(e,r);if(-1!==n)return xu(e,r,n)?{encoding:r,skip:0}:Iu;if(!t)return;const o=e.length-e.length%2;return function(e,t){const r="utf16le"===t?1:0;for(let t=0;te.length?t?o:void 0:xu(e,r,n)?o:Iu}if(-1===i)return t?Iu:void 0;if("utf16le"===r&&i%2==0){if(i+1>=e.length)return t?Iu:void 0;if(0===e[i+1])return o}return Iu},p=e=>{if(e===r)return"";const t=i(s().end());return r=e,t},f=e=>"utf8"===r&&0!==e&&e<128,m=(e,n)=>{let o="",m=e;for(;;){if(c){const e=Math.min(m.length,512-l.length);let r;if(r=l.length>0?Buffer.concat([l,m.subarray(0,e)]):e===m.length?m:m.subarray(0,e),0===r.length)return o;const s=h(r,n||r.length>=512);if(void 0===s)return 1===r.length&&f(r[0])&&(o+=t.write(r),u=!0),l=Buffer.from(r),o;let i=s.skip,g=!1;if(u&&(i="utf8"===s.encoding?1:2,g=r[0]===_u,u=!1),0===l.length)i>0&&(m=m.subarray(i));else{const t=r.subarray(i);m=m.subarray(e),m=0===m.length?t:0===t.length?m:Buffer.concat([t,m]),l=Cu}if(c=g,d=0,a=void 0,o+=p(s.encoding),g)continue}if(0===m.length)return o;if("utf8"===r&&!m.includes(0)&&!m.includes(254)&&!m.includes(255)){const e=m.lastIndexOf(_u),r=-1===e?-1:m.length-e-1;if(-1===r||r>=2)return o+t.write(m);if(c=!0,0===r)return e>0&&m[e-1]===_u&&(l=Buffer.of(_u),u=!0),o+t.write(m);const n=m[m.length-1];return l=Buffer.of(n),u=f(n),o+t.write(u?m:m.subarray(0,e+1))}const e=Pu(m,r,d,a);if(-1===e)return d+=m.length,a=m[m.length-1],o+i(s().write(m));o+=i(s().write(m.subarray(0,e))),m=m.subarray(e),c=!0}};return{write:e=>0===e.length?s().write(e):m(e,!1),peek(){if(!c||0===l.length)return"";const t=h(l,!0);if(void 0===t)return"";const r=u?"utf8"===t.encoding?1:2:t.skip,n=l.subarray(r);return 0===n.length?"":"utf8"===t.encoding?e().write(n):Ru(t.encoding).write(n)},end(){const e=m(Cu,!0)+i(s().end());return c=!0,l=Cu,u=!1,d=0,a=void 0,e},branch:()=>!0===t.usedCodePage?.()?"code_page":o?"utf16":"utf8"}}var Au=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},$u=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Mu=(0,l.h)("local-exec:shell-core"),Du=(0,u.Pu)("local_exec.shell.encoding_check",{description:"Shell command output streams that produced text, per encoding detector (U+FFFD): whether the decoded text holds the pattern and how much, which decode path (UTF-8, Windows code page, UTF-16) produced it, which stream, and the machine's Windows code page",labelNames:["detector","outcome","run_count","branch","stream","code_page"]}),Ou="win32"===process.platform,Fu=["CURSOR_CONVERSATION_ID","CURSOR_REQUEST_ID","CURSOR_AGENT_STORE_FILES_DIR","CURSOR_AGENT_STORE_SHARED_PATHS"];function Nu(e){return`'${e.replace(/'/g,"'\\''")}'`}async function Lu(e){try{return(await(0,Co.stat)(e)).isDirectory()}catch(e){const t=Sc(e);if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}const ju=["eval-cursorbench","cursorbench","sand-eval","eval-harness"];function Uu(e){return ju.some((t=>e.includes(t)))?(0,bo.createHash)("sha256").update(e).digest("hex"):e}function Bu(e,t){return e[t]??process.env[t]}const Wu=/^[A-Za-z_][A-Za-z0-9_]*$/,Hu=/CURSOR_SANDBOX/i;function qu(e){return Wu.test(e)&&!Hu.test(e)}function zu(e){return"function"==typeof e?e():e}function Gu(e,t){const r=void 0===e?[]:[...e];return r.includes(t)||r.push(t),r}function Vu(e){let t=0,r=0;const n=e.length;for(;r"insecure_none"===e?.type?void 0:e?.privateTmp)).find((e=>void 0!==e));if("linux"!==process.platform||!0!==n||void 0===r||!(0,Yo.ZU)({basePath:"/tmp",targetPath:e}))return!1;const o=(0,Oo.W1)(r);return void 0!==o&&await Lu(s.default.join(o,"tmp",s.default.relative("/tmp",e)))}(c,t.sandboxPolicy,this.workspacePath))){if(c!==(0,Yo.o1)(await i.getCwd(),this.workspacePath))throw new Ku(c);return yield{type:"stderr",data:`The shell's working directory no longer exists: ${c}. The command did not run. Re-run it with working_directory set to an existing directory.\n`},void(yield{type:"exit",code:1,aborted:!1,localExecutionTimeMs:Math.round(performance.now()-o)})}let l,u,d=0,h=0,p=!1,f=!1,m=!1;t.fileOutputThresholdBytes&&this.projectDir&&(l={buffer:"",lineCount:0,size:0,threshold:Number(t.fileOutputThresholdBytes)});const g=t.signal,w={CURSOR_AGENT:"1"};t.conversationId&&(w.CURSOR_CONVERSATION_ID=(0,So.sh)(t.conversationId)),t.requestId&&(w.CURSOR_REQUEST_ID=t.requestId),this.projectDir&&(w.AGENT_TRANSCRIPTS=s.default.join(this.projectDir,So.O2));const y=this.options.extraEnvProvider?.(e,t);void 0!==y&&Object.assign(w,y);const v=t.requestScopedEnv??{};for(const[e,t]of Object.entries(v))void 0!==t&&qu(e)&&(w[e]=t);const b=w.CURSOR_REQUEST_ID;void 0!==b&&(w.CURSOR_REQUEST_ID=Uu(b)),function(e,t){const r=Fu,n=Object.keys(t).filter((e=>qu(e)&&!r.includes(e))),o=`builtin unset ${[...Fu,...n].join(" ")} 2>/dev/null || true`,s=[];for(const t of Fu){const r=Bu(e,t);void 0!==r&&s.push(`builtin export ${t}=${Nu(r)}`)}for(const e of n){const r=t[e];void 0!==r&&s.push(`builtin export ${e}=${Nu(r)}`)}const i=e.__CURSOR_SANDBOX_ENV_RESTORE?.trim(),a=process.env.__CURSOR_SANDBOX_ENV_RESTORE?.trim();e.__CURSOR_SANDBOX_ENV_RESTORE=[o,a,i,...s].filter((e=>void 0!==e&&""!==e)).join("; ")}(w,v),void 0!==w.__CURSOR_SANDBOX_ENV_RESTORE&&(w.__CURSOR_SANDBOX_ENV_RESTORE=function(e,t){let r=e;for(const e of t){if(null==e||0===e.length)continue;const t=Uu(e);t!==e&&(r=r.split(e).join(t))}return r}(w.__CURSOR_SANDBOX_ENV_RESTORE,[t.requestId,b,v.CURSOR_REQUEST_ID,process.env.CURSOR_REQUEST_ID]));const S=function(e,t){const r=Bu(t,"CURSOR_AGENT_STORE_FILES_DIR"),n=function(e){if(void 0===e)return[];try{const t=JSON.parse(e);if("object"!=typeof t||null===t)return[];const r=[];for(const e of Object.values(t))"object"==typeof e&&null!==e&&"path"in e&&"readOnly"in e&&"string"==typeof e.path&&"boolean"==typeof e.readOnly&&r.push({path:e.path,readOnly:e.readOnly});return r}catch{return[]}}(Bu(t,"CURSOR_AGENT_STORE_SHARED_PATHS"));if(void 0===r&&0===n.length)return e;const o=e?.perUser,s=e?.perRepo??e?.perUser??e?.teamAdmin;if("workspace_readwrite"!==s?.type&&"workspace_readonly"!==s?.type)return e;const i=o?.type===s.type?{...o}:{type:s.type};var a;void 0!==r&&(a=r,"workspace_readwrite"!==i.type?i.additionalReadonlyPaths=Gu(i.additionalReadonlyPaths,a):i.additionalReadwritePaths=Gu(i.additionalReadwritePaths,a));for(const e of n)e.readOnly||"workspace_readwrite"!==i.type?i.additionalReadonlyPaths=Gu(i.additionalReadonlyPaths,e.path):i.additionalReadwritePaths=Gu(i.additionalReadwritePaths,e.path);return{...e,perUser:i}}(t.sandboxPolicy,w),k=(0,Oo.CG)(S??Oo.BM);let _,C,E,x;S&&(yield{type:"start",sandboxed:"workspace_readonly"===k||"workspace_readwrite"===k}),t.askpassConfig&&!Ou&&(w.SUDO_ASKPASS=t.askpassConfig.helperPath,w.CURSOR_ASKPASS_SOCKET=t.askpassConfig.socketPath,w.CURSOR_ASKPASS_SECRET=t.askpassConfig.secret);const P=this.options.codePageLookup??gu,R=(this.options.outputFallbackEncoding??(()=>P.current()))(),I=()=>function(e){if(void 0===e)return bu();const t=mu.get(e);return void 0!==t&&Vs.encodingExists(e)?function(e,t){const{script:r}=t,o=function(e){const{script:t}=e,r=new RegExp(`${t.source}{2}`);let n=!1,o=!1,s=!1;return{note(i,a){if(!s&&0!==i.length){if(!n){const e=yu.exec(i);null!==e&&(n=!0,s=t.test(e[0]))}s||=o&&t.test(i[0])||r.test(i)||e.doubleByte&&void 0!==a&&ku.test(a.toString("latin1")),o=t.test(i[i.length-1])}},isUtf8Text:()=>s,reset(){n=!1,o=!1,s=!1}}}(t);let s=wu,i=0,a="utf8",c=!1;const l=()=>{a="utf8",o.reset(),i=0},u=(t,n)=>{const s=n?vu(t):0,l=t.subarray(0,t.length-s),u=l.toString("utf8");if("replacement"!==a){const t=l.subarray(i);if(i=0,o.note(t.toString("utf8"),t),o.isUtf8Text())a="replacement";else{const t=0===u.length?"":u[u.length-1],o=n&&r.test(t)?Buffer.byteLength(t):0,d=function(e,t,r){let n=Su(e,t);if(!r)return{text:n,keep:0};const o=Math.min(3,t.length);let s=0;for(;s0&&(c=!0),{text:d.text,keep:i+s}}}return{text:u,keep:s}};return{write:e=>{const t=0===s.length?e:Buffer.concat([s,e]);if(s=wu,"utf8"===a){const e=t.subarray(0,t.length-vu(t));if((0,n.isUtf8)(e)){e.length{const t=e.lastIndexOf("\n");-1===t?o.note(e):(l(),o.note(e.slice(t+1)))})(r),r}}let r="",i=0;for(;i0&&(s=Buffer.from(d.subarray(u.length))),-1===e?o.note(n):l(),i=c;continue}a="undecided"}const{text:h,keep:p}=u(d,-1===e);r+=h,p>0&&(s=Buffer.from(d.subarray(d.length-p))),-1!==e&&l(),i=c}return r},end:()=>{const e=s;s=wu;const t=0===e.length?"":"utf8"===a?e.toString("utf8"):u(e,!1).text;return l(),t},usedCodePage:()=>c}}(e,t):bu()}(R),T={stdout:Tu(I),stderr:Tu(I)},A=new Cl,M=Ul(this.options.encodingSlices,e)?new nu:void 0,D=void 0===M?void 0:function(e,t,r){return n=>{try{const o=function(e,t,r){if(!(Object.hasOwn(Bc,e.shell)&&Object.hasOwn(Wc,e.parse)&&Object.hasOwn(Hc,e.stateFile)&&Object.hasOwn(qc,e.exit)))return;let n="withheld";if(r){if("function"!=typeof e.callsExit)return;n=!0===e.callsExit()?"yes":"no"}return{shell_kind:e.shell,parse:e.parse,calls_exit:n,state_file:e.stateFile,exit:e.exit,version_bucket:jc(t)}}(n,t,r);if(void 0===o)return;zc.increment(e,1,{...o})}catch(t){Uc.warn(e,"PowerShell run was not counted (command unaffected)",{error:t instanceof Error?t.name:"unknown"})}}}(e,this.options.encodingSlices?.clientVersion,function(e,t){return!0===jl(e?.commandTextReadable,t)}(this.options.encodingSlices,e));let O=!1;const F=()=>{if(!O){O=!0;try{const t={stdout:T.stdout.branch(),stderr:T.stderr.branch()};for(const r of A.labels(t,P.pages()))Du.increment(e,1,r);M?.record(this.options.encodingSlices,e,t,P.lastOutcome())}catch(t){Mu.warn(e,"shell output encoding check failed (command result unaffected)",{error:t instanceof Error?t.message:String(t)})}}},N=e=>{void 0!==l&&0!==e.length&&(l.file?l.file.write(e):l.buffer+=e)},L=function*(){const e={stdout:p,stderr:f};for(const t of["stdout","stderr"]){const r=T[t].end();if(0===r.length)continue;const n=void 0!==l&&!0!==l.truncated;n&&N(r),!n&&e[t]||(A.note(t,r),M?.noteText(t,r)),e[t]||(yield{type:t,data:r})}F()};try{for await(const r of i.execute(e,t.command,{signal:g,workingDirectory:c,env:w,sandboxPolicy:S,sandboxWorkspaceRoot:this.workspacePath,pipeStdin:t.pipeStdin??!1,keepBackgroundJobs:this.options.keepBackgroundJobs??!1,bufferOutputEvents:this.options.shellOutputBackpressureOptions?.bufferOutputEvents,outputLimiterOptions:this.options.shellOutputBackpressureOptions?.outputLimiterOptions,powershellUtf8Console:zu(this.options.powershellUtf8Console),powershellUtf8ChildEnv:zu(this.options.powershellUtf8ChildEnv),powershellParseAfterUtf8Switch:zu(this.options.powershellParseAfterUtf8Switch),powershellWebRequestUtf8:zu(this.options.powershellWebRequestUtf8),powershellPerLineStateDump:zu(this.options.powershellPerLineStateDump),...void 0===D?{}:{powershellRunObserver:D}})){_=0,C="",E="",x="";let e=!1,t=!1;if("stdout"===r.type||"stderr"===r.type){const n=T[r.type],o="stdout"===r.type?p:f,i=void 0===l||!0===l.truncated;let a=!1;if(!o||!i){_=r.data.length;const c="stdout"===r.type?d:h,p=!o&&c+_<=rs,f=void 0!==l&&!0!==l.truncated&&l.size+_<=Mc;"stdout"===r.type?e=p:t=p;const m=!o&&!p,g=!i&&!f;if((m||g)&&(x=n.peek(),g&&N(x),m&&(E=x)),(p||f)&&(C=n.write(r.data),a=!0,A.note(r.type,C),M?.noteBytes(r.type,r.data),M?.noteText(r.type,C)),void 0!==l&&l.size+_>Mc)l.truncated=!0;else if(f&&void 0!==l)if(l.size+=_,l.lineCount+=Vu(r.data),l.file)l.file.write(C);else if(l.buffer+=C,l.size>l.threshold){const e=s.default.join(this.projectDir,$c);l.path=s.default.join(e,`${(0,bo.randomUUID)()}.txt`);try{await(0,Co.mkdir)(e,{recursive:!0}),l.file=(0,xo.createWriteStream)(l.path),l.file.on("error",(e=>{u??=e})),l.file.write(l.buffer)}catch(e){u??=e instanceof Error?e:new Error(String(e)),l.truncated=!0}l.buffer=""}}a||(n.end(),A.note(r.type,x),M?.noteDropped(r.type),M?.noteText(r.type,x))}switch(r.type){case"stdout":e?(d+=_,C&&(yield{type:"stdout",data:C})):p||(E&&(yield{type:"stdout",data:E}),p=!0,yield{type:"stdout_trimmed"});break;case"suppressed_output":m||(m=!0,yield{type:"stdout",data:Oo.Ls});break;case"stderr":t?(h+=_,C&&(yield{type:"stderr",data:C})):f||(E&&(yield{type:"stderr",data:E}),f=!0,yield{type:"stderr_trimmed"});break;case"exit":{yield*L();const e=Math.max(0,Math.round(performance.now()-o));let t;if(l?.file){if(l.truncated){const e=`\n... (output truncated at ${l.size} bytes) ...\n`;l.file.write(e),l.size+=e.length,l.lineCount+=Js(e)-1}const e=await new Promise((e=>l.file.end(e)));u??=e??void 0,u?await(0,Co.rm)(l.path,{force:!0}):t=new Dc.pV({filePath:l.path,sizeBytes:BigInt(l.size),lineCount:BigInt(l.lineCount)})}u&&void 0!==l?.path&&(yield{type:"stderr",data:`\nThe full output could not be saved to ${l.path}: ${u.message}\n`}),yield{type:"exit",code:r.code,signal:r.signal,aborted:r.aborted,outputLocation:t,localExecutionTimeMs:e};break}case"stdin_ready":M?.noteShell(r.shell),yield{type:"stdin_ready",stdin:r.stdin,pid:r.pid};break;case"sandbox_denies":yield{type:"sandbox_denies",events:r.events}}}yield*L()}catch(t){if("ENOENT"===Sc(t)&&(0,qs.$f)(c))try{Mu.warn(e,"shell failed with ENOENT in an agent store working directory",{...await(0,qs.KZ)(c)})}catch{}throw t}finally{F()}}catch(e){r.error=e,r.hasError=!0}finally{$u(r)}}async getCwd(e){return this.executorFor(e).getCwd()}getWorkspacePath(){if(!this.workspacePath)throw new Error("Workspace path is not configured");return this.workspacePath}}class Zu{constructor(e,t){this.innerExecutor=e,this.shellManager=t}async*execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{Au(r,(0,$.VI)(e.withName("ManagedShellCoreExecutor.execute")),!1),Mu.info(e,"Executing shell command",{command:t.command,workingDirectory:t.workingDirectory,toolCallId:t.toolCallId});let n=null;t.toolCallId&&(n=this.shellManager.getOrCreateShellEmitter(t.toolCallId));for await(const r of this.innerExecutor.execute(e,t)){if(n)switch(r.type){case"stdin_ready":n.emit({type:"stdin_ready",stdin:r.stdin,pid:r.pid});break;case"start":n.emit({type:"start",sandboxed:r.sandboxed});break;case"stdout":n.emit({type:"stdout",data:r.data});break;case"stderr":n.emit({type:"stderr",data:r.data});break;case"exit":n.emit({type:"exit",code:r.code??-1,aborted:r.aborted})}yield r}}catch(e){r.error=e,r.hasError=!0}finally{$u(r)}}async getCwd(e){return this.innerExecutor.getCwd(e)}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}class Xu{constructor(e,t){this.innerExecutor=e,this.askpassConfig=t}async*execute(e,t){const r={...t,askpassConfig:t.askpassConfig??this.askpassConfig};yield*this.innerExecutor.execute(e,r)}async getCwd(e){return this.innerExecutor.getCwd(e)}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}async function Qu(e,t){switch(e.type){case"needsApproval":return t.onNeedsApproval(e.approvalReason,e.approvalDetails);case"userRejected":return t.onUserRejected(e.reason);case"cursorIgnore":return t.onPermissionDenied("Blocked by cursor ignore");case"permissionsConfig":return t.onPermissionDenied("Blocked by permissions configuration",{isReadonly:e.isReadonly});case"cursorFiles":return t.onPermissionDenied("Blocked by cursor files protection");case"adminBlock":return t.onPermissionDenied("Blocked by admin repository block");case"adminCommandDenylist":return t.onPermissionDenied(Ss(e.pattern));case"unsafeResolution":return t.onPermissionDenied(e.message);default:{const t=e;throw new Error(`Unhandled block reason type: ${JSON.stringify(t)}`)}}}function Yu(e){switch(e.type){case"userRejected":return e.reason;case"unsafeResolution":return e.message;case"adminCommandDenylist":return Ss(e.pattern);case"needsApproval":case"cursorIgnore":case"adminBlock":case"permissionsConfig":case"cursorFiles":return"Command is not allowed";default:{const t=e;return`Command is not allowed (${JSON.stringify(t)})`}}}function ed(e,t,r){return"permissionsConfig"===r.type?{case:"permissionDenied",value:new he.jn({command:e,workingDirectory:t,error:"Command blocked by permissions configuration",isReadonly:r.isReadonly??!1})}:{case:"rejected",value:new he.pZ({command:e,workingDirectory:t,reason:Yu(r)})}}var td=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const rd=(0,l.h)("local-exec:background-shell");function nd(e,t,r){return new Do.Lt({result:ed(e,t,r)})}class od{constructor(e,t){this.id=e,this.abortController=t,this.disposed=!1,this.completed=!1,this.completionListeners=[]}abort(){this.abortController.abort()}dispose(){this.disposed||(this.disposed=!0,this.abortController.signal.aborted||this.abortController.abort())}get signal(){return this.abortController.signal}isDisposed(){return this.disposed}onComplete(e){this.completed&&this.completion?e(this.completion):this.completionListeners.push(e)}markCompleted(e){if(this.completed)return;this.completed=!0,this.completion=e;const t=[...this.completionListeners];this.completionListeners=[];for(const r of t)r(e)}}async function sd(e,t){let r;try{for(let n=await t.next();!n.done;n=await t.next())"stdin_ready"===n.value.type?(e.stdin=n.value.stdin,e.pid=n.value.pid):"exit"===n.value.type&&(r={code:n.value.code,signal:n.value.signal,aborted:n.value.aborted,outputPath:n.value.outputLocation?.filePath})}catch(e){}finally{e.markCompleted(r??{code:null,aborted:e.signal.aborted})}}function id(e){e().catch((()=>{}))}class ad{constructor(e){if(this.args=e,this.carryover="",this.matchedOccurrences=0,this.emittedNotifications=0,this.finished=!1,this.monotonicStartMs=performance.now(),this.limit=e.config.notificationLimit??100,e.config.pattern.length>500)throw new Error("Output notification pattern exceeds 500 characters");this.regex=Qo.L3.compile(e.config.pattern,Qo.L3.MULTILINE)}observe(e){if(this.finished||this.matchedOccurrences>=this.limit||0===e.length)return;if(e.length>65536){for(const t of function(e){if(0===e.length)return[];const t=Math.max(1,Math.trunc(65536)||1),r=[];let n=0;for(;n=this.limit)break;this.observe(t)}return}const t=this.carryover.length,r=`${this.carryover}${e}`,n=this.regex.matcher(r);for(;this.matchedOccurrencest&&this.queueMatch(e)}this.carryover=Ko(r,1024)}finish(){this.finished||(this.finished=!0,this.flushPendingBatch("finish"),this.clearFlushTimer(),0===this.matchedOccurrences&&this.recordWatchOutcome("silent",{silent_ms:ud(this.monotonicStartMs)}))}queueMatch(e){if(this.matchedOccurrences>=this.limit)return;this.matchedOccurrences+=1;const t=this.matchedOccurrences,r=function(e,t){return e.length<=5e3?`${t}: ${e}`:`${t} is ${e.length} characters; omitted from notification detail.`}(e,1===t?"Matched text":"Latest match");return 1===t?(this.emitNotification({startOccurrence:t,endOccurrence:t,count:1,matchedTextDetail:r}),this.recordWatchOutcome("matched",{first_match_ms:ud(this.monotonicStartMs)}),void(t===this.limit&&this.emitLimitReachedNotification())):(this.pendingBatch?(this.pendingBatch.endOccurrence=t,this.pendingBatch.count+=1,this.pendingBatch.matchedTextDetail=r):this.pendingBatch={startOccurrence:t,endOccurrence:t,count:1,matchedTextDetail:r},t===this.limit?(this.flushPendingBatch("limit"),void this.emitLimitReachedNotification()):void this.scheduleFlush())}scheduleFlush(){if(void 0!==this.flushTimer)return;const e=this.getDebounceMs();this.flushTimer=setTimeout((()=>{this.flushPendingBatch("debounce")}),e)}getDebounceMs(){const e=this.args.debounceMs??function(e){const t=e.debounce;if(void 0!==t&&Number.isFinite(t))return Math.ceil(1e3*t)}(this.args.config)??5e3;return Math.max(e,5e3)}clearFlushTimer(){void 0!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0)}flushPendingBatch(e){const t=this.pendingBatch;t&&(this.pendingBatch=void 0,this.clearFlushTimer(),this.emitNotification(t))}emitNotification(e){this.emittedNotifications+=1;const t=this.args.config.reason.trim()||`Shell output contains /${this.args.config.pattern}/`,r=this.args.config.pattern,n=void 0!==e.matchedTextDetail?` ${e.matchedTextDetail}.`:"",o=1===e.count?`Shell output has pattern /${r}/. This is occurrence number ${e.startOccurrence}.${n} The title message is being displayed to the user.`:`Shell output matched /${r}/ ${e.count} more times since the previous notification. The title message is being displayed to the user.${n}`,s=Ro(String(this.args.shellId),this.emittedNotifications);var i;this.args.registry.enqueue({conversationId:this.args.conversationId,id:s,source:"shell",payload:{taskId:s,...void 0!==this.args.toolCallId?{toolCallId:this.args.toolCallId}:{},kind:"shell",status:"success",title:(i=t,i.length<=500?i:`${Vo(i,500)}...`),detail:o,outputPath:this.args.outputPath,reason:"task_progress"}})}emitLimitReachedNotification(){this.emittedNotifications+=1;const e=this.args.config.pattern,t=Ro(String(this.args.shellId),this.emittedNotifications);this.args.registry.enqueue({conversationId:this.args.conversationId,id:t,source:"shell",payload:{taskId:t,...void 0!==this.args.toolCallId?{toolCallId:this.args.toolCallId}:{},kind:"shell",status:"success",title:`Notification limit reached (${this.limit})`,detail:`Shell output matched /${e}/ ${this.limit} times and has reached the notification limit. No further notifications will be sent for this pattern. To continue monitoring, read the output file directly at the output path.`,outputPath:this.args.outputPath,reason:"task_progress"}}),this.recordWatchOutcome("limit_reached")}recordWatchOutcome(e,t){void 0!==this.args.ctx&&rd.info(this.args.ctx,"agent.shell_output_notification_match",{event:"agent.shell_output_notification_match",outcome:e,shell_id:this.args.shellId,conversation_id:this.args.conversationId,tool_call_id:this.args.toolCallId,limit:this.limit,...t})}}class cd{constructor(e,t,r){this.innerFactory=e,this.projectDir=t,this.backgroundWorkRegistry=r}async spawn(e,t){const r=this.createObserver(e.ctx,e.shellId,e.conversationId,e.toolCallId,e.outputNotification);if(!r)return this.innerFactory.spawn(e,t);try{return await this.innerFactory.spawn(e,this.createObservingExecutor(t,r))}catch(e){throw r.finish(),e}}async adopt(e){const t=this.createObserver(e.ctx,e.shellId,void 0,e.toolCallId,e.outputNotification);if(!t)return this.innerFactory.adopt(e);e.initialOutput.length>0&&t.observe(e.initialOutput);try{return await this.innerFactory.adopt({...e,eventIterator:this.createObservingIterator(e.eventIterator,t)})}catch(e){throw t.finish(),e}}createObserver(e,t,r,n,o){if(!this.backgroundWorkRegistry||!o)return;if(0===o.pattern.trim().length)return;const i=s.join(this.projectDir,"terminals",`${t}.txt`);try{return new ad({shellId:t,outputPath:i,config:o,conversationId:r??Po,toolCallId:n,registry:this.backgroundWorkRegistry,ctx:e})}catch(r){return void(void 0!==e&&rd.warn(e,"Invalid shell output notification pattern",{shellId:t,error:r instanceof Error?r.message:String(r)}))}}createObservingExecutor(e,t){const r=e.execute.bind(e);return{...e,execute:async function*(e,n){try{for await(const o of r(e,n))"stdout"===o.type||"stderr"===o.type?t.observe(o.data):"exit"===o.type&&t.finish(),yield o}finally{t.finish()}}}}createObservingIterator(e,t){const r=e.return?.bind(e);return{next:async()=>{try{const r=await e.next();if(r.done)t.finish();else{const e=r.value;"stdout"===e.type||"stderr"===e.type?t.observe(e.data):"exit"===e.type&&t.finish()}return r}catch(e){throw t.finish(),e}},return:async e=>(t.finish(),r?r(e):{done:!0,value:void 0})}}}class ld{async spawn(e,t){const r=new AbortController,n=new od(e.shellId,r),o=t.execute(e.ctx,{command:e.command,workingDirectory:e.workingDirectory,signal:r.signal,toolCallId:e.toolCallId,conversationId:e.conversationId,requestId:e.requestId,secretScopeId:e.secretScopeId,sandboxPolicy:e.sandboxPolicy,pipeStdin:e.enableWriteShellStdinTool,showElapsedTime:!0})[Symbol.asyncIterator]();try{for(let e=await o.next();!e.done;e=await o.next())if("stdin_ready"===e.value.type){n.stdin=e.value.stdin,n.pid=e.value.pid;break}}catch(e){if(e instanceof Oo.SandboxUnsupportedError||e instanceof Ku)throw e}return id((()=>sd(n,o))),n}async adopt(e){const t=new od(e.shellId,e.abortController);return t.stdin=e.stdin,t.pid=e.pid,id((()=>sd(t,e.eventIterator))),t}}function ud(e){return Math.round(performance.now()-e)}function dd(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}function hd(e){const t=String(e.runningForMs).padEnd(9," "),r=e.status.padEnd(9," ");let n="---\n";return void 0!==e.pid&&0!==e.pid&&(n+=`pid: ${e.pid}\n`),n+=`cwd: ${dd(e.cwd)}\n`,n+=`command: ${dd(e.command)}\n`,void 0!==e.title&&e.title.trim().length>0&&(n+=`title: ${dd(e.title)}\n`),n+=`status: ${r}\n`,n+=`started_at: ${e.startedAt}\n`,n+=`running_for_ms: ${t}\n`,n+="---\n",n}function pd(e){return`\n[${e} truncated by cursor: the command wrote more than 1048576 characters to ${e}; only the first 1048576 were captured and the rest was dropped from this file]\n`}class fd{constructor(e,t){this.innerFactory=e,this.projectDir=t}async spawn(e,t){const r=s.join(this.projectDir,"terminals");await(0,Co.mkdir)(r,{recursive:!0});const n=this.createLoggingExecutor(t,e,r);return this.innerFactory.spawn(e,n)}createLoggingExecutor(e,t,r){const o=e.execute.bind(e);return{...e,execute:async function*(e,i){let a,c,l,u=!1,d=!1,h=!1,p=!1;const f=Date.now(),m=new Date(f).toISOString(),g=performance.now();let w,y="running",v=!1,b=Promise.resolve();const S=async e=>{if(c)try{await c.write(e)}catch(e){}},k=t.shellId,_=s.join(r,`${k}.txt`),C=async()=>{if(!a)return;const e=ud(g),r=hd({pid:w,cwd:t.workingDirectory,command:t.command,title:t.description,status:y,startedAt:m,runningForMs:e});try{await a.write(r,0,"utf8")}catch(e){}},E=()=>(b=b.then(C).catch((()=>{})),b),x=()=>{void 0!==l&&(clearInterval(l),l=void 0)},P=async e=>{if(p)return;p=!0,w=e;const r=ud(g),n=hd({pid:e,cwd:t.workingDirectory,command:t.command,title:t.description,status:y,startedAt:m,runningForMs:r});await(0,Co.writeFile)(_,n,"utf8"),l=setInterval((()=>{E()}),5e3)},R=async()=>{a||(a=await xo.promises.open(_,"r+")),c||(c=await xo.promises.open(_,"a"))},I=async(e,t)=>{if(!v){if(v=!0,x(),p||await P(),await R(),void 0!==t){const e=ud(g),r=`\n---\n${t}\n`+(i.showElapsedTime?`elapsed_ms: ${e}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await S(r)}y=e,await E()}};try{for await(const r of o(e,i)){if("stdout"===r.type)p||(await P(),await R()),await S(r.data);else if("stderr"===r.type)p||(await P(),await R()),await S(r.data);else if("stdout_trimmed"!==r.type||d)if("stderr_trimmed"!==r.type||h)if("stdin_ready"!==r.type||u)"exit"===r.type&&await I(r.aborted?"aborted":0===r.code?"succeeded":"failed",`exit_code: ${r.code??"unknown"}`);else{u=!0,p||(await P(r.pid),await R());const e=r.stdin;if(e&&!0!==t.suppressStdinLogging){const t=e=>{if(null==e)return;const t="string"==typeof e?e:n.Buffer.isBuffer(e)||e instanceof Uint8Array?n.Buffer.from(e).toString():"";if(!t)return;const r=t.endsWith("\n")?t:`${t}\n`;S(`[stdin] ${r}`)},r=e.write.bind(e);if(e.write=(e,n,o)=>(t(e),r(e,n,o)),"function"==typeof e.end){const r=e.end.bind(e);e.end=(e,n,o)=>(void 0!==e&&t(e),r(e,n,o))}}}else h=!0,p||await P(),await R(),await S(pd("stderr"));else d=!0,p||await P(),await R(),await S(pd("stdout"));yield r}if(!v){const e=i.signal?.aborted??!1;await I(e?"aborted":"failed")}}catch(e){const t=i.signal?.aborted??!1,r=dd(e instanceof Error?e.message:"Unknown error");if(await I(t?"aborted":"failed",t?void 0:`error: ${r}`),!t)throw e}finally{if(x(),await b,a)try{await a.close()}catch{}if(c)try{await c.close()}catch{}}}}}async adopt(e){const t=s.join(this.projectDir,"terminals");await(0,Co.mkdir)(t,{recursive:!0});const r=s.join(t,`${e.shellId}.txt`),n=e.startTime,o=new Date(n).toISOString(),i=e.monotonicStartMs;let a="running";const c=ud(i),l=hd({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:a,startedAt:o,runningForMs:c})+(e.initialOutput??"");await(0,Co.writeFile)(r,l,"utf8");const u=await xo.promises.open(r,"r+");let d;try{d=await xo.promises.open(r,"a")}catch(e){throw await u.close(),e}let h=!1,p=!1,f=!1,m=!1,g=Promise.resolve();const w=async()=>{const t=ud(i),r=hd({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:a,startedAt:o,runningForMs:t});try{await u.write(r,0,"utf8")}catch{}},y=()=>(g=g.then(w).catch((()=>{})),g);let v=setInterval((()=>{y()}),5e3);const b=()=>{void 0!==v&&(clearInterval(v),v=void 0)},S=async()=>{if(!h){h=!0,b(),await g;try{await u.close()}catch{}try{await d.close()}catch{}}},k=async e=>{try{await d.write(e)}catch(e){}},_=async(t,r)=>{if(!p){if(p=!0,b(),void 0!==r){const t=ud(i),n=`\n---\n${r}\n`+(e.showElapsedTime?`elapsed_ms: ${t}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await k(n)}a=t,await y()}},C={next:async()=>{try{const t=await e.eventIterator.next();if(t.done){if(!p){const t=e.abortController.signal.aborted;await _(t?"aborted":"failed")}}else{const e=t.value;"stdout"===e.type||"stderr"===e.type?await k(e.data):"stdout_trimmed"!==e.type||f?"stderr_trimmed"!==e.type||m?"exit"===e.type&&(await _(e.aborted?"aborted":0===e.code?"succeeded":"failed",`exit_code: ${e.code??"unknown"}`),await S()):(m=!0,await k(pd("stderr"))):(f=!0,await k(pd("stdout")))}return t.done&&await S(),t}catch(t){const r=e.abortController.signal.aborted;throw await _(r?"aborted":"failed"),await S(),t}},return:async()=>{if(!p){const t=e.abortController.signal.aborted;await _(t?"aborted":"failed")}return await S(),e.eventIterator.return?e.eventIterator.return():{done:!0,value:void 0}}};return this.innerFactory.adopt({...e,eventIterator:C})}}class md{constructor(e,t){this.factory=e,this.backgroundWorkRegistry=t,this.runningShells=new Map,this.nextShellId=1e3+Math.floor(999e3*Math.random())}registerShellWork(e,t){const r=String(e.id);this.backgroundWorkRegistry?.upsertWork({id:r,kind:"shell",state:"running",metadata:Io(t),abort:()=>{this.abort(e.id)}})}clearShellWork(e){this.backgroundWorkRegistry?.clearWork(String(e))}cleanupShell(e){this.runningShells.has(e)&&(this.runningShells.delete(e),this.clearShellWork(e))}enqueueShellCompletion(e,t,r,n,o,s){if(!this.backgroundWorkRegistry)return;const i=s.aborted?"aborted":0===s.code?"success":"error",a=function(e){if(!e.aborted)return void 0!==e.signal?`signal=${e.signal}`:null!==e.code&&0!==e.code?`exit_code=${e.code}`:void 0}(s),c=function(e){if(!e.aborted)return void 0!==e.signal?{kind:"signal",signal:e.signal}:null!==e.code?{kind:"exit",code:e.code}:void 0}(s),l=n.description?.trim()?n.description:void 0,u=String(e);this.backgroundWorkRegistry.enqueue({conversationId:r??Po,id:u,source:"shell",payload:{taskId:u,...void 0!==t?{toolCallId:t}:{},kind:"shell",status:i,title:n.description||n.command,...a?{detail:a}:{},...s.outputPath?{outputPath:s.outputPath}:{},reason:"task_finished",durationMs:ud(o),...c?{shellEnd:c}:{},...l?{description:l}:{}}})}async spawn(e,t){const r=await this.factory.spawn(e,t),n=Date.now(),o=performance.now();{const __t3b=globalThis[Symbol.for("@cursor/sdk.backgroundShell")];if(typeof __t3b==="function")try{__t3b({conversationId:e.conversationId,toolCallId:e.toolCallId,command:e.command,description:e.description,shell:r})===!0&&(r.__t3kept=!0)}catch{}}return this.runningShells.set(r.id,r),this.registerShellWork(r,{title:e.description||e.command,cwd:e.workingDirectory,startTimeMs:n}),r.signal.addEventListener("abort",(()=>{this.cleanupShell(r.id)})),r.onComplete?.((t=>{this.enqueueShellCompletion(r.id,e.toolCallId,e.conversationId,{command:e.command,description:e.description},o,t),this.cleanupShell(r.id)})),{shellId:r.id,pid:r.pid}}async adopt(e){const t=await this.factory.adopt(e);{const __t3b=globalThis[Symbol.for("@cursor/sdk.backgroundShell")];if(typeof __t3b==="function")try{__t3b({conversationId:e.conversationId,toolCallId:e.toolCallId,command:e.command,description:e.description,shell:t})===!0&&(t.__t3kept=!0)}catch{}}return this.runningShells.set(t.id,t),this.registerShellWork(t,{title:e.description||e.command,cwd:e.workingDirectory,startTimeMs:e.startTime}),t.signal.addEventListener("abort",(()=>{this.cleanupShell(t.id),e.onCleanup?.()})),t.onComplete?.((r=>{this.enqueueShellCompletion(t.id,e.toolCallId,void 0,{command:e.command,description:e.description},e.monotonicStartMs,r),this.cleanupShell(t.id),e.onCleanup?.()})),{shellId:t.id,pid:e.pid}}generateShellId(){for(let e=0;e<=998999;e++){this.nextShellId>999999&&(this.nextShellId=1e3);const e=this.nextShellId;if(this.nextShellId+=1,!this.runningShells.has(e))return e}throw new Error("No available background shell id in range")}abort(e){const t=this.runningShells.get(e);return!!t&&(t.abort(),this.runningShells.delete(e),this.clearShellWork(e),!0)}isRunning(e){return this.runningShells.has(e)}dispose(){for(const[e,t]of this.runningShells)t.__t3kept||t.dispose(),this.clearShellWork(e);this.runningShells.clear()}async writeStdin(e,t){const r=this.runningShells.get(e);if(!r)throw new Error("Shell not found");if(!r.stdin)throw new Error("Shell stdin not available");const n=t.indexOf(""),o=-1!==n?n:t.indexOf("\\u0004");if(-1!==o){const e=t.substring(0,o);e.length>0&&await new Promise(((t,n)=>{r.stdin.write(e,(e=>{e?n(e):t(void 0)}))})),r.stdin.end()}else await new Promise(((e,n)=>{r.stdin.write(t,(t=>{t?n(t):e(void 0)}))}))}}new WeakMap;class gd{constructor(e,t){this.inner=e,this.ownerConversationId=t}enqueue(e){this.inner.enqueue({...e,conversationId:this.ownerConversationId})}enqueueCompletion(e){this.enqueue({conversationId:this.ownerConversationId,id:e.taskId,source:e.kind,payload:e})}pull(e){return this.inner.pull(e)}ack(e){return this.inner.ack(e)}nack(e,t){this.inner.nack(e,t)}suppress(e,t){this.inner.suppress(e,t)}upsertWork(e){this.inner.upsertWork(e)}clearWork(e){return this.inner.clearWork(e)}abortWork(e){return this.inner.abortWork(e)}hasRunningWork(e){return this.inner.hasRunningWork(e)}abortAllWork(e){return this.inner.abortAllWork(e)}listWork(e){return this.inner.listWork(e)}drainCompletions(){return this.inner.drainCompletions()}hasPendingCompletions(e){return this.inner.hasPendingCompletions(e)}markAwaitedCompletion(e){this.inner.suppress(this.ownerConversationId,e)}}class wd{constructor(e,t,r,n,o,s,i,a){if(this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r,void 0!==a)return this.backgroundShellManager=a,void(this.ownsBackgroundShellManager=!1);const c=s&&void 0!==i?new gd(s,i):s,l=o??function(e){const t=new ld;return new fd(t,e)}(n),u=new cd(l,n,c);this.backgroundShellManager=new md(u,c),this.ownsBackgroundShellManager=!0}getManager(){return this.backgroundShellManager}dispose(){this.ownsBackgroundShellManager&&this.backgroundShellManager.dispose()}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,$.VI)(e.withName("LocalBackgroundShellExecutor.execute")),!1);const n=t.command,o=t.sandboxPolicy?ls(t.sandboxPolicy):void 0,s=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),i=(0,Yo.o1)(s),a=new he.HO(Wo(n).structured),c=ks({command:n,parsingResult:a,blockedCommands:t.adminCommandDenylist});if(void 0!==c)return new Do.Lt({result:{case:"rejected",value:new he.pZ({command:n,workingDirectory:i,reason:c})}});let l;if(rd.info(e,"Background shell: approval gate reached",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,hasSmartModeApproval:void 0!==t.smartModeApproval,hasSmartModeApprovalReason:void 0!==t.smartModeApproval?.reason,hasSmartModeApprovalRequestId:void 0!==t.smartModeApproval?.requestId,requestedPolicyType:o?.type??"undefined",parserCommandCount:a.executableCommands.length,classifierCommandCount:t.classifierResult?.commands.length??0,commandLength:n.length}),Mo(t)){const r=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:i,skipUnsafeWorkingDirectoryBlock:!0,command:n,parsingResult:a,toolCallId:t.toolCallId,resolveSkippedApprovalPolicy:!0},o);if("block"===r.kind)return rd.info(e,"Background shell: invariant blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,skipApproval:t.skipApproval}),nd(n,i,r.reason);l=r.policy??o,rd.info(e,"Background shell: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:o?.type??"undefined",effectivePolicyType:l?.type??"undefined"})}else{const r=await this.permissionsService.shouldBlockShellCommand(e,n,{workingDirectory:i,timeout:0,parsingResult:a,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Ao(t)},o);if("block"===r.kind)return rd.info(e,"Background shell: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),nd(n,i,r.reason);l=r.policy,rd.info(e,"Background shell: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:l.type})}l=await Tc(l,{command:n,workingDirectory:i,parsingResult:a,permissionsService:this.permissionsService,ignoreService:this.ignoreService});try{const r=this.backgroundShellManager.generateShellId(),o=l?{perUser:l}:void 0,s={ctx:e,command:n,workingDirectory:i,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:o,shellId:r,enableWriteShellStdinTool:t.enableWriteShellStdinTool,suppressStdinLogging:t.suppressStdinLogging,description:t.description,outputNotification:t.outputNotification},a=await this.backgroundShellManager.spawn(s,this.coreExecutor);return new Do.Lt({result:{case:"success",value:new Do.Po({shellId:r,command:n,workingDirectory:i,pid:a.pid})}})}catch(r){if(r instanceof Oo.SandboxUnsupportedError){const o=l?.type??"unknown";return rd.debug(e,"Background shell: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:o,reason:r.reason}),new Do.Lt({result:{case:"sandboxUnsupported",value:new he.rI({command:n,workingDirectory:i,sandboxPolicyType:o,reason:r.reason??r.message,isReadonly:"workspace_readonly"===o})}})}return new Do.Lt({result:{case:"error",value:new Do.Of({command:n,workingDirectory:i,error:r instanceof Error?r.message:"Unknown error"})}})}}catch(e){r.error=e,r.hasError=!0}finally{td(r)}}writeStdin(e,t){return this.backgroundShellManager.writeStdin(e,t)}}var yd=r("node:async_hooks");r("../../node_modules/.pnpm/minimatch@10.2.5/node_modules/minimatch/dist/esm/index.js");function vd(e){return e instanceof Error?e.message:String(e)}function bd(e){return"Failed to read skill file: "+vd(e)}function Sd(e){return"Invalid skill frontmatter: "+vd(e)}function kd(e,t){return e||t?void 0:"Description is required"}new Set(["EACCES","EPERM","ENOENT","ENOTDIR","EISDIR","ELOOP","ENAMETOOLONG"]);const _d=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function Cd(e){return e.toLocaleString("en-US")}var Ed=r("node:url");const xd={beforeShellExecution:"beforeShellExecution",beforeMCPExecution:"beforeMCPExecution",afterShellExecution:"afterShellExecution",afterMCPExecution:"afterMCPExecution",beforeReadFile:"beforeReadFile",afterFileEdit:"afterFileEdit",beforeTabFileRead:"beforeTabFileRead",afterTabFileEdit:"afterTabFileEdit",stop:"stop",beforeSubmitPrompt:"beforeSubmitPrompt",afterAgentResponse:"afterAgentResponse",afterAgentThought:"afterAgentThought",sessionStart:"sessionStart",sessionEnd:"sessionEnd",preCompact:"preCompact",subagentStart:"subagentStart",subagentStop:"subagentStop",preToolUse:"preToolUse",postToolUse:"postToolUse",postToolUseFailure:"postToolUseFailure",workspaceOpen:"workspaceOpen"},Pd=e=>"string"==typeof e,Rd=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),Id=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),Td=(e,t=[])=>({isValid:e,errors:t});function Ad(e,t,r){void 0===e||Pd(e)||r.push(`${t} must be a string if provided`)}const $d=e=>{const t=[];if(!Rd(e))return t.push("Hook script must be an object with either a 'command' property (command hook) or 'type: \"prompt\"' with a 'prompt' property (prompt hook)"),Td(!1,t);const r=e.type;return"prompt"===r?((e,t)=>{Pd(e.prompt)?""===e.prompt.trim()&&t.push("Prompt hook 'prompt' property cannot be empty"):t.push("Prompt hook must have a 'prompt' property (string)"),void 0!==e.model&&(Pd(e.model)?""===e.model.trim()&&t.push("Prompt hook 'model' cannot be an empty string"):t.push("Prompt hook 'model' must be a string if provided"))})(e,t):"command"===r||void 0===r?((e,t)=>{Pd(e.command)||t.push("Hook script command must be a string")})(e,t):t.push(`Invalid hook type: "${r}". Must be "command", "prompt", or omitted (defaults to "command")`),((e,t)=>{if(void 0!==e.matcher)if(Pd(e.matcher)){if(""!==e.matcher&&"*"!==e.matcher)try{new RegExp(e.matcher)}catch(r){t.push(`Hook script matcher "${e.matcher}" is not a valid regex: ${r?.message??String(r)}`)}}else t.push("Hook script matcher must be a string if provided");if(void 0!==e.timeout&&("number"!=typeof e.timeout?t.push("Hook script timeout must be a number (seconds)"):e.timeout<=0?t.push("Hook script timeout must be a positive number"):e.timeout>3600&&console.warn(`[hooks] Hook timeout of ${e.timeout}s is very long (>1 hour)`)),void 0!==e.loop_limit){const r=e.loop_limit;null!==r&&("number"!=typeof r?t.push("Hook script loop_limit must be a positive integer or null"):Number.isInteger(r)?r<=0&&t.push("Hook script loop_limit must be a positive integer (use null for no limit)"):t.push("Hook script loop_limit must be an integer"))}void 0!==e.failClosed&&"boolean"!=typeof e.failClosed&&t.push("Hook script failClosed must be a boolean")})(e,t),Td(0===t.length,t)},Md=(e,t)=>{const r=[];if(!Array.isArray(e))return r.push(`${t} must be an array of hook scripts`),Td(!1,r);for(let n=0;n{const t=[];if(!Rd(e))return t.push("Hooks config must be an object"),Td(!1,t);if("number"!=typeof e.version?t.push("Config version must be a number"):(!Number.isInteger(e.version)||e.version<1)&&t.push("Config version must be a positive integer"),!Rd(e.hooks))return t.push("Config hooks must be an object"),Td(!1,t);void 0!==e.stop_hook_loop_limit&&console.warn("[hooks] DEPRECATION WARNING: 'stop_hook_loop_limit' is deprecated. Use 'loop_limit' on individual hook scripts instead. The configured value is being ignored.");const r=Object.values(xd),n=e.hooks;for(const[e,o]of Object.entries(n))if(r.includes(e)){if(void 0!==o){const r=Md(o,e);r.isValid||t.push(...r.errors)}}else t.push(`Unknown hook type: ${e}. Valid types are: ${r.join(", ")}`);return Td(0===t.length,t)},Od={PreToolUse:xd.preToolUse,PermissionRequest:null,PostToolUse:xd.postToolUse,UserPromptSubmit:xd.beforeSubmitPrompt,Stop:xd.stop,SubagentStop:xd.subagentStop,SessionStart:xd.sessionStart,SessionEnd:xd.sessionEnd,PreCompact:xd.preCompact,Notification:null},Fd=Object.fromEntries(Object.entries(Od).filter((e=>Nd(e[0])&&null!==e[1])).map((([e,t])=>[t,e])));function Nd(e){return Object.prototype.hasOwnProperty.call(Od,e)}const Ld={Bash:"Shell",Read:"Read",Write:"Write",Edit:"Write",Glob:null,Grep:"Grep",WebFetch:"WebFetch",WebSearch:"WebSearch",Task:"Task"},jd=["Glob"],Ud=["Notification","PermissionRequest"],Bd=/^[A-Za-z0-9_./:=+-]+$/,Wd=/^=|^-.*\./,Hd=/\$\{(?:CLAUDE_PROJECT_DIR|CURSOR_PROJECT_DIR|CLAUDE_PLUGIN_ROOT|CURSOR_PLUGIN_ROOT)\}/g,qd=/^[^\p{Cc}$`"]*$/u,zd=/\\(?:[$`"\\]|$)/;function Gd(e){return`'${e.replace(/'/g,"'\\''")}'`}function Vd(e){if(Bd.test(e)&&!Wd.test(e))return e;const t=e.replace(Hd,"");if((t!==e||e.includes("'"))&&qd.test(t)&&!zd.test(e))return`"${e}"`;const r=[];let n=0;for(const t of e.matchAll(Hd))t.index>n&&r.push(Gd(e.slice(n,t.index))),r.push(`"${t[0]}"`),n=t.index+t[0].length;return(n{},info:()=>{}};function Jd(e,t,r=Kd){const n={loop_limit:null,failClosed:!1};if(t&&"*"!==t&&(n.matcher=t),void 0!==e.timeout&&(n.timeout=e.timeout),"prompt"===e.type)return e.prompt?{type:"prompt",prompt:e.prompt,...n}:null;const o=function(e,t){const r=e.command;if(!r)return null;const n=e.args;return null==n?(void 0!==e.shell&&t.warn(`Hook "${r}" sets shell "${e.shell}", which Cursor does not support; the platform default shell will be used`),r):(o=n,Array.isArray(o)&&o.every((e=>"string"==typeof e))?function(e,t){return[e,...t].map(Vd).join(" ")}(r,n):(t.warn(`Hook "${r}" has invalid "args" (expected an array of strings), skipping`),null));var o}(e,r);return null===o?null:{type:"command",command:o,...n}}function Zd(e,t,r=Kd){const n=[];let o;if("PreToolUse"===t||"PostToolUse"===t){const t=function(e,t=Kd){if(!e||"*"===e)return"*";const r=e.split("|"),n=[],o=[];for(const e of r){const t=e.trim();if(t.startsWith("mcp__")){const e=t.split("__");if(e.length>=3){const t=e.slice(2).join("__");n.push(`MCP:${t}`);continue}}const r=Ld[t];null!==r?void 0!==r?n.includes(r)||n.push(r):n.push(t):jd.includes(t)&&o.push(`Tool "${t}" is not supported in Cursor and will be ignored`)}for(const e of o)t.warn(e);return 0===n.length?null:n.join("|")}(e.matcher,r);if(null===t)return r.warn(`All tools in matcher "${e.matcher}" are unsupported, skipping hooks`),[];o="*"===t?void 0:t}else"SessionStart"===t||"PreCompact"===t?(e.matcher&&"*"!==e.matcher&&""!==e.matcher&&("SessionStart"===t?["startup","resume","clear","compact"].includes(e.matcher):["manual","auto"].includes(e.matcher))&&r.warn(`${t} trigger matcher "${e.matcher}" is not supported in Cursor, hooks will fire for all triggers`),o=void 0):o=void 0;for(const t of e.hooks){const e=Jd(t,o,r);e&&n.push(e)}return n}function Xd(e,t=Kd){const r={};for(const[n,o]of Object.entries(e)){if(!Nd(n)){t.warn(`Unknown Claude Code event "${n}", skipping`);continue}if(Ud.includes(n)){t.warn(`Claude Code event "${n}" is not supported in Cursor and will be ignored`);continue}const e=Od[n];if(!e){t.warn(`Unknown Claude Code event "${n}", skipping`);continue}const s=[];if(Array.isArray(o))for(const e of o){const r=Zd(e,n,t);s.push(...r)}else void 0!==o&&t.warn(`Claude Code event "${n}" has invalid value (expected array), skipping`);if(s.length>0){const t=r[e]||[];r[e]=[...t,...s]}}return{version:1,hooks:r}}var Qd=r("../../node_modules/.pnpm/gray-matter@4.0.3/node_modules/gray-matter/index.js");const Yd=()=>({});function eh(e,t){return Qd(e,{...t,engines:{...t?.engines,js:Yd,javascript:Yd}})}function th(e,t,r){return Qd.stringify({content:e,data:{}},t,r)}var rh=r("node:zlib");function nh(e,t){const r=function(e){return e.split(/[/\\]/).filter((e=>e))}(e);for(let e=0;ee.isDirectory())).map((e=>e.name))}catch{return[]}}async removeVersion(e){const t=this.getCacheDir(e);try{await(0,Co.rm)(t,{recursive:!0,force:!0})}catch{}}async removeAllVersions(e){const t=dh(this.cacheRoot,e);await(0,Co.rm)(t,{recursive:!0,force:!0})}async pruneOldVersions(e){const t=await this.listCachedVersions({marketplaceSlug:e.marketplaceSlug,pluginId:e.pluginId}),r=new Set(e.keepVersions.map((e=>lh(e))));for(const n of t)r.has(n)||await this.removeVersion({marketplaceSlug:e.marketplaceSlug,pluginId:e.pluginId,version:n})}async markCacheComplete(e){const t=this.getCacheDir(e);await(0,Co.writeFile)(uh({parent:t,name:ch}),"")}}class ph extends Error{constructor(e,t){super(t),this.reason=e,this.name="PluginContentInstallError"}}const fh=(0,zs.promisify)(rh.gunzip),mh=/^[A-Za-z0-9._-]{1,128}$/,gh=/^[0-9a-f]{64}$/,wh=/^[1-9]\d{0,18}$/,yh="backend-content://",vh="backend-content/",bh=new Map([[3,"request_refused"],[5,"not_found"],[9,"account_not_connected"],[10,"revision_superseded"],[12,"unsupported_server"],[14,"unavailable"]]),Sh=new Set(["unavailable","revision_superseded","timeout","download_failed","integrity"]);function kh(e){return e instanceof ph&&Sh.has(e.reason)}class _h{constructor(){this.awaited=new Map}forListing(e){return{startLoad:()=>{for(const[t,r]of this.awaited)r.listing===e&&(r.attemptedThisLoad?r.attemptedThisLoad=!1:this.awaited.delete(t))},heldFailure:({pluginDbId:e,revision:t})=>{const r=this.awaited.get(e);if(void 0!==r&&r.revision===t)return r.attemptedThisLoad=!0,Date.now(){kh(n)?this.awaited.set(t,{revision:r,reason:n.reason,retryAtMs:Date.now()+6e4,listing:e,attemptedThisLoad:!0}):this.awaited.delete(t)},isRetryDue:()=>this.isRetryDue(),allowImmediateRetry:()=>this.allowImmediateRetry()}}isRetryDue(){const e=Date.now();return[...this.awaited.values()].some((t=>e>=t.retryAtMs))}allowImmediateRetry(){for(const e of this.awaited.values())e.retryAtMs=0}}function Ch(e){if("bigint"!=typeof e&&"number"!=typeof e&&"string"!=typeof e)return;const t=String(e);return wh.test(t)?t:void 0}function Eh(e){return e.startsWith(yh)}function xh(e){return`${vh}${e}`}function Ph(e,t){return new ph(e,function(e,t){const r=JSON.stringify(t);switch(e){case"unsupported_client":return`Plugin ${r} could not be downloaded: this client cannot install plugins whose files the server provides.`;case"not_found":return`Plugin ${r} could not be downloaded: it no longer exists or you no longer have access to it.`;case"account_not_connected":return`Plugin ${r} could not be downloaded: connect your account on the host of its source repository first.`;case"revision_superseded":return`Plugin ${r} changed while it was downloading. The new version installs on the next plugin refresh.`;case"unavailable":return`Plugin ${r} could not be downloaded: its files cannot be served right now. It installs on a later plugin refresh.`;case"unsupported_server":return`Plugin ${r} could not be downloaded: this server does not provide plugin files.`;case"request_refused":return`Plugin ${r} could not be downloaded: the server refused the request.`;case"download_failed":return`Plugin ${r} could not be downloaded.`;case"timeout":return`Downloading plugin ${r} timed out.`;case"integrity":return`The download of plugin ${r} did not match the size or hash the server gave for it, so it was discarded.`;case"too_large":return`Plugin ${r} could not be downloaded: its files are larger than this client accepts.`;case"unsafe_archive":return`The download of plugin ${r} could not be unpacked safely, so it was discarded.`;case"unpack_failed":return`The download of plugin ${r} could not be written to the plugin cache.`;default:return e}}(e,t))}function Rh(e){if("File"!==e.type&&"OldFile"!==e.type&&"Directory"!==e.type)return!0;const t=e.path;return!(0!==t.length&&!t.includes("\0")&&!/^([/\\]|[A-Za-z]:)/.test(t))||t.split(/[/\\]/).includes("..")}async function Ih(e){const{download:t,pluginName:r,content:n,targetDir:o}=e;if(void 0===t)throw Ph("unsupported_client",r);const s=new AbortController;let i;try{i=await async function(e){const t=e[Symbol.asyncIterator](),r=()=>(0,Or.wj)(t.next(),12e4);try{const e=await r();if(!0===e.done||"header"!==e.value.part.case)return"integrity";const{sha256:t}=e.value.part.value,n=function(e){let t;if("bigint"==typeof e||"number"==typeof e)t=Number(e);else{if("string"!=typeof e||!/^\d{1,15}$/.test(e))return;t=Number(e)}return Number.isSafeInteger(t)&&t>0?t:void 0}(e.value.part.value.sizeBytes);if(void 0===n||"string"!=typeof t||!gh.test(t))return"integrity";if(n>16777216)return"too_large";const o=[];let s=0;for(;;){const e=await r();if(!0===e.done)break;const{part:t}=e.value;if(void 0!==t.case){if("data"!==t.case||0===t.value.byteLength)return"integrity";if(s+=t.value.byteLength,s>n)return"integrity";o.push(t.value)}}const i=Buffer.concat(o,s);return s===n&&(0,bo.createHash)("sha256").update(i).digest("hex")===t?i:"integrity"}finally{Promise.resolve(t.return?.()).catch((()=>{}))}}(t({pluginId:BigInt(e.pluginDbId),revision:n.revision},{signal:s.signal}))}catch(e){throw Ph(function(e){return e instanceof Or.MU?"timeout":"object"==typeof e&&null!==e&&"code"in e?"number"!=typeof e.code?"download_failed":bh.get(e.code)??"download_failed":"download_failed"}(e),r)}finally{s.abort()}if("string"==typeof i)throw Ph(i,r);const a=await async function(e){let t;try{t=await fh(e,{maxOutputLength:268435456})}catch{return}const r=t.byteLength>=512,n=r&&31===t[0]&&139===t[1],o=r&&682962941===t.readUInt32BE(0);if(r&&!n&&!o)return t}(i);if(void 0===a||!await function(e){return new Promise((t=>{let r=0;const n=(0,sh.p_)({strict:!0,onReadEntry:e=>{r+=1,(r>5e4||Rh(e))&&(t(!1),n.abort(new Error("unsafe entry")))}});n.once("end",(()=>t(r>0))),n.once("error",(()=>t(!1))),n.end(e)}))}(a))throw Ph("unsafe_archive",r);try{await async function(e,t){const r=(0,sh.o6)({cwd:t,strict:!0,preserveOwner:!1,filter:(e,t)=>{if(!("type"in t)||Rh(t))return!1;const r=!!(64&(t.mode??0));return t.mode="Directory"===t.type||r?493:420,!0}});await new Promise(((t,n)=>{r.once("close",t),r.once("error",n),r.end(e)}))}(a,o)}catch{throw Ph("unpack_failed",r)}}function Th(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")||"/"}function Ah(e,t){if(Object.hasOwn(e,t))return e[t]}function $h(e,t,r,n){const o=e?.plugins;if(!o||"object"!=typeof o)return[];const s=t?.enabledPlugins??{},i={};r?.enabledPlugins&&Object.assign(i,r.enabledPlugins);const a=void 0!==n?Th(n):void 0,c=new Set,l=[];for(const[e,t]of Object.entries(o)){if(!Array.isArray(t)||0===t.length)continue;if(void 0!==a&&!1===Ah(i,e))continue;let r;void 0!==a&&(r=t.find((t=>!("project"!==t.scope&&"local"!==t.scope||!t.projectPath)&&(Th(t.projectPath)===a&&!0===Ah(i,e))))),r||!0!==Ah(s,e)||(r=t.find((e=>"user"===e.scope))),r?.installPath&&!c.has(e)&&(l.push({pluginId:e,installPath:r.installPath}),c.add(e))}return l}var Mh=r("../../node_modules/.pnpm/js-yaml@4.3.1/node_modules/js-yaml/dist/js-yaml.mjs");const Dh=je.enum(["canvas"]),Oh=je.array(Dh).transform((e=>[...new Set(e)].sort())),Fh=new Set(["https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","https://agent-plugins.org/schemas/1.0.0/mcp.schema.json"]),Nh=/^v?(\d+\.\d+(?:\.\d+)?)$/;function Lh(e){if("object"!=typeof(t=e)||null===t||Array.isArray(t))return;var t;const r=e.$schema;return"string"==typeof r&&r.length>0?r:void 0}function jh(e){let t;try{t=new URL(e).pathname.split("/")}catch{t=e.split("/")}for(const e of t){const t=Nh.exec(e);if(null!==t)return t[1]}}function Uh(e){return void 0===e?{kind:"absent"}:Fh.has(e)?{kind:"supported",id:e,version:jh(e)??e}:{kind:"unsupported",id:e}}const Bh=10485760,Wh=/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/,Hh=[".cursor-plugin/plugin.json",".claude-plugin/plugin.json","plugin.json"],qh=[".cursor-plugin",".claude-plugin"],zh=[".cursor-plugin/marketplace.json",".claude-plugin/marketplace.json"],Gh=je.object({source:je.literal("github"),repo:je.string().regex(/^[^/]+\/[^/]+$/,"Must be in owner/repo format"),ref:je.string().optional(),sha:je.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Vh=je.object({source:je.literal("url"),url:je.string().url().endsWith(".git","URL must end with .git"),ref:je.string().optional(),sha:je.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Kh=je.object({source:je.literal("git-subdir"),url:je.string().url().endsWith(".git","URL must end with .git"),path:je.string().min(1),ref:je.string().optional(),sha:je.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Jh=je.union([je.string(),Gh,Vh,Kh]),Zh=/^(\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?|never)$/,Xh='Must be a semver version (X.Y.Z) or "never"',Qh=je.object({cursor:je.string().regex(Zh,Xh).optional(),sand:je.string().regex(Zh,Xh).optional(),sandMobile:je.string().regex(Zh,Xh).optional()}),Yh=je.object({name:je.string().min(1,"Author name is required"),email:je.string().email().optional()}),ep=je.enum(["string","number","integer","boolean","object","array","null"]),tp=je.union([ep,je.array(ep).nonempty().superRefine(((e,t)=>{new Set(e).size!==e.length&&t.addIssue({code:je.ZodIssueCode.custom,message:"Schema type arrays must not contain duplicates"})}))]);function rp(e,t){if(void 0!==e.required)if(void 0===e.properties)for(const r of e.required)t.addIssue({code:je.ZodIssueCode.custom,message:`Required property "${r}" must be declared in properties`,path:["required"]});else for(const r of e.required)r in e.properties||t.addIssue({code:je.ZodIssueCode.custom,message:`Required property "${r}" must be declared in properties`,path:["required"]});void 0!==e.minLength&&void 0!==e.maxLength&&e.minLength>e.maxLength&&t.addIssue({code:je.ZodIssueCode.custom,message:"minLength must be less than or equal to maxLength",path:["minLength"]}),void 0!==e.minimum&&void 0!==e.maximum&&e.minimum>e.maximum&&t.addIssue({code:je.ZodIssueCode.custom,message:"minimum must be less than or equal to maximum",path:["minimum"]}),void 0!==e.exclusiveMinimum&&void 0!==e.exclusiveMaximum&&e.exclusiveMinimum>=e.exclusiveMaximum&&t.addIssue({code:je.ZodIssueCode.custom,message:"exclusiveMinimum must be less than exclusiveMaximum",path:["exclusiveMinimum"]}),void 0!==e.minItems&&void 0!==e.maxItems&&e.minItems>e.maxItems&&t.addIssue({code:je.ZodIssueCode.custom,message:"minItems must be less than or equal to maxItems",path:["minItems"]}),void 0!==e.minProperties&&void 0!==e.maxProperties&&e.minProperties>e.maxProperties&&t.addIssue({code:je.ZodIssueCode.custom,message:"minProperties must be less than or equal to maxProperties",path:["minProperties"]})}const np=je.lazy((()=>je.object({type:tp.optional(),title:je.string().optional(),description:je.string().optional(),format:je.string().optional(),writeOnly:je.boolean().optional(),placeholder:je.string().optional(),default:je.unknown().optional(),enum:je.array(je.any()).nonempty().optional(),const:je.unknown().optional(),properties:je.record(je.string(),np).optional(),required:je.array(je.string()).optional(),additionalProperties:je.union([je.boolean(),np]).optional(),items:je.union([np,je.array(np)]).optional(),minLength:je.number().int().nonnegative().optional(),maxLength:je.number().int().nonnegative().optional(),minimum:je.number().optional(),maximum:je.number().optional(),exclusiveMinimum:je.number().optional(),exclusiveMaximum:je.number().optional(),multipleOf:je.number().positive().optional(),minItems:je.number().int().nonnegative().optional(),maxItems:je.number().int().nonnegative().optional(),uniqueItems:je.boolean().optional(),minProperties:je.number().int().nonnegative().optional(),maxProperties:je.number().int().nonnegative().optional()}).strict().superRefine(rp)));function op(e){const t=np.superRefine(((e,t)=>{ap(e)&&"object"===e.type||t.addIssue({code:je.ZodIssueCode.custom,message:'Plugin variable schemas must declare type "object"',path:["type"]})})).safeParse(e);return t.success?cp(t.data)?{success:!0,data:t.data}:{success:!1,error:new je.ZodError([{code:"custom",path:["type"],message:'Plugin variable schemas must declare type "object"'}])}:{success:!1,error:t.error}}const sp=je.unknown().superRefine(((e,t)=>{const r=op(e);if(!r.success)for(const e of r.error.issues)t.addIssue({code:"custom",message:e.message,path:e.path})})).transform((e=>{if(!cp(e))throw new Error('Plugin variable schema must declare type "object"');return e})),ip=(je.object({name:je.string().min(1).transform((e=>e.toLowerCase())).refine((e=>Wh.test(e)),"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:je.string().optional(),source:Jh,description:je.string().optional(),version:je.string().optional(),author:Yh.optional(),publisher:je.string().min(1).optional(),homepage:je.string().url().optional(),repository:je.string().url().optional(),license:je.string().optional(),keywords:je.array(je.string()).optional(),capabilities:Oh.optional(),logo:je.string().optional(),category:je.string().optional(),tags:je.array(je.string()).optional(),minClientVersions:Qh.optional(),strict:je.boolean().default(!0),commands:je.union([je.string(),je.array(je.string())]).optional(),agents:je.union([je.string(),je.array(je.string())]).optional(),skills:je.union([je.string(),je.array(je.string())]).optional(),rules:je.union([je.string(),je.array(je.string())]).optional(),hooks:je.union([je.string(),je.record(je.string(),je.unknown())]).optional(),variables:sp.optional(),mcpServers:je.union([je.string(),je.record(je.string(),je.unknown()),je.array(je.union([je.string(),je.record(je.string(),je.unknown())]))]).optional()}),je.object({description:je.string().optional(),version:je.string().optional(),pluginRoot:je.string().optional()}),je.object({name:je.string().min(1).regex(Wh,"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:je.string().optional(),description:je.string().optional(),version:je.string().optional(),author:Yh.optional(),publisher:je.string().min(1).optional(),homepage:je.string().url().optional(),repository:je.string().url().optional(),license:je.string().optional(),logo:je.string().optional(),keywords:je.array(je.string()).optional(),capabilities:Oh.optional(),minClientVersions:Qh.optional(),commands:je.union([je.string(),je.array(je.string())]).optional(),agents:je.union([je.string(),je.array(je.string())]).optional(),skills:je.union([je.string(),je.array(je.string())]).optional(),rules:je.union([je.string(),je.array(je.string())]).optional(),hooks:je.union([je.string(),je.record(je.string(),je.unknown())]).optional(),variables:sp.optional(),mcpServers:je.union([je.string(),je.record(je.string(),je.unknown()),je.array(je.union([je.string(),je.record(je.string(),je.unknown())]))]).optional()}));function ap(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function cp(e){return ap(e)&&"object"===e.type}function lp(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function up(e,t){if(ap(e)&&"string"==typeof e.name){const t=lp(e.name);if(t.length>0)return t}return function(e){const t=void 0!==e.repoName?lp(e.repoName):"";return t.length>0?t:`cursor-marketplace-${e.fallbackId??(0,bo.randomUUID)()}`}(t)}function dp(e){if(ap(e)&&ap(e.owner)){const t="string"==typeof e.owner.name&&e.owner.name.trim().length>0?e.owner.name:"Unknown",r="string"==typeof e.owner.email&&e.owner.email.trim().length>0?e.owner.email:void 0;return{name:t,...void 0!==r?{email:r}:{}}}return{name:"Unknown"}}function hp(e){return"string"==typeof e?e:void 0}function pp(e){if(!Array.isArray(e))return;const t=e.filter((e=>"string"==typeof e));return t.length>0?t:void 0}function fp(e){return"string"==typeof e?e:pp(e)}function mp(e){if(!ap(e)||!ap(e.metadata))return;const t={description:hp(e.metadata.description),version:hp(e.metadata.version),pluginRoot:hp(e.metadata.pluginRoot)};return void 0!==t.description||void 0!==t.version||void 0!==t.pluginRoot?t:void 0}function gp(e){if(!ap(e))return;const t=hp(e.name);if(void 0===t||0===t.length)return;const r=hp(e.email);return{name:t,...void 0!==r?{email:r}:{}}}function wp(e){if("string"==typeof e||ap(e))return e;if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e||ap(e)));return t.length>0?t:void 0}}function yp(e){if("string"==typeof e||ap(e))return e}function vp(e){if(void 0===e)return;const t=op(e);return t.success?t.data:void 0}function bp(e,t={}){if(e.length>Bh)return{success:!1,error:"Manifest exceeds maximum size of 10485760 bytes"};let r;try{r=JSON.parse(e)}catch(e){return{success:!1,error:`Invalid JSON: ${e instanceof Error?e.message:"Unknown error"}`}}if(!ap(r))return{success:!1,error:"Invalid marketplace manifest: expected a JSON object"};const n=[],o=[],i=new Set;return(Array.isArray(r.plugins)?r.plugins:[]).forEach(((e,t)=>{const r=function(e,t){if(!ap(e))return{skippedEntry:{index:t,error:`Plugin entry at index ${t} is not an object`}};const r="string"==typeof(n=e.source)?n:ap(n)?"github"===n.source&&"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:hp(n.ref),sha:hp(n.sha)}:("url"===n.source||void 0===n.source)&&"string"==typeof n.url&&n.url.length>0?{source:"url",url:n.url,ref:hp(n.ref),sha:hp(n.sha)}:"git-subdir"===n.source&&"string"==typeof n.url&&n.url.length>0&&"string"==typeof n.path&&n.path.length>0?{source:"git-subdir",url:n.url,path:n.path,ref:hp(n.ref),sha:hp(n.sha)}:"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:hp(n.ref),sha:hp(n.sha)}:void 0:void 0;var n;if(void 0===r){const r=hp(e.name);return{skippedEntry:{index:t,...void 0!==r&&r.length>0?{name:r}:{},error:`Plugin entry at index ${t} has no usable source`}}}const o=("string"==typeof e.name?lp(e.name):"")||function(e){if("string"==typeof e){const t=lp((0,s.basename)(e));return t.length>0?t:void 0}if("github"===e.source){const t=lp(e.repo.split("/").at(-1)??"");return t.length>0?t:void 0}if("git-subdir"===e.source){const t=lp((0,s.basename)(e.path));return t.length>0?t:void 0}let t=e.url;try{t=new URL(e.url).pathname}catch{}for(;t.endsWith("/");)t=t.slice(0,-1);t.toLowerCase().endsWith(".git")&&(t=t.slice(0,-4));const r=lp((0,s.basename)(t));return r.length>0?r:void 0}(r);if(void 0===o)return{skippedEntry:{index:t,error:`Plugin entry at index ${t} has no usable name`}};const i=Oh.safeParse(e.capabilities);if(void 0!==e.capabilities&&!i.success)return{skippedEntry:{index:t,name:o,error:`Plugin entry at index ${t} has invalid capabilities: ${i.error.issues.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`}};const a=i.success?i.data:void 0,c=function(e){const t=Qh.safeParse(e);if(t.success&&(void 0!==t.data.cursor||void 0!==t.data.sand||void 0!==t.data.sandMobile))return t.data}(e.minClientVersions);return{entry:{name:o,displayName:hp(e.displayName),source:r,description:hp(e.description),version:hp(e.version),author:gp(e.author),publisher:hp(e.publisher),homepage:hp(e.homepage),repository:hp(e.repository),license:hp(e.license),keywords:pp(e.keywords),logo:hp(e.logo),category:hp(e.category),tags:pp(e.tags),strict:"boolean"!=typeof e.strict||e.strict,commands:fp(e.commands),agents:fp(e.agents),skills:fp(e.skills),rules:fp(e.rules),hooks:yp(e.hooks),variables:vp(e.variables),mcpServers:wp(e.mcpServers),...void 0!==a&&{capabilities:a},...void 0!==c&&{minClientVersions:c}}}}(e,t);"skippedEntry"in r?o.push(r.skippedEntry):i.has(r.entry.name)?o.push({index:t,name:r.entry.name,error:`Duplicate plugin name "${r.entry.name}" at index ${t}`}):(i.add(r.entry.name),n.push(r.entry))})),{success:!0,data:{name:up(r,t),owner:dp(r),description:hp(r.description),plugins:n,metadata:mp(r),skippedPluginEntries:o}}}function Sp(e){if(e.length>Bh)return{success:!1,error:"Manifest exceeds maximum size of 10485760 bytes"};let t;try{t=JSON.parse(e)}catch(e){return{success:!1,error:`Invalid JSON: ${e instanceof Error?e.message:"Unknown error"}`}}const r=Uh(Lh(t)),n=ip.safeParse(t);return n.success?{success:!0,data:n.data,..."unsupported"===r.kind&&{unrecognizedSchemaId:r.id}}:{success:!1,error:`Invalid plugin manifest: ${n.error.issues.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`,details:n.error}}function kp(e,t){if("string"!=typeof e)return null;let r=e;if(r.startsWith("./")&&(r=r.slice(2)),void 0!==t){let e=t;e.startsWith("./")&&(e=e.slice(2)),e.endsWith("/")&&(e=e.slice(0,-1)),r=`${e}/${r}`}return r||"."}function _p(e){return!e.includes("..")&&!(0,s.isAbsolute)(e)&&!e.includes("://")}var Cp=r("../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js");const Ep=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g,xp=/\$%7B([^%/?#]+?)%7D/gi;function Pp(e,t){return Rp(e,"function"==typeof t?t:function(e){const t=new Map(Object.entries(e).map((([e,t])=>[e.toLowerCase(),t])));return r=>e[r]??t.get(r.toLowerCase())}(t))}function Rp(e,t){if("string"==typeof e)return function(e,t){return e.replace(xp,"${$1}").replace(Ep,((e,r,n,o)=>{if(void 0!==r)return t(r)??e;if(void 0===n)return e;const s=t(n);return void 0!==s?s:void 0!==o?o:e}))}(e,t);if(Array.isArray(e))return e.map((e=>Rp(e,t)));if(function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e)){const r={};for(const[n,o]of Object.entries(e))r[n]=Rp(o,t);return r}return e}function Ip(e,t){return e.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g,(()=>t)).replace(/\$\{CURSOR_PLUGIN_ROOT\}/g,(()=>t))}const Tp={log:()=>{},increment:()=>{},distribution:()=>{},captureException:()=>{}},Ap=je.object({command:je.string().optional(),args:je.array(je.string()).optional(),env:je.record(je.string(),je.string()).optional(),url:je.string().optional(),headers:je.record(je.string(),je.string()).optional(),cwd:je.string().optional(),envFile:je.string().optional(),auth:je.object({CLIENT_ID:je.string(),CLIENT_SECRET:je.string().optional(),scopes:je.array(je.string()).optional()}).optional(),enabledTools:je.array(je.string()).optional(),placement:je.enum(["server","client"]).optional(),tls:je.object({caBundle:je.string().trim().min(1).max(131072)}).optional()}),$p=je.object({mcpServers:je.record(je.string(),Ap).optional()}),Mp=[".mcp.json","mcp.json"],Dp=new Set(["author","owner","source","metadata"].map((e=>e.toLowerCase())));function Op(e,t){if(!function(e){return Dp.has(e.toLowerCase())}(e))return!1;if(!function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(t))return!1;const r=t;switch(e.toLowerCase()){case"author":case"owner":return"string"==typeof r.name;case"source":return"string"==typeof r.source||"string"==typeof r.repo||"string"==typeof r.path||"string"==typeof r.ref||"string"==typeof r.sha;case"metadata":return"string"==typeof r.description||"string"==typeof r.version||"string"==typeof r.pluginRoot;default:return!1}}function Fp(e){return"object"==typeof e&&null!==e&&("command"in e||"url"in e)}function Np(e){const t=void 0!==e&&e.length>0?e.replace(/\/+$/,""):void 0;return Mp.map((e=>void 0!==t?`${t}/${e}`:e))}function Lp(e,t,r){if(!e.mcpServers)return e;const n={};for(const[r,o]of Object.entries(e.mcpServers)){const e={...o};if("string"==typeof o.command&&(e.command=Ip(o.command,t)),Array.isArray(o.args)&&(e.args=o.args.map((e=>"string"==typeof e?Ip(e,t):e))),o.env&&"object"==typeof o.env){const r={};for(const[e,n]of Object.entries(o.env))r[e]="string"==typeof n?Ip(n,t):n;e.env=r}"string"==typeof o.cwd&&(e.cwd=Ip(o.cwd,t)),n[r]=e}return function(e,t){const r=t?.cloudAgentEnvLookup,n=t?.configuredVariables;if(void 0!==r)return Pp(e,r);const o=new Map(Object.keys(n??{}).map((e=>[e.toLowerCase(),e])));return Pp(e,(e=>{const t=process.env[e];if(void 0!==t)return t;const r=void 0!==n&&Object.hasOwn(n,e)?e:o.get(e.toLowerCase()),s=void 0!==r?n?.[r]:void 0;return null!=s?"string"==typeof s?s:"number"==typeof s||"boolean"==typeof s||"bigint"==typeof s?String(s):JSON.stringify(s):void 0}))}({...e,mcpServers:n},r)}function jp(e,t,r){try{const n=(0,Cp.qg)(e),o=Lh(n);if(void 0!==o){const e=r?.log??Tp;"unsupported"===Uh(o).kind?e.log("debug",`mcp.json declares an unrecognized $schema, loading anyway: ${o}`):function(e,t){if(void 0===e||void 0===t)return!1;const r=jh(e),n=jh(t);return void 0!==r&&void 0!==n&&r!==n}(r?.pluginSchemaId,o)&&e.log("debug",`mcp.json $schema ${o} disagrees with plugin.json $schema ${r?.pluginSchemaId}, loading anyway`)}const s=$p.safeParse(n),i=!0===r?.skipExpansion;if(s.success&&s.data.mcpServers&&Object.keys(s.data.mcpServers).length>0)return i?s.data:Lp(s.data,t,r);const a={};for(const[e,t]of Object.entries(n))"mcpServers"!==e&&!Op(e,t)&&Fp(t)&&(a[e]=t);if(Object.keys(a).length>0){const e=$p.safeParse({mcpServers:a});if(e.success)return i?e.data:Lp(e.data,t,r)}return null}catch{return null}}function Up(e,t,r){for(const[n,o]of Object.entries(t))e.mcpServers[n]=o,e.mcpServerSourcePaths[n]=r}async function Bp(e,t,r,n={}){const o=n.toSourcePath??(e=>e),s=n.installPathForExpansion??"",i=n.fallbackFileNames??Mp,a=n.manifestPrecedence??"override",c={},l={};for(const t of i){const r=await e(t);if(null===r)continue;const i=jp(r,s,n.parserOptions);if(i?.mcpServers)for(const[e,r]of Object.entries(i.mcpServers))void 0===c[e]&&(c[e]=r,l[e]=o(t))}if(void 0!==t){const i=await async function(e,t,r={}){const n=r.toSourcePath??(e=>e),o=r.installPathForExpansion??"",s={mcpServers:{},mcpServerSourcePaths:{}},i=async e=>{const i=e.replace(/^\.\//,"");if(!_p(i))return;const a=await t(i);if(null===a)return;const c=jp(a,o,r.parserOptions);c?.mcpServers&&Object.keys(c.mcpServers).length>0&&Up(s,c.mcpServers,n(i))},a=e=>{const t=jp(JSON.stringify(e),o,r.parserOptions);t?.mcpServers&&Object.keys(t.mcpServers).length>0&&Up(s,t.mcpServers,r.manifestSourcePath??"manifest")};if("string"==typeof e)await i(e);else if(Array.isArray(e))for(const t of e)"string"==typeof t?await i(t):"object"==typeof t&&null!==t&&a(t);else"object"==typeof e&&null!==e&&a(e);return s}(t,e,{toSourcePath:o,manifestSourcePath:r,installPathForExpansion:s,parserOptions:n.parserOptions});for(const[e,t]of Object.entries(i.mcpServers))"fill"===a&&void 0!==c[e]||(c[e]=t,l[e]=i.mcpServerSourcePaths[e])}return 0===Object.keys(c).length?null:{mcpServers:c,...Object.keys(l).length>0&&{mcpServerSourcePaths:l}}}const Wp=new Set(["CREDENTIAL","CREDENTIALS","KEY","PASSPHRASE","PASSWORD","SECRET","TOKEN"]);function Hp(e){return function(e){return e.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/[^a-z\d]+/gi,"_").toUpperCase().split("_").filter((e=>e.length>0))}(e).some((e=>Wp.has(e)))}const qp=/\$\{(?:env:([A-Z][A-Z0-9_]*)|([A-Z][A-Z0-9_]*)(?::-([^}]*))?)\}/g,zp=new Set(["CURSOR_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT"]),Gp=new Set(["api","aws","db","dd","gcp","http","https","id","mcp","ssl","tls","uri","url"]);function Vp(e){return e.split("_").filter((e=>e.length>0)).map((e=>{const t=e.toLowerCase();return Gp.has(t)?e.toUpperCase():e.charAt(0).toUpperCase()+t.slice(1)})).join(" ")}function Kp(e,t){if("string"!=typeof e){if(Array.isArray(e))for(const r of e)Kp(r,t);else if(null!==e&&"object"==typeof e)for(const r of Object.values(e))Kp(r,t)}else for(const[,r,n,o]of e.matchAll(qp)){const e=r??n;if(void 0===e||zp.has(e)||t.has(e))continue;const s=void 0===r?`\${${e}}`:`\${env:${e}}`;t.set(e,{reference:s,defaultValue:o})}}function Jp(e){if(void 0===e?.mcpServers)return;const t=new Map;if(Kp(e.mcpServers,t),0===t.size)return;const r={};for(const e of[...t.keys()].sort()){const n=t.get(e);if(void 0===n)continue;const{reference:o,defaultValue:s}=n;r[e]={type:"string",title:Vp(e),description:void 0===s||0===s.length?`Referenced as \`${o}\` in this plugin's MCP configuration.`:`Referenced as \`${o}\` in this plugin's MCP configuration. Defaults to \`${s}\` when left blank.`,...Hp(e)?{writeOnly:!0}:{}}}return{type:"object",properties:r}}const Zp=[".md",".mdc",".markdown"],Xp=[...Zp,".txt"],Qp=/^---\s*\n([\s\S]*?)\n---/;function Yp(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ef(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9.-]/g,"")}function tf(e){const t=e.match(Qp);if(!t)return{};try{const e=Mh.Ay.load(t[1],{schema:Mh.Ay.JSON_SCHEMA});if(!Yp(e))return{};const r=Yp(e.metadata)?e.metadata:void 0,n=rf(e.environments??r?.environments);return{disabledEnvironments:rf(e["disabled-environments"]??r?.disabledEnvironments),environments:n,name:"string"==typeof e.name?e.name:void 0,description:"string"==typeof e.description?e.description:void 0}}catch{const e=t[1],r=e.match(/^name:\s*(.+)$/m),n=e.match(/^description:\s*(.+)$/m);return r||n?{name:r?r[1].trim():void 0,description:n?n[1].trim():void 0}:{}}}function rf(e){if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e&&e.length>0));return 0===t.length?void 0:t}if("string"==typeof e){const t=e.split(",").map((e=>e.trim())).filter((e=>e.length>0));return 0===t.length?void 0:t}}function nf(e){return ef((0,s.basename)(e).replace(/\.(md|mdc|markdown|txt)$/i,""))}function of(e){const t=new Set,r=[];for(const n of e)t.has(n.name)||(t.add(n.name),r.push(n));return r}class sf{constructor(e){this.fetcher=e}async discoverComponents(e={}){const t=e.basePath??"",r=t?`${t}/`:"",n=e.manifest;let o;try{o=await this.fetcher.listDirectory(t)}catch{o=[]}const s=new Set(o.filter((e=>"dir"===e.type)).map((e=>e.name.toLowerCase()))),i=Mp.filter((e=>o.some((t=>"file"===t.type&&t.name===e)))),a=o.some((e=>"file"===e.type&&"SKILL.md"===e.name)),[c,l,u,d,h,p,f]=await Promise.all([a&&void 0===n?.skills?this.discoverRootSkill(r):Promise.resolve(null),void 0!==n?.skills?this.discoverFromManifestPaths(r,n.skills,!0,Zp):s.has("skills")?this.discoverSkills(`${r}skills`):Promise.resolve([]),void 0!==n?.agents?this.discoverFromManifestPaths(r,n.agents,!1,Zp):s.has("agents")?this.discoverMarkdownComponents(`${r}agents`,Zp):Promise.resolve([]),void 0!==n?.hooks?this.discoverHooksFromManifest(r,n.hooks):s.has("hooks")?this.discoverHooksFromJson(`${r}hooks/hooks.json`):Promise.resolve([]),void 0!==n?.commands?this.discoverFromManifestPaths(r,n.commands,!1,Xp):s.has("commands")?this.discoverMarkdownComponents(`${r}commands`,Xp):Promise.resolve([]),void 0!==n?.rules?this.discoverFromManifestPaths(r,n.rules,!1,Zp):s.has("rules")?this.discoverMarkdownComponents(`${r}rules`,Zp):Promise.resolve([]),this.discoverMcpServers(r,n?.mcpServers,i)]);return{skills:of(c?[c,...l]:l),agents:of(u),hooks:d,commands:of(h),rules:of(p),mcpServers:f.servers,mcpVariables:f.variables,mcpConfigs:f.configs}}async discoverHooksFromJson(e){try{if(!await this.fetcher.fileExists(e))return[];const{content:t}=await this.fetcher.fetchFile(e),r=JSON.parse(t);return Yp(r)&&Yp(r.hooks)?Object.keys(r.hooks).map((t=>({name:ef(t),path:e,description:`Hook: ${t}`}))):[]}catch{return[]}}async discoverHooksFromManifest(e,t){if("string"==typeof t){if(!_p(t))return[];const r=`${e}${t.replace(/^\.\//,"")}`;return r.endsWith(".json")?this.discoverHooksFromJson(r):this.discoverHooksFromJson(`${r}/hooks.json`)}const r=t.hooks??t;return!r||"object"!=typeof r||Array.isArray(r)?[]:Object.keys(r).map((e=>({name:ef(e),path:"manifest",description:`Hook: ${e}`})))}async discoverFromManifestPaths(e,t,r=!1,n=Zp){if("string"==typeof t){if(!_p(t))return[];const o=`${e}${t.replace(/^\.\//,"")}`.replace(/\/$/,"");return r?this.discoverSkills(o):this.discoverMarkdownComponents(o,n)}const o=[];for(const n of t)try{if(!_p(n))continue;const t=`${e}${n.replace(/^\.\//,"")}`;if(r){const e=t.endsWith("SKILL.md")?t:`${t.replace(/\/$/,"")}/SKILL.md`;if(!await this.fetcher.fileExists(e)){const e=t.replace(/\/$/,""),r=await this.discoverSkills(e);o.push(...r);continue}let r=nf(t.endsWith("SKILL.md")?t.slice(0,-8).replace(/\/$/,""):t);const{content:n}=await this.fetcher.fetchFile(e),s=tf(n);if(r=s.name??r,r){const t={disabledEnvironments:s.disabledEnvironments,environments:s.environments,name:ef(r),path:e};void 0!==s.description&&(t.description=s.description),o.push(t)}}else{if(!await this.fetcher.fileExists(t))continue;let e=nf(t);const{content:r}=await this.fetcher.fetchFile(t),n=tf(r);e=n.name??e;const s=n.description;if(e){const r={name:ef(e),path:t};void 0!==s&&(r.description=s),o.push(r)}}}catch{}return o}async discoverMarkdownComponents(e,t=Zp,r=new Set){let n;try{n=await this.fetcher.listDirectory(e,r)}catch{return[]}const o=n.filter((e=>"file"===e.type&&t.some((t=>e.name.endsWith(t))))),s=n.filter((e=>"dir"===e.type)),[i,a]=await Promise.all([Promise.all(o.map((async e=>{try{let t=nf(e.name);const{content:r}=await this.fetcher.fetchFile(e.path),n=tf(r);t=n.name?ef(n.name):t;const o=n.description;if(!t)return null;const s={name:t,path:e.path};return void 0!==o&&(s.description=o),s}catch{return null}}))),Promise.all(s.map((e=>this.discoverMarkdownComponents(e.path,t,r))))]);return[...i.filter((e=>null!==e)),...a.flat()]}async discoverRootSkill(e){try{const t=`${e}SKILL.md`;let r=ef((0,s.basename)(e.replace(/[\\/]+$/,"")));const{content:n}=await this.fetcher.fetchFile(t),o=tf(n);if(r=o.name?ef(o.name):r,!r)return null;const i={disabledEnvironments:o.disabledEnvironments,environments:o.environments,name:r,path:t};return void 0!==o.description&&(i.description=o.description),i}catch{return null}}async discoverSkills(e){let t;try{t=await this.fetcher.listDirectory(e)}catch{return[]}const r=t.filter((e=>"dir"===e.type));return(await Promise.all(r.map((async e=>{try{const t=`${e.path}/SKILL.md`;if(!await this.fetcher.fileExists(t))return null;const{content:r}=await this.fetcher.fetchFile(t),n=tf(r),o=n.name?ef(n.name):ef(e.name);if(!o)return null;const s={disabledEnvironments:n.disabledEnvironments,environments:n.environments,name:o,path:t};return void 0!==n.description&&(s.description=n.description),s}catch{return null}})))).filter((e=>null!==e))}async discoverMcpServers(e,t,r){const n=new Map,o=async t=>{const r=n.get(t);if(void 0!==r)return r;const o=this.fetcher.fetchFile(`${e}${t}`).then((({content:e})=>e)).catch((()=>null));return n.set(t,o),o},s=async n=>Bp(o,t,void 0!==t?"manifest":void 0,{fallbackFileNames:r,manifestPrecedence:n,toSourcePath:t=>`${e}${t}`,parserOptions:{skipExpansion:!0}}),i=await s("fill");if(void 0===i?.mcpServers)return{servers:[],variables:void 0,configs:void 0};const a=void 0===t?i:await s("override"),c=a?.mcpServers??i.mcpServers,l={};for(const[e,t]of Object.entries(c))l[e]=t;return{servers:Object.keys(i.mcpServers).map((e=>({name:ef(e),path:i.mcpServerSourcePaths?.[e]??"manifest"}))),variables:Jp(a??i),configs:l}}}class af extends Error{constructor(e,t){super(`Invalid Claude Code plugin identifier "${t}": ${e}`),this.raw=t,this.name="CCPluginIdentifierError"}}function cf(e){const t=e.trim();if(!t)throw new af("Empty identifier",e);const r=/^[a-zA-Z0-9_-]+$/,n=t.indexOf("@");if(n!==t.lastIndexOf("@"))throw new af("Plugin identifier cannot contain multiple @ symbols",e);if(-1===n){if(!r.test(t))throw new af("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(t.length>100)throw new af("Plugin name must be 100 characters or less",e);return{name:t,sourceType:"marketplace",marketplace:"claude-plugins-official",raw:e}}const o=t.slice(0,n).trim(),s=t.slice(n+1).trim();if(!o)throw new af("Missing plugin name before @",e);if(!s)throw new af("Missing source after @",e);if(!r.test(o))throw new af("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(o.length>100)throw new af("Plugin name must be 100 characters or less",e);if(s.startsWith("github:")){const t=s.slice(7).trim();if(!t||!/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(t))throw new af("Invalid GitHub repo format, expected 'org/repo' (e.g., 'anthropics/claude-plugins')",e);return{name:o,sourceType:"github",githubRepo:t,raw:e}}if(s.startsWith("local:")){const t=s.slice(6).trim();if(!t)throw new af("Missing path after 'local:'",e);return{name:o,sourceType:"local",localPath:t,raw:e}}if(s.startsWith("url:")){const t=s.slice(4).trim();if(!t)throw new af("Missing Git URL after 'url:'",e);try{new URL(t)}catch{throw new af("Invalid Git URL format",e)}return{name:o,sourceType:"url",gitUrl:t,raw:e}}const i=s.indexOf("#");let a,c;if(-1!==i?(a=s.slice(0,i).trim(),c=s.slice(i+1).trim()):a=s,!a)throw new af("Missing marketplace name",e);if(!r.test(a))throw new af("Marketplace name must contain only alphanumeric characters, dashes, and underscores",e);return{name:o,sourceType:"marketplace",marketplace:a,version:c,raw:e}}function lf(e){if("claude-plugin"===e.source)return e.sourceInfo.raw;if("user-local"===e.source)return`user-local:${e.sourceInfo.name}`;if("extension"===e.source){const t=e.sourceInfo;return`extension:${t.extensionId}:${t.localPath}`}const t=e.sourceInfo;return`${t.name}-${t.version}`}function uf(e){return e.sourceInfo.name}function df(e){switch(e.source){case"claude-plugin":case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplace;default:return}}function hf(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.pluginDbId;default:return}}function pf(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplaceDbId;default:return}}function ff(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function mf(e){return!!ff(e)&&(void 0===e.enabledPlugins||ff(e.enabledPlugins))}function gf(e){return JSON.parse(e)}function wf(e){const t=e??process.env.HOME??"";return(0,s.join)(t,".claude")}async function yf(e){const t={enabledPlugins:{}};let r=!1;const n=(0,s.join)(e,".claude","settings.json");try{const e=gf(await(0,Co.readFile)(n,"utf-8"));mf(e)&&e.enabledPlugins&&(Object.assign(t.enabledPlugins,e.enabledPlugins),r=!0)}catch{}const o=(0,s.join)(e,".claude","settings.local.json");try{const e=gf(await(0,Co.readFile)(o,"utf-8"));mf(e)&&e.enabledPlugins&&(Object.assign(t.enabledPlugins,e.enabledPlugins),r=!0)}catch{}return r?t:null}function vf(e,t){const r=(0,s.resolve)(e),n=(0,s.resolve)(e,t),o=(0,s.relative)(r,n);if(o.startsWith("..")||(0,s.isAbsolute)(o))throw new Error(`Invalid subPath: path traversal not allowed (${JSON.stringify(t)})`);return n}async function bf(e){try{return(await(0,Co.lstat)(e)).isSymbolicLink()}catch{return!1}}async function Sf(e){if(await bf(e))throw new Error(`Refusing to read symlink: ${e}`);return(0,Co.readFile)(e,"utf-8")}async function kf(e){if((await(0,Co.stat)(e)).size>10485760)throw new Error(`File ${e} exceeds maximum size of 10485760 bytes`)}function _f(e){const t=e instanceof Error?e.message:String(e);return/timed?\s*out/i.test(t)?"timeout":/clone|fetch|git/i.test(t)?"clone":/manifest|marketplace\.json/i.test(t)?"manifest":/parse|invalid|malformed/i.test(t)?"parse":/install|download|copy/i.test(t)?"install":"unknown"}async function Cf({installPath:e,logo:t}){const r=t?.trim();if(r&&!(0,s.isAbsolute)(r)&&!r.includes("://"))try{const t=await(0,Co.realpath)(e),n=vf(t,r),o=await(0,Co.realpath)(n);if(vf(t,o),!(await(0,Co.stat)(o)).isFile())return;return await kf(o),(0,Ed.pathToFileURL)(o).href}catch{return}}function Ef(e){const t={};return void 0!==e.version&&(t.version=e.version),void 0!==e.homepage&&(t.homepage=e.homepage),void 0!==e.repository&&(t.repository=e.repository),t}function xf(e){return void 0!==e.version||void 0!==e.homepage||void 0!==e.repository}function Pf(e,t){return Ef({version:e.version??t?.version,homepage:e.homepage??t?.homepage,repository:e.repository??t?.repository})}async function Rf(e,t,r){let n;for(const o of Hh){const i=(0,s.join)(e,o);let a;try{if(await bf(i))continue;if(!(await(0,Co.stat)(i)).isFile())continue;await kf(i),a=await Sf(i)}catch{continue}const c=Sp(a);if(!c.success)continue;const l=c.data,u=l.commands,d=l.agents,h=l.skills,p=l.rules,f=l.hooks,m=l.mcpServers,g=void 0!==u||void 0!==d||void 0!==h||void 0!==p||void 0!==f||void 0!==m,w="string"==typeof l.displayName?l.displayName:void 0,y="string"==typeof l.description?l.description:void 0,v=l.author?.name,b=await Cf({installPath:e,logo:l.logo}),S=Ef(l),k=l.variables,_=l.capabilities,C=void 0!==w||void 0!==y||void 0!==v||void 0!==b||void 0!==k||void 0!==_;if(!g&&!C&&!xf(S))continue;if(!g&&!C){n=n?{...n,fields:Pf(n.fields,S)}:{fields:S,path:i,relPath:o,unrecognizedSchemaId:c.unrecognizedSchemaId};continue}void 0!==c.unrecognizedSchemaId&&r.log("debug",`${t}: ${o} declares an unrecognized $schema, loading anyway: ${c.unrecognizedSchemaId}`);const E=Pf(S,n?.fields);return{manifestFilePath:i,...g&&{manifestOptions:{commands:u,agents:d,skills:h,rules:p,hooks:f,mcpServers:m}},...(C||xf(E))&&{metadata:{displayName:w,description:y,authorName:v,logoUrl:b,...E,variables:k,capabilities:_}}}}if(void 0!==n)return void 0!==n.unrecognizedSchemaId&&r.log("debug",`${t}: ${n.relPath} declares an unrecognized $schema, loading anyway: ${n.unrecognizedSchemaId}`),{manifestFilePath:n.path,metadata:n.fields}}async function If(e,t){const r=function(e,t){const r=new Map,n=(0,s.resolve)(e),o=(0,s.resolve)(t?.symlinkTargetRoot??n),i=(0,Co.realpath)(o).catch((()=>o));function a(e){const t=(0,s.resolve)(e);try{return vf(n,t)}catch{throw new Error(`Path escapes plugin directory: ${e}`)}}async function c(e){const t=a(e),r=await i,n=await(0,Co.realpath)(t);try{return vf(r,n)}catch{throw new Error(`Path escapes plugin directory via symlink: ${e}`)}}return{async listDirectory(t,r){const n=a(t?(0,s.join)(e,t):e);try{const e=await c(n);if(r?.has(e))return[];r?.add(e);const o=await(0,Co.readdir)(e,{withFileTypes:!0}),i=[];for(const e of o){const r=(0,s.join)(n,e.name);let o=e.isDirectory()?"dir":"file";if(e.isSymbolicLink())try{const e=await c(r);o=(await(0,Co.stat)(e)).isDirectory()?"dir":"file"}catch{continue}i.push({name:e.name,type:o,path:t?`${t}/${e.name}`:e.name})}return i}catch{return[]}},async fetchFile(t){const n=r.get(t);if(void 0!==n)return{content:n};const o=a((0,s.join)(e,t)),i=await c(o);await kf(i);const l=await(0,Co.readFile)(i,"utf-8");return r.set(t,l),{content:l}},async fileExists(t){try{const r=a((0,s.join)(e,t)),n=await c(r);return(await(0,Co.stat)(n)).isFile()}catch{return!1}}}}(e),n=new sf(r),o=await n.discoverComponents({manifest:t}),[i,a,c,l]=await Promise.all([Tf(r,o.skills,e),$f(r,o.agents,e),Mf(r,o.commands,e),Af(r,o.rules,e)]);return{skills:i,agents:a,commands:c,rules:l}}async function Tf(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Of({content:Ip(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}async function Af(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Of({content:Ip(t,r),relativePath:o.path});s&&n.push({...s,name:o.name})}catch{}return n}async function $f(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Ff({content:Ip(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}async function Mf(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Nf({content:Ip(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}function Df(e){if("string"==typeof e){const t=function(e){const t=[];let r=0,n=0;for(let o=0;o0)n--;else if(","===s&&0===n){const n=e.slice(r,o).trim();n&&t.push(n),r=o+1}}if(n>0){for(const n of e.slice(r).split(",")){const e=n.trim();e&&t.push(e)}return t}const o=e.slice(r).trim();return o&&t.push(o),t}(e);return t.length>0?t:void 0}if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e)).map((e=>e.trim())).filter(Boolean);return t.length>0?t:void 0}}function Of({content:e,relativePath:t}){try{const r=eh(e),n=t.replace(/\\/g,"/"),o=n.split("/").filter((e=>e.length>0)),s=o.length>=2?o[o.length-2]:void 0,i=o[o.length-1]??n,a=s??i.replace(/\.md$/i,""),c="string"==typeof r.data.name?r.data.name.trim():void 0,l=rf(r.data.environments??r.data.metadata?.environments),u=rf(r.data["disabled-environments"]??r.data.metadata?.disabledEnvironments);return{path:t,name:c&&c.length>0?c:a,description:"string"==typeof r.data.description?r.data.description:void 0,globs:Df(r.data.globs),alwaysApply:!0===r.data.alwaysApply,content:e,environments:l,disabledEnvironments:u}}catch{return null}}function Ff({content:e,relativePath:t}){try{const n=eh(e),o=n.content.trim();if(!o)return null;let i;"string"==typeof n.data.tools?i=n.data.tools.split(",").map((e=>e.trim())).filter(Boolean):Array.isArray(n.data.tools)&&(i=n.data.tools.map((e=>"string"==typeof e?e.trim():String(e))).filter(Boolean));const a=n.data.permissionMode??n.data.permissionmode,c=(0,s.basename)(t);return{path:t,name:"string"==typeof n.data.name?n.data.name:(0,s.basename)(c,(0,s.extname)(c)).replace(/[\s_]+/g,"-"),description:"string"==typeof n.data.description?n.data.description:void 0,tools:i,model:"string"==typeof n.data.model?n.data.model:"inherit",prompt:o,permissionMode:(r=a,"readonly"===(r??"").trim().toLowerCase()?"readonly":"default")}}catch{return null}var r}function Nf({content:e,relativePath:t}){try{const r=eh(e);let n;const o=r.data["argument-hint"];"string"==typeof o?n=o:Array.isArray(o)&&(n=`[${o.join(" ")}]`);const i=(0,s.basename)(t);return{path:t,name:"string"==typeof r.data.name?r.data.name:(0,s.basename)(i,(0,s.extname)(i)),description:"string"==typeof r.data.description?r.data.description:void 0,argumentHint:n,content:r.content.trim()}}catch{return null}}function Lf(e){if(void 0!==e)return{configuredVariables:e.configuredVariables}}async function jf(e,t,r){const n=r??Lf(t);return async function(e,t={}){const r=t.toSourcePath??(e=>e);let n,o,s;for(const t of Hh){const i=await e(t);if(null===i)continue;let a;try{a=JSON.parse(i)}catch{continue}s=Lh(a);const c=Sp(i);if(c.success){void 0!==c.data.mcpServers&&(n=c.data.mcpServers,o=r(t));break}}return Bp(e,n,o,void 0===s?t:{...t,parserOptions:{...t.parserOptions,pluginSchemaId:s}})}(function(e){return async t=>{if(!_p(t))return null;const r=(0,s.join)(e,t);try{return await bf(r)?null:(await(0,Co.stat)(r)).isFile()?(await kf(r),await Sf(r)):null}catch{return null}}}(e),{fallbackFileNames:Np(),manifestPrecedence:"override",toSourcePath:t=>(0,s.join)(e,t),installPathForExpansion:e,parserOptions:n})}async function Uf(e,t,r){const n=await jf(e,void 0,{log:r});if(n)return n;for(const n of zh){const o=(0,s.join)(e,n);try{if(!(await(0,Co.stat)(o)).isFile())continue;const n=await(0,Co.readFile)(o,"utf-8"),i=JSON.parse(n);if(!Hf(i)||!Array.isArray(i.plugins))continue;const a=i.plugins.filter(qf),c=t.name,l=a.find((e=>e.name===c));if(!l?.mcpServers?.length)continue;for(const t of l.mcpServers){const n=t.replace(/^\.\//,"");if(!_p(n))continue;const o=(0,s.join)(e,n);try{await kf(o);const t=jp(await Sf(o),e,{log:r});if(t?.mcpServers&&Object.keys(t.mcpServers).length>0){const e=Object.fromEntries(Object.keys(t.mcpServers).map((e=>[e,o])));return{...t,mcpServerSourcePaths:e}}}catch{}}return null}catch{}}return null}Error;const Bf=new Set(Object.values(xd));function Wf(e){return Bf.has(e)}function Hf(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function qf(e){return!(!Hf(e)||"string"!=typeof e.name)&&(void 0===e.mcpServers||Array.isArray(e.mcpServers)&&e.mcpServers.every((e=>"string"==typeof e)))}function zf(e,t){const r={};for(const[n,o]of Object.entries(e.hooks))Array.isArray(o)&&Wf(n)&&(r[n]=o.map((e=>"command"in e&&"string"==typeof e.command?{...e,command:Ip(e.command,t)}:"prompt"in e&&"string"==typeof e.prompt?{...e,prompt:Ip(e.prompt,t)}:e)));return{...e,hooks:r}}async function Gf(e,t,r,n,o){if("object"==typeof n){const s=Vf(n,t,r);return s&&"config"in s?{config:zf(s.config,e),...void 0!==o&&{sourcePath:o}}:s}let i,a,c;if("string"==typeof n){const t=n.replace(/^\.\//,"");if(!_p(t))return;i=t.endsWith(".json")?(0,s.join)(e,t):(0,s.join)(e,t,"hooks.json")}else i=(0,s.join)(e,"hooks","hooks.json");try{if(await bf(i))return;if(!(await(0,Co.stat)(i)).isFile())return}catch{return}try{await kf(i),a=await(0,Co.readFile)(i,"utf-8")}catch{return}try{c=JSON.parse(a)}catch{return{error:{source:"claude-plugin",message:`Plugin ${t} ${i}: invalid JSON`}}}const l=Vf(c,t,r);return l&&"config"in l?{config:zf(l.config,e),sourcePath:i}:l}function Vf(e,t,r){const n=function(e){if(!Id(e))return"unknown";const t=e,r="object"==typeof t.hooks&&null!==t.hooks?t.hooks:null;if(!r)return"unknown";for(const e of Object.values(r)){if(!Array.isArray(e)||0===e.length)continue;const t=e[0];if(Id(t)){if("hooks"in t&&Array.isArray(t.hooks))return"claude-code";if("command"in t||"prompt"in t||"type"in t)return"cursor"}}return"unknown"}(e);if("cursor"===n){const r=Dd(e);return r.isValid&&Dd(e).isValid?{config:e}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${r.errors.join("; ")}`}}}if("claude-code"===n){if(!(Hf(o=e)&&Hf(o.hooks)&&Object.keys(o.hooks).length>0))return;const n=Xd(e.hooks,{warn:e=>r.log("warn",`Plugin ${t} hooks: ${e}`),info:e=>r.log("info",`Plugin ${t} hooks: ${e}`)}),s=Dd(n);return s.isValid?{config:n}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${s.errors.join("; ")}`}}}var o}async function Kf(e,t,r,n){const o=n?.log??Tp,s=await Rf(e,t,o),i={...Lf(r)??(n?.configuredVariables?{configuredVariables:n.configuredVariables}:void 0),log:o},[a,c,l]=await Promise.all([If(e,s?.manifestOptions),jf(e,r,i),Gf(e,t,o,s?.manifestOptions?.hooks,s?.manifestFilePath)]);return{...a,...void 0!==s?.metadata?.displayName&&{displayName:s.metadata.displayName},...void 0!==s?.metadata?.description&&{description:s.metadata.description},...void 0!==s?.metadata?.authorName&&{authorName:s.metadata.authorName},...void 0!==s?.metadata?.logoUrl&&{logoUrl:s.metadata.logoUrl},...void 0!==s?.metadata?.version&&{version:s.metadata.version},...void 0!==s?.metadata?.homepage&&{homepage:s.metadata.homepage},...void 0!==s?.metadata?.repository&&{repository:s.metadata.repository},variablesSchema:s?.metadata?.variables,mcpConfig:c,capabilities:s?.metadata?.capabilities??[],hooks:l}}async function Jf(e,t,r){const n=r?.log??Tp,o=await Rf(e,t.raw,n),[s,i,a]=await Promise.all([If(e,o?.manifestOptions),Uf(e,t,n),Gf(e,t.raw,n,o?.manifestOptions?.hooks,o?.manifestFilePath)]);return{identifier:{source:"claude-plugin",sourceInfo:t},installPath:e,...void 0!==o?.metadata?.displayName&&{displayName:o.metadata.displayName},...void 0!==o?.metadata?.description&&{description:o.metadata.description},...void 0!==o?.metadata?.authorName&&{authorName:o.metadata.authorName},...void 0!==o?.metadata?.logoUrl&&{logoUrl:o.metadata.logoUrl},...void 0!==o?.metadata?.version&&{version:o.metadata.version},...void 0!==o?.metadata?.homepage&&{homepage:o.metadata.homepage},...void 0!==o?.metadata?.repository&&{repository:o.metadata.repository},...s,mcpConfig:i??void 0,capabilities:o?.metadata?.capabilities??[],hooks:a}}async function Zf(e,t,r,n){const o=`${r.name}@${r.version}`,{displayName:s,description:i,authorName:a,logoUrl:c,version:l,homepage:u,repository:d,variablesSchema:h,skills:p,rules:f,agents:m,commands:g,mcpConfig:w,capabilities:y,hooks:v}=await Kf(e,o,r,{log:n?.log});return{identifier:{source:t,sourceInfo:r},installPath:e,...void 0!==s&&{displayName:s},...void 0!==i&&{description:i},...void 0!==a&&{authorName:a},...void 0!==c&&{logoUrl:c},...void 0!==l&&{version:l},...void 0!==u&&{homepage:u},...void 0!==d&&{repository:d},variablesSchema:h,skills:p,rules:f,agents:m,commands:g,mcpConfig:w??void 0,capabilities:y,hooks:v}}async function Xf(e,t,r={}){const n=r.log??Tp,o=performance.now(),i=await async function(e){const t=wf(e),r=(0,s.join)(t,"plugins","installed_plugins.json");try{const e=gf(await(0,Co.readFile)(r,"utf-8"));return ff(n=e)&&ff(n.plugins)?e:null}catch{return null}var n}(r.userHomeDir);if(!i?.plugins)return n.log("info",`loadAllEnabledPlugins: no installed plugins metadata found (${(performance.now()-o).toFixed(1)}ms)`),[];const a=await async function(e){const t=wf(e),r=(0,s.join)(t,"settings.json");try{const e=gf(await(0,Co.readFile)(r,"utf-8"));return mf(e)?e:null}catch{return null}}(r.userHomeDir),c=function(e){if(void 0===e)return[];const t="string"==typeof e?[e]:e,r=new Set,n=[];for(const e of t){if(!e)continue;const t=(0,s.resolve)(e);r.has(t)||(r.add(t),n.push(t))}return n}(e),l=function(e,t,r){if(0===r.length)return $h(e,t,null,void 0);const n=new Set;for(const{settings:e}of r)for(const[t,r]of Object.entries(e?.enabledPlugins??{}))!1===r&&n.add(t);const o=new Set,s=[];for(const{workspacePath:i,settings:a}of r){const r=$h(e,t,a,i);for(const e of r)o.has(e.pluginId)||n.has(e.pluginId)||(o.add(e.pluginId),s.push(e))}return s}(i,a,await(0,Or.PH)(c,(async e=>({workspacePath:e,settings:await yf(e)})),{max:8})),u=[],d=r.onError;for(const{pluginId:e,installPath:t}of l)try{const r=performance.now(),o=cf(e),s=await Jf(t,o,{log:n});u.push(s),n.log("info",`loadClaudePlugin ${e} loaded in ${(performance.now()-r).toFixed(1)}ms`)}catch(t){const r=t instanceof Error?t:new Error(String(t));if(d)try{d(cf(e),r)}catch{d({name:e.split("@")[0]??e,sourceType:"marketplace",marketplace:"unknown",raw:e},r)}}return n.log("info",`loadAllEnabledPlugins completed in ${(performance.now()-o).toFixed(1)}ms (${l.length} resolved, ${u.length} loaded)`),u}const Qf=new Map;async function Yf(e){const{entry:t,slug:r,cacheManager:n}=e;if(void 0===t.backendContent&&!Eh(t.downloadUrl))return em(e);const o=n.getCacheDir({marketplaceSlug:r,pluginId:t.pluginId,version:t.version}),s=Qf.get(o);if(void 0!==s)return s;const i=em(e).finally((()=>{Qf.delete(o)}));return Qf.set(o,i),i}async function em(e){const{entry:t,slug:r,client:n,cacheManager:o,pluginLogger:s}=e;if(await o.isCached({marketplaceSlug:r,pluginId:t.pluginId,version:t.version})){const e=o.getCacheDir({marketplaceSlug:r,pluginId:t.pluginId,version:t.version});return s.log("info",`loadFromMarketplaceSource: Found cached plugin: ${t.pluginId} at ${e}`,{marketplaceSlug:r,pluginId:t.pluginId,gitRef:t.version,marketplaceId:t.marketplace?.id}),e}const i=o.getCacheDir({marketplaceSlug:r,pluginId:t.pluginId,version:t.version});s.log("info",`loadFromMarketplaceSource: Plugin missing from cache, installing: ${t.pluginId} at ${i}`,{marketplaceSlug:r,pluginId:t.pluginId,gitRef:t.version,marketplaceId:t.marketplace?.id}),await(0,Co.mkdir)(i,{recursive:!0});try{await n.installPlugin(t,i),await o.markCacheComplete({marketplaceSlug:r,pluginId:t.pluginId,version:t.version})}catch(e){try{await(0,Co.rm)(i,{recursive:!0,force:!0})}catch{}throw e}return i}async function tm(e){const{error:t,entry:r,slug:n,client:o,cacheManager:s,pluginLogger:i}=e;if(!kh(t))return;if("revision_superseded"===t.reason){const t=await(o.relistPlugin?.(r).catch((()=>{})));if(void 0!==t)try{return{entry:t,installPath:await Yf({...e,entry:t})}}catch(e){if(!kh(e))throw e}}const a=await async function(e){const{cacheManager:t,marketplaceSlug:r,pluginId:n,exceptVersion:o}=e,s=oh(vh),i=await t.listCachedVersions({marketplaceSlug:r,pluginId:n});let a;for(const e of i){if(!e.startsWith(s))continue;const i=xh(e.slice(s.length));if(i===o)continue;const c=uh({parent:t.getCacheDir({marketplaceSlug:r,pluginId:n,version:i}),name:ch}),l=await(0,Co.stat)(c).then((e=>e.mtimeMs),(()=>{}));void 0!==l&&(void 0===a||l>a.installedAtMs)&&(a={version:i,installedAtMs:l})}return a?.version}({cacheManager:s,marketplaceSlug:n,pluginId:r.pluginId,exceptVersion:r.version});return void 0!==a?(i.log("warn",`Plugin ${r.pluginId} keeps its installed version until the listed one can be downloaded`,{pluginId:r.pluginId,reason:t.reason}),{entry:{...r,version:a},installPath:s.getCacheDir({marketplaceSlug:n,pluginId:r.pluginId,version:a})}):void 0}async function rm(e){const t=e.log??Tp,r=performance.now(),{client:n,userId:o,teamId:s,onCursorError:i,pruneOldVersions:a,pluginFilter:c,onPluginsListed:l}=e,u=[],d=e.cacheManager??new hh(e.userHomeDir),h=performance.now();let p;try{p=await n.listEnabledPlugins(o,s)}catch(e){return t.captureException(e,{error_type:"list_enabled_plugins"}),t.increment("marketplace.source_unavailable",1),t.log("error",`marketplace listEnabledPlugins failed after ${(performance.now()-h).toFixed(1)}ms; treating source as unavailable: ${e instanceof Error?e.message:String(e)}`),{plugins:[],failures:[],sourceUnavailable:!0}}t.log("info",`marketplace listEnabledPlugins completed in ${(performance.now()-h).toFixed(1)}ms (${p.plugins.length} plugins)`),l&&await l(p.plugins);const f=[];if(p.listFailures){u.push(...p.listFailures);for(const e of p.listFailures)f.push({identifier:{source:e.marketplaceName&&"cursor-public"!==e.marketplaceName?"cursor-third-party":"cursor-first-party",sourceInfo:{name:e.pluginName,version:"",...void 0!==e.pluginDbId&&{pluginDbId:e.pluginDbId},marketplace:e.marketplaceName}},installPath:"",loadError:e.errorMessage,skills:[],rules:[],agents:[],commands:[],capabilities:[]})}const m=new Map;for(const e of p.plugins){if(c&&!c(e))continue;let r=e;try{const e=r.marketplace?.name;if(!e){const e=new Error(`Plugin ${r.name} has no marketplace metadata — cannot determine cache path`);u.push({pluginName:r.name,pluginId:r.pluginId,marketplaceName:void 0,errorMessage:e.message,errorType:"manifest"}),i&&i(r,e);continue}const o=`${e}/${r.pluginId}`;let s,a=m.get(o);a||(a={slug:e,pluginId:r.pluginId,versions:[]},m.set(o,a)),a.versions.push(r.version);try{s=await Yf({entry:r,slug:e,client:n,cacheManager:d,pluginLogger:t})}catch(o){const i=await tm({error:o,entry:r,slug:e,client:n,cacheManager:d,pluginLogger:t});if(void 0===i)throw o;({entry:r,installPath:s}=i),a.versions.push(r.version)}const c=r.marketplace?.name,l=void 0!==c&&"cursor-public"!==c&&c.length>0?"cursor-third-party":"cursor-first-party",h={name:r.name,version:r.version,pluginDbId:r.pluginDbId,configuredVariables:r.configuredVariables,marketplace:c,marketplaceDbId:r.marketplaceDbId,isTeamRequired:r.isTeamRequired},p=await Zf(s,l,h,{log:t});f.push(p);try{await d.pruneOldVersions({marketplaceSlug:e,pluginId:r.pluginId,keepVersions:[r.version]})}catch{}}catch(e){t.captureException(e,{error_type:"load_plugin_from_marketplace"});const n=e instanceof Error?e:new Error(String(e));u.push({pluginName:r.name,pluginId:r.pluginId,marketplaceName:r.marketplace?.name,errorMessage:n.message,errorType:_f(n)});const o=r.marketplace?.name,s=void 0!==o&&"cursor-public"!==o&&o.length>0;f.push({identifier:{source:s?"cursor-third-party":"cursor-first-party",sourceInfo:{name:r.name,version:r.version,pluginDbId:r.pluginDbId,marketplace:o,marketplaceDbId:r.marketplaceDbId,isTeamRequired:r.isTeamRequired}},installPath:"",loadError:n.message||"Plugin load failed",skills:[],rules:[],agents:[],commands:[],capabilities:[]}),i&&i(r,n)}}if(a)for(const{slug:e,pluginId:t,versions:r}of m.values())try{await d.pruneOldVersions({marketplaceSlug:e,pluginId:t,keepVersions:r})}catch{}return t.log("info",`loadFromMarketplaceSource completed in ${(performance.now()-r).toFixed(1)}ms (${f.length} plugins loaded, ${u.length} failures)`),{plugins:f,failures:u,sourceUnavailable:!1}}function nm(e){const{identifier:t}=e;switch(t.source){case"claude-plugin":return"marketplace"===t.sourceInfo.sourceType&&t.sourceInfo.marketplace?`${t.sourceInfo.marketplace}/${t.sourceInfo.name}`:void 0;case"cursor-first-party":case"cursor-third-party":return t.sourceInfo.marketplace?`${t.sourceInfo.marketplace}/${t.sourceInfo.name}`:void 0;default:return}}function om(e){return nm(e)??`path:${e.installPath}`}function sm(e,t={}){return{...e,model:t.stripModel?void 0:e.model,tools:t.stripTools?void 0:e.tools}}function im(e,t){const r=[];for(const o of e){const e=lf(o.identifier),i=`plugin:${e}`,a=uf(o.identifier),c=df(o.identifier),l=hf(o.identifier),u=pf(o.identifier);for(const d of t(o)){const t=(0,s.join)(o.installPath,d.path),{type:h,globs:p,description:f}=(n=d).alwaysApply?{type:"global"}:n.globs&&n.globs.length>0?{type:"fileGlobbed",globs:n.globs}:n.description?{type:"agentFetched",description:n.description}:{type:"manuallyAttached"};r.push({fullPath:t,content:d.content,type:h,globs:p,description:f,pluginIdentifier:e,gitRemoteOrigin:i,plugin:a,marketplace:c,pluginId:l,marketplaceId:u,environments:d.environments,disabledEnvironments:d.disabledEnvironments})}}var n;return r}var am=r("../proto/dist/generated/agent/v1/agent_skills_pb.js");const cm=(0,zs.debuglog)("agent-skills-catalog-cache");function lm(e){return(0,bo.createHash)("sha256").update(JSON.stringify({v:1,...e})).digest("hex")}async function um(e){try{return(await(0,Co.stat)(e)).mtimeMs}catch{return}}function dm(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const hm=[".kits","cursor-pages"],pm={configDir:".cursor",subdir:"skills-cursor",thirdParty:!1,builtin:!0},fm=[{configDir:".cursor",subdir:"skills",thirdParty:!1,builtin:!1},{configDir:".claude",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".codex",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".grok",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".agents",subdir:"skills",thirdParty:!1,builtin:!1},pm],mm=(new Set(fm.map((e=>e.configDir))),new Set(["imagegen","openai-docs","opneai-docs","plugin-creator","skill-creator","skill-installer"]));function gm(e){return e.replace(/\\/g,"/").split("/").filter(Boolean)}function wm(e){const t=gm(e);if(function(e){const t=e.findIndex(((t,r)=>function(e,t){return fm.some((r=>r.configDir===e&&r.subdir===t))}(t,e[r+1])));return-1!==t&&e.slice(t+2).some((e=>e.startsWith(".")))}(t))return!0;const r=t.lastIndexOf(".codex");if(-1===r||"skills"!==t[r+1])return!1;const n=t.at(-1),o="SKILL.md"===n?t.at(-2):n;return void 0!==o&&mm.has(o)}function ym(e){return{dirPath:(0,s.join)(e,pm.configDir,pm.subdir),scope:"builtin",source:"builtin"}}const vm="canvas";function bm(e,t){return{dirPath:(0,s.join)(ym(e).dirPath,...hm),scope:"builtin",source:"builtin"}}function Sm(e,t){const r=e.replace(/\\/g,"/"),n=t.replace(/\\/g,"/").replace(/\/+$/,"");if(r.startsWith(`${n}/`))return gm(r.slice(n.length+1))}function km(e,t){const r=Sm(e,t);return void 0!==r&&!r.some((e=>e.startsWith(".")))}function _m(e){return fm.filter((t=>!t.builtin&&(e||!t.thirdParty)))}function Cm(e,t){return _m(t).map((t=>({dirPath:(0,s.join)(e,t.configDir,t.subdir),scope:"project",source:"workspace"})))}function Em(e,t){return _m(t).map((t=>({dirPath:(0,s.join)(e,t.configDir,t.subdir),scope:"user",source:"user"})))}var xm=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function Pm(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const Rm=fm.map((({configDir:e,subdir:t,thirdParty:r})=>({pattern:new RegExp(`[/\\\\]${Pm(e)}[/\\\\]${Pm(t)}[/\\\\]`,"i"),requiresThirdParty:r}))),Im=/[/\\]\.cursor[/\\]rules[/\\]/i,Tm=[{pattern:/[/\\]\.cursor[/\\]agents[/\\]/i,requiresThirdParty:!1},{pattern:/[/\\]\.claude[/\\]agents[/\\]/i,requiresThirdParty:!0}],Am=new Set(["AGENTS.md","CLAUDE.md","CLAUDE.local.md"]);function $m(e,t){const r=e.replace(/\\/g,"/"),n=(0,s.basename)(r);if(Am.has(n))return"AGENTS.md"===n||t&&("CLAUDE.md"===n||"CLAUDE.local.md"===n)?"markdown":void 0;if(Im.test(r)&&n.endsWith(".mdc"))return"rules";if("SKILL.md"===n)for(const{pattern:e,requiresThirdParty:n}of Rm)if(e.test(r)){if(n&&!t)continue;return"skills"}if(n.endsWith(".md"))for(const{pattern:e,requiresThirdParty:n}of Tm)if(e.test(r)){if(n&&!t)continue;return"agents"}}class Mm{constructor(e,t,r,n){this.root=e,this.gitExecutor=t,this.userHomeDirectory=r,this.getThirdPartyExtensibilityEnabled=n}static getRipwalkCache(){return Mm.ripwalkCache??=new Sa,Mm.ripwalkCache}async discover(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,$.VI)(e.withName("NestedExtensibilityService.discover")),!1),n={rules:[],skills:[],markdown:[],agents:[]},o=(0,s.resolve)(this.root),i=(0,s.resolve)(this.userHomeDirectory);if(o===i||Hs(o,{platform:process.platform,homeDirectory:i}).length>0)return r.span.setAttribute("nested_extensibility.rules",0),r.span.setAttribute("nested_extensibility.skills",0),r.span.setAttribute("nested_extensibility.markdown",0),r.span.setAttribute("nested_extensibility.agents",0),n;if(!await Ya(e,this.gitExecutor,(0,s.resolve)(this.root)))return r.span.setAttribute("nested_extensibility.rules",0),r.span.setAttribute("nested_extensibility.skills",0),r.span.setAttribute("nested_extensibility.markdown",0),r.span.setAttribute("nested_extensibility.agents",0),n;const a=this.getThirdPartyExtensibilityEnabled(),c=this.buildIncludeGlobs(a),l={root:this.root,includeGlobs:c,excludeGlobs:lc,followSymlinks:!0,source:"nested_extensibility"},u={rules:[],skills:[],markdown:[],agents:[]},d=Mm.getRipwalkCache();try{const e=d.walk(r.ctx,l);try{for await(const t of e.lines){const e=$m(t,a);e&&u[e].push((0,s.resolve)(this.root,t))}}finally{d.delete(l)}}catch{}return r.span.setAttribute("nested_extensibility.rules",u.rules.length),r.span.setAttribute("nested_extensibility.skills",u.skills.length),r.span.setAttribute("nested_extensibility.markdown",u.markdown.length),r.span.setAttribute("nested_extensibility.agents",u.agents.length),u}catch(e){t.error=e,t.hasError=!0}finally{xm(t)}}buildIncludeGlobs(e){const t=["*/**/.cursor/**","*/**/.agents/**","*/**/AGENTS.md"];return e&&t.push("*/**/.claude/**","*/**/.codex/**","*/**/.grok/**","*/**/CLAUDE.md","*/**/CLAUDE.local.md"),t}}const Dm=new Set(["node_modules","__pycache__","dist","build"]);async function Om({rootDir:e,includeFile:t,maxDepth:r=10,containmentRootDir:n}){const o=[],i=[{dir:e,depth:0}],a=new Set,c=void 0!==n?await(0,Co.realpath)(n):null,l=e=>{if(null===c)return!0;const t=(0,s.relative)(c,e);return""===t||!t.startsWith("..")&&!(0,s.isAbsolute)(t)};for(;i.length>0;){const e=i.pop();if(void 0===e)continue;const{dir:n,depth:c}=e;if(c>r)continue;try{const e=await(0,Co.realpath)(n);if(!l(e))continue;if(a.has(e))continue;a.add(e)}catch{continue}const d=await(0,Co.readdir)(n,{withFileTypes:!0,encoding:"utf8"}).catch((()=>null));if(null!==d)for(const e of d){const r=(0,s.join)(n,e.name);let a=e.isDirectory(),l=e.isFile();if(e.isSymbolicLink())try{const e=await(0,Co.stat)(r);a=e.isDirectory(),l=e.isFile()}catch{continue}if(a){if((u=e.name).startsWith(".")||Dm.has(u))continue;i.push({dir:r,depth:c+1})}else l&&t(e.name)&&o.push(r)}}var u;return o.sort(((e,t)=>e.localeCompare(t))),o}const Fm={agentStoreSkillsDirs:[],userHomeDirectory:""};function Nm(e){const t=e.replace(/\\/g,"/");return t.endsWith("/")?t.slice(0,-1):t}function Lm(e,t){const r=Nm(t.userHomeDirectory),n=e.replace(/\\/g,"/");if(r.length>0)for(const e of t.agentStoreSkillsDirs){const t=Nm(e);if(t.length>0&&n.startsWith(`${t}/`))return{key:`${r}::skills/${n.slice(t.length+1)}`,inAgentStore:!0}}return{key:jm(e),inAgentStore:!1}}function jm(e){const t=e.replace(/\\/g,"/"),r=t.toLowerCase(),n=r.indexOf("/.cursor/"),o=r.indexOf("/.claude/"),s=r.indexOf("/.codex/"),i=r.indexOf("/.grok/"),a=r.indexOf("/.agents/");return-1!==n?`${t.slice(0,n)}::${t.slice(n+9)}`:-1!==o?`${t.slice(0,o)}::${t.slice(o+9)}`:-1!==s?`${t.slice(0,s)}::${t.slice(s+8)}`:-1!==i?`${t.slice(0,i)}::${t.slice(i+7)}`:-1!==a?`${t.slice(0,a)}::${t.slice(a+9)}`:e}function Um(e,t){const r=new Map,n=[];for(const o of e){const{key:e,inAgentStore:s}=Lm(o.fullPath,t),i=r.get(e);void 0!==i?s&&!n[i].inAgentStore&&(n[i]={item:o,inAgentStore:s}):(r.set(e,n.length),n.push({item:o,inAgentStore:s}))}return n.map((e=>e.item))}var Bm=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Wm=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Hm=(0,l.h)("local-exec:cursor-rules");function qm(e){return"/"===e||"\\"===e}function zm(e){return e.split(/[\\/]+/).filter((e=>e.length>0)).length}async function Gm(e){return await Om({rootDir:e,includeFile:e=>"SKILL.md"===e})}async function Vm(e){let t;try{t=await ji(e)}catch(t){return{skillFilePath:e,error:bd(t)}}try{return{skillFilePath:e,content:t,parsed:eh(t)}}catch(t){return{skillFilePath:e,error:Sd(t)}}}async function Km(e){const t=await ts(e);return{...await Vm(e),realSkillFilePath:t}}function Jm(e){return Qm(e.data?.environments??e.data?.metadata?.environments)??[]}function Zm(e){return Qm(e.data?.["disabled-environments"]??e.data?.metadata?.disabledEnvironments)??[]}function Xm(e){return Qm(e.data?.metadata?.scopedTo??e.data?.["metadata.scopedTo"])??[]}function Qm(e){if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e&&e.length>0));return 0===t.length?void 0:t}if("string"==typeof e){const t=e.split(",").map((e=>e.trim())).filter((e=>e.length>0));return 0===t.length?void 0:t}}function Ym(e,t,r){const n=function(e){const t=e.data?.metadata?.surfaces;return Array.isArray(t)?t:"string"==typeof t?t.split(",").map((e=>e.trim())).filter(Boolean):[]}(e);return n.length>0&&!n.includes(t)&&!r.includes(e.data?.name)}function eg(e){return Vo(e,1536)}function tg(e){return!0===e.data?.alwaysApply}function rg(e){return!0===e.data?.["disable-model-invocation"]}function ng({skillFilePath:e,content:t,parsed:r}){const n=function(e){return function(e){const t=(e.matter??"").trim(),r=e.language?.toLowerCase();return t.length>0&&"js"!==r&&"javascript"!==r?`---\n${t}\n---`:th("",e.data??{}).trim()}(e)}(r),o=function({fullPath:e,name:t,description:r,body:n}){const o=[],s=function(e){const t=e.replace(/\\/g,"/").split("/"),r=t[t.length-1]??"";return"SKILL.md"===r&&t.length>=2?t[t.length-2]??"":r}(e);s.length>64&&o.push(`Name is ${Cd(s.length)} characters; the limit is 64. Rename the skill's folder.`),_d.test(s)||o.push('Name should be lowercase letters and numbers joined by single hyphens, like "pdf-helper". Rename the skill\'s folder.'),void 0!==t&&t!==s&&o.push(`Frontmatter name ${JSON.stringify(t)} doesn't match the folder name ${JSON.stringify(s)}, which is the name the skill goes by. Make them the same.`);const i=r?.trim().length??0;i>1024&&o.push(`Description is ${Cd(i)} characters; the limit is ${Cd(1024)}.`);const a=Math.round(n.length/4);return a>5e3&&o.push(`Body is about ${Cd(a)} tokens; the recommended limit is ${Cd(5e3)}. Move details into reference files that SKILL.md links to.`),o}({fullPath:e,name:"string"==typeof r.data?.name?r.data.name:void 0,description:"string"==typeof r.data?.description?r.data.description:void 0,body:r.content});if(tg(r))return new Vr.DX({fullPath:e,content:t,frontmatter:n,type:new Vr.f5({type:{case:"global",value:new Vr.i9}}),environments:Jm(r),disabledEnvironments:Zm(r),scopedTo:Xm(r),warnings:o});const s="string"==typeof r.data?.description?eg(r.data.description):void 0,i=kd(s,rg(r));return i?new Vr.DX({fullPath:e,parseError:i,frontmatter:n,scopedTo:Xm(r),type:new Vr.f5({type:{case:"agentFetched",value:new Vr.Xo}})}):new Vr.DX({fullPath:e,content:t,frontmatter:n,type:new Vr.f5({type:{case:"agentFetched",value:new Vr.Xo({description:s})}}),environments:Jm(r),disabledEnvironments:Zm(r),scopedTo:Xm(r),warnings:o})}function og({skillFilePath:e,content:t,parsed:r}){const n="string"==typeof r.data?.description?eg(r.data.description):"",o=Df(r.data?.paths??r.data?.globs),s=rg(r);return new am.N({fullPath:e,content:t,description:n,globs:o??[],parseError:kd(n,s),environments:Jm(r),disabledEnvironments:Zm(r),scopedTo:Xm(r),disableModelInvocation:s})}function sg({rules:e,agentSkills:t,skillFilePath:r,errorMessage:n}){e.push(function({skillFilePath:e,errorMessage:t}){return new Vr.DX({fullPath:e,parseError:t,type:new Vr.f5({type:{case:"agentFetched",value:new Vr.Xo}})})}({skillFilePath:r,errorMessage:n})),t.push(function({skillFilePath:e,errorMessage:t}){return new am.N({fullPath:e,parseError:t})}({skillFilePath:r,errorMessage:n}))}function ig(e,t,r,n){if("error"in t)return e.realSkillFilePathsByFullPath.set(t.skillFilePath,t.realSkillFilePath),void sg({rules:e.rules,agentSkills:e.agentSkills,skillFilePath:t.skillFilePath,errorMessage:t.error});Ym(t.parsed,r,n)||(e.realSkillFilePathsByFullPath.set(t.skillFilePath,t.realSkillFilePath),e.rules.push(ng(t)),tg(t.parsed)||e.agentSkills.push(og(t)))}const ag=(0,zs.debuglog)("cursor-rules-service");function cg(){return{rules:[],agentSkills:[],realSkillFilePathsByFullPath:new Map}}function lg(e){return t=>(ag("%s: %O",e,t),cg())}function ug(e,t){return lm({kind:"agent-store",surface:e,roots:[...t].sort()})}function dg(e,t){const r=t.replace(/\\/g,"/").replace(/\/+$/,"");return""!==r&&e.replace(/\\/g,"/").startsWith(`${r}/`)}function hg(e){let t;if(!0===e.frontmatter.alwaysApply)t={case:"global",value:new Vr.i9};else{const r=Df(e.frontmatter.globs);t=r&&r.length>0?{case:"fileGlobbed",value:new Vr.uT({globs:r})}:"string"==typeof e.frontmatter.description&&e.frontmatter.description.trim().length>0?{case:"agentFetched",value:new Vr.Xo({description:eg(e.frontmatter.description)})}:{case:"manuallyAttached",value:new Vr._u}}const r=e.frontmatter["metadata.environments"],n=Array.isArray(r)?r:[],o=e.frontmatter["metadata.disabledEnvironments"],s=Array.isArray(o)?o:[],i=e.frontmatter["metadata.scopedTo"],a=Array.isArray(i)?i:[];return new Vr.DX({fullPath:e.path,content:e.body,type:new Vr.f5({type:t}),environments:n,disabledEnvironments:s,scopedTo:a,frontmatter:e.rawFrontmatter??""})}class pg{constructor(e,t){this.cursorRulesServices=e,this.getAgentStoreSkillsContext=t,this.onChangeCallbacks=new Set}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Bm(t,(0,$.VI)(e.withName("MergedCursorRulesService.getAllCursorRules")),!1),n=this.cursorRulesServices.map((e=>e.getAllCursorRules(r.ctx).catch((e=>((0,zs.debuglog)("Failed to load cursor rules from service:",e),[])))));return Um((await Promise.all(n)).flat(),this.getAgentStoreSkillsContext())}catch(e){t.error=e,t.hasError=!0}finally{Wm(t)}}reload(e){for(const t of this.cursorRulesServices)t.reload(e)}scheduleDidChangeRules(){void 0===this.changeTimer&&(this.changeTimer=setTimeout((()=>{this.changeTimer=void 0;for(const e of Array.from(this.onChangeCallbacks))e()}),pg.CHANGE_COALESCE_MS))}ensureChangeListenersRegistered(){void 0===this.disposeChangeListeners&&(this.disposeChangeListeners=this.cursorRulesServices.map((e=>e.onDidChangeRules((()=>this.scheduleDidChangeRules())))))}disposeChangeListenersIfUnused(){if(!(this.onChangeCallbacks.size>0||void 0===this.disposeChangeListeners)){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0,void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0)}}onDidChangeRules(e){return this.onChangeCallbacks.add(e),this.ensureChangeListenersRegistered(),()=>{this.onChangeCallbacks.delete(e),this.disposeChangeListenersIfUnused()}}dispose(){if(void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0),this.onChangeCallbacks.clear(),void 0!==this.disposeChangeListeners){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0}for(const e of this.cursorRulesServices)e.dispose&&e.dispose()}}pg.CHANGE_COALESCE_MS=1e3;class fg{constructor(e,t,r,n,i,a,c,l){this.gitExecutor=t,this.rootDirectory=r,this.loadNestedRules=n,this.getThirdPartyExtensibilityEnabled=i,this.loadTraceId=void 0,this.onChangeCallbacks=new Set,this.nestedExtensibilityService=new Mm(r,t,(0,o.homedir)(),i),this.ignoreService=c??new xc(t,void 0,[this.rootDirectory]);const u=performance.now();if(this._rules=this.load(e,l).then((t=>{try{Hm.info(e,"LocalCursorRulesService load completed",{durationMs:Math.round(performance.now()-u),ruleCount:t.length})}catch{}return t})).catch((e=>((0,zs.debuglog)("Failed to load cursor rules:",e),[]))),a){const e=[".cursor/rules/**/*.mdc","AGENTS.md","CLAUDE.md","CLAUDE.local.md",".cursorrules",".cursorignore"];this.unsubscribeWatcher=a.subscribe(this.rootDirectory,e,(e=>{const t={stack:[],error:void 0,hasError:!1};try{const r=(0,y.q6)(),n=Bm(t,(0,$.VI)(r.withName("LocalCursorRulesService.fileWatcher.subscribe")),!1);if(".cursorignore"===(0,s.basename)(e))return fg.getRipwalkCache().clear(),void this.reload(n.ctx);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{Wm(t)}}))}}reload(e){this._rules=this.load(e).catch((e=>((0,zs.debuglog)("Failed to load cursor rules:",e),[])));for(const e of this.onChangeCallbacks)e()}static getRipwalkCache(){return fg.ripwalkCache??=new Sa,fg.ripwalkCache}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.reloadAtPath")),!1);if(Jr((0,s.basename)(t)))return void this.reload(n.ctx);const o=this._rules;this._rules=(async()=>{const e=(await o).filter((e=>e.fullPath!==t));const r=(await this.readRulesAtPath(n.ctx,t)).map((e=>this.toCursorRule(e)));return[...e,...r]})().catch((e=>((0,zs.debuglog)("Failed to load cursor rules at path:",e),[])));for(const e of this.onChangeCallbacks)e()}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}isRuleMarkdownFile(e){return Jr(e)}async readRulesAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.readRulesAtPath")),!1),o=(0,s.basename)(t);if(".cursorrules"===o){const e=(0,s.resolve)(this.rootDirectory),t=await Ya(n.ctx,this.gitExecutor,e)||e,r=await this.loadCursorRulesRule(n.ctx,t);return r?[r]:[]}if(o.endsWith(".mdc"))return await mg(t);if(this.isRuleMarkdownFile(o))try{return await this.loadRulesFromMarkdownFile(n.ctx,(0,s.dirname)(t),o)}catch{}return[]}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}dispose(){this.unsubscribeWatcher&&(this.unsubscribeWatcher(),this.unsubscribeWatcher=void 0)}async load(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.load")),!1);this.loadTraceId=n.span.spanContext().traceId;const o=(0,s.resolve)(this.rootDirectory),i=await Ya(n.ctx,this.gitExecutor,o)||o,a=this.loadCursorRulesRule(n.ctx,i).then((e=>e?[e]:[])),c=this.loadRulesFromDirAndAncestors(n.ctx,o);let l,u;if(this.loadNestedRules){const e=t??this.nestedExtensibilityService.discover(n.ctx);l=e.then((e=>this.parseNestedRuleFiles(n.ctx,e.rules))),u=e.then((e=>this.parseNestedMarkdownFiles(n.ctx,e.markdown)))}else l=[],u=[];const d=(await Promise.all([a,c,l,u])).flat(),h=new Map;for(const e of d)h.set(e.path,e);const p=[...h.values()];return(await async function(e){const t=e.filter((e=>Jr((0,s.basename)(e.fullPath))));if(t.length<=1)return[...e];const r=await(0,Or.PH)(t,(e=>async function(e){try{const t=await(0,Co.stat)(e,{bigint:!0});if(0n!==t.ino)return`ino:${String(t.dev)}:${String(t.ino)}`}catch{}return await ts(e)}(e.fullPath)),{max:16}),n=t.map(((e,t)=>({item:e,identity:r[t],dir:(0,s.dirname)(e.fullPath),content:e.content.trim()}))).sort(((e,t)=>{const r=zm(e.dir)-zm(t.dir);if(0!==r)return r;const n="AGENTS.md"===(0,s.basename)(e.item.fullPath);return n===("AGENTS.md"===(0,s.basename)(t.item.fullPath))?0:n?-1:1})),o=[];for(const e of n)o.some((t=>{return((r=t.dir)===(n=e.dir)||!!n.startsWith(r)&&(qm(r.at(-1))||qm(n[r.length])))&&(t.identity===e.identity||t.content===e.content);var r,n}))||o.push(e);const i=new Set(o.map((e=>e.item)));return e.filter((e=>!Jr((0,s.basename)(e.fullPath))||i.has(e)))}(p.map((e=>({fullPath:e.path,content:e.body,rule:e}))))).map((e=>this.toCursorRule(e.rule)))}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}async loadCursorRulesRule(e,t){const r={stack:[],error:void 0,hasError:!1};try{Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.loadCursorrules")),!1);try{const e=(0,s.join)(t,".cursorrules");if((await(0,Co.stat)(e)).isFile())return{filename:".cursorrules",path:e,frontmatter:{alwaysApply:!0},body:await ji(e)}}catch{}return null}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{return Bm(t,(0,$.VI)(e.withName("LocalCursorRulesService.getAllCursorRules")),!1).span.setAttribute("cacheTraceId",this.loadTraceId??"undefined"),await this._rules}catch(e){t.error=e,t.hasError=!0}finally{Wm(t)}}toCursorRule(e){return hg({path:e.path,body:e.body,frontmatter:e.frontmatter,rawFrontmatter:e.rawFrontmatter})}async loadRulesFromDirAndAncestors(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirAndAncestors")),!1),o=[];let i=t;const a=this.getThirdPartyExtensibilityEnabled();for(;;){const e=(0,s.join)(i,".cursor","rules"),t=i;o.push((async()=>await this.dirIsDirectory(n.ctx,e)?this.loadRulesFromDirectory(n.ctx,t):[])());const r=[];a&&r.push("CLAUDE.md","CLAUDE.local.md"),r.push("AGENTS.md");for(const e of r)o.push(this.loadRulesFromMarkdownFile(n.ctx,i,e));const c=(0,s.dirname)(i);if(c===i)break;i=c}const c=(await Promise.all(o)).flat();return n.span.setAttribute("rules",c.length),c}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}async loadRulesFromMarkdownFile(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{Bm(n,(0,$.VI)(e.withName("LocalCursorRulesService.loadRulesFromMarkdownFile")),!1).span.setAttribute("filename",r);try{const e=(0,s.join)(t,r);if(await this.isCursorIgnored(e))return[];if((await(0,Co.stat)(e)).isFile()){const t=Zr({content:await ji(e),filename:r});return[{filename:(0,s.basename)(e,".md"),path:e,frontmatter:{alwaysApply:!0},body:t}]}}catch{}return[]}catch(e){n.error=e,n.hasError=!0}finally{Wm(n)}}async isCursorIgnored(e){try{const t=await Cc((0,s.resolve)(this.rootDirectory,e));return null===t||await this.ignoreService.isCursorIgnored(t)}catch{return!1}}async parseNestedRuleFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.parseNestedRuleFiles")),!1),o=(await Promise.all(t.map((async e=>{try{const t=en(await ji(e));if(t)return{filename:(0,s.basename)(e,".mdc"),path:e,frontmatter:t.frontmatter,rawFrontmatter:t.rawFrontmatter,body:t.body}}catch{}})))).filter((e=>void 0!==e));return n.span.setAttribute("ruleFiles",o.length),o}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}async parseNestedMarkdownFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.parseNestedMarkdownFiles")),!1),o=(await Promise.all(t.map((async e=>{try{const t=(0,s.basename)(e);if(!this.isRuleMarkdownFile(t))return[];const r=(0,s.dirname)(e);return await this.loadRulesFromMarkdownFile(n.ctx,r,t)}catch{}return[]})))).flat();return n.span.setAttribute("markdownFiles",o.length),o}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}async loadRulesFromDirectory(e,t){return await async function(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=Bm(n,(0,$.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirectory")),!1),i=[];try{(0,s.join)(t,".cursorignore");const e={root:(0,s.join)(t,".cursor","rules"),includeGlobs:["**/*.mdc"],followSymlinks:!0,source:"cursor_rules"},n=r.walk(o.ctx,e);for await(const t of n.lines){const r=(0,s.join)(e.root,t);i.push(...await mg(r))}}catch{}return o.span.setAttribute("rules",i.length),i}catch(e){n.error=e,n.hasError=!0}finally{Wm(n)}}(e,t,fg.getRipwalkCache())}async dirIsDirectory(e,t){const r={stack:[],error:void 0,hasError:!1};try{Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.dirIsDirectory")),!1);try{return(await(0,Co.stat)(t)).isDirectory()}catch{return!1}}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}}async function mg(e){try{const t=en(await ji(e));if(t)return[{filename:(0,s.basename)(e,".mdc"),path:e,frontmatter:t.frontmatter,rawFrontmatter:t.rawFrontmatter,body:t.body}]}catch{}return[]}class gg{constructor(e,t,r,n,o,s,i=()=>!0,a=Promise.resolve(),c="ide",l,u=()=>[],d,h,p=()=>[],f){if(this.workspacePaths=t,this.userHomeDirectory=r,this.gitExecutor=n,this.getEnabledSkills=p,this.ignoreService=f,this.agentStoreLoadRequestedWhileInFlight=!1,this.agentStoreLoadGeneration=0,this.watchersByFolder=new Map,this.onChangeCallbacks=new Set,this.reloadRequestedDuringSeed=!1,this.surface=c,this.waitBeforeSkillLoad="function"==typeof a?a:()=>a,this.getAgentStoreSkillRoots=u,this.fileWatcher=s,this.getThirdPartyExtensibilityEnabled=i,this.catalogCache=d,this.builtinSkillRootDir=ym(r).dirPath,this.canvasKitSkillRootDir=void 0===h?void 0:bm(r).dirPath,this.workspaceCatalogKey=lm({kind:"workspace",surface:c,loadNestedSkills:o,thirdPartyExtensibility:i(),workspacePaths:[...t].sort(),userHomeDirectory:r,...void 0===h?{}:{canvasKit:h}}),void 0!==l&&l.length!==t.length)throw new Error(`initialNestedExtensibilityResults length (${l.length}) must match workspacePaths length (${t.length})`);this.nestedExtensibilityEntries=o?t.map((e=>new Mm(e,n,r,i))):[],this.foldersToWatch=this.computeFoldersToWatch();const m=performance.now();let g=!1,w=!1,y=!1;const v=this.loadAll(e,l).then((t=>{try{Hm.info(e,"AgentSkillsCursorRulesService load completed",{durationMs:Math.round(performance.now()-m),ruleCount:t.rules.length,skillCount:t.agentSkills.length,servedFromCache:g})}catch{}return t})).catch((e=>(w=!0,lg("Failed to load Agent Skills")(e))));if(void 0===this.catalogCache)this._loaded=v;else{const t=this.readCatalog(this.workspaceCatalogKey).then((r=>(y=!0,this._loaded!==t?this._loaded:(w&&this.closeSeedWindow(e),void 0===r?v:(g=!0,r)))));this.seededLoaded=t,this._loaded=t,v.then((r=>{this._loaded===t?w?y&&this.closeSeedWindow(e):(this._loaded=v,g&&this.notifyChanged(),this.persistCatalog(this.workspaceCatalogKey,r),this.closeSeedWindow(e)):this.seededLoaded=void 0}))}this.refreshAgentStoreSkills(),this.setupWatchers(this.foldersToWatch)}closeSeedWindow(e){this.seededLoaded=void 0,this.reloadRequestedDuringSeed&&(this.reloadRequestedDuringSeed=!1,this.reload(e))}async readCatalog(e){if(void 0!==this.catalogCache)try{const t=await this.catalogCache.read(e);return void 0===t?void 0:await async function(e){if(!function(e){if(!dm(e))return!1;const t=e.fileMtimesMs;return 1===e.version&&Array.isArray(e.rules)&&Array.isArray(e.agentSkills)&&Array.isArray(e.realSkillFilePathsByFullPath)&&e.realSkillFilePathsByFullPath.every((e=>Array.isArray(e)&&2===e.length&&"string"==typeof e[0]&&"string"==typeof e[1]))&&dm(t)&&Object.values(t).every((e=>"number"==typeof e&&Number.isFinite(e)))}(e))return;const t=new Map;if(await Promise.all(e.realSkillFilePathsByFullPath.map((async([r,n])=>{const o=e.fileMtimesMs[n];void 0!==o&&await um(r)===o&&t.set(r,n)}))),0===t.size)return;const r=e=>void 0!==e&&t.has(e);try{return{rules:e.rules.map((e=>Vr.DX.fromJson(e,{ignoreUnknownFields:!0}))).filter((e=>r(e.fullPath))),agentSkills:e.agentSkills.map((e=>am.N.fromJson(e,{ignoreUnknownFields:!0}))).filter((e=>r(e.fullPath))),realSkillFilePathsByFullPath:t}}catch(e){return void cm("snapshot failed to decode: %O",e)}}(t)}catch(e){return void ag("Failed to read the skills catalog cache: %O",e)}}persistCatalog(e,t){const r=this.catalogCache;void 0!==r&&async function(e){const t=new Set(e.realSkillFilePathsByFullPath.values()),r={};return await Promise.all(Array.from(t,(async e=>{const t=await um(e);void 0!==t&&(r[e]=t)}))),{version:1,rules:e.rules.map((e=>e.toJson())),agentSkills:e.agentSkills.map((e=>e.toJson())),realSkillFilePathsByFullPath:Array.from(e.realSkillFilePathsByFullPath),fileMtimesMs:r}}(t).then((t=>r.write(e,t))).catch((e=>{ag("Failed to persist the skills catalog cache: %O",e)}))}computeFoldersToWatch(){const e=this.getThirdPartyExtensibilityEnabled(),t=new Set;for(const r of this.workspacePaths){t.add((0,s.join)(r,".cursor","rules"));for(const n of Cm(r,e))t.add(n.dirPath)}for(const r of Em(this.userHomeDirectory,e))t.add(r.dirPath);for(const e of this.getAgentStoreSkillRoots())t.add(e);return t.add(this.builtinSkillRootDir),void 0!==this.canvasKitSkillRootDir&&t.add(this.canvasKitSkillRootDir),Array.from(t)}isIgnoredSkillPath(e){if(void 0!==this.canvasKitSkillRootDir){if(km(e,this.canvasKitSkillRootDir))return!1;if(function(e,t){const r=Sm(e,t);return void 0!==r&&2===r.length&&r[0]===vm&&"SKILL.md"===r[1]}(e,this.builtinSkillRootDir))return!0}return wm(e)}setupWatchers(e){if(!this.fileWatcher)return;const t=["**"];for(const r of e){if(this.watchersByFolder.has(r))continue;const e=this.fileWatcher.subscribe(r,t,(e=>{const t={stack:[],error:void 0,hasError:!1};try{const r=(0,y.q6)(),n=Bm(t,(0,$.VI)(r.withName("AgentSkillsCursorRulesService.fileWatcher.subscribe")),!1);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{Wm(t)}}));this.watchersByFolder.set(r,e)}}removeWatchers(e){for(const t of e){const e=this.watchersByFolder.get(t);e&&(e(),this.watchersByFolder.delete(t))}}async getAllCursorRules(e){const[t]=await Promise.all([this._loaded,this.awaitAgentStoreSeed()]);return this.withAgentStoreSkills(t).rules}async awaitAgentStoreSeed(){void 0!==this.agentStoreSeedInFlight&&await(0,Or.wj)(this.agentStoreSeedInFlight,250,"Agent Store skills cache read timed out").catch((()=>{}))}reload(e){this.syncWatchers(),this.seededLoaded=void 0,this.reloadRequestedDuringSeed=!1;const t=this.loadAll(e),r=t.catch(lg("Failed to load Agent Skills"));this._loaded=r,t.then((e=>{this._loaded===r&&this.persistCatalog(this.workspaceCatalogKey,e)}),(()=>{})),this.refreshAgentStoreSkills(),this.notifyChanged()}reloadSkillRoots(){try{this.syncWatchers()}finally{this.refreshAgentStoreSkills()}}async agentStoreSkillsSettled(){for(let e=this.agentStoreWalk;void 0!==e;e=this.agentStoreWalk)await e}syncWatchers(){const e=this.computeFoldersToWatch(),t=new Set(this.foldersToWatch),r=new Set(e);this.removeWatchers(this.foldersToWatch.filter((e=>!r.has(e)))),this.setupWatchers(e.filter((e=>!t.has(e)))),this.foldersToWatch=e}isPrunedByExtensibilityScan(e){if(void 0!==this.canvasKitSkillRootDir&&km(e,this.canvasKitSkillRootDir))return!1;const t=e.replace(/\\/g,"/");for(const e of this.foldersToWatch){const r=e.replace(/\\/g,"/");if(t.startsWith(`${r}/`))return t.slice(r.length+1).split("/").slice(0,-1).some((e=>e.startsWith(".")))}return!1}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("AgentSkillsCursorRulesService.reloadAtPath")),!1),o=function(e,t,r=s){for(const n of t){const t=r.relative(n,e);if(""!==t&&".."!==t&&!t.startsWith(`..${r.sep}`)&&!r.isAbsolute(t))return r.join(n,t)}return e}(t,this.foldersToWatch),i=o.endsWith("SKILL.md")?o:(0,s.join)(o,"SKILL.md");if(void 0!==this.seededLoaded&&this._loaded===this.seededLoaded&&!this.getAgentStoreSkillRoots().some((e=>dg(i,e))))return void(this.reloadRequestedDuringSeed=!0);if(this.getAgentStoreSkillRoots().some((e=>dg(i,e))))return void this.refreshAgentStoreSkills();if(this.foldersToWatch.some((e=>""===(0,s.relative)(e,o))))return void this.reload(n.ctx);const a=this._loaded,c=(async()=>{const e=await a,{realSkillFilePathsByFullPath:t}=e,r=function(e,t){const r=new Map(e.realSkillFilePathsByFullPath);for(const e of t)r.delete(e);return{rules:e.rules.filter((e=>!t.has(e.fullPath))),agentSkills:e.agentSkills.filter((e=>!t.has(e.fullPath))),realSkillFilePathsByFullPath:r}}(e,new Set([i]));if(this.isIgnoredSkillPath(i)||this.isPrunedByExtensibilityScan(i))return r;const o=t.get(i);if(void 0===o){try{await(0,Co.stat)(i)}catch{return r}return await this.loadAll(n.ctx)}let s;try{s=await(0,Co.realpath)(i)}catch{return await this.loadAll(n.ctx)}if(s!==o)return await this.loadAll(n.ctx);try{return ig(r,{...await async function(e){const t=await ji(e);return{skillFilePath:e,content:t,parsed:eh(t)}}(i),realSkillFilePath:s},this.surface,this.getEnabledSkills()),r}catch{return await this.loadAll(n.ctx)}})().catch(lg("Failed to load Agent Skills at path"));this._loaded=c,this.notifyChanged()}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}async getAllAgentSkills(e){const[t]=await Promise.all([this._loaded,this.awaitAgentStoreSeed()]);return this.withAgentStoreSkills(t).agentSkills}withAgentStoreSkills(e){const t=this.settledAgentStoreSkills?.loaded;if(void 0===t||0===t.realSkillFilePathsByFullPath.size)return e;const r=new Set(e.realSkillFilePathsByFullPath.values()),n={rules:[...e.rules],agentSkills:[...e.agentSkills],realSkillFilePathsByFullPath:new Map(e.realSkillFilePathsByFullPath)},o=new Set;for(const[e,s]of t.realSkillFilePathsByFullPath)n.realSkillFilePathsByFullPath.has(e)||r.has(s)?o.add(e):n.realSkillFilePathsByFullPath.set(e,s);for(const e of t.rules)o.has(e.fullPath)||n.rules.push(e);for(const e of t.agentSkills)o.has(e.fullPath)||n.agentSkills.push(e);return n}refreshAgentStoreSkills(){const e=this.getAgentStoreSkillRoots().filter((e=>""!==e.trim())),t=++this.agentStoreLoadGeneration;var r,n;if(void 0===this.settledAgentStoreSkills||(r=this.settledAgentStoreSkills.roots,n=e,r.length===n.length&&r.every(((e,t)=>e===n[t])))||(this.settledAgentStoreSkills=void 0,this.notifyChanged()),0!==e.length){if(void 0===this.settledAgentStoreSkills){const r=this.seedAgentStoreSkills(e,t).finally((()=>{this.agentStoreSeedInFlight===r&&(this.agentStoreSeedInFlight=void 0)}));this.agentStoreSeedInFlight=r}void 0===this.agentStoreWalk?this.agentStoreWalk=(0,Or.wj)(this.loadAgentStoreSkills(e),3e4,"Agent Store skills walk timed out").then((r=>{t===this.agentStoreLoadGeneration&&(this.settledAgentStoreSkills={roots:e,loaded:r},this.notifyChanged(),(r.rules.length>0||r.agentSkills.length>0)&&this.persistCatalog(ug(this.surface,e),r))}),(e=>{ag("Failed to load Agent Store skills: %O",e)})).finally((()=>{this.agentStoreWalk=void 0,this.agentStoreLoadRequestedWhileInFlight&&(this.agentStoreLoadRequestedWhileInFlight=!1,this.refreshAgentStoreSkills())})):this.agentStoreLoadRequestedWhileInFlight=!0}}async seedAgentStoreSkills(e,t){const r=await this.readCatalog(ug(this.surface,e));void 0!==r&&t===this.agentStoreLoadGeneration&&void 0===this.settledAgentStoreSkills&&(this.settledAgentStoreSkills={roots:e,loaded:r},this.notifyChanged())}async loadAgentStoreSkills(e){const t=cg(),r=(await Promise.all(e.map((e=>Gm(e))))).flat().filter((e=>!wm(e))),n=await Promise.all(r.map((e=>Km(e)))),o=new Set;for(const e of n)o.has(e.realSkillFilePath)||(o.add(e.realSkillFilePath),ig(t,e,this.surface,this.getEnabledSkills()));return t}notifyChanged(){for(const e of Array.from(this.onChangeCallbacks))e()}onDidChangeSkills(e){return this.onDidChangeRules(e)}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}dispose(){for(const e of this.watchersByFolder.values())e();this.watchersByFolder.clear()}async loadAll(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("AgentSkillsCursorRulesService.loadAll")),!1);await this.waitBeforeSkillLoad();const o=[],s=[],i=new Map,a=Promise.all(this.nestedExtensibilityEntries.map(((e,r)=>(t?.[r]??e.discover(n.ctx)).catch((e=>{ag("Failed to discover nested agent skills: %O",e)}))))),c=new Set(this.getAgentStoreSkillRoots()),l=await Promise.all(this.foldersToWatch.filter((e=>!c.has(e))).map((async e=>{const t=(await Gm(e)).filter((e=>!this.isIgnoredSkillPath(e)));return Promise.all(t.map((e=>Km(e))))}))),u=new Set;for(const e of l)for(const t of e)if(!u.has(t.realSkillFilePath))if(u.add(t.realSkillFilePath),"error"in t)i.set(t.skillFilePath,t.realSkillFilePath),sg({rules:o,agentSkills:s,skillFilePath:t.skillFilePath,errorMessage:t.error});else{if(Ym(t.parsed,this.surface,this.getEnabledSkills()))continue;i.set(t.skillFilePath,t.realSkillFilePath),o.push(ng(t)),tg(t.parsed)||s.push(og(t))}const d=(await a).flatMap((e=>e?.skills??[])).filter((e=>!wm(e))),h=await Promise.all(d.map((e=>ts(e)))),p=[];for(const[e,t]of d.entries()){const r=h[e];u.has(r)||(u.add(r),p.push(t))}const f=await Promise.all(p.map((e=>Km(e))));for(const e of f)if("error"in e)i.set(e.skillFilePath,e.realSkillFilePath),sg({rules:o,agentSkills:s,skillFilePath:e.skillFilePath,errorMessage:e.error});else{if(Ym(e.parsed,this.surface,this.getEnabledSkills()))continue;i.set(e.skillFilePath,e.realSkillFilePath),o.push(ng(e)),tg(e.parsed)||s.push(og(e))}return n.span.setAttribute("agent_skills.total",o.length),n.span.setAttribute("agent_skills_proto.total",s.length),{rules:o,agentSkills:s,realSkillFilePathsByFullPath:i}}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}}function wg(e){let t;switch(e.type){case"global":t=new Vr.f5({type:{case:"global",value:new Vr.i9}});break;case"fileGlobbed":t=new Vr.f5({type:{case:"fileGlobbed",value:new Vr.uT({globs:e.globs??[]})}});break;case"agentFetched":t=new Vr.f5({type:{case:"agentFetched",value:new Vr.Xo({description:eg(e.description??"")})}});break;case"manuallyAttached":t=new Vr.f5({type:{case:"manuallyAttached",value:new Vr._u}});break;default:e.type,t=new Vr.f5({type:{case:"manuallyAttached",value:new Vr._u}})}return new Vr.DX({fullPath:e.fullPath,content:e.content,type:t,gitRemoteOrigin:e.gitRemoteOrigin,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,environments:e.environments??[],disabledEnvironments:e.disabledEnvironments??[],scopedTo:[]})}class yg{constructor(e,t,r,n){this.getImportSettings=t,this.pluginsService=n,this._rules=Promise.resolve([]),this._agentSkills=Promise.resolve([]),this._lastLoaded={rules:[],agentSkills:[]},this._loadGeneration=0,this.onChangeCallbacks=new Set,this.currentImportSettings=this.getImportSettings();const o=performance.now();this.startLoad(e,!1,(t=>{try{Hm.info(e,"CursorPluginsAgentSkillsService load completed",{durationMs:Math.round(performance.now()-o),ruleCount:t.rules.length,skillCount:t.agentSkills.length})}catch{}}))}startLoad(e,t,r){const n=++this._loadGeneration,o=this.loadAll(e,t).catch((e=>((0,zs.debuglog)("cursor-plugins-agent-skills")("Failed to load Cursor Plugins Agent Skills: %s",e instanceof Error?e.message:String(e)),{rules:[],agentSkills:[]}))).then((e=>(n===this._loadGeneration&&(this._lastLoaded=e,r?.(e)),e))),s=()=>(o.then((e=>{n===this._loadGeneration&&(this._rules=Promise.resolve(e.rules),this._agentSkills=Promise.resolve(e.agentSkills),this.notifyChange())})),this._lastLoaded),i=void 0!==this._overBudgetLoad?Promise.resolve(s()):(0,Or.wj)(o,5e3,"Cursor plugin load did not finish within the rules wait budget").catch((t=>(Hm.warn(e,"Serving rules without plugin primitives while plugins load",{error:t instanceof Error?t.message:String(t),waitMs:5e3}),this._overBudgetLoad=o,o.then((()=>{this._overBudgetLoad===o&&(this._overBudgetLoad=void 0)})),s())));this._rules=i.then((e=>e.rules)),this._agentSkills=i.then((e=>e.agentSkills))}notifyChange(){for(const e of Array.from(this.onChangeCallbacks))e()}async getAllCursorRules(e){return await this._rules}async getAllAgentSkills(e){return await this._agentSkills}reload(e){const t=this.getImportSettings();this.currentImportSettings=t,this.startLoad(e,!0),this.notifyChange()}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}onDidChangeSkills(e){return this.onDidChangeRules(e)}dispose(){this.onChangeCallbacks.clear()}async loadAll(e,t=!1){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("CursorPluginsAgentSkillsService.loadAll")),!1),o=[],i=[];try{let e=t?await this.pluginsService.reload():await this.pluginsService.getAllEnabledPlugins();this.currentImportSettings.importThirdPartyPlugins||(e=e.filter((e=>"claude-plugin"!==e.identifier.source))),n.span.setAttribute("cursor_plugins.loaded",e.length);const r=function(e){return im(e,(e=>e.skills))}(e),a=function(e){return im(e,(e=>e.rules))}(e);for(const e of[...r,...a])o.push(wg(e));for(const t of e){const e=`plugin:${lf(t.identifier)}`,r=uf(t.identifier),n=df(t.identifier),o=hf(t.identifier),a=pf(t.identifier);for(const c of t.skills){if(!0===c.alwaysApply)continue;let l=!1;if(c.content?.includes("disable-model-invocation"))try{l=!0===eh(c.content).data?.["disable-model-invocation"]}catch{}i.push(new am.N({fullPath:(0,s.join)(t.installPath,c.path),content:c.content,description:eg(c.description??""),environments:c.environments??[],disabledEnvironments:c.disabledEnvironments??[],gitRemoteOrigin:e,plugin:r,marketplace:n,pluginId:o,marketplaceId:a,disableModelInvocation:l}))}}}catch(e){n.span.setAttribute("cursor_plugins.error",String(e))}return n.span.setAttribute("cursor_plugins.total",o.length),n.span.setAttribute("cursor_plugins_proto.total",i.length),{rules:o,agentSkills:i}}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}}var vg=r("../proto/dist/generated/agent/v1/subagents_pb.js");const bg=(0,zs.debuglog)("local-subagents");class Sg{async getAllSubagents(){return[]}async reload(){return[]}}function kg(e){return"true"===(e??"").trim().toLowerCase()}function _g(e){const t=e.match(/^---\s*\n([\s\S]*?)\n---\s*\n?([\s\S]*)$/m);if(!t)return null;const r=t[1]??"",n=(t[2]??"").trim();if(0===n.length)return null;const o={};for(const e of r.split("\n")){const t=e.trim();if(0===t.length||t.startsWith("#"))continue;const r=t.indexOf(":");if(-1===r)continue;const n=t.slice(0,r).trim().toLowerCase(),s=t.slice(r+1).trim();0!==n.length&&(o[n]=s)}const s=o.name??"",i=o.description,a=o.model,c=kg(o["force-default-model"]),l="true"===(o.readonly??"").trim().toLowerCase()?vg.b$.READONLY:vg.b$.DEFAULT,u=kg(o.background??o.is_background),d=o.tools;return{name:s,description:i,tools:void 0!==d&&d.length>0?d.split(",").map((e=>e.trim())).filter((e=>e.length>0)):[],model:a,forceDefaultModel:c,prompt:n,permissionMode:l,isBackground:u}}function Cg(e){const t=(0,s.extname)(e).toLowerCase();return".md"===t||".mdc"===t||".markdown"===t}function Eg(e){return(0,s.basename)(e,(0,s.extname)(e)).replace(/[\s_]+/g,"-")}async function xg(e,t){return await Om({rootDir:e,includeFile:Cg,containmentRootDir:t})}class Pg{constructor(e,t,r="workspace",n=!1,o){this.workspacePath=e,this.cursorAgentsSource=r,this.allowExternalAgentSymlinks=n,this.ignoreService=o,this.getThirdPartyExtensibilityEnabled=t??(()=>!0),this.subagents=this.load().catch((e=>(bg("Failed to load subagents: %o",e),[])))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents=this.load().catch((e=>(bg("Failed to load subagents: %o",e),[]))),await this.subagents}computeAgentsDirs(){const e=(0,s.resolve)(this.workspacePath),t=[{dirPath:(0,s.join)(e,".cursor","agents"),source:this.cursorAgentsSource}];return this.getThirdPartyExtensibilityEnabled()&&(t.push({dirPath:(0,s.join)(e,".claude","agents"),source:"claude"}),t.push({dirPath:(0,s.join)(e,".grok","agents"),source:"grok"})),t}async load(){const e=this.computeAgentsDirs(),t=[];for(const{dirPath:r,source:n}of e){const e=await xg(r,this.allowExternalAgentSymlinks?void 0:this.workspacePath);for(const r of e){const e=(0,s.basename)(r);try{if(!(await(0,Co.stat)(r)).isFile())continue}catch(e){bg("Skipping subagent file %s due to stat error: %o",r,e);continue}try{const o=_g(await ji(r));if(!o)continue;t.push(new vg.zz({fullPath:r,name:o.name||Eg(e),description:o.description??"",tools:o.tools,model:o.model??"inherit",forceDefaultModel:o.forceDefaultModel,prompt:o.prompt,permissionMode:o.permissionMode,isBackground:o.isBackground,source:n}))}catch(e){bg("Failed to parse subagent file %s: %o",r,e)}}}return t}}const Rg=new Set(["claude-code-tutor"]);class Ig{constructor(e){this.subagentsServices=e}async getAllSubagents(){const e=await Promise.all(this.subagentsServices.map((e=>e.getAllSubagents().catch((e=>(bg("Failed to load subagents from merged service: %o",e),[])))))),t=new Map;for(const r of e)for(const e of r)Rg.has(e.name)||t.has(e.name)||t.set(e.name,e);return Array.from(t.values())}async reload(){return await Promise.all(this.subagentsServices.map((e=>e.reload()))),this.getAllSubagents()}}class Tg{constructor(e,t){this.getSettings=e,this.pluginsService=t,this._subagentsCache=[],this._loadId=0,this._loadPromise=null,this._loadedOnce=!1,this.runLoadInBackground()}async getAllSubagents(){return this._loadPromise&&await this._loadPromise,this._loadedOnce||await this.reload(),[...this._subagentsCache]}async reload(){return this.runLoadInBackground(!0),this._loadPromise&&await this._loadPromise,this._subagentsCache}runLoadInBackground(e=!1){const t=++this._loadId;this._loadPromise=this.load(e).then((e=>{t===this._loadId&&(this._subagentsCache=e,this._loadedOnce=!0)})).catch((e=>{t===this._loadId&&(bg("Failed to load Cursor plugin subagents: %o",e),this._subagentsCache=[],this._loadedOnce=!0)})).finally((()=>{t===this._loadId&&(this._loadPromise=null)}))}dispose(){}async load(e){const t=[];try{let r=e?await this.pluginsService.reload():await this.pluginsService.getAllEnabledPlugins();this.getSettings().importThirdPartyPlugins||(r=r.filter((e=>"claude-plugin"!==e.identifier.source)));const n=function(e,t={stripModel:!0,stripTools:!0}){const r=[];for(const n of e){const e=uf(n.identifier),o=df(n.identifier),i=hf(n.identifier),a=pf(n.identifier);for(const c of n.agents){const l=sm(c,t),u=(0,s.join)(n.installPath,l.path);r.push({name:l.name,description:l.description??"",prompt:l.prompt,fullPath:u,permissionMode:"readonly"===l.permissionMode?"readonly":"default",plugin:e,marketplace:o,pluginId:i,marketplaceId:a})}}return r}(r,{stripModel:!0,stripTools:!0});for(const e of n){const r="readonly"===e.permissionMode?vg.b$.READONLY:vg.b$.DEFAULT;t.push(new vg.zz({name:e.name,description:e.description,tools:[],model:"inherit",prompt:e.prompt,fullPath:e.fullPath,permissionMode:r,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,source:"plugin"}))}}catch{}return t}}class Ag{constructor(e){this.pastElements=[],this.closed=!1,this.forks=new Set,this.consume(e)}async consume(e){try{for await(const t of e){this.pastElements.push(t);const e=[];for(const r of this.forks)e.push(r.write(t).catch((()=>{})));await Promise.allSettled(e)}}catch(e){this.error=e instanceof Error?e:new Error(String(e))}finally{this.closed=!0;for(const e of this.forks)this.error?e.throw(this.error):e.close();this.forks.clear()}}fork(){if(this.closed){const e=this.pastElements,t=this.error;return async function*(){for(const t of e)yield t;if(t)throw t}()}const e=(0,h.Jt)(),t=this.pastElements.slice();this.forks.add(e);const r=this;return async function*(){for(const e of t)yield e;try{for await(const t of e)yield t}finally{r.forks.delete(e)}}()}}function $g(e,t){return`${e}:${(0,bo.createHash)("sha256").update(t.toBinary()).digest("hex")}`}function Mg(e){return new Eo.q({max:e?.max??10,ttl:e?.ttl})}function Dg(e,t,r=Mg(t)){return{async execute(t,n,o){if(!o?.execId)return e.execute(t,n,o);const s=$g(o.execId,n),i=r.get(s);if(void 0!==i)return i;const a=await e.execute(t,n,o);return r.set(s,a),a}}}var Og=r("../proto/dist/generated/agent/v1/computer_use_tool_pb.js");r("node:readline"),Error;var Fg=r("node:timers/promises");const Ng=ou.execFile;function Lg(e,t,r){return new Promise(((n,o)=>{r?.signal?.throwIfAborted();const s={timeout:r?.timeoutMs??3e4,env:r?.env?{...process.env,...r.env}:void 0,signal:r?.signal};(0,su.D9)(Ng,e,t.map(String),{...s,encoding:"utf8"},((e,t)=>{e?o(e):n(t)}))}))}Og.w3.UNSPECIFIED,Og.w3.LEFT,Og.w3.MIDDLE,Og.w3.RIGHT,Og.w3.BACK,Og.w3.FORWARD,Og.Dh.UNSPECIFIED,Og.Dh.UP,Og.Dh.DOWN,Og.Dh.LEFT,Og.Dh.RIGHT;const jg=(0,zs.promisify)(ou.execFile);function Ug(e){const t=e.lastIndexOf(":");if(-1===t)throw new Error(`Invalid X11 display string: ${e} (missing ':')`);const r=e.slice(t+1).split(".")[0],n=parseInt(r,10);if(!Number.isFinite(n)||n<0)throw new Error(`Invalid X11 display number in: ${e} (parsed: ${r})`);return n}function Bg(e,t,r,n){const o=function(e={}){const t=e.displayWidth??1920,r=e.displayHeight??1200,n=e.apiWidth??1280;return{width:n,height:Math.round(n*r/t)}}({displayWidth:e,displayHeight:t,apiWidth:r});return{display:{width:e,height:t},api:{width:o.width,height:n??o.height}}}async function Wg(e){const{stdout:t}=await(0,su.D9)(jg,"xrandr",["--display",e],{timeout:5e3,encoding:"utf8"}),r=function(e){let t,r,n;for(const o of e.split("\n"))if(o.includes("*")){const e=o.trim().match(/^(\d+)x(\d+)/);e&&(t=parseInt(e[1],10),r=parseInt(e[2],10));const s=o.match(/(\d+(?:\.\d+)?)\*(?:\+)?/);if(s){const e=parseFloat(s[1]);e>0&&e<=500&&(n=Math.round(e))}if(t&&r)break}if(!t||!r){const n=e.match(/current\s+(\d+)\s*x\s*(\d+)/i);n&&(t=parseInt(n[1],10),r=parseInt(n[2],10))}if(!t||!r)throw new Error(`Could not detect display resolution from xrandr output.\nExpected a line with '*' indicating active mode, or 'current WxH'.\nxrandr output:\n${e}`);return n||(n=60),{width:t,height:r,refreshRate:n}}(t);return{display:r,resolution:Bg(r.width,r.height),resolutionString:`${r.width}x${r.height}`}}Og.w3.UNSPECIFIED,Og.w3.LEFT,Og.w3.MIDDLE,Og.w3.RIGHT,Og.w3.BACK,Og.w3.FORWARD,Og.Dh.UNSPECIFIED,Og.Dh.UP,Og.Dh.DOWN,Og.Dh.LEFT,Og.Dh.RIGHT;const Hg={pattern:"[\\w-]{1,64}",next:e=>e},qg={pattern:"[0-9a-f-]{36}",next:()=>bo.randomUUID()},zg={pattern:"webp",next:()=>"webp"},Gg={native:[qg,zg],agent:[Hg,qg,zg],legacyNative:[qg,{pattern:"png",next:()=>"png"}]};new RegExp(`^(?:${Object.values(Gg).map((e=>e.map((e=>e.pattern)).join("\\."))).join("|")})$`),new RegExp(`^${Hg.pattern}$`),Og.Z8.NATIVE_X11,Og.Z8.XDOTOOL,(0,u.v5)("computer_use.session.duration_ms",{description:"Duration of computer-use session in milliseconds"}),(0,u.v5)("computer_use.session.action_count",{description:"Number of actions executed in a computer-use session"}),(0,u.Pu)("computer_use.session.result",{description:"Result status of computer-use session",labelNames:["outcome"]}),(0,u.Pu)("computer_use.session.action_kind",{description:"Requested computer-use actions by bounded kind",labelNames:["kind"]}),(0,l.h)("computer-use"),Math.floor(35927136),["Skip changes that cannot affect what runs in any deployed environment:","- documentation-only changes (Markdown, docs sites, code comments, changelogs)","- formatting, lint, or typo fixes with no behavior change","- test-only changes (test files, fixtures, snapshots)","Monitor everything else, including dependency bumps, configuration, and infrastructure changes."].join("\n"),Error,(0,u.Pu)("computer_use.desktop_lease.check",{description:"Desktop lease action-gate outcomes",labelNames:["outcome","reason"]});var Vg=r("../proto/dist/runtime/compact.js");Vg.HL;var Kg=(0,Vg.QT)(we.proto3,"agent.v1.","CursorType",[[0,"UNSPECIFIED"],[1,"ARROW"],[2,"POINTER"],[3,"TEXT"],[4,"WAIT"],[5,"CROSSHAIR"],[6,"MOVE"],[7,"RESIZE_NS"],[8,"RESIZE_EW"],[9,"RESIZE_NWSE"],[10,"RESIZE_NESW"],[11,"NOT_ALLOWED"],[12,"GRAB"],[13,"GRABBING"]],1);we.proto3,we.proto3,we.proto3,we.proto3;class Jg{constructor(e){this.config=e;const t=e.display.width/e.display.height,r=e.api.width/e.api.height;if(Math.abs(t-r)>.02)throw new Error(`Aspect ratio mismatch: display=${t.toFixed(3)}, api=${r.toFixed(3)}`);this.xScaleUp=e.display.width/e.api.width,this.yScaleUp=e.display.height/e.api.height,this.xScaleDown=e.api.width/e.display.width,this.yScaleDown=e.api.height/e.display.height}apiToDisplay(e,t){return{x:Math.round(e*this.xScaleUp),y:Math.round(t*this.yScaleUp)}}displayToApi(e,t){return{x:Math.round(e*this.xScaleDown),y:Math.round(t*this.yScaleDown)}}get apiWidth(){return this.config.api.width}get apiHeight(){return this.config.api.height}get displayWidth(){return this.config.display.width}get displayHeight(){return this.config.display.height}}const Zg={left_ptr:Kg.ARROW,arrow:Kg.ARROW,default:Kg.ARROW,top_left_arrow:Kg.ARROW,hand:Kg.POINTER,hand1:Kg.POINTER,hand2:Kg.POINTER,pointer:Kg.POINTER,pointing_hand:Kg.POINTER,xterm:Kg.TEXT,ibeam:Kg.TEXT,text:Kg.TEXT,watch:Kg.WAIT,wait:Kg.WAIT,progress:Kg.WAIT,left_ptr_watch:Kg.WAIT,crosshair:Kg.CROSSHAIR,cross:Kg.CROSSHAIR,tcross:Kg.CROSSHAIR,move:Kg.MOVE,fleur:Kg.MOVE,size_all:Kg.MOVE,sb_v_double_arrow:Kg.RESIZE_NS,v_double_arrow:Kg.RESIZE_NS,ns_resize:Kg.RESIZE_NS,row_resize:Kg.RESIZE_NS,top_side:Kg.RESIZE_NS,bottom_side:Kg.RESIZE_NS,sb_h_double_arrow:Kg.RESIZE_EW,h_double_arrow:Kg.RESIZE_EW,ew_resize:Kg.RESIZE_EW,col_resize:Kg.RESIZE_EW,left_side:Kg.RESIZE_EW,right_side:Kg.RESIZE_EW,top_left_corner:Kg.RESIZE_NWSE,bottom_right_corner:Kg.RESIZE_NWSE,nwse_resize:Kg.RESIZE_NWSE,size_fdiag:Kg.RESIZE_NWSE,top_right_corner:Kg.RESIZE_NESW,bottom_left_corner:Kg.RESIZE_NESW,nesw_resize:Kg.RESIZE_NESW,size_bdiag:Kg.RESIZE_NESW,not_allowed:Kg.NOT_ALLOWED,no_drop:Kg.NOT_ALLOWED,forbidden:Kg.NOT_ALLOWED,circle:Kg.NOT_ALLOWED,grab:Kg.GRAB,openhand:Kg.GRAB,grabbing:Kg.GRABBING,closedhand:Kg.GRABBING};class Xg{constructor(e){this.events=[],this.recordingStartTime=0,this.lastKnownPosition={x:0,y:0},this.isRunning=!1,this.pending=Promise.resolve();const t=e.displayNum??1;this.env={DISPLAY:`:${t}`},this.scaler=new Jg(e.resolution)}async start(){this.events=[],this.recordingStartTime=Date.now(),this.isRunning=!0,this.pending=Promise.resolve();try{this.lastKnownPosition=await this.captureCurrentPosition()}catch{this.lastKnownPosition={x:Math.floor(this.scaler.apiWidth/2),y:Math.floor(this.scaler.apiHeight/2)}}}logEvent(e,t,r){if(!this.isRunning)return;const n={...this.lastKnownPosition},o=this.getExpectedPositionAfterAction(e,n);this.lastKnownPosition=o;const s=async()=>{let s,i;try{[s,i]=await Promise.all([this.captureCurrentPosition(),this.detectCursorType()]),this.lastKnownPosition=s}catch{s=o,i=Kg.ARROW}const a={executionTimestampMs:r-this.recordingStartTime,action:e,commandDurationMs:r-t,positionBefore:n,positionAfter:s,cursorTypeAfter:i};this.events.push(a)};this.pending=this.pending.then((()=>s())).catch((()=>{}))}async stop(){return this.isRunning=!1,await this.pending,[...this.events]}getEvents(){return[...this.events]}getRecordingStartTime(){return this.recordingStartTime}getIsRunning(){return this.isRunning}async captureCurrentPosition(){const e=await Lg("xdotool",["getmouselocation","--shell"],{env:this.env}),t=e.match(/X=(\d+)/),r=e.match(/Y=(\d+)/);if(!t||!r)throw new Error(`Failed to parse cursor position: ${e}`);const n=parseInt(t[1],10),o=parseInt(r[1],10);return this.scaler.displayToApi(n,o)}async detectCursorType(){try{const e=(await Lg("xdotool",["getmouselocation","--shell"],{env:this.env})).match(/CURSOR=(\S+)/i);if(e){const t=e[1].toLowerCase();return Zg[t]??Kg.ARROW}try{const e=await Lg("xprop",["-root","_XSERVER_CURSOR"],{env:this.env,timeoutMs:500});for(const[t,r]of Object.entries(Zg))if(e.toLowerCase().includes(t))return r}catch{}return Kg.ARROW}catch{return Kg.ARROW}}getExpectedPositionAfterAction(e,t){const r=e.action;if(!r)return t;switch(r.case){case"mouseMove":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}case"click":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}case"drag":{const e=r.value.path;if(e.length>0){const t=e[e.length-1];return{x:t.x,y:t.y}}break}case"scroll":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}}return t}}(0,l.h)("computer-use-lazy");var Qg=r("node:net");function Yg(e){return!!e.includes(o.homedir())||e.includes("node_modules")||e.includes("Application Support")||/\.wasm\b/.test(e)||/(?:^|[\s'`"(=])(?:\/|\.{1,2}\/)/.test(e)||/(?:^|[\s'`"(=:])(?:[A-Za-z]:[\\/]|\\\\)/.test(e)||/\bS-1-5-21(?:-\d+){3,}/i.test(e)}class ew extends Error{constructor(e){super(e),this.name="MacRPCProtocolError"}}const tw=je.object({rpcSocketPath:je.string().min(1).optional(),appControlSocketPath:je.string().min(1).optional(),pid:je.number().int().positive().optional().catch(void 0),protocolMajor:je.number().int().positive().optional().catch(void 0)}).passthrough(),rw=je.object({data:je.string(),mimeType:je.string().min(1)}).strip(),nw=je.object({message:je.string(),screenshot:rw.optional(),screenshotBefore:rw.optional(),structuredContent:je.unknown().optional(),isError:je.boolean()}).strip(),ow=je.object({accessibilityTrusted:je.boolean(),screenRecordingGranted:je.boolean()}).strip(),sw=je.union([je.object({id:je.number().int(),result:nw,ok:je.never().optional(),error:je.never().optional(),errorCode:je.never().optional(),permissionStatus:je.never().optional(),sessionId:je.never().optional()}).strip(),je.object({id:je.number().int(),sessionId:je.string().min(1),ok:je.literal(!0).optional(),result:je.never().optional(),error:je.never().optional(),errorCode:je.never().optional(),permissionStatus:je.never().optional()}).strip(),je.object({id:je.number().int(),ok:je.literal(!0),result:je.never().optional(),error:je.never().optional(),errorCode:je.never().optional(),permissionStatus:je.never().optional(),sessionId:je.never().optional()}).strip(),je.object({id:je.number().int().nullable().optional(),error:je.string().min(1),errorCode:je.string().min(1).optional(),result:je.never().optional(),ok:je.never().optional(),permissionStatus:je.never().optional(),sessionId:je.never().optional()}).strip(),je.object({id:je.number().int(),permissionStatus:ow,result:je.never().optional(),ok:je.never().optional(),error:je.never().optional(),errorCode:je.never().optional(),sessionId:je.never().optional()}).strip()]);function iw(e,t){try{return JSON.parse(e)}catch{throw new ew(`local-cua ${t} is not valid JSON`)}}const aw={responseMaxBytes:33554432,parseServiceState(e){const t=tw.safeParse(iw(e,"service state")),r=t.success?t.data.rpcSocketPath??t.data.appControlSocketPath:void 0;if(!t.success||void 0===r)throw new ew("local-cua service state is malformed");return{...t.data,rpcSocketPath:r}},parseResponse({line:e,expectedID:t}){const r=sw.safeParse(iw(e.toString("utf8"),"RPC response"));if(!r.success)throw new ew("local-cua RPC response is malformed");if(void 0!==r.data.id&&null!==r.data.id&&r.data.id!==t)throw new ew("local-cua RPC response ID did not match");return r.data}};class cw extends Error{constructor(e,t){super(e),this.name="MacComputerUseRPCError",this.code=t?.code,this.userFacing=!0===t?.userFacing,this.tool=t?.tool}}function lw(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:e instanceof Error?Yg(e.message)?e.name:e.message.length>0?`${e.name}: ${e.message}`:e.name:"unknown"}const uw=new Map([["co.anysphere.cursor-computer-use","cursor-computer-use"],["co.anysphere.cursor-computer-use.dev","cursor-computer-use-dev"]]),dw=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;class hw{constructor(e){this.mode=e}static isInstalled(){if((0,xo.existsSync)(hw.serviceExecutablePath()))return!0;let e;try{e=aw.parseServiceState((0,xo.readFileSync)(hw.serviceStatePath(),"utf8"))}catch{return!1}return void 0===e.pid||hw.isProcessAlive(e.pid)}static async runningHelperPid(){const e=await hw.readServiceState(),t=e?.pid;return void 0!==t&&hw.isProcessAlive(t)?t:void 0}static isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}static isExitedIncompatibleHelper(e){return void 0!==e.protocolMajor&&e.protocolMajor!==hw.protocolMajor&&void 0!==e.pid&&!hw.isProcessAlive(e.pid)}screenshot(e){return this.callTool(e,"computer_use_screenshot",{})}click(e,t){return this.callTool(e,"computer_use_click",{method:"coordinate",...void 0!==t.coordinate&&{x:t.coordinate.x,y:t.coordinate.y},button:t.button,count:t.count,modifier_keys:t.modifierKeys})}scroll(e,t){return this.callTool(e,"computer_use_scroll",{x:t.coordinate?.x,y:t.coordinate?.y,direction:t.direction,amount:t.amount,modifier_keys:t.modifierKeys})}move(e,t){return this.callTool(e,"computer_use_mouse_move",{x:t.x,y:t.y})}mouseButton(e,t){return this.callTool(e,"computer_use_mouse_button",{button:t.button,action:t.action})}drag(e,t){return this.callTool(e,"computer_use_drag",{button:t.button,path:t.path,modifier_keys:t.modifierKeys})}typeText(e,t){return this.callTool(e,"computer_use_typing",{value:t})}pressKey(e,t){return this.callTool(e,"computer_use_press_key",{key:t.key,hold_duration_ms:t.holdDurationMs})}checkPermissions(e){return this.callTool(e,"computer_use_check_permissions",{})}async startControl(e){if("remote"!==this.mode||void 0!==this.activeSessionId)return;hw.throwIfAborted(e.signal);const t=(0,bo.randomUUID)(),r=await this.sendWithRelaunchRetry(e,(()=>({id:hw.requestID,method:"control/start",requestID:t,mode:this.mode})),"control/start");if(void 0!==r.error)throw hw.rpcError(r);if(void 0===r.sessionId)throw new cw("local-cua control/start returned no session");this.activeSessionId=r.sessionId}async releaseControl(e){const t=this.activeSessionId;if(void 0!==t){this.activeSessionId=void 0;try{const e=await hw.readServiceState();if(void 0===e)return;const r=await hw.sendOnce(hw.socketPathFrom(e),{id:hw.requestID,method:"control/release",requestID:(0,bo.randomUUID)(),mode:this.mode,sessionId:t},hw.defaultCallTimeoutMs);if(void 0!==r.error)throw hw.rpcError(r)}catch(t){hw.logger.warn(e,"local-cua control release failed",{error:lw(t)})}}}async callTool(e,t,r){hw.throwIfAborted(e.signal);const n=hw.defaultCallTimeoutMs,o=await this.sendWithRelaunchRetry(e,(()=>{const e=Date.now()/1e3,o=this.activeSessionId;return{id:hw.requestID,method:"tools/call",requestID:(0,bo.randomUUID)(),name:t,arguments:r,timeoutSeconds:n/1e3,startedAtEpochSeconds:e,deadlineEpochSeconds:e+n/1e3,mode:this.mode,...void 0!==o&&{sessionId:o}}}),t);if(void 0!==o.error)throw hw.rpcError(o,t);const s=o.result;if(void 0===s)throw new cw(`local-cua tool ${t} returned no result`,{tool:t});if(s.isError){const e=s.message.trim();throw new cw(e.length>0?e:`local-cua tool ${t} reported an error`,{tool:t,userFacing:e.length>0})}return s}async sendWithRelaunchRetry(e,t,r){const n=hw.defaultCallTimeoutMs,o=await this.ensureSocketPath(e);hw.throwIfAborted(e.signal);try{return await hw.sendOnce(o,t(),n,e.signal)}catch(o){if(!hw.isPreDeliveryConnectionError(o))throw o;hw.logger.warn(e,"local-cua callTool failed; relaunching and retrying",{tool:r,error:hw.spawnErrorCode(o)});const s=await this.ensureSocketPath(e,!0);return hw.throwIfAborted(e.signal),void 0!==this.activeSessionId&&(this.activeSessionId=void 0,await this.startControl(e)),await hw.sendOnce(s,t(),n,e.signal)}}static rpcError(e,t){return new cw(e.error,{code:e.errorCode,userFacing:!0,tool:t})}async ensureSocketPath(e,t=!1){if(hw.throwIfAborted(e.signal),!t){const e=await hw.readServiceState();if(e&&!hw.isExitedIncompatibleHelper(e))return hw.socketPathFrom(e)}await this.launchAndWait(e);const r=await hw.readServiceState();if(!r)throw new cw("local-cua sidecar did not publish service.json after launch");return hw.socketPathFrom(r)}static setLaunchGuard(e){hw.launchGuard=e}async launchAndWait(e){const t=hw.serviceAppPath(),r=hw.launchGuard,n=()=>this.launchAppAndWait(e,t);await(void 0===r?n():r(t,n,e.signal))}async launchAppAndWait(e,t){hw.logger.info(e,"launching local-cua sidecar",hw.sidecarLaunchLogFields(t)),"1"===process.env[hw.directLaunchEnv]?await hw.spawnSidecarProcess(e,hw.serviceExecutablePath(),[],{detached:!0}):await hw.spawnSidecarProcess(e,"/usr/bin/open",["-g",t]);const r=Date.now()+hw.launchReadyTimeoutMs;for(;Date.now()0?e:s.join(o.homedir(),...hw.sharedInstallRelativePath,`${hw.serviceAppBundleName}.app`)}static helperIdentity(){const e=hw.serviceAppPath(),t=process.env[hw.appSupportOverrideEnv],r=`${e}\0${t??""}`,n=hw.identityCache;if(n?.key===r)return n.identity;const i=function(e){let t;try{t=(0,xo.readFileSync)(s.join(e,"Contents","Info.plist"),"utf8")}catch{return{}}const r=e=>{const r=new RegExp(`${e}\\s*([^<]*)`).exec(t)?.[1];return void 0!==r&&dw.test(r.trim())?r.trim():void 0};return{executableName:r("CFBundleExecutable"),bundleIdentifier:r("CFBundleIdentifier")}}(e),a=s.join(e,"Contents","MacOS",i.executableName??hw.productionExecutableName),c={appPath:e,executablePath:a,appSupportDirectory:void 0!==t&&t.length>0?t:s.join(o.homedir(),"Library","Application Support",(void 0===i.bundleIdentifier?void 0:uw.get(i.bundleIdentifier))??hw.appSupportFolder)};return(0,xo.existsSync)(a)&&(hw.identityCache={key:r,identity:c}),c}static sidecarLaunchLogFields(e){const t=`${hw.serviceAppBundleName}.app`;return{appName:s.basename(e)===t?t:"custom",appPathHash:(0,bo.createHash)("sha256").update(e).digest("hex"),usingOverride:Boolean(process.env[hw.serviceAppOverrideEnv])}}static spawnErrorCode(e){return lw(e)}static socketError(e){const t=lw(e);return new cw(`local-cua RPC connection failed: ${t}`,{code:t})}static serviceExecutablePath(){return hw.helperIdentity().executablePath}static spawnSidecarProcess(e,t,r,n){return new Promise(((o,s)=>{const i=(0,ou.spawn)(t,[...r],{detached:!0===n?.detached,stdio:"ignore"}),a=e=>{s(new cw(`local-cua sidecar launch failed: ${hw.spawnErrorCode(e)}`))};i.once("error",a),i.once("spawn",(()=>{i.removeListener("error",a),i.on("error",(t=>{hw.logger.warn(e,"local-cua sidecar process error after launch",{error:hw.spawnErrorCode(t)})})),i.unref(),o()}))}))}static async readServiceState(){try{const e=await(0,Co.readFile)(hw.serviceStatePath(),"utf8");return aw.parseServiceState(e)}catch(e){if(e instanceof Error&&"code"in e&&"ENOENT"===e.code)return;if(e instanceof ew)return;throw new cw("local-cua service state could not be read")}}static socketPathFrom(e){if(void 0!==e.protocolMajor&&e.protocolMajor!==hw.protocolMajor)throw new cw(`The running Cursor Computer Use speaks protocol ${e.protocolMajor}, and this Cursor CLI speaks protocol ${hw.protocolMajor}. Update the Cursor CLI.`,{userFacing:!0});return e.rpcSocketPath}static abortError(e){return e.reason instanceof Error?e.reason:new cw("local-cua RPC aborted")}static throwIfAborted(e){if(e.aborted)throw hw.abortError(e)}static sendOnce(e,t,r,n){return n?.aborted?Promise.reject(hw.abortError(n)):new Promise(((o,s)=>{let i=!1,a=[],c=0,l=!1;const u=(0,Qg.createConnection)({path:e}),d=e=>{i||(i=!0,clearTimeout(p),n?.removeEventListener("abort",h),u.destroy(),e())},h=()=>{d((()=>s(void 0===n?new cw("local-cua RPC aborted"):hw.abortError(n))))},p=setTimeout((()=>{d((()=>s(new cw(`local-cua RPC timed out after ${r}ms`))))}),r);n?.addEventListener("abort",h,{once:!0}),n?.aborted?h():(u.on("connect",(()=>{u.write(`${JSON.stringify(t)}\n`,(e=>{null==e?l=!0:d((()=>s(hw.socketError(e))))}))})),u.on("data",(e=>{const t=e.indexOf(10),r=c+(t<0?e.length:t);if(r>aw.responseMaxBytes)return void d((()=>s(new cw("local-cua RPC response exceeded the size limit"))));if(t<0)return a.push(e),void(c+=e.length);a.push(e.subarray(0,t));const n=Buffer.concat(a,r);a=[],c=0;try{const e=aw.parseResponse({line:n,expectedID:hw.requestID});d((()=>o(e)))}catch(e){d((()=>s(e)))}})),u.on("error",(e=>{d(l?()=>s(new cw("local-cua RPC connection failed after request delivery")):()=>s(hw.socketError(e)))})),u.on("close",(()=>{const e=c>0?"local-cua RPC response ended without a newline":l?"local-cua RPC connection closed after request delivery":"local-cua RPC connection closed";d((()=>s(new cw(e))))})))}))}}let pw;function fw(){if(void 0===pw){const e=async function(){const[{createJimp:e},{default:t},{default:n},{default:o,msBmp:s},{default:i},{default:a},{methods:c}]=await Promise.all([Promise.all([r.e(731),r.e(250)]).then(r.bind(r,"../../node_modules/.pnpm/@jimp+core@1.6.0/node_modules/@jimp/core/dist/esm/index.js")),r.e(690).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-png@1.6.0/node_modules/@jimp/js-png/dist/esm/index.js")),r.e(831).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-jpeg@1.6.0/node_modules/@jimp/js-jpeg/dist/esm/index.js")),Promise.all([r.e(731),r.e(284)]).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-bmp@1.6.0/node_modules/@jimp/js-bmp/dist/esm/index.js")),r.e(295).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-gif@1.6.0/node_modules/@jimp/js-gif/dist/esm/index.js")),r.e(181).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-tiff@1.6.0/node_modules/@jimp/js-tiff/dist/esm/index.js")),r.e(162).then(r.bind(r,"../../node_modules/.pnpm/@jimp+plugin-resize@1.6.0/node_modules/@jimp/plugin-resize/dist/esm/index.js"))]);return e({formats:[t,n,o,s,i,a],plugins:[c]})}().catch((t=>{throw pw===e&&(pw=void 0),t}));pw=e}return pw}hw.logger=(0,l.h)("local-cua:rpc"),hw.serviceAppBundleName="Cursor Computer Use",hw.appSupportFolder="cursor-computer-use",hw.productionExecutableName="CUCursorService",hw.sharedInstallRelativePath=[".cursor","computer-use-sidecar"],hw.appSupportOverrideEnv="CUA_APP_SUPPORT_DIR",hw.serviceAppOverrideEnv="CUA_SERVICE_APP",hw.directLaunchEnv="CUA_DIRECT_LAUNCH",hw.protocolMajor=1,hw.defaultCallTimeoutMs=45e3,hw.launchReadyTimeoutMs=8e3,hw.launchPollIntervalMs=200,hw.requestID=1;var mw=r("node:module");const gw="mac-webp-runtime.cjs";function ww(e){return"function"==typeof e}function yw(e){return"object"==typeof e&&null!==e&&"getFileName"in e&&"function"==typeof e.getFileName}function vw(){const e=(new Error).stack;return Array.isArray(e)?e.filter(yw):[]}let bw,Sw;function kw(){return bw??=(()=>{const e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;const e=vw()[0]?.getFileName();return function(){const e=mw;if("createRequire"in e&&ww(e.createRequire))return e.createRequire;if("default"in e&&"object"==typeof e.default&&null!==e.default&&"createRequire"in e.default&&ww(e.default.createRequire))return e.default.createRequire;throw new Error("node:module createRequire is unavailable")}()("string"==typeof e&&e.length>0?e:(0,s.join)(process.cwd(),"package.json"))}finally{Error.prepareStackTrace=e}})(),bw}function _w(){const e=globalThis.__MAC_WEBP_IMPORT__;return"function"==typeof e?t=>Promise.resolve(e(t)):(Sw??=function(){const e=[],t=new Set,r=r=>{t.has(r)||(t.add(r),e.push(r))};for(const e of function(){const e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;const e=[];for(const t of vw()){const r=t.getFileName();"string"==typeof r&&r.length>0&&e.push(r)}return e}finally{Error.prepareStackTrace=e}}()){const t=(0,s.dirname)((n=e).startsWith("file:")?(0,Ed.fileURLToPath)(n):n);r((0,s.join)(t,gw)),r((0,s.join)(t,"..","..","src","computer-use",gw))}var n;"string"==typeof process.argv[1]&&process.argv[1].length>0&&r((0,s.join)((0,s.dirname)(process.argv[1]),gw)),r((0,s.join)(process.cwd(),"src","computer-use",gw)),r((0,s.join)(process.cwd(),"computer-use",gw));try{const e=(0,s.dirname)(kw().resolve("@anysphere/local-exec/package.json"));r((0,s.join)(e,"src","computer-use",gw)),r((0,s.join)(e,"dist","computer-use",gw))}catch{}for(const t of e)try{const e=kw()(t);if("object"==typeof e&&null!==e&&"importFile"in e&&"function"==typeof e.importFile)return e.importFile.bind(e)}catch{}throw new Error("mac-webp runtime importer was not found next to the bundle")}(),Sw)}function Cw(...e){return t=["@jsquash","webp",...e].join("/"),kw().resolve(t);var t}async function Ew(...e){var t;return await(t=(0,Ed.pathToFileURL)(Cw(...e)).href,_w()(t))}const xw=e=>{let t;return()=>{if(void 0===t){const r=e();r.catch((()=>{t===r&&(t=void 0)})),t=r}return t}},Pw=(xw((async()=>{const e=await Ew("decode.js");return await e.init({wasmBinary:await xo.promises.readFile(Cw("codec","dec","webp_dec.wasm"))}),e})),xw((async()=>{const[e,t,r]=await Promise.all([Ew("utils.js"),Ew("meta.js"),Ew("codec","enc","webp_enc.js")]);return{module:await e.initEmscriptenModule(r.default,void 0,{wasmBinary:await xo.promises.readFile(Cw("codec","enc","webp_enc.wasm"))}),defaultOptions:t.defaultOptions}}))),Rw="image/png",Iw={async normalize(e){if(e.mimeType!==Rw)throw new Error(`Mac screenshot must be ${Rw}, received ${e.mimeType}`);const t=await fw(),r=await t.read(Buffer.from(e.data,"base64"));return(await(n={data:r.bitmap.data,width:r.bitmap.width,height:r.bitmap.height},(async e=>{const{module:t,defaultOptions:r}=await Pw(),n=new Uint8ClampedArray(e.data.buffer,e.data.byteOffset,e.data.byteLength);return Buffer.from(t.encode(n,e.width,e.height,{...r,lossless:1,exact:1}))})(n))).toString("base64");var n}},Tw={userFacing:function(e){if(e instanceof cw&&e.userFacing&&e.message.trim().length>0&&!Yg(e.message))return e.message.trim()},isCaptureBlocked:function(e){return e instanceof cw&&("computer_use_screenshot"===e.tool||"permission_required"===e.code)}},Aw=new Set(["keys"]),$w=new Set(["matched","mismatch","unchecked"]),Mw=new Set(["no_text","password","control_keys","too_long","unreadable","moved","chromium","gecko"]),Dw=new Set(["matched"]),Ow=new Set(["too_long"]),Fw=new Set(["watched","fell_back","unavailable","over_budget"]);class Nw{constructor({ctx:e,actions:t,sidecar:r,errors:n,reportTyping:o}){this.startTime=Date.now(),this.typingNotes=[],this.typing=[],this.geometryPrimed=!1,this.actionCount=0,this.hasCompletedActuation=!1,this.staleAfterWait=!1,this.ctx=e,this.actions=t,this.sidecar=r,this.errors=n??Tw,this.reportTyping=!0===o}async execute(){const e=this.actions.some((e=>Nw.isInputAction(e.action.case)));try{this.throwIfAborted(),e&&await this.sidecar.startControl(this.ctx);for(const e of this.actions){this.throwIfAborted();const t=e.action;if(void 0===t.case)throw new Error("Computer use action case is undefined");switch(this.actionCount+=1,t.case){case"screenshot":case"cursorPosition":await this.captureScreen();break;case"click":void 0!==t.value.coordinate&&await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.click(this.ctx,{coordinate:t.value.coordinate,button:Nw.mouseButtonName(t.value.button),count:t.value.count>0?t.value.count:1,modifierKeys:t.value.modifierKeys}),t.value.coordinate);break;case"scroll":void 0!==t.value.coordinate&&await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.scroll(this.ctx,{coordinate:t.value.coordinate,direction:Nw.scrollDirectionName(t.value.direction),amount:t.value.amount>0?t.value.amount:3,modifierKeys:t.value.modifierKeys}),t.value.coordinate);break;case"mouseMove":if(void 0===t.value.coordinate)throw new Error("MouseMoveAction requires coordinate");await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.move(this.ctx,{x:t.value.coordinate.x,y:t.value.coordinate.y}),t.value.coordinate);break;case"mouseDown":this.recordActuation(await this.sidecar.mouseButton(this.ctx,{button:Nw.mouseButtonName(t.value.button),action:"down"}));break;case"mouseUp":this.recordActuation(await this.sidecar.mouseButton(this.ctx,{button:Nw.mouseButtonName(t.value.button),action:"up"}));break;case"drag":{const e=t.value.path.map((e=>({x:e.x,y:e.y})));await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.drag(this.ctx,{button:Nw.mouseButtonName(t.value.button),path:e,modifierKeys:t.value.modifierKeys}),e.at(-1));break}case"type":{const e=await this.sidecar.typeText(this.ctx,t.value.text);this.recordActuation(e),this.recordTyping(e);break}case"key":if(t.value.stroke===Og.EB.DOWN||t.value.stroke===Og.EB.UP)throw new Error("Held keys (KeyAction.stroke DOWN/UP) are not supported by the computer-use sidecar; use hold_duration_ms");this.recordActuation(await this.sidecar.pressKey(this.ctx,{key:t.value.key,holdDurationMs:t.value.holdDurationMs}));break;case"wait":await this.delay(Math.max(0,t.value.durationMs)),this.staleAfterWait=!0;break;default:{const e=t;throw new Error(`Unknown computer use action: ${JSON.stringify(e)}`)}}}this.throwIfAborted(),(void 0===this.screenshot||this.staleAfterWait)&&await this.captureScreen(),this.throwIfAborted();const t=await this.normalizeRetainedScreenshots();return t.screenshotFailed&&!this.hasCompletedActuation?this.screenshotUnavailableResult(t.failureReason):(this.throwIfAborted(),new Og.ks({result:{case:"success",value:new Og.Wd({actionCount:this.actionCount,durationMs:Date.now()-this.startTime,screenshot:t.screenshot,cursorPosition:this.cursor,log:this.log(t.screenshotFailed?"Screenshot unavailable":void 0),typing:this.typing})}}))}catch(e){return this.ctx.signal.aborted?this.abortedResult():this.errorResult(e)}finally{e&&await this.sidecar.releaseControl(this.ctx)}}static isInputAction(e){switch(e){case"click":case"scroll":case"mouseMove":case"mouseDown":case"mouseUp":case"drag":case"type":case"key":return!0;default:return!1}}async captureScreen(){const e=await this.sidecar.screenshot(this.ctx);this.screenshot=e.screenshot,this.cursor=Nw.cursorFromResult(e)??this.cursor,this.geometryPrimed=!0,this.staleAfterWait=!1}async ensureGeometryCached(){this.geometryPrimed||await this.captureScreen()}recordActuation(e,t){this.screenshot=e.screenshot,this.hasCompletedActuation=!0,this.staleAfterWait=!1,void 0!==e.screenshot&&(this.geometryPrimed=!0),this.cursor=Nw.cursorFromResult(e)??Nw.coordinateFromPoint(t)??this.cursor}recordTyping(e){if(!this.reportTyping)return;const t=e.message.trim();""!==t&&this.typingNotes.push(t);const r=Nw.typingFromResult(e);void 0!==r&&this.typing.push(r)}log(e){const t=void 0===e?this.typingNotes:[...this.typingNotes,e];return 0===t.length?void 0:t.join("\n")}static typingFromResult(e){const t=e.structuredContent;if("object"!=typeof t||null===t||!("type"in t))return;const r=t.type;if("object"!=typeof r||null===r)return;const n=new Map(Object.entries(r)),o=(e,t)=>{const r=n.get(e);return"string"==typeof r&&t.has(r)?r:void 0},s=e=>{const t=n.get(e);return"number"==typeof t&&Number.isInteger(t)&&t>=0?t:void 0},i=o("check",$w),a=o("unchecked",Mw),c=void 0!==n.get("unchecked")&&null!==n.get("unchecked"),l=void 0!==i&&Dw.has(i)&&!c||"unchecked"===i&&void 0!==a&&Ow.has(a);return new Og.qA({method:o("method",Aw)??"",chars:l?s("chars")??0:0,atoms:l?s("atoms")??0:0,typedAtoms:l?s("typedAtoms")??0:0,aborted:!0===n.get("aborted"),check:i,verified:l?s("verified"):void 0,unchecked:a,landing:o("landing",Fw)})}async errorResult(e){let t;if(Nw.logger.error(this.ctx,"local-cua execute failed",void 0,{error:lw(e)}),!this.errors.isCaptureBlocked(e))try{const e=await this.sidecar.screenshot(this.ctx);t=(await this.normalizeScreenshot(e.screenshot,"error")).data}catch(e){Nw.logger.warn(this.ctx,"local-cua error screenshot capture failed",{error:lw(e)})}const r=this.errors.userFacing(e);return new Og.ks({result:{case:"error",value:new Og.Jb({error:void 0===r?"Computer use failed":`Computer use failed: ${r}`,actionCount:this.actionCount,durationMs:Date.now()-this.startTime,screenshot:t,log:this.log(),typing:this.typing})}})}screenshotUnavailableResult(e){return new Og.ks({result:{case:"error",value:new Og.Jb({error:"Screenshot unavailable",actionCount:this.actionCount,durationMs:Date.now()-this.startTime,log:e})}})}abortedResult(){return new Og.ks({result:{case:"error",value:new Og.Jb({error:"Computer use aborted",actionCount:this.actionCount,durationMs:Date.now()-this.startTime,log:this.log(),typing:this.typing})}})}static mouseButtonName(e){return Nw.mouseButtonNames[e]??"left"}static scrollDirectionName(e){return Nw.scrollDirectionNames[e]??"down"}async normalizeRetainedScreenshots(){const e=await this.normalizeScreenshot(this.screenshot,"post-action");return{screenshot:e.data,screenshotFailed:void 0===this.screenshot||e.failed,failureReason:void 0===this.screenshot?"sidecar returned no image":e.reason}}async normalizeScreenshot(e,t){if(void 0===e)return{failed:!1};try{return{data:await Iw.normalize(e),failed:!1}}catch(r){const n=lw(r);return Nw.logger.error(this.ctx,"local-cua screenshot conversion failed",void 0,{frame:t,error:n}),"image/png"===e.mimeType&&e.data.length>0?{data:e.data,failed:!1}:{failed:!0,reason:n}}}static coordinateFromPoint(e){if(void 0!==e&&Number.isFinite(e.x)&&Number.isFinite(e.y))return new Og.xp({x:Math.round(e.x),y:Math.round(e.y)})}static cursorFromResult(e){const t=e.structuredContent;if("object"!=typeof t||null===t||!("cursor"in t))return;const r=t.cursor;return"object"==typeof r&&null!==r&&"x"in r&&"y"in r&&"number"==typeof r.x&&"number"==typeof r.y&&Number.isFinite(r.x)&&Number.isFinite(r.y)?new Og.xp({x:Math.round(r.x),y:Math.round(r.y)}):void 0}throwIfAborted(){if(this.ctx.signal.aborted)throw this.ctx.signal.reason??new Error("Computer use aborted")}delay(e){return this.throwIfAborted(),new Promise(((t,r)=>{const n=()=>{clearTimeout(o),r(this.ctx.signal.reason??new Error("Computer use aborted"))},o=setTimeout((()=>{this.ctx.signal.removeEventListener("abort",n),t()}),e);this.ctx.signal.addEventListener("abort",n,{once:!0}),this.ctx.signal.aborted&&n()}))}}Nw.logger=(0,l.h)("local-cua:actions"),Nw.mouseButtonNames={[Og.w3.UNSPECIFIED]:"left",[Og.w3.LEFT]:"left",[Og.w3.RIGHT]:"right",[Og.w3.MIDDLE]:"middle",[Og.w3.BACK]:"left",[Og.w3.FORWARD]:"left"},Nw.scrollDirectionNames={[Og.Dh.UNSPECIFIED]:"down",[Og.Dh.UP]:"up",[Og.Dh.DOWN]:"down",[Og.Dh.LEFT]:"left",[Og.Dh.RIGHT]:"right"},s.default.join(o.default.tmpdir(),"computer-use"),(0,l.h)("local-cua:windows");Error,Buffer.from([137,80,78,71,13,10,26,10]),new Set(["capture_failed","secure_desktop","input_desktop_unavailable","sidecar_unavailable","user_aborted","session_busy","canvas_mismatch"]);var Lw,jw=r("../proto/dist/generated/agent/v1/delete_exec_pb.js");function Uw({encoding:e,bom:t,lineEnding:r}){return{encoding:e,bom:t,lineEnding:r}}class Bw{constructor(e){this.workspacePath=e,this.changes=new Map,this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){for(const t of this.listeners)t(e)}async trackChange(e,t,r,n,o){const s=this.changes.get(e);if(s){const t=s.before,o=n||s.metadata;if(t===r||void 0===t&&void 0===r)this.changes.delete(e),this.notify();else{const n={path:e,before:t,after:r,metadata:o,...void 0===s.beforeFormat?{}:{beforeFormat:s.beforeFormat}};this.changes.set(e,n),this.notify(n)}}else{const s={path:e,before:t,after:r,metadata:n,...void 0===o?{}:{beforeFormat:o}};this.changes.set(e,s),this.notify(s)}}getChanges(){return Array.from(this.changes.values())}getChange(e){return this.changes.get(e)}hasChange(e){return this.changes.has(e)}accept(e){const t=this.changes.get(e);this.changes.delete(e),this.notify(t)}acceptAll(){this.changes.clear(),this.notify()}async reject(e){const t=this.changes.get(e);if(t)try{void 0===t.before&&void 0!==t.after?await(0,Co.unlink)(e):(void 0!==t.before&&void 0===t.after||void 0!==t.before&&void 0!==t.after)&&await async function(e,t,r,n){const{buffer:o,format:s}=await Wi(e,t,r,n);await(0,Co.writeFile)(e,o),await Bi(e,{buffer:o,encoding:s.encoding})}(e,t.before,this.workspacePath)}catch{}finally{this.changes.delete(e),this.notify(t)}}async rejectAll(){const e=Array.from(this.changes.keys());await Promise.all(e.map((e=>this.reject(e))))}clear(){const e=this.changes.values().next().value;this.changes.clear(),this.notify(e)}get size(){return this.changes.size}dispose(){this.changes.clear(),this.listeners.clear()}}!function(e){e.Write="write",e.Read="read",e.Shell="shell",e.Delete="delete",e.Mcp="mcp"}(Lw||(Lw={}));var Ww=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class Hw{constructor(e,t,r,n,o,s){this.pendingDecisionProvider=e,this.fileChangeTracker=t,this.permissionsService=r,this.workspacePath=n,this.onDeleteForAiTracking=o,this.agentFileViews=s}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,$.VI)(e.withName("LocalDeleteExecutor.execute")),!1);const n=t.path;if(""===n.trim())return new jw.Pi({result:{case:"error",value:new jw.GU({path:n,error:es})}});const o=(0,Yo.o1)(n,this.workspacePath),i=await this.permissionsService.shouldBlockWrite(e,o,"");if(i){const e=await Qu(i,{onNeedsApproval:async(e,t)=>null,onUserRejected:e=>new jw.Pi({result:{case:"rejected",value:new jw.iq({path:o,reason:e||""})}}),onPermissionDenied:(e,t)=>new jw.Pi({result:{case:"permissionDenied",value:new jw.QG({path:o,clientVisibleError:e,isReadonly:t?.isReadonly??!1})}})});if(null!==e)return e}const a=await async function(e,t){const r=await(0,Co.realpath)((0,s.dirname)(e)).catch((()=>{}));if(void 0===r)return e;if(void 0!==t){const n=await(0,Co.realpath)(t).catch((()=>{}));if(void 0!==n&&(0,Yo.BJ)(r,n))return(0,s.resolve)(t,(0,s.relative)(n,r),(0,s.basename)(e))}return(0,s.join)(r,(0,s.basename)(e))}(o,this.workspacePath),c=await this.pendingDecisionProvider.requestApproval({type:Lw.Delete,details:{path:a},toolCallId:t.toolCallId});if(!c.approved)return new jw.Pi({result:{case:"rejected",value:new jw.iq({path:o,reason:c.reason||""})}});let l;try{l=await(0,Co.stat)(o)}catch(e){return"ENOENT"===Sc(e)?new jw.Pi({result:{case:"fileNotFound",value:new jw.n0({path:o})}}):new jw.Pi({result:{case:"error",value:new jw.GU({path:o,error:kc(e)})}})}if(!l.isFile()){const e=l.isDirectory()?"directory":"other";return new jw.Pi({result:{case:"notFile",value:new jw.LX({path:o,actualType:e})}})}const u=l.size;let d,h;if(u<=ns)try{const e=await Ui(o);d=e.text,h=Uw(e)}catch{}const p=d??"",f=await(0,Co.realpath)(o).catch((()=>o)),m=await(0,Co.stat)(o).catch((()=>{}));if(m?.dev!==l.dev||m.ino!==l.ino)return new jw.Pi({result:{case:"error",value:new jw.GU({path:o,error:"File changed while deleting; nothing was removed"})}});e.signal.throwIfAborted();try{await(0,Co.unlink)(o),this.agentFileViews?.recordDelete(o)}catch(e){return"EACCES"===Sc(e)?new jw.Pi({result:{case:"permissionDenied",value:new jw.QG({path:o,clientVisibleError:"Permission denied"})}}):"EBUSY"===Sc(e)?new jw.Pi({result:{case:"fileBusy",value:new jw.vX({path:o})}}):new jw.Pi({result:{case:"error",value:new jw.GU({path:o,error:kc(e)})}})}if(this.fileChangeTracker&&void 0!==d){const e={...t.toolCallId?{toolCallId:t.toolCallId}:{},...f===o?{}:{writtenPath:f},beforeMode:511&l.mode};await this.fileChangeTracker.trackChange(o,d,void 0,e,h)}return this.onDeleteForAiTracking&&this.onDeleteForAiTracking({path:o}).catch((()=>{})),new jw.Pi({result:{case:"success",value:new jw.fl({path:o,deletedFile:o,fileSize:BigInt(u),prevContent:p})}})}catch(e){r.error=e,r.hasError=!0}finally{Ww(r)}}}class qw{constructor(e,t){this.inner=e,this.extraTools=t}async getTools(e){return[...await this.inner.getTools(e).catch((()=>[])),...this.extraTools]}async getToolsForServers(e,t){const r=await this.inner.getToolsForServers(e,t).catch((()=>[])),n=new Set(t);return[...r,...this.extraTools.filter((e=>n.has(e.clientKey)||n.has(e.providerIdentifier)))]}async getClients(e){return this.inner.getClients(e)}async getClient(e,t){return this.inner.getClient(e,t)}async getInstructions(e){const t=await this.inner.getInstructions(e).catch((()=>[])),r=this.extraTools.filter((e=>e.providerIdentifier===zn));if(0===r.length)return t;const n=r.map((e=>{const t="string"==typeof e.description&&e.description.length>0?e.description:"(no description provided)";return`- ${e.toolName}: ${t}`})).join("\n");return[...t,new wn.I0({serverIdentifier:zn,serverName:zn,instructions:`User-defined tools for this session (server "${zn}"). Discover schemas via MCP meta-tool discovery for that server, then invoke via the MCP invocation meta-tool.\n\nAvailable tools:\n${n}`})]}async getToolSet(e){return this.inner.getToolSet(e)}}class zw extends qw{constructor(e,t){super(e,t),this.observableInner=e}onDidChange(e){return this.observableInner.onDidChange(e)}}var Gw=r("../proto/dist/generated/agent/v1/fetch_exec_pb.js"),Vw=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Kw=/;\s*charset\s*=\s*"?([^";\s]+)/i;class Jw{constructor(e){this.encodingSlices=e?.encodingSlices}async readText(e,t){if(!Ul(this.encodingSlices,e))return await t.text();const r=async function(e,t){if(void 0===e)return"unseen";try{return(0,n.isUtf8)(await e.arrayBuffer())?"utf8_valid":t?"declared_other":"utf8_invalid"}catch{return"unseen"}}(function(e){try{return e.clone()}catch{return}}(t),function(e){const t=Kw.exec(e.headers.get("content-type")??"")?.[1];return void 0!==t&&!/^utf-?8$/i.test(t)}(t)),o=await t.text();return this.recordFetched(e,o,r),o}async recordFetched(e,t,r){try{Yl(this.encodingSlices,e,{layer:"exec_web_fetch",evidence:await r},t)}catch{}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,$.VI)(e.withName("LocalFetchExecutor.execute")),!1);const n=t.url;try{const t=await fetch(n),r=await this.readText(e,t),o=t.headers.get("content-type")||"text/plain";return new Gw.uN({result:{case:"success",value:new Gw.Uk({url:n,content:r,statusCode:t.status,contentType:o})}})}catch(e){return new Gw.uN({result:{case:"error",value:new Gw.fk({url:n,error:kc(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{Vw(r)}}}const Zw=[["safe.bareRepository","explicit"]],Xw=[["core.fsmonitor","false"],["core.hooksPath",o.devNull],["core.attributesFile",o.devNull]],Qw=[["core.quotePath","false"]];function Yw(e){const t="allow-hooks"===e?Xw.filter((([e])=>"core.hooksPath"!==e)):Xw;return[...Zw,...t]}const ey=(0,zs.promisify)(ou.execFile),ty=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env","--attr-source"]),ry=new Set(["diff","show","blame","log","whatchanged"]);function ny(e){for(let t=0;t["-c",`${e}=${t}`]))}const gy=my([...Yw("block"),["submodule.recurse","false"],["fetch.recurseSubmodules","false"],["diff.submodule","short"],["status.submoduleSummary","false"],["log.showSignature","false"],["log.diffMerges","separate"],["gpg.openpgp.program",o.devNull],["gpg.x509.program",o.devNull],["gpg.ssh.program",o.devNull]]);function wy(e){const t=e?.timeout??0,r=Number.isFinite(t)&&t>0?Math.min(t,2147483647):6e4;return performance.now()+r}function yy(e,t=2147483647){return Math.max(1,Math.ceil(Math.min(t,e-performance.now())))}function vy(){const e=new Map;return{async exec(t,r,n){const o=wy(n);return ay("git",await by(e,t,r,o),{cwd:t,env:fy,windowsHide:!0,killSignal:"SIGTERM",timeout:yy(o)})},async run(t,r,n){const o=wy(n);return function(e,t,r,n){return new Promise(((o,s)=>{const i=function(e,t,r){const{env:n,...o}=r??{},s=sy(t);return(0,ou.spawn)("git",s,{...o,env:iy(s,n)})}(0,t,{cwd:e,env:fy,windowsHide:!0,stdio:[void 0===n?"ignore":"pipe","pipe","pipe"]}),a=[],c=[];let l=!1;const u=()=>{const e=!l;return l=!0,clearTimeout(d),e},d=setTimeout((()=>{u()&&(i.kill("SIGTERM"),i.stdin?.destroy(),i.stdout?.destroy(),i.stderr?.destroy(),s(Object.assign(new Error("git timed out"),{code:null,killed:!0,signal:"SIGTERM"})))}),yy(r));i.stdout?.on("data",(e=>{a.push(e)})),i.stderr?.on("data",(e=>{c.push(e)}));for(const e of[i.stdout,i.stderr])e?.on("error",(e=>{u()&&(i.kill("SIGTERM"),s(e))}));i.on("error",(e=>{u()&&s(e)})),i.on("close",((e,t)=>{u()&&(null!==e?o({exitCode:e,stdout:Buffer.concat(a).toString("utf8"),stderr:Buffer.concat(c).toString("utf8")}):s(Object.assign(new Error(`git was killed by ${String(t)}`),{code:e,killed:!1,signal:t})))})),void 0!==n&&null!==i.stdin&&(i.stdin.on("error",(()=>{})),i.stdin.end(n))}))}(t,await by(e,t,r,o),o,n?.input)}}}async function by(e,t,r,n){const{prefix:o,tail:s,readsConfig:i}=function(e){const t=sy(e),r=ny(t),n=t.findIndex(((e,t)=>t>r&&("--"===e||"--end-of-options"===e))),o=t.slice(0,-1===n?t.length:n);if(o.includes("--help")||o.includes("-h"))throw new TypeError("git help is refused: it starts the repository's man viewer");if(-1===r)return{prefix:[],tail:t,readsConfig:!1};const s=t[r],i=ly.get(s);if(void 0===i)throw new TypeError(`git ${s} is refused: the pins cover only a fixed set of verbs`);const[a,c]=i,l=o.find((e=>function(e,t,r){const n=r.startsWith("--")?r.slice(2).split("=",1)[0]:"",o=[...uy,..."status"===e?["verbose"]:[],..."worktree"===e?["checkout","no-force"]:[],...t?["ignore-submodules","no-ignore-submodules"]:[]];return""!==n&&o.some((e=>e.startsWith(n)))||"status"===e&&/^-[^-]*v/.test(r)}(s,c,e)));if(void 0!==l)throw new TypeError(`git ${s} ${l} is refused: it can start a program the pins miss`);const u=t.slice(r+1),d="worktree"===s?u.find((e=>!e.startsWith("-"))):void 0;if("remove"===d&&!o.includes("--force")&&!o.includes("-f"))throw new TypeError("git worktree remove is refused without --force");if("add"===d&&"--no-checkout"!==u[u.indexOf("add")+1])throw new TypeError("git worktree add is refused unless --no-checkout follows add");return{prefix:[...t.slice(0,r),...gy],tail:[s,...c?["--ignore-submodules=dirty"]:[],...u],readsConfig:a}}(r),a=i?await function(e,t,r,n){const o=`${t}\0${r.join("\0")}`,s=e.get(o);if(void 0!==s)return s;const i=async function(e,t,r){let n;try{n=(await ay("git",[...t,"config","--list","--show-scope","--includes","-z"],{cwd:e,env:fy,windowsHide:!0,killSignal:"SIGTERM",timeout:yy(r,1e4),maxBuffer:16777216})).stdout}catch(e){throw function(e){if(!(e instanceof Error))return new cy("read-failed");if("syscall"in e&&"string"==typeof e.syscall&&e.syscall.startsWith("spawn"))return e;if("killed"in e&&!0===e.killed)return new cy("timed-out");const t="code"in e&&"number"==typeof e.code?e.code:void 0;return new cy("read-failed",t)}(e)}if(performance.now()>=r)throw new cy("timed-out");return function(e){if(""===e)return[];const t=e.split("\0");if(""!==t.pop()||t.length%2!=0)throw new cy("read-failed");const r=new Set;for(let e=0;emy([[`filter.${e}.clean`,""],[`filter.${e}.smudge`,""],[`filter.${e}.process`,""],[`filter.${e}.required`,"false"]])))}(n)}(t,r,n);return e.set(o,i),i}(e,t,o,n):[];return[...o,...a,...s]}function Sy(e,t,r){return vy().exec(e,t,r)}var ky=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class _y{constructor(e={}){void 0!==e.guardedRootLookup&&(this.guardedRootLookup=e.guardedRootLookup)}async exec(e,t,r,n){return Cy(e,t,r,n,Sy)}forRequest(){const e=vy();return{exec:(t,r,n,o)=>Cy(t,r,n,o,((t,r,n)=>e.exec(t,r,n))),...void 0===this.guardedRootLookup?{}:{guardedRootLookup:this.guardedRootLookup}}}}async function Cy(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(s,(0,$.VI)(e.withName("LocalGitExecutor.exec"),{attributes:{"git.cwd":t,"git.args":r,"git.caller":n?.caller}}),!1);const{stdout:i,stderr:a}=await o(t,r,{timeout:n?.timeout});return{exitCode:0,stdout:i,stderr:a}}catch(e){s.error=e,s.hasError=!0}finally{ky(s)}}var Ey=r("../proto/dist/generated/agent/v1/grep_exec_pb.js");class xy{constructor(){this.lineEnd=0,this.nextStart=0}}function Py(e,t,r){const n=e.length;if(t>=n)return!1;const o=e.indexOf("\n",t);if(-1!==o){const n=o>t&&13===e.charCodeAt(o-1);return r.lineEnd=n?o-1:o,r.nextStart=o+1,!0}return r.lineEnd=n,r.nextStart=n,!0}function Ry(e,t,r,n,o,s){const i=e.indexOf("\0",t);if(-1===i||i>=r)return;let a=i+1;for(;a=48&&e.charCodeAt(a)<=57;)a++;if(a===i+1||a>=r)return;const c=e.charCodeAt(a);if(58!==c&&45!==c)return;const l=n.indexOf(0,o);if(-1===l||l>=s)return;const u=l+(a-i);return u>=s||n.toString("latin1",l+1,u+1)!==e.slice(i+1,a+1)?void 0:{file:e.slice(t,i),contentStart:a+1,contentEnd:r,contentBytesStart:u+1,contentBytesEnd:s}}const Iy=-(2**31),Ty=2**31-1;function Ay(e){return Number.isNaN(e)?0:eTy?Ty:e}function $y(e){if("number"==typeof e&&Number.isFinite(e)&&!(e<0))return Ay(Math.trunc(e))}function My(e){const t=e.replace(/\s/g,"_").replace(/[^a-zA-Z0-9_.-]/g,"").replace(/\.+/g,".");return"."===t||".."===t?t.replace(/\./g,"_"):0===t.length?"_":t}async function Dy(e,t){const r=My(t),n=(0,s.join)(e,"mcps",r,"tools");let o;try{o=await(0,Co.readdir)(n)}catch(e){if("ENOENT"===Sc(e))return{toolNames:[],toolsDirExists:!1};throw e}const i=await Promise.all(o.map((async e=>{if(e.endsWith(".json"))try{return function(e){try{const t=JSON.parse(e);return"string"==typeof t.name&&t.name.length>0?t.name:"string"==typeof t.toolName&&t.toolName.length>0?t.toolName:void 0}catch{return}}(await(0,Co.readFile)((0,s.join)(n,e),"utf8"))}catch{return}}))),a=new Set;for(const e of i)e&&a.add(e);return{toolNames:Array.from(a).sort(((e,t)=>e.localeCompare(t))),toolsDirExists:!0}}const Oy=(0,l.h)("local-exec:mcp-disk-freshness-on-access"),Fy="/mcps/",Ny=(0,u.Pu)("mcp.discovery_freshness.check",{description:"MCP discovery surface freshness comparison outcome against canonical live tools",labelNames:["surface","outcome"]}),Ly=(0,u.v5)("mcp.discovery_freshness.missing_tools",{description:"Number of tools present in canonical live state but missing from the observed discovery surface",labelNames:["surface"]}),jy=(0,u.v5)("mcp.discovery_freshness.extra_tools",{description:"Number of tools present on the observed discovery surface but absent from canonical live state",labelNames:["surface"]}),Uy=(0,u.v5)("mcp.discovery_freshness.symmetric_difference",{description:"Total symmetric difference between canonical live tools and the observed discovery surface",labelNames:["surface"]}),By=new Map;function Wy(e){const t=e.replace(/\\/g,"/");return t.endsWith("/mcps")?`${t}/`:t}async function Hy({ctx:e,mcpStateAccessor:t,projectDir:r,sanitizedServerFolder:n,readDiskCatalog:o,state:s}){let i=s;if(void 0===i)try{i=await t.getState(e)}catch(t){return void Oy.warn(e,"mcp_disk_state_read_failed",{error_type:t instanceof Error?t.name:typeof t})}const a=i.servers.find((e=>My(e.serverIdentifier)===n));if(void 0===a)return;let c;try{c=await o(r,a.serverIdentifier)}catch(t){return void Oy.warn(e,"mcp_disk_catalog_read_failed",{error_type:t instanceof Error?t.name:typeof t})}if(!c.toolsDirExists)return;const l=a.tools.map((e=>e.toolName)).filter((e=>e.length>0)).sort(((e,t)=>e.localeCompare(t)));!function({ctx:e,serverIdentifier:t,canonicalToolNames:r,observedToolNames:n}){const o=new Set(n),s=new Set(r),i=r.filter((e=>!o.has(e))),a=n.filter((e=>!s.has(e))),c=0===i.length&&0===a.length?"match":"mismatch",l={surface:"disk"};Ny.increment(e,1,{...l,outcome:c}),Ly.histogram(e,i.length,l),jy.histogram(e,a.length,l),Uy.histogram(e,i.length+a.length,l),"mismatch"===c&&Oy.warn(e,"mcp_disk_discovery_freshness_mismatch",{server_identifier:t,missing_tool_count:i.length,extra_tool_count:a.length})}({ctx:e,serverIdentifier:a.serverIdentifier,canonicalToolNames:l,observedToolNames:c.toolNames})}function qy(e,t,r,n=Dy){if(void 0===r||(void 0===(o=r)||!Wy(o).includes(Fy)))return;var o;const s=function(e){const t=Wy(e),r=t.indexOf(Fy);if(-1===r)return;const n=t.slice(0,r),o=t.slice(r+6).split("/").filter(Boolean);return 0!==n.length?0===o.length?{projectDir:n,kind:"mcps_root"}:{projectDir:n,kind:"server",sanitizedServerFolder:o[0]}:void 0}(r);if(void 0===s)return;let i,a;const c="mcps_root"===s.kind;"mcps_root"===s.kind?(i=`${s.projectDir}\0__mcps_root__`,a=void 0):(i=`${s.projectDir}\0${s.sanitizedServerFolder}`,a=s.sanitizedServerFolder);const l=By.get(i);void 0!==l&&clearTimeout(l);const u=e,d=setTimeout((()=>{By.delete(i),(async()=>{if(c){const e=await t.getState(u);for(const r of e.servers){const o=My(r.serverIdentifier);await Hy({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:o,readDiskCatalog:n,state:e})}}else void 0!==a&&await Hy({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:a,readDiskCatalog:n})})().catch((e=>{Oy.warn(u,"mcp_disk_discovery_freshness_schedule_failed",{error_type:e instanceof Error?e.name:typeof e})}))}),2e3);By.set(i,d)}async function zy(e){try{return(await(0,Co.stat)(e,{bigint:!0})).mtimeNs}catch{return}}function Gy(e,t,r){const n=e.map(((e,n)=>({file:e,mtime:t[n],segments:e.path.split(r)})));return n.sort(((e,t)=>e.mtime!==t.mtime?void 0===e.mtime?1:void 0===t.mtime||e.mtime>t.mtime?-1:1:function({left:e,right:t}){const r=Math.min(e.length,t.length);for(let n=0;ne.file))}async function Vy(e,t,r=zy){const n=e.map((e=>({item:e,path:t(e)})));let o;try{o=await(0,Or.wj)(Promise.all(n.map((({path:e})=>r(e)))),2e3,"stat timed out")}catch(t){if(t instanceof Or.MU)return{items:[...e],statTimedOut:!0};throw t}return{items:Gy(n,o,s.sep).map((({item:e})=>e)),statTimedOut:!1}}var Ky=r("../proto/dist/generated/agent/v1/read_exec_pb.js");const Jy=Buffer.from([137,80,78,71,13,10,26,10]),Zy=Buffer.from([0,0,0,0,73,69,78,68,174,66,96,130]),Xy=e=>{if(e.lengthe.subarray(e.length-Zy.length).equals(Zy)||(e=>{let t=Jy.length+25;for(;t+Zy.length<=e.length;){const r=e.readUInt32BE(t);if(r>e.length-t-Zy.length)return!1;if("IEND"===e.toString("ascii",t+4,t+8))return e.subarray(t,t+Zy.length).equals(Zy);t+=Zy.length+r}return!1})(e))(e))return;const t=e.readUInt32BE(16),r=e.readUInt32BE(20);return t<1||r<1?void 0:{width:t,height:r,colorType:e.readUInt8(25)}},Qy=e=>1===e||e>=208&&e<=216,Yy=e=>192===e||193===e||194===e,ev=e=>e>=195&&e<=207&&196!==e&&200!==e&&204!==e,tv=e=>0===e||e>=208&&e<=215,rv=(e,t)=>{let r=e.indexOf(255,t);for(;-1!==r&&r+1(e=>{const t=Xy(e);if(void 0!==t)return{mimeType:"image/png",width:t.width,height:t.height}})(e)??(e=>{if(e.length<4||255!==e[0]||216!==e[1]||!(e=>255===e[e.length-2]&&217===e[e.length-1]||(e=>{let t=2;for(;t+2<=e.length;){if(255!==e[t])return!1;const r=e[t+1];if(255===r){t+=1;continue}if(217===r)return!0;if(Qy(r)){t+=2;continue}if(t+4>e.length)return!1;const n=e.readUInt16BE(t+2);if(n<2)return!1;const o=t+2+n;if(218!==r){t=o;continue}const s=rv(e,o);if(void 0===s)return!1;t=s}return!1})(e))(e))return;let t=2;for(;t+4<=e.length;){if(255!==e[t])return;const r=e[t+1];if(255===r){t+=1;continue}if(Qy(r)){t+=2;continue}if(218===r||217===r||ev(r))return;const n=e.readUInt16BE(t+2);if(n<2)return;if(Yy(r)){if(n<8||t+9>e.length)return;const r=e.readUInt16BE(t+5),o=e.readUInt16BE(t+7);if(o<1||r<1)return;return{mimeType:"image/jpeg",width:o,height:r}}t+=2+n}})(e),ov=(e,t)=>({width:Math.max(e?.width??0,t.width),height:Math.max(e?.height??0,t.height)}),sv=(e,t)=>{for(;t{const t=e.toString("latin1",0,6);return e.subarray(0,Jy.length).equals(Jy)?"png":t.startsWith("ÿØÿ")?"jpeg":"GIF87a"===t||"GIF89a"===t?"gif":t.startsWith("BM")?"bmp":t.startsWith("II*\0")||t.startsWith("MM\0*")?"tiff":t.startsWith("ID3")?"id3":void 0},av={0:1,2:3,4:2,6:4},cv=async({data:e,width:t,height:r})=>{const n=lv(e);if(void 0===n||t>n.width||r>n.height)return;const o=n.width*n.channels,s=new Uint32Array(n.width);for(let e=0;e{let t;const r=[];let n=8;for(;n+12<=e.length;){const o=e.readUInt32BE(n),s=e.toString("ascii",n+4,n+8),i=e.subarray(n+8,n+8+o);if(i.length!==o)return;if("IHDR"===s){const e=av[i[9]];if(void 0!==t||13!==o||8!==i[8]||0!==i[12]||void 0===e)return;t={width:i.readUInt32BE(0),height:i.readUInt32BE(4),channels:e}}else if("IDAT"===s)r.push(i);else{if("tRNS"===s)return;if("IEND"===s)break}n+=o+12}return void 0===t||0===r.length?void 0:{...t,idat:r}},uv=({filter:e,row:t,previous:r,bytesPerPixel:n})=>{if(0!==e)for(let o=0;o=n?t[o-n]:0,i=r[o];switch(e){case 1:t[o]+=s;break;case 2:t[o]+=i;break;case 3:t[o]+=s+i>>1;break;case 4:{const e=o>=n?r[o-n]:0,a=s+i-e,c=Math.abs(a-s),l=Math.abs(a-i),u=Math.abs(a-e);t[o]+=c<=l&&c<=u?s:l<=u?i:e;break}default:throw new Error(`unknown PNG filter type ${e}`)}}},dv=({row:e,channels:t,columnOf:r,sums:n,counts:o})=>{const s=t<3;for(let i=0,a=0;i{for(let s=0;s0&&(e[c]=Math.round(n[i]/a),e[c+1]=Math.round(n[i+1]/a),e[c+2]=Math.round(n[i+2]/a),e[c+3]=Math.round(a/o[s]))}n.fill(0),o.fill(0)},pv={0:1,2:3,3:1,4:2,6:4},fv=[1,2,4,8,16],mv=[[0,0,8,8],[4,0,8,8],[0,4,4,8],[2,0,4,4],[0,2,2,4],[1,0,2,2],[0,1,1,2]],gv=async e=>{const t=wv(e);if(void 0===t)return;const r=yv(t);let n=0;const o=ih.Readable.from(t.idat).pipe((0,rh.createInflate)());for await(const e of o)if(n+=e.length,n>=r)return void o.destroy();throw new Error(`PNG pixel data ends after ${n} of ${r} bytes`)},wv=e=>{let t;const r=[];let n=8;for(;n+12<=e.length;){const o=e.readUInt32BE(n),s=e.toString("ascii",n+4,n+8),i=e.subarray(n+8,n+8+o);if("IHDR"===s&&void 0===t&&13===i.length){const e=pv[i[9]];if(void 0===e||!fv.includes(i[8])||i[12]>1)return;t={width:i.readUInt32BE(0),height:i.readUInt32BE(4),bitsPerPixel:e*i[8],interlaced:1===i[12]}}else if("IDAT"===s)r.push(i);else if("IEND"===s)break;n+=o+12}return void 0===t||0===r.length?void 0:{...t,idat:r}},yv=({width:e,height:t,bitsPerPixel:r,interlaced:n})=>{const o=(e,t)=>e<=0||t<=0?0:t*(1+Math.ceil(e*r/8));return n?mv.reduce(((r,[n,s,i,a])=>r+o(Math.ceil((e-n)/i),Math.ceil((t-s)/a))),0):o(e,t)};const vv=()=>{throw new Error("webp codec not registered: registerWebpCodec() must be called by a Node server before decoding/encoding webp")},bv=e=>e.length>=12&&"RIFF"===e.toString("ascii",0,4)&&"WEBP"===e.toString("ascii",8,12),Sv=e=>{if(!bv(e)||e.length<16)return;const t=e.toString("ascii",12,16);if("VP8 "===t){if(e.length<30||157!==e[23]||1!==e[24]||42!==e[25])return;return{width:16383&(e[26]|e[27]<<8),height:16383&(e[28]|e[29]<<8)}}if("VP8L"===t){if(e.length<25||47!==e[20])return;const t=(e[21]|e[22]<<8|e[23]<<16|e[24]<<24)>>>0;return{width:1+(16383&t),height:1+(t>>14&16383)}}if("VP8X"===t){if(e.length<30)return;return{width:1+(e[24]|e[25]<<8|e[26]<<16),height:1+(e[27]|e[28]<<8|e[29]<<16)}}},kv=e=>vv().decode(e);async function _v(e){((e,t)=>{if(!Number.isSafeInteger(e)||e<1||e>t)throw new Error("pngByteBudgetBytes must be a positive integer at most MAX_IMAGE_SIZE_BYTES")})(e.budgetBytes,e.maxImageBytes);nv(e.data);return e.resizeWithoutBudget(e.data)}const Cv=[{width:1280,height:800},{width:1456,height:840}],Ev=e=>void 0!==e&&Cv.some((t=>t.width===e.width&&t.height===e.height)),xv=1048576,Pv=e=>{const t=e.buffer;return t instanceof ArrayBuffer?new Uint8Array(t,e.byteOffset,e.byteLength):Uint8Array.from(e)};function Rv(e,t,r=1024){if(e<1||t<1)return{width:e,height:t,needsResize:!1};const n=Math.max(e,t);if(n<=r)return{width:e,height:t,needsResize:!1};const o=Math.min(e,t);if(o<8)return{width:e,height:t,needsResize:!1};let s=r/n,i=Math.max(1,Math.round(e*s)),a=Math.max(1,Math.round(t*s));return(i<8||a<8)&&(s=8/o,i=Math.max(8,Math.round(e*s)),a=Math.max(8,Math.round(t*s))),{width:i,height:a,needsResize:i!==e||a!==t}}const Iv=(e,t,r=1024)=>Rv(e,t,r),Tv=(e,t)=>Ev({width:e,height:t})?{width:e,height:t,needsResize:!1}:Rv(e,t),Av=(e,t,r)=>{e.resize({w:t,h:r})};function $v(e){if(void 0===e)throw new Error("image dimensions could not be read before decoding");const{width:t,height:r}=e;if(!(t*r<=178956970))throw new Error(`image dimensions ${t}x${r} exceed the 178956970 pixel decode limit`);if(!(Math.max(t,r)<=1e6))throw new Error(`image dimensions ${t}x${r} exceed the 1000000 pixel side limit`)}const Mv=(e,t)=>{switch(t){case"tiff":throw new Error("TIFF images are not supported; convert the image to PNG or JPEG");case"id3":throw new Error("images that start with an ID3 tag are not supported");case"jpeg":return;default:$v(((e,t)=>{switch(t){case"png":return(e=>{let t,r=Jy.length;for(;r+16<=e.length;)"IHDR"===e.toString("ascii",r+4,r+8)&&(t=ov(t,{width:e.readUInt32BE(r+8),height:e.readUInt32BE(r+12)})),r+=12+e.readUInt32BE(r);return t})(e);case"gif":return(e=>{if(e.length<13)return;const t={width:e.readUInt16LE(6),height:e.readUInt16LE(8)};let r=13+(128&(n=e[10])?3<<1+(7&n):0);for(var n;re.length<26?void 0:{width:e.readUInt32LE(18),height:Math.abs(e.readInt32LE(22))})(e)}})(e,t))}},Dv=e=>{const{width:t,height:r}=Iv(e.width,e.height,1280);return{width:t,height:r}},Ov=async(e,t)=>{let{width:r,height:n}=e,o=await t({width:r,height:n});for(;o.length>xv&&r>8&&n>8;)r=Math.max(8,Math.round(.8*r)),n=Math.max(8,Math.round(.8*n)),o=await t({width:r,height:n});return{data:Pv(o),mimeType:"image/webp",reencoded:!0}},Fv=async(e,t)=>{const r=(await fw()).fromBitmap({data:Buffer.from(e.data),width:e.width,height:e.height});return Ov(t,(async e=>(r.bitmap.width===e.width&&r.bitmap.height===e.height||Av(r,e.width,e.height),(e=>vv().encode(e))({data:r.bitmap.data,width:r.bitmap.width,height:r.bitmap.height}))))};let Nv;const Lv=async(e,t)=>{if(void 0!==t?.pngByteBudgetBytes){const{pngByteBudgetBytes:r,...n}=t,o=nv(e);return"image/png"===o?.mimeType&&Ev(o)&&await gv(e),_v({data:e,budgetBytes:r,maxImageBytes:xv,fitImage:Tv,resizeWithoutBudget:e=>Lv(e,n)})}const r=await(async(e,t)=>{const r=bv(e);if(r&&!0===t?.preserveWebpDimensions)return;const n=r?void 0:nv(e),o=r?Sv(e):n;if(void 0===o||!Ev(o))return;const s=Nv;if(void 0!==n&&void 0!==s&&!Ev(await s.readOrientedDimensions(e)))return;const i="image/png"===n?.mimeType;if(i&&await gv(e),e.length<=xv)return{data:Pv(e),mimeType:n?.mimeType??"image/webp"};const a=s?.resizeWebp;if(void 0!==a)return Ov(o,(t=>a({data:e,...t})))})(e,t);if(void 0!==r)return r;if(bv(e))return(async(e,t)=>{const r=Sv(e);if(!0===t?.preserveWebpDimensions&&void 0!==r)return{data:Pv(e),mimeType:"image/webp"};if(void 0!==r&&!Iv(r.width,r.height,1280).needsResize&&e.length<=xv)return{data:Pv(e),mimeType:"image/webp"};if("passthrough"===t?.webpWithoutCodec)return{data:Pv(e),mimeType:"image/webp"};$v(r);const n=undefined;if(void 0!==n)return Ov(Dv(r),(t=>n({data:e,...t})));const o=await kv(e);return Fv(o,Dv(o))})(e,t);const n=nv(e);if(void 0!==n&&e.length<=xv&&!Iv(n.width,n.height).needsResize)return{data:Pv(e),mimeType:n.mimeType};const o=iv(e);void 0!==o&&Mv(e,o);const s=void 0===n?void 0:Iv(n.width,n.height),i="image/png"===n?.mimeType&&!0===s?.needsResize?await cv({data:e,width:s.width,height:s.height}).catch((()=>{})):void 0;void 0===i&&"png"===o&&await gv(e);const a=await fw(),c=void 0===i?await a.read(e):a.fromBitmap(i),l=(e=>{switch(e.mime){case"image/png":default:return"image/png";case"image/bmp":return"image/bmp";case"image/tiff":return"image/tiff";case"image/x-ms-bmp":return"image/x-ms-bmp";case"image/gif":return"image/gif";case"image/jpeg":return"image/jpeg"}})(c),u=!0===t?.convertUnsupportedModelFormatsToPng&&"image/png"!==l&&"image/jpeg"!==l?"image/png":l,{width:d,height:h,needsResize:p}=Iv(c.width,c.height);if(void 0===i&&!p&&e.length<=xv&&u===l)return{data:Pv(e),mimeType:l};let f=d,m=h;p&&Av(c,f,m);let g=await c.getBuffer(u);for(;g.length>xv&&f>8&&m>8;)f=Math.max(8,Math.round(.8*f)),m=Math.max(8,Math.round(.8*m)),Av(c,f,m),g=await c.getBuffer(u);return{data:Pv(g),mimeType:u,reencoded:!0}},jv=async e=>{const t=Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=iv(t);let n;if(bv(t))return{kind:"unchecked"};if(void 0===r)return{kind:"unchecked"};{Mv(t,r);const e=await fw();n=async()=>("png"===r&&await gv(t),e.read(t))}try{return await n(),{kind:"decodes"}}catch(e){return{kind:"undecodable",reason:e instanceof Error?e.message:String(e)}}},Uv=BigInt(0),Bv=BigInt(8),Wv=BigInt(16),Hv=BigInt(65535);function qv(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function zv(e){const t=e.split(".");if(4!==t.length)return;let r=Uv;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<>Wv&Hv)),t.push(Number(o.value&Hv))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function Vv(e){return zv(e)??function(e){const t=qv(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=Gv(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<7?void 0:{version:6,value:[...s,...new Array(8-a).fill(0),...i].reduce(((e,t)=>e<i)return!1;const a=BigInt(i-s);return o.value>>a==n.value>>a}(r,n);if(n.startsWith("*.")){const e=n.slice(2);return r===e||r.endsWith(`.${e}`)}return r===n}function Jv(e,t){const r=function(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch{return}}(e);return!!r&&function(e,t){return t.some((t=>Kv(e,t)))}(r.hostname,t)}var Zv=r("../constants/dist/commercial-cursor-hosts.js");new Set([1,2]);const Xv="cursor/requiresConfirmation",Qv="https://grok.com/connectors-oauth-exchange-code/",Yv="https://x.com/i/connectors/oauth_callback",eb="https://chat.x.com/connectors/oauth_callback",tb="https://lite.x.com/i/connectors/oauth_callback",rb={provider:"google-workspace",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0,authorizationParams:{access_type:"offline",prompt:"select_account consent"}},nb={provider:"x-money",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,registeredAppRedirectUris:[Qv,Yv]},ob="x-cursor-auth";function sb(e,t){return function({serverUrl:e,restMcpHost:t}){if(void 0===e)return;let r;try{r=new URL(e)}catch{return}return"https:"===r.protocol&&r.hostname.toLowerCase()===t.toLowerCase()&&""===r.port?ib(e):void 0}({serverUrl:e,restMcpHost:t})}function ib(e){if(void 0===e)return;let t;try{t=new URL(e)}catch{return}const r=/^\/rest-mcp\/([^/]+)\/mcp\/?$/.exec(t.pathname);return r?.[1]}new Set(Object.values({notConnected:"scm_not_connected",tokenUnavailable:"scm_token_unavailable",tokenRejected:"scm_token_rejected",repoNotAccessible:"scm_repo_not_accessible",orgBlocked:"scm_org_blocked"})),new Set(Object.values({originNotEnabled:"origin_not_enabled",teamDisabled:"team_disabled",admissionRejected:"admission_rejected"}));const ab="https://mcp.shop.com",cb={provider:"grok-connectors",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,scopes:["grok-plugins:access","offline_access"]},lb=new Map([["mcp.slack.com",{displayName:"Slack",baseScopes:["canvases:read","canvases:write","channels:history","channels:read","channels:write","chat:write","emoji:read","files:read","files:write","groups:history","groups:read","im:history","im:read","im:write","lists:read","lists:write","mpim:history","mpim:read","mpim:write","reactions:read","reactions:write","search:read.files","search:read.im","search:read.mpim","search:read.private","search:read.public","search:read.users","users:read","users:read.email"],stepUpScopes:{"groups:write":{action:"create private channels",tools:[{name:"slack_create_conversation",args:{is_private:!0}}]}},missingScopeAnswer:/\bmissing_scope\b/}]]),ub=new Map([["gmailmcp.googleapis.com",{...rb,scopes:["https://www.googleapis.com/auth/gmail.readonly","https://www.googleapis.com/auth/gmail.compose","https://www.googleapis.com/auth/gmail.modify"]}],["drivemcp.googleapis.com",{...rb,scopes:["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/drive.file"]}],["calendarmcp.googleapis.com",{...rb,scopes:["https://www.googleapis.com/auth/calendar.events","https://www.googleapis.com/auth/calendar.calendarlist.readonly","https://www.googleapis.com/auth/calendar.events.readonly","https://www.googleapis.com/auth/calendar.events.freebusy"]}],["docsmcp.googleapis.com",{...rb,scopes:["https://www.googleapis.com/auth/documents"]}],["sheetsmcp.googleapis.com",{...rb,scopes:["https://www.googleapis.com/auth/spreadsheets"]}],["slidesmcp.googleapis.com",{...rb,scopes:["https://www.googleapis.com/auth/presentations"]}],["bigquery.googleapis.com",{...rb,scopes:["https://www.googleapis.com/auth/bigquery"]}],["api.x.com",{provider:"x",clientRegistration:"static",unauthenticatedConnect:!1,rejectsCustomSchemeRedirects:!1,pinsScopesOverConfiguredScopes:!0}],["mcp.money-dev.x.com",nb],["mcp.money-staging.x.com",nb],["mcp.money.x.com",nb],["connectors-gateway.grok.gcp.mouseion.dev",cb],["connectors-gateway.grok.com",cb],["mcp.hubspot.com",{provider:"hubspot",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0}],["mcp.box.com",{provider:"box",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0}],["mcp.asana.com",{provider:"asana",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,configuredSecretStaysOnBackend:!0}],["mcp.strava.com",{provider:"strava",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,scopes:["read","activity:read_all","profile:read_all"]}],["mcp.quickbooks.intuit.com",{provider:"quickbooks-online",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,unauthenticatedEndpointBlocked:!0,backendOnlyTokenExchange:!0,scopes:["com.intuit.quickbooks.accounting","foundations.tools.businessreports.read","foundations.tools.bi-dashboard","foundations.tools.transactions.write","foundations.tools.companyprofile.read","foundations.tools.companyprofile.write","payroll.tools.tax.read","payroll.tools.employer.read","payroll.tools.employer.manage","payroll.tools.run.read","payroll.tools.run.manage","payroll.tools.employee.read","payroll.tools.employee.manage","worker-mgmt.tools.employee.read","worker-mgmt.tools.employee.manage","time-tracking.tools.timeentry.read","sales.tools.invoice.read","sales.tools.invoice","sales.tools.estimate.read","sales.tools.estimate","sales.tools.payment-link.read","sales.tools.payment-link","sales.tools.settings.read","sales.tools.settings","sales.tools.salesorder.read","sales.tools.salesorder","contact.tools.customer.read","contact.tools.customer","catalog.tools.item.read","catalog.tools.item","lending.tools.servicing.read","money-onboarding.tools.application"]}],["setup.shopify.com",{provider:"shopify",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!1}],["mcp.cloudflare.com",{provider:"cloudflare",clientRegistration:"dynamic",unauthenticatedConnect:!1,rejectsCustomSchemeRedirects:!1,scopes:["user:read","account:read","offline_access","d1.metadata_read","d1.read","d1.write","workers-scripts.read","workers-scripts.write","workers-routes.read","workers-routes.write","workers-tail.read","workers-kv-storage.metadata_read","workers-kv-storage.read","workers-kv-storage.write","workers-r2.metadata_read","workers-r2.read","workers-r2.write","workers-r2-bucket-item.read","workers-r2-bucket-item.write","workers-observability.read","workers-observability.write","dns.read","dns.write","zone.read","zone.write"],pinsScopesOverConfiguredScopes:!0,scopesPinGate:"mcp_cloudflare_api_oauth_scopes"}],["mcp.shop.com",{provider:"shop",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,backendOnlyTokenExchange:!0,scopes:["openid","personal_agent"],pinsScopesOverConfiguredScopes:!0,authorizationParams:{resource:ab}}],["api.elections.kalshi.com",{provider:"kalshi",clientRegistration:"dynamic",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0}],["mcp.squarespace.com",{provider:"squarespace",clientRegistration:"dynamic",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0}]]),db=[".databricks.com",".azuredatabricks.net"];const hb=/^\/sncapps\/mcp-server\/mcp\/[^/]+$/,pb={provider:"databricks",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,scopes:["ai-gateway","offline_access"],pinsScopesOverConfiguredScopes:!0},fb={provider:"servicenow",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,unauthenticatedEndpointBlocked:!0,backendOnlyTokenExchange:!0,ownMcpJsonClientMayExchange:!0};function mb(e){if(void 0===e)return;let t;try{t=new URL(e)}catch{return}return function(e){return"https:"===e.protocol&&""===e.port&&""===e.username&&""===e.password&&function(e){const t=e.toLowerCase();return!(!/^[a-z0-9.-]+$/.test(t)||t.includes("..")||t.startsWith("."))&&db.some((e=>t.endsWith(e)&&t.length>e.length))}(e.hostname)&&"/ai-gateway/mcp-services/system.ai.genie_one_mcp"===e.pathname.replace(/\/+$/,"")}(t)?pb:function(e){return"https:"===e.protocol&&""===e.port&&""===e.username&&""===e.password&&hb.test(e.pathname.replace(/\/+$/,""))}(t)?fb:(r=t.hostname,ub.get(r.toLowerCase()));var r}function gb(e){return e.endsWith("/")?e:`${e}/`}async function wb(e,t){if(void 0===t)return;const r=new URL(e),n=new URL(t);if(r.origin!==n.origin||!gb(r.pathname).startsWith(gb(n.pathname)))throw new Error(`Protected resource ${t} does not match expected ${r.href} (or origin)`);return n}const yb=/^\/shops\/[A-Za-z0-9-]+\/mcp$/;function vb(e){if(void 0!==e)try{return new URL(e)}catch{return}}async function bb(e,t){if(void 0===t)return;const r=new URL(e),n=vb(t);if(void 0===n||n.origin!==r.origin||n.pathname!==r.pathname&&!yb.test(n.pathname))throw new Error(`Protected resource ${t} does not match expected ${r.href} (or origin)`);return n}function Sb(e){const t=vb(e);return void 0===t?void 0:lb.get(t.hostname.toLowerCase())}const kb=new Set([...ub].filter((([,e])=>"google-workspace"===e.provider)).map((([e])=>e))),_b="https://www.cursor.com/bot/mcp/oauth/callback",Cb={portal:"https://www.cursor.com/agents/mcp/oauth/callback",grokBotBounce:_b},Eb="tailnet_";new Set([`${Eb}waiting_for_approval`,`${Eb}tailnet_locked`,`${Eb}joining`]);const xb="grokbot://mcp/oauth/callback",Pb="http://localhost:8787/callback",Rb="gb";function Ib(e){const t=new URL(Pb);return t.port=String(e),t.toString()}function Tb(e){try{const t=new URL(e);if("http:"!==t.protocol)return!1;const r=t.hostname;return"localhost"===r||"127.0.0.1"===r||"[::1]"===r}catch{return!1}}function Ab(e){const t=e.redirectUrl??Pb;if(!0!==e.loopbackIpv4||!Tb(t))return t;const r=new URL(t);return r.hostname="127.0.0.1",r.toString()}function $b(e,t=Cb){const r=new Set,n=void 0!==e&&Tb(e);return e&&!n&&r.add(e),r.add(t.portal),e===xb&&r.add(t.grokBotBounce),r.add(Pb),e&&n&&r.add(e),Array.from(r)}function Mb(e){var t;if(void 0!==e&&0!==e.length)try{const r=JSON.parse(e);if("object"==typeof(t=r)&&null!==t&&!Array.isArray(t))return r}catch{}}function Db(e){if(void 0===e)return{};const t={};"string"==typeof e.title&&e.title.length>0&&(t.title=Vo(e.title,256));for(const r of["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"])"boolean"==typeof e[r]&&(t[r]=e[r]);return function(e){return!0===e?.[Xv]}(e)&&(t[Xv]=!0),0===Object.keys(t).length?{}:{annotationsJson:JSON.stringify(t)}}new Map([[Rb,xb],["gw",Qv],["gd",Pb],["xa",Yv],["xc",eb],["xl",tb],...[18787,28787,31787].map((e=>[`gd${e}`,Ib(e)]))]),new Map([[xb,Rb],[_b,Rb],[Qv,"gw"],[Yv,"xa"],[eb,"xc"],[tb,"xl"]]),Ab({loopbackIpv4:!0});var Ob=r("../mcp-core/dist/transport/mcp-url-utils.js");function Fb(e){return e.trim().toLowerCase()}const Nb="";function Lb({mode:e,tools:t}){const r=(t??[]).map(Fb).filter((e=>e.length>0)),n=void 0===e?void 0:Fb(e);return"all"===n?{mode:"all"}:"reads"===n?{mode:"reads"}:r.length>0?{mode:"custom",tools:r}:{mode:"all"}}function jb(e,t){switch(e.mode){case"all":return!0;case"custom":return function(e,t){const r=Fb(e);return 0!==r.length&&r!==Nb&&t.some((e=>Fb(e)===r))}(t.name,e.tools);case"reads":return void 0!==(r=t.annotations)&&!0!==r.destructiveHint&&!0===r.readOnlyHint;default:return e}var r}function Ub(e,t){switch(t.mode){case"all":return[`${e}:*`];case"custom":return t.tools.filter((e=>Fb(e)!==Nb)).map((t=>`${e}:${t}`));case"reads":return[];default:return t}}const Bb=new Set(["ash","bash","csh","dash","fish","ksh","powershell","pwsh","sh","tcsh","zsh","cmd"]);function Wb(e){return e.trim().split(/\s+/).filter(Boolean)}function Hb(e){const t=function(e){const t=e.trim(),r=t[0];if('"'===r||"'"===r){const e=t.indexOf(r,1);if(-1!==e)return t.slice(0,e+1)}return Wb(t)[0]}(e);if(!t)return!1;const r=t.replace(/^["']|["']$/g,"").replaceAll("\\","/").split("/"),n=(r[r.length-1]??"").replace(/\.exe$/i,"").toLowerCase();return Bb.has(n)}function qb(e,t){if(e.length>t.length)return!1;for(let r=0;r=t.tokenCount)continue;let a=!0;for(const t of e.tokens)if(!n.has(t)){a=!1;break}if(!a)continue;const c=qb(e.tokens,t.tokens);void 0!==o?e.tokenCount>o.tokenCount?(o=e,s=c):e.tokenCount===o.tokenCount&&c&&!s&&(o=e,s=!0):(o=e,s=c)}void 0!==o&&(t.indentLevel=o.indentLevel+1,t.ancestorIds=[...o.ancestorIds,t.id])}const n=r.filter((e=>!r.some((t=>t.id!==e.id&&t.tokenCounte.id));return{options:r,defaultSelectedOptionIds:n}}(e),n=[...r.defaultSelectedOptionIds];if(!t||0===t.length)return{defaultSelectedOptionIds:n,hasClassifierSuggestions:!1};const o=[],s=new Set;for(const e of t){const t=r.options.find((t=>t.id===e));if(t){o.push(t.id),s.add(Gb(t.id));continue}const n=r.options.filter((t=>t.id.startsWith(`${e} `)||t.id===e)),i=r.options.filter((t=>e.startsWith(`${t.id} `)||e===t.id));if(i.length>0){const e=i.reduce(((e,t)=>e.id.length>t.id.length?e:t));o.push(e.id),s.add(Gb(e.id))}else if(n.length>0){const e=n.reduce(((e,t)=>e.id.length!s.has(Gb(e))));return{defaultSelectedOptionIds:[...new Set([...i,...o])],hasClassifierSuggestions:!0}}(e,t).defaultSelectedOptionIds}const Kb=["com.todesktop.230313mzl4w4u92","co.anysphere.cursor","com.anysphere.molten-glass"],Jb=["cursor","molten glass"];function Zb(e){return Kb.some((t=>e===t||e.startsWith(`${t}.`)))}const Xb=[{bundleId:"com.apple.scripteditor2",name:"Script Editor"},{bundleId:"com.apple.automator",name:"Automator"},{bundleId:"com.apple.shortcuts",name:"Shortcuts"}],Qb=[{bundleId:"com.apple.terminal",name:"Terminal"},{bundleId:"com.googlecode.iterm2",name:"iTerm",aliases:["iTerm2"]},{bundleId:"dev.warp.warp-stable",name:"Warp"},{bundleId:"dev.warp.warp-preview",name:"WarpPreview",aliases:["Warp Preview"]},{bundleId:"com.mitchellh.ghostty",name:"Ghostty"},{bundleId:"org.alacritty",name:"Alacritty"},{bundleId:"net.kovidgoyal.kitty",name:"kitty"},{bundleId:"com.github.wez.wezterm",name:"WezTerm"},{bundleId:"co.zeit.hyper",name:"Hyper"},{bundleId:"org.tabby",name:"Tabby"},...Xb,{bundleId:Kb[0],name:"Cursor"}];function Yb(e){const t=e.toLowerCase(),r=(0,s.basename)(e,".app").toLowerCase(),n=Qb.find((({bundleId:e,name:n,aliases:o=[]})=>e===t||[n,...o].some((e=>{const n=e.toLowerCase();return n===t||n===r}))));return void 0!==n?{bundleId:n.bundleId,name:n.name}:Zb(t)?{bundleId:t,name:"Cursor"}:[t,r].some((e=>Jb.some((t=>e===t||e.startsWith(`${t} `)))))?{bundleId:Kb[0],name:"Cursor"}:void 0}const eS=new Set(["com.apple.systempreferences","com.apple.keychainaccess","com.apple.passwords","com.1password.1password","com.agilebits.onepassword7","com.bitwarden.desktop","com.lastpass.lastpass","org.keepassxc.keepassxc"]);function tS(e){return eS.has(e.toLowerCase())}function rS(e){return`app/${e}`}function nS(e){return"object"==typeof e&&null!==e}function oS(e){return iS.includes(e)}function sS(e){if(!nS(e))return;const{appArg:t,appSelectorArgs:r,capturesScreen:n}=e;if("boolean"==typeof n){if(void 0!==r){if(void 0!==t||!nS(r))return;const e={};for(const[t,n]of Object.entries(r)){if(!oS(t)||"string"!=typeof n||0===n.length)return;e[t]=n}if(0===Object.keys(e).length)return;return{appSelectorArgs:e,capturesScreen:n}}return void 0===t?{capturesScreen:n}:"string"==typeof t&&t.length>0?{appArg:t,capturesScreen:n}:void 0}}const iS=["pid","bundleId","path","appName"],aS=/^[+-]?\d+$/;var cS=r("../../node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/create.js");const lS=".cursor/worktrees",uS=".grok/build-desktop/worktrees",dS="win32"===process.platform||"darwin"===process.platform,hS=new Map;function pS(e,t){if(!(0,Yo.BJ)(t,e))return;const r=(dS?(0,s.relative)(e.toLowerCase(),t.toLowerCase()):(0,s.relative)(e,t)).split(s.sep).filter(Boolean);return r.length>0?r:void 0}function fS(e,t){const r=pS(e,t);if(void 0!==r)return r;const n=function(e){if(hS.has(e))return hS.get(e);const t=[];let r,n=e;for(;;)try{const e=xo.realpathSync.native(n);r=0===t.length?e:(0,s.join)(e,...t);break}catch(e){const r=Sc(e);if("ENOENT"!==r&&"ENOTDIR"!==r)break;const o=(0,s.dirname)(n);if(o===n)break;t.unshift((0,s.basename)(n)),n=o}return hS.size>=64&&hS.clear(),hS.set(e,r),r}(e);var o,i;return void 0!==n&&(o=n,i=e,dS?o.toLowerCase()!==i.toLowerCase():o!==i)?pS(n,t):void 0}function mS(e){const t=e?.trim();return t&&".cursor"!==t?[".cursor",t]:[".cursor"]}function gS(e,t){const r=(0,o.homedir)();return mS(t?.dataFolderName).some((t=>void 0!==fS((0,s.join)(r,t,"projects"),e)))}function wS(e){const t=(0,o.homedir)();return[lS,uS].some((r=>void 0!==fS((0,s.join)(t,...r.split("/")),e)))}function yS(e,t,r){const n=function(e,t){const r=(0,o.homedir)();for(const n of mS(t?.dataFolderName)){const t=fS((0,s.join)(r,n,"projects"),e);if(void 0!==t&&t.length>=2)return t[1]}}(e,r);return void 0!==n&&(dS?t.some((e=>e.toLowerCase()===n.toLowerCase())):t.includes(n))}function vS(e,t,r){const n=fS(e,t);if(void 0===n)return!1;const o=n[0];return dS?r.some((e=>e.toLowerCase()===o.toLowerCase())):r.includes(o)}const bS=/[\s"'`=/\\:;()[\]{},&|<>]/,SS="win32"===process.platform||"darwin"===process.platform;async function kS(e,t,r,n){const o=RS(await PS((0,s.join)(e,"gitdir")),"");if(void 0===o)return;const i=(0,s.resolve)(e,o);if(".git"!==(0,s.basename)(i)||(0,qs.$f)(i))return;const a=(0,s.dirname)(i);if(r&&wS(a))return;const c=await IS(i);if(void 0===c)return;const l=(0,s.dirname)(c);if(r&&wS(l))return;if(void 0!==n&&(u=AS(a,l)?[l]:[a,l],d=n.command,!(void 0!==(h=n.realWorkingDirectory)&&u.some((e=>(0,Yo.BJ)(h,e)))||void 0!==d&&u.some((e=>{const t=(0,s.basename)(e);return t.length>0&&function(e,t){const r=SS?e.toLowerCase():e,n=SS?t.toLowerCase():t;let o=0;for(;;){const e=r.indexOf(n,o);if(-1===e)return!1;const t=0===e||bS.test(r[e-1]),s=e+n.length,i=s===r.length||bS.test(r[s]);if(t&&i)return!0;o=e+1}}(d,t)})))))return;var u,d,h;const p=await xS(i,c);return void 0!==p&&AS(p.commonDir,t)?l:void 0}async function _S(e,t){const r=await(0,Co.readdir)(e).catch(TS);return void 0===r?[]:r.sort().slice(0,t)}function CS(e,t){return t.some((t=>(0,Yo.BJ)(t,e)))}async function ES(e){for(let t=e;;t=(0,s.dirname)(t)){if((0,qs.$f)(t))return;const e=(0,s.join)(t,".git"),r=await(0,Co.lstat)(e).catch(TS);if(r?.isFile())return(await xS(e))?.commonDir;if(r?.isDirectory())return e;if(void 0!==r||(0,s.dirname)(t)===t)return}}async function xS(e,t){const r=RS(await PS(e),"gitdir: ");if(void 0===r)return;const n=await IS((0,s.resolve)((0,s.dirname)(e),r));if(void 0===n||"worktrees"!==(0,s.basename)((0,s.dirname)(n)))return;const o=(0,s.dirname)((0,s.dirname)(n));if(".git"!==(0,s.basename)(o))return;const i=RS(await PS((0,s.join)(n,"commondir")),"");if(void 0===i)return;const a=await IS((0,s.resolve)(n,i));if(void 0===a||!AS(a,o))return;const c=RS(await PS((0,s.join)(n,"gitdir")),"");if(void 0===c)return;const[l,u]=await Promise.all([IS((0,s.resolve)(n,c)),t??IS(e)]);return void 0!==l&&void 0!==u&&AS(l,u)?{commonDir:o,realDotGit:u}:void 0}async function PS(e){const t=await(0,Co.lstat)(e).catch(TS);if(void 0!==t&&t.isFile()&&!(t.size>4096))return(0,Co.readFile)(e,"utf8").catch(TS)}function RS(e,t){const r=e?.split("\n",1)[0]?.replace(/\r$/,"");if(void 0===r||!r.startsWith(t))return;const n=r.slice(t.length);return n.length>0&&!n.includes("\0")?n:void 0}async function IS(e){if(!(0,qs.$f)(e))return(0,Co.realpath)(e).catch(TS)}function TS(e){const t=Sc(e);if(void 0===t||t.startsWith("ERR_"))throw e}function AS(e,t){return SS?e.toLowerCase()===t.toLowerCase():e===t}function $S(e,t,r){return{resolvedPath:e,originalPath:t,resolution:r}}function MS(e){const t=Sc(e);switch(t){case"ENOENT":return{status:"newFile"};case"EACCES":case"EPERM":return{status:"permissionDenied",errno:t};case"ELOOP":return{status:"symlinkLoop",errno:t};default:return{status:"unknownError",errno:t??"UNKNOWN",message:kc(e)}}}async function DS(e,t){const r=(0,Yo.o1)(e,t);try{return $S(await(0,Co.realpath)(r),r,{status:"resolved"})}catch(e){if("ENOENT"!==Sc(e))return $S(r,r,MS(e));try{if((await(0,Co.lstat)(r)).isSymbolicLink()){let e=null;try{e=await(0,Co.readlink)(r)}catch{}return $S(r,r,{status:"danglingSymlink",symlinkTarget:e})}try{return $S(await(0,Co.realpath)(r),r,{status:"resolved"})}catch(e){if("ENOENT"!==Sc(e))return $S(r,r,MS(e))}return $S(r,r,{status:"unknownError",errno:"ENOENT",message:"realpath returned ENOENT but lstat found a non-symlink entry"})}catch(e){return"ENOENT"===Sc(e)?async function(e){let t=(0,s.dirname)(e);const r=[(0,s.basename)(e)];for(;(0,s.dirname)(t)!==t;){try{const n=await(0,Co.realpath)(t);return $S((0,s.join)(n,...r),e,{status:"newFile"})}catch(t){if("ENOENT"!==Sc(t))return $S(e,e,MS(t))}r.unshift((0,s.basename)(t)),t=(0,s.dirname)(t)}return $S(e,e,{status:"newFile"})}(r):$S(r,r,MS(e))}}}function OS(e){return"resolved"===e.status||"newFile"===e.status}function FS(e,t){switch(t.status){case"resolved":case"newFile":return"";case"danglingSymlink":return`Write blocked: \`${e}\` is a dangling symlink${t.symlinkTarget?` (target: ${t.symlinkTarget})`:""}. Cannot verify it does not point to a protected file.`;case"permissionDenied":return`Write blocked: cannot verify \`${e}\` -- permission denied resolving symlinks (${t.errno}).`;case"symlinkLoop":return`Write blocked: \`${e}\` has a symlink loop (${t.errno}). Cannot verify target.`;case"unknownError":return`Write blocked: cannot verify \`${e}\` -- ${t.errno}: ${t.message}.`;default:return`Write blocked: unknown resolution status for \`${e}\`.`}}function NS({realAbsolutePath:e,setting:t,resolvedWorkspaceRoots:r,resolvedAllowFolders:n,resolvedAllowGlobs:o}){return!("workspace"!==t.boundary||LS(e,r)||LS(e,n)||US(e,t.allowPaths)||US(e,o))}function LS(e,t){return t.some((t=>(0,Yo.BJ)(e,t)))}function jS(e){return e.flatMap((e=>{const t=(0,Yo.jl)(e.trim());return!t.includes("*")&&(0,s.isAbsolute)(t)?[(0,s.resolve)(t)]:[]}))}function US(e,t){const r="win32"===process.platform?Yo.oL:e=>e,n=r(e);return t.some((e=>{const t=(0,Yo.jl)(e.trim());return!(!t.includes("*")&&(0,s.isAbsolute)(t))&&(0,ms.T)(r(t),n)}))}const BS={caffeinate:{flags:["-d","-i","-m","-s","-u"],valueOptions:["-t","-w"]},command:{flags:["-p"],valueOptions:[],lookupFlags:["-v","-V"]},env:{flags:["-","-i","-0","-v","--ignore-environment","--null","--debug"],valueOptions:["-u","-C","--unset","--chdir"],assignments:!0,directoryOptions:["-C","--chdir"]},nice:{flags:[],valueOptions:["-n","--adjustment"],numericOption:!0},nohup:{flags:[],valueOptions:[]},stdbuf:{flags:[],valueOptions:["-i","-o","-e","--input","--output","--error"]},time:{flags:["-p"],valueOptions:[]},timeout:{flags:["-f","-p","-v","--foreground","--preserve-status","--verbose"],valueOptions:["-k","-s","--kill-after","--signal"],operands:1},xargs:{flags:["-0","-o","-p","-r","-t","-x","--null","--open-tty","--interactive","--no-run-if-empty","--verbose","--exit","--show-limits"],valueOptions:["-a","-d","-E","-I","-J","-L","-n","-P","-R","-S","-s","--arg-file","--delimiter","--max-args","--max-procs","--max-chars","--process-slot-var"],attachedValueOptions:["-e","-i","-l","--eof","--replace","--max-lines"],readsArguments:!0}};function WS(e){const t=[];let r=!0,n=!1,o=e;for(;;){const e=BS[s.posix.basename(o.name)];if(void 0===e)return{command:o,wrapperForms:t,allowlistable:r,readsArguments:n};const i=HS(o.args,e);if("unreadable"===i)return{command:o,wrapperForms:t,allowlistable:!1,readsArguments:n};if("none"===i)return{command:o,wrapperForms:t,allowlistable:r,readsArguments:n};const[a,...c]=o.args.slice(i);if(void 0===a||!KS(a))return{command:o,wrapperForms:t,allowlistable:!1,readsArguments:n};(o.name.includes("/")||o.args.slice(0,i).some((t=>qS(t,e)||zS(t.value,e))))&&(r=!1),n||=!0===e.readsArguments,t.push(o.fullText.trim()),o=new he.Pv({name:a.value,args:c,fullText:[a.value,...c.map((e=>e.value))].join(" ")})}}function HS(e,t){let r=0;for(;rt.startsWith("--")?e===t||e.startsWith(`${t}=`):/^-[^-]/.test(e)&&e.includes(t.slice(1))))}function GS(e,t,r){const n=e=>!0===r.attachedValueOptions?.includes(e);if(r.flags.includes(e)||n(e))return 1;if(e.startsWith("--")){const o=e.indexOf("=");if(-1!==o){const t=e.slice(0,o);return r.valueOptions.includes(t)||n(t)?1:void 0}if(!r.valueOptions.includes(e))return;return void 0===t?void 0:2}for(let o=1;o{const t=await DS(e);return OS(t.resolution)?t.resolvedPath:(0,Yo.o1)(e)})))}function uk(e,t,r){return`${e} blocked: cannot verify ${t} \`${r}\` while resolving symlinks. This can happen when access is denied or the path contains a symlink loop.`}function dk(e){return[...new Set(e)]}function hk(){return{fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}}function pk({basePath:e,targetPath:t,pathModule:r}){const n=r.resolve(e),o=r.resolve(t),s=r.relative(n,o);return""===s||".."!==s&&!s.startsWith(`..${r.sep}`)&&!r.isAbsolute(s)}function fk(e){return">"===e||">>"===e||">|"===e||"&>"===e||"&>>"===e}function mk(e){return"<"!==e.operator&&"<&"!==e.operator}function gk(e){if(void 0===e||e.trim()!==e)return;const t=Number(e);return Number.isInteger(t)&&t>=0?t:void 0}function wk(e){return"<<"===e.operator&&"heredoc_redirect"===e.targetNodeType&&1===e.destinationFds.length&&0===Number(e.destinationFds[0])&&void 0!==e.targetText}function yk(e,t){return!(/^=|[~*?[{(#^`]/.test(e)||"\\"!==t.sep&&e.includes("\\"))}function vk(e){return"word"===e.type||"number"===e.type?yk(e.value,s)?e.value:void 0:"raw_string"===e.type||"string"===e.type&&!/[$`\\]/.test(e.value)?e.value.slice(1,-1):void 0}function bk({command:e,readsArguments:t}){if(!function(e){const t=e.replace(/["']/g,"");return[t,t.replace(/\\/g,"")].some((e=>/^tee(?:-object)?(?:\.exe)?$/i.test(e.slice(Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"))+1))))}(e.name))return[];const r=e.args.map(vk);return t?[...r,void 0]:r}const Sk=new Set(["cd","chdir","pushd"]),kk=new Set(["popd","eval","source",".","trap","set-location","sl","push-location","pop-location"]);function _k(e){const t=e.replace(/["'\\]/g,"");return t.slice(t.lastIndexOf("/")+1).toLowerCase()}function Ck(e,t){return new he.Pv({name:e,args:t,fullText:[e,...t.map((e=>e.value))].join(" ")})}function Ek(e){let t=e;for(;;){const e=_k(t.name);if("command"===e){const e=Ck("command",t.args),r=WS(e).command;if(r!==e){t=r;continue}const n=t.args[0]?.value;return void 0===n||"-v"===n||"-V"===n?t:"unreadable"}if("builtin"!==e)return t;const r="--"===t.args[0]?.value?t.args.slice(1):t.args,[n,...o]=r;if(void 0===n)return t;const s=vk(n);if(void 0===s||s.startsWith("-"))return"unreadable";t=Ck(s,o)}}function xk(e,t){return!(!t.isAbsolute(e)||"/"!==t.sep&&/^[\\/]$/.test(t.parse(e).root))}async function Pk({parsingResult:e,workingDirectory:t,resolvePathForPermissions:r,pathModule:n}){const o=[t];for(const t of e.executableCommands.map(WS)){const e=Ek(t.command);if("unreadable"===e)return;const i=_k(e.name),a=e.args;if(kk.has(i)||/^cd\.\./.test(s=i)||/^[a-z]:$/.test(s))return;if(!Sk.has(i))continue;const c=1===a.length&&void 0!==a[0]?vk(a[0]):void 0;if(void 0===c||!xk(c,n))return;const l=await r(c);if(!OS(l.resolution))return;o.push(l.resolvedPath)}var s;return o}async function Rk({targetText:e,workingDirectory:t,workingDirectories:r,...n}){const o=xk(e,n.pathModule)?[t]:r;if(void 0===o)return;let s;for(const t of o)if(s=await Ik({...n,targetText:e,workingDirectory:t}),void 0===s)return;return s}async function Ik({targetText:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:o,pathModule:s,tempPathOptions:i}){if(""!==s.parse(e).root&&!s.isAbsolute(e))return;const a=await o(e,t);if(!OS(a.resolution))return;const c=[];for(const e of r){const t=await o(e);OS(t.resolution)&&c.push(t.resolvedPath)}return await async function({targetPath:e,rootPaths:t,pathModule:r}){if(e.split(r.sep).some((e=>".git"===e.toLowerCase())))return!0;for(const r of t)if(await(0,Oo.OK)(e,r).catch((()=>!0)))return!0;return!1}({targetPath:a.resolvedPath,rootPaths:c,pathModule:s})?void 0:c.some((e=>pk({basePath:e,targetPath:a.resolvedPath,pathModule:s})))?"workspace-file":n&&!(0,Oo.dA)(a.originalPath)&&Wk(a.resolvedPath,i)?"tmp-file":void 0}async function Tk({parsingResult:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n}){const i=await Pk({parsingResult:e,workingDirectory:t,resolvePathForPermissions:DS,pathModule:s});for(const a of e.executableCommands.map(WS).flatMap(bk))if("/dev/null"!==a&&(void 0===a||!await Rk({targetText:a,workingDirectory:t,workingDirectories:i,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:DS,pathModule:s,tempPathOptions:{platform:process.platform,env:process.env,pathModule:s,homeDirectory:(0,o.homedir)()}})))return!1;return!0}function Ak(e){return dk(e.map((e=>e.trim())).filter(Boolean))}function $k(e){const t=e.name.trim();if(!t)return[];const r=e.arguments.map((e=>e.trim())).filter(Boolean),n=r.length>0?`${t} ${r.join(" ")}`:t,o=e.subcommandTokens.map((e=>e.trim())).filter(Boolean);if(0===o.length)return[n];const s=`${t} ${o.join(" ")}`;return s===n?[n]:[n,s]}function Mk(e,t){const r=t.trim();return!!r&&e.some((e=>e===r||e.startsWith(`${r} `)))}function Dk(e){const t=e.name.trim(),r=e.arguments.map((e=>e.trim())).filter(Boolean).map((e=>new he.r6({type:"word",value:e})));return new he.Pv({name:t,args:r,fullText:[t,...r.map((e=>e.value))].join(" ").trim()})}function Ok(e,t={}){return{type:e,...t}}function Fk(e){return void 0!==e&&("deny"===e.default||void 0!==e.allow&&e.allow.length>0||void 0!==e.deny&&e.deny.length>0)}function Nk(...e){return e.filter((e=>void 0!==e)).join(" • ")}function Lk(e){const t=[];for(const r of e){const e=r.match(/^\s*Read\s*\((.*)\)\s*$/);e&&t.push((e[1]??"").trim())}return t}function jk(e,t){if("workspace"===e&&void 0!==t)return t}const Uk={workspace:0,system:1};function Bk(e){const t=e.match(/^\s*(Shell|Bash)\s*\((.*)\)\s*$/);if(!t)return null;const r=t[1];if("Shell"!==r&&"Bash"!==r)return null;const n=t[2]?.trim()??"",o=n.indexOf(":");return-1!==o?{shellType:r,fullPattern:n,commandPattern:n.slice(0,o).trim(),argsPattern:n.slice(o+1).trim()}:{shellType:r,fullPattern:n,commandPattern:n,argsPattern:null}}function Wk(e,{platform:t,env:r,pathModule:n,homeDirectory:o}){if((0,Oo.dA)(e))return!1;if("win32"===t){const t=r.TEMP??r.TMP;if(t){const r=n.normalize(t).toLowerCase(),o=n.normalize(e).toLowerCase(),s=r.endsWith(n.sep)?r:r+n.sep;return o===r||o.startsWith(s)}return!1}const s=e=>{const r=n.normalize(e);return"darwin"!==t?r:"/tmp"===r||r.startsWith("/tmp/")||"/var"===r||r.startsWith("/var/")?`/private${r}`:r},i=s(e);return(void 0===o||!pk({basePath:s(o),targetPath:i,pathModule:n}))&&("darwin"===t?["/private/tmp/","/private/var/folders/"].some((e=>i.startsWith(e))):["/tmp/","/private/tmp/","/var/folders/","/private/var/folders/","/var/tmp/"].some((e=>i.startsWith(e))))}function Hk(e,t){if("insecure_none"===t.type)return!0;if("insecure_none"===e.type)return!1;const r=(0,Oo.$b)(e.networkPolicy),n=(0,Oo.$b)(t.networkPolicy);if(r&&!n)return!1;const o=(0,Oo._B)(e.networkPolicy),s=(0,Oo._B)(t.networkPolicy);if(o&&n&&!s)return!1;if("workspace_readonly"===e.type&&"workspace_readwrite"===t.type)return!0;if("workspace_readwrite"===e.type&&"workspace_readonly"===t.type)return!1;const i=e.readBoundary??"system",a=t.readBoundary??"system";return!(Uk[i]>Uk[a])}function qk(e){return{wrapperForms:e.flatMap((e=>e.wrapperForms)),allowlistable:e.every((e=>e.allowlistable)),readsArguments:e.some((e=>e.readsArguments))}}function zk(e){return[...e.wrapperForms,e.command.fullText.trim()].filter(Boolean)}class Gk{constructor(e,t,r,n,o){this.command=e,this.requestedPolicy=t,this.wrapperForms=o?.wrapperForms??[],this.allowlistable=o?.allowlistable??!0,this.readsArguments=o?.readsArguments??!1;const s=void 0!==r&&Hk(t,r);this.state=s?"preapproved":"approvable";const i=[e.fullText.trim()].filter(Boolean);this.matchForms=n&&n.length>0?[...n]:i}approveWithPolicy(e){"approvable"!==this.state&&"preapproved"!==this.state||!Hk(this.requestedPolicy,e)||(this.state="allowlisted")}deny(){this.state="denied"}isRunnable(){return"preapproved"===this.state||"allowlisted"===this.state}}function Vk(e){return e?.type??"undefined"}const Kk=["skills","skills-cursor","rules","plugins"],Jk=["assets","agent-notes","agent-tools","swarm-agents"];async function Zk(e,t,r){return e.shouldBlockFileRead?.(t,r)??e.shouldBlockRead(t,r)}function Xk(e){const t=e.lastIndexOf("::mcpScope:");return-1===t?e:e.slice(0,t)}function Qk({server:e,tool:t}){const r=e=>e.length>0&&e.length<=256&&!/[:*]/.test(e),n=e.trim().toLowerCase(),o=t.trim().toLowerCase();return r(n)&&r(o)?`${n}:${o}`:void 0}const Yk=/^\s*Read\s*\((.*)\)\s*$/,e_=/^\s*Write\s*\((.*)\)\s*$/;class t_{constructor(e,t,r,n,i,a=!1,c){this.ignoreService=e,this.pendingDecisionStore=t,this.permissionsProvider=r,this.teamSettingsService=n,this.adminNetworkControlsEnabled=a,this.computerUseAppsAllowedForSession=[],this.rootDirectories=Array.isArray(i)?i:[i??process.cwd()],this.projectDir=c?.projectDir,this.perUserSandboxConfigPath=c?.perUserSandboxConfigPath??(0,s.join)((0,o.homedir)(),".cursor","sandbox.json"),this.mcpAllowlistLog=c?.mcpAllowlistLog,this.computerUse=c?.computerUse,this.computerUseAdminPolicy=c?.computerUseAdminPolicy,this.enforceMcpAdminToolLimits=c?.enforceMcpAdminToolLimits,this.onMcpAdminToolLimitCheck=c?.onMcpAdminToolLimitCheck}async shouldBlockRead(e,t={}){return this.shouldBlockReadInternal(e,t,!1)}async shouldBlockFileRead(e,t={}){return this.shouldBlockReadInternal(e,t,!0)}async getFileReadBoundaryBlocker(){const{perms:e,setting:t}=await this.readControlSetting(),r=e.deny.filter((e=>this.isPathEntry("Read",e))),n="workspace"===t.boundary&&"unrestricted"!==e.approvalMode;if(!n&&0===r.length)return;const[o,s,i]=n?await Promise.all([this.resolveWorkspaceReadRoots(e.userSandboxDataFolderName),this.resolvedReadAllowFolders(t.allowPaths),this.resolvedReadAllowGlobs(t.allowPaths)]):[[],[],[]],a=r.map((e=>this.compileReadDenyMatcher(e))),c=e=>a.some((t=>t(e)));return async(e,r)=>c(e)||c(r)||n&&NS({realAbsolutePath:r,setting:t,resolvedWorkspaceRoots:o,resolvedAllowFolders:s,resolvedAllowGlobs:i})}async readControlSetting(){const e=await this.getPermissions(),{enabled:t,...r}=await this.adminReadControls(e);return{perms:e,setting:function(e){if(!e.enabled)return{boundary:"system",allowPaths:[],enforcedByAdmin:!1};const t="workspace"===e.admin.boundary,r=t||"workspace"===e.local.boundary?"workspace":"system",n=t?e.admin.allowPaths:[];return{boundary:r,allowPaths:t&&!1===e.admin.allowUserOverride?[...n]:[...new Set([...n,...e.local.allowPaths])],enforcedByAdmin:t}}({enabled:t,admin:r,local:{boundary:e.readBoundary,allowPaths:Lk(e.allow)}})}}async adminReadControls(e){const t=e.teamAdminPolicy,r=this.teamSettingsService.isReadControlEnabled?.()??!0;if(void 0!==t&&"unavailable"!==t){const e=await r;return"workspace"!==t.readBoundary?{enabled:e,boundary:void 0,allowPaths:[],allowUserOverride:void 0}:{enabled:e,boundary:"workspace",allowPaths:t.additionalReadPaths??[],allowUserOverride:t.allowUserOverrideReadPaths}}const[n,o]=await Promise.all([r,this.teamSettingsService.getSandboxingControls()]);return{enabled:n,boundary:o.readBoundary,allowPaths:o.readAllowlistPaths??[],allowUserOverride:o.allowUserOverrideReadAllowlist}}resolvedReadAllowFolders(e){return lk([...jS(e),...(0,Oo.r5)()])}async resolvedReadAllowGlobs(e){const t=function(e){return e.flatMap((e=>{const t=(0,Yo.jl)(e.trim()),r=t.indexOf("*");if(r<0||!(0,s.isAbsolute)(t))return[];const n="win32"===process.platform?Math.max(t.lastIndexOf("/",r),t.lastIndexOf("\\",r)):t.lastIndexOf("/",r);return n>=(0,s.parse)(t).root.length?[{folder:t.slice(0,n),rest:t.slice(n)}]:[]}))}(e),r=await lk(t.map((({folder:e})=>e)));return t.map((({rest:e},t)=>function(e,t,r={parse:s.parse}){return r.parse(e).root===e&&/[\\/]$/.test(e)?`${e}${t.slice(1)}`:`${e}${t}`}(r[t],e)))}async resolveWorkspaceReadRoots(e){const t=(0,s.join)((0,o.homedir)(),void 0!==e&&e.length>0?e:".cursor"),r=[...this.rootDirectories.map((e=>(0,s.join)(t,"projects",(0,So.r_)(e)))),...Kk.map((e=>(0,s.join)(t,e)))],n=this.rootDirectories.flatMap((e=>(0,Oo.W1)(e)??[]));return lk([...this.rootDirectories,...r,...n,...void 0===this.projectDir?[]:[this.projectDir]])}async shouldBlockReadInternal(e,{cursorIgnoreChecked:t=!1},r){const n=(0,Yo.o1)(e),o=await Cc(n);if(null===o)return{type:"unsafeResolution",message:uk("Read","path",n)};if(await this.ignoreService.isRepoBlocked(o))return{type:"adminBlock",source:"Team repo blocklist"};if(await this.isPathExplicitlyDenied("Read",n))return{type:"permissionsConfig"};if(!t&&!wS(o)&&!gS(o,{dataFolderName:(await this.getPermissions()).userSandboxDataFolderName})&&await this.ignoreService.isCursorIgnored(o))return{type:"cursorIgnore"};if(r){const e=await this.shouldBlockReadForBoundary(o);if(e)return e}return!1}async shouldBlockReadForBoundary(e){const{perms:t,setting:r}=await this.readControlSetting();if("workspace"!==r.boundary||"unrestricted"===t.approvalMode)return!1;const n=await this.resolveWorkspaceReadRoots(t.userSandboxDataFolderName);if(LS(e,n))return!1;const[o,s]=await Promise.all([this.resolvedReadAllowFolders(r.allowPaths),this.resolvedReadAllowGlobs(r.allowPaths)]);return!!NS({realAbsolutePath:e,setting:r,resolvedWorkspaceRoots:n,resolvedAllowFolders:o,resolvedAllowGlobs:s})&&{type:"needsApproval",approvalReason:r.enforcedByAdmin?"This reads a file outside your workspace and requires approval under your team's read policy.":"This reads a file outside your workspace.",approvalDetails:{type:"fileRead",path:e}}}async isProjectDirInternalPath(e,t){if(void 0===this.projectDir)return!1;const r=await DS(this.projectDir);return!!OS(r.resolution)&&vS(r.resolvedPath,e,t)}async isFreelyWritableOutsideWorkspace(e,t){return function(e){return Wk(e,{platform:process.platform,env:process.env,pathModule:s,homeDirectory:(0,o.homedir)()})}(e)||yS(e,Jk,{dataFolderName:t})||await this.isProjectDirInternalPath(e,Jk)}async shouldBlockWrite(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{QS(n,(0,$.VI)(e.withName("InteractivePermissionsService.shouldBlockWrite")),!1).ctx;const i=await DS(t);if(!OS(i.resolution))return{type:"unsafeResolution",message:FS(i.originalPath,i.resolution)};const a=i.resolvedPath,c=a;if(await this.ignoreService.isRepoBlocked(c))return{type:"adminBlock",source:"Team repo blocklist"};if(await this.isPathExplicitlyDenied("Write",a))return{type:"permissionsConfig"};const l=i.originalPath.split(s.sep).pop()?.toLowerCase()??"",u=a.split(s.sep).pop()?.toLowerCase()??"";if(".cursorignore"===l||".cursorignore"===u)return{type:"permissionsConfig"};if((0,Oo.dA)(i.originalPath)||(0,Oo.dA)(a))return{type:"permissionsConfig"};const d=await this.getPermissions();if(!wS(c)&&!gS(c,{dataFolderName:d.userSandboxDataFolderName})&&await this.ignoreService.isCursorIgnored(c))return{type:"cursorIgnore"};if("workspace_readonly"===d.userConfiguredPolicy.type)return{type:"permissionsConfig",isReadonly:!0};if(await this.isPathExplicitlyAllowed("Write",a))return!1;if("unrestricted"===d.approvalMode)return!1;const h=async()=>{let e,t,n="";try{n=await ji(a),e=!1}catch{e=!0}if(e)t=r;else{const e=e=>e.endsWith("\n")?e:`${e}\n`,{hunks:o}=(0,cS.YB)("a","b",e(n),e(r),"","",{context:2});t=o.map((e=>e.lines.map((e=>e.length>0?`${e[0]} ${e.slice(1)}`:e)).join("\n"))).join("\n...\n")}return{isNewFile:e,diffString:t}};let p;const f=[];for(const e of this.rootDirectories){const t=await DS(e);if(OS(t.resolution)){if((0,Yo.BJ)(a,t.resolvedPath)){p=t.resolvedPath;break}f.push(t.resolvedPath)}}const m=void 0===p?await async function(e,t,r={}){if(0===t.length)return;let n;for(let o=(0,s.dirname)(e);;o=(0,s.dirname)(o)){if((0,qs.$f)(o))return;const e=(0,s.join)(o,".git"),i=await(0,Co.lstat)(e).catch(TS);if(i?.isFile()){const s=await xS(e);if(void 0!==s){const{commonDir:e}=s;if(CS(o,t))return;if(t.some((t=>(0,Yo.BJ)(e,t))))return{root:o,commonDir:e};if(!await(r.isUntrustedExternalGitDir?.(e))&&(await(n??=Promise.all(t.map((e=>ES(e)))),n)).some((t=>void 0!==t&&AS(t,e))))return{root:o,commonDir:e}}}if((0,s.dirname)(o)===o)return}}(a,f,{isUntrustedExternalGitDir:e=>this.isFreelyWritableOutsideWorkspace(e,d.userSandboxDataFolderName)}):void 0;let g=!1;const w=p??m?.root;if(void 0!==w){const e=(0,s.relative)(w,a),t=e.split(s.sep).map((e=>"win32"===process.platform&&e.includes(":")?e.split(":")[0]:e));if(g=function(e){const t=e.replace(/\\/g,"/");return/(^|\/)\.cursor\/debug(?:-[a-zA-Z0-9-]+)?\.log$/i.test(t)}(e),!g){const e=await this.checkCursorFileProtection(t);if(e)return e}if("win32"===process.platform&&t.some((e=>e.includes("~")))){const{isNewFile:e,diffString:r}=await h();return{type:"needsApproval",approvalReason:`Protected config file: ${t[t.length-1]??""}`,approvalDetails:{type:"fileEdit",isNewFile:e,diffString:r,blockReason:"protectedConfig"}}}if(await(0,Oo.OK)(a,w)){const e=t[t.length-1]?.toLowerCase()??"",{isNewFile:r,diffString:n}=await h();return{type:"needsApproval",approvalReason:`Protected config file: ${e}`,approvalDetails:{type:"fileEdit",isNewFile:r,diffString:n,blockReason:"protectedConfig"}}}}if(void 0===p&&(void 0===m||"workspace"===(await this.readControlSetting()).setting.boundary)){if(await this.isFreelyWritableOutsideWorkspace(a,d.userSandboxDataFolderName))return!1;const e=`${(0,o.homedir)()}${s.sep}.cursor${s.sep}`;if(a.startsWith(e)){const e=a.split(s.sep).pop()?.toLowerCase()??"";if(e.endsWith(".md")||e.endsWith(".mdc")||".cursorrules"===e)return!1}const{isNewFile:t,diffString:r}=await h();return{type:"needsApproval",approvalReason:"Out of workspace",approvalDetails:{type:"fileEdit",isNewFile:t,diffString:r,blockReason:"outOfWorkspace"}}}if(g)return!1;if(!0===d.promptWorkspaceWrites){const{isNewFile:e,diffString:t}=await h();return{type:"needsApproval",approvalReason:"Workspace write",approvalDetails:{type:"fileEdit",isNewFile:e,diffString:t,blockReason:"workspaceWrite"}}}return!1}catch(e){n.error=e,n.hasError=!0}finally{YS(n)}}async shouldEnforceShellInvariantBlocks(e,t,r){const n=await this.getAdminCommandDenylistBlock(e,{command:t.command,parsingResult:t.parsingResult,toolCallId:t.toolCallId});if(void 0!==n)return{kind:"block",reason:n};const o=await Cc(t.workingDirectory);if(null===o){if(!0!==t.skipUnsafeWorkingDirectoryBlock)return{kind:"block",reason:{type:"unsafeResolution",message:uk("Command","working directory",t.workingDirectory)}}}else if(await this.ignoreService.isRepoBlocked(o))return{kind:"block",reason:{type:"adminBlock",source:"Team repo blocklist"}};const s=(await this.getPermissions()).userConfiguredPolicy,i=r??s;return"workspace_readonly"===s.type&&"workspace_readonly"!==i.type?{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}}:void 0!==r?{kind:"allow",policy:r}:!0!==t.resolveSkippedApprovalPolicy||"workspace_readonly"!==s.type?{kind:"allow",policy:void 0}:{kind:"allow",policy:await this.applyServerAndAdminPolicies({...s,skipStatsigDefaults:s.skipStatsigDefaults??!0})}}async shouldBlockShellCommand(e,t,r,n){const o="insecure_none"===n?.type,s=await this.shouldEnforceShellInvariantBlocks(e,{workingDirectory:r.workingDirectory,command:t,parsingResult:r.parsingResult,toolCallId:r.toolCallId},n);if("block"===s.kind)return s;const i=await this.getPermissions(),a=i.approvalMode,c="unrestricted"===a,l=i.userConfiguredPolicy,u=!i.dashboardTerminalAllowlistOverriddenByPermissionsFile;if(ek.info(e,"Shell permissions: evaluating shell command",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:Vk(l),requestedPolicyType:Vk(n),effectiveRequestedPolicyType:Vk(n??l),smartAllowlistEnabled:!0===i.smartAllowlistEnabled,hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId,hookForcesPrompt:$o(r.hookApprovalRequirement),classifierClassificationFailed:!0===r.classifierResult?.classificationFailed,classifierCommandCount:r.classifierResult?.commands.length??0,parserCommandCount:r.parsingResult.executableCommands.length,parsingFailed:r.parsingResult.parsingFailed,hasRedirects:r.parsingResult.hasRedirects,commandLength:t.length}),await this.shouldPromptForEmptyPlainShellAllowlist(t,i))return ek.info(e,"Shell permissions: prompting for empty allowlist",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:Vk(l),requestedPolicyType:Vk(n),hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId}),await this.requestApprovalForEmptyShellAllowlist(t,r,n??l);const d=r.parsingResult.executableCommands,h=r.parsingResult.parsingFailed,p=r.classifierResult,f=r.smartModeApprovalReason,m=r.smartModeApprovalRequestId,g=void 0!==p&&!p.classificationFailed&&p.commands.length>0?p:void 0,w="allowlist"===a&&i.smartAllowlistEnabled?g?.commands:void 0,y=void 0!==w,v=d.map(WS),b=w?w.map(Dk):v.map((e=>e.command)),S=void 0!==w?w.map($k):b.map((e=>[e.fullText.trim()].filter(Boolean))),k=void 0!==g?g.commands.map($k):v.map(zk);if(n||(n=i.userConfiguredPolicy),"insecure_none"!==n.type&&void 0===n.skipStatsigDefaults&&"insecure_none"!==l.type&&(n={...n,skipStatsigDefaults:l.skipStatsigDefaults??!0}),"insecure_none"!==l.type&&(0,Oo.$b)(l.networkPolicy)&&"insecure_none"!==n.type&&!(0,Oo._B)(n.networkPolicy)){const e=l.networkPolicy,t=n.networkPolicy?.allow;if(void 0!==t&&t.length>0&&e){const r=[...new Set([...e.allow??[],...t])];n={...n,networkPolicy:{...e,allow:r}}}else n={...n,networkPolicy:e}}let _;n=function({requestedPolicy:e,userConfiguredPolicy:t}){if("insecure_none"===e.type||"insecure_none"===t.type)return e;const r=(0,Oo.XX)(e.readBoundary,t.readBoundary),n="workspace"===r?(0,Oo.wG)(jk(e.readBoundary,e.additionalReadPaths),jk(t.readBoundary,t.additionalReadPaths)):void 0;return{...e,readBoundary:r,additionalReadPaths:n}}({requestedPolicy:n,userConfiguredPolicy:l}),p&&ek.info(e,"Smart allowlist: classifier result received",{classificationFailed:p.classificationFailed,suggestedSandboxMode:p.suggestedSandboxMode,commandCount:p.commands.length,suggestedAllowlistEntryCount:p.commands.filter((e=>e.suggestedAllowlistEntry)).length});const C=[],E=[];let x=[],P=[],R=[];const I=Ak(i.smartAllowlistDenylist??[]);if(I.length>0){P=[];const t=k.map((e=>e[0]??""));for(let e=0;eMk(r,e)))){const r=t[e];r&&P.push(r)}}P.length>0&&(ek.info(e,"Command blocklist: commands require approval",{count:P.length}),C.push(`In blocklist: ${P.join(", ")}`))}if(y&&p){const t=S.map((e=>e[0]??"")),r=i.allow.filter((e=>this.isShellEntry(e)));ek.info(e,"Smart allowlist: checking commands against lists",{commandCount:t.length,allowlistCount:r.length,commandBlocklistCount:I.length});const n=S.map((e=>r.some((t=>e.some((e=>this.matchesShell(t,e))))))),o=n.every(Boolean),s=[];for(let e=0;efunction(e){const t=e.name.trim();if(!t)return[];if(Hb(t))return[];const r=e.subcommandTokens.map((e=>e.trim())).filter(Boolean),n=e.arguments.map((e=>e.trim())).filter(Boolean),o=[t],s=[t];for(const e of r)s.push(e),o.push(s.join(" "));const i=[t,...n].join(" ");return o.includes(i)||o.push(i),Ak(o)}(e)))),R=s.map((e=>e.suggestedAllowlistEntry)).filter((e=>"string"==typeof e)).filter((e=>x.includes(e))),x.length>0){const e=Vb(x,R),t=e.length>0?e.join(", "):x.join(", ");E.push(`Not in allowlist: ${t}`)}_=o&&0===P.length,_&&ek.info(e,"Smart allowlist: all commands in allowlist, will check security",{commandCount:t.length})}const T="ask-every-time"===a||"insecure_none"===n.type&&"allowlist"===a?void 0:l,A=qk(v),$=b.map(((e,t)=>new Gk(e,n,T,S[t],y?A:v[t])));if((0===b.length||h&&!y)&&!c){ek.info(e,"Shell permissions: prompting after parser miss",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:Vk(n),userConfiguredPolicyType:Vk(l),isSmartAllowlistActive:y,parsingFailed:h,parserCommandCount:b.length,hasSmartModeApprovalReason:void 0!==f,hasSmartModeApprovalRequestId:void 0!==m});const o={type:Lw.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:Nk(f??(h?"Parser failed to parse command (possible bypass)":"Parser found no commands (possible bypass)"),await this.adminNetworkLimitReason(n)),isSandboxAvailable:!1,isSandboxEnabled:!1,canAllowlist:!1,notAllowedCommands:[],smartModeApprovalReason:f,smartModeApprovalRequestId:m}};r.onApprovalRequested?.();const s=await this.pendingDecisionStore.requestApproval(o);return s.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(n)}:{kind:"block",reason:{type:"userRejected",reason:s.reason}}}if(await this.hasHardDeny(e,$))return{kind:"block",reason:{type:"permissionsConfig",..."workspace_readonly"===l.type?{isReadonly:!0}:{}}};const{allowlistOfferSafe:M,redirectsAllowlistSafe:D}=await this.computeRedirectAllowlistSafety(r.parsingResult,r.workingDirectory,"insecure_none"===l.type||"workspace"!==l.readBoundary),O=await this.teamSettingsService.getAutoRunControls(),F={type:"insecure_none"};for(const e of $)await this.cmdIsAllowedByAllowlist(e,{redirectsAllowlistSafe:D,autoRunControls:O,applyTeamAllowlist:u})&&e.approveWithPolicy(F);for(const e of $)O&&this.isInTeamBlocklist(O,e)&&e.deny();const N=await this.teamSettingsService.getDeleteFileProtection();if(N)for(const e of $)"rm"===e.command.name&&e.deny();const L=this.buildShellApprovalDecisionFacts({commands:$,autoRunControls:O,shouldApplyTeamShellAllowlist:u,deleteProtectionEnabled:N,softDenylistedCommands:P});if("workspace_readonly"===l.type&&"workspace_readonly"!==n.type)return ek.info(e,"Shell permissions: blocked by readonly mode"),{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}};const j=$o(r.hookApprovalRequirement),U=r.hookApprovalRequirement?.reason,B=o&&"insecure_none"!==l.type&&function(e){if(/\brimraf\b/i.test(e))return!0;for(const t of e.replace(/[\\`^]\r?\n/g," ").split(/(?|])&|\|\||[;\n]/)){let e=!1;for(const r of t.split("|")){if(e&&JS.test(r)||XS(r,JS,ZS)||XS(r,/(?0&&(L.hasSecurityDenies||L.hasSoftDenies||!L.allCommandsRunnable);if(void 0!==f&&G.push(f),j&&(V||G.push(U?`Hook requested approval: ${U}`:"Hook requested approval"),z=!1),B&&(V||G.push("Recursive delete outside the sandbox"),z=!1),C.length>0&&(V||G.push(...C),z=!1),!V)if(y&&E.length>0)G.push(...E);else if(L.unapprovedCommands.length>0){const e=Vb(this.generateAllowlistPatterns(L.unapprovedCommands)),t=e.length>0?e.join(", "):L.unapprovedCommands.map((e=>e.command.fullText)).join(", ");G.push(`Not in allowlist: ${t}`)}if(L.hasSecurityDenies&&(V||(L.rmDeniedByDeleteProtection.length>0&&G.push("Delete protection is enabled"),L.teamBlocklistedCommands.length>0&&G.push(`In team blocklist: ${L.teamBlocklistedCommands.map((e=>e.command.name)).join(", ")}`)),z=!1),K){const t=L.notInTeamAllowlist.map((e=>e.command.fullText)).join(", ");ek.info(e,"Shell permissions: commands not in team allowlist",{commandCount:L.notInTeamAllowlist.length}),V||G.push(`Not in team allowlist: ${t}`),z=!1}const J="unrestricted"===a&&"workspace_readonly"===n.type,Z="unrestricted"!==a||J?n:{type:"insecure_none"},X=Nk(...G,await this.adminNetworkLimitReason(Z)),Q=[];if(z){const e=void 0!==f?$.filter((e=>"allowlisted"!==e.state)):L.unapprovedCommands;Q.push(...this.generateAllowlistPatterns(e))}const Y=y&&E.length>0,ee=Y?x:Q,te=Y&&R.length>0?R:void 0,re="insecure_none"!==n.type&&"insecure_none"!==l.type,ne="insecure_none"!==n.type,oe=[void 0!==f?"smart_mode_approval":void 0,j?"hook_forces_prompt":void 0,B?"unsandboxed_recursive_delete":void 0,C.length>0?"command_blocklist":void 0,y&&E.length>0?"smart_allowlist_miss":void 0,L.unapprovedCommands.length>0?"unapproved_commands":void 0,L.hasSecurityDenies?"security_denies":void 0,K?"team_allowlist_miss":void 0].filter((e=>void 0!==e));ek.info(e,"Shell permissions: requesting shell approval",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:Vk(n),userConfiguredPolicyType:Vk(l),isSandboxAvailable:re,isSandboxEnabled:ne,canAllowlist:z,isSmartAllowlistActive:y,hasSmartModeApprovalReason:void 0!==f,hasSmartModeApprovalRequestId:void 0!==m,hookForcesPrompt:j,approvalReasonTypes:oe,commandCount:$.length,unapprovedCommandCount:L.unapprovedCommands.length,deniedCommandCount:L.deniedCommands.length,notInTeamAllowlistCount:L.notInTeamAllowlist.length,notAllowedCommandCount:ee.length,suggestedAllowlistEntryCount:te?.length??0,allCommandsRunnable:L.allCommandsRunnable,allCommandsAllowlisted:L.allCommandsAllowlisted,allCommandsPreapproved:L.allCommandsPreapproved,hasSecurityDenies:L.hasSecurityDenies,hasSoftDenies:L.hasSoftDenies});const se={type:Lw.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:X,isSandboxAvailable:"allowlist"===a&&re,isSandboxEnabled:!("allowlist"!==a&&!J)&&ne,canAllowlist:z,notAllowedCommands:ee,suggestedAllowlistEntries:te,smartModeApprovalReason:f,smartModeApprovalRequestId:m}};r.onApprovalRequested?.();const ie=await this.pendingDecisionStore.requestApproval(se);return ie.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(Z)}:{kind:"block",reason:{type:"userRejected",reason:ie.reason}}}async isShellCommandFullyAllowlisted(e,t,r){const n=e.withName("InteractivePermissionsService.isShellCommandFullyAllowlisted"),o=await this.getPermissions(),s=!o.dashboardTerminalAllowlistOverriddenByPermissionsFile;if("allowlist"!==o.approvalMode)return!1;if("workspace_readonly"===o.userConfiguredPolicy.type)return!1;const{redirectsAllowlistSafe:i}=await this.computeRedirectAllowlistSafety(r.parsingResult,r.workingDirectory,"insecure_none"===o.userConfiguredPolicy.type||"workspace"!==o.userConfiguredPolicy.readBoundary);if(!i)return!1;const a=r.classifierResult,c=void 0!==a&&!a.classificationFailed&&a.commands.length>0?a:void 0,l=(o.smartAllowlistEnabled??!1)&&void 0!==c;if(r.parsingResult.parsingFailed&&!l)return!1;const u=r.parsingResult.executableCommands.map(WS),d=l?c.commands.map(Dk):u.map((e=>e.command));if(0===d.length)return!1;const h=l?c.commands.map($k):d.map((e=>[e.fullText.trim()].filter(Boolean))),p=void 0!==c?c.commands.map($k):u.map(zk),f={type:"insecure_none"},m=qk(u),g=d.map(((e,t)=>new Gk(e,f,void 0,h[t],l?m:u[t])));if(await this.hasHardDeny(n,g))return!1;const w=Ak(o.smartAllowlistDenylist??[]);if(w.length>0)for(const e of p)if(e&&0!==e.length&&w.some((t=>Mk(e,t))))return!1;if(await this.teamSettingsService.getDeleteFileProtection()&&g.some((e=>"rm"===e.command.name)))return!1;const y=await this.teamSettingsService.getAutoRunControls();if(void 0!==y&&g.some((e=>this.isInTeamBlocklist(y,e))))return!1;for(const e of g)if(!await this.cmdIsAllowedByAllowlist(e,{redirectsAllowlistSafe:i,autoRunControls:y,applyTeamAllowlist:s}))return!1;return!0}async applyServerAndAdminPolicies(e){if("insecure_none"===e.type)return e;const t=this.rootDirectories.at(0)??(0,o.homedir)(),{userSandboxDataFolderName:r,teamAdminPolicy:n}=await this.getPermissions(),i=void 0!==r&&r.length>0?(0,s.join)((0,o.homedir)(),r,"sandbox.json"):this.perUserSandboxConfigPath,a=await this.foldPerUserFilePolicy(e,i),c=a.skipStatsigDefaults?a:await this.applyStatsigDefaults(a),l=await this.loadPerRepoFilePolicy(c,t),u=await this.resolveTeamAdminLayer(n);if("unavailable"===u){const{policy:e}=await(0,Oo.resolveSandboxPolicyForWorkspace)(t,{perUser:c,perRepo:l});return function(e){return"insecure_none"===e.type?e:{...e,networkPolicy:(0,Oo.Po)(),readBoundary:"workspace",additionalReadPaths:[]}}(e)}const d=void 0===u?void 0:Ok(c.type,u),h=(0,Oo._B)(e.networkPolicy)&&!Fk(d?.networkPolicy),{policy:p}=await(0,Oo.resolveSandboxPolicyForWorkspace)(t,{perUser:c,perRepo:l,teamAdmin:d});return h?{...p,networkPolicy:(0,Oo.T6)()}:p}async resolveLinkedWorktreeSandboxGrants(e,t){if("workspace_readwrite"!==e.type||"workspace"===e.readBoundary)return;const{perms:r,setting:n}=await this.readControlSetting();if("workspace"===n.boundary||"unavailable"===r.teamAdminPolicy)return;const i=r.userSandboxDataFolderName;if(void 0===e.readBoundary){const t=this.rootDirectories.at(0)??(0,o.homedir)(),n=void 0!==i&&i.length>0?(0,s.join)((0,o.homedir)(),i,"sandbox.json"):this.perUserSandboxConfigPath,a="readBoundary"in r.userConfiguredPolicy&&void 0!==r.userConfiguredPolicy.readBoundary?{...e,readBoundary:r.userConfiguredPolicy.readBoundary}:e,c=await this.foldPerUserFilePolicy(a,n),l=await this.loadPerRepoFilePolicy(c,t);if("workspace"===(l?.readBoundary??c.readBoundary))return}const a=[];for(const e of this.rootDirectories){if((0,qs.$f)(e))continue;const t=await DS(e);OS(t.resolution)&&!wS(t.resolvedPath)&&a.push(t.resolvedPath)}if(0===a.length)return;let c;if(!(0,qs.$f)(t.workingDirectory)){const e=await DS(t.workingDirectory);OS(e.resolution)&&(c=e.resolvedPath)}return async function(e,t={}){if(0===e.length)return;const r=await Promise.all(e.map((e=>ES(e)))),n=[];for(const o of r)void 0===o||n.some((e=>AS(e,o)))||!e.some((e=>(0,Yo.BJ)(o,e)))&&await(t.isUntrustedExternalGitDir?.(o))||n.push(o);if(0===n.length)return;const o=[],i=[],a=void 0!==t.command||void 0!==t.realWorkingDirectory;for(const r of n){const n=await _S((0,s.join)(r,"worktrees"),256),c=await(0,Or.PH)(n,(e=>kS((0,s.join)(r,"worktrees",e),r,!0===t.excludeAgentWorktrees,a?{command:t.command,realWorkingDirectory:t.realWorkingDirectory}:void 0)),{max:16});let l=!1;for(const r of c){if(o.length>=16)break;void 0===r||o.some((e=>AS(e,r)))||e.some((e=>(0,Yo.BJ)(r,e)))||CS(r,e)||await(t.isExcludedWorktreeRoot?.(r))||(o.push(r),l=!0)}l&&i.push(r)}return 0===o.length?void 0:{roots:o,commonDirs:i}}(a,{command:t.command,realWorkingDirectory:c,excludeAgentWorktrees:!0,isUntrustedExternalGitDir:e=>this.isFreelyWritableOutsideWorkspace(e,i),isExcludedWorktreeRoot:async e=>await this.isFreelyWritableOutsideWorkspace(e,i)||await this.ignoreService.isRepoBlocked(e)})}async foldPerUserFilePolicy(e,t=this.perUserSandboxConfigPath){const r=await(0,Oo.tv)(t,(0,o.homedir)());if(!r||"insecure_none"===r.type)return e;let n=(0,Oo.fZ)(r.networkPolicy,e.networkPolicy);n&&void 0!==e.networkPolicy?.default&&(n={...n,default:e.networkPolicy.default});const s=(0,Oo.s9)(r.additionalReadonlyPaths,e.additionalReadonlyPaths),i={...e,networkPolicy:n,additionalReadonlyPaths:s.length>0?s:void 0,readBoundary:r.readBoundary??e.readBoundary,additionalReadPaths:void 0!==r.additionalReadPaths?r.additionalReadPaths:e.additionalReadPaths,privateTmp:r.privateTmp??e.privateTmp};if("workspace_readwrite"===e.type&&"workspace_readwrite"===r.type){const t=(0,Oo.s9)(r.additionalReadwritePaths,e.additionalReadwritePaths);return{...i,additionalReadwritePaths:t.length>0?t:void 0}}return i}async applyStatsigDefaults(e){const t=await this.teamSettingsService.getDefaultNetworkAllowlist();if(!t.available||0===t.allowlist.length)return e;if((0,Oo._B)(e.networkPolicy))return e;const r={default:"deny",allow:dk(t.allowlist)};return{...e,networkPolicy:(0,Oo.fZ)(e.networkPolicy,r)}}async loadPerRepoFilePolicy(e,t){const r=await(0,Oo.tv)((0,s.join)(t,".cursor","sandbox.json"),t);if(r){if("1"===process.env[Zv.K4]){const n=(0,Oo.fB)({perUser:e,perRepo:r},t).perRepo;return"insecure_none"===n?.type?void 0:n}if("insecure_none"!==r.type)return r.type!==e.type?Ok(e.type,{networkPolicy:r.networkPolicy,additionalReadonlyPaths:r.additionalReadonlyPaths,..."additionalReadwritePaths"in r?{additionalReadwritePaths:r.additionalReadwritePaths}:{},disableTmpWrite:r.disableTmpWrite,networkPolicyStrict:r.networkPolicyStrict,readBoundary:r.readBoundary,additionalReadPaths:r.additionalReadPaths,privateTmp:r.privateTmp}):r}}async resolveTeamAdminLayer(e){return void 0!==e?"unavailable"===e?"unavailable":"workspace"===(t=e).readBoundary?t:void 0===t.networkPolicy?{}:{networkPolicy:t.networkPolicy}:async function(e){const{teamSettings:t}=e,r=e.adminNetworkControlsEnabled?(i=await t.getNetworkAccessControls()).available?0!==i.allowlist.length||0!==i.denylist.length?{...i.allowlist.length>0?{default:"deny",allow:dk(i.allowlist)}:{},...i.denylist.length>0?{deny:dk(i.denylist)}:{}}:void 0:(0,Oo.Po)():void 0,[n,o]=await Promise.all([t.isReadControlEnabled?.()??!0,t.getSandboxingControls()]),s=void 0===r?{}:{networkPolicy:r};var i;return n&&"workspace"===o.readBoundary?{...s,readBoundary:"workspace",additionalReadPaths:o.readAllowlistPaths??[],allowUserOverrideReadPaths:o.allowUserOverrideReadAllowlist}:void 0===r?void 0:s}({teamSettings:this.teamSettingsService,adminNetworkControlsEnabled:this.adminNetworkControlsEnabled});var t}async adminNetworkLimitReason(e){if("insecure_none"===e.type||!(0,Oo._B)(e.networkPolicy))return;const{teamAdminPolicy:t}=await this.getPermissions(),r=await this.resolveTeamAdminLayer(t);return function(e){if(Fk(e))return void 0!==e.allow&&e.allow.length>0?"Network access limited to your admin's allowlist":"deny"===e.default?"Network access limited by your admin":"Network access excludes domains your admin blocks"}("unavailable"===r?(0,Oo.Po)():r?.networkPolicy)}async getAdminReadSandboxing(){const e=await this.getPermissions();if("unavailable"===e.teamAdminPolicy)return{readBoundary:"workspace"};const{enabled:t,boundary:r}=await this.adminReadControls(e);return{readBoundary:t&&"workspace"===r?"workspace":void 0}}async isInShellAllowlist(e){if(!e.allowlistable)return!1;const t=await this.getPermissions(),r=e.readsArguments?e.matchForms.map((e=>`${e} \0`)):e.matchForms;return t.allow.some((e=>this.isShellEntry(e)&&r.some((t=>this.matchesShell(e,t)))))}isInTeamBlocklist(e,t){const r=[...t.wrapperForms,t.command.fullText];return e.blocked.some((e=>r.some((t=>this.matchesAutoRunCommand(t,e)))))}isInTeamAllowlist(e,t){return!!t.allowlistable&&e.allowed.some((e=>this.matchesAutoRunCommand(t.command.fullText,e)))}async computeRedirectAllowlistSafety(e,t,r){const n=e.hasRedirects,i=e.parsingFailed,a=!0===e.allRedirectsAreDevNull,c=!(!n||a||i)&&await async function({parsingResult:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n=!0,resolvePathForPermissions:i=DS,pathModule:a=s,tempPathOptions:c={platform:process.platform,env:process.env,pathModule:a,homeDirectory:(0,o.homedir)()}}){if(!e.hasRedirects)return!0;const l=e.redirects;if(0===l.length)return!1;const u=e.executableCommands.length>1,d=await Pk({parsingResult:e,workingDirectory:t,resolvePathForPermissions:i,pathModule:a}),h=hk();for(const e of l){if(wk(e))continue;const o=u?hk():h,{operator:s,targetText:l}=e,f=e.destinationFds;if(">&"===s){const e=gk(l),t=void 0===e?void 0:o.fdTargets.get(e);if("original-stdout"!==(p=t)&&"original-stderr"!==p&&"dev-null"!==p&&"workspace-file"!==p&&"tmp-file"!==p){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}for(const e of f)o.fdTargets.set(e,t);continue}if("<&"===s){const e=gk(l),t=void 0===e?void 0:o.fdTargets.get(e);if("dev-null"!==t){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}for(const e of f)o.fdTargets.set(e,t);continue}if("/dev/null"===l){for(const e of f)o.fdTargets.set(e,"dev-null");continue}if(!fk(s)||void 0===l||"word"===e.targetNodeType&&!yk(l,a)){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}const m=await Rk({targetText:l,workingDirectory:t,workingDirectories:d,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:i,pathModule:a,tempPathOptions:c});if(!m){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}for(const e of f)o.fdTargets.set(e,m)}var p;return!0}({parsingResult:e,workingDirectory:t,rootDirectories:this.rootDirectories,allowTmpRedirects:r}),l=await Tk({parsingResult:e,workingDirectory:t,rootDirectories:this.rootDirectories,allowTmpRedirects:r}),u=!function({parsingResult:e,hasRedirects:t,parsingFailed:r,allRedirectsAreAllowlistSafe:n,allRedirectsAreWorkspaceFileSafe:o}){return!(!t||r||n||o)&&(0===e.redirects.length||e.redirects.some(mk))}({parsingResult:e,hasRedirects:n,parsingFailed:i,allRedirectsAreAllowlistSafe:a,allRedirectsAreWorkspaceFileSafe:c})&&l;return{allowlistOfferSafe:(!n||a||c)&&l&&!i,redirectsAllowlistSafe:u}}async cmdIsAllowedByAllowlist(e,t){return!!t.redirectsAllowlistSafe&&(!!await this.isInShellAllowlist(e)||t.applyTeamAllowlist&&void 0!==t.autoRunControls&&this.isInTeamAllowlist(t.autoRunControls,e))}buildShellApprovalDecisionFacts({commands:e,softDenylistedCommands:t,autoRunControls:r,shouldApplyTeamShellAllowlist:n,deleteProtectionEnabled:o}){const s=e.filter((e=>"denied"===e.state)),i=e.filter((e=>"approvable"===e.state)),a=n&&r?.enabled?e.filter((e=>!this.isInTeamAllowlist(r,e))):[],c=s.filter((e=>void 0!==r&&this.isInTeamBlocklist(r,e))),l=o?s.filter((e=>"rm"===e.command.name)):[];return{hasSecurityDenies:s.length>0,hasSoftDenies:t.length>0,hasTeamAllowlistMisses:a.length>0,allCommandsRunnable:e.every((e=>e.isRunnable())),allCommandsAllowlisted:e.every((e=>"allowlisted"===e.state)),allCommandsPreapproved:e.every((e=>"preapproved"===e.state)),canAllowlistInPrompt:0===s.length&&0===a.length,unapprovedCommands:i,deniedCommands:s,notInTeamAllowlist:a,teamBlocklistedCommands:c,rmDeniedByDeleteProtection:l}}getShellAutoApprovalPolicy({approvalMode:e,isUnrestricted:t,requestedPolicy:r,facts:n,preserveRequestedPolicyForAllowlistedCommands:o}){if(!n.hasSecurityDenies&&!n.hasSoftDenies&&n.allCommandsRunnable){if(t)return"workspace_readonly"===r.type?r:{type:"insecure_none"};if("allowlist"===e)return n.allCommandsAllowlisted&&!o&&"workspace_readonly"!==r.type?{type:"insecure_none",allowlistEscalated:!0}:r}}async getPermissions(){return await this.permissionsProvider.getPermissions()}hasLocalShellControls(e){return e.allow.some((e=>this.isShellEntry(e)))||e.deny.some((e=>this.isShellEntry(e)))||(e.smartAllowlistDenylist?.length??0)>0}hasTeamShellControls(e,t=!0){return void 0!==e&&(t&&(e.enabled||e.allowed.length>0)||e.blocked.length>0)}async shouldPromptForEmptyPlainShellAllowlist(e,t){if("allowlist"!==t.approvalMode||"insecure_none"!==t.userConfiguredPolicy.type||0===e.trim().length||this.hasLocalShellControls(t))return!1;const[r,n]=await Promise.all([this.teamSettingsService.getAutoRunControls(),this.teamSettingsService.getDeleteFileProtection()]);return!this.hasTeamShellControls(r,!t.dashboardTerminalAllowlistOverriddenByPermissionsFile)&&!n}async requestApprovalForEmptyShellAllowlist(e,t,r){const n=await this.getEmptyShellAllowlistCandidates(t);t.onApprovalRequested?.();const o=await this.pendingDecisionStore.requestApproval({type:Lw.Shell,toolCallId:t.toolCallId,details:{command:e,workingDirectory:t.workingDirectory,timeout:t.timeout,reason:Nk(t.smartModeApprovalReason??"Shell allowlist is empty",await this.adminNetworkLimitReason(r)),isSandboxAvailable:!1,isSandboxEnabled:!1,canAllowlist:n.length>0,notAllowedCommands:n,smartModeApprovalReason:t.smartModeApprovalReason,smartModeApprovalRequestId:t.smartModeApprovalRequestId}});return o.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(r)}:{kind:"block",reason:{type:"userRejected",reason:o.reason}}}async getEmptyShellAllowlistCandidates(e){const t=e.parsingResult;return t.parsingFailed||0===t.executableCommands.length||t.hasRedirects&&!0!==t.allRedirectsAreDevNull||!await Tk({parsingResult:t,workingDirectory:e.workingDirectory,rootDirectories:this.rootDirectories,allowTmpRedirects:!0})?[]:this.generateAllowlistPatterns(t.executableCommands.map(WS))}async getAdminCommandDenylistBlock(e,t){const r=(await this.teamSettingsService.getAdminCommandDenylist()).rules;if(0===r.length)return;const n=bs({matchForms:t.parsingResult?gs({command:t.command,parsingResult:t.parsingResult}):[t.command],blockedCommands:r});return void 0!==n?(ek.info(e,"Admin command denylist hard-blocked shell at execution time",{toolCallId:t.toolCallId,parsingFailed:t.parsingResult?.parsingFailed??!0,parserCommandCount:t.parsingResult?.executableCommands.length??0}),{type:"adminCommandDenylist",pattern:n}):void 0}async hasHardDeny(e,t){const r=await this.getPermissions();return t.some((e=>r.deny.some((t=>this.isShellEntry(t)&&[...e.wrapperForms,...e.matchForms].some((e=>this.matchesShell(t,e)))))))}isShellEntry(e){return null!==Bk(e)}isPathEntry(e,t){return new RegExp(`^\\s*${e}\\s*\\(`).test(t)}matchesShell(e,t){const r=Bk(e);if(!r)return!1;const n=t.trim(),o=this.extractBaseCommand(n);if(null!==r.argsPattern){const e=n.includes(" ")?n.slice(n.indexOf(" ")+1).trim():"",t=this.matchGlob(r.commandPattern,o)||this.matchGlob(r.commandPattern,n),s=this.matchGlob(r.argsPattern,e);if(t&&s)return!0}return!!this.matchGlob(r.fullPattern,n)||!!n.startsWith(`${r.fullPattern} `)||!!this.matchGlob(r.fullPattern,o)||o===r.fullPattern}async checkCursorFileProtection(e){if(!e.some((e=>".cursor"===e.toLowerCase()||".vscode"===e.toLowerCase())))return null;const t=e[e.length-1]?.toLowerCase()??"";return t.endsWith(".md")||t.endsWith(".mdc")||".cursorrules"===t?null:await this.teamSettingsService.getDotCursorProtection()?{type:"permissionsConfig"}:null}extractBaseCommand(e){const t=e.trim(),r=t.indexOf(" ");return-1===r?t:t.substring(0,r)}generateAllowlistPatterns(e){const t=[],r=["git","npm","yarn","pnpm","docker","pip","systemctl","uv","cargo","bun","npx"];for(const{command:n,allowlistable:o}of e)o&&!Hb(n.name)&&(r.includes(n.name)&&n.args.length>0&&"word"===n.args[0].type?t.push(`${n.name} ${n.args[0].value}`):t.push(n.name));return[...new Set(t)]}pathEntryRawPattern(e,t){const r=t.match(function(e){return"Read"===e?Yk:e_}(e));if(r)return(r[1]??"").trim()}compileReadDenyMatcher(e){try{const t=this.pathEntryRawPattern("Read",e);if(void 0===t)return()=>!1;const r=(0,ms.b)((0,Yo.jl)(t));return e=>r(e)}catch(e){return()=>{throw e}}}matchesPathEntry(e,t,r){const n=this.pathEntryRawPattern(e,t);return void 0!==n&&this.matchGlob((0,Yo.jl)(n),r)}async isPathExplicitlyDenied(e,t){return(await this.getPermissions()).deny.some((r=>this.isPathEntry(e,r)&&this.matchesPathEntry(e,r,t)))}async isPathExplicitlyAllowed(e,t){return(await this.getPermissions()).allow.some((r=>this.isPathEntry(e,r)&&this.matchesPathEntry(e,r,t)))}matchGlob(e,t){return(0,ms.T)(e,t)}async addToAllowList(e,t,r){const n=`${t}(${r})`;await this.permissionsProvider.updatePermissions((e=>{const t=e.allow.includes(n)?e.allow:[...e.allow,n];return{...e,allow:t}}))}async addToDenyList(e,t,r){const n=`${t}(${r})`;await this.permissionsProvider.updatePermissions((e=>{const t=e.deny.includes(n)?e.deny:[...e.deny,n];return{...e,deny:t}}))}async shouldBlockMcp(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{QS(o,(0,$.VI)(e.withName("InteractivePermissionsService.shouldBlockMcp")),!1);const{name:s,toolName:i,providerIdentifier:a,args:c}=t,l=function(e,t){if(void 0!==t)return t;const r=e;return void 0!==r.annotations?r.annotations:Mb(r.annotationsJson)}(t,r?.annotations),u=e=>{this.mcpAllowlistLog?.(e)};if(u(`[permissions-service] shouldBlockMcp: toolName="${i}", providerIdentifier="${a}"`),await this.isComputerUseDisabledByAdminFor(a))return u(`[permissions-service] shouldBlockMcp: BLOCKED (Computer Use off for team) toolName="${i}", providerIdentifier="${a}"`),{type:"unsafeResolution",message:"Computer Use is turned off by your team admin. Ask the user to do it instead."};const d=await this.mcpAdminToolLimitRefusal(e,{resolvedTool:n?.resolvedTool,toolName:i});if(void 0!==d)return u(`[permissions-service] shouldBlockMcp: BLOCKED (team tool limit) toolName="${i}", providerIdentifier="${a}"`),{type:"unsafeResolution",message:d};const h=await this.computerUseDecision(t,r);if(await this.isMcpExplicitlyDenied(e,a,i))return u(`[permissions-service] shouldBlockMcp: BLOCKED (explicitly denied) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig"};const p=await this.getPermissions(),f="workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode;if(!0===n?.alreadyApproved&&!f&&"block"!==h.kind&&"askEachCall"!==h.kind)return!1;const m=await this.teamSettingsService.getMcpToolControls(),g=!0===m?.enabled&&!(void 0!==n?.client&&!0===await(this.teamSettingsService.isHostMcpBridgeClient?.(n.client))),w=g&&"block"!==h.kind?{kind:"notComputerUse"}:h,y=void 0!==t.smartModeApproval?.reason&&f,v=Qk({server:Xk(a),tool:i});let b,S,k;switch(w.kind){case"block":return u(`[permissions-service] shouldBlockMcp: BLOCKED (Computer Use app) toolName="${i}", providerIdentifier="${a}"`),{type:"unsafeResolution",message:w.message};case"noAccess":if(!f&&!await this.teamSettingsService.getShouldBlockMcp())return u(`[permissions-service] shouldBlockMcp: ALLOWED (Computer Use no access) toolName="${i}", providerIdentifier="${a}"`),!1;b=v,k=!0;break;case"app":if(!y&&(this.computerUseAppsAllowedForSession.includes(w.entry)||await this.isComputerUseAppSaved(w.entry)))return u(`[permissions-service] shouldBlockMcp: ALLOWED (Computer Use app grant) toolName="${i}", providerIdentifier="${a}"`),!1;b=w.entry,S=w.app,k=!1;break;case"askEachCall":b=void 0,S=w.app&&{...w.app,allowOnce:!0},k=!1;break;case"notComputerUse":b=v,k=!0}const _=k||void 0!==b,C=t.smartModeApproval?.reason;if(void 0!==C)return"workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode?(u(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode, Smart Mode forced approval) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig",isReadonly:!0}):(u(`[permissions-service] shouldBlockMcp: needsApproval (Smart Mode) toolName="${i}", providerIdentifier="${a}"`),!(g?this.isMcpInTeamAllowlist(m,{providerIdentifier:a,toolName:i,annotations:l}):k&&await this.isMcpExplicitlyAllowed(e,a,i))&&!("unrestricted"===p.approvalMode&&!await this.teamSettingsService.getShouldBlockMcp())&&{type:"needsApproval",approvalReason:C,approvalDetails:{type:"mcp",name:s,toolName:i,...ck(r,l),providerIdentifier:a,args:c,reason:"smartMode",canAllowlist:_&&!this.isComputerUseServer(a),smartModeApprovalReason:C,smartModeApprovalRequestId:t.smartModeApproval?.requestId,allowlistEntry:b,computerUseApp:S}});if(g){const t=this.isMcpInTeamAllowlist(m,{providerIdentifier:a,toolName:i,annotations:l});if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"team",outcome:t?"pass":"fail"}),t)return u(`[permissions-service] shouldBlockMcp: ALLOWED (in admin MCP allowlist) toolName="${i}", providerIdentifier="${a}"`),!1}else if(k){const t=await this.isMcpExplicitlyAllowed(e,a,i);if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"user",outcome:t?"pass":"fail"}),t)return u(`[permissions-service] shouldBlockMcp: ALLOWED (explicitly in allowlist) toolName="${i}", providerIdentifier="${a}"`),!1}if("workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode)return u(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig",isReadonly:!0};if("unrestricted"===p.approvalMode){if(!await this.teamSettingsService.getShouldBlockMcp())return u(`[permissions-service] shouldBlockMcp: ALLOWED (auto-run, no team block) toolName="${i}", providerIdentifier="${a}"`),!1;u(`[permissions-service] shouldBlockMcp: needsApproval (auto-run but team blocks MCP) toolName="${i}", providerIdentifier="${a}"`)}return u(`[permissions-service] shouldBlockMcp: needsApproval (not in allowlist) toolName="${i}", providerIdentifier="${a}", approvalMode="${p.approvalMode}"`),{type:"needsApproval",approvalReason:`MCP tool: ${i}`,approvalDetails:{type:"mcp",name:s,toolName:i,...ck(r,l),providerIdentifier:a,args:c,canAllowlist:_,allowlistEntry:b,computerUseApp:S}}}catch(e){o.error=e,o.hasError=!0}finally{YS(o)}}async mcpAdminToolLimitRefusal(e,{resolvedTool:t,toolName:r}){if(void 0===t||void 0===this.enforceMcpAdminToolLimits)return;if(!await this.enforcesMcpAdminToolLimits())return void(void 0!==this.onMcpAdminToolLimitCheck&&this.judgeMcpAdminToolLimit(t,r).then((e=>this.reportMcpAdminToolLimitCheck("shadow",e)),(()=>{})));const n=await this.judgeMcpAdminToolLimit(t,r);this.reportMcpAdminToolLimitCheck("enforce",n);const o=n?.outcome;switch(o){case void 0:case"within_limit":return;case"outside_limit":return rk.increment(e,1,{reason:"outside_limit"}),"Your team's admin limits this MCP tool";case"settings_unavailable":if(!0===n?.ranWithoutLimit)return;return rk.increment(e,1,{reason:"settings_unavailable"}),"Your team's MCP settings could not be read, so this MCP tool can't run right now";case"unknown_server":return rk.increment(e,1,{reason:"unknown_server"}),nk;default:return o}}async judgeMcpAdminToolLimit(e,t){if("unresolved"===e)return{outcome:"unknown_server"};const r=await(this.teamSettingsService.getMcpAdminToolLimit?.(e.client));if(void 0!==r)switch(r.kind){case"none":return;case"settings_unavailable":return{outcome:"settings_unavailable",...void 0===r.failure?{}:{settingsFailure:r.failure},...!0===r.noLimitApplies?{ranWithoutLimit:!0}:{}};case"unknown_server":return{outcome:"unknown_server"};case"limit":return{outcome:jb(r.policy,{name:t,annotations:e.annotations})?"within_limit":"outside_limit"};default:return r}}reportMcpAdminToolLimitCheck(e,t){if(void 0!==t)try{this.onMcpAdminToolLimitCheck?.({mode:e,...t})}catch{}}async enforcesMcpAdminToolLimits(){if(void 0===this.enforceMcpAdminToolLimits)return!1;try{return await this.enforceMcpAdminToolLimits()}catch{return!1}}async computerUseDecision(e,t){const r=this.computerUse;if(void 0===r||!this.isComputerUseServer(e.providerIdentifier))return{kind:"notComputerUse"};const n=await r.isOwnServer(Xk(e.serverIdentifier||e.providerIdentifier),t);if(!1===n)return{kind:"notComputerUse"};const o=await async function(e,t){const r=sS(e.meta?.["cursor/computerUseScope"])??sS(t.toolScopes?.[e.toolName]);if(void 0===r)return{kind:"screen"};let n;if(void 0!==r.appSelectorArgs){const t=Object.entries(r.appSelectorArgs).flatMap((([t,r])=>oS(t)&&void 0!==r&&void 0!==e.args[r]&&null!==e.args[r]?[{selector:t,value:e.args[r]}]:[]));if(0===t.length){const t=new Intl.ListFormat("en",{type:"disjunction"}).format(Object.values(r.appSelectorArgs).filter((e=>void 0!==e)));return{kind:"noAppSelector",message:`${e.toolName} needs exactly one of ${t} to name the app. Call it again with one of them.`}}const o=t.filter((({selector:e,value:t})=>function(e,t){return"pid"===e?"number"==typeof t&&Number.isInteger(t)||"string"==typeof t&&aS.test(t):"string"==typeof t&&t.length>0}(e,t)));if(1!==o.length){for(const{value:e}of t){const t="string"==typeof e?Yb(e.trim()):void 0;if(void 0!==t)return{kind:"app",app:t}}return{kind:"unknownApp"}}n=function(e,t){if("pid"===e){const e="string"==typeof t&&aS.test(t)?Number(t):t;return"number"==typeof e&&Number.isSafeInteger(e)&&e>0?{pid:e}:void 0}const r="string"==typeof t?t.trim():"";if(0!==r.length)return"bundleId"===e?{bundleId:r}:"path"===e?{path:r}:{appName:r}}(o[0].selector,o[0].value)}else{if(void 0===r.appArg)return r.capturesScreen?{kind:"screen"}:{kind:"none"};{const t=e.args[r.appArg];if(null==t||function(e){return"object"==typeof e&&null!==e&&"screen"===e.scope}(t))return{kind:"screen"};n=function(e){if("string"==typeof e){const t=e.trim();return t.length>0?{name:t}:void 0}if("object"!=typeof e||null===e)return;const{scope:t,pid:r}=e;return"app"===t&&"number"==typeof r&&Number.isInteger(r)&&r>0?{pid:r}:void 0}(t)}}if(void 0===n)return{kind:"unknownApp"};const o=function(e){return"pid"in e?void 0:"name"in e?e.name:"bundleId"in e?e.bundleId:"path"in e?e.path:e.appName}(n),s=await t.describeApp(n)??(void 0===o?void 0:Yb(o));return void 0===s?{kind:"unknownApp"}:{kind:"app",app:s}}({toolName:e.toolName,args:Object.fromEntries(Object.entries(e.args).map((([e,t])=>[e,t.toJson()]))),meta:t?._meta},r);if(void 0===n&&"app"!==o.kind)return{kind:"askEachCall"};switch(o.kind){case"none":return{kind:"noAccess"};case"screen":return{kind:"notComputerUse"};case"unknownApp":return{kind:"askEachCall"};case"noAppSelector":return{kind:"block",message:o.message};case"app":{const e=function(e){const t=e.toLowerCase();return Zb(t)?"Computer Use doesn't control Cursor itself, including its approval cards. Ask the user to do it instead.":Xb.some((e=>e.bundleId===t))?"Computer Use doesn't control apps that run scripts, such as Script Editor, Automator and Shortcuts. Ask the user to do it instead.":Qb.some((e=>e.bundleId===t))?"Computer Use doesn't control terminal apps. Use your shell tool to run commands instead.":void 0}(o.app.bundleId);if(void 0!==e)return{kind:"block",message:e};if(void 0===n)return{kind:"askEachCall"};const t=tS(o.app.bundleId)?void 0:Qk({server:r.serverId,tool:rS(o.app.bundleId)});return void 0===t?{kind:"askEachCall",app:o.app}:{kind:"app",app:o.app,entry:t}}}throw new Error("unreachable computer-use subject")}isComputerUseServer(e){const t=Xk(e);return!0===this.computerUse?.providerIdentifiers.has(t)}async isComputerUseDisabledByAdminFor(e){const t=this.computerUseAdminPolicy;return t?.providerIdentifiers.has(Xk(e))?await t.isDisabledByAdmin():!!this.isComputerUseServer(e)&&!0===await(this.teamSettingsService.isComputerUseDisabledByAdmin?.())}allowComputerUseAppForSession({bundleId:e}){const t=void 0===this.computerUse||tS(e)?void 0:Qk({server:this.computerUse.serverId,tool:rS(e)});void 0!==t&&this.computerUseAppsAllowedForSession.push(t)}async isMcpFullyAllowlisted(e,t){const r=e.withName("InteractivePermissionsService.isMcpFullyAllowlisted"),{providerIdentifier:n,toolName:o}=t,s=t.annotations??Mb(t.annotationsJson);if(await this.isMcpExplicitlyDenied(r,n,o)||await this.isComputerUseDisabledByAdminFor(n))return!1;const i=await this.teamSettingsService.getMcpToolControls();return!0===i?.enabled?!!this.isMcpInTeamAllowlist(i,{providerIdentifier:n,toolName:o,annotations:s}):!this.isComputerUseServer(n)&&await this.isMcpExplicitlyAllowed(r,n,o)}async isWebFetchFullyAllowlisted(e,t){const r=await this.getPermissions();if("allowlist"!==r.approvalMode)return!1;let n;try{n=new URL(t.url)}catch{return!1}const o=n.hostname;return!r.deny.some((e=>this.matchesWebFetchEntry(e,o)))&&r.allow.some((e=>this.matchesWebFetchEntry(e,o)))}matchesAutoRunCommand(e,t){const r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^${r}(\\s|$)`).test(e.trim())}matchesMcpPattern({pattern:e,providerIdentifier:t,toolName:r,logLabel:n}){const o=e.indexOf(":");if(-1===o)return!1;const s=e.slice(0,o).trim().toLowerCase(),i=e.slice(o+1).trim().toLowerCase(),a=Xk(t).toLowerCase().trim(),c=r.toLowerCase().trim(),l="*"===s||this.matchGlob(s,a),u="*"===i||this.matchGlob(i,c),d=l&&u,h=`[permissions-service] ${n}: serverPattern="${s}", toolPattern="${i}", normalizedProviderIdentifier="${a}", normalizedToolName="${c}", serverMatches=${l}, toolMatches=${u}, result=${d}`;return this.mcpAllowlistLog?.(h),d}recordMcpAllowlistCheckResult(e,{allowlistScope:t,outcome:r}){tk.increment(e,1,{allowlist_scope:t,outcome:r})}matchesMcpEntry(e,t,r){const n=e.match(/^\s*Mcp\s*\((.*)\)\s*$/);if(!n)return!1;const o=n[1]?.trim()??"";return this.matchesMcpPattern({pattern:o,providerIdentifier:t,toolName:r,logLabel:"matchesMcpEntry"})}matchesWebFetchEntry(e,t){const r=e.match(/^\s*WebFetch\s*\((.*)\)\s*$/);return!!r&&Kv(t,r[1]?.trim()??"")}matchesMcpEntryBare({pattern:e,providerIdentifier:t,toolName:r}){return this.matchesMcpPattern({pattern:e,providerIdentifier:t,toolName:r,logLabel:"matchesMcpEntryBare"})}isMcpInTeamAllowlist(e,{providerIdentifier:t,toolName:r,annotations:n}){if(e.mcpToolAllowlist.some((e=>this.matchesMcpEntryBare({pattern:e,providerIdentifier:t,toolName:r}))))return!0;const o=this.findTeamMcpServerPolicy(e,t);return void 0!==o&&"reads"===o.mode&&jb(o,{name:r,annotations:n})}findTeamMcpServerPolicy(e,t){for(const r of e.serverPolicies??[])if(this.matchesMcpEntryBare({pattern:`${r.name}:*`,providerIdentifier:t,toolName:""}))return r.policy}async isMcpExplicitlyDenied(e,t,r){return(await this.getPermissions()).deny.some((e=>this.matchesMcpEntry(e,t,r)))}async isComputerUseAppSaved(e){return(await this.getPermissions()).allow.some((t=>t.match(/^\s*Mcp\s*\((.*)\)\s*$/)?.[1]?.trim().toLowerCase()===e))}async isMcpExplicitlyAllowed(e,t,r){return(await this.getPermissions()).allow.some((e=>this.matchesMcpEntry(e,t,r)))}}var r_=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const n_=65536,o_=1048576,s_=(0,l.h)("LocalReadExecutor"),i_=async(e,t,r,n)=>{const o=setTimeout((()=>{s_.warn(e,`[watchdog, LocalReadExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function a_(e){return BigInt(Math.min(e,4294967295))}async function c_(e,t){if(0===t)return(0,Co.readFile)(e);if(t>2147483647)throw new RangeError(`File size (${t}) is greater than 2 GiB`);const r=await(0,Co.open)(e,"r");try{const e=Buffer.allocUnsafe(t);let n=0;for(;n=32&&e<=126||9===e||10===e||13===e}function d_(e){if(e.length>=2){if(255===e[0]&&254===e[1])return"utf-16le";if(254===e[0]&&255===e[1])return"utf-16be"}const t=Math.min(4096,e.length);if(t<16)return"utf-8";let r=0,n=0;for(let o=0;o+1=8&&r>=4*Math.max(1,n)?"utf-16le":n>=8&&n>=4*Math.max(1,r)?"utf-16be":"utf-8"}const h_=Buffer.from("\n---\n");function p_(e,t){const r=e.length;if(r<2*h_.length)return r;if(10!==e[r-1]||45!==e[r-2]||45!==e[r-3]||45!==e[r-4]||10!==e[r-5])return r;const n=Math.max(t,r-4096),o=e.lastIndexOf(h_,r-h_.length-1);return-1===o||o126))return!1}const t=e.split("\n").filter((e=>e.length>0));if(t.length<2||t.length>3)return!1;const r=t[0],n=t[t.length-1];return!(!/^(exit_code: (?:-?\d+|unknown)|error: .+)$/.test(r)||!n.startsWith("ended_at: ")||3===t.length&&!/^elapsed_ms: \d+$/.test(t[1]))}(e.subarray(o+h_.length,r-4).toString("utf-8"))?o:r}const f_=[Buffer.from("%PDF-","ascii"),Buffer.from([208,207,17,224,161,177,26,225]),Buffer.from([80,75,3,4]),Buffer.from([80,75,5,6]),Buffer.from([80,75,7,8]),Buffer.from([127,69,76,70]),Buffer.from([254,237,250,206]),Buffer.from([254,237,250,207]),Buffer.from([206,250,237,254]),Buffer.from([207,250,237,254]),Buffer.from([77,90,144]),Buffer.from([0,97,115,109]),Buffer.from([137,80,78,71,13,10,26,10]),Buffer.from([255,216,255]),Buffer.from("GIF87a","ascii"),Buffer.from("GIF89a","ascii"),Buffer.from("SQLite format 3\0","ascii"),Buffer.from([31,139]),Buffer.from("BZh","ascii"),Buffer.from([253,55,122,88,90,0]),Buffer.from([40,181,47,253]),Buffer.from([55,122,188,175,39,28]),Buffer.from([82,97,114,33,26,7,0]),Buffer.from([82,97,114,33,26,7,1,0])];function m_(e){return new Ky.sV({result:{case:"invalidFile",value:new Ky.cW({path:e,reason:"File content is binary data, not text"})}})}function g_(e,t,r){if(void 0===r.offset&&void 0===r.limit)return{applied:!1};if(t)return{applied:!1};const n=r.offset??1,o=r.limit??(n<0?Math.abs(n):e),s=n<0?Math.max(0,e+n):Math.max(0,n-1);if(s>=e)return{applied:!1};const i=Math.min(e,s+o),a=w_(s,e),c=w_(i,e);return{applied:!0,start:a,end:Math.max(a,c)}}function w_(e,t){if(Number.isNaN(e)||0===e)return 0;if(e===Number.POSITIVE_INFINITY)return t;if(e===Number.NEGATIVE_INFINITY)return 0;const r=Math.trunc(e);return r<0?Math.max(t+r,0):Math.min(r,t)}function y_(e){return-1===e.indexOf("\r\n")?e:e.replaceAll("\r\n","\n")}function v_(e,t,r,n,o,s){if(n>=o)return{from:0,to:0};let i=0,a=0,c=0===n,l=0;for(;ia&&13===r(t)?t-1:t};l=t+1}return c?{from:a,to:t}:{from:t,to:t}}function b_(e,t,r){const n=v_((t=>e.indexOf("\n",t)),e.length,(t=>e.charCodeAt(t-1)),t,r,!1);return 0===n.from&&n.to===e.length?e:n.from>=n.to?"":e.slice(n.from,n.to)}function S_(e,t,r,n,o){if(t>=r)return{text:"",truncated:!1};const s=n>=0?n+3:-1;let i=t;if(n>=0&&i>=n&&i=r)return{text:"",truncated:!1};const a=function(e,t,r,n){if(r>=n)return n;if(r<=t)return t;const o=Math.max(t,r-3);let s=r;for(;s>o;){if(128!=(192&(e[s]??0)))return s;s--}return 192&~(e[s]??0)?r:s}(e,i,Math.min(r,i+3*(o+1)+3),r);let c=y_(function(e,t,r,n){if(t>=r)return"";if(n<0)return e.toString("utf8",t,r);const o=n+3;return r<=n||t>=o?e.toString("utf8",t,r):t>=n&&r<=o?"":(to?e.toString("utf8",Math.max(t,o),r):"")}(e,i,a,n));const l=c.length>o||ao&&(c=Vo(c,o)),{text:c,truncated:l}}function k_(e,t,r,n){if(t>=r)return{text:"",truncated:!1};const o=Math.min(r,t+2*n+1);let s=y_(e.slice(t,o));const i=s.length>n||on&&(s=Vo(s,n)),s.lengthn?{text:e.text+Vo(t,n),truncated:!0}:{text:e.text+t,truncated:e.truncated}}function C_(e,t){if(e.truncated)return e;const r=__(e,t);return{text:r.text,truncated:r.truncated}}function E_(e,t,r){let n=e;return t.forEach(((e,t)=>{const o=function(e,t){const{line:r,hasNewline:n}=e;return t&&n&&r.text.endsWith("\r")?{...r,text:r.text.slice(0,-1)}:r}(e,r);t>0&&(n=__(n,"\n")),n=__(n,o.text),o.truncated&&(n={text:n.text,truncated:!0})})),n}function x_(e){const t=e.toLowerCase();return"utf-8"===t?"utf8":"utf-8-bom"===t||"utf-8 bom"===t?"utf8bom":"latin-1"===t?"latin1":t}function P_(e){return void 0===e.maxChars||void 0!==e.offset||void 0!==e.limit?Gs:Math.min(Gs,e.maxChars+2)}function R_(e,t,r){if(!t||void 0===r.maxChars||e.length-1<=r.maxChars)return e;const n=e.charCodeAt(e.length-1);return n>=55296&&n<=56319?e.slice(0,-1):e}class I_ extends Error{constructor(){super("Invalid UTF-8 while streaming read"),this.name="InvalidUtf8Error"}}function T_(e){for(let t=1;t<=Math.min(3,e.length);t++){const r=e[e.length-t]??0;if(128!=(192&r))return A_(r)>t?t:0}return 0}function A_(e){return e>=240?4:e>=224?3:e>=192?2:1}class $_{constructor(e,t,r){this.previousEndsWithCr=e,this.carry=t,this.strict=r,this.lines=0,this.crlfCount=0,this.lfOnlyCount=0,this.continuesLine=t.length>0}count(e){this.strict&&this.validate(e),0===this.lines&&e.length>0&&10!==e[0]&&(this.continuesLine=!0);for(let t=e.indexOf(10);-1!==t;t=e.indexOf(10,t+1))(t>0?13===e[t-1]:this.previousEndsWithCr)?this.crlfCount++:this.lfOnlyCount++,this.lines++;e.length>0&&(this.previousEndsWithCr=13===e[e.length-1])}finish(){if(this.strict&&this.carry.length>0)throw new I_}validate(e){let t=e;if(this.carry.length>0){const r=A_(this.carry[0]??0)-this.carry.length;if(e.length0&&(0,n.isUtf8)(e.subarray(0,e.length-t))?"utf8_cut":"utf8_invalid"}(e)}async function O_(e,t){const r=t>0?Math.min(t,o_):o_,o=await c_(e,r);return o.length===t&&(0,n.isUtf8)(o)||ci(new zs.TextDecoder("utf-8",{fatal:!1}).decode(o,{stream:o.length===o_&&o.length!==t}))?{kind:"lossyUtf8",cacheEncoding:"utf8"}:{kind:"iconv",decoderEncoding:"latin1",cacheEncoding:"latin1"}}async function F_(e){const t=await(0,Co.stat)(e),r=await Hi(e);if(r.isBinaryFile)return;const n=M_({file:e,stats:t,format:r},void 0);if("iconv"===n.kind)return n.decoderEncoding;const o=await O_(e,t.size);return"iconv"===o.kind?o.decoderEncoding:void 0}async function N_(e,{file:t,stats:r},n,o,s){const i=r.size,a=void 0!==n.offset||void 0!==n.limit,c=(n.offset??1)<0,l=n.offset??1,u=Math.max(0,l-1),d=void 0===n.limit?void 0:u+n.limit,h=c?Math.abs(l):0,p=a?1/0:n.maxChars??1/0,f=a&&!c?n.maxChars??1/0:1/0;let m=[],g=0,w=!1,y=0,v=!1,b=!(c||a&&u<=0),S=!1;const k=[];let _,C=0,E=!1,x=0,P=!1,R=[],I=0,T=0,A=0,$=!1,M={text:"",truncated:!1},D=!1,O=!1,F=0,N=0,L=0,j=!1,U=!1;const B=e=>{let t=e;return!j&&t.length>0&&(j=!0,65279===t.charCodeAt(0)&&(U=!0,t=t.slice(1))),t},W=(e,t)=>t&&13===e.text.charCodeAt(e.text.length-1),H=()=>P||E&&C>=Gs,q=()=>v||w&&g>=Gs,z=(e,t)=>{if(H())return;const r=k.length>0?1:0;let n=Gs-C;if(r>0){if(n<=0)return void(E=!0);n--}const o=e.text.length>n?{line:{text:Vo(e.text,n),truncated:!0},hasNewline:t}:{line:e,hasNewline:t};k.push(o),C+=r+(o.line.truncated?n:o.line.text.length),e.truncated&&(E=!0),o.line.truncated&&(E=!0),W(o.line,t)&&x++,C-x>f&&(P=!0,_=F)},G=(e,t)=>{if(q())return;const r=m.length>0?1:0;let n=Gs-g;if(r>0){if(n<=0)return void(w=!0);n--}const o=e.text.length>n?{line:{text:Vo(e.text,n),truncated:!0},hasNewline:t}:{line:e,hasNewline:t};m.push(o),g+=r+(o.line.truncated?n:o.line.text.length),(e.truncated||o.line.truncated)&&(w=!0),W(o.line,t)&&y++,g-y>p&&(v=!0,_=F)},V=(e,t)=>{e&&(t?N++:L++),F++},K=()=>{const e=R[I];void 0!==e&&(A-=e.line.text.length+1),R[I]=void 0,I=(I+1)%R.length,T--},J=(e,t,r)=>{const n=F;if(0===n&&(S=0===e.text.length),!c&&a&&b&&n>=u&&(b=!1,m=[]),b&&G(e,t),c){if(h>0)for(T===h&&K(),(e=>{if(T===R.length){const e=new Array(Math.min(h,Math.max(16,2*R.length)));for(let t=0;t1&&A>Gs;)K(),$=!0}else a&&n>=u&&(void 0===d||n!(D||(!b||q())&&(!a||0!==F)&&!(c?h>0:!(!a||H())&&F>=u&&F<(d??1/0))),X=()=>{const e=M.text.length-1;if(a){const t=!c&&F>=u&&F<(d??1/0),r=k.length>0?1:0;if(!t||C-x+r+e<=f)return;z(M,!1)}else{const t=m.length>0?1:0;if(g-y+t+e<=p)return;G(M,!1)}M={text:"",truncated:!1},D=!0};let Q;const Y=e=>{if(void 0===n.maxChars||c)return;if(!(a?H()||F>=(d??1/0):q()))return;const t=e.subarray(e.length-T_(e));return Q=new $_(ee,Buffer.from(t),"strictUtf8"===o.kind),Q};let ee=!1;for await(const r of async function*(e,t,r,n,o){const s=function(e){return e>0?{start:0,end:e-1}:{}}(n);if("strictUtf8"===r.kind||"lossyUtf8"===r.kind){const n=new zs.TextDecoder("utf-8",{fatal:"strictUtf8"===r.kind,ignoreBOM:!0}),i=(0,xo.createReadStream)(t,{highWaterMark:n_,signal:e.signal,...s});let a;try{for await(const e of i){if(void 0!==a){a.count(e);continue}const t=n.decode(e,{stream:!0});t.length>0&&(yield t),e.length>=4&&(a=o?.(e))}if(void 0!==a)return void a.finish();const e=n.decode();e.length>0&&(yield e)}catch(e){if(e instanceof TypeError)throw new I_;throw e}return}const i=(0,xo.createReadStream)(t,{highWaterMark:n_,signal:e.signal,...s}).pipe(Vs.decodeStream(r.decoderEncoding));for await(const e of i)yield"string"==typeof e?e:String(e)}(e,t,o,i,Y)){const e=B(r);let t=0,n=e.indexOf("\n",t);for(;-1!==n;){const r=n>t?13===e.charCodeAt(n-1):ee;Z()?(M=C_(M,e.slice(t,n)),J(M,!0,r)):(D&&n>t&&(O=!0),V(!0,r)),M={text:"",truncated:!1},D=!1,ee=!1,t=n+1,n=e.indexOf("\n",t)}t0&&N/te*100>=5,ne="utf8"===o.cacheEncoding&&U?"utf8bom":o.cacheEncoding;s&&Yi(t,r,ne);const oe=Math.min(F,a?d??1/0:1/0),se=void 0!==_&&(O||oe>_+1),ie=(n.maxChars??1/0)+n_,ae=e=>e.text.length>ie?{text:Vo(e.text,ie),truncated:!0}:e,ce=()=>E_({text:"",truncated:w||se},m,re);if(!a){const e=ae(ce());return{content:e.text,totalLines:F,truncated:e.truncated,rangeApplied:!1}}if(F<=1&&S)return{content:"",totalLines:F,truncated:!1,rangeApplied:!1};if(c){const e=n.limit??h,t=[];for(let e=0;e=F){const e=ce();return{content:e.text,totalLines:F,truncated:e.truncated,rangeApplied:!1}}const le=ae(E_({text:"",truncated:E||se},k,re));return{content:le.text,totalLines:F,truncated:le.truncated,rangeApplied:!0}}class L_{constructor(e,t,r){this.permissionsService=e,this.workspacePath=t,this.terminalReads=new Zl,this.mcpStateAccessor=r?.mcpStateAccessor,this.useStreamingRead=r?.useStreamingRead,this.pendingDecisionProvider=r?.pendingDecisionProvider,this.encodingSlices=r?.encodingSlices}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,$.VI)(e.withName("LocalReadExecutor.execute")),!1);const o=t.path;if(""===o.trim())return new Ky.sV({result:{case:"error",value:new Ky.F_({path:o,error:es})}});const i=(0,Yo.o1)(o,this.workspacePath),a=await i_(e,"permissionsService.shouldBlockFileRead",3e3,(()=>Zk(this.permissionsService,i)));if(a){const r=await i_(e,"resolveFileReadBlock",3e3,(()=>async function(e,t){return await Qu(e,{onNeedsApproval:async(e,r)=>{const n=t.pendingDecisionProvider?.requestReadApproval?.bind(t.pendingDecisionProvider);if("fileRead"!==r.type||!n)return{kind:"denied",message:"Blocked by permissions configuration"};const o=await n({type:Lw.Read,details:{path:r.path,reason:e},toolCallId:t.toolCallId});return o.approved?null:{kind:"rejected",reason:o.reason}},onUserRejected:e=>({kind:"rejected",reason:e}),onPermissionDenied:e=>({kind:"denied",message:e})})??{kind:"proceed"}}(a,{pendingDecisionProvider:this.pendingDecisionProvider,toolCallId:t.toolCallId})));if("rejected"===r.kind)return new Ky.sV({result:{case:"rejected",value:new Ky.f4({path:i,reason:r.reason??""})}});if("denied"===r.kind)return new Ky.sV({result:{case:"permissionDenied",value:new Ky.lW({path:i})}})}void 0!==this.mcpStateAccessor&&qy(e,this.mcpStateAccessor,i);try{const r=await i_(e,"stat",3e3,(()=>(0,Co.stat)(i)));if(r.isDirectory())return new Ky.sV({result:{case:"invalidFile",value:new Ky.cW({path:i,reason:"Path is a directory, not a file"})}});if(!r.isFile())return new Ky.sV({result:{case:"invalidFile",value:new Ky.cW({path:i,reason:"Path is neither a file nor a directory"})}});const o=function(e){return null!==function(e){const t=nh(e,"terminals");if(!t||1!==t.remainingPath.length)return null;const r=t.remainingPath[0],n=/^(\d+)\.txt$/.exec(r);if(!n)return null;const o=Number.parseInt(n[1],10);return Number.isNaN(o)?null:{id:o}}(e)}(i),a=function(e){const t=nh(e,"agent-tools");return null!==t&&1===t.remainingPath.length&&t.remainingPath[0].endsWith(".txt")}(i);if(o||a)return await this.readTerminalFile(e,i,r,t,a&&!o);const c=await i_(e,"getFormatForFile",3e3,(()=>Hi(i))),l=c.isImageFile,u=function(e){return".pdf"===(0,s.extname)(e).toLowerCase()}(i),d=Ni(i);if(l){const t=await i_(e,"prepareImageForModel",3e3,(async()=>(async e=>{let t;try{t=await Lv(e)}catch(t){const r=await jv(e);if("undecodable"===r.kind)return r;throw t}if(!0===t.reencoded)return{kind:"image",image:t};const r=await jv(t.data);return"undecodable"===r.kind?r:{kind:"image",image:t}})(await(0,Co.readFile)(i))));return"undecodable"===t.kind?new Ky.sV({result:{case:"invalidFile",value:new Ky.cW({path:i,reason:(n=t.reason,`File is not a valid image: its data could not be decoded (${n}). A truncated or hand-copied file does this; write it again from the original bytes with code.`)})}}):new Ky.sV({result:{case:"success",value:new Ky.mE({path:i,output:{case:"data",value:t.image.data},totalLines:0,fileSize:a_(r.size),truncated:!1})}})}if(u){const t=await i_(e,"readPdfBinary",3e3,(()=>(0,Co.readFile)(i)));return new Ky.sV({result:{case:"success",value:new Ky.mE({path:i,output:{case:"data",value:t},totalLines:0,fileSize:a_(r.size),truncated:!1})}})}if(c.isBinaryFile&&d){if(void 0!==t.maxVideoBytes&&r.size>t.maxVideoBytes)return new Ky.sV({result:{case:"success",value:new Ky.mE({path:i,totalLines:0,fileSize:a_(r.size),truncated:!0})}});const n=await i_(e,"readBinaryFile",3e3,(()=>(0,Co.readFile)(i)));return new Ky.sV({result:{case:"success",value:new Ky.mE({path:i,output:{case:"data",value:n},totalLines:0,fileSize:a_(r.size),truncated:!1})}})}if(c.isBinaryFile)return m_(i);{const n=this.useStreamingRead,o=!n||await i_(e,"useStreamingRead",3e3,(()=>n()));if(o||r.size>Gs){const n=await i_(e,"readTextStreaming",7e3,(()=>async function(e,t,r,n){const o=M_(t,r.encodingHint);try{return{...await N_(e,t,r,o,n),decoder:o.kind}}catch(o){if(o instanceof I_){const o=await O_(t.file,t.stats.size);return{...await N_(e,t,r,o,n),decoder:o.kind}}throw o}}(e,{file:i,stats:r,format:c},t,o))),s=R_(n.content,n.truncated,t);return Ul(this.encodingSlices,e)&&this.recordStreamedRead(e,i,r.size,n,s),new Ky.sV({result:{case:"success",value:new Ky.mE({path:i,output:{case:"content",value:s},totalLines:n.totalLines,fileSize:a_(r.size),truncated:n.truncated,rangeApplied:n.rangeApplied})}})}const s=await i_(e,"readText",3e3,(()=>ji(i,t.encodingHint))),a=await i_(e,"countLines",3e3,(()=>Js(s))),l=function(e,t,r){const n=g_(t,""===e,r);return n.applied?n.start>=n.end?{content:"",rangeApplied:!0}:{content:b_(e,n.start,n.end),rangeApplied:!0}:{content:e,rangeApplied:!1}}(s,a,t);let u=l.content,d=!1;const h=P_(t);return u.length>h&&(u=R_(u.substring(0,h),!0,t),d=!0),u.length16777216)return"other_encoding";try{return r=await c_(e,t),!(0,n.isAscii)(r)&&(0,n.isUtf8)(r)?"utf8_as_other":"other_encoding"}catch{return"other_encoding"}var r}(t,r)),eu(this.encodingSlices,e,{layer:"exec_read",evidence:a,partial:o.rangeApplied||o.truncated},i)}catch{}}async readTerminalFile(e,t,r,n,o){const s=await i_(e,"readTerminalFile",3e3,(()=>c_(t,r.size)));if(o&&(i=s,f_.some((e=>function(e,t){return e.length>=t.length&&e.subarray(0,t.length).equals(t)}(i,e)))))return m_(t);var i;const a=function(e,t,r=8388608){if(0===e.length)return{content:"",totalLines:1,rangeApplied:!1,truncated:!1};const n=l_(e),o=p_(e,n);if("utf-8"!==d_(e.subarray(n,o)))return function(e,t,r){const n=0===e.length,o=function(e){let t=0,r=0;const n=e.length;for(;r=s.end)return{content:"",totalLines:o,rangeApplied:!0,truncated:!1};const i=v_((t=>e.indexOf("\n",t)),e.length,(t=>e.charCodeAt(t-1)),s.start,s.end,!0),a=k_(e,i.from,i.to,r);return{content:a.text,totalLines:o,rangeApplied:!0,truncated:a.truncated}}(function(e){const t=l_(e),r=t>0?e.subarray(0,t).toString("utf-8"):"",n=p_(e,t),o=nr?-1:239===e[t]&&187===e[t+1]&&191===e[t+2]?t:-1}(e,n,o);return function(e,t,r,n){const o=e.length-(t>=0?3:0)==0,s=function(e){let t=0,r=0;const n=e.length;for(;r=i.end)return{content:"",totalLines:s,rangeApplied:!0,truncated:!1};const a=v_((t=>e.indexOf(10,t)),e.length,(t=>e[t-1]??0),i.start,i.end,!0),c=S_(e,a.from,a.to,t,n);return{content:c.text,totalLines:s,rangeApplied:!0,truncated:c.truncated}}(e,s,t,r)}(s,n,P_(n)),c=R_(a.content,a.truncated,n);return Ul(this.encodingSlices,e)&&(o||this.terminalReads.firstRead(n.toolCallId,t))&&Yl(this.encodingSlices,e,{layer:o?"exec_read":"exec_terminal_context",evidence:D_(s),partial:a.rangeApplied||a.truncated},c),new Ky.sV({result:{case:"success",value:new Ky.mE({path:t,output:{case:"content",value:c},totalLines:a.totalLines,fileSize:a_(r.size),truncated:a.truncated,rangeApplied:a.rangeApplied})}})}}function j_(e){return Buffer.from(e,"utf16le").toString("utf16le")}var U_=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},B_=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function W_(e){return`Path '${e}' could not be verified while resolving symlinks. This can happen when access is denied or the path contains a symlink loop.`}function H_(e){return`Path '${e}' is neither a file nor a directory`}async function q_(e){const t=await(0,Co.stat)(e).catch((()=>{}));return void 0!==t&&!t.isFile()&&!t.isDirectory()}function z_(e,t,r){const n=function(e,t){let r;for(const n of t)(0,Yo.ZU)({basePath:n,targetPath:e})&&(void 0===r||n.length>r.length)&&(r=n);return r}((0,s.resolve)(e,t),r);return void 0===n||n===e}class G_ extends Error{}function V_(e){const t=new AbortController,r=setTimeout((()=>t.abort()),e);return{signal:t.signal,clear:()=>clearTimeout(r)}}function K_(e){switch(e.result.case){case"content":return e.result.value.matches.length>0;case"files":return e.result.value.files.length>0;case"count":return e.result.value.counts.length>0;case void 0:return!1;default:{const t=e.result;throw new Error(`Unknown grep result: ${String(t)}`)}}}function J_(e){switch(e){case"content":return new Ey.vD({result:{case:"content",value:new Ey.Zp({ripgrepTruncated:!0})}});case"files_with_matches":return new Ey.vD({result:{case:"files",value:new Ey.T7({ripgrepTruncated:!0})}});case"count":return new Ey.vD({result:{case:"count",value:new Ey.xA({ripgrepTruncated:!0})}});default:throw new Error(`Unknown output mode: ${String(e)}`)}}function Z_(e){return"success"===e.result.case&&Object.values(e.result.value.workspaceResults).some((e=>!0===e.result.value?.clientTruncated))}function X_(e,t,r){let n=Buffer.concat(e);t&&(n=n.subarray(0,n.lastIndexOf(10)+1)),r?.note(n);const o=n.toString("utf8");return o.includes("�")?{stdout:o,stdoutBytes:n}:{stdout:o}}function Q_(e){return/^(utf-?16|ucs-?2)/i.test(e)}const Y_=(0,l.h)("local-exec/grep"),eC=(0,u.Pu)("local_exec.grep.deadline_reached",{description:"Grep and Glob searches the search deadline stopped, by whether they kept what was found",labelNames:["output_mode","outcome","streaming"]}),tC=(0,u.Pu)("local_exec.grep.newest_first_stat_fallback",{description:"Grep and Glob results left in ripgrep's order because stat was too slow to sort them",labelNames:["output_mode"]}),rC=(0,u.v5)("local_exec.grep.rg.spawn_ms",{description:"Time to start the ripgrep process for one Grep or Glob search",labelNames:["sandboxed"]}),nC=(0,u.v5)("local_exec.grep.rg.search_ms",{description:"Time ripgrep took to search and exit after it started, for runs it finished",labelNames:["output_mode","sandboxed"]});function oC(e){return e instanceof Error&&e.message.includes("ENOENT")&&e.message.includes("spawn")}function sC(e){try{return(0,xo.existsSync)(e)}catch{return"check_failed"}}function iC(e){if("object"==typeof e&&null!==e&&"errno"in e){const t=e.errno;if("number"==typeof t)return t}}function aC(e,t){if("object"==typeof e&&null!==e)return"syscall"===t&&"syscall"in e&&"string"==typeof e.syscall?e.syscall:"path"===t&&"path"in e&&"string"==typeof e.path?e.path:void 0}function cC(e,t,r,n){return{...uC(e),...n,cwd:t,cwdExists:sC(t),errorMessage:kc(r),errorCode:Sc(r),errno:iC(r),syscall:aC(r,"syscall"),errorPath:aC(r,"path")}}function lC(e){return new Error(`Path does not exist: ${e}`)}function uC(e){const t={rgPath:e,platform:process.platform,arch:process.arch,pid:process.pid,uptimeSeconds:Math.round(process.uptime()),execPath:process.execPath};try{t.rgPathExists=(0,xo.existsSync)(e)}catch(e){t.rgPathExists=!1,t.rgPathExistsError=e instanceof Error?e.message:String(e)}try{const r=(0,xo.lstatSync)(e);t.rgIsSymlink=r.isSymbolicLink(),r.isSymbolicLink()&&!t.rgPathExists&&(t.rgBrokenSymlink=!0)}catch{t.rgLstatFailed=!0}const r=(0,s.dirname)(e);try{t.parentDirExists=(0,xo.existsSync)(r),t.parentDirExists&&(t.parentDirContents=(0,xo.readdirSync)(r).slice(0,50))}catch(e){t.parentDirError=e instanceof Error?e.message:String(e)}const n=(0,s.dirname)(r);try{t.grandparentDirExists=(0,xo.existsSync)(n),t.grandparentDirExists&&(t.grandparentDirContents=(0,xo.readdirSync)(n).slice(0,50))}catch(e){t.grandparentDirError=e instanceof Error?e.message:String(e)}if(t.rgPathExists)try{const r=(0,xo.statSync)(e);t.rgFileSize=r.size,t.rgFileMode=r.mode.toString(8),t.rgIsFile=r.isFile(),t.rgModifiedMs=r.mtimeMs}catch(e){t.rgStatError=e instanceof Error?e.message:String(e)}const o="node_modules.asar.unpacked";if(e.includes(o)){const r=e.split(o)[0];if(r){const n=r.concat("node_modules.asar");try{t.asarExists=(0,xo.existsSync)(n)}catch{t.asarExists="check_failed"}const i=r.concat(o);try{if(t.asarUnpackedDirExists=(0,xo.existsSync)(i),t.asarUnpackedDirExists){const r=(0,s.dirname)((0,s.dirname)(e));t.ripgrepPkgDirExists=(0,xo.existsSync)(r)}}catch{t.asarUnpackedDirExists="check_failed"}}}return t}class dC{constructor(e,t,r,n){this.ignoreService=e,this.grepProvider=t,this.workspacePath=r,this.stdoutDecodes=new WeakMap;const o=Array.isArray(this.workspacePath)?this.workspacePath[0]:this.workspacePath;this.singleWorkspacePath=Array.isArray(this.workspacePath)&&this.workspacePath.length>1?void 0:o,this.mcpStateAccessor=n?.mcpStateAccessor,this.permissionsService=n?.permissionsService,this.useStreamingGrep=n?.useStreamingGrep,this.encodingSlices=n?.encodingSlices}computeRelativeTarget(e,t){const r=(0,Yo.o1)(e,this.singleWorkspacePath??t);return r===t?".":(0,s.relative)(t,r)}isRootIndependentSearchPath(e){return(0,s.isAbsolute)(e)||/^~(?=$|[/\\])/.test(e)||e.startsWith("file://")}resolveSearchTargets(e,t){const r=this.isRootIndependentSearchPath(e);return t.map((t=>{const n=(0,s.resolve)(t);return{root:t,resolvedRoot:n,target:(0,Yo.o1)(e,r?void 0:n)}}))}findOutsideTargets(e,t){if(void 0===e||""===e)return;const r=this.resolveSearchTargets(e,t);return r.some((({resolvedRoot:e,target:t})=>(0,Yo.BJ)(t,e)))?void 0:[...new Set(r.map((({target:e})=>e)))]}searchTarget(e,t){if(!t.path)return".";const r=(0,Yo.o1)(t.path,this.singleWorkspacePath??e);return(0,Yo.BJ)(r,(0,s.resolve)(e))?this.computeRelativeTarget(t.path,e):r}sortsAfterRipgrep(e,t,r){return void 0===t.sort&&(r?!0!==t.sortAscending:(0,s.isAbsolute)(this.searchTarget(e,t)))}async buildArgs(e,t,r,n){const o=[],s=function(e,t){return"files_with_matches"===t&&""===e.pattern&&Boolean(e.glob)}(t,r),i=await pa(await this.ignoreService.listCursorIgnoreFilesByRoot(e));for(const e of i)o.push("--cursor-ignore",e);if("content"===r)o.push("--line-number","--with-filename","--no-heading","-0"),void 0!==t.contextBefore&&o.push("--before-context",String(t.contextBefore)),void 0!==t.contextAfter&&o.push("--after-context",String(t.contextAfter)),o.push("--max-columns",String(1e3),"--max-columns-preview"),void 0!==t.context&&void 0===t.contextBefore&&void 0===t.contextAfter&&o.push("--before-context",String(t.context),"--after-context",String(t.context));else if("files_with_matches"===r)o.push(s?"--files":"-l");else{if("count"!==r)throw new Error(`Unknown output mode: ${String(r)}`);o.push("-c","--with-filename")}!0===t.caseInsensitive?o.push("--ignore-case"):o.push("--case-sensitive"),t.type&&o.push("--type",t.type),t.glob&&(o.push("--iglob",t.glob),s&&o.push("--iglob","!**/.git")),t.multiline&&o.push("--multiline","--multiline-dotall");const a=n?"none":t.sort??"modified";if(n&&o.push("--line-buffered"),"none"!==a){const e=!0===t.sortAscending?"--sort":"--sortr";o.push(e,a)}o.push("--no-config","--color=never"),o.push("--hidden"),o.push("--follow");const c=this.searchTarget(e,t);if(t.path){const t=await async function(e){try{if(!(await(0,Co.stat)(e)).isFile())return;const{encoding:t}=await Hi(e);return Q_(t)?t.toLowerCase():void 0}catch{return}}((0,Yo.o1)(c,e));void 0!==t&&o.push("--encoding",t)}return s||o.push("--regexp",t.pattern),o.push("--"),o.push(c),o}async filterBlockedFiles(e,t){const r=new Map,n=await(this.permissionsService?.getFileReadBoundaryBlocker?.()),o=[];for(const s of e){const e=(0,Yo.o1)(s.file,t),i=await Cc(e);null===i||await this.isPostRipgrepBlocked(i,r)||void 0!==n&&await n(e,i)||o.push(s)}return o}async isPostRipgrepBlocked(e,t){const[r,n]=await Promise.all([this.ignoreService.isCursorIgnored(e,t),this.ignoreService.isRepoBlocked(e)]);return r||n}throwOnRipgrepFailure(e,t,r){if((""!==e.stderr||2===e.exitCode)&&""===e.stdout.trim()&&!function({stderr:e,target:t}){return e.trim().split(/\r?\n/).every((e=>{if(/^rg: .+: line \d+: /.test(e))return!0;const r=/^rg: (.+?): .*\(os error (?:13|5|2|1)\)$/.exec(e)?.[1]??/^rg: File system loop found: (.+) points to an ancestor /.exec(e)?.[1];return void 0!==r&&r!==t}))}({stderr:e.stderr,target:this.searchTarget(t,r)}))throw new Error(e.stderr||`ripgrep exited with code ${e.exitCode}`)}async orderNewestFirst(e,t,r,n,o){const s=await Vy(t,(e=>(0,Yo.o1)(n(e),r)));return s.statTimedOut&&(Y_.info(e,"newest_first.stat_timeout_fallback",{toolCallId:o.toolCallId,execId:o.execId,outputMode:o.outputMode,fileCount:t.length}),tC.increment(e,1,{output_mode:o.outputMode})),s.items}async keepNewestPage(e,t,r,n,o){return(await this.orderNewestFirst(e,t,r,n,o)).slice(0,dC.CLIENT_LIMIT_LINES)}async runFilesMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const d=U_(a,(0,$.VI)(e.withName("LocalGrepExecutor.runFilesMode")),!1),h=await this.buildArgs(t,r,"files_with_matches",n),p=await this.executeRg(d.ctx,t,h,void 0,o,s,i);this.throwOnRipgrepFailure(p,t,r);const f=(c=p.stdout,l=n?dC.HARD_MAX_OUTPUT_LINES:dC.CLIENT_LIMIT_LINES,u=dC.HARD_MAX_OUTPUT_LINES,function(e,t,r){const n=e.trim();if(""===n)return{files:[],totalFiles:0,clientTruncated:!1,ripgrepTruncated:!1};const o=new xy;let s=0,i=0,a=0;for(;Py(n,a,o);)a=o.nextStart,st?Buffer.from(n.slice(0,i)).toString():n,l=[];for(a=0;l.lengtht,ripgrepTruncated:s>=r}}(c,l,u)),m=f.totalFiles>dC.CLIENT_LIMIT_LINES;let g=f.files;n&&(g=await this.keepNewestPage(d.ctx,g,t,(e=>e),i),m&&(g=g.join("\0").split("\0")));const w=(await this.filterBlockedFiles(g.map((e=>({file:e}))),t)).map((({file:e})=>e)),y=g.length-w.length,v=new Ey.T7({files:w,totalFiles:Ay(f.totalFiles-y),clientTruncated:m,ripgrepTruncated:f.ripgrepTruncated||p.timedOut||p.stdoutByteCapped});return{result:new Ey.vD({result:{case:"files",value:v}}),timedOut:p.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{B_(a)}var c,l,u}async runCountMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const d=U_(a,(0,$.VI)(e.withName("LocalGrepExecutor.runCountMode")),!1),h=await this.buildArgs(t,r,"count",n),p=await this.executeRg(d.ctx,t,h,void 0,o,s,i);this.throwOnRipgrepFailure(p,t,r);const f=(c=p.stdout,l=n?dC.HARD_MAX_OUTPUT_LINES:dC.CLIENT_LIMIT_LINES,u=dC.HARD_MAX_OUTPUT_LINES,function(e,t,r){const n=e.trim();if(""===n)return{counts:[],totalFiles:0,totalMatches:0,clientTruncated:!1,ripgrepTruncated:!1};const o=[],s=new xy;let i=0;for(;Py(n,i,s);){const e=i,t=s.lineEnd;if(i=s.nextStart,t===e)continue;const r=n.lastIndexOf(":",t-1);if(rt,ripgrepTruncated:a>=r}}(c,l,u)),m=n?await this.keepNewestPage(d.ctx,f.counts,t,(e=>e.file),i):f.counts,g=await this.filterBlockedFiles(m,t),w=g.reduce(((e,t)=>e+t.count),0),y=m.length-g.length,v=m.reduce(((e,t)=>e+t.count),0)-w,b=new Ey.xA({counts:g.map((e=>new Ey.sS({file:e.file,count:Ay(e.count)}))),totalFiles:Ay(f.totalFiles-y),totalMatches:Ay(f.totalMatches-v),clientTruncated:f.totalFiles>dC.CLIENT_LIMIT_LINES,ripgrepTruncated:f.ripgrepTruncated||p.timedOut||p.stdoutByteCapped});return{result:new Ey.vD({result:{case:"count",value:b}}),timedOut:p.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{B_(a)}var c,l,u}async runContentMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const c=U_(a,(0,$.VI)(e.withName("LocalGrepExecutor.runContentMode")),!1),l=await this.buildArgs(t,r,"content",n),u=void 0!==r.context||void 0!==r.contextBefore||void 0!==r.contextAfter,d=dC.CLIENT_LIMIT_LINES*(u?2:1),h=await this.executeRg(c.ctx,t,l,d,o,s,i);this.throwOnRipgrepFailure(h,t,r);const p=await this.decodeLinesAsRead(c.ctx,h,t,i),{byFile:f,totalLines:m,totalMatchedLines:g,clientTruncated:w,ripgrepTruncated:y}=function(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{return U_(o,(0,$.VI)(n.withName("parseContentOutput")),!1),function(e,t,r){const n={byFile:new Map,totalLines:0,totalMatchedLines:0,totalFiles:0,clientTruncated:!1,ripgrepTruncated:!1};if(""===e.trim())return n;const o=new Map,s=new Set,i=new xy;let a=0,c=0,l=0,u=0;for(;Py(e,u,i);){const r=u,n=i.lineEnd;if(u=i.nextStart,l++,d=e,n-(h=r)==2&&45===d.charCodeAt(h)&&45===d.charCodeAt(h+1))continue;let p=-1;for(let t=r;t=n)continue;let m=0,g=0;for(;f57)break;m=10*m+(t-48),g++,f++}if(0===g||f>=n||!Number.isFinite(m))continue;const w=e.charCodeAt(f);if(58!==w&&45!==w)continue;const y=45===w;y||a++;const v=e.slice(r,p);if(s.has(v)||s.add(v),c>=t)continue;const b=e.slice(f+1,n);let S=o.get(v);void 0===S&&(S={file:v,matches:[]},o.set(v,S)),S.matches.push({lineNumber:m,content:b,isContextLine:y}),c++}var d,h;return{byFile:o,totalLines:Ay(l),totalMatchedLines:Ay(a),totalFiles:Ay(s.size),clientTruncated:c>=t,ripgrepTruncated:l>=r}}(e,t,r)}catch(e){o.error=e,o.hasError=!0}finally{B_(o)}}(p,dC.CLIENT_LIMIT_LINES,d,c.ctx),v=Array.from(f.values()),b=await this.filterBlockedFiles(v,t),S=v.filter((e=>!b.includes(e))),k=S.reduce(((e,t)=>e+t.matches.length),0),_=S.reduce(((e,t)=>e+t.matches.filter((e=>!e.isContextLine)).length),0),C=n?await this.orderNewestFirst(c.ctx,b,t,(e=>e.file),i):b,E=new Ey.Zp({matches:C.map((e=>new Ey.uI({file:e.file,matches:e.matches.map((e=>new Ey.dx({lineNumber:e.lineNumber,content:e.content,isContextLine:e.isContextLine})))}))),totalLines:Ay(m-k),totalMatchedLines:Ay(g-_),clientTruncated:w,ripgrepTruncated:y||h.timedOut||h.stdoutByteCapped});return{result:new Ey.vD({result:{case:"content",value:E}}),timedOut:h.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{B_(a)}}async decodeLinesAsRead(e,t,r,o){const s={stack:[],error:void 0,hasError:!1};try{const i=t.stdoutBytes;if(void 0===i)return t.stdout;const a=U_(s,(0,$.VI)(e.withName("LocalGrepExecutor.decodeLinesAsRead")),!1),c=function(e,t){const r=[],o=new xy;let s=0,i=0,a=e.indexOf("�");for(;-1!==a&&Py(e,s,o);){const{lineEnd:c,nextStart:l}=o,u=t.indexOf(10,i),d=-1===u?t.length:u+1;let h=-1===u?t.length:u;if(h>i&&-1!==u&&13===t[h-1]&&h--,ae.file)))],u=new Map,d=performance.now()+dC.LINE_ENCODING_TIMEOUT_MS;let h=0;for(;h{let d=!1,h=!1;const p=()=>{h||(h=!0,a.span.end())};if(e.signal.aborted)return p(),void u(new Error("Grep was cancelled"));if(o.aborted)return p(),void u(dC.ripgrepTimeoutError());let f;const m="insecure_none"===s.type?"false":"true",g=performance.now();let w=g;try{const e=s;f=(0,Oo.spawnInSandbox)((0,Oo.Ko)(),r,{cwd:t},e),w=performance.now(),0}catch(r){if(p(),oC(r)){const n=(0,Oo.Ko)();if(Y_.error(e,"rg_diagnostics.spawn_throw",void 0,cC(n,t,r,i)),!1===sC(t))return u(lC(t))}return u(r)}const y=[],v=[];let b=0,S=0,k=0,_=!1,C=!1,E=!1;const x=()=>{if(!d)try{p(),E=!0;const e=X_(y,!0,this.stdoutDecodes.get(i));""===e.stdout?u(dC.ripgrepTimeoutError()):l({...e,stderr:"",exitCode:0,timedOut:!0,stdoutByteCapped:C}),f.kill()}catch{}};o.addEventListener("abort",x,{once:!0});const P=()=>{o.removeEventListener("abort",x),p(),u(new Error("Grep was cancelled"));try{f.kill()}catch{}};e.signal.addEventListener("abort",P,{once:!0}),f.stdout?.on("data",(e=>{if(!C&&!_)if(b+=e.length,b>c){C=!0;try{f.kill()}catch{}}else if(void 0!==n){let t=-1,r=0;for(let o=0;o=n)){t=o+1,_=!0;try{f.kill()}catch{}break}k+=r;const o=t>=0?e.subarray(0,t):e;y.push(o)}else y.push(e)})),f.stderr?.on("data",(e=>{S+=e.length,S<=c&&v.push(e)})),f.on("error",(r=>{if(o.removeEventListener("abort",x),e.signal.removeEventListener("abort",P),p(),oC(r)){const n=(0,Oo.Ko)();if(Y_.error(e,"rg_diagnostics.spawn_enoent",void 0,cC(n,t,r,i)),!1===sC(t))return void u(lC(t))}u(r)})),f.on("close",(t=>{const r=performance.now()-w;d=!0,o.removeEventListener("abort",x),e.signal.removeEventListener("abort",P);const n=X_(y,C,E?void 0:this.stdoutDecodes.get(i)),s=Buffer.concat(v).toString("utf8");p(),l({...n,stderr:s,exitCode:t??0,timedOut:!1,stdoutByteCapped:C}),rC.histogram(e,w-g,{sandboxed:m}),C||_||o.aborted||e.signal.aborted||0!==t&&1!==t||nC.histogram(e,r,{output_mode:i.outputMode,sandboxed:m})}))}))}async checkOutsideTarget(e,t){if(1!==t.length||void 0===t[0])return{error:`Path '${e}' points to a different folder from each workspace root; use an absolute path`};const r=await Cc(t[0]);return null===r?{error:W_(e)}:await this.ignoreService.isCursorIgnored(r)?{error:`Path '${e}' is filtered out by .cursorignore`}:await q_(t[0])?{error:H_(e)}:{resolvedTarget:r}}async execute(e,t,r){if(!Ul(this.encodingSlices,e))return this.search(e,t,r,void 0);const n=new tu,o=await this.search(e,t,r,n);return"success"===o.result.case&&Yl(this.encodingSlices,e,{layer:"exec_grep",evidence:n.evidence(),partial:Z_(o)},o),o}async search(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{const a=U_(o,(0,$.VI)(e.withName("LocalGrepExecutor.execute")),!1),c=Array.isArray(this.workspacePath)?this.workspacePath:[this.workspacePath??process.cwd()],l=t.outputMode??"content";if("content"!==(i=l)&&"files_with_matches"!==i&&"count"!==i)throw new Error(`Unknown output mode: ${l}`);const u=l,d={toolCallId:t.toolCallId,execId:r?.execId,outputMode:u,targetPath:t.path,workspacePaths:c};void 0!==n&&this.stdoutDecodes.set(d,n);const h=ls(t.sandboxPolicy),p=this.grepProvider.getWorktreeGuardInfo?.(c);if((0,Yo.fl)({targetPath:t.path,workspacePaths:c,mainWorktreePath:p?.mainWorktreePath}))return new Ey.Ud({result:{case:"error",value:new Ey.ts({error:Yo.PS})}});const f=this.findOutsideTargets(t.path,c);let m=t,g=c;try{if(t.path&&void 0!==f){const r=await this.checkOutsideTarget(t.path,f);if("error"in r)return new Ey.Ud({result:{case:"error",value:new Ey.ts({error:r.error})}});void 0!==this.mcpStateAccessor&&qy(e,this.mcpStateAccessor,r.resolvedTarget),g=c.slice(0,1),m=t.clone(),m.path=f[0]}else if(m.path){const t=[];let r=!1;for(const{root:n,resolvedRoot:o,target:s}of this.resolveSearchTargets(m.path,c)){if(!(0,Yo.BJ)(s,o))continue;const i=await Cc(s);if(null!==i)if(await this.ignoreService.isCursorIgnored(i))r=!0;else{if(await q_(s))return new Ey.Ud({result:{case:"error",value:new Ey.ts({error:H_(m.path)})}});t.push(n),void 0!==this.mcpStateAccessor&&qy(e,this.mcpStateAccessor,i)}}if(0===t.length){const e=r?`Path '${m.path}' is filtered out by .cursorignore`:W_(m.path);return new Ey.Ud({result:{case:"error",value:new Ey.ts({error:e})}})}g=t}let r={};const n=void 0===f?await this.executeIndexedGrepWithTimeout(a.ctx,g,m,d):void 0;if(void 0!==n){r=n;for(const[e,t]of Object.entries(r)){const r=t.result;switch(r.case){case"content":r.value.matches=await this.filterBlockedFiles(r.value.matches,e);break;case"files":r.value.files=(await this.filterBlockedFiles(r.value.files.map((e=>({file:e}))),e)).map((({file:e})=>e));break;case"count":r.value.counts=await this.filterBlockedFiles(r.value.counts,e)}}}else{const e=await this.streamingEnabled(a.ctx,d),t=e?V_(dC.MAIN_TIMEOUT_MS):void 0;let n=0,o=!1;try{for(const s of g){if(!0===t?.signal.aborted){r[s]=J_(u),n++,o=!0;continue}if(!1===sC(s))return new Ey.Ud({result:{case:"error",value:new Ey.ts({error:`Path does not exist: ${s}`})}});const i=t??V_(dC.MAIN_TIMEOUT_MS);try{const t=await this.runMode(a.ctx,u,s,m,e,i.signal,h,d);r[s]=t.result,t.timedOut&&n++}catch(t){if(!(t instanceof G_))throw t;if(r[s]=J_(u),n++,o=!0,!e)break}finally{i!==t&&i.clear()}}}finally{t?.clear()}if(n>0){const t=o&&(!e||!Object.values(r).some(K_));if(this.reportDeadlineReached(a.ctx,d,{streaming:e,folderCount:g.length,stoppedFolderCount:n,outcome:t?"failed":"partial"}),t)throw dC.ripgrepTimeoutError()}}const o=function(e,t){if(t.length<=1)return e;const r=[...new Set(t.map((e=>(0,s.resolve)(e))))],n={};for(const[t,o]of Object.entries(e)){const e=(0,s.resolve)(t),i=t=>z_(e,t,r),a=o.result;switch(a.case){case"content":{const e=a.value,r=[];let o=0,s=0;for(const t of e.matches)i(t.file)?r.push(t):(o+=t.matches.length,s+=t.matches.filter((e=>!e.isContextLine)).length);const c=e.clone();c.matches=r,c.totalLines=Math.max(0,e.totalLines-o),c.totalMatchedLines=Math.max(0,e.totalMatchedLines-s),n[t]=new Ey.vD({result:{case:"content",value:c}});break}case"files":{const e=a.value,r=e.files.filter((e=>i(e))),o=e.clone();o.files=r,o.totalFiles=Math.max(0,e.totalFiles-(e.files.length-r.length)),n[t]=new Ey.vD({result:{case:"files",value:o}});break}case"count":{const e=a.value,r=[];let o=0;for(const t of e.counts)i(t.file)?r.push(t):o+=t.count;const s=e.clone();s.counts=r,s.totalFiles=Math.max(0,e.totalFiles-(e.counts.length-r.length)),s.totalMatches=Math.max(0,e.totalMatches-o),n[t]=new Ey.vD({result:{case:"count",value:s}});break}default:n[t]=o}}return n}(r,g),i=new Ey._0({pattern:m.pattern,path:void 0!==m.path&&this.isRootIndependentSearchPath(m.path)?(0,Yo.o1)(m.path):m.path,outputMode:u,workspaceResults:o});return new Ey.Ud({result:{case:"success",value:i}})}catch(e){if(m.path){const e=(0,Yo.o1)(m.path,this.singleWorkspacePath);try{await(0,Co.stat)(e)}catch(t){return new Ey.Ud({result:{case:"error",value:new Ey.ts({error:`Path does not exist: ${e}`})}})}}return new Ey.Ud({result:{case:"error",value:new Ey.ts({error:e instanceof Error?e.message:String(e)})}})}}catch(e){o.error=e,o.hasError=!0}finally{B_(o)}var i}}dC.MAIN_TIMEOUT_MS=25e3,dC.INDEXED_GREP_TIMEOUT_MS=25e3,dC.INDEXED_GREP_CONTEXT_TIMEOUT_MS=dC.INDEXED_GREP_TIMEOUT_MS+100,dC.HARD_MAX_OUTPUT_LINES=1e4,dC.CLIENT_LIMIT_LINES=2e3,dC.LINE_ENCODING_TIMEOUT_MS=2e3,je.object({record_v:je.number().int().nullish(),pid:je.number().int().nonnegative().nullish(),version:je.string().nullish(),started_at:je.number().nullish(),control_sock:je.string().nullish(),runtime_dir:je.string().nullish(),data_dir:je.string().nullish(),config_path:je.string().nullish(),log_path:je.string().nullish(),metrics_addr:je.string().nullish(),exe:je.string().nullish()}),je.object({mountpoint:je.string().nullish(),capabilities:je.array(je.string()).nullish(),nfs_transport:je.string().nullish(),bind_ignored:je.object({active:je.array(je.string()).nullish()}).passthrough().nullish()});const hC=je.object({daemon_alive:je.boolean().nullish(),mounts:je.array(je.unknown()).nullish(),data_plane:je.object({enabled:je.boolean().nullish()}).passthrough().nullish()});je.object({daemon_alive:je.boolean().nullish(),daemon_version:je.string().nullish(),capabilities:je.array(je.string()).nullish()}),hC.extend({memory:je.object({anon_bytes:je.number()}).nullish().catch(null)});const pC=je.number().int().nonnegative(),fC=je.object({line_no:je.number().int().positive(),kind:je.enum(["match","before","after"]),text:je.string().optional(),bytes:je.string().regex(/^(?:[0-9a-fA-F]{2})*$/).optional(),truncated:je.boolean().default(!1)}).refine((e=>void 0!==e.text||void 0!==e.bytes));je.object({type:je.literal("file"),path:je.string(),lines:je.array(fC)}),je.object({type:je.literal("summary"),files_searched:pC,more:je.boolean(),stop_reason:je.string().nullable(),skipped:je.object({over_size:pC,size_unknown:pC,budget_exhausted:pC,fetch_failed:pC,unreadable:pC})}),je.object({type:je.string()}),(0,l.h)("local-exec/grove-grep"),(0,u.Pu)("local_exec.grep.grove",{description:"Grep searches Grove served, or declined to ripgrep, by decline reason",labelNames:["outcome","reason"]}),(0,u.v5)("local_exec.grep.grove.served_ms",{description:"Time Grove took to answer a Grep search it served"});var mC=r("../proto/dist/generated/agent/v1/ls_exec_pb.js"),gC=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},wC=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class yC{constructor(e,t,r){this.permissionsService=e,this.ignoreService=t,this.workspacePath=r}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{gC(r,(0,$.VI)(e.withName("LocalLsExecutor.execute")),!1).ctx;const n=(0,Yo.o1)(t.path,this.workspacePath);try{let r;try{r=await(0,Co.stat)(n)}catch(e){return"ENOENT"===Sc(e)?function(e){const t=nh(e,"terminals");return null!==t&&0===t.remainingPath.length}(n)?new mC.fv({result:{case:"error",value:new mC.uj({path:n,error:"No active terminals."})}}):new mC.fv({result:{case:"error",value:new mC.uj({path:n,error:`Path does not exist: ${n}`})}}):new mC.fv({result:{case:"error",value:new mC.uj({path:n,error:kc(e)})}})}if(!r.isDirectory())return new mC.fv({result:{case:"error",value:new mC.uj({path:n,error:`Path is not a directory: ${n}`})}});const o=ls(t.sandboxPolicy),s=t.timeoutMs??5e3,i=e.withTimeout(s),{tree:a,didTimeout:c}=await this.getDirectoryTree(i,n,t.ignore,o);return c?new mC.fv({result:{case:"timeout",value:new mC.ze({directoryTreeRoot:a})}}):new mC.fv({result:{case:"success",value:new mC.PC({directoryTreeRoot:a})}})}catch(e){return new mC.fv({result:{case:"error",value:new mC.uj({path:n,error:e instanceof Error?e.message:"Unknown error occurred"})}})}}catch(e){r.error=e,r.hasError=!0}finally{wC(r)}}async getDirectoryTree(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{return gC(o,(0,$.VI)(e.withName("LocalLsExecutor.getDirectoryTree")),!1),await this.buildTreeFromRipgrepStream(e,t,r,n,2500)}catch(e){o.error=e,o.hasError=!0}finally{wC(o)}}async buildTreeFromRipgrepStream(e,t,r,n,o){const i={stack:[],error:void 0,hasError:!1};try{gC(i,(0,$.VI)(e.withName("LocalLsExecutor.buildTreeFromRipgrepStream")),!1);const a=(0,s.resolve)(t),c=new mC.vq({absPath:a,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!0,fullSubtreeExtensionCounts:{}}),l=new Map;l.set(a,c);const u={charactersUsed:a.length,budgetExceeded:!1},[d,h]=await Promise.all([this.ignoreService.listCursorIgnoreFilesByRoot(t),this.ignoreService.getRepoBlockExcludeGlobs(t)]),p=[...r,...h],{lines:f,didTimeout:m}=ga(e,{root:t,excludeGlobs:p,caseSensitive:!0,cursorIgnoreFiles:d,sandboxPolicy:n,source:"ls"});for await(const e of f){if(!e)continue;const r=(0,s.resolve)(t,e),n=await Cc(r);null===n||await this.ignoreService.isCursorIgnored(n)||await this.ignoreService.isRepoBlocked(n)||this.addPathToTree(r,a,l,u,o)}return this.sortTreeChildren(c),{tree:c,didTimeout:await m}}catch(e){i.error=e,i.hasError=!0}finally{wC(i)}}addPathToTree(e,t,r,n,o){const i=(0,s.basename)(e),a=(0,s.dirname)(e);this.ensureDirectoryPath(a,t,r,n.budgetExceeded);const c=r.get(a);if(!c)return;const l=i.length;if(!n.budgetExceeded&&n.charactersUsed+l<=o){const e=new mC.ur({name:i});c.childrenFiles.push(e),n.charactersUsed+=l}else{if(!n.budgetExceeded){n.budgetExceeded=!0;let e=a;for(;e.startsWith(t);){const t=r.get(e);t&&(t.childrenWereProcessed=!1);const n=(0,s.dirname)(e);if(n===e)break;e=n}}let o=n.overflowChain;if(n.overflowDir!==a||void 0===o){o=[];let e=a;for(;e.startsWith(t);){const t=r.get(e);t&&o.push(t);const n=(0,s.dirname)(e);if(n===e)break;e=n}n.overflowDir=a,n.overflowChain=o}const i=(0,s.extname)(e);for(const e of o)e.fullSubtreeExtensionCounts[i]??=0,e.fullSubtreeExtensionCounts[i]=Ay(e.fullSubtreeExtensionCounts[i]+1),e.numFiles??=0,e.numFiles=Ay(e.numFiles+1)}}ensureDirectoryPath(e,t,r,n){if(r.has(e)||e===t)return;const o=(0,s.dirname)(e);o!==e&&o.startsWith(t)&&this.ensureDirectoryPath(o,t,r,n);const i=new mC.vq({absPath:e,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!n,fullSubtreeExtensionCounts:{}});r.set(e,i);const a=r.get(o);a&&a.childrenDirs.push(i)}sortTreeChildren(e){e.childrenDirs.sort(((e,t)=>(0,s.basename)(e.absPath).localeCompare((0,s.basename)(t.absPath)))),e.childrenFiles.sort(((e,t)=>e.name.localeCompare(t.name)));for(const t of e.childrenDirs)this.sortTreeChildren(t)}}class vC extends Error{constructor(e,t){super(`Tool ${e} not found, available tools: ${t.join(", ")}`),this.toolName=e,this.availableTools=t,this.name="McpToolNotFoundError"}}function bC(e){if(e instanceof vC)return!0;if(!(e instanceof Error)||"McpToolNotFoundError"!==e.name)return!1;const t=e;return"string"==typeof t.toolName&&Array.isArray(t.availableTools)}function SC(e){return!0===e.url?.startsWith("mcp-provider://")}function kC(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function _C(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function CC(e,t){return(t??[]).some((t=>{const r=kC(t.command),n=_C(t.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==e.command&&(0,Ob.mD)(r,e.command),s=void 0===n||void 0!==e.url&&(0,Ob.eA)(n,e.url);return o&&s}))}function EC(e,t){if(SC(e))return!1;const r=t?.rules??[];if(0===r.length)return!1;if(CC(e,r))return!0;const n=function(e){return e.flatMap((e=>{if(void 0===e.serverUrl)return[];const t=function(e){if(e.includes("*"))return e;const t=e.search(/[?#]/);return-1===t?e:e.slice(0,t)}(e.serverUrl);return t===e.serverUrl?[]:[{...e,serverUrl:t}]}))}(r);return n.length>0&&CC(e,n)}function xC(e,t){const{command:r,url:n}=e;return void 0!==r&&t.commandPatterns.some((e=>(0,Ob.mD)(e.trim(),r)))||void 0!==n&&t.serverUrlPatterns.some((e=>(0,Ob.eA)(e.trim(),n)))}var PC=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class RC extends Error{constructor(e){super(`MCP server "${e}" is disabled`),this.name="McpServerDisabledError"}}class IC extends Error{constructor(e){super(`MCP server "${e}" has not been approved`),this.serverName=e,this.name="McpServerNotApprovedError"}}class TC extends Error{constructor(e,t){super(`MCP server "${e}" is overridden by ${t}`),this.serverName=e,this.overridingConfigPath=t,this.name="McpServerOverriddenError"}}class AC{constructor(e){this.disabledService=e}async load(e,t,r,n,o){if(await this.disabledService.isServerDisabled(t))throw new RC(t);return await o(e,r)}}class $C{constructor(e){this.approvalService=e}async load(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{if(function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(s,(0,$.VI)(e.withName("ServerApprovalMiddleware.load")),!1),!await this.approvalService.isServerApproved(t,r,n))throw new IC(t);return await o(e,r)}catch(e){s.error=e,s.hasError=!0}finally{PC(s)}}}class MC{constructor(e,t){this.approvalsPath=e,this.cwd=t,this.approvalsPromise=this.loadApprovals()}async isServerApproved(e,t,r){const n=function(e,t,r){const n={path:r,server:t};return`${e}-${(0,bo.createHash)("sha256").update(JSON.stringify(n)).digest("hex").substring(0,16)}`}(e,t,this.cwd);return(await this.getApprovals()).includes(n)}async loadApprovals(){try{const e=await(0,Co.readFile)(this.approvalsPath,"utf8"),t=JSON.parse(e);return Array.isArray(t)?t:(await this.saveApprovalsToFile([]),[])}catch(e){if(e instanceof Error&&e.message.includes("ENOENT"))return[];throw e}}async getApprovals(){return this.approvalsPromise}async addApproval(e){const t=await this.approvalsPromise;t.includes(e)||(t.push(e),await this.saveApprovals(t))}async addApprovals(e){const t=await this.approvalsPromise,r=e.filter((e=>!t.includes(e)));r.length>0&&(t.push(...r),await this.saveApprovals(t))}async removeApproval(e){const t=await this.approvalsPromise,r=t.filter((t=>t!==e));r.length!==t.length&&await this.saveApprovals(r)}async clearApprovals(e){const t=await this.approvalsPromise,r=e?t.filter((t=>!e(t))):[];r.length!==t.length&&await this.saveApprovals(r)}async saveApprovalsToFile(e){await(0,Co.mkdir)(s.default.dirname(this.approvalsPath),{recursive:!0}),await(0,Co.writeFile)(this.approvalsPath,JSON.stringify(e,null,2))}async saveApprovals(e){await this.saveApprovalsToFile(e),this.approvalsPromise=Promise.resolve(e)}}const DC=["https://api.cursor.com","https://api2.cursor.sh"],OC=["CURSOR_API_BASE_URL","CURSOR_BACKEND_URL"],FC=/^MCP server ".+" is blocked by \S/u;function NC(e){if(void 0!==e&&""!==e)try{return new URL(e).origin}catch{return}}function LC(e,t=process.env){if(void 0===e)return!1;let r;try{r=new URL(e)}catch{return!1}if("/v1/agent/mcp"!==r.pathname.replace(/\/+$/,"")&&!r.pathname.startsWith("/internal/agent-serve/agent-sdk-mcp-relay/"))return!1;const n=new Set(DC);for(const e of OC){const r=NC(t[e]);void 0!==r&&n.add(r)}return n.has(r.origin)}function jC(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function UC(e,t){if("string"!=typeof e)return;const r=e.trim();return""===r||r.length>t||/\p{Cc}/u.test(r)?void 0:r}function BC(e){if(!Array.isArray(e))return;const t=[];for(const r of e.slice(0,200)){const e=UC(r,200);void 0!==e&&t.push(e)}return t}function WC(e,t){const r=t.slice(0,20).join(", "),n=t.length-20;return n>0?` ${e}: ${r}, and ${n} more.`:` ${e}: ${r}.`}var HC=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},qC=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class zC{async load(e,t,r,n,o){const s=o(e,r);return new VC(e,t,s,r)}}function GC(e){let t;return e.then((e=>{t=e})).catch((()=>{})),t}class VC{constructor(e,t,r,n){this.serverName=t,this.clientPromise=r,this.config=n,this.clientPromiseTraceId=(0,$.fU)(e)?.spanContext()?.traceId,this.toolsPromise=this.clientPromise.then((async t=>null===t?[]:await t.getTools(e))),this.resourcesPromise=this.clientPromise.then((async t=>null===t?[]:(await t.listResources(e)).resources)),this.promptsPromise=this.clientPromise.then((async t=>null===t?[]:await t.listPrompts(e))),this.toolsPromise.catch((()=>{})),this.resourcesPromise.catch((()=>{})),this.promptsPromise.catch((()=>{}))}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=HC(t,(0,$.VI)(e.withName("CachedMcpClient.getTools")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=GC(this.toolsPromise);return void 0!==n?n:await this.toolsPromise}catch(e){t.error=e,t.hasError=!0}finally{qC(t)}}async callTool(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{const i=HC(s,(0,$.VI)(e.withName("CachedMcpClient.callTool")),!1),a=await this.getClient(i.ctx);if(null===a)throw new Error("Client is not ready");return a.callTool(i.ctx,t,r,n,o)}catch(e){s.error=e,s.hasError=!0}finally{qC(s)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=HC(t,(0,$.VI)(e.withName("CachedMcpClient.getInstructions")),!1),n=await this.getClient(r.ctx);if(null===n)return;return await n.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{qC(t)}}async getClient(e){const t={stack:[],error:void 0,hasError:!1};try{const r=HC(t,(0,$.VI)(e.withName("CachedMcpClient.getClient")),!1);return r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined"),await this.clientPromise}catch(e){t.error=e,t.hasError=!0}finally{qC(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{const r=HC(t,(0,$.VI)(e.withName("CachedMcpClient.listResources")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=GC(this.resourcesPromise);return void 0!==n?{resources:n}:{resources:await this.resourcesPromise}}catch(e){t.error=e,t.hasError=!0}finally{qC(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=HC(r,(0,$.VI)(e.withName("CachedMcpClient.readResource")),!1),o=await this.getClient(n.ctx);return null===o?{contents:[]}:o.readResource(n.ctx,t)}catch(e){r.error=e,r.hasError=!0}finally{qC(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{const r=HC(t,(0,$.VI)(e.withName("CachedMcpClient.listPrompts")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=GC(this.promptsPromise);return void 0!==n?n:await this.promptsPromise}catch(e){t.error=e,t.hasError=!0}finally{qC(t)}}async getPrompt(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=HC(n,(0,$.VI)(e.withName("CachedMcpClient.getPrompt")),!1),s=await this.getClient(o.ctx);return null===s?{messages:[]}:s.getPrompt(o.ctx,t,r)}catch(e){n.error=e,n.hasError=!0}finally{qC(n)}}async getState(e){const t={stack:[],error:void 0,hasError:!1};try{const r=HC(t,(0,$.VI)(e.withName("CachedMcpClient.getState")),!1);r.span.setAttribute("serverName",this.serverName);const n=await this.getClient(r.ctx);if(null===n)throw new Error("Client is not ready");return await n.getState(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{qC(t)}}async getAllowlistInUse(){try{await this.toolsPromise;const e=await this.clientPromise;return await(e?.getAllowlistInUse?.())}catch{return}}async getAllowlistRefusal(){if(void 0!==this.config&&"url"in this.config&&LC(this.config.url))try{return void await this.toolsPromise}catch(e){return function(e){const t=e instanceof Error?e.message:"string"==typeof e?e:void 0;if(void 0===t)return;const r=t.indexOf("{");if(-1===r)return;let n;try{n=JSON.parse(t.slice(r))}catch{return}if(!jC(n))return;const o=UC(n.error,700);return void 0!==o&&FC.test(o)?o:void 0}(e)}}async close(){try{const e=await this.clientPromise;await(e?.close?.())}catch{}}}function KC(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function JC(e,t){if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e||"bigint"==typeof e)return String(e);if(null==e)return t;try{const r=JSON.stringify(e);return"string"==typeof r?r:t}catch{return t}}function ZC(e){return e?` (${JC(e,"")})`:""}function XC(e){if(null===e||"string"==typeof e||"boolean"==typeof e)return e;if("number"==typeof e)return Number.isFinite(e)?e:void 0;if(Array.isArray(e)){const t=[];for(const r of e){if(void 0===r){t.push(null);continue}const e=XC(r);if(void 0===e)return;t.push(e)}return t}if("object"!=typeof e)return;const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&null!==t)return;const r={};for(const[t,n]of Object.entries(e)){if(void 0===n)continue;const e=XC(n);if(void 0===e)return;r[t]=e}return r}function QC(e){const t=XC(e);if(null!=t&&"object"==typeof t&&!Array.isArray(t))return t}const YC=new TextDecoder("utf-8",{fatal:!0});function eE(e){return"string"==typeof e?e.split(";")[0]?.trim().toLowerCase()??"":""}function tE(e,t){const r=Buffer.from(t,"base64"),n=function(e){try{const t=YC.decode(e);return t.includes("\0")?void 0:t}catch{return}}(r)??(function(e){const t=eE(e);return t.startsWith("text/")||"application/xml"===t||t.endsWith("+xml")}(e.mimeType)?r.toString("utf8").replace(/^\uFEFF/,""):void 0);if(void 0!==n)return{text:n,binary:!1};const o="string"==typeof e.mimeType&&e.mimeType.length>0?e.mimeType:"unknown type";return{text:`[Binary resource: ${JC(e.uri,"unknown")} (${o}, ${r.byteLength} bytes). The file is not text, so its contents are not included.]`,binary:!0}}const rE=new Set(["image/png","image/jpeg","image/jpg","image/gif","image/webp"]);function nE(e){return"string"==typeof e.text&&e.text.length>0?e.text:void 0}function oE(e){if(!KC(e))return;const t=e.resource;return KC(t)&&void 0===nE(t)&&"string"==typeof t.blob&&rE.has(eE(t.mimeType))?t.blob:void 0}function sE(e){const t=e,r=t.resource;if(KC(r)){const e=nE(r);return void 0!==e?e:"string"==typeof r.blob?tE(r,r.blob).text:`Resource: ${JC(r.uri,"unknown")}${ZC(r.name)}`}return t.uri?`Resource: ${JC(t.uri,"unknown")}${ZC(t.name)}`:`Unsupported content type "${e.type}": ${JSON.stringify(e)}`}function iE(e){const t=QC(e);if(void 0!==t&&0!==Object.keys(t).length)try{return Buffer.byteLength(JSON.stringify(t))<=262144?t:void 0}catch{return}}var aE=r("zod/v4-mini");const cE=aE.object({CLIENT_ID:aE.string(),CLIENT_SECRET:aE.optional(aE.string()),scopes:aE.optional(aE.array(aE.string()))}),lE=aE.strictObject({caBundle:aE.string().check(aE.trim(),aE.minLength(1),aE.maxLength(131072))}),uE=aE.object({type:aE.optional(aE.literal("stdio")),command:aE.string(),args:aE.optional(aE.array(aE.string())),env:aE.optional(aE.record(aE.string(),aE.string())),envFile:aE.optional(aE.string()),cwd:aE.optional(aE.string()),enabledTools:aE.optional(aE.array(aE.string())),startupTimeoutSec:aE.catch(aE.optional(aE.number().check(aE.positive())),void 0)}),dE=aE.object({type:aE.optional(aE.enum(["http","sse"])),url:aE.string(),headers:aE.optional(aE.record(aE.string(),aE.string())),auth:aE.optional(cE),tls:aE.optional(lE),placement:aE.optional(aE.enum(["server","client"])),enabledTools:aE.optional(aE.array(aE.string()))}),hE=aE.union([uE,dE]),pE=aE.object({mcpServers:aE.record(aE.string(),hE)});Error;const fE=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g;function mE(e,t){if("string"==typeof e)return function(e,t){return e.replace(fE,((e,r,n,o)=>{if(void 0!==r){const n=t(r);return void 0!==n?n:e}if(void 0===n)return e;const s=t(n);return void 0!==s?s:void 0!==o?o:e}))}(e,t);if(Array.isArray(e))return e.map((e=>mE(e,t)));if(null!==e&&"object"==typeof e){const r={};for(const[n,o]of Object.entries(e))r[n]=mE(o,t);return r}return e}r("../../node_modules/.pnpm/smol-toml@1.9.0/node_modules/smol-toml/dist/index.js");Symbol("invalid");function gE(e){const t=Object.entries(e);return{jsonKeyOf:new Map(t.map((([e,t])=>[t,e]))),tomlKeyOf:new Map(t)}}const wE=gE({CLIENT_ID:"client_id",CLIENT_SECRET:"client_secret",scopes:"scopes"}),yE=gE({caBundle:"ca_bundle"}),vE=gE({type:"type",command:"command",args:"args",env:"env",envFile:"env_file",cwd:"cwd",enabledTools:"enabled_tools",startupTimeoutSec:"startup_timeout_sec"}),bE=gE({type:"type",url:"url",headers:"http_headers",auth:"auth",tls:"tls",placement:"placement",enabledTools:"enabled_tools"}),SE=(new Map([["auth",{keys:wE,unknownKeyIsError:!1}],["tls",{keys:yE,unknownKeyIsError:!0}]]),"enabled");new Set([...vE.jsonKeyOf.keys(),...bE.jsonKeyOf.keys(),SE]);Symbol("disabled");const kE=(0,l.h)("McpConfig");async function _E(e,t=e=>process.env[e]){try{const r=await(0,Co.readFile)(e,"utf8"),n=mE((0,Cp.qg)(r),t);return pE.parse(n)}catch{return{mcpServers:{}}}}async function CE(e,t=e=>process.env[e]){const r={config:{mcpServers:{}},diagnostics:[]};return r}async function EE(e,t=e=>process.env[e]){const{config:r,diagnostics:n}=await CE(0,t);return n.length>0&&kE.warn((0,y.q6)(),"[mcp config] problems in MCP config; `agent mcp list` shows them",{errorCount:n.filter((e=>"error"===e.severity)).length,warningCount:n.filter((e=>"warning"===e.severity)).length,fileNames:[...new Set(n.map((e=>s.default.basename(e.file))))]}),r}const xE=["enterprise","project","user","env"];function PE(e){return"project"===e||"env"===e}const RE=["0.0.0.0/0","::/0"];function IE(e){const t=(e??[]).filter((e=>e.trim().length>0)),r=t.flatMap((e=>{const t=(0,Ob.bi)(e);return void 0===t?[]:[t]}));return{hasInvalidEntries:r.length!==t.length,entries:r}}function TE(e){const t=!0===e.enabled,r=IE(e.mcpNetworkDenylist),n="deny_all"===e.mcpNetworkMode||r.entries.includes("*")||r.hasInvalidEntries,o=t?function(e){if("allow_all"===e.mcpNetworkMode)return[...RE];const t=IE(e.mcpNetworkAllowlist);if("allowlist"===e.mcpNetworkMode)return t.entries.includes("*")?[...RE]:t.entries;if(!function(e){return(e.mcpNetworkAllowlist??[]).some((e=>e.trim().length>0))}(e))return[...RE];const r=(0,Ob.b6)(e);return r.includes("*")?[...RE]:r}(e):[],s=t?n?["*"]:r.entries:[];return JSON.stringify({enabled:t,mode:e.mcpNetworkMode,allow:n?[]:o,deny:s})}class AE extends Error{constructor(e,t){super(`MCP server "${e}" wasn't started: your team's MCP settings require it to run in a sandbox, and the sandbox isn't supported on this machine. Ask a team admin to review the team's MCP settings for this server.`),this.serverName=e,this.name="McpSandboxUnavailableError",void 0!==t&&(this.cause=t)}}const $E=new Set(["invalid_auth","not_authed","account_inactive","token_revoked","token_expired"]);class ME extends Error{constructor(){super("Your organization admin only allows Slack workspaces your company manages. Connect your company Slack workspace instead."),this.name="SlackWorkspaceNotManagedError"}}class DE extends Error{constructor(){super("Slack couldn't confirm which workspace this connection is for, and your organization admin only allows the Slack workspaces your company manages. Try again in a moment."),this.name="SlackWorkspaceUnconfirmedError"}}function OE(e){return URL.canParse(e)&&"mcp.slack.com"===new URL(e).hostname.toLowerCase()}function FE(e,t){const r=new Map,n=t.lookUpWorkspace??(t=>async function(e,t){let r;try{const n=await e("https://slack.com/api/auth.test",{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/x-www-form-urlencoded"},signal:AbortSignal.timeout(5e3)});r=await n.json()}catch{return{kind:"unavailable"}}if("object"!=typeof r||null===r)return{kind:"unavailable"};if("object"!=typeof(n=r)||null===n||Array.isArray(n))return{kind:"unavailable"};var n;const o=r;return!0!==o.ok?"string"==typeof o.error&&$E.has(o.error)?{kind:"dead"}:{kind:"unavailable"}:"string"!=typeof o.team_id||0===o.team_id.length?{kind:"unavailable"}:"string"==typeof o.enterprise_id&&o.enterprise_id.length>0?{kind:"found",slackTeamId:o.team_id,slackEnterpriseId:o.enterprise_id}:{kind:"found",slackTeamId:o.team_id}}(e,t));let o,s=[];return async(i,a)=>{if(!OE(function(e){return"string"==typeof e?e:e instanceof URL?e.href:e.url}(i)))return e(i,a);const c=function(e,t){const r=new Headers(t?.headers??(e instanceof Request?e.headers:void 0)),n=/^Bearer\s+(.+)$/i.exec(r.get("authorization")??"");return n?.[1]?.trim()||void 0}(i,a);if(void 0===c)return e(i,a);const l=await((void 0===o||Date.now()-o.atMs>=3e4)&&(o={atMs:Date.now(),lists:t.managedSlackWorkspaceLists().then((e=>"unconfirmed"===e?e:(s=e.filter((e=>e.length>0)).map((e=>e.map((e=>e.toUpperCase())))),s)),(()=>s))}),o.lists);if("unconfirmed"===l)throw new DE;if(0===l.length)return e(i,a);let u=r.get(c);if(void 0===u){const t=await n(c);if("dead"===t.kind)return e(i,a);if("unavailable"===t.kind)throw new DE;r.size>=64&&r.clear(),r.set(c,t),u=t}const d=[u.slackTeamId,u.slackEnterpriseId].flatMap((e=>void 0===e?[]:[e.toUpperCase()]));if(!l.every((e=>d.some((t=>e.includes(t))))))throw new ME;return e(i,a)}}function NE(e,t,r){if("string"==typeof e)return t(e);if(!(e instanceof Error))return e;if(r.results.has(e))return r.results.get(e)===e&&r.cycled.add(e),r.results.get(e);r.results.set(e,e);const n=Object.isFrozen(e)&&GE(e,t)?new Error:void 0;void 0!==n&&r.results.set(e,n);const o=t(e.message),s="string"==typeof e.stack?t(e.stack):void 0,i=Object.keys(e).flatMap((n=>{if("cause"===n)return[];const o=UE(e,n),s=qE(o,t,r);return Object.is(s,o)?[]:[[n,s]]})),a=Object.getOwnPropertyDescriptor(e,"cause"),c=void 0===a?void 0:UE(e,"cause"),l=qE(c,t,r),u=e instanceof AggregateError?UE(e,"errors"):void 0,d=function(e,t,r){if(!Array.isArray(e))return e;const n=e.map((e=>qE(e,t,r)));if(n.every(((t,r)=>Object.is(t,e[r]))))return e;try{return n.forEach(((t,r)=>{e[r]=t})),e}catch{return n}}(u,t,r),h=[...i,...Object.is(l,c)?[]:[["cause",l]],...Object.is(d,u)?[]:[["errors",d]]];let p=!1;if(void 0===n)try{o!==e.message&&(e.message=o),void 0!==s&&s!==e.stack&&(e.stack=s),p=e.message===o&&(void 0===s||e.stack===s)&&h.every((([t,r])=>jE(e,t,r)))}catch{}if(p)return e;const f=Object.defineProperties(n??new Error,{message:{value:o,writable:!0,enumerable:!1,configurable:!0},...Object.getOwnPropertyDescriptors(WE(e,new Map(i)))});Array.isArray(d)&&Object.defineProperty(f,"errors",{value:d,writable:!0,enumerable:!1,configurable:!0}),void 0!==a&&Object.defineProperty(f,"cause",{value:l,writable:!0,enumerable:!0===a.enumerable,configurable:!0});const m=Object.getPrototypeOf(e);null!==m&&"object"==typeof m&&m!==Error.prototype&&(Object.setPrototypeOf(f,m),function(e){try{let t=Object.getPrototypeOf(e);for(let r=0;r<8&&null!==t&&"object"==typeof t&&t!==Error.prototype&&t!==Object.prototype;r++){for(const r of Reflect.ownKeys(t)){const n=Object.getOwnPropertyDescriptor(t,r)?.get;void 0!==n&&Reflect.apply(n,e,[])}t=Object.getPrototypeOf(t)}String(e);const r=e;"function"==typeof r.toJSON&&Reflect.apply(r.toJSON,e,[""]);const n=r[BE];return"function"==typeof n&&Reflect.apply(n,e,[0,{depth:0,stylize:String},String]),!0}catch{return!1}}(f)||Object.setPrototypeOf(f,Error.prototype));const g=JE(e);return void 0!==g&&JE(f)!==g&&Object.defineProperty(f,"name",{value:g,writable:!0,configurable:!0,enumerable:!1}),void 0!==s&&(f.stack=s),r.results.set(e,f),f}function LE(e,t){if(e instanceof Error)return t.get(e)??e;if(!Array.isArray(e)||!Object.isFrozen(e))return e;const r=e.map((e=>e instanceof Error?t.get(e)??e:e));return r.every(((t,r)=>Object.is(t,e[r])))?e:r}function jE(e,t,r){const n=Object.getOwnPropertyDescriptor(e,t);return!0===n?.writable&&Reflect.defineProperty(e,t,{...n,value:r})}function UE(e,t){try{const r=Object.getOwnPropertyDescriptor(e,t);return void 0===r?.get?r?.value:r.get.call(e)}catch{return}}const BE=Symbol.for("nodejs.util.inspect.custom");function WE(e,t){const r={};for(const n of Object.keys(e))try{const o=Object.getOwnPropertyDescriptor(e,n),s=void 0===o?.get?o?.value:o.get.call(e);Object.defineProperty(r,n,{value:t.has(n)?t.get(n):s,writable:!0,enumerable:!0,configurable:!0})}catch{}return r}function HE(e,t,r,n){if("string"==typeof e)return t(e);if("object"!=typeof e||null===e)return e;if(e instanceof Error)return NE(e,t,n);if(Array.isArray(e)){if(r>=4)return;return e.slice(0,64).map((e=>HE(e,t,r+1,n)))}const o=Object.getPrototypeOf(e);return o!==Object.prototype&&null!==o?e:r>=4?void 0:function(e,t,r,n){const o={};for(const s of Object.keys(e).slice(0,64))try{const i=Object.getOwnPropertyDescriptor(e,s),a=void 0===i?.get?i?.value:i.get.call(e);Object.defineProperty(o,s,{value:HE(a,t,r,n),writable:!0,enumerable:!0,configurable:!0})}catch{}return o}(e,t,r+1,n)}function qE(e,t,r){if(e instanceof Error)return NE(e,t,r);try{return GE(e,t)?HE(e,t,1,r):e}catch{return}}const zE=4096;function GE(e,t){const r=new Set,n=[e];for(let o=0;n.length>0;o++){if(o>=zE||n.length>zE)return VE(e,t);const s=n.pop();if("string"==typeof s){if(t(s)!==s)return!0}else if((KE(s)||s instanceof Error)&&!r.has(s)){r.add(s),s instanceof Error&&(n.push(UE(s,"message"),UE(s,"stack"),UE(s,"cause")),s instanceof AggregateError&&n.push(UE(s,"errors")));for(const e of Object.keys(s))n.push(UE(s,e))}}return!1}function VE(e,t){const r=new Set;let n;try{n=JSON.stringify(e,((e,t)=>{return"bigint"==typeof t?t.toString():"object"!=typeof t||null===t?t:r.has(t)?void 0:(r.add(t),t instanceof Error?(n=t,{...Object.fromEntries(Object.keys(n).map((e=>[e,UE(n,e)]))),message:UE(n,"message"),stack:UE(n,"stack"),cause:UE(n,"cause"),...n instanceof AggregateError?{errors:UE(n,"errors")}:{}}):t);var n}))}catch{return!0}return void 0!==n&&t(n)!==n}function KE(e){if(Array.isArray(e))return!0;if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function JE(e){try{return"string"==typeof e.name?e.name:void 0}catch{return}}const ZE=/spt_[A-Za-z0-9_]{6,}/g,XE=/[A-Z0-9]/;function QE(e){return function(e){return e.replace(ZE,(e=>function(e){return e.slice(4).split("_").some((e=>e.length>=8&&XE.test(e)))}(e)?"[redacted Link shared payment token]":e))}(e)}var YE=r("../../node_modules/.pnpm/string-argv@0.3.2/node_modules/string-argv/index.js");new Set(["EAI_AGAIN","ECONNABORTED","ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ENOTFOUND","EPIPE","ETIMEDOUT","EADDRNOTAVAIL","UND_ERR_CONNECT_TIMEOUT"]),new Set(["ECONNRESET","EPIPE"]);const ex=new Set([429,502,503,504]);function tx(e){return"object"==typeof e&&null!==e}function rx(e){const t=tx(e)?e.code:void 0,r=(e instanceof Error||tx(e)&&"string"==typeof e.message?e.message:"").match(/\(HTTP (\d+)\)|Non-200 status code \((\d+)\)|\bHTTP\s+(\d{3})\b/i),n=r?.[1]??r?.[2]??r?.[3],o=void 0!==n?parseInt(n,10):void 0;if("number"==typeof t&&t>=100)return void 0!==o&&ex.has(o)&&!ex.has(t)?o:t;if("string"==typeof t&&/^\d{3}$/.test(t)){const e=Number.parseInt(t,10);return e>=100&&e<=599?e:o}return o}new Set(["UND_ERR_SOCKET","UND_ERR_CLOSED","ECONNRESET"]);const nx=8192;function ox(e){return void 0===e?"unknown":"url"in e&&e.url.length>0?void 0!==ib(e.url)?"rest_mcp":"streamable_http":"command"in e?"stdio":"unknown"}new Set(["ENOENT","EACCES","ENOTDIR","EPERM"]);const sx=/\$\{[^}]*\}/;function ix(e){if(void 0!==function(e){if(void 0===e)return;const t=e.trim();return 0!==t.length&&sx.test(t)?t:void 0}(e))return;const t=e?.trim();return t&&t.length>0?t:void 0}const ax=new Map;async function cx(e,t=fetch){if(void 0===ib(e))return;const r=new URL(e),n=`${r.origin}/.well-known/oauth-protected-resource${r.pathname.replace(/\/+$/,"")}`,o=ax.get(n);if(void 0!==o&&o.expiresAtMs>Date.now())return o.metadata;let s;try{const e=await t(n);if(!e.ok)return;s=function(e){if("object"!=typeof(t=e)||null===t)return{};var t;const r=e,n="string"==typeof r.cursor_client_id&&r.cursor_client_id.length>0?r.cursor_client_id:void 0;let o;if("object"==typeof r.cursor_authorization_params&&null!==r.cursor_authorization_params){const e=Object.entries(r.cursor_authorization_params).filter((e=>"string"==typeof e[1]));e.length>0&&(o=Object.fromEntries(e))}return{...void 0!==n?{clientId:n}:{},...!0===r.cursor_omit_resource_indicator?{omitResourceIndicator:!0}:{},...!0===r.cursor_omit_consent_prompt?{omitConsentPrompt:!0}:{},...void 0!==o?{authorizationParams:o}:{},...!0===r.cursor_rejects_custom_scheme_redirects?{rejectsCustomSchemeRedirects:!0}:{},...!0===r.cursor_unauthenticated_connect?{unauthenticatedConnect:!0}:{},...!0===r.cursor_loopback_ipv4?{loopbackIpv4:!0}:{},...!0===r.cursor_backend_only_token_exchange?{backendOnlyTokenExchange:!0}:{}}}(await e.json())}catch{return}return ax.set(n,{metadata:s,expiresAtMs:Date.now()+3e5}),s}(0,_s.J)((function(){ax.clear()}));const lx={info:()=>{},warn:()=>{},error:()=>{},debug:()=>{}};function ux(e){return lx}const dx=/^[\x21\x23-\x5B\x5D-\x7E]+$/,hx=["invalid_request","invalid_token","insufficient_scope"];function px(e){return hx.some((t=>t===e))}function fx(e){const t=new Set;for(const r of e)r.length<=200&&dx.test(r)&&t.add(r);return[...t]}const mx=/[!#$%&'*+.^_`|~0-9A-Za-z-]+/y,gx=/"((?:[^"\\]|\\.)*)"?/y,wx=/[^\s,]*/y;function yx(e,t){let r,n=0;const o=t=>{t.lastIndex=n;const r=t.exec(e);return null!==r&&(n=t.lastIndex),r};for(;n"string"==typeof e&&e.length>0)):void 0}function Sx(e){if("object"!=typeof e||null===e||Array.isArray(e))return vx;const t=bx("grantedScopes"in e?e.grantedScopes:void 0),r=bx("requestedScopes"in e?e.requestedScopes:void 0);return{...void 0!==t?{grantedScopes:t}:{},stepUpScopes:bx("stepUpScopes"in e?e.stepUpScopes:void 0)??[],signInMissing:bx("signInMissing"in e?e.signInMissing:void 0)??[],...void 0!==r?{requestedScopes:r}:{}}}function kx(e){return(e??"").split(/\s+/).filter((e=>e.length>0))}function _x(e,t){return e.filter((e=>!t.has(e)))}function Cx(e){const t=Sb(e.serverUrl),r=e.connectorName??t?.displayName??e.accountKey,n=ux(e.accountKey);let o;const s=async()=>Sx(await e.readRecord()),i=async t=>{if(void 0!==t.grantedScopes)return t.grantedScopes;const r=kx(await e.readTokenScope());return r.length>0?r:void 0},a=(e,t)=>{n.info(`MCP OAuth scope step-up: ${e}`,{event:`mcp_oauth_scope_step_up_${e}`,...t})};return{accountKey:e.accountKey,connectorName:r,async decide(r){if(401!==r.status&&403!==r.status)return;const n=function(e){const t=e??"",r=yx(t,"error")?.toLowerCase(),n=yx(t,"resource_metadata");return{error:void 0===r||""===r?"none":px(r)?r:"other",scopes:fx((yx(t,"scope")??"").split(/\s+/)),resourceMetadata:void 0===n||""===n?void 0:n}}(r.wwwAuthenticate);if("insufficient_scope"!==n.error||0===n.scopes.length)return;if(function(e){try{return kb.has(new URL(e).hostname.toLowerCase())}catch{return!1}}(e.serverUrl))return;const o=function(e,t){if(void 0!==t)try{return new URL(t).origin===new URL(e).origin?t:void 0}catch{return}}(e.serverUrl,n.resourceMetadata),c=void 0===t?await e.readScopesSupported(o).catch((()=>{})):void 0,l=await s(),u=await i(l),{accepted:d,dropped:h}=function(e){const t=new Set(e.granted??[]),r=[],n=[];for(const o of fx(e.named))e.allowlist.has(o)?t.has(o)||r.push(o):n.push(o);return{accepted:r,dropped:n}}({named:n.scopes,allowlist:(p={policy:t,scopesSupported:c,configuredScopes:e.configuredScopes},void 0!==p.policy?new Set([...p.policy.baseScopes,...Object.keys(p.policy.stepUpScopes)]):new Set([...p.scopesSupported??[],...p.configuredScopes??[]])),granted:u});var p;if(0===d.length)return void a("none_accepted",{status:r.status,namedCount:n.scopes.length,droppedCount:h.length});const f=new Set(l.signInMissing),m=d.every((e=>f.has(e)))?"blocked":"offer";return"offer"===m&&await e.writeRecord({...l,...void 0!==u?{grantedScopes:u}:{},stepUpScopes:[...new Set([...l.stepUpScopes,...d])]}),a(m,{status:r.status,acceptedCount:d.length,droppedCount:h.length}),{kind:m,status:r.status,scopes:d,dropped:h,toolName:r.toolName,resourceMetadataUrl:o}},signIn:async e=>(void 0===o&&(o=Promise.resolve().then(e).finally((()=>{o=void 0}))),o),get isSigningIn(){return void 0!==o},tokensForSdk(e){if(void 0===o||void 0===e?.refresh_token)return e;const{refresh_token:t,...r}=e;return r},async prepareAuthorization(){const t=await s();return{stepUpScopes:t.stepUpScopes.length>0?[...new Set([...await i(t)??[],...t.stepUpScopes])]:[],recordRequestedScopes:async t=>{await e.writeRecord({...await s(),requestedScopes:kx(t.searchParams.get("scope"))})}}},async recordTokens(t,{isRefresh:r}){const n=await e.readRecord();if(void 0===n)return;const o=Sx(n),s=kx(t.scope);if(r)return void(s.length>0&&await e.writeRecord({...o,grantedScopes:s}));if(void 0===o.requestedScopes)return;const i=s.length>0?s:o.requestedScopes,c=new Set(i),l=_x(o.requestedScopes,c);await e.writeRecord({grantedScopes:i,stepUpScopes:_x(o.stepUpScopes,c),signInMissing:l}),a("sign_in_recorded",{grantedCount:i.length,signInMissingCount:l.length,scopeReported:s.length>0})},async clear(t){await e.writeRecord(!0===t?.keepPendingScopes?function(e){const{stepUpScopes:t}=Sx(e);return t.length>0?{stepUpScopes:t,signInMissing:[]}:void 0}(await e.readRecord()):void 0)}}}function Ex(e){const t=Sb(e.serverUrl);for(const r of e.scopes){const e=t?.stepUpScopes[r]?.action;if(void 0!==e)return e}return e.toolTitle}function xx(e){const t=function(e){return void 0===e.action?`${e.connectorName} needs a permission its sign-in did not grant.`:`${e.connectorName} needs one more permission to ${e.action}.`}({connectorName:e.connectorName,action:Ex(e)}),r="offer"===e.kind?`Authorize ${e.connectorName} again to approve it; the turn can continue once it's granted.`:`Its last sign-in did not grant ${1===e.scopes.length?"it":"them"}, so an admin or your consent is blocking this. Reconnect ${e.connectorName} from its MCP settings to ask again.`,n=function(e){if(0===e.length)return;const t=e.slice(0,3).join(", "),r=e.length-3;return`${1===e.length?"Permission":"Permissions"}: ${t}${r>0?` and ${r} more`:""}`}(e.scopes);return void 0===n?`${t} ${r}`:`${t} ${r}\n${n}`}class Px extends Error{constructor(e,t,r){super(xx({kind:e.kind,serverUrl:t,connectorName:r,scopes:e.scopes,toolTitle:e.toolName})),this.decision=e,this.serverUrl=t,this.connectorName=r,this.name="McpOAuthScopeStepUpError"}answerWithToolTitle(e){return xx({kind:this.decision.kind,serverUrl:this.serverUrl,connectorName:this.connectorName,scopes:this.decision.scopes,toolTitle:e??this.decision.toolName})}}function Rx(e){if("string"!=typeof e)return;let t;try{t=JSON.parse(e)}catch{return}const r=Array.isArray(t)?t:[t];for(const e of r){if("object"!=typeof e||null===e||!("method"in e)||"tools/call"!==e.method)continue;const t="params"in e?e.params:void 0,r="object"==typeof t&&null!==t&&"name"in t?t.name:void 0;return"string"==typeof r?r:void 0}}function Ix(e){return e instanceof Error&&/does not support dynamic client registration/i.test(e.message)}Error,Error;const Tx=new Set(["UnauthorizedError","InvalidGrantError","InvalidTokenError","InvalidClientError","UnauthorizedClientError"]),Ax=new Set(["invalid_grant","invalid_token","invalid_client","unauthorized_client"]),$x=[/\btoken (?:has |is )?expired\b/i,/\btoken (?:was|is) invalid\b/i,/\binvalid (?:refresh[ _]?)?token\b/i,/\btoken (?:has been |was )?revoked\b/i];var Mx=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js");const Dx="2026-07-28",Ox=-32022,Fx="io.modelcontextprotocol/protocolVersion",Nx="io.modelcontextprotocol/clientCapabilities",Lx="io.modelcontextprotocol/clientInfo",jx="io.modelcontextprotocol/serverInfo",Ux={name:"cursor",version:"1.0.0"},Bx=new Map;function Wx(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Hx(e){const t=new URL(String(e));return t.hash="",t.href}function qx(e,t){const r=Bx.get(e);return!(void 0===r||r<=t()&&(Bx.delete(e),1))}function zx(e,t){try{return Hx(e)===t}catch{return!1}}function Gx(e){return(e.headers.get("content-type")??"").toLowerCase().includes("application/json")}const Vx=new Set(["events/subscribe","events/unsubscribe","events/poll","events/stream"]);function Kx(e,t,r,n,o=t.message){const s=new Headers(e?.headers);if(s.set("mcp-protocol-version",Dx),s.set("mcp-method",r),s.delete("mcp-session-id"),!t.isRequest&&o===t.message)return{...e,headers:s};const i=Wx(o.params)?o.params:{},a=Wx(i._meta)?i._meta:{},c=function(e,t){const r="tools/call"===e||"prompts/get"===e||Vx.has(e)?"name":"resources/read"===e?"uri":void 0,n=void 0===r?void 0:t[r];return"string"==typeof n?n:void 0}(r,i);void 0!==c&&s.set("mcp-name",c);const l=JSON.stringify({...o,params:{...i,_meta:{...a,[Fx]:Dx,[Nx]:n.capabilities,[Lx]:n.clientInfo}}});return{...e,headers:s,body:l}}function Jx(e){return new Response(JSON.stringify({jsonrpc:"2.0",...e}),{status:200,headers:{"content-type":"application/json"}})}function Zx(e,t){const r=Hx(t.serverUrl),n=t.now??Date.now;let o={capabilities:{},clientInfo:{...Ux}},s=!1;const i=()=>s||qx(r,n),a=async(t,i,a)=>{const{method:c,message:l}=t;if(void 0===c)return e(i,a);if("notifications/initialized"===c)return new Response(null,{status:202});if(t.isRequest&&"initialize"===c){const c={jsonrpc:"2.0",id:l.id,method:"server/discover",params:{}},u=await e(i,Kx(a,t,"server/discover",o,c)),d=await async function(e,t,r){if(!e.ok||!Gx(e))return e;let n;try{n=await e.clone().json()}catch{return e}if(!Wx(n)||!Wx(n.result))return e;const o=n.result,s=o.supportedVersions;if(!Array.isArray(s)||!s.includes(Dx))return Jx({id:t,error:{code:Ox,message:"Unsupported protocol version",data:{requested:Dx,supported:s??[]}}});const i=Wx(o._meta)?o._meta:{},a=Wx(i[jx])?i[jx]:{name:new URL(r).hostname,version:"unknown"};return Jx({id:t,result:{protocolVersion:Mx.aE,capabilities:Wx(o.capabilities)?o.capabilities:{},serverInfo:a,..."string"==typeof o.instructions?{instructions:o.instructions}:{}}})}(u,l.id,r);return d!==u&&(s=!0,function(e,t){Bx.set(e,t()+6e5)}(r,n)),d}return e(i,Kx(a,t,c,o))};return async(t,c)=>{const l=function(e,t,r){if("POST"!==(t?.method??"GET").toUpperCase()||"string"!=typeof t?.body||!zx(e,r))return;let n;try{n=JSON.parse(t.body)}catch{return}if(!Wx(n)||"2.0"!==n.jsonrpc)return;const o="string"==typeof n.method?n.method:void 0;return{message:n,method:o,isRequest:void 0!==o&&"id"in n}}(t,c,r);if(void 0===l)return function(e,t,r){return"GET"===(t?.method??"GET").toUpperCase()&&zx(e,r)}(t,c,r)&&i()?new Response(null,{status:405}):e(t,c);if(l.isRequest&&"initialize"===l.method){const e=Wx(l.message.params)?l.message.params:{};o={capabilities:Wx(e.capabilities)?e.capabilities:{},clientInfo:Wx(e.clientInfo)?e.clientInfo:o.clientInfo}}const u=l.isRequest&&"initialize"===l.method;if(u?qx(r,n):i())return a(l,t,c);if(u&&(s=!1),!l.isRequest)return e(t,c);const d=await e(t,c);if(u&&await async function(e){if(e.status>=500||!Gx(e))return!1;const t=Number(e.headers.get("content-length"));if(Number.isFinite(t)&&t>4096)return!1;let r;try{r=await e.clone().json()}catch{return!1}if(!Wx(r)||!Wx(r.error))return!1;const n=r.error;if(n.code!==Ox||!Wx(n.data))return!1;const o=n.data.supported;return Array.isArray(o)&&o.includes(Dx)}(d)){const e=await a(l,t,c);return s?e:d}return d}}function Xx(e,t){if(void 0===t)return{headers:t,cursorAuthHeaderValue:void 0,cursorAuthOrigin:void 0};const r=Object.entries(t),n=r.find((([e])=>e.toLowerCase()===ob));if(void 0===n)return{headers:t,cursorAuthHeaderValue:void 0,cursorAuthOrigin:void 0};let o;try{o=new URL(e).origin}catch{o=void 0}return{headers:Object.fromEntries(r.filter((([e])=>e.toLowerCase()!==ob))),cursorAuthHeaderValue:n[1],cursorAuthOrigin:o}}function Qx(e,t,r){return async(n,o)=>{let s;try{s=new URL("string"==typeof n?n:n.toString()).origin}catch{return r(n,o)}if(s!==t)return r(n,o);const i=await e();if(void 0===i||0===i.length)return r(n,o);const a=new Headers(o?.headers);return a.set(ob,i),r(n,{...o,headers:a,redirect:"manual"})}}class Yx{constructor(e=864e5){this.ttl=e,this.staleDirty=!1,this.refreshGeneration=0}async get(e){const t=performance.now();if(this.state&&this.state.expiresAt>t&&!this.staleDirty)return this.state.value;if(this.staleDirty&&this.state){const t=this.state.value;if(!this.refreshInFlight){const t=this.refreshGeneration;let r;r=(async()=>{try{const r=await e();if(t!==this.refreshGeneration)return;this.state={expiresAt:performance.now()+this.ttl,value:r},this.staleDirty=!1}catch{}finally{r&&this.refreshInFlight===r&&(this.refreshInFlight=void 0)}})(),this.refreshInFlight=r}return t}const r=this.refreshGeneration,n=await e();return r!==this.refreshGeneration||(this.state={expiresAt:performance.now()+this.ttl,value:n},this.staleDirty=!1),n}invalidate(){this.refreshGeneration++,this.state=void 0,this.staleDirty=!1,this.refreshInFlight=void 0}invalidateKeepingStale(){this.state&&(this.staleDirty=!0)}}var eP=r("crypto");function tP(e){const t={};for(const[r,n]of Object.entries(e))void 0!==n&&(t[r]=n);return t}function rP(e,t){const r=function(e){try{const t=new URL(e);return{host:t.host,origin:t.origin,pathname:t.pathname}}catch{return{host:null,origin:null,pathname:null}}}(e),n=!1!==t?.includePath;return{host:r.host,origin:r.origin,path:n?r.pathname:null}}function nP(e,t){return rP(e,t)}function oP(e){if(e)return(0,eP.createHash)("sha256").update(e).digest("hex").slice(0,12)}function sP(e){if(e&&0!==e.length)return oP(JSON.stringify([...e].sort()))}function iP(e){return{clientIdHash:oP(e?.client_id),hasClientSecret:(e?.client_secret??"").length>0,redirectUrisHash:sP(e?.redirect_uris),redirectUriCount:e?.redirect_uris?.length??0}}function aP(e){return"object"==typeof e&&null!==e}function cP(e,t){let r=e;for(const e of t){if(!aP(r)||!(e in r))return;r=r[e]}return r}function lP(e,t){for(const r of t){const t=cP(e,r.split("."));if("string"==typeof t)return t}}function uP(e){if(!e||"object"!=typeof e)return;const t=e.errorCode;return"string"==typeof t?t:void 0}function dP(e){if(!e)return;const t=e.match(/\(HTTP (\d+)\)|Non-200 status code \((\d+)\)|\bHTTP\s+(\d{3})\b/i),r=t?.[1]??t?.[2]??t?.[3];if(!r)return;const n=Number.parseInt(r,10);return Number.isNaN(n)?void 0:n}const hP=e=>e;function pP(e,t){if(e instanceof Error){const r=e.message;return r&&r!==e.name?bP(t(r)):void 0}if("string"==typeof e||"number"==typeof e||"boolean"==typeof e){const r=String(e);return r?bP(t(r)):void 0}}function fP(e){if(e&&"object"==typeof e)return aP(e)?e.cause:void 0}function mP(e,t,r=4){const n=[];let o=e;for(let e=0;e1?n.join(" > "):void 0}const gP="[REDACTED]",wP=/(^|_|-)(token|secret|password|assertion|authorization|verifier|challenge|code)(_|-|$)/i;function yP(e){return e.replace(/(authorization[^:=\r\n]{0,32}[:=]\s*["']?)(?:[A-Za-z][\w.~+/-]*[ \t]+)?[^"',\s&}]+/gi,`$1${gP}`).replace(/((?:access_token|refresh_token|id_token|client_secret|code|password|assertion|token|secret)[^:=\r\n]{0,32}[:=]\s*["']?)([^"',\s&}]+)/gi,`$1${gP}`).replace(/(\bBearer\s+)([A-Za-z0-9\-._~+/]+=*)/gi,`$1${gP}`)}function vP(e,t=256){return e.length>t?`${e.slice(0,Math.max(0,t-3))}...`:e}function bP(e,t){return vP(yP(e),t?.maxLength)}function SP(e,t=hP){if("string"==typeof e)return vP(yP(t(e)));if(void 0!==e)try{const r=JSON.stringify(e,((e,r)=>e&&function(e){const t=e.toLowerCase();return"code"===t||"authorization"===t||t.includes("token")||t.includes("secret")||t.includes("password")||t.includes("assertion")||t.includes("verifier")||t.includes("challenge")||wP.test(t)}(e)?gP:"string"==typeof r?yP(t(r)):r));if(!r)return;return vP(r)}catch{return}}function kP(e,t=hP){const r=fP(e),n=e instanceof Error?e.name:null!=e?typeof e:void 0,o=r instanceof Error?r.name:void 0,s=pP(r,t),i=pP(e,t)??s,a=lP(e,["code","cause.code"]),c=uP(e)??uP(r)??lP(e,["errorCode","error","cause.errorCode","cause.error","body.error","response.body.error"]),l=void 0===c?void 0:bP(t(c)),u=function(e){for(const t of["status","statusCode","response.status","response.statusCode","cause.status","cause.statusCode","cause.response.status","cause.response.statusCode"]){const r=cP(e,t.split("."));if("number"==typeof r&&Number.isFinite(r))return r}}(e)??dP(i)??dP(s),d=SP(cP(e,["response","body"])??cP(e,["body"])??cP(e,["data"])??cP(e,["cause","body"])??cP(e,["cause","response","body"]),t),h=function(e){const t=e.message?.toLowerCase(),r=e.code?.toLowerCase();return t?.includes("timed out")||t?.includes("timeout")||t?.includes("etimedout")||"etimedout"===r?"timeout":t?.includes("enotfound")||t?.includes("eai_again")||t?.includes("dns")||"enotfound"===r||"eai_again"===r?"dns":t?.includes("certificate")||t?.includes("tls")||t?.includes("ssl")?"tls":t?.includes("econnreset")||t?.includes("connection reset")||"econnreset"===r?"connection_reset":t?.includes("econnrefused")||t?.includes("connection refused")||"econnrefused"===r?"connection_refused":void 0}({message:i,code:a}),p=l?"oauth_error":h?"auth_transport_error":i?"generic_error":void 0;return tP({errorName:n,errorMessage:i,errorType:null!=e?typeof e:void 0,httpStatus:u,oauthErrorCode:l,errorResponseSummary:d,networkClassification:h,causeName:o,causeMessage:s,causeChain:mP(e,t),sdkErrorKind:p})}const _P={mcp_oauth_provider_initialized:"MCP OAuth provider initialized",mcp_oauth_tokens_loaded:"MCP OAuth tokens loaded",mcp_oauth_tokens_saved:"MCP OAuth tokens saved",mcp_oauth_callback_completion:"MCP OAuth callback exchange completed",mcp_oauth_client_info_loaded:"MCP OAuth client information loaded",mcp_oauth_client_info_saved:"MCP OAuth client information saved",mcp_oauth_refresh_prepare:"MCP OAuth refresh prepared",mcp_oauth_refresh_error_release:"MCP OAuth refresh error released",mcp_oauth_state_transition:"MCP OAuth state transition",mcp_oauth_credentials_invalidated:"MCP OAuth credentials invalidated"};function CP(e){const t=e.message??_P[e.event],r={event:e.event,cursorMcp:{oauth:tP({...e.metadata})}},n=e.level??"info";"error"!==n?"warn"!==n?"debug"!==n?e.logger.info?.(t,r):e.logger.debug?.(t,r):e.logger.warn?.(t,r):e.logger.error?.(t,e.error,r)}const EP=new Map(["AWS4-HMAC-SHA256","Api-Key","ApiKey","Basic","Bearer","Bot","DPoP","Digest","GNAP","HOBA","Key","Mutual","NTLM","Negotiate","OAuth","PrivateToken","SCRAM-SHA-1","SCRAM-SHA-256","Token","vapid"].map((e=>[e.toLowerCase(),e]))),xP=4096;function PP(e){return"object"==typeof e&&null!==e&&"url"in e&&"string"==typeof e.url}function RP(e){return"string"==typeof e?e:e instanceof URL?e.toString():e.url}function IP(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function TP(e){if(e instanceof Headers)return e;if(Array.isArray(e)){const t=[];for(const r of e){if(!Array.isArray(r)||"string"!=typeof r[0]||"string"!=typeof r[1])return;t.push([r[0],r[1]])}return t}if(IP(e)){const t={};for(const[r,n]of Object.entries(e)){if("string"!=typeof n)return;t[r]=n}return t}}function AP(e,t){const r=new Headers(TP(PP(e)?e.headers:void 0));return new Headers(TP(t?.headers)).forEach(((e,t)=>{r.set(t,e)})),r}function $P(e){const t=[];return e.forEach(((e,r)=>{t.push(r)})),t.sort()}function MP(e){if(null===e)return null;const t=Number.parseInt(e,10);return Number.isNaN(t)?null:t}function DP(e,t){if(null==e)return{kind:"none",bytes:0,contentLength:MP(t.get("content-length"))};if("string"==typeof e){const r=(new TextEncoder).encode(e).length;return{kind:"text",bytes:r,contentLength:MP(t.get("content-length"))??r}}if(e instanceof URLSearchParams){const r=e.toString(),n=(new TextEncoder).encode(r).length;return{kind:"text",bytes:n,contentLength:MP(t.get("content-length"))??n}}return e instanceof Blob?{kind:"blob",bytes:e.size,contentLength:MP(t.get("content-length"))??e.size}:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?{kind:"binary",bytes:e.byteLength,contentLength:MP(t.get("content-length"))??e.byteLength}:"object"==typeof e&&null!==e&&("getReader"in e||Symbol.asyncIterator in e)?{kind:"stream",bytes:null,contentLength:MP(t.get("content-length"))}:{kind:"unknown",bytes:null,contentLength:MP(t.get("content-length"))}}function OP(e,t){if(null===e||!e.toLowerCase().startsWith("application/x-www-form-urlencoded"))return;const r="string"==typeof t?function(e){for(const t of e.split("&")){const e=t.indexOf("="),r=e>=0?t.slice(0,e):t;let n;try{n=decodeURIComponent(r.replaceAll("+"," "))}catch{return}if("grant_type"!==n)continue;const o=e>=0?t.slice(e+1):"";try{return decodeURIComponent(o.replaceAll("+"," "))}catch{return}}}(t):t instanceof URLSearchParams?t.get("grant_type")??void 0:void 0;return r?function(e){switch(e){case"authorization_code":case"refresh_token":case"client_credentials":case"urn:ietf:params:oauth:grant-type:jwt-bearer":case"urn:ietf:params:oauth:grant-type:token-exchange":return e;default:return"other"}}(r):void 0}function FP(e){const{input:t,init:r}=e,n=rP(RP(t)),o=AP(t,r),s=$P(o),i=o.get("content-type"),a=oP(o.get("mcp-session-id")??void 0),c=function(e){if(!e)return null;const t=e.trim().split(/\s+/,1)[0]??"";return EP.get(t.toLowerCase())??"unrecognized"}(o.get("authorization"));return{method:(r?.method??(PP(t)?t.method:void 0)??"GET").toUpperCase(),url:n,headers:{names:s,count:s.length},contentType:i,body:DP(r?.body,o),sessionIdHash:a??null,authorizationScheme:c}}function NP(e,t){const r=$P(e.headers),n=MP(e.headers.get("content-length"));return{status:e.status,ok:e.ok,headers:{names:r,count:r.length},contentType:e.headers.get("content-type"),body:{kind:null===e.body?"none":"stream",bytes:null===e.body?0:n,contentLength:n,...void 0!==t?{errorSummary:t}:{}},sessionIdHash:oP(e.headers.get("mcp-session-id")??void 0)??null,wwwAuthenticateHash:oP(e.headers.get("www-authenticate")??void 0)??null,mcpProtocolVersion:e.headers.get("mcp-protocol-version")??null,requestId:e.headers.get("x-request-id")??null,retryAfter:LP(e.headers,"retry-after"),slackRateLimitType:LP(e.headers,"x-slack-ratelimit-type")}}function LP(e,t){return e.get(t)?.slice(0,64)??null}function jP(e){const t={};return void 0!==e.errorName&&(t.name=e.errorName),void 0!==e.errorMessage&&(t.message=e.errorMessage),void 0!==e.errorType&&(t.type=e.errorType),void 0!==e.oauthErrorCode&&(t.oauthErrorCode=e.oauthErrorCode),void 0!==e.errorResponseSummary&&(t.responseSummary=e.errorResponseSummary),void 0!==e.networkClassification&&(t.networkClassification=e.networkClassification),void 0!==e.sdkErrorKind&&(t.sdkErrorKind=e.sdkErrorKind),t}function UP(e,t){const r=FP({input:e,init:t});if(void 0!==OP(r.contentType,t?.body))return!0;const n=r.url.path?.toLowerCase()??"";return n.endsWith("/token")||n.includes("/oauth/token")||n.includes("/connect/token")}const BP=e=>e,WP="REDACTED_SESSION_ID",HP=/\b00D[A-Za-z0-9]{12,15}![A-Za-z0-9._]{20,512}/g;async function qP(e,t,r){try{const n=r(await e.clone().text());return n.length>t?n.slice(0,t):n}catch{return}}async function zP(e){if(!UP(e.input,e.init))return;const t=await qP(e.response,xP,e.redact);if(void 0!==t)try{return SP(JSON.parse(t))}catch{return bP(t,{maxLength:xP})}}async function GP(e){const t=await async function(e,t,r){try{if(t.ok)return;const n=t.headers.get("content-type")?.toLowerCase()??"";if(!n.includes("json")&&!n.includes("text"))return;const o=await qP(t,xP,r);if(void 0===o)return;return function(e){if("/mcp"!==(t=rP(RP(e.input)).path)&&!0!==t?.endsWith("/mcp"))return bP(e.rawText,{maxLength:xP});var t;try{const t=JSON.parse(e.rawText);return IP(t)?function(e){const t=e.error;if("string"==typeof t)return JSON.stringify({error:t});if("object"!=typeof t||null===t)return;if(!IP(t))return;const r=t,n="number"==typeof r.code||"string"==typeof r.code?r.code:void 0,o="string"==typeof r.message?bP(r.message,{maxLength:xP}):void 0;return void 0!==n||void 0!==o?JSON.stringify({...void 0!==n?{code:n}:{},...void 0!==o?{message:o}:{}}):void 0}(t):void 0}catch{return}}({input:e,rawText:o})}catch{return}}(e.input,e.response,e.redact);return{responseErrorSummary:t,oauthTokenErrorBodySummary:void 0===t?await zP({input:e.input,response:e.response,init:e.init,redact:e.redact}):void 0}}function VP(e,t,r){try{e()}catch{t.warn?.("MCP HTTP exchange logging failed",{event:"mcp_http_exchange_logging_failure",phase:r})}}function KP(e,t,r){if("string"==typeof e)return t(e);if("object"!=typeof e||null===e||r>12)return e;if(Array.isArray(e))return e.map((e=>KP(e,t,r+1)));const n=Object.getPrototypeOf(e);return n!==Object.prototype&&null!==n?e:Object.fromEntries(Object.entries(e).map((([e,n])=>[e,KP(n,t,r+1)])))}function JP(e,t){const r=e=>{const r=KP(e,t,0);return IP(r)?r:void 0};return{debug:(t,n)=>e.debug?.(t,r(n)),info:(t,n)=>e.info?.(t,r(n)),warn:(t,n)=>e.warn?.(t,r(n))}}function ZP(e){const{fetch:t,logSuccessfulExchanges:r=!0,redactLogText:n}=e,o=void 0===n?e.logger:JP(e.logger,n);return async(s,i)=>{const a=Date.now(),c="function"==typeof e.metadata?e.metadata(s):e.metadata,l=!0===e.redactEchoedSessionId?function(e,t,r){const n=AP(e,t).get("mcp-session-id")?.trim()??"";return e=>{const t=n.length>=8?e.split(n).join(WP):e;return r(t.replace(HP,WP))}}(s,i,n??BP):n??BP;try{const e=await t(s,i),{responseErrorSummary:n,oauthTokenErrorBodySummary:u}=e.ok?{}:await GP({input:s,init:i,response:e,redact:l});return!r&&e.ok||VP((()=>{!function(e){const{logger:t,response:r}=e,n=function(e){const{input:t,init:r,response:n,durationMs:o,metadata:s,responseErrorSummary:i,oauthTokenErrorBodySummary:a}=e,c=FP({input:t,init:r}),l=OP(c.contentType,r?.body);return{event:"mcp_http_exchange",outcome:n.ok?"success":"http_error",durationMs:o,cursorMcp:{transport:{...s,request:c,response:NP(n,i),...void 0!==l?{oauth:{grantType:l}}:{},...void 0!==a?{oauthTokenErrorBodySummary:a}:{}}}}}(e);r.ok?t.info?.("MCP HTTP exchange completed",n):function(e){return 401===e.response.status&&null===e.request.authorizationScheme&&e.response.headers.has("www-authenticate")&&!UP(e.input,e.init)}({response:r,request:n.cursorMcp.transport.request,input:e.input,init:e.init})?t.debug?.("MCP HTTP exchange completed",n):t.warn?.("MCP HTTP exchange completed",n)}({logger:o,input:s,init:i,response:e,durationMs:Date.now()-a,metadata:c,responseErrorSummary:n,oauthTokenErrorBodySummary:u})}),o,"success"),e}catch(t){const r=function(e){if(!aP(e))return;const t=aP(e.cause)?e.cause:void 0,r=[e.response,t?.response];for(const e of r)if("object"==typeof(n=e)&&null!==n&&"status"in n&&"number"==typeof n.status&&"headers"in n&&"object"==typeof n.headers&&null!==n.headers&&"get"in n.headers&&"function"==typeof n.headers.get)return e;var n}(t),{responseErrorSummary:u,oauthTokenErrorBodySummary:d}=r?await GP({input:s,init:i,response:r,redact:l}):{};throw VP((()=>{!function(e){const{logger:t}=e;t.warn?.("MCP HTTP exchange failed",function(e){const{input:t,init:r,error:n,durationMs:o,metadata:s,responseFromError:i,responseErrorSummary:a,oauthTokenErrorBodySummary:c}=e,l=kP(n,e.redactLogText),u=FP({input:t,init:r}),d=OP(u.contentType,r?.body);return{event:"mcp_http_exchange",outcome:"error",durationMs:o,cursorMcp:{transport:{...s,request:u,response:void 0!==i?NP(i,a):{status:l.httpStatus??null,ok:null,headers:{names:[],count:0},contentType:null,body:{kind:"none",bytes:null,contentLength:null,...void 0!==a?{errorSummary:a}:{}},requestId:null,sessionIdHash:null,wwwAuthenticateHash:null,mcpProtocolVersion:null,retryAfter:null,slackRateLimitType:null},...void 0!==d?{oauth:{grantType:d}}:{},...void 0!==c?{oauthTokenErrorBodySummary:c}:{},error:jP(l)}}}}(e))}({logger:o,input:s,init:i,error:t,durationMs:Date.now()-a,metadata:c,responseFromError:r,responseErrorSummary:u,oauthTokenErrorBodySummary:d,redactLogText:!0===e.redactEchoedSessionId?l:n})}),o,"failure"),t}}}function XP(e,t){const r=e?.access_token,n="string"==typeof r?r.length:0,o=Boolean(e?.refresh_token),s="number"==typeof e?.expires_in&&Number.isFinite(e.expires_in)?e.expires_in:null;return{accessTokenLen:n,refreshTokenPresent:o,expiresAtTimestamp:t?.expiresInIsFresh&&null!==s?Date.now()+Math.round(1e3*s):null,grantedScope:"string"==typeof e?.scope&&e.scope.length>0?e.scope:null}}function QP(e){const t=function(e){if(!e||"object"!=typeof e)return;const t=e.code;if("number"==typeof t&&t>=100&&t<=599)return t;if("string"==typeof t&&/^\d{3}$/.test(t)&&Number(t)>=100&&Number(t)<=599)return Number(t);const r=e instanceof Error||"object"==typeof e&&null!==e&&"message"in e&&"string"==typeof e.message?e.message:void 0;if(!r)return;const n=r.match(/\bHTTP\s+(\d{3})\b/i);if(!n?.[1])return;const o=Number.parseInt(n[1],10);return Number.isNaN(o)?void 0:o}(e);return void 0!==t?400===t||404===t||405===t:!!(e instanceof Error&&e.message.toLowerCase().includes("sessionid must be provided"))||function(e){if(!(e instanceof Error))return!1;const t="code"in e&&"string"==typeof e.code?e.code:void 0,r="cause"in e&&"object"==typeof e.cause&&null!==e.cause&&"code"in e.cause&&"string"==typeof e.cause.code?e.cause.code:void 0;return"ECONNREFUSED"===t||"ECONNREFUSED"===r||e.message.includes("ECONNREFUSED")}(e)}function YP(e,t=process.env){const r=t.TMPDIR,n={...void 0===r?{}:{TMPDIR:r},...e},{NODE_COMPILE_CACHE:o,...s}=n;return{...s,NODE_DISABLE_COMPILE_CACHE:"1"}}const eR=["PYTHONIOENCODING","PYTHONUTF8","PYTHONLEGACYWINDOWSSTDIO"],tR=[".exe",".cmd",".bat"],rR=/^pythonw?(?:\d+(?:\.\d+)*t?)?$/,nR=new Set(["py","pyw"]),oR=new Set(["--cache-dir","--color","--allow-insecure-host","--directory","--project","--config-file"]),sR=new Set;function iR(e){return eR.some((t=>function(e,t){const r=t.toUpperCase();return Object.entries(e).some((([e,t])=>void 0!==t&&e.toUpperCase()===r))}(e,t)))}function aR(e,t){for(let r=0;r=2&&e.endsWith(t)?e.slice(1,-1):e}(e.trim())).toLowerCase();for(const e of tR)if(t.endsWith(e))return t.slice(0,-e.length);return t}(e);if(rR.test(r)||nR.has(r)||"uvx"===r)return!0;if("uv"===r){const e=aR(t,oR);return"run"===e?.value||"tool"===e?.value&&"run"===aR(e.rest,oR)?.value}return"pipx"===r&&"run"===aR(t,sR)?.value}(n,o)?iR(i)||iR(r)?i:{...i,PYTHONIOENCODING:"utf-8:surrogateescape"}:i}async function lR(e){const t=[],r=new Set;let n;for(let o=1;;o++){const s=await e.fetchPage(n),i=e.itemsOf(s);t.push(...i);const a=e.nextCursorOf(s);if(!a||r.has(a))return t;if(o>=1e3)throw new Error("MCP list did not end after 1000 pages; refusing to keep paging");r.add(a),n=a}}var uR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"),dR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js"),hR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js"),pR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js");var fR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js");function mR(e){return`${typeof e}:${String(e)}`}function gR(e){const t=new Map,r=new Set,n=new Set,o=e=>{for(const t of n)t(e)},s=e=>{t.delete(e),r.delete(e)},i=e.send.bind(e);e.send=(e,n)=>((e=>{if("method"in e)if("tools/call"===e.method&&"id"in e){const r=e.params?.name;"string"==typeof r&&t.set(mR(e.id),r)}else if("notifications/cancelled"===e.method){const n=e.params?.requestId;if("string"!=typeof n&&"number"!=typeof n)return;const o=mR(n);if(!t.has(o))return;if(r.add(o),r.size>64){const e=r.values().next().value;void 0!==e&&s(e)}}})(e),i(e,n));const a=e.onmessage;return e.onmessage=(e,n)=>{(e=>{if("method"in e)return void("notifications/tools/list_changed"===e.method&&o({kind:"tools_list_changed"}));if(!("id"in e))return;const n=e.id;if("string"!=typeof n&&"number"!=typeof n)return;const i=mR(n),a=t.get(i);if(void 0===a)return;const c=r.has(i);if(s(i),!c)return;const l="error"in e||"object"==typeof e.result&&null!==e.result&&"isError"in e.result&&!0===e.result.isError;o({kind:"late_tool_result",toolName:a,isError:l})})(e),a?.(e,n)},{subscribe:e=>(n.add(e),()=>{n.delete(e)})}}function wR(e){const t=Object.entries(e.headers??{}).map((([e,t])=>[e.toLowerCase(),t])).sort((([e],[t])=>et?1:0));return(0,bo.createHash)("sha256").update(JSON.stringify([e.url,t,e.accessToken??null])).digest("hex")}class yR{constructor(e,t){this.inner=e,this.initializeResult=t,e.onclose=()=>this.onclose?.(),e.onerror=e=>this.onerror?.(e),e.onmessage=e=>this.onmessage?.(e)}get sessionId(){return this.inner.sessionId}setProtocolVersion(e){this.inner.setProtocolVersion(e)}start(){return this.inner.start()}close(){return this.inner.close()}async send(e,t){if((0,Mx.vo)(e)&&(0,Mx.eK)(e)){const t={jsonrpc:"2.0",id:e.id,result:this.initializeResult};queueMicrotask((()=>this.onmessage?.(t)))}else(0,Mx.wU)(e)||await this.inner.send(e,t)}}const vR=je.object({tools:je.array(je.unknown()),nextCursor:je.unknown().optional(),_meta:je.unknown().optional()}),bR={typeFilled:0,toolDropped:0,outputStripped:0};function SR(e){if(PR(e))return"string"==typeof e.name?e.name:void 0}function kR(e){return _R(e.issues.filter((e=>"outputSchema"===e.path[0])))}function _R(e){return e.map((e=>`${e.path.map(String).join(".")}: ${e.message}`))}function CR(e){if(!PR(e))return e;const t={...e};return delete t.outputSchema,t}function ER(e){return PR(e)&&!("type"in e)}function xR(e,t){return{...e,inputSchema:{type:"object",...t}}}function PR(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var RR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js");const IR=new class{constructor({maxSchemasPerCompiler:e=2048,createCompiler:t=()=>new RR.p}={}){this.compiled=new Map,this.maxSchemasPerCompiler=e,this.createCompiler=t,this.compiler=t()}get compiledSchemaCount(){return this.compiled.size}getValidator(e){let t;return r=>(t??=this.compile(e),t(r))}compile(e){const t=JSON.stringify(e),r=(0,bo.createHash)("sha256").update(t).digest("base64url"),n=this.compiled.get(r);if(void 0!==n)return n;this.compiled.size>=this.maxSchemasPerCompiler&&(this.compiler=this.createCompiler(),this.compiled.clear());const o=(t.includes('"$id"')?this.createCompiler():this.compiler).getValidator(e);return this.compiled.set(r,o),o}};class TR{constructor(){this.decoder=new TextDecoder("utf-8"),this.captured="",this.capturedBytes=0}push(e){const t="string"==typeof e?e:this.decoder.decode(e,{stream:!0});return this.append(t),t}end(){const e=this.decoder.decode();return this.append(e),e}get text(){return this.captured}get full(){return this.capturedBytes>=nx}append(e){const t=nx-this.capturedBytes;if(t<=0||0===e.length)return;const r=function(e,t){if(!(t>0))return"";if(3*e.length<=t)return e;const{read:r}=Xo(e,Math.trunc(t));return r>=e.length?e:e.slice(0,r)}(e,t);this.captured+=r,this.capturedBytes=r.length=100&&t<=599?{error_class:"http",error_code:String(t),transport:e.transport}:void 0!==e.error||!0===e.failed?{error_class:"other",error_code:"exception",transport:e.transport}:!0===e.isError?{error_class:"payload",error_code:"is_error",transport:e.transport}:{error_class:"none",error_code:"none",transport:e.transport}}({transport:ox(t),...r}))}catch{}}const NR=(0,u.Pu)("mcp_tool.oauth_scope_step_up",{description:"A tools/call refused for a missing OAuth scope, by step-up decision",labelNames:["decision","dropped"]});function LR(e){return void 0===e?"unknown":"url"in e?"http":"stdio"}const jR=["authorization_code","refresh_token"],UR=["code"];class BR{constructor(e){this._refreshInProgress=!1,this._identifier=e.identifier,this._redirectUrl=e.redirectUrl,this._serverUrl=e.serverUrl,this._restMcpProviderMetadata=e.restMcpProviderMetadata,this.validateResourceURL=!0===e.restMcpProviderMetadata?.omitResourceIndicator?async()=>{}:function(e,t){if(function(e,t){const r=t.gtmApiOrigin;if(void 0===e||void 0===r)return!1;let n,o;try{n=new URL(e),o=new URL(r)}catch{return!1}return n.protocol===o.protocol&&n.hostname===o.hostname&&""===n.port&&"/mcp"===n.pathname}(e,t))return async()=>{};const r=vb(e);return void 0!==r&&function(e){return"https:"===e.protocol&&e.hostname===new URL(ab).hostname}(r)?async()=>{}:void 0!==r&&function(e){return"https:"===e.protocol&&"setup.shopify.com"===e.hostname&&""===e.port&&"/mcp"===e.pathname}(r)?bb:wb}(e.serverUrl,e.gtmMcpMatch),this._clientMetadata=e.clientMetadata,this._scopes=e.scopes,this._isScopePinGateEnabled=e.isScopePinGateEnabled,this.scopeStepUp=e.scopeStepUp,this._tokens=e.tokens,this._clientInformation=e.clientInformation,this._saveTokens=e.saveTokens,this._prepareForRefresh=e.prepareForRefresh,this._releaseRefreshLeaseOnError=e.releaseRefreshLeaseOnError,this._invalidateCredentials=e.invalidateCredentials,this._saveClientInformation=e.saveClientInformation,this.addClientAuthentication=e.addClientAuthentication}get redirectUrl(){return this._redirectUrl}get clientMetadata(){return this._clientMetadata}state(){return this._oauthAttemptId=(0,bo.randomUUID)(),this._oauthState=function(e,t,r){const n={id:e,owner:t,...r?{attemptId:r}:{}};return Buffer.from(JSON.stringify(n),"utf8").toString("base64url")}(this._identifier,{workspaceId:this._redirectUrl},this._oauthAttemptId),this._oauthState}clientInformation(){return this._clientInformation}hasClientInformation(){return void 0!==this._clientInformation}async saveClientInformation(e){this._clientInformation=e,await this._saveClientInformation(e)}tokens(){return this.scopeStepUp?.tokensForSdk(this._tokens)??this._tokens}async saveTokens(e){const t=this._refreshInProgress;this._refreshInProgress=!1,this._tokens=e,await this._saveTokens(e),await(this.scopeStepUp?.recordTokens(e,{isRefresh:t}))}async prepareForRefresh(){await(this._prepareForRefresh?.()),this._refreshInProgress=!0}async releaseRefreshLeaseOnError(e){this._refreshInProgress=!1,await(this._releaseRefreshLeaseOnError?.(e))}async invalidateCredentials(e){switch(this._refreshInProgress=!1,e){case"tokens":this._tokens=void 0;break;case"client":this._clientInformation=void 0;break;case"verifier":this._codeVerifier=void 0,this._oauthState=void 0,this._oauthAttemptId=void 0;break;case"all":this._tokens=void 0,this._clientInformation=void 0,this._codeVerifier=void 0,this._oauthState=void 0,this._oauthAttemptId=void 0,this._lastRedirectUrl=void 0,await(this.scopeStepUp?.clear({keepPendingScopes:!0}));break;default:return e}await(this._invalidateCredentials?.(e))}async redirectToAuthorization(e){const t=await(this.scopeStepUp?.prepareAuthorization());(function(e,t,r={}){const n=r.stepUpScopes??[],o=void 0!==t&&t.length>0?t:n.length>0?(e.searchParams.get("scope")??"").split(" ").filter((e=>e.length>0)):void 0;var s;void 0!==o&&e.searchParams.set("scope",(s={scopes:o,stepUpScopes:n},[...new Set([...s.scopes,...s.stepUpScopes])]).join(" "))})(e,function(e,t,r){const n=mb(e);return!0!==n?.pinsScopesOverConfiguredScopes?void 0!==t&&t.length>0||void 0===r?t:Sb(e)?.baseScopes??t:void 0!==n.scopesPinGate&&!0!==r?.(n.scopesPinGate)?t:n.scopes??t}(this._serverUrl??"",this._scopes,this._isScopePinGateEnabled),{stepUpScopes:t?.stepUpScopes}),void 0!==this._serverUrl&&function(e,t){const r=mb(t)?.authorizationParams;if(void 0!==r)for(const[t,n]of Object.entries(r))e.searchParams.set(t,n)}(e,this._serverUrl);for(const[t,r]of Object.entries(this._restMcpProviderMetadata?.authorizationParams??{}))e.searchParams.set(t,r);(!0===this._restMcpProviderMetadata?.omitConsentPrompt||function(e){return"login.microsoftonline.com"===e.hostname}(e))&&function(e){const t=new Set(e.searchParams.getAll("prompt").flatMap((e=>e.split(" "))).filter((e=>""!==e&&"consent"!==e)));e.searchParams.delete("prompt"),t.size>0&&e.searchParams.set("prompt",[...t].join(" "))}(e),await(t?.recordRequestedScopes(e)),this._lastRedirectUrl=e}get lastRedirectUrl(){return this._lastRedirectUrl}async saveCodeVerifier(e){this._codeVerifier=e}codeVerifier(){if(!this._codeVerifier)throw new Error("No code verifier saved");return this._codeVerifier}}async function WR(e){const{serverName:t,config:n,tokenStorage:o}=e,s=await cx(n.url,e.fetchImpl),i=Ab({loopbackIpv4:s?.loopbackIpv4,redirectUrl:e.authRedirectUrl}),a=function(e,t){const r=ix(e?.CLIENT_ID);if(void 0!==r)return{client_id:r,...e?.CLIENT_SECRET?{client_secret:e.CLIENT_SECRET}:{},redirect_uris:$b(t),grant_types:[...jR],response_types:[...UR],token_endpoint_auth_method:"none"}}(n.auth,i),c=function({storedClientInformation:e,staticClientInformation:t}){return t?e&&e.client_id===t.client_id?{...t,...e,client_secret:t.client_secret??e.client_secret,redirect_uris:t.redirect_uris,grant_types:e.grant_types??t.grant_types,response_types:e.response_types??t.response_types,token_endpoint_auth_method:e.token_endpoint_auth_method??t.token_endpoint_auth_method}:t:e}({storedClientInformation:await o.loadClientInformation(),staticClientInformation:a});return new BR({identifier:t,redirectUrl:i,serverUrl:n.url,restMcpProviderMetadata:s,gtmMcpMatch:e.gtmMcpMatch??{gtmApiOrigin:void 0},clientMetadata:{redirect_uris:$b(i),token_endpoint_auth_method:"none",grant_types:[...jR],response_types:[...UR],client_name:"Cursor",logo_uri:"https://ptht05hbb1ssoooe.public.blob.vercel-storage.com/assets/uploads/cursorlogomcpv3.svg"},scopes:n.auth?.scopes,isScopePinGateEnabled:e.isScopePinGateEnabled,...!0===e.scopeChallengeStepUp&&void 0!==o.loadScopeStepUpRecord&&void 0!==o.saveScopeStepUpRecord?{scopeStepUp:Cx({serverUrl:n.url,accountKey:t,configuredScopes:n.auth?.scopes,readTokenScope:async()=>void 0!==o.loadGrantedScope?o.loadGrantedScope():(await o.loadTokens())?.scope,readRecord:async()=>o.loadScopeStepUpRecord?.(),writeRecord:async e=>o.saveScopeStepUpRecord?.(e),readScopesSupported:t=>async function(e){try{const{discoverAuthorizationServerMetadata:t,discoverOAuthProtectedResourceMetadata:n}=await Promise.resolve().then(r.bind(r,"../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js")),o=await n(e.serverUrl,void 0!==e.resourceMetadataUrl?{resourceMetadataUrl:new URL(e.resourceMetadataUrl)}:void 0,e.fetch),s=await t(o.authorization_servers?.[0]??new URL("/",e.serverUrl),{fetchFn:e.fetch}).catch((()=>{}));if(void 0===s&&!0===e.requireAuthorizationServerMetadata)return;const i=new Set([...o.scopes_supported??[],...s?.scopes_supported??[]]);return i.size>0?[...i]:void 0}catch{return}}({serverUrl:n.url,resourceMetadataUrl:t,fetch:e.fetchImpl})})}:{},tokens:await o.loadTokens(),clientInformation:c,saveTokens:e=>o.saveTokens(e),prepareForRefresh:()=>o.prepareForRefresh?.()??Promise.resolve(),releaseRefreshLeaseOnError:e=>o.releaseRefreshLeaseOnError?.(e)??Promise.resolve(),invalidateCredentials:o.invalidateCredentials?e=>o.invalidateCredentials(e):void 0,saveClientInformation:e=>o.saveClientInformation(e),addClientAuthentication:o.tokenEndpointAuth?.({clientId:c?.client_id})})}const HR=new Set;let qR=!1;function zR(){for(const e of HR)try{process.kill(e,"SIGKILL")}catch{}}function GR(e){return Ix(e)?new uR.D_:e}function VR(e,t){return Zx(e??globalThis.fetch.bind(globalThis),{serverUrl:t})}function KR(e,t,r){const n=Xx(e,t),o=r??(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),s=void 0!==n.cursorAuthHeaderValue&&void 0!==n.cursorAuthOrigin&&void 0!==o?Qx((()=>n.cursorAuthHeaderValue),n.cursorAuthOrigin,o):o;return{transportHeaders:n.headers,baseFetch:s}}class JR{constructor(e,t,r){this._toolListGeneration=0,this._toolListSuccessGeneration=0,this._toolListStateGeneration=0,this._callToolLock=Promise.resolve(),this._callToolQueueDepth=0,this._stateEnteredAtMs=Date.now(),this._terminatingSession=!1,this._closeRequested=!1,this.serverName=e,this.client=t,this.tools=new Yx,this.stateValue=r.initialState,this._authProvider=r.authProvider,this._authCodeExchange=r.authCodeExchange,this._sessionId=r.sessionId,this._protocolVersion=r.protocolVersion,this._resumedInstructions=r.resumedInstructions,this._sessionlessInitialize=r.sessionlessInitialize,this.config=r.config,this._oauthLifecycleLogger=r.oauthLifecycleLogger,this._serverSignals=r.serverSignals,this._redactLogText=r.redactLogText,this.setupElicitationHandler(),!0===r.stdioServer&&(t.onclose=()=>{this._closeRequested||(this.updateState({kind:"error",message:"MCP server exited"},"stdio_exited"),this.tools.invalidate())})}_stateKindLabel(e){return"requires_authentication"===e.kind?"needsAuth":e.kind}_logStateTransition(e,t,r,n){if(!this._oauthLifecycleLogger)return;const o=this._stateKindLabel(e),s=this._stateKindLabel(t);if(o===s)return;const i=Date.now()-this._stateEnteredAtMs,a=(()=>{try{const e=this.config&&"url"in this.config?this.config.url:void 0;return e?new URL(e).host:void 0}catch{return}})();CP({logger:this._oauthLifecycleLogger,event:"mcp_oauth_state_transition",metadata:{identifier:this.serverName,from:o,to:s,cause:r,serverUrlHost:a,previousStateDurationMs:i,...n}})}static createClient(e={}){const t={elicitation:{form:{}},...!1===e.mcpAppsUi?{}:{extensions:{"io.modelcontextprotocol/ui":{mimeTypes:["text/html;profile=mcp-app"]}}}};return new fR.K({name:"Cursor",version:"1.0.0"},{capabilities:t,jsonSchemaValidator:IR})}setupElicitationHandler(){this.client.setRequestHandler(Mx.$9,(async e=>{if(!this._currentElicitationProvider)return{action:"decline"};if(!("requestedSchema"in e.params))return{action:"decline"};try{const t=e.params.requestedSchema,r=await this._currentElicitationProvider.elicit({message:e.params.message,requestedSchema:t});return{action:r.action,content:r.content}}catch(e){return{action:"decline"}}}))}static async fromStreamableHttp(e,t,r,n,o,s,i,a,c,l,u,d=!1,h={}){const p=new URL(t.url);o=o??Pb;const f=await WR({serverName:e,config:t,tokenStorage:r,authRedirectUrl:o,fetchImpl:s,gtmMcpMatch:c,isScopePinGateEnabled:l,scopeChallengeStepUp:u}),m=f.tokens(),g=Xx(t.url,n),w=g.headers,y=d&&function(e){return Object.entries(e??{}).some((([e,t])=>"authorization"===e.toLowerCase()&&t.trim().length>0))}(w)?void 0:f,v=s??(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),b=void 0!==g.cursorAuthHeaderValue&&void 0!==g.cursorAuthOrigin&&void 0!==v?Qx((()=>g.cursorAuthHeaderValue),g.cursorAuthOrigin,v):v,S=e=>void 0===b||void 0===i?b:ZP({fetch:b,logger:i.logger,metadata:{...i.metadata,transportType:e},redactLogText:i.redactLogText});let k;const _=e=>{const r=f.scopeStepUp,n=e??v;return void 0===r||void 0===n?e:(o={fetch:n,scopeStepUp:r,serverUrl:t.url,startSignIn:async e=>{const t=void 0!==e.resourceMetadataUrl&&URL.canParse(e.resourceMetadataUrl)?new URL(e.resourceMetadataUrl):void 0;await(0,uR.j2)(f,{serverUrl:p.toString(),...void 0!==t?{resourceMetadataUrl:t}:{},...void 0!==b?{fetchFn:b}:{}});const r=f.lastRedirectUrl;k=void 0!==r&&void 0!==t?{redirectUrl:r,resourceMetadataUrl:t}:void 0}},async(e,t)=>{const r=await o.fetch(e,t);if(401!==r.status&&403!==r.status||!function(e){if("string"!=typeof e)return!1;let t;try{t=JSON.parse(e)}catch{return!1}return(Array.isArray(t)?t:[t]).some((e=>"object"==typeof e&&null!==e&&"method"in e&&"tools/call"===e.method))}(t?.body))return r;const n=await o.scopeStepUp.decide({status:r.status,wwwAuthenticate:r.headers.get("www-authenticate"),toolName:Rx(t?.body)});if(void 0===n)return r;if(o.onDecision?.(n),await(r.body?.cancel().catch((()=>{}))),"offer"===n.kind)try{await o.scopeStepUp.signIn((()=>o.startSignIn(n)))}catch(e){ux(o.scopeStepUp.accountKey).warn("MCP OAuth scope step-up: could not start the sign-in",{event:"mcp_oauth_scope_step_up_sign_in_failed",errorName:e instanceof Error?e.name:typeof e})}throw new Px(n,o.serverUrl,o.scopeStepUp.connectorName)});var o},C=JR.createClient(h),E=e=>e instanceof uR.D_||function(e){if(null===e||"object"!=typeof e)return!1;const t=e.name;if("string"==typeof t&&Tx.has(t))return!0;const r=e.errorCode;return!("string"!=typeof r||!Ax.has(r.toLowerCase()))||function(e){if(null===e||"object"!=typeof e)return!1;const t=e.name,r=e.errorCode;if("InvalidRequestError"!==t&&("string"!=typeof r||"invalid_request"!==r.toLowerCase()))return!1;const n=e.message;return"string"==typeof n&&$x.some((e=>e.test(n)))}(e)}(e)||Ix(e),x=async t=>{if(!f.hasClientInformation())throw new Error("OAuth client registration has not completed. The MCP server may not support dynamic client registration or the registration failed.");const r=void 0!==k&&k.redirectUrl===f.lastRedirectUrl?k.resourceMetadataUrl:void 0;await(0,uR.j2)(f,{serverUrl:p.toString(),authorizationCode:t,...void 0!==r?{resourceMetadataUrl:r}:{},...void 0!==b?{fetchFn:b}:{}}),a&&CP({logger:a,event:"mcp_oauth_callback_completion",metadata:{identifier:e,...nP(p.toString()),...XP(f.tokens(),{expiresInIsFresh:!0})}})},P=r=>{const n=f.lastRedirectUrl?.toString?.()??"",o=new JR(e,C,{oauthLifecycleLogger:a,redactLogText:i?.redactLogText,initialState:{kind:"requires_authentication",url:n,callback:async e=>{try{await x(e),o.updateState({kind:"ready"})}catch(e){const t=e instanceof Error?e.message:"Authentication failed";throw new Error(`Authentication callback failed: ${t}`)}}},authProvider:f,authCodeExchange:x,sessionId:r,config:t});return o},R=async r=>{const n=new dR.A(p,{authProvider:y,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...w??{}}},fetch:_(S("sse"))});try{return await C.connect(n),new JR(e,C,{initialState:{kind:"ready"},authProvider:f,authCodeExchange:x,config:t,oauthLifecycleLogger:a,redactLogText:i?.redactLogText})}catch(t){if(await n.close().catch((()=>{})),E(t))return a&&CP({logger:a,event:"mcp_oauth_state_transition",metadata:{identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"sse",refreshTokenPresent:Boolean(m?.refresh_token),...nP(p.toString()),...kP(t,i?.redactLogText)}}),P();if(void 0!==r&&QP(t)&&t instanceof dR._)throw function(e,t){let r=e;for(let e=0;e<8&&r instanceof Error&&r.cause instanceof Error;e++)r=r.cause;return r instanceof Error&&void 0===r.cause&&Reflect.defineProperty(r,"cause",{value:t,writable:!0,configurable:!0,enumerable:!1}),e}(r,t);throw t}};if("sse"===t.type)return R();const I=new pR.j(p,{authProvider:y,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...w??{}}},fetch:_(VR(S("streamableHttp"),p))});try{await C.connect(I);const r=function(e,t=Date.now){return qx(Hx(e),t)}(t.url)?void 0:function(e,r){const o=r.protocolVersion;if(void 0!==r.sessionId||void 0===o)return;const s=e.getServerCapabilities(),i=e.getServerVersion();if(void 0===s||void 0===i)return;const a=e.getInstructions();return{result:{protocolVersion:o,capabilities:s,serverInfo:i,...void 0===a?{}:{instructions:a}},credentialFingerprint:wR({url:t.url,headers:n,accessToken:f.tokens()?.access_token})}}(C,I);return new JR(e,C,{initialState:{kind:"ready"},authProvider:f,authCodeExchange:x,sessionId:I.sessionId,protocolVersion:I.protocolVersion,...void 0===r?{}:{sessionlessInitialize:r},config:t,oauthLifecycleLogger:a,redactLogText:i?.redactLogText})}catch(t){if(E(t))return a&&CP({logger:a,event:"mcp_oauth_state_transition",metadata:{identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"streamableHttp",refreshTokenPresent:Boolean(m?.refresh_token),...nP(p.toString()),...kP(t,i?.redactLogText)}}),P(I.sessionId);if(QP(t))return R(t);throw t}}static async fromStreamableHttpWithoutOAuth(e,t,r){const n=JR.createClient(),o=new pR.j(new URL(t.url),{requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...t.headers}},fetch:r});return await n.connect(o),new JR(e,n,{initialState:{kind:"ready"},sessionId:o.sessionId,protocolVersion:o.protocolVersion,config:t})}static async fromCachedSession(e,t,r,n,o,s=Pb,i,a,c,l,u){const d=new URL(t.url),h=await WR({serverName:e,config:t,tokenStorage:n,authRedirectUrl:s,fetchImpl:i,gtmMcpMatch:l,isScopePinGateEnabled:u}),{transportHeaders:p,baseFetch:f}=KR(t.url,o,i),m=new pR.j(d,{authProvider:h,sessionId:r.sessionId,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...p??{}}},fetch:void 0!==f&&void 0!==a?ZP({fetch:f,logger:a.logger,metadata:{...a.metadata,transportType:"streamableHttp"},redactLogText:a.redactLogText}):f});m.setProtocolVersion(r.protocolVersion);const g=function(e){return e._requestMessageId=(0,bo.randomInt)(1048576,2146435072),e}(JR.createClient());return await g.connect(m),new JR(e,g,{initialState:{kind:"ready"},authProvider:h,sessionId:m.sessionId,protocolVersion:r.protocolVersion,...void 0===r.instructions?{}:{resumedInstructions:r.instructions},config:t,oauthLifecycleLogger:c,redactLogText:a?.redactLogText})}static async fromSessionlessInitialize(e,t,r,n,o,s=Pb,i,a,c,l){const u=await WR({serverName:e,config:t,tokenStorage:n,authRedirectUrl:s,fetchImpl:i,gtmMcpMatch:a,isScopePinGateEnabled:c});if(wR({url:t.url,headers:o,accessToken:u.tokens()?.access_token})!==r.credentialFingerprint)return;const{transportHeaders:d,baseFetch:h}=KR(t.url,o,i),p=new pR.j(new URL(t.url),{authProvider:u,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...d??{}}},fetch:h}),f=JR.createClient();return await f.connect(new yR(p,r.result)),new JR(e,f,{initialState:{kind:"ready"},authProvider:u,sessionlessInitialize:r,config:t,redactLogText:l})}get sessionId(){return this._sessionId}get protocolVersion(){return this._protocolVersion}get sessionlessInitialize(){return this._sessionlessInitialize}get holdsOAuthAccessToken(){return Boolean(this._authProvider?.tokens()?.access_token)}async openStandaloneStream(){const e=this.client.transport;e instanceof pR.j&&await e.resumeStream("")}static async fromCommand(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{$R(s,(0,$.VI)(e.withName("McpSdkClient.fromCommand")),!1);const l=(c=o?.spawn,void 0!==c||"linux"!==process.platform?c:(e,t,r)=>(0,su.D9)(ou.spawn,e,t,r)),u=r.args??[],d=new hR.oQ({command:r.command,args:u,env:YP(cR({command:r.command,args:u,env:n})),cwd:r.cwd,stderr:"pipe",...l&&{spawn:l}}),h=function(e){const t=new TR;let r=null===e;return null!==e&&(e.on("data",(e=>{t.full||t.push(e)})),e.once("end",(()=>{t.end(),r=!0}))),{read:()=>bP(t.text.replace(/\s+/g," ").trim(),{maxLength:nx}),waitForFlush:async()=>{r||null===e||await new Promise((t=>{let r;const n=()=>{void 0!==r&&clearTimeout(r),e.off("end",n),t()};r=setTimeout(n,250),r.unref(),e.once("end",n)}))}}}(d.stderr),p=JR.createClient({mcpAppsUi:o?.mcpAppsUi}),f=o?.connectTimeoutMs??(void 0!==(a=r.startupTimeoutSec)&&Number.isFinite(a)&&a>0?Math.min(1e3*a,3e5):6e4);let m;d.onclose=()=>{var e;void 0!==m&&(e=m,HR.delete(e))};let g=0,w=!0;d.onerror=e=>{w&&function(e){return e instanceof SyntaxError||"ZodError"===e.name}(e)&&(g+=1)};const y=new AbortController,v=p.connect(d,{timeout:f,signal:y.signal});let b;m=d.pid??void 0,void 0!==m&&(i=m,HR.add(i),qR||(qR=!0,process.on("exit",zR)));const S=new Promise(((e,r)=>{b=setTimeout((()=>r(new Error(`MCP server connection timed out after ${f}ms: ${t}`))),f)}));try{await Promise.race([v,S])}catch(e){throw y.abort(),v.catch((()=>{})),await d.close().catch((()=>{})),await h.waitForFlush(),g>0&&e instanceof Error&&(e.message=`${e.message}; non-JSON-RPC output on stdout before initialize (${String(g)} line${1===g?"":"s"})`),function(e,t){if(""===t)return e;const r=e instanceof Error?e:new Error(String(e));return r.message=`${r.message}; stderr: ${t}`,AR.set(r,t),r}(e,h.read())}finally{w=!1,void 0!==b&&clearTimeout(b)}return new JR(t,p,{initialState:{kind:"ready"},config:r,stdioServer:void 0!==m,serverSignals:gR(d)})}catch(e){s.error=e,s.hasError=!0}finally{MR(s)}var i,a,c}terminateSessionOnClose(e){this._sessionTermination=e}setToolCallRequestOptions(e){this._toolCallRequestOptions=e}failToolCallInFlight(e){const t=this._toolCallInFlight;return void 0!==t&&!t.signal.aborted&&(t.abort(e),!0)}onServerSignal(e){return this._serverSignals?.subscribe(e)??(()=>{})}setToolCallOutputSchemaPassthrough(e){this._toolCallOutputSchemaPassthrough=e}async close(){if(this._closeRequested=!0,this._terminatingSession)return;const e=this._sessionTermination,t=this.client.transport;if(void 0!==e&&t instanceof pR.j)return this._terminatingSession=!0,void(async()=>{await async function(e,t){const r=await async function(e,t){if(void 0===e.sessionId)return{outcome:"no_session",durationMs:0};const r=Date.now(),n=e.terminateSession();n.catch((()=>{}));try{await(0,Or.wj)(n,t.timeoutMs)}catch(e){const t=Date.now()-r;return e instanceof Or.MU?{outcome:"timeout",durationMs:t}:e instanceof pR.b&&void 0!==e.code&&e.code>0?{outcome:"rejected",durationMs:t,httpStatus:e.code,error:e.message}:{outcome:"failed",durationMs:t,error:String(e)}}const o=t.deleteObserver?.lastDeleteStatus;return{outcome:405===o?"unsupported":"terminated",durationMs:Date.now()-r,...void 0!==o?{httpStatus:o}:{}}}(e,t);try{t.onResult?.(r)}catch{}return r}(t,e),await this.client.close()})().catch((()=>{}));await this.client.close()}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=$R(t,(0,$.VI)(e.withName("McpSdkClient.getTools")),!1);if(r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("mcp.transport",LR(this.config)),"requires_authentication"===this.stateValue.kind)return r.span.setAttribute("mcp.tools.requires_authentication",!0),[];if("error"===this.stateValue.kind)return[];const n=++this._toolListGeneration;let o=0,s=0;try{const e=await this.tools.get((async()=>{let e;const t=await lR({fetchPage:async t=>{o++;const n=await async function(e,t,r){try{const r=await e.listTools({cursor:t});return{tools:r.tools,nextCursor:r.nextCursor,meta:r._meta,...bR}}catch(c){if(!(c instanceof Error&&"issues"in c&&Array.isArray(c.issues)))throw c}const n=await e.request({method:"tools/list",params:{cursor:t}},vR),o=[];let s=0,i=0,a=0;for(const e of n.tools){let t=e;if(PR(e)){const r=e.inputSchema;ER(r)&&(t=xR(e,r),s++)}let n=Mx.Dn.safeParse(t);if(!n.success&&(c=n.error).issues.some((e=>"outputSchema"===e.path[0]))){const o=Mx.Dn.safeParse(CR(t));o.success&&(a++,r(SR(e),kR(n.error),"output_stripped"),n=o)}n.success?o.push(n.data):(i++,r(SR(e),_R(n.error.issues),"dropped"))}var c;return{tools:o,nextCursor:"string"==typeof n.nextCursor?n.nextCursor:void 0,meta:n._meta,typeFilled:s,toolDropped:i,outputStripped:a}}(this.client,t,((e,t,n)=>{(function(e,t,r){const n=JSON.stringify([e,t,r]);if(XR.has(n))return XR.delete(n),XR.add(n),!1;if(XR.add(n),XR.size>256){const e=XR.keys().next().value;void 0!==e&&XR.delete(e)}return!0})(n,this.serverName,e??"")&&DR.warn(r.ctx,"output_stripped"===n?"Removed an MCP tool output schema the client rejected":"Left out an MCP tool whose definition is invalid",{serverName:this.serverName,..."string"==typeof e?{toolName:e}:{},issues:t})}));return s+=n.typeFilled,QR(r.ctx,"type_filled",n.typeFilled),QR(r.ctx,"tool_dropped",n.toolDropped),QR(r.ctx,"output_stripped",n.outputStripped),e??=function(e){if(!jC(e))return;const t=e.mcpAllowlist;if(!jC(t)||"string"!=typeof t.list)return;const r=UC(t.name,200),n=UC(t.reason,200);if(void 0===r||void 0===n)return;const o={list:"local"===t.list||"cloud"===t.list?t.list:"other",name:r,reason:n},s=BC(t.allowedServerNames)??BC(t.allowedServers);void 0!==s&&(o.allowedServers=s);const i=BC(t.blockedServers);return void 0!==i&&(o.blockedServers=i),o}(n.meta),n},itemsOf:e=>e.tools,nextCursorOf:e=>e.nextCursor});return this._allowlistInUse=this.reportsCursorMcpAllowlist()?e:void 0,t.map((e=>({...e,inputSchema:XC(e.inputSchema),outputSchema:void 0===e.outputSchema?void 0:XC(e.outputSchema)})))}));return this.noteToolListSuccess(),r.span.setAttribute("mcp.tools.fetched",o>0),r.span.setAttribute("mcp.tools.pages",o),o>0&&r.span.setAttribute("mcp.tools.type_filled",s),r.span.setAttribute("mcp.tools.count",e.length),e}catch(e){const t=GR(e);if(r.span.setAttribute("mcp.tools.fetched",o>0),r.span.setAttribute("mcp.tools.pages",o),o>0&&r.span.setAttribute("mcp.tools.type_filled",s),this.noteToolListFailure(r.ctx,t,n),t instanceof uR.D_&&n===this._toolListGeneration&&n>this._toolListStateGeneration&&"ready"===this.stateValue.kind){const e=this.stateValue,r=this._authProvider?.lastRedirectUrl?.toString()??"";this.stateValue={kind:"requires_authentication",url:r,callback:e=>this.completeRuntimeAuthorization(e)},this.discardToolListError(),this._logStateTransition(e,this.stateValue,"runtime_unauthorized",{...kP(t,this._redactLogText)}),this._stateEnteredAtMs=Date.now()}throw t}}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async getAllowlistInUse(){return this._allowlistInUse}reportsCursorMcpAllowlist(){return void 0!==this.config&&"url"in this.config&&LC(this.config.url)}toolListAttemptIsCurrent(e){return e>this._toolListSuccessGeneration&&e>this._toolListStateGeneration}noteToolListSuccess(){this._toolListError=void 0,this._toolListSuccessGeneration=this._toolListGeneration}discardToolListError(){this._toolListError=void 0,this._toolListStateGeneration=this._toolListGeneration}noteToolListFailure(e,t,r){const n=Mx.O4.MethodNotFound;if(t instanceof Mx.Nh&&t.code===n&&void 0===this.client.getServerCapabilities()?.tools)return void this.noteToolListSuccess();if(t instanceof uR.D_||!this.toolListAttemptIsCurrent(r))return;const o=function(e){if(e instanceof Mx.Nh)return{descriptor:`McpError ${e.code}`,errorClass:"McpError",jsonRpcCode:e.code};if(e instanceof pR.b||e instanceof dR._){const t=e instanceof pR.b?"StreamableHTTPError":"SseError",r="number"==typeof e.code?e.code:void 0;return{descriptor:void 0===r?t:`${t} ${r}`,errorClass:t,...void 0===r?{}:{httpStatus:r}}}return e instanceof Error?{descriptor:"Error",errorClass:"Error"}:{descriptor:"unknown",errorClass:"unknown"}}(t);o.descriptor!==this._toolListError&&DR.warn(e,"MCP server failed to list its tools",{serverName:this.serverName,errorClass:o.errorClass,...void 0!==o.jsonRpcCode?{jsonRpcCode:o.jsonRpcCode}:{},...void 0!==o.httpStatus?{httpStatus:o.httpStatus}:{}}),this._toolListError=o.descriptor}async callTool(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{const a=$R(s,(0,$.VI)(e.withName("McpSdkClient.callTool")),!1);a.span.setAttribute("toolName",t),a.span.setAttribute("serverName",this.serverName),a.span.setAttribute("mcp.transport",LR(this.config));const c=this._callToolLock,l=this._callToolQueueDepth;let u;this._callToolQueueDepth++,this._callToolLock=new Promise((e=>{u=e}));try{{const e={stack:[],error:void 0,hasError:!1};try{const t=$R(e,(0,$.VI)(a.ctx.withName("McpSdkClient.callTool.lockWait")),!1);t.span.setAttribute("serverName",this.serverName),t.span.setAttribute("mcp.call_tool.queued_ahead",l);const r=performance.now();await c;const n=performance.now()-r;t.span.setAttribute("mcp.call_tool.lock_wait_ms",n),a.span.setAttribute("mcp.call_tool.lock_wait_ms",n),a.span.setAttribute("mcp.call_tool.queued_ahead",l)}catch(t){e.error=t,e.hasError=!0}finally{MR(e)}}if("requires_authentication"===this.stateValue.kind)throw new uR.D_(`MCP server "${this.serverName}" requires authentication`);this._currentToolCallId=n,this._currentToolName=t,this._currentElicitationProvider=o;const s=new AbortController;this._toolCallInFlight=s;const u=this._authProvider?.lastRedirectUrl;try{const n={stack:[],error:void 0,hasError:!1};try{const o=$R(n,(0,$.VI)(a.ctx.withName("McpSdkClient.callTool.sdk")),!1);o.span.setAttribute("toolName",t),o.span.setAttribute("serverName",this.serverName);const c=await this.sendToolCall({name:t,arguments:r},s.signal);return o.span.setAttribute("mcp.call_tool.is_error",!0===c.isError),FR(e,this.config,{isError:!0===c.isError}),{content:c.content,isError:!0===c.isError,structuredContent:(i=c.structuredContent,QC(i)),_meta:iE(c._meta)}}catch(e){n.error=e,n.hasError=!0}finally{MR(n)}}catch(t){const r=GR(t);r instanceof Px?(FR(e,this.config,{error:r,httpStatus:r.decision.status}),function(e,t){try{NR.increment(e,1,{decision:t.decision.kind,dropped:String(t.decision.dropped.length>0)})}catch{}}(e,r)):FR(e,this.config,{error:r});const n=r instanceof Px&&"offer"===r.decision.kind&&void 0!==this._authProvider?.lastRedirectUrl&&this._authProvider.lastRedirectUrl!==u;if((r instanceof uR.D_||n)&&"ready"===this.stateValue.kind){const e=this.stateValue,t=this._authProvider?.lastRedirectUrl?.toString()??"";this.stateValue={kind:"requires_authentication",url:t,callback:e=>this.completeRuntimeAuthorization(e)},this.discardToolListError(),this._logStateTransition(e,this.stateValue,n?"scope_step_up":"runtime_unauthorized",{...kP(r,this._redactLogText)}),this._stateEnteredAtMs=Date.now()}throw r}finally{this._toolCallInFlight=void 0,this._currentElicitationProvider=void 0,this._currentToolCallId=void 0,this._currentToolName=void 0}}finally{this._callToolQueueDepth--,c.then(u)}}catch(e){s.error=e,s.hasError=!0}finally{MR(s)}var i}sendToolCall(e,t){const r=this._toolCallRequestOptions?.(e.name),n={...r,signal:void 0===r?.signal?t:AbortSignal.any([r.signal,t])};return!0===this._toolCallOutputSchemaPassthrough?.()?this.client.request({method:"tools/call",params:e},Mx.TF,n):this.client.callTool(e,void 0,n)}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{if($R(t,(0,$.VI)(e.withName("McpSdkClient.getInstructions")),!1).span.setAttribute("serverName",this.serverName),"requires_authentication"===this.stateValue.kind)return;return this.client.getInstructions()??this._resumedInstructions}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{if($R(t,(0,$.VI)(e.withName("McpSdkClient.listResources")),!1),"requires_authentication"===this.stateValue.kind||"error"===this.stateValue.kind)return{resources:[]};const r=this.client.getServerCapabilities();return r?.resources?{resources:await lR({fetchPage:e=>this.client.listResources({cursor:e}),itemsOf:e=>e.resources,nextCursorOf:e=>e.nextCursor})}:{resources:[]}}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{return $R(r,(0,$.VI)(e.withName("McpSdkClient.readResource")),!1),"requires_authentication"===this.stateValue.kind?{contents:[]}:{contents:(await this.client.readResource({uri:t.uri})).contents}}catch(e){r.error=e,r.hasError=!0}finally{MR(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{return $R(t,(0,$.VI)(e.withName("McpSdkClient.listPrompts")),!1),"requires_authentication"===this.stateValue.kind||"error"===this.stateValue.kind?[]:(this.client.getServerCapabilities()??{prompts:!1}).prompts?(await lR({fetchPage:e=>this.client.listPrompts({cursor:e}),itemsOf:e=>e.prompts,nextCursorOf:e=>e.nextCursor})).map((e=>({name:e.name,description:e.description,arguments:e.arguments?.map((e=>({name:e.name,description:e.description,required:e.required})))}))):[]}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async getPrompt(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{return $R(n,(0,$.VI)(e.withName("McpSdkClient.getPrompt")),!1),"requires_authentication"===this.stateValue.kind?{messages:[]}:{messages:(await this.client.getPrompt({name:t,arguments:r})).messages.map((e=>({role:e.role,content:Array.isArray(e.content)?e.content.map((e=>"text"===e.type?{type:"text",text:e.text}:"image"===e.type?{type:"image",data:e.data,mimeType:e.mimeType}:{type:"text",text:JSON.stringify(e)})):[{type:"text",text:"string"==typeof e.content?e.content:JSON.stringify(e.content)}]})))}}catch(e){n.error=e,n.hasError=!0}finally{MR(n)}}getCurrentToolCallContext(){if(this._currentToolName)return{toolName:this._currentToolName,toolCallId:this._currentToolCallId}}async getState(e){return"ready"===this.stateValue.kind&&void 0!==this._toolListError?{kind:"ready",toolListError:this._toolListError}:this.stateValue}async completeRuntimeAuthorization(e){if(!this._authCodeExchange)throw new Error(`MCP server "${this.serverName}" cannot complete authorization: no code exchange is configured for this client.`);try{await this._authCodeExchange(e)}catch(e){const t=e instanceof Error?e.message:"Authentication failed";throw new Error(`Authentication callback failed: ${t}`)}this.updateState({kind:"ready"},"runtime_authorization_completed")}updateState(e,t){const r=this.stateValue;this.discardToolListError(),this.stateValue=e,this._logStateTransition(r,e,t??"explicit_update"),this._stateEnteredAtMs=Date.now()}}const ZR=(0,u.Pu)("mcp_tool.schema",{description:"One MCP tool definition a tools/list repair touched",labelNames:["outcome"]}),XR=new Set;function QR(e,t,r){if(0!==r)try{ZR.increment(e,r,{outcome:t})}catch{}}class YR extends Error{constructor(e,t){super(`MCP server ${e} not found, available servers: ${t.join(", ")}`),this.serverName=e,this.availableServers=t,this.name="McpServerNotFoundError"}}Error,Error;class eI{constructor(e){this.tools=e}async execute(e,t,r,n){const o=this.tools[e];if(!o)throw new vC(e,Object.keys(this.tools));return o.execute(t,r,n)}async executeOn(e,t,r,n,o){const s=this.tools[t];if(!s)throw new vC(t,Object.keys(this.tools));if(s.client===e)return s.execute(r,n,o)}getTools(){return Object.entries(this.tools).map((([e,t])=>({...t.definition,name:e})))}}class tI{async getClients(e){return{}}async getClient(e,t){}async getInstructions(e){return[]}async getToolSet(e){return new eI({})}async getTools(e){return[]}async getToolsForServers(e,t){return[]}}class rI{constructor(e){this.manager=e}async getClients(e){return this.manager.getClients()}async getClient(e,t){return this.manager.getClient(t)}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=$R(t,(0,$.VI)(e.withName("ManagerMcpLease.getInstructions")),!1);return await this.manager.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async getToolSet(e){const t={stack:[],error:void 0,hasError:!1};try{const r=$R(t,(0,$.VI)(e.withName("ManagerMcpLease.getToolSet")),!1);return await this.manager.getToolSet(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=$R(t,(0,$.VI)(e.withName("ManagerMcpLease.getTools")),!1);return(await this.getToolSet(r.ctx)).getTools()}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async getToolsForServers(e,t){const r=new Set(t);return(await this.getTools(e)).filter((e=>r.has(e.clientKey)))}onDidChange(e){return{dispose:this.manager.onDidChange((()=>e(void 0)))}}async reconcileSelection(e,t,r){for(const e of t.removed){const t=this.manager.getClient(e);this.manager.deleteClient(e);try{await(t?.close?.())}catch{}}for(const n of t.added){if(this.manager.getClient(n))continue;const t=await r(e,n);this.manager.setClient(n,t)}}}class nI{constructor(e,t){this.clients=e,this.elicitationFactory=t,this.changeListeners=new Set,this.warnedToolNameCollisions=new Set}onDidChange(e){return this.changeListeners.add(e),()=>{this.changeListeners.delete(e)}}fireDidChange(){for(const e of this.changeListeners)try{e()}catch(e){console.error("Error in McpManager change listener:",e)}}getClients(){return this.clients}getClient(e){return this.clients[e]}setClient(e,t){this.clients[e]=t,this.fireDidChange()}deleteClient(e){delete this.clients[e],this.fireDidChange()}setListingDeadline(e){this.listingDeadlineAt=void 0===e?void 0:performance.now()+e}async closeAllClients(){const e=Object.values(this.clients);await Promise.all(e.map((async e=>{try{await(e.close?.())}catch{}})))}async getToolSet(e){const t={stack:[],error:void 0,hasError:!1};try{const r=$R(t,(0,$.VI)(e.withName("McpManager.getToolSet")),!1),n=$R(t,oI(this.listingDeadlineAt),!1),o=await(0,Or.PH)(Object.entries(this.clients),(([e,t])=>n.within(t,r.ctx,(()=>t.getTools(r.ctx))).then((r=>(r??[]).map((r=>({...r,clientKey:e,clientName:t.serverName,client:t}))))).catch((()=>[]))),{max:n.concurrency}),s=Array.from(o.values()).flat(),i=new Map;for(const e of s){const t=`${e.clientName}-${e.name}`,r=i.get(t);void 0===r?i.set(t,[e]):r.push(e)}const a={};for(const[e,t]of i){const n=t[0];if(void 0===n)continue;if(t.some((e=>e.clientName!==n.clientName||e.name!==n.name))){if(!this.warnedToolNameCollisions.has(e)){this.warnedToolNameCollisions.add(e);const r=t.map((e=>`${e.clientName}/${e.name}`)).join(", ");console.warn("Colliding MCP tool name; exposing neither:",`${e} (${r})`)}continue}const o=t[t.length-1]?.clientKey,s=t.filter((e=>e.clientKey===o)),i=s[0]??n;s.length>1&&!this.warnedToolNameCollisions.has(e)&&(this.warnedToolNameCollisions.add(e),console.warn("MCP server lists a tool name more than once; using the first:",`${i.clientName}/${i.name}`)),a[e]={definition:{...i,clientKey:i.clientKey,providerIdentifier:i.clientName,toolName:i.name},client:i.client,execute:async(e,t,n)=>{const o=n?.createProvider(i.clientName,i.name,t);return await i.client.callTool(r.ctx,i.name,e,t,o)}}}return new eI(a)}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=$R(t,(0,$.VI)(e.withName("McpManager.getInstructions")),!1),n=$R(t,oI(this.listingDeadlineAt),!1),o=await(0,Or.PH)(Object.entries(this.clients),(([e,t])=>n.within(t,r.ctx,(()=>t.getInstructions(r.ctx))).then((e=>e&&0!==e.trim().length?new wn.I0({serverName:t.serverName,instructions:e.trim()}):null)).catch((()=>null))),{max:n.concurrency});return Array.from(o.values()).filter((e=>null!==e))}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}}function oI(e){if(void 0===e)return{concurrency:4,within:(e,t,r)=>r(),[Symbol.dispose]:()=>{}};let t;const r=new Promise((r=>{t=setTimeout((()=>r(void 0)),Math.max(0,e-performance.now()))}));return{concurrency:Number.POSITIVE_INFINITY,within:async(t,n,o)=>{const s=await Promise.race([t.getState(n).catch((()=>{})),r]);if("ready"!==s?.kind)return Promise.race([o(),r]);let i;try{return await Promise.race([o(),new Promise((t=>{i=setTimeout((()=>t(void 0)),Math.max(2e3,e-performance.now()))}))])}finally{clearTimeout(i)}},[Symbol.dispose]:()=>clearTimeout(t)}}function sI(e,t){return function(e){const{logger:t,ctx:r}=e;return{debug:(e,n)=>t.debug(r,e,n),info:(e,n)=>t.info(r,e,n),warn:(e,n)=>t.warn(r,e,n),error:(e,n,o)=>t.error(r,e,n,o)}}({ctx:e,logger:t})}Error;class iI{constructor(e){this.options=e,CP({logger:e.logger,event:"mcp_oauth_provider_initialized",metadata:this.baseMetadata})}get baseMetadata(){return{identifier:this.options.identifier,...this.options.serverUrl?{serverUrl:nP(this.options.serverUrl)}:{}}}async loadTokens(){const e=await this.options.inner.loadTokens();return CP({logger:this.options.logger,event:"mcp_oauth_tokens_loaded",level:"debug",metadata:{...this.baseMetadata,...XP(e)}}),e}async saveTokens(e){await this.options.inner.saveTokens(e),CP({logger:this.options.logger,event:"mcp_oauth_tokens_saved",metadata:{...this.baseMetadata,...XP(e,{expiresInIsFresh:!0})}})}async prepareForRefresh(){CP({logger:this.options.logger,event:"mcp_oauth_refresh_prepare",metadata:this.baseMetadata}),await(this.options.inner.prepareForRefresh?.())}async releaseRefreshLeaseOnError(e){CP({logger:this.options.logger,event:"mcp_oauth_refresh_error_release",level:"warn",error:e,metadata:{...this.baseMetadata,...kP(e,this.options.redactLogText)}}),await(this.options.inner.releaseRefreshLeaseOnError?.(e))}async loadClientInformation(){const e=await this.options.inner.loadClientInformation();return CP({logger:this.options.logger,event:"mcp_oauth_client_info_loaded",level:"debug",metadata:{...this.baseMetadata,...iP(e)}}),e}async saveClientInformation(e){await this.options.inner.saveClientInformation(e),CP({logger:this.options.logger,event:"mcp_oauth_client_info_saved",metadata:{...this.baseMetadata,...iP(e)}})}async invalidateCredentials(e){void 0!==this.options.inner.invalidateCredentials&&(CP({logger:this.options.logger,event:"mcp_oauth_credentials_invalidated",level:"warn",metadata:{...this.baseMetadata,scope:e}}),await this.options.inner.invalidateCredentials(e))}tokenEndpointAuth(e){return this.options.inner.tokenEndpointAuth?.(e)}get loadScopeStepUpRecord(){return this.options.inner.loadScopeStepUpRecord?.bind(this.options.inner)}get saveScopeStepUpRecord(){return this.options.inner.saveScopeStepUpRecord?.bind(this.options.inner)}}class aI{constructor(e,t){this.storage=e,this.identifier=t}async loadTokens(){return this.storage.loadTokens(this.identifier)}async saveTokens(e){return this.storage.saveTokens(this.identifier,e)}async loadClientInformation(){return this.storage.loadClientInformation(this.identifier)}async saveClientInformation(e){return this.storage.saveClientInformation(this.identifier,e)}get loadScopeStepUpRecord(){const{storage:e,identifier:t}=this;return void 0===e.loadScopeStepUpRecord?void 0:()=>e.loadScopeStepUpRecord(t)}get saveScopeStepUpRecord(){const{storage:e,identifier:t}=this;return void 0===e.saveScopeStepUpRecord?void 0:r=>e.saveScopeStepUpRecord(t,r)}}class cI{constructor(e){this.inner=e}async loadTokens(){}async loadClientInformation(){}async saveTokens(e){return this.inner.saveTokens(e)}async saveClientInformation(e){return this.inner.saveClientInformation(e)}async invalidateCredentials(e){await(this.inner.invalidateCredentials?.(e))}get loadScopeStepUpRecord(){return this.inner.loadScopeStepUpRecord?.bind(this.inner)}get saveScopeStepUpRecord(){return this.inner.saveScopeStepUpRecord?.bind(this.inner)}async loadGrantedScope(){return void 0!==this.inner.loadGrantedScope?this.inner.loadGrantedScope():(await this.inner.loadTokens())?.scope}}var lI=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},uI=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const dI=(0,l.h)("DefinitionMcpLoader"),hI=(0,u.Pu)("connector_policy.blocked",{description:"MCP servers a team or org policy refused to load, once per loader and server.",labelNames:["surface","stage","reason"]});function pI(e){const{filePath:t,baseDir:r}=e;return"~"===t||t.startsWith("~/")?s.default.join(o.default.homedir(),t.slice(1)):t.startsWith("./")||"."===t?s.default.resolve(r??process.cwd(),t):t}function fI(e){return"getManagedSlackWorkspaceLists"in e&&"function"==typeof e.getManagedSlackWorkspaceLists}function mI(e){return"getMcpNetworkControlsConfig"in e&&"function"==typeof e.getMcpNetworkControlsConfig}function gI(e){return e?.length??0}function wI(e){if(void 0!==e)return(0,bo.createHash)("sha256").update(TE(e)).digest("hex")}function yI(e){if(void 0===e)return;let t;return r=>(void 0===t&&(t=e(),queueMicrotask((()=>{t=void 0}))),t?QE(r):r)}async function vI(e,t,n,o,s={middlewares:[],configPath:""},i,a,c={},l={}){const u={stack:[],error:void 0,hasError:!1};try{const{middlewares:d,configPath:h}=s,p=lI(u,(0,$.VI)(e.withName("mcp-agent-exec.loadServer")),!1);p.span.setAttribute("serverName",t);const f=!1!==l.mcpAppsUi;p.span.setAttribute("mcpAppsUi",f),dI.info(p.ctx,`Loading MCP server "${t}" ${f?"declaring":"without declaring"} the MCP Apps UI extension`,{event:"mcp_apps_ui_capability",serverName:t,mcpAppsUi:f,transport:"command"in n?"stdio":"http"});let m=async(e,n)=>{const s={stack:[],error:void 0,hasError:!1};try{const u=lI(s,(0,$.VI)(e.withName("loadServer.next")),!1);u.span.setAttribute("serverName",t);const h=u.ctx;if("command"in n){u.span.setAttribute("kind","command");const e=d.find(mI);return await async function(e,t,n,o,s={}){const i=n.cwd?pI({filePath:n.cwd}):void 0;let a,c;if(n.args&&n.args.length>0)a=pI({filePath:n.command,baseDir:i}),c=n.args.map((e=>pI({filePath:e,baseDir:i})));else{const e=(0,YE.A)(n.command);a=pI({filePath:e[0],baseDir:i}),c=e.slice(1).map((e=>pI({filePath:e,baseDir:i})))}const l=n.env??{},{startupTimeoutSec:u}=n,d=await(o?.getMcpNetworkControlsConfig?.({command:[n.command,...n.args??[]].join(" ")})),h=(0,Ob.$H)(d);if(void 0!==h){const{buildMcpSandboxPolicy:n}=await r.e(449).then(r.bind(r,"../mcp-agent-exec/dist/mcp-sandbox-policy.js")),{SandboxUnsupportedError:o,spawnInSandbox:p}=await Promise.resolve().then(r.bind(r,"../shell-exec/dist/api/index.js")),f=i??process.cwd(),m=await n(h,f);dI.info(e,function(e){return`Sandboxing local MCP server "${e.serverName}" with network controls: networkControlsEnabled=${String(!0===e.networkControlsConfig?.enabled)}, mcpNetworkMode=${e.networkControlsConfig?.mcpNetworkMode??"unset"}, mcpNetworkAllowlistCount=${gI(e.networkControlsConfig?.mcpNetworkAllowlist)}, mcpNetworkDenylistCount=${gI(e.networkControlsConfig?.mcpNetworkDenylist)}, localAgentNetworkAllowlistCount=${gI(e.networkControlsConfig?.localAgentNetworkAllowlist)}, sandboxPolicyHash=${wI(e.sandboxNetworkControlsConfig)??"none"}`}({serverName:t,networkControlsConfig:d,sandboxNetworkControlsConfig:h}),function(e){return{event:"mcp_stdio_sandbox_policy",serverName:e.serverName,networkControlsEnabled:!0===e.networkControlsConfig?.enabled,mcpNetworkMode:e.networkControlsConfig?.mcpNetworkMode,mcpNetworkAllowlistCount:gI(e.networkControlsConfig?.mcpNetworkAllowlist),mcpNetworkDenylistCount:gI(e.networkControlsConfig?.mcpNetworkDenylist),localAgentNetworkAllowlistCount:gI(e.networkControlsConfig?.localAgentNetworkAllowlist),sandboxPolicyHash:wI(e.sandboxNetworkControlsConfig)}}({serverName:t,networkControlsConfig:d,sandboxNetworkControlsConfig:h}));try{return await JR.fromCommand(e,t,{command:a,args:c,cwd:i,startupTimeoutSec:u},l,{...s,spawn:(e,t,r)=>p(e,t,r,m)})}catch(e){if(e instanceof o)throw new AE(t,e);throw e}}return!0===d?.enabled&&"no_sandbox"===d.mcpNetworkMode&&(!0===d.win32UserExtensionUnsandbox?dI.info(e,`Starting local MCP server "${t}" without MCP sandboxing`,{event:"mcp_stdio_win32_user_extension_unsandbox",serverName:t}):dI.info(e,`Starting local MCP server "${t}" without MCP sandboxing`)),JR.fromCommand(e,t,{command:a,args:c,cwd:i,startupTimeoutSec:u},l,s)}(h,t,n,e,l)}if("url"in n){u.span.setAttribute("kind","url");const e=i?.(t);return await async function(e,t,r,n,o,s,i,a,c={}){const l=sI(e,dI),u=function(e,t,r){return{logger:{debug:(t,r)=>dI.debug(e,t,r),info:(t,r)=>dI.info(e,t,r),warn:(t,r)=>dI.warn(e,t,r),error:(t,r,n)=>dI.error(e,t,r,n)},metadata:{identifier:t,source:"mcp-agent-exec"},redactLogText:yI(r)}}(e,t,a),d=void 0!==s&&OE(r.url)?FE(globalThis.fetch.bind(globalThis),{managedSlackWorkspaceLists:()=>s.getManagedSlackWorkspaceLists()}):void 0;return JR.fromStreamableHttp(t,r,n,r.headers,o,d,u,l,void 0,void 0,i,!1,c)}(h,t,n,o,e,d.find(fI),a,c.isLinkSharedPaymentTokenLogRedactionEnabled,l)}throw new Error(`Invalid server: ${JSON.stringify(n)}`)}catch(e){s.error=e,s.hasError=!0}finally{uI(s)}};for(const e of d){const r=m;m=async(n,o)=>await e.load(n,t,o,h,r)}try{return await m(p.ctx,n)}catch(e){throw function(e,t){if(void 0===t)return e;!function(e,t){if("object"!=typeof e||null===e)return;const r=AR.get(e);void 0!==r&&AR.set(e,t(r))}(e,t);const r=function(e,t){if(void 0===t)return e;const r={results:new Map,cycled:new Set},n=NE(e,t,r),o=new Map([...r.cycled].flatMap((e=>{const t=r.results.get(e);return t===e?[]:[[e,t]]})));return o.size>0&&function(e,t){const r=new Set,n=[e];for(let e=0;n.length>0&&e({identifier:e,serverConfig:t,configPath:this.configPath})))}}class SI{constructor(e,t,r=[],n={}){this.source=e,this.tokenStorage=t,this.middlewares=r,this.options=n,this.clientCache=new Map}async load(e,t=!0){const r={stack:[],error:void 0,hasError:!1};try{lI(r,(0,$.VI)(e.withName("DefinitionMcpLoader.load")),!1),t||(await this.closeAllCachedClients(),this.source.clearCache?.());const n=await this.source.getDefinitions(e,t);await this.evictClientsOnSandboxPolicyChange(e,n);const o={};return await(0,Or.PH)([...n],(async r=>{try{const n=t?this.clientCache.get(r.identifier):void 0,s=n??await this.loadDefinitionClient(e,r);n||this.clientCache.set(r.identifier,s),o[r.identifier]=s}catch(t){if(this.handleDefinitionLoadError(e,r,t))return;!function(e,t,r,n){const o=yI(n)??(e=>e),s=function(e){if("object"==typeof e&&null!==e)return AR.get(e)}(r);dI.warn(e,"Failed to load MCP server",{identifier:t.identifier,source:t.source,configPath:t.configPath,metadata:t.metadata,errorMessage:o(r instanceof Error?r.message:String(r)),stderrTail:void 0===s?void 0:o(s)})}(e,r,t,this.options.isLinkSharedPaymentTokenLogRedactionEnabled)}}),{max:this.options.maxConcurrency??Math.max(n.length,1)}),new nI(o,this.options.elicitationFactory)}catch(e){r.error=e,r.hasError=!0}finally{uI(r)}}clearClient(e){this.clientCache.delete(e)}clearAllMcpCaches(){this.clientCache.clear()}async evictClientsOnSandboxPolicyChange(e,t){const r=this.middlewares.find(mI);if(!r)return;let n;try{n=JSON.stringify(await Promise.all([...t].sort(((e,t)=>e.identifier.localeCompare(t.identifier))).map((async e=>{const t=await(r.getMcpNetworkControlsConfig?.((n=e.serverConfig,"url"in n?{url:n.url}:{command:[n.command,...n.args??[]].join(" ")})))??{};var n;return[e.identifier,TE(t)]}))))}catch{return}const o=this.sandboxPolicyFingerprint;this.sandboxPolicyFingerprint=n,void 0!==o&&o!==n&&(dI.info(e,"MCP network-controls policy changed; reloading MCP clients to apply the new egress policy"),await this.closeAllCachedClients())}async closeAllCachedClients(){const e=[...this.clientCache.values()];this.clientCache.clear(),await(0,Or.PH)(e,(async e=>{try{await(e.close?.())}catch{}}),{max:Math.max(e.length,1)})}async loadClient(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{lI(n,(0,$.VI)(e.withName("DefinitionMcpLoader.loadClient")),!1);const o=await this.source.getDefinitions(e);if(await this.evictClientsOnSandboxPolicyChange(e,o),!r){const e=this.clientCache.get(t);if(e)return e}const s=o.find((e=>e.identifier===t));if(!s)throw new Error(`MCP server "${t}" not found in config`);let i;try{i=await this.loadDefinitionClient(e,s,r)}catch(t){throw this.handleDefinitionLoadError(e,s,t),t}return r||this.clientCache.set(t,i),i}catch(e){n.error=e,n.hasError=!0}finally{uI(n)}}async loadDefinitionClient(e,t,r){const n=t.authStorageKey??t.identifier,o=new aI(this.tokenStorage,n),s=sI(e,dI),i=new iI({inner:o,logger:s,redactLogText:yI(this.options.isLinkSharedPaymentTokenLogRedactionEnabled),identifier:n,serverUrl:"url"in t.serverConfig?t.serverConfig.url:void 0}),a=r?new cI(i):i;return vI(e,t.identifier,t.serverConfig,a,{middlewares:this.middlewares,configPath:t.configPath??""},this.options.authRedirectUrlGenerator,this.options.scopeChallengeStepUp,{isLinkSharedPaymentTokenLogRedactionEnabled:this.options.isLinkSharedPaymentTokenLogRedactionEnabled})}handleDefinitionLoadError(e,t,r){let n=!1;try{n="handled"===this.options.onDefinitionLoadError?.(e,t,r)}catch(r){dI.warn(e,"MCP definition load error hook failed",{identifier:t.identifier,source:t.source,configPath:t.configPath,metadata:t.metadata,errorMessage:r instanceof Error?r.message:String(r)})}return n||function(e){return e instanceof RC||e instanceof IC||e instanceof TC||e instanceof kI}(r)}}class kI extends Error{constructor(e,t,r){super(r??("teamNetworkAllowlist"===t?`MCP server "${e}" is not on the team network allowlist`:`MCP server "${e}" is blocked by team policy`)),this.serverName=e,this.reason=t,this.name="McpServerBlockedError"}}const _I=[1e3,3e3];class CI{constructor(e){this.blockingService=e,this.countedPolicyBlocks=new Set}async getMcpNetworkControlsConfig(e){return await(this.blockingService.getMcpNetworkControlsConfig?.(e))??{}}async getManagedSlackWorkspaceLists(){return await(this.blockingService.getManagedSlackWorkspaceLists?.())??[]}async load(e,t,r,n,o){const s=function(e){return{command:"command"in e?[e.command,...e.args??[]].join(" "):void 0,url:"url"in e?e.url:void 0}}(r),i=await(this.blockingService.getMcpServerBlockInfo?.(s))??{blocked:await this.blockingService.isServerBlocked(s)};if(i.blocked){const r=i.reason??"teamPolicy";throw"teamPolicy"!==r||this.countedPolicyBlocks.has(t)||(this.countedPolicyBlocks.add(t),hI.increment(e,1,{surface:"desktop",stage:"tool_call",reason:"server_not_allowed"})),new kI(t,r,i.message)}for(let n=0;;n++)try{const t=await o(e,r);return!0===i.hostMcpBridge&&this.blockingService.recordHostMcpBridgeClient?.(t),this.blockingService.recordMcpServerClient?.(t,s),t}catch(e){if(e instanceof ME)throw new kI(t,"teamPolicy",e.message);const r=e instanceof DE?_I[n]:void 0;if(void 0===r)throw e;await(0,Or.cb)(r)}}}class EI extends SI{constructor(e,t,r=[],n={}){super(new bI(e),t,r,n),this.configPath=e}static init(e,t,r=[]){return new EI(t,e,r)}}function xI(e){return"stdio"===e.type&&e.command?{command:e.command,args:e.args??[],env:e.env,cwd:e.cwd}:"streamableHttp"===e.type&&e.url?{url:e.url,headers:e.headers,auth:e.auth,...void 0!==e.tls?{tls:e.tls}:{},...void 0!==e.placement?{placement:e.placement}:{}}:void 0}var PI=r("../utils/dist/private-file.js"),RI=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js");function II(e){const t=RI.VE.safeParse(e);return t.success?t.data:void 0}function TI(e){const t=RI.H5.safeParse(e);return t.success?t.data:void 0}class AI{constructor(e){this.mcpAuthPath=e;const t=AI.mcpAuthPromises.get(e);if(t)this.mcpAuthPromise=t;else{const t=this.loadMcpAuth();this.mcpAuthPromise=t,AI.mcpAuthPromises.set(e,t),t.catch((()=>{AI.mcpAuthPromises.get(e)===t&&AI.mcpAuthPromises.delete(e)}))}AI.saveLocks.has(e)||AI.saveLocks.set(e,Promise.resolve())}async loadMcpAuth(){try{await(0,PI.rV)(this.mcpAuthPath);const e=await(0,Co.readFile)(this.mcpAuthPath,"utf8"),t=JSON.parse(e);if(t&&"object"==typeof t){if(Object.values(t).some((e=>e&&"object"==typeof e&&null!==e&&("access_token"in e||"refresh_token"in e)&&!("tokens"in e)&&!("clientInfo"in e)))){const e={};for(const[r,n]of Object.entries(t)){const t=II(n);void 0!==t&&(e[r]={tokens:t})}return e}const e={};for(const[r,n]of Object.entries(t))n&&"object"==typeof n&&null!==n&&(e[r]={tokens:"tokens"in n?II(n.tokens):void 0,clientInfo:"clientInfo"in n?TI(n.clientInfo):void 0,..."scopeStepUp"in n?{scopeStepUp:n.scopeStepUp}:{}});return e}return{}}catch(e){if(e instanceof Error&&e.message.includes("ENOENT"))return{};throw e}}async loadTokens(e){const t=await this.mcpAuthPromise;return t[e]?.tokens}async saveTokens(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),r[e].tokens=t,await this.saveMcpAuth(r)}))}async loadClientInformation(e){const t=await this.mcpAuthPromise;return t[e]?.clientInfo}async withSaveLock(e){const t=AI.saveLocks.get(this.mcpAuthPath)??Promise.resolve();let r;AI.saveLocks.set(this.mcpAuthPath,new Promise((e=>{r=e})));try{return await t,await e()}finally{r()}}async saveClientInformation(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),r[e].clientInfo=t,await this.saveMcpAuth(r)}))}async loadScopeStepUpRecord(e){const t=await this.mcpAuthPromise;return t[e]?.scopeStepUp}async saveScopeStepUpRecord(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),void 0===t?delete r[e].scopeStepUp:r[e].scopeStepUp=t,await this.saveMcpAuth(r)}))}async deleteCredentials(e){await this.withSaveLock((async()=>{const t=await this.mcpAuthPromise;e in t&&(delete t[e],await this.saveMcpAuth(t))}))}async saveMcpAuth(e){await(0,PI.Pl)(this.mcpAuthPath,JSON.stringify(e,null,2))}}AI.mcpAuthPromises=new Map,AI.saveLocks=new Map,(0,y.cF)(Symbol("execHookConversationId"),void 0),(0,y.cF)(Symbol("execHookGenerationId"),void 0),(0,y.cF)(Symbol("execHookModel"),void 0);const $I=(0,y.cF)(Symbol("execHookWorkspaceRoots"),void 0);var MI=r("../proto/dist/generated/agent/v1/write_exec_pb.js"),DI=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},OI=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const FI=(0,u.Pu)("mcp.filesystem.divergence",{description:"Divergence detected between MCP lease state and filesystem state",labelNames:["divergence_type","mcp_source","configured_servers","mcp_version"]}),NI=(0,u.Pu)("mcp.filesystem.sync_check",{description:"MCP filesystem sync check executed",labelNames:["synced","mcp_source","configured_servers","mcp_version"]}),LI=(0,u.wt)("mcp.filesystem.sync_check.expected_servers",{description:"Number of expected MCP servers at last sync check",labelNames:["mcp_source","mcp_version"]}),jI=(0,u.wt)("mcp.filesystem.sync_check.actual_servers",{description:"Number of actual MCP servers on disk at last sync check",labelNames:["mcp_source","mcp_version"]}),UI=(0,u.wt)("mcp.filesystem.sync_check.servers_missing",{description:"Number of expected MCP servers missing from disk at last sync check",labelNames:["mcp_source","mcp_version"]}),BI=(0,u.wt)("mcp.filesystem.sync_check.tool_mismatches",{description:"Number of MCP servers with tool count mismatches at last sync check",labelNames:["mcp_source","mcp_version"]}),WI=(0,l.h)("McpFileSystemWriter"),HI="mcpFsStructuredLogOptIn";function qI(e,t){return t?.includeStructuredLogs?{...e??{},[HI]:!0}:e}const zI={debug(e,t,r,n){WI.debug(e,t,qI(r,n))},info(e,t,r,n){WI.info(e,t,qI(r,n))},warn(e,t,r,n){WI.warn(e,t,qI(r,n))},error(e,t,r,n,o){WI.error(e,t,r,qI(n,o))}},GI="mcps",VI="tools",KI="~staging",JI="~prev",ZI=[25,50,100,200],XI=new Set(["EPERM","EBUSY","EACCES"]),QI=new Map;function YI(e){return e.slice(0,e.indexOf("~"))}function eT(e,t){return`${e}~${Date.now()}-${process.pid}-${(0,bo.randomBytes)(4).toString("hex")}${t}`}const tT=/~(\d+)-\d+-[0-9a-f]+~(?:staging|prev)$/;async function rT(e,t){const r=tT.exec(t),n=r?Number(r[1]):0;try{const{mtimeMs:r}=await(0,Co.stat)((0,s.join)(e,t));return Date.now()-Math.max(n,r)>6e4}catch{return!1}}const nT="mcp_auth",oT="Authenticate this MCP server so its tools can be used. Call this tool through your MCP tool-calling interface when STATUS.md indicates this server needs authentication.",sT="# >>> CURSOR MANAGED BLOCK >>>",iT="# <<< CURSOR MANAGED BLOCK <<<",aT=["# Ignore everything in .cursor","*","# Un-ignore projects so we can descend to allowlisted subdirs","!projects/","projects/*","!projects/*/","projects/*/*","# MCP tool descriptors, resources, prompts","!projects/*/mcps/","!projects/*/mcps/**","# Agent transcripts for citation","!projects/*/agent-transcripts/","!projects/*/agent-transcripts/**","# Terminal output files","!projects/*/terminals/","!projects/*/terminals/**","# Conversation notes (shared scratchpad)","!projects/*/agent-notes/","!projects/*/agent-notes/**","# Large tool output files","!projects/*/agent-tools/","!projects/*/agent-tools/**","# Plugin cache (rules, skills, agents)","!plugins/","!plugins/**","# Built-in Cursor skills","!skills-cursor/","!skills-cursor/**","# User's personal skills","!skills/","!skills/**","# User's personal slash commands","!commands/","!commands/**","# User's plan files","!plans/","!plans/**","# Subagent state/transcripts","!subagents/","!subagents/**","# User-level cursor rules","!rules/","!rules/**"].join("\n");function cT(e,t,r=15e3){let n;return Promise.race([e.catch((()=>t)),new Promise((e=>{n=setTimeout((()=>e(t)),r)}))]).finally((()=>clearTimeout(n)))}function lT(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function uT(e){if(void 0===e)return;const t=e.trim();return t.length>0?t:void 0}function dT(e){switch(e.kind){case"loading":return"initializing";case"requires_authentication":return"needsAuth";case"ready":return"connected";case"error":return"error";default:return"disconnected"}}function hT(e){if(Array.isArray(e))return e.map((e=>hT(e)));if(function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e)){const t=Object.entries(e).filter((([,e])=>void 0!==e)).sort((([e],[t])=>et?1:0)).map((([e,t])=>[e,hT(t)]));return Object.fromEntries(t)}return e}function pT(e){return JSON.stringify(hT(e))}function fT(e){const t=e.map((e=>({value:e,key:pT(e)})));return t.sort(((e,t)=>e.keyt.key?1:0)),t.map((e=>e.value))}function mT(e){const t=fT(e.tools.map((e=>({name:e.toolName,description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema})))),r=fT(e.resources.map((e=>({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType})))),n=fT(e.prompts.map((e=>({name:e.name,description:e.description,arguments:e.arguments}))));return pT({id:e.serverIdentifier,name:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,tools:t,resources:r,prompts:n,instructions:e.instructions,status:e.status})}class gT{constructor(e,t,r){this.cachedFingerprints=new Map,this.disposed=!1,this.hasPendingLeaseChangeEvent=!1,this.lastDivergenceCheckMs=0,this.mcpLease=e,this.projectDir=t,this.debounceMs=r?.debounceMs??100,this.mcpAuthCopyOverrides=r?.mcpAuthCopyOverrides,this.exposeVirtualMcpAuthTool=r?.exposeVirtualMcpAuthTool??!0,this.alwaysExposeVirtualMcpAuthTool=r?.alwaysExposeVirtualMcpAuthTool??!1,this.snapshotProvider=r?.snapshotProvider,this.mcpVersion=r?.mcpVersion??(this.snapshotProvider?"snapshots":"v1"),this.onDidWrite=r?.onDidWrite,this.ctx=this.getContext(r?.loggerBackend),this.startupCleanupPromise=this.cleanupStaleStagingDirs(this.ctx),this.leaseChangeDisposable=this.mcpLease.onDidChange((e=>{zI.info(this.ctx,"Lease change event received",{serverIdentifiers:e?.serverIdentifiers,reason:e?.reason}),this.onLeaseChanged(this.ctx,e)})),zI.info(this.ctx,"Constructor: scheduling initial write"),this.scheduleWrite(this.ctx),this.ensureCursorDirGitignore()}ensureCursorDirGitignore(){(async function(e){const t=(0,s.join)(e,".gitignore"),r=`${sT}\n${aT}\n${iT}\n`;let n;await(0,Co.mkdir)(e,{recursive:!0});try{n=await(0,Co.readFile)(t,"utf-8")}catch(e){if("ENOENT"!==Sc(e))throw e}if(void 0===n)return void await(0,Co.writeFile)(t,r);const o=n.indexOf(sT),i=n.indexOf(iT,o+30);if(-1===o||-1===i)await(0,Co.writeFile)(t,r);else{const e=`${n.slice(0,o)}${r}${n.slice(i+30).replace(/^\n/,"")}`;e!==n&&await(0,Co.writeFile)(t,e)}})((0,s.join)((0,o.homedir)(),".cursor")).catch((e=>{zI.warn(this.ctx,"Failed to ensure ~/.cursor/.gitignore",e)}))}async cleanupStaleStagingDirs(e){const t=this.getLogContext(e),r=(0,s.join)(this.projectDir,GI);try{const e=await(0,Co.readdir)(r);await Promise.allSettled(e.filter((e=>e.endsWith(KI))).map((async e=>{await rT(r,e)&&await(0,Co.rm)((0,s.join)(r,e),{recursive:!0,force:!0})})))}catch(e){"ENOENT"!==Sc(e)&&zI.error(t,"Error clearing stale mcps staging dirs",e)}}onLeaseChanged(e,t){if(this.disposed)return;const r=t??{serverIdentifiers:void 0};this.hasPendingLeaseChangeEvent?this.pendingLeaseChangeEvent=function(...e){const[t,r]=e;return e.length<2?t:Qn(r)?{serverIdentifiers:void 0,reason:t?.reason??r?.reason}:void 0===t?r:Qn(t)?{serverIdentifiers:void 0,reason:t.reason??r?.reason}:{serverIdentifiers:[...new Set([...t.serverIdentifiers??[],...r?.serverIdentifiers??[]])],reason:t.reason??r?.reason}}(this.pendingLeaseChangeEvent??{serverIdentifiers:void 0},r):(this.pendingLeaseChangeEvent=r,this.hasPendingLeaseChangeEvent=!0),void 0!==this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout((()=>{this.debounceTimer=void 0;const t=this.takePendingLeaseChangeEvent();this.scheduleWrite(e,t)}),this.debounceMs)}takePendingLeaseChangeEvent(){if(!this.hasPendingLeaseChangeEvent)return;const e=this.pendingLeaseChangeEvent??{serverIdentifiers:void 0};return this.pendingLeaseChangeEvent=void 0,this.hasPendingLeaseChangeEvent=!1,e}scheduleWrite(e,t){const r=this.getLogContext(e);if(this.disposed)return;const n=this.writePromise;this.writePromise=(async()=>{if(n)try{await n}catch(e){zI.error(r,"Error waiting for previous write",e)}this.disposed||(await this.startupCleanupPromise,this.disposed||await this.fetchAndWrite(e,t))})()}getContext(e){let t=(0,y.q6)();return e&&(t=t.with(l._O,e)),t}getLogContext(e){return e.with(l._O,this.ctx.get(l._O))}getMetricTags(e){return{...e,mcp_version:this.mcpVersion}}getMcpAuthToolDescription(){return uT(this.mcpAuthCopyOverrides?.authToolDescription)??oT}shouldExposeVirtualMcpAuthToolForStatus(e,t){return this.exposeVirtualMcpAuthTool&&Vn(e)&&(this.alwaysExposeVirtualMcpAuthTool||"needsAuth"===t)}getErrorStatusMessage(){return uT(this.mcpAuthCopyOverrides?.errorStatusMessage)??"The MCP server errored. If this server is important for completing the task, concisely inform the user and ask them to check the MCP status in Cursor's Customize page > MCPs; otherwise continue with a different approach."}getNeedsAuthStatusMessage(e){return t=uT(this.mcpAuthCopyOverrides?.needsAuthStatusMessageWithAuthTool)??'The MCP server needs authentication. Authenticate it by calling the `{authToolName}` tool for server "{serverIdentifier}" through your MCP tool-calling interface using an empty arguments object. If this server is important for completing the task, authenticate it first; otherwise continue with a different approach.',r={serverIdentifier:e,authToolName:nT},t.replace(/\{serverIdentifier\}/g,r.serverIdentifier).replace(/\{authToolName\}/g,r.authToolName);var t,r}getNeedsAuthStatusMessageForWrite(e){return this.exposeVirtualMcpAuthTool&&Vn(e)?this.getNeedsAuthStatusMessage(e):uT(this.mcpAuthCopyOverrides?.needsAuthStatusMessageWithoutVirtualTool)??"This MCP server requires authentication before its tools can be used. Open Cursor's Customize page > MCPs, select this server, and use Authenticate/Reopen, or refresh credentials in your MCP configuration (for example mcp.json), then restart this environment. If this server is not required for the task, continue without it."}async getToolsForServers(e,t){if(0===t.length)return[];const r=this.getLogContext(e);try{return await this.mcpLease.getToolsForServers(e,t)}catch(n){zI.warn(r,`getToolsForServers() threw, falling back to filtered getTools(): ${kc(n)}`);const o=await this.mcpLease.getTools(e).catch((e=>(zI.warn(r,`getTools() threw during scoped-tool fallback, defaulting to []: ${e}`),[]))),s=new Set(t);return o.filter((e=>s.has(e.clientKey)))}}async fetchClientDataForServer(e,t,r,n){const o=await cT(r.getState(e),{kind:"error"}).then((r=>("error"!==r.kind||"message"in r||zI.warn(e,`getState() timed out for "${t}", defaulting to error`),r))),s="ready"===o.kind||"requires_authentication"===o.kind,[i,a,c]=await Promise.all([s?cT(r.listResources(e),{resources:[]}):Promise.resolve({resources:[]}),s?cT(r.listPrompts(e),[]):Promise.resolve([]),s&&n?.fetchInstructions?cT(r.getInstructions(e),void 0):Promise.resolve(void 0)]);return{clientKey:t,serverName:r.serverName,plugin:r.plugin,marketplace:r.marketplace,pluginId:r.pluginId,marketplaceId:r.marketplaceId,resources:i.resources.map((e=>({...e,serverIdentifier:t,serverName:r.serverName}))),prompts:a.map((e=>({...e,serverIdentifier:t,serverName:r.serverName}))),instructions:c,status:dT(o)}}buildServerDataMap(e,t,r){const n=new Map;for(const e of t){const t=My(e.clientKey);n.set(e.clientKey,{serverIdentifier:e.clientKey,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,sanitizedId:t,folderPath:(0,s.join)(this.projectDir,GI,t),tools:[],resources:e.resources,prompts:e.prompts,instructions:e.instructions,status:e.status})}for(const t of e){let e=n.get(t.clientKey);if(!e){const r=My(t.clientKey);e={serverIdentifier:t.clientKey,serverName:t.providerIdentifier,plugin:t.plugin,marketplace:t.marketplace,pluginId:t.pluginId,marketplaceId:t.marketplaceId,sanitizedId:r,folderPath:(0,s.join)(this.projectDir,GI,r),tools:[],resources:[],prompts:[],instructions:void 0,status:void 0},n.set(t.clientKey,e)}e.tools.push(t)}if(void 0!==r)for(const e of r){const t=e.serverIdentifier?.trim();let r=t?Array.from(n.values()).find((e=>e.serverIdentifier===t)):void 0;if(!r){const t=e.serverName?.trim();r=t?Array.from(n.values()).find((e=>e.serverName===t)):void 0}r&&e.instructions&&(r.instructions=e.instructions)}if(this.exposeVirtualMcpAuthTool)for(const e of n.values())this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&(e.tools.some((e=>e.toolName===nT))||e.tools.push({clientKey:(o={serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,authToolDescription:this.getMcpAuthToolDescription()}).serverIdentifier,providerIdentifier:o.serverName,plugin:o.plugin,marketplace:o.marketplace,pluginId:o.pluginId,marketplaceId:o.marketplaceId,toolName:nT,name:nT,description:o.authToolDescription,inputSchema:{type:"object",properties:{},additionalProperties:!1}}));var o;return n}buildServersToWrite(e,t){const r=[],n=new Set;for(const o of t.values()){const t=o.tools.length>0||o.resources.length>0||o.prompts.length>0||o.instructions,s="error"===o.status||"needsAuth"===o.status||"initializing"===o.status;t||s?n.has(o.sanitizedId)?zI.warn(e,`Skipping server "${o.serverIdentifier}" — sanitizedId "${o.sanitizedId}" collides with another server`):(n.add(o.sanitizedId),r.push(o)):zI.info(e,`Server "${o.serverIdentifier}" excluded from write: tools=${o.tools.length}, resources=${o.resources.length}, prompts=${o.prompts.length}, hasInstructions=${!!o.instructions}, status=${o.status}`)}return r}mergeScopedRefreshWithCachedServerData(e,t){const r=[...t.tools];if(this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&!r.some((e=>e.toolName===nT))){const t=e.tools.find((e=>e.toolName===nT));void 0!==t&&r.push(t)}return{...e,...t,tools:r,resources:e.resources,prompts:e.prompts,instructions:e.instructions,status:e.status,plugin:t.plugin??e.plugin,marketplace:t.marketplace??e.marketplace,pluginId:t.pluginId??e.pluginId,marketplaceId:t.marketplaceId??e.marketplaceId}}async refreshServersFromLease(e,t){const r=this.getLogContext(e),n=[...new Set(t.serverIdentifiers??[])];zI.info(r,`fetchAndWrite: refreshing ${n.length} targeted servers`,{serverIdentifiers:n});const o=await this.getToolsForServers(e,n),s=await this.mcpLease.getInstructions(e).catch((e=>(zI.warn(r,`getInstructions() threw during scoped refresh, defaulting to []: ${e}`),[]))),i=await Promise.all(n.map((async t=>{try{const r=await this.mcpLease.getClient(e,t);return void 0===r?{serverIdentifier:t,kind:"missing"}:{serverIdentifier:t,kind:"client",client:r}}catch(e){return zI.warn(r,`getClient("${t}") threw during scoped refresh, preserving cached data: ${kc(e)}`),{serverIdentifier:t,kind:"error",error:e}}}))),a=i.filter((e=>"missing"===e.kind)).map((e=>e.serverIdentifier));let c=new Set;if(a.length>0){const t=await this.mcpLease.getClients(e).catch((e=>{zI.warn(r,`getClients() threw while confirming targeted server removal, preserving cached data: ${e}`)}));void 0!==t&&(c=new Set(a.filter((e=>void 0===t[e]))))}const l=await Promise.all(i.filter((e=>"client"===e.kind)).map((({serverIdentifier:t,client:r})=>this.fetchClientDataForServer(e,t,r,{fetchInstructions:!0})))),u=new Map((this.cachedServerData??[]).map((e=>[e.serverIdentifier,e]))),d=this.buildServerDataMap(o,l,s),h=new Set(n),p=new Set(i.filter((e=>"error"===e.kind||"missing"===e.kind&&!c.has(e.serverIdentifier))).map((e=>e.serverIdentifier)));for(const e of n){const t=u.get(e),n=d.get(e);if(void 0===n)c.has(e)?u.delete(e):zI.warn(r,`refreshServersFromLease: preserving cached data for "${e}" because targeted refresh returned no replacement`);else{if(p.has(e)&&void 0!==t){u.set(e,this.mergeScopedRefreshWithCachedServerData(t,n)),zI.warn(r,`refreshServersFromLease: preserving cached metadata for "${e}" because the client was unavailable during targeted refresh`);continue}u.set(e,n)}}const f=new Map(Array.from(u.values()).map((e=>[e.sanitizedId,e.serverIdentifier])));for(const[e,t]of this.cachedFingerprints)if(!h.has(e)&&!u.has(e)){const t=My(e);f.set(t,e)}const m=this.buildServersToWrite(e,u);await this.writeServerData(e,m,f),this.cachedServerData=m,this.fireOnDidWrite(m)}async fetchAndWrite(e,t){const r={stack:[],error:void 0,hasError:!1};try{DI(r,(0,$.VI)(e.withName("McpFileSystemWriter.fetchAndWrite")),!1);const n=this.getLogContext(e);try{if(void 0!==this.cachedServerData&&void 0!==t&&!Qn(t)&&[...new Set(t.serverIdentifiers??[])].length>0)return void await this.refreshServersFromLease(e,t);const[r,o,s]=await Promise.all([this.mcpLease.getTools(e).catch((e=>(zI.warn(n,`getTools() threw, defaulting to []: ${e}`),[]))),this.mcpLease.getInstructions(e).catch((()=>[])),this.mcpLease.getClients(e).catch((e=>(zI.warn(n,`getClients() threw, defaulting to {}: ${e}`),{})))]),i=Object.keys(s);zI.info(n,`fetchAndWrite: lease returned ${r.length} tools across ${i.length} clients`);const a=Object.entries(s).map((([t,r])=>this.fetchClientDataForServer(e,t,r))),c=await Promise.all(a),l=this.buildServerDataMap(r,c,o),u=this.buildServersToWrite(e,l),d=new Map(Array.from(l.values()).map((e=>[e.sanitizedId,e.serverIdentifier])));await this.writeServerData(e,u,d),this.cachedServerData=u,this.fireOnDidWrite(u)}catch(e){zI.error(n,"Error fetching/writing MCP state",e)}}catch(e){r.error=e,r.hasError=!0}finally{OI(r)}}fireOnDidWrite(e){if(this.onDidWrite)try{const t=e.map((e=>({serverIdentifier:e.serverIdentifier,folderPath:e.folderPath,tools:e.tools.map((t=>({toolName:t.toolName,definitionPath:(0,s.join)(e.folderPath,VI,`${lT(t.toolName)}.json`)})))})));this.onDidWrite(t)}catch{}}async writeServerData(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{DI(n,(0,$.VI)(e.withName("McpFileSystemWriter.writeServerData")),!1);const o=this.getLogContext(e),i=(0,s.join)(this.projectDir,GI);await(0,Co.mkdir)(i,{recursive:!0});const a=new Map;for(const e of t)try{a.set(e.serverIdentifier,mT(e))}catch(t){zI.error(o,"Error computing server fingerprint, will force write",t,{serverIdentifier:e.serverIdentifier}),a.set(e.serverIdentifier,`__error_${Date.now()}_${Math.random()}`)}const c=[];for(const e of t){const t=this.cachedFingerprints.get(e.serverIdentifier);t!==a.get(e.serverIdentifier)&&(c.push(e),void 0!==t&&zI.info(o,`Server "${e.serverIdentifier}" fingerprint changed: tools=${e.tools.length}, status=${e.status}`))}for(const e of t)if(!c.includes(e))try{await(0,Co.stat)((0,s.join)(i,e.sanitizedId))}catch{zI.info(o,`Server "${e.serverIdentifier}" directory missing on disk, forcing write`),c.push(e)}const l=new Set;for(const[e]of this.cachedFingerprints)if(!a.has(e)){const t=this.cachedServerData?.find((t=>t.serverIdentifier===e)),n=t?.sanitizedId??My(e);r.has(n)?(zI.info(o,`Server "${e}" (sanitized="${n}") still in lease but excluded from write, preserving directory`),a.set(e,this.cachedFingerprints.get(e))):(zI.info(o,`Server "${e}" (sanitized="${n}") left the lease, scheduling directory removal`),l.add(n))}const u=void 0===this.cachedServerData;if(u)try{const e=await(0,Co.readdir)(i),t=new Set(e.filter((e=>!e.endsWith(KI)&&!e.endsWith(JI))));for(const r of e){const e=r.endsWith(KI),n=r.endsWith(JI);if((e||n)&&await rT(i,r))if(e)await(0,Co.rm)((0,s.join)(i,r),{recursive:!0,force:!0});else{const e=YI(r);if(t.has(e))await(0,Co.rm)((0,s.join)(i,r),{recursive:!0,force:!0});else try{await(0,Co.rename)((0,s.join)(i,r),(0,s.join)(i,e)),t.add(e)}catch{await(0,Co.rm)((0,s.join)(i,r),{recursive:!0,force:!0}).catch((()=>{}))}}}for(const e of t)if(r.has(e)){const t=r.get(e);a.has(t)||a.set(t,`__preserved_${e}`)}else l.add(e)}catch(e){zI.error(o,"Error clearing mcps directory",e)}const d=Array.from(l);if(c.length>0||l.size>0){const e=c.map((e=>({serverIdentifier:e.serverIdentifier,sanitizedId:e.sanitizedId,toolCount:e.tools.length})));zI.info(o,`Incremental write: ${c.length} changed, ${l.size} removed, ${t.length-c.length} unchanged`,{changedServerCount:c.length,changedServers:e,removedServerCount:l.size,removedServerSanitizedIds:d,unchangedServerCount:t.length-c.length,totalServerCount:t.length,leaseServerCount:r.size,coldStartReconcile:u,projectDirHash:(0,bo.createHash)("sha256").update(this.projectDir).digest("hex")},{includeStructuredLogs:!0})}const h=await Promise.allSettled(c.map((t=>this.writeServerAtomic(e,t,i))));for(let t=0;t(0,Co.rm)((0,s.join)(i,e),{recursive:!0,force:!0}))));for(let r=0;r{await(i?.catch((()=>{}))),await this.swapServerDirectory(e,t,r)})();QI.set(o,a);try{await a}finally{QI.get(o)===a&&QI.delete(o)}}catch(e){n.error=e,n.hasError=!0}finally{OI(n)}}async swapServerDirectory(e,t,r){const n=eT(t.sanitizedId,KI),o=(0,s.join)(r,n),i=(0,s.join)(r,t.sanitizedId);try{await this.writeServerDirectory(e,t,{basePath:r,dirName:n})}catch(e){throw await(0,Co.rm)(o,{recursive:!0,force:!0}).catch((()=>{})),e}const a=(0,s.join)(r,eT(t.sanitizedId,JI));let c=!1;try{try{await this.renameWithRetry(i,a),c=!0}catch(e){if("ENOENT"!==Sc(e))throw e}await this.renameWithRetry(o,i)}catch(r){if(zI.error(e,"Per-server swap failed",r,{serverIdentifier:t.serverIdentifier,sanitizedId:t.sanitizedId},{includeStructuredLogs:!0}),c)try{await this.renameWithRetry(a,i)}catch{await(0,Co.stat)(i).then((()=>!0),(()=>!1))&&await(0,Co.rm)(a,{recursive:!0,force:!0}).catch((()=>{}))}throw await(0,Co.rm)(o,{recursive:!0,force:!0}).catch((()=>{})),r}await(0,Co.rm)(a,{recursive:!0,force:!0}).catch((()=>{}))}async renameWithRetry(e,t){for(let r=0;;r++)try{return void await(0,Co.rename)(e,t)}catch(e){const t=Sc(e);if(r>=ZI.length||void 0===t||!XI.has(t))throw e;await(0,Or.cb)(ZI[r])}}async writeServerDirectory(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{DI(n,(0,$.VI)(e.withName("McpFileSystemWriter.writeServerDirectory")),!1);const o=(0,s.join)(r.basePath,r.dirName??t.sanitizedId);await(0,Co.mkdir)(o,{recursive:!0});const i=[];if(t.tools.length>0){const e=(0,s.join)(o,VI);await(0,Co.mkdir)(e,{recursive:!0});for(const r of t.tools){const t=lT(r.toolName);i.push({path:(0,s.join)(e,`${t}.json`),content:JSON.stringify(Zn(r),null,2)})}}if(t.resources.length>0){const e=(0,s.join)(o,"resources");await(0,Co.mkdir)(e,{recursive:!0});for(const r of t.resources){const t=lT(r.name||r.uri.replace(/[^a-zA-Z0-9_-]/g,"_")),n={uri:r.uri,name:r.name,description:r.description,mimeType:r.mimeType};i.push({path:(0,s.join)(e,`${t}.json`),content:JSON.stringify(n,null,2)})}}if(t.prompts.length>0){const e=(0,s.join)(o,"prompts");await(0,Co.mkdir)(e,{recursive:!0});for(const r of t.prompts){const t=lT(r.name),n={name:r.name,description:r.description,arguments:r.arguments};i.push({path:(0,s.join)(e,`${t}.json`),content:JSON.stringify(n,null,2)})}}t.instructions&&t.instructions.trim().length>0&&i.push({path:(0,s.join)(o,"INSTRUCTIONS.md"),content:t.instructions.trim()}),"error"!==t.status&&"needsAuth"!==t.status||i.push({path:(0,s.join)(o,"STATUS.md"),content:"error"===t.status?this.getErrorStatusMessage():this.getNeedsAuthStatusMessageForWrite(t.serverIdentifier)});const a={serverIdentifier:t.serverIdentifier,serverName:t.serverName};i.push({path:(0,s.join)(o,"SERVER_METADATA.json"),content:JSON.stringify(a,null,2)});if(new Set(i.map((e=>e.path.toLowerCase()))).size!==i.length){for(const e of i)await(0,Co.writeFile)(e.path,e.content);return}const c=(await(0,Or.up)(i,(e=>(0,Co.writeFile)(e.path,e.content)),{max:8})).find((e=>"rejected"===e.status));if(c)throw c.reason}catch(e){n.error=e,n.hasError=!0}finally{OI(n)}}async getMcpFileSystemOptions(e,t){const r={stack:[],error:void 0,hasError:!1};try{if(this.disposed)return;DI(r,(0,$.VI)(e.withName("McpFileSystemWriter.getMcpFileSystemOptions")),!1);const n=this.getLogContext(e),o=await this.ensureWritesSettled(e,t?.timeoutMs);if(this.snapshotProvider&&!o)return this.buildOptionsFromSnapshots(e);this.snapshotProvider&&o&&zI.warn(n,"Snapshot mode write barrier timed out; falling back to cached descriptors",{timeoutMs:t?.timeoutMs},{includeStructuredLogs:!0});const i=(this.cachedServerData??[]).map((e=>{const t=e.tools.map((t=>{const r=lT(t.toolName),n=(0,s.join)(e.folderPath,VI,`${r}.json`);return new wn.E$({toolName:t.toolName,definitionPath:n,...Db(t.annotations)})}));return new wn.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,folderPath:e.folderPath,serverUseInstructions:e.instructions,tools:t})}));return this.checkDescriptorsVsFilesystem(e,i,"workbench_lease"),new wn.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:i})}catch(e){r.error=e,r.hasError=!0}finally{OI(r)}}async ensureWritesSettled(e,t){const r=this.getLogContext(e),n=void 0!==this.debounceTimer;if(void 0!==this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0,this.scheduleWrite(e,this.takePendingLeaseChangeEvent())),n&&zI.info(r,"getMcpFileSystemOptions force-fired pending debounce"),!this.writePromise)return!1;if(void 0!==t){let e,n=!1;try{await Promise.race([this.writePromise,new Promise((r=>{e=setTimeout((()=>{n=!0,r()}),t)}))])}catch(e){zI.error(r,"Error waiting for pending write to complete",e)}finally{clearTimeout(e)}return n&&zI.warn(r,`getMcpFileSystemOptions timed out after ${t}ms waiting for write; returning stale cache`),n}try{await this.writePromise}catch(e){zI.error(r,"Error waiting for pending write to complete",e)}return!1}async buildOptionsFromSnapshots(e){const t={stack:[],error:void 0,hasError:!1};try{DI(t,(0,$.VI)(e.withName("McpFileSystemWriter.buildOptionsFromSnapshots")),!1);const r=this.getLogContext(e),n=Date.now(),o=await this.snapshotProvider.getAllSnapshots(e),i=(0,s.join)(this.projectDir,GI),a=o.filter((e=>e.tools.length>0||e.resources.length>0||e.prompts.length>0||void 0!==e.instructions||this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)||"needsAuth"===e.status||"error"===e.status)).map((e=>{const t=My(e.serverIdentifier),r=(0,s.join)(i,t),n=e.tools.map((e=>{const t=lT(e.name);return new wn.E$({toolName:e.name,definitionPath:(0,s.join)(r,VI,`${t}.json`),...Db(e.annotations)})}));if(this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&!e.tools.some((e=>e.name===nT))){const e=lT(nT);n.push(new wn.E$({toolName:nT,definitionPath:(0,s.join)(r,VI,`${e}.json`)}))}return new wn.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,folderPath:r,serverUseInstructions:e.instructions,tools:n})})),c=a.reduce(((e,t)=>e+t.tools.length),0);return zI.info(r,`buildOptionsFromSnapshots completed in ${Date.now()-n}ms: ${o.length} snapshots, ${a.length} descriptors, ${c} tools`),this.checkDescriptorsVsFilesystem(e,a,"snapshot"),new wn.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:a})}catch(e){t.error=e,t.hasError=!0}finally{OI(t)}}async waitForPendingWrites(){if(void 0!==this.debounceTimer&&await new Promise((e=>{const t=()=>{void 0===this.debounceTimer?e():setTimeout(t,10)};t()})),this.writePromise)try{await this.writePromise}catch{}}getCachedServerData(){return this.cachedServerData}checkDescriptorsVsFilesystem(e,t,r){const n=this.getLogContext(e),o=Date.now();o-this.lastDivergenceCheckMs{zI.warn(n,"Divergence check failed",e)})))}async _checkDescriptorsVsFilesystemAsync(e,t,r){const n=this.getLogContext(e),o=(0,s.join)(this.projectDir,GI),i=new Set,a=new Map;for(const e of t){const t=My(e.serverIdentifier);i.add(t),a.set(t,e.tools.length)}let c=[];try{c=await(0,Co.readdir)(o),c=c.filter((e=>!e.endsWith(KI)&&!e.endsWith(JI)))}catch(e){if("ENOENT"!==Sc(e))throw e}const l=new Set(c);let u=!0,d=0,h=0,p=0;const f=function(e){return 0===e?"0":e<=3?"1-3":e<=6?"4-6":e<=10?"7-10":"11+"}(i.size);for(const t of i)l.has(t)||(u=!1,d++,FI.increment(e,1,this.getMetricTags({divergence_type:"server_missing",mcp_source:r,configured_servers:f})),zI.warn(n,"Divergence detected: server missing from filesystem",{mcpFileSystemMeta:{divergenceType:"server_missing",serverId:t,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}));for(const t of l)i.has(t)||(u=!1,h++,FI.increment(e,1,this.getMetricTags({divergence_type:"server_stale",mcp_source:r,configured_servers:f})));for(const t of i){if(!l.has(t))continue;const c=a.get(t)??0,d=(0,s.join)(o,t,VI);let h=0;try{h=(await(0,Co.readdir)(d)).filter((e=>e.endsWith(".json"))).length}catch{}h!==c&&(u=!1,p++,FI.increment(e,1,this.getMetricTags({divergence_type:"tool_count_mismatch",mcp_source:r,configured_servers:f})),zI.warn(n,"Divergence detected: tool count mismatch",{mcpFileSystemMeta:{divergenceType:"tool_count_mismatch",serverId:t,expected:c,actual:h,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}))}NI.increment(e,1,this.getMetricTags({synced:String(u),mcp_source:r,configured_servers:f})),LI.gauge(e,i.size,this.getMetricTags({mcp_source:r})),jI.gauge(e,l.size,this.getMetricTags({mcp_source:r})),UI.gauge(e,d,this.getMetricTags({mcp_source:r})),BI.gauge(e,p,this.getMetricTags({mcp_source:r})),zI.info(n,"MCP filesystem sync check",{mcpFileSystemMeta:{synced:u,expectedServers:i.size,actualServers:l.size,serversMissing:d,serversStale:h,toolMismatches:p,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}),u||zI.warn(n,"MCP filesystem divergence summary",{mcpFileSystemMeta:{synced:u,expectedServers:i.size,actualServers:l.size,serversMissing:d,serversStale:h,toolMismatches:p,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0})}dispose(){this.disposed||(this.disposed=!0,void 0!==this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.leaseChangeDisposable&&(this.leaseChangeDisposable.dispose(),this.leaseChangeDisposable=void 0),this.cachedServerData=void 0,this.cachedFingerprints.clear())}}gT.DIVERGENCE_CHECK_COOLDOWN_MS=1e4;var wT=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},yT=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function vT(e){if("object"!=typeof e||null===e||Array.isArray(e))return;const t={};for(const[r,n]of Object.entries(e))"string"==typeof n&&(t[r]=n);return t}const bT=(0,l.h)("local-exec:mcp");function ST(e,t){const r=s.default.relative(e,t);return""===r||!s.default.isAbsolute(r)&&".."!==r&&!r.startsWith(`..${s.default.sep}`)}function kT(e){return e instanceof Error&&"code"in e&&"string"==typeof e.code?e.code:void 0}function _T(e){return new Ac._Z({content:{case:"image",value:new Ac.do({data:e.data,mimeType:e.mimeType})}})}function CT(e){return new Ac._Z({content:{case:"text",value:new Ac.zN({text:e})}})}async function ET(e,t,r){const n=await r.permissionsService.shouldBlockMcp(e,t,r.toolDef,{alreadyApproved:t.skipApproval,...void 0===r.client?{}:{client:r.client},...void 0===r.resolvedTool?{}:{resolvedTool:r.resolvedTool}});if(!n)return;const o=await Qu(n,{onNeedsApproval:async(e,n)=>{if("mcp"!==n.type)return new Ac.iz({result:{case:"error",value:new Ac.Nh({error:"Invalid approval details type for MCP execution"})}});const o=await r.pendingDecisionProvider.requestApproval({type:Lw.Mcp,details:{name:n.name,toolName:n.toolName,toolTitle:n.toolTitle,destructiveHint:n.destructiveHint,providerIdentifier:n.providerIdentifier,source:r.toolDef?.source,args:n.args,reason:n.reason??e,canAllowlist:n.canAllowlist,smartModeApprovalReason:n.smartModeApprovalReason,smartModeApprovalRequestId:n.smartModeApprovalRequestId,allowlistEntry:n.allowlistEntry,computerUseApp:n.computerUseApp},toolCallId:t.toolCallId});return o.approved&&void 0!==n.computerUseApp&&!0!==n.computerUseApp.allowOnce&&r.permissionsService.allowComputerUseAppForSession?.({bundleId:n.computerUseApp.bundleId}),o.approved?t.smartModeApprovalOnly?new Ac.iz({result:{case:"approved",value:new Ac.Ke}}):null:new Ac.iz({result:{case:"rejected",value:new Ac.xo({reason:`User rejected MCP: ${t.name}${o.reason?` - ${o.reason}`:""}`})}})},onUserRejected:e=>new Ac.iz({result:{case:"error",value:new Ac.Nh({error:`User rejected MCP: ${t.name}${e?` - ${e}`:""}`})}}),onPermissionDenied:(e,r)=>xT({name:t.name,reason:e,isReadonly:r?.isReadonly??!1})});return o??void 0}function xT({name:e,reason:t,isReadonly:r}){return new Ac.iz({result:{case:"permissionDenied",value:new Ac.HQ({error:`MCP tool execution blocked: ${e} - ${t}`,isReadonly:r})}})}class PT{constructor(e,t,r,n,o=4e4,s,i,a={}){this.toolSet=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.projectDir=n,this.fileOutputThresholdBytes=o,this.elicitationFactory=s,this.ensureMcpServersLoaded=i,this.spillOptions=a}async describeDisconnectedServer(e,t){const r=new Set(t.filter((e=>""!==e)));if(0===r.size)return;let n;try{n=await this.toolSet.getClients(e)}catch{return}const o=Object.entries(n).find((([e,t])=>r.has(e)||r.has(t.serverName)));if(void 0===o)return;const[s,i]=o;let a;try{a=await i.getState(e)}catch{return}if("ready"===a.kind&&void 0===a.toolListError)return;const c=function(e){switch(e){case"needsAuth":return"This MCP server requires authentication before its tools can be used.";case"error":return"This MCP server failed during live tool discovery. Its tools are unavailable until the connection is fixed.";case"loading":return"This MCP server is still loading; tools may not be available yet.";default:return}}(Yn(a));return void 0!==c?`MCP server "${s}" has no callable tools right now. ${c}${"error"===a.kind&&a.message?` (${a.message})`:""}`:void 0}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=wT(r,(0,$.VI)(e.withName("LocalMcpToolExecutor.execute")),!1).ctx,i=t.serverIdentifier||t.providerIdentifier;await(this.ensureMcpServersLoaded?.(o,[i]));const a=await this.toolSet.getTools(o),c=Array.from(new Set(a.map((e=>e.clientKey)))).sort(),l=a.find((e=>e.clientKey===i&&e.toolName===t.toolName)),u=a.find((e=>e.name===t.name));if(void 0!==u&&(void 0!==l?u!==l:u.toolName!==t.toolName||u.clientKey!==i&&u.providerIdentifier!==i))return new Ac.iz({result:{case:"error",value:new Ac.Nh({error:`MCP tool "${t.name}" is not the tool "${t.toolName}" on server "${i}" that the call names.`})}});const d=void 0===l?void 0:await this.toolSet.getClient(o,l.clientKey).catch((()=>{})),h=l??u,p=void 0===h?void 0:h===l?d:await this.toolSet.getClient(o,h.clientKey).catch((()=>{})),f=await ET(o,t,{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionProvider,toolDef:l,...void 0===d?{}:{client:d},...void 0===h?{}:{resolvedTool:void 0===p?"unresolved":{client:p,annotations:h.annotations}}});if(void 0!==f)return f;const m=await this.toolSet.getToolSet(o),g=!0===await(this.permissionsService.enforcesMcpAdminToolLimits?.());let w;try{if(g&&void 0===h)throw new vC(t.name,a.map((e=>e.name)));const e=l?.name??t.name,r=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()])));if(g){const n=void 0===p?void 0:await(m.executeOn?.(p,e,r,t.toolCallId,this.elicitationFactory));if(void 0===n)return bT.warn(o,"Refusing an MCP tool whose client was not judged",{toolName:t.toolName,toolSetNamesClients:void 0!==m.executeOn}),xT({name:t.name,reason:nk,isReadonly:!1});w=n}else w=await m.execute(e,r,t.toolCallId,this.elicitationFactory)}catch(e){let r=e;if(bC(r)&&t.providerIdentifier.length>0&&!a.some((e=>e.clientKey===t.providerIdentifier||e.providerIdentifier===t.providerIdentifier))&&(r=new YR(t.providerIdentifier,c)),r instanceof YR){const e=await this.describeDisconnectedServer(o,[i,t.providerIdentifier]);return void 0!==e?new Ac.iz({result:{case:"error",value:new Ac.Nh({error:e})}}):new Ac.iz({result:{case:"serverNotFound",value:new Ac.JL({name:r.serverName,availableServers:r.availableServers})}})}if(bC(r))return new Ac.iz({result:{case:"toolNotFound",value:new Ac.WV({name:r.toolName,availableTools:r.availableTools})}});throw r}const y=[];for(const e of w.content){const r=e.type;if("text"===r&&"object"==typeof e&&null!==e&&"text"in e&&"string"==typeof e.text)y.push(CT(e.text));else if("resource"===r){const r=oE(e),n=void 0===r?void 0:Buffer.from(r,"base64"),s=void 0===n?void 0:await Lv(n).then(_T,(e=>{bT.warn(o,"Describing an undecodable MCP resource image",{toolName:t.toolName,bytes:n.byteLength,error:e instanceof Error?e.message:String(e)})}));y.push(s??CT(sE(e)))}else if("image"===r){const r=e,s="string"==typeof r.data?Buffer.from(r.data,"base64"):Buffer.alloc(0);let i;try{i=await Lv(s)}catch(e){bT.warn(o,"Omitting undecodable MCP tool image",{toolName:t.toolName,mimeType:"string"==typeof r.mimeType?r.mimeType.slice(0,100):typeof r.mimeType,bytes:s.byteLength,error:e instanceof Error?e.message:String(e)}),y.push(CT(`[Image omitted: the tool returned ${n=r.mimeType,"string"==typeof n&&/^image\/[\w.+-]{1,40}$/.test(n)?n:"image"} data (${s.byteLength} bytes) that could not be decoded.]`));continue}y.push(_T(i))}else if("image"!==r){const t=sE(e);y.push(CT(t))}}const v=await async function({contentItems:e,thresholdBytes:t,write:r}){const n=e.filter((e=>"text"===e.content.case&&void 0===e.content.value.outputLocation)).map((e=>"text"===e.content.case?e.content.value.text:"")).join("\n\n");if(t<=0||Buffer.byteLength(n,"utf8")<=t)return e;const o=await r(n);if(void 0===o)return;const s=[];let i=!1;for(const t of e)"text"===t.content.case&&void 0===t.content.value.outputLocation?i||(s.push(new Ac._Z({content:{case:"text",value:new Ac.zN({text:"",outputLocation:o})}})),i=!0):s.push(t);return s}({contentItems:y,thresholdBytes:this.fileOutputThresholdBytes,write:e=>async function(e,t,r){const n=s.default.join(t,$c),o=s.default.join(n,`${(0,bo.randomUUID)()}.txt`);await(0,Co.mkdir)(s.default.dirname(o),{recursive:!0});const i=Vo(!0===r.blankSharedPaymentTokens?QE(e):e,Mc),a=Js(i),c=Buffer.byteLength(i,"utf8");return await(0,Co.writeFile)(o,i,"utf8"),new Dc.pV({filePath:o,sizeBytes:BigInt(c),lineCount:BigInt(a)})}(e,this.projectDir,this.spillOptions)});if(void 0===v)throw new Error("Failed to materialize MCP text output");const b=w.structuredContent&&"object"==typeof w.structuredContent&&!Array.isArray(w.structuredContent)?we.Struct.fromJson(w.structuredContent):void 0,S=new Ac.QW({content:v,isError:w.isError,structuredContent:b,resultMeta:void 0===w._meta?void 0:we.Struct.fromJson(w._meta)});return new Ac.iz({result:{case:"success",value:S}})}catch(e){r.error=e,r.hasError=!0}finally{yT(r)}var n}}class RT{constructor(e,t){this.mcpLease=e,this.ensureMcpServersLoaded=t}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=wT(r,(0,$.VI)(e.withName("LocalListMcpResourcesExecutor.execute")),!1).ctx;try{if(t.server){await(this.ensureMcpServersLoaded?.(n,[t.server]));const e=await this.mcpLease.getClients(n),r=e[t.server]??Object.values(e).find((e=>e.serverName===t.server));if(!r)return new Ac.kP({result:{case:"error",value:new Ac.w2({error:`Server "${t.server}" not found`})}});const o=await this.listResourcesFromClient(n,r,t.server,!0);return new Ac.kP({result:{case:"success",value:new Ac.T2({resources:o})}})}const e=await this.mcpLease.getClients(n),r=new Set,o=await this.mcpLease.getTools(n);for(const e of o)r.add(e.providerIdentifier),r.add(`user-${e.providerIdentifier}`);const s=[];for(const[t,o]of Object.entries(e)){if(r.size>0&&!r.has(t))continue;const e=await this.listResourcesFromClient(n,o,t);s.push(...e)}return new Ac.kP({result:{case:"success",value:new Ac.T2({resources:s})}})}catch(e){const t=e instanceof Error?e.message:String(e);return new Ac.kP({result:{case:"error",value:new Ac.w2({error:`Failed to list MCP resources: ${t}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{yT(r)}}async listResourcesFromClient(e,t,r,n=!1){const o=await t.getState(e);if("ready"!==o.kind&&(!n||"loading"!==o.kind))return[];const s=await t.listResources(e);return s&&s.resources?s.resources.map((e=>new Ac.X2({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType,server:r,annotations:vT(e.annotations)}))):[]}}class IT{constructor(e,t=".",r,n=[],o,s,i){this.mcpLease=e,this.projectDir=t,this.pendingDecisionProvider=o,this.ensureMcpServersLoaded=s,this.writeExecutor=i,this.workspacePaths=n.filter((e=>e.length>0))}resolveProjectDir(e){const t=e.get($I),r=t?.find((e=>"string"==typeof e&&e.length>0));return r||(this.workspacePaths.length>0?this.workspacePaths[0]:this.projectDir)}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=wT(r,(0,$.VI)(e.withName("LocalReadMcpResourceExecutor.execute")),!1).ctx,o=t.smartModeApproval?.reason;if(void 0!==o){if(void 0===this.pendingDecisionProvider)return new Ac.ZD({result:{case:"error",value:new Ac.Jx({uri:t.uri,error:"Auto-review approval provider is not configured"})}});const e=await this.pendingDecisionProvider.requestApproval({type:Lw.Mcp,details:{name:"FetchMcpResource",toolName:"FetchMcpResource",providerIdentifier:t.server,args:{server:we.Value.fromJson(t.server),uri:we.Value.fromJson(t.uri),...void 0!==t.downloadPath?{downloadPath:we.Value.fromJson(t.downloadPath)}:{}},reason:"smartMode",canAllowlist:!1,smartModeApprovalReason:o,smartModeApprovalRequestId:t.smartModeApproval?.requestId},toolCallId:t.toolCallId});if(!e.approved)return new Ac.ZD({result:{case:"rejected",value:new Ac.Dh({reason:"User rejected MCP resource fetch"+(e.reason?` - ${e.reason}`:"")})}})}await(this.ensureMcpServersLoaded?.(n,[t.server]));const i=await this.mcpLease.getClients(n),a=i[t.server]??Object.values(i).find((e=>e.serverName===t.server));if(!a)return new Ac.ZD({result:{case:"error",value:new Ac.Jx({uri:t.uri,error:`Server "${t.server}" not found`})}});try{if("ready"!==(await a.getState(n)).kind)return new Ac.ZD({result:{case:"error",value:new Ac.Jx({uri:t.uri,error:`Server "${t.server}" is not ready`})}});const e=await a.readResource(n,{uri:t.uri});if(!e||!e.contents||0===e.contents.length)return new Ac.ZD({result:{case:"notFound",value:new Ac.ov({uri:t.uri})}});const r=e.contents[0];if(t.downloadPath){const e=await async function(e,t){const r=s.default.resolve(e),n=await(0,Co.realpath)(r),o=s.default.isAbsolute(t)?s.default.resolve(t):s.default.resolve(r,t),i=ST(r,o),a=s.default.isAbsolute(t)&&ST(n,o);if(!i&&!a)throw new Error("downloadPath must stay within the workspace");let c=s.default.dirname(o);for(;;)try{if(!ST(n,await(0,Co.realpath)(c)))throw new Error("downloadPath must stay within the workspace");break}catch(e){if("ENOENT"!==kT(e))throw e;const t=s.default.dirname(c);if(t===c)throw e;c=t}try{if((await(0,Co.lstat)(o)).isSymbolicLink())throw new Error("downloadPath must stay within the workspace")}catch(e){if("ENOENT"!==kT(e))throw e}return o}(this.resolveProjectDir(n),t.downloadPath);let o=e;if(r.text||r.blob){if(void 0===this.writeExecutor)throw new Error("File-write executor is not configured");const s=await this.writeExecutor.execute(n,new MI.hY({path:e,fileText:r.text??"",fileBytes:r.text||void 0===r.blob?new Uint8Array:new Uint8Array(Buffer.from(r.blob,"base64")),toolCallId:t.toolCallId,confineToWorkspace:!0}));if("rejected"===s.result.case)return new Ac.ZD({result:{case:"rejected",value:new Ac.Dh({uri:t.uri,reason:s.result.value.reason})}});if("success"!==s.result.case)return new Ac.ZD({result:{case:"error",value:new Ac.Jx({uri:t.uri,error:TT(s)})}});o=s.result.value.path}return new Ac.ZD({result:{case:"success",value:new Ac.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,downloadPath:o})}})}if(r.text)return new Ac.ZD({result:{case:"success",value:new Ac.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:vT(r.annotations),metaJson:Jn(r._meta),content:{case:"text",value:r.text}})}});if(r.blob){const e=Buffer.from(r.blob,"base64");return new Ac.ZD({result:{case:"success",value:new Ac.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:vT(r.annotations),metaJson:Jn(r._meta),content:{case:"blob",value:e}})}})}return new Ac.ZD({result:{case:"error",value:new Ac.Jx({uri:t.uri,error:"Failed to read resource"})}})}catch(e){const r=e instanceof Error?e.message:String(e);return bT.warn(n,"LocalReadMcpResourceExecutor.execute failed",{server:t.server,hasDownloadPath:Boolean(t.downloadPath),errorName:e instanceof Error?e.name:typeof e,errorMessage:r}),new Ac.ZD({result:{case:"error",value:new Ac.Jx({uri:t.uri,error:`Failed to read MCP resource: ${r}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{yT(r)}}}function TT(e){switch(e.result.case){case"error":return e.result.value.error;case"permissionDenied":return e.result.value.error||"Permission denied";case"noSpace":return"No space left on device";case"rejected":return e.result.value.reason||"Write rejected";case"success":return"";case void 0:return"Write executor returned result without case";default:{const t=e.result;return String(t)}}}var AT=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const $T=1e4,MT=5e3,DT={PAGER:"cat",MANPAGER:"cat",LESS:"-R",PIP_PROGRESS_BAR:"off",TQDM_DISABLE:"1"};class OT{constructor(){this.fullOutput="",this.outputHead="",this.outputTail="",this.totalChars=0}append(e){if(0===e.length)return;const t=this.totalChars;if(this.totalChars+=e.length,t$T&&(this.fullOutput="")}getOutput(){return this.totalChars<=$T?this.fullOutput:void 0}getTruncation(){if(!(this.totalChars<=$T))return{outputHead:this.outputHead,outputTail:this.outputTail,elidedChars:this.totalChars-this.outputHead.length-this.outputTail.length}}}class FT{constructor(){this.kept="",this.full=!1}append(e){if(this.full)return;const t=rs-this.kept.length;this.full=e.length>=t,this.kept+=Vo(e,t)}get text(){return this.kept}}function NT(e,t){return null!==e?e:null===t?-1:-o.constants.signals[t]}class LT{constructor(e,t,r){this.permissionsService=e,this.ignoreService=t,this.defaultCwd=r}buildResult({args:e,workingDirectory:t,processResult:r,sandboxPolicy:n}){const o={command:e.command,workingDirectory:t,exitCode:r.returncode,signal:r.signal,stdout:r.stdout,stderr:r.exceptionInfo||r.stderr,interleavedOutput:r.output,outputHead:r.outputTruncation?.outputHead,outputTail:r.outputTruncation?.outputTail,elidedChars:r.outputTruncation?.elidedChars,executionTime:r.localExecutionTimeMs??0,localExecutionTimeMs:r.localExecutionTimeMs},s=r.exceptionInfo.length>0,i=0!==r.returncode||s?{case:"failure",value:new he.xC({...o,aborted:s,abortReason:r.abortReason})}:{case:"success",value:new he.QR(o)};return new he.W4({result:i,sandboxPolicy:us(n)})}async runProcess({ctx:e,args:t,workingDirectory:r,sandboxPolicy:n,timeoutMs:o}){const s=performance.now(),i=this.defaultCwd,a=(await(0,Oo.resolveSandboxPolicyForWorkspace)(i,n?{perUser:n}:void 0)).policy,c="insecure_none"!==a.type?{...a,sandboxWorkspaceRoot:i}:a;return await new Promise((n=>{const i=new OT,a=new FT,l=new FT;let u,d,h=!1,p=!1,f="",m=()=>{};const g=(0,Oo.Qw)((0,Oo.ue)((0,Oo.Xw)({...process.env,...DT,CURSOR_AGENT:"1"}))),w={cwd:r,env:g,stdio:["pipe","pipe","pipe"],detached:"win32"!==process.platform,windowsVerbatimArguments:"win32"===process.platform},y="win32"===process.platform?{executable:process.env.ComSpec??"cmd.exe",args:(v=t.command,["/d","/s","/c",`"${v}"`])}:{executable:"/bin/sh",args:["-c",t.command]};var v;const b="insecure_none"===c.type?(0,su.D9)(ou.spawn,y.executable,y.args,w):(0,Oo.spawnInSandbox)(y.executable,y.args,w,c);b.stdin?.end();const S=e=>{h||(h=!0,clearTimeout(d),m(),n({...e,output:i.getOutput(),outputTruncation:i.getTruncation(),localExecutionTimeMs:$y(performance.now()-s)}))};d=setTimeout((()=>{if(p=!0,void 0===u&&(f=`An error occurred while executing the command: Command timed out after ${o}ms`,u=he.Lv.TIMEOUT,m()),void 0!==b.pid&&"win32"!==process.platform)try{return void process.kill(-b.pid,"SIGKILL")}catch{}b.kill("SIGKILL")}),o);const k=()=>{if(void 0===u){if(f="An error occurred while executing the command: Command aborted",u=he.Lv.USER_ABORT,void 0!==b.pid&&"win32"!==process.platform)try{return void process.kill(-b.pid,"SIGTERM")}catch{}b.kill("SIGTERM")}};e.signal.aborted?k():(e.signal.addEventListener("abort",k,{once:!0}),m=()=>{e.signal.removeEventListener("abort",k)}),b.stdout?.setEncoding("utf8"),b.stdout?.on("data",(e=>{a.append(e),i.append(e)})),b.stderr?.setEncoding("utf8"),b.stderr?.on("data",(e=>{l.append(e),i.append(e)})),b.on("error",(e=>{S({stdout:a.text,stderr:l.text,returncode:-1,signal:"",exceptionInfo:`An error occurred while executing the command: ${e.message}`})})),b.on("close",((e,t)=>{S({stdout:a.text,stderr:l.text,returncode:f.length>0?-1:NT(e,t),signal:t??(p?"SIGKILL":""),exceptionInfo:f,abortReason:u})}))}))}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,$.VI)(e.withName("LocalMiniSweAgentBashExecutor.execute")),!1).ctx;(0,$.HF)(n,"LocalMiniSweAgentBashExecutor.execute");const o=t.command,s=(0,Yo.o1)(t.workingDirectory||this.defaultCwd),i=t.timeout>0?t.timeout:3e4;if(!t.parsingResult)return new he.W4({result:{case:"spawnError",value:new he.mJ({command:o,workingDirectory:s,error:"Parsing result is required"})}});let a=t.requestedSandboxPolicy?ls(t.requestedSandboxPolicy):void 0;const c=await this.permissionsService.shouldBlockShellCommand(n,o,{workingDirectory:s,timeout:i,parsingResult:t.parsingResult,toolCallId:t.toolCallId},a);if("block"===c.kind)return"permissionsConfig"===c.reason.type&&c.reason.isReadonly?new he.W4({result:{case:"permissionDenied",value:new he.jn({command:o,workingDirectory:s,error:"Command blocked by permissions configuration",isReadonly:!0})}}):new he.W4({result:{case:"rejected",value:new he.pZ({command:o,workingDirectory:s,reason:Yu(c.reason)})}});a=c.policy,$s()&&(a=Ls(o,t.parsingResult)),a&&"insecure_none"!==a.type&&(a={...a,ignoreMapping:await this.ignoreService.getCursorIgnoreMapping()});const l=await this.runProcess({ctx:n,args:t,workingDirectory:s,sandboxPolicy:a,timeoutMs:i});return this.buildResult({args:t,workingDirectory:s,processResult:l,sandboxPolicy:a})}catch(e){r.error=e,r.hasError=!0}finally{AT(r)}}}const jT=q("shell-executor",(e=>new B(e,Z("shellArgs"),X("shellResult"))),((e,t)=>{t.register(new I(e,Y("shellArgs"),Q("shellResult")))})),UT=q("mini-swe-agent-bash-executor",(e=>new B(e,Z("miniSweAgentBashArgs"),X("miniSweAgentBashResult"))),((e,t)=>{t.register(new I(e,Y("miniSweAgentBashArgs"),Q("miniSweAgentBashResult")))}));function BT(e){return`${e} changed on disk after this tool call read it. Nothing was written. Read the file again and retry.`}function WT(e){return`${e} changed on disk after you last read or wrote it. Nothing was written. Read the file again and retry.`}(0,y.cF)(Symbol("optionalPendingPodWrite"),!1);const HT=q("write-executor",(e=>new B(e,Z("writeArgs"),X("writeResult"))),((e,t)=>{t.register(new I(e,Y("writeArgs"),Q("writeResult")))})),qT=q("delete-executor",(e=>new B(e,Z("deleteArgs"),X("deleteResult"))),((e,t)=>{t.register(new I(e,Y("deleteArgs"),Q("deleteResult")))})),zT=q("fetch-executor",(e=>new B(e,Z("fetchArgs"),X("fetchResult"))),((e,t)=>{t.register(new I(e,Y("fetchArgs"),Q("fetchResult")))})),GT=q("git-diff-executor",(e=>new B(e,Z("gitDiffRequest"),X("gitDiffResponse"))),((e,t)=>{t.register(new I(e,Y("gitDiffRequest"),Q("gitDiffResponse")))})),VT=q("grep-executor",(e=>new B(e,Z("grepArgs"),X("grepResult"))),((e,t)=>{t.register(new I(e,Y("grepArgs"),Q("grepResult")))})),KT="[REDACTED]",JT=new TextEncoder;async function ZT(e){const t=JT.encode(e),r=await crypto.subtle.digest("SHA-256",t);return{sha256:[...new Uint8Array(r)].map((e=>e.toString(16).padStart(2,"0"))).join(""),bytes:t.byteLength}}class XT{constructor(e){this.inner=e}async execute(e,t,r){if(!0!==t.digestOnly)return this.inner.execute(e,t,r);const n=t.clone();return n.digestOnly=void 0,n.maxChars=void 0,async function(e){if("success"!==e.result.case)return e;const t=e.result.value;if("content"!==t.output.case)return e;const{sha256:r,bytes:n}=await ZT(t.output.value),o=t.clone();return o.output={case:void 0},o.outputBlobId=void 0,o.sha256=r,o.sizeBytes=BigInt(n),new Ky.sV({result:{case:"success",value:o}})}(await this.inner.execute(e,n,r))}}const QT=q("read-executor",(e=>new B(e,Z("readArgs"),X("readResult"))),((e,t)=>{t.register(new I(e,Y("readArgs"),Q("readResult")))})),YT=q("redacted-read-executor",(e=>new B(e,Z("redactedReadArgs"),X("redactedReadResult"))),((e,t)=>{t.register(new I(e,Y("redactedReadArgs"),Q("redactedReadResult")))})),eA=q("ls-executor",(e=>new B(e,Z("lsArgs"),X("lsResult"))),((e,t)=>{t.register(new I(e,Y("lsArgs"),Q("lsResult")))})),tA=q("diagnostics-executor",(e=>new B(e,Z("diagnosticsArgs"),X("diagnosticsResult"))),((e,t)=>{t.register(new I(e,Y("diagnosticsArgs"),Q("diagnosticsResult")))})),rA=q("canvas-diagnostics-executor",(e=>new B(e,Z("canvasDiagnosticsArgs"),X("canvasDiagnosticsResult"))),((e,t)=>{t.register(new I(e,Y("canvasDiagnosticsArgs"),Q("canvasDiagnosticsResult")))})),nA="$file:";const oA=(0,u.Pu)("mcp.symbolic_args.expansion",{description:"Outcome of late-binding $file:/abs/path MCP argument expansion at the executor boundary. The call is refused rather than carrying a placeholder to the server when the read reports having replaced a saved secret (`redacted`), or, from a read executor too old to report that, when its text still carries the redaction marker (`redacted_marker`)",labelNames:["route","outcome"]}),sA=(0,u.v5)("mcp.symbolic_args.bytes",{description:"Total bytes substituted into one MCP tool call by $file:/abs/path arguments",labelNames:["route"]}),iA=(0,u.Pu)("mcp.symbolic_args.describe",{description:"Per-file $file:/abs/path describe reads: `vm_digest` when the read executor hashed the file where it lives, `outdated_executor` when it returned the text instead (it predates $file: expansion, so the call is refused)",labelNames:["source"]}),aA=(0,u.v5)("mcp.symbolic_args.paths",{description:"Number of distinct $file:/abs/path arguments expanded in one MCP tool call",labelNames:["route"]});function cA(e,t,r){return{kind:e,message:`Could not resolve the symbolic argument "${nA}${t}": ${r} A string argument of the form "${nA}/absolute/path" is replaced with that file's contents before the tool runs; pass the literal text instead if you did not intend that.`}}const lA={redacted:e=>`${e} contains a saved secret, and a saved secret is never sent through a "${nA}/absolute/path" argument, so this call was not made. Do not retry it, and do not read the file to pass the value yourself. Tell the user that this file holds a saved secret and that they have to enter it in the tool's service themselves.`,redacted_marker:e=>`${e} may contain a saved secret: its text includes the placeholder "${KT}", and the computer that read it is too old to say whether a saved secret stood there, so this call was not made. Do not retry it, and do not read the file to pass the value yourself. Tell the user that this file may hold a saved secret and that they have to enter it in the tool's service themselves.`};function uA(e,t){return{kind:e,message:`Could not resolve the symbolic argument "${nA}${t}": ${lA[e](t)}`}}class dA extends Error{constructor(e){super(e.message),this.failure=e}}let hA;async function pA(e,t,r,n,o,{maxFileBytes:s=8388608,maxTotalBytes:i=16777216,refuseSavedSecrets:a=!1}){if(t.length>4)throw new dA(cA("too_many",t[4]??"",`at most 4 symbolic arguments may be used in one call (${t.length} given). Split the call or pass paths to tools that accept them.`));const c=r();if(void 0===c)throw new dA(cA("no_read_executor",t[0]??"","this environment cannot read files on behalf of a tool call."));const l=await(0,Or.xb)(t,(t=>async function(e,t,r,n,o){const s=await t.execute(e,new Ky.a2({path:r,toolCallId:n,...o.digestOnly?{digestOnly:!0}:{}}));if("success"!==s.result.case)throw new dA(function(e,t,r){switch(e.result.case){case"fileNotFound":return cA("not_found",t,"the file does not exist.");case"permissionDenied":return cA("permission_denied",t,"reading it was not permitted.");case"rejected":return cA("rejected",t,`${e.result.value.reason||"the read was rejected"}. Only files the Read tool can read without approval can be substituted; read it with Read instead.`);case"invalidFile":return cA("not_text",t,"the file cannot be read as text.");case"error":return r?{kind:"read_error",message:`Could not resolve the symbolic argument "${nA}${t}": ${e.result.value.error}`}:cA("read_error",t,e.result.value.error);default:return cA("read_error",t,"the read returned no result.")}}(s,r,o.refuseSavedSecrets));return await async function(e,t,r,{maxFileBytes:n,digestOnly:o,refuseSavedSecrets:s}){const i=function(e,t,r,n){const o=n&&void 0!==t.sha256&&void 0!==t.sizeBytes?{sha256:t.sha256,bytes:Number(t.sizeBytes)}:void 0;if(void 0===o&&"content"!==t.output.case)throw new dA(cA("not_text",r,"the file is not a text file."));if(n){if(iA.increment(e,1,{source:void 0!==o?"vm_digest":"outdated_executor"}),void 0===o)throw new dA(cA("outdated_executor",r,"the computer that would run this tool has an older tool runner that cannot substitute files. Read the file and pass its contents instead."));return o}}(e,t,r,o),a="content"===t.output.case?t.output.value:void 0,{sha256:c,bytes:l}=i??await ZT(a??""),u={content:a,bytes:l,sha256:c};if(t.truncated||l>n)throw new dA(cA("too_large",r,`the file is too large to inline (${Number(t.fileSize)||l} bytes; at most ${n} bytes per file may be substituted). Pass the path to a tool that accepts one, or read a range of it.`));return await async function(e,t,r,n){if(n){if(!0===e.redacted)throw new dA(uA("redacted",r));if(void 0===e.redacted&&await async function(e){return void 0!==e.content?e.content.includes(KT):(await(hA??=Promise.all([KT,`${KT}\n`,`${KT}\r\n`].map((async e=>(await ZT(e)).sha256))).then((e=>new Set(e))),hA)).has(e.sha256)}(t))throw new dA(uA("redacted_marker",r))}}(t,u,r,s),u}(e,s.result.value,r,o)}(e,c,t,n,{maxFileBytes:s,digestOnly:o,refuseSavedSecrets:a})),{max:4});let u=0;for(const[e,r]of l)if(u+=r.bytes,u>i)throw new dA(cA("over_budget",e,`together the ${t.length} symbolic arguments exceed the ${i} bytes that may be substituted per call. Pass paths to tools that accept them instead.`));return l}async function fA(e,t,{route:r,getReadExecutor:n,...o}){if(0===t.symbolicPathArguments.length)return{kind:"none"};const s=new Map(t.symbolicPathArguments.map((e=>[e.path,e]))),i=[...s.keys()],a=t=>(oA.increment(e,1,{route:r,outcome:t.kind}),{kind:"failed",failure:t,result:new Ac.iz({result:{case:"error",value:new Ac.Nh({error:t.message})}})});let c;try{c=await pA(e,i,n,t.toolCallId,!1,o)}catch(e){return a(function(e,t){return e instanceof dA?e.failure:cA("read_error",t,e instanceof Error?e.message:String(e))}(e,i[0]??""))}let l=0;for(const[e,t]of c){l+=t.bytes;const r=s.get(e);if(r?.sha256!==t.sha256)return a(cA("content_changed",e,`the file changed after the call was reviewed (${r?.sizeBytes??0} bytes then, ${t.bytes} bytes now), so its new contents were not sent. Re-run the call to review the current contents.`))}const u=new Map([...c].map((([e,t])=>[e,t.content??""]))),d=function(e,t){const r=e=>{const n=function(e){if("string"!=typeof e||!e.startsWith(nA))return;const t=e.slice(6);return(r=t).startsWith("/")||/^[a-zA-Z]:[\\/]/.test(r)||r.startsWith("\\\\")?t:void 0;var r}(e);return void 0!==n?t.get(n)??e:Array.isArray(e)?e.map(r):null!==e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map((([e,t])=>[e,r(t)]))):e};return Object.fromEntries(Object.entries(e).map((([e,t])=>[e,r(t)])))}(Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()]))),u),h=t.clone();return h.args=Object.fromEntries(Object.entries(d).map((([e,t])=>[e,we.Value.fromJson(t)]))),h.symbolicPathArguments=[],h.argumentsRepaired=!1,oA.increment(e,1,{route:r,outcome:"expanded"}),sA.record(e,l,{route:r}),aA.record(e,i.length,{route:r}),{kind:"expanded",expansion:{args:h,files:[...c].map((([e,t])=>({path:e,bytes:t.bytes}))),paths:i.length,bytes:l}}}const mA=/\b413\b|payload too large|request entity too large|body.*too large|too large.*body|ECONNRESET|EPIPE|socket hang up|max(?:imum)? (?:body|payload|request|content) (?:size|length)/i;function gA(e,t,r,n){return mA.test(t)?(oA.increment(e,1,{route:n,outcome:"server_rejected_body"}),`${t}\n\nThe request carried ${r.bytes} bytes of file contents substituted from ${r.paths} "${nA}/abs/path" argument(s), and the server appears to have rejected the request body as too large. Do not retry the same call: pass a smaller file or a range of it, or use a tool that accepts a path or upload instead.`):t}function wA(e){return e.files.map((e=>`"${nA}${e.path}" was replaced with the contents of ${e.path} (${e.bytes} bytes) before the call.`)).join("\n")}class yA{constructor(e,t,r={}){this.inner=e,this.getReadExecutor=t,this.options=r}isBackendRouted(e){return this.inner.isBackendRouted?.(e)??!1}async execute(e,t,r){if(0===t.symbolicPathArguments.length)return this.inner.execute(e,t,r);const n=await fA(e,t,{route:"local",getReadExecutor:this.getReadExecutor,refuseSavedSecrets:!0===this.options.refuseSavedSecrets&&t.refuseSavedSecrets});if("none"===n.kind)return this.inner.execute(e,t,r);if("failed"===n.kind)return n.result;let o;try{o=await this.inner.execute(e,n.expansion.args,r)}catch(t){throw t instanceof Error&&(t.message=gA(e,t.message,n.expansion,"local")),t}return function(e,t,r){const n=t.clone();return"success"===n.result.case?n.result.value.content.push(new Ac._Z({content:{case:"text",value:new Ac.zN({text:wA(r)})}})):"error"===n.result.case&&(n.result.value.error=gA(e,n.result.value.error,r,"local")),n}(e,o,n.expansion)}}const vA=q("background-shell-executor",(e=>new B(e,Z("backgroundShellSpawnArgs"),X("backgroundShellSpawnResult"))),((e,t)=>{t.register(new I(e,Y("backgroundShellSpawnArgs"),Q("backgroundShellSpawnResult")))})),bA=q("write-background-shell-input-executor",(e=>new B(e,Z("writeShellStdinArgs"),X("writeShellStdinResult"))),((e,t)=>{t.register(new I(e,Y("writeShellStdinArgs"),Q("writeShellStdinResult")))})),SA=q("agent-store-conflict-executor",(e=>new B(e,Z("agentStoreConflictArgs"),X("agentStoreConflictResult"))),((e,t)=>{t.register(new I(e,Y("agentStoreConflictArgs"),Q("agentStoreConflictResult")))})),kA=q("shell-allowlist-precheck-executor",(e=>new B(e,Z("shellAllowlistPrecheckArgs"),X("shellAllowlistPrecheckResult"))),((e,t)=>{t.register(new I(e,Y("shellAllowlistPrecheckArgs"),Q("shellAllowlistPrecheckResult")))})),_A=q("mcp-allowlist-precheck-executor",(e=>new B(e,Z("mcpAllowlistPrecheckArgs"),X("mcpAllowlistPrecheckResult"))),((e,t)=>{t.register(new I(e,Y("mcpAllowlistPrecheckArgs"),Q("mcpAllowlistPrecheckResult")))})),CA=q("web-fetch-allowlist-precheck-executor",(e=>new B(e,Z("webFetchAllowlistPrecheckArgs"),X("webFetchAllowlistPrecheckResult"))),((e,t)=>{t.register(new I(e,Y("webFetchAllowlistPrecheckArgs"),Q("webFetchAllowlistPrecheckResult")))})),EA=q("force-background-shell-executor",(e=>new B(e,Z("forceBackgroundShellArgs"),X("forceBackgroundShellResult"))),((e,t)=>{t.register(new I(e,Y("forceBackgroundShellArgs"),Q("forceBackgroundShellResult")))})),xA=q("computer-use-executor",(e=>new B(e,Z("computerUseArgs"),X("computerUseResult"))),((e,t)=>{t.register(new I(e,Y("computerUseArgs"),Q("computerUseResult")))})),PA=q("computer-use-end-turn-executor",(e=>new B(function(e){return{createExecInstance:(t,r)=>e.createExecInstance(t,(e=>{if(t.signal.aborted)throw new Error("computer-use turn end not sent: its caller stopped waiting");return r(e)}))}}(e),Z("computerUseEndTurnArgs"),X("computerUseEndTurnResult"))),((e,t)=>{t.register(new I(e,Y("computerUseEndTurnArgs"),Q("computerUseEndTurnResult")))})),RA=q("record-screen-executor",(e=>new B(e,Z("recordScreenArgs"),X("recordScreenResult"))),((e,t)=>{t.register(new I(e,Y("recordScreenArgs"),Q("recordScreenResult")))}));var IA=r("../proto/dist/generated/agent/v1/agent_store_conflict_exec_pb.js");function TA(e){if(void 0!==e)return{journalEpoch:e.journalEpoch,seq:Number(e.seq),lastEventId:e.lastEventId}}class AA{constructor(e){this.drainer=e}async execute(e,t){try{void 0!==t.includeQuotaNotices&&this.drainer.setIncludeQuotaNoticesOverride(t.includeQuotaNotices);const e=await this.drainer.drain({cursor:TA(t.cursor),advance:!1!==t.advance});return new IA.Ev({result:{case:"success",value:new IA.iS({events:e.events.map((e=>new IA.RZ({v:e.v,eventId:e.event_id,journalEpoch:e.journal_epoch,seq:BigInt(e.seq),tsMs:BigInt(e.ts_ms),kind:e.kind,storeId:e.store_id,originalRelPath:e.original_rel_path,conflictRelPath:e.conflict_rel_path,originalAbsPath:e.original_abs_path,conflictAbsPath:e.conflict_abs_path,preservedBytes:void 0===e.preserved_bytes?void 0:BigInt(e.preserved_bytes),scopeKind:e.scope_kind,limitBytes:void 0===e.limit_bytes?void 0:BigInt(e.limit_bytes),usageBytes:void 0===e.usage_bytes?void 0:BigInt(e.usage_bytes)}))),nextCursor:(r=e.nextCursor,new IA.LK({journalEpoch:r.journalEpoch,seq:BigInt(r.seq),lastEventId:r.lastEventId})),gap:e.gap})}})}catch(e){return new IA.Ev({result:{case:"error",value:new IA.h6({error:e instanceof Error?e.message:String(e)})}})}var r}}class $A{constructor(e){this.shellStdinWriter=e}async execute(e,t){const r=t.shellId;try{await this.shellStdinWriter(r,t.chars)}catch(e){return new Do.nt({result:{case:"error",value:new Do.Gv({error:`Failed to write to shell ${r} stdin: ${e instanceof Error?e.message:"Unknown error"}`})}})}return new Do.nt({result:{case:"success",value:new Do.tR({shellId:r,terminalFileLengthBeforeInputWritten:0})}})}}var MA=r("../proto/dist/generated/agent/v1/canvas_diagnostics_exec_pb.js"),DA=r("../proto/dist/generated/agent/v1/diagnostics_exec_pb.js");class OA{constructor(e,t){this.getCanvasDiagnostics=e,this.beginCanvasSave=t}async execute(e,t){let r=()=>{};const n=new Promise((e=>{r=e}));let o;if(void 0===this.beginCanvasSave)o=Promise.resolve(void 0);else try{o=this.beginCanvasSave(t.path,{typecheckOutcome:n}).catch((()=>{}))}catch{o=Promise.resolve(void 0)}try{const e=await this.getCanvasDiagnostics(t.path);return void 0===e?(r("unavailable"),FA(NA(t.path,"diagnostics unavailable"),await o)):(r(e.some((e=>1===e.severity))?"failed":"passed"),FA(new MA.GL({result:{case:"success",value:new MA.uX({path:t.path,diagnostics:e.map(LA)})}}),await o))}catch(e){return r("unavailable"),FA(NA(t.path,e instanceof Error?e.message:String(e)),await o)}}}function FA(e,t){return void 0===t||(e.saveState=t.saveState,e.canvasId=t.canvasId,e.title=t.title,e.saveDetail=t.saveDetail),e}function NA(e,t){return new MA.GL({result:{case:"error",value:new MA.HW({path:e,error:t})}})}function LA(e){return new DA.oQ({severity:jA(e.severity),range:new Dc.Q6({start:new Dc.yX({line:e.range.start.line+1,column:e.range.start.character+1}),end:new Dc.yX({line:e.range.end.line+1,column:e.range.end.character+1})}),message:e.message,source:"ts",code:e.code??""})}function jA(e){switch(e){case 1:return DA.h_.ERROR;case 2:return DA.h_.WARNING;case 3:return DA.h_.INFORMATION;case 4:return DA.h_.HINT;default:return DA.h_.UNSPECIFIED}}class UA{constructor(e){if(e.startsWith("file://")){if(!this.isValidFileUrl(e))throw new Error(`Invalid file URL: ${e}`);this.urlString=e}else{const t=this.resolvePath(e);this.urlString=this.pathToFileUrl(t)}}isValidFileUrl(e){try{return"file:"===new URL(e).protocol}catch{return!1}}resolvePath(e){if(e.includes("\\")&&(e=e.replace(/\\/g,"/")),/^[a-zA-Z]:\//.test(e)||/^\//.test(e))return e;const t=e.split("/"),r=[];for(let e=0;ethis.convertDiagnostic(e)));return new DA.Ek({result:{case:"success",value:new DA.a1({path:t.path,diagnostics:s,totalDiagnostics:s.length})}})}catch(r){return e.canceled?new DA.Ek({result:{case:"error",value:new DA.Ho({path:t.path,error:"Request timed out after 10 seconds"})}}):new DA.Ek({result:{case:"error",value:new DA.Ho({path:t.path,error:r instanceof Error?r.message:String(r)})}})}finally{n()}}catch(e){r.error=e,r.hasError=!0}finally{BA(r)}}convertDiagnostic(e){const t=e.message,r="string"==typeof t?t:t&&"object"==typeof t&&"value"in t&&"string"==typeof t.value?t.value:"";return new DA.oQ({severity:this.convertSeverity(e.severity),range:e.range?new Dc.Q6({start:new Dc.yX({line:e.range.start.line,column:e.range.start.character}),end:new Dc.yX({line:e.range.end.line,column:e.range.end.character})}):void 0,message:r,source:e.source,code:e.code?String(e.code):void 0})}convertSeverity(e){switch(e){case 1:return DA.h_.ERROR;case 2:return DA.h_.WARNING;case 3:return DA.h_.INFORMATION;case 4:return DA.h_.HINT;default:return DA.h_.UNSPECIFIED}}}async function HA(e){const{repoRoot:t,filePaths:r,getContent:n}=e,o=new Map;if(0===r.length)return o;const s=await async function(e,t){const r=new Map;if(0===t.length)return r;try{const{stdout:n}=await vy().run(e,["check-attr","linguist-generated","--stdin"],{input:`${t.join("\n")}\n`});for(const e of n.trim().split("\n")){const t=e.match(/^(.+): linguist-generated: (.+)$/);if(t){const e=t[1],n=t[2];"true"===n||"set"===n?r.set(e,!0):"false"!==n&&"unset"!==n||r.set(e,!1)}}}catch{}return r}(t,r);return await Promise.all(r.map((async e=>{const t=s.get(e);if(!0!==t)if(!1!==t)if(function(e){return new qA(e).isGeneratedByPath()}(e))o.set(e,{isGenerated:!0,source:"path-heuristic"});else{if(n){const t=await n(e);if(void 0!==t&&function(e,t){return new qA(e,(()=>t)).isGeneratedByContent()}(e,t))return void o.set(e,{isGenerated:!0,source:"content-heuristic"})}o.set(e,{isGenerated:!1,source:"none"})}else o.set(e,{isGenerated:!1,source:"gitattributes"});else o.set(e,{isGenerated:!0,source:"gitattributes"})}))),o}class qA{constructor(e,t){this.name=e,this.extname=s.extname(e).toLowerCase(),this.getContent=t}get lines(){if(void 0===this.cachedLines){const e=this.getContent?.();this.cachedLines=e?e.split("\n"):[]}return this.cachedLines}get data(){return this.getContent?.()}isGeneratedByPath(){return this.xcodeFile()||this.intellijFile()||this.cocoapods()||this.carthageBuild()||this.generatedGraphqlRelay()||this.generatedNetDesignerFile()||this.generatedNetSpecflowFeatureFile()||this.composerLock()||this.cargoLock()||this.cargoOrig()||this.denoLock()||this.flakeLock()||this.bazelLock()||this.nodeModules()||this.goVendor()||this.goLock()||this.packageResolved()||this.poetryLock()||this.pdmLock()||this.uvLock()||this.pixiLock()||this.esyLock()||this.npmShrinkwrapOrPackageLock()||this.pnpmLock()||this.bunLock()||this.terraformLock()||this.generatedYarnPlugnplay()||this.godeps()||this.generatedByZephir()||this.htmlcov()||this.gradleWrapper()||this.mavenWrapper()||this.pipenvLock()||this.generatedPascalTlb()||this.generatedSqlxQuery()||this.sourceMapByName()}isGeneratedByContent(){return!!this.getContent&&(this.minifiedFiles()||this.hasSourceMap()||this.sourceMap()||this.compiledCoffeescript()||this.generatedParser()||this.generatedNetDocfile()||this.generatedPostscript()||this.compiledCythonFile()||this.generatedGo()||this.generatedProtocolBufferFromGo()||this.generatedProtocolBuffer()||this.generatedJavascriptProtocolBuffer()||this.generatedTypescriptProtocolBuffer()||this.generatedApacheThrift()||this.generatedJniHeader()||this.vcrCassette()||this.generatedAntlr()||this.generatedModule()||this.generatedUnity3dMeta()||this.generatedRacc()||this.generatedJflex()||this.generatedGrammarkit()||this.generatedRoxygen2()||this.generatedHtml()||this.generatedJison()||this.generatedGrpcCpp()||this.generatedDart()||this.generatedPerlPpportHeader()||this.generatedGamemakerstudio()||this.generatedGimp()||this.generatedVisualstudio6()||this.generatedHaxe()||this.generatedJooq()||this.generatedSorbetRbi()||this.generatedMysqlViewDefinitionFormat())}xcodeFile(){return[".nib",".xcworkspacedata",".xcuserstate"].includes(this.extname)}intellijFile(){return/(?:^|\/)\.idea\//.test(this.name)}cocoapods(){return/(^Pods|\/Pods)\//.test(this.name)}carthageBuild(){return/(^|\/)Carthage\/Build\//.test(this.name)}generatedGraphqlRelay(){return/__generated__\//.test(this.name)}generatedNetDesignerFile(){return/\.designer\.(cs|vb)$/i.test(this.name)}generatedNetSpecflowFeatureFile(){return/\.feature\.cs$/i.test(this.name)}composerLock(){return/composer\.lock/.test(this.name)}cargoLock(){return/Cargo\.lock/.test(this.name)}cargoOrig(){return/Cargo\.toml\.orig/.test(this.name)}denoLock(){return/deno\.lock/.test(this.name)}flakeLock(){return/(^|\/)flake\.lock$/.test(this.name)}bazelLock(){return/(^|\/)MODULE\.bazel\.lock$/.test(this.name)}nodeModules(){return/node_modules\//.test(this.name)}goVendor(){return/vendor\/((?!-)[-0-9A-Za-z]+(?e+t.length),0)/this.lines.length>110}hasSourceMap(){return!!this.maybeMinified()&&this.lines.slice(-2).some((e=>/^\/[*/][#@] source(?:Mapping)?URL|sourceURL=/.test(e)))}sourceMap(){if(".map"!==this.extname)return!1;if(/\.(css|js)\.map$/i.test(this.name))return!0;const e=this.lines[0]||"";return/^{"version":\d+,/.test(e)||/^\/\*\* Begin line maps\. \*\*\/{/.test(e)}compiledCoffeescript(){if(".js"!==this.extname)return!1;const e=this.lines[0]||"";if(/^\/\/ Generated by /.test(e))return!0;if("(function() {"===e&&"}).call(this);"===(this.lines[this.lines.length-2]||"")&&""===(this.lines[this.lines.length-1]||"")){let e=0;for(const t of this.lines)if(/var /.test(t)){const r=t.match(/_fn|_i|_len|_ref|_results/g);e+=1*(r?.length||0);const n=t.match(/__bind|__extends|__hasProp|__indexOf|__slice/g);e+=3*(n?.length||0)}return e>=3}return!1}generatedNetDocfile(){return".xml"===this.extname&&!(this.lines.length<=3)&&(this.lines[1]||"").includes("")&&(this.lines[2]||"").includes("")&&(this.lines[this.lines.length-2]||"").includes("")}generatedParser(){if(".js"!==this.extname)return!1;const e=this.lines.slice(0,5).join("");return/^(?:[^/]|\/[^*])*\/\*(?:[^*]|\*[^/])*Generated by PEG\.js/.test(e)}generatedPostscript(){if(![".ps",".eps",".pfa"].includes(this.extname))return!1;const e=this.data;if(!e)return!1;if(/^\s*(?:currentfile eexec\s+|\/sfnts\s+\[\s<)/.test(e))return!0;const t=this.lines.slice(0,10).find((e=>/^%%Creator: /.test(e)));return!!t&&(!(!/[0-9]|draw|mpage|ImageMagick|inkscape|MATLAB/.test(t)&&!/PCBNEW|pnmtops|\(Unknown\)|Serif Affinity|Filterimage -tops/.test(t))||!!t.includes("EAGLE")&&this.lines.slice(0,5).some((e=>/^%%Title: EAGLE Drawing /.test(e))))}generatedGo(){return".go"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,40).some((e=>/^\/\/ Code generated .*/.test(e)))}generatedProtocolBufferFromGo(){return".proto"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,20).some((e=>e.includes("This file was autogenerated by go-to-protobuf")))}generatedProtocolBuffer(){return!![".py",".java",".h",".cc",".cpp",".m",".rb",".php"].includes(this.extname)&&!(this.lines.length<=1)&&this.lines.slice(0,3).some((e=>e.includes("Generated by the protocol buffer compiler. DO NOT EDIT!")))}generatedJavascriptProtocolBuffer(){return".js"===this.extname&&!(this.lines.length<=6)&&(this.lines[5]||"").includes("GENERATED CODE -- DO NOT EDIT!")}generatedTypescriptProtocolBuffer(){return".ts"===this.extname&&!(this.lines.length<=4)&&(this.lines[0]||"").includes("Code generated by protoc-gen-ts_proto. DO NOT EDIT.")}generatedApacheThrift(){return!![".rb",".py",".go",".js",".m",".java",".h",".cc",".cpp",".php"].includes(this.extname)&&this.lines.slice(0,6).some((e=>e.includes("Autogenerated by Thrift Compiler")))}generatedJniHeader(){return".h"===this.extname&&!(this.lines.length<=2)&&(this.lines[0]||"").includes("/* DO NOT EDIT THIS FILE - it is machine generated */")&&(this.lines[1]||"").includes("#include ")}vcrCassette(){return".yml"===this.extname&&!(this.lines.length<=2)&&(this.lines[this.lines.length-2]||"").includes("recorded_with: VCR")}generatedAntlr(){return".g"===this.extname&&!(this.lines.length<=2)&&(this.lines[1]||"").includes("generated by Xtest")}compiledCythonFile(){return!![".c",".cpp"].includes(this.extname)&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("Generated by Cython")}generatedModule(){if(".mod"!==this.extname)return!1;if(this.lines.length<=1)return!1;const e=this.lines[0]||"";return e.includes("PCBNEW-LibModule-V")||e.includes("GFORTRAN module version '")}generatedUnity3dMeta(){return".meta"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("fileFormatVersion: ")}generatedRacc(){return".rb"===this.extname&&!(this.lines.length<=2)&&(this.lines[2]||"").startsWith("# This file is automatically generated by Racc")}generatedJflex(){return".java"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("/* The following code was generated by JFlex ")}generatedGrammarkit(){return".java"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("// This is a generated file. Not intended for manual editing.")}generatedRoxygen2(){return".rd"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("% Generated by roxygen2: do not edit by hand")}generatedHtml(){if(![".html",".htm",".xhtml"].includes(this.extname))return!1;if(this.lines.length<=1)return!1;if(this.lines.slice(0,2).some((e=>//.test(e))))return!0;if(this.lines.length>2&&(this.lines[2]||"").startsWith("\x3c!-- This is an automatically generated file."))return!0;if(this.lines.slice(0,31).some((e=>//i.test(e))))return!0;const e=this.lines.slice(0,31).join(" ").match(/]+)>/gi);if(!e)return!1;for(const t of e){const e=this.extractHtmlMeta(t);if("generator"===e.name?.toLowerCase()&&(e.content||e.value)){const t=e.content||e.value||"";if(/^(org\s+mode|j?latex2html|groff|makeinfo|texi2html|ronn)\b/i.test(t))return!0}}return!1}extractHtmlMeta(e){const t={},r=e.matchAll(/(?<=^|\s)(name|content|value)\s*=\s*("[^"]+"|'[^']+'|[^\s"']+)/gi);for(const e of r){const r=e[1].toLowerCase();let n=e[2];(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'"))&&(n=n.slice(1,-1)),t[r]=n}return t}generatedJison(){if(".js"!==this.extname)return!1;if(this.lines.length<=1)return!1;const e=this.lines[0]||"";return e.startsWith("/* parser generated by jison ")||e.startsWith("/* generated by jison-lex ")}generatedGrpcCpp(){return!![".cpp",".hpp",".h",".cc"].includes(this.extname)&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("// Generated by the gRPC")}generatedDart(){return".dart"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,3).some((e=>/generated code\W{2,3}do not modify/i.test(e)))}generatedPerlPpportHeader(){return!!/ppport\.h$/.test(this.name)&&!(this.lines.length<=10)&&(this.lines[8]||"").includes("Automatically created by Devel::PPPort")}generatedGamemakerstudio(){if(![".yy",".yyp"].includes(this.extname))return!1;if(this.lines.length<=3)return!1;const e=this.lines.slice(0,3).join("");return/^\s*[{[]/.test(e)||/^\d\.\d\.\d.+\|\{/.test(this.lines[0]||"")}generatedGimp(){if(![".c",".h"].includes(this.extname))return!1;if(0===this.lines.length)return!1;const e=this.lines[0]||"";return/^\/\* GIMP [a-zA-Z0-9- ]+ C-Source image dump \(.+?\.c\) \*\//.test(e)||/^\/\* {2}GIMP header image file format \([a-zA-Z0-9- ]+\): .+?\.h {2}\*\//.test(e)}generatedVisualstudio6(){return".dsp"===this.extname&&this.lines.slice(0,3).some((e=>e.includes("# Microsoft Developer Studio Generated Build File")))}generatedHaxe(){return!![".js",".py",".lua",".cpp",".h",".java",".cs",".php"].includes(this.extname)&&this.lines.slice(0,3).some((e=>e.includes("Generated by Haxe")))}generatedJooq(){return".java"===this.extname&&this.lines.slice(0,2).some((e=>e.includes("This file is generated by jOOQ.")))}generatedSorbetRbi(){return".rbi"===this.extname&&!(this.lines.length<5)&&/^# typed:/.test(this.lines[0]||"")&&(this.lines[2]||"").includes("DO NOT EDIT MANUALLY")&&/^# Please (run|instead update this file by running) `bin\/tapioca/.test(this.lines[4]||"")}generatedMysqlViewDefinitionFormat(){return".frm"===this.extname&&(this.lines[0]||"").includes("TYPE=VIEW")}}const zA=e=>{if(!e)return[];if("string"!=typeof e||e.match(/^\s+$/))return[];const t=e.split("\n");if(0===t.length)return[];const r=[];let n=null,o=null,s=0,i=0,a=null;const c=e=>{o?.changes.push({type:"normal",normal:!0,ln1:s++,ln2:i++,content:e}),a.oldLines--,a.newLines--},l=e=>{const[t,o]=KA(e)??[];n={chunks:[],deletions:0,additions:0,from:t,to:o},r.push(n)},u=()=>{n&&!n.chunks.length||l()},d=e=>+(e||1),h=e=>{o&&(o.changes.push({type:"del",del:!0,ln:s++,content:e}),n.deletions++,a.oldLines--)},p=e=>{o&&(o.changes.push({type:"add",add:!0,ln:i++,content:e}),n.additions++,a.newLines--)},f=e=>{if(!o)return;const[t]=o.changes.slice(-1);o.changes.push({type:t.type,[t.type]:!0,ln1:t.ln1,ln2:t.ln2,ln:t.ln,content:e})},m=[[/^diff\s/,l],[/^new file mode (\d+)$/,(e,t)=>{u(),n.new=!0,n.newMode=t[1],n.from="/dev/null"}],[/^deleted file mode (\d+)$/,(e,t)=>{u(),n.deleted=!0,n.oldMode=t[1],n.to="/dev/null"}],[/^old mode (\d+)$/,(e,t)=>{u(),n.oldMode=t[1]}],[/^new mode (\d+)$/,(e,t)=>{u(),n.newMode=t[1]}],[/^index\s[\da-zA-Z]+\.\.[\da-zA-Z]+(\s(\d+))?$/,(e,t)=>{u(),n.index=e.split(" ").slice(1),t[1]&&(n.oldMode=n.newMode=t[1].trim())}],[/^---\s/,e=>{u(),n.from=ZA(e)}],[/^\+\+\+\s/,e=>{u(),n.to=ZA(e)}],[/^@@\s+-(\d+),?(\d+)?\s+\+(\d+),?(\d+)?\s@@/,(e,t)=>{n||l(e);const[r,c,u,h]=t.slice(1);s=+r,i=+u,o={content:e,changes:[],oldStart:+r,oldLines:d(c),newStart:+u,newLines:d(h)},a={oldLines:d(c),newLines:d(h)},n.chunks.push(o)}],[/^\\ No newline at end of file$/,f]],g=[[/^\\ No newline at end of file$/,f],[/^-/,h],[/^\+/,p],[/^\s+/,c]],w=e=>{a?(e=>{const t=e.charCodeAt(0);if(43===t)p(e);else if(45===t)h(e);else if(32===t)c(e);else if(92===t&&/^\\ No newline at end of file$/.test(e))f(e);else for(const[t,r]of g){const n=e.match(t);if(n){r(e,n);break}}0===a.oldLines&&0===a.newLines&&(a=null)})(e):(e=>{for(const[t,r]of m){const n=e.match(t);if(n){r(e,n);break}}})(e)};for(const e of t)w(e);return r},GA=/(a|i|w|c|o|1|2)\/.*(?=["']? ["']?(b|i|w|c|o|1|2)\/)|(b|i|w|c|o|1|2)\/.*$/g,VA=/^(a|b|i|w|c|o|1|2)\//,KA=e=>{const t=e?.match(GA);return t?.map((e=>e.replace(VA,"").replace(/("|')$/,"")))},JA=/^\\?['"]|\\?['"]$/g,ZA=e=>{let t=XA(e,"-+").trim();return t=YA(t),t.replace(JA,"").replace(VA,"")},XA=(e,t)=>{if(e=t$(e),!t&&String.prototype.trimLeft)return e.trimLeft();const r=e$(t);return e.replace(new RegExp(`^${r}+`),"")},QA=/\t.*|\d{4}-\d\d-\d\d\s\d\d:\d\d:\d\d(.\d+)?\s(\+|-)\d\d\d\d/,YA=e=>{const t=QA.exec(e);return t&&(e=e.substring(0,t.index).trim()),e},e$=e=>null==e?"\\s":e instanceof RegExp?e.source:`[${t$(e).replace(/([.*+?^=!:${}()|[\]/\\])/g,"\\$1")}]`,t$=e=>`${e??""}`,r$=(0,l.h)("local-mercurial-diff"),n$=5242880,o$="0000000000000000000000000000000000000000";let s$,i$;async function a$(e,t,r={}){const n=await async function(){if(void 0===s$&&(s$=await async function(e){const t="win32"===process.platform?["hg.com","hg.exe"]:["hg"];for(const r of e.split(s.default.delimiter))if(s.default.isAbsolute(r))for(const e of t){const t=s.default.join(r,e);try{if(!(await Co.stat(t)).isFile())continue;return"win32"!==process.platform&&await Co.access(t,xo.constants.X_OK),t}catch{}}}(process.env.PATH??"")??null),null===s$){const e=new Error("hg executable not found");throw e.code="ENOENT",e}return s$}(),o=await new Promise(((o,s)=>{const i=(0,ou.spawn)(n,t,{cwd:e,env:{...process.env,HGPLAIN:"+strictflags",HGRCPATH:"",HGRCSKIPREPO:"1"},shell:!1}),a=new ia.StringDecoder("utf8");let c="";i.stdout.on("data",(e=>{c+=a.write(e)})),i.stderr.on("data",(()=>{})),i.on("error",(e=>{!0===r.allowFailure?o(""):s(e)})),i.on("close",(e=>{if(0===e||!0===r.allowFailure)o(c+a.end());else{const r=t.find((e=>!e.startsWith("-")))??"hg";s(new Error(`MercurialDiffFailed: hg ${r} exited ${e??"unknown"}`))}}))}));return o}async function c$(e){const t=await async function(e){let t=s.default.resolve(e);for(;;){try{if((await Co.stat(s.default.join(t,".hg"))).isDirectory())return!0}catch{}const e=s.default.dirname(t);if(e===t)return!1;t=e}}(e);if(!t)return;const r=function(e,t){return e&&"absent"!==t?"skips-repo-config"!==t?"unsafe":"proceed":"not-mercurial"}(t,await async function(){if(void 0!==i$)return i$;const e=await Co.mkdtemp(s.default.join((0,o.tmpdir)(),"hg-probe-"));try{const t=await a$(e,["help","environment"]);i$=/\bHGRCSKIPREPO\b/.test(t)?"skips-repo-config":"reads-repo-config"}catch(e){i$=function(e){return"object"==typeof e&&null!==e&&"code"in e&&"ENOENT"===e.code}(e)?"absent":"reads-repo-config"}finally{await Co.rm(e,{recursive:!0,force:!0})}return i$}());if("not-mercurial"===r)return;if("unsafe"===r)throw new Error("MercurialClientUnsafe: hg would read repository config");let n;try{n=(await a$(e,["root"])).trim()}catch{return}if(0!==n.length)try{return(await Co.stat(s.default.join(n,".hg"))).isDirectory()?n:void 0}catch{return}}function l$(e,t){return"win32"===process.platform?s.default.win32.normalize(e).toLowerCase()===s.default.win32.normalize(t).toLowerCase():s.default.resolve(e)===s.default.resolve(t)}function u$(e,t){const r=s.default.relative(s.default.resolve(t),s.default.resolve(e));return 0===r.length||!s.default.isAbsolute(r)&&!r.split(s.default.sep).includes("..")}async function d$(e){const t=s.default.resolve(e);try{return await Co.realpath(t)}catch{return t}}function h$(e){if(0===e.length)return[];const t=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),r=t.split("\n");return t.endsWith("\n")&&r.pop(),r}function p$(e){if(e.includes("\0")||/[\r\n]/.test(e))throw new Error("MercurialDiffFailed: base ref contains a newline")}async function f$({repositoryRoot:e,rev:t,filePath:r}){const n=await async function({repositoryRoot:e,rev:t,filePath:r}){let n;try{n=await a$(e,["files","-r",t,"-T","{size}","--",r])}catch{return}const o=n.trim();if(!/^\d+$/.test(o))return;const s=Number(o);return Number.isFinite(s)?s:void 0}({repositoryRoot:e,rev:t,filePath:r});return void 0===n||n>n$?"":a$(e,["cat","-r",t,"--",r])}async function m$(e,t,r){const n=function(e){switch(e){case Le.ek.NAME_STATUS:return Le.ek.NAME_STATUS;case Le.ek.NAME_STATUS_AND_NUMSTAT:return Le.ek.NAME_STATUS_AND_NUMSTAT;case Le.ek.FILE_DIFFS:return Le.ek.FILE_DIFFS;case Le.ek.DIFFS_WITH_BEFORE_AND_AFTER:return Le.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return Le.ek.FILE_DIFFS}}(r.outputFormat),o=["root"],i=(await a$(t,["root"])).trim();if(0===i.length)throw new Error("MercurialDiffFailed: hg root did not resolve");let a,c;if(0!==r.ref.length||"HEAD"!==r.baseRef&&(r.mergeBase||0!==r.baseRef.length)){if(r.mergeBase||0===r.baseRef.length)a=await async function({cwd:e,baseRef:t,commands:r}){if(t.length>0&&"HEAD"!==t){p$(t),r.push("log");const n=(await a$(e,["log","-r",`ancestor(., (${t}))`,"-T","{node}"])).trim();if(0===n.length||n===o$)throw new Error("MercurialDiffFailed: base ref did not resolve");return n}r.push("log");const n=(await a$(e,["log","-r","max(::. and public())","-T","{node}"],{allowFailure:!0})).trim();if(n.length>0&&n!==o$)return n;const o=(await a$(e,["log","-r","ancestor(., default)","-T","{node}"],{allowFailure:!0})).trim();if(o.length>0&&o!==o$)return o;const s=(await a$(e,["log","-r",".","-T","{node}"],{allowFailure:!0})).trim();return s.length>0?s:o$}({cwd:t,baseRef:r.baseRef,commands:o});else if(p$(r.baseRef),o.push("log"),a=(await a$(t,["log","-r",r.baseRef,"-T","{node}"])).trim(),0===a.length)throw new Error("MercurialDiffFailed: base ref did not resolve");r.ref.length>0&&(p$(r.ref),o.push("log"),c=(await a$(t,["log","-r",r.ref,"-T","{node}"])).trim())}const l=["diff","--git"];r.includeSpaceChanges||l.push("-b"),void 0!==r.unifiedContextLines&&l.push(`-U${r.unifiedContextLines}`),void 0!==a&&l.push("-r",a),void 0!==c&&l.push("-r",c),r.targetPaths.length>0&&l.push("--",...r.targetPaths),o.push("diff");const u=await a$(t,l),d=function(e){const t=e.replace(/\r\n/g,"\n");return new Le.o$({diffs:zA(t).map((e=>function(e){const t=new Le.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new Le.Ei({content:e.content,lines:e.changes.map((e=>e.content)),oldStart:e.oldStart,oldLines:e.oldLines,newStart:e.newStart,newLines:e.newLines})))});return t.added=e.additions,t.removed=e.deletions,t}(e))),diffType:Le.Wf.UNSPECIFIED})}(u);let h=[];if(r.maxUntrackedFiles>0&&(o.push("status"),h=await async function({cwd:e,repositoryRoot:t,maxUnknownFiles:r}){let n=(await a$(e,["status","-un0"])).split("\0").filter((e=>e.length>0));return n.length>r&&(n=n.slice(0,r)),(await Promise.all(n.map((async e=>{try{const r=s.default.join(t,e),n=await Co.stat(r);if(n.size>n$){const t=await async function(e){const t=(0,bo.createHash)("sha256"),r=await Co.open(e,"r");try{const e=Buffer.alloc(65536);let n=0;for(;;){const{bytesRead:o}=await r.read(e,0,e.length,n);if(0===o)break;t.update(e.subarray(0,o)),n+=o}}finally{await r.close()}return t.digest("hex")}(r);return{contents:"",path:e,omittedDueToSize:!0,byteSize:n.size,contentHash:t}}return{contents:await Co.readFile(r,"utf8"),path:e}}catch{return}})))).filter((e=>void 0!==e))}({cwd:t,repositoryRoot:i,maxUnknownFiles:r.maxUntrackedFiles}),d.diffs.push(...h.map((e=>function(e){if(!0===e.omittedDueToSize)return new Le.QP({from:"/dev/null",to:e.path,chunks:[],added:0,removed:0});const t=h$(e.contents);if(0===t.length)return new Le.QP({from:"/dev/null",to:e.path,chunks:[],added:0,removed:0});const r=t.length;return new Le.QP({from:"/dev/null",to:e.path,chunks:[new Le.Ei({content:`@@ -0,0 +1${1===r?"":`,${r}`} @@`,lines:t.map((e=>`+${e}`)),oldStart:0,oldLines:0,newStart:1,newLines:r})],added:r,removed:0})}(e))))),n!==Le.ek.FILE_DIFFS)for(const e of d.diffs)e.chunks=[];if(n===Le.ek.DIFFS_WITH_BEFORE_AND_AFTER){const e=a??".";await Promise.all(d.diffs.map((async t=>{if("/dev/null"!==t.from)try{t.beforeFileContents=await f$({repositoryRoot:i,rev:e,filePath:t.from})}catch{t.beforeFileContents=""}else t.beforeFileContents="";if("/dev/null"!==t.to)if(void 0===c)try{const e=s.default.join(i,t.to),r=await Co.stat(e);t.afterFileContents=r.size>n$?"":await Co.readFile(e,"utf8")}catch{t.afterFileContents=""}else try{t.afterFileContents=await f$({repositoryRoot:i,rev:c,filePath:t.to})}catch{t.afterFileContents=""}else t.afterFileContents=""})))}const p=[u,function(e){const t=[];for(const r of e){const e=h$(r.contents);if(t.push(`diff --git a/${r.path} b/${r.path}`),t.push("new file mode 100644"),t.push("--- /dev/null"),t.push(`+++ b/${r.path}`),0===e.length)continue;const n=e.length;t.push(`@@ -0,0 +1${1===n?"":`,${n}`} @@`),t.push(...e.map((e=>`+${e}`)))}return t.join("\n")}(h.filter((e=>!0!==e.omittedDueToSize))),h.filter((e=>!0===e.omittedDueToSize)).map((e=>`omitted-untracked ${e.byteSize??0} ${e.contentHash??""} ${JSON.stringify(e.path)}`)).join("\n")].filter((e=>e.length>0)).join("\n"),f=r.computePatchId?function(e){if(0!==e.length)return`hg:${(0,bo.createHash)("sha256").update(e).digest("hex")}`}(p.length>0?`${p}\n`:""):void 0;let m,g;if(!0===r.returnHeadSha){o.push("log","status");const e=(await a$(t,["log","-r",".","-T","{node}"],{allowFailure:!0})).trim();m=e.length>0?e:o$,g=(await a$(t,["status","-0"])).length>0}r$.info(e,"Local mercurial diff commands",{sourceControl:"mercurial",commands:o});const w=new Le.df({diff:d,submoduleDiffs:[],patchId:f,headSha:m,hasUncommittedChanges:g}),y=r.maxResponseBytes??0;if(y>0){const t=w.toBinary().byteLength;if(t>y)throw r$.info(e,"Local diff outcome",{sourceControl:"mercurial",outcome:"too_large"}),new Error(`GetDiffResponseTooLarge: ${t} bytes exceeds the ${y} byte limit`)}return r$.info(e,"Local diff outcome",{sourceControl:"mercurial",outcome:"ok",fileCount:d.diffs.length,patchIdPrefixed:!0===f?.startsWith("hg:")}),w}const g$=(0,l.h)("local-git-diff");function w$({exitCode:e,stderr:t}){return new Error(`Git command failed with code ${e}: ${t}`)}async function y$(e,t,r={}){let n;try{n=await e(t)}catch(e){if(!0===r.ignoreErrors)return"";throw e}if(0!==n.exitCode&&!0!==r.ignoreErrors)throw w$(n);return!0===r.shouldNotTrimOutput?n.stdout:n.stdout.trim()}function v$(e){const t=zA(e);return new Le.o$({diffs:t.map((e=>function(e){const t=new Le.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new Le.Ei({content:e.content,lines:e.changes.map((e=>e.content)),oldStart:e.oldStart,oldLines:e.oldLines,newStart:e.newStart,newLines:e.newLines})))});return t.added=e.additions,t.removed=e.deletions,t}(e))),diffType:Le.Wf.UNSPECIFIED})}function b$(e){const t=[];for(const n of e){const e={body:`+${(r=n.contents).replaceAll("\n","\n+")}`,numLines:Js(r)},o=1===e.numLines?"@@ -0,0 +1 @@":`@@ -0,0 +1,${e.numLines} @@`;t.push(`diff --git a/${n.path} b/${n.path}\n--- /dev/null\n+++ b/${n.path}\n${o}\n${e.body}`)}var r;return t.join("\n")}const S$=["main","master","develop"];async function k$(e,t){const r=s.default.join(e,t),n=await Co.lstat(r);if(n.isSymbolicLink())return{contents:await Co.readlink(r),path:t,isSymlink:!0};if(!n.isFile())throw new Error("Not a regular file or symlink");return{contents:await Co.readFile(r,"utf8"),path:t,isSymlink:!1}}async function _$(e,t,r){const n=vy(),o=(e,r)=>n.run(t,e,r),i=await async function(e,t){let r;try{const e=(await y$(t,["rev-parse","--show-toplevel"])).trim();e.length>0&&(r=e)}catch{}if(void 0!==r){const t=await async function({cwd:e,gitRoot:t}){const r=await d$(t);let n=await d$(e);if(l$(n,r))return;let o=!1;for(;u$(n,r)&&!l$(n,r);){try{if((await Co.stat(s.default.join(n,".hg"))).isDirectory()){o=!0;break}}catch{}const e=s.default.dirname(n);if(e===n)break;n=e}return o?c$(e):void 0}({cwd:e,gitRoot:r});return void 0!==t?"mercurial":"git"}return void 0===await c$(e)?"none":"mercurial"}(t,o);if(g$.info(e,"Local diff source control",{sourceControl:i}),"none"===i)throw g$.info(e,"Local diff outcome",{sourceControl:i,outcome:"no_version_control"}),new Error("NoVersionControl: no git or mercurial repository");if("mercurial"===i)return m$(e,t,r);const a=function(e){switch(e){case Le.ek.NAME_STATUS:return Le.ek.NAME_STATUS;case Le.ek.NAME_STATUS_AND_NUMSTAT:return Le.ek.NAME_STATUS_AND_NUMSTAT;case Le.ek.FILE_DIFFS:return Le.ek.FILE_DIFFS;case Le.ek.DIFFS_WITH_BEFORE_AND_AFTER:return Le.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return Le.ek.FILE_DIFFS}}(r.outputFormat),c=await(async()=>{let e=r.baseRef.length>0?r.baseRef:await async function(e){try{const t=await y$(e,["symbolic-ref","--short","refs/remotes/origin/HEAD"]);if(t)return t.trim()}catch{}for(const t of S$){const r=`origin/${t}`;try{return await y$(e,["rev-parse","--verify",r]),r}catch{}}try{const t=(await y$(e,["branch","-r"])).split("\n").map((e=>e.trim())).find((e=>e.startsWith("origin/")));if(t)return t}catch{}try{const t=await y$(e,["config","--get","init.defaultBranch"]);if(t)return t.trim()}catch{}throw new Error("Could not determine default branch")}(o);if(r.mergeBase){const t=r.ref.length>0?r.ref:"HEAD";e=(await y$(o,["merge-base","--end-of-options",e,t])).trim()}return e})(),l=["diff","--no-color"];r.includeSpaceChanges||l.push("--ignore-space-change"),void 0!==r.unifiedContextLines&&l.push(`-U${r.unifiedContextLines}`);const u=["--end-of-options",c];r.ref.length>0&&u.push(r.ref),r.targetPaths.length>0&&u.push("--",...r.targetPaths);const d=await o([...l,...u]);let h,p;if(0===d.exitCode)h=d.stdout,p=v$(h);else{const t=w$(d);if(r.computePatchId||!await async function(e){return(await y$(e,["config","--get-regexp","^(extensions\\.partialclone|remote\\..+\\.promisor)$"],{ignoreErrors:!0})).split("\n").some((e=>/^(extensions\.partialclone \S|remote\..+\.promisor( (true|yes|on|1))?$)/i.test(e)))}(o))throw t;p=await async function(e,t){const r=(await y$(e,["diff","--name-status","--no-renames","-z",...t])).split("\0"),n=[];for(let e=1;e{throw t})),g$.info(e,"Local diff outcome",{sourceControl:i,outcome:"partial_clone_names_only"})}let f=[];if(r.maxUntrackedFiles>0){f=await async function(e,t,r){let n=(await y$(t,["ls-files","--others","--exclude-standard"])).split("\n").map((e=>e.trim())).filter((e=>e.length>0));return n.length>r&&(n=n.slice(0,r)),(await Promise.all(n.map((async t=>{try{return await k$(e,t)}catch{return}})))).filter((e=>void 0!==e))}(t,o,r.maxUntrackedFiles);for(const e of f){const t=e.isSymlink?`${b$([e])}\n\\ No newline at end of file`:await y$(o,["diff","--no-color","--no-index","--","/dev/null",e.path],{ignoreErrors:!0,shouldNotTrimOutput:!0});p.diffs.push(...v$(t).diffs)}}if(a!==Le.ek.FILE_DIFFS||!0===p.fileContentsOmitted)for(const e of p.diffs)e.chunks=[];if(a===Le.ek.DIFFS_WITH_BEFORE_AND_AFTER&&!0!==p.fileContentsOmitted){const n=r.ref.length>0?r.ref:"HEAD";await Promise.all(p.diffs.map((async s=>{try{if("/dev/null"!==s.from)try{s.beforeFileContents=await y$(o,["show","--end-of-options",`${c}:${s.from}`],{shouldNotTrimOutput:!0})}catch{s.beforeFileContents=""}else s.beforeFileContents="";if("/dev/null"!==s.to)if(r.ref.length>0)try{s.afterFileContents=await y$(o,["show","--end-of-options",`${n}:${s.to}`],{shouldNotTrimOutput:!0})}catch{s.afterFileContents=""}else try{s.afterFileContents=(await k$(t,s.to)).contents}catch{try{s.afterFileContents=await y$(o,["show","--end-of-options",`${n}:${s.to}`],{shouldNotTrimOutput:!0})}catch{s.afterFileContents=""}}else s.afterFileContents=""}catch(t){g$.error(e,"Error fetching file contents for diff",t)}})))}const m=new Map;for(const e of p.diffs){const t="/dev/null"!==e.to?e.to:e.from;t&&m.set(t,e)}const g=[...m.keys()],w=r.ref.length>0?r.ref:"HEAD";try{const e=await HA({repoRoot:t,filePaths:g,getContent:async e=>{const t=m.get(e);if(t){if(void 0!==t.afterFileContents)return t.afterFileContents;try{if(t.to&&"/dev/null"!==t.to)return await y$(o,["show","--end-of-options",`${w}:${t.to}`],{shouldNotTrimOutput:!0})}catch{}}}});for(const[t,r]of e){const e=m.get(t);e&&(e.isGenerated=r.isGenerated)}}catch(t){g$.warn(e,"Generated-file detection failed; continuing without it",{error:t instanceof Error?t.message:String(t)})}const y=r.computePatchId&&void 0!==h?await async function(e,t){if(0===t.length)return;const{exitCode:r,stdout:n,stderr:o}=await e(["patch-id","--stable"],{input:t});if(0!==r)throw new Error(`git patch-id failed with code ${r}: ${o}`);return n.trim().split(/\s+/)[0]||void 0}(o,function(...e){const t=e.filter((e=>e.length>0));return 0===t.length?"":`${t.join("\n")}\n`}(h,b$(f))):void 0,v=!0===r.returnHeadSha?(await y$(o,["rev-parse","HEAD"])).trim():void 0,b=!0===r.returnHeadSha?(await y$(o,["status","--porcelain=v1","--untracked-files=all"])).trim().length>0:void 0,S=new Le.df({diff:p,submoduleDiffs:[],patchId:y,headSha:v,hasUncommittedChanges:b}),k=r.maxResponseBytes??0;if(k>0){const e=S.toBinary().byteLength;if(e>k)throw new Error(`GetDiffResponseTooLarge: ${e} bytes exceeds the ${k} byte limit`)}return S}class C${async execute(e,t){return _$(e,t.cwd,t)}}var E$=r("../proto/dist/generated/agent/v1/mcp_allowlist_precheck_exec_pb.js");class x${constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isMcpFullyAllowlisted(e,{providerIdentifier:t.providerIdentifier,toolName:t.toolName,annotationsJson:t.annotationsJson});return new E$.M({allowlisted:r})}}var P$=r("../proto/dist/generated/agent/v1/record_screen_exec_pb.js"),R$=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function I$(e){return null!==e.exitCode||null!==e.signalCode||e.killed}function T$(e,t){return"object"==typeof e&&null!==e&&"code"in e&&e.code===t}function A$(e){return e instanceof Error?e.message:String(e)}function $$(e,t){return new P$.Tj({result:{case:"failure",value:new P$.yH({error:t,kind:e})}})}function M$(e){return e instanceof Error?e.message.startsWith("Failed to load polished-renderer native binding")?"binding_load_failed":"code"in e&&"string"==typeof e.code?e.code:e.name:typeof e}function D$(e,t,r,n){const o=[],s=function(e,t){const r=e.ffmpegExitCode??e.childProcess.exitCode,n=e.ffmpegExitSignal??e.childProcess.signalCode;if(e.ffmpegDiedEarly||null!==e.ffmpegDiedTime||null!==r||null!==n)return`ffmpeg exited code=${r} signal=${n}${null!==e.ffmpegDiedTime?` ${Math.max(0,Math.round((t-e.ffmpegDiedTime)/1e3))}s before SAVE`:""}`}(t,n);return void 0!==s&&o.push(s),void 0!==r&&o.push(`stop failed: ${A$(r)}`),o.length>0?`${e} (${o.join("; ")})`:e}const O$=(0,zs.promisify)(ou.execFile);class F${constructor(e){if(this.activeRecording=null,this.inFlightSaves=[],this.onRecordingStartedCallback=null,this.onRecordingStoppedCallback=null,this.recordingStoppedCallbackInvoked=!1,this.artifactsDir=e.artifactsDir,this.stagingDir=e.stagingDir??"/opt/cursor/recording-staging/",this.display=e.display,this.disablePolishedRendering=e.disablePolishedRendering??!1,this.polishedRenderer=e.polishedRenderer,!this.disablePolishedRendering){if(!this.polishedRenderer)throw new Error("record_screen requires a polished recording renderer when polished rendering is enabled. This tool should run via exec-daemon where that dependency is bundled.");this.polishedRenderer.assertAvailable()}}setOnRecordingStarted(e){this.onRecordingStartedCallback=e}setOnRecordingStopped(e){this.onRecordingStoppedCallback=e}invokeStoppedCallbackOnce(){!this.recordingStoppedCallbackInvoked&&this.onRecordingStoppedCallback&&(this.recordingStoppedCallbackInvoked=!0,this.onRecordingStoppedCallback())}async cleanupRecording(e){try{await(e.inputEventLogger?.stop())}catch{}if(!I$(e.childProcess)&&e.childProcess.pid)try{await this.stopFfmpegRecording(e)}catch{try{process.kill(e.childProcess.pid,"SIGKILL")}catch{}}}getActiveInputEventLogger(){return this.activeRecording?.inputEventLogger??null}async dispose(){const e=this.inFlightSaves.map((e=>e.promise));if(e.length>0)try{await(0,Or.wj)(Promise.all(e),F$.IN_FLIGHT_SAVE_DISPOSE_TIMEOUT_MS,"Timed out waiting for in-flight recording save")}catch{}if(this.activeRecording){await this.cleanupRecording(this.activeRecording),this.invokeStoppedCallbackOnce();try{await Co.rm(this.activeRecording.sessionDir,{force:!0,recursive:!0})}catch{}this.activeRecording=null}}findInFlightSave(e){return this.inFlightSaves.find((t=>t.state===e))}clearActiveRecordingIfCurrent(e){this.activeRecording===e&&(this.activeRecording=null)}invokeStoppedCallbackIfCurrent(e){this.activeRecording===e&&this.invokeStoppedCallbackOnce()}sanitizeToolCallId(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}async ensureRecordingDirectoryExists(){await Co.mkdir(this.stagingDir,{recursive:!0}),await Co.mkdir(this.artifactsDir,{recursive:!0})}buildSessionDir(e){const t=this.sanitizeToolCallId(e),r=`session-${(new Date).toISOString().replace(/[:.]/g,"-")}-${t}`;return s.join(this.stagingDir,r)}validateAndNormalizeSaveAsFilename(e){let t=e.trim();return t.startsWith(this.artifactsDir)&&(t=t.slice(this.artifactsDir.length),t.startsWith("/")&&(t=t.slice(1))),t=t.trim(),0===t.length?{success:!1,reason:P$.y.UNSPECIFIED}:t.includes("/")||t.includes("\\")?{success:!1,reason:P$.y.SLASHES_NOT_ALLOWED}:(t=t.replace(/[^a-zA-Z0-9 ._-]/g,"_"),t=t.trim(),0===t.length?{success:!1,reason:P$.y.UNSPECIFIED}:(t.length>128&&(t=t.slice(0,128).trim()),t.toLowerCase().endsWith(".mp4")||(t=`${t}.mp4`),{success:!0,filename:t}))}async movePolishedVideo(e,t){try{return void await Co.rename(e,t)}catch(e){if(!T$(e,"EXDEV"))throw e}try{await Co.copyFile(e,t)}catch(e){throw await Co.rm(t,{force:!0}).catch((()=>{})),e}try{await Co.unlink(e)}catch(e){throw await Co.rm(t,{force:!0}).catch((()=>{})),e}}async getUniqueArtifactVideoPath(e){const t=s.parse(e),r=t.name||"recording",n=t.ext||".mp4";let o=`${r}${n}`,i=2;for(;;){const e=s.join(this.artifactsDir,o);try{const t=await Co.open(e,"wx");return await t.close(),e}catch(e){if(!T$(e,"EEXIST"))throw e;o=`${r}-${i}${n}`,i++}}}async resolveArtifactVideoPath(e){const{saveAsFilename:t,stagingSessionDir:r}=e;let n,o;if(t){const e=this.validateAndNormalizeSaveAsFilename(t);e.success?o=e.filename:(n=e.reason,o=`${s.basename(r)}.mp4`)}else o=`${s.basename(r)}.mp4`;return{finalVideoPath:await this.getUniqueArtifactVideoPath(o),requestedFilePathRejectedReason:n}}async getVideoDurationMs(e){const{stdout:t}=await(0,su.D9)(O$,"ffprobe",["-v","error","-show_entries","format=duration","-of","default=noprint_wrappers=1:nokey=1",e],{encoding:"utf8"}),r=parseFloat(t.trim());if(!Number.isFinite(r)||r<0)throw new Error(`Invalid video duration from ffprobe: ${t.trim()}`);return Math.floor(1e3*r)}async getVideoDimensions(e){const{stdout:t}=await(0,su.D9)(O$,"ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=width,height","-of","csv=p=0:s=x",e],{encoding:"utf8"}),[r,n]=t.trim().split("x"),o=Number.parseInt(r,10),s=Number.parseInt(n,10);if(!Number.isFinite(o)||!Number.isFinite(s))throw new Error(`Invalid video dimensions from ffprobe: ${t.trim()}`);if(o<=0||s<=0)throw new Error(`Invalid non-positive video dimensions from ffprobe: ${t.trim()}`);return{width:o,height:s}}async renderPolished(e,t){const r=s.join(t,"recording"),n=s.join(r,"recording_full.mp4");try{await this.polishedRenderer.renderRecordingSession({stagingSessionDir:t,outputVideoPath:n,fps:F$.PROXY_TARGET_FPS,includeBrandTag:!0}),await Co.access(n,Co.constants.R_OK)}catch(t){const r=(0,$.fU)(e);throw r?.setAttribute("error.type",M$(t)),r?.setStatus({code:2}),t}return n}async getVideoFramerate(e){try{const{stdout:t}=await(0,su.D9)(O$,"ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=r_frame_rate","-of","default=noprint_wrappers=1:nokey=1",e],{encoding:"utf8"}),r=t.trim();if(r.includes("/")){const[e,t]=r.split("/"),n=Number.parseFloat(e),o=Number.parseFloat(t);if(Number.isFinite(n)&&Number.isFinite(o)&&0!==o){const e=n/o;if(e>0&&e<500)return Math.round(e)}}else{const e=Number.parseFloat(r);if(Number.isFinite(e)&&e>0&&e<500)return Math.round(e)}console.warn(`[record-screen] Unexpected ffprobe r_frame_rate output "${r}", defaulting to ${F$.PROXY_TARGET_FPS}fps`)}catch(e){console.warn(`[record-screen] Failed to read video framerate: ${e instanceof Error?e.message:String(e)}, defaulting to ${F$.PROXY_TARGET_FPS}fps`)}return F$.PROXY_TARGET_FPS}async startFfmpegRecording(e,t){const r=s.join(t,"recording");await Co.mkdir(r,{recursive:!0});const n=s.join(r,"recording_render_proxy_1080p.mp4"),o="windowsDesktop"===e.kind?["-f","gdigrab","-i","desktop"]:["-video_size",e.resolution,"-framerate",String(await this.detectRefreshRate(e.display)),"-draw_mouse","0","-f","x11grab","-i",e.display],i=["-vf",`scale=${F$.PROXY_TARGET_WIDTH}:-2:flags=lanczos,fps=${F$.PROXY_TARGET_FPS}`,"-c:v","libx264","-preset",F$.PROXY_PRESET,"-crf",String(F$.PROXY_CRF),"-pix_fmt","yuv420p","-profile:v","high","-x264-params","keyint=1:min-keyint=1:scenecut=0:bframes=0","-movflags","+faststart","-tune","fastdecode"],a=["-vf",`scale=${F$.PROXY_TARGET_WIDTH}:-2:flags=lanczos`,"-c:v","libx264","-preset",F$.PROXY_PRESET,"-pix_fmt","yuv420p","-movflags","+faststart"],c=this.disablePolishedRendering?a:i,l=(0,su.D9)(ou.spawn,"ffmpeg",[...o,...c,"-y",n],{stdio:["win32"===process.platform?"pipe":"ignore","pipe","pipe"],detached:"win32"!==process.platform,windowsHide:!0}),u=new Promise(((e,t)=>{let r="",n=!1;l.stderr?.on("data",(t=>{r+=t.toString(),!n&&r.includes("frame=")&&(n=!0,e(Date.now()))}));const o=setTimeout((()=>{n||t(new Error("ffmpeg did not start encoding within 5 seconds"))}),5e3);l.once("exit",((e,r)=>{clearTimeout(o),n||t(new Error(`ffmpeg exited before starting: code=${e} signal=${r}`))})),l.once("error",(e=>{clearTimeout(o),n||t(new Error(`ffmpeg failed to start: ${e.message}`))}))}));return await new Promise(((e,t)=>{const r=setTimeout(e,300);l.once("error",(e=>{clearTimeout(r),t(new Error(`Failed to start ffmpeg: ${e.message}`))})),l.once("exit",((e,n)=>{clearTimeout(r),t(null!==e&&0!==e?new Error(`ffmpeg exited with code ${e}`):null!==n?new Error(`ffmpeg killed by signal ${n}`):new Error("ffmpeg exited unexpectedly during startup"))}))})),{process:l,videoStartedPromise:u}}async detectRefreshRate(e){try{return(await Wg(e)).display.refreshRate}catch(e){return console.warn(`[record-screen] Failed to detect refresh rate: ${e instanceof Error?e.message:String(e)}, using default ${F$.DEFAULT_REFRESH_RATE}Hz`),F$.DEFAULT_REFRESH_RATE}}async runFfmpegCommand(e,t){return await new Promise(((r,n)=>{const o=(0,su.D9)(ou.spawn,"ffmpeg",t,{stdio:["ignore","ignore","pipe"]});let s="";o.stderr?.on("data",(e=>{s.length<2e4&&(s+=e.toString())})),o.once("error",(t=>{n(new Error(`ffmpeg ${e} failed to start: ${t instanceof Error?t.message:String(t)}`))})),o.once("close",(t=>{0===t?r():n(new Error(`ffmpeg ${e} exited with code ${t}: ${s.trim()}`))}))}))}async saveRecordingDataPackage(e){const{sessionDir:t,durationMs:r,recordingStartEpochMs:n,ffmpegStartedEpochMs:o,inputEvents:i,resolution:a,renderProxies:c}=e,l=s.join(t,"recording"),u=s.join(l,"recording-data.json"),d=o-n,h=i.map((e=>({executionTimestampMs:e.executionTimestampMs,commandDurationMs:e.commandDurationMs,positionBefore:e.positionBefore,positionAfter:e.positionAfter,cursorTypeAfter:e.cursorTypeAfter,action:{action:this.serializeAction(e.action)}}))),p={version:3,durationMs:r,recordingStartEpochMs:n,ffmpegStartedEpochMs:o,eventToVideoOffsetMs:d,displayWidth:a.display.width,displayHeight:a.display.height,apiWidth:a.api.width,apiHeight:a.api.height,inputEvents:h,renderProxies:c??null};await Co.writeFile(u,JSON.stringify(p,null,2))}serializeAction(e){const{action:t}=e,r={case:t.case};switch(t.case){case"click":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null,button:t.value.button,count:t.value.count,modifierKeys:t.value.modifierKeys};break;case"mouseMove":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null};break;case"type":r.value={text:t.value.text};break;case"key":r.value={key:t.value.key,holdDurationMs:t.value.holdDurationMs};break;case"scroll":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null,direction:t.value.direction,amount:t.value.amount,modifierKeys:t.value.modifierKeys};break;case"drag":r.value={path:t.value.path.map((e=>({x:e.x,y:e.y}))),button:t.value.button};break;case"wait":r.value={durationMs:t.value.durationMs};break;case"screenshot":case"cursorPosition":case"mouseDown":case"mouseUp":r.value=t.value;break;default:r.value={}}return r}async stopFfmpegRecording(e){const{childProcess:t}=e;if(I$(t)||!t.pid)return;const r=t.pid;return new Promise(((e,n)=>{const o=setTimeout((()=>{try{try{process.kill(-r,"SIGKILL")}catch{process.kill(r,"SIGKILL")}}catch{}n(new Error("Timeout waiting for ffmpeg to stop"))}),2e4);t.once("exit",(()=>{clearTimeout(o),e()})),t.once("error",(e=>{clearTimeout(o),n(new Error(`Error stopping ffmpeg: ${e.message}`))}));try{if(t.stdin)return t.stdin.on("error",(()=>{})),void t.stdin.end("q");try{process.kill(-r,"SIGTERM")}catch{process.kill(r,"SIGTERM")}}catch(t){if(clearTimeout(o),T$(t,"ESRCH"))return void e();n(new Error(`Failed to send SIGTERM: ${t instanceof Error?t.message:String(t)}`))}}))}async performSave(e,t,r){const n=Date.now();let o=P$.Wg.INTERNAL;try{const i=await(r.inputEventLogger?.stop())??[],a=r.inputEventLogger?.getRecordingStartTime()??r.startTime;let c;this.invokeStoppedCallbackIfCurrent(r);try{!I$(r.childProcess)&&r.childProcess.pid&&await this.stopFfmpegRecording(r)}catch(e){c=e,console.warn(`[record-screen] Failed to stop ffmpeg: ${A$(e)}`)}const l=r.ffmpegStartedEpochMs??a,u=r.sessionDir,d=s.join(u,"recording"),h=s.join(d,"recording_render_proxy_1080p.mp4");let p,f,m;try{await Co.access(h,Co.constants.R_OK)}catch(e){await this.cleanupRecording(r),this.clearActiveRecordingIfCurrent(r);const t=T$(e,"ENOENT"),o=t?`Recording proxy not found at ${h}`:`Recording proxy at ${h} could not be validated: ${A$(e)}`;return $$(t?P$.Wg.PROXY_MISSING:P$.Wg.STAGING_IO,D$(o,r,c,n))}try{if([p,f,m]=await Promise.all([this.getVideoDurationMs(h),this.getVideoDimensions(h),this.getVideoFramerate(h)]),p<=0)throw new Error(`Recording proxy has zero duration at ${h}`)}catch(e){await this.cleanupRecording(r);const t=A$(e),o=t.includes(h)?t:`Recording proxy at ${h} could not be validated: ${t}`;return $$(P$.Wg.PROXY_INVALID,D$(o,r,c,n))}const g={profileVersion:F$.PROXY_PROFILE_VERSION,generatedAtEpochMs:Date.now(),source:{width:f.width,height:f.height,durationMs:p,fps:m},artifacts:[{name:"render_proxy_1080p",path:"recording_render_proxy_1080p.mp4",width:f.width,height:f.height,fps:F$.PROXY_TARGET_FPS,codec:"h264",profile:F$.PROXY_PROFILE_VERSION,keyint:1,status:"success",elapsedMs:0}]};o=P$.Wg.STAGING_IO,void 0!==r.resolution&&await this.saveRecordingDataPackage({sessionDir:u,durationMs:p,recordingStartEpochMs:a,ffmpegStartedEpochMs:l,inputEvents:i,resolution:r.resolution,renderProxies:g}),o=P$.Wg.ARTIFACT_WRITE_FAILED;const{finalVideoPath:w,requestedFilePathRejectedReason:y}=await this.resolveArtifactVideoPath({saveAsFilename:t.saveAsFilename,stagingSessionDir:u});try{if(this.disablePolishedRendering)await Co.copyFile(h,w);else{o=P$.Wg.RENDER_FAILED;const t=await this.renderPolished(e,u);o=P$.Wg.ARTIFACT_WRITE_FAILED,await this.movePolishedVideo(t,w)}}catch(e){throw await Co.rm(w,{force:!0}).catch((()=>{})),e}try{await Co.rm(u,{force:!0,recursive:!0})}catch(e){console.warn(`[record-screen] Failed to remove staging session ${u}: ${A$(e)}`)}return this.clearActiveRecordingIfCurrent(r),new P$.Tj({result:{case:"saveSuccess",value:new P$.ol({path:w,recordingDurationMs:we.protoInt64.parse(p.toString()),requestedFilePathRejectedReason:y})}})}catch(e){return await this.cleanupRecording(r),this.invokeStoppedCallbackIfCurrent(r),$$("binding_load_failed"===M$(e)?P$.Wg.RENDERER_UNAVAILABLE:o,A$(e))}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,$.VI)(e.withName("LocalRecordScreenExecutor.execute")),!1);try{await this.ensureRecordingDirectoryExists()}catch(e){return $$(P$.Wg.STAGING_IO,`Failed to create recording directory: ${e instanceof Error?e.message:String(e)}. Ensure the parent directory exists and has write permissions, or run: sudo mkdir -p ${this.stagingDir} ${this.artifactsDir} && sudo chmod 777 ${this.stagingDir} ${this.artifactsDir}`)}if(t.mode===P$.$u.UNSPECIFIED)return $$(P$.Wg.INVALID_MODE,"Mode must be one of START_RECORDING, SAVE_RECORDING, DISCARD_RECORDING");switch(t.mode){case P$.$u.START_RECORDING:{this.recordingStoppedCallbackInvoked=!1;let e=!1;if(this.activeRecording){const t=this.activeRecording;if(!this.inFlightSaves.some((e=>e.state===t))){e=!0;try{await this.cleanupRecording(t),await Co.rm(t.sessionDir,{force:!0,recursive:!0}).catch((()=>{}))}catch{}}this.activeRecording=null}let r,n=null,o=null,s=P$.Wg.STAGING_IO;try{o=this.buildSessionDir(t.toolCallId||"recording"),await Co.mkdir(o,{recursive:!0}),s=P$.Wg.DISPLAY_UNAVAILABLE;const i="win32"===process.platform?void 0:await Wg(this.display),a=void 0===i?{kind:"windowsDesktop"}:{kind:"x11",display:this.display,resolution:i.resolutionString};s=P$.Wg.FFMPEG_START_FAILED;const{process:c,videoStartedPromise:l}=await this.startFfmpegRecording(a,o);n=c;const u=this.disablePolishedRendering?void 0:i?.resolution;void 0!==u&&(s=P$.Wg.INTERNAL,r=new Xg({displayNum:Ug(this.display),resolution:u}),await r.start());const d=r?.getRecordingStartTime()??Date.now();let h;s=P$.Wg.FFMPEG_START_FAILED;try{h=await l}catch(e){throw new Error(`ffmpeg failed to start encoding: ${e instanceof Error?e.message:String(e)}`)}const p={childProcess:n,sessionDir:o,startTime:d,inputEventLogger:r,resolution:u,ffmpegStartedEpochMs:h,ffmpegDiedEarly:!1,ffmpegDiedTime:null,ffmpegExitCode:null,ffmpegExitSignal:null};this.activeRecording=p,this.onRecordingStartedCallback&&r&&this.onRecordingStartedCallback(r),n.once("exit",((e,t)=>{p.ffmpegDiedEarly=!0,p.ffmpegDiedTime=Date.now(),p.ffmpegExitCode=e,p.ffmpegExitSignal=t}));const f=!!t.saveAsFilename;return new P$.Tj({result:{case:"startSuccess",value:new P$.T4({wasPriorRecordingCancelled:e,wasSaveAsFilenameIgnored:f})}})}catch(e){if(r)try{await r.stop()}catch{}if(n&&!n.killed&&n.pid)try{process.kill(n.pid,"SIGKILL")}catch{}return o&&await Co.rm(o,{force:!0,recursive:!0}).catch((()=>{})),this.activeRecording=null,$$(s,A$(e))}}case P$.$u.SAVE_RECORDING:{if(!this.activeRecording)return 1===this.inFlightSaves.length?await this.inFlightSaves[0].promise:$$(P$.Wg.NO_ACTIVE_RECORDING,"No active recording to save");const e=this.activeRecording,r=this.findInFlightSave(e);if(r)return await r.promise;const o=Promise.resolve().then((()=>this.performSave(n.ctx,t,e))),s={state:e,promise:o};this.inFlightSaves.push(s);try{return await o}finally{this.inFlightSaves=this.inFlightSaves.filter((e=>e!==s))}}case P$.$u.DISCARD_RECORDING:{if(!this.activeRecording)return $$(P$.Wg.NO_ACTIVE_RECORDING,"No active recording to discard");const e=this.activeRecording;if(this.findInFlightSave(e))return $$(P$.Wg.SAVE_IN_PROGRESS,"Save in progress for this recording; wait for it or start a new recording");let t=P$.Wg.INTERNAL;try{return await(e.inputEventLogger?.stop()),this.invokeStoppedCallbackOnce(),!I$(e.childProcess)&&e.childProcess.pid&&(t=P$.Wg.FFMPEG_STOP_FAILED,await this.stopFfmpegRecording(e)),t=P$.Wg.STAGING_IO,await Co.rm(e.sessionDir,{force:!0,recursive:!0}),this.activeRecording=null,new P$.Tj({result:{case:"discardSuccess",value:new P$.N8}})}catch(r){await this.cleanupRecording(e),this.invokeStoppedCallbackOnce();const n=e.sessionDir;let o=!1;try{await Co.rm(n,{force:!0,recursive:!0}),o=!0}catch{}this.activeRecording=null;return $$(t,`Failed to discard recording: ${r instanceof Error?r.message:String(r)}${o?"":`. Session may remain at: ${n}`}`)}}default:{const e=t.mode;return $$(P$.Wg.INVALID_MODE,`Unhandled recording mode: ${String(e)}`)}}}catch(e){r.error=e,r.hasError=!0}finally{R$(r)}}}async function N$(e){const t=await(0,Co.readdir)(e,{withFileTypes:!0}).catch((()=>[])),r=[];for(const n of t){const t=s.join(e,n.name),o={name:n.name,path:t,isDirectory:n.isDirectory()};n.isDirectory()&&(o.children=await N$(t)),r.push(o)}return r.sort(((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)))}function L$(e,t="",r=!0){const n=[`${t}${r?"└── ":"├── "}${e.isDirectory?`${e.name}/`:e.name}`],o=e.children;if(o?.length){const e=t+(r?" ":"│ ");o.forEach(((t,r)=>{const s=r===o.length-1;n.push(...L$(t,e,s))}))}return n}async function j$(e){if(!await(0,Co.access)(e,Co.constants.R_OK).then((()=>!0),(()=>!1)))return"(No notes directory yet - will be created when you write your first note)";const t=await N$(e);return 0===t.length?"(Notes directory is empty)":t.flatMap(((e,r)=>L$(e,"",r===t.length-1))).join("\n")}async function U$(e,t){return j$(s.join(e,"agent-notes",t))}async function B$(e){return j$(s.join(e,"agent-notes","shared"))}F$.IN_FLIGHT_SAVE_DISPOSE_TIMEOUT_MS=3e4,F$.PROXY_TARGET_WIDTH=1920,F$.PROXY_TARGET_FPS=60,F$.PROXY_CRF=17,F$.PROXY_PRESET="veryfast",F$.PROXY_PROFILE_VERSION="render-proxy-h264-all-i-v1",F$.DEFAULT_REFRESH_RATE=60;var W$=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},H$=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const q$=3e3,z$=(0,l.h)("local-exec:request-context"),G$=Symbol("sectionLoadTimedOut");function V$(e,t){if(void 0===t)return e;let r;const n=new Promise((e=>{r=setTimeout((()=>e(G$)),t)}));return e.catch((()=>{})),Promise.race([e,n]).finally((()=>{clearTimeout(r)}))}class K${async read(e,t){const r=this.inFlight??this.begin(e),n=this.last;if(void 0===n)return r;const o=await V$(r,t).catch((()=>G$));return o===G$?n.value:o}prefetch(e){void 0===this.inFlight&&this.begin(e).catch((()=>{}))}begin(e){const t=e();this.inFlight=t;const r=()=>{this.inFlight===t&&(this.inFlight=void 0)};return t.then((e=>{this.last={value:e},r()}),r),t}}async function J$(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{W$(o,(0,$.VI)(e.withName("LocalRequestContextExecutor.getGitStatusForRepoPath")),!1);try{return(await t.exec(e,r,["--no-optional-locks","status","--short","--branch"],{timeout:n,caller:"getGitStatusForRepoPath"})).stdout}catch{return}}catch(e){o.error=e,o.hasError=!0}finally{H$(o)}}async function Z$(e,t,r,n){try{const o=(await t.exec(e,r,["rev-parse","--abbrev-ref","HEAD"],{timeout:n,caller:"getGitBranchForRepoPath"})).stdout.trim();if("HEAD"===o||0===o.length)return;return o}catch{return}}async function X$(e,t,r,n){const o=e=>{let t;const r=new Promise((e=>{t=setTimeout((()=>{e(void 0)}),n)}));return Promise.race([e.catch((()=>{})),r]).finally((()=>{void 0!==t&&clearTimeout(t)}))},[s,i]=await Promise.all([o(J$(e,t,r,n)),o(Z$(e,t,r,n))]);return{status:s,branchName:i}}async function Q$(e,t,r={}){const{projectDir:n,notesSessionId:s,agentNotesEnabled:i,reportProcessWorkingDirectory:a,getSmartModeClassifierAutoModeEnabled:c,devForceNextSmartModeClassifierBlockToken:l,isWorkingDirHomeDir:u,getSandboxEnabled:d,getSandboxSupported:h,getNetworkAllowlistInfo:p,userTerminalHint:f,artifactsFolder:m,secretRedactionEnabled:g,getComputerUseSupported:w,getComputerUseDesktop:y,getMockPromptTime:v}=r,b=y?.(),S=`${o.default.platform()} ${o.default.release()}`,k=(0,Oo.G6)(f),_=v?.(),C=(()=>{try{return(new Intl.DateTimeFormat).resolvedOptions().timeZone??void 0}catch{return}})(),E=n,x=n?`${n}/terminals`:void 0,P=n&&!1!==i?`${n}/agent-notes/shared`:void 0,R=n&&s&&!1!==i?`${n}/agent-notes/${s}`:void 0,I=n?`${n}/agent-transcripts`:void 0,T=!!d&&d(),A=h?.(),$=c?.();let M;if(p)try{const e=await V$(p(),3e3);e!==G$&&(M=e)}catch{M=void 0}return new Dr.GE({osVersion:S,workspacePaths:t,shell:k,sandboxEnabled:T,projectFolder:E,terminalsFolder:x,agentSharedNotesFolder:P,agentConversationNotesFolder:R,agentTranscriptsFolder:I,timeZone:C,...!1!==a&&{processWorkingDirectory:process.cwd()},artifactsFolder:m,...void 0!==$&&{smartModeClassifierAutoModeEnabled:$},...void 0!==l&&{devForceNextSmartModeClassifierBlockToken:l},...void 0!==_&&{devMockPromptTime:we.Timestamp.fromDate(_)},...void 0!==g&&{secretRedactionEnabled:g},...void 0!==A&&{sandboxSupported:A},...void 0!==M?.hasDefaults&&{sandboxNetworkHasDefaults:M.hasDefaults},...M?.explicitEntries&&M.explicitEntries.length>0&&{sandboxNetworkExplicitAllowlist:M.explicitEntries},...void 0!==w&&{computerUseSupported:w()},...void 0!==b&&{computerUseDesktop:b},...void 0!==u&&{isWorkingDirHomeDir:u}})}const Y$={type:"object",properties:{},additionalProperties:!1};function eM(e,t){return{tools:(!0===t?.internalBrowserProvidersOnly?e.servers.filter((e=>Kn.has(e.serverIdentifier))):e.servers).flatMap((e=>e.tools)).map((e=>new wn.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,...!0===t?.inputSchemaJson?{inputSchemaJson:void 0===e.inputSchema?void 0:JSON.stringify(e.inputSchema)}:{inputSchema:e.inputSchema?we.Value.fromJson(e.inputSchema):void 0}}))),mcpInstructions:e.servers.flatMap((e=>e.instructions))}}function tM(e,t){const r=!0===t?.slimDescriptors,n=e.servers.map((e=>{const n=e.instructions.map((e=>e.instructions)).filter(Boolean).join("\n"),o=e.tools.map((e=>new wn.E$({toolName:e.toolName,...Db(e.annotations),...r?{}:{description:e.description,...!0===t?.inputSchemaJson?{inputSchemaJson:void 0===e.inputSchema?void 0:JSON.stringify(e.inputSchema)}:{inputSchema:void 0!==e.inputSchema?we.Value.fromJson(e.inputSchema):void 0}}})));return!Vn(e.serverIdentifier)||!0!==t?.alwaysExposeVirtualMcpAuthTool&&"needsAuth"!==e.status||o.some((e=>e.toolName===nT))||o.push(new wn.E$({toolName:nT,...r?{}:{description:oT,...!0===t?.inputSchemaJson?{inputSchemaJson:JSON.stringify(Y$)}:{inputSchema:we.Value.fromJson(Y$)}}})),new wn.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,serverUseInstructions:n||void 0,tools:o})}));return new wn.U_({enabled:!0,mcpDescriptors:n})}function rM(e){const t=e?.trim();return t||void 0}function nM(e,t){const r=function(e){return rM(e.serverIdentifier)}(e);if(r)return r;const n=rM(e.serverName);return n?t.get(n)??n:void 0}class oM{constructor(e){this.mcpLease=e}async getState(e){const[t,r]=await Promise.all([this.mcpLease.getTools(e).catch((t=>(z$.warn(e,"Error fetching MCP tools",{error:t}),[]))),this.mcpLease.getInstructions(e).catch((t=>(z$.warn(e,"Error fetching MCP instructions",{error:t}),[])))]);return function(e,t,r,n=!1){const o=new Map;for(const t of e)o.has(t.providerIdentifier)||o.set(t.providerIdentifier,t.clientKey);const s=t.map((e=>nM(e,o))).filter((e=>Boolean(e))),i=[...new Set([...e.map((e=>e.clientKey)),...s,...Array.from(r?.entries()??[]).filter((([,e])=>"connected"!==e.status)).map((([e])=>e))])];if(n&&void 0!==r){const e=new Map(Array.from(r.keys(),((e,t)=>[e,t])));i.sort(((t,r)=>(e.get(t)??e.size)-(e.get(r)??e.size)))}return{servers:i.map((n=>{const s=e.filter((e=>e.clientKey===n));return{serverName:s[0]?.providerIdentifier??n,serverIdentifier:n,plugin:s[0]?.plugin,marketplace:s[0]?.marketplace,tools:s,instructions:t.filter((e=>nM(e,o)===n)),status:r?.get(n)?.status,errorMessage:r?.get(n)?.errorMessage}}))}}(t,r,await async function(e,t){const r=await t.getClients(e).catch((t=>(z$.warn(e,"Error fetching MCP clients",{error:t}),{}))),n=await Promise.all(Object.entries(r).map((async([t,r])=>{const n=await r.getState(e).catch((()=>({kind:"error",message:"Failed to fetch MCP client state"})));return[t,{status:Yn(n),errorMessage:"error"===n.kind&&void 0!==n.message?n.message:void 0}]})));return new Map(n)}(e,this.mcpLease))}}function sM(e){return new Ac._W({result:{case:"success",value:new Ac.pv({servers:e.servers.map((e=>new Ac.XE({serverName:e.serverName,serverIdentifier:e.serverIdentifier,plugin:e.plugin,marketplace:e.marketplace,tools:e.tools.map((e=>new wn.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?we.Value.fromJson(e.inputSchema):void 0,metaJson:Jn(e._meta),...Db(e.annotations)}))),instructions:e.instructions,status:e.status,errorMessage:e.errorMessage})))})}})}class iM{constructor(e,t,r){this.mcpStateAccessor=e,this.ensureMcpServersLoaded=t,this.options=r}async execute(e,t){if(void 0!==t.ruleSubjects&&void 0!==this.options?.serverRuleSubjects)return function(e,t){const r={commandPatterns:t.commandPatterns,serverUrlPatterns:t.serverUrlPatterns},n=[];for(const[t,o]of e){const e=void 0!==o.command?{transport:Ac.zj.STDIO,value:o.command,matched:{command:o.command}}:void 0!==o.url?{transport:Ac.zj.HTTP,value:o.url,matched:{url:o.url}}:void 0;void 0!==e&&n.push(new Ac.XE({serverName:t,serverIdentifier:t,ruleSubject:new Ac.D0({transport:e.transport,...xC(e.matched,r)?{value:e.value}:{}})}))}return new Ac._W({result:{case:"success",value:new Ac.pv({servers:n})}})}(this.options.serverRuleSubjects(),t.ruleSubjects);try{await(this.ensureMcpServersLoaded?.(e,t.serverIdentifiers,{wait:!t.kickOnly}))}catch{}t.refreshPolicy!==Ac.ew.FORCE_IF_MISSING&&t.refreshPolicy!==Ac.ew.FORCE||await(this.mcpStateAccessor.refreshNow?.(e));const r=await this.mcpStateAccessor.getState(e);if(!0===this.options?.filterToRequestedServers&&t.serverIdentifiers.length>0){const e=new Set(t.serverIdentifiers),n=r.servers.filter((t=>e.has(t.serverIdentifier)));if(n.length>0)return sM({...r,servers:n})}return sM(r)}}class aM{constructor(e,t,r,n,o,s,i,a,c={}){this.cursorRulesService=e,this.cloudRulesService=t,this.subagentsService=r,this.repositoryProvider=n,this.grepProvider=o,this.mcpStateAccessor=s,this.gitExecutor=i,this.workspacePaths=a,this.reusedGitInfo=new Map,this.reusedMcpState=new K$,this.reusedAgentSkills=new K$,this.reusedAdminCommandDenylist=new K$,this.cachedWorkspaces=new Map,this.inFlightWorkspaceWarms=new Map;const{projectDir:l,getSmartModeClassifierAutoModeEnabled:u,getAdminCommandDenylist:d,devForceNextSmartModeClassifierBlockToken:h,isWorkingDirHomeDir:p,agentNotesEnabled:f,reportProcessWorkingDirectory:m,createFileWatcher:g,getSandboxEnabled:w,getSandboxSupported:y,getNetworkAllowlistInfo:v,userTerminalHint:b,getMcpFileSystemOptions:S,mcpMetaToolEnabled:k,mcpMetaToolSlimDescriptors:_,mcpInputSchemaJson:C,alwaysExposeVirtualMcpAuthTool:E,getArtifactsFolder:x,secretRedactionEnabled:P,attributionConfigProvider:R,isAttributionDisabledByAdmin:I,getAgentSkills:T,additionalRules:A,getComputerUseSupported:$,getComputerUseDesktop:M,getMockPromptTime:D}=c;this.projectDir=l,this.isWorkingDirHomeDir=p,this.agentNotesEnabled=f??!0,this.reportProcessWorkingDirectory=m??!0,this.getSandboxEnabled=w,this.getSandboxSupported=y,this.getNetworkAllowlistInfo=v,this.getSmartModeClassifierAutoModeEnabled=u,this.getAdminCommandDenylist=d,this.devForceNextSmartModeClassifierBlockToken=h,this.getMockPromptTime=D,this.userTerminalHint=b,this.getMcpFileSystemOptions=S,this.mcpMetaToolEnabled=k??!1,this.mcpMetaToolSlimDescriptors=_??!1,this.mcpInputSchemaJson=C??!1,this.alwaysExposeVirtualMcpAuthTool=E??!1,this.getArtifactsFolder=x,this.secretRedactionEnabled=P,this.attributionConfigProvider=R,this.isAttributionDisabledByAdmin=I,this.getAgentSkills=T,this.additionalRules=A??[],this.getComputerUseSupported=$,this.getComputerUseDesktop=M,this.reduceContextHotPath=c.reduceContextHotPath??!1,this.sectionLoadTimeoutMs=c.sectionLoadTimeoutMs,this.reportSectionCompleteness=c.reportSectionCompleteness??!1,this.freshSectionWaitMs=c.freshSectionWaitMs,this.onRequestContext=c.onRequestContext,this.mcpFieldsFromCaller=c.mcpFieldsFromCaller??!1,!0!==c.deferWarmup&&this.warm(),void 0!==g&&(this.fileWatcher=g(),this.fileWatcher.onDidChange((e=>{this.onWorkspacePathChanged(e)})),this.fileWatcher.onDidCreate((e=>{this.onWorkspacePathChanged(e)})),this.fileWatcher.onDidDelete((e=>{this.onWorkspacePathChanged(e)})))}warm(){this.warmWorkspaceCaches(),void 0===this.globalCache&&this.rebuildGlobalCache()}onWorkspacePathChanged(e){this.rebuildAllCaches()}getWorkspaceCache(e){return this.cachedWorkspaces.get(e)}warmWorkspaceCaches(){const e=(0,y.q6)();Promise.all(this.workspacePaths.map((t=>this.ensureWorkspaceCacheWarm(e,t))))}ensureWorkspaceCacheWarm(e,t){if(this.cachedWorkspaces.has(t))return Promise.resolve();const r=this.inFlightWorkspaceWarms.get(t);if(void 0!==r)return r;const n=this.warmWorkspaceCache(e,t).finally((()=>{this.inFlightWorkspaceWarms.delete(t)}));return this.inFlightWorkspaceWarms.set(t,n),n}async warmWorkspaceCache(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=W$(r,(0,$.VI)(e.withName("LocalRequestContextExecutor.warmWorkspaceCache")),!1),o=await Ya(n.ctx,this.gitExecutor,t),s=o?await sc(n.ctx,this.gitExecutor,o):void 0,i={repoPath:o??void 0,remoteUrl:void 0!==s?ic(s):void 0};if(this.cachedWorkspaces.set(t,i),void 0!==this.freshSectionWaitMs&&void 0!==i.repoPath){const e=i.repoPath;this.gitInfoSection(e).prefetch((()=>X$((0,y.q6)(),this.gitExecutor,e,q$)))}}catch(e){r.error=e,r.hasError=!0}finally{H$(r)}}gitInfoSection(e){let t=this.reusedGitInfo.get(e);return void 0===t&&(t=new K$,this.reusedGitInfo.set(e,t)),t}rebuildAllCaches(){this.cacheDebounceTimeout&&clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=setTimeout((()=>{this.cacheDebounceTimeout=void 0,this.rebuildGlobalCache()}),5e3)}invalidateGlobalCache(){this.globalCache=void 0,this.lastGoodGlobalCache=void 0,this.globalCacheTraceId=void 0}refreshGlobalCache(){this.cacheDebounceTimeout&&(clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=void 0),this.rebuildGlobalCache()}rebuildGlobalCache(){const e={stack:[],error:void 0,hasError:!1};try{const t=(0,y.q6)(),r=W$(e,(0,$.VI)(t.withName("LocalRequestContextExecutor.rebuildGlobalCache")),!1);this.globalCacheTraceId=r.span.spanContext().traceId;const n=this.computeGlobalCache(r.ctx);return this.globalCache=n,(this.reduceContextHotPath||void 0!==this.sectionLoadTimeoutMs||void 0!==this.freshSectionWaitMs)&&n.then((e=>{this.globalCache===n&&(this.lastGoodGlobalCache=e)}),(()=>{this.globalCache===n&&(this.globalCache=void 0)})),n}catch(t){e.error=t,e.hasError=!0}finally{H$(e)}}async computeGlobalCache(e){const t={stack:[],error:void 0,hasError:!1};try{const r=W$(t,(0,$.VI)(e.withName("LocalRequestContextExecutor.computeGlobalCache")),!1),n=AbortSignal.timeout(1e3),o=performance.now(),s={},i=(e,t)=>{const r=performance.now();return t.finally((()=>{s[e]=Math.round(performance.now()-r)}))},[a,c,l,u]=await Promise.all([i("cursorRules",this.cursorRulesService.getAllCursorRules(r.ctx)),i("cloudRule",this.cloudRulesService?this.cloudRulesService.getCloudRule(r.ctx):Promise.resolve(null)),i("codebaseRef",this.repositoryProvider.getCodebaseReference(r.ctx,n).catch((()=>{}))),i("subagents",this.subagentsService?this.subagentsService.getAllSubagents().catch((()=>[])):Promise.resolve([]))]),d=Math.round(performance.now()-o);return d>1e3&&z$.warn(r.ctx,"computeGlobalCache: slow",{totalMs:d,...s,ruleCount:a.length}),{rules:[...this.additionalRules,...a],cloudRule:c,codebaseReference:l,customSubagents:u}}catch(e){t.error=e,t.hasError=!0}finally{H$(t)}}dispose(){this.cacheDebounceTimeout&&(clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=void 0),this.fileWatcher&&(this.fileWatcher.dispose(),this.fileWatcher=void 0),this.globalCache=void 0,this.lastGoodGlobalCache=void 0}async collectWorkspaceCaches(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=W$(r,(0,$.VI)(e.withName("LocalRequestContextExecutor.collectWorkspaceCaches")),!1);let o;if(this.grepProvider.getTrackedState)try{o=await this.grepProvider.getTrackedState(this.workspacePaths)}catch{o=void 0}let s=!0,i=!0;return{gitRepos:(await Promise.all(this.workspacePaths.map((async e=>{let r=this.getWorkspaceCache(e);if(void 0===r){if(!t.waitForWorkspaceCache)return s=!1,void this.ensureWorkspaceCacheWarm(n.ctx,e);if(await this.ensureWorkspaceCacheWarm(n.ctx,e),r=this.getWorkspaceCache(e),void 0===r)return void(s=!1)}const a=o?.[e];if(void 0!==a)return void 0!==r.repoPath&&void 0===a.gitStatus&&(i=!1),new Dr.DS({path:r.repoPath,status:a.gitStatus,branchName:a.gitBranchName,remoteUrl:r.remoteUrl,isOriginBacked:Ja(r.remoteUrl)});if(void 0===r.repoPath)return;const c=r.repoPath,{status:l,branchName:u}=void 0===this.freshSectionWaitMs?await X$(n.ctx,t.gitExecutor,c,q$):await this.gitInfoSection(c).read((()=>X$((0,y.q6)(),t.gitExecutor,c,q$)),this.freshSectionWaitMs);return void 0===l&&(i=!1),new Dr.DS({path:r.repoPath,status:l,branchName:u,remoteUrl:r.remoteUrl,isOriginBacked:Ja(r.remoteUrl)})})))).filter((e=>void 0!==e)),gitRepoInfoComplete:s,gitStatusInfoComplete:s&&i}}catch(e){r.error=e,r.hasError=!0}finally{H$(r)}}shareBoundedSectionLoad(e,t,r){if(void 0===this.sectionLoadTimeoutMs)return r();const n=e();if(void 0!==n)return n;const o=r();t(o);const s=()=>{e()===o&&t(void 0)};return o.then(s,s),o}async computeCachedRequestContext(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=W$(n,(0,$.VI)(e.withName("LocalRequestContextExecutor.computeCachedRequestContext")),!1),s=this.projectDir,i=async()=>{const e={stack:[],error:void 0,hasError:!1};try{const t=W$(e,(0,$.VI)(o.ctx.withName("LocalRequestContextExecutor.computeCachedRequestContext.getGlobalData")),!1);if(this.globalCacheTraceId&&t.span.setAttribute("cacheTraceId",this.globalCacheTraceId),!this.reduceContextHotPath&&void 0===this.freshSectionWaitMs){if(void 0===this.globalCache){const e=this.computeGlobalCache(o.ctx);this.globalCache=e,e.catch((()=>{this.globalCache===e&&(this.globalCache=void 0)})),void 0!==this.sectionLoadTimeoutMs&&e.then((t=>{this.globalCache===e&&(this.lastGoodGlobalCache=t)}),(()=>{}))}return this.globalCache}return void 0!==this.lastGoodGlobalCache?this.lastGoodGlobalCache:this.globalCache??this.rebuildGlobalCache()}catch(t){e.error=t,e.hasError=!0}finally{H$(e)}},a=performance.now(),c={},l=(e,t)=>{const r=performance.now();return t.finally((()=>{c[e]=Math.round(performance.now()-r)}))},u=e=>V$(e,this.sectionLoadTimeoutMs),d=(e,t,r)=>this.shareBoundedSectionLoad(e,t,r),h=this.freshSectionWaitMs,p=(e,t)=>void 0===h?t():e.read(t,h),f=void 0===h?o.ctx:(0,y.q6)(),[m,g,w,{gitRepos:v,gitRepoInfoComplete:b,gitStatusInfoComplete:S},k,_,C,E,x,P]=await Promise.all([l("globalCache",u(i())),l("mcpState",this.mcpFieldsFromCaller?Promise.resolve({servers:[]}):u(p(this.reusedMcpState,(()=>d((()=>this.inFlightMcpState),(e=>{this.inFlightMcpState=e}),(()=>this.mcpStateAccessor.getState(f))))))),l("env",Q$(o.ctx,this.workspacePaths,{projectDir:s,notesSessionId:t.notesSessionId,agentNotesEnabled:this.agentNotesEnabled,reportProcessWorkingDirectory:this.reportProcessWorkingDirectory,getSmartModeClassifierAutoModeEnabled:this.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:this.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:this.getMockPromptTime,isWorkingDirHomeDir:this.isWorkingDirHomeDir,getSandboxEnabled:this.getSandboxEnabled,getSandboxSupported:this.getSandboxSupported,getNetworkAllowlistInfo:this.getNetworkAllowlistInfo,userTerminalHint:this.userTerminalHint,artifactsFolder:this.getArtifactsFolder?.(o.ctx),secretRedactionEnabled:this.secretRedactionEnabled,getComputerUseSupported:this.getComputerUseSupported,getComputerUseDesktop:this.getComputerUseDesktop})),l("git",this.collectWorkspaceCaches(o.ctx,{waitForWorkspaceCache:!0===t.waitForWorkspaceCache,gitExecutor:r})),l("conversationNotes",this.agentNotesEnabled&&s&&t.notesSessionId?U$(s,t.notesSessionId):Promise.resolve(void 0)),l("sharedNotes",this.agentNotesEnabled&&s?B$(s):Promise.resolve(void 0)),l("mcpFileSystemOptions",this.getMcpFileSystemOptions?this.getMcpFileSystemOptions(o.ctx,{timeoutMs:3e3}):Promise.resolve(void 0)),l("attribution",this.isAttributionDisabledByAdmin?this.isAttributionDisabledByAdmin().catch((()=>!0)):Promise.resolve(!1)),l("agentSkills",u(p(this.reusedAgentSkills,(()=>d((()=>this.inFlightAgentSkills),(e=>{this.inFlightAgentSkills=e}),(()=>this.getAgentSkills?this.getAgentSkills(f):Promise.resolve([]))))))),l("adminCommandDenylist",u(p(this.reusedAdminCommandDenylist,(()=>d((()=>this.inFlightAdminCommandDenylist),(e=>{this.inFlightAdminCommandDenylist=e}),(()=>this.getAdminCommandDenylist?this.getAdminCommandDenylist():Promise.resolve(void 0)))))))]),R=m===G$,I=g===G$,T=x===G$,A=P===G$,M=R?this.lastGoodGlobalCache??{rules:[...this.additionalRules],cloudRule:null,codebaseReference:void 0,customSubagents:[]}:m,D=I?{servers:[]}:g,O=T?[]:x,F=A?void 0:P;(R||I||T||A)&&z$.warn(o.ctx,"computeCachedRequestContext: section load timed out",{timeoutMs:this.sectionLoadTimeoutMs,rulesAndSubagents:R,mcpState:I,agentSkills:T,adminCommandDenylist:A});const N=performance.now()-a;for(const[e,t]of Object.entries(c))o.span.setAttribute(`requestContext.timing.${e}Ms`,t);o.span.setAttribute("requestContext.timing.totalMs",Math.round(N)),N>1e3&&z$.warn(o.ctx,"computeCachedRequestContext: slow parallel data collection",{durationMs:Math.round(N),...c});const L=this.mcpMetaToolEnabled?tM(D,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,slimDescriptors:this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}):void 0,j=this.attributionConfigProvider?.get(),U=!E&&(j?.attribution?.attributeCommitsToAgent??!0),B=!E&&(j?.attribution?.attributePRsToAgent??!0),W=new Dr.bb({rules:M.rules,env:w,gitRepos:v,gitRepoInfoComplete:b,repositoryInfo:M.codebaseReference?[{relativeWorkspacePath:M.codebaseReference.relativeWorkspacePath,repoName:M.codebaseReference.repoName,repoOwner:M.codebaseReference.repoOwner,isTracked:M.codebaseReference.isTracked,isLocal:M.codebaseReference.isLocal,orthogonalTransformSeed:M.codebaseReference.orthogonalTransformSeed,pathEncryptionKey:M.codebaseReference.pathEncryptionKey}]:[],...eM(D,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}),conversationNotesListing:k,sharedNotesListing:_,customSubagents:M.customSubagents,mcpFileSystemOptions:C,mcpMetaToolOptions:L,supportsMcpAuth:!0,commitAttributionMessage:U?"enabled":void 0,prAttributionMessage:B?"enabled":void 0,agentSkills:O,adminCommandDenylist:F?.rules??[]});return null!==M.cloudRule&&void 0!==M.cloudRule&&(W.cloudRule=M.cloudRule),this.reportSectionCompleteness&&(W.rulesInfoComplete=!R,W.customSubagentsInfoComplete=!R,W.agentSkillsInfoComplete=!T,W.mcpInfoComplete=!I,W.mcpFileSystemInfoComplete=this.mcpMetaToolEnabled||void 0!==C,W.envInfoComplete=!0,W.gitStatusInfoComplete=S),W}catch(e){n.error=e,n.hasError=!0}finally{H$(n)}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{this.onRequestContext?.();const n=W$(r,(0,$.VI)(e.withName("LocalRequestContextExecutor.execute")),!1);n.span.setAttribute("enableCaching",void 0!==this.fileWatcher),n.span.setAttribute("hasGlobalCache",!!this.globalCache);try{const e=this.gitExecutor.forRequest?.()??this.gitExecutor,r=await this.computeCachedRequestContext(n.ctx,t,e);return new Dr._G({result:{case:"success",value:new Dr.yW({requestContext:r})}})}catch(e){return e instanceof Error||"string"==typeof e?n.span.recordException(e):n.span.recordException(kc(e)),new Dr._G({result:{case:"error",value:new Dr.nf({error:e instanceof Error?e.message:String(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{H$(r)}}}function cM(e){return 0!==e.timeout?e.timeout:e.isBackground||e.timeoutBehavior===he._d.BACKGROUND||void 0!==e.hardTimeout&&e.hardTimeout>0?0:3e4}var lM=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class uM{constructor(e,t,r,n){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r}buildResultFromExit(e){return 0===(e.exitCode??-1)?new he.W4({result:{case:"success",value:new he.QR({...e,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:us(e.sandboxPolicy)}):new he.W4({result:{case:"failure",value:new he.xC({...e,aborted:void 0!==e.abortReason,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:us(e.sandboxPolicy)})}async executeWithPolicy(e,t,r,n,o){const s=Date.now(),i=new AbortController,a=e.signal?AbortSignal.any([e.signal,i.signal]):i.signal,c=setTimeout((()=>{i.abort()}),n);try{let n,l,u,d="",h="",p=null;const f=o?{perUser:o}:void 0;for await(const o of this.coreExecutor.execute(e,{command:t.command,workingDirectory:r,signal:a,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:f,fileOutputThresholdBytes:t.fileOutputThresholdBytes,pipeStdin:!1}))"stdout"===o.type?d+=o.data:"stderr"===o.type?h+=o.data:"exit"===o.type&&(p=null!=o.code?0|o.code:null,l=o.outputLocation,n=o.aborted?a.aborted?i.signal.aborted&&a.reason===i.signal.reason?he.Lv.TIMEOUT:he.Lv.USER_ABORT:he.Lv.UNSPECIFIED:void 0,u=$y(o.localExecutionTimeMs));clearTimeout(c);const m=Date.now()-s,g={command:t.command,workingDirectory:r,exitCode:void 0!==n?-1:p??-1,signal:void 0!==n?"SIGTERM":"",abortReason:n,stdout:d,stderr:h,executionTime:m,localExecutionTimeMs:u,sandboxPolicy:o,outputLocation:l};return this.buildResultFromExit(g)}catch(s){return clearTimeout(c),i.signal.aborted&&!e.signal.aborted?new he.W4({result:{case:"timeout",value:new he.eG({command:t.command,workingDirectory:r,timeoutMs:n})},sandboxPolicy:us(o)}):e.signal.aborted?new he.W4({result:{case:"rejected",value:new he.pZ({command:t.command,workingDirectory:r,reason:"Command aborted"})},sandboxPolicy:us(o)}):new he.W4({result:{case:"spawnError",value:new he.mJ({command:t.command,workingDirectory:r,error:s instanceof Error?s.message:"Unknown error"})},sandboxPolicy:us(o)})}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,$.VI)(e.withName("LocalShellExecutor.execute")),!1).ctx;(0,$.HF)(n,"LocalShellExecutor.execute");const o=t.command,s=t.requestedSandboxPolicy?ls(t.requestedSandboxPolicy):void 0,i=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),a=cM(t),c=(0,Yo.o1)(i);if(!t.parsingResult)return new he.W4({result:{case:"spawnError",value:new he.mJ({command:o,workingDirectory:c,error:"Parsing result is required"})}});let l;if(Mo(t)){const e=await this.permissionsService.shouldEnforceShellInvariantBlocks(n,{workingDirectory:c,skipUnsafeWorkingDirectoryBlock:!0,command:o,parsingResult:t.parsingResult,toolCallId:t.toolCallId,resolveSkippedApprovalPolicy:!0},s);if("block"===e.kind)return new he.W4({result:ed(o,c,e.reason)});l=e.policy??s}else{const e=await this.permissionsService.shouldBlockShellCommand(n,o,{workingDirectory:c,timeout:a,parsingResult:t.parsingResult,toolCallId:t.toolCallId,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Ao(t)},s);if("block"===e.kind)return new he.W4({result:ed(o,c,e.reason)});l=e.policy}return l=await Tc(l,{command:o,workingDirectory:c,parsingResult:t.parsingResult,permissionsService:this.permissionsService,ignoreService:this.ignoreService}),this.executeWithPolicy(n,t,i,a,l)}catch(e){r.error=e,r.hasError=!0}finally{lM(r)}}}var dM=r("../proto/dist/generated/agent/v1/shell_allowlist_precheck_exec_pb.js");class hM{constructor(e){this.permissionsService=e}async execute(e,t){const r=t.parsingResult??new he.HO,n=await this.permissionsService.isShellCommandFullyAllowlisted(e,t.command,{workingDirectory:t.workingDirectory,parsingResult:r,classifierResult:t.classifierResult,toolCallId:t.toolCallId});return new dM.e({allowlisted:n})}}class pM{constructor(e){this.shellStreamExecutor=e}async execute(e,t,r){return""===t.toolCallId.trim()?new he.jK({status:he.iA.NOT_FOUND}):this.shellStreamExecutor.forceBackgroundByToolCallId(e,t.toolCallId)}}var fM=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const mM=(0,l.h)("local-exec:shell-stream");class gM{constructor(e,t){this.iterator=e,this.timeoutMs=t,this.pendingPromise=null,this.stopPromise=new Promise((e=>{this.stopResolve=e}))}stop(e){return void 0===this.stopReason&&(this.stopReason=e,this.stopResolve?.(),!0)}get timedOut(){return"background"===this.stopReason?.kind&&this.stopReason.reason===he.Jg.TIMEOUT}get backgroundRequested(){return"background"===this.stopReason?.kind}get backgroundReasonValue(){return"background"===this.stopReason?.kind?this.stopReason.reason:void 0}get stopReasonValue(){return this.stopReason}async*iterate(){this.timer=setTimeout((()=>{this.stop({kind:"background",reason:he.Jg.TIMEOUT})}),this.timeoutMs);try{for(;;){if(void 0!==this.stopReason)return;this.pendingPromise=this.iterator.next();const e=await Promise.race([this.pendingPromise.then((e=>({kind:"result",result:e}))),this.stopPromise.then((()=>({kind:"stopped"})))]);if("stopped"===e.kind)return;if(this.pendingPromise=null,e.result.done)return;yield e.result.value}}finally{clearTimeout(this.timer)}}requestBackground(){return this.stop({kind:"background",reason:he.Jg.USER_REQUEST})}abort(){this.stop({kind:"abort"})}getHandoffIterator(){if(this.pendingPromise){const e=this.pendingPromise;this.pendingPromise=null;let t=!1;return{next:async()=>t?this.iterator.next():(t=!0,e)}}return this.iterator}}function wM(){let e=()=>{};return{promise:new Promise((t=>{e=t})),resolve:e}}class yM{constructor(e,t,r,n){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r,this.backgroundShellManager=n,this.activeForegroundExecutions=new Map,this.pendingShells=new Map}hasForegroundWork(){return this.activeForegroundExecutions.size>0||this.pendingShells.size>0}async forceBackgroundByToolCallId(e,t){const r=this.pendingShells.get(t),n=void 0===r||r.awaitingApproval?this.activeForegroundExecutions.get(t):await async function(e,t){const[r,n]=e.withCancel();try{return await Promise.race([t.registered.promise,(0,y.uk)(r).then((()=>{}))])}finally{n()}}(e,r),o=n?.requestBackground();return o?new he.jK({status:he.iA.ACCEPTED,shellResult:o}):new he.jK({status:he.iA.NOT_FOUND})}pendingFrom(e){return{execute:(t,r,n)=>this.whilePending(r,(()=>e.get(ee).execute(t,r,n)))}}execute(e,t){return this.whilePending(t,(r=>this.run(e,t,r)))}async*whilePending(e,t){let r=this.pendingShells.get(e.toolCallId);void 0===r&&(r={awaitingApproval:!1,registered:wM()},""!==e.toolCallId&&e.timeoutBehavior===he._d.BACKGROUND&&this.pendingShells.set(e.toolCallId,r));try{yield*t(r)}finally{this.settle(e.toolCallId,r,void 0)}}settle(e,t,r){this.pendingShells.get(e)===t&&this.pendingShells.delete(e),t.registered.resolve(r)}async*run(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{e.signal?.throwIfAborted(),function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(n,(0,$.VI)(e.withName("LocalShellStreamExecutor.execute")),!1);const o=t.command;let s=t.requestedSandboxPolicy?ls(t.requestedSandboxPolicy):void 0;const i=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),a=cM(t),c=(0,Yo.o1)(i),l=Date.now(),u=performance.now(),d=new he.HO(Wo(o).structured),h=ks({command:o,parsingResult:d,blockedCommands:t.adminCommandDenylist});if(void 0!==h)return void(yield new he.FI({event:{case:"rejected",value:new he.pZ({command:o,workingDirectory:c,reason:h})}}));const p=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:c,skipUnsafeWorkingDirectoryBlock:!0,command:o,parsingResult:d,toolCallId:t.toolCallId,resolveSkippedApprovalPolicy:Mo(t)},s);if("block"===p.kind)return"permissionsConfig"===p.reason.type?void(yield new he.FI({event:{case:"permissionDenied",value:new he.jn({command:o,workingDirectory:c,error:"Command blocked by permissions configuration",isReadonly:p.reason.isReadonly??!1})}})):void(yield new he.FI({event:{case:"rejected",value:new he.pZ({command:o,workingDirectory:c,reason:Yu(p.reason)})}}));if(mM.info(e,"Shell stream: approval gate reached",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,hasSmartModeApproval:void 0!==t.smartModeApproval,hasSmartModeApprovalReason:void 0!==t.smartModeApproval?.reason,hasSmartModeApprovalRequestId:void 0!==t.smartModeApproval?.requestId,requestedPolicyType:s?.type??"undefined",parserCommandCount:d.executableCommands.length,classifierCommandCount:t.classifierResult?.commands.length??0,commandLength:o.length}),Mo(t)){const r=p.policy??s;mM.info(e,"Shell stream: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:s?.type??"undefined",effectivePolicyType:r?.type??"undefined"}),s=r}else{r.awaitingApproval=!0;const n=await this.permissionsService.shouldBlockShellCommand(e,o,{workingDirectory:c,timeout:a,parsingResult:d,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Ao(t),onApprovalRequested:()=>{r.registered.resolve(void 0),r.registered=wM()}},s);if(r.awaitingApproval=!1,"block"===n.kind){if(mM.info(e,"Shell stream: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:n.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),"permissionsConfig"===n.reason.type)return void(yield new he.FI({event:{case:"permissionDenied",value:new he.jn({command:o,workingDirectory:c,error:"Command blocked by permissions configuration",isReadonly:n.reason.isReadonly??!1})}}));const r=Yu(n.reason);return void(yield new he.FI({event:{case:"rejected",value:new he.pZ({command:o,workingDirectory:c,reason:r})}}))}s=n.policy,mM.info(e,"Shell stream: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:s.type})}s=await Tc(s,{command:o,workingDirectory:c,parsingResult:d,permissionsService:this.permissionsService,ignoreService:this.ignoreService}),yield new he.FI({event:{case:"start",value:new he.tD({sandboxPolicy:us(s)})}});const f=t.timeoutBehavior===he._d.BACKGROUND,m=f&&!t.closeStdin&&void 0===t.smartModeApproval,g=new AbortController,w=f?g.signal:e.signal?AbortSignal.any([e.signal,g.signal]):g.signal,y=!0,v=s?{perUser:s}:void 0,b=this.coreExecutor.execute(e,{command:o,workingDirectory:i,signal:w,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:v,fileOutputThresholdBytes:t.fileOutputThresholdBytes,pipeStdin:m,showElapsedTime:y});let S;f||(S=setTimeout((()=>g.abort()),a));const k=f?new gM(b[Symbol.asyncIterator](),a):null;let _,C,E,x="",P=!1,R=!1;const I=t.toolCallId&&k?{requestBackground:()=>{if(k.requestBackground())return E=E??this.backgroundShellManager.generateShellId(),new he.W4({result:{case:"success",value:new he.QR({shellId:E,pid:C,command:o,workingDirectory:c,msToWait:$y(performance.now()-u),backgroundReason:he.Jg.USER_REQUEST,interleavedOutput:x})}})}}:void 0;t.toolCallId&&I&&this.activeForegroundExecutions.set(t.toolCallId,I),this.settle(t.toolCallId,r,I);const T=()=>{t.toolCallId&&this.activeForegroundExecutions.get(t.toolCallId)===I&&this.activeForegroundExecutions.delete(t.toolCallId)},A=()=>{k&&!k.backgroundRequested&&(g.abort(),k.abort())};let M;k&&e.signal&&(e.signal.aborted?A():e.signal.addEventListener("abort",A,{once:!0}));const D=t.hardTimeout;void 0!==D&&D>0&&(M=setTimeout((()=>{void 0!==E?this.backgroundShellManager.abort(E)||g.abort():(P=!0,g.abort(),k?.abort())}),D));const O=k?.iterate()??b;try{for await(const r of O)if("stdout"===r.type)x+=r.data,yield new he.FI({event:{case:"stdout",value:new he.o0({data:r.data})}});else if("stderr"===r.type)x+=r.data,yield new he.FI({event:{case:"stderr",value:new he.Db({data:r.data})}});else if("stdin_ready"===r.type)_=r.stdin,C=r.pid;else if("exit"===r.type){let n;R=!0,r.aborted&&(n=e.signal?.aborted?he.Lv.USER_ABORT:k?.timedOut||g.signal.aborted?he.Lv.TIMEOUT:he.Lv.USER_ABORT),yield new he.FI({event:{case:"exit",value:new he.vb({code:(r.code??-1)>>>0,cwd:await this.coreExecutor.getCwd(t.conversationId),outputLocation:r.outputLocation,aborted:r.aborted,abortReason:n,localExecutionTimeMs:$y(r.localExecutionTimeMs)})}})}}catch(r){if(!(r instanceof Oo.SandboxUnsupportedError))throw r;const n=s?.type??"unknown";return mM.debug(e,"Shell stream: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:n,reason:r.reason}),void(yield new he.FI({event:{case:"sandboxUnsupported",value:new he.rI({command:o,workingDirectory:c,sandboxPolicyType:n,reason:r.reason??r.message,isReadonly:"workspace_readonly"===n})}}))}finally{clearTimeout(S),k?.backgroundRequested||clearTimeout(M),T(),!k||k.backgroundRequested||R||g.abort(),e.signal?.removeEventListener("abort",A)}if(k?.backgroundRequested&&!P){const r=E??this.backgroundShellManager.generateShellId();E=r;const n=k.backgroundReasonValue===he.Jg.USER_REQUEST?he.Jg.USER_REQUEST:he.Jg.TIMEOUT,s=n===he.Jg.USER_REQUEST?Math.round(performance.now()-u):a;await this.backgroundShellManager.adopt({ctx:e,shellId:r,command:o,workingDirectory:c,toolCallId:t.toolCallId,sandboxPolicy:v,initialOutput:x,stdin:_,pid:C,abortController:g,eventIterator:k.getHandoffIterator(),startTime:l,monotonicStartMs:u,showElapsedTime:y,description:t.description,outputNotification:t.outputNotification,onCleanup:()=>clearTimeout(M)}),yield new he.FI({event:{case:"backgrounded",value:new he.Y9({shellId:r,command:o,workingDirectory:c,pid:C,msToWait:y?s:void 0,reason:n})}})}else e.signal?.aborted&&void 0!==k?.stopReasonValue?(clearTimeout(M),yield new he.FI({event:{case:"exit",value:new he.vb({code:4294967295,cwd:await this.coreExecutor.getCwd(t.conversationId),aborted:!0,abortReason:he.Lv.USER_ABORT})}})):clearTimeout(M)}catch(e){n.error=e,n.hasError=!0}finally{fM(n)}}}const vM={kind:"absent"};class bM{constructor(e){this.cells=new Map,this.takenCells=new WeakMap,this.collectedCells=new FinalizationRegistry((e=>{void 0===this.cells.get(e)?.deref()&&this.cells.delete(e)})),this.claims=new Map,this.nextGeneration=0,this.entries=new Eo.q({max:1e3,ttl:6e4,ttlResolution:0,perf:e})}begin(e){this.entries.purgeStale();const t=++this.nextGeneration;return this.claims.set(PM(e),t),t}record(e,t,r){if(!this.claim(e,r))return;const n=PM(e);this.entries.set(n,{recorded:t,generation:r}),this.commitGeneration(n,r)}forget(e,t){if(!this.claim(e,t))return;const r=PM(e);this.entries.delete(r),this.commitGeneration(r,t)}end(e,t){this.claim(e,t)}take(e){const t=PM(e),r=this.entries.get(t);if(void 0===r)return;const n=this.entries.getRemainingTTL(t);this.entries.delete(t);let o=this.cells.get(t)?.deref();void 0===o&&(o={committed:r.generation},this.cells.set(t,new WeakRef(o)),this.collectedCells.register(o,t));const s={read:e,recorded:r.recorded,remainingTtlMs:n,generation:r.generation};return this.takenCells.set(s,o),s}restore(e){const t=this.takenCells.get(e);if(void 0===t||t.committed!==e.generation)return;const r=PM(e.read);this.entries.has(r)||!Number.isFinite(e.remainingTtlMs)||e.remainingTtlMs<=0||this.entries.set(r,{recorded:e.recorded,generation:e.generation},{ttl:e.remainingTtlMs})}commitGeneration(e,t){const r=this.cells.get(e)?.deref();void 0!==r&&(r.committed=t)}claim(e,t){const r=PM(e);return this.claims.get(r)===t&&(this.claims.delete(r),!0)}}class SM{constructor(){this.views=new Eo.q({max:1e3})}get(e){return this.views.get(e)}set(e,t){this.views.set(e,t)}forget(e){this.views.delete(e)}recordWrite(e,t){if(t.length>Gs)return void this.views.delete(e);const r=(0,bo.createHash)("sha256").update(t).digest("hex");this.views.set(e,{kind:"fingerprint",byteLength:t.length,sha256:r})}recordDelete(e){this.views.set(e,vM)}}async function kM(e,t){if(void 0===e)return!1;try{if("absent"===e.kind)return await xM(t);const r=await EM(t);return void 0===r||r.byteLength!==e.byteLength||r.sha256!==e.sha256}catch{return!1}}async function _M(e,t){if("fingerprint"!==e?.kind)return!1;try{return!await xM(t)}catch{return!1}}class CM{constructor(e,t,r,n,o){this.inner=e,this.reads=t,this.permissionsService=r,this.workspacePath=n,this.views=o}async execute(e,t,r){const n=!0===r?.recordAgentView?(0,Yo.o1)(t.path,this.workspacePath):void 0,o=function(e,t){if(""!==e.toolCallId&&void 0===e.offset&&void 0===e.limit)return{toolCallId:e.toolCallId,resolvedPath:(0,Yo.o1)(e.path,t)}}(t,this.workspacePath);if(void 0===o){const o=await this.inner.execute(e,t,r);return this.forgetViewReadPast(n,o),o}const s=this.reads.begin(o);try{let i,a;try{i=await Zk(this.permissionsService,o.resolvedPath)}catch{return await this.readAndForget(e,t,r,o,s,n)}if(!1!==i&&"needsApproval"!==i.type)return await this.readAndForget(e,t,r,o,s,n);if(!1!==i){const i=await this.inner.execute(e,t,r),a=await async function(e,t){if("success"===e.result.case&&"content"===e.result.value.output.case)try{return await EM(t)}catch{return}}(i,o.resolvedPath);return this.commit(o,s,i,a,n),i}try{a=await EM(o.resolvedPath)}catch{return await this.readAndForget(e,t,r,o,s,n)}const c=await this.inner.execute(e,t,r);return this.commit(o,s,c,a,n),c}finally{this.reads.end(o,s)}}commit(e,t,r,n,o){let s;if("fileNotFound"===r.result.case?s=vM:void 0!==n&&"success"===r.result.case&&"content"===r.result.value.output.case&&(s={kind:"fingerprint",...n}),void 0===s)return this.reads.forget(e,t),void this.forgetViewReadPast(o,r);this.reads.record(e,s,t),void 0!==o&&this.views?.set(o,s)}async readAndForget(e,t,r,n,o,s){const i=await this.inner.execute(e,t,r);return this.reads.forget(n,o),this.forgetViewReadPast(s,i),i}forgetViewReadPast(e,t){void 0===e||"success"!==t.result.case&&"fileNotFound"!==t.result.case||this.views?.forget(e)}}async function EM(e){try{const t=await(0,Co.stat)(e);if(!t.isFile()||t.size>Gs)return}catch(e){return RM(e)}let t;try{t=await(0,Co.open)(e,function(){const e=xo.constants;return e.O_RDONLY|(e.O_NONBLOCK??0)}());const r=await t.stat();if(!r.isFile()||r.size>Gs)return;const n=(0,bo.createHash)("sha256");let o=0;const s=Buffer.alloc(65536);for(;o<=Gs;){const{bytesRead:e}=await t.read(s,0,s.length,o);if(0===e)break;o+=e,n.update(s.subarray(0,e))}if(o>Gs)return;return{byteLength:o,sha256:n.digest("hex")}}catch(e){return RM(e)}finally{await(t?.close())}}async function xM(e){try{return await(0,Co.stat)(e),!0}catch(e){if(IM(e))return!1;throw e}}function PM({toolCallId:e,resolvedPath:t}){return`${e}\0${t}`}function RM(e){if(!IM(e))throw e}function IM(e){const t=Sc(e);return"ENOENT"===t||"ENOTDIR"===t}var TM=r("../proto/dist/generated/agent/v1/web_fetch_allowlist_precheck_exec_pb.js");class AM{constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isWebFetchFullyAllowlisted(e,{url:t.url});return new TM.M({allowlisted:r})}}var $M=r("node:constants");const MM=[".md",".markdown",".mdown",".mkd",".mkdn",".mdx"];function DM(e){const t=e.trim().toLowerCase();return MM.some((e=>t.endsWith(e)))}function OM(e,t){const r=e.trim().toLowerCase().split("win32"===t?/[\\/]/:"/");if(r.some((e=>"."===e||".."===e)))return!1;const[n,o,s,i,a]=r.slice(-5);return r.length>=5&&".cursor"===n&&"projects"===o&&void 0!==s&&""!==s&&"canvases"===i&&void 0!==a&&a.length>11&&a.endsWith(".canvas.tsx")}const FM="win32"===process.platform;process.platform;const NM="\\"===s.sep?"win32":"posix",LM={allowed:!1};class jM extends Error{constructor(e,t){super(t),this.name="SymlinkRefusedError",this.path=e}}function UM(e,{nonBlocking:t}){const r=xo.constants;let n=e;return"number"==typeof r.O_NOFOLLOW&&(n|=r.O_NOFOLLOW),t&&"number"==typeof r.O_NONBLOCK&&(n|=r.O_NONBLOCK),"number"==typeof r.O_CLOEXEC&&(n|=r.O_CLOEXEC),n}const BM=[20,40,80],WM=new Set(["UNKNOWN","EBUSY"]);async function HM(e,t){try{const[r,n]=await Promise.all([t.stat({bigint:!0}),(0,Co.lstat)(e,{bigint:!0})]);r.dev===n.dev&&r.ino===n.ino&&await(0,Co.unlink)(e)}catch{}}async function qM(e,t,r,{removeOnRefusal:n=!1}={}){let o;try{o=await async function(e,t){try{return await(0,Co.open)(e,UM(t,{nonBlocking:!0}),438)}catch(r){const n=Sc(r);if(("EAGAIN"===n||"EWOULDBLOCK"===n)&&await async function(e){try{return(await(0,Co.lstat)(e)).isFile()}catch{return!1}}(e))return await(0,Co.open)(e,UM(t,{nonBlocking:!1}),438);throw r}}(e,t)}catch(t){if(function(e){const t=Sc(e);return"ELOOP"===t||"EMLINK"===t||"EPERM"===t&&"number"==typeof xo.constants.O_NOFOLLOW}(t))throw new jM(e,`Refusing to ${r} through a symlink at ${e}`);throw t}try{let t;try{t=(0,xo.realpathSync)(e)}catch{throw new jM(e,`Cannot verify canonical path before ${r}: ${e}`)}if(t!==e)throw new jM(e,`Refusing ${r}: ${e} now resolves through a symlinked parent to ${t}`);const n=await o.stat();if(!n.isFile())throw new jM(e,`Refusing to ${r} non-regular file at ${e}`);return{fd:o,stats:n}}catch(t){throw n&&await HM(e,o),await o.close(),t}}var zM=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const GM=(0,l.h)("LocalWriteExecutor"),VM=(0,u.Pu)("local_exec.write.encoding_check",{description:"Text writes that landed, per encoding detector (mojibake, U+FFFD): whether the written text holds the pattern and holds more of it than the file did, and for a detection what the file held, its extension family, encoding and the machine's Windows code page",labelNames:["detector","outcome","file","ext","encoding","code_page","run_count","delta","before_count","pattern"]}),KM=async(e,t,r,n)=>{const o=setTimeout((()=>{GM.warn(e,`[watchdog, LocalWriteExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function JM(e){return new Error(`Could not create ${e}: directory creation exceeded the path depth and was stopped.`)}async function ZM(e){try{return(await(0,Co.stat)(e)).isDirectory()?"directory":"present"}catch(e){if("ENOENT"===Sc(e))return"missing";throw e}}async function XM(e,t){const r=[];let n=e;for(let o=0;o<=t;o+=1){const t=await ZM(n);if("directory"===t)return r.reverse(),r;if("present"===t)return await(0,Co.mkdir)(n,{recursive:!1}),r.reverse(),r;r.push(n);const o=(0,s.dirname)(n);if(o===n){const t=new Error(`ENOENT: no such file or directory, mkdir '${e}'`);throw t.code="ENOENT",t.syscall="mkdir",t.path=e,t}n=o}throw JM(e)}class QM{constructor(e,t,r,{workspacePaths:n,workspacePath:o,worktreeMainPath:s,projectDir:i,onWriteForAiTracking:a,writeFileMutationGuard:c,toolCallReads:l,agentFileViews:u}){this.fileChangeTracker=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.workspacePaths=n,this.workspacePath=o,this.worktreeMainPath=s,this.projectDir=i,this.onWriteForAiTracking=a,this.writeFileMutationGuard=c,this.toolCallReads=l,this.agentFileViews=u}async execute(e,t,r){if(function(e){if(!e.startsWith("file://"))return!1;try{return(0,Ed.fileURLToPath)(e),!1}catch{return!0}}(t.path))return new MI.v3({result:{case:"error",value:new MI.QM({path:t.path,error:`${t.path} is not a valid file URL. Use an absolute path instead.`})}});const n=(0,Yo.o1)(t.path,this.workspacePath),o=this.toolCallReads,s=void 0!==o&&""!==t.toolCallId?o.take({toolCallId:t.toolCallId,resolvedPath:n}):void 0,i=!0===r?.refuseUnreadChanges?this.agentFileViews?.get(n):void 0,a={writeStarted:!1},c=()=>{void 0===s||a.writeStarted||o?.restore(s)};try{const r=await this.executeWithRecord(e,t,n,s?.recorded,i,a);return tD(r)&&c(),r}catch(e){throw c(),e}}async executeWithRecord(e,t,r,n,o,i){const a={stack:[],error:void 0,hasError:!1};try{const c=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(a,(0,$.VI)(e.withName("LocalWriteExecutor.execute")),!1).ctx,l=(t.path,t.fileText),u=t.fileBytes.length>0?t.fileBytes:void 0,d=["assets","agent-tools","swarm-agents"],h=yS(r,d)||void 0!==this.projectDir&&!this.workspacePaths.some((e=>{return t=e,n=r,FM&&(t=t.toLowerCase(),n=n.toLowerCase()),t===n||(t.charAt(t.length-1)!==s.sep&&(t+=s.sep),n.startsWith(t));var t,n}))&&vS(this.projectDir,r,d);if((0,Yo.fl)({targetPath:r,workspacePaths:this.workspacePaths,mainWorktreePath:this.worktreeMainPath}))return new MI.v3({result:{case:"error",value:new MI.QM({path:r,error:Yo.PS})}});let p,f,m,g,w=!1;try{const e=await(0,Co.stat)(r);if(g=511&e.mode,e.size<=ns){const e=await KM(c,"readText before write",3e3,(()=>Ui(r,t.encodingHint)));p=e.text,f=e.encoding,m=Uw(e)}else w=!0}catch(e){w="ENOENT"!==Sc(e)}const y=await DS(r),v=y.resolvedPath;if(t.confineToWorkspace){let e=(await Promise.all(this.workspacePaths.map((e=>(0,Co.realpath)(e).catch((()=>{})))))).filter((e=>void 0!==e));if(0===e.length&&void 0!==this.projectDir){const t=await(0,Co.realpath)(this.projectDir).catch((()=>{}));void 0!==t&&(e=[t])}if(!e.some((e=>(0,Yo.BJ)(v,e))))return new MI.v3({result:{case:"error",value:new MI.QM({path:r,error:"downloadPath must stay within the workspace"})}})}const b=async()=>{return await kM(n,v)?BT(r):(t=n,void 0!==(e=o)&&void 0!==t&&e.kind===t.kind&&("absent"===e.kind||"fingerprint"===t.kind&&e.byteLength===t.byteLength&&e.sha256===t.sha256)||!await kM(o,v)?void 0:WT(r));var e,t},S=t.planMode?await KM(c,"checkPlanModeWriteTarget",3e3,(()=>async function(e,t){switch(t.resolution.status){case"resolved":case"newFile":return DM(t.resolvedPath)?{allowed:!0}:await async function(e,t){if(!(OM(t.resolvedPath,NM)||OM(e,NM)&&t.resolvedPath===await async function(e){const t=(0,s.dirname)((0,s.dirname)((0,s.dirname)((0,s.dirname)(e)))),r=await DS(t);if(OS(r.resolution))return(0,s.join)(r.resolvedPath,(0,s.relative)(t,e))}(e)))return LM;if("newFile"===t.resolution.status)return{allowed:!0,singleLink:{kind:"create"}};const r=await async function(e){try{const t=await(0,Co.lstat)(e,{bigint:!0});return t.isFile()&&1n===t.nlink?{kind:"existing",dev:t.dev,ino:t.ino}:void 0}catch{return}}(t.resolvedPath);return void 0===r?LM:{allowed:!0,singleLink:r}}(e,t);case"danglingSymlink":{const e=await async function(e){let t=e;for(let e=0;e<40;e++){let e;try{e=await(0,Co.readlink)(t)}catch(e){const r=Sc(e);return"ENOENT"===r||"EINVAL"===r?t:void 0}t=(0,s.resolve)((0,s.dirname)(t),e)}}(t.resolvedPath);return void 0!==e&&DM(e)?{allowed:!0}:LM}case"permissionDenied":case"symlinkLoop":case"unknownError":return LM;default:return t.resolution,LM}}(r,y))):void 0;if(void 0!==S&&!S.allowed)return new MI.v3({result:{case:"rejected",value:new MI.en({path:r,reason:"Cannot edit non markdown files in plan mode"})}});const k=(".cursorignore"===(r.split(s.sep).pop()?.toLowerCase()??"")?{type:"permissionsConfig"}:void 0)??await KM(c,"permissionsService.shouldBlockWrite",3e3,(()=>this.permissionsService.shouldBlockWrite(c,v,l)));if(k){const e=await KM(c,"handleBlockReason",3e3,(()=>Qu(k,{onNeedsApproval:async(e,n)=>{const o="fileEdit"!==n?.type||n.isNewFile,s="fileEdit"===n?.type?n.diffString:l,i="fileEdit"===n?.type?n.blockReason:void 0,a=await b();if(void 0!==a)return YM(r,a);const c=await this.pendingDecisionProvider.requestApproval({type:Lw.Write,details:{path:r,reason:e,isNewFile:o,diffString:s,before:p,after:l,blockReason:i},toolCallId:t.toolCallId});return c.approved?null:new MI.v3({result:{case:"rejected",value:new MI.en({path:r,reason:c.reason||""})}})},onUserRejected:e=>new MI.v3({result:{case:"rejected",value:new MI.en({path:r,reason:e||""})}}),onPermissionDenied:(e,t)=>new MI.v3({result:{case:"permissionDenied",value:new MI.U7({path:r,error:e,isReadonly:t?.isReadonly??!1})}})})));if(null!==e)return e}const _=await KM(c,"anotherSpellingRefusal",3e3,(()=>async function(e){const t=(0,s.basename)(e);let r;try{if(!(await(0,Co.stat)(e)).isFile())return;const n=await(0,Co.readdir)((0,s.dirname)(e));if(n.includes(t))return;const o=t.normalize("NFC");if(n.some((e=>e.normalize("NFC")===o)))return;const i=t.toLowerCase(),a=n.filter((e=>e.toLowerCase()===i)),c=o.toLowerCase();r=a.length>0?a:n.filter((e=>e.normalize("NFC").toLowerCase()===c))}catch{return}const n=1===r.length?r[0]:void 0;return void 0===n?`${t} names an existing file that this folder lists under another name, so writing it would replace that file. Nothing was written. List the folder and write the file by its listed name to change it; for a new file, choose a different name.`:`${t} names the existing file ${n}: this volume does not tell names apart by case, so writing it would replace ${n}. Nothing was written. To change that file, write ${n}; for a new file, choose a name no file in this folder has in any case.`}(r)));if(void 0!==_)return new MI.v3({result:{case:"error",value:new MI.QM({path:r,error:_})}});const C=(0,s.dirname)(v);if(await _M(n,C))return YM(r,BT(r));if(await _M(o,C))return YM(r,WT(r));let E,x,P,R;try{E=await KM(c,"mkdir",3e3,(()=>async function(e){const t=function(e){let t=0,r=e;for(;;){const e=(0,s.dirname)(r);if(e===r)return t;t+=1,r=e}}(e),r=t+4;let n=0,o=0,i=await XM(e,t),a=0;for(;ar)throw JM(e);try{await(0,Co.mkdir)(c,{recursive:!1})}catch(r){const n=Sc(r);if("EEXIST"===n){if("directory"!==await ZM(c))throw r;a+=1;continue}if("ENOENT"===n){const n=(0,s.dirname)(c);if(n===c||"missing"!==await ZM(n))throw r;i=await XM(e,t),a=0,o=0;continue}throw r}o+=1,a+=1}return o}(C)))}catch(e){const t=Sc(e);return"EACCES"===t||"EPERM"===t?new MI.v3({result:{case:"permissionDenied",value:new MI.U7({path:r,directory:C,operation:"create_directory",error:"Permission denied"})}}):new MI.v3({result:{case:"error",value:new MI.QM({path:r,error:kc(e)})}})}if(void 0!==u)x=u,P=0;else{const e=await KM(c,"getBufferForWrite",3e3,(()=>Wi(r,l,this.workspacePath,t.encodingHint)));x=e.buffer,P=e.lines,R=e.format.encoding}const I=()=>KM(c,"writeFile",3e3,(async()=>{const e=await b();if(void 0!==e)throw new Error(e);let t;c.signal.throwIfAborted(),i.writeStarted=!0,await async function(e,t,r){const n=r?.singleLink,{fd:o}=void 0===n?await qM(e,xo.constants.O_WRONLY|xo.constants.O_CREAT,"write"):await async function(e,t){const r="create"===t.kind,n=r?xo.constants.O_WRONLY|xo.constants.O_CREAT|xo.constants.O_EXCL:xo.constants.O_WRONLY;let o;try{o=await qM(e,n,"write",{removeOnRefusal:r})}catch(t){const r=Sc(t);if("EEXIST"===r||"ENOENT"===r)throw new jM(e,`Refusing to write: ${e} was ${"EEXIST"===r?"created":"removed"} after it was checked`);throw t}const{fd:s}=o;try{const r=await s.stat({bigint:!0});if(1n!==r.nlink)throw new jM(e,`Refusing to write: ${e} has ${r.nlink} hard links`);if("existing"===t.kind&&(r.dev!==t.dev||r.ino!==t.ino))throw new jM(e,`Refusing to write: ${e} was replaced after it was checked`);return o}catch(t){throw r&&await HM(e,s),await s.close(),t}}(e,n);try{await async function(e){for(let t=0;;t++)try{return void await e.truncate(0)}catch(e){const r=Sc(e);if(t>=BM.length||void 0===r||!WM.has(r))throw e;await(0,Fg.setTimeout)(BM[t])}}(o);const e=function(e){return Buffer.isBuffer(e)?e:Buffer.from(e)}(t);let n=0;for(;n{try{await I()}catch(e){throw T=e,A=!0,e}};try{void 0===this.writeFileMutationGuard?await I():await this.writeFileMutationGuard.runExclusive(v,M)}catch(e){if(void 0!==this.writeFileMutationGuard&&(!A||e!==T))return new MI.v3({result:{case:"error",value:new MI.QM({path:r,error:e instanceof Error?e.message:String(e)})}});if(e instanceof jM)return new MI.v3({result:{case:"permissionDenied",value:new MI.U7({path:r,directory:"",operation:"create_file",error:e.message})}});const t=Sc(e);return"EACCES"===t||"EPERM"===t?new MI.v3({result:{case:"permissionDenied",value:new MI.U7({path:r,directory:"",operation:"create_file",error:"Permission denied"})}}):"ENOSPC"===Sc(e)?new MI.v3({result:{case:"noSpace",value:new MI.bM({path:r})}}):"EDQUOT"===t?new MI.v3({result:{case:"error",value:new MI.QM({path:r,error:"Agent-store quota exceeded: this write was rejected because the storage quota is full. Nothing was written; your local copy is intact. Delete or truncate files to free space (including resolved *.conflict* files), then retry. Do not retry the same write without freeing space first."})}}):new MI.v3({result:{case:"error",value:new MI.QM({path:r,error:kc(e)})}})}if(this.fileChangeTracker&&void 0===u&&!h&&!w){const e={...t.toolCallId?{toolCallId:t.toolCallId}:{},...v===r?{}:{writtenPath:v},...void 0===g?{}:{beforeMode:g},...E>0?{createdDirectories:E}:{}};await this.fileChangeTracker.trackChange(r,p,l,e,m)}if(this.onWriteForAiTracking&&void 0===u&&!h){const e=t.toolCallId?{toolCallId:t.toolCallId}:{};try{await this.onWriteForAiTracking({path:r,beforeContent:p,afterContent:l,metadata:e})}catch(e){GM.warn(c,"onWriteForAiTracking failed (write succeeded)",{path:r,error:e instanceof Error?e.message:String(e)})}}const D=x.byteLength;let O;if(void 0!==u||w||h||this.recordEncodingChecks(c,r,p,f,l),t.returnFileContentAfterWrite)try{O=await KM(c,"readText after write",3e3,(()=>ji(r,t.encodingHint)))}catch{}return new MI.v3({result:{case:"success",value:new MI.j6({path:r,linesCreated:P,fileSize:D,...void 0!==O&&{fileContentAfterWrite:O}})}})}catch(e){a.error=e,a.hasError=!0}finally{zM(a)}}recordEncodingChecks(e,t,r,n,o){try{const i={path:t,encoding:n,pages:(s=gu.pages(),"failed"===s?"none":s)};for(const t of function(e,t,r){return[gl(e,t,r),wl(e,t,r)]}(r,n,o))VM.increment(e,1,_l(t,i))}catch(t){for(const t of ll)VM.increment(e,1,{detector:t,outcome:"error",file:"unclassified"});GM.warn(e,"encoding check failed (write succeeded)",{error:t instanceof Error?t.message:String(t)})}var s}}function YM(e,t){return new MI.v3({result:{case:"error",value:new MI.QM({path:e,error:t})}})}class eD extends Error{constructor(e){super("stale write refusal"),this.result=e,this.name="StaleWriteRefusal"}}function tD(e){if("error"!==e.result.case)return!1;const{error:t,path:r}=e.result.value;return t===BT(r)||t===WT(r)}const rD=(0,l.h)("local-exec:provider"),nD=new Set,oD=new yd.AsyncLocalStorage;class sD extends K{getMcpExecutionPolicyDeps(){return{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionStore}}static dropOwnedRequestContextCaches(){for(const e of nD)e.ownedRequestContextExecutor?.invalidateGlobalCache()}static rebuildRequestContextCachesFor(e){for(const t of nD)t.cursorRulesService===e&&t.ownedRequestContextExecutor?.refreshGlobalCache()}constructor(e){super(),this.pendingDecisionStore=e.pendingDecisionStore,this.fileChangeTracker=e.fileChangeTracker,this.gitExecutor=e.gitExecutor,this.ignoreService=e.ignoreService,this.grepProvider=e.grepProvider,this.permissionsService=e.permissionsService,this.workspacePaths=e.workspacePaths,this.worktreeMainPath=e.worktreeMainPath,this.diagnosticsProvider=e.diagnosticsProvider,this.mcpLease=e.mcpLease,this.mcpStateAccessor=e.mcpStateAccessor,this.cursorRulesService=e.cursorRulesService,this.cloudRulesService=e.cloudRulesService,this.subagentsService=e.subagentsService,this.repositoryProvider=e.repositoryProvider,this.projectDir=e.projectDir,this.shellManager=e.shellManager,this._sandboxPolicyResolver=e._sandboxPolicyResolver,this._defaultSandboxPolicy=e._defaultSandboxPolicy??{type:"insecure_none"};const t=e.workspacePaths[0],r=t?function(e){const t=(0,s.join)(e,".cursor/sandbox.json");try{const r=(0,xo.readFileSync)(t,"utf-8"),n=JSON.parse(r),o=(0,Oo.$6)(n);return(0,Oo.l7)(o,e)}catch{return}}(t):void 0,n=e._defaultSandboxPolicySources;this._defaultSandboxPolicySources=r||n?{perUser:n?.perUser,perRepo:r??n?.perRepo,teamAdmin:n?.teamAdmin}:void 0,this.mcpFileOutputThresholdBytes=e.mcpFileOutputThresholdBytes,this.blankSharedPaymentTokensInMcpOutputFiles=!0===e.blankSharedPaymentTokensInMcpOutputFiles,this.backgroundShellFactory=e.backgroundShellFactory,this.backgroundWorkRegistry=e.backgroundWorkRegistry,this.wakeupOwnerConversationId=e.wakeupOwnerConversationId,this.mcpElicitationFactory=e.mcpElicitationFactory,this.createFileWatcher=e.createFileWatcher,this.sharedRequestContextExecutor=e.sharedRequestContextExecutor,this.terminalExecutor=e.terminalExecutor,this.mcpMetaToolEnabled=e.mcpMetaToolEnabled??!1,this.mcpMetaToolSlimDescriptors=e.mcpMetaToolSlimDescriptors??!1,this.mcpInputSchemaJson=e.mcpInputSchemaJson??!1,this.alwaysExposeVirtualMcpAuthTool=e.alwaysExposeVirtualMcpAuthTool??!1,this.enableRecordScreen=e.enableRecordScreen??!1,this.recordScreenArtifactsDir=e.recordScreenArtifactsDir,this.recordScreenDisplay=e.recordScreenDisplay,this.disableRecordScreenRendering=e.disableRecordScreenRendering??!1,this.userTerminalHint=e.userTerminalHint,this.attributionConfigProvider=e.attributionConfigProvider,this.isAttributionDisabledByAdmin=e.isAttributionDisabledByAdmin,this.getAgentSkills=e.getAgentSkills,this.getSmartModeClassifierAutoModeEnabled=e.getSmartModeClassifierAutoModeEnabled,this.getAdminCommandDenylist=e.getAdminCommandDenylist,this.devForceNextSmartModeClassifierBlockToken=e.devForceNextSmartModeClassifierBlockToken,this.getMockPromptTime=e.getMockPromptTime,this.additionalRules=e.additionalRules??[],this.askpassConfig=e.askpassConfig,this.rebuildRequestContextOnRulesChange=!0===e.rebuildRequestContextOnRulesChange;const i=this.terminalExecutor??(0,Oo.Fn)({env:{CURSOR_AGENT:"1"},userTerminalHint:this.userTerminalHint,isLoginShellEnabled:e.isLoginShellEnabled});let a;if(this.workspacePaths.length>1){const e=this.workspacePaths.map((e=>(0,s.dirname)(e)));a=e.every((t=>t===e[0]))?e[0]:void 0}else a=t;let c=new Ju(i,t??(0,o.homedir)(),this.projectDir,{shellOutputBackpressureOptions:e.shellOutputBackpressureOptions,extraEnvProvider:e.shellExtraEnvProvider,powershellUtf8Console:e.powershellUtf8Console,powershellUtf8ChildEnv:e.powershellUtf8ChildEnv,powershellParseAfterUtf8Switch:e.powershellParseAfterUtf8Switch,powershellWebRequestUtf8:e.powershellWebRequestUtf8,powershellPerLineStateDump:e.powershellPerLineStateDump,encodingSlices:e.encodingSlices,keepBackgroundJobs:e.keepShellBackgroundJobs});e.shellCoreWrapper&&(c=e.shellCoreWrapper(c)),this.askpassConfig&&(c=new Xu(c,this.askpassConfig)),this.shellManager&&(c=new Zu(c,this.shellManager));const l=e.overrideShellExecutor??(!0===e.suppressDefaultShellExecutor?void 0:new uM(this.permissionsService,c,this.ignoreService,this.pendingDecisionStore));void 0!==l&&this.register(jT,Dg(l)),this.register(UT,Dg(new LT(this.permissionsService,this.ignoreService,a??t??this.projectDir)));const u=new bM,d=new SM,h=e.overrideWriteExecutor??new QM(this.fileChangeTracker,this.permissionsService,this.pendingDecisionStore,{workspacePaths:this.workspacePaths,workspacePath:a,worktreeMainPath:this.worktreeMainPath,projectDir:this.projectDir,onWriteForAiTracking:e.onWriteForAiTracking,writeFileMutationGuard:e.writeFileMutationGuard,toolCallReads:u,agentFileViews:d});this.register(HT,function(e){const t=(r={execute:(t,r,n)=>e.execute(t,r,n).then((e=>{if(tD(e))throw new eD(e);return e}))},Dg(r));var r;return{async execute(e,r,n){try{return await t.execute(e,r,n)}catch(e){if(e instanceof eD)return e.result;throw e}}}}(h));const p=e.overrideDeleteExecutor??new Hw(this.pendingDecisionStore,this.fileChangeTracker,this.permissionsService,a,e.onDeleteForAiTracking,d);this.register(qT,Dg(p)),this.register(zT,Dg(new Jw({encodingSlices:e.encodingSlices}))),this.register(GT,new C$);const f=this.mcpStateAccessor??new oM(this.mcpLease),m=e.overrideGrepExecutor??new dC(this.ignoreService,this.grepProvider,this.workspacePaths,{mcpStateAccessor:f,permissionsService:this.permissionsService,useStreamingGrep:e.useStreamingGrep,encodingSlices:e.encodingSlices});this.register(VT,Dg(m));const g=e.overrideReadExecutor??new CM(new L_(this.permissionsService,a,{mcpStateAccessor:f,useStreamingRead:e.useStreamingRead,pendingDecisionProvider:this.pendingDecisionStore,encodingSlices:e.encodingSlices}),u,this.permissionsService,a,d),w=new XT(g);this.register(QT,w),e.registerRedactedReadExecutor&&this.register(YT,w);const y=e.overrideLsExecutor??new yC(this.permissionsService,this.ignoreService,a);this.register(eA,Dg(y)),this.register(tA,Dg(new WA(a,this.diagnosticsProvider))),e.getCanvasDiagnostics&&this.register(rA,Dg(new OA(e.getCanvasDiagnostics,e.beginCanvasSave))),this.register(eo,Dg(new yA(ru(new PT(this.mcpLease,this.permissionsService,this.pendingDecisionStore,this.projectDir,this.mcpFileOutputThresholdBytes,this.mcpElicitationFactory,e.ensureMcpServersLoaded,{blankSharedPaymentTokens:this.blankSharedPaymentTokensInMcpOutputFiles}),e.encodingSlices,"exec_mcp",(e=>"success"===e.result.case)),(()=>this.get(QT))))),this.register(to,Dg(new RT(this.mcpLease,e.ensureMcpServersLoaded))),this.register(ro,Dg(ru(new IT(this.mcpLease,a||this.projectDir,this.permissionsService,this.workspacePaths,this.pendingDecisionStore,e.ensureMcpServersLoaded,h),e.encodingSlices,"exec_mcp",(e=>"success"===e.result.case)))),this.register(no,Dg(new iM(f,e.ensureMcpServersLoaded,{filterToRequestedServers:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,...void 0===e.mcpServerRuleSubjects?{}:{serverRuleSubjects:e.mcpServerRuleSubjects}})));const v=this.sharedRequestContextExecutor??this.createOwnedRequestContextExecutor(f,t,e),b=Dg({execute:(e,t,r)=>{const n=oD.getStore();return void 0!==n&&(n.ran=!0),v.execute(e,t,r)}});this.register($r,{execute:async(t,r,n)=>{const o={ran:!1},s=await oD.run(o,(()=>b.execute(t,r,n)));if("success"!==s.result.case||void 0===s.result.value.requestContext)return s;const i=s.clone();if("success"!==i.result.case)return s;const a=i.result.value.requestContext;if(void 0===a)return i;const c=await f.getState(t),l=eM(c,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson});if(a.tools=l.tools,a.mcpInstructions=l.mcpInstructions,a.mcpMetaToolOptions=this.mcpMetaToolEnabled?tM(c,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,slimDescriptors:this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}):void 0,o.ran&&void 0!==e.getMcpFileSystemOptions||(a.mcpFileSystemOptions=await(e.getMcpFileSystemOptions?.(t))),void 0!==a.env&&(a.env.artifactsFolder=e.getArtifactsFolder?.(t),void 0!==e.getSandboxEnabled&&(a.env.sandboxEnabled=e.getSandboxEnabled()),void 0!==e.getSessionSandboxSupported&&(a.env.sandboxSupported=e.getSessionSandboxSupported())),void 0!==e.getMountedAgentStores&&void 0!==a.env)try{const r=await e.getMountedAgentStores(t);a.env.mountedAgentStores=r.map((e=>e.clone()))}catch{a.env.mountedAgentStores=[],rD.warn(t,"Failed to get mounted agent stores; continuing without prompt inventory")}return i}}),this.backgroundShellExecutor=new wd(this.permissionsService,c,this.ignoreService,this.projectDir,this.backgroundShellFactory,this.backgroundWorkRegistry,this.wakeupOwnerConversationId,e.backgroundShellManager),this.shellRedeliveryCaches=e.shellRedeliveryCaches??{backgroundShell:Mg(),shellStream:Mg(),writeStdin:Mg()},this.register(vA,Dg(this.backgroundShellExecutor,void 0,this.shellRedeliveryCaches.backgroundShell)),this.shellStreamExecutor=new yM(this.permissionsService,c,this.ignoreService,this.backgroundShellExecutor.getManager()),this.register(ee,function(e,t,r=Mg(t)){return{async*execute(t,n,o){if(!o?.execId)return void(yield*e.execute(t,n,o));const s=$g(o.execId,n),i=r.get(s);if(i)return void(yield*i.fork());const a=e.execute(t,n,o),c=new Ag(a);r.set(s,c),yield*c.fork()}}}(this.shellStreamExecutor,void 0,this.shellRedeliveryCaches.shellStream)),void 0!==e.agentStoreConflictDrainer&&this.register(SA,new AA(e.agentStoreConflictDrainer)),this.register(kA,new hM(this.permissionsService)),this.register(_A,new x$(this.permissionsService)),this.register(CA,new AM(this.permissionsService));const S=new pM(this.shellStreamExecutor);this.register(EA,Dg(S));const k=!1===e.enableWriteBackgroundShellStdin?new $A((async()=>{throw new Error(e.writeBackgroundShellStdinDisabledReason??"write_shell_stdin is disabled for this session")})):new $A(((e,t)=>this.backgroundShellExecutor.writeStdin(e,t)));if(this.register(bA,Dg(k,void 0,this.shellRedeliveryCaches.writeStdin)),e.computerUseExecutor&&(this.computerUseExecutor=e.computerUseExecutor,this.register(xA,Dg(this.computerUseExecutor)),void 0!==e.computerUseEndTurnExecutor&&this.register(PA,e.computerUseEndTurnExecutor)),this.enableRecordScreen){if(!this.recordScreenArtifactsDir||!this.recordScreenDisplay)throw new Error("recordScreenArtifactsDir and recordScreenDisplay are required when enableRecordScreen is true");this.recordScreenExecutor=new F$({artifactsDir:this.recordScreenArtifactsDir,display:this.recordScreenDisplay,disablePolishedRendering:this.disableRecordScreenRendering,polishedRenderer:e.polishedRecordingRenderer}),this.register(RA,Dg(this.recordScreenExecutor))}}createOwnedRequestContextExecutor(e,t,r){const n=new aM(this.cursorRulesService,this.cloudRulesService,this.subagentsService,this.repositoryProvider,this.grepProvider,e,this.gitExecutor,void 0===r.requestContextWorkspacePaths?this.workspacePaths:[...r.requestContextWorkspacePaths],{projectDir:this.projectDir,isWorkingDirHomeDir:r.requestContextIsWorkingDirHomeDir??(0,Yo.yn)(t,(0,o.homedir)()),agentNotesEnabled:r.agentNotesEnabled,reportProcessWorkingDirectory:r.reportProcessWorkingDirectory,sectionLoadTimeoutMs:r.requestContextSectionLoadTimeoutMs,reportSectionCompleteness:r.reportRequestContextSectionCompleteness,freshSectionWaitMs:r.requestContextFreshSectionWaitMs,createFileWatcher:this.createFileWatcher,getSandboxEnabled:r.getSandboxEnabled,getSandboxSupported:r.getSandboxSupported,getNetworkAllowlistInfo:r.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:this.getSmartModeClassifierAutoModeEnabled,getAdminCommandDenylist:this.getAdminCommandDenylist,devForceNextSmartModeClassifierBlockToken:this.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:this.getMockPromptTime,userTerminalHint:this.userTerminalHint,getMcpFileSystemOptions:r.getMcpFileSystemOptions,mcpMetaToolEnabled:this.mcpMetaToolEnabled,mcpMetaToolSlimDescriptors:this.mcpMetaToolSlimDescriptors,mcpInputSchemaJson:this.mcpInputSchemaJson,alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,getArtifactsFolder:r.getArtifactsFolder,secretRedactionEnabled:r.secretRedactionEnabled,attributionConfigProvider:this.attributionConfigProvider,isAttributionDisabledByAdmin:this.isAttributionDisabledByAdmin,getAgentSkills:this.getAgentSkills,additionalRules:this.additionalRules,getComputerUseSupported:()=>void 0!==this.computerUseExecutor,getComputerUseDesktop:r.getComputerUseDesktop,onRequestContext:r.onRequestContext,mcpFieldsFromCaller:!0===r.requestContextMcpFieldsFromOverlay,deferWarmup:!0===r.deferRequestContextWarmup});return!0===r.deferRequestContextWarmup&&(this.requestContextExecutorAwaitingWarmup=n),this.rebuildRequestContextOnRulesChange&&(this.ownedRequestContextExecutor=n,nD.add(this),this.disposeRulesChangeListener=this.cursorRulesService.onDidChangeRules?.((()=>{n.rebuildAllCaches()}))),n}warmRequestContext(){const e=this.requestContextExecutorAwaitingWarmup;this.requestContextExecutorAwaitingWarmup=void 0,e?.warm()}getRecordScreenExecutor(){return this.recordScreenExecutor}getBackgroundShellManager(){return this.backgroundShellExecutor.getManager()}getShellRedeliveryCaches(){return this.shellRedeliveryCaches}hasForegroundShells(){return this.shellStreamExecutor.hasForegroundWork()}withPendingShells(e){return new J(e,[G(ee,this.shellStreamExecutor.pendingFrom(e))])}async dispose(){this.requestContextExecutorAwaitingWarmup=void 0,this.rebuildRequestContextOnRulesChange&&(nD.delete(this),this.disposeRulesChangeListener?.(),this.disposeRulesChangeListener=void 0,this.ownedRequestContextExecutor?.dispose(),this.ownedRequestContextExecutor=void 0),this.backgroundShellExecutor.dispose(),this.recordScreenExecutor&&await this.recordScreenExecutor.dispose()}}function iD(e){return e.replace(/\\/g,"/")}function aD(e,t){for(const r of t){const t=iD(r);if(e===t||e.startsWith(`${t}/`))return!0}return!1}var cD;function lD(e,t,r){if(function(e){return Boolean(e.plugin?.trim()||e.pluginId?.trim()||e.marketplaceId?.trim())}(e))return cD.Plugin;const n=iD(e.fullPath);return aD(n,r.builtinDirs)?cD.Builtin:Lm(e.fullPath,t).inAgentStore?cD.UserStore:aD(n,r.userDirs)?cD.UserHome:(aD(n,r.workspaceDirs),cD.Workspace)}"function"==typeof SuppressedError&&SuppressedError,function(e){e[e.Builtin=0]="Builtin",e[e.UserStore=1]="UserStore",e[e.UserHome=2]="UserHome",e[e.Workspace=3]="Workspace",e[e.Plugin=4]="Plugin"}(cD||(cD={}));var uD=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const dD=(0,zs.debuglog)("merged-agent-skills"),hD=(0,l.h)("merged-agent-skills");class pD{constructor(e,t=()=>[],r){this.services=e,this.getDisabledManagedSkillPaths=t,this.getPromptSortContext=r,this.onChangeCallbacks=new Set}async getAllAgentSkills(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,$.VI)(e.withName("MergedAgentSkillsService.getAllAgentSkills")),!1),n=this.services.map((e=>e.getAllAgentSkills(r.ctx).catch((e=>(dD("Failed to load agent skills from service: %s",e instanceof Error?e.message:String(e)),[]))))),o=async()=>{try{return{ok:!0,paths:await this.getDisabledManagedSkillPaths()}}catch(e){return hD.warn(r.ctx,"getDisabledManagedSkillPaths failed; failing closed by dropping all managed skills for this call",{error:e instanceof Error?e.message:String(e)}),{ok:!1}}},[i,a]=await Promise.all([Promise.all(n),o()]),c=i.flat(),l=this.getPromptSortContext?.(),u=Um(c,l??Fm);let d=u;return a.ok?a.paths.length>0&&(d=u.filter((e=>!function(e,t){if(!e)return!1;const r=e.replace(/\\/g,"/");return t.some((e=>r.endsWith(e)))}(e.fullPath,a.paths)))):d=u.filter((e=>{return!((t=e.fullPath)&&t.replace(/\\/g,"/").includes(fD));var t})),void 0!==l?function(e,t){if(e.length<=1)return e;const r=function(e){const t=[ym(e.userHomeDirectory).dirPath],r=Em(e.userHomeDirectory,!0).map((e=>e.dirPath)),n=[];for(const t of e.workspacePaths){n.push((0,s.join)(t,".cursor","rules"));for(const e of Cm(t,!0))n.push(e.dirPath)}return{builtinDirs:t,userDirs:r,workspaceDirs:n}}(t),n=e.map(((e,n)=>({skill:e,index:n,tier:lD(e,t,r)})));return n.sort(((e,t)=>e.tier-t.tier||e.index-t.index)),n.map((e=>e.skill))}(d,l):d}catch(e){t.error=e,t.hasError=!0}finally{uD(t)}}reload(e){for(const t of this.services)t.reload(e)}scheduleDidChangeSkills(){void 0===this.changeTimer&&(this.changeTimer=setTimeout((()=>{this.changeTimer=void 0;for(const e of Array.from(this.onChangeCallbacks))e()}),pD.CHANGE_COALESCE_MS))}ensureChangeListenersRegistered(){void 0===this.disposeChangeListeners&&(this.disposeChangeListeners=this.services.map((e=>e.onDidChangeSkills((()=>this.scheduleDidChangeSkills())))))}disposeChangeListenersIfUnused(){if(!(this.onChangeCallbacks.size>0||void 0===this.disposeChangeListeners)){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0,void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0)}}onDidChangeSkills(e){return this.onChangeCallbacks.add(e),this.ensureChangeListenersRegistered(),()=>{this.onChangeCallbacks.delete(e),this.disposeChangeListenersIfUnused()}}dispose(){if(void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0),this.onChangeCallbacks.clear(),void 0!==this.disposeChangeListeners){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0}for(const e of this.services)e.dispose()}}pD.CHANGE_COALESCE_MS=1500;const fD=`/${pm.configDir}/${pm.subdir}/`;function mD(e,t){if((e.disabledEnvironments??[]).includes(t))return!1;const r=e.environments??[];return 0===r.length||r.includes(t)}const gD=(0,l.h)("skill-sync-manifest"),wD=".sync-manifest.json",yD=new Set(["EPERM","EBUSY"]),vD=[20,50,100],bD=new Map;async function SD(e,t){try{const r=await(0,Co.readFile)((0,s.join)(e,wD),"utf-8"),n=JSON.parse(r);return function(e){if(!function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e))return!1;const t=e;return"number"==typeof t.version&&"object"==typeof t.skills&&null!==t.skills&&!Array.isArray(t.skills)&&(void 0===t.lastInventoryAt||"number"==typeof t.lastInventoryAt)}(n)?n:(gD.warn(t,"Manifest failed schema validation, resetting",{skillDir:e}),{version:1,skills:{}})}catch(r){return r instanceof Error&&"ENOENT"===Sc(r)||gD.debug(t,"Failed to read sync manifest, resetting",{skillDir:e,error:String(r)}),{version:1,skills:{}}}}function kD(e,t,r){e.skills[t]={lastSyncedAt:r}}function _D(e,t){delete e.skills[t]}var CD=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const ED=(0,l.h)("builtin-skills-sync");function xD(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function PD(e){for(const t of Object.keys(e.resources??{}))if(0===t.length||t.includes("\\")||t.includes("\0")||s.posix.isAbsolute(t)||s.posix.normalize(t)!==t||t.split("/").includes("..")||"SKILL.md"===s.posix.basename(t)||!t.endsWith(".md"))throw new Error(`Unsafe managed skill resource path: ${JSON.stringify(t)}`)}function RD(e){const t=eh(e.content),r=xD(t.data)?t.data:{};return th(`${t.content.trim()}\n`,function(e,t){const r={...t??{},name:e.id,description:e.description};delete r.disabledEnvironments,e.disableModelInvocation?r["disable-model-invocation"]=!0:delete r["disable-model-invocation"],e.environments&&e.environments.length>0?r.environments=e.environments:delete r.environments,e.disabledEnvironments&&e.disabledEnvironments.length>0?r["disabled-environments"]=e.disabledEnvironments:delete r["disabled-environments"];const n={...xD(r.metadata)?r.metadata:{}};return delete n.environments,delete n.disabledEnvironments,delete n["disabled-environments"],Object.keys(n).length>0?r.metadata=n:delete r.metadata,r}(e,r))}async function ID(e,t,r){const n=(0,s.join)(t,r.id),o=(0,s.join)(n,"SKILL.md"),i=r.fileContent,a=Object.keys(r.resources),c=await TD(n);if(a.length>0||c.length>0){const e=new Map([["SKILL.md",i],...Object.entries(r.resources)]),o=new Set(["SKILL.md",...c]);if(o.size===e.size&&[...e.keys()].every((e=>o.has(e)))){let t=!0;for(const[r,o]of e)try{if(await(0,Co.readFile)((0,s.join)(n,...r.split("/")),"utf-8")!==o){t=!1;break}}catch{t=!1;break}if(t)return!1}return await async function(e,t){const r=(0,s.join)(e,t.id),n=await(0,Co.mkdtemp)((0,s.join)(e,`.${t.id}-staging-`)),o=`${n}-backup`;let i=!1;try{await(0,Co.writeFile)((0,s.join)(n,"SKILL.md"),t.fileContent,"utf-8");for(const[e,r]of Object.entries(t.resources)){const t=(0,s.join)(n,...e.split("/"));await(0,Co.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,Co.writeFile)(t,r,"utf-8")}try{await(0,Co.rename)(r,o),i=!0}catch(e){if(!(e instanceof Error)||"ENOENT"!==Sc(e))throw e}try{await(0,Co.rename)(n,r)}catch(e){throw i&&(await(0,Co.rename)(o,r),i=!1),e}i&&(await(0,Co.rm)(o,{recursive:!0,force:!0}),i=!1)}finally{await(0,Co.rm)(n,{recursive:!0,force:!0})}}(t,r),!0}try{if(await(0,Co.readFile)(o,"utf-8")===i)return!1}catch(t){t instanceof Error&&"ENOENT"===Sc(t)||ED.warn(e,"Unexpected error reading skill file",{skillId:r.id,error:String(t)})}return await(0,Co.mkdir)(n,{recursive:!0}),await(0,Co.writeFile)(o,i,"utf-8"),!0}async function TD(e,t=""){const r=t?(0,s.join)(e,...t.split("/")):e;let n;try{n=await(0,Co.readdir)(r,{withFileTypes:!0})}catch(e){if(e instanceof Error&&"ENOENT"===Sc(e))return[];throw e}const o=[];for(const r of n){const n=t?`${t}/${r.name}`:r.name;r.isDirectory()?o.push(...await TD(e,n)):r.isFile()&&r.name.endsWith(".md")&&"SKILL.md"!==n&&o.push(n)}return o}async function AD(e,t){try{return(await(0,Co.readdir)(t,{withFileTypes:!0})).filter((e=>e.isDirectory()&&!e.name.startsWith("."))).map((e=>e.name))}catch(r){return r instanceof Error&&"ENOENT"===Sc(r)||ED.warn(e,"Failed to list skills directory, skipping cleanup",{skillDir:t,error:String(r)}),[]}}async function $D(e,t={}){const r={stack:[],error:void 0,hasError:!1};try{const i=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,$.VI)(e.withName("syncBuiltinSkills")),!1).ctx,a=Date.now(),c=t.userHome??(0,o.homedir)(),l=t.skillDir??ym(c).dirPath;await(0,Co.mkdir)(l,{recursive:!0});const[u,d]=await Promise.all([SD(l,i),AD(i,l)]),h=u.lastInventoryAt;(void 0===h||a-h>=864e5)&&(await async function(e,t,r,n){try{const o=await Promise.all(r.map((async e=>{const r=(0,s.join)(t,e),[o,i]=await Promise.all([MD((0,s.join)(r,"SKILL.md")),"canvas"===e?MD((0,s.join)(r,"sdk")):Promise.resolve(!1)]);return{skill_id:e,has_skill_md:o,has_sdk_dir:i,last_synced_at:n.skills[e]?.lastSyncedAt??null}})));ED.info(e,"managed_skills.startup_inventory",{skills_on_disk:o,manifest_present:Object.keys(n.skills).length>0})}catch(t){ED.warn(e,"Failed to emit managed skills startup inventory",{error:String(t)})}}(i,l,d,u),u.lastInventoryAt=a);const p=new Map;for(const e of t.managedSkills??[])(n=e.id)&&n===n.trim()&&!(n.includes("..")||n.includes("/")||n.includes("\\"))?p.set(e.id,e):ED.warn(i,"Skipping managed skill with unsafe id",{skillId:e.id});const f=void 0===t.canvasKit?void 0:bm(c,t.canvasKit).dirPath,m=void 0!==f&&await MD((0,s.join)(f,vm)),g=new Set([...p.keys(),...d,...m?[vm]:[]]),w=e=>void 0!==f&&e===vm?f:l,y=e=>void 0!==f&&e===vm?m:d.includes(e);let v=0,b=0;const S=[];for(const e of g)try{const t=p.get(e),r=u.skills[e],n=r?a-r.lastSyncedAt:0,o=void 0!==r&&n>2592e5,c=void 0!==t&&mD(t,"local"),d=void 0!==t&&!c,h=void 0!==r||y(e),f=w(e);if(t&&!1!==t.enabled&&c)PD(t),f!==l&&await(0,Co.mkdir)(f,{recursive:!0}),await ID(i,f,{id:e,fileContent:RD(t),resources:t.resources??{}})?v++:b++,kD(u,e,a);else if(!1===t?.enabled||d||o){const n=!1===t?.enabled?"enabled_false":d?"environment_ineligible":"grace_expired";await(0,Co.rm)((0,s.join)(f,e),{recursive:!0,force:!0}),_D(u,e),h&&(S.push(e),ED.info(i,"managed_skills.removed",{skill_id:e,reason:n,server_enabled:t?.enabled??null,had_manifest_entry:void 0!==r,last_synced_ms_ago:r?a-r.lastSyncedAt:null}))}else r||kD(u,e,a)}catch(t){ED.warn(i,"Failed to apply skill, will retry next sync",{skillId:e,error:String(t)})}try{await function(e,t){const r=(bD.get(e)??Promise.resolve()).then((()=>async function(e,t){const r=(0,s.join)(e,`${wD}.${process.pid}.${(0,bo.randomBytes)(6).toString("hex")}.tmp`);await(0,Co.mkdir)(e,{recursive:!0});try{await(0,Co.writeFile)(r,JSON.stringify(t,null,2),"utf-8"),await async function(e,t){for(let r=0;;r++)try{return void await(0,Co.rename)(e,t)}catch(e){const t=Sc(e),n=vD[r];if(void 0===n||void 0===t||!yD.has(t))throw e;await(0,Or.cb)(n)}}(r,(0,s.join)(e,wD))}catch(e){throw await(0,Co.rm)(r,{force:!0}).catch((()=>{})),e}}(e,t))),n=r.catch((()=>{}));return bD.set(e,n),n.then((()=>{bD.get(e)===n&&bD.delete(e)})),r}(l,u)}catch(e){!function(e){if(e instanceof Error&&"ENOENT"===Sc(e))return!0;const t=String(e);return t.includes("ENOENT")||t.includes("no such file or directory")}(e)?ED.warn(i,"Failed to persist sync manifest",{skillDir:l,error:String(e)}):ED.debug(i,"Skipped persisting sync manifest, path removed concurrently",{skillDir:l,error:String(e)})}return{synced:v,upToDate:b,removed:S}}catch(e){r.error=e,r.hasError=!0}finally{CD(r)}var n}async function MD(e){try{return await(0,Co.stat)(e),!0}catch(e){const t=Sc(e);if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}const DD=(0,l.h)("managed-skills-sync");function OD(e,t,r,n,o,s){const i=[],a=e.mcpServers;if(!a)return i;for(const[e,c]of Object.entries(a)){const a=c,l=`plugin-${n}-${e}`,u=e;a.url?i.push({identifier:l,name:u,marketplace:t,marketplaceId:r,pluginName:n,pluginId:o,pluginSource:s,type:"streamableHttp",url:a.url,headers:a.headers,auth:a.auth,tls:a.tls,enabledTools:a.enabledTools,placement:a.placement,projectManaged:!1,pluginManaged:!0}):a.command&&i.push({identifier:l,name:u,marketplace:t,marketplaceId:r,pluginName:n,pluginId:o,pluginSource:s,type:"stdio",command:a.command,args:a.args??[],env:a.env??{},cwd:a.cwd,envFile:a.envFile,enabledTools:a.enabledTools,projectManaged:!1,pluginManaged:!0})}return i}function FD(e){try{const t=new URL(e),r=new URL(t.pathname,t.origin);return r.search=t.search,r.pathname.endsWith("/")&&r.pathname.length>1&&(r.pathname=r.pathname.slice(0,-1)),"/"===r.pathname?r.origin+r.search:r.toString()}catch{return e.toLowerCase().trim()}}class ND{constructor(e){this.pluginsService=e}async getPluginMcpServers(){const e=await this.pluginsService.reload(),t=[];for(const r of e){const e="marketplace"in r.identifier.sourceInfo?r.identifier.sourceInfo.marketplace:void 0,n="marketplaceDbId"in r.identifier.sourceInfo?r.identifier.sourceInfo.marketplaceDbId:void 0,o=r.identifier.sourceInfo.name,s="pluginDbId"in r.identifier.sourceInfo?r.identifier.sourceInfo.pluginDbId:void 0,i=r.mcpConfig;i&&t.push(...OD(i,e,n,o,s,r.identifier.source))}return function(e){const t=[],r=new Set;for(const n of e){if("streamableHttp"!==n.type||!n.url){t.push(n);continue}const e=FD(n.url);r.has(e)||(r.add(e),t.push(n))}return t}(t)}}var LD=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function jD(e,t){return void 0===e?[]:(Array.isArray(e)?e:[e]).map((e=>({...e,userHomeDir:t})))}class UD{constructor(e,t,r,n,o,s){this.workspacePaths=e,this.userHomeDirectory=t,this.getSettings=r,this.marketplaceOptions=n,this.localPluginVariablesLookup=s,this.plugins=[],this._loadFailures=[],this._pluginSetIncomplete=!0,this._retainedFromPreviousLoad=0,this._wasFirstLoad=!0,this.loadedOnce=!1,this._extensionPlugins=new Map,this._extensionPluginOriginalPaths=new Map,this.pluginLogger=o??Tp,this.reload()}async getAllEnabledPlugins(){return await this.ensureLoaded(),[...this.plugins]}getLoadFailures(){return[...this._loadFailures]}isPluginSetIncomplete(){return this._pluginSetIncomplete}getLoadDiagnostics(){return{userHomeDirectory:this.userHomeDirectory,pluginsLoaded:this.plugins.length,retainedFromPreviousLoad:this._retainedFromPreviousLoad,wasFirstLoad:this._wasFirstLoad,sourceUnavailable:this._pluginSetIncomplete}}async reload(){return this.loadPromise||(this.loadPromise=this.load().then((async e=>{const t=!this.loadedOnce;let r=[];try{r=await this._reloadExtensionPlugins()}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugins after base load success: ${kc(e)}`)}const n=e.sourceUnavailable?this._retainPluginsMissingFromPartialLoad(e.plugins):[],o=[...e.plugins,...n],s=new Set(o.map((e=>e.installPath))),i=r.filter((e=>!s.has(e.installPath)));return this.plugins=[...o,...i],e.sourceUnavailable||(this._loadFailures=e.failures),this._pluginSetIncomplete=e.sourceUnavailable,this._retainedFromPreviousLoad=n.length,this._wasFirstLoad=t,this.loadedOnce=!0,this.pluginLogger.log("info",`Plugins reload completed: ${this.plugins.length} plugins loaded (${i.length} extension, ${n.length} retained), ${e.failures.length} failures`),this.plugins})).catch((async e=>{const t=!this.loadedOnce;this.pluginLogger.log("error",`Failed to load plugins: ${e}`),this._pluginSetIncomplete=!0,this._retainedFromPreviousLoad=0,this._wasFirstLoad=t;try{const e=await this._reloadExtensionPlugins(),t=new Set(this.plugins.map((e=>e.installPath)));this.plugins=[...this.plugins,...e.filter((e=>!t.has(e.installPath)))]}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugins after base load failure: ${kc(e)}`)}return this.loadedOnce=!0,this.plugins})).finally((()=>{this.loadPromise=void 0}))),this.loadPromise}_retainPluginsMissingFromPartialLoad(e){if(!this.loadedOnce)return[];const t=new Set(e.map(om));return this.plugins.filter((e=>"extension"!==e.identifier.source&&void 0===e.loadError&&e.installPath.length>0&&!t.has(om(e))))}async reloadPlugin(e){this.loadPromise&&await this.loadPromise;const t=jD(this.marketplaceOptions,this.userHomeDirectory);if(0===t.length)return;if(!(this.getSettings().loadCursorFirstParty??t.length>0))return;const r=t=>t.pluginDbId===e.pluginDbId,n=e=>"cursor-first-party"===e.identifier.source||"cursor-third-party"===e.identifier.source?e.identifier.sourceInfo:void 0,o=t=>n(t)?.pluginDbId===e.pluginDbId,s=(t,r)=>void 0!==t.pluginDbId?t.pluginDbId===e.pluginDbId:t.pluginName===r?.name&&t.marketplaceName===r?.marketplace;let i,a,c;for(const l of t){let t;try{t=await rm({...l,log:l.log??this.pluginLogger,pluginFilter:r})}catch(t){this.pluginLogger.log("error",`reloadPlugin: source load failed for ${e.name}: ${kc(t)}`);continue}const u=t.plugins.find((e=>o(e)&&void 0===e.loadError));if(void 0!==u){i=u;break}const d=t.plugins.find(o);if(void 0!==d&&void 0===a){const e=n(d);a=d,c=t.failures.find((t=>s(t,e)))}}if(void 0===i){if(void 0!==a){const t=n(a),r={...c??{pluginName:t?.name??e.name,errorMessage:a.loadError??"Plugin load failed",errorType:"unknown",...void 0!==t?.marketplace&&{marketplaceName:t.marketplace}},pluginDbId:e.pluginDbId};this._loadFailures=[...this._loadFailures.filter((e=>!s(e,t))),r]}return}const l=this.plugins.findIndex(o);if(-1===l)this.plugins=[...this.plugins,i];else{const e=[...this.plugins];e[l]=i,this.plugins=e}this.loadedOnce=!0;const u=n(i);return this._loadFailures=this._loadFailures.filter((e=>!s(e,u))),i}async registerExtensionPlugin({path:e,extensionId:t}){const r=(0,s.resolve)(e),n=await(0,Co.realpath)(r);if(!(await(0,Co.stat)(n)).isDirectory())throw new Error(`Extension plugin path is not a directory: ${n}`);const i=o.homedir();if(n.split(s.sep).filter(Boolean).length<3||n===i||"/"===n)throw new Error(`Extension plugin path is too broad (must be a specific subdirectory, not root or home): ${n}`);for(const[e,r]of this._extensionPlugins)if(e!==t&&r.has(n))throw new Error(`Plugin path ${n} is already registered by extension ${e}`);let a=this._extensionPlugins.get(t);if(a||(a=new Map,this._extensionPlugins.set(t,a)),a.has(n))return void this._rememberExtensionPluginOriginalPath({extensionId:t,originalPath:r,canonicalPath:n});const c=(0,s.basename)(n),l=await this._loadExtensionPluginContent(n,t);a.set(n,l),this._rememberExtensionPluginOriginalPath({extensionId:t,originalPath:r,canonicalPath:n}),this.pluginLogger.log("info",`Registered extension plugin: ${c} from ${n} (extension: ${t})`)}async unregisterExtensionPlugin({path:e,extensionId:t}){const r=this._extensionPlugins.get(t);if(!r)return!1;const n=(0,s.resolve)(e);let o;try{o=await(0,Co.realpath)(n)}catch{const e=this._extensionPluginOriginalPaths.get(t);o=e?.get(n)??n}const i=r.delete(o);return 0===r.size?(this._extensionPlugins.delete(t),this._extensionPluginOriginalPaths.delete(t)):i&&this._forgetExtensionPluginOriginalPath(t,o),i&&this.pluginLogger.log("info",`Unregistered extension plugin: ${o} (extension: ${t})`),i}async _loadExtensionPluginContent(e,t){const r=(0,s.basename)(e),n={name:r,localPath:e,extensionId:t},o=await Kf(e,r,{name:r,version:"0.0.0"});return o.displayName&&(n.name=o.displayName),{identifier:{source:"extension",sourceInfo:n},installPath:e,...void 0!==o.displayName&&{displayName:o.displayName},...void 0!==o.description&&{description:o.description},...void 0!==o.authorName&&{authorName:o.authorName},...void 0!==o.logoUrl&&{logoUrl:o.logoUrl},...void 0!==o.version&&{version:o.version},...void 0!==o.homepage&&{homepage:o.homepage},...void 0!==o.repository&&{repository:o.repository},skills:o.skills,rules:o.rules,agents:o.agents,commands:o.commands,mcpConfig:o.mcpConfig??void 0,capabilities:o.capabilities,hooks:o.hooks}}_rememberExtensionPluginOriginalPath(e){let t=this._extensionPluginOriginalPaths.get(e.extensionId);t||(t=new Map,this._extensionPluginOriginalPaths.set(e.extensionId,t)),t.set(e.originalPath,e.canonicalPath)}_forgetExtensionPluginOriginalPath(e,t){const r=this._extensionPluginOriginalPaths.get(e);if(r){for(const[e,n]of r)n===t&&r.delete(e);0===r.size&&this._extensionPluginOriginalPaths.delete(e)}}_getExtensionPluginPaths(){const e=[];for(const[t,r]of this._extensionPlugins)for(const n of r.keys())e.push({canonicalPath:n,extensionId:t});return e}async _reloadExtensionPlugins(){const e=this._getExtensionPluginPaths(),t=[];for(const{canonicalPath:r,extensionId:n}of e)try{const e=await this._loadExtensionPluginContent(r,n),o=this._extensionPlugins.get(n);o&&o.set(r,e),t.push(e)}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugin ${r}: ${kc(e)}`);const o=this._extensionPlugins.get(n),s=o?.get(r);s&&t.push(s)}return t}async ensureLoaded(){this.loadPromise?await this.loadPromise:this.loadedOnce||await this.reload()}async load(){const e={stack:[],error:void 0,hasError:!1};try{const t=(0,y.q6)().withName("LocalPluginsService.load"),r=(function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(e,(0,$.VI)(t),!1),performance.now()),n=e=>{this.pluginLogger.increment(`local_plugins_service.load.${e}`,1),this.pluginLogger.distribution("local_plugins_service.load.duration",performance.now()-r,{outcome:e})},o=this.getSettings(),i=jD(this.marketplaceOptions,this.userHomeDirectory),a=o.importThirdPartyPlugins,c=o.loadUserLocalPlugins??!0,l=o.loadCursorFirstParty??i.length>0;if(!a&&!l&&!c)return this.pluginLogger.log("info","Skipping plugin loading, cursor 1p, 3p, and user-local plugins are disabled"),{plugins:[],failures:[],sourceUnavailable:!1};this.pluginLogger.increment("local_plugins_service.load.start",1);const u=(e,t)=>{this.pluginLogger.increment("local_plugins_service.load_plugin.error",1),this.pluginLogger.log("error",`Cursor plugin load error ${e.name}@${e.version}: ${t?.message??String(t)}`)};try{const e=await async function(e,t={}){const r=t.log??Tp,n=performance.now(),o=t.loadClaude??!0,i=t.loadUserLocal??!0,a=t.marketplaceSources??[],c=t.loadCursorFirstParty??a.length>0,l=[],u=[];let d;o&&l.push(Xf(e,0,{userHomeDir:t.userHomeDir,onError:t.onError,log:r})),c&&a.length>0&&(d=Promise.allSettled(a.map((e=>rm({...e,userHomeDir:e.userHomeDir??t.userHomeDir,log:e.log??r}))))),i&&l.push(async function(e={}){const t=e.log??Tp,r=performance.now(),n=e.userHomeDir??process.env.HOME;if(!n)return t.log("info","loadUserLocalPlugins: no home directory available, skipping"),[];const o=(0,s.join)(n,".cursor","plugins","local");let i;try{i=await(0,Co.readdir)(o,{withFileTypes:!0})}catch{return t.log("info",`loadUserLocalPlugins: ${o} not found or not readable (${(performance.now()-r).toFixed(1)}ms)`),[]}const a=await(0,Co.realpath)(o).catch((()=>(0,s.resolve)(o))),c=[];for(const r of i){if(!r.isDirectory()&&!r.isSymbolicLink())continue;if(r.name.startsWith("."))continue;const n=(0,s.join)(o,r.name);try{if(r.isSymbolicLink()){let e;try{e=await(0,Co.realpath)(n)}catch(e){t.log("warn",`loadUserLocalPlugin ${r.name} rejected: failed to resolve symlink (${e instanceof Error?e.message:String(e)})`);continue}try{vf(a,e)}catch{t.log("warn",`loadUserLocalPlugin ${r.name} rejected: symlink target ${e} is outside ${o}`);continue}}if(!(await(0,Co.stat)(n)).isDirectory()){r.isSymbolicLink()&&t.log("warn",`loadUserLocalPlugin ${r.name} rejected: symlink target is not a directory`);continue}const s=performance.now(),i=await(e.localPluginVariablesLookup?.(r.name)),{displayName:l,description:u,authorName:d,logoUrl:h,version:p,homepage:f,repository:m,variablesSchema:g,skills:w,rules:y,agents:v,commands:b,mcpConfig:S,capabilities:k,hooks:_}=await Kf(n,r.name,void 0,{configuredVariables:i,log:t}),C={source:"user-local",sourceInfo:{name:r.name,localPath:n}};c.push({identifier:C,installPath:n,...void 0!==l&&{displayName:l},...void 0!==u&&{description:u},...void 0!==d&&{authorName:d},...void 0!==h&&{logoUrl:h},...void 0!==p&&{version:p},...void 0!==f&&{homepage:f},...void 0!==m&&{repository:m},variablesSchema:g,skills:w,rules:y,agents:v,commands:b,mcpConfig:S??void 0,capabilities:k,hooks:_}),t.log("info",`loadUserLocalPlugin ${r.name} loaded in ${(performance.now()-s).toFixed(1)}ms`)}catch(e){t.log("error",`loadUserLocalPlugin ${r.name} failed: ${e instanceof Error?e.message:String(e)}`)}}return t.log("info",`loadUserLocalPlugins completed in ${(performance.now()-r).toFixed(1)}ms (${c.length} plugins loaded)`),c}({userHomeDir:t.userHomeDir,log:r,localPluginVariablesLookup:t.localPluginVariablesLookup}));const[h,p]=await Promise.all([Promise.allSettled(l),d??Promise.resolve([])]);let f=!1;const m=[];for(const e of p)"rejected"!==e.status?(e.value.sourceUnavailable&&(f=!0),m.push(...e.value.plugins),u.push(...e.value.failures)):(f=!0,r.log("error",`marketplace source threw while loading; treating it as unavailable: ${String(e.reason)}`));for(const e of h)"rejected"!==e.status?m.push(...e.value):(f=!0,r.log("error",`plugin source threw while loading; treating it as unavailable: ${String(e.reason)}`));const g=new Set,w=[];for(const e of m){if(!e.installPath){w.push(e);continue}const t=await(0,Co.realpath)(e.installPath).catch((()=>e.installPath));g.has(t)||(g.add(t),w.push(e))}const y=new Map,v=[];for(const e of w){const t=nm(e);if(void 0!==t){const r=y.get(t),n=!e.loadError;if(!0===r)continue;if(!1===r&&n){const r=v.findIndex((e=>nm(e)===t&&e.loadError));-1!==r&&v.splice(r,1),y.set(t,!0),v.push(e);continue}y.set(t,n)}v.push(e)}const b=performance.now()-n;return r.log("info",`loadAllPlugins completed in ${b.toFixed(1)}ms (claude=${o}, userLocal=${i}, marketplace=${a.length} sources, total=${v.length} plugins, failures=${u.length}, sourceUnavailable=${f})`),{plugins:v,failures:u,sourceUnavailable:f}}(this.workspacePaths,{userHomeDir:this.userHomeDirectory,loadClaude:a,loadUserLocal:c,loadCursorFirstParty:l&&i.length>0,marketplaceSources:i.length>0?i.map((e=>({...e,onCursorError:u}))):void 0,onError:(e,t)=>{this.pluginLogger.log("error",`Claude plugin load error ${e.raw}: ${t?.message??String(t)}`)},log:this.pluginLogger,localPluginVariablesLookup:this.localPluginVariablesLookup});return n("success"),this.pluginLogger.log("info",`Plugins loaded in ${(performance.now()-r).toFixed(1)}ms`),e}catch(e){return n("error"),this.pluginLogger.log("error",`Failed to load all plugins: ${kc(e)}`),{plugins:[],failures:[],sourceUnavailable:!0}}}catch(t){e.error=t,e.hasError=!0}finally{LD(e)}}}const BD=["parse binary","parse json"],WD=["decompression failed","unsupported response encoding","unsupported content type","protocol error: promised"],HD=new Set([1,4,10,14]),qD=new Set(["AbortError","TimeoutError"]),zD=["ECONN","ENOT","ETIMEDOUT","EPIPE","EAI_","EHOST","ENET","ERR_HTTP2","ERR_SSL","ERR_TLS","UND_ERR","CERT_","DEPTH_ZERO_SELF_SIGNED_CERT","SELF_SIGNED_CERT","UNABLE_TO_"];function GD(e,t){return t.some((t=>e.startsWith(t)))}function VD(e){if(e instanceof Error&&qD.has(e.name))return!0;const t=function(e){if("object"==typeof e&&null!==e&&"code"in e)return"string"==typeof e.code?e.code:void 0}(e);return void 0!==t&&GD(t,zD)}function KD(e){const t=function(e){if(e instanceof Error&&"ConnectError"===e.name&&"code"in e&&"number"==typeof e.code&&"rawMessage"in e&&"string"==typeof e.rawMessage)return{code:e.code,text:e.rawMessage,cause:e.cause}}(e);if(void 0===t)return VD(e)?"transport":"other";const{code:r,text:n,cause:o}=t;return GD(n,BD)?"reply_schema":GD(n,WD)?"reply_encoding":n.startsWith("http/2 stream closed with error code")||HD.has(r)||VD(o)?"transport":"other"}var JD=r("../proto/dist/generated/aiserver/v1/dashboard_pb.js");const ZD=BigInt(0),XD=BigInt(8),QD=BigInt(16),YD=BigInt(65535);function eO(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch{return}}function tO(e){let t=e.trim().replace(/\.+$/,"").toLowerCase();if(t.startsWith("[")){const e=t.indexOf("]");-1!==e&&(t=t.slice(1,e))}else if(t.split(":").length-1==1){const e=t.lastIndexOf(":"),r=t.slice(e+1);Array.from(r).every((e=>/\d/.test(e)))&&(t=t.slice(0,e))}return t}function rO(e){const t=e.split(".");if(4!==t.length)return;let r=ZD;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<>QD&YD)),t.push(Number(o.value&YD))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function oO(e){return rO(e)??function(e){const t=tO(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=nO(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<7?void 0:{version:6,value:[...n,...new Array(8-s).fill(0),...o].reduce(((e,t)=>e<i)return!1;const a=BigInt(i-s);return o.value>>a==n.value>>a}(r,n);if(n.startsWith("*.")){const e=n.slice(2);return r===e||r.endsWith(`.${e}`)}return r===n}function iO(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}function aO(e,t){if(iO(e,t))return!0;if(e.includes("://")){let r,n;try{r=new URL(e),n=new URL(t)}catch{return!1}if(""!==r.username||""!==r.password||""!==n.username||""!==n.password||r.protocol!==n.protocol||r.port!==n.port)return!1;const o=tO(r.hostname);return!!sO(tO(n.hostname),o)&&iO(`${r.pathname}${r.search}`,`${n.pathname}${n.search}`)}const r=function(e){const t=function(e){const t=e.trim(),r=t.indexOf("["),n=t.indexOf("]");if(-1!==r&&n>r){const e=t.slice(r+1,n);if(t.slice(n+1).startsWith("("))return`${t.slice(0,r)}${e}`}return t}(e).trim();if(0===t.length)return;const r=t.lastIndexOf("/");if(!t.includes("://")&&r>0&&/^\d+$/.test(t.slice(r+1).trim())){const e=tO(t.slice(0,r));if(e.length>0)return`${e}/${t.slice(r+1).trim()}`}const n=eO(t);if(n)return tO(n.hostname);let o=t;const s=o.indexOf("://");-1!==s&&(o=o.slice(s+3));const i=o.indexOf("/");-1!==i&&(o=o.slice(0,i));const a=tO(function(e){if(e.startsWith("[")){const t=e.indexOf("]");return-1!==t?e.slice(1,t):e}const t=e.split(":");return 2===t.length&&Array.from(t[1]??"").every((e=>/\d/.test(e)))?t[0]:e}(o));if(0!==a.length){if(a.startsWith("*.")){const e=a.slice(2);if(0===e.length||e.includes("*")||e.includes("?"))return;return a}if(!a.includes("*")&&!a.includes("?"))return a}}(e),n=function(e){const t=eO(e);if(t)return tO(t.hostname);const r=tO(e);return r.length>0?r:void 0}(t);return!(!r||!n)&&sO(n,r)}async function cO(e){try{return await e.current()}catch{return}}function lO(e){try{const t=new URL(e);return`${t.protocol}//${t.host}${t.pathname}`}catch{return}}function uO({failOpenWhenEmpty:e,server:t,settings:r}){if(!0!==r?.allowedMcpConfiguration?.requireMcpServersInTeamNetworkAllowlist||void 0===t.url)return{blocked:!1};const n=function(e){return!0===e.cloudAgentMcpAllowlistApplied&&!1===e.mirrorSandboxAllowlistForEgress?e.cloudAgentEgressAllowlist??[]:e.networkAllowlist??[]}(r).map((e=>e.trim())).filter((e=>e.length>0));return 0===n.length&&e||Jv(t.url,n)?{blocked:!1}:{blocked:!0,reason:"teamNetworkAllowlist",message:"Not on the team network allowlist"}}function dO(e){const t=e?.trim();return t&&t.length>0?t:void 0}function hO(e,t,r){if(!0===r?.useCorePolicy)return!function(e,t){if(void 0===t)return!0;if(!0===t.disableAll)return!1;if(SC(e))return!0;if(EC(e,t.offMcpServerRules))return!1;const r=t.allowedMcpServers??[];return 0===r.length&&!0!==t.allowUserOverrideMcpServers||!!function(e,t){return t.length>0&&function(e,t){return t.some((t=>{const r=kC(t.command),n=_C(t.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==e.command&&(0,Ob.mD)(r,e.command),s=void 0===n||void 0!==e.url&&(0,Ob.vc)(n,e.url);return o&&s}))}(e,t)}(e,r)||!0===t.allowUserOverrideMcpServers&&!CC(e,t.deniedMcpServers)}(e,t);if(void 0===t)return!1;if(!0===t.disableAll)return!0;const n=t.allowedMcpServers;return 0!==n.length&&!n.some((t=>function(e,t){const r=dO(e.command),n=dO(e.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==t.command&&function(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}(r,t.command),s=void 0===n||void 0!==t.url&&aO(n,t.url);return o&&s}(t,e)))}class pO{constructor(e,t={}){this.dashboardClient=e,this.options=t}getTeamAdminSettings(){return this.dashboardClient.getTeamAdminSettingsOrEmptyIfNotInTeam(new JD.Byz(!0===this.options.supportsHostMcpBridgeExemption?{supportsHostMcpBridgeExemption:!0}:{}))}getTeamRepos(){return this.dashboardClient.getTeamReposOrEmptyIfNotInTeam(new JD.aYW({}))}}function fO(e,t){if("workspace"!==e)return[];const r=[],n=new Set;for(const e of t??[]){const t=e.trim();0===t.length||n.has(t)||(n.add(t),r.push(t))}return r}class mO{constructor(e){this.fetch=e}get(){const e=this.cached,t=void 0===e?1/0:Date.now()-e.fetchedAt;return void 0===e||t>6e5?(this.cached=void 0,this.refresh()):(t>3e5&&this.refresh().catch((()=>{})),Promise.resolve(e.value))}invalidate(){this.cached=void 0,this.inFlight=void 0}refresh(){if(void 0===this.inFlight){const e=this.fetch().then((t=>(this.inFlight!==e||void 0===t&&void 0!==this.cached||(this.cached={value:t,fetchedAt:Date.now()}),t))).finally((()=>{this.inFlight===e&&(this.inFlight=void 0)}));this.inFlight=e}return this.inFlight}}class gO{constructor(e,t,r={}){this.teamAdminSettingsProvider=e,this.defaultAllowlistProvider=t,this.options=r,this.lastFetchSucceeded=!0,this.lastFetchFailure="other",this.settingsGeneration=0,this.lastFetchedGeneration=0,this.settings=new mO((()=>this.fetchSettings())),this.droppedReplies=new WeakSet,this.hostMcpBridgeClients=new WeakSet,this.mcpServerByClient=new WeakMap,this.teamRepos=new mO((()=>this.teamAdminSettingsProvider.getTeamRepos())),this.defaultAllowlist=new mO((()=>this.fetchDefaultAllowlist())),this.getTeamAdminSettings(),this.prefetchTeamRepos()}async prefetchTeamRepos(){try{await this.teamRepos.get()}catch{}}invalidateCache(){this.settingsGeneration+=1,this.settings.invalidate(),!0!==this.options.preserveTeamReposOnInvalidate&&this.teamRepos.invalidate(),this.defaultAllowlist.invalidate()}invalidateTeamRepos(){this.teamRepos.invalidate()}async refreshTeamAdminSettings(){try{await this.settings.refresh()}catch{}}async fetchSettings(){const{fetchIdentity:e}=this.options;if(void 0!==e)return this.fetchSettingsFor(e);const t=this.settingsGeneration;try{const e=await this.teamAdminSettingsProvider.getTeamAdminSettings();return this.lastFetchSucceeded=!0,t>=this.lastFetchedGeneration&&(this.lastFetchedSettings=e,this.lastFetchedGeneration=t),e}catch(e){throw this.lastFetchSucceeded=!1,this.lastFetchFailure=KD(e),e}}async fetchSettingsFor(e){const t=await cO(e),r=this.settingsGeneration;if(void 0===t)throw this.lastFetchSucceeded=!1,this.lastFetchFailure="other",new Error("No one is named whose team settings a fetch would read");try{const e=await this.teamAdminSettingsProvider.getTeamAdminSettings();return void 0!==e&&this.droppedReplies.delete(e),this.isSentFor(e,t)?(this.lastFetchSucceeded=!0,r>=this.lastFetchedGeneration&&(this.lastFetchedSettings=e,this.lastFetchedGeneration=r),e):e}catch(e){throw this.lastFetchSucceeded=!1,this.lastFetchFailure=KD(e),e}}getTeamAdminSettings(){const{fetchIdentity:e}=this.options;return void 0!==e?this.getTeamAdminSettingsFor(e):this.settings.get().catch((()=>{}))}async getTeamAdminSettingsFor(e){const t=await this.settings.get().catch((()=>{})),r=await cO(e);if(void 0===t)return void(this.isSentFor(this.lastFetchedSettings,r)||(this.settingsGeneration+=1));if(void 0===r)return this.answerAsFailedRead();if(this.isSentFor(t,r))return t;let n=t,o=r;const s=await this.settings.get().catch((()=>{}));if(s!==t){if(void 0===s)return this.answerAsFailedRead();if(this.isSentFor(s,r))return s;if(o=await cO(e),void 0===o)return this.answerAsFailedRead();if(this.isSentFor(s,o))return s;n=s}this.droppedReplies.has(n)||(this.droppedReplies.add(n),this.settingsGeneration+=1,this.settings.invalidate());const i=await this.settings.get().catch((()=>{}));return void 0!==i?this.isSentFor(i,r)||this.isSentFor(i,o)||this.isSentFor(i,await cO(e))?i:this.answerAsFailedRead():void 0}answerAsFailedRead(){this.settingsGeneration+=1,this.lastFetchSucceeded=!1,this.lastFetchFailure="other"}isSentFor(e,t){return void 0!==e&&void 0!==t&&this.options.fetchIdentity?.sentFor(e)===t}async getDotCursorProtection(){const e=await this.getTeamAdminSettings();return e?.dotCursorProtection??!0}async getShouldBlockMcp(){const e=await this.getTeamAdminSettings();return!(!e?.autoRunControls?.enabled||!e?.autoRunControls?.disableMcpAutoRun)}async getDeleteFileProtection(){const e=await this.getTeamAdminSettings();return!(!e?.autoRunControls?.enabled||!e?.autoRunControls?.deleteFileProtection)}async getIsHeadlessDisabled(){return"disabled"===(await this.getHeadlessCliPolicy()).kind}async getHeadlessCliPolicy(){const e=await this.getTeamAdminSettings();return void 0!==e||this.lastFetchSucceeded?!0===e?.cliSettings?.disableHeadless?{kind:"disabled"}:{kind:"enabled"}:{kind:"unavailable"}}async getMcpServerBlockInfo(e){const t=await this.getTeamAdminSettings(),r=t?.allowedMcpConfiguration,n=await this.isMcpSettingsOverhaulEnabled({disableExposureLog:!0});if(!0===r?.disableAll)return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};if(this.isHostMcpBridge(t,e))return{blocked:!1,hostMcpBridge:!0};if(EC(e,r?.offMcpServerRules))return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};if(n){if(hO(e,r,{useCorePolicy:!0}))return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};const n=await this.getMcpNetworkControlsConfig(e),o=void 0===e.url?{allowed:!0}:(0,Ob.ME)(e.url,n);if(!o.allowed)return{blocked:!0,reason:"teamNetworkAllowlist",message:o.message};const s=uO({failOpenWhenEmpty:!1,server:e,settings:t});if(s.blocked)return s}if(!n){const r=function({isMcpAccessNetworkAllowlistEnabled:e,server:t,settings:r}){return e&&!0===r?.allowedMcpConfiguration?.requireMcpServersInTeamNetworkAllowlist?uO({failOpenWhenEmpty:!0,server:t,settings:r}):{blocked:!1}}({isMcpAccessNetworkAllowlistEnabled:await this.isMcpAccessNetworkAllowlistEnabled(),server:e,settings:t});if(r.blocked)return r}return void 0!==t||this.lastFetchSucceeded?{blocked:!1}:{blocked:!1,settingsUnavailable:!0}}async getManagedSlackWorkspaceLists(){const e=await this.getTeamAdminSettings()??this.lastFetchedSettings;return void 0===e?[]:function(e){return e.memberSlackManagedWorkspacesUnreadable?"unconfirmed":e.memberSlackManagedWorkspaces.map((e=>e.slackTeamIds)).filter((e=>e.length>0))}(e)}async getMcpNetworkControlsConfig(e){const t=await this.getTeamAdminSettings(),r=t?.allowedMcpConfiguration;if(await this.isMcpSettingsOverhaulEnabled()&&(void 0===e||!this.isHostMcpBridge(t,e))){const n="win32"===process.platform&&await this.isWin32UserExtensionStdioUnsandboxEnabled();return(0,Ob._N)({allowedMcpConfiguration:r,server:e,localAgentNetworkAllowlist:t?.networkAllowlist,blockMessage:"Not on the team network allowlist",aggregateManagedServerNetworkAllowlists:!1,stdioPlatform:process.platform,unsandboxUserExtensionStdio:n})}return{enabled:!1,localAgentNetworkAllowlist:t?.networkAllowlist,blockMessage:"Not on the team network allowlist"}}isHostMcpBridge(e,t){const r=this.options.hostMcpBridgeUrls;if(!0!==e?.cloudAgentMcpAllowlistApplied||void 0===r||void 0!==t.command||void 0===t.url)return!1;const n=lO(t.url);return void 0!==n&&r.some((e=>lO(e)===n))}recordHostMcpBridgeClient(e){this.hostMcpBridgeClients.add(e)}async isHostMcpBridgeClient(e){if(!this.hostMcpBridgeClients.has(e))return!1;const t=await this.getTeamAdminSettings();return!0===t?.cloudAgentMcpAllowlistApplied&&!0!==t.allowedMcpConfiguration?.disableAll}recordMcpServerClient(e,t){this.mcpServerByClient.set(e,t)}async getMcpAdminToolLimit(e){if(await this.isHostMcpBridgeClient(e))return{kind:"none"};const t=this.mcpServerByClient.get(e);if(void 0===t)return{kind:"unknown_server"};const r=!0===this.options.mcpAdminToolLimitSurvivesFailedRead;let n=await this.getTeamAdminSettings();if(void 0===n&&!this.lastFetchSucceeded&&r&&(n=await this.getTeamAdminSettings()),void 0===n){if(this.lastFetchSucceeded)return{kind:"none"};if(!r)return{kind:"settings_unavailable"};const e=this.lastFetchFailure,t=this.lastFetchedGeneration===this.settingsGeneration?this.lastFetchedSettings:void 0;if(void 0===t)return{kind:"settings_unavailable",failure:e,noLimitApplies:!0};n=t}const o=function(e,t){const r=e?.find((e=>(0,Ob.rM)(e,t)));if(void 0!==r)return Lb({mode:r.toolAllowlistMode,tools:r.toolAllowlist})}(n.allowedMcpConfiguration?.allowedMcpServers,t);return void 0===o?{kind:"none"}:{kind:"limit",policy:o}}async isServerBlocked(e){return(await this.getMcpServerBlockInfo(e)).blocked}async getAutoRunControls(){const e=await this.getTeamAdminSettings();if(e?.autoRunControls?.enabled)return{enabled:e.autoRunControls.enabled,allowed:e.autoRunControls.allowed??[],blocked:e.autoRunControls.blocked??[],enableAllowlistMode:e.autoRunControls.enableAllowlistMode??!0,enableRunEverything:e.autoRunControls.enableRunEverything??!1,enableSmartAuto:e.autoRunControls.enableSmartAuto??!0,mcpToolAllowlist:e.autoRunControls.mcpToolAllowlist??[]}}async isReadControlEnabled(){try{return await(this.options.isReadControlEnabled?.())??!0}catch{return!1}}async isDenylistEnforcementKilled(){try{return!0===await(this.options.isAdminCommandDenylistEnforcementKilled?.())}catch{return!1}}async getAdminCommandDenylist(){if(await this.isDenylistEnforcementKilled())return{rules:[]};const e=await this.getTeamAdminSettings();return{rules:e?.autoRunControls?.adminCommandDenylist?.rules??[]}}async isMcpSettingsOverhaulEnabled(e){const t=this.options.isMcpSettingsOverhaulEnabled?.(e);return void 0!==t&&await t}async isWin32UserExtensionStdioUnsandboxEnabled(){try{const e=this.options.isWin32UserExtensionStdioUnsandboxEnabled?.();return void 0!==e&&await e}catch{return!1}}async getMcpToolControls(){const e=await this.getTeamAdminSettings(),t=e?.allowedMcpConfiguration;if(void 0===t)return;const r=function({autoRunControls:e,allowedMcpServers:t}){const r=!0===e?.enabled?e.mcpToolAllowlist??[]:[],n=function(e){return(e??[]).flatMap((e=>{const t=void 0===e.name?"":Fb(e.name);if(0===t.length)return[];const r=Lb({mode:e.toolAllowlistMode,tools:e.toolAllowlist});return[{name:t,policy:r,flattened:Ub(t,r)}]}))}(t);return{tools:(o=[...n.flatMap((e=>[...e.flattened])),...r],[...new Set(o)]),policies:n.map((e=>({name:e.name,policy:e.policy})))};var o}({autoRunControls:e?.autoRunControls,allowedMcpServers:t?.allowedMcpServers});return r.policies.length>0||r.tools.length>0?{enabled:!0,mcpToolAllowlist:r.tools,allowUserOverride:t?.allowUserOverrideMcpServers??!1,serverPolicies:r.policies}:void 0}async getNetworkAccessControls(){const e=await this.getTeamAdminSettings();return void 0!==e||this.lastFetchSucceeded?{allowlist:e?.networkAllowlist??[],denylist:e?.networkDenylist??[],available:!0}:{allowlist:[],denylist:[],available:!1}}async getSandboxingControls(){const e=await this.getTeamAdminSettings(),t=e?.autoRunControls?.sandboxingControls,r=(n=t?.sandboxReadBoundary,n===JD.h0i.WORKSPACE?"workspace":"system");var n;return{sandboxingDisabled:t?.sandboxing===JD.faf.DISABLED,networkingDisabled:t?.sandboxNetworking===JD._mX.ALWAYS_DISABLED,gitDisabled:t?.sandboxGit===JD.i24.ALWAYS_DISABLED,readBoundary:r,readAllowlistPaths:fO(r,t?.sandboxReadAllowlistPaths),allowUserOverrideReadAllowlist:!1!==t?.allowUserOverrideSandboxReadAllowlist}}async isAttributionDisabledByAdmin(){const e=await this.getTeamAdminSettings();return void 0===e&&!this.lastFetchSucceeded||(e?.attributionControls?.disableAttribution??!1)}async isComputerUseDisabledByAdmin(){const e=await this.getTeamAdminSettings();return void 0!==e?!1===e.computerUse:this.lastFetchedGeneration!==this.settingsGeneration||void 0===this.lastFetchedSettings&&!this.lastFetchSucceeded||!1===this.lastFetchedSettings?.computerUse}getDefaultNetworkAllowlist(){return this.defaultAllowlist.get().catch((()=>({allowlist:[],available:!1})))}async fetchDefaultAllowlist(){return this.defaultAllowlistProvider?{allowlist:await this.defaultAllowlistProvider.getDefaultNetworkAllowlist(),available:!0}:{allowlist:[],available:!0}}getTeamRepos(){return this.teamRepos.get()}async isMcpAccessNetworkAllowlistEnabled(){return await(this.options.isMcpAccessNetworkAllowlistEnabled?.())??!1}}const wO=new _y,yO={async resolveWorkspaceState(e){const t=e.workingDirectory??e.projectRoot??e.workspaceRoots?.[0],r=e.projectRoot??(void 0!==t?await Ya((0,y.q6)(),wO,t)??t:void 0),n=e.workspaceRoots??(void 0!==r?[r]:void 0!==t?[t]:[]);return{workingDirectory:t,projectRoot:r,projectDirectory:e.projectDirectory??(void 0!==r?_o(r):void 0),workspaceRoots:n,createdAt:new Date}}},vO=(0,l.h)("ControlledConversationActionManager");class bO{get signal(){return this.abortController.signal}get abortRequested(){return this.abortCalled}constructor(){this.abortCallbacks=[],this.abortController=new AbortController,this.acceptsActions=!0,this.disposed=!1,this.abortStarted=!1,this.abortCalled=!1,this.runActive=!1,this.unprocessedUserMessages=[],this.clientStream=(0,h.Jt)()}addAbortCallback(e){this.abortCallbacks.push(e)}abort(e,t){if(this.abortCalled=!0,this.abortController.signal.aborted||this.abortStarted)return;const r=t?.interruptedPendingToolCallResolutions;if(this.abortStarted=!0,!this.runActive){this.abortController.abort(e);for(const e of this.abortCallbacks)e();return void(this.abortCallbacks.length=0)}const n=this.abortController,o=[...this.abortCallbacks];this.abortCallbacks.length=0,this.submitConversationAction(new i.QFf({action:{case:"cancelAction",value:new i.TTG({reason:e,interruptedPendingToolCallResolutions:r})}})).catch((()=>{})).finally((()=>{n.abort(e);for(const e of o)e();if(this.abortController===n){const e=[...this.abortCallbacks];this.abortCallbacks.length=0;for(const t of e)t()}}))}async submitConversationAction(e){if(!this.acceptsActions)throw new h.W2("ControlledConversationActionManager is not accepting actions");if("userMessageAction"===e.action.case){const t=e.action.value.userMessage;t&&this.unprocessedUserMessages.push(t)}await this.clientStream.write(e)}queueFollowUpUserMessage(e){if(this.disposed||this.abortStarted)throw new h.W2("ControlledConversationActionManager run was aborted or disposed");this.unprocessedUserMessages.push(e)}async enqueueReplayableConversationAction(e){if("asyncAskQuestionCompletionAction"!==e.action.case)throw new TypeError("Only asyncAskQuestionCompletionAction can use enqueue acknowledgement");if(!this.acceptsActions)throw new h.W2("ControlledConversationActionManager is not accepting actions");this.clientStream.write(e).catch((()=>{}))}markMessageAsProcessed(e){this.unprocessedUserMessages=this.unprocessedUserMessages.filter((t=>t.messageId!==e.messageId))}requeueMessage(e){this.unprocessedUserMessages.some((t=>t.messageId===e.messageId))||this.unprocessedUserMessages.unshift(e)}getUnprocessedUserMessages(){return[...this.unprocessedUserMessages]}hasUnprocessedMessages(){return this.unprocessedUserMessages.length>0}close(){this.acceptsActions=!1,this.clientStream.close()}reopen(){this.disposed||this.acceptsActions||this.resetStream()}resetStream(){if(this.disposed)throw new h.W2("ControlledConversationActionManager disposed");this.acceptsActions=!1,this.clientStream.close(),this.clientStream=(0,h.Jt)(),this.acceptsActions=!0,this.abortController=new AbortController,this.abortStarted=!1;for(const e of this.unprocessedUserMessages)this.clientStream.write(new i.QFf({action:{case:"userMessageAction",value:new i.Vtf({userMessage:e})}})).catch((()=>{}))}async run(e,t){const r=this.clientStream;this.runActive=!0;try{for await(const n of r)try{await t.write(n)}catch(t){vO.error(e,"Error writing conversation action",t)}}catch(e){if(!(e instanceof h.W2))throw e}finally{this.clientStream===r&&(this.runActive=!1)}}dispose(){this.disposed||(this.disposed=!0,this.abortCallbacks.length=0,this.acceptsActions=!1,this.clientStream.throw(new h.W2("ControlledConversationActionManager disposed")))}}var SO=r("../cursor-sdk-local-runtime/dist/utils/logger.js"),kO=r("../agent-kv/dist/agent-store.js");const _O="x-blob-encryption-key";function CO(e,t){const r={...t};return void 0!==r[_O]||(0,kO.TU)(e)&&(r[_O]=e),r}const EO=new Map;function xO(e){if("userMessageAction"===e.action.case)return e.action.value.userMessage?.text}function PO(e,t,r){const n=e.runOptions?.requestedModel;return{conversationId:e.conversationId,generationId:e.conversationId,model:n?.modelId??"unknown",modelId:n?.modelId,modelParams:n?.parameters.map((e=>({id:e.id,value:e.value}))),loopCount:t,promptText:r}}function RO(e){return new i.QFf({action:{case:"userMessageAction",value:new i.Vtf({userMessage:new i.RGk({text:e})})}})}function IO(e){return e instanceof DOMException&&"AbortError"===e.name||e instanceof Error&&("AbortError"===e.name||"The operation was aborted"===e.message)}function TO(e){e?.catch((e=>{SO.Jz.warn("[agent-session-runner] fire-and-forget hook failed:",e)}))}class AO{constructor(e,t,r){this.inner=e,this.getToken=t,this.restMcpHost=r}async getDefinitions(e,t=!0){const r=await this.inner.getDefinitions(e,t);return Promise.all(r.map((async e=>{const t=await async function(e,t,r){if(!("url"in e)||!e.url||void 0===sb(e.url,r)||Object.keys(e.headers??{}).some((e=>e.toLowerCase()===ob)))return e;const n=await t();return void 0===n||0===n.length?e:{...e,headers:{...e.headers??{},[ob]:`Bearer ${n}`}}}(e.serverConfig,this.getToken,this.restMcpHost);return t===e.serverConfig?e:{...e,serverConfig:t}})))}clearCache(){this.inner.clearCache?.()}}const $O=new Set(["mcp.slack.com","setup.shopify.com"]);class MO{constructor(e,t){this.inner=e,this.resolver=t}async getDefinitions(e,t=!0){const r=await this.inner.getDefinitions(e,t);return Promise.all(r.map((async e=>{const t=await async function(e,t){if(!("url"in e)||!e.url)return e;const r=await async function(e,t,r,n=fetch){let o;try{o=new URL(e).hostname}catch{return t}const s=void 0!==sb(e,r.restMcpHost);if(!$O.has(o)&&!s)return t;let i=await r.resolve(e);if(!i&&s){const t=(await cx(e,n))?.clientId;void 0!==t&&(i={CLIENT_ID:t})}return i?t?void 0===ix(t.CLIENT_ID)?{...i,...t,CLIENT_ID:i.CLIENT_ID}:{...i,...t}:i:t}(e.url,e.auth,t);return r===e.auth?e:{...e,auth:r}}(e.serverConfig,this.resolver);return t===e.serverConfig?e:{...e,serverConfig:t}})))}clearCache(){this.inner.clearCache?.()}}class DO{constructor(e,t){this.storage=e,this.prefix=t}async loadTokens(e){return this.storage.loadTokens(this.prefix+e)}async saveTokens(e,t){return this.storage.saveTokens(this.prefix+e,t)}async loadClientInformation(e){return this.storage.loadClientInformation(this.prefix+e)}async saveClientInformation(e,t){return this.storage.saveClientInformation(this.prefix+e,t)}}class OO{constructor(e,t){this.storage=e,this.prefix=t}async isServerApproved(e,t,r){return this.storage.isServerApproved(this.prefix+e,t,r)}}class FO{constructor(e){this.higherPrecedenceSources=e}async load(e,t,r,n,o){for(const r of this.higherPrecedenceSources){const n=(await r.getDefinitions(e)).find((e=>e.identifier===t));if(void 0!==n)throw new TC(t,n.configPath??"another config")}return await o(e,r)}}class NO extends nI{constructor(e,t){super(e),this.shadowedClientsClosed=t}async closeAllClients(){await Promise.all([super.closeAllClients(),this.shadowedClientsClosed])}}async function LO(e){try{await(e.close?.())}catch{}}class jO{constructor(e){this.loaders=e}async load(e,t=!0){const r=await Promise.allSettled(this.loaders.map((({loader:r})=>r.load(e,t)))),n=r.find((e=>"rejected"===e.status));if(n)throw await Promise.allSettled(r.flatMap((e=>"fulfilled"===e.status?[e.value.closeAllClients()]:[]))),n.reason;const o=r.filter((e=>"fulfilled"===e.status)).map((e=>e.value)),s={},i=[];for(let e=0;e{})))}async loadClient(e,t,r=!1){for(const{loader:n,prefix:o}of this.loaders)if(t.startsWith(o)){t=t.slice(o.length);try{return await n.loadClient(e,t,r)}catch(e){if(e instanceof Error&&e.message.includes("not found in config"))continue;throw e}}throw new Error(`MCP client "${t}" not found in config`)}clearClient(e){for(const{loader:t,prefix:r}of this.loaders){if(!e.startsWith(r))continue;const n=e.slice(r.length);t.clearClient?.(n)}}clearAllMcpCaches(){for(const{loader:e}of this.loaders)e.clearAllMcpCaches?.()}}class UO{constructor(e,t,r,n,i=!1,a,c,l=s.join((0,o.homedir)(),".cursor","mcp.json"),u,d,h){const p=Array.isArray(e)?e:[e],f={}.location,m=[];"enterprise"===f?.source&&m.push({path:f.path,prefix:"enterprise-",scope:"enterprise"});for(let e=0;e({prefix:t,scope:r,fileSource:new bI(e,"enterprise"===r||"env"===r?EE:void 0)}))),y=[];for(const{prefix:e,scope:o,fileSource:s}of w){const l=i?"":e,d=new DO(t,l),p=new OO(n,l),f=w.flatMap((e=>{return t=e.scope,r=o,xE.indexOf(t)0?[new FO(f)]:[]],g=new SI(u?new MO(s,u):s,d,m,{authRedirectUrlGenerator:a,isLinkSharedPaymentTokenLogRedactionEnabled:h});y.push({prefix:l,loader:g})}this.loader=new jO(y)}static init(e,t,r,n=!1,o,i={}){const a=new AI(s.join(r,"mcp-auth.json"));(async function(e){await(0,Co.rm)(s.join(e,"mcp-cache.json"),{force:!0})})(r).catch((()=>{}));const c=n?{isServerApproved:()=>Promise.resolve(!0)}:new MC(s.join(r,"mcp-approvals.json"),t);return new UO(t,a,e,c,!0,void 0,o,void 0,i.defaultAuthResolver,void 0,i.isLinkSharedPaymentTokenLogRedactionEnabled)}async load(e,t=!0){return this.loader.load(e,t)}async loadClient(e,t,r=!1){return this.loader.loadClient(e,t,r)}clearClient(e){this.loader.clearClient(e)}clearAllMcpCaches(){this.loader.clearAllMcpCaches()}}const BO="cursor-plugins/local";function WO(e){var t;if(e)for(const r of e)if("object"==typeof(t=r)&&null!==t&&t.kind===BO)return r}class HO extends rI{constructor(e){super(e),this.runtimeManager=e,this.disposed=!1}async dispose(){this.disposed||(this.disposed=!0,await this.runtimeManager.closeAllClients())}}class qO{constructor(e){this.storagePath=e}async isServerDisabled(e){try{const t=await(0,Co.readFile)(this.storagePath,"utf8"),r=JSON.parse(t);return Array.isArray(r)?r.includes(e):(await this.writeDisabledServers([]),!1)}catch(e){if("object"==typeof e&&null!==e&&"code"in e&&"ENOENT"===e.code)return!1;throw e}}async writeDisabledServers(e){await(0,Co.mkdir)((0,s.dirname)(this.storagePath),{recursive:!0}),await(0,Co.writeFile)(this.storagePath,JSON.stringify(e,null,2))}}class zO{constructor(e,t){this.pluginMcpService=e,this.importThirdPartyPlugins=t}async getDefinitions(){let e;try{e=await this.pluginMcpService.getPluginMcpServers()}catch(e){return SO.Jz.warn("[cursor-config-mcp] Failed to enumerate plugin MCP servers:",e),[]}const t=[];for(const r of e){if(!this.importThirdPartyPlugins&&ZO(r))continue;const e=xI(r);e?t.push({identifier:r.identifier,authStorageKey:r.identifier,serverConfig:e,configPath:"",source:"plugin",metadata:{identifier:r.identifier,pluginName:r.pluginName,pluginSource:r.pluginSource}}):SO.Jz.warn("[cursor-config-mcp] Failed to initialize plugin MCP client:",{identifier:r.identifier,pluginName:r.pluginName,pluginSource:r.pluginSource,result:"invalid-config",errorMessage:"pluginMcpDescriptorToServerConfig returned undefined"})}return t}}class GO{constructor(e){this.servers=e}async getDefinitions(){return Object.entries(this.servers).map((([e,t])=>({identifier:e,authStorageKey:`inline:${e}`,serverConfig:JO(e,t),source:"inline",metadata:{source:"cursor-sdk"}})))}}function VO(e={}){const t=e.teamSettingsService??{getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getAdminCommandDenylist:async()=>({rules:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}},r=e.ignoreApprovals??!1,n=e.importThirdPartyPlugins??!1,i=void 0===e.isLinkSharedPaymentTokenLogRedactionEnabled?{}:{isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled},a=e.restMcpCursorAuthTokenSupplier,c=e=>void 0===a?e:new AO(e,a,"api.cursor.com");return{async createLease(a){const l=a.workspaceState,u=l.projectRoot??l.workingDirectory,d=l.projectDirectory;if(!u||!d)return new tI;const h=new qO((0,s.join)(d,"mcp-disabled.json")),p=function(e){const{teamSettingsService:t,projectRoot:r,projectDirectory:n,ignoreApprovals:i,disabledStore:a,includeProjectMcp:c,includeUserMcp:l,isLinkSharedPaymentTokenLogRedactionEnabled:u}=e;if(c&&l)return UO.init(t,r,n,i,a,{isLinkSharedPaymentTokenLogRedactionEnabled:u});if(!c&&!l)return;const d=new AI((0,s.join)(n,"mcp-auth.json")),h=i?{isServerApproved:()=>Promise.resolve(!0)}:new MC((0,s.join)(n,"mcp-approvals.json"),r),p=[new zC,new $C(h),new CI(t),new AC(a)],f=[];return c&&f.push({prefix:"",loader:new EI((0,s.join)(r,".cursor","mcp.json"),d,p,{isLinkSharedPaymentTokenLogRedactionEnabled:u})}),l&&f.push({prefix:"",loader:new EI((0,s.join)((0,o.homedir)(),".cursor","mcp.json"),d,p,{isLinkSharedPaymentTokenLogRedactionEnabled:u})}),KO(f)}({teamSettingsService:t,projectRoot:u,projectDirectory:d,ignoreApprovals:r,disabledStore:h,includeProjectMcp:e.includeProjectMcp??!0,includeUserMcp:e.includeUserMcp??!0,isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled}),f=[],m=e.inlineMcpServers??{};if(Object.keys(m).length>0){const e=new AI((0,s.join)(d,"mcp-auth.json")),r=[new zC,new CI(t)];f.push({prefix:"",loader:new SI(c(new GO(m)),e,r,i)})}const g=WO(a.services.pluginBootstrapOutputs);if(g&&(e.includePluginMcp??1)){const e=new MC((0,s.join)(d,"mcp-approvals.json"),u),o=new AI((0,s.join)(d,"mcp-auth.json")),a=[new zC];r||a.push(new $C(e)),a.push(new CI(t),new AC(h));const l=new ND(g.pluginsService),p=new SI(c(new zO(l,n)),o,a,i);f.push({prefix:"",loader:p})}if(p&&f.push({prefix:"",loader:p}),0===f.length)return new tI;const w=KO(f),v=await w.load(e.initializationCtx??(0,y.q6)(),e.cache);return new HO(v)}}}function KO(e){return 1===e.length?e[0].loader:new jO(e)}function JO(e,t){if("command"in t){if(void 0!==t.type&&"stdio"!==t.type)throw new Error(`Unsupported MCP server type "${String(t.type)}" for "${e}"`);return{command:t.command,args:t.args?[...t.args]:void 0,env:t.env,cwd:t.cwd,startupTimeoutSec:t.startupTimeoutSec}}if("url"in t){if(void 0!==t.type&&"http"!==t.type&&"sse"!==t.type)throw new Error(`Unsupported MCP server type "${String(t.type)}" for "${e}"`);const r={url:t.url,headers:t.headers,auth:t.auth?{CLIENT_ID:t.auth.CLIENT_ID,CLIENT_SECRET:t.auth.CLIENT_SECRET,scopes:t.auth.scopes?[...t.auth.scopes]:void 0}:void 0};return"sse"===t.type?{...r,type:"sse"}:r}throw new Error(`Invalid inline MCP server config for "${e}"`)}function ZO(e){return"claude-plugin"===e.pluginSource}const XO=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass"];function QO(e){let t=e.trim();t.startsWith("&")&&(t=t.slice(1).trim());const r=t.charAt(0);if("'"!==r&&'"'!==r)return t.split(/\s/)[0]??"";let n="";for(let e=1;e0)return{...n,followup_message:n.reason.trim()};if(!sF(t))return n;const o=aF(e),s=cF(o,r)?o:void 0,i=void 0!==s?{...n,...s}:n;return"block"===i.decision&&"string"==typeof i.reason&&i.reason.trim().length>0?{...i,followup_message:i.reason.trim()}:n}const uF=e=>{const t=[];return Rd(e)?Td(!0):(t.push("Expected an object"),Td(!1,t))},dF=e=>{const t=[],r=uF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny","ask"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("Invalid user_message value. Expected a string if provided"),void 0!==e.agent_message&&"string"!=typeof e.agent_message&&t.push("Invalid agent_message value. Expected a string if provided"),Td(0===t.length,t)};function hF(e){const t=e.modelId,r=e.modelParams;return{...void 0!==t&&{model_id:t},...void 0!==r&&r.length>0?{model_params:r.map((e=>({id:e.id,value:e.value})))}:{}}}const pF=new Set([xd.sessionStart,xd.beforeSubmitPrompt,xd.preToolUse,xd.postToolUse,xd.postToolUseFailure]);function fF(e){return"prompt"===e.type}function mF(e){return"command"===e.type||void 0===e.type}const gF={[xd.beforeShellExecution]:dF,[xd.beforeMCPExecution]:dF,[xd.afterShellExecution]:e=>{const t=uF(e);return t.isValid,t},[xd.afterMCPExecution]:e=>{const t=uF(e);return t.isValid,t},[xd.beforeReadFile]:e=>{const t=[],r=uF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("user_message must be a string if provided"),Td(0===t.length,t)},[xd.afterFileEdit]:e=>{const t=uF(e);return t.isValid,t},[xd.beforeTabFileRead]:e=>{const t=[],r=uF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("user_message must be a string if provided"),Td(0===t.length,t)},[xd.afterTabFileEdit]:e=>uF(e),[xd.beforeSubmitPrompt]:e=>{const t=uF(e);if(!t.isValid)return t;const r=[];return void 0!==e.continue&&"boolean"!=typeof e.continue&&r.push("continue must be a boolean if provided"),void 0!==e.user_message&&"string"!=typeof e.user_message&&r.push("user_message must be a string if provided"),void 0===e.additional_context||Pd(e.additional_context)||r.push("additional_context must be a string if provided"),Td(0===r.length,r)},[xd.stop]:e=>{const t=uF(e);if(!t.isValid)return t;const r=[];return void 0!==e.followup_message&&"string"!=typeof e.followup_message&&r.push("followup_message must be a string if provided"),Td(0===r.length,r)},[xd.afterAgentResponse]:e=>{const t=uF(e);return t.isValid,t},[xd.afterAgentThought]:e=>{const t=uF(e);return t.isValid,t},[xd.sessionStart]:e=>{const t=uF(e);if(!t.isValid)return t;const r=[];if(void 0!==e.env)if(Rd(e.env))for(const[t,n]of Object.entries(e.env))Pd(t)||r.push(`env key "${t}" must be a string`),Pd(n)||r.push(`env value for "${t}" must be a string`);else r.push("env must be an object if provided");return void 0===e.additional_context||Pd(e.additional_context)||r.push("additional_context must be a string if provided"),void 0!==e.continue&&"boolean"!=typeof e.continue&&r.push("continue must be a boolean if provided"),void 0===e.user_message||Pd(e.user_message)||r.push("user_message must be a string if provided"),Td(0===r.length,r)},[xd.sessionEnd]:e=>{const t=uF(e);return t.isValid?Td(!0,[]):t},[xd.preCompact]:e=>{const t=uF(e);if(!t.isValid)return t;if(null==e||0===Object.keys(e).length)return Td(!0,[]);const r=[];if(!Id(e))return r.push("PreCompact response must be an object"),Td(!1,r);const n=e;return void 0===n.user_message||(e=>"string"==typeof e)(n.user_message)||r.push("user_message must be a string"),Td(0===r.length,r)},[xd.subagentStart]:e=>{const t=uF(e);if(!t.isValid)return t;if(!Id(e))return Td(!1,["Expected an object"]);const r=[],n=e;if(void 0!==n.permission){const e=["allow","deny","ask"];"string"==typeof n.permission&&e.includes(n.permission)||r.push(`Invalid permission value. Expected one of: ${e.join(", ")}, or undefined`)}return void 0===n.user_message||Pd(n.user_message)||r.push("user_message must be a string if provided"),Td(0===r.length,r)},[xd.subagentStop]:e=>{const t=uF(e);if(!t.isValid)return t;const r=[];return Id(e)&&void 0!==e.followup_message&&"string"!=typeof e.followup_message&&r.push("followup_message must be a string if provided"),Td(0===r.length,r)},[xd.preToolUse]:e=>{const t=[],r=uF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny","ask"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("Invalid user_message value. Expected a string if provided"),void 0!==e.agent_message&&"string"!=typeof e.agent_message&&t.push("Invalid agent_message value. Expected a string if provided"),void 0!==e.updated_input&&("object"!=typeof e.updated_input||null===e.updated_input||Array.isArray(e.updated_input))&&t.push("Invalid updated_input value. Expected a plain object if provided"),Ad(e.additional_context,"additional_context",t),Td(0===t.length,t)},[xd.postToolUse]:e=>{const t=[],r=uF(e);return r.isValid?(Ad(e.additional_context,"additional_context",t),Td(0===t.length,t)):r},[xd.postToolUseFailure]:e=>{const t=uF(e);if(!t.isValid)return t;const r=[];return Ad(e.additional_context,"additional_context",r),Td(0===r.length,r)},[xd.workspaceOpen]:e=>{const t=uF(e);if(!t.isValid)return t;const r=[];return void 0!==e.pluginPaths&&(Array.isArray(e.pluginPaths)?e.pluginPaths.forEach(((e,t)=>{"string"==typeof e?0===e.trim().length&&r.push(`pluginPaths[${t}] must be a non-empty string`):r.push(`pluginPaths[${t}] must be a string`)})):r.push("pluginPaths must be an array of strings if provided")),Td(0===r.length,r)}},wF=(e,t,r)=>{const n=function(e,t,r){let n;return n=e===xd.preToolUse?function(e,t){if(!iF(e))return e;const r=e;if(void 0!==r.permission||void 0!==r.user_message||void 0!==r.agent_message||void 0!==r.updated_input)return r;if(!sF(t))return r;const n=aF(e);if(!cF(n,"PreToolUse"))return r;const o={...r};let s=!1;return void 0!==n.permissionDecision&&(o.permission=n.permissionDecision,s=!0),"string"==typeof n.permissionDecisionReason&&(o.user_message=n.permissionDecisionReason,s=!0),iF(n.updatedInput)&&(o.updated_input=n.updatedInput,s=!0),s?o:r}(t,r):e===xd.stop?lF(t,r,"Stop"):e===xd.subagentStop?lF(t,r,"SubagentStop"):t,function(e,t,r,n){if(!pF.has(e)||!iF(r)||void 0!==r.additional_context)return r;const o=iF(t)?function(e){return"string"==typeof e.additionalContext?e.additionalContext:void 0}(t)??function(e,t,r){if(!sF(r))return;const n=Fd[e];if(void 0===n)return;const o=aF(t);return cF(o,n)&&"string"==typeof o.additionalContext?o.additionalContext:void 0}(e,t,n):void 0;return void 0===o?r:{...r,additional_context:o}}(e,t,n,r)}(e,t,r),o=(0,gF[e])(n);return o.isValid?{success:!0,data:n}:{success:!1,errors:o.errors}},yF=[xd.beforeShellExecution,xd.beforeMCPExecution,xd.beforeReadFile,xd.beforeTabFileRead,xd.subagentStart,xd.preToolUse],vF=[xd.workspaceOpen];function bF(e,t){const r=[];return"string"==typeof e&&e.trim()&&r.push(e.trim()),"string"==typeof t&&t.trim()&&r.push(t.trim()),r.length>0?r.join("\n\n---\n\n"):void 0}function SF(e,t){return{..."object"==typeof e&&null!==e?e:{},...t}}function kF(e){return yF.includes(e)}function _F({step:e,command:t,failClosed:r,kind:n}){const o=kF(e);if(!r&&!o)return{shouldNotifyUser:!1};const s=r?"Tool blocked because this hook is configured to fail closed (block when it fails). "+("invalid_json"===n?`Hook "${t}" returned invalid JSON.`:`Hook "${t}" returned invalid response.`):"invalid_json"===n?`Hook "${t}" returned invalid JSON. The command was blocked for safety.`:`Hook "${t}" returned an invalid response for this hook step. The command was blocked for safety.`;return{blockResponse:EF(e,s),cause:r?"script_fail_closed":"permission_hook_invalid_output",reason:s,shouldNotifyUser:o&&!r}}function CF(e,t){return t}function EF(e,t){return kF(e)?CF(0,{permission:"deny",user_message:t}):e===xd.beforeSubmitPrompt||e===xd.sessionStart?CF(0,{continue:!1,user_message:t}):e===xd.stop?CF(0,{}):void 0}function xF(e){try{return{value:JSON.parse(e)}}catch{return}}function PF(e){if("object"!=typeof e||null===e)return!1;const t=e.event;return"backgrounded"===t?.case}function RF(e){if("object"!=typeof e||null===e)return;const t=e.path;return"string"==typeof t&&t.length>0?t:void 0}class IF{cacheCarriersForExecId(e,t){const r=this.carriersByExecId.get(e);if(!(void 0!==r&&r.length>0&&0===t.length))for(this.carriersByExecId.has(e)&&this.carriersByExecId.delete(e),this.carriersByExecId.set(e,t);this.carriersByExecId.size>IF.CARRIERS_BY_EXEC_ID_MAX;){const e=this.carriersByExecId.keys().next().value;if(void 0===e)break;this.carriersByExecId.delete(e)}}constructor(e,t,r,n){this.inner=e,this.wake=r,this.carriersByExecId=new Map,this.inFlightByExecId=new Map,this.resolveDrain="function"==typeof t?t:e=>t,this.skipPathWriteDrain=n?.skipPathWriteDrain,this.onWakeWrittenPath=n?.onWakeWrittenPath,this.forceWrittenPathBeforeDrain=n?.forceWrittenPathBeforeDrain,this.writeBarrierTimeoutMs=n?.writeBarrierTimeoutMs??2e3,this.resolveWriteBarrierTimeoutMs=n?.resolveWriteBarrierTimeoutMs,this.onWriteBarrier=n?.onWriteBarrier}resolveTimeoutMs(){if(void 0!==this.resolveWriteBarrierTimeoutMs)try{const e=this.resolveWriteBarrierTimeoutMs();if("number"==typeof e&&Number.isFinite(e))return e}catch{}return this.writeBarrierTimeoutMs}get(e){return this.wrapImpl(e.symbol,this.inner.get(e))}*entries(){for(const[e,t]of this.inner.entries())yield[e,this.wrapImpl(e.symbol,t)]}wrapImpl(e,t){if(!function(e){return"object"==typeof e&&null!==e&&"execute"in e&&"function"==typeof e.execute}(t))return t;const r=function(e){return e===HT.symbol||e===qT.symbol?{kind:"path"}:e===jT.symbol||e===ee.symbol||e===vA.symbol?{kind:"exposed"}:void 0}(e),n=this.resolveDrain,o=this.wake,s=this.skipPathWriteDrain,i=this.forceWrittenPathBeforeDrain,a=()=>this.resolveTimeoutMs(),c=this.onWriteBarrier,l=this.onWakeWrittenPath,u=(e,t)=>{if(void 0!==r&&void 0!==o)try{if("path"===r.kind){const r=RF(e);void 0!==r&&(o.wakeForWrittenPath(r),l?.(r,t))}else o.wakeExposedMounts()}catch{}},d=this.cacheCarriersForExecId.bind(this),h=this.carriersByExecId,p=this.inFlightByExecId,f=async(e,t)=>{const r=t?.hookContextCollector;if(void 0===r)return[];if(!1===t?.deliverAgentStoreConflictNotices)return[];const o=void 0!==t?.execId&&t.execId.length>0?t.execId:void 0;if(void 0!==o){const e=h.get(o);if(void 0!==e)return e.length>0&&r.push(...e),e;const t=p.get(o);if(void 0!==t){const e=await t;return e.length>0&&r.push(...e),e}}const s=async t=>{const r=n(e);let s=[];try{const e=await r.peek();if(s=e.eventIds,e.carriers.length>0)return t.push(...e.carriers),r.ack(e.eventIds),void 0!==o&&d(o,e.carriers),e.carriers;s.length>0&&r.ack(s);const n=[];return void 0!==o&&d(o,n),n}catch{return s.length>0&&r.release(s),[]}};if(void 0===o)return await s(r);const i=s(r);p.set(o,i);try{return await i}finally{p.get(o)===i&&p.delete(o)}};return new Proxy(t,{get:(t,n,o)=>"execute"!==n?Reflect.get(t,n,o):(n,o,l)=>{const d=t.execute.call(t,n,o,l);return"object"==typeof(h=d)&&null!==h&&Symbol.asyncIterator in h&&"function"==typeof h[Symbol.asyncIterator]?async function*(){let t=!1,r=!1,s=!1;try{for await(const r of d)if(e===ee.symbol&&PF(r)){if(!t){u(o,n);const e=await f(n,l);t=!0,e.length>0&&(yield new he.FI({event:{case:"hookContext",value:new he.Ng({hookAdditionalContexts:[...e]})}}))}yield r}else yield r;s=!0}catch(e){throw r=!0,e}finally{u(o,n),t||r||!s||await f(n,l)}}():function(e){return"object"==typeof e&&null!==e&&"then"in e&&"function"==typeof e.then}(d)?(async()=>{try{const t=await d;return u(o,n),e===HT.symbol&&!0===s?.()&&!0===l?.enableAgentStoreConflictNotices||(await async function(e,t,r,n){const o=e=>{try{n.onWriteBarrier?.(e)}catch{}};if(void 0===e||"path"!==r?.kind)return;const s=RF(t);if(void 0===s)return;if(!(n.timeoutMs>0))return void o({durationMs:0,outcome:"skipped"});const i=Date.now(),a=e(s).then((e=>e),(()=>"error")),c=await Promise.race([a,(0,Or.cb)(n.timeoutMs).then((()=>"timeout"))]);"not_store_path"!==c&&o({durationMs:Date.now()-i,outcome:c})}(i,o,r,{timeoutMs:a(),onWriteBarrier:c}),await f(n,l)),t}catch(e){throw u(o,n),e}})():(u(o,n),d);var h}})}}function TF(e){return new RegExp(`<${e}(?:\\s[^>]*)?>[\\s\\S]*?`,"gi")}IF.CARRIERS_BY_EXEC_ID_MAX=32,Error,ou.execFileSync,new Map,xo.constants.O_NOFOLLOW,new Set(["write_conflict","create_conflict","truncate_conflict_failed","conflict_fallback_failed","quota_exceeded","gap"]),new Set(["write_conflict","create_conflict","truncate_conflict_failed","conflict_fallback_failed","quota_exceeded"]),Math.max(1,Math.floor(8192));const AF=["user_info","project_layout","rules","always_applied_workspace_rules","agent_requestable_workspace_rules","user_rules","agent_skills","available_skills","cloud_instructions","cloud_task_instructions","open_and_recently_viewed_files","system_reminder","system-reminder","instructions_update","mcp_instructions","mcp_file_system","mcp_file_system_servers","git_status","agent_transcripts","cursor_rules_context","attached_files","system_notification","task_notification","agent_notification"].map(TF);function $F(e){return function(e,t){let r=e;if(r.includes("<"))for(const e of t)r=r.replace(e,"");return(r.includes("\n\n\n")?r.replace(MF,"\n\n"):r).trim()}(e,AF)}["system_reminder","system-reminder"].map(TF);const MF=/\n{3,}/g;function DF(e){const t=(0,So.sh)(e.conversationId);if("subagent"===e.kind&&e.parentConversationId){const r=(0,So.sh)(e.parentConversationId);return`${So.O2}/${r}/subagents/${t}.${e.ext}`}return`${So.O2}/${t}/${t}.${e.ext}`}function OF(e){const t=(0,So.sh)(e.conversationId);return`${So.O2}/${t}.${e.ext}`}function FF(e){const t=e.exts??["jsonl","txt"],r=e.includeLegacy??!0,n=[],o=e=>{n.includes(e)||n.push(e)};for(const n of t)o(DF({conversationId:e.conversationId,ext:n,kind:e.kind,parentConversationId:e.parentConversationId})),"subagent"===e.kind&&e.parentConversationId&&o(DF({conversationId:e.conversationId,ext:n,kind:"primary"})),r&&o(OF({conversationId:e.conversationId,ext:n}));return n}var NF;!function(e){e.INTERNAL="INTERNAL",e.EXTERNAL="EXTERNAL",e.NO_PREAMBLE="NO_PREAMBLE"}(NF||(NF={}));var LF=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},jF=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function UF(e){switch(e){case i.xyI.AGENT:return"agent";case i.xyI.ASK:return"ask";case i.xyI.PLAN:return"plan";case i.xyI.DEBUG:return"debug";case i.xyI.TRIAGE:return"triage";case i.xyI.MULTITASK:return"multitask";case i.xyI.CUSTOM:return"custom";case i.xyI.UNSPECIFIED:default:return"agent"}}function BF(e,t){return t instanceof Uint8Array?{__type:"Uint8Array",hex:(r=t,Array.from(r).map((e=>e.toString(16).padStart(2,"0"))).join(""))}:"bigint"==typeof t?t.toString():t;var r}function WF(e,t){return function(e){return"object"==typeof e&&null!==e&&"__type"in e&&"Uint8Array"===e.__type&&"hex"in e&&"string"==typeof e.hex}(t)?`[Binary data omitted from transcript: ${t.hex.length/2} bytes]`:t}const HF=new TextEncoder,qF=new TextDecoder,zF=new class{serialize(e){const t=JSON.stringify(e,BF);return HF.encode(t)}deserialize(e){const t=qF.decode(e);return t.includes('"__type":"Uint8Array"')?JSON.parse(t,WF):JSON.parse(t)}};function GF(e){const t=e.providerOptions;return!0===t?.cursor?.isSummary}function VF(e){return"system"!==e.role&&!GF(e)}function KF(e,t){return"user"===e.role&&"user"===t.role}async function JF(e,t,r){const n=await t.getBlob(e,r);return n?i.Anz.fromBinary(n).summarizedMessages:[]}async function ZF(e,t,r,n){const o=await t.getBlob(e,r);if(o){if(o.length>5e6)return n.omittedOversizeBlobCount++,n.omittedOversizeBlobBytes+=o.length,n.largestOmittedOversizeBlobBytes=Math.max(n.largestOmittedOversizeBlobBytes,o.length),{role:"assistant",content:`[Oversize transcript blob omitted: ${s=o.length,`${(s/1e6).toFixed(1)} MB`}]`};var s;try{const e=performance.now(),t=zF.deserialize(o);return n.totalDeserializeDurationMs+=performance.now()-e,n.hydratedBlobCount++,n.hydratedBlobBytes+=o.length,n.largestHydratedBlobBytes=Math.max(n.largestHydratedBlobBytes,o.length),t}catch{return}}}async function XF(e,t,r){const n={messages:[],hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0};for(const o of r){const r=await ZF(e,t,o,n);r&&n.messages.push(r)}return n}async function QF(e,t,r,n,o){const s=[];let i=0;const a=()=>{const o=ZF(e,t,r[i++],n);o.catch((()=>{})),s.push(o)};for(;i{let r;return r="string"==typeof t?t:"object"==typeof t&&null!==t?JSON.stringify(t):String(t),` ${e}: ${r}`})).join("\n")}`}(e.args)}`;case"tool-result":return`[Tool result] ${e.toolName}`;default:return""}}function eN(e){return $F(e)}const tN=/[\s\S]*?<\/think>/gi,rN=/[\s\S]*?<\/thinking>/gi,nN=/\n{3,}/g;function oN(e){let t=e;return t.includes("<")&&(t=t.replace(tN,"").replace(rN,"")),(t.includes("\n\n\n")?t.replace(nN,"\n\n"):t).trim()}function sN(e,t,r){if(void 0===e)return"";if("string"==typeof e){const n=t?eN(e):e;return r?oN(n):n}return e.map((e=>{if(r&&"text"===e.type){const r=oN(t?eN(e.text):e.text);return YF({...e,text:r},!1)}return YF(e,t)})).filter(Boolean).join("\n")}function iN(e,t){const r={role:e.role},n=e.content;if("string"==typeof n){const o=t?eN(n):n,s="assistant"===e.role?oN(o):o;s.trim()&&(r.text=s)}else if(Array.isArray(n)){const o=[],s=[],i=[];let a;for(const r of n)switch(r.type){case"text":{const n=t?eN(r.text):r.text,s="assistant"===e.role?oN(n):n;s.trim()&&o.push(s);break}case"reasoning":r.text.trim()&&s.push(r.text);break;case"redacted-reasoning":s.push("[REDACTED]");break;case"image":o.push("[Image]");break;case"file":o.push(r.filename?`[File: ${r.filename}]`:"[File]");break;case"tool-call":i.push({toolName:r.toolName,args:r.args});break;case"tool-result":a={toolName:r.toolName}}o.length>0&&(r.text=o.join("\n")),s.length>0&&(r.thinking=s.join("\n")),i.length>0&&(r.toolCalls=i),a&&(r.toolResult=a)}return r}function aN(e){return e.endsWith("\n")?e:`${e}\n`}function cN(e){const{turnEnded:t}=e,r=[],n={},o=[];return void 0!==t&&(r.push(function(e){switch(e.status){case"success":return"Turn ended: success.";case"error":return`Turn ended: error: ${e.error}`;case"aborted":return e.error?`Turn ended: aborted: ${e.error}`:"Turn ended: aborted.";default:return e}}(t)),n.turnEnded=t,o.push(JSON.stringify({type:"turn_ended",...t}))),{textSuffixes:r,jsonFields:n,jsonlLines:o}}function lN(e){if("system"===e.role||GF(e))return;const t=iN(e,"user"===e.role),r=[],n=[];if(t.text&&n.push(t.text),t.thinking&&n.push(t.thinking),n.length>0&&r.push({type:"text",text:n.join("\n\n")}),t.toolCalls)for(const e of t.toolCalls)r.push({type:"tool_use",name:e.toolName,input:e.args});if(0===r.length)return;const o={role:e.role,message:{content:r}};return JSON.stringify(o)}class uN{constructor(e,t,r,n={}){this.projectDir=e,this.blobStore=t,this.writeFile=r,this.options={writeText:n.writeText??!0,writeJson:n.writeJson??!1,writeJsonl:n.writeJsonl??!1,pathResolver:n.pathResolver,appendFile:n.appendFile,streamFullJsonlWrites:n.streamFullJsonlWrites??!1,fallbackToFullWriteOnIncrementalFailure:n.fallbackToFullWriteOnIncrementalFailure??!0}}resolveFilePath(e,t){if(this.options.pathResolver)return this.options.pathResolver(e,t);const r=DF({conversationId:e,ext:t,kind:"primary"});return`${this.projectDir}/${r}`}async writeFromStateFull(e,t,r,n={}){const o={stack:[],error:void 0,hasError:!1};try{const s=LF(o,(0,$.VI)(e.withName("writeFromState")),!1);try{const{overviewFactory:e}=n,o=cN(n),{appendFile:i,streamFullJsonlWrites:a,writeJsonl:c,writeText:l,writeJson:u}=this.options;if(i&&a&&c&&!l&&!u&&!e)try{return await this.writeJsonlStreamed(s,{state:t,filePath:this.resolveFilePath(r,"jsonl"),appendFile:i,terminalLines:o.jsonlLines}),!0}catch(e){console.error("[TranscriptStore] Streamed transcript write failed, retrying as a single write:",e)}const d=await async function(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=LF(n,(0,$.VI)(e.withName("hydrateSummaryArchives")),!1);let s=0;const i=(0,$.OA)(o.ctx),a=[];let c=0,l=0,u=0,d=0,h=0,p=0,f=0;const m=await Promise.all(r.summaryArchives.map((async e=>{s++;try{const r=await JF(i,t,e);return s+=r.length,await XF(i,t,r)}catch{return{messages:[],hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0}}})));for(const e of m)a.push(...e.messages),c+=e.hydratedBlobCount,l+=e.hydratedBlobBytes,u=Math.max(u,e.largestHydratedBlobBytes),d+=e.totalDeserializeDurationMs,h+=e.omittedOversizeBlobCount,p+=e.omittedOversizeBlobBytes,f=Math.max(f,e.largestOmittedOversizeBlobBytes);o.span.setAttribute("getBlobCount",s),o.span.setAttribute("hydratedBlobCount",c),o.span.setAttribute("hydratedBlobBytes",l),o.span.setAttribute("largestHydratedBlobBytes",u),o.span.setAttribute("totalDeserializeDurationMs",d),o.span.setAttribute("omittedOversizeBlobCount",h),o.span.setAttribute("omittedOversizeBlobBytes",p),o.span.setAttribute("largestOmittedOversizeBlobBytes",f);const g=LF(n,(0,$.VI)(e.withName("hydratePromptMessages")),!1),w=await XF(i,t,r.rootPromptMessagesJson);g.span.setAttribute("getBlobCount",r.rootPromptMessagesJson.length),g.span.setAttribute("hydratedBlobCount",w.hydratedBlobCount),g.span.setAttribute("hydratedBlobBytes",w.hydratedBlobBytes),g.span.setAttribute("largestHydratedBlobBytes",w.largestHydratedBlobBytes),g.span.setAttribute("totalDeserializeDurationMs",w.totalDeserializeDurationMs),g.span.setAttribute("omittedOversizeBlobCount",w.omittedOversizeBlobCount),g.span.setAttribute("omittedOversizeBlobBytes",w.omittedOversizeBlobBytes),g.span.setAttribute("largestOmittedOversizeBlobBytes",w.largestOmittedOversizeBlobBytes);const y=w.messages.filter(VF);return a.push(...y),a}catch(e){n.error=e,n.hasError=!0}finally{jF(n)}}(s.ctx,this.blobStore,t);if(0===d.length&&0===o.jsonlLines.length)return!0;let h;if((this.options.writeText||e)&&(h=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&"user"===t[0].role&&"user"===t[1].role&&(t=t.slice(1));const r=[];for(const e of t){const t="user"===e.role,n="assistant"===e.role,o=sN(e.content,t,n);o.trim()&&("tool"===e.role?r.push(o):r.push(`${e.role}:\n${o}`))}return r.join("\n\n")}(d)),this.options.writeText){const e=h??"",t=o.textSuffixes.length>0?e.trim().length>0?`${e}\n\n${o.textSuffixes.join("\n")}`:o.textSuffixes.join("\n"):e;t.trim()&&await this.writeFile(this.resolveFilePath(r,"txt"),t)}if(this.options.writeJson){const e=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&"user"===t[0].role&&"user"===t[1].role&&(t=t.slice(1));const r=[];for(const e of t){const t=iN(e,"user"===e.role);(t.text||t.thinking||t.toolCalls||t.toolResult)&&r.push(t)}return 0===r.length?"":JSON.stringify(r,null,2)}(d);if(e||o.jsonlLines.length>0){const n={mode:UF(t.mode),messages:e?JSON.parse(e):[],...o.jsonFields};await this.writeFile(this.resolveFilePath(r,"json"),JSON.stringify(n,null,2))}}if(this.options.writeJsonl){const t=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&KF(t[0],t[1])&&(t=t.slice(1));const r=[];for(const e of t){const t=lN(e);t&&r.push(t)}return r.join("\n")}(d);let n=[t,...o.jsonlLines].filter((e=>e.length>0)).join("\n");if(n&&e&&h?.trim())try{const t=(await e(h)).trim();t&&(n=function(e,t){const r={type:"metadata",metadata:{overview:t}};return`${JSON.stringify(r)}\n${e}`}(n,t))}catch(e){console.error("[TranscriptStore] Failed to generate transcript overview:",e)}n&&await this.writeFile(this.resolveFilePath(r,"jsonl"),aN(n))}return!0}catch(e){return console.error("[TranscriptStore] Failed to write transcript:",e),!1}}catch(e){o.error=e,o.hasError=!0}finally{jF(o)}}async writeJsonlStreamed(e,t){const{filePath:r,appendFile:n}=t;let o=[],s=0,i=0,a=0;const c=async()=>{if(0===o.length)return;const e=`${o.join("\n")}\n`;o=[],s=0,0===i?await this.writeFile(r,e):await n(r,e),i++,a+=e.length},l=async e=>{e&&(o.push(e),s+=e.length+1,s>=1e6&&await c())};let u,d=0;const h=await async function(e,t,r,n){const o={hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0};for(const s of r.summaryArchives){let r;try{r=await JF(e,t,s)}catch{continue}await QF(e,t,r,o,{skipFailedReads:!0,visit:n})}return await QF(e,t,r.rootPromptMessagesJson,o,{skipFailedReads:!1,visit:async e=>{VF(e)&&await n(e)}}),o}((0,$.OA)(e.ctx),this.blobStore,t.state,(async e=>{"system"!==e.role&&(d++,1!==d?(2===d&&u&&(KF(u,e)||await l(lN(u)),u=void 0),await l(lN(e))):u=e)}));u&&await l(lN(u));for(const e of t.terminalLines)await l(e);await c(),e.span.setAttribute("streamed",!0),e.span.setAttribute("chunkCount",i),e.span.setAttribute("writtenChars",a),e.span.setAttribute("hydratedBlobCount",h.hydratedBlobCount),e.span.setAttribute("hydratedBlobBytes",h.hydratedBlobBytes),e.span.setAttribute("largestHydratedBlobBytes",h.largestHydratedBlobBytes),e.span.setAttribute("totalDeserializeDurationMs",h.totalDeserializeDurationMs),e.span.setAttribute("omittedOversizeBlobCount",h.omittedOversizeBlobCount),e.span.setAttribute("omittedOversizeBlobBytes",h.omittedOversizeBlobBytes),e.span.setAttribute("largestOmittedOversizeBlobBytes",h.largestOmittedOversizeBlobBytes)}async writeFromStateIncremental(e,t,r,n,o={}){const s={stack:[],error:void 0,hasError:!1};try{const i=t.rootPromptMessagesJson.length,a=cN(o),c=a.jsonlLines.length>0;if(i===n&&!c&&!o.overviewFactory)return i;const l=this.options.appendFile;if(!(l&&this.options.writeJsonl&&!this.options.writeText&&!this.options.writeJson&&n>0&&i>=n&&(i>n||c))||o.overviewFactory)return await this.writeFromStateFull(e,t,r,o)?i:0;const u=LF(s,(0,$.VI)(e.withName("writeFromStateIncremental")),!1);if(i===n&&c)try{return await l(this.resolveFilePath(r,"jsonl"),aN(a.jsonlLines.join("\n"))),i}catch(n){return console.error(this.options.fallbackToFullWriteOnIncrementalFailure?"[TranscriptStore] Failed to append transcript, falling back to full write:":"[TranscriptStore] Failed to append transcript:",n),this.options.fallbackToFullWriteOnIncrementalFailure?await this.writeFromStateFull(e,t,r,o)?i:0:0}try{const e=t.rootPromptMessagesJson.slice(n),o=await XF(u.ctx,this.blobStore,e);u.span.setAttribute("hydratedBlobCount",o.hydratedBlobCount),u.span.setAttribute("hydratedBlobBytes",o.hydratedBlobBytes),u.span.setAttribute("largestHydratedBlobBytes",o.largestHydratedBlobBytes),u.span.setAttribute("totalDeserializeDurationMs",o.totalDeserializeDurationMs),u.span.setAttribute("omittedOversizeBlobCount",o.omittedOversizeBlobCount),u.span.setAttribute("omittedOversizeBlobBytes",o.omittedOversizeBlobBytes),u.span.setAttribute("largestOmittedOversizeBlobBytes",o.largestOmittedOversizeBlobBytes);const s=[];for(const e of o.messages){const t=lN(e);t&&s.push(t)}if(s.push(...a.jsonlLines),s.length>0){const e=aN(s.join("\n"));await l(this.resolveFilePath(r,"jsonl"),e)}return i}catch(n){return console.error(this.options.fallbackToFullWriteOnIncrementalFailure?"[TranscriptStore] Failed to append transcript, falling back to full write:":"[TranscriptStore] Failed to append transcript:",n),this.options.fallbackToFullWriteOnIncrementalFailure?await this.writeFromStateFull(e,t,r,o)?i:0:0}}catch(e){s.error=e,s.hasError=!0}finally{jF(s)}}}function dN(e,t){const r=function(e){return"object"==typeof e&&null!==e}(e)&&t in e?e[t]:void 0;return"string"==typeof r&&""!==r?r:void 0}function hN(e,t){return e.filter((e=>function(e,t){if(!e.matcher||""===e.matcher||"*"===e.matcher)return!0;if(void 0===t)return!0;try{return new RegExp(e.matcher).test(t)}catch{return!0}}(e,t)))}function pN(e){return`Tool blocked because this hook is configured to fail closed (block when it fails). ${e}`}function fN(e){return Object.values(xd).some((t=>t===e))}function mN(e){switch(e??(0,o.platform)()){case"darwin":return s.default.join("/Library","Application Support","Cursor","hooks.json");case"win32":return s.default.join("C:\\","ProgramData","Cursor","hooks.json");default:return s.default.join("/etc","cursor","hooks.json")}}function gN(e){return fF(e)?`prompt:${e.prompt}`:`command:${e.command}`}function wN(e){return(e.repoHooks??[]).flatMap((e=>[e.projectHooks,e.claudeProjectHooks,e.claudeProjectLocalHooks]))}class yN{constructor(e,t,r){this.fileReader=e,this.paths=t,this.logger=r||{warn:e=>console.warn(`[hooks] ${e}`),info:e=>{}}}async load(e={}){const{loadProjectHooks:t=!0}=e,r={errors:[],configDirs:{}},n=this.paths.projectConfigPath??this.paths.claudeProjectConfigPath??this.paths.claudeProjectLocalConfigPath,o=n?s.default.dirname(s.default.dirname(n)):void 0,i=(e,t)=>{if(!e||!o)return;if(t)return o;const r=s.default.relative(s.default.resolve(o),s.default.resolve(e));return".."===r||r.startsWith(`..${s.default.sep}`)||s.default.isAbsolute(r)?void 0:o},a=async(e,t,n,o,i,a,c,l)=>{if(e)try{if(!await this.fileReader.exists(e))return;if(c&&this.fileReader.pathContainsSymlink&&await this.fileReader.pathContainsSymlink(e,c))return r.errors.push({source:t,message:`${i} at ${e}: refusing to load config path that contains a symlink`}),void this.logger.warn(`Refusing to load ${a} config via symlink path: ${e}`);const u=await this.fileReader.readFile(e);if(!u)return;const{config:d,error:h}=l(u);if(d){switch(n){case"enterpriseHooks":r.enterpriseHooks=d;break;case"teamHooks":r.teamHooks=d;break;case"userHooks":r.userHooks=d;break;case"projectHooks":r.projectHooks=d;break;case"claudeUserHooks":r.claudeUserHooks=d;break;case"claudeProjectHooks":r.claudeProjectHooks=d;break;case"claudeProjectLocalHooks":r.claudeProjectLocalHooks=d;break;default:return}((e,t)=>{r.configDirs[e]=s.default.dirname(t)})(o,e)}else h&&r.errors.push({source:t,message:`${i} at ${e}: ${h}`})}catch(e){r.errors.push({source:t,message:`Error accessing ${a} config file: ${String(e)}`})}},c=[{path:this.paths.enterpriseConfigPath,source:"enterprise",resultKey:"enterpriseHooks",configDirKey:"enterprise",parsePrefix:"Enterprise hooks.json",accessLabel:"enterprise",symlinkCheckRoot:i(this.paths.enterpriseConfigPath,!1)},{path:this.paths.teamConfigPath,source:"team",resultKey:"teamHooks",configDirKey:"team",parsePrefix:"Team hooks.json",accessLabel:"team",symlinkCheckRoot:i(this.paths.teamConfigPath,!1)},{path:this.paths.userConfigPath,source:"user",resultKey:"userHooks",configDirKey:"user",parsePrefix:"User hooks.json",accessLabel:"user",symlinkCheckRoot:i(this.paths.userConfigPath,!1)},{path:t?this.paths.projectConfigPath:void 0,source:"project",resultKey:"projectHooks",configDirKey:"project",parsePrefix:"Project hooks.json",accessLabel:"project",symlinkCheckRoot:i(this.paths.projectConfigPath,!0)}];for(const e of c)await a(e.path,e.source,e.resultKey,e.configDirKey,e.parsePrefix,e.accessLabel,e.symlinkCheckRoot,(t=>this.parseAndValidate(t,e.source)));const l=[{path:this.paths.claudeUserConfigPath,source:"claude-user",resultKey:"claudeUserHooks",configDirKey:"claudeUser",label:"user",symlinkCheckRoot:i(this.paths.claudeUserConfigPath,!1)},{path:t?this.paths.claudeProjectConfigPath:void 0,source:"claude-project",resultKey:"claudeProjectHooks",configDirKey:"claudeProject",label:"project",symlinkCheckRoot:i(this.paths.claudeProjectConfigPath,!0)},{path:t?this.paths.claudeProjectLocalConfigPath:void 0,source:"claude-project-local",resultKey:"claudeProjectLocalHooks",configDirKey:"claudeProjectLocal",label:"project local",symlinkCheckRoot:i(this.paths.claudeProjectLocalConfigPath,!0)}];for(const e of l)await a(e.path,e.source,e.resultKey,e.configDirKey,`Claude ${e.label} settings.json`,`Claude ${e.label}`,e.symlinkCheckRoot,(t=>this.parseClaudeConfig(t,e.source)));return function(e){const{cursorConfigs:t,claudeConfigs:r,logger:n}=e,o=new Map;for(const e of t)if(e?.hooks)for(const[t,r]of Object.entries(e.hooks)){if(!r)continue;let e=o.get(t);e||(e=new Set,o.set(t,e));for(const t of r)e.add(gN(t))}for(const{config:e,source:t}of r)if(e?.hooks)for(const[r,s]of Object.entries(e.hooks)){if(!s)continue;const i=o.get(r);if(!i||0===i.size)continue;const a=s.filter((e=>{const o=gN(e);return!i.has(o)||(n?.info(`Removed duplicate ${t} hook for ${r}: ${o}`),!1)}));a.length!==s.length&&(e.hooks[r]=a)}}({cursorConfigs:[r.enterpriseHooks,r.teamHooks,r.userHooks,r.projectHooks],claudeConfigs:[{config:r.claudeUserHooks,source:"claude-user"},{config:r.claudeProjectHooks,source:"claude-project"},{config:r.claudeProjectLocalHooks,source:"claude-project-local"}],logger:this.logger}),r}parseClaudeConfig(e,t){try{const t=JSON.parse(e);if(!function(e,t={}){if(!Id(e))return!1;if(!("hooks"in e))return!1;const r=e.hooks;if(!Id(r))return!1;const n=r;for(const[e,r]of Object.entries(n))if(e in Od&&Array.isArray(r)){const n=!0===t.allowMatcherlessStop&&"Stop"===e;for(const e of r)if(Id(e)&&"hooks"in e&&Array.isArray(e.hooks)&&("matcher"in e||n))return!0}return!1}(t))return{};const r=t.hooks;if(!r||0===Object.keys(r).length)return{};const n=Xd(r,this.logger),o=Dd(n);return o.isValid?{config:n}:{error:`Invalid transformed config: ${o.errors.join("; ")}`}}catch(e){return{error:`Failed to parse JSON: ${String(e)}`}}}parseAndValidate(e,t){try{const n=this.parseJSONC(e),o=Dd(n);return o.isValid?"object"==typeof(r=n)&&null!==r&&"version"in r&&"number"==typeof r.version&&"hooks"in r&&"object"==typeof r.hooks&&null!==r.hooks&&!Array.isArray(r.hooks)?{config:n}:{error:`Invalid ${t} config: missing 'hooks' property`}:{error:`Invalid ${t} config: ${o.errors.join("; ")}`}}catch(e){return{error:`Failed to parse ${t} config JSON: ${String(e)}`}}var r}parseJSONC(e){let t=e.replace(/\/\/.*$/gm,"");return t=t.replace(/\/\*[\s\S]*?\*\//g,""),JSON.parse(t)}static getConfiguredSteps(e){const t=new Set,r=[e.enterpriseHooks,e.teamHooks,e.userHooks,e.projectHooks,e.claudeUserHooks,e.claudeProjectHooks,e.claudeProjectLocalHooks,...wN(e)];for(const e of r)if(e?.hooks)for(const r of Object.keys(e.hooks))fN(r)&&t.add(r);for(const r of e.pluginHooks??[])for(const e of Object.keys(r.config.hooks))fN(e)&&t.add(e);return t}}const vN="Read",bN="Write",SN="Delete",kN="List",_N="Grep",CN="Shell",EN="ReadLints";function xN(e,t){if("object"==typeof e&&null!==e)return Object.getOwnPropertyDescriptor(e,t)?.value}const PN=new Set([vN,bN,SN,kN,_N,EN]);function RN(e){const t=xN(e,"tool_name"),r=[xN(e,"file_path"),"string"==typeof t&&PN.has(t)?xN(xN(e,"tool_input"),"file_path"):void 0];for(const e of r)if("string"==typeof e&&e.length>0)return e}const IN=(0,l.h)("cli-hooks-executor");function TN(e){try{return(0,xo.statSync)(e).isFile()}catch{return!1}}const AN="\nJSON Parse Error: Error: Failed to parse hook stdout as JSON";function $N(e,t){for(const[r,n]of Object.entries(e))if(r===t)return n}function MN(e,t){const r=$N(e,t);if("string"==typeof r||null===r)return r}class DN{constructor(e,t,r,n,o,s,i,a){this.workspacePath=t,this.globalContext=r,this.shellExecutor=n,this.promptHookClient=o,this.onHookExecution=i,this.options=a,this.sessionEnvById=new Map,this.sessionUserEmailById=new Map,this.activeSessionIdsByConversationId=new Map,this.transcriptParentConversationIdById=new Map,this.configReadyPromises=[],this.config=e,s&&this.addConfigReadyPromise(s)}addConfigReadyPromise(e){this.configReadyPromises.push(e.catch((()=>{})))}reportCommandFailure(e,t){if(void 0!==e)try{e(t)}catch{}}finishHookRun(e,t,r,n){const o=e.transportMode??("prompt"===e.hookType?"prompt":this.getCommandHookPayloadTransportMode());try{this.onHookExecution?.({...e,transportMode:o})}catch{}const s=this.options?.onHookRun;if(void 0===s)return;const i=n.exitCode??e.exitCode,a="spawn_error"===(c=e.errorClass)?"shell_exec_transport_error":"prompt_error"===c?"prompt_execution_error":void 0;var c;try{s({step:e.hookStep,script:t,source:e.hookSource,...void 0===e.pluginId?{}:{pluginId:e.pluginId},request:r,response:n.response??null,status:e.status,durationMs:e.latencyMs,...void 0===i?{}:{exitCode:i},stderr:n.stderr,transportMode:o,configuredTimeoutSec:t.timeout??60,timedOut:!0===e.timedOut,...void 0===a?{}:{failureType:a}})}catch{}}getCommandHookPayloadTransportMode(){return"stdin"===this.options?.commandHookPayloadTransport?"win32"===process.platform?"windows_temp_file":"stdin":"argv_heredoc"}shouldUseCommandHookDirectStdinTransport(){return"stdin"===this.getCommandHookPayloadTransportMode()}async writeCommandHookStdinPayload(e,t){if(!e)throw new Error("Hook stdin transport was requested, but the executor did not provide stdin");try{e.end(Buffer.from(t,"utf8"))}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;if("EPIPE"===t||"ERR_STREAM_DESTROYED"===t||"ERR_STREAM_PREMATURE_CLOSE"===t)return;throw e}try{await(0,ah.finished)(e)}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;if("EPIPE"===t||"ERR_STREAM_DESTROYED"===t||"ERR_STREAM_PREMATURE_CLOSE"===t)return;throw e}}updateConfig(e){this.config=e}beginSessionEnvironment(e,t){this.sessionEnvById.delete(e.sessionId),this.sessionUserEmailById.delete(e.sessionId);const r=this.activeSessionIdsByConversationId.get(e.conversationId)??[];this.activeSessionIdsByConversationId.set(e.conversationId,r.filter((t=>t!==e.sessionId)).concat(e.sessionId));const n=t?.userEmail?.trim()??"";n.length>0&&this.sessionUserEmailById.set(e.sessionId,n)}setSessionUserEmail(e,t){const r=t?.trim()??"";0!==r.length&&this.sessionUserEmailById.set(e.sessionId,r)}setSessionEnvironment(e,t){void 0===t?this.sessionEnv={...this.sessionEnv,...e}:this.sessionEnvById.set(t.sessionId,{...this.sessionEnvById.get(t.sessionId),...e})}clearSessionEnvironment(e){if(void 0===e)this.sessionEnv=void 0;else{this.sessionEnvById.delete(e.sessionId),this.sessionUserEmailById.delete(e.sessionId);const t=(this.activeSessionIdsByConversationId.get(e.conversationId)??[]).filter((t=>t!==e.sessionId));0===t.length?this.activeSessionIdsByConversationId.delete(e.conversationId):this.activeSessionIdsByConversationId.set(e.conversationId,t)}}resolveUserEmail(e){const{conversation_id:t,session_id:r}=e;if(void 0!==r&&this.sessionUserEmailById.has(r))return this.sessionUserEmailById.get(r)??null;if(void 0!==t){const e=this.activeSessionIdsByConversationId.get(t)?.at(-1);if(void 0!==e){const t=this.sessionUserEmailById.get(e);if(void 0!==t)return t}}return this.globalContext.user_email}setTranscriptParentConversationId(e,t){this.transcriptParentConversationIdById.set(e,t)}async getTranscriptPathIfExists(e){try{const t=(0,So.Rv)((0,o.homedir)(),this.workspacePath),r=this.transcriptParentConversationIdById.get(e),n=FF(r?{conversationId:e,kind:"subagent",parentConversationId:r}:{conversationId:e,kind:"primary"}).map((e=>(0,s.join)(t,e)));for(const e of n)try{return await(0,Co.access)(e),e}catch{}return null}catch{return null}}async getSubagentTranscriptPathIfExists(e){const{subagentId:t,parentConversationId:r}=e;try{const e=(0,So.Rv)((0,o.homedir)(),this.workspacePath),n=FF({conversationId:t,kind:"subagent",parentConversationId:r}).map((t=>(0,s.join)(e,t)));for(const e of n)try{return await(0,Co.access)(e),e}catch{}return null}catch{return null}}hasHooksForStep(e){return[this.config.enterpriseHooks,this.config.teamHooks,this.config.userHooks,this.config.projectHooks,this.options?.runtimeHooks,this.config.claudeUserHooks,this.config.claudeProjectHooks,this.config.claudeProjectLocalHooks,...wN(this.config),...(this.config.pluginHooks??[]).map((e=>e.config))].some((t=>{const r=t?.hooks[e];return void 0!==r&&r.length>0}))}hasFailClosedHooksForStep(e,t){const r=[this.config.enterpriseHooks,this.config.teamHooks,this.config.projectHooks,...(this.config.repoHooks??[]).map((e=>e.projectHooks)),this.config.userHooks,this.options?.runtimeHooks];for(const n of r){const r=n?.hooks[e];if(r&&(t?hN(r,t):r).some((e=>!0===e.failClosed)))return!0}for(const r of this.config.pluginHooks??[]){const n=r.config.hooks[e];if(n&&(t?hN(n,t):n).some((e=>mF(e)&&!0===e.failClosed)))return!0}return!1}configuredHookDirectory(e){const t=this.config.configDirs;switch(e){case"enterprise":return t?.enterprise;case"team":return t?.team;case"user":return t?.user;case"claude-user":return t?.claudeUser;default:return}}cwdForHookSource(e,t){if(void 0!==e?.cwd&&e.cwd.length>0)return e.cwd;const r=this.configuredHookDirectory(t.source);if(void 0!==r&&r.length>0)return r;const n=e?.cwdForSource?.(t.source);return void 0!==n&&n.length>0?n:t.fallback}getCwdForSource(e){const t=this.config.configDirs;switch(e){case"enterprise":return t?.enterprise??this.workspacePath;case"team":return t?.team??this.workspacePath;case"project":case"claude-project":case"claude-project-local":case"claude-plugin":case"runtime":default:return this.workspacePath;case"user":return t?.user??this.workspacePath;case"claude-user":return t?.claudeUser??this.workspacePath}}buildHookEnvironment(e){const{transcriptPath:t,sessionId:r,conversationId:n,executionEnv:o}=e,s=this.resolveUserEmail({conversation_id:n,session_id:r});return{CURSOR_PROJECT_DIR:this.workspacePath,CURSOR_VERSION:this.globalContext.cursor_version,...s&&{CURSOR_USER_EMAIL:s},...t&&{CURSOR_TRANSCRIPT_PATH:t},CLAUDE_PROJECT_DIR:this.workspacePath,...this.sessionEnv,...void 0!==r?this.sessionEnvById.get(r):void 0,...o}}shouldSkipHookDueToLoopLimit(e,t,r){if("stop"!==e&&"subagentStop"!==e)return!1;const n=$N(r,"loop_count");if("number"!=typeof n)return!1;const o=n,s=t.loop_limit;return null!==s&&(void 0===s?o>=5:o>=s)}async executeHookForStep(e,t,r){this.configReadyPromises.length>0&&await this.whenConfigReady();const n=function(e){return vF.includes(e)}(e),o=t,i=n?null:o.conversation_id?await this.getTranscriptPathIfExists(o.conversation_id):null;let a;if(e===xd.subagentStop){const e=MN(t,"subagent_id"),r=MN(t,"parent_conversation_id");a=e?await this.getSubagentTranscriptPathIfExists({subagentId:e,parentConversationId:r??void 0}):null}const c=n?void 0:o.session_id??o.conversation_id,l={...t,...void 0!==c&&{session_id:c},hook_event_name:e,cursor_version:this.globalContext.cursor_version,workspace_roots:[...new Set([this.workspacePath,...(this.config.repoHooks??[]).map((e=>e.repoPath))])],user_email:this.resolveUserEmail(o),...!n&&{transcript_path:i},...e===xd.subagentStop&&{agent_transcript_path:a??null}},u=function(e,t){switch(e){case"beforeShellExecution":case"afterShellExecution":return dN(t,"command");case"beforeMCPExecution":case"afterMCPExecution":{const e=dN(t,"tool_name");return e?`MCP:${e}`:void 0}case"beforeReadFile":return"Read";case"afterFileEdit":return"Write";case"beforeTabFileRead":return"TabRead";case"afterTabFileEdit":return"TabWrite";case"beforeSubmitPrompt":return"UserPromptSubmit";case"stop":return"Stop";case"afterAgentResponse":return"AgentResponse";case"afterAgentThought":return"AgentThought";case"subagentStart":case"subagentStop":return dN(t,"subagent_type");case"preToolUse":case"postToolUse":case"postToolUseFailure":return dN(t,"tool_name");default:return}}(e,l),d=[],h=(e,t,n)=>{if(!e)return;const o=hN(e,u),s=this.cwdForHookSource(r,{source:t,fallback:n??this.getCwdForSource(t)}),i=void 0===n?r?.env:{CURSOR_PROJECT_DIR:n,CLAUDE_PROJECT_DIR:n,...r?.env};for(const e of o)fF(e)?this.promptHookClient&&d.push({type:"prompt",script:e,source:t}):mF(e)&&d.push({type:"command",script:e,cwd:s,env:i,source:t})},p=await async function({repoHooks:e,targetPath:t,workspacePath:r}){if(e.length<2||void 0===t||0===t.length)return e;const n=(0,Yo.o1)(t,r),[o,i,a]=await Promise.all([(0,Yo.DN)(n),(0,Yo.DN)(s.default.dirname(n)),Promise.all(e.map((async e=>await(0,Yo.DN)(e.repoPath)??s.default.resolve(e.repoPath))))]);if(null===o||null===i)return e;const c=t=>{let r;return e.forEach(((e,n)=>{const o=a[n],i=s.default.relative(o,t);(""===i||".."!==i&&!i.startsWith(`..${s.default.sep}`)&&!s.default.isAbsolute(i))&&(void 0===r||o.length>r.repoPath.length)&&(r={repo:e,repoPath:o})})),r?.repo},l=new Set;for(const t of[o,s.default.join(i,s.default.basename(n))]){const r=c(t);if(void 0===r)return e;l.add(r)}return e.filter((e=>l.has(e)))}({repoHooks:this.config.repoHooks??[],targetPath:RN(t),workspacePath:this.workspacePath});h(this.config.enterpriseHooks?.hooks[e],"enterprise"),h(this.config.teamHooks?.hooks[e],"team"),h(this.config.projectHooks?.hooks[e],"project");for(const t of p)h(t.projectHooks?.hooks[e],"project",t.repoPath);h(this.config.userHooks?.hooks[e],"user"),h(this.options?.runtimeHooks?.hooks[e],"runtime"),h(this.config.claudeProjectLocalHooks?.hooks[e],"claude-project-local"),h(this.config.claudeProjectHooks?.hooks[e],"claude-project");for(const t of p)h(t.claudeProjectLocalHooks?.hooks[e],"claude-project-local",t.repoPath),h(t.claudeProjectHooks?.hooks[e],"claude-project",t.repoPath);h(this.config.claudeUserHooks?.hooks[e],"claude-user");for(const t of this.config.pluginHooks??[]){const n=t.config.hooks[e];if(!n?.length)continue;const o=r?.cwd??(e===xd.stop||e===xd.subagentStop?this.workspacePath:t.installPath),s={...void 0!==t.plugin&&{plugin:t.plugin},...void 0!==t.marketplace&&{marketplace:t.marketplace},...void 0!==t.pluginId&&{pluginId:t.pluginId},...void 0!==t.marketplaceId&&{marketplaceId:t.marketplaceId}};for(const e of hN(n,u))mF(e)&&d.push({type:"command",script:e,cwd:o,env:r?.env,source:"claude-plugin",attribution:s,pluginInstallPath:t.installPath})}if(0!==d.length)return this.executeAllAndMerge(e,d,l,r?.onCommandFailure)}async whenConfigReady(){await Promise.all(this.configReadyPromises)}async executeAllAndMerge(e,t,r,n){let o;const s=()=>o??=function(e){const t=JSON.stringify(e);return{json:t,payloadSizeBytes:Buffer.byteLength(t,"utf8")}}(r),i=t.map((async(t,o)=>{const{source:i,attribution:a}=t;try{return"prompt"===t.type?await this.executePromptHook(e,t.script,r,i,o,s,a):await this.executeCommandHook(e,t.script,t.cwd,t.env,r,i,o,s,a,t.pluginInstallPath,n)}catch(r){const n=r instanceof Error?r.message:String(r);if(!0===t.script.failClosed){const t=pN(`Hook execution failed: ${n}`),r=EF(e,t);if(r)return{success:!0,data:r,source:i,index:o}}return IN.warn((0,y.q6)(),`${e} hook error`,{source:i,index:o,error:n}),{success:!1,source:i,index:o}}})),a=await Promise.all(i),c=[];for(const e of a)e.success&&void 0!==e.data&&c.push(e.data);return function(e,t){if(0===t.length)return;const[r]=t;if(!(1!==t.length||Id(n=r)&&Id(n.updated_input)&&0===Object.keys(n.updated_input).length))return r;var n;const o=yF.includes(e),s=e===xd.sessionStart,i=e===xd.workspaceOpen,a=pF.has(e),c={};for(const e of t){const t=e;for(const[e,r]of Object.entries(t))if(void 0!==r)if(i&&"pluginPaths"===e&&Array.isArray(r)){const t=c[e],n=Array.isArray(t)?t:[],o=new Set(n),s=[...n];for(const e of r)"string"!=typeof e||o.has(e)||(o.add(e),s.push(e));c[e]=s}else"permission"===e&&o?c[e]=(u=r,"deny"===(l=c[e])||"deny"===u?"deny":"ask"===l||"ask"===u?"ask":"allow"===l||"allow"===u?"allow":void 0):"user_message"!==e&&"agent_message"!==e?"updated_input"!==e?a&&"additional_context"===e&&"string"==typeof r?c[e]=bF(c[e],r):"continue"!==e||"boolean"!=typeof r?c[e]=s&&"env"===e&&"object"==typeof r&&null!==r?SF(c[e],r):r:void 0===c[e]?c[e]=r:c[e]=c[e]&&r:void 0===c[e]&&Id(r)&&Object.keys(r).length>0&&(c[e]=r):c[e]=bF(c[e],r)}var l,u;return c}(e,c)}async executeCommandHook(e,t,r,n,o,s,i,a,c,l,u){if(this.shouldSkipHookDueToLoopLimit(e,t,o))return{success:!1,source:s,index:i};const d=Date.now(),h=a(),p=h.payloadSizeBytes,f=(e,r)=>this.finishHookRun(e,t,o,r);let m;try{m=await this.executeCommandScript({script:t,cwd:r,request:o,jsonPayload:h.json,env:n,...void 0!==l&&{pluginInstallPath:l}})}catch(r){const n=r instanceof Error?r.message:String(r),o=n.toLowerCase().includes("timed out");this.reportCommandFailure(u,{command:t.command,source:s,exitCode:null,stderr:"",errorMessage:n});const a=Date.now()-d,l=o?"timeout":"spawn_error";if(!0===t.failClosed){const u=EF(e,pN(`Hook "${t.command}" execution failed: ${n}`));if(u)return f({hookStep:e,hookSource:s,hookType:"command",status:o?"timeout":"blocked",latencyMs:a,payloadSizeBytes:p,errorClass:l,failClosed:!0,timedOut:o,...c},{response:null,stderr:String(r)}),{success:!0,data:u,source:s,index:i}}return f({hookStep:e,hookSource:s,hookType:"command",status:o?"timeout":"failed",latencyMs:a,payloadSizeBytes:p,errorClass:l,failClosed:!0===t.failClosed,timedOut:o,...c},{response:null,stderr:String(r)}),{success:!1,source:s,index:i}}if(2===m.exitCode){const r=function(e,t,r){const n=e.trim(),o=t.trim();return n||(o?`Hook blocked with message: ${o}`:`Hook "${r}" blocked this action (exit code 2) but provided no reason.`)}(m.stdout,m.stderr,t.command),n=EF(e,r);return n?(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,failClosed:!0===t.failClosed,exitCode:m.exitCode,...c},{response:n,stderr:m.stderr}),{success:!0,data:n,source:s,index:i}):(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,failClosed:!0===t.failClosed,exitCode:m.exitCode,...c},{response:null,stderr:m.stderr}),{success:!1,source:s,index:i})}if(0!==m.exitCode&&null!==m.exitCode){if(this.reportCommandFailure(u,{command:t.command,source:s,exitCode:m.exitCode,stderr:m.stderr}),!0===t.failClosed){const r=EF(e,pN(`Hook "${t.command}" failed with exit code ${m.exitCode}${m.stderr?`: ${m.stderr.trim()}`:""}`));if(r)return f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"exit_nonzero",failClosed:!0,exitCode:m.exitCode,...c},{response:null,stderr:m.stderr}),{success:!0,data:r,source:s,index:i}}return f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"exit_nonzero",failClosed:!0===t.failClosed,exitCode:m.exitCode,...c},{response:null,stderr:m.stderr}),{success:!1,source:s,index:i}}const g=m.stdout.trim();if(!g){if(!0===t.failClosed){const r=EF(e,pN(`Hook "${t.command}" returned no output.`));if(r)return f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"empty_stdout",failClosed:!0,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr}),{success:!0,data:r,source:s,index:i}}return f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"empty_stdout",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr}),{success:!1,source:s,index:i}}const w=function(e){const t=e.trim();if(0===t.length)return;const r=xF(t);if(void 0!==r)return r.value;if(t.endsWith("}"))for(let e=t.length-1;e>=0;e--){if("{"!==t[e])continue;const r=xF(t.slice(e));if(void 0!==r)return r.value}}(g);if(void 0===w){const r=_F({step:e,command:t.command,failClosed:!0===t.failClosed,kind:"invalid_json"});return r.blockResponse?(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_json",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr+AN}),{success:!0,data:r.blockResponse,source:s,index:i}):(f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_json",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr+AN}),{success:!1,source:s,index:i})}const y=wF(e,w,{enableClaudeNestedHookSpecificOutputCompatibility:this.options?.enableClaudeNestedHookSpecificOutputCompatibility});if(y.success&&null!=y.data){const r=y.data,n="object"==typeof r&&"permission"in r?r.permission:void 0;return f({hookStep:e,hookSource:s,hookType:"command",status:"deny"===n||"ask"===n?"blocked":"success",latencyMs:m.duration,payloadSizeBytes:p,failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:r,stderr:m.stderr}),{success:!0,data:r,source:s,index:i}}const v=_F({step:e,command:t.command,failClosed:!0===t.failClosed,kind:"invalid_response"});return v.blockResponse?(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_response",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:w,stderr:m.stderr}),{success:!0,data:v.blockResponse,source:s,index:i}):(f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_response",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:w,stderr:m.stderr}),{success:!1,source:s,index:i})}async executePromptHook(e,t,r,n,o,s,i){if(this.shouldSkipHookDueToLoopLimit(e,t,r))return{success:!1,source:n,index:o};if(!this.promptHookClient)return{success:!1,source:n,index:o};const a=1e3*(t.timeout??60),c=Date.now(),l=s(),u=l.payloadSizeBytes,d=(e,n)=>this.finishHookRun(e,t,r,n),h=(0,y.q6)(),[p,f]=h.withTimeoutAndCancel(a);try{const r=JSON.parse(l.json),s=await this.promptHookClient.evaluatePromptHook(p,{prompt:t.prompt,hookInputJson:r,modelName:t.model});if(s.ok){const r=function(e){return kF(e)?CF(0,{permission:"allow"}):e===xd.beforeSubmitPrompt||e===xd.sessionStart?CF(0,{continue:!0}):e===xd.stop?CF(0,{}):void 0}(e);return d({hookStep:e,hookSource:n,hookType:"prompt",status:"success",latencyMs:Date.now()-c,payloadSizeBytes:u,failClosed:!0===t.failClosed,...i},{response:r,stderr:"",exitCode:0}),r?{success:!0,data:r,source:n,index:o}:{success:!1,source:n,index:o}}{const r=EF(e,s.reason??"Prompt hook blocked this action");return d({hookStep:e,hookSource:n,hookType:"prompt",status:"blocked",latencyMs:Date.now()-c,payloadSizeBytes:u,failClosed:!0===t.failClosed,...i},{response:r,stderr:"",exitCode:2}),r?{success:!0,data:r,source:n,index:o}:{success:!1,source:n,index:o}}}catch(r){const s=r instanceof Error?r.message:String(r),a=s.toLowerCase().includes("abort")||s.toLowerCase().includes("timed out"),l=a?"timeout":"prompt_error";if(!0===t.failClosed){const t=EF(e,pN(`Prompt hook failed: ${s}`));if(t)return d({hookStep:e,hookSource:n,hookType:"prompt",status:a?"timeout":"blocked",latencyMs:Date.now()-c,payloadSizeBytes:u,errorClass:l,failClosed:!0,timedOut:a,...i},{response:null,stderr:String(r)}),{success:!0,data:t,source:n,index:o}}return d({hookStep:e,hookSource:n,hookType:"prompt",status:a?"timeout":"failed",latencyMs:Date.now()-c,payloadSizeBytes:u,errorClass:l,failClosed:!0===t.failClosed,timedOut:a,...i},{response:null,stderr:String(r)}),{success:!1,source:n,index:o}}finally{f()}}async executeCommandScript(e){const{script:t,cwd:r,request:n,env:i,pluginInstallPath:a,jsonPayload:c}=e,l=1e3*(t.timeout??60),u=Date.now();let d;const h=new AbortController,p=setTimeout((()=>{h.abort()}),l);try{const e="win32"===process.platform,f=this.getCommandHookPayloadTransportMode(),m=this.shouldUseCommandHookDirectStdinTransport(),g=e?function(e,t){const r=function(e){let t=0;for(;t0&&!/^\s/.test(i))return e;if(/[$`{}()|;,<>]/.test(s)||""===o&&/['"]/.test(s))return e;const a=s.slice(Math.max(s.lastIndexOf("\\"),s.lastIndexOf("/"))+1);if(0===a.length||a.includes("."))return e;const c="'"===o?s.replace(/''/g,"'"):s,l=/^[A-Za-z]:[\\/]/.test(u=c)||u.startsWith("\\")||u.startsWith("/")?c:`${t.cwd.replace(/[\\/]+$/,"")}\\${c}`;var u;const d=nF.find((e=>t.isFile(l+e)));return void 0===d?e:""!==o?`${n}${o}${s}${d}${o}${i}`:`${n}'${s}${d}'${i}`}(t.command,{cwd:r,isFile:TN}):t.command;let w;if(m)w=e?oF(g):g;else if("windows_temp_file"===f){d=await(0,Co.mkdtemp)((0,s.join)((0,o.tmpdir)(),"cursor-hooks-"));const e=(0,s.join)(d,"payload.json");await(0,Co.writeFile)(e,c,{encoding:"utf8",flag:"wx"}),w=function(e,t){return`$OutputEncoding = [System.Text.UTF8Encoding]::new($false); try { $global:cursorHookConsoleInputEncoding = [Console]::InputEncoding; $null = Register-EngineEvent -SourceIdentifier PowerShell.Exiting -Action { try { [Console]::InputEncoding = $global:cursorHookConsoleInputEncoding } catch { } }; [Console]::InputEncoding = $OutputEncoding } catch { }; Get-Content -LiteralPath '${e.replace(/'/g,"''")}' -Raw -Encoding UTF8 | & { $input | ${oF(t)} }`+rF(t)}(e,g)}else w=e?`@'\n${c.replace(/'/g,"''")}\n'@ | & ${g}`+rF(g):`${t.command} <<'CURSOR_HOOK_EOF'\n${c}\nCURSOR_HOOK_EOF`;const v=MN(n,"conversation_id")??void 0,b=MN(n,"session_id")??void 0,S=MN(n,"transcript_path"),k=void 0===v?void 0:this.activeSessionIdsByConversationId.get(v),_=void 0===b||b===v&&!this.sessionEnvById.has(b)?void 0===v?void 0:k?.at(-1)??v:b,C=this.buildHookEnvironment({transcriptPath:S,sessionId:_,conversationId:v,executionEnv:i}),E={};for(const[e,t]of Object.entries(C))void 0!==t&&(E[e]=t);void 0!==a&&(E.CURSOR_PLUGIN_ROOT=a,E.CLAUDE_PLUGIN_ROOT=a);const x=(0,y.q6)(),P=new ia.StringDecoder("utf8"),R=new ia.StringDecoder("utf8");let I,T="",A="",$=null,M=!1;for await(const e of this.shellExecutor.execute(x,w,{workingDirectory:r,signal:h.signal,sandboxPolicy:{perUser:{type:"insecure_none"}},env:E,pipeStdin:m}))switch(e.type){case"stdin_ready":m&&(await this.writeCommandHookStdinPayload(e.stdin,c),M=!0);break;case"stdout":T+=P.write(e.data);break;case"stderr":A+=R.write(e.data);break;case"exit":$=e.code,I=e.aborted}if(T+=P.end(),A+=R.end(),m&&!M)throw new Error("Hook stdin transport was requested, but the executor did not signal stdin readiness");clearTimeout(p);const D=Date.now()-u;if(I??h.signal.aborted)throw new Error(`Hook script timed out after ${l}ms`);return{stdout:T,stderr:A,exitCode:$,duration:D}}catch(e){if(clearTimeout(p),Date.now(),h.signal.aborted)throw new Error(`Hook script timed out after ${l}ms`);throw e}finally{if(d)try{await(0,Co.rm)(d,{recursive:!0,force:!0})}catch{}}}}class ON{constructor(e){this.config=e,this.configuredSteps=yN.getConfiguredSteps(e)}getConfig(){return this.config}hasHookForStep(e){return this.configuredSteps.has(e)}getConfiguredSteps(){return new Set(this.configuredSteps)}}var FN=r("node:perf_hooks");const NN=(0,y.cF)(Symbol.for("@anysphere/agent-exec/toolCallHooks"),{kind:"none"});function LN(e){return"inExecute"!==e.get(NN).kind}function jN(e,t){const r=e.get(NN);return"inExecute"!==r.kind||!r.toolStepsInPreToolUse.includes(t)}(0,y.cF)(Symbol.for("@anysphere/agent-exec/hookAsk"),void 0),(0,y.cF)(Symbol.for("@anysphere/agent-exec/hookAllow"),void 0),new WeakMap,new WeakMap,(0,y.cF)(Symbol.for("@anysphere/agent-exec/toolCallRefusal"),void 0),new WeakMap,new WeakMap,new WeakMap,(0,y.cF)(Symbol.for("@anysphere/agent-exec/approvalWaits"),void 0),new WeakMap;const UN=(0,y.cF)(Symbol.for("@anysphere/agent-exec/hookStepTime"),void 0),BN=new yd.AsyncLocalStorage;function WN(e,t){return BN.run(e,t)}function HN(e,t){void 0!==e&&t.length>0&&e.push(...t)}class qN extends Error{constructor(e){super(`Hook additional_context for ${e.hookEventName} is ${e.actualLength} chars (max ${e.maxLength}).`),this.name="HookAdditionalContextTooLargeError",this.hookEventName=e.hookEventName,this.actualLength=e.actualLength,this.maxLength=e.maxLength}}var zN=r("../proto/dist/generated/agent/v1/hook_additional_context_pb.js");function GN({hookEventName:e,additionalContext:t}){const r=function(e){const t=e?.trim();return void 0!==t&&t.length>0?t:void 0}(t);if(void 0===r)return[];if(r.length>1e4)throw new qN({hookEventName:e,actualLength:r.length,maxLength:1e4});return[new zN.C({hookEventName:e,content:r})]}Object.fromEntries(Array.from(pF).map((e=>{if(!function(e){return e===xd.sessionStart||e===xd.beforeSubmitPrompt||e===xd.preToolUse||e===xd.postToolUse||e===xd.postToolUseFailure}(e))throw new Error(`HOOK_STEPS_SUPPORTING_ADDITIONAL_CONTEXT lists ${e} but HookStepAdditionalContextEventName does not include it. Extend the Extract<> union in spec.ts.`);return[e,{hookEventName:e}]})));const VN="Agent note: Do not suggest workarounds to the blocked tool.";function KN(e){return e.includes(VN)?e:`${e}\n\n${VN}`}class JN extends Error{constructor(e){super(`Hook denied: ${e}`),this.failureType="permission_denied",this.name="HookDeniedError",this.reason=e}}class ZN extends Error{constructor(e,t){super(`Hook failed (fail-closed): ${e}`),this.failureType="error",this.name="FailClosedError",this.reason=e,this.cause=t}}const XN="To view or modify configured hooks, go to Cursor Settings > Hooks.";function QN(e,t){return KN(`${t?`${e} was blocked by a hook: ${t}`:`${e} was blocked by a hook.`}\n\n${XN}`)}function YN(e){return function(e){return e instanceof JN}(e)||function(e){return e instanceof ZN}(e)}const eL=(0,l.h)("generic-hooks");function tL(e,t,r,n){try{return GN({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof qN)return eL.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}const rL=e=>Math.round(1e3*e)/1e3;function nL(e,t,r,n,o,s){const i=n(e),a=o.getToolCallId?.(t)??(0,bo.randomUUID)(),c=o.getExtraHookFields?.(t)??{},l={baseHookRequest:i,toolUseId:a,toolInput:o.createToolInput(t),extraHookFields:c,hookContextCollector:s?.hookContextCollector??o.getHookContextCollector?.(t)??[]},u=function(e,t,r,n){let{toolInput:o,extraHookFields:s,hookContextCollector:i}=n;const{baseHookRequest:a,toolUseId:c}=n;return{fireFailureAsync:async(n,l,u,d=!1)=>{try{const h=await WN(e.signal,(()=>t.executeHookForStep(xd.postToolUseFailure,{...a,tool_name:r,tool_input:o,error_message:l,failure_type:u,duration:n,tool_use_id:c,is_interrupt:d,...s})));HN(i,tL(e,r,xd.postToolUseFailure,h?.additional_context))}catch(t){eL.warn(e,"postToolUseFailure hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}},fireSuccessAsync:async(n,l)=>{try{const u=await WN(e.signal,(()=>t.executeHookForStep(xd.postToolUse,{...a,tool_name:r,tool_input:o,tool_output:l,duration:n,tool_use_id:c,...s})));HN(i,tL(e,r,xd.postToolUse,u?.additional_context))}catch(t){eL.warn(e,"postToolUse hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}},getToolInput:()=>o,setToolInput:e=>{o=e},setExtraHookFields:e=>{s=e,n.extraHookFields=e}}}(e,r,o.toolName,l);return{hookContext:l,helpers:u}}async function oL(e,t,r,n,o,s,i,a){const{baseHookRequest:c,toolUseId:l,extraHookFields:u}=n;try{const a=await WN(e.signal,(()=>r.executeHookForStep(xd.preToolUse,{...c,tool_name:s.toolName,tool_input:o.getToolInput(),tool_use_id:l,...u})));if("deny"===a?.permission){const r=a.user_message||`${s.toolName} blocked by preToolUse hook`,c=KN(r);try{HN(n.hookContextCollector,GN({hookEventName:xd.preToolUse,additionalContext:a.additional_context}))}catch(t){if(!(t instanceof qN))throw t;eL.warn(e,"preToolUse deny additional_context exceeded max size; dropping carrier",{toolName:s.toolName,actualLength:t.actualLength,maxLength:t.maxLength})}return await o.fireFailureAsync(0,r,"permission_denied"),{type:"rejected",result:i(t,c),reason:c}}a?.updated_input&&s.applyUpdatedInput&&(s.applyUpdatedInput(t,a.updated_input),o.setToolInput(s.createToolInput(t)),s.getExtraHookFields&&o.setExtraHookFields(s.getExtraHookFields(t))),HN(n.hookContextCollector,GN({hookEventName:xd.preToolUse,additionalContext:a?.additional_context}))}catch(n){const a=r.hasFailClosedHooksForStep?.(xd.preToolUse,s.toolName)??!1,c=n instanceof qN;if(a){const e=pN(`${c?"preToolUse additional_context exceeded max size":"preToolUse hook failed"}: ${n instanceof Error?n.message:"preToolUse hook error"}`);return await o.fireFailureAsync(0,e,"error"),{type:"rejected",result:i(t,e),reason:e}}eL.warn(e,c?"preToolUse additional_context exceeded max size; dropping carrier":"preToolUse hook error",{toolName:s.toolName,error:n instanceof Error?n.message:String(n),...c?{actualLength:n.actualLength,maxLength:n.maxLength}:{}})}if(a)try{const s=await a({ctx:e,args:t,baseHookRequest:c,hookExecutor:r,toolInput:o.getToolInput(),toolUseId:l,extraHookFields:n.extraHookFields});if(void 0!==s){const e="Pre-execution hook returned rejection";return await o.fireFailureAsync(0,e,"permission_denied"),{type:"rejected",result:s,reason:e}}}catch(e){if(YN(e))return await o.fireFailureAsync(0,e.reason,e.failureType),{type:"rejected",result:i(t,e.reason),reason:e.reason};throw e}return{type:"continue"}}function sL(e){return e.toolCallId}function iL(e,t,r,n){return{async execute(o,s,i){const a=cL(o,t),{hookContext:c,helpers:l}=nL(o,s,a,r,n,i);let u;try{u=await oL(o,s,a,c,l,n,n.createRejectedResult,n.runPreExecutionHooks)}catch(e){throw n.runCleanup?.(c.toolUseId),e}if("rejected"===u.type)return n.runCleanup?.(c.toolUseId),u.result;const d=FN.performance.now();try{const t=await e.execute(o,s,i),r=rL(FN.performance.now()-d);if(n.runPostExecutionHooks)try{const e=await n.runPostExecutionHooks({ctx:o,args:s,result:t,baseHookRequest:c.baseHookRequest,hookExecutor:a,toolInput:l.getToolInput(),toolUseId:c.toolUseId,executionDurationMs:r,extraHookFields:c.extraHookFields});if(void 0!==e)return await l.fireSuccessAsync(r,JSON.stringify(n.createSuccessOutput(s,e))),n.runCleanup?.(c.toolUseId),e}catch(e){if(YN(e))return await l.fireFailureAsync(r,e.reason,e.failureType),n.runCleanup?.(c.toolUseId),n.createRejectedResult(s,e.reason);eL.warn(o,"postExecutionHooks error",{toolName:n.toolName,error:e instanceof Error?e.message:String(e)})}return n.isSuccess(t)?await l.fireSuccessAsync(r,JSON.stringify(n.createSuccessOutput(s,t))):await l.fireFailureAsync(r,n.getErrorMessage(t),n.getFailureType?.(t)??"error",n.isInterrupt?.(t)??!1),n.runCleanup?.(c.toolUseId),t}catch(e){const t=rL(FN.performance.now()-d);throw await l.fireFailureAsync(t,e instanceof Error?e.message:String(e),"error"),n.runCleanup?.(c.toolUseId),e}}}}function*aL(e,t){const r=t.hookContextCollector;e.createHookContextEvent&&void 0!==r&&0!==r.length&&(yield e.createHookContextEvent(r))}function cL(e,t){const r=LN(e),n=e.get(UN);if(r&&void 0===n)return t;const o=e=>n?.during(e)??e;return{executeHookForStep:async(e,n)=>{if(r||!function(e){return e===xd.preToolUse||e===xd.postToolUse||e===xd.postToolUseFailure}(e))return o(t.executeHookForStep(e,n));await o(t.whenConfigReady())},hasFailClosedHooksForStep:(e,r)=>t.hasFailClosedHooksForStep?.(e,r)??!1,hasHooksForStep:e=>t.hasHooksForStep?.(e)??!0,whenConfigReady:()=>o(t.whenConfigReady())}}function lL(e){if("object"!=typeof e||null===e||!("code"in e))return!1;const t=e.code;return"ENOENT"===t||"ENOTDIR"===t}class uL{async readFile(e){try{return await Co.readFile(e,"utf-8")}catch(e){if("ENOENT"===e?.code)return;throw e}}async exists(e){try{return await Co.access(e),!0}catch{return!1}}async pathContainsSymlink(e,t){return async function(e,t){const r=function(e,t){const r=s.default.resolve(e),n=s.default.resolve(t),o=s.default.relative(n,r);if(0===o.length||".."===o||o.startsWith(`..${s.default.sep}`)||s.default.isAbsolute(o))return"unsafe";const i=o.split(s.default.sep).filter((e=>e.length>0)),a=[];let c=n;for(const e of i)c=s.default.join(c,e),a.push(c);return a}(e,t);if("unsafe"===r)return!0;for(const e of r)try{if((await(0,Co.lstat)(e)).isSymbolicLink())return!0}catch(e){if(lL(e))return!0;throw e}return!1}(e,t)}}var dL=r("../proto/dist/generated/agent/v1/hooks_pb.js");const hL=q("hook-executor",(e=>new B(e,Z("executeHookArgs"),X("executeHookResult"))),((e,t)=>{t.register(new I(e,Y("executeHookArgs"),Q("executeHookResult")))})),pL=new Set(Object.values(xd));function fL(e){switch(e){case"completed":case"aborted":case"error":return e;default:return"error"}}function mL(e){switch(e){case"error":case"timeout":case"permission_denied":return e;default:return"error"}}function gL(e){const t=e?.toJson();return"object"!=typeof t||null===t||Array.isArray(t)?{}:t}class wL{constructor(e){this.hookExecutor=e}hasFailClosedHooksForStep(e,t){return!!function(e){return pL.has(e)}(e)&&(this.hookExecutor.hasFailClosedHooksForStep?.(e,t)??!1)}async execute(e,t){const r=t.request;if(!r)return new d.S1({response:void 0});switch(r.request.case){case"preCompact":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...hF(e),trigger:"manual"===e.trigger?"manual":"auto",context_usage_percent:e.contextUsagePercent,context_tokens:Number(e.contextTokens),context_window_size:Number(e.contextWindowSize),message_count:e.messageCount,messages_to_compact:e.messagesToCompact,is_first_compaction:e.isFirstCompaction},n=await this.hookExecutor.executeHookForStep(xd.preCompact,t);return new d.S1({response:new d.w5({response:{case:"preCompact",value:new dL.$_({userMessage:n?.user_message})}})})}case"subagentStart":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...hF(e),subagent_id:e.subagentId,subagent_type:e.subagentType,task:e.task,parent_conversation_id:e.parentConversationId,tool_call_id:e.toolCallId,subagent_model:e.subagentModel,is_parallel_worker:e.isParallelWorker,git_branch:e.gitBranch},n=await this.hookExecutor.executeHookForStep(xd.subagentStart,t);return new d.S1({response:new d.w5({response:{case:"subagentStart",value:new dL.W0({permission:n?.permission,userMessage:n?.user_message,additionalContext:n?.additional_context})}})})}case"subagentStop":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...hF(e),subagent_id:e.subagentId,subagent_type:e.subagentType,status:fL(e.status),duration_ms:Number(e.durationMs),summary:e.summary,parent_conversation_id:e.parentConversationId,message_count:e.messageCount,tool_call_count:e.toolCallCount,error_message:e.errorMessage,modified_files:e.modifiedFiles,git_branch:e.gitBranch,loop_count:e.loopCount??0,task:e.task,description:e.description,...e.childConversationId?{child_conversation_id:e.childConversationId}:{}},n=await this.hookExecutor.executeHookForStep(xd.subagentStop,t);return new d.S1({response:new d.w5({response:{case:"subagentStop",value:new dL.AH({followupMessage:n?.followup_message,additionalContext:n?.additional_context})}})})}case"beforeSubmitPrompt":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(xd.beforeSubmitPrompt,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...hF(e),prompt:e.prompt,attachments:(n=e.attachments,n.flatMap((e=>"file"===e.type||"rule"===e.type?[{type:e.type,file_path:e.filePath}]:[]))),composer_mode:e.composerMode});return new d.S1({response:new d.w5({response:{case:"beforeSubmitPrompt",value:new dL.u1({continue:t?.continue,userMessage:t?.user_message,additionalContext:t?.additional_context})}})})}case"afterAgentResponse":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(xd.afterAgentResponse,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...hF(e),text:e.text,input_tokens:void 0!==e.inputTokens?Number(e.inputTokens):void 0,output_tokens:void 0!==e.outputTokens?Number(e.outputTokens):void 0,cache_read_tokens:void 0!==e.cacheReadTokens?Number(e.cacheReadTokens):void 0,cache_write_tokens:void 0!==e.cacheWriteTokens?Number(e.cacheWriteTokens):void 0}),new d.S1({response:new d.w5({response:{case:"afterAgentResponse",value:new dL.FW}})})}case"afterAgentThought":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(xd.afterAgentThought,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...hF(e),text:e.text,duration_ms:void 0!==e.durationMs?Number(e.durationMs):void 0}),new d.S1({response:new d.w5({response:{case:"afterAgentThought",value:new dL.H}})})}case"stop":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(xd.stop,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...hF(e),status:fL(e.status),loop_count:e.loopCount,input_tokens:void 0!==e.inputTokens?Number(e.inputTokens):void 0,output_tokens:void 0!==e.outputTokens?Number(e.outputTokens):void 0,cache_read_tokens:void 0!==e.cacheReadTokens?Number(e.cacheReadTokens):void 0,cache_write_tokens:void 0!==e.cacheWriteTokens?Number(e.cacheWriteTokens):void 0});return new d.S1({response:new d.w5({response:{case:"stop",value:new dL.rT({followupMessage:t?.followup_message})}})})}case"preToolUse":{if(!LN(e))return this.skipToolUseStep();const t=r.request.value,n=gL(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...hF(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,tool_use_id:t.toolUseId,cwd:t.cwd},s=await this.hookExecutor.executeHookForStep(xd.preToolUse,o);return new d.S1({response:new d.w5({response:{case:"preToolUse",value:new dL.Wn({permission:s?.permission,userMessage:s?.user_message,agentMessage:s?.agent_message,updatedInput:s?.updated_input?JSON.stringify(s.updated_input):void 0,additionalContext:s?.additional_context})}})})}case"postToolUse":{if(!LN(e))return this.skipToolUseStep();const t=r.request.value,n=gL(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...hF(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,tool_output:t.toolOutput,duration:Number(t.durationMs),tool_use_id:t.toolUseId,cwd:t.cwd},s=await this.hookExecutor.executeHookForStep(xd.postToolUse,o);return new d.S1({response:new d.w5({response:{case:"postToolUse",value:new dL.uB({additionalContext:s?.additional_context,updatedMcpToolOutput:void 0===s?.updated_mcp_tool_output?void 0:JSON.stringify(s.updated_mcp_tool_output)})}})})}case"postToolUseFailure":{if(!LN(e))return this.skipToolUseStep();const t=r.request.value,n=gL(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...hF(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,error_message:t.errorMessage,failure_type:mL(t.failureType),duration:Number(t.durationMs),tool_use_id:t.toolUseId,is_interrupt:t.isInterrupt},s=await this.hookExecutor.executeHookForStep(xd.postToolUseFailure,o);return new d.S1({response:new d.w5({response:{case:"postToolUseFailure",value:new dL.U1({additionalContext:s?.additional_context})}})})}default:return new d.S1({response:void 0})}var n}async skipToolUseStep(){return await this.hookExecutor.whenConfigReady(),new d.S1({response:void 0})}}class yL{constructor(e,t,r,n){this.innerExecutor=e,this.hooksAdditionalContextPromise=t,this.teamHooksReadyPromise=r,this.hooksConfigLease=n}async execute(e,t,r){this.teamHooksReadyPromise&&await this.teamHooksReadyPromise;const n=await this.innerExecutor.execute(e,t,r),o=await this.hooksAdditionalContextPromise,s=this.hooksConfigLease?new Dr.Jy({configuredSteps:Array.from(this.hooksConfigLease.getConfiguredSteps())}):void 0;if("success"===n.result.case&&(o||s)){const e=n.result.value.requestContext,t=e?.clone()??new Dr.bb;return o&&(t.hooksAdditionalContext=o),s&&(t.hooksConfig=s),new Dr._G({result:{case:"success",value:new Dr.yW({requestContext:t,servedFromDiskCache:n.result.value.servedFromDiskCache})}})}return n}}function vL(e){return!!e&&e.type!==os.vc.INSECURE_NONE&&e.type!==os.vc.UNSPECIFIED}async function bL({hookExecutor:e,baseHookRequest:t,toolUseId:r,command:n,cwd:o,sandbox:s}){const i=await e.executeHookForStep(xd.beforeShellExecution,{...t,command:n,cwd:o,sandbox:s,tool_use_id:r});if("deny"===i?.permission){const e=QN("Command execution",i.user_message);throw new JN(e)}if("ask"===i?.permission)return a=i.user_message,new he.In({kind:he.b.FORCE_PROMPT,reason:a});var a}const SL={toolName:CN,getToolCallId:sL,createToolInput:e=>{const t=e.workingDirectory||"";return{command:e.command,cwd:t}},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd)},createRejectedResult:(e,t)=>new Do.Lt({result:{case:"rejected",value:new he.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"BackgroundShell error";case"rejected":return e.result.value.reason||"BackgroundShell rejected";case"permissionDenied":return"Permission denied";case"sandboxUnsupported":return`Sandbox policy unsupported on this host: ${e.result.value.reason}`;default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{shell_id:t.result.value.shellId,pid:t.result.value.pid}:{success:!0},getExtraHookFields:e=>({cwd:e.workingDirectory||""}),runPreExecutionHooks:async e=>{const{ctx:t,args:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e,i=r.workingDirectory||"",a=vL(r.sandboxPolicy);jN(t,xd.beforeShellExecution)&&To(r,await bL({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:a}))}};class kL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,SL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const _L={toolName:"WriteShellStdin",createToolInput:e=>({shell_id:e.shellId,chars_length:e.chars.length}),createRejectedResult:(e,t)=>new Do.nt({result:{case:"error",value:new Do.Gv({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"WriteShellStdin error":"Unknown error",createSuccessOutput:e=>({shell_id:e.shellId,success:!0})};class CL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,_L)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const EL={toolName:"ComputerUse",getToolCallId:sL,createToolInput:e=>({actions_count:e.actions.length}),createRejectedResult:(e,t)=>new Og.ks({result:{case:"error",value:new Og.Jb({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"ComputerUse error":"Unknown error",createSuccessOutput:(e,t)=>"success"===t.result.case?{action_count:t.result.value.actionCount,duration_ms:t.result.value.durationMs}:{success:!0}};class xL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,EL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const PL={toolName:SN,getToolCallId:sL,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new jw.Pi({result:{case:"rejected",value:new jw.iq({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"fileNotFound":return`File not found: ${e.result.value.path}`;case"notFile":return`Not a file: ${e.result.value.path}`;case"permissionDenied":return`Permission denied: ${e.result.value.path}`;case"fileBusy":return`File busy: ${e.result.value.path}`;case"rejected":return e.result.value.reason||"Delete rejected";case"error":return e.result.value.error||"Delete error";default:return"Unknown error"}},createSuccessOutput:e=>({file_path:e.path,deleted:!0})};class RL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,PL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const IL={toolName:EN,getToolCallId:sL,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new DA.Ek({result:{case:"rejected",value:new DA.J6({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"Diagnostics error";case"rejected":return e.result.value.reason||"Diagnostics rejected";case"fileNotFound":return`File not found: ${e.result.value.path}`;case"permissionDenied":return`Permission denied: ${e.result.value.path}`;default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{file_path:e.path,diagnostics_count:t.result.value.totalDiagnostics}:{file_path:e.path,success:!0}};class TL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,IL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const AL={toolName:"Fetch",getToolCallId:sL,createToolInput:e=>({url:e.url}),applyUpdatedInput:(e,t)=>{"string"==typeof t.url&&(e.url=t.url)},createRejectedResult:(e,t)=>new Gw.uN({result:{case:"error",value:new Gw.fk({url:e.url,error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Fetch error":"Unknown error",createSuccessOutput:(e,t)=>"success"===t.result.case?{url:e.url,status_code:t.result.value.statusCode,content_length:t.result.value.content.length}:{url:e.url,success:!0}};class $L{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,AL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const ML={toolName:_N,getToolCallId:sL,createToolInput:e=>({pattern:e.pattern,file_path:e.path,glob:e.glob,output_mode:e.outputMode}),applyUpdatedInput:(e,t)=>{"string"==typeof t.pattern&&(e.pattern=t.pattern),"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Ey.Ud({result:{case:"error",value:new Ey.ts({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Grep error":"Unknown error",createSuccessOutput:e=>({pattern:e.pattern,success:!0})};class DL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,ML)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const OL={toolName:kN,getToolCallId:sL,createToolInput:e=>({file_path:e.path,ignore:e.ignore}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new mC.fv({result:{case:"rejected",value:new mC.k2({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"Ls error";case"rejected":return e.result.value.reason||"Ls rejected";case"timeout":return"Ls operation timed out";default:return"Unknown error"}},getFailureType:e=>"timeout"===e.result.case?"timeout":"error",createSuccessOutput:e=>({file_path:e.path,success:!0})};class FL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,OL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const NL=(0,l.h)("hooks-exec:mcp");function LL(e){return!!(null===e||"string"==typeof e||"boolean"==typeof e||"number"==typeof e&&Number.isFinite(e))||(Array.isArray(e)?e.every(LL):"object"==typeof e&&Object.values(e).every((e=>void 0!==e&&LL(e))))}function jL(e,t,r,n){try{return GN({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof qN)return NL.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}class UL{constructor(e,t,r,n,o){this.innerExecutor=e,this.hookExecutor=t,this.baseHookRequestExtractor=r,this.mcpLease=n,this.hooksConfigLease=o}async execute(e,t,r){if(t.smartModeApprovalOnly)return this.innerExecutor.execute(e,t,r);if(t.symbolicPathArguments.length>0&&(!0===this.hooksConfigLease?.hasHookForStep(xd.preToolUse)||!0===this.hooksConfigLease?.hasHookForStep(xd.beforeMCPExecution)))return new Ac.iz({result:{case:"error",value:new Ac.Nh({error:`"${nA}" arguments can't be used on this computer: hooks that inspect MCP calls are configured here, and they would not see the file's contents. Read the file and pass its contents instead.`})}});const n=cL(e,this.hookExecutor),o=this.baseHookRequestExtractor(e),s=(0,bo.randomUUID)(),i=r?.hookContextCollector??[];let a=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t?.toJson()])));const c=`MCP:${t.toolName}`;try{const r=await n.executeHookForStep(xd.preToolUse,{...o,tool_name:c,tool_input:a,tool_use_id:s});if("deny"===r?.permission){const t=r.user_message||"MCP tool blocked by preToolUse hook";try{HN(i,GN({hookEventName:xd.preToolUse,additionalContext:r.additional_context}))}catch(t){if(!(t instanceof qN))throw t;NL.warn(e,"preToolUse deny additional_context exceeded max size; dropping carrier",{toolName:c,actualLength:t.actualLength,maxLength:t.maxLength})}return await this.firePostToolUseFailureAsync(e,n,o,c,a,t,"permission_denied",0,s,!1,i),new Ac.iz({result:{case:"permissionDenied",value:new Ac.HQ({error:QN("MCP tool execution",t),isReadonly:!1})}})}if(r?.updated_input)try{for(const[e,n]of Object.entries(r.updated_input))if(void 0!==n){if(!LL(n))throw new TypeError("updated_input value is not JSON");t.args[e]=we.Value.fromJson(n)}a=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t?.toJson()])))}catch(t){NL.warn(e,"Failed to merge updated_input for MCP",{error:t instanceof Error?t.message:String(t)})}HN(i,GN({hookEventName:xd.preToolUse,additionalContext:r?.additional_context}))}catch(t){const r=n.hasFailClosedHooksForStep?.(xd.preToolUse,c)??!1,l=t instanceof qN;if(r){const r=pN(`${l?"preToolUse additional_context exceeded max size":"preToolUse hook failed"}: ${t instanceof Error?t.message:"preToolUse hook error"}`);return await this.firePostToolUseFailureAsync(e,n,o,c,a,r,"error",0,s,!1,i),new Ac.iz({result:{case:"permissionDenied",value:new Ac.HQ({error:QN("MCP tool execution",r),isReadonly:!1})}})}NL.warn(e,l?"preToolUse additional_context exceeded max size; dropping carrier":"preToolUse hook error in MCP executor",{toolName:c,error:t instanceof Error?t.message:String(t),...l?{actualLength:t.actualLength,maxLength:t.maxLength}:{}})}const l=await(this.mcpLease?.getClient(e,t.providerIdentifier)),u=l?.config;let d;const h=u&&"url"in u&&u.url?u.url:void 0;d=void 0!==h?{url:h}:u&&"command"in u?{command:[u.command,...u.args??[]].filter(Boolean).join(" ")}:{command:t.providerIdentifier};const p={mcp_server_name:t.providerIdentifier,...void 0!==h?{mcp_server_url:h}:{}},f={...o,tool_name:t.toolName,tool_input:JSON.stringify(a),tool_use_id:s,...p,...d},m=jN(e,xd.beforeMCPExecution)?await n.executeHookForStep(xd.beforeMCPExecution,f):void 0;if("deny"===m?.permission){const t=QN("MCP tool execution",m.user_message);return await this.firePostToolUseFailureAsync(e,n,o,c,a,t,"permission_denied",0,s,!1,i),new Ac.iz({result:{case:"permissionDenied",value:new Ac.HQ({error:t,isReadonly:!1})}})}const g=FN.performance.now();try{const l=await this.innerExecutor.execute(e,t,r),u=rL(FN.performance.now()-g);let d="{}";if("success"===l.result.case)try{const e=l.result.value.content.map((e=>"text"===e.content.case?{type:"text",text:e.content.value.text}:"image"===e.content.case?{type:"image",data:Buffer.from(e.content.value.data).toString("base64"),mimeType:e.content.value.mimeType}:{type:"unknown"}));d=JSON.stringify({content:e,isError:l.result.value.isError})}catch(t){NL.warn(e,"Failed to serialize MCP result",{error:t instanceof Error?t.message:String(t)}),d=JSON.stringify({error:"Failed to serialize result"})}else"error"===l.result.case?d=JSON.stringify({error:l.result.value.error}):"rejected"===l.result.case?d=JSON.stringify({rejected:!0,reason:l.result.value.reason}):"permissionDenied"===l.result.case&&(d=JSON.stringify({permissionDenied:!0,error:l.result.value.error}));const h={...o,tool_name:t.toolName,tool_input:JSON.stringify(a),result_json:d,duration:u,tool_use_id:s,...p};await n.executeHookForStep(xd.afterMCPExecution,h);const f=await this.firePostToolUse(e,n,o,c,a,d,u,s,i);if(void 0!==f?.updated_mcp_tool_output)try{const e=f.updated_mcp_tool_output,t=[];if("string"==typeof e)t.push(new Ac._Z({content:{case:"text",value:new Ac.zN({text:e})}}));else if("object"==typeof e&&null!==e&&"content"in e&&Array.isArray(e.content)){const r=e.content;for(const e of r)"object"==typeof e&&null!==e&&"type"in e&&"text"===e.type&&"text"in e?t.push(new Ac._Z({content:{case:"text",value:new Ac.zN({text:String(e.text)})}})):t.push(new Ac._Z({content:{case:"text",value:new Ac.zN({text:JSON.stringify(e)})}}))}else t.push(new Ac._Z({content:{case:"text",value:new Ac.zN({text:JSON.stringify(e)})}}));const r="object"==typeof e&&null!==e&&"isError"in e&&Boolean(e.isError);return new Ac.iz({result:{case:"success",value:new Ac.QW({content:t,isError:r})}})}catch(t){return NL.warn(e,"Failed to process updated_mcp_tool_output",{error:t instanceof Error?t.message:String(t)}),l}return l}catch(t){const r=rL(FN.performance.now()-g),l=t instanceof Error?t.message:String(t);throw await this.firePostToolUseFailureAsync(e,n,o,c,a,l,"error",r,s,!1,i),t}}async firePostToolUse(e,t,r,n,o,s,i,a,c){try{const l=await t.executeHookForStep(xd.postToolUse,{...r,tool_name:n,tool_input:o,tool_output:s,duration:i,tool_use_id:a});return HN(c,jL(e,n,xd.postToolUse,l?.additional_context)),l}catch(t){return void NL.warn(e,"postToolUse hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}async firePostToolUseFailureAsync(e,t,r,n,o,s,i,a,c,l,u){try{const d=await t.executeHookForStep(xd.postToolUseFailure,{...r,tool_name:n,tool_input:o,error_message:s,failure_type:i,duration:a,tool_use_id:c,is_interrupt:l});HN(u,jL(e,n,xd.postToolUseFailure,d?.additional_context))}catch(t){NL.warn(e,"postToolUseFailure hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}}const BL={toolName:"ListMcpResources",createToolInput:e=>({server:e.server}),applyUpdatedInput:(e,t)=>{"string"==typeof t.server&&(e.server=t.server)},createRejectedResult:(e,t)=>new Ac.kP({result:{case:"error",value:new Ac.w2({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"ListMcpResources error";case"rejected":return e.result.value.reason||"ListMcpResources rejected";default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{resources_count:t.result.value.resources.length}:{success:!0}};class WL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,BL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const HL={toolName:"FetchMcpResource",createToolInput:e=>({server:e.server,uri:e.uri,download_path:e.downloadPath}),applyUpdatedInput:(e,t)=>{"string"==typeof t.server&&(e.server=t.server),"string"==typeof t.uri&&(e.uri=t.uri),"string"==typeof t.download_path&&(e.downloadPath=t.download_path)},createRejectedResult:(e,t)=>new Ac.ZD({result:{case:"error",value:new Ac.Jx({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"ReadMcpResource error";case"rejected":return e.result.value.reason||"ReadMcpResource rejected";case"notFound":return"Resource not found";default:return"Unknown error"}},createSuccessOutput:(e,t)=>{if("success"===t.result.case){const r=t.result.value;return{uri:e.uri,name:r.name,mime_type:r.mimeType,download_path:r.downloadPath,content_type:r.content.case,content_length:"text"===r.content.case||"blob"===r.content.case?r.content.value.length:void 0}}return{uri:e.uri,success:!0}}};class qL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,HL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const zL={toolName:vN,getToolCallId:sL,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Ky.sV({result:{case:"rejected",value:new Ky.f4({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"Read error";case"rejected":return e.result.value.reason||"Read rejected";case"fileNotFound":return`File not found: ${e.result.value.path}`;case"permissionDenied":return`Permission denied: ${e.result.value.path}`;case"invalidFile":return`Invalid file: ${e.result.value.path}`;default:return"Unknown error"}},createSuccessOutput:(e,t)=>{if("success"===t.result.case){const r="content"===t.result.value.output.case?t.result.value.output.value:"";return{file_path:e.path,content_length:r.length}}return{file_path:e.path,success:!0}},runPostExecutionHooks:async e=>{const{args:t,result:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e;if("success"!==r.result.case||!1===o.hasHooksForStep?.(xd.beforeReadFile))return;const i="content"===r.result.value.output.case?r.result.value.output.value:"",a=await async function(e,t){try{return await e()}catch(e){const r=function(e,t){return`${e??"Action"} was blocked because a configured hook failed to execute${t?`: ${t}`:"."}\n\nThis is a safety measure (fail-closed) - when hooks cannot be evaluated, the action is blocked to prevent potentially unsafe operations.\n\n${XN}`}(t,e instanceof Error?e.message:String(e));throw new ZN(r,e)}}((()=>o.executeHookForStep(xd.beforeReadFile,{...n,content:i,file_path:t.path,attachments:[],tool_use_id:s})),"File read");if("deny"===a?.permission){const e=QN("File read",a.user_message);throw new JN(e)}}};class GL{constructor(e,t,r){this.wrappedExecutor=new XT(iL(e,t,r,zL))}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const VL={toolName:"RecordScreen",getToolCallId:sL,createToolInput:e=>({mode:e.mode,save_as_filename:e.saveAsFilename}),createRejectedResult:(e,t)=>new P$.Tj({result:{case:"failure",value:new P$.yH({error:t,kind:P$.Wg.HOOK_REJECTED})}}),isSuccess:e=>"failure"!==e.result.case,getErrorMessage:e=>"failure"===e.result.case?e.result.value.error||"RecordScreen failed":"Unknown error",createSuccessOutput:(e,t)=>({result_type:t.result.case})};class KL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,VL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}function JL(e){return"success"===e.result.case||"failure"===e.result.case?e.result.value.stdout+e.result.value.stderr:""}const ZL={toolName:CN,createToolInput:e=>{const t=e.workingDirectory||"",r=e.timeout;return{command:e.command,cwd:t,..."number"==typeof r&&r>0&&{timeout:r}}},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd),"number"==typeof t.timeout&&t.timeout>=0&&(e.timeout=t.timeout)},createRejectedResult:(e,t)=>new he.W4({result:{case:"rejected",value:new he.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),isSuccess:e=>"success"===e.result.case||"failure"===e.result.case&&!e.result.value.aborted,getErrorMessage:e=>{switch(e.result.case){case"timeout":return`Command timed out after ${e.result.value.timeoutMs}ms`;case"spawnError":return e.result.value.error||"Failed to spawn command";case"failure":return e.result.value.aborted?"Command was aborted":"Command failed";case"rejected":return e.result.value.reason||"Command rejected";default:return"Unknown error"}},getFailureType:e=>"timeout"===e.result.case?"timeout":"error",isInterrupt:e=>"failure"===e.result.case&&e.result.value.aborted,createSuccessOutput:(e,t)=>({output:JL(t),exitCode:"success"===t.result.case?0:1}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),runPreExecutionHooks:async e=>{const{ctx:t,args:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e,i=r.workingDirectory||"";jN(t,xd.beforeShellExecution)&&To(r,await bL({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:vL(r.requestedSandboxPolicy)}))},runPostExecutionHooks:async e=>{const{args:t,result:r,baseHookRequest:n,hookExecutor:o,executionDurationMs:s,toolUseId:i}=e,a=JL(r);await o.executeHookForStep(xd.afterShellExecution,{...n,command:t.command,output:a,duration:s,sandbox:vL(t.requestedSandboxPolicy),tool_use_id:i})}};class XL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,ZL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class QL{constructor(){this.output=""}onEvent(e){"stdout"===e.event.case||"stderr"===e.event.case?this.output+=e.event.value.data:"exit"===e.event.case&&(this.exitEvent=e.event.value)}getOutput(){return this.output}isAborted(){return this.exitEvent?.aborted??!1}getExitCode(){return this.exitEvent?.code??0}}const YL={toolName:CN,createToolInput:e=>{const t=e.workingDirectory||"",r=e.timeout;return{command:e.command,cwd:t,..."number"==typeof r&&r>0&&{timeout:r}}},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd),"number"==typeof t.timeout&&t.timeout>=0&&(e.timeout=t.timeout)},createRejectedEvent:(e,t)=>new he.FI({event:{case:"rejected",value:new he.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),createHookContextEvent:e=>new he.FI({event:{case:"hookContext",value:new he.Ng({hookAdditionalContexts:[...e]})}}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),createResultCollector:()=>new QL,createSuccessOutput:(e,t)=>({output:t.getOutput(),exitCode:t.getExitCode()}),isStreamSuccess:e=>0===e.getExitCode(),getStreamErrorMessage:(e,t)=>t.getOutput().trim()||`Command failed with exit code ${t.getExitCode()}`,runPreExecutionHooks:async e=>{const{ctx:t,args:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e,i=r.workingDirectory||"",a=vL(r.requestedSandboxPolicy);jN(t,xd.beforeShellExecution)&&To(r,await bL({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:a}))},runPostExecutionHooks:async e=>{const{args:t,baseHookRequest:r,hookExecutor:n,collector:o,executionDurationMs:s,toolUseId:i}=e,a=vL(t.requestedSandboxPolicy);await n.executeHookForStep(xd.afterShellExecution,{...r,command:t.command,output:o.getOutput(),duration:s,sandbox:a,tool_use_id:i})}};class ej{constructor(e,t,r){this.wrappedExecutor=function(e,t,r,n){return{async*execute(o,s,i){const a=cL(o,t),{hookContext:c,helpers:l}=nL(o,s,a,r,n,i),u=n.runPreExecutionHooks?async e=>{await n.runPreExecutionHooks(e)}:void 0,d=await oL(o,s,a,c,l,n,((e,t)=>n.createRejectedEvent(e,t)),u);if("rejected"===d.type){yield d.result;for(const e of aL(n,c))yield e;return}const h=FN.performance.now(),p=n.createResultCollector();try{for await(const t of e.execute(o,s,i))p.onEvent(t),yield t}catch(e){const t=rL(FN.performance.now()-h),r=e instanceof Error?e.message:String(e);await l.fireFailureAsync(t,r,"error");for(const e of aL(n,c))yield e;throw e}const f=rL(FN.performance.now()-h);if(n.runPostExecutionHooks)try{await n.runPostExecutionHooks({ctx:o,args:s,baseHookRequest:c.baseHookRequest,hookExecutor:a,toolInput:l.getToolInput(),toolUseId:c.toolUseId,extraHookFields:c.extraHookFields,collector:p,executionDurationMs:f})}catch(e){eL.warn(o,"postExecutionHooks error",{toolName:n.toolName,error:e instanceof Error?e.message:String(e)})}if(p.isAborted())await l.fireFailureAsync(f,"Command was aborted","error",!0);else if(n.isStreamSuccess?.(p)??1)await l.fireSuccessAsync(f,JSON.stringify(n.createSuccessOutput(s,p)));else{const e=n.getStreamErrorMessage?.(s,p)??`Command failed with exit code ${p.getExitCode()}`;await l.fireFailureAsync(f,e,"error")}for(const e of aL(n,c))yield e}}}(e,t,r,YL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class tj{constructor(e,t,r){const n=new Map;this.wrappedExecutor=iL(e,t,r,function(e){return{toolName:bN,getToolCallId:sL,createToolInput:e=>({file_path:e.path,content:e.fileText}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new MI.v3({result:{case:"error",value:new MI.QM({path:e.path,error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Write error":"Unknown error",createSuccessOutput:e=>({file_path:e.path,success:!0}),runPreExecutionHooks:async t=>{const{args:r,hookExecutor:n,toolUseId:o}=t;if(!1===n.hasHooksForStep?.(xd.afterFileEdit))return;let s,i=!1;try{(await(0,Co.stat)(r.path)).size>262144?i=!0:s=await ji(r.path)}catch(e){}e.set(o,{contentBeforeWrite:s,fileTooLarge:i})},runCleanup:t=>{e.delete(t)},runPostExecutionHooks:async t=>{const{args:r,result:n,baseHookRequest:o,hookExecutor:s,toolUseId:i}=t,a=e.get(i);if("success"!==n.result.case||!1===s.hasHooksForStep?.(xd.afterFileEdit))return;const{contentBeforeWrite:c,fileTooLarge:l}=a??{fileTooLarge:!1};let u;u=l||void 0===c?[{old_string:"",new_string:r.fileText}]:c===r.fileText?[]:function(e,t){const r=(0,cS.YB)("","",e,t,"","",{context:0,timeout:50});return void 0===r?[{old_string:"",new_string:t}]:0===r.hunks.length?[]:r.hunks.map((e=>{const t=[],r=[];for(const n of e.lines)n.startsWith("-")?t.push(n.slice(1)):n.startsWith("+")&&r.push(n.slice(1));return{old_string:t.join("\n"),new_string:r.join("\n")}}))}(c,r.fileText);const d={...o,file_path:r.path,edits:u},h=await s.executeHookForStep(xd.afterFileEdit,d);if(r.returnFileContentAfterWrite&&void 0!==h){const e=n.result.value.path;try{const t=await ji(e),r=Js(t),o=Buffer.byteLength(t,"utf8");return new MI.v3({result:{case:"success",value:new MI.j6({path:n.result.value.path,linesCreated:r,fileSize:o,fileContentAfterWrite:t})}})}catch(e){return}}}}}(n))}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}function rj(e,t,r){return t===e.symbol}function nj(e,t,r){return rj(jT,e)?new XL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(ee,e)?new ej(t,r.hookExecutor,r.baseHookRequestExtractor):rj(HT,e)?new tj(t,r.hookExecutor,r.baseHookRequestExtractor):rj(eo,e)?new UL(t,r.hookExecutor,r.baseHookRequestExtractor,r.mcpLease,r.hooksConfigLease):rj(QT,e)||rj(YT,e)?new GL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(eA,e)?new FL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(VT,e)?new DL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(zT,e)?new $L(t,r.hookExecutor,r.baseHookRequestExtractor):rj(qT,e)?new RL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(tA,e)?new TL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(to,e)?new WL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(ro,e)?new qL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(vA,e)?new kL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(bA,e)?new CL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(xA,e)?new xL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(RA,e)?new KL(t,r.hookExecutor,r.baseHookRequestExtractor):rj($r,e)&&(r.hooksAdditionalContextPromise||r.hooksConfigLease)?new yL(t,r.hooksAdditionalContextPromise??Promise.resolve(void 0),r.teamHooksReadyPromise,r.hooksConfigLease):void 0}class oj{constructor(e,t,r,n,o,s,i){this.innerAccessor=e,this.hookExecutor=t,this.baseHookRequestExtractor=r,this.mcpLease=n,this.hooksAdditionalContextPromise=o,this.teamHooksReadyPromise=s,this.hooksConfigLease=i}get(e){const t=function(e,t){if(e.symbol===hL.symbol)return new wL(t)}(e,this.hookExecutor);return void 0!==t?t:function(e,t,r){const n=nj(e.symbol,t,r);return void 0!==n?n:t}(e,this.innerAccessor.get(e),{hookExecutor:this.hookExecutor,baseHookRequestExtractor:this.baseHookRequestExtractor,mcpLease:this.mcpLease,hooksAdditionalContextPromise:this.hooksAdditionalContextPromise,teamHooksReadyPromise:this.teamHooksReadyPromise,hooksConfigLease:this.hooksConfigLease})}*entries(){for(const[e,t]of this.innerAccessor.entries()){const r=nj(e.symbol,t,{hookExecutor:this.hookExecutor,baseHookRequestExtractor:this.baseHookRequestExtractor,mcpLease:this.mcpLease,hooksAdditionalContextPromise:this.hooksAdditionalContextPromise,teamHooksReadyPromise:this.teamHooksReadyPromise,hooksConfigLease:this.hooksConfigLease});yield[e,r??t]}const e=hL;yield[e,new wL(this.hookExecutor)]}}const sj={cursor_version:process.env.AGENT_CLI_STATIC_VERSION??"1.0.0",user_email:null};function ij(e=process.cwd()){let t=e;const r={getCwd:async()=>t,clone:e=>ij(e??t),async*execute(e,r,n={}){const o=n.workingDirectory??t;t=o;const s=function(e){return"win32"===process.platform?{executable:(0,Oo.oG)(),args:[...XO,"-Command",e]}:{executable:process.env.SHELL||"/bin/sh",args:["-lc",e]}}(r),i=(0,ou.spawn)(s.executable,[...s.args],{cwd:o,env:{...process.env,...n.env??{}},signal:n.signal,stdio:[!0===n.pipeStdin?"pipe":"ignore","pipe","pipe"]}),a=[];let c,l,u=!1;const d=()=>{c?.(),c=void 0},h=e=>{a.push(e),d()};for(i.on("spawn",(()=>{!0===n.pipeStdin&&h({type:"stdin_ready",stdin:i.stdin??void 0})})),i.stdout?.setEncoding("utf8"),i.stdout?.on("data",(e=>{h({type:"stdout",data:String(e)})})),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",(e=>{h({type:"stderr",data:String(e)})})),i.on("error",(e=>{l=e,u=!0,d()})),i.on("close",(e=>{h({type:"exit",code:e}),u=!0}));!u||a.length>0;)0!==a.length?yield a.shift():await new Promise((e=>{c=e}));if(void 0!==l)throw l}};return r}function aj(e,t,...r){for(const n of r){const r=t(e[n]);if(void 0!==r)return r}}function cj(e){return"string"==typeof e&&e.length>0?e:void 0}function lj(e){return"object"==typeof e&&null!==e&&"string"==typeof e.id&&"string"==typeof e.value}function uj(e){if(Array.isArray(e)&&e.every(lj))return e.map((e=>({id:e.id,value:e.value})))}class dj{constructor(e,t){this.innerAccessor=e,this.sessionHooksRuntime=t}get(e){return this.innerAccessor.get(e)}entries(){return this.innerAccessor.entries()}async dispose(){await this.sessionHooksRuntime.dispose()}}async function hj(e,t={}){const r=await new yN(new uL,function(e,t){const r=e.projectRoot??e.workingDirectory??e.workspaceRoots[0],n=t.includeProjectHooks??!0,i=t.includeUserHooks??!0;return{enterpriseConfigPath:t.includeEnterpriseHooks??1?mN():void 0,userConfigPath:i?(0,s.join)((0,o.homedir)(),".cursor","hooks.json"):void 0,claudeUserConfigPath:i?(0,s.join)((0,o.homedir)(),".claude","settings.json"):void 0,projectConfigPath:n&&void 0!==r?(0,s.join)(r,".cursor","hooks.json"):void 0,claudeProjectConfigPath:n&&void 0!==r?(0,s.join)(r,".claude","settings.json"):void 0,claudeProjectLocalConfigPath:n&&void 0!==r?(0,s.join)(r,".claude","settings.local.json"):void 0}}(e,t)).load(),n=new ON(r),i=function(e){return e.projectRoot??e.workingDirectory??e.workspaceRoots[0]??process.cwd()}(e),a=function(e){return Object.freeze({...sj,...e.globalContext??{}})}(t);return{projectDir:e.projectRoot,workspacePath:i,hooksConfig:r,hooksConfigLease:n,globalContext:a,createSessionRuntime(){const e=new DN(r,i,a,(t.createTerminalExecutor??ij)(),t.promptHookClient,void 0,void 0,{enableClaudeNestedHookSpecificOutputCompatibility:!0,commandHookPayloadTransport:(o=t.useCommandHookStdinTransport,!0===o?"stdin":"legacy")});var o;return{hookExecutor:e,hooksConfigLease:n,async dispose(){e.clearSessionEnvironment()}}},async dispose(){}}}function pj(e={}){return{createHooksRuntime:t=>hj(t.workspaceState,e)}}var fj=r("../proto/dist/generated/aiserver/v1/dashboard_service_connect.js");async function mj(e){(function(e){return"object"==typeof e&&null!==e&&"dispose"in e&&"function"==typeof e.dispose})(e)&&await e.dispose()}function gj(e={}){const t=e.getThirdPartyExtensibilityEnabled??(()=>!0),r=e.importThirdPartyPlugins??!1,n=e.includeProjectExtensibility??!0,s=e.includeUserExtensibility??!0,i=e.includeManagedSkills??!0,a=e.includePluginExtensibility??!0,c=new _y,l=(0,o.homedir)(),u=ym(l).dirPath;let d,h=!0;return{async prepareLocalExtensibility(){h=i&&await async function(e){if(!e)return!1;const t=(0,ye.createClient)(fj.I,e);return"synced"===(await async function(e,t){try{const r=await t.getManagedSkills()??[],n=await $D(e,{managedSkills:[...r]});return{status:"synced",managedSkillsCount:r.length,syncResult:n}}catch(t){return DD.warn(e,"Failed to sync managed skills from source",{error:t}),{status:"fetch_failed",error:t}}}((0,y.q6)(),{getManagedSkills:async()=>(await t.getManagedSkills(new JD.X8g({}))).skills??[]})).status}(e.dashboardTransport)},async loadLocalExtensibility(o){const i=function(e){if(e.workspaceRoots.length>0)return[...e.workspaceRoots];const t=e.projectRoot??e.workingDirectory;return void 0!==t?[t]:[]}(o.workspaceState);if(0===i.length)return d=void 0,{cursorRulesService:_j(),getAgentSkills:async e=>[]};const p=(0,y.q6)(),f=e.loadNestedRules??!0,m=n?i.map((e=>new fg(p,c,e,f,t,void 0))):[],g=function(e,t){const r=wj(t);return{getAllCursorRules:async t=>yj(await e.getAllCursorRules(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),dispose(){e.dispose()}}}(0===m.length?_j():1===m.length?m[0]:new pg(m,(()=>Fm)),{allowedRoots:n?i:[],excludedRoots:[]}),w=function(e,t){const r=wj(t);return{getAllCursorRules:async t=>yj(await e.getAllCursorRules(t),r),getAllAgentSkills:async t=>yj(await e.getAllAgentSkills(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),onDidChangeSkills:t=>e.onDidChangeSkills(t),dispose(){e.dispose()}}}(new gg(p,n?i:[],l,c,f,void 0,t,Promise.resolve(),"sdk"),{allowedRoots:[...n?i:[],...s?[l]:[],...h?[u]:[]],excludedRoots:h?[]:[u]}),v=n?i.map((e=>new Pg(e,t))):[],b=0===v.length?new Sg:1===v.length?v[0]:new Ig(v),S=WO(o.services.pluginBootstrapOutputs),k=S&&a?new yg(p,(()=>({importThirdPartyPlugins:r})),void 0,S.pluginsService):void 0,_=S&&a?new Tg((()=>({importThirdPartyPlugins:r})),S.pluginsService):void 0,C=new pg([g,w,...k?[k]:[]],(()=>Fm)),E=new pD([w,...k?[k]:[]],(()=>[]),(()=>({workspacePaths:n?i:[],userHomeDirectory:l,agentStoreSkillsDirs:[]}))),x=new Ig([b,..._?[_]:[]]);d={localRulesService:g,localSkillsService:w,localSubagentsService:b,pluginSkillsService:k,pluginSubagentsService:_,mergedCursorRulesService:C,mergedAgentSkillsService:E,mergedSubagentsService:x};const P={cursorRulesService:C,getAgentSkills:e=>E.getAllAgentSkills(e),subagentsService:x};return P},async disposeLocalExtensibility(){if(!d)return;const e=d;d=void 0,await async function(e){let t;const r=[e.mergedSubagentsService,e.mergedAgentSkillsService,e.mergedCursorRulesService,e.pluginSubagentsService,e.pluginSkillsService,e.localSubagentsService,e.localSkillsService,e.localRulesService];for(const e of r)try{await mj(e)}catch(e){t??=e}if(void 0!==t)throw t}(e)}}}function wj(e){const t=Promise.all(e.allowedRoots.map(Sj)),r=Promise.all(e.excludedRoots.map(Sj));return async e=>{const[n,o,s]=await Promise.all([kj(e.fullPath),t,r]);return void 0!==n&&!s.some((e=>vj(n,e)))&&o.some((e=>vj(n,e)))}}async function yj(e,t){const r=await Promise.all(e.map(t));return e.filter(((e,t)=>r[t]))}function vj(e,t){if(e===t)return!0;const r=`${t}/`;return e.startsWith(r)}function bj(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")}async function Sj(e){try{return bj(await(0,Co.realpath)(e))}catch{return bj(e)}}async function kj(e){try{return bj(await(0,Co.realpath)(e))}catch{return}}function _j(){return{getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}}}function Cj(e,t){const r=e.releaseTag??t;if(e.releaseRepo&&e.releaseAsset&&r)return{kind:"release",releaseRepo:e.releaseRepo,releaseAsset:e.releaseAsset,releaseTag:r}}const Ej=/^[a-z][a-z0-9+.-]*:\/\/([^/?#]*)/i,xj=/^(?:[^@/\s]+@)?([^:/\s\\]+):(?!\/\/)/,Pj=/^([a-z][a-z0-9+.-]*)::(.*)$/i,Rj=/^([a-z][a-z0-9+.-]*):\/\//i,Ij=new Set(["file","git","http","https","ssh"]);function Tj(e){if(/^(?:\\\\|\/\/)[^\\/]/.test(e))throw new Error("Cursor Orbit: plugin git remote could not be validated");const t=Pj.exec(e);if(null!==t){const e=t[1].toLowerCase();if(!Ij.has(e))throw new Error("Cursor Orbit: plugin git remote could not be validated");const r=t[2];if(!("http"!==e&&"https"!==e||null!==Rj.exec(r)&&URL.canParse(r)))throw new Error("Cursor Orbit: plugin git remote could not be validated");const n=Tj(r);if(0===n.length)throw new Error("Cursor Orbit: plugin git remote could not be validated");return n}const r=Rj.exec(e)?.[1].toLowerCase();if(void 0!==r&&!Ij.has(r))throw new Error("Cursor Orbit: plugin git remote could not be validated");const n=Ej.exec(e)?.[1];if(void 0===n){const t=xj.exec(e)?.[1];if(void 0===t)return[];const r=function(e){const t=/^\[([^\]]+)\]$/.exec(e)?.[1],r=t??e;if(""!==r&&!/[\[\]\s@%\/\\]/.test(r))return Aj(r)}(t);if(void 0===r)throw new Error("Cursor Orbit: plugin git remote could not be validated");return[r]}const o=[];URL.canParse(e)&&o.push(Aj(new URL(e).hostname));const s=function(e){try{return decodeURIComponent(e)}catch{return e}}(n.slice(n.lastIndexOf("@")+1)),i=`https://${s}`;if(URL.canParse(i))o.push(Aj(new URL(i).hostname));else{const e=/^\[([^\]]+)\](?::\d*)?$/.exec(s)?.[1];if(void 0===e)throw new Error("Cursor Orbit: plugin git remote could not be validated");o.push(Aj(e))}const a=o.filter((e=>""!==e));if(0===a.length)throw new Error("Cursor Orbit: plugin git remote could not be validated");return[...new Set(a)]}function Aj(e){return e.trim().toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,"")}function $j(){const e=["-c","credential.interactive=false","-c","core.fsmonitor=false"];return"1"===process.env[Zv.K4]&&e.push("-c","http.followRedirects=false"),"win32"===process.platform&&e.push("-c","core.longpaths=true"),e}function Mj(e){return"function"==typeof e?e():e}async function Dj(e,t){const r=function(e){const t={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:void 0,VSCODE_GIT_ASKPASS_NODE:void 0,VSCODE_GIT_ASKPASS_MAIN:void 0,VSCODE_GIT_ASKPASS_EXTRA_ARGS:void 0,GCM_INTERACTIVE:"Never"};if(t.GIT_CONFIG_NOSYSTEM=void 0,!0===e?.sshBatchMode){const e=process.env.GIT_SSH_COMMAND?.trim()||"ssh";t.GIT_SSH_COMMAND=`${e} -oBatchMode=yes`}if(void 0!==e?.extraGitConfig){const r=Object.entries(e.extraGitConfig).flatMap((([e,t])=>Array.isArray(t)?t.map((t=>[e,t])):[[e,t]]));t.GIT_CONFIG_COUNT=String(r.length);for(const[e,[n,o]]of r.entries())t[`GIT_CONFIG_KEY_${e}`]=n,t[`GIT_CONFIG_VALUE_${e}`]=o}return{cwd:e?.cwd,env:t}}({cwd:t?.cwd,sshBatchMode:t?.sshBatchMode,extraGitConfig:t?.extraGitConfig}),n=function(e){return function(e,t=process.env){if("1"!==t[Zv.K4])return;const r=(0,Zv.H)(t[Zv.Zf]);for(const t of e)for(const e of Tj(t))if((0,Zv.ad)(e,r))throw new Error(`Cursor Orbit: plugin git egress to ${e} is refused`)}(e),[...$j(),...e]}(e);try{return await ay("git",n,{...r,...void 0!==t?.timeoutMs&&{timeout:t.timeoutMs,killSignal:"SIGTERM"}})}catch(e){if("1"===process.env[Zv.K4]&&function(e){if("object"!=typeof e||null===e||!("stderr"in e))return!1;const t=e.stderr;return"string"==typeof t&&/The requested URL returned error: 3\d{2}\b/i.test(t)}(e))throw new Error("Cursor Orbit: the plugin gitUrl redirected. Ask an administrator to update gitUrl to the final URL; redirects are disabled for plugin Git operations.",{cause:e});throw e}}const Oj=/^[0-9a-f]{7,40}$/i,Fj=/^[0-9a-f]{40}$/i;function Nj(e){if(void 0===e||""===e)return;const t=e.split(/\r?\n/).map((e=>{const[t,r]=e.split("\t");if(t&&r&&/^[0-9a-f]{40}$/i.test(t))return{sha:t,refName:r}})).filter((e=>void 0!==e)),r=t[0];return void 0!==r?t.find((e=>e.refName.endsWith("^{}")))?.sha??r.sha:void 0}async function Lj(e,t,r){const n=t.trim();if(Fj.test(n))return{fullSha:n.toLowerCase()};if(Oj.test(n)){try{const t=await async function(e,t,r){const{stdout:n}=await Dj(["ls-remote",e,`refs/heads/${t}`,`refs/tags/${t}`,`refs/tags/${t}^{}`],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs});return Nj(n)?.toLowerCase()}(e,n,r);if(t)return{fullSha:t}}catch{}return{fullSha:n.toLowerCase()}}let o;try{if("HEAD"===n.toUpperCase()){const t=await Dj(["ls-remote","--symref",e,"HEAD"],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs}),n=Nj(t.stdout);if(!n)throw new Error(`git ls-remote did not return a resolvable commit for HEAD (${e})`);return{fullSha:n.toLowerCase(),headSymrefStdout:t.stdout}}o=(await Dj(["ls-remote",e,n],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs})).stdout}catch(t){const r=t instanceof Error?t.message:String(t),o=new Error(`Failed to resolve git ref "${n}" for ${e}: ${r}`);throw o.cause=t,o}const s=Nj(o);if(!s)throw new Error(`git ls-remote did not return a resolvable commit for ref "${n}" (${e})`);return{fullSha:s.toLowerCase()}}const jj=zh.map((function(e){const t=e.split("/")[0];if(void 0===t||0===t.length)throw new Error(`Marketplace manifest path has no directory: ${e}`);return t}));let Uj;function Bj(e){let t=e.trim().replaceAll("\\","/");for(;t.startsWith("./");)t=t.slice(2);return t=t.replace(/\/+$/,""),""===t||"."===t||t.startsWith("/")||/^[a-zA-Z]:/.test(t)||t.split("/").some((e=>""===e||"."===e||".."===e))?null:t}function Wj(e){const t=[];for(const r of e){const e=Bj(r);if(null===e)return"all";t.push(e)}return t}async function Hj(e,t){const r="all"===e?"all":Wj(e),n=t&&"all"!==r&&await(process.env.CURSOR_DISABLE_SPARSE_PLUGIN_CLONES?Promise.resolve(!1):(Uj??=(async()=>{try{const{stdout:e}=await Dj(["--version"]),t=function(e){const t=/git version (\d+)\.(\d+)/.exec(e);return t?{major:Number(t[1]),minor:Number(t[2])}:null}(e);return null!==t&&(t.major>2||2===t.major&&t.minor>=28)}catch{return!1}})(),Uj));return{materialize:r,sparse:n,sparseDirs:n?(o=r,[...new Set([...jj,...o])]):[]};var o}function qj(e){return e.toLowerCase().includes("filtering not recognized by server")}async function zj(e,t,r){await Dj(["sparse-checkout","set","--cone","--",...t],{...r,cwd:e})}async function Gj(e){try{await(0,Co.access)((0,s.join)(e,".git","info","sparse-checkout"))}catch{return!1}try{const{stdout:t}=await Dj(["config","--bool","--get","core.sparseCheckout"],{cwd:e});return"true"===t.trim()}catch{return!1}}async function Vj(e,t,r){if("all"!==t&&0===t.length)return;if(!await Gj(e))return;const n={...r,cwd:e,sshBatchMode:!0};if("all"===t)return void await Dj(["sparse-checkout","disable"],n);const o=Wj(t);"all"!==o?await Dj(["sparse-checkout","add","--",...o],n):await Dj(["sparse-checkout","disable"],n)}(0,_s.J)((function(){Uj=void 0}));const Kj=/\.git$/i,Jj=new Set(["account","dashboard"]);function Zj(e){return e.replace(Kj,"")}function Xj(e){let t;try{t=decodeURIComponent(e)}catch{return}return t.length>0&&!t.includes("/")?t:void 0}function Qj(e){const t=e.toLowerCase();return"github.com"===t||t.endsWith(".github.com")}function Yj(e){return e.toLowerCase().split(".").includes("gitlab")}function eU(e){const t=e.toLowerCase();return"bitbucket.org"===t||"www.bitbucket.org"===t}function tU(e){const t=e.toLowerCase();return Yj(e)?"GitLab":t.includes("bitbucket")?"Bitbucket":t.includes("gitea")||t.includes("codeberg")?"Gitea/Codeberg":t.includes("azure")&&t.includes("dev")?"Azure DevOps":null}function rU(e){return Qj(e)?"github":Yj(e)?"gitlab":eU(e)?"bitbucket":function(e){const t=e.toLowerCase();return"dev.azure.com"===t||"www.dev.azure.com"===t}(e)?"azure_devops":"generic"}function nU(e){let t;try{const r=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;t=new URL(r.includes("://")?r:`https://${r}`)}catch{return null}const r=t.hostname;let n=t.pathname.split("/").filter(Boolean);Ga(r)&&"git"===n[0]?.toLowerCase()&&(n=n.slice(1));const o=n[0];void 0!==o&&n.length>=3&&"scm"===o.toLowerCase()&&(n=n.slice(1));const s=function(e){const t=e[0],r=e[1];if(!t||!r)return;const n=Zj(r);return n?{owner:t,repo:n,hasSubpath:e.length>2}:void 0}(n);return void 0===s?null:{provider:rU(r),owner:s.owner,repo:s.repo,host:r}}function oU(e){const t=sU(e);if(null===t)return!1;const r=t.pathname.split("/").filter(Boolean),n=r[0];return void 0!==n&&r.length>=3&&"scm"===n.toLowerCase()}function sU(e){try{const t=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;return new URL(t.includes("://")?t:`https://${t}`)}catch{return null}}function iU(e){const t=e.trim();if(""===t)return{error:"URL cannot be empty"};const r=nU(t);if(null===r)return{error:"Invalid URL format. Expected: github.com/owner/repo or gitlab.com/namespace/repo"};if(Yj(r.host)){const e=sU(t),r=null===e?void 0:function(e){const t=e.indexOf("-"),r=-1!==t,n=r?e.slice(0,t):[...e];if(n.length<2||n.some((e=>0===e.length)))return;const o=Zj(n[n.length-1]);return o?(n[n.length-1]=o,{repositorySegments:n,hasSpecialRouteSeparator:r}):void 0}(e.pathname.split("/").filter(Boolean));if(null===e||void 0===r)return{error:"Invalid GitLab repository URL format. Expected: https://gitlab.com/namespace/repo"};const n=e.host.replace(/^www\./i,""),o=r.repositorySegments[0],s=r.repositorySegments[r.repositorySegments.length-1];return void 0===o||void 0===s?{error:"Invalid GitLab repository URL format. Expected: https://gitlab.com/namespace/repo"}:{url:`https://${n}/${r.repositorySegments.join("/")}`,owner:o,repo:s,host:n,provider:"gitlab"}}if("bitbucket"===r.provider){const e=function(e){const t=sU(e.trim());if(null!==t&&eU(t.hostname))return function(e){const t=e[0],r=e[1];if(void 0===t||void 0===r)return;const n=Xj(t),o=Xj(r);if(void 0===n||void 0===o||Jj.has(n.toLowerCase()))return;const s=Zj(o);return s?{workspace:encodeURIComponent(n),repo:encodeURIComponent(s),hasSubpath:e.length>2}:void 0}(function(e){const t=e.pathname.split("/");return""===t[0]&&t.shift(),""===t[t.length-1]&&t.pop(),t}(t))}(t);if(void 0===e)return{error:"Invalid Bitbucket repository URL format. Expected: https://bitbucket.org/{workspace}/{repo}"};const n=r.host.replace(/^www\./i,"");return{url:`https://${n}/${e.workspace}/${e.repo}`,owner:e.workspace,repo:e.repo,host:n,provider:"bitbucket"}}if("azure_devops"===r.provider){const e=sU(t),n=null===e?void 0:function(e){const t=e.findIndex((e=>"_git"===e.toLowerCase()));if(t<1||t>2)return;const r=e[0],n=e[t+1];if(!r||!n)return;const o=Zj(n);if(!o)return;const s=2===t?e[1]:o;return s?{organization:r,project:s,repo:o,hasSubpath:e.length>t+2}:void 0}(e.pathname.split("/").filter(Boolean));if(null===e||void 0===n)return{error:"Invalid Azure DevOps repository URL format. Expected: https://dev.azure.com/{organization}/{project}/_git/{repo}"};const o=r.host.replace(/^www\./i,"");return{url:`https://${o}/${n.organization}/${n.project}/_git/${n.repo}`,owner:n.organization,repo:n.repo,host:o,provider:"azure_devops",project:n.project}}if(function(e){switch(e.provider){case"github":return!0;case"generic":return!Ga(e.host)&&null===tU(e.host);case"gitlab":case"bitbucket":case"azure_devops":return!1;default:return e.provider,!1}}(r)){const e=cU(r.host.replace(/^www\./i,""));return{url:`https://${e}/${oU(t)?"scm/":""}${r.owner}/${r.repo}`,owner:r.owner,repo:r.repo,host:e,provider:"github"}}const n=tU(r.host);return{error:"Only GitHub, GitLab, Bitbucket, and Azure DevOps URLs are currently supported."+(null!==n?` ${n} is not supported yet.`:"")}}function aU(e){const t=iU(e);if("error"in t)return null;switch(t.provider){case"github":return`git@${t.host}:${t.owner}/${t.repo}.git`;case"gitlab":return function(e){let t;try{t=new URL(e.url).pathname.replace(/^\//,"").replace(/\.git$/i,"")}catch{return null}if(0===t.length)return null;return`git@${e.host.replace(/:\d+$/,"")}:${t}.git`}(t);case"bitbucket":case"azure_devops":return null;default:return t.provider,null}}function cU(e){return Qj(e)?"github.com":e}function lU(e){return!e.operatingSystems||0===e.operatingSystems.length||e.operatingSystems.includes(function(){const e=(0,o.platform)();return"win32"===e?"Windows":"darwin"===e?"Macintosh":"Linux"}())}function uU(e){return/[\n\r:#[\]{}&*!|>'"%@`]/.test(e)||e.startsWith(" ")||e.endsWith(" ")?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:e}const dU=new Set(["con","prn","aux","nul","com1","com2","com3","com4","com5","com6","com7","com8","com9","lpt1","lpt2","lpt3","lpt4","lpt5","lpt6","lpt7","lpt8","lpt9"]);function hU(e){const t=oh(e).replace(/[. ]+$/g,"");return""===t||"."===t||".."===t?"_":dU.has(t.toLowerCase())?`_${t}`:t}const pU=18e5,fU=6e5,mU={recursive:!0,force:!0,maxRetries:3},gU=["terminal prompts disabled","could not read username","host key verification failed","could not read from remote repository","permission denied","repository not found","user cancelled dialog","spawn git enoent","authentication failed","unable to get password from user","you do not have access to"],wU=["enotempty: directory not empty, rename","/_staging/"],yU=["upload-pack: not our ref","server does not allow request for unadvertised object"];function vU(e){const t=String(e).toLowerCase().replaceAll("\\","/");return gU.some((e=>t.includes(e)))?"user_git_access":wU.every((e=>t.includes(e)))?"local_cache_race":yU.some((e=>t.includes(e)))?"stale_pinned_ref":"infrastructure"}function bU(e){return"object"==typeof e&&null!==e&&(!0===e.killed||bU(e.cause))}function SU(e){return bU(e)?"killed_by_budget":vU(e)}function kU(e){const t=iU(e);if(!("error"in t)&&"gitlab"===t.provider){let r;try{r=new URL(t.url).pathname.replace(/^\//,"")}catch{throw new Error(`Invalid git URL: ${e}`)}const n=r.split("/").filter(Boolean).map((e=>e.toLowerCase()));if(n.length<2)throw new Error(`Invalid git URL: ${e}`);return{host:t.host.toLowerCase(),pathSegments:n}}const r=nU(e);if(null===r)throw new Error(`Invalid git URL: ${e}`);return{host:cU(r.host.replace(/^www\./i,"")).toLowerCase(),pathSegments:[r.owner.toLowerCase(),r.repo.toLowerCase()]}}const _U=new Map;class CU{constructor(e,t){this.cacheRoot=e,this.options=t,this.manifestCache=new Map}get sparsePluginClones(){return this.options?.sparsePluginClones??!1}remoteTimeoutMs(){return this.sparsePluginClones?pU:void 0}localTimeoutMs(){return this.sparsePluginClones?fU:void 0}lsRemoteTimeoutMs(){return this.sparsePluginClones?3e4:void 0}async cloneResolvedRef(e,t,r,n){const o={cwd:e,sshBatchMode:n?.sshBatchMode,extraGitConfig:{...Mj(this.options?.extraGitConfig),"safe.directory":e}},{sparse:s,sparseDirs:i}=await Hj(n?.materialize??"all",this.sparsePluginClones);await Dj(["init"],{...o,timeoutMs:this.localTimeoutMs()}),s&&await zj(e,i,{sshBatchMode:n?.sshBatchMode,extraGitConfig:Mj(this.options?.extraGitConfig),timeoutMs:this.localTimeoutMs()});const{stderr:a}=await Dj(["fetch","--depth","1",...s?["--filter=blob:none"]:[],t,r],{...o,timeoutMs:this.remoteTimeoutMs()});return await Dj(["checkout","FETCH_HEAD"],{...o,timeoutMs:this.remoteTimeoutMs()}),{strategy:s?"sparse":"full",filterIgnoredByServer:s&&qj(a??"")}}async createStagingDir(){const e=(0,s.join)(this.cacheRoot,"_staging",(0,bo.randomUUID)());return await(0,Co.mkdir)(e,{recursive:!0}),e}async moveToCanonicalDir(e,t){return await(0,Co.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,Co.rm)(t,mU),await(0,Co.rename)(e,t),t}async cleanStaleStagingDirs(){const e=(0,s.join)(this.cacheRoot,"_staging");try{const t=await(0,Co.readdir)(e,{withFileTypes:!0}),r=Date.now();await Promise.all(t.filter((e=>e.isDirectory())).map((async t=>{try{const n=(0,s.join)(e,t.name),o=await(0,Co.stat)(n);r-o.mtimeMs>CU.STALE_STAGING_THRESHOLD_MS&&await(0,Co.rm)(n,mU)}catch{}})))}catch{}}getLegacyCloneDir(e,t){return(0,s.join)(this.cacheRoot,hU(e),hU(t))}getCanonicalCloneDir(e,t){const{host:r,pathSegments:n}=kU(e);return(0,s.join)(this.cacheRoot,hU(r),...n.map(hU),hU(t))}getCanonicalRepoRootDir(e){const{host:t,pathSegments:r}=kU(e);return(0,s.join)(this.cacheRoot,hU(t),...r.map(hU))}async pruneSiblingCloneDirs(e,t,r){const n=this.getCanonicalRepoRootDir(e),o=hU(t);try{const e=await(0,Co.readdir)(n,{withFileTypes:!0});await Promise.all(e.filter((e=>e.isDirectory()&&e.name!==o)).map((e=>(0,Co.rm)((0,s.join)(n,e.name),mU))))}catch{}if(void 0!==r)try{await(0,Co.rm)(r,mU)}catch{}}async ensureCloned(e,t,r,n=Tp,o){const s=this.serializedOnRepo(this.getCanonicalRepoRootDir(t),(()=>this.ensureClonedImpl(e,t,r,n,o?.materialize??"all")));return this.sparsePluginClones?s:(0,Or.wj)(s,3e4,`ensureCloned timed out after 30000ms for ${t} @ ${r}`)}async ensureMaterialized(e,t,r=Tp){const n=this.serializedOnRepo((0,s.dirname)(e),(async()=>{const n=performance.now();try{await Vj(e,t,{extraGitConfig:Mj(this.options?.extraGitConfig),timeoutMs:this.remoteTimeoutMs()}),r.increment("marketplace_cache_manager.ensure_materialized.success",1),r.distribution("marketplace_cache_manager.ensure_materialized.duration",performance.now()-n)}catch(o){throw r.log("error","Failed to materialize plugin directories in sparse marketplace clone",{clonePath:e,spec:"all"===t?"all":t.join(","),error:String(o),errorCategory:SU(o)}),r.increment("marketplace_cache_manager.ensure_materialized.error",1,{error_category:SU(o)}),r.distribution("marketplace_cache_manager.ensure_materialized.duration",performance.now()-n,{outcome:"error"}),o}}));return this.sparsePluginClones?n:(0,Or.wj)(n,3e4,`ensureMaterialized timed out after 30000ms for ${e}`)}async serializedOnRepo(e,t){const r=`${this.cacheRoot}:${e}`,n=(_U.get(r)??Promise.resolve()).catch((()=>{})).then(t);_U.set(r,n);try{return await n}finally{_U.get(r)===n&&_U.delete(r)}}async ensureClonedImpl(e,t,r,n,o){n.log("info",`MarketplaceCacheManager: Ensuring cloned ${e} at ${t}@${r}`,{marketplaceId:e,gitUrl:t,ref:r});const s=r.trim();let i,a=t.startsWith("git@")||t.startsWith("ssh://")?null:aU(t);if(null!==a)try{i=(await Lj(a,s,{sshBatchMode:!0,extraGitConfig:Mj(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}catch(e){if(this.sparsePluginClones&&bU(e))throw e;n.log("debug","Failed to resolve remote ref using SSH URL, falling back to HTTPS",{gitUrl:t,ref:r,error:String(e),errorCategory:vU(e)}),a=null,i=(await Lj(t,s,{extraGitConfig:Mj(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}else i=(await Lj(t,s,{extraGitConfig:Mj(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha;const c=this.getCanonicalCloneDir(t,i),l=this.getLegacyCloneDir(e,s);n.log("info",`MarketplaceCacheManager: Resolved clone directory for ${e} at ${t}@${r} to ${c}`,{marketplaceId:e,resolvedRef:i,originalRef:s});const u=performance.now(),d=(e,t)=>{n.increment(`marketplace_cache_manager.ensure_cloned.${e}`,1,t),n.distribution(`marketplace_cache_manager.ensure_cloned.${e}.duration`,performance.now()-u,t)};if(await this.isCloneComplete(c)){await this.pruneSiblingCloneDirs(t,i,l);const e=await Gj(c);return e&&await Vj(c,o,{extraGitConfig:Mj(this.options?.extraGitConfig),timeoutMs:this.remoteTimeoutMs()}),d("cache_hit",{strategy:e?"sparse":"full"}),c}return n.increment("marketplace_cache_manager.ensure_cloned.cache_miss",1),this.cloneViaStaging(c,t,a,i,l,r,n,d,o)}async cloneViaStaging(e,t,r,n,o,s,i,a,c){await this.cleanStaleStagingDirs();const l=await this.createStagingDir();i.log("info",`MarketplaceCacheManager: Cloning ${t}@${s} into staging directory: ${l}`,{gitUrl:t,ref:s,cloneDir:e});const u=this.sparsePluginClones?setInterval((()=>{const e=new Date;(0,Co.utimes)(l,e,e).catch((()=>{}))}),CU.STAGING_HEARTBEAT_INTERVAL_MS):void 0;u?.unref?.();try{let u;if(null!==r)try{u=await this.cloneResolvedRef(l,r,n,{sshBatchMode:!0,materialize:c})}catch(e){if(this.sparsePluginClones&&bU(e))throw e;i.log("debug","Falling back to HTTPS clone due to SSH clone failure",{gitUrl:t,ref:s,error:String(e),errorCategory:SU(e)}),await(0,Co.rm)(l,mU),await(0,Co.mkdir)(l,{recursive:!0}),u=await this.cloneResolvedRef(l,t,n,{materialize:c})}else u=await this.cloneResolvedRef(l,t,n,{materialize:c});u.filterIgnoredByServer&&(i.log("warn","Server ignored --filter=blob:none; sparse clone downloaded a full pack",{gitUrl:t,ref:s}),i.increment("marketplace_cache_manager.ensure_cloned.filter_ignored_by_server",1));const d=await this.moveToCanonicalDir(l,e);return await this.pruneSiblingCloneDirs(t,n,o),a("cache_write_success",{strategy:u.strategy}),d}catch(e){const r=SU(e);throw a("error",{error_category:r}),i.log("error","Failed to clone marketplace repository via staging clone",{gitUrl:t,ref:s,error:String(e),errorCategory:r}),i.captureException(e,{error_type:"clone_marketplace_repository",error_category:r}),e}finally{void 0!==u&&clearInterval(u);try{await(0,Co.rm)(l,mU)}catch{}}}async isCloneComplete(e){try{if(!(await(0,Co.stat)(e)).isDirectory())return!1;const t=await(0,Co.readdir)(e);if(!t.includes(".git"))return!1;if(t.length>1)return!0;try{return(await(0,Co.stat)((0,s.join)(e,".git","info","sparse-checkout"))).isFile()}catch{return!1}}catch{return!1}}getPluginDir(e,t){return vf(e,t)}async copyPluginToDir(e,t){await(0,Co.mkdir)(t,{recursive:!0}),await(0,Co.cp)(e,t,{recursive:!0,verbatimSymlinks:!0})}async readManifest(e,t={}){const r=function(e,t){return JSON.stringify({clonePath:e,repoName:t.repoName??null,fallbackId:t.fallbackId??null})}(e,t);if(this.manifestCache.has(r))return this.manifestCache.get(r)??null;const n=await async function(e,t={}){for(const r of zh){const n=(0,s.join)(e,r);let o;try{o=await(0,Co.readFile)(n,"utf-8")}catch{continue}const i=bp(o,t);if(i.success)return i.data}return null}(e,t);return this.manifestCache.set(r,n),n}async resolvePluginPath(e,t){const r=await this.readManifest(e);if(!r)return null;const n=r.plugins.find((e=>e.name===t.toLowerCase()));if(!n)return null;const o=kp(n.source,r.metadata?.pluginRoot);return o&&_p(o)?o:null}async discoverPlugins(e){const t=await this.readManifest(e);return t?function(e){const t=[],r=function(e,t){const r=[];for(const n of e){const e=n.source;if("string"!=typeof e)switch(e.source){case"github":r.push({entry:n,kind:"external-github",externalUrl:`https://github.com/${e.repo}.git`,externalRef:e.ref,externalSha:e.sha,effectiveRef:e.sha??e.ref});break;case"url":r.push({entry:n,kind:"external-url",externalUrl:e.url,externalRef:e.ref,externalSha:e.sha,effectiveRef:e.sha??e.ref});break;case"git-subdir":r.push({entry:n,kind:"external-git-subdir",externalUrl:e.url,externalRef:e.ref,externalSha:e.sha,effectiveRef:e.sha??e.ref,subdirPath:e.path})}else{const o=kp(e,t);null!==o?r.push({entry:n,kind:"local",localPath:o}):r.push({entry:n,kind:"unresolvable",rawSource:e})}}return r}(e.plugins,e.metadata?.pluginRoot);for(const e of r){const{name:r,displayName:n,description:o,version:s}=e.entry,i={name:r,displayName:n,description:o,version:s};switch(e.kind){case"local":_p(e.localPath)&&t.push({...i,sourceType:"local",gitPath:e.localPath});break;case"external-github":t.push({...i,sourceType:"github",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha});break;case"external-url":t.push({...i,sourceType:"url",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha});break;case"external-git-subdir":t.push({...i,sourceType:"git-subdir",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha,subdirPath:e.subdirPath})}}return t}(t):[]}}CU.STALE_STAGING_THRESHOLD_MS=3e5,CU.STAGING_HEARTBEAT_INTERVAL_MS=6e4;const EU=(0,zs.debuglog)("cursor-plugins");function xU(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function PU(e){return xU(e)?e:void 0}function RU(e){const t=e.name?.trim();return void 0!==t&&t.length>0?t:e.pluginId}function IU(e,t){return void 0!==e?.marketplace?e.marketplace:void 0!==e?.marketplaceId?(t??[]).find((t=>void 0!==t.id&&String(t.id)===String(e.marketplaceId))):void 0}function TU(e,t){const r=t?.distributionGitUrl?.trim();return r?t?.gitUrl&&!BU(e,t.gitUrl)?e:r:e}function AU(e){return e?.distributionGitUrl?.trim()||e?.gitUrl}function $U(e,t){if(e.pinnedGitRef)return e.pinnedGitRef;if(e.plugin?.gitRef)return e.plugin.gitRef;const r=IU(e.plugin,t),n=e.plugin?.gitUrl,o=r?.gitUrl;return n&&o&&n!==o||!r?.gitRef?"main":r.gitRef}const MU="backend-git://";function DU(e,t,r){const n=r?`#${encodeURIComponent(r)}`:"";return`${MU}${encodeURIComponent(e)}@${encodeURIComponent(t)}${n}`}function OU(e){if(!e.startsWith(MU))return null;const t=e.slice(14),r=t.indexOf("#"),n=r>=0?t.slice(0,r):t,o=r>=0?t.slice(r+1):void 0,s=n.lastIndexOf("@");return s<0?null:{gitUrl:decodeURIComponent(n.slice(0,s)),ref:decodeURIComponent(n.slice(s+1)),gitPath:o?decodeURIComponent(o):void 0}}const FU="backend-release://";function NU(e){const t=e.tag?`@${encodeURIComponent(e.tag)}`:"";return`${FU}${encodeURIComponent(e.repo)}#${encodeURIComponent(e.asset)}${t}`}function LU(e){if(!e.startsWith(FU))return null;const t=e.slice(18),r=t.indexOf("#");if(r<0)return null;const n=decodeURIComponent(t.slice(0,r)),o=t.slice(r+1),s=o.lastIndexOf("@");return{repo:n,asset:s>=0?decodeURIComponent(o.slice(0,s)):decodeURIComponent(o),tag:s>=0?decodeURIComponent(o.slice(s+1)):void 0}}const jU=/^[0-9a-f]{7,40}$/i;function UU(e){let t;try{t=kU(e)}catch{return null}return`${t.host}\0${t.pathSegments.join("\0")}`}function BU(e,t){if(e.trim()===t.trim())return!0;const r=UU(e),n=UU(t);return null!==r&&r===n}const WU=104857600;async function HU(e,t,r,n,i,a){const c=await async function(e){const{repo:t,asset:r,tag:n}=e,{apiBase:o,ownerRepo:s,host:i}=function(e){const t=e.split("/"),r=t[0],n=t[1],o=t[2];if(3===t.length&&void 0!==r&&void 0!==n&&void 0!==o)return{apiBase:`https://${r}/api/v3`,ownerRepo:`${n}/${o}`,host:r};if(2===t.length)return{apiBase:"https://api.github.com",ownerRepo:e,host:"github.com"};throw new Error(`Invalid release repo format: ${e}`)}(t),a="github.com"===i&&void 0!==e.githubToken&&e.githubToken.length>0?{Authorization:`token ${e.githubToken}`}:{},c=n?`${o}/repos/${s}/releases/tags/${encodeURIComponent(n)}`:`${o}/repos/${s}/releases/latest`,l=await fetch(c,{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"CursorPluginInstaller",...a}});if(!l.ok)throw new Error(`Failed to fetch release from ${c}: ${l.status} ${l.statusText}`);const u=await l.json();if(!(xU(d=u)&&Array.isArray(d.assets)&&d.assets.every((e=>xU(e)&&"string"==typeof e.name&&"string"==typeof e.browser_download_url&&"number"==typeof e.size))))throw new Error(`Release payload from ${c} did not include assets`);var d;const h=u,p=h.assets.find((e=>e.name===r));if(!p){const e=h.assets.map((e=>e.name)).join(", ");throw new Error(`Release asset "${r}" not found. Available assets: ${e}`)}if(p.size>WU)throw new Error(`Release asset "${r}" exceeds maximum size of 104857600 bytes (actual: ${p.size})`);const f=new URL(p.browser_download_url);if("https:"!==f.protocol||!qU(f.hostname,i))throw new Error(`Refusing to download release asset from untrusted host: ${f.hostname}`);const m=await fetch(p.browser_download_url,{headers:{"User-Agent":"CursorPluginInstaller",Accept:"application/octet-stream",...a}});if(!m.ok)throw new Error(`Failed to download release asset: ${m.status} ${m.statusText}`);if(m.url){const e=new URL(m.url);if("https:"!==e.protocol||!qU(e.hostname,i))throw new Error(`Refusing to download release asset: redirected to untrusted host: ${e.hostname}`)}const g=Buffer.from(await m.arrayBuffer());if(g.byteLength>WU)throw new Error(`Release asset "${r}" actual download size exceeds maximum of 104857600 bytes (actual: ${g.byteLength})`);if(e.expectedSha256){const t=(0,bo.createHash)("sha256").update(g).digest("hex");if(t!==e.expectedSha256)throw new Error(`Release asset "${r}" integrity check failed: expected SHA-256 ${e.expectedSha256}, got ${t}`)}return g}({repo:e,asset:t,tag:r,expectedSha256:i,githubToken:a}),l=c.byteLength;await(0,Co.mkdir)(n,{recursive:!0});const u=await(0,Co.mkdtemp)((0,s.join)((0,o.tmpdir)(),"release-asset-")),d=(0,s.join)(u,"asset.tar.gz"),h=(0,s.join)(u,"extracted");try{await(0,Co.writeFile)(d,c),await(0,Co.mkdir)(h,{recursive:!0});let e=0,t=0;await sh.x({file:d,cwd:h,onReadEntry:r=>{if(t++,t>5e4)throw new Error("Release archive contains too many files (>50000).");if(e+=r.size,e>524288e3)throw new Error("Release archive uncompressed size exceeds maximum of 524288000 bytes.");if(l>0&&e/l>100)throw new Error("Release archive has suspicious compression ratio (>100x).")}});const r=await(0,Co.readdir)(h,{withFileTypes:!0}),o=r.filter((e=>e.isDirectory())),i=r.filter((e=>e.isFile()));let a=h;const u=o[0];if(1===o.length&&0===i.length&&void 0!==u){const e=(0,s.join)(h,u.name);(await(0,Co.readdir)(e)).some((e=>qh.includes(e)))&&(a=e)}const p=await(0,Co.readdir)(a);await Promise.all(p.map((e=>(0,Co.cp)((0,s.join)(a,e),(0,s.join)(n,e),{recursive:!0,verbatimSymlinks:!0}))))}finally{await(0,Co.rm)(u,{recursive:!0,force:!0}).catch((()=>{}))}}function qU(e,t){return!(e!==t&&!e.endsWith(".githubusercontent.com"))||("github.com"===t?"github.com"===e:e.endsWith(`.${t}`))}class zU{constructor(e,t,r,n,o){this.getEffectiveUserPlugins=e;const s="string"==typeof t||void 0===t?{marketplaceCacheRoot:t,pluginLogger:r,marketplaceCacheOptions:n,listOptions:o}:t,i=s.marketplaceCacheOptions??n;this.pluginLogger=s.pluginLogger??r??Tp,this.extraGitConfig=s.extraGitConfig,this.awaitAuthReady=s.awaitAuthReady,this.githubToken=s.githubToken,this.downloadPluginContent=s.downloadPluginContent,this.contentRetries=s.contentRetries??(new _h).forListing(""),this.sparsePluginClones=s.sparsePluginClones??!1,this.marketplaceCache=s.marketplaceCacheRoot?new CU(s.marketplaceCacheRoot,{...i,extraGitConfig:i?.extraGitConfig??s.extraGitConfig,sparsePluginClones:this.sparsePluginClones}):void 0;const a=s.listOptions??o;this.allowedMarketplaceNames=a?.allowedMarketplaceNames?new Set(a.allowedMarketplaceNames):void 0,this.enableInlinePlugins=a?.enableInlinePlugins??!1}isMarketplaceAllowed(e){return void 0===this.allowedMarketplaceNames||void 0!==e?.name&&this.allowedMarketplaceNames.has(e.name)}async listEnabledPlugins(e,t){const r=await this.getEffectiveUserPlugins(),n=r.plugins??[],o=r.marketplaces??[],s=[],i=[],a=new Map,c=async(e,t)=>{const r=`${e}\0${t}`;let n=a.get(r);if(!n){const o=Mj(this.extraGitConfig),s=this.sparsePluginClones?3e4:void 0,i=e.startsWith("git@")||e.startsWith("ssh://")?null:aU(e),c=async(e,r)=>{const n={};return r&&(n.sshBatchMode=!0),void 0!==o&&(n.extraGitConfig=o),void 0!==s&&(n.timeoutMs=s),(Object.keys(n).length>0?await Lj(e,t,n):await Lj(e,t)).fullSha};if(null!==i)try{n=await c(i,!0)}catch(t){if(this.sparsePluginClones&&bU(t))throw t;n=await c(e,!1)}else n=await c(e,!1);a.set(r,n)}return n},l=async e=>{const{preferredGitUrl:t,sourceGitUrl:r,gitRef:n,pluginId:o}=e;if(t!==r){void 0!==this.awaitAuthReady&&await this.awaitAuthReady();const e=`${t}\0${n}`,s=!a.has(e);let i;s&&this.pluginLogger.increment("marketplace.origin_distribution.fetch",1);try{i={sha:await c(t,n),gitUrl:t}}catch(e){s&&this.pluginLogger.increment("marketplace.origin_distribution.fetch.error",1),this.pluginLogger.captureException(e,{error_type:"distribution_url_fallback"}),this.pluginLogger.log("warn",`Distribution mirror ${t}@${n} unavailable (not synced yet or unreachable); falling back to source ${r}`,{pluginId:o,preferredGitUrl:t,sourceGitUrl:r,gitRef:n,error:String(e)})}if(void 0!==i){if(s)try{this.pluginLogger.log("info",`Resolved plugin ${o} from Origin distribution mirror ${t}@${n}`,{pluginId:o,preferredGitUrl:t,gitRef:n})}catch{}return i}}return{sha:await c(r,n),gitUrl:r}};this.contentRetries.startLoad();for(const e of n){if(!e.isEnabled||!e.plugin?.name)continue;const t=e.plugin,r=IU(t,o);if(!this.isMarketplaceAllowed(r)){this.pluginLogger.log("info",`Skipping plugin ${t.name} because marketplace ${r?.name??""} is not allowed`,{pluginId:t.name,marketplaceName:r?.name,allowedMarketplaceNames:void 0!==this.allowedMarketplaceNames?Array.from(this.allowedMarketplaceNames):void 0});continue}const n=RU({name:t.name,pluginId:void 0!==t.id?String(t.id):t.name??""}),a=n;if(void 0!==t.backendContent&&null!==t.backendContent){const t=this.listBackendContentPlugin(e,r,n);"entry"in t?s.push(t.entry):i.push(t.failure);continue}if(!t.gitUrl){if(!this.enableInlinePlugins){this.pluginLogger.log("info",`Skipping plugin ${n} without gitUrl (enableInlinePlugins=false)`,{pluginId:a});continue}const o=e.inlineContentJson;if(!o){this.pluginLogger.log("info",`Skipping DB-inline plugin ${n}: no inline content provided`,{pluginId:a});continue}const i=(0,bo.createHash)("sha256").update(`${t.id??"0"}:${t.updatedAt??"0"}`).digest("hex").slice(0,40),c=r?.name?{id:void 0!==r.id?`${r.name}-${r.id}`:`${r.name}-inline`,name:r.name}:void 0;this.pluginLogger.log("info",`BackendMarketplaceClient: Adding DB-inline plugin: ${a}`,{pluginId:a,marketplaceId:c?.id??"unknown",version:i}),s.push({pluginId:a,pluginDbId:void 0!==t.id?String(t.id):void 0,configuredVariables:PU(e.configuredVariables),isTeamRequired:e.isTeamRequired,name:n,version:i,downloadUrl:`inline://${t.id??a}`,marketplaceDbId:void 0!==r?.id?String(r.id):void 0,marketplace:c,inlineContentJson:o});continue}const c=t.gitUrl,u=TU(c,r),d=$U(e,o),h=Cj(t,d),p=r?.gitRef??d;let f,m,g=u;try{if(void 0!==h)f=`release/${h.releaseTag}`;else{const e=await l({preferredGitUrl:u,sourceGitUrl:c,gitRef:d,pluginId:a});f=e.sha,g=e.gitUrl}}catch(e){this.pluginLogger.captureException(e,{error_type:"resolve_version_sha"}),this.pluginLogger.log("error",`Failed to resolve version for plugin ${n}@${d}, skipping plugin`,{pluginId:a,ref:d,error:String(e)});const o=e instanceof Error?e.message:String(e);i.push({pluginName:n,pluginId:a,pluginDbId:void 0!==t.id?String(t.id):void 0,marketplaceName:r?.name,errorMessage:o,errorType:/timed?\s*out/i.test(o)?"timeout":"clone"});continue}m=void 0!==h?NU({repo:h.releaseRepo,asset:h.releaseAsset,tag:h.releaseTag}):DU(g,d,t.gitPath??void 0);const w=AU(r);let y=w,v=r?.gitUrl,b=p;if(r?.gitUrl&&w){const e=BU(c,r.gitUrl),t=e?g:w,o=e?c:r.gitUrl,s=e?d:p;v=o;try{const e=await l({preferredGitUrl:t,sourceGitUrl:o,gitRef:s,pluginId:a});b=e.sha,y=e.gitUrl}catch(e){this.pluginLogger.captureException(e,{error_type:"resolve_marketplace_cache_ref"}),this.pluginLogger.log("warn",`Failed to resolve marketplace cache ref for plugin ${n} from ${t}@${s}, falling back to raw ref`,{pluginId:a,cacheRepoUrl:t,cacheRef:s,error:String(e)}),y=o}}const S=r?.name?{id:void 0!==r.id?`${r.name}-${r.id}`:`${r.name}-${encodeURIComponent(r.gitUrl??"project")}`,name:r.name,...y&&{gitUrl:y,gitRef:b}}:void 0,k=void 0!==h||g===c&&y===v?void 0:{downloadUrl:DU(c,d,t.gitPath??void 0),marketplaceGitUrl:v};this.pluginLogger.log("info",`BackendMarketplaceClient: Adding enabled plugin: ${a} from ${b} at ${t.gitPath}`,{pluginId:a,marketplaceId:S?.id??"unknown",gitPath:t.gitPath??void 0,gitRef:b}),s.push({pluginId:a,pluginDbId:void 0!==t.id?String(t.id):void 0,configuredVariables:PU(e.configuredVariables),isTeamRequired:e.isTeamRequired,name:n,version:f,downloadUrl:m,marketplaceDbId:void 0!==r?.id?String(r.id):void 0,marketplace:S,gitPath:t.gitPath??void 0,isOriginBacked:void 0===h&&g!==c||void 0,originSourceFallback:k})}return{plugins:s,listFailures:i}}isBackendContentRetryDue(){return this.contentRetries.isRetryDue()}allowImmediateBackendContentRetry(){this.contentRetries.allowImmediateRetry()}listBackendContentPlugin(e,t,r){const n=Ch(e.plugin?.id),o=function(e){const{revision:t}=e;return"string"==typeof t&&mh.test(t)?{revision:t}:{invalid:"revision"}}(e.plugin?.backendContent??{}),s=void 0===n?"plugin_id":"invalid"in o?o.invalid:void 0;if(void 0===n||"invalid"in o)return this.pluginLogger.log("error",`Skipping plugin ${r}: the listing's backend content has an unusable ${s}`,{pluginId:r,invalidField:s}),this.pluginLogger.increment("backend_marketplace_client.backend_content.list.invalid",1),{failure:{pluginName:r,pluginId:r,pluginDbId:n,marketplaceName:t?.name,errorMessage:`Plugin ${JSON.stringify(r)} could not be installed: the server listed it with details this client does not accept.`,errorType:"install"}};const i=t?.name?{id:void 0!==t.id?`${t.name}-${t.id}`:`${t.name}-backend-content`,name:t.name}:void 0;return this.pluginLogger.log("info",`BackendMarketplaceClient: Adding backend-served plugin: ${r}`,{pluginId:r,marketplaceId:i?.id??"unknown",revision:o.revision}),{entry:{pluginId:r,pluginDbId:n,configuredVariables:PU(e.configuredVariables),isTeamRequired:e.isTeamRequired,name:r,version:xh(o.revision),downloadUrl:(a={pluginDbId:n,revision:o.revision},`${yh}${a.pluginDbId}@${a.revision}`),marketplaceDbId:void 0!==t?.id?String(t.id):void 0,marketplace:i,backendContent:o}};var a}async relistPlugin(e){if(void 0===e.backendContent||void 0===e.pluginDbId)return;const t=await this.getEffectiveUserPlugins(),r=(t.plugins??[]).find((t=>!0===t.isEnabled&&Ch(t.plugin?.id)===e.pluginDbId)),n=r?.plugin;if(void 0===r||!n?.name||void 0===n.backendContent||null===n.backendContent)return;const o=IU(n,t.marketplaces??[]);if(!this.isMarketplaceAllowed(o))return;const s=this.listBackendContentPlugin(r,o,e.name);return"entry"in s&&s.entry.version!==e.version?s.entry:void 0}async installBackendContentPlugin(e,t){const r=e.backendContent,n=Ch(e.pluginDbId);if(void 0===r||void 0===n)throw new Error(`Plugin ${JSON.stringify(e.name)} has no backend content to install`);const o={pluginDbId:n,revision:r.revision},s=this.contentRetries.heldFailure(o);if(void 0!==s)throw Ph(s,e.name);const i=performance.now();let a="success";try{await Ih({download:this.downloadPluginContent,pluginDbId:n,pluginName:e.name,content:r,targetDir:t}),this.contentRetries.recordAttempt(o)}catch(e){throw a=e instanceof ph?e.reason:"unknown",this.contentRetries.recordAttempt({...o,error:e}),e}finally{this.pluginLogger.increment("backend_marketplace_client.backend_content.install",1,{outcome:a}),this.pluginLogger.distribution("backend_marketplace_client.backend_content.install.duration",performance.now()-i,{outcome:a})}this.pluginLogger.log("info",`Installed backend-served plugin ${e.pluginId}`,{pluginId:e.pluginId,revision:r.revision})}isDirectInstallSameFetch(e){const t=e.marketplace;if(!t?.gitUrl||!t.gitRef)return!1;const r=OU(e.downloadUrl);return!(!r||!BU(r.gitUrl,t.gitUrl)||r.ref!==t.gitRef&&e.version!==t.gitRef)}async installPlugin(e,t){if(void 0!==e.backendContent||Eh(e.downloadUrl))await this.installBackendContentPlugin(e,t);else if(e.inlineContentJson)await async function(e){const{targetDir:t,inlineContentJson:r,pluginName:n}=e,o=JSON.parse(r);await(0,Co.mkdir)(t,{recursive:!0});const i={};if(o.rules&&o.rules.length>0){const e=(0,s.join)(t,"rules");await(0,Co.mkdir)(e,{recursive:!0});const r=[];for(const t of o.rules){if(!t.content)continue;if(!1===t.isActive)continue;const n=`${oh(t.name)}.md`,o=[];o.push(`description: ${uU(t.name)}`),t.globs&&t.globs.length>0&&o.push(`globs: ${uU(t.globs.join(", "))}`),o.push(`alwaysApply: ${!0===t.isRequired}`);const i=`---\n${o.join("\n")}\n---\n\n`;await(0,Co.writeFile)((0,s.join)(e,n),i+t.content,"utf-8"),r.push(`rules/${n}`)}r.length>0&&(i.rules=r)}if(o.commands&&o.commands.length>0){const e=(0,s.join)(t,"commands");await(0,Co.mkdir)(e,{recursive:!0});const r=[];for(const t of o.commands){if(!t.content)continue;if(!1===t.isActive)continue;const n=`${oh(t.name)}.md`,o=t.description?`---\ndescription: ${uU(t.description)}\n---\n\n`:"";await(0,Co.writeFile)((0,s.join)(e,n),o+t.content,"utf-8"),r.push(`commands/${n}`)}r.length>0&&(i.commands=r)}if(o.hooks&&o.hooks.length>0){const e=(0,s.join)(t,"hooks");await(0,Co.mkdir)(e,{recursive:!0});const r={};for(const e of o.hooks){const t=e.hookStep;t&&!1!==e.isActive&&lU(e)&&(r[t]||(r[t]=[]),"prompt"===e.hookType?r[t].push({type:"prompt",prompt:e.promptContent??"",...e.promptModel?{model:e.promptModel}:{}}):r[t].push({type:"command",command:e.scriptContent??""}))}await(0,Co.writeFile)((0,s.join)(e,"hooks.json"),JSON.stringify({version:1,hooks:r},null,2),"utf-8")}if(o.mcpServers&&o.mcpServers.length>0){const e={};for(const t of o.mcpServers)t.config&&(e[t.name]=t.config);Object.keys(e).length>0&&await(0,Co.writeFile)((0,s.join)(t,".mcp.json"),JSON.stringify({mcpServers:e},null,2),"utf-8")}const a={name:n,...i},c=(0,s.join)(t,".cursor-plugin");await(0,Co.mkdir)(c,{recursive:!0}),await(0,Co.writeFile)((0,s.join)(c,"plugin.json"),JSON.stringify(a,null,2),"utf-8")}({targetDir:t,inlineContentJson:e.inlineContentJson,pluginName:e.name});else{e.isOriginBacked&&void 0!==this.awaitAuthReady&&await this.awaitAuthReady();try{return void await this.installFromEntryUrls(e,t)}catch(r){const n=function(e){const t=e.originSourceFallback;if(void 0===t)return;let r=e.marketplace;if(void 0!==r)if(void 0!==t.marketplaceGitUrl)r={...r,gitUrl:t.marketplaceGitUrl};else{const{gitUrl:e,gitRef:t,...n}=r;r=n}return{...e,downloadUrl:t.downloadUrl,marketplace:r,isOriginBacked:void 0,originSourceFallback:void 0}}(e);if(void 0===n)throw r;this.pluginLogger.captureException(r,{error_type:"install_plugin_from_origin_distribution"}),this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from the Origin distribution mirror, falling back to the source repo`,{pluginId:e.pluginId,version:e.version,sourceDownloadUrl:n.downloadUrl,sourceMarketplaceGitUrl:n.marketplace?.gitUrl,error:String(r)}),this.pluginLogger.increment("marketplace.origin_distribution.install.source_fallback",1),await(0,Co.rm)(t,{recursive:!0,force:!0});try{await this.installFromEntryUrls(n,t)}catch(e){throw this.pluginLogger.increment("marketplace.origin_distribution.install.source_fallback.error",1),e}}}}async installFromEntryUrls(e,t){if(null===LU(e.downloadUrl))try{if(await this.tryInstallFromMarketplaceCache(e,t))return void this.emitOriginLoadIfApplicable(e)}catch(t){if(this.pluginLogger.captureException(t,{error_type:"install_plugin_from_marketplace_cache"}),this.sparsePluginClones&&this.isDirectInstallSameFetch(e)&&bU(t))throw this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from marketplace cache; skipping direct install fallback because it would repeat the identical fetch`,{pluginId:e.pluginId,version:e.version,error:String(t)}),t;this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from marketplace cache, falling back to direct install`,{pluginId:e.pluginId,version:e.version,error:String(t)})}await async function(e,t,r=Tp,n,i){const a=i?.sparsePluginClones??!1,c=a?pU:void 0,l=LU(e.downloadUrl);if(l){if(e.gitPath){const r=await(0,Co.mkdtemp)((0,s.join)((0,o.tmpdir)(),"release-plugin-"));try{await HU(l.repo,l.asset,l.tag,r,i?.expectedReleaseAssetSha256,i?.githubToken);const n=vf(r,e.gitPath);await(0,Co.mkdir)(t,{recursive:!0}),await(0,Co.cp)(n,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,Co.rm)(r,{recursive:!0,force:!0}).catch((()=>{}))}}else await HU(l.repo,l.asset,l.tag,t,i?.expectedReleaseAssetSha256,i?.githubToken);return}const u=OU(e.downloadUrl);if(!u)throw new Error(`Invalid download URL format for plugin ${e.pluginId}: ${e.downloadUrl}`);const d=await(0,Co.mkdtemp)((0,s.join)((0,o.tmpdir)(),"backend-plugin-"));try{let o;if(await async function(e,t,r,n=Tp,o,s="all",i=!1){const a=performance.now(),c=jU.test(t),l="HEAD"===t.toUpperCase(),u={...o,"safe.directory":r},d=i?pU:void 0,h=i?fU:void 0,{sparse:p,sparseDirs:f}=await Hj(s,i),m=p?["--filter=blob:none","--sparse"]:[],g=!!p||void 0,w=async e=>{p&&await zj(r,f,{extraGitConfig:u,timeoutMs:e,sshBatchMode:!0})},y=async(e,n)=>{let o;return l?(({stderr:o}=await Dj(["clone","--depth","1",...m,e,r],{extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await w(d)):c?(await Dj(["init"],{cwd:r,extraGitConfig:u,timeoutMs:h}),await Dj(["remote","add","origin",e],{cwd:r,extraGitConfig:u,timeoutMs:h}),await w(h),({stderr:o}=await Dj(["fetch","--depth","1",...p?["--filter=blob:none"]:[],"origin",t],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await Dj(["checkout","FETCH_HEAD"],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})):(({stderr:o}=await Dj(["clone","--depth","1","--branch",t,...m,e,r],{extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await w(d)),o},v=e.startsWith("git@")||e.startsWith("ssh://")?null:aU(e);let b;if(null!==v)try{b=await y(v,!0)}catch(t){if(i&&bU(t))throw t;await(0,Co.rm)(r,{recursive:!0,force:!0}),await(0,Co.mkdir)(r,{recursive:!0}),b=await y(e,g)}else b=await y(e,g);p&&qj(b)&&(n.log("warn",`shallowClone: server ignored --filter=blob:none for ${e}; sparse clone downloaded a full pack`),n.increment("backend_marketplace_client.shallow_clone.filter_ignored_by_server",1));const S=(performance.now()-a).toFixed(1);EU("shallowClone %s@%s completed in %sms",e,t,S),n.log("info",`shallowClone ${e}@${t} completed in ${S}ms (${p?"sparse":"full"})`)}(u.gitUrl,u.ref,d,r,n,u.gitPath?Wj([u.gitPath]):[],a),u.gitPath)o=vf(d,u.gitPath);else{const t=await async function(e,t){for(const r of zh){const n=(0,s.join)(e,r);let o;try{o=await(0,Co.readFile)(n,"utf-8")}catch{continue}const i=bp(o);if(!i.success)return{type:"manifest-unresolved",reason:`Invalid marketplace manifest at ${r}: ${i.error}`};const a=i.data,c=a.plugins.find((e=>e.name===t.toLowerCase()));if(!c)return{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} not found in ${r}`};if("string"!=typeof c.source&&"git-subdir"===c.source.source)return{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} uses unsupported git-subdir source`};const l=kp(c.source,a.metadata?.pluginRoot);return l&&_p(l)?{type:"resolved",gitPath:l}:{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} has unresolved or unsafe source path`}}return{type:"no-manifest"}}(d,e.name);if("resolved"===t.type)await Vj(d,Wj([t.gitPath]),{extraGitConfig:n,timeoutMs:c}),o=vf(d,t.gitPath);else{if("manifest-unresolved"===t.type)throw new Error(`Unable to install plugin ${JSON.stringify(e.name)} without gitPath: ${t.reason}`);await Vj(d,"all",{extraGitConfig:n,timeoutMs:c}),o=d}}await(0,Co.mkdir)(t,{recursive:!0}),await(0,Co.cp)(o,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,Co.rm)(d,{recursive:!0,force:!0}).catch((()=>{}))}}(e,t,this.pluginLogger,Mj(this.extraGitConfig),{githubToken:this.githubToken,sparsePluginClones:this.sparsePluginClones}),this.emitOriginLoadIfApplicable(e)}emitOriginLoadIfApplicable(e){if(e.isOriginBacked)try{this.pluginLogger.increment("marketplace.origin_distribution.load",1),this.pluginLogger.log("info",`Loaded plugin ${e.pluginId} from Origin distribution (fetch complete)`,{pluginId:e.pluginId})}catch{}}async prewarmMarketplaceClones(e){const t=this.marketplaceCache;if(!t)return;const r=new Map;for(const t of e){const e=t.marketplace;if(!e?.gitUrl)continue;const n=e.gitRef??"main",o=`${e.id}\0${e.gitUrl}\0${n}`;let s=r.get(o);void 0===s&&(s={marketplaceId:e.id,gitUrl:e.gitUrl,gitRef:n,gitPaths:[]},r.set(o,s)),t.gitPath&&s.gitPaths.push(t.gitPath)}for(const e of r.values()){const r=Wj(e.gitPaths),n=performance.now();try{await t.ensureCloned(e.marketplaceId,e.gitUrl,e.gitRef,this.pluginLogger,{materialize:r}),this.pluginLogger.log("info",`Prewarmed marketplace clone ${e.gitUrl}@${e.gitRef} for ${e.gitPaths.length} plugin directories`,{marketplaceId:e.marketplaceId,gitUrl:e.gitUrl,gitRef:e.gitRef,requestedDirs:e.gitPaths.length,materialize:"all"===r?"all":r.length}),this.pluginLogger.increment("marketplace_cache_manager.prewarm.success",1,{materialize:"all"===r?"all":"dirs"})}catch(t){this.pluginLogger.captureException(t,{error_type:"prewarm_marketplace_clone"}),this.pluginLogger.log("warn",`Failed to prewarm marketplace clone ${e.gitUrl}@${e.gitRef}; falling back to per-plugin materialization`,{marketplaceId:e.marketplaceId,gitUrl:e.gitUrl,gitRef:e.gitRef,error:String(t)}),this.pluginLogger.increment("marketplace_cache_manager.prewarm.error",1)}this.pluginLogger.distribution("marketplace_cache_manager.prewarm.duration",performance.now()-n)}}async tryInstallFromMarketplaceCache(e,t){const r=this.marketplaceCache,n=e.marketplace;if(!r||!n||!n.gitUrl)return this.pluginLogger.log("info","No marketplace cache or marketplace metadata, skipping cache check",{pluginId:e.pluginId,name:e.name,version:e.version,marketplaceId:e.marketplace?.id}),!1;const o=await r.ensureCloned(n.id,n.gitUrl,n.gitRef??"main",this.pluginLogger,{materialize:e.gitPath?Wj([e.gitPath]):[]}),s=e.gitPath??await r.resolvePluginPath(o,e.name);if(!s)return this.pluginLogger.log("info","No git path found for plugin, skipping cache check",{pluginId:e.pluginId,name:e.name,version:e.version,marketplaceId:e.marketplace?.id}),!1;void 0===e.gitPath&&await r.ensureMaterialized(o,Wj([s]),this.pluginLogger);const i=r.getPluginDir(o,s);return await r.copyPluginToDir(i,t),!0}async discoverMarketplacePlugins(e,t,r){const n=this.marketplaceCache;if(!n)throw new Error("discoverMarketplacePlugins requires a MarketplaceCacheManager (marketplaceCacheRoot)");const o=await n.ensureCloned(e,t,r,this.pluginLogger,{materialize:[]});return n.discoverPlugins(o)}}function GU(e,t,r,n,o){return new zU(e,t,r,n,o)}function VU(e){const t=e.trim();if(!t)return!1;if(t.startsWith("git@"))return/^git@[a-zA-Z0-9.-]+:[a-zA-Z0-9._~\-/]+(?:\.git)?$/.test(t);try{const e=new URL(t);return"https:"===e.protocol&&""===e.username&&""===e.password&&""===e.search&&""===e.hash}catch{return!1}}class KU extends Error{constructor(e){super(e),this.name="SettingsParseError"}}function JU(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ZU(e){return 65279===e.charCodeAt(0)?e.slice(1):e}async function XU(e){try{return ZU(await(0,Co.readFile)(function(e){return(0,s.join)(e,".cursor","settings.json")}(e),"utf-8"))}catch(e){if(function(e){return e instanceof Error&&"code"in e}(e)&&("ENOENT"===e.code||"ENOTDIR"===e.code))return;throw e}}async function QU(e){const t=await XU(e);return void 0===t?[]:function(e){const t=function(e){const t=ZU(e);if(0===t.trim().length)return{};const r=[],n=(0,Cp.qg)(t,r,{allowTrailingComma:!0});if(r.length>0){const e=r.slice(0,3).map((e=>`${(0,Cp._n)(e.error)} at offset ${e.offset}`)).join("; ");throw new KU(`.cursor/settings.json contains syntax errors: ${e}`)}if(!JU(n))return{};const o=n.plugins;if(void 0===o)return{};if(!JU(o))return{};const s={};for(const[e,t]of Object.entries(o))JU(t)&&(s[e]=t);return{plugins:s}}(e);return t.plugins?Object.entries(t.plugins).filter((([,e])=>!0===e.enabled)).filter((([,e])=>!e.gitUrl||VU(e.gitUrl))).map((([e,t])=>({key:e,entry:t}))):[]}(t)}function YU(e){const t=e.indexOf("/");return-1===t?{name:e}:{name:e.slice(t+1),marketplaceName:e.slice(0,t)}}const eB={supportsBackendContent:!0};function tB(e={}){const t=e.userHomeDirectory??(0,o.homedir)(),r=e.importThirdPartyPlugins??!1,n=e.pluginLogger??{log(e,t,r){switch(e){case"warn":SO.Jz.warn("[local-plugins-bootstrap]",t,r??{});break;case"error":SO.Jz.error("[local-plugins-bootstrap]",t,r??{})}},increment(){},distribution(){},captureException(e,t){SO.Jz.error("[local-plugins-bootstrap] Unexpected plugin exception:",e,t??{})}},i=rB(e.marketplaceOptions),a=void 0!==e.dashboardTransport,c=e.loadCursorFirstParty??(i||a);return{async loadPluginBootstrapOutputs(o){const i=(a=o.workspaceState).projectRoot??a.workspaceRoots[0]??a.workingDirectory;var a;const{discoveredEntries:l,failures:u}=await async function(e){if(void 0===e)return{discoveredEntries:[],failures:[]};try{return{discoveredEntries:(await QU(e)).map((({key:t,entry:r})=>({source:"project-settings",workspacePath:e,key:t,entry:r}))),failures:[]}}catch(e){return{discoveredEntries:[],failures:[{stage:"discovery",source:"project-settings",message:e instanceof Error?`Failed to read project plugin settings: ${e.message}`:`Failed to read project plugin settings: ${String(e)}`,detail:e}]}}}(i),d=e.marketplaceOptions??(e.dashboardTransport?function(e){const t=(0,s.join)(e.userHomeDirectory,".cursor","plugins","marketplaces"),r=(0,ye.createClient)(fj.I,e.dashboardTransport),n=(e,{signal:t})=>r.downloadPluginContent(e,{signal:t}),o=new _h,i=GU((async()=>{try{return await r.getEffectiveUserPlugins(new JD.EwF(eB))}catch{return{plugins:[]}}}),{marketplaceCacheRoot:t,listOptions:{allowedMarketplaceNames:["cursor-public"]},downloadPluginContent:n,contentRetries:o.forListing("account")}),a=e.workspacePath,c=GU((async()=>{if(void 0===a)return{plugins:[]};try{const e=await QU(a);if(0===e.length)return{plugins:[]};const t=e.filter((e=>e.entry.gitUrl)),n=e.filter((e=>!e.entry.gitUrl)),o=t.filter((({entry:e})=>{const t=e.gitUrl;return!t||VU(t)})).map((({key:e,entry:t})=>{const r=YU(e),n=t.gitUrl;return{plugin:{name:r.name,gitUrl:n,gitRef:t.gitRef,gitPath:t.gitPath,marketplace:{name:r.marketplaceName,gitUrl:n,gitRef:t.gitRef}},isEnabled:!0}}));let s=[];if(n.length>0)try{const e=n.map((e=>{const t=YU(e.key);return new JD.vwy({name:t.name,marketplaceName:t.marketplaceName})})),t=await r.resolvePluginsByRef(new JD.WvV({refs:e,...eB}));s=t.plugins?.map((e=>({plugin:e,isEnabled:!0})))??[]}catch{}return{plugins:[...o,...s]}}catch{return{plugins:[]}}}),{marketplaceCacheRoot:t,listOptions:{allowedMarketplaceNames:["cursor-public"]},downloadPluginContent:n,contentRetries:o.forListing("project")});return[{client:i,userId:"",cacheManager:new hh(e.userHomeDirectory),pruneOldVersions:!0},{client:c,userId:"",cacheManager:new hh(e.userHomeDirectory),pruneOldVersions:!0}]}({dashboardTransport:e.dashboardTransport,workspacePath:i,userHomeDirectory:t}):void 0),h=rB(d),p=new UD(void 0!==i?[i]:[],t,(()=>({importThirdPartyPlugins:r,loadCursorFirstParty:c})),d,n);let f=[];const m=[...u];try{f=await p.getAllEnabledPlugins()}catch(e){m.push({stage:"resolution",source:"plugin-loader",message:e instanceof Error?`Failed to load plugins: ${e.message}`:`Failed to load plugins: ${String(e)}`,detail:e})}l.length>0&&!h&&m.push({stage:"resolution",source:"plugin-loader",message:"Project plugin entries were discovered, but no marketplace-backed project plugin source was configured. Those entries remain available through discoveredEntries only.",detail:{workspacePath:i,discoveredEntryCount:l.length}});const g={kind:BO,discoveredEntries:l,loadedPlugins:f,loadFailures:p.getLoadFailures(),bootstrapFailures:m,pluginsService:p,async dispose(){}};for(const e of m)SO.Jz.warn("[local-plugins-bootstrap] Plugin bootstrap failure:",{workspacePath:i,stage:e.stage,source:e.source,message:e.message,detail:e.detail});for(const e of g.loadFailures)SO.Jz.warn("[local-plugins-bootstrap] Plugin load failure:",{workspacePath:i,pluginName:e.pluginName,pluginId:e.pluginId,marketplaceName:e.marketplaceName,errorType:e.errorType,errorMessage:e.errorMessage});return[g]}}}function rB(e){return void 0!==e&&(!Array.isArray(e)||e.length>0)}class nB{async getAllCursorRules(e){return[]}reload(e){}dispose(){}onDidChangeRules(e){return()=>{}}}const oB=["projectFolder","terminalsFolder","agentSharedNotesFolder","agentConversationNotesFolder","agentTranscriptsFolder","processWorkingDirectory","artifactsFolder"];function sB(e){if(e.length<=1)return e;let t=e.length;for(;t>1&&("/"===(r=e[t-1])||"\\"===r)&&(3!==t||":"!==e[1]);)t-=1;var r;return e.slice(0,t)}function iB(e){const t=sB(e).replaceAll("\\","/");return/^[A-Za-z]:\/$/.test(t)?t.slice(0,-1):t}function aB(e){const t=sB(e.reportedWorkspacePath);if(""===e.suffix)return t;const r=t.replaceAll("\\","/"),n="/"===r?e.suffix:`${r}${e.suffix}`;return t.includes("\\")?n.replaceAll("/","\\"):n}function cB(e){const t=iB(e.value),r=e.roots.filter((e=>e.host.length>0)).sort(((e,t)=>iB(t.host).length-iB(e.host).length));for(const e of r){const r=iB(e.host);if(t===r)return aB({reportedWorkspacePath:e.reported,suffix:""});const n="/"===r?"/":`${r}/`;if(t.startsWith(n)){const n="/"===r?t:t.slice(r.length);return aB({reportedWorkspacePath:e.reported,suffix:n})}}}const lB={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1};class uB extends sD{constructor(e,t){super(e),this.sessionMcpLease=t}async dispose(){try{await super.dispose()}finally{await mj(this.sessionMcpLease)}}}function dB(e){const t=new _y;return{async createResources(r){const n=e.createSessionDependencies?.(r)??{pendingDecisionStore:e.pendingDecisionStore,fileChangeTracker:e.fileChangeTracker,permissionsService:e.permissionsService};if(!n.pendingDecisionStore||!n.fileChangeTracker||!n.permissionsService)throw new Error("Local resource provider factory requires either shared dependencies or a per-session dependency factory.");const o=r.workspaceServices.cursorRulesService??new nB,s=r.workspaceServices.subagentsService??new Sg,i=r.workspaceServices.mcpLease??new tI,a=!0===r.options.excludeProjectMcp,c=void 0!==r.options.mcpServersOverride||a?void 0!==e.createSessionMcpLease?await e.createSessionMcpLease(r,r.options.mcpServersOverride):a?new tI:void 0:void 0,l=(u=c??i,0===(d=r.options.extraMcpTools??[]).length?u:"onDidChange"in(h=u)&&"function"==typeof h.onDidChange?new zw(u,d):new qw(u,d));var u,d,h;try{const i=await async function(e,t){return void 0===e?{}:"function"==typeof e?await e({sessionId:t.sessionState.sessionId,metadata:t.metadata}):e}(r.options.localResourceProviderOptions,r),a=await async function(e){if(void 0===e)return lB;try{const t=await e();return{powershellUtf8Console:t.powershellUtf8Console,powershellUtf8ChildEnv:t.powershellUtf8ChildEnv}}catch{return lB}}(e.getPowershellUtf8Options),u={pendingDecisionStore:n.pendingDecisionStore,fileChangeTracker:n.fileChangeTracker,gitExecutor:t,ignoreService:e.ignoreService,grepProvider:e.grepProvider,permissionsService:n.permissionsService,workspacePaths:e.workspacePaths,diagnosticsProvider:e.diagnosticsProvider,mcpLease:l,mcpStateAccessor:e.createMcpStateAccessor?.(l,r.options),cursorRulesService:o,subagentsService:s,repositoryProvider:e.repositoryProvider,projectDir:e.projectDir,shellManager:e.shellManager,_defaultSandboxPolicy:e.defaultSandboxPolicy??{type:"insecure_none"},_defaultSandboxPolicySources:e.defaultSandboxPolicySources,getSandboxEnabled:e.getSandboxEnabled,getSandboxSupported:e.getSandboxSupported,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:e.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:e.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:e.getMockPromptTime,mcpFileOutputThresholdBytes:e.mcpFileOutputThresholdBytes,mcpMetaToolEnabled:e.mcpMetaToolEnabled,attributionConfigProvider:e.attributionConfigProvider,getAgentSkills:r.workspaceServices.getAgentSkills,powershellUtf8Console:a.powershellUtf8Console,powershellUtf8ChildEnv:a.powershellUtf8ChildEnv,...i},d=void 0===c?new sD(u):new uB(u,c);return void 0===r.options.reportedWorkspacePath&&void 0===r.options.reportedProjectFolder||function(e,t){const r=e.get($r);if(void 0===r)return;const{reportedWorkspacePath:n,reportedProjectFolder:o}=t,s=void 0===n?[]:t.workspacePaths.map((e=>({host:e,reported:n}))),i=o??n;void 0!==i&&s.push({host:t.projectDir,reported:i}),e.register($r,{execute:async(e,t,o)=>function(e,t){if("success"!==e.result.case||void 0===e.result.value.requestContext?.env)return e;const r=e.clone();if("success"!==r.result.case)return e;const n=r.result.value.requestContext?.env;if(void 0===n)return r;const{roots:o,reportedWorkspacePath:s}=t;n.workspacePaths=n.workspacePaths.map((e=>cB({value:e,roots:o})??e));for(const e of oB){const t=n[e];if(void 0===t||""===t)continue;const r=cB({value:t,roots:o});n[e]="processWorkingDirectory"===e&&void 0!==s?r??sB(s):r??t}return r}(await r.execute(e,t,o),{roots:s,reportedWorkspacePath:n})})}(d,{reportedWorkspacePath:r.options.reportedWorkspacePath,reportedProjectFolder:r.options.reportedProjectFolder,workspacePaths:u.workspacePaths,projectDir:u.projectDir}),d}catch(e){throw await mj(c),e}}}}const hB=["cursorRulesService","getAgentSkills","subagentsService"],pB=new WeakSet;function fB(e){("object"==typeof e&&null!==e||"function"==typeof e)&&pB.add(e)}function mB(e){return("object"==typeof e&&null!==e||"function"==typeof e)&&pB.has(e)}function gB(e,t){const r=Object.keys(t).filter((e=>!hB.includes(e)));if(r.length>0)throw new Error(`Workspace service contributors may only provide ${hB.join(", ")}. Received unsupported service keys: ${r.join(", ")}.`);for(const r of hB)Object.hasOwn(t,r)&&(e[r]=t[r])}async function wB(e,t,r){const n={config:void 0,plugins:[],pluginBootstrapOutputs:[],cursorRulesService:void 0,getAgentSkills:void 0,subagentsService:void 0,mcpLease:void 0,hooksRuntime:void 0};try{n.config=e.config?await e.config.loadConfig(t):void 0,n.plugins=e.plugins?await e.plugins.loadPlugins(t):[];const o=()=>({workspaceState:t,policy:r,services:n});n.pluginBootstrapOutputs=e.pluginBootstrap?await e.pluginBootstrap.loadPluginBootstrapOutputs(o()):n.pluginBootstrapOutputs,n.mcpLease=e.mcp?await e.mcp.createLease(o()):void 0,n.hooksRuntime=e.hooks?await e.hooks.createHooksRuntime(o()):void 0,e.localExtensibility?.prepareLocalExtensibility&&await e.localExtensibility.prepareLocalExtensibility(o());const s=e.localExtensibility?await e.localExtensibility.loadLocalExtensibility(o()):void 0;void 0!==s&&(fB(s.cursorRulesService),fB(s.subagentsService),Object.assign(n,s));for(const t of e.workspaceServicesContributors??[]){const e=await t.contributeServices(o());void 0!==e&&gB(n,e)}return n}catch(t){try{await yB(n,{disposeLocalExtensibility:void 0===e.localExtensibility?void 0:()=>e.localExtensibility?.disposeLocalExtensibility?.()})}catch(e){throw function(e,t){return new AggregateError([t],"Workspace service loading failed and resource cleanup also failed.",{cause:e})}(t,e)}throw t}}async function yB(e,t){const r=t?.preserveSharedContributorsFrom;let n;const o=async e=>{try{await mj(e)}catch(e){n??=e}};if(e.subagentsService===r?.subagentsService||mB(e.subagentsService)||await o(e.subagentsService),e.cursorRulesService===r?.cursorRulesService||mB(e.cursorRulesService)||await o(e.cursorRulesService),t?.disposeLocalExtensibility)try{await t.disposeLocalExtensibility()}catch(e){n??=e}await o(e.hooksRuntime),await o(e.mcpLease);try{await async function(e){let t;for(let r=e.length-1;r>=0;r-=1)try{await mj(e[r])}catch(e){t??=e}if(void 0!==t)throw t}(e.pluginBootstrapOutputs)}catch(e){n??=e}if(void 0!==n)throw n}const vB=["project","user","team","mdm","plugins"],bB=new Set([...vB,"all"]);function SB(e){if(void 0===e||0===e.length)return _B([]);for(const t of e)if(!bB.has(t))throw new Error(`Unsupported setting source "${t}"`);if(e.includes("all")){if(e.length>1)throw new Error('settingSources cannot mix "all" with individual setting sources');return{..._B(vB),all:!0}}return _B(e.filter((e=>"all"!==e)))}function kB(e,t){return e[t]}function _B(e){const t=new Set(e);return{project:t.has("project"),user:t.has("user"),team:t.has("team"),mdm:t.has("mdm"),plugins:t.has("plugins"),all:!1}}const CB=Object.freeze({}),EB=Object.freeze({allowMcpServers:!0,allowPlugins:!0,allowBackgroundSessions:!0,requireMcpApproval:!1,maxParallelSessions:void 0,sandboxMode:void 0,metadata:CB});async function xB(e){const t=new Set;let r;for(let n=e.length-1;n>=0;n-=1){const o=e[n];if(!t.has(o)){t.add(o);try{await mj(o)}catch(e){r??=e}}}if(void 0!==r)throw r}async function PB(e={}){const t=function(e={}){return{workspace:e.workspace??yO,config:e.config,plugins:e.plugins,pluginBootstrap:e.pluginBootstrap,mcp:e.mcp,hooks:e.hooks,localExtensibility:e.localExtensibility,resourceFactory:e.resourceFactory,resourceWrappers:e.resourceWrappers,workspaceServicesContributors:e.workspaceServicesContributors,lifecycle:e.lifecycle}}(e.adapters),r=await t.workspace.resolveWorkspaceState({workingDirectory:e.workingDirectory,projectRoot:e.projectRoot,projectDirectory:e.projectDirectory,workspaceRoots:e.workspaceRoots}),n=await async function(e,t){return e.resolvePolicy(t)}(e.policyAdapter??function(e={}){const t=Object.freeze({...EB.metadata,...e.metadata}),r={...EB,...e,metadata:t};return{name:"permissive-sdk-local",resolvePolicy:()=>r}}(),{workspaceState:r});let o=await wB(t,r,n),s=!1,i=Promise.resolve();const a=e=>{const t=i.then(e);return i=t.catch((()=>{})),t},c=t.localExtensibility,l=void 0===c?void 0:()=>c.disposeLocalExtensibility?.();return{state:r,get services(){return o},policy:n,async createSessionRuntime(e={}){if(s)throw new Error("Cannot create a session runtime after the workspace runtime has been disposed.");return async function(e){const t={sessionId:e.options?.sessionId??(0,ge.C)(),createdAt:new Date},r=Object.freeze({...e.options?.metadata??{}}),n={options:e.options??{},workspaceState:e.workspaceState,workspaceServices:e.workspaceServices,policy:e.policy,sessionState:t,metadata:r,getAgentSkills:e.workspaceServices.getAgentSkills};let o,s;const i=[];try{o=e.adapters.resourceFactory?await e.adapters.resourceFactory.createResources(n):void 0,s=o,i.push(o);for(const t of e.adapters.resourceWrappers??[])s=await t.wrapResources({...n,baseResources:o,resources:s}),i.push(s);await(e.adapters.lifecycle?.onSessionCreated?.(t))}catch(e){try{await xB(i)}catch(t){throw function(e,t){return new AggregateError([t],"Session creation failed and resource cleanup also failed.",{cause:e})}(e,t)}throw e}let a=!1;return{state:t,resources:{base:o,wrapped:s},metadata:r,workspaceServices:e.workspaceServices,policy:e.policy,async dispose(){if(!a){a=!0;try{await xB(i)}finally{await(e.adapters.lifecycle?.onSessionDisposed?.(t))}}}}}({options:e,workspaceState:r,workspaceServices:o,policy:n,adapters:t})},async reload(){s||await a((async()=>{if(s)return;const e=o,i=await wB(t,r,n);s?await yB(i,{disposeLocalExtensibility:l}):(o=i,await yB(e,{preserveSharedContributorsFrom:i,disposeLocalExtensibility:l}),await(t.lifecycle?.onWorkspaceReload?.(r)))}))},async dispose(){s||(s=!0,await a((async()=>{try{await yB(o,{disposeLocalExtensibility:l})}finally{await(t.lifecycle?.dispose())}})))}}}class RB{async requestApproval(e){return{approved:!0}}}class IB{constructor(e,t,r,n){this.approvalMode=e,this.userConfiguredPolicy=t,this.teamSettingsService=r,this.respectAdminControls=n}async getPermissions(){const e=!(!this.respectAdminControls||"insecure_none"===this.userConfiguredPolicy.type)&&(await this.teamSettingsService.getSandboxingControls()).sandboxingDisabled;return{allow:[],deny:[],approvalMode:this.approvalMode,userConfiguredPolicy:e?{type:"insecure_none"}:this.userConfiguredPolicy}}async updatePermissions(){}}class TB{async open(e,t){}async getDiagnostics(e,t){return[]}}class AB{async getCodebaseReference(e,t){}}class $B{constructor(e,t){this.inner=e,this.allowlistReports=t}async getState(e){const t=await this.inner.getState(e);return await this.reportAllowlists(e),{...t,servers:t.servers.filter((e=>"needsAuth"!==e.status))}}async reportAllowlists(e){if(void 0===this.allowlistReports)return;const{mcpLease:t,onMcpAllowlistInUse:r,onMcpServerBlockedByAllowlist:n}=this.allowlistReports;let o;try{o=await t.getClients(e)}catch(e){return void SO.Jz.warn("[sdk-mcp-state] Could not read the MCP allowlist in use:",e)}for(const[e,t]of Object.entries(o))try{if(void 0!==r){const n=await(t.getAllowlistInUse?.());void 0!==n&&r({serverName:e,allowlist:n})}if(void 0!==n){const r=await(t.getAllowlistRefusal?.());void 0!==r&&n({serverName:e,refusal:r})}}catch(e){SO.Jz.warn("[sdk-mcp-state] Could not read the MCP allowlist in use:",e)}}}class MB{constructor(e){this.subagents=e.map((e=>new vg.zz({fullPath:`sdk-inline://${e.name}`,name:e.name,description:e.description,tools:[],model:e.model,prompt:e.prompt,permissionMode:vg.b$.DEFAULT,isBackground:!1,source:"sdk"})))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents}}class DB{constructor(e={}){this.options=e,this.states=new Map,this.runCounterBySession=new Map,this.dispatchQueueBySession=new Map,this.dispatchInProgress=new Set,this.releaseRequestedBySession=new Set}getState(e){return this.states.get(e)??{status:"idle"}}isBusy(e){return"idle"!==this.getState(e).status}startRun(e,t){const r=this.nextRunId(e);return this.enqueueEvent(e,{type:"startRun",runId:r,abort:t?.abort}),r}queueResume(e,t){this.enqueueEvent(e,{type:"queueResume",queuedResume:t.queuedResume,targetRunId:t.targetRunId,mergeQueuedResume:t.mergeQueuedResume})}finishRun(e,t){this.enqueueEvent(e,{type:"runFinished",runId:t})}clearQueuedResume(e){this.enqueueEvent(e,{type:"clearQueuedResume"})}abort(e){this.enqueueEvent(e,{type:"abort"})}release(e){this.enqueueEvent(e,{type:"release"})}nextRunId(e){const t=(this.runCounterBySession.get(e)??0)+1;return this.runCounterBySession.set(e,t),t}enqueueEvent(e,t){const r=this.dispatchQueueBySession.get(e)??[];r.push(t),this.dispatchQueueBySession.set(e,r),this.drainEventQueue(e)}drainEventQueue(e){if(this.dispatchInProgress.has(e))return;let t;this.dispatchInProgress.add(e);try{const r=this.dispatchQueueBySession.get(e);if(!r)return;for(;r.length>0;){const n=r.shift();if(n)try{this.processEvent(e,n)}catch(e){t??=e}}}finally{this.dispatchQueueBySession.delete(e),this.dispatchInProgress.delete(e)}if(t)throw t}processEvent(e,t){const r=this.getState(e),{nextState:n,effects:o}=function(e,t){switch(e.status){case"idle":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"running",runId:t.runId,abort:t.abort},effects:[]};case"queueResume":return void 0===t.targetRunId?{nextState:e,effects:[]}:{nextState:{status:"runningWithQueuedResume",runId:t.targetRunId,queuedResume:t.queuedResume},effects:[]};case"runFinished":case"clearQueuedResume":case"abort":case"release":return{nextState:e,effects:[]};default:throw new Error(`Unhandled idle-state event: ${String(t)}`)}}(e,t);case"running":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"running",runId:t.runId,abort:t.abort},effects:[{type:"abortActiveRun",abort:e.abort}]};case"queueResume":return{nextState:{status:"runningWithQueuedResume",runId:e.runId,abort:e.abort,queuedResume:t.queuedResume},effects:[]};case"runFinished":return t.runId!==e.runId?{nextState:e,effects:[]}:{nextState:{status:"idle"},effects:[]};case"clearQueuedResume":case"release":return{nextState:e,effects:[]};case"abort":return{nextState:{status:"idle"},effects:[{type:"abortActiveRun",abort:e.abort}]};default:throw new Error(`Unhandled running-state event: ${String(t)}`)}}(e,t);case"runningWithQueuedResume":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"runningWithQueuedResume",runId:t.runId,abort:t.abort,queuedResume:e.queuedResume},effects:[{type:"abortActiveRun",abort:e.abort}]};case"queueResume":return{nextState:{...e,queuedResume:t.mergeQueuedResume(e.queuedResume,t.queuedResume)},effects:[]};case"runFinished":return t.runId!==e.runId?{nextState:e,effects:[]}:{nextState:{status:"running",runId:e.runId,abort:e.abort},effects:[{type:"startQueuedRun",sourceRunId:e.runId,queuedResume:e.queuedResume}]};case"clearQueuedResume":return{nextState:{status:"running",runId:e.runId,abort:e.abort},effects:[]};case"abort":return{nextState:{status:"idle"},effects:[{type:"abortActiveRun",abort:e.abort}]};case"release":return{nextState:e,effects:[]};default:throw new Error(`Unhandled runningWithQueuedResume-state event: ${String(t)}`)}}(e,t);default:return{nextState:e,effects:[]}}}(r,t);this.states.set(e,n),this.options.onStateChange?.({sessionId:e,previousState:r,nextState:n});for(const t of o)switch(t.type){case"abortActiveRun":t.abort?.();break;case"startQueuedRun":this.options.onQueuedRunReady?.({sessionId:e,sourceRunId:t.sourceRunId,queuedResume:t.queuedResume});break;default:throw new Error(`Unhandled lifecycle manager effect: ${String(t)}`)}const s=this.getState(e);"release"===t.type&&"idle"!==s.status&&this.releaseRequestedBySession.add(e),"idle"!==s.status||"release"!==t.type&&!this.releaseRequestedBySession.has(e)||(this.states.delete(e),this.runCounterBySession.delete(e),this.releaseRequestedBySession.delete(e))}}function OB(e){return"string"==typeof e&&e.trim().length>0}function FB(e,t){return new he.jn({command:t.command??"",workingDirectory:t.workingDirectory??"",error:e,isReadonly:!0})}function NB(e){return{execute:async(t,r)=>new MI.v3({result:{case:"permissionDenied",value:new MI.U7({path:r.path,error:e,isReadonly:!0})}})}}function LB(e){return{execute:async(t,r)=>new jw.Pi({result:{case:"permissionDenied",value:new jw.QG({path:r.path,clientVisibleError:e,isReadonly:!0})}})}}function jB(e){return{execute:async(t,r)=>new Ac.iz({result:{case:"permissionDenied",value:new Ac.HQ({error:`${e} Tool: ${r.name}`,isReadonly:!0})}})}}var UB=r("../agent-kv/dist/subagent-states.js");let BB;function WB(e){const t=process.env.CURSOR_DATA_DIR;if(t?.trim())return _o(e);let r;try{r=(0,o.homedir)()}catch{r=void 0}return function(e){const t=e.cursorDataDir?.trim();return t?(0,s.join)(t,"projects",(0,So.r_)(e.workspacePath)):void 0!==e.homeDir&&function(e){if(""===e.trim())return!1;try{return!!(0,xo.statSync)(e).isDirectory()&&((0,xo.accessSync)(e,xo.constants.W_OK),!0)}catch{return!1}}(e.homeDir)?(0,s.join)(e.homeDir,".cursor","projects",(0,So.r_)(e.workspacePath)):(0,s.join)(e.ensureFallbackRoot(e.tempDir),(0,So.r_)(e.workspacePath))}({workspacePath:e,homeDir:r,tempDir:(0,o.tmpdir)(),ensureFallbackRoot:e=>(void 0===BB&&(BB=function(e){return(0,xo.mkdtempSync)((0,s.join)(e,"cursor-transcripts-"))}(e)),BB)})}async function HB(e,t){const r=(0,s.dirname)(e);await(0,Co.mkdir)(r,{recursive:!0}),await(0,Co.writeFile)(e,t,"utf-8")}class qB{constructor(e){this.writeChain=Promise.resolve(),this.workspacePath=e.workspacePath,this.conversationId=e.conversationId,this.parentConversationId=e.parentConversationId,this.blobStore=e.blobStore,this.projectDir=WB(this.workspacePath);const t=this.parentConversationId?(e,t)=>{const r=DF({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,r)}:void 0;this.transcriptStore=new uN(this.projectDir,e.blobStore,HB,{writeText:!1,writeJsonl:!0,...t?{pathResolver:t}:{}}),this.nestedSubagentTranscriptStore=new uN(this.projectDir,e.blobStore,HB,{writeText:!1,writeJsonl:!0,pathResolver:(e,t)=>{const r=DF({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.conversationId});return(0,s.join)(this.projectDir,r)}})}enqueueWrite(e,t){const r=this.writeChain;return this.writeChain=r.then((async()=>{try{await e()}catch(e){SO.Jz.warn(`${t} ${e instanceof Error?e.message:String(e)}`)}})),this.writeChain}async writeFromState(e,t){return this.enqueueWrite((async()=>{await this.transcriptStore.writeFromStateFull(e,t,this.conversationId);const r=await(0,UB.Vn)(e,t,this.blobStore);for(const[t,n]of Object.entries(r))n?.conversationState&&await this.nestedSubagentTranscriptStore.writeFromStateFull(e,n.conversationState,t)}),"[LocalTranscriptWriter] Failed to write transcript:")}async writeTurnEndedFromState(e,t,r){return this.enqueueWrite((async()=>{await this.transcriptStore.writeFromStateFull(e,t,this.conversationId,{turnEnded:r})}),"[LocalTranscriptWriter] Failed to write turn-ended transcript:")}waitForPendingWrites(){return this.writeChain}getTranscriptPath(){if(this.parentConversationId){const e=DF({conversationId:this.conversationId,ext:"jsonl",kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,e)}return function(e,t){const r=DF({conversationId:t,ext:"jsonl",kind:"primary"});return(0,s.join)(WB(e),r)}(this.workspacePath,this.conversationId)}getProjectDir(){return this.projectDir}}const zB=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,GB="User aborted/interrupted manually.";class VB{constructor(e){this.sessions=new Map,this.backgroundRuns=new Map,this.activeForegroundExecutions=new Map,this.backgroundPromises=new Set,this.pendingReleaseSessions=new Set,this.childParentIds=new Map,this.parentChildIds=new Map,this.queuedChildCompletions=new Map,this.childCompletionWaiters=new Map,this.childLineageRequestIds=new Map,this.untrackedParentRequestIds=new Map,this.agentClient=e.agentClient,this.getResources=e.getResources,this.mcpTools=e.mcpTools??[],this.workspacePath=e.workspacePath,this.parentConversationId=e.parentConversationId;const t=e.rootRequestId?.trim();this.rootLineageRequestId=void 0!==t&&t.length>0?t:(0,ge.C)(),this.headers=e.headers,this.endlessRetries=e.endlessRetries,this.onSessionCreated=e.onSessionCreated,this.onInteractionUpdate=e.onInteractionUpdate,this.onSessionCompleted=e.onSessionCompleted,this.onSessionReleased=e.onSessionReleased,this.onSubagentTokenDelta=e.onSubagentTokenDelta,this.lifecycleStore=new DB}async createOrResumeSession(e,t){if(t.forkAgentId)throw new Error("forkAgentId is not supported in local subagents.");const r=t.resumeAgentId;if(r&&function(e){if(!zB.test(e))throw new Error(`Invalid resumeAgentId format: ${e}`)}(r),r&&!t.prompt)return r;if(r&&OB(t.prompt)&&this.isBackgroundRunBusy(r))throw new Error("Sub-agent is currently running. You may send the follow-up message when it has completed.");if(r&&this.sessions.get(r))return r;const n=r??(0,ge.C)(),o=function(e){const t=new re.We,r=(0,kO.sh)(e),n=new kO.pH(new re.ve,t);return n.setMetadata("agentId",r.agentId),n.setMetadata("latestRootBlobId",r.latestRootBlobId),n.setMetadata("name",r.name),n.setMetadata("createdAt",r.createdAt),n.setMetadata("mode",r.mode),n.setMetadata("isRunEverything",r.isRunEverything),n.setMetadata("lastUsedModel",r.lastUsedModel),n.setMetadata("lastDebugServerPort",r.lastDebugServerPort),n.setMetadata("currentPlanUri",r.currentPlanUri),n.setMetadata("subagentInfo",r.subagentInfo),n.setMetadata("blobEncryptionKey",r.blobEncryptionKey),n}(n),s=new qB({workspacePath:this.workspacePath,conversationId:n,parentConversationId:this.parentConversationId,blobStore:o.getBlobStore()});return this.sessions.set(n,{agentStore:o,transcriptWriter:s,toolCallId:t.toolCallId}),this.onSessionCreated?.({agentId:n,toolCallId:t.toolCallId,subagentType:t.subagentType,parentAgentId:t.parentConversationId}),n}async runSession(e,t,r,n){if(this.isAwaitBackgroundMode(r))return this.awaitBackgroundRun(r.resumeAgentId,e.signal);const o=this.sessions.get(t);if(!o)return{status:"error",error:`Subagent session not found: ${t}`};if(r.runInBackground){const[n,s]=e.withDetached().withCancel();return this.registerBackgroundRun(t,this.executeSubagent(n,t,r,o),r.parentConversationId,s),{status:"background",backgroundReason:vg.qL.AGENT_REQUEST,toolCallCount:0}}const[s,i]=e.withDetached().withCancel();let a=!1;const c=()=>{a||i()};e.signal.addEventListener("abort",c,{once:!0}),e.signal.aborted&&c();let l=()=>{};const u=new Promise((e=>{l=e})),d={requestBackground:()=>!!a||!s.signal.aborted&&(a=!0,e.signal.removeEventListener("abort",c),l(),!0)};this.activeForegroundExecutions.set(r.toolCallId,d),this.activeForegroundExecutions.set(t,d);try{const e=this.executeSubagent(s,t,r,o),n=await Promise.race([e.then((e=>({handedOff:!1,outcome:e}))),u.then((()=>({handedOff:!0})))]);return n.handedOff?(this.registerBackgroundRun(t,e,r.parentConversationId,i),{status:"background",backgroundReason:vg.qL.USER_REQUEST,toolCallCount:0}):(this.onSessionCompleted?.(t,n.outcome),n.outcome)}finally{this.clearForegroundExecution(r.toolCallId,d),this.clearForegroundExecution(t,d),a||e.signal.removeEventListener("abort",c)}}forceBackgroundByToolCallId(e){const t=this.activeForegroundExecutions.get(e);return t?.requestBackground()?new oo.a3({status:oo.jh.ACCEPTED}):new oo.a3({status:oo.jh.NOT_FOUND})}clearForegroundExecution(e,t){this.activeForegroundExecutions.get(e)===t&&this.activeForegroundExecutions.delete(e)}releaseSession(e){this.lifecycleStore.release(e),this.isBackgroundRunBusy(e)?this.pendingReleaseSessions.add(e):this.cleanupSession(e)}async awaitBackgroundWorkers(){for(;this.backgroundPromises.size>0;)await Promise.allSettled([...this.backgroundPromises])}async waitForBackgroundCompletions(e,t){return this.collectAvailableChildCompletions(e,t)}isBackgroundRunBusy(e){return this.lifecycleStore.isBusy(e)||this.backgroundRuns.has(e)}registerBackgroundRun(e,t,r,n){this.registerParentChildLink(e,r);const o=this.lifecycleStore.startRun(e,{abort:n}),s=t.catch((e=>({status:"error",error:e instanceof Error?e.message:String(e)}))),i={runId:o,promise:s};this.backgroundRuns.set(e,i),this.backgroundPromises.add(s),s.then((t=>{this.lifecycleStore.finishRun(e,o);const r=this.backgroundRuns.get(e);if(r?.runId===o){this.backgroundRuns.delete(e),this.enqueueChildCompletion(e,o,t),this.maybeCleanupReleasedSession(e);try{this.onSessionCompleted?.(e,t)}catch(t){SO.Jz.error("[LocalSubagentHostAdapter] onSessionCompleted threw after background run",{agentId:e,error:t instanceof Error?t.message:String(t)})}}return t})).finally((()=>this.backgroundPromises.delete(s)))}maybeCleanupReleasedSession(e){this.pendingReleaseSessions.has(e)&&!this.isBackgroundRunBusy(e)&&this.cleanupSession(e)}cleanupSession(e){this.pendingReleaseSessions.delete(e);const t=this.sessions.get(e);if(!t)return;const r=this.parentChildIds.get(e);if(r)for(const e of r)this.childParentIds.delete(e);this.removeParentChildLink(e),this.parentChildIds.delete(e),this.queuedChildCompletions.delete(e),this.childCompletionWaiters.delete(e),t.transcriptWriter.waitForPendingWrites().catch((()=>{})),this.sessions.delete(e),this.onSessionReleased?.(e)}async executeSubagent(e,t,r,n){return r.continuationConfig?this.executeSubagentWithContinuation(e,t,r,n,r.continuationConfig):this.executeSubagentOnce(e,t,r,n)}async executeSubagentWithContinuation(e,t,r,n,o){const s=o.maxLoops>0?o.maxLoops:Number.POSITIVE_INFINITY;let i=await this.runContinuationLoop(e,t,r,n,o,s);if(!o.collectBackgroundChildren||"completed"!==i.status)return i;for(let a=0;a<500;a++){if(e.signal.aborted)return{status:"error",error:"Subagent was aborted by the user"};let a;try{a=await this.collectAvailableChildCompletions(t,e.signal)}catch{return{status:"error",error:"Subagent was aborted by the user"}}if(0===a.length)return i;const c=this.buildChildrenCompletedMessage(a,o.childrenCompletedMessageTemplate);if(i=await this.runContinuationLoop(e,t,new oo.Pw({...r,prompt:c,resumeAgentId:t,runInBackground:!1}),n,o,s),"completed"!==i.status)return i}return i}async runContinuationLoop(e,t,r,n,o,s){let i,a,c=0;for(let l=0;l0?(c=0,i=void 0):(c+=1,i=c>=o.idleThreshold?`DONE_${(0,ge.C)().replace(/-/g,"").slice(0,8)}`:void 0)}return a??{status:"error",error:"Subagent continuation exited unexpectedly"}}computeContinuationNudge(e,t,r){return t>=e.idleThreshold&&void 0!==r?e.escapeMessageTemplate.replace("{idle_count}",String(t)).replace("{escape_token}",r):e.nudgeMessage}lineageForChildRun(e){this.childLineageRequestIds.has(e.agentId)||this.childLineageRequestIds.set(e.agentId,(0,ge.C)());const t=e.parentConversationId?.trim()??"",r=e.toolCallId.trim();return{parentRequestId:""===t||t===this.parentConversationId?this.rootLineageRequestId:this.childLineageRequestIds.get(t)??this.untrackedParentRequestId(t),rootParentRequestId:this.rootLineageRequestId,...r.length>0?{parentAgentToolCallId:r}:{}}}untrackedParentRequestId(e){let t=this.untrackedParentRequestIds.get(e);return void 0===t&&(t=(0,ge.C)(),this.untrackedParentRequestIds.set(e,t)),t}async executeSubagentOnce(e,t,r,n){const o=this.lineageForChildRun({agentId:t,parentConversationId:r.parentConversationId,toolCallId:r.toolCallId});let s,a=0;const c=new i.QFf({action:{case:"userMessageAction",value:new i.Vtf({userMessage:new i.RGk({text:r.prompt})})}}),l=new i.Gmx({modelId:r.modelId,displayModelId:r.modelId,displayName:r.modelId});void 0!==r.credentials.case&&(l.credentials=r.credentials);const u=new bO,d={sendUpdate:async(e,r)=>{"tokenDelta"===r.message.case&&this.onSubagentTokenDelta?.(t,r.message.value.tokens),"toolCallStarted"!==r.message.case&&"toolCallCompleted"!==r.message.case&&"partialToolCall"!==r.message.case||this.onInteractionUpdate?.(t,r),"toolCallCompleted"===r.message.case&&a++,"textDelta"===r.message.case&&(s=(s??"")+r.message.value.text)},query:async(e,t)=>function(e){const t=e.query.case;switch(t){case"webSearchRequestQuery":return dr(e.id,"Web search is not supported in local subagent");case"webFetchRequestQuery":return pr(e.id,"Web fetch is not supported in local subagent");case"switchModeRequestQuery":return gr(e.id,"Subagent mode switches are not supported in local subagent");case"askQuestionInteractionQuery":{const t=new Qt.tz({result:{case:"rejected",value:new Qt.ox({reason:"Interactive questions are not supported in local subagent mode"})}});return fr(e.id,t)}default:throw new Error(`Unhandled interaction query type in local subagent: ${String(t)}`)}}(t)},h={handleCheckpoint:async(e,t)=>{await n.agentStore.handleCheckpoint(e,t),n.transcriptWriter.writeFromState(e,t)},getLatestCheckpoint:()=>n.agentStore.getLatestCheckpoint()};try{const i=r.rootParentConversationId?.trim(),p=r.parentConversationId?.trim(),f=void 0!==i&&""!==i?i:void 0!==p&&""!==p?p:t,m=await this.getResources({agentId:t,parentAgentId:r.parentConversationId}),g=r.readonly?new J(m,function(e){const t=[G(HT,NB(e.errorMessage)),G(qT,LB(e.errorMessage)),G(eo,jB(e.errorMessage))];return e.wrapShell&&t.push(G(jT,function(e){return{execute:async(t,r)=>new he.W4({result:{case:"permissionDenied",value:FB(e,r)}})}}(e.errorMessage)),G(ee,function(e){return{async*execute(t,r){yield new he.FI({event:{case:"permissionDenied",value:FB(e,r)}})}}}(e.errorMessage)),G(vA,function(e){return{execute:async(t,r)=>new Do.Lt({result:{case:"permissionDenied",value:FB(e,r)}})}}(e.errorMessage))),e.includeWriteBackgroundShellStdin&&t.push(G(bA,function(e){return{execute:async(t,r)=>new Do.nt({result:{case:"error",value:new Do.Gv({error:e})}})}}(e.errorMessage))),t}({errorMessage:"This operation is not allowed in readonly mode. The subagent was launched with readonly: true, which restricts shell, write, delete, and MCP operations.",wrapShell:!0,includeWriteBackgroundShellStdin:!0})):m;return await this.agentClient.run(e,n.agentStore.getConversationStateStructure(),c,l,d,g,n.agentStore.getBlobStore(),u,h,[...this.mcpTools],{conversationGroupId:f,conversationId:t,...n.transcriptWriter.parentConversationId?{transcriptParentConversationId:n.transcriptWriter.parentConversationId}:{},subagentTypeName:r.subagentType||void 0,...o,headers:CO(n.agentStore.getMetadata("blobEncryptionKey"),this.headers),endlessRetries:this.endlessRetries,subagentModelOverrides:[]}),await n.transcriptWriter.writeTurnEndedFromState(e,n.agentStore.getConversationStateStructure(),e.signal.aborted?{status:"aborted",error:GB}:{status:"success"}),{status:"completed",finalMessage:s,toolCallCount:a}}catch(r){const o=r instanceof Error?r.message:String(r);return SO.Jz.error("[LocalSubagentHostAdapter] Subagent session failed",{agentId:t,error:o}),await n.transcriptWriter.writeTurnEndedFromState(e,n.agentStore.getLatestCheckpoint()??n.agentStore.getConversationStateStructure(),this.getTurnEndedFromError(e,o)),e.signal.aborted?{status:"aborted",error:GB}:{status:"error",error:o}}}getTurnEndedFromError(e,t){return e.signal.aborted?{status:"aborted",error:GB}:{status:"error",error:t}}isAwaitBackgroundMode(e){if(!Boolean(e.resumeAgentId&&!OB(e.prompt)&&e.readonly&&!0!==e.runInBackground))return!1;if(0===(e.parentConversationId??"").trim().length)throw new Error(`Missing parentConversationId for subagent await/status check (subagentId: ${e.resumeAgentId})`);return!0}async awaitBackgroundRun(e,t){const r=this.backgroundRuns.get(e);return r?this.awaitBackgroundEntry(r,t):this.isBackgroundRunBusy(e)?this.awaitBusyLifecycleRun(e,t):{status:"error",error:`No background subagent found for id: ${e}`}}async awaitBackgroundRunBounded(e,t){const r=t.agentId;if(e.signal.aborted)return new oo.zJ({result:{case:"stillRunning",value:new oo.L5({agentId:r})}});const n=this.backgroundRuns.get(r);if(void 0===n){const e=this.takeQueuedChildCompletion(r);return void 0!==e?"success"===e.status?new oo.zJ({result:{case:"complete",value:new oo.bE({agentId:r,finalMessage:e.finalMessage,toolCallCount:e.toolCallCount??0})}}):new oo.zJ({result:{case:"error",value:new oo.Y({agentId:r,error:e.finalMessage||"Subagent was aborted"})}}):this.isBackgroundRunBusy(r)?new oo.zJ({result:{case:"stillRunning",value:new oo.L5({agentId:r})}}):new oo.zJ({result:{case:"notFound",value:new oo.Hq({agentId:r})}})}const[o,s]=e.withTimeoutAndCancel(Math.max(0,t.timeoutMs)),i=await new Promise((e=>{const t=()=>e(void 0);o.signal.addEventListener("abort",t,{once:!0}),n.promise.then(e).finally((()=>{o.signal.removeEventListener("abort",t),s()}))}));return void 0===i||"background"===i.status||e.signal.aborted?new oo.zJ({result:{case:"stillRunning",value:new oo.L5({agentId:r})}}):(this.takeQueuedChildCompletion(r,n.runId),"completed"===i.status?new oo.zJ({result:{case:"complete",value:new oo.bE({agentId:r,finalMessage:i.finalMessage,toolCallCount:i.toolCallCount??0})}}):new oo.zJ({result:{case:"error",value:new oo.Y({agentId:r,error:i.error??"Subagent was aborted"})}}))}takeQueuedChildCompletion(e,t){for(const[r,n]of this.queuedChildCompletions){const o=n.findIndex((r=>r.agentId===e&&(void 0===t||r.runId===t)));if(-1===o)continue;const[s]=n.splice(o,1);return 0===n.length&&this.queuedChildCompletions.delete(r),s}}async awaitBusyLifecycleRun(e,t){for(;this.isBackgroundRunBusy(e);){if(t.aborted)return{status:"error",error:"Await timed out while task is still running"};const r=this.backgroundRuns.get(e);if(r)return this.awaitBackgroundEntry(r,t);await new Promise((e=>setTimeout(e,50)))}return{status:"completed",toolCallCount:0}}async awaitBackgroundEntry(e,t){if(t.aborted)return{status:"error",error:"Await timed out while task is still running"};const r={status:"error",error:"Await timed out while task is still running"};return new Promise((n=>{const o=()=>{n(r)};t.addEventListener("abort",o,{once:!0}),e.promise.then(n).finally((()=>t.removeEventListener("abort",o)))}))}registerParentChildLink(e,t){const r=t?.trim();if(!r||r===e||!this.sessions.has(r)&&r!==this.parentConversationId)return;const n=this.childParentIds.get(e);if(n===r)return;n&&(this.parentChildIds.get(n)?.delete(e),0===(this.parentChildIds.get(n)?.size??0)&&this.parentChildIds.delete(n)),this.childParentIds.set(e,r);const o=this.parentChildIds.get(r)??new Set;o.add(e),this.parentChildIds.set(r,o)}removeParentChildLink(e){const t=this.childParentIds.get(e);if(!t)return;this.childParentIds.delete(e);const r=this.parentChildIds.get(t);r?.delete(e),0===(r?.size??0)&&this.parentChildIds.delete(t)}enqueueChildCompletion(e,t,r){const n=this.childParentIds.get(e);if(!n)return;const o=this.queuedChildCompletions.get(n)??[];o.push({agentId:e,runId:t,status:"completed"===r.status?"success":"error"===r.status?"error":"aborted",finalMessage:"completed"===r.status?r.finalMessage??"":"error"===r.status?r.error:"Subagent was aborted by the user",..."completed"===r.status&&void 0!==r.toolCallCount?{toolCallCount:r.toolCallCount}:{}}),this.queuedChildCompletions.set(n,o),this.removeParentChildLink(e);const s=this.childCompletionWaiters.get(n);if(s){this.childCompletionWaiters.delete(n);for(const e of s)e()}}async collectAvailableChildCompletions(e,t){const r=this.drainChildCompletions(e);return r.length>0?r:this.hasPendingChildSubagents(e)?(await this.waitForChildCompletion(e,t),this.drainChildCompletions(e)):[]}hasPendingChildSubagents(e){return(this.parentChildIds.get(e)?.size??0)>0}drainChildCompletions(e){const t=this.queuedChildCompletions.get(e)??[];return this.queuedChildCompletions.delete(e),t}async waitForChildCompletion(e,t){if(t.aborted)throw new Error("aborted");await new Promise(((r,n)=>{const o=this.childCompletionWaiters.get(e)??new Set,s=()=>{a(),r()},i=()=>{a(),n(new Error("aborted"))},a=()=>{o.delete(s),0===o.size&&this.childCompletionWaiters.delete(e),t.removeEventListener("abort",i)};o.add(s),this.childCompletionWaiters.set(e,o),t.addEventListener("abort",i,{once:!0})}))}buildChildrenCompletedMessage(e,t){const r=e.map((e=>{const t="success"===e.status?"SUCCESS":"FAILED";return`## Agent ${e.agentId} -- ${t}\n\n${e.finalMessage}`})).join("\n\n---\n\n");return t.replace("{summaries}",r)}}var KB=r("../proto/dist/generated/agent/v1/agent_service_connect.js"),JB=r("../proto/dist/generated/agent/v1/requested_model_pb.js"),ZB=r("../proto/dist/generated/agent/v1/selected_context_pb.js"),XB=r("./src/agent/analytics.ts"),QB=r("../proto/dist/generated/agent/v1/todo_tool_pb.js");const YB={[Og.w3.UNSPECIFIED]:"unspecified",[Og.w3.LEFT]:"left",[Og.w3.RIGHT]:"right",[Og.w3.MIDDLE]:"middle",[Og.w3.BACK]:"back",[Og.w3.FORWARD]:"forward"},eW={[Og.Dh.UNSPECIFIED]:"unspecified",[Og.Dh.UP]:"up",[Og.Dh.DOWN]:"down",[Og.Dh.LEFT]:"left",[Og.Dh.RIGHT]:"right"},tW={[Og.EB.UNSPECIFIED]:"unspecified",[Og.EB.TAP]:"tap",[Og.EB.DOWN]:"down",[Og.EB.UP]:"up"};function rW(e){return YB[e]??"unspecified"}function nW(e){return void 0===e?void 0:{x:e.x,y:e.y}}function oW({result:e}){switch(e.case){case"success":return{status:"success",value:{actionCount:e.value.actionCount,durationMs:e.value.durationMs,settleMs:e.value.settleMs,screenshotPath:e.value.screenshotPath,cursorPosition:nW(e.value.cursorPosition),log:e.value.log}};case"error":return{status:"error",error:{message:e.value.error,actionCount:e.value.actionCount,durationMs:e.value.durationMs,screenshotPath:e.value.screenshotPath,log:e.value.log}};default:return}}function sW(e,t){switch(e.message.case){case"textDelta":return{type:"text-delta",text:e.message.value.text};case"thinkingDelta":return{type:"thinking-delta",text:e.message.value.text};case"thinkingCompleted":return{type:"thinking-completed",thinkingDurationMs:e.message.value.thinkingDurationMs};case"userMessageAppended":return{type:"user-message-appended",userMessage:{type:"user_message",session_id:t,text:e.message.value.userMessage?.text??""}};case"tokenDelta":return{type:"token-delta",tokens:e.message.value.tokens};case"summary":return{type:"summary",summary:e.message.value.summary};case"summaryStarted":return{type:"summary-started"};case"summaryCompleted":{const{failed:t,fallback:r}=e.message.value;return{type:"summary-completed",...t?{failed:t}:{},...r?{fallback:r}:{}}}case"shellOutputDelta":return{type:"shell-output-delta",event:e.message.value.event.case?{case:e.message.value.event.case,value:e.message.value.event.value?.toJson?.()??e.message.value.event.value}:{}};case"toolCallStarted":return iW("tool-call-started",e.message.value);case"partialToolCall":return iW("partial-tool-call",e.message.value);case"toolCallCompleted":return iW("tool-call-completed",e.message.value);case"heartbeat":return null;case"turnEnded":{const t=e.message.value;return{type:"turn-ended",...(void 0!==t.inputTokens||void 0!==t.outputTokens||void 0!==t.cacheReadTokens||void 0!==t.cacheWriteTokens)&&{usage:{inputTokens:Number(t.inputTokens??BigInt(0)),outputTokens:Number(t.outputTokens??BigInt(0)),cacheReadTokens:Number(t.cacheReadTokens??BigInt(0)),cacheWriteTokens:Number(t.cacheWriteTokens??BigInt(0)),...t.reasoningTokens&&{reasoningTokens:Number(t.reasoningTokens)}}}}}case"modelCallCompleted":{const t=e.message.value;return{type:"model-call-completed",modelCallId:t.modelCallId,usage:{inputTokens:Number(t.inputTokens),outputTokens:Number(t.outputTokens),cacheReadTokens:Number(t.cacheReadTokens),cacheWriteTokens:Number(t.cacheWriteTokens),...t.reasoningTokens&&{reasoningTokens:Number(t.reasoningTokens)}}}}case"toolCallDelta":{const r=e.message.value,n=r.toolCallDelta;if("taskToolCallDelta"!==n?.delta.case)return null;const o=n.delta.value.interactionUpdate;if(void 0===o)return null;const s=sW(o,t);return null!==s&&function(e){switch(e.type){case"text-delta":case"thinking-delta":case"thinking-completed":case"tool-call-started":case"tool-call-completed":case"partial-tool-call":case"step-started":case"step-completed":case"tool-requests-listed":return!0;default:return!1}}(s)?{type:"tool-call-delta",callId:r.callId,modelCallId:r.modelCallId,taskUpdate:s}:null}case"stepStarted":return{type:"step-started",stepId:Number(e.message.value.stepId)};case"toolRequestsListed":return{type:"tool-requests-listed",callCount:e.message.value.callCount};case"stepCompleted":return{type:"step-completed",stepId:Number(e.message.value.stepId),stepDurationMs:Number(e.message.value.stepDurationMs)};case"postRequestPrompt":case"activeBranchChange":case"feedbackRequest":case"responseComparison":case"contextInjectionState":case"routedModel":case"grokBotNudge":case"thinkingNote":case"voiceCallUtterance":case void 0:return null;default:return e.message,null}}function iW(e,t){const r=function(e){if(!e?.tool)return null;switch(e.tool.case){case"shellToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"shell",args:{command:t.command,...t.workingDirectory?{workingDirectory:t.workingDirectory}:{},...t.timeout?{timeout:t.timeout}:{}},...r?{result:hW(r)}:{}}:null}case"deleteToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"delete",args:{path:t.path},...r?{result:pW(r)}:{}}:null}case"globToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"glob",args:{globPattern:t.globPattern,...t.targetDirectory?{targetDirectory:t.targetDirectory}:{}},...r?{result:fW(r)}:{}}:null}case"grepToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"grep",args:{pattern:t.pattern,...t.path?{path:t.path}:{},...t.glob?{glob:t.glob}:{},...t.outputMode?{outputMode:t.outputMode}:{},...t.contextBefore?{contextBefore:t.contextBefore}:{},...t.contextAfter?{contextAfter:t.contextAfter}:{},...t.context?{context:t.context}:{},...t.caseInsensitive?{caseInsensitive:t.caseInsensitive}:{},...t.type?{type:t.type}:{},...t.headLimit?{headLimit:t.headLimit}:{},...void 0!==t.offset?{offset:t.offset}:{},...t.multiline?{multiline:t.multiline}:{},...t.sort?{sort:t.sort}:{},...t.sortAscending?{sortAscending:t.sortAscending}:{}},...r?{result:mW(r)}:{}}:null}case"readToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"read",args:{path:t.path},...r?{result:wW(r)}:{}}:null}case"editToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"edit",args:{path:t.path},...r?{result:yW(r)}:{}}:null}case"lsToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"ls",args:{path:t.path,...t.ignore&&t.ignore.length>0?{ignore:t.ignore}:{}},...r?{result:vW(r)}:{}}:null}case"readLintsToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"readLints",args:{paths:t.paths},...r?{result:SW(r)}:{}}:null}case"mcpToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"mcp",args:{...t.providerIdentifier?{providerIdentifier:t.providerIdentifier}:{},...t.toolName?{toolName:t.toolName}:{},...t.args?{args:Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()])))}:{}},...r?{result:kW(r)}:{}}:null}case"generateImageToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"generateImage",args:{description:t.description,...t.filePath?{filePath:t.filePath}:{}},...r?{result:CW(r)}:{}}:null}case"recordScreenToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"recordScreen",args:{mode:EW(t.mode)},...r?{result:xW(r)}:{}}:null}case"semSearchToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"semSearch",args:{query:t.query,...t.targetDirectories&&t.targetDirectories.length>0?{targetDirectories:t.targetDirectories}:{},...t.explanation?{explanation:t.explanation}:{}},...r?{result:_W(r)}:{}}:null}case"createPlanToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"createPlan",args:{plan:t.plan},...r?{result:PW(r)}:{}}:null}case"updateTodosToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"updateTodos",args:{todos:t.todos.map((e=>({content:e.content,status:IW(e.status)})))},...r?{result:RW(r)}:{}}:null}case"fetchToolCall":case"switchModeToolCall":return null;case"computerUseToolCall":return function({args:e,result:t}){return e?{type:"computerUse",args:{actions:e.actions.flatMap((e=>function({action:e}){switch(e.case){case"mouseMove":return{type:"mouseMove",coordinate:nW(e.value.coordinate)};case"click":return{type:"click",coordinate:nW(e.value.coordinate),button:rW(e.value.button),count:e.value.count,modifierKeys:e.value.modifierKeys};case"mouseDown":case"mouseUp":return{type:e.case,button:rW(e.value.button)};case"drag":return{type:"drag",path:e.value.path.map((e=>({x:e.x,y:e.y}))),button:rW(e.value.button),modifierKeys:e.value.modifierKeys};case"scroll":return{type:"scroll",coordinate:nW(e.value.coordinate),direction:eW[e.value.direction]??"unspecified",amount:e.value.amount,modifierKeys:e.value.modifierKeys};case"type":return{type:"type",text:e.value.text};case"key":return{type:"key",key:e.value.key,holdDurationMs:e.value.holdDurationMs,stroke:tW[e.value.stroke]??"unspecified"};case"wait":return{type:"wait",durationMs:e.value.durationMs};case"screenshot":case"cursorPosition":return{type:e.case};default:return}}(e)??[])),description:e.description},result:t?oW(t):void 0}:null}(e.tool.value);case"readTodosToolCall":case"webSearchToolCall":case"listMcpResourcesToolCall":case"readMcpResourceToolCall":return null;case"taskToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"task",args:aW(t),...r?{result:uW(r)}:{}}:null}case"applyAgentDiffToolCall":case"askQuestionToolCall":case"writeShellStdinToolCall":case"reflectToolCall":case"setupVmEnvironmentToolCall":case"replaceEnvToolCall":case"startGrindExecutionToolCall":case"startGrindPlanningToolCall":case"truncatedToolCall":case"webFetchToolCall":case"reportBugfixResultsToolCall":case"aiAttributionToolCall":case"prManagementToolCall":case"editPrLabelsToolCall":case"fetchCloudAgentDataToolCall":case"mcpAuthToolCall":case"connectScmToolCall":case"searchConversationsToolCall":case"awaitToolCall":case"blameByFilePathToolCall":case"getMcpToolsToolCall":case"reportBugToolCall":case"setActiveBranchToolCall":case"communicateUpdateToolCall":case"sendFinalSummaryToolCall":case"updateOriginPrCodeTourToolCall":case"getOriginPrCodeTourToolCall":case"recordCiInvestigationFindingsToolCall":case"sendMessageToolCall":case"sendToUserToolCall":case"createGoalToolCall":case"updateGoalToolCall":case"getAgentStatusToolCall":case"sendToAgentToolCall":case"readAgentTranscriptToolCall":case"createAgentToolCall":case"createProjectToolCall":case"startProjectUpdatesToolCall":case"stopProjectUpdatesToolCall":case"manageAccessToolCall":case"stopAgentToolCall":case"listTrackedTasksToolCall":case"createTrackedTasksToolCall":case"updateTrackedTasksToolCall":case"deleteTrackedTasksToolCall":case"updateTrackedTaskStatusesToolCall":case"updateTrackedTaskTagsToolCall":case"writeCanvasToolCall":case"readCanvasToolCall":case"generateVideoToolCall":case"xSearchToolCall":case"executeToolCall":case void 0:return null;default:return e.tool}}(t.toolCall);return r?{type:e,callId:t.callId,toolCall:r,modelCallId:t.modelCallId}:null}function aW(e){return{description:e.description??"",prompt:e.prompt??"",...e.subagentType?{subagentType:cW(e.subagentType)}:{},...e.model?{model:e.model}:{},...e.resume?{resume:e.resume}:{},...e.agentId?{agentId:e.agentId}:{},...e.attachments&&e.attachments.length>0?{attachments:e.attachments}:{},...void 0!==e.mode?{mode:lW(e.mode)}:{},...e.respondingToMessageIds&&e.respondingToMessageIds.length>0?{respondingToMessageIds:e.respondingToMessageIds}:{}}}function cW(e){const t=e.type.case;return t?"custom"===t?{kind:t,name:e.type.value.name}:{kind:t}:{kind:"unspecified"}}function lW(e){switch(e){case vg.FL.AGENT:return"agent";case vg.FL.PLAN:return"plan";default:return"unspecified"}}function uW(e){if(e.result?.case)switch(e.result.case){case"success":{const t=e.result.value;return{status:"success",value:{...t.conversationSteps&&t.conversationSteps.length>0?{conversationSteps:t.conversationSteps.map((e=>e.toJson?.()??e))}:{},...t.agentId?{agentId:t.agentId}:{},isBackground:t.isBackground??!1,...void 0!==t.durationMs?{durationMs:Number(t.durationMs)}:{},...t.resultSuffix?{resultSuffix:t.resultSuffix}:{},backgroundReason:dW(t.backgroundReason),...t.transcriptPath?{transcriptPath:t.transcriptPath}:{}}}}case"error":return{status:"error",error:{message:e.result.value.error??"Task failed"}};default:return}}function dW(e){switch(e){case vg.qL.AGENT_REQUEST:return"agentRequest";case vg.qL.USER_REQUEST:return"userRequest";case vg.qL.QUEUED_FOLLOW_UP:return"queuedFollowUp";default:return"unspecified"}}function hW(e){if(e.result?.case)switch(e.result.case){case"success":case"failure":{const t=e.result.value;return{status:"success",value:{exitCode:t.exitCode??0,signal:t.signal??"",stdout:t.stdout??"",stderr:t.stderr??"",executionTime:t.executionTime??0}}}case"timeout":return{status:"error",error:{message:`Command timed out after ${e.result.value.timeoutMs}ms`,command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};case"rejected":return{status:"error",error:{message:e.result.value.reason??"Command rejected",command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};case"spawnError":return{status:"error",error:{message:e.result.value.error??"Failed to spawn command",command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};default:return}}function pW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{fileSize:Number(e.result.value.fileSize??0)}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.value.clientVisibleError??e.result.case,path:e.result.value.path}}}function fW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{files:e.result.value.files??[],totalFiles:e.result.value.totalFiles??0,clientTruncated:e.result.value.clientTruncated??!1,ripgrepTruncated:e.result.value.ripgrepTruncated??!1}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case}}}function mW(e){if(e.result?.case){if("success"===e.result.case){const t=e.result.value,r={};if(t.workspaceResults)for(const[e,n]of Object.entries(t.workspaceResults))r[e]=gW(n);return{status:"success",value:{...Object.keys(r).length>0?{workspaceResults:r}:{},...t.activeEditorResult?{activeEditorResult:gW(t.activeEditorResult)}:{}}}}return{status:"error",error:{message:e.result.value.error??e.result.case}}}}function gW(e){if(e?.result?.case)switch(e.result.case){case"content":return{type:"content",output:{matches:e.result.value.matches?.map((e=>({file:e.file,...void 0!==e.lineNumber?{lineNumber:e.lineNumber}:{},line:e.line,...e.beforeContext?{beforeContext:e.beforeContext}:{},...e.afterContext?{afterContext:e.afterContext}:{}})))??[],totalMatches:e.result.value.totalMatches??0}};case"files":return{type:"files",output:{files:e.result.value.files??[],count:e.result.value.count??0}};case"count":return{type:"count",output:{counts:e.result.value.counts?.map((e=>({file:e.file,count:e.count})))??[],total:e.result.value.total??0}};default:return}}function wW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{content:"content"===e.result.value.output.case?e.result.value.output.value:"",totalLines:e.result.value.totalLines??0,fileSize:Number(e.result.value.fileSize??0)}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case,path:e.result.value.path}}}function yW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{...void 0!==e.result.value.linesAdded?{linesAdded:e.result.value.linesAdded}:{},...void 0!==e.result.value.linesRemoved?{linesRemoved:e.result.value.linesRemoved}:{},...e.result.value.diffString?{diffString:e.result.value.diffString}:{}}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case,path:e.result.value.path}}}function vW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{directoryTreeRoot:bW(e.result.value.directoryTreeRoot)}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function bW(e){if(e)return{absPath:e.absPath??"",childrenDirs:e.childrenDirs?.map(bW)??[],childrenFiles:e.childrenFiles?.map((e=>({name:e.name})))??[],childrenWereProcessed:e.childrenWereProcessed??!1,fullSubtreeExtensionCounts:e.fullSubtreeExtensionCounts??{},numFiles:e.numFiles??0}}function SW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{fileDiagnostics:e.result.value.fileDiagnostics?.map((e=>({path:e.path,diagnostics:e.diagnostics?.map((e=>({severity:TW(e.severity),...e.range?{range:{...e.range.start?{start:{line:e.range.start.line,character:e.range.start.character}}:{},...e.range.end?{end:{line:e.range.end.line,character:e.range.end.character}}:{}}}:{},message:e.message,source:e.source,code:e.code})))??[],diagnosticsCount:e.diagnosticsCount??0})))??[],totalFiles:e.result.value.totalFiles??0,totalDiagnostics:e.result.value.totalDiagnostics??0}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function kW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{content:e.result.value.content?.map((e=>{const t={};return"text"===e.content?.case?t.text={text:e.content.value.text}:"image"===e.content?.case&&(t.image={data:e.content.value.data,...e.content.value.mimeType?{mimeType:e.content.value.mimeType}:{}}),t}))??[],isError:e.result.value.isError??!1}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case}}}function _W(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{results:e.result.value.results??""}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function CW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{filePath:e.result.value.filePath??""}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function EW(e){switch(e){case P$.$u.START_RECORDING:return"START_RECORDING";case P$.$u.SAVE_RECORDING:return"SAVE_RECORDING";case P$.$u.DISCARD_RECORDING:return"DISCARD_RECORDING";default:throw new Error(`Unknown RecordingMode: ${e}`)}}function xW(e){if(e.result?.case)switch(e.result.case){case"startSuccess":return{status:"success",value:{wasPriorRecordingCancelled:e.result.value.wasPriorRecordingCancelled??!1}};case"saveSuccess":return{status:"success",value:{path:e.result.value.path??"",recordingDurationMs:Number(e.result.value.recordingDurationMs??0)}};case"discardSuccess":return{status:"success",value:{}};case"failure":return{status:"error",error:{message:e.result.value.error??"Unknown error"}};default:return}}function PW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function RW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{todos:e.result.value.todos?.map((e=>({content:e.content,status:IW(e.status)})))??[],totalCount:e.result.value.totalCount??0}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function IW(e){switch(e){case QB.Vj.UNSPECIFIED:case QB.Vj.PENDING:return"pending";case QB.Vj.IN_PROGRESS:return"inProgress";case QB.Vj.COMPLETED:return"completed";case QB.Vj.CANCELLED:return"cancelled";default:return"pending"}}function TW(e){switch(e){case DA.h_.UNSPECIFIED:case DA.h_.ERROR:return"error";case DA.h_.WARNING:return"warning";case DA.h_.INFORMATION:return"information";case DA.h_.HINT:return"hint";default:return"error"}}const AW={type:"object",properties:{},additionalProperties:!0};function $W(e){const t={};for(const[r,n]of Object.entries(e))t[r]=n;return t}function MW(e){return"text"===e.type?new Ac._Z({content:{case:"text",value:new Ac.zN({text:e.text})}}):new Ac._Z({content:{case:"image",value:new Ac.do({data:n.Buffer.from(e.data,"base64"),mimeType:e.mimeType??""})}})}function DW(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var OW=r("./src/agent/errors.ts");const FW="Shell is not available when local.fs is set: the agent's files live in a FileSystem, and a shell would run on the host disk. Use Read, Grep, Glob, LS, and the edit tools instead.";function NW(e){return{async execute(){throw new Error(e)}}}function LW(e){var t;e.register(jT,NW(FW)),e.register(ee,(t=FW,{async*execute(){throw new Error(t)}})),e.register(vA,NW(FW)),e.register(EA,NW(FW)),e.register(bA,NW(FW)),e.register(UT,NW(FW)),e.register(tA,NW("ReadLints is not available when local.fs is set: lint diagnostics come from a host language service, not the FileSystem.")),e.register(GT,NW("Git is not available when local.fs is set: the agent's files live in a FileSystem, not a host git checkout."))}var jW=r("./src/agent/filesystem/executors.ts"),UW=r("./src/agent/filesystem/compose.ts"),BW=r("./src/agent/filesystem/trees.ts"),WW=r("./src/agent/filesystem/walk.ts");const HW="/tmp",qW=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.txt$/i;function zW(e){const{write:t,hostProjectDir:r}=e;return{async execute(e,n,o){const i=function(e){if(t=e.writePath,!/^([/\\]|[A-Za-z]:[/\\])/.test(t))return;var t;const r=function(e){if(void 0===e.hostProjectDir||""===e.hostProjectDir)return;const t=(0,WW.eI)(e.hostProjectDir),r=(0,WW.eI)(e.writePath);return"/"!==t&&(0,WW.hJ)({path:r,prefix:t})?r.slice(t.length):void 0}(e),n=void 0===r?(0,WW.eI)(e.writePath):(0,WW.eI)(`${HW}/${r}`);if(!(0,WW.hJ)({path:n,prefix:HW}))return;const o=s.default.posix.basename(n),i=s.default.posix.join(HW,$c);return s.default.posix.dirname(n)===i&&qW.test(o)?s.default.posix.join(HW,o):n}({writePath:n.path,hostProjectDir:r});if(void 0===i||i===n.path)return await t.execute(e,n,o);const a=n.clone();a.path=i;const c=await t.execute(e,a,o);return"success"===c.result.case&&(c.result.value.path=i),c}}}class GW{constructor(e,t="/"){this.fs=e,this.listeners=new Set,this.workspace=(0,WW.eI)(t)}getAllCursorRules(e){return this.rules??=async function(e,t){const[r,n]=await Promise.all([VW(e,s.posix.join(t,".cursor/rules")),KW(e,s.posix.join(t,"AGENTS.md"))]);return void 0===n?r:[...r,n]}(this.fs,this.workspace),this.rules}reload(e){this.rules=void 0;for(const e of this.listeners)e()}onDidChangeRules(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}dispose(){this.listeners.clear()}}async function VW(e,t){const r=[];try{for await(const n of e.list(t))"directory"!==n.kind&&n.path.endsWith(".mdc")&&r.push(n.path)}catch{return[]}return(await(0,Or.PH)(r,(async t=>{const r=await JW(e,t),n=void 0===r?null:en(r);if(null!==n)return hg({path:t,body:n.body,frontmatter:n.frontmatter,rawFrontmatter:n.rawFrontmatter})}),{max:8})).filter((e=>void 0!==e))}async function KW(e,t){const r=await JW(e,t);if(void 0!==r)return hg({path:t,body:Zr({content:r,filename:"AGENTS.md"}),frontmatter:{alwaysApply:!0}})}async function JW(e,t){try{const r=await e.read(t);return"string"==typeof r?r:(new TextDecoder).decode(r)}catch{return}}const ZW={getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}},XW={async exec(){throw new Error("git is not available in a FileSystem session")}},QW={isIgnoredByAny:async()=>!1,isGitIgnored:async()=>!1,isCursorIgnored:async()=>!1,isRepoBlocked:async()=>!1,listCursorIgnoreFilesByRoot:async()=>[],getCursorIgnoreMapping:async()=>({}),getShellSandboxIgnoreMapping:async()=>({}),getGitIgnoreMapping:async()=>({}),getRepoBlockExcludeGlobs:async()=>[]};function YW(e){return{cursorRulesService:!0===e.includeProjectRules?new GW(e.fs,e.workspace):ZW,getAgentSkills:async()=>[],subagentsService:e.subagentsService??new Sg,gitExecutor:XW,ignoreService:QW,requestContextIsWorkingDirHomeDir:!1,reportProcessWorkingDirectory:!1}}function eH(e,t){const r=t.workspace??"/",n=(0,jW.c9)(e,{workspace:r});return{localResourceProviderOptions:{overrideReadExecutor:n.read,overrideWriteExecutor:zW({write:n.write,hostProjectDir:t.hostProjectDir}),overrideGrepExecutor:n.grep,overrideLsExecutor:n.ls,overrideDeleteExecutor:n.delete,suppressDefaultShellExecutor:!0,...YW({...t.settings,fs:e,workspace:r})},reportedWorkspacePath:r,reportedProjectFolder:HW,excludeHooks:!0,excludeProjectMcp:!0}}var tH=r("./src/agent/executor-common.ts");class rH{constructor(){this.countsByMode=new Map,this.failureKindsByMode=new Map,this.record=e=>{let t=this.countsByMode.get(e.mode);switch(void 0===t&&(t={mode:e.mode,checked_calls:0,outside_limit_calls:0,settings_unavailable_calls:0,unknown_server_calls:0},this.countsByMode.set(e.mode,t)),e.outcome){case"within_limit":return void(t.checked_calls+=1);case"outside_limit":return t.checked_calls+=1,void(t.outside_limit_calls+=1);case"settings_unavailable":{t.settings_unavailable_calls+=1;const r=e.settingsFailure;if(void 0===r)return;let n=this.failureKindsByMode.get(e.mode);return void 0===n&&(n=new Map,this.failureKindsByMode.set(e.mode,n)),void n.set(r,(n.get(r)??0)+1)}case"unknown_server":return void(t.unknown_server_calls+=1);default:return e.outcome}}}take(){const e=[...this.countsByMode.values()].map((e=>{const t=function(e){let t;for(const[r,n]of e??[])(void 0===t||n>t.calls)&&(t={kind:r,calls:n});return t?.kind}(this.failureKindsByMode.get(e.mode));return void 0===t?e:{...e,settings_unavailable_kind:t}}));return this.countsByMode.clear(),this.failureKindsByMode.clear(),e}}class nH{constructor(e=e=>{console.warn(e)}){this.write=e,this.printed=new Set,this.report=e=>{if(!this.printed.has(e.serverName)){this.printed.add(e.serverName);try{this.write(function(e){return`[cursor-sdk] ${e.refusal}`}(e))}catch{}}}}}const oH=new class{constructor(e=e=>{console.warn(e)}){this.write=e,this.printed=new Set,this.report=e=>{const t=JSON.stringify([e.serverName,(r=e.allowlist,JSON.stringify([r.list,r.name,r.reason,r.allowedServers??null,r.blockedServers??null]))]);var r;if(!this.printed.has(t)){this.printed.size>=1e3&&this.printed.clear(),this.printed.add(t);try{this.write(function(e){return`[cursor-sdk] MCP server "${e.serverName}" is under ${function(e){return`${e.name}, which applies because ${e.reason}.${r=e.allowedServers,void 0===r?"":0===r.length?" Allowed servers: none.":WC("Allowed servers",r)}${t=e.blockedServers,void 0===t||0===t.length?"":WC("Blocked",t)}`;var t,r}(e.allowlist)}`}(e))}catch{}}}}};var sH=r("./src/agent/native/vendored-tree-sitter.ts"),iH=r("./src/agent/platform-package-locator.ts"),aH=r("./src/agent/sdk-config.ts"),cH=r("../../node_modules/.pnpm/@statsig+js-client@3.31.0/node_modules/@statsig/js-client/src/index.js"),lH=r("./src/agent/utils/logger.ts");const uH={checkFeatureGate:()=>!1,getDynamicConfigValue:({defaultValue:e})=>e},dH=new Map;async function hH(e){try{const t=await async function(e){const t=await(0,tH.dC)(e,tH.EV);if(!t)return;const r=tH.EV.endsWith("/")?tH.EV.slice(0,-1):tH.EV,n=await fetch(`${r}/aiserver.v1.AnalyticsService/BootstrapStatsig`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json","x-cursor-client-type":"sdk","x-cursor-client-version":(0,tH.tF)(),"x-ghost-mode":(0,tH.U)(e)},body:JSON.stringify({})});if(!n.ok)return void lH.v.log(`Failed to bootstrap SDK Statsig: ${n.status} ${n.statusText}`);const o=await n.json();return pH(o)&&"string"==typeof o.config&&o.config.length>0?o.config:void 0}(e);if(!t)return uH;const r=new cH.StatsigClient("client-Bm4HJ0aDjXHQVsoACMREyLNxm5p6zzuzhO50MgtoT5D",function(e){try{const r=JSON.parse(e);if(pH(r)&&"object"==typeof(t=r.user)&&null!==t&&!Array.isArray(t))return{...r.user,custom:{...r.user.custom,clientType:"sdk",clientVersion:(0,tH.tF)()}}}catch(e){lH.v.log(`Failed to parse SDK Statsig bootstrap user: ${e instanceof Error?e.message:String(e)}`)}var t;return{custom:{clientType:"sdk",clientVersion:(0,tH.tF)()}}}(t),{disableLogging:!0,disableStorage:!0,networkConfig:{preventAllNetworkTraffic:!0}});return r.dataAdapter.setData(t),r.initializeSync(),{checkFeatureGate:(e,t)=>{try{return r.checkGate(e,t)}catch{return!1}},getDynamicConfigValue({configName:e,paramName:t,defaultValue:n}){try{return r.getDynamicConfig(e).get(t,n)}catch{return n}}}}catch(e){return lH.v.log(`Failed to initialize SDK Statsig: ${e instanceof Error?e.message:String(e)}`),uH}}function pH(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function fH(e){let t;return e?.then((e=>{t=e}),(()=>{})),()=>t?.checkFeatureGate("grok_bot_mcp_app_payment_token_filter",{disableExposureLog:!0})??!1}var mH=r("./src/agent/tools-option.ts");class gH{async requestApproval(){return{approved:!0}}}function wH(e,t){if(!function(e){return void 0!==e&&Object.keys(e).length>0}(t))return;const r=e.resources.base;if(!(r instanceof sD))throw new OW.j1("SDK custom tools require the default local workspace resource provider.",{isRetryable:!1});const n=r.getMcpExecutionPolicyDeps(),o=r.get(eo),s=function(e,t){return{async execute(r,n,o){const s=n.toolName||function(e){const t=`${zn}-`;return e.startsWith(t)?e.slice(t.length):e}(n.name),i=e[s];if(void 0===i)return new Ac.iz({result:{case:"error",value:new Ac.Nh({error:`Unknown custom tool: ${s}`})}});try{return function(e){const t=function(e){return"object"==typeof(t=e)&&null!==t&&!Array.isArray(t)&&"content"in t&&Array.isArray(t.content)?{content:e.content,isError:e.isError,structuredContent:e.structuredContent}:"string"==typeof e?{content:[{type:"text",text:e}]}:{content:[{type:"text",text:JSON.stringify(e)}],structuredContent:DW(e)?e:void 0};var t}(e),r=void 0!==t.structuredContent?we.Struct.fromJson(t.structuredContent):void 0;return new Ac.iz({result:{case:"success",value:new Ac.QW({content:t.content.map(MW),isError:t.isError??!1,structuredContent:r})}})}(await i.execute(function(e){return Object.fromEntries(Object.entries(e.args).map((([e,t])=>[e,t.toJson()])))}(n),{toolCallId:n.toolCallId||void 0,...void 0===t||""===t?{}:{sessionId:t}}))}catch(e){return new Ac.iz({result:{case:"error",value:new Ac.Nh({error:e instanceof Error?e.message:String(e)})}})}}}}(t,e.state.sessionId),i=new gH;e.resources.base.register(eo,{async execute(e,t,r){if(function(e){return e.providerIdentifier===zn}(t)){const o=await ET(e,t,{...n,pendingDecisionProvider:i,toolDef:{source:"internal"}});return void 0!==o?o:s.execute(e,t,r)}return o.execute(e,t,r)}})}const yH=new Set(["127.0.0.1","localhost","[::1]"]);function vH(e){if(void 0===e)return{};const t=e.resourceProviderOptions;return{...void 0!==t?{localResourceProviderOptions:t}:{},...void 0!==e.reportedWorkspacePath?{reportedWorkspacePath:e.reportedWorkspacePath}:{}}}function bH(){const e=process.env.CURSOR_SDK_MOCK_PROMPT_TIME;if(void 0===e||""===e)return;const t=new Date(e);return Number.isNaN(t.getTime())?void 0:t}const SH={warn(){},error(){}},kH={log(){}};class _H{async requestApproval(e){return{approved:!1,reason:`Local SDK runs cannot request interactive approval for ${CH(e)}. Keep the action within the configured sandbox policy or Smart Auto Review's auto-approval boundary, or re-run without sandboxing/autoReview enabled.`}}}function CH(e){switch(e.type){case Lw.Shell:return"this shell command";case Lw.Mcp:return"this MCP tool call";case Lw.Write:return"this file edit";case Lw.Delete:return"this file deletion";default:return"this operation"}}function EH(e){return void 0!==e&&"insecure_none"!==e.type}async function xH(e,t){const r="string"==typeof e||void 0===e?{workingDirectory:e,apiKey:t}:e,a=(0,y.q6)().with(l._O,kH),c=SB(r.settingSources),u=void 0===r.hostMcpBridgeUrls?void 0:r.hostMcpBridgeUrls.filter((e=>{let t;try{t=new URL(e)}catch{t=void 0}const r=void 0!==t&&"http:"===t.protocol&&""===t.username&&""===t.password&&yH.has(t.hostname);return r||console.warn(`[cursor-sdk] ignoring local.hostMcpBridgeUrls entry ${e}: not an http URL on 127.0.0.1, localhost or [::1]`),r}));!function(e){if(void 0!==e&&(!Number.isFinite(e)||e<=0))throw new Error(`Workspace scan cache TTL must be a positive number of milliseconds, got ${e}`);ya=e}((0,aH.Mu)()),/:\/\/(localhost|127\.0\.0\.1)/.test(tH.EV)&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0");const d=performance.now();let h=0;if(r.apiKey){const e=performance.now();await Promise.all([(0,tH.ly)(r.apiKey),(0,tH.mU)(r.apiKey)]),h=performance.now()-e}const p=r.workingDirectory||process.cwd();(0,sH.configureVendoredTreeSitterWorkspaceDir)(p);for(const e of r.dirs??[])(0,sH.configureVendoredTreeSitterWorkspaceDir)(e);const f=(0,So.Rv)((0,o.homedir)(),p),m={hostProjectDir:f,settings:{includeProjectRules:kB(c,"project"),subagentsService:new MB(r.customSubagents??[])}};let g;const w="win32"===process.platform?"rg.exe":"rg",v=process.env.CURSOR_RIPGREP_PATH;g=v&&(0,s.isAbsolute)(v)?v:(0,iH.hQ)({binaryName:w,excludedWorkspaceDir:p}),g||(g=(0,Oo.xS)()),g&&(0,Oo.J)(g);let b,S,k,_={getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getAdminCommandDenylist:async()=>({rules:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}};if(r.apiKey)try{const e=(0,tH.qN)(r.apiKey,r.teamId);b=e.transport,S=e.getAccessToken;const t=(0,ye.createClient)(fj.I,b),n=function(e){let t=dH.get(e);return t||(t=hH(e),dH.set(e,t),t.then((r=>{r===uH&&dH.get(e)===t&&dH.delete(e)}),(()=>{dH.get(e)===t&&dH.delete(e)}))),t}(r.apiKey);k=n;const o={getDefaultNetworkAllowlist:async()=>(await n).getDynamicConfigValue({configName:"sandbox_default_network_allowlist",paramName:"allowlist",defaultValue:[]})};_=new gO(new pO(t,{supportsHostMcpBridgeExemption:!0}),o,{...void 0===u?{}:{hostMcpBridgeUrls:u},mcpAdminToolLimitSurvivesFailedRead:!0,isMcpAccessNetworkAllowlistEnabled:async()=>(await n).checkFeatureGate("mcp_access_network_allowlist"),isMcpSettingsOverhaulEnabled:async e=>(await n).checkFeatureGate("mcp_settings_overhaul",e),isWin32UserExtensionStdioUnsandboxEnabled:async e=>(await n).checkFeatureGate("mcp_user_extension_stdio_unsandboxed_win32",e),isAdminCommandDenylistEnforcementKilled:async()=>(await n).checkFeatureGate("admin_command_denylist_enforcement_killswitch")})}catch(e){lH.v.log(`Failed to initialize authenticated dashboard services: ${e instanceof Error?e.message:String(e)}`)}const C=performance.now(),E=r.apiKey?await(0,Oo.tv)(`${(0,o.homedir)()}/.cursor/sandbox.json`,(0,o.homedir)()):void 0,x=void 0!==r.apiKey?await async function(e){const{cwd:t,perUserSandboxPolicy:r,sandboxOptions:n}=e;if(!1===n?.enabled)return{defaultSandboxPolicy:{type:"insecure_none"},defaultSandboxPolicySources:void 0};const o=EH(r)?r:!0===n?.enabled?function(e,t={}){return{type:e,...t}}("workspace_readwrite",{networkPolicy:(0,Oo.Po)()}):void 0;if(void 0===o)return{defaultSandboxPolicy:{type:"insecure_none"},defaultSandboxPolicySources:void 0};if(function(e){const t="win32"===process.platform?"cursorsandbox.exe":"cursorsandbox",r=(0,iH.hQ)({binaryName:t,excludedWorkspaceDir:e});r&&(0,Oo.St)({sandboxBinaryPath:r})}(t),!(0,Oo.K3)(void 0,{ctx:e.initializationCtx}))throw new OW.j1("Local SDK sandboxing was requested, but sandboxing is not supported in this environment. Disable local.sandboxOptions.enabled or remove ~/.cursor/sandbox.json to run without sandboxing.",{isRetryable:!1});const s={};s.perUser=o;const{policy:i}=await(0,Oo.resolveSandboxPolicyForWorkspace)(t,s);return{defaultSandboxPolicy:i,defaultSandboxPolicySources:s}}({cwd:p,perUserSandboxPolicy:E,sandboxOptions:r.sandboxOptions,initializationCtx:a}):void 0,P=performance.now()-C,R=x?.defaultSandboxPolicy,I=x?.defaultSandboxPolicySources,T=EH(R),A=performance.now(),M=(()=>{const e=[],t=new Set;for(const n of[p,...r.dirs??[]]){const r=(0,s.resolve)(n);t.has(r)||(t.add(r),e.push(n))}return e.length>1?e:void 0})(),D={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1},O=await async function(e){const{workingDirectory:t,projectDir:r}=e,n=function(e,t){const r=[],n=new Set;for(const o of[e,...t??[]]){const e=(0,s.resolve)(o);n.has(e)||(n.add(e),r.push(o))}return r}(t,e.dirs),o=n.length>1?n:void 0,i=SB(e.settingSources),a=e.teamSettingsService??{getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getAdminCommandDenylist:async()=>({rules:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}},c=e.defaultSandboxPolicy??{type:"insecure_none"},l=e.getSandboxSupported??(()=>(0,Oo.K3)(c,{ctx:e.initializationCtx})),u=e.getSandboxEnabled??(()=>"insecure_none"!==c.type&&l()),d=new _y,h=new xc(d,a,n),p=new TB,f=new AB,m=e.getSmartModeClassifierAutoModeEnabled?.(),g=new IB(m?"allowlist":e.approvalMode??"unrestricted",c,a,e.respectAdminControls??!1),w=e.pendingDecisionProvider,y={executeIndexedGrep:void 0},v=()=>!0,b=kB(i,"plugins"),S=e.importThirdPartyPlugins??!1,k=e.mcpMetaToolEnabled??!0,_=void 0!==e.mcpServers&&Object.keys(e.mcpServers).length>0,C=void 0!==e.customSubagents&&e.customSubagents.length>0,E=_||kB(i,"project")||kB(i,"user")||b,x=kB(i,"project")||kB(i,"user")||kB(i,"mdm"),P=kB(i,"team"),R=P&&void 0!==e.dashboardTransport,I=kB(i,"project")||kB(i,"user")||P||R||b,T={teamSettingsService:a,initializationCtx:e.initializationCtx,importThirdPartyPlugins:S,ignoreApprovals:!0,includeProjectMcp:kB(i,"project"),includeUserMcp:kB(i,"user"),includePluginMcp:b,isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled,restMcpCursorAuthTokenSupplier:e.restMcpCursorAuthTokenSupplier},A=s=>PB({workingDirectory:t,...void 0!==o?{workspaceRoots:o}:{},adapters:{...s.includeMcp?{mcp:VO({...T,inlineMcpServers:e.mcpServers})}:{},...b?{pluginBootstrap:tB({importThirdPartyPlugins:S,dashboardTransport:e.dashboardTransport})}:{},...x?{hooks:pj({includeProjectHooks:kB(i,"project"),includeUserHooks:kB(i,"user"),includeEnterpriseHooks:kB(i,"mdm"),useCommandHookStdinTransport:e.useCommandHookStdinTransport})}:{},...I?{localExtensibility:gj({includeProjectExtensibility:kB(i,"project"),includeUserExtensibility:kB(i,"user"),includeManagedSkills:R,includeTeamExtensibility:P,includePluginExtensibility:b,teamSettingsService:a,getThirdPartyExtensibilityEnabled:v,dashboardTransport:e.dashboardTransport,importThirdPartyPlugins:S})}:{},resourceFactory:dB({attributionConfigProvider:kB(i,"user")?{get(){try{const{readFileSync:r}=process.getBuiltinModule("node:fs"),{join:j}=process.getBuiltinModule("node:path"),{homedir:h}=process.getBuiltinModule("node:os"),x=process.env.XDG_CONFIG_HOME,d=process.env.CURSOR_CONFIG_DIR||(x&&process.platform!=="darwin"&&process.platform!=="win32"?j(x,"cursor"):j(h(),".cursor"));return JSON.parse(r(j(d,"cli-config.json"),"utf8"))}catch{return}}}:void 0,ignoreService:h,grepProvider:y,workspacePaths:n,diagnosticsProvider:p,repositoryProvider:f,projectDir:r??t,shellManager:void 0,defaultSandboxPolicy:c,defaultSandboxPolicySources:e.defaultSandboxPolicySources,getSandboxEnabled:u,getSandboxSupported:l,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:e.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:e.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:e.getMockPromptTime,getPowershellUtf8Options:e.getPowershellUtf8Options,mcpFileOutputThresholdBytes:void 0,mcpMetaToolEnabled:k,createMcpStateAccessor:(e,t)=>new $B(new oM(e),void 0===t?.onMcpAllowlistInUse&&void 0===t?.onMcpServerBlockedByAllowlist?void 0:{mcpLease:e,onMcpAllowlistInUse:t.onMcpAllowlistInUse,onMcpServerBlockedByAllowlist:t.onMcpServerBlockedByAllowlist}),createSessionMcpLease:(t,r)=>VO({...T,includeProjectMcp:T.includeProjectMcp&&!0!==t.options.excludeProjectMcp,inlineMcpServers:r??e.mcpServers}).createLease({workspaceState:t.workspaceState,services:t.workspaceServices,policy:t.policy}),createSessionDependencies:r=>{const n=w??new RB;return{pendingDecisionStore:n,fileChangeTracker:new Bw(t),permissionsService:new t_(h,n,g,a,t,e.respectAdminControls??!1,{enforceMcpAdminToolLimits:e.isMcpAdminToolLimitEnforced,onMcpAdminToolLimitCheck:r.options.onMcpAdminToolLimitCheck})}}}),resourceWrappers:x?[{wrapResources(e){const t=e.workspaceServices.hooksRuntime;if(!0===e.options.excludeHooks||"object"!=typeof(r=t)||null===r||!("hooksConfigLease"in r)||!("createSessionRuntime"in r)||"function"!=typeof r.createSessionRuntime||!function(e){return"object"==typeof e&&null!==e&&"get"in e&&"function"==typeof e.get&&"entries"in e&&"function"==typeof e.entries}(e.resources))return e.resources;var r;const n=t.createSessionRuntime({sessionState:e.sessionState,metadata:e.metadata});return new dj(new oj(e.resources,n.hookExecutor,(()=>function(e,t){const r=aj(t,cj,"conversationId","conversation_id")??e.sessionId??"";return{conversation_id:r,generation_id:aj(t,cj,"generationId","generation_id")??r,model:aj(t,cj,"model")??"unknown",...hF({modelId:aj(t,cj,"modelId","model_id"),modelParams:aj(t,uj,"modelParams","model_params")})}}(e.sessionState,e.metadata)),e.workspaceServices.mcpLease,void 0,void 0,t.hooksConfigLease),n)}}]:[],...C?{workspaceServicesContributors:[{contributeServices:t=>{const r=new MB(e.customSubagents??[]),n=t.services.subagentsService;return{subagentsService:void 0===n?r:new Ig([r,n])}}}]}:{}}});if(!E)return A({includeMcp:!1});try{return await A({includeMcp:!0})}catch(e){return SO.Jz.warn("[default-local-workspace-runtime] Failed to initialize MCP-enabled runtime, retrying without MCP:",{error:e,workingDirectory:t,projectDir:r,enablePlugins:b,importThirdPartyPlugins:S}),A({includeMcp:!1})}}({workingDirectory:p,...void 0!==M?{dirs:M}:{},projectDir:f,teamSettingsService:_,initializationCtx:a,dashboardTransport:b,settingSources:r.settingSources,mcpServers:r.mcpServers,customSubagents:r.customSubagents,defaultSandboxPolicy:R,defaultSandboxPolicySources:I,approvalMode:T?"allowlist":void 0,pendingDecisionProvider:T||!0===r.autoReview?new _H:void 0,getNetworkAllowlistInfo:T?()=>async function(e,t,r){const[n,o]=await Promise.all([e.getDefaultNetworkAllowlist(),e.getNetworkAccessControls()]),s=[...o.allowlist],i=`${t}/.cursor/sandbox.json`,a=await(0,Oo.tv)(i,t);if(a&&"insecure_none"!==a.type&&a.networkPolicy?.allow&&s.push(...a.networkPolicy.allow),"1"!==process.env[Zv.K4]&&r){const e=await(0,Oo.tv)(`${r}/.cursor/sandbox.json`,r);e&&"insecure_none"!==e.type&&e.networkPolicy?.allow&&s.push(...e.networkPolicy.allow)}const c=[...new Set(s)];return{hasDefaults:n.available&&n.allowlist.length>0,explicitEntries:c}}(_,(0,o.homedir)(),p):void 0,getSmartModeClassifierAutoModeEnabled:()=>!0===r.autoReview,devForceNextSmartModeClassifierBlockToken:r.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:bH,getPowershellUtf8Options:async()=>{if(void 0===k)return D;try{const e=await k;return{powershellUtf8Console:e.checkFeatureGate("shell_exec_powershell_utf8_console"),powershellUtf8ChildEnv:e.checkFeatureGate("shell_exec_powershell_utf8_child_env")}}catch{return D}},isLinkSharedPaymentTokenLogRedactionEnabled:fH(k),restMcpCursorAuthTokenSupplier:S,respectAdminControls:void 0!==r.apiKey,isMcpAdminToolLimitEnforced:void 0===k?void 0:(F=k,async()=>{try{return(await F).checkFeatureGate("sdk_local_mcp_admin_tool_limits",{disableExposureLog:!0})}catch{return!1}}),useCommandHookStdinTransport:!0});var F;const N=performance.now()-A;let L,j;return(0,XB.ou)(r.apiKey,{runtime:"local",ensure_ghost_mode_ms:Math.round(h),bootstrap_statsig_ms:0,create_workspace_runtime_ms:Math.round(N),load_sandbox_policy_ms:Math.round(P),total_ms:Math.round(performance.now()-d)}),{run:async(e,t,o)=>(0,SO.ni)(SH,(async()=>{const s=(0,$.VI)((0,y.q6)().withName("sdk.run").with(l._O,kH)),[a,c]=s.ctx.withCancel(),u=t.sessionId??(0,ge.C)(),d=t.mcpServersOverride,h=void 0===(f=t.customTools)?[]:Object.entries(f).map((([e,t])=>({clientKey:zn,providerIdentifier:zn,toolName:e,name:`${zn}-${e}`,description:t.description??"",inputSchema:t.inputSchema??AW,...void 0===t.outputSchema?{}:{outputSchema:t.outputSchema},...void 0===t.annotations?{}:{annotations:$W(t.annotations)},source:"internal"})));var f;let g;const w={...m,workspace:t.fileSystemWorkspace},v=void 0===t.fileSystem?void 0:(_=await async function(e,t){return"function"==typeof e?await e(t):e}(t.fileSystem,{agentId:u,sessionId:u}),C=_,(0,UW.VL)({"/":C,[HW]:(0,BW.Om)()})),b=void 0===t.onMcpAdminToolLimitCounts?void 0:new rH,S=()=>{for(const e of b?.take()??[])try{t.onMcpAdminToolLimitCounts?.(e)}catch{}},k=new nH;var _,C;g=await O.createSessionRuntime({sessionId:u,mcpServersOverride:d,extraMcpTools:h,onMcpAdminToolLimitCheck:b?.record,onMcpAllowlistInUse:oH.report,onMcpServerBlockedByAllowlist:k.report,...void 0===v?vH(t.sessionResources):eH(v,w)});const E=new Map;try{const s=g.resources.wrapped;wH(g,t.customTools),void 0!==v&&LW(g.resources.base);const l=t.blobStore??new re.ve;let f=t.initialState??new i.Y9z({});const m=void 0!==t.model?new JB.G4({modelId:t.model.id,...!0===t.model.maxMode?{maxMode:!0}:{},parameters:(t.model.params??[]).map((e=>new JB.SR({id:e.id,value:e.value})))}):void 0,y=!0===e.summarize?void 0:e.images,_=Array.isArray(y)?y.map((e=>{const t=(0,ge.C)(),r=new Uint8Array(n.Buffer.from(e.data,"base64")),o=(0,tH.v8)(r);return new ZB.d({uuid:t,...o?{mimeType:o}:{},dataOrBlobId:{case:"data",value:r}})})):[],C=_.length>0?new ZB.xv({selectedImages:_}):void 0,R=function(e){switch(e){case"agent":return i.xyI.AGENT;case"plan":return i.xyI.PLAN;default:return}}(t.mode),I=e.resume===!0?new i.QFf({action:{case:"resumeAction",value:new i.qKo}}):!0===e.summarize?new i.QFf({action:{case:"summarizeAction",value:new i.Scs}}):new i.QFf({action:{case:"userMessageAction",value:new i.Vtf({userMessage:new i.RGk({text:e.text,selectedContext:C,...void 0!==R?{mode:R}:{}})})}}),T={sendUpdate:async(e,t)=>{const r=sW(t,u);null!==r&&await o.sendUpdate(r)},query:async(e,r)=>await async function(e,t){if("mcpAuthRequestQuery"===e.query.case&&void 0!==t){const r=await async function(e,t,r){let n;try{n=await e({serverName:r.args?.serverIdentifier??"",toolCallId:r.args?.toolCallId??""})}catch{return kr(t,"The MCP sign-in request failed.")}if(void 0!==n)switch(n.kind){case"approved":return Sr(t);case"rejected":return kr(t,n.reason);default:return n}}(t,e.id,e.query.value);if(void 0!==r)return r}return function(e){switch(e.query.case){case"webSearchRequestQuery":return ur(e.id);case"webFetchRequestQuery":return hr(e.id);case"switchModeRequestQuery":return mr(e.id);case"askQuestionInteractionQuery":return fr(e.id,new Qt.tz({result:{case:"rejected",value:new Qt.ox({reason:"Interactive questions are not supported in local SDK runs"})}}));case"createPlanRequestQuery":return wr(e.id,new Yt.bK({result:{case:"success",value:new Yt.Jo},planUri:""}));case"setupVmEnvironmentArgs":return yr(e.id,new rr.r$({result:{case:"success",value:new rr.JH}}));case"replaceEnvArgs":return vr(e.id,new tr.dV({result:{case:"failure",value:new tr.uq({errorMessage:"Environment replacement is not supported in local SDK runs",setupLogs:""})}}));case"prManagementRequestQuery":return br(e.id,new er.HL({result:{case:"error",value:new er.K$({error:"PR management is only available in cloud agents"})}}));case"mcpAuthRequestQuery":return kr(e.id,"MCP authentication is not supported in local SDK runs");case"connectScmRequestQuery":return _r(e.id,"Connecting GitHub is not supported in local SDK runs");case"generateImageRequestQuery":return Cr(e.id,e.query.value.args?.description);case void 0:throw new OW.j1("Missing interaction query type",{isRetryable:!1});default:throw e.query,new OW.j1("Unhandled interaction query type",{isRetryable:!1})}}(e)}(r,t.onMcpAuthRequest)};if(L!==t.apiKey||!j){await Promise.all([(0,tH.ly)(t.apiKey),(0,tH.mU)(t.apiKey)]);const e=(0,tH.KU)(t.apiKey,r.teamId),n=vo((0,ye.createClient)(KB.N,e),{injectTraceHeaders:!0});j=new Wn(n),L=t.apiKey}const A=(0,tH.Vh)(j,(()=>{const e=(0,tH.KU)(t.apiKey,r.teamId),n=vo((0,ye.createClient)(KB.N,e),{injectTraceHeaders:!0}),o=new Wn(n);return j=o,L=t.apiKey,o})),$=function(e){return{...void 0!==e.allowedTools?{[mH.$$]:e.allowedTools.join(",")}:{},...void 0!==e.disallowedTools&&e.disallowedTools.length>0?{[mH.VJ]:e.disallowedTools.join(",")}:{}}}(t),M=new VB({agentClient:A,rootRequestId:t.requestId,getResources:async({agentId:e})=>{let r=E.get(e);return r||(r=await O.createSessionRuntime({sessionId:e,mcpServersOverride:d,extraMcpTools:h,onMcpAdminToolLimitCheck:b?.record,onMcpAllowlistInUse:oH.report,onMcpServerBlockedByAllowlist:k.report,...void 0===v?vH(t.subagentInherit):eH(v,w)}),wH(r,t.customTools),void 0!==v&&LW(r.resources.base),r.resources.base.register(io,D),r.resources.base.register(ao,F),r.resources.base.register(co,N),E.set(e,r)),r.resources.wrapped},mcpTools:h,workspacePath:p,parentConversationId:u,...(void 0!==t.subagentInherit||void 0!==v)&&Object.keys($).length>0?{headers:$}:{},onSessionReleased:e=>{const t=E.get(e);t&&(t.dispose(),E.delete(e))}}),D=function(e){const t=new Map,r=new Map;async function n(t,r,n){let o;try{o=await e.createOrResumeSession(t,r);const s=await e.runSession(t,o,r,{execId:n?.execId});return"error"===s.status?new oo.vS({result:{case:"error",value:new oo.od({agentId:o,error:s.error})}}):"aborted"===s.status?new oo.vS({result:{case:"error",value:new oo.od({agentId:o,error:s.error??"Subagent was aborted by the user"})}}):"background"===s.status?new oo.vS({result:{case:"success",value:new oo.HJ({agentId:o,finalMessage:s.finalMessage,toolCallCount:s.toolCallCount??0,backgroundReason:s.backgroundReason,transcriptPath:s.transcriptPath})}}):new oo.vS({result:{case:"success",value:new oo.HJ({agentId:o,finalMessage:s.finalMessage,toolCallCount:s.toolCallCount??0})}})}catch(t){if(o&&e.releaseSession&&e.releaseSession(o),t instanceof lr)throw t;const n=t instanceof Error?t.message:String(t),s=o??function(e){return e instanceof so&&e.agentId||e&&"object"==typeof e&&"agentId"in e&&"string"==typeof e.agentId?e.agentId:void 0}(t)??r.resumeAgentId;return new oo.vS({result:{case:"error",value:new oo.od({...s?{agentId:s}:{},error:n})}})}}return{execute(e,o,s){const i=function(e){if(e.toolCallId&&e.parentConversationId)return[e.parentConversationId,e.toolCallId,e.resumeAgentId??"",e.forkAgentId??""].join("\0")}(o);if(void 0===i)return n(e,o,s);const a=r.get(i);if(void 0!==a)return Promise.resolve(a);const c=t.get(i);if(void 0!==c)return c;const l=n(e,o,s).then((e=>("success"===e.result.case&&(r.set(i,e),r.size>1e3&&r.delete(r.keys().next().value)),e))).finally((()=>{t.delete(i)}));return t.set(i,l),l}}}(M),F=(P=M,{execute:(e,t)=>P.awaitBackgroundRunBounded(e,t)}),N=function(e){return{execute:async(t,r)=>e.forceBackgroundByToolCallId(r.toolCallId)}}(M);g.resources.base.register(io,D),g.resources.base.register(ao,F),g.resources.base.register(co,N);const U=O.services.hooksRuntime,B="object"==typeof(x=U)&&null!==x&&"workspacePath"in x&&"string"==typeof x.workspacePath&&"createSessionRuntime"in x&&"function"==typeof x.createSessionRuntime?U:void 0,W=void 0!==B&&void 0===v&&!0!==e.summarize?function(e){const{workspaceRuntime:t}=e;if(!(t.hooksConfigLease.hasHookForStep(xd.sessionStart)||t.hooksConfigLease.hasHookForStep(xd.sessionEnd)||t.hooksConfigLease.hasHookForStep(xd.stop)||t.hooksConfigLease.hasHookForStep(xd.beforeSubmitPrompt)))return{};const r=t.createSessionRuntime({sessionState:e.sessionState,metadata:e.metadata}),{hookExecutor:n}=r;let o;return{async onSessionStart(e){if(o=e,n.hasHooksForStep(xd.sessionStart))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...hF(e),is_background_agent:!1},r=await n.executeHookForStep(xd.sessionStart,t);if(r)return r.env&&n.setSessionEnvironment(r.env),{env:r.env,additionalContext:r.additional_context,blocked:!1===r.continue,blockedReason:r.user_message}}catch(e){SO.Jz.warn("[hooks-adapter] sessionStart hook failed:",e)}},async onSessionEnd(e,t){if(n.hasHooksForStep(xd.sessionEnd))try{const r={conversation_id:o?.conversationId??"",generation_id:o?.generationId??"",model:o?.model??"unknown",...o?hF(o):{},reason:e,duration_ms:t,is_background_agent:!1,final_status:e};await n.executeHookForStep(xd.sessionEnd,r)}catch(e){SO.Jz.warn("[hooks-adapter] sessionEnd hook failed:",e)}finally{n.clearSessionEnvironment()}else n.clearSessionEnvironment()},async onBeforeSubmitPrompt(e){if(n.hasHooksForStep(xd.beforeSubmitPrompt))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...hF(e),prompt:e.promptText??"",attachments:[]};await n.executeHookForStep(xd.beforeSubmitPrompt,t)}catch(e){SO.Jz.warn("[hooks-adapter] beforeSubmitPrompt hook failed:",e)}},async onTurnCompleted(e){if(!n.hasHooksForStep(xd.stop))return;const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...hF(e),status:"completed",loop_count:e.loopCount},r=await n.executeHookForStep(xd.stop,t),o="string"==typeof r?.followup_message?r.followup_message.trim():"";return o.length>0?o:void 0},async onTurnError(e){if(n.hasHooksForStep(xd.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...hF(e),status:"error",loop_count:e.loopCount};await n.executeHookForStep(xd.stop,t)}catch(e){SO.Jz.warn("[hooks-adapter] onTurnError stop hook failed:",e)}},async onTurnAborted(e){if(n.hasHooksForStep(xd.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...hF(e),status:"aborted",loop_count:e.loopCount};await n.executeHookForStep(xd.stop,t)}catch(e){SO.Jz.warn("[hooks-adapter] onTurnAborted stop hook failed:",e)}},async dispose(){await r.dispose()}}}({workspaceRuntime:B,sessionState:g.state,metadata:g.metadata}):void 0,H=new qB({workspacePath:p,conversationId:u,blobStore:l}),q=function(e,t,r){const{hooks:n}=r,[o,s]=e.withCancel(),a=new bO;let c;const l=new Map,u=(e,t)=>{const r=l.get(e);void 0!==r&&(l.delete(e),clearTimeout(r.ackTimer),r.resolve(t))};let d;const h=[],p=e=>{for(const t of h.splice(0))t.resolve(e)},f=()=>{if(0===h.length)return;const e=h.map((e=>e.text)).join("\n\n");return p("complete_delivered"),RO(e)},m=r.interactionListener,g={async sendUpdate(e,t){const r=t.message;if("contextInjectionState"===r?.case){const e=r.value,t="object"==typeof e&&null!==e&&"injectionId"in e&&"string"==typeof e.injectionId?e.injectionId:void 0,n=function(e){if("object"!=typeof e||null===e||!("state"in e))return;const t=e.state;if("object"!=typeof t||null===t||!("state"in t))return;const r=t.state;return"object"==typeof r&&null!==r&&"case"in r&&"string"==typeof r.case?r.case:void 0}(e),o=function(e){switch(e){case"queued":return"queued";case"delivered":return"delivered";case"queuedForNextTurn":return"queued_for_next_turn";case"cancelled":return"cancelled";default:return"rejected"}}(n),s=void 0===t?void 0:l.get(t);if(void 0!==s&&void 0!==t){const e=function(e){switch(e){case"queued":return"confirm_steering";case"delivered":return"complete_delivered";case"queued_for_next_turn":case"cancelled":case"rejected":return"revert_to_followup";default:throw new Error(`Unknown steer ack state: ${String(e)}`)}}(o);"confirm_steering"===e?clearTimeout(s.ackTimer):(l.delete(t),s.resolve(e))}}await m.sendUpdate(e,t)},query:(e,t)=>m.query(e,t),...void 0!==m.enqueuePostTurnEndedWork?{enqueuePostTurnEndedWork:e=>m.enqueuePostTurnEndedWork?.(e)}:{},...void 0!==m.flushPostTurnEndedWork?{flushPostTurnEndedWork:e=>m.flushPostTurnEndedWork?.(e)??Promise.resolve()}:{}};let w=r.initialState;const y={async handleCheckpoint(e,t){w=t,await(r.onCheckpoint?.(t))},getLatestCheckpoint:()=>w};let v="completed";const b=Date.now(),S=CO(function(e,t){if((0,kO.TU)(t))return t;const r=EO.get(e);if(void 0!==r)return r;const n=(0,kO.sh)(e).blobEncryptionKey;if(void 0===n)throw new Error("getDefaultAgentMetadata did not seed a blobEncryptionKey");return EO.set(e,n),n}(r.conversationId,r.blobEncryptionKey),r.runOptions?.headers);return{done:(async()=>{const e=PO(r,0,xO(t));try{const t=await(n?.onSessionStart?.(e));if(t?.blocked)throw v="error",new Error(t.blockedReason??"Session blocked by sessionStart hook")}catch(e){if("completed"!==v)throw e;SO.Jz.warn("[agent-session-runner] sessionStart hook failed:",e)}let s=t,i=0;for(;s;){const e=PO(r,i,xO(s));try{await(n?.onBeforeSubmitPrompt?.(e))}catch(e){SO.Jz.warn("[agent-session-runner] beforeSubmitPrompt hook failed:",e)}c=r.runOptions?.generationUUID??(0,ge.C)();try{await r.agentClient.run(o,w,s,void 0,g,r.resources,r.blobStore,a,y,r.mcpTools??[],{conversationId:r.conversationId,...r.runOptions,generationUUID:c,headers:S,subagentModelOverrides:r.runOptions?.subagentModelOverrides??[]})}catch(t){throw v=IO(t)?"aborted":"error",TO("aborted"===v?n?.onTurnAborted?.(e):n?.onTurnError?.(e)),t}finally{c=void 0;for(const e of[...l.keys()])u(e,"revert_to_followup")}let t;try{t=await(n?.onTurnCompleted?.(e))}catch(e){throw v="error",e}const h="string"==typeof t?t.trim():"";let m;if(h.length>0)m=RO(h);else{const t=new AbortController;d=t;try{m=await(r.nextAction?.(e,AbortSignal.any([o.signal,t.signal])))}catch(r){if(o.signal.aborted||!t.signal.aborted)throw v=o.signal.aborted||IO(r)?"aborted":"error",TO("aborted"===v?n?.onTurnAborted?.(e):n?.onTurnError?.(e)),r}finally{d=void 0}void 0===m?m=f():p("revert_to_followup")}void 0!==m?(i+=1,a.resetStream(),s=m):s=void 0}})().finally((async()=>{p("revert_to_followup");const e=Date.now()-b;try{await(n?.onSessionEnd?.(v,e))}catch(e){SO.Jz.warn("[agent-session-runner] sessionEnd hook failed:",e)}try{await(n?.dispose?.())}catch(e){SO.Jz.warn("[agent-session-runner] hooks dispose failed:",e)}})),abort(){s()},async steer(e){if(""===e.trim())return"revert_to_followup";const t=c;if(void 0===t){const t=d;if(void 0===t)return"revert_to_followup";const r=new Promise((t=>{h.push({text:e,resolve:t})}));return t.abort(),await r}const r=(0,ge.C)(),n=new Promise((e=>{const t=setTimeout((()=>{u(r,"revert_to_followup")}),15e3);t.unref?.(),l.set(r,{resolve:e,ackTimer:t})}));try{return await a.submitConversationAction(new i.QFf({action:{case:"injectContextAction",value:new i.hGJ({injectionId:r,expectedRunId:t,payload:{case:"userContext",value:new i.oW$({userMessage:new i.RGk({messageId:(0,ge.C)(),text:e})})}})}})),await n}catch(e){return u(r,"revert_to_followup"),SO.Jz.warn("[agent-session-runner] context injection failed:",e),"revert_to_followup"}}}}(a,I,{agentClient:A,interactionListener:T,resources:s,blobStore:l,initialState:f,conversationId:u,mcpTools:h,blobEncryptionKey:t.blobEncryptionKey,runOptions:{generationUUID:t.requestId,requestedModel:m,enableAgentRetries:!1!==r.enableAgentRetries,emitModelCallUsage:!0,...void 0!==t.onConnectionStateChange?{onConnectionStateChange:e=>{!function(e,t){if(void 0!==e)try{e(function(e){switch(e.state){case"connected":return{state:"connected"};case"reconnecting":{const t=e.trigger?.errorClass,r=e.trigger?.stallAborted,n={...void 0!==t?{errorClass:t}:{},...void 0!==r?{stallAborted:r}:{}};return{state:"reconnecting",attempt:e.attempt,...Object.keys(n).length>0?{trigger:n}:{}}}default:return e}}(t))}catch(e){lH.v.warn(`onConnectionStateChange failed: ${e instanceof Error?e.message:String(e)}`)}}(t.onConnectionStateChange,e)}}:{},...Object.keys($).length>0?{headers:$}:{},...void 0!==t.systemPrompt?{customSystemPrompt:t.systemPrompt}:{}},hooks:W,async nextAction(e,t){const r=await M.waitForBackgroundCompletions(u,t);return r.length>0?function(e){return new i.QFf({action:{case:"backgroundTaskCompletionAction",value:new i.Kwc({completions:e.map((e=>new i.KFq({taskId:e.agentId,kind:i.aZc.SUBAGENT,status:"success"===e.status?i.uHL.SUCCESS:"aborted"===e.status?i.uHL.ABORTED:i.uHL.ERROR,...e.finalMessage.length>0?{detail:e.finalMessage}:{}})))})}})}(r):void 0},async onCheckpoint(e){f=e,H.writeFromState(a,e),await(t.onCheckpoint?.(e))}}),z=q.done.finally((async()=>{try{await M.awaitBackgroundWorkers()}finally{await H.waitForPendingWrites().catch((()=>{}));for(const e of E.values())try{await e.dispose()}catch(e){lH.v.log(`Failed to dispose subagent session runtime: ${e instanceof Error?e.message:String(e)}`)}E.clear();try{await g.dispose()}finally{S()}}})).catch((e=>{throw e}));return{abort(){q.abort(),c()},done:z,steer:e=>q.steer(e)}}catch(e){for(const e of E.values())try{await e.dispose()}catch{}E.clear();try{await g.dispose()}finally{S()}throw e}var x,P})),async reload(){await O.reload()},async dispose(){await O.dispose()}}}},"./src/agent/native/tree-sitter-bash.webpack.cjs"(e,r,n){const{loadVendoredTreeSitterModule:o}=n("./src/agent/native/vendored-tree-sitter.ts"),s=o({packageName:"tree-sitter-bash",nativeRequire:t});e.exports=s.available?s.module:{}},"./src/agent/native/tree-sitter.webpack.cjs"(e,r,n){const{createUnavailableParserClass:o,loadVendoredTreeSitterModule:s}=n("./src/agent/native/vendored-tree-sitter.ts"),i=s({packageName:"tree-sitter",nativeRequire:t});e.exports=i.available?i.module:o(i.reason)},"../constants/dist/commercial-cursor-hosts.js"(e,t,r){r.d(t,{H:()=>c,K4:()=>i,Zf:()=>a,ad:()=>l});const n=["cursor.sh","cursor.com","cursorapi.com","cursor.so","cursor-marketplace.com","cursorusercontent.com","anysphere.co"],o=["cursor.blob.core.windows.net"];function s(e){return e.trim().toLowerCase().replace(/\.+$/,"")}const i="CURSOR_ORBIT_BUILD",a="CURSOR_ORBIT_DEPLOYMENT_HOSTS";function c(e){return new Set((e??"").split(",").map(s).filter((e=>""!==e)))}function l(e,t){return function(e){const t=s(e);return o.includes(t)||n.some((e=>t===e||t.endsWith(`.${e}`)))}(e)&&!t.has(s(e))}},"../context/dist/otel.js"(e,t,r){r.d(t,{F:()=>E,HF:()=>_,MG:()=>k,Mf:()=>v,OA:()=>y,V5:()=>C,VI:()=>P,fR:()=>g,fU:()=>w,mJ:()=>b,r2:()=>x,xd:()=>R});var n=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js"),o=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/context-api.js"),s=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace-api.js"),i=r("../context/dist/core.js");const a=(0,i.cF)(Symbol("otel.span"),void 0),c=(0,i.cF)(Symbol("otel.root_span"),void 0),l=(0,i.cF)(Symbol("otel.root_start_ms"),void 0),u=(0,i.cF)(Symbol("otel.suppress_child_spans"),!1),d=(0,i.cF)(Symbol("otel.inheritable_span_attributes"),{});function h(e,t){const r=t.get(d);for(const t in r){const n=r[t];"string"!=typeof n&&"number"!=typeof n&&"boolean"!=typeof n||e.setAttribute(t,n)}}function p(e){return e.name||"anonymous-context"}function f(e,t){return!!t&&(e.get(u)||(p(e),!1))}function m(e="context-tracer"){return s.u.getTracer(e)}function g(e,t){const r=m(),n=e.get(a);if(f(e,n))return e;const i=p(e);let u;if(n){const e=s.u.setSpan(o._.active(),n);u=r.startSpan(i,t,e)}else u=r.startSpan(i,t);h(u,e);const d=Date.now();let g=e.with(a,u);return n||(g=g.with(c,u).with(l,d)),g}function w(e){return e.get(a)}function y(e){return e.with(u,!0)}function v(e,t,r){const n=e.get(d),o=w(e);return o&&null!==r&&o.setAttribute(t,r),e.with(d,{...n,[t]:r})}function b(e){try{const t=w(e);if(!t)return;const r=t.spanContext(),n=e.get(u);return{traceId:r.traceId,spanId:r.spanId,traceFlags:n?0:r.traceFlags,traceState:r.traceState?.serialize()}}catch{return}}const S=Symbol.for("anysphere.context.activeOtelSpanAls");function k(e,t){const r=()=>o._.with(s.u.setSpan(o._.active(),e),t),n=function(){const e=globalThis;if("object"!=typeof(t=e)||null===t||!(S in e))return;var t;const r=e[S];return function(e){return"object"==typeof e&&null!==e&&"run"in e&&"function"==typeof e.run&&"getStore"in e&&"function"==typeof e.getStore}(r)?r:void 0}();return void 0===n?r():n.run(e,r)}function _(e,t){try{const r=m(),n=w(e);if(!n)return;const i=s.u.setSpan(o._.active(),n),a=r.startSpan(t,void 0,i);h(a,e);const u=Date.now(),d=e.get(l),p="number"==typeof d?u-d:0,f=`event.${t}`;(e.get(c)??n).setAttribute(f,p),a.setAttribute(f,p),a.end()}catch{}}function C(e,t,r){const c=m(),l={traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags,isRemote:!0},u=s.u.setSpanContext(o._.active(),l),d=t||"child.span",h=c.startSpan(d,{kind:n.v.INTERNAL},u),p=r??(0,i.q6)();return(t?p.withName(t):p).with(a,h)}function E(e,t,r){const n=s.u.wrapSpanContext({traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags,isRemote:!0}),o=r??(0,i.q6)();return(t?o.withName(t):o).with(a,n)}class x{constructor(e,t,r=!0){this.disposed=!1,this.ctx=e,this.span=t,this.shouldEnd=r}[Symbol.dispose](){this.disposed||(this.disposed=!0,this.shouldEnd&&this.span.end())}}function P(e,t){const r=f(e,w(e)),n=g(e,t),o=w(n);return new x(n,o,!r)}function R(e,t,r){const n=w(e);if(!n||f(e,n))return;const o=w(g(e,t));return o.end(r),o}},"../mcp-core/dist/transport/mcp-url-utils.js"(e,t,r){r.d(t,{$H:()=>Q,ME:()=>G,_N:()=>X,b6:()=>z,bi:()=>P,eA:()=>j,mD:()=>A,rM:()=>J,vc:()=>L});const n=BigInt(0),o=BigInt(8),s=BigInt(16),i=BigInt(65535);function a(e){const t=e.split(".");if(4!==t.length)return;let r=n;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<>s&i)),t.push(Number(o.value&i))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function l(e){return a(e)??function(e){const t=H(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=c(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<7?void 0:{version:6,value:[...a,...new Array(8-u).fill(0),...l].reduce(((e,t)=>e<=R&&d.clear();const t=l(e);return d.set(e,t),t}(e);return void 0!==r&&r.version===t.version&&r.value>>t.shift===t.shiftedNetwork}case"subdomainOrBase":return e===t.suffix||e.endsWith(`.${t.suffix}`);case"exact":return e===t.value;default:return t}}(H(e),function(e){const t=u.get(e);if(t)return t;u.size>=R&&u.clear();const r=function(e){const t=H(e);if("*"===t)return{kind:"matchAll"};if(t.includes("/")){const e=t.lastIndexOf("/");if(e<=0||e===t.length-1)return{kind:"invalidCidr"};const r=l(t.slice(0,e));if(!r)return{kind:"invalidCidr"};const n=Number(t.slice(e+1)),o=4===r.version?32:128;if(!Number.isInteger(n)||n<0||n>o)return{kind:"invalidCidr"};const s=BigInt(o-n);return{kind:"cidr",version:r.version,shift:s,shiftedNetwork:r.value>>s}}return t.startsWith("*.")?{kind:"subdomainOrBase",suffix:t.slice(2)}:{kind:"exact",value:t}}(e);return u.set(e,r),r}(t))}new Set(["airtable.com","anysphere.co","api.aws","apify.com","asana.com","ashbyhq.com","atlassian.com","atlassian.net","azuredatabricks.net","box.com","buildkite.com","calendly.com","canva.com","clickhouse.cloud","clickup.com","cloudflare.com","composio.dev","context7.com","cursor.com","cursor.sh","cursorapi.com","databricks.com","datadoghq.com","datadoghq.eu","ddog-gov.com","dropbox.com","elevenlabs.io","exa.ai","figma.com","firecrawl.dev","github.com","githubcopilot.com","gitlab.com","google.com","googleapis.com","granola.ai","hex.tech","hubspot.com","huggingface.co","intercom.com","linear.app","monday.com","neon.tech","notion.com","plain.com","posthog.com","prisma.io","railway.com","ramp.com","render.com","salesforce.com","sentry.dev","sentry.io","slack.com","snowflakecomputing.com","spacelift.io","statsig.com","stripe.com","supabase.com","todoist.net","vercel.com","workos.com","x.ai","x.com","zapier.com"]);const p="Blocked by MCP Network Admin Server Controls";function f(e){return/\s/.test(e)}const m="[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?",g=new RegExp(`^(?:${m}\\.)*${m}$`),w=new RegExp(`^\\*\\.(?:${m}\\.)*${m}$`),y="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)",v=new RegExp(`^${y}(?:\\.${y}){3}$`),b=/^[0-9a-f:]+$/,S=new RegExp(`^(?:${y}(?:\\.${y}){3}|[0-9a-f:]+)\\/\\d{1,3}$`);function k(e){const t=H(e);return t.length>0&&t.length<=253&&g.test(t)}function _(e){const t=H(e);return v.test(t)||function(e){const t=H(e);if(!b.test(t))return!1;try{return new URL(`https://[${t}]`),!0}catch{return!1}}(t)}function C(e,t){return""===t||"http:"===e&&"80"===t||"https:"===e&&"443"===t}function E(e){const t=new URL(e.pathname||"/",e.origin);if(t.search=e.search,t.pathname.endsWith("/")&&t.pathname.length>1&&(t.pathname=t.pathname.slice(0,-1)),"/"===t.pathname&&""===t.search){const t=e.protocol.toLowerCase();let r=`${t}//${e.hostname.toLowerCase()}`;return C(t,e.port)||(r+=`:${e.port}`),r}const r=e.protocol.toLowerCase();let n=`${r}//${e.hostname.toLowerCase()}`;return C(r,e.port)||(n+=`:${e.port}`),`${n}${t.pathname}${t.search}`}function x(e){if(e.includes("://"))return function(e){try{const t=new URL(e);return("http:"===t.protocol||"https:"===t.protocol)&&!(0===t.hostname.length||t.username.length>0||t.password.length>0)&&""===t.hash&&function(e){const t=e.toLowerCase();return!t.includes("*")&&(k(t)||_(t))}(t.hostname)}catch{return!1}}(e);const t=H(e);return"*"===t||!!w.test(t)||(t.includes("/")?function(e){const t=H(e);if(!S.test(t))return!1;const[r]=t.split("/");return void 0!==r&&h(r,t)}(t):k(t)||_(t))}function P(e){if(I.has(e))return I.get(e);I.size>=R&&I.clear();const t=function(e){const t=e.trim();if(0===t.length)return;const r=t.lastIndexOf("/");if(!t.includes("://")&&r>0&&/^\d+$/.test(t.slice(r+1).trim())){const e=`${H(t.slice(0,r))}/${t.slice(r+1).trim()}`;return x(e)?e:void 0}if(f(t)||t.includes("#")||t.includes("@"))return;const n=t.indexOf("://");if(-1!==n){const e=t.slice(0,n).toLowerCase();if("http"!==e&&"https"!==e)return;try{const e=new URL(t);if(0===e.hostname.length||e.username.length>0||e.password.length>0)return;const r="/"!==e.pathname&&""!==e.pathname,n=""!==e.search;if(e.hostname.includes("*"))return;if(r||n){const t=E(e);if(!x(t))return;return t}{const t=E(e);if(!x(t))return;return t}}catch{return}}else if(t.includes("/"))return;const o=t.trim().toLowerCase(),s=function(e){const t=e.indexOf(":");if(-1===t)return e;const r=e.slice(t+1);return/^\d+$/.test(r)?e.slice(0,t):e}(o);return 0===s.length||!x(s)||s!==o&&"*"===s?void 0:s}(e);return I.set(e,t),t}const R=2048,I=new Map,T=new Map;function A(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}function $(e){return e.endsWith("/")&&e.length>1?e.slice(0,-1):e}function M(e,t){return function(e,t,r){const n=D(t);if(!n)return!1;let o;try{o=new URL(e)}catch{return!1}return""===o.username&&""===o.password&&""===n.username&&""===n.password&&o.protocol===n.protocol&&o.port===n.port&&(s=o.hostname,i=n.hostname,!s.includes("*")&&H(s)===H(i)&&(A(a=o.pathname,c=n.pathname)||A($(a),$(c)))&&function(e,t,r){return""===e?r.allowRequestQueryWhenPatternOmitsQuery||""===t:A(e,t)}(o.search,n.search,r));var s,i,a,c}(e,t,{allowRequestQueryWhenPatternOmitsQuery:!0})}function D(e){const t=e.trim();if(0===t.length||f(t))return;if(function(e){const t=e.indexOf("[");return-1!==t&&-1===e.indexOf("]",t)}(t))return;const r=q(t);if(r&&("http:"===r.protocol||"https:"===r.protocol)&&""===r.username&&""===r.password&&0!==r.hostname.length&&(!H(r.hostname).includes(":")||t.includes("["))){if(t.includes("[")){const e=t.indexOf("["),n=t.indexOf("]",e);if(-1===n)return;const o=t.slice(e+1,n);if(H(r.hostname)!==H(o))return}return r}}function O(e,t){const r=e.toLowerCase(),n=t.toLowerCase();if("*"===r)return!0;if(void 0!==a(n))return A(r,n);if(!r.includes("*"))return r===n;const o=r.slice(1);if(r.startsWith("*.")&&!o.includes("*"))return n.endsWith(o)&&n.length>o.length;const s=r.split("."),i=n.split(".");return s.length===i.length&&!s[s.length-1]?.includes("*")&&A(r,n)}const F=/^([^/?#]+\/\/[^/?#]*):\*(?=[/?#]|$)/,N=/^[^/?#]+\/\/[^/?#]*\*$/;function L(e,t){if("*"===e||e===t)return!0;let r;T.has(t)?r=T.get(t):(T.size>=R&&T.clear(),r=q(t),T.set(t,r));const n=function(e){if(void 0===e||!/[^.]\.$/.test(e.hostname))return;const t=new URL(e.href);return t.hostname=e.hostname.slice(0,-1),t.href}(r);if(void 0!==n&&L(e,n))return!0;const o=function(e){const t=e.trim(),r=t.indexOf("://");if(-1===r)return/^[^/?#]*[^.*/?#]\.$/.test(t)?t.slice(0,-1):void 0;if(!t.includes("*"))return;const n=r+3,o=n+(t.slice(n).split(/[/?#]/,1)[0]??"").replace(/:(?:\d+|\*)$/,"").length;return/[^.*]\.$/.test(t.slice(n,o))?`${t.slice(0,o-1)}${t.slice(o)}`:void 0}(e);return!(void 0===o||!L(o,t))||!!r&&(e.includes("://")?function(e,t){const r=N.test(e),n=r||F.test(e),o=e.indexOf("://"),s=e.slice(0,o).toLowerCase(),i=t.protocol.slice(0,-1),a=q((s.includes("*")&&A(s,i)?`${i}${e.slice(o)}`:e).replace(F,"$1"));if(void 0===a||""!==a.username||""!==a.password||""!==t.username||""!==t.password||a.protocol!==t.protocol||!n&&a.port!==t.port)return!1;const c=a.hostname.replace(/%2a/gi,"*");return(O(c,t.hostname)||r&&O(c.replace(/\*$/,""),t.hostname))&&(r||A(`${a.pathname}${a.search}`,`${t.pathname}${t.search}`))}(e,r):h(r.hostname,e))}function j(e,t){if(A(e,t)||L(e,t))return!0;const r=function(e){const t=e.trim();if(t.includes("*")||!t.includes("://"))return;const r=q(t);return void 0!==r&&""===r.search&&""===r.hash?W(r):void 0}(e);if(void 0===r)return!1;const n=q(t.trim());return void 0!==n&&W(n)===r}const U=/%[0-9a-f]{2}/gi,B=/^[A-Za-z0-9\-._~]$/;function W(e){const t="http:"===e.protocol||"https:"===e.protocol?"http(s):":e.protocol,r=e.hostname.endsWith(".")?e.hostname.slice(0,-1):e.hostname,n=""===e.port?"":`:${e.port}`,o=e.pathname.replace(U,(e=>{const t=String.fromCharCode(Number.parseInt(e.slice(1),16));return B.test(t)?t:e.toUpperCase()})).replace(/\/{2,}/g,"/");return`${t}//${r}${n}${o.endsWith("/")?o.slice(0,-1):o}`}function H(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function q(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch{return}}function z(e){return(e.mcpNetworkAllowlist??[]).flatMap((e=>{const t=P(e);return void 0===t?[]:[t]}))}function G(e,t){if(!0!==t.enabled)return{allowed:!0};if("no_sandbox"===t.mcpNetworkMode)return{allowed:!0};if(!D(e))return{allowed:!1,message:t.blockMessage??p};const r=z(t);return r.length>0&&r.some((t=>function(e,t){const r=D(t);if(!r)return!1;if(!e.includes("://"))return h(H(r.hostname),e);if(M(e,t))return!0;const n=function(e){try{const t=new URL(e);if(""!==t.username||""!==t.password||"/"!==t.pathname||""!==t.search||""!==t.hash)return;return`${t.protocol}//${t.host}/*`}catch{return}}(e);return void 0!==n&&M(n,t)}(t,e)))?{allowed:!0}:{allowed:!1,message:t.blockMessage??p}}function V(e){const t=e?.trim();return t&&t.length>0?t:void 0}function K(e){return V(e)?.toLowerCase()}function J(e,t){const r=K(e.builtinServer),n=K(t.builtinServer);if(void 0!==r||void 0!==n)return void 0!==r&&r===n;const o=V(e.command),s=V(e.serverUrl);if(void 0===o&&void 0===s)return!1;const i=void 0===o||void 0!==t.command&&A(o,t.command),a=void 0===s||void 0!==t.url&&L(s,t.url);return i&&a}function Z(e,t,r){return void 0!==r?.command&&void 0===r.url&&void 0===t&&!0===e?.allowUserOverrideMcpServers}function X({allowedMcpConfiguration:e,server:t,localAgentNetworkAllowlist:r,blockMessage:n,unmatchedServerAllowlist:o,aggregateManagedServerNetworkAllowlists:s=!0,stdioPlatform:i,unsandboxUserExtensionStdio:a}){const c=e?.allowedMcpServers,l=function(e){if(!0!==e?.allowUserOverrideMcpServers)return;const t=(e.deniedMcpServers??[]).flatMap((e=>{const t=V(e.serverUrl),r=void 0===t?void 0:function(e){const t=e.trim();if(0===t.length)return;if(function(e){const t=e.indexOf("://");if(-1===t)return!1;const r=e.slice(t+3),n=r.indexOf("/");return-1===n?r.includes("?"):r.slice(n).includes("*")}(t)){const e=t.indexOf("://");if(-1!==e){const r=t.slice(e+3).split(/[/?#]/,1)[0];if(r?.includes("*")){const e=P(r.replace(/:\d+$/,""));if(void 0!==e)return e}}return}if(!t.includes("://")&&t.includes("*")&&"*"!==t&&!t.startsWith("*."))return;const r=P(e);if(void 0!==r)return r;const n=e.indexOf("://");if(-1===n)return;const o=e.slice(0,n).toLowerCase();if("http"!==o&&"https"!==o)return;const s=e.slice(n+3).split(/[/?#]/,1)[0];if(void 0===s||s.includes("@"))return;const i=P(s.replace(/:\d+$/,""));if(void 0!==i)return i;try{return P(new URL(e).hostname)}catch{return}}(t);return void 0===r?[]:[r]}));return t.length>0?t:void 0}(e),u=void 0===t?void 0:function(e,t){return e?.find((e=>J(e,t)))}(c,t),d=Z(e,u,t),h=function({allowedMcpConfiguration:e,matchedServer:t,server:r}){return void 0===r?(e?.allowedMcpServers?.length??0)>0:void 0!==t||Z(e,t,r)}({allowedMcpConfiguration:e,matchedServer:u,server:t})||void 0===t&&void 0!==l,p=void 0===t?s?c?.flatMap((e=>e.networkAllowlist??[])):void 0:d?[]:function(e,t,r){return void 0===e?r:[...e.networkAllowlist??[],...void 0!==V(e.serverUrl)&&void 0!==t.url?[t.url]:[]]}(u,t,o),f=d&&"win32"===i&&!0===a;let m;m=void 0===t?void 0:f?"no_sandbox":d?"allow_all":function(e,t){var r;if(void 0!==V(e?.command)&&void 0!==t.command&&void 0===t.url)return r=e?.networkMode,("allow_all"===r||"allowlist"===r||"deny_all"===r||"no_sandbox"===r?r:void 0)??"no_sandbox"}(u,t);const g=void 0===t||d?l:void 0;return{enabled:h,mcpNetworkAllowlist:p,...void 0!==m?{mcpNetworkMode:m}:{},...void 0!==g?{mcpNetworkDenylist:g}:{},...void 0!==r?{localAgentNetworkAllowlist:r}:{},...void 0!==n?{blockMessage:n}:{},...f?{win32UserExtensionUnsandbox:!0}:{}}}function Q(e){if(!0===e?.enabled&&"no_sandbox"!==e.mcpNetworkMode)return e}},"../shell-exec/dist/api/index.js"(e,t,r){r.d(t,{BM:()=>Oo,Ls:()=>f,SandboxUnsupportedError:()=>_r,J:()=>x,St:()=>Er,Fn:()=>Do,Qw:()=>a,ue:()=>s,r5:()=>Ie,getLastSandboxFailureReason:()=>kr,oG:()=>no,Ko:()=>T,CG:()=>ht,W1:()=>Z,G6:()=>Mo,dA:()=>He,_B:()=>Qe,OK:()=>Ze,$b:()=>Xe,K3:()=>Rr,tv:()=>st,wG:()=>vt,fZ:()=>bt,s9:()=>mt,XX:()=>yt,T6:()=>et,Po:()=>Ye,$6:()=>nt,l7:()=>it,xS:()=>E,resolveSandboxPolicyForWorkspace:()=>Ct,fB:()=>Dt,spawnInSandbox:()=>xr,Xw:()=>I});var n=r("node:child_process");new Set;const o=["SSH_CLIENT","SSH2_CLIENT"];function s(e){const t=e||process.env,{ELECTRON_RUN_AS_NODE:r,...n}=t;for(const e of Object.keys(n))e.startsWith("AGENT_HOST_DAEMON_")&&delete n[e];for(const e of o)delete n[e];return n}const i="NODE_COMPILE_CACHE";function a(e){const{[i]:t,...r}=e;return r.NODE_DISABLE_COMPILE_CACHE="1",r}const c=["SSH_AUTH_SOCK","DBUS_SESSION_BUS_ADDRESS","XDG_RUNTIME_DIR","WAYLAND_DISPLAY"];function l(e){const t={...e};for(const e of c)delete t[e];return t}const u=[["core.quotePath","false"]];function d(e){const t=function(e){const t=e.GIT_CONFIG_COUNT;if(void 0===t||""===t)return 0;const r=Number.parseInt(t,10);return Number.isFinite(r)&&r>=0?r:0}(e),r=new Set;for(let n=0;no.endsWith(e)))){const n=S(e,r);if(g.existsSync(n))return k(n,t,r)}for(const o of n){const n=S(`${e}${o}`,r);if(g.existsSync(n))return k(n,t,r)}}return e.match(/\.ps1$/i)?{cmd:m.join(process.env.SYSTEMROOT,"System32","WindowsPowerShell","v1.0","PowerShell.exe"),args:["-ExecutionPolicy","Unrestricted","-NoLogo","-NonInteractive","-File",e].concat(t)}:e.match(/\.(bat|cmd)$/i)?{cmd:m.join(process.env.SYSTEMROOT,"System32","cmd.exe"),args:["/C",e,...t]}:e.match(/\.(js)$/i)?{cmd:process.execPath,args:[e].concat(t)}:{cmd:e,args:t}}let _;const C=["/usr/local/bin","/usr/bin","/bin"];function E(){const e=k("rg",[]).cmd;return"rg"!==e?e:void 0}function x(e){if(!e)throw new Error("configureRipgrepPath: path must not be empty");_=e}function P(e){const t=Object.keys(e).filter((e=>"path"===e.toLowerCase()));if(0!==t.length)return"win32"===process.platform?t.find((e=>"Path"===e))??t[0]:t.find((e=>"PATH"===e))??t[0]}function R(e,t){const r=(0,m.dirname)(t);if(!r||"."===r)return e;let n=function(e){const t=P(e);return void 0!==t?e[t]??"":""}(e).split(m.delimiter).filter(Boolean);return 0===n.length&&"win32"!==process.platform&&(n=C),function(e,t){const r=P(e)??("win32"===process.platform?"Path":"PATH"),n={...e};for(const e of Object.keys(n))e!==r&&"path"===e.toLowerCase()&&delete n[e];return n[r]=t,n}(e,[r,...n.filter((e=>e!==r))].join(m.delimiter))}function I(e){return _&&(0,m.isAbsolute)(_)?{...R(e,_),CURSOR_RIPGREP_PATH:_}:e}function T(){if(!_)throw new Error("Ripgrep path not configured. Call configureRipgrepPath() at startup.");return _}const A="win32"===process.platform;function $(e){return!A&&!!e?.SUDO_ASKPASS}function M(e){return $(e)?"alias sudo='sudo -A'; ":""}function D(e){const t=[];let r=0;for(;r=e.length||/\s/.test(e[n])){let o=n;for(;ovoid 0!==t&&e.toUpperCase()===r))}const F=["PYTHONIOENCODING","PYTHONUTF8","PYTHONLEGACYWINDOWSSTDIO"];function N(e){F.some((t=>O(e,t)))||(e.PYTHONIOENCODING="utf-8:surrogateescape")}function L(e){O(e,"WSL_UTF8")||(e.WSL_UTF8="1")}const j="-Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8 -Dstdout.encoding=UTF-8 -Dstderr.encoding=UTF-8",U=["sun.stdout.encoding","sun.stderr.encoding","stdout.encoding","stderr.encoding"],B=`case " \${MAVEN_OPTS-} \${JAVA_TOOL_OPTIONS-} \${JDK_JAVA_OPTIONS-} \${_JAVA_OPTIONS-} " in ${U.map((e=>`*[[:space:]]-D${e}=*`)).join("|")}) ;; *) builtin export MAVEN_OPTS="\${MAVEN_OPTS:+$MAVEN_OPTS }${j}";; esac; `,W=`if ("$env:MAVEN_OPTS $env:JAVA_TOOL_OPTIONS $env:JDK_JAVA_OPTIONS \${env:_JAVA_OPTIONS}" -cnotmatch '(^|\\s)-D(${U.map((e=>e.replace(/\./g,"\\."))).join("|")})=') {\n if ($env:MAVEN_OPTS) { $env:MAVEN_OPTS = "$env:MAVEN_OPTS ${j}" } else { $env:MAVEN_OPTS = '${j}' }\n}`;var H=r("node:crypto?8af2"),q=r("node:os"),z=r("../utils/dist/workspace-paths.js"),G=r("../utils/dist/test-resets.js");let V;function K(e,t){const r=(0,g.lstatSync)(e);return r.isDirectory()&&r.uid===t&&!(18&r.mode)}function J(e){try{(0,g.mkdirSync)(e,{mode:448})}catch(e){if(!(e instanceof Error&&"code"in e&&"EEXIST"===e.code))throw e}}function Z(e){return X(e,{create:!1})}function X(e,{create:t}){const r=process.getuid?.();if(void 0===r)return;const n=(0,m.join)((0,q.tmpdir)(),`cursor-sandbox-${(0,z.r_)((0,m.resolve)(e))}`);try{for(const e of[n,(0,m.join)(n,"tmp")])if(t&&J(e),!K(e,r))return;return n}catch{return}}(0,G.J)((function(){V=void 0}));const Q='builtin eval "${__CURSOR_SANDBOX_TEMP_RESTORE:-}" 2>/dev/null; ',Y=["TMPDIR","TMP","TEMP","TMPPREFIX","NODE_COMPILE_CACHE","NODE_DISABLE_COMPILE_CACHE"],ee="builtin export NODE_DISABLE_COMPILE_CACHE=1; builtin unset NODE_COMPILE_CACHE; ";function te(e){const t=(0,m.join)(e,"tmp");return{TMPDIR:t,TMP:t,TEMP:t,TMPPREFIX:(0,m.join)(t,"sh-")}}function re(e=(0,m.join)((0,q.tmpdir)(),"cursor-sandbox-cache",function(){return V||(V=(0,H.randomBytes)(16).toString("hex")),V}())){return{NPM_CONFIG_CACHE:(0,m.join)(e,"npm"),PNPM_STORE_PATH:(0,m.join)(e,"pnpm-store"),GOCACHE:(0,m.join)(e,"go-build"),GOMODCACHE:(0,m.join)(e,"go-mod"),CARGO_TARGET_DIR:(0,m.join)(e,"cargo-target"),PIP_CACHE_DIR:(0,m.join)(e,"pip"),UV_CACHE_DIR:(0,m.join)(e,"uv"),BUN_INSTALL_CACHE_DIR:(0,m.join)(e,"bun"),YARN_CACHE_FOLDER:(0,m.join)(e,"yarn"),npm_config_devdir:(0,m.join)(e,"node-gyp"),PLAYWRIGHT_BROWSERS_PATH:(0,m.join)(e,"playwright"),PUPPETEER_CACHE_DIR:(0,m.join)(e,"puppeteer"),TURBO_CACHE_DIR:(0,m.join)(e,"turbo"),GRADLE_USER_HOME:(0,m.join)(e,"gradle"),CONDA_PKGS_DIRS:(0,m.join)(e,"conda"),POETRY_CACHE_DIR:(0,m.join)(e,"poetry"),GEM_SPEC_CACHE:(0,m.join)(e,"gem-specs"),COMPOSER_HOME:(0,m.join)(e,"composer"),HOMEBREW_CACHE:(0,m.join)(e,"homebrew"),CYPRESS_CACHE_FOLDER:(0,m.join)(e,"cypress"),NX_CACHE_DIRECTORY:(0,m.join)(e,"nx"),NUGET_PACKAGES:(0,m.join)(e,"nuget"),CCACHE_DIR:(0,m.join)(e,"ccache"),CP_HOME_DIR:(0,m.join)(e,"cocoapods")}}var ne=r("node:fs/promises"),oe=r("../utils/dist/safe-spawn-cwd.js"),se=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js");function ie(){const e=process.env.CURSOR_SANDBOX_POLICY_DIR?.trim();return e?m.resolve(e):m.resolve(m.join(q.homedir(),".cursor","sandbox-policies"))}let ae=0;function ce(){const e=ie();g.mkdirSync(e,{recursive:!0,mode:448});try{g.chmodSync(e,448)}catch{}const t=Date.now();return t-ae>=9e5&&(ae=t,function(e){let t;try{t=g.readdirSync(e)}catch{return}const r=Date.now();for(const n of t){if(!n.startsWith("sandbox-policy-"))continue;const t=m.join(e,n);try{const e=g.statSync(t);if(!e.isFile())continue;r-e.mtimeMs>36e5&&g.unlinkSync(t)}catch{}}}(e)),e}function le(e){const t=ce(),r=H.randomBytes(8).toString("hex"),n=m.join(t,`sandbox-policy-${r}`);return g.writeFileSync(n,e,{encoding:"utf-8",mode:384}),n}const ue="/tmp/node-compile-cache",de="cursor-compile-cache",he=Symbol.for("cursor.startupNodeCompileCache"),pe=process.platform;function fe(e=q.tmpdir(),t=process.platform){if("win32"===t||0===e.length)return[];const r=m.posix.join(e,"node-compile-cache");return r===ue?[]:[r]}function me(e=q.tmpdir(),t=process.env,r=process.platform){if("win32"===r)return[];const n=new Set(fe(e,r));for(const e of["TMPDIR","TMP","TEMP"]){const o=t[e];if(void 0!==o&&m.posix.isAbsolute(o))for(const e of fe(m.posix.resolve(o),r))n.add(e)}return[...n]}function ge(e=process.env,t=q.homedir(),r=process.platform){if("darwin"===r)return t.length>0?m.posix.join(t,"Library/Caches",de):void 0;if("linux"!==r)return;const n=e.XDG_CACHE_HOME;return void 0!==n&&m.posix.isAbsolute(n)?m.posix.join(n,de):t.length>0?m.posix.join(t,".cache",de):void 0}function we(e=process.env,t=process.platform){if("win32"===t)return;const r=Object.getOwnPropertyDescriptor(globalThis,he)?.value,n="string"==typeof r?r:e.NODE_COMPILE_CACHE;if(void 0===n||!m.posix.isAbsolute(n))return;const o=m.posix.resolve(n);return"/"===o?void 0:o}function ye(e=q.homedir(),t=q.tmpdir(),r=process.env,n=process.platform){if("win32"===n)return[];const o=new Set([ue]);e.length>0&&(o.add(m.posix.join(e,".cache",de)),o.add(m.posix.join(e,"Library/Caches",de)));const s=[];for(const i of[...me(t,r,n),ge(r,e,n),we(r,n)])void 0===i||o.has(i)||(o.add(i),s.push(i));return s}function ve(e=q.homedir(),t=q.tmpdir(),r=process.platform,n=process.env){if("win32"===r)return[];const o=[ue,...me(t,n,r)],s=ge(n,e,r);return void 0===s||o.includes(s)||o.push(s),o}function be(e,t){return e.isSymbolicLink()?"a link, not followed":e.isDirectory()?e.uid!==t?`owned by uid ${e.uid}`:void 0:"not a folder"}function Se(e){return"object"!=typeof e||null===e?{}:Object.fromEntries(Object.entries(e).filter((e=>"string"==typeof e[1])))}function ke(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:"error"}const _e=[".local/bin",".local/share/mise",".local/share/pnpm",".nvm",".volta",".asdf",".pyenv",".rbenv",".rustup",".cargo/bin",".cargo/registry",".cargo/git"],Ce=["bin","sbin","lib","opt","Cellar","share","Frameworks","etc/gitconfig","etc/openssl@3/cert.pem","etc/openssl@3/openssl.cnf","etc/ca-certificates"],Ee=(e,t)=>t.flatMap((t=>Ce.map((r=>({platform:e,scope:"global",path:`${t}/${r}`}))))),xe={linux:[".cache/node",".cache/yarn"],darwin:[".cache/node","Library/Caches/Yarn"]},Pe=e=>[..._e,...xe[e]].map((t=>({platform:e,scope:"home-dir",path:t}))),Re=[{platform:"linux",scope:"global",path:"/bin"},{platform:"linux",scope:"global",path:"/sbin"},{platform:"linux",scope:"global",path:"/usr/bin"},{platform:"linux",scope:"global",path:"/usr/sbin"},{platform:"linux",scope:"global",path:"/lib"},{platform:"linux",scope:"global",path:"/lib64"},{platform:"linux",scope:"global",path:"/usr/lib"},{platform:"linux",scope:"global",path:"/usr/lib64"},{platform:"linux",scope:"global",path:"/usr/libexec"},{platform:"linux",scope:"global",path:"/usr/share"},{platform:"linux",scope:"global",path:"/etc/ld.so.cache"},{platform:"linux",scope:"global",path:"/etc/ld.so.conf"},{platform:"linux",scope:"global",path:"/etc/ld.so.conf.d"},{platform:"linux",scope:"global",path:"/etc/ssl/certs"},{platform:"linux",scope:"global",path:"/etc/ssl/openssl.cnf"},{platform:"linux",scope:"global",path:"/etc/ssl/cert.pem"},{platform:"linux",scope:"global",path:"/etc/ssl/ca-bundle.pem"},{platform:"linux",scope:"global",path:"/etc/ssl/certs/ca-certificates.crt"},{platform:"linux",scope:"global",path:"/etc/pki/tls/certs"},{platform:"linux",scope:"global",path:"/etc/pki/tls/openssl.cnf"},{platform:"linux",scope:"global",path:"/etc/pki/ca-trust/extracted"},{platform:"linux",scope:"global",path:"/etc/resolv.conf"},{platform:"linux",scope:"global",path:"/etc/hosts"},{platform:"linux",scope:"global",path:"/etc/nsswitch.conf"},{platform:"linux",scope:"global",path:"/etc/gai.conf"},{platform:"linux",scope:"global",path:"/etc/alternatives"},{platform:"linux",scope:"global",path:"/etc/mime.types"},{platform:"linux",scope:"global",path:"/etc/profile"},{platform:"linux",scope:"global",path:"/etc/bash.bashrc"},{platform:"linux",scope:"global",path:"/etc/zsh/zshenv"},{platform:"linux",scope:"global",path:"/etc/zsh/zprofile"},{platform:"linux",scope:"global",path:"/etc/zsh/zshrc"},{platform:"linux",scope:"global",path:"/etc/zsh/zlogin"},{platform:"linux",scope:"global",path:"/etc/gitconfig"},{platform:"linux",scope:"home",path:".bashrc"},{platform:"linux",scope:"home",path:".bash_profile"},{platform:"linux",scope:"home",path:".profile"},{platform:"linux",scope:"home",path:".zshenv"},{platform:"linux",scope:"home",path:".zprofile"},{platform:"linux",scope:"home",path:".zshrc"},{platform:"linux",scope:"home",path:".zlogin"},{platform:"linux",scope:"home",path:".gitconfig"},{platform:"linux",scope:"home",path:".ssh/known_hosts"},{platform:"linux",scope:"home",path:".config/mise/config.toml"},{platform:"linux",scope:"home-dir",path:".cache/dotslash"},...Pe("linux"),...Ee("linux",["/usr/local","/home/linuxbrew/.linuxbrew"]),{platform:"linux",scope:"global",path:"/usr/local/go"},{platform:"linux",scope:"global",path:"/nix/store"},{platform:"linux",scope:"global",path:"/nix/var/nix/profiles"},{platform:"linux",scope:"bundled",path:"ripgrep"},{platform:"darwin",scope:"global",path:"/bin"},{platform:"darwin",scope:"global",path:"/usr/bin"},{platform:"darwin",scope:"global",path:"/usr/lib"},{platform:"darwin",scope:"global",path:"/usr/libexec"},{platform:"darwin",scope:"global",path:"/usr/share"},{platform:"darwin",scope:"global",path:"/System/Library"},{platform:"darwin",scope:"global",path:"/System/Cryptexes"},{platform:"darwin",scope:"global",path:"/Library/Apple"},{platform:"darwin",scope:"global",path:"/Library/Developer/CommandLineTools"},{platform:"darwin",scope:"global",path:"/Applications/Xcode.app"},{platform:"darwin",scope:"global",path:"/Library/Preferences/com.apple.dt.Xcode.plist"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/cert.pem"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/certs"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/openssl.cnf"},{platform:"darwin",scope:"global",path:"/private/etc/hosts"},{platform:"darwin",scope:"global",path:"/private/etc/resolv.conf"},{platform:"darwin",scope:"global",path:"/private/etc/apache2/mime.types"},{platform:"darwin",scope:"global",path:"/etc/profile"},{platform:"darwin",scope:"global",path:"/etc/bashrc"},{platform:"darwin",scope:"global",path:"/etc/zshenv"},{platform:"darwin",scope:"global",path:"/etc/zprofile"},{platform:"darwin",scope:"global",path:"/etc/zshrc"},{platform:"darwin",scope:"global",path:"/etc/zlogin"},{platform:"darwin",scope:"global",path:"/etc/gitconfig"},{platform:"darwin",scope:"home",path:".bashrc"},{platform:"darwin",scope:"home",path:".bash_profile"},{platform:"darwin",scope:"home",path:".profile"},{platform:"darwin",scope:"home",path:".zshenv"},{platform:"darwin",scope:"home",path:".zprofile"},{platform:"darwin",scope:"home",path:".zshrc"},{platform:"darwin",scope:"home",path:".zlogin"},{platform:"darwin",scope:"home",path:".gitconfig"},{platform:"darwin",scope:"home",path:".ssh/known_hosts"},{platform:"darwin",scope:"home",path:"Library/Preferences/.GlobalPreferences.plist"},{platform:"darwin",scope:"home",path:".config/mise/config.toml"},{platform:"darwin",scope:"home-dir",path:"Library/Python"},{platform:"darwin",scope:"home-dir",path:"Library/Caches/dotslash"},...Pe("darwin"),...Ee("darwin",["/opt/homebrew","/usr/local"]),{platform:"darwin",scope:"global",path:"/nix/store"},{platform:"darwin",scope:"global",path:"/nix/var/nix/profiles"},{platform:"darwin",scope:"bundled",path:"ripgrep"},{platform:"darwin",scope:"global",path:"/dev/null"},{platform:"darwin",scope:"global",path:"/dev/zero"},{platform:"darwin",scope:"global",path:"/dev/random"},{platform:"darwin",scope:"global",path:"/dev/urandom"}];function Ie(e=process.platform,t=q.default.homedir(),r={}){const n=[];for(const o of Re){if(o.platform!==e)continue;if("global"===o.scope){n.push(o.path);continue}const s="bundled"===o.scope?r[o.path]:(0,m.join)(t,o.path);if(s)try{let e;switch(o.scope){case"home":e=(0,g.lstatSync)(s).isFile();break;case"home-dir":e=(0,g.lstatSync)(s).isDirectory();break;case"bundled":e=(0,g.statSync)(s).isFile()}e&&n.push(s)}catch{}}return n}const Te=[{type:"workspace",pattern:"**/.cursor/*.json"},{type:"workspace",pattern:"**/.cursor/**/*.json"},{type:"workspace",pattern:"**/.cursor/.workspace-trusted"},{type:"workspace",pattern:"!**/.cursor/rules"},{type:"workspace",pattern:"!**/.cursor/rules/**"},{type:"workspace",pattern:"!**/.cursor/commands"},{type:"workspace",pattern:"!**/.cursor/commands/**"},{type:"workspace",pattern:"!**/.cursor/worktrees"},{type:"workspace",pattern:"!**/.cursor/worktrees/**"},{type:"workspace",pattern:"!**/.cursor/skills"},{type:"workspace",pattern:"!**/.cursor/skills/**"},{type:"workspace",pattern:"!**/.cursor/agents"},{type:"workspace",pattern:"!**/.cursor/agents/**"},{type:"workspace",pattern:"**/.claude/*.json"},{type:"workspace",pattern:"**/.claude/**/*.json"},{type:"workspace",pattern:"**/.vscode/**"},{type:"workspace",pattern:"**/.idea/**"},{type:"workspace",pattern:"**/.venv/"},{type:"workspace",pattern:"**/venv/"},{type:"workspace",pattern:"**/*.code-workspace"},{type:"workspace",pattern:"**/.cursorignore"},{type:"workspace",pattern:"**/.workspace-trusted"},{type:"workspace",pattern:"**/.cursor/**/cli.json"},{type:"workspace",pattern:"**/.cursor/**/cli-config.json"},{type:"workspace",pattern:"**/.cursor/**/mcp.json"},{type:"workspace",pattern:"**/.cursor/**/mcp-approvals.json"},{type:"workspace",pattern:"**/.cursor/**/permissions.json"},{type:"git",pattern:"**/.git/hooks/**"},{type:"git",pattern:"**/.git/config"},{type:"git",pattern:"**/.git/config.worktree"},{type:"git",pattern:"**/.git/info/attributes"},{type:"git",pattern:"**/.git/commondir"},{type:"git",pattern:"**/.git/worktrees/*/commondir"},{type:"git",pattern:"**/.git/worktrees/*/gitdir"},{type:"worktree",pattern:".git"},{type:"absolute",pattern:"/etc/ssl/cert.pem"},{type:"absolute",pattern:"/etc/ssl/ca-bundle.pem"},{type:"absolute",pattern:"/private/etc/ssl/cert.pem"},{type:"absolute",pattern:"/etc/ssl/certs/ca-certificates.crt"},{type:"absolute",pattern:"/etc/pki/tls/certs/ca-bundle.crt"},{type:"absolute",pattern:"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem"},{type:"home",pattern:".cursor/sandbox-policies"},{type:"absolute",pattern:"/tmp/node-compile-cache"},{type:"home",pattern:".cache/cursor-compile-cache"},{type:"home",pattern:"Library/Caches/cursor-compile-cache"}];function Ae(e){const t=Te.filter((e=>"workspace"===e.type)).map((e=>e.pattern));return{[e]:t}}function $e(e){const t=Te.filter((e=>"git"===e.type)).map((e=>e.pattern));return{[e]:t}}function Me(e){const t=Te.filter((e=>"worktree"===e.type)).map((e=>e.pattern));return{[e]:t}}Te.filter((e=>"git"===e.type)).map((e=>e.pattern)),Te.filter((e=>"workspace"===e.type&&e.pattern.startsWith("!")&&!e.pattern.endsWith("/**"))).map((e=>e.pattern.replace(/^!(\*\*\/)?/,"")));const De=[];let Oe=null,Fe=null;function Ne(e){if(!(e instanceof Error&&"code"in e&&"string"==typeof e.code)||e.code.startsWith("ERR_"))throw e}async function Le(e,t=""){const r=await(0,ne.lstat)(e).catch(Ne);if(void 0===r||!r.isFile()||r.size>4096)return;const n=await(0,ne.readFile)(e,"utf8").catch(Ne),o=n?.split("\n",1)[0]?.replace(/\r$/,"");if(void 0===o||!o.startsWith(t))return;const s=o.slice(t.length);return s.length>0&&!s.includes("\0")?s:void 0}async function je(e){if(!(0,oe.$f)(e))return(0,ne.realpath)(e).catch(Ne)}async function Ue(e){const t=await Le((0,m.join)(e,".git"),"gitdir: ");if(void 0===t)return;const r=await je((0,m.resolve)(e,t));if(void 0===r)return;const n=await Le((0,m.join)(r,"commondir")),o=void 0===n?r:await je((0,m.resolve)(r,n));return void 0===o?void 0:{gitDir:r,commonDirLink:n,commonDir:o}}async function Be(e){const t=await Ue(e);if(void 0===t||void 0===t.commonDirLink||"worktrees"!==(0,m.basename)((0,m.dirname)(t.gitDir)))return;const r=(0,m.dirname)((0,m.dirname)(t.gitDir));if(".git"!==(0,m.basename)(r)||(ze?t.commonDir.toLowerCase()!==r.toLowerCase():t.commonDir!==r))return;const n=await Le((0,m.join)(t.gitDir,"gitdir"));if(void 0===n)return;const o=(0,m.join)(e,".git"),[s,i]=await Promise.all([je((0,m.resolve)(t.gitDir,n)),je(o)]);return void 0!==s&&void 0!==i&&(ze?s.toLowerCase()===i.toLowerCase():s===i)?r:void 0}let We=null;function He(e){return function(){const e=q.default.homedir();if(null===We){const t=[];for(const r of Te)switch(r.type){case"absolute":t.push(r.pattern);break;case"home":e.length>0&&t.push((0,m.join)(e,r.pattern))}We=t}return[...We,...ye(e)]}().some((t=>{if(Ke(e,t))return!0;const r=function(e){let t;try{t=g.realpathSync.native((0,m.dirname)(e))}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;return"ENOENT"===t||"ENOTDIR"===t?void 0:qe}const r=(0,m.join)(t,(0,m.basename)(e));return r===(0,m.dirname)(r)?void 0:r}(t);return r===qe||void 0!==r&&Ke(e,r)}))}const qe=Symbol("unresolved parent");const ze="win32"===process.platform||"darwin"===process.platform;function Ge(e){if(!e.endsWith(m.sep))return e;const t=e.slice(0,-1);return""===t||"win32"===process.platform&&/^[a-zA-Z]:$/.test(t)?e:t}function Ve(e){return e.endsWith(m.sep)?e:e+m.sep}function Ke(e,t){const r=Ge(t);if(ze){const t=e.toLowerCase(),n=r.toLowerCase();return t===n||t.startsWith(Ve(n))}return e===r||e.startsWith(Ve(r))}function Je(e,t){const r=Ge(e);return ze?(0,m.relative)(r.toLowerCase(),t.toLowerCase()).replace(/\\/g,"/"):(0,m.relative)(r,t).replace(/\\/g,"/")}async function Ze(e,t){if(Ke(e,t)){const r=Je(t,e);if((null===Oe&&(Oe=se({ignoreCase:!0}),Oe.add(Te.filter((e=>"workspace"===e.type)).map((e=>e.pattern)))),Oe).ignores(r))return!0}const{isWorktree:r,gitDirParent:n}=await async function(e){const t=await(0,ne.lstat)((0,m.join)(e,".git")).catch(Ne);if(!t?.isFile())return{isWorktree:!1,gitDirParent:e};const r=await async function(e){return(await Ue(e))?.commonDir}(e);return{isWorktree:!0,gitDirParent:void 0===r?e:(0,m.dirname)(r)}}(t);for(const r of new Set([n,t]))if(Ke(e,r)){const t=Je(r,e);if((null===Fe&&(Fe=se({ignoreCase:!0}),Fe.add(Te.filter((e=>"git"===e.type)).map((e=>e.pattern)))),Fe).ignores(t))return!0}return!(!r||!Ke(e,t)||".git"!==Je(t,e))||He(e)}function Xe(e){return void 0!==e&&("allow"===e.default||void 0!==e.allow&&e.allow.length>0)}function Qe(e){return void 0!==e&&"allow"===e.default}function Ye(){return{version:1,default:"deny"}}function et(){return{version:1,default:"allow"}}var tt=r("../utils/dist/path-utils.js");function rt(e){if(!e)return;const t={version:1};if("allow"!==e.default&&"deny"!==e.default||(t.default=e.default),Array.isArray(e.allow)&&e.allow.length>0&&(t.allow=e.allow.filter((e=>"string"==typeof e))),Array.isArray(e.deny)&&e.deny.length>0&&(t.deny=e.deny.filter((e=>"string"==typeof e))),e.logging){const r={};"string"==typeof e.logging.decisionLogPath&&(r.decisionLogPath=e.logging.decisionLogPath),"jsonl"===e.logging.logFormat&&(r.logFormat="jsonl"),Object.keys(r).length>0&&(t.logging=r)}return t}function nt(e){const t=e.type??"workspace_readwrite",r={debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,enableSharedBuildCache:e.enableSharedBuildCache};if("insecure_none"===t)return{type:"insecure_none",...r};let n;if(Array.isArray(e.additionalReadonlyPaths)){const t=e.additionalReadonlyPaths;n=t.length>0?t:void 0}const o={...r,networkAccess:e.networkAccess,networkPolicy:rt(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,additionalReadonlyPaths:n,readBoundary:e.readBoundary,additionalReadPaths:Array.isArray(e.additionalReadPaths)?e.additionalReadPaths:void 0,disableTmpWrite:e.disableTmpWrite,privateTmp:e.privateTmp};return"workspace_readonly"===t?{type:"workspace_readonly",...o}:{type:"workspace_readwrite",...o,additionalReadwritePaths:e.additionalReadwritePaths}}function ot(e){if("object"!=typeof e||null===e)return"Expected an object";const t=Object.fromEntries(Object.entries(e));if(void 0!==t.type){const e=["insecure_none","workspace_readwrite","workspace_readonly"];if("string"!=typeof t.type||!e.includes(t.type))return`Invalid type: expected one of ${e.join(", ")}`}const r=["networkAccess","networkPolicyStrict","disableTmpWrite","privateTmp","enableSharedBuildCache","captureDenies"];for(const e of r)if(void 0!==t[e]&&"boolean"!=typeof t[e])return`Invalid ${e}: expected boolean`;const n=["debugOutputDir"];for(const e of n)if(void 0!==t[e]&&"string"!=typeof t[e])return`Invalid ${e}: expected string`;const o=["additionalReadwritePaths","additionalReadonlyPaths","additionalReadPaths"];for(const e of o)if(void 0!==t[e]){if(!Array.isArray(t[e]))return`Invalid ${e}: expected array`;if(!t[e].every((e=>"string"==typeof e)))return`Invalid ${e}: expected array of strings`}if(void 0!==t.readBoundary&&"system"!==t.readBoundary&&"workspace"!==t.readBoundary)return'Invalid readBoundary: expected "system" or "workspace"';if(void 0!==t.networkPolicy){if("object"!=typeof t.networkPolicy||null===t.networkPolicy)return"Invalid networkPolicy: expected object";const e=Object.fromEntries(Object.entries(t.networkPolicy));if(void 0!==e.default&&"allow"!==e.default&&"deny"!==e.default)return'Invalid networkPolicy.default: expected "allow" or "deny"';if(void 0!==e.allow&&!Array.isArray(e.allow))return"Invalid networkPolicy.allow: expected array";if(void 0!==e.deny&&!Array.isArray(e.deny))return"Invalid networkPolicy.deny: expected array"}}async function st(e,t){const r=await async function(e,t){try{const r=await(0,ne.readFile)(e,"utf-8"),n=JSON.parse(r);if(void 0!==ot(n))return{success:!1,error:`Invalid sandbox policy: ${ot(n)??""}`};let o=nt(n);return t&&(o=it(o,t)),{success:!0,policy:o}}catch(e){return e instanceof Error?"code"in e&&"ENOENT"===e.code?{success:!1,error:"File not found"}:e instanceof SyntaxError?{success:!1,error:`Invalid JSON: ${e.message}`}:{success:!1,error:e.message}:{success:!1,error:"Unknown error"}}}(e,t);if(r.success)return r.policy}function it(e,t){if("insecure_none"===e.type)return e;const r=e.additionalReadonlyPaths?.map((e=>(0,tt.o1)(e,t))),n=e.additionalReadPaths?.map((e=>(0,tt.o1)(e,t)));if("workspace_readonly"===e.type)return{...e,additionalReadonlyPaths:r,additionalReadPaths:n};const o=e.additionalReadwritePaths?.map((e=>(0,tt.o1)(e,t)));return{...e,additionalReadonlyPaths:r,additionalReadPaths:n,additionalReadwritePaths:o}}var at=r("../constants/dist/commercial-cursor-hosts.js");function ct(e){const t=e.replace(/\\/g,"/").replace(/\/+$/,"");return""===t?"/":/^[a-zA-Z]:$/.test(t)?`${t}/`:t}function lt(e){const t=ct(e);return/^[a-zA-Z]:\//.test(t)||t.startsWith("//")?t.toLowerCase():t}const ut={insecure_none:0,workspace_readwrite:1,workspace_readonly:2};function dt(){return"1"===process.env[at.K4]}function ht(e){if(!dt())return e.teamAdmin?.type??e.perRepo?.type??e.perUser?.type??"insecure_none";const t=e.teamAdmin?.type??e.perUser?.type;return void 0===t&&void 0===e.perRepo?"insecure_none":Rt(t??"workspace_readwrite",e.perRepo?.type??"insecure_none")}function pt(...e){return e.some((e=>!0===e))}function ft(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return[];if(t.some((e=>0===e.length)))return[];if(1===t.length)return function(e){const t=new Set,r=[];for(const n of e){const e=lt(n);t.has(e)||(t.add(e),r.push(n))}return r}(t[0]).map(ct);let r=new Map(t[0].map((e=>{const t=ct(e);return[lt(t),t]})));for(let e=1;en.has(e))))}return[...r.values()]}function mt(...e){const t=new Map;for(const r of e)if(r)for(const e of r){const r=ct(e),n=lt(r);t.has(n)||t.set(n,r)}return[...t.values()]}const gt=function({defaultValue:e,rank:t}){return{defaultValue:e,merge:(...r)=>{const n=r.filter((e=>void 0!==e));return 0===n.length?e:n.reduce(((e,r)=>t[r]ft(...e);function yt(...e){return gt.merge(...e)}function vt(...e){return wt(...e)}function bt(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return;let r;for(const e of t){if("deny"===e.default){r="deny";break}"allow"===e.default&&void 0===r&&(r="allow")}const n=new Set;for(const e of t)if(e.deny)for(const t of e.deny)n.add(t);const o=new Set;for(const e of t)if(e.allow)for(const t of e.allow)o.add(t);const s=o.size>0?[...o]:void 0;let i;for(let e=t.length-1;e>=0;e--)if(void 0!==t[e].logging){i=t[e].logging;break}const a={version:1};return void 0!==r&&(a.default=r),void 0!==s&&(a.allow=s),n.size>0&&(a.deny=[...n]),void 0!==i&&(a.logging=i),void 0!==a.default||void 0!==a.allow&&0!==a.allow.length||void 0!==a.deny&&0!==a.deny.length||void 0!==a.logging?a:void 0}function St(e,t){if(!e||0===e.length)return[...t];const r=new Set(e);for(const e of t)r.has(e)&&r.delete(e),r.add(e);return[...r]}function kt(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return;const r={};for(const e of t)for(const[t,n]of Object.entries(e))r[t]=St(r[t],n);return 0!==Object.keys(r).length?r:void 0}function _t(...e){for(let t=e.length-1;t>=0;t--)if(void 0!==e[t])return e[t]}async function Ct(e,t,r={}){if(!t)return{policy:{type:"insecure_none"}};if(dt()&&(t=Mt(t,e)),(0,oe.$f)(e))return Ot(t,{workspaceDir:e});if("workspace_readwrite"!==(Pt(t)??"workspace_readwrite"))return Ot(t,{workspaceDir:e});const n=r.stat??ne.stat,o=await async function(e,t){for(let r=e;;r=(0,m.dirname)(r)){if((0,oe.$f)(r))return;const e=await Et(r,t);if(void 0!==e)return e;if((0,m.dirname)(r)===r)return}}(e,n);let s=o?.root??e;if(o?.isFile){const e=await Be(o.root);void 0!==e&&(s=(0,m.dirname)(e)),t=xt(t,void 0===e?[]:[e],Me(o.root))}return t=await async function(e,t,r){const n=Nt(e,"workspace_readwrite"),o=mt(n.perUser?.additionalReadwritePaths,n.perRepo?.additionalReadwritePaths,n.teamAdmin?.additionalReadwritePaths);if(0===o.length)return e;const s=(await Promise.all(o.map((async e=>{if(t.has(ct(e))||(0,oe.$f)(e))return[];const n=await Et(e,r);if(void 0===n)return[];const o=[Ae(e),$e(e)];if(n.isFile){o.push(Me(e));const t=await Be(e);void 0!==t&&o.push($e((0,m.dirname)(t)))}return o})))).flat();return 0===s.length?e:xt(e,[],...s)}(t,new Set([ct(e)]),n),Ot(t,{workspaceDir:e,gitDirParent:s})}async function Et(e,t){const r=await t((0,m.join)(e,".git")).catch(Ne);return r?.isFile()||r?.isDirectory()?{root:e,isFile:r.isFile()}:void 0}function xt(e,t,...r){const n=dt(),o=n?e.perUser:e.perRepo,s="workspace_readwrite"===o?.type||void 0===o?o:void 0,i={...s,type:"workspace_readwrite",additionalReadwritePaths:t.length>0?[...s?.additionalReadwritePaths??[],...t]:s?.additionalReadwritePaths,writeProtectionMapping:kt(s?.writeProtectionMapping,...r)};return n?{...e,perUser:i}:{...e,perRepo:i}}function Pt(e){const{perUser:t,perRepo:r,teamAdmin:n}=e,o=[t,r,n].filter((e=>void 0!==e));if(0===o.length)return;const s=o[0].type;for(const e of o)if(e.type!==s)throw new Error(`Cannot merge policies of different types: found "${s}" and "${e.type}". All policies must be of the same type (all workspace_readwrite, all workspace_readonly, or all insecure_none).`);return s}function Rt(e,t){return ut[e]>=ut[t]?e:t}function It(e,t){if(void 0===e||e.type===t)return e;if("insecure_none"===t)return{type:t,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,enableSharedBuildCache:e.enableSharedBuildCache};if("insecure_none"===e.type)return{...e,type:t};if("workspace_readonly"===t){if("workspace_readwrite"===e.type){const{additionalReadwritePaths:r,...n}=e;return{...n,type:t}}return e}return e}function Tt(e){if("deny"===e?.default||void 0!==e?.deny&&0!==e.deny.length)return{version:1,..."deny"===e.default?{default:"deny"}:{},...void 0!==e.deny&&e.deny.length>0?{deny:e.deny}:{}}}function At(e,t,r){if(void 0===e||"insecure_none"===t)return;const n="insecure_none"===e.type?void 0:e,o={captureDenies:!0===e.captureDenies||void 0,networkPolicy:Tt(n?.networkPolicy),networkPolicyStrict:!0===n?.networkPolicyStrict||void 0,readBoundary:"workspace"===n?.readBoundary?"workspace":void 0,additionalReadPaths:void 0===n?.additionalReadPaths?void 0:ft(n.additionalReadPaths,r),additionalReadonlyPaths:n?.additionalReadonlyPaths,disableTmpWrite:!0===n?.disableTmpWrite||void 0,ignoreMapping:n?.ignoreMapping,writeProtectionMapping:n?.writeProtectionMapping};return"workspace_readonly"===t?{type:t,...o}:{type:"workspace_readwrite",...o}}function $t(e,t){return void 0===e||"insecure_none"===e.type||void 0===t?e:{...e,additionalReadPaths:e.additionalReadPaths?.map((e=>ct((0,tt.o1)(e,t))))}}function Mt(e,t){const r=Pt({perUser:e.perUser,teamAdmin:e.teamAdmin})??"workspace_readwrite",n=void 0===e.perRepo?r:Rt(r,e.perRepo.type),o=$t(It(e.perUser,n),t),s=$t(It(e.teamAdmin,n),t),i=mt("insecure_none"===o?.type?void 0:o?.additionalReadPaths,"insecure_none"===s?.type?void 0:s?.additionalReadPaths);return{perUser:o,perRepo:At(e.perRepo,n,i),teamAdmin:s}}function Dt(e,t){return Mt(e,t)}function Ot(e,t){return function(e,t){dt()&&(e=Mt(e,t?.workspaceDir));const r=Pt(e);if(void 0===r)return Ut({},t);switch(r){case"workspace_readwrite":return Ut(Nt(e,r),t);case"workspace_readonly":return function(e,t){const r=t?.debug,n=Lt(e,t),o={policy:jt({type:"workspace_readonly",disableTmpWrite:n.disableTmpWrite,networkPolicyStrict:n.networkPolicyStrict,readBoundary:n.readBoundary,additionalReadPaths:n.additionalReadPaths,additionalReadonlyPaths:n.additionalReadonlyPaths,networkPolicy:n.networkPolicy,debugOutputDir:n.debugOutputDir,captureDenies:n.captureDenies,enableSharedBuildCache:n.enableSharedBuildCache,privateTmp:n.privateTmp,ignoreMapping:n.ignoreMapping,writeProtectionMapping:n.writeProtectionMapping},"workspace_readonly")};return r&&(o.debug={fieldSources:n.fieldSources}),o}(Nt(e,r),t);case"insecure_none":return function(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,s=t?.debug,i={policy:jt({type:"insecure_none",allowlistEscalated:pt(r?.allowlistEscalated,n?.allowlistEscalated,o?.allowlistEscalated)||void 0,debugOutputDir:_t(r?.debugOutputDir,n?.debugOutputDir,o?.debugOutputDir),captureDenies:pt(r?.captureDenies,n?.captureDenies,o?.captureDenies)||void 0,enableSharedBuildCache:_t(r?.enableSharedBuildCache,n?.enableSharedBuildCache,o?.enableSharedBuildCache)},"insecure_none")};return s&&(i.debug={fieldSources:{}}),i}(Nt(e,r),t);default:throw new Error(`Unknown policy type: ${String(r)}`)}}(e,t)}function Ft(e,t){return e?.type===t}function Nt(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e;return{perUser:Ft(r,t)?r:void 0,perRepo:Ft(n,t)?n:void 0,teamAdmin:Ft(o,t)?o:void 0}}function Lt(e,t){const r=t?.debug,{perUser:n,perRepo:o,teamAdmin:s}=e,i=t?.workspaceDir??process.cwd(),a=function(e){const t=function(){if(0!==De.length)return{version:1,deny:[...De]}}(),r=q.default.homedir(),n=[];for(const e of Te)switch(e.type){case"workspace":case"git":case"worktree":break;case"absolute":n.push(e.pattern);break;case"home":r.length>0&&n.push((0,m.join)(r,e.pattern));break;default:{const t=e.type;throw new Error(`Unknown entry type: ${String(t)}`)}}return n.push(...ye(r)),{type:"workspace_readwrite",additionalReadonlyPaths:n,writeProtectionMapping:Ae(e),...t&&{networkPolicy:t},networkPolicyStrict:!0}}(i),c={},l=[n,o,s],u=["perUser","perRepo","teamAdmin","hardcoded"],d=(e,t)=>{r&&(c[e]=u[t]??"unknown")},h=pt(n?.disableTmpWrite,o?.disableTmpWrite,s?.disableTmpWrite);for(let e=l.length-1;e>=0;e--)if(!0===l[e]?.disableTmpWrite){d("disableTmpWrite",e);break}const p=pt(n?.networkPolicyStrict,o?.networkPolicyStrict,s?.networkPolicyStrict,a.networkPolicyStrict);a.networkPolicyStrict&&d("networkPolicyStrict",3);const f=dt()?yt(_t(n?.readBoundary,s?.readBoundary)??"system",o?.readBoundary):_t(n?.readBoundary,o?.readBoundary,s?.readBoundary)??"system",g=_t(n?.additionalReadPaths,o?.additionalReadPaths),w=!1===s?.allowUserOverrideReadPaths?mt(s.additionalReadPaths):mt(g,s?.additionalReadPaths),y="workspace"===f?w:void 0,v=mt(n?.additionalReadonlyPaths,o?.additionalReadonlyPaths,s?.additionalReadonlyPaths,a.additionalReadonlyPaths),b=v.length>0?v:void 0;let S=bt(n?.networkPolicy,o?.networkPolicy,s?.networkPolicy,a.networkPolicy);const k=s?.networkPolicy?.allow;void 0!==k&&k.length>0&&void 0!==S&&(S={...S,allow:[...k]},r&&(c["networkPolicy.allow"]="teamAdmin (replace)"));const _=void 0!==(C=S)?C:{version:1,default:"deny"};var C;const E=_t(n?.debugOutputDir,o?.debugOutputDir,s?.debugOutputDir),x=pt(n?.captureDenies,o?.captureDenies,s?.captureDenies),P=_t(n?.enableSharedBuildCache,o?.enableSharedBuildCache,s?.enableSharedBuildCache),R=_t(n?.privateTmp,o?.privateTmp,s?.privateTmp),I=kt(n?.ignoreMapping,o?.ignoreMapping,s?.ignoreMapping,a.ignoreMapping),T=$e(t?.gitDirParent??i);return{disableTmpWrite:h||void 0,networkPolicyStrict:p,readBoundary:f,additionalReadPaths:y,additionalReadonlyPaths:b,networkPolicy:_,debugOutputDir:E,captureDenies:x||void 0,enableSharedBuildCache:P,privateTmp:R,ignoreMapping:I,writeProtectionMapping:kt(n?.writeProtectionMapping,o?.writeProtectionMapping,s?.writeProtectionMapping,a.writeProtectionMapping,T),fieldSources:c}}function jt(e,t){const r={...e,type:t};for(const[e,t]of Object.entries(r))void 0===t&&Reflect.deleteProperty(r,e);return r}function Ut(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,s=t?.debug,i=Lt(e,t),a=mt(r?.additionalReadwritePaths,n?.additionalReadwritePaths,o?.additionalReadwritePaths),c={policy:jt({type:"workspace_readwrite",disableTmpWrite:i.disableTmpWrite,networkPolicyStrict:i.networkPolicyStrict,readBoundary:i.readBoundary,additionalReadPaths:i.additionalReadPaths,additionalReadwritePaths:a.length>0?a:void 0,additionalReadonlyPaths:i.additionalReadonlyPaths,networkPolicy:i.networkPolicy,debugOutputDir:i.debugOutputDir,captureDenies:i.captureDenies,enableSharedBuildCache:i.enableSharedBuildCache,privateTmp:i.privateTmp,ignoreMapping:i.ignoreMapping,writeProtectionMapping:i.writeProtectionMapping},"workspace_readwrite")};return s&&(c.debug={fieldSources:i.fieldSources}),c}var Bt=r("../utils/dist/workload-spawn.js"),Wt=r("../context/dist/logger.js"),Ht=r("../context/dist/core.js"),qt=r("../utils/dist/command-glob.js");const zt=n.execFile,Gt=new WeakMap;function Vt(e,t,r){return e===t?"related":r?.has(e)?"probably_unrelated":"maybe_related"}const Kt="darwin"===process.platform,Jt="linux"===process.platform,Zt=(0,Wt.h)("shell-exec:sandbox");function Xt(e){const t=ce();return e&&0!==e.length?e.includes(t)?e:[...e,t]:[t]}let Qt,Yt=!0,er=!1;function tr(){return Qt}function rr(e){"linux"===process.platform&&Object.assign(e,I(e))}let nr=null,or=null,sr=null,ir=null,ar=!1,cr=null;function lr(e){return{...e,additionalReadonlyPaths:Xt(e.additionalReadonlyPaths)}}class ur extends Error{}function dr(e){return e instanceof Error&&"code"in e&&"string"==typeof e.code?e.code:"unknown"}function hr(e,t,r){let n;e.ignoreMapping&&(n=function(e){return vr(e)}(e.ignoreMapping));const o=function(e,t,r){const n=e&&e.length>0?function(...e){const t={};for(const r of e){let e=!1;try{e=(0,g.existsSync)(r)&&(0,g.statSync)(r).isDirectory()}catch{}if(e)t[r]||(t[r]=[]),t[r].push("**");else{const e=r.lastIndexOf("/"),n=e>0?r.slice(0,e):"/",o=e>=0?r.slice(e+1):r;t[n]||(t[n]=[]),o?t[n].push(o,`${o}/**`):t[n].push("**")}}return t}(...e):{},o=!Jt||yr(r),s={...n};for(const[e,r]of Object.entries(t??{})){const t=e.startsWith("file://")?br(e):e;(o||yr(t))&&(s[e]=St(s[e],r))}if(0!==Object.keys(s).length)return vr(s)}(e.additionalReadonlyPaths,e.writeProtectionMapping,t),s=(i=e.readBoundary,r?.workspaceReadEnabled??function(){const e=Yt;return"function"==typeof e?e():e}()?i??"system":"system");var i;const a=function(e=process.platform){const t=[],r=new Set,n={};try{n.ripgrep=T()}catch{}for(const o of Ie(e,q.homedir(),n))r.has(o)||(r.add(o),t.push(o));return t}(),c=[t,..."workspace_readwrite"===e.type&&e.additionalReadwritePaths||[],Z(t)].filter((e=>void 0!==e)),l="workspace"===s?(e.additionalReadPaths??[]).flatMap((e=>function(e,t){let r=e.trim();(r.startsWith("~/")||r.startsWith("~\\"))&&(r=m.join(q.homedir(),r.slice(2)));const n=e=>e.includes("*")||e.includes("?"),o=/[/\\]\*\*?$/;if(o.test(r)&&n(m.basename(r.replace(/(?:[/\\]\*\*?)+$/,""))))return Zt.warn((0,Ht.q6)(),"[additionalReadPathGrants] a Read Allowlist file-name glob followed by /* or /** grants nothing"),[];const s=m.basename(r);if(o.test(r)||!n(s))return function(e){const t=[],r=new Set;for(const n of e){let e=n.trim();if(!e)continue;"~"===e?e=q.homedir():(e.startsWith("~/")||e.startsWith("~\\"))&&(e=m.join(q.homedir(),e.slice(2))),e=e.replace(/\/\*\*$/,"").replace(/\/\*$/,""),e=e.replace(/\\\*\*$/,"").replace(/\\\*$/,"");const o=m.basename(e);if((o.includes("*")||o.includes("?"))&&(e=m.dirname(e)),!e||"."===e)continue;const s=m.normalize(e);r.has(s)||(r.add(s),t.push(s))}return t}([e]);const i=m.dirname(r);return m.isAbsolute(i)?function(e,t,r){const n=(0,qt.b)(t),o=[];let s;try{const t=(0,g.realpathSync)(e);if(r.filter((e=>g.existsSync(e))).map((e=>(0,g.realpathSync)(e))).some((e=>(0,tt.BJ)(t,e))))return[];s=g.opendirSync(t);for(let e=1;;e++){const r=s.readSync();if(null===r)return o;if(e>1e4)throw new ur("its folder has more than 10000 entries");if(!n(r.name))continue;const i=m.join(t,r.name);try{if(!g.lstatSync(i).isFile()||m.dirname((0,g.realpathSync)(i))!==t)continue}catch(e){Zt.info((0,Ht.q6)(),`[fileNameGlobMatches] skips a matching file: error ${dr(e)}`);continue}if(256===o.length)throw new ur("more than 256 files match");o.push(i)}}catch(e){const t=e instanceof ur?e.message:`error ${dr(e)}`;return Zt.warn((0,Ht.q6)(),`[fileNameGlobMatches] a Read Allowlist file-name glob grants nothing: ${t}`),[]}finally{s?.closeSync()}}(i,s,t):[]}(e,c))):[],u=[...a],d=new Set(a);for(const e of l)d.has(e)||(d.add(e),u.push(e));const h={cwd:t,readBoundary:s,hardcodedReadPaths:u,additionalReadonlyPaths:o,networkAccess:Xe(e.networkPolicy),ignoreMapping:n};return"workspace_readonly"===e.type?{type:e.type,...h}:{type:e.type,...h,additionalReadwritePaths:e.additionalReadwritePaths||[],disableTmpWrite:e.disableTmpWrite||!1}}function pr(e){const t={sandbox:e};return Jt&&function(){const e=er;return"function"==typeof e?e():e}()&&(t.kernelMountBudget=!0),t}function fr(e){if(null!==nr)return nr;try{const t=tr();return Zt.info(e,`[checkBinaryAvailable] Resolved binary path: ${t}`),t?(nr=g.existsSync(t),nr?Zt.info(e,`[checkBinaryAvailable] Binary path exists: ${String(nr)}`):(or=new Error(`Sandbox binary not found at ${t}`),Zt.info(e,`[checkBinaryAvailable] Binary not found at: ${t}`)),nr):(or=new Error("Sandbox binary path was not configured"),nr=!1,Zt.info(e,"[checkBinaryAvailable] Binary path not set, returning false"),!1)}catch(t){return or=t instanceof Error?t:new Error(String(t)),nr=!1,Zt.info(e,`[checkBinaryAvailable] Exception checking binary: ${String(t)}`),!1}}function mr(e){if(null!==ir)return ir;const t=e??(0,Ht.q6)();if(Zt.info(t,"[isSandboxHelperSupported] Starting sandbox support check..."),!fr(t)){const e=or?.message||"Binary check failed";return sr=e,Zt.info(t,`[isSandboxHelperSupported] Binary not available, returning false. Reason: ${e}`),ir=!1,ir}if("win32"===process.platform)return sr="Windows sandbox helper only provides network proxy, not filesystem isolation",Zt.info(t,"[isSandboxHelperSupported] win32: returning false (proxy-only, no filesystem sandbox)"),ir=!1,ir;if("darwin"===process.platform)return sr=null,Zt.info(t,`[isSandboxHelperSupported] ${process.platform} platform, binary available, sandbox supported!`),ir=!0,ir;const{binaryPath:r,args:o,env:s}=function(e,t){const r=pr(hr(lr({type:"workspace_readwrite"}),t)),n=String(tr());Zt.info(e,`[sandboxPreflight] Running preflight with binary: ${n}`),Zt.info(e,`[sandboxPreflight] CWD: ${t}`);const o={...process.env};return rr(o),{binaryPath:n,args:["--policy",le(JSON.stringify(r)),"--preflight-only","--","/bin/true"],env:o}}(t,process.cwd());try{const e=Date.now();(0,Bt.D9)(n.execFileSync,r,o,{stdio:["ignore","ignore","pipe"],timeout:gr,env:s,shell:!1});const i=Date.now()-e;return sr=null,Zt.info(t,`[isSandboxHelperSupported] Preflight succeeded in ${i}ms, sandbox supported!`),ir=!0,ir}catch(e){return function(e,t){const{message:r,status:n,stderrText:o}=t;return Zt.error(e,`[sandboxPreflight] Preflight failed: ${r}`),Zt.error(e,`[sandboxPreflight] Exit status: ${n}`),o&&Zt.error(e,`[sandboxPreflight] Stderr: ${o}`),sr=2===n?`Linux preflight failed with exit code 2 (unsupported kernel features). stderr: ${o||"none"}`:`Linux preflight failed: ${r||"unknown error"}. Exit status: ${n}. stderr: ${o||"none"}`,ir=!1,!1}(t,function(e){if("object"!=typeof e||null===e)return{stderrText:""};const t="message"in e&&"string"==typeof e.message?e.message:void 0,r=!("status"in e)||"number"!=typeof e.status&&null!==e.status?void 0:e.status,n="stderr"in e?e.stderr:void 0;return{message:t,status:r,stderrText:Buffer.isBuffer(n)||"string"==typeof n?n.toString():""}}(e))}}(0,G.J)((function(){ir=null,ar=!1,cr=null,sr=null,nr=null,or=null}));const gr=15e3;function wr(e,t=[],r={},o){const i=(0,Ht.q6)();if(r.env=a(s(r.env)),!fr(i))throw new Error(`Sandbox binary not available: ${or?.message||"binary not configured"}. Please build the binary or use 'insecure_none' policy.`);if("insecure_none"===o.type)return(0,Bt.D9)(n.spawn,e,t,{...r,windowsHide:!0});if("workspace_readwrite"===o.type||"workspace_readonly"===o.type)return function(e,t,r,o){if("workspace_readwrite"!==o.type&&"workspace_readonly"!==o.type)throw new Error("Expected workspace_readwrite or workspace_readonly policy");const i=String(r.cwd??process.cwd()),c=o.sandboxWorkspaceRoot??i;let u=e,d=t;r.shell&&("win32"===process.platform?(u="string"==typeof r.shell?r.shell:"cmd.exe",d=["/c",`${e} ${t.join(" ")}`]):(u="string"==typeof r.shell?r.shell:"/bin/sh",d=["-c",`${e} ${t.join(" ")}`]));const h=function({workspaceRoot:e,executionCwd:t}){const r=m.resolve(e),n=m.resolve(t),o=Sr(r);if(n===r||n===o)return;const s=e=>(0,tt.ZU)({basePath:o,targetPath:e})?m.join(r,m.relative(o,e)):void 0,i=(0,tt.ZU)({basePath:r,targetPath:n})?n:s(n)??n;return{directory:i,fallbackDirectory:s(Sr(n))??i}}({workspaceRoot:c,executionCwd:i});"win32"!==process.platform&&void 0!==h&&({command:u,args:d}=(0,oe.kO)(u,d,h));const p=hr(lr(o),c),f=(0,Ht.q6)();!function({log:e,dirs:t=ve(q.homedir(),q.tmpdir(),pe),createOnly:r=[we(process.env,pe)].filter((e=>void 0!==e)),policyDir:n=ie(),uid:o=process.getuid?.()??-1}){const s=m.join(n,"node-compile-cache-removed-1"),{record:i,problem:a}=function(e){const t=e=>({record:{cleaned:[],kept:{},failed:{}},problem:e});let r,n;try{r=g.readFileSync(e,"utf8")}catch(e){const r=ke(e);return t("ENOENT"===r?void 0:r)}try{n=JSON.parse(r)}catch(e){return t(e instanceof SyntaxError?"not JSON":ke(e))}if("object"!=typeof n||null===n)return t("not a record");const o="cleaned"in n?n.cleaned:void 0;return{record:{cleaned:Array.isArray(o)?o.filter((e=>"string"==typeof e)):[],kept:Se("kept"in n?n.kept:void 0),failed:Se("failed"in n?n.failed:void 0)}}}(s);void 0!==a&&e(`node compile cache: starting a new cleanup record (${a})`);const c=new Set(i.cleaned),l=new Set(t);let u=!1;for(const n of[...t,...r.filter((e=>!l.has(e)))])try{const t=g.lstatSync(n,{throwIfNoEntry:!1});if(void 0!==t){const r=be(t,o);if(void 0!==r){i.kept[n]!==r&&(e(`node compile cache: kept ${n} (${r})`),i.kept[n]=r,u=!0);continue}l.has(n)&&!c.has(n)&&(g.rmSync(n,{recursive:!0,force:!0}),e(`node compile cache: removed ${n}`))}g.mkdirSync(n,{recursive:!0,mode:448}),l.has(n)&&!c.has(n)&&(c.add(n),u=!0),void 0===i.kept[n]&&void 0===i.failed[n]||(delete i.kept[n],delete i.failed[n],u=!0)}catch(t){const r=ke(t);i.failed[n]!==r&&(e(`node compile cache: could not prepare ${n} (${r})`),i.failed[n]=r,u=!0)}u&&function(e,t){const r=`${e}.${process.pid}.tmp`;try{g.writeFileSync(r,`${JSON.stringify(t)}\n`,{mode:384}),g.renameSync(r,e)}catch{g.rmSync(r,{force:!0})}}(s,{...i,cleaned:[...c]})}({log:e=>Zt.info(f,e)});const w=function(e){if(!("workspace"!==e.readBoundary||"workspace_readwrite"===e.type&&e.disableTmpWrite||"win32"===process.platform))return X(e.cwd,{create:!0})}(p);let y;w&&(p.additionalReadwritePaths=[...p.additionalReadwritePaths??[],w],Jt&&!0===o.privateTmp&&(y=te(w).TMPDIR));const v=function(e){if("insecure_none"===e.type)return;const t=e.networkPolicy;if(void 0===t)return;if(!Xe(t))return;const r=void 0!==t.deny&&t.deny.length>0;return"allow"!==t.default||r?{version:1,...t}:void 0}(o),b=pr(p);void 0!==y&&(b.mapTmpTo=y),void 0!==v&&(b.networkPolicy=v),!1===o.networkPolicyStrict&&(b.networkPolicyStrict=!1);const S=["--policy",le(JSON.stringify(b)),"--",u,...d],k=s(process.env),_={..."linux"===process.platform?l(k):k,..."linux"===process.platform&&r.env?l(r.env):r.env,CURSOR_SANDBOX:"native"};rr(_);const C=new Set(Y);if(w){const e=function(e,t,r){const n=te(e);if(r){const r=re();for(const[o,s]of Object.entries(re(e)))t[o]===r[o]&&(n[o]=s)}return n}(w,_,o.enableSharedBuildCache);Object.assign(_,e);for(const t of Object.keys(e))C.add(t);_.__CURSOR_SANDBOX_TEMP_RESTORE=Object.entries(e).map((([e,t])=>`builtin export ${e}='${t.replace(/'/g,"'\\''")}'`)).join("; ")}_.__CURSOR_SANDBOX_OWNED_ENV=[...C].join(" ");const E={cwd:void 0!==y?p.cwd:r.cwd||i,env:a(_),stdio:r.stdio||["pipe","pipe","pipe"],detached:r.detached,windowsHide:!0};try{const e=new Date,t=(0,Bt.D9)(n.spawn,String(tr()),S,E);return Kt&&t.pid&&function(e,t){Gt.set(e,t)}(t,{startTime:e,pid:t.pid}),t}catch(e){throw new Error(`Failed to spawn sandboxed process: ${String(e)}`)}}(e,t,r,o);throw new Error(`Unsupported sandbox policy: ${String(o)}`)}function yr(e,t=e=>g.existsSync(e)){if((0,oe.$f)(e))return!0;let r=m.resolve(e);for(;;){try{if(t(m.join(r,".git")))return!0}catch{}const e=m.dirname(r);if(e===r)return!1;r=e}}function vr(e,t,r,n){const o={};for(const[t,r]of Object.entries(e)){const e=t.startsWith("file://")?br(t):t;o[e]=St(o[e],r);const n=Sr(e);n!==e&&(o[n]=St(o[n],r))}return o}function br(e){let t=e.replace(/^file:\/\//,"");return t=decodeURIComponent(t),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t}function Sr(e,t){if((0,oe.$f)(e))return e;try{return(t??g.realpathSync)(e)}catch{return e}}function kr(){return sr}class _r extends Error{reason;constructor(e,t){super(e),this.reason=t,this.name="SandboxUnsupportedError"}}const Cr="darwin"===process.platform;function Er(e){!function(e){T();const{sandboxBinaryPath:t,workspaceReadEnabled:r,kernelMountBudget:n}=e;Qt||(Qt=t),void 0!==r&&(Yt=r),void 0!==n&&(er=n)}(e)}function xr(e,t=[],r={},o){if(r.env=s(r.env),o.enableSharedBuildCache&&(r={...r,env:{...s(process.env),...re(),...r.env}}),"insecure_none"!==o.type){if(mr())return wr(e,t,r,o);const n=kr();throw new _r(`Sandbox policy '${o.type}' is not supported on this system. Ensure the sandbox helper binary is available, or use 'insecure_none'. Reason: ${n||"unknown"}`,n??void 0)}return function(e,t,r,o={spawn:n.spawn,spawnWorkload:Bt.D9}){return o.spawnWorkload(o.spawn,e,t,{...r,env:a(r.env??process.env),windowsHide:!0})}(e,t,r)}function Pr(e){return Cr?async function(e){const t=Gt.get(e);return t?(r=t.pid,n=t.startTime,o=t.unrelatedPids,new Promise((e=>{try{const t=new Date,s=["show","--style","ndjson","--predicate",'process=="kernel" AND eventMessage CONTAINS "Sandbox:" AND eventMessage contains "deny"',"--last",Math.ceil((t.getTime()-n.getTime())/1e3).toString()];(0,Bt.D9)(zt,"/usr/bin/log",s,((t,n)=>{if(t)return void e([{raw:t.message}]);const s=n.split(/\r?\n/).filter((e=>e.trim().length>0)),i=[];for(const e of s)try{const t=JSON.parse(e),n=t?.eventMessage??"";if(!n||"string"!=typeof n)continue;const s=/^Sandbox:\s+([^(]+)\((\d+)\)\s+([a-zA-Z-]+)\((\d+)\)\s+([^\s]+)\s+(.+)$/.exec(n);if(s){const[,e,a,c,l,u,d]=s,h=Number(a);i.push({timestamp:t.timestamp,processName:e.trim(),pid:h,decision:c.toLowerCase(),decisionCode:Number(l),operation:u,target:d,duplicateCount:1,raw:n,relationship:Vt(h,r,o)});continue}const a=/^(\d+) duplicate report for Sandbox: (.+)$/.exec(n);if(a){const e=Number(a[1]),s=a[2],c=/^([^(]+)\((\d+)\)\s+([a-zA-Z-]+)\((\d+)\)\s+([^\s]+)\s+(.+)$/.exec(s);if(c){const[,s,a,l,u,d,h]=c,p=Number(a);i.push({timestamp:t.timestamp,processName:s.trim(),pid:p,decision:l.toLowerCase(),decisionCode:Number(u),operation:d,target:h,duplicateCount:e,raw:n,relationship:Vt(p,r,o)})}else i.push({timestamp:t.timestamp,duplicateCount:e,raw:n});continue}i.push({timestamp:t.timestamp,raw:n})}catch{}e(i)}))}catch(t){e([{raw:String(t)}])}}))):(console.log("No sandbox metadata found on child process"),[]);var r,n,o}(e):Promise.resolve([])}function Rr(e,t){if(Cr)try{(0,g.accessSync)("/usr/bin/sandbox-exec",g.constants.X_OK)}catch{return!1}return mr(t?.ctx)}var Ir=r("node:stream"),Tr=r("../context/dist/otel.js"),Ar=r("../utils/dist/writable-iterable.js");const $r="--",Mr='builtin eval "$1" 3<&- 4>&-';var Dr=r("node:string_decoder");const Or=50,Fr=262144;class Nr{writable;pending=[];pendingBytes=0;flushTimeout;flushPromise;flushIntervalMs;maxBufferedBytes;constructor(e,t){this.writable=e,this.flushIntervalMs=t?.flushIntervalMs??Or,this.maxBufferedBytes=t?.maxBufferedBytes??Fr}async push(e,t){0!==t.length&&(this.pending.push({type:e,data:t}),this.pendingBytes+=t.length,this.pendingBytes>=this.maxBufferedBytes?await this.flush():this.scheduleFlush())}async flush(){if(this.clearFlushTimeout(),this.flushPromise)return await this.flushPromise,void(this.pendingBytes>0&&await this.flush());if(0===this.pendingBytes)return;const e=this.pending;this.pending=[],this.pendingBytes=0,this.flushPromise=this.writeBufferedOutput(e);try{await this.flushPromise}finally{this.flushPromise=void 0}}async close(){await this.flush()}scheduleFlush(){void 0===this.flushTimeout&&(this.flushTimeout=setTimeout((()=>{this.flushTimeout=void 0,this.flush()}),this.flushIntervalMs))}clearFlushTimeout(){void 0!==this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=void 0)}async writeBufferedOutput(e){for(const t of function(e){if(0===e.length)return[];const t=[];let r=e[0].type,n=[e[0].data];for(let o=1;o{e.writable.write({type:t,data:r}).catch((()=>{}))};return e.stdout?.on("data",(e=>{const n=t.note(e);void 0!==n&&n.length>0&&r("stdout",n)})),e.stderr?.on("data",(e=>{r("stderr",e)})),{get stdoutBytes(){return t.bytes},get stdoutPrefix(){return t.stdoutPrefix},async waitForOutput(){},async releaseHeldStdout(){const e=t.takeHeld();void 0!==e&&e.length>0&&r("stdout",e)},dropHeldStdout(){t.takeHeld()},async flush(){await this.releaseHeldStdout()}}}const r=new Nr(e.writable,e.outputLimiterOptions);let n;const o=Promise.all([jr(e.stdout,r,t),Ur(e.stderr,"stderr",r)]).then((()=>{})).catch((e=>{n=e}));return{get stdoutBytes(){return t.bytes},get stdoutPrefix(){return t.stdoutPrefix},async waitForOutput(){if(await o,void 0!==n)throw(e=n)instanceof Error?e:new Error(String(e));var e},async releaseHeldStdout(){const e=t.takeHeld();void 0!==e&&e.length>0&&await r.push("stdout",e)},dropHeldStdout(){t.takeHeld()},async flush(){await this.releaseHeldStdout(),await r.flush()}}}async function jr(e,t,r){if(e)for await(const n of e){const e=r.note(n);void 0!==e&&e.length>0&&await t.push("stdout",e)}}async function Ur(e,t,r,n){if(e)for await(const o of e)n?.(o),await r.push(t,o)}var Br;!function(e){e.Zsh="zsh",e.ZshLight="zsh-light",e.Bash="bash",e.PowerShell="powershell",e.Naive="naive"}(Br||(Br={}));const Wr={TERM:"dumb",NO_COLOR:"1",FORCE_COLOR:"0",_ZO_DOCTOR:"0"};function Hr(e){return"win32"===e.platform?"windows_tree":e.detached?"process_group":"single_process"}function qr(e,t,r,o={spawn:n.spawn,killPid:process.kill.bind(process)}){const s=e.pid;if(void 0===s)return;const i=()=>{try{e.kill(r)}catch{}};switch(t){case"process_group":try{o.killPid(-s,r)}catch{i()}return;case"windows_tree":try{o.spawn("taskkill",["/pid",String(s),"/t","/f"],{stdio:"ignore",windowsHide:!0}).on("error",i)}catch{i()}return;case"single_process":return void i();default:throw new Error(`Unknown process tree kill mode: ${String(t)}`)}}function zr(e,t=[],r={},n,o){const s=xr(e,t,{...r,env:I(r.env??process.env)},n);return o?Vr(s,{detached:!0===r.detached},o):Gr(s,!0===r.detached),s}function Gr(e,t){"single_process"!==Hr({platform:process.platform,detached:t})&&e.pid}function Vr(e,t,r){const n=Hr({platform:process.platform,detached:t.detached});Gr(e,t.detached);const o=()=>{if(!e.pid)return;qr(e,n,"SIGTERM");const t=setTimeout((()=>{!e.killed&&e.pid&&qr(e,n,"SIGKILL")}),1e3);"process_group"!==n&&e.once("exit",(()=>{clearTimeout(t)}))};r.aborted?o():(r.addEventListener("abort",o,{once:!0}),e.once("exit",(()=>{r.removeEventListener("abort",o)})))}function Kr(e,t,r){if(e){try{process.kill(-e,t)}catch{return}"SIGTERM"===t&&void 0!==r&&r>0&&setTimeout((()=>{try{process.kill(-e,"SIGKILL")}catch{}}),r)}}const Jr=new Set(["SIGTERM","SIGINT","SIGHUP","SIGQUIT","SIGKILL"]);function Zr(e,t,r){null!==t&&Jr.has(t)&&!r&&"win32"!==process.platform&&Kr(e,t)}function Xr(e,{shellName:t,closeGraceMs:r,timeoutMs:n}){const o=r??5e3,s=n??6e4;return new Promise((r=>{const n=[];let i;const a=e=>{n.push(e)},c=()=>{clearTimeout(d),o<=0||(i=setTimeout((()=>{console.warn(`[shell-exec] ${t} state init exited but its stdio did not close within ${o}ms; a startup file left a background process holding the output pipe. Proceeding with the dump received so far.`),u("exit_without_close")}),o))},l=()=>{u("closed")},u=t=>{clearTimeout(d),clearTimeout(i),e.off("exit",c),e.off("close",l),e.stdout?.off("data",a),e.stdout?.resume(),r({outcome:t,stdout:Buffer.concat(n).toString("utf8")})},d=s>0?setTimeout((()=>{console.warn(`[shell-exec] ${t} state init did not exit within ${s}ms; a startup file is blocking. Killing it and falling back to an empty state.`),qr(e,Hr({platform:process.platform,detached:!0}),"SIGKILL"),u("timed_out")}),s):void 0;e.stdout?.on("data",a),Qr(e.stdout),e.on("exit",c),e.on("close",l)}))}function Qr(e){e?.on("error",(()=>{}))}function Yr(e){e.removeAllListeners(),e.on("error",(()=>{})),e.stdout?.removeAllListeners("close"),e.stderr?.removeAllListeners("close");for(const t of e.stdio.slice(3))t?.destroy()}const en="IFS= builtin read -r -d '' __cursor_command <&5 2>/dev/null || { builtin printf '%s\\n' 'The command did not run: a shell startup file ($BASH_ENV or .zshenv) closed or replaced file descriptor 5, which carries the command. Run it again; this shell now passes commands as arguments.' >&2; builtin exit 126; }; exec 5<&-; builtin set -- \"$__cursor_command\"; builtin unset __cursor_command; ";function tn(e,t){return 126===e&&""===t}function rn(){return"win32"!==process.platform}function nn(e,t){const r=e.stdio.at(5);r instanceof Ir.default.Writable&&(Qr(r),r.end(`${t}\0`))}function on(e,t){e&&(Qr(e),e.write(t),e.end())}function sn(e,t){if(!e)return;Qr(e);const r=new Dr.StringDecoder("utf8");e.on("data",(e=>{const n=r.write(e);""!==n&&t(n)})),e.on("end",(()=>{const e=r.end();""!==e&&t(e)}))}function an(e){const t=e.indexOf("\n");return{cwd:Buffer.from(e.substring(0,t),"utf16le").toString("utf16le"),rest:e.substring(t)}}function cn(e,t){const r=t instanceof Error&&"code"in t&&"string"==typeof t.code?t.code:"unknown";console.warn(e,r)}function ln(e,t){const r=`${t}\n`,n=e.indexOf(r);return n>=0?e.slice(n+r.length):e}function un(e){return!1===e?.isLoginShellEnabled?"-ic":"-ilc"}function dn(e,t,r){const n=`${t}\n`;if(!e.startsWith(n))return;const o=e.indexOf(`\n${r}\n`,n.length-1);return o<0?void 0:e.slice(n.length,o+1)}const hn="__CURSOR_BASH_STATE_START__",pn="__CURSOR_BASH_STATE_END__",fn="\n Emit $PWD.Path\n #Log-Timing \"working_dir\"\n\n function ShouldPersistEnvVar {\n param([string]$Name)\n if ($Name -eq 'CURSOR_CONVERSATION_ID') {\n return $false\n }\n if ($Name -eq 'CURSOR_REQUEST_ID') {\n return $false\n }\n if ($Name -like 'CURSOR_AGENT_STORE*') {\n return $false\n }\n if ($Name -like '*CURSOR_SANDBOX*') {\n return $false\n }\n if ($Name -eq 'ELECTRON_RUN_AS_NODE') {\n return $false\n }\n return $true\n }\n\n $envVars = Get-ChildItem Env: | Sort-Object Name\n foreach ($var in $envVars) {\n if (-not (ShouldPersistEnvVar -Name $var.Name)) {\n continue\n }\n $encoded = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes([string]$var.Value))\n Emit ('Set-Item -LiteralPath ''Env:{0}'' -Value ([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String(''{1}'')))' -f $var.Name, $encoded)\n }\n #Log-Timing \"environment\"\n\n $aliases = Get-Alias | Sort-Object Name\n foreach ($alias in $aliases) {\n $definition = $alias.Definition\n\n if ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::ReadOnly) {\n }\n elseif ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::Constant) {\n }\n elseif ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::AllScope) {\n }\n else {\n Emit ('Set-Alias -Name \"{0}\" -Value \"{1}\"' -f $alias.Name, $definition)\n }\n }\n\n #Log-Timing \"finalize\"\n",mn=`\nfunction Dump-PowerShellState {\n param(\n [Parameter(Mandatory = $true)]\n [string]$OutputFile\n )\n\n function Emit {\n param([string]$Content)\n Add-Content -Path $OutputFile -Value $Content -Encoding UTF8\n }\n\n if (Test-Path $OutputFile) {\n Remove-Item $OutputFile -Force\n }\n New-Item -Path $OutputFile -ItemType File -Force | Out-Null\n #Log-Timing "file_init"\n${fn}}\n`,gn=`\nfunction Dump-PowerShellState {\n param(\n [Parameter(Mandatory = $true)]\n [string]$OutputFile,\n [string]$Trailer\n )\n\n $__cursorDumpText = New-Object System.Text.StringBuilder\n $__cursorDumpNewLine = [Environment]::NewLine\n function Emit {\n param([string]$Content)\n [void]$__cursorDumpText.Append($Content).Append($__cursorDumpNewLine)\n }\n${fn}\n if ($Trailer) {\n Emit $Trailer\n }\n [System.IO.File]::WriteAllText($OutputFile, $__cursorDumpText.ToString(), (New-Object System.Text.UTF8Encoding ($PSVersionTable.PSVersion.Major -lt 6)))\n}\n`,wn="# cursor-shell-timings ",yn="[long](([DateTime]::UtcNow.Ticks - 621355968000000000) / 10000)",vn="\ntry { [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\ntry { [Console]::InputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\ntry { $global:OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\n",bn=e=>e.map((e=>`'${e}'`)).join(", "),Sn=` # The body of the proxy for Set-Content and Export-Csv. Its param block comes from the\n # cmdlet itself. Every step of its own is guarded, so a failure in the proxy leaves the\n # file as the cmdlet writes it.\n $__cursorProxyBody = @'\nbegin {\n # The file system paths the call writes, each with its own 'bom' or 'nobom', and what each\n # held before the call; the call gets -Encoding only when every path has a decision.\n $__cursorFiles = $null\n $__cursorDecisions = @{}\n $__cursorBefore = @{}\n $__cursorDecided = $false\n # The command line asked for UTF8 by name, for files whose readers take it without a BOM.\n $__cursorAsked = $false\n $__cursorStrip = $false\n $__cursorStopped = $false\n $__cursorScopeBound = $null\n $__cursorInvoked = "$($MyInvocation.InvocationName)"\n # The first 8 KiB of the file and its length; $null for a file that does not exist.\n $__cursorHeadOf = {\n param([string]$__cursorFile)\n if (-not [System.IO.File]::Exists($__cursorFile)) { return $null }\n $__cursorHead = New-Object byte[] 8192\n $__cursorCount = 0\n $__cursorStream = [System.IO.File]::Open($__cursorFile, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite -bor [System.IO.FileShare]::Delete)\n try {\n $__cursorLength = $__cursorStream.Length\n while ($__cursorCount -lt $__cursorHead.Length) {\n $__cursorRead = $__cursorStream.Read($__cursorHead, $__cursorCount, $__cursorHead.Length - $__cursorCount)\n if ($__cursorRead -le 0) { break }\n $__cursorCount += $__cursorRead\n }\n } finally { $__cursorStream.Dispose() }\n return @{ Length = $__cursorLength; Head = $__cursorHead; Count = $__cursorCount }\n }\n # 'bom' or 'nobom' for a file the proxy writes in UTF-8, $null for one it leaves to the\n # cmdlet: the file's own bytes decide when it has content, its extension otherwise.\n $__cursorEncodingOf = {\n param([string]$__cursorFile, $__cursorWas)\n $__cursorExtension = [System.IO.Path]::GetExtension($__cursorFile).ToLowerInvariant()\n if ($__cursorExtension -in @(${bn([".bat",".cmd",".reg",".ini",".inf",".vbs",".vbe",".wsf"])})) { return $null }\n if ([System.IO.Directory]::Exists($__cursorFile)) { return $null }\n if ($null -ne $__cursorWas -and $__cursorWas.Count -gt 0) {\n $__cursorHead = $__cursorWas.Head\n $__cursorEnd = $__cursorWas.Count\n if ($__cursorEnd -ge 3 -and $__cursorHead[0] -eq 0xEF -and $__cursorHead[1] -eq 0xBB -and $__cursorHead[2] -eq 0xBF) { return 'bom' }\n if ($__cursorEnd -ge 2 -and (($__cursorHead[0] -eq 0xFF -and $__cursorHead[1] -eq 0xFE) -or ($__cursorHead[0] -eq 0xFE -and $__cursorHead[1] -eq 0xFF))) { return $null }\n if ($__cursorEnd -eq $__cursorHead.Length) {\n # A full header may end inside a character; that character is left out.\n $__cursorAt = $__cursorEnd - 1\n while ($__cursorAt -gt $__cursorEnd - 4 -and ($__cursorHead[$__cursorAt] -band 0xC0) -eq 0x80) { $__cursorAt-- }\n if ($__cursorHead[$__cursorAt] -ge 0xC0) {\n $__cursorNeed = if ($__cursorHead[$__cursorAt] -ge 0xF0) { 4 } elseif ($__cursorHead[$__cursorAt] -ge 0xE0) { 3 } else { 2 }\n if ($__cursorEnd - $__cursorAt -lt $__cursorNeed) { $__cursorEnd = $__cursorAt }\n }\n }\n # A strict decode throws on bytes that are not UTF-8; a character beyond ASCII takes\n # more bytes than code units, so all-ASCII content is the one that decodes to as many.\n try { $__cursorText = [System.Text.UTF8Encoding]::new($false, $true).GetString($__cursorHead, 0, $__cursorEnd) } catch { return $null }\n if ($__cursorText.Length -lt $__cursorEnd) { return 'nobom' }\n }\n if ($__cursorExtension -in @(${bn([".ps1",".psm1",".psd1"])})) { return 'bom' }\n if ($__cursorExtension -in @(${bn([".py",".pyw",".pyi",".js",".mjs",".cjs",".jsx",".ts",".tsx",".mts",".cts",".go",".rs",".kt",".kts",".scala",".swift",".dart",".rb",".cs",".fs",".fsx",".vb",".razor",".cshtml",".sh",".bash",".zsh",".html",".htm",".css",".scss",".sass",".less",".vue",".svelte",".json",".jsonc",".json5",".yaml",".yml",".toml",".xml",".xsd",".xsl",".xslt",".svg",".csproj",".props",".targets",".graphql",".gql",".proto",".tf",".hcl",".md",".markdown",".mdx",".rst",".adoc",".gitignore",".gitattributes",".gitmodules",".editorconfig",".cursorignore",".cursorindexingignore",".mdc"])})) { return 'nobom' }\n return $null\n }\n # Whether the -Encoding the call bound is the UTF-8 with a BOM that Windows PowerShell names\n # UTF8. PowerShell 7 binds the encoding object of that name, and reaches this only when a\n # test fakes the version.\n $__cursorIsUtf8Bom = {\n param($__cursorEncoding)\n if ($__cursorEncoding -is [System.Text.Encoding]) { return ($__cursorEncoding -is [System.Text.UTF8Encoding] -and $__cursorEncoding.GetPreamble().Length -gt 0) }\n return ("$__cursorEncoding" -eq 'UTF8')\n }\n # Whether a default under $PSDefaultParameterValues can reach this call's -Encoding: under\n # the cmdlet's name, an alias it had when the proxy was built, or the name the call used. A\n # value such a default put in $PSBoundParameters is not one the command line asked for.\n $__cursorHasEncodingDefault = {\n param([string]$__cursorInvoked)\n foreach ($__cursorKey in @($PSDefaultParameterValues.Keys)) {\n $__cursorKeyParts = "$__cursorKey" -split ':', 2\n if ($__cursorKeyParts.Count -ne 2 -or 'Encoding' -notlike $__cursorKeyParts[1].Trim()) { continue }\n foreach ($__cursorName in @(__CURSORNAMES__, $__cursorInvoked)) {\n if ($__cursorName -like $__cursorKeyParts[0].Trim()) { return $true }\n }\n }\n return $false\n }\n # Whether a UTF8 asked for by name is UTF-8 without a BOM for this file: one whose reader\n # rejects a BOM, and that is new, empty or starts with no BOM of any encoding.\n $__cursorTakesNoBom = {\n param([string]$__cursorFile, $__cursorWas)\n if ([System.IO.Directory]::Exists($__cursorFile)) { return $false }\n if ([System.IO.Path]::GetExtension($__cursorFile).ToLowerInvariant() -notin @(${bn([".json",".py",".js",".ts",".sh",".yaml",".toml",".mdc"])}) -and\n [System.IO.Path]::GetFileName($__cursorFile).ToLowerInvariant() -notin @(${bn([".gitignore",".editorconfig"])})) { return $false }\n if ($null -eq $__cursorWas -or $__cursorWas.Count -lt 2) { return $true }\n $__cursorHead = $__cursorWas.Head\n if ($__cursorWas.Count -ge 3 -and $__cursorHead[0] -eq 0xEF -and $__cursorHead[1] -eq 0xBB -and $__cursorHead[2] -eq 0xBF) { return $false }\n if (($__cursorHead[0] -eq 0xFF -and $__cursorHead[1] -eq 0xFE) -or ($__cursorHead[0] -eq 0xFE -and $__cursorHead[1] -eq 0xFF)) { return $false }\n if ($__cursorWas.Count -ge 4 -and $__cursorHead[0] -eq 0 -and $__cursorHead[1] -eq 0 -and $__cursorHead[2] -eq 0xFE -and $__cursorHead[3] -eq 0xFF) { return $false }\n return $true\n }\n # Takes a UTF-8 BOM off the front of the file in place, unless it is to stay and the\n # content has a character beyond ASCII. A file the cmdlet left as it was is not touched.\n $__cursorStripBom = {\n param([string]$__cursorFile, [bool]$__cursorKeepUnlessAscii, $__cursorWas)\n if (-not [System.IO.File]::Exists($__cursorFile)) { return }\n $__cursorStream = $null\n # The cmdlet may still hold the file for a moment after it returns.\n for ($__cursorAttempt = 0; $__cursorAttempt -lt 5 -and $null -eq $__cursorStream; $__cursorAttempt++) {\n try { $__cursorStream = [System.IO.File]::Open($__cursorFile, [System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None) }\n catch [System.IO.FileNotFoundException] { return }\n catch [System.IO.DirectoryNotFoundException] { return }\n catch [System.IO.IOException] { Start-Sleep -Milliseconds 20 }\n catch { return }\n }\n if ($null -eq $__cursorStream) { return }\n try {\n $__cursorBuffer = New-Object byte[] 65536\n if ($null -ne $__cursorWas -and $__cursorWas.Length -eq $__cursorStream.Length) {\n $__cursorCount = 0\n while ($__cursorCount -lt $__cursorWas.Count) {\n $__cursorRead = $__cursorStream.Read($__cursorBuffer, $__cursorCount, $__cursorWas.Count - $__cursorCount)\n if ($__cursorRead -le 0) { break }\n $__cursorCount += $__cursorRead\n }\n if ($__cursorCount -eq $__cursorWas.Count -and [System.Convert]::ToBase64String($__cursorBuffer, 0, $__cursorCount) -eq [System.Convert]::ToBase64String($__cursorWas.Head, 0, $__cursorCount)) { return }\n $__cursorStream.Position = 0\n }\n if ($__cursorStream.Read($__cursorBuffer, 0, 3) -ne 3 -or $__cursorBuffer[0] -ne 0xEF -or $__cursorBuffer[1] -ne 0xBB -or $__cursorBuffer[2] -ne 0xBF) { return }\n if ($__cursorKeepUnlessAscii) {\n while (($__cursorRead = $__cursorStream.Read($__cursorBuffer, 0, $__cursorBuffer.Length)) -gt 0) {\n if ([regex]::IsMatch([System.Text.Encoding]::UTF8.GetString($__cursorBuffer, 0, $__cursorRead), '[^\\x00-\\x7F]')) { return }\n }\n }\n $__cursorReadAt = 3L\n $__cursorWriteAt = 0L\n while ($__cursorReadAt -lt $__cursorStream.Length) {\n $__cursorStream.Position = $__cursorReadAt\n $__cursorRead = $__cursorStream.Read($__cursorBuffer, 0, $__cursorBuffer.Length)\n if ($__cursorRead -le 0) { break }\n $__cursorStream.Position = $__cursorWriteAt\n $__cursorStream.Write($__cursorBuffer, 0, $__cursorRead)\n $__cursorReadAt += $__cursorRead\n $__cursorWriteAt += $__cursorRead\n }\n $__cursorStream.SetLength($__cursorWriteAt)\n } catch { } finally { $__cursorStream.Dispose() }\n }\n try {\n $__cursorBound = $null\n if ($PSBoundParameters.ContainsKey('Path')) { $__cursorBound = @{ Path = $PSBoundParameters['Path'] } }\n elseif ($PSBoundParameters.ContainsKey('LiteralPath')) { $__cursorBound = @{ LiteralPath = $PSBoundParameters['LiteralPath'] } }\n if ($null -ne $__cursorBound) {\n # The file system paths that -Path or -LiteralPath names; none when one is on another\n # provider or a wildcard matches nothing.\n $__cursorLiteral = $__cursorBound.ContainsKey('LiteralPath')\n $__cursorFiles = New-Object System.Collections.Generic.List[string]\n foreach ($__cursorPath in @(@($__cursorBound.Values)[0])) {\n $__cursorProvider = $null\n $__cursorDrive = $null\n if ($__cursorLiteral -or -not [System.Management.Automation.WildcardPattern]::ContainsWildcardCharacters("$__cursorPath")) {\n $__cursorResolved = @($ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath("$__cursorPath", [ref]$__cursorProvider, [ref]$__cursorDrive))\n } else {\n $__cursorResolved = @($ExecutionContext.SessionState.Path.GetResolvedProviderPathFromPSPath("$__cursorPath", [ref]$__cursorProvider))\n }\n if ($null -ne $__cursorProvider -and $__cursorProvider.Name -in @('Variable', 'Function', 'Alias')) { $__cursorScopeBound = $__cursorProvider.Name }\n if ($null -eq $__cursorProvider -or $__cursorProvider.Name -ne 'FileSystem' -or $__cursorResolved.Count -eq 0) { $__cursorFiles = $null; break }\n $__cursorFiles.AddRange([string[]]$__cursorResolved)\n }\n }\n # -WhatIf sets $WhatIfPreference and -Confirm sets $ConfirmPreference in this scope.\n if ($null -ne $__cursorFiles -and $__cursorFiles.Count -gt 0 -and -not $PSBoundParameters.ContainsKey('Encoding') -and\n -not $WhatIfPreference -and $ConfirmPreference -notin @('Low', 'Medium') -and -not $PSBoundParameters.ContainsKey('Stream') -and\n -not $PSBoundParameters.ContainsKey('Filter') -and -not $PSBoundParameters.ContainsKey('Include') -and\n -not $PSBoundParameters.ContainsKey('Exclude')) {\n $__cursorAppend = ($PSBoundParameters.ContainsKey('Append') -and $PSBoundParameters['Append']) -or ($PSBoundParameters.ContainsKey('NoClobber') -and $PSBoundParameters['NoClobber'])\n $__cursorDecided = $true\n $__cursorStrip = $true\n foreach ($__cursorFile in $__cursorFiles) {\n $__cursorBefore[$__cursorFile] = & $__cursorHeadOf $__cursorFile\n $__cursorDecisions[$__cursorFile] = & $__cursorEncodingOf $__cursorFile $__cursorBefore[$__cursorFile]\n if ($null -eq $__cursorDecisions[$__cursorFile]) { $__cursorDecided = $false; break }\n # An append onto a file with content writes no BOM, so there is none to take off.\n if ($__cursorAppend -and $null -ne $__cursorBefore[$__cursorFile] -and $__cursorBefore[$__cursorFile].Length -gt 0) { $__cursorStrip = $false }\n }\n }\n elseif ($null -ne $__cursorFiles -and $__cursorFiles.Count -gt 0 -and $PSBoundParameters.ContainsKey('Encoding') -and\n (& $__cursorIsUtf8Bom $PSBoundParameters['Encoding']) -and -not (& $__cursorHasEncodingDefault $__cursorInvoked) -and\n -not $WhatIfPreference -and $ConfirmPreference -notin @('Low', 'Medium') -and -not $PSBoundParameters.ContainsKey('Stream') -and\n -not $PSBoundParameters.ContainsKey('Filter') -and -not $PSBoundParameters.ContainsKey('Include') -and\n -not $PSBoundParameters.ContainsKey('Exclude')) {\n # The UTF8 the command line asked for is UTF-8 with a BOM on this shell and without\n # one on PowerShell 7. For a file whose reader rejects a BOM, and that has none, it\n # means what it means there: the cmdlet writes its BOM, and the proxy takes it off.\n $__cursorAsked = $true\n foreach ($__cursorFile in $__cursorFiles) {\n $__cursorBefore[$__cursorFile] = & $__cursorHeadOf $__cursorFile\n if (-not (& $__cursorTakesNoBom $__cursorFile $__cursorBefore[$__cursorFile])) { $__cursorAsked = $false; break }\n $__cursorDecisions[$__cursorFile] = 'nobom'\n }\n $__cursorStrip = $__cursorAsked\n }\n } catch { $__cursorDecided = $false; $__cursorAsked = $false }\n if ($__cursorDecided) { $PSBoundParameters['Encoding'] = '__CURSORUTF8__' }\n if ($null -ne $__cursorScopeBound) {\n Write-Warning "__CURSORNAME__ runs through a function in this shell, so an item it writes to the $__cursorScopeBound provider lives in a scope that ends with the call. Use an assignment, a function definition or Set-Alias instead."\n }\n # An error the caller asked to stop on ends the caller too, as it does from the cmdlet: it\n # goes on as it is, as from the proxy PowerShell itself generates, which rethrows everything\n # with 'throw'. Any other terminating error of the cmdlet ends the statement and the caller\n # goes on; ThrowTerminatingError keeps that rule, where 'throw' would end the caller's whole\n # script, and the pipeline it ended is not stepped again. Of the two, only the cmdlet's own\n # terminating error names this function rather than the cmdlet's type in the suffix of its\n # FullyQualifiedErrorId; the record of an error the caller asked to stop on is the cmdlet's.\n try {\n $outBuffer = $null\n if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 }\n $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('__CURSORTARGET__', [System.Management.Automation.CommandTypes]::Cmdlet)\n $scriptCmd = { & $wrappedCmd @PSBoundParameters }\n $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)\n $steppablePipeline.Begin($PSCmdlet)\n } catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n}\nprocess {\n if ($__cursorStopped) { return }\n try { $steppablePipeline.Process($_) }\n catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n}\nend {\n if ($__cursorStopped) { return }\n try { $steppablePipeline.End() }\n catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n if (-not $__cursorStrip -or -not ($__cursorDecided -or $__cursorAsked)) { return }\n try {\n foreach ($__cursorFile in $__cursorFiles) { & $__cursorStripBom $__cursorFile ($__cursorDecisions[$__cursorFile] -eq 'bom') $__cursorBefore[$__cursorFile] }\n } catch { }\n}\n'@\n foreach ($__cursorWriter in @('Set-Content', 'Export-Csv')) {\n $__cursorWriterNames = @($__cursorWriter) + @(Get-Alias -Definition $__cursorWriter -ErrorAction Ignore | ForEach-Object { $_.Name })\n $__cursorHasWriterDefault = $false\n foreach ($__cursorKey in @($PSDefaultParameterValues.Keys)) {\n $__cursorKeyParts = "$__cursorKey" -split ':', 2\n if ($__cursorKeyParts.Count -ne 2 -or 'Encoding' -notlike $__cursorKeyParts[1].Trim()) { continue }\n foreach ($__cursorName in $__cursorWriterNames) {\n if ($__cursorName -like $__cursorKeyParts[0].Trim()) { $__cursorHasWriterDefault = $true }\n }\n }\n if ($__cursorHasWriterDefault) { continue }\n try {\n # A function of this name that a profile defined stays in charge; the proxy is built on the cmdlet alone.\n $__cursorCmdlet = @(Microsoft.PowerShell.Core\\Get-Command -Name $__cursorWriter -ErrorAction Stop)[0]\n if ($__cursorCmdlet.CommandType -eq 'Cmdlet') {\n $__cursorTarget = "$($__cursorCmdlet.ModuleName)\\$($__cursorCmdlet.Name)"\n $__cursorMetadata = New-Object System.Management.Automation.CommandMetadata $__cursorCmdlet\n $__cursorNamesList = @($__cursorWriterNames | ForEach-Object { "'" + $_.Replace("'", "''") + "'" }) -join ', '\n $__cursorProxyText = @(\n '<#', ".ForwardHelpTargetName $__cursorTarget", '.ForwardHelpCategory Cmdlet', '#>',\n [System.Management.Automation.ProxyCommand]::GetCmdletBindingAttribute($__cursorMetadata),\n 'param(', [System.Management.Automation.ProxyCommand]::GetParamBlock($__cursorMetadata), ')',\n 'dynamicparam {', [System.Management.Automation.ProxyCommand]::GetDynamicParam($__cursorMetadata), '}',\n $__cursorProxyBody.Replace('__CURSORTARGET__', $__cursorTarget).Replace('__CURSORNAMES__', $__cursorNamesList).Replace('__CURSORNAME__', $__cursorCmdlet.Name).Replace('__CURSORUTF8__', $__cursorUtf8)\n ) -join [Environment]::NewLine\n # Global, as a profile would define it, so that a module's code reaches it too.\n Microsoft.PowerShell.Management\\Set-Item -LiteralPath "function:global:$__cursorWriter" -Value ([scriptblock]::Create($__cursorProxyText)) -ErrorAction Stop\n }\n } catch { }\n }`,kn=String.raw` ++import{createRequire as e}from"node:module";const t=e(import.meta.url);export const __webpack_esm_id__=977;export const __webpack_esm_ids__=[977];export const __webpack_esm_modules__={"./src/agent/local-executor.ts"(e,t,r){r.d(t,{createLocalExecutor:()=>xH});var n=r("node:buffer"),o=r("node:os"),s=r("node:path"),i=r("../proto/dist/generated/agent/v1/agent_pb.js");const a={textDelta:(e,t)=>new i.Uq({messageStartedAtMs:t,message:{case:"textDelta",value:new i.PtE({text:e})}}),toolCallStarted:(e,t,r)=>new i.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"toolCallStarted",value:new i.xuG({callId:e,toolCall:t,modelCallId:r})}}),toolCallCompleted:(e,t,r)=>new i.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"toolCallCompleted",value:new i.LLS({callId:e,toolCall:t,modelCallId:r})}}),toolCallDelta:(e,t,r,n)=>new i.Uq({messageStartedAtMs:n,message:{case:"toolCallDelta",value:new i.I0n({callId:e,toolCallDelta:t,modelCallId:r})}}),thinkingDelta:(e,t,r)=>new i.Uq({messageStartedAtMs:r,message:{case:"thinkingDelta",value:new i.cHB({text:e,thinkingStyle:t})}}),thinkingCompleted:(e,t,r)=>new i.Uq({messageStartedAtMs:t,message:{case:"thinkingCompleted",value:new i.tr3({thinkingDurationMs:e,...!0===r?{narration:!0}:{}})}}),thinkingNote:e=>new i.Uq({message:{case:"thinkingNote",value:new i.Y$k({text:e})}}),taskChild:(e,t,r)=>"thinkingNote"===t.message.case?t:a.toolCallDelta(e,new i.V1v({delta:{case:"taskToolCallDelta",value:new i.aon({interactionUpdate:t})}}),r),userMessageAppended:e=>new i.Uq({messageStartedAtMs:e.startedAtMs,message:{case:"userMessageAppended",value:new i.v$T({userMessage:e})}}),partialToolCall:(e,t,r)=>new i.Uq({messageStartedAtMs:t.startedAtMs,message:{case:"partialToolCall",value:new i.fxF({callId:e,toolCall:t,modelCallId:r})}}),tokenDelta:e=>new i.Uq({message:{case:"tokenDelta",value:new i.Fyz({tokens:e})}}),summary:e=>new i.Uq({message:{case:"summary",value:new i.ECk({summary:e})}}),summaryStarted:()=>new i.Uq({message:{case:"summaryStarted",value:new i.lWT}}),heartbeat:()=>new i.Uq({message:{case:"heartbeat",value:new i.ih1}}),summaryCompleted:(e,t,r)=>new i.Uq({message:{case:"summaryCompleted",value:new i.ZM9({hookMessage:e,failed:t,fallback:r})}}),shellOutputDelta:e=>new i.Uq({message:{case:"shellOutputDelta",value:new i.Nn_({event:e})}}),modelCallCompleted:(e,t)=>new i.Uq({message:{case:"modelCallCompleted",value:new i.c2D({modelCallId:e,inputTokens:BigInt(t.inputTokens),outputTokens:BigInt(t.outputTokens),cacheReadTokens:BigInt(t.cacheReadTokens),cacheWriteTokens:BigInt(t.cacheWriteTokens),...void 0!==t.reasoningTokens?{reasoningTokens:BigInt(t.reasoningTokens)}:{}})}}),turnEnded(e,t){const r=e?.catalogCostCents;return new i.Uq({message:{case:"turnEnded",value:new i.lJj({...e?{inputTokens:BigInt(e.inputTokens),outputTokens:BigInt(e.outputTokens),cacheReadTokens:BigInt(e.cacheReadTokens),cacheWriteTokens:BigInt(e.cacheWriteTokens),reasoningTokens:BigInt(e.reasoningTokens??0)}:{},...void 0!==t?{endedAtMs:t}:{},...void 0!==r&&Number.isFinite(r)?{estimatedCost:new i.QVp({rawCostCents:r,chargedCents:r,source:i.nnk.CATALOG})}:{}})}})},stepStarted:e=>new i.Uq({message:{case:"stepStarted",value:new i.dwJ({stepId:BigInt(e)})}}),toolRequestsListed:e=>new i.Uq({message:{case:"toolRequestsListed",value:new i.BU$({callCount:Math.max(0,e)})}}),voiceCallUtterance:e=>new i.Uq({message:{case:"voiceCallUtterance",value:e}}),stepCompleted:(e,t)=>new i.Uq({message:{case:"stepCompleted",value:new i.Lrv({stepId:BigInt(e),stepDurationMs:BigInt(t)})}}),activeBranchChange:(e,t)=>new i.Uq({message:{case:"activeBranchChange",value:new i.PSN({path:e,branchName:t})}}),feedbackRequest:(e,t,r,n=[],o={})=>new i.Uq({message:{case:"feedbackRequest",value:new i.apn({requestId:e,canonicalModelName:t,categories:[...r],categoryGroups:[...n],title:o.title,negativeTitle:o.negativeTitle,commentPlaceholder:o.commentPlaceholder})}})};class c{constructor(e=0){this.nextId=e}next(){return this.nextId++}peekNext(){return this.nextId}observe(e){Number.isSafeInteger(e)&&e>=this.nextId&&(this.nextId=e+1)}}var l=r("../context/dist/logger.js"),u=r("../metrics/dist/index.js"),d=r("../proto/dist/generated/agent/v1/exec_pb.js"),h=r("../utils/dist/writable-iterable.js");const p=/https?:\/\/\S+/gi,f=/[)"'<>,.;:\]}]$/;function m(e){const{url:t,wrappers:r}=function(e){let t=e.length;for(;t>0&&f.test(e.slice(t-1,t));)t-=1;return{url:e.slice(0,t),wrappers:e.slice(t)}}(e),n=t.search(/[?#]/),o=-1===n?t:t.slice(0,n),s=o.indexOf("//")+2,i=o.slice(s).search(/[/?#]/),a=-1===i?o.length:s+i,c=o.lastIndexOf("@",a-1);return c0&&o.push(`gitErrorCode=${n.gitErrorCode}`),"number"==typeof n.exitCode&&Number.isFinite(n.exitCode)&&o.push(`exitCode=${n.exitCode}`),0===o.length)return e;let s=`${e} [git: ${o.join(" ")}]`;var i,a;return!0===r?.includeStderr&&"string"==typeof n.stderr&&n.stderr.length>0&&(s+=`\n--- git stderr ---\n${a=n.stderr,i=a.replace(p,m),i.length<=2048?i:`${i.slice(0,2048)}… [truncated to 2048 chars]`}`),s}var y=r("../context/dist/core.js");const v=(0,y.cF)(Symbol("machineProfile"),void 0),b=(0,l.h)("SimpleControlledExecManager"),S=(0,u.v5)("agent_exec.controlled.exec.duration_ms",{description:"Duration of controlled exec operations in milliseconds",labelNames:["exec_case"]}),k=(0,u.v5)("agent_exec.controlled.exec.machine_duration_ms",{description:"Duration of grep, shell and hook execs by coarse machine profile",labelNames:["exec_case","cpu_cores","ram_gb","defender_rt"]}),_=new Set(["grepArgs","shellStreamArgs","executeHookArgs"]),C=(0,u.Pu)("agent_exec.controlled.exec.success",{description:"Count of successful controlled exec operations",labelNames:["exec_case"]}),E=(0,u.Pu)("agent_exec.controlled.exec.error",{description:"Count of failed controlled exec operations",labelNames:["exec_case"]}),x={computerUseArgs:"Computer use is not enabled for this environment, so the Computer tool and the computerUse subagent cannot run here. Do not retry computer actions; verify with non-GUI methods (automated tests, shell commands) instead. (No computer-use handler is registered on this exec daemon.)",recordScreenArgs:"Screen recording is not enabled for this environment, so recordings cannot be captured here. Do not retry; skip the recording and present other evidence instead. (No record-screen handler is registered on this exec daemon.)"};class P extends Error{constructor(e){super(e),this.name="ControlledExecDisposedError"}}function R(e){return e instanceof P?"EXEC_BACKEND_UNAVAILABLE":e instanceof Error&&"AgentExecStreamStartTimeoutError"===e.name?"AGENT_EXEC_STREAM_START_TIMEOUT":void 0}class I{constructor(e,t,r){this.exec=e,this.deserializeArgs=t,this.serializeResult=r}handle(e,t){const r=this.deserializeArgs(t);if(void 0===r)return;const{id:n,args:o}=r;return async function*(r){const s=performance.now(),i=[],a=await r.exec.execute(e,o,{execId:t.execId,hookContextCollector:i,deliverAgentStoreConflictNotices:!0===t.acceptHookAdditionalContexts,recordAgentView:!0===t.recordAgentView,refuseUnreadChanges:!0===t.refuseUnreadChanges}),c=r.serializeResult(n,a);c.localExecutionTimeMs=Math.round(Math.max(0,performance.now()-s)),i.length>0&&(c.hookAdditionalContexts=i),yield c}(this)}}class T{constructor(e,t,r){this.exec=e,this.deserializeArgs=t,this.serializeStream=r}handle(e,t){const r=this.deserializeArgs(t);if(void 0===r)return;const{id:n,args:o}=r;return async function*(r){const s=performance.now(),i=[],a=r.exec.execute(e,o,{execId:t.execId,hookContextCollector:i,deliverAgentStoreConflictNotices:!0===t.acceptHookAdditionalContexts});try{for await(const e of a){{const __t3h=globalThis[Symbol.for("@cursor/sdk.shellStreamOutput")];const __t3c=e.event?.case;if(typeof __t3h==="function"&&(__t3c==="stdout"||__t3c==="stderr"))try{__t3h({conversationId:o.conversationId,toolCallId:o.toolCallId,event:{case:__t3c,value:{data:e.event.value.data}}})}catch{}}const t=r.serializeStream(n,e);t.localExecutionTimeMs=Math.round(Math.max(0,performance.now()-s)),yield t}}finally{const e=i.filter((e=>"agentStoreConflict"===e.hookEventName));e.length>0&&(yield new d.yT({id:n,hookAdditionalContexts:e}))}}(this)}}class A{constructor(e){this.handlers=[],this.runningExecs=new Map;const t=e?.includeGitStderrInThrows??!1;this.includeGitStderrInThrows="function"==typeof t?t:()=>t,this.observeResults=e?.observeResults}startResultObserver(e,t,r){if(void 0!==this.observeResults)try{return this.observeResults(e,t,r)}catch{return}}register(e){this.handlers.push(e)}handleControlMessage(e){if("abort"===e.message.case){const t=e.message.value.id,r=this.runningExecs.get(t);r&&r()}}handle(e,t){const[r,n]=e.withCancel();this.runningExecs.set(t.id,n);const o=t.message.case??"unknown";for(const e of this.handlers){const s=e.handle(r,t);if(void 0===s)continue;const i=s,a=(0,h.Jt)();let c;const l=()=>{c=setTimeout((()=>{a.write(new d.$Y({message:{case:"heartbeat",value:new d.VA({id:t.id})}})).then(l).catch((()=>{}))}),3e3)};l();const u=performance.now(),p=this.startResultObserver(r,o,t);return(async()=>{try{for await(const e of i){if(void 0!==p&&e instanceof d.yT)try{p.message(e)}catch{}await a.write(e)}await a.write(new d.$Y({message:{case:"streamClose",value:new d.D9({id:t.id})}})),C.increment(r,1,{exec_case:o})}catch(e){if(e instanceof h.W2)return;E.increment(r,1,{exec_case:o}),await a.write(new d.$Y({message:{case:"throw",value:new d.Fu({id:t.id,error:e instanceof Error?w(e.message,e,{includeStderr:this.includeGitStderrInThrows()}):"Unknown error",stackTrace:e instanceof Error?e.stack:void 0,errorCode:R(e)})}}))}finally{if(void 0!==p)try{p.done()}catch{}const e=performance.now()-u;if(S.histogram(r,e,{exec_case:o}),_.has(o)){const t=r.get(v)?.();void 0!==t&&k.histogram(r,e,{exec_case:o,...t})}clearTimeout(c),a.close(),this.runningExecs.delete(t.id),n()}})(),a}this.runningExecs.delete(t.id),n();const s=t.message.case,i=(void 0===s?void 0:x[s])??`No handler found for server message of type ${s}`;return b.error(e,i,{messageCase:s}),E.increment(e,1,{exec_case:o}),async function*(){yield new d.$Y({message:{case:"throw",value:new d.Fu({id:t.id,error:i})}}),yield new d.$Y({message:{case:"streamClose",value:new d.D9({id:t.id})}})}()}static fromResources(e,t){const r=new A(t);for(const[t,n]of e.entries())t.registerControlledImplementation(n,r);return r}}var $=r("../context/dist/otel.js");async function M(e){const t=e[Symbol.asyncIterator](),r=await t.next();if(r.done)return;const n={async*[Symbol.asyncIterator](){for(;;){const e=await t.next();if(e.done)return;yield e.value}}};return{firstItem:r.value,rest:n}}const D=(0,y.cF)(Symbol("agentExec.remoteExecResultObserverFactory"),void 0),O={message(){},[Symbol.dispose](){}};function F(e){const t=e.get(D);if(void 0===t)return O;let r;try{r=t(e)}catch{return O}return void 0===r?O:{message(e){try{r?.message(e)}catch{r=void 0}},[Symbol.dispose](){const e=r;r=void 0;try{e?.end()}catch{}}}}var N=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},L=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const j=(0,l.h)("ExecutorResource"),U=(0,u.Pu)("agent_exec.hook_additional_context.delivered",{description:"Hook additional_context carriers drained into the caller collector",labelNames:["hook_event_name"]});class B{constructor(e,t,r){this.execManager=e,this.serializeArgs=t,this.deserializeResult=r}async execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=N(n,(0,$.VI)(e.withName("ExecutorResource.execute")),!1),s=o.ctx;void 0!==r?.execId&&o.span.setAttribute("exec.id",r.execId);const i=(0,$.mJ)(s),a=i?new d.Kg(i):void 0,c=this.execManager.createExecInstance(s,(e=>{const n=this.serializeArgs(e,t);return new d.Ye({id:n.id,message:n.message,execId:r?.execId,machineId:r?.machineId,spanContext:a,acceptHookAdditionalContexts:void 0!==r?.hookContextCollector,recordAgentView:r?.recordAgentView,refuseUnreadChanges:r?.refuseUnreadChanges})})),l=await M(c);if(void 0===l)throw new Error("No exec result");let{firstItem:u,rest:h}=l;const p=N(n,F(s),!1),f=e=>{if(p.message(e),void 0!==r?.hookContextCollector&&e.hookAdditionalContexts.length>0){r.hookContextCollector.push(...e.hookAdditionalContexts);for(const t of e.hookAdditionalContexts)U.increment(s,1,{hook_event_name:t.hookEventName})}};f(u);let m=this.deserializeResult(u);for(;void 0===m;){const e=await M(h);if(void 0===e)throw new Error("No result value");u=e.firstItem,h=e.rest,f(u),m=this.deserializeResult(u)}return(async()=>{try{for await(const e of h)f(e)}catch(e){j.info(s,"Ignoring exec stream shutdown during detached drain",{error:e})}})().catch((()=>{})),m}catch(e){n.error=e,n.hasError=!0}finally{L(n)}}}class W{constructor(e,t,r){this.execManager=e,this.serializeArgs=t,this.deserializeStream=r}async*execute(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=N(n,(0,$.VI)(e.withName("StreamExecutorResource.execute")),!1).ctx,s=(0,$.mJ)(o),i=s?new d.Kg(s):void 0,a=this.execManager.createExecInstance(o,(e=>{const n=this.serializeArgs(e,t);return new d.Ye({id:n.id,message:n.message,execId:r?.execId,machineId:r?.machineId,spanContext:i,acceptHookAdditionalContexts:void 0!==r?.hookContextCollector||!0===r?.deliverAgentStoreConflictNotices})})),c=N(n,F(o),!1);for await(const e of a){c.message(e),void 0!==r?.hookContextCollector&&e.hookAdditionalContexts.length>0&&r.hookContextCollector.push(...e.hookAdditionalContexts);const t=this.deserializeStream(e);void 0!==t&&(yield t)}}catch(e){n.error=e,n.hasError=!0}finally{L(n)}}}function H(e){return Symbol.for(`@anysphere/agent-exec/resource/${e}`)}function q(e,t,r){return{name:e,symbol:H(e),remoteImplementation:t,registerControlledImplementation:r}}class z{constructor(e,t){this.resource=e,this.value=t}}function G(e,t){return[e,t]}function V(e,t){return t}class K{constructor(){this.resources=new Map}register(e,t){this.resources.set(e.symbol,new z(e,t))}get(e){return V(0,this.resources.get(e.symbol)?.value)}entries(){return Array.from(this.resources.values()).map((e=>[e.resource,e.value]))}}class J{constructor(e,t){this.remoteAccessor=e,this.localResources=new Map;for(const[e,r]of t)this.localResources.set(e.symbol,{resource:e,implementation:r})}get(e){const t=this.localResources.get(e.symbol);return t?V(0,t.implementation):this.remoteAccessor.get(e)}*entries(){for(const{resource:e,implementation:t}of this.localResources.values())yield[e,t];for(const e of this.remoteAccessor.entries())this.localResources.has(e[0].symbol)||(yield e)}}function Z(e){return function(t,r){return new d.Ye({id:t,message:{case:e,value:r}})}}function X(e){return t=>{if(t.message.case===e)return t.message.value}}function Q(e){return function(t,r){const n={case:e,value:r};return new d.yT({id:t,message:n})}}function Y(e){return function(t){if(t.message.case===e)return{id:t.id,args:t.message.value}}}const ee=q("shell-stream-executor",(e=>new W(e,Z("shellStreamArgs"),X("shellStream"))),((e,t)=>{t.register(new T(e,Y("shellStreamArgs"),Q("shellStream")))}));var te=r("../proto/dist/generated/agent/v1/kv_pb.js"),re=r("../agent-kv/dist/blob-store.js"),ne=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const oe=(0,l.h)("ControlledKvManager");function se(e,t,r){return e?(0,$.F)({traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags??1},t,r):r}function ie(e,t,r,n,o){o<=r||(0,$.xd)(e.withName(`${t}.slow`),{startTime:n,attributes:{durationMs:o,slowThresholdMs:r}},n+o)}const ae=(0,u.v5)("agent_kv.controlled.get_blob.duration_ms",{description:"Duration of ControlledKvManager getBlob operations in milliseconds"}),ce=(0,u.v5)("agent_kv.controlled.set_blob.duration_ms",{description:"Duration of ControlledKvManager setBlob operations in milliseconds"});class le{constructor(e,t,r,n={}){this.serverStream=e,this.clientStream=t,this.blobStore=r,this.options=n}async run(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,$.VI)(e.withName("ControlledKvManager.run")),!1).ctx,n=new Set,o=e=>{n.add(e),e.finally((()=>{n.delete(e)}))};try{for await(const e of this.serverStream){const t=performance.now(),n=Date.now();switch(e.message.case){case"getBlobArgs":{const s=e.message.value.blobId;o((async()=>{const o=se(e.spanContext,"ControlledKvManager.getBlob",r);try{await(this.options.beforeGetBlob?.(o,s));const t=await this.blobStore.getBlob(o,s);await this.clientStream.write(new te.gm({id:e.id,message:{case:"getBlobResult",value:{blobData:t?(0,re.Fo)(t):void 0}}}))}catch(t){oe.error(o,"Error handling getBlob",t);const r=t instanceof Error?t.message:String(t);try{await this.clientStream.write(new te.gm({id:e.id,message:{case:"getBlobResult",value:{blobData:void 0,error:{message:r}}}}))}catch(e){oe.error(o,"Error writing failed getBlobResult",e)}}finally{const e=performance.now()-t;ae.histogram(o,e),ie(o,"ControlledKvManager.getBlob",50,n,e)}})());break}case"setBlobArgs":{const s=e.message.value.blobId,i=e.message.value.blobData;o((async()=>{const o=se(e.spanContext,"ControlledKvManager.setBlob",r);try{await this.blobStore.setBlob(o,s,i),await this.clientStream.write(new te.gm({id:e.id,message:{case:"setBlobResult",value:{error:void 0}}}))}catch(t){const r=t instanceof Error?t.message:String(t);try{await this.clientStream.write(new te.gm({id:e.id,message:{case:"setBlobResult",value:{error:{message:r}}}}))}catch(e){oe.error(o,"Error writing setBlobResult",e)}}finally{const e=performance.now()-t;ce.histogram(o,e),ie(o,"ControlledKvManager.setBlob",100,n,e)}})());break}}}}finally{await Promise.allSettled(n)}}catch(e){t.error=e,t.hasError=!0}finally{ne(t)}}}function ue(e){return e instanceof Error?{abortReasonType:"error",abortReasonName:e.name,abortReasonMessage:e.message}:"string"==typeof e?{abortReasonType:"string",abortReasonMessage:e}:void 0===e?{abortReasonType:"undefined"}:{abortReasonType:typeof e}}var de=r("../proto/dist/generated/agent/v1/agent_service_pb.js"),he=r("../proto/dist/generated/agent/v1/shell_exec_pb.js");Error;const pe={stateRestoreMs:"client_prep_state_restore_ms",rootPromptRestoreMs:"client_prep_root_prompt_restore_ms",requestContextMs:"client_prep_request_context_ms",systemPromptMs:"client_prep_system_prompt_ms",preTurnSnapshotMs:"client_prep_pre_turn_snapshot_ms",preTurnSnapshotWaitMs:"client_prep_pre_turn_snapshot_wait_ms",preTurnSnapshotBlobWritesMs:"client_prep_pre_turn_snapshot_blob_writes_ms",preTurnSnapshotSerializeMs:"client_prep_pre_turn_snapshot_serialize_ms",firstStepToFirstInvocationMs:"client_prep_first_step_to_first_invocation_ms",promptMessageCount:"client_prep_prompt_message_count",turnCount:"client_prep_turn_count"},fe=Object.keys(pe).filter((e=>e in pe));function me(e){const t={};for(const r of fe){const n=e[r];void 0!==n&&(t[r]=n)}return t}new WeakMap;var ge=r("../utils/dist/fresh-uuid.js"),we=r("@bufbuild/protobuf"),ye=r("@connectrpc/connect"),ve=r("../../node_modules/.pnpm/@connectrpc+connect@1.6.1_patch_hash=c9c7616ccfc0246b19c6537f56676d8501713cb6c94b440d13_c9bdc997d82622067cc922804d7b4f50/node_modules/@connectrpc/connect/dist/esm/protocol/async-iterable.js"),be=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class Se{constructor(e,t,r){this.checkpointStream=e,this.checkpointHandler=t,this.ctx=r}async run(){const e={stack:[],error:void 0,hasError:!1};try{const t=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(e,(0,$.VI)(this.ctx.withName("CheckpointController.run")),!1).ctx,r=[];for await(const e of this.checkpointStream){let n;try{n=this.checkpointHandler.handleCheckpoint(t,e.checkpoint,e.metadata)}catch(t){throw e.onSettled?.(),t}r.push(n),void 0!==e.onSettled&&n.then(e.onSettled,e.onSettled)}await Promise.all(r)}catch(t){e.error=t,e.hasError=!0}finally{be(e)}}}const ke=(0,l.h)("@anysphere/agent-client:checkpoint-store-waits");class _e{constructor(e={}){this.options=e,this.inFlight=new Map}noteRouted(e){const t=Ee(e.pendingToolCalls);if(0===t.size)return Ce;let r;const n=new Promise((e=>{r=e}));for(const e of t){let t=this.inFlight.get(e);void 0===t&&(t=new Set,this.inFlight.set(e,t)),t.add(n)}return()=>{for(const e of t){const t=this.inFlight.get(e);t?.delete(n),0===t?.size&&this.inFlight.delete(e)}r()}}storedBefore(e,t){const r=this.inFlight.get(t);if(void 0!==r){try{this.options.onExecHeld?.(t)}catch(t){ke.warn(e,"onExecHeldForCheckpointStore callback failed",{error:String(t)})}return Promise.all(r).then(Ce)}}}function Ce(){}function Ee(e){const t=new Set;for(const r of e){let e;try{e=JSON.parse(r)}catch{continue}const n=Pe(e)?e.content:void 0;if(!Array.isArray(n))continue;const o=n;for(const e of o)Pe(e)&&"tool-call"===e.type&&"string"==typeof e.toolCallId&&t.add(e.toolCallId)}return t}function xe(e){if("executeHookArgs"===e.message.case)return function(e){const t=e.request?.request;switch(t?.case){case"preToolUse":case"postToolUse":case"postToolUseFailure":return""===t.value.toolUseId?void 0:t.value.toolUseId;case"subagentStart":return""===t.value.toolCallId?void 0:t.value.toolCallId;default:return}}(e.message.value);const t=e.message.value;return Pe(t)&&"string"==typeof t.toolCallId&&""!==t.toolCallId?t.toolCallId:void 0}function Pe(e){return"object"==typeof e&&null!==e}const Re=(0,l.h)("@anysphere/agent-client:exec-checkpoint-gate"),Ie=new Set(["shellArgs","shellStreamArgs","backgroundShellSpawnArgs","forceBackgroundShellArgs","miniSweAgentBashArgs","writeArgs","deleteArgs","mcpArgs","readMcpResourceExecArgs","computerUseArgs","recordScreenArgs","subagentArgs","forceBackgroundSubagentArgs","executeHookArgs"]),Te=new Set(["userMessageAction","resumeAction","backgroundTaskCompletionAction","goalContinuationAction","subscriptionNotificationAction","executePlanAction","asyncAskQuestionCompletionAction"]);function Ae(e){const t=e.message.case;return void 0!==t&&Ie.has(t)?xe(e):void 0}const $e=e=>e.replace(/[\r\n]/g,"");function Me(e){return{...void 0!==e.parentRequestId?{"x-parent-request-id":$e(e.parentRequestId)}:{},...void 0!==e.rootParentRequestId?{"x-root-parent-request-id":$e(e.rootParentRequestId)}:{},...void 0!==e.parentAgentToolCallId?{"x-parent-agent-tool-call-id":$e(e.parentAgentToolCallId)}:{},...!0===e.directMetaParentChildSubagent?{"x-direct-meta-parent-child-subagent":"true"}:{}}}const De="x-inference-authentication-jwt";function Oe(){const e=globalThis.process?.env,t=e?.INFERENCE_PROXY_JWT?.trim();return void 0===t||""===t||t.startsWith("$")?{}:{[De]:t}}class Fe extends Error{constructor(e,t){super(`This conversation's data is missing and can't be restored. Start a new chat to continue.${function(e){if(0===e.length)return"";const t=e.slice(0,3).map((e=>e.slice(0,12)));return` (${1===e.length?`missing blob ${t[0]}`:`${e.length} missing blobs: ${t.join(", ")}${e.length>t.length?", …":""}`})`}(e)}`,void 0!==t?.cause?{cause:t.cause}:void 0),this.isUsageError=!0,this.isBlobNotFound=!0,this.name="BlobNotFoundError",this.blobIdHexes=[...e]}}function Ne(e){return e instanceof Error&&(e instanceof Fe||"isBlobNotFound"in e&&!0===e.isBlobNotFound||"BlobNotFoundError"===e.name)}var Le=r("../proto/dist/generated/aiserver/v1/utils_pb.js"),je=r("zod/v4");const Ue="relayedAttemptFailure",Be=je.object({transport:je.boolean(),stallAborted:je.boolean(),errorName:je.string(),connectCode:je.number().optional(),connectCodeName:je.string().optional(),connectCause:je.object({code:je.union([je.string(),je.number()]).optional(),name:je.string().optional()}).optional(),transportFailureKind:je.string().optional(),loop:je.string().optional(),transportMode:je.string().optional()});function We(e){const t=e?.details?.additionalInfo[Ue];if(void 0!==t)try{const e=Be.safeParse(JSON.parse(t));return e.success?e.data:void 0}catch{return}}class He extends Error{constructor(e,t={}){super(e),Object.setPrototypeOf(this,new.target.prototype),this.cause=t.cause,this.requestId=t.requestId,this.displayInfo=t.displayInfo,this.isTransport=t.isTransport}get name(){return this.kind}}class qe extends He{get kind(){return"RetriableError"}}class ze extends He{constructor(e,t,r={}){super(e,r),this.action=t}get kind(){return"ActionRequiredError"}}class Ge extends He{get kind(){return"NonRetriableError"}}class Ve extends Ge{constructor(e){const t=`This turn's step limit (${e}) needs an in-process agent loop; the network client cannot send it.`;super(t,{displayInfo:{title:"Step limit not supported",detail:t,isRetryable:!1}}),this.maxSteps=e}}class Ke extends He{get kind(){return"CancelledError"}}const Je=new Set([Le.yM.NOT_LOGGED_IN,Le.yM.AGENT_REQUIRES_LOGIN,Le.yM.AUTH_TOKEN_NOT_FOUND,Le.yM.AUTH_TOKEN_EXPIRED,Le.yM.INVALID_AUTH_ID,Le.yM.UNAUTHORIZED,Le.yM.GITHUB_NO_USER_CREDENTIALS,Le.yM.GITHUB_USER_NO_ACCESS]),Ze=new Set([Le.yM.FREE_USER_USAGE_LIMIT,Le.yM.FREE_USER_RATE_LIMIT_EXCEEDED,Le.yM.PRO_USER_ONLY,Le.yM.PRO_USER_USAGE_LIMIT,Le.yM.PRO_USER_RATE_LIMIT_EXCEEDED,Le.yM.RATE_LIMITED,Le.yM.RATE_LIMITED_CHANGEABLE,Le.yM.GENERIC_RATE_LIMIT_EXCEEDED]),Xe=new Set([Le.yM.USAGE_PRICING_REQUIRED,Le.yM.USAGE_PRICING_REQUIRED_CHANGEABLE]),Qe=new Set([Le.yM.BAD_API_KEY,Le.yM.BAD_USER_API_KEY,Le.yM.OUTDATED_CLIENT]),Ye=new Set([Le.yM.USER_ABORTED_REQUEST,Le.yM.DEBOUNCED]),et=new Set([Le.yM.CUSTOM_MESSAGE]),tt=new Map([[ye.Code.PermissionDenied,"Permission Denied"]]),rt=["NGHTTP2","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE","socket hang up","Premature close","UND_ERR_SOCKET","ERR_STREAM","protocol error","http/2 stream","ERR_HTTP2_SESSION_ERROR","Session closed with error code","connection aborted","PING timed out","HTTP/2 session not established","HTTP/2 peer not answering","refused to tunnel to","HTTP CONNECT through proxy","Could not connect to proxy"],nt=new Set(["ENOTFOUND","EAI_AGAIN","EAI_FAIL","ENODATA","ESERVFAIL","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ECONNABORTED"]),ot=new RegExp(`\\b(${[...nt].join("|")})\\b`),st=["IMAGE_TOO_LARGE","MAX_TOKENS","CONVERSATION_TOO_LONG","CONTENT_POLICY","DEPRECATED","MAX_MODE_REQUIRED","MODEL_NO_LONGER_SUPPORTED","UNSUPPORTED_REGION","OUTDATED_CLIENT"],it="x-cursor-inference-request-error-type",at="AgentWebSocketDeliveryAmbiguousError";function ct(e,t={}){const{requestId:r}=t;if(e instanceof He)return e;if(lt(e))return function(e,t){const r=dt(e),n=r.code,o=ht(e),s=void 0===o?void 0:function(e){if(void 0===e.details?.additionalInfo[Ue])return e;const t=e.clone();return void 0!==t.details&&(delete t.details.additionalInfo[Ue],t.details.equals(new Le.ej)&&(t.details=void 0)),t}(o),i={title:s?.details?.title,detail:s?.details?.detail,isRetryable:s?.details?.isRetryable,connectCode:n,errorCode:s?.error,inferenceRequestErrorType:pt(r,it)??pt(e,it),errorDetails:s},a={cause:e,requestId:t,displayInfo:i,...!0===We(o)?.transport?{isTransport:!0}:{}};if(n===ye.Code.Canceled||n===ye.Code.Aborted)return bt(e)?new qe(e.message,a):new Ke(e.message,a);if(void 0!==s?.error){const t=s.error;if(Ye.has(t))return new Ke(wt(e,s),a);const r=s.details?.analyticsMetadata?.actionRequired;if(void 0!==r&&""!==r)return new ze(wt(e,s),r,a);if(void 0!==At(s))return new qe(wt(e,s),a);if(Je.has(t))return new ze(wt(e,s),"login",a);if(Ze.has(t))return new ze(wt(e,s),"upgrade",a);if(Xe.has(t))return new ze(wt(e,s),"payment",a);if(Qe.has(t))return new ze(wt(e,s),"config",a);if(et.has(t)&&!0!==s.details?.isRetryable)return new Ge(wt(e,s),a);if(!1===s.details?.isRetryable)return new Ge(wt(e,s),a)}if(n===ye.Code.Unauthenticated)return new ze(e.message,"login",{...a,displayInfo:ut(i,"Sign in required",r)});const c=gt(r);if(Rt.test(c))return new ze(e.message,"proxy_sign_in",{...a,displayInfo:{...i,title:"Proxy sign-in required",detail:`${c}. Please check your sign-in for this proxy and try again.`,isRetryable:!0}});if(It.test(c))return new ze(e.message,"proxy_blocked",{...a,displayInfo:{...i,title:"Connection blocked by proxy",detail:`${c}. Your proxy doesn't allow this connection. Please ask your network administrator to allow it and try again.`,isRetryable:!0}});const l=tt.get(n);return void 0===l||!0===s?.details?.isRetryable||bt(e)?new qe(e.message,a):new Ge(wt(e,s),{...a,displayInfo:ut(i,l,r)})}(e,r);const n=function(e){let t=e;for(let e=0;e<10;e++){if(null==t)return;if(Ne(t))return t;if("object"!=typeof t||!("cause"in t))return;t=t.cause}}(e);if(void 0!==n)return new Ge(n.message,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Conversation data missing",detail:n.message,isRetryable:!1}});const o=function(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){if(r.name===yt)return r;t.add(r),r=r.cause}}(e);if(void 0!==o)return new Ge(o.message,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Context summarization failed",detail:o.message,isRetryable:!1}});if(function(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){const e="code"in r?r.code:void 0,n="errcode"in r?r.errcode:void 0;if("ENOSPC"===e||"ERR_SQLITE_ERROR"===e&&"number"==typeof n&&13==(255&n))return!0;t.add(r),r=r.cause}return!1}(e))return new Ge(vt,{cause:e instanceof Error?e:void 0,requestId:r,displayInfo:{title:"Out of disk space",detail:vt,isRetryable:!1}});if(e instanceof Error){if("AbortError"===e.name)return new Ke(e.message,{cause:e,requestId:r});if(e.name===at)return new qe(e.message,{cause:e,requestId:r,isTransport:!0});if(bt(e))return new qe(e.message,{cause:e,requestId:r})}const s=e instanceof Error?e.message:String(e);return new qe(s,{cause:e instanceof Error?e:void 0,requestId:r})}function lt(e){return null!==e&&"object"==typeof e&&"code"in e&&"name"in e&&("ConnectError"===e.name||"rawMessage"in e&&"string"==typeof e.rawMessage&&"details"in e&&Array.isArray(e.details)&&"findDetails"in e&&"function"==typeof e.findDetails)}function ut(e,t,r){return{...e,title:e.title||t,detail:e.detail||gt(r),isRetryable:e.isRetryable??!1}}function dt(e){let t=e;for(let e=0;e<10&&t.code===ye.Code.Unknown;e++){const e=t.cause;if(!lt(e))break;t=e}return t}function ht(e){let t=e;for(let e=0;e<10&<(t);e++){try{const e=t.findDetails?.(Le.vj);if(void 0!==e&&e.length>0)return e[0]}catch{}t=t.cause}}function pt(e,t){const r=e.metadata;if(null===r||"object"!=typeof r||!("get"in r)||"function"!=typeof r.get)return;const n=r.get(t);return"string"==typeof n?n:void 0}function ft(e){let t=e;for(let e=0;e<10&&"object"==typeof t&&null!==t;e++){if(lt(t))return t;t="cause"in t?t.cause:void 0}}function mt(e){const t=ft(e);return void 0===t?void 0:dt(t)}function gt(e){const t=e.rawMessage;return"string"==typeof t?t:e.message.replace(/^\[[a-z_]+\] /,"")}function wt(e,t){if(t?.details){const{title:r,detail:n}=t.details;return r&&n?`${r} ${n}`:r||n||e.message}return e.message}const yt="SummaryPlaceholderRejectedError",vt="Out of disk space. Free some space and try again.";function bt(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){t.add(r);const e=`${r.name}: ${r.message}`;if(rt.some((t=>e.includes(t)))||ot.test(e))return!0;const n=r.code;if("string"==typeof n&&(rt.some((e=>n.includes(e)))||nt.has(n)))return!0;r=r.cause}return!1}function St(e){return rt.some((t=>e.includes(t)))||ot.test(e)}function kt(e){return e instanceof He&&e.cause instanceof Error?bt(e.cause):e instanceof Error?bt(e):"string"==typeof e&&St(e)}function _t(e){return void 0!==e&&e>0}function Ct(e){return e+1}function Et(e){return Object.defineProperty(e,"code",{value:"connection_stalled",enumerable:!0,configurable:!0}),e}function xt(e){const{cause:t,requestId:r,transportErrorRetries:n,connectCode:o}=e;return _t(n)?Et(new qe("Connection stalled repeatedly",{cause:t,requestId:r,displayInfo:{title:"Connection stalled",detail:`The connection stalled ${Ct(n)} times. Please check your network connection and try again.`,isRetryable:!0,connectCode:o}})):Et(new qe("Connection stalled",{cause:t,requestId:r,displayInfo:{title:"Connection stalled",detail:"The connection stalled. Please try again.",isRetryable:!0,connectCode:o}}))}const Pt=/^(?:Proxy \S+ refused to tunnel to |HTTP CONNECT through proxy \S+ failed: |Could not connect to proxy \S+: )/,Rt=/^Proxy \S+ refused to tunnel to \S+: 407\b/,It=/^Proxy \S+ refused to tunnel to \S+: 403\b/;function Tt(e){let t=e.cause;for(let e=0;e<10&&void 0!==t;e++){if(t instanceof Error&&"AbortError"===t.name)return!0;if(lt(t)&&(t.code===ye.Code.Canceled||t.code===ye.Code.Aborted))return!0;t=null!==t&&"object"==typeof t&&"cause"in t?t.cause:void 0}return!1}function At(e){const t=e?.details?.additionalInfo;if(e?.error!==Le.yM.RATE_LIMITED||"run_inference_novel_tokens"!==t?.kind||void 0===t.retryAfterMs)return;const r=Number(t.retryAfterMs);return Number.isFinite(r)&&r>=0?r:void 0}var $t=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Mt=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Dt=(0,l.h)("@anysphere/agent-client:exec-controller");class Ot extends Error{constructor(e){super(e),this.name="LostConnection"}}class Ft{constructor(e,t,r,n){this.serverStream=e,this.clientStream=t,this.controlledExecManager=r,this.checkpointStoreWaits=n}async run(e){const t={stack:[],error:void 0,hasError:!1};try{$t(t,(0,$.VI)(e.withName("ClientExecController.run")),!1);const r=[],n=t=>{if((0,we.isMessage)(t,d.Nv))this.controlledExecManager.handleControlMessage(t);else{const n=this.execute(e,t);n.catch((()=>{})),r.push(n)}};let o,s,i=!1;try{try{for await(const t of this.serverStream){const r=(0,we.isMessage)(t,d.Nv)?void 0:xe(t),a=void 0===r?void 0:this.checkpointStoreWaits?.storedBefore(e,r);if(void 0===o&&void 0===a){n(t);continue}const c=(o??Promise.resolve()).then((async()=>{await a,(0,we.isMessage)(t,d.Nv)||!i&&!e.canceled?n(t):Dt.info(e,"Dropped an exec queued behind a checkpoint's store",{toolCallId:r})})).catch((e=>{s??={error:e}}));o=c,c.then((()=>{o===c&&(o=void 0)}))}}finally{i=!0}if(await o,void 0!==s)throw s.error;await Promise.all(r)}catch(e){if(e instanceof ye.ConnectError&&"protocol error: missing EndStreamResponse"===e.rawMessage)throw new Ot(e.message);if(e instanceof ye.ConnectError&&e.code===ye.Code.Aborted){const t=e.cause;if(t instanceof Error&&"code"in t&&"string"==typeof t.code&&t.code.includes("ERR_STREAM_WRITE_AFTER_END"))throw new Ot(e.message)}else{if(e instanceof h.W2)throw new Ot(e.message);if(e instanceof ye.ConnectError&&e.code===ye.Code.Internal){const t=e.cause;if(t instanceof Error&&t.message.includes("NGHTTP2_PROTOCOL_ERROR"))throw new Ot(e.message)}}throw e}}catch(e){t.error=e,t.hasError=!0}finally{Mt(t)}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{let n,o;if(t.spanContext){const r=t.spanContext;n=(0,$.V5)({traceId:r.traceId,spanId:r.spanId,traceFlags:r.traceFlags??1},"exec.handle",e),o=(0,$.fU)(n)}else n=e;$t(r,o?new $.r2(n,o):void 0,!1);const s=this.controlledExecManager.handle(n,t);for await(const e of s)await this.clientStream.write(e)}catch(e){r.error=e,r.hasError=!0}finally{Mt(r)}}}const Nt=(0,l.h)("@anysphere/agent-client:stall-detector"),Lt=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,jt={nal:"[NAL client stall detector]",local_loop:"[local-loop client stall detector]",module:"[module client stall detector]"},Ut=new Set(["http2","http1_sse","http1_poll","websocket"]);function Bt(e){return void 0===e?"unknown":Ut.has(e)?e:"other"}const Wt=(0,u.Pu)("agent_client.stream.stall.count",{description:"Number of bidirectional stream stalls detected",labelNames:["activity_type","message_type","loop","transport_mode"]}),Ht=(0,u.v5)("agent_client.stream.stall.duration_ms",{description:"Duration of stream stalls in milliseconds",labelNames:["activity_type","loop","transport_mode"]}),qt=(0,u.Pu)("agent_client.stream.did_stall",{description:"Number of streams that experienced at least one stall",labelNames:["loop","transport_mode"]}),zt=(0,u.Pu)("agent_client.stream.total",{description:"Total number of streams monitored",labelNames:["loop","transport_mode"]});class Gt{constructor(){this.handlers=new Map}track(e,t){return this.handlers.set(e,{name:e,state:"started",startedAt:Date.now()}),t.then((t=>{const r=this.handlers.get(e);return r&&(r.state="completed",r.endedAt=Date.now()),t})).catch((t=>{const r=this.handlers.get(e);throw r&&(r.state="errored",r.endedAt=Date.now(),r.error=t instanceof Error?t.message:String(t)),t}))}getHandlerStates(){const e=Date.now(),t={};for(const[r,n]of this.handlers)t[r]={state:n.state,durationMs:(n.endedAt??e)-n.startedAt,error:n.error};return t}}class Vt{constructor(e,t,r){this.lastActivityTime=performance.now(),this.lastMeaningfulActivityTime=performance.now(),this.hasLogged=!1,this.hasLoggedAdvisory=!1,this.hasLoggedHeartbeatOnly=!1,this.hasEverStalled=!1,this.paused=!1,this.disposed=!1,this.activityHistory=[],this.ctx=e,"number"==typeof t?(this.thresholdMs=t,this.advisoryThresholdMs=void 0,this.heartbeatOnlyThresholdMs=3*t,this.onStall=r,this.onStallCallback=void 0,this.handlerTracker=void 0,this.loop="nal",this.readTransportMode=void 0):(this.thresholdMs=t.thresholdMs,this.advisoryThresholdMs=t.advisoryThresholdMs,this.heartbeatOnlyThresholdMs=t.heartbeatOnlyThresholdMs??3*t.thresholdMs,this.onStall=t.onStall,this.onStallCallback=t.onStallCallback,this.handlerTracker=t.handlerTracker,this.loop=t.loop??"nal",this.readTransportMode=t.transportMode),this.logPrefix=jt[this.loop],this.startTimer(),this.startAdvisoryTimer(),this.startHeartbeatOnlyTimer(),this.onCtxSignalAbort=()=>{this.trackActivity("ctx.signal","abort"),this.abortedAt=performance.now(),this.emitLifecycleLog(`${this.logPrefix} Stream aborted while stall detector active`,"aborted")},e.signal.addEventListener("abort",this.onCtxSignalAbort)}metricLabels(){return{loop:this.loop,transport_mode:Bt(this.readTransportMode?.())}}trackActivity(e,t){const r={type:e,messageType:t};this.lastActivity=r,"inbound_message"===e?this.lastInboundMessage=r:"outbound_write"===e&&(this.lastOutboundMessage=r);const n=this.activityHistory.at(-1);n?.type===e&&n.messageType===t?n.repeat=(n.repeat??1)+1:(this.activityHistory.push(r),this.activityHistory.length>10&&this.activityHistory.shift())}reset(e="inbound_message",t,r=!0){if(this.trackActivity(e,t),"inbound_message"===e){const e=this.hasLogged,t=this.hasLoggedAdvisory,n=this.hasLoggedHeartbeatOnly;e&&(this.hasLogged=!1,this.emitLogAndMetric()),n&&r&&(this.hasLoggedHeartbeatOnly=!1),t&&(this.hasLoggedAdvisory=!1),this.lastActivityTime=performance.now(),r&&(this.lastMeaningfulActivityTime=performance.now()),void 0===this.timer&&this.startTimer(),void 0===this.advisoryTimer&&this.startAdvisoryTimer(),r&&void 0===this.heartbeatOnlyTimer&&this.startHeartbeatOnlyTimer()}}onStreamEnded(){this.trackActivity("stream","ended"),this.streamEndedAt=performance.now()}onClientSentHeartbeat(){this.lastClientSentHeartbeatAt=performance.now()}onServerSentHeartbeat(){this.lastServerSentHeartbeatAt=performance.now()}setPaused(e){if(!this.disposed&&e!==this.paused&&(this.paused=e,!e)){const e=performance.now();this.lastActivityTime=e,this.lastMeaningfulActivityTime=e,void 0===this.timer&&this.startTimer(),void 0===this.advisoryTimer&&this.startAdvisoryTimer(),void 0===this.heartbeatOnlyTimer&&this.startHeartbeatOnlyTimer()}}restartedAfterLoopGap(e,t){const r=performance.now(),n=r-e;return!(n<5e3||t>=e||(this.reportLoopGap(n,r-t),this.lastActivityTime=r,this.lastMeaningfulActivityTime=r,0))}reportLoopGap(e,t){try{Nt.info(this.ctx,`${this.logPrefix} Stall check ran late - the process was not running, its windows restart`,this.buildLogMetadata({late_ms:e,window_ms:t,stall_type:"loop_gap"}))}catch(e){console.error("Error in stall detection:",e)}}startTimer(){if(this.disposed||this.thresholdMs<=0||void 0!==this.timer)return;let e=0;const t=t=>{e=performance.now()+t,this.timer=setTimeout(r,t)},r=()=>{if(this.paused||this.restartedAfterLoopGap(e,this.lastActivityTime))return void t(this.thresholdMs);const r=this.thresholdMs-(performance.now()-this.lastActivityTime);if(r<=0)return this.timer=void 0,void this.onStallDetected("no_activity");t(r)};t(this.thresholdMs)}startAdvisoryTimer(){if(this.disposed||void 0===this.advisoryThresholdMs||this.advisoryThresholdMs<=0||void 0!==this.advisoryTimer)return;const e=this.advisoryThresholdMs;let t=0;const r=e=>{t=performance.now()+e,this.advisoryTimer=setTimeout(n,e)},n=()=>{if(this.paused||this.restartedAfterLoopGap(t,this.lastActivityTime))return void r(e);const n=e-(performance.now()-this.lastActivityTime);if(n<=0)return this.advisoryTimer=void 0,void this.onAdvisoryDetected();r(n)};r(e)}startHeartbeatOnlyTimer(){if(this.disposed||this.thresholdMs<=0||this.heartbeatOnlyThresholdMs<=0||void 0!==this.heartbeatOnlyTimer)return;let e=0;const t=t=>{e=performance.now()+t,this.heartbeatOnlyTimer=setTimeout(r,t)},r=()=>{if(this.paused||this.restartedAfterLoopGap(e,this.lastMeaningfulActivityTime))return void t(this.heartbeatOnlyThresholdMs);const r=this.heartbeatOnlyThresholdMs-(performance.now()-this.lastMeaningfulActivityTime);if(r<=0)return this.heartbeatOnlyTimer=void 0,void this.onStallDetected("heartbeat_only");t(r)};t(this.heartbeatOnlyThresholdMs)}buildLogMetadata(e){const t=this.ctx.get(Mn),r={...e};t?.modelDetails?.displayName&&(r.model_name=t.modelDetails.displayName);const n=performance.now();void 0!==this.abortedAt&&(r.aborted_ago_ms=n-this.abortedAt),void 0!==this.disposedAt&&(r.disposed_ago_ms=n-this.disposedAt),void 0!==this.lastClientSentHeartbeatAt&&(r.last_client_sent_heartbeat_ago_ms=n-this.lastClientSentHeartbeatAt),void 0!==this.lastServerSentHeartbeatAt&&(r.last_server_sent_heartbeat_ago_ms=n-this.lastServerSentHeartbeatAt),void 0!==this.streamEndedAt&&(r.stream_ended_ago_ms=n-this.streamEndedAt),this.lastInboundMessage&&(r.last_inbound_message_type=this.lastInboundMessage.messageType),this.lastOutboundMessage&&(r.last_outbound_message_type=this.lastOutboundMessage.messageType);const o=[];let s;for(let e=this.activityHistory.length-1;e>=0;e--){const{type:t,messageType:r,repeat:n}=this.activityHistory[e];s!==t&&(s?o.push(`[${t}]`):o.push(`[${t}] (MOST RECENT)`),s=t),o.push(`${r}${n?` (x${n})`:""}`)}return r.activities=o.join("\n"),{reqId:t?.requestId,loop:this.loop,stall:r}}onAdvisoryDetected(){if(this.hasLogged||this.hasLoggedAdvisory)return;if(void 0===this.advisoryThresholdMs||this.advisoryThresholdMs<=0)return;const e=performance.now()-this.lastActivityTime;e=this.heartbeatOnlyThresholdMs){if(this.hasLoggedHeartbeatOnly)return;this.hasLoggedHeartbeatOnly=!0,this.reportStall(e,n)}return}if(this.hasLogged)return;this.hasLogged=!0,this.hasLoggedAdvisory=!0;const t=performance.now()-this.lastActivityTime;this.reportStall(e,t)}reportStall(e,t){const r=this.lastActivity,n=this.lastInboundMessage,o=this.lastOutboundMessage,s=this.ctx.get(Mn);try{const i=this.buildLogMetadata({duration_ms:t,threshold_ms:"heartbeat_only"===e?this.heartbeatOnlyThresholdMs:this.thresholdMs,stall_type:e}),a="heartbeat_only"===e?`${this.logPrefix} Stream receiving heartbeats only - no meaningful data for threshold period`:`${this.logPrefix} Bidirectional stream stall detected - no activity for threshold period`;if(Nt.warn(this.ctx,a,i),Wt.increment(this.ctx,1,{activity_type:r?.type??"unknown",message_type:r?.messageType??"unknown",...this.metricLabels()}),this.hasEverStalled||(this.hasEverStalled=!0,qt.increment(this.ctx,1,this.metricLabels())),this.onStallCallback){const t=performance.now(),i={type:e,lastActivityAgoMs:t-this.lastActivityTime,lastMeaningfulActivityAgoMs:t-this.lastMeaningfulActivityTime,lastActivityType:r?.messageType,lastInboundMessageType:n?.messageType,lastOutboundMessageType:o?.messageType,requestId:s?.requestId,modelName:s?.modelDetails?.displayName,streamEnded:void 0!==this.streamEndedAt,aborted:void 0!==this.abortedAt,lastServerHeartbeatAgoMs:void 0!==this.lastServerSentHeartbeatAt?t-this.lastServerSentHeartbeatAt:void 0,lastClientHeartbeatAgoMs:void 0!==this.lastClientSentHeartbeatAt?t-this.lastClientSentHeartbeatAt:void 0,thresholdMs:"heartbeat_only"===e?this.heartbeatOnlyThresholdMs:this.thresholdMs,handlers:this.handlerTracker?.getHandlerStates(),loop:this.loop};try{this.onStallCallback(i)}catch(e){console.error("Error in stall callback:",e)}}}catch(e){console.error("Error in stall detection:",e)}try{this.onStall?.(function(e){const t=new DOMException(`the stall detector cut the stream: ${e}`,"AbortError");return Object.defineProperty(t,"cursorStallCut",{value:!0}),t}("heartbeat_only"===e?`heartbeats alone for ${this.heartbeatOnlyThresholdMs} ms`:`no activity for ${this.thresholdMs} ms`))}catch(e){console.error("Error in onStall callback:",e)}}emitLifecycleLog(e,t){const r=performance.now()-this.lastActivityTime;try{const n=this.buildLogMetadata({duration_ms:r,event_type:t});Nt.info(this.ctx,e,n)}catch(e){console.error("Error logging stream lifecycle:",e)}}emitLogAndMetric(){const e=performance.now()-this.lastActivityTime;this.emitLifecycleLog(`${this.logPrefix} Stream activity resumed after stall`,"recovered"),Ht.histogram(this.ctx,e,{activity_type:this.lastActivity?.type??"unknown",...this.metricLabels()})}[Symbol.dispose](){this.disposed||zt.increment(this.ctx,1,this.metricLabels()),this.disposed=!0,this.paused=!1,void 0!==this.timer&&(clearTimeout(this.timer),this.timer=void 0),void 0!==this.advisoryTimer&&(clearTimeout(this.advisoryTimer),this.advisoryTimer=void 0),void 0!==this.heartbeatOnlyTimer&&(clearTimeout(this.heartbeatOnlyTimer),this.heartbeatOnlyTimer=void 0),this.ctx.signal.removeEventListener("abort",this.onCtxSignalAbort),this.trackActivity("disposed","disposed"),this.disposedAt=performance.now(),this.emitLifecycleLog(`${this.logPrefix} Stream stall detector disposed`,"disposed")}}const Kt={now:()=>performance.now(),setTimeout(e,t){const r=setTimeout(e,t);return r.unref?.(),r},clearTimeout(e){clearTimeout(e)}},Jt=(0,u.v5)("agent_client.first_message.event_loop_max_lag_ms",{description:"Longest event-loop block between the network phase start and the first server message of a run's first attempt",labelNames:["loop","transport_mode","first_message_slow"]}),Zt=(0,u.v5)("agent_client.first_message.event_loop_total_lag_ms",{description:"Summed event-loop blocking between the network phase start and the first server message of a run's first attempt",labelNames:["loop","transport_mode","first_message_slow"]}),Xt=(0,u.v5)("agent_client.first_message.network_ms",{description:"Time from the network phase start to the first server message of a run's first attempt, on attempts that sampled event-loop lag",labelNames:["loop","transport_mode","first_message_slow"]});var Qt=r("../proto/dist/generated/agent/v1/ask_question_tool_pb.js"),Yt=r("../proto/dist/generated/agent/v1/create_plan_tool_pb.js"),er=r("../proto/dist/generated/agent/v1/pr_management_tool_pb.js"),tr=r("../proto/dist/generated/agent/v1/replace_env_tool_pb.js"),rr=r("../proto/dist/generated/agent/v1/setup_vm_environment_tool_pb.js"),nr=r("../proto/dist/generated/agent/v1/connect_scm_tool_pb.js"),or=r("../proto/dist/generated/agent/v1/generate_image_tool_pb.js"),sr=r("../proto/dist/generated/agent/v1/mcp_auth_tool_pb.js"),ir=r("../proto/dist/generated/agent/v1/switch_mode_tool_pb.js"),ar=r("../proto/dist/generated/agent/v1/web_fetch_tool_pb.js"),cr=r("../proto/dist/generated/agent/v1/web_search_tool_pb.js");class lr extends Error{constructor(e){super(`Deferred interaction response requested for query ${e.id} (${e.query.case??"unknown"})`),this.query=e,this.name="DeferredInteractionResponseError",Object.setPrototypeOf(this,new.target.prototype)}}const ur=e=>new i.Y5({id:e,result:{case:"webSearchRequestResponse",value:new cr.lI({result:{case:"approved",value:new cr.XJ}})}}),dr=(e,t)=>new i.Y5({id:e,result:{case:"webSearchRequestResponse",value:new cr.lI({result:{case:"rejected",value:new cr.yc({reason:t??""})}})}}),hr=e=>new i.Y5({id:e,result:{case:"webFetchRequestResponse",value:new ar.fS({result:{case:"approved",value:new ar.Hs}})}}),pr=(e,t)=>new i.Y5({id:e,result:{case:"webFetchRequestResponse",value:new ar.fS({result:{case:"rejected",value:new ar.m$({reason:t??""})}})}}),fr=(e,t)=>new i.Y5({id:e,result:{case:"askQuestionInteractionResponse",value:new i.zT({result:t})}}),mr=e=>new i.Y5({id:e,result:{case:"switchModeRequestResponse",value:new ir.w$({result:{case:"approved",value:new ir.q5}})}}),gr=(e,t)=>new i.Y5({id:e,result:{case:"switchModeRequestResponse",value:new ir.w$({result:{case:"rejected",value:new ir.rA({reason:t??""})}})}}),wr=(e,t)=>new i.Y5({id:e,result:{case:"createPlanRequestResponse",value:new Yt.gz({result:t})}}),yr=(e,t)=>new i.Y5({id:e,result:{case:"setupVmEnvironmentResult",value:t}}),vr=(e,t)=>new i.Y5({id:e,result:{case:"replaceEnvResult",value:t}}),br=(e,t)=>new i.Y5({id:e,result:{case:"prManagementResult",value:t}}),Sr=e=>new i.Y5({id:e,result:{case:"mcpAuthRequestResponse",value:new sr.h({result:{case:"approved",value:new sr.D5}})}}),kr=(e,t)=>new i.Y5({id:e,result:{case:"mcpAuthRequestResponse",value:new sr.h({result:{case:"rejected",value:new sr.OI({reason:t??"Authentication was rejected"})}})}}),_r=(e,t)=>new i.Y5({id:e,result:{case:"connectScmRequestResponse",value:new nr.qG({result:{case:"rejected",value:new nr.lB({reason:t??"Connecting GitHub was skipped"})}})}}),Cr=(e,t)=>new i.Y5({id:e,result:{case:"generateImageRequestResponse",value:new or.vW({result:{case:"approved",value:new or.l3({description:t??""})}})}}),Er=(e,t)=>new i.Y5({id:e,result:{case:"generateImageRequestResponse",value:new or.vW({result:{case:"rejected",value:new or.Uq({reason:t??""})}})}});class xr extends Error{constructor(e,t={}){super(e),this.name="InteractionListenerStreamClosedError",this.cause=t.cause,Object.setPrototypeOf(this,new.target.prototype)}}xr.telemetryName="InteractionListenerStreamClosedError";var Pr=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Rr=(0,l.h)("ClientInteractionController"),Ir=new Set(["askQuestionInteractionQuery","switchModeRequestQuery","mcpAuthRequestQuery","connectScmRequestQuery"]);class Tr{constructor(e,t,r,n){this.interactionStream=e,this.interactionListener=t,this.queryResponseStream=r,this.stallSuspender=n,this.pendingHumanQueries=0}async run(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,$.VI)(e.withName("ClientInteractionController.run")),!1);e=r.ctx;let n,o=Promise.resolve();for await(const t of this.interactionStream){const r=()=>"interactionQuery"===t.case?this.handleInteractionQuery(e,t.value):this.handleInteractionUpdate(e,t.value);o=o.then(r).catch((r=>{Rr.error(e,"Error handling interaction message",r,{messageCase:t.case}),n??=r}))}if(await o,void 0!==n)throw n}catch(e){t.error=e,t.hasError=!0}finally{Pr(t)}}async handleInteractionUpdate(e,t){await this.interactionListener.sendUpdate(e,t)}handleInteractionQuery(e,t){const r=void 0!==t.query.case&&Ir.has(t.query.case);let n=!1;const o=()=>{r&&!n&&(n=!0,this.pendingHumanQueries--,0===this.pendingHumanQueries&&this.stallSuspender?.setPaused(!1))};r&&(this.pendingHumanQueries++,1===this.pendingHumanQueries&&this.stallSuspender?.setPaused(!0)),(async()=>this.interactionListener.query(e,t))().catch((r=>{const n=function(e,t){switch(e.query.case){case"webSearchRequestQuery":return dr(e.id,t);case"webFetchRequestQuery":return pr(e.id,t);case"askQuestionInteractionQuery":return fr(e.id,new Qt.tz({result:{case:"rejected",value:new Qt.ox({reason:t})}}));case"switchModeRequestQuery":return gr(e.id,t);case"createPlanRequestQuery":return wr(e.id,new Yt.bK({result:{case:"error",value:new Yt.iY({error:t})}}));case"setupVmEnvironmentArgs":return yr(e.id,new rr.r$({result:{case:"success",value:new rr.JH({})}}));case"replaceEnvArgs":return vr(e.id,new tr.dV({result:{case:"failure",value:new tr.uq({errorMessage:t,setupLogs:""})}}));case"prManagementRequestQuery":return br(e.id,new er.HL({result:{case:"error",value:new er.K$({error:t})}}));case"mcpAuthRequestQuery":return kr(e.id,t);case"connectScmRequestQuery":return _r(e.id,t);case"generateImageRequestQuery":return Er(e.id,t);case void 0:return;default:return e.query}}(t,"The client could not show this request to the user");if(!(n instanceof i.Y5))throw r;return Rr.error(e,"Error handling interaction query; answering with a fail-closed response",{queryCase:t.query.case,error:r}),n})).then((e=>(o(),this.queryResponseStream.write(e)))).catch((t=>{Rr.error(e,"Error handling interaction query",t)})).finally(o)}}async function Ar(e,t){let r;try{r=await e(t.signal)}catch(e){if(t.isCanceled())throw new Ke("User aborted request");throw new Ge("Failed to mint LLM Gateway credential",{cause:e instanceof Error?e:void 0,requestId:t.requestId})}if(void 0===r)throw new Ge("LLM Gateway credential minter returned no credential",{requestId:t.requestId});if(""===r.bearerToken.trim())throw new Ge("LLM Gateway credential minter returned an empty bearer token",{requestId:t.requestId});return new i.Ibo({bearerToken:r.bearerToken})}const $r=q("request-context-executor",(e=>new B(e,Z("requestContextArgs"),X("requestContextResult"))),((e,t)=>{t.register(new I(e,Y("requestContextArgs"),Q("requestContextResult")))}));var Mr=r("../agent-kv/dist/serde.js"),Dr=r("../proto/dist/generated/agent/v1/request_context_exec_pb.js"),Or=r("../utils/dist/promise-extras.js");const Fr=15728640,Nr=(0,u.Pu)("agent_client.request_context_blob.prepared",{description:"Prepared RequestContext blob references"}),Lr=(0,u.v5)("agent_client.request_context_blob.bytes",{description:"Serialized RequestContext bytes staged by the client"}),jr=(0,u.v5)("agent_client.request_context_blob.preparation_ms",{description:"Time to hydrate, serialize, and hash RequestContext"});function Ur(e){switch(e.action.case){case"userMessageAction":case"subscriptionNotificationAction":case"resumeAction":case"executePlanAction":return e.action.value;default:return}}class Br{constructor(e,t=62914560){this.parent=e,this.maxTransientBytes=t,this.transientBlobs=new Map,this.persistedBlobIds=new Set,this.transientBytes=0}seed(e,t){return this.seedAll([{blobId:e,blobData:t}])}seedAll(e){const t=new Map;for(const{blobId:r,blobData:n}of e)t.set((0,Mr.nj)(r),n.byteLength);let r=this.transientBytes;for(const[e,n]of t)r-=this.transientBlobs.get(e)?.byteLength??0,r+=n;if(r>this.maxTransientBytes)return!1;for(const{blobId:t,blobData:r}of e)this.transientBlobs.set((0,Mr.nj)(t),r);return this.transientBytes=r,!0}has(e){return this.transientBlobs.has((0,Mr.nj)(e))}hasAll(e){return e.every((e=>this.has(e)))}async getBlob(e,t){const r=(0,Mr.nj)(t),n=this.transientBlobs.get(r);return void 0===n?await this.parent.getBlob(e,t):n}async persistForRemoteRead(e,t){const r=(0,Mr.nj)(t),n=this.transientBlobs.get(r);void 0===n||this.persistedBlobIds.has(r)||(await(0,Or.O$)((()=>this.parent.setBlob(e,t,n)),2),this.persistedBlobIds.add(r))}async setBlob(e,t,r){await this.parent.setBlob(e,t,r)}async setBlobLocallyOnly(e,t,r){await this.parent.setBlobLocallyOnly(e,t,r)}async flush(e){await this.parent.flush(e)}}async function Wr({ctx:e,action:t,resources:r,blobStore:n,mode:o,maxBlobBytes:s,maxInlineDynamicBytes:i=1048576,notesSessionId:a}){const c=performance.now(),l=Ur(t);if(void 0===l)return{kind:"not_applicable"};if("legacy"===o)return t.requestContextParts=void 0,{kind:"legacy"};if(void 0!==t.requestContextParts){const e=void 0===(u=t.requestContextParts)?[]:[u.rulesBlobId,u.skillsBlobId,u.subagentsBlobId,u.mcpsBlobId],r=void 0!==l.requestContext,s=e.length>0&&n.hasAll(e);if(r||s){const e=t.requestContextParts;return"ref_only"===o&&r&&s&&void 0!==e?.dynamicContext&&(l.requestContext=void 0),{kind:"already_prepared"}}}var u;t.requestContextParts=void 0;const d=void 0===l.requestContext,h=l.requestContext??await async function({ctx:e,resources:t,notesSessionId:r}){const n=t.get($r),o=await n.execute(e,new Dr._K({notesSessionId:r})),s="success"===o.result.case?o.result.value.requestContext:void 0;if(void 0===s)throw new Error(`Failed to compute request context: ${o.result.case}`);return s}({ctx:e,resources:r,notesSessionId:a}),p=Math.min(Math.max(0,s),Fr),f=await async function({requestContext:e,mode:t,maxBlobBytes:r,maxInlineDynamicBytes:n}){const o=function(e){const t=e.clone();return t.rules=[],t.nonFileRules=[],t.cloudRule=void 0,t.agentSkills=[],t.skillOptions=void 0,t.customSubagents=[],t.tools=[],t.mcpInstructions=[],t.mcpFileSystemOptions=void 0,t.mcpMetaToolOptions=void 0,{dynamicContext:t,rules:new Dr.T3({rules:e.rules.map((e=>e.clone())),nonFileRules:e.nonFileRules.map((e=>e.clone())),cloudRule:e.cloudRule}),skills:new Dr.CB({agentSkills:e.agentSkills.map((e=>e.clone())),skillOptions:e.skillOptions?.clone()}),subagents:new Dr.yb({customSubagents:e.customSubagents.map((e=>e.clone()))}),mcps:new Dr.vB({tools:e.tools.map((e=>e.clone())),mcpInstructions:e.mcpInstructions.map((e=>e.clone())),mcpFileSystemOptions:e.mcpFileSystemOptions?.clone(),mcpMetaToolOptions:e.mcpMetaToolOptions?.clone()})}}(e),s="ref_only"===t?o.dynamicContext.toBinary().byteLength:void 0;if(void 0!==s&&s>n)return;const i=o.rules.toBinary(),a=o.skills.toBinary(),c=o.subagents.toBinary(),l=o.mcps.toBinary(),u=i.byteLength+a.byteLength+c.byteLength+l.byteLength;if(u>r)return;const[d,h,p,f]=await Promise.all([(0,re.Bk)(i),(0,re.Bk)(a),(0,re.Bk)(c),(0,re.Bk)(l)]),m=[{blobId:d,blobData:i},{blobId:h,blobData:a},{blobId:p,blobData:c},{blobId:f,blobData:l}],g=new Dr.sG({rulesBlobId:d,rulesByteLength:i.byteLength,skillsBlobId:h,skillsByteLength:a.byteLength,subagentsBlobId:p,subagentsByteLength:c.byteLength,mcpsBlobId:f,mcpsByteLength:l.byteLength,dynamicContext:"ref_only"===t?o.dynamicContext:void 0});if("dual"===t)return{kind:"dual",inlineContext:e,byteLength:u,parts:g};if(void 0===s)throw new Error("ref_only request context did not measure dynamic bytes");return{kind:"ref_only",stagedBlobs:m,byteLength:u,parts:g,dynamicByteLength:s}}({requestContext:h,mode:o,maxBlobBytes:p,maxInlineDynamicBytes:Math.min(Math.max(0,i),p)});if(void 0===f)return l.requestContext=h,t.requestContextParts=void 0,Nr.increment(e,1,{mode:o,outcome:"oversized"}),{kind:"oversized"};if("ref_only"===f.kind&&!n.seedAll(f.stagedBlobs))return l.requestContext=h,t.requestContextParts=void 0,Nr.increment(e,1,{mode:o,outcome:"transient_budget_exceeded"}),{kind:"transient_budget_exceeded"};l.requestContext="dual"===f.kind?f.inlineContext:void 0,t.requestContextParts=f.parts;const m=f.byteLength;return Nr.increment(e,1,{mode:o,outcome:d?"hydrated":"inline"}),Lr.histogram(e,m,{mode:o}),jr.histogram(e,performance.now()-c,{mode:o}),{kind:"prepared",byteLength:m,hydrated:d,rulesByteLength:f.parts.rulesByteLength,skillsByteLength:f.parts.skillsByteLength,subagentsByteLength:f.parts.subagentsByteLength,mcpsByteLength:f.parts.mcpsByteLength,dynamicByteLength:"ref_only"===f.kind?f.dynamicByteLength:void 0}}function Hr(e){return Object.keys(e.fileContents).length>0}function qr(e,t){return Object.assign(new(e.getType()),e,t)}function zr(e){return qr(e,{fileContents:{}})}function Gr(e){for(const[t]of e.entries())if(t.symbol===$r.symbol)return e.get($r)}var Vr=r("../proto/dist/generated/agent/v1/cursor_rules_pb.js");const Kr=102400;function Jr(e){return"AGENTS.md"===e||"CLAUDE.md"===e||"CLAUDE.local.md"===e}function Zr({content:e,filename:t}){return Buffer.byteLength(e,"utf8")>Kr?function({content:e,filename:t}){const r=Buffer.from(e,"utf8");let n=Kr;for(;128==(192&r.readUInt8(n));)n--;const o=`[truncated: ${t} is ${Math.round(r.length/1024)} KB; only the first 100 KB is included]`;return`${r.subarray(0,n).toString("utf8")}\n\n${o}`}({content:e,filename:t}):e}function Xr(e){const t=/^\s*("(?:[^"\\]|\\.)*"|'(?:[^']|'')*')\s+#/.exec(e);return null!==t?t[1]:/^\s*["']/.test(e)?e.trim():e.replace(/\s#.*$/,"").trim()}function Qr(e,t){return"description"===e?t.trim():Xr(t)}function Yr(e){const t=e.trim();return"true"===t||"false"!==t&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t)}function en(e){const t=e.trimStart();if(!t.startsWith("---"))return null;const r=t.split("---").filter(Boolean);if(r.length<2)return null;const n=r[0].trim(),o=r.slice(1).join("---").trim(),s={};let i=null,a=null;for(const e of n.split("\n")){const t=e.replace(/\r$/,"");if(/^\s*#/.test(t))continue;const r=t.match(/^\s+-\s+(.*)$/);if(r&&a){let e=Xr(r[1]);(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1));const t=s[a];Array.isArray(t)&&t.push(e);continue}const n=t.startsWith(" ")||t.startsWith("\t");if(i&&n){const e=t.trim(),r=e.indexOf(":");if(-1===r)continue;const n=e.slice(0,r).trim(),o=Xr(e.slice(r+1)),c=Yr(o),l=`${i}.${n}`;""===o?(s[l]=[],a=l):"metadata.environments"===l||"metadata.disabledEnvironments"===l||"metadata.scopedTo"===l?(s[l]=String(c).split(",").map((e=>e.trim())).filter(Boolean),a=null):(s[l]=c,a=null);continue}i=null,a=null;const o=t.indexOf(":");if(-1===o)continue;const c=t.slice(0,o).trim(),l=Qr(c,t.slice(o+1));if(""===l&&"metadata"===c){i=c;continue}if("globs"===c&&""===l){s.globs=[],a="globs";continue}const u=Yr(l);s[c]="metadata.environments"!==c&&"metadata.disabledEnvironments"!==c&&"metadata.scopedTo"!==c?u:String(u).split(",").map((e=>e.trim())).filter(Boolean)}return{frontmatter:s,rawFrontmatter:`---\n${n}\n---`,body:o}}function tn(e){const t=e.replace(/\\/g,"/").replace(/^[A-Za-z]:/,(e=>e.toLowerCase())),r=[];for(const e of t.split("/"))""!==e&&"."!==e&&(".."!==e?r.push(e):r.pop());return`${t.startsWith("/")?"/":""}${r.join("/")}`}function rn(e,t){return"/"===t?e.length>1:e.startsWith(`${t}/`)}const nn=[[".cursor","skills"],[".cursor","skills-cursor"],[".claude","skills"],[".claude","plugins"],[".codex","skills"],[".grok","skills"],[".agents","skills"],[".cursor","plugins"]];class on{constructor(){this.allowed=!1}observeHeaders(e){this.allowed="1"===e.get("x-cursor-lazy-rule-bodies")}isAllowed(){return this.allowed}}function sn(e){if("success"!==e.result.case)return e;const t=e.result.value,r=t.requestContext;if(void 0===r)return e;const n=function(e){const t=e.env?.workspacePaths??[];let r=!1;const n=e.rules.map((e=>{if(!function(e,t){if(!0===e.bodyOmitted||0===e.content.length||void 0!==e.parseError||e.source!==Vr.gv.UNSPECIFIED||void 0!==e.plugin||void 0!==e.marketplace||void 0!==e.pluginId||void 0!==e.marketplaceId)return!1;if(0===e.scopedTo.length&&0===e.frontmatter.length&&e.content.trimStart().startsWith("---"))return!1;const r=tn(e.fullPath),n=r.startsWith("/"),o=r.split("/").filter((e=>e.length>0)),s=o.at(-1);if(void 0===s||function(e){return"SKILL.md"===e.at(-1)||e.some(((t,r)=>nn.some((([n,o])=>t===n&&e[r+1]===o))))}(o))return!1;const i=t.map(tn);if(!i.some((e=>rn(r,e))))return!1;const a=function(e,t){let r=e.length-1;for(let t=e.length-2;t>=0;t--)if(".cursor"===e[t]&&"rules"===e[t+1]){r=t;break}return`${t?"/":""}${e.slice(0,r).join("/")}`}(o,n),c=a!==`${n?"/":""}${o.slice(0,-1).join("/")}`,l=e.type?.type.case;return"fileGlobbed"===l?s.endsWith(".mdc")&&c:"global"===l&&!!(Jr(s)||s.endsWith(".mdc")&&c)&&!i.includes(a)&&i.some((e=>rn(a,e)))}(e,t))return e;r=!0;const n=Object.assign(new(e.getType()),e);return n.content=e.content.split("\n").find((e=>e.trim().length>0))??"",n.bodyOmitted=!0,n}));return r?Object.assign(new(e.getType()),e,{rules:n}):e}(r);return n===r?e:new Dr._G({result:{case:"success",value:Object.assign(new(t.getType()),t,{requestContext:n})}})}function an(e){return void 0!==e&&Number.isFinite(e)&&Number.isInteger(e)}function cn(e,t){const{rulesByteLength:r,skillsByteLength:n}=e,{subagentsByteLength:o,mcpsByteLength:s}=e;if(!(an(r)&&an(n)&&an(o)&&an(s)))return;const i=t?.dynamicByteLength;return{bytes:r+n+o+s+(i??0),bytesSource:"blob_parts",rulesBytes:r,skillsBytes:n,mcpBytes:s,subagentsBytes:o,...an(i)?{dynamicBytes:i}:{}}}const ln=["alpn_failure","poll_seqno_gap","append_fatal","http_464","http_404_unimplemented","socket_reset","stream_closed_early","idle_deadline","stall","other"],un=/\bHTTP (\d{3})\b/;function dn(e){const t=e.message;return"string"==typeof t?t:""}function hn(e){return e instanceof Error&&("AbortError"===e.name||e.name===at)}const pn={serverCap:3,transportCap:10},fn={alpn_failure:"server",poll_seqno_gap:"server",append_fatal:"by_signature",http_464:"server",http_404_unimplemented:"server",socket_reset:"transport",stream_closed_early:"server",idle_deadline:"server",stall:"transport",other:"server"};function mn(e){return{action:"retry",countAsServerError:!0,countAsTransportError:!1,transportFailureKind:e}}function gn(e,t,r){const n=r.attemptRequestId,o=!0===t.endless,s=r.retriesEnabled||o,i=(e,n)=>!o&&(e>=n||void 0!==t.sharedCap&&r.serverErrorRetries+r.transportErrorRetries>=t.sharedCap);let a=e instanceof He?e:ct(e,{requestId:n});const c=a instanceof Ke&&("owner"===r.abortOrigin||function(e){const t=e.displayInfo?.errorCode;return void 0!==t&&Ye.has(t)}(a)),l="stall_detector"===r.abortOrigin&&!c&&(a instanceof Ke||a instanceof qe),u="owner"===r.abortOrigin&&a instanceof qe&&Tt(a),d=function(e,t,r){return t.stalled?"stall":t.userStop?"other":function(e,t={}){const r=function(e){const t=[],r=new Set;let n=e;for(;"object"==typeof n&&null!==n&&!r.has(n);)r.add(n),t.push(n),n="cause"in n?n.cause:void 0;return t}(e);if(r.some((e=>"cursorBidiAppendFatal"in e)))return"append_fatal";const n=r.map(dn),o=e=>n.some((t=>t.includes(e))),s=function(e){return mt(e)?.code}(e),i=void 0===t.transportMode;if(i&&s===ye.Code.Unavailable&&o("ALPN protocol failed to negotiate"))return"alpn_failure";if((i||"http1_poll"===t.transportMode)&&s===ye.Code.Unavailable&&o("Unexpected seqno"))return"poll_seqno_gap";const a=n.map((e=>un.exec(e)?.[1])).find((e=>void 0!==e));return i&&s===ye.Code.Unknown&&"464"===a?"http_464":i&&s===ye.Code.Unimplemented&&"404"===a?"http_404_unimplemented":s===ye.Code.DeadlineExceeded&&function(e){const t=ft(e);return void 0===t?void 0:ht(t)?.error}(e)===Le.yM.TIMEOUT?"idle_deadline":i&&s===ye.Code.Unknown&&o("unsupported content type null")?"stream_closed_early":kt(e)||function(e){return e instanceof Error&&"isTransport"in e&&!0===e.isTransport}(e)||r.some(hn)?"socket_reset":"other"}(e,r)}(e,{stalled:l,userStop:c||u},{transportMode:r.attemptTransportMode}),h=(e,t={})=>({action:"throw",error:e,...t,transportFailureKind:d}),p=(e,n,{immediateFirstRetry:o})=>s?i(r.transportErrorRetries,t.transportCap)?h(e(),{countAsTransportError:!0}):function(e,t){return{action:"retry",countAsServerError:!1,countAsTransportError:!0,transportFailureKind:e,...t?{noBackoff:!0}:{}}}(d,o&&0===r.transportErrorRetries):h(n(),{countAsTransportError:!0}),f=()=>({cause:a.cause,requestId:n,transportErrorRetries:r.transportErrorRetries,connectCode:a.displayInfo?.connectCode});if(l){if(s&&void 0!==r.stallRetryElapsedMs&&r.stallRetryElapsedMs>=18e4)return h(xt(f()),{countAsTransportError:!0});const e=p((()=>xt(f())),(()=>xt({...f(),transportErrorRetries:void 0})),{immediateFirstRetry:!1});return"retry"===e.action?{...e,stall:!0}:e}if(a instanceof Ke&&!c&&Tt(a)&&(a=new qe(a.message,{cause:a.cause,requestId:n,displayInfo:a.displayInfo,isTransport:!0})),u)return h(new Ke(a.message,{cause:a.cause,requestId:n,displayInfo:a.displayInfo}));if(!0===t.retryAllInference&&(a instanceof ze||a instanceof Ge)&&function(e){const t=e.displayInfo?.inferenceRequestErrorType;return void 0!==t&&!st.some((e=>e===t))}(a))return i(r.serverErrorRetries,t.serverCap)?h(a):mn(d);if(a instanceof Ke||a instanceof ze||a instanceof Ge)return h(a);const m=function(e){return At(e.displayInfo?.errorDetails)}(a);if(a instanceof qe&&void 0!==m){const e=(r.rateLimitRetryElapsedMs??0)+m;return!s||!o&&e>3e5?h(a):{action:"retry",countAsServerError:!1,countAsTransportError:!1,transportFailureKind:d,retryAfterMs:m,rateLimit:!0}}if(a instanceof qe&&(!0===a.isTransport||function(e,t){const r=fn[e];return"by_signature"===r?kt(t):"transport"===r}(d,a)||"owner"!==r.abortOrigin&&Tt(a))){const e=function(e){const t=e.displayInfo,r=t?.title,n=t?.detail;return r&&n?{...t,title:r,detail:n}:void 0}(a);return p((()=>function(e){const{cause:t,requestId:r,transportErrorRetries:n,connectCode:o,ownCopy:s}=e;if(void 0!==s)return new qe(_t(n)?"Connection failed repeatedly":"Connection failed",{cause:t,requestId:r,displayInfo:{...s,isRetryable:!0,connectCode:o??s.connectCode}});const i=function(e){const t=new Set;let r=e;for(;r instanceof Error&&!t.has(r);){t.add(r);const e=lt(r)?gt(r):r.message;if(Pt.test(e))return e;r=r.cause}}(t),a=void 0===i?"Please check your network connection and try again.":"Please check your proxy settings and try again.";return _t(n)?new qe("Connection failed repeatedly",{cause:t,requestId:r,displayInfo:{title:"Connection failed",detail:`${void 0===i?"":`${i}. `}The connection failed ${Ct(n)} times. ${a}`,isRetryable:!0,connectCode:o}}):new qe("Connection failed",{cause:t,requestId:r,displayInfo:{title:"Connection failed",detail:`${i??"The connection was interrupted"}. ${a}`,isRetryable:!0,connectCode:o}})}({...f(),...void 0===e?{}:{ownCopy:e}})),(()=>a),{immediateFirstRetry:!0})}return s?i(r.serverErrorRetries,t.serverCap)?h(function(e){const{classified:t,requestId:r,serverErrorRetries:n}=e,o=t.displayInfo;return new qe(t.message,{cause:t.cause,requestId:r,displayInfo:{...o,title:o?.title||"Server error",detail:o?.detail||`The server failed ${Ct(n)} times. Please try again, or contact support if the issue persists.`,isRetryable:!0}})}({classified:a,requestId:n,serverErrorRetries:r.serverErrorRetries})):mn(d):h(a)}var wn=r("../proto/dist/generated/agent/v1/mcp_pb.js");const yn=(0,y.cF)(Symbol("agentTransportTimingRecorder"),void 0),vn=(0,l.h)("@anysphere/agent-client:turn-runner"),bn=1e3,Sn=6e4,kn=(0,u.Pu)("agent_client.turn.retry",{description:"Turn attempts retried by the turn runner",labelNames:["attempt","reason","loop"]});function _n(e){return e<=1?"1":2===e?"2":e<=5?"3_5":"gt5"}function Cn(e){return!0===e.stall?"stall":!0===e.rateLimit?"rate_limit":e.countAsTransportError?"transport":e.countAsServerError?"server":!0===e.immediate?"speculative":"other"}const En=new Set(["textDelta","thinkingDelta","thinkingCompleted","partialToolCall","toolCallDelta","toolCallStarted","toolCallCompleted","tokenDelta"]);function xn(e){const{message:t}=e;return("textDelta"!==t.case||void 0===t.value||!("isServerNotice"in t.value)||!0!==t.value.isServerNotice)&&En.has(t.case??"")}async function Pn(e,t,r){await new Promise(((n,o)=>{if(t?.aborted)return void o(new Ke("Cancelled during backoff"));const s=new AbortController,i=setTimeout(a,e);function a(){clearTimeout(i),t?.removeEventListener("abort",c),s.abort(),n()}function c(){clearTimeout(i),s.abort(),o(new Ke("Cancelled during backoff"))}t?.addEventListener("abort",c,{once:!0});try{r?.(s.signal)?.then(a,(()=>{}))}catch{}}))}function Rn(e,t){return e.length===t.length&&e.every(((e,r)=>{const n=t[r];return void 0!==n&&e.byteLength===n.byteLength&&e.every(((e,t)=>e===n[t]))}))}function In(e){const{connectCode:t,connectCodeName:r,...n}=e;return void 0===r?n:{...n,connectCode:r}}async function Tn(e){const{ctx:t,checkpointHandler:r,runOptions:n,requestId:o,hooks:s,cancellation:a}=e,c=e.originalRequestId??o;let l=bn;const u=async(r,o,s,i,a)=>{if(s||(l=bn),void 0!==e.backoff)return void await e.backoff(r,o,i.retryAfterMs);if(!0===i.rateLimit&&void 0!==i.retryAfterMs){const n=i.retryAfterMs+1e3*Math.random();return e.logging&&vn.info(t,`[${e.logging.tag}] Waiting out a rate limit`,{attempt:r,retryAfterMs:i.retryAfterMs,selectedDelayMs:n}),void await Pn(n,o)}const c=s?function(e,t){const r=Math.min(3e5,3*e);return t??bn+(r-bn)*Math.random()}(l,n.fixedRetryDelayMs):function(e,t,r){const n=t?100:bn,o=r??Math.min(n*2**e,Sn);return o+(void 0===r?.2*o*Math.random():0)}(r,n.isRunningInTest,n.fixedRetryDelayMs),u=function(e,t){if(void 0===t||t<=e)return e;const r=Math.min(t,Sn),n=Math.min(r+.2*r*Math.random(),Sn);return Math.max(e,n)}(c,i.retryAfterMs);u!==c&&e.logging&&vn.info(t,`[${e.logging.tag}] Waiting for Retry-After`,{attempt:r,retryAfterMs:i.retryAfterMs,computedDelayMs:c,selectedDelayMs:u,endlessRetries:s}),s&&(l=c,e.logging&&vn.info(t,`[${e.logging.tag}] Endless retry delay selected`,{selectedDelayMs:u,attempt:r,retryCategory:i.countAsServerError?"server":"transport",endlessRetries:s}));const{retryWake:d}=n;await Pn(u,o,void 0===d?void 0:e=>d({error:a,delayMs:u,waitEnded:e}))};let d,h,p,f,m,g,w=e.state,y=e.action,v=0,b=o,S=0,k=0,_=!1,C=0;const E=()=>{_&&(n.onConnectionStateChange?.({state:"connected"}),_=!1)},x=(e,t)=>()=>{e===v&&("progress"===t?m=!0:g=!0,E())},P=e=>({handleCheckpoint:async(t,n,o)=>{e===v&&(m=!0),await r.handleCheckpoint(t,n,o),e===v&&(d=n,h=o?.resumeEligibility??"eligible",E())},getLatestCheckpoint:()=>r.getLatestCheckpoint()});for(;;){if(t.canceled)throw a.toCancelledError(void 0,b);if(d=void 0,h=void 0,m=!1,g=!1,s.beginAttempt?.({attempt:v,originalRequestId:c}),v>0?(b=(0,ge.C)(),await(n.onRetryStarting?.(v,{actionCase:y.action.case,conversationState:w,isResume:"resumeAction"===y.action.case,attemptRequestId:b})),e.logging&&vn.info(t,`[${e.logging.tag}] Retrying attempt ${v}`,{attempt:v,actionCase:y.action.case,requestId:b,originalRequestId:c}),"resumeAction"===y.action.case&&(await(n.onRetryResuming?.({checkpointState:w,nextAttempt:v,reason:"resume_action"})),e.logging&&vn.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:v,reason:"resume_action"}))):(e.logging&&vn.info(t,`[${e.logging.tag}] Initial request`,{attempt:v,actionCase:y.action.case,requestId:b}),!0===e.notifyInitialResume&&"resumeAction"===y.action.case&&(await(n.onRetryResuming?.({checkpointState:w,nextAttempt:v,reason:"resume_action"})),e.logging&&vn.info(t,`[${e.logging.tag}] Resuming from checkpoint`,{nextAttempt:v,reason:"resume_action"}))),t.canceled)throw a.toCancelledError(void 0,b);try{return await s.runAttempt({state:w,action:y,checkpointHandler:P(v),attempt:v,attemptRequestId:b,notifyConnected:E,notifyApplicationProgress:x(v,"progress"),notifyApplicationActivity:x(v,"activity")}),E(),void(e.logging&&vn.info(t,`[${e.logging.tag}] Request successful`,{attempt:v,actionCase:y.action.case,requestId:b,originalRequestId:c}))}catch(r){if(!0===a.shortCircuit?.(r))throw a.toCancelledError(r,b);const o=!0===n.endlessRetries?.(),E=e.nowMs?.()??Date.now();(m||g)&&(p=void 0,f=void 0);const x=void 0===p?void 0:E-p,P=void 0===f?void 0:E-f;let T=s.classify(r,{attempt:v,attemptRequestId:b,originalRequestId:c,serverErrorRetries:S,transportErrorRetries:k,stallRetryElapsedMs:x,rateLimitRetryElapsedMs:P,endlessRetries:o});if("retry"===T.action){const n=!("resumeAction"===y.action.case&&w.pendingToolCalls.length>0)&&("resumeAction"===y.action.case||!0===e.noProgressGuardCountsReplays&&v>0);void 0!==d?C=0:n&&m&&(C++,C>=2&&(e.logging&&vn.warn(t,`[${e.logging.tag}] Resume attempts are streaming but not producing checkpoints; stopping automatic resume`,{noProgressResumeFailures:C,attempt:v,requestId:b,originalRequestId:c,errorName:r instanceof Error?r.name:typeof r}),T={action:"throw",error:new qe("Agent turn stopped after repeated resume attempts made no progress",{cause:r instanceof Error?r:void 0,requestId:b,displayInfo:{title:"Agent stopped retrying",detail:"The connection was interrupted repeatedly without saving progress, so the agent stopped to avoid repeating the same work. Retry to continue from the last saved state.",isRetryable:!0}}),transportFailureKind:T.transportFailureKind}))}const A={...void 0===T.transportFailureKind?{}:{transportFailureKind:T.transportFailureKind},...void 0===e.loop?{}:{loop:e.loop}},$=e.logging?.diagnostics?.(r);if(e.logging){const e="retry"===T.action?`RETRY (countAsServerError=${T.countAsServerError}, countAsTransportError=${T.countAsTransportError})`:`THROW ${T.error.kind}`;vn.warn(t,`[AGENT_ERROR_DIAGNOSTICS] requestId=${b} originalRequestId=${c} decision=${e}`,{decision:e,willRetry:"retry"===T.action,enableAgentRetries:n.enableAgentRetries??!1,endlessRetries:o,isRunningInTest:n.isRunningInTest??!1,serverErrorRetries:S,transportErrorRetries:k,attempt:v,requestId:b,originalRequestId:c,...A,...$})}if("throw"===T.action){if(0===v){const r={attempt:0,actionCase:y.action.case,error:T.error,requestId:b,originalRequestId:c,enableAgentRetries:!0===n.enableAgentRetries,endlessRetries:o,stallAborted:!1,abortSources:[]};try{await(n.onErrorNotRetried?.(s.buildNonRetriedErrorInfo?.(r)??r))}catch(r){e.logging&&vn.warn(t,`[${e.logging.tag}] onErrorNotRetried callback failed`,{error:String(r),requestId:b,originalRequestId:c})}}throw e.logging&&vn.warn(t,`[${e.logging.tag}] Error not retryable`,{...A,...$,attempt:v,actionCase:y.action.case,requestId:b,originalRequestId:c,errorName:T.error.name,...!0===e.logging.includeErrorObjects?{error:T.error}:{},serverErrorRetries:S,transportErrorRetries:k}),T.error}const M=v+1;if("ineligible_terminal_turn"===h)return void(e.logging&&vn.warn(t,`[${e.logging.tag}] Terminal checkpoint received before retryable error; completing without automatic resume`,{errorName:r instanceof Error?r.name:typeof r,errorMessage:r instanceof Error?r.message:String(r)}));!0!==T.immediate&&(n.onConnectionStateChange?.({state:"reconnecting",attempt:M,trigger:{...A,...s.reconnectTrigger?.(r,T,{originalRequestId:c,failedAttemptRequestId:b,nextAttempt:M})??{originatingRequestId:c,attemptRequestId:b}}}),_=!0),T.countAsServerError&&S++,T.countAsTransportError&&k++,!0===T.stall?p??=E:p=void 0,!0===T.rateLimit?f??=E:f=void 0,v=M;try{kn.increment(t,1,{attempt:_n(M),reason:Cn(T),loop:e.loop??"nal"})}catch{}void 0!==d&&(I=d,Rn((R=w).turns,I.turns)&&Rn(R.rootPromptMessagesJson,I.rootPromptMessagesJson)||(l=bn),w=d,y=new i.QFf({action:{case:"resumeAction",value:new i.qKo}})),s.onRetryCommitted?.(),!0===T.immediate||!0===T.noBackoff&&void 0===T.retryAfterMs||await u(v,t.signal,o,T,r)}}var R,I}var An=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},$n=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Mn=(0,y.cF)(Symbol("agentStreamMetadata"),void 0),Dn=(0,l.h)("@anysphere/agent-client:abort"),On=(0,l.h)("@anysphere/agent-client:retry"),Fn=(0,l.h)("@anysphere/agent-client:request-context-blob");async function Nn({ctx:e,action:t,resources:r,blobStore:n,options:o,source:s,transportMode:i,notifyBytes:a}){!0===o.omitRequestContextFileContents&&function(e){const t=Ur(e);if(void 0===t)return;const r=t.requestContext;void 0!==r&&Hr(r)&&(t.requestContext=zr(r));const n=e.requestContextParts,o=n?.dynamicContext;void 0!==n&&void 0!==o&&Hr(o)&&(e.requestContextParts=qr(n,{dynamicContext:zr(o)}))}(t);try{const s=await Wr({ctx:e,action:t,resources:r,blobStore:n,mode:i??o.requestContextBlobTransportMode??"legacy",maxBlobBytes:o.requestContextBlobMaxBytes??Fr,maxInlineDynamicBytes:o.requestContextDynamicInlineMaxBytes??1048576,notesSessionId:o.conversationId});if(!0===a){const e=function({prepared:e,parts:t}){return"prepared"===e.kind?cn(e,{dynamicByteLength:e.dynamicByteLength}):"already_prepared"===e.kind&&void 0!==t?cn(t):void 0}({prepared:s,parts:t.requestContextParts});void 0!==e&&o.onRequestContextBytes?.(e)}}catch(r){t.requestContextParts=void 0,Fn.warn(e,"Failed to prepare request context blob; using legacy fallback",{actionCase:t.action.case,errorName:r instanceof Error?r.name:typeof r,source:s})}}const Ln=e=>{const t=[];switch(t.push(e.message.case),e.message.case){case"conversationAction":t.push(e.message.value.action.case);break;case"execClientMessage":case"execClientControlMessage":case"kvClientMessage":case"execServerMessage":case"execServerControlMessage":t.push(e.message.value.message.case);break;case"interactionResponse":t.push(e.message.value.result.case);break;case"interactionUpdate":switch(t.push(e.message.value.message.case),e.message.value.message.case){case"partialToolCall":case"toolCallCompleted":case"toolCallStarted":t.push(e.message.value.message.value.toolCall?.tool.case);break;case"toolCallDelta":t.push(e.message.value.message.value.toolCallDelta?.delta.case)}break;case"interactionQuery":t.push(e.message.value.query.case)}return t.filter((e=>void 0!==e)).join(":")};function jn(e){if(e instanceof Error)return`${e.name}: ${e.message}`;if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e||"bigint"==typeof e)return String(e);if(null==e)return String(e);try{const t=JSON.stringify(e);return"string"==typeof t?t:"unserializable error"}catch{return"unserializable error"}}async function Un(e,t,r){for await(const n of t)switch(n.event.case){case"stdout":await r.sendUpdate(e,a.shellOutputDelta({case:"stdout",value:new he.o0({data:n.event.value.data})}));break;case"stderr":await r.sendUpdate(e,a.shellOutputDelta({case:"stderr",value:new he.Db({data:n.event.value.data})}));break;case"exit":await r.sendUpdate(e,a.shellOutputDelta({case:"exit",value:new he.vb({code:n.event.value.code,aborted:n.event.value.aborted})}))}}function Bn(e){return e instanceof Error?e.name:void 0}class Wn{constructor(e,t,r={}){this.client=e,this.endpointUrl=t,this.options=r,this.hasStartedStream=!1}async run(e,t,r,n,o,s,i,a,l,u,d){const h={stack:[],error:void 0,hasError:!1};try{if(void 0!==d.maxSteps)throw new Ve(d.maxSteps);const g=!0===d.omitRequestContextFileContents?function(e){const t=Gr(e);return void 0===t?e:new J(e,[G($r,{execute:async(e,r,n)=>function(e){if("success"!==e.result.case)return e;const t=e.result.value,r=t.requestContext;return void 0!==r&&Hr(r)?new Dr._G({result:{case:"success",value:qr(t,{requestContext:zr(r)})}}):e}(await t.execute(e,r,n))})])}(s):s,w=!0===d.lazyFileScopedRuleBodies?new on:void 0,y=void 0===w?g:function(e,t){const r=Gr(e);return void 0===r?e:new J(e,[G($r,{execute:async(e,n,o)=>{const s=await r.execute(e,n,o);return void 0!==o?.execId&&t.isAllowed()?sn(s):s}})])}(g,w),v=void 0===w?d:{...d,onHeader:e=>{w.observeHeaders(e),d.onHeader?.(e)}},b=new Br(i),S=d.generationUUID??(0,ge.C)(),k=new c,_=(m=k,p=o,f=e=>{m.observe(e.id)},{sendUpdate:(e,t)=>p.sendUpdate(e,t),query:(e,t)=>(f(t),p.query(e,t)),enqueuePostTurnEndedWork:p.enqueuePostTurnEndedWork?.bind(p),flushPostTurnEndedWork:p.flushPostTurnEndedWork?.bind(p)}),C={sources:[],abortReasonName:void 0,abortReasonMessage:void 0},E=e=>{const t=function(e){const t=ft(e);return void 0===t?void 0:We(ht(t))}(e),r=C.sources.includes("stall_detector")||!0===t?.stallAborted,n=(o=C.sources).some((e=>"stall_detector"!==e))?"owner":o.includes("stall_detector")?"stall_detector":"none";var o;const s=function(e){const t={errorName:Bn(e)},r=mt(e);if(void 0===r)return t;const n=function(e){if(null!==e&&"object"==typeof e&&"cause"in e)return e.cause}(r),o=function(e){if(null===e||"object"!=typeof e||!("code"in e))return;const t=e.code;return"string"==typeof t||"number"==typeof t?t:void 0}(n),s=Bn(n);return{...t,underlyingConnectError:{code:r.code,codeName:ye.Code[r.code],cause:void 0!==o||void 0!==s?{code:o,name:s}:void 0}}}(e),i=s.underlyingConnectError;return{relayed:t,stallAborted:r,abortOrigin:"none"===n&&r?"stall_detector":n,reading:void 0===t?{errorName:s.errorName,connectCode:i?.code,connectCodeName:i?.codeName,connectCause:i?.cause,abortSources:[...C.sources],abortReasonName:C.abortReasonName,...void 0===i?{}:{underlyingConnectError:i}}:{errorName:t.errorName,connectCode:t.connectCode,connectCodeName:t.connectCodeName,connectCause:t.connectCause,...(a=t.loop,"nal"===a||"local_loop"===a||"module"===a?{loop:t.loop}:{}),...void 0===t.transportMode?{}:{transportMode:t.transportMode}}};var a};let x=0,P=0;const R={networkPhaseStartedAt:performance.now()};try{d.onNetworkPhaseStart?.()}catch(t){On.warn(e,"onNetworkPhaseStart callback failed",{error:String(t)})}const I=An(h,(0,$.VI)(e.withName("networkPhase")),!1);e=I.ctx,await(0,$.MG)(I.span,(()=>Tn({ctx:e,state:t,action:r,checkpointHandler:l,runOptions:d,requestId:S,loop:this.options.loop??"nal",notifyInitialResume:!0,logging:{...this.options.retryLogging??{tag:"nal_agent_retries",includeErrorObjects:!0},diagnostics:e=>{const{stallAborted:t,abortOrigin:r,reading:n}=E(e);return{stallAborted:t,abortOrigin:r,...In(n)}}},cancellation:{toCancelledError:()=>new Ke("Request cancelled")},hooks:{beginAttempt:()=>{C.sources=[],C.abortReasonName=void 0,C.abortReasonMessage=void 0,P=++x},runAttempt:async({state:t,action:r,checkpointHandler:o,attempt:s,attemptRequestId:i,notifyConnected:c,notifyApplicationProgress:l,notifyApplicationActivity:d})=>{const h=function(e,t,r){return{sendUpdate:async(n,o)=>{if(t===r())return e.sendUpdate(n,o);"toolCallCompleted"===o.message?.case&&On.warn(n,"nal.await_stall.stale_completion_dropped",{attemptGen:t,currentGen:r()})},query:async(n,o)=>{if(t!==r())throw new Ke("Stale query from previous attempt");return e.query(n,o)},enqueuePostTurnEndedWork:e.enqueuePostTurnEndedWork?t=>e.enqueuePostTurnEndedWork(t):void 0,flushPostTurnEndedWork:e.flushPostTurnEndedWork?t=>e.flushPostTurnEndedWork(t):void 0}}(_,P,(()=>x));await this.runInternal(e,t,r,n,h,y,b,a,o,u,v,i,S,k,C,c,l,d,s,R)},classify:(e,t)=>{const{abortOrigin:r,relayed:n}=E(e),o=gn(e,function(e,t,r=pn){const n=function(e){if(void 0!==e&&Number.isFinite(e))return Math.min(Math.max(Math.floor(e),1),100)-1}(e.maxRetries),o=void 0===n?r:{serverCap:n,transportCap:n};return{serverCap:o.serverCap,transportCap:!0===e.isRunningInTest?Math.min(o.transportCap,2):o.transportCap,...void 0===n?{}:{sharedCap:n},endless:t.endlessRetries,retryAllInference:!0===e.retryAllInferenceErrors}}(d,t),{...t,retriesEnabled:d.enableAgentRetries??!1,abortOrigin:r}),s=n?.transportFailureKind;return"string"==typeof(i=s)&&ln.includes(i)?{...o,transportFailureKind:s}:o;var i},buildNonRetriedErrorInfo:e=>({...e,enableAgentRetries:d.enableAgentRetries??!1,stallAborted:E(e.error).stallAborted,abortSources:[...C.sources],abortReasonName:C.abortReasonName,abortReasonMessage:C.abortReasonMessage}),reconnectTrigger:(e,t,r)=>{const{relayed:n,stallAborted:o,reading:s}=E(e),i=e instanceof He?e:ct(e,{requestId:r.failedAttemptRequestId});return{errorClass:n?.errorName??i.name,connectCode:s.connectCode,connectCodeName:s.connectCodeName,errorCode:i.displayInfo?.errorCode,countAsServerError:t.countAsServerError,countAsTransportError:t.countAsTransportError,stallAborted:o,originatingRequestId:r.originalRequestId,attemptRequestId:r.failedAttemptRequestId,...void 0===s.transportMode?{}:{transportMode:s.transportMode},endpointUrl:this.endpointUrl}},onRetryCommitted:()=>a.reopen()}})))}catch(e){h.error=e,h.hasError=!0}finally{$n(h)}var p,f,m}async runInternal(e,t,r,n,o,s,a,c,l,u,p,f,m,g,w,y,v,b,S,k,_="agent.request.attempt"){const C={stack:[],error:void 0,hasError:!1};try{const P=e;e=this.options.prepareAttemptContext?.(e,{attempt:S,attemptRequestId:f,originalRequestId:m,runOptions:p})??e;const R=An(C,(0,$.VI)(e.withName(_)),!1);R.span.setAttribute("agent.attempt",S),R.span.setAttribute("agent.request_id",f),R.span.setAttribute("agent.original_request_id",m),e=R.ctx,e=(0,$.Mf)(e,"agent.request_id",f),e=(e=(0,$.Mf)(e,"agent.original_request_id",m)).with(Mn,{requestId:f,rootParentRequestId:p.rootParentRequestId,modelDetails:n});const I=new Set(w.sources);let T=void 0!==w.abortReasonName||void 0!==w.abortReasonMessage;const M=(t,r)=>{if(I.has(t))return;I.add(t),w.sources=[...I];const n=(e=>{const t="string"==typeof e?.abortReasonName?e.abortReasonName:void 0,r="string"==typeof e?.abortReasonMessage?e.abortReasonMessage:void 0;if(void 0!==t||void 0!==r)return{abortReasonName:t,abortReasonMessage:r}})(r);T||void 0===n||(T=!0,w.abortReasonName=n.abortReasonName,w.abortReasonMessage=n.abortReasonMessage),Dn.error(e,"Agent client stream abort",new Error(t),{abortSource:t,requestId:f,conversationId:p.conversationId,...r??{}})};if(e.signal.aborted){const t=e.signal.reason;M("ctx_signal_abort",ue(t))}else e.signal.addEventListener("abort",(()=>{const t=e.signal.reason;M("ctx_signal_abort",ue(t))}),{once:!0});const[D,O]=e.withCancel();if(c.signal?.aborted){const e=c.signal?.reason;M("conversation_action_abort",ue(e)),O()}else c.signal?.addEventListener("abort",(()=>{const e=c.signal?.reason;M("conversation_action_abort",ue(e)),O()}),{once:!0});if(e.canceled||D.canceled){const t={ctxCanceled:e.canceled,softCancel:D.canceled};throw M("pre_run_cancel",t),new Ke("User aborted request")}const F=(0,$.VI)(e.withName("createControlledExecManager")),N=A.fromResources(s);F[Symbol.dispose]();const[L,j]=e.withCancel(),U=new Gt,{failThresholdMs:B,advisoryThresholdMs:W}=function(e,t){const r=Lt(e?.failTimeoutMs)??3e4,n=r>0&&!0!==t?.isRunningInTest?Math.max(r,2e4):r,o=Lt(e?.advisoryTimeoutMs);return{failThresholdMs:n,advisoryThresholdMs:void 0!==o&&o>0&&(n<=0||oH,onStall:e=>{M("stall_detector",{thresholdMs:B,advisoryThresholdMs:W}),j(e)},onStallCallback:p.onStall,handlerTracker:U}),!1);let z,G,V;const K=(0,ve.Jt)(),J=new h.F8(K,(e=>(q.reset("outbound_write",Ln(e)),e))),Z=An(C,(0,$.VI)(e.withName("writeInitialRequest")),!1);let X;const Q=function(e){return new wn.Or({mcpTools:e.map((e=>({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?we.Value.fromJson(e.inputSchema):void 0,outputSchemaJson:void 0!==e.outputSchema?JSON.stringify(e.outputSchema):void 0})))})}(u),Y=p.requestContextBlobTransportMode??"legacy",te=0===S&&"userMessageAction"===r.action.case&&0===t.turns.length,re="ref_only"===Y&&te?"dual":Y,[,ne]=await Promise.all([Nn({ctx:e,action:r,resources:s,blobStore:a,options:p,source:"run_request",transportMode:re,notifyBytes:0===S}),void 0===p.mintLlmGatewayCredential?Promise.resolve(void 0):Ar(p.mintLlmGatewayCredential,{signal:D.signal,isCanceled:()=>D.canceled,requestId:f})]),oe={action:r,headers:p.headers??{}},se=this.options.decorateAttempt?.(oe,p)??oe,ie=new i.Mpn({conversationState:t,action:se.action,modelDetails:n,requestedModel:p.requestedModel,clientLlmGatewayCredential:ne,mcpTools:Q,conversationGroupId:p.conversationGroupId,conversationId:p.conversationId,agentSessionId:p.agentSessionId,mcpFileSystemOptions:p.mcpFileSystemOptions,customSystemPrompt:p.customSystemPrompt,systemPromptSpec:p.systemPromptSpec,harness:p.harness,computerUseCoordinateMode:p.computerUseCoordinateMode,subagentTypeName:p.subagentTypeName,excludeWorkspaceContext:p.excludeWorkspaceContext,devRawModelSlug:p.devRawModelSlug,selectedSubagentModels:p.selectedSubagentModels,subagentModelOverrides:p.subagentModelOverrides??[],selectedSubagentModelDetails:p.selectedSubagentModelsLegacy,clientSupportsInlineImages:p.clientSupportsInlineImages,clientSupportsPreviewCard:p.clientSupportsPreviewCard,startedAsNewProject:p.startedAsNewProject,firstProjectOnboarding:p.firstProjectOnboarding,clientSupportsSendToUser:p.clientSupportsSendToUser,clientSupportsRoutedModelUpdate:p.clientSupportsRoutedModelUpdate,emitModelCallUsage:p.emitModelCallUsage,canCreateCloudSubagents:p.canCreateCloudSubagents,suppressSubagentProgressUpdateTool:p.suppressSubagentProgressUpdateTool,transcriptParentConversationId:p.transcriptParentConversationId,runId:m,nextInteractionQueryId:g.peekNext(),voiceCallNotes:p.voiceCallNotes});if(X=J.write(new de.KS({message:{case:"runRequest",value:ie}})),D.canceled){const t={ctxCanceled:e.canceled,softCancel:D.canceled};throw M("post_write_cancel",t),Z[Symbol.dispose](),new Ke("User aborted request")}const ae={...se.headers,"x-request-id":f,"x-original-request-id":m,...Me(p),...Oe()};z=(0,$.VI)(e.withName("handshakeEstablishment")),z.span.setAttribute("handshake.firstStreamOnClient",!this.hasStartedStream),this.hasStartedStream=!0;const ce=function(e){return e?.get(yn)}(e)?.startTransportRun(),pe=void 0===ce?z.ctx:function(e,t){return e.with(yn,t)}(z.ctx,ce),fe=0===S&&void 0!==p.onTtftBreakdown?k?.networkPhaseStartedAt:void 0;let ge;const ye=void 0===ce&&void 0===fe?K:(E=K,x=()=>{ge=performance.now(),ce?.markFirstRequestSent(ge)},{[Symbol.asyncIterator](){const e=E[Symbol.asyncIterator]();let t=!1;const r={next:()=>(t||(t=!0,x()),e.next())};return void 0!==e.return&&(r.return=t=>e.return(t)),void 0!==e.throw&&(r.throw=t=>e.throw(t)),r}}),be=this.client.run(pe,ye,{signal:L.signal,headers:ae,onHeader:e=>{H=e.get("x-cursor-agent-transport-mode")??void 0,p.onHeader?.(e)},onNetworkStarted:()=>{void 0===G&&(G=performance.now(),0===S&&(V=function(e=Kt,t=25){let r,n=0,o=0,s=e.now()+t;const i=e=>{e<=0||(o+=e,e>n&&(n=e))},a=()=>{const r=e.now();i(r-s),s=r+t,c=e.setTimeout(a,t)};let c=e.setTimeout(a,t);return{stop:()=>(void 0===r&&(e.clearTimeout(c),i(e.now()-s),r={maxLagMs:n,totalLagMs:o}),r)}}()))}}),ke=performance.now();let Ce;const xe=t=>{z&&(z.span.setAttribute("handshake.firstMessageHeartbeat",t),void 0!==G&&z.span.setAttribute("handshake.preNetworkMs",G-ke),z[Symbol.dispose](),z=void 0),y();const r=performance.now();Ce=r,p.onFirstMessage?.(r-ke),void 0!==G&&(p.onFirstMessageNetwork?.(r-G),void 0!==V&&(function(e,t){const r={loop:t.loop??"nal",transport_mode:Bt(t.transportMode),first_message_slow:t.firstMessageNetworkMs>=1e3?"true":"false"};Jt.histogram(e,t.reading.maxLagMs,r),Zt.histogram(e,t.reading.totalLagMs,r),Xt.histogram(e,t.firstMessageNetworkMs,r)}(e,{loop:this.options.loop,transportMode:H,firstMessageNetworkMs:r-G,reading:V.stop()}),V=void 0))},Pe=()=>{b(),p.onFirstNonHeartbeatResponse?.(performance.now()-ke,S)},Ie=p.onTtftBreakdown?e=>{const t=performance.now(),r=void 0===fe||void 0===ge||"server"!==e.clock?void 0:function(e){const t=Math.min(e.firstRequestTakenAt,e.firstMessageAt);return{requestBuildMs:Math.max(0,e.transportRunCalledAt-e.networkPhaseStartedAt),connectMs:Math.max(0,t-e.transportRunCalledAt),roundTripMs:Math.max(0,e.firstMessageAt-t),firstByteToOutputMs:Math.max(0,e.firstOutputAt-e.firstMessageAt),firstOutputReceivedAtEpochMs:e.firstOutputAtEpochMs}}({networkPhaseStartedAt:fe,transportRunCalledAt:ke,firstRequestTakenAt:ge,firstMessageAt:Ce??t,firstOutputAt:t,firstOutputAtEpochMs:Date.now()});p.onTtftBreakdown(void 0===r?e:{...e,transit:r},S)}:void 0,$e=!0===this.options.execCheckpointGate?function(e,t,r,n={}){return Te.has(r.action.action.case)?async function*(e,t,r,n){const o=[];let s=0;const i=()=>o.flatMap((e=>void 0===e.toolCallId?[]:[e.toolCallId])),a=e=>{const t=[];for(;o.length>0;){const n=o[0];if(!e&&void 0!==n.toolCallId&&!r.has(n.toolCallId))break;t.push(n.message),o.shift()}return t.length>0&&o.length>0&&(s=n.now()),t},c=()=>{const e=o.filter((e=>"execServerControlMessage"===e.message.message.case)),t=o.filter((e=>"execServerControlMessage"!==e.message.message.case));return o.splice(0,o.length,...t),e.map((e=>e.message))},l=t[Symbol.asyncIterator]();let u=!0;try{for(;;){let t;try{t=await l.next()}catch(e){throw u=!1,yield*c(),e}if(!0===t.done)return u=!1,void(yield*c());const d=t.value,h=d.message;if("execServerMessage"!==h.case&&"execServerControlMessage"!==h.case)if("conversationCheckpointUpdate"!==h.case){if(yield d,o.length>0&&n.now()-s>=n.holdMs){Re.info(e,"No checkpoint named held tool calls on a stream still delivering: handed on as they came",{toolCallIds:i().join(", "),waitedMs:Math.round(n.now()-s)});for(const e of i())r.add(e);yield*a(!0)}}else{for(const e of Ee(h.value.pendingToolCalls))r.add(e);if(yield d,o.length>0){const t=Math.round(n.now()-s),r=a(!1);r.length>0&&Re.debug(e,"Handed held execs on after their checkpoint",{count:r.length,waitedMs:t}),yield*r}}else{const t="execServerMessage"===h.case?Ae(h.value):void 0,i=void 0!==t&&!r.has(t);if(0===o.length&&!i){yield d;continue}if(0===o.length&&(s=n.now()),o.push({message:d,toolCallId:i?t:void 0}),i){Re.debug(e,"Held a tool call's exec for the checkpoint that names it",{toolCallId:t});try{n.onHeld?.(t)}catch(t){Re.warn(e,"onExecHeldForCheckpoint callback failed",{error:String(t)})}}}}}catch(e){if(u){u=!1;try{await(l.return?.())}catch{}}throw e}finally{o.length>0&&Re.info(e,"The stream ended before a checkpoint named held tool calls: dropped, never run",{toolCallIds:i().join(", ")}),u&&await(l.return?.())}}(e,t,Ee(r.state.pendingToolCalls),{holdMs:n.holdMs??5e3,now:n.now??(()=>performance.now()),onHeld:n.onHeld}):t}(e,be,{action:se.action,state:t},void 0===this.options.onExecHeldForCheckpoint?{}:{onHeld:this.options.onExecHeldForCheckpoint}):be,De=!0===this.options.execAfterCheckpointStored||!0===this.options.execCheckpointGate?new _e(void 0===this.options.onExecHeldForCheckpointStore?{}:{onExecHeld:this.options.onExecHeldForCheckpointStore}):void 0,{interactionStream:Fe,execStream:Ne,checkpointStream:Le,kvStream:je,done:Ue}=function(e,t,r,n,o,s,i,a,c,l){const u=(0,ve.Jt)(),d=(0,ve.Jt)(),h=(0,ve.Jt)(),p=(0,ve.Jt)();let f=!1,m=!1,g=!1;return{interactionStream:u,execStream:d,checkpointStream:h,kvStream:p,done:async function(){let w,y,v=!1,b=!1;try{for await(const o of t){if(void 0!==o.ttftBreakdown){const t=o.ttftBreakdown;try{a?.({serverFirstTokenMs:t.serverFirstTokenMs,preStreamSetupMs:t.preStreamSetupMs,waitForFirstEventMs:t.waitForFirstEventMs,providerTtftMs:t.providerTtftMs,slowPoolWaitMs:t.slowPoolWaitMs,...void 0===t.clientPrepMs?{}:{clientPrepMs:t.clientPrepMs},...void 0===t.clientPrepLegs?{}:{clientPrepLegs:me(t.clientPrepLegs)},...void 0===t.preHandlerMs?{}:{preHandlerMs:t.preHandlerMs},clock:t.clientClock?"client":"server"})}catch(t){On.warn(e,"onTtftBreakdown callback failed",{error:String(t)})}}const t="interactionUpdate"===o.message.case&&"heartbeat"===o.message.value.message.case;if(f||(f=!0,n(t)),t)r.onServerSentHeartbeat(),r.reset("inbound_message","heartbeat");else{if(!m){m=!0;try{i?.()}catch(t){On.warn(e,"onFirstNonHeartbeatMessage callback failed",{error:String(t)})}}if(!g&&"interactionUpdate"===o.message.case&&xn(o.message.value)){g=!0;try{l?.()}catch(t){On.warn(e,"onFirstModelOutput callback failed",{error:String(t)})}}r.reset("inbound_message",Ln(o))}if("interactionUpdate"===o.message.case&&"turnEnded"===o.message.value.message.case&&(v=!0),"interactionUpdate"!==o.message.case&&"interactionQuery"!==o.message.case||await u.write(o.message).catch((()=>{})),"execServerMessage"!==o.message.case&&"execServerControlMessage"!==o.message.case||await d.write(o.message.value),"conversationCheckpointUpdate"===o.message.case){const e=v?"ineligible_terminal_turn":"eligible";"ineligible_terminal_turn"===e&&(b=!0);const t=c?.noteRouted(o.message.value);try{await h.write({checkpoint:o.message.value,metadata:{resumeEligibility:e},...void 0===t?{}:{onSettled:t}})}catch(e){throw t?.(),e}}"kvServerMessage"===o.message.case&&await p.write(o.message.value)}r.onStreamEnded()}catch(e){w=e}finally{if(y=w,v&&b&&void 0!==w&&!o?.aborted&&!s?.aborted&&function(e){const t=e instanceof He?e:ct(e);return t instanceof qe&&function(e){return!0===e.isTransport||(e.cause instanceof Error?bt(e.cause):St(e.message))}(t)}(w)&&(On.debug(e,"Ignoring transport close after terminal agent stream",{caughtError:w instanceof Error?`${w.name}: ${w.message}`:String(w)}),r.onStreamEnded(),y=void 0),v||o?.aborted||s?.aborted){if(!v&&!o?.aborted){const t=`Stream ended without turnEnded, abort signals: signal.aborted=${o?.aborted}, parentSignal.aborted=${s?.aborted}; firstMessageFired=${f}`;On.warn(e,t)}}else{const t="Stream ended without turnEnded — connection likely dropped mid-stream";void 0===w?(On.warn(e,t),y=new qe(t,{isTransport:!0})):w instanceof Error&&"[aborted] aborted"===w.message?(On.warn(e,`${t}; retrying caught [aborted] aborted error`),y=new qe(t,{cause:w,isTransport:!0})):On.warn(e,`${t}; caught non-retriable stream error, rethrowing as-is`,{caughtError:jn(w)})}u.close(),d.close(),h.close(),p.close()}if(void 0!==y)throw y}()}}(e,$e,q,xe,D.signal,e.signal,Pe,Ie,De,v);let Be;const We={handleCheckpoint:async(e,t,r)=>{await l.handleCheckpoint(e,t,r),Be=r?.resumeEligibility??"eligible"},getLatestCheckpoint:()=>l.getLatestCheckpoint()};Z[Symbol.dispose]();const ze=5e3;let Ve;const Je=()=>{Ve=setTimeout((()=>{J.write(new de.KS({message:{case:"clientHeartbeat",value:new de.kA}})).then((()=>q.onClientSentHeartbeat()),(()=>{})),Je()}),ze)},Ze=()=>{void 0!==Ve&&(clearTimeout(Ve),Ve=void 0)};Je();try{let t;if("shellCommandAction"===r.action.case&&r.action.value.execId){const n=r.action.value,i=new he.a({command:n.shellCommand?.command||"",parsingResult:new he.HO,skipApproval:!0}),a=s.get(ee).execute(e,i,{execId:n.execId}),c=new Tr(Fe,o,new h.F8(J,(e=>new de.KS({message:{case:"interactionResponse",value:e}}))),q);t={run:async e=>{await Promise.all([U.track("handleShellStream",Un(e,a,o)),U.track("interactionController",c.run(e))])}}}else{const e=new Tr(Fe,o,new h.F8(J,(e=>new de.KS({message:{case:"interactionResponse",value:e}}))),q);t={run:async t=>{await U.track("interactionController",e.run(t))}}}void 0!==X&&await Promise.race([X,Ue.catch((()=>{}))]);const i=new h.F8(J,(e=>{if((0,we.isMessage)(e,d.yT))return new de.KS({message:{case:"execClientMessage",value:e}});if((0,we.isMessage)(e,d.$Y))return new de.KS({message:{case:"execClientControlMessage",value:e}});throw new Error(`Unknown exec message (type: ${(0,we.isMessage)(e)?e.getType().typeName:typeof e})`)})),l=new Ft(Ne,i,N,De),S=new le(je,new h.F8(J,(e=>new de.KS({message:{case:"kvClientMessage",value:e}}))),a,{beforeGetBlob:async(e,t)=>a.persistForRemoteRead(e,t)}),k=new Se(Le,We,e);let _,C;const E={promise:new Promise(((e,t)=>{_=e,C=t})),resolve:_,reject:C};D.canceled?(E.resolve(),Fe.close()):D.signal.addEventListener("abort",(()=>{E.resolve(),Fe.close()}),{once:!0}),l.run(D).then(E.resolve).catch(E.reject);const x=Promise.allSettled([U.track("streamSplitter",Ue.finally((()=>{Ze(),c.close(),i.close()}))),U.track("execHandler",E.promise),t.run(e),U.track("checkpointController",k.run()),U.track("kvHandler",S.run(e)),U.track("conversationActionManager",c.run(e,{write:async t=>{await Nn({ctx:e,action:t,resources:s,blobStore:a,options:p,source:"queued_action"}),await J.write(new de.KS({message:{case:"conversationAction",value:t}}))}}))]);let R,I;const T={promise:new Promise(((e,t)=>{R=e,I=t})),resolve:R,reject:I};x.then(T.resolve).catch(T.reject),e.canceled?T.reject(new Ke("User aborted request")):e.signal.addEventListener("abort",(()=>T.reject(new Ke("User aborted request"))),{once:!0});const A=()=>{e.signal.aborted?j():function(e){const t=e.lingerMs??6e3;return new Promise((r=>{let n=!1;const o=e=>{n||(n=!0,clearTimeout(s),r(e))},s=setTimeout((()=>o("linger_timed_out")),t);e.done.then((()=>o("stream_ended")),(()=>o("stream_ended")))}))}({done:Ue,lingerMs:p.softCancelLingerMs}).then((t=>{On.info(e,"Soft-cancel transport linger finished",{outcome:t,requestId:f}),j()}))};D.canceled?(A(),T.reject(new Ke("User aborted request"))):D.signal.addEventListener("abort",(()=>{A(),T.reject(new Ke("User aborted request"))}),{once:!0});const $=await T.promise,M=$[0],O=$[1],F=$[3],L=e=>e.reason instanceof Error?`${e.reason.name}: ${e.reason.message}`:String(e.reason);if("rejected"===F.status)throw new Ge("Checkpoint persistence failed",{cause:F.reason instanceof Error?F.reason:void 0,requestId:f,displayInfo:{title:"Checkpoint persistence failed",detail:L(F),isRetryable:!1}});const B="ineligible_terminal_turn"===Be;if(B){const t={..."rejected"===M.status?{streamSplitter:L(M)}:{},..."rejected"===O.status?{execHandler:L(O)}:{}};Object.keys(t).length>0&&On.debug(e,"Ignoring handler errors after terminal checkpoint",t)}if("rejected"===M.status&&!B)throw M.reason;if("rejected"===O.status&&!B)throw O.reason;D.canceled||await this.processUnprocessedMessages(P,c,We,n,o,s,a,u,p,f,m,g,w,q,y,v,b)}finally{Ze(),V?.stop(),V=void 0,z&&(z[Symbol.dispose](),z=void 0)}}catch(e){C.error=e,C.hasError=!0}finally{$n(C)}var E,x}async processUnprocessedMessages(e,t,r,n,o,s,a,c,l,u,d,h,p,f,m,g,w){if(!t.hasUnprocessedMessages())return;const y=t.getUnprocessedUserMessages(),v=r.getLatestCheckpoint();if(!v||0===y.length)return;const b=y[0];t.markMessageAsProcessed(b),t.resetStream(),f[Symbol.dispose]();const S=r.getLatestCheckpoint();try{await this.runInternal(e,v,new i.QFf({action:{case:"userMessageAction",value:new i.Vtf({userMessage:b})}}),n,o,s,a,t,r,c,l,u,d,h,p,m,g,w,0,void 0,"agent.request.queuedMessage")}catch(e){throw S===r.getLatestCheckpoint()&&t.requeueMessage(b),e}}}const Hn="cursor-ide-browser",qn="cursor-dev-control",zn="custom-user-tools",Gn=new Set(["cursor-app-control","cursor-backend-control","cursor-browser-extension",Hn,qn,zn,"fsd","cursor-subscriptions","cursor-cloud","suggestions","Cursor Slack Tools","Cursor Automation Tools"]);function Vn(e){return!Gn.has(e)}const Kn=new Set([qn,Hn]);function Jn(e){if(void 0!==e&&0!==Object.keys(e).length)try{return JSON.stringify(e)}catch{return}}function Zn(e){return{name:e.toolName,description:e.description,arguments:e.inputSchema,outputSchema:e.outputSchema,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId}}var Xn;function Qn(e){return void 0===e||void 0===e.serverIdentifiers}function Yn(e){switch(e.kind){case"ready":return void 0===e.toolListError?"connected":"error";case"requires_authentication":return"needsAuth";case"error":return"error";default:return"loading"}}(0,y.cF)(Symbol("mcpHostFilledArguments"),[]),function(e){e.Snapshots="cursor_mcp_lease_snapshot_store",e.Status="cursor_mcp_lease_server_status",e.Settings="cursor_mcp_lease_settings",e.Providers="cursor_mcp_lease_providers",e.Unknown="cursor_mcp_lease_unknown"}(Xn||(Xn={}));const eo=q("mcp-executor",(e=>new B(e,Z("mcpArgs"),X("mcpResult"))),((e,t)=>{t.register(new I(e,Y("mcpArgs"),Q("mcpResult")))})),to=q("list-mcp-resources-executor",(e=>new B(e,Z("listMcpResourcesExecArgs"),X("listMcpResourcesExecResult"))),((e,t)=>{t.register(new I(e,Y("listMcpResourcesExecArgs"),Q("listMcpResourcesExecResult")))})),ro=q("read-mcp-resource-executor",(e=>new B(e,Z("readMcpResourceExecArgs"),X("readMcpResourceExecResult"))),((e,t)=>{t.register(new I(e,Y("readMcpResourceExecArgs"),Q("readMcpResourceExecResult")))})),no=q("mcp-state-executor",(e=>new B(e,Z("mcpStateExecArgs"),X("mcpStateExecResult"))),((e,t)=>{t.register(new I(e,Y("mcpStateExecArgs"),Q("mcpStateExecResult")))}));var oo=r("../proto/dist/generated/agent/v1/subagent_exec_pb.js");(0,y.cF)(Symbol("pendingSubagentReplay"),void 0);class so extends Error{constructor(e,t){super(e),this.name="SubagentHostError",this.agentId=t?.agentId,this.cause=t?.cause}}const io=q("subagent-executor",(e=>new B(e,Z("subagentArgs"),X("subagentResult"))),((e,t)=>{t.register(new I(e,Y("subagentArgs"),Q("subagentResult")))})),ao=q("subagent-await-executor",(e=>new B(e,Z("subagentAwaitArgs"),X("subagentAwaitResult"))),((e,t)=>{t.register(new I(e,Y("subagentAwaitArgs"),Q("subagentAwaitResult")))})),co=q("force-background-subagent-executor",(e=>new B(e,Z("forceBackgroundSubagentArgs"),X("forceBackgroundSubagentResult"))),((e,t)=>{t.register(new I(e,Y("forceBackgroundSubagentArgs"),Q("forceBackgroundSubagentResult")))}));var lo=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/status.js"),uo=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js");const ho=(0,ye.createContextKey)(void 0,{description:"anysphere.callerContext"}),po=(0,y.cF)(Symbol("context-rpc.expected_error"),void 0);function fo(e,t,r){!0===t.get(po)?.(r)?e?.setAttribute("rpc.expected_error",!0):(e?.recordException(go(r)),e?.setStatus({code:lo.s.ERROR,message:r instanceof Error?r.message:"RPC call failed"})),e?.end()}function mo(e){return null!==e&&"object"==typeof e&&Symbol.asyncIterator in e}function go(e){return e instanceof Error?e:new Error(String(e))}function wo(e,t,r){return{[Symbol.asyncIterator](){const n=e[Symbol.asyncIterator]();let o=!1;const s=e=>{o||(o=!0,e?(t?.recordException(go(e)),t?.setStatus({code:lo.s.ERROR,message:e instanceof Error?e.message:"Stream failed"})):t?.setStatus({code:lo.s.OK}),t?.end(),r?.())};return{async next(){try{const e=await n.next();return e.done&&s(),e}catch(e){throw s(e),e}},return:async e=>(s(),n.return?n.return(e):{done:!0,value:void 0}),async throw(e){if(s(e),n.throw)return n.throw(e);throw e}}}}}function yo(...e){const t=new Headers;for(const r of e)r&&(r instanceof Headers?r:new Headers(r)).forEach(((e,r)=>{t.set(r,e)}));return t}function vo(e,t){const{injectTraceHeaders:r=!0,extractHeaders:n}=t;return new Proxy(e,{get(e,o){const s=e[o];return"function"!=typeof s?s:(i,a,c={})=>{const l=(0,$.fR)(i.withName(`rpc.${String(o)}`),{kind:uo.v.CLIENT,attributes:{"rpc.method":String(o),"rpc.system":"connect"}}),u=(0,$.fU)(l);let d;try{let o;if(r&&(o=function(e){const t=new Headers;try{const r=(0,$.fU)(e),n=r?.spanContext?.();if(n?.traceId&&n.spanId){const e=n.traceFlags??0,r=`00-${n.traceId}-${n.spanId}-${e.toString(16).padStart(2,"0")}`;t.set("traceparent",r),t.set("backend-traceparent",r),n.traceState&&t.set("tracestate",n.traceState.serialize())}}catch{}return t}(l)),n){const e=n(l);e&&(o=yo(o,e))}const i=yo(c.headers,o),{signal:p,cleanup:f}=!0===t.enableAbortSignal?function(e,t){if(void 0===t||t===e)return{signal:e};const r=new AbortController,n=()=>{r.abort(e.reason)},o=()=>{r.abort(t.reason)};e.addEventListener("abort",n,{once:!0}),t.addEventListener("abort",o,{once:!0}),e.aborted?n():t.aborted&&o();return{signal:r.signal,cleanup:()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",o)}}}(l.signal,c.signal):{signal:c.signal,cleanup:void 0};d=f;const m=(c.contextValues??(0,ye.createContextValues)()).set(ho,l),g={...c,headers:i,signal:p,contextValues:m},w=s.call(e,a,g);return mo(w)?wo(w,u,d):null!==(h=w)&&"object"==typeof h&&"then"in h&&"function"==typeof h.then?Promise.resolve(w).then((e=>mo(e)?wo(e,u,d):(u?.setStatus({code:lo.s.OK}),u?.end(),d?.(),e))).catch((e=>{throw fo(u,l,e),d?.(),e})):(u?.setStatus({code:lo.s.OK}),u?.end(),d?.(),w)}catch(e){throw fo(u,l,e),d?.(),e}var h}}})}var bo=r("node:crypto?8af2"),So=r("../utils/dist/workspace-paths.js");function ko(){return(0,s.join)(function(){const e=process.env.CURSOR_DATA_DIR;return e?.trim()?e:(0,s.join)((0,o.homedir)(),".cursor")}(),"projects")}function _o(e){return(0,s.join)(ko(),(0,So.r_)(e))}var Co=r("node:fs/promises"),Eo=r("../../node_modules/.pnpm/lru-cache@11.2.5/node_modules/lru-cache/dist/esm/index.js"),xo=r("node:fs");const Po="local";function Ro(e,t){return`${e}:task_progress:${t}`}function Io(e){const t={};return"string"==typeof e.title&&e.title.trim().length>0&&(t.title=e.title),"string"==typeof e.cwd&&e.cwd.trim().length>0&&(t.cwd=e.cwd),"number"==typeof e.startTimeMs&&Number.isFinite(e.startTimeMs)&&e.startTimeMs>0&&(t.startTimeMs=String(Math.floor(e.startTimeMs))),Object.keys(t).length>0?t:void 0}function To(e,t){e.hookApprovalRequirement=void 0!==t?new he.In(t):void 0}function Ao(e){return e.hookApprovalRequirement}function $o(e){return e?.kind===he.b.FORCE_PROMPT}function Mo(e){return!(!e.skipApproval||e.smartModeClassifierAllowed&&$o(e.hookApprovalRequirement))}var Do=r("../proto/dist/generated/agent/v1/background_shell_exec_pb.js"),Oo=r("../shell-exec/dist/api/index.js"),Fo=r("./src/agent/native/tree-sitter.webpack.cjs"),No=r("./src/agent/native/tree-sitter-bash.webpack.cjs");const Lo=function(e,t=console.warn){let r;return()=>{if(void 0!==r)return r;try{const t=e();t.setLanguage(No),r=t}catch(e){if(!function(e){return"object"==typeof e&&null!==e&&"CURSOR_TREE_SITTER_STUBBED"===e.code}(e))throw e;r=null,t("shell-parser: tree-sitter natives are unavailable in this artifact; shell command analysis degrades to parsingFailed")}return r}}((()=>new Fo)),jo=new Set(["file_redirect","heredoc_redirect","herestring_redirect","heredoc","here_string","redirect","redirection"]),Uo=new Set(["<",">",">>",">|","<>","<&",">&","&>","&>>"]);function Bo(e,t){if(null===e)return{legacy:{simpleCommands:[],hasInputRedirect:!1,hasOutputRedirect:!1},structured:{parsingFailed:!0,executableCommands:[],hasRedirects:!1,hasCommandSubstitution:!1,redirects:[]}};const r=e.parse(t),n=new WeakSet;let o=!1,s=!0;const i={simpleCommands:[],hasInputRedirect:!1,hasOutputRedirect:!1},a={parsingFailed:!1,executableCommands:[],hasRedirects:!1,hasCommandSubstitution:!1,redirects:[]},c=e=>{o=!0,a.hasRedirects=!0,s=s&&e},l=e=>{if(e&&/^\d+$/.test(e.text))return Number.parseInt(e.text,10)},u=()=>({fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}),d=(e,t)=>{const r=(e=>{const t=e.children,r=t.findIndex((e=>Uo.has(e.type)));if(-1!==r)return{operator:t[r]?.type??"",target:t.slice(r+1).find((e=>"comment"!==e.type))}})(e);if(!r)return!1;const{operator:n,target:o}=r,s=((e,t)=>{if("&>"===t||"&>>"===t)return[1,2];const r=(e=>l(e.children.find((e=>"file_descriptor"===e.type))))(e);return void 0!==r?[r]:t.startsWith("<")?[0]:[1]})(e,n),i=(e=>{if(e){if("word"===e.type)return 0===e.namedChildren.length?e.text:void 0;if("number"===e.type)return e.text;if("raw_string"===e.type){if(e.text.length<2)return;return e.text.slice(1,-1)}if("string"===e.type){const t=e.namedChildren;if(0===t.length||t.some((e=>"string_content"!==e.type)))return;return t.map((e=>e.text)).join("")}}})(o),c={operator:n,destinationFds:s,targetNodeType:o?.type??""};if(void 0!==i&&(c.targetText=i),a.redirects.push(c),">&"===n){const e=l(o),r=void 0===e?void 0:t.fdTargets.get(e);if(!(e=>"original-stdout"===e||"original-stderr"===e||"dev-null"===e)(r)){for(const e of s)t.fdTargets.set(e,"unsafe");return!1}for(const e of s)t.fdTargets.set(e,r);return!0}if("<&"===n){const e=l(o),r=void 0===e?void 0:t.fdTargets.get(e);if("dev-null"!==r){for(const e of s)t.fdTargets.set(e,"unsafe");return!1}for(const e of s)t.fdTargets.set(e,r);return!0}if(!(e=>{if(!e)return!1;if("word"===e.type)return"/dev/null"===e.text;if("raw_string"===e.type)return"'/dev/null'"===e.text;if("string"===e.type){const t=e.namedChildren;return 1===t.length&&"string_content"===t[0]?.type&&"/dev/null"===t[0].text}return!1})(o)){for(const e of s)t.fdTargets.set(e,"unsafe");return!1}for(const e of s)t.fdTargets.set(e,"dev-null");return!0},h=(e,t)=>{if(!n.has(e)){if(n.add(e),(e=>{var t;t=e.text,/(^|\s)[0-9]*<>/.test(t)||/(^|\s)[0-9]*>(\||&)?/.test(t)||/(^|\s)&>/.test(t)||/(^|\s)[0-9]+>&[0-9]+/.test(t))&&(i.hasOutputRedirect=!0),"heredoc_redirect"!==e.type&&"herestring_redirect"!==e.type||(i.hasInputRedirect=!0)})(e),"heredoc_redirect"===e.type){const{redirect:t,isAllowlistSafe:r}=(e=>{const t=(e=>{const t=e.parent;if("redirected_statement"!==t?.type)return;const r=t.children.find((e=>"command"===e.type)),n=r?.childForFieldName("name");return n?.text})(e),r=void 0!==t&&!(e=>{let t=e.parent;for(;t;){if("command_substitution"===t.type&&"string"!==t.parent?.type)return!0;t=t.parent}return!1})(e),n={operator:r?"<<":"",destinationFds:r?[0]:[],targetNodeType:e.type};return r&&(n.targetText=t),{redirect:n,isAllowlistSafe:r}})(e);return a.redirects.push(t),void c(r)}if("file_redirect"!==e.type)return a.redirects.push({operator:"",destinationFds:[],targetNodeType:e.type}),void c(!1);c(d(e,t))}};return function e(t){const r=t.type;if((e=>{const t=u();for(const r of e.children)jo.has(r.type)&&h(r,t)})(t),jo.has(r)&&!n.has(t)&&h(t,u()),"command"===r){const e=t.childForFieldName("name");if(null===e)a.parsingFailed=!0;else{i.simpleCommands.push(e.text);let r=e.text;const n=[];for(const e of function(e){const t=[],r=e.walk();if(r.gotoFirstChild())do{"argument"===r.currentFieldName&&t.push(r.currentNode)}while(r.gotoNextSibling());return t}(t))n.push({type:e.type,value:e.text}),r+=` ${e.text}`;a.executableCommands.push({name:e.text,args:n,fullText:r})}}if("command_name"===r||"simple_command"===r)if("command_name"!==r||i.simpleCommands.includes(t.text)){if("simple_command"===r){const e=t.firstNamedChild;e&&"command_name"===e.type?i.simpleCommands.includes(e.text)||i.simpleCommands.push(e.text):i.simpleCommands.push(t.text)}}else i.simpleCommands.push(t.text);"command_substitution"!==r&&"process_substitution"!==r||(a.hasCommandSubstitution=!0);for(const r of t.children)e(r)}(r.rootNode),o&&(a.allRedirectsAreDevNull=s),{legacy:i,structured:a}}function Wo(e){return Bo(Lo(),e)}function Ho(e,t){return t>0&&t=55296&&r<=56319)&&function(e){return e>=56320&&e<=57343}(e.charCodeAt(t));var r}function qo(e,t){return t>0?t>=e.length?e.length:Math.trunc(t):0}function zo(e,t){const r=qo(e,t);return Ho(e,r)?r-1:r}function Go(e,t){const r=qo(e,t);return Ho(e,r)?r+1:r}function Vo(e,t){return t>0?e.length<=t?e:e.slice(0,zo(e,t)):""}function Ko(e,t){return t>0?e.length<=t?e:e.slice(Go(e,e.length-Math.trunc(t))):""}let Jo,Zo;function Xo(e,t){Jo??=new TextEncoder,Zo??=new Uint8Array(65536);let r=0,n=0;for(;r{const t=(0,Yo.o1)(e);try{return await(0,Co.realpath)(t)}catch{return t}},rs=1048576,ns=52428800;var os=r("../proto/dist/generated/agent/v1/sandbox_pb.js");function ss(e){if(!e)return;let t;return"allow"===e.default?t=os.h1.ALLOW:"deny"===e.default&&(t=os.h1.DENY),new os.RB({version:e.version,defaultAction:t,deny:e.deny??[],allow:e.allow??[],logging:e.logging?(r=e.logging,new os.Qq({decisionLogPath:r.decisionLogPath,logFormat:r.logFormat})):void 0});var r}function is(e){const t=function(e){if(!e)return;const t={};if(1===e.version&&(t.version=1),void 0!==e.defaultAction)switch(e.defaultAction){case os.h1.ALLOW:t.default="allow";break;case os.h1.DENY:t.default="deny"}return e.deny&&e.deny.length>0&&(t.deny=e.deny),e.allow&&e.allow.length>0&&(t.allow=e.allow),e.logging&&(t.logging=function(e){const t={};return e.decisionLogPath&&(t.decisionLogPath=e.decisionLogPath),"jsonl"===e.logFormat&&(t.logFormat="jsonl"),t}(e.logging)),t}(e.networkPolicy);return t||(e.networkAccess?(0,Oo.T6)():(0,Oo.Po)())}function as(e){switch(e){case"system":return os.Sz.SYSTEM;case"workspace":return os.Sz.WORKSPACE;default:return os.Sz.UNSPECIFIED}}function cs(e){const t=function(e){switch(e){case os.Sz.SYSTEM:return"system";case os.Sz.WORKSPACE:return"workspace";case os.Sz.UNSPECIFIED:default:return}}(e.readBoundary),r=e.additionalReadPaths??[];return{readBoundary:t,additionalReadPaths:"workspace"===t&&r.length>0?r:void 0,privateTmp:e.privateTmp}}function ls(e){if(!e)return{type:"insecure_none"};switch(e.type){case os.vc.INSECURE_NONE:case os.vc.UNSPECIFIED:return{type:"insecure_none",allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies};case os.vc.WORKSPACE_READWRITE:return{type:"workspace_readwrite",networkPolicy:is(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadwritePaths:e.additionalReadwritePaths,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict,...cs(e)};case os.vc.WORKSPACE_READONLY:return{type:"workspace_readonly",networkPolicy:is(e),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths,disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicyStrict:e.networkPolicyStrict,...cs(e)};default:return{type:"insecure_none"}}}function us(e){if(e)return"insecure_none"===e.type?new os.Mw({type:os.vc.INSECURE_NONE,allowlistEscalated:e.allowlistEscalated,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies}):"workspace_readwrite"===e.type?new os.Mw({type:os.vc.WORKSPACE_READWRITE,networkAccess:(0,Oo.$b)(e.networkPolicy),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadwritePaths:e.additionalReadwritePaths??[],additionalReadonlyPaths:e.additionalReadonlyPaths??[],disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicy:ss(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:as(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[],privateTmp:e.privateTmp}):"workspace_readonly"===e.type?new os.Mw({type:os.vc.WORKSPACE_READONLY,networkAccess:(0,Oo.$b)(e.networkPolicy),skipStatsigDefaults:e.skipStatsigDefaults,additionalReadonlyPaths:e.additionalReadonlyPaths??[],disableTmpWrite:e.disableTmpWrite,enableSharedBuildCache:e.enableSharedBuildCache,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,networkPolicy:ss(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,readBoundary:as(e.readBoundary),additionalReadPaths:"workspace"===e.readBoundary?e.additionalReadPaths??[]:[],privateTmp:e.privateTmp}):new os.Mw({type:os.vc.INSECURE_NONE})}function ds(e){return" "===e||"\t"===e||"\n"===e||"\r"===e||" "===e||"​"===e||"‌"===e||"‍"===e||"\ufeff"===e}function hs(e){let t="",r=!1;for(const n of e)ds(n)?r=!0:(r&&t.length>0&&(t+=" "),r=!1,t+=n);return t}function ps(e){if(0===e.length)return!1;for(let t=0;te.fullText))])]}const ws={a:"",b:"\b",e:"",E:"",f:"\f",n:"\n",r:"\r",t:"\t",v:"\v","\\":"\\","'":"'",'"':'"',"?":"?"};function ys(e){let t="",r="plain",n=0;for(;n=e.length){t+=o,n++;continue}const s=e[n+1],i=ws[s];if(void 0!==i){t+=i,n+=2;continue}const a="x"===s?e.slice(n+2).match(/^[0-9a-fA-F]{1,2}/)?.[0]:"u"===s?e.slice(n+2).match(/^[0-9a-fA-F]{1,4}/)?.[0]:"U"===s?e.slice(n+2).match(/^[0-9a-fA-F]{1,8}/)?.[0]:e.slice(n+1).match(/^[0-7]{1,3}/)?.[0],c="u"===s||"U"===s,l="x"===s||c?16:8;if(void 0!==a){const e=Number.parseInt(a,l);if(!c||e<=1114111){t+=c?String.fromCodePoint(e):String.fromCharCode(e),n+=a.length+(16===l?2:1);continue}}t+=s,n+=2}return hs(t)}function vs({rule:e,command:t}){const r=hs(e).trim();return 0!==r.length&&(null!==function(e){const t=hs(e).trim();if(0===t.length)return"Rule cannot be empty";if(t.length>512)return"Rule cannot exceed 512 characters";if(ps(t))return"Rule cannot match every command; be more specific than wildcards alone";if(t.startsWith(":"))return"Colon rules need an executable before `:` (e.g. `aws:*s3 rm*`)";const r=fs(t);if(void 0!==r){const{executablePattern:e,argsPattern:t}=r;if(ps(e)&&(0===t.length||ps(t)))return"Rule cannot match every command; narrow the executable or argument pattern"}return null}(r)||[t.trim(),hs(t).trim(),ys(t).trim()].some((e=>function(e,t){const r=fs(e);if(void 0!==r){const{executablePattern:e,argsPattern:n}=r,o=t.indexOf(" "),s=-1===o?t:t.slice(0,o),i=-1===o?"":t.slice(o+1).trim();if((0,ms.T)(e,s)&&(0,ms.T)(n,i))return!0}return e.includes("*")?(0,ms.T)(e,t):t===e||t.startsWith(`${e} `)}(r,e))))}function bs({matchForms:e,blockedCommands:t}){const r=t.map((e=>e.trim())).filter((e=>e.length>0));if(0===r.length)return;const n=e.map((e=>e.trim())).filter((e=>e.length>0)),o=n.length>0?n:[""];for(const e of r)if(o.some((t=>vs({rule:e,command:t}))))return e}function Ss(e){return`Denied: this command was blocked by administrator policy (denylist rule: ${e}) and was not executed. It cannot be approved from this conversation; only a user can run it manually outside the agent. You may continue working on the task.`}function ks({command:e,parsingResult:t,blockedCommands:r}){if(0===r.length)return;if(t.parsingFailed||0===t.executableCommands.length)return"Denied: this command could not be conclusively analyzed against your team's administrator command denylist, so it was blocked (fail-closed) and was not executed. It cannot be approved from this conversation; only a user can run it manually outside the agent. You may continue working on the task.";const n=bs({matchForms:gs({command:e,parsingResult:t}),blockedCommands:r});return void 0===n?void 0:Ss(n)}var _s=r("../utils/dist/test-resets.js");const Cs="CURSOR_FORCED_SHELL_EGRESS_NETWORK_DEFAULT",Es="CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_DENY_DOMAINS",xs=/\$\(|`|<\(|>\(/,Ps=/[;&|]/;let Rs,Is,Ts,As;function $s(){if(void 0===Rs){const e=(process.env.CURSOR_FORCED_SHELL_EGRESS??"").trim().toLowerCase();Rs=""!==e&&"0"!==e&&"false"!==e&&"off"!==e}return Rs}function Ms(e){const t=(process.env[e]??"").trim();if(t)try{return new RegExp(t,"i"),t}catch(t){throw new Error(`[forced-egress] invalid regex in ${e}: ${String(t)}`)}}function Ds(e){return(process.env[e]??"").split(",").map((e=>e.trim())).filter((e=>e.length>0))}function Os(e){const t=(process.env[e]??"").split(":").map((e=>e.trim())).filter((e=>e.length>0)),r=t.filter((e=>e.startsWith("/"))),n=t.length-r.length;return n>0&&console.error(`[forced-egress] ignoring ${n} non-absolute path(s) in ${e}.`),r}function Fs(){if(void 0===As){const e=(process.env[Cs]??"").trim().toLowerCase();let t="deny";"allow"===e||"deny"===e?t=e:""!==e&&console.error(`[forced-egress] ignoring invalid value in ${Cs} (expected "allow" or "deny"); using "deny".`);const r=Ds("CURSOR_FORCED_SHELL_EGRESS_DENY_DOMAINS"),n=(process.env[Es]??"").trim();let o=r;"none"===n.toLowerCase()?o=[]:""!==n&&(o=Ds(Es)),As={networkDefault:t,denyDomains:r,dependencyDenyDomains:o,allowDomains:Ds("CURSOR_FORCED_SHELL_EGRESS_ALLOW_DOMAINS"),writablePaths:Os("CURSOR_FORCED_SHELL_EGRESS_WRITABLE_PATHS")}}return As}function Ns(e,t,r={}){const n=[Ms(e),Ms(t)].filter((e=>void 0!==e)).map((e=>`(?:${e})`));if(0===n.length)return null;const o=n.join("|"),s=r.anchorToExecutable?`^\\s*(?:[A-Za-z_][A-Za-z0-9_]*=[^\\s]*\\s+)*(?:${o})`:o;return new RegExp(s,"i")}function Ls(e,t){const r=function(){const e=Fs();return{type:"workspace_readwrite",...e.writablePaths.length>0?{additionalReadwritePaths:e.writablePaths}:{},networkPolicy:{version:1,default:e.networkDefault,allow:["127.0.0.0/8","::1/128","localhost",...e.allowDomains],...e.denyDomains.length>0?{deny:e.denyDomains}:{}},networkPolicyStrict:!0,skipStatsigDefaults:!0,enableSharedBuildCache:!0}}(),n=(void 0===Is&&(Is=Ns("CURSOR_FORCED_SHELL_EGRESS_DEPENDENCY_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_DEPENDENCY_REGEX",{anchorToExecutable:!0})),Is);if(null===n)return r;const o=t?.executableCommands??[];if(t?.parsingFailed||0===o.length)return r;if(xs.test(e))return r;const s=(void 0===Ts&&(Ts=Ns("CURSOR_FORCED_SHELL_EGRESS_SOURCE_REGEX","CURSOR_FORCED_SHELL_EGRESS_EXTRA_SOURCE_REGEX")),Ts);for(const e of o){const t=e.fullText?.trim()||e.name?.trim()||"";if(!t||s?.test(t)||Ps.test(t))return r}return o.every((e=>n.test(e.fullText?.trim()||e.name?.trim()||"")))?function(){const e=Fs();return{type:"workspace_readwrite",...e.writablePaths.length>0?{additionalReadwritePaths:e.writablePaths}:{},networkPolicy:{version:1,default:"allow",...e.dependencyDenyDomains.length>0?{deny:e.dependencyDenyDomains}:{}},skipStatsigDefaults:!0,enableSharedBuildCache:!0}}():r}(0,_s.J)((function(){Rs=void 0,Is=void 0,Ts=void 0,As=void 0}));var js=r("../utils/dist/lru-cache.js");const Us=["Desktop","Documents","Downloads","Music","Movies","Pictures","Library",".Trash"],Bs="/Volumes";function Ws(e){const t=e.replace(/\/{2,}/g,"/");return t.length>1&&t.endsWith("/")?t.slice(0,-1):t}function Hs(e,t){if("darwin"!==t.platform)return[];const r=Ws(e),n=r.toLowerCase(),o=Ws(t.homeDirectory),s="/"===r?1:r.split("/").length;return[...Us.map((e=>`${o}/${e}`)),Bs].filter((e=>function(e,t){return e!==t&&e.startsWith(t.endsWith("/")?t:`${t}/`)}(e.toLowerCase(),n))).map((e=>{const t=e.split("/").slice(s).join("/");return`${"/"===r?"":r}/${t}`}))}var qs=r("../utils/dist/safe-spawn-cwd.js"),zs=r("node:util");const Gs=8388608;var Vs=r("../../node_modules/.pnpm/iconv-lite@0.7.0/node_modules/iconv-lite/lib/index.js"),Ks=r("../../node_modules/.pnpm/jschardet@3.1.4/node_modules/jschardet/index.js");function Js(e){let t=1,r=0;for(;;){const n=e.indexOf("\n",r);if(-1===n)return t;t++,r=n+1}}const Zs="utf8",Xs="utf8bom",Qs="latin1",Ys={"windows-1250":"cp1250","windows-1251":"cp1251","windows-1252":"cp1252","windows-1253":"cp1253","windows-1254":"cp1254","windows-1255":"cp1255","windows-1256":"cp1256","windows-1257":"cp1257","windows-1258":"cp1258","iso-8859-1":"iso88591","iso-8859-2":"iso88592","iso-8859-5":"iso88595","iso-8859-6":"iso88596","iso-8859-7":"iso88597","iso-8859-8":"iso88598","iso-8859-9":"iso88599","iso-8859-15":"iso885915","iso-8859-16":"iso885916",shift_jis:"shiftjis","euc-jp":"eucjp","euc-kr":"euckr","iso-2022-jp":"iso2022jp","iso-2022-kr":"iso2022kr",gb2312:"gb2312",gbk:"gbk",gb18030:"gb18030",big5:"big5","big5-hkscs":"big5hkscs","koi8-r":"koi8r","koi8-u":"koi8u",ibm855:"cp855",ibm866:"cp866",maccyrillic:"maccyrillic","x-mac-cyrillic":"maccyrillic","utf-16le":"utf16le","utf-16be":"utf16be","utf-32le":"utf32le","utf-32be":"utf32be",johab:"johab",cp949:"cp949",cp932:"cp932"};function ei(e){return Ys[e]||e}function ti(e){return e.startsWith("\ufeff")?e.slice(1):e}function ri(e){const t=e.toLowerCase();return"latin-1"===t?Qs:"utf-8"===t?Zs:"utf-8-bom"===t||"utf-8 bom"===t?Xs:t}function ni(e){const t=[],r=[];let n=0;for(let o=e.indexOf("\n");-1!==o;o=e.indexOf("\n",n)){const s=13===e.charCodeAt(o-1);t.push(e.slice(n,s?o-1:o)),r.push(s?"\r\n":"\n"),n=o+1}return t.push(e.slice(n)),r.push(""),{lines:t,ends:r}}const oi=new zs.TextDecoder("utf-8",{fatal:!1}),si=new zs.TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),ii="�";function ai(e){return oi.decode(e)}function ci(e){let t=0,r=0,n=0,o=0;for(let s=0;s0?o--:n++}return r+=n,r>t}function li(e,t=1/0){let r=0,n=0;for(;r=194&&r<=223)n=2;else if(r>=224&&r<=239)n=3,224===r&&(o=160),237===r&&(s=159);else{if(!(r>=240&&r<=244))return 1;n=4,240===r&&(o=144),244===r&&(s=143)}let i=1;for(;i(1===i?s:191))break;i++}return i===n?void 0:i}function di(e){return e<128?1:e<2048?2:e<65536?3:4}var hi;!function(e){e.CRLF="CRLF",e.LF="LF"}(hi||(hi={}));const pi=[".mp4",".webm",".mov",".avi",".mkv",".wmv",".flv",".m4v"],fi=new Set(pi),mi=new zs.TextDecoder("utf-8",{fatal:!0}),gi=new zs.TextDecoder("latin1"),wi=Buffer.from([239,187,191]),yi={utf16le:Buffer.from([255,254]),utf16be:Buffer.from([254,255]),utf32le:Buffer.from([255,254,0,0]),utf32be:Buffer.from([0,0,254,255])},vi=8192,bi="UTF-8",Si="windows-1252",ki=/[^\u0000-\u007f\ufffd]/u,_i=/(?:\p{Script=Cyrillic}\p{M}*){3,}/gu,Ci=/(?:\p{Script=Greek}\p{M}*){3,}/gu,Ei=/(?:\p{Script=Hebrew}\p{M}*){3,}/gu,xi=new Map([["windows-1251",_i],["ISO-8859-5",_i],["KOI8-R",_i],["x-mac-cyrillic",_i],["IBM866",_i],["IBM855",_i],["ISO-8859-7",Ci],["windows-1253",Ci],["windows-1255",Ei],["ISO-8859-8",Ei],["TIS-620",/(?:\p{Script=Thai}\p{M}*){3,}/gu]]),Pi=/\p{Script=Latin}\p{M}*[\p{Script=Cyrillic}\p{Script=Greek}\p{Script=Hebrew}\p{Script=Thai}]|[\p{Script=Cyrillic}\p{Script=Greek}\p{Script=Hebrew}\p{Script=Thai}]\p{M}*\p{Script=Latin}/u,Ri=/[\p{L}\p{M}]+/gu,Ii=String.raw`[\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF\u0152\u0153\u0160\u0161\u017D\u017E\u0178]`,Ti=new RegExp(`[A-Za-z]${Ii}{1,2}(?!${Ii})|^${Ii}{1,2}[A-Za-z]`,"u"),Ai=new Map,$i=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".pdf",".zip",".tar",".gz",".exe",".dll",".so",".dylib",".bin",...pi]),Mi=/\.(png|jpg|jpeg|gif|webp|ico|bmp)$/i,Di=new Set([".ps1",".psm1",".psd1"]),Oi=/[^\u0000-\u007f]/u;function Fi(e){const t=e.toLowerCase(),r=t.lastIndexOf(".");return-1===r?"":t.substring(r)}function Ni(e){const t=Fi(e);return fi.has(t)}function Li(e){const t=Fi(e);return{encoding:"binary",lineEnding:hi.LF,isBinaryFile:!0,isImageFile:Mi.test(t),isVideoFile:fi.has(t)}}async function ji(e,t){return(await Ui(e,t)).text}async function Ui(e,t){const{stamp:r,buf:n}=await async function(e){const t=await(0,Co.open)(e,"r");try{return{stamp:await t.stat(),buf:await t.readFile()}}finally{await t.close()}}(e),o=qi(n);if(o.isBinaryFile)throw new Error("Binary file cannot be decoded as text");const s=Qi(e,r);let i;i=t||s||o.encoding;const{text:a,encoding:c}=ta(n,i),l=ti(a),u=c===Zs&&ra(n)?Xs:c;Yi(e,r,u);const d=function(e,t){if(t===Xs)return ra(e);const r=yi[ei(ri(t))];return void 0!==r&&e.subarray(0,r.length).equals(r)}(n,u);if(o.lineEnding===hi.CRLF){const e=l.match(/\r\n/g)?.length??0,t=(l.match(/\n/g)?.length??0)-e;return{text:l.replaceAll("\r\n","\n"),encoding:u,bom:d,lineEnding:e>t?"CRLF":"LF"}}return{text:l,encoding:u,bom:d,lineEnding:"LF"}}async function Bi(e,t){if("binary"===t.encoding)return void Xi(e);let r;try{r=await(0,Co.stat)(e)}catch{return void Xi(e)}r.size===t.buffer.byteLength?Yi(e,r,t.encoding):Xi(e)}async function Wi(e,t,r,o){let s,i;try{s=r?await async function(e,t){try{return await Hi(e)}catch{}const r=Fi(e);if($i.has(r))return Li(e);try{return await async function(e){const t=new Map;let r=0;for await(const n of Ji(e)){if(r>=100)break;try{const e=await Hi(n);if(!e.isBinaryFile){const r=`${e.encoding}:${e.lineEnding}`,n=t.get(r);if(n){if(n.count++,n.count>=3)return n.format}else t.set(r,{format:e,count:1})}r++}catch(e){}}let n;for(const e of t.values())(!n||e.count>n.count)&&(n=e);return n?n.format:Zi()}(t)}catch{return Zi()}}(e,r):await Hi(e)}catch{const t=Fi(e);s=$i.has(t)?Li(e):Zi()}const a=()=>i??=async function(e){try{const t=await(0,Co.stat)(e);if(!t.isFile()||t.size>Gs)return;return await(0,Co.readFile)(e)}catch{return}}(e),c=Qi(e,await async function(e){try{return await(0,Co.stat)(e)}catch{return}}(e));let l;if(!s.isBinaryFile){let r;o?r=ri(o):c?r=ri(c):(r=ri(s.encoding),r===Xs||Vs.encodingExists(ei(r))||(r=Zs),r!==Zs&&r!==Xs||(r=await async function(e,t){const r=await t();return void 0===r||(0,n.isUtf8)(r)?e:ea(r).encoding===Qs?Qs:e}(r,a))),r===Zs&&!o&&function(e,t){return"win32"===process.platform&&Di.has(Fi(e))&&Oi.test(t)&&!t.startsWith("#!")}(e,t)&&(await async function(e){try{return await(0,Co.stat)(e),!1}catch(e){return e instanceof Error&&"code"in e&&"ENOENT"===e.code}}(e)||await async function(e){const t=await e();return void 0!==t&&(0,n.isAscii)(t)}(a))&&(r=Xs);const i=r===Xs||r===Zs&&!o&&await na(e,wi),u=yi[ei(r)];i?l=wi:u&&await na(e,u)&&(l=u),s={...s,encoding:i?Xs:r}}const u=Js(t),d=t.includes("\r\n")?void 0:await async function(e,t){if(t.isBinaryFile)return;const r=await e();if(void 0===r||!r.includes(13))return;const n=ti(ta(r,t.encoding).text);return function(e){let t=!1,r=!1;for(let n=e.indexOf("\n");-1!==n;n=e.indexOf("\n",n+1))if(13===e.charCodeAt(n-1)?t=!0:r=!0,t&&r)return!0;return!1}(n)?n:void 0}(a,s);if(void 0!==d?t=function({content:e,existing:t,defaultEnding:r}){const n=ni(t),o=ni(e),s=function({before:e,after:t}){const r=new Int32Array(t.length).fill(-1);let n=0;for(;n0&&i>0&&(s+1)*(i+1)<=4e6){const o=i+1,a=new Uint16Array((s+1)*o);for(let r=s-1;r>=0;r--)for(let s=i-1;s>=0;s--)a[r*o+s]=e[n+r]===t[n+s]?a[(r+1)*o+s+1]+1:Math.max(a[(r+1)*o+s],a[r*o+s+1]);for(let c=0,l=0;c=a[c*o+l+1]?c++:l++}let a=-1,c=-1;for(let n=0;n<=t.length;n++){const o=n===t.length?e.length:r[n];if(-1!==o){if(o-a==n-c)for(let e=1;e50&&/^[A-Za-z0-9+/]*={0,2}$/.test(t))try{const e=Buffer.from(t,"base64");if(e.length>0){const r=Math.floor(.5*t.length);if(e.length>=r)return e}}catch{}return Buffer.from(e,"latin1")}(t);return{lines:u,buffer:e,format:s}}const h=l?ti(t):t,p=s.encoding===Xs?Zs:s.encoding,f=p===Zs?await async function(e,t){if(!t.includes(ii))return;const r=await e();return void 0===r?void 0:function(e,t){if(!e.includes(ii)||(0,n.isUtf8)(t))return;const r=function(e){const t=[];let r=0;for(const n of si.decode(e)){const o=n.codePointAt(0)??0;if(65533!==o){r+=di(o);continue}const s=ui(e,r);void 0===s?(t.push(void 0),r+=3):(t.push(e.subarray(r,r+s)),r+=s)}return r===e.length?t:void 0}(t),o=e.split(ii);if(void 0===r||o.length-1!==r.length)return;const s=[];for(let e=0;e=Math.max(0,e.length-3);t--){const r=e[t];if(r<128)return e;if(r>=192){const n=r>=240?4:r>=224?3:2;return e.length-t=e.length);o+=2){if(0===e[o+1]){const r=e[o];(r>=32&&r<=126||9===r||10===r||13===r)&&t++}if(0===e[o]){const t=e[o+1];(t>=32&&t<=126||9===t||10===t||13===t)&&r++}}return t>.8*n?"UTF-16LE":r>.8*n?"UTF-16BE":null}(e)??function(e){if(e.length<8)return null;if(0===e[0]&&0===e[1]&&254===e[2]&&255===e[3])return"UTF-32BE";if(255===e[0]&&254===e[1]&&0===e[2]&&0===e[3])return"UTF-32LE";let t=0,r=0;const n=Math.min(50,Math.floor(e.length/4));for(let o=0;o<4*n&&!(o+3>=e.length);o+=4){if(0===e[o]&&0===e[o+1]&&0===e[o+2]){const r=e[o+3];(r>=32&&r<=126||9===r||10===r||13===r)&&t++}if(0===e[o+1]&&0===e[o+2]&&0===e[o+3]){const t=e[o];(t>=32&&t<=126||9===t||10===t||13===t)&&r++}}return t>.8*n?"UTF-32BE":r>.8*n?"UTF-32LE":null}(e);if(t)return{encoding:t,lineEnding:Gi(Vs.decode(e.subarray(0,vi),ei(ri(t)))),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};if(!function(e){const t=Math.min(vi,e.length);if(0===t)return!0;for(let r=0;r=8&&137===r[0]&&80===r[1]&&78===r[2]&&71===r[3]&&13===r[4]&&10===r[5]&&26===r[6]&&10===r[7]||255===r[0]&&216===r[1]&&255===r[2]||r.length>=12&&82===r[0]&&73===r[1]&&70===r[2]&&70===r[3]&&87===r[8]&&69===r[9]&&66===r[10]&&80===r[11]||r.length>=6&&71===r[0]&&73===r[1]&&70===r[2]&&56===r[3]&&(55===r[4]||57===r[4])&&97===r[5])),isVideoFile:!1};var r,o,s;if((0,n.isUtf8)(e)&&(!e.includes(27)||!(0,n.isAscii)(e)))return{encoding:bi,lineEnding:zi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};if(!(0,n.isUtf8)(e)&&(o=ai(e),s=e.length,ci(o)||1024*li(o)<=s&&!ki.test(o)))return{encoding:bi,lineEnding:zi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1};const i=Ks.detect(e);let a=i.confidence>.7?i.encoding:"utf-8";"ascii"===a&&(a="utf-8");const c=xi.get(a);return void 0!==c&&(a=function(e,t,r){const n=ei(ri(t));if(!Vs.encodingExists(n))return t;const o=Vs.decode(e,n);return Pi.test(o)&&function(e,t,r){const n=t.match(r)?.length??0;let o=0;for(const[t]of Vs.decode(e,Si).matchAll(Ri))Ti.test(t)&&o++;return o>n}(e,o,r)?Si:t}(e,a,c)),a!==Si||function(e,t){const r=ei(ri(t));return!Vs.getDecoder(r).write(e).includes(ii)}(e,a)||(a="utf-8"),{encoding:a??"utf-8",lineEnding:zi(e),isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function zi(e){let t=0,r=0;for(let n=0;n0&&13===e[n-1]?t++:r++);return Vi(t,r)}function Gi(e){const t=e.match(/\n/g)?.length??0,r=e.match(/\r\n/g)?.length??0;return Vi(r,t-r)}function Vi(e,t){return 0===e&&0===t?hi.LF:e/(e+t)*100>=5?hi.CRLF:hi.LF}async function Ki(e){const t=await(0,Co.open)(e,"r");try{const e=Buffer.allocUnsafe(vi),{bytesRead:r}=await t.read(e,0,vi,0);return e.subarray(0,r)}finally{await t.close()}}async function*Ji(e){const t=new Set(["node_modules",".git",".svn",".hg","dist","build","out",".next",".cache","coverage","__pycache__",".venv","venv",".turbo"]);try{const r=await(0,Co.readdir)(e,{withFileTypes:!0});for(const n of r){if(n.name.startsWith(".")&&".gitignore"!==n.name)continue;const r=(0,s.join)(e,n.name);n.isDirectory()?t.has(n.name)||(yield*Ji(r)):n.isFile()&&(yield r)}}catch(e){return}}function Zi(){return{encoding:Zs,lineEnding:"win32"===process.platform?hi.CRLF:hi.LF,isBinaryFile:!1,isImageFile:!1,isVideoFile:!1}}function Xi(e){Ai.delete(e)}function Qi(e,t){const r=Ai.get(e);if(void 0!==r)return void 0!==t&&r.size===t.size&&r.mtimeMs===t.mtimeMs?r.encoding:void Ai.delete(e)}function Yi(e,t,r){if(Ai.has(e)&&Ai.delete(e),Ai.set(e,{encoding:r,size:t.size,mtimeMs:t.mtimeMs}),Ai.size<=100)return;const n=Ai.keys().next().value;void 0!==n&&Ai.delete(n)}function ea(e){try{return{text:mi.decode(e),encoding:Zs}}catch{const t=ai(e);return ci(t)?{text:t,encoding:Zs}:{text:gi.decode(e),encoding:Qs}}}function ta(e,t){const r=ri(t);if(r===Zs||r===Xs||"ascii"===r){const t=ea(e);return r===Xs&&t.encoding===Zs?{text:t.text,encoding:Xs}:t}if(r===Qs)return{text:gi.decode(e),encoding:Qs};try{const t=ei(r);if(Vs.encodingExists(t))return{text:Vs.decode(e,t),encoding:r}}catch{}return ea(e)}function ra(e){return e.length>=wi.length&&e[0]===wi[0]&&e[1]===wi[1]&&e[2]===wi[2]}async function na(e,t){try{return(await Ki(e)).subarray(0,t.length).equals(t)}catch{return!1}}var oa=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js");class sa{constructor({ttlMs:e,now:t=Date.now}){this.entries=new Map,this.nextSweepAtMs=0,this.ttlMs="function"==typeof e?e:sa.validated(e),this.now=t}static validated(e){if(!Number.isFinite(e)||e<=0)throw new Error(`TTL cache requires a positive ttlMs, got ${e}`);return()=>e}get(e){const t=this.entries.get(e);if(void 0!==t){if(!(t.expiresAtMs<=this.now()))return t.value;this.entries.delete(e)}}has(e){const t=this.entries.get(e);return!(void 0===t||t.expiresAtMs<=this.now()&&(this.entries.delete(e),1))}get size(){return this.entries.size}set(e,t){const r=this.now(),n=this.ttlMs();if(this.entries.set(e,{value:t,expiresAtMs:r+n}),!(r1048576?e:await async function(e,t){const r=function(e){const t=Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=qi(t);return r.isBinaryFile?ai(t):ti(ta(t,r.encoding).text)}(t);return function(e,t){if(!(0,n.isUtf8)(e))return!1;const r=e.toString("utf8");return(r.startsWith("\ufeff")?r.slice(1):r)===t}(t,r)?e:async function(e,t){const r=await(la??=(0,Co.mkdtemp)((0,s.join)((0,o.tmpdir)(),"cursorignore-utf8-")).then((e=>(process.once("exit",(()=>{try{(0,xo.rmSync)(e,{recursive:!0,force:!0})}catch{}})),e))),la),n=(0,s.join)(r,`cursorignore-${ua(e)}-${ua(t)}.txt`);if(await da(n))return n;const i=`${n}.${process.pid}.${Date.now()}.tmp`;return await(0,Co.writeFile)(i,t,"utf8"),await(0,Co.rename)(i,n),n}(e,r)}(e,await(0,Co.readFile)(e));return aa.set(e,{mtimeMs:t.mtimeMs,size:t.size,ripgrepPath:i}),i}function pa(e){return Promise.all(e.map((e=>async function(e){const t=ca.get(e);if(void 0!==t)return t;const r=ha(e).catch((()=>e)).finally((()=>{ca.delete(e)}));return ca.set(e,r),r}(e))))}(0,_s.J)((function(){aa.clear(),ca.clear()}));var fa=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function ma(e){if(e.aborted)return{aborted:Promise.resolve("aborted"),[Symbol.dispose](){}};let t=()=>{};const r=new Promise((e=>{t=()=>e("aborted")}));return e.addEventListener("abort",t,{once:!0}),{aborted:r,[Symbol.dispose](){e.removeEventListener("abort",t)}}}function ga(e,{root:t,searchPaths:r=[],includeGlobs:n=[],excludeGlobs:s=[],caseSensitive:i=!1,cursorIgnoreFiles:a=[],sandboxPolicy:c={type:"insecure_none"},noIgnoreVcs:l=!1,followSymlinks:u=!1,source:d="ripwalk"}){const h=["--files","--hidden","--no-require-git","--no-config","--color=never"],p=function(e=process.env){const t=e.CURSOR_RIPWALK_THREADS?.trim();if(void 0!==t&&""!==t){const e=Number(t);if(Number.isInteger(e)&&e>=0)return 0===e?void 0:e}return Math.min(2,(0,o.availableParallelism)())}();void 0!==p&&h.push("--threads",String(p)),u&&h.push("--follow"),l&&h.push("--no-ignore-vcs"),i&&h.push("--case-sensitive");for(const e of n)h.push("--iglob",e);for(const e of s)h.push("--iglob",`!${e}`);const f=r.length>0?["--",...r]:[];let m,g=!1;const w=new Promise((e=>{m=e}));return{lines:async function*(){const r={stack:[],error:void 0,hasError:!1};try{const n=[];for(const e of await pa(a))n.push("--cursor-ignore",e);const o=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,function(e,t,r,n){const o=(0,Oo.spawnInSandbox)((0,Oo.Ko)(),t,{cwd:r},n),s=[];o.stderr?.on("data",(e=>{s.push(e)}));const i=new Promise(((e,t)=>{o.on("error",t),o.on("close",(t=>e(t??0)))}));if(i.catch((()=>{})),!o.stdout)throw new Error("No stdout from ripgrep process");const a=ma(e.signal);return{stdout:o.stdout,processExit:i,stderr:()=>Buffer.concat(s).toString(),aborted:a.aborted,[Symbol.dispose](){a[Symbol.dispose](),o.kill()}}}(e,[...h,...n,...f],t,c),!1);let s=0;const i=async function*(e){const t=new ia.StringDecoder("utf8");let r="";for await(const n of e){r+=t.write(n);const e=r.split("\n");r=e.pop()??"",e.length>0&&(yield e)}r+=t.end(),r&&(yield[r])}(o.stdout)[Symbol.asyncIterator]();e:for(;;){const t=await Promise.race([i.next(),o.aborted]);if("aborted"===t){g=!0,m(!0);break}if(t.done)break;for(const r of t.value){if(e.signal.aborted){g=!0,m(!0);break e}s++,yield r}}if(s>0);else if(!g){const e=await o.processExit;if(0!==e&&1!==e){const t=o.stderr();throw new Error(`Ripgrep failed (exit ${e}) with no results${t?`: ${t}`:""}`)}}g||m(!1)}catch(e){r.error=e,r.hasError=!0}finally{fa(r)}}(),didTimeout:w}}var wa=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});let ya;function va(e=process.env){if(void 0!==ya)return ya;const t=e.CURSOR_RIPWALK_CACHE_TTL_MS?.trim();if(void 0!==t&&""!==t){const e=Number(t);if(Number.isFinite(e)&&e>0)return e}return 2e4}function ba({root:e,searchPaths:t=[],includeGlobs:r=[],excludeGlobs:n=[],caseSensitive:o=!1,cursorIgnoreFiles:s=[],sandboxPolicy:i={type:"insecure_none"},noIgnoreVcs:a=!1,followSymlinks:c=!1}){return JSON.stringify({root:e,searchPaths:t,includeGlobs:r,excludeGlobs:n,caseSensitive:o,cursorIgnoreFiles:s,sandboxPolicy:i,noIgnoreVcs:a,followSymlinks:c})}class Sa{constructor(e=()=>va()){this.cache=new sa({ttlMs:e})}get size(){return this.cache.size}clear(){this.cache.clear()}delete(e){this.cache.delete(ba(e))}walk(e,t){const r=ba(t);let n,o=!1,s=!1;const i=new Promise((e=>{n=e})),a=e=>{s||(s=!0,n(e))};return{lines:async function*(){const n=this.cache.get(r);if(void 0!==n){const t={stack:[],error:void 0,hasError:!1};try{const s=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,ma(e.signal),!1),i=await Promise.race([n.linesPromise.then((e=>({type:"lines",lines:e})),(e=>({type:"error",error:e}))),s.aborted.then((()=>({type:"aborted"})))]);if("aborted"===i.type)return o=!0,void a(!0);if("lines"===i.type)return a(!1),void(yield*i.lines);this.cache.get(r)===n&&this.cache.delete(r)}catch(e){t.error=e,t.hasError=!0}finally{wa(t)}}let s,i;const c={linesPromise:new Promise(((e,t)=>{s=e,i=t}))};c.linesPromise.catch((()=>{})),this.cache.set(r,c);const l=[];let u,d=!1;try{const r=ga(e,t);for await(const e of r.lines)l.push(e),yield e;if(await r.didTimeout)return o=!0,u=new Error("Ripwalk aborted before cacheable result was available"),void a(!0);d=!0}catch(e){throw u=e,e}finally{d?s?.(l):(this.cache.get(r)===c&&this.cache.delete(r),i?.(u??new Error("Ripwalk terminated before cacheable result was available"))),o||a(!1)}}.bind(this)(),didTimeout:i}}}const ka=16777216,_a=new Set([32,9,10,13]),Ca="a path through /proc or /dev/fd",Ea={kind:"none"},xa={kind:"stop"};function Pa(e,t){return{kind:"refused",refused:{name:e,reason:t}}}async function Ra(e){const t=await async function(e){if(void 0===await(0,Co.lstat)(e).catch((()=>{})))return Ea;if(await Aa(Buffer.from(e)))return Pa(".git",Ca);const t=await(0,Co.stat)(e).catch((()=>{}));if(void 0===t)return Ea;if(!t.isFile())return Ia(e);const r=await Oa(e,{whole:1048576});if("not-regular"===r.kind)return Pa(".git","not a regular file");if("bytes"!==r.kind)return xa;const n=Buffer.from("gitdir: "),o=ja(r.bytes);if(!o.subarray(0,n.length).equals(n)||o.length<=n.length)return xa;const i=La({dir:(0,s.dirname)(e),target:Ua(o.subarray(n.length))});if(await Aa(i))return Pa(".git",Ca);const a=await Ia(i);return"none"===a.kind?xa:a}(Na(e,".git").toString());return"none"!==t.kind?t:Ia(e)}async function Ia(e){const t=await async function(e){const t=await(0,Co.lstat)(e).catch((()=>{}));if(void 0===t||t.isDirectory())return Ea;if(t.isSymbolicLink()){const t=await(0,Co.readlink)(e,{encoding:"buffer"}).catch((()=>{}));return"refs/"===t?.subarray(0,5).toString("latin1")?"valid":Ea}if(!t.isFile())return Pa("HEAD","not a regular file");const r=await Oa(e,{prefix:255});if("not-regular"===r.kind)return Pa("HEAD","not a regular file");if("bytes"!==r.kind)return Ea;const n=Ua(r.bytes.subarray(0,255)).toString("latin1");if(n.startsWith("ref:")){let e=4;for(;e{}))){if(await Aa(n))return Pa("commondir",Ca);const t=await Oa(n,{whole:ka});switch(t.kind){case"bytes":{if(0===t.bytes.length)return xa;const n=La({dir:e,target:Ua(ja(t.bytes))});if(await Aa(n))return Pa("commondir",Ca);const o=await(0,Co.realpath)(n,{encoding:"buffer"}).catch((()=>{}));if(void 0===o)return Ea;r=o;break}case"too-large":return Pa("commondir","over the size cap");case"not-regular":return Pa("commondir","not a regular file");case"directory":case"unreadable":return xa;default:throw new Error(`unhandled read ${String(t)}`)}}for(const e of["objects","refs"]){const t=Na(r,e);if(await Aa(t))return Pa(e,Ca);if(!await Fa(t))return Ea}return{kind:"repository",gitDir:e,commonDir:r}}async function Ta({gitDir:e,commonDir:t}){const r=[["HEAD",Na(e,"HEAD")],["config.worktree",Na(e,"config.worktree")],["config",Na(t,"config")],["info/exclude",Na(Na(t,"info"),"exclude")]];for(const[e,t]of r){if(await Aa(t))return{name:e,reason:Ca};const r=await(0,Co.stat)(t).catch((()=>{}));if(void 0!==r&&!r.isDirectory()&&!await Da(r)){if(!r.isFile())return{name:e,reason:"not a regular file"};if(r.size>ka)return{name:e,reason:"over the size cap"}}}}async function Aa(e){if("win32"===process.platform)return!1;const t=$a(e.toString("latin1")).reverse();let r="/",n=0;for(let e=t.pop();void 0!==e;e=t.pop()){if(".."===e){r=(0,s.dirname)(r);continue}const o=(0,s.join)(r,e),i="darwin"===process.platform?o.toLowerCase():o;if(["/proc","/dev/fd"].some((e=>i===e||i.startsWith(`${e}/`))))return!0;const a=await(0,Co.readlink)(Buffer.from(o,"latin1"),{encoding:"buffer"}).catch((()=>{}));if(void 0===a){r=o;continue}if(++n>40)return!1;const c=a.toString("latin1");(0,s.isAbsolute)(c)&&(r="/"),t.push(...$a(c).reverse())}return!1}function $a(e){return e.split("/").filter((e=>""!==e&&"."!==e))}let Ma;async function Da(e){if(!e.isCharacterDevice())return!1;Ma??=(0,Co.stat)("/dev/null").catch((()=>{}));const t=await Ma;return void 0!==t&&e.dev===t.dev&&e.ino===t.ino}async function Oa(e,t){const r=xo.constants.O_RDONLY|(xo.constants.O_NONBLOCK??0)|(xo.constants.O_NOCTTY??0),n=await(0,Co.open)(e,r).catch((()=>{}));if(void 0===n)return{kind:"unreadable"};try{const e=await n.stat();if(e.isDirectory())return{kind:"directory"};if(!e.isFile())return{kind:"not-regular"};if("whole"in t&&e.size>t.whole)return{kind:"too-large"};const r="whole"in t?t.whole:t.prefix,o=Buffer.alloc(Math.min(r+1,e.size+1));let s=0;for(;st.whole?{kind:"too-large"}:{kind:"bytes",bytes:o.subarray(0,s)}}catch{return{kind:"unreadable"}}finally{await n.close().catch((()=>{}))}}function Fa(e){return(0,Co.access)(e,xo.constants.X_OK).then((()=>!0),(()=>!1))}function Na(e,t){const r=Buffer.isBuffer(e)?e:Buffer.from(e),n=r.toString("latin1").endsWith(s.sep)?"":s.sep;return Buffer.concat([r,Buffer.from(`${n}${t}`)])}function La({dir:e,target:t}){return(0,s.isAbsolute)(t.toString("latin1"))?t:Buffer.concat([Na(e,""),t])}function ja(e){let t=e.length;for(;t>0&&(10===e[t-1]||13===e[t-1]);)t--;return e.subarray(0,t)}function Ua(e){const t=e.indexOf(0);return-1===t?e:e.subarray(0,t)}const Ba=[{stage:"prod",gitHost:"origin.cursor.com",gitCdnHost:"gitcdn.origin.cursor.com",cloneKitS3Host:"git-forge-prod-bundles.s3.us-east-1.amazonaws.com",rawUserContentHost:"raw.cursorusercontent.com",apiHost:"api.origin.cursor.com",internalHost:"origin-prod.internal.cursor.com"},{stage:"staging",gitHost:"origin-staging.cursor.com",gitCdnHost:"gitcdn.origin-staging.cursor.com",cloneKitS3Host:"git-forge-staging-bundles.s3.us-east-1.amazonaws.com",rawUserContentHost:"raw.staging.cursorusercontent.com",apiHost:"api.origin-staging.cursor.com",internalHost:"origin-staging.internal.cursor.com"},{stage:"test",gitHost:"origin-test.cursor.com",gitCdnHost:"gitcdn.origin-test.cursor.com",cloneKitS3Host:"git-forge-test-bundles.s3.us-east-1.amazonaws.com",rawUserContentHost:"raw.test.cursorusercontent.com",apiHost:"api.origin-test.cursor.com",internalHost:"origin-test.internal.cursor.com"}];function Wa(e){let t=e.length;for(;t>0&&47===e.charCodeAt(t-1);)t--;const r=e.slice(0,t).replace(/\.git$/i,"");return r&&"/"!==r?r.startsWith("/")?r:`/${r}`:""}function Ha(e,t){const r=Wa(t);return r?`${e}${r}`.toLowerCase():""}new Map(Ba.map((e=>[e.gitHost,e.apiHost]))),new Map(Ba.map((e=>[e.gitHost,e.gitCdnHost]))),new Map(Ba.map((e=>[e.gitHost,e.cloneKitS3Host]))),new Map(Ba.map((e=>[e.gitHost,e.rawUserContentHost]))),new Map(Ba.map((e=>[e.apiHost,e.gitHost]))),new Map(Ba.map((e=>[e.apiHost,e.internalHost])));const qa=new Map;function za(e){const t=qa.get(e);if(void 0!==t)return t;const r=function(e){const t=e.trim();if(!t)return"";try{const e=function(e){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(e))return e;const t=`https://${e}`;try{return new URL(t),t}catch{const r=e.match(/^([^@/\s]+@)?([^:/\s]+):(.+)$/);return r?`ssh://${r[1]??""}${r[2]}/${r[3]}`:t}}(t),r=new URL(e);return Ha(r.hostname,r.pathname)}catch{const e=t.replace(/^(?:https?|ssh|git):\/\//i,""),r=e.indexOf("/"),n=-1===r?e:e.slice(0,r),o=-1===r?"":e.slice(r);return Ha(n.includes("@")?n.slice(n.lastIndexOf("@")+1):n,o)}}(e);return qa.size>=16384&&qa.clear(),qa.set(e,r),r}function Ga(e){return/^origin(-[a-z0-9]+)?\.cursor\.com$/i.test(e)}(function(e){const t=Ba.find((t=>t.stage===e));if(void 0===t)throw new Error(`unknown Origin stage: ${e}`);return t})("prod").gitHost;const Va=new Map;function Ka(e){if(void 0===e)return;if(Va.has(e))return Va.get(e);const t=function(e){const t=e?function(e){let t=e.trim();if(""!==t){t.startsWith("git@")?t=`https://${t.slice(4).replace(":","/")}`:/^[a-z][a-z0-9+.-]*:\/\//i.test(t)&&!/^https?:\/\//i.test(t)?t=t.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"https://"):/^https?:\/\//i.test(t)||(t=`https://${t}`);try{return new URL(t)}catch{return}}}(e):void 0;if(void 0===t||!Ga(t.hostname))return;const r=Wa(t.pathname).split("/").filter(Boolean),n=3===r.length&&"git"===r[0]?.toLowerCase(),o=2===r.length&&"git"!==r[0]?.toLowerCase();if(!n&&!o)return;const s=n?r[1]:r[0],i=n?r[2]:r[1];return s&&i?Object.freeze({hostname:t.hostname,owner:s,name:i}):void 0}(e);return Va.size>=16384&&Va.clear(),Va.set(e,t),t}function Ja(e){return void 0!==function(e){const t=Ka(e);return void 0===t?void 0:{owner:t.owner,name:t.name}}(e)}new Set(["github.com","www.github.com"]),new RegExp("^tmp-[0-9a-f]{16}$");const Za=(0,l.h)("local-exec:git-root"),Xa=new WeakMap,Qa=new Map;function Ya(e,t,r){return ec(e,t,r).then((e=>"repository"===e.kind?e.root:null))}function ec(e,t,r){const n=performance.now();let o=Xa.get(t);void 0===o&&(o=new Map,Xa.set(t,o));const s=o.get(r);if(void 0!==s&&tc(s,n))return s.result;for(const[e,t]of o)tc(t,n)||o.delete(e);const i=t.guardedRootLookup,a=void 0===i?{result:oc(e,t,r,void 0),windowStart:n}:{result:rc(e,t,r,i.timeoutMs),windowStart:void 0};return void 0===a.windowStart&&a.result.then((()=>{a.windowStart=performance.now()})),o.set(r,a),a.result}function tc(e,t){return void 0===e.windowStart||t-e.windowStart<5e3}async function rc(e,t,r,n){const o=new AbortController,i=performance.now()+n,a=await(0,Or.wj)(async function({ctx:e,gitExecutor:t,startPath:r,deadline:n,settled:o}){const i=await function(e){let t=Qa.get(e);if(void 0===t){t=async function(e){const t=await(0,Co.realpath)(e).catch((()=>{}));if(void 0===t)return;const r=function(){const e=(process.env.GIT_DISCOVERY_ACROSS_FILESYSTEM??"").toLowerCase();return!["","0","false","no","off"].includes(e)}()?void 0:(await(0,Co.stat)(t).catch((()=>{})))?.dev;for(let e=t;;){const t=await Ra(e);switch(t.kind){case"refused":return t.refused;case"stop":return;case"repository":return Ta(t);case"none":break;default:throw new Error(`unhandled probe ${String(t)}`)}const n=(0,s.dirname)(e);if(n===e||void 0!==r&&(await(0,Co.stat)(n).catch((()=>{})))?.dev!==r)return;e=n}}(e),Qa.set(e,t);const r=()=>{Qa.delete(e)};t.then(r,r)}return t}(r);if(o.aborted)return{kind:"unknown",reason:"timed-out"};if(void 0!==i)return Za.warn(e,"findGitRoot: not starting git; its answer is unknown",{adminFile:i.name,reason:i.reason}),{kind:"unknown",reason:"refused"};const a=Math.ceil(n-performance.now());return a<=0?{kind:"unknown",reason:"timed-out"}:oc(e,t,r,a)}({ctx:e,gitExecutor:t,startPath:r,deadline:i,settled:o.signal}),n).catch((t=>t instanceof Or.MU?{kind:"unknown",reason:"timed-out"}:(Za.warn(e,"findGitRoot: the admin file check failed; not starting git",{code:nc(t)}),{kind:"unknown",reason:"refused"}))).finally((()=>{o.abort()}));return"unknown"===a.kind&&"timed-out"===a.reason&&Za.warn(e,"findGitRoot: the lookup ran past its bound; its answer is unknown",{timeoutMs:n}),a}function nc(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:void 0}async function oc(e,t,r,n){try{return{kind:"repository",root:(await t.exec(e,r,["rev-parse","--show-toplevel"],{...void 0===n?{}:{timeout:n},caller:"findGitRoot"})).stdout.trim()}}catch(e){return void 0!==n&&function(e){return"object"==typeof e&&null!==e&&"killed"in e&&!0===e.killed}(e)?{kind:"unknown",reason:"timed-out"}:{kind:"none"}}}async function sc(e,t,r){try{return(await t.exec(e,r,["config","--get","remote.origin.url"],{caller:"getGitRemoteUrl"})).stdout.trim()}catch{return}}function ic(e){const t=e.trim();if(""===t)return t;try{const e=new URL(t);return""===e.host?cc(t)??e.toString():(e.username="",e.password="",e.toString())}catch{return function(e){const t=e.replace(/^[\u0000-\u0020]+|[\u0000-\u0020]+$/g,"").replace(/[\t\n\r]/g,""),r=t.indexOf(":"),n=t.slice(0,r);if(r<0||!/^[A-Za-z][A-Za-z0-9+.-]*$/.test(n))return;const o=t.slice(r+1),s=ac.has(n.toLowerCase());let i;if(s)i=o.replace(/^[/\\]+/,"");else{if(!o.startsWith("//"))return;i=o.slice(2)}const a=i.search(s?/[/?#\\]/:/[/?#]/),c=a<0?i.length:a,l=i.slice(0,c),u=l.lastIndexOf("@");return u<0?void 0:`${t.slice(0,t.length-i.length)}${l.slice(u+1)}${i.slice(c)}`}(t)??cc(t)??t}}const ac=new Set(["ftp","file","http","https","ws","wss"]);function cc(e){const t=e.indexOf("/"),r=t<0?e:e.slice(0,t),n=r.indexOf(":"),o=r.lastIndexOf("@",r.lastIndexOf(":"));if(!(n<0||o<0||r.indexOf("@")`/${s.posix.relative(e,t)}`))}var dc=r("../../node_modules/.pnpm/picomatch@4.0.5/node_modules/picomatch/index.js");function hc(e,t){return e.some((e=>{return"*"===e.url.trim()?(e.patterns??[]).some((e=>mc(e.pattern,t))):!((r=e.url).includes("://")||r.includes("github.com")||r.includes("gitlab.com")||r.includes("bitbucket.org")||r.includes("@"))&&mc(e.url,t);var r}))}function pc(e,t,r){return fc(e.url,t)&&(e.patterns??[]).some((e=>mc(e.pattern,r)))}function fc(e,t){return e.includes("*")?"*"===e.trim()||function(e,t){const r=e.trim();return!!mc(r,t)||!!r.startsWith("*/")&&mc(`**/${r.slice(2)}`,t)}(bc(e),bc(t)):bc(e)===bc(t)}function mc(e,t){const r=e.trim();return!("."!==t&&""!==t||"**"!==r&&"**/*"!==r)||function(e){const t=yc.get(e);if(void 0!==t)return t;let r;try{const t=dc(e,{dot:!0});r=r=>{try{return t(r)}catch{return e===r}}}catch{r=t=>e===t}return vc(yc,gc,e,r)}(r)(t)}const gc=2048,wc=new Map,yc=new Map;function vc(e,t,r,n){if(e.set(r,n),e.size>t){const t=e.keys().next().value;void 0!==t&&e.delete(t)}return n}function bc(e){const t=wc.get(e);if(void 0!==t)return t;const r=(function(e){const t=Ka(e);if(void 0!==t)return`${t.hostname}/git/${t.owner}/${t.name}`.toLowerCase()}(n=e)??za(n))||function(e){let t=e.trim();t.startsWith("git@")&&(t=`https://${t.slice(4).replace(":","/")}`),/^[a-z][a-z0-9+.-]*:\/\//i.test(t)&&!/^https?:\/\//i.test(t)&&(t=t.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"https://")),/^https?:\/\//i.test(t)||(t=`https://${t}`);try{const e=new URL(t),r=e.pathname.replace(/\/+$/,"").replace(/\.git$/i,"").replace(/\/+$/,"");return e.hostname+r}catch{return t=t.replace(/^https?:\/\//i,""),t=t.replace(/[?#].*$/,""),t=t.replace(/\/+$/,""),t=t.replace(/\.git$/i,""),t=t.replace(/\/+$/,""),t}}(e).toLowerCase();var n;return vc(wc,2048,e,r)}function Sc(e){if("object"==typeof e&&null!==e&&"code"in e){const t=e.code;if("string"==typeof t)return t}}function kc(e){if(e instanceof Error)return e.message;if("object"==typeof e&&null!==e&&"message"in e){const t=e.message;if("string"==typeof t)return t}return""}(0,_s.J)((function(){wc.clear(),yc.clear()}));const _c=[".gitignore",".cursorignore"];async function Cc(e){if(!(0,s.isAbsolute)(e))return null;const t=await(0,Yo.DN)(e);return null===t?null:t}function Ec(e,t){if(!e||0===e.length)return[...t];const r=new Set(e);for(const e of t)r.has(e)&&r.delete(e),r.add(e);return[...r]}class xc{constructor(e,t,r,n={}){this.disposeRequested=!1,this.initIgnoreService=()=>Ic.init((0,y.q6)(),e,r??[process.cwd()],t),!0!==n.deferInit&&this.ensureStarted()}ensureStarted(){if(void 0===this.ignoreServicePromise){if(this.disposeRequested)return Promise.reject(new Error("LazyIgnoreService was disposed before its ignore-file scan started"));this.ignoreServicePromise=this.initIgnoreService()}return this.ignoreServicePromise}isIgnoredByAny(e){return this.ensureStarted().then((t=>t.isIgnoredByAny(e)))}isGitIgnored(e){return this.ensureStarted().then((t=>t.isGitIgnored(e)))}isCursorIgnored(e,t){return this.ensureStarted().then((r=>r.isCursorIgnored(e,t)))}isRepoBlocked(e){return this.ensureStarted().then((t=>t.isRepoBlocked(e)))}listCursorIgnoreFilesByRoot(e){return this.ensureStarted().then((t=>t.listCursorIgnoreFilesByRoot(e)))}getCursorIgnoreMapping(){return this.ensureStarted().then((e=>e.getCursorIgnoreMapping()))}getShellSandboxIgnoreMapping(e){return this.ensureStarted().then((t=>t.getShellSandboxIgnoreMapping(e)))}getGitIgnoreMapping(){return this.ensureStarted().then((e=>e.getGitIgnoreMapping()))}getRepoBlockExcludeGlobs(e){return this.ensureStarted().then((t=>t.getRepoBlockExcludeGlobs(e)))}handleCursorIgnoreCreated(e){return this.ensureStarted().then((t=>t.handleCursorIgnoreCreated(e)))}handleCursorIgnoreChanged(e){return this.ensureStarted().then((t=>t.handleCursorIgnoreChanged(e)))}handleCursorIgnoreDeleted(e){return this.ensureStarted().then((t=>t.handleCursorIgnoreDeleted(e)))}dispose(){this.disposeRequested||(this.disposeRequested=!0,this.ignoreServicePromise?.then((e=>{e.dispose()})).catch((()=>{})))}}const Pc=Math.min(8,Math.max(1,Math.floor(o.default.availableParallelism()/2)));class Rc{constructor(e){this.maxLookups=e,this.instances=new Map,this.lookups=0}get(e,t){this.lookups>=this.maxLookups&&this.clear(),this.lookups++;let r=this.instances.get(e);return void 0===r&&(r=oa().add(t),this.instances.set(e,r)),r}delete(e){this.instances.delete(e)}clear(){this.instances.clear(),this.lookups=0}}class Ic{constructor(e,t,r,n,o,s){this.gitExecutor=e,this.gitIgnoreMapping=t,this.cursorIgnoreMapping=r,this.teamSettingsService=n,this.rootDirectories=o,this.scanEnvironment=s,this.gitIgnoreCache=new js.q({max:2e3}),this.cursorIgnoreCache=new js.q({max:2e3}),this.gitRootCache=new js.q({max:1e4}),this.gitRemoteUrlCache=new js.q({max:200}),this.hasGitDirCache=new js.q({max:1e3}),this.gitParsedIgnoreCache=new Rc(1e4),this.cursorParsedIgnoreCache=new Rc(1e4),this.ignoreMappingsHaveEntries=!1,this.directoryWalkPlacementCache=new js.q({max:1e4}),this.extraRootCursorIgnoreCache=new js.q({max:32}),this.extraGitRepoMappingCache=new js.q({max:32}),this.unwalkedFolders=o.flatMap((e=>Hs(e,s)))}static getRipwalkCache(){return Ic.ripwalkCache??=new Sa,Ic.ripwalkCache}hasNoWorkspaceFolders(){return!this.ignoreMappingsHaveEntries&&(this.ignoreMappingsHaveEntries=Object.keys(this.gitIgnoreMapping).length>0||Object.keys(this.cursorIgnoreMapping).length>0,!this.ignoreMappingsHaveEntries)}async resolveLookupRoot(e){return await(0,Yo.DN)(e)??(0,Yo.o1)(e)}static async init(e,t,r,n,s={platform:process.platform,homeDirectory:o.default.homedir()}){const i={...s,homeDirectory:await(0,Yo.DN)(s.homeDirectory)??s.homeDirectory},a=await(0,Or.PH)(r,(async e=>{const t=await(0,Yo.DN)(e);return null===t?(console.warn(`[IgnoreService] Cannot resolve workspace root, using as-is: ${e}`),e):t})),c={},l={},u=await(0,Or.PH)(a,(async r=>({root:r,lookup:await ec(e,t,r)}))),d=u.map((({root:e,lookup:t})=>"none"===t.kind?null:"unknown"===t.kind||Hs(t.root,i).length>0?e:t.root)).filter((e=>null!==e)),h=u.filter((({lookup:e})=>"unknown"===e.kind)).map((({root:e})=>(0,Yo.o1)(e)));return d.length>0&&await Promise.all([Ic.initializeIgnoreMapping({rootDirectories:d,ignoreFileName:".gitignore",mapping:c,scanEnvironment:i,unknownRoots:h}),Ic.initializeIgnoreMapping({rootDirectories:a,ignoreFileName:".cursorignore",mapping:l,scanEnvironment:i,unknownRoots:h})]),new Ic(t,c,l,n,a,i)}static async preloadHierarchy(e,t,r,n){let o=(0,Yo.o1)(e);const i=(0,s.parse)(o).root;for(;o!==i;){if(n?.has(o)){const e=(0,s.dirname)(o);if(e===o)break;o=e;continue}void 0===r[o]&&await Ic.handleHierarchyIgnore(o,t,r),n?.add(o);const e=(0,s.dirname)(o);if(e===o)break;o=e}}static async handleHierarchyIgnore(e,t,r){const n=(0,s.join)(e,t);try{await(0,Co.access)(n,Co.default.constants.F_OK);const t=await ji(n),o=Ic.parseIgnoreRules(t);r[e]=o}catch(o){"ENOENT"===Sc(o)||console.error(`Error reading ${t} file at ${n}:`,o),r[e]=[]}}static async initializeIgnoreMapping({rootDirectories:e,ignoreFileName:t,mapping:r,scanEnvironment:n,unknownRoots:o}){try{const i=Ic.deduplicateRootDirectories(e),a=await Ic.promiseQueue.enqueueList(i,(e=>Ic.findFilesWithRipgrep({rootDirectory:e,fileName:t,scanEnvironment:n,noIgnoreVcs:o.some((t=>(0,Yo.ZU)({basePath:e,targetPath:t})))}))),c=Array.from(a.values()).flat();await Promise.all(c.map((async e=>{try{const t=await ji(e),n=Ic.parseIgnoreRules(t),o=(0,s.dirname)(e);r[o]=n}catch(r){console.error(`Error processing ${t} file at ${e}:`,r)}})));const l=new Set;for(const e of i)await Ic.preloadHierarchy(e,t,r,l)}catch(e){console.error(`Error initializing ignore mapping for ${t}:`,e)}}static async findFilesWithRipgrep({rootDirectory:e,fileName:t,scanEnvironment:r,noIgnoreVcs:n}){const o=(0,y.q6)(),i=[],a={root:e,includeGlobs:_c.map((e=>`**/${e}`)),excludeGlobs:[...lc,...uc(e,r)],noIgnoreVcs:n,source:"ignore_scan"},c=Ic.getRipwalkCache().walk(o,a);for await(const r of c.lines)(0,s.basename)(r)===t&&i.push((0,s.join)(e,r));return i}async handleManualLookupWhenNoWorkspaceDirs(e,t,r){const n={};let o=(0,s.dirname)(e);const i=(0,s.parse)(o).root;for(;;){let e=r?.get(o);if(void 0===e){try{e=Ic.parseIgnoreRules(await ji((0,s.join)(o,t)))}catch{e=[]}r?.set(o,e)}if(e.length>0&&(n[o]=e),o===i)break;o=(0,s.dirname)(o)}return this.testIgnored(e,n,((e,t)=>oa().add(t)))}async isIgnoredByAny(e){const[t,r,n]=await Promise.all([this.checkGitIgnored(e),this.checkCursorIgnored(e),this.checkRepoBlocked(e)]);return t||r||n}async isGitIgnored(e){return this.checkGitIgnored(e)}async isCursorIgnored(e,t){return this.checkCursorIgnored(e,t)}async checkGitIgnored(e){if(this.hasNoWorkspaceFolders())return this.handleManualLookupWhenNoWorkspaceDirs(e,".gitignore");const t=this.gitIgnoreCache.get(e);if(void 0!==t)return t;await this.populateHierarchyIfNeeded(e,".gitignore",this.gitIgnoreMapping);const r=this.checkIgnored(e,this.gitIgnoreMapping,this.gitParsedIgnoreCache);return this.gitIgnoreCache.set(e,r),r}async checkCursorIgnored(e,t){if(this.hasNoWorkspaceFolders())return this.handleManualLookupWhenNoWorkspaceDirs(e,".cursorignore",t);const r=this.cursorIgnoreCache.get(e);if(void 0!==r)return r;await this.populateHierarchyIfNeeded(e,".cursorignore",this.cursorIgnoreMapping);const n=this.checkIgnored(e,this.cursorIgnoreMapping,this.cursorParsedIgnoreCache);return this.cursorIgnoreCache.set(e,n),n}isInUnwalkedFolder(e){const t="darwin"===this.scanEnvironment.platform,r=t?e.toLowerCase():e;return this.unwalkedFolders.some((e=>(0,Yo.ZU)({basePath:t?e.toLowerCase():e,targetPath:r})))}directoryWalkPlacement(e){const t=this.directoryWalkPlacementCache.get(e);if(void 0!==t)return t;let r;return r=this.isInUnwalkedFolder(e)?"unwalked":this.rootDirectories.some((t=>(0,Yo.ZU)({basePath:t,targetPath:e})))?"walked":"outside",this.directoryWalkPlacementCache.set(e,r),r}async populateHierarchyIfNeeded(e,t,r){let n=(0,s.dirname)((0,Yo.o1)(e));const o=[],i=(0,s.parse)(n).root;for(;n!==i;){const e=this.directoryWalkPlacement(n),t="unwalked"===e;if("walked"===e){n=(0,s.dirname)(n);continue}if(void 0===r[n])o.push(n);else if(!t)break;const i=(0,s.dirname)(n);if(i===n)break;n=i}o.length>0&&(await Ic.promiseQueue.enqueueList(o,(e=>Ic.handleHierarchyIgnore(e,t,r))),".gitignore"===t?this.gitIgnoreCache.clear():this.cursorIgnoreCache.clear())}testIgnored(e,t,r){for(const[n,o]of Object.entries(t)){if(0===o.length)continue;if(!(0,Yo.ZU)({basePath:n,targetPath:e}))continue;const t=(0,s.relative)(n,e);if(""===t)continue;const i=r(n,o),a=(0,Yo.oL)(t),c=i.test(a);if(c.ignored&&!c.unignored)return!0;const l=i.test(`${a}/`);if(l.ignored&&!l.unignored)return!0}return!1}checkIgnored(e,t,r){return this.testIgnored(e,t,((e,t)=>r.get(e,t)))}async listCursorIgnoreFilesByRoot(e){const t=await this.resolveLookupRoot(e),r=[];for(const[e,n]of Object.entries(this.cursorIgnoreMapping)){if(0===n.length)continue;if(!(0,Yo.ZU)({basePath:t,targetPath:e}))continue;const o=(0,s.join)(e,".cursorignore");try{await(0,Co.access)(o),r.push(o)}catch{}}return r}async getCursorIgnoreMapping(){return{...this.cursorIgnoreMapping}}async getShellSandboxIgnoreMapping(e=[]){const t={...this.cursorIgnoreMapping},r=[];for(const t of e){if((0,qs.$f)(t))continue;const e=await(0,Yo.DN)(t);if(null===e||".git"===(0,s.basename)(e)||this.rootDirectories.some((t=>(0,Yo.ZU)({basePath:t,targetPath:e})))||r.includes(e))continue;const n=await Co.default.stat(e).catch((e=>{if(void 0===Sc(e))throw e}));n?.isDirectory()&&r.push(e)}const n=Date.now();for(const e of r){let r=this.extraRootCursorIgnoreCache.get(e);if(void 0===r||r.expiresAt<=n){const t={},o=void 0===this.gitExecutor.guardedRootLookup?void 0:await ec((0,y.q6)(),this.gitExecutor,e);await Ic.initializeIgnoreMapping({rootDirectories:[e],ignoreFileName:".cursorignore",mapping:t,scanEnvironment:this.scanEnvironment,unknownRoots:"unknown"===o?.kind?[e]:[]}),r={mapping:t,expiresAt:n+va()},this.extraRootCursorIgnoreCache.set(e,r)}for(const[e,n]of Object.entries(r.mapping))t[e]=Ec(t[e],n)}for(const e of[...this.rootDirectories,...r]){const r=await this.getRepoBlockExcludeGlobs(e);0!==r.length&&(t[e]=Ec(t[e],r))}return t}async getGitIgnoreMapping(){return{...this.gitIgnoreMapping}}static deduplicateRootDirectories(e){const t=[...e.map((e=>(0,Yo.o1)(e)))].sort(((e,t)=>e.length-t.length)),r=[];for(const e of t)r.some((t=>e.startsWith(`${t}/`)||e.startsWith(`${t}\\`)))||r.push(e);return r}static parseIgnoreRules(e){return e.split("\n").map((e=>e.replace(/\r$/,"").trimStart())).filter((e=>""!==e&&!e.startsWith("#")))}clearCaches(){this.gitIgnoreCache.clear(),this.cursorIgnoreCache.clear(),this.gitRootCache.clear(),this.gitRemoteUrlCache.clear(),this.hasGitDirCache.clear(),this.gitParsedIgnoreCache.clear(),this.cursorParsedIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear(),this.extraGitRepoMappingCache.clear()}dispose(){this.gitIgnoreCache=new js.q({max:1}),this.cursorIgnoreCache=new js.q({max:1}),this.gitRootCache=new js.q({max:1}),this.gitRemoteUrlCache=new js.q({max:1}),this.hasGitDirCache=new js.q({max:1}),this.directoryWalkPlacementCache=new js.q({max:1}),this.extraRootCursorIgnoreCache=new js.q({max:1}),this.extraGitRepoMappingCache=new js.q({max:1}),this.gitParsedIgnoreCache.clear(),this.cursorParsedIgnoreCache.clear(),this.gitRepoMappingPromise=void 0}async handleCursorIgnoreCreated(e){const t=(0,s.dirname)(e),r=await ji(e),n=Ic.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear()}async handleCursorIgnoreChanged(e){const t=(0,s.dirname)(e),r=await ji(e),n=Ic.parseIgnoreRules(r);this.cursorIgnoreMapping[t]=n,this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear()}handleCursorIgnoreDeleted(e){const t=(0,s.dirname)(e);this.cursorIgnoreMapping[t]=[],this.cursorParsedIgnoreCache.delete(t),this.cursorIgnoreCache.clear(),this.extraRootCursorIgnoreCache.clear()}async findGitRootsForFile(e){const t=(0,Yo.o1)(e),r=this.gitRootCache.get(t);if(void 0!==r)return r;const n=[],o=[],i=[];let a=t;const c=(0,s.parse)(a).root;for(;a!==c;){o.push(a),void 0===this.hasGitDirCache.get(a)&&i.push(a);const e=(0,s.dirname)(a);if(e===a)break;a=e}if(i.length>0){const e=i.map((e=>(0,Co.access)((0,s.join)(e,".git"),Co.default.constants.F_OK).then((()=>[e,!0])).catch((()=>[e,!1])))),t=await Promise.all(e);for(const[e,r]of t)this.hasGitDirCache.set(e,r)}for(const e of o)!0===this.hasGitDirCache.get(e)&&n.push(e);return this.gitRootCache.set(t,n),n}async isRepoBlocked(e){return this.checkRepoBlocked(e)}async checkRepoBlocked(e){const t=function(e){if(void 0===e)return;const t=e.repos??[],r=e.disableLocalExecAllowlistEnforcement?[]:e.allowedRepos??[];return 0===t.length&&0===r.length?void 0:{blocked:t,allowed:r}}(await(this.teamSettingsService?.getTeamRepos()));if(void 0===t)return!1;const r=await this.findGitRootsForFile(e);if(0===r.length)return 0!==t.allowed.length&&!(0,Yo.ZU)({basePath:await this.getCursorDataDir(),targetPath:e})&&function(e,t){return 0!==e.allowed.length&&!hc(e.allowed,t)}(t,this.getWorkspaceRelativePath(e));const n=[];for(const t of r)n.push({url:await this.remoteUrlOf(t),relativePath:(0,s.relative)(t,e)||"."});return function(e,t){let r=0===e.allowed.length,n=!1;for(const{url:o,relativePath:s}of t)if(void 0!==o){if(e.blocked.some((e=>pc(e,o,s))))return!0;e.allowed.length>0&&!n&&(n=!0,r=e.allowed.some((e=>pc(e,o,s))))}else 0;return!r}(t,n)}async remoteUrlOf(e){if(this.gitRemoteUrlCache.has(e))return this.gitRemoteUrlCache.get(e);const t=await sc((0,y.q6)(),this.gitExecutor,e);return void 0!==t&&this.gitRemoteUrlCache.set(e,t),t}getWorkspaceRelativePath(e){let t;for(const r of this.rootDirectories)(0,Yo.ZU)({basePath:r,targetPath:e})&&(void 0===t||r.length>t.length)&&(t=r);return void 0!==t?(0,Yo.oL)((0,s.relative)(t,e)):(0,Yo.oL)(e)}getCursorDataDir(){return this.cursorDataDirPromise??=(async()=>{const e=(0,s.join)(o.default.homedir(),".cursor");return await(0,Yo.DN)(e)??e})(),this.cursorDataDirPromise}async getRepoBlockExcludeGlobs(e){const t=await(this.teamSettingsService?.getTeamRepos());if(!t?.repos?.length)return[];const r=await this.resolveLookupRoot(e);let n;if(this.rootDirectories.some((e=>(0,Yo.ZU)({basePath:e,targetPath:r}))))n=await this.getGitRepoMapping();else{const e=this.extraGitRepoMappingCache.get(r);void 0!==e?n=e:(n=await this.initializeGitRepoMapping([r]),this.extraGitRepoMappingCache.set(r,n))}if(0===n.size)return[];const o=[];for(const[e,i]of n){if(void 0===i)continue;const n=this.normalizePathForComparison(e),a=this.normalizePathForComparison(r);let c=!1,l="";if(a.startsWith(n)?(c=!0,l=""):n.startsWith(a)&&(c=!0,l=(0,s.relative)(r,e)),!c)continue;const u=t.repos.filter((e=>fc(e.url,i)));if(0!==u.length)for(const e of u)for(const t of e.patterns||[]){const e=t.pattern.trim();if(!e)continue;let r;r=l?(0,s.join)(l,e).replace(/\\/g,"/"):e,o.push(r),r.endsWith("/**")||o.push(`${r}/**`)}}return o}normalizePathForComparison(e){let t=e.replace(/\\/g,"/");return t.startsWith("/")&&t.length>2&&":"===t[2]&&(t=t.substring(1)),"win32"===process.platform&&(t=t.toLowerCase()),t}getGitRepoMapping(){return this.gitRepoMappingPromise||(this.gitRepoMappingPromise=this.initializeGitRepoMapping()),this.gitRepoMappingPromise}async initializeGitRepoMapping(e=this.rootDirectories){const t=new Map,r=[],n=["**/node_modules/**","**/.turbo/**","**/.next/**","**/.cache/**","**/.pnpm/**","**/.yarn/**","**/dist/**","**/build/**","**/out/**","**/target/**","**/.vscode/**","**/.idea/**","**/venv/**","**/__pycache__/**","**/logs/**","**/tmp/**","**/temp/**"],o=(0,y.q6)();for(const t of e){const e=(0,Yo.o1)(t);try{await(0,Co.access)((0,s.join)(e,".git"),Co.default.constants.F_OK),r.includes(e)||r.push(e)}catch{}let i=(0,s.dirname)(e);const a=(0,s.parse)(i).root;for(;i!==a&&""!==i;){try{await(0,Co.access)((0,s.join)(i,".git"),Co.default.constants.F_OK),r.includes(i)||r.push(i)}catch{}const e=(0,s.dirname)(i);if(e===i)break;i=e}try{const t={root:e,includeGlobs:["**/.git/config"],excludeGlobs:[...n,...uc(e,this.scanEnvironment)],noIgnoreVcs:!0,source:"ignore_scan"},i=Ic.getRipwalkCache().walk(o,t);for await(const t of i.lines){const n=(0,s.join)(e,t),o=(0,s.dirname)(n),i=(0,s.dirname)(o);r.includes(i)||r.push(i)}}catch{}}return await Promise.all(r.map((async e=>{try{const r=await sc(o,this.gitExecutor,e);t.set(e,r)}catch{t.set(e,void 0)}}))),t}}async function Tc(e,t){let r=e;if($s()&&(r=Ls(t.command,t.parsingResult)),!r||"insecure_none"===r.type)return r;const n="workspace_readwrite"===r.type&&t.permissionsService.resolveLinkedWorktreeSandboxGrants?await t.permissionsService.resolveLinkedWorktreeSandboxGrants(r,{command:t.command,workingDirectory:t.workingDirectory}):void 0,o=function(e,t){if(!e)return t;const r={...e};for(const[e,n]of Object.entries(t))r[e]=Ec(r[e],n);return r}(r.ignoreMapping,await async function(e,t){return e.getShellSandboxIgnoreMapping?e.getShellSandboxIgnoreMapping(t):e.getCursorIgnoreMapping()}(t.ignoreService,n?.roots));if("workspace_readwrite"===r.type&&void 0!==n){const e=(0,Oo.s9)(r.additionalReadwritePaths,[...n.roots,...n.commonDirs]);return{...r,additionalReadwritePaths:e.length>0?e:void 0,ignoreMapping:o}}return{...r,ignoreMapping:o}}Ic.promiseQueue=new Or.TJ({max:Pc});var Ac=r("../proto/dist/generated/agent/v1/mcp_exec_pb.js");const $c="agent-tools",Mc=51380224;var Dc=r("../proto/dist/generated/agent/v1/utils_pb.js");const Oc=/^v?(\d{1,9})\.(\d{1,9})(?:\.\d{1,9})?(?:[-+][0-9A-Za-z.+-]*)?$/,Fc=["unknown","other","older","3.24","3.25","3.26","3.27","3.28","3.29","3.30","3.31","3.32","3.33","3.34","3.35","3.36","3.37","3.38","3.39","3.40","newer"].flatMap((e=>{const t=/^(\d+)\.(\d+)$/.exec(e);return null===t?[]:[{major:Number(t[1]),minor:Number(t[2]),bucket:e}]})),Nc=Fc[0].major,Lc=Fc[0].minor;function jc(e){if(null==e)return"unknown";const t=e.trim();if(0===t.length||t.length>128)return"unknown";const r=Oc.exec(t);if(null===r)return"unknown";const n=Number(r[1]),o=Number(r[2]);if(n!==Nc)return"other";const s=Fc.find((e=>e.minor===o));return void 0!==s?s.bucket:o=128&&t<=191?t:Vc.get(e)}function rl(e,t){const r=e.charCodeAt(t),n=function(e){return e>=194&&e<=222?201===e?0:2:e>=224&&e<=239?3:240===e?4:0}(r);if(0===n||t+n>e.length)return;const o=new Uint8Array(n);o[0]=r;for(let r=1;r0&&Jc.test(e[t-1]))return}else{if(Zc.has(s))return;if(!0===Qc.get(r)?.has(s))return;if(3===n&&Yc.has(s)&&Zc.has(e[t+2]))return}let i;try{i=Gc.decode(o)}catch{return}return el.test(i)?void 0:{index:t,text:e.slice(t,t+n),repaired:i}}function nl(e,t=Number.POSITIVE_INFINITY){const r=[];let n=0;for(;n240){n++;continue}const o=rl(e,n);void 0!==o?(r.push(o),n+=o.text.length):n++}return r}const ol=`[\\u00c2-\\u00f0][\\u0080-\\u00bf${[...Vc.keys()].join("")}]`,sl=new RegExp(ol),il=/\p{L}/u;function al(e,t){const r=e.charCodeAt(t);let n;if(r>=194&&r<=223)n=2;else if(r>=224&&r<=239)n=3;else{if(!(r>=240&&r<=244))return 0;n=4}if(t+n>e.length)return 0;for(let r=1;r=128&&n<=191)&&(n<128||!Vc.has(e[t+r])))return 0}return n}function cl(e,t){if(t.text.length>2)return!0;const r=t.text.charCodeAt(1);if(r>=128&&r<=159)return!0;if(0===t.index||!Jc.test(e[t.index-1]))return!0;const n=t.index+t.text.length;return n0)return"damaged";const n=yl(r);return"utf8"!==n&&"utf8_bom"!==n?"other_encoding":"intact"}function pl(e,t){return e<=t?"existing_only":"new_damage"}function fl(e,t){const r=new Set(t.map((e=>e.text))),n=e.filter((e=>!r.has(e.text))),o=n.length>0?n:e;if(function(e){let t="",r=-1;for(const n of e){if(n.index!==r){if(nl(t,1).length>0)return!0;t=""}t+=n.repaired,r=n.index+n.text.length}return nl(t,1).length>0}(o))return"double";if(1!==new Set(o.map((e=>e.text.length))).size)return"mixed";switch(o[0].text.length){case 2:return"two_byte";case 3:return"three_byte";default:return"four_byte"}}function ml(e){return{detector:e,outcome:"clean",afterCount:0,beforeCount:0}}function gl(e,t,r){const n=nl(r,1e3);if(0===n.length)return ml("mojibake");const o=void 0===e?[]:nl(e,Math.max(n.length,6));return{detector:"mojibake",outcome:pl(n.length,o.length),file:hl(e,o.length,t),afterCount:n.length,beforeCount:o.length,pattern:fl(n,o)}}function wl(e,t,r){const n=li(r);if(0===n)return ml("replacement_chars");const o=void 0===e?0:li(e);return{detector:"replacement_chars",outcome:pl(n,o),file:hl(e,o,t),afterCount:n,beforeCount:o}}function yl(e){if(void 0===e)return"none";const t=e.toLowerCase().replace(/[^a-z0-9]/g,"");return"utf8"===t||"ascii"===t?"utf8":"utf8bom"===t?"utf8_bom":t.startsWith("utf16")?"utf16":"latin1"===t||"iso88591"===t?"latin1":"windows1252"===t||"cp1252"===t?"windows_1252":"gbk"===t||"gb2312"===t||"gb18030"===t||"cp936"===t?"gbk":"shiftjis"===t||"sjis"===t||"cp932"===t||"windows31j"===t?"shift_jis":"euckr"===t||"cp949"===t?"euc_kr":"big5"===t||"big5hkscs"===t||"cp950"===t?"big5":"other"}const vl=new Map([["md",["md","mdx","markdown"]],["txt",["txt","text","log","rst","adoc","asciidoc","tex"]],["js_ts",["js","jsx","mjs","cjs","ts","tsx","mts","cts"]],["web",["html","htm","xhtml","css","scss","sass","less","vue","svelte","astro"]],["py",["py","pyi","pyw","ipynb"]],["jvm",["java","kt","kts","scala","groovy","gradle"]],["dotnet",["cs","csx","vb","fs","fsx","razor","cshtml","xaml"]],["c_cpp",["c","h","cc","cpp","cxx","c++","hpp","hh","hxx","h++","m","mm"]],["other_code",["go","rs","rb","erb","php","swift","dart","lua","pl","pm","r","ex","exs","erl","hs","clj","cljs","zig","nim","jl","sol","elm","ml","mli","pas","bas"]],["shell",["sh","bash","zsh","fish","ps1","psm1","psd1","bat","cmd"]],["sql",["sql","psql","ddl","dml"]],["config",["json","jsonc","json5","yaml","yml","toml","ini","cfg","conf","env","properties","editorconfig"]],["xml",["xml","xsl","xslt","xsd","svg","csproj","vbproj","fsproj","props","targets","nuspec","plist","storyboard","xib"]],["i18n",["po","pot","strings","stringsdict","arb","xlf","xliff","ftl","resx"]],["csv",["csv","tsv"]]].flatMap((([e,t])=>t.map((t=>[t,e])))));function bl(e){const t=(0,s.extname)(e).slice(1).toLowerCase();return""===t?"none":vl.get(t)??"other"}const Sl=new Map([[1252,"1252"],[1250,"1250"],[1251,"1251"],[874,"874"],[932,"932"],[936,"936"],[949,"949"],[950,"950"],[65001,"65001"]]);function kl(e){if("string"==typeof e)return e;const t=void 0===e.acp?void 0:Sl.get(e.acp);return void 0===t?"other":e.oemcp===e.acp?t:`${t}_split`}function _l(e,t){if("clean"===e.outcome)return{detector:e.detector,outcome:"clean",file:"unclassified"};const r={outcome:e.outcome,file:e.file,ext:bl(t.path),encoding:yl(t.encoding),code_page:kl(t.pages),run_count:ul(e.afterCount),delta:(n=e.afterCount-e.beforeCount,n<0?"neg":dl(n)),before_count:dl(e.beforeCount)};var n;return"mojibake"===e.detector?{detector:"mojibake",pattern:e.pattern,...r}:{detector:"replacement_chars",...r}}class Cl{constructor(){this.counts={stdout:0,stderr:0},this.produced={stdout:!1,stderr:!1}}note(e,t){if(0===t.length)return;this.produced[e]=!0;const r=this.counts[e];r>=6||(this.counts[e]=r+li(t,6-r))}labels(e,t){const r=kl(t),n=[];for(const t of["stdout","stderr"]){if(!this.produced[t])continue;const o=this.counts[t];n.push({detector:"replacement_chars",outcome:o>0?"damaged":"clean",run_count:dl(o),branch:e[t],stream:t,code_page:r})}return n}}const El=/[\ud800-\udbff](?![\udc00-\udfff])|(?=e.length||e.startsWith(Al,r))&&e.startsWith(Al,r+Fl(e,r)))return!0}return!1}(e)}(e,o))return"utf16";if(r)return"clean";if(!Tl.test(e))return"clean";const s=function(e){if(!sl.test(e))return;let t=0,r=!1,n=!0,o=0;for(;o=194&&s<=240?rl(e,o):void 0;if(void 0!==i){if(t++,r=cl(e,i),o+=i.text.length,!n||!r&&t>=256)return"medium";continue}const a=n?al(e,o):0;if(0===a){if(n=!1,t>0)return"medium";o++}else o+=a}return 0!==t?r&&n?"high":"medium":void 0}(e);return void 0!==s?"high"===s?"mojibake_high":"mojibake_medium":Il.test(e)?"c1":"clean"}const Ll=(0,l.h)("local-exec:encoding-slices");function jl(e,t){if(void 0===e)return!1;try{return"function"==typeof e?e(t):e}catch{return!1}}function Ul(e,t){return jl(e?.enabled,t)}function Bl(e,t,r=!1){if("clean"===e)return"clean";switch(t){case"utf8_valid":return"lone_surrogate"===e?"new_damage_cut":"existing_only";case"utf8_invalid":return"lone_surrogate"===e?"new_damage_cut":"replacement"!==e?"existing_only":r?"unknown":"not_text";case"utf8_cut":return"lone_surrogate"===e?"new_damage_cut":"replacement"!==e?"existing_only":r?"unknown":"new_damage_cut";case"utf8_as_other":return"new_damage_decode";case"declared_other":return"replacement"!==e||r?"unknown":"new_damage_decode";case"other_encoding":case"unseen":return"unknown";default:return t}}function Wl(e){for(let t=1;t<=Math.min(3,e.length);t++){const r=e[e.length-t]??0;if(128!=(192&r))return(r>=240?4:r>=224?3:r>=192?2:1)>t?t:0}return 0}class Hl{constructor(){this.seen=!1,this.invalid=!1,this.carry=new Uint8Array(0)}write(e){if(0===e.length)return;if(this.seen=!0,this.invalid)return;const t=this.carry.length>0?Buffer.concat([this.carry,e]):e,r=Wl(t);if(!(0,n.isUtf8)(t.subarray(0,t.length-r)))return this.invalid=!0,void(this.carry=new Uint8Array(0));this.carry=r>0?Uint8Array.from(t.subarray(t.length-r)):t.subarray(0,0)}evidence(){return this.seen?this.invalid?"utf8_invalid":this.carry.length>0?"utf8_cut":"utf8_valid":"unseen"}}const ql=new Map(Object.entries({zsh:"zsh",zsh_light:"zsh_light",bash:"bash",pwsh:"pwsh",powershell51:"powershell51",naive_pwsh:"naive_pwsh",naive_powershell51:"naive_powershell51",naive_bash:"naive_bash",naive_zsh:"naive_zsh",naive_other:"naive_other"})),zl=(0,u.Pu)("local_exec.encoding_slice",{description:"Results a local executor returned, and results about to be encoded for the wire, by the boundary they were counted at, the kind of encoding damage their text holds (one kind per result, clean included), whose the damage is as far as the bytes at that boundary say, which executor the result came from, the client's version bucket, for a shell result counted on Windows how the code page lookup stood, and for a shell result which shell ran the command",labelNames:["layer","kind","origin","source","version_bucket","code_page_lookup","shell_kind"]}),Gl=Pl[0],Vl=new Map(Pl.map(((e,t)=>[e,t])));function Kl(e){return Vl.get(e)??Pl.length}class Jl{constructor(){this.worst="clean",this.remaining=262144}note(e){this.walk(e,0)}kind(){return this.worst}capped(){return this.remaining<=0}settled(){return this.remaining<=0||this.worst===Gl}noteText(e){if(0===e.length)return;const t=e.length>this.remaining?Vo(e,this.remaining):e;this.remaining-=Math.max(t.length,1);const r=Nl(t);Kl(r)=16)return;if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer)return;if(Array.isArray(e)){for(const r of e)if(this.walk(r,t+1),this.settled())return;return}const r=Object.values(e);for(const e of r)if(this.walk(e,t+1),this.settled())return}}class Zl{constructor(e=1024){this.capacity=e,this.counted=new Set}firstRead(e,t){if(""===e)return!0;const r=`${e}\n${t}`,n=this.counted.delete(r);if(this.counted.add(r),this.counted.size>this.capacity)for(const e of this.counted){this.counted.delete(e);break}return!n}}function Xl(e,t,r,n){const o={layer:r.layer,kind:n,origin:Bl(n,r.evidence??"unseen",!0===r.partial),source:r.source??r.layer,version_bucket:jc(e.clientVersion)};void 0!==r.codePageLookup&&(o.code_page_lookup=r.codePageLookup),void 0!==r.shellKind&&(o.shell_kind=r.shellKind),zl.increment(t,1,o)}function Ql(e,t){Ll.warn(e,"encoding slice was not counted (result unaffected)",{error:t instanceof Error?t.name:"unknown"})}function Yl(e,t,r,n){if(void 0!==e&&Ul(e,t))try{const o=new Jl;o.note(n),Xl(e,t,r,o.kind())}catch(e){Ql(t,e)}}function eu(e,t,r,n){if(void 0!==e&&Ul(e,t))try{Xl(e,t,r,n)}catch(e){Ql(t,e)}}class tu{constructor(){this.seen=!1,this.invalid=!1}note(e){this.seen=!0,this.invalid||(0,n.isUtf8)(e)||(this.invalid=!0)}evidence(){return this.seen?this.invalid?"utf8_invalid":"utf8_valid":"unseen"}}function ru(e,t,r,n){return void 0===t?e:{execute:async(o,s,i)=>{const a=await e.execute(o,s,i);if(Ul(t,o))try{n(a)&&Yl(t,o,{layer:r},a)}catch(e){Ql(o,e)}return a}}}new Map([["readArgs","exec_read"],["redactedReadArgs","exec_read"],["grepArgs","exec_grep"],["mcpArgs","exec_mcp"],["readMcpResourceExecArgs","exec_mcp"],["executeHookArgs","exec_hooks"],["fetchArgs","exec_web_fetch"],["shellArgs","exec_shell"],["shellStreamArgs","exec_shell"],["backgroundShellSpawnArgs","exec_shell"],["miniSweAgentBashArgs","exec_shell"],["writeArgs","exec_write"]]);class nu{constructor(){this.text={stdout:new Jl,stderr:new Jl},this.bytes={stdout:new Hl,stderr:new Hl},this.produced={stdout:!1,stderr:!1},this.dropped={stdout:!1,stderr:!1},this.shellKind="unknown"}noteBytes(e,t){this.bytes[e].write(t)}noteText(e,t){0!==t.length&&(this.produced[e]=!0,this.text[e].note(t))}noteDropped(e){this.dropped[e]=!0}noteShell(e){this.shellKind=function(e){return"string"!=typeof e?"unknown":ql.get(e)??"unknown"}(e)}record(e,t,r,n){for(const o of["stdout","stderr"])this.produced[o]&&eu(e,t,{layer:"exec_shell",evidence:this.evidence(o,r[o]),partial:this.dropped[o]||this.text[o].capped(),codePageLookup:n,shellKind:this.shellKind},this.text[o].kind())}evidence(e,t){if("utf8"!==t)return"other_encoding";const r=this.bytes[e].evidence();return"utf8_cut"===r?"utf8_invalid":r}}var ou=r("node:child_process"),su=r("../utils/dist/workload-spawn.js");const iu=(0,l.h)("local-exec:shell-output-encoding"),au=(0,zs.promisify)(ou.execFile),cu=/^\s*OEMCP\s+REG_\w+\s+(\d+)\s*$/m,lu=/^\s*ACP\s+REG_\w+\s+(\d+)\s*$/m;function uu(e,t){const r=t.exec(e);return null===r?void 0:Number(r[1])}const du="㐀-䶿一-鿿豈-﫿",hu=" -〿㈀-㏿︰-﹯＀-￯",pu="‐-※←-⇿─-◿★☆",fu="぀-ヿ",mu=new Map([["cp932",{script:new RegExp(`[${du}${hu}${pu}${fu}]`),doubleByte:!0}],["cp936",{script:new RegExp(`[${du}${hu}${pu}${fu}㄀-ㄯ]`),doubleByte:!0}],["cp949",{script:new RegExp(`[${du}${hu}${pu}${fu}㄰-㆏가-힯]`),doubleByte:!0}],["cp950",{script:new RegExp(`[${du}${hu}${pu}㄀-ㄯ]`),doubleByte:!0}],["cp874",{script:new RegExp("[฀-๿]"),doubleByte:!1}]]);const gu=function(e){let t,r,n,o,s=!1,i=0;const a=()=>{i+=1;const e=i;n=async function(){const{stdout:e}=await(0,su.D9)(au,"\\\\.\\GLOBALROOT\\SystemRoot\\System32\\reg.exe",["query","HKLM\\SYSTEM\\CurrentControlSet\\Control\\Nls\\CodePage"],{encoding:"buffer",timeout:3e3,windowsHide:!0});return e}().then((e=>{const i=function(e){const t=Buffer.isBuffer(e)?function(e){return e.length>=2&&255===e[0]&&254===e[1]?e.subarray(2).toString("utf16le"):e.includes(0)?e.toString("utf16le"):e.toString("latin1")}(e):e,r={},n=uu(t,cu),o=uu(t,lu);return void 0!==n&&(r.oemcp=n),void 0!==o&&(r.acp=o),r}(e);t=function(e){const{oemcp:t,acp:r}=e;if(void 0===t||void 0===r||t!==r)return;const n=function(e){if(65001===e)return;const t=`cp${e}`;return Vs.encodingExists(t)?t:void 0}(t);return void 0!==n&&mu.has(n)?n:void 0}(i),r=i,s=!0,n=void 0,o=void 0===i.oemcp&&void 0===i.acp?"unparsed":"answered",iu.info((0,y.q6)(),"Resolved the fallback encoding for shell output",{encoding:t??"none",oemcp:i.oemcp??"none",acp:i.acp??"none"})}),(t=>{n=void 0,o=function(e){try{if("object"!=typeof e||null===e)return"spawn_error";const t="code"in e?e.code:void 0;return"killed"in e&&!0===e.killed&&"string"!=typeof t?"timeout":"number"==typeof t?"nonzero_exit":"spawn_error"}catch{return"spawn_error"}}(t),iu.warn((0,y.q6)(),"Could not read the Windows code pages; shell output stays UTF-8 only",{error:t instanceof Error?t.message:String(t),attempt:e})}))};return"win32"===e&&a(),{current:()=>("win32"===e&&!s&&void 0===n&&i<3&&a(),t),pages:()=>void 0!==r?r:"win32"!==e?"none":i>=3&&void 0===n?"failed":"pending",lastOutcome:()=>"win32"===e?o??"pending":void 0,settled:()=>n??Promise.resolve()}}(process.platform),wu=Buffer.alloc(0),yu=/[\u0080-\uffff]/;function vu(e){const t=Math.max(0,e.length-3);for(let r=e.length-1;r>=t;r--){const t=e[r];if(128==(192&t))continue;const n=t>=248?1:t>=240?4:t>=224?3:t>=192?2:1,o=e.length-r;return n>o?o:0}return 0}function bu(){const e=new ia.StringDecoder("utf8");return{write:t=>e.write(t),end:()=>e.end()}}function Su(e,t){return Vs.decode(t,e,{stripBOM:!1})}const ku=/[\xe0-\xef][\x80-\xbf]\?/;const _u=10,Cu=Buffer.alloc(0),Eu=new Set([7,8,9,10,11,12,13,27]);function xu(e,t,r){for(let n=0;n+1(r=void 0,t.end())}}const Iu={encoding:"utf8",skip:0};function Tu(e){const t=e();let r="utf8";const n={};let o=!1;const s=()=>"utf8"===r?t:n[r]??=Ru(r),i=e=>("utf8"!==r&&e.length>0&&(o=!0),e);let a,c=!0,l=Cu,u=!1,d=0;const h=(e,t)=>{const n=function(e){if(!(e.length<2))return 255===e[0]&&254===e[1]?"utf16le":254===e[0]&&255===e[1]?"utf16be":void 0}(e);if(void 0!==n)return{encoding:n,skip:2};if("utf8"===r){if(e.length<2)return t?Iu:void 0;const r=0===e[0]?"utf16be":0===e[1]?"utf16le":void 0;if(void 0===r)return Iu;const n=Pu(e,r);if(-1!==n)return xu(e,r,n)?{encoding:r,skip:0}:Iu;if(!t)return;const o=e.length-e.length%2;return function(e,t){const r="utf16le"===t?1:0;for(let t=0;te.length?t?o:void 0:xu(e,r,n)?o:Iu}if(-1===i)return t?Iu:void 0;if("utf16le"===r&&i%2==0){if(i+1>=e.length)return t?Iu:void 0;if(0===e[i+1])return o}return Iu},p=e=>{if(e===r)return"";const t=i(s().end());return r=e,t},f=e=>"utf8"===r&&0!==e&&e<128,m=(e,n)=>{let o="",m=e;for(;;){if(c){const e=Math.min(m.length,512-l.length);let r;if(r=l.length>0?Buffer.concat([l,m.subarray(0,e)]):e===m.length?m:m.subarray(0,e),0===r.length)return o;const s=h(r,n||r.length>=512);if(void 0===s)return 1===r.length&&f(r[0])&&(o+=t.write(r),u=!0),l=Buffer.from(r),o;let i=s.skip,g=!1;if(u&&(i="utf8"===s.encoding?1:2,g=r[0]===_u,u=!1),0===l.length)i>0&&(m=m.subarray(i));else{const t=r.subarray(i);m=m.subarray(e),m=0===m.length?t:0===t.length?m:Buffer.concat([t,m]),l=Cu}if(c=g,d=0,a=void 0,o+=p(s.encoding),g)continue}if(0===m.length)return o;if("utf8"===r&&!m.includes(0)&&!m.includes(254)&&!m.includes(255)){const e=m.lastIndexOf(_u),r=-1===e?-1:m.length-e-1;if(-1===r||r>=2)return o+t.write(m);if(c=!0,0===r)return e>0&&m[e-1]===_u&&(l=Buffer.of(_u),u=!0),o+t.write(m);const n=m[m.length-1];return l=Buffer.of(n),u=f(n),o+t.write(u?m:m.subarray(0,e+1))}const e=Pu(m,r,d,a);if(-1===e)return d+=m.length,a=m[m.length-1],o+i(s().write(m));o+=i(s().write(m.subarray(0,e))),m=m.subarray(e),c=!0}};return{write:e=>0===e.length?s().write(e):m(e,!1),peek(){if(!c||0===l.length)return"";const t=h(l,!0);if(void 0===t)return"";const r=u?"utf8"===t.encoding?1:2:t.skip,n=l.subarray(r);return 0===n.length?"":"utf8"===t.encoding?e().write(n):Ru(t.encoding).write(n)},end(){const e=m(Cu,!0)+i(s().end());return c=!0,l=Cu,u=!1,d=0,a=void 0,e},branch:()=>!0===t.usedCodePage?.()?"code_page":o?"utf16":"utf8"}}var Au=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},$u=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Mu=(0,l.h)("local-exec:shell-core"),Du=(0,u.Pu)("local_exec.shell.encoding_check",{description:"Shell command output streams that produced text, per encoding detector (U+FFFD): whether the decoded text holds the pattern and how much, which decode path (UTF-8, Windows code page, UTF-16) produced it, which stream, and the machine's Windows code page",labelNames:["detector","outcome","run_count","branch","stream","code_page"]}),Ou="win32"===process.platform,Fu=["CURSOR_CONVERSATION_ID","CURSOR_REQUEST_ID","CURSOR_AGENT_STORE_FILES_DIR","CURSOR_AGENT_STORE_SHARED_PATHS"];function Nu(e){return`'${e.replace(/'/g,"'\\''")}'`}async function Lu(e){try{return(await(0,Co.stat)(e)).isDirectory()}catch(e){const t=Sc(e);if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}const ju=["eval-cursorbench","cursorbench","sand-eval","eval-harness"];function Uu(e){return ju.some((t=>e.includes(t)))?(0,bo.createHash)("sha256").update(e).digest("hex"):e}function Bu(e,t){return e[t]??process.env[t]}const Wu=/^[A-Za-z_][A-Za-z0-9_]*$/,Hu=/CURSOR_SANDBOX/i;function qu(e){return Wu.test(e)&&!Hu.test(e)}function zu(e){return"function"==typeof e?e():e}function Gu(e,t){const r=void 0===e?[]:[...e];return r.includes(t)||r.push(t),r}function Vu(e){let t=0,r=0;const n=e.length;for(;r"insecure_none"===e?.type?void 0:e?.privateTmp)).find((e=>void 0!==e));if("linux"!==process.platform||!0!==n||void 0===r||!(0,Yo.ZU)({basePath:"/tmp",targetPath:e}))return!1;const o=(0,Oo.W1)(r);return void 0!==o&&await Lu(s.default.join(o,"tmp",s.default.relative("/tmp",e)))}(c,t.sandboxPolicy,this.workspacePath))){if(c!==(0,Yo.o1)(await i.getCwd(),this.workspacePath))throw new Ku(c);return yield{type:"stderr",data:`The shell's working directory no longer exists: ${c}. The command did not run. Re-run it with working_directory set to an existing directory.\n`},void(yield{type:"exit",code:1,aborted:!1,localExecutionTimeMs:Math.round(performance.now()-o)})}let l,u,d=0,h=0,p=!1,f=!1,m=!1;t.fileOutputThresholdBytes&&this.projectDir&&(l={buffer:"",lineCount:0,size:0,threshold:Number(t.fileOutputThresholdBytes)});const g=t.signal,w={CURSOR_AGENT:"1"};t.conversationId&&(w.CURSOR_CONVERSATION_ID=(0,So.sh)(t.conversationId)),t.requestId&&(w.CURSOR_REQUEST_ID=t.requestId),this.projectDir&&(w.AGENT_TRANSCRIPTS=s.default.join(this.projectDir,So.O2));const y=this.options.extraEnvProvider?.(e,t);void 0!==y&&Object.assign(w,y);const v=t.requestScopedEnv??{};for(const[e,t]of Object.entries(v))void 0!==t&&qu(e)&&(w[e]=t);const b=w.CURSOR_REQUEST_ID;void 0!==b&&(w.CURSOR_REQUEST_ID=Uu(b)),function(e,t){const r=Fu,n=Object.keys(t).filter((e=>qu(e)&&!r.includes(e))),o=`builtin unset ${[...Fu,...n].join(" ")} 2>/dev/null || true`,s=[];for(const t of Fu){const r=Bu(e,t);void 0!==r&&s.push(`builtin export ${t}=${Nu(r)}`)}for(const e of n){const r=t[e];void 0!==r&&s.push(`builtin export ${e}=${Nu(r)}`)}const i=e.__CURSOR_SANDBOX_ENV_RESTORE?.trim(),a=process.env.__CURSOR_SANDBOX_ENV_RESTORE?.trim();e.__CURSOR_SANDBOX_ENV_RESTORE=[o,a,i,...s].filter((e=>void 0!==e&&""!==e)).join("; ")}(w,v),void 0!==w.__CURSOR_SANDBOX_ENV_RESTORE&&(w.__CURSOR_SANDBOX_ENV_RESTORE=function(e,t){let r=e;for(const e of t){if(null==e||0===e.length)continue;const t=Uu(e);t!==e&&(r=r.split(e).join(t))}return r}(w.__CURSOR_SANDBOX_ENV_RESTORE,[t.requestId,b,v.CURSOR_REQUEST_ID,process.env.CURSOR_REQUEST_ID]));const S=function(e,t){const r=Bu(t,"CURSOR_AGENT_STORE_FILES_DIR"),n=function(e){if(void 0===e)return[];try{const t=JSON.parse(e);if("object"!=typeof t||null===t)return[];const r=[];for(const e of Object.values(t))"object"==typeof e&&null!==e&&"path"in e&&"readOnly"in e&&"string"==typeof e.path&&"boolean"==typeof e.readOnly&&r.push({path:e.path,readOnly:e.readOnly});return r}catch{return[]}}(Bu(t,"CURSOR_AGENT_STORE_SHARED_PATHS"));if(void 0===r&&0===n.length)return e;const o=e?.perUser,s=e?.perRepo??e?.perUser??e?.teamAdmin;if("workspace_readwrite"!==s?.type&&"workspace_readonly"!==s?.type)return e;const i=o?.type===s.type?{...o}:{type:s.type};var a;void 0!==r&&(a=r,"workspace_readwrite"!==i.type?i.additionalReadonlyPaths=Gu(i.additionalReadonlyPaths,a):i.additionalReadwritePaths=Gu(i.additionalReadwritePaths,a));for(const e of n)e.readOnly||"workspace_readwrite"!==i.type?i.additionalReadonlyPaths=Gu(i.additionalReadonlyPaths,e.path):i.additionalReadwritePaths=Gu(i.additionalReadwritePaths,e.path);return{...e,perUser:i}}(t.sandboxPolicy,w),k=(0,Oo.CG)(S??Oo.BM);let _,C,E,x;S&&(yield{type:"start",sandboxed:"workspace_readonly"===k||"workspace_readwrite"===k}),t.askpassConfig&&!Ou&&(w.SUDO_ASKPASS=t.askpassConfig.helperPath,w.CURSOR_ASKPASS_SOCKET=t.askpassConfig.socketPath,w.CURSOR_ASKPASS_SECRET=t.askpassConfig.secret);const P=this.options.codePageLookup??gu,R=(this.options.outputFallbackEncoding??(()=>P.current()))(),I=()=>function(e){if(void 0===e)return bu();const t=mu.get(e);return void 0!==t&&Vs.encodingExists(e)?function(e,t){const{script:r}=t,o=function(e){const{script:t}=e,r=new RegExp(`${t.source}{2}`);let n=!1,o=!1,s=!1;return{note(i,a){if(!s&&0!==i.length){if(!n){const e=yu.exec(i);null!==e&&(n=!0,s=t.test(e[0]))}s||=o&&t.test(i[0])||r.test(i)||e.doubleByte&&void 0!==a&&ku.test(a.toString("latin1")),o=t.test(i[i.length-1])}},isUtf8Text:()=>s,reset(){n=!1,o=!1,s=!1}}}(t);let s=wu,i=0,a="utf8",c=!1;const l=()=>{a="utf8",o.reset(),i=0},u=(t,n)=>{const s=n?vu(t):0,l=t.subarray(0,t.length-s),u=l.toString("utf8");if("replacement"!==a){const t=l.subarray(i);if(i=0,o.note(t.toString("utf8"),t),o.isUtf8Text())a="replacement";else{const t=0===u.length?"":u[u.length-1],o=n&&r.test(t)?Buffer.byteLength(t):0,d=function(e,t,r){let n=Su(e,t);if(!r)return{text:n,keep:0};const o=Math.min(3,t.length);let s=0;for(;s0&&(c=!0),{text:d.text,keep:i+s}}}return{text:u,keep:s}};return{write:e=>{const t=0===s.length?e:Buffer.concat([s,e]);if(s=wu,"utf8"===a){const e=t.subarray(0,t.length-vu(t));if((0,n.isUtf8)(e)){e.length{const t=e.lastIndexOf("\n");-1===t?o.note(e):(l(),o.note(e.slice(t+1)))})(r),r}}let r="",i=0;for(;i0&&(s=Buffer.from(d.subarray(u.length))),-1===e?o.note(n):l(),i=c;continue}a="undecided"}const{text:h,keep:p}=u(d,-1===e);r+=h,p>0&&(s=Buffer.from(d.subarray(d.length-p))),-1!==e&&l(),i=c}return r},end:()=>{const e=s;s=wu;const t=0===e.length?"":"utf8"===a?e.toString("utf8"):u(e,!1).text;return l(),t},usedCodePage:()=>c}}(e,t):bu()}(R),T={stdout:Tu(I),stderr:Tu(I)},A=new Cl,M=Ul(this.options.encodingSlices,e)?new nu:void 0,D=void 0===M?void 0:function(e,t,r){return n=>{try{const o=function(e,t,r){if(!(Object.hasOwn(Bc,e.shell)&&Object.hasOwn(Wc,e.parse)&&Object.hasOwn(Hc,e.stateFile)&&Object.hasOwn(qc,e.exit)))return;let n="withheld";if(r){if("function"!=typeof e.callsExit)return;n=!0===e.callsExit()?"yes":"no"}return{shell_kind:e.shell,parse:e.parse,calls_exit:n,state_file:e.stateFile,exit:e.exit,version_bucket:jc(t)}}(n,t,r);if(void 0===o)return;zc.increment(e,1,{...o})}catch(t){Uc.warn(e,"PowerShell run was not counted (command unaffected)",{error:t instanceof Error?t.name:"unknown"})}}}(e,this.options.encodingSlices?.clientVersion,function(e,t){return!0===jl(e?.commandTextReadable,t)}(this.options.encodingSlices,e));let O=!1;const F=()=>{if(!O){O=!0;try{const t={stdout:T.stdout.branch(),stderr:T.stderr.branch()};for(const r of A.labels(t,P.pages()))Du.increment(e,1,r);M?.record(this.options.encodingSlices,e,t,P.lastOutcome())}catch(t){Mu.warn(e,"shell output encoding check failed (command result unaffected)",{error:t instanceof Error?t.message:String(t)})}}},N=e=>{void 0!==l&&0!==e.length&&(l.file?l.file.write(e):l.buffer+=e)},L=function*(){const e={stdout:p,stderr:f};for(const t of["stdout","stderr"]){const r=T[t].end();if(0===r.length)continue;const n=void 0!==l&&!0!==l.truncated;n&&N(r),!n&&e[t]||(A.note(t,r),M?.noteText(t,r)),e[t]||(yield{type:t,data:r})}F()};try{for await(const r of i.execute(e,t.command,{signal:g,workingDirectory:c,env:w,sandboxPolicy:S,sandboxWorkspaceRoot:this.workspacePath,pipeStdin:t.pipeStdin??!1,keepBackgroundJobs:this.options.keepBackgroundJobs??!1,bufferOutputEvents:this.options.shellOutputBackpressureOptions?.bufferOutputEvents,outputLimiterOptions:this.options.shellOutputBackpressureOptions?.outputLimiterOptions,powershellUtf8Console:zu(this.options.powershellUtf8Console),powershellUtf8ChildEnv:zu(this.options.powershellUtf8ChildEnv),powershellParseAfterUtf8Switch:zu(this.options.powershellParseAfterUtf8Switch),powershellWebRequestUtf8:zu(this.options.powershellWebRequestUtf8),powershellPerLineStateDump:zu(this.options.powershellPerLineStateDump),...void 0===D?{}:{powershellRunObserver:D}})){_=0,C="",E="",x="";let e=!1,t=!1;if("stdout"===r.type||"stderr"===r.type){const n=T[r.type],o="stdout"===r.type?p:f,i=void 0===l||!0===l.truncated;let a=!1;if(!o||!i){_=r.data.length;const c="stdout"===r.type?d:h,p=!o&&c+_<=rs,f=void 0!==l&&!0!==l.truncated&&l.size+_<=Mc;"stdout"===r.type?e=p:t=p;const m=!o&&!p,g=!i&&!f;if((m||g)&&(x=n.peek(),g&&N(x),m&&(E=x)),(p||f)&&(C=n.write(r.data),a=!0,A.note(r.type,C),M?.noteBytes(r.type,r.data),M?.noteText(r.type,C)),void 0!==l&&l.size+_>Mc)l.truncated=!0;else if(f&&void 0!==l)if(l.size+=_,l.lineCount+=Vu(r.data),l.file)l.file.write(C);else if(l.buffer+=C,l.size>l.threshold){const e=s.default.join(this.projectDir,$c);l.path=s.default.join(e,`${(0,bo.randomUUID)()}.txt`);try{await(0,Co.mkdir)(e,{recursive:!0}),l.file=(0,xo.createWriteStream)(l.path),l.file.on("error",(e=>{u??=e})),l.file.write(l.buffer)}catch(e){u??=e instanceof Error?e:new Error(String(e)),l.truncated=!0}l.buffer=""}}a||(n.end(),A.note(r.type,x),M?.noteDropped(r.type),M?.noteText(r.type,x))}switch(r.type){case"stdout":e?(d+=_,C&&(yield{type:"stdout",data:C})):p||(E&&(yield{type:"stdout",data:E}),p=!0,yield{type:"stdout_trimmed"});break;case"suppressed_output":m||(m=!0,yield{type:"stdout",data:Oo.Ls});break;case"stderr":t?(h+=_,C&&(yield{type:"stderr",data:C})):f||(E&&(yield{type:"stderr",data:E}),f=!0,yield{type:"stderr_trimmed"});break;case"exit":{yield*L();const e=Math.max(0,Math.round(performance.now()-o));let t;if(l?.file){if(l.truncated){const e=`\n... (output truncated at ${l.size} bytes) ...\n`;l.file.write(e),l.size+=e.length,l.lineCount+=Js(e)-1}const e=await new Promise((e=>l.file.end(e)));u??=e??void 0,u?await(0,Co.rm)(l.path,{force:!0}):t=new Dc.pV({filePath:l.path,sizeBytes:BigInt(l.size),lineCount:BigInt(l.lineCount)})}u&&void 0!==l?.path&&(yield{type:"stderr",data:`\nThe full output could not be saved to ${l.path}: ${u.message}\n`}),yield{type:"exit",code:r.code,signal:r.signal,aborted:r.aborted,outputLocation:t,localExecutionTimeMs:e};break}case"stdin_ready":M?.noteShell(r.shell),yield{type:"stdin_ready",stdin:r.stdin,pid:r.pid};break;case"sandbox_denies":yield{type:"sandbox_denies",events:r.events}}}yield*L()}catch(t){if("ENOENT"===Sc(t)&&(0,qs.$f)(c))try{Mu.warn(e,"shell failed with ENOENT in an agent store working directory",{...await(0,qs.KZ)(c)})}catch{}throw t}finally{F()}}catch(e){r.error=e,r.hasError=!0}finally{$u(r)}}async getCwd(e){return this.executorFor(e).getCwd()}getWorkspacePath(){if(!this.workspacePath)throw new Error("Workspace path is not configured");return this.workspacePath}}class Zu{constructor(e,t){this.innerExecutor=e,this.shellManager=t}async*execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{Au(r,(0,$.VI)(e.withName("ManagedShellCoreExecutor.execute")),!1),Mu.info(e,"Executing shell command",{command:t.command,workingDirectory:t.workingDirectory,toolCallId:t.toolCallId});let n=null;t.toolCallId&&(n=this.shellManager.getOrCreateShellEmitter(t.toolCallId));for await(const r of this.innerExecutor.execute(e,t)){if(n)switch(r.type){case"stdin_ready":n.emit({type:"stdin_ready",stdin:r.stdin,pid:r.pid});break;case"start":n.emit({type:"start",sandboxed:r.sandboxed});break;case"stdout":n.emit({type:"stdout",data:r.data});break;case"stderr":n.emit({type:"stderr",data:r.data});break;case"exit":n.emit({type:"exit",code:r.code??-1,aborted:r.aborted})}yield r}}catch(e){r.error=e,r.hasError=!0}finally{$u(r)}}async getCwd(e){return this.innerExecutor.getCwd(e)}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}class Xu{constructor(e,t){this.innerExecutor=e,this.askpassConfig=t}async*execute(e,t){const r={...t,askpassConfig:t.askpassConfig??this.askpassConfig};yield*this.innerExecutor.execute(e,r)}async getCwd(e){return this.innerExecutor.getCwd(e)}getWorkspacePath(){return this.innerExecutor.getWorkspacePath()}}async function Qu(e,t){switch(e.type){case"needsApproval":return t.onNeedsApproval(e.approvalReason,e.approvalDetails);case"userRejected":return t.onUserRejected(e.reason);case"cursorIgnore":return t.onPermissionDenied("Blocked by cursor ignore");case"permissionsConfig":return t.onPermissionDenied("Blocked by permissions configuration",{isReadonly:e.isReadonly});case"cursorFiles":return t.onPermissionDenied("Blocked by cursor files protection");case"adminBlock":return t.onPermissionDenied("Blocked by admin repository block");case"adminCommandDenylist":return t.onPermissionDenied(Ss(e.pattern));case"unsafeResolution":return t.onPermissionDenied(e.message);default:{const t=e;throw new Error(`Unhandled block reason type: ${JSON.stringify(t)}`)}}}function Yu(e){switch(e.type){case"userRejected":return e.reason;case"unsafeResolution":return e.message;case"adminCommandDenylist":return Ss(e.pattern);case"needsApproval":case"cursorIgnore":case"adminBlock":case"permissionsConfig":case"cursorFiles":return"Command is not allowed";default:{const t=e;return`Command is not allowed (${JSON.stringify(t)})`}}}function ed(e,t,r){return"permissionsConfig"===r.type?{case:"permissionDenied",value:new he.jn({command:e,workingDirectory:t,error:"Command blocked by permissions configuration",isReadonly:r.isReadonly??!1})}:{case:"rejected",value:new he.pZ({command:e,workingDirectory:t,reason:Yu(r)})}}var td=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const rd=(0,l.h)("local-exec:background-shell");function nd(e,t,r){return new Do.Lt({result:ed(e,t,r)})}class od{constructor(e,t){this.id=e,this.abortController=t,this.disposed=!1,this.completed=!1,this.completionListeners=[]}abort(){this.abortController.abort()}dispose(){this.disposed||(this.disposed=!0,this.abortController.signal.aborted||this.abortController.abort())}get signal(){return this.abortController.signal}isDisposed(){return this.disposed}onComplete(e){this.completed&&this.completion?e(this.completion):this.completionListeners.push(e)}markCompleted(e){if(this.completed)return;this.completed=!0,this.completion=e;const t=[...this.completionListeners];this.completionListeners=[];for(const r of t)r(e)}}async function sd(e,t){let r;try{for(let n=await t.next();!n.done;n=await t.next())"stdin_ready"===n.value.type?(e.stdin=n.value.stdin,e.pid=n.value.pid):"exit"===n.value.type&&(r={code:n.value.code,signal:n.value.signal,aborted:n.value.aborted,outputPath:n.value.outputLocation?.filePath})}catch(e){}finally{e.markCompleted(r??{code:null,aborted:e.signal.aborted})}}function id(e){e().catch((()=>{}))}class ad{constructor(e){if(this.args=e,this.carryover="",this.matchedOccurrences=0,this.emittedNotifications=0,this.finished=!1,this.monotonicStartMs=performance.now(),this.limit=e.config.notificationLimit??100,e.config.pattern.length>500)throw new Error("Output notification pattern exceeds 500 characters");this.regex=Qo.L3.compile(e.config.pattern,Qo.L3.MULTILINE)}observe(e){if(this.finished||this.matchedOccurrences>=this.limit||0===e.length)return;if(e.length>65536){for(const t of function(e){if(0===e.length)return[];const t=Math.max(1,Math.trunc(65536)||1),r=[];let n=0;for(;n=this.limit)break;this.observe(t)}return}const t=this.carryover.length,r=`${this.carryover}${e}`,n=this.regex.matcher(r);for(;this.matchedOccurrencest&&this.queueMatch(e)}this.carryover=Ko(r,1024)}finish(){this.finished||(this.finished=!0,this.flushPendingBatch("finish"),this.clearFlushTimer(),0===this.matchedOccurrences&&this.recordWatchOutcome("silent",{silent_ms:ud(this.monotonicStartMs)}))}queueMatch(e){if(this.matchedOccurrences>=this.limit)return;this.matchedOccurrences+=1;const t=this.matchedOccurrences,r=function(e,t){return e.length<=5e3?`${t}: ${e}`:`${t} is ${e.length} characters; omitted from notification detail.`}(e,1===t?"Matched text":"Latest match");return 1===t?(this.emitNotification({startOccurrence:t,endOccurrence:t,count:1,matchedTextDetail:r}),this.recordWatchOutcome("matched",{first_match_ms:ud(this.monotonicStartMs)}),void(t===this.limit&&this.emitLimitReachedNotification())):(this.pendingBatch?(this.pendingBatch.endOccurrence=t,this.pendingBatch.count+=1,this.pendingBatch.matchedTextDetail=r):this.pendingBatch={startOccurrence:t,endOccurrence:t,count:1,matchedTextDetail:r},t===this.limit?(this.flushPendingBatch("limit"),void this.emitLimitReachedNotification()):void this.scheduleFlush())}scheduleFlush(){if(void 0!==this.flushTimer)return;const e=this.getDebounceMs();this.flushTimer=setTimeout((()=>{this.flushPendingBatch("debounce")}),e)}getDebounceMs(){const e=this.args.debounceMs??function(e){const t=e.debounce;if(void 0!==t&&Number.isFinite(t))return Math.ceil(1e3*t)}(this.args.config)??5e3;return Math.max(e,5e3)}clearFlushTimer(){void 0!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0)}flushPendingBatch(e){const t=this.pendingBatch;t&&(this.pendingBatch=void 0,this.clearFlushTimer(),this.emitNotification(t))}emitNotification(e){this.emittedNotifications+=1;const t=this.args.config.reason.trim()||`Shell output contains /${this.args.config.pattern}/`,r=this.args.config.pattern,n=void 0!==e.matchedTextDetail?` ${e.matchedTextDetail}.`:"",o=1===e.count?`Shell output has pattern /${r}/. This is occurrence number ${e.startOccurrence}.${n} The title message is being displayed to the user.`:`Shell output matched /${r}/ ${e.count} more times since the previous notification. The title message is being displayed to the user.${n}`,s=Ro(String(this.args.shellId),this.emittedNotifications);var i;this.args.registry.enqueue({conversationId:this.args.conversationId,id:s,source:"shell",payload:{taskId:s,...void 0!==this.args.toolCallId?{toolCallId:this.args.toolCallId}:{},kind:"shell",status:"success",title:(i=t,i.length<=500?i:`${Vo(i,500)}...`),detail:o,outputPath:this.args.outputPath,reason:"task_progress"}})}emitLimitReachedNotification(){this.emittedNotifications+=1;const e=this.args.config.pattern,t=Ro(String(this.args.shellId),this.emittedNotifications);this.args.registry.enqueue({conversationId:this.args.conversationId,id:t,source:"shell",payload:{taskId:t,...void 0!==this.args.toolCallId?{toolCallId:this.args.toolCallId}:{},kind:"shell",status:"success",title:`Notification limit reached (${this.limit})`,detail:`Shell output matched /${e}/ ${this.limit} times and has reached the notification limit. No further notifications will be sent for this pattern. To continue monitoring, read the output file directly at the output path.`,outputPath:this.args.outputPath,reason:"task_progress"}}),this.recordWatchOutcome("limit_reached")}recordWatchOutcome(e,t){void 0!==this.args.ctx&&rd.info(this.args.ctx,"agent.shell_output_notification_match",{event:"agent.shell_output_notification_match",outcome:e,shell_id:this.args.shellId,conversation_id:this.args.conversationId,tool_call_id:this.args.toolCallId,limit:this.limit,...t})}}class cd{constructor(e,t,r){this.innerFactory=e,this.projectDir=t,this.backgroundWorkRegistry=r}async spawn(e,t){const r=this.createObserver(e.ctx,e.shellId,e.conversationId,e.toolCallId,e.outputNotification);if(!r)return this.innerFactory.spawn(e,t);try{return await this.innerFactory.spawn(e,this.createObservingExecutor(t,r))}catch(e){throw r.finish(),e}}async adopt(e){const t=this.createObserver(e.ctx,e.shellId,void 0,e.toolCallId,e.outputNotification);if(!t)return this.innerFactory.adopt(e);e.initialOutput.length>0&&t.observe(e.initialOutput);try{return await this.innerFactory.adopt({...e,eventIterator:this.createObservingIterator(e.eventIterator,t)})}catch(e){throw t.finish(),e}}createObserver(e,t,r,n,o){if(!this.backgroundWorkRegistry||!o)return;if(0===o.pattern.trim().length)return;const i=s.join(this.projectDir,"terminals",`${t}.txt`);try{return new ad({shellId:t,outputPath:i,config:o,conversationId:r??Po,toolCallId:n,registry:this.backgroundWorkRegistry,ctx:e})}catch(r){return void(void 0!==e&&rd.warn(e,"Invalid shell output notification pattern",{shellId:t,error:r instanceof Error?r.message:String(r)}))}}createObservingExecutor(e,t){const r=e.execute.bind(e);return{...e,execute:async function*(e,n){try{for await(const o of r(e,n))"stdout"===o.type||"stderr"===o.type?t.observe(o.data):"exit"===o.type&&t.finish(),yield o}finally{t.finish()}}}}createObservingIterator(e,t){const r=e.return?.bind(e);return{next:async()=>{try{const r=await e.next();if(r.done)t.finish();else{const e=r.value;"stdout"===e.type||"stderr"===e.type?t.observe(e.data):"exit"===e.type&&t.finish()}return r}catch(e){throw t.finish(),e}},return:async e=>(t.finish(),r?r(e):{done:!0,value:void 0})}}}class ld{async spawn(e,t){const r=new AbortController,n=new od(e.shellId,r),o=t.execute(e.ctx,{command:e.command,workingDirectory:e.workingDirectory,signal:r.signal,toolCallId:e.toolCallId,conversationId:e.conversationId,requestId:e.requestId,secretScopeId:e.secretScopeId,sandboxPolicy:e.sandboxPolicy,pipeStdin:e.enableWriteShellStdinTool,showElapsedTime:!0})[Symbol.asyncIterator]();try{for(let e=await o.next();!e.done;e=await o.next())if("stdin_ready"===e.value.type){n.stdin=e.value.stdin,n.pid=e.value.pid;break}}catch(e){if(e instanceof Oo.SandboxUnsupportedError||e instanceof Ku)throw e}return id((()=>sd(n,o))),n}async adopt(e){const t=new od(e.shellId,e.abortController);return t.stdin=e.stdin,t.pid=e.pid,id((()=>sd(t,e.eventIterator))),t}}function ud(e){return Math.round(performance.now()-e)}function dd(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}function hd(e){const t=String(e.runningForMs).padEnd(9," "),r=e.status.padEnd(9," ");let n="---\n";return void 0!==e.pid&&0!==e.pid&&(n+=`pid: ${e.pid}\n`),n+=`cwd: ${dd(e.cwd)}\n`,n+=`command: ${dd(e.command)}\n`,void 0!==e.title&&e.title.trim().length>0&&(n+=`title: ${dd(e.title)}\n`),n+=`status: ${r}\n`,n+=`started_at: ${e.startedAt}\n`,n+=`running_for_ms: ${t}\n`,n+="---\n",n}function pd(e){return`\n[${e} truncated by cursor: the command wrote more than 1048576 characters to ${e}; only the first 1048576 were captured and the rest was dropped from this file]\n`}class fd{constructor(e,t){this.innerFactory=e,this.projectDir=t}async spawn(e,t){const r=s.join(this.projectDir,"terminals");await(0,Co.mkdir)(r,{recursive:!0});const n=this.createLoggingExecutor(t,e,r);return this.innerFactory.spawn(e,n)}createLoggingExecutor(e,t,r){const o=e.execute.bind(e);return{...e,execute:async function*(e,i){let a,c,l,u=!1,d=!1,h=!1,p=!1;const f=Date.now(),m=new Date(f).toISOString(),g=performance.now();let w,y="running",v=!1,b=Promise.resolve();const S=async e=>{if(c)try{await c.write(e)}catch(e){}},k=t.shellId,_=s.join(r,`${k}.txt`),C=async()=>{if(!a)return;const e=ud(g),r=hd({pid:w,cwd:t.workingDirectory,command:t.command,title:t.description,status:y,startedAt:m,runningForMs:e});try{await a.write(r,0,"utf8")}catch(e){}},E=()=>(b=b.then(C).catch((()=>{})),b),x=()=>{void 0!==l&&(clearInterval(l),l=void 0)},P=async e=>{if(p)return;p=!0,w=e;const r=ud(g),n=hd({pid:e,cwd:t.workingDirectory,command:t.command,title:t.description,status:y,startedAt:m,runningForMs:r});await(0,Co.writeFile)(_,n,"utf8"),l=setInterval((()=>{E()}),5e3)},R=async()=>{a||(a=await xo.promises.open(_,"r+")),c||(c=await xo.promises.open(_,"a"))},I=async(e,t)=>{if(!v){if(v=!0,x(),p||await P(),await R(),void 0!==t){const e=ud(g),r=`\n---\n${t}\n`+(i.showElapsedTime?`elapsed_ms: ${e}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await S(r)}y=e,await E()}};try{for await(const r of o(e,i)){if("stdout"===r.type)p||(await P(),await R()),await S(r.data);else if("stderr"===r.type)p||(await P(),await R()),await S(r.data);else if("stdout_trimmed"!==r.type||d)if("stderr_trimmed"!==r.type||h)if("stdin_ready"!==r.type||u)"exit"===r.type&&await I(r.aborted?"aborted":0===r.code?"succeeded":"failed",`exit_code: ${r.code??"unknown"}`);else{u=!0,p||(await P(r.pid),await R());const e=r.stdin;if(e&&!0!==t.suppressStdinLogging){const t=e=>{if(null==e)return;const t="string"==typeof e?e:n.Buffer.isBuffer(e)||e instanceof Uint8Array?n.Buffer.from(e).toString():"";if(!t)return;const r=t.endsWith("\n")?t:`${t}\n`;S(`[stdin] ${r}`)},r=e.write.bind(e);if(e.write=(e,n,o)=>(t(e),r(e,n,o)),"function"==typeof e.end){const r=e.end.bind(e);e.end=(e,n,o)=>(void 0!==e&&t(e),r(e,n,o))}}}else h=!0,p||await P(),await R(),await S(pd("stderr"));else d=!0,p||await P(),await R(),await S(pd("stdout"));yield r}if(!v){const e=i.signal?.aborted??!1;await I(e?"aborted":"failed")}}catch(e){const t=i.signal?.aborted??!1,r=dd(e instanceof Error?e.message:"Unknown error");if(await I(t?"aborted":"failed",t?void 0:`error: ${r}`),!t)throw e}finally{if(x(),await b,a)try{await a.close()}catch{}if(c)try{await c.close()}catch{}}}}}async adopt(e){const t=s.join(this.projectDir,"terminals");await(0,Co.mkdir)(t,{recursive:!0});const r=s.join(t,`${e.shellId}.txt`),n=e.startTime,o=new Date(n).toISOString(),i=e.monotonicStartMs;let a="running";const c=ud(i),l=hd({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:a,startedAt:o,runningForMs:c})+(e.initialOutput??"");await(0,Co.writeFile)(r,l,"utf8");const u=await xo.promises.open(r,"r+");let d;try{d=await xo.promises.open(r,"a")}catch(e){throw await u.close(),e}let h=!1,p=!1,f=!1,m=!1,g=Promise.resolve();const w=async()=>{const t=ud(i),r=hd({pid:e.pid,cwd:e.workingDirectory,command:e.command,title:e.description,status:a,startedAt:o,runningForMs:t});try{await u.write(r,0,"utf8")}catch{}},y=()=>(g=g.then(w).catch((()=>{})),g);let v=setInterval((()=>{y()}),5e3);const b=()=>{void 0!==v&&(clearInterval(v),v=void 0)},S=async()=>{if(!h){h=!0,b(),await g;try{await u.close()}catch{}try{await d.close()}catch{}}},k=async e=>{try{await d.write(e)}catch(e){}},_=async(t,r)=>{if(!p){if(p=!0,b(),void 0!==r){const t=ud(i),n=`\n---\n${r}\n`+(e.showElapsedTime?`elapsed_ms: ${t}\n`:"")+`ended_at: ${(new Date).toISOString()}\n---\n`;await k(n)}a=t,await y()}},C={next:async()=>{try{const t=await e.eventIterator.next();if(t.done){if(!p){const t=e.abortController.signal.aborted;await _(t?"aborted":"failed")}}else{const e=t.value;"stdout"===e.type||"stderr"===e.type?await k(e.data):"stdout_trimmed"!==e.type||f?"stderr_trimmed"!==e.type||m?"exit"===e.type&&(await _(e.aborted?"aborted":0===e.code?"succeeded":"failed",`exit_code: ${e.code??"unknown"}`),await S()):(m=!0,await k(pd("stderr"))):(f=!0,await k(pd("stdout")))}return t.done&&await S(),t}catch(t){const r=e.abortController.signal.aborted;throw await _(r?"aborted":"failed"),await S(),t}},return:async()=>{if(!p){const t=e.abortController.signal.aborted;await _(t?"aborted":"failed")}return await S(),e.eventIterator.return?e.eventIterator.return():{done:!0,value:void 0}}};return this.innerFactory.adopt({...e,eventIterator:C})}}class md{constructor(e,t){this.factory=e,this.backgroundWorkRegistry=t,this.runningShells=new Map,this.nextShellId=1e3+Math.floor(999e3*Math.random())}registerShellWork(e,t){const r=String(e.id);this.backgroundWorkRegistry?.upsertWork({id:r,kind:"shell",state:"running",metadata:Io(t),abort:()=>{this.abort(e.id)}})}clearShellWork(e){this.backgroundWorkRegistry?.clearWork(String(e))}cleanupShell(e){this.runningShells.has(e)&&(this.runningShells.delete(e),this.clearShellWork(e))}enqueueShellCompletion(e,t,r,n,o,s){if(!this.backgroundWorkRegistry)return;const i=s.aborted?"aborted":0===s.code?"success":"error",a=function(e){if(!e.aborted)return void 0!==e.signal?`signal=${e.signal}`:null!==e.code&&0!==e.code?`exit_code=${e.code}`:void 0}(s),c=function(e){if(!e.aborted)return void 0!==e.signal?{kind:"signal",signal:e.signal}:null!==e.code?{kind:"exit",code:e.code}:void 0}(s),l=n.description?.trim()?n.description:void 0,u=String(e);this.backgroundWorkRegistry.enqueue({conversationId:r??Po,id:u,source:"shell",payload:{taskId:u,...void 0!==t?{toolCallId:t}:{},kind:"shell",status:i,title:n.description||n.command,...a?{detail:a}:{},...s.outputPath?{outputPath:s.outputPath}:{},reason:"task_finished",durationMs:ud(o),...c?{shellEnd:c}:{},...l?{description:l}:{}}})}async spawn(e,t){const r=await this.factory.spawn(e,t),n=Date.now(),o=performance.now();{const __t3b=globalThis[Symbol.for("@cursor/sdk.backgroundShell")];if(typeof __t3b==="function")try{__t3b({conversationId:e.conversationId,toolCallId:e.toolCallId,command:e.command,description:e.description,shell:r})===!0&&(r.__t3kept=!0)}catch{}}return this.runningShells.set(r.id,r),this.registerShellWork(r,{title:e.description||e.command,cwd:e.workingDirectory,startTimeMs:n}),r.signal.addEventListener("abort",(()=>{this.cleanupShell(r.id)})),r.onComplete?.((t=>{this.enqueueShellCompletion(r.id,e.toolCallId,e.conversationId,{command:e.command,description:e.description},o,t),this.cleanupShell(r.id)})),{shellId:r.id,pid:r.pid}}async adopt(e){const t=await this.factory.adopt(e);{const __t3b=globalThis[Symbol.for("@cursor/sdk.backgroundShell")];if(typeof __t3b==="function")try{__t3b({conversationId:e.conversationId,toolCallId:e.toolCallId,command:e.command,description:e.description,shell:t})===!0&&(t.__t3kept=!0)}catch{}}return this.runningShells.set(t.id,t),this.registerShellWork(t,{title:e.description||e.command,cwd:e.workingDirectory,startTimeMs:e.startTime}),t.signal.addEventListener("abort",(()=>{this.cleanupShell(t.id),e.onCleanup?.()})),t.onComplete?.((r=>{this.enqueueShellCompletion(t.id,e.toolCallId,void 0,{command:e.command,description:e.description},e.monotonicStartMs,r),this.cleanupShell(t.id),e.onCleanup?.()})),{shellId:t.id,pid:e.pid}}generateShellId(){for(let e=0;e<=998999;e++){this.nextShellId>999999&&(this.nextShellId=1e3);const e=this.nextShellId;if(this.nextShellId+=1,!this.runningShells.has(e))return e}throw new Error("No available background shell id in range")}abort(e){const t=this.runningShells.get(e);return!!t&&(t.abort(),this.runningShells.delete(e),this.clearShellWork(e),!0)}isRunning(e){return this.runningShells.has(e)}dispose(){for(const[e,t]of this.runningShells)t.__t3kept||t.dispose(),this.clearShellWork(e);this.runningShells.clear()}async writeStdin(e,t){const r=this.runningShells.get(e);if(!r)throw new Error("Shell not found");if(!r.stdin)throw new Error("Shell stdin not available");const n=t.indexOf(""),o=-1!==n?n:t.indexOf("\\u0004");if(-1!==o){const e=t.substring(0,o);e.length>0&&await new Promise(((t,n)=>{r.stdin.write(e,(e=>{e?n(e):t(void 0)}))})),r.stdin.end()}else await new Promise(((e,n)=>{r.stdin.write(t,(t=>{t?n(t):e(void 0)}))}))}}new WeakMap;class gd{constructor(e,t){this.inner=e,this.ownerConversationId=t}enqueue(e){this.inner.enqueue({...e,conversationId:this.ownerConversationId})}enqueueCompletion(e){this.enqueue({conversationId:this.ownerConversationId,id:e.taskId,source:e.kind,payload:e})}pull(e){return this.inner.pull(e)}ack(e){return this.inner.ack(e)}nack(e,t){this.inner.nack(e,t)}suppress(e,t){this.inner.suppress(e,t)}upsertWork(e){this.inner.upsertWork(e)}clearWork(e){return this.inner.clearWork(e)}abortWork(e){return this.inner.abortWork(e)}hasRunningWork(e){return this.inner.hasRunningWork(e)}abortAllWork(e){return this.inner.abortAllWork(e)}listWork(e){return this.inner.listWork(e)}drainCompletions(){return this.inner.drainCompletions()}hasPendingCompletions(e){return this.inner.hasPendingCompletions(e)}markAwaitedCompletion(e){this.inner.suppress(this.ownerConversationId,e)}}class wd{constructor(e,t,r,n,o,s,i,a){if(this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r,void 0!==a)return this.backgroundShellManager=a,void(this.ownsBackgroundShellManager=!1);const c=s&&void 0!==i?new gd(s,i):s,l=o??function(e){const t=new ld;return new fd(t,e)}(n),u=new cd(l,n,c);this.backgroundShellManager=new md(u,c),this.ownsBackgroundShellManager=!0}getManager(){return this.backgroundShellManager}dispose(){this.ownsBackgroundShellManager&&this.backgroundShellManager.dispose()}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,$.VI)(e.withName("LocalBackgroundShellExecutor.execute")),!1);const n=t.command,o=t.sandboxPolicy?ls(t.sandboxPolicy):void 0,s=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),i=(0,Yo.o1)(s),a=new he.HO(Wo(n).structured),c=ks({command:n,parsingResult:a,blockedCommands:t.adminCommandDenylist});if(void 0!==c)return new Do.Lt({result:{case:"rejected",value:new he.pZ({command:n,workingDirectory:i,reason:c})}});let l;if(rd.info(e,"Background shell: approval gate reached",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,hasSmartModeApproval:void 0!==t.smartModeApproval,hasSmartModeApprovalReason:void 0!==t.smartModeApproval?.reason,hasSmartModeApprovalRequestId:void 0!==t.smartModeApproval?.requestId,requestedPolicyType:o?.type??"undefined",parserCommandCount:a.executableCommands.length,classifierCommandCount:t.classifierResult?.commands.length??0,commandLength:n.length}),Mo(t)){const r=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:i,skipUnsafeWorkingDirectoryBlock:!0,command:n,parsingResult:a,toolCallId:t.toolCallId,resolveSkippedApprovalPolicy:!0},o);if("block"===r.kind)return rd.info(e,"Background shell: invariant blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,skipApproval:t.skipApproval}),nd(n,i,r.reason);l=r.policy??o,rd.info(e,"Background shell: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:o?.type??"undefined",effectivePolicyType:l?.type??"undefined"})}else{const r=await this.permissionsService.shouldBlockShellCommand(e,n,{workingDirectory:i,timeout:0,parsingResult:a,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Ao(t)},o);if("block"===r.kind)return rd.info(e,"Background shell: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:r.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),nd(n,i,r.reason);l=r.policy,rd.info(e,"Background shell: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:l.type})}l=await Tc(l,{command:n,workingDirectory:i,parsingResult:a,permissionsService:this.permissionsService,ignoreService:this.ignoreService});try{const r=this.backgroundShellManager.generateShellId(),o=l?{perUser:l}:void 0,s={ctx:e,command:n,workingDirectory:i,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:o,shellId:r,enableWriteShellStdinTool:t.enableWriteShellStdinTool,suppressStdinLogging:t.suppressStdinLogging,description:t.description,outputNotification:t.outputNotification},a=await this.backgroundShellManager.spawn(s,this.coreExecutor);return new Do.Lt({result:{case:"success",value:new Do.Po({shellId:r,command:n,workingDirectory:i,pid:a.pid})}})}catch(r){if(r instanceof Oo.SandboxUnsupportedError){const o=l?.type??"unknown";return rd.debug(e,"Background shell: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:o,reason:r.reason}),new Do.Lt({result:{case:"sandboxUnsupported",value:new he.rI({command:n,workingDirectory:i,sandboxPolicyType:o,reason:r.reason??r.message,isReadonly:"workspace_readonly"===o})}})}return new Do.Lt({result:{case:"error",value:new Do.Of({command:n,workingDirectory:i,error:r instanceof Error?r.message:"Unknown error"})}})}}catch(e){r.error=e,r.hasError=!0}finally{td(r)}}writeStdin(e,t){return this.backgroundShellManager.writeStdin(e,t)}}var yd=r("node:async_hooks");r("../../node_modules/.pnpm/minimatch@10.2.5/node_modules/minimatch/dist/esm/index.js");function vd(e){return e instanceof Error?e.message:String(e)}function bd(e){return"Failed to read skill file: "+vd(e)}function Sd(e){return"Invalid skill frontmatter: "+vd(e)}function kd(e,t){return e||t?void 0:"Description is required"}new Set(["EACCES","EPERM","ENOENT","ENOTDIR","EISDIR","ELOOP","ENAMETOOLONG"]);const _d=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function Cd(e){return e.toLocaleString("en-US")}var Ed=r("node:url");const xd={beforeShellExecution:"beforeShellExecution",beforeMCPExecution:"beforeMCPExecution",afterShellExecution:"afterShellExecution",afterMCPExecution:"afterMCPExecution",beforeReadFile:"beforeReadFile",afterFileEdit:"afterFileEdit",beforeTabFileRead:"beforeTabFileRead",afterTabFileEdit:"afterTabFileEdit",stop:"stop",beforeSubmitPrompt:"beforeSubmitPrompt",afterAgentResponse:"afterAgentResponse",afterAgentThought:"afterAgentThought",sessionStart:"sessionStart",sessionEnd:"sessionEnd",preCompact:"preCompact",subagentStart:"subagentStart",subagentStop:"subagentStop",preToolUse:"preToolUse",postToolUse:"postToolUse",postToolUseFailure:"postToolUseFailure",workspaceOpen:"workspaceOpen"},Pd=e=>"string"==typeof e,Rd=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),Id=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),Td=(e,t=[])=>({isValid:e,errors:t});function Ad(e,t,r){void 0===e||Pd(e)||r.push(`${t} must be a string if provided`)}const $d=e=>{const t=[];if(!Rd(e))return t.push("Hook script must be an object with either a 'command' property (command hook) or 'type: \"prompt\"' with a 'prompt' property (prompt hook)"),Td(!1,t);const r=e.type;return"prompt"===r?((e,t)=>{Pd(e.prompt)?""===e.prompt.trim()&&t.push("Prompt hook 'prompt' property cannot be empty"):t.push("Prompt hook must have a 'prompt' property (string)"),void 0!==e.model&&(Pd(e.model)?""===e.model.trim()&&t.push("Prompt hook 'model' cannot be an empty string"):t.push("Prompt hook 'model' must be a string if provided"))})(e,t):"command"===r||void 0===r?((e,t)=>{Pd(e.command)||t.push("Hook script command must be a string")})(e,t):t.push(`Invalid hook type: "${r}". Must be "command", "prompt", or omitted (defaults to "command")`),((e,t)=>{if(void 0!==e.matcher)if(Pd(e.matcher)){if(""!==e.matcher&&"*"!==e.matcher)try{new RegExp(e.matcher)}catch(r){t.push(`Hook script matcher "${e.matcher}" is not a valid regex: ${r?.message??String(r)}`)}}else t.push("Hook script matcher must be a string if provided");if(void 0!==e.timeout&&("number"!=typeof e.timeout?t.push("Hook script timeout must be a number (seconds)"):e.timeout<=0?t.push("Hook script timeout must be a positive number"):e.timeout>3600&&console.warn(`[hooks] Hook timeout of ${e.timeout}s is very long (>1 hour)`)),void 0!==e.loop_limit){const r=e.loop_limit;null!==r&&("number"!=typeof r?t.push("Hook script loop_limit must be a positive integer or null"):Number.isInteger(r)?r<=0&&t.push("Hook script loop_limit must be a positive integer (use null for no limit)"):t.push("Hook script loop_limit must be an integer"))}void 0!==e.failClosed&&"boolean"!=typeof e.failClosed&&t.push("Hook script failClosed must be a boolean")})(e,t),Td(0===t.length,t)},Md=(e,t)=>{const r=[];if(!Array.isArray(e))return r.push(`${t} must be an array of hook scripts`),Td(!1,r);for(let n=0;n{const t=[];if(!Rd(e))return t.push("Hooks config must be an object"),Td(!1,t);if("number"!=typeof e.version?t.push("Config version must be a number"):(!Number.isInteger(e.version)||e.version<1)&&t.push("Config version must be a positive integer"),!Rd(e.hooks))return t.push("Config hooks must be an object"),Td(!1,t);void 0!==e.stop_hook_loop_limit&&console.warn("[hooks] DEPRECATION WARNING: 'stop_hook_loop_limit' is deprecated. Use 'loop_limit' on individual hook scripts instead. The configured value is being ignored.");const r=Object.values(xd),n=e.hooks;for(const[e,o]of Object.entries(n))if(r.includes(e)){if(void 0!==o){const r=Md(o,e);r.isValid||t.push(...r.errors)}}else t.push(`Unknown hook type: ${e}. Valid types are: ${r.join(", ")}`);return Td(0===t.length,t)},Od={PreToolUse:xd.preToolUse,PermissionRequest:null,PostToolUse:xd.postToolUse,UserPromptSubmit:xd.beforeSubmitPrompt,Stop:xd.stop,SubagentStop:xd.subagentStop,SessionStart:xd.sessionStart,SessionEnd:xd.sessionEnd,PreCompact:xd.preCompact,Notification:null},Fd=Object.fromEntries(Object.entries(Od).filter((e=>Nd(e[0])&&null!==e[1])).map((([e,t])=>[t,e])));function Nd(e){return Object.prototype.hasOwnProperty.call(Od,e)}const Ld={Bash:"Shell",Read:"Read",Write:"Write",Edit:"Write",Glob:null,Grep:"Grep",WebFetch:"WebFetch",WebSearch:"WebSearch",Task:"Task"},jd=["Glob"],Ud=["Notification","PermissionRequest"],Bd=/^[A-Za-z0-9_./:=+-]+$/,Wd=/^=|^-.*\./,Hd=/\$\{(?:CLAUDE_PROJECT_DIR|CURSOR_PROJECT_DIR|CLAUDE_PLUGIN_ROOT|CURSOR_PLUGIN_ROOT)\}/g,qd=/^[^\p{Cc}$`"]*$/u,zd=/\\(?:[$`"\\]|$)/;function Gd(e){return`'${e.replace(/'/g,"'\\''")}'`}function Vd(e){if(Bd.test(e)&&!Wd.test(e))return e;const t=e.replace(Hd,"");if((t!==e||e.includes("'"))&&qd.test(t)&&!zd.test(e))return`"${e}"`;const r=[];let n=0;for(const t of e.matchAll(Hd))t.index>n&&r.push(Gd(e.slice(n,t.index))),r.push(`"${t[0]}"`),n=t.index+t[0].length;return(n{},info:()=>{}};function Jd(e,t,r=Kd){const n={loop_limit:null,failClosed:!1};if(t&&"*"!==t&&(n.matcher=t),void 0!==e.timeout&&(n.timeout=e.timeout),"prompt"===e.type)return e.prompt?{type:"prompt",prompt:e.prompt,...n}:null;const o=function(e,t){const r=e.command;if(!r)return null;const n=e.args;return null==n?(void 0!==e.shell&&t.warn(`Hook "${r}" sets shell "${e.shell}", which Cursor does not support; the platform default shell will be used`),r):(o=n,Array.isArray(o)&&o.every((e=>"string"==typeof e))?function(e,t){return[e,...t].map(Vd).join(" ")}(r,n):(t.warn(`Hook "${r}" has invalid "args" (expected an array of strings), skipping`),null));var o}(e,r);return null===o?null:{type:"command",command:o,...n}}function Zd(e,t,r=Kd){const n=[];let o;if("PreToolUse"===t||"PostToolUse"===t){const t=function(e,t=Kd){if(!e||"*"===e)return"*";const r=e.split("|"),n=[],o=[];for(const e of r){const t=e.trim();if(t.startsWith("mcp__")){const e=t.split("__");if(e.length>=3){const t=e.slice(2).join("__");n.push(`MCP:${t}`);continue}}const r=Ld[t];null!==r?void 0!==r?n.includes(r)||n.push(r):n.push(t):jd.includes(t)&&o.push(`Tool "${t}" is not supported in Cursor and will be ignored`)}for(const e of o)t.warn(e);return 0===n.length?null:n.join("|")}(e.matcher,r);if(null===t)return r.warn(`All tools in matcher "${e.matcher}" are unsupported, skipping hooks`),[];o="*"===t?void 0:t}else"SessionStart"===t||"PreCompact"===t?(e.matcher&&"*"!==e.matcher&&""!==e.matcher&&("SessionStart"===t?["startup","resume","clear","compact"].includes(e.matcher):["manual","auto"].includes(e.matcher))&&r.warn(`${t} trigger matcher "${e.matcher}" is not supported in Cursor, hooks will fire for all triggers`),o=void 0):o=void 0;for(const t of e.hooks){const e=Jd(t,o,r);e&&n.push(e)}return n}function Xd(e,t=Kd){const r={};for(const[n,o]of Object.entries(e)){if(!Nd(n)){t.warn(`Unknown Claude Code event "${n}", skipping`);continue}if(Ud.includes(n)){t.warn(`Claude Code event "${n}" is not supported in Cursor and will be ignored`);continue}const e=Od[n];if(!e){t.warn(`Unknown Claude Code event "${n}", skipping`);continue}const s=[];if(Array.isArray(o))for(const e of o){const r=Zd(e,n,t);s.push(...r)}else void 0!==o&&t.warn(`Claude Code event "${n}" has invalid value (expected array), skipping`);if(s.length>0){const t=r[e]||[];r[e]=[...t,...s]}}return{version:1,hooks:r}}var Qd=r("../../node_modules/.pnpm/gray-matter@4.0.3/node_modules/gray-matter/index.js");const Yd=()=>({});function eh(e,t){return Qd(e,{...t,engines:{...t?.engines,js:Yd,javascript:Yd}})}function th(e,t,r){return Qd.stringify({content:e,data:{}},t,r)}var rh=r("node:zlib");function nh(e,t){const r=function(e){return e.split(/[/\\]/).filter((e=>e))}(e);for(let e=0;ee.isDirectory())).map((e=>e.name))}catch{return[]}}async removeVersion(e){const t=this.getCacheDir(e);try{await(0,Co.rm)(t,{recursive:!0,force:!0})}catch{}}async removeAllVersions(e){const t=dh(this.cacheRoot,e);await(0,Co.rm)(t,{recursive:!0,force:!0})}async pruneOldVersions(e){const t=await this.listCachedVersions({marketplaceSlug:e.marketplaceSlug,pluginId:e.pluginId}),r=new Set(e.keepVersions.map((e=>lh(e))));for(const n of t)r.has(n)||await this.removeVersion({marketplaceSlug:e.marketplaceSlug,pluginId:e.pluginId,version:n})}async markCacheComplete(e){const t=this.getCacheDir(e);await(0,Co.writeFile)(uh({parent:t,name:ch}),"")}}class ph extends Error{constructor(e,t){super(t),this.reason=e,this.name="PluginContentInstallError"}}const fh=(0,zs.promisify)(rh.gunzip),mh=/^[A-Za-z0-9._-]{1,128}$/,gh=/^[0-9a-f]{64}$/,wh=/^[1-9]\d{0,18}$/,yh="backend-content://",vh="backend-content/",bh=new Map([[3,"request_refused"],[5,"not_found"],[9,"account_not_connected"],[10,"revision_superseded"],[12,"unsupported_server"],[14,"unavailable"]]),Sh=new Set(["unavailable","revision_superseded","timeout","download_failed","integrity"]);function kh(e){return e instanceof ph&&Sh.has(e.reason)}class _h{constructor(){this.awaited=new Map}forListing(e){return{startLoad:()=>{for(const[t,r]of this.awaited)r.listing===e&&(r.attemptedThisLoad?r.attemptedThisLoad=!1:this.awaited.delete(t))},heldFailure:({pluginDbId:e,revision:t})=>{const r=this.awaited.get(e);if(void 0!==r&&r.revision===t)return r.attemptedThisLoad=!0,Date.now(){kh(n)?this.awaited.set(t,{revision:r,reason:n.reason,retryAtMs:Date.now()+6e4,listing:e,attemptedThisLoad:!0}):this.awaited.delete(t)},isRetryDue:()=>this.isRetryDue(),allowImmediateRetry:()=>this.allowImmediateRetry()}}isRetryDue(){const e=Date.now();return[...this.awaited.values()].some((t=>e>=t.retryAtMs))}allowImmediateRetry(){for(const e of this.awaited.values())e.retryAtMs=0}}function Ch(e){if("bigint"!=typeof e&&"number"!=typeof e&&"string"!=typeof e)return;const t=String(e);return wh.test(t)?t:void 0}function Eh(e){return e.startsWith(yh)}function xh(e){return`${vh}${e}`}function Ph(e,t){return new ph(e,function(e,t){const r=JSON.stringify(t);switch(e){case"unsupported_client":return`Plugin ${r} could not be downloaded: this client cannot install plugins whose files the server provides.`;case"not_found":return`Plugin ${r} could not be downloaded: it no longer exists or you no longer have access to it.`;case"account_not_connected":return`Plugin ${r} could not be downloaded: connect your account on the host of its source repository first.`;case"revision_superseded":return`Plugin ${r} changed while it was downloading. The new version installs on the next plugin refresh.`;case"unavailable":return`Plugin ${r} could not be downloaded: its files cannot be served right now. It installs on a later plugin refresh.`;case"unsupported_server":return`Plugin ${r} could not be downloaded: this server does not provide plugin files.`;case"request_refused":return`Plugin ${r} could not be downloaded: the server refused the request.`;case"download_failed":return`Plugin ${r} could not be downloaded.`;case"timeout":return`Downloading plugin ${r} timed out.`;case"integrity":return`The download of plugin ${r} did not match the size or hash the server gave for it, so it was discarded.`;case"too_large":return`Plugin ${r} could not be downloaded: its files are larger than this client accepts.`;case"unsafe_archive":return`The download of plugin ${r} could not be unpacked safely, so it was discarded.`;case"unpack_failed":return`The download of plugin ${r} could not be written to the plugin cache.`;default:return e}}(e,t))}function Rh(e){if("File"!==e.type&&"OldFile"!==e.type&&"Directory"!==e.type)return!0;const t=e.path;return!(0!==t.length&&!t.includes("\0")&&!/^([/\\]|[A-Za-z]:)/.test(t))||t.split(/[/\\]/).includes("..")}async function Ih(e){const{download:t,pluginName:r,content:n,targetDir:o}=e;if(void 0===t)throw Ph("unsupported_client",r);const s=new AbortController;let i;try{i=await async function(e){const t=e[Symbol.asyncIterator](),r=()=>(0,Or.wj)(t.next(),12e4);try{const e=await r();if(!0===e.done||"header"!==e.value.part.case)return"integrity";const{sha256:t}=e.value.part.value,n=function(e){let t;if("bigint"==typeof e||"number"==typeof e)t=Number(e);else{if("string"!=typeof e||!/^\d{1,15}$/.test(e))return;t=Number(e)}return Number.isSafeInteger(t)&&t>0?t:void 0}(e.value.part.value.sizeBytes);if(void 0===n||"string"!=typeof t||!gh.test(t))return"integrity";if(n>16777216)return"too_large";const o=[];let s=0;for(;;){const e=await r();if(!0===e.done)break;const{part:t}=e.value;if(void 0!==t.case){if("data"!==t.case||0===t.value.byteLength)return"integrity";if(s+=t.value.byteLength,s>n)return"integrity";o.push(t.value)}}const i=Buffer.concat(o,s);return s===n&&(0,bo.createHash)("sha256").update(i).digest("hex")===t?i:"integrity"}finally{Promise.resolve(t.return?.()).catch((()=>{}))}}(t({pluginId:BigInt(e.pluginDbId),revision:n.revision},{signal:s.signal}))}catch(e){throw Ph(function(e){return e instanceof Or.MU?"timeout":"object"==typeof e&&null!==e&&"code"in e?"number"!=typeof e.code?"download_failed":bh.get(e.code)??"download_failed":"download_failed"}(e),r)}finally{s.abort()}if("string"==typeof i)throw Ph(i,r);const a=await async function(e){let t;try{t=await fh(e,{maxOutputLength:268435456})}catch{return}const r=t.byteLength>=512,n=r&&31===t[0]&&139===t[1],o=r&&682962941===t.readUInt32BE(0);if(r&&!n&&!o)return t}(i);if(void 0===a||!await function(e){return new Promise((t=>{let r=0;const n=(0,sh.p_)({strict:!0,onReadEntry:e=>{r+=1,(r>5e4||Rh(e))&&(t(!1),n.abort(new Error("unsafe entry")))}});n.once("end",(()=>t(r>0))),n.once("error",(()=>t(!1))),n.end(e)}))}(a))throw Ph("unsafe_archive",r);try{await async function(e,t){const r=(0,sh.o6)({cwd:t,strict:!0,preserveOwner:!1,filter:(e,t)=>{if(!("type"in t)||Rh(t))return!1;const r=!!(64&(t.mode??0));return t.mode="Directory"===t.type||r?493:420,!0}});await new Promise(((t,n)=>{r.once("close",t),r.once("error",n),r.end(e)}))}(a,o)}catch{throw Ph("unpack_failed",r)}}function Th(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")||"/"}function Ah(e,t){if(Object.hasOwn(e,t))return e[t]}function $h(e,t,r,n){const o=e?.plugins;if(!o||"object"!=typeof o)return[];const s=t?.enabledPlugins??{},i={};r?.enabledPlugins&&Object.assign(i,r.enabledPlugins);const a=void 0!==n?Th(n):void 0,c=new Set,l=[];for(const[e,t]of Object.entries(o)){if(!Array.isArray(t)||0===t.length)continue;if(void 0!==a&&!1===Ah(i,e))continue;let r;void 0!==a&&(r=t.find((t=>!("project"!==t.scope&&"local"!==t.scope||!t.projectPath)&&(Th(t.projectPath)===a&&!0===Ah(i,e))))),r||!0!==Ah(s,e)||(r=t.find((e=>"user"===e.scope))),r?.installPath&&!c.has(e)&&(l.push({pluginId:e,installPath:r.installPath}),c.add(e))}return l}var Mh=r("../../node_modules/.pnpm/js-yaml@4.3.1/node_modules/js-yaml/dist/js-yaml.mjs");const Dh=je.enum(["canvas"]),Oh=je.array(Dh).transform((e=>[...new Set(e)].sort())),Fh=new Set(["https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","https://agent-plugins.org/schemas/1.0.0/mcp.schema.json"]),Nh=/^v?(\d+\.\d+(?:\.\d+)?)$/;function Lh(e){if("object"!=typeof(t=e)||null===t||Array.isArray(t))return;var t;const r=e.$schema;return"string"==typeof r&&r.length>0?r:void 0}function jh(e){let t;try{t=new URL(e).pathname.split("/")}catch{t=e.split("/")}for(const e of t){const t=Nh.exec(e);if(null!==t)return t[1]}}function Uh(e){return void 0===e?{kind:"absent"}:Fh.has(e)?{kind:"supported",id:e,version:jh(e)??e}:{kind:"unsupported",id:e}}const Bh=10485760,Wh=/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/,Hh=[".cursor-plugin/plugin.json",".claude-plugin/plugin.json","plugin.json"],qh=[".cursor-plugin",".claude-plugin"],zh=[".cursor-plugin/marketplace.json",".claude-plugin/marketplace.json"],Gh=je.object({source:je.literal("github"),repo:je.string().regex(/^[^/]+\/[^/]+$/,"Must be in owner/repo format"),ref:je.string().optional(),sha:je.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Vh=je.object({source:je.literal("url"),url:je.string().url().endsWith(".git","URL must end with .git"),ref:je.string().optional(),sha:je.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Kh=je.object({source:je.literal("git-subdir"),url:je.string().url().endsWith(".git","URL must end with .git"),path:je.string().min(1),ref:je.string().optional(),sha:je.string().length(40,"SHA must be 40 characters").regex(/^[a-f0-9]+$/,"SHA must be hexadecimal").optional()}),Jh=je.union([je.string(),Gh,Vh,Kh]),Zh=/^(\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?|never)$/,Xh='Must be a semver version (X.Y.Z) or "never"',Qh=je.object({cursor:je.string().regex(Zh,Xh).optional(),sand:je.string().regex(Zh,Xh).optional(),sandMobile:je.string().regex(Zh,Xh).optional()}),Yh=je.object({name:je.string().min(1,"Author name is required"),email:je.string().email().optional()}),ep=je.enum(["string","number","integer","boolean","object","array","null"]),tp=je.union([ep,je.array(ep).nonempty().superRefine(((e,t)=>{new Set(e).size!==e.length&&t.addIssue({code:je.ZodIssueCode.custom,message:"Schema type arrays must not contain duplicates"})}))]);function rp(e,t){if(void 0!==e.required)if(void 0===e.properties)for(const r of e.required)t.addIssue({code:je.ZodIssueCode.custom,message:`Required property "${r}" must be declared in properties`,path:["required"]});else for(const r of e.required)r in e.properties||t.addIssue({code:je.ZodIssueCode.custom,message:`Required property "${r}" must be declared in properties`,path:["required"]});void 0!==e.minLength&&void 0!==e.maxLength&&e.minLength>e.maxLength&&t.addIssue({code:je.ZodIssueCode.custom,message:"minLength must be less than or equal to maxLength",path:["minLength"]}),void 0!==e.minimum&&void 0!==e.maximum&&e.minimum>e.maximum&&t.addIssue({code:je.ZodIssueCode.custom,message:"minimum must be less than or equal to maximum",path:["minimum"]}),void 0!==e.exclusiveMinimum&&void 0!==e.exclusiveMaximum&&e.exclusiveMinimum>=e.exclusiveMaximum&&t.addIssue({code:je.ZodIssueCode.custom,message:"exclusiveMinimum must be less than exclusiveMaximum",path:["exclusiveMinimum"]}),void 0!==e.minItems&&void 0!==e.maxItems&&e.minItems>e.maxItems&&t.addIssue({code:je.ZodIssueCode.custom,message:"minItems must be less than or equal to maxItems",path:["minItems"]}),void 0!==e.minProperties&&void 0!==e.maxProperties&&e.minProperties>e.maxProperties&&t.addIssue({code:je.ZodIssueCode.custom,message:"minProperties must be less than or equal to maxProperties",path:["minProperties"]})}const np=je.lazy((()=>je.object({type:tp.optional(),title:je.string().optional(),description:je.string().optional(),format:je.string().optional(),writeOnly:je.boolean().optional(),placeholder:je.string().optional(),default:je.unknown().optional(),enum:je.array(je.any()).nonempty().optional(),const:je.unknown().optional(),properties:je.record(je.string(),np).optional(),required:je.array(je.string()).optional(),additionalProperties:je.union([je.boolean(),np]).optional(),items:je.union([np,je.array(np)]).optional(),minLength:je.number().int().nonnegative().optional(),maxLength:je.number().int().nonnegative().optional(),minimum:je.number().optional(),maximum:je.number().optional(),exclusiveMinimum:je.number().optional(),exclusiveMaximum:je.number().optional(),multipleOf:je.number().positive().optional(),minItems:je.number().int().nonnegative().optional(),maxItems:je.number().int().nonnegative().optional(),uniqueItems:je.boolean().optional(),minProperties:je.number().int().nonnegative().optional(),maxProperties:je.number().int().nonnegative().optional()}).strict().superRefine(rp)));function op(e){const t=np.superRefine(((e,t)=>{ap(e)&&"object"===e.type||t.addIssue({code:je.ZodIssueCode.custom,message:'Plugin variable schemas must declare type "object"',path:["type"]})})).safeParse(e);return t.success?cp(t.data)?{success:!0,data:t.data}:{success:!1,error:new je.ZodError([{code:"custom",path:["type"],message:'Plugin variable schemas must declare type "object"'}])}:{success:!1,error:t.error}}const sp=je.unknown().superRefine(((e,t)=>{const r=op(e);if(!r.success)for(const e of r.error.issues)t.addIssue({code:"custom",message:e.message,path:e.path})})).transform((e=>{if(!cp(e))throw new Error('Plugin variable schema must declare type "object"');return e})),ip=(je.object({name:je.string().min(1).transform((e=>e.toLowerCase())).refine((e=>Wh.test(e)),"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:je.string().optional(),source:Jh,description:je.string().optional(),version:je.string().optional(),author:Yh.optional(),publisher:je.string().min(1).optional(),homepage:je.string().url().optional(),repository:je.string().url().optional(),license:je.string().optional(),keywords:je.array(je.string()).optional(),capabilities:Oh.optional(),logo:je.string().optional(),category:je.string().optional(),tags:je.array(je.string()).optional(),minClientVersions:Qh.optional(),strict:je.boolean().default(!0),commands:je.union([je.string(),je.array(je.string())]).optional(),agents:je.union([je.string(),je.array(je.string())]).optional(),skills:je.union([je.string(),je.array(je.string())]).optional(),rules:je.union([je.string(),je.array(je.string())]).optional(),hooks:je.union([je.string(),je.record(je.string(),je.unknown())]).optional(),variables:sp.optional(),mcpServers:je.union([je.string(),je.record(je.string(),je.unknown()),je.array(je.union([je.string(),je.record(je.string(),je.unknown())]))]).optional()}),je.object({description:je.string().optional(),version:je.string().optional(),pluginRoot:je.string().optional()}),je.object({name:je.string().min(1).regex(Wh,"Name must be kebab-case (lowercase alphanumeric with hyphens and periods)"),displayName:je.string().optional(),description:je.string().optional(),version:je.string().optional(),author:Yh.optional(),publisher:je.string().min(1).optional(),homepage:je.string().url().optional(),repository:je.string().url().optional(),license:je.string().optional(),logo:je.string().optional(),keywords:je.array(je.string()).optional(),capabilities:Oh.optional(),minClientVersions:Qh.optional(),commands:je.union([je.string(),je.array(je.string())]).optional(),agents:je.union([je.string(),je.array(je.string())]).optional(),skills:je.union([je.string(),je.array(je.string())]).optional(),rules:je.union([je.string(),je.array(je.string())]).optional(),hooks:je.union([je.string(),je.record(je.string(),je.unknown())]).optional(),variables:sp.optional(),mcpServers:je.union([je.string(),je.record(je.string(),je.unknown()),je.array(je.union([je.string(),je.record(je.string(),je.unknown())]))]).optional()}));function ap(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function cp(e){return ap(e)&&"object"===e.type}function lp(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function up(e,t){if(ap(e)&&"string"==typeof e.name){const t=lp(e.name);if(t.length>0)return t}return function(e){const t=void 0!==e.repoName?lp(e.repoName):"";return t.length>0?t:`cursor-marketplace-${e.fallbackId??(0,bo.randomUUID)()}`}(t)}function dp(e){if(ap(e)&&ap(e.owner)){const t="string"==typeof e.owner.name&&e.owner.name.trim().length>0?e.owner.name:"Unknown",r="string"==typeof e.owner.email&&e.owner.email.trim().length>0?e.owner.email:void 0;return{name:t,...void 0!==r?{email:r}:{}}}return{name:"Unknown"}}function hp(e){return"string"==typeof e?e:void 0}function pp(e){if(!Array.isArray(e))return;const t=e.filter((e=>"string"==typeof e));return t.length>0?t:void 0}function fp(e){return"string"==typeof e?e:pp(e)}function mp(e){if(!ap(e)||!ap(e.metadata))return;const t={description:hp(e.metadata.description),version:hp(e.metadata.version),pluginRoot:hp(e.metadata.pluginRoot)};return void 0!==t.description||void 0!==t.version||void 0!==t.pluginRoot?t:void 0}function gp(e){if(!ap(e))return;const t=hp(e.name);if(void 0===t||0===t.length)return;const r=hp(e.email);return{name:t,...void 0!==r?{email:r}:{}}}function wp(e){if("string"==typeof e||ap(e))return e;if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e||ap(e)));return t.length>0?t:void 0}}function yp(e){if("string"==typeof e||ap(e))return e}function vp(e){if(void 0===e)return;const t=op(e);return t.success?t.data:void 0}function bp(e,t={}){if(e.length>Bh)return{success:!1,error:"Manifest exceeds maximum size of 10485760 bytes"};let r;try{r=JSON.parse(e)}catch(e){return{success:!1,error:`Invalid JSON: ${e instanceof Error?e.message:"Unknown error"}`}}if(!ap(r))return{success:!1,error:"Invalid marketplace manifest: expected a JSON object"};const n=[],o=[],i=new Set;return(Array.isArray(r.plugins)?r.plugins:[]).forEach(((e,t)=>{const r=function(e,t){if(!ap(e))return{skippedEntry:{index:t,error:`Plugin entry at index ${t} is not an object`}};const r="string"==typeof(n=e.source)?n:ap(n)?"github"===n.source&&"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:hp(n.ref),sha:hp(n.sha)}:("url"===n.source||void 0===n.source)&&"string"==typeof n.url&&n.url.length>0?{source:"url",url:n.url,ref:hp(n.ref),sha:hp(n.sha)}:"git-subdir"===n.source&&"string"==typeof n.url&&n.url.length>0&&"string"==typeof n.path&&n.path.length>0?{source:"git-subdir",url:n.url,path:n.path,ref:hp(n.ref),sha:hp(n.sha)}:"string"==typeof n.repo&&n.repo.length>0?{source:"github",repo:n.repo,ref:hp(n.ref),sha:hp(n.sha)}:void 0:void 0;var n;if(void 0===r){const r=hp(e.name);return{skippedEntry:{index:t,...void 0!==r&&r.length>0?{name:r}:{},error:`Plugin entry at index ${t} has no usable source`}}}const o=("string"==typeof e.name?lp(e.name):"")||function(e){if("string"==typeof e){const t=lp((0,s.basename)(e));return t.length>0?t:void 0}if("github"===e.source){const t=lp(e.repo.split("/").at(-1)??"");return t.length>0?t:void 0}if("git-subdir"===e.source){const t=lp((0,s.basename)(e.path));return t.length>0?t:void 0}let t=e.url;try{t=new URL(e.url).pathname}catch{}for(;t.endsWith("/");)t=t.slice(0,-1);t.toLowerCase().endsWith(".git")&&(t=t.slice(0,-4));const r=lp((0,s.basename)(t));return r.length>0?r:void 0}(r);if(void 0===o)return{skippedEntry:{index:t,error:`Plugin entry at index ${t} has no usable name`}};const i=Oh.safeParse(e.capabilities);if(void 0!==e.capabilities&&!i.success)return{skippedEntry:{index:t,name:o,error:`Plugin entry at index ${t} has invalid capabilities: ${i.error.issues.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`}};const a=i.success?i.data:void 0,c=function(e){const t=Qh.safeParse(e);if(t.success&&(void 0!==t.data.cursor||void 0!==t.data.sand||void 0!==t.data.sandMobile))return t.data}(e.minClientVersions);return{entry:{name:o,displayName:hp(e.displayName),source:r,description:hp(e.description),version:hp(e.version),author:gp(e.author),publisher:hp(e.publisher),homepage:hp(e.homepage),repository:hp(e.repository),license:hp(e.license),keywords:pp(e.keywords),logo:hp(e.logo),category:hp(e.category),tags:pp(e.tags),strict:"boolean"!=typeof e.strict||e.strict,commands:fp(e.commands),agents:fp(e.agents),skills:fp(e.skills),rules:fp(e.rules),hooks:yp(e.hooks),variables:vp(e.variables),mcpServers:wp(e.mcpServers),...void 0!==a&&{capabilities:a},...void 0!==c&&{minClientVersions:c}}}}(e,t);"skippedEntry"in r?o.push(r.skippedEntry):i.has(r.entry.name)?o.push({index:t,name:r.entry.name,error:`Duplicate plugin name "${r.entry.name}" at index ${t}`}):(i.add(r.entry.name),n.push(r.entry))})),{success:!0,data:{name:up(r,t),owner:dp(r),description:hp(r.description),plugins:n,metadata:mp(r),skippedPluginEntries:o}}}function Sp(e){if(e.length>Bh)return{success:!1,error:"Manifest exceeds maximum size of 10485760 bytes"};let t;try{t=JSON.parse(e)}catch(e){return{success:!1,error:`Invalid JSON: ${e instanceof Error?e.message:"Unknown error"}`}}const r=Uh(Lh(t)),n=ip.safeParse(t);return n.success?{success:!0,data:n.data,..."unsupported"===r.kind&&{unrecognizedSchemaId:r.id}}:{success:!1,error:`Invalid plugin manifest: ${n.error.issues.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}`,details:n.error}}function kp(e,t){if("string"!=typeof e)return null;let r=e;if(r.startsWith("./")&&(r=r.slice(2)),void 0!==t){let e=t;e.startsWith("./")&&(e=e.slice(2)),e.endsWith("/")&&(e=e.slice(0,-1)),r=`${e}/${r}`}return r||"."}function _p(e){return!e.includes("..")&&!(0,s.isAbsolute)(e)&&!e.includes("://")}var Cp=r("../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js");const Ep=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g,xp=/\$%7B([^%/?#]+?)%7D/gi;function Pp(e,t){return Rp(e,"function"==typeof t?t:function(e){const t=new Map(Object.entries(e).map((([e,t])=>[e.toLowerCase(),t])));return r=>e[r]??t.get(r.toLowerCase())}(t))}function Rp(e,t){if("string"==typeof e)return function(e,t){return e.replace(xp,"${$1}").replace(Ep,((e,r,n,o)=>{if(void 0!==r)return t(r)??e;if(void 0===n)return e;const s=t(n);return void 0!==s?s:void 0!==o?o:e}))}(e,t);if(Array.isArray(e))return e.map((e=>Rp(e,t)));if(function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e)){const r={};for(const[n,o]of Object.entries(e))r[n]=Rp(o,t);return r}return e}function Ip(e,t){return e.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g,(()=>t)).replace(/\$\{CURSOR_PLUGIN_ROOT\}/g,(()=>t))}const Tp={log:()=>{},increment:()=>{},distribution:()=>{},captureException:()=>{}},Ap=je.object({command:je.string().optional(),args:je.array(je.string()).optional(),env:je.record(je.string(),je.string()).optional(),url:je.string().optional(),headers:je.record(je.string(),je.string()).optional(),cwd:je.string().optional(),envFile:je.string().optional(),auth:je.object({CLIENT_ID:je.string(),CLIENT_SECRET:je.string().optional(),scopes:je.array(je.string()).optional()}).optional(),enabledTools:je.array(je.string()).optional(),placement:je.enum(["server","client"]).optional(),tls:je.object({caBundle:je.string().trim().min(1).max(131072)}).optional()}),$p=je.object({mcpServers:je.record(je.string(),Ap).optional()}),Mp=[".mcp.json","mcp.json"],Dp=new Set(["author","owner","source","metadata"].map((e=>e.toLowerCase())));function Op(e,t){if(!function(e){return Dp.has(e.toLowerCase())}(e))return!1;if(!function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(t))return!1;const r=t;switch(e.toLowerCase()){case"author":case"owner":return"string"==typeof r.name;case"source":return"string"==typeof r.source||"string"==typeof r.repo||"string"==typeof r.path||"string"==typeof r.ref||"string"==typeof r.sha;case"metadata":return"string"==typeof r.description||"string"==typeof r.version||"string"==typeof r.pluginRoot;default:return!1}}function Fp(e){return"object"==typeof e&&null!==e&&("command"in e||"url"in e)}function Np(e){const t=void 0!==e&&e.length>0?e.replace(/\/+$/,""):void 0;return Mp.map((e=>void 0!==t?`${t}/${e}`:e))}function Lp(e,t,r){if(!e.mcpServers)return e;const n={};for(const[r,o]of Object.entries(e.mcpServers)){const e={...o};if("string"==typeof o.command&&(e.command=Ip(o.command,t)),Array.isArray(o.args)&&(e.args=o.args.map((e=>"string"==typeof e?Ip(e,t):e))),o.env&&"object"==typeof o.env){const r={};for(const[e,n]of Object.entries(o.env))r[e]="string"==typeof n?Ip(n,t):n;e.env=r}"string"==typeof o.cwd&&(e.cwd=Ip(o.cwd,t)),n[r]=e}return function(e,t){const r=t?.cloudAgentEnvLookup,n=t?.configuredVariables;if(void 0!==r)return Pp(e,r);const o=new Map(Object.keys(n??{}).map((e=>[e.toLowerCase(),e])));return Pp(e,(e=>{const t=process.env[e];if(void 0!==t)return t;const r=void 0!==n&&Object.hasOwn(n,e)?e:o.get(e.toLowerCase()),s=void 0!==r?n?.[r]:void 0;return null!=s?"string"==typeof s?s:"number"==typeof s||"boolean"==typeof s||"bigint"==typeof s?String(s):JSON.stringify(s):void 0}))}({...e,mcpServers:n},r)}function jp(e,t,r){try{const n=(0,Cp.qg)(e),o=Lh(n);if(void 0!==o){const e=r?.log??Tp;"unsupported"===Uh(o).kind?e.log("debug",`mcp.json declares an unrecognized $schema, loading anyway: ${o}`):function(e,t){if(void 0===e||void 0===t)return!1;const r=jh(e),n=jh(t);return void 0!==r&&void 0!==n&&r!==n}(r?.pluginSchemaId,o)&&e.log("debug",`mcp.json $schema ${o} disagrees with plugin.json $schema ${r?.pluginSchemaId}, loading anyway`)}const s=$p.safeParse(n),i=!0===r?.skipExpansion;if(s.success&&s.data.mcpServers&&Object.keys(s.data.mcpServers).length>0)return i?s.data:Lp(s.data,t,r);const a={};for(const[e,t]of Object.entries(n))"mcpServers"!==e&&!Op(e,t)&&Fp(t)&&(a[e]=t);if(Object.keys(a).length>0){const e=$p.safeParse({mcpServers:a});if(e.success)return i?e.data:Lp(e.data,t,r)}return null}catch{return null}}function Up(e,t,r){for(const[n,o]of Object.entries(t))e.mcpServers[n]=o,e.mcpServerSourcePaths[n]=r}async function Bp(e,t,r,n={}){const o=n.toSourcePath??(e=>e),s=n.installPathForExpansion??"",i=n.fallbackFileNames??Mp,a=n.manifestPrecedence??"override",c={},l={};for(const t of i){const r=await e(t);if(null===r)continue;const i=jp(r,s,n.parserOptions);if(i?.mcpServers)for(const[e,r]of Object.entries(i.mcpServers))void 0===c[e]&&(c[e]=r,l[e]=o(t))}if(void 0!==t){const i=await async function(e,t,r={}){const n=r.toSourcePath??(e=>e),o=r.installPathForExpansion??"",s={mcpServers:{},mcpServerSourcePaths:{}},i=async e=>{const i=e.replace(/^\.\//,"");if(!_p(i))return;const a=await t(i);if(null===a)return;const c=jp(a,o,r.parserOptions);c?.mcpServers&&Object.keys(c.mcpServers).length>0&&Up(s,c.mcpServers,n(i))},a=e=>{const t=jp(JSON.stringify(e),o,r.parserOptions);t?.mcpServers&&Object.keys(t.mcpServers).length>0&&Up(s,t.mcpServers,r.manifestSourcePath??"manifest")};if("string"==typeof e)await i(e);else if(Array.isArray(e))for(const t of e)"string"==typeof t?await i(t):"object"==typeof t&&null!==t&&a(t);else"object"==typeof e&&null!==e&&a(e);return s}(t,e,{toSourcePath:o,manifestSourcePath:r,installPathForExpansion:s,parserOptions:n.parserOptions});for(const[e,t]of Object.entries(i.mcpServers))"fill"===a&&void 0!==c[e]||(c[e]=t,l[e]=i.mcpServerSourcePaths[e])}return 0===Object.keys(c).length?null:{mcpServers:c,...Object.keys(l).length>0&&{mcpServerSourcePaths:l}}}const Wp=new Set(["CREDENTIAL","CREDENTIALS","KEY","PASSPHRASE","PASSWORD","SECRET","TOKEN"]);function Hp(e){return function(e){return e.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/[^a-z\d]+/gi,"_").toUpperCase().split("_").filter((e=>e.length>0))}(e).some((e=>Wp.has(e)))}const qp=/\$\{(?:env:([A-Z][A-Z0-9_]*)|([A-Z][A-Z0-9_]*)(?::-([^}]*))?)\}/g,zp=new Set(["CURSOR_PLUGIN_ROOT","CLAUDE_PLUGIN_ROOT"]),Gp=new Set(["api","aws","db","dd","gcp","http","https","id","mcp","ssl","tls","uri","url"]);function Vp(e){return e.split("_").filter((e=>e.length>0)).map((e=>{const t=e.toLowerCase();return Gp.has(t)?e.toUpperCase():e.charAt(0).toUpperCase()+t.slice(1)})).join(" ")}function Kp(e,t){if("string"!=typeof e){if(Array.isArray(e))for(const r of e)Kp(r,t);else if(null!==e&&"object"==typeof e)for(const r of Object.values(e))Kp(r,t)}else for(const[,r,n,o]of e.matchAll(qp)){const e=r??n;if(void 0===e||zp.has(e)||t.has(e))continue;const s=void 0===r?`\${${e}}`:`\${env:${e}}`;t.set(e,{reference:s,defaultValue:o})}}function Jp(e){if(void 0===e?.mcpServers)return;const t=new Map;if(Kp(e.mcpServers,t),0===t.size)return;const r={};for(const e of[...t.keys()].sort()){const n=t.get(e);if(void 0===n)continue;const{reference:o,defaultValue:s}=n;r[e]={type:"string",title:Vp(e),description:void 0===s||0===s.length?`Referenced as \`${o}\` in this plugin's MCP configuration.`:`Referenced as \`${o}\` in this plugin's MCP configuration. Defaults to \`${s}\` when left blank.`,...Hp(e)?{writeOnly:!0}:{}}}return{type:"object",properties:r}}const Zp=[".md",".mdc",".markdown"],Xp=[...Zp,".txt"],Qp=/^---\s*\n([\s\S]*?)\n---/;function Yp(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ef(e){return e.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9.-]/g,"")}function tf(e){const t=e.match(Qp);if(!t)return{};try{const e=Mh.Ay.load(t[1],{schema:Mh.Ay.JSON_SCHEMA});if(!Yp(e))return{};const r=Yp(e.metadata)?e.metadata:void 0,n=rf(e.environments??r?.environments);return{disabledEnvironments:rf(e["disabled-environments"]??r?.disabledEnvironments),environments:n,name:"string"==typeof e.name?e.name:void 0,description:"string"==typeof e.description?e.description:void 0}}catch{const e=t[1],r=e.match(/^name:\s*(.+)$/m),n=e.match(/^description:\s*(.+)$/m);return r||n?{name:r?r[1].trim():void 0,description:n?n[1].trim():void 0}:{}}}function rf(e){if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e&&e.length>0));return 0===t.length?void 0:t}if("string"==typeof e){const t=e.split(",").map((e=>e.trim())).filter((e=>e.length>0));return 0===t.length?void 0:t}}function nf(e){return ef((0,s.basename)(e).replace(/\.(md|mdc|markdown|txt)$/i,""))}function of(e){const t=new Set,r=[];for(const n of e)t.has(n.name)||(t.add(n.name),r.push(n));return r}class sf{constructor(e){this.fetcher=e}async discoverComponents(e={}){const t=e.basePath??"",r=t?`${t}/`:"",n=e.manifest;let o;try{o=await this.fetcher.listDirectory(t)}catch{o=[]}const s=new Set(o.filter((e=>"dir"===e.type)).map((e=>e.name.toLowerCase()))),i=Mp.filter((e=>o.some((t=>"file"===t.type&&t.name===e)))),a=o.some((e=>"file"===e.type&&"SKILL.md"===e.name)),[c,l,u,d,h,p,f]=await Promise.all([a&&void 0===n?.skills?this.discoverRootSkill(r):Promise.resolve(null),void 0!==n?.skills?this.discoverFromManifestPaths(r,n.skills,!0,Zp):s.has("skills")?this.discoverSkills(`${r}skills`):Promise.resolve([]),void 0!==n?.agents?this.discoverFromManifestPaths(r,n.agents,!1,Zp):s.has("agents")?this.discoverMarkdownComponents(`${r}agents`,Zp):Promise.resolve([]),void 0!==n?.hooks?this.discoverHooksFromManifest(r,n.hooks):s.has("hooks")?this.discoverHooksFromJson(`${r}hooks/hooks.json`):Promise.resolve([]),void 0!==n?.commands?this.discoverFromManifestPaths(r,n.commands,!1,Xp):s.has("commands")?this.discoverMarkdownComponents(`${r}commands`,Xp):Promise.resolve([]),void 0!==n?.rules?this.discoverFromManifestPaths(r,n.rules,!1,Zp):s.has("rules")?this.discoverMarkdownComponents(`${r}rules`,Zp):Promise.resolve([]),this.discoverMcpServers(r,n?.mcpServers,i)]);return{skills:of(c?[c,...l]:l),agents:of(u),hooks:d,commands:of(h),rules:of(p),mcpServers:f.servers,mcpVariables:f.variables,mcpConfigs:f.configs}}async discoverHooksFromJson(e){try{if(!await this.fetcher.fileExists(e))return[];const{content:t}=await this.fetcher.fetchFile(e),r=JSON.parse(t);return Yp(r)&&Yp(r.hooks)?Object.keys(r.hooks).map((t=>({name:ef(t),path:e,description:`Hook: ${t}`}))):[]}catch{return[]}}async discoverHooksFromManifest(e,t){if("string"==typeof t){if(!_p(t))return[];const r=`${e}${t.replace(/^\.\//,"")}`;return r.endsWith(".json")?this.discoverHooksFromJson(r):this.discoverHooksFromJson(`${r}/hooks.json`)}const r=t.hooks??t;return!r||"object"!=typeof r||Array.isArray(r)?[]:Object.keys(r).map((e=>({name:ef(e),path:"manifest",description:`Hook: ${e}`})))}async discoverFromManifestPaths(e,t,r=!1,n=Zp){if("string"==typeof t){if(!_p(t))return[];const o=`${e}${t.replace(/^\.\//,"")}`.replace(/\/$/,"");return r?this.discoverSkills(o):this.discoverMarkdownComponents(o,n)}const o=[];for(const n of t)try{if(!_p(n))continue;const t=`${e}${n.replace(/^\.\//,"")}`;if(r){const e=t.endsWith("SKILL.md")?t:`${t.replace(/\/$/,"")}/SKILL.md`;if(!await this.fetcher.fileExists(e)){const e=t.replace(/\/$/,""),r=await this.discoverSkills(e);o.push(...r);continue}let r=nf(t.endsWith("SKILL.md")?t.slice(0,-8).replace(/\/$/,""):t);const{content:n}=await this.fetcher.fetchFile(e),s=tf(n);if(r=s.name??r,r){const t={disabledEnvironments:s.disabledEnvironments,environments:s.environments,name:ef(r),path:e};void 0!==s.description&&(t.description=s.description),o.push(t)}}else{if(!await this.fetcher.fileExists(t))continue;let e=nf(t);const{content:r}=await this.fetcher.fetchFile(t),n=tf(r);e=n.name??e;const s=n.description;if(e){const r={name:ef(e),path:t};void 0!==s&&(r.description=s),o.push(r)}}}catch{}return o}async discoverMarkdownComponents(e,t=Zp,r=new Set){let n;try{n=await this.fetcher.listDirectory(e,r)}catch{return[]}const o=n.filter((e=>"file"===e.type&&t.some((t=>e.name.endsWith(t))))),s=n.filter((e=>"dir"===e.type)),[i,a]=await Promise.all([Promise.all(o.map((async e=>{try{let t=nf(e.name);const{content:r}=await this.fetcher.fetchFile(e.path),n=tf(r);t=n.name?ef(n.name):t;const o=n.description;if(!t)return null;const s={name:t,path:e.path};return void 0!==o&&(s.description=o),s}catch{return null}}))),Promise.all(s.map((e=>this.discoverMarkdownComponents(e.path,t,r))))]);return[...i.filter((e=>null!==e)),...a.flat()]}async discoverRootSkill(e){try{const t=`${e}SKILL.md`;let r=ef((0,s.basename)(e.replace(/[\\/]+$/,"")));const{content:n}=await this.fetcher.fetchFile(t),o=tf(n);if(r=o.name?ef(o.name):r,!r)return null;const i={disabledEnvironments:o.disabledEnvironments,environments:o.environments,name:r,path:t};return void 0!==o.description&&(i.description=o.description),i}catch{return null}}async discoverSkills(e){let t;try{t=await this.fetcher.listDirectory(e)}catch{return[]}const r=t.filter((e=>"dir"===e.type));return(await Promise.all(r.map((async e=>{try{const t=`${e.path}/SKILL.md`;if(!await this.fetcher.fileExists(t))return null;const{content:r}=await this.fetcher.fetchFile(t),n=tf(r),o=n.name?ef(n.name):ef(e.name);if(!o)return null;const s={disabledEnvironments:n.disabledEnvironments,environments:n.environments,name:o,path:t};return void 0!==n.description&&(s.description=n.description),s}catch{return null}})))).filter((e=>null!==e))}async discoverMcpServers(e,t,r){const n=new Map,o=async t=>{const r=n.get(t);if(void 0!==r)return r;const o=this.fetcher.fetchFile(`${e}${t}`).then((({content:e})=>e)).catch((()=>null));return n.set(t,o),o},s=async n=>Bp(o,t,void 0!==t?"manifest":void 0,{fallbackFileNames:r,manifestPrecedence:n,toSourcePath:t=>`${e}${t}`,parserOptions:{skipExpansion:!0}}),i=await s("fill");if(void 0===i?.mcpServers)return{servers:[],variables:void 0,configs:void 0};const a=void 0===t?i:await s("override"),c=a?.mcpServers??i.mcpServers,l={};for(const[e,t]of Object.entries(c))l[e]=t;return{servers:Object.keys(i.mcpServers).map((e=>({name:ef(e),path:i.mcpServerSourcePaths?.[e]??"manifest"}))),variables:Jp(a??i),configs:l}}}class af extends Error{constructor(e,t){super(`Invalid Claude Code plugin identifier "${t}": ${e}`),this.raw=t,this.name="CCPluginIdentifierError"}}function cf(e){const t=e.trim();if(!t)throw new af("Empty identifier",e);const r=/^[a-zA-Z0-9_-]+$/,n=t.indexOf("@");if(n!==t.lastIndexOf("@"))throw new af("Plugin identifier cannot contain multiple @ symbols",e);if(-1===n){if(!r.test(t))throw new af("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(t.length>100)throw new af("Plugin name must be 100 characters or less",e);return{name:t,sourceType:"marketplace",marketplace:"claude-plugins-official",raw:e}}const o=t.slice(0,n).trim(),s=t.slice(n+1).trim();if(!o)throw new af("Missing plugin name before @",e);if(!s)throw new af("Missing source after @",e);if(!r.test(o))throw new af("Plugin name must contain only alphanumeric characters, dashes, and underscores",e);if(o.length>100)throw new af("Plugin name must be 100 characters or less",e);if(s.startsWith("github:")){const t=s.slice(7).trim();if(!t||!/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(t))throw new af("Invalid GitHub repo format, expected 'org/repo' (e.g., 'anthropics/claude-plugins')",e);return{name:o,sourceType:"github",githubRepo:t,raw:e}}if(s.startsWith("local:")){const t=s.slice(6).trim();if(!t)throw new af("Missing path after 'local:'",e);return{name:o,sourceType:"local",localPath:t,raw:e}}if(s.startsWith("url:")){const t=s.slice(4).trim();if(!t)throw new af("Missing Git URL after 'url:'",e);try{new URL(t)}catch{throw new af("Invalid Git URL format",e)}return{name:o,sourceType:"url",gitUrl:t,raw:e}}const i=s.indexOf("#");let a,c;if(-1!==i?(a=s.slice(0,i).trim(),c=s.slice(i+1).trim()):a=s,!a)throw new af("Missing marketplace name",e);if(!r.test(a))throw new af("Marketplace name must contain only alphanumeric characters, dashes, and underscores",e);return{name:o,sourceType:"marketplace",marketplace:a,version:c,raw:e}}function lf(e){if("claude-plugin"===e.source)return e.sourceInfo.raw;if("user-local"===e.source)return`user-local:${e.sourceInfo.name}`;if("extension"===e.source){const t=e.sourceInfo;return`extension:${t.extensionId}:${t.localPath}`}const t=e.sourceInfo;return`${t.name}-${t.version}`}function uf(e){return e.sourceInfo.name}function df(e){switch(e.source){case"claude-plugin":case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplace;default:return}}function hf(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.pluginDbId;default:return}}function pf(e){switch(e.source){case"cursor-first-party":case"cursor-third-party":return e.sourceInfo.marketplaceDbId;default:return}}function ff(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function mf(e){return!!ff(e)&&(void 0===e.enabledPlugins||ff(e.enabledPlugins))}function gf(e){return JSON.parse(e)}function wf(e){const t=e??process.env.HOME??"";return(0,s.join)(t,".claude")}async function yf(e){const t={enabledPlugins:{}};let r=!1;const n=(0,s.join)(e,".claude","settings.json");try{const e=gf(await(0,Co.readFile)(n,"utf-8"));mf(e)&&e.enabledPlugins&&(Object.assign(t.enabledPlugins,e.enabledPlugins),r=!0)}catch{}const o=(0,s.join)(e,".claude","settings.local.json");try{const e=gf(await(0,Co.readFile)(o,"utf-8"));mf(e)&&e.enabledPlugins&&(Object.assign(t.enabledPlugins,e.enabledPlugins),r=!0)}catch{}return r?t:null}function vf(e,t){const r=(0,s.resolve)(e),n=(0,s.resolve)(e,t),o=(0,s.relative)(r,n);if(o.startsWith("..")||(0,s.isAbsolute)(o))throw new Error(`Invalid subPath: path traversal not allowed (${JSON.stringify(t)})`);return n}async function bf(e){try{return(await(0,Co.lstat)(e)).isSymbolicLink()}catch{return!1}}async function Sf(e){if(await bf(e))throw new Error(`Refusing to read symlink: ${e}`);return(0,Co.readFile)(e,"utf-8")}async function kf(e){if((await(0,Co.stat)(e)).size>10485760)throw new Error(`File ${e} exceeds maximum size of 10485760 bytes`)}function _f(e){const t=e instanceof Error?e.message:String(e);return/timed?\s*out/i.test(t)?"timeout":/clone|fetch|git/i.test(t)?"clone":/manifest|marketplace\.json/i.test(t)?"manifest":/parse|invalid|malformed/i.test(t)?"parse":/install|download|copy/i.test(t)?"install":"unknown"}async function Cf({installPath:e,logo:t}){const r=t?.trim();if(r&&!(0,s.isAbsolute)(r)&&!r.includes("://"))try{const t=await(0,Co.realpath)(e),n=vf(t,r),o=await(0,Co.realpath)(n);if(vf(t,o),!(await(0,Co.stat)(o)).isFile())return;return await kf(o),(0,Ed.pathToFileURL)(o).href}catch{return}}function Ef(e){const t={};return void 0!==e.version&&(t.version=e.version),void 0!==e.homepage&&(t.homepage=e.homepage),void 0!==e.repository&&(t.repository=e.repository),t}function xf(e){return void 0!==e.version||void 0!==e.homepage||void 0!==e.repository}function Pf(e,t){return Ef({version:e.version??t?.version,homepage:e.homepage??t?.homepage,repository:e.repository??t?.repository})}async function Rf(e,t,r){let n;for(const o of Hh){const i=(0,s.join)(e,o);let a;try{if(await bf(i))continue;if(!(await(0,Co.stat)(i)).isFile())continue;await kf(i),a=await Sf(i)}catch{continue}const c=Sp(a);if(!c.success)continue;const l=c.data,u=l.commands,d=l.agents,h=l.skills,p=l.rules,f=l.hooks,m=l.mcpServers,g=void 0!==u||void 0!==d||void 0!==h||void 0!==p||void 0!==f||void 0!==m,w="string"==typeof l.displayName?l.displayName:void 0,y="string"==typeof l.description?l.description:void 0,v=l.author?.name,b=await Cf({installPath:e,logo:l.logo}),S=Ef(l),k=l.variables,_=l.capabilities,C=void 0!==w||void 0!==y||void 0!==v||void 0!==b||void 0!==k||void 0!==_;if(!g&&!C&&!xf(S))continue;if(!g&&!C){n=n?{...n,fields:Pf(n.fields,S)}:{fields:S,path:i,relPath:o,unrecognizedSchemaId:c.unrecognizedSchemaId};continue}void 0!==c.unrecognizedSchemaId&&r.log("debug",`${t}: ${o} declares an unrecognized $schema, loading anyway: ${c.unrecognizedSchemaId}`);const E=Pf(S,n?.fields);return{manifestFilePath:i,...g&&{manifestOptions:{commands:u,agents:d,skills:h,rules:p,hooks:f,mcpServers:m}},...(C||xf(E))&&{metadata:{displayName:w,description:y,authorName:v,logoUrl:b,...E,variables:k,capabilities:_}}}}if(void 0!==n)return void 0!==n.unrecognizedSchemaId&&r.log("debug",`${t}: ${n.relPath} declares an unrecognized $schema, loading anyway: ${n.unrecognizedSchemaId}`),{manifestFilePath:n.path,metadata:n.fields}}async function If(e,t){const r=function(e,t){const r=new Map,n=(0,s.resolve)(e),o=(0,s.resolve)(t?.symlinkTargetRoot??n),i=(0,Co.realpath)(o).catch((()=>o));function a(e){const t=(0,s.resolve)(e);try{return vf(n,t)}catch{throw new Error(`Path escapes plugin directory: ${e}`)}}async function c(e){const t=a(e),r=await i,n=await(0,Co.realpath)(t);try{return vf(r,n)}catch{throw new Error(`Path escapes plugin directory via symlink: ${e}`)}}return{async listDirectory(t,r){const n=a(t?(0,s.join)(e,t):e);try{const e=await c(n);if(r?.has(e))return[];r?.add(e);const o=await(0,Co.readdir)(e,{withFileTypes:!0}),i=[];for(const e of o){const r=(0,s.join)(n,e.name);let o=e.isDirectory()?"dir":"file";if(e.isSymbolicLink())try{const e=await c(r);o=(await(0,Co.stat)(e)).isDirectory()?"dir":"file"}catch{continue}i.push({name:e.name,type:o,path:t?`${t}/${e.name}`:e.name})}return i}catch{return[]}},async fetchFile(t){const n=r.get(t);if(void 0!==n)return{content:n};const o=a((0,s.join)(e,t)),i=await c(o);await kf(i);const l=await(0,Co.readFile)(i,"utf-8");return r.set(t,l),{content:l}},async fileExists(t){try{const r=a((0,s.join)(e,t)),n=await c(r);return(await(0,Co.stat)(n)).isFile()}catch{return!1}}}}(e),n=new sf(r),o=await n.discoverComponents({manifest:t}),[i,a,c,l]=await Promise.all([Tf(r,o.skills,e),$f(r,o.agents,e),Mf(r,o.commands,e),Af(r,o.rules,e)]);return{skills:i,agents:a,commands:c,rules:l}}async function Tf(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Of({content:Ip(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}async function Af(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Of({content:Ip(t,r),relativePath:o.path});s&&n.push({...s,name:o.name})}catch{}return n}async function $f(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Ff({content:Ip(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}async function Mf(e,t,r){const n=[];for(const o of t)try{const{content:t}=await e.fetchFile(o.path),s=Nf({content:Ip(t,r),relativePath:o.path});s&&n.push(s)}catch{}return n}function Df(e){if("string"==typeof e){const t=function(e){const t=[];let r=0,n=0;for(let o=0;o0)n--;else if(","===s&&0===n){const n=e.slice(r,o).trim();n&&t.push(n),r=o+1}}if(n>0){for(const n of e.slice(r).split(",")){const e=n.trim();e&&t.push(e)}return t}const o=e.slice(r).trim();return o&&t.push(o),t}(e);return t.length>0?t:void 0}if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e)).map((e=>e.trim())).filter(Boolean);return t.length>0?t:void 0}}function Of({content:e,relativePath:t}){try{const r=eh(e),n=t.replace(/\\/g,"/"),o=n.split("/").filter((e=>e.length>0)),s=o.length>=2?o[o.length-2]:void 0,i=o[o.length-1]??n,a=s??i.replace(/\.md$/i,""),c="string"==typeof r.data.name?r.data.name.trim():void 0,l=rf(r.data.environments??r.data.metadata?.environments),u=rf(r.data["disabled-environments"]??r.data.metadata?.disabledEnvironments);return{path:t,name:c&&c.length>0?c:a,description:"string"==typeof r.data.description?r.data.description:void 0,globs:Df(r.data.globs),alwaysApply:!0===r.data.alwaysApply,content:e,environments:l,disabledEnvironments:u}}catch{return null}}function Ff({content:e,relativePath:t}){try{const n=eh(e),o=n.content.trim();if(!o)return null;let i;"string"==typeof n.data.tools?i=n.data.tools.split(",").map((e=>e.trim())).filter(Boolean):Array.isArray(n.data.tools)&&(i=n.data.tools.map((e=>"string"==typeof e?e.trim():String(e))).filter(Boolean));const a=n.data.permissionMode??n.data.permissionmode,c=(0,s.basename)(t);return{path:t,name:"string"==typeof n.data.name?n.data.name:(0,s.basename)(c,(0,s.extname)(c)).replace(/[\s_]+/g,"-"),description:"string"==typeof n.data.description?n.data.description:void 0,tools:i,model:"string"==typeof n.data.model?n.data.model:"inherit",prompt:o,permissionMode:(r=a,"readonly"===(r??"").trim().toLowerCase()?"readonly":"default")}}catch{return null}var r}function Nf({content:e,relativePath:t}){try{const r=eh(e);let n;const o=r.data["argument-hint"];"string"==typeof o?n=o:Array.isArray(o)&&(n=`[${o.join(" ")}]`);const i=(0,s.basename)(t);return{path:t,name:"string"==typeof r.data.name?r.data.name:(0,s.basename)(i,(0,s.extname)(i)),description:"string"==typeof r.data.description?r.data.description:void 0,argumentHint:n,content:r.content.trim()}}catch{return null}}function Lf(e){if(void 0!==e)return{configuredVariables:e.configuredVariables}}async function jf(e,t,r){const n=r??Lf(t);return async function(e,t={}){const r=t.toSourcePath??(e=>e);let n,o,s;for(const t of Hh){const i=await e(t);if(null===i)continue;let a;try{a=JSON.parse(i)}catch{continue}s=Lh(a);const c=Sp(i);if(c.success){void 0!==c.data.mcpServers&&(n=c.data.mcpServers,o=r(t));break}}return Bp(e,n,o,void 0===s?t:{...t,parserOptions:{...t.parserOptions,pluginSchemaId:s}})}(function(e){return async t=>{if(!_p(t))return null;const r=(0,s.join)(e,t);try{return await bf(r)?null:(await(0,Co.stat)(r)).isFile()?(await kf(r),await Sf(r)):null}catch{return null}}}(e),{fallbackFileNames:Np(),manifestPrecedence:"override",toSourcePath:t=>(0,s.join)(e,t),installPathForExpansion:e,parserOptions:n})}async function Uf(e,t,r){const n=await jf(e,void 0,{log:r});if(n)return n;for(const n of zh){const o=(0,s.join)(e,n);try{if(!(await(0,Co.stat)(o)).isFile())continue;const n=await(0,Co.readFile)(o,"utf-8"),i=JSON.parse(n);if(!Hf(i)||!Array.isArray(i.plugins))continue;const a=i.plugins.filter(qf),c=t.name,l=a.find((e=>e.name===c));if(!l?.mcpServers?.length)continue;for(const t of l.mcpServers){const n=t.replace(/^\.\//,"");if(!_p(n))continue;const o=(0,s.join)(e,n);try{await kf(o);const t=jp(await Sf(o),e,{log:r});if(t?.mcpServers&&Object.keys(t.mcpServers).length>0){const e=Object.fromEntries(Object.keys(t.mcpServers).map((e=>[e,o])));return{...t,mcpServerSourcePaths:e}}}catch{}}return null}catch{}}return null}Error;const Bf=new Set(Object.values(xd));function Wf(e){return Bf.has(e)}function Hf(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function qf(e){return!(!Hf(e)||"string"!=typeof e.name)&&(void 0===e.mcpServers||Array.isArray(e.mcpServers)&&e.mcpServers.every((e=>"string"==typeof e)))}function zf(e,t){const r={};for(const[n,o]of Object.entries(e.hooks))Array.isArray(o)&&Wf(n)&&(r[n]=o.map((e=>"command"in e&&"string"==typeof e.command?{...e,command:Ip(e.command,t)}:"prompt"in e&&"string"==typeof e.prompt?{...e,prompt:Ip(e.prompt,t)}:e)));return{...e,hooks:r}}async function Gf(e,t,r,n,o){if("object"==typeof n){const s=Vf(n,t,r);return s&&"config"in s?{config:zf(s.config,e),...void 0!==o&&{sourcePath:o}}:s}let i,a,c;if("string"==typeof n){const t=n.replace(/^\.\//,"");if(!_p(t))return;i=t.endsWith(".json")?(0,s.join)(e,t):(0,s.join)(e,t,"hooks.json")}else i=(0,s.join)(e,"hooks","hooks.json");try{if(await bf(i))return;if(!(await(0,Co.stat)(i)).isFile())return}catch{return}try{await kf(i),a=await(0,Co.readFile)(i,"utf-8")}catch{return}try{c=JSON.parse(a)}catch{return{error:{source:"claude-plugin",message:`Plugin ${t} ${i}: invalid JSON`}}}const l=Vf(c,t,r);return l&&"config"in l?{config:zf(l.config,e),sourcePath:i}:l}function Vf(e,t,r){const n=function(e){if(!Id(e))return"unknown";const t=e,r="object"==typeof t.hooks&&null!==t.hooks?t.hooks:null;if(!r)return"unknown";for(const e of Object.values(r)){if(!Array.isArray(e)||0===e.length)continue;const t=e[0];if(Id(t)){if("hooks"in t&&Array.isArray(t.hooks))return"claude-code";if("command"in t||"prompt"in t||"type"in t)return"cursor"}}return"unknown"}(e);if("cursor"===n){const r=Dd(e);return r.isValid&&Dd(e).isValid?{config:e}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${r.errors.join("; ")}`}}}if("claude-code"===n){if(!(Hf(o=e)&&Hf(o.hooks)&&Object.keys(o.hooks).length>0))return;const n=Xd(e.hooks,{warn:e=>r.log("warn",`Plugin ${t} hooks: ${e}`),info:e=>r.log("info",`Plugin ${t} hooks: ${e}`)}),s=Dd(n);return s.isValid?{config:n}:{error:{source:"claude-plugin",message:`Plugin ${t} hooks: ${s.errors.join("; ")}`}}}var o}async function Kf(e,t,r,n){const o=n?.log??Tp,s=await Rf(e,t,o),i={...Lf(r)??(n?.configuredVariables?{configuredVariables:n.configuredVariables}:void 0),log:o},[a,c,l]=await Promise.all([If(e,s?.manifestOptions),jf(e,r,i),Gf(e,t,o,s?.manifestOptions?.hooks,s?.manifestFilePath)]);return{...a,...void 0!==s?.metadata?.displayName&&{displayName:s.metadata.displayName},...void 0!==s?.metadata?.description&&{description:s.metadata.description},...void 0!==s?.metadata?.authorName&&{authorName:s.metadata.authorName},...void 0!==s?.metadata?.logoUrl&&{logoUrl:s.metadata.logoUrl},...void 0!==s?.metadata?.version&&{version:s.metadata.version},...void 0!==s?.metadata?.homepage&&{homepage:s.metadata.homepage},...void 0!==s?.metadata?.repository&&{repository:s.metadata.repository},variablesSchema:s?.metadata?.variables,mcpConfig:c,capabilities:s?.metadata?.capabilities??[],hooks:l}}async function Jf(e,t,r){const n=r?.log??Tp,o=await Rf(e,t.raw,n),[s,i,a]=await Promise.all([If(e,o?.manifestOptions),Uf(e,t,n),Gf(e,t.raw,n,o?.manifestOptions?.hooks,o?.manifestFilePath)]);return{identifier:{source:"claude-plugin",sourceInfo:t},installPath:e,...void 0!==o?.metadata?.displayName&&{displayName:o.metadata.displayName},...void 0!==o?.metadata?.description&&{description:o.metadata.description},...void 0!==o?.metadata?.authorName&&{authorName:o.metadata.authorName},...void 0!==o?.metadata?.logoUrl&&{logoUrl:o.metadata.logoUrl},...void 0!==o?.metadata?.version&&{version:o.metadata.version},...void 0!==o?.metadata?.homepage&&{homepage:o.metadata.homepage},...void 0!==o?.metadata?.repository&&{repository:o.metadata.repository},...s,mcpConfig:i??void 0,capabilities:o?.metadata?.capabilities??[],hooks:a}}async function Zf(e,t,r,n){const o=`${r.name}@${r.version}`,{displayName:s,description:i,authorName:a,logoUrl:c,version:l,homepage:u,repository:d,variablesSchema:h,skills:p,rules:f,agents:m,commands:g,mcpConfig:w,capabilities:y,hooks:v}=await Kf(e,o,r,{log:n?.log});return{identifier:{source:t,sourceInfo:r},installPath:e,...void 0!==s&&{displayName:s},...void 0!==i&&{description:i},...void 0!==a&&{authorName:a},...void 0!==c&&{logoUrl:c},...void 0!==l&&{version:l},...void 0!==u&&{homepage:u},...void 0!==d&&{repository:d},variablesSchema:h,skills:p,rules:f,agents:m,commands:g,mcpConfig:w??void 0,capabilities:y,hooks:v}}async function Xf(e,t,r={}){const n=r.log??Tp,o=performance.now(),i=await async function(e){const t=wf(e),r=(0,s.join)(t,"plugins","installed_plugins.json");try{const e=gf(await(0,Co.readFile)(r,"utf-8"));return ff(n=e)&&ff(n.plugins)?e:null}catch{return null}var n}(r.userHomeDir);if(!i?.plugins)return n.log("info",`loadAllEnabledPlugins: no installed plugins metadata found (${(performance.now()-o).toFixed(1)}ms)`),[];const a=await async function(e){const t=wf(e),r=(0,s.join)(t,"settings.json");try{const e=gf(await(0,Co.readFile)(r,"utf-8"));return mf(e)?e:null}catch{return null}}(r.userHomeDir),c=function(e){if(void 0===e)return[];const t="string"==typeof e?[e]:e,r=new Set,n=[];for(const e of t){if(!e)continue;const t=(0,s.resolve)(e);r.has(t)||(r.add(t),n.push(t))}return n}(e),l=function(e,t,r){if(0===r.length)return $h(e,t,null,void 0);const n=new Set;for(const{settings:e}of r)for(const[t,r]of Object.entries(e?.enabledPlugins??{}))!1===r&&n.add(t);const o=new Set,s=[];for(const{workspacePath:i,settings:a}of r){const r=$h(e,t,a,i);for(const e of r)o.has(e.pluginId)||n.has(e.pluginId)||(o.add(e.pluginId),s.push(e))}return s}(i,a,await(0,Or.PH)(c,(async e=>({workspacePath:e,settings:await yf(e)})),{max:8})),u=[],d=r.onError;for(const{pluginId:e,installPath:t}of l)try{const r=performance.now(),o=cf(e),s=await Jf(t,o,{log:n});u.push(s),n.log("info",`loadClaudePlugin ${e} loaded in ${(performance.now()-r).toFixed(1)}ms`)}catch(t){const r=t instanceof Error?t:new Error(String(t));if(d)try{d(cf(e),r)}catch{d({name:e.split("@")[0]??e,sourceType:"marketplace",marketplace:"unknown",raw:e},r)}}return n.log("info",`loadAllEnabledPlugins completed in ${(performance.now()-o).toFixed(1)}ms (${l.length} resolved, ${u.length} loaded)`),u}const Qf=new Map;async function Yf(e){const{entry:t,slug:r,cacheManager:n}=e;if(void 0===t.backendContent&&!Eh(t.downloadUrl))return em(e);const o=n.getCacheDir({marketplaceSlug:r,pluginId:t.pluginId,version:t.version}),s=Qf.get(o);if(void 0!==s)return s;const i=em(e).finally((()=>{Qf.delete(o)}));return Qf.set(o,i),i}async function em(e){const{entry:t,slug:r,client:n,cacheManager:o,pluginLogger:s}=e;if(await o.isCached({marketplaceSlug:r,pluginId:t.pluginId,version:t.version})){const e=o.getCacheDir({marketplaceSlug:r,pluginId:t.pluginId,version:t.version});return s.log("info",`loadFromMarketplaceSource: Found cached plugin: ${t.pluginId} at ${e}`,{marketplaceSlug:r,pluginId:t.pluginId,gitRef:t.version,marketplaceId:t.marketplace?.id}),e}const i=o.getCacheDir({marketplaceSlug:r,pluginId:t.pluginId,version:t.version});s.log("info",`loadFromMarketplaceSource: Plugin missing from cache, installing: ${t.pluginId} at ${i}`,{marketplaceSlug:r,pluginId:t.pluginId,gitRef:t.version,marketplaceId:t.marketplace?.id}),await(0,Co.mkdir)(i,{recursive:!0});try{await n.installPlugin(t,i),await o.markCacheComplete({marketplaceSlug:r,pluginId:t.pluginId,version:t.version})}catch(e){try{await(0,Co.rm)(i,{recursive:!0,force:!0})}catch{}throw e}return i}async function tm(e){const{error:t,entry:r,slug:n,client:o,cacheManager:s,pluginLogger:i}=e;if(!kh(t))return;if("revision_superseded"===t.reason){const t=await(o.relistPlugin?.(r).catch((()=>{})));if(void 0!==t)try{return{entry:t,installPath:await Yf({...e,entry:t})}}catch(e){if(!kh(e))throw e}}const a=await async function(e){const{cacheManager:t,marketplaceSlug:r,pluginId:n,exceptVersion:o}=e,s=oh(vh),i=await t.listCachedVersions({marketplaceSlug:r,pluginId:n});let a;for(const e of i){if(!e.startsWith(s))continue;const i=xh(e.slice(s.length));if(i===o)continue;const c=uh({parent:t.getCacheDir({marketplaceSlug:r,pluginId:n,version:i}),name:ch}),l=await(0,Co.stat)(c).then((e=>e.mtimeMs),(()=>{}));void 0!==l&&(void 0===a||l>a.installedAtMs)&&(a={version:i,installedAtMs:l})}return a?.version}({cacheManager:s,marketplaceSlug:n,pluginId:r.pluginId,exceptVersion:r.version});return void 0!==a?(i.log("warn",`Plugin ${r.pluginId} keeps its installed version until the listed one can be downloaded`,{pluginId:r.pluginId,reason:t.reason}),{entry:{...r,version:a},installPath:s.getCacheDir({marketplaceSlug:n,pluginId:r.pluginId,version:a})}):void 0}async function rm(e){const t=e.log??Tp,r=performance.now(),{client:n,userId:o,teamId:s,onCursorError:i,pruneOldVersions:a,pluginFilter:c,onPluginsListed:l}=e,u=[],d=e.cacheManager??new hh(e.userHomeDir),h=performance.now();let p;try{p=await n.listEnabledPlugins(o,s)}catch(e){return t.captureException(e,{error_type:"list_enabled_plugins"}),t.increment("marketplace.source_unavailable",1),t.log("error",`marketplace listEnabledPlugins failed after ${(performance.now()-h).toFixed(1)}ms; treating source as unavailable: ${e instanceof Error?e.message:String(e)}`),{plugins:[],failures:[],sourceUnavailable:!0}}t.log("info",`marketplace listEnabledPlugins completed in ${(performance.now()-h).toFixed(1)}ms (${p.plugins.length} plugins)`),l&&await l(p.plugins);const f=[];if(p.listFailures){u.push(...p.listFailures);for(const e of p.listFailures)f.push({identifier:{source:e.marketplaceName&&"cursor-public"!==e.marketplaceName?"cursor-third-party":"cursor-first-party",sourceInfo:{name:e.pluginName,version:"",...void 0!==e.pluginDbId&&{pluginDbId:e.pluginDbId},marketplace:e.marketplaceName}},installPath:"",loadError:e.errorMessage,skills:[],rules:[],agents:[],commands:[],capabilities:[]})}const m=new Map;for(const e of p.plugins){if(c&&!c(e))continue;let r=e;try{const e=r.marketplace?.name;if(!e){const e=new Error(`Plugin ${r.name} has no marketplace metadata — cannot determine cache path`);u.push({pluginName:r.name,pluginId:r.pluginId,marketplaceName:void 0,errorMessage:e.message,errorType:"manifest"}),i&&i(r,e);continue}const o=`${e}/${r.pluginId}`;let s,a=m.get(o);a||(a={slug:e,pluginId:r.pluginId,versions:[]},m.set(o,a)),a.versions.push(r.version);try{s=await Yf({entry:r,slug:e,client:n,cacheManager:d,pluginLogger:t})}catch(o){const i=await tm({error:o,entry:r,slug:e,client:n,cacheManager:d,pluginLogger:t});if(void 0===i)throw o;({entry:r,installPath:s}=i),a.versions.push(r.version)}const c=r.marketplace?.name,l=void 0!==c&&"cursor-public"!==c&&c.length>0?"cursor-third-party":"cursor-first-party",h={name:r.name,version:r.version,pluginDbId:r.pluginDbId,configuredVariables:r.configuredVariables,marketplace:c,marketplaceDbId:r.marketplaceDbId,isTeamRequired:r.isTeamRequired},p=await Zf(s,l,h,{log:t});f.push(p);try{await d.pruneOldVersions({marketplaceSlug:e,pluginId:r.pluginId,keepVersions:[r.version]})}catch{}}catch(e){t.captureException(e,{error_type:"load_plugin_from_marketplace"});const n=e instanceof Error?e:new Error(String(e));u.push({pluginName:r.name,pluginId:r.pluginId,marketplaceName:r.marketplace?.name,errorMessage:n.message,errorType:_f(n)});const o=r.marketplace?.name,s=void 0!==o&&"cursor-public"!==o&&o.length>0;f.push({identifier:{source:s?"cursor-third-party":"cursor-first-party",sourceInfo:{name:r.name,version:r.version,pluginDbId:r.pluginDbId,marketplace:o,marketplaceDbId:r.marketplaceDbId,isTeamRequired:r.isTeamRequired}},installPath:"",loadError:n.message||"Plugin load failed",skills:[],rules:[],agents:[],commands:[],capabilities:[]}),i&&i(r,n)}}if(a)for(const{slug:e,pluginId:t,versions:r}of m.values())try{await d.pruneOldVersions({marketplaceSlug:e,pluginId:t,keepVersions:r})}catch{}return t.log("info",`loadFromMarketplaceSource completed in ${(performance.now()-r).toFixed(1)}ms (${f.length} plugins loaded, ${u.length} failures)`),{plugins:f,failures:u,sourceUnavailable:!1}}function nm(e){const{identifier:t}=e;switch(t.source){case"claude-plugin":return"marketplace"===t.sourceInfo.sourceType&&t.sourceInfo.marketplace?`${t.sourceInfo.marketplace}/${t.sourceInfo.name}`:void 0;case"cursor-first-party":case"cursor-third-party":return t.sourceInfo.marketplace?`${t.sourceInfo.marketplace}/${t.sourceInfo.name}`:void 0;default:return}}function om(e){return nm(e)??`path:${e.installPath}`}function sm(e,t={}){return{...e,model:t.stripModel?void 0:e.model,tools:t.stripTools?void 0:e.tools}}function im(e,t){const r=[];for(const o of e){const e=lf(o.identifier),i=`plugin:${e}`,a=uf(o.identifier),c=df(o.identifier),l=hf(o.identifier),u=pf(o.identifier);for(const d of t(o)){const t=(0,s.join)(o.installPath,d.path),{type:h,globs:p,description:f}=(n=d).alwaysApply?{type:"global"}:n.globs&&n.globs.length>0?{type:"fileGlobbed",globs:n.globs}:n.description?{type:"agentFetched",description:n.description}:{type:"manuallyAttached"};r.push({fullPath:t,content:d.content,type:h,globs:p,description:f,pluginIdentifier:e,gitRemoteOrigin:i,plugin:a,marketplace:c,pluginId:l,marketplaceId:u,environments:d.environments,disabledEnvironments:d.disabledEnvironments})}}var n;return r}var am=r("../proto/dist/generated/agent/v1/agent_skills_pb.js");const cm=(0,zs.debuglog)("agent-skills-catalog-cache");function lm(e){return(0,bo.createHash)("sha256").update(JSON.stringify({v:1,...e})).digest("hex")}async function um(e){try{return(await(0,Co.stat)(e)).mtimeMs}catch{return}}function dm(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const hm=[".kits","cursor-pages"],pm={configDir:".cursor",subdir:"skills-cursor",thirdParty:!1,builtin:!0},fm=[{configDir:".cursor",subdir:"skills",thirdParty:!1,builtin:!1},{configDir:".claude",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".codex",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".grok",subdir:"skills",thirdParty:!0,builtin:!1},{configDir:".agents",subdir:"skills",thirdParty:!1,builtin:!1},pm],mm=(new Set(fm.map((e=>e.configDir))),new Set(["imagegen","openai-docs","opneai-docs","plugin-creator","skill-creator","skill-installer"]));function gm(e){return e.replace(/\\/g,"/").split("/").filter(Boolean)}function wm(e){const t=gm(e);if(function(e){const t=e.findIndex(((t,r)=>function(e,t){return fm.some((r=>r.configDir===e&&r.subdir===t))}(t,e[r+1])));return-1!==t&&e.slice(t+2).some((e=>e.startsWith(".")))}(t))return!0;const r=t.lastIndexOf(".codex");if(-1===r||"skills"!==t[r+1])return!1;const n=t.at(-1),o="SKILL.md"===n?t.at(-2):n;return void 0!==o&&mm.has(o)}function ym(e){return{dirPath:(0,s.join)(e,pm.configDir,pm.subdir),scope:"builtin",source:"builtin"}}const vm="canvas";function bm(e,t){return{dirPath:(0,s.join)(ym(e).dirPath,...hm),scope:"builtin",source:"builtin"}}function Sm(e,t){const r=e.replace(/\\/g,"/"),n=t.replace(/\\/g,"/").replace(/\/+$/,"");if(r.startsWith(`${n}/`))return gm(r.slice(n.length+1))}function km(e,t){const r=Sm(e,t);return void 0!==r&&!r.some((e=>e.startsWith(".")))}function _m(e){return fm.filter((t=>!t.builtin&&(e||!t.thirdParty)))}function Cm(e,t){return _m(t).map((t=>({dirPath:(0,s.join)(e,t.configDir,t.subdir),scope:"project",source:"workspace"})))}function Em(e,t){return _m(t).map((t=>({dirPath:(0,s.join)(e,t.configDir,t.subdir),scope:"user",source:"user"})))}var xm=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function Pm(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const Rm=fm.map((({configDir:e,subdir:t,thirdParty:r})=>({pattern:new RegExp(`[/\\\\]${Pm(e)}[/\\\\]${Pm(t)}[/\\\\]`,"i"),requiresThirdParty:r}))),Im=/[/\\]\.cursor[/\\]rules[/\\]/i,Tm=[{pattern:/[/\\]\.cursor[/\\]agents[/\\]/i,requiresThirdParty:!1},{pattern:/[/\\]\.claude[/\\]agents[/\\]/i,requiresThirdParty:!0}],Am=new Set(["AGENTS.md","CLAUDE.md","CLAUDE.local.md"]);function $m(e,t){const r=e.replace(/\\/g,"/"),n=(0,s.basename)(r);if(Am.has(n))return"AGENTS.md"===n||t&&("CLAUDE.md"===n||"CLAUDE.local.md"===n)?"markdown":void 0;if(Im.test(r)&&n.endsWith(".mdc"))return"rules";if("SKILL.md"===n)for(const{pattern:e,requiresThirdParty:n}of Rm)if(e.test(r)){if(n&&!t)continue;return"skills"}if(n.endsWith(".md"))for(const{pattern:e,requiresThirdParty:n}of Tm)if(e.test(r)){if(n&&!t)continue;return"agents"}}class Mm{constructor(e,t,r,n){this.root=e,this.gitExecutor=t,this.userHomeDirectory=r,this.getThirdPartyExtensibilityEnabled=n}static getRipwalkCache(){return Mm.ripwalkCache??=new Sa,Mm.ripwalkCache}async discover(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,$.VI)(e.withName("NestedExtensibilityService.discover")),!1),n={rules:[],skills:[],markdown:[],agents:[]},o=(0,s.resolve)(this.root),i=(0,s.resolve)(this.userHomeDirectory);if(o===i||Hs(o,{platform:process.platform,homeDirectory:i}).length>0)return r.span.setAttribute("nested_extensibility.rules",0),r.span.setAttribute("nested_extensibility.skills",0),r.span.setAttribute("nested_extensibility.markdown",0),r.span.setAttribute("nested_extensibility.agents",0),n;if(!await Ya(e,this.gitExecutor,(0,s.resolve)(this.root)))return r.span.setAttribute("nested_extensibility.rules",0),r.span.setAttribute("nested_extensibility.skills",0),r.span.setAttribute("nested_extensibility.markdown",0),r.span.setAttribute("nested_extensibility.agents",0),n;const a=this.getThirdPartyExtensibilityEnabled(),c=this.buildIncludeGlobs(a),l={root:this.root,includeGlobs:c,excludeGlobs:lc,followSymlinks:!0,source:"nested_extensibility"},u={rules:[],skills:[],markdown:[],agents:[]},d=Mm.getRipwalkCache();try{const e=d.walk(r.ctx,l);try{for await(const t of e.lines){const e=$m(t,a);e&&u[e].push((0,s.resolve)(this.root,t))}}finally{d.delete(l)}}catch{}return r.span.setAttribute("nested_extensibility.rules",u.rules.length),r.span.setAttribute("nested_extensibility.skills",u.skills.length),r.span.setAttribute("nested_extensibility.markdown",u.markdown.length),r.span.setAttribute("nested_extensibility.agents",u.agents.length),u}catch(e){t.error=e,t.hasError=!0}finally{xm(t)}}buildIncludeGlobs(e){const t=["*/**/.cursor/**","*/**/.agents/**","*/**/AGENTS.md"];return e&&t.push("*/**/.claude/**","*/**/.codex/**","*/**/.grok/**","*/**/CLAUDE.md","*/**/CLAUDE.local.md"),t}}const Dm=new Set(["node_modules","__pycache__","dist","build"]);async function Om({rootDir:e,includeFile:t,maxDepth:r=10,containmentRootDir:n}){const o=[],i=[{dir:e,depth:0}],a=new Set,c=void 0!==n?await(0,Co.realpath)(n):null,l=e=>{if(null===c)return!0;const t=(0,s.relative)(c,e);return""===t||!t.startsWith("..")&&!(0,s.isAbsolute)(t)};for(;i.length>0;){const e=i.pop();if(void 0===e)continue;const{dir:n,depth:c}=e;if(c>r)continue;try{const e=await(0,Co.realpath)(n);if(!l(e))continue;if(a.has(e))continue;a.add(e)}catch{continue}const d=await(0,Co.readdir)(n,{withFileTypes:!0,encoding:"utf8"}).catch((()=>null));if(null!==d)for(const e of d){const r=(0,s.join)(n,e.name);let a=e.isDirectory(),l=e.isFile();if(e.isSymbolicLink())try{const e=await(0,Co.stat)(r);a=e.isDirectory(),l=e.isFile()}catch{continue}if(a){if((u=e.name).startsWith(".")||Dm.has(u))continue;i.push({dir:r,depth:c+1})}else l&&t(e.name)&&o.push(r)}}var u;return o.sort(((e,t)=>e.localeCompare(t))),o}const Fm={agentStoreSkillsDirs:[],userHomeDirectory:""};function Nm(e){const t=e.replace(/\\/g,"/");return t.endsWith("/")?t.slice(0,-1):t}function Lm(e,t){const r=Nm(t.userHomeDirectory),n=e.replace(/\\/g,"/");if(r.length>0)for(const e of t.agentStoreSkillsDirs){const t=Nm(e);if(t.length>0&&n.startsWith(`${t}/`))return{key:`${r}::skills/${n.slice(t.length+1)}`,inAgentStore:!0}}return{key:jm(e),inAgentStore:!1}}function jm(e){const t=e.replace(/\\/g,"/"),r=t.toLowerCase(),n=r.indexOf("/.cursor/"),o=r.indexOf("/.claude/"),s=r.indexOf("/.codex/"),i=r.indexOf("/.grok/"),a=r.indexOf("/.agents/");return-1!==n?`${t.slice(0,n)}::${t.slice(n+9)}`:-1!==o?`${t.slice(0,o)}::${t.slice(o+9)}`:-1!==s?`${t.slice(0,s)}::${t.slice(s+8)}`:-1!==i?`${t.slice(0,i)}::${t.slice(i+7)}`:-1!==a?`${t.slice(0,a)}::${t.slice(a+9)}`:e}function Um(e,t){const r=new Map,n=[];for(const o of e){const{key:e,inAgentStore:s}=Lm(o.fullPath,t),i=r.get(e);void 0!==i?s&&!n[i].inAgentStore&&(n[i]={item:o,inAgentStore:s}):(r.set(e,n.length),n.push({item:o,inAgentStore:s}))}return n.map((e=>e.item))}var Bm=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},Wm=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Hm=(0,l.h)("local-exec:cursor-rules");function qm(e){return"/"===e||"\\"===e}function zm(e){return e.split(/[\\/]+/).filter((e=>e.length>0)).length}async function Gm(e){return await Om({rootDir:e,includeFile:e=>"SKILL.md"===e})}async function Vm(e){let t;try{t=await ji(e)}catch(t){return{skillFilePath:e,error:bd(t)}}try{return{skillFilePath:e,content:t,parsed:eh(t)}}catch(t){return{skillFilePath:e,error:Sd(t)}}}async function Km(e){const t=await ts(e);return{...await Vm(e),realSkillFilePath:t}}function Jm(e){return Qm(e.data?.environments??e.data?.metadata?.environments)??[]}function Zm(e){return Qm(e.data?.["disabled-environments"]??e.data?.metadata?.disabledEnvironments)??[]}function Xm(e){return Qm(e.data?.metadata?.scopedTo??e.data?.["metadata.scopedTo"])??[]}function Qm(e){if(Array.isArray(e)){const t=e.filter((e=>"string"==typeof e&&e.length>0));return 0===t.length?void 0:t}if("string"==typeof e){const t=e.split(",").map((e=>e.trim())).filter((e=>e.length>0));return 0===t.length?void 0:t}}function Ym(e,t,r){const n=function(e){const t=e.data?.metadata?.surfaces;return Array.isArray(t)?t:"string"==typeof t?t.split(",").map((e=>e.trim())).filter(Boolean):[]}(e);return n.length>0&&!n.includes(t)&&!r.includes(e.data?.name)}function eg(e){return Vo(e,1536)}function tg(e){return!0===e.data?.alwaysApply}function rg(e){return!0===e.data?.["disable-model-invocation"]}function ng({skillFilePath:e,content:t,parsed:r}){const n=function(e){return function(e){const t=(e.matter??"").trim(),r=e.language?.toLowerCase();return t.length>0&&"js"!==r&&"javascript"!==r?`---\n${t}\n---`:th("",e.data??{}).trim()}(e)}(r),o=function({fullPath:e,name:t,description:r,body:n}){const o=[],s=function(e){const t=e.replace(/\\/g,"/").split("/"),r=t[t.length-1]??"";return"SKILL.md"===r&&t.length>=2?t[t.length-2]??"":r}(e);s.length>64&&o.push(`Name is ${Cd(s.length)} characters; the limit is 64. Rename the skill's folder.`),_d.test(s)||o.push('Name should be lowercase letters and numbers joined by single hyphens, like "pdf-helper". Rename the skill\'s folder.'),void 0!==t&&t!==s&&o.push(`Frontmatter name ${JSON.stringify(t)} doesn't match the folder name ${JSON.stringify(s)}, which is the name the skill goes by. Make them the same.`);const i=r?.trim().length??0;i>1024&&o.push(`Description is ${Cd(i)} characters; the limit is ${Cd(1024)}.`);const a=Math.round(n.length/4);return a>5e3&&o.push(`Body is about ${Cd(a)} tokens; the recommended limit is ${Cd(5e3)}. Move details into reference files that SKILL.md links to.`),o}({fullPath:e,name:"string"==typeof r.data?.name?r.data.name:void 0,description:"string"==typeof r.data?.description?r.data.description:void 0,body:r.content});if(tg(r))return new Vr.DX({fullPath:e,content:t,frontmatter:n,type:new Vr.f5({type:{case:"global",value:new Vr.i9}}),environments:Jm(r),disabledEnvironments:Zm(r),scopedTo:Xm(r),warnings:o});const s="string"==typeof r.data?.description?eg(r.data.description):void 0,i=kd(s,rg(r));return i?new Vr.DX({fullPath:e,parseError:i,frontmatter:n,scopedTo:Xm(r),type:new Vr.f5({type:{case:"agentFetched",value:new Vr.Xo}})}):new Vr.DX({fullPath:e,content:t,frontmatter:n,type:new Vr.f5({type:{case:"agentFetched",value:new Vr.Xo({description:s})}}),environments:Jm(r),disabledEnvironments:Zm(r),scopedTo:Xm(r),warnings:o})}function og({skillFilePath:e,content:t,parsed:r}){const n="string"==typeof r.data?.description?eg(r.data.description):"",o=Df(r.data?.paths??r.data?.globs),s=rg(r);return new am.N({fullPath:e,content:t,description:n,globs:o??[],parseError:kd(n,s),environments:Jm(r),disabledEnvironments:Zm(r),scopedTo:Xm(r),disableModelInvocation:s})}function sg({rules:e,agentSkills:t,skillFilePath:r,errorMessage:n}){e.push(function({skillFilePath:e,errorMessage:t}){return new Vr.DX({fullPath:e,parseError:t,type:new Vr.f5({type:{case:"agentFetched",value:new Vr.Xo}})})}({skillFilePath:r,errorMessage:n})),t.push(function({skillFilePath:e,errorMessage:t}){return new am.N({fullPath:e,parseError:t})}({skillFilePath:r,errorMessage:n}))}function ig(e,t,r,n){if("error"in t)return e.realSkillFilePathsByFullPath.set(t.skillFilePath,t.realSkillFilePath),void sg({rules:e.rules,agentSkills:e.agentSkills,skillFilePath:t.skillFilePath,errorMessage:t.error});Ym(t.parsed,r,n)||(e.realSkillFilePathsByFullPath.set(t.skillFilePath,t.realSkillFilePath),e.rules.push(ng(t)),tg(t.parsed)||e.agentSkills.push(og(t)))}const ag=(0,zs.debuglog)("cursor-rules-service");function cg(){return{rules:[],agentSkills:[],realSkillFilePathsByFullPath:new Map}}function lg(e){return t=>(ag("%s: %O",e,t),cg())}function ug(e,t){return lm({kind:"agent-store",surface:e,roots:[...t].sort()})}function dg(e,t){const r=t.replace(/\\/g,"/").replace(/\/+$/,"");return""!==r&&e.replace(/\\/g,"/").startsWith(`${r}/`)}function hg(e){let t;if(!0===e.frontmatter.alwaysApply)t={case:"global",value:new Vr.i9};else{const r=Df(e.frontmatter.globs);t=r&&r.length>0?{case:"fileGlobbed",value:new Vr.uT({globs:r})}:"string"==typeof e.frontmatter.description&&e.frontmatter.description.trim().length>0?{case:"agentFetched",value:new Vr.Xo({description:eg(e.frontmatter.description)})}:{case:"manuallyAttached",value:new Vr._u}}const r=e.frontmatter["metadata.environments"],n=Array.isArray(r)?r:[],o=e.frontmatter["metadata.disabledEnvironments"],s=Array.isArray(o)?o:[],i=e.frontmatter["metadata.scopedTo"],a=Array.isArray(i)?i:[];return new Vr.DX({fullPath:e.path,content:e.body,type:new Vr.f5({type:t}),environments:n,disabledEnvironments:s,scopedTo:a,frontmatter:e.rawFrontmatter??""})}class pg{constructor(e,t){this.cursorRulesServices=e,this.getAgentStoreSkillsContext=t,this.onChangeCallbacks=new Set}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{const r=Bm(t,(0,$.VI)(e.withName("MergedCursorRulesService.getAllCursorRules")),!1),n=this.cursorRulesServices.map((e=>e.getAllCursorRules(r.ctx).catch((e=>((0,zs.debuglog)("Failed to load cursor rules from service:",e),[])))));return Um((await Promise.all(n)).flat(),this.getAgentStoreSkillsContext())}catch(e){t.error=e,t.hasError=!0}finally{Wm(t)}}reload(e){for(const t of this.cursorRulesServices)t.reload(e)}scheduleDidChangeRules(){void 0===this.changeTimer&&(this.changeTimer=setTimeout((()=>{this.changeTimer=void 0;for(const e of Array.from(this.onChangeCallbacks))e()}),pg.CHANGE_COALESCE_MS))}ensureChangeListenersRegistered(){void 0===this.disposeChangeListeners&&(this.disposeChangeListeners=this.cursorRulesServices.map((e=>e.onDidChangeRules((()=>this.scheduleDidChangeRules())))))}disposeChangeListenersIfUnused(){if(!(this.onChangeCallbacks.size>0||void 0===this.disposeChangeListeners)){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0,void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0)}}onDidChangeRules(e){return this.onChangeCallbacks.add(e),this.ensureChangeListenersRegistered(),()=>{this.onChangeCallbacks.delete(e),this.disposeChangeListenersIfUnused()}}dispose(){if(void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0),this.onChangeCallbacks.clear(),void 0!==this.disposeChangeListeners){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0}for(const e of this.cursorRulesServices)e.dispose&&e.dispose()}}pg.CHANGE_COALESCE_MS=1e3;class fg{constructor(e,t,r,n,i,a,c,l){this.gitExecutor=t,this.rootDirectory=r,this.loadNestedRules=n,this.getThirdPartyExtensibilityEnabled=i,this.loadTraceId=void 0,this.onChangeCallbacks=new Set,this.nestedExtensibilityService=new Mm(r,t,(0,o.homedir)(),i),this.ignoreService=c??new xc(t,void 0,[this.rootDirectory]);const u=performance.now();if(this._rules=this.load(e,l).then((t=>{try{Hm.info(e,"LocalCursorRulesService load completed",{durationMs:Math.round(performance.now()-u),ruleCount:t.length})}catch{}return t})).catch((e=>((0,zs.debuglog)("Failed to load cursor rules:",e),[]))),a){const e=[".cursor/rules/**/*.mdc","AGENTS.md","CLAUDE.md","CLAUDE.local.md",".cursorrules",".cursorignore"];this.unsubscribeWatcher=a.subscribe(this.rootDirectory,e,(e=>{const t={stack:[],error:void 0,hasError:!1};try{const r=(0,y.q6)(),n=Bm(t,(0,$.VI)(r.withName("LocalCursorRulesService.fileWatcher.subscribe")),!1);if(".cursorignore"===(0,s.basename)(e))return fg.getRipwalkCache().clear(),void this.reload(n.ctx);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{Wm(t)}}))}}reload(e){this._rules=this.load(e).catch((e=>((0,zs.debuglog)("Failed to load cursor rules:",e),[])));for(const e of this.onChangeCallbacks)e()}static getRipwalkCache(){return fg.ripwalkCache??=new Sa,fg.ripwalkCache}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.reloadAtPath")),!1);if(Jr((0,s.basename)(t)))return void this.reload(n.ctx);const o=this._rules;this._rules=(async()=>{const e=(await o).filter((e=>e.fullPath!==t));const r=(await this.readRulesAtPath(n.ctx,t)).map((e=>this.toCursorRule(e)));return[...e,...r]})().catch((e=>((0,zs.debuglog)("Failed to load cursor rules at path:",e),[])));for(const e of this.onChangeCallbacks)e()}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}isRuleMarkdownFile(e){return Jr(e)}async readRulesAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.readRulesAtPath")),!1),o=(0,s.basename)(t);if(".cursorrules"===o){const e=(0,s.resolve)(this.rootDirectory),t=await Ya(n.ctx,this.gitExecutor,e)||e,r=await this.loadCursorRulesRule(n.ctx,t);return r?[r]:[]}if(o.endsWith(".mdc"))return await mg(t);if(this.isRuleMarkdownFile(o))try{return await this.loadRulesFromMarkdownFile(n.ctx,(0,s.dirname)(t),o)}catch{}return[]}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}dispose(){this.unsubscribeWatcher&&(this.unsubscribeWatcher(),this.unsubscribeWatcher=void 0)}async load(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.load")),!1);this.loadTraceId=n.span.spanContext().traceId;const o=(0,s.resolve)(this.rootDirectory),i=await Ya(n.ctx,this.gitExecutor,o)||o,a=this.loadCursorRulesRule(n.ctx,i).then((e=>e?[e]:[])),c=this.loadRulesFromDirAndAncestors(n.ctx,o);let l,u;if(this.loadNestedRules){const e=t??this.nestedExtensibilityService.discover(n.ctx);l=e.then((e=>this.parseNestedRuleFiles(n.ctx,e.rules))),u=e.then((e=>this.parseNestedMarkdownFiles(n.ctx,e.markdown)))}else l=[],u=[];const d=(await Promise.all([a,c,l,u])).flat(),h=new Map;for(const e of d)h.set(e.path,e);const p=[...h.values()];return(await async function(e){const t=e.filter((e=>Jr((0,s.basename)(e.fullPath))));if(t.length<=1)return[...e];const r=await(0,Or.PH)(t,(e=>async function(e){try{const t=await(0,Co.stat)(e,{bigint:!0});if(0n!==t.ino)return`ino:${String(t.dev)}:${String(t.ino)}`}catch{}return await ts(e)}(e.fullPath)),{max:16}),n=t.map(((e,t)=>({item:e,identity:r[t],dir:(0,s.dirname)(e.fullPath),content:e.content.trim()}))).sort(((e,t)=>{const r=zm(e.dir)-zm(t.dir);if(0!==r)return r;const n="AGENTS.md"===(0,s.basename)(e.item.fullPath);return n===("AGENTS.md"===(0,s.basename)(t.item.fullPath))?0:n?-1:1})),o=[];for(const e of n)o.some((t=>{return((r=t.dir)===(n=e.dir)||!!n.startsWith(r)&&(qm(r.at(-1))||qm(n[r.length])))&&(t.identity===e.identity||t.content===e.content);var r,n}))||o.push(e);const i=new Set(o.map((e=>e.item)));return e.filter((e=>!Jr((0,s.basename)(e.fullPath))||i.has(e)))}(p.map((e=>({fullPath:e.path,content:e.body,rule:e}))))).map((e=>this.toCursorRule(e.rule)))}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}async loadCursorRulesRule(e,t){const r={stack:[],error:void 0,hasError:!1};try{Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.loadCursorrules")),!1);try{const e=(0,s.join)(t,".cursorrules");if((await(0,Co.stat)(e)).isFile())return{filename:".cursorrules",path:e,frontmatter:{alwaysApply:!0},body:await ji(e)}}catch{}return null}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}async getAllCursorRules(e){const t={stack:[],error:void 0,hasError:!1};try{return Bm(t,(0,$.VI)(e.withName("LocalCursorRulesService.getAllCursorRules")),!1).span.setAttribute("cacheTraceId",this.loadTraceId??"undefined"),await this._rules}catch(e){t.error=e,t.hasError=!0}finally{Wm(t)}}toCursorRule(e){return hg({path:e.path,body:e.body,frontmatter:e.frontmatter,rawFrontmatter:e.rawFrontmatter})}async loadRulesFromDirAndAncestors(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirAndAncestors")),!1),o=[];let i=t;const a=this.getThirdPartyExtensibilityEnabled();for(;;){const e=(0,s.join)(i,".cursor","rules"),t=i;o.push((async()=>await this.dirIsDirectory(n.ctx,e)?this.loadRulesFromDirectory(n.ctx,t):[])());const r=[];a&&r.push("CLAUDE.md","CLAUDE.local.md"),r.push("AGENTS.md");for(const e of r)o.push(this.loadRulesFromMarkdownFile(n.ctx,i,e));const c=(0,s.dirname)(i);if(c===i)break;i=c}const c=(await Promise.all(o)).flat();return n.span.setAttribute("rules",c.length),c}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}async loadRulesFromMarkdownFile(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{Bm(n,(0,$.VI)(e.withName("LocalCursorRulesService.loadRulesFromMarkdownFile")),!1).span.setAttribute("filename",r);try{const e=(0,s.join)(t,r);if(await this.isCursorIgnored(e))return[];if((await(0,Co.stat)(e)).isFile()){const t=Zr({content:await ji(e),filename:r});return[{filename:(0,s.basename)(e,".md"),path:e,frontmatter:{alwaysApply:!0},body:t}]}}catch{}return[]}catch(e){n.error=e,n.hasError=!0}finally{Wm(n)}}async isCursorIgnored(e){try{const t=await Cc((0,s.resolve)(this.rootDirectory,e));return null===t||await this.ignoreService.isCursorIgnored(t)}catch{return!1}}async parseNestedRuleFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.parseNestedRuleFiles")),!1),o=(await Promise.all(t.map((async e=>{try{const t=en(await ji(e));if(t)return{filename:(0,s.basename)(e,".mdc"),path:e,frontmatter:t.frontmatter,rawFrontmatter:t.rawFrontmatter,body:t.body}}catch{}})))).filter((e=>void 0!==e));return n.span.setAttribute("ruleFiles",o.length),o}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}async parseNestedMarkdownFiles(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.parseNestedMarkdownFiles")),!1),o=(await Promise.all(t.map((async e=>{try{const t=(0,s.basename)(e);if(!this.isRuleMarkdownFile(t))return[];const r=(0,s.dirname)(e);return await this.loadRulesFromMarkdownFile(n.ctx,r,t)}catch{}return[]})))).flat();return n.span.setAttribute("markdownFiles",o.length),o}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}async loadRulesFromDirectory(e,t){return await async function(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=Bm(n,(0,$.VI)(e.withName("LocalCursorRulesService.loadRulesFromDirectory")),!1),i=[];try{(0,s.join)(t,".cursorignore");const e={root:(0,s.join)(t,".cursor","rules"),includeGlobs:["**/*.mdc"],followSymlinks:!0,source:"cursor_rules"},n=r.walk(o.ctx,e);for await(const t of n.lines){const r=(0,s.join)(e.root,t);i.push(...await mg(r))}}catch{}return o.span.setAttribute("rules",i.length),i}catch(e){n.error=e,n.hasError=!0}finally{Wm(n)}}(e,t,fg.getRipwalkCache())}async dirIsDirectory(e,t){const r={stack:[],error:void 0,hasError:!1};try{Bm(r,(0,$.VI)(e.withName("LocalCursorRulesService.dirIsDirectory")),!1);try{return(await(0,Co.stat)(t)).isDirectory()}catch{return!1}}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}}async function mg(e){try{const t=en(await ji(e));if(t)return[{filename:(0,s.basename)(e,".mdc"),path:e,frontmatter:t.frontmatter,rawFrontmatter:t.rawFrontmatter,body:t.body}]}catch{}return[]}class gg{constructor(e,t,r,n,o,s,i=()=>!0,a=Promise.resolve(),c="ide",l,u=()=>[],d,h,p=()=>[],f){if(this.workspacePaths=t,this.userHomeDirectory=r,this.gitExecutor=n,this.getEnabledSkills=p,this.ignoreService=f,this.agentStoreLoadRequestedWhileInFlight=!1,this.agentStoreLoadGeneration=0,this.watchersByFolder=new Map,this.onChangeCallbacks=new Set,this.reloadRequestedDuringSeed=!1,this.surface=c,this.waitBeforeSkillLoad="function"==typeof a?a:()=>a,this.getAgentStoreSkillRoots=u,this.fileWatcher=s,this.getThirdPartyExtensibilityEnabled=i,this.catalogCache=d,this.builtinSkillRootDir=ym(r).dirPath,this.canvasKitSkillRootDir=void 0===h?void 0:bm(r).dirPath,this.workspaceCatalogKey=lm({kind:"workspace",surface:c,loadNestedSkills:o,thirdPartyExtensibility:i(),workspacePaths:[...t].sort(),userHomeDirectory:r,...void 0===h?{}:{canvasKit:h}}),void 0!==l&&l.length!==t.length)throw new Error(`initialNestedExtensibilityResults length (${l.length}) must match workspacePaths length (${t.length})`);this.nestedExtensibilityEntries=o?t.map((e=>new Mm(e,n,r,i))):[],this.foldersToWatch=this.computeFoldersToWatch();const m=performance.now();let g=!1,w=!1,y=!1;const v=this.loadAll(e,l).then((t=>{try{Hm.info(e,"AgentSkillsCursorRulesService load completed",{durationMs:Math.round(performance.now()-m),ruleCount:t.rules.length,skillCount:t.agentSkills.length,servedFromCache:g})}catch{}return t})).catch((e=>(w=!0,lg("Failed to load Agent Skills")(e))));if(void 0===this.catalogCache)this._loaded=v;else{const t=this.readCatalog(this.workspaceCatalogKey).then((r=>(y=!0,this._loaded!==t?this._loaded:(w&&this.closeSeedWindow(e),void 0===r?v:(g=!0,r)))));this.seededLoaded=t,this._loaded=t,v.then((r=>{this._loaded===t?w?y&&this.closeSeedWindow(e):(this._loaded=v,g&&this.notifyChanged(),this.persistCatalog(this.workspaceCatalogKey,r),this.closeSeedWindow(e)):this.seededLoaded=void 0}))}this.refreshAgentStoreSkills(),this.setupWatchers(this.foldersToWatch)}closeSeedWindow(e){this.seededLoaded=void 0,this.reloadRequestedDuringSeed&&(this.reloadRequestedDuringSeed=!1,this.reload(e))}async readCatalog(e){if(void 0!==this.catalogCache)try{const t=await this.catalogCache.read(e);return void 0===t?void 0:await async function(e){if(!function(e){if(!dm(e))return!1;const t=e.fileMtimesMs;return 1===e.version&&Array.isArray(e.rules)&&Array.isArray(e.agentSkills)&&Array.isArray(e.realSkillFilePathsByFullPath)&&e.realSkillFilePathsByFullPath.every((e=>Array.isArray(e)&&2===e.length&&"string"==typeof e[0]&&"string"==typeof e[1]))&&dm(t)&&Object.values(t).every((e=>"number"==typeof e&&Number.isFinite(e)))}(e))return;const t=new Map;if(await Promise.all(e.realSkillFilePathsByFullPath.map((async([r,n])=>{const o=e.fileMtimesMs[n];void 0!==o&&await um(r)===o&&t.set(r,n)}))),0===t.size)return;const r=e=>void 0!==e&&t.has(e);try{return{rules:e.rules.map((e=>Vr.DX.fromJson(e,{ignoreUnknownFields:!0}))).filter((e=>r(e.fullPath))),agentSkills:e.agentSkills.map((e=>am.N.fromJson(e,{ignoreUnknownFields:!0}))).filter((e=>r(e.fullPath))),realSkillFilePathsByFullPath:t}}catch(e){return void cm("snapshot failed to decode: %O",e)}}(t)}catch(e){return void ag("Failed to read the skills catalog cache: %O",e)}}persistCatalog(e,t){const r=this.catalogCache;void 0!==r&&async function(e){const t=new Set(e.realSkillFilePathsByFullPath.values()),r={};return await Promise.all(Array.from(t,(async e=>{const t=await um(e);void 0!==t&&(r[e]=t)}))),{version:1,rules:e.rules.map((e=>e.toJson())),agentSkills:e.agentSkills.map((e=>e.toJson())),realSkillFilePathsByFullPath:Array.from(e.realSkillFilePathsByFullPath),fileMtimesMs:r}}(t).then((t=>r.write(e,t))).catch((e=>{ag("Failed to persist the skills catalog cache: %O",e)}))}computeFoldersToWatch(){const e=this.getThirdPartyExtensibilityEnabled(),t=new Set;for(const r of this.workspacePaths){t.add((0,s.join)(r,".cursor","rules"));for(const n of Cm(r,e))t.add(n.dirPath)}for(const r of Em(this.userHomeDirectory,e))t.add(r.dirPath);for(const e of this.getAgentStoreSkillRoots())t.add(e);return t.add(this.builtinSkillRootDir),void 0!==this.canvasKitSkillRootDir&&t.add(this.canvasKitSkillRootDir),Array.from(t)}isIgnoredSkillPath(e){if(void 0!==this.canvasKitSkillRootDir){if(km(e,this.canvasKitSkillRootDir))return!1;if(function(e,t){const r=Sm(e,t);return void 0!==r&&2===r.length&&r[0]===vm&&"SKILL.md"===r[1]}(e,this.builtinSkillRootDir))return!0}return wm(e)}setupWatchers(e){if(!this.fileWatcher)return;const t=["**"];for(const r of e){if(this.watchersByFolder.has(r))continue;const e=this.fileWatcher.subscribe(r,t,(e=>{const t={stack:[],error:void 0,hasError:!1};try{const r=(0,y.q6)(),n=Bm(t,(0,$.VI)(r.withName("AgentSkillsCursorRulesService.fileWatcher.subscribe")),!1);this.reloadAtPath(n.ctx,e)}catch(e){t.error=e,t.hasError=!0}finally{Wm(t)}}));this.watchersByFolder.set(r,e)}}removeWatchers(e){for(const t of e){const e=this.watchersByFolder.get(t);e&&(e(),this.watchersByFolder.delete(t))}}async getAllCursorRules(e){const[t]=await Promise.all([this._loaded,this.awaitAgentStoreSeed()]);return this.withAgentStoreSkills(t).rules}async awaitAgentStoreSeed(){void 0!==this.agentStoreSeedInFlight&&await(0,Or.wj)(this.agentStoreSeedInFlight,250,"Agent Store skills cache read timed out").catch((()=>{}))}reload(e){this.syncWatchers(),this.seededLoaded=void 0,this.reloadRequestedDuringSeed=!1;const t=this.loadAll(e),r=t.catch(lg("Failed to load Agent Skills"));this._loaded=r,t.then((e=>{this._loaded===r&&this.persistCatalog(this.workspaceCatalogKey,e)}),(()=>{})),this.refreshAgentStoreSkills(),this.notifyChanged()}reloadSkillRoots(){try{this.syncWatchers()}finally{this.refreshAgentStoreSkills()}}async agentStoreSkillsSettled(){for(let e=this.agentStoreWalk;void 0!==e;e=this.agentStoreWalk)await e}syncWatchers(){const e=this.computeFoldersToWatch(),t=new Set(this.foldersToWatch),r=new Set(e);this.removeWatchers(this.foldersToWatch.filter((e=>!r.has(e)))),this.setupWatchers(e.filter((e=>!t.has(e)))),this.foldersToWatch=e}isPrunedByExtensibilityScan(e){if(void 0!==this.canvasKitSkillRootDir&&km(e,this.canvasKitSkillRootDir))return!1;const t=e.replace(/\\/g,"/");for(const e of this.foldersToWatch){const r=e.replace(/\\/g,"/");if(t.startsWith(`${r}/`))return t.slice(r.length+1).split("/").slice(0,-1).some((e=>e.startsWith(".")))}return!1}reloadAtPath(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("AgentSkillsCursorRulesService.reloadAtPath")),!1),o=function(e,t,r=s){for(const n of t){const t=r.relative(n,e);if(""!==t&&".."!==t&&!t.startsWith(`..${r.sep}`)&&!r.isAbsolute(t))return r.join(n,t)}return e}(t,this.foldersToWatch),i=o.endsWith("SKILL.md")?o:(0,s.join)(o,"SKILL.md");if(void 0!==this.seededLoaded&&this._loaded===this.seededLoaded&&!this.getAgentStoreSkillRoots().some((e=>dg(i,e))))return void(this.reloadRequestedDuringSeed=!0);if(this.getAgentStoreSkillRoots().some((e=>dg(i,e))))return void this.refreshAgentStoreSkills();if(this.foldersToWatch.some((e=>""===(0,s.relative)(e,o))))return void this.reload(n.ctx);const a=this._loaded,c=(async()=>{const e=await a,{realSkillFilePathsByFullPath:t}=e,r=function(e,t){const r=new Map(e.realSkillFilePathsByFullPath);for(const e of t)r.delete(e);return{rules:e.rules.filter((e=>!t.has(e.fullPath))),agentSkills:e.agentSkills.filter((e=>!t.has(e.fullPath))),realSkillFilePathsByFullPath:r}}(e,new Set([i]));if(this.isIgnoredSkillPath(i)||this.isPrunedByExtensibilityScan(i))return r;const o=t.get(i);if(void 0===o){try{await(0,Co.stat)(i)}catch{return r}return await this.loadAll(n.ctx)}let s;try{s=await(0,Co.realpath)(i)}catch{return await this.loadAll(n.ctx)}if(s!==o)return await this.loadAll(n.ctx);try{return ig(r,{...await async function(e){const t=await ji(e);return{skillFilePath:e,content:t,parsed:eh(t)}}(i),realSkillFilePath:s},this.surface,this.getEnabledSkills()),r}catch{return await this.loadAll(n.ctx)}})().catch(lg("Failed to load Agent Skills at path"));this._loaded=c,this.notifyChanged()}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}async getAllAgentSkills(e){const[t]=await Promise.all([this._loaded,this.awaitAgentStoreSeed()]);return this.withAgentStoreSkills(t).agentSkills}withAgentStoreSkills(e){const t=this.settledAgentStoreSkills?.loaded;if(void 0===t||0===t.realSkillFilePathsByFullPath.size)return e;const r=new Set(e.realSkillFilePathsByFullPath.values()),n={rules:[...e.rules],agentSkills:[...e.agentSkills],realSkillFilePathsByFullPath:new Map(e.realSkillFilePathsByFullPath)},o=new Set;for(const[e,s]of t.realSkillFilePathsByFullPath)n.realSkillFilePathsByFullPath.has(e)||r.has(s)?o.add(e):n.realSkillFilePathsByFullPath.set(e,s);for(const e of t.rules)o.has(e.fullPath)||n.rules.push(e);for(const e of t.agentSkills)o.has(e.fullPath)||n.agentSkills.push(e);return n}refreshAgentStoreSkills(){const e=this.getAgentStoreSkillRoots().filter((e=>""!==e.trim())),t=++this.agentStoreLoadGeneration;var r,n;if(void 0===this.settledAgentStoreSkills||(r=this.settledAgentStoreSkills.roots,n=e,r.length===n.length&&r.every(((e,t)=>e===n[t])))||(this.settledAgentStoreSkills=void 0,this.notifyChanged()),0!==e.length){if(void 0===this.settledAgentStoreSkills){const r=this.seedAgentStoreSkills(e,t).finally((()=>{this.agentStoreSeedInFlight===r&&(this.agentStoreSeedInFlight=void 0)}));this.agentStoreSeedInFlight=r}void 0===this.agentStoreWalk?this.agentStoreWalk=(0,Or.wj)(this.loadAgentStoreSkills(e),3e4,"Agent Store skills walk timed out").then((r=>{t===this.agentStoreLoadGeneration&&(this.settledAgentStoreSkills={roots:e,loaded:r},this.notifyChanged(),(r.rules.length>0||r.agentSkills.length>0)&&this.persistCatalog(ug(this.surface,e),r))}),(e=>{ag("Failed to load Agent Store skills: %O",e)})).finally((()=>{this.agentStoreWalk=void 0,this.agentStoreLoadRequestedWhileInFlight&&(this.agentStoreLoadRequestedWhileInFlight=!1,this.refreshAgentStoreSkills())})):this.agentStoreLoadRequestedWhileInFlight=!0}}async seedAgentStoreSkills(e,t){const r=await this.readCatalog(ug(this.surface,e));void 0!==r&&t===this.agentStoreLoadGeneration&&void 0===this.settledAgentStoreSkills&&(this.settledAgentStoreSkills={roots:e,loaded:r},this.notifyChanged())}async loadAgentStoreSkills(e){const t=cg(),r=(await Promise.all(e.map((e=>Gm(e))))).flat().filter((e=>!wm(e))),n=await Promise.all(r.map((e=>Km(e)))),o=new Set;for(const e of n)o.has(e.realSkillFilePath)||(o.add(e.realSkillFilePath),ig(t,e,this.surface,this.getEnabledSkills()));return t}notifyChanged(){for(const e of Array.from(this.onChangeCallbacks))e()}onDidChangeSkills(e){return this.onDidChangeRules(e)}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}dispose(){for(const e of this.watchersByFolder.values())e();this.watchersByFolder.clear()}async loadAll(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("AgentSkillsCursorRulesService.loadAll")),!1);await this.waitBeforeSkillLoad();const o=[],s=[],i=new Map,a=Promise.all(this.nestedExtensibilityEntries.map(((e,r)=>(t?.[r]??e.discover(n.ctx)).catch((e=>{ag("Failed to discover nested agent skills: %O",e)}))))),c=new Set(this.getAgentStoreSkillRoots()),l=await Promise.all(this.foldersToWatch.filter((e=>!c.has(e))).map((async e=>{const t=(await Gm(e)).filter((e=>!this.isIgnoredSkillPath(e)));return Promise.all(t.map((e=>Km(e))))}))),u=new Set;for(const e of l)for(const t of e)if(!u.has(t.realSkillFilePath))if(u.add(t.realSkillFilePath),"error"in t)i.set(t.skillFilePath,t.realSkillFilePath),sg({rules:o,agentSkills:s,skillFilePath:t.skillFilePath,errorMessage:t.error});else{if(Ym(t.parsed,this.surface,this.getEnabledSkills()))continue;i.set(t.skillFilePath,t.realSkillFilePath),o.push(ng(t)),tg(t.parsed)||s.push(og(t))}const d=(await a).flatMap((e=>e?.skills??[])).filter((e=>!wm(e))),h=await Promise.all(d.map((e=>ts(e)))),p=[];for(const[e,t]of d.entries()){const r=h[e];u.has(r)||(u.add(r),p.push(t))}const f=await Promise.all(p.map((e=>Km(e))));for(const e of f)if("error"in e)i.set(e.skillFilePath,e.realSkillFilePath),sg({rules:o,agentSkills:s,skillFilePath:e.skillFilePath,errorMessage:e.error});else{if(Ym(e.parsed,this.surface,this.getEnabledSkills()))continue;i.set(e.skillFilePath,e.realSkillFilePath),o.push(ng(e)),tg(e.parsed)||s.push(og(e))}return n.span.setAttribute("agent_skills.total",o.length),n.span.setAttribute("agent_skills_proto.total",s.length),{rules:o,agentSkills:s,realSkillFilePathsByFullPath:i}}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}}function wg(e){let t;switch(e.type){case"global":t=new Vr.f5({type:{case:"global",value:new Vr.i9}});break;case"fileGlobbed":t=new Vr.f5({type:{case:"fileGlobbed",value:new Vr.uT({globs:e.globs??[]})}});break;case"agentFetched":t=new Vr.f5({type:{case:"agentFetched",value:new Vr.Xo({description:eg(e.description??"")})}});break;case"manuallyAttached":t=new Vr.f5({type:{case:"manuallyAttached",value:new Vr._u}});break;default:e.type,t=new Vr.f5({type:{case:"manuallyAttached",value:new Vr._u}})}return new Vr.DX({fullPath:e.fullPath,content:e.content,type:t,gitRemoteOrigin:e.gitRemoteOrigin,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,environments:e.environments??[],disabledEnvironments:e.disabledEnvironments??[],scopedTo:[]})}class yg{constructor(e,t,r,n){this.getImportSettings=t,this.pluginsService=n,this._rules=Promise.resolve([]),this._agentSkills=Promise.resolve([]),this._lastLoaded={rules:[],agentSkills:[]},this._loadGeneration=0,this.onChangeCallbacks=new Set,this.currentImportSettings=this.getImportSettings();const o=performance.now();this.startLoad(e,!1,(t=>{try{Hm.info(e,"CursorPluginsAgentSkillsService load completed",{durationMs:Math.round(performance.now()-o),ruleCount:t.rules.length,skillCount:t.agentSkills.length})}catch{}}))}startLoad(e,t,r){const n=++this._loadGeneration,o=this.loadAll(e,t).catch((e=>((0,zs.debuglog)("cursor-plugins-agent-skills")("Failed to load Cursor Plugins Agent Skills: %s",e instanceof Error?e.message:String(e)),{rules:[],agentSkills:[]}))).then((e=>(n===this._loadGeneration&&(this._lastLoaded=e,r?.(e)),e))),s=()=>(o.then((e=>{n===this._loadGeneration&&(this._rules=Promise.resolve(e.rules),this._agentSkills=Promise.resolve(e.agentSkills),this.notifyChange())})),this._lastLoaded),i=void 0!==this._overBudgetLoad?Promise.resolve(s()):(0,Or.wj)(o,5e3,"Cursor plugin load did not finish within the rules wait budget").catch((t=>(Hm.warn(e,"Serving rules without plugin primitives while plugins load",{error:t instanceof Error?t.message:String(t),waitMs:5e3}),this._overBudgetLoad=o,o.then((()=>{this._overBudgetLoad===o&&(this._overBudgetLoad=void 0)})),s())));this._rules=i.then((e=>e.rules)),this._agentSkills=i.then((e=>e.agentSkills))}notifyChange(){for(const e of Array.from(this.onChangeCallbacks))e()}async getAllCursorRules(e){return await this._rules}async getAllAgentSkills(e){return await this._agentSkills}reload(e){const t=this.getImportSettings();this.currentImportSettings=t,this.startLoad(e,!0),this.notifyChange()}onDidChangeRules(e){return this.onChangeCallbacks.add(e),()=>{this.onChangeCallbacks.delete(e)}}onDidChangeSkills(e){return this.onDidChangeRules(e)}dispose(){this.onChangeCallbacks.clear()}async loadAll(e,t=!1){const r={stack:[],error:void 0,hasError:!1};try{const n=Bm(r,(0,$.VI)(e.withName("CursorPluginsAgentSkillsService.loadAll")),!1),o=[],i=[];try{let e=t?await this.pluginsService.reload():await this.pluginsService.getAllEnabledPlugins();this.currentImportSettings.importThirdPartyPlugins||(e=e.filter((e=>"claude-plugin"!==e.identifier.source))),n.span.setAttribute("cursor_plugins.loaded",e.length);const r=function(e){return im(e,(e=>e.skills))}(e),a=function(e){return im(e,(e=>e.rules))}(e);for(const e of[...r,...a])o.push(wg(e));for(const t of e){const e=`plugin:${lf(t.identifier)}`,r=uf(t.identifier),n=df(t.identifier),o=hf(t.identifier),a=pf(t.identifier);for(const c of t.skills){if(!0===c.alwaysApply)continue;let l=!1;if(c.content?.includes("disable-model-invocation"))try{l=!0===eh(c.content).data?.["disable-model-invocation"]}catch{}i.push(new am.N({fullPath:(0,s.join)(t.installPath,c.path),content:c.content,description:eg(c.description??""),environments:c.environments??[],disabledEnvironments:c.disabledEnvironments??[],gitRemoteOrigin:e,plugin:r,marketplace:n,pluginId:o,marketplaceId:a,disableModelInvocation:l}))}}}catch(e){n.span.setAttribute("cursor_plugins.error",String(e))}return n.span.setAttribute("cursor_plugins.total",o.length),n.span.setAttribute("cursor_plugins_proto.total",i.length),{rules:o,agentSkills:i}}catch(e){r.error=e,r.hasError=!0}finally{Wm(r)}}}var vg=r("../proto/dist/generated/agent/v1/subagents_pb.js");const bg=(0,zs.debuglog)("local-subagents");class Sg{async getAllSubagents(){return[]}async reload(){return[]}}function kg(e){return"true"===(e??"").trim().toLowerCase()}function _g(e){const t=e.match(/^---\s*\n([\s\S]*?)\n---\s*\n?([\s\S]*)$/m);if(!t)return null;const r=t[1]??"",n=(t[2]??"").trim();if(0===n.length)return null;const o={};for(const e of r.split("\n")){const t=e.trim();if(0===t.length||t.startsWith("#"))continue;const r=t.indexOf(":");if(-1===r)continue;const n=t.slice(0,r).trim().toLowerCase(),s=t.slice(r+1).trim();0!==n.length&&(o[n]=s)}const s=o.name??"",i=o.description,a=o.model,c=kg(o["force-default-model"]),l="true"===(o.readonly??"").trim().toLowerCase()?vg.b$.READONLY:vg.b$.DEFAULT,u=kg(o.background??o.is_background),d=o.tools;return{name:s,description:i,tools:void 0!==d&&d.length>0?d.split(",").map((e=>e.trim())).filter((e=>e.length>0)):[],model:a,forceDefaultModel:c,prompt:n,permissionMode:l,isBackground:u}}function Cg(e){const t=(0,s.extname)(e).toLowerCase();return".md"===t||".mdc"===t||".markdown"===t}function Eg(e){return(0,s.basename)(e,(0,s.extname)(e)).replace(/[\s_]+/g,"-")}async function xg(e,t){return await Om({rootDir:e,includeFile:Cg,containmentRootDir:t})}class Pg{constructor(e,t,r="workspace",n=!1,o){this.workspacePath=e,this.cursorAgentsSource=r,this.allowExternalAgentSymlinks=n,this.ignoreService=o,this.getThirdPartyExtensibilityEnabled=t??(()=>!0),this.subagents=this.load().catch((e=>(bg("Failed to load subagents: %o",e),[])))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents=this.load().catch((e=>(bg("Failed to load subagents: %o",e),[]))),await this.subagents}computeAgentsDirs(){const e=(0,s.resolve)(this.workspacePath),t=[{dirPath:(0,s.join)(e,".cursor","agents"),source:this.cursorAgentsSource}];return this.getThirdPartyExtensibilityEnabled()&&(t.push({dirPath:(0,s.join)(e,".claude","agents"),source:"claude"}),t.push({dirPath:(0,s.join)(e,".grok","agents"),source:"grok"})),t}async load(){const e=this.computeAgentsDirs(),t=[];for(const{dirPath:r,source:n}of e){const e=await xg(r,this.allowExternalAgentSymlinks?void 0:this.workspacePath);for(const r of e){const e=(0,s.basename)(r);try{if(!(await(0,Co.stat)(r)).isFile())continue}catch(e){bg("Skipping subagent file %s due to stat error: %o",r,e);continue}try{const o=_g(await ji(r));if(!o)continue;t.push(new vg.zz({fullPath:r,name:o.name||Eg(e),description:o.description??"",tools:o.tools,model:o.model??"inherit",forceDefaultModel:o.forceDefaultModel,prompt:o.prompt,permissionMode:o.permissionMode,isBackground:o.isBackground,source:n}))}catch(e){bg("Failed to parse subagent file %s: %o",r,e)}}}return t}}const Rg=new Set(["claude-code-tutor"]);class Ig{constructor(e){this.subagentsServices=e}async getAllSubagents(){const e=await Promise.all(this.subagentsServices.map((e=>e.getAllSubagents().catch((e=>(bg("Failed to load subagents from merged service: %o",e),[])))))),t=new Map;for(const r of e)for(const e of r)Rg.has(e.name)||t.has(e.name)||t.set(e.name,e);return Array.from(t.values())}async reload(){return await Promise.all(this.subagentsServices.map((e=>e.reload()))),this.getAllSubagents()}}class Tg{constructor(e,t){this.getSettings=e,this.pluginsService=t,this._subagentsCache=[],this._loadId=0,this._loadPromise=null,this._loadedOnce=!1,this.runLoadInBackground()}async getAllSubagents(){return this._loadPromise&&await this._loadPromise,this._loadedOnce||await this.reload(),[...this._subagentsCache]}async reload(){return this.runLoadInBackground(!0),this._loadPromise&&await this._loadPromise,this._subagentsCache}runLoadInBackground(e=!1){const t=++this._loadId;this._loadPromise=this.load(e).then((e=>{t===this._loadId&&(this._subagentsCache=e,this._loadedOnce=!0)})).catch((e=>{t===this._loadId&&(bg("Failed to load Cursor plugin subagents: %o",e),this._subagentsCache=[],this._loadedOnce=!0)})).finally((()=>{t===this._loadId&&(this._loadPromise=null)}))}dispose(){}async load(e){const t=[];try{let r=e?await this.pluginsService.reload():await this.pluginsService.getAllEnabledPlugins();this.getSettings().importThirdPartyPlugins||(r=r.filter((e=>"claude-plugin"!==e.identifier.source)));const n=function(e,t={stripModel:!0,stripTools:!0}){const r=[];for(const n of e){const e=uf(n.identifier),o=df(n.identifier),i=hf(n.identifier),a=pf(n.identifier);for(const c of n.agents){const l=sm(c,t),u=(0,s.join)(n.installPath,l.path);r.push({name:l.name,description:l.description??"",prompt:l.prompt,fullPath:u,permissionMode:"readonly"===l.permissionMode?"readonly":"default",plugin:e,marketplace:o,pluginId:i,marketplaceId:a})}}return r}(r,{stripModel:!0,stripTools:!0});for(const e of n){const r="readonly"===e.permissionMode?vg.b$.READONLY:vg.b$.DEFAULT;t.push(new vg.zz({name:e.name,description:e.description,tools:[],model:"inherit",prompt:e.prompt,fullPath:e.fullPath,permissionMode:r,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,source:"plugin"}))}}catch{}return t}}class Ag{constructor(e){this.pastElements=[],this.closed=!1,this.forks=new Set,this.consume(e)}async consume(e){try{for await(const t of e){this.pastElements.push(t);const e=[];for(const r of this.forks)e.push(r.write(t).catch((()=>{})));await Promise.allSettled(e)}}catch(e){this.error=e instanceof Error?e:new Error(String(e))}finally{this.closed=!0;for(const e of this.forks)this.error?e.throw(this.error):e.close();this.forks.clear()}}fork(){if(this.closed){const e=this.pastElements,t=this.error;return async function*(){for(const t of e)yield t;if(t)throw t}()}const e=(0,h.Jt)(),t=this.pastElements.slice();this.forks.add(e);const r=this;return async function*(){for(const e of t)yield e;try{for await(const t of e)yield t}finally{r.forks.delete(e)}}()}}function $g(e,t){return`${e}:${(0,bo.createHash)("sha256").update(t.toBinary()).digest("hex")}`}function Mg(e){return new Eo.q({max:e?.max??10,ttl:e?.ttl})}function Dg(e,t,r=Mg(t)){return{async execute(t,n,o){if(!o?.execId)return e.execute(t,n,o);const s=$g(o.execId,n),i=r.get(s);if(void 0!==i)return i;const a=await e.execute(t,n,o);return r.set(s,a),a}}}var Og=r("../proto/dist/generated/agent/v1/computer_use_tool_pb.js");r("node:readline"),Error;var Fg=r("node:timers/promises");const Ng=ou.execFile;function Lg(e,t,r){return new Promise(((n,o)=>{r?.signal?.throwIfAborted();const s={timeout:r?.timeoutMs??3e4,env:r?.env?{...process.env,...r.env}:void 0,signal:r?.signal};(0,su.D9)(Ng,e,t.map(String),{...s,encoding:"utf8"},((e,t)=>{e?o(e):n(t)}))}))}Og.w3.UNSPECIFIED,Og.w3.LEFT,Og.w3.MIDDLE,Og.w3.RIGHT,Og.w3.BACK,Og.w3.FORWARD,Og.Dh.UNSPECIFIED,Og.Dh.UP,Og.Dh.DOWN,Og.Dh.LEFT,Og.Dh.RIGHT;const jg=(0,zs.promisify)(ou.execFile);function Ug(e){const t=e.lastIndexOf(":");if(-1===t)throw new Error(`Invalid X11 display string: ${e} (missing ':')`);const r=e.slice(t+1).split(".")[0],n=parseInt(r,10);if(!Number.isFinite(n)||n<0)throw new Error(`Invalid X11 display number in: ${e} (parsed: ${r})`);return n}function Bg(e,t,r,n){const o=function(e={}){const t=e.displayWidth??1920,r=e.displayHeight??1200,n=e.apiWidth??1280;return{width:n,height:Math.round(n*r/t)}}({displayWidth:e,displayHeight:t,apiWidth:r});return{display:{width:e,height:t},api:{width:o.width,height:n??o.height}}}async function Wg(e){const{stdout:t}=await(0,su.D9)(jg,"xrandr",["--display",e],{timeout:5e3,encoding:"utf8"}),r=function(e){let t,r,n;for(const o of e.split("\n"))if(o.includes("*")){const e=o.trim().match(/^(\d+)x(\d+)/);e&&(t=parseInt(e[1],10),r=parseInt(e[2],10));const s=o.match(/(\d+(?:\.\d+)?)\*(?:\+)?/);if(s){const e=parseFloat(s[1]);e>0&&e<=500&&(n=Math.round(e))}if(t&&r)break}if(!t||!r){const n=e.match(/current\s+(\d+)\s*x\s*(\d+)/i);n&&(t=parseInt(n[1],10),r=parseInt(n[2],10))}if(!t||!r)throw new Error(`Could not detect display resolution from xrandr output.\nExpected a line with '*' indicating active mode, or 'current WxH'.\nxrandr output:\n${e}`);return n||(n=60),{width:t,height:r,refreshRate:n}}(t);return{display:r,resolution:Bg(r.width,r.height),resolutionString:`${r.width}x${r.height}`}}Og.w3.UNSPECIFIED,Og.w3.LEFT,Og.w3.MIDDLE,Og.w3.RIGHT,Og.w3.BACK,Og.w3.FORWARD,Og.Dh.UNSPECIFIED,Og.Dh.UP,Og.Dh.DOWN,Og.Dh.LEFT,Og.Dh.RIGHT;const Hg={pattern:"[\\w-]{1,64}",next:e=>e},qg={pattern:"[0-9a-f-]{36}",next:()=>bo.randomUUID()},zg={pattern:"webp",next:()=>"webp"},Gg={native:[qg,zg],agent:[Hg,qg,zg],legacyNative:[qg,{pattern:"png",next:()=>"png"}]};new RegExp(`^(?:${Object.values(Gg).map((e=>e.map((e=>e.pattern)).join("\\."))).join("|")})$`),new RegExp(`^${Hg.pattern}$`),Og.Z8.NATIVE_X11,Og.Z8.XDOTOOL,(0,u.v5)("computer_use.session.duration_ms",{description:"Duration of computer-use session in milliseconds"}),(0,u.v5)("computer_use.session.action_count",{description:"Number of actions executed in a computer-use session"}),(0,u.Pu)("computer_use.session.result",{description:"Result status of computer-use session",labelNames:["outcome"]}),(0,u.Pu)("computer_use.session.action_kind",{description:"Requested computer-use actions by bounded kind",labelNames:["kind"]}),(0,l.h)("computer-use"),Math.floor(35927136),["Skip changes that cannot affect what runs in any deployed environment:","- documentation-only changes (Markdown, docs sites, code comments, changelogs)","- formatting, lint, or typo fixes with no behavior change","- test-only changes (test files, fixtures, snapshots)","Monitor everything else, including dependency bumps, configuration, and infrastructure changes."].join("\n"),Error,(0,u.Pu)("computer_use.desktop_lease.check",{description:"Desktop lease action-gate outcomes",labelNames:["outcome","reason"]});var Vg=r("../proto/dist/runtime/compact.js");Vg.HL;var Kg=(0,Vg.QT)(we.proto3,"agent.v1.","CursorType",[[0,"UNSPECIFIED"],[1,"ARROW"],[2,"POINTER"],[3,"TEXT"],[4,"WAIT"],[5,"CROSSHAIR"],[6,"MOVE"],[7,"RESIZE_NS"],[8,"RESIZE_EW"],[9,"RESIZE_NWSE"],[10,"RESIZE_NESW"],[11,"NOT_ALLOWED"],[12,"GRAB"],[13,"GRABBING"]],1);we.proto3,we.proto3,we.proto3,we.proto3;class Jg{constructor(e){this.config=e;const t=e.display.width/e.display.height,r=e.api.width/e.api.height;if(Math.abs(t-r)>.02)throw new Error(`Aspect ratio mismatch: display=${t.toFixed(3)}, api=${r.toFixed(3)}`);this.xScaleUp=e.display.width/e.api.width,this.yScaleUp=e.display.height/e.api.height,this.xScaleDown=e.api.width/e.display.width,this.yScaleDown=e.api.height/e.display.height}apiToDisplay(e,t){return{x:Math.round(e*this.xScaleUp),y:Math.round(t*this.yScaleUp)}}displayToApi(e,t){return{x:Math.round(e*this.xScaleDown),y:Math.round(t*this.yScaleDown)}}get apiWidth(){return this.config.api.width}get apiHeight(){return this.config.api.height}get displayWidth(){return this.config.display.width}get displayHeight(){return this.config.display.height}}const Zg={left_ptr:Kg.ARROW,arrow:Kg.ARROW,default:Kg.ARROW,top_left_arrow:Kg.ARROW,hand:Kg.POINTER,hand1:Kg.POINTER,hand2:Kg.POINTER,pointer:Kg.POINTER,pointing_hand:Kg.POINTER,xterm:Kg.TEXT,ibeam:Kg.TEXT,text:Kg.TEXT,watch:Kg.WAIT,wait:Kg.WAIT,progress:Kg.WAIT,left_ptr_watch:Kg.WAIT,crosshair:Kg.CROSSHAIR,cross:Kg.CROSSHAIR,tcross:Kg.CROSSHAIR,move:Kg.MOVE,fleur:Kg.MOVE,size_all:Kg.MOVE,sb_v_double_arrow:Kg.RESIZE_NS,v_double_arrow:Kg.RESIZE_NS,ns_resize:Kg.RESIZE_NS,row_resize:Kg.RESIZE_NS,top_side:Kg.RESIZE_NS,bottom_side:Kg.RESIZE_NS,sb_h_double_arrow:Kg.RESIZE_EW,h_double_arrow:Kg.RESIZE_EW,ew_resize:Kg.RESIZE_EW,col_resize:Kg.RESIZE_EW,left_side:Kg.RESIZE_EW,right_side:Kg.RESIZE_EW,top_left_corner:Kg.RESIZE_NWSE,bottom_right_corner:Kg.RESIZE_NWSE,nwse_resize:Kg.RESIZE_NWSE,size_fdiag:Kg.RESIZE_NWSE,top_right_corner:Kg.RESIZE_NESW,bottom_left_corner:Kg.RESIZE_NESW,nesw_resize:Kg.RESIZE_NESW,size_bdiag:Kg.RESIZE_NESW,not_allowed:Kg.NOT_ALLOWED,no_drop:Kg.NOT_ALLOWED,forbidden:Kg.NOT_ALLOWED,circle:Kg.NOT_ALLOWED,grab:Kg.GRAB,openhand:Kg.GRAB,grabbing:Kg.GRABBING,closedhand:Kg.GRABBING};class Xg{constructor(e){this.events=[],this.recordingStartTime=0,this.lastKnownPosition={x:0,y:0},this.isRunning=!1,this.pending=Promise.resolve();const t=e.displayNum??1;this.env={DISPLAY:`:${t}`},this.scaler=new Jg(e.resolution)}async start(){this.events=[],this.recordingStartTime=Date.now(),this.isRunning=!0,this.pending=Promise.resolve();try{this.lastKnownPosition=await this.captureCurrentPosition()}catch{this.lastKnownPosition={x:Math.floor(this.scaler.apiWidth/2),y:Math.floor(this.scaler.apiHeight/2)}}}logEvent(e,t,r){if(!this.isRunning)return;const n={...this.lastKnownPosition},o=this.getExpectedPositionAfterAction(e,n);this.lastKnownPosition=o;const s=async()=>{let s,i;try{[s,i]=await Promise.all([this.captureCurrentPosition(),this.detectCursorType()]),this.lastKnownPosition=s}catch{s=o,i=Kg.ARROW}const a={executionTimestampMs:r-this.recordingStartTime,action:e,commandDurationMs:r-t,positionBefore:n,positionAfter:s,cursorTypeAfter:i};this.events.push(a)};this.pending=this.pending.then((()=>s())).catch((()=>{}))}async stop(){return this.isRunning=!1,await this.pending,[...this.events]}getEvents(){return[...this.events]}getRecordingStartTime(){return this.recordingStartTime}getIsRunning(){return this.isRunning}async captureCurrentPosition(){const e=await Lg("xdotool",["getmouselocation","--shell"],{env:this.env}),t=e.match(/X=(\d+)/),r=e.match(/Y=(\d+)/);if(!t||!r)throw new Error(`Failed to parse cursor position: ${e}`);const n=parseInt(t[1],10),o=parseInt(r[1],10);return this.scaler.displayToApi(n,o)}async detectCursorType(){try{const e=(await Lg("xdotool",["getmouselocation","--shell"],{env:this.env})).match(/CURSOR=(\S+)/i);if(e){const t=e[1].toLowerCase();return Zg[t]??Kg.ARROW}try{const e=await Lg("xprop",["-root","_XSERVER_CURSOR"],{env:this.env,timeoutMs:500});for(const[t,r]of Object.entries(Zg))if(e.toLowerCase().includes(t))return r}catch{}return Kg.ARROW}catch{return Kg.ARROW}}getExpectedPositionAfterAction(e,t){const r=e.action;if(!r)return t;switch(r.case){case"mouseMove":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}case"click":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}case"drag":{const e=r.value.path;if(e.length>0){const t=e[e.length-1];return{x:t.x,y:t.y}}break}case"scroll":{const e=r.value.coordinate;if(e)return{x:e.x,y:e.y};break}}return t}}(0,l.h)("computer-use-lazy");var Qg=r("node:net");function Yg(e){return!!e.includes(o.homedir())||e.includes("node_modules")||e.includes("Application Support")||/\.wasm\b/.test(e)||/(?:^|[\s'`"(=])(?:\/|\.{1,2}\/)/.test(e)||/(?:^|[\s'`"(=:])(?:[A-Za-z]:[\\/]|\\\\)/.test(e)||/\bS-1-5-21(?:-\d+){3,}/i.test(e)}class ew extends Error{constructor(e){super(e),this.name="MacRPCProtocolError"}}const tw=je.object({rpcSocketPath:je.string().min(1).optional(),appControlSocketPath:je.string().min(1).optional(),pid:je.number().int().positive().optional().catch(void 0),protocolMajor:je.number().int().positive().optional().catch(void 0)}).passthrough(),rw=je.object({data:je.string(),mimeType:je.string().min(1)}).strip(),nw=je.object({message:je.string(),screenshot:rw.optional(),screenshotBefore:rw.optional(),structuredContent:je.unknown().optional(),isError:je.boolean()}).strip(),ow=je.object({accessibilityTrusted:je.boolean(),screenRecordingGranted:je.boolean()}).strip(),sw=je.union([je.object({id:je.number().int(),result:nw,ok:je.never().optional(),error:je.never().optional(),errorCode:je.never().optional(),permissionStatus:je.never().optional(),sessionId:je.never().optional()}).strip(),je.object({id:je.number().int(),sessionId:je.string().min(1),ok:je.literal(!0).optional(),result:je.never().optional(),error:je.never().optional(),errorCode:je.never().optional(),permissionStatus:je.never().optional()}).strip(),je.object({id:je.number().int(),ok:je.literal(!0),result:je.never().optional(),error:je.never().optional(),errorCode:je.never().optional(),permissionStatus:je.never().optional(),sessionId:je.never().optional()}).strip(),je.object({id:je.number().int().nullable().optional(),error:je.string().min(1),errorCode:je.string().min(1).optional(),result:je.never().optional(),ok:je.never().optional(),permissionStatus:je.never().optional(),sessionId:je.never().optional()}).strip(),je.object({id:je.number().int(),permissionStatus:ow,result:je.never().optional(),ok:je.never().optional(),error:je.never().optional(),errorCode:je.never().optional(),sessionId:je.never().optional()}).strip()]);function iw(e,t){try{return JSON.parse(e)}catch{throw new ew(`local-cua ${t} is not valid JSON`)}}const aw={responseMaxBytes:33554432,parseServiceState(e){const t=tw.safeParse(iw(e,"service state")),r=t.success?t.data.rpcSocketPath??t.data.appControlSocketPath:void 0;if(!t.success||void 0===r)throw new ew("local-cua service state is malformed");return{...t.data,rpcSocketPath:r}},parseResponse({line:e,expectedID:t}){const r=sw.safeParse(iw(e.toString("utf8"),"RPC response"));if(!r.success)throw new ew("local-cua RPC response is malformed");if(void 0!==r.data.id&&null!==r.data.id&&r.data.id!==t)throw new ew("local-cua RPC response ID did not match");return r.data}};class cw extends Error{constructor(e,t){super(e),this.name="MacComputerUseRPCError",this.code=t?.code,this.userFacing=!0===t?.userFacing,this.tool=t?.tool}}function lw(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:e instanceof Error?Yg(e.message)?e.name:e.message.length>0?`${e.name}: ${e.message}`:e.name:"unknown"}const uw=new Map([["co.anysphere.cursor-computer-use","cursor-computer-use"],["co.anysphere.cursor-computer-use.dev","cursor-computer-use-dev"]]),dw=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;class hw{constructor(e){this.mode=e}static isInstalled(){if((0,xo.existsSync)(hw.serviceExecutablePath()))return!0;let e;try{e=aw.parseServiceState((0,xo.readFileSync)(hw.serviceStatePath(),"utf8"))}catch{return!1}return void 0===e.pid||hw.isProcessAlive(e.pid)}static async runningHelperPid(){const e=await hw.readServiceState(),t=e?.pid;return void 0!==t&&hw.isProcessAlive(t)?t:void 0}static isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}static isExitedIncompatibleHelper(e){return void 0!==e.protocolMajor&&e.protocolMajor!==hw.protocolMajor&&void 0!==e.pid&&!hw.isProcessAlive(e.pid)}screenshot(e){return this.callTool(e,"computer_use_screenshot",{})}click(e,t){return this.callTool(e,"computer_use_click",{method:"coordinate",...void 0!==t.coordinate&&{x:t.coordinate.x,y:t.coordinate.y},button:t.button,count:t.count,modifier_keys:t.modifierKeys})}scroll(e,t){return this.callTool(e,"computer_use_scroll",{x:t.coordinate?.x,y:t.coordinate?.y,direction:t.direction,amount:t.amount,modifier_keys:t.modifierKeys})}move(e,t){return this.callTool(e,"computer_use_mouse_move",{x:t.x,y:t.y})}mouseButton(e,t){return this.callTool(e,"computer_use_mouse_button",{button:t.button,action:t.action})}drag(e,t){return this.callTool(e,"computer_use_drag",{button:t.button,path:t.path,modifier_keys:t.modifierKeys})}typeText(e,t){return this.callTool(e,"computer_use_typing",{value:t})}pressKey(e,t){return this.callTool(e,"computer_use_press_key",{key:t.key,hold_duration_ms:t.holdDurationMs})}checkPermissions(e){return this.callTool(e,"computer_use_check_permissions",{})}async startControl(e){if("remote"!==this.mode||void 0!==this.activeSessionId)return;hw.throwIfAborted(e.signal);const t=(0,bo.randomUUID)(),r=await this.sendWithRelaunchRetry(e,(()=>({id:hw.requestID,method:"control/start",requestID:t,mode:this.mode})),"control/start");if(void 0!==r.error)throw hw.rpcError(r);if(void 0===r.sessionId)throw new cw("local-cua control/start returned no session");this.activeSessionId=r.sessionId}async releaseControl(e){const t=this.activeSessionId;if(void 0!==t){this.activeSessionId=void 0;try{const e=await hw.readServiceState();if(void 0===e)return;const r=await hw.sendOnce(hw.socketPathFrom(e),{id:hw.requestID,method:"control/release",requestID:(0,bo.randomUUID)(),mode:this.mode,sessionId:t},hw.defaultCallTimeoutMs);if(void 0!==r.error)throw hw.rpcError(r)}catch(t){hw.logger.warn(e,"local-cua control release failed",{error:lw(t)})}}}async callTool(e,t,r){hw.throwIfAborted(e.signal);const n=hw.defaultCallTimeoutMs,o=await this.sendWithRelaunchRetry(e,(()=>{const e=Date.now()/1e3,o=this.activeSessionId;return{id:hw.requestID,method:"tools/call",requestID:(0,bo.randomUUID)(),name:t,arguments:r,timeoutSeconds:n/1e3,startedAtEpochSeconds:e,deadlineEpochSeconds:e+n/1e3,mode:this.mode,...void 0!==o&&{sessionId:o}}}),t);if(void 0!==o.error)throw hw.rpcError(o,t);const s=o.result;if(void 0===s)throw new cw(`local-cua tool ${t} returned no result`,{tool:t});if(s.isError){const e=s.message.trim();throw new cw(e.length>0?e:`local-cua tool ${t} reported an error`,{tool:t,userFacing:e.length>0})}return s}async sendWithRelaunchRetry(e,t,r){const n=hw.defaultCallTimeoutMs,o=await this.ensureSocketPath(e);hw.throwIfAborted(e.signal);try{return await hw.sendOnce(o,t(),n,e.signal)}catch(o){if(!hw.isPreDeliveryConnectionError(o))throw o;hw.logger.warn(e,"local-cua callTool failed; relaunching and retrying",{tool:r,error:hw.spawnErrorCode(o)});const s=await this.ensureSocketPath(e,!0);return hw.throwIfAborted(e.signal),void 0!==this.activeSessionId&&(this.activeSessionId=void 0,await this.startControl(e)),await hw.sendOnce(s,t(),n,e.signal)}}static rpcError(e,t){return new cw(e.error,{code:e.errorCode,userFacing:!0,tool:t})}async ensureSocketPath(e,t=!1){if(hw.throwIfAborted(e.signal),!t){const e=await hw.readServiceState();if(e&&!hw.isExitedIncompatibleHelper(e))return hw.socketPathFrom(e)}await this.launchAndWait(e);const r=await hw.readServiceState();if(!r)throw new cw("local-cua sidecar did not publish service.json after launch");return hw.socketPathFrom(r)}static setLaunchGuard(e){hw.launchGuard=e}async launchAndWait(e){const t=hw.serviceAppPath(),r=hw.launchGuard,n=()=>this.launchAppAndWait(e,t);await(void 0===r?n():r(t,n,e.signal))}async launchAppAndWait(e,t){hw.logger.info(e,"launching local-cua sidecar",hw.sidecarLaunchLogFields(t)),"1"===process.env[hw.directLaunchEnv]?await hw.spawnSidecarProcess(e,hw.serviceExecutablePath(),[],{detached:!0}):await hw.spawnSidecarProcess(e,"/usr/bin/open",["-g",t]);const r=Date.now()+hw.launchReadyTimeoutMs;for(;Date.now()0?e:s.join(o.homedir(),...hw.sharedInstallRelativePath,`${hw.serviceAppBundleName}.app`)}static helperIdentity(){const e=hw.serviceAppPath(),t=process.env[hw.appSupportOverrideEnv],r=`${e}\0${t??""}`,n=hw.identityCache;if(n?.key===r)return n.identity;const i=function(e){let t;try{t=(0,xo.readFileSync)(s.join(e,"Contents","Info.plist"),"utf8")}catch{return{}}const r=e=>{const r=new RegExp(`${e}\\s*([^<]*)`).exec(t)?.[1];return void 0!==r&&dw.test(r.trim())?r.trim():void 0};return{executableName:r("CFBundleExecutable"),bundleIdentifier:r("CFBundleIdentifier")}}(e),a=s.join(e,"Contents","MacOS",i.executableName??hw.productionExecutableName),c={appPath:e,executablePath:a,appSupportDirectory:void 0!==t&&t.length>0?t:s.join(o.homedir(),"Library","Application Support",(void 0===i.bundleIdentifier?void 0:uw.get(i.bundleIdentifier))??hw.appSupportFolder)};return(0,xo.existsSync)(a)&&(hw.identityCache={key:r,identity:c}),c}static sidecarLaunchLogFields(e){const t=`${hw.serviceAppBundleName}.app`;return{appName:s.basename(e)===t?t:"custom",appPathHash:(0,bo.createHash)("sha256").update(e).digest("hex"),usingOverride:Boolean(process.env[hw.serviceAppOverrideEnv])}}static spawnErrorCode(e){return lw(e)}static socketError(e){const t=lw(e);return new cw(`local-cua RPC connection failed: ${t}`,{code:t})}static serviceExecutablePath(){return hw.helperIdentity().executablePath}static spawnSidecarProcess(e,t,r,n){return new Promise(((o,s)=>{const i=(0,ou.spawn)(t,[...r],{detached:!0===n?.detached,stdio:"ignore"}),a=e=>{s(new cw(`local-cua sidecar launch failed: ${hw.spawnErrorCode(e)}`))};i.once("error",a),i.once("spawn",(()=>{i.removeListener("error",a),i.on("error",(t=>{hw.logger.warn(e,"local-cua sidecar process error after launch",{error:hw.spawnErrorCode(t)})})),i.unref(),o()}))}))}static async readServiceState(){try{const e=await(0,Co.readFile)(hw.serviceStatePath(),"utf8");return aw.parseServiceState(e)}catch(e){if(e instanceof Error&&"code"in e&&"ENOENT"===e.code)return;if(e instanceof ew)return;throw new cw("local-cua service state could not be read")}}static socketPathFrom(e){if(void 0!==e.protocolMajor&&e.protocolMajor!==hw.protocolMajor)throw new cw(`The running Cursor Computer Use speaks protocol ${e.protocolMajor}, and this Cursor CLI speaks protocol ${hw.protocolMajor}. Update the Cursor CLI.`,{userFacing:!0});return e.rpcSocketPath}static abortError(e){return e.reason instanceof Error?e.reason:new cw("local-cua RPC aborted")}static throwIfAborted(e){if(e.aborted)throw hw.abortError(e)}static sendOnce(e,t,r,n){return n?.aborted?Promise.reject(hw.abortError(n)):new Promise(((o,s)=>{let i=!1,a=[],c=0,l=!1;const u=(0,Qg.createConnection)({path:e}),d=e=>{i||(i=!0,clearTimeout(p),n?.removeEventListener("abort",h),u.destroy(),e())},h=()=>{d((()=>s(void 0===n?new cw("local-cua RPC aborted"):hw.abortError(n))))},p=setTimeout((()=>{d((()=>s(new cw(`local-cua RPC timed out after ${r}ms`))))}),r);n?.addEventListener("abort",h,{once:!0}),n?.aborted?h():(u.on("connect",(()=>{u.write(`${JSON.stringify(t)}\n`,(e=>{null==e?l=!0:d((()=>s(hw.socketError(e))))}))})),u.on("data",(e=>{const t=e.indexOf(10),r=c+(t<0?e.length:t);if(r>aw.responseMaxBytes)return void d((()=>s(new cw("local-cua RPC response exceeded the size limit"))));if(t<0)return a.push(e),void(c+=e.length);a.push(e.subarray(0,t));const n=Buffer.concat(a,r);a=[],c=0;try{const e=aw.parseResponse({line:n,expectedID:hw.requestID});d((()=>o(e)))}catch(e){d((()=>s(e)))}})),u.on("error",(e=>{d(l?()=>s(new cw("local-cua RPC connection failed after request delivery")):()=>s(hw.socketError(e)))})),u.on("close",(()=>{const e=c>0?"local-cua RPC response ended without a newline":l?"local-cua RPC connection closed after request delivery":"local-cua RPC connection closed";d((()=>s(new cw(e))))})))}))}}let pw;function fw(){if(void 0===pw){const e=async function(){const[{createJimp:e},{default:t},{default:n},{default:o,msBmp:s},{default:i},{default:a},{methods:c}]=await Promise.all([Promise.all([r.e(731),r.e(250)]).then(r.bind(r,"../../node_modules/.pnpm/@jimp+core@1.6.0/node_modules/@jimp/core/dist/esm/index.js")),r.e(690).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-png@1.6.0/node_modules/@jimp/js-png/dist/esm/index.js")),r.e(831).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-jpeg@1.6.0/node_modules/@jimp/js-jpeg/dist/esm/index.js")),Promise.all([r.e(731),r.e(284)]).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-bmp@1.6.0/node_modules/@jimp/js-bmp/dist/esm/index.js")),r.e(295).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-gif@1.6.0/node_modules/@jimp/js-gif/dist/esm/index.js")),r.e(181).then(r.bind(r,"../../node_modules/.pnpm/@jimp+js-tiff@1.6.0/node_modules/@jimp/js-tiff/dist/esm/index.js")),r.e(162).then(r.bind(r,"../../node_modules/.pnpm/@jimp+plugin-resize@1.6.0/node_modules/@jimp/plugin-resize/dist/esm/index.js"))]);return e({formats:[t,n,o,s,i,a],plugins:[c]})}().catch((t=>{throw pw===e&&(pw=void 0),t}));pw=e}return pw}hw.logger=(0,l.h)("local-cua:rpc"),hw.serviceAppBundleName="Cursor Computer Use",hw.appSupportFolder="cursor-computer-use",hw.productionExecutableName="CUCursorService",hw.sharedInstallRelativePath=[".cursor","computer-use-sidecar"],hw.appSupportOverrideEnv="CUA_APP_SUPPORT_DIR",hw.serviceAppOverrideEnv="CUA_SERVICE_APP",hw.directLaunchEnv="CUA_DIRECT_LAUNCH",hw.protocolMajor=1,hw.defaultCallTimeoutMs=45e3,hw.launchReadyTimeoutMs=8e3,hw.launchPollIntervalMs=200,hw.requestID=1;var mw=r("node:module");const gw="mac-webp-runtime.cjs";function ww(e){return"function"==typeof e}function yw(e){return"object"==typeof e&&null!==e&&"getFileName"in e&&"function"==typeof e.getFileName}function vw(){const e=(new Error).stack;return Array.isArray(e)?e.filter(yw):[]}let bw,Sw;function kw(){return bw??=(()=>{const e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;const e=vw()[0]?.getFileName();return function(){const e=mw;if("createRequire"in e&&ww(e.createRequire))return e.createRequire;if("default"in e&&"object"==typeof e.default&&null!==e.default&&"createRequire"in e.default&&ww(e.default.createRequire))return e.default.createRequire;throw new Error("node:module createRequire is unavailable")}()("string"==typeof e&&e.length>0?e:(0,s.join)(process.cwd(),"package.json"))}finally{Error.prepareStackTrace=e}})(),bw}function _w(){const e=globalThis.__MAC_WEBP_IMPORT__;return"function"==typeof e?t=>Promise.resolve(e(t)):(Sw??=function(){const e=[],t=new Set,r=r=>{t.has(r)||(t.add(r),e.push(r))};for(const e of function(){const e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;const e=[];for(const t of vw()){const r=t.getFileName();"string"==typeof r&&r.length>0&&e.push(r)}return e}finally{Error.prepareStackTrace=e}}()){const t=(0,s.dirname)((n=e).startsWith("file:")?(0,Ed.fileURLToPath)(n):n);r((0,s.join)(t,gw)),r((0,s.join)(t,"..","..","src","computer-use",gw))}var n;"string"==typeof process.argv[1]&&process.argv[1].length>0&&r((0,s.join)((0,s.dirname)(process.argv[1]),gw)),r((0,s.join)(process.cwd(),"src","computer-use",gw)),r((0,s.join)(process.cwd(),"computer-use",gw));try{const e=(0,s.dirname)(kw().resolve("@anysphere/local-exec/package.json"));r((0,s.join)(e,"src","computer-use",gw)),r((0,s.join)(e,"dist","computer-use",gw))}catch{}for(const t of e)try{const e=kw()(t);if("object"==typeof e&&null!==e&&"importFile"in e&&"function"==typeof e.importFile)return e.importFile.bind(e)}catch{}throw new Error("mac-webp runtime importer was not found next to the bundle")}(),Sw)}function Cw(...e){return t=["@jsquash","webp",...e].join("/"),kw().resolve(t);var t}async function Ew(...e){var t;return await(t=(0,Ed.pathToFileURL)(Cw(...e)).href,_w()(t))}const xw=e=>{let t;return()=>{if(void 0===t){const r=e();r.catch((()=>{t===r&&(t=void 0)})),t=r}return t}},Pw=(xw((async()=>{const e=await Ew("decode.js");return await e.init({wasmBinary:await xo.promises.readFile(Cw("codec","dec","webp_dec.wasm"))}),e})),xw((async()=>{const[e,t,r]=await Promise.all([Ew("utils.js"),Ew("meta.js"),Ew("codec","enc","webp_enc.js")]);return{module:await e.initEmscriptenModule(r.default,void 0,{wasmBinary:await xo.promises.readFile(Cw("codec","enc","webp_enc.wasm"))}),defaultOptions:t.defaultOptions}}))),Rw="image/png",Iw={async normalize(e){if(e.mimeType!==Rw)throw new Error(`Mac screenshot must be ${Rw}, received ${e.mimeType}`);const t=await fw(),r=await t.read(Buffer.from(e.data,"base64"));return(await(n={data:r.bitmap.data,width:r.bitmap.width,height:r.bitmap.height},(async e=>{const{module:t,defaultOptions:r}=await Pw(),n=new Uint8ClampedArray(e.data.buffer,e.data.byteOffset,e.data.byteLength);return Buffer.from(t.encode(n,e.width,e.height,{...r,lossless:1,exact:1}))})(n))).toString("base64");var n}},Tw={userFacing:function(e){if(e instanceof cw&&e.userFacing&&e.message.trim().length>0&&!Yg(e.message))return e.message.trim()},isCaptureBlocked:function(e){return e instanceof cw&&("computer_use_screenshot"===e.tool||"permission_required"===e.code)}},Aw=new Set(["keys"]),$w=new Set(["matched","mismatch","unchecked"]),Mw=new Set(["no_text","password","control_keys","too_long","unreadable","moved","chromium","gecko"]),Dw=new Set(["matched"]),Ow=new Set(["too_long"]),Fw=new Set(["watched","fell_back","unavailable","over_budget"]);class Nw{constructor({ctx:e,actions:t,sidecar:r,errors:n,reportTyping:o}){this.startTime=Date.now(),this.typingNotes=[],this.typing=[],this.geometryPrimed=!1,this.actionCount=0,this.hasCompletedActuation=!1,this.staleAfterWait=!1,this.ctx=e,this.actions=t,this.sidecar=r,this.errors=n??Tw,this.reportTyping=!0===o}async execute(){const e=this.actions.some((e=>Nw.isInputAction(e.action.case)));try{this.throwIfAborted(),e&&await this.sidecar.startControl(this.ctx);for(const e of this.actions){this.throwIfAborted();const t=e.action;if(void 0===t.case)throw new Error("Computer use action case is undefined");switch(this.actionCount+=1,t.case){case"screenshot":case"cursorPosition":await this.captureScreen();break;case"click":void 0!==t.value.coordinate&&await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.click(this.ctx,{coordinate:t.value.coordinate,button:Nw.mouseButtonName(t.value.button),count:t.value.count>0?t.value.count:1,modifierKeys:t.value.modifierKeys}),t.value.coordinate);break;case"scroll":void 0!==t.value.coordinate&&await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.scroll(this.ctx,{coordinate:t.value.coordinate,direction:Nw.scrollDirectionName(t.value.direction),amount:t.value.amount>0?t.value.amount:3,modifierKeys:t.value.modifierKeys}),t.value.coordinate);break;case"mouseMove":if(void 0===t.value.coordinate)throw new Error("MouseMoveAction requires coordinate");await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.move(this.ctx,{x:t.value.coordinate.x,y:t.value.coordinate.y}),t.value.coordinate);break;case"mouseDown":this.recordActuation(await this.sidecar.mouseButton(this.ctx,{button:Nw.mouseButtonName(t.value.button),action:"down"}));break;case"mouseUp":this.recordActuation(await this.sidecar.mouseButton(this.ctx,{button:Nw.mouseButtonName(t.value.button),action:"up"}));break;case"drag":{const e=t.value.path.map((e=>({x:e.x,y:e.y})));await this.ensureGeometryCached(),this.recordActuation(await this.sidecar.drag(this.ctx,{button:Nw.mouseButtonName(t.value.button),path:e,modifierKeys:t.value.modifierKeys}),e.at(-1));break}case"type":{const e=await this.sidecar.typeText(this.ctx,t.value.text);this.recordActuation(e),this.recordTyping(e);break}case"key":if(t.value.stroke===Og.EB.DOWN||t.value.stroke===Og.EB.UP)throw new Error("Held keys (KeyAction.stroke DOWN/UP) are not supported by the computer-use sidecar; use hold_duration_ms");this.recordActuation(await this.sidecar.pressKey(this.ctx,{key:t.value.key,holdDurationMs:t.value.holdDurationMs}));break;case"wait":await this.delay(Math.max(0,t.value.durationMs)),this.staleAfterWait=!0;break;default:{const e=t;throw new Error(`Unknown computer use action: ${JSON.stringify(e)}`)}}}this.throwIfAborted(),(void 0===this.screenshot||this.staleAfterWait)&&await this.captureScreen(),this.throwIfAborted();const t=await this.normalizeRetainedScreenshots();return t.screenshotFailed&&!this.hasCompletedActuation?this.screenshotUnavailableResult(t.failureReason):(this.throwIfAborted(),new Og.ks({result:{case:"success",value:new Og.Wd({actionCount:this.actionCount,durationMs:Date.now()-this.startTime,screenshot:t.screenshot,cursorPosition:this.cursor,log:this.log(t.screenshotFailed?"Screenshot unavailable":void 0),typing:this.typing})}}))}catch(e){return this.ctx.signal.aborted?this.abortedResult():this.errorResult(e)}finally{e&&await this.sidecar.releaseControl(this.ctx)}}static isInputAction(e){switch(e){case"click":case"scroll":case"mouseMove":case"mouseDown":case"mouseUp":case"drag":case"type":case"key":return!0;default:return!1}}async captureScreen(){const e=await this.sidecar.screenshot(this.ctx);this.screenshot=e.screenshot,this.cursor=Nw.cursorFromResult(e)??this.cursor,this.geometryPrimed=!0,this.staleAfterWait=!1}async ensureGeometryCached(){this.geometryPrimed||await this.captureScreen()}recordActuation(e,t){this.screenshot=e.screenshot,this.hasCompletedActuation=!0,this.staleAfterWait=!1,void 0!==e.screenshot&&(this.geometryPrimed=!0),this.cursor=Nw.cursorFromResult(e)??Nw.coordinateFromPoint(t)??this.cursor}recordTyping(e){if(!this.reportTyping)return;const t=e.message.trim();""!==t&&this.typingNotes.push(t);const r=Nw.typingFromResult(e);void 0!==r&&this.typing.push(r)}log(e){const t=void 0===e?this.typingNotes:[...this.typingNotes,e];return 0===t.length?void 0:t.join("\n")}static typingFromResult(e){const t=e.structuredContent;if("object"!=typeof t||null===t||!("type"in t))return;const r=t.type;if("object"!=typeof r||null===r)return;const n=new Map(Object.entries(r)),o=(e,t)=>{const r=n.get(e);return"string"==typeof r&&t.has(r)?r:void 0},s=e=>{const t=n.get(e);return"number"==typeof t&&Number.isInteger(t)&&t>=0?t:void 0},i=o("check",$w),a=o("unchecked",Mw),c=void 0!==n.get("unchecked")&&null!==n.get("unchecked"),l=void 0!==i&&Dw.has(i)&&!c||"unchecked"===i&&void 0!==a&&Ow.has(a);return new Og.qA({method:o("method",Aw)??"",chars:l?s("chars")??0:0,atoms:l?s("atoms")??0:0,typedAtoms:l?s("typedAtoms")??0:0,aborted:!0===n.get("aborted"),check:i,verified:l?s("verified"):void 0,unchecked:a,landing:o("landing",Fw)})}async errorResult(e){let t;if(Nw.logger.error(this.ctx,"local-cua execute failed",void 0,{error:lw(e)}),!this.errors.isCaptureBlocked(e))try{const e=await this.sidecar.screenshot(this.ctx);t=(await this.normalizeScreenshot(e.screenshot,"error")).data}catch(e){Nw.logger.warn(this.ctx,"local-cua error screenshot capture failed",{error:lw(e)})}const r=this.errors.userFacing(e);return new Og.ks({result:{case:"error",value:new Og.Jb({error:void 0===r?"Computer use failed":`Computer use failed: ${r}`,actionCount:this.actionCount,durationMs:Date.now()-this.startTime,screenshot:t,log:this.log(),typing:this.typing})}})}screenshotUnavailableResult(e){return new Og.ks({result:{case:"error",value:new Og.Jb({error:"Screenshot unavailable",actionCount:this.actionCount,durationMs:Date.now()-this.startTime,log:e})}})}abortedResult(){return new Og.ks({result:{case:"error",value:new Og.Jb({error:"Computer use aborted",actionCount:this.actionCount,durationMs:Date.now()-this.startTime,log:this.log(),typing:this.typing})}})}static mouseButtonName(e){return Nw.mouseButtonNames[e]??"left"}static scrollDirectionName(e){return Nw.scrollDirectionNames[e]??"down"}async normalizeRetainedScreenshots(){const e=await this.normalizeScreenshot(this.screenshot,"post-action");return{screenshot:e.data,screenshotFailed:void 0===this.screenshot||e.failed,failureReason:void 0===this.screenshot?"sidecar returned no image":e.reason}}async normalizeScreenshot(e,t){if(void 0===e)return{failed:!1};try{return{data:await Iw.normalize(e),failed:!1}}catch(r){const n=lw(r);return Nw.logger.error(this.ctx,"local-cua screenshot conversion failed",void 0,{frame:t,error:n}),"image/png"===e.mimeType&&e.data.length>0?{data:e.data,failed:!1}:{failed:!0,reason:n}}}static coordinateFromPoint(e){if(void 0!==e&&Number.isFinite(e.x)&&Number.isFinite(e.y))return new Og.xp({x:Math.round(e.x),y:Math.round(e.y)})}static cursorFromResult(e){const t=e.structuredContent;if("object"!=typeof t||null===t||!("cursor"in t))return;const r=t.cursor;return"object"==typeof r&&null!==r&&"x"in r&&"y"in r&&"number"==typeof r.x&&"number"==typeof r.y&&Number.isFinite(r.x)&&Number.isFinite(r.y)?new Og.xp({x:Math.round(r.x),y:Math.round(r.y)}):void 0}throwIfAborted(){if(this.ctx.signal.aborted)throw this.ctx.signal.reason??new Error("Computer use aborted")}delay(e){return this.throwIfAborted(),new Promise(((t,r)=>{const n=()=>{clearTimeout(o),r(this.ctx.signal.reason??new Error("Computer use aborted"))},o=setTimeout((()=>{this.ctx.signal.removeEventListener("abort",n),t()}),e);this.ctx.signal.addEventListener("abort",n,{once:!0}),this.ctx.signal.aborted&&n()}))}}Nw.logger=(0,l.h)("local-cua:actions"),Nw.mouseButtonNames={[Og.w3.UNSPECIFIED]:"left",[Og.w3.LEFT]:"left",[Og.w3.RIGHT]:"right",[Og.w3.MIDDLE]:"middle",[Og.w3.BACK]:"left",[Og.w3.FORWARD]:"left"},Nw.scrollDirectionNames={[Og.Dh.UNSPECIFIED]:"down",[Og.Dh.UP]:"up",[Og.Dh.DOWN]:"down",[Og.Dh.LEFT]:"left",[Og.Dh.RIGHT]:"right"},s.default.join(o.default.tmpdir(),"computer-use"),(0,l.h)("local-cua:windows");Error,Buffer.from([137,80,78,71,13,10,26,10]),new Set(["capture_failed","secure_desktop","input_desktop_unavailable","sidecar_unavailable","user_aborted","session_busy","canvas_mismatch"]);var Lw,jw=r("../proto/dist/generated/agent/v1/delete_exec_pb.js");function Uw({encoding:e,bom:t,lineEnding:r}){return{encoding:e,bom:t,lineEnding:r}}class Bw{constructor(e){this.workspacePath=e,this.changes=new Map,this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){for(const t of this.listeners)t(e)}async trackChange(e,t,r,n,o){const s=this.changes.get(e);if(s){const t=s.before,o=n||s.metadata;if(t===r||void 0===t&&void 0===r)this.changes.delete(e),this.notify();else{const n={path:e,before:t,after:r,metadata:o,...void 0===s.beforeFormat?{}:{beforeFormat:s.beforeFormat}};this.changes.set(e,n),this.notify(n)}}else{const s={path:e,before:t,after:r,metadata:n,...void 0===o?{}:{beforeFormat:o}};this.changes.set(e,s),this.notify(s)}}getChanges(){return Array.from(this.changes.values())}getChange(e){return this.changes.get(e)}hasChange(e){return this.changes.has(e)}accept(e){const t=this.changes.get(e);this.changes.delete(e),this.notify(t)}acceptAll(){this.changes.clear(),this.notify()}async reject(e){const t=this.changes.get(e);if(t)try{void 0===t.before&&void 0!==t.after?await(0,Co.unlink)(e):(void 0!==t.before&&void 0===t.after||void 0!==t.before&&void 0!==t.after)&&await async function(e,t,r,n){const{buffer:o,format:s}=await Wi(e,t,r,n);await(0,Co.writeFile)(e,o),await Bi(e,{buffer:o,encoding:s.encoding})}(e,t.before,this.workspacePath)}catch{}finally{this.changes.delete(e),this.notify(t)}}async rejectAll(){const e=Array.from(this.changes.keys());await Promise.all(e.map((e=>this.reject(e))))}clear(){const e=this.changes.values().next().value;this.changes.clear(),this.notify(e)}get size(){return this.changes.size}dispose(){this.changes.clear(),this.listeners.clear()}}!function(e){e.Write="write",e.Read="read",e.Shell="shell",e.Delete="delete",e.Mcp="mcp"}(Lw||(Lw={}));var Ww=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class Hw{constructor(e,t,r,n,o,s){this.pendingDecisionProvider=e,this.fileChangeTracker=t,this.permissionsService=r,this.workspacePath=n,this.onDeleteForAiTracking=o,this.agentFileViews=s}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,$.VI)(e.withName("LocalDeleteExecutor.execute")),!1);const n=t.path;if(""===n.trim())return new jw.Pi({result:{case:"error",value:new jw.GU({path:n,error:es})}});const o=(0,Yo.o1)(n,this.workspacePath),i=await this.permissionsService.shouldBlockWrite(e,o,"");if(i){const e=await Qu(i,{onNeedsApproval:async(e,t)=>null,onUserRejected:e=>new jw.Pi({result:{case:"rejected",value:new jw.iq({path:o,reason:e||""})}}),onPermissionDenied:(e,t)=>new jw.Pi({result:{case:"permissionDenied",value:new jw.QG({path:o,clientVisibleError:e,isReadonly:t?.isReadonly??!1})}})});if(null!==e)return e}const a=await async function(e,t){const r=await(0,Co.realpath)((0,s.dirname)(e)).catch((()=>{}));if(void 0===r)return e;if(void 0!==t){const n=await(0,Co.realpath)(t).catch((()=>{}));if(void 0!==n&&(0,Yo.BJ)(r,n))return(0,s.resolve)(t,(0,s.relative)(n,r),(0,s.basename)(e))}return(0,s.join)(r,(0,s.basename)(e))}(o,this.workspacePath),c=await this.pendingDecisionProvider.requestApproval({type:Lw.Delete,details:{path:a},toolCallId:t.toolCallId});if(!c.approved)return new jw.Pi({result:{case:"rejected",value:new jw.iq({path:o,reason:c.reason||""})}});let l;try{l=await(0,Co.stat)(o)}catch(e){return"ENOENT"===Sc(e)?new jw.Pi({result:{case:"fileNotFound",value:new jw.n0({path:o})}}):new jw.Pi({result:{case:"error",value:new jw.GU({path:o,error:kc(e)})}})}if(!l.isFile()){const e=l.isDirectory()?"directory":"other";return new jw.Pi({result:{case:"notFile",value:new jw.LX({path:o,actualType:e})}})}const u=l.size;let d,h;if(u<=ns)try{const e=await Ui(o);d=e.text,h=Uw(e)}catch{}const p=d??"",f=await(0,Co.realpath)(o).catch((()=>o)),m=await(0,Co.stat)(o).catch((()=>{}));if(m?.dev!==l.dev||m.ino!==l.ino)return new jw.Pi({result:{case:"error",value:new jw.GU({path:o,error:"File changed while deleting; nothing was removed"})}});e.signal.throwIfAborted();try{await(0,Co.unlink)(o),this.agentFileViews?.recordDelete(o)}catch(e){return"EACCES"===Sc(e)?new jw.Pi({result:{case:"permissionDenied",value:new jw.QG({path:o,clientVisibleError:"Permission denied"})}}):"EBUSY"===Sc(e)?new jw.Pi({result:{case:"fileBusy",value:new jw.vX({path:o})}}):new jw.Pi({result:{case:"error",value:new jw.GU({path:o,error:kc(e)})}})}if(this.fileChangeTracker&&void 0!==d){const e={...t.toolCallId?{toolCallId:t.toolCallId}:{},...f===o?{}:{writtenPath:f},beforeMode:511&l.mode};await this.fileChangeTracker.trackChange(o,d,void 0,e,h)}return this.onDeleteForAiTracking&&this.onDeleteForAiTracking({path:o}).catch((()=>{})),new jw.Pi({result:{case:"success",value:new jw.fl({path:o,deletedFile:o,fileSize:BigInt(u),prevContent:p})}})}catch(e){r.error=e,r.hasError=!0}finally{Ww(r)}}}class qw{constructor(e,t){this.inner=e,this.extraTools=t}async getTools(e){return[...await this.inner.getTools(e).catch((()=>[])),...this.extraTools]}async getToolsForServers(e,t){const r=await this.inner.getToolsForServers(e,t).catch((()=>[])),n=new Set(t);return[...r,...this.extraTools.filter((e=>n.has(e.clientKey)||n.has(e.providerIdentifier)))]}async getClients(e){return this.inner.getClients(e)}async getClient(e,t){return this.inner.getClient(e,t)}async getInstructions(e){const t=await this.inner.getInstructions(e).catch((()=>[])),r=this.extraTools.filter((e=>e.providerIdentifier===zn));if(0===r.length)return t;const n=r.map((e=>{const t="string"==typeof e.description&&e.description.length>0?e.description:"(no description provided)";return`- ${e.toolName}: ${t}`})).join("\n");return[...t,new wn.I0({serverIdentifier:zn,serverName:zn,instructions:`User-defined tools for this session (server "${zn}"). Discover schemas via MCP meta-tool discovery for that server, then invoke via the MCP invocation meta-tool.\n\nAvailable tools:\n${n}`})]}async getToolSet(e){return this.inner.getToolSet(e)}}class zw extends qw{constructor(e,t){super(e,t),this.observableInner=e}onDidChange(e){return this.observableInner.onDidChange(e)}}var Gw=r("../proto/dist/generated/agent/v1/fetch_exec_pb.js"),Vw=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const Kw=/;\s*charset\s*=\s*"?([^";\s]+)/i;class Jw{constructor(e){this.encodingSlices=e?.encodingSlices}async readText(e,t){if(!Ul(this.encodingSlices,e))return await t.text();const r=async function(e,t){if(void 0===e)return"unseen";try{return(0,n.isUtf8)(await e.arrayBuffer())?"utf8_valid":t?"declared_other":"utf8_invalid"}catch{return"unseen"}}(function(e){try{return e.clone()}catch{return}}(t),function(e){const t=Kw.exec(e.headers.get("content-type")??"")?.[1];return void 0!==t&&!/^utf-?8$/i.test(t)}(t)),o=await t.text();return this.recordFetched(e,o,r),o}async recordFetched(e,t,r){try{Yl(this.encodingSlices,e,{layer:"exec_web_fetch",evidence:await r},t)}catch{}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,$.VI)(e.withName("LocalFetchExecutor.execute")),!1);const n=t.url;try{const t=await fetch(n),r=await this.readText(e,t),o=t.headers.get("content-type")||"text/plain";return new Gw.uN({result:{case:"success",value:new Gw.Uk({url:n,content:r,statusCode:t.status,contentType:o})}})}catch(e){return new Gw.uN({result:{case:"error",value:new Gw.fk({url:n,error:kc(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{Vw(r)}}}const Zw=[["safe.bareRepository","explicit"]],Xw=[["core.fsmonitor","false"],["core.hooksPath",o.devNull],["core.attributesFile",o.devNull]],Qw=[["core.quotePath","false"]];function Yw(e){const t="allow-hooks"===e?Xw.filter((([e])=>"core.hooksPath"!==e)):Xw;return[...Zw,...t]}const ey=(0,zs.promisify)(ou.execFile),ty=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--super-prefix","--config-env","--attr-source"]),ry=new Set(["diff","show","blame","log","whatchanged"]);function ny(e){for(let t=0;t["-c",`${e}=${t}`]))}const gy=my([...Yw("block"),["submodule.recurse","false"],["fetch.recurseSubmodules","false"],["diff.submodule","short"],["status.submoduleSummary","false"],["log.showSignature","false"],["log.diffMerges","separate"],["gpg.openpgp.program",o.devNull],["gpg.x509.program",o.devNull],["gpg.ssh.program",o.devNull]]);function wy(e){const t=e?.timeout??0,r=Number.isFinite(t)&&t>0?Math.min(t,2147483647):6e4;return performance.now()+r}function yy(e,t=2147483647){return Math.max(1,Math.ceil(Math.min(t,e-performance.now())))}function vy(){const e=new Map;return{async exec(t,r,n){const o=wy(n);return ay("git",await by(e,t,r,o),{cwd:t,env:fy,windowsHide:!0,killSignal:"SIGTERM",timeout:yy(o)})},async run(t,r,n){const o=wy(n);return function(e,t,r,n){return new Promise(((o,s)=>{const i=function(e,t,r){const{env:n,...o}=r??{},s=sy(t);return(0,ou.spawn)("git",s,{...o,env:iy(s,n)})}(0,t,{cwd:e,env:fy,windowsHide:!0,stdio:[void 0===n?"ignore":"pipe","pipe","pipe"]}),a=[],c=[];let l=!1;const u=()=>{const e=!l;return l=!0,clearTimeout(d),e},d=setTimeout((()=>{u()&&(i.kill("SIGTERM"),i.stdin?.destroy(),i.stdout?.destroy(),i.stderr?.destroy(),s(Object.assign(new Error("git timed out"),{code:null,killed:!0,signal:"SIGTERM"})))}),yy(r));i.stdout?.on("data",(e=>{a.push(e)})),i.stderr?.on("data",(e=>{c.push(e)}));for(const e of[i.stdout,i.stderr])e?.on("error",(e=>{u()&&(i.kill("SIGTERM"),s(e))}));i.on("error",(e=>{u()&&s(e)})),i.on("close",((e,t)=>{u()&&(null!==e?o({exitCode:e,stdout:Buffer.concat(a).toString("utf8"),stderr:Buffer.concat(c).toString("utf8")}):s(Object.assign(new Error(`git was killed by ${String(t)}`),{code:e,killed:!1,signal:t})))})),void 0!==n&&null!==i.stdin&&(i.stdin.on("error",(()=>{})),i.stdin.end(n))}))}(t,await by(e,t,r,o),o,n?.input)}}}async function by(e,t,r,n){const{prefix:o,tail:s,readsConfig:i}=function(e){const t=sy(e),r=ny(t),n=t.findIndex(((e,t)=>t>r&&("--"===e||"--end-of-options"===e))),o=t.slice(0,-1===n?t.length:n);if(o.includes("--help")||o.includes("-h"))throw new TypeError("git help is refused: it starts the repository's man viewer");if(-1===r)return{prefix:[],tail:t,readsConfig:!1};const s=t[r],i=ly.get(s);if(void 0===i)throw new TypeError(`git ${s} is refused: the pins cover only a fixed set of verbs`);const[a,c]=i,l=o.find((e=>function(e,t,r){const n=r.startsWith("--")?r.slice(2).split("=",1)[0]:"",o=[...uy,..."status"===e?["verbose"]:[],..."worktree"===e?["checkout","no-force"]:[],...t?["ignore-submodules","no-ignore-submodules"]:[]];return""!==n&&o.some((e=>e.startsWith(n)))||"status"===e&&/^-[^-]*v/.test(r)}(s,c,e)));if(void 0!==l)throw new TypeError(`git ${s} ${l} is refused: it can start a program the pins miss`);const u=t.slice(r+1),d="worktree"===s?u.find((e=>!e.startsWith("-"))):void 0;if("remove"===d&&!o.includes("--force")&&!o.includes("-f"))throw new TypeError("git worktree remove is refused without --force");if("add"===d&&"--no-checkout"!==u[u.indexOf("add")+1])throw new TypeError("git worktree add is refused unless --no-checkout follows add");return{prefix:[...t.slice(0,r),...gy],tail:[s,...c?["--ignore-submodules=dirty"]:[],...u],readsConfig:a}}(r),a=i?await function(e,t,r,n){const o=`${t}\0${r.join("\0")}`,s=e.get(o);if(void 0!==s)return s;const i=async function(e,t,r){let n;try{n=(await ay("git",[...t,"config","--list","--show-scope","--includes","-z"],{cwd:e,env:fy,windowsHide:!0,killSignal:"SIGTERM",timeout:yy(r,1e4),maxBuffer:16777216})).stdout}catch(e){throw function(e){if(!(e instanceof Error))return new cy("read-failed");if("syscall"in e&&"string"==typeof e.syscall&&e.syscall.startsWith("spawn"))return e;if("killed"in e&&!0===e.killed)return new cy("timed-out");const t="code"in e&&"number"==typeof e.code?e.code:void 0;return new cy("read-failed",t)}(e)}if(performance.now()>=r)throw new cy("timed-out");return function(e){if(""===e)return[];const t=e.split("\0");if(""!==t.pop()||t.length%2!=0)throw new cy("read-failed");const r=new Set;for(let e=0;emy([[`filter.${e}.clean`,""],[`filter.${e}.smudge`,""],[`filter.${e}.process`,""],[`filter.${e}.required`,"false"]])))}(n)}(t,r,n);return e.set(o,i),i}(e,t,o,n):[];return[...o,...a,...s]}function Sy(e,t,r){return vy().exec(e,t,r)}var ky=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class _y{constructor(e={}){void 0!==e.guardedRootLookup&&(this.guardedRootLookup=e.guardedRootLookup)}async exec(e,t,r,n){return Cy(e,t,r,n,Sy)}forRequest(){const e=vy();return{exec:(t,r,n,o)=>Cy(t,r,n,o,((t,r,n)=>e.exec(t,r,n))),...void 0===this.guardedRootLookup?{}:{guardedRootLookup:this.guardedRootLookup}}}}async function Cy(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(s,(0,$.VI)(e.withName("LocalGitExecutor.exec"),{attributes:{"git.cwd":t,"git.args":r,"git.caller":n?.caller}}),!1);const{stdout:i,stderr:a}=await o(t,r,{timeout:n?.timeout});return{exitCode:0,stdout:i,stderr:a}}catch(e){s.error=e,s.hasError=!0}finally{ky(s)}}var Ey=r("../proto/dist/generated/agent/v1/grep_exec_pb.js");class xy{constructor(){this.lineEnd=0,this.nextStart=0}}function Py(e,t,r){const n=e.length;if(t>=n)return!1;const o=e.indexOf("\n",t);if(-1!==o){const n=o>t&&13===e.charCodeAt(o-1);return r.lineEnd=n?o-1:o,r.nextStart=o+1,!0}return r.lineEnd=n,r.nextStart=n,!0}function Ry(e,t,r,n,o,s){const i=e.indexOf("\0",t);if(-1===i||i>=r)return;let a=i+1;for(;a=48&&e.charCodeAt(a)<=57;)a++;if(a===i+1||a>=r)return;const c=e.charCodeAt(a);if(58!==c&&45!==c)return;const l=n.indexOf(0,o);if(-1===l||l>=s)return;const u=l+(a-i);return u>=s||n.toString("latin1",l+1,u+1)!==e.slice(i+1,a+1)?void 0:{file:e.slice(t,i),contentStart:a+1,contentEnd:r,contentBytesStart:u+1,contentBytesEnd:s}}const Iy=-(2**31),Ty=2**31-1;function Ay(e){return Number.isNaN(e)?0:eTy?Ty:e}function $y(e){if("number"==typeof e&&Number.isFinite(e)&&!(e<0))return Ay(Math.trunc(e))}function My(e){const t=e.replace(/\s/g,"_").replace(/[^a-zA-Z0-9_.-]/g,"").replace(/\.+/g,".");return"."===t||".."===t?t.replace(/\./g,"_"):0===t.length?"_":t}async function Dy(e,t){const r=My(t),n=(0,s.join)(e,"mcps",r,"tools");let o;try{o=await(0,Co.readdir)(n)}catch(e){if("ENOENT"===Sc(e))return{toolNames:[],toolsDirExists:!1};throw e}const i=await Promise.all(o.map((async e=>{if(e.endsWith(".json"))try{return function(e){try{const t=JSON.parse(e);return"string"==typeof t.name&&t.name.length>0?t.name:"string"==typeof t.toolName&&t.toolName.length>0?t.toolName:void 0}catch{return}}(await(0,Co.readFile)((0,s.join)(n,e),"utf8"))}catch{return}}))),a=new Set;for(const e of i)e&&a.add(e);return{toolNames:Array.from(a).sort(((e,t)=>e.localeCompare(t))),toolsDirExists:!0}}const Oy=(0,l.h)("local-exec:mcp-disk-freshness-on-access"),Fy="/mcps/",Ny=(0,u.Pu)("mcp.discovery_freshness.check",{description:"MCP discovery surface freshness comparison outcome against canonical live tools",labelNames:["surface","outcome"]}),Ly=(0,u.v5)("mcp.discovery_freshness.missing_tools",{description:"Number of tools present in canonical live state but missing from the observed discovery surface",labelNames:["surface"]}),jy=(0,u.v5)("mcp.discovery_freshness.extra_tools",{description:"Number of tools present on the observed discovery surface but absent from canonical live state",labelNames:["surface"]}),Uy=(0,u.v5)("mcp.discovery_freshness.symmetric_difference",{description:"Total symmetric difference between canonical live tools and the observed discovery surface",labelNames:["surface"]}),By=new Map;function Wy(e){const t=e.replace(/\\/g,"/");return t.endsWith("/mcps")?`${t}/`:t}async function Hy({ctx:e,mcpStateAccessor:t,projectDir:r,sanitizedServerFolder:n,readDiskCatalog:o,state:s}){let i=s;if(void 0===i)try{i=await t.getState(e)}catch(t){return void Oy.warn(e,"mcp_disk_state_read_failed",{error_type:t instanceof Error?t.name:typeof t})}const a=i.servers.find((e=>My(e.serverIdentifier)===n));if(void 0===a)return;let c;try{c=await o(r,a.serverIdentifier)}catch(t){return void Oy.warn(e,"mcp_disk_catalog_read_failed",{error_type:t instanceof Error?t.name:typeof t})}if(!c.toolsDirExists)return;const l=a.tools.map((e=>e.toolName)).filter((e=>e.length>0)).sort(((e,t)=>e.localeCompare(t)));!function({ctx:e,serverIdentifier:t,canonicalToolNames:r,observedToolNames:n}){const o=new Set(n),s=new Set(r),i=r.filter((e=>!o.has(e))),a=n.filter((e=>!s.has(e))),c=0===i.length&&0===a.length?"match":"mismatch",l={surface:"disk"};Ny.increment(e,1,{...l,outcome:c}),Ly.histogram(e,i.length,l),jy.histogram(e,a.length,l),Uy.histogram(e,i.length+a.length,l),"mismatch"===c&&Oy.warn(e,"mcp_disk_discovery_freshness_mismatch",{server_identifier:t,missing_tool_count:i.length,extra_tool_count:a.length})}({ctx:e,serverIdentifier:a.serverIdentifier,canonicalToolNames:l,observedToolNames:c.toolNames})}function qy(e,t,r,n=Dy){if(void 0===r||(void 0===(o=r)||!Wy(o).includes(Fy)))return;var o;const s=function(e){const t=Wy(e),r=t.indexOf(Fy);if(-1===r)return;const n=t.slice(0,r),o=t.slice(r+6).split("/").filter(Boolean);return 0!==n.length?0===o.length?{projectDir:n,kind:"mcps_root"}:{projectDir:n,kind:"server",sanitizedServerFolder:o[0]}:void 0}(r);if(void 0===s)return;let i,a;const c="mcps_root"===s.kind;"mcps_root"===s.kind?(i=`${s.projectDir}\0__mcps_root__`,a=void 0):(i=`${s.projectDir}\0${s.sanitizedServerFolder}`,a=s.sanitizedServerFolder);const l=By.get(i);void 0!==l&&clearTimeout(l);const u=e,d=setTimeout((()=>{By.delete(i),(async()=>{if(c){const e=await t.getState(u);for(const r of e.servers){const o=My(r.serverIdentifier);await Hy({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:o,readDiskCatalog:n,state:e})}}else void 0!==a&&await Hy({ctx:u,mcpStateAccessor:t,projectDir:s.projectDir,sanitizedServerFolder:a,readDiskCatalog:n})})().catch((e=>{Oy.warn(u,"mcp_disk_discovery_freshness_schedule_failed",{error_type:e instanceof Error?e.name:typeof e})}))}),2e3);By.set(i,d)}async function zy(e){try{return(await(0,Co.stat)(e,{bigint:!0})).mtimeNs}catch{return}}function Gy(e,t,r){const n=e.map(((e,n)=>({file:e,mtime:t[n],segments:e.path.split(r)})));return n.sort(((e,t)=>e.mtime!==t.mtime?void 0===e.mtime?1:void 0===t.mtime||e.mtime>t.mtime?-1:1:function({left:e,right:t}){const r=Math.min(e.length,t.length);for(let n=0;ne.file))}async function Vy(e,t,r=zy){const n=e.map((e=>({item:e,path:t(e)})));let o;try{o=await(0,Or.wj)(Promise.all(n.map((({path:e})=>r(e)))),2e3,"stat timed out")}catch(t){if(t instanceof Or.MU)return{items:[...e],statTimedOut:!0};throw t}return{items:Gy(n,o,s.sep).map((({item:e})=>e)),statTimedOut:!1}}var Ky=r("../proto/dist/generated/agent/v1/read_exec_pb.js");const Jy=Buffer.from([137,80,78,71,13,10,26,10]),Zy=Buffer.from([0,0,0,0,73,69,78,68,174,66,96,130]),Xy=e=>{if(e.lengthe.subarray(e.length-Zy.length).equals(Zy)||(e=>{let t=Jy.length+25;for(;t+Zy.length<=e.length;){const r=e.readUInt32BE(t);if(r>e.length-t-Zy.length)return!1;if("IEND"===e.toString("ascii",t+4,t+8))return e.subarray(t,t+Zy.length).equals(Zy);t+=Zy.length+r}return!1})(e))(e))return;const t=e.readUInt32BE(16),r=e.readUInt32BE(20);return t<1||r<1?void 0:{width:t,height:r,colorType:e.readUInt8(25)}},Qy=e=>1===e||e>=208&&e<=216,Yy=e=>192===e||193===e||194===e,ev=e=>e>=195&&e<=207&&196!==e&&200!==e&&204!==e,tv=e=>0===e||e>=208&&e<=215,rv=(e,t)=>{let r=e.indexOf(255,t);for(;-1!==r&&r+1(e=>{const t=Xy(e);if(void 0!==t)return{mimeType:"image/png",width:t.width,height:t.height}})(e)??(e=>{if(e.length<4||255!==e[0]||216!==e[1]||!(e=>255===e[e.length-2]&&217===e[e.length-1]||(e=>{let t=2;for(;t+2<=e.length;){if(255!==e[t])return!1;const r=e[t+1];if(255===r){t+=1;continue}if(217===r)return!0;if(Qy(r)){t+=2;continue}if(t+4>e.length)return!1;const n=e.readUInt16BE(t+2);if(n<2)return!1;const o=t+2+n;if(218!==r){t=o;continue}const s=rv(e,o);if(void 0===s)return!1;t=s}return!1})(e))(e))return;let t=2;for(;t+4<=e.length;){if(255!==e[t])return;const r=e[t+1];if(255===r){t+=1;continue}if(Qy(r)){t+=2;continue}if(218===r||217===r||ev(r))return;const n=e.readUInt16BE(t+2);if(n<2)return;if(Yy(r)){if(n<8||t+9>e.length)return;const r=e.readUInt16BE(t+5),o=e.readUInt16BE(t+7);if(o<1||r<1)return;return{mimeType:"image/jpeg",width:o,height:r}}t+=2+n}})(e),ov=(e,t)=>({width:Math.max(e?.width??0,t.width),height:Math.max(e?.height??0,t.height)}),sv=(e,t)=>{for(;t{const t=e.toString("latin1",0,6);return e.subarray(0,Jy.length).equals(Jy)?"png":t.startsWith("ÿØÿ")?"jpeg":"GIF87a"===t||"GIF89a"===t?"gif":t.startsWith("BM")?"bmp":t.startsWith("II*\0")||t.startsWith("MM\0*")?"tiff":t.startsWith("ID3")?"id3":void 0},av={0:1,2:3,4:2,6:4},cv=async({data:e,width:t,height:r})=>{const n=lv(e);if(void 0===n||t>n.width||r>n.height)return;const o=n.width*n.channels,s=new Uint32Array(n.width);for(let e=0;e{let t;const r=[];let n=8;for(;n+12<=e.length;){const o=e.readUInt32BE(n),s=e.toString("ascii",n+4,n+8),i=e.subarray(n+8,n+8+o);if(i.length!==o)return;if("IHDR"===s){const e=av[i[9]];if(void 0!==t||13!==o||8!==i[8]||0!==i[12]||void 0===e)return;t={width:i.readUInt32BE(0),height:i.readUInt32BE(4),channels:e}}else if("IDAT"===s)r.push(i);else{if("tRNS"===s)return;if("IEND"===s)break}n+=o+12}return void 0===t||0===r.length?void 0:{...t,idat:r}},uv=({filter:e,row:t,previous:r,bytesPerPixel:n})=>{if(0!==e)for(let o=0;o=n?t[o-n]:0,i=r[o];switch(e){case 1:t[o]+=s;break;case 2:t[o]+=i;break;case 3:t[o]+=s+i>>1;break;case 4:{const e=o>=n?r[o-n]:0,a=s+i-e,c=Math.abs(a-s),l=Math.abs(a-i),u=Math.abs(a-e);t[o]+=c<=l&&c<=u?s:l<=u?i:e;break}default:throw new Error(`unknown PNG filter type ${e}`)}}},dv=({row:e,channels:t,columnOf:r,sums:n,counts:o})=>{const s=t<3;for(let i=0,a=0;i{for(let s=0;s0&&(e[c]=Math.round(n[i]/a),e[c+1]=Math.round(n[i+1]/a),e[c+2]=Math.round(n[i+2]/a),e[c+3]=Math.round(a/o[s]))}n.fill(0),o.fill(0)},pv={0:1,2:3,3:1,4:2,6:4},fv=[1,2,4,8,16],mv=[[0,0,8,8],[4,0,8,8],[0,4,4,8],[2,0,4,4],[0,2,2,4],[1,0,2,2],[0,1,1,2]],gv=async e=>{const t=wv(e);if(void 0===t)return;const r=yv(t);let n=0;const o=ih.Readable.from(t.idat).pipe((0,rh.createInflate)());for await(const e of o)if(n+=e.length,n>=r)return void o.destroy();throw new Error(`PNG pixel data ends after ${n} of ${r} bytes`)},wv=e=>{let t;const r=[];let n=8;for(;n+12<=e.length;){const o=e.readUInt32BE(n),s=e.toString("ascii",n+4,n+8),i=e.subarray(n+8,n+8+o);if("IHDR"===s&&void 0===t&&13===i.length){const e=pv[i[9]];if(void 0===e||!fv.includes(i[8])||i[12]>1)return;t={width:i.readUInt32BE(0),height:i.readUInt32BE(4),bitsPerPixel:e*i[8],interlaced:1===i[12]}}else if("IDAT"===s)r.push(i);else if("IEND"===s)break;n+=o+12}return void 0===t||0===r.length?void 0:{...t,idat:r}},yv=({width:e,height:t,bitsPerPixel:r,interlaced:n})=>{const o=(e,t)=>e<=0||t<=0?0:t*(1+Math.ceil(e*r/8));return n?mv.reduce(((r,[n,s,i,a])=>r+o(Math.ceil((e-n)/i),Math.ceil((t-s)/a))),0):o(e,t)};const vv=()=>{throw new Error("webp codec not registered: registerWebpCodec() must be called by a Node server before decoding/encoding webp")},bv=e=>e.length>=12&&"RIFF"===e.toString("ascii",0,4)&&"WEBP"===e.toString("ascii",8,12),Sv=e=>{if(!bv(e)||e.length<16)return;const t=e.toString("ascii",12,16);if("VP8 "===t){if(e.length<30||157!==e[23]||1!==e[24]||42!==e[25])return;return{width:16383&(e[26]|e[27]<<8),height:16383&(e[28]|e[29]<<8)}}if("VP8L"===t){if(e.length<25||47!==e[20])return;const t=(e[21]|e[22]<<8|e[23]<<16|e[24]<<24)>>>0;return{width:1+(16383&t),height:1+(t>>14&16383)}}if("VP8X"===t){if(e.length<30)return;return{width:1+(e[24]|e[25]<<8|e[26]<<16),height:1+(e[27]|e[28]<<8|e[29]<<16)}}},kv=e=>vv().decode(e);async function _v(e){((e,t)=>{if(!Number.isSafeInteger(e)||e<1||e>t)throw new Error("pngByteBudgetBytes must be a positive integer at most MAX_IMAGE_SIZE_BYTES")})(e.budgetBytes,e.maxImageBytes);nv(e.data);return e.resizeWithoutBudget(e.data)}const Cv=[{width:1280,height:800},{width:1456,height:840}],Ev=e=>void 0!==e&&Cv.some((t=>t.width===e.width&&t.height===e.height)),xv=1048576,Pv=e=>{const t=e.buffer;return t instanceof ArrayBuffer?new Uint8Array(t,e.byteOffset,e.byteLength):Uint8Array.from(e)};function Rv(e,t,r=1024){if(e<1||t<1)return{width:e,height:t,needsResize:!1};const n=Math.max(e,t);if(n<=r)return{width:e,height:t,needsResize:!1};const o=Math.min(e,t);if(o<8)return{width:e,height:t,needsResize:!1};let s=r/n,i=Math.max(1,Math.round(e*s)),a=Math.max(1,Math.round(t*s));return(i<8||a<8)&&(s=8/o,i=Math.max(8,Math.round(e*s)),a=Math.max(8,Math.round(t*s))),{width:i,height:a,needsResize:i!==e||a!==t}}const Iv=(e,t,r=1024)=>Rv(e,t,r),Tv=(e,t)=>Ev({width:e,height:t})?{width:e,height:t,needsResize:!1}:Rv(e,t),Av=(e,t,r)=>{e.resize({w:t,h:r})};function $v(e){if(void 0===e)throw new Error("image dimensions could not be read before decoding");const{width:t,height:r}=e;if(!(t*r<=178956970))throw new Error(`image dimensions ${t}x${r} exceed the 178956970 pixel decode limit`);if(!(Math.max(t,r)<=1e6))throw new Error(`image dimensions ${t}x${r} exceed the 1000000 pixel side limit`)}const Mv=(e,t)=>{switch(t){case"tiff":throw new Error("TIFF images are not supported; convert the image to PNG or JPEG");case"id3":throw new Error("images that start with an ID3 tag are not supported");case"jpeg":return;default:$v(((e,t)=>{switch(t){case"png":return(e=>{let t,r=Jy.length;for(;r+16<=e.length;)"IHDR"===e.toString("ascii",r+4,r+8)&&(t=ov(t,{width:e.readUInt32BE(r+8),height:e.readUInt32BE(r+12)})),r+=12+e.readUInt32BE(r);return t})(e);case"gif":return(e=>{if(e.length<13)return;const t={width:e.readUInt16LE(6),height:e.readUInt16LE(8)};let r=13+(128&(n=e[10])?3<<1+(7&n):0);for(var n;re.length<26?void 0:{width:e.readUInt32LE(18),height:Math.abs(e.readInt32LE(22))})(e)}})(e,t))}},Dv=e=>{const{width:t,height:r}=Iv(e.width,e.height,1280);return{width:t,height:r}},Ov=async(e,t)=>{let{width:r,height:n}=e,o=await t({width:r,height:n});for(;o.length>xv&&r>8&&n>8;)r=Math.max(8,Math.round(.8*r)),n=Math.max(8,Math.round(.8*n)),o=await t({width:r,height:n});return{data:Pv(o),mimeType:"image/webp",reencoded:!0}},Fv=async(e,t)=>{const r=(await fw()).fromBitmap({data:Buffer.from(e.data),width:e.width,height:e.height});return Ov(t,(async e=>(r.bitmap.width===e.width&&r.bitmap.height===e.height||Av(r,e.width,e.height),(e=>vv().encode(e))({data:r.bitmap.data,width:r.bitmap.width,height:r.bitmap.height}))))};let Nv;const Lv=async(e,t)=>{if(void 0!==t?.pngByteBudgetBytes){const{pngByteBudgetBytes:r,...n}=t,o=nv(e);return"image/png"===o?.mimeType&&Ev(o)&&await gv(e),_v({data:e,budgetBytes:r,maxImageBytes:xv,fitImage:Tv,resizeWithoutBudget:e=>Lv(e,n)})}const r=await(async(e,t)=>{const r=bv(e);if(r&&!0===t?.preserveWebpDimensions)return;const n=r?void 0:nv(e),o=r?Sv(e):n;if(void 0===o||!Ev(o))return;const s=Nv;if(void 0!==n&&void 0!==s&&!Ev(await s.readOrientedDimensions(e)))return;const i="image/png"===n?.mimeType;if(i&&await gv(e),e.length<=xv)return{data:Pv(e),mimeType:n?.mimeType??"image/webp"};const a=s?.resizeWebp;if(void 0!==a)return Ov(o,(t=>a({data:e,...t})))})(e,t);if(void 0!==r)return r;if(bv(e))return(async(e,t)=>{const r=Sv(e);if(!0===t?.preserveWebpDimensions&&void 0!==r)return{data:Pv(e),mimeType:"image/webp"};if(void 0!==r&&!Iv(r.width,r.height,1280).needsResize&&e.length<=xv)return{data:Pv(e),mimeType:"image/webp"};if("passthrough"===t?.webpWithoutCodec)return{data:Pv(e),mimeType:"image/webp"};$v(r);const n=undefined;if(void 0!==n)return Ov(Dv(r),(t=>n({data:e,...t})));const o=await kv(e);return Fv(o,Dv(o))})(e,t);const n=nv(e);if(void 0!==n&&e.length<=xv&&!Iv(n.width,n.height).needsResize)return{data:Pv(e),mimeType:n.mimeType};const o=iv(e);void 0!==o&&Mv(e,o);const s=void 0===n?void 0:Iv(n.width,n.height),i="image/png"===n?.mimeType&&!0===s?.needsResize?await cv({data:e,width:s.width,height:s.height}).catch((()=>{})):void 0;void 0===i&&"png"===o&&await gv(e);const a=await fw(),c=void 0===i?await a.read(e):a.fromBitmap(i),l=(e=>{switch(e.mime){case"image/png":default:return"image/png";case"image/bmp":return"image/bmp";case"image/tiff":return"image/tiff";case"image/x-ms-bmp":return"image/x-ms-bmp";case"image/gif":return"image/gif";case"image/jpeg":return"image/jpeg"}})(c),u=!0===t?.convertUnsupportedModelFormatsToPng&&"image/png"!==l&&"image/jpeg"!==l?"image/png":l,{width:d,height:h,needsResize:p}=Iv(c.width,c.height);if(void 0===i&&!p&&e.length<=xv&&u===l)return{data:Pv(e),mimeType:l};let f=d,m=h;p&&Av(c,f,m);let g=await c.getBuffer(u);for(;g.length>xv&&f>8&&m>8;)f=Math.max(8,Math.round(.8*f)),m=Math.max(8,Math.round(.8*m)),Av(c,f,m),g=await c.getBuffer(u);return{data:Pv(g),mimeType:u,reencoded:!0}},jv=async e=>{const t=Buffer.from(e.buffer,e.byteOffset,e.byteLength),r=iv(t);let n;if(bv(t))return{kind:"unchecked"};if(void 0===r)return{kind:"unchecked"};{Mv(t,r);const e=await fw();n=async()=>("png"===r&&await gv(t),e.read(t))}try{return await n(),{kind:"decodes"}}catch(e){return{kind:"undecodable",reason:e instanceof Error?e.message:String(e)}}},Uv=BigInt(0),Bv=BigInt(8),Wv=BigInt(16),Hv=BigInt(65535);function qv(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function zv(e){const t=e.split(".");if(4!==t.length)return;let r=Uv;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<>Wv&Hv)),t.push(Number(o.value&Hv))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function Vv(e){return zv(e)??function(e){const t=qv(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=Gv(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<7?void 0:{version:6,value:[...s,...new Array(8-a).fill(0),...i].reduce(((e,t)=>e<i)return!1;const a=BigInt(i-s);return o.value>>a==n.value>>a}(r,n);if(n.startsWith("*.")){const e=n.slice(2);return r===e||r.endsWith(`.${e}`)}return r===n}function Jv(e,t){const r=function(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch{return}}(e);return!!r&&function(e,t){return t.some((t=>Kv(e,t)))}(r.hostname,t)}var Zv=r("../constants/dist/commercial-cursor-hosts.js");new Set([1,2]);const Xv="cursor/requiresConfirmation",Qv="https://grok.com/connectors-oauth-exchange-code/",Yv="https://x.com/i/connectors/oauth_callback",eb="https://chat.x.com/connectors/oauth_callback",tb="https://lite.x.com/i/connectors/oauth_callback",rb={provider:"google-workspace",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0,authorizationParams:{access_type:"offline",prompt:"select_account consent"}},nb={provider:"x-money",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,registeredAppRedirectUris:[Qv,Yv]},ob="x-cursor-auth";function sb(e,t){return function({serverUrl:e,restMcpHost:t}){if(void 0===e)return;let r;try{r=new URL(e)}catch{return}return"https:"===r.protocol&&r.hostname.toLowerCase()===t.toLowerCase()&&""===r.port?ib(e):void 0}({serverUrl:e,restMcpHost:t})}function ib(e){if(void 0===e)return;let t;try{t=new URL(e)}catch{return}const r=/^\/rest-mcp\/([^/]+)\/mcp\/?$/.exec(t.pathname);return r?.[1]}new Set(Object.values({notConnected:"scm_not_connected",tokenUnavailable:"scm_token_unavailable",tokenRejected:"scm_token_rejected",repoNotAccessible:"scm_repo_not_accessible",orgBlocked:"scm_org_blocked"})),new Set(Object.values({originNotEnabled:"origin_not_enabled",teamDisabled:"team_disabled",admissionRejected:"admission_rejected"}));const ab="https://mcp.shop.com",cb={provider:"grok-connectors",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,scopes:["grok-plugins:access","offline_access"]},lb=new Map([["mcp.slack.com",{displayName:"Slack",baseScopes:["canvases:read","canvases:write","channels:history","channels:read","channels:write","chat:write","emoji:read","files:read","files:write","groups:history","groups:read","im:history","im:read","im:write","lists:read","lists:write","mpim:history","mpim:read","mpim:write","reactions:read","reactions:write","search:read.files","search:read.im","search:read.mpim","search:read.private","search:read.public","search:read.users","users:read","users:read.email"],stepUpScopes:{"groups:write":{action:"create private channels",tools:[{name:"slack_create_conversation",args:{is_private:!0}}]}},missingScopeAnswer:/\bmissing_scope\b/}]]),ub=new Map([["gmailmcp.googleapis.com",{...rb,scopes:["https://www.googleapis.com/auth/gmail.readonly","https://www.googleapis.com/auth/gmail.compose","https://www.googleapis.com/auth/gmail.modify"]}],["drivemcp.googleapis.com",{...rb,scopes:["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/drive.file"]}],["calendarmcp.googleapis.com",{...rb,scopes:["https://www.googleapis.com/auth/calendar.events","https://www.googleapis.com/auth/calendar.calendarlist.readonly","https://www.googleapis.com/auth/calendar.events.readonly","https://www.googleapis.com/auth/calendar.events.freebusy"]}],["docsmcp.googleapis.com",{...rb,scopes:["https://www.googleapis.com/auth/documents"]}],["sheetsmcp.googleapis.com",{...rb,scopes:["https://www.googleapis.com/auth/spreadsheets"]}],["slidesmcp.googleapis.com",{...rb,scopes:["https://www.googleapis.com/auth/presentations"]}],["bigquery.googleapis.com",{...rb,scopes:["https://www.googleapis.com/auth/bigquery"]}],["api.x.com",{provider:"x",clientRegistration:"static",unauthenticatedConnect:!1,rejectsCustomSchemeRedirects:!1,pinsScopesOverConfiguredScopes:!0}],["mcp.money-dev.x.com",nb],["mcp.money-staging.x.com",nb],["mcp.money.x.com",nb],["connectors-gateway.grok.gcp.mouseion.dev",cb],["connectors-gateway.grok.com",cb],["mcp.hubspot.com",{provider:"hubspot",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0}],["mcp.box.com",{provider:"box",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0}],["mcp.asana.com",{provider:"asana",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,configuredSecretStaysOnBackend:!0}],["mcp.strava.com",{provider:"strava",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,scopes:["read","activity:read_all","profile:read_all"]}],["mcp.quickbooks.intuit.com",{provider:"quickbooks-online",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,unauthenticatedEndpointBlocked:!0,backendOnlyTokenExchange:!0,scopes:["com.intuit.quickbooks.accounting","foundations.tools.businessreports.read","foundations.tools.bi-dashboard","foundations.tools.transactions.write","foundations.tools.companyprofile.read","foundations.tools.companyprofile.write","payroll.tools.tax.read","payroll.tools.employer.read","payroll.tools.employer.manage","payroll.tools.run.read","payroll.tools.run.manage","payroll.tools.employee.read","payroll.tools.employee.manage","worker-mgmt.tools.employee.read","worker-mgmt.tools.employee.manage","time-tracking.tools.timeentry.read","sales.tools.invoice.read","sales.tools.invoice","sales.tools.estimate.read","sales.tools.estimate","sales.tools.payment-link.read","sales.tools.payment-link","sales.tools.settings.read","sales.tools.settings","sales.tools.salesorder.read","sales.tools.salesorder","contact.tools.customer.read","contact.tools.customer","catalog.tools.item.read","catalog.tools.item","lending.tools.servicing.read","money-onboarding.tools.application"]}],["setup.shopify.com",{provider:"shopify",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!1}],["mcp.cloudflare.com",{provider:"cloudflare",clientRegistration:"dynamic",unauthenticatedConnect:!1,rejectsCustomSchemeRedirects:!1,scopes:["user:read","account:read","offline_access","d1.metadata_read","d1.read","d1.write","workers-scripts.read","workers-scripts.write","workers-routes.read","workers-routes.write","workers-tail.read","workers-kv-storage.metadata_read","workers-kv-storage.read","workers-kv-storage.write","workers-r2.metadata_read","workers-r2.read","workers-r2.write","workers-r2-bucket-item.read","workers-r2-bucket-item.write","workers-observability.read","workers-observability.write","dns.read","dns.write","zone.read","zone.write"],pinsScopesOverConfiguredScopes:!0,scopesPinGate:"mcp_cloudflare_api_oauth_scopes"}],["mcp.shop.com",{provider:"shop",clientRegistration:"static",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,backendOnlyTokenExchange:!0,scopes:["openid","personal_agent"],pinsScopesOverConfiguredScopes:!0,authorizationParams:{resource:ab}}],["api.elections.kalshi.com",{provider:"kalshi",clientRegistration:"dynamic",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0}],["mcp.squarespace.com",{provider:"squarespace",clientRegistration:"dynamic",unauthenticatedConnect:!0,rejectsCustomSchemeRedirects:!0}]]),db=[".databricks.com",".azuredatabricks.net"];const hb=/^\/sncapps\/mcp-server\/mcp\/[^/]+$/,pb={provider:"databricks",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,requiresHostedCallback:!0,unauthenticatedConnect:!1,backendOnlyTokenExchange:!0,scopes:["ai-gateway","offline_access"],pinsScopesOverConfiguredScopes:!0},fb={provider:"servicenow",clientRegistration:"static",rejectsCustomSchemeRedirects:!0,unauthenticatedConnect:!1,unauthenticatedEndpointBlocked:!0,backendOnlyTokenExchange:!0,ownMcpJsonClientMayExchange:!0};function mb(e){if(void 0===e)return;let t;try{t=new URL(e)}catch{return}return function(e){return"https:"===e.protocol&&""===e.port&&""===e.username&&""===e.password&&function(e){const t=e.toLowerCase();return!(!/^[a-z0-9.-]+$/.test(t)||t.includes("..")||t.startsWith("."))&&db.some((e=>t.endsWith(e)&&t.length>e.length))}(e.hostname)&&"/ai-gateway/mcp-services/system.ai.genie_one_mcp"===e.pathname.replace(/\/+$/,"")}(t)?pb:function(e){return"https:"===e.protocol&&""===e.port&&""===e.username&&""===e.password&&hb.test(e.pathname.replace(/\/+$/,""))}(t)?fb:(r=t.hostname,ub.get(r.toLowerCase()));var r}function gb(e){return e.endsWith("/")?e:`${e}/`}async function wb(e,t){if(void 0===t)return;const r=new URL(e),n=new URL(t);if(r.origin!==n.origin||!gb(r.pathname).startsWith(gb(n.pathname)))throw new Error(`Protected resource ${t} does not match expected ${r.href} (or origin)`);return n}const yb=/^\/shops\/[A-Za-z0-9-]+\/mcp$/;function vb(e){if(void 0!==e)try{return new URL(e)}catch{return}}async function bb(e,t){if(void 0===t)return;const r=new URL(e),n=vb(t);if(void 0===n||n.origin!==r.origin||n.pathname!==r.pathname&&!yb.test(n.pathname))throw new Error(`Protected resource ${t} does not match expected ${r.href} (or origin)`);return n}function Sb(e){const t=vb(e);return void 0===t?void 0:lb.get(t.hostname.toLowerCase())}const kb=new Set([...ub].filter((([,e])=>"google-workspace"===e.provider)).map((([e])=>e))),_b="https://www.cursor.com/bot/mcp/oauth/callback",Cb={portal:"https://www.cursor.com/agents/mcp/oauth/callback",grokBotBounce:_b},Eb="tailnet_";new Set([`${Eb}waiting_for_approval`,`${Eb}tailnet_locked`,`${Eb}joining`]);const xb="grokbot://mcp/oauth/callback",Pb="http://localhost:8787/callback",Rb="gb";function Ib(e){const t=new URL(Pb);return t.port=String(e),t.toString()}function Tb(e){try{const t=new URL(e);if("http:"!==t.protocol)return!1;const r=t.hostname;return"localhost"===r||"127.0.0.1"===r||"[::1]"===r}catch{return!1}}function Ab(e){const t=e.redirectUrl??Pb;if(!0!==e.loopbackIpv4||!Tb(t))return t;const r=new URL(t);return r.hostname="127.0.0.1",r.toString()}function $b(e,t=Cb){const r=new Set,n=void 0!==e&&Tb(e);return e&&!n&&r.add(e),r.add(t.portal),e===xb&&r.add(t.grokBotBounce),r.add(Pb),e&&n&&r.add(e),Array.from(r)}function Mb(e){var t;if(void 0!==e&&0!==e.length)try{const r=JSON.parse(e);if("object"==typeof(t=r)&&null!==t&&!Array.isArray(t))return r}catch{}}function Db(e){if(void 0===e)return{};const t={};"string"==typeof e.title&&e.title.length>0&&(t.title=Vo(e.title,256));for(const r of["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"])"boolean"==typeof e[r]&&(t[r]=e[r]);return function(e){return!0===e?.[Xv]}(e)&&(t[Xv]=!0),0===Object.keys(t).length?{}:{annotationsJson:JSON.stringify(t)}}new Map([[Rb,xb],["gw",Qv],["gd",Pb],["xa",Yv],["xc",eb],["xl",tb],...[18787,28787,31787].map((e=>[`gd${e}`,Ib(e)]))]),new Map([[xb,Rb],[_b,Rb],[Qv,"gw"],[Yv,"xa"],[eb,"xc"],[tb,"xl"]]),Ab({loopbackIpv4:!0});var Ob=r("../mcp-core/dist/transport/mcp-url-utils.js");function Fb(e){return e.trim().toLowerCase()}const Nb="";function Lb({mode:e,tools:t}){const r=(t??[]).map(Fb).filter((e=>e.length>0)),n=void 0===e?void 0:Fb(e);return"all"===n?{mode:"all"}:"reads"===n?{mode:"reads"}:r.length>0?{mode:"custom",tools:r}:{mode:"all"}}function jb(e,t){switch(e.mode){case"all":return!0;case"custom":return function(e,t){const r=Fb(e);return 0!==r.length&&r!==Nb&&t.some((e=>Fb(e)===r))}(t.name,e.tools);case"reads":return void 0!==(r=t.annotations)&&!0!==r.destructiveHint&&!0===r.readOnlyHint;default:return e}var r}function Ub(e,t){switch(t.mode){case"all":return[`${e}:*`];case"custom":return t.tools.filter((e=>Fb(e)!==Nb)).map((t=>`${e}:${t}`));case"reads":return[];default:return t}}const Bb=new Set(["ash","bash","csh","dash","fish","ksh","powershell","pwsh","sh","tcsh","zsh","cmd"]);function Wb(e){return e.trim().split(/\s+/).filter(Boolean)}function Hb(e){const t=function(e){const t=e.trim(),r=t[0];if('"'===r||"'"===r){const e=t.indexOf(r,1);if(-1!==e)return t.slice(0,e+1)}return Wb(t)[0]}(e);if(!t)return!1;const r=t.replace(/^["']|["']$/g,"").replaceAll("\\","/").split("/"),n=(r[r.length-1]??"").replace(/\.exe$/i,"").toLowerCase();return Bb.has(n)}function qb(e,t){if(e.length>t.length)return!1;for(let r=0;r=t.tokenCount)continue;let a=!0;for(const t of e.tokens)if(!n.has(t)){a=!1;break}if(!a)continue;const c=qb(e.tokens,t.tokens);void 0!==o?e.tokenCount>o.tokenCount?(o=e,s=c):e.tokenCount===o.tokenCount&&c&&!s&&(o=e,s=!0):(o=e,s=c)}void 0!==o&&(t.indentLevel=o.indentLevel+1,t.ancestorIds=[...o.ancestorIds,t.id])}const n=r.filter((e=>!r.some((t=>t.id!==e.id&&t.tokenCounte.id));return{options:r,defaultSelectedOptionIds:n}}(e),n=[...r.defaultSelectedOptionIds];if(!t||0===t.length)return{defaultSelectedOptionIds:n,hasClassifierSuggestions:!1};const o=[],s=new Set;for(const e of t){const t=r.options.find((t=>t.id===e));if(t){o.push(t.id),s.add(Gb(t.id));continue}const n=r.options.filter((t=>t.id.startsWith(`${e} `)||t.id===e)),i=r.options.filter((t=>e.startsWith(`${t.id} `)||e===t.id));if(i.length>0){const e=i.reduce(((e,t)=>e.id.length>t.id.length?e:t));o.push(e.id),s.add(Gb(e.id))}else if(n.length>0){const e=n.reduce(((e,t)=>e.id.length!s.has(Gb(e))));return{defaultSelectedOptionIds:[...new Set([...i,...o])],hasClassifierSuggestions:!0}}(e,t).defaultSelectedOptionIds}const Kb=["com.todesktop.230313mzl4w4u92","co.anysphere.cursor","com.anysphere.molten-glass"],Jb=["cursor","molten glass"];function Zb(e){return Kb.some((t=>e===t||e.startsWith(`${t}.`)))}const Xb=[{bundleId:"com.apple.scripteditor2",name:"Script Editor"},{bundleId:"com.apple.automator",name:"Automator"},{bundleId:"com.apple.shortcuts",name:"Shortcuts"}],Qb=[{bundleId:"com.apple.terminal",name:"Terminal"},{bundleId:"com.googlecode.iterm2",name:"iTerm",aliases:["iTerm2"]},{bundleId:"dev.warp.warp-stable",name:"Warp"},{bundleId:"dev.warp.warp-preview",name:"WarpPreview",aliases:["Warp Preview"]},{bundleId:"com.mitchellh.ghostty",name:"Ghostty"},{bundleId:"org.alacritty",name:"Alacritty"},{bundleId:"net.kovidgoyal.kitty",name:"kitty"},{bundleId:"com.github.wez.wezterm",name:"WezTerm"},{bundleId:"co.zeit.hyper",name:"Hyper"},{bundleId:"org.tabby",name:"Tabby"},...Xb,{bundleId:Kb[0],name:"Cursor"}];function Yb(e){const t=e.toLowerCase(),r=(0,s.basename)(e,".app").toLowerCase(),n=Qb.find((({bundleId:e,name:n,aliases:o=[]})=>e===t||[n,...o].some((e=>{const n=e.toLowerCase();return n===t||n===r}))));return void 0!==n?{bundleId:n.bundleId,name:n.name}:Zb(t)?{bundleId:t,name:"Cursor"}:[t,r].some((e=>Jb.some((t=>e===t||e.startsWith(`${t} `)))))?{bundleId:Kb[0],name:"Cursor"}:void 0}const eS=new Set(["com.apple.systempreferences","com.apple.keychainaccess","com.apple.passwords","com.1password.1password","com.agilebits.onepassword7","com.bitwarden.desktop","com.lastpass.lastpass","org.keepassxc.keepassxc"]);function tS(e){return eS.has(e.toLowerCase())}function rS(e){return`app/${e}`}function nS(e){return"object"==typeof e&&null!==e}function oS(e){return iS.includes(e)}function sS(e){if(!nS(e))return;const{appArg:t,appSelectorArgs:r,capturesScreen:n}=e;if("boolean"==typeof n){if(void 0!==r){if(void 0!==t||!nS(r))return;const e={};for(const[t,n]of Object.entries(r)){if(!oS(t)||"string"!=typeof n||0===n.length)return;e[t]=n}if(0===Object.keys(e).length)return;return{appSelectorArgs:e,capturesScreen:n}}return void 0===t?{capturesScreen:n}:"string"==typeof t&&t.length>0?{appArg:t,capturesScreen:n}:void 0}}const iS=["pid","bundleId","path","appName"],aS=/^[+-]?\d+$/;var cS=r("../../node_modules/.pnpm/diff@8.0.3/node_modules/diff/libesm/patch/create.js");const lS=".cursor/worktrees",uS=".grok/build-desktop/worktrees",dS="win32"===process.platform||"darwin"===process.platform,hS=new Map;function pS(e,t){if(!(0,Yo.BJ)(t,e))return;const r=(dS?(0,s.relative)(e.toLowerCase(),t.toLowerCase()):(0,s.relative)(e,t)).split(s.sep).filter(Boolean);return r.length>0?r:void 0}function fS(e,t){const r=pS(e,t);if(void 0!==r)return r;const n=function(e){if(hS.has(e))return hS.get(e);const t=[];let r,n=e;for(;;)try{const e=xo.realpathSync.native(n);r=0===t.length?e:(0,s.join)(e,...t);break}catch(e){const r=Sc(e);if("ENOENT"!==r&&"ENOTDIR"!==r)break;const o=(0,s.dirname)(n);if(o===n)break;t.unshift((0,s.basename)(n)),n=o}return hS.size>=64&&hS.clear(),hS.set(e,r),r}(e);var o,i;return void 0!==n&&(o=n,i=e,dS?o.toLowerCase()!==i.toLowerCase():o!==i)?pS(n,t):void 0}function mS(e){const t=e?.trim();return t&&".cursor"!==t?[".cursor",t]:[".cursor"]}function gS(e,t){const r=(0,o.homedir)();return mS(t?.dataFolderName).some((t=>void 0!==fS((0,s.join)(r,t,"projects"),e)))}function wS(e){const t=(0,o.homedir)();return[lS,uS].some((r=>void 0!==fS((0,s.join)(t,...r.split("/")),e)))}function yS(e,t,r){const n=function(e,t){const r=(0,o.homedir)();for(const n of mS(t?.dataFolderName)){const t=fS((0,s.join)(r,n,"projects"),e);if(void 0!==t&&t.length>=2)return t[1]}}(e,r);return void 0!==n&&(dS?t.some((e=>e.toLowerCase()===n.toLowerCase())):t.includes(n))}function vS(e,t,r){const n=fS(e,t);if(void 0===n)return!1;const o=n[0];return dS?r.some((e=>e.toLowerCase()===o.toLowerCase())):r.includes(o)}const bS=/[\s"'`=/\\:;()[\]{},&|<>]/,SS="win32"===process.platform||"darwin"===process.platform;async function kS(e,t,r,n){const o=RS(await PS((0,s.join)(e,"gitdir")),"");if(void 0===o)return;const i=(0,s.resolve)(e,o);if(".git"!==(0,s.basename)(i)||(0,qs.$f)(i))return;const a=(0,s.dirname)(i);if(r&&wS(a))return;const c=await IS(i);if(void 0===c)return;const l=(0,s.dirname)(c);if(r&&wS(l))return;if(void 0!==n&&(u=AS(a,l)?[l]:[a,l],d=n.command,!(void 0!==(h=n.realWorkingDirectory)&&u.some((e=>(0,Yo.BJ)(h,e)))||void 0!==d&&u.some((e=>{const t=(0,s.basename)(e);return t.length>0&&function(e,t){const r=SS?e.toLowerCase():e,n=SS?t.toLowerCase():t;let o=0;for(;;){const e=r.indexOf(n,o);if(-1===e)return!1;const t=0===e||bS.test(r[e-1]),s=e+n.length,i=s===r.length||bS.test(r[s]);if(t&&i)return!0;o=e+1}}(d,t)})))))return;var u,d,h;const p=await xS(i,c);return void 0!==p&&AS(p.commonDir,t)?l:void 0}async function _S(e,t){const r=await(0,Co.readdir)(e).catch(TS);return void 0===r?[]:r.sort().slice(0,t)}function CS(e,t){return t.some((t=>(0,Yo.BJ)(t,e)))}async function ES(e){for(let t=e;;t=(0,s.dirname)(t)){if((0,qs.$f)(t))return;const e=(0,s.join)(t,".git"),r=await(0,Co.lstat)(e).catch(TS);if(r?.isFile())return(await xS(e))?.commonDir;if(r?.isDirectory())return e;if(void 0!==r||(0,s.dirname)(t)===t)return}}async function xS(e,t){const r=RS(await PS(e),"gitdir: ");if(void 0===r)return;const n=await IS((0,s.resolve)((0,s.dirname)(e),r));if(void 0===n||"worktrees"!==(0,s.basename)((0,s.dirname)(n)))return;const o=(0,s.dirname)((0,s.dirname)(n));if(".git"!==(0,s.basename)(o))return;const i=RS(await PS((0,s.join)(n,"commondir")),"");if(void 0===i)return;const a=await IS((0,s.resolve)(n,i));if(void 0===a||!AS(a,o))return;const c=RS(await PS((0,s.join)(n,"gitdir")),"");if(void 0===c)return;const[l,u]=await Promise.all([IS((0,s.resolve)(n,c)),t??IS(e)]);return void 0!==l&&void 0!==u&&AS(l,u)?{commonDir:o,realDotGit:u}:void 0}async function PS(e){const t=await(0,Co.lstat)(e).catch(TS);if(void 0!==t&&t.isFile()&&!(t.size>4096))return(0,Co.readFile)(e,"utf8").catch(TS)}function RS(e,t){const r=e?.split("\n",1)[0]?.replace(/\r$/,"");if(void 0===r||!r.startsWith(t))return;const n=r.slice(t.length);return n.length>0&&!n.includes("\0")?n:void 0}async function IS(e){if(!(0,qs.$f)(e))return(0,Co.realpath)(e).catch(TS)}function TS(e){const t=Sc(e);if(void 0===t||t.startsWith("ERR_"))throw e}function AS(e,t){return SS?e.toLowerCase()===t.toLowerCase():e===t}function $S(e,t,r){return{resolvedPath:e,originalPath:t,resolution:r}}function MS(e){const t=Sc(e);switch(t){case"ENOENT":return{status:"newFile"};case"EACCES":case"EPERM":return{status:"permissionDenied",errno:t};case"ELOOP":return{status:"symlinkLoop",errno:t};default:return{status:"unknownError",errno:t??"UNKNOWN",message:kc(e)}}}async function DS(e,t){const r=(0,Yo.o1)(e,t);try{return $S(await(0,Co.realpath)(r),r,{status:"resolved"})}catch(e){if("ENOENT"!==Sc(e))return $S(r,r,MS(e));try{if((await(0,Co.lstat)(r)).isSymbolicLink()){let e=null;try{e=await(0,Co.readlink)(r)}catch{}return $S(r,r,{status:"danglingSymlink",symlinkTarget:e})}try{return $S(await(0,Co.realpath)(r),r,{status:"resolved"})}catch(e){if("ENOENT"!==Sc(e))return $S(r,r,MS(e))}return $S(r,r,{status:"unknownError",errno:"ENOENT",message:"realpath returned ENOENT but lstat found a non-symlink entry"})}catch(e){return"ENOENT"===Sc(e)?async function(e){let t=(0,s.dirname)(e);const r=[(0,s.basename)(e)];for(;(0,s.dirname)(t)!==t;){try{const n=await(0,Co.realpath)(t);return $S((0,s.join)(n,...r),e,{status:"newFile"})}catch(t){if("ENOENT"!==Sc(t))return $S(e,e,MS(t))}r.unshift((0,s.basename)(t)),t=(0,s.dirname)(t)}return $S(e,e,{status:"newFile"})}(r):$S(r,r,MS(e))}}}function OS(e){return"resolved"===e.status||"newFile"===e.status}function FS(e,t){switch(t.status){case"resolved":case"newFile":return"";case"danglingSymlink":return`Write blocked: \`${e}\` is a dangling symlink${t.symlinkTarget?` (target: ${t.symlinkTarget})`:""}. Cannot verify it does not point to a protected file.`;case"permissionDenied":return`Write blocked: cannot verify \`${e}\` -- permission denied resolving symlinks (${t.errno}).`;case"symlinkLoop":return`Write blocked: \`${e}\` has a symlink loop (${t.errno}). Cannot verify target.`;case"unknownError":return`Write blocked: cannot verify \`${e}\` -- ${t.errno}: ${t.message}.`;default:return`Write blocked: unknown resolution status for \`${e}\`.`}}function NS({realAbsolutePath:e,setting:t,resolvedWorkspaceRoots:r,resolvedAllowFolders:n,resolvedAllowGlobs:o}){return!("workspace"!==t.boundary||LS(e,r)||LS(e,n)||US(e,t.allowPaths)||US(e,o))}function LS(e,t){return t.some((t=>(0,Yo.BJ)(e,t)))}function jS(e){return e.flatMap((e=>{const t=(0,Yo.jl)(e.trim());return!t.includes("*")&&(0,s.isAbsolute)(t)?[(0,s.resolve)(t)]:[]}))}function US(e,t){const r="win32"===process.platform?Yo.oL:e=>e,n=r(e);return t.some((e=>{const t=(0,Yo.jl)(e.trim());return!(!t.includes("*")&&(0,s.isAbsolute)(t))&&(0,ms.T)(r(t),n)}))}const BS={caffeinate:{flags:["-d","-i","-m","-s","-u"],valueOptions:["-t","-w"]},command:{flags:["-p"],valueOptions:[],lookupFlags:["-v","-V"]},env:{flags:["-","-i","-0","-v","--ignore-environment","--null","--debug"],valueOptions:["-u","-C","--unset","--chdir"],assignments:!0,directoryOptions:["-C","--chdir"]},nice:{flags:[],valueOptions:["-n","--adjustment"],numericOption:!0},nohup:{flags:[],valueOptions:[]},stdbuf:{flags:[],valueOptions:["-i","-o","-e","--input","--output","--error"]},time:{flags:["-p"],valueOptions:[]},timeout:{flags:["-f","-p","-v","--foreground","--preserve-status","--verbose"],valueOptions:["-k","-s","--kill-after","--signal"],operands:1},xargs:{flags:["-0","-o","-p","-r","-t","-x","--null","--open-tty","--interactive","--no-run-if-empty","--verbose","--exit","--show-limits"],valueOptions:["-a","-d","-E","-I","-J","-L","-n","-P","-R","-S","-s","--arg-file","--delimiter","--max-args","--max-procs","--max-chars","--process-slot-var"],attachedValueOptions:["-e","-i","-l","--eof","--replace","--max-lines"],readsArguments:!0}};function WS(e){const t=[];let r=!0,n=!1,o=e;for(;;){const e=BS[s.posix.basename(o.name)];if(void 0===e)return{command:o,wrapperForms:t,allowlistable:r,readsArguments:n};const i=HS(o.args,e);if("unreadable"===i)return{command:o,wrapperForms:t,allowlistable:!1,readsArguments:n};if("none"===i)return{command:o,wrapperForms:t,allowlistable:r,readsArguments:n};const[a,...c]=o.args.slice(i);if(void 0===a||!KS(a))return{command:o,wrapperForms:t,allowlistable:!1,readsArguments:n};(o.name.includes("/")||o.args.slice(0,i).some((t=>qS(t,e)||zS(t.value,e))))&&(r=!1),n||=!0===e.readsArguments,t.push(o.fullText.trim()),o=new he.Pv({name:a.value,args:c,fullText:[a.value,...c.map((e=>e.value))].join(" ")})}}function HS(e,t){let r=0;for(;rt.startsWith("--")?e===t||e.startsWith(`${t}=`):/^-[^-]/.test(e)&&e.includes(t.slice(1))))}function GS(e,t,r){const n=e=>!0===r.attachedValueOptions?.includes(e);if(r.flags.includes(e)||n(e))return 1;if(e.startsWith("--")){const o=e.indexOf("=");if(-1!==o){const t=e.slice(0,o);return r.valueOptions.includes(t)||n(t)?1:void 0}if(!r.valueOptions.includes(e))return;return void 0===t?void 0:2}for(let o=1;o{const t=await DS(e);return OS(t.resolution)?t.resolvedPath:(0,Yo.o1)(e)})))}function uk(e,t,r){return`${e} blocked: cannot verify ${t} \`${r}\` while resolving symlinks. This can happen when access is denied or the path contains a symlink loop.`}function dk(e){return[...new Set(e)]}function hk(){return{fdTargets:new Map([[0,"original-stdin"],[1,"original-stdout"],[2,"original-stderr"]])}}function pk({basePath:e,targetPath:t,pathModule:r}){const n=r.resolve(e),o=r.resolve(t),s=r.relative(n,o);return""===s||".."!==s&&!s.startsWith(`..${r.sep}`)&&!r.isAbsolute(s)}function fk(e){return">"===e||">>"===e||">|"===e||"&>"===e||"&>>"===e}function mk(e){return"<"!==e.operator&&"<&"!==e.operator}function gk(e){if(void 0===e||e.trim()!==e)return;const t=Number(e);return Number.isInteger(t)&&t>=0?t:void 0}function wk(e){return"<<"===e.operator&&"heredoc_redirect"===e.targetNodeType&&1===e.destinationFds.length&&0===Number(e.destinationFds[0])&&void 0!==e.targetText}function yk(e,t){return!(/^=|[~*?[{(#^`]/.test(e)||"\\"!==t.sep&&e.includes("\\"))}function vk(e){return"word"===e.type||"number"===e.type?yk(e.value,s)?e.value:void 0:"raw_string"===e.type||"string"===e.type&&!/[$`\\]/.test(e.value)?e.value.slice(1,-1):void 0}function bk({command:e,readsArguments:t}){if(!function(e){const t=e.replace(/["']/g,"");return[t,t.replace(/\\/g,"")].some((e=>/^tee(?:-object)?(?:\.exe)?$/i.test(e.slice(Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"))+1))))}(e.name))return[];const r=e.args.map(vk);return t?[...r,void 0]:r}const Sk=new Set(["cd","chdir","pushd"]),kk=new Set(["popd","eval","source",".","trap","set-location","sl","push-location","pop-location"]);function _k(e){const t=e.replace(/["'\\]/g,"");return t.slice(t.lastIndexOf("/")+1).toLowerCase()}function Ck(e,t){return new he.Pv({name:e,args:t,fullText:[e,...t.map((e=>e.value))].join(" ")})}function Ek(e){let t=e;for(;;){const e=_k(t.name);if("command"===e){const e=Ck("command",t.args),r=WS(e).command;if(r!==e){t=r;continue}const n=t.args[0]?.value;return void 0===n||"-v"===n||"-V"===n?t:"unreadable"}if("builtin"!==e)return t;const r="--"===t.args[0]?.value?t.args.slice(1):t.args,[n,...o]=r;if(void 0===n)return t;const s=vk(n);if(void 0===s||s.startsWith("-"))return"unreadable";t=Ck(s,o)}}function xk(e,t){return!(!t.isAbsolute(e)||"/"!==t.sep&&/^[\\/]$/.test(t.parse(e).root))}async function Pk({parsingResult:e,workingDirectory:t,resolvePathForPermissions:r,pathModule:n}){const o=[t];for(const t of e.executableCommands.map(WS)){const e=Ek(t.command);if("unreadable"===e)return;const i=_k(e.name),a=e.args;if(kk.has(i)||/^cd\.\./.test(s=i)||/^[a-z]:$/.test(s))return;if(!Sk.has(i))continue;const c=1===a.length&&void 0!==a[0]?vk(a[0]):void 0;if(void 0===c||!xk(c,n))return;const l=await r(c);if(!OS(l.resolution))return;o.push(l.resolvedPath)}var s;return o}async function Rk({targetText:e,workingDirectory:t,workingDirectories:r,...n}){const o=xk(e,n.pathModule)?[t]:r;if(void 0===o)return;let s;for(const t of o)if(s=await Ik({...n,targetText:e,workingDirectory:t}),void 0===s)return;return s}async function Ik({targetText:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:o,pathModule:s,tempPathOptions:i}){if(""!==s.parse(e).root&&!s.isAbsolute(e))return;const a=await o(e,t);if(!OS(a.resolution))return;const c=[];for(const e of r){const t=await o(e);OS(t.resolution)&&c.push(t.resolvedPath)}return await async function({targetPath:e,rootPaths:t,pathModule:r}){if(e.split(r.sep).some((e=>".git"===e.toLowerCase())))return!0;for(const r of t)if(await(0,Oo.OK)(e,r).catch((()=>!0)))return!0;return!1}({targetPath:a.resolvedPath,rootPaths:c,pathModule:s})?void 0:c.some((e=>pk({basePath:e,targetPath:a.resolvedPath,pathModule:s})))?"workspace-file":n&&!(0,Oo.dA)(a.originalPath)&&Wk(a.resolvedPath,i)?"tmp-file":void 0}async function Tk({parsingResult:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n}){const i=await Pk({parsingResult:e,workingDirectory:t,resolvePathForPermissions:DS,pathModule:s});for(const a of e.executableCommands.map(WS).flatMap(bk))if("/dev/null"!==a&&(void 0===a||!await Rk({targetText:a,workingDirectory:t,workingDirectories:i,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:DS,pathModule:s,tempPathOptions:{platform:process.platform,env:process.env,pathModule:s,homeDirectory:(0,o.homedir)()}})))return!1;return!0}function Ak(e){return dk(e.map((e=>e.trim())).filter(Boolean))}function $k(e){const t=e.name.trim();if(!t)return[];const r=e.arguments.map((e=>e.trim())).filter(Boolean),n=r.length>0?`${t} ${r.join(" ")}`:t,o=e.subcommandTokens.map((e=>e.trim())).filter(Boolean);if(0===o.length)return[n];const s=`${t} ${o.join(" ")}`;return s===n?[n]:[n,s]}function Mk(e,t){const r=t.trim();return!!r&&e.some((e=>e===r||e.startsWith(`${r} `)))}function Dk(e){const t=e.name.trim(),r=e.arguments.map((e=>e.trim())).filter(Boolean).map((e=>new he.r6({type:"word",value:e})));return new he.Pv({name:t,args:r,fullText:[t,...r.map((e=>e.value))].join(" ").trim()})}function Ok(e,t={}){return{type:e,...t}}function Fk(e){return void 0!==e&&("deny"===e.default||void 0!==e.allow&&e.allow.length>0||void 0!==e.deny&&e.deny.length>0)}function Nk(...e){return e.filter((e=>void 0!==e)).join(" • ")}function Lk(e){const t=[];for(const r of e){const e=r.match(/^\s*Read\s*\((.*)\)\s*$/);e&&t.push((e[1]??"").trim())}return t}function jk(e,t){if("workspace"===e&&void 0!==t)return t}const Uk={workspace:0,system:1};function Bk(e){const t=e.match(/^\s*(Shell|Bash)\s*\((.*)\)\s*$/);if(!t)return null;const r=t[1];if("Shell"!==r&&"Bash"!==r)return null;const n=t[2]?.trim()??"",o=n.indexOf(":");return-1!==o?{shellType:r,fullPattern:n,commandPattern:n.slice(0,o).trim(),argsPattern:n.slice(o+1).trim()}:{shellType:r,fullPattern:n,commandPattern:n,argsPattern:null}}function Wk(e,{platform:t,env:r,pathModule:n,homeDirectory:o}){if((0,Oo.dA)(e))return!1;if("win32"===t){const t=r.TEMP??r.TMP;if(t){const r=n.normalize(t).toLowerCase(),o=n.normalize(e).toLowerCase(),s=r.endsWith(n.sep)?r:r+n.sep;return o===r||o.startsWith(s)}return!1}const s=e=>{const r=n.normalize(e);return"darwin"!==t?r:"/tmp"===r||r.startsWith("/tmp/")||"/var"===r||r.startsWith("/var/")?`/private${r}`:r},i=s(e);return(void 0===o||!pk({basePath:s(o),targetPath:i,pathModule:n}))&&("darwin"===t?["/private/tmp/","/private/var/folders/"].some((e=>i.startsWith(e))):["/tmp/","/private/tmp/","/var/folders/","/private/var/folders/","/var/tmp/"].some((e=>i.startsWith(e))))}function Hk(e,t){if("insecure_none"===t.type)return!0;if("insecure_none"===e.type)return!1;const r=(0,Oo.$b)(e.networkPolicy),n=(0,Oo.$b)(t.networkPolicy);if(r&&!n)return!1;const o=(0,Oo._B)(e.networkPolicy),s=(0,Oo._B)(t.networkPolicy);if(o&&n&&!s)return!1;if("workspace_readonly"===e.type&&"workspace_readwrite"===t.type)return!0;if("workspace_readwrite"===e.type&&"workspace_readonly"===t.type)return!1;const i=e.readBoundary??"system",a=t.readBoundary??"system";return!(Uk[i]>Uk[a])}function qk(e){return{wrapperForms:e.flatMap((e=>e.wrapperForms)),allowlistable:e.every((e=>e.allowlistable)),readsArguments:e.some((e=>e.readsArguments))}}function zk(e){return[...e.wrapperForms,e.command.fullText.trim()].filter(Boolean)}class Gk{constructor(e,t,r,n,o){this.command=e,this.requestedPolicy=t,this.wrapperForms=o?.wrapperForms??[],this.allowlistable=o?.allowlistable??!0,this.readsArguments=o?.readsArguments??!1;const s=void 0!==r&&Hk(t,r);this.state=s?"preapproved":"approvable";const i=[e.fullText.trim()].filter(Boolean);this.matchForms=n&&n.length>0?[...n]:i}approveWithPolicy(e){"approvable"!==this.state&&"preapproved"!==this.state||!Hk(this.requestedPolicy,e)||(this.state="allowlisted")}deny(){this.state="denied"}isRunnable(){return"preapproved"===this.state||"allowlisted"===this.state}}function Vk(e){return e?.type??"undefined"}const Kk=["skills","skills-cursor","rules","plugins"],Jk=["assets","agent-notes","agent-tools","swarm-agents"];async function Zk(e,t,r){return e.shouldBlockFileRead?.(t,r)??e.shouldBlockRead(t,r)}function Xk(e){const t=e.lastIndexOf("::mcpScope:");return-1===t?e:e.slice(0,t)}function Qk({server:e,tool:t}){const r=e=>e.length>0&&e.length<=256&&!/[:*]/.test(e),n=e.trim().toLowerCase(),o=t.trim().toLowerCase();return r(n)&&r(o)?`${n}:${o}`:void 0}const Yk=/^\s*Read\s*\((.*)\)\s*$/,e_=/^\s*Write\s*\((.*)\)\s*$/;class t_{constructor(e,t,r,n,i,a=!1,c){this.ignoreService=e,this.pendingDecisionStore=t,this.permissionsProvider=r,this.teamSettingsService=n,this.adminNetworkControlsEnabled=a,this.computerUseAppsAllowedForSession=[],this.rootDirectories=Array.isArray(i)?i:[i??process.cwd()],this.projectDir=c?.projectDir,this.perUserSandboxConfigPath=c?.perUserSandboxConfigPath??(0,s.join)((0,o.homedir)(),".cursor","sandbox.json"),this.mcpAllowlistLog=c?.mcpAllowlistLog,this.computerUse=c?.computerUse,this.computerUseAdminPolicy=c?.computerUseAdminPolicy,this.enforceMcpAdminToolLimits=c?.enforceMcpAdminToolLimits,this.onMcpAdminToolLimitCheck=c?.onMcpAdminToolLimitCheck}async shouldBlockRead(e,t={}){return this.shouldBlockReadInternal(e,t,!1)}async shouldBlockFileRead(e,t={}){return this.shouldBlockReadInternal(e,t,!0)}async getFileReadBoundaryBlocker(){const{perms:e,setting:t}=await this.readControlSetting(),r=e.deny.filter((e=>this.isPathEntry("Read",e))),n="workspace"===t.boundary&&"unrestricted"!==e.approvalMode;if(!n&&0===r.length)return;const[o,s,i]=n?await Promise.all([this.resolveWorkspaceReadRoots(e.userSandboxDataFolderName),this.resolvedReadAllowFolders(t.allowPaths),this.resolvedReadAllowGlobs(t.allowPaths)]):[[],[],[]],a=r.map((e=>this.compileReadDenyMatcher(e))),c=e=>a.some((t=>t(e)));return async(e,r)=>c(e)||c(r)||n&&NS({realAbsolutePath:r,setting:t,resolvedWorkspaceRoots:o,resolvedAllowFolders:s,resolvedAllowGlobs:i})}async readControlSetting(){const e=await this.getPermissions(),{enabled:t,...r}=await this.adminReadControls(e);return{perms:e,setting:function(e){if(!e.enabled)return{boundary:"system",allowPaths:[],enforcedByAdmin:!1};const t="workspace"===e.admin.boundary,r=t||"workspace"===e.local.boundary?"workspace":"system",n=t?e.admin.allowPaths:[];return{boundary:r,allowPaths:t&&!1===e.admin.allowUserOverride?[...n]:[...new Set([...n,...e.local.allowPaths])],enforcedByAdmin:t}}({enabled:t,admin:r,local:{boundary:e.readBoundary,allowPaths:Lk(e.allow)}})}}async adminReadControls(e){const t=e.teamAdminPolicy,r=this.teamSettingsService.isReadControlEnabled?.()??!0;if(void 0!==t&&"unavailable"!==t){const e=await r;return"workspace"!==t.readBoundary?{enabled:e,boundary:void 0,allowPaths:[],allowUserOverride:void 0}:{enabled:e,boundary:"workspace",allowPaths:t.additionalReadPaths??[],allowUserOverride:t.allowUserOverrideReadPaths}}const[n,o]=await Promise.all([r,this.teamSettingsService.getSandboxingControls()]);return{enabled:n,boundary:o.readBoundary,allowPaths:o.readAllowlistPaths??[],allowUserOverride:o.allowUserOverrideReadAllowlist}}resolvedReadAllowFolders(e){return lk([...jS(e),...(0,Oo.r5)()])}async resolvedReadAllowGlobs(e){const t=function(e){return e.flatMap((e=>{const t=(0,Yo.jl)(e.trim()),r=t.indexOf("*");if(r<0||!(0,s.isAbsolute)(t))return[];const n="win32"===process.platform?Math.max(t.lastIndexOf("/",r),t.lastIndexOf("\\",r)):t.lastIndexOf("/",r);return n>=(0,s.parse)(t).root.length?[{folder:t.slice(0,n),rest:t.slice(n)}]:[]}))}(e),r=await lk(t.map((({folder:e})=>e)));return t.map((({rest:e},t)=>function(e,t,r={parse:s.parse}){return r.parse(e).root===e&&/[\\/]$/.test(e)?`${e}${t.slice(1)}`:`${e}${t}`}(r[t],e)))}async resolveWorkspaceReadRoots(e){const t=(0,s.join)((0,o.homedir)(),void 0!==e&&e.length>0?e:".cursor"),r=[...this.rootDirectories.map((e=>(0,s.join)(t,"projects",(0,So.r_)(e)))),...Kk.map((e=>(0,s.join)(t,e)))],n=this.rootDirectories.flatMap((e=>(0,Oo.W1)(e)??[]));return lk([...this.rootDirectories,...r,...n,...void 0===this.projectDir?[]:[this.projectDir]])}async shouldBlockReadInternal(e,{cursorIgnoreChecked:t=!1},r){const n=(0,Yo.o1)(e),o=await Cc(n);if(null===o)return{type:"unsafeResolution",message:uk("Read","path",n)};if(await this.ignoreService.isRepoBlocked(o))return{type:"adminBlock",source:"Team repo blocklist"};if(await this.isPathExplicitlyDenied("Read",n))return{type:"permissionsConfig"};if(!t&&!wS(o)&&!gS(o,{dataFolderName:(await this.getPermissions()).userSandboxDataFolderName})&&await this.ignoreService.isCursorIgnored(o))return{type:"cursorIgnore"};if(r){const e=await this.shouldBlockReadForBoundary(o);if(e)return e}return!1}async shouldBlockReadForBoundary(e){const{perms:t,setting:r}=await this.readControlSetting();if("workspace"!==r.boundary||"unrestricted"===t.approvalMode)return!1;const n=await this.resolveWorkspaceReadRoots(t.userSandboxDataFolderName);if(LS(e,n))return!1;const[o,s]=await Promise.all([this.resolvedReadAllowFolders(r.allowPaths),this.resolvedReadAllowGlobs(r.allowPaths)]);return!!NS({realAbsolutePath:e,setting:r,resolvedWorkspaceRoots:n,resolvedAllowFolders:o,resolvedAllowGlobs:s})&&{type:"needsApproval",approvalReason:r.enforcedByAdmin?"This reads a file outside your workspace and requires approval under your team's read policy.":"This reads a file outside your workspace.",approvalDetails:{type:"fileRead",path:e}}}async isProjectDirInternalPath(e,t){if(void 0===this.projectDir)return!1;const r=await DS(this.projectDir);return!!OS(r.resolution)&&vS(r.resolvedPath,e,t)}async isFreelyWritableOutsideWorkspace(e,t){return function(e){return Wk(e,{platform:process.platform,env:process.env,pathModule:s,homeDirectory:(0,o.homedir)()})}(e)||yS(e,Jk,{dataFolderName:t})||await this.isProjectDirInternalPath(e,Jk)}async shouldBlockWrite(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{QS(n,(0,$.VI)(e.withName("InteractivePermissionsService.shouldBlockWrite")),!1).ctx;const i=await DS(t);if(!OS(i.resolution))return{type:"unsafeResolution",message:FS(i.originalPath,i.resolution)};const a=i.resolvedPath,c=a;if(await this.ignoreService.isRepoBlocked(c))return{type:"adminBlock",source:"Team repo blocklist"};if(await this.isPathExplicitlyDenied("Write",a))return{type:"permissionsConfig"};const l=i.originalPath.split(s.sep).pop()?.toLowerCase()??"",u=a.split(s.sep).pop()?.toLowerCase()??"";if(".cursorignore"===l||".cursorignore"===u)return{type:"permissionsConfig"};if((0,Oo.dA)(i.originalPath)||(0,Oo.dA)(a))return{type:"permissionsConfig"};const d=await this.getPermissions();if(!wS(c)&&!gS(c,{dataFolderName:d.userSandboxDataFolderName})&&await this.ignoreService.isCursorIgnored(c))return{type:"cursorIgnore"};if("workspace_readonly"===d.userConfiguredPolicy.type)return{type:"permissionsConfig",isReadonly:!0};if(await this.isPathExplicitlyAllowed("Write",a))return!1;if("unrestricted"===d.approvalMode)return!1;const h=async()=>{let e,t,n="";try{n=await ji(a),e=!1}catch{e=!0}if(e)t=r;else{const e=e=>e.endsWith("\n")?e:`${e}\n`,{hunks:o}=(0,cS.YB)("a","b",e(n),e(r),"","",{context:2});t=o.map((e=>e.lines.map((e=>e.length>0?`${e[0]} ${e.slice(1)}`:e)).join("\n"))).join("\n...\n")}return{isNewFile:e,diffString:t}};let p;const f=[];for(const e of this.rootDirectories){const t=await DS(e);if(OS(t.resolution)){if((0,Yo.BJ)(a,t.resolvedPath)){p=t.resolvedPath;break}f.push(t.resolvedPath)}}const m=void 0===p?await async function(e,t,r={}){if(0===t.length)return;let n;for(let o=(0,s.dirname)(e);;o=(0,s.dirname)(o)){if((0,qs.$f)(o))return;const e=(0,s.join)(o,".git"),i=await(0,Co.lstat)(e).catch(TS);if(i?.isFile()){const s=await xS(e);if(void 0!==s){const{commonDir:e}=s;if(CS(o,t))return;if(t.some((t=>(0,Yo.BJ)(e,t))))return{root:o,commonDir:e};if(!await(r.isUntrustedExternalGitDir?.(e))&&(await(n??=Promise.all(t.map((e=>ES(e)))),n)).some((t=>void 0!==t&&AS(t,e))))return{root:o,commonDir:e}}}if((0,s.dirname)(o)===o)return}}(a,f,{isUntrustedExternalGitDir:e=>this.isFreelyWritableOutsideWorkspace(e,d.userSandboxDataFolderName)}):void 0;let g=!1;const w=p??m?.root;if(void 0!==w){const e=(0,s.relative)(w,a),t=e.split(s.sep).map((e=>"win32"===process.platform&&e.includes(":")?e.split(":")[0]:e));if(g=function(e){const t=e.replace(/\\/g,"/");return/(^|\/)\.cursor\/debug(?:-[a-zA-Z0-9-]+)?\.log$/i.test(t)}(e),!g){const e=await this.checkCursorFileProtection(t);if(e)return e}if("win32"===process.platform&&t.some((e=>e.includes("~")))){const{isNewFile:e,diffString:r}=await h();return{type:"needsApproval",approvalReason:`Protected config file: ${t[t.length-1]??""}`,approvalDetails:{type:"fileEdit",isNewFile:e,diffString:r,blockReason:"protectedConfig"}}}if(await(0,Oo.OK)(a,w)){const e=t[t.length-1]?.toLowerCase()??"",{isNewFile:r,diffString:n}=await h();return{type:"needsApproval",approvalReason:`Protected config file: ${e}`,approvalDetails:{type:"fileEdit",isNewFile:r,diffString:n,blockReason:"protectedConfig"}}}}if(void 0===p&&(void 0===m||"workspace"===(await this.readControlSetting()).setting.boundary)){if(await this.isFreelyWritableOutsideWorkspace(a,d.userSandboxDataFolderName))return!1;const e=`${(0,o.homedir)()}${s.sep}.cursor${s.sep}`;if(a.startsWith(e)){const e=a.split(s.sep).pop()?.toLowerCase()??"";if(e.endsWith(".md")||e.endsWith(".mdc")||".cursorrules"===e)return!1}const{isNewFile:t,diffString:r}=await h();return{type:"needsApproval",approvalReason:"Out of workspace",approvalDetails:{type:"fileEdit",isNewFile:t,diffString:r,blockReason:"outOfWorkspace"}}}if(g)return!1;if(!0===d.promptWorkspaceWrites){const{isNewFile:e,diffString:t}=await h();return{type:"needsApproval",approvalReason:"Workspace write",approvalDetails:{type:"fileEdit",isNewFile:e,diffString:t,blockReason:"workspaceWrite"}}}return!1}catch(e){n.error=e,n.hasError=!0}finally{YS(n)}}async shouldEnforceShellInvariantBlocks(e,t,r){const n=await this.getAdminCommandDenylistBlock(e,{command:t.command,parsingResult:t.parsingResult,toolCallId:t.toolCallId});if(void 0!==n)return{kind:"block",reason:n};const o=await Cc(t.workingDirectory);if(null===o){if(!0!==t.skipUnsafeWorkingDirectoryBlock)return{kind:"block",reason:{type:"unsafeResolution",message:uk("Command","working directory",t.workingDirectory)}}}else if(await this.ignoreService.isRepoBlocked(o))return{kind:"block",reason:{type:"adminBlock",source:"Team repo blocklist"}};const s=(await this.getPermissions()).userConfiguredPolicy,i=r??s;return"workspace_readonly"===s.type&&"workspace_readonly"!==i.type?{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}}:void 0!==r?{kind:"allow",policy:r}:!0!==t.resolveSkippedApprovalPolicy||"workspace_readonly"!==s.type?{kind:"allow",policy:void 0}:{kind:"allow",policy:await this.applyServerAndAdminPolicies({...s,skipStatsigDefaults:s.skipStatsigDefaults??!0})}}async shouldBlockShellCommand(e,t,r,n){const o="insecure_none"===n?.type,s=await this.shouldEnforceShellInvariantBlocks(e,{workingDirectory:r.workingDirectory,command:t,parsingResult:r.parsingResult,toolCallId:r.toolCallId},n);if("block"===s.kind)return s;const i=await this.getPermissions(),a=i.approvalMode,c="unrestricted"===a,l=i.userConfiguredPolicy,u=!i.dashboardTerminalAllowlistOverriddenByPermissionsFile;if(ek.info(e,"Shell permissions: evaluating shell command",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:Vk(l),requestedPolicyType:Vk(n),effectiveRequestedPolicyType:Vk(n??l),smartAllowlistEnabled:!0===i.smartAllowlistEnabled,hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId,hookForcesPrompt:$o(r.hookApprovalRequirement),classifierClassificationFailed:!0===r.classifierResult?.classificationFailed,classifierCommandCount:r.classifierResult?.commands.length??0,parserCommandCount:r.parsingResult.executableCommands.length,parsingFailed:r.parsingResult.parsingFailed,hasRedirects:r.parsingResult.hasRedirects,commandLength:t.length}),await this.shouldPromptForEmptyPlainShellAllowlist(t,i))return ek.info(e,"Shell permissions: prompting for empty allowlist",{toolCallId:r.toolCallId,approvalMode:a,userConfiguredPolicyType:Vk(l),requestedPolicyType:Vk(n),hasSmartModeApprovalReason:void 0!==r.smartModeApprovalReason,hasSmartModeApprovalRequestId:void 0!==r.smartModeApprovalRequestId}),await this.requestApprovalForEmptyShellAllowlist(t,r,n??l);const d=r.parsingResult.executableCommands,h=r.parsingResult.parsingFailed,p=r.classifierResult,f=r.smartModeApprovalReason,m=r.smartModeApprovalRequestId,g=void 0!==p&&!p.classificationFailed&&p.commands.length>0?p:void 0,w="allowlist"===a&&i.smartAllowlistEnabled?g?.commands:void 0,y=void 0!==w,v=d.map(WS),b=w?w.map(Dk):v.map((e=>e.command)),S=void 0!==w?w.map($k):b.map((e=>[e.fullText.trim()].filter(Boolean))),k=void 0!==g?g.commands.map($k):v.map(zk);if(n||(n=i.userConfiguredPolicy),"insecure_none"!==n.type&&void 0===n.skipStatsigDefaults&&"insecure_none"!==l.type&&(n={...n,skipStatsigDefaults:l.skipStatsigDefaults??!0}),"insecure_none"!==l.type&&(0,Oo.$b)(l.networkPolicy)&&"insecure_none"!==n.type&&!(0,Oo._B)(n.networkPolicy)){const e=l.networkPolicy,t=n.networkPolicy?.allow;if(void 0!==t&&t.length>0&&e){const r=[...new Set([...e.allow??[],...t])];n={...n,networkPolicy:{...e,allow:r}}}else n={...n,networkPolicy:e}}let _;n=function({requestedPolicy:e,userConfiguredPolicy:t}){if("insecure_none"===e.type||"insecure_none"===t.type)return e;const r=(0,Oo.XX)(e.readBoundary,t.readBoundary),n="workspace"===r?(0,Oo.wG)(jk(e.readBoundary,e.additionalReadPaths),jk(t.readBoundary,t.additionalReadPaths)):void 0;return{...e,readBoundary:r,additionalReadPaths:n}}({requestedPolicy:n,userConfiguredPolicy:l}),p&&ek.info(e,"Smart allowlist: classifier result received",{classificationFailed:p.classificationFailed,suggestedSandboxMode:p.suggestedSandboxMode,commandCount:p.commands.length,suggestedAllowlistEntryCount:p.commands.filter((e=>e.suggestedAllowlistEntry)).length});const C=[],E=[];let x=[],P=[],R=[];const I=Ak(i.smartAllowlistDenylist??[]);if(I.length>0){P=[];const t=k.map((e=>e[0]??""));for(let e=0;eMk(r,e)))){const r=t[e];r&&P.push(r)}}P.length>0&&(ek.info(e,"Command blocklist: commands require approval",{count:P.length}),C.push(`In blocklist: ${P.join(", ")}`))}if(y&&p){const t=S.map((e=>e[0]??"")),r=i.allow.filter((e=>this.isShellEntry(e)));ek.info(e,"Smart allowlist: checking commands against lists",{commandCount:t.length,allowlistCount:r.length,commandBlocklistCount:I.length});const n=S.map((e=>r.some((t=>e.some((e=>this.matchesShell(t,e))))))),o=n.every(Boolean),s=[];for(let e=0;efunction(e){const t=e.name.trim();if(!t)return[];if(Hb(t))return[];const r=e.subcommandTokens.map((e=>e.trim())).filter(Boolean),n=e.arguments.map((e=>e.trim())).filter(Boolean),o=[t],s=[t];for(const e of r)s.push(e),o.push(s.join(" "));const i=[t,...n].join(" ");return o.includes(i)||o.push(i),Ak(o)}(e)))),R=s.map((e=>e.suggestedAllowlistEntry)).filter((e=>"string"==typeof e)).filter((e=>x.includes(e))),x.length>0){const e=Vb(x,R),t=e.length>0?e.join(", "):x.join(", ");E.push(`Not in allowlist: ${t}`)}_=o&&0===P.length,_&&ek.info(e,"Smart allowlist: all commands in allowlist, will check security",{commandCount:t.length})}const T="ask-every-time"===a||"insecure_none"===n.type&&"allowlist"===a?void 0:l,A=qk(v),$=b.map(((e,t)=>new Gk(e,n,T,S[t],y?A:v[t])));if((0===b.length||h&&!y)&&!c){ek.info(e,"Shell permissions: prompting after parser miss",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:Vk(n),userConfiguredPolicyType:Vk(l),isSmartAllowlistActive:y,parsingFailed:h,parserCommandCount:b.length,hasSmartModeApprovalReason:void 0!==f,hasSmartModeApprovalRequestId:void 0!==m});const o={type:Lw.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:Nk(f??(h?"Parser failed to parse command (possible bypass)":"Parser found no commands (possible bypass)"),await this.adminNetworkLimitReason(n)),isSandboxAvailable:!1,isSandboxEnabled:!1,canAllowlist:!1,notAllowedCommands:[],smartModeApprovalReason:f,smartModeApprovalRequestId:m}};r.onApprovalRequested?.();const s=await this.pendingDecisionStore.requestApproval(o);return s.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(n)}:{kind:"block",reason:{type:"userRejected",reason:s.reason}}}if(await this.hasHardDeny(e,$))return{kind:"block",reason:{type:"permissionsConfig",..."workspace_readonly"===l.type?{isReadonly:!0}:{}}};const{allowlistOfferSafe:M,redirectsAllowlistSafe:D}=await this.computeRedirectAllowlistSafety(r.parsingResult,r.workingDirectory,"insecure_none"===l.type||"workspace"!==l.readBoundary),O=await this.teamSettingsService.getAutoRunControls(),F={type:"insecure_none"};for(const e of $)await this.cmdIsAllowedByAllowlist(e,{redirectsAllowlistSafe:D,autoRunControls:O,applyTeamAllowlist:u})&&e.approveWithPolicy(F);for(const e of $)O&&this.isInTeamBlocklist(O,e)&&e.deny();const N=await this.teamSettingsService.getDeleteFileProtection();if(N)for(const e of $)"rm"===e.command.name&&e.deny();const L=this.buildShellApprovalDecisionFacts({commands:$,autoRunControls:O,shouldApplyTeamShellAllowlist:u,deleteProtectionEnabled:N,softDenylistedCommands:P});if("workspace_readonly"===l.type&&"workspace_readonly"!==n.type)return ek.info(e,"Shell permissions: blocked by readonly mode"),{kind:"block",reason:{type:"permissionsConfig",isReadonly:!0}};const j=$o(r.hookApprovalRequirement),U=r.hookApprovalRequirement?.reason,B=o&&"insecure_none"!==l.type&&function(e){if(/\brimraf\b/i.test(e))return!0;for(const t of e.replace(/[\\`^]\r?\n/g," ").split(/(?|])&|\|\||[;\n]/)){let e=!1;for(const r of t.split("|")){if(e&&JS.test(r)||XS(r,JS,ZS)||XS(r,/(?0&&(L.hasSecurityDenies||L.hasSoftDenies||!L.allCommandsRunnable);if(void 0!==f&&G.push(f),j&&(V||G.push(U?`Hook requested approval: ${U}`:"Hook requested approval"),z=!1),B&&(V||G.push("Recursive delete outside the sandbox"),z=!1),C.length>0&&(V||G.push(...C),z=!1),!V)if(y&&E.length>0)G.push(...E);else if(L.unapprovedCommands.length>0){const e=Vb(this.generateAllowlistPatterns(L.unapprovedCommands)),t=e.length>0?e.join(", "):L.unapprovedCommands.map((e=>e.command.fullText)).join(", ");G.push(`Not in allowlist: ${t}`)}if(L.hasSecurityDenies&&(V||(L.rmDeniedByDeleteProtection.length>0&&G.push("Delete protection is enabled"),L.teamBlocklistedCommands.length>0&&G.push(`In team blocklist: ${L.teamBlocklistedCommands.map((e=>e.command.name)).join(", ")}`)),z=!1),K){const t=L.notInTeamAllowlist.map((e=>e.command.fullText)).join(", ");ek.info(e,"Shell permissions: commands not in team allowlist",{commandCount:L.notInTeamAllowlist.length}),V||G.push(`Not in team allowlist: ${t}`),z=!1}const J="unrestricted"===a&&"workspace_readonly"===n.type,Z="unrestricted"!==a||J?n:{type:"insecure_none"},X=Nk(...G,await this.adminNetworkLimitReason(Z)),Q=[];if(z){const e=void 0!==f?$.filter((e=>"allowlisted"!==e.state)):L.unapprovedCommands;Q.push(...this.generateAllowlistPatterns(e))}const Y=y&&E.length>0,ee=Y?x:Q,te=Y&&R.length>0?R:void 0,re="insecure_none"!==n.type&&"insecure_none"!==l.type,ne="insecure_none"!==n.type,oe=[void 0!==f?"smart_mode_approval":void 0,j?"hook_forces_prompt":void 0,B?"unsandboxed_recursive_delete":void 0,C.length>0?"command_blocklist":void 0,y&&E.length>0?"smart_allowlist_miss":void 0,L.unapprovedCommands.length>0?"unapproved_commands":void 0,L.hasSecurityDenies?"security_denies":void 0,K?"team_allowlist_miss":void 0].filter((e=>void 0!==e));ek.info(e,"Shell permissions: requesting shell approval",{toolCallId:r.toolCallId,approvalMode:a,requestedPolicyType:Vk(n),userConfiguredPolicyType:Vk(l),isSandboxAvailable:re,isSandboxEnabled:ne,canAllowlist:z,isSmartAllowlistActive:y,hasSmartModeApprovalReason:void 0!==f,hasSmartModeApprovalRequestId:void 0!==m,hookForcesPrompt:j,approvalReasonTypes:oe,commandCount:$.length,unapprovedCommandCount:L.unapprovedCommands.length,deniedCommandCount:L.deniedCommands.length,notInTeamAllowlistCount:L.notInTeamAllowlist.length,notAllowedCommandCount:ee.length,suggestedAllowlistEntryCount:te?.length??0,allCommandsRunnable:L.allCommandsRunnable,allCommandsAllowlisted:L.allCommandsAllowlisted,allCommandsPreapproved:L.allCommandsPreapproved,hasSecurityDenies:L.hasSecurityDenies,hasSoftDenies:L.hasSoftDenies});const se={type:Lw.Shell,toolCallId:r.toolCallId,details:{command:t,workingDirectory:r.workingDirectory,timeout:r.timeout,reason:X,isSandboxAvailable:"allowlist"===a&&re,isSandboxEnabled:!("allowlist"!==a&&!J)&&ne,canAllowlist:z,notAllowedCommands:ee,suggestedAllowlistEntries:te,smartModeApprovalReason:f,smartModeApprovalRequestId:m}};r.onApprovalRequested?.();const ie=await this.pendingDecisionStore.requestApproval(se);return ie.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(Z)}:{kind:"block",reason:{type:"userRejected",reason:ie.reason}}}async isShellCommandFullyAllowlisted(e,t,r){const n=e.withName("InteractivePermissionsService.isShellCommandFullyAllowlisted"),o=await this.getPermissions(),s=!o.dashboardTerminalAllowlistOverriddenByPermissionsFile;if("allowlist"!==o.approvalMode)return!1;if("workspace_readonly"===o.userConfiguredPolicy.type)return!1;const{redirectsAllowlistSafe:i}=await this.computeRedirectAllowlistSafety(r.parsingResult,r.workingDirectory,"insecure_none"===o.userConfiguredPolicy.type||"workspace"!==o.userConfiguredPolicy.readBoundary);if(!i)return!1;const a=r.classifierResult,c=void 0!==a&&!a.classificationFailed&&a.commands.length>0?a:void 0,l=(o.smartAllowlistEnabled??!1)&&void 0!==c;if(r.parsingResult.parsingFailed&&!l)return!1;const u=r.parsingResult.executableCommands.map(WS),d=l?c.commands.map(Dk):u.map((e=>e.command));if(0===d.length)return!1;const h=l?c.commands.map($k):d.map((e=>[e.fullText.trim()].filter(Boolean))),p=void 0!==c?c.commands.map($k):u.map(zk),f={type:"insecure_none"},m=qk(u),g=d.map(((e,t)=>new Gk(e,f,void 0,h[t],l?m:u[t])));if(await this.hasHardDeny(n,g))return!1;const w=Ak(o.smartAllowlistDenylist??[]);if(w.length>0)for(const e of p)if(e&&0!==e.length&&w.some((t=>Mk(e,t))))return!1;if(await this.teamSettingsService.getDeleteFileProtection()&&g.some((e=>"rm"===e.command.name)))return!1;const y=await this.teamSettingsService.getAutoRunControls();if(void 0!==y&&g.some((e=>this.isInTeamBlocklist(y,e))))return!1;for(const e of g)if(!await this.cmdIsAllowedByAllowlist(e,{redirectsAllowlistSafe:i,autoRunControls:y,applyTeamAllowlist:s}))return!1;return!0}async applyServerAndAdminPolicies(e){if("insecure_none"===e.type)return e;const t=this.rootDirectories.at(0)??(0,o.homedir)(),{userSandboxDataFolderName:r,teamAdminPolicy:n}=await this.getPermissions(),i=void 0!==r&&r.length>0?(0,s.join)((0,o.homedir)(),r,"sandbox.json"):this.perUserSandboxConfigPath,a=await this.foldPerUserFilePolicy(e,i),c=a.skipStatsigDefaults?a:await this.applyStatsigDefaults(a),l=await this.loadPerRepoFilePolicy(c,t),u=await this.resolveTeamAdminLayer(n);if("unavailable"===u){const{policy:e}=await(0,Oo.resolveSandboxPolicyForWorkspace)(t,{perUser:c,perRepo:l});return function(e){return"insecure_none"===e.type?e:{...e,networkPolicy:(0,Oo.Po)(),readBoundary:"workspace",additionalReadPaths:[]}}(e)}const d=void 0===u?void 0:Ok(c.type,u),h=(0,Oo._B)(e.networkPolicy)&&!Fk(d?.networkPolicy),{policy:p}=await(0,Oo.resolveSandboxPolicyForWorkspace)(t,{perUser:c,perRepo:l,teamAdmin:d});return h?{...p,networkPolicy:(0,Oo.T6)()}:p}async resolveLinkedWorktreeSandboxGrants(e,t){if("workspace_readwrite"!==e.type||"workspace"===e.readBoundary)return;const{perms:r,setting:n}=await this.readControlSetting();if("workspace"===n.boundary||"unavailable"===r.teamAdminPolicy)return;const i=r.userSandboxDataFolderName;if(void 0===e.readBoundary){const t=this.rootDirectories.at(0)??(0,o.homedir)(),n=void 0!==i&&i.length>0?(0,s.join)((0,o.homedir)(),i,"sandbox.json"):this.perUserSandboxConfigPath,a="readBoundary"in r.userConfiguredPolicy&&void 0!==r.userConfiguredPolicy.readBoundary?{...e,readBoundary:r.userConfiguredPolicy.readBoundary}:e,c=await this.foldPerUserFilePolicy(a,n),l=await this.loadPerRepoFilePolicy(c,t);if("workspace"===(l?.readBoundary??c.readBoundary))return}const a=[];for(const e of this.rootDirectories){if((0,qs.$f)(e))continue;const t=await DS(e);OS(t.resolution)&&!wS(t.resolvedPath)&&a.push(t.resolvedPath)}if(0===a.length)return;let c;if(!(0,qs.$f)(t.workingDirectory)){const e=await DS(t.workingDirectory);OS(e.resolution)&&(c=e.resolvedPath)}return async function(e,t={}){if(0===e.length)return;const r=await Promise.all(e.map((e=>ES(e)))),n=[];for(const o of r)void 0===o||n.some((e=>AS(e,o)))||!e.some((e=>(0,Yo.BJ)(o,e)))&&await(t.isUntrustedExternalGitDir?.(o))||n.push(o);if(0===n.length)return;const o=[],i=[],a=void 0!==t.command||void 0!==t.realWorkingDirectory;for(const r of n){const n=await _S((0,s.join)(r,"worktrees"),256),c=await(0,Or.PH)(n,(e=>kS((0,s.join)(r,"worktrees",e),r,!0===t.excludeAgentWorktrees,a?{command:t.command,realWorkingDirectory:t.realWorkingDirectory}:void 0)),{max:16});let l=!1;for(const r of c){if(o.length>=16)break;void 0===r||o.some((e=>AS(e,r)))||e.some((e=>(0,Yo.BJ)(r,e)))||CS(r,e)||await(t.isExcludedWorktreeRoot?.(r))||(o.push(r),l=!0)}l&&i.push(r)}return 0===o.length?void 0:{roots:o,commonDirs:i}}(a,{command:t.command,realWorkingDirectory:c,excludeAgentWorktrees:!0,isUntrustedExternalGitDir:e=>this.isFreelyWritableOutsideWorkspace(e,i),isExcludedWorktreeRoot:async e=>await this.isFreelyWritableOutsideWorkspace(e,i)||await this.ignoreService.isRepoBlocked(e)})}async foldPerUserFilePolicy(e,t=this.perUserSandboxConfigPath){const r=await(0,Oo.tv)(t,(0,o.homedir)());if(!r||"insecure_none"===r.type)return e;let n=(0,Oo.fZ)(r.networkPolicy,e.networkPolicy);n&&void 0!==e.networkPolicy?.default&&(n={...n,default:e.networkPolicy.default});const s=(0,Oo.s9)(r.additionalReadonlyPaths,e.additionalReadonlyPaths),i={...e,networkPolicy:n,additionalReadonlyPaths:s.length>0?s:void 0,readBoundary:r.readBoundary??e.readBoundary,additionalReadPaths:void 0!==r.additionalReadPaths?r.additionalReadPaths:e.additionalReadPaths,privateTmp:r.privateTmp??e.privateTmp};if("workspace_readwrite"===e.type&&"workspace_readwrite"===r.type){const t=(0,Oo.s9)(r.additionalReadwritePaths,e.additionalReadwritePaths);return{...i,additionalReadwritePaths:t.length>0?t:void 0}}return i}async applyStatsigDefaults(e){const t=await this.teamSettingsService.getDefaultNetworkAllowlist();if(!t.available||0===t.allowlist.length)return e;if((0,Oo._B)(e.networkPolicy))return e;const r={default:"deny",allow:dk(t.allowlist)};return{...e,networkPolicy:(0,Oo.fZ)(e.networkPolicy,r)}}async loadPerRepoFilePolicy(e,t){const r=await(0,Oo.tv)((0,s.join)(t,".cursor","sandbox.json"),t);if(r){if("1"===process.env[Zv.K4]){const n=(0,Oo.fB)({perUser:e,perRepo:r},t).perRepo;return"insecure_none"===n?.type?void 0:n}if("insecure_none"!==r.type)return r.type!==e.type?Ok(e.type,{networkPolicy:r.networkPolicy,additionalReadonlyPaths:r.additionalReadonlyPaths,..."additionalReadwritePaths"in r?{additionalReadwritePaths:r.additionalReadwritePaths}:{},disableTmpWrite:r.disableTmpWrite,networkPolicyStrict:r.networkPolicyStrict,readBoundary:r.readBoundary,additionalReadPaths:r.additionalReadPaths,privateTmp:r.privateTmp}):r}}async resolveTeamAdminLayer(e){return void 0!==e?"unavailable"===e?"unavailable":"workspace"===(t=e).readBoundary?t:void 0===t.networkPolicy?{}:{networkPolicy:t.networkPolicy}:async function(e){const{teamSettings:t}=e,r=e.adminNetworkControlsEnabled?(i=await t.getNetworkAccessControls()).available?0!==i.allowlist.length||0!==i.denylist.length?{...i.allowlist.length>0?{default:"deny",allow:dk(i.allowlist)}:{},...i.denylist.length>0?{deny:dk(i.denylist)}:{}}:void 0:(0,Oo.Po)():void 0,[n,o]=await Promise.all([t.isReadControlEnabled?.()??!0,t.getSandboxingControls()]),s=void 0===r?{}:{networkPolicy:r};var i;return n&&"workspace"===o.readBoundary?{...s,readBoundary:"workspace",additionalReadPaths:o.readAllowlistPaths??[],allowUserOverrideReadPaths:o.allowUserOverrideReadAllowlist}:void 0===r?void 0:s}({teamSettings:this.teamSettingsService,adminNetworkControlsEnabled:this.adminNetworkControlsEnabled});var t}async adminNetworkLimitReason(e){if("insecure_none"===e.type||!(0,Oo._B)(e.networkPolicy))return;const{teamAdminPolicy:t}=await this.getPermissions(),r=await this.resolveTeamAdminLayer(t);return function(e){if(Fk(e))return void 0!==e.allow&&e.allow.length>0?"Network access limited to your admin's allowlist":"deny"===e.default?"Network access limited by your admin":"Network access excludes domains your admin blocks"}("unavailable"===r?(0,Oo.Po)():r?.networkPolicy)}async getAdminReadSandboxing(){const e=await this.getPermissions();if("unavailable"===e.teamAdminPolicy)return{readBoundary:"workspace"};const{enabled:t,boundary:r}=await this.adminReadControls(e);return{readBoundary:t&&"workspace"===r?"workspace":void 0}}async isInShellAllowlist(e){if(!e.allowlistable)return!1;const t=await this.getPermissions(),r=e.readsArguments?e.matchForms.map((e=>`${e} \0`)):e.matchForms;return t.allow.some((e=>this.isShellEntry(e)&&r.some((t=>this.matchesShell(e,t)))))}isInTeamBlocklist(e,t){const r=[...t.wrapperForms,t.command.fullText];return e.blocked.some((e=>r.some((t=>this.matchesAutoRunCommand(t,e)))))}isInTeamAllowlist(e,t){return!!t.allowlistable&&e.allowed.some((e=>this.matchesAutoRunCommand(t.command.fullText,e)))}async computeRedirectAllowlistSafety(e,t,r){const n=e.hasRedirects,i=e.parsingFailed,a=!0===e.allRedirectsAreDevNull,c=!(!n||a||i)&&await async function({parsingResult:e,workingDirectory:t,rootDirectories:r,allowTmpRedirects:n=!0,resolvePathForPermissions:i=DS,pathModule:a=s,tempPathOptions:c={platform:process.platform,env:process.env,pathModule:a,homeDirectory:(0,o.homedir)()}}){if(!e.hasRedirects)return!0;const l=e.redirects;if(0===l.length)return!1;const u=e.executableCommands.length>1,d=await Pk({parsingResult:e,workingDirectory:t,resolvePathForPermissions:i,pathModule:a}),h=hk();for(const e of l){if(wk(e))continue;const o=u?hk():h,{operator:s,targetText:l}=e,f=e.destinationFds;if(">&"===s){const e=gk(l),t=void 0===e?void 0:o.fdTargets.get(e);if("original-stdout"!==(p=t)&&"original-stderr"!==p&&"dev-null"!==p&&"workspace-file"!==p&&"tmp-file"!==p){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}for(const e of f)o.fdTargets.set(e,t);continue}if("<&"===s){const e=gk(l),t=void 0===e?void 0:o.fdTargets.get(e);if("dev-null"!==t){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}for(const e of f)o.fdTargets.set(e,t);continue}if("/dev/null"===l){for(const e of f)o.fdTargets.set(e,"dev-null");continue}if(!fk(s)||void 0===l||"word"===e.targetNodeType&&!yk(l,a)){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}const m=await Rk({targetText:l,workingDirectory:t,workingDirectories:d,rootDirectories:r,allowTmpRedirects:n,resolvePathForPermissions:i,pathModule:a,tempPathOptions:c});if(!m){for(const e of f)o.fdTargets.set(e,"unsafe");return!1}for(const e of f)o.fdTargets.set(e,m)}var p;return!0}({parsingResult:e,workingDirectory:t,rootDirectories:this.rootDirectories,allowTmpRedirects:r}),l=await Tk({parsingResult:e,workingDirectory:t,rootDirectories:this.rootDirectories,allowTmpRedirects:r}),u=!function({parsingResult:e,hasRedirects:t,parsingFailed:r,allRedirectsAreAllowlistSafe:n,allRedirectsAreWorkspaceFileSafe:o}){return!(!t||r||n||o)&&(0===e.redirects.length||e.redirects.some(mk))}({parsingResult:e,hasRedirects:n,parsingFailed:i,allRedirectsAreAllowlistSafe:a,allRedirectsAreWorkspaceFileSafe:c})&&l;return{allowlistOfferSafe:(!n||a||c)&&l&&!i,redirectsAllowlistSafe:u}}async cmdIsAllowedByAllowlist(e,t){return!!t.redirectsAllowlistSafe&&(!!await this.isInShellAllowlist(e)||t.applyTeamAllowlist&&void 0!==t.autoRunControls&&this.isInTeamAllowlist(t.autoRunControls,e))}buildShellApprovalDecisionFacts({commands:e,softDenylistedCommands:t,autoRunControls:r,shouldApplyTeamShellAllowlist:n,deleteProtectionEnabled:o}){const s=e.filter((e=>"denied"===e.state)),i=e.filter((e=>"approvable"===e.state)),a=n&&r?.enabled?e.filter((e=>!this.isInTeamAllowlist(r,e))):[],c=s.filter((e=>void 0!==r&&this.isInTeamBlocklist(r,e))),l=o?s.filter((e=>"rm"===e.command.name)):[];return{hasSecurityDenies:s.length>0,hasSoftDenies:t.length>0,hasTeamAllowlistMisses:a.length>0,allCommandsRunnable:e.every((e=>e.isRunnable())),allCommandsAllowlisted:e.every((e=>"allowlisted"===e.state)),allCommandsPreapproved:e.every((e=>"preapproved"===e.state)),canAllowlistInPrompt:0===s.length&&0===a.length,unapprovedCommands:i,deniedCommands:s,notInTeamAllowlist:a,teamBlocklistedCommands:c,rmDeniedByDeleteProtection:l}}getShellAutoApprovalPolicy({approvalMode:e,isUnrestricted:t,requestedPolicy:r,facts:n,preserveRequestedPolicyForAllowlistedCommands:o}){if(!n.hasSecurityDenies&&!n.hasSoftDenies&&n.allCommandsRunnable){if(t)return"workspace_readonly"===r.type?r:{type:"insecure_none"};if("allowlist"===e)return n.allCommandsAllowlisted&&!o&&"workspace_readonly"!==r.type?{type:"insecure_none",allowlistEscalated:!0}:r}}async getPermissions(){return await this.permissionsProvider.getPermissions()}hasLocalShellControls(e){return e.allow.some((e=>this.isShellEntry(e)))||e.deny.some((e=>this.isShellEntry(e)))||(e.smartAllowlistDenylist?.length??0)>0}hasTeamShellControls(e,t=!0){return void 0!==e&&(t&&(e.enabled||e.allowed.length>0)||e.blocked.length>0)}async shouldPromptForEmptyPlainShellAllowlist(e,t){if("allowlist"!==t.approvalMode||"insecure_none"!==t.userConfiguredPolicy.type||0===e.trim().length||this.hasLocalShellControls(t))return!1;const[r,n]=await Promise.all([this.teamSettingsService.getAutoRunControls(),this.teamSettingsService.getDeleteFileProtection()]);return!this.hasTeamShellControls(r,!t.dashboardTerminalAllowlistOverriddenByPermissionsFile)&&!n}async requestApprovalForEmptyShellAllowlist(e,t,r){const n=await this.getEmptyShellAllowlistCandidates(t);t.onApprovalRequested?.();const o=await this.pendingDecisionStore.requestApproval({type:Lw.Shell,toolCallId:t.toolCallId,details:{command:e,workingDirectory:t.workingDirectory,timeout:t.timeout,reason:Nk(t.smartModeApprovalReason??"Shell allowlist is empty",await this.adminNetworkLimitReason(r)),isSandboxAvailable:!1,isSandboxEnabled:!1,canAllowlist:n.length>0,notAllowedCommands:n,smartModeApprovalReason:t.smartModeApprovalReason,smartModeApprovalRequestId:t.smartModeApprovalRequestId}});return o.approved?{kind:"allow",policy:await this.applyServerAndAdminPolicies(r)}:{kind:"block",reason:{type:"userRejected",reason:o.reason}}}async getEmptyShellAllowlistCandidates(e){const t=e.parsingResult;return t.parsingFailed||0===t.executableCommands.length||t.hasRedirects&&!0!==t.allRedirectsAreDevNull||!await Tk({parsingResult:t,workingDirectory:e.workingDirectory,rootDirectories:this.rootDirectories,allowTmpRedirects:!0})?[]:this.generateAllowlistPatterns(t.executableCommands.map(WS))}async getAdminCommandDenylistBlock(e,t){const r=(await this.teamSettingsService.getAdminCommandDenylist()).rules;if(0===r.length)return;const n=bs({matchForms:t.parsingResult?gs({command:t.command,parsingResult:t.parsingResult}):[t.command],blockedCommands:r});return void 0!==n?(ek.info(e,"Admin command denylist hard-blocked shell at execution time",{toolCallId:t.toolCallId,parsingFailed:t.parsingResult?.parsingFailed??!0,parserCommandCount:t.parsingResult?.executableCommands.length??0}),{type:"adminCommandDenylist",pattern:n}):void 0}async hasHardDeny(e,t){const r=await this.getPermissions();return t.some((e=>r.deny.some((t=>this.isShellEntry(t)&&[...e.wrapperForms,...e.matchForms].some((e=>this.matchesShell(t,e)))))))}isShellEntry(e){return null!==Bk(e)}isPathEntry(e,t){return new RegExp(`^\\s*${e}\\s*\\(`).test(t)}matchesShell(e,t){const r=Bk(e);if(!r)return!1;const n=t.trim(),o=this.extractBaseCommand(n);if(null!==r.argsPattern){const e=n.includes(" ")?n.slice(n.indexOf(" ")+1).trim():"",t=this.matchGlob(r.commandPattern,o)||this.matchGlob(r.commandPattern,n),s=this.matchGlob(r.argsPattern,e);if(t&&s)return!0}return!!this.matchGlob(r.fullPattern,n)||!!n.startsWith(`${r.fullPattern} `)||!!this.matchGlob(r.fullPattern,o)||o===r.fullPattern}async checkCursorFileProtection(e){if(!e.some((e=>".cursor"===e.toLowerCase()||".vscode"===e.toLowerCase())))return null;const t=e[e.length-1]?.toLowerCase()??"";return t.endsWith(".md")||t.endsWith(".mdc")||".cursorrules"===t?null:await this.teamSettingsService.getDotCursorProtection()?{type:"permissionsConfig"}:null}extractBaseCommand(e){const t=e.trim(),r=t.indexOf(" ");return-1===r?t:t.substring(0,r)}generateAllowlistPatterns(e){const t=[],r=["git","npm","yarn","pnpm","docker","pip","systemctl","uv","cargo","bun","npx"];for(const{command:n,allowlistable:o}of e)o&&!Hb(n.name)&&(r.includes(n.name)&&n.args.length>0&&"word"===n.args[0].type?t.push(`${n.name} ${n.args[0].value}`):t.push(n.name));return[...new Set(t)]}pathEntryRawPattern(e,t){const r=t.match(function(e){return"Read"===e?Yk:e_}(e));if(r)return(r[1]??"").trim()}compileReadDenyMatcher(e){try{const t=this.pathEntryRawPattern("Read",e);if(void 0===t)return()=>!1;const r=(0,ms.b)((0,Yo.jl)(t));return e=>r(e)}catch(e){return()=>{throw e}}}matchesPathEntry(e,t,r){const n=this.pathEntryRawPattern(e,t);return void 0!==n&&this.matchGlob((0,Yo.jl)(n),r)}async isPathExplicitlyDenied(e,t){return(await this.getPermissions()).deny.some((r=>this.isPathEntry(e,r)&&this.matchesPathEntry(e,r,t)))}async isPathExplicitlyAllowed(e,t){return(await this.getPermissions()).allow.some((r=>this.isPathEntry(e,r)&&this.matchesPathEntry(e,r,t)))}matchGlob(e,t){return(0,ms.T)(e,t)}async addToAllowList(e,t,r){const n=`${t}(${r})`;await this.permissionsProvider.updatePermissions((e=>{const t=e.allow.includes(n)?e.allow:[...e.allow,n];return{...e,allow:t}}))}async addToDenyList(e,t,r){const n=`${t}(${r})`;await this.permissionsProvider.updatePermissions((e=>{const t=e.deny.includes(n)?e.deny:[...e.deny,n];return{...e,deny:t}}))}async shouldBlockMcp(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{QS(o,(0,$.VI)(e.withName("InteractivePermissionsService.shouldBlockMcp")),!1);const{name:s,toolName:i,providerIdentifier:a,args:c}=t,l=function(e,t){if(void 0!==t)return t;const r=e;return void 0!==r.annotations?r.annotations:Mb(r.annotationsJson)}(t,r?.annotations),u=e=>{this.mcpAllowlistLog?.(e)};if(u(`[permissions-service] shouldBlockMcp: toolName="${i}", providerIdentifier="${a}"`),await this.isComputerUseDisabledByAdminFor(a))return u(`[permissions-service] shouldBlockMcp: BLOCKED (Computer Use off for team) toolName="${i}", providerIdentifier="${a}"`),{type:"unsafeResolution",message:"Computer Use is turned off by your team admin. Ask the user to do it instead."};const d=await this.mcpAdminToolLimitRefusal(e,{resolvedTool:n?.resolvedTool,toolName:i});if(void 0!==d)return u(`[permissions-service] shouldBlockMcp: BLOCKED (team tool limit) toolName="${i}", providerIdentifier="${a}"`),{type:"unsafeResolution",message:d};const h=await this.computerUseDecision(t,r);if(await this.isMcpExplicitlyDenied(e,a,i))return u(`[permissions-service] shouldBlockMcp: BLOCKED (explicitly denied) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig"};const p=await this.getPermissions(),f="workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode;if(!0===n?.alreadyApproved&&!f&&"block"!==h.kind&&"askEachCall"!==h.kind)return!1;const m=await this.teamSettingsService.getMcpToolControls(),g=!0===m?.enabled&&!(void 0!==n?.client&&!0===await(this.teamSettingsService.isHostMcpBridgeClient?.(n.client))),w=g&&"block"!==h.kind?{kind:"notComputerUse"}:h,y=void 0!==t.smartModeApproval?.reason&&f,v=Qk({server:Xk(a),tool:i});let b,S,k;switch(w.kind){case"block":return u(`[permissions-service] shouldBlockMcp: BLOCKED (Computer Use app) toolName="${i}", providerIdentifier="${a}"`),{type:"unsafeResolution",message:w.message};case"noAccess":if(!f&&!await this.teamSettingsService.getShouldBlockMcp())return u(`[permissions-service] shouldBlockMcp: ALLOWED (Computer Use no access) toolName="${i}", providerIdentifier="${a}"`),!1;b=v,k=!0;break;case"app":if(!y&&(this.computerUseAppsAllowedForSession.includes(w.entry)||await this.isComputerUseAppSaved(w.entry)))return u(`[permissions-service] shouldBlockMcp: ALLOWED (Computer Use app grant) toolName="${i}", providerIdentifier="${a}"`),!1;b=w.entry,S=w.app,k=!1;break;case"askEachCall":b=void 0,S=w.app&&{...w.app,allowOnce:!0},k=!1;break;case"notComputerUse":b=v,k=!0}const _=k||void 0!==b,C=t.smartModeApproval?.reason;if(void 0!==C)return"workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode?(u(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode, Smart Mode forced approval) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig",isReadonly:!0}):(u(`[permissions-service] shouldBlockMcp: needsApproval (Smart Mode) toolName="${i}", providerIdentifier="${a}"`),!(g?this.isMcpInTeamAllowlist(m,{providerIdentifier:a,toolName:i,annotations:l}):k&&await this.isMcpExplicitlyAllowed(e,a,i))&&!("unrestricted"===p.approvalMode&&!await this.teamSettingsService.getShouldBlockMcp())&&{type:"needsApproval",approvalReason:C,approvalDetails:{type:"mcp",name:s,toolName:i,...ck(r,l),providerIdentifier:a,args:c,reason:"smartMode",canAllowlist:_&&!this.isComputerUseServer(a),smartModeApprovalReason:C,smartModeApprovalRequestId:t.smartModeApproval?.requestId,allowlistEntry:b,computerUseApp:S}});if(g){const t=this.isMcpInTeamAllowlist(m,{providerIdentifier:a,toolName:i,annotations:l});if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"team",outcome:t?"pass":"fail"}),t)return u(`[permissions-service] shouldBlockMcp: ALLOWED (in admin MCP allowlist) toolName="${i}", providerIdentifier="${a}"`),!1}else if(k){const t=await this.isMcpExplicitlyAllowed(e,a,i);if(this.recordMcpAllowlistCheckResult(e,{allowlistScope:"user",outcome:t?"pass":"fail"}),t)return u(`[permissions-service] shouldBlockMcp: ALLOWED (explicitly in allowlist) toolName="${i}", providerIdentifier="${a}"`),!1}if("workspace_readonly"===p.userConfiguredPolicy.type&&"unrestricted"!==p.approvalMode)return u(`[permissions-service] shouldBlockMcp: BLOCKED (readonly mode) toolName="${i}", providerIdentifier="${a}"`),{type:"permissionsConfig",isReadonly:!0};if("unrestricted"===p.approvalMode){if(!await this.teamSettingsService.getShouldBlockMcp())return u(`[permissions-service] shouldBlockMcp: ALLOWED (auto-run, no team block) toolName="${i}", providerIdentifier="${a}"`),!1;u(`[permissions-service] shouldBlockMcp: needsApproval (auto-run but team blocks MCP) toolName="${i}", providerIdentifier="${a}"`)}return u(`[permissions-service] shouldBlockMcp: needsApproval (not in allowlist) toolName="${i}", providerIdentifier="${a}", approvalMode="${p.approvalMode}"`),{type:"needsApproval",approvalReason:`MCP tool: ${i}`,approvalDetails:{type:"mcp",name:s,toolName:i,...ck(r,l),providerIdentifier:a,args:c,canAllowlist:_,allowlistEntry:b,computerUseApp:S}}}catch(e){o.error=e,o.hasError=!0}finally{YS(o)}}async mcpAdminToolLimitRefusal(e,{resolvedTool:t,toolName:r}){if(void 0===t||void 0===this.enforceMcpAdminToolLimits)return;if(!await this.enforcesMcpAdminToolLimits())return void(void 0!==this.onMcpAdminToolLimitCheck&&this.judgeMcpAdminToolLimit(t,r).then((e=>this.reportMcpAdminToolLimitCheck("shadow",e)),(()=>{})));const n=await this.judgeMcpAdminToolLimit(t,r);this.reportMcpAdminToolLimitCheck("enforce",n);const o=n?.outcome;switch(o){case void 0:case"within_limit":return;case"outside_limit":return rk.increment(e,1,{reason:"outside_limit"}),"Your team's admin limits this MCP tool";case"settings_unavailable":if(!0===n?.ranWithoutLimit)return;return rk.increment(e,1,{reason:"settings_unavailable"}),"Your team's MCP settings could not be read, so this MCP tool can't run right now";case"unknown_server":return rk.increment(e,1,{reason:"unknown_server"}),nk;default:return o}}async judgeMcpAdminToolLimit(e,t){if("unresolved"===e)return{outcome:"unknown_server"};const r=await(this.teamSettingsService.getMcpAdminToolLimit?.(e.client));if(void 0!==r)switch(r.kind){case"none":return;case"settings_unavailable":return{outcome:"settings_unavailable",...void 0===r.failure?{}:{settingsFailure:r.failure},...!0===r.noLimitApplies?{ranWithoutLimit:!0}:{}};case"unknown_server":return{outcome:"unknown_server"};case"limit":return{outcome:jb(r.policy,{name:t,annotations:e.annotations})?"within_limit":"outside_limit"};default:return r}}reportMcpAdminToolLimitCheck(e,t){if(void 0!==t)try{this.onMcpAdminToolLimitCheck?.({mode:e,...t})}catch{}}async enforcesMcpAdminToolLimits(){if(void 0===this.enforceMcpAdminToolLimits)return!1;try{return await this.enforceMcpAdminToolLimits()}catch{return!1}}async computerUseDecision(e,t){const r=this.computerUse;if(void 0===r||!this.isComputerUseServer(e.providerIdentifier))return{kind:"notComputerUse"};const n=await r.isOwnServer(Xk(e.serverIdentifier||e.providerIdentifier),t);if(!1===n)return{kind:"notComputerUse"};const o=await async function(e,t){const r=sS(e.meta?.["cursor/computerUseScope"])??sS(t.toolScopes?.[e.toolName]);if(void 0===r)return{kind:"screen"};let n;if(void 0!==r.appSelectorArgs){const t=Object.entries(r.appSelectorArgs).flatMap((([t,r])=>oS(t)&&void 0!==r&&void 0!==e.args[r]&&null!==e.args[r]?[{selector:t,value:e.args[r]}]:[]));if(0===t.length){const t=new Intl.ListFormat("en",{type:"disjunction"}).format(Object.values(r.appSelectorArgs).filter((e=>void 0!==e)));return{kind:"noAppSelector",message:`${e.toolName} needs exactly one of ${t} to name the app. Call it again with one of them.`}}const o=t.filter((({selector:e,value:t})=>function(e,t){return"pid"===e?"number"==typeof t&&Number.isInteger(t)||"string"==typeof t&&aS.test(t):"string"==typeof t&&t.length>0}(e,t)));if(1!==o.length){for(const{value:e}of t){const t="string"==typeof e?Yb(e.trim()):void 0;if(void 0!==t)return{kind:"app",app:t}}return{kind:"unknownApp"}}n=function(e,t){if("pid"===e){const e="string"==typeof t&&aS.test(t)?Number(t):t;return"number"==typeof e&&Number.isSafeInteger(e)&&e>0?{pid:e}:void 0}const r="string"==typeof t?t.trim():"";if(0!==r.length)return"bundleId"===e?{bundleId:r}:"path"===e?{path:r}:{appName:r}}(o[0].selector,o[0].value)}else{if(void 0===r.appArg)return r.capturesScreen?{kind:"screen"}:{kind:"none"};{const t=e.args[r.appArg];if(null==t||function(e){return"object"==typeof e&&null!==e&&"screen"===e.scope}(t))return{kind:"screen"};n=function(e){if("string"==typeof e){const t=e.trim();return t.length>0?{name:t}:void 0}if("object"!=typeof e||null===e)return;const{scope:t,pid:r}=e;return"app"===t&&"number"==typeof r&&Number.isInteger(r)&&r>0?{pid:r}:void 0}(t)}}if(void 0===n)return{kind:"unknownApp"};const o=function(e){return"pid"in e?void 0:"name"in e?e.name:"bundleId"in e?e.bundleId:"path"in e?e.path:e.appName}(n),s=await t.describeApp(n)??(void 0===o?void 0:Yb(o));return void 0===s?{kind:"unknownApp"}:{kind:"app",app:s}}({toolName:e.toolName,args:Object.fromEntries(Object.entries(e.args).map((([e,t])=>[e,t.toJson()]))),meta:t?._meta},r);if(void 0===n&&"app"!==o.kind)return{kind:"askEachCall"};switch(o.kind){case"none":return{kind:"noAccess"};case"screen":return{kind:"notComputerUse"};case"unknownApp":return{kind:"askEachCall"};case"noAppSelector":return{kind:"block",message:o.message};case"app":{const e=function(e){const t=e.toLowerCase();return Zb(t)?"Computer Use doesn't control Cursor itself, including its approval cards. Ask the user to do it instead.":Xb.some((e=>e.bundleId===t))?"Computer Use doesn't control apps that run scripts, such as Script Editor, Automator and Shortcuts. Ask the user to do it instead.":Qb.some((e=>e.bundleId===t))?"Computer Use doesn't control terminal apps. Use your shell tool to run commands instead.":void 0}(o.app.bundleId);if(void 0!==e)return{kind:"block",message:e};if(void 0===n)return{kind:"askEachCall"};const t=tS(o.app.bundleId)?void 0:Qk({server:r.serverId,tool:rS(o.app.bundleId)});return void 0===t?{kind:"askEachCall",app:o.app}:{kind:"app",app:o.app,entry:t}}}throw new Error("unreachable computer-use subject")}isComputerUseServer(e){const t=Xk(e);return!0===this.computerUse?.providerIdentifiers.has(t)}async isComputerUseDisabledByAdminFor(e){const t=this.computerUseAdminPolicy;return t?.providerIdentifiers.has(Xk(e))?await t.isDisabledByAdmin():!!this.isComputerUseServer(e)&&!0===await(this.teamSettingsService.isComputerUseDisabledByAdmin?.())}allowComputerUseAppForSession({bundleId:e}){const t=void 0===this.computerUse||tS(e)?void 0:Qk({server:this.computerUse.serverId,tool:rS(e)});void 0!==t&&this.computerUseAppsAllowedForSession.push(t)}async isMcpFullyAllowlisted(e,t){const r=e.withName("InteractivePermissionsService.isMcpFullyAllowlisted"),{providerIdentifier:n,toolName:o}=t,s=t.annotations??Mb(t.annotationsJson);if(await this.isMcpExplicitlyDenied(r,n,o)||await this.isComputerUseDisabledByAdminFor(n))return!1;const i=await this.teamSettingsService.getMcpToolControls();return!0===i?.enabled?!!this.isMcpInTeamAllowlist(i,{providerIdentifier:n,toolName:o,annotations:s}):!this.isComputerUseServer(n)&&await this.isMcpExplicitlyAllowed(r,n,o)}async isWebFetchFullyAllowlisted(e,t){const r=await this.getPermissions();if("allowlist"!==r.approvalMode)return!1;let n;try{n=new URL(t.url)}catch{return!1}const o=n.hostname;return!r.deny.some((e=>this.matchesWebFetchEntry(e,o)))&&r.allow.some((e=>this.matchesWebFetchEntry(e,o)))}matchesAutoRunCommand(e,t){const r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^${r}(\\s|$)`).test(e.trim())}matchesMcpPattern({pattern:e,providerIdentifier:t,toolName:r,logLabel:n}){const o=e.indexOf(":");if(-1===o)return!1;const s=e.slice(0,o).trim().toLowerCase(),i=e.slice(o+1).trim().toLowerCase(),a=Xk(t).toLowerCase().trim(),c=r.toLowerCase().trim(),l="*"===s||this.matchGlob(s,a),u="*"===i||this.matchGlob(i,c),d=l&&u,h=`[permissions-service] ${n}: serverPattern="${s}", toolPattern="${i}", normalizedProviderIdentifier="${a}", normalizedToolName="${c}", serverMatches=${l}, toolMatches=${u}, result=${d}`;return this.mcpAllowlistLog?.(h),d}recordMcpAllowlistCheckResult(e,{allowlistScope:t,outcome:r}){tk.increment(e,1,{allowlist_scope:t,outcome:r})}matchesMcpEntry(e,t,r){const n=e.match(/^\s*Mcp\s*\((.*)\)\s*$/);if(!n)return!1;const o=n[1]?.trim()??"";return this.matchesMcpPattern({pattern:o,providerIdentifier:t,toolName:r,logLabel:"matchesMcpEntry"})}matchesWebFetchEntry(e,t){const r=e.match(/^\s*WebFetch\s*\((.*)\)\s*$/);return!!r&&Kv(t,r[1]?.trim()??"")}matchesMcpEntryBare({pattern:e,providerIdentifier:t,toolName:r}){return this.matchesMcpPattern({pattern:e,providerIdentifier:t,toolName:r,logLabel:"matchesMcpEntryBare"})}isMcpInTeamAllowlist(e,{providerIdentifier:t,toolName:r,annotations:n}){if(e.mcpToolAllowlist.some((e=>this.matchesMcpEntryBare({pattern:e,providerIdentifier:t,toolName:r}))))return!0;const o=this.findTeamMcpServerPolicy(e,t);return void 0!==o&&"reads"===o.mode&&jb(o,{name:r,annotations:n})}findTeamMcpServerPolicy(e,t){for(const r of e.serverPolicies??[])if(this.matchesMcpEntryBare({pattern:`${r.name}:*`,providerIdentifier:t,toolName:""}))return r.policy}async isMcpExplicitlyDenied(e,t,r){return(await this.getPermissions()).deny.some((e=>this.matchesMcpEntry(e,t,r)))}async isComputerUseAppSaved(e){return(await this.getPermissions()).allow.some((t=>t.match(/^\s*Mcp\s*\((.*)\)\s*$/)?.[1]?.trim().toLowerCase()===e))}async isMcpExplicitlyAllowed(e,t,r){return(await this.getPermissions()).allow.some((e=>this.matchesMcpEntry(e,t,r)))}}var r_=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const n_=65536,o_=1048576,s_=(0,l.h)("LocalReadExecutor"),i_=async(e,t,r,n)=>{const o=setTimeout((()=>{s_.warn(e,`[watchdog, LocalReadExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function a_(e){return BigInt(Math.min(e,4294967295))}async function c_(e,t){if(0===t)return(0,Co.readFile)(e);if(t>2147483647)throw new RangeError(`File size (${t}) is greater than 2 GiB`);const r=await(0,Co.open)(e,"r");try{const e=Buffer.allocUnsafe(t);let n=0;for(;n=32&&e<=126||9===e||10===e||13===e}function d_(e){if(e.length>=2){if(255===e[0]&&254===e[1])return"utf-16le";if(254===e[0]&&255===e[1])return"utf-16be"}const t=Math.min(4096,e.length);if(t<16)return"utf-8";let r=0,n=0;for(let o=0;o+1=8&&r>=4*Math.max(1,n)?"utf-16le":n>=8&&n>=4*Math.max(1,r)?"utf-16be":"utf-8"}const h_=Buffer.from("\n---\n");function p_(e,t){const r=e.length;if(r<2*h_.length)return r;if(10!==e[r-1]||45!==e[r-2]||45!==e[r-3]||45!==e[r-4]||10!==e[r-5])return r;const n=Math.max(t,r-4096),o=e.lastIndexOf(h_,r-h_.length-1);return-1===o||o126))return!1}const t=e.split("\n").filter((e=>e.length>0));if(t.length<2||t.length>3)return!1;const r=t[0],n=t[t.length-1];return!(!/^(exit_code: (?:-?\d+|unknown)|error: .+)$/.test(r)||!n.startsWith("ended_at: ")||3===t.length&&!/^elapsed_ms: \d+$/.test(t[1]))}(e.subarray(o+h_.length,r-4).toString("utf-8"))?o:r}const f_=[Buffer.from("%PDF-","ascii"),Buffer.from([208,207,17,224,161,177,26,225]),Buffer.from([80,75,3,4]),Buffer.from([80,75,5,6]),Buffer.from([80,75,7,8]),Buffer.from([127,69,76,70]),Buffer.from([254,237,250,206]),Buffer.from([254,237,250,207]),Buffer.from([206,250,237,254]),Buffer.from([207,250,237,254]),Buffer.from([77,90,144]),Buffer.from([0,97,115,109]),Buffer.from([137,80,78,71,13,10,26,10]),Buffer.from([255,216,255]),Buffer.from("GIF87a","ascii"),Buffer.from("GIF89a","ascii"),Buffer.from("SQLite format 3\0","ascii"),Buffer.from([31,139]),Buffer.from("BZh","ascii"),Buffer.from([253,55,122,88,90,0]),Buffer.from([40,181,47,253]),Buffer.from([55,122,188,175,39,28]),Buffer.from([82,97,114,33,26,7,0]),Buffer.from([82,97,114,33,26,7,1,0])];function m_(e){return new Ky.sV({result:{case:"invalidFile",value:new Ky.cW({path:e,reason:"File content is binary data, not text"})}})}function g_(e,t,r){if(void 0===r.offset&&void 0===r.limit)return{applied:!1};if(t)return{applied:!1};const n=r.offset??1,o=r.limit??(n<0?Math.abs(n):e),s=n<0?Math.max(0,e+n):Math.max(0,n-1);if(s>=e)return{applied:!1};const i=Math.min(e,s+o),a=w_(s,e),c=w_(i,e);return{applied:!0,start:a,end:Math.max(a,c)}}function w_(e,t){if(Number.isNaN(e)||0===e)return 0;if(e===Number.POSITIVE_INFINITY)return t;if(e===Number.NEGATIVE_INFINITY)return 0;const r=Math.trunc(e);return r<0?Math.max(t+r,0):Math.min(r,t)}function y_(e){return-1===e.indexOf("\r\n")?e:e.replaceAll("\r\n","\n")}function v_(e,t,r,n,o,s){if(n>=o)return{from:0,to:0};let i=0,a=0,c=0===n,l=0;for(;ia&&13===r(t)?t-1:t};l=t+1}return c?{from:a,to:t}:{from:t,to:t}}function b_(e,t,r){const n=v_((t=>e.indexOf("\n",t)),e.length,(t=>e.charCodeAt(t-1)),t,r,!1);return 0===n.from&&n.to===e.length?e:n.from>=n.to?"":e.slice(n.from,n.to)}function S_(e,t,r,n,o){if(t>=r)return{text:"",truncated:!1};const s=n>=0?n+3:-1;let i=t;if(n>=0&&i>=n&&i=r)return{text:"",truncated:!1};const a=function(e,t,r,n){if(r>=n)return n;if(r<=t)return t;const o=Math.max(t,r-3);let s=r;for(;s>o;){if(128!=(192&(e[s]??0)))return s;s--}return 192&~(e[s]??0)?r:s}(e,i,Math.min(r,i+3*(o+1)+3),r);let c=y_(function(e,t,r,n){if(t>=r)return"";if(n<0)return e.toString("utf8",t,r);const o=n+3;return r<=n||t>=o?e.toString("utf8",t,r):t>=n&&r<=o?"":(to?e.toString("utf8",Math.max(t,o),r):"")}(e,i,a,n));const l=c.length>o||ao&&(c=Vo(c,o)),{text:c,truncated:l}}function k_(e,t,r,n){if(t>=r)return{text:"",truncated:!1};const o=Math.min(r,t+2*n+1);let s=y_(e.slice(t,o));const i=s.length>n||on&&(s=Vo(s,n)),s.lengthn?{text:e.text+Vo(t,n),truncated:!0}:{text:e.text+t,truncated:e.truncated}}function C_(e,t){if(e.truncated)return e;const r=__(e,t);return{text:r.text,truncated:r.truncated}}function E_(e,t,r){let n=e;return t.forEach(((e,t)=>{const o=function(e,t){const{line:r,hasNewline:n}=e;return t&&n&&r.text.endsWith("\r")?{...r,text:r.text.slice(0,-1)}:r}(e,r);t>0&&(n=__(n,"\n")),n=__(n,o.text),o.truncated&&(n={text:n.text,truncated:!0})})),n}function x_(e){const t=e.toLowerCase();return"utf-8"===t?"utf8":"utf-8-bom"===t||"utf-8 bom"===t?"utf8bom":"latin-1"===t?"latin1":t}function P_(e){return void 0===e.maxChars||void 0!==e.offset||void 0!==e.limit?Gs:Math.min(Gs,e.maxChars+2)}function R_(e,t,r){if(!t||void 0===r.maxChars||e.length-1<=r.maxChars)return e;const n=e.charCodeAt(e.length-1);return n>=55296&&n<=56319?e.slice(0,-1):e}class I_ extends Error{constructor(){super("Invalid UTF-8 while streaming read"),this.name="InvalidUtf8Error"}}function T_(e){for(let t=1;t<=Math.min(3,e.length);t++){const r=e[e.length-t]??0;if(128!=(192&r))return A_(r)>t?t:0}return 0}function A_(e){return e>=240?4:e>=224?3:e>=192?2:1}class $_{constructor(e,t,r){this.previousEndsWithCr=e,this.carry=t,this.strict=r,this.lines=0,this.crlfCount=0,this.lfOnlyCount=0,this.continuesLine=t.length>0}count(e){this.strict&&this.validate(e),0===this.lines&&e.length>0&&10!==e[0]&&(this.continuesLine=!0);for(let t=e.indexOf(10);-1!==t;t=e.indexOf(10,t+1))(t>0?13===e[t-1]:this.previousEndsWithCr)?this.crlfCount++:this.lfOnlyCount++,this.lines++;e.length>0&&(this.previousEndsWithCr=13===e[e.length-1])}finish(){if(this.strict&&this.carry.length>0)throw new I_}validate(e){let t=e;if(this.carry.length>0){const r=A_(this.carry[0]??0)-this.carry.length;if(e.length0&&(0,n.isUtf8)(e.subarray(0,e.length-t))?"utf8_cut":"utf8_invalid"}(e)}async function O_(e,t){const r=t>0?Math.min(t,o_):o_,o=await c_(e,r);return o.length===t&&(0,n.isUtf8)(o)||ci(new zs.TextDecoder("utf-8",{fatal:!1}).decode(o,{stream:o.length===o_&&o.length!==t}))?{kind:"lossyUtf8",cacheEncoding:"utf8"}:{kind:"iconv",decoderEncoding:"latin1",cacheEncoding:"latin1"}}async function F_(e){const t=await(0,Co.stat)(e),r=await Hi(e);if(r.isBinaryFile)return;const n=M_({file:e,stats:t,format:r},void 0);if("iconv"===n.kind)return n.decoderEncoding;const o=await O_(e,t.size);return"iconv"===o.kind?o.decoderEncoding:void 0}async function N_(e,{file:t,stats:r},n,o,s){const i=r.size,a=void 0!==n.offset||void 0!==n.limit,c=(n.offset??1)<0,l=n.offset??1,u=Math.max(0,l-1),d=void 0===n.limit?void 0:u+n.limit,h=c?Math.abs(l):0,p=a?1/0:n.maxChars??1/0,f=a&&!c?n.maxChars??1/0:1/0;let m=[],g=0,w=!1,y=0,v=!1,b=!(c||a&&u<=0),S=!1;const k=[];let _,C=0,E=!1,x=0,P=!1,R=[],I=0,T=0,A=0,$=!1,M={text:"",truncated:!1},D=!1,O=!1,F=0,N=0,L=0,j=!1,U=!1;const B=e=>{let t=e;return!j&&t.length>0&&(j=!0,65279===t.charCodeAt(0)&&(U=!0,t=t.slice(1))),t},W=(e,t)=>t&&13===e.text.charCodeAt(e.text.length-1),H=()=>P||E&&C>=Gs,q=()=>v||w&&g>=Gs,z=(e,t)=>{if(H())return;const r=k.length>0?1:0;let n=Gs-C;if(r>0){if(n<=0)return void(E=!0);n--}const o=e.text.length>n?{line:{text:Vo(e.text,n),truncated:!0},hasNewline:t}:{line:e,hasNewline:t};k.push(o),C+=r+(o.line.truncated?n:o.line.text.length),e.truncated&&(E=!0),o.line.truncated&&(E=!0),W(o.line,t)&&x++,C-x>f&&(P=!0,_=F)},G=(e,t)=>{if(q())return;const r=m.length>0?1:0;let n=Gs-g;if(r>0){if(n<=0)return void(w=!0);n--}const o=e.text.length>n?{line:{text:Vo(e.text,n),truncated:!0},hasNewline:t}:{line:e,hasNewline:t};m.push(o),g+=r+(o.line.truncated?n:o.line.text.length),(e.truncated||o.line.truncated)&&(w=!0),W(o.line,t)&&y++,g-y>p&&(v=!0,_=F)},V=(e,t)=>{e&&(t?N++:L++),F++},K=()=>{const e=R[I];void 0!==e&&(A-=e.line.text.length+1),R[I]=void 0,I=(I+1)%R.length,T--},J=(e,t,r)=>{const n=F;if(0===n&&(S=0===e.text.length),!c&&a&&b&&n>=u&&(b=!1,m=[]),b&&G(e,t),c){if(h>0)for(T===h&&K(),(e=>{if(T===R.length){const e=new Array(Math.min(h,Math.max(16,2*R.length)));for(let t=0;t1&&A>Gs;)K(),$=!0}else a&&n>=u&&(void 0===d||n!(D||(!b||q())&&(!a||0!==F)&&!(c?h>0:!(!a||H())&&F>=u&&F<(d??1/0))),X=()=>{const e=M.text.length-1;if(a){const t=!c&&F>=u&&F<(d??1/0),r=k.length>0?1:0;if(!t||C-x+r+e<=f)return;z(M,!1)}else{const t=m.length>0?1:0;if(g-y+t+e<=p)return;G(M,!1)}M={text:"",truncated:!1},D=!0};let Q;const Y=e=>{if(void 0===n.maxChars||c)return;if(!(a?H()||F>=(d??1/0):q()))return;const t=e.subarray(e.length-T_(e));return Q=new $_(ee,Buffer.from(t),"strictUtf8"===o.kind),Q};let ee=!1;for await(const r of async function*(e,t,r,n,o){const s=function(e){return e>0?{start:0,end:e-1}:{}}(n);if("strictUtf8"===r.kind||"lossyUtf8"===r.kind){const n=new zs.TextDecoder("utf-8",{fatal:"strictUtf8"===r.kind,ignoreBOM:!0}),i=(0,xo.createReadStream)(t,{highWaterMark:n_,signal:e.signal,...s});let a;try{for await(const e of i){if(void 0!==a){a.count(e);continue}const t=n.decode(e,{stream:!0});t.length>0&&(yield t),e.length>=4&&(a=o?.(e))}if(void 0!==a)return void a.finish();const e=n.decode();e.length>0&&(yield e)}catch(e){if(e instanceof TypeError)throw new I_;throw e}return}const i=(0,xo.createReadStream)(t,{highWaterMark:n_,signal:e.signal,...s}).pipe(Vs.decodeStream(r.decoderEncoding));for await(const e of i)yield"string"==typeof e?e:String(e)}(e,t,o,i,Y)){const e=B(r);let t=0,n=e.indexOf("\n",t);for(;-1!==n;){const r=n>t?13===e.charCodeAt(n-1):ee;Z()?(M=C_(M,e.slice(t,n)),J(M,!0,r)):(D&&n>t&&(O=!0),V(!0,r)),M={text:"",truncated:!1},D=!1,ee=!1,t=n+1,n=e.indexOf("\n",t)}t0&&N/te*100>=5,ne="utf8"===o.cacheEncoding&&U?"utf8bom":o.cacheEncoding;s&&Yi(t,r,ne);const oe=Math.min(F,a?d??1/0:1/0),se=void 0!==_&&(O||oe>_+1),ie=(n.maxChars??1/0)+n_,ae=e=>e.text.length>ie?{text:Vo(e.text,ie),truncated:!0}:e,ce=()=>E_({text:"",truncated:w||se},m,re);if(!a){const e=ae(ce());return{content:e.text,totalLines:F,truncated:e.truncated,rangeApplied:!1}}if(F<=1&&S)return{content:"",totalLines:F,truncated:!1,rangeApplied:!1};if(c){const e=n.limit??h,t=[];for(let e=0;e=F){const e=ce();return{content:e.text,totalLines:F,truncated:e.truncated,rangeApplied:!1}}const le=ae(E_({text:"",truncated:E||se},k,re));return{content:le.text,totalLines:F,truncated:le.truncated,rangeApplied:!0}}class L_{constructor(e,t,r){this.permissionsService=e,this.workspacePath=t,this.terminalReads=new Zl,this.mcpStateAccessor=r?.mcpStateAccessor,this.useStreamingRead=r?.useStreamingRead,this.pendingDecisionProvider=r?.pendingDecisionProvider,this.encodingSlices=r?.encodingSlices}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{!function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(r,(0,$.VI)(e.withName("LocalReadExecutor.execute")),!1);const o=t.path;if(""===o.trim())return new Ky.sV({result:{case:"error",value:new Ky.F_({path:o,error:es})}});const i=(0,Yo.o1)(o,this.workspacePath),a=await i_(e,"permissionsService.shouldBlockFileRead",3e3,(()=>Zk(this.permissionsService,i)));if(a){const r=await i_(e,"resolveFileReadBlock",3e3,(()=>async function(e,t){return await Qu(e,{onNeedsApproval:async(e,r)=>{const n=t.pendingDecisionProvider?.requestReadApproval?.bind(t.pendingDecisionProvider);if("fileRead"!==r.type||!n)return{kind:"denied",message:"Blocked by permissions configuration"};const o=await n({type:Lw.Read,details:{path:r.path,reason:e},toolCallId:t.toolCallId});return o.approved?null:{kind:"rejected",reason:o.reason}},onUserRejected:e=>({kind:"rejected",reason:e}),onPermissionDenied:e=>({kind:"denied",message:e})})??{kind:"proceed"}}(a,{pendingDecisionProvider:this.pendingDecisionProvider,toolCallId:t.toolCallId})));if("rejected"===r.kind)return new Ky.sV({result:{case:"rejected",value:new Ky.f4({path:i,reason:r.reason??""})}});if("denied"===r.kind)return new Ky.sV({result:{case:"permissionDenied",value:new Ky.lW({path:i})}})}void 0!==this.mcpStateAccessor&&qy(e,this.mcpStateAccessor,i);try{const r=await i_(e,"stat",3e3,(()=>(0,Co.stat)(i)));if(r.isDirectory())return new Ky.sV({result:{case:"invalidFile",value:new Ky.cW({path:i,reason:"Path is a directory, not a file"})}});if(!r.isFile())return new Ky.sV({result:{case:"invalidFile",value:new Ky.cW({path:i,reason:"Path is neither a file nor a directory"})}});const o=function(e){return null!==function(e){const t=nh(e,"terminals");if(!t||1!==t.remainingPath.length)return null;const r=t.remainingPath[0],n=/^(\d+)\.txt$/.exec(r);if(!n)return null;const o=Number.parseInt(n[1],10);return Number.isNaN(o)?null:{id:o}}(e)}(i),a=function(e){const t=nh(e,"agent-tools");return null!==t&&1===t.remainingPath.length&&t.remainingPath[0].endsWith(".txt")}(i);if(o||a)return await this.readTerminalFile(e,i,r,t,a&&!o);const c=await i_(e,"getFormatForFile",3e3,(()=>Hi(i))),l=c.isImageFile,u=function(e){return".pdf"===(0,s.extname)(e).toLowerCase()}(i),d=Ni(i);if(l){const t=await i_(e,"prepareImageForModel",3e3,(async()=>(async e=>{let t;try{t=await Lv(e)}catch(t){const r=await jv(e);if("undecodable"===r.kind)return r;throw t}if(!0===t.reencoded)return{kind:"image",image:t};const r=await jv(t.data);return"undecodable"===r.kind?r:{kind:"image",image:t}})(await(0,Co.readFile)(i))));return"undecodable"===t.kind?new Ky.sV({result:{case:"invalidFile",value:new Ky.cW({path:i,reason:(n=t.reason,`File is not a valid image: its data could not be decoded (${n}). A truncated or hand-copied file does this; write it again from the original bytes with code.`)})}}):new Ky.sV({result:{case:"success",value:new Ky.mE({path:i,output:{case:"data",value:t.image.data},totalLines:0,fileSize:a_(r.size),truncated:!1})}})}if(u){const t=await i_(e,"readPdfBinary",3e3,(()=>(0,Co.readFile)(i)));return new Ky.sV({result:{case:"success",value:new Ky.mE({path:i,output:{case:"data",value:t},totalLines:0,fileSize:a_(r.size),truncated:!1})}})}if(c.isBinaryFile&&d){if(void 0!==t.maxVideoBytes&&r.size>t.maxVideoBytes)return new Ky.sV({result:{case:"success",value:new Ky.mE({path:i,totalLines:0,fileSize:a_(r.size),truncated:!0})}});const n=await i_(e,"readBinaryFile",3e3,(()=>(0,Co.readFile)(i)));return new Ky.sV({result:{case:"success",value:new Ky.mE({path:i,output:{case:"data",value:n},totalLines:0,fileSize:a_(r.size),truncated:!1})}})}if(c.isBinaryFile)return m_(i);{const n=this.useStreamingRead,o=!n||await i_(e,"useStreamingRead",3e3,(()=>n()));if(o||r.size>Gs){const n=await i_(e,"readTextStreaming",7e3,(()=>async function(e,t,r,n){const o=M_(t,r.encodingHint);try{return{...await N_(e,t,r,o,n),decoder:o.kind}}catch(o){if(o instanceof I_){const o=await O_(t.file,t.stats.size);return{...await N_(e,t,r,o,n),decoder:o.kind}}throw o}}(e,{file:i,stats:r,format:c},t,o))),s=R_(n.content,n.truncated,t);return Ul(this.encodingSlices,e)&&this.recordStreamedRead(e,i,r.size,n,s),new Ky.sV({result:{case:"success",value:new Ky.mE({path:i,output:{case:"content",value:s},totalLines:n.totalLines,fileSize:a_(r.size),truncated:n.truncated,rangeApplied:n.rangeApplied})}})}const s=await i_(e,"readText",3e3,(()=>ji(i,t.encodingHint))),a=await i_(e,"countLines",3e3,(()=>Js(s))),l=function(e,t,r){const n=g_(t,""===e,r);return n.applied?n.start>=n.end?{content:"",rangeApplied:!0}:{content:b_(e,n.start,n.end),rangeApplied:!0}:{content:e,rangeApplied:!1}}(s,a,t);let u=l.content,d=!1;const h=P_(t);return u.length>h&&(u=R_(u.substring(0,h),!0,t),d=!0),u.length16777216)return"other_encoding";try{return r=await c_(e,t),!(0,n.isAscii)(r)&&(0,n.isUtf8)(r)?"utf8_as_other":"other_encoding"}catch{return"other_encoding"}var r}(t,r)),eu(this.encodingSlices,e,{layer:"exec_read",evidence:a,partial:o.rangeApplied||o.truncated},i)}catch{}}async readTerminalFile(e,t,r,n,o){const s=await i_(e,"readTerminalFile",3e3,(()=>c_(t,r.size)));if(o&&(i=s,f_.some((e=>function(e,t){return e.length>=t.length&&e.subarray(0,t.length).equals(t)}(i,e)))))return m_(t);var i;const a=function(e,t,r=8388608){if(0===e.length)return{content:"",totalLines:1,rangeApplied:!1,truncated:!1};const n=l_(e),o=p_(e,n);if("utf-8"!==d_(e.subarray(n,o)))return function(e,t,r){const n=0===e.length,o=function(e){let t=0,r=0;const n=e.length;for(;r=s.end)return{content:"",totalLines:o,rangeApplied:!0,truncated:!1};const i=v_((t=>e.indexOf("\n",t)),e.length,(t=>e.charCodeAt(t-1)),s.start,s.end,!0),a=k_(e,i.from,i.to,r);return{content:a.text,totalLines:o,rangeApplied:!0,truncated:a.truncated}}(function(e){const t=l_(e),r=t>0?e.subarray(0,t).toString("utf-8"):"",n=p_(e,t),o=nr?-1:239===e[t]&&187===e[t+1]&&191===e[t+2]?t:-1}(e,n,o);return function(e,t,r,n){const o=e.length-(t>=0?3:0)==0,s=function(e){let t=0,r=0;const n=e.length;for(;r=i.end)return{content:"",totalLines:s,rangeApplied:!0,truncated:!1};const a=v_((t=>e.indexOf(10,t)),e.length,(t=>e[t-1]??0),i.start,i.end,!0),c=S_(e,a.from,a.to,t,n);return{content:c.text,totalLines:s,rangeApplied:!0,truncated:c.truncated}}(e,s,t,r)}(s,n,P_(n)),c=R_(a.content,a.truncated,n);return Ul(this.encodingSlices,e)&&(o||this.terminalReads.firstRead(n.toolCallId,t))&&Yl(this.encodingSlices,e,{layer:o?"exec_read":"exec_terminal_context",evidence:D_(s),partial:a.rangeApplied||a.truncated},c),new Ky.sV({result:{case:"success",value:new Ky.mE({path:t,output:{case:"content",value:c},totalLines:a.totalLines,fileSize:a_(r.size),truncated:a.truncated,rangeApplied:a.rangeApplied})}})}}function j_(e){return Buffer.from(e,"utf16le").toString("utf16le")}var U_=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},B_=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function W_(e){return`Path '${e}' could not be verified while resolving symlinks. This can happen when access is denied or the path contains a symlink loop.`}function H_(e){return`Path '${e}' is neither a file nor a directory`}async function q_(e){const t=await(0,Co.stat)(e).catch((()=>{}));return void 0!==t&&!t.isFile()&&!t.isDirectory()}function z_(e,t,r){const n=function(e,t){let r;for(const n of t)(0,Yo.ZU)({basePath:n,targetPath:e})&&(void 0===r||n.length>r.length)&&(r=n);return r}((0,s.resolve)(e,t),r);return void 0===n||n===e}class G_ extends Error{}function V_(e){const t=new AbortController,r=setTimeout((()=>t.abort()),e);return{signal:t.signal,clear:()=>clearTimeout(r)}}function K_(e){switch(e.result.case){case"content":return e.result.value.matches.length>0;case"files":return e.result.value.files.length>0;case"count":return e.result.value.counts.length>0;case void 0:return!1;default:{const t=e.result;throw new Error(`Unknown grep result: ${String(t)}`)}}}function J_(e){switch(e){case"content":return new Ey.vD({result:{case:"content",value:new Ey.Zp({ripgrepTruncated:!0})}});case"files_with_matches":return new Ey.vD({result:{case:"files",value:new Ey.T7({ripgrepTruncated:!0})}});case"count":return new Ey.vD({result:{case:"count",value:new Ey.xA({ripgrepTruncated:!0})}});default:throw new Error(`Unknown output mode: ${String(e)}`)}}function Z_(e){return"success"===e.result.case&&Object.values(e.result.value.workspaceResults).some((e=>!0===e.result.value?.clientTruncated))}function X_(e,t,r){let n=Buffer.concat(e);t&&(n=n.subarray(0,n.lastIndexOf(10)+1)),r?.note(n);const o=n.toString("utf8");return o.includes("�")?{stdout:o,stdoutBytes:n}:{stdout:o}}function Q_(e){return/^(utf-?16|ucs-?2)/i.test(e)}const Y_=(0,l.h)("local-exec/grep"),eC=(0,u.Pu)("local_exec.grep.deadline_reached",{description:"Grep and Glob searches the search deadline stopped, by whether they kept what was found",labelNames:["output_mode","outcome","streaming"]}),tC=(0,u.Pu)("local_exec.grep.newest_first_stat_fallback",{description:"Grep and Glob results left in ripgrep's order because stat was too slow to sort them",labelNames:["output_mode"]}),rC=(0,u.v5)("local_exec.grep.rg.spawn_ms",{description:"Time to start the ripgrep process for one Grep or Glob search",labelNames:["sandboxed"]}),nC=(0,u.v5)("local_exec.grep.rg.search_ms",{description:"Time ripgrep took to search and exit after it started, for runs it finished",labelNames:["output_mode","sandboxed"]});function oC(e){return e instanceof Error&&e.message.includes("ENOENT")&&e.message.includes("spawn")}function sC(e){try{return(0,xo.existsSync)(e)}catch{return"check_failed"}}function iC(e){if("object"==typeof e&&null!==e&&"errno"in e){const t=e.errno;if("number"==typeof t)return t}}function aC(e,t){if("object"==typeof e&&null!==e)return"syscall"===t&&"syscall"in e&&"string"==typeof e.syscall?e.syscall:"path"===t&&"path"in e&&"string"==typeof e.path?e.path:void 0}function cC(e,t,r,n){return{...uC(e),...n,cwd:t,cwdExists:sC(t),errorMessage:kc(r),errorCode:Sc(r),errno:iC(r),syscall:aC(r,"syscall"),errorPath:aC(r,"path")}}function lC(e){return new Error(`Path does not exist: ${e}`)}function uC(e){const t={rgPath:e,platform:process.platform,arch:process.arch,pid:process.pid,uptimeSeconds:Math.round(process.uptime()),execPath:process.execPath};try{t.rgPathExists=(0,xo.existsSync)(e)}catch(e){t.rgPathExists=!1,t.rgPathExistsError=e instanceof Error?e.message:String(e)}try{const r=(0,xo.lstatSync)(e);t.rgIsSymlink=r.isSymbolicLink(),r.isSymbolicLink()&&!t.rgPathExists&&(t.rgBrokenSymlink=!0)}catch{t.rgLstatFailed=!0}const r=(0,s.dirname)(e);try{t.parentDirExists=(0,xo.existsSync)(r),t.parentDirExists&&(t.parentDirContents=(0,xo.readdirSync)(r).slice(0,50))}catch(e){t.parentDirError=e instanceof Error?e.message:String(e)}const n=(0,s.dirname)(r);try{t.grandparentDirExists=(0,xo.existsSync)(n),t.grandparentDirExists&&(t.grandparentDirContents=(0,xo.readdirSync)(n).slice(0,50))}catch(e){t.grandparentDirError=e instanceof Error?e.message:String(e)}if(t.rgPathExists)try{const r=(0,xo.statSync)(e);t.rgFileSize=r.size,t.rgFileMode=r.mode.toString(8),t.rgIsFile=r.isFile(),t.rgModifiedMs=r.mtimeMs}catch(e){t.rgStatError=e instanceof Error?e.message:String(e)}const o="node_modules.asar.unpacked";if(e.includes(o)){const r=e.split(o)[0];if(r){const n=r.concat("node_modules.asar");try{t.asarExists=(0,xo.existsSync)(n)}catch{t.asarExists="check_failed"}const i=r.concat(o);try{if(t.asarUnpackedDirExists=(0,xo.existsSync)(i),t.asarUnpackedDirExists){const r=(0,s.dirname)((0,s.dirname)(e));t.ripgrepPkgDirExists=(0,xo.existsSync)(r)}}catch{t.asarUnpackedDirExists="check_failed"}}}return t}class dC{constructor(e,t,r,n){this.ignoreService=e,this.grepProvider=t,this.workspacePath=r,this.stdoutDecodes=new WeakMap;const o=Array.isArray(this.workspacePath)?this.workspacePath[0]:this.workspacePath;this.singleWorkspacePath=Array.isArray(this.workspacePath)&&this.workspacePath.length>1?void 0:o,this.mcpStateAccessor=n?.mcpStateAccessor,this.permissionsService=n?.permissionsService,this.useStreamingGrep=n?.useStreamingGrep,this.encodingSlices=n?.encodingSlices}computeRelativeTarget(e,t){const r=(0,Yo.o1)(e,this.singleWorkspacePath??t);return r===t?".":(0,s.relative)(t,r)}isRootIndependentSearchPath(e){return(0,s.isAbsolute)(e)||/^~(?=$|[/\\])/.test(e)||e.startsWith("file://")}resolveSearchTargets(e,t){const r=this.isRootIndependentSearchPath(e);return t.map((t=>{const n=(0,s.resolve)(t);return{root:t,resolvedRoot:n,target:(0,Yo.o1)(e,r?void 0:n)}}))}findOutsideTargets(e,t){if(void 0===e||""===e)return;const r=this.resolveSearchTargets(e,t);return r.some((({resolvedRoot:e,target:t})=>(0,Yo.BJ)(t,e)))?void 0:[...new Set(r.map((({target:e})=>e)))]}searchTarget(e,t){if(!t.path)return".";const r=(0,Yo.o1)(t.path,this.singleWorkspacePath??e);return(0,Yo.BJ)(r,(0,s.resolve)(e))?this.computeRelativeTarget(t.path,e):r}sortsAfterRipgrep(e,t,r){return void 0===t.sort&&(r?!0!==t.sortAscending:(0,s.isAbsolute)(this.searchTarget(e,t)))}async buildArgs(e,t,r,n){const o=[],s=function(e,t){return"files_with_matches"===t&&""===e.pattern&&Boolean(e.glob)}(t,r),i=await pa(await this.ignoreService.listCursorIgnoreFilesByRoot(e));for(const e of i)o.push("--cursor-ignore",e);if("content"===r)o.push("--line-number","--with-filename","--no-heading","-0"),void 0!==t.contextBefore&&o.push("--before-context",String(t.contextBefore)),void 0!==t.contextAfter&&o.push("--after-context",String(t.contextAfter)),o.push("--max-columns",String(1e3),"--max-columns-preview"),void 0!==t.context&&void 0===t.contextBefore&&void 0===t.contextAfter&&o.push("--before-context",String(t.context),"--after-context",String(t.context));else if("files_with_matches"===r)o.push(s?"--files":"-l");else{if("count"!==r)throw new Error(`Unknown output mode: ${String(r)}`);o.push("-c","--with-filename")}!0===t.caseInsensitive?o.push("--ignore-case"):o.push("--case-sensitive"),t.type&&o.push("--type",t.type),t.glob&&(o.push("--iglob",t.glob),s&&o.push("--iglob","!**/.git")),t.multiline&&o.push("--multiline","--multiline-dotall");const a=n?"none":t.sort??"modified";if(n&&o.push("--line-buffered"),"none"!==a){const e=!0===t.sortAscending?"--sort":"--sortr";o.push(e,a)}o.push("--no-config","--color=never"),o.push("--hidden"),o.push("--follow");const c=this.searchTarget(e,t);if(t.path){const t=await async function(e){try{if(!(await(0,Co.stat)(e)).isFile())return;const{encoding:t}=await Hi(e);return Q_(t)?t.toLowerCase():void 0}catch{return}}((0,Yo.o1)(c,e));void 0!==t&&o.push("--encoding",t)}return s||o.push("--regexp",t.pattern),o.push("--"),o.push(c),o}async filterBlockedFiles(e,t){const r=new Map,n=await(this.permissionsService?.getFileReadBoundaryBlocker?.()),o=[];for(const s of e){const e=(0,Yo.o1)(s.file,t),i=await Cc(e);null===i||await this.isPostRipgrepBlocked(i,r)||void 0!==n&&await n(e,i)||o.push(s)}return o}async isPostRipgrepBlocked(e,t){const[r,n]=await Promise.all([this.ignoreService.isCursorIgnored(e,t),this.ignoreService.isRepoBlocked(e)]);return r||n}throwOnRipgrepFailure(e,t,r){if((""!==e.stderr||2===e.exitCode)&&""===e.stdout.trim()&&!function({stderr:e,target:t}){return e.trim().split(/\r?\n/).every((e=>{if(/^rg: .+: line \d+: /.test(e))return!0;const r=/^rg: (.+?): .*\(os error (?:13|5|2|1)\)$/.exec(e)?.[1]??/^rg: File system loop found: (.+) points to an ancestor /.exec(e)?.[1];return void 0!==r&&r!==t}))}({stderr:e.stderr,target:this.searchTarget(t,r)}))throw new Error(e.stderr||`ripgrep exited with code ${e.exitCode}`)}async orderNewestFirst(e,t,r,n,o){const s=await Vy(t,(e=>(0,Yo.o1)(n(e),r)));return s.statTimedOut&&(Y_.info(e,"newest_first.stat_timeout_fallback",{toolCallId:o.toolCallId,execId:o.execId,outputMode:o.outputMode,fileCount:t.length}),tC.increment(e,1,{output_mode:o.outputMode})),s.items}async keepNewestPage(e,t,r,n,o){return(await this.orderNewestFirst(e,t,r,n,o)).slice(0,dC.CLIENT_LIMIT_LINES)}async runFilesMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const d=U_(a,(0,$.VI)(e.withName("LocalGrepExecutor.runFilesMode")),!1),h=await this.buildArgs(t,r,"files_with_matches",n),p=await this.executeRg(d.ctx,t,h,void 0,o,s,i);this.throwOnRipgrepFailure(p,t,r);const f=(c=p.stdout,l=n?dC.HARD_MAX_OUTPUT_LINES:dC.CLIENT_LIMIT_LINES,u=dC.HARD_MAX_OUTPUT_LINES,function(e,t,r){const n=e.trim();if(""===n)return{files:[],totalFiles:0,clientTruncated:!1,ripgrepTruncated:!1};const o=new xy;let s=0,i=0,a=0;for(;Py(n,a,o);)a=o.nextStart,st?Buffer.from(n.slice(0,i)).toString():n,l=[];for(a=0;l.lengtht,ripgrepTruncated:s>=r}}(c,l,u)),m=f.totalFiles>dC.CLIENT_LIMIT_LINES;let g=f.files;n&&(g=await this.keepNewestPage(d.ctx,g,t,(e=>e),i),m&&(g=g.join("\0").split("\0")));const w=(await this.filterBlockedFiles(g.map((e=>({file:e}))),t)).map((({file:e})=>e)),y=g.length-w.length,v=new Ey.T7({files:w,totalFiles:Ay(f.totalFiles-y),clientTruncated:m,ripgrepTruncated:f.ripgrepTruncated||p.timedOut||p.stdoutByteCapped});return{result:new Ey.vD({result:{case:"files",value:v}}),timedOut:p.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{B_(a)}var c,l,u}async runCountMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const d=U_(a,(0,$.VI)(e.withName("LocalGrepExecutor.runCountMode")),!1),h=await this.buildArgs(t,r,"count",n),p=await this.executeRg(d.ctx,t,h,void 0,o,s,i);this.throwOnRipgrepFailure(p,t,r);const f=(c=p.stdout,l=n?dC.HARD_MAX_OUTPUT_LINES:dC.CLIENT_LIMIT_LINES,u=dC.HARD_MAX_OUTPUT_LINES,function(e,t,r){const n=e.trim();if(""===n)return{counts:[],totalFiles:0,totalMatches:0,clientTruncated:!1,ripgrepTruncated:!1};const o=[],s=new xy;let i=0;for(;Py(n,i,s);){const e=i,t=s.lineEnd;if(i=s.nextStart,t===e)continue;const r=n.lastIndexOf(":",t-1);if(rt,ripgrepTruncated:a>=r}}(c,l,u)),m=n?await this.keepNewestPage(d.ctx,f.counts,t,(e=>e.file),i):f.counts,g=await this.filterBlockedFiles(m,t),w=g.reduce(((e,t)=>e+t.count),0),y=m.length-g.length,v=m.reduce(((e,t)=>e+t.count),0)-w,b=new Ey.xA({counts:g.map((e=>new Ey.sS({file:e.file,count:Ay(e.count)}))),totalFiles:Ay(f.totalFiles-y),totalMatches:Ay(f.totalMatches-v),clientTruncated:f.totalFiles>dC.CLIENT_LIMIT_LINES,ripgrepTruncated:f.ripgrepTruncated||p.timedOut||p.stdoutByteCapped});return{result:new Ey.vD({result:{case:"count",value:b}}),timedOut:p.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{B_(a)}var c,l,u}async runContentMode(e,t,r,n,o,s,i){const a={stack:[],error:void 0,hasError:!1};try{const c=U_(a,(0,$.VI)(e.withName("LocalGrepExecutor.runContentMode")),!1),l=await this.buildArgs(t,r,"content",n),u=void 0!==r.context||void 0!==r.contextBefore||void 0!==r.contextAfter,d=dC.CLIENT_LIMIT_LINES*(u?2:1),h=await this.executeRg(c.ctx,t,l,d,o,s,i);this.throwOnRipgrepFailure(h,t,r);const p=await this.decodeLinesAsRead(c.ctx,h,t,i),{byFile:f,totalLines:m,totalMatchedLines:g,clientTruncated:w,ripgrepTruncated:y}=function(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{return U_(o,(0,$.VI)(n.withName("parseContentOutput")),!1),function(e,t,r){const n={byFile:new Map,totalLines:0,totalMatchedLines:0,totalFiles:0,clientTruncated:!1,ripgrepTruncated:!1};if(""===e.trim())return n;const o=new Map,s=new Set,i=new xy;let a=0,c=0,l=0,u=0;for(;Py(e,u,i);){const r=u,n=i.lineEnd;if(u=i.nextStart,l++,d=e,n-(h=r)==2&&45===d.charCodeAt(h)&&45===d.charCodeAt(h+1))continue;let p=-1;for(let t=r;t=n)continue;let m=0,g=0;for(;f57)break;m=10*m+(t-48),g++,f++}if(0===g||f>=n||!Number.isFinite(m))continue;const w=e.charCodeAt(f);if(58!==w&&45!==w)continue;const y=45===w;y||a++;const v=e.slice(r,p);if(s.has(v)||s.add(v),c>=t)continue;const b=e.slice(f+1,n);let S=o.get(v);void 0===S&&(S={file:v,matches:[]},o.set(v,S)),S.matches.push({lineNumber:m,content:b,isContextLine:y}),c++}var d,h;return{byFile:o,totalLines:Ay(l),totalMatchedLines:Ay(a),totalFiles:Ay(s.size),clientTruncated:c>=t,ripgrepTruncated:l>=r}}(e,t,r)}catch(e){o.error=e,o.hasError=!0}finally{B_(o)}}(p,dC.CLIENT_LIMIT_LINES,d,c.ctx),v=Array.from(f.values()),b=await this.filterBlockedFiles(v,t),S=v.filter((e=>!b.includes(e))),k=S.reduce(((e,t)=>e+t.matches.length),0),_=S.reduce(((e,t)=>e+t.matches.filter((e=>!e.isContextLine)).length),0),C=n?await this.orderNewestFirst(c.ctx,b,t,(e=>e.file),i):b,E=new Ey.Zp({matches:C.map((e=>new Ey.uI({file:e.file,matches:e.matches.map((e=>new Ey.dx({lineNumber:e.lineNumber,content:e.content,isContextLine:e.isContextLine})))}))),totalLines:Ay(m-k),totalMatchedLines:Ay(g-_),clientTruncated:w,ripgrepTruncated:y||h.timedOut||h.stdoutByteCapped});return{result:new Ey.vD({result:{case:"content",value:E}}),timedOut:h.timedOut}}catch(e){a.error=e,a.hasError=!0}finally{B_(a)}}async decodeLinesAsRead(e,t,r,o){const s={stack:[],error:void 0,hasError:!1};try{const i=t.stdoutBytes;if(void 0===i)return t.stdout;const a=U_(s,(0,$.VI)(e.withName("LocalGrepExecutor.decodeLinesAsRead")),!1),c=function(e,t){const r=[],o=new xy;let s=0,i=0,a=e.indexOf("�");for(;-1!==a&&Py(e,s,o);){const{lineEnd:c,nextStart:l}=o,u=t.indexOf(10,i),d=-1===u?t.length:u+1;let h=-1===u?t.length:u;if(h>i&&-1!==u&&13===t[h-1]&&h--,ae.file)))],u=new Map,d=performance.now()+dC.LINE_ENCODING_TIMEOUT_MS;let h=0;for(;h{let d=!1,h=!1;const p=()=>{h||(h=!0,a.span.end())};if(e.signal.aborted)return p(),void u(new Error("Grep was cancelled"));if(o.aborted)return p(),void u(dC.ripgrepTimeoutError());let f;const m="insecure_none"===s.type?"false":"true",g=performance.now();let w=g;try{const e=s;f=(0,Oo.spawnInSandbox)((0,Oo.Ko)(),r,{cwd:t},e),w=performance.now(),0}catch(r){if(p(),oC(r)){const n=(0,Oo.Ko)();if(Y_.error(e,"rg_diagnostics.spawn_throw",void 0,cC(n,t,r,i)),!1===sC(t))return u(lC(t))}return u(r)}const y=[],v=[];let b=0,S=0,k=0,_=!1,C=!1,E=!1;const x=()=>{if(!d)try{p(),E=!0;const e=X_(y,!0,this.stdoutDecodes.get(i));""===e.stdout?u(dC.ripgrepTimeoutError()):l({...e,stderr:"",exitCode:0,timedOut:!0,stdoutByteCapped:C}),f.kill()}catch{}};o.addEventListener("abort",x,{once:!0});const P=()=>{o.removeEventListener("abort",x),p(),u(new Error("Grep was cancelled"));try{f.kill()}catch{}};e.signal.addEventListener("abort",P,{once:!0}),f.stdout?.on("data",(e=>{if(!C&&!_)if(b+=e.length,b>c){C=!0;try{f.kill()}catch{}}else if(void 0!==n){let t=-1,r=0;for(let o=0;o=n)){t=o+1,_=!0;try{f.kill()}catch{}break}k+=r;const o=t>=0?e.subarray(0,t):e;y.push(o)}else y.push(e)})),f.stderr?.on("data",(e=>{S+=e.length,S<=c&&v.push(e)})),f.on("error",(r=>{if(o.removeEventListener("abort",x),e.signal.removeEventListener("abort",P),p(),oC(r)){const n=(0,Oo.Ko)();if(Y_.error(e,"rg_diagnostics.spawn_enoent",void 0,cC(n,t,r,i)),!1===sC(t))return void u(lC(t))}u(r)})),f.on("close",(t=>{const r=performance.now()-w;d=!0,o.removeEventListener("abort",x),e.signal.removeEventListener("abort",P);const n=X_(y,C,E?void 0:this.stdoutDecodes.get(i)),s=Buffer.concat(v).toString("utf8");p(),l({...n,stderr:s,exitCode:t??0,timedOut:!1,stdoutByteCapped:C}),rC.histogram(e,w-g,{sandboxed:m}),C||_||o.aborted||e.signal.aborted||0!==t&&1!==t||nC.histogram(e,r,{output_mode:i.outputMode,sandboxed:m})}))}))}async checkOutsideTarget(e,t){if(1!==t.length||void 0===t[0])return{error:`Path '${e}' points to a different folder from each workspace root; use an absolute path`};const r=await Cc(t[0]);return null===r?{error:W_(e)}:await this.ignoreService.isCursorIgnored(r)?{error:`Path '${e}' is filtered out by .cursorignore`}:await q_(t[0])?{error:H_(e)}:{resolvedTarget:r}}async execute(e,t,r){if(!Ul(this.encodingSlices,e))return this.search(e,t,r,void 0);const n=new tu,o=await this.search(e,t,r,n);return"success"===o.result.case&&Yl(this.encodingSlices,e,{layer:"exec_grep",evidence:n.evidence(),partial:Z_(o)},o),o}async search(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{const a=U_(o,(0,$.VI)(e.withName("LocalGrepExecutor.execute")),!1),c=Array.isArray(this.workspacePath)?this.workspacePath:[this.workspacePath??process.cwd()],l=t.outputMode??"content";if("content"!==(i=l)&&"files_with_matches"!==i&&"count"!==i)throw new Error(`Unknown output mode: ${l}`);const u=l,d={toolCallId:t.toolCallId,execId:r?.execId,outputMode:u,targetPath:t.path,workspacePaths:c};void 0!==n&&this.stdoutDecodes.set(d,n);const h=ls(t.sandboxPolicy),p=this.grepProvider.getWorktreeGuardInfo?.(c);if((0,Yo.fl)({targetPath:t.path,workspacePaths:c,mainWorktreePath:p?.mainWorktreePath}))return new Ey.Ud({result:{case:"error",value:new Ey.ts({error:Yo.PS})}});const f=this.findOutsideTargets(t.path,c);let m=t,g=c;try{if(t.path&&void 0!==f){const r=await this.checkOutsideTarget(t.path,f);if("error"in r)return new Ey.Ud({result:{case:"error",value:new Ey.ts({error:r.error})}});void 0!==this.mcpStateAccessor&&qy(e,this.mcpStateAccessor,r.resolvedTarget),g=c.slice(0,1),m=t.clone(),m.path=f[0]}else if(m.path){const t=[];let r=!1;for(const{root:n,resolvedRoot:o,target:s}of this.resolveSearchTargets(m.path,c)){if(!(0,Yo.BJ)(s,o))continue;const i=await Cc(s);if(null!==i)if(await this.ignoreService.isCursorIgnored(i))r=!0;else{if(await q_(s))return new Ey.Ud({result:{case:"error",value:new Ey.ts({error:H_(m.path)})}});t.push(n),void 0!==this.mcpStateAccessor&&qy(e,this.mcpStateAccessor,i)}}if(0===t.length){const e=r?`Path '${m.path}' is filtered out by .cursorignore`:W_(m.path);return new Ey.Ud({result:{case:"error",value:new Ey.ts({error:e})}})}g=t}let r={};const n=void 0===f?await this.executeIndexedGrepWithTimeout(a.ctx,g,m,d):void 0;if(void 0!==n){r=n;for(const[e,t]of Object.entries(r)){const r=t.result;switch(r.case){case"content":r.value.matches=await this.filterBlockedFiles(r.value.matches,e);break;case"files":r.value.files=(await this.filterBlockedFiles(r.value.files.map((e=>({file:e}))),e)).map((({file:e})=>e));break;case"count":r.value.counts=await this.filterBlockedFiles(r.value.counts,e)}}}else{const e=await this.streamingEnabled(a.ctx,d),t=e?V_(dC.MAIN_TIMEOUT_MS):void 0;let n=0,o=!1;try{for(const s of g){if(!0===t?.signal.aborted){r[s]=J_(u),n++,o=!0;continue}if(!1===sC(s))return new Ey.Ud({result:{case:"error",value:new Ey.ts({error:`Path does not exist: ${s}`})}});const i=t??V_(dC.MAIN_TIMEOUT_MS);try{const t=await this.runMode(a.ctx,u,s,m,e,i.signal,h,d);r[s]=t.result,t.timedOut&&n++}catch(t){if(!(t instanceof G_))throw t;if(r[s]=J_(u),n++,o=!0,!e)break}finally{i!==t&&i.clear()}}}finally{t?.clear()}if(n>0){const t=o&&(!e||!Object.values(r).some(K_));if(this.reportDeadlineReached(a.ctx,d,{streaming:e,folderCount:g.length,stoppedFolderCount:n,outcome:t?"failed":"partial"}),t)throw dC.ripgrepTimeoutError()}}const o=function(e,t){if(t.length<=1)return e;const r=[...new Set(t.map((e=>(0,s.resolve)(e))))],n={};for(const[t,o]of Object.entries(e)){const e=(0,s.resolve)(t),i=t=>z_(e,t,r),a=o.result;switch(a.case){case"content":{const e=a.value,r=[];let o=0,s=0;for(const t of e.matches)i(t.file)?r.push(t):(o+=t.matches.length,s+=t.matches.filter((e=>!e.isContextLine)).length);const c=e.clone();c.matches=r,c.totalLines=Math.max(0,e.totalLines-o),c.totalMatchedLines=Math.max(0,e.totalMatchedLines-s),n[t]=new Ey.vD({result:{case:"content",value:c}});break}case"files":{const e=a.value,r=e.files.filter((e=>i(e))),o=e.clone();o.files=r,o.totalFiles=Math.max(0,e.totalFiles-(e.files.length-r.length)),n[t]=new Ey.vD({result:{case:"files",value:o}});break}case"count":{const e=a.value,r=[];let o=0;for(const t of e.counts)i(t.file)?r.push(t):o+=t.count;const s=e.clone();s.counts=r,s.totalFiles=Math.max(0,e.totalFiles-(e.counts.length-r.length)),s.totalMatches=Math.max(0,e.totalMatches-o),n[t]=new Ey.vD({result:{case:"count",value:s}});break}default:n[t]=o}}return n}(r,g),i=new Ey._0({pattern:m.pattern,path:void 0!==m.path&&this.isRootIndependentSearchPath(m.path)?(0,Yo.o1)(m.path):m.path,outputMode:u,workspaceResults:o});return new Ey.Ud({result:{case:"success",value:i}})}catch(e){if(m.path){const e=(0,Yo.o1)(m.path,this.singleWorkspacePath);try{await(0,Co.stat)(e)}catch(t){return new Ey.Ud({result:{case:"error",value:new Ey.ts({error:`Path does not exist: ${e}`})}})}}return new Ey.Ud({result:{case:"error",value:new Ey.ts({error:e instanceof Error?e.message:String(e)})}})}}catch(e){o.error=e,o.hasError=!0}finally{B_(o)}var i}}dC.MAIN_TIMEOUT_MS=25e3,dC.INDEXED_GREP_TIMEOUT_MS=25e3,dC.INDEXED_GREP_CONTEXT_TIMEOUT_MS=dC.INDEXED_GREP_TIMEOUT_MS+100,dC.HARD_MAX_OUTPUT_LINES=1e4,dC.CLIENT_LIMIT_LINES=2e3,dC.LINE_ENCODING_TIMEOUT_MS=2e3,je.object({record_v:je.number().int().nullish(),pid:je.number().int().nonnegative().nullish(),version:je.string().nullish(),started_at:je.number().nullish(),control_sock:je.string().nullish(),runtime_dir:je.string().nullish(),data_dir:je.string().nullish(),config_path:je.string().nullish(),log_path:je.string().nullish(),metrics_addr:je.string().nullish(),exe:je.string().nullish()}),je.object({mountpoint:je.string().nullish(),capabilities:je.array(je.string()).nullish(),nfs_transport:je.string().nullish(),bind_ignored:je.object({active:je.array(je.string()).nullish()}).passthrough().nullish()});const hC=je.object({daemon_alive:je.boolean().nullish(),mounts:je.array(je.unknown()).nullish(),data_plane:je.object({enabled:je.boolean().nullish()}).passthrough().nullish()});je.object({daemon_alive:je.boolean().nullish(),daemon_version:je.string().nullish(),capabilities:je.array(je.string()).nullish()}),hC.extend({memory:je.object({anon_bytes:je.number()}).nullish().catch(null)});const pC=je.number().int().nonnegative(),fC=je.object({line_no:je.number().int().positive(),kind:je.enum(["match","before","after"]),text:je.string().optional(),bytes:je.string().regex(/^(?:[0-9a-fA-F]{2})*$/).optional(),truncated:je.boolean().default(!1)}).refine((e=>void 0!==e.text||void 0!==e.bytes));je.object({type:je.literal("file"),path:je.string(),lines:je.array(fC)}),je.object({type:je.literal("summary"),files_searched:pC,more:je.boolean(),stop_reason:je.string().nullable(),skipped:je.object({over_size:pC,size_unknown:pC,budget_exhausted:pC,fetch_failed:pC,unreadable:pC})}),je.object({type:je.string()}),(0,l.h)("local-exec/grove-grep"),(0,u.Pu)("local_exec.grep.grove",{description:"Grep searches Grove served, or declined to ripgrep, by decline reason",labelNames:["outcome","reason"]}),(0,u.v5)("local_exec.grep.grove.served_ms",{description:"Time Grove took to answer a Grep search it served"});var mC=r("../proto/dist/generated/agent/v1/ls_exec_pb.js"),gC=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},wC=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class yC{constructor(e,t,r){this.permissionsService=e,this.ignoreService=t,this.workspacePath=r}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{gC(r,(0,$.VI)(e.withName("LocalLsExecutor.execute")),!1).ctx;const n=(0,Yo.o1)(t.path,this.workspacePath);try{let r;try{r=await(0,Co.stat)(n)}catch(e){return"ENOENT"===Sc(e)?function(e){const t=nh(e,"terminals");return null!==t&&0===t.remainingPath.length}(n)?new mC.fv({result:{case:"error",value:new mC.uj({path:n,error:"No active terminals."})}}):new mC.fv({result:{case:"error",value:new mC.uj({path:n,error:`Path does not exist: ${n}`})}}):new mC.fv({result:{case:"error",value:new mC.uj({path:n,error:kc(e)})}})}if(!r.isDirectory())return new mC.fv({result:{case:"error",value:new mC.uj({path:n,error:`Path is not a directory: ${n}`})}});const o=ls(t.sandboxPolicy),s=t.timeoutMs??5e3,i=e.withTimeout(s),{tree:a,didTimeout:c}=await this.getDirectoryTree(i,n,t.ignore,o);return c?new mC.fv({result:{case:"timeout",value:new mC.ze({directoryTreeRoot:a})}}):new mC.fv({result:{case:"success",value:new mC.PC({directoryTreeRoot:a})}})}catch(e){return new mC.fv({result:{case:"error",value:new mC.uj({path:n,error:e instanceof Error?e.message:"Unknown error occurred"})}})}}catch(e){r.error=e,r.hasError=!0}finally{wC(r)}}async getDirectoryTree(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{return gC(o,(0,$.VI)(e.withName("LocalLsExecutor.getDirectoryTree")),!1),await this.buildTreeFromRipgrepStream(e,t,r,n,2500)}catch(e){o.error=e,o.hasError=!0}finally{wC(o)}}async buildTreeFromRipgrepStream(e,t,r,n,o){const i={stack:[],error:void 0,hasError:!1};try{gC(i,(0,$.VI)(e.withName("LocalLsExecutor.buildTreeFromRipgrepStream")),!1);const a=(0,s.resolve)(t),c=new mC.vq({absPath:a,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!0,fullSubtreeExtensionCounts:{}}),l=new Map;l.set(a,c);const u={charactersUsed:a.length,budgetExceeded:!1},[d,h]=await Promise.all([this.ignoreService.listCursorIgnoreFilesByRoot(t),this.ignoreService.getRepoBlockExcludeGlobs(t)]),p=[...r,...h],{lines:f,didTimeout:m}=ga(e,{root:t,excludeGlobs:p,caseSensitive:!0,cursorIgnoreFiles:d,sandboxPolicy:n,source:"ls"});for await(const e of f){if(!e)continue;const r=(0,s.resolve)(t,e),n=await Cc(r);null===n||await this.ignoreService.isCursorIgnored(n)||await this.ignoreService.isRepoBlocked(n)||this.addPathToTree(r,a,l,u,o)}return this.sortTreeChildren(c),{tree:c,didTimeout:await m}}catch(e){i.error=e,i.hasError=!0}finally{wC(i)}}addPathToTree(e,t,r,n,o){const i=(0,s.basename)(e),a=(0,s.dirname)(e);this.ensureDirectoryPath(a,t,r,n.budgetExceeded);const c=r.get(a);if(!c)return;const l=i.length;if(!n.budgetExceeded&&n.charactersUsed+l<=o){const e=new mC.ur({name:i});c.childrenFiles.push(e),n.charactersUsed+=l}else{if(!n.budgetExceeded){n.budgetExceeded=!0;let e=a;for(;e.startsWith(t);){const t=r.get(e);t&&(t.childrenWereProcessed=!1);const n=(0,s.dirname)(e);if(n===e)break;e=n}}let o=n.overflowChain;if(n.overflowDir!==a||void 0===o){o=[];let e=a;for(;e.startsWith(t);){const t=r.get(e);t&&o.push(t);const n=(0,s.dirname)(e);if(n===e)break;e=n}n.overflowDir=a,n.overflowChain=o}const i=(0,s.extname)(e);for(const e of o)e.fullSubtreeExtensionCounts[i]??=0,e.fullSubtreeExtensionCounts[i]=Ay(e.fullSubtreeExtensionCounts[i]+1),e.numFiles??=0,e.numFiles=Ay(e.numFiles+1)}}ensureDirectoryPath(e,t,r,n){if(r.has(e)||e===t)return;const o=(0,s.dirname)(e);o!==e&&o.startsWith(t)&&this.ensureDirectoryPath(o,t,r,n);const i=new mC.vq({absPath:e,childrenDirs:[],childrenFiles:[],childrenWereProcessed:!n,fullSubtreeExtensionCounts:{}});r.set(e,i);const a=r.get(o);a&&a.childrenDirs.push(i)}sortTreeChildren(e){e.childrenDirs.sort(((e,t)=>(0,s.basename)(e.absPath).localeCompare((0,s.basename)(t.absPath)))),e.childrenFiles.sort(((e,t)=>e.name.localeCompare(t.name)));for(const t of e.childrenDirs)this.sortTreeChildren(t)}}class vC extends Error{constructor(e,t){super(`Tool ${e} not found, available tools: ${t.join(", ")}`),this.toolName=e,this.availableTools=t,this.name="McpToolNotFoundError"}}function bC(e){if(e instanceof vC)return!0;if(!(e instanceof Error)||"McpToolNotFoundError"!==e.name)return!1;const t=e;return"string"==typeof t.toolName&&Array.isArray(t.availableTools)}function SC(e){return!0===e.url?.startsWith("mcp-provider://")}function kC(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function _C(e){const t=e?.trim();return void 0===t||0===t.length?void 0:t}function CC(e,t){return(t??[]).some((t=>{const r=kC(t.command),n=_C(t.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==e.command&&(0,Ob.mD)(r,e.command),s=void 0===n||void 0!==e.url&&(0,Ob.eA)(n,e.url);return o&&s}))}function EC(e,t){if(SC(e))return!1;const r=t?.rules??[];if(0===r.length)return!1;if(CC(e,r))return!0;const n=function(e){return e.flatMap((e=>{if(void 0===e.serverUrl)return[];const t=function(e){if(e.includes("*"))return e;const t=e.search(/[?#]/);return-1===t?e:e.slice(0,t)}(e.serverUrl);return t===e.serverUrl?[]:[{...e,serverUrl:t}]}))}(r);return n.length>0&&CC(e,n)}function xC(e,t){const{command:r,url:n}=e;return void 0!==r&&t.commandPatterns.some((e=>(0,Ob.mD)(e.trim(),r)))||void 0!==n&&t.serverUrlPatterns.some((e=>(0,Ob.eA)(e.trim(),n)))}var PC=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class RC extends Error{constructor(e){super(`MCP server "${e}" is disabled`),this.name="McpServerDisabledError"}}class IC extends Error{constructor(e){super(`MCP server "${e}" has not been approved`),this.serverName=e,this.name="McpServerNotApprovedError"}}class TC extends Error{constructor(e,t){super(`MCP server "${e}" is overridden by ${t}`),this.serverName=e,this.overridingConfigPath=t,this.name="McpServerOverriddenError"}}class AC{constructor(e){this.disabledService=e}async load(e,t,r,n,o){if(await this.disabledService.isServerDisabled(t))throw new RC(t);return await o(e,r)}}class $C{constructor(e){this.approvalService=e}async load(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{if(function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(s,(0,$.VI)(e.withName("ServerApprovalMiddleware.load")),!1),!await this.approvalService.isServerApproved(t,r,n))throw new IC(t);return await o(e,r)}catch(e){s.error=e,s.hasError=!0}finally{PC(s)}}}class MC{constructor(e,t){this.approvalsPath=e,this.cwd=t,this.approvalsPromise=this.loadApprovals()}async isServerApproved(e,t,r){const n=function(e,t,r){const n={path:r,server:t};return`${e}-${(0,bo.createHash)("sha256").update(JSON.stringify(n)).digest("hex").substring(0,16)}`}(e,t,this.cwd);return(await this.getApprovals()).includes(n)}async loadApprovals(){try{const e=await(0,Co.readFile)(this.approvalsPath,"utf8"),t=JSON.parse(e);return Array.isArray(t)?t:(await this.saveApprovalsToFile([]),[])}catch(e){if(e instanceof Error&&e.message.includes("ENOENT"))return[];throw e}}async getApprovals(){return this.approvalsPromise}async addApproval(e){const t=await this.approvalsPromise;t.includes(e)||(t.push(e),await this.saveApprovals(t))}async addApprovals(e){const t=await this.approvalsPromise,r=e.filter((e=>!t.includes(e)));r.length>0&&(t.push(...r),await this.saveApprovals(t))}async removeApproval(e){const t=await this.approvalsPromise,r=t.filter((t=>t!==e));r.length!==t.length&&await this.saveApprovals(r)}async clearApprovals(e){const t=await this.approvalsPromise,r=e?t.filter((t=>!e(t))):[];r.length!==t.length&&await this.saveApprovals(r)}async saveApprovalsToFile(e){await(0,Co.mkdir)(s.default.dirname(this.approvalsPath),{recursive:!0}),await(0,Co.writeFile)(this.approvalsPath,JSON.stringify(e,null,2))}async saveApprovals(e){await this.saveApprovalsToFile(e),this.approvalsPromise=Promise.resolve(e)}}const DC=["https://api.cursor.com","https://api2.cursor.sh"],OC=["CURSOR_API_BASE_URL","CURSOR_BACKEND_URL"],FC=/^MCP server ".+" is blocked by \S/u;function NC(e){if(void 0!==e&&""!==e)try{return new URL(e).origin}catch{return}}function LC(e,t=process.env){if(void 0===e)return!1;let r;try{r=new URL(e)}catch{return!1}if("/v1/agent/mcp"!==r.pathname.replace(/\/+$/,"")&&!r.pathname.startsWith("/internal/agent-serve/agent-sdk-mcp-relay/"))return!1;const n=new Set(DC);for(const e of OC){const r=NC(t[e]);void 0!==r&&n.add(r)}return n.has(r.origin)}function jC(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function UC(e,t){if("string"!=typeof e)return;const r=e.trim();return""===r||r.length>t||/\p{Cc}/u.test(r)?void 0:r}function BC(e){if(!Array.isArray(e))return;const t=[];for(const r of e.slice(0,200)){const e=UC(r,200);void 0!==e&&t.push(e)}return t}function WC(e,t){const r=t.slice(0,20).join(", "),n=t.length-20;return n>0?` ${e}: ${r}, and ${n} more.`:` ${e}: ${r}.`}var HC=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},qC=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class zC{async load(e,t,r,n,o){const s=o(e,r);return new VC(e,t,s,r)}}function GC(e){let t;return e.then((e=>{t=e})).catch((()=>{})),t}class VC{constructor(e,t,r,n){this.serverName=t,this.clientPromise=r,this.config=n,this.clientPromiseTraceId=(0,$.fU)(e)?.spanContext()?.traceId,this.toolsPromise=this.clientPromise.then((async t=>null===t?[]:await t.getTools(e))),this.resourcesPromise=this.clientPromise.then((async t=>null===t?[]:(await t.listResources(e)).resources)),this.promptsPromise=this.clientPromise.then((async t=>null===t?[]:await t.listPrompts(e))),this.toolsPromise.catch((()=>{})),this.resourcesPromise.catch((()=>{})),this.promptsPromise.catch((()=>{}))}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=HC(t,(0,$.VI)(e.withName("CachedMcpClient.getTools")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=GC(this.toolsPromise);return void 0!==n?n:await this.toolsPromise}catch(e){t.error=e,t.hasError=!0}finally{qC(t)}}async callTool(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{const i=HC(s,(0,$.VI)(e.withName("CachedMcpClient.callTool")),!1),a=await this.getClient(i.ctx);if(null===a)throw new Error("Client is not ready");return a.callTool(i.ctx,t,r,n,o)}catch(e){s.error=e,s.hasError=!0}finally{qC(s)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=HC(t,(0,$.VI)(e.withName("CachedMcpClient.getInstructions")),!1),n=await this.getClient(r.ctx);if(null===n)return;return await n.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{qC(t)}}async getClient(e){const t={stack:[],error:void 0,hasError:!1};try{const r=HC(t,(0,$.VI)(e.withName("CachedMcpClient.getClient")),!1);return r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined"),await this.clientPromise}catch(e){t.error=e,t.hasError=!0}finally{qC(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{const r=HC(t,(0,$.VI)(e.withName("CachedMcpClient.listResources")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=GC(this.resourcesPromise);return void 0!==n?{resources:n}:{resources:await this.resourcesPromise}}catch(e){t.error=e,t.hasError=!0}finally{qC(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=HC(r,(0,$.VI)(e.withName("CachedMcpClient.readResource")),!1),o=await this.getClient(n.ctx);return null===o?{contents:[]}:o.readResource(n.ctx,t)}catch(e){r.error=e,r.hasError=!0}finally{qC(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{const r=HC(t,(0,$.VI)(e.withName("CachedMcpClient.listPrompts")),!1);r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("cacheTraceId",this.clientPromiseTraceId??"undefined");const n=GC(this.promptsPromise);return void 0!==n?n:await this.promptsPromise}catch(e){t.error=e,t.hasError=!0}finally{qC(t)}}async getPrompt(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=HC(n,(0,$.VI)(e.withName("CachedMcpClient.getPrompt")),!1),s=await this.getClient(o.ctx);return null===s?{messages:[]}:s.getPrompt(o.ctx,t,r)}catch(e){n.error=e,n.hasError=!0}finally{qC(n)}}async getState(e){const t={stack:[],error:void 0,hasError:!1};try{const r=HC(t,(0,$.VI)(e.withName("CachedMcpClient.getState")),!1);r.span.setAttribute("serverName",this.serverName);const n=await this.getClient(r.ctx);if(null===n)throw new Error("Client is not ready");return await n.getState(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{qC(t)}}async getAllowlistInUse(){try{await this.toolsPromise;const e=await this.clientPromise;return await(e?.getAllowlistInUse?.())}catch{return}}async getAllowlistRefusal(){if(void 0!==this.config&&"url"in this.config&&LC(this.config.url))try{return void await this.toolsPromise}catch(e){return function(e){const t=e instanceof Error?e.message:"string"==typeof e?e:void 0;if(void 0===t)return;const r=t.indexOf("{");if(-1===r)return;let n;try{n=JSON.parse(t.slice(r))}catch{return}if(!jC(n))return;const o=UC(n.error,700);return void 0!==o&&FC.test(o)?o:void 0}(e)}}async close(){try{const e=await this.clientPromise;await(e?.close?.())}catch{}}}function KC(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function JC(e,t){if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e||"bigint"==typeof e)return String(e);if(null==e)return t;try{const r=JSON.stringify(e);return"string"==typeof r?r:t}catch{return t}}function ZC(e){return e?` (${JC(e,"")})`:""}function XC(e){if(null===e||"string"==typeof e||"boolean"==typeof e)return e;if("number"==typeof e)return Number.isFinite(e)?e:void 0;if(Array.isArray(e)){const t=[];for(const r of e){if(void 0===r){t.push(null);continue}const e=XC(r);if(void 0===e)return;t.push(e)}return t}if("object"!=typeof e)return;const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&null!==t)return;const r={};for(const[t,n]of Object.entries(e)){if(void 0===n)continue;const e=XC(n);if(void 0===e)return;r[t]=e}return r}function QC(e){const t=XC(e);if(null!=t&&"object"==typeof t&&!Array.isArray(t))return t}const YC=new TextDecoder("utf-8",{fatal:!0});function eE(e){return"string"==typeof e?e.split(";")[0]?.trim().toLowerCase()??"":""}function tE(e,t){const r=Buffer.from(t,"base64"),n=function(e){try{const t=YC.decode(e);return t.includes("\0")?void 0:t}catch{return}}(r)??(function(e){const t=eE(e);return t.startsWith("text/")||"application/xml"===t||t.endsWith("+xml")}(e.mimeType)?r.toString("utf8").replace(/^\uFEFF/,""):void 0);if(void 0!==n)return{text:n,binary:!1};const o="string"==typeof e.mimeType&&e.mimeType.length>0?e.mimeType:"unknown type";return{text:`[Binary resource: ${JC(e.uri,"unknown")} (${o}, ${r.byteLength} bytes). The file is not text, so its contents are not included.]`,binary:!0}}const rE=new Set(["image/png","image/jpeg","image/jpg","image/gif","image/webp"]);function nE(e){return"string"==typeof e.text&&e.text.length>0?e.text:void 0}function oE(e){if(!KC(e))return;const t=e.resource;return KC(t)&&void 0===nE(t)&&"string"==typeof t.blob&&rE.has(eE(t.mimeType))?t.blob:void 0}function sE(e){const t=e,r=t.resource;if(KC(r)){const e=nE(r);return void 0!==e?e:"string"==typeof r.blob?tE(r,r.blob).text:`Resource: ${JC(r.uri,"unknown")}${ZC(r.name)}`}return t.uri?`Resource: ${JC(t.uri,"unknown")}${ZC(t.name)}`:`Unsupported content type "${e.type}": ${JSON.stringify(e)}`}function iE(e){const t=QC(e);if(void 0!==t&&0!==Object.keys(t).length)try{return Buffer.byteLength(JSON.stringify(t))<=262144?t:void 0}catch{return}}var aE=r("zod/v4-mini");const cE=aE.object({CLIENT_ID:aE.string(),CLIENT_SECRET:aE.optional(aE.string()),scopes:aE.optional(aE.array(aE.string()))}),lE=aE.strictObject({caBundle:aE.string().check(aE.trim(),aE.minLength(1),aE.maxLength(131072))}),uE=aE.object({type:aE.optional(aE.literal("stdio")),command:aE.string(),args:aE.optional(aE.array(aE.string())),env:aE.optional(aE.record(aE.string(),aE.string())),envFile:aE.optional(aE.string()),cwd:aE.optional(aE.string()),enabledTools:aE.optional(aE.array(aE.string())),startupTimeoutSec:aE.catch(aE.optional(aE.number().check(aE.positive())),void 0)}),dE=aE.object({type:aE.optional(aE.enum(["http","sse"])),url:aE.string(),headers:aE.optional(aE.record(aE.string(),aE.string())),auth:aE.optional(cE),tls:aE.optional(lE),placement:aE.optional(aE.enum(["server","client"])),enabledTools:aE.optional(aE.array(aE.string()))}),hE=aE.union([uE,dE]),pE=aE.object({mcpServers:aE.record(aE.string(),hE)});Error;const fE=/\$\{(?:env:([A-Za-z_][A-Za-z0-9_]*)|([^:}]+)(?::-([^}]*))?)\}/g;function mE(e,t){if("string"==typeof e)return function(e,t){return e.replace(fE,((e,r,n,o)=>{if(void 0!==r){const n=t(r);return void 0!==n?n:e}if(void 0===n)return e;const s=t(n);return void 0!==s?s:void 0!==o?o:e}))}(e,t);if(Array.isArray(e))return e.map((e=>mE(e,t)));if(null!==e&&"object"==typeof e){const r={};for(const[n,o]of Object.entries(e))r[n]=mE(o,t);return r}return e}r("../../node_modules/.pnpm/smol-toml@1.9.0/node_modules/smol-toml/dist/index.js");Symbol("invalid");function gE(e){const t=Object.entries(e);return{jsonKeyOf:new Map(t.map((([e,t])=>[t,e]))),tomlKeyOf:new Map(t)}}const wE=gE({CLIENT_ID:"client_id",CLIENT_SECRET:"client_secret",scopes:"scopes"}),yE=gE({caBundle:"ca_bundle"}),vE=gE({type:"type",command:"command",args:"args",env:"env",envFile:"env_file",cwd:"cwd",enabledTools:"enabled_tools",startupTimeoutSec:"startup_timeout_sec"}),bE=gE({type:"type",url:"url",headers:"http_headers",auth:"auth",tls:"tls",placement:"placement",enabledTools:"enabled_tools"}),SE=(new Map([["auth",{keys:wE,unknownKeyIsError:!1}],["tls",{keys:yE,unknownKeyIsError:!0}]]),"enabled");new Set([...vE.jsonKeyOf.keys(),...bE.jsonKeyOf.keys(),SE]);Symbol("disabled");const kE=(0,l.h)("McpConfig");async function _E(e,t=e=>process.env[e]){try{const r=await(0,Co.readFile)(e,"utf8"),n=mE((0,Cp.qg)(r),t);return pE.parse(n)}catch{return{mcpServers:{}}}}async function CE(e,t=e=>process.env[e]){const r={config:{mcpServers:{}},diagnostics:[]};return r}async function EE(e,t=e=>process.env[e]){const{config:r,diagnostics:n}=await CE(0,t);return n.length>0&&kE.warn((0,y.q6)(),"[mcp config] problems in MCP config; `agent mcp list` shows them",{errorCount:n.filter((e=>"error"===e.severity)).length,warningCount:n.filter((e=>"warning"===e.severity)).length,fileNames:[...new Set(n.map((e=>s.default.basename(e.file))))]}),r}const xE=["enterprise","project","user","env"];function PE(e){return"project"===e||"env"===e}const RE=["0.0.0.0/0","::/0"];function IE(e){const t=(e??[]).filter((e=>e.trim().length>0)),r=t.flatMap((e=>{const t=(0,Ob.bi)(e);return void 0===t?[]:[t]}));return{hasInvalidEntries:r.length!==t.length,entries:r}}function TE(e){const t=!0===e.enabled,r=IE(e.mcpNetworkDenylist),n="deny_all"===e.mcpNetworkMode||r.entries.includes("*")||r.hasInvalidEntries,o=t?function(e){if("allow_all"===e.mcpNetworkMode)return[...RE];const t=IE(e.mcpNetworkAllowlist);if("allowlist"===e.mcpNetworkMode)return t.entries.includes("*")?[...RE]:t.entries;if(!function(e){return(e.mcpNetworkAllowlist??[]).some((e=>e.trim().length>0))}(e))return[...RE];const r=(0,Ob.b6)(e);return r.includes("*")?[...RE]:r}(e):[],s=t?n?["*"]:r.entries:[];return JSON.stringify({enabled:t,mode:e.mcpNetworkMode,allow:n?[]:o,deny:s})}class AE extends Error{constructor(e,t){super(`MCP server "${e}" wasn't started: your team's MCP settings require it to run in a sandbox, and the sandbox isn't supported on this machine. Ask a team admin to review the team's MCP settings for this server.`),this.serverName=e,this.name="McpSandboxUnavailableError",void 0!==t&&(this.cause=t)}}const $E=new Set(["invalid_auth","not_authed","account_inactive","token_revoked","token_expired"]);class ME extends Error{constructor(){super("Your organization admin only allows Slack workspaces your company manages. Connect your company Slack workspace instead."),this.name="SlackWorkspaceNotManagedError"}}class DE extends Error{constructor(){super("Slack couldn't confirm which workspace this connection is for, and your organization admin only allows the Slack workspaces your company manages. Try again in a moment."),this.name="SlackWorkspaceUnconfirmedError"}}function OE(e){return URL.canParse(e)&&"mcp.slack.com"===new URL(e).hostname.toLowerCase()}function FE(e,t){const r=new Map,n=t.lookUpWorkspace??(t=>async function(e,t){let r;try{const n=await e("https://slack.com/api/auth.test",{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/x-www-form-urlencoded"},signal:AbortSignal.timeout(5e3)});r=await n.json()}catch{return{kind:"unavailable"}}if("object"!=typeof r||null===r)return{kind:"unavailable"};if("object"!=typeof(n=r)||null===n||Array.isArray(n))return{kind:"unavailable"};var n;const o=r;return!0!==o.ok?"string"==typeof o.error&&$E.has(o.error)?{kind:"dead"}:{kind:"unavailable"}:"string"!=typeof o.team_id||0===o.team_id.length?{kind:"unavailable"}:"string"==typeof o.enterprise_id&&o.enterprise_id.length>0?{kind:"found",slackTeamId:o.team_id,slackEnterpriseId:o.enterprise_id}:{kind:"found",slackTeamId:o.team_id}}(e,t));let o,s=[];return async(i,a)=>{if(!OE(function(e){return"string"==typeof e?e:e instanceof URL?e.href:e.url}(i)))return e(i,a);const c=function(e,t){const r=new Headers(t?.headers??(e instanceof Request?e.headers:void 0)),n=/^Bearer\s+(.+)$/i.exec(r.get("authorization")??"");return n?.[1]?.trim()||void 0}(i,a);if(void 0===c)return e(i,a);const l=await((void 0===o||Date.now()-o.atMs>=3e4)&&(o={atMs:Date.now(),lists:t.managedSlackWorkspaceLists().then((e=>"unconfirmed"===e?e:(s=e.filter((e=>e.length>0)).map((e=>e.map((e=>e.toUpperCase())))),s)),(()=>s))}),o.lists);if("unconfirmed"===l)throw new DE;if(0===l.length)return e(i,a);let u=r.get(c);if(void 0===u){const t=await n(c);if("dead"===t.kind)return e(i,a);if("unavailable"===t.kind)throw new DE;r.size>=64&&r.clear(),r.set(c,t),u=t}const d=[u.slackTeamId,u.slackEnterpriseId].flatMap((e=>void 0===e?[]:[e.toUpperCase()]));if(!l.every((e=>d.some((t=>e.includes(t))))))throw new ME;return e(i,a)}}function NE(e,t,r){if("string"==typeof e)return t(e);if(!(e instanceof Error))return e;if(r.results.has(e))return r.results.get(e)===e&&r.cycled.add(e),r.results.get(e);r.results.set(e,e);const n=Object.isFrozen(e)&&GE(e,t)?new Error:void 0;void 0!==n&&r.results.set(e,n);const o=t(e.message),s="string"==typeof e.stack?t(e.stack):void 0,i=Object.keys(e).flatMap((n=>{if("cause"===n)return[];const o=UE(e,n),s=qE(o,t,r);return Object.is(s,o)?[]:[[n,s]]})),a=Object.getOwnPropertyDescriptor(e,"cause"),c=void 0===a?void 0:UE(e,"cause"),l=qE(c,t,r),u=e instanceof AggregateError?UE(e,"errors"):void 0,d=function(e,t,r){if(!Array.isArray(e))return e;const n=e.map((e=>qE(e,t,r)));if(n.every(((t,r)=>Object.is(t,e[r]))))return e;try{return n.forEach(((t,r)=>{e[r]=t})),e}catch{return n}}(u,t,r),h=[...i,...Object.is(l,c)?[]:[["cause",l]],...Object.is(d,u)?[]:[["errors",d]]];let p=!1;if(void 0===n)try{o!==e.message&&(e.message=o),void 0!==s&&s!==e.stack&&(e.stack=s),p=e.message===o&&(void 0===s||e.stack===s)&&h.every((([t,r])=>jE(e,t,r)))}catch{}if(p)return e;const f=Object.defineProperties(n??new Error,{message:{value:o,writable:!0,enumerable:!1,configurable:!0},...Object.getOwnPropertyDescriptors(WE(e,new Map(i)))});Array.isArray(d)&&Object.defineProperty(f,"errors",{value:d,writable:!0,enumerable:!1,configurable:!0}),void 0!==a&&Object.defineProperty(f,"cause",{value:l,writable:!0,enumerable:!0===a.enumerable,configurable:!0});const m=Object.getPrototypeOf(e);null!==m&&"object"==typeof m&&m!==Error.prototype&&(Object.setPrototypeOf(f,m),function(e){try{let t=Object.getPrototypeOf(e);for(let r=0;r<8&&null!==t&&"object"==typeof t&&t!==Error.prototype&&t!==Object.prototype;r++){for(const r of Reflect.ownKeys(t)){const n=Object.getOwnPropertyDescriptor(t,r)?.get;void 0!==n&&Reflect.apply(n,e,[])}t=Object.getPrototypeOf(t)}String(e);const r=e;"function"==typeof r.toJSON&&Reflect.apply(r.toJSON,e,[""]);const n=r[BE];return"function"==typeof n&&Reflect.apply(n,e,[0,{depth:0,stylize:String},String]),!0}catch{return!1}}(f)||Object.setPrototypeOf(f,Error.prototype));const g=JE(e);return void 0!==g&&JE(f)!==g&&Object.defineProperty(f,"name",{value:g,writable:!0,configurable:!0,enumerable:!1}),void 0!==s&&(f.stack=s),r.results.set(e,f),f}function LE(e,t){if(e instanceof Error)return t.get(e)??e;if(!Array.isArray(e)||!Object.isFrozen(e))return e;const r=e.map((e=>e instanceof Error?t.get(e)??e:e));return r.every(((t,r)=>Object.is(t,e[r])))?e:r}function jE(e,t,r){const n=Object.getOwnPropertyDescriptor(e,t);return!0===n?.writable&&Reflect.defineProperty(e,t,{...n,value:r})}function UE(e,t){try{const r=Object.getOwnPropertyDescriptor(e,t);return void 0===r?.get?r?.value:r.get.call(e)}catch{return}}const BE=Symbol.for("nodejs.util.inspect.custom");function WE(e,t){const r={};for(const n of Object.keys(e))try{const o=Object.getOwnPropertyDescriptor(e,n),s=void 0===o?.get?o?.value:o.get.call(e);Object.defineProperty(r,n,{value:t.has(n)?t.get(n):s,writable:!0,enumerable:!0,configurable:!0})}catch{}return r}function HE(e,t,r,n){if("string"==typeof e)return t(e);if("object"!=typeof e||null===e)return e;if(e instanceof Error)return NE(e,t,n);if(Array.isArray(e)){if(r>=4)return;return e.slice(0,64).map((e=>HE(e,t,r+1,n)))}const o=Object.getPrototypeOf(e);return o!==Object.prototype&&null!==o?e:r>=4?void 0:function(e,t,r,n){const o={};for(const s of Object.keys(e).slice(0,64))try{const i=Object.getOwnPropertyDescriptor(e,s),a=void 0===i?.get?i?.value:i.get.call(e);Object.defineProperty(o,s,{value:HE(a,t,r,n),writable:!0,enumerable:!0,configurable:!0})}catch{}return o}(e,t,r+1,n)}function qE(e,t,r){if(e instanceof Error)return NE(e,t,r);try{return GE(e,t)?HE(e,t,1,r):e}catch{return}}const zE=4096;function GE(e,t){const r=new Set,n=[e];for(let o=0;n.length>0;o++){if(o>=zE||n.length>zE)return VE(e,t);const s=n.pop();if("string"==typeof s){if(t(s)!==s)return!0}else if((KE(s)||s instanceof Error)&&!r.has(s)){r.add(s),s instanceof Error&&(n.push(UE(s,"message"),UE(s,"stack"),UE(s,"cause")),s instanceof AggregateError&&n.push(UE(s,"errors")));for(const e of Object.keys(s))n.push(UE(s,e))}}return!1}function VE(e,t){const r=new Set;let n;try{n=JSON.stringify(e,((e,t)=>{return"bigint"==typeof t?t.toString():"object"!=typeof t||null===t?t:r.has(t)?void 0:(r.add(t),t instanceof Error?(n=t,{...Object.fromEntries(Object.keys(n).map((e=>[e,UE(n,e)]))),message:UE(n,"message"),stack:UE(n,"stack"),cause:UE(n,"cause"),...n instanceof AggregateError?{errors:UE(n,"errors")}:{}}):t);var n}))}catch{return!0}return void 0!==n&&t(n)!==n}function KE(e){if(Array.isArray(e))return!0;if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function JE(e){try{return"string"==typeof e.name?e.name:void 0}catch{return}}const ZE=/spt_[A-Za-z0-9_]{6,}/g,XE=/[A-Z0-9]/;function QE(e){return function(e){return e.replace(ZE,(e=>function(e){return e.slice(4).split("_").some((e=>e.length>=8&&XE.test(e)))}(e)?"[redacted Link shared payment token]":e))}(e)}var YE=r("../../node_modules/.pnpm/string-argv@0.3.2/node_modules/string-argv/index.js");new Set(["EAI_AGAIN","ECONNABORTED","ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ENOTFOUND","EPIPE","ETIMEDOUT","EADDRNOTAVAIL","UND_ERR_CONNECT_TIMEOUT"]),new Set(["ECONNRESET","EPIPE"]);const ex=new Set([429,502,503,504]);function tx(e){return"object"==typeof e&&null!==e}function rx(e){const t=tx(e)?e.code:void 0,r=(e instanceof Error||tx(e)&&"string"==typeof e.message?e.message:"").match(/\(HTTP (\d+)\)|Non-200 status code \((\d+)\)|\bHTTP\s+(\d{3})\b/i),n=r?.[1]??r?.[2]??r?.[3],o=void 0!==n?parseInt(n,10):void 0;if("number"==typeof t&&t>=100)return void 0!==o&&ex.has(o)&&!ex.has(t)?o:t;if("string"==typeof t&&/^\d{3}$/.test(t)){const e=Number.parseInt(t,10);return e>=100&&e<=599?e:o}return o}new Set(["UND_ERR_SOCKET","UND_ERR_CLOSED","ECONNRESET"]);const nx=8192;function ox(e){return void 0===e?"unknown":"url"in e&&e.url.length>0?void 0!==ib(e.url)?"rest_mcp":"streamable_http":"command"in e?"stdio":"unknown"}new Set(["ENOENT","EACCES","ENOTDIR","EPERM"]);const sx=/\$\{[^}]*\}/;function ix(e){if(void 0!==function(e){if(void 0===e)return;const t=e.trim();return 0!==t.length&&sx.test(t)?t:void 0}(e))return;const t=e?.trim();return t&&t.length>0?t:void 0}const ax=new Map;async function cx(e,t=fetch){if(void 0===ib(e))return;const r=new URL(e),n=`${r.origin}/.well-known/oauth-protected-resource${r.pathname.replace(/\/+$/,"")}`,o=ax.get(n);if(void 0!==o&&o.expiresAtMs>Date.now())return o.metadata;let s;try{const e=await t(n);if(!e.ok)return;s=function(e){if("object"!=typeof(t=e)||null===t)return{};var t;const r=e,n="string"==typeof r.cursor_client_id&&r.cursor_client_id.length>0?r.cursor_client_id:void 0;let o;if("object"==typeof r.cursor_authorization_params&&null!==r.cursor_authorization_params){const e=Object.entries(r.cursor_authorization_params).filter((e=>"string"==typeof e[1]));e.length>0&&(o=Object.fromEntries(e))}return{...void 0!==n?{clientId:n}:{},...!0===r.cursor_omit_resource_indicator?{omitResourceIndicator:!0}:{},...!0===r.cursor_omit_consent_prompt?{omitConsentPrompt:!0}:{},...void 0!==o?{authorizationParams:o}:{},...!0===r.cursor_rejects_custom_scheme_redirects?{rejectsCustomSchemeRedirects:!0}:{},...!0===r.cursor_unauthenticated_connect?{unauthenticatedConnect:!0}:{},...!0===r.cursor_loopback_ipv4?{loopbackIpv4:!0}:{},...!0===r.cursor_backend_only_token_exchange?{backendOnlyTokenExchange:!0}:{}}}(await e.json())}catch{return}return ax.set(n,{metadata:s,expiresAtMs:Date.now()+3e5}),s}(0,_s.J)((function(){ax.clear()}));const lx={info:()=>{},warn:()=>{},error:()=>{},debug:()=>{}};function ux(e){return lx}const dx=/^[\x21\x23-\x5B\x5D-\x7E]+$/,hx=["invalid_request","invalid_token","insufficient_scope"];function px(e){return hx.some((t=>t===e))}function fx(e){const t=new Set;for(const r of e)r.length<=200&&dx.test(r)&&t.add(r);return[...t]}const mx=/[!#$%&'*+.^_`|~0-9A-Za-z-]+/y,gx=/"((?:[^"\\]|\\.)*)"?/y,wx=/[^\s,]*/y;function yx(e,t){let r,n=0;const o=t=>{t.lastIndex=n;const r=t.exec(e);return null!==r&&(n=t.lastIndex),r};for(;n"string"==typeof e&&e.length>0)):void 0}function Sx(e){if("object"!=typeof e||null===e||Array.isArray(e))return vx;const t=bx("grantedScopes"in e?e.grantedScopes:void 0),r=bx("requestedScopes"in e?e.requestedScopes:void 0);return{...void 0!==t?{grantedScopes:t}:{},stepUpScopes:bx("stepUpScopes"in e?e.stepUpScopes:void 0)??[],signInMissing:bx("signInMissing"in e?e.signInMissing:void 0)??[],...void 0!==r?{requestedScopes:r}:{}}}function kx(e){return(e??"").split(/\s+/).filter((e=>e.length>0))}function _x(e,t){return e.filter((e=>!t.has(e)))}function Cx(e){const t=Sb(e.serverUrl),r=e.connectorName??t?.displayName??e.accountKey,n=ux(e.accountKey);let o;const s=async()=>Sx(await e.readRecord()),i=async t=>{if(void 0!==t.grantedScopes)return t.grantedScopes;const r=kx(await e.readTokenScope());return r.length>0?r:void 0},a=(e,t)=>{n.info(`MCP OAuth scope step-up: ${e}`,{event:`mcp_oauth_scope_step_up_${e}`,...t})};return{accountKey:e.accountKey,connectorName:r,async decide(r){if(401!==r.status&&403!==r.status)return;const n=function(e){const t=e??"",r=yx(t,"error")?.toLowerCase(),n=yx(t,"resource_metadata");return{error:void 0===r||""===r?"none":px(r)?r:"other",scopes:fx((yx(t,"scope")??"").split(/\s+/)),resourceMetadata:void 0===n||""===n?void 0:n}}(r.wwwAuthenticate);if("insufficient_scope"!==n.error||0===n.scopes.length)return;if(function(e){try{return kb.has(new URL(e).hostname.toLowerCase())}catch{return!1}}(e.serverUrl))return;const o=function(e,t){if(void 0!==t)try{return new URL(t).origin===new URL(e).origin?t:void 0}catch{return}}(e.serverUrl,n.resourceMetadata),c=void 0===t?await e.readScopesSupported(o).catch((()=>{})):void 0,l=await s(),u=await i(l),{accepted:d,dropped:h}=function(e){const t=new Set(e.granted??[]),r=[],n=[];for(const o of fx(e.named))e.allowlist.has(o)?t.has(o)||r.push(o):n.push(o);return{accepted:r,dropped:n}}({named:n.scopes,allowlist:(p={policy:t,scopesSupported:c,configuredScopes:e.configuredScopes},void 0!==p.policy?new Set([...p.policy.baseScopes,...Object.keys(p.policy.stepUpScopes)]):new Set([...p.scopesSupported??[],...p.configuredScopes??[]])),granted:u});var p;if(0===d.length)return void a("none_accepted",{status:r.status,namedCount:n.scopes.length,droppedCount:h.length});const f=new Set(l.signInMissing),m=d.every((e=>f.has(e)))?"blocked":"offer";return"offer"===m&&await e.writeRecord({...l,...void 0!==u?{grantedScopes:u}:{},stepUpScopes:[...new Set([...l.stepUpScopes,...d])]}),a(m,{status:r.status,acceptedCount:d.length,droppedCount:h.length}),{kind:m,status:r.status,scopes:d,dropped:h,toolName:r.toolName,resourceMetadataUrl:o}},signIn:async e=>(void 0===o&&(o=Promise.resolve().then(e).finally((()=>{o=void 0}))),o),get isSigningIn(){return void 0!==o},tokensForSdk(e){if(void 0===o||void 0===e?.refresh_token)return e;const{refresh_token:t,...r}=e;return r},async prepareAuthorization(){const t=await s();return{stepUpScopes:t.stepUpScopes.length>0?[...new Set([...await i(t)??[],...t.stepUpScopes])]:[],recordRequestedScopes:async t=>{await e.writeRecord({...await s(),requestedScopes:kx(t.searchParams.get("scope"))})}}},async recordTokens(t,{isRefresh:r}){const n=await e.readRecord();if(void 0===n)return;const o=Sx(n),s=kx(t.scope);if(r)return void(s.length>0&&await e.writeRecord({...o,grantedScopes:s}));if(void 0===o.requestedScopes)return;const i=s.length>0?s:o.requestedScopes,c=new Set(i),l=_x(o.requestedScopes,c);await e.writeRecord({grantedScopes:i,stepUpScopes:_x(o.stepUpScopes,c),signInMissing:l}),a("sign_in_recorded",{grantedCount:i.length,signInMissingCount:l.length,scopeReported:s.length>0})},async clear(t){await e.writeRecord(!0===t?.keepPendingScopes?function(e){const{stepUpScopes:t}=Sx(e);return t.length>0?{stepUpScopes:t,signInMissing:[]}:void 0}(await e.readRecord()):void 0)}}}function Ex(e){const t=Sb(e.serverUrl);for(const r of e.scopes){const e=t?.stepUpScopes[r]?.action;if(void 0!==e)return e}return e.toolTitle}function xx(e){const t=function(e){return void 0===e.action?`${e.connectorName} needs a permission its sign-in did not grant.`:`${e.connectorName} needs one more permission to ${e.action}.`}({connectorName:e.connectorName,action:Ex(e)}),r="offer"===e.kind?`Authorize ${e.connectorName} again to approve it; the turn can continue once it's granted.`:`Its last sign-in did not grant ${1===e.scopes.length?"it":"them"}, so an admin or your consent is blocking this. Reconnect ${e.connectorName} from its MCP settings to ask again.`,n=function(e){if(0===e.length)return;const t=e.slice(0,3).join(", "),r=e.length-3;return`${1===e.length?"Permission":"Permissions"}: ${t}${r>0?` and ${r} more`:""}`}(e.scopes);return void 0===n?`${t} ${r}`:`${t} ${r}\n${n}`}class Px extends Error{constructor(e,t,r){super(xx({kind:e.kind,serverUrl:t,connectorName:r,scopes:e.scopes,toolTitle:e.toolName})),this.decision=e,this.serverUrl=t,this.connectorName=r,this.name="McpOAuthScopeStepUpError"}answerWithToolTitle(e){return xx({kind:this.decision.kind,serverUrl:this.serverUrl,connectorName:this.connectorName,scopes:this.decision.scopes,toolTitle:e??this.decision.toolName})}}function Rx(e){if("string"!=typeof e)return;let t;try{t=JSON.parse(e)}catch{return}const r=Array.isArray(t)?t:[t];for(const e of r){if("object"!=typeof e||null===e||!("method"in e)||"tools/call"!==e.method)continue;const t="params"in e?e.params:void 0,r="object"==typeof t&&null!==t&&"name"in t?t.name:void 0;return"string"==typeof r?r:void 0}}function Ix(e){return e instanceof Error&&/does not support dynamic client registration/i.test(e.message)}Error,Error;const Tx=new Set(["UnauthorizedError","InvalidGrantError","InvalidTokenError","InvalidClientError","UnauthorizedClientError"]),Ax=new Set(["invalid_grant","invalid_token","invalid_client","unauthorized_client"]),$x=[/\btoken (?:has |is )?expired\b/i,/\btoken (?:was|is) invalid\b/i,/\binvalid (?:refresh[ _]?)?token\b/i,/\btoken (?:has been |was )?revoked\b/i];var Mx=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js");const Dx="2026-07-28",Ox=-32022,Fx="io.modelcontextprotocol/protocolVersion",Nx="io.modelcontextprotocol/clientCapabilities",Lx="io.modelcontextprotocol/clientInfo",jx="io.modelcontextprotocol/serverInfo",Ux={name:"cursor",version:"1.0.0"},Bx=new Map;function Wx(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Hx(e){const t=new URL(String(e));return t.hash="",t.href}function qx(e,t){const r=Bx.get(e);return!(void 0===r||r<=t()&&(Bx.delete(e),1))}function zx(e,t){try{return Hx(e)===t}catch{return!1}}function Gx(e){return(e.headers.get("content-type")??"").toLowerCase().includes("application/json")}const Vx=new Set(["events/subscribe","events/unsubscribe","events/poll","events/stream"]);function Kx(e,t,r,n,o=t.message){const s=new Headers(e?.headers);if(s.set("mcp-protocol-version",Dx),s.set("mcp-method",r),s.delete("mcp-session-id"),!t.isRequest&&o===t.message)return{...e,headers:s};const i=Wx(o.params)?o.params:{},a=Wx(i._meta)?i._meta:{},c=function(e,t){const r="tools/call"===e||"prompts/get"===e||Vx.has(e)?"name":"resources/read"===e?"uri":void 0,n=void 0===r?void 0:t[r];return"string"==typeof n?n:void 0}(r,i);void 0!==c&&s.set("mcp-name",c);const l=JSON.stringify({...o,params:{...i,_meta:{...a,[Fx]:Dx,[Nx]:n.capabilities,[Lx]:n.clientInfo}}});return{...e,headers:s,body:l}}function Jx(e){return new Response(JSON.stringify({jsonrpc:"2.0",...e}),{status:200,headers:{"content-type":"application/json"}})}function Zx(e,t){const r=Hx(t.serverUrl),n=t.now??Date.now;let o={capabilities:{},clientInfo:{...Ux}},s=!1;const i=()=>s||qx(r,n),a=async(t,i,a)=>{const{method:c,message:l}=t;if(void 0===c)return e(i,a);if("notifications/initialized"===c)return new Response(null,{status:202});if(t.isRequest&&"initialize"===c){const c={jsonrpc:"2.0",id:l.id,method:"server/discover",params:{}},u=await e(i,Kx(a,t,"server/discover",o,c)),d=await async function(e,t,r){if(!e.ok||!Gx(e))return e;let n;try{n=await e.clone().json()}catch{return e}if(!Wx(n)||!Wx(n.result))return e;const o=n.result,s=o.supportedVersions;if(!Array.isArray(s)||!s.includes(Dx))return Jx({id:t,error:{code:Ox,message:"Unsupported protocol version",data:{requested:Dx,supported:s??[]}}});const i=Wx(o._meta)?o._meta:{},a=Wx(i[jx])?i[jx]:{name:new URL(r).hostname,version:"unknown"};return Jx({id:t,result:{protocolVersion:Mx.aE,capabilities:Wx(o.capabilities)?o.capabilities:{},serverInfo:a,..."string"==typeof o.instructions?{instructions:o.instructions}:{}}})}(u,l.id,r);return d!==u&&(s=!0,function(e,t){Bx.set(e,t()+6e5)}(r,n)),d}return e(i,Kx(a,t,c,o))};return async(t,c)=>{const l=function(e,t,r){if("POST"!==(t?.method??"GET").toUpperCase()||"string"!=typeof t?.body||!zx(e,r))return;let n;try{n=JSON.parse(t.body)}catch{return}if(!Wx(n)||"2.0"!==n.jsonrpc)return;const o="string"==typeof n.method?n.method:void 0;return{message:n,method:o,isRequest:void 0!==o&&"id"in n}}(t,c,r);if(void 0===l)return function(e,t,r){return"GET"===(t?.method??"GET").toUpperCase()&&zx(e,r)}(t,c,r)&&i()?new Response(null,{status:405}):e(t,c);if(l.isRequest&&"initialize"===l.method){const e=Wx(l.message.params)?l.message.params:{};o={capabilities:Wx(e.capabilities)?e.capabilities:{},clientInfo:Wx(e.clientInfo)?e.clientInfo:o.clientInfo}}const u=l.isRequest&&"initialize"===l.method;if(u?qx(r,n):i())return a(l,t,c);if(u&&(s=!1),!l.isRequest)return e(t,c);const d=await e(t,c);if(u&&await async function(e){if(e.status>=500||!Gx(e))return!1;const t=Number(e.headers.get("content-length"));if(Number.isFinite(t)&&t>4096)return!1;let r;try{r=await e.clone().json()}catch{return!1}if(!Wx(r)||!Wx(r.error))return!1;const n=r.error;if(n.code!==Ox||!Wx(n.data))return!1;const o=n.data.supported;return Array.isArray(o)&&o.includes(Dx)}(d)){const e=await a(l,t,c);return s?e:d}return d}}function Xx(e,t){if(void 0===t)return{headers:t,cursorAuthHeaderValue:void 0,cursorAuthOrigin:void 0};const r=Object.entries(t),n=r.find((([e])=>e.toLowerCase()===ob));if(void 0===n)return{headers:t,cursorAuthHeaderValue:void 0,cursorAuthOrigin:void 0};let o;try{o=new URL(e).origin}catch{o=void 0}return{headers:Object.fromEntries(r.filter((([e])=>e.toLowerCase()!==ob))),cursorAuthHeaderValue:n[1],cursorAuthOrigin:o}}function Qx(e,t,r){return async(n,o)=>{let s;try{s=new URL("string"==typeof n?n:n.toString()).origin}catch{return r(n,o)}if(s!==t)return r(n,o);const i=await e();if(void 0===i||0===i.length)return r(n,o);const a=new Headers(o?.headers);return a.set(ob,i),r(n,{...o,headers:a,redirect:"manual"})}}class Yx{constructor(e=864e5){this.ttl=e,this.staleDirty=!1,this.refreshGeneration=0}async get(e){const t=performance.now();if(this.state&&this.state.expiresAt>t&&!this.staleDirty)return this.state.value;if(this.staleDirty&&this.state){const t=this.state.value;if(!this.refreshInFlight){const t=this.refreshGeneration;let r;r=(async()=>{try{const r=await e();if(t!==this.refreshGeneration)return;this.state={expiresAt:performance.now()+this.ttl,value:r},this.staleDirty=!1}catch{}finally{r&&this.refreshInFlight===r&&(this.refreshInFlight=void 0)}})(),this.refreshInFlight=r}return t}const r=this.refreshGeneration,n=await e();return r!==this.refreshGeneration||(this.state={expiresAt:performance.now()+this.ttl,value:n},this.staleDirty=!1),n}invalidate(){this.refreshGeneration++,this.state=void 0,this.staleDirty=!1,this.refreshInFlight=void 0}invalidateKeepingStale(){this.state&&(this.staleDirty=!0)}}var eP=r("crypto");function tP(e){const t={};for(const[r,n]of Object.entries(e))void 0!==n&&(t[r]=n);return t}function rP(e,t){const r=function(e){try{const t=new URL(e);return{host:t.host,origin:t.origin,pathname:t.pathname}}catch{return{host:null,origin:null,pathname:null}}}(e),n=!1!==t?.includePath;return{host:r.host,origin:r.origin,path:n?r.pathname:null}}function nP(e,t){return rP(e,t)}function oP(e){if(e)return(0,eP.createHash)("sha256").update(e).digest("hex").slice(0,12)}function sP(e){if(e&&0!==e.length)return oP(JSON.stringify([...e].sort()))}function iP(e){return{clientIdHash:oP(e?.client_id),hasClientSecret:(e?.client_secret??"").length>0,redirectUrisHash:sP(e?.redirect_uris),redirectUriCount:e?.redirect_uris?.length??0}}function aP(e){return"object"==typeof e&&null!==e}function cP(e,t){let r=e;for(const e of t){if(!aP(r)||!(e in r))return;r=r[e]}return r}function lP(e,t){for(const r of t){const t=cP(e,r.split("."));if("string"==typeof t)return t}}function uP(e){if(!e||"object"!=typeof e)return;const t=e.errorCode;return"string"==typeof t?t:void 0}function dP(e){if(!e)return;const t=e.match(/\(HTTP (\d+)\)|Non-200 status code \((\d+)\)|\bHTTP\s+(\d{3})\b/i),r=t?.[1]??t?.[2]??t?.[3];if(!r)return;const n=Number.parseInt(r,10);return Number.isNaN(n)?void 0:n}const hP=e=>e;function pP(e,t){if(e instanceof Error){const r=e.message;return r&&r!==e.name?bP(t(r)):void 0}if("string"==typeof e||"number"==typeof e||"boolean"==typeof e){const r=String(e);return r?bP(t(r)):void 0}}function fP(e){if(e&&"object"==typeof e)return aP(e)?e.cause:void 0}function mP(e,t,r=4){const n=[];let o=e;for(let e=0;e1?n.join(" > "):void 0}const gP="[REDACTED]",wP=/(^|_|-)(token|secret|password|assertion|authorization|verifier|challenge|code)(_|-|$)/i;function yP(e){return e.replace(/(authorization[^:=\r\n]{0,32}[:=]\s*["']?)(?:[A-Za-z][\w.~+/-]*[ \t]+)?[^"',\s&}]+/gi,`$1${gP}`).replace(/((?:access_token|refresh_token|id_token|client_secret|code|password|assertion|token|secret)[^:=\r\n]{0,32}[:=]\s*["']?)([^"',\s&}]+)/gi,`$1${gP}`).replace(/(\bBearer\s+)([A-Za-z0-9\-._~+/]+=*)/gi,`$1${gP}`)}function vP(e,t=256){return e.length>t?`${e.slice(0,Math.max(0,t-3))}...`:e}function bP(e,t){return vP(yP(e),t?.maxLength)}function SP(e,t=hP){if("string"==typeof e)return vP(yP(t(e)));if(void 0!==e)try{const r=JSON.stringify(e,((e,r)=>e&&function(e){const t=e.toLowerCase();return"code"===t||"authorization"===t||t.includes("token")||t.includes("secret")||t.includes("password")||t.includes("assertion")||t.includes("verifier")||t.includes("challenge")||wP.test(t)}(e)?gP:"string"==typeof r?yP(t(r)):r));if(!r)return;return vP(r)}catch{return}}function kP(e,t=hP){const r=fP(e),n=e instanceof Error?e.name:null!=e?typeof e:void 0,o=r instanceof Error?r.name:void 0,s=pP(r,t),i=pP(e,t)??s,a=lP(e,["code","cause.code"]),c=uP(e)??uP(r)??lP(e,["errorCode","error","cause.errorCode","cause.error","body.error","response.body.error"]),l=void 0===c?void 0:bP(t(c)),u=function(e){for(const t of["status","statusCode","response.status","response.statusCode","cause.status","cause.statusCode","cause.response.status","cause.response.statusCode"]){const r=cP(e,t.split("."));if("number"==typeof r&&Number.isFinite(r))return r}}(e)??dP(i)??dP(s),d=SP(cP(e,["response","body"])??cP(e,["body"])??cP(e,["data"])??cP(e,["cause","body"])??cP(e,["cause","response","body"]),t),h=function(e){const t=e.message?.toLowerCase(),r=e.code?.toLowerCase();return t?.includes("timed out")||t?.includes("timeout")||t?.includes("etimedout")||"etimedout"===r?"timeout":t?.includes("enotfound")||t?.includes("eai_again")||t?.includes("dns")||"enotfound"===r||"eai_again"===r?"dns":t?.includes("certificate")||t?.includes("tls")||t?.includes("ssl")?"tls":t?.includes("econnreset")||t?.includes("connection reset")||"econnreset"===r?"connection_reset":t?.includes("econnrefused")||t?.includes("connection refused")||"econnrefused"===r?"connection_refused":void 0}({message:i,code:a}),p=l?"oauth_error":h?"auth_transport_error":i?"generic_error":void 0;return tP({errorName:n,errorMessage:i,errorType:null!=e?typeof e:void 0,httpStatus:u,oauthErrorCode:l,errorResponseSummary:d,networkClassification:h,causeName:o,causeMessage:s,causeChain:mP(e,t),sdkErrorKind:p})}const _P={mcp_oauth_provider_initialized:"MCP OAuth provider initialized",mcp_oauth_tokens_loaded:"MCP OAuth tokens loaded",mcp_oauth_tokens_saved:"MCP OAuth tokens saved",mcp_oauth_callback_completion:"MCP OAuth callback exchange completed",mcp_oauth_client_info_loaded:"MCP OAuth client information loaded",mcp_oauth_client_info_saved:"MCP OAuth client information saved",mcp_oauth_refresh_prepare:"MCP OAuth refresh prepared",mcp_oauth_refresh_error_release:"MCP OAuth refresh error released",mcp_oauth_state_transition:"MCP OAuth state transition",mcp_oauth_credentials_invalidated:"MCP OAuth credentials invalidated"};function CP(e){const t=e.message??_P[e.event],r={event:e.event,cursorMcp:{oauth:tP({...e.metadata})}},n=e.level??"info";"error"!==n?"warn"!==n?"debug"!==n?e.logger.info?.(t,r):e.logger.debug?.(t,r):e.logger.warn?.(t,r):e.logger.error?.(t,e.error,r)}const EP=new Map(["AWS4-HMAC-SHA256","Api-Key","ApiKey","Basic","Bearer","Bot","DPoP","Digest","GNAP","HOBA","Key","Mutual","NTLM","Negotiate","OAuth","PrivateToken","SCRAM-SHA-1","SCRAM-SHA-256","Token","vapid"].map((e=>[e.toLowerCase(),e]))),xP=4096;function PP(e){return"object"==typeof e&&null!==e&&"url"in e&&"string"==typeof e.url}function RP(e){return"string"==typeof e?e:e instanceof URL?e.toString():e.url}function IP(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function TP(e){if(e instanceof Headers)return e;if(Array.isArray(e)){const t=[];for(const r of e){if(!Array.isArray(r)||"string"!=typeof r[0]||"string"!=typeof r[1])return;t.push([r[0],r[1]])}return t}if(IP(e)){const t={};for(const[r,n]of Object.entries(e)){if("string"!=typeof n)return;t[r]=n}return t}}function AP(e,t){const r=new Headers(TP(PP(e)?e.headers:void 0));return new Headers(TP(t?.headers)).forEach(((e,t)=>{r.set(t,e)})),r}function $P(e){const t=[];return e.forEach(((e,r)=>{t.push(r)})),t.sort()}function MP(e){if(null===e)return null;const t=Number.parseInt(e,10);return Number.isNaN(t)?null:t}function DP(e,t){if(null==e)return{kind:"none",bytes:0,contentLength:MP(t.get("content-length"))};if("string"==typeof e){const r=(new TextEncoder).encode(e).length;return{kind:"text",bytes:r,contentLength:MP(t.get("content-length"))??r}}if(e instanceof URLSearchParams){const r=e.toString(),n=(new TextEncoder).encode(r).length;return{kind:"text",bytes:n,contentLength:MP(t.get("content-length"))??n}}return e instanceof Blob?{kind:"blob",bytes:e.size,contentLength:MP(t.get("content-length"))??e.size}:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?{kind:"binary",bytes:e.byteLength,contentLength:MP(t.get("content-length"))??e.byteLength}:"object"==typeof e&&null!==e&&("getReader"in e||Symbol.asyncIterator in e)?{kind:"stream",bytes:null,contentLength:MP(t.get("content-length"))}:{kind:"unknown",bytes:null,contentLength:MP(t.get("content-length"))}}function OP(e,t){if(null===e||!e.toLowerCase().startsWith("application/x-www-form-urlencoded"))return;const r="string"==typeof t?function(e){for(const t of e.split("&")){const e=t.indexOf("="),r=e>=0?t.slice(0,e):t;let n;try{n=decodeURIComponent(r.replaceAll("+"," "))}catch{return}if("grant_type"!==n)continue;const o=e>=0?t.slice(e+1):"";try{return decodeURIComponent(o.replaceAll("+"," "))}catch{return}}}(t):t instanceof URLSearchParams?t.get("grant_type")??void 0:void 0;return r?function(e){switch(e){case"authorization_code":case"refresh_token":case"client_credentials":case"urn:ietf:params:oauth:grant-type:jwt-bearer":case"urn:ietf:params:oauth:grant-type:token-exchange":return e;default:return"other"}}(r):void 0}function FP(e){const{input:t,init:r}=e,n=rP(RP(t)),o=AP(t,r),s=$P(o),i=o.get("content-type"),a=oP(o.get("mcp-session-id")??void 0),c=function(e){if(!e)return null;const t=e.trim().split(/\s+/,1)[0]??"";return EP.get(t.toLowerCase())??"unrecognized"}(o.get("authorization"));return{method:(r?.method??(PP(t)?t.method:void 0)??"GET").toUpperCase(),url:n,headers:{names:s,count:s.length},contentType:i,body:DP(r?.body,o),sessionIdHash:a??null,authorizationScheme:c}}function NP(e,t){const r=$P(e.headers),n=MP(e.headers.get("content-length"));return{status:e.status,ok:e.ok,headers:{names:r,count:r.length},contentType:e.headers.get("content-type"),body:{kind:null===e.body?"none":"stream",bytes:null===e.body?0:n,contentLength:n,...void 0!==t?{errorSummary:t}:{}},sessionIdHash:oP(e.headers.get("mcp-session-id")??void 0)??null,wwwAuthenticateHash:oP(e.headers.get("www-authenticate")??void 0)??null,mcpProtocolVersion:e.headers.get("mcp-protocol-version")??null,requestId:e.headers.get("x-request-id")??null,retryAfter:LP(e.headers,"retry-after"),slackRateLimitType:LP(e.headers,"x-slack-ratelimit-type")}}function LP(e,t){return e.get(t)?.slice(0,64)??null}function jP(e){const t={};return void 0!==e.errorName&&(t.name=e.errorName),void 0!==e.errorMessage&&(t.message=e.errorMessage),void 0!==e.errorType&&(t.type=e.errorType),void 0!==e.oauthErrorCode&&(t.oauthErrorCode=e.oauthErrorCode),void 0!==e.errorResponseSummary&&(t.responseSummary=e.errorResponseSummary),void 0!==e.networkClassification&&(t.networkClassification=e.networkClassification),void 0!==e.sdkErrorKind&&(t.sdkErrorKind=e.sdkErrorKind),t}function UP(e,t){const r=FP({input:e,init:t});if(void 0!==OP(r.contentType,t?.body))return!0;const n=r.url.path?.toLowerCase()??"";return n.endsWith("/token")||n.includes("/oauth/token")||n.includes("/connect/token")}const BP=e=>e,WP="REDACTED_SESSION_ID",HP=/\b00D[A-Za-z0-9]{12,15}![A-Za-z0-9._]{20,512}/g;async function qP(e,t,r){try{const n=r(await e.clone().text());return n.length>t?n.slice(0,t):n}catch{return}}async function zP(e){if(!UP(e.input,e.init))return;const t=await qP(e.response,xP,e.redact);if(void 0!==t)try{return SP(JSON.parse(t))}catch{return bP(t,{maxLength:xP})}}async function GP(e){const t=await async function(e,t,r){try{if(t.ok)return;const n=t.headers.get("content-type")?.toLowerCase()??"";if(!n.includes("json")&&!n.includes("text"))return;const o=await qP(t,xP,r);if(void 0===o)return;return function(e){if("/mcp"!==(t=rP(RP(e.input)).path)&&!0!==t?.endsWith("/mcp"))return bP(e.rawText,{maxLength:xP});var t;try{const t=JSON.parse(e.rawText);return IP(t)?function(e){const t=e.error;if("string"==typeof t)return JSON.stringify({error:t});if("object"!=typeof t||null===t)return;if(!IP(t))return;const r=t,n="number"==typeof r.code||"string"==typeof r.code?r.code:void 0,o="string"==typeof r.message?bP(r.message,{maxLength:xP}):void 0;return void 0!==n||void 0!==o?JSON.stringify({...void 0!==n?{code:n}:{},...void 0!==o?{message:o}:{}}):void 0}(t):void 0}catch{return}}({input:e,rawText:o})}catch{return}}(e.input,e.response,e.redact);return{responseErrorSummary:t,oauthTokenErrorBodySummary:void 0===t?await zP({input:e.input,response:e.response,init:e.init,redact:e.redact}):void 0}}function VP(e,t,r){try{e()}catch{t.warn?.("MCP HTTP exchange logging failed",{event:"mcp_http_exchange_logging_failure",phase:r})}}function KP(e,t,r){if("string"==typeof e)return t(e);if("object"!=typeof e||null===e||r>12)return e;if(Array.isArray(e))return e.map((e=>KP(e,t,r+1)));const n=Object.getPrototypeOf(e);return n!==Object.prototype&&null!==n?e:Object.fromEntries(Object.entries(e).map((([e,n])=>[e,KP(n,t,r+1)])))}function JP(e,t){const r=e=>{const r=KP(e,t,0);return IP(r)?r:void 0};return{debug:(t,n)=>e.debug?.(t,r(n)),info:(t,n)=>e.info?.(t,r(n)),warn:(t,n)=>e.warn?.(t,r(n))}}function ZP(e){const{fetch:t,logSuccessfulExchanges:r=!0,redactLogText:n}=e,o=void 0===n?e.logger:JP(e.logger,n);return async(s,i)=>{const a=Date.now(),c="function"==typeof e.metadata?e.metadata(s):e.metadata,l=!0===e.redactEchoedSessionId?function(e,t,r){const n=AP(e,t).get("mcp-session-id")?.trim()??"";return e=>{const t=n.length>=8?e.split(n).join(WP):e;return r(t.replace(HP,WP))}}(s,i,n??BP):n??BP;try{const e=await t(s,i),{responseErrorSummary:n,oauthTokenErrorBodySummary:u}=e.ok?{}:await GP({input:s,init:i,response:e,redact:l});return!r&&e.ok||VP((()=>{!function(e){const{logger:t,response:r}=e,n=function(e){const{input:t,init:r,response:n,durationMs:o,metadata:s,responseErrorSummary:i,oauthTokenErrorBodySummary:a}=e,c=FP({input:t,init:r}),l=OP(c.contentType,r?.body);return{event:"mcp_http_exchange",outcome:n.ok?"success":"http_error",durationMs:o,cursorMcp:{transport:{...s,request:c,response:NP(n,i),...void 0!==l?{oauth:{grantType:l}}:{},...void 0!==a?{oauthTokenErrorBodySummary:a}:{}}}}}(e);r.ok?t.info?.("MCP HTTP exchange completed",n):function(e){return 401===e.response.status&&null===e.request.authorizationScheme&&e.response.headers.has("www-authenticate")&&!UP(e.input,e.init)}({response:r,request:n.cursorMcp.transport.request,input:e.input,init:e.init})?t.debug?.("MCP HTTP exchange completed",n):t.warn?.("MCP HTTP exchange completed",n)}({logger:o,input:s,init:i,response:e,durationMs:Date.now()-a,metadata:c,responseErrorSummary:n,oauthTokenErrorBodySummary:u})}),o,"success"),e}catch(t){const r=function(e){if(!aP(e))return;const t=aP(e.cause)?e.cause:void 0,r=[e.response,t?.response];for(const e of r)if("object"==typeof(n=e)&&null!==n&&"status"in n&&"number"==typeof n.status&&"headers"in n&&"object"==typeof n.headers&&null!==n.headers&&"get"in n.headers&&"function"==typeof n.headers.get)return e;var n}(t),{responseErrorSummary:u,oauthTokenErrorBodySummary:d}=r?await GP({input:s,init:i,response:r,redact:l}):{};throw VP((()=>{!function(e){const{logger:t}=e;t.warn?.("MCP HTTP exchange failed",function(e){const{input:t,init:r,error:n,durationMs:o,metadata:s,responseFromError:i,responseErrorSummary:a,oauthTokenErrorBodySummary:c}=e,l=kP(n,e.redactLogText),u=FP({input:t,init:r}),d=OP(u.contentType,r?.body);return{event:"mcp_http_exchange",outcome:"error",durationMs:o,cursorMcp:{transport:{...s,request:u,response:void 0!==i?NP(i,a):{status:l.httpStatus??null,ok:null,headers:{names:[],count:0},contentType:null,body:{kind:"none",bytes:null,contentLength:null,...void 0!==a?{errorSummary:a}:{}},requestId:null,sessionIdHash:null,wwwAuthenticateHash:null,mcpProtocolVersion:null,retryAfter:null,slackRateLimitType:null},...void 0!==d?{oauth:{grantType:d}}:{},...void 0!==c?{oauthTokenErrorBodySummary:c}:{},error:jP(l)}}}}(e))}({logger:o,input:s,init:i,error:t,durationMs:Date.now()-a,metadata:c,responseFromError:r,responseErrorSummary:u,oauthTokenErrorBodySummary:d,redactLogText:!0===e.redactEchoedSessionId?l:n})}),o,"failure"),t}}}function XP(e,t){const r=e?.access_token,n="string"==typeof r?r.length:0,o=Boolean(e?.refresh_token),s="number"==typeof e?.expires_in&&Number.isFinite(e.expires_in)?e.expires_in:null;return{accessTokenLen:n,refreshTokenPresent:o,expiresAtTimestamp:t?.expiresInIsFresh&&null!==s?Date.now()+Math.round(1e3*s):null,grantedScope:"string"==typeof e?.scope&&e.scope.length>0?e.scope:null}}function QP(e){const t=function(e){if(!e||"object"!=typeof e)return;const t=e.code;if("number"==typeof t&&t>=100&&t<=599)return t;if("string"==typeof t&&/^\d{3}$/.test(t)&&Number(t)>=100&&Number(t)<=599)return Number(t);const r=e instanceof Error||"object"==typeof e&&null!==e&&"message"in e&&"string"==typeof e.message?e.message:void 0;if(!r)return;const n=r.match(/\bHTTP\s+(\d{3})\b/i);if(!n?.[1])return;const o=Number.parseInt(n[1],10);return Number.isNaN(o)?void 0:o}(e);return void 0!==t?400===t||404===t||405===t:!!(e instanceof Error&&e.message.toLowerCase().includes("sessionid must be provided"))||function(e){if(!(e instanceof Error))return!1;const t="code"in e&&"string"==typeof e.code?e.code:void 0,r="cause"in e&&"object"==typeof e.cause&&null!==e.cause&&"code"in e.cause&&"string"==typeof e.cause.code?e.cause.code:void 0;return"ECONNREFUSED"===t||"ECONNREFUSED"===r||e.message.includes("ECONNREFUSED")}(e)}function YP(e,t=process.env){const r=t.TMPDIR,n={...void 0===r?{}:{TMPDIR:r},...e},{NODE_COMPILE_CACHE:o,...s}=n;return{...s,NODE_DISABLE_COMPILE_CACHE:"1"}}const eR=["PYTHONIOENCODING","PYTHONUTF8","PYTHONLEGACYWINDOWSSTDIO"],tR=[".exe",".cmd",".bat"],rR=/^pythonw?(?:\d+(?:\.\d+)*t?)?$/,nR=new Set(["py","pyw"]),oR=new Set(["--cache-dir","--color","--allow-insecure-host","--directory","--project","--config-file"]),sR=new Set;function iR(e){return eR.some((t=>function(e,t){const r=t.toUpperCase();return Object.entries(e).some((([e,t])=>void 0!==t&&e.toUpperCase()===r))}(e,t)))}function aR(e,t){for(let r=0;r=2&&e.endsWith(t)?e.slice(1,-1):e}(e.trim())).toLowerCase();for(const e of tR)if(t.endsWith(e))return t.slice(0,-e.length);return t}(e);if(rR.test(r)||nR.has(r)||"uvx"===r)return!0;if("uv"===r){const e=aR(t,oR);return"run"===e?.value||"tool"===e?.value&&"run"===aR(e.rest,oR)?.value}return"pipx"===r&&"run"===aR(t,sR)?.value}(n,o)?iR(i)||iR(r)?i:{...i,PYTHONIOENCODING:"utf-8:surrogateescape"}:i}async function lR(e){const t=[],r=new Set;let n;for(let o=1;;o++){const s=await e.fetchPage(n),i=e.itemsOf(s);t.push(...i);const a=e.nextCursorOf(s);if(!a||r.has(a))return t;if(o>=1e3)throw new Error("MCP list did not end after 1000 pages; refusing to keep paging");r.add(a),n=a}}var uR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"),dR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js"),hR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js"),pR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js");var fR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js");function mR(e){return`${typeof e}:${String(e)}`}function gR(e){const t=new Map,r=new Set,n=new Set,o=e=>{for(const t of n)t(e)},s=e=>{t.delete(e),r.delete(e)},i=e.send.bind(e);e.send=(e,n)=>((e=>{if("method"in e)if("tools/call"===e.method&&"id"in e){const r=e.params?.name;"string"==typeof r&&t.set(mR(e.id),r)}else if("notifications/cancelled"===e.method){const n=e.params?.requestId;if("string"!=typeof n&&"number"!=typeof n)return;const o=mR(n);if(!t.has(o))return;if(r.add(o),r.size>64){const e=r.values().next().value;void 0!==e&&s(e)}}})(e),i(e,n));const a=e.onmessage;return e.onmessage=(e,n)=>{(e=>{if("method"in e)return void("notifications/tools/list_changed"===e.method&&o({kind:"tools_list_changed"}));if(!("id"in e))return;const n=e.id;if("string"!=typeof n&&"number"!=typeof n)return;const i=mR(n),a=t.get(i);if(void 0===a)return;const c=r.has(i);if(s(i),!c)return;const l="error"in e||"object"==typeof e.result&&null!==e.result&&"isError"in e.result&&!0===e.result.isError;o({kind:"late_tool_result",toolName:a,isError:l})})(e),a?.(e,n)},{subscribe:e=>(n.add(e),()=>{n.delete(e)})}}function wR(e){const t=Object.entries(e.headers??{}).map((([e,t])=>[e.toLowerCase(),t])).sort((([e],[t])=>et?1:0));return(0,bo.createHash)("sha256").update(JSON.stringify([e.url,t,e.accessToken??null])).digest("hex")}class yR{constructor(e,t){this.inner=e,this.initializeResult=t,e.onclose=()=>this.onclose?.(),e.onerror=e=>this.onerror?.(e),e.onmessage=e=>this.onmessage?.(e)}get sessionId(){return this.inner.sessionId}setProtocolVersion(e){this.inner.setProtocolVersion(e)}start(){return this.inner.start()}close(){return this.inner.close()}async send(e,t){if((0,Mx.vo)(e)&&(0,Mx.eK)(e)){const t={jsonrpc:"2.0",id:e.id,result:this.initializeResult};queueMicrotask((()=>this.onmessage?.(t)))}else(0,Mx.wU)(e)||await this.inner.send(e,t)}}const vR=je.object({tools:je.array(je.unknown()),nextCursor:je.unknown().optional(),_meta:je.unknown().optional()}),bR={typeFilled:0,toolDropped:0,outputStripped:0};function SR(e){if(PR(e))return"string"==typeof e.name?e.name:void 0}function kR(e){return _R(e.issues.filter((e=>"outputSchema"===e.path[0])))}function _R(e){return e.map((e=>`${e.path.map(String).join(".")}: ${e.message}`))}function CR(e){if(!PR(e))return e;const t={...e};return delete t.outputSchema,t}function ER(e){return PR(e)&&!("type"in e)}function xR(e,t){return{...e,inputSchema:{type:"object",...t}}}function PR(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var RR=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js");const IR=new class{constructor({maxSchemasPerCompiler:e=2048,createCompiler:t=()=>new RR.p}={}){this.compiled=new Map,this.maxSchemasPerCompiler=e,this.createCompiler=t,this.compiler=t()}get compiledSchemaCount(){return this.compiled.size}getValidator(e){let t;return r=>(t??=this.compile(e),t(r))}compile(e){const t=JSON.stringify(e),r=(0,bo.createHash)("sha256").update(t).digest("base64url"),n=this.compiled.get(r);if(void 0!==n)return n;this.compiled.size>=this.maxSchemasPerCompiler&&(this.compiler=this.createCompiler(),this.compiled.clear());const o=(t.includes('"$id"')?this.createCompiler():this.compiler).getValidator(e);return this.compiled.set(r,o),o}};class TR{constructor(){this.decoder=new TextDecoder("utf-8"),this.captured="",this.capturedBytes=0}push(e){const t="string"==typeof e?e:this.decoder.decode(e,{stream:!0});return this.append(t),t}end(){const e=this.decoder.decode();return this.append(e),e}get text(){return this.captured}get full(){return this.capturedBytes>=nx}append(e){const t=nx-this.capturedBytes;if(t<=0||0===e.length)return;const r=function(e,t){if(!(t>0))return"";if(3*e.length<=t)return e;const{read:r}=Xo(e,Math.trunc(t));return r>=e.length?e:e.slice(0,r)}(e,t);this.captured+=r,this.capturedBytes=r.length=100&&t<=599?{error_class:"http",error_code:String(t),transport:e.transport}:void 0!==e.error||!0===e.failed?{error_class:"other",error_code:"exception",transport:e.transport}:!0===e.isError?{error_class:"payload",error_code:"is_error",transport:e.transport}:{error_class:"none",error_code:"none",transport:e.transport}}({transport:ox(t),...r}))}catch{}}const NR=(0,u.Pu)("mcp_tool.oauth_scope_step_up",{description:"A tools/call refused for a missing OAuth scope, by step-up decision",labelNames:["decision","dropped"]});function LR(e){return void 0===e?"unknown":"url"in e?"http":"stdio"}const jR=["authorization_code","refresh_token"],UR=["code"];class BR{constructor(e){this._refreshInProgress=!1,this._identifier=e.identifier,this._redirectUrl=e.redirectUrl,this._serverUrl=e.serverUrl,this._restMcpProviderMetadata=e.restMcpProviderMetadata,this.validateResourceURL=!0===e.restMcpProviderMetadata?.omitResourceIndicator?async()=>{}:function(e,t){if(function(e,t){const r=t.gtmApiOrigin;if(void 0===e||void 0===r)return!1;let n,o;try{n=new URL(e),o=new URL(r)}catch{return!1}return n.protocol===o.protocol&&n.hostname===o.hostname&&""===n.port&&"/mcp"===n.pathname}(e,t))return async()=>{};const r=vb(e);return void 0!==r&&function(e){return"https:"===e.protocol&&e.hostname===new URL(ab).hostname}(r)?async()=>{}:void 0!==r&&function(e){return"https:"===e.protocol&&"setup.shopify.com"===e.hostname&&""===e.port&&"/mcp"===e.pathname}(r)?bb:wb}(e.serverUrl,e.gtmMcpMatch),this._clientMetadata=e.clientMetadata,this._scopes=e.scopes,this._isScopePinGateEnabled=e.isScopePinGateEnabled,this.scopeStepUp=e.scopeStepUp,this._tokens=e.tokens,this._clientInformation=e.clientInformation,this._saveTokens=e.saveTokens,this._prepareForRefresh=e.prepareForRefresh,this._releaseRefreshLeaseOnError=e.releaseRefreshLeaseOnError,this._invalidateCredentials=e.invalidateCredentials,this._saveClientInformation=e.saveClientInformation,this.addClientAuthentication=e.addClientAuthentication}get redirectUrl(){return this._redirectUrl}get clientMetadata(){return this._clientMetadata}state(){return this._oauthAttemptId=(0,bo.randomUUID)(),this._oauthState=function(e,t,r){const n={id:e,owner:t,...r?{attemptId:r}:{}};return Buffer.from(JSON.stringify(n),"utf8").toString("base64url")}(this._identifier,{workspaceId:this._redirectUrl},this._oauthAttemptId),this._oauthState}clientInformation(){return this._clientInformation}hasClientInformation(){return void 0!==this._clientInformation}async saveClientInformation(e){this._clientInformation=e,await this._saveClientInformation(e)}tokens(){return this.scopeStepUp?.tokensForSdk(this._tokens)??this._tokens}async saveTokens(e){const t=this._refreshInProgress;this._refreshInProgress=!1,this._tokens=e,await this._saveTokens(e),await(this.scopeStepUp?.recordTokens(e,{isRefresh:t}))}async prepareForRefresh(){await(this._prepareForRefresh?.()),this._refreshInProgress=!0}async releaseRefreshLeaseOnError(e){this._refreshInProgress=!1,await(this._releaseRefreshLeaseOnError?.(e))}async invalidateCredentials(e){switch(this._refreshInProgress=!1,e){case"tokens":this._tokens=void 0;break;case"client":this._clientInformation=void 0;break;case"verifier":this._codeVerifier=void 0,this._oauthState=void 0,this._oauthAttemptId=void 0;break;case"all":this._tokens=void 0,this._clientInformation=void 0,this._codeVerifier=void 0,this._oauthState=void 0,this._oauthAttemptId=void 0,this._lastRedirectUrl=void 0,await(this.scopeStepUp?.clear({keepPendingScopes:!0}));break;default:return e}await(this._invalidateCredentials?.(e))}async redirectToAuthorization(e){const t=await(this.scopeStepUp?.prepareAuthorization());(function(e,t,r={}){const n=r.stepUpScopes??[],o=void 0!==t&&t.length>0?t:n.length>0?(e.searchParams.get("scope")??"").split(" ").filter((e=>e.length>0)):void 0;var s;void 0!==o&&e.searchParams.set("scope",(s={scopes:o,stepUpScopes:n},[...new Set([...s.scopes,...s.stepUpScopes])]).join(" "))})(e,function(e,t,r){const n=mb(e);return!0!==n?.pinsScopesOverConfiguredScopes?void 0!==t&&t.length>0||void 0===r?t:Sb(e)?.baseScopes??t:void 0!==n.scopesPinGate&&!0!==r?.(n.scopesPinGate)?t:n.scopes??t}(this._serverUrl??"",this._scopes,this._isScopePinGateEnabled),{stepUpScopes:t?.stepUpScopes}),void 0!==this._serverUrl&&function(e,t){const r=mb(t)?.authorizationParams;if(void 0!==r)for(const[t,n]of Object.entries(r))e.searchParams.set(t,n)}(e,this._serverUrl);for(const[t,r]of Object.entries(this._restMcpProviderMetadata?.authorizationParams??{}))e.searchParams.set(t,r);(!0===this._restMcpProviderMetadata?.omitConsentPrompt||function(e){return"login.microsoftonline.com"===e.hostname}(e))&&function(e){const t=new Set(e.searchParams.getAll("prompt").flatMap((e=>e.split(" "))).filter((e=>""!==e&&"consent"!==e)));e.searchParams.delete("prompt"),t.size>0&&e.searchParams.set("prompt",[...t].join(" "))}(e),await(t?.recordRequestedScopes(e)),this._lastRedirectUrl=e}get lastRedirectUrl(){return this._lastRedirectUrl}async saveCodeVerifier(e){this._codeVerifier=e}codeVerifier(){if(!this._codeVerifier)throw new Error("No code verifier saved");return this._codeVerifier}}async function WR(e){const{serverName:t,config:n,tokenStorage:o}=e,s=await cx(n.url,e.fetchImpl),i=Ab({loopbackIpv4:s?.loopbackIpv4,redirectUrl:e.authRedirectUrl}),a=function(e,t){const r=ix(e?.CLIENT_ID);if(void 0!==r)return{client_id:r,...e?.CLIENT_SECRET?{client_secret:e.CLIENT_SECRET}:{},redirect_uris:$b(t),grant_types:[...jR],response_types:[...UR],token_endpoint_auth_method:"none"}}(n.auth,i),c=function({storedClientInformation:e,staticClientInformation:t}){return t?e&&e.client_id===t.client_id?{...t,...e,client_secret:t.client_secret??e.client_secret,redirect_uris:t.redirect_uris,grant_types:e.grant_types??t.grant_types,response_types:e.response_types??t.response_types,token_endpoint_auth_method:e.token_endpoint_auth_method??t.token_endpoint_auth_method}:t:e}({storedClientInformation:await o.loadClientInformation(),staticClientInformation:a});return new BR({identifier:t,redirectUrl:i,serverUrl:n.url,restMcpProviderMetadata:s,gtmMcpMatch:e.gtmMcpMatch??{gtmApiOrigin:void 0},clientMetadata:{redirect_uris:$b(i),token_endpoint_auth_method:"none",grant_types:[...jR],response_types:[...UR],client_name:"Cursor",logo_uri:"https://ptht05hbb1ssoooe.public.blob.vercel-storage.com/assets/uploads/cursorlogomcpv3.svg"},scopes:n.auth?.scopes,isScopePinGateEnabled:e.isScopePinGateEnabled,...!0===e.scopeChallengeStepUp&&void 0!==o.loadScopeStepUpRecord&&void 0!==o.saveScopeStepUpRecord?{scopeStepUp:Cx({serverUrl:n.url,accountKey:t,configuredScopes:n.auth?.scopes,readTokenScope:async()=>void 0!==o.loadGrantedScope?o.loadGrantedScope():(await o.loadTokens())?.scope,readRecord:async()=>o.loadScopeStepUpRecord?.(),writeRecord:async e=>o.saveScopeStepUpRecord?.(e),readScopesSupported:t=>async function(e){try{const{discoverAuthorizationServerMetadata:t,discoverOAuthProtectedResourceMetadata:n}=await Promise.resolve().then(r.bind(r,"../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js")),o=await n(e.serverUrl,void 0!==e.resourceMetadataUrl?{resourceMetadataUrl:new URL(e.resourceMetadataUrl)}:void 0,e.fetch),s=await t(o.authorization_servers?.[0]??new URL("/",e.serverUrl),{fetchFn:e.fetch}).catch((()=>{}));if(void 0===s&&!0===e.requireAuthorizationServerMetadata)return;const i=new Set([...o.scopes_supported??[],...s?.scopes_supported??[]]);return i.size>0?[...i]:void 0}catch{return}}({serverUrl:n.url,resourceMetadataUrl:t,fetch:e.fetchImpl})})}:{},tokens:await o.loadTokens(),clientInformation:c,saveTokens:e=>o.saveTokens(e),prepareForRefresh:()=>o.prepareForRefresh?.()??Promise.resolve(),releaseRefreshLeaseOnError:e=>o.releaseRefreshLeaseOnError?.(e)??Promise.resolve(),invalidateCredentials:o.invalidateCredentials?e=>o.invalidateCredentials(e):void 0,saveClientInformation:e=>o.saveClientInformation(e),addClientAuthentication:o.tokenEndpointAuth?.({clientId:c?.client_id})})}const HR=new Set;let qR=!1;function zR(){for(const e of HR)try{process.kill(e,"SIGKILL")}catch{}}function GR(e){return Ix(e)?new uR.D_:e}function VR(e,t){return Zx(e??globalThis.fetch.bind(globalThis),{serverUrl:t})}function KR(e,t,r){const n=Xx(e,t),o=r??(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),s=void 0!==n.cursorAuthHeaderValue&&void 0!==n.cursorAuthOrigin&&void 0!==o?Qx((()=>n.cursorAuthHeaderValue),n.cursorAuthOrigin,o):o;return{transportHeaders:n.headers,baseFetch:s}}class JR{constructor(e,t,r){this._toolListGeneration=0,this._toolListSuccessGeneration=0,this._toolListStateGeneration=0,this._callToolLock=Promise.resolve(),this._callToolQueueDepth=0,this._stateEnteredAtMs=Date.now(),this._terminatingSession=!1,this._closeRequested=!1,this.serverName=e,this.client=t,this.tools=new Yx,this.stateValue=r.initialState,this._authProvider=r.authProvider,this._authCodeExchange=r.authCodeExchange,this._sessionId=r.sessionId,this._protocolVersion=r.protocolVersion,this._resumedInstructions=r.resumedInstructions,this._sessionlessInitialize=r.sessionlessInitialize,this.config=r.config,this._oauthLifecycleLogger=r.oauthLifecycleLogger,this._serverSignals=r.serverSignals,this._redactLogText=r.redactLogText,this.setupElicitationHandler(),!0===r.stdioServer&&(t.onclose=()=>{this._closeRequested||(this.updateState({kind:"error",message:"MCP server exited"},"stdio_exited"),this.tools.invalidate())})}_stateKindLabel(e){return"requires_authentication"===e.kind?"needsAuth":e.kind}_logStateTransition(e,t,r,n){if(!this._oauthLifecycleLogger)return;const o=this._stateKindLabel(e),s=this._stateKindLabel(t);if(o===s)return;const i=Date.now()-this._stateEnteredAtMs,a=(()=>{try{const e=this.config&&"url"in this.config?this.config.url:void 0;return e?new URL(e).host:void 0}catch{return}})();CP({logger:this._oauthLifecycleLogger,event:"mcp_oauth_state_transition",metadata:{identifier:this.serverName,from:o,to:s,cause:r,serverUrlHost:a,previousStateDurationMs:i,...n}})}static createClient(e={}){const t={elicitation:{form:{}},...!1===e.mcpAppsUi?{}:{extensions:{"io.modelcontextprotocol/ui":{mimeTypes:["text/html;profile=mcp-app"]}}}};return new fR.K({name:"Cursor",version:"1.0.0"},{capabilities:t,jsonSchemaValidator:IR})}setupElicitationHandler(){this.client.setRequestHandler(Mx.$9,(async e=>{if(!this._currentElicitationProvider)return{action:"decline"};if(!("requestedSchema"in e.params))return{action:"decline"};try{const t=e.params.requestedSchema,r=await this._currentElicitationProvider.elicit({message:e.params.message,requestedSchema:t});return{action:r.action,content:r.content}}catch(e){return{action:"decline"}}}))}static async fromStreamableHttp(e,t,r,n,o,s,i,a,c,l,u,d=!1,h={}){const p=new URL(t.url);o=o??Pb;const f=await WR({serverName:e,config:t,tokenStorage:r,authRedirectUrl:o,fetchImpl:s,gtmMcpMatch:c,isScopePinGateEnabled:l,scopeChallengeStepUp:u}),m=f.tokens(),g=Xx(t.url,n),w=g.headers,y=d&&function(e){return Object.entries(e??{}).some((([e,t])=>"authorization"===e.toLowerCase()&&t.trim().length>0))}(w)?void 0:f,v=s??(globalThis.fetch?globalThis.fetch.bind(globalThis):void 0),b=void 0!==g.cursorAuthHeaderValue&&void 0!==g.cursorAuthOrigin&&void 0!==v?Qx((()=>g.cursorAuthHeaderValue),g.cursorAuthOrigin,v):v,S=e=>void 0===b||void 0===i?b:ZP({fetch:b,logger:i.logger,metadata:{...i.metadata,transportType:e},redactLogText:i.redactLogText});let k;const _=e=>{const r=f.scopeStepUp,n=e??v;return void 0===r||void 0===n?e:(o={fetch:n,scopeStepUp:r,serverUrl:t.url,startSignIn:async e=>{const t=void 0!==e.resourceMetadataUrl&&URL.canParse(e.resourceMetadataUrl)?new URL(e.resourceMetadataUrl):void 0;await(0,uR.j2)(f,{serverUrl:p.toString(),...void 0!==t?{resourceMetadataUrl:t}:{},...void 0!==b?{fetchFn:b}:{}});const r=f.lastRedirectUrl;k=void 0!==r&&void 0!==t?{redirectUrl:r,resourceMetadataUrl:t}:void 0}},async(e,t)=>{const r=await o.fetch(e,t);if(401!==r.status&&403!==r.status||!function(e){if("string"!=typeof e)return!1;let t;try{t=JSON.parse(e)}catch{return!1}return(Array.isArray(t)?t:[t]).some((e=>"object"==typeof e&&null!==e&&"method"in e&&"tools/call"===e.method))}(t?.body))return r;const n=await o.scopeStepUp.decide({status:r.status,wwwAuthenticate:r.headers.get("www-authenticate"),toolName:Rx(t?.body)});if(void 0===n)return r;if(o.onDecision?.(n),await(r.body?.cancel().catch((()=>{}))),"offer"===n.kind)try{await o.scopeStepUp.signIn((()=>o.startSignIn(n)))}catch(e){ux(o.scopeStepUp.accountKey).warn("MCP OAuth scope step-up: could not start the sign-in",{event:"mcp_oauth_scope_step_up_sign_in_failed",errorName:e instanceof Error?e.name:typeof e})}throw new Px(n,o.serverUrl,o.scopeStepUp.connectorName)});var o},C=JR.createClient(h),E=e=>e instanceof uR.D_||function(e){if(null===e||"object"!=typeof e)return!1;const t=e.name;if("string"==typeof t&&Tx.has(t))return!0;const r=e.errorCode;return!("string"!=typeof r||!Ax.has(r.toLowerCase()))||function(e){if(null===e||"object"!=typeof e)return!1;const t=e.name,r=e.errorCode;if("InvalidRequestError"!==t&&("string"!=typeof r||"invalid_request"!==r.toLowerCase()))return!1;const n=e.message;return"string"==typeof n&&$x.some((e=>e.test(n)))}(e)}(e)||Ix(e),x=async t=>{if(!f.hasClientInformation())throw new Error("OAuth client registration has not completed. The MCP server may not support dynamic client registration or the registration failed.");const r=void 0!==k&&k.redirectUrl===f.lastRedirectUrl?k.resourceMetadataUrl:void 0;await(0,uR.j2)(f,{serverUrl:p.toString(),authorizationCode:t,...void 0!==r?{resourceMetadataUrl:r}:{},...void 0!==b?{fetchFn:b}:{}}),a&&CP({logger:a,event:"mcp_oauth_callback_completion",metadata:{identifier:e,...nP(p.toString()),...XP(f.tokens(),{expiresInIsFresh:!0})}})},P=r=>{const n=f.lastRedirectUrl?.toString?.()??"",o=new JR(e,C,{oauthLifecycleLogger:a,redactLogText:i?.redactLogText,initialState:{kind:"requires_authentication",url:n,callback:async e=>{try{await x(e),o.updateState({kind:"ready"})}catch(e){const t=e instanceof Error?e.message:"Authentication failed";throw new Error(`Authentication callback failed: ${t}`)}}},authProvider:f,authCodeExchange:x,sessionId:r,config:t});return o},R=async r=>{const n=new dR.A(p,{authProvider:y,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...w??{}}},fetch:_(S("sse"))});try{return await C.connect(n),new JR(e,C,{initialState:{kind:"ready"},authProvider:f,authCodeExchange:x,config:t,oauthLifecycleLogger:a,redactLogText:i?.redactLogText})}catch(t){if(await n.close().catch((()=>{})),E(t))return a&&CP({logger:a,event:"mcp_oauth_state_transition",metadata:{identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"sse",refreshTokenPresent:Boolean(m?.refresh_token),...nP(p.toString()),...kP(t,i?.redactLogText)}}),P();if(void 0!==r&&QP(t)&&t instanceof dR._)throw function(e,t){let r=e;for(let e=0;e<8&&r instanceof Error&&r.cause instanceof Error;e++)r=r.cause;return r instanceof Error&&void 0===r.cause&&Reflect.defineProperty(r,"cause",{value:t,writable:!0,configurable:!0,enumerable:!1}),e}(r,t);throw t}};if("sse"===t.type)return R();const I=new pR.j(p,{authProvider:y,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...w??{}}},fetch:_(VR(S("streamableHttp"),p))});try{await C.connect(I);const r=function(e,t=Date.now){return qx(Hx(e),t)}(t.url)?void 0:function(e,r){const o=r.protocolVersion;if(void 0!==r.sessionId||void 0===o)return;const s=e.getServerCapabilities(),i=e.getServerVersion();if(void 0===s||void 0===i)return;const a=e.getInstructions();return{result:{protocolVersion:o,capabilities:s,serverInfo:i,...void 0===a?{}:{instructions:a}},credentialFingerprint:wR({url:t.url,headers:n,accessToken:f.tokens()?.access_token})}}(C,I);return new JR(e,C,{initialState:{kind:"ready"},authProvider:f,authCodeExchange:x,sessionId:I.sessionId,protocolVersion:I.protocolVersion,...void 0===r?{}:{sessionlessInitialize:r},config:t,oauthLifecycleLogger:a,redactLogText:i?.redactLogText})}catch(t){if(E(t))return a&&CP({logger:a,event:"mcp_oauth_state_transition",metadata:{identifier:e,from:"connecting",to:"needsAuth",cause:"connect_auth_error",transport:"streamableHttp",refreshTokenPresent:Boolean(m?.refresh_token),...nP(p.toString()),...kP(t,i?.redactLogText)}}),P(I.sessionId);if(QP(t))return R(t);throw t}}static async fromStreamableHttpWithoutOAuth(e,t,r){const n=JR.createClient(),o=new pR.j(new URL(t.url),{requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...t.headers}},fetch:r});return await n.connect(o),new JR(e,n,{initialState:{kind:"ready"},sessionId:o.sessionId,protocolVersion:o.protocolVersion,config:t})}static async fromCachedSession(e,t,r,n,o,s=Pb,i,a,c,l,u){const d=new URL(t.url),h=await WR({serverName:e,config:t,tokenStorage:n,authRedirectUrl:s,fetchImpl:i,gtmMcpMatch:l,isScopePinGateEnabled:u}),{transportHeaders:p,baseFetch:f}=KR(t.url,o,i),m=new pR.j(d,{authProvider:h,sessionId:r.sessionId,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...p??{}}},fetch:void 0!==f&&void 0!==a?ZP({fetch:f,logger:a.logger,metadata:{...a.metadata,transportType:"streamableHttp"},redactLogText:a.redactLogText}):f});m.setProtocolVersion(r.protocolVersion);const g=function(e){return e._requestMessageId=(0,bo.randomInt)(1048576,2146435072),e}(JR.createClient());return await g.connect(m),new JR(e,g,{initialState:{kind:"ready"},authProvider:h,sessionId:m.sessionId,protocolVersion:r.protocolVersion,...void 0===r.instructions?{}:{resumedInstructions:r.instructions},config:t,oauthLifecycleLogger:c,redactLogText:a?.redactLogText})}static async fromSessionlessInitialize(e,t,r,n,o,s=Pb,i,a,c,l){const u=await WR({serverName:e,config:t,tokenStorage:n,authRedirectUrl:s,fetchImpl:i,gtmMcpMatch:a,isScopePinGateEnabled:c});if(wR({url:t.url,headers:o,accessToken:u.tokens()?.access_token})!==r.credentialFingerprint)return;const{transportHeaders:d,baseFetch:h}=KR(t.url,o,i),p=new pR.j(new URL(t.url),{authProvider:u,requestInit:{headers:{"User-Agent":"Cursor/1.0.0",...d??{}}},fetch:h}),f=JR.createClient();return await f.connect(new yR(p,r.result)),new JR(e,f,{initialState:{kind:"ready"},authProvider:u,sessionlessInitialize:r,config:t,redactLogText:l})}get sessionId(){return this._sessionId}get protocolVersion(){return this._protocolVersion}get sessionlessInitialize(){return this._sessionlessInitialize}get holdsOAuthAccessToken(){return Boolean(this._authProvider?.tokens()?.access_token)}async openStandaloneStream(){const e=this.client.transport;e instanceof pR.j&&await e.resumeStream("")}static async fromCommand(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{$R(s,(0,$.VI)(e.withName("McpSdkClient.fromCommand")),!1);const l=(c=o?.spawn,void 0!==c||"linux"!==process.platform?c:(e,t,r)=>(0,su.D9)(ou.spawn,e,t,r)),u=r.args??[],d=new hR.oQ({command:r.command,args:u,env:YP(cR({command:r.command,args:u,env:n})),cwd:r.cwd,stderr:"pipe",...l&&{spawn:l}}),h=function(e){const t=new TR;let r=null===e;return null!==e&&(e.on("data",(e=>{t.full||t.push(e)})),e.once("end",(()=>{t.end(),r=!0}))),{read:()=>bP(t.text.replace(/\s+/g," ").trim(),{maxLength:nx}),waitForFlush:async()=>{r||null===e||await new Promise((t=>{let r;const n=()=>{void 0!==r&&clearTimeout(r),e.off("end",n),t()};r=setTimeout(n,250),r.unref(),e.once("end",n)}))}}}(d.stderr),p=JR.createClient({mcpAppsUi:o?.mcpAppsUi}),f=o?.connectTimeoutMs??(void 0!==(a=r.startupTimeoutSec)&&Number.isFinite(a)&&a>0?Math.min(1e3*a,3e5):6e4);let m;d.onclose=()=>{var e;void 0!==m&&(e=m,HR.delete(e))};let g=0,w=!0;d.onerror=e=>{w&&function(e){return e instanceof SyntaxError||"ZodError"===e.name}(e)&&(g+=1)};const y=new AbortController,v=p.connect(d,{timeout:f,signal:y.signal});let b;m=d.pid??void 0,void 0!==m&&(i=m,HR.add(i),qR||(qR=!0,process.on("exit",zR)));const S=new Promise(((e,r)=>{b=setTimeout((()=>r(new Error(`MCP server connection timed out after ${f}ms: ${t}`))),f)}));try{await Promise.race([v,S])}catch(e){throw y.abort(),v.catch((()=>{})),await d.close().catch((()=>{})),await h.waitForFlush(),g>0&&e instanceof Error&&(e.message=`${e.message}; non-JSON-RPC output on stdout before initialize (${String(g)} line${1===g?"":"s"})`),function(e,t){if(""===t)return e;const r=e instanceof Error?e:new Error(String(e));return r.message=`${r.message}; stderr: ${t}`,AR.set(r,t),r}(e,h.read())}finally{w=!1,void 0!==b&&clearTimeout(b)}return new JR(t,p,{initialState:{kind:"ready"},config:r,stdioServer:void 0!==m,serverSignals:gR(d)})}catch(e){s.error=e,s.hasError=!0}finally{MR(s)}var i,a,c}terminateSessionOnClose(e){this._sessionTermination=e}setToolCallRequestOptions(e){this._toolCallRequestOptions=e}failToolCallInFlight(e){const t=this._toolCallInFlight;return void 0!==t&&!t.signal.aborted&&(t.abort(e),!0)}onServerSignal(e){return this._serverSignals?.subscribe(e)??(()=>{})}setToolCallOutputSchemaPassthrough(e){this._toolCallOutputSchemaPassthrough=e}async close(){if(this._closeRequested=!0,this._terminatingSession)return;const e=this._sessionTermination,t=this.client.transport;if(void 0!==e&&t instanceof pR.j)return this._terminatingSession=!0,void(async()=>{await async function(e,t){const r=await async function(e,t){if(void 0===e.sessionId)return{outcome:"no_session",durationMs:0};const r=Date.now(),n=e.terminateSession();n.catch((()=>{}));try{await(0,Or.wj)(n,t.timeoutMs)}catch(e){const t=Date.now()-r;return e instanceof Or.MU?{outcome:"timeout",durationMs:t}:e instanceof pR.b&&void 0!==e.code&&e.code>0?{outcome:"rejected",durationMs:t,httpStatus:e.code,error:e.message}:{outcome:"failed",durationMs:t,error:String(e)}}const o=t.deleteObserver?.lastDeleteStatus;return{outcome:405===o?"unsupported":"terminated",durationMs:Date.now()-r,...void 0!==o?{httpStatus:o}:{}}}(e,t);try{t.onResult?.(r)}catch{}return r}(t,e),await this.client.close()})().catch((()=>{}));await this.client.close()}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=$R(t,(0,$.VI)(e.withName("McpSdkClient.getTools")),!1);if(r.span.setAttribute("serverName",this.serverName),r.span.setAttribute("mcp.transport",LR(this.config)),"requires_authentication"===this.stateValue.kind)return r.span.setAttribute("mcp.tools.requires_authentication",!0),[];if("error"===this.stateValue.kind)return[];const n=++this._toolListGeneration;let o=0,s=0;try{const e=await this.tools.get((async()=>{let e;const t=await lR({fetchPage:async t=>{o++;const n=await async function(e,t,r){try{const r=await e.listTools({cursor:t});return{tools:r.tools,nextCursor:r.nextCursor,meta:r._meta,...bR}}catch(c){if(!(c instanceof Error&&"issues"in c&&Array.isArray(c.issues)))throw c}const n=await e.request({method:"tools/list",params:{cursor:t}},vR),o=[];let s=0,i=0,a=0;for(const e of n.tools){let t=e;if(PR(e)){const r=e.inputSchema;ER(r)&&(t=xR(e,r),s++)}let n=Mx.Dn.safeParse(t);if(!n.success&&(c=n.error).issues.some((e=>"outputSchema"===e.path[0]))){const o=Mx.Dn.safeParse(CR(t));o.success&&(a++,r(SR(e),kR(n.error),"output_stripped"),n=o)}n.success?o.push(n.data):(i++,r(SR(e),_R(n.error.issues),"dropped"))}var c;return{tools:o,nextCursor:"string"==typeof n.nextCursor?n.nextCursor:void 0,meta:n._meta,typeFilled:s,toolDropped:i,outputStripped:a}}(this.client,t,((e,t,n)=>{(function(e,t,r){const n=JSON.stringify([e,t,r]);if(XR.has(n))return XR.delete(n),XR.add(n),!1;if(XR.add(n),XR.size>256){const e=XR.keys().next().value;void 0!==e&&XR.delete(e)}return!0})(n,this.serverName,e??"")&&DR.warn(r.ctx,"output_stripped"===n?"Removed an MCP tool output schema the client rejected":"Left out an MCP tool whose definition is invalid",{serverName:this.serverName,..."string"==typeof e?{toolName:e}:{},issues:t})}));return s+=n.typeFilled,QR(r.ctx,"type_filled",n.typeFilled),QR(r.ctx,"tool_dropped",n.toolDropped),QR(r.ctx,"output_stripped",n.outputStripped),e??=function(e){if(!jC(e))return;const t=e.mcpAllowlist;if(!jC(t)||"string"!=typeof t.list)return;const r=UC(t.name,200),n=UC(t.reason,200);if(void 0===r||void 0===n)return;const o={list:"local"===t.list||"cloud"===t.list?t.list:"other",name:r,reason:n},s=BC(t.allowedServerNames)??BC(t.allowedServers);void 0!==s&&(o.allowedServers=s);const i=BC(t.blockedServers);return void 0!==i&&(o.blockedServers=i),o}(n.meta),n},itemsOf:e=>e.tools,nextCursorOf:e=>e.nextCursor});return this._allowlistInUse=this.reportsCursorMcpAllowlist()?e:void 0,t.map((e=>({...e,inputSchema:XC(e.inputSchema),outputSchema:void 0===e.outputSchema?void 0:XC(e.outputSchema)})))}));return this.noteToolListSuccess(),r.span.setAttribute("mcp.tools.fetched",o>0),r.span.setAttribute("mcp.tools.pages",o),o>0&&r.span.setAttribute("mcp.tools.type_filled",s),r.span.setAttribute("mcp.tools.count",e.length),e}catch(e){const t=GR(e);if(r.span.setAttribute("mcp.tools.fetched",o>0),r.span.setAttribute("mcp.tools.pages",o),o>0&&r.span.setAttribute("mcp.tools.type_filled",s),this.noteToolListFailure(r.ctx,t,n),t instanceof uR.D_&&n===this._toolListGeneration&&n>this._toolListStateGeneration&&"ready"===this.stateValue.kind){const e=this.stateValue,r=this._authProvider?.lastRedirectUrl?.toString()??"";this.stateValue={kind:"requires_authentication",url:r,callback:e=>this.completeRuntimeAuthorization(e)},this.discardToolListError(),this._logStateTransition(e,this.stateValue,"runtime_unauthorized",{...kP(t,this._redactLogText)}),this._stateEnteredAtMs=Date.now()}throw t}}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async getAllowlistInUse(){return this._allowlistInUse}reportsCursorMcpAllowlist(){return void 0!==this.config&&"url"in this.config&&LC(this.config.url)}toolListAttemptIsCurrent(e){return e>this._toolListSuccessGeneration&&e>this._toolListStateGeneration}noteToolListSuccess(){this._toolListError=void 0,this._toolListSuccessGeneration=this._toolListGeneration}discardToolListError(){this._toolListError=void 0,this._toolListStateGeneration=this._toolListGeneration}noteToolListFailure(e,t,r){const n=Mx.O4.MethodNotFound;if(t instanceof Mx.Nh&&t.code===n&&void 0===this.client.getServerCapabilities()?.tools)return void this.noteToolListSuccess();if(t instanceof uR.D_||!this.toolListAttemptIsCurrent(r))return;const o=function(e){if(e instanceof Mx.Nh)return{descriptor:`McpError ${e.code}`,errorClass:"McpError",jsonRpcCode:e.code};if(e instanceof pR.b||e instanceof dR._){const t=e instanceof pR.b?"StreamableHTTPError":"SseError",r="number"==typeof e.code?e.code:void 0;return{descriptor:void 0===r?t:`${t} ${r}`,errorClass:t,...void 0===r?{}:{httpStatus:r}}}return e instanceof Error?{descriptor:"Error",errorClass:"Error"}:{descriptor:"unknown",errorClass:"unknown"}}(t);o.descriptor!==this._toolListError&&DR.warn(e,"MCP server failed to list its tools",{serverName:this.serverName,errorClass:o.errorClass,...void 0!==o.jsonRpcCode?{jsonRpcCode:o.jsonRpcCode}:{},...void 0!==o.httpStatus?{httpStatus:o.httpStatus}:{}}),this._toolListError=o.descriptor}async callTool(e,t,r,n,o){const s={stack:[],error:void 0,hasError:!1};try{const a=$R(s,(0,$.VI)(e.withName("McpSdkClient.callTool")),!1);a.span.setAttribute("toolName",t),a.span.setAttribute("serverName",this.serverName),a.span.setAttribute("mcp.transport",LR(this.config));const c=this._callToolLock,l=this._callToolQueueDepth;let u;this._callToolQueueDepth++,this._callToolLock=new Promise((e=>{u=e}));try{{const e={stack:[],error:void 0,hasError:!1};try{const t=$R(e,(0,$.VI)(a.ctx.withName("McpSdkClient.callTool.lockWait")),!1);t.span.setAttribute("serverName",this.serverName),t.span.setAttribute("mcp.call_tool.queued_ahead",l);const r=performance.now();await c;const n=performance.now()-r;t.span.setAttribute("mcp.call_tool.lock_wait_ms",n),a.span.setAttribute("mcp.call_tool.lock_wait_ms",n),a.span.setAttribute("mcp.call_tool.queued_ahead",l)}catch(t){e.error=t,e.hasError=!0}finally{MR(e)}}if("requires_authentication"===this.stateValue.kind)throw new uR.D_(`MCP server "${this.serverName}" requires authentication`);this._currentToolCallId=n,this._currentToolName=t,this._currentElicitationProvider=o;const s=new AbortController;this._toolCallInFlight=s;const u=this._authProvider?.lastRedirectUrl;try{const n={stack:[],error:void 0,hasError:!1};try{const o=$R(n,(0,$.VI)(a.ctx.withName("McpSdkClient.callTool.sdk")),!1);o.span.setAttribute("toolName",t),o.span.setAttribute("serverName",this.serverName);const c=await this.sendToolCall({name:t,arguments:r},s.signal);return o.span.setAttribute("mcp.call_tool.is_error",!0===c.isError),FR(e,this.config,{isError:!0===c.isError}),{content:c.content,isError:!0===c.isError,structuredContent:(i=c.structuredContent,QC(i)),_meta:iE(c._meta)}}catch(e){n.error=e,n.hasError=!0}finally{MR(n)}}catch(t){const r=GR(t);r instanceof Px?(FR(e,this.config,{error:r,httpStatus:r.decision.status}),function(e,t){try{NR.increment(e,1,{decision:t.decision.kind,dropped:String(t.decision.dropped.length>0)})}catch{}}(e,r)):FR(e,this.config,{error:r});const n=r instanceof Px&&"offer"===r.decision.kind&&void 0!==this._authProvider?.lastRedirectUrl&&this._authProvider.lastRedirectUrl!==u;if((r instanceof uR.D_||n)&&"ready"===this.stateValue.kind){const e=this.stateValue,t=this._authProvider?.lastRedirectUrl?.toString()??"";this.stateValue={kind:"requires_authentication",url:t,callback:e=>this.completeRuntimeAuthorization(e)},this.discardToolListError(),this._logStateTransition(e,this.stateValue,n?"scope_step_up":"runtime_unauthorized",{...kP(r,this._redactLogText)}),this._stateEnteredAtMs=Date.now()}throw r}finally{this._toolCallInFlight=void 0,this._currentElicitationProvider=void 0,this._currentToolCallId=void 0,this._currentToolName=void 0}}finally{this._callToolQueueDepth--,c.then(u)}}catch(e){s.error=e,s.hasError=!0}finally{MR(s)}var i}sendToolCall(e,t){const r=this._toolCallRequestOptions?.(e.name),n={...r,signal:void 0===r?.signal?t:AbortSignal.any([r.signal,t])};return!0===this._toolCallOutputSchemaPassthrough?.()?this.client.request({method:"tools/call",params:e},Mx.TF,n):this.client.callTool(e,void 0,n)}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{if($R(t,(0,$.VI)(e.withName("McpSdkClient.getInstructions")),!1).span.setAttribute("serverName",this.serverName),"requires_authentication"===this.stateValue.kind)return;return this.client.getInstructions()??this._resumedInstructions}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async listResources(e){const t={stack:[],error:void 0,hasError:!1};try{if($R(t,(0,$.VI)(e.withName("McpSdkClient.listResources")),!1),"requires_authentication"===this.stateValue.kind||"error"===this.stateValue.kind)return{resources:[]};const r=this.client.getServerCapabilities();return r?.resources?{resources:await lR({fetchPage:e=>this.client.listResources({cursor:e}),itemsOf:e=>e.resources,nextCursorOf:e=>e.nextCursor})}:{resources:[]}}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async readResource(e,t){const r={stack:[],error:void 0,hasError:!1};try{return $R(r,(0,$.VI)(e.withName("McpSdkClient.readResource")),!1),"requires_authentication"===this.stateValue.kind?{contents:[]}:{contents:(await this.client.readResource({uri:t.uri})).contents}}catch(e){r.error=e,r.hasError=!0}finally{MR(r)}}async listPrompts(e){const t={stack:[],error:void 0,hasError:!1};try{return $R(t,(0,$.VI)(e.withName("McpSdkClient.listPrompts")),!1),"requires_authentication"===this.stateValue.kind||"error"===this.stateValue.kind?[]:(this.client.getServerCapabilities()??{prompts:!1}).prompts?(await lR({fetchPage:e=>this.client.listPrompts({cursor:e}),itemsOf:e=>e.prompts,nextCursorOf:e=>e.nextCursor})).map((e=>({name:e.name,description:e.description,arguments:e.arguments?.map((e=>({name:e.name,description:e.description,required:e.required})))}))):[]}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async getPrompt(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{return $R(n,(0,$.VI)(e.withName("McpSdkClient.getPrompt")),!1),"requires_authentication"===this.stateValue.kind?{messages:[]}:{messages:(await this.client.getPrompt({name:t,arguments:r})).messages.map((e=>({role:e.role,content:Array.isArray(e.content)?e.content.map((e=>"text"===e.type?{type:"text",text:e.text}:"image"===e.type?{type:"image",data:e.data,mimeType:e.mimeType}:{type:"text",text:JSON.stringify(e)})):[{type:"text",text:"string"==typeof e.content?e.content:JSON.stringify(e.content)}]})))}}catch(e){n.error=e,n.hasError=!0}finally{MR(n)}}getCurrentToolCallContext(){if(this._currentToolName)return{toolName:this._currentToolName,toolCallId:this._currentToolCallId}}async getState(e){return"ready"===this.stateValue.kind&&void 0!==this._toolListError?{kind:"ready",toolListError:this._toolListError}:this.stateValue}async completeRuntimeAuthorization(e){if(!this._authCodeExchange)throw new Error(`MCP server "${this.serverName}" cannot complete authorization: no code exchange is configured for this client.`);try{await this._authCodeExchange(e)}catch(e){const t=e instanceof Error?e.message:"Authentication failed";throw new Error(`Authentication callback failed: ${t}`)}this.updateState({kind:"ready"},"runtime_authorization_completed")}updateState(e,t){const r=this.stateValue;this.discardToolListError(),this.stateValue=e,this._logStateTransition(r,e,t??"explicit_update"),this._stateEnteredAtMs=Date.now()}}const ZR=(0,u.Pu)("mcp_tool.schema",{description:"One MCP tool definition a tools/list repair touched",labelNames:["outcome"]}),XR=new Set;function QR(e,t,r){if(0!==r)try{ZR.increment(e,r,{outcome:t})}catch{}}class YR extends Error{constructor(e,t){super(`MCP server ${e} not found, available servers: ${t.join(", ")}`),this.serverName=e,this.availableServers=t,this.name="McpServerNotFoundError"}}Error,Error;class eI{constructor(e){this.tools=e}async execute(e,t,r,n){const o=this.tools[e];if(!o)throw new vC(e,Object.keys(this.tools));return o.execute(t,r,n)}async executeOn(e,t,r,n,o){const s=this.tools[t];if(!s)throw new vC(t,Object.keys(this.tools));if(s.client===e)return s.execute(r,n,o)}getTools(){return Object.entries(this.tools).map((([e,t])=>({...t.definition,name:e})))}}class tI{async getClients(e){return{}}async getClient(e,t){}async getInstructions(e){return[]}async getToolSet(e){return new eI({})}async getTools(e){return[]}async getToolsForServers(e,t){return[]}}class rI{constructor(e){this.manager=e}async getClients(e){return this.manager.getClients()}async getClient(e,t){return this.manager.getClient(t)}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=$R(t,(0,$.VI)(e.withName("ManagerMcpLease.getInstructions")),!1);return await this.manager.getInstructions(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async getToolSet(e){const t={stack:[],error:void 0,hasError:!1};try{const r=$R(t,(0,$.VI)(e.withName("ManagerMcpLease.getToolSet")),!1);return await this.manager.getToolSet(r.ctx)}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async getTools(e){const t={stack:[],error:void 0,hasError:!1};try{const r=$R(t,(0,$.VI)(e.withName("ManagerMcpLease.getTools")),!1);return(await this.getToolSet(r.ctx)).getTools()}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async getToolsForServers(e,t){const r=new Set(t);return(await this.getTools(e)).filter((e=>r.has(e.clientKey)))}onDidChange(e){return{dispose:this.manager.onDidChange((()=>e(void 0)))}}async reconcileSelection(e,t,r){for(const e of t.removed){const t=this.manager.getClient(e);this.manager.deleteClient(e);try{await(t?.close?.())}catch{}}for(const n of t.added){if(this.manager.getClient(n))continue;const t=await r(e,n);this.manager.setClient(n,t)}}}class nI{constructor(e,t){this.clients=e,this.elicitationFactory=t,this.changeListeners=new Set,this.warnedToolNameCollisions=new Set}onDidChange(e){return this.changeListeners.add(e),()=>{this.changeListeners.delete(e)}}fireDidChange(){for(const e of this.changeListeners)try{e()}catch(e){console.error("Error in McpManager change listener:",e)}}getClients(){return this.clients}getClient(e){return this.clients[e]}setClient(e,t){this.clients[e]=t,this.fireDidChange()}deleteClient(e){delete this.clients[e],this.fireDidChange()}setListingDeadline(e){this.listingDeadlineAt=void 0===e?void 0:performance.now()+e}async closeAllClients(){const e=Object.values(this.clients);await Promise.all(e.map((async e=>{try{await(e.close?.())}catch{}})))}async getToolSet(e){const t={stack:[],error:void 0,hasError:!1};try{const r=$R(t,(0,$.VI)(e.withName("McpManager.getToolSet")),!1),n=$R(t,oI(this.listingDeadlineAt),!1),o=await(0,Or.PH)(Object.entries(this.clients),(([e,t])=>n.within(t,r.ctx,(()=>t.getTools(r.ctx))).then((r=>(r??[]).map((r=>({...r,clientKey:e,clientName:t.serverName,client:t}))))).catch((()=>[]))),{max:n.concurrency}),s=Array.from(o.values()).flat(),i=new Map;for(const e of s){const t=`${e.clientName}-${e.name}`,r=i.get(t);void 0===r?i.set(t,[e]):r.push(e)}const a={};for(const[e,t]of i){const n=t[0];if(void 0===n)continue;if(t.some((e=>e.clientName!==n.clientName||e.name!==n.name))){if(!this.warnedToolNameCollisions.has(e)){this.warnedToolNameCollisions.add(e);const r=t.map((e=>`${e.clientName}/${e.name}`)).join(", ");console.warn("Colliding MCP tool name; exposing neither:",`${e} (${r})`)}continue}const o=t[t.length-1]?.clientKey,s=t.filter((e=>e.clientKey===o)),i=s[0]??n;s.length>1&&!this.warnedToolNameCollisions.has(e)&&(this.warnedToolNameCollisions.add(e),console.warn("MCP server lists a tool name more than once; using the first:",`${i.clientName}/${i.name}`)),a[e]={definition:{...i,clientKey:i.clientKey,providerIdentifier:i.clientName,toolName:i.name},client:i.client,execute:async(e,t,n)=>{const o=n?.createProvider(i.clientName,i.name,t);return await i.client.callTool(r.ctx,i.name,e,t,o)}}}return new eI(a)}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}async getInstructions(e){const t={stack:[],error:void 0,hasError:!1};try{const r=$R(t,(0,$.VI)(e.withName("McpManager.getInstructions")),!1),n=$R(t,oI(this.listingDeadlineAt),!1),o=await(0,Or.PH)(Object.entries(this.clients),(([e,t])=>n.within(t,r.ctx,(()=>t.getInstructions(r.ctx))).then((e=>e&&0!==e.trim().length?new wn.I0({serverName:t.serverName,instructions:e.trim()}):null)).catch((()=>null))),{max:n.concurrency});return Array.from(o.values()).filter((e=>null!==e))}catch(e){t.error=e,t.hasError=!0}finally{MR(t)}}}function oI(e){if(void 0===e)return{concurrency:4,within:(e,t,r)=>r(),[Symbol.dispose]:()=>{}};let t;const r=new Promise((r=>{t=setTimeout((()=>r(void 0)),Math.max(0,e-performance.now()))}));return{concurrency:Number.POSITIVE_INFINITY,within:async(t,n,o)=>{const s=await Promise.race([t.getState(n).catch((()=>{})),r]);if("ready"!==s?.kind)return Promise.race([o(),r]);let i;try{return await Promise.race([o(),new Promise((t=>{i=setTimeout((()=>t(void 0)),Math.max(2e3,e-performance.now()))}))])}finally{clearTimeout(i)}},[Symbol.dispose]:()=>clearTimeout(t)}}function sI(e,t){return function(e){const{logger:t,ctx:r}=e;return{debug:(e,n)=>t.debug(r,e,n),info:(e,n)=>t.info(r,e,n),warn:(e,n)=>t.warn(r,e,n),error:(e,n,o)=>t.error(r,e,n,o)}}({ctx:e,logger:t})}Error;class iI{constructor(e){this.options=e,CP({logger:e.logger,event:"mcp_oauth_provider_initialized",metadata:this.baseMetadata})}get baseMetadata(){return{identifier:this.options.identifier,...this.options.serverUrl?{serverUrl:nP(this.options.serverUrl)}:{}}}async loadTokens(){const e=await this.options.inner.loadTokens();return CP({logger:this.options.logger,event:"mcp_oauth_tokens_loaded",level:"debug",metadata:{...this.baseMetadata,...XP(e)}}),e}async saveTokens(e){await this.options.inner.saveTokens(e),CP({logger:this.options.logger,event:"mcp_oauth_tokens_saved",metadata:{...this.baseMetadata,...XP(e,{expiresInIsFresh:!0})}})}async prepareForRefresh(){CP({logger:this.options.logger,event:"mcp_oauth_refresh_prepare",metadata:this.baseMetadata}),await(this.options.inner.prepareForRefresh?.())}async releaseRefreshLeaseOnError(e){CP({logger:this.options.logger,event:"mcp_oauth_refresh_error_release",level:"warn",error:e,metadata:{...this.baseMetadata,...kP(e,this.options.redactLogText)}}),await(this.options.inner.releaseRefreshLeaseOnError?.(e))}async loadClientInformation(){const e=await this.options.inner.loadClientInformation();return CP({logger:this.options.logger,event:"mcp_oauth_client_info_loaded",level:"debug",metadata:{...this.baseMetadata,...iP(e)}}),e}async saveClientInformation(e){await this.options.inner.saveClientInformation(e),CP({logger:this.options.logger,event:"mcp_oauth_client_info_saved",metadata:{...this.baseMetadata,...iP(e)}})}async invalidateCredentials(e){void 0!==this.options.inner.invalidateCredentials&&(CP({logger:this.options.logger,event:"mcp_oauth_credentials_invalidated",level:"warn",metadata:{...this.baseMetadata,scope:e}}),await this.options.inner.invalidateCredentials(e))}tokenEndpointAuth(e){return this.options.inner.tokenEndpointAuth?.(e)}get loadScopeStepUpRecord(){return this.options.inner.loadScopeStepUpRecord?.bind(this.options.inner)}get saveScopeStepUpRecord(){return this.options.inner.saveScopeStepUpRecord?.bind(this.options.inner)}}class aI{constructor(e,t){this.storage=e,this.identifier=t}async loadTokens(){return this.storage.loadTokens(this.identifier)}async saveTokens(e){return this.storage.saveTokens(this.identifier,e)}async loadClientInformation(){return this.storage.loadClientInformation(this.identifier)}async saveClientInformation(e){return this.storage.saveClientInformation(this.identifier,e)}get loadScopeStepUpRecord(){const{storage:e,identifier:t}=this;return void 0===e.loadScopeStepUpRecord?void 0:()=>e.loadScopeStepUpRecord(t)}get saveScopeStepUpRecord(){const{storage:e,identifier:t}=this;return void 0===e.saveScopeStepUpRecord?void 0:r=>e.saveScopeStepUpRecord(t,r)}}class cI{constructor(e){this.inner=e}async loadTokens(){}async loadClientInformation(){}async saveTokens(e){return this.inner.saveTokens(e)}async saveClientInformation(e){return this.inner.saveClientInformation(e)}async invalidateCredentials(e){await(this.inner.invalidateCredentials?.(e))}get loadScopeStepUpRecord(){return this.inner.loadScopeStepUpRecord?.bind(this.inner)}get saveScopeStepUpRecord(){return this.inner.saveScopeStepUpRecord?.bind(this.inner)}async loadGrantedScope(){return void 0!==this.inner.loadGrantedScope?this.inner.loadGrantedScope():(await this.inner.loadTokens())?.scope}}var lI=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},uI=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const dI=(0,l.h)("DefinitionMcpLoader"),hI=(0,u.Pu)("connector_policy.blocked",{description:"MCP servers a team or org policy refused to load, once per loader and server.",labelNames:["surface","stage","reason"]});function pI(e){const{filePath:t,baseDir:r}=e;return"~"===t||t.startsWith("~/")?s.default.join(o.default.homedir(),t.slice(1)):t.startsWith("./")||"."===t?s.default.resolve(r??process.cwd(),t):t}function fI(e){return"getManagedSlackWorkspaceLists"in e&&"function"==typeof e.getManagedSlackWorkspaceLists}function mI(e){return"getMcpNetworkControlsConfig"in e&&"function"==typeof e.getMcpNetworkControlsConfig}function gI(e){return e?.length??0}function wI(e){if(void 0!==e)return(0,bo.createHash)("sha256").update(TE(e)).digest("hex")}function yI(e){if(void 0===e)return;let t;return r=>(void 0===t&&(t=e(),queueMicrotask((()=>{t=void 0}))),t?QE(r):r)}async function vI(e,t,n,o,s={middlewares:[],configPath:""},i,a,c={},l={}){const u={stack:[],error:void 0,hasError:!1};try{const{middlewares:d,configPath:h}=s,p=lI(u,(0,$.VI)(e.withName("mcp-agent-exec.loadServer")),!1);p.span.setAttribute("serverName",t);const f=!1!==l.mcpAppsUi;p.span.setAttribute("mcpAppsUi",f),dI.info(p.ctx,`Loading MCP server "${t}" ${f?"declaring":"without declaring"} the MCP Apps UI extension`,{event:"mcp_apps_ui_capability",serverName:t,mcpAppsUi:f,transport:"command"in n?"stdio":"http"});let m=async(e,n)=>{const s={stack:[],error:void 0,hasError:!1};try{const u=lI(s,(0,$.VI)(e.withName("loadServer.next")),!1);u.span.setAttribute("serverName",t);const h=u.ctx;if("command"in n){u.span.setAttribute("kind","command");const e=d.find(mI);return await async function(e,t,n,o,s={}){const i=n.cwd?pI({filePath:n.cwd}):void 0;let a,c;if(n.args&&n.args.length>0)a=pI({filePath:n.command,baseDir:i}),c=n.args.map((e=>pI({filePath:e,baseDir:i})));else{const e=(0,YE.A)(n.command);a=pI({filePath:e[0],baseDir:i}),c=e.slice(1).map((e=>pI({filePath:e,baseDir:i})))}const l=n.env??{},{startupTimeoutSec:u}=n,d=await(o?.getMcpNetworkControlsConfig?.({command:[n.command,...n.args??[]].join(" ")})),h=(0,Ob.$H)(d);if(void 0!==h){const{buildMcpSandboxPolicy:n}=await r.e(449).then(r.bind(r,"../mcp-agent-exec/dist/mcp-sandbox-policy.js")),{SandboxUnsupportedError:o,spawnInSandbox:p}=await Promise.resolve().then(r.bind(r,"../shell-exec/dist/api/index.js")),f=i??process.cwd(),m=await n(h,f);dI.info(e,function(e){return`Sandboxing local MCP server "${e.serverName}" with network controls: networkControlsEnabled=${String(!0===e.networkControlsConfig?.enabled)}, mcpNetworkMode=${e.networkControlsConfig?.mcpNetworkMode??"unset"}, mcpNetworkAllowlistCount=${gI(e.networkControlsConfig?.mcpNetworkAllowlist)}, mcpNetworkDenylistCount=${gI(e.networkControlsConfig?.mcpNetworkDenylist)}, localAgentNetworkAllowlistCount=${gI(e.networkControlsConfig?.localAgentNetworkAllowlist)}, sandboxPolicyHash=${wI(e.sandboxNetworkControlsConfig)??"none"}`}({serverName:t,networkControlsConfig:d,sandboxNetworkControlsConfig:h}),function(e){return{event:"mcp_stdio_sandbox_policy",serverName:e.serverName,networkControlsEnabled:!0===e.networkControlsConfig?.enabled,mcpNetworkMode:e.networkControlsConfig?.mcpNetworkMode,mcpNetworkAllowlistCount:gI(e.networkControlsConfig?.mcpNetworkAllowlist),mcpNetworkDenylistCount:gI(e.networkControlsConfig?.mcpNetworkDenylist),localAgentNetworkAllowlistCount:gI(e.networkControlsConfig?.localAgentNetworkAllowlist),sandboxPolicyHash:wI(e.sandboxNetworkControlsConfig)}}({serverName:t,networkControlsConfig:d,sandboxNetworkControlsConfig:h}));try{return await JR.fromCommand(e,t,{command:a,args:c,cwd:i,startupTimeoutSec:u},l,{...s,spawn:(e,t,r)=>p(e,t,r,m)})}catch(e){if(e instanceof o)throw new AE(t,e);throw e}}return!0===d?.enabled&&"no_sandbox"===d.mcpNetworkMode&&(!0===d.win32UserExtensionUnsandbox?dI.info(e,`Starting local MCP server "${t}" without MCP sandboxing`,{event:"mcp_stdio_win32_user_extension_unsandbox",serverName:t}):dI.info(e,`Starting local MCP server "${t}" without MCP sandboxing`)),JR.fromCommand(e,t,{command:a,args:c,cwd:i,startupTimeoutSec:u},l,s)}(h,t,n,e,l)}if("url"in n){u.span.setAttribute("kind","url");const e=i?.(t);return await async function(e,t,r,n,o,s,i,a,c={}){const l=sI(e,dI),u=function(e,t,r){return{logger:{debug:(t,r)=>dI.debug(e,t,r),info:(t,r)=>dI.info(e,t,r),warn:(t,r)=>dI.warn(e,t,r),error:(t,r,n)=>dI.error(e,t,r,n)},metadata:{identifier:t,source:"mcp-agent-exec"},redactLogText:yI(r)}}(e,t,a),d=void 0!==s&&OE(r.url)?FE(globalThis.fetch.bind(globalThis),{managedSlackWorkspaceLists:()=>s.getManagedSlackWorkspaceLists()}):void 0;return JR.fromStreamableHttp(t,r,n,r.headers,o,d,u,l,void 0,void 0,i,!1,c)}(h,t,n,o,e,d.find(fI),a,c.isLinkSharedPaymentTokenLogRedactionEnabled,l)}throw new Error(`Invalid server: ${JSON.stringify(n)}`)}catch(e){s.error=e,s.hasError=!0}finally{uI(s)}};for(const e of d){const r=m;m=async(n,o)=>await e.load(n,t,o,h,r)}try{return await m(p.ctx,n)}catch(e){throw function(e,t){if(void 0===t)return e;!function(e,t){if("object"!=typeof e||null===e)return;const r=AR.get(e);void 0!==r&&AR.set(e,t(r))}(e,t);const r=function(e,t){if(void 0===t)return e;const r={results:new Map,cycled:new Set},n=NE(e,t,r),o=new Map([...r.cycled].flatMap((e=>{const t=r.results.get(e);return t===e?[]:[[e,t]]})));return o.size>0&&function(e,t){const r=new Set,n=[e];for(let e=0;n.length>0&&e({identifier:e,serverConfig:t,configPath:this.configPath})))}}class SI{constructor(e,t,r=[],n={}){this.source=e,this.tokenStorage=t,this.middlewares=r,this.options=n,this.clientCache=new Map}async load(e,t=!0){const r={stack:[],error:void 0,hasError:!1};try{lI(r,(0,$.VI)(e.withName("DefinitionMcpLoader.load")),!1),t||(await this.closeAllCachedClients(),this.source.clearCache?.());const n=await this.source.getDefinitions(e,t);await this.evictClientsOnSandboxPolicyChange(e,n);const o={};return await(0,Or.PH)([...n],(async r=>{try{const n=t?this.clientCache.get(r.identifier):void 0,s=n??await this.loadDefinitionClient(e,r);n||this.clientCache.set(r.identifier,s),o[r.identifier]=s}catch(t){if(this.handleDefinitionLoadError(e,r,t))return;!function(e,t,r,n){const o=yI(n)??(e=>e),s=function(e){if("object"==typeof e&&null!==e)return AR.get(e)}(r);dI.warn(e,"Failed to load MCP server",{identifier:t.identifier,source:t.source,configPath:t.configPath,metadata:t.metadata,errorMessage:o(r instanceof Error?r.message:String(r)),stderrTail:void 0===s?void 0:o(s)})}(e,r,t,this.options.isLinkSharedPaymentTokenLogRedactionEnabled)}}),{max:this.options.maxConcurrency??Math.max(n.length,1)}),new nI(o,this.options.elicitationFactory)}catch(e){r.error=e,r.hasError=!0}finally{uI(r)}}clearClient(e){this.clientCache.delete(e)}clearAllMcpCaches(){this.clientCache.clear()}async evictClientsOnSandboxPolicyChange(e,t){const r=this.middlewares.find(mI);if(!r)return;let n;try{n=JSON.stringify(await Promise.all([...t].sort(((e,t)=>e.identifier.localeCompare(t.identifier))).map((async e=>{const t=await(r.getMcpNetworkControlsConfig?.((n=e.serverConfig,"url"in n?{url:n.url}:{command:[n.command,...n.args??[]].join(" ")})))??{};var n;return[e.identifier,TE(t)]}))))}catch{return}const o=this.sandboxPolicyFingerprint;this.sandboxPolicyFingerprint=n,void 0!==o&&o!==n&&(dI.info(e,"MCP network-controls policy changed; reloading MCP clients to apply the new egress policy"),await this.closeAllCachedClients())}async closeAllCachedClients(){const e=[...this.clientCache.values()];this.clientCache.clear(),await(0,Or.PH)(e,(async e=>{try{await(e.close?.())}catch{}}),{max:Math.max(e.length,1)})}async loadClient(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{lI(n,(0,$.VI)(e.withName("DefinitionMcpLoader.loadClient")),!1);const o=await this.source.getDefinitions(e);if(await this.evictClientsOnSandboxPolicyChange(e,o),!r){const e=this.clientCache.get(t);if(e)return e}const s=o.find((e=>e.identifier===t));if(!s)throw new Error(`MCP server "${t}" not found in config`);let i;try{i=await this.loadDefinitionClient(e,s,r)}catch(t){throw this.handleDefinitionLoadError(e,s,t),t}return r||this.clientCache.set(t,i),i}catch(e){n.error=e,n.hasError=!0}finally{uI(n)}}async loadDefinitionClient(e,t,r){const n=t.authStorageKey??t.identifier,o=new aI(this.tokenStorage,n),s=sI(e,dI),i=new iI({inner:o,logger:s,redactLogText:yI(this.options.isLinkSharedPaymentTokenLogRedactionEnabled),identifier:n,serverUrl:"url"in t.serverConfig?t.serverConfig.url:void 0}),a=r?new cI(i):i;return vI(e,t.identifier,t.serverConfig,a,{middlewares:this.middlewares,configPath:t.configPath??""},this.options.authRedirectUrlGenerator,this.options.scopeChallengeStepUp,{isLinkSharedPaymentTokenLogRedactionEnabled:this.options.isLinkSharedPaymentTokenLogRedactionEnabled})}handleDefinitionLoadError(e,t,r){let n=!1;try{n="handled"===this.options.onDefinitionLoadError?.(e,t,r)}catch(r){dI.warn(e,"MCP definition load error hook failed",{identifier:t.identifier,source:t.source,configPath:t.configPath,metadata:t.metadata,errorMessage:r instanceof Error?r.message:String(r)})}return n||function(e){return e instanceof RC||e instanceof IC||e instanceof TC||e instanceof kI}(r)}}class kI extends Error{constructor(e,t,r){super(r??("teamNetworkAllowlist"===t?`MCP server "${e}" is not on the team network allowlist`:`MCP server "${e}" is blocked by team policy`)),this.serverName=e,this.reason=t,this.name="McpServerBlockedError"}}const _I=[1e3,3e3];class CI{constructor(e){this.blockingService=e,this.countedPolicyBlocks=new Set}async getMcpNetworkControlsConfig(e){return await(this.blockingService.getMcpNetworkControlsConfig?.(e))??{}}async getManagedSlackWorkspaceLists(){return await(this.blockingService.getManagedSlackWorkspaceLists?.())??[]}async load(e,t,r,n,o){const s=function(e){return{command:"command"in e?[e.command,...e.args??[]].join(" "):void 0,url:"url"in e?e.url:void 0}}(r),i=await(this.blockingService.getMcpServerBlockInfo?.(s))??{blocked:await this.blockingService.isServerBlocked(s)};if(i.blocked){const r=i.reason??"teamPolicy";throw"teamPolicy"!==r||this.countedPolicyBlocks.has(t)||(this.countedPolicyBlocks.add(t),hI.increment(e,1,{surface:"desktop",stage:"tool_call",reason:"server_not_allowed"})),new kI(t,r,i.message)}for(let n=0;;n++)try{const t=await o(e,r);return!0===i.hostMcpBridge&&this.blockingService.recordHostMcpBridgeClient?.(t),this.blockingService.recordMcpServerClient?.(t,s),t}catch(e){if(e instanceof ME)throw new kI(t,"teamPolicy",e.message);const r=e instanceof DE?_I[n]:void 0;if(void 0===r)throw e;await(0,Or.cb)(r)}}}class EI extends SI{constructor(e,t,r=[],n={}){super(new bI(e),t,r,n),this.configPath=e}static init(e,t,r=[]){return new EI(t,e,r)}}function xI(e){return"stdio"===e.type&&e.command?{command:e.command,args:e.args??[],env:e.env,cwd:e.cwd}:"streamableHttp"===e.type&&e.url?{url:e.url,headers:e.headers,auth:e.auth,...void 0!==e.tls?{tls:e.tls}:{},...void 0!==e.placement?{placement:e.placement}:{}}:void 0}var PI=r("../utils/dist/private-file.js"),RI=r("../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_patch_hash=2bd8f4e10dbcd01cfcea8e193632e43ca9f7882c365_34e0eca30e67c84d461832b8dcd209c5/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js");function II(e){const t=RI.VE.safeParse(e);return t.success?t.data:void 0}function TI(e){const t=RI.H5.safeParse(e);return t.success?t.data:void 0}class AI{constructor(e){this.mcpAuthPath=e;const t=AI.mcpAuthPromises.get(e);if(t)this.mcpAuthPromise=t;else{const t=this.loadMcpAuth();this.mcpAuthPromise=t,AI.mcpAuthPromises.set(e,t),t.catch((()=>{AI.mcpAuthPromises.get(e)===t&&AI.mcpAuthPromises.delete(e)}))}AI.saveLocks.has(e)||AI.saveLocks.set(e,Promise.resolve())}async loadMcpAuth(){try{await(0,PI.rV)(this.mcpAuthPath);const e=await(0,Co.readFile)(this.mcpAuthPath,"utf8"),t=JSON.parse(e);if(t&&"object"==typeof t){if(Object.values(t).some((e=>e&&"object"==typeof e&&null!==e&&("access_token"in e||"refresh_token"in e)&&!("tokens"in e)&&!("clientInfo"in e)))){const e={};for(const[r,n]of Object.entries(t)){const t=II(n);void 0!==t&&(e[r]={tokens:t})}return e}const e={};for(const[r,n]of Object.entries(t))n&&"object"==typeof n&&null!==n&&(e[r]={tokens:"tokens"in n?II(n.tokens):void 0,clientInfo:"clientInfo"in n?TI(n.clientInfo):void 0,..."scopeStepUp"in n?{scopeStepUp:n.scopeStepUp}:{}});return e}return{}}catch(e){if(e instanceof Error&&e.message.includes("ENOENT"))return{};throw e}}async loadTokens(e){const t=await this.mcpAuthPromise;return t[e]?.tokens}async saveTokens(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),r[e].tokens=t,await this.saveMcpAuth(r)}))}async loadClientInformation(e){const t=await this.mcpAuthPromise;return t[e]?.clientInfo}async withSaveLock(e){const t=AI.saveLocks.get(this.mcpAuthPath)??Promise.resolve();let r;AI.saveLocks.set(this.mcpAuthPath,new Promise((e=>{r=e})));try{return await t,await e()}finally{r()}}async saveClientInformation(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),r[e].clientInfo=t,await this.saveMcpAuth(r)}))}async loadScopeStepUpRecord(e){const t=await this.mcpAuthPromise;return t[e]?.scopeStepUp}async saveScopeStepUpRecord(e,t){await this.withSaveLock((async()=>{const r=await this.mcpAuthPromise;r[e]||(r[e]={}),void 0===t?delete r[e].scopeStepUp:r[e].scopeStepUp=t,await this.saveMcpAuth(r)}))}async deleteCredentials(e){await this.withSaveLock((async()=>{const t=await this.mcpAuthPromise;e in t&&(delete t[e],await this.saveMcpAuth(t))}))}async saveMcpAuth(e){await(0,PI.Pl)(this.mcpAuthPath,JSON.stringify(e,null,2))}}AI.mcpAuthPromises=new Map,AI.saveLocks=new Map,(0,y.cF)(Symbol("execHookConversationId"),void 0),(0,y.cF)(Symbol("execHookGenerationId"),void 0),(0,y.cF)(Symbol("execHookModel"),void 0);const $I=(0,y.cF)(Symbol("execHookWorkspaceRoots"),void 0);var MI=r("../proto/dist/generated/agent/v1/write_exec_pb.js"),DI=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},OI=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const FI=(0,u.Pu)("mcp.filesystem.divergence",{description:"Divergence detected between MCP lease state and filesystem state",labelNames:["divergence_type","mcp_source","configured_servers","mcp_version"]}),NI=(0,u.Pu)("mcp.filesystem.sync_check",{description:"MCP filesystem sync check executed",labelNames:["synced","mcp_source","configured_servers","mcp_version"]}),LI=(0,u.wt)("mcp.filesystem.sync_check.expected_servers",{description:"Number of expected MCP servers at last sync check",labelNames:["mcp_source","mcp_version"]}),jI=(0,u.wt)("mcp.filesystem.sync_check.actual_servers",{description:"Number of actual MCP servers on disk at last sync check",labelNames:["mcp_source","mcp_version"]}),UI=(0,u.wt)("mcp.filesystem.sync_check.servers_missing",{description:"Number of expected MCP servers missing from disk at last sync check",labelNames:["mcp_source","mcp_version"]}),BI=(0,u.wt)("mcp.filesystem.sync_check.tool_mismatches",{description:"Number of MCP servers with tool count mismatches at last sync check",labelNames:["mcp_source","mcp_version"]}),WI=(0,l.h)("McpFileSystemWriter"),HI="mcpFsStructuredLogOptIn";function qI(e,t){return t?.includeStructuredLogs?{...e??{},[HI]:!0}:e}const zI={debug(e,t,r,n){WI.debug(e,t,qI(r,n))},info(e,t,r,n){WI.info(e,t,qI(r,n))},warn(e,t,r,n){WI.warn(e,t,qI(r,n))},error(e,t,r,n,o){WI.error(e,t,r,qI(n,o))}},GI="mcps",VI="tools",KI="~staging",JI="~prev",ZI=[25,50,100,200],XI=new Set(["EPERM","EBUSY","EACCES"]),QI=new Map;function YI(e){return e.slice(0,e.indexOf("~"))}function eT(e,t){return`${e}~${Date.now()}-${process.pid}-${(0,bo.randomBytes)(4).toString("hex")}${t}`}const tT=/~(\d+)-\d+-[0-9a-f]+~(?:staging|prev)$/;async function rT(e,t){const r=tT.exec(t),n=r?Number(r[1]):0;try{const{mtimeMs:r}=await(0,Co.stat)((0,s.join)(e,t));return Date.now()-Math.max(n,r)>6e4}catch{return!1}}const nT="mcp_auth",oT="Authenticate this MCP server so its tools can be used. Call this tool through your MCP tool-calling interface when STATUS.md indicates this server needs authentication.",sT="# >>> CURSOR MANAGED BLOCK >>>",iT="# <<< CURSOR MANAGED BLOCK <<<",aT=["# Ignore everything in .cursor","*","# Un-ignore projects so we can descend to allowlisted subdirs","!projects/","projects/*","!projects/*/","projects/*/*","# MCP tool descriptors, resources, prompts","!projects/*/mcps/","!projects/*/mcps/**","# Agent transcripts for citation","!projects/*/agent-transcripts/","!projects/*/agent-transcripts/**","# Terminal output files","!projects/*/terminals/","!projects/*/terminals/**","# Conversation notes (shared scratchpad)","!projects/*/agent-notes/","!projects/*/agent-notes/**","# Large tool output files","!projects/*/agent-tools/","!projects/*/agent-tools/**","# Plugin cache (rules, skills, agents)","!plugins/","!plugins/**","# Built-in Cursor skills","!skills-cursor/","!skills-cursor/**","# User's personal skills","!skills/","!skills/**","# User's personal slash commands","!commands/","!commands/**","# User's plan files","!plans/","!plans/**","# Subagent state/transcripts","!subagents/","!subagents/**","# User-level cursor rules","!rules/","!rules/**"].join("\n");function cT(e,t,r=15e3){let n;return Promise.race([e.catch((()=>t)),new Promise((e=>{n=setTimeout((()=>e(t)),r)}))]).finally((()=>clearTimeout(n)))}function lT(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function uT(e){if(void 0===e)return;const t=e.trim();return t.length>0?t:void 0}function dT(e){switch(e.kind){case"loading":return"initializing";case"requires_authentication":return"needsAuth";case"ready":return"connected";case"error":return"error";default:return"disconnected"}}function hT(e){if(Array.isArray(e))return e.map((e=>hT(e)));if(function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e)){const t=Object.entries(e).filter((([,e])=>void 0!==e)).sort((([e],[t])=>et?1:0)).map((([e,t])=>[e,hT(t)]));return Object.fromEntries(t)}return e}function pT(e){return JSON.stringify(hT(e))}function fT(e){const t=e.map((e=>({value:e,key:pT(e)})));return t.sort(((e,t)=>e.keyt.key?1:0)),t.map((e=>e.value))}function mT(e){const t=fT(e.tools.map((e=>({name:e.toolName,description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema})))),r=fT(e.resources.map((e=>({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType})))),n=fT(e.prompts.map((e=>({name:e.name,description:e.description,arguments:e.arguments}))));return pT({id:e.serverIdentifier,name:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,tools:t,resources:r,prompts:n,instructions:e.instructions,status:e.status})}class gT{constructor(e,t,r){this.cachedFingerprints=new Map,this.disposed=!1,this.hasPendingLeaseChangeEvent=!1,this.lastDivergenceCheckMs=0,this.mcpLease=e,this.projectDir=t,this.debounceMs=r?.debounceMs??100,this.mcpAuthCopyOverrides=r?.mcpAuthCopyOverrides,this.exposeVirtualMcpAuthTool=r?.exposeVirtualMcpAuthTool??!0,this.alwaysExposeVirtualMcpAuthTool=r?.alwaysExposeVirtualMcpAuthTool??!1,this.snapshotProvider=r?.snapshotProvider,this.mcpVersion=r?.mcpVersion??(this.snapshotProvider?"snapshots":"v1"),this.onDidWrite=r?.onDidWrite,this.ctx=this.getContext(r?.loggerBackend),this.startupCleanupPromise=this.cleanupStaleStagingDirs(this.ctx),this.leaseChangeDisposable=this.mcpLease.onDidChange((e=>{zI.info(this.ctx,"Lease change event received",{serverIdentifiers:e?.serverIdentifiers,reason:e?.reason}),this.onLeaseChanged(this.ctx,e)})),zI.info(this.ctx,"Constructor: scheduling initial write"),this.scheduleWrite(this.ctx),this.ensureCursorDirGitignore()}ensureCursorDirGitignore(){(async function(e){const t=(0,s.join)(e,".gitignore"),r=`${sT}\n${aT}\n${iT}\n`;let n;await(0,Co.mkdir)(e,{recursive:!0});try{n=await(0,Co.readFile)(t,"utf-8")}catch(e){if("ENOENT"!==Sc(e))throw e}if(void 0===n)return void await(0,Co.writeFile)(t,r);const o=n.indexOf(sT),i=n.indexOf(iT,o+30);if(-1===o||-1===i)await(0,Co.writeFile)(t,r);else{const e=`${n.slice(0,o)}${r}${n.slice(i+30).replace(/^\n/,"")}`;e!==n&&await(0,Co.writeFile)(t,e)}})((0,s.join)((0,o.homedir)(),".cursor")).catch((e=>{zI.warn(this.ctx,"Failed to ensure ~/.cursor/.gitignore",e)}))}async cleanupStaleStagingDirs(e){const t=this.getLogContext(e),r=(0,s.join)(this.projectDir,GI);try{const e=await(0,Co.readdir)(r);await Promise.allSettled(e.filter((e=>e.endsWith(KI))).map((async e=>{await rT(r,e)&&await(0,Co.rm)((0,s.join)(r,e),{recursive:!0,force:!0})})))}catch(e){"ENOENT"!==Sc(e)&&zI.error(t,"Error clearing stale mcps staging dirs",e)}}onLeaseChanged(e,t){if(this.disposed)return;const r=t??{serverIdentifiers:void 0};this.hasPendingLeaseChangeEvent?this.pendingLeaseChangeEvent=function(...e){const[t,r]=e;return e.length<2?t:Qn(r)?{serverIdentifiers:void 0,reason:t?.reason??r?.reason}:void 0===t?r:Qn(t)?{serverIdentifiers:void 0,reason:t.reason??r?.reason}:{serverIdentifiers:[...new Set([...t.serverIdentifiers??[],...r?.serverIdentifiers??[]])],reason:t.reason??r?.reason}}(this.pendingLeaseChangeEvent??{serverIdentifiers:void 0},r):(this.pendingLeaseChangeEvent=r,this.hasPendingLeaseChangeEvent=!0),void 0!==this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout((()=>{this.debounceTimer=void 0;const t=this.takePendingLeaseChangeEvent();this.scheduleWrite(e,t)}),this.debounceMs)}takePendingLeaseChangeEvent(){if(!this.hasPendingLeaseChangeEvent)return;const e=this.pendingLeaseChangeEvent??{serverIdentifiers:void 0};return this.pendingLeaseChangeEvent=void 0,this.hasPendingLeaseChangeEvent=!1,e}scheduleWrite(e,t){const r=this.getLogContext(e);if(this.disposed)return;const n=this.writePromise;this.writePromise=(async()=>{if(n)try{await n}catch(e){zI.error(r,"Error waiting for previous write",e)}this.disposed||(await this.startupCleanupPromise,this.disposed||await this.fetchAndWrite(e,t))})()}getContext(e){let t=(0,y.q6)();return e&&(t=t.with(l._O,e)),t}getLogContext(e){return e.with(l._O,this.ctx.get(l._O))}getMetricTags(e){return{...e,mcp_version:this.mcpVersion}}getMcpAuthToolDescription(){return uT(this.mcpAuthCopyOverrides?.authToolDescription)??oT}shouldExposeVirtualMcpAuthToolForStatus(e,t){return this.exposeVirtualMcpAuthTool&&Vn(e)&&(this.alwaysExposeVirtualMcpAuthTool||"needsAuth"===t)}getErrorStatusMessage(){return uT(this.mcpAuthCopyOverrides?.errorStatusMessage)??"The MCP server errored. If this server is important for completing the task, concisely inform the user and ask them to check the MCP status in Cursor's Customize page > MCPs; otherwise continue with a different approach."}getNeedsAuthStatusMessage(e){return t=uT(this.mcpAuthCopyOverrides?.needsAuthStatusMessageWithAuthTool)??'The MCP server needs authentication. Authenticate it by calling the `{authToolName}` tool for server "{serverIdentifier}" through your MCP tool-calling interface using an empty arguments object. If this server is important for completing the task, authenticate it first; otherwise continue with a different approach.',r={serverIdentifier:e,authToolName:nT},t.replace(/\{serverIdentifier\}/g,r.serverIdentifier).replace(/\{authToolName\}/g,r.authToolName);var t,r}getNeedsAuthStatusMessageForWrite(e){return this.exposeVirtualMcpAuthTool&&Vn(e)?this.getNeedsAuthStatusMessage(e):uT(this.mcpAuthCopyOverrides?.needsAuthStatusMessageWithoutVirtualTool)??"This MCP server requires authentication before its tools can be used. Open Cursor's Customize page > MCPs, select this server, and use Authenticate/Reopen, or refresh credentials in your MCP configuration (for example mcp.json), then restart this environment. If this server is not required for the task, continue without it."}async getToolsForServers(e,t){if(0===t.length)return[];const r=this.getLogContext(e);try{return await this.mcpLease.getToolsForServers(e,t)}catch(n){zI.warn(r,`getToolsForServers() threw, falling back to filtered getTools(): ${kc(n)}`);const o=await this.mcpLease.getTools(e).catch((e=>(zI.warn(r,`getTools() threw during scoped-tool fallback, defaulting to []: ${e}`),[]))),s=new Set(t);return o.filter((e=>s.has(e.clientKey)))}}async fetchClientDataForServer(e,t,r,n){const o=await cT(r.getState(e),{kind:"error"}).then((r=>("error"!==r.kind||"message"in r||zI.warn(e,`getState() timed out for "${t}", defaulting to error`),r))),s="ready"===o.kind||"requires_authentication"===o.kind,[i,a,c]=await Promise.all([s?cT(r.listResources(e),{resources:[]}):Promise.resolve({resources:[]}),s?cT(r.listPrompts(e),[]):Promise.resolve([]),s&&n?.fetchInstructions?cT(r.getInstructions(e),void 0):Promise.resolve(void 0)]);return{clientKey:t,serverName:r.serverName,plugin:r.plugin,marketplace:r.marketplace,pluginId:r.pluginId,marketplaceId:r.marketplaceId,resources:i.resources.map((e=>({...e,serverIdentifier:t,serverName:r.serverName}))),prompts:a.map((e=>({...e,serverIdentifier:t,serverName:r.serverName}))),instructions:c,status:dT(o)}}buildServerDataMap(e,t,r){const n=new Map;for(const e of t){const t=My(e.clientKey);n.set(e.clientKey,{serverIdentifier:e.clientKey,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,sanitizedId:t,folderPath:(0,s.join)(this.projectDir,GI,t),tools:[],resources:e.resources,prompts:e.prompts,instructions:e.instructions,status:e.status})}for(const t of e){let e=n.get(t.clientKey);if(!e){const r=My(t.clientKey);e={serverIdentifier:t.clientKey,serverName:t.providerIdentifier,plugin:t.plugin,marketplace:t.marketplace,pluginId:t.pluginId,marketplaceId:t.marketplaceId,sanitizedId:r,folderPath:(0,s.join)(this.projectDir,GI,r),tools:[],resources:[],prompts:[],instructions:void 0,status:void 0},n.set(t.clientKey,e)}e.tools.push(t)}if(void 0!==r)for(const e of r){const t=e.serverIdentifier?.trim();let r=t?Array.from(n.values()).find((e=>e.serverIdentifier===t)):void 0;if(!r){const t=e.serverName?.trim();r=t?Array.from(n.values()).find((e=>e.serverName===t)):void 0}r&&e.instructions&&(r.instructions=e.instructions)}if(this.exposeVirtualMcpAuthTool)for(const e of n.values())this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&(e.tools.some((e=>e.toolName===nT))||e.tools.push({clientKey:(o={serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginId:e.pluginId,marketplaceId:e.marketplaceId,authToolDescription:this.getMcpAuthToolDescription()}).serverIdentifier,providerIdentifier:o.serverName,plugin:o.plugin,marketplace:o.marketplace,pluginId:o.pluginId,marketplaceId:o.marketplaceId,toolName:nT,name:nT,description:o.authToolDescription,inputSchema:{type:"object",properties:{},additionalProperties:!1}}));var o;return n}buildServersToWrite(e,t){const r=[],n=new Set;for(const o of t.values()){const t=o.tools.length>0||o.resources.length>0||o.prompts.length>0||o.instructions,s="error"===o.status||"needsAuth"===o.status||"initializing"===o.status;t||s?n.has(o.sanitizedId)?zI.warn(e,`Skipping server "${o.serverIdentifier}" — sanitizedId "${o.sanitizedId}" collides with another server`):(n.add(o.sanitizedId),r.push(o)):zI.info(e,`Server "${o.serverIdentifier}" excluded from write: tools=${o.tools.length}, resources=${o.resources.length}, prompts=${o.prompts.length}, hasInstructions=${!!o.instructions}, status=${o.status}`)}return r}mergeScopedRefreshWithCachedServerData(e,t){const r=[...t.tools];if(this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&!r.some((e=>e.toolName===nT))){const t=e.tools.find((e=>e.toolName===nT));void 0!==t&&r.push(t)}return{...e,...t,tools:r,resources:e.resources,prompts:e.prompts,instructions:e.instructions,status:e.status,plugin:t.plugin??e.plugin,marketplace:t.marketplace??e.marketplace,pluginId:t.pluginId??e.pluginId,marketplaceId:t.marketplaceId??e.marketplaceId}}async refreshServersFromLease(e,t){const r=this.getLogContext(e),n=[...new Set(t.serverIdentifiers??[])];zI.info(r,`fetchAndWrite: refreshing ${n.length} targeted servers`,{serverIdentifiers:n});const o=await this.getToolsForServers(e,n),s=await this.mcpLease.getInstructions(e).catch((e=>(zI.warn(r,`getInstructions() threw during scoped refresh, defaulting to []: ${e}`),[]))),i=await Promise.all(n.map((async t=>{try{const r=await this.mcpLease.getClient(e,t);return void 0===r?{serverIdentifier:t,kind:"missing"}:{serverIdentifier:t,kind:"client",client:r}}catch(e){return zI.warn(r,`getClient("${t}") threw during scoped refresh, preserving cached data: ${kc(e)}`),{serverIdentifier:t,kind:"error",error:e}}}))),a=i.filter((e=>"missing"===e.kind)).map((e=>e.serverIdentifier));let c=new Set;if(a.length>0){const t=await this.mcpLease.getClients(e).catch((e=>{zI.warn(r,`getClients() threw while confirming targeted server removal, preserving cached data: ${e}`)}));void 0!==t&&(c=new Set(a.filter((e=>void 0===t[e]))))}const l=await Promise.all(i.filter((e=>"client"===e.kind)).map((({serverIdentifier:t,client:r})=>this.fetchClientDataForServer(e,t,r,{fetchInstructions:!0})))),u=new Map((this.cachedServerData??[]).map((e=>[e.serverIdentifier,e]))),d=this.buildServerDataMap(o,l,s),h=new Set(n),p=new Set(i.filter((e=>"error"===e.kind||"missing"===e.kind&&!c.has(e.serverIdentifier))).map((e=>e.serverIdentifier)));for(const e of n){const t=u.get(e),n=d.get(e);if(void 0===n)c.has(e)?u.delete(e):zI.warn(r,`refreshServersFromLease: preserving cached data for "${e}" because targeted refresh returned no replacement`);else{if(p.has(e)&&void 0!==t){u.set(e,this.mergeScopedRefreshWithCachedServerData(t,n)),zI.warn(r,`refreshServersFromLease: preserving cached metadata for "${e}" because the client was unavailable during targeted refresh`);continue}u.set(e,n)}}const f=new Map(Array.from(u.values()).map((e=>[e.sanitizedId,e.serverIdentifier])));for(const[e,t]of this.cachedFingerprints)if(!h.has(e)&&!u.has(e)){const t=My(e);f.set(t,e)}const m=this.buildServersToWrite(e,u);await this.writeServerData(e,m,f),this.cachedServerData=m,this.fireOnDidWrite(m)}async fetchAndWrite(e,t){const r={stack:[],error:void 0,hasError:!1};try{DI(r,(0,$.VI)(e.withName("McpFileSystemWriter.fetchAndWrite")),!1);const n=this.getLogContext(e);try{if(void 0!==this.cachedServerData&&void 0!==t&&!Qn(t)&&[...new Set(t.serverIdentifiers??[])].length>0)return void await this.refreshServersFromLease(e,t);const[r,o,s]=await Promise.all([this.mcpLease.getTools(e).catch((e=>(zI.warn(n,`getTools() threw, defaulting to []: ${e}`),[]))),this.mcpLease.getInstructions(e).catch((()=>[])),this.mcpLease.getClients(e).catch((e=>(zI.warn(n,`getClients() threw, defaulting to {}: ${e}`),{})))]),i=Object.keys(s);zI.info(n,`fetchAndWrite: lease returned ${r.length} tools across ${i.length} clients`);const a=Object.entries(s).map((([t,r])=>this.fetchClientDataForServer(e,t,r))),c=await Promise.all(a),l=this.buildServerDataMap(r,c,o),u=this.buildServersToWrite(e,l),d=new Map(Array.from(l.values()).map((e=>[e.sanitizedId,e.serverIdentifier])));await this.writeServerData(e,u,d),this.cachedServerData=u,this.fireOnDidWrite(u)}catch(e){zI.error(n,"Error fetching/writing MCP state",e)}}catch(e){r.error=e,r.hasError=!0}finally{OI(r)}}fireOnDidWrite(e){if(this.onDidWrite)try{const t=e.map((e=>({serverIdentifier:e.serverIdentifier,folderPath:e.folderPath,tools:e.tools.map((t=>({toolName:t.toolName,definitionPath:(0,s.join)(e.folderPath,VI,`${lT(t.toolName)}.json`)})))})));this.onDidWrite(t)}catch{}}async writeServerData(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{DI(n,(0,$.VI)(e.withName("McpFileSystemWriter.writeServerData")),!1);const o=this.getLogContext(e),i=(0,s.join)(this.projectDir,GI);await(0,Co.mkdir)(i,{recursive:!0});const a=new Map;for(const e of t)try{a.set(e.serverIdentifier,mT(e))}catch(t){zI.error(o,"Error computing server fingerprint, will force write",t,{serverIdentifier:e.serverIdentifier}),a.set(e.serverIdentifier,`__error_${Date.now()}_${Math.random()}`)}const c=[];for(const e of t){const t=this.cachedFingerprints.get(e.serverIdentifier);t!==a.get(e.serverIdentifier)&&(c.push(e),void 0!==t&&zI.info(o,`Server "${e.serverIdentifier}" fingerprint changed: tools=${e.tools.length}, status=${e.status}`))}for(const e of t)if(!c.includes(e))try{await(0,Co.stat)((0,s.join)(i,e.sanitizedId))}catch{zI.info(o,`Server "${e.serverIdentifier}" directory missing on disk, forcing write`),c.push(e)}const l=new Set;for(const[e]of this.cachedFingerprints)if(!a.has(e)){const t=this.cachedServerData?.find((t=>t.serverIdentifier===e)),n=t?.sanitizedId??My(e);r.has(n)?(zI.info(o,`Server "${e}" (sanitized="${n}") still in lease but excluded from write, preserving directory`),a.set(e,this.cachedFingerprints.get(e))):(zI.info(o,`Server "${e}" (sanitized="${n}") left the lease, scheduling directory removal`),l.add(n))}const u=void 0===this.cachedServerData;if(u)try{const e=await(0,Co.readdir)(i),t=new Set(e.filter((e=>!e.endsWith(KI)&&!e.endsWith(JI))));for(const r of e){const e=r.endsWith(KI),n=r.endsWith(JI);if((e||n)&&await rT(i,r))if(e)await(0,Co.rm)((0,s.join)(i,r),{recursive:!0,force:!0});else{const e=YI(r);if(t.has(e))await(0,Co.rm)((0,s.join)(i,r),{recursive:!0,force:!0});else try{await(0,Co.rename)((0,s.join)(i,r),(0,s.join)(i,e)),t.add(e)}catch{await(0,Co.rm)((0,s.join)(i,r),{recursive:!0,force:!0}).catch((()=>{}))}}}for(const e of t)if(r.has(e)){const t=r.get(e);a.has(t)||a.set(t,`__preserved_${e}`)}else l.add(e)}catch(e){zI.error(o,"Error clearing mcps directory",e)}const d=Array.from(l);if(c.length>0||l.size>0){const e=c.map((e=>({serverIdentifier:e.serverIdentifier,sanitizedId:e.sanitizedId,toolCount:e.tools.length})));zI.info(o,`Incremental write: ${c.length} changed, ${l.size} removed, ${t.length-c.length} unchanged`,{changedServerCount:c.length,changedServers:e,removedServerCount:l.size,removedServerSanitizedIds:d,unchangedServerCount:t.length-c.length,totalServerCount:t.length,leaseServerCount:r.size,coldStartReconcile:u,projectDirHash:(0,bo.createHash)("sha256").update(this.projectDir).digest("hex")},{includeStructuredLogs:!0})}const h=await Promise.allSettled(c.map((t=>this.writeServerAtomic(e,t,i))));for(let t=0;t(0,Co.rm)((0,s.join)(i,e),{recursive:!0,force:!0}))));for(let r=0;r{await(i?.catch((()=>{}))),await this.swapServerDirectory(e,t,r)})();QI.set(o,a);try{await a}finally{QI.get(o)===a&&QI.delete(o)}}catch(e){n.error=e,n.hasError=!0}finally{OI(n)}}async swapServerDirectory(e,t,r){const n=eT(t.sanitizedId,KI),o=(0,s.join)(r,n),i=(0,s.join)(r,t.sanitizedId);try{await this.writeServerDirectory(e,t,{basePath:r,dirName:n})}catch(e){throw await(0,Co.rm)(o,{recursive:!0,force:!0}).catch((()=>{})),e}const a=(0,s.join)(r,eT(t.sanitizedId,JI));let c=!1;try{try{await this.renameWithRetry(i,a),c=!0}catch(e){if("ENOENT"!==Sc(e))throw e}await this.renameWithRetry(o,i)}catch(r){if(zI.error(e,"Per-server swap failed",r,{serverIdentifier:t.serverIdentifier,sanitizedId:t.sanitizedId},{includeStructuredLogs:!0}),c)try{await this.renameWithRetry(a,i)}catch{await(0,Co.stat)(i).then((()=>!0),(()=>!1))&&await(0,Co.rm)(a,{recursive:!0,force:!0}).catch((()=>{}))}throw await(0,Co.rm)(o,{recursive:!0,force:!0}).catch((()=>{})),r}await(0,Co.rm)(a,{recursive:!0,force:!0}).catch((()=>{}))}async renameWithRetry(e,t){for(let r=0;;r++)try{return void await(0,Co.rename)(e,t)}catch(e){const t=Sc(e);if(r>=ZI.length||void 0===t||!XI.has(t))throw e;await(0,Or.cb)(ZI[r])}}async writeServerDirectory(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{DI(n,(0,$.VI)(e.withName("McpFileSystemWriter.writeServerDirectory")),!1);const o=(0,s.join)(r.basePath,r.dirName??t.sanitizedId);await(0,Co.mkdir)(o,{recursive:!0});const i=[];if(t.tools.length>0){const e=(0,s.join)(o,VI);await(0,Co.mkdir)(e,{recursive:!0});for(const r of t.tools){const t=lT(r.toolName);i.push({path:(0,s.join)(e,`${t}.json`),content:JSON.stringify(Zn(r),null,2)})}}if(t.resources.length>0){const e=(0,s.join)(o,"resources");await(0,Co.mkdir)(e,{recursive:!0});for(const r of t.resources){const t=lT(r.name||r.uri.replace(/[^a-zA-Z0-9_-]/g,"_")),n={uri:r.uri,name:r.name,description:r.description,mimeType:r.mimeType};i.push({path:(0,s.join)(e,`${t}.json`),content:JSON.stringify(n,null,2)})}}if(t.prompts.length>0){const e=(0,s.join)(o,"prompts");await(0,Co.mkdir)(e,{recursive:!0});for(const r of t.prompts){const t=lT(r.name),n={name:r.name,description:r.description,arguments:r.arguments};i.push({path:(0,s.join)(e,`${t}.json`),content:JSON.stringify(n,null,2)})}}t.instructions&&t.instructions.trim().length>0&&i.push({path:(0,s.join)(o,"INSTRUCTIONS.md"),content:t.instructions.trim()}),"error"!==t.status&&"needsAuth"!==t.status||i.push({path:(0,s.join)(o,"STATUS.md"),content:"error"===t.status?this.getErrorStatusMessage():this.getNeedsAuthStatusMessageForWrite(t.serverIdentifier)});const a={serverIdentifier:t.serverIdentifier,serverName:t.serverName};i.push({path:(0,s.join)(o,"SERVER_METADATA.json"),content:JSON.stringify(a,null,2)});if(new Set(i.map((e=>e.path.toLowerCase()))).size!==i.length){for(const e of i)await(0,Co.writeFile)(e.path,e.content);return}const c=(await(0,Or.up)(i,(e=>(0,Co.writeFile)(e.path,e.content)),{max:8})).find((e=>"rejected"===e.status));if(c)throw c.reason}catch(e){n.error=e,n.hasError=!0}finally{OI(n)}}async getMcpFileSystemOptions(e,t){const r={stack:[],error:void 0,hasError:!1};try{if(this.disposed)return;DI(r,(0,$.VI)(e.withName("McpFileSystemWriter.getMcpFileSystemOptions")),!1);const n=this.getLogContext(e),o=await this.ensureWritesSettled(e,t?.timeoutMs);if(this.snapshotProvider&&!o)return this.buildOptionsFromSnapshots(e);this.snapshotProvider&&o&&zI.warn(n,"Snapshot mode write barrier timed out; falling back to cached descriptors",{timeoutMs:t?.timeoutMs},{includeStructuredLogs:!0});const i=(this.cachedServerData??[]).map((e=>{const t=e.tools.map((t=>{const r=lT(t.toolName),n=(0,s.join)(e.folderPath,VI,`${r}.json`);return new wn.E$({toolName:t.toolName,definitionPath:n,...Db(t.annotations)})}));return new wn.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,folderPath:e.folderPath,serverUseInstructions:e.instructions,tools:t})}));return this.checkDescriptorsVsFilesystem(e,i,"workbench_lease"),new wn.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:i})}catch(e){r.error=e,r.hasError=!0}finally{OI(r)}}async ensureWritesSettled(e,t){const r=this.getLogContext(e),n=void 0!==this.debounceTimer;if(void 0!==this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0,this.scheduleWrite(e,this.takePendingLeaseChangeEvent())),n&&zI.info(r,"getMcpFileSystemOptions force-fired pending debounce"),!this.writePromise)return!1;if(void 0!==t){let e,n=!1;try{await Promise.race([this.writePromise,new Promise((r=>{e=setTimeout((()=>{n=!0,r()}),t)}))])}catch(e){zI.error(r,"Error waiting for pending write to complete",e)}finally{clearTimeout(e)}return n&&zI.warn(r,`getMcpFileSystemOptions timed out after ${t}ms waiting for write; returning stale cache`),n}try{await this.writePromise}catch(e){zI.error(r,"Error waiting for pending write to complete",e)}return!1}async buildOptionsFromSnapshots(e){const t={stack:[],error:void 0,hasError:!1};try{DI(t,(0,$.VI)(e.withName("McpFileSystemWriter.buildOptionsFromSnapshots")),!1);const r=this.getLogContext(e),n=Date.now(),o=await this.snapshotProvider.getAllSnapshots(e),i=(0,s.join)(this.projectDir,GI),a=o.filter((e=>e.tools.length>0||e.resources.length>0||e.prompts.length>0||void 0!==e.instructions||this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)||"needsAuth"===e.status||"error"===e.status)).map((e=>{const t=My(e.serverIdentifier),r=(0,s.join)(i,t),n=e.tools.map((e=>{const t=lT(e.name);return new wn.E$({toolName:e.name,definitionPath:(0,s.join)(r,VI,`${t}.json`),...Db(e.annotations)})}));if(this.shouldExposeVirtualMcpAuthToolForStatus(e.serverIdentifier,e.status)&&!e.tools.some((e=>e.name===nT))){const e=lT(nT);n.push(new wn.E$({toolName:nT,definitionPath:(0,s.join)(r,VI,`${e}.json`)}))}return new wn.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,folderPath:r,serverUseInstructions:e.instructions,tools:n})})),c=a.reduce(((e,t)=>e+t.tools.length),0);return zI.info(r,`buildOptionsFromSnapshots completed in ${Date.now()-n}ms: ${o.length} snapshots, ${a.length} descriptors, ${c} tools`),this.checkDescriptorsVsFilesystem(e,a,"snapshot"),new wn.Is({enabled:!0,workspaceProjectDir:this.projectDir,mcpDescriptors:a})}catch(e){t.error=e,t.hasError=!0}finally{OI(t)}}async waitForPendingWrites(){if(void 0!==this.debounceTimer&&await new Promise((e=>{const t=()=>{void 0===this.debounceTimer?e():setTimeout(t,10)};t()})),this.writePromise)try{await this.writePromise}catch{}}getCachedServerData(){return this.cachedServerData}checkDescriptorsVsFilesystem(e,t,r){const n=this.getLogContext(e),o=Date.now();o-this.lastDivergenceCheckMs{zI.warn(n,"Divergence check failed",e)})))}async _checkDescriptorsVsFilesystemAsync(e,t,r){const n=this.getLogContext(e),o=(0,s.join)(this.projectDir,GI),i=new Set,a=new Map;for(const e of t){const t=My(e.serverIdentifier);i.add(t),a.set(t,e.tools.length)}let c=[];try{c=await(0,Co.readdir)(o),c=c.filter((e=>!e.endsWith(KI)&&!e.endsWith(JI)))}catch(e){if("ENOENT"!==Sc(e))throw e}const l=new Set(c);let u=!0,d=0,h=0,p=0;const f=function(e){return 0===e?"0":e<=3?"1-3":e<=6?"4-6":e<=10?"7-10":"11+"}(i.size);for(const t of i)l.has(t)||(u=!1,d++,FI.increment(e,1,this.getMetricTags({divergence_type:"server_missing",mcp_source:r,configured_servers:f})),zI.warn(n,"Divergence detected: server missing from filesystem",{mcpFileSystemMeta:{divergenceType:"server_missing",serverId:t,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}));for(const t of l)i.has(t)||(u=!1,h++,FI.increment(e,1,this.getMetricTags({divergence_type:"server_stale",mcp_source:r,configured_servers:f})));for(const t of i){if(!l.has(t))continue;const c=a.get(t)??0,d=(0,s.join)(o,t,VI);let h=0;try{h=(await(0,Co.readdir)(d)).filter((e=>e.endsWith(".json"))).length}catch{}h!==c&&(u=!1,p++,FI.increment(e,1,this.getMetricTags({divergence_type:"tool_count_mismatch",mcp_source:r,configured_servers:f})),zI.warn(n,"Divergence detected: tool count mismatch",{mcpFileSystemMeta:{divergenceType:"tool_count_mismatch",serverId:t,expected:c,actual:h,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}))}NI.increment(e,1,this.getMetricTags({synced:String(u),mcp_source:r,configured_servers:f})),LI.gauge(e,i.size,this.getMetricTags({mcp_source:r})),jI.gauge(e,l.size,this.getMetricTags({mcp_source:r})),UI.gauge(e,d,this.getMetricTags({mcp_source:r})),BI.gauge(e,p,this.getMetricTags({mcp_source:r})),zI.info(n,"MCP filesystem sync check",{mcpFileSystemMeta:{synced:u,expectedServers:i.size,actualServers:l.size,serversMissing:d,serversStale:h,toolMismatches:p,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0}),u||zI.warn(n,"MCP filesystem divergence summary",{mcpFileSystemMeta:{synced:u,expectedServers:i.size,actualServers:l.size,serversMissing:d,serversStale:h,toolMismatches:p,source:r,configuredServers:i.size,configuredServersBucket:f}},{includeStructuredLogs:!0})}dispose(){this.disposed||(this.disposed=!0,void 0!==this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.leaseChangeDisposable&&(this.leaseChangeDisposable.dispose(),this.leaseChangeDisposable=void 0),this.cachedServerData=void 0,this.cachedFingerprints.clear())}}gT.DIVERGENCE_CHECK_COOLDOWN_MS=1e4;var wT=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},yT=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function vT(e){if("object"!=typeof e||null===e||Array.isArray(e))return;const t={};for(const[r,n]of Object.entries(e))"string"==typeof n&&(t[r]=n);return t}const bT=(0,l.h)("local-exec:mcp");function ST(e,t){const r=s.default.relative(e,t);return""===r||!s.default.isAbsolute(r)&&".."!==r&&!r.startsWith(`..${s.default.sep}`)}function kT(e){return e instanceof Error&&"code"in e&&"string"==typeof e.code?e.code:void 0}function _T(e){return new Ac._Z({content:{case:"image",value:new Ac.do({data:e.data,mimeType:e.mimeType})}})}function CT(e){return new Ac._Z({content:{case:"text",value:new Ac.zN({text:e})}})}async function ET(e,t,r){const n=await r.permissionsService.shouldBlockMcp(e,t,r.toolDef,{alreadyApproved:t.skipApproval,...void 0===r.client?{}:{client:r.client},...void 0===r.resolvedTool?{}:{resolvedTool:r.resolvedTool}});if(!n)return;const o=await Qu(n,{onNeedsApproval:async(e,n)=>{if("mcp"!==n.type)return new Ac.iz({result:{case:"error",value:new Ac.Nh({error:"Invalid approval details type for MCP execution"})}});const o=await r.pendingDecisionProvider.requestApproval({type:Lw.Mcp,details:{name:n.name,toolName:n.toolName,toolTitle:n.toolTitle,destructiveHint:n.destructiveHint,providerIdentifier:n.providerIdentifier,source:r.toolDef?.source,args:n.args,reason:n.reason??e,canAllowlist:n.canAllowlist,smartModeApprovalReason:n.smartModeApprovalReason,smartModeApprovalRequestId:n.smartModeApprovalRequestId,allowlistEntry:n.allowlistEntry,computerUseApp:n.computerUseApp},toolCallId:t.toolCallId});return o.approved&&void 0!==n.computerUseApp&&!0!==n.computerUseApp.allowOnce&&r.permissionsService.allowComputerUseAppForSession?.({bundleId:n.computerUseApp.bundleId}),o.approved?t.smartModeApprovalOnly?new Ac.iz({result:{case:"approved",value:new Ac.Ke}}):null:new Ac.iz({result:{case:"rejected",value:new Ac.xo({reason:`User rejected MCP: ${t.name}${o.reason?` - ${o.reason}`:""}`})}})},onUserRejected:e=>new Ac.iz({result:{case:"error",value:new Ac.Nh({error:`User rejected MCP: ${t.name}${e?` - ${e}`:""}`})}}),onPermissionDenied:(e,r)=>xT({name:t.name,reason:e,isReadonly:r?.isReadonly??!1})});return o??void 0}function xT({name:e,reason:t,isReadonly:r}){return new Ac.iz({result:{case:"permissionDenied",value:new Ac.HQ({error:`MCP tool execution blocked: ${e} - ${t}`,isReadonly:r})}})}class PT{constructor(e,t,r,n,o=4e4,s,i,a={}){this.toolSet=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.projectDir=n,this.fileOutputThresholdBytes=o,this.elicitationFactory=s,this.ensureMcpServersLoaded=i,this.spillOptions=a}async describeDisconnectedServer(e,t){const r=new Set(t.filter((e=>""!==e)));if(0===r.size)return;let n;try{n=await this.toolSet.getClients(e)}catch{return}const o=Object.entries(n).find((([e,t])=>r.has(e)||r.has(t.serverName)));if(void 0===o)return;const[s,i]=o;let a;try{a=await i.getState(e)}catch{return}if("ready"===a.kind&&void 0===a.toolListError)return;const c=function(e){switch(e){case"needsAuth":return"This MCP server requires authentication before its tools can be used.";case"error":return"This MCP server failed during live tool discovery. Its tools are unavailable until the connection is fixed.";case"loading":return"This MCP server is still loading; tools may not be available yet.";default:return}}(Yn(a));return void 0!==c?`MCP server "${s}" has no callable tools right now. ${c}${"error"===a.kind&&a.message?` (${a.message})`:""}`:void 0}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const o=wT(r,(0,$.VI)(e.withName("LocalMcpToolExecutor.execute")),!1).ctx,i=t.serverIdentifier||t.providerIdentifier;await(this.ensureMcpServersLoaded?.(o,[i]));const a=await this.toolSet.getTools(o),c=Array.from(new Set(a.map((e=>e.clientKey)))).sort(),l=a.find((e=>e.clientKey===i&&e.toolName===t.toolName)),u=a.find((e=>e.name===t.name));if(void 0!==u&&(void 0!==l?u!==l:u.toolName!==t.toolName||u.clientKey!==i&&u.providerIdentifier!==i))return new Ac.iz({result:{case:"error",value:new Ac.Nh({error:`MCP tool "${t.name}" is not the tool "${t.toolName}" on server "${i}" that the call names.`})}});const d=void 0===l?void 0:await this.toolSet.getClient(o,l.clientKey).catch((()=>{})),h=l??u,p=void 0===h?void 0:h===l?d:await this.toolSet.getClient(o,h.clientKey).catch((()=>{})),f=await ET(o,t,{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionProvider,toolDef:l,...void 0===d?{}:{client:d},...void 0===h?{}:{resolvedTool:void 0===p?"unresolved":{client:p,annotations:h.annotations}}});if(void 0!==f)return f;const m=await this.toolSet.getToolSet(o),g=!0===await(this.permissionsService.enforcesMcpAdminToolLimits?.());let w;try{if(g&&void 0===h)throw new vC(t.name,a.map((e=>e.name)));const e=l?.name??t.name,r=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()])));if(g){const n=void 0===p?void 0:await(m.executeOn?.(p,e,r,t.toolCallId,this.elicitationFactory));if(void 0===n)return bT.warn(o,"Refusing an MCP tool whose client was not judged",{toolName:t.toolName,toolSetNamesClients:void 0!==m.executeOn}),xT({name:t.name,reason:nk,isReadonly:!1});w=n}else w=await m.execute(e,r,t.toolCallId,this.elicitationFactory)}catch(e){let r=e;if(bC(r)&&t.providerIdentifier.length>0&&!a.some((e=>e.clientKey===t.providerIdentifier||e.providerIdentifier===t.providerIdentifier))&&(r=new YR(t.providerIdentifier,c)),r instanceof YR){const e=await this.describeDisconnectedServer(o,[i,t.providerIdentifier]);return void 0!==e?new Ac.iz({result:{case:"error",value:new Ac.Nh({error:e})}}):new Ac.iz({result:{case:"serverNotFound",value:new Ac.JL({name:r.serverName,availableServers:r.availableServers})}})}if(bC(r))return new Ac.iz({result:{case:"toolNotFound",value:new Ac.WV({name:r.toolName,availableTools:r.availableTools})}});throw r}const y=[];for(const e of w.content){const r=e.type;if("text"===r&&"object"==typeof e&&null!==e&&"text"in e&&"string"==typeof e.text)y.push(CT(e.text));else if("resource"===r){const r=oE(e),n=void 0===r?void 0:Buffer.from(r,"base64"),s=void 0===n?void 0:await Lv(n).then(_T,(e=>{bT.warn(o,"Describing an undecodable MCP resource image",{toolName:t.toolName,bytes:n.byteLength,error:e instanceof Error?e.message:String(e)})}));y.push(s??CT(sE(e)))}else if("image"===r){const r=e,s="string"==typeof r.data?Buffer.from(r.data,"base64"):Buffer.alloc(0);let i;try{i=await Lv(s)}catch(e){bT.warn(o,"Omitting undecodable MCP tool image",{toolName:t.toolName,mimeType:"string"==typeof r.mimeType?r.mimeType.slice(0,100):typeof r.mimeType,bytes:s.byteLength,error:e instanceof Error?e.message:String(e)}),y.push(CT(`[Image omitted: the tool returned ${n=r.mimeType,"string"==typeof n&&/^image\/[\w.+-]{1,40}$/.test(n)?n:"image"} data (${s.byteLength} bytes) that could not be decoded.]`));continue}y.push(_T(i))}else if("image"!==r){const t=sE(e);y.push(CT(t))}}const v=await async function({contentItems:e,thresholdBytes:t,write:r}){const n=e.filter((e=>"text"===e.content.case&&void 0===e.content.value.outputLocation)).map((e=>"text"===e.content.case?e.content.value.text:"")).join("\n\n");if(t<=0||Buffer.byteLength(n,"utf8")<=t)return e;const o=await r(n);if(void 0===o)return;const s=[];let i=!1;for(const t of e)"text"===t.content.case&&void 0===t.content.value.outputLocation?i||(s.push(new Ac._Z({content:{case:"text",value:new Ac.zN({text:"",outputLocation:o})}})),i=!0):s.push(t);return s}({contentItems:y,thresholdBytes:this.fileOutputThresholdBytes,write:e=>async function(e,t,r){const n=s.default.join(t,$c),o=s.default.join(n,`${(0,bo.randomUUID)()}.txt`);await(0,Co.mkdir)(s.default.dirname(o),{recursive:!0});const i=Vo(!0===r.blankSharedPaymentTokens?QE(e):e,Mc),a=Js(i),c=Buffer.byteLength(i,"utf8");return await(0,Co.writeFile)(o,i,"utf8"),new Dc.pV({filePath:o,sizeBytes:BigInt(c),lineCount:BigInt(a)})}(e,this.projectDir,this.spillOptions)});if(void 0===v)throw new Error("Failed to materialize MCP text output");const b=w.structuredContent&&"object"==typeof w.structuredContent&&!Array.isArray(w.structuredContent)?we.Struct.fromJson(w.structuredContent):void 0,S=new Ac.QW({content:v,isError:w.isError,structuredContent:b,resultMeta:void 0===w._meta?void 0:we.Struct.fromJson(w._meta)});return new Ac.iz({result:{case:"success",value:S}})}catch(e){r.error=e,r.hasError=!0}finally{yT(r)}var n}}class RT{constructor(e,t){this.mcpLease=e,this.ensureMcpServersLoaded=t}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=wT(r,(0,$.VI)(e.withName("LocalListMcpResourcesExecutor.execute")),!1).ctx;try{if(t.server){await(this.ensureMcpServersLoaded?.(n,[t.server]));const e=await this.mcpLease.getClients(n),r=e[t.server]??Object.values(e).find((e=>e.serverName===t.server));if(!r)return new Ac.kP({result:{case:"error",value:new Ac.w2({error:`Server "${t.server}" not found`})}});const o=await this.listResourcesFromClient(n,r,t.server,!0);return new Ac.kP({result:{case:"success",value:new Ac.T2({resources:o})}})}const e=await this.mcpLease.getClients(n),r=new Set,o=await this.mcpLease.getTools(n);for(const e of o)r.add(e.providerIdentifier),r.add(`user-${e.providerIdentifier}`);const s=[];for(const[t,o]of Object.entries(e)){if(r.size>0&&!r.has(t))continue;const e=await this.listResourcesFromClient(n,o,t);s.push(...e)}return new Ac.kP({result:{case:"success",value:new Ac.T2({resources:s})}})}catch(e){const t=e instanceof Error?e.message:String(e);return new Ac.kP({result:{case:"error",value:new Ac.w2({error:`Failed to list MCP resources: ${t}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{yT(r)}}async listResourcesFromClient(e,t,r,n=!1){const o=await t.getState(e);if("ready"!==o.kind&&(!n||"loading"!==o.kind))return[];const s=await t.listResources(e);return s&&s.resources?s.resources.map((e=>new Ac.X2({uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType,server:r,annotations:vT(e.annotations)}))):[]}}class IT{constructor(e,t=".",r,n=[],o,s,i){this.mcpLease=e,this.projectDir=t,this.pendingDecisionProvider=o,this.ensureMcpServersLoaded=s,this.writeExecutor=i,this.workspacePaths=n.filter((e=>e.length>0))}resolveProjectDir(e){const t=e.get($I),r=t?.find((e=>"string"==typeof e&&e.length>0));return r||(this.workspacePaths.length>0?this.workspacePaths[0]:this.projectDir)}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=wT(r,(0,$.VI)(e.withName("LocalReadMcpResourceExecutor.execute")),!1).ctx,o=t.smartModeApproval?.reason;if(void 0!==o){if(void 0===this.pendingDecisionProvider)return new Ac.ZD({result:{case:"error",value:new Ac.Jx({uri:t.uri,error:"Auto-review approval provider is not configured"})}});const e=await this.pendingDecisionProvider.requestApproval({type:Lw.Mcp,details:{name:"FetchMcpResource",toolName:"FetchMcpResource",providerIdentifier:t.server,args:{server:we.Value.fromJson(t.server),uri:we.Value.fromJson(t.uri),...void 0!==t.downloadPath?{downloadPath:we.Value.fromJson(t.downloadPath)}:{}},reason:"smartMode",canAllowlist:!1,smartModeApprovalReason:o,smartModeApprovalRequestId:t.smartModeApproval?.requestId},toolCallId:t.toolCallId});if(!e.approved)return new Ac.ZD({result:{case:"rejected",value:new Ac.Dh({reason:"User rejected MCP resource fetch"+(e.reason?` - ${e.reason}`:"")})}})}await(this.ensureMcpServersLoaded?.(n,[t.server]));const i=await this.mcpLease.getClients(n),a=i[t.server]??Object.values(i).find((e=>e.serverName===t.server));if(!a)return new Ac.ZD({result:{case:"error",value:new Ac.Jx({uri:t.uri,error:`Server "${t.server}" not found`})}});try{if("ready"!==(await a.getState(n)).kind)return new Ac.ZD({result:{case:"error",value:new Ac.Jx({uri:t.uri,error:`Server "${t.server}" is not ready`})}});const e=await a.readResource(n,{uri:t.uri});if(!e||!e.contents||0===e.contents.length)return new Ac.ZD({result:{case:"notFound",value:new Ac.ov({uri:t.uri})}});const r=e.contents[0];if(t.downloadPath){const e=await async function(e,t){const r=s.default.resolve(e),n=await(0,Co.realpath)(r),o=s.default.isAbsolute(t)?s.default.resolve(t):s.default.resolve(r,t),i=ST(r,o),a=s.default.isAbsolute(t)&&ST(n,o);if(!i&&!a)throw new Error("downloadPath must stay within the workspace");let c=s.default.dirname(o);for(;;)try{if(!ST(n,await(0,Co.realpath)(c)))throw new Error("downloadPath must stay within the workspace");break}catch(e){if("ENOENT"!==kT(e))throw e;const t=s.default.dirname(c);if(t===c)throw e;c=t}try{if((await(0,Co.lstat)(o)).isSymbolicLink())throw new Error("downloadPath must stay within the workspace")}catch(e){if("ENOENT"!==kT(e))throw e}return o}(this.resolveProjectDir(n),t.downloadPath);let o=e;if(r.text||r.blob){if(void 0===this.writeExecutor)throw new Error("File-write executor is not configured");const s=await this.writeExecutor.execute(n,new MI.hY({path:e,fileText:r.text??"",fileBytes:r.text||void 0===r.blob?new Uint8Array:new Uint8Array(Buffer.from(r.blob,"base64")),toolCallId:t.toolCallId,confineToWorkspace:!0}));if("rejected"===s.result.case)return new Ac.ZD({result:{case:"rejected",value:new Ac.Dh({uri:t.uri,reason:s.result.value.reason})}});if("success"!==s.result.case)return new Ac.ZD({result:{case:"error",value:new Ac.Jx({uri:t.uri,error:TT(s)})}});o=s.result.value.path}return new Ac.ZD({result:{case:"success",value:new Ac.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,downloadPath:o})}})}if(r.text)return new Ac.ZD({result:{case:"success",value:new Ac.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:vT(r.annotations),metaJson:Jn(r._meta),content:{case:"text",value:r.text}})}});if(r.blob){const e=Buffer.from(r.blob,"base64");return new Ac.ZD({result:{case:"success",value:new Ac.KZ({uri:t.uri,name:r.name,description:r.description,mimeType:r.mimeType,annotations:vT(r.annotations),metaJson:Jn(r._meta),content:{case:"blob",value:e}})}})}return new Ac.ZD({result:{case:"error",value:new Ac.Jx({uri:t.uri,error:"Failed to read resource"})}})}catch(e){const r=e instanceof Error?e.message:String(e);return bT.warn(n,"LocalReadMcpResourceExecutor.execute failed",{server:t.server,hasDownloadPath:Boolean(t.downloadPath),errorName:e instanceof Error?e.name:typeof e,errorMessage:r}),new Ac.ZD({result:{case:"error",value:new Ac.Jx({uri:t.uri,error:`Failed to read MCP resource: ${r}`})}})}}catch(e){r.error=e,r.hasError=!0}finally{yT(r)}}}function TT(e){switch(e.result.case){case"error":return e.result.value.error;case"permissionDenied":return e.result.value.error||"Permission denied";case"noSpace":return"No space left on device";case"rejected":return e.result.value.reason||"Write rejected";case"success":return"";case void 0:return"Write executor returned result without case";default:{const t=e.result;return String(t)}}}var AT=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const $T=1e4,MT=5e3,DT={PAGER:"cat",MANPAGER:"cat",LESS:"-R",PIP_PROGRESS_BAR:"off",TQDM_DISABLE:"1"};class OT{constructor(){this.fullOutput="",this.outputHead="",this.outputTail="",this.totalChars=0}append(e){if(0===e.length)return;const t=this.totalChars;if(this.totalChars+=e.length,t$T&&(this.fullOutput="")}getOutput(){return this.totalChars<=$T?this.fullOutput:void 0}getTruncation(){if(!(this.totalChars<=$T))return{outputHead:this.outputHead,outputTail:this.outputTail,elidedChars:this.totalChars-this.outputHead.length-this.outputTail.length}}}class FT{constructor(){this.kept="",this.full=!1}append(e){if(this.full)return;const t=rs-this.kept.length;this.full=e.length>=t,this.kept+=Vo(e,t)}get text(){return this.kept}}function NT(e,t){return null!==e?e:null===t?-1:-o.constants.signals[t]}class LT{constructor(e,t,r){this.permissionsService=e,this.ignoreService=t,this.defaultCwd=r}buildResult({args:e,workingDirectory:t,processResult:r,sandboxPolicy:n}){const o={command:e.command,workingDirectory:t,exitCode:r.returncode,signal:r.signal,stdout:r.stdout,stderr:r.exceptionInfo||r.stderr,interleavedOutput:r.output,outputHead:r.outputTruncation?.outputHead,outputTail:r.outputTruncation?.outputTail,elidedChars:r.outputTruncation?.elidedChars,executionTime:r.localExecutionTimeMs??0,localExecutionTimeMs:r.localExecutionTimeMs},s=r.exceptionInfo.length>0,i=0!==r.returncode||s?{case:"failure",value:new he.xC({...o,aborted:s,abortReason:r.abortReason})}:{case:"success",value:new he.QR(o)};return new he.W4({result:i,sandboxPolicy:us(n)})}async runProcess({ctx:e,args:t,workingDirectory:r,sandboxPolicy:n,timeoutMs:o}){const s=performance.now(),i=this.defaultCwd,a=(await(0,Oo.resolveSandboxPolicyForWorkspace)(i,n?{perUser:n}:void 0)).policy,c="insecure_none"!==a.type?{...a,sandboxWorkspaceRoot:i}:a;return await new Promise((n=>{const i=new OT,a=new FT,l=new FT;let u,d,h=!1,p=!1,f="",m=()=>{};const g=(0,Oo.Qw)((0,Oo.ue)((0,Oo.Xw)({...process.env,...DT,CURSOR_AGENT:"1"}))),w={cwd:r,env:g,stdio:["pipe","pipe","pipe"],detached:"win32"!==process.platform,windowsVerbatimArguments:"win32"===process.platform},y="win32"===process.platform?{executable:process.env.ComSpec??"cmd.exe",args:(v=t.command,["/d","/s","/c",`"${v}"`])}:{executable:"/bin/sh",args:["-c",t.command]};var v;const b="insecure_none"===c.type?(0,su.D9)(ou.spawn,y.executable,y.args,w):(0,Oo.spawnInSandbox)(y.executable,y.args,w,c);b.stdin?.end();const S=e=>{h||(h=!0,clearTimeout(d),m(),n({...e,output:i.getOutput(),outputTruncation:i.getTruncation(),localExecutionTimeMs:$y(performance.now()-s)}))};d=setTimeout((()=>{if(p=!0,void 0===u&&(f=`An error occurred while executing the command: Command timed out after ${o}ms`,u=he.Lv.TIMEOUT,m()),void 0!==b.pid&&"win32"!==process.platform)try{return void process.kill(-b.pid,"SIGKILL")}catch{}b.kill("SIGKILL")}),o);const k=()=>{if(void 0===u){if(f="An error occurred while executing the command: Command aborted",u=he.Lv.USER_ABORT,void 0!==b.pid&&"win32"!==process.platform)try{return void process.kill(-b.pid,"SIGTERM")}catch{}b.kill("SIGTERM")}};e.signal.aborted?k():(e.signal.addEventListener("abort",k,{once:!0}),m=()=>{e.signal.removeEventListener("abort",k)}),b.stdout?.setEncoding("utf8"),b.stdout?.on("data",(e=>{a.append(e),i.append(e)})),b.stderr?.setEncoding("utf8"),b.stderr?.on("data",(e=>{l.append(e),i.append(e)})),b.on("error",(e=>{S({stdout:a.text,stderr:l.text,returncode:-1,signal:"",exceptionInfo:`An error occurred while executing the command: ${e.message}`})})),b.on("close",((e,t)=>{S({stdout:a.text,stderr:l.text,returncode:f.length>0?-1:NT(e,t),signal:t??(p?"SIGKILL":""),exceptionInfo:f,abortReason:u})}))}))}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,$.VI)(e.withName("LocalMiniSweAgentBashExecutor.execute")),!1).ctx;(0,$.HF)(n,"LocalMiniSweAgentBashExecutor.execute");const o=t.command,s=(0,Yo.o1)(t.workingDirectory||this.defaultCwd),i=t.timeout>0?t.timeout:3e4;if(!t.parsingResult)return new he.W4({result:{case:"spawnError",value:new he.mJ({command:o,workingDirectory:s,error:"Parsing result is required"})}});let a=t.requestedSandboxPolicy?ls(t.requestedSandboxPolicy):void 0;const c=await this.permissionsService.shouldBlockShellCommand(n,o,{workingDirectory:s,timeout:i,parsingResult:t.parsingResult,toolCallId:t.toolCallId},a);if("block"===c.kind)return"permissionsConfig"===c.reason.type&&c.reason.isReadonly?new he.W4({result:{case:"permissionDenied",value:new he.jn({command:o,workingDirectory:s,error:"Command blocked by permissions configuration",isReadonly:!0})}}):new he.W4({result:{case:"rejected",value:new he.pZ({command:o,workingDirectory:s,reason:Yu(c.reason)})}});a=c.policy,$s()&&(a=Ls(o,t.parsingResult)),a&&"insecure_none"!==a.type&&(a={...a,ignoreMapping:await this.ignoreService.getCursorIgnoreMapping()});const l=await this.runProcess({ctx:n,args:t,workingDirectory:s,sandboxPolicy:a,timeoutMs:i});return this.buildResult({args:t,workingDirectory:s,processResult:l,sandboxPolicy:a})}catch(e){r.error=e,r.hasError=!0}finally{AT(r)}}}const jT=q("shell-executor",(e=>new B(e,Z("shellArgs"),X("shellResult"))),((e,t)=>{t.register(new I(e,Y("shellArgs"),Q("shellResult")))})),UT=q("mini-swe-agent-bash-executor",(e=>new B(e,Z("miniSweAgentBashArgs"),X("miniSweAgentBashResult"))),((e,t)=>{t.register(new I(e,Y("miniSweAgentBashArgs"),Q("miniSweAgentBashResult")))}));function BT(e){return`${e} changed on disk after this tool call read it. Nothing was written. Read the file again and retry.`}function WT(e){return`${e} changed on disk after you last read or wrote it. Nothing was written. Read the file again and retry.`}(0,y.cF)(Symbol("optionalPendingPodWrite"),!1);const HT=q("write-executor",(e=>new B(e,Z("writeArgs"),X("writeResult"))),((e,t)=>{t.register(new I(e,Y("writeArgs"),Q("writeResult")))})),qT=q("delete-executor",(e=>new B(e,Z("deleteArgs"),X("deleteResult"))),((e,t)=>{t.register(new I(e,Y("deleteArgs"),Q("deleteResult")))})),zT=q("fetch-executor",(e=>new B(e,Z("fetchArgs"),X("fetchResult"))),((e,t)=>{t.register(new I(e,Y("fetchArgs"),Q("fetchResult")))})),GT=q("git-diff-executor",(e=>new B(e,Z("gitDiffRequest"),X("gitDiffResponse"))),((e,t)=>{t.register(new I(e,Y("gitDiffRequest"),Q("gitDiffResponse")))})),VT=q("grep-executor",(e=>new B(e,Z("grepArgs"),X("grepResult"))),((e,t)=>{t.register(new I(e,Y("grepArgs"),Q("grepResult")))})),KT="[REDACTED]",JT=new TextEncoder;async function ZT(e){const t=JT.encode(e),r=await crypto.subtle.digest("SHA-256",t);return{sha256:[...new Uint8Array(r)].map((e=>e.toString(16).padStart(2,"0"))).join(""),bytes:t.byteLength}}class XT{constructor(e){this.inner=e}async execute(e,t,r){if(!0!==t.digestOnly)return this.inner.execute(e,t,r);const n=t.clone();return n.digestOnly=void 0,n.maxChars=void 0,async function(e){if("success"!==e.result.case)return e;const t=e.result.value;if("content"!==t.output.case)return e;const{sha256:r,bytes:n}=await ZT(t.output.value),o=t.clone();return o.output={case:void 0},o.outputBlobId=void 0,o.sha256=r,o.sizeBytes=BigInt(n),new Ky.sV({result:{case:"success",value:o}})}(await this.inner.execute(e,n,r))}}const QT=q("read-executor",(e=>new B(e,Z("readArgs"),X("readResult"))),((e,t)=>{t.register(new I(e,Y("readArgs"),Q("readResult")))})),YT=q("redacted-read-executor",(e=>new B(e,Z("redactedReadArgs"),X("redactedReadResult"))),((e,t)=>{t.register(new I(e,Y("redactedReadArgs"),Q("redactedReadResult")))})),eA=q("ls-executor",(e=>new B(e,Z("lsArgs"),X("lsResult"))),((e,t)=>{t.register(new I(e,Y("lsArgs"),Q("lsResult")))})),tA=q("diagnostics-executor",(e=>new B(e,Z("diagnosticsArgs"),X("diagnosticsResult"))),((e,t)=>{t.register(new I(e,Y("diagnosticsArgs"),Q("diagnosticsResult")))})),rA=q("canvas-diagnostics-executor",(e=>new B(e,Z("canvasDiagnosticsArgs"),X("canvasDiagnosticsResult"))),((e,t)=>{t.register(new I(e,Y("canvasDiagnosticsArgs"),Q("canvasDiagnosticsResult")))})),nA="$file:";const oA=(0,u.Pu)("mcp.symbolic_args.expansion",{description:"Outcome of late-binding $file:/abs/path MCP argument expansion at the executor boundary. The call is refused rather than carrying a placeholder to the server when the read reports having replaced a saved secret (`redacted`), or, from a read executor too old to report that, when its text still carries the redaction marker (`redacted_marker`)",labelNames:["route","outcome"]}),sA=(0,u.v5)("mcp.symbolic_args.bytes",{description:"Total bytes substituted into one MCP tool call by $file:/abs/path arguments",labelNames:["route"]}),iA=(0,u.Pu)("mcp.symbolic_args.describe",{description:"Per-file $file:/abs/path describe reads: `vm_digest` when the read executor hashed the file where it lives, `outdated_executor` when it returned the text instead (it predates $file: expansion, so the call is refused)",labelNames:["source"]}),aA=(0,u.v5)("mcp.symbolic_args.paths",{description:"Number of distinct $file:/abs/path arguments expanded in one MCP tool call",labelNames:["route"]});function cA(e,t,r){return{kind:e,message:`Could not resolve the symbolic argument "${nA}${t}": ${r} A string argument of the form "${nA}/absolute/path" is replaced with that file's contents before the tool runs; pass the literal text instead if you did not intend that.`}}const lA={redacted:e=>`${e} contains a saved secret, and a saved secret is never sent through a "${nA}/absolute/path" argument, so this call was not made. Do not retry it, and do not read the file to pass the value yourself. Tell the user that this file holds a saved secret and that they have to enter it in the tool's service themselves.`,redacted_marker:e=>`${e} may contain a saved secret: its text includes the placeholder "${KT}", and the computer that read it is too old to say whether a saved secret stood there, so this call was not made. Do not retry it, and do not read the file to pass the value yourself. Tell the user that this file may hold a saved secret and that they have to enter it in the tool's service themselves.`};function uA(e,t){return{kind:e,message:`Could not resolve the symbolic argument "${nA}${t}": ${lA[e](t)}`}}class dA extends Error{constructor(e){super(e.message),this.failure=e}}let hA;async function pA(e,t,r,n,o,{maxFileBytes:s=8388608,maxTotalBytes:i=16777216,refuseSavedSecrets:a=!1}){if(t.length>4)throw new dA(cA("too_many",t[4]??"",`at most 4 symbolic arguments may be used in one call (${t.length} given). Split the call or pass paths to tools that accept them.`));const c=r();if(void 0===c)throw new dA(cA("no_read_executor",t[0]??"","this environment cannot read files on behalf of a tool call."));const l=await(0,Or.xb)(t,(t=>async function(e,t,r,n,o){const s=await t.execute(e,new Ky.a2({path:r,toolCallId:n,...o.digestOnly?{digestOnly:!0}:{}}));if("success"!==s.result.case)throw new dA(function(e,t,r){switch(e.result.case){case"fileNotFound":return cA("not_found",t,"the file does not exist.");case"permissionDenied":return cA("permission_denied",t,"reading it was not permitted.");case"rejected":return cA("rejected",t,`${e.result.value.reason||"the read was rejected"}. Only files the Read tool can read without approval can be substituted; read it with Read instead.`);case"invalidFile":return cA("not_text",t,"the file cannot be read as text.");case"error":return r?{kind:"read_error",message:`Could not resolve the symbolic argument "${nA}${t}": ${e.result.value.error}`}:cA("read_error",t,e.result.value.error);default:return cA("read_error",t,"the read returned no result.")}}(s,r,o.refuseSavedSecrets));return await async function(e,t,r,{maxFileBytes:n,digestOnly:o,refuseSavedSecrets:s}){const i=function(e,t,r,n){const o=n&&void 0!==t.sha256&&void 0!==t.sizeBytes?{sha256:t.sha256,bytes:Number(t.sizeBytes)}:void 0;if(void 0===o&&"content"!==t.output.case)throw new dA(cA("not_text",r,"the file is not a text file."));if(n){if(iA.increment(e,1,{source:void 0!==o?"vm_digest":"outdated_executor"}),void 0===o)throw new dA(cA("outdated_executor",r,"the computer that would run this tool has an older tool runner that cannot substitute files. Read the file and pass its contents instead."));return o}}(e,t,r,o),a="content"===t.output.case?t.output.value:void 0,{sha256:c,bytes:l}=i??await ZT(a??""),u={content:a,bytes:l,sha256:c};if(t.truncated||l>n)throw new dA(cA("too_large",r,`the file is too large to inline (${Number(t.fileSize)||l} bytes; at most ${n} bytes per file may be substituted). Pass the path to a tool that accepts one, or read a range of it.`));return await async function(e,t,r,n){if(n){if(!0===e.redacted)throw new dA(uA("redacted",r));if(void 0===e.redacted&&await async function(e){return void 0!==e.content?e.content.includes(KT):(await(hA??=Promise.all([KT,`${KT}\n`,`${KT}\r\n`].map((async e=>(await ZT(e)).sha256))).then((e=>new Set(e))),hA)).has(e.sha256)}(t))throw new dA(uA("redacted_marker",r))}}(t,u,r,s),u}(e,s.result.value,r,o)}(e,c,t,n,{maxFileBytes:s,digestOnly:o,refuseSavedSecrets:a})),{max:4});let u=0;for(const[e,r]of l)if(u+=r.bytes,u>i)throw new dA(cA("over_budget",e,`together the ${t.length} symbolic arguments exceed the ${i} bytes that may be substituted per call. Pass paths to tools that accept them instead.`));return l}async function fA(e,t,{route:r,getReadExecutor:n,...o}){if(0===t.symbolicPathArguments.length)return{kind:"none"};const s=new Map(t.symbolicPathArguments.map((e=>[e.path,e]))),i=[...s.keys()],a=t=>(oA.increment(e,1,{route:r,outcome:t.kind}),{kind:"failed",failure:t,result:new Ac.iz({result:{case:"error",value:new Ac.Nh({error:t.message})}})});let c;try{c=await pA(e,i,n,t.toolCallId,!1,o)}catch(e){return a(function(e,t){return e instanceof dA?e.failure:cA("read_error",t,e instanceof Error?e.message:String(e))}(e,i[0]??""))}let l=0;for(const[e,t]of c){l+=t.bytes;const r=s.get(e);if(r?.sha256!==t.sha256)return a(cA("content_changed",e,`the file changed after the call was reviewed (${r?.sizeBytes??0} bytes then, ${t.bytes} bytes now), so its new contents were not sent. Re-run the call to review the current contents.`))}const u=new Map([...c].map((([e,t])=>[e,t.content??""]))),d=function(e,t){const r=e=>{const n=function(e){if("string"!=typeof e||!e.startsWith(nA))return;const t=e.slice(6);return(r=t).startsWith("/")||/^[a-zA-Z]:[\\/]/.test(r)||r.startsWith("\\\\")?t:void 0;var r}(e);return void 0!==n?t.get(n)??e:Array.isArray(e)?e.map(r):null!==e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map((([e,t])=>[e,r(t)]))):e};return Object.fromEntries(Object.entries(e).map((([e,t])=>[e,r(t)])))}(Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()]))),u),h=t.clone();return h.args=Object.fromEntries(Object.entries(d).map((([e,t])=>[e,we.Value.fromJson(t)]))),h.symbolicPathArguments=[],h.argumentsRepaired=!1,oA.increment(e,1,{route:r,outcome:"expanded"}),sA.record(e,l,{route:r}),aA.record(e,i.length,{route:r}),{kind:"expanded",expansion:{args:h,files:[...c].map((([e,t])=>({path:e,bytes:t.bytes}))),paths:i.length,bytes:l}}}const mA=/\b413\b|payload too large|request entity too large|body.*too large|too large.*body|ECONNRESET|EPIPE|socket hang up|max(?:imum)? (?:body|payload|request|content) (?:size|length)/i;function gA(e,t,r,n){return mA.test(t)?(oA.increment(e,1,{route:n,outcome:"server_rejected_body"}),`${t}\n\nThe request carried ${r.bytes} bytes of file contents substituted from ${r.paths} "${nA}/abs/path" argument(s), and the server appears to have rejected the request body as too large. Do not retry the same call: pass a smaller file or a range of it, or use a tool that accepts a path or upload instead.`):t}function wA(e){return e.files.map((e=>`"${nA}${e.path}" was replaced with the contents of ${e.path} (${e.bytes} bytes) before the call.`)).join("\n")}class yA{constructor(e,t,r={}){this.inner=e,this.getReadExecutor=t,this.options=r}isBackendRouted(e){return this.inner.isBackendRouted?.(e)??!1}async execute(e,t,r){if(0===t.symbolicPathArguments.length)return this.inner.execute(e,t,r);const n=await fA(e,t,{route:"local",getReadExecutor:this.getReadExecutor,refuseSavedSecrets:!0===this.options.refuseSavedSecrets&&t.refuseSavedSecrets});if("none"===n.kind)return this.inner.execute(e,t,r);if("failed"===n.kind)return n.result;let o;try{o=await this.inner.execute(e,n.expansion.args,r)}catch(t){throw t instanceof Error&&(t.message=gA(e,t.message,n.expansion,"local")),t}return function(e,t,r){const n=t.clone();return"success"===n.result.case?n.result.value.content.push(new Ac._Z({content:{case:"text",value:new Ac.zN({text:wA(r)})}})):"error"===n.result.case&&(n.result.value.error=gA(e,n.result.value.error,r,"local")),n}(e,o,n.expansion)}}const vA=q("background-shell-executor",(e=>new B(e,Z("backgroundShellSpawnArgs"),X("backgroundShellSpawnResult"))),((e,t)=>{t.register(new I(e,Y("backgroundShellSpawnArgs"),Q("backgroundShellSpawnResult")))})),bA=q("write-background-shell-input-executor",(e=>new B(e,Z("writeShellStdinArgs"),X("writeShellStdinResult"))),((e,t)=>{t.register(new I(e,Y("writeShellStdinArgs"),Q("writeShellStdinResult")))})),SA=q("agent-store-conflict-executor",(e=>new B(e,Z("agentStoreConflictArgs"),X("agentStoreConflictResult"))),((e,t)=>{t.register(new I(e,Y("agentStoreConflictArgs"),Q("agentStoreConflictResult")))})),kA=q("shell-allowlist-precheck-executor",(e=>new B(e,Z("shellAllowlistPrecheckArgs"),X("shellAllowlistPrecheckResult"))),((e,t)=>{t.register(new I(e,Y("shellAllowlistPrecheckArgs"),Q("shellAllowlistPrecheckResult")))})),_A=q("mcp-allowlist-precheck-executor",(e=>new B(e,Z("mcpAllowlistPrecheckArgs"),X("mcpAllowlistPrecheckResult"))),((e,t)=>{t.register(new I(e,Y("mcpAllowlistPrecheckArgs"),Q("mcpAllowlistPrecheckResult")))})),CA=q("web-fetch-allowlist-precheck-executor",(e=>new B(e,Z("webFetchAllowlistPrecheckArgs"),X("webFetchAllowlistPrecheckResult"))),((e,t)=>{t.register(new I(e,Y("webFetchAllowlistPrecheckArgs"),Q("webFetchAllowlistPrecheckResult")))})),EA=q("force-background-shell-executor",(e=>new B(e,Z("forceBackgroundShellArgs"),X("forceBackgroundShellResult"))),((e,t)=>{t.register(new I(e,Y("forceBackgroundShellArgs"),Q("forceBackgroundShellResult")))})),xA=q("computer-use-executor",(e=>new B(e,Z("computerUseArgs"),X("computerUseResult"))),((e,t)=>{t.register(new I(e,Y("computerUseArgs"),Q("computerUseResult")))})),PA=q("computer-use-end-turn-executor",(e=>new B(function(e){return{createExecInstance:(t,r)=>e.createExecInstance(t,(e=>{if(t.signal.aborted)throw new Error("computer-use turn end not sent: its caller stopped waiting");return r(e)}))}}(e),Z("computerUseEndTurnArgs"),X("computerUseEndTurnResult"))),((e,t)=>{t.register(new I(e,Y("computerUseEndTurnArgs"),Q("computerUseEndTurnResult")))})),RA=q("record-screen-executor",(e=>new B(e,Z("recordScreenArgs"),X("recordScreenResult"))),((e,t)=>{t.register(new I(e,Y("recordScreenArgs"),Q("recordScreenResult")))}));var IA=r("../proto/dist/generated/agent/v1/agent_store_conflict_exec_pb.js");function TA(e){if(void 0!==e)return{journalEpoch:e.journalEpoch,seq:Number(e.seq),lastEventId:e.lastEventId}}class AA{constructor(e){this.drainer=e}async execute(e,t){try{void 0!==t.includeQuotaNotices&&this.drainer.setIncludeQuotaNoticesOverride(t.includeQuotaNotices);const e=await this.drainer.drain({cursor:TA(t.cursor),advance:!1!==t.advance});return new IA.Ev({result:{case:"success",value:new IA.iS({events:e.events.map((e=>new IA.RZ({v:e.v,eventId:e.event_id,journalEpoch:e.journal_epoch,seq:BigInt(e.seq),tsMs:BigInt(e.ts_ms),kind:e.kind,storeId:e.store_id,originalRelPath:e.original_rel_path,conflictRelPath:e.conflict_rel_path,originalAbsPath:e.original_abs_path,conflictAbsPath:e.conflict_abs_path,preservedBytes:void 0===e.preserved_bytes?void 0:BigInt(e.preserved_bytes),scopeKind:e.scope_kind,limitBytes:void 0===e.limit_bytes?void 0:BigInt(e.limit_bytes),usageBytes:void 0===e.usage_bytes?void 0:BigInt(e.usage_bytes)}))),nextCursor:(r=e.nextCursor,new IA.LK({journalEpoch:r.journalEpoch,seq:BigInt(r.seq),lastEventId:r.lastEventId})),gap:e.gap})}})}catch(e){return new IA.Ev({result:{case:"error",value:new IA.h6({error:e instanceof Error?e.message:String(e)})}})}var r}}class $A{constructor(e){this.shellStdinWriter=e}async execute(e,t){const r=t.shellId;try{await this.shellStdinWriter(r,t.chars)}catch(e){return new Do.nt({result:{case:"error",value:new Do.Gv({error:`Failed to write to shell ${r} stdin: ${e instanceof Error?e.message:"Unknown error"}`})}})}return new Do.nt({result:{case:"success",value:new Do.tR({shellId:r,terminalFileLengthBeforeInputWritten:0})}})}}var MA=r("../proto/dist/generated/agent/v1/canvas_diagnostics_exec_pb.js"),DA=r("../proto/dist/generated/agent/v1/diagnostics_exec_pb.js");class OA{constructor(e,t){this.getCanvasDiagnostics=e,this.beginCanvasSave=t}async execute(e,t){let r=()=>{};const n=new Promise((e=>{r=e}));let o;if(void 0===this.beginCanvasSave)o=Promise.resolve(void 0);else try{o=this.beginCanvasSave(t.path,{typecheckOutcome:n}).catch((()=>{}))}catch{o=Promise.resolve(void 0)}try{const e=await this.getCanvasDiagnostics(t.path);return void 0===e?(r("unavailable"),FA(NA(t.path,"diagnostics unavailable"),await o)):(r(e.some((e=>1===e.severity))?"failed":"passed"),FA(new MA.GL({result:{case:"success",value:new MA.uX({path:t.path,diagnostics:e.map(LA)})}}),await o))}catch(e){return r("unavailable"),FA(NA(t.path,e instanceof Error?e.message:String(e)),await o)}}}function FA(e,t){return void 0===t||(e.saveState=t.saveState,e.canvasId=t.canvasId,e.title=t.title,e.saveDetail=t.saveDetail),e}function NA(e,t){return new MA.GL({result:{case:"error",value:new MA.HW({path:e,error:t})}})}function LA(e){return new DA.oQ({severity:jA(e.severity),range:new Dc.Q6({start:new Dc.yX({line:e.range.start.line+1,column:e.range.start.character+1}),end:new Dc.yX({line:e.range.end.line+1,column:e.range.end.character+1})}),message:e.message,source:"ts",code:e.code??""})}function jA(e){switch(e){case 1:return DA.h_.ERROR;case 2:return DA.h_.WARNING;case 3:return DA.h_.INFORMATION;case 4:return DA.h_.HINT;default:return DA.h_.UNSPECIFIED}}class UA{constructor(e){if(e.startsWith("file://")){if(!this.isValidFileUrl(e))throw new Error(`Invalid file URL: ${e}`);this.urlString=e}else{const t=this.resolvePath(e);this.urlString=this.pathToFileUrl(t)}}isValidFileUrl(e){try{return"file:"===new URL(e).protocol}catch{return!1}}resolvePath(e){if(e.includes("\\")&&(e=e.replace(/\\/g,"/")),/^[a-zA-Z]:\//.test(e)||/^\//.test(e))return e;const t=e.split("/"),r=[];for(let e=0;ethis.convertDiagnostic(e)));return new DA.Ek({result:{case:"success",value:new DA.a1({path:t.path,diagnostics:s,totalDiagnostics:s.length})}})}catch(r){return e.canceled?new DA.Ek({result:{case:"error",value:new DA.Ho({path:t.path,error:"Request timed out after 10 seconds"})}}):new DA.Ek({result:{case:"error",value:new DA.Ho({path:t.path,error:r instanceof Error?r.message:String(r)})}})}finally{n()}}catch(e){r.error=e,r.hasError=!0}finally{BA(r)}}convertDiagnostic(e){const t=e.message,r="string"==typeof t?t:t&&"object"==typeof t&&"value"in t&&"string"==typeof t.value?t.value:"";return new DA.oQ({severity:this.convertSeverity(e.severity),range:e.range?new Dc.Q6({start:new Dc.yX({line:e.range.start.line,column:e.range.start.character}),end:new Dc.yX({line:e.range.end.line,column:e.range.end.character})}):void 0,message:r,source:e.source,code:e.code?String(e.code):void 0})}convertSeverity(e){switch(e){case 1:return DA.h_.ERROR;case 2:return DA.h_.WARNING;case 3:return DA.h_.INFORMATION;case 4:return DA.h_.HINT;default:return DA.h_.UNSPECIFIED}}}async function HA(e){const{repoRoot:t,filePaths:r,getContent:n}=e,o=new Map;if(0===r.length)return o;const s=await async function(e,t){const r=new Map;if(0===t.length)return r;try{const{stdout:n}=await vy().run(e,["check-attr","linguist-generated","--stdin"],{input:`${t.join("\n")}\n`});for(const e of n.trim().split("\n")){const t=e.match(/^(.+): linguist-generated: (.+)$/);if(t){const e=t[1],n=t[2];"true"===n||"set"===n?r.set(e,!0):"false"!==n&&"unset"!==n||r.set(e,!1)}}}catch{}return r}(t,r);return await Promise.all(r.map((async e=>{const t=s.get(e);if(!0!==t)if(!1!==t)if(function(e){return new qA(e).isGeneratedByPath()}(e))o.set(e,{isGenerated:!0,source:"path-heuristic"});else{if(n){const t=await n(e);if(void 0!==t&&function(e,t){return new qA(e,(()=>t)).isGeneratedByContent()}(e,t))return void o.set(e,{isGenerated:!0,source:"content-heuristic"})}o.set(e,{isGenerated:!1,source:"none"})}else o.set(e,{isGenerated:!1,source:"gitattributes"});else o.set(e,{isGenerated:!0,source:"gitattributes"})}))),o}class qA{constructor(e,t){this.name=e,this.extname=s.extname(e).toLowerCase(),this.getContent=t}get lines(){if(void 0===this.cachedLines){const e=this.getContent?.();this.cachedLines=e?e.split("\n"):[]}return this.cachedLines}get data(){return this.getContent?.()}isGeneratedByPath(){return this.xcodeFile()||this.intellijFile()||this.cocoapods()||this.carthageBuild()||this.generatedGraphqlRelay()||this.generatedNetDesignerFile()||this.generatedNetSpecflowFeatureFile()||this.composerLock()||this.cargoLock()||this.cargoOrig()||this.denoLock()||this.flakeLock()||this.bazelLock()||this.nodeModules()||this.goVendor()||this.goLock()||this.packageResolved()||this.poetryLock()||this.pdmLock()||this.uvLock()||this.pixiLock()||this.esyLock()||this.npmShrinkwrapOrPackageLock()||this.pnpmLock()||this.bunLock()||this.terraformLock()||this.generatedYarnPlugnplay()||this.godeps()||this.generatedByZephir()||this.htmlcov()||this.gradleWrapper()||this.mavenWrapper()||this.pipenvLock()||this.generatedPascalTlb()||this.generatedSqlxQuery()||this.sourceMapByName()}isGeneratedByContent(){return!!this.getContent&&(this.minifiedFiles()||this.hasSourceMap()||this.sourceMap()||this.compiledCoffeescript()||this.generatedParser()||this.generatedNetDocfile()||this.generatedPostscript()||this.compiledCythonFile()||this.generatedGo()||this.generatedProtocolBufferFromGo()||this.generatedProtocolBuffer()||this.generatedJavascriptProtocolBuffer()||this.generatedTypescriptProtocolBuffer()||this.generatedApacheThrift()||this.generatedJniHeader()||this.vcrCassette()||this.generatedAntlr()||this.generatedModule()||this.generatedUnity3dMeta()||this.generatedRacc()||this.generatedJflex()||this.generatedGrammarkit()||this.generatedRoxygen2()||this.generatedHtml()||this.generatedJison()||this.generatedGrpcCpp()||this.generatedDart()||this.generatedPerlPpportHeader()||this.generatedGamemakerstudio()||this.generatedGimp()||this.generatedVisualstudio6()||this.generatedHaxe()||this.generatedJooq()||this.generatedSorbetRbi()||this.generatedMysqlViewDefinitionFormat())}xcodeFile(){return[".nib",".xcworkspacedata",".xcuserstate"].includes(this.extname)}intellijFile(){return/(?:^|\/)\.idea\//.test(this.name)}cocoapods(){return/(^Pods|\/Pods)\//.test(this.name)}carthageBuild(){return/(^|\/)Carthage\/Build\//.test(this.name)}generatedGraphqlRelay(){return/__generated__\//.test(this.name)}generatedNetDesignerFile(){return/\.designer\.(cs|vb)$/i.test(this.name)}generatedNetSpecflowFeatureFile(){return/\.feature\.cs$/i.test(this.name)}composerLock(){return/composer\.lock/.test(this.name)}cargoLock(){return/Cargo\.lock/.test(this.name)}cargoOrig(){return/Cargo\.toml\.orig/.test(this.name)}denoLock(){return/deno\.lock/.test(this.name)}flakeLock(){return/(^|\/)flake\.lock$/.test(this.name)}bazelLock(){return/(^|\/)MODULE\.bazel\.lock$/.test(this.name)}nodeModules(){return/node_modules\//.test(this.name)}goVendor(){return/vendor\/((?!-)[-0-9A-Za-z]+(?e+t.length),0)/this.lines.length>110}hasSourceMap(){return!!this.maybeMinified()&&this.lines.slice(-2).some((e=>/^\/[*/][#@] source(?:Mapping)?URL|sourceURL=/.test(e)))}sourceMap(){if(".map"!==this.extname)return!1;if(/\.(css|js)\.map$/i.test(this.name))return!0;const e=this.lines[0]||"";return/^{"version":\d+,/.test(e)||/^\/\*\* Begin line maps\. \*\*\/{/.test(e)}compiledCoffeescript(){if(".js"!==this.extname)return!1;const e=this.lines[0]||"";if(/^\/\/ Generated by /.test(e))return!0;if("(function() {"===e&&"}).call(this);"===(this.lines[this.lines.length-2]||"")&&""===(this.lines[this.lines.length-1]||"")){let e=0;for(const t of this.lines)if(/var /.test(t)){const r=t.match(/_fn|_i|_len|_ref|_results/g);e+=1*(r?.length||0);const n=t.match(/__bind|__extends|__hasProp|__indexOf|__slice/g);e+=3*(n?.length||0)}return e>=3}return!1}generatedNetDocfile(){return".xml"===this.extname&&!(this.lines.length<=3)&&(this.lines[1]||"").includes("")&&(this.lines[2]||"").includes("")&&(this.lines[this.lines.length-2]||"").includes("")}generatedParser(){if(".js"!==this.extname)return!1;const e=this.lines.slice(0,5).join("");return/^(?:[^/]|\/[^*])*\/\*(?:[^*]|\*[^/])*Generated by PEG\.js/.test(e)}generatedPostscript(){if(![".ps",".eps",".pfa"].includes(this.extname))return!1;const e=this.data;if(!e)return!1;if(/^\s*(?:currentfile eexec\s+|\/sfnts\s+\[\s<)/.test(e))return!0;const t=this.lines.slice(0,10).find((e=>/^%%Creator: /.test(e)));return!!t&&(!(!/[0-9]|draw|mpage|ImageMagick|inkscape|MATLAB/.test(t)&&!/PCBNEW|pnmtops|\(Unknown\)|Serif Affinity|Filterimage -tops/.test(t))||!!t.includes("EAGLE")&&this.lines.slice(0,5).some((e=>/^%%Title: EAGLE Drawing /.test(e))))}generatedGo(){return".go"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,40).some((e=>/^\/\/ Code generated .*/.test(e)))}generatedProtocolBufferFromGo(){return".proto"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,20).some((e=>e.includes("This file was autogenerated by go-to-protobuf")))}generatedProtocolBuffer(){return!![".py",".java",".h",".cc",".cpp",".m",".rb",".php"].includes(this.extname)&&!(this.lines.length<=1)&&this.lines.slice(0,3).some((e=>e.includes("Generated by the protocol buffer compiler. DO NOT EDIT!")))}generatedJavascriptProtocolBuffer(){return".js"===this.extname&&!(this.lines.length<=6)&&(this.lines[5]||"").includes("GENERATED CODE -- DO NOT EDIT!")}generatedTypescriptProtocolBuffer(){return".ts"===this.extname&&!(this.lines.length<=4)&&(this.lines[0]||"").includes("Code generated by protoc-gen-ts_proto. DO NOT EDIT.")}generatedApacheThrift(){return!![".rb",".py",".go",".js",".m",".java",".h",".cc",".cpp",".php"].includes(this.extname)&&this.lines.slice(0,6).some((e=>e.includes("Autogenerated by Thrift Compiler")))}generatedJniHeader(){return".h"===this.extname&&!(this.lines.length<=2)&&(this.lines[0]||"").includes("/* DO NOT EDIT THIS FILE - it is machine generated */")&&(this.lines[1]||"").includes("#include ")}vcrCassette(){return".yml"===this.extname&&!(this.lines.length<=2)&&(this.lines[this.lines.length-2]||"").includes("recorded_with: VCR")}generatedAntlr(){return".g"===this.extname&&!(this.lines.length<=2)&&(this.lines[1]||"").includes("generated by Xtest")}compiledCythonFile(){return!![".c",".cpp"].includes(this.extname)&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("Generated by Cython")}generatedModule(){if(".mod"!==this.extname)return!1;if(this.lines.length<=1)return!1;const e=this.lines[0]||"";return e.includes("PCBNEW-LibModule-V")||e.includes("GFORTRAN module version '")}generatedUnity3dMeta(){return".meta"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("fileFormatVersion: ")}generatedRacc(){return".rb"===this.extname&&!(this.lines.length<=2)&&(this.lines[2]||"").startsWith("# This file is automatically generated by Racc")}generatedJflex(){return".java"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("/* The following code was generated by JFlex ")}generatedGrammarkit(){return".java"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("// This is a generated file. Not intended for manual editing.")}generatedRoxygen2(){return".rd"===this.extname&&!(this.lines.length<=1)&&(this.lines[0]||"").includes("% Generated by roxygen2: do not edit by hand")}generatedHtml(){if(![".html",".htm",".xhtml"].includes(this.extname))return!1;if(this.lines.length<=1)return!1;if(this.lines.slice(0,2).some((e=>//.test(e))))return!0;if(this.lines.length>2&&(this.lines[2]||"").startsWith("\x3c!-- This is an automatically generated file."))return!0;if(this.lines.slice(0,31).some((e=>//i.test(e))))return!0;const e=this.lines.slice(0,31).join(" ").match(/]+)>/gi);if(!e)return!1;for(const t of e){const e=this.extractHtmlMeta(t);if("generator"===e.name?.toLowerCase()&&(e.content||e.value)){const t=e.content||e.value||"";if(/^(org\s+mode|j?latex2html|groff|makeinfo|texi2html|ronn)\b/i.test(t))return!0}}return!1}extractHtmlMeta(e){const t={},r=e.matchAll(/(?<=^|\s)(name|content|value)\s*=\s*("[^"]+"|'[^']+'|[^\s"']+)/gi);for(const e of r){const r=e[1].toLowerCase();let n=e[2];(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'"))&&(n=n.slice(1,-1)),t[r]=n}return t}generatedJison(){if(".js"!==this.extname)return!1;if(this.lines.length<=1)return!1;const e=this.lines[0]||"";return e.startsWith("/* parser generated by jison ")||e.startsWith("/* generated by jison-lex ")}generatedGrpcCpp(){return!![".cpp",".hpp",".h",".cc"].includes(this.extname)&&!(this.lines.length<=1)&&(this.lines[0]||"").startsWith("// Generated by the gRPC")}generatedDart(){return".dart"===this.extname&&!(this.lines.length<=1)&&this.lines.slice(0,3).some((e=>/generated code\W{2,3}do not modify/i.test(e)))}generatedPerlPpportHeader(){return!!/ppport\.h$/.test(this.name)&&!(this.lines.length<=10)&&(this.lines[8]||"").includes("Automatically created by Devel::PPPort")}generatedGamemakerstudio(){if(![".yy",".yyp"].includes(this.extname))return!1;if(this.lines.length<=3)return!1;const e=this.lines.slice(0,3).join("");return/^\s*[{[]/.test(e)||/^\d\.\d\.\d.+\|\{/.test(this.lines[0]||"")}generatedGimp(){if(![".c",".h"].includes(this.extname))return!1;if(0===this.lines.length)return!1;const e=this.lines[0]||"";return/^\/\* GIMP [a-zA-Z0-9- ]+ C-Source image dump \(.+?\.c\) \*\//.test(e)||/^\/\* {2}GIMP header image file format \([a-zA-Z0-9- ]+\): .+?\.h {2}\*\//.test(e)}generatedVisualstudio6(){return".dsp"===this.extname&&this.lines.slice(0,3).some((e=>e.includes("# Microsoft Developer Studio Generated Build File")))}generatedHaxe(){return!![".js",".py",".lua",".cpp",".h",".java",".cs",".php"].includes(this.extname)&&this.lines.slice(0,3).some((e=>e.includes("Generated by Haxe")))}generatedJooq(){return".java"===this.extname&&this.lines.slice(0,2).some((e=>e.includes("This file is generated by jOOQ.")))}generatedSorbetRbi(){return".rbi"===this.extname&&!(this.lines.length<5)&&/^# typed:/.test(this.lines[0]||"")&&(this.lines[2]||"").includes("DO NOT EDIT MANUALLY")&&/^# Please (run|instead update this file by running) `bin\/tapioca/.test(this.lines[4]||"")}generatedMysqlViewDefinitionFormat(){return".frm"===this.extname&&(this.lines[0]||"").includes("TYPE=VIEW")}}const zA=e=>{if(!e)return[];if("string"!=typeof e||e.match(/^\s+$/))return[];const t=e.split("\n");if(0===t.length)return[];const r=[];let n=null,o=null,s=0,i=0,a=null;const c=e=>{o?.changes.push({type:"normal",normal:!0,ln1:s++,ln2:i++,content:e}),a.oldLines--,a.newLines--},l=e=>{const[t,o]=KA(e)??[];n={chunks:[],deletions:0,additions:0,from:t,to:o},r.push(n)},u=()=>{n&&!n.chunks.length||l()},d=e=>+(e||1),h=e=>{o&&(o.changes.push({type:"del",del:!0,ln:s++,content:e}),n.deletions++,a.oldLines--)},p=e=>{o&&(o.changes.push({type:"add",add:!0,ln:i++,content:e}),n.additions++,a.newLines--)},f=e=>{if(!o)return;const[t]=o.changes.slice(-1);o.changes.push({type:t.type,[t.type]:!0,ln1:t.ln1,ln2:t.ln2,ln:t.ln,content:e})},m=[[/^diff\s/,l],[/^new file mode (\d+)$/,(e,t)=>{u(),n.new=!0,n.newMode=t[1],n.from="/dev/null"}],[/^deleted file mode (\d+)$/,(e,t)=>{u(),n.deleted=!0,n.oldMode=t[1],n.to="/dev/null"}],[/^old mode (\d+)$/,(e,t)=>{u(),n.oldMode=t[1]}],[/^new mode (\d+)$/,(e,t)=>{u(),n.newMode=t[1]}],[/^index\s[\da-zA-Z]+\.\.[\da-zA-Z]+(\s(\d+))?$/,(e,t)=>{u(),n.index=e.split(" ").slice(1),t[1]&&(n.oldMode=n.newMode=t[1].trim())}],[/^---\s/,e=>{u(),n.from=ZA(e)}],[/^\+\+\+\s/,e=>{u(),n.to=ZA(e)}],[/^@@\s+-(\d+),?(\d+)?\s+\+(\d+),?(\d+)?\s@@/,(e,t)=>{n||l(e);const[r,c,u,h]=t.slice(1);s=+r,i=+u,o={content:e,changes:[],oldStart:+r,oldLines:d(c),newStart:+u,newLines:d(h)},a={oldLines:d(c),newLines:d(h)},n.chunks.push(o)}],[/^\\ No newline at end of file$/,f]],g=[[/^\\ No newline at end of file$/,f],[/^-/,h],[/^\+/,p],[/^\s+/,c]],w=e=>{a?(e=>{const t=e.charCodeAt(0);if(43===t)p(e);else if(45===t)h(e);else if(32===t)c(e);else if(92===t&&/^\\ No newline at end of file$/.test(e))f(e);else for(const[t,r]of g){const n=e.match(t);if(n){r(e,n);break}}0===a.oldLines&&0===a.newLines&&(a=null)})(e):(e=>{for(const[t,r]of m){const n=e.match(t);if(n){r(e,n);break}}})(e)};for(const e of t)w(e);return r},GA=/(a|i|w|c|o|1|2)\/.*(?=["']? ["']?(b|i|w|c|o|1|2)\/)|(b|i|w|c|o|1|2)\/.*$/g,VA=/^(a|b|i|w|c|o|1|2)\//,KA=e=>{const t=e?.match(GA);return t?.map((e=>e.replace(VA,"").replace(/("|')$/,"")))},JA=/^\\?['"]|\\?['"]$/g,ZA=e=>{let t=XA(e,"-+").trim();return t=YA(t),t.replace(JA,"").replace(VA,"")},XA=(e,t)=>{if(e=t$(e),!t&&String.prototype.trimLeft)return e.trimLeft();const r=e$(t);return e.replace(new RegExp(`^${r}+`),"")},QA=/\t.*|\d{4}-\d\d-\d\d\s\d\d:\d\d:\d\d(.\d+)?\s(\+|-)\d\d\d\d/,YA=e=>{const t=QA.exec(e);return t&&(e=e.substring(0,t.index).trim()),e},e$=e=>null==e?"\\s":e instanceof RegExp?e.source:`[${t$(e).replace(/([.*+?^=!:${}()|[\]/\\])/g,"\\$1")}]`,t$=e=>`${e??""}`,r$=(0,l.h)("local-mercurial-diff"),n$=5242880,o$="0000000000000000000000000000000000000000";let s$,i$;async function a$(e,t,r={}){const n=await async function(){if(void 0===s$&&(s$=await async function(e){const t="win32"===process.platform?["hg.com","hg.exe"]:["hg"];for(const r of e.split(s.default.delimiter))if(s.default.isAbsolute(r))for(const e of t){const t=s.default.join(r,e);try{if(!(await Co.stat(t)).isFile())continue;return"win32"!==process.platform&&await Co.access(t,xo.constants.X_OK),t}catch{}}}(process.env.PATH??"")??null),null===s$){const e=new Error("hg executable not found");throw e.code="ENOENT",e}return s$}(),o=await new Promise(((o,s)=>{const i=(0,ou.spawn)(n,t,{cwd:e,env:{...process.env,HGPLAIN:"+strictflags",HGRCPATH:"",HGRCSKIPREPO:"1"},shell:!1}),a=new ia.StringDecoder("utf8");let c="";i.stdout.on("data",(e=>{c+=a.write(e)})),i.stderr.on("data",(()=>{})),i.on("error",(e=>{!0===r.allowFailure?o(""):s(e)})),i.on("close",(e=>{if(0===e||!0===r.allowFailure)o(c+a.end());else{const r=t.find((e=>!e.startsWith("-")))??"hg";s(new Error(`MercurialDiffFailed: hg ${r} exited ${e??"unknown"}`))}}))}));return o}async function c$(e){const t=await async function(e){let t=s.default.resolve(e);for(;;){try{if((await Co.stat(s.default.join(t,".hg"))).isDirectory())return!0}catch{}const e=s.default.dirname(t);if(e===t)return!1;t=e}}(e);if(!t)return;const r=function(e,t){return e&&"absent"!==t?"skips-repo-config"!==t?"unsafe":"proceed":"not-mercurial"}(t,await async function(){if(void 0!==i$)return i$;const e=await Co.mkdtemp(s.default.join((0,o.tmpdir)(),"hg-probe-"));try{const t=await a$(e,["help","environment"]);i$=/\bHGRCSKIPREPO\b/.test(t)?"skips-repo-config":"reads-repo-config"}catch(e){i$=function(e){return"object"==typeof e&&null!==e&&"code"in e&&"ENOENT"===e.code}(e)?"absent":"reads-repo-config"}finally{await Co.rm(e,{recursive:!0,force:!0})}return i$}());if("not-mercurial"===r)return;if("unsafe"===r)throw new Error("MercurialClientUnsafe: hg would read repository config");let n;try{n=(await a$(e,["root"])).trim()}catch{return}if(0!==n.length)try{return(await Co.stat(s.default.join(n,".hg"))).isDirectory()?n:void 0}catch{return}}function l$(e,t){return"win32"===process.platform?s.default.win32.normalize(e).toLowerCase()===s.default.win32.normalize(t).toLowerCase():s.default.resolve(e)===s.default.resolve(t)}function u$(e,t){const r=s.default.relative(s.default.resolve(t),s.default.resolve(e));return 0===r.length||!s.default.isAbsolute(r)&&!r.split(s.default.sep).includes("..")}async function d$(e){const t=s.default.resolve(e);try{return await Co.realpath(t)}catch{return t}}function h$(e){if(0===e.length)return[];const t=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),r=t.split("\n");return t.endsWith("\n")&&r.pop(),r}function p$(e){if(e.includes("\0")||/[\r\n]/.test(e))throw new Error("MercurialDiffFailed: base ref contains a newline")}async function f$({repositoryRoot:e,rev:t,filePath:r}){const n=await async function({repositoryRoot:e,rev:t,filePath:r}){let n;try{n=await a$(e,["files","-r",t,"-T","{size}","--",r])}catch{return}const o=n.trim();if(!/^\d+$/.test(o))return;const s=Number(o);return Number.isFinite(s)?s:void 0}({repositoryRoot:e,rev:t,filePath:r});return void 0===n||n>n$?"":a$(e,["cat","-r",t,"--",r])}async function m$(e,t,r){const n=function(e){switch(e){case Le.ek.NAME_STATUS:return Le.ek.NAME_STATUS;case Le.ek.NAME_STATUS_AND_NUMSTAT:return Le.ek.NAME_STATUS_AND_NUMSTAT;case Le.ek.FILE_DIFFS:return Le.ek.FILE_DIFFS;case Le.ek.DIFFS_WITH_BEFORE_AND_AFTER:return Le.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return Le.ek.FILE_DIFFS}}(r.outputFormat),o=["root"],i=(await a$(t,["root"])).trim();if(0===i.length)throw new Error("MercurialDiffFailed: hg root did not resolve");let a,c;if(0!==r.ref.length||"HEAD"!==r.baseRef&&(r.mergeBase||0!==r.baseRef.length)){if(r.mergeBase||0===r.baseRef.length)a=await async function({cwd:e,baseRef:t,commands:r}){if(t.length>0&&"HEAD"!==t){p$(t),r.push("log");const n=(await a$(e,["log","-r",`ancestor(., (${t}))`,"-T","{node}"])).trim();if(0===n.length||n===o$)throw new Error("MercurialDiffFailed: base ref did not resolve");return n}r.push("log");const n=(await a$(e,["log","-r","max(::. and public())","-T","{node}"],{allowFailure:!0})).trim();if(n.length>0&&n!==o$)return n;const o=(await a$(e,["log","-r","ancestor(., default)","-T","{node}"],{allowFailure:!0})).trim();if(o.length>0&&o!==o$)return o;const s=(await a$(e,["log","-r",".","-T","{node}"],{allowFailure:!0})).trim();return s.length>0?s:o$}({cwd:t,baseRef:r.baseRef,commands:o});else if(p$(r.baseRef),o.push("log"),a=(await a$(t,["log","-r",r.baseRef,"-T","{node}"])).trim(),0===a.length)throw new Error("MercurialDiffFailed: base ref did not resolve");r.ref.length>0&&(p$(r.ref),o.push("log"),c=(await a$(t,["log","-r",r.ref,"-T","{node}"])).trim())}const l=["diff","--git"];r.includeSpaceChanges||l.push("-b"),void 0!==r.unifiedContextLines&&l.push(`-U${r.unifiedContextLines}`),void 0!==a&&l.push("-r",a),void 0!==c&&l.push("-r",c),r.targetPaths.length>0&&l.push("--",...r.targetPaths),o.push("diff");const u=await a$(t,l),d=function(e){const t=e.replace(/\r\n/g,"\n");return new Le.o$({diffs:zA(t).map((e=>function(e){const t=new Le.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new Le.Ei({content:e.content,lines:e.changes.map((e=>e.content)),oldStart:e.oldStart,oldLines:e.oldLines,newStart:e.newStart,newLines:e.newLines})))});return t.added=e.additions,t.removed=e.deletions,t}(e))),diffType:Le.Wf.UNSPECIFIED})}(u);let h=[];if(r.maxUntrackedFiles>0&&(o.push("status"),h=await async function({cwd:e,repositoryRoot:t,maxUnknownFiles:r}){let n=(await a$(e,["status","-un0"])).split("\0").filter((e=>e.length>0));return n.length>r&&(n=n.slice(0,r)),(await Promise.all(n.map((async e=>{try{const r=s.default.join(t,e),n=await Co.stat(r);if(n.size>n$){const t=await async function(e){const t=(0,bo.createHash)("sha256"),r=await Co.open(e,"r");try{const e=Buffer.alloc(65536);let n=0;for(;;){const{bytesRead:o}=await r.read(e,0,e.length,n);if(0===o)break;t.update(e.subarray(0,o)),n+=o}}finally{await r.close()}return t.digest("hex")}(r);return{contents:"",path:e,omittedDueToSize:!0,byteSize:n.size,contentHash:t}}return{contents:await Co.readFile(r,"utf8"),path:e}}catch{return}})))).filter((e=>void 0!==e))}({cwd:t,repositoryRoot:i,maxUnknownFiles:r.maxUntrackedFiles}),d.diffs.push(...h.map((e=>function(e){if(!0===e.omittedDueToSize)return new Le.QP({from:"/dev/null",to:e.path,chunks:[],added:0,removed:0});const t=h$(e.contents);if(0===t.length)return new Le.QP({from:"/dev/null",to:e.path,chunks:[],added:0,removed:0});const r=t.length;return new Le.QP({from:"/dev/null",to:e.path,chunks:[new Le.Ei({content:`@@ -0,0 +1${1===r?"":`,${r}`} @@`,lines:t.map((e=>`+${e}`)),oldStart:0,oldLines:0,newStart:1,newLines:r})],added:r,removed:0})}(e))))),n!==Le.ek.FILE_DIFFS)for(const e of d.diffs)e.chunks=[];if(n===Le.ek.DIFFS_WITH_BEFORE_AND_AFTER){const e=a??".";await Promise.all(d.diffs.map((async t=>{if("/dev/null"!==t.from)try{t.beforeFileContents=await f$({repositoryRoot:i,rev:e,filePath:t.from})}catch{t.beforeFileContents=""}else t.beforeFileContents="";if("/dev/null"!==t.to)if(void 0===c)try{const e=s.default.join(i,t.to),r=await Co.stat(e);t.afterFileContents=r.size>n$?"":await Co.readFile(e,"utf8")}catch{t.afterFileContents=""}else try{t.afterFileContents=await f$({repositoryRoot:i,rev:c,filePath:t.to})}catch{t.afterFileContents=""}else t.afterFileContents=""})))}const p=[u,function(e){const t=[];for(const r of e){const e=h$(r.contents);if(t.push(`diff --git a/${r.path} b/${r.path}`),t.push("new file mode 100644"),t.push("--- /dev/null"),t.push(`+++ b/${r.path}`),0===e.length)continue;const n=e.length;t.push(`@@ -0,0 +1${1===n?"":`,${n}`} @@`),t.push(...e.map((e=>`+${e}`)))}return t.join("\n")}(h.filter((e=>!0!==e.omittedDueToSize))),h.filter((e=>!0===e.omittedDueToSize)).map((e=>`omitted-untracked ${e.byteSize??0} ${e.contentHash??""} ${JSON.stringify(e.path)}`)).join("\n")].filter((e=>e.length>0)).join("\n"),f=r.computePatchId?function(e){if(0!==e.length)return`hg:${(0,bo.createHash)("sha256").update(e).digest("hex")}`}(p.length>0?`${p}\n`:""):void 0;let m,g;if(!0===r.returnHeadSha){o.push("log","status");const e=(await a$(t,["log","-r",".","-T","{node}"],{allowFailure:!0})).trim();m=e.length>0?e:o$,g=(await a$(t,["status","-0"])).length>0}r$.info(e,"Local mercurial diff commands",{sourceControl:"mercurial",commands:o});const w=new Le.df({diff:d,submoduleDiffs:[],patchId:f,headSha:m,hasUncommittedChanges:g}),y=r.maxResponseBytes??0;if(y>0){const t=w.toBinary().byteLength;if(t>y)throw r$.info(e,"Local diff outcome",{sourceControl:"mercurial",outcome:"too_large"}),new Error(`GetDiffResponseTooLarge: ${t} bytes exceeds the ${y} byte limit`)}return r$.info(e,"Local diff outcome",{sourceControl:"mercurial",outcome:"ok",fileCount:d.diffs.length,patchIdPrefixed:!0===f?.startsWith("hg:")}),w}const g$=(0,l.h)("local-git-diff");function w$({exitCode:e,stderr:t}){return new Error(`Git command failed with code ${e}: ${t}`)}async function y$(e,t,r={}){let n;try{n=await e(t)}catch(e){if(!0===r.ignoreErrors)return"";throw e}if(0!==n.exitCode&&!0!==r.ignoreErrors)throw w$(n);return!0===r.shouldNotTrimOutput?n.stdout:n.stdout.trim()}function v$(e){const t=zA(e);return new Le.o$({diffs:t.map((e=>function(e){const t=new Le.QP({from:e.from,to:e.to,chunks:e.chunks.map((e=>new Le.Ei({content:e.content,lines:e.changes.map((e=>e.content)),oldStart:e.oldStart,oldLines:e.oldLines,newStart:e.newStart,newLines:e.newLines})))});return t.added=e.additions,t.removed=e.deletions,t}(e))),diffType:Le.Wf.UNSPECIFIED})}function b$(e){const t=[];for(const n of e){const e={body:`+${(r=n.contents).replaceAll("\n","\n+")}`,numLines:Js(r)},o=1===e.numLines?"@@ -0,0 +1 @@":`@@ -0,0 +1,${e.numLines} @@`;t.push(`diff --git a/${n.path} b/${n.path}\n--- /dev/null\n+++ b/${n.path}\n${o}\n${e.body}`)}var r;return t.join("\n")}const S$=["main","master","develop"];async function k$(e,t){const r=s.default.join(e,t),n=await Co.lstat(r);if(n.isSymbolicLink())return{contents:await Co.readlink(r),path:t,isSymlink:!0};if(!n.isFile())throw new Error("Not a regular file or symlink");return{contents:await Co.readFile(r,"utf8"),path:t,isSymlink:!1}}async function _$(e,t,r){const n=vy(),o=(e,r)=>n.run(t,e,r),i=await async function(e,t){let r;try{const e=(await y$(t,["rev-parse","--show-toplevel"])).trim();e.length>0&&(r=e)}catch{}if(void 0!==r){const t=await async function({cwd:e,gitRoot:t}){const r=await d$(t);let n=await d$(e);if(l$(n,r))return;let o=!1;for(;u$(n,r)&&!l$(n,r);){try{if((await Co.stat(s.default.join(n,".hg"))).isDirectory()){o=!0;break}}catch{}const e=s.default.dirname(n);if(e===n)break;n=e}return o?c$(e):void 0}({cwd:e,gitRoot:r});return void 0!==t?"mercurial":"git"}return void 0===await c$(e)?"none":"mercurial"}(t,o);if(g$.info(e,"Local diff source control",{sourceControl:i}),"none"===i)throw g$.info(e,"Local diff outcome",{sourceControl:i,outcome:"no_version_control"}),new Error("NoVersionControl: no git or mercurial repository");if("mercurial"===i)return m$(e,t,r);const a=function(e){switch(e){case Le.ek.NAME_STATUS:return Le.ek.NAME_STATUS;case Le.ek.NAME_STATUS_AND_NUMSTAT:return Le.ek.NAME_STATUS_AND_NUMSTAT;case Le.ek.FILE_DIFFS:return Le.ek.FILE_DIFFS;case Le.ek.DIFFS_WITH_BEFORE_AND_AFTER:return Le.ek.DIFFS_WITH_BEFORE_AND_AFTER;default:return Le.ek.FILE_DIFFS}}(r.outputFormat),c=await(async()=>{let e=r.baseRef.length>0?r.baseRef:await async function(e){try{const t=await y$(e,["symbolic-ref","--short","refs/remotes/origin/HEAD"]);if(t)return t.trim()}catch{}for(const t of S$){const r=`origin/${t}`;try{return await y$(e,["rev-parse","--verify",r]),r}catch{}}try{const t=(await y$(e,["branch","-r"])).split("\n").map((e=>e.trim())).find((e=>e.startsWith("origin/")));if(t)return t}catch{}try{const t=await y$(e,["config","--get","init.defaultBranch"]);if(t)return t.trim()}catch{}throw new Error("Could not determine default branch")}(o);if(r.mergeBase){const t=r.ref.length>0?r.ref:"HEAD";e=(await y$(o,["merge-base","--end-of-options",e,t])).trim()}return e})(),l=["diff","--no-color"];r.includeSpaceChanges||l.push("--ignore-space-change"),void 0!==r.unifiedContextLines&&l.push(`-U${r.unifiedContextLines}`);const u=["--end-of-options",c];r.ref.length>0&&u.push(r.ref),r.targetPaths.length>0&&u.push("--",...r.targetPaths);const d=await o([...l,...u]);let h,p;if(0===d.exitCode)h=d.stdout,p=v$(h);else{const t=w$(d);if(r.computePatchId||!await async function(e){return(await y$(e,["config","--get-regexp","^(extensions\\.partialclone|remote\\..+\\.promisor)$"],{ignoreErrors:!0})).split("\n").some((e=>/^(extensions\.partialclone \S|remote\..+\.promisor( (true|yes|on|1))?$)/i.test(e)))}(o))throw t;p=await async function(e,t){const r=(await y$(e,["diff","--name-status","--no-renames","-z",...t])).split("\0"),n=[];for(let e=1;e{throw t})),g$.info(e,"Local diff outcome",{sourceControl:i,outcome:"partial_clone_names_only"})}let f=[];if(r.maxUntrackedFiles>0){f=await async function(e,t,r){let n=(await y$(t,["ls-files","--others","--exclude-standard"])).split("\n").map((e=>e.trim())).filter((e=>e.length>0));return n.length>r&&(n=n.slice(0,r)),(await Promise.all(n.map((async t=>{try{return await k$(e,t)}catch{return}})))).filter((e=>void 0!==e))}(t,o,r.maxUntrackedFiles);for(const e of f){const t=e.isSymlink?`${b$([e])}\n\\ No newline at end of file`:await y$(o,["diff","--no-color","--no-index","--","/dev/null",e.path],{ignoreErrors:!0,shouldNotTrimOutput:!0});p.diffs.push(...v$(t).diffs)}}if(a!==Le.ek.FILE_DIFFS||!0===p.fileContentsOmitted)for(const e of p.diffs)e.chunks=[];if(a===Le.ek.DIFFS_WITH_BEFORE_AND_AFTER&&!0!==p.fileContentsOmitted){const n=r.ref.length>0?r.ref:"HEAD";await Promise.all(p.diffs.map((async s=>{try{if("/dev/null"!==s.from)try{s.beforeFileContents=await y$(o,["show","--end-of-options",`${c}:${s.from}`],{shouldNotTrimOutput:!0})}catch{s.beforeFileContents=""}else s.beforeFileContents="";if("/dev/null"!==s.to)if(r.ref.length>0)try{s.afterFileContents=await y$(o,["show","--end-of-options",`${n}:${s.to}`],{shouldNotTrimOutput:!0})}catch{s.afterFileContents=""}else try{s.afterFileContents=(await k$(t,s.to)).contents}catch{try{s.afterFileContents=await y$(o,["show","--end-of-options",`${n}:${s.to}`],{shouldNotTrimOutput:!0})}catch{s.afterFileContents=""}}else s.afterFileContents=""}catch(t){g$.error(e,"Error fetching file contents for diff",t)}})))}const m=new Map;for(const e of p.diffs){const t="/dev/null"!==e.to?e.to:e.from;t&&m.set(t,e)}const g=[...m.keys()],w=r.ref.length>0?r.ref:"HEAD";try{const e=await HA({repoRoot:t,filePaths:g,getContent:async e=>{const t=m.get(e);if(t){if(void 0!==t.afterFileContents)return t.afterFileContents;try{if(t.to&&"/dev/null"!==t.to)return await y$(o,["show","--end-of-options",`${w}:${t.to}`],{shouldNotTrimOutput:!0})}catch{}}}});for(const[t,r]of e){const e=m.get(t);e&&(e.isGenerated=r.isGenerated)}}catch(t){g$.warn(e,"Generated-file detection failed; continuing without it",{error:t instanceof Error?t.message:String(t)})}const y=r.computePatchId&&void 0!==h?await async function(e,t){if(0===t.length)return;const{exitCode:r,stdout:n,stderr:o}=await e(["patch-id","--stable"],{input:t});if(0!==r)throw new Error(`git patch-id failed with code ${r}: ${o}`);return n.trim().split(/\s+/)[0]||void 0}(o,function(...e){const t=e.filter((e=>e.length>0));return 0===t.length?"":`${t.join("\n")}\n`}(h,b$(f))):void 0,v=!0===r.returnHeadSha?(await y$(o,["rev-parse","HEAD"])).trim():void 0,b=!0===r.returnHeadSha?(await y$(o,["status","--porcelain=v1","--untracked-files=all"])).trim().length>0:void 0,S=new Le.df({diff:p,submoduleDiffs:[],patchId:y,headSha:v,hasUncommittedChanges:b}),k=r.maxResponseBytes??0;if(k>0){const e=S.toBinary().byteLength;if(e>k)throw new Error(`GetDiffResponseTooLarge: ${e} bytes exceeds the ${k} byte limit`)}return S}class C${async execute(e,t){return _$(e,t.cwd,t)}}var E$=r("../proto/dist/generated/agent/v1/mcp_allowlist_precheck_exec_pb.js");class x${constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isMcpFullyAllowlisted(e,{providerIdentifier:t.providerIdentifier,toolName:t.toolName,annotationsJson:t.annotationsJson});return new E$.M({allowlisted:r})}}var P$=r("../proto/dist/generated/agent/v1/record_screen_exec_pb.js"),R$=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function I$(e){return null!==e.exitCode||null!==e.signalCode||e.killed}function T$(e,t){return"object"==typeof e&&null!==e&&"code"in e&&e.code===t}function A$(e){return e instanceof Error?e.message:String(e)}function $$(e,t){return new P$.Tj({result:{case:"failure",value:new P$.yH({error:t,kind:e})}})}function M$(e){return e instanceof Error?e.message.startsWith("Failed to load polished-renderer native binding")?"binding_load_failed":"code"in e&&"string"==typeof e.code?e.code:e.name:typeof e}function D$(e,t,r,n){const o=[],s=function(e,t){const r=e.ffmpegExitCode??e.childProcess.exitCode,n=e.ffmpegExitSignal??e.childProcess.signalCode;if(e.ffmpegDiedEarly||null!==e.ffmpegDiedTime||null!==r||null!==n)return`ffmpeg exited code=${r} signal=${n}${null!==e.ffmpegDiedTime?` ${Math.max(0,Math.round((t-e.ffmpegDiedTime)/1e3))}s before SAVE`:""}`}(t,n);return void 0!==s&&o.push(s),void 0!==r&&o.push(`stop failed: ${A$(r)}`),o.length>0?`${e} (${o.join("; ")})`:e}const O$=(0,zs.promisify)(ou.execFile);class F${constructor(e){if(this.activeRecording=null,this.inFlightSaves=[],this.onRecordingStartedCallback=null,this.onRecordingStoppedCallback=null,this.recordingStoppedCallbackInvoked=!1,this.artifactsDir=e.artifactsDir,this.stagingDir=e.stagingDir??"/opt/cursor/recording-staging/",this.display=e.display,this.disablePolishedRendering=e.disablePolishedRendering??!1,this.polishedRenderer=e.polishedRenderer,!this.disablePolishedRendering){if(!this.polishedRenderer)throw new Error("record_screen requires a polished recording renderer when polished rendering is enabled. This tool should run via exec-daemon where that dependency is bundled.");this.polishedRenderer.assertAvailable()}}setOnRecordingStarted(e){this.onRecordingStartedCallback=e}setOnRecordingStopped(e){this.onRecordingStoppedCallback=e}invokeStoppedCallbackOnce(){!this.recordingStoppedCallbackInvoked&&this.onRecordingStoppedCallback&&(this.recordingStoppedCallbackInvoked=!0,this.onRecordingStoppedCallback())}async cleanupRecording(e){try{await(e.inputEventLogger?.stop())}catch{}if(!I$(e.childProcess)&&e.childProcess.pid)try{await this.stopFfmpegRecording(e)}catch{try{process.kill(e.childProcess.pid,"SIGKILL")}catch{}}}getActiveInputEventLogger(){return this.activeRecording?.inputEventLogger??null}async dispose(){const e=this.inFlightSaves.map((e=>e.promise));if(e.length>0)try{await(0,Or.wj)(Promise.all(e),F$.IN_FLIGHT_SAVE_DISPOSE_TIMEOUT_MS,"Timed out waiting for in-flight recording save")}catch{}if(this.activeRecording){await this.cleanupRecording(this.activeRecording),this.invokeStoppedCallbackOnce();try{await Co.rm(this.activeRecording.sessionDir,{force:!0,recursive:!0})}catch{}this.activeRecording=null}}findInFlightSave(e){return this.inFlightSaves.find((t=>t.state===e))}clearActiveRecordingIfCurrent(e){this.activeRecording===e&&(this.activeRecording=null)}invokeStoppedCallbackIfCurrent(e){this.activeRecording===e&&this.invokeStoppedCallbackOnce()}sanitizeToolCallId(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}async ensureRecordingDirectoryExists(){await Co.mkdir(this.stagingDir,{recursive:!0}),await Co.mkdir(this.artifactsDir,{recursive:!0})}buildSessionDir(e){const t=this.sanitizeToolCallId(e),r=`session-${(new Date).toISOString().replace(/[:.]/g,"-")}-${t}`;return s.join(this.stagingDir,r)}validateAndNormalizeSaveAsFilename(e){let t=e.trim();return t.startsWith(this.artifactsDir)&&(t=t.slice(this.artifactsDir.length),t.startsWith("/")&&(t=t.slice(1))),t=t.trim(),0===t.length?{success:!1,reason:P$.y.UNSPECIFIED}:t.includes("/")||t.includes("\\")?{success:!1,reason:P$.y.SLASHES_NOT_ALLOWED}:(t=t.replace(/[^a-zA-Z0-9 ._-]/g,"_"),t=t.trim(),0===t.length?{success:!1,reason:P$.y.UNSPECIFIED}:(t.length>128&&(t=t.slice(0,128).trim()),t.toLowerCase().endsWith(".mp4")||(t=`${t}.mp4`),{success:!0,filename:t}))}async movePolishedVideo(e,t){try{return void await Co.rename(e,t)}catch(e){if(!T$(e,"EXDEV"))throw e}try{await Co.copyFile(e,t)}catch(e){throw await Co.rm(t,{force:!0}).catch((()=>{})),e}try{await Co.unlink(e)}catch(e){throw await Co.rm(t,{force:!0}).catch((()=>{})),e}}async getUniqueArtifactVideoPath(e){const t=s.parse(e),r=t.name||"recording",n=t.ext||".mp4";let o=`${r}${n}`,i=2;for(;;){const e=s.join(this.artifactsDir,o);try{const t=await Co.open(e,"wx");return await t.close(),e}catch(e){if(!T$(e,"EEXIST"))throw e;o=`${r}-${i}${n}`,i++}}}async resolveArtifactVideoPath(e){const{saveAsFilename:t,stagingSessionDir:r}=e;let n,o;if(t){const e=this.validateAndNormalizeSaveAsFilename(t);e.success?o=e.filename:(n=e.reason,o=`${s.basename(r)}.mp4`)}else o=`${s.basename(r)}.mp4`;return{finalVideoPath:await this.getUniqueArtifactVideoPath(o),requestedFilePathRejectedReason:n}}async getVideoDurationMs(e){const{stdout:t}=await(0,su.D9)(O$,"ffprobe",["-v","error","-show_entries","format=duration","-of","default=noprint_wrappers=1:nokey=1",e],{encoding:"utf8"}),r=parseFloat(t.trim());if(!Number.isFinite(r)||r<0)throw new Error(`Invalid video duration from ffprobe: ${t.trim()}`);return Math.floor(1e3*r)}async getVideoDimensions(e){const{stdout:t}=await(0,su.D9)(O$,"ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=width,height","-of","csv=p=0:s=x",e],{encoding:"utf8"}),[r,n]=t.trim().split("x"),o=Number.parseInt(r,10),s=Number.parseInt(n,10);if(!Number.isFinite(o)||!Number.isFinite(s))throw new Error(`Invalid video dimensions from ffprobe: ${t.trim()}`);if(o<=0||s<=0)throw new Error(`Invalid non-positive video dimensions from ffprobe: ${t.trim()}`);return{width:o,height:s}}async renderPolished(e,t){const r=s.join(t,"recording"),n=s.join(r,"recording_full.mp4");try{await this.polishedRenderer.renderRecordingSession({stagingSessionDir:t,outputVideoPath:n,fps:F$.PROXY_TARGET_FPS,includeBrandTag:!0}),await Co.access(n,Co.constants.R_OK)}catch(t){const r=(0,$.fU)(e);throw r?.setAttribute("error.type",M$(t)),r?.setStatus({code:2}),t}return n}async getVideoFramerate(e){try{const{stdout:t}=await(0,su.D9)(O$,"ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=r_frame_rate","-of","default=noprint_wrappers=1:nokey=1",e],{encoding:"utf8"}),r=t.trim();if(r.includes("/")){const[e,t]=r.split("/"),n=Number.parseFloat(e),o=Number.parseFloat(t);if(Number.isFinite(n)&&Number.isFinite(o)&&0!==o){const e=n/o;if(e>0&&e<500)return Math.round(e)}}else{const e=Number.parseFloat(r);if(Number.isFinite(e)&&e>0&&e<500)return Math.round(e)}console.warn(`[record-screen] Unexpected ffprobe r_frame_rate output "${r}", defaulting to ${F$.PROXY_TARGET_FPS}fps`)}catch(e){console.warn(`[record-screen] Failed to read video framerate: ${e instanceof Error?e.message:String(e)}, defaulting to ${F$.PROXY_TARGET_FPS}fps`)}return F$.PROXY_TARGET_FPS}async startFfmpegRecording(e,t){const r=s.join(t,"recording");await Co.mkdir(r,{recursive:!0});const n=s.join(r,"recording_render_proxy_1080p.mp4"),o="windowsDesktop"===e.kind?["-f","gdigrab","-i","desktop"]:["-video_size",e.resolution,"-framerate",String(await this.detectRefreshRate(e.display)),"-draw_mouse","0","-f","x11grab","-i",e.display],i=["-vf",`scale=${F$.PROXY_TARGET_WIDTH}:-2:flags=lanczos,fps=${F$.PROXY_TARGET_FPS}`,"-c:v","libx264","-preset",F$.PROXY_PRESET,"-crf",String(F$.PROXY_CRF),"-pix_fmt","yuv420p","-profile:v","high","-x264-params","keyint=1:min-keyint=1:scenecut=0:bframes=0","-movflags","+faststart","-tune","fastdecode"],a=["-vf",`scale=${F$.PROXY_TARGET_WIDTH}:-2:flags=lanczos`,"-c:v","libx264","-preset",F$.PROXY_PRESET,"-pix_fmt","yuv420p","-movflags","+faststart"],c=this.disablePolishedRendering?a:i,l=(0,su.D9)(ou.spawn,"ffmpeg",[...o,...c,"-y",n],{stdio:["win32"===process.platform?"pipe":"ignore","pipe","pipe"],detached:"win32"!==process.platform,windowsHide:!0}),u=new Promise(((e,t)=>{let r="",n=!1;l.stderr?.on("data",(t=>{r+=t.toString(),!n&&r.includes("frame=")&&(n=!0,e(Date.now()))}));const o=setTimeout((()=>{n||t(new Error("ffmpeg did not start encoding within 5 seconds"))}),5e3);l.once("exit",((e,r)=>{clearTimeout(o),n||t(new Error(`ffmpeg exited before starting: code=${e} signal=${r}`))})),l.once("error",(e=>{clearTimeout(o),n||t(new Error(`ffmpeg failed to start: ${e.message}`))}))}));return await new Promise(((e,t)=>{const r=setTimeout(e,300);l.once("error",(e=>{clearTimeout(r),t(new Error(`Failed to start ffmpeg: ${e.message}`))})),l.once("exit",((e,n)=>{clearTimeout(r),t(null!==e&&0!==e?new Error(`ffmpeg exited with code ${e}`):null!==n?new Error(`ffmpeg killed by signal ${n}`):new Error("ffmpeg exited unexpectedly during startup"))}))})),{process:l,videoStartedPromise:u}}async detectRefreshRate(e){try{return(await Wg(e)).display.refreshRate}catch(e){return console.warn(`[record-screen] Failed to detect refresh rate: ${e instanceof Error?e.message:String(e)}, using default ${F$.DEFAULT_REFRESH_RATE}Hz`),F$.DEFAULT_REFRESH_RATE}}async runFfmpegCommand(e,t){return await new Promise(((r,n)=>{const o=(0,su.D9)(ou.spawn,"ffmpeg",t,{stdio:["ignore","ignore","pipe"]});let s="";o.stderr?.on("data",(e=>{s.length<2e4&&(s+=e.toString())})),o.once("error",(t=>{n(new Error(`ffmpeg ${e} failed to start: ${t instanceof Error?t.message:String(t)}`))})),o.once("close",(t=>{0===t?r():n(new Error(`ffmpeg ${e} exited with code ${t}: ${s.trim()}`))}))}))}async saveRecordingDataPackage(e){const{sessionDir:t,durationMs:r,recordingStartEpochMs:n,ffmpegStartedEpochMs:o,inputEvents:i,resolution:a,renderProxies:c}=e,l=s.join(t,"recording"),u=s.join(l,"recording-data.json"),d=o-n,h=i.map((e=>({executionTimestampMs:e.executionTimestampMs,commandDurationMs:e.commandDurationMs,positionBefore:e.positionBefore,positionAfter:e.positionAfter,cursorTypeAfter:e.cursorTypeAfter,action:{action:this.serializeAction(e.action)}}))),p={version:3,durationMs:r,recordingStartEpochMs:n,ffmpegStartedEpochMs:o,eventToVideoOffsetMs:d,displayWidth:a.display.width,displayHeight:a.display.height,apiWidth:a.api.width,apiHeight:a.api.height,inputEvents:h,renderProxies:c??null};await Co.writeFile(u,JSON.stringify(p,null,2))}serializeAction(e){const{action:t}=e,r={case:t.case};switch(t.case){case"click":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null,button:t.value.button,count:t.value.count,modifierKeys:t.value.modifierKeys};break;case"mouseMove":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null};break;case"type":r.value={text:t.value.text};break;case"key":r.value={key:t.value.key,holdDurationMs:t.value.holdDurationMs};break;case"scroll":r.value={coordinate:t.value.coordinate?{x:t.value.coordinate.x,y:t.value.coordinate.y}:null,direction:t.value.direction,amount:t.value.amount,modifierKeys:t.value.modifierKeys};break;case"drag":r.value={path:t.value.path.map((e=>({x:e.x,y:e.y}))),button:t.value.button};break;case"wait":r.value={durationMs:t.value.durationMs};break;case"screenshot":case"cursorPosition":case"mouseDown":case"mouseUp":r.value=t.value;break;default:r.value={}}return r}async stopFfmpegRecording(e){const{childProcess:t}=e;if(I$(t)||!t.pid)return;const r=t.pid;return new Promise(((e,n)=>{const o=setTimeout((()=>{try{try{process.kill(-r,"SIGKILL")}catch{process.kill(r,"SIGKILL")}}catch{}n(new Error("Timeout waiting for ffmpeg to stop"))}),2e4);t.once("exit",(()=>{clearTimeout(o),e()})),t.once("error",(e=>{clearTimeout(o),n(new Error(`Error stopping ffmpeg: ${e.message}`))}));try{if(t.stdin)return t.stdin.on("error",(()=>{})),void t.stdin.end("q");try{process.kill(-r,"SIGTERM")}catch{process.kill(r,"SIGTERM")}}catch(t){if(clearTimeout(o),T$(t,"ESRCH"))return void e();n(new Error(`Failed to send SIGTERM: ${t instanceof Error?t.message:String(t)}`))}}))}async performSave(e,t,r){const n=Date.now();let o=P$.Wg.INTERNAL;try{const i=await(r.inputEventLogger?.stop())??[],a=r.inputEventLogger?.getRecordingStartTime()??r.startTime;let c;this.invokeStoppedCallbackIfCurrent(r);try{!I$(r.childProcess)&&r.childProcess.pid&&await this.stopFfmpegRecording(r)}catch(e){c=e,console.warn(`[record-screen] Failed to stop ffmpeg: ${A$(e)}`)}const l=r.ffmpegStartedEpochMs??a,u=r.sessionDir,d=s.join(u,"recording"),h=s.join(d,"recording_render_proxy_1080p.mp4");let p,f,m;try{await Co.access(h,Co.constants.R_OK)}catch(e){await this.cleanupRecording(r),this.clearActiveRecordingIfCurrent(r);const t=T$(e,"ENOENT"),o=t?`Recording proxy not found at ${h}`:`Recording proxy at ${h} could not be validated: ${A$(e)}`;return $$(t?P$.Wg.PROXY_MISSING:P$.Wg.STAGING_IO,D$(o,r,c,n))}try{if([p,f,m]=await Promise.all([this.getVideoDurationMs(h),this.getVideoDimensions(h),this.getVideoFramerate(h)]),p<=0)throw new Error(`Recording proxy has zero duration at ${h}`)}catch(e){await this.cleanupRecording(r);const t=A$(e),o=t.includes(h)?t:`Recording proxy at ${h} could not be validated: ${t}`;return $$(P$.Wg.PROXY_INVALID,D$(o,r,c,n))}const g={profileVersion:F$.PROXY_PROFILE_VERSION,generatedAtEpochMs:Date.now(),source:{width:f.width,height:f.height,durationMs:p,fps:m},artifacts:[{name:"render_proxy_1080p",path:"recording_render_proxy_1080p.mp4",width:f.width,height:f.height,fps:F$.PROXY_TARGET_FPS,codec:"h264",profile:F$.PROXY_PROFILE_VERSION,keyint:1,status:"success",elapsedMs:0}]};o=P$.Wg.STAGING_IO,void 0!==r.resolution&&await this.saveRecordingDataPackage({sessionDir:u,durationMs:p,recordingStartEpochMs:a,ffmpegStartedEpochMs:l,inputEvents:i,resolution:r.resolution,renderProxies:g}),o=P$.Wg.ARTIFACT_WRITE_FAILED;const{finalVideoPath:w,requestedFilePathRejectedReason:y}=await this.resolveArtifactVideoPath({saveAsFilename:t.saveAsFilename,stagingSessionDir:u});try{if(this.disablePolishedRendering)await Co.copyFile(h,w);else{o=P$.Wg.RENDER_FAILED;const t=await this.renderPolished(e,u);o=P$.Wg.ARTIFACT_WRITE_FAILED,await this.movePolishedVideo(t,w)}}catch(e){throw await Co.rm(w,{force:!0}).catch((()=>{})),e}try{await Co.rm(u,{force:!0,recursive:!0})}catch(e){console.warn(`[record-screen] Failed to remove staging session ${u}: ${A$(e)}`)}return this.clearActiveRecordingIfCurrent(r),new P$.Tj({result:{case:"saveSuccess",value:new P$.ol({path:w,recordingDurationMs:we.protoInt64.parse(p.toString()),requestedFilePathRejectedReason:y})}})}catch(e){return await this.cleanupRecording(r),this.invokeStoppedCallbackIfCurrent(r),$$("binding_load_failed"===M$(e)?P$.Wg.RENDERER_UNAVAILABLE:o,A$(e))}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,$.VI)(e.withName("LocalRecordScreenExecutor.execute")),!1);try{await this.ensureRecordingDirectoryExists()}catch(e){return $$(P$.Wg.STAGING_IO,`Failed to create recording directory: ${e instanceof Error?e.message:String(e)}. Ensure the parent directory exists and has write permissions, or run: sudo mkdir -p ${this.stagingDir} ${this.artifactsDir} && sudo chmod 777 ${this.stagingDir} ${this.artifactsDir}`)}if(t.mode===P$.$u.UNSPECIFIED)return $$(P$.Wg.INVALID_MODE,"Mode must be one of START_RECORDING, SAVE_RECORDING, DISCARD_RECORDING");switch(t.mode){case P$.$u.START_RECORDING:{this.recordingStoppedCallbackInvoked=!1;let e=!1;if(this.activeRecording){const t=this.activeRecording;if(!this.inFlightSaves.some((e=>e.state===t))){e=!0;try{await this.cleanupRecording(t),await Co.rm(t.sessionDir,{force:!0,recursive:!0}).catch((()=>{}))}catch{}}this.activeRecording=null}let r,n=null,o=null,s=P$.Wg.STAGING_IO;try{o=this.buildSessionDir(t.toolCallId||"recording"),await Co.mkdir(o,{recursive:!0}),s=P$.Wg.DISPLAY_UNAVAILABLE;const i="win32"===process.platform?void 0:await Wg(this.display),a=void 0===i?{kind:"windowsDesktop"}:{kind:"x11",display:this.display,resolution:i.resolutionString};s=P$.Wg.FFMPEG_START_FAILED;const{process:c,videoStartedPromise:l}=await this.startFfmpegRecording(a,o);n=c;const u=this.disablePolishedRendering?void 0:i?.resolution;void 0!==u&&(s=P$.Wg.INTERNAL,r=new Xg({displayNum:Ug(this.display),resolution:u}),await r.start());const d=r?.getRecordingStartTime()??Date.now();let h;s=P$.Wg.FFMPEG_START_FAILED;try{h=await l}catch(e){throw new Error(`ffmpeg failed to start encoding: ${e instanceof Error?e.message:String(e)}`)}const p={childProcess:n,sessionDir:o,startTime:d,inputEventLogger:r,resolution:u,ffmpegStartedEpochMs:h,ffmpegDiedEarly:!1,ffmpegDiedTime:null,ffmpegExitCode:null,ffmpegExitSignal:null};this.activeRecording=p,this.onRecordingStartedCallback&&r&&this.onRecordingStartedCallback(r),n.once("exit",((e,t)=>{p.ffmpegDiedEarly=!0,p.ffmpegDiedTime=Date.now(),p.ffmpegExitCode=e,p.ffmpegExitSignal=t}));const f=!!t.saveAsFilename;return new P$.Tj({result:{case:"startSuccess",value:new P$.T4({wasPriorRecordingCancelled:e,wasSaveAsFilenameIgnored:f})}})}catch(e){if(r)try{await r.stop()}catch{}if(n&&!n.killed&&n.pid)try{process.kill(n.pid,"SIGKILL")}catch{}return o&&await Co.rm(o,{force:!0,recursive:!0}).catch((()=>{})),this.activeRecording=null,$$(s,A$(e))}}case P$.$u.SAVE_RECORDING:{if(!this.activeRecording)return 1===this.inFlightSaves.length?await this.inFlightSaves[0].promise:$$(P$.Wg.NO_ACTIVE_RECORDING,"No active recording to save");const e=this.activeRecording,r=this.findInFlightSave(e);if(r)return await r.promise;const o=Promise.resolve().then((()=>this.performSave(n.ctx,t,e))),s={state:e,promise:o};this.inFlightSaves.push(s);try{return await o}finally{this.inFlightSaves=this.inFlightSaves.filter((e=>e!==s))}}case P$.$u.DISCARD_RECORDING:{if(!this.activeRecording)return $$(P$.Wg.NO_ACTIVE_RECORDING,"No active recording to discard");const e=this.activeRecording;if(this.findInFlightSave(e))return $$(P$.Wg.SAVE_IN_PROGRESS,"Save in progress for this recording; wait for it or start a new recording");let t=P$.Wg.INTERNAL;try{return await(e.inputEventLogger?.stop()),this.invokeStoppedCallbackOnce(),!I$(e.childProcess)&&e.childProcess.pid&&(t=P$.Wg.FFMPEG_STOP_FAILED,await this.stopFfmpegRecording(e)),t=P$.Wg.STAGING_IO,await Co.rm(e.sessionDir,{force:!0,recursive:!0}),this.activeRecording=null,new P$.Tj({result:{case:"discardSuccess",value:new P$.N8}})}catch(r){await this.cleanupRecording(e),this.invokeStoppedCallbackOnce();const n=e.sessionDir;let o=!1;try{await Co.rm(n,{force:!0,recursive:!0}),o=!0}catch{}this.activeRecording=null;return $$(t,`Failed to discard recording: ${r instanceof Error?r.message:String(r)}${o?"":`. Session may remain at: ${n}`}`)}}default:{const e=t.mode;return $$(P$.Wg.INVALID_MODE,`Unhandled recording mode: ${String(e)}`)}}}catch(e){r.error=e,r.hasError=!0}finally{R$(r)}}}async function N$(e){const t=await(0,Co.readdir)(e,{withFileTypes:!0}).catch((()=>[])),r=[];for(const n of t){const t=s.join(e,n.name),o={name:n.name,path:t,isDirectory:n.isDirectory()};n.isDirectory()&&(o.children=await N$(t)),r.push(o)}return r.sort(((e,t)=>e.isDirectory&&!t.isDirectory?-1:!e.isDirectory&&t.isDirectory?1:e.name.localeCompare(t.name)))}function L$(e,t="",r=!0){const n=[`${t}${r?"└── ":"├── "}${e.isDirectory?`${e.name}/`:e.name}`],o=e.children;if(o?.length){const e=t+(r?" ":"│ ");o.forEach(((t,r)=>{const s=r===o.length-1;n.push(...L$(t,e,s))}))}return n}async function j$(e){if(!await(0,Co.access)(e,Co.constants.R_OK).then((()=>!0),(()=>!1)))return"(No notes directory yet - will be created when you write your first note)";const t=await N$(e);return 0===t.length?"(Notes directory is empty)":t.flatMap(((e,r)=>L$(e,"",r===t.length-1))).join("\n")}async function U$(e,t){return j$(s.join(e,"agent-notes",t))}async function B$(e){return j$(s.join(e,"agent-notes","shared"))}F$.IN_FLIGHT_SAVE_DISPOSE_TIMEOUT_MS=3e4,F$.PROXY_TARGET_WIDTH=1920,F$.PROXY_TARGET_FPS=60,F$.PROXY_CRF=17,F$.PROXY_PRESET="veryfast",F$.PROXY_PROFILE_VERSION="render-proxy-h264-all-i-v1",F$.DEFAULT_REFRESH_RATE=60;var W$=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},H$=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const q$=3e3,z$=(0,l.h)("local-exec:request-context"),G$=Symbol("sectionLoadTimedOut");function V$(e,t){if(void 0===t)return e;let r;const n=new Promise((e=>{r=setTimeout((()=>e(G$)),t)}));return e.catch((()=>{})),Promise.race([e,n]).finally((()=>{clearTimeout(r)}))}class K${async read(e,t){const r=this.inFlight??this.begin(e),n=this.last;if(void 0===n)return r;const o=await V$(r,t).catch((()=>G$));return o===G$?n.value:o}prefetch(e){void 0===this.inFlight&&this.begin(e).catch((()=>{}))}begin(e){const t=e();this.inFlight=t;const r=()=>{this.inFlight===t&&(this.inFlight=void 0)};return t.then((e=>{this.last={value:e},r()}),r),t}}async function J$(e,t,r,n){const o={stack:[],error:void 0,hasError:!1};try{W$(o,(0,$.VI)(e.withName("LocalRequestContextExecutor.getGitStatusForRepoPath")),!1);try{return(await t.exec(e,r,["--no-optional-locks","status","--short","--branch"],{timeout:n,caller:"getGitStatusForRepoPath"})).stdout}catch{return}}catch(e){o.error=e,o.hasError=!0}finally{H$(o)}}async function Z$(e,t,r,n){try{const o=(await t.exec(e,r,["rev-parse","--abbrev-ref","HEAD"],{timeout:n,caller:"getGitBranchForRepoPath"})).stdout.trim();if("HEAD"===o||0===o.length)return;return o}catch{return}}async function X$(e,t,r,n){const o=e=>{let t;const r=new Promise((e=>{t=setTimeout((()=>{e(void 0)}),n)}));return Promise.race([e.catch((()=>{})),r]).finally((()=>{void 0!==t&&clearTimeout(t)}))},[s,i]=await Promise.all([o(J$(e,t,r,n)),o(Z$(e,t,r,n))]);return{status:s,branchName:i}}async function Q$(e,t,r={}){const{projectDir:n,notesSessionId:s,agentNotesEnabled:i,reportProcessWorkingDirectory:a,getSmartModeClassifierAutoModeEnabled:c,devForceNextSmartModeClassifierBlockToken:l,isWorkingDirHomeDir:u,getSandboxEnabled:d,getSandboxSupported:h,getNetworkAllowlistInfo:p,userTerminalHint:f,artifactsFolder:m,secretRedactionEnabled:g,getComputerUseSupported:w,getComputerUseDesktop:y,getMockPromptTime:v}=r,b=y?.(),S=`${o.default.platform()} ${o.default.release()}`,k=(0,Oo.G6)(f),_=v?.(),C=(()=>{try{return(new Intl.DateTimeFormat).resolvedOptions().timeZone??void 0}catch{return}})(),E=n,x=n?`${n}/terminals`:void 0,P=n&&!1!==i?`${n}/agent-notes/shared`:void 0,R=n&&s&&!1!==i?`${n}/agent-notes/${s}`:void 0,I=n?`${n}/agent-transcripts`:void 0,T=!!d&&d(),A=h?.(),$=c?.();let M;if(p)try{const e=await V$(p(),3e3);e!==G$&&(M=e)}catch{M=void 0}return new Dr.GE({osVersion:S,workspacePaths:t,shell:k,sandboxEnabled:T,projectFolder:E,terminalsFolder:x,agentSharedNotesFolder:P,agentConversationNotesFolder:R,agentTranscriptsFolder:I,timeZone:C,...!1!==a&&{processWorkingDirectory:process.cwd()},artifactsFolder:m,...void 0!==$&&{smartModeClassifierAutoModeEnabled:$},...void 0!==l&&{devForceNextSmartModeClassifierBlockToken:l},...void 0!==_&&{devMockPromptTime:we.Timestamp.fromDate(_)},...void 0!==g&&{secretRedactionEnabled:g},...void 0!==A&&{sandboxSupported:A},...void 0!==M?.hasDefaults&&{sandboxNetworkHasDefaults:M.hasDefaults},...M?.explicitEntries&&M.explicitEntries.length>0&&{sandboxNetworkExplicitAllowlist:M.explicitEntries},...void 0!==w&&{computerUseSupported:w()},...void 0!==b&&{computerUseDesktop:b},...void 0!==u&&{isWorkingDirHomeDir:u}})}const Y$={type:"object",properties:{},additionalProperties:!1};function eM(e,t){return{tools:(!0===t?.internalBrowserProvidersOnly?e.servers.filter((e=>Kn.has(e.serverIdentifier))):e.servers).flatMap((e=>e.tools)).map((e=>new wn.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,...!0===t?.inputSchemaJson?{inputSchemaJson:void 0===e.inputSchema?void 0:JSON.stringify(e.inputSchema)}:{inputSchema:e.inputSchema?we.Value.fromJson(e.inputSchema):void 0}}))),mcpInstructions:e.servers.flatMap((e=>e.instructions))}}function tM(e,t){const r=!0===t?.slimDescriptors,n=e.servers.map((e=>{const n=e.instructions.map((e=>e.instructions)).filter(Boolean).join("\n"),o=e.tools.map((e=>new wn.E$({toolName:e.toolName,...Db(e.annotations),...r?{}:{description:e.description,...!0===t?.inputSchemaJson?{inputSchemaJson:void 0===e.inputSchema?void 0:JSON.stringify(e.inputSchema)}:{inputSchema:void 0!==e.inputSchema?we.Value.fromJson(e.inputSchema):void 0}}})));return!Vn(e.serverIdentifier)||!0!==t?.alwaysExposeVirtualMcpAuthTool&&"needsAuth"!==e.status||o.some((e=>e.toolName===nT))||o.push(new wn.E$({toolName:nT,...r?{}:{description:oT,...!0===t?.inputSchemaJson?{inputSchemaJson:JSON.stringify(Y$)}:{inputSchema:we.Value.fromJson(Y$)}}})),new wn.UC({serverIdentifier:e.serverIdentifier,serverName:e.serverName,plugin:e.plugin,marketplace:e.marketplace,pluginDbId:e.pluginId,marketplaceId:e.marketplaceId,serverUseInstructions:n||void 0,tools:o})}));return new wn.U_({enabled:!0,mcpDescriptors:n})}function rM(e){const t=e?.trim();return t||void 0}function nM(e,t){const r=function(e){return rM(e.serverIdentifier)}(e);if(r)return r;const n=rM(e.serverName);return n?t.get(n)??n:void 0}class oM{constructor(e){this.mcpLease=e}async getState(e){const[t,r]=await Promise.all([this.mcpLease.getTools(e).catch((t=>(z$.warn(e,"Error fetching MCP tools",{error:t}),[]))),this.mcpLease.getInstructions(e).catch((t=>(z$.warn(e,"Error fetching MCP instructions",{error:t}),[])))]);return function(e,t,r,n=!1){const o=new Map;for(const t of e)o.has(t.providerIdentifier)||o.set(t.providerIdentifier,t.clientKey);const s=t.map((e=>nM(e,o))).filter((e=>Boolean(e))),i=[...new Set([...e.map((e=>e.clientKey)),...s,...Array.from(r?.entries()??[]).filter((([,e])=>"connected"!==e.status)).map((([e])=>e))])];if(n&&void 0!==r){const e=new Map(Array.from(r.keys(),((e,t)=>[e,t])));i.sort(((t,r)=>(e.get(t)??e.size)-(e.get(r)??e.size)))}return{servers:i.map((n=>{const s=e.filter((e=>e.clientKey===n));return{serverName:s[0]?.providerIdentifier??n,serverIdentifier:n,plugin:s[0]?.plugin,marketplace:s[0]?.marketplace,tools:s,instructions:t.filter((e=>nM(e,o)===n)),status:r?.get(n)?.status,errorMessage:r?.get(n)?.errorMessage}}))}}(t,r,await async function(e,t){const r=await t.getClients(e).catch((t=>(z$.warn(e,"Error fetching MCP clients",{error:t}),{}))),n=await Promise.all(Object.entries(r).map((async([t,r])=>{const n=await r.getState(e).catch((()=>({kind:"error",message:"Failed to fetch MCP client state"})));return[t,{status:Yn(n),errorMessage:"error"===n.kind&&void 0!==n.message?n.message:void 0}]})));return new Map(n)}(e,this.mcpLease))}}function sM(e){return new Ac._W({result:{case:"success",value:new Ac.pv({servers:e.servers.map((e=>new Ac.XE({serverName:e.serverName,serverIdentifier:e.serverIdentifier,plugin:e.plugin,marketplace:e.marketplace,tools:e.tools.map((e=>new wn.gd({name:e.name,providerIdentifier:e.providerIdentifier,toolName:e.toolName,description:e.description,inputSchema:e.inputSchema?we.Value.fromJson(e.inputSchema):void 0,metaJson:Jn(e._meta),...Db(e.annotations)}))),instructions:e.instructions,status:e.status,errorMessage:e.errorMessage})))})}})}class iM{constructor(e,t,r){this.mcpStateAccessor=e,this.ensureMcpServersLoaded=t,this.options=r}async execute(e,t){if(void 0!==t.ruleSubjects&&void 0!==this.options?.serverRuleSubjects)return function(e,t){const r={commandPatterns:t.commandPatterns,serverUrlPatterns:t.serverUrlPatterns},n=[];for(const[t,o]of e){const e=void 0!==o.command?{transport:Ac.zj.STDIO,value:o.command,matched:{command:o.command}}:void 0!==o.url?{transport:Ac.zj.HTTP,value:o.url,matched:{url:o.url}}:void 0;void 0!==e&&n.push(new Ac.XE({serverName:t,serverIdentifier:t,ruleSubject:new Ac.D0({transport:e.transport,...xC(e.matched,r)?{value:e.value}:{}})}))}return new Ac._W({result:{case:"success",value:new Ac.pv({servers:n})}})}(this.options.serverRuleSubjects(),t.ruleSubjects);try{await(this.ensureMcpServersLoaded?.(e,t.serverIdentifiers,{wait:!t.kickOnly}))}catch{}t.refreshPolicy!==Ac.ew.FORCE_IF_MISSING&&t.refreshPolicy!==Ac.ew.FORCE||await(this.mcpStateAccessor.refreshNow?.(e));const r=await this.mcpStateAccessor.getState(e);if(!0===this.options?.filterToRequestedServers&&t.serverIdentifiers.length>0){const e=new Set(t.serverIdentifiers),n=r.servers.filter((t=>e.has(t.serverIdentifier)));if(n.length>0)return sM({...r,servers:n})}return sM(r)}}class aM{constructor(e,t,r,n,o,s,i,a,c={}){this.cursorRulesService=e,this.cloudRulesService=t,this.subagentsService=r,this.repositoryProvider=n,this.grepProvider=o,this.mcpStateAccessor=s,this.gitExecutor=i,this.workspacePaths=a,this.reusedGitInfo=new Map,this.reusedMcpState=new K$,this.reusedAgentSkills=new K$,this.reusedAdminCommandDenylist=new K$,this.cachedWorkspaces=new Map,this.inFlightWorkspaceWarms=new Map;const{projectDir:l,getSmartModeClassifierAutoModeEnabled:u,getAdminCommandDenylist:d,devForceNextSmartModeClassifierBlockToken:h,isWorkingDirHomeDir:p,agentNotesEnabled:f,reportProcessWorkingDirectory:m,createFileWatcher:g,getSandboxEnabled:w,getSandboxSupported:y,getNetworkAllowlistInfo:v,userTerminalHint:b,getMcpFileSystemOptions:S,mcpMetaToolEnabled:k,mcpMetaToolSlimDescriptors:_,mcpInputSchemaJson:C,alwaysExposeVirtualMcpAuthTool:E,getArtifactsFolder:x,secretRedactionEnabled:P,attributionConfigProvider:R,isAttributionDisabledByAdmin:I,getAgentSkills:T,additionalRules:A,getComputerUseSupported:$,getComputerUseDesktop:M,getMockPromptTime:D}=c;this.projectDir=l,this.isWorkingDirHomeDir=p,this.agentNotesEnabled=f??!0,this.reportProcessWorkingDirectory=m??!0,this.getSandboxEnabled=w,this.getSandboxSupported=y,this.getNetworkAllowlistInfo=v,this.getSmartModeClassifierAutoModeEnabled=u,this.getAdminCommandDenylist=d,this.devForceNextSmartModeClassifierBlockToken=h,this.getMockPromptTime=D,this.userTerminalHint=b,this.getMcpFileSystemOptions=S,this.mcpMetaToolEnabled=k??!1,this.mcpMetaToolSlimDescriptors=_??!1,this.mcpInputSchemaJson=C??!1,this.alwaysExposeVirtualMcpAuthTool=E??!1,this.getArtifactsFolder=x,this.secretRedactionEnabled=P,this.attributionConfigProvider=R,this.isAttributionDisabledByAdmin=I,this.getAgentSkills=T,this.additionalRules=A??[],this.getComputerUseSupported=$,this.getComputerUseDesktop=M,this.reduceContextHotPath=c.reduceContextHotPath??!1,this.sectionLoadTimeoutMs=c.sectionLoadTimeoutMs,this.reportSectionCompleteness=c.reportSectionCompleteness??!1,this.freshSectionWaitMs=c.freshSectionWaitMs,this.onRequestContext=c.onRequestContext,this.mcpFieldsFromCaller=c.mcpFieldsFromCaller??!1,!0!==c.deferWarmup&&this.warm(),void 0!==g&&(this.fileWatcher=g(),this.fileWatcher.onDidChange((e=>{this.onWorkspacePathChanged(e)})),this.fileWatcher.onDidCreate((e=>{this.onWorkspacePathChanged(e)})),this.fileWatcher.onDidDelete((e=>{this.onWorkspacePathChanged(e)})))}warm(){this.warmWorkspaceCaches(),void 0===this.globalCache&&this.rebuildGlobalCache()}onWorkspacePathChanged(e){this.rebuildAllCaches()}getWorkspaceCache(e){return this.cachedWorkspaces.get(e)}warmWorkspaceCaches(){const e=(0,y.q6)();Promise.all(this.workspacePaths.map((t=>this.ensureWorkspaceCacheWarm(e,t))))}ensureWorkspaceCacheWarm(e,t){if(this.cachedWorkspaces.has(t))return Promise.resolve();const r=this.inFlightWorkspaceWarms.get(t);if(void 0!==r)return r;const n=this.warmWorkspaceCache(e,t).finally((()=>{this.inFlightWorkspaceWarms.delete(t)}));return this.inFlightWorkspaceWarms.set(t,n),n}async warmWorkspaceCache(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=W$(r,(0,$.VI)(e.withName("LocalRequestContextExecutor.warmWorkspaceCache")),!1),o=await Ya(n.ctx,this.gitExecutor,t),s=o?await sc(n.ctx,this.gitExecutor,o):void 0,i={repoPath:o??void 0,remoteUrl:void 0!==s?ic(s):void 0};if(this.cachedWorkspaces.set(t,i),void 0!==this.freshSectionWaitMs&&void 0!==i.repoPath){const e=i.repoPath;this.gitInfoSection(e).prefetch((()=>X$((0,y.q6)(),this.gitExecutor,e,q$)))}}catch(e){r.error=e,r.hasError=!0}finally{H$(r)}}gitInfoSection(e){let t=this.reusedGitInfo.get(e);return void 0===t&&(t=new K$,this.reusedGitInfo.set(e,t)),t}rebuildAllCaches(){this.cacheDebounceTimeout&&clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=setTimeout((()=>{this.cacheDebounceTimeout=void 0,this.rebuildGlobalCache()}),5e3)}invalidateGlobalCache(){this.globalCache=void 0,this.lastGoodGlobalCache=void 0,this.globalCacheTraceId=void 0}refreshGlobalCache(){this.cacheDebounceTimeout&&(clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=void 0),this.rebuildGlobalCache()}rebuildGlobalCache(){const e={stack:[],error:void 0,hasError:!1};try{const t=(0,y.q6)(),r=W$(e,(0,$.VI)(t.withName("LocalRequestContextExecutor.rebuildGlobalCache")),!1);this.globalCacheTraceId=r.span.spanContext().traceId;const n=this.computeGlobalCache(r.ctx);return this.globalCache=n,(this.reduceContextHotPath||void 0!==this.sectionLoadTimeoutMs||void 0!==this.freshSectionWaitMs)&&n.then((e=>{this.globalCache===n&&(this.lastGoodGlobalCache=e)}),(()=>{this.globalCache===n&&(this.globalCache=void 0)})),n}catch(t){e.error=t,e.hasError=!0}finally{H$(e)}}async computeGlobalCache(e){const t={stack:[],error:void 0,hasError:!1};try{const r=W$(t,(0,$.VI)(e.withName("LocalRequestContextExecutor.computeGlobalCache")),!1),n=AbortSignal.timeout(1e3),o=performance.now(),s={},i=(e,t)=>{const r=performance.now();return t.finally((()=>{s[e]=Math.round(performance.now()-r)}))},[a,c,l,u]=await Promise.all([i("cursorRules",this.cursorRulesService.getAllCursorRules(r.ctx)),i("cloudRule",this.cloudRulesService?this.cloudRulesService.getCloudRule(r.ctx):Promise.resolve(null)),i("codebaseRef",this.repositoryProvider.getCodebaseReference(r.ctx,n).catch((()=>{}))),i("subagents",this.subagentsService?this.subagentsService.getAllSubagents().catch((()=>[])):Promise.resolve([]))]),d=Math.round(performance.now()-o);return d>1e3&&z$.warn(r.ctx,"computeGlobalCache: slow",{totalMs:d,...s,ruleCount:a.length}),{rules:[...this.additionalRules,...a],cloudRule:c,codebaseReference:l,customSubagents:u}}catch(e){t.error=e,t.hasError=!0}finally{H$(t)}}dispose(){this.cacheDebounceTimeout&&(clearTimeout(this.cacheDebounceTimeout),this.cacheDebounceTimeout=void 0),this.fileWatcher&&(this.fileWatcher.dispose(),this.fileWatcher=void 0),this.globalCache=void 0,this.lastGoodGlobalCache=void 0}async collectWorkspaceCaches(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=W$(r,(0,$.VI)(e.withName("LocalRequestContextExecutor.collectWorkspaceCaches")),!1);let o;if(this.grepProvider.getTrackedState)try{o=await this.grepProvider.getTrackedState(this.workspacePaths)}catch{o=void 0}let s=!0,i=!0;return{gitRepos:(await Promise.all(this.workspacePaths.map((async e=>{let r=this.getWorkspaceCache(e);if(void 0===r){if(!t.waitForWorkspaceCache)return s=!1,void this.ensureWorkspaceCacheWarm(n.ctx,e);if(await this.ensureWorkspaceCacheWarm(n.ctx,e),r=this.getWorkspaceCache(e),void 0===r)return void(s=!1)}const a=o?.[e];if(void 0!==a)return void 0!==r.repoPath&&void 0===a.gitStatus&&(i=!1),new Dr.DS({path:r.repoPath,status:a.gitStatus,branchName:a.gitBranchName,remoteUrl:r.remoteUrl,isOriginBacked:Ja(r.remoteUrl)});if(void 0===r.repoPath)return;const c=r.repoPath,{status:l,branchName:u}=void 0===this.freshSectionWaitMs?await X$(n.ctx,t.gitExecutor,c,q$):await this.gitInfoSection(c).read((()=>X$((0,y.q6)(),t.gitExecutor,c,q$)),this.freshSectionWaitMs);return void 0===l&&(i=!1),new Dr.DS({path:r.repoPath,status:l,branchName:u,remoteUrl:r.remoteUrl,isOriginBacked:Ja(r.remoteUrl)})})))).filter((e=>void 0!==e)),gitRepoInfoComplete:s,gitStatusInfoComplete:s&&i}}catch(e){r.error=e,r.hasError=!0}finally{H$(r)}}shareBoundedSectionLoad(e,t,r){if(void 0===this.sectionLoadTimeoutMs)return r();const n=e();if(void 0!==n)return n;const o=r();t(o);const s=()=>{e()===o&&t(void 0)};return o.then(s,s),o}async computeCachedRequestContext(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=W$(n,(0,$.VI)(e.withName("LocalRequestContextExecutor.computeCachedRequestContext")),!1),s=this.projectDir,i=async()=>{const e={stack:[],error:void 0,hasError:!1};try{const t=W$(e,(0,$.VI)(o.ctx.withName("LocalRequestContextExecutor.computeCachedRequestContext.getGlobalData")),!1);if(this.globalCacheTraceId&&t.span.setAttribute("cacheTraceId",this.globalCacheTraceId),!this.reduceContextHotPath&&void 0===this.freshSectionWaitMs){if(void 0===this.globalCache){const e=this.computeGlobalCache(o.ctx);this.globalCache=e,e.catch((()=>{this.globalCache===e&&(this.globalCache=void 0)})),void 0!==this.sectionLoadTimeoutMs&&e.then((t=>{this.globalCache===e&&(this.lastGoodGlobalCache=t)}),(()=>{}))}return this.globalCache}return void 0!==this.lastGoodGlobalCache?this.lastGoodGlobalCache:this.globalCache??this.rebuildGlobalCache()}catch(t){e.error=t,e.hasError=!0}finally{H$(e)}},a=performance.now(),c={},l=(e,t)=>{const r=performance.now();return t.finally((()=>{c[e]=Math.round(performance.now()-r)}))},u=e=>V$(e,this.sectionLoadTimeoutMs),d=(e,t,r)=>this.shareBoundedSectionLoad(e,t,r),h=this.freshSectionWaitMs,p=(e,t)=>void 0===h?t():e.read(t,h),f=void 0===h?o.ctx:(0,y.q6)(),[m,g,w,{gitRepos:v,gitRepoInfoComplete:b,gitStatusInfoComplete:S},k,_,C,E,x,P]=await Promise.all([l("globalCache",u(i())),l("mcpState",this.mcpFieldsFromCaller?Promise.resolve({servers:[]}):u(p(this.reusedMcpState,(()=>d((()=>this.inFlightMcpState),(e=>{this.inFlightMcpState=e}),(()=>this.mcpStateAccessor.getState(f))))))),l("env",Q$(o.ctx,this.workspacePaths,{projectDir:s,notesSessionId:t.notesSessionId,agentNotesEnabled:this.agentNotesEnabled,reportProcessWorkingDirectory:this.reportProcessWorkingDirectory,getSmartModeClassifierAutoModeEnabled:this.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:this.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:this.getMockPromptTime,isWorkingDirHomeDir:this.isWorkingDirHomeDir,getSandboxEnabled:this.getSandboxEnabled,getSandboxSupported:this.getSandboxSupported,getNetworkAllowlistInfo:this.getNetworkAllowlistInfo,userTerminalHint:this.userTerminalHint,artifactsFolder:this.getArtifactsFolder?.(o.ctx),secretRedactionEnabled:this.secretRedactionEnabled,getComputerUseSupported:this.getComputerUseSupported,getComputerUseDesktop:this.getComputerUseDesktop})),l("git",this.collectWorkspaceCaches(o.ctx,{waitForWorkspaceCache:!0===t.waitForWorkspaceCache,gitExecutor:r})),l("conversationNotes",this.agentNotesEnabled&&s&&t.notesSessionId?U$(s,t.notesSessionId):Promise.resolve(void 0)),l("sharedNotes",this.agentNotesEnabled&&s?B$(s):Promise.resolve(void 0)),l("mcpFileSystemOptions",this.getMcpFileSystemOptions?this.getMcpFileSystemOptions(o.ctx,{timeoutMs:3e3}):Promise.resolve(void 0)),l("attribution",this.isAttributionDisabledByAdmin?this.isAttributionDisabledByAdmin().catch((()=>!0)):Promise.resolve(!1)),l("agentSkills",u(p(this.reusedAgentSkills,(()=>d((()=>this.inFlightAgentSkills),(e=>{this.inFlightAgentSkills=e}),(()=>this.getAgentSkills?this.getAgentSkills(f):Promise.resolve([]))))))),l("adminCommandDenylist",u(p(this.reusedAdminCommandDenylist,(()=>d((()=>this.inFlightAdminCommandDenylist),(e=>{this.inFlightAdminCommandDenylist=e}),(()=>this.getAdminCommandDenylist?this.getAdminCommandDenylist():Promise.resolve(void 0)))))))]),R=m===G$,I=g===G$,T=x===G$,A=P===G$,M=R?this.lastGoodGlobalCache??{rules:[...this.additionalRules],cloudRule:null,codebaseReference:void 0,customSubagents:[]}:m,D=I?{servers:[]}:g,O=T?[]:x,F=A?void 0:P;(R||I||T||A)&&z$.warn(o.ctx,"computeCachedRequestContext: section load timed out",{timeoutMs:this.sectionLoadTimeoutMs,rulesAndSubagents:R,mcpState:I,agentSkills:T,adminCommandDenylist:A});const N=performance.now()-a;for(const[e,t]of Object.entries(c))o.span.setAttribute(`requestContext.timing.${e}Ms`,t);o.span.setAttribute("requestContext.timing.totalMs",Math.round(N)),N>1e3&&z$.warn(o.ctx,"computeCachedRequestContext: slow parallel data collection",{durationMs:Math.round(N),...c});const L=this.mcpMetaToolEnabled?tM(D,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,slimDescriptors:this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}):void 0,j=this.attributionConfigProvider?.get(),U=!E&&(j?.attribution?.attributeCommitsToAgent??!0),B=!E&&(j?.attribution?.attributePRsToAgent??!0),W=new Dr.bb({rules:M.rules,env:w,gitRepos:v,gitRepoInfoComplete:b,repositoryInfo:M.codebaseReference?[{relativeWorkspacePath:M.codebaseReference.relativeWorkspacePath,repoName:M.codebaseReference.repoName,repoOwner:M.codebaseReference.repoOwner,isTracked:M.codebaseReference.isTracked,isLocal:M.codebaseReference.isLocal,orthogonalTransformSeed:M.codebaseReference.orthogonalTransformSeed,pathEncryptionKey:M.codebaseReference.pathEncryptionKey}]:[],...eM(D,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}),conversationNotesListing:k,sharedNotesListing:_,customSubagents:M.customSubagents,mcpFileSystemOptions:C,mcpMetaToolOptions:L,supportsMcpAuth:!0,commitAttributionMessage:U?"enabled":void 0,prAttributionMessage:B?"enabled":void 0,agentSkills:O,adminCommandDenylist:F?.rules??[]});return null!==M.cloudRule&&void 0!==M.cloudRule&&(W.cloudRule=M.cloudRule),this.reportSectionCompleteness&&(W.rulesInfoComplete=!R,W.customSubagentsInfoComplete=!R,W.agentSkillsInfoComplete=!T,W.mcpInfoComplete=!I,W.mcpFileSystemInfoComplete=this.mcpMetaToolEnabled||void 0!==C,W.envInfoComplete=!0,W.gitStatusInfoComplete=S),W}catch(e){n.error=e,n.hasError=!0}finally{H$(n)}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{this.onRequestContext?.();const n=W$(r,(0,$.VI)(e.withName("LocalRequestContextExecutor.execute")),!1);n.span.setAttribute("enableCaching",void 0!==this.fileWatcher),n.span.setAttribute("hasGlobalCache",!!this.globalCache);try{const e=this.gitExecutor.forRequest?.()??this.gitExecutor,r=await this.computeCachedRequestContext(n.ctx,t,e);return new Dr._G({result:{case:"success",value:new Dr.yW({requestContext:r})}})}catch(e){return e instanceof Error||"string"==typeof e?n.span.recordException(e):n.span.recordException(kc(e)),new Dr._G({result:{case:"error",value:new Dr.nf({error:e instanceof Error?e.message:String(e)})}})}}catch(e){r.error=e,r.hasError=!0}finally{H$(r)}}}function cM(e){return 0!==e.timeout?e.timeout:e.isBackground||e.timeoutBehavior===he._d.BACKGROUND||void 0!==e.hardTimeout&&e.hardTimeout>0?0:3e4}var lM=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});class uM{constructor(e,t,r,n){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r}buildResultFromExit(e){return 0===(e.exitCode??-1)?new he.W4({result:{case:"success",value:new he.QR({...e,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:us(e.sandboxPolicy)}):new he.W4({result:{case:"failure",value:new he.xC({...e,aborted:void 0!==e.abortReason,stdout:e.outputLocation?"":e.stdout,stderr:e.outputLocation?"":e.stderr})},sandboxPolicy:us(e.sandboxPolicy)})}async executeWithPolicy(e,t,r,n,o){const s=Date.now(),i=new AbortController,a=e.signal?AbortSignal.any([e.signal,i.signal]):i.signal,c=setTimeout((()=>{i.abort()}),n);try{let n,l,u,d="",h="",p=null;const f=o?{perUser:o}:void 0;for await(const o of this.coreExecutor.execute(e,{command:t.command,workingDirectory:r,signal:a,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:f,fileOutputThresholdBytes:t.fileOutputThresholdBytes,pipeStdin:!1}))"stdout"===o.type?d+=o.data:"stderr"===o.type?h+=o.data:"exit"===o.type&&(p=null!=o.code?0|o.code:null,l=o.outputLocation,n=o.aborted?a.aborted?i.signal.aborted&&a.reason===i.signal.reason?he.Lv.TIMEOUT:he.Lv.USER_ABORT:he.Lv.UNSPECIFIED:void 0,u=$y(o.localExecutionTimeMs));clearTimeout(c);const m=Date.now()-s,g={command:t.command,workingDirectory:r,exitCode:void 0!==n?-1:p??-1,signal:void 0!==n?"SIGTERM":"",abortReason:n,stdout:d,stderr:h,executionTime:m,localExecutionTimeMs:u,sandboxPolicy:o,outputLocation:l};return this.buildResultFromExit(g)}catch(s){return clearTimeout(c),i.signal.aborted&&!e.signal.aborted?new he.W4({result:{case:"timeout",value:new he.eG({command:t.command,workingDirectory:r,timeoutMs:n})},sandboxPolicy:us(o)}):e.signal.aborted?new he.W4({result:{case:"rejected",value:new he.pZ({command:t.command,workingDirectory:r,reason:"Command aborted"})},sandboxPolicy:us(o)}):new he.W4({result:{case:"spawnError",value:new he.mJ({command:t.command,workingDirectory:r,error:s instanceof Error?s.message:"Unknown error"})},sandboxPolicy:us(o)})}}async execute(e,t){const r={stack:[],error:void 0,hasError:!1};try{const n=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,$.VI)(e.withName("LocalShellExecutor.execute")),!1).ctx;(0,$.HF)(n,"LocalShellExecutor.execute");const o=t.command,s=t.requestedSandboxPolicy?ls(t.requestedSandboxPolicy):void 0,i=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),a=cM(t),c=(0,Yo.o1)(i);if(!t.parsingResult)return new he.W4({result:{case:"spawnError",value:new he.mJ({command:o,workingDirectory:c,error:"Parsing result is required"})}});let l;if(Mo(t)){const e=await this.permissionsService.shouldEnforceShellInvariantBlocks(n,{workingDirectory:c,skipUnsafeWorkingDirectoryBlock:!0,command:o,parsingResult:t.parsingResult,toolCallId:t.toolCallId,resolveSkippedApprovalPolicy:!0},s);if("block"===e.kind)return new he.W4({result:ed(o,c,e.reason)});l=e.policy??s}else{const e=await this.permissionsService.shouldBlockShellCommand(n,o,{workingDirectory:c,timeout:a,parsingResult:t.parsingResult,toolCallId:t.toolCallId,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Ao(t)},s);if("block"===e.kind)return new he.W4({result:ed(o,c,e.reason)});l=e.policy}return l=await Tc(l,{command:o,workingDirectory:c,parsingResult:t.parsingResult,permissionsService:this.permissionsService,ignoreService:this.ignoreService}),this.executeWithPolicy(n,t,i,a,l)}catch(e){r.error=e,r.hasError=!0}finally{lM(r)}}}var dM=r("../proto/dist/generated/agent/v1/shell_allowlist_precheck_exec_pb.js");class hM{constructor(e){this.permissionsService=e}async execute(e,t){const r=t.parsingResult??new he.HO,n=await this.permissionsService.isShellCommandFullyAllowlisted(e,t.command,{workingDirectory:t.workingDirectory,parsingResult:r,classifierResult:t.classifierResult,toolCallId:t.toolCallId});return new dM.e({allowlisted:n})}}class pM{constructor(e){this.shellStreamExecutor=e}async execute(e,t,r){return""===t.toolCallId.trim()?new he.jK({status:he.iA.NOT_FOUND}):this.shellStreamExecutor.forceBackgroundByToolCallId(e,t.toolCallId)}}var fM=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const mM=(0,l.h)("local-exec:shell-stream");class gM{constructor(e,t){this.iterator=e,this.timeoutMs=t,this.pendingPromise=null,this.stopPromise=new Promise((e=>{this.stopResolve=e}))}stop(e){return void 0===this.stopReason&&(this.stopReason=e,this.stopResolve?.(),!0)}get timedOut(){return"background"===this.stopReason?.kind&&this.stopReason.reason===he.Jg.TIMEOUT}get backgroundRequested(){return"background"===this.stopReason?.kind}get backgroundReasonValue(){return"background"===this.stopReason?.kind?this.stopReason.reason:void 0}get stopReasonValue(){return this.stopReason}async*iterate(){this.timer=setTimeout((()=>{this.stop({kind:"background",reason:he.Jg.TIMEOUT})}),this.timeoutMs);try{for(;;){if(void 0!==this.stopReason)return;this.pendingPromise=this.iterator.next();const e=await Promise.race([this.pendingPromise.then((e=>({kind:"result",result:e}))),this.stopPromise.then((()=>({kind:"stopped"})))]);if("stopped"===e.kind)return;if(this.pendingPromise=null,e.result.done)return;yield e.result.value}}finally{clearTimeout(this.timer)}}requestBackground(){return this.stop({kind:"background",reason:he.Jg.USER_REQUEST})}abort(){this.stop({kind:"abort"})}getHandoffIterator(){if(this.pendingPromise){const e=this.pendingPromise;this.pendingPromise=null;let t=!1;return{next:async()=>t?this.iterator.next():(t=!0,e)}}return this.iterator}}function wM(){let e=()=>{};return{promise:new Promise((t=>{e=t})),resolve:e}}class yM{constructor(e,t,r,n){this.permissionsService=e,this.coreExecutor=t,this.ignoreService=r,this.backgroundShellManager=n,this.activeForegroundExecutions=new Map,this.pendingShells=new Map}hasForegroundWork(){return this.activeForegroundExecutions.size>0||this.pendingShells.size>0}async forceBackgroundByToolCallId(e,t){const r=this.pendingShells.get(t),n=void 0===r||r.awaitingApproval?this.activeForegroundExecutions.get(t):await async function(e,t){const[r,n]=e.withCancel();try{return await Promise.race([t.registered.promise,(0,y.uk)(r).then((()=>{}))])}finally{n()}}(e,r),o=n?.requestBackground();return o?new he.jK({status:he.iA.ACCEPTED,shellResult:o}):new he.jK({status:he.iA.NOT_FOUND})}pendingFrom(e){return{execute:(t,r,n)=>this.whilePending(r,(()=>e.get(ee).execute(t,r,n)))}}execute(e,t){return this.whilePending(t,(r=>this.run(e,t,r)))}async*whilePending(e,t){let r=this.pendingShells.get(e.toolCallId);void 0===r&&(r={awaitingApproval:!1,registered:wM()},""!==e.toolCallId&&e.timeoutBehavior===he._d.BACKGROUND&&this.pendingShells.set(e.toolCallId,r));try{yield*t(r)}finally{this.settle(e.toolCallId,r,void 0)}}settle(e,t,r){this.pendingShells.get(e)===t&&this.pendingShells.delete(e),t.registered.resolve(r)}async*run(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{e.signal?.throwIfAborted(),function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(n,(0,$.VI)(e.withName("LocalShellStreamExecutor.execute")),!1);const o=t.command;let s=t.requestedSandboxPolicy?ls(t.requestedSandboxPolicy):void 0;const i=t.workingDirectory||await this.coreExecutor.getCwd(t.conversationId),a=cM(t),c=(0,Yo.o1)(i),l=Date.now(),u=performance.now(),d=new he.HO(Wo(o).structured),h=ks({command:o,parsingResult:d,blockedCommands:t.adminCommandDenylist});if(void 0!==h)return void(yield new he.FI({event:{case:"rejected",value:new he.pZ({command:o,workingDirectory:c,reason:h})}}));const p=await this.permissionsService.shouldEnforceShellInvariantBlocks(e,{workingDirectory:c,skipUnsafeWorkingDirectoryBlock:!0,command:o,parsingResult:d,toolCallId:t.toolCallId,resolveSkippedApprovalPolicy:Mo(t)},s);if("block"===p.kind)return"permissionsConfig"===p.reason.type?void(yield new he.FI({event:{case:"permissionDenied",value:new he.jn({command:o,workingDirectory:c,error:"Command blocked by permissions configuration",isReadonly:p.reason.isReadonly??!1})}})):void(yield new he.FI({event:{case:"rejected",value:new he.pZ({command:o,workingDirectory:c,reason:Yu(p.reason)})}}));if(mM.info(e,"Shell stream: approval gate reached",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,hasSmartModeApproval:void 0!==t.smartModeApproval,hasSmartModeApprovalReason:void 0!==t.smartModeApproval?.reason,hasSmartModeApprovalRequestId:void 0!==t.smartModeApproval?.requestId,requestedPolicyType:s?.type??"undefined",parserCommandCount:d.executableCommands.length,classifierCommandCount:t.classifierResult?.commands.length??0,commandLength:o.length}),Mo(t)){const r=p.policy??s;mM.info(e,"Shell stream: skipped local approval",{toolCallId:t.toolCallId,requestedPolicyType:s?.type??"undefined",effectivePolicyType:r?.type??"undefined"}),s=r}else{r.awaitingApproval=!0;const n=await this.permissionsService.shouldBlockShellCommand(e,o,{workingDirectory:c,timeout:a,parsingResult:d,toolCallId:t.toolCallId,classifierResult:t.classifierResult,smartModeApprovalReason:t.smartModeApproval?.reason,smartModeApprovalRequestId:t.smartModeApproval?.requestId,hookApprovalRequirement:Ao(t),onApprovalRequested:()=>{r.registered.resolve(void 0),r.registered=wM()}},s);if(r.awaitingApproval=!1,"block"===n.kind){if(mM.info(e,"Shell stream: approval gate blocked command",{toolCallId:t.toolCallId,blockReasonType:n.reason.type,hasSmartModeApproval:void 0!==t.smartModeApproval,skipApproval:t.skipApproval}),"permissionsConfig"===n.reason.type)return void(yield new he.FI({event:{case:"permissionDenied",value:new he.jn({command:o,workingDirectory:c,error:"Command blocked by permissions configuration",isReadonly:n.reason.isReadonly??!1})}}));const r=Yu(n.reason);return void(yield new he.FI({event:{case:"rejected",value:new he.pZ({command:o,workingDirectory:c,reason:r})}}))}s=n.policy,mM.info(e,"Shell stream: approval gate allowed command",{toolCallId:t.toolCallId,skipApproval:t.skipApproval,effectivePolicyType:s.type})}s=await Tc(s,{command:o,workingDirectory:c,parsingResult:d,permissionsService:this.permissionsService,ignoreService:this.ignoreService}),yield new he.FI({event:{case:"start",value:new he.tD({sandboxPolicy:us(s)})}});const f=t.timeoutBehavior===he._d.BACKGROUND,m=f&&!t.closeStdin&&void 0===t.smartModeApproval,g=new AbortController,w=f?g.signal:e.signal?AbortSignal.any([e.signal,g.signal]):g.signal,y=!0,v=s?{perUser:s}:void 0,b=this.coreExecutor.execute(e,{command:o,workingDirectory:i,signal:w,toolCallId:t.toolCallId,conversationId:t.conversationId,requestId:t.requestId,secretScopeId:t.secretScopeId,sandboxPolicy:v,fileOutputThresholdBytes:t.fileOutputThresholdBytes,pipeStdin:m,showElapsedTime:y});let S;f||(S=setTimeout((()=>g.abort()),a));const k=f?new gM(b[Symbol.asyncIterator](),a):null;let _,C,E,x="",P=!1,R=!1;const I=t.toolCallId&&k?{requestBackground:()=>{if(k.requestBackground())return E=E??this.backgroundShellManager.generateShellId(),new he.W4({result:{case:"success",value:new he.QR({shellId:E,pid:C,command:o,workingDirectory:c,msToWait:$y(performance.now()-u),backgroundReason:he.Jg.USER_REQUEST,interleavedOutput:x})}})}}:void 0;t.toolCallId&&I&&this.activeForegroundExecutions.set(t.toolCallId,I),this.settle(t.toolCallId,r,I);const T=()=>{t.toolCallId&&this.activeForegroundExecutions.get(t.toolCallId)===I&&this.activeForegroundExecutions.delete(t.toolCallId)},A=()=>{k&&!k.backgroundRequested&&(g.abort(),k.abort())};let M;k&&e.signal&&(e.signal.aborted?A():e.signal.addEventListener("abort",A,{once:!0}));const D=t.hardTimeout;void 0!==D&&D>0&&(M=setTimeout((()=>{void 0!==E?this.backgroundShellManager.abort(E)||g.abort():(P=!0,g.abort(),k?.abort())}),D));const O=k?.iterate()??b;try{for await(const r of O)if("stdout"===r.type)x+=r.data,yield new he.FI({event:{case:"stdout",value:new he.o0({data:r.data})}});else if("stderr"===r.type)x+=r.data,yield new he.FI({event:{case:"stderr",value:new he.Db({data:r.data})}});else if("stdin_ready"===r.type)_=r.stdin,C=r.pid;else if("exit"===r.type){let n;R=!0,r.aborted&&(n=e.signal?.aborted?he.Lv.USER_ABORT:k?.timedOut||g.signal.aborted?he.Lv.TIMEOUT:he.Lv.USER_ABORT),yield new he.FI({event:{case:"exit",value:new he.vb({code:(r.code??-1)>>>0,cwd:await this.coreExecutor.getCwd(t.conversationId),outputLocation:r.outputLocation,aborted:r.aborted,abortReason:n,localExecutionTimeMs:$y(r.localExecutionTimeMs)})}})}}catch(r){if(!(r instanceof Oo.SandboxUnsupportedError))throw r;const n=s?.type??"unknown";return mM.debug(e,"Shell stream: sandbox policy unsupported on this host",{toolCallId:t.toolCallId,policyType:n,reason:r.reason}),void(yield new he.FI({event:{case:"sandboxUnsupported",value:new he.rI({command:o,workingDirectory:c,sandboxPolicyType:n,reason:r.reason??r.message,isReadonly:"workspace_readonly"===n})}}))}finally{clearTimeout(S),k?.backgroundRequested||clearTimeout(M),T(),!k||k.backgroundRequested||R||g.abort(),e.signal?.removeEventListener("abort",A)}if(k?.backgroundRequested&&!P){const r=E??this.backgroundShellManager.generateShellId();E=r;const n=k.backgroundReasonValue===he.Jg.USER_REQUEST?he.Jg.USER_REQUEST:he.Jg.TIMEOUT,s=n===he.Jg.USER_REQUEST?Math.round(performance.now()-u):a;await this.backgroundShellManager.adopt({ctx:e,shellId:r,command:o,workingDirectory:c,toolCallId:t.toolCallId,sandboxPolicy:v,initialOutput:x,stdin:_,pid:C,abortController:g,eventIterator:k.getHandoffIterator(),startTime:l,monotonicStartMs:u,showElapsedTime:y,description:t.description,outputNotification:t.outputNotification,onCleanup:()=>clearTimeout(M)}),yield new he.FI({event:{case:"backgrounded",value:new he.Y9({shellId:r,command:o,workingDirectory:c,pid:C,msToWait:y?s:void 0,reason:n})}})}else e.signal?.aborted&&void 0!==k?.stopReasonValue?(clearTimeout(M),yield new he.FI({event:{case:"exit",value:new he.vb({code:4294967295,cwd:await this.coreExecutor.getCwd(t.conversationId),aborted:!0,abortReason:he.Lv.USER_ABORT})}})):clearTimeout(M)}catch(e){n.error=e,n.hasError=!0}finally{fM(n)}}}const vM={kind:"absent"};class bM{constructor(e){this.cells=new Map,this.takenCells=new WeakMap,this.collectedCells=new FinalizationRegistry((e=>{void 0===this.cells.get(e)?.deref()&&this.cells.delete(e)})),this.claims=new Map,this.nextGeneration=0,this.entries=new Eo.q({max:1e3,ttl:6e4,ttlResolution:0,perf:e})}begin(e){this.entries.purgeStale();const t=++this.nextGeneration;return this.claims.set(PM(e),t),t}record(e,t,r){if(!this.claim(e,r))return;const n=PM(e);this.entries.set(n,{recorded:t,generation:r}),this.commitGeneration(n,r)}forget(e,t){if(!this.claim(e,t))return;const r=PM(e);this.entries.delete(r),this.commitGeneration(r,t)}end(e,t){this.claim(e,t)}take(e){const t=PM(e),r=this.entries.get(t);if(void 0===r)return;const n=this.entries.getRemainingTTL(t);this.entries.delete(t);let o=this.cells.get(t)?.deref();void 0===o&&(o={committed:r.generation},this.cells.set(t,new WeakRef(o)),this.collectedCells.register(o,t));const s={read:e,recorded:r.recorded,remainingTtlMs:n,generation:r.generation};return this.takenCells.set(s,o),s}restore(e){const t=this.takenCells.get(e);if(void 0===t||t.committed!==e.generation)return;const r=PM(e.read);this.entries.has(r)||!Number.isFinite(e.remainingTtlMs)||e.remainingTtlMs<=0||this.entries.set(r,{recorded:e.recorded,generation:e.generation},{ttl:e.remainingTtlMs})}commitGeneration(e,t){const r=this.cells.get(e)?.deref();void 0!==r&&(r.committed=t)}claim(e,t){const r=PM(e);return this.claims.get(r)===t&&(this.claims.delete(r),!0)}}class SM{constructor(){this.views=new Eo.q({max:1e3})}get(e){return this.views.get(e)}set(e,t){this.views.set(e,t)}forget(e){this.views.delete(e)}recordWrite(e,t){if(t.length>Gs)return void this.views.delete(e);const r=(0,bo.createHash)("sha256").update(t).digest("hex");this.views.set(e,{kind:"fingerprint",byteLength:t.length,sha256:r})}recordDelete(e){this.views.set(e,vM)}}async function kM(e,t){if(void 0===e)return!1;try{if("absent"===e.kind)return await xM(t);const r=await EM(t);return void 0===r||r.byteLength!==e.byteLength||r.sha256!==e.sha256}catch{return!1}}async function _M(e,t){if("fingerprint"!==e?.kind)return!1;try{return!await xM(t)}catch{return!1}}class CM{constructor(e,t,r,n,o){this.inner=e,this.reads=t,this.permissionsService=r,this.workspacePath=n,this.views=o}async execute(e,t,r){const n=!0===r?.recordAgentView?(0,Yo.o1)(t.path,this.workspacePath):void 0,o=function(e,t){if(""!==e.toolCallId&&void 0===e.offset&&void 0===e.limit)return{toolCallId:e.toolCallId,resolvedPath:(0,Yo.o1)(e.path,t)}}(t,this.workspacePath);if(void 0===o){const o=await this.inner.execute(e,t,r);return this.forgetViewReadPast(n,o),o}const s=this.reads.begin(o);try{let i,a;try{i=await Zk(this.permissionsService,o.resolvedPath)}catch{return await this.readAndForget(e,t,r,o,s,n)}if(!1!==i&&"needsApproval"!==i.type)return await this.readAndForget(e,t,r,o,s,n);if(!1!==i){const i=await this.inner.execute(e,t,r),a=await async function(e,t){if("success"===e.result.case&&"content"===e.result.value.output.case)try{return await EM(t)}catch{return}}(i,o.resolvedPath);return this.commit(o,s,i,a,n),i}try{a=await EM(o.resolvedPath)}catch{return await this.readAndForget(e,t,r,o,s,n)}const c=await this.inner.execute(e,t,r);return this.commit(o,s,c,a,n),c}finally{this.reads.end(o,s)}}commit(e,t,r,n,o){let s;if("fileNotFound"===r.result.case?s=vM:void 0!==n&&"success"===r.result.case&&"content"===r.result.value.output.case&&(s={kind:"fingerprint",...n}),void 0===s)return this.reads.forget(e,t),void this.forgetViewReadPast(o,r);this.reads.record(e,s,t),void 0!==o&&this.views?.set(o,s)}async readAndForget(e,t,r,n,o,s){const i=await this.inner.execute(e,t,r);return this.reads.forget(n,o),this.forgetViewReadPast(s,i),i}forgetViewReadPast(e,t){void 0===e||"success"!==t.result.case&&"fileNotFound"!==t.result.case||this.views?.forget(e)}}async function EM(e){try{const t=await(0,Co.stat)(e);if(!t.isFile()||t.size>Gs)return}catch(e){return RM(e)}let t;try{t=await(0,Co.open)(e,function(){const e=xo.constants;return e.O_RDONLY|(e.O_NONBLOCK??0)}());const r=await t.stat();if(!r.isFile()||r.size>Gs)return;const n=(0,bo.createHash)("sha256");let o=0;const s=Buffer.alloc(65536);for(;o<=Gs;){const{bytesRead:e}=await t.read(s,0,s.length,o);if(0===e)break;o+=e,n.update(s.subarray(0,e))}if(o>Gs)return;return{byteLength:o,sha256:n.digest("hex")}}catch(e){return RM(e)}finally{await(t?.close())}}async function xM(e){try{return await(0,Co.stat)(e),!0}catch(e){if(IM(e))return!1;throw e}}function PM({toolCallId:e,resolvedPath:t}){return`${e}\0${t}`}function RM(e){if(!IM(e))throw e}function IM(e){const t=Sc(e);return"ENOENT"===t||"ENOTDIR"===t}var TM=r("../proto/dist/generated/agent/v1/web_fetch_allowlist_precheck_exec_pb.js");class AM{constructor(e){this.permissionsService=e}async execute(e,t){const r=await this.permissionsService.isWebFetchFullyAllowlisted(e,{url:t.url});return new TM.M({allowlisted:r})}}var $M=r("node:constants");const MM=[".md",".markdown",".mdown",".mkd",".mkdn",".mdx"];function DM(e){const t=e.trim().toLowerCase();return MM.some((e=>t.endsWith(e)))}function OM(e,t){const r=e.trim().toLowerCase().split("win32"===t?/[\\/]/:"/");if(r.some((e=>"."===e||".."===e)))return!1;const[n,o,s,i,a]=r.slice(-5);return r.length>=5&&".cursor"===n&&"projects"===o&&void 0!==s&&""!==s&&"canvases"===i&&void 0!==a&&a.length>11&&a.endsWith(".canvas.tsx")}const FM="win32"===process.platform;process.platform;const NM="\\"===s.sep?"win32":"posix",LM={allowed:!1};class jM extends Error{constructor(e,t){super(t),this.name="SymlinkRefusedError",this.path=e}}function UM(e,{nonBlocking:t}){const r=xo.constants;let n=e;return"number"==typeof r.O_NOFOLLOW&&(n|=r.O_NOFOLLOW),t&&"number"==typeof r.O_NONBLOCK&&(n|=r.O_NONBLOCK),"number"==typeof r.O_CLOEXEC&&(n|=r.O_CLOEXEC),n}const BM=[20,40,80],WM=new Set(["UNKNOWN","EBUSY"]);async function HM(e,t){try{const[r,n]=await Promise.all([t.stat({bigint:!0}),(0,Co.lstat)(e,{bigint:!0})]);r.dev===n.dev&&r.ino===n.ino&&await(0,Co.unlink)(e)}catch{}}async function qM(e,t,r,{removeOnRefusal:n=!1}={}){let o;try{o=await async function(e,t){try{return await(0,Co.open)(e,UM(t,{nonBlocking:!0}),438)}catch(r){const n=Sc(r);if(("EAGAIN"===n||"EWOULDBLOCK"===n)&&await async function(e){try{return(await(0,Co.lstat)(e)).isFile()}catch{return!1}}(e))return await(0,Co.open)(e,UM(t,{nonBlocking:!1}),438);throw r}}(e,t)}catch(t){if(function(e){const t=Sc(e);return"ELOOP"===t||"EMLINK"===t||"EPERM"===t&&"number"==typeof xo.constants.O_NOFOLLOW}(t))throw new jM(e,`Refusing to ${r} through a symlink at ${e}`);throw t}try{let t;try{t=(0,xo.realpathSync)(e)}catch{throw new jM(e,`Cannot verify canonical path before ${r}: ${e}`)}if(t!==e)throw new jM(e,`Refusing ${r}: ${e} now resolves through a symlinked parent to ${t}`);const n=await o.stat();if(!n.isFile())throw new jM(e,`Refusing to ${r} non-regular file at ${e}`);return{fd:o,stats:n}}catch(t){throw n&&await HM(e,o),await o.close(),t}}var zM=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const GM=(0,l.h)("LocalWriteExecutor"),VM=(0,u.Pu)("local_exec.write.encoding_check",{description:"Text writes that landed, per encoding detector (mojibake, U+FFFD): whether the written text holds the pattern and holds more of it than the file did, and for a detection what the file held, its extension family, encoding and the machine's Windows code page",labelNames:["detector","outcome","file","ext","encoding","code_page","run_count","delta","before_count","pattern"]}),KM=async(e,t,r,n)=>{const o=setTimeout((()=>{GM.warn(e,`[watchdog, LocalWriteExecutor] ${t} still not completed after ${r}ms`)}),r);try{return await n()}finally{clearTimeout(o)}};function JM(e){return new Error(`Could not create ${e}: directory creation exceeded the path depth and was stopped.`)}async function ZM(e){try{return(await(0,Co.stat)(e)).isDirectory()?"directory":"present"}catch(e){if("ENOENT"===Sc(e))return"missing";throw e}}async function XM(e,t){const r=[];let n=e;for(let o=0;o<=t;o+=1){const t=await ZM(n);if("directory"===t)return r.reverse(),r;if("present"===t)return await(0,Co.mkdir)(n,{recursive:!1}),r.reverse(),r;r.push(n);const o=(0,s.dirname)(n);if(o===n){const t=new Error(`ENOENT: no such file or directory, mkdir '${e}'`);throw t.code="ENOENT",t.syscall="mkdir",t.path=e,t}n=o}throw JM(e)}class QM{constructor(e,t,r,{workspacePaths:n,workspacePath:o,worktreeMainPath:s,projectDir:i,onWriteForAiTracking:a,writeFileMutationGuard:c,toolCallReads:l,agentFileViews:u}){this.fileChangeTracker=e,this.permissionsService=t,this.pendingDecisionProvider=r,this.workspacePaths=n,this.workspacePath=o,this.worktreeMainPath=s,this.projectDir=i,this.onWriteForAiTracking=a,this.writeFileMutationGuard=c,this.toolCallReads=l,this.agentFileViews=u}async execute(e,t,r){if(function(e){if(!e.startsWith("file://"))return!1;try{return(0,Ed.fileURLToPath)(e),!1}catch{return!0}}(t.path))return new MI.v3({result:{case:"error",value:new MI.QM({path:t.path,error:`${t.path} is not a valid file URL. Use an absolute path instead.`})}});const n=(0,Yo.o1)(t.path,this.workspacePath),o=this.toolCallReads,s=void 0!==o&&""!==t.toolCallId?o.take({toolCallId:t.toolCallId,resolvedPath:n}):void 0,i=!0===r?.refuseUnreadChanges?this.agentFileViews?.get(n):void 0,a={writeStarted:!1},c=()=>{void 0===s||a.writeStarted||o?.restore(s)};try{const r=await this.executeWithRecord(e,t,n,s?.recorded,i,a);return tD(r)&&c(),r}catch(e){throw c(),e}}async executeWithRecord(e,t,r,n,o,i){const a={stack:[],error:void 0,hasError:!1};try{const c=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(a,(0,$.VI)(e.withName("LocalWriteExecutor.execute")),!1).ctx,l=(t.path,t.fileText),u=t.fileBytes.length>0?t.fileBytes:void 0,d=["assets","agent-tools","swarm-agents"],h=yS(r,d)||void 0!==this.projectDir&&!this.workspacePaths.some((e=>{return t=e,n=r,FM&&(t=t.toLowerCase(),n=n.toLowerCase()),t===n||(t.charAt(t.length-1)!==s.sep&&(t+=s.sep),n.startsWith(t));var t,n}))&&vS(this.projectDir,r,d);if((0,Yo.fl)({targetPath:r,workspacePaths:this.workspacePaths,mainWorktreePath:this.worktreeMainPath}))return new MI.v3({result:{case:"error",value:new MI.QM({path:r,error:Yo.PS})}});let p,f,m,g,w=!1;try{const e=await(0,Co.stat)(r);if(g=511&e.mode,e.size<=ns){const e=await KM(c,"readText before write",3e3,(()=>Ui(r,t.encodingHint)));p=e.text,f=e.encoding,m=Uw(e)}else w=!0}catch(e){w="ENOENT"!==Sc(e)}const y=await DS(r),v=y.resolvedPath;if(t.confineToWorkspace){let e=(await Promise.all(this.workspacePaths.map((e=>(0,Co.realpath)(e).catch((()=>{})))))).filter((e=>void 0!==e));if(0===e.length&&void 0!==this.projectDir){const t=await(0,Co.realpath)(this.projectDir).catch((()=>{}));void 0!==t&&(e=[t])}if(!e.some((e=>(0,Yo.BJ)(v,e))))return new MI.v3({result:{case:"error",value:new MI.QM({path:r,error:"downloadPath must stay within the workspace"})}})}const b=async()=>{return await kM(n,v)?BT(r):(t=n,void 0!==(e=o)&&void 0!==t&&e.kind===t.kind&&("absent"===e.kind||"fingerprint"===t.kind&&e.byteLength===t.byteLength&&e.sha256===t.sha256)||!await kM(o,v)?void 0:WT(r));var e,t},S=t.planMode?await KM(c,"checkPlanModeWriteTarget",3e3,(()=>async function(e,t){switch(t.resolution.status){case"resolved":case"newFile":return DM(t.resolvedPath)?{allowed:!0}:await async function(e,t){if(!(OM(t.resolvedPath,NM)||OM(e,NM)&&t.resolvedPath===await async function(e){const t=(0,s.dirname)((0,s.dirname)((0,s.dirname)((0,s.dirname)(e)))),r=await DS(t);if(OS(r.resolution))return(0,s.join)(r.resolvedPath,(0,s.relative)(t,e))}(e)))return LM;if("newFile"===t.resolution.status)return{allowed:!0,singleLink:{kind:"create"}};const r=await async function(e){try{const t=await(0,Co.lstat)(e,{bigint:!0});return t.isFile()&&1n===t.nlink?{kind:"existing",dev:t.dev,ino:t.ino}:void 0}catch{return}}(t.resolvedPath);return void 0===r?LM:{allowed:!0,singleLink:r}}(e,t);case"danglingSymlink":{const e=await async function(e){let t=e;for(let e=0;e<40;e++){let e;try{e=await(0,Co.readlink)(t)}catch(e){const r=Sc(e);return"ENOENT"===r||"EINVAL"===r?t:void 0}t=(0,s.resolve)((0,s.dirname)(t),e)}}(t.resolvedPath);return void 0!==e&&DM(e)?{allowed:!0}:LM}case"permissionDenied":case"symlinkLoop":case"unknownError":return LM;default:return t.resolution,LM}}(r,y))):void 0;if(void 0!==S&&!S.allowed)return new MI.v3({result:{case:"rejected",value:new MI.en({path:r,reason:"Cannot edit non markdown files in plan mode"})}});const k=(".cursorignore"===(r.split(s.sep).pop()?.toLowerCase()??"")?{type:"permissionsConfig"}:void 0)??await KM(c,"permissionsService.shouldBlockWrite",3e3,(()=>this.permissionsService.shouldBlockWrite(c,v,l)));if(k){const e=await KM(c,"handleBlockReason",3e3,(()=>Qu(k,{onNeedsApproval:async(e,n)=>{const o="fileEdit"!==n?.type||n.isNewFile,s="fileEdit"===n?.type?n.diffString:l,i="fileEdit"===n?.type?n.blockReason:void 0,a=await b();if(void 0!==a)return YM(r,a);const c=await this.pendingDecisionProvider.requestApproval({type:Lw.Write,details:{path:r,reason:e,isNewFile:o,diffString:s,before:p,after:l,blockReason:i},toolCallId:t.toolCallId});return c.approved?null:new MI.v3({result:{case:"rejected",value:new MI.en({path:r,reason:c.reason||""})}})},onUserRejected:e=>new MI.v3({result:{case:"rejected",value:new MI.en({path:r,reason:e||""})}}),onPermissionDenied:(e,t)=>new MI.v3({result:{case:"permissionDenied",value:new MI.U7({path:r,error:e,isReadonly:t?.isReadonly??!1})}})})));if(null!==e)return e}const _=await KM(c,"anotherSpellingRefusal",3e3,(()=>async function(e){const t=(0,s.basename)(e);let r;try{if(!(await(0,Co.stat)(e)).isFile())return;const n=await(0,Co.readdir)((0,s.dirname)(e));if(n.includes(t))return;const o=t.normalize("NFC");if(n.some((e=>e.normalize("NFC")===o)))return;const i=t.toLowerCase(),a=n.filter((e=>e.toLowerCase()===i)),c=o.toLowerCase();r=a.length>0?a:n.filter((e=>e.normalize("NFC").toLowerCase()===c))}catch{return}const n=1===r.length?r[0]:void 0;return void 0===n?`${t} names an existing file that this folder lists under another name, so writing it would replace that file. Nothing was written. List the folder and write the file by its listed name to change it; for a new file, choose a different name.`:`${t} names the existing file ${n}: this volume does not tell names apart by case, so writing it would replace ${n}. Nothing was written. To change that file, write ${n}; for a new file, choose a name no file in this folder has in any case.`}(r)));if(void 0!==_)return new MI.v3({result:{case:"error",value:new MI.QM({path:r,error:_})}});const C=(0,s.dirname)(v);if(await _M(n,C))return YM(r,BT(r));if(await _M(o,C))return YM(r,WT(r));let E,x,P,R;try{E=await KM(c,"mkdir",3e3,(()=>async function(e){const t=function(e){let t=0,r=e;for(;;){const e=(0,s.dirname)(r);if(e===r)return t;t+=1,r=e}}(e),r=t+4;let n=0,o=0,i=await XM(e,t),a=0;for(;ar)throw JM(e);try{await(0,Co.mkdir)(c,{recursive:!1})}catch(r){const n=Sc(r);if("EEXIST"===n){if("directory"!==await ZM(c))throw r;a+=1;continue}if("ENOENT"===n){const n=(0,s.dirname)(c);if(n===c||"missing"!==await ZM(n))throw r;i=await XM(e,t),a=0,o=0;continue}throw r}o+=1,a+=1}return o}(C)))}catch(e){const t=Sc(e);return"EACCES"===t||"EPERM"===t?new MI.v3({result:{case:"permissionDenied",value:new MI.U7({path:r,directory:C,operation:"create_directory",error:"Permission denied"})}}):new MI.v3({result:{case:"error",value:new MI.QM({path:r,error:kc(e)})}})}if(void 0!==u)x=u,P=0;else{const e=await KM(c,"getBufferForWrite",3e3,(()=>Wi(r,l,this.workspacePath,t.encodingHint)));x=e.buffer,P=e.lines,R=e.format.encoding}const I=()=>KM(c,"writeFile",3e3,(async()=>{const e=await b();if(void 0!==e)throw new Error(e);let t;c.signal.throwIfAborted(),i.writeStarted=!0,await async function(e,t,r){const n=r?.singleLink,{fd:o}=void 0===n?await qM(e,xo.constants.O_WRONLY|xo.constants.O_CREAT,"write"):await async function(e,t){const r="create"===t.kind,n=r?xo.constants.O_WRONLY|xo.constants.O_CREAT|xo.constants.O_EXCL:xo.constants.O_WRONLY;let o;try{o=await qM(e,n,"write",{removeOnRefusal:r})}catch(t){const r=Sc(t);if("EEXIST"===r||"ENOENT"===r)throw new jM(e,`Refusing to write: ${e} was ${"EEXIST"===r?"created":"removed"} after it was checked`);throw t}const{fd:s}=o;try{const r=await s.stat({bigint:!0});if(1n!==r.nlink)throw new jM(e,`Refusing to write: ${e} has ${r.nlink} hard links`);if("existing"===t.kind&&(r.dev!==t.dev||r.ino!==t.ino))throw new jM(e,`Refusing to write: ${e} was replaced after it was checked`);return o}catch(t){throw r&&await HM(e,s),await s.close(),t}}(e,n);try{await async function(e){for(let t=0;;t++)try{return void await e.truncate(0)}catch(e){const r=Sc(e);if(t>=BM.length||void 0===r||!WM.has(r))throw e;await(0,Fg.setTimeout)(BM[t])}}(o);const e=function(e){return Buffer.isBuffer(e)?e:Buffer.from(e)}(t);let n=0;for(;n{try{await I()}catch(e){throw T=e,A=!0,e}};try{void 0===this.writeFileMutationGuard?await I():await this.writeFileMutationGuard.runExclusive(v,M)}catch(e){if(void 0!==this.writeFileMutationGuard&&(!A||e!==T))return new MI.v3({result:{case:"error",value:new MI.QM({path:r,error:e instanceof Error?e.message:String(e)})}});if(e instanceof jM)return new MI.v3({result:{case:"permissionDenied",value:new MI.U7({path:r,directory:"",operation:"create_file",error:e.message})}});const t=Sc(e);return"EACCES"===t||"EPERM"===t?new MI.v3({result:{case:"permissionDenied",value:new MI.U7({path:r,directory:"",operation:"create_file",error:"Permission denied"})}}):"ENOSPC"===Sc(e)?new MI.v3({result:{case:"noSpace",value:new MI.bM({path:r})}}):"EDQUOT"===t?new MI.v3({result:{case:"error",value:new MI.QM({path:r,error:"Agent-store quota exceeded: this write was rejected because the storage quota is full. Nothing was written; your local copy is intact. Delete or truncate files to free space (including resolved *.conflict* files), then retry. Do not retry the same write without freeing space first."})}}):new MI.v3({result:{case:"error",value:new MI.QM({path:r,error:kc(e)})}})}if(this.fileChangeTracker&&void 0===u&&!h&&!w){const e={...t.toolCallId?{toolCallId:t.toolCallId}:{},...v===r?{}:{writtenPath:v},...void 0===g?{}:{beforeMode:g},...E>0?{createdDirectories:E}:{}};await this.fileChangeTracker.trackChange(r,p,l,e,m)}if(this.onWriteForAiTracking&&void 0===u&&!h){const e=t.toolCallId?{toolCallId:t.toolCallId}:{};try{await this.onWriteForAiTracking({path:r,beforeContent:p,afterContent:l,metadata:e})}catch(e){GM.warn(c,"onWriteForAiTracking failed (write succeeded)",{path:r,error:e instanceof Error?e.message:String(e)})}}const D=x.byteLength;let O;if(void 0!==u||w||h||this.recordEncodingChecks(c,r,p,f,l),t.returnFileContentAfterWrite)try{O=await KM(c,"readText after write",3e3,(()=>ji(r,t.encodingHint)))}catch{}return new MI.v3({result:{case:"success",value:new MI.j6({path:r,linesCreated:P,fileSize:D,...void 0!==O&&{fileContentAfterWrite:O}})}})}catch(e){a.error=e,a.hasError=!0}finally{zM(a)}}recordEncodingChecks(e,t,r,n,o){try{const i={path:t,encoding:n,pages:(s=gu.pages(),"failed"===s?"none":s)};for(const t of function(e,t,r){return[gl(e,t,r),wl(e,t,r)]}(r,n,o))VM.increment(e,1,_l(t,i))}catch(t){for(const t of ll)VM.increment(e,1,{detector:t,outcome:"error",file:"unclassified"});GM.warn(e,"encoding check failed (write succeeded)",{error:t instanceof Error?t.message:String(t)})}var s}}function YM(e,t){return new MI.v3({result:{case:"error",value:new MI.QM({path:e,error:t})}})}class eD extends Error{constructor(e){super("stale write refusal"),this.result=e,this.name="StaleWriteRefusal"}}function tD(e){if("error"!==e.result.case)return!1;const{error:t,path:r}=e.result.value;return t===BT(r)||t===WT(r)}const rD=(0,l.h)("local-exec:provider"),nD=new Set,oD=new yd.AsyncLocalStorage;class sD extends K{getMcpExecutionPolicyDeps(){return{permissionsService:this.permissionsService,pendingDecisionProvider:this.pendingDecisionStore}}static dropOwnedRequestContextCaches(){for(const e of nD)e.ownedRequestContextExecutor?.invalidateGlobalCache()}static rebuildRequestContextCachesFor(e){for(const t of nD)t.cursorRulesService===e&&t.ownedRequestContextExecutor?.refreshGlobalCache()}constructor(e){super(),this.pendingDecisionStore=e.pendingDecisionStore,this.fileChangeTracker=e.fileChangeTracker,this.gitExecutor=e.gitExecutor,this.ignoreService=e.ignoreService,this.grepProvider=e.grepProvider,this.permissionsService=e.permissionsService,this.workspacePaths=e.workspacePaths,this.worktreeMainPath=e.worktreeMainPath,this.diagnosticsProvider=e.diagnosticsProvider,this.mcpLease=e.mcpLease,this.mcpStateAccessor=e.mcpStateAccessor,this.cursorRulesService=e.cursorRulesService,this.cloudRulesService=e.cloudRulesService,this.subagentsService=e.subagentsService,this.repositoryProvider=e.repositoryProvider,this.projectDir=e.projectDir,this.shellManager=e.shellManager,this._sandboxPolicyResolver=e._sandboxPolicyResolver,this._defaultSandboxPolicy=e._defaultSandboxPolicy??{type:"insecure_none"};const t=e.workspacePaths[0],r=t?function(e){const t=(0,s.join)(e,".cursor/sandbox.json");try{const r=(0,xo.readFileSync)(t,"utf-8"),n=JSON.parse(r),o=(0,Oo.$6)(n);return(0,Oo.l7)(o,e)}catch{return}}(t):void 0,n=e._defaultSandboxPolicySources;this._defaultSandboxPolicySources=r||n?{perUser:n?.perUser,perRepo:r??n?.perRepo,teamAdmin:n?.teamAdmin}:void 0,this.mcpFileOutputThresholdBytes=e.mcpFileOutputThresholdBytes,this.blankSharedPaymentTokensInMcpOutputFiles=!0===e.blankSharedPaymentTokensInMcpOutputFiles,this.backgroundShellFactory=e.backgroundShellFactory,this.backgroundWorkRegistry=e.backgroundWorkRegistry,this.wakeupOwnerConversationId=e.wakeupOwnerConversationId,this.mcpElicitationFactory=e.mcpElicitationFactory,this.createFileWatcher=e.createFileWatcher,this.sharedRequestContextExecutor=e.sharedRequestContextExecutor,this.terminalExecutor=e.terminalExecutor,this.mcpMetaToolEnabled=e.mcpMetaToolEnabled??!1,this.mcpMetaToolSlimDescriptors=e.mcpMetaToolSlimDescriptors??!1,this.mcpInputSchemaJson=e.mcpInputSchemaJson??!1,this.alwaysExposeVirtualMcpAuthTool=e.alwaysExposeVirtualMcpAuthTool??!1,this.enableRecordScreen=e.enableRecordScreen??!1,this.recordScreenArtifactsDir=e.recordScreenArtifactsDir,this.recordScreenDisplay=e.recordScreenDisplay,this.disableRecordScreenRendering=e.disableRecordScreenRendering??!1,this.userTerminalHint=e.userTerminalHint,this.attributionConfigProvider=e.attributionConfigProvider,this.isAttributionDisabledByAdmin=e.isAttributionDisabledByAdmin,this.getAgentSkills=e.getAgentSkills,this.getSmartModeClassifierAutoModeEnabled=e.getSmartModeClassifierAutoModeEnabled,this.getAdminCommandDenylist=e.getAdminCommandDenylist,this.devForceNextSmartModeClassifierBlockToken=e.devForceNextSmartModeClassifierBlockToken,this.getMockPromptTime=e.getMockPromptTime,this.additionalRules=e.additionalRules??[],this.askpassConfig=e.askpassConfig,this.rebuildRequestContextOnRulesChange=!0===e.rebuildRequestContextOnRulesChange;const i=this.terminalExecutor??(0,Oo.Fn)({env:{CURSOR_AGENT:"1"},userTerminalHint:this.userTerminalHint,isLoginShellEnabled:e.isLoginShellEnabled});let a;if(this.workspacePaths.length>1){const e=this.workspacePaths.map((e=>(0,s.dirname)(e)));a=e.every((t=>t===e[0]))?e[0]:void 0}else a=t;let c=new Ju(i,t??(0,o.homedir)(),this.projectDir,{shellOutputBackpressureOptions:e.shellOutputBackpressureOptions,extraEnvProvider:e.shellExtraEnvProvider,powershellUtf8Console:e.powershellUtf8Console,powershellUtf8ChildEnv:e.powershellUtf8ChildEnv,powershellParseAfterUtf8Switch:e.powershellParseAfterUtf8Switch,powershellWebRequestUtf8:e.powershellWebRequestUtf8,powershellPerLineStateDump:e.powershellPerLineStateDump,encodingSlices:e.encodingSlices,keepBackgroundJobs:e.keepShellBackgroundJobs});e.shellCoreWrapper&&(c=e.shellCoreWrapper(c)),this.askpassConfig&&(c=new Xu(c,this.askpassConfig)),this.shellManager&&(c=new Zu(c,this.shellManager));const l=e.overrideShellExecutor??(!0===e.suppressDefaultShellExecutor?void 0:new uM(this.permissionsService,c,this.ignoreService,this.pendingDecisionStore));void 0!==l&&this.register(jT,Dg(l)),this.register(UT,Dg(new LT(this.permissionsService,this.ignoreService,a??t??this.projectDir)));const u=new bM,d=new SM,h=e.overrideWriteExecutor??new QM(this.fileChangeTracker,this.permissionsService,this.pendingDecisionStore,{workspacePaths:this.workspacePaths,workspacePath:a,worktreeMainPath:this.worktreeMainPath,projectDir:this.projectDir,onWriteForAiTracking:e.onWriteForAiTracking,writeFileMutationGuard:e.writeFileMutationGuard,toolCallReads:u,agentFileViews:d});this.register(HT,function(e){const t=(r={execute:(t,r,n)=>e.execute(t,r,n).then((e=>{if(tD(e))throw new eD(e);return e}))},Dg(r));var r;return{async execute(e,r,n){try{return await t.execute(e,r,n)}catch(e){if(e instanceof eD)return e.result;throw e}}}}(h));const p=e.overrideDeleteExecutor??new Hw(this.pendingDecisionStore,this.fileChangeTracker,this.permissionsService,a,e.onDeleteForAiTracking,d);this.register(qT,Dg(p)),this.register(zT,Dg(new Jw({encodingSlices:e.encodingSlices}))),this.register(GT,new C$);const f=this.mcpStateAccessor??new oM(this.mcpLease),m=e.overrideGrepExecutor??new dC(this.ignoreService,this.grepProvider,this.workspacePaths,{mcpStateAccessor:f,permissionsService:this.permissionsService,useStreamingGrep:e.useStreamingGrep,encodingSlices:e.encodingSlices});this.register(VT,Dg(m));const g=e.overrideReadExecutor??new CM(new L_(this.permissionsService,a,{mcpStateAccessor:f,useStreamingRead:e.useStreamingRead,pendingDecisionProvider:this.pendingDecisionStore,encodingSlices:e.encodingSlices}),u,this.permissionsService,a,d),w=new XT(g);this.register(QT,w),e.registerRedactedReadExecutor&&this.register(YT,w);const y=e.overrideLsExecutor??new yC(this.permissionsService,this.ignoreService,a);this.register(eA,Dg(y)),this.register(tA,Dg(new WA(a,this.diagnosticsProvider))),e.getCanvasDiagnostics&&this.register(rA,Dg(new OA(e.getCanvasDiagnostics,e.beginCanvasSave))),this.register(eo,Dg(new yA(ru(new PT(this.mcpLease,this.permissionsService,this.pendingDecisionStore,this.projectDir,this.mcpFileOutputThresholdBytes,this.mcpElicitationFactory,e.ensureMcpServersLoaded,{blankSharedPaymentTokens:this.blankSharedPaymentTokensInMcpOutputFiles}),e.encodingSlices,"exec_mcp",(e=>"success"===e.result.case)),(()=>this.get(QT))))),this.register(to,Dg(new RT(this.mcpLease,e.ensureMcpServersLoaded))),this.register(ro,Dg(ru(new IT(this.mcpLease,a||this.projectDir,this.permissionsService,this.workspacePaths,this.pendingDecisionStore,e.ensureMcpServersLoaded,h),e.encodingSlices,"exec_mcp",(e=>"success"===e.result.case)))),this.register(no,Dg(new iM(f,e.ensureMcpServersLoaded,{filterToRequestedServers:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,...void 0===e.mcpServerRuleSubjects?{}:{serverRuleSubjects:e.mcpServerRuleSubjects}})));const v=this.sharedRequestContextExecutor??this.createOwnedRequestContextExecutor(f,t,e),b=Dg({execute:(e,t,r)=>{const n=oD.getStore();return void 0!==n&&(n.ran=!0),v.execute(e,t,r)}});this.register($r,{execute:async(t,r,n)=>{const o={ran:!1},s=await oD.run(o,(()=>b.execute(t,r,n)));if("success"!==s.result.case||void 0===s.result.value.requestContext)return s;const i=s.clone();if("success"!==i.result.case)return s;const a=i.result.value.requestContext;if(void 0===a)return i;const c=await f.getState(t),l=eM(c,{internalBrowserProvidersOnly:this.mcpMetaToolEnabled&&this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson});if(a.tools=l.tools,a.mcpInstructions=l.mcpInstructions,a.mcpMetaToolOptions=this.mcpMetaToolEnabled?tM(c,{alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,slimDescriptors:this.mcpMetaToolSlimDescriptors,inputSchemaJson:this.mcpInputSchemaJson}):void 0,o.ran&&void 0!==e.getMcpFileSystemOptions||(a.mcpFileSystemOptions=await(e.getMcpFileSystemOptions?.(t))),void 0!==a.env&&(a.env.artifactsFolder=e.getArtifactsFolder?.(t),void 0!==e.getSandboxEnabled&&(a.env.sandboxEnabled=e.getSandboxEnabled()),void 0!==e.getSessionSandboxSupported&&(a.env.sandboxSupported=e.getSessionSandboxSupported())),void 0!==e.getMountedAgentStores&&void 0!==a.env)try{const r=await e.getMountedAgentStores(t);a.env.mountedAgentStores=r.map((e=>e.clone()))}catch{a.env.mountedAgentStores=[],rD.warn(t,"Failed to get mounted agent stores; continuing without prompt inventory")}return i}}),this.backgroundShellExecutor=new wd(this.permissionsService,c,this.ignoreService,this.projectDir,this.backgroundShellFactory,this.backgroundWorkRegistry,this.wakeupOwnerConversationId,e.backgroundShellManager),this.shellRedeliveryCaches=e.shellRedeliveryCaches??{backgroundShell:Mg(),shellStream:Mg(),writeStdin:Mg()},this.register(vA,Dg(this.backgroundShellExecutor,void 0,this.shellRedeliveryCaches.backgroundShell)),this.shellStreamExecutor=new yM(this.permissionsService,c,this.ignoreService,this.backgroundShellExecutor.getManager()),this.register(ee,function(e,t,r=Mg(t)){return{async*execute(t,n,o){if(!o?.execId)return void(yield*e.execute(t,n,o));const s=$g(o.execId,n),i=r.get(s);if(i)return void(yield*i.fork());const a=e.execute(t,n,o),c=new Ag(a);r.set(s,c),yield*c.fork()}}}(this.shellStreamExecutor,void 0,this.shellRedeliveryCaches.shellStream)),void 0!==e.agentStoreConflictDrainer&&this.register(SA,new AA(e.agentStoreConflictDrainer)),this.register(kA,new hM(this.permissionsService)),this.register(_A,new x$(this.permissionsService)),this.register(CA,new AM(this.permissionsService));const S=new pM(this.shellStreamExecutor);this.register(EA,Dg(S));const k=!1===e.enableWriteBackgroundShellStdin?new $A((async()=>{throw new Error(e.writeBackgroundShellStdinDisabledReason??"write_shell_stdin is disabled for this session")})):new $A(((e,t)=>this.backgroundShellExecutor.writeStdin(e,t)));if(this.register(bA,Dg(k,void 0,this.shellRedeliveryCaches.writeStdin)),e.computerUseExecutor&&(this.computerUseExecutor=e.computerUseExecutor,this.register(xA,Dg(this.computerUseExecutor)),void 0!==e.computerUseEndTurnExecutor&&this.register(PA,e.computerUseEndTurnExecutor)),this.enableRecordScreen){if(!this.recordScreenArtifactsDir||!this.recordScreenDisplay)throw new Error("recordScreenArtifactsDir and recordScreenDisplay are required when enableRecordScreen is true");this.recordScreenExecutor=new F$({artifactsDir:this.recordScreenArtifactsDir,display:this.recordScreenDisplay,disablePolishedRendering:this.disableRecordScreenRendering,polishedRenderer:e.polishedRecordingRenderer}),this.register(RA,Dg(this.recordScreenExecutor))}}createOwnedRequestContextExecutor(e,t,r){const n=new aM(this.cursorRulesService,this.cloudRulesService,this.subagentsService,this.repositoryProvider,this.grepProvider,e,this.gitExecutor,void 0===r.requestContextWorkspacePaths?this.workspacePaths:[...r.requestContextWorkspacePaths],{projectDir:this.projectDir,isWorkingDirHomeDir:r.requestContextIsWorkingDirHomeDir??(0,Yo.yn)(t,(0,o.homedir)()),agentNotesEnabled:r.agentNotesEnabled,reportProcessWorkingDirectory:r.reportProcessWorkingDirectory,sectionLoadTimeoutMs:r.requestContextSectionLoadTimeoutMs,reportSectionCompleteness:r.reportRequestContextSectionCompleteness,freshSectionWaitMs:r.requestContextFreshSectionWaitMs,createFileWatcher:this.createFileWatcher,getSandboxEnabled:r.getSandboxEnabled,getSandboxSupported:r.getSandboxSupported,getNetworkAllowlistInfo:r.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:this.getSmartModeClassifierAutoModeEnabled,getAdminCommandDenylist:this.getAdminCommandDenylist,devForceNextSmartModeClassifierBlockToken:this.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:this.getMockPromptTime,userTerminalHint:this.userTerminalHint,getMcpFileSystemOptions:r.getMcpFileSystemOptions,mcpMetaToolEnabled:this.mcpMetaToolEnabled,mcpMetaToolSlimDescriptors:this.mcpMetaToolSlimDescriptors,mcpInputSchemaJson:this.mcpInputSchemaJson,alwaysExposeVirtualMcpAuthTool:this.alwaysExposeVirtualMcpAuthTool,getArtifactsFolder:r.getArtifactsFolder,secretRedactionEnabled:r.secretRedactionEnabled,attributionConfigProvider:this.attributionConfigProvider,isAttributionDisabledByAdmin:this.isAttributionDisabledByAdmin,getAgentSkills:this.getAgentSkills,additionalRules:this.additionalRules,getComputerUseSupported:()=>void 0!==this.computerUseExecutor,getComputerUseDesktop:r.getComputerUseDesktop,onRequestContext:r.onRequestContext,mcpFieldsFromCaller:!0===r.requestContextMcpFieldsFromOverlay,deferWarmup:!0===r.deferRequestContextWarmup});return!0===r.deferRequestContextWarmup&&(this.requestContextExecutorAwaitingWarmup=n),this.rebuildRequestContextOnRulesChange&&(this.ownedRequestContextExecutor=n,nD.add(this),this.disposeRulesChangeListener=this.cursorRulesService.onDidChangeRules?.((()=>{n.rebuildAllCaches()}))),n}warmRequestContext(){const e=this.requestContextExecutorAwaitingWarmup;this.requestContextExecutorAwaitingWarmup=void 0,e?.warm()}getRecordScreenExecutor(){return this.recordScreenExecutor}getBackgroundShellManager(){return this.backgroundShellExecutor.getManager()}getShellRedeliveryCaches(){return this.shellRedeliveryCaches}hasForegroundShells(){return this.shellStreamExecutor.hasForegroundWork()}withPendingShells(e){return new J(e,[G(ee,this.shellStreamExecutor.pendingFrom(e))])}async dispose(){this.requestContextExecutorAwaitingWarmup=void 0,this.rebuildRequestContextOnRulesChange&&(nD.delete(this),this.disposeRulesChangeListener?.(),this.disposeRulesChangeListener=void 0,this.ownedRequestContextExecutor?.dispose(),this.ownedRequestContextExecutor=void 0),this.backgroundShellExecutor.dispose(),this.recordScreenExecutor&&await this.recordScreenExecutor.dispose()}}function iD(e){return e.replace(/\\/g,"/")}function aD(e,t){for(const r of t){const t=iD(r);if(e===t||e.startsWith(`${t}/`))return!0}return!1}var cD;function lD(e,t,r){if(function(e){return Boolean(e.plugin?.trim()||e.pluginId?.trim()||e.marketplaceId?.trim())}(e))return cD.Plugin;const n=iD(e.fullPath);return aD(n,r.builtinDirs)?cD.Builtin:Lm(e.fullPath,t).inAgentStore?cD.UserStore:aD(n,r.userDirs)?cD.UserHome:(aD(n,r.workspaceDirs),cD.Workspace)}"function"==typeof SuppressedError&&SuppressedError,function(e){e[e.Builtin=0]="Builtin",e[e.UserStore=1]="UserStore",e[e.UserHome=2]="UserHome",e[e.Workspace=3]="Workspace",e[e.Plugin=4]="Plugin"}(cD||(cD={}));var uD=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const dD=(0,zs.debuglog)("merged-agent-skills"),hD=(0,l.h)("merged-agent-skills");class pD{constructor(e,t=()=>[],r){this.services=e,this.getDisabledManagedSkillPaths=t,this.getPromptSortContext=r,this.onChangeCallbacks=new Set}async getAllAgentSkills(e){const t={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(t,(0,$.VI)(e.withName("MergedAgentSkillsService.getAllAgentSkills")),!1),n=this.services.map((e=>e.getAllAgentSkills(r.ctx).catch((e=>(dD("Failed to load agent skills from service: %s",e instanceof Error?e.message:String(e)),[]))))),o=async()=>{try{return{ok:!0,paths:await this.getDisabledManagedSkillPaths()}}catch(e){return hD.warn(r.ctx,"getDisabledManagedSkillPaths failed; failing closed by dropping all managed skills for this call",{error:e instanceof Error?e.message:String(e)}),{ok:!1}}},[i,a]=await Promise.all([Promise.all(n),o()]),c=i.flat(),l=this.getPromptSortContext?.(),u=Um(c,l??Fm);let d=u;return a.ok?a.paths.length>0&&(d=u.filter((e=>!function(e,t){if(!e)return!1;const r=e.replace(/\\/g,"/");return t.some((e=>r.endsWith(e)))}(e.fullPath,a.paths)))):d=u.filter((e=>{return!((t=e.fullPath)&&t.replace(/\\/g,"/").includes(fD));var t})),void 0!==l?function(e,t){if(e.length<=1)return e;const r=function(e){const t=[ym(e.userHomeDirectory).dirPath],r=Em(e.userHomeDirectory,!0).map((e=>e.dirPath)),n=[];for(const t of e.workspacePaths){n.push((0,s.join)(t,".cursor","rules"));for(const e of Cm(t,!0))n.push(e.dirPath)}return{builtinDirs:t,userDirs:r,workspaceDirs:n}}(t),n=e.map(((e,n)=>({skill:e,index:n,tier:lD(e,t,r)})));return n.sort(((e,t)=>e.tier-t.tier||e.index-t.index)),n.map((e=>e.skill))}(d,l):d}catch(e){t.error=e,t.hasError=!0}finally{uD(t)}}reload(e){for(const t of this.services)t.reload(e)}scheduleDidChangeSkills(){void 0===this.changeTimer&&(this.changeTimer=setTimeout((()=>{this.changeTimer=void 0;for(const e of Array.from(this.onChangeCallbacks))e()}),pD.CHANGE_COALESCE_MS))}ensureChangeListenersRegistered(){void 0===this.disposeChangeListeners&&(this.disposeChangeListeners=this.services.map((e=>e.onDidChangeSkills((()=>this.scheduleDidChangeSkills())))))}disposeChangeListenersIfUnused(){if(!(this.onChangeCallbacks.size>0||void 0===this.disposeChangeListeners)){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0,void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0)}}onDidChangeSkills(e){return this.onChangeCallbacks.add(e),this.ensureChangeListenersRegistered(),()=>{this.onChangeCallbacks.delete(e),this.disposeChangeListenersIfUnused()}}dispose(){if(void 0!==this.changeTimer&&(clearTimeout(this.changeTimer),this.changeTimer=void 0),this.onChangeCallbacks.clear(),void 0!==this.disposeChangeListeners){for(const e of this.disposeChangeListeners)e();this.disposeChangeListeners=void 0}for(const e of this.services)e.dispose()}}pD.CHANGE_COALESCE_MS=1500;const fD=`/${pm.configDir}/${pm.subdir}/`;function mD(e,t){if((e.disabledEnvironments??[]).includes(t))return!1;const r=e.environments??[];return 0===r.length||r.includes(t)}const gD=(0,l.h)("skill-sync-manifest"),wD=".sync-manifest.json",yD=new Set(["EPERM","EBUSY"]),vD=[20,50,100],bD=new Map;async function SD(e,t){try{const r=await(0,Co.readFile)((0,s.join)(e,wD),"utf-8"),n=JSON.parse(r);return function(e){if(!function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}(e))return!1;const t=e;return"number"==typeof t.version&&"object"==typeof t.skills&&null!==t.skills&&!Array.isArray(t.skills)&&(void 0===t.lastInventoryAt||"number"==typeof t.lastInventoryAt)}(n)?n:(gD.warn(t,"Manifest failed schema validation, resetting",{skillDir:e}),{version:1,skills:{}})}catch(r){return r instanceof Error&&"ENOENT"===Sc(r)||gD.debug(t,"Failed to read sync manifest, resetting",{skillDir:e,error:String(r)}),{version:1,skills:{}}}}function kD(e,t,r){e.skills[t]={lastSyncedAt:r}}function _D(e,t){delete e.skills[t]}var CD=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});const ED=(0,l.h)("builtin-skills-sync");function xD(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function PD(e){for(const t of Object.keys(e.resources??{}))if(0===t.length||t.includes("\\")||t.includes("\0")||s.posix.isAbsolute(t)||s.posix.normalize(t)!==t||t.split("/").includes("..")||"SKILL.md"===s.posix.basename(t)||!t.endsWith(".md"))throw new Error(`Unsafe managed skill resource path: ${JSON.stringify(t)}`)}function RD(e){const t=eh(e.content),r=xD(t.data)?t.data:{};return th(`${t.content.trim()}\n`,function(e,t){const r={...t??{},name:e.id,description:e.description};delete r.disabledEnvironments,e.disableModelInvocation?r["disable-model-invocation"]=!0:delete r["disable-model-invocation"],e.environments&&e.environments.length>0?r.environments=e.environments:delete r.environments,e.disabledEnvironments&&e.disabledEnvironments.length>0?r["disabled-environments"]=e.disabledEnvironments:delete r["disabled-environments"];const n={...xD(r.metadata)?r.metadata:{}};return delete n.environments,delete n.disabledEnvironments,delete n["disabled-environments"],Object.keys(n).length>0?r.metadata=n:delete r.metadata,r}(e,r))}async function ID(e,t,r){const n=(0,s.join)(t,r.id),o=(0,s.join)(n,"SKILL.md"),i=r.fileContent,a=Object.keys(r.resources),c=await TD(n);if(a.length>0||c.length>0){const e=new Map([["SKILL.md",i],...Object.entries(r.resources)]),o=new Set(["SKILL.md",...c]);if(o.size===e.size&&[...e.keys()].every((e=>o.has(e)))){let t=!0;for(const[r,o]of e)try{if(await(0,Co.readFile)((0,s.join)(n,...r.split("/")),"utf-8")!==o){t=!1;break}}catch{t=!1;break}if(t)return!1}return await async function(e,t){const r=(0,s.join)(e,t.id),n=await(0,Co.mkdtemp)((0,s.join)(e,`.${t.id}-staging-`)),o=`${n}-backup`;let i=!1;try{await(0,Co.writeFile)((0,s.join)(n,"SKILL.md"),t.fileContent,"utf-8");for(const[e,r]of Object.entries(t.resources)){const t=(0,s.join)(n,...e.split("/"));await(0,Co.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,Co.writeFile)(t,r,"utf-8")}try{await(0,Co.rename)(r,o),i=!0}catch(e){if(!(e instanceof Error)||"ENOENT"!==Sc(e))throw e}try{await(0,Co.rename)(n,r)}catch(e){throw i&&(await(0,Co.rename)(o,r),i=!1),e}i&&(await(0,Co.rm)(o,{recursive:!0,force:!0}),i=!1)}finally{await(0,Co.rm)(n,{recursive:!0,force:!0})}}(t,r),!0}try{if(await(0,Co.readFile)(o,"utf-8")===i)return!1}catch(t){t instanceof Error&&"ENOENT"===Sc(t)||ED.warn(e,"Unexpected error reading skill file",{skillId:r.id,error:String(t)})}return await(0,Co.mkdir)(n,{recursive:!0}),await(0,Co.writeFile)(o,i,"utf-8"),!0}async function TD(e,t=""){const r=t?(0,s.join)(e,...t.split("/")):e;let n;try{n=await(0,Co.readdir)(r,{withFileTypes:!0})}catch(e){if(e instanceof Error&&"ENOENT"===Sc(e))return[];throw e}const o=[];for(const r of n){const n=t?`${t}/${r.name}`:r.name;r.isDirectory()?o.push(...await TD(e,n)):r.isFile()&&r.name.endsWith(".md")&&"SKILL.md"!==n&&o.push(n)}return o}async function AD(e,t){try{return(await(0,Co.readdir)(t,{withFileTypes:!0})).filter((e=>e.isDirectory()&&!e.name.startsWith("."))).map((e=>e.name))}catch(r){return r instanceof Error&&"ENOENT"===Sc(r)||ED.warn(e,"Failed to list skills directory, skipping cleanup",{skillDir:t,error:String(r)}),[]}}async function $D(e,t={}){const r={stack:[],error:void 0,hasError:!1};try{const i=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t}(r,(0,$.VI)(e.withName("syncBuiltinSkills")),!1).ctx,a=Date.now(),c=t.userHome??(0,o.homedir)(),l=t.skillDir??ym(c).dirPath;await(0,Co.mkdir)(l,{recursive:!0});const[u,d]=await Promise.all([SD(l,i),AD(i,l)]),h=u.lastInventoryAt;(void 0===h||a-h>=864e5)&&(await async function(e,t,r,n){try{const o=await Promise.all(r.map((async e=>{const r=(0,s.join)(t,e),[o,i]=await Promise.all([MD((0,s.join)(r,"SKILL.md")),"canvas"===e?MD((0,s.join)(r,"sdk")):Promise.resolve(!1)]);return{skill_id:e,has_skill_md:o,has_sdk_dir:i,last_synced_at:n.skills[e]?.lastSyncedAt??null}})));ED.info(e,"managed_skills.startup_inventory",{skills_on_disk:o,manifest_present:Object.keys(n.skills).length>0})}catch(t){ED.warn(e,"Failed to emit managed skills startup inventory",{error:String(t)})}}(i,l,d,u),u.lastInventoryAt=a);const p=new Map;for(const e of t.managedSkills??[])(n=e.id)&&n===n.trim()&&!(n.includes("..")||n.includes("/")||n.includes("\\"))?p.set(e.id,e):ED.warn(i,"Skipping managed skill with unsafe id",{skillId:e.id});const f=void 0===t.canvasKit?void 0:bm(c,t.canvasKit).dirPath,m=void 0!==f&&await MD((0,s.join)(f,vm)),g=new Set([...p.keys(),...d,...m?[vm]:[]]),w=e=>void 0!==f&&e===vm?f:l,y=e=>void 0!==f&&e===vm?m:d.includes(e);let v=0,b=0;const S=[];for(const e of g)try{const t=p.get(e),r=u.skills[e],n=r?a-r.lastSyncedAt:0,o=void 0!==r&&n>2592e5,c=void 0!==t&&mD(t,"local"),d=void 0!==t&&!c,h=void 0!==r||y(e),f=w(e);if(t&&!1!==t.enabled&&c)PD(t),f!==l&&await(0,Co.mkdir)(f,{recursive:!0}),await ID(i,f,{id:e,fileContent:RD(t),resources:t.resources??{}})?v++:b++,kD(u,e,a);else if(!1===t?.enabled||d||o){const n=!1===t?.enabled?"enabled_false":d?"environment_ineligible":"grace_expired";await(0,Co.rm)((0,s.join)(f,e),{recursive:!0,force:!0}),_D(u,e),h&&(S.push(e),ED.info(i,"managed_skills.removed",{skill_id:e,reason:n,server_enabled:t?.enabled??null,had_manifest_entry:void 0!==r,last_synced_ms_ago:r?a-r.lastSyncedAt:null}))}else r||kD(u,e,a)}catch(t){ED.warn(i,"Failed to apply skill, will retry next sync",{skillId:e,error:String(t)})}try{await function(e,t){const r=(bD.get(e)??Promise.resolve()).then((()=>async function(e,t){const r=(0,s.join)(e,`${wD}.${process.pid}.${(0,bo.randomBytes)(6).toString("hex")}.tmp`);await(0,Co.mkdir)(e,{recursive:!0});try{await(0,Co.writeFile)(r,JSON.stringify(t,null,2),"utf-8"),await async function(e,t){for(let r=0;;r++)try{return void await(0,Co.rename)(e,t)}catch(e){const t=Sc(e),n=vD[r];if(void 0===n||void 0===t||!yD.has(t))throw e;await(0,Or.cb)(n)}}(r,(0,s.join)(e,wD))}catch(e){throw await(0,Co.rm)(r,{force:!0}).catch((()=>{})),e}}(e,t))),n=r.catch((()=>{}));return bD.set(e,n),n.then((()=>{bD.get(e)===n&&bD.delete(e)})),r}(l,u)}catch(e){!function(e){if(e instanceof Error&&"ENOENT"===Sc(e))return!0;const t=String(e);return t.includes("ENOENT")||t.includes("no such file or directory")}(e)?ED.warn(i,"Failed to persist sync manifest",{skillDir:l,error:String(e)}):ED.debug(i,"Skipped persisting sync manifest, path removed concurrently",{skillDir:l,error:String(e)})}return{synced:v,upToDate:b,removed:S}}catch(e){r.error=e,r.hasError=!0}finally{CD(r)}var n}async function MD(e){try{return await(0,Co.stat)(e),!0}catch(e){const t=Sc(e);if("ENOENT"===t||"ENOTDIR"===t)return!1;throw e}}const DD=(0,l.h)("managed-skills-sync");function OD(e,t,r,n,o,s){const i=[],a=e.mcpServers;if(!a)return i;for(const[e,c]of Object.entries(a)){const a=c,l=`plugin-${n}-${e}`,u=e;a.url?i.push({identifier:l,name:u,marketplace:t,marketplaceId:r,pluginName:n,pluginId:o,pluginSource:s,type:"streamableHttp",url:a.url,headers:a.headers,auth:a.auth,tls:a.tls,enabledTools:a.enabledTools,placement:a.placement,projectManaged:!1,pluginManaged:!0}):a.command&&i.push({identifier:l,name:u,marketplace:t,marketplaceId:r,pluginName:n,pluginId:o,pluginSource:s,type:"stdio",command:a.command,args:a.args??[],env:a.env??{},cwd:a.cwd,envFile:a.envFile,enabledTools:a.enabledTools,projectManaged:!1,pluginManaged:!0})}return i}function FD(e){try{const t=new URL(e),r=new URL(t.pathname,t.origin);return r.search=t.search,r.pathname.endsWith("/")&&r.pathname.length>1&&(r.pathname=r.pathname.slice(0,-1)),"/"===r.pathname?r.origin+r.search:r.toString()}catch{return e.toLowerCase().trim()}}class ND{constructor(e){this.pluginsService=e}async getPluginMcpServers(){const e=await this.pluginsService.reload(),t=[];for(const r of e){const e="marketplace"in r.identifier.sourceInfo?r.identifier.sourceInfo.marketplace:void 0,n="marketplaceDbId"in r.identifier.sourceInfo?r.identifier.sourceInfo.marketplaceDbId:void 0,o=r.identifier.sourceInfo.name,s="pluginDbId"in r.identifier.sourceInfo?r.identifier.sourceInfo.pluginDbId:void 0,i=r.mcpConfig;i&&t.push(...OD(i,e,n,o,s,r.identifier.source))}return function(e){const t=[],r=new Set;for(const n of e){if("streamableHttp"!==n.type||!n.url){t.push(n);continue}const e=FD(n.url);r.has(e)||(r.add(e),t.push(n))}return t}(t)}}var LD=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function jD(e,t){return void 0===e?[]:(Array.isArray(e)?e:[e]).map((e=>({...e,userHomeDir:t})))}class UD{constructor(e,t,r,n,o,s){this.workspacePaths=e,this.userHomeDirectory=t,this.getSettings=r,this.marketplaceOptions=n,this.localPluginVariablesLookup=s,this.plugins=[],this._loadFailures=[],this._pluginSetIncomplete=!0,this._retainedFromPreviousLoad=0,this._wasFirstLoad=!0,this.loadedOnce=!1,this._extensionPlugins=new Map,this._extensionPluginOriginalPaths=new Map,this.pluginLogger=o??Tp,this.reload()}async getAllEnabledPlugins(){return await this.ensureLoaded(),[...this.plugins]}getLoadFailures(){return[...this._loadFailures]}isPluginSetIncomplete(){return this._pluginSetIncomplete}getLoadDiagnostics(){return{userHomeDirectory:this.userHomeDirectory,pluginsLoaded:this.plugins.length,retainedFromPreviousLoad:this._retainedFromPreviousLoad,wasFirstLoad:this._wasFirstLoad,sourceUnavailable:this._pluginSetIncomplete}}async reload(){return this.loadPromise||(this.loadPromise=this.load().then((async e=>{const t=!this.loadedOnce;let r=[];try{r=await this._reloadExtensionPlugins()}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugins after base load success: ${kc(e)}`)}const n=e.sourceUnavailable?this._retainPluginsMissingFromPartialLoad(e.plugins):[],o=[...e.plugins,...n],s=new Set(o.map((e=>e.installPath))),i=r.filter((e=>!s.has(e.installPath)));return this.plugins=[...o,...i],e.sourceUnavailable||(this._loadFailures=e.failures),this._pluginSetIncomplete=e.sourceUnavailable,this._retainedFromPreviousLoad=n.length,this._wasFirstLoad=t,this.loadedOnce=!0,this.pluginLogger.log("info",`Plugins reload completed: ${this.plugins.length} plugins loaded (${i.length} extension, ${n.length} retained), ${e.failures.length} failures`),this.plugins})).catch((async e=>{const t=!this.loadedOnce;this.pluginLogger.log("error",`Failed to load plugins: ${e}`),this._pluginSetIncomplete=!0,this._retainedFromPreviousLoad=0,this._wasFirstLoad=t;try{const e=await this._reloadExtensionPlugins(),t=new Set(this.plugins.map((e=>e.installPath)));this.plugins=[...this.plugins,...e.filter((e=>!t.has(e.installPath)))]}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugins after base load failure: ${kc(e)}`)}return this.loadedOnce=!0,this.plugins})).finally((()=>{this.loadPromise=void 0}))),this.loadPromise}_retainPluginsMissingFromPartialLoad(e){if(!this.loadedOnce)return[];const t=new Set(e.map(om));return this.plugins.filter((e=>"extension"!==e.identifier.source&&void 0===e.loadError&&e.installPath.length>0&&!t.has(om(e))))}async reloadPlugin(e){this.loadPromise&&await this.loadPromise;const t=jD(this.marketplaceOptions,this.userHomeDirectory);if(0===t.length)return;if(!(this.getSettings().loadCursorFirstParty??t.length>0))return;const r=t=>t.pluginDbId===e.pluginDbId,n=e=>"cursor-first-party"===e.identifier.source||"cursor-third-party"===e.identifier.source?e.identifier.sourceInfo:void 0,o=t=>n(t)?.pluginDbId===e.pluginDbId,s=(t,r)=>void 0!==t.pluginDbId?t.pluginDbId===e.pluginDbId:t.pluginName===r?.name&&t.marketplaceName===r?.marketplace;let i,a,c;for(const l of t){let t;try{t=await rm({...l,log:l.log??this.pluginLogger,pluginFilter:r})}catch(t){this.pluginLogger.log("error",`reloadPlugin: source load failed for ${e.name}: ${kc(t)}`);continue}const u=t.plugins.find((e=>o(e)&&void 0===e.loadError));if(void 0!==u){i=u;break}const d=t.plugins.find(o);if(void 0!==d&&void 0===a){const e=n(d);a=d,c=t.failures.find((t=>s(t,e)))}}if(void 0===i){if(void 0!==a){const t=n(a),r={...c??{pluginName:t?.name??e.name,errorMessage:a.loadError??"Plugin load failed",errorType:"unknown",...void 0!==t?.marketplace&&{marketplaceName:t.marketplace}},pluginDbId:e.pluginDbId};this._loadFailures=[...this._loadFailures.filter((e=>!s(e,t))),r]}return}const l=this.plugins.findIndex(o);if(-1===l)this.plugins=[...this.plugins,i];else{const e=[...this.plugins];e[l]=i,this.plugins=e}this.loadedOnce=!0;const u=n(i);return this._loadFailures=this._loadFailures.filter((e=>!s(e,u))),i}async registerExtensionPlugin({path:e,extensionId:t}){const r=(0,s.resolve)(e),n=await(0,Co.realpath)(r);if(!(await(0,Co.stat)(n)).isDirectory())throw new Error(`Extension plugin path is not a directory: ${n}`);const i=o.homedir();if(n.split(s.sep).filter(Boolean).length<3||n===i||"/"===n)throw new Error(`Extension plugin path is too broad (must be a specific subdirectory, not root or home): ${n}`);for(const[e,r]of this._extensionPlugins)if(e!==t&&r.has(n))throw new Error(`Plugin path ${n} is already registered by extension ${e}`);let a=this._extensionPlugins.get(t);if(a||(a=new Map,this._extensionPlugins.set(t,a)),a.has(n))return void this._rememberExtensionPluginOriginalPath({extensionId:t,originalPath:r,canonicalPath:n});const c=(0,s.basename)(n),l=await this._loadExtensionPluginContent(n,t);a.set(n,l),this._rememberExtensionPluginOriginalPath({extensionId:t,originalPath:r,canonicalPath:n}),this.pluginLogger.log("info",`Registered extension plugin: ${c} from ${n} (extension: ${t})`)}async unregisterExtensionPlugin({path:e,extensionId:t}){const r=this._extensionPlugins.get(t);if(!r)return!1;const n=(0,s.resolve)(e);let o;try{o=await(0,Co.realpath)(n)}catch{const e=this._extensionPluginOriginalPaths.get(t);o=e?.get(n)??n}const i=r.delete(o);return 0===r.size?(this._extensionPlugins.delete(t),this._extensionPluginOriginalPaths.delete(t)):i&&this._forgetExtensionPluginOriginalPath(t,o),i&&this.pluginLogger.log("info",`Unregistered extension plugin: ${o} (extension: ${t})`),i}async _loadExtensionPluginContent(e,t){const r=(0,s.basename)(e),n={name:r,localPath:e,extensionId:t},o=await Kf(e,r,{name:r,version:"0.0.0"});return o.displayName&&(n.name=o.displayName),{identifier:{source:"extension",sourceInfo:n},installPath:e,...void 0!==o.displayName&&{displayName:o.displayName},...void 0!==o.description&&{description:o.description},...void 0!==o.authorName&&{authorName:o.authorName},...void 0!==o.logoUrl&&{logoUrl:o.logoUrl},...void 0!==o.version&&{version:o.version},...void 0!==o.homepage&&{homepage:o.homepage},...void 0!==o.repository&&{repository:o.repository},skills:o.skills,rules:o.rules,agents:o.agents,commands:o.commands,mcpConfig:o.mcpConfig??void 0,capabilities:o.capabilities,hooks:o.hooks}}_rememberExtensionPluginOriginalPath(e){let t=this._extensionPluginOriginalPaths.get(e.extensionId);t||(t=new Map,this._extensionPluginOriginalPaths.set(e.extensionId,t)),t.set(e.originalPath,e.canonicalPath)}_forgetExtensionPluginOriginalPath(e,t){const r=this._extensionPluginOriginalPaths.get(e);if(r){for(const[e,n]of r)n===t&&r.delete(e);0===r.size&&this._extensionPluginOriginalPaths.delete(e)}}_getExtensionPluginPaths(){const e=[];for(const[t,r]of this._extensionPlugins)for(const n of r.keys())e.push({canonicalPath:n,extensionId:t});return e}async _reloadExtensionPlugins(){const e=this._getExtensionPluginPaths(),t=[];for(const{canonicalPath:r,extensionId:n}of e)try{const e=await this._loadExtensionPluginContent(r,n),o=this._extensionPlugins.get(n);o&&o.set(r,e),t.push(e)}catch(e){this.pluginLogger.log("error",`Failed to reload extension plugin ${r}: ${kc(e)}`);const o=this._extensionPlugins.get(n),s=o?.get(r);s&&t.push(s)}return t}async ensureLoaded(){this.loadPromise?await this.loadPromise:this.loadedOnce||await this.reload()}async load(){const e={stack:[],error:void 0,hasError:!1};try{const t=(0,y.q6)().withName("LocalPluginsService.load"),r=(function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0})}(e,(0,$.VI)(t),!1),performance.now()),n=e=>{this.pluginLogger.increment(`local_plugins_service.load.${e}`,1),this.pluginLogger.distribution("local_plugins_service.load.duration",performance.now()-r,{outcome:e})},o=this.getSettings(),i=jD(this.marketplaceOptions,this.userHomeDirectory),a=o.importThirdPartyPlugins,c=o.loadUserLocalPlugins??!0,l=o.loadCursorFirstParty??i.length>0;if(!a&&!l&&!c)return this.pluginLogger.log("info","Skipping plugin loading, cursor 1p, 3p, and user-local plugins are disabled"),{plugins:[],failures:[],sourceUnavailable:!1};this.pluginLogger.increment("local_plugins_service.load.start",1);const u=(e,t)=>{this.pluginLogger.increment("local_plugins_service.load_plugin.error",1),this.pluginLogger.log("error",`Cursor plugin load error ${e.name}@${e.version}: ${t?.message??String(t)}`)};try{const e=await async function(e,t={}){const r=t.log??Tp,n=performance.now(),o=t.loadClaude??!0,i=t.loadUserLocal??!0,a=t.marketplaceSources??[],c=t.loadCursorFirstParty??a.length>0,l=[],u=[];let d;o&&l.push(Xf(e,0,{userHomeDir:t.userHomeDir,onError:t.onError,log:r})),c&&a.length>0&&(d=Promise.allSettled(a.map((e=>rm({...e,userHomeDir:e.userHomeDir??t.userHomeDir,log:e.log??r}))))),i&&l.push(async function(e={}){const t=e.log??Tp,r=performance.now(),n=e.userHomeDir??process.env.HOME;if(!n)return t.log("info","loadUserLocalPlugins: no home directory available, skipping"),[];const o=(0,s.join)(n,".cursor","plugins","local");let i;try{i=await(0,Co.readdir)(o,{withFileTypes:!0})}catch{return t.log("info",`loadUserLocalPlugins: ${o} not found or not readable (${(performance.now()-r).toFixed(1)}ms)`),[]}const a=await(0,Co.realpath)(o).catch((()=>(0,s.resolve)(o))),c=[];for(const r of i){if(!r.isDirectory()&&!r.isSymbolicLink())continue;if(r.name.startsWith("."))continue;const n=(0,s.join)(o,r.name);try{if(r.isSymbolicLink()){let e;try{e=await(0,Co.realpath)(n)}catch(e){t.log("warn",`loadUserLocalPlugin ${r.name} rejected: failed to resolve symlink (${e instanceof Error?e.message:String(e)})`);continue}try{vf(a,e)}catch{t.log("warn",`loadUserLocalPlugin ${r.name} rejected: symlink target ${e} is outside ${o}`);continue}}if(!(await(0,Co.stat)(n)).isDirectory()){r.isSymbolicLink()&&t.log("warn",`loadUserLocalPlugin ${r.name} rejected: symlink target is not a directory`);continue}const s=performance.now(),i=await(e.localPluginVariablesLookup?.(r.name)),{displayName:l,description:u,authorName:d,logoUrl:h,version:p,homepage:f,repository:m,variablesSchema:g,skills:w,rules:y,agents:v,commands:b,mcpConfig:S,capabilities:k,hooks:_}=await Kf(n,r.name,void 0,{configuredVariables:i,log:t}),C={source:"user-local",sourceInfo:{name:r.name,localPath:n}};c.push({identifier:C,installPath:n,...void 0!==l&&{displayName:l},...void 0!==u&&{description:u},...void 0!==d&&{authorName:d},...void 0!==h&&{logoUrl:h},...void 0!==p&&{version:p},...void 0!==f&&{homepage:f},...void 0!==m&&{repository:m},variablesSchema:g,skills:w,rules:y,agents:v,commands:b,mcpConfig:S??void 0,capabilities:k,hooks:_}),t.log("info",`loadUserLocalPlugin ${r.name} loaded in ${(performance.now()-s).toFixed(1)}ms`)}catch(e){t.log("error",`loadUserLocalPlugin ${r.name} failed: ${e instanceof Error?e.message:String(e)}`)}}return t.log("info",`loadUserLocalPlugins completed in ${(performance.now()-r).toFixed(1)}ms (${c.length} plugins loaded)`),c}({userHomeDir:t.userHomeDir,log:r,localPluginVariablesLookup:t.localPluginVariablesLookup}));const[h,p]=await Promise.all([Promise.allSettled(l),d??Promise.resolve([])]);let f=!1;const m=[];for(const e of p)"rejected"!==e.status?(e.value.sourceUnavailable&&(f=!0),m.push(...e.value.plugins),u.push(...e.value.failures)):(f=!0,r.log("error",`marketplace source threw while loading; treating it as unavailable: ${String(e.reason)}`));for(const e of h)"rejected"!==e.status?m.push(...e.value):(f=!0,r.log("error",`plugin source threw while loading; treating it as unavailable: ${String(e.reason)}`));const g=new Set,w=[];for(const e of m){if(!e.installPath){w.push(e);continue}const t=await(0,Co.realpath)(e.installPath).catch((()=>e.installPath));g.has(t)||(g.add(t),w.push(e))}const y=new Map,v=[];for(const e of w){const t=nm(e);if(void 0!==t){const r=y.get(t),n=!e.loadError;if(!0===r)continue;if(!1===r&&n){const r=v.findIndex((e=>nm(e)===t&&e.loadError));-1!==r&&v.splice(r,1),y.set(t,!0),v.push(e);continue}y.set(t,n)}v.push(e)}const b=performance.now()-n;return r.log("info",`loadAllPlugins completed in ${b.toFixed(1)}ms (claude=${o}, userLocal=${i}, marketplace=${a.length} sources, total=${v.length} plugins, failures=${u.length}, sourceUnavailable=${f})`),{plugins:v,failures:u,sourceUnavailable:f}}(this.workspacePaths,{userHomeDir:this.userHomeDirectory,loadClaude:a,loadUserLocal:c,loadCursorFirstParty:l&&i.length>0,marketplaceSources:i.length>0?i.map((e=>({...e,onCursorError:u}))):void 0,onError:(e,t)=>{this.pluginLogger.log("error",`Claude plugin load error ${e.raw}: ${t?.message??String(t)}`)},log:this.pluginLogger,localPluginVariablesLookup:this.localPluginVariablesLookup});return n("success"),this.pluginLogger.log("info",`Plugins loaded in ${(performance.now()-r).toFixed(1)}ms`),e}catch(e){return n("error"),this.pluginLogger.log("error",`Failed to load all plugins: ${kc(e)}`),{plugins:[],failures:[],sourceUnavailable:!0}}}catch(t){e.error=t,e.hasError=!0}finally{LD(e)}}}const BD=["parse binary","parse json"],WD=["decompression failed","unsupported response encoding","unsupported content type","protocol error: promised"],HD=new Set([1,4,10,14]),qD=new Set(["AbortError","TimeoutError"]),zD=["ECONN","ENOT","ETIMEDOUT","EPIPE","EAI_","EHOST","ENET","ERR_HTTP2","ERR_SSL","ERR_TLS","UND_ERR","CERT_","DEPTH_ZERO_SELF_SIGNED_CERT","SELF_SIGNED_CERT","UNABLE_TO_"];function GD(e,t){return t.some((t=>e.startsWith(t)))}function VD(e){if(e instanceof Error&&qD.has(e.name))return!0;const t=function(e){if("object"==typeof e&&null!==e&&"code"in e)return"string"==typeof e.code?e.code:void 0}(e);return void 0!==t&&GD(t,zD)}function KD(e){const t=function(e){if(e instanceof Error&&"ConnectError"===e.name&&"code"in e&&"number"==typeof e.code&&"rawMessage"in e&&"string"==typeof e.rawMessage)return{code:e.code,text:e.rawMessage,cause:e.cause}}(e);if(void 0===t)return VD(e)?"transport":"other";const{code:r,text:n,cause:o}=t;return GD(n,BD)?"reply_schema":GD(n,WD)?"reply_encoding":n.startsWith("http/2 stream closed with error code")||HD.has(r)||VD(o)?"transport":"other"}var JD=r("../proto/dist/generated/aiserver/v1/dashboard_pb.js");const ZD=BigInt(0),XD=BigInt(8),QD=BigInt(16),YD=BigInt(65535);function eO(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch{return}}function tO(e){let t=e.trim().replace(/\.+$/,"").toLowerCase();if(t.startsWith("[")){const e=t.indexOf("]");-1!==e&&(t=t.slice(1,e))}else if(t.split(":").length-1==1){const e=t.lastIndexOf(":"),r=t.slice(e+1);Array.from(r).every((e=>/\d/.test(e)))&&(t=t.slice(0,e))}return t}function rO(e){const t=e.split(".");if(4!==t.length)return;let r=ZD;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<>QD&YD)),t.push(Number(o.value&YD))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function oO(e){return rO(e)??function(e){const t=tO(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=nO(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<7?void 0:{version:6,value:[...n,...new Array(8-s).fill(0),...o].reduce(((e,t)=>e<i)return!1;const a=BigInt(i-s);return o.value>>a==n.value>>a}(r,n);if(n.startsWith("*.")){const e=n.slice(2);return r===e||r.endsWith(`.${e}`)}return r===n}function iO(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}function aO(e,t){if(iO(e,t))return!0;if(e.includes("://")){let r,n;try{r=new URL(e),n=new URL(t)}catch{return!1}if(""!==r.username||""!==r.password||""!==n.username||""!==n.password||r.protocol!==n.protocol||r.port!==n.port)return!1;const o=tO(r.hostname);return!!sO(tO(n.hostname),o)&&iO(`${r.pathname}${r.search}`,`${n.pathname}${n.search}`)}const r=function(e){const t=function(e){const t=e.trim(),r=t.indexOf("["),n=t.indexOf("]");if(-1!==r&&n>r){const e=t.slice(r+1,n);if(t.slice(n+1).startsWith("("))return`${t.slice(0,r)}${e}`}return t}(e).trim();if(0===t.length)return;const r=t.lastIndexOf("/");if(!t.includes("://")&&r>0&&/^\d+$/.test(t.slice(r+1).trim())){const e=tO(t.slice(0,r));if(e.length>0)return`${e}/${t.slice(r+1).trim()}`}const n=eO(t);if(n)return tO(n.hostname);let o=t;const s=o.indexOf("://");-1!==s&&(o=o.slice(s+3));const i=o.indexOf("/");-1!==i&&(o=o.slice(0,i));const a=tO(function(e){if(e.startsWith("[")){const t=e.indexOf("]");return-1!==t?e.slice(1,t):e}const t=e.split(":");return 2===t.length&&Array.from(t[1]??"").every((e=>/\d/.test(e)))?t[0]:e}(o));if(0!==a.length){if(a.startsWith("*.")){const e=a.slice(2);if(0===e.length||e.includes("*")||e.includes("?"))return;return a}if(!a.includes("*")&&!a.includes("?"))return a}}(e),n=function(e){const t=eO(e);if(t)return tO(t.hostname);const r=tO(e);return r.length>0?r:void 0}(t);return!(!r||!n)&&sO(n,r)}async function cO(e){try{return await e.current()}catch{return}}function lO(e){try{const t=new URL(e);return`${t.protocol}//${t.host}${t.pathname}`}catch{return}}function uO({failOpenWhenEmpty:e,server:t,settings:r}){if(!0!==r?.allowedMcpConfiguration?.requireMcpServersInTeamNetworkAllowlist||void 0===t.url)return{blocked:!1};const n=function(e){return!0===e.cloudAgentMcpAllowlistApplied&&!1===e.mirrorSandboxAllowlistForEgress?e.cloudAgentEgressAllowlist??[]:e.networkAllowlist??[]}(r).map((e=>e.trim())).filter((e=>e.length>0));return 0===n.length&&e||Jv(t.url,n)?{blocked:!1}:{blocked:!0,reason:"teamNetworkAllowlist",message:"Not on the team network allowlist"}}function dO(e){const t=e?.trim();return t&&t.length>0?t:void 0}function hO(e,t,r){if(!0===r?.useCorePolicy)return!function(e,t){if(void 0===t)return!0;if(!0===t.disableAll)return!1;if(SC(e))return!0;if(EC(e,t.offMcpServerRules))return!1;const r=t.allowedMcpServers??[];return 0===r.length&&!0!==t.allowUserOverrideMcpServers||!!function(e,t){return t.length>0&&function(e,t){return t.some((t=>{const r=kC(t.command),n=_C(t.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==e.command&&(0,Ob.mD)(r,e.command),s=void 0===n||void 0!==e.url&&(0,Ob.vc)(n,e.url);return o&&s}))}(e,t)}(e,r)||!0===t.allowUserOverrideMcpServers&&!CC(e,t.deniedMcpServers)}(e,t);if(void 0===t)return!1;if(!0===t.disableAll)return!0;const n=t.allowedMcpServers;return 0!==n.length&&!n.some((t=>function(e,t){const r=dO(e.command),n=dO(e.serverUrl);if(void 0===r&&void 0===n)return!1;const o=void 0===r||void 0!==t.command&&function(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}(r,t.command),s=void 0===n||void 0!==t.url&&aO(n,t.url);return o&&s}(t,e)))}class pO{constructor(e,t={}){this.dashboardClient=e,this.options=t}getTeamAdminSettings(){return this.dashboardClient.getTeamAdminSettingsOrEmptyIfNotInTeam(new JD.Byz(!0===this.options.supportsHostMcpBridgeExemption?{supportsHostMcpBridgeExemption:!0}:{}))}getTeamRepos(){return this.dashboardClient.getTeamReposOrEmptyIfNotInTeam(new JD.aYW({}))}}function fO(e,t){if("workspace"!==e)return[];const r=[],n=new Set;for(const e of t??[]){const t=e.trim();0===t.length||n.has(t)||(n.add(t),r.push(t))}return r}class mO{constructor(e){this.fetch=e}get(){const e=this.cached,t=void 0===e?1/0:Date.now()-e.fetchedAt;return void 0===e||t>6e5?(this.cached=void 0,this.refresh()):(t>3e5&&this.refresh().catch((()=>{})),Promise.resolve(e.value))}invalidate(){this.cached=void 0,this.inFlight=void 0}refresh(){if(void 0===this.inFlight){const e=this.fetch().then((t=>(this.inFlight!==e||void 0===t&&void 0!==this.cached||(this.cached={value:t,fetchedAt:Date.now()}),t))).finally((()=>{this.inFlight===e&&(this.inFlight=void 0)}));this.inFlight=e}return this.inFlight}}class gO{constructor(e,t,r={}){this.teamAdminSettingsProvider=e,this.defaultAllowlistProvider=t,this.options=r,this.lastFetchSucceeded=!0,this.lastFetchFailure="other",this.settingsGeneration=0,this.lastFetchedGeneration=0,this.settings=new mO((()=>this.fetchSettings())),this.droppedReplies=new WeakSet,this.hostMcpBridgeClients=new WeakSet,this.mcpServerByClient=new WeakMap,this.teamRepos=new mO((()=>this.teamAdminSettingsProvider.getTeamRepos())),this.defaultAllowlist=new mO((()=>this.fetchDefaultAllowlist())),this.getTeamAdminSettings(),this.prefetchTeamRepos()}async prefetchTeamRepos(){try{await this.teamRepos.get()}catch{}}invalidateCache(){this.settingsGeneration+=1,this.settings.invalidate(),!0!==this.options.preserveTeamReposOnInvalidate&&this.teamRepos.invalidate(),this.defaultAllowlist.invalidate()}invalidateTeamRepos(){this.teamRepos.invalidate()}async refreshTeamAdminSettings(){try{await this.settings.refresh()}catch{}}async fetchSettings(){const{fetchIdentity:e}=this.options;if(void 0!==e)return this.fetchSettingsFor(e);const t=this.settingsGeneration;try{const e=await this.teamAdminSettingsProvider.getTeamAdminSettings();return this.lastFetchSucceeded=!0,t>=this.lastFetchedGeneration&&(this.lastFetchedSettings=e,this.lastFetchedGeneration=t),e}catch(e){throw this.lastFetchSucceeded=!1,this.lastFetchFailure=KD(e),e}}async fetchSettingsFor(e){const t=await cO(e),r=this.settingsGeneration;if(void 0===t)throw this.lastFetchSucceeded=!1,this.lastFetchFailure="other",new Error("No one is named whose team settings a fetch would read");try{const e=await this.teamAdminSettingsProvider.getTeamAdminSettings();return void 0!==e&&this.droppedReplies.delete(e),this.isSentFor(e,t)?(this.lastFetchSucceeded=!0,r>=this.lastFetchedGeneration&&(this.lastFetchedSettings=e,this.lastFetchedGeneration=r),e):e}catch(e){throw this.lastFetchSucceeded=!1,this.lastFetchFailure=KD(e),e}}getTeamAdminSettings(){const{fetchIdentity:e}=this.options;return void 0!==e?this.getTeamAdminSettingsFor(e):this.settings.get().catch((()=>{}))}async getTeamAdminSettingsFor(e){const t=await this.settings.get().catch((()=>{})),r=await cO(e);if(void 0===t)return void(this.isSentFor(this.lastFetchedSettings,r)||(this.settingsGeneration+=1));if(void 0===r)return this.answerAsFailedRead();if(this.isSentFor(t,r))return t;let n=t,o=r;const s=await this.settings.get().catch((()=>{}));if(s!==t){if(void 0===s)return this.answerAsFailedRead();if(this.isSentFor(s,r))return s;if(o=await cO(e),void 0===o)return this.answerAsFailedRead();if(this.isSentFor(s,o))return s;n=s}this.droppedReplies.has(n)||(this.droppedReplies.add(n),this.settingsGeneration+=1,this.settings.invalidate());const i=await this.settings.get().catch((()=>{}));return void 0!==i?this.isSentFor(i,r)||this.isSentFor(i,o)||this.isSentFor(i,await cO(e))?i:this.answerAsFailedRead():void 0}answerAsFailedRead(){this.settingsGeneration+=1,this.lastFetchSucceeded=!1,this.lastFetchFailure="other"}isSentFor(e,t){return void 0!==e&&void 0!==t&&this.options.fetchIdentity?.sentFor(e)===t}async getDotCursorProtection(){const e=await this.getTeamAdminSettings();return e?.dotCursorProtection??!0}async getShouldBlockMcp(){const e=await this.getTeamAdminSettings();return!(!e?.autoRunControls?.enabled||!e?.autoRunControls?.disableMcpAutoRun)}async getDeleteFileProtection(){const e=await this.getTeamAdminSettings();return!(!e?.autoRunControls?.enabled||!e?.autoRunControls?.deleteFileProtection)}async getIsHeadlessDisabled(){return"disabled"===(await this.getHeadlessCliPolicy()).kind}async getHeadlessCliPolicy(){const e=await this.getTeamAdminSettings();return void 0!==e||this.lastFetchSucceeded?!0===e?.cliSettings?.disableHeadless?{kind:"disabled"}:{kind:"enabled"}:{kind:"unavailable"}}async getMcpServerBlockInfo(e){const t=await this.getTeamAdminSettings(),r=t?.allowedMcpConfiguration,n=await this.isMcpSettingsOverhaulEnabled({disableExposureLog:!0});if(!0===r?.disableAll)return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};if(this.isHostMcpBridge(t,e))return{blocked:!1,hostMcpBridge:!0};if(EC(e,r?.offMcpServerRules))return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};if(n){if(hO(e,r,{useCorePolicy:!0}))return{blocked:!0,reason:"teamPolicy",message:"Blocked by team policy"};const n=await this.getMcpNetworkControlsConfig(e),o=void 0===e.url?{allowed:!0}:(0,Ob.ME)(e.url,n);if(!o.allowed)return{blocked:!0,reason:"teamNetworkAllowlist",message:o.message};const s=uO({failOpenWhenEmpty:!1,server:e,settings:t});if(s.blocked)return s}if(!n){const r=function({isMcpAccessNetworkAllowlistEnabled:e,server:t,settings:r}){return e&&!0===r?.allowedMcpConfiguration?.requireMcpServersInTeamNetworkAllowlist?uO({failOpenWhenEmpty:!0,server:t,settings:r}):{blocked:!1}}({isMcpAccessNetworkAllowlistEnabled:await this.isMcpAccessNetworkAllowlistEnabled(),server:e,settings:t});if(r.blocked)return r}return void 0!==t||this.lastFetchSucceeded?{blocked:!1}:{blocked:!1,settingsUnavailable:!0}}async getManagedSlackWorkspaceLists(){const e=await this.getTeamAdminSettings()??this.lastFetchedSettings;return void 0===e?[]:function(e){return e.memberSlackManagedWorkspacesUnreadable?"unconfirmed":e.memberSlackManagedWorkspaces.map((e=>e.slackTeamIds)).filter((e=>e.length>0))}(e)}async getMcpNetworkControlsConfig(e){const t=await this.getTeamAdminSettings(),r=t?.allowedMcpConfiguration;if(await this.isMcpSettingsOverhaulEnabled()&&(void 0===e||!this.isHostMcpBridge(t,e))){const n="win32"===process.platform&&await this.isWin32UserExtensionStdioUnsandboxEnabled();return(0,Ob._N)({allowedMcpConfiguration:r,server:e,localAgentNetworkAllowlist:t?.networkAllowlist,blockMessage:"Not on the team network allowlist",aggregateManagedServerNetworkAllowlists:!1,stdioPlatform:process.platform,unsandboxUserExtensionStdio:n})}return{enabled:!1,localAgentNetworkAllowlist:t?.networkAllowlist,blockMessage:"Not on the team network allowlist"}}isHostMcpBridge(e,t){const r=this.options.hostMcpBridgeUrls;if(!0!==e?.cloudAgentMcpAllowlistApplied||void 0===r||void 0!==t.command||void 0===t.url)return!1;const n=lO(t.url);return void 0!==n&&r.some((e=>lO(e)===n))}recordHostMcpBridgeClient(e){this.hostMcpBridgeClients.add(e)}async isHostMcpBridgeClient(e){if(!this.hostMcpBridgeClients.has(e))return!1;const t=await this.getTeamAdminSettings();return!0===t?.cloudAgentMcpAllowlistApplied&&!0!==t.allowedMcpConfiguration?.disableAll}recordMcpServerClient(e,t){this.mcpServerByClient.set(e,t)}async getMcpAdminToolLimit(e){if(await this.isHostMcpBridgeClient(e))return{kind:"none"};const t=this.mcpServerByClient.get(e);if(void 0===t)return{kind:"unknown_server"};const r=!0===this.options.mcpAdminToolLimitSurvivesFailedRead;let n=await this.getTeamAdminSettings();if(void 0===n&&!this.lastFetchSucceeded&&r&&(n=await this.getTeamAdminSettings()),void 0===n){if(this.lastFetchSucceeded)return{kind:"none"};if(!r)return{kind:"settings_unavailable"};const e=this.lastFetchFailure,t=this.lastFetchedGeneration===this.settingsGeneration?this.lastFetchedSettings:void 0;if(void 0===t)return{kind:"settings_unavailable",failure:e,noLimitApplies:!0};n=t}const o=function(e,t){const r=e?.find((e=>(0,Ob.rM)(e,t)));if(void 0!==r)return Lb({mode:r.toolAllowlistMode,tools:r.toolAllowlist})}(n.allowedMcpConfiguration?.allowedMcpServers,t);return void 0===o?{kind:"none"}:{kind:"limit",policy:o}}async isServerBlocked(e){return(await this.getMcpServerBlockInfo(e)).blocked}async getAutoRunControls(){const e=await this.getTeamAdminSettings();if(e?.autoRunControls?.enabled)return{enabled:e.autoRunControls.enabled,allowed:e.autoRunControls.allowed??[],blocked:e.autoRunControls.blocked??[],enableAllowlistMode:e.autoRunControls.enableAllowlistMode??!0,enableRunEverything:e.autoRunControls.enableRunEverything??!1,enableSmartAuto:e.autoRunControls.enableSmartAuto??!0,mcpToolAllowlist:e.autoRunControls.mcpToolAllowlist??[]}}async isReadControlEnabled(){try{return await(this.options.isReadControlEnabled?.())??!0}catch{return!1}}async isDenylistEnforcementKilled(){try{return!0===await(this.options.isAdminCommandDenylistEnforcementKilled?.())}catch{return!1}}async getAdminCommandDenylist(){if(await this.isDenylistEnforcementKilled())return{rules:[]};const e=await this.getTeamAdminSettings();return{rules:e?.autoRunControls?.adminCommandDenylist?.rules??[]}}async isMcpSettingsOverhaulEnabled(e){const t=this.options.isMcpSettingsOverhaulEnabled?.(e);return void 0!==t&&await t}async isWin32UserExtensionStdioUnsandboxEnabled(){try{const e=this.options.isWin32UserExtensionStdioUnsandboxEnabled?.();return void 0!==e&&await e}catch{return!1}}async getMcpToolControls(){const e=await this.getTeamAdminSettings(),t=e?.allowedMcpConfiguration;if(void 0===t)return;const r=function({autoRunControls:e,allowedMcpServers:t}){const r=!0===e?.enabled?e.mcpToolAllowlist??[]:[],n=function(e){return(e??[]).flatMap((e=>{const t=void 0===e.name?"":Fb(e.name);if(0===t.length)return[];const r=Lb({mode:e.toolAllowlistMode,tools:e.toolAllowlist});return[{name:t,policy:r,flattened:Ub(t,r)}]}))}(t);return{tools:(o=[...n.flatMap((e=>[...e.flattened])),...r],[...new Set(o)]),policies:n.map((e=>({name:e.name,policy:e.policy})))};var o}({autoRunControls:e?.autoRunControls,allowedMcpServers:t?.allowedMcpServers});return r.policies.length>0||r.tools.length>0?{enabled:!0,mcpToolAllowlist:r.tools,allowUserOverride:t?.allowUserOverrideMcpServers??!1,serverPolicies:r.policies}:void 0}async getNetworkAccessControls(){const e=await this.getTeamAdminSettings();return void 0!==e||this.lastFetchSucceeded?{allowlist:e?.networkAllowlist??[],denylist:e?.networkDenylist??[],available:!0}:{allowlist:[],denylist:[],available:!1}}async getSandboxingControls(){const e=await this.getTeamAdminSettings(),t=e?.autoRunControls?.sandboxingControls,r=(n=t?.sandboxReadBoundary,n===JD.h0i.WORKSPACE?"workspace":"system");var n;return{sandboxingDisabled:t?.sandboxing===JD.faf.DISABLED,networkingDisabled:t?.sandboxNetworking===JD._mX.ALWAYS_DISABLED,gitDisabled:t?.sandboxGit===JD.i24.ALWAYS_DISABLED,readBoundary:r,readAllowlistPaths:fO(r,t?.sandboxReadAllowlistPaths),allowUserOverrideReadAllowlist:!1!==t?.allowUserOverrideSandboxReadAllowlist}}async isAttributionDisabledByAdmin(){const e=await this.getTeamAdminSettings();return void 0===e&&!this.lastFetchSucceeded||(e?.attributionControls?.disableAttribution??!1)}async isComputerUseDisabledByAdmin(){const e=await this.getTeamAdminSettings();return void 0!==e?!1===e.computerUse:this.lastFetchedGeneration!==this.settingsGeneration||void 0===this.lastFetchedSettings&&!this.lastFetchSucceeded||!1===this.lastFetchedSettings?.computerUse}getDefaultNetworkAllowlist(){return this.defaultAllowlist.get().catch((()=>({allowlist:[],available:!1})))}async fetchDefaultAllowlist(){return this.defaultAllowlistProvider?{allowlist:await this.defaultAllowlistProvider.getDefaultNetworkAllowlist(),available:!0}:{allowlist:[],available:!0}}getTeamRepos(){return this.teamRepos.get()}async isMcpAccessNetworkAllowlistEnabled(){return await(this.options.isMcpAccessNetworkAllowlistEnabled?.())??!1}}const wO=new _y,yO={async resolveWorkspaceState(e){const t=e.workingDirectory??e.projectRoot??e.workspaceRoots?.[0],r=e.projectRoot??(void 0!==t?await Ya((0,y.q6)(),wO,t)??t:void 0),n=e.workspaceRoots??(void 0!==r?[r]:void 0!==t?[t]:[]);return{workingDirectory:t,projectRoot:r,projectDirectory:e.projectDirectory??(void 0!==r?_o(r):void 0),workspaceRoots:n,createdAt:new Date}}},vO=(0,l.h)("ControlledConversationActionManager");class bO{get signal(){return this.abortController.signal}get abortRequested(){return this.abortCalled}constructor(){this.abortCallbacks=[],this.abortController=new AbortController,this.acceptsActions=!0,this.disposed=!1,this.abortStarted=!1,this.abortCalled=!1,this.runActive=!1,this.unprocessedUserMessages=[],this.clientStream=(0,h.Jt)()}addAbortCallback(e){this.abortCallbacks.push(e)}abort(e,t){if(this.abortCalled=!0,this.abortController.signal.aborted||this.abortStarted)return;const r=t?.interruptedPendingToolCallResolutions;if(this.abortStarted=!0,!this.runActive){this.abortController.abort(e);for(const e of this.abortCallbacks)e();return void(this.abortCallbacks.length=0)}const n=this.abortController,o=[...this.abortCallbacks];this.abortCallbacks.length=0,this.submitConversationAction(new i.QFf({action:{case:"cancelAction",value:new i.TTG({reason:e,interruptedPendingToolCallResolutions:r})}})).catch((()=>{})).finally((()=>{n.abort(e);for(const e of o)e();if(this.abortController===n){const e=[...this.abortCallbacks];this.abortCallbacks.length=0;for(const t of e)t()}}))}async submitConversationAction(e){if(!this.acceptsActions)throw new h.W2("ControlledConversationActionManager is not accepting actions");if("userMessageAction"===e.action.case){const t=e.action.value.userMessage;t&&this.unprocessedUserMessages.push(t)}await this.clientStream.write(e)}queueFollowUpUserMessage(e){if(this.disposed||this.abortStarted)throw new h.W2("ControlledConversationActionManager run was aborted or disposed");this.unprocessedUserMessages.push(e)}async enqueueReplayableConversationAction(e){if("asyncAskQuestionCompletionAction"!==e.action.case)throw new TypeError("Only asyncAskQuestionCompletionAction can use enqueue acknowledgement");if(!this.acceptsActions)throw new h.W2("ControlledConversationActionManager is not accepting actions");this.clientStream.write(e).catch((()=>{}))}markMessageAsProcessed(e){this.unprocessedUserMessages=this.unprocessedUserMessages.filter((t=>t.messageId!==e.messageId))}requeueMessage(e){this.unprocessedUserMessages.some((t=>t.messageId===e.messageId))||this.unprocessedUserMessages.unshift(e)}getUnprocessedUserMessages(){return[...this.unprocessedUserMessages]}hasUnprocessedMessages(){return this.unprocessedUserMessages.length>0}close(){this.acceptsActions=!1,this.clientStream.close()}reopen(){this.disposed||this.acceptsActions||this.resetStream()}resetStream(){if(this.disposed)throw new h.W2("ControlledConversationActionManager disposed");this.acceptsActions=!1,this.clientStream.close(),this.clientStream=(0,h.Jt)(),this.acceptsActions=!0,this.abortController=new AbortController,this.abortStarted=!1;for(const e of this.unprocessedUserMessages)this.clientStream.write(new i.QFf({action:{case:"userMessageAction",value:new i.Vtf({userMessage:e})}})).catch((()=>{}))}async run(e,t){const r=this.clientStream;this.runActive=!0;try{for await(const n of r)try{await t.write(n)}catch(t){vO.error(e,"Error writing conversation action",t)}}catch(e){if(!(e instanceof h.W2))throw e}finally{this.clientStream===r&&(this.runActive=!1)}}dispose(){this.disposed||(this.disposed=!0,this.abortCallbacks.length=0,this.acceptsActions=!1,this.clientStream.throw(new h.W2("ControlledConversationActionManager disposed")))}}var SO=r("../cursor-sdk-local-runtime/dist/utils/logger.js"),kO=r("../agent-kv/dist/agent-store.js");const _O="x-blob-encryption-key";function CO(e,t){const r={...t};return void 0!==r[_O]||(0,kO.TU)(e)&&(r[_O]=e),r}const EO=new Map;function xO(e){if("userMessageAction"===e.action.case)return e.action.value.userMessage?.text}function PO(e,t,r){const n=e.runOptions?.requestedModel;return{conversationId:e.conversationId,generationId:e.conversationId,model:n?.modelId??"unknown",modelId:n?.modelId,modelParams:n?.parameters.map((e=>({id:e.id,value:e.value}))),loopCount:t,promptText:r}}function RO(e){return new i.QFf({action:{case:"userMessageAction",value:new i.Vtf({userMessage:new i.RGk({text:e})})}})}function IO(e){return e instanceof DOMException&&"AbortError"===e.name||e instanceof Error&&("AbortError"===e.name||"The operation was aborted"===e.message)}function TO(e){e?.catch((e=>{SO.Jz.warn("[agent-session-runner] fire-and-forget hook failed:",e)}))}class AO{constructor(e,t,r){this.inner=e,this.getToken=t,this.restMcpHost=r}async getDefinitions(e,t=!0){const r=await this.inner.getDefinitions(e,t);return Promise.all(r.map((async e=>{const t=await async function(e,t,r){if(!("url"in e)||!e.url||void 0===sb(e.url,r)||Object.keys(e.headers??{}).some((e=>e.toLowerCase()===ob)))return e;const n=await t();return void 0===n||0===n.length?e:{...e,headers:{...e.headers??{},[ob]:`Bearer ${n}`}}}(e.serverConfig,this.getToken,this.restMcpHost);return t===e.serverConfig?e:{...e,serverConfig:t}})))}clearCache(){this.inner.clearCache?.()}}const $O=new Set(["mcp.slack.com","setup.shopify.com"]);class MO{constructor(e,t){this.inner=e,this.resolver=t}async getDefinitions(e,t=!0){const r=await this.inner.getDefinitions(e,t);return Promise.all(r.map((async e=>{const t=await async function(e,t){if(!("url"in e)||!e.url)return e;const r=await async function(e,t,r,n=fetch){let o;try{o=new URL(e).hostname}catch{return t}const s=void 0!==sb(e,r.restMcpHost);if(!$O.has(o)&&!s)return t;let i=await r.resolve(e);if(!i&&s){const t=(await cx(e,n))?.clientId;void 0!==t&&(i={CLIENT_ID:t})}return i?t?void 0===ix(t.CLIENT_ID)?{...i,...t,CLIENT_ID:i.CLIENT_ID}:{...i,...t}:i:t}(e.url,e.auth,t);return r===e.auth?e:{...e,auth:r}}(e.serverConfig,this.resolver);return t===e.serverConfig?e:{...e,serverConfig:t}})))}clearCache(){this.inner.clearCache?.()}}class DO{constructor(e,t){this.storage=e,this.prefix=t}async loadTokens(e){return this.storage.loadTokens(this.prefix+e)}async saveTokens(e,t){return this.storage.saveTokens(this.prefix+e,t)}async loadClientInformation(e){return this.storage.loadClientInformation(this.prefix+e)}async saveClientInformation(e,t){return this.storage.saveClientInformation(this.prefix+e,t)}}class OO{constructor(e,t){this.storage=e,this.prefix=t}async isServerApproved(e,t,r){return this.storage.isServerApproved(this.prefix+e,t,r)}}class FO{constructor(e){this.higherPrecedenceSources=e}async load(e,t,r,n,o){for(const r of this.higherPrecedenceSources){const n=(await r.getDefinitions(e)).find((e=>e.identifier===t));if(void 0!==n)throw new TC(t,n.configPath??"another config")}return await o(e,r)}}class NO extends nI{constructor(e,t){super(e),this.shadowedClientsClosed=t}async closeAllClients(){await Promise.all([super.closeAllClients(),this.shadowedClientsClosed])}}async function LO(e){try{await(e.close?.())}catch{}}class jO{constructor(e){this.loaders=e}async load(e,t=!0){const r=await Promise.allSettled(this.loaders.map((({loader:r})=>r.load(e,t)))),n=r.find((e=>"rejected"===e.status));if(n)throw await Promise.allSettled(r.flatMap((e=>"fulfilled"===e.status?[e.value.closeAllClients()]:[]))),n.reason;const o=r.filter((e=>"fulfilled"===e.status)).map((e=>e.value)),s={},i=[];for(let e=0;e{})))}async loadClient(e,t,r=!1){for(const{loader:n,prefix:o}of this.loaders)if(t.startsWith(o)){t=t.slice(o.length);try{return await n.loadClient(e,t,r)}catch(e){if(e instanceof Error&&e.message.includes("not found in config"))continue;throw e}}throw new Error(`MCP client "${t}" not found in config`)}clearClient(e){for(const{loader:t,prefix:r}of this.loaders){if(!e.startsWith(r))continue;const n=e.slice(r.length);t.clearClient?.(n)}}clearAllMcpCaches(){for(const{loader:e}of this.loaders)e.clearAllMcpCaches?.()}}class UO{constructor(e,t,r,n,i=!1,a,c,l=s.join((0,o.homedir)(),".cursor","mcp.json"),u,d,h){const p=Array.isArray(e)?e:[e],f={}.location,m=[];"enterprise"===f?.source&&m.push({path:f.path,prefix:"enterprise-",scope:"enterprise"});for(let e=0;e({prefix:t,scope:r,fileSource:new bI(e,"enterprise"===r||"env"===r?EE:void 0)}))),y=[];for(const{prefix:e,scope:o,fileSource:s}of w){const l=i?"":e,d=new DO(t,l),p=new OO(n,l),f=w.flatMap((e=>{return t=e.scope,r=o,xE.indexOf(t)0?[new FO(f)]:[]],g=new SI(u?new MO(s,u):s,d,m,{authRedirectUrlGenerator:a,isLinkSharedPaymentTokenLogRedactionEnabled:h});y.push({prefix:l,loader:g})}this.loader=new jO(y)}static init(e,t,r,n=!1,o,i={}){const a=new AI(s.join(r,"mcp-auth.json"));(async function(e){await(0,Co.rm)(s.join(e,"mcp-cache.json"),{force:!0})})(r).catch((()=>{}));const c=n?{isServerApproved:()=>Promise.resolve(!0)}:new MC(s.join(r,"mcp-approvals.json"),t);return new UO(t,a,e,c,!0,void 0,o,void 0,i.defaultAuthResolver,void 0,i.isLinkSharedPaymentTokenLogRedactionEnabled)}async load(e,t=!0){return this.loader.load(e,t)}async loadClient(e,t,r=!1){return this.loader.loadClient(e,t,r)}clearClient(e){this.loader.clearClient(e)}clearAllMcpCaches(){this.loader.clearAllMcpCaches()}}const BO="cursor-plugins/local";function WO(e){var t;if(e)for(const r of e)if("object"==typeof(t=r)&&null!==t&&t.kind===BO)return r}class HO extends rI{constructor(e){super(e),this.runtimeManager=e,this.disposed=!1}async dispose(){this.disposed||(this.disposed=!0,await this.runtimeManager.closeAllClients())}}class qO{constructor(e){this.storagePath=e}async isServerDisabled(e){try{const t=await(0,Co.readFile)(this.storagePath,"utf8"),r=JSON.parse(t);return Array.isArray(r)?r.includes(e):(await this.writeDisabledServers([]),!1)}catch(e){if("object"==typeof e&&null!==e&&"code"in e&&"ENOENT"===e.code)return!1;throw e}}async writeDisabledServers(e){await(0,Co.mkdir)((0,s.dirname)(this.storagePath),{recursive:!0}),await(0,Co.writeFile)(this.storagePath,JSON.stringify(e,null,2))}}class zO{constructor(e,t){this.pluginMcpService=e,this.importThirdPartyPlugins=t}async getDefinitions(){let e;try{e=await this.pluginMcpService.getPluginMcpServers()}catch(e){return SO.Jz.warn("[cursor-config-mcp] Failed to enumerate plugin MCP servers:",e),[]}const t=[];for(const r of e){if(!this.importThirdPartyPlugins&&ZO(r))continue;const e=xI(r);e?t.push({identifier:r.identifier,authStorageKey:r.identifier,serverConfig:e,configPath:"",source:"plugin",metadata:{identifier:r.identifier,pluginName:r.pluginName,pluginSource:r.pluginSource}}):SO.Jz.warn("[cursor-config-mcp] Failed to initialize plugin MCP client:",{identifier:r.identifier,pluginName:r.pluginName,pluginSource:r.pluginSource,result:"invalid-config",errorMessage:"pluginMcpDescriptorToServerConfig returned undefined"})}return t}}class GO{constructor(e){this.servers=e}async getDefinitions(){return Object.entries(this.servers).map((([e,t])=>({identifier:e,authStorageKey:`inline:${e}`,serverConfig:JO(e,t),source:"inline",metadata:{source:"cursor-sdk"}})))}}function VO(e={}){const t=e.teamSettingsService??{getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getAdminCommandDenylist:async()=>({rules:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}},r=e.ignoreApprovals??!1,n=e.importThirdPartyPlugins??!1,i=void 0===e.isLinkSharedPaymentTokenLogRedactionEnabled?{}:{isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled},a=e.restMcpCursorAuthTokenSupplier,c=e=>void 0===a?e:new AO(e,a,"api.cursor.com");return{async createLease(a){const l=a.workspaceState,u=l.projectRoot??l.workingDirectory,d=l.projectDirectory;if(!u||!d)return new tI;const h=new qO((0,s.join)(d,"mcp-disabled.json")),p=function(e){const{teamSettingsService:t,projectRoot:r,projectDirectory:n,ignoreApprovals:i,disabledStore:a,includeProjectMcp:c,includeUserMcp:l,isLinkSharedPaymentTokenLogRedactionEnabled:u}=e;if(c&&l)return UO.init(t,r,n,i,a,{isLinkSharedPaymentTokenLogRedactionEnabled:u});if(!c&&!l)return;const d=new AI((0,s.join)(n,"mcp-auth.json")),h=i?{isServerApproved:()=>Promise.resolve(!0)}:new MC((0,s.join)(n,"mcp-approvals.json"),r),p=[new zC,new $C(h),new CI(t),new AC(a)],f=[];return c&&f.push({prefix:"",loader:new EI((0,s.join)(r,".cursor","mcp.json"),d,p,{isLinkSharedPaymentTokenLogRedactionEnabled:u})}),l&&f.push({prefix:"",loader:new EI((0,s.join)((0,o.homedir)(),".cursor","mcp.json"),d,p,{isLinkSharedPaymentTokenLogRedactionEnabled:u})}),KO(f)}({teamSettingsService:t,projectRoot:u,projectDirectory:d,ignoreApprovals:r,disabledStore:h,includeProjectMcp:e.includeProjectMcp??!0,includeUserMcp:e.includeUserMcp??!0,isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled}),f=[],m=e.inlineMcpServers??{};if(Object.keys(m).length>0){const e=new AI((0,s.join)(d,"mcp-auth.json")),r=[new zC,new CI(t)];f.push({prefix:"",loader:new SI(c(new GO(m)),e,r,i)})}const g=WO(a.services.pluginBootstrapOutputs);if(g&&(e.includePluginMcp??1)){const e=new MC((0,s.join)(d,"mcp-approvals.json"),u),o=new AI((0,s.join)(d,"mcp-auth.json")),a=[new zC];r||a.push(new $C(e)),a.push(new CI(t),new AC(h));const l=new ND(g.pluginsService),p=new SI(c(new zO(l,n)),o,a,i);f.push({prefix:"",loader:p})}if(p&&f.push({prefix:"",loader:p}),0===f.length)return new tI;const w=KO(f),v=await w.load(e.initializationCtx??(0,y.q6)(),e.cache);return new HO(v)}}}function KO(e){return 1===e.length?e[0].loader:new jO(e)}function JO(e,t){if("command"in t){if(void 0!==t.type&&"stdio"!==t.type)throw new Error(`Unsupported MCP server type "${String(t.type)}" for "${e}"`);return{command:t.command,args:t.args?[...t.args]:void 0,env:t.env,cwd:t.cwd,startupTimeoutSec:t.startupTimeoutSec}}if("url"in t){if(void 0!==t.type&&"http"!==t.type&&"sse"!==t.type)throw new Error(`Unsupported MCP server type "${String(t.type)}" for "${e}"`);const r={url:t.url,headers:t.headers,auth:t.auth?{CLIENT_ID:t.auth.CLIENT_ID,CLIENT_SECRET:t.auth.CLIENT_SECRET,scopes:t.auth.scopes?[...t.auth.scopes]:void 0}:void 0};return"sse"===t.type?{...r,type:"sse"}:r}throw new Error(`Invalid inline MCP server config for "${e}"`)}function ZO(e){return"claude-plugin"===e.pluginSource}const XO=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass"];function QO(e){let t=e.trim();t.startsWith("&")&&(t=t.slice(1).trim());const r=t.charAt(0);if("'"!==r&&'"'!==r)return t.split(/\s/)[0]??"";let n="";for(let e=1;e0)return{...n,followup_message:n.reason.trim()};if(!sF(t))return n;const o=aF(e),s=cF(o,r)?o:void 0,i=void 0!==s?{...n,...s}:n;return"block"===i.decision&&"string"==typeof i.reason&&i.reason.trim().length>0?{...i,followup_message:i.reason.trim()}:n}const uF=e=>{const t=[];return Rd(e)?Td(!0):(t.push("Expected an object"),Td(!1,t))},dF=e=>{const t=[],r=uF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny","ask"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("Invalid user_message value. Expected a string if provided"),void 0!==e.agent_message&&"string"!=typeof e.agent_message&&t.push("Invalid agent_message value. Expected a string if provided"),Td(0===t.length,t)};function hF(e){const t=e.modelId,r=e.modelParams;return{...void 0!==t&&{model_id:t},...void 0!==r&&r.length>0?{model_params:r.map((e=>({id:e.id,value:e.value})))}:{}}}const pF=new Set([xd.sessionStart,xd.beforeSubmitPrompt,xd.preToolUse,xd.postToolUse,xd.postToolUseFailure]);function fF(e){return"prompt"===e.type}function mF(e){return"command"===e.type||void 0===e.type}const gF={[xd.beforeShellExecution]:dF,[xd.beforeMCPExecution]:dF,[xd.afterShellExecution]:e=>{const t=uF(e);return t.isValid,t},[xd.afterMCPExecution]:e=>{const t=uF(e);return t.isValid,t},[xd.beforeReadFile]:e=>{const t=[],r=uF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("user_message must be a string if provided"),Td(0===t.length,t)},[xd.afterFileEdit]:e=>{const t=uF(e);return t.isValid,t},[xd.beforeTabFileRead]:e=>{const t=[],r=uF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("user_message must be a string if provided"),Td(0===t.length,t)},[xd.afterTabFileEdit]:e=>uF(e),[xd.beforeSubmitPrompt]:e=>{const t=uF(e);if(!t.isValid)return t;const r=[];return void 0!==e.continue&&"boolean"!=typeof e.continue&&r.push("continue must be a boolean if provided"),void 0!==e.user_message&&"string"!=typeof e.user_message&&r.push("user_message must be a string if provided"),void 0===e.additional_context||Pd(e.additional_context)||r.push("additional_context must be a string if provided"),Td(0===r.length,r)},[xd.stop]:e=>{const t=uF(e);if(!t.isValid)return t;const r=[];return void 0!==e.followup_message&&"string"!=typeof e.followup_message&&r.push("followup_message must be a string if provided"),Td(0===r.length,r)},[xd.afterAgentResponse]:e=>{const t=uF(e);return t.isValid,t},[xd.afterAgentThought]:e=>{const t=uF(e);return t.isValid,t},[xd.sessionStart]:e=>{const t=uF(e);if(!t.isValid)return t;const r=[];if(void 0!==e.env)if(Rd(e.env))for(const[t,n]of Object.entries(e.env))Pd(t)||r.push(`env key "${t}" must be a string`),Pd(n)||r.push(`env value for "${t}" must be a string`);else r.push("env must be an object if provided");return void 0===e.additional_context||Pd(e.additional_context)||r.push("additional_context must be a string if provided"),void 0!==e.continue&&"boolean"!=typeof e.continue&&r.push("continue must be a boolean if provided"),void 0===e.user_message||Pd(e.user_message)||r.push("user_message must be a string if provided"),Td(0===r.length,r)},[xd.sessionEnd]:e=>{const t=uF(e);return t.isValid?Td(!0,[]):t},[xd.preCompact]:e=>{const t=uF(e);if(!t.isValid)return t;if(null==e||0===Object.keys(e).length)return Td(!0,[]);const r=[];if(!Id(e))return r.push("PreCompact response must be an object"),Td(!1,r);const n=e;return void 0===n.user_message||(e=>"string"==typeof e)(n.user_message)||r.push("user_message must be a string"),Td(0===r.length,r)},[xd.subagentStart]:e=>{const t=uF(e);if(!t.isValid)return t;if(!Id(e))return Td(!1,["Expected an object"]);const r=[],n=e;if(void 0!==n.permission){const e=["allow","deny","ask"];"string"==typeof n.permission&&e.includes(n.permission)||r.push(`Invalid permission value. Expected one of: ${e.join(", ")}, or undefined`)}return void 0===n.user_message||Pd(n.user_message)||r.push("user_message must be a string if provided"),Td(0===r.length,r)},[xd.subagentStop]:e=>{const t=uF(e);if(!t.isValid)return t;const r=[];return Id(e)&&void 0!==e.followup_message&&"string"!=typeof e.followup_message&&r.push("followup_message must be a string if provided"),Td(0===r.length,r)},[xd.preToolUse]:e=>{const t=[],r=uF(e);if(!r.isValid)return r;if(void 0!==e.permission){const r=["allow","deny","ask"];r.includes(e.permission)||t.push(`Invalid permission value. Expected one of: ${r.join(", ")}, or undefined`)}return void 0!==e.user_message&&"string"!=typeof e.user_message&&t.push("Invalid user_message value. Expected a string if provided"),void 0!==e.agent_message&&"string"!=typeof e.agent_message&&t.push("Invalid agent_message value. Expected a string if provided"),void 0!==e.updated_input&&("object"!=typeof e.updated_input||null===e.updated_input||Array.isArray(e.updated_input))&&t.push("Invalid updated_input value. Expected a plain object if provided"),Ad(e.additional_context,"additional_context",t),Td(0===t.length,t)},[xd.postToolUse]:e=>{const t=[],r=uF(e);return r.isValid?(Ad(e.additional_context,"additional_context",t),Td(0===t.length,t)):r},[xd.postToolUseFailure]:e=>{const t=uF(e);if(!t.isValid)return t;const r=[];return Ad(e.additional_context,"additional_context",r),Td(0===r.length,r)},[xd.workspaceOpen]:e=>{const t=uF(e);if(!t.isValid)return t;const r=[];return void 0!==e.pluginPaths&&(Array.isArray(e.pluginPaths)?e.pluginPaths.forEach(((e,t)=>{"string"==typeof e?0===e.trim().length&&r.push(`pluginPaths[${t}] must be a non-empty string`):r.push(`pluginPaths[${t}] must be a string`)})):r.push("pluginPaths must be an array of strings if provided")),Td(0===r.length,r)}},wF=(e,t,r)=>{const n=function(e,t,r){let n;return n=e===xd.preToolUse?function(e,t){if(!iF(e))return e;const r=e;if(void 0!==r.permission||void 0!==r.user_message||void 0!==r.agent_message||void 0!==r.updated_input)return r;if(!sF(t))return r;const n=aF(e);if(!cF(n,"PreToolUse"))return r;const o={...r};let s=!1;return void 0!==n.permissionDecision&&(o.permission=n.permissionDecision,s=!0),"string"==typeof n.permissionDecisionReason&&(o.user_message=n.permissionDecisionReason,s=!0),iF(n.updatedInput)&&(o.updated_input=n.updatedInput,s=!0),s?o:r}(t,r):e===xd.stop?lF(t,r,"Stop"):e===xd.subagentStop?lF(t,r,"SubagentStop"):t,function(e,t,r,n){if(!pF.has(e)||!iF(r)||void 0!==r.additional_context)return r;const o=iF(t)?function(e){return"string"==typeof e.additionalContext?e.additionalContext:void 0}(t)??function(e,t,r){if(!sF(r))return;const n=Fd[e];if(void 0===n)return;const o=aF(t);return cF(o,n)&&"string"==typeof o.additionalContext?o.additionalContext:void 0}(e,t,n):void 0;return void 0===o?r:{...r,additional_context:o}}(e,t,n,r)}(e,t,r),o=(0,gF[e])(n);return o.isValid?{success:!0,data:n}:{success:!1,errors:o.errors}},yF=[xd.beforeShellExecution,xd.beforeMCPExecution,xd.beforeReadFile,xd.beforeTabFileRead,xd.subagentStart,xd.preToolUse],vF=[xd.workspaceOpen];function bF(e,t){const r=[];return"string"==typeof e&&e.trim()&&r.push(e.trim()),"string"==typeof t&&t.trim()&&r.push(t.trim()),r.length>0?r.join("\n\n---\n\n"):void 0}function SF(e,t){return{..."object"==typeof e&&null!==e?e:{},...t}}function kF(e){return yF.includes(e)}function _F({step:e,command:t,failClosed:r,kind:n}){const o=kF(e);if(!r&&!o)return{shouldNotifyUser:!1};const s=r?"Tool blocked because this hook is configured to fail closed (block when it fails). "+("invalid_json"===n?`Hook "${t}" returned invalid JSON.`:`Hook "${t}" returned invalid response.`):"invalid_json"===n?`Hook "${t}" returned invalid JSON. The command was blocked for safety.`:`Hook "${t}" returned an invalid response for this hook step. The command was blocked for safety.`;return{blockResponse:EF(e,s),cause:r?"script_fail_closed":"permission_hook_invalid_output",reason:s,shouldNotifyUser:o&&!r}}function CF(e,t){return t}function EF(e,t){return kF(e)?CF(0,{permission:"deny",user_message:t}):e===xd.beforeSubmitPrompt||e===xd.sessionStart?CF(0,{continue:!1,user_message:t}):e===xd.stop?CF(0,{}):void 0}function xF(e){try{return{value:JSON.parse(e)}}catch{return}}function PF(e){if("object"!=typeof e||null===e)return!1;const t=e.event;return"backgrounded"===t?.case}function RF(e){if("object"!=typeof e||null===e)return;const t=e.path;return"string"==typeof t&&t.length>0?t:void 0}class IF{cacheCarriersForExecId(e,t){const r=this.carriersByExecId.get(e);if(!(void 0!==r&&r.length>0&&0===t.length))for(this.carriersByExecId.has(e)&&this.carriersByExecId.delete(e),this.carriersByExecId.set(e,t);this.carriersByExecId.size>IF.CARRIERS_BY_EXEC_ID_MAX;){const e=this.carriersByExecId.keys().next().value;if(void 0===e)break;this.carriersByExecId.delete(e)}}constructor(e,t,r,n){this.inner=e,this.wake=r,this.carriersByExecId=new Map,this.inFlightByExecId=new Map,this.resolveDrain="function"==typeof t?t:e=>t,this.skipPathWriteDrain=n?.skipPathWriteDrain,this.onWakeWrittenPath=n?.onWakeWrittenPath,this.forceWrittenPathBeforeDrain=n?.forceWrittenPathBeforeDrain,this.writeBarrierTimeoutMs=n?.writeBarrierTimeoutMs??2e3,this.resolveWriteBarrierTimeoutMs=n?.resolveWriteBarrierTimeoutMs,this.onWriteBarrier=n?.onWriteBarrier}resolveTimeoutMs(){if(void 0!==this.resolveWriteBarrierTimeoutMs)try{const e=this.resolveWriteBarrierTimeoutMs();if("number"==typeof e&&Number.isFinite(e))return e}catch{}return this.writeBarrierTimeoutMs}get(e){return this.wrapImpl(e.symbol,this.inner.get(e))}*entries(){for(const[e,t]of this.inner.entries())yield[e,this.wrapImpl(e.symbol,t)]}wrapImpl(e,t){if(!function(e){return"object"==typeof e&&null!==e&&"execute"in e&&"function"==typeof e.execute}(t))return t;const r=function(e){return e===HT.symbol||e===qT.symbol?{kind:"path"}:e===jT.symbol||e===ee.symbol||e===vA.symbol?{kind:"exposed"}:void 0}(e),n=this.resolveDrain,o=this.wake,s=this.skipPathWriteDrain,i=this.forceWrittenPathBeforeDrain,a=()=>this.resolveTimeoutMs(),c=this.onWriteBarrier,l=this.onWakeWrittenPath,u=(e,t)=>{if(void 0!==r&&void 0!==o)try{if("path"===r.kind){const r=RF(e);void 0!==r&&(o.wakeForWrittenPath(r),l?.(r,t))}else o.wakeExposedMounts()}catch{}},d=this.cacheCarriersForExecId.bind(this),h=this.carriersByExecId,p=this.inFlightByExecId,f=async(e,t)=>{const r=t?.hookContextCollector;if(void 0===r)return[];if(!1===t?.deliverAgentStoreConflictNotices)return[];const o=void 0!==t?.execId&&t.execId.length>0?t.execId:void 0;if(void 0!==o){const e=h.get(o);if(void 0!==e)return e.length>0&&r.push(...e),e;const t=p.get(o);if(void 0!==t){const e=await t;return e.length>0&&r.push(...e),e}}const s=async t=>{const r=n(e);let s=[];try{const e=await r.peek();if(s=e.eventIds,e.carriers.length>0)return t.push(...e.carriers),r.ack(e.eventIds),void 0!==o&&d(o,e.carriers),e.carriers;s.length>0&&r.ack(s);const n=[];return void 0!==o&&d(o,n),n}catch{return s.length>0&&r.release(s),[]}};if(void 0===o)return await s(r);const i=s(r);p.set(o,i);try{return await i}finally{p.get(o)===i&&p.delete(o)}};return new Proxy(t,{get:(t,n,o)=>"execute"!==n?Reflect.get(t,n,o):(n,o,l)=>{const d=t.execute.call(t,n,o,l);return"object"==typeof(h=d)&&null!==h&&Symbol.asyncIterator in h&&"function"==typeof h[Symbol.asyncIterator]?async function*(){let t=!1,r=!1,s=!1;try{for await(const r of d)if(e===ee.symbol&&PF(r)){if(!t){u(o,n);const e=await f(n,l);t=!0,e.length>0&&(yield new he.FI({event:{case:"hookContext",value:new he.Ng({hookAdditionalContexts:[...e]})}}))}yield r}else yield r;s=!0}catch(e){throw r=!0,e}finally{u(o,n),t||r||!s||await f(n,l)}}():function(e){return"object"==typeof e&&null!==e&&"then"in e&&"function"==typeof e.then}(d)?(async()=>{try{const t=await d;return u(o,n),e===HT.symbol&&!0===s?.()&&!0===l?.enableAgentStoreConflictNotices||(await async function(e,t,r,n){const o=e=>{try{n.onWriteBarrier?.(e)}catch{}};if(void 0===e||"path"!==r?.kind)return;const s=RF(t);if(void 0===s)return;if(!(n.timeoutMs>0))return void o({durationMs:0,outcome:"skipped"});const i=Date.now(),a=e(s).then((e=>e),(()=>"error")),c=await Promise.race([a,(0,Or.cb)(n.timeoutMs).then((()=>"timeout"))]);"not_store_path"!==c&&o({durationMs:Date.now()-i,outcome:c})}(i,o,r,{timeoutMs:a(),onWriteBarrier:c}),await f(n,l)),t}catch(e){throw u(o,n),e}})():(u(o,n),d);var h}})}}function TF(e){return new RegExp(`<${e}(?:\\s[^>]*)?>[\\s\\S]*?`,"gi")}IF.CARRIERS_BY_EXEC_ID_MAX=32,Error,ou.execFileSync,new Map,xo.constants.O_NOFOLLOW,new Set(["write_conflict","create_conflict","truncate_conflict_failed","conflict_fallback_failed","quota_exceeded","gap"]),new Set(["write_conflict","create_conflict","truncate_conflict_failed","conflict_fallback_failed","quota_exceeded"]),Math.max(1,Math.floor(8192));const AF=["user_info","project_layout","rules","always_applied_workspace_rules","agent_requestable_workspace_rules","user_rules","agent_skills","available_skills","cloud_instructions","cloud_task_instructions","open_and_recently_viewed_files","system_reminder","system-reminder","instructions_update","mcp_instructions","mcp_file_system","mcp_file_system_servers","git_status","agent_transcripts","cursor_rules_context","attached_files","system_notification","task_notification","agent_notification"].map(TF);function $F(e){return function(e,t){let r=e;if(r.includes("<"))for(const e of t)r=r.replace(e,"");return(r.includes("\n\n\n")?r.replace(MF,"\n\n"):r).trim()}(e,AF)}["system_reminder","system-reminder"].map(TF);const MF=/\n{3,}/g;function DF(e){const t=(0,So.sh)(e.conversationId);if("subagent"===e.kind&&e.parentConversationId){const r=(0,So.sh)(e.parentConversationId);return`${So.O2}/${r}/subagents/${t}.${e.ext}`}return`${So.O2}/${t}/${t}.${e.ext}`}function OF(e){const t=(0,So.sh)(e.conversationId);return`${So.O2}/${t}.${e.ext}`}function FF(e){const t=e.exts??["jsonl","txt"],r=e.includeLegacy??!0,n=[],o=e=>{n.includes(e)||n.push(e)};for(const n of t)o(DF({conversationId:e.conversationId,ext:n,kind:e.kind,parentConversationId:e.parentConversationId})),"subagent"===e.kind&&e.parentConversationId&&o(DF({conversationId:e.conversationId,ext:n,kind:"primary"})),r&&o(OF({conversationId:e.conversationId,ext:n}));return n}var NF;!function(e){e.INTERNAL="INTERNAL",e.EXTERNAL="EXTERNAL",e.NO_PREAMBLE="NO_PREAMBLE"}(NF||(NF={}));var LF=function(e,t,r){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var n,o;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(void 0===n){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose],r&&(o=n)}if("function"!=typeof n)throw new TypeError("Object not disposable.");o&&(n=function(){try{o.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:n,async:r})}else r&&e.stack.push({async:!0});return t},jF=function(e){return function(t){function r(r){t.error=t.hasError?new e(r,t.error,"An error was suppressed during disposal."):r,t.hasError=!0}var n,o=0;return function e(){for(;n=t.stack.pop();)try{if(!n.async&&1===o)return o=0,t.stack.push(n),Promise.resolve().then(e);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return o|=2,Promise.resolve(s).then(e,(function(t){return r(t),e()}))}else o|=1}catch(e){r(e)}if(1===o)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,r){var n=new Error(r);return n.name="SuppressedError",n.error=e,n.suppressed=t,n});function UF(e){switch(e){case i.xyI.AGENT:return"agent";case i.xyI.ASK:return"ask";case i.xyI.PLAN:return"plan";case i.xyI.DEBUG:return"debug";case i.xyI.TRIAGE:return"triage";case i.xyI.MULTITASK:return"multitask";case i.xyI.CUSTOM:return"custom";case i.xyI.UNSPECIFIED:default:return"agent"}}function BF(e,t){return t instanceof Uint8Array?{__type:"Uint8Array",hex:(r=t,Array.from(r).map((e=>e.toString(16).padStart(2,"0"))).join(""))}:"bigint"==typeof t?t.toString():t;var r}function WF(e,t){return function(e){return"object"==typeof e&&null!==e&&"__type"in e&&"Uint8Array"===e.__type&&"hex"in e&&"string"==typeof e.hex}(t)?`[Binary data omitted from transcript: ${t.hex.length/2} bytes]`:t}const HF=new TextEncoder,qF=new TextDecoder,zF=new class{serialize(e){const t=JSON.stringify(e,BF);return HF.encode(t)}deserialize(e){const t=qF.decode(e);return t.includes('"__type":"Uint8Array"')?JSON.parse(t,WF):JSON.parse(t)}};function GF(e){const t=e.providerOptions;return!0===t?.cursor?.isSummary}function VF(e){return"system"!==e.role&&!GF(e)}function KF(e,t){return"user"===e.role&&"user"===t.role}async function JF(e,t,r){const n=await t.getBlob(e,r);return n?i.Anz.fromBinary(n).summarizedMessages:[]}async function ZF(e,t,r,n){const o=await t.getBlob(e,r);if(o){if(o.length>5e6)return n.omittedOversizeBlobCount++,n.omittedOversizeBlobBytes+=o.length,n.largestOmittedOversizeBlobBytes=Math.max(n.largestOmittedOversizeBlobBytes,o.length),{role:"assistant",content:`[Oversize transcript blob omitted: ${s=o.length,`${(s/1e6).toFixed(1)} MB`}]`};var s;try{const e=performance.now(),t=zF.deserialize(o);return n.totalDeserializeDurationMs+=performance.now()-e,n.hydratedBlobCount++,n.hydratedBlobBytes+=o.length,n.largestHydratedBlobBytes=Math.max(n.largestHydratedBlobBytes,o.length),t}catch{return}}}async function XF(e,t,r){const n={messages:[],hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0};for(const o of r){const r=await ZF(e,t,o,n);r&&n.messages.push(r)}return n}async function QF(e,t,r,n,o){const s=[];let i=0;const a=()=>{const o=ZF(e,t,r[i++],n);o.catch((()=>{})),s.push(o)};for(;i{let r;return r="string"==typeof t?t:"object"==typeof t&&null!==t?JSON.stringify(t):String(t),` ${e}: ${r}`})).join("\n")}`}(e.args)}`;case"tool-result":return`[Tool result] ${e.toolName}`;default:return""}}function eN(e){return $F(e)}const tN=/[\s\S]*?<\/think>/gi,rN=/[\s\S]*?<\/thinking>/gi,nN=/\n{3,}/g;function oN(e){let t=e;return t.includes("<")&&(t=t.replace(tN,"").replace(rN,"")),(t.includes("\n\n\n")?t.replace(nN,"\n\n"):t).trim()}function sN(e,t,r){if(void 0===e)return"";if("string"==typeof e){const n=t?eN(e):e;return r?oN(n):n}return e.map((e=>{if(r&&"text"===e.type){const r=oN(t?eN(e.text):e.text);return YF({...e,text:r},!1)}return YF(e,t)})).filter(Boolean).join("\n")}function iN(e,t){const r={role:e.role},n=e.content;if("string"==typeof n){const o=t?eN(n):n,s="assistant"===e.role?oN(o):o;s.trim()&&(r.text=s)}else if(Array.isArray(n)){const o=[],s=[],i=[];let a;for(const r of n)switch(r.type){case"text":{const n=t?eN(r.text):r.text,s="assistant"===e.role?oN(n):n;s.trim()&&o.push(s);break}case"reasoning":r.text.trim()&&s.push(r.text);break;case"redacted-reasoning":s.push("[REDACTED]");break;case"image":o.push("[Image]");break;case"file":o.push(r.filename?`[File: ${r.filename}]`:"[File]");break;case"tool-call":i.push({toolName:r.toolName,args:r.args});break;case"tool-result":a={toolName:r.toolName}}o.length>0&&(r.text=o.join("\n")),s.length>0&&(r.thinking=s.join("\n")),i.length>0&&(r.toolCalls=i),a&&(r.toolResult=a)}return r}function aN(e){return e.endsWith("\n")?e:`${e}\n`}function cN(e){const{turnEnded:t}=e,r=[],n={},o=[];return void 0!==t&&(r.push(function(e){switch(e.status){case"success":return"Turn ended: success.";case"error":return`Turn ended: error: ${e.error}`;case"aborted":return e.error?`Turn ended: aborted: ${e.error}`:"Turn ended: aborted.";default:return e}}(t)),n.turnEnded=t,o.push(JSON.stringify({type:"turn_ended",...t}))),{textSuffixes:r,jsonFields:n,jsonlLines:o}}function lN(e){if("system"===e.role||GF(e))return;const t=iN(e,"user"===e.role),r=[],n=[];if(t.text&&n.push(t.text),t.thinking&&n.push(t.thinking),n.length>0&&r.push({type:"text",text:n.join("\n\n")}),t.toolCalls)for(const e of t.toolCalls)r.push({type:"tool_use",name:e.toolName,input:e.args});if(0===r.length)return;const o={role:e.role,message:{content:r}};return JSON.stringify(o)}class uN{constructor(e,t,r,n={}){this.projectDir=e,this.blobStore=t,this.writeFile=r,this.options={writeText:n.writeText??!0,writeJson:n.writeJson??!1,writeJsonl:n.writeJsonl??!1,pathResolver:n.pathResolver,appendFile:n.appendFile,streamFullJsonlWrites:n.streamFullJsonlWrites??!1,fallbackToFullWriteOnIncrementalFailure:n.fallbackToFullWriteOnIncrementalFailure??!0}}resolveFilePath(e,t){if(this.options.pathResolver)return this.options.pathResolver(e,t);const r=DF({conversationId:e,ext:t,kind:"primary"});return`${this.projectDir}/${r}`}async writeFromStateFull(e,t,r,n={}){const o={stack:[],error:void 0,hasError:!1};try{const s=LF(o,(0,$.VI)(e.withName("writeFromState")),!1);try{const{overviewFactory:e}=n,o=cN(n),{appendFile:i,streamFullJsonlWrites:a,writeJsonl:c,writeText:l,writeJson:u}=this.options;if(i&&a&&c&&!l&&!u&&!e)try{return await this.writeJsonlStreamed(s,{state:t,filePath:this.resolveFilePath(r,"jsonl"),appendFile:i,terminalLines:o.jsonlLines}),!0}catch(e){console.error("[TranscriptStore] Streamed transcript write failed, retrying as a single write:",e)}const d=await async function(e,t,r){const n={stack:[],error:void 0,hasError:!1};try{const o=LF(n,(0,$.VI)(e.withName("hydrateSummaryArchives")),!1);let s=0;const i=(0,$.OA)(o.ctx),a=[];let c=0,l=0,u=0,d=0,h=0,p=0,f=0;const m=await Promise.all(r.summaryArchives.map((async e=>{s++;try{const r=await JF(i,t,e);return s+=r.length,await XF(i,t,r)}catch{return{messages:[],hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0}}})));for(const e of m)a.push(...e.messages),c+=e.hydratedBlobCount,l+=e.hydratedBlobBytes,u=Math.max(u,e.largestHydratedBlobBytes),d+=e.totalDeserializeDurationMs,h+=e.omittedOversizeBlobCount,p+=e.omittedOversizeBlobBytes,f=Math.max(f,e.largestOmittedOversizeBlobBytes);o.span.setAttribute("getBlobCount",s),o.span.setAttribute("hydratedBlobCount",c),o.span.setAttribute("hydratedBlobBytes",l),o.span.setAttribute("largestHydratedBlobBytes",u),o.span.setAttribute("totalDeserializeDurationMs",d),o.span.setAttribute("omittedOversizeBlobCount",h),o.span.setAttribute("omittedOversizeBlobBytes",p),o.span.setAttribute("largestOmittedOversizeBlobBytes",f);const g=LF(n,(0,$.VI)(e.withName("hydratePromptMessages")),!1),w=await XF(i,t,r.rootPromptMessagesJson);g.span.setAttribute("getBlobCount",r.rootPromptMessagesJson.length),g.span.setAttribute("hydratedBlobCount",w.hydratedBlobCount),g.span.setAttribute("hydratedBlobBytes",w.hydratedBlobBytes),g.span.setAttribute("largestHydratedBlobBytes",w.largestHydratedBlobBytes),g.span.setAttribute("totalDeserializeDurationMs",w.totalDeserializeDurationMs),g.span.setAttribute("omittedOversizeBlobCount",w.omittedOversizeBlobCount),g.span.setAttribute("omittedOversizeBlobBytes",w.omittedOversizeBlobBytes),g.span.setAttribute("largestOmittedOversizeBlobBytes",w.largestOmittedOversizeBlobBytes);const y=w.messages.filter(VF);return a.push(...y),a}catch(e){n.error=e,n.hasError=!0}finally{jF(n)}}(s.ctx,this.blobStore,t);if(0===d.length&&0===o.jsonlLines.length)return!0;let h;if((this.options.writeText||e)&&(h=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&"user"===t[0].role&&"user"===t[1].role&&(t=t.slice(1));const r=[];for(const e of t){const t="user"===e.role,n="assistant"===e.role,o=sN(e.content,t,n);o.trim()&&("tool"===e.role?r.push(o):r.push(`${e.role}:\n${o}`))}return r.join("\n\n")}(d)),this.options.writeText){const e=h??"",t=o.textSuffixes.length>0?e.trim().length>0?`${e}\n\n${o.textSuffixes.join("\n")}`:o.textSuffixes.join("\n"):e;t.trim()&&await this.writeFile(this.resolveFilePath(r,"txt"),t)}if(this.options.writeJson){const e=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&"user"===t[0].role&&"user"===t[1].role&&(t=t.slice(1));const r=[];for(const e of t){const t=iN(e,"user"===e.role);(t.text||t.thinking||t.toolCalls||t.toolResult)&&r.push(t)}return 0===r.length?"":JSON.stringify(r,null,2)}(d);if(e||o.jsonlLines.length>0){const n={mode:UF(t.mode),messages:e?JSON.parse(e):[],...o.jsonFields};await this.writeFile(this.resolveFilePath(r,"json"),JSON.stringify(n,null,2))}}if(this.options.writeJsonl){const t=function(e){let t=e.filter((e=>"system"!==e.role));t.length>=2&&KF(t[0],t[1])&&(t=t.slice(1));const r=[];for(const e of t){const t=lN(e);t&&r.push(t)}return r.join("\n")}(d);let n=[t,...o.jsonlLines].filter((e=>e.length>0)).join("\n");if(n&&e&&h?.trim())try{const t=(await e(h)).trim();t&&(n=function(e,t){const r={type:"metadata",metadata:{overview:t}};return`${JSON.stringify(r)}\n${e}`}(n,t))}catch(e){console.error("[TranscriptStore] Failed to generate transcript overview:",e)}n&&await this.writeFile(this.resolveFilePath(r,"jsonl"),aN(n))}return!0}catch(e){return console.error("[TranscriptStore] Failed to write transcript:",e),!1}}catch(e){o.error=e,o.hasError=!0}finally{jF(o)}}async writeJsonlStreamed(e,t){const{filePath:r,appendFile:n}=t;let o=[],s=0,i=0,a=0;const c=async()=>{if(0===o.length)return;const e=`${o.join("\n")}\n`;o=[],s=0,0===i?await this.writeFile(r,e):await n(r,e),i++,a+=e.length},l=async e=>{e&&(o.push(e),s+=e.length+1,s>=1e6&&await c())};let u,d=0;const h=await async function(e,t,r,n){const o={hydratedBlobCount:0,hydratedBlobBytes:0,largestHydratedBlobBytes:0,totalDeserializeDurationMs:0,omittedOversizeBlobCount:0,omittedOversizeBlobBytes:0,largestOmittedOversizeBlobBytes:0};for(const s of r.summaryArchives){let r;try{r=await JF(e,t,s)}catch{continue}await QF(e,t,r,o,{skipFailedReads:!0,visit:n})}return await QF(e,t,r.rootPromptMessagesJson,o,{skipFailedReads:!1,visit:async e=>{VF(e)&&await n(e)}}),o}((0,$.OA)(e.ctx),this.blobStore,t.state,(async e=>{"system"!==e.role&&(d++,1!==d?(2===d&&u&&(KF(u,e)||await l(lN(u)),u=void 0),await l(lN(e))):u=e)}));u&&await l(lN(u));for(const e of t.terminalLines)await l(e);await c(),e.span.setAttribute("streamed",!0),e.span.setAttribute("chunkCount",i),e.span.setAttribute("writtenChars",a),e.span.setAttribute("hydratedBlobCount",h.hydratedBlobCount),e.span.setAttribute("hydratedBlobBytes",h.hydratedBlobBytes),e.span.setAttribute("largestHydratedBlobBytes",h.largestHydratedBlobBytes),e.span.setAttribute("totalDeserializeDurationMs",h.totalDeserializeDurationMs),e.span.setAttribute("omittedOversizeBlobCount",h.omittedOversizeBlobCount),e.span.setAttribute("omittedOversizeBlobBytes",h.omittedOversizeBlobBytes),e.span.setAttribute("largestOmittedOversizeBlobBytes",h.largestOmittedOversizeBlobBytes)}async writeFromStateIncremental(e,t,r,n,o={}){const s={stack:[],error:void 0,hasError:!1};try{const i=t.rootPromptMessagesJson.length,a=cN(o),c=a.jsonlLines.length>0;if(i===n&&!c&&!o.overviewFactory)return i;const l=this.options.appendFile;if(!(l&&this.options.writeJsonl&&!this.options.writeText&&!this.options.writeJson&&n>0&&i>=n&&(i>n||c))||o.overviewFactory)return await this.writeFromStateFull(e,t,r,o)?i:0;const u=LF(s,(0,$.VI)(e.withName("writeFromStateIncremental")),!1);if(i===n&&c)try{return await l(this.resolveFilePath(r,"jsonl"),aN(a.jsonlLines.join("\n"))),i}catch(n){return console.error(this.options.fallbackToFullWriteOnIncrementalFailure?"[TranscriptStore] Failed to append transcript, falling back to full write:":"[TranscriptStore] Failed to append transcript:",n),this.options.fallbackToFullWriteOnIncrementalFailure?await this.writeFromStateFull(e,t,r,o)?i:0:0}try{const e=t.rootPromptMessagesJson.slice(n),o=await XF(u.ctx,this.blobStore,e);u.span.setAttribute("hydratedBlobCount",o.hydratedBlobCount),u.span.setAttribute("hydratedBlobBytes",o.hydratedBlobBytes),u.span.setAttribute("largestHydratedBlobBytes",o.largestHydratedBlobBytes),u.span.setAttribute("totalDeserializeDurationMs",o.totalDeserializeDurationMs),u.span.setAttribute("omittedOversizeBlobCount",o.omittedOversizeBlobCount),u.span.setAttribute("omittedOversizeBlobBytes",o.omittedOversizeBlobBytes),u.span.setAttribute("largestOmittedOversizeBlobBytes",o.largestOmittedOversizeBlobBytes);const s=[];for(const e of o.messages){const t=lN(e);t&&s.push(t)}if(s.push(...a.jsonlLines),s.length>0){const e=aN(s.join("\n"));await l(this.resolveFilePath(r,"jsonl"),e)}return i}catch(n){return console.error(this.options.fallbackToFullWriteOnIncrementalFailure?"[TranscriptStore] Failed to append transcript, falling back to full write:":"[TranscriptStore] Failed to append transcript:",n),this.options.fallbackToFullWriteOnIncrementalFailure?await this.writeFromStateFull(e,t,r,o)?i:0:0}}catch(e){s.error=e,s.hasError=!0}finally{jF(s)}}}function dN(e,t){const r=function(e){return"object"==typeof e&&null!==e}(e)&&t in e?e[t]:void 0;return"string"==typeof r&&""!==r?r:void 0}function hN(e,t){return e.filter((e=>function(e,t){if(!e.matcher||""===e.matcher||"*"===e.matcher)return!0;if(void 0===t)return!0;try{return new RegExp(e.matcher).test(t)}catch{return!0}}(e,t)))}function pN(e){return`Tool blocked because this hook is configured to fail closed (block when it fails). ${e}`}function fN(e){return Object.values(xd).some((t=>t===e))}function mN(e){switch(e??(0,o.platform)()){case"darwin":return s.default.join("/Library","Application Support","Cursor","hooks.json");case"win32":return s.default.join("C:\\","ProgramData","Cursor","hooks.json");default:return s.default.join("/etc","cursor","hooks.json")}}function gN(e){return fF(e)?`prompt:${e.prompt}`:`command:${e.command}`}function wN(e){return(e.repoHooks??[]).flatMap((e=>[e.projectHooks,e.claudeProjectHooks,e.claudeProjectLocalHooks]))}class yN{constructor(e,t,r){this.fileReader=e,this.paths=t,this.logger=r||{warn:e=>console.warn(`[hooks] ${e}`),info:e=>{}}}async load(e={}){const{loadProjectHooks:t=!0}=e,r={errors:[],configDirs:{}},n=this.paths.projectConfigPath??this.paths.claudeProjectConfigPath??this.paths.claudeProjectLocalConfigPath,o=n?s.default.dirname(s.default.dirname(n)):void 0,i=(e,t)=>{if(!e||!o)return;if(t)return o;const r=s.default.relative(s.default.resolve(o),s.default.resolve(e));return".."===r||r.startsWith(`..${s.default.sep}`)||s.default.isAbsolute(r)?void 0:o},a=async(e,t,n,o,i,a,c,l)=>{if(e)try{if(!await this.fileReader.exists(e))return;if(c&&this.fileReader.pathContainsSymlink&&await this.fileReader.pathContainsSymlink(e,c))return r.errors.push({source:t,message:`${i} at ${e}: refusing to load config path that contains a symlink`}),void this.logger.warn(`Refusing to load ${a} config via symlink path: ${e}`);const u=await this.fileReader.readFile(e);if(!u)return;const{config:d,error:h}=l(u);if(d){switch(n){case"enterpriseHooks":r.enterpriseHooks=d;break;case"teamHooks":r.teamHooks=d;break;case"userHooks":r.userHooks=d;break;case"projectHooks":r.projectHooks=d;break;case"claudeUserHooks":r.claudeUserHooks=d;break;case"claudeProjectHooks":r.claudeProjectHooks=d;break;case"claudeProjectLocalHooks":r.claudeProjectLocalHooks=d;break;default:return}((e,t)=>{r.configDirs[e]=s.default.dirname(t)})(o,e)}else h&&r.errors.push({source:t,message:`${i} at ${e}: ${h}`})}catch(e){r.errors.push({source:t,message:`Error accessing ${a} config file: ${String(e)}`})}},c=[{path:this.paths.enterpriseConfigPath,source:"enterprise",resultKey:"enterpriseHooks",configDirKey:"enterprise",parsePrefix:"Enterprise hooks.json",accessLabel:"enterprise",symlinkCheckRoot:i(this.paths.enterpriseConfigPath,!1)},{path:this.paths.teamConfigPath,source:"team",resultKey:"teamHooks",configDirKey:"team",parsePrefix:"Team hooks.json",accessLabel:"team",symlinkCheckRoot:i(this.paths.teamConfigPath,!1)},{path:this.paths.userConfigPath,source:"user",resultKey:"userHooks",configDirKey:"user",parsePrefix:"User hooks.json",accessLabel:"user",symlinkCheckRoot:i(this.paths.userConfigPath,!1)},{path:t?this.paths.projectConfigPath:void 0,source:"project",resultKey:"projectHooks",configDirKey:"project",parsePrefix:"Project hooks.json",accessLabel:"project",symlinkCheckRoot:i(this.paths.projectConfigPath,!0)}];for(const e of c)await a(e.path,e.source,e.resultKey,e.configDirKey,e.parsePrefix,e.accessLabel,e.symlinkCheckRoot,(t=>this.parseAndValidate(t,e.source)));const l=[{path:this.paths.claudeUserConfigPath,source:"claude-user",resultKey:"claudeUserHooks",configDirKey:"claudeUser",label:"user",symlinkCheckRoot:i(this.paths.claudeUserConfigPath,!1)},{path:t?this.paths.claudeProjectConfigPath:void 0,source:"claude-project",resultKey:"claudeProjectHooks",configDirKey:"claudeProject",label:"project",symlinkCheckRoot:i(this.paths.claudeProjectConfigPath,!0)},{path:t?this.paths.claudeProjectLocalConfigPath:void 0,source:"claude-project-local",resultKey:"claudeProjectLocalHooks",configDirKey:"claudeProjectLocal",label:"project local",symlinkCheckRoot:i(this.paths.claudeProjectLocalConfigPath,!0)}];for(const e of l)await a(e.path,e.source,e.resultKey,e.configDirKey,`Claude ${e.label} settings.json`,`Claude ${e.label}`,e.symlinkCheckRoot,(t=>this.parseClaudeConfig(t,e.source)));return function(e){const{cursorConfigs:t,claudeConfigs:r,logger:n}=e,o=new Map;for(const e of t)if(e?.hooks)for(const[t,r]of Object.entries(e.hooks)){if(!r)continue;let e=o.get(t);e||(e=new Set,o.set(t,e));for(const t of r)e.add(gN(t))}for(const{config:e,source:t}of r)if(e?.hooks)for(const[r,s]of Object.entries(e.hooks)){if(!s)continue;const i=o.get(r);if(!i||0===i.size)continue;const a=s.filter((e=>{const o=gN(e);return!i.has(o)||(n?.info(`Removed duplicate ${t} hook for ${r}: ${o}`),!1)}));a.length!==s.length&&(e.hooks[r]=a)}}({cursorConfigs:[r.enterpriseHooks,r.teamHooks,r.userHooks,r.projectHooks],claudeConfigs:[{config:r.claudeUserHooks,source:"claude-user"},{config:r.claudeProjectHooks,source:"claude-project"},{config:r.claudeProjectLocalHooks,source:"claude-project-local"}],logger:this.logger}),r}parseClaudeConfig(e,t){try{const t=JSON.parse(e);if(!function(e,t={}){if(!Id(e))return!1;if(!("hooks"in e))return!1;const r=e.hooks;if(!Id(r))return!1;const n=r;for(const[e,r]of Object.entries(n))if(e in Od&&Array.isArray(r)){const n=!0===t.allowMatcherlessStop&&"Stop"===e;for(const e of r)if(Id(e)&&"hooks"in e&&Array.isArray(e.hooks)&&("matcher"in e||n))return!0}return!1}(t))return{};const r=t.hooks;if(!r||0===Object.keys(r).length)return{};const n=Xd(r,this.logger),o=Dd(n);return o.isValid?{config:n}:{error:`Invalid transformed config: ${o.errors.join("; ")}`}}catch(e){return{error:`Failed to parse JSON: ${String(e)}`}}}parseAndValidate(e,t){try{const n=this.parseJSONC(e),o=Dd(n);return o.isValid?"object"==typeof(r=n)&&null!==r&&"version"in r&&"number"==typeof r.version&&"hooks"in r&&"object"==typeof r.hooks&&null!==r.hooks&&!Array.isArray(r.hooks)?{config:n}:{error:`Invalid ${t} config: missing 'hooks' property`}:{error:`Invalid ${t} config: ${o.errors.join("; ")}`}}catch(e){return{error:`Failed to parse ${t} config JSON: ${String(e)}`}}var r}parseJSONC(e){let t=e.replace(/\/\/.*$/gm,"");return t=t.replace(/\/\*[\s\S]*?\*\//g,""),JSON.parse(t)}static getConfiguredSteps(e){const t=new Set,r=[e.enterpriseHooks,e.teamHooks,e.userHooks,e.projectHooks,e.claudeUserHooks,e.claudeProjectHooks,e.claudeProjectLocalHooks,...wN(e)];for(const e of r)if(e?.hooks)for(const r of Object.keys(e.hooks))fN(r)&&t.add(r);for(const r of e.pluginHooks??[])for(const e of Object.keys(r.config.hooks))fN(e)&&t.add(e);return t}}const vN="Read",bN="Write",SN="Delete",kN="List",_N="Grep",CN="Shell",EN="ReadLints";function xN(e,t){if("object"==typeof e&&null!==e)return Object.getOwnPropertyDescriptor(e,t)?.value}const PN=new Set([vN,bN,SN,kN,_N,EN]);function RN(e){const t=xN(e,"tool_name"),r=[xN(e,"file_path"),"string"==typeof t&&PN.has(t)?xN(xN(e,"tool_input"),"file_path"):void 0];for(const e of r)if("string"==typeof e&&e.length>0)return e}const IN=(0,l.h)("cli-hooks-executor");function TN(e){try{return(0,xo.statSync)(e).isFile()}catch{return!1}}const AN="\nJSON Parse Error: Error: Failed to parse hook stdout as JSON";function $N(e,t){for(const[r,n]of Object.entries(e))if(r===t)return n}function MN(e,t){const r=$N(e,t);if("string"==typeof r||null===r)return r}class DN{constructor(e,t,r,n,o,s,i,a){this.workspacePath=t,this.globalContext=r,this.shellExecutor=n,this.promptHookClient=o,this.onHookExecution=i,this.options=a,this.sessionEnvById=new Map,this.sessionUserEmailById=new Map,this.activeSessionIdsByConversationId=new Map,this.transcriptParentConversationIdById=new Map,this.configReadyPromises=[],this.config=e,s&&this.addConfigReadyPromise(s)}addConfigReadyPromise(e){this.configReadyPromises.push(e.catch((()=>{})))}reportCommandFailure(e,t){if(void 0!==e)try{e(t)}catch{}}finishHookRun(e,t,r,n){const o=e.transportMode??("prompt"===e.hookType?"prompt":this.getCommandHookPayloadTransportMode());try{this.onHookExecution?.({...e,transportMode:o})}catch{}const s=this.options?.onHookRun;if(void 0===s)return;const i=n.exitCode??e.exitCode,a="spawn_error"===(c=e.errorClass)?"shell_exec_transport_error":"prompt_error"===c?"prompt_execution_error":void 0;var c;try{s({step:e.hookStep,script:t,source:e.hookSource,...void 0===e.pluginId?{}:{pluginId:e.pluginId},request:r,response:n.response??null,status:e.status,durationMs:e.latencyMs,...void 0===i?{}:{exitCode:i},stderr:n.stderr,transportMode:o,configuredTimeoutSec:t.timeout??60,timedOut:!0===e.timedOut,...void 0===a?{}:{failureType:a}})}catch{}}getCommandHookPayloadTransportMode(){return"stdin"===this.options?.commandHookPayloadTransport?"win32"===process.platform?"windows_temp_file":"stdin":"argv_heredoc"}shouldUseCommandHookDirectStdinTransport(){return"stdin"===this.getCommandHookPayloadTransportMode()}async writeCommandHookStdinPayload(e,t){if(!e)throw new Error("Hook stdin transport was requested, but the executor did not provide stdin");try{e.end(Buffer.from(t,"utf8"))}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;if("EPIPE"===t||"ERR_STREAM_DESTROYED"===t||"ERR_STREAM_PREMATURE_CLOSE"===t)return;throw e}try{await(0,ah.finished)(e)}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;if("EPIPE"===t||"ERR_STREAM_DESTROYED"===t||"ERR_STREAM_PREMATURE_CLOSE"===t)return;throw e}}updateConfig(e){this.config=e}beginSessionEnvironment(e,t){this.sessionEnvById.delete(e.sessionId),this.sessionUserEmailById.delete(e.sessionId);const r=this.activeSessionIdsByConversationId.get(e.conversationId)??[];this.activeSessionIdsByConversationId.set(e.conversationId,r.filter((t=>t!==e.sessionId)).concat(e.sessionId));const n=t?.userEmail?.trim()??"";n.length>0&&this.sessionUserEmailById.set(e.sessionId,n)}setSessionUserEmail(e,t){const r=t?.trim()??"";0!==r.length&&this.sessionUserEmailById.set(e.sessionId,r)}setSessionEnvironment(e,t){void 0===t?this.sessionEnv={...this.sessionEnv,...e}:this.sessionEnvById.set(t.sessionId,{...this.sessionEnvById.get(t.sessionId),...e})}clearSessionEnvironment(e){if(void 0===e)this.sessionEnv=void 0;else{this.sessionEnvById.delete(e.sessionId),this.sessionUserEmailById.delete(e.sessionId);const t=(this.activeSessionIdsByConversationId.get(e.conversationId)??[]).filter((t=>t!==e.sessionId));0===t.length?this.activeSessionIdsByConversationId.delete(e.conversationId):this.activeSessionIdsByConversationId.set(e.conversationId,t)}}resolveUserEmail(e){const{conversation_id:t,session_id:r}=e;if(void 0!==r&&this.sessionUserEmailById.has(r))return this.sessionUserEmailById.get(r)??null;if(void 0!==t){const e=this.activeSessionIdsByConversationId.get(t)?.at(-1);if(void 0!==e){const t=this.sessionUserEmailById.get(e);if(void 0!==t)return t}}return this.globalContext.user_email}setTranscriptParentConversationId(e,t){this.transcriptParentConversationIdById.set(e,t)}async getTranscriptPathIfExists(e){try{const t=(0,So.Rv)((0,o.homedir)(),this.workspacePath),r=this.transcriptParentConversationIdById.get(e),n=FF(r?{conversationId:e,kind:"subagent",parentConversationId:r}:{conversationId:e,kind:"primary"}).map((e=>(0,s.join)(t,e)));for(const e of n)try{return await(0,Co.access)(e),e}catch{}return null}catch{return null}}async getSubagentTranscriptPathIfExists(e){const{subagentId:t,parentConversationId:r}=e;try{const e=(0,So.Rv)((0,o.homedir)(),this.workspacePath),n=FF({conversationId:t,kind:"subagent",parentConversationId:r}).map((t=>(0,s.join)(e,t)));for(const e of n)try{return await(0,Co.access)(e),e}catch{}return null}catch{return null}}hasHooksForStep(e){return[this.config.enterpriseHooks,this.config.teamHooks,this.config.userHooks,this.config.projectHooks,this.options?.runtimeHooks,this.config.claudeUserHooks,this.config.claudeProjectHooks,this.config.claudeProjectLocalHooks,...wN(this.config),...(this.config.pluginHooks??[]).map((e=>e.config))].some((t=>{const r=t?.hooks[e];return void 0!==r&&r.length>0}))}hasFailClosedHooksForStep(e,t){const r=[this.config.enterpriseHooks,this.config.teamHooks,this.config.projectHooks,...(this.config.repoHooks??[]).map((e=>e.projectHooks)),this.config.userHooks,this.options?.runtimeHooks];for(const n of r){const r=n?.hooks[e];if(r&&(t?hN(r,t):r).some((e=>!0===e.failClosed)))return!0}for(const r of this.config.pluginHooks??[]){const n=r.config.hooks[e];if(n&&(t?hN(n,t):n).some((e=>mF(e)&&!0===e.failClosed)))return!0}return!1}configuredHookDirectory(e){const t=this.config.configDirs;switch(e){case"enterprise":return t?.enterprise;case"team":return t?.team;case"user":return t?.user;case"claude-user":return t?.claudeUser;default:return}}cwdForHookSource(e,t){if(void 0!==e?.cwd&&e.cwd.length>0)return e.cwd;const r=this.configuredHookDirectory(t.source);if(void 0!==r&&r.length>0)return r;const n=e?.cwdForSource?.(t.source);return void 0!==n&&n.length>0?n:t.fallback}getCwdForSource(e){const t=this.config.configDirs;switch(e){case"enterprise":return t?.enterprise??this.workspacePath;case"team":return t?.team??this.workspacePath;case"project":case"claude-project":case"claude-project-local":case"claude-plugin":case"runtime":default:return this.workspacePath;case"user":return t?.user??this.workspacePath;case"claude-user":return t?.claudeUser??this.workspacePath}}buildHookEnvironment(e){const{transcriptPath:t,sessionId:r,conversationId:n,executionEnv:o}=e,s=this.resolveUserEmail({conversation_id:n,session_id:r});return{CURSOR_PROJECT_DIR:this.workspacePath,CURSOR_VERSION:this.globalContext.cursor_version,...s&&{CURSOR_USER_EMAIL:s},...t&&{CURSOR_TRANSCRIPT_PATH:t},CLAUDE_PROJECT_DIR:this.workspacePath,...this.sessionEnv,...void 0!==r?this.sessionEnvById.get(r):void 0,...o}}shouldSkipHookDueToLoopLimit(e,t,r){if("stop"!==e&&"subagentStop"!==e)return!1;const n=$N(r,"loop_count");if("number"!=typeof n)return!1;const o=n,s=t.loop_limit;return null!==s&&(void 0===s?o>=5:o>=s)}async executeHookForStep(e,t,r){this.configReadyPromises.length>0&&await this.whenConfigReady();const n=function(e){return vF.includes(e)}(e),o=t,i=n?null:o.conversation_id?await this.getTranscriptPathIfExists(o.conversation_id):null;let a;if(e===xd.subagentStop){const e=MN(t,"subagent_id"),r=MN(t,"parent_conversation_id");a=e?await this.getSubagentTranscriptPathIfExists({subagentId:e,parentConversationId:r??void 0}):null}const c=n?void 0:o.session_id??o.conversation_id,l={...t,...void 0!==c&&{session_id:c},hook_event_name:e,cursor_version:this.globalContext.cursor_version,workspace_roots:[...new Set([this.workspacePath,...(this.config.repoHooks??[]).map((e=>e.repoPath))])],user_email:this.resolveUserEmail(o),...!n&&{transcript_path:i},...e===xd.subagentStop&&{agent_transcript_path:a??null}},u=function(e,t){switch(e){case"beforeShellExecution":case"afterShellExecution":return dN(t,"command");case"beforeMCPExecution":case"afterMCPExecution":{const e=dN(t,"tool_name");return e?`MCP:${e}`:void 0}case"beforeReadFile":return"Read";case"afterFileEdit":return"Write";case"beforeTabFileRead":return"TabRead";case"afterTabFileEdit":return"TabWrite";case"beforeSubmitPrompt":return"UserPromptSubmit";case"stop":return"Stop";case"afterAgentResponse":return"AgentResponse";case"afterAgentThought":return"AgentThought";case"subagentStart":case"subagentStop":return dN(t,"subagent_type");case"preToolUse":case"postToolUse":case"postToolUseFailure":return dN(t,"tool_name");default:return}}(e,l),d=[],h=(e,t,n)=>{if(!e)return;const o=hN(e,u),s=this.cwdForHookSource(r,{source:t,fallback:n??this.getCwdForSource(t)}),i=void 0===n?r?.env:{CURSOR_PROJECT_DIR:n,CLAUDE_PROJECT_DIR:n,...r?.env};for(const e of o)fF(e)?this.promptHookClient&&d.push({type:"prompt",script:e,source:t}):mF(e)&&d.push({type:"command",script:e,cwd:s,env:i,source:t})},p=await async function({repoHooks:e,targetPath:t,workspacePath:r}){if(e.length<2||void 0===t||0===t.length)return e;const n=(0,Yo.o1)(t,r),[o,i,a]=await Promise.all([(0,Yo.DN)(n),(0,Yo.DN)(s.default.dirname(n)),Promise.all(e.map((async e=>await(0,Yo.DN)(e.repoPath)??s.default.resolve(e.repoPath))))]);if(null===o||null===i)return e;const c=t=>{let r;return e.forEach(((e,n)=>{const o=a[n],i=s.default.relative(o,t);(""===i||".."!==i&&!i.startsWith(`..${s.default.sep}`)&&!s.default.isAbsolute(i))&&(void 0===r||o.length>r.repoPath.length)&&(r={repo:e,repoPath:o})})),r?.repo},l=new Set;for(const t of[o,s.default.join(i,s.default.basename(n))]){const r=c(t);if(void 0===r)return e;l.add(r)}return e.filter((e=>l.has(e)))}({repoHooks:this.config.repoHooks??[],targetPath:RN(t),workspacePath:this.workspacePath});h(this.config.enterpriseHooks?.hooks[e],"enterprise"),h(this.config.teamHooks?.hooks[e],"team"),h(this.config.projectHooks?.hooks[e],"project");for(const t of p)h(t.projectHooks?.hooks[e],"project",t.repoPath);h(this.config.userHooks?.hooks[e],"user"),h(this.options?.runtimeHooks?.hooks[e],"runtime"),h(this.config.claudeProjectLocalHooks?.hooks[e],"claude-project-local"),h(this.config.claudeProjectHooks?.hooks[e],"claude-project");for(const t of p)h(t.claudeProjectLocalHooks?.hooks[e],"claude-project-local",t.repoPath),h(t.claudeProjectHooks?.hooks[e],"claude-project",t.repoPath);h(this.config.claudeUserHooks?.hooks[e],"claude-user");for(const t of this.config.pluginHooks??[]){const n=t.config.hooks[e];if(!n?.length)continue;const o=r?.cwd??(e===xd.stop||e===xd.subagentStop?this.workspacePath:t.installPath),s={...void 0!==t.plugin&&{plugin:t.plugin},...void 0!==t.marketplace&&{marketplace:t.marketplace},...void 0!==t.pluginId&&{pluginId:t.pluginId},...void 0!==t.marketplaceId&&{marketplaceId:t.marketplaceId}};for(const e of hN(n,u))mF(e)&&d.push({type:"command",script:e,cwd:o,env:r?.env,source:"claude-plugin",attribution:s,pluginInstallPath:t.installPath})}if(0!==d.length)return this.executeAllAndMerge(e,d,l,r?.onCommandFailure)}async whenConfigReady(){await Promise.all(this.configReadyPromises)}async executeAllAndMerge(e,t,r,n){let o;const s=()=>o??=function(e){const t=JSON.stringify(e);return{json:t,payloadSizeBytes:Buffer.byteLength(t,"utf8")}}(r),i=t.map((async(t,o)=>{const{source:i,attribution:a}=t;try{return"prompt"===t.type?await this.executePromptHook(e,t.script,r,i,o,s,a):await this.executeCommandHook(e,t.script,t.cwd,t.env,r,i,o,s,a,t.pluginInstallPath,n)}catch(r){const n=r instanceof Error?r.message:String(r);if(!0===t.script.failClosed){const t=pN(`Hook execution failed: ${n}`),r=EF(e,t);if(r)return{success:!0,data:r,source:i,index:o}}return IN.warn((0,y.q6)(),`${e} hook error`,{source:i,index:o,error:n}),{success:!1,source:i,index:o}}})),a=await Promise.all(i),c=[];for(const e of a)e.success&&void 0!==e.data&&c.push(e.data);return function(e,t){if(0===t.length)return;const[r]=t;if(!(1!==t.length||Id(n=r)&&Id(n.updated_input)&&0===Object.keys(n.updated_input).length))return r;var n;const o=yF.includes(e),s=e===xd.sessionStart,i=e===xd.workspaceOpen,a=pF.has(e),c={};for(const e of t){const t=e;for(const[e,r]of Object.entries(t))if(void 0!==r)if(i&&"pluginPaths"===e&&Array.isArray(r)){const t=c[e],n=Array.isArray(t)?t:[],o=new Set(n),s=[...n];for(const e of r)"string"!=typeof e||o.has(e)||(o.add(e),s.push(e));c[e]=s}else"permission"===e&&o?c[e]=(u=r,"deny"===(l=c[e])||"deny"===u?"deny":"ask"===l||"ask"===u?"ask":"allow"===l||"allow"===u?"allow":void 0):"user_message"!==e&&"agent_message"!==e?"updated_input"!==e?a&&"additional_context"===e&&"string"==typeof r?c[e]=bF(c[e],r):"continue"!==e||"boolean"!=typeof r?c[e]=s&&"env"===e&&"object"==typeof r&&null!==r?SF(c[e],r):r:void 0===c[e]?c[e]=r:c[e]=c[e]&&r:void 0===c[e]&&Id(r)&&Object.keys(r).length>0&&(c[e]=r):c[e]=bF(c[e],r)}var l,u;return c}(e,c)}async executeCommandHook(e,t,r,n,o,s,i,a,c,l,u){if(this.shouldSkipHookDueToLoopLimit(e,t,o))return{success:!1,source:s,index:i};const d=Date.now(),h=a(),p=h.payloadSizeBytes,f=(e,r)=>this.finishHookRun(e,t,o,r);let m;try{m=await this.executeCommandScript({script:t,cwd:r,request:o,jsonPayload:h.json,env:n,...void 0!==l&&{pluginInstallPath:l}})}catch(r){const n=r instanceof Error?r.message:String(r),o=n.toLowerCase().includes("timed out");this.reportCommandFailure(u,{command:t.command,source:s,exitCode:null,stderr:"",errorMessage:n});const a=Date.now()-d,l=o?"timeout":"spawn_error";if(!0===t.failClosed){const u=EF(e,pN(`Hook "${t.command}" execution failed: ${n}`));if(u)return f({hookStep:e,hookSource:s,hookType:"command",status:o?"timeout":"blocked",latencyMs:a,payloadSizeBytes:p,errorClass:l,failClosed:!0,timedOut:o,...c},{response:null,stderr:String(r)}),{success:!0,data:u,source:s,index:i}}return f({hookStep:e,hookSource:s,hookType:"command",status:o?"timeout":"failed",latencyMs:a,payloadSizeBytes:p,errorClass:l,failClosed:!0===t.failClosed,timedOut:o,...c},{response:null,stderr:String(r)}),{success:!1,source:s,index:i}}if(2===m.exitCode){const r=function(e,t,r){const n=e.trim(),o=t.trim();return n||(o?`Hook blocked with message: ${o}`:`Hook "${r}" blocked this action (exit code 2) but provided no reason.`)}(m.stdout,m.stderr,t.command),n=EF(e,r);return n?(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,failClosed:!0===t.failClosed,exitCode:m.exitCode,...c},{response:n,stderr:m.stderr}),{success:!0,data:n,source:s,index:i}):(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,failClosed:!0===t.failClosed,exitCode:m.exitCode,...c},{response:null,stderr:m.stderr}),{success:!1,source:s,index:i})}if(0!==m.exitCode&&null!==m.exitCode){if(this.reportCommandFailure(u,{command:t.command,source:s,exitCode:m.exitCode,stderr:m.stderr}),!0===t.failClosed){const r=EF(e,pN(`Hook "${t.command}" failed with exit code ${m.exitCode}${m.stderr?`: ${m.stderr.trim()}`:""}`));if(r)return f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"exit_nonzero",failClosed:!0,exitCode:m.exitCode,...c},{response:null,stderr:m.stderr}),{success:!0,data:r,source:s,index:i}}return f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"exit_nonzero",failClosed:!0===t.failClosed,exitCode:m.exitCode,...c},{response:null,stderr:m.stderr}),{success:!1,source:s,index:i}}const g=m.stdout.trim();if(!g){if(!0===t.failClosed){const r=EF(e,pN(`Hook "${t.command}" returned no output.`));if(r)return f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"empty_stdout",failClosed:!0,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr}),{success:!0,data:r,source:s,index:i}}return f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"empty_stdout",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr}),{success:!1,source:s,index:i}}const w=function(e){const t=e.trim();if(0===t.length)return;const r=xF(t);if(void 0!==r)return r.value;if(t.endsWith("}"))for(let e=t.length-1;e>=0;e--){if("{"!==t[e])continue;const r=xF(t.slice(e));if(void 0!==r)return r.value}}(g);if(void 0===w){const r=_F({step:e,command:t.command,failClosed:!0===t.failClosed,kind:"invalid_json"});return r.blockResponse?(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_json",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr+AN}),{success:!0,data:r.blockResponse,source:s,index:i}):(f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_json",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:null,stderr:m.stderr+AN}),{success:!1,source:s,index:i})}const y=wF(e,w,{enableClaudeNestedHookSpecificOutputCompatibility:this.options?.enableClaudeNestedHookSpecificOutputCompatibility});if(y.success&&null!=y.data){const r=y.data,n="object"==typeof r&&"permission"in r?r.permission:void 0;return f({hookStep:e,hookSource:s,hookType:"command",status:"deny"===n||"ask"===n?"blocked":"success",latencyMs:m.duration,payloadSizeBytes:p,failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:r,stderr:m.stderr}),{success:!0,data:r,source:s,index:i}}const v=_F({step:e,command:t.command,failClosed:!0===t.failClosed,kind:"invalid_response"});return v.blockResponse?(f({hookStep:e,hookSource:s,hookType:"command",status:"blocked",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_response",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:w,stderr:m.stderr}),{success:!0,data:v.blockResponse,source:s,index:i}):(f({hookStep:e,hookSource:s,hookType:"command",status:"failed",latencyMs:m.duration,payloadSizeBytes:p,errorClass:"invalid_response",failClosed:!0===t.failClosed,exitCode:m.exitCode??void 0,...c},{response:w,stderr:m.stderr}),{success:!1,source:s,index:i})}async executePromptHook(e,t,r,n,o,s,i){if(this.shouldSkipHookDueToLoopLimit(e,t,r))return{success:!1,source:n,index:o};if(!this.promptHookClient)return{success:!1,source:n,index:o};const a=1e3*(t.timeout??60),c=Date.now(),l=s(),u=l.payloadSizeBytes,d=(e,n)=>this.finishHookRun(e,t,r,n),h=(0,y.q6)(),[p,f]=h.withTimeoutAndCancel(a);try{const r=JSON.parse(l.json),s=await this.promptHookClient.evaluatePromptHook(p,{prompt:t.prompt,hookInputJson:r,modelName:t.model});if(s.ok){const r=function(e){return kF(e)?CF(0,{permission:"allow"}):e===xd.beforeSubmitPrompt||e===xd.sessionStart?CF(0,{continue:!0}):e===xd.stop?CF(0,{}):void 0}(e);return d({hookStep:e,hookSource:n,hookType:"prompt",status:"success",latencyMs:Date.now()-c,payloadSizeBytes:u,failClosed:!0===t.failClosed,...i},{response:r,stderr:"",exitCode:0}),r?{success:!0,data:r,source:n,index:o}:{success:!1,source:n,index:o}}{const r=EF(e,s.reason??"Prompt hook blocked this action");return d({hookStep:e,hookSource:n,hookType:"prompt",status:"blocked",latencyMs:Date.now()-c,payloadSizeBytes:u,failClosed:!0===t.failClosed,...i},{response:r,stderr:"",exitCode:2}),r?{success:!0,data:r,source:n,index:o}:{success:!1,source:n,index:o}}}catch(r){const s=r instanceof Error?r.message:String(r),a=s.toLowerCase().includes("abort")||s.toLowerCase().includes("timed out"),l=a?"timeout":"prompt_error";if(!0===t.failClosed){const t=EF(e,pN(`Prompt hook failed: ${s}`));if(t)return d({hookStep:e,hookSource:n,hookType:"prompt",status:a?"timeout":"blocked",latencyMs:Date.now()-c,payloadSizeBytes:u,errorClass:l,failClosed:!0,timedOut:a,...i},{response:null,stderr:String(r)}),{success:!0,data:t,source:n,index:o}}return d({hookStep:e,hookSource:n,hookType:"prompt",status:a?"timeout":"failed",latencyMs:Date.now()-c,payloadSizeBytes:u,errorClass:l,failClosed:!0===t.failClosed,timedOut:a,...i},{response:null,stderr:String(r)}),{success:!1,source:n,index:o}}finally{f()}}async executeCommandScript(e){const{script:t,cwd:r,request:n,env:i,pluginInstallPath:a,jsonPayload:c}=e,l=1e3*(t.timeout??60),u=Date.now();let d;const h=new AbortController,p=setTimeout((()=>{h.abort()}),l);try{const e="win32"===process.platform,f=this.getCommandHookPayloadTransportMode(),m=this.shouldUseCommandHookDirectStdinTransport(),g=e?function(e,t){const r=function(e){let t=0;for(;t0&&!/^\s/.test(i))return e;if(/[$`{}()|;,<>]/.test(s)||""===o&&/['"]/.test(s))return e;const a=s.slice(Math.max(s.lastIndexOf("\\"),s.lastIndexOf("/"))+1);if(0===a.length||a.includes("."))return e;const c="'"===o?s.replace(/''/g,"'"):s,l=/^[A-Za-z]:[\\/]/.test(u=c)||u.startsWith("\\")||u.startsWith("/")?c:`${t.cwd.replace(/[\\/]+$/,"")}\\${c}`;var u;const d=nF.find((e=>t.isFile(l+e)));return void 0===d?e:""!==o?`${n}${o}${s}${d}${o}${i}`:`${n}'${s}${d}'${i}`}(t.command,{cwd:r,isFile:TN}):t.command;let w;if(m)w=e?oF(g):g;else if("windows_temp_file"===f){d=await(0,Co.mkdtemp)((0,s.join)((0,o.tmpdir)(),"cursor-hooks-"));const e=(0,s.join)(d,"payload.json");await(0,Co.writeFile)(e,c,{encoding:"utf8",flag:"wx"}),w=function(e,t){return`$OutputEncoding = [System.Text.UTF8Encoding]::new($false); try { $global:cursorHookConsoleInputEncoding = [Console]::InputEncoding; $null = Register-EngineEvent -SourceIdentifier PowerShell.Exiting -Action { try { [Console]::InputEncoding = $global:cursorHookConsoleInputEncoding } catch { } }; [Console]::InputEncoding = $OutputEncoding } catch { }; Get-Content -LiteralPath '${e.replace(/'/g,"''")}' -Raw -Encoding UTF8 | & { $input | ${oF(t)} }`+rF(t)}(e,g)}else w=e?`@'\n${c.replace(/'/g,"''")}\n'@ | & ${g}`+rF(g):`${t.command} <<'CURSOR_HOOK_EOF'\n${c}\nCURSOR_HOOK_EOF`;const v=MN(n,"conversation_id")??void 0,b=MN(n,"session_id")??void 0,S=MN(n,"transcript_path"),k=void 0===v?void 0:this.activeSessionIdsByConversationId.get(v),_=void 0===b||b===v&&!this.sessionEnvById.has(b)?void 0===v?void 0:k?.at(-1)??v:b,C=this.buildHookEnvironment({transcriptPath:S,sessionId:_,conversationId:v,executionEnv:i}),E={};for(const[e,t]of Object.entries(C))void 0!==t&&(E[e]=t);void 0!==a&&(E.CURSOR_PLUGIN_ROOT=a,E.CLAUDE_PLUGIN_ROOT=a);const x=(0,y.q6)(),P=new ia.StringDecoder("utf8"),R=new ia.StringDecoder("utf8");let I,T="",A="",$=null,M=!1;for await(const e of this.shellExecutor.execute(x,w,{workingDirectory:r,signal:h.signal,sandboxPolicy:{perUser:{type:"insecure_none"}},env:E,pipeStdin:m}))switch(e.type){case"stdin_ready":m&&(await this.writeCommandHookStdinPayload(e.stdin,c),M=!0);break;case"stdout":T+=P.write(e.data);break;case"stderr":A+=R.write(e.data);break;case"exit":$=e.code,I=e.aborted}if(T+=P.end(),A+=R.end(),m&&!M)throw new Error("Hook stdin transport was requested, but the executor did not signal stdin readiness");clearTimeout(p);const D=Date.now()-u;if(I??h.signal.aborted)throw new Error(`Hook script timed out after ${l}ms`);return{stdout:T,stderr:A,exitCode:$,duration:D}}catch(e){if(clearTimeout(p),Date.now(),h.signal.aborted)throw new Error(`Hook script timed out after ${l}ms`);throw e}finally{if(d)try{await(0,Co.rm)(d,{recursive:!0,force:!0})}catch{}}}}class ON{constructor(e){this.config=e,this.configuredSteps=yN.getConfiguredSteps(e)}getConfig(){return this.config}hasHookForStep(e){return this.configuredSteps.has(e)}getConfiguredSteps(){return new Set(this.configuredSteps)}}var FN=r("node:perf_hooks");const NN=(0,y.cF)(Symbol.for("@anysphere/agent-exec/toolCallHooks"),{kind:"none"});function LN(e){return"inExecute"!==e.get(NN).kind}function jN(e,t){const r=e.get(NN);return"inExecute"!==r.kind||!r.toolStepsInPreToolUse.includes(t)}(0,y.cF)(Symbol.for("@anysphere/agent-exec/hookAsk"),void 0),(0,y.cF)(Symbol.for("@anysphere/agent-exec/hookAllow"),void 0),new WeakMap,new WeakMap,(0,y.cF)(Symbol.for("@anysphere/agent-exec/toolCallRefusal"),void 0),new WeakMap,new WeakMap,new WeakMap,(0,y.cF)(Symbol.for("@anysphere/agent-exec/approvalWaits"),void 0),new WeakMap;const UN=(0,y.cF)(Symbol.for("@anysphere/agent-exec/hookStepTime"),void 0),BN=new yd.AsyncLocalStorage;function WN(e,t){return BN.run(e,t)}function HN(e,t){void 0!==e&&t.length>0&&e.push(...t)}class qN extends Error{constructor(e){super(`Hook additional_context for ${e.hookEventName} is ${e.actualLength} chars (max ${e.maxLength}).`),this.name="HookAdditionalContextTooLargeError",this.hookEventName=e.hookEventName,this.actualLength=e.actualLength,this.maxLength=e.maxLength}}var zN=r("../proto/dist/generated/agent/v1/hook_additional_context_pb.js");function GN({hookEventName:e,additionalContext:t}){const r=function(e){const t=e?.trim();return void 0!==t&&t.length>0?t:void 0}(t);if(void 0===r)return[];if(r.length>1e4)throw new qN({hookEventName:e,actualLength:r.length,maxLength:1e4});return[new zN.C({hookEventName:e,content:r})]}Object.fromEntries(Array.from(pF).map((e=>{if(!function(e){return e===xd.sessionStart||e===xd.beforeSubmitPrompt||e===xd.preToolUse||e===xd.postToolUse||e===xd.postToolUseFailure}(e))throw new Error(`HOOK_STEPS_SUPPORTING_ADDITIONAL_CONTEXT lists ${e} but HookStepAdditionalContextEventName does not include it. Extend the Extract<> union in spec.ts.`);return[e,{hookEventName:e}]})));const VN="Agent note: Do not suggest workarounds to the blocked tool.";function KN(e){return e.includes(VN)?e:`${e}\n\n${VN}`}class JN extends Error{constructor(e){super(`Hook denied: ${e}`),this.failureType="permission_denied",this.name="HookDeniedError",this.reason=e}}class ZN extends Error{constructor(e,t){super(`Hook failed (fail-closed): ${e}`),this.failureType="error",this.name="FailClosedError",this.reason=e,this.cause=t}}const XN="To view or modify configured hooks, go to Cursor Settings > Hooks.";function QN(e,t){return KN(`${t?`${e} was blocked by a hook: ${t}`:`${e} was blocked by a hook.`}\n\n${XN}`)}function YN(e){return function(e){return e instanceof JN}(e)||function(e){return e instanceof ZN}(e)}const eL=(0,l.h)("generic-hooks");function tL(e,t,r,n){try{return GN({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof qN)return eL.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}const rL=e=>Math.round(1e3*e)/1e3;function nL(e,t,r,n,o,s){const i=n(e),a=o.getToolCallId?.(t)??(0,bo.randomUUID)(),c=o.getExtraHookFields?.(t)??{},l={baseHookRequest:i,toolUseId:a,toolInput:o.createToolInput(t),extraHookFields:c,hookContextCollector:s?.hookContextCollector??o.getHookContextCollector?.(t)??[]},u=function(e,t,r,n){let{toolInput:o,extraHookFields:s,hookContextCollector:i}=n;const{baseHookRequest:a,toolUseId:c}=n;return{fireFailureAsync:async(n,l,u,d=!1)=>{try{const h=await WN(e.signal,(()=>t.executeHookForStep(xd.postToolUseFailure,{...a,tool_name:r,tool_input:o,error_message:l,failure_type:u,duration:n,tool_use_id:c,is_interrupt:d,...s})));HN(i,tL(e,r,xd.postToolUseFailure,h?.additional_context))}catch(t){eL.warn(e,"postToolUseFailure hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}},fireSuccessAsync:async(n,l)=>{try{const u=await WN(e.signal,(()=>t.executeHookForStep(xd.postToolUse,{...a,tool_name:r,tool_input:o,tool_output:l,duration:n,tool_use_id:c,...s})));HN(i,tL(e,r,xd.postToolUse,u?.additional_context))}catch(t){eL.warn(e,"postToolUse hook error",{toolName:r,error:t instanceof Error?t.message:String(t)})}},getToolInput:()=>o,setToolInput:e=>{o=e},setExtraHookFields:e=>{s=e,n.extraHookFields=e}}}(e,r,o.toolName,l);return{hookContext:l,helpers:u}}async function oL(e,t,r,n,o,s,i,a){const{baseHookRequest:c,toolUseId:l,extraHookFields:u}=n;try{const a=await WN(e.signal,(()=>r.executeHookForStep(xd.preToolUse,{...c,tool_name:s.toolName,tool_input:o.getToolInput(),tool_use_id:l,...u})));if("deny"===a?.permission){const r=a.user_message||`${s.toolName} blocked by preToolUse hook`,c=KN(r);try{HN(n.hookContextCollector,GN({hookEventName:xd.preToolUse,additionalContext:a.additional_context}))}catch(t){if(!(t instanceof qN))throw t;eL.warn(e,"preToolUse deny additional_context exceeded max size; dropping carrier",{toolName:s.toolName,actualLength:t.actualLength,maxLength:t.maxLength})}return await o.fireFailureAsync(0,r,"permission_denied"),{type:"rejected",result:i(t,c),reason:c}}a?.updated_input&&s.applyUpdatedInput&&(s.applyUpdatedInput(t,a.updated_input),o.setToolInput(s.createToolInput(t)),s.getExtraHookFields&&o.setExtraHookFields(s.getExtraHookFields(t))),HN(n.hookContextCollector,GN({hookEventName:xd.preToolUse,additionalContext:a?.additional_context}))}catch(n){const a=r.hasFailClosedHooksForStep?.(xd.preToolUse,s.toolName)??!1,c=n instanceof qN;if(a){const e=pN(`${c?"preToolUse additional_context exceeded max size":"preToolUse hook failed"}: ${n instanceof Error?n.message:"preToolUse hook error"}`);return await o.fireFailureAsync(0,e,"error"),{type:"rejected",result:i(t,e),reason:e}}eL.warn(e,c?"preToolUse additional_context exceeded max size; dropping carrier":"preToolUse hook error",{toolName:s.toolName,error:n instanceof Error?n.message:String(n),...c?{actualLength:n.actualLength,maxLength:n.maxLength}:{}})}if(a)try{const s=await a({ctx:e,args:t,baseHookRequest:c,hookExecutor:r,toolInput:o.getToolInput(),toolUseId:l,extraHookFields:n.extraHookFields});if(void 0!==s){const e="Pre-execution hook returned rejection";return await o.fireFailureAsync(0,e,"permission_denied"),{type:"rejected",result:s,reason:e}}}catch(e){if(YN(e))return await o.fireFailureAsync(0,e.reason,e.failureType),{type:"rejected",result:i(t,e.reason),reason:e.reason};throw e}return{type:"continue"}}function sL(e){return e.toolCallId}function iL(e,t,r,n){return{async execute(o,s,i){const a=cL(o,t),{hookContext:c,helpers:l}=nL(o,s,a,r,n,i);let u;try{u=await oL(o,s,a,c,l,n,n.createRejectedResult,n.runPreExecutionHooks)}catch(e){throw n.runCleanup?.(c.toolUseId),e}if("rejected"===u.type)return n.runCleanup?.(c.toolUseId),u.result;const d=FN.performance.now();try{const t=await e.execute(o,s,i),r=rL(FN.performance.now()-d);if(n.runPostExecutionHooks)try{const e=await n.runPostExecutionHooks({ctx:o,args:s,result:t,baseHookRequest:c.baseHookRequest,hookExecutor:a,toolInput:l.getToolInput(),toolUseId:c.toolUseId,executionDurationMs:r,extraHookFields:c.extraHookFields});if(void 0!==e)return await l.fireSuccessAsync(r,JSON.stringify(n.createSuccessOutput(s,e))),n.runCleanup?.(c.toolUseId),e}catch(e){if(YN(e))return await l.fireFailureAsync(r,e.reason,e.failureType),n.runCleanup?.(c.toolUseId),n.createRejectedResult(s,e.reason);eL.warn(o,"postExecutionHooks error",{toolName:n.toolName,error:e instanceof Error?e.message:String(e)})}return n.isSuccess(t)?await l.fireSuccessAsync(r,JSON.stringify(n.createSuccessOutput(s,t))):await l.fireFailureAsync(r,n.getErrorMessage(t),n.getFailureType?.(t)??"error",n.isInterrupt?.(t)??!1),n.runCleanup?.(c.toolUseId),t}catch(e){const t=rL(FN.performance.now()-d);throw await l.fireFailureAsync(t,e instanceof Error?e.message:String(e),"error"),n.runCleanup?.(c.toolUseId),e}}}}function*aL(e,t){const r=t.hookContextCollector;e.createHookContextEvent&&void 0!==r&&0!==r.length&&(yield e.createHookContextEvent(r))}function cL(e,t){const r=LN(e),n=e.get(UN);if(r&&void 0===n)return t;const o=e=>n?.during(e)??e;return{executeHookForStep:async(e,n)=>{if(r||!function(e){return e===xd.preToolUse||e===xd.postToolUse||e===xd.postToolUseFailure}(e))return o(t.executeHookForStep(e,n));await o(t.whenConfigReady())},hasFailClosedHooksForStep:(e,r)=>t.hasFailClosedHooksForStep?.(e,r)??!1,hasHooksForStep:e=>t.hasHooksForStep?.(e)??!0,whenConfigReady:()=>o(t.whenConfigReady())}}function lL(e){if("object"!=typeof e||null===e||!("code"in e))return!1;const t=e.code;return"ENOENT"===t||"ENOTDIR"===t}class uL{async readFile(e){try{return await Co.readFile(e,"utf-8")}catch(e){if("ENOENT"===e?.code)return;throw e}}async exists(e){try{return await Co.access(e),!0}catch{return!1}}async pathContainsSymlink(e,t){return async function(e,t){const r=function(e,t){const r=s.default.resolve(e),n=s.default.resolve(t),o=s.default.relative(n,r);if(0===o.length||".."===o||o.startsWith(`..${s.default.sep}`)||s.default.isAbsolute(o))return"unsafe";const i=o.split(s.default.sep).filter((e=>e.length>0)),a=[];let c=n;for(const e of i)c=s.default.join(c,e),a.push(c);return a}(e,t);if("unsafe"===r)return!0;for(const e of r)try{if((await(0,Co.lstat)(e)).isSymbolicLink())return!0}catch(e){if(lL(e))return!0;throw e}return!1}(e,t)}}var dL=r("../proto/dist/generated/agent/v1/hooks_pb.js");const hL=q("hook-executor",(e=>new B(e,Z("executeHookArgs"),X("executeHookResult"))),((e,t)=>{t.register(new I(e,Y("executeHookArgs"),Q("executeHookResult")))})),pL=new Set(Object.values(xd));function fL(e){switch(e){case"completed":case"aborted":case"error":return e;default:return"error"}}function mL(e){switch(e){case"error":case"timeout":case"permission_denied":return e;default:return"error"}}function gL(e){const t=e?.toJson();return"object"!=typeof t||null===t||Array.isArray(t)?{}:t}class wL{constructor(e){this.hookExecutor=e}hasFailClosedHooksForStep(e,t){return!!function(e){return pL.has(e)}(e)&&(this.hookExecutor.hasFailClosedHooksForStep?.(e,t)??!1)}async execute(e,t){const r=t.request;if(!r)return new d.S1({response:void 0});switch(r.request.case){case"preCompact":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...hF(e),trigger:"manual"===e.trigger?"manual":"auto",context_usage_percent:e.contextUsagePercent,context_tokens:Number(e.contextTokens),context_window_size:Number(e.contextWindowSize),message_count:e.messageCount,messages_to_compact:e.messagesToCompact,is_first_compaction:e.isFirstCompaction},n=await this.hookExecutor.executeHookForStep(xd.preCompact,t);return new d.S1({response:new d.w5({response:{case:"preCompact",value:new dL.$_({userMessage:n?.user_message})}})})}case"subagentStart":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...hF(e),subagent_id:e.subagentId,subagent_type:e.subagentType,task:e.task,parent_conversation_id:e.parentConversationId,tool_call_id:e.toolCallId,subagent_model:e.subagentModel,is_parallel_worker:e.isParallelWorker,git_branch:e.gitBranch},n=await this.hookExecutor.executeHookForStep(xd.subagentStart,t);return new d.S1({response:new d.w5({response:{case:"subagentStart",value:new dL.W0({permission:n?.permission,userMessage:n?.user_message,additionalContext:n?.additional_context})}})})}case"subagentStop":{const e=r.request.value,t={conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...hF(e),subagent_id:e.subagentId,subagent_type:e.subagentType,status:fL(e.status),duration_ms:Number(e.durationMs),summary:e.summary,parent_conversation_id:e.parentConversationId,message_count:e.messageCount,tool_call_count:e.toolCallCount,error_message:e.errorMessage,modified_files:e.modifiedFiles,git_branch:e.gitBranch,loop_count:e.loopCount??0,task:e.task,description:e.description,...e.childConversationId?{child_conversation_id:e.childConversationId}:{}},n=await this.hookExecutor.executeHookForStep(xd.subagentStop,t);return new d.S1({response:new d.w5({response:{case:"subagentStop",value:new dL.AH({followupMessage:n?.followup_message,additionalContext:n?.additional_context})}})})}case"beforeSubmitPrompt":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(xd.beforeSubmitPrompt,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...hF(e),prompt:e.prompt,attachments:(n=e.attachments,n.flatMap((e=>"file"===e.type||"rule"===e.type?[{type:e.type,file_path:e.filePath}]:[]))),composer_mode:e.composerMode});return new d.S1({response:new d.w5({response:{case:"beforeSubmitPrompt",value:new dL.u1({continue:t?.continue,userMessage:t?.user_message,additionalContext:t?.additional_context})}})})}case"afterAgentResponse":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(xd.afterAgentResponse,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...hF(e),text:e.text,input_tokens:void 0!==e.inputTokens?Number(e.inputTokens):void 0,output_tokens:void 0!==e.outputTokens?Number(e.outputTokens):void 0,cache_read_tokens:void 0!==e.cacheReadTokens?Number(e.cacheReadTokens):void 0,cache_write_tokens:void 0!==e.cacheWriteTokens?Number(e.cacheWriteTokens):void 0}),new d.S1({response:new d.w5({response:{case:"afterAgentResponse",value:new dL.FW}})})}case"afterAgentThought":{const e=r.request.value;return await this.hookExecutor.executeHookForStep(xd.afterAgentThought,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...hF(e),text:e.text,duration_ms:void 0!==e.durationMs?Number(e.durationMs):void 0}),new d.S1({response:new d.w5({response:{case:"afterAgentThought",value:new dL.H}})})}case"stop":{const e=r.request.value,t=await this.hookExecutor.executeHookForStep(xd.stop,{conversation_id:e.conversationId??"",generation_id:e.generationId??"",model:e.model??"",...hF(e),status:fL(e.status),loop_count:e.loopCount,input_tokens:void 0!==e.inputTokens?Number(e.inputTokens):void 0,output_tokens:void 0!==e.outputTokens?Number(e.outputTokens):void 0,cache_read_tokens:void 0!==e.cacheReadTokens?Number(e.cacheReadTokens):void 0,cache_write_tokens:void 0!==e.cacheWriteTokens?Number(e.cacheWriteTokens):void 0});return new d.S1({response:new d.w5({response:{case:"stop",value:new dL.rT({followupMessage:t?.followup_message})}})})}case"preToolUse":{if(!LN(e))return this.skipToolUseStep();const t=r.request.value,n=gL(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...hF(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,tool_use_id:t.toolUseId,cwd:t.cwd},s=await this.hookExecutor.executeHookForStep(xd.preToolUse,o);return new d.S1({response:new d.w5({response:{case:"preToolUse",value:new dL.Wn({permission:s?.permission,userMessage:s?.user_message,agentMessage:s?.agent_message,updatedInput:s?.updated_input?JSON.stringify(s.updated_input):void 0,additionalContext:s?.additional_context})}})})}case"postToolUse":{if(!LN(e))return this.skipToolUseStep();const t=r.request.value,n=gL(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...hF(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,tool_output:t.toolOutput,duration:Number(t.durationMs),tool_use_id:t.toolUseId,cwd:t.cwd},s=await this.hookExecutor.executeHookForStep(xd.postToolUse,o);return new d.S1({response:new d.w5({response:{case:"postToolUse",value:new dL.uB({additionalContext:s?.additional_context,updatedMcpToolOutput:void 0===s?.updated_mcp_tool_output?void 0:JSON.stringify(s.updated_mcp_tool_output)})}})})}case"postToolUseFailure":{if(!LN(e))return this.skipToolUseStep();const t=r.request.value,n=gL(t.toolInput),o={conversation_id:t.conversationId??"",generation_id:t.generationId??"",model:t.model??"",...hF(t),...t.parentToolCallId?{parent_tool_call_id:t.parentToolCallId}:{},tool_name:t.toolName,tool_input:n,error_message:t.errorMessage,failure_type:mL(t.failureType),duration:Number(t.durationMs),tool_use_id:t.toolUseId,is_interrupt:t.isInterrupt},s=await this.hookExecutor.executeHookForStep(xd.postToolUseFailure,o);return new d.S1({response:new d.w5({response:{case:"postToolUseFailure",value:new dL.U1({additionalContext:s?.additional_context})}})})}default:return new d.S1({response:void 0})}var n}async skipToolUseStep(){return await this.hookExecutor.whenConfigReady(),new d.S1({response:void 0})}}class yL{constructor(e,t,r,n){this.innerExecutor=e,this.hooksAdditionalContextPromise=t,this.teamHooksReadyPromise=r,this.hooksConfigLease=n}async execute(e,t,r){this.teamHooksReadyPromise&&await this.teamHooksReadyPromise;const n=await this.innerExecutor.execute(e,t,r),o=await this.hooksAdditionalContextPromise,s=this.hooksConfigLease?new Dr.Jy({configuredSteps:Array.from(this.hooksConfigLease.getConfiguredSteps())}):void 0;if("success"===n.result.case&&(o||s)){const e=n.result.value.requestContext,t=e?.clone()??new Dr.bb;return o&&(t.hooksAdditionalContext=o),s&&(t.hooksConfig=s),new Dr._G({result:{case:"success",value:new Dr.yW({requestContext:t,servedFromDiskCache:n.result.value.servedFromDiskCache})}})}return n}}function vL(e){return!!e&&e.type!==os.vc.INSECURE_NONE&&e.type!==os.vc.UNSPECIFIED}async function bL({hookExecutor:e,baseHookRequest:t,toolUseId:r,command:n,cwd:o,sandbox:s}){const i=await e.executeHookForStep(xd.beforeShellExecution,{...t,command:n,cwd:o,sandbox:s,tool_use_id:r});if("deny"===i?.permission){const e=QN("Command execution",i.user_message);throw new JN(e)}if("ask"===i?.permission)return a=i.user_message,new he.In({kind:he.b.FORCE_PROMPT,reason:a});var a}const SL={toolName:CN,getToolCallId:sL,createToolInput:e=>{const t=e.workingDirectory||"";return{command:e.command,cwd:t}},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd)},createRejectedResult:(e,t)=>new Do.Lt({result:{case:"rejected",value:new he.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"BackgroundShell error";case"rejected":return e.result.value.reason||"BackgroundShell rejected";case"permissionDenied":return"Permission denied";case"sandboxUnsupported":return`Sandbox policy unsupported on this host: ${e.result.value.reason}`;default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{shell_id:t.result.value.shellId,pid:t.result.value.pid}:{success:!0},getExtraHookFields:e=>({cwd:e.workingDirectory||""}),runPreExecutionHooks:async e=>{const{ctx:t,args:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e,i=r.workingDirectory||"",a=vL(r.sandboxPolicy);jN(t,xd.beforeShellExecution)&&To(r,await bL({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:a}))}};class kL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,SL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const _L={toolName:"WriteShellStdin",createToolInput:e=>({shell_id:e.shellId,chars_length:e.chars.length}),createRejectedResult:(e,t)=>new Do.nt({result:{case:"error",value:new Do.Gv({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"WriteShellStdin error":"Unknown error",createSuccessOutput:e=>({shell_id:e.shellId,success:!0})};class CL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,_L)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const EL={toolName:"ComputerUse",getToolCallId:sL,createToolInput:e=>({actions_count:e.actions.length}),createRejectedResult:(e,t)=>new Og.ks({result:{case:"error",value:new Og.Jb({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"ComputerUse error":"Unknown error",createSuccessOutput:(e,t)=>"success"===t.result.case?{action_count:t.result.value.actionCount,duration_ms:t.result.value.durationMs}:{success:!0}};class xL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,EL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const PL={toolName:SN,getToolCallId:sL,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new jw.Pi({result:{case:"rejected",value:new jw.iq({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"fileNotFound":return`File not found: ${e.result.value.path}`;case"notFile":return`Not a file: ${e.result.value.path}`;case"permissionDenied":return`Permission denied: ${e.result.value.path}`;case"fileBusy":return`File busy: ${e.result.value.path}`;case"rejected":return e.result.value.reason||"Delete rejected";case"error":return e.result.value.error||"Delete error";default:return"Unknown error"}},createSuccessOutput:e=>({file_path:e.path,deleted:!0})};class RL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,PL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const IL={toolName:EN,getToolCallId:sL,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new DA.Ek({result:{case:"rejected",value:new DA.J6({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"Diagnostics error";case"rejected":return e.result.value.reason||"Diagnostics rejected";case"fileNotFound":return`File not found: ${e.result.value.path}`;case"permissionDenied":return`Permission denied: ${e.result.value.path}`;default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{file_path:e.path,diagnostics_count:t.result.value.totalDiagnostics}:{file_path:e.path,success:!0}};class TL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,IL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const AL={toolName:"Fetch",getToolCallId:sL,createToolInput:e=>({url:e.url}),applyUpdatedInput:(e,t)=>{"string"==typeof t.url&&(e.url=t.url)},createRejectedResult:(e,t)=>new Gw.uN({result:{case:"error",value:new Gw.fk({url:e.url,error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Fetch error":"Unknown error",createSuccessOutput:(e,t)=>"success"===t.result.case?{url:e.url,status_code:t.result.value.statusCode,content_length:t.result.value.content.length}:{url:e.url,success:!0}};class $L{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,AL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const ML={toolName:_N,getToolCallId:sL,createToolInput:e=>({pattern:e.pattern,file_path:e.path,glob:e.glob,output_mode:e.outputMode}),applyUpdatedInput:(e,t)=>{"string"==typeof t.pattern&&(e.pattern=t.pattern),"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Ey.Ud({result:{case:"error",value:new Ey.ts({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Grep error":"Unknown error",createSuccessOutput:e=>({pattern:e.pattern,success:!0})};class DL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,ML)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const OL={toolName:kN,getToolCallId:sL,createToolInput:e=>({file_path:e.path,ignore:e.ignore}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new mC.fv({result:{case:"rejected",value:new mC.k2({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"Ls error";case"rejected":return e.result.value.reason||"Ls rejected";case"timeout":return"Ls operation timed out";default:return"Unknown error"}},getFailureType:e=>"timeout"===e.result.case?"timeout":"error",createSuccessOutput:e=>({file_path:e.path,success:!0})};class FL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,OL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const NL=(0,l.h)("hooks-exec:mcp");function LL(e){return!!(null===e||"string"==typeof e||"boolean"==typeof e||"number"==typeof e&&Number.isFinite(e))||(Array.isArray(e)?e.every(LL):"object"==typeof e&&Object.values(e).every((e=>void 0!==e&&LL(e))))}function jL(e,t,r,n){try{return GN({hookEventName:r,additionalContext:n})}catch(n){if(n instanceof qN)return NL.warn(e,`${r} additional_context exceeded max size; dropping carrier`,{toolName:t,hookEventName:r,actualLength:n.actualLength,maxLength:n.maxLength}),[];throw n}}class UL{constructor(e,t,r,n,o){this.innerExecutor=e,this.hookExecutor=t,this.baseHookRequestExtractor=r,this.mcpLease=n,this.hooksConfigLease=o}async execute(e,t,r){if(t.smartModeApprovalOnly)return this.innerExecutor.execute(e,t,r);if(t.symbolicPathArguments.length>0&&(!0===this.hooksConfigLease?.hasHookForStep(xd.preToolUse)||!0===this.hooksConfigLease?.hasHookForStep(xd.beforeMCPExecution)))return new Ac.iz({result:{case:"error",value:new Ac.Nh({error:`"${nA}" arguments can't be used on this computer: hooks that inspect MCP calls are configured here, and they would not see the file's contents. Read the file and pass its contents instead.`})}});const n=cL(e,this.hookExecutor),o=this.baseHookRequestExtractor(e),s=(0,bo.randomUUID)(),i=r?.hookContextCollector??[];let a=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t?.toJson()])));const c=`MCP:${t.toolName}`;try{const r=await n.executeHookForStep(xd.preToolUse,{...o,tool_name:c,tool_input:a,tool_use_id:s});if("deny"===r?.permission){const t=r.user_message||"MCP tool blocked by preToolUse hook";try{HN(i,GN({hookEventName:xd.preToolUse,additionalContext:r.additional_context}))}catch(t){if(!(t instanceof qN))throw t;NL.warn(e,"preToolUse deny additional_context exceeded max size; dropping carrier",{toolName:c,actualLength:t.actualLength,maxLength:t.maxLength})}return await this.firePostToolUseFailureAsync(e,n,o,c,a,t,"permission_denied",0,s,!1,i),new Ac.iz({result:{case:"permissionDenied",value:new Ac.HQ({error:QN("MCP tool execution",t),isReadonly:!1})}})}if(r?.updated_input)try{for(const[e,n]of Object.entries(r.updated_input))if(void 0!==n){if(!LL(n))throw new TypeError("updated_input value is not JSON");t.args[e]=we.Value.fromJson(n)}a=Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t?.toJson()])))}catch(t){NL.warn(e,"Failed to merge updated_input for MCP",{error:t instanceof Error?t.message:String(t)})}HN(i,GN({hookEventName:xd.preToolUse,additionalContext:r?.additional_context}))}catch(t){const r=n.hasFailClosedHooksForStep?.(xd.preToolUse,c)??!1,l=t instanceof qN;if(r){const r=pN(`${l?"preToolUse additional_context exceeded max size":"preToolUse hook failed"}: ${t instanceof Error?t.message:"preToolUse hook error"}`);return await this.firePostToolUseFailureAsync(e,n,o,c,a,r,"error",0,s,!1,i),new Ac.iz({result:{case:"permissionDenied",value:new Ac.HQ({error:QN("MCP tool execution",r),isReadonly:!1})}})}NL.warn(e,l?"preToolUse additional_context exceeded max size; dropping carrier":"preToolUse hook error in MCP executor",{toolName:c,error:t instanceof Error?t.message:String(t),...l?{actualLength:t.actualLength,maxLength:t.maxLength}:{}})}const l=await(this.mcpLease?.getClient(e,t.providerIdentifier)),u=l?.config;let d;const h=u&&"url"in u&&u.url?u.url:void 0;d=void 0!==h?{url:h}:u&&"command"in u?{command:[u.command,...u.args??[]].filter(Boolean).join(" ")}:{command:t.providerIdentifier};const p={mcp_server_name:t.providerIdentifier,...void 0!==h?{mcp_server_url:h}:{}},f={...o,tool_name:t.toolName,tool_input:JSON.stringify(a),tool_use_id:s,...p,...d},m=jN(e,xd.beforeMCPExecution)?await n.executeHookForStep(xd.beforeMCPExecution,f):void 0;if("deny"===m?.permission){const t=QN("MCP tool execution",m.user_message);return await this.firePostToolUseFailureAsync(e,n,o,c,a,t,"permission_denied",0,s,!1,i),new Ac.iz({result:{case:"permissionDenied",value:new Ac.HQ({error:t,isReadonly:!1})}})}const g=FN.performance.now();try{const l=await this.innerExecutor.execute(e,t,r),u=rL(FN.performance.now()-g);let d="{}";if("success"===l.result.case)try{const e=l.result.value.content.map((e=>"text"===e.content.case?{type:"text",text:e.content.value.text}:"image"===e.content.case?{type:"image",data:Buffer.from(e.content.value.data).toString("base64"),mimeType:e.content.value.mimeType}:{type:"unknown"}));d=JSON.stringify({content:e,isError:l.result.value.isError})}catch(t){NL.warn(e,"Failed to serialize MCP result",{error:t instanceof Error?t.message:String(t)}),d=JSON.stringify({error:"Failed to serialize result"})}else"error"===l.result.case?d=JSON.stringify({error:l.result.value.error}):"rejected"===l.result.case?d=JSON.stringify({rejected:!0,reason:l.result.value.reason}):"permissionDenied"===l.result.case&&(d=JSON.stringify({permissionDenied:!0,error:l.result.value.error}));const h={...o,tool_name:t.toolName,tool_input:JSON.stringify(a),result_json:d,duration:u,tool_use_id:s,...p};await n.executeHookForStep(xd.afterMCPExecution,h);const f=await this.firePostToolUse(e,n,o,c,a,d,u,s,i);if(void 0!==f?.updated_mcp_tool_output)try{const e=f.updated_mcp_tool_output,t=[];if("string"==typeof e)t.push(new Ac._Z({content:{case:"text",value:new Ac.zN({text:e})}}));else if("object"==typeof e&&null!==e&&"content"in e&&Array.isArray(e.content)){const r=e.content;for(const e of r)"object"==typeof e&&null!==e&&"type"in e&&"text"===e.type&&"text"in e?t.push(new Ac._Z({content:{case:"text",value:new Ac.zN({text:String(e.text)})}})):t.push(new Ac._Z({content:{case:"text",value:new Ac.zN({text:JSON.stringify(e)})}}))}else t.push(new Ac._Z({content:{case:"text",value:new Ac.zN({text:JSON.stringify(e)})}}));const r="object"==typeof e&&null!==e&&"isError"in e&&Boolean(e.isError);return new Ac.iz({result:{case:"success",value:new Ac.QW({content:t,isError:r})}})}catch(t){return NL.warn(e,"Failed to process updated_mcp_tool_output",{error:t instanceof Error?t.message:String(t)}),l}return l}catch(t){const r=rL(FN.performance.now()-g),l=t instanceof Error?t.message:String(t);throw await this.firePostToolUseFailureAsync(e,n,o,c,a,l,"error",r,s,!1,i),t}}async firePostToolUse(e,t,r,n,o,s,i,a,c){try{const l=await t.executeHookForStep(xd.postToolUse,{...r,tool_name:n,tool_input:o,tool_output:s,duration:i,tool_use_id:a});return HN(c,jL(e,n,xd.postToolUse,l?.additional_context)),l}catch(t){return void NL.warn(e,"postToolUse hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}async firePostToolUseFailureAsync(e,t,r,n,o,s,i,a,c,l,u){try{const d=await t.executeHookForStep(xd.postToolUseFailure,{...r,tool_name:n,tool_input:o,error_message:s,failure_type:i,duration:a,tool_use_id:c,is_interrupt:l});HN(u,jL(e,n,xd.postToolUseFailure,d?.additional_context))}catch(t){NL.warn(e,"postToolUseFailure hook error in MCP executor",{error:t instanceof Error?t.message:String(t)})}}}const BL={toolName:"ListMcpResources",createToolInput:e=>({server:e.server}),applyUpdatedInput:(e,t)=>{"string"==typeof t.server&&(e.server=t.server)},createRejectedResult:(e,t)=>new Ac.kP({result:{case:"error",value:new Ac.w2({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"ListMcpResources error";case"rejected":return e.result.value.reason||"ListMcpResources rejected";default:return"Unknown error"}},createSuccessOutput:(e,t)=>"success"===t.result.case?{resources_count:t.result.value.resources.length}:{success:!0}};class WL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,BL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const HL={toolName:"FetchMcpResource",createToolInput:e=>({server:e.server,uri:e.uri,download_path:e.downloadPath}),applyUpdatedInput:(e,t)=>{"string"==typeof t.server&&(e.server=t.server),"string"==typeof t.uri&&(e.uri=t.uri),"string"==typeof t.download_path&&(e.downloadPath=t.download_path)},createRejectedResult:(e,t)=>new Ac.ZD({result:{case:"error",value:new Ac.Jx({error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"ReadMcpResource error";case"rejected":return e.result.value.reason||"ReadMcpResource rejected";case"notFound":return"Resource not found";default:return"Unknown error"}},createSuccessOutput:(e,t)=>{if("success"===t.result.case){const r=t.result.value;return{uri:e.uri,name:r.name,mime_type:r.mimeType,download_path:r.downloadPath,content_type:r.content.case,content_length:"text"===r.content.case||"blob"===r.content.case?r.content.value.length:void 0}}return{uri:e.uri,success:!0}}};class qL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,HL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const zL={toolName:vN,getToolCallId:sL,createToolInput:e=>({file_path:e.path}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new Ky.sV({result:{case:"rejected",value:new Ky.f4({path:e.path,reason:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>{switch(e.result.case){case"error":return e.result.value.error||"Read error";case"rejected":return e.result.value.reason||"Read rejected";case"fileNotFound":return`File not found: ${e.result.value.path}`;case"permissionDenied":return`Permission denied: ${e.result.value.path}`;case"invalidFile":return`Invalid file: ${e.result.value.path}`;default:return"Unknown error"}},createSuccessOutput:(e,t)=>{if("success"===t.result.case){const r="content"===t.result.value.output.case?t.result.value.output.value:"";return{file_path:e.path,content_length:r.length}}return{file_path:e.path,success:!0}},runPostExecutionHooks:async e=>{const{args:t,result:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e;if("success"!==r.result.case||!1===o.hasHooksForStep?.(xd.beforeReadFile))return;const i="content"===r.result.value.output.case?r.result.value.output.value:"",a=await async function(e,t){try{return await e()}catch(e){const r=function(e,t){return`${e??"Action"} was blocked because a configured hook failed to execute${t?`: ${t}`:"."}\n\nThis is a safety measure (fail-closed) - when hooks cannot be evaluated, the action is blocked to prevent potentially unsafe operations.\n\n${XN}`}(t,e instanceof Error?e.message:String(e));throw new ZN(r,e)}}((()=>o.executeHookForStep(xd.beforeReadFile,{...n,content:i,file_path:t.path,attachments:[],tool_use_id:s})),"File read");if("deny"===a?.permission){const e=QN("File read",a.user_message);throw new JN(e)}}};class GL{constructor(e,t,r){this.wrappedExecutor=new XT(iL(e,t,r,zL))}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}const VL={toolName:"RecordScreen",getToolCallId:sL,createToolInput:e=>({mode:e.mode,save_as_filename:e.saveAsFilename}),createRejectedResult:(e,t)=>new P$.Tj({result:{case:"failure",value:new P$.yH({error:t,kind:P$.Wg.HOOK_REJECTED})}}),isSuccess:e=>"failure"!==e.result.case,getErrorMessage:e=>"failure"===e.result.case?e.result.value.error||"RecordScreen failed":"Unknown error",createSuccessOutput:(e,t)=>({result_type:t.result.case})};class KL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,VL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}function JL(e){return"success"===e.result.case||"failure"===e.result.case?e.result.value.stdout+e.result.value.stderr:""}const ZL={toolName:CN,createToolInput:e=>{const t=e.workingDirectory||"",r=e.timeout;return{command:e.command,cwd:t,..."number"==typeof r&&r>0&&{timeout:r}}},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd),"number"==typeof t.timeout&&t.timeout>=0&&(e.timeout=t.timeout)},createRejectedResult:(e,t)=>new he.W4({result:{case:"rejected",value:new he.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),isSuccess:e=>"success"===e.result.case||"failure"===e.result.case&&!e.result.value.aborted,getErrorMessage:e=>{switch(e.result.case){case"timeout":return`Command timed out after ${e.result.value.timeoutMs}ms`;case"spawnError":return e.result.value.error||"Failed to spawn command";case"failure":return e.result.value.aborted?"Command was aborted":"Command failed";case"rejected":return e.result.value.reason||"Command rejected";default:return"Unknown error"}},getFailureType:e=>"timeout"===e.result.case?"timeout":"error",isInterrupt:e=>"failure"===e.result.case&&e.result.value.aborted,createSuccessOutput:(e,t)=>({output:JL(t),exitCode:"success"===t.result.case?0:1}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),runPreExecutionHooks:async e=>{const{ctx:t,args:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e,i=r.workingDirectory||"";jN(t,xd.beforeShellExecution)&&To(r,await bL({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:vL(r.requestedSandboxPolicy)}))},runPostExecutionHooks:async e=>{const{args:t,result:r,baseHookRequest:n,hookExecutor:o,executionDurationMs:s,toolUseId:i}=e,a=JL(r);await o.executeHookForStep(xd.afterShellExecution,{...n,command:t.command,output:a,duration:s,sandbox:vL(t.requestedSandboxPolicy),tool_use_id:i})}};class XL{constructor(e,t,r){this.wrappedExecutor=iL(e,t,r,ZL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class QL{constructor(){this.output=""}onEvent(e){"stdout"===e.event.case||"stderr"===e.event.case?this.output+=e.event.value.data:"exit"===e.event.case&&(this.exitEvent=e.event.value)}getOutput(){return this.output}isAborted(){return this.exitEvent?.aborted??!1}getExitCode(){return this.exitEvent?.code??0}}const YL={toolName:CN,createToolInput:e=>{const t=e.workingDirectory||"",r=e.timeout;return{command:e.command,cwd:t,..."number"==typeof r&&r>0&&{timeout:r}}},applyUpdatedInput:(e,t)=>{"string"==typeof t.command&&(e.command=t.command),"string"==typeof t.cwd&&(e.workingDirectory=t.cwd),"number"==typeof t.timeout&&t.timeout>=0&&(e.timeout=t.timeout)},createRejectedEvent:(e,t)=>new he.FI({event:{case:"rejected",value:new he.pZ({command:e.command,workingDirectory:e.workingDirectory,reason:t})}}),createHookContextEvent:e=>new he.FI({event:{case:"hookContext",value:new he.Ng({hookAdditionalContexts:[...e]})}}),getExtraHookFields:e=>({cwd:e.workingDirectory||""}),createResultCollector:()=>new QL,createSuccessOutput:(e,t)=>({output:t.getOutput(),exitCode:t.getExitCode()}),isStreamSuccess:e=>0===e.getExitCode(),getStreamErrorMessage:(e,t)=>t.getOutput().trim()||`Command failed with exit code ${t.getExitCode()}`,runPreExecutionHooks:async e=>{const{ctx:t,args:r,baseHookRequest:n,hookExecutor:o,toolUseId:s}=e,i=r.workingDirectory||"",a=vL(r.requestedSandboxPolicy);jN(t,xd.beforeShellExecution)&&To(r,await bL({hookExecutor:o,baseHookRequest:n,toolUseId:s,command:r.command,cwd:i,sandbox:a}))},runPostExecutionHooks:async e=>{const{args:t,baseHookRequest:r,hookExecutor:n,collector:o,executionDurationMs:s,toolUseId:i}=e,a=vL(t.requestedSandboxPolicy);await n.executeHookForStep(xd.afterShellExecution,{...r,command:t.command,output:o.getOutput(),duration:s,sandbox:a,tool_use_id:i})}};class ej{constructor(e,t,r){this.wrappedExecutor=function(e,t,r,n){return{async*execute(o,s,i){const a=cL(o,t),{hookContext:c,helpers:l}=nL(o,s,a,r,n,i),u=n.runPreExecutionHooks?async e=>{await n.runPreExecutionHooks(e)}:void 0,d=await oL(o,s,a,c,l,n,((e,t)=>n.createRejectedEvent(e,t)),u);if("rejected"===d.type){yield d.result;for(const e of aL(n,c))yield e;return}const h=FN.performance.now(),p=n.createResultCollector();try{for await(const t of e.execute(o,s,i))p.onEvent(t),yield t}catch(e){const t=rL(FN.performance.now()-h),r=e instanceof Error?e.message:String(e);await l.fireFailureAsync(t,r,"error");for(const e of aL(n,c))yield e;throw e}const f=rL(FN.performance.now()-h);if(n.runPostExecutionHooks)try{await n.runPostExecutionHooks({ctx:o,args:s,baseHookRequest:c.baseHookRequest,hookExecutor:a,toolInput:l.getToolInput(),toolUseId:c.toolUseId,extraHookFields:c.extraHookFields,collector:p,executionDurationMs:f})}catch(e){eL.warn(o,"postExecutionHooks error",{toolName:n.toolName,error:e instanceof Error?e.message:String(e)})}if(p.isAborted())await l.fireFailureAsync(f,"Command was aborted","error",!0);else if(n.isStreamSuccess?.(p)??1)await l.fireSuccessAsync(f,JSON.stringify(n.createSuccessOutput(s,p)));else{const e=n.getStreamErrorMessage?.(s,p)??`Command failed with exit code ${p.getExitCode()}`;await l.fireFailureAsync(f,e,"error")}for(const e of aL(n,c))yield e}}}(e,t,r,YL)}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}class tj{constructor(e,t,r){const n=new Map;this.wrappedExecutor=iL(e,t,r,function(e){return{toolName:bN,getToolCallId:sL,createToolInput:e=>({file_path:e.path,content:e.fileText}),applyUpdatedInput:(e,t)=>{"string"==typeof t.file_path&&(e.path=t.file_path)},createRejectedResult:(e,t)=>new MI.v3({result:{case:"error",value:new MI.QM({path:e.path,error:t})}}),isSuccess:e=>"success"===e.result.case,getErrorMessage:e=>"error"===e.result.case?e.result.value.error||"Write error":"Unknown error",createSuccessOutput:e=>({file_path:e.path,success:!0}),runPreExecutionHooks:async t=>{const{args:r,hookExecutor:n,toolUseId:o}=t;if(!1===n.hasHooksForStep?.(xd.afterFileEdit))return;let s,i=!1;try{(await(0,Co.stat)(r.path)).size>262144?i=!0:s=await ji(r.path)}catch(e){}e.set(o,{contentBeforeWrite:s,fileTooLarge:i})},runCleanup:t=>{e.delete(t)},runPostExecutionHooks:async t=>{const{args:r,result:n,baseHookRequest:o,hookExecutor:s,toolUseId:i}=t,a=e.get(i);if("success"!==n.result.case||!1===s.hasHooksForStep?.(xd.afterFileEdit))return;const{contentBeforeWrite:c,fileTooLarge:l}=a??{fileTooLarge:!1};let u;u=l||void 0===c?[{old_string:"",new_string:r.fileText}]:c===r.fileText?[]:function(e,t){const r=(0,cS.YB)("","",e,t,"","",{context:0,timeout:50});return void 0===r?[{old_string:"",new_string:t}]:0===r.hunks.length?[]:r.hunks.map((e=>{const t=[],r=[];for(const n of e.lines)n.startsWith("-")?t.push(n.slice(1)):n.startsWith("+")&&r.push(n.slice(1));return{old_string:t.join("\n"),new_string:r.join("\n")}}))}(c,r.fileText);const d={...o,file_path:r.path,edits:u},h=await s.executeHookForStep(xd.afterFileEdit,d);if(r.returnFileContentAfterWrite&&void 0!==h){const e=n.result.value.path;try{const t=await ji(e),r=Js(t),o=Buffer.byteLength(t,"utf8");return new MI.v3({result:{case:"success",value:new MI.j6({path:n.result.value.path,linesCreated:r,fileSize:o,fileContentAfterWrite:t})}})}catch(e){return}}}}}(n))}execute(e,t,r){return this.wrappedExecutor.execute(e,t,r)}}function rj(e,t,r){return t===e.symbol}function nj(e,t,r){return rj(jT,e)?new XL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(ee,e)?new ej(t,r.hookExecutor,r.baseHookRequestExtractor):rj(HT,e)?new tj(t,r.hookExecutor,r.baseHookRequestExtractor):rj(eo,e)?new UL(t,r.hookExecutor,r.baseHookRequestExtractor,r.mcpLease,r.hooksConfigLease):rj(QT,e)||rj(YT,e)?new GL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(eA,e)?new FL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(VT,e)?new DL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(zT,e)?new $L(t,r.hookExecutor,r.baseHookRequestExtractor):rj(qT,e)?new RL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(tA,e)?new TL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(to,e)?new WL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(ro,e)?new qL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(vA,e)?new kL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(bA,e)?new CL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(xA,e)?new xL(t,r.hookExecutor,r.baseHookRequestExtractor):rj(RA,e)?new KL(t,r.hookExecutor,r.baseHookRequestExtractor):rj($r,e)&&(r.hooksAdditionalContextPromise||r.hooksConfigLease)?new yL(t,r.hooksAdditionalContextPromise??Promise.resolve(void 0),r.teamHooksReadyPromise,r.hooksConfigLease):void 0}class oj{constructor(e,t,r,n,o,s,i){this.innerAccessor=e,this.hookExecutor=t,this.baseHookRequestExtractor=r,this.mcpLease=n,this.hooksAdditionalContextPromise=o,this.teamHooksReadyPromise=s,this.hooksConfigLease=i}get(e){const t=function(e,t){if(e.symbol===hL.symbol)return new wL(t)}(e,this.hookExecutor);return void 0!==t?t:function(e,t,r){const n=nj(e.symbol,t,r);return void 0!==n?n:t}(e,this.innerAccessor.get(e),{hookExecutor:this.hookExecutor,baseHookRequestExtractor:this.baseHookRequestExtractor,mcpLease:this.mcpLease,hooksAdditionalContextPromise:this.hooksAdditionalContextPromise,teamHooksReadyPromise:this.teamHooksReadyPromise,hooksConfigLease:this.hooksConfigLease})}*entries(){for(const[e,t]of this.innerAccessor.entries()){const r=nj(e.symbol,t,{hookExecutor:this.hookExecutor,baseHookRequestExtractor:this.baseHookRequestExtractor,mcpLease:this.mcpLease,hooksAdditionalContextPromise:this.hooksAdditionalContextPromise,teamHooksReadyPromise:this.teamHooksReadyPromise,hooksConfigLease:this.hooksConfigLease});yield[e,r??t]}const e=hL;yield[e,new wL(this.hookExecutor)]}}const sj={cursor_version:process.env.AGENT_CLI_STATIC_VERSION??"1.0.0",user_email:null};function ij(e=process.cwd()){let t=e;const r={getCwd:async()=>t,clone:e=>ij(e??t),async*execute(e,r,n={}){const o=n.workingDirectory??t;t=o;const s=function(e){return"win32"===process.platform?{executable:(0,Oo.oG)(),args:[...XO,"-Command",e]}:{executable:process.env.SHELL||"/bin/sh",args:["-lc",e]}}(r),i=(0,ou.spawn)(s.executable,[...s.args],{cwd:o,env:{...process.env,...n.env??{}},signal:n.signal,stdio:[!0===n.pipeStdin?"pipe":"ignore","pipe","pipe"]}),a=[];let c,l,u=!1;const d=()=>{c?.(),c=void 0},h=e=>{a.push(e),d()};for(i.on("spawn",(()=>{!0===n.pipeStdin&&h({type:"stdin_ready",stdin:i.stdin??void 0})})),i.stdout?.setEncoding("utf8"),i.stdout?.on("data",(e=>{h({type:"stdout",data:String(e)})})),i.stderr?.setEncoding("utf8"),i.stderr?.on("data",(e=>{h({type:"stderr",data:String(e)})})),i.on("error",(e=>{l=e,u=!0,d()})),i.on("close",(e=>{h({type:"exit",code:e}),u=!0}));!u||a.length>0;)0!==a.length?yield a.shift():await new Promise((e=>{c=e}));if(void 0!==l)throw l}};return r}function aj(e,t,...r){for(const n of r){const r=t(e[n]);if(void 0!==r)return r}}function cj(e){return"string"==typeof e&&e.length>0?e:void 0}function lj(e){return"object"==typeof e&&null!==e&&"string"==typeof e.id&&"string"==typeof e.value}function uj(e){if(Array.isArray(e)&&e.every(lj))return e.map((e=>({id:e.id,value:e.value})))}class dj{constructor(e,t){this.innerAccessor=e,this.sessionHooksRuntime=t}get(e){return this.innerAccessor.get(e)}entries(){return this.innerAccessor.entries()}async dispose(){await this.sessionHooksRuntime.dispose()}}async function hj(e,t={}){const r=await new yN(new uL,function(e,t){const r=e.projectRoot??e.workingDirectory??e.workspaceRoots[0],n=t.includeProjectHooks??!0,i=t.includeUserHooks??!0;return{enterpriseConfigPath:t.includeEnterpriseHooks??1?mN():void 0,userConfigPath:i?(0,s.join)((0,o.homedir)(),".cursor","hooks.json"):void 0,claudeUserConfigPath:i?(0,s.join)((0,o.homedir)(),".claude","settings.json"):void 0,projectConfigPath:n&&void 0!==r?(0,s.join)(r,".cursor","hooks.json"):void 0,claudeProjectConfigPath:n&&void 0!==r?(0,s.join)(r,".claude","settings.json"):void 0,claudeProjectLocalConfigPath:n&&void 0!==r?(0,s.join)(r,".claude","settings.local.json"):void 0}}(e,t)).load(),n=new ON(r),i=function(e){return e.projectRoot??e.workingDirectory??e.workspaceRoots[0]??process.cwd()}(e),a=function(e){return Object.freeze({...sj,...e.globalContext??{}})}(t);return{projectDir:e.projectRoot,workspacePath:i,hooksConfig:r,hooksConfigLease:n,globalContext:a,createSessionRuntime(){const e=new DN(r,i,a,(t.createTerminalExecutor??ij)(),t.promptHookClient,void 0,void 0,{enableClaudeNestedHookSpecificOutputCompatibility:!0,commandHookPayloadTransport:(o=t.useCommandHookStdinTransport,!0===o?"stdin":"legacy")});var o;return{hookExecutor:e,hooksConfigLease:n,async dispose(){e.clearSessionEnvironment()}}},async dispose(){}}}function pj(e={}){return{createHooksRuntime:t=>hj(t.workspaceState,e)}}var fj=r("../proto/dist/generated/aiserver/v1/dashboard_service_connect.js");async function mj(e){(function(e){return"object"==typeof e&&null!==e&&"dispose"in e&&"function"==typeof e.dispose})(e)&&await e.dispose()}function gj(e={}){const t=e.getThirdPartyExtensibilityEnabled??(()=>!0),r=e.importThirdPartyPlugins??!1,n=e.includeProjectExtensibility??!0,s=e.includeUserExtensibility??!0,i=e.includeManagedSkills??!0,a=e.includePluginExtensibility??!0,c=new _y,l=(0,o.homedir)(),u=ym(l).dirPath;let d,h=!0;return{async prepareLocalExtensibility(){h=i&&await async function(e){if(!e)return!1;const t=(0,ye.createClient)(fj.I,e);return"synced"===(await async function(e,t){try{const r=await t.getManagedSkills()??[],n=await $D(e,{managedSkills:[...r]});return{status:"synced",managedSkillsCount:r.length,syncResult:n}}catch(t){return DD.warn(e,"Failed to sync managed skills from source",{error:t}),{status:"fetch_failed",error:t}}}((0,y.q6)(),{getManagedSkills:async()=>(await t.getManagedSkills(new JD.X8g({}))).skills??[]})).status}(e.dashboardTransport)},async loadLocalExtensibility(o){const i=function(e){if(e.workspaceRoots.length>0)return[...e.workspaceRoots];const t=e.projectRoot??e.workingDirectory;return void 0!==t?[t]:[]}(o.workspaceState);if(0===i.length)return d=void 0,{cursorRulesService:_j(),getAgentSkills:async e=>[]};const p=(0,y.q6)(),f=e.loadNestedRules??!0,m=n?i.map((e=>new fg(p,c,e,f,t,void 0))):[],g=function(e,t){const r=wj(t);return{getAllCursorRules:async t=>yj(await e.getAllCursorRules(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),dispose(){e.dispose()}}}(0===m.length?_j():1===m.length?m[0]:new pg(m,(()=>Fm)),{allowedRoots:n?i:[],excludedRoots:[]}),w=function(e,t){const r=wj(t);return{getAllCursorRules:async t=>yj(await e.getAllCursorRules(t),r),getAllAgentSkills:async t=>yj(await e.getAllAgentSkills(t),r),reload(t){e.reload(t)},onDidChangeRules:t=>e.onDidChangeRules(t),onDidChangeSkills:t=>e.onDidChangeSkills(t),dispose(){e.dispose()}}}(new gg(p,n?i:[],l,c,f,void 0,t,Promise.resolve(),"sdk"),{allowedRoots:[...n?i:[],...s?[l]:[],...h?[u]:[]],excludedRoots:h?[]:[u]}),v=n?i.map((e=>new Pg(e,t))):[],b=0===v.length?new Sg:1===v.length?v[0]:new Ig(v),S=WO(o.services.pluginBootstrapOutputs),k=S&&a?new yg(p,(()=>({importThirdPartyPlugins:r})),void 0,S.pluginsService):void 0,_=S&&a?new Tg((()=>({importThirdPartyPlugins:r})),S.pluginsService):void 0,C=new pg([g,w,...k?[k]:[]],(()=>Fm)),E=new pD([w,...k?[k]:[]],(()=>[]),(()=>({workspacePaths:n?i:[],userHomeDirectory:l,agentStoreSkillsDirs:[]}))),x=new Ig([b,..._?[_]:[]]);d={localRulesService:g,localSkillsService:w,localSubagentsService:b,pluginSkillsService:k,pluginSubagentsService:_,mergedCursorRulesService:C,mergedAgentSkillsService:E,mergedSubagentsService:x};const P={cursorRulesService:C,getAgentSkills:e=>E.getAllAgentSkills(e),subagentsService:x};return P},async disposeLocalExtensibility(){if(!d)return;const e=d;d=void 0,await async function(e){let t;const r=[e.mergedSubagentsService,e.mergedAgentSkillsService,e.mergedCursorRulesService,e.pluginSubagentsService,e.pluginSkillsService,e.localSubagentsService,e.localSkillsService,e.localRulesService];for(const e of r)try{await mj(e)}catch(e){t??=e}if(void 0!==t)throw t}(e)}}}function wj(e){const t=Promise.all(e.allowedRoots.map(Sj)),r=Promise.all(e.excludedRoots.map(Sj));return async e=>{const[n,o,s]=await Promise.all([kj(e.fullPath),t,r]);return void 0!==n&&!s.some((e=>vj(n,e)))&&o.some((e=>vj(n,e)))}}async function yj(e,t){const r=await Promise.all(e.map(t));return e.filter(((e,t)=>r[t]))}function vj(e,t){if(e===t)return!0;const r=`${t}/`;return e.startsWith(r)}function bj(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")}async function Sj(e){try{return bj(await(0,Co.realpath)(e))}catch{return bj(e)}}async function kj(e){try{return bj(await(0,Co.realpath)(e))}catch{return}}function _j(){return{getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}}}function Cj(e,t){const r=e.releaseTag??t;if(e.releaseRepo&&e.releaseAsset&&r)return{kind:"release",releaseRepo:e.releaseRepo,releaseAsset:e.releaseAsset,releaseTag:r}}const Ej=/^[a-z][a-z0-9+.-]*:\/\/([^/?#]*)/i,xj=/^(?:[^@/\s]+@)?([^:/\s\\]+):(?!\/\/)/,Pj=/^([a-z][a-z0-9+.-]*)::(.*)$/i,Rj=/^([a-z][a-z0-9+.-]*):\/\//i,Ij=new Set(["file","git","http","https","ssh"]);function Tj(e){if(/^(?:\\\\|\/\/)[^\\/]/.test(e))throw new Error("Cursor Orbit: plugin git remote could not be validated");const t=Pj.exec(e);if(null!==t){const e=t[1].toLowerCase();if(!Ij.has(e))throw new Error("Cursor Orbit: plugin git remote could not be validated");const r=t[2];if(!("http"!==e&&"https"!==e||null!==Rj.exec(r)&&URL.canParse(r)))throw new Error("Cursor Orbit: plugin git remote could not be validated");const n=Tj(r);if(0===n.length)throw new Error("Cursor Orbit: plugin git remote could not be validated");return n}const r=Rj.exec(e)?.[1].toLowerCase();if(void 0!==r&&!Ij.has(r))throw new Error("Cursor Orbit: plugin git remote could not be validated");const n=Ej.exec(e)?.[1];if(void 0===n){const t=xj.exec(e)?.[1];if(void 0===t)return[];const r=function(e){const t=/^\[([^\]]+)\]$/.exec(e)?.[1],r=t??e;if(""!==r&&!/[\[\]\s@%\/\\]/.test(r))return Aj(r)}(t);if(void 0===r)throw new Error("Cursor Orbit: plugin git remote could not be validated");return[r]}const o=[];URL.canParse(e)&&o.push(Aj(new URL(e).hostname));const s=function(e){try{return decodeURIComponent(e)}catch{return e}}(n.slice(n.lastIndexOf("@")+1)),i=`https://${s}`;if(URL.canParse(i))o.push(Aj(new URL(i).hostname));else{const e=/^\[([^\]]+)\](?::\d*)?$/.exec(s)?.[1];if(void 0===e)throw new Error("Cursor Orbit: plugin git remote could not be validated");o.push(Aj(e))}const a=o.filter((e=>""!==e));if(0===a.length)throw new Error("Cursor Orbit: plugin git remote could not be validated");return[...new Set(a)]}function Aj(e){return e.trim().toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,"")}function $j(){const e=["-c","credential.interactive=false","-c","core.fsmonitor=false"];return"1"===process.env[Zv.K4]&&e.push("-c","http.followRedirects=false"),"win32"===process.platform&&e.push("-c","core.longpaths=true"),e}function Mj(e){return"function"==typeof e?e():e}async function Dj(e,t){const r=function(e){const t={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:void 0,VSCODE_GIT_ASKPASS_NODE:void 0,VSCODE_GIT_ASKPASS_MAIN:void 0,VSCODE_GIT_ASKPASS_EXTRA_ARGS:void 0,GCM_INTERACTIVE:"Never"};if(t.GIT_CONFIG_NOSYSTEM=void 0,!0===e?.sshBatchMode){const e=process.env.GIT_SSH_COMMAND?.trim()||"ssh";t.GIT_SSH_COMMAND=`${e} -oBatchMode=yes`}if(void 0!==e?.extraGitConfig){const r=Object.entries(e.extraGitConfig).flatMap((([e,t])=>Array.isArray(t)?t.map((t=>[e,t])):[[e,t]]));t.GIT_CONFIG_COUNT=String(r.length);for(const[e,[n,o]]of r.entries())t[`GIT_CONFIG_KEY_${e}`]=n,t[`GIT_CONFIG_VALUE_${e}`]=o}return{cwd:e?.cwd,env:t}}({cwd:t?.cwd,sshBatchMode:t?.sshBatchMode,extraGitConfig:t?.extraGitConfig}),n=function(e){return function(e,t=process.env){if("1"!==t[Zv.K4])return;const r=(0,Zv.H)(t[Zv.Zf]);for(const t of e)for(const e of Tj(t))if((0,Zv.ad)(e,r))throw new Error(`Cursor Orbit: plugin git egress to ${e} is refused`)}(e),[...$j(),...e]}(e);try{return await ay("git",n,{...r,...void 0!==t?.timeoutMs&&{timeout:t.timeoutMs,killSignal:"SIGTERM"}})}catch(e){if("1"===process.env[Zv.K4]&&function(e){if("object"!=typeof e||null===e||!("stderr"in e))return!1;const t=e.stderr;return"string"==typeof t&&/The requested URL returned error: 3\d{2}\b/i.test(t)}(e))throw new Error("Cursor Orbit: the plugin gitUrl redirected. Ask an administrator to update gitUrl to the final URL; redirects are disabled for plugin Git operations.",{cause:e});throw e}}const Oj=/^[0-9a-f]{7,40}$/i,Fj=/^[0-9a-f]{40}$/i;function Nj(e){if(void 0===e||""===e)return;const t=e.split(/\r?\n/).map((e=>{const[t,r]=e.split("\t");if(t&&r&&/^[0-9a-f]{40}$/i.test(t))return{sha:t,refName:r}})).filter((e=>void 0!==e)),r=t[0];return void 0!==r?t.find((e=>e.refName.endsWith("^{}")))?.sha??r.sha:void 0}async function Lj(e,t,r){const n=t.trim();if(Fj.test(n))return{fullSha:n.toLowerCase()};if(Oj.test(n)){try{const t=await async function(e,t,r){const{stdout:n}=await Dj(["ls-remote",e,`refs/heads/${t}`,`refs/tags/${t}`,`refs/tags/${t}^{}`],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs});return Nj(n)?.toLowerCase()}(e,n,r);if(t)return{fullSha:t}}catch{}return{fullSha:n.toLowerCase()}}let o;try{if("HEAD"===n.toUpperCase()){const t=await Dj(["ls-remote","--symref",e,"HEAD"],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs}),n=Nj(t.stdout);if(!n)throw new Error(`git ls-remote did not return a resolvable commit for HEAD (${e})`);return{fullSha:n.toLowerCase(),headSymrefStdout:t.stdout}}o=(await Dj(["ls-remote",e,n],{sshBatchMode:r?.sshBatchMode,extraGitConfig:r?.extraGitConfig,timeoutMs:r?.timeoutMs})).stdout}catch(t){const r=t instanceof Error?t.message:String(t),o=new Error(`Failed to resolve git ref "${n}" for ${e}: ${r}`);throw o.cause=t,o}const s=Nj(o);if(!s)throw new Error(`git ls-remote did not return a resolvable commit for ref "${n}" (${e})`);return{fullSha:s.toLowerCase()}}const jj=zh.map((function(e){const t=e.split("/")[0];if(void 0===t||0===t.length)throw new Error(`Marketplace manifest path has no directory: ${e}`);return t}));let Uj;function Bj(e){let t=e.trim().replaceAll("\\","/");for(;t.startsWith("./");)t=t.slice(2);return t=t.replace(/\/+$/,""),""===t||"."===t||t.startsWith("/")||/^[a-zA-Z]:/.test(t)||t.split("/").some((e=>""===e||"."===e||".."===e))?null:t}function Wj(e){const t=[];for(const r of e){const e=Bj(r);if(null===e)return"all";t.push(e)}return t}async function Hj(e,t){const r="all"===e?"all":Wj(e),n=t&&"all"!==r&&await(process.env.CURSOR_DISABLE_SPARSE_PLUGIN_CLONES?Promise.resolve(!1):(Uj??=(async()=>{try{const{stdout:e}=await Dj(["--version"]),t=function(e){const t=/git version (\d+)\.(\d+)/.exec(e);return t?{major:Number(t[1]),minor:Number(t[2])}:null}(e);return null!==t&&(t.major>2||2===t.major&&t.minor>=28)}catch{return!1}})(),Uj));return{materialize:r,sparse:n,sparseDirs:n?(o=r,[...new Set([...jj,...o])]):[]};var o}function qj(e){return e.toLowerCase().includes("filtering not recognized by server")}async function zj(e,t,r){await Dj(["sparse-checkout","set","--cone","--",...t],{...r,cwd:e})}async function Gj(e){try{await(0,Co.access)((0,s.join)(e,".git","info","sparse-checkout"))}catch{return!1}try{const{stdout:t}=await Dj(["config","--bool","--get","core.sparseCheckout"],{cwd:e});return"true"===t.trim()}catch{return!1}}async function Vj(e,t,r){if("all"!==t&&0===t.length)return;if(!await Gj(e))return;const n={...r,cwd:e,sshBatchMode:!0};if("all"===t)return void await Dj(["sparse-checkout","disable"],n);const o=Wj(t);"all"!==o?await Dj(["sparse-checkout","add","--",...o],n):await Dj(["sparse-checkout","disable"],n)}(0,_s.J)((function(){Uj=void 0}));const Kj=/\.git$/i,Jj=new Set(["account","dashboard"]);function Zj(e){return e.replace(Kj,"")}function Xj(e){let t;try{t=decodeURIComponent(e)}catch{return}return t.length>0&&!t.includes("/")?t:void 0}function Qj(e){const t=e.toLowerCase();return"github.com"===t||t.endsWith(".github.com")}function Yj(e){return e.toLowerCase().split(".").includes("gitlab")}function eU(e){const t=e.toLowerCase();return"bitbucket.org"===t||"www.bitbucket.org"===t}function tU(e){const t=e.toLowerCase();return Yj(e)?"GitLab":t.includes("bitbucket")?"Bitbucket":t.includes("gitea")||t.includes("codeberg")?"Gitea/Codeberg":t.includes("azure")&&t.includes("dev")?"Azure DevOps":null}function rU(e){return Qj(e)?"github":Yj(e)?"gitlab":eU(e)?"bitbucket":function(e){const t=e.toLowerCase();return"dev.azure.com"===t||"www.dev.azure.com"===t}(e)?"azure_devops":"generic"}function nU(e){let t;try{const r=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;t=new URL(r.includes("://")?r:`https://${r}`)}catch{return null}const r=t.hostname;let n=t.pathname.split("/").filter(Boolean);Ga(r)&&"git"===n[0]?.toLowerCase()&&(n=n.slice(1));const o=n[0];void 0!==o&&n.length>=3&&"scm"===o.toLowerCase()&&(n=n.slice(1));const s=function(e){const t=e[0],r=e[1];if(!t||!r)return;const n=Zj(r);return n?{owner:t,repo:n,hasSubpath:e.length>2}:void 0}(n);return void 0===s?null:{provider:rU(r),owner:s.owner,repo:s.repo,host:r}}function oU(e){const t=sU(e);if(null===t)return!1;const r=t.pathname.split("/").filter(Boolean),n=r[0];return void 0!==n&&r.length>=3&&"scm"===n.toLowerCase()}function sU(e){try{const t=e.startsWith("git@")?`ssh://${e.replace(":","/")}`:e;return new URL(t.includes("://")?t:`https://${t}`)}catch{return null}}function iU(e){const t=e.trim();if(""===t)return{error:"URL cannot be empty"};const r=nU(t);if(null===r)return{error:"Invalid URL format. Expected: github.com/owner/repo or gitlab.com/namespace/repo"};if(Yj(r.host)){const e=sU(t),r=null===e?void 0:function(e){const t=e.indexOf("-"),r=-1!==t,n=r?e.slice(0,t):[...e];if(n.length<2||n.some((e=>0===e.length)))return;const o=Zj(n[n.length-1]);return o?(n[n.length-1]=o,{repositorySegments:n,hasSpecialRouteSeparator:r}):void 0}(e.pathname.split("/").filter(Boolean));if(null===e||void 0===r)return{error:"Invalid GitLab repository URL format. Expected: https://gitlab.com/namespace/repo"};const n=e.host.replace(/^www\./i,""),o=r.repositorySegments[0],s=r.repositorySegments[r.repositorySegments.length-1];return void 0===o||void 0===s?{error:"Invalid GitLab repository URL format. Expected: https://gitlab.com/namespace/repo"}:{url:`https://${n}/${r.repositorySegments.join("/")}`,owner:o,repo:s,host:n,provider:"gitlab"}}if("bitbucket"===r.provider){const e=function(e){const t=sU(e.trim());if(null!==t&&eU(t.hostname))return function(e){const t=e[0],r=e[1];if(void 0===t||void 0===r)return;const n=Xj(t),o=Xj(r);if(void 0===n||void 0===o||Jj.has(n.toLowerCase()))return;const s=Zj(o);return s?{workspace:encodeURIComponent(n),repo:encodeURIComponent(s),hasSubpath:e.length>2}:void 0}(function(e){const t=e.pathname.split("/");return""===t[0]&&t.shift(),""===t[t.length-1]&&t.pop(),t}(t))}(t);if(void 0===e)return{error:"Invalid Bitbucket repository URL format. Expected: https://bitbucket.org/{workspace}/{repo}"};const n=r.host.replace(/^www\./i,"");return{url:`https://${n}/${e.workspace}/${e.repo}`,owner:e.workspace,repo:e.repo,host:n,provider:"bitbucket"}}if("azure_devops"===r.provider){const e=sU(t),n=null===e?void 0:function(e){const t=e.findIndex((e=>"_git"===e.toLowerCase()));if(t<1||t>2)return;const r=e[0],n=e[t+1];if(!r||!n)return;const o=Zj(n);if(!o)return;const s=2===t?e[1]:o;return s?{organization:r,project:s,repo:o,hasSubpath:e.length>t+2}:void 0}(e.pathname.split("/").filter(Boolean));if(null===e||void 0===n)return{error:"Invalid Azure DevOps repository URL format. Expected: https://dev.azure.com/{organization}/{project}/_git/{repo}"};const o=r.host.replace(/^www\./i,"");return{url:`https://${o}/${n.organization}/${n.project}/_git/${n.repo}`,owner:n.organization,repo:n.repo,host:o,provider:"azure_devops",project:n.project}}if(function(e){switch(e.provider){case"github":return!0;case"generic":return!Ga(e.host)&&null===tU(e.host);case"gitlab":case"bitbucket":case"azure_devops":return!1;default:return e.provider,!1}}(r)){const e=cU(r.host.replace(/^www\./i,""));return{url:`https://${e}/${oU(t)?"scm/":""}${r.owner}/${r.repo}`,owner:r.owner,repo:r.repo,host:e,provider:"github"}}const n=tU(r.host);return{error:"Only GitHub, GitLab, Bitbucket, and Azure DevOps URLs are currently supported."+(null!==n?` ${n} is not supported yet.`:"")}}function aU(e){const t=iU(e);if("error"in t)return null;switch(t.provider){case"github":return`git@${t.host}:${t.owner}/${t.repo}.git`;case"gitlab":return function(e){let t;try{t=new URL(e.url).pathname.replace(/^\//,"").replace(/\.git$/i,"")}catch{return null}if(0===t.length)return null;return`git@${e.host.replace(/:\d+$/,"")}:${t}.git`}(t);case"bitbucket":case"azure_devops":return null;default:return t.provider,null}}function cU(e){return Qj(e)?"github.com":e}function lU(e){return!e.operatingSystems||0===e.operatingSystems.length||e.operatingSystems.includes(function(){const e=(0,o.platform)();return"win32"===e?"Windows":"darwin"===e?"Macintosh":"Linux"}())}function uU(e){return/[\n\r:#[\]{}&*!|>'"%@`]/.test(e)||e.startsWith(" ")||e.endsWith(" ")?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:e}const dU=new Set(["con","prn","aux","nul","com1","com2","com3","com4","com5","com6","com7","com8","com9","lpt1","lpt2","lpt3","lpt4","lpt5","lpt6","lpt7","lpt8","lpt9"]);function hU(e){const t=oh(e).replace(/[. ]+$/g,"");return""===t||"."===t||".."===t?"_":dU.has(t.toLowerCase())?`_${t}`:t}const pU=18e5,fU=6e5,mU={recursive:!0,force:!0,maxRetries:3},gU=["terminal prompts disabled","could not read username","host key verification failed","could not read from remote repository","permission denied","repository not found","user cancelled dialog","spawn git enoent","authentication failed","unable to get password from user","you do not have access to"],wU=["enotempty: directory not empty, rename","/_staging/"],yU=["upload-pack: not our ref","server does not allow request for unadvertised object"];function vU(e){const t=String(e).toLowerCase().replaceAll("\\","/");return gU.some((e=>t.includes(e)))?"user_git_access":wU.every((e=>t.includes(e)))?"local_cache_race":yU.some((e=>t.includes(e)))?"stale_pinned_ref":"infrastructure"}function bU(e){return"object"==typeof e&&null!==e&&(!0===e.killed||bU(e.cause))}function SU(e){return bU(e)?"killed_by_budget":vU(e)}function kU(e){const t=iU(e);if(!("error"in t)&&"gitlab"===t.provider){let r;try{r=new URL(t.url).pathname.replace(/^\//,"")}catch{throw new Error(`Invalid git URL: ${e}`)}const n=r.split("/").filter(Boolean).map((e=>e.toLowerCase()));if(n.length<2)throw new Error(`Invalid git URL: ${e}`);return{host:t.host.toLowerCase(),pathSegments:n}}const r=nU(e);if(null===r)throw new Error(`Invalid git URL: ${e}`);return{host:cU(r.host.replace(/^www\./i,"")).toLowerCase(),pathSegments:[r.owner.toLowerCase(),r.repo.toLowerCase()]}}const _U=new Map;class CU{constructor(e,t){this.cacheRoot=e,this.options=t,this.manifestCache=new Map}get sparsePluginClones(){return this.options?.sparsePluginClones??!1}remoteTimeoutMs(){return this.sparsePluginClones?pU:void 0}localTimeoutMs(){return this.sparsePluginClones?fU:void 0}lsRemoteTimeoutMs(){return this.sparsePluginClones?3e4:void 0}async cloneResolvedRef(e,t,r,n){const o={cwd:e,sshBatchMode:n?.sshBatchMode,extraGitConfig:{...Mj(this.options?.extraGitConfig),"safe.directory":e}},{sparse:s,sparseDirs:i}=await Hj(n?.materialize??"all",this.sparsePluginClones);await Dj(["init"],{...o,timeoutMs:this.localTimeoutMs()}),s&&await zj(e,i,{sshBatchMode:n?.sshBatchMode,extraGitConfig:Mj(this.options?.extraGitConfig),timeoutMs:this.localTimeoutMs()});const{stderr:a}=await Dj(["fetch","--depth","1",...s?["--filter=blob:none"]:[],t,r],{...o,timeoutMs:this.remoteTimeoutMs()});return await Dj(["checkout","FETCH_HEAD"],{...o,timeoutMs:this.remoteTimeoutMs()}),{strategy:s?"sparse":"full",filterIgnoredByServer:s&&qj(a??"")}}async createStagingDir(){const e=(0,s.join)(this.cacheRoot,"_staging",(0,bo.randomUUID)());return await(0,Co.mkdir)(e,{recursive:!0}),e}async moveToCanonicalDir(e,t){return await(0,Co.mkdir)((0,s.dirname)(t),{recursive:!0}),await(0,Co.rm)(t,mU),await(0,Co.rename)(e,t),t}async cleanStaleStagingDirs(){const e=(0,s.join)(this.cacheRoot,"_staging");try{const t=await(0,Co.readdir)(e,{withFileTypes:!0}),r=Date.now();await Promise.all(t.filter((e=>e.isDirectory())).map((async t=>{try{const n=(0,s.join)(e,t.name),o=await(0,Co.stat)(n);r-o.mtimeMs>CU.STALE_STAGING_THRESHOLD_MS&&await(0,Co.rm)(n,mU)}catch{}})))}catch{}}getLegacyCloneDir(e,t){return(0,s.join)(this.cacheRoot,hU(e),hU(t))}getCanonicalCloneDir(e,t){const{host:r,pathSegments:n}=kU(e);return(0,s.join)(this.cacheRoot,hU(r),...n.map(hU),hU(t))}getCanonicalRepoRootDir(e){const{host:t,pathSegments:r}=kU(e);return(0,s.join)(this.cacheRoot,hU(t),...r.map(hU))}async pruneSiblingCloneDirs(e,t,r){const n=this.getCanonicalRepoRootDir(e),o=hU(t);try{const e=await(0,Co.readdir)(n,{withFileTypes:!0});await Promise.all(e.filter((e=>e.isDirectory()&&e.name!==o)).map((e=>(0,Co.rm)((0,s.join)(n,e.name),mU))))}catch{}if(void 0!==r)try{await(0,Co.rm)(r,mU)}catch{}}async ensureCloned(e,t,r,n=Tp,o){const s=this.serializedOnRepo(this.getCanonicalRepoRootDir(t),(()=>this.ensureClonedImpl(e,t,r,n,o?.materialize??"all")));return this.sparsePluginClones?s:(0,Or.wj)(s,3e4,`ensureCloned timed out after 30000ms for ${t} @ ${r}`)}async ensureMaterialized(e,t,r=Tp){const n=this.serializedOnRepo((0,s.dirname)(e),(async()=>{const n=performance.now();try{await Vj(e,t,{extraGitConfig:Mj(this.options?.extraGitConfig),timeoutMs:this.remoteTimeoutMs()}),r.increment("marketplace_cache_manager.ensure_materialized.success",1),r.distribution("marketplace_cache_manager.ensure_materialized.duration",performance.now()-n)}catch(o){throw r.log("error","Failed to materialize plugin directories in sparse marketplace clone",{clonePath:e,spec:"all"===t?"all":t.join(","),error:String(o),errorCategory:SU(o)}),r.increment("marketplace_cache_manager.ensure_materialized.error",1,{error_category:SU(o)}),r.distribution("marketplace_cache_manager.ensure_materialized.duration",performance.now()-n,{outcome:"error"}),o}}));return this.sparsePluginClones?n:(0,Or.wj)(n,3e4,`ensureMaterialized timed out after 30000ms for ${e}`)}async serializedOnRepo(e,t){const r=`${this.cacheRoot}:${e}`,n=(_U.get(r)??Promise.resolve()).catch((()=>{})).then(t);_U.set(r,n);try{return await n}finally{_U.get(r)===n&&_U.delete(r)}}async ensureClonedImpl(e,t,r,n,o){n.log("info",`MarketplaceCacheManager: Ensuring cloned ${e} at ${t}@${r}`,{marketplaceId:e,gitUrl:t,ref:r});const s=r.trim();let i,a=t.startsWith("git@")||t.startsWith("ssh://")?null:aU(t);if(null!==a)try{i=(await Lj(a,s,{sshBatchMode:!0,extraGitConfig:Mj(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}catch(e){if(this.sparsePluginClones&&bU(e))throw e;n.log("debug","Failed to resolve remote ref using SSH URL, falling back to HTTPS",{gitUrl:t,ref:r,error:String(e),errorCategory:vU(e)}),a=null,i=(await Lj(t,s,{extraGitConfig:Mj(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha}else i=(await Lj(t,s,{extraGitConfig:Mj(this.options?.extraGitConfig),timeoutMs:this.lsRemoteTimeoutMs()})).fullSha;const c=this.getCanonicalCloneDir(t,i),l=this.getLegacyCloneDir(e,s);n.log("info",`MarketplaceCacheManager: Resolved clone directory for ${e} at ${t}@${r} to ${c}`,{marketplaceId:e,resolvedRef:i,originalRef:s});const u=performance.now(),d=(e,t)=>{n.increment(`marketplace_cache_manager.ensure_cloned.${e}`,1,t),n.distribution(`marketplace_cache_manager.ensure_cloned.${e}.duration`,performance.now()-u,t)};if(await this.isCloneComplete(c)){await this.pruneSiblingCloneDirs(t,i,l);const e=await Gj(c);return e&&await Vj(c,o,{extraGitConfig:Mj(this.options?.extraGitConfig),timeoutMs:this.remoteTimeoutMs()}),d("cache_hit",{strategy:e?"sparse":"full"}),c}return n.increment("marketplace_cache_manager.ensure_cloned.cache_miss",1),this.cloneViaStaging(c,t,a,i,l,r,n,d,o)}async cloneViaStaging(e,t,r,n,o,s,i,a,c){await this.cleanStaleStagingDirs();const l=await this.createStagingDir();i.log("info",`MarketplaceCacheManager: Cloning ${t}@${s} into staging directory: ${l}`,{gitUrl:t,ref:s,cloneDir:e});const u=this.sparsePluginClones?setInterval((()=>{const e=new Date;(0,Co.utimes)(l,e,e).catch((()=>{}))}),CU.STAGING_HEARTBEAT_INTERVAL_MS):void 0;u?.unref?.();try{let u;if(null!==r)try{u=await this.cloneResolvedRef(l,r,n,{sshBatchMode:!0,materialize:c})}catch(e){if(this.sparsePluginClones&&bU(e))throw e;i.log("debug","Falling back to HTTPS clone due to SSH clone failure",{gitUrl:t,ref:s,error:String(e),errorCategory:SU(e)}),await(0,Co.rm)(l,mU),await(0,Co.mkdir)(l,{recursive:!0}),u=await this.cloneResolvedRef(l,t,n,{materialize:c})}else u=await this.cloneResolvedRef(l,t,n,{materialize:c});u.filterIgnoredByServer&&(i.log("warn","Server ignored --filter=blob:none; sparse clone downloaded a full pack",{gitUrl:t,ref:s}),i.increment("marketplace_cache_manager.ensure_cloned.filter_ignored_by_server",1));const d=await this.moveToCanonicalDir(l,e);return await this.pruneSiblingCloneDirs(t,n,o),a("cache_write_success",{strategy:u.strategy}),d}catch(e){const r=SU(e);throw a("error",{error_category:r}),i.log("error","Failed to clone marketplace repository via staging clone",{gitUrl:t,ref:s,error:String(e),errorCategory:r}),i.captureException(e,{error_type:"clone_marketplace_repository",error_category:r}),e}finally{void 0!==u&&clearInterval(u);try{await(0,Co.rm)(l,mU)}catch{}}}async isCloneComplete(e){try{if(!(await(0,Co.stat)(e)).isDirectory())return!1;const t=await(0,Co.readdir)(e);if(!t.includes(".git"))return!1;if(t.length>1)return!0;try{return(await(0,Co.stat)((0,s.join)(e,".git","info","sparse-checkout"))).isFile()}catch{return!1}}catch{return!1}}getPluginDir(e,t){return vf(e,t)}async copyPluginToDir(e,t){await(0,Co.mkdir)(t,{recursive:!0}),await(0,Co.cp)(e,t,{recursive:!0,verbatimSymlinks:!0})}async readManifest(e,t={}){const r=function(e,t){return JSON.stringify({clonePath:e,repoName:t.repoName??null,fallbackId:t.fallbackId??null})}(e,t);if(this.manifestCache.has(r))return this.manifestCache.get(r)??null;const n=await async function(e,t={}){for(const r of zh){const n=(0,s.join)(e,r);let o;try{o=await(0,Co.readFile)(n,"utf-8")}catch{continue}const i=bp(o,t);if(i.success)return i.data}return null}(e,t);return this.manifestCache.set(r,n),n}async resolvePluginPath(e,t){const r=await this.readManifest(e);if(!r)return null;const n=r.plugins.find((e=>e.name===t.toLowerCase()));if(!n)return null;const o=kp(n.source,r.metadata?.pluginRoot);return o&&_p(o)?o:null}async discoverPlugins(e){const t=await this.readManifest(e);return t?function(e){const t=[],r=function(e,t){const r=[];for(const n of e){const e=n.source;if("string"!=typeof e)switch(e.source){case"github":r.push({entry:n,kind:"external-github",externalUrl:`https://github.com/${e.repo}.git`,externalRef:e.ref,externalSha:e.sha,effectiveRef:e.sha??e.ref});break;case"url":r.push({entry:n,kind:"external-url",externalUrl:e.url,externalRef:e.ref,externalSha:e.sha,effectiveRef:e.sha??e.ref});break;case"git-subdir":r.push({entry:n,kind:"external-git-subdir",externalUrl:e.url,externalRef:e.ref,externalSha:e.sha,effectiveRef:e.sha??e.ref,subdirPath:e.path})}else{const o=kp(e,t);null!==o?r.push({entry:n,kind:"local",localPath:o}):r.push({entry:n,kind:"unresolvable",rawSource:e})}}return r}(e.plugins,e.metadata?.pluginRoot);for(const e of r){const{name:r,displayName:n,description:o,version:s}=e.entry,i={name:r,displayName:n,description:o,version:s};switch(e.kind){case"local":_p(e.localPath)&&t.push({...i,sourceType:"local",gitPath:e.localPath});break;case"external-github":t.push({...i,sourceType:"github",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha});break;case"external-url":t.push({...i,sourceType:"url",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha});break;case"external-git-subdir":t.push({...i,sourceType:"git-subdir",gitUrl:e.externalUrl,gitRef:e.externalRef,sha:e.externalSha,subdirPath:e.subdirPath})}}return t}(t):[]}}CU.STALE_STAGING_THRESHOLD_MS=3e5,CU.STAGING_HEARTBEAT_INTERVAL_MS=6e4;const EU=(0,zs.debuglog)("cursor-plugins");function xU(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function PU(e){return xU(e)?e:void 0}function RU(e){const t=e.name?.trim();return void 0!==t&&t.length>0?t:e.pluginId}function IU(e,t){return void 0!==e?.marketplace?e.marketplace:void 0!==e?.marketplaceId?(t??[]).find((t=>void 0!==t.id&&String(t.id)===String(e.marketplaceId))):void 0}function TU(e,t){const r=t?.distributionGitUrl?.trim();return r?t?.gitUrl&&!BU(e,t.gitUrl)?e:r:e}function AU(e){return e?.distributionGitUrl?.trim()||e?.gitUrl}function $U(e,t){if(e.pinnedGitRef)return e.pinnedGitRef;if(e.plugin?.gitRef)return e.plugin.gitRef;const r=IU(e.plugin,t),n=e.plugin?.gitUrl,o=r?.gitUrl;return n&&o&&n!==o||!r?.gitRef?"main":r.gitRef}const MU="backend-git://";function DU(e,t,r){const n=r?`#${encodeURIComponent(r)}`:"";return`${MU}${encodeURIComponent(e)}@${encodeURIComponent(t)}${n}`}function OU(e){if(!e.startsWith(MU))return null;const t=e.slice(14),r=t.indexOf("#"),n=r>=0?t.slice(0,r):t,o=r>=0?t.slice(r+1):void 0,s=n.lastIndexOf("@");return s<0?null:{gitUrl:decodeURIComponent(n.slice(0,s)),ref:decodeURIComponent(n.slice(s+1)),gitPath:o?decodeURIComponent(o):void 0}}const FU="backend-release://";function NU(e){const t=e.tag?`@${encodeURIComponent(e.tag)}`:"";return`${FU}${encodeURIComponent(e.repo)}#${encodeURIComponent(e.asset)}${t}`}function LU(e){if(!e.startsWith(FU))return null;const t=e.slice(18),r=t.indexOf("#");if(r<0)return null;const n=decodeURIComponent(t.slice(0,r)),o=t.slice(r+1),s=o.lastIndexOf("@");return{repo:n,asset:s>=0?decodeURIComponent(o.slice(0,s)):decodeURIComponent(o),tag:s>=0?decodeURIComponent(o.slice(s+1)):void 0}}const jU=/^[0-9a-f]{7,40}$/i;function UU(e){let t;try{t=kU(e)}catch{return null}return`${t.host}\0${t.pathSegments.join("\0")}`}function BU(e,t){if(e.trim()===t.trim())return!0;const r=UU(e),n=UU(t);return null!==r&&r===n}const WU=104857600;async function HU(e,t,r,n,i,a){const c=await async function(e){const{repo:t,asset:r,tag:n}=e,{apiBase:o,ownerRepo:s,host:i}=function(e){const t=e.split("/"),r=t[0],n=t[1],o=t[2];if(3===t.length&&void 0!==r&&void 0!==n&&void 0!==o)return{apiBase:`https://${r}/api/v3`,ownerRepo:`${n}/${o}`,host:r};if(2===t.length)return{apiBase:"https://api.github.com",ownerRepo:e,host:"github.com"};throw new Error(`Invalid release repo format: ${e}`)}(t),a="github.com"===i&&void 0!==e.githubToken&&e.githubToken.length>0?{Authorization:`token ${e.githubToken}`}:{},c=n?`${o}/repos/${s}/releases/tags/${encodeURIComponent(n)}`:`${o}/repos/${s}/releases/latest`,l=await fetch(c,{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"CursorPluginInstaller",...a}});if(!l.ok)throw new Error(`Failed to fetch release from ${c}: ${l.status} ${l.statusText}`);const u=await l.json();if(!(xU(d=u)&&Array.isArray(d.assets)&&d.assets.every((e=>xU(e)&&"string"==typeof e.name&&"string"==typeof e.browser_download_url&&"number"==typeof e.size))))throw new Error(`Release payload from ${c} did not include assets`);var d;const h=u,p=h.assets.find((e=>e.name===r));if(!p){const e=h.assets.map((e=>e.name)).join(", ");throw new Error(`Release asset "${r}" not found. Available assets: ${e}`)}if(p.size>WU)throw new Error(`Release asset "${r}" exceeds maximum size of 104857600 bytes (actual: ${p.size})`);const f=new URL(p.browser_download_url);if("https:"!==f.protocol||!qU(f.hostname,i))throw new Error(`Refusing to download release asset from untrusted host: ${f.hostname}`);const m=await fetch(p.browser_download_url,{headers:{"User-Agent":"CursorPluginInstaller",Accept:"application/octet-stream",...a}});if(!m.ok)throw new Error(`Failed to download release asset: ${m.status} ${m.statusText}`);if(m.url){const e=new URL(m.url);if("https:"!==e.protocol||!qU(e.hostname,i))throw new Error(`Refusing to download release asset: redirected to untrusted host: ${e.hostname}`)}const g=Buffer.from(await m.arrayBuffer());if(g.byteLength>WU)throw new Error(`Release asset "${r}" actual download size exceeds maximum of 104857600 bytes (actual: ${g.byteLength})`);if(e.expectedSha256){const t=(0,bo.createHash)("sha256").update(g).digest("hex");if(t!==e.expectedSha256)throw new Error(`Release asset "${r}" integrity check failed: expected SHA-256 ${e.expectedSha256}, got ${t}`)}return g}({repo:e,asset:t,tag:r,expectedSha256:i,githubToken:a}),l=c.byteLength;await(0,Co.mkdir)(n,{recursive:!0});const u=await(0,Co.mkdtemp)((0,s.join)((0,o.tmpdir)(),"release-asset-")),d=(0,s.join)(u,"asset.tar.gz"),h=(0,s.join)(u,"extracted");try{await(0,Co.writeFile)(d,c),await(0,Co.mkdir)(h,{recursive:!0});let e=0,t=0;await sh.x({file:d,cwd:h,onReadEntry:r=>{if(t++,t>5e4)throw new Error("Release archive contains too many files (>50000).");if(e+=r.size,e>524288e3)throw new Error("Release archive uncompressed size exceeds maximum of 524288000 bytes.");if(l>0&&e/l>100)throw new Error("Release archive has suspicious compression ratio (>100x).")}});const r=await(0,Co.readdir)(h,{withFileTypes:!0}),o=r.filter((e=>e.isDirectory())),i=r.filter((e=>e.isFile()));let a=h;const u=o[0];if(1===o.length&&0===i.length&&void 0!==u){const e=(0,s.join)(h,u.name);(await(0,Co.readdir)(e)).some((e=>qh.includes(e)))&&(a=e)}const p=await(0,Co.readdir)(a);await Promise.all(p.map((e=>(0,Co.cp)((0,s.join)(a,e),(0,s.join)(n,e),{recursive:!0,verbatimSymlinks:!0}))))}finally{await(0,Co.rm)(u,{recursive:!0,force:!0}).catch((()=>{}))}}function qU(e,t){return!(e!==t&&!e.endsWith(".githubusercontent.com"))||("github.com"===t?"github.com"===e:e.endsWith(`.${t}`))}class zU{constructor(e,t,r,n,o){this.getEffectiveUserPlugins=e;const s="string"==typeof t||void 0===t?{marketplaceCacheRoot:t,pluginLogger:r,marketplaceCacheOptions:n,listOptions:o}:t,i=s.marketplaceCacheOptions??n;this.pluginLogger=s.pluginLogger??r??Tp,this.extraGitConfig=s.extraGitConfig,this.awaitAuthReady=s.awaitAuthReady,this.githubToken=s.githubToken,this.downloadPluginContent=s.downloadPluginContent,this.contentRetries=s.contentRetries??(new _h).forListing(""),this.sparsePluginClones=s.sparsePluginClones??!1,this.marketplaceCache=s.marketplaceCacheRoot?new CU(s.marketplaceCacheRoot,{...i,extraGitConfig:i?.extraGitConfig??s.extraGitConfig,sparsePluginClones:this.sparsePluginClones}):void 0;const a=s.listOptions??o;this.allowedMarketplaceNames=a?.allowedMarketplaceNames?new Set(a.allowedMarketplaceNames):void 0,this.enableInlinePlugins=a?.enableInlinePlugins??!1}isMarketplaceAllowed(e){return void 0===this.allowedMarketplaceNames||void 0!==e?.name&&this.allowedMarketplaceNames.has(e.name)}async listEnabledPlugins(e,t){const r=await this.getEffectiveUserPlugins(),n=r.plugins??[],o=r.marketplaces??[],s=[],i=[],a=new Map,c=async(e,t)=>{const r=`${e}\0${t}`;let n=a.get(r);if(!n){const o=Mj(this.extraGitConfig),s=this.sparsePluginClones?3e4:void 0,i=e.startsWith("git@")||e.startsWith("ssh://")?null:aU(e),c=async(e,r)=>{const n={};return r&&(n.sshBatchMode=!0),void 0!==o&&(n.extraGitConfig=o),void 0!==s&&(n.timeoutMs=s),(Object.keys(n).length>0?await Lj(e,t,n):await Lj(e,t)).fullSha};if(null!==i)try{n=await c(i,!0)}catch(t){if(this.sparsePluginClones&&bU(t))throw t;n=await c(e,!1)}else n=await c(e,!1);a.set(r,n)}return n},l=async e=>{const{preferredGitUrl:t,sourceGitUrl:r,gitRef:n,pluginId:o}=e;if(t!==r){void 0!==this.awaitAuthReady&&await this.awaitAuthReady();const e=`${t}\0${n}`,s=!a.has(e);let i;s&&this.pluginLogger.increment("marketplace.origin_distribution.fetch",1);try{i={sha:await c(t,n),gitUrl:t}}catch(e){s&&this.pluginLogger.increment("marketplace.origin_distribution.fetch.error",1),this.pluginLogger.captureException(e,{error_type:"distribution_url_fallback"}),this.pluginLogger.log("warn",`Distribution mirror ${t}@${n} unavailable (not synced yet or unreachable); falling back to source ${r}`,{pluginId:o,preferredGitUrl:t,sourceGitUrl:r,gitRef:n,error:String(e)})}if(void 0!==i){if(s)try{this.pluginLogger.log("info",`Resolved plugin ${o} from Origin distribution mirror ${t}@${n}`,{pluginId:o,preferredGitUrl:t,gitRef:n})}catch{}return i}}return{sha:await c(r,n),gitUrl:r}};this.contentRetries.startLoad();for(const e of n){if(!e.isEnabled||!e.plugin?.name)continue;const t=e.plugin,r=IU(t,o);if(!this.isMarketplaceAllowed(r)){this.pluginLogger.log("info",`Skipping plugin ${t.name} because marketplace ${r?.name??""} is not allowed`,{pluginId:t.name,marketplaceName:r?.name,allowedMarketplaceNames:void 0!==this.allowedMarketplaceNames?Array.from(this.allowedMarketplaceNames):void 0});continue}const n=RU({name:t.name,pluginId:void 0!==t.id?String(t.id):t.name??""}),a=n;if(void 0!==t.backendContent&&null!==t.backendContent){const t=this.listBackendContentPlugin(e,r,n);"entry"in t?s.push(t.entry):i.push(t.failure);continue}if(!t.gitUrl){if(!this.enableInlinePlugins){this.pluginLogger.log("info",`Skipping plugin ${n} without gitUrl (enableInlinePlugins=false)`,{pluginId:a});continue}const o=e.inlineContentJson;if(!o){this.pluginLogger.log("info",`Skipping DB-inline plugin ${n}: no inline content provided`,{pluginId:a});continue}const i=(0,bo.createHash)("sha256").update(`${t.id??"0"}:${t.updatedAt??"0"}`).digest("hex").slice(0,40),c=r?.name?{id:void 0!==r.id?`${r.name}-${r.id}`:`${r.name}-inline`,name:r.name}:void 0;this.pluginLogger.log("info",`BackendMarketplaceClient: Adding DB-inline plugin: ${a}`,{pluginId:a,marketplaceId:c?.id??"unknown",version:i}),s.push({pluginId:a,pluginDbId:void 0!==t.id?String(t.id):void 0,configuredVariables:PU(e.configuredVariables),isTeamRequired:e.isTeamRequired,name:n,version:i,downloadUrl:`inline://${t.id??a}`,marketplaceDbId:void 0!==r?.id?String(r.id):void 0,marketplace:c,inlineContentJson:o});continue}const c=t.gitUrl,u=TU(c,r),d=$U(e,o),h=Cj(t,d),p=r?.gitRef??d;let f,m,g=u;try{if(void 0!==h)f=`release/${h.releaseTag}`;else{const e=await l({preferredGitUrl:u,sourceGitUrl:c,gitRef:d,pluginId:a});f=e.sha,g=e.gitUrl}}catch(e){this.pluginLogger.captureException(e,{error_type:"resolve_version_sha"}),this.pluginLogger.log("error",`Failed to resolve version for plugin ${n}@${d}, skipping plugin`,{pluginId:a,ref:d,error:String(e)});const o=e instanceof Error?e.message:String(e);i.push({pluginName:n,pluginId:a,pluginDbId:void 0!==t.id?String(t.id):void 0,marketplaceName:r?.name,errorMessage:o,errorType:/timed?\s*out/i.test(o)?"timeout":"clone"});continue}m=void 0!==h?NU({repo:h.releaseRepo,asset:h.releaseAsset,tag:h.releaseTag}):DU(g,d,t.gitPath??void 0);const w=AU(r);let y=w,v=r?.gitUrl,b=p;if(r?.gitUrl&&w){const e=BU(c,r.gitUrl),t=e?g:w,o=e?c:r.gitUrl,s=e?d:p;v=o;try{const e=await l({preferredGitUrl:t,sourceGitUrl:o,gitRef:s,pluginId:a});b=e.sha,y=e.gitUrl}catch(e){this.pluginLogger.captureException(e,{error_type:"resolve_marketplace_cache_ref"}),this.pluginLogger.log("warn",`Failed to resolve marketplace cache ref for plugin ${n} from ${t}@${s}, falling back to raw ref`,{pluginId:a,cacheRepoUrl:t,cacheRef:s,error:String(e)}),y=o}}const S=r?.name?{id:void 0!==r.id?`${r.name}-${r.id}`:`${r.name}-${encodeURIComponent(r.gitUrl??"project")}`,name:r.name,...y&&{gitUrl:y,gitRef:b}}:void 0,k=void 0!==h||g===c&&y===v?void 0:{downloadUrl:DU(c,d,t.gitPath??void 0),marketplaceGitUrl:v};this.pluginLogger.log("info",`BackendMarketplaceClient: Adding enabled plugin: ${a} from ${b} at ${t.gitPath}`,{pluginId:a,marketplaceId:S?.id??"unknown",gitPath:t.gitPath??void 0,gitRef:b}),s.push({pluginId:a,pluginDbId:void 0!==t.id?String(t.id):void 0,configuredVariables:PU(e.configuredVariables),isTeamRequired:e.isTeamRequired,name:n,version:f,downloadUrl:m,marketplaceDbId:void 0!==r?.id?String(r.id):void 0,marketplace:S,gitPath:t.gitPath??void 0,isOriginBacked:void 0===h&&g!==c||void 0,originSourceFallback:k})}return{plugins:s,listFailures:i}}isBackendContentRetryDue(){return this.contentRetries.isRetryDue()}allowImmediateBackendContentRetry(){this.contentRetries.allowImmediateRetry()}listBackendContentPlugin(e,t,r){const n=Ch(e.plugin?.id),o=function(e){const{revision:t}=e;return"string"==typeof t&&mh.test(t)?{revision:t}:{invalid:"revision"}}(e.plugin?.backendContent??{}),s=void 0===n?"plugin_id":"invalid"in o?o.invalid:void 0;if(void 0===n||"invalid"in o)return this.pluginLogger.log("error",`Skipping plugin ${r}: the listing's backend content has an unusable ${s}`,{pluginId:r,invalidField:s}),this.pluginLogger.increment("backend_marketplace_client.backend_content.list.invalid",1),{failure:{pluginName:r,pluginId:r,pluginDbId:n,marketplaceName:t?.name,errorMessage:`Plugin ${JSON.stringify(r)} could not be installed: the server listed it with details this client does not accept.`,errorType:"install"}};const i=t?.name?{id:void 0!==t.id?`${t.name}-${t.id}`:`${t.name}-backend-content`,name:t.name}:void 0;return this.pluginLogger.log("info",`BackendMarketplaceClient: Adding backend-served plugin: ${r}`,{pluginId:r,marketplaceId:i?.id??"unknown",revision:o.revision}),{entry:{pluginId:r,pluginDbId:n,configuredVariables:PU(e.configuredVariables),isTeamRequired:e.isTeamRequired,name:r,version:xh(o.revision),downloadUrl:(a={pluginDbId:n,revision:o.revision},`${yh}${a.pluginDbId}@${a.revision}`),marketplaceDbId:void 0!==t?.id?String(t.id):void 0,marketplace:i,backendContent:o}};var a}async relistPlugin(e){if(void 0===e.backendContent||void 0===e.pluginDbId)return;const t=await this.getEffectiveUserPlugins(),r=(t.plugins??[]).find((t=>!0===t.isEnabled&&Ch(t.plugin?.id)===e.pluginDbId)),n=r?.plugin;if(void 0===r||!n?.name||void 0===n.backendContent||null===n.backendContent)return;const o=IU(n,t.marketplaces??[]);if(!this.isMarketplaceAllowed(o))return;const s=this.listBackendContentPlugin(r,o,e.name);return"entry"in s&&s.entry.version!==e.version?s.entry:void 0}async installBackendContentPlugin(e,t){const r=e.backendContent,n=Ch(e.pluginDbId);if(void 0===r||void 0===n)throw new Error(`Plugin ${JSON.stringify(e.name)} has no backend content to install`);const o={pluginDbId:n,revision:r.revision},s=this.contentRetries.heldFailure(o);if(void 0!==s)throw Ph(s,e.name);const i=performance.now();let a="success";try{await Ih({download:this.downloadPluginContent,pluginDbId:n,pluginName:e.name,content:r,targetDir:t}),this.contentRetries.recordAttempt(o)}catch(e){throw a=e instanceof ph?e.reason:"unknown",this.contentRetries.recordAttempt({...o,error:e}),e}finally{this.pluginLogger.increment("backend_marketplace_client.backend_content.install",1,{outcome:a}),this.pluginLogger.distribution("backend_marketplace_client.backend_content.install.duration",performance.now()-i,{outcome:a})}this.pluginLogger.log("info",`Installed backend-served plugin ${e.pluginId}`,{pluginId:e.pluginId,revision:r.revision})}isDirectInstallSameFetch(e){const t=e.marketplace;if(!t?.gitUrl||!t.gitRef)return!1;const r=OU(e.downloadUrl);return!(!r||!BU(r.gitUrl,t.gitUrl)||r.ref!==t.gitRef&&e.version!==t.gitRef)}async installPlugin(e,t){if(void 0!==e.backendContent||Eh(e.downloadUrl))await this.installBackendContentPlugin(e,t);else if(e.inlineContentJson)await async function(e){const{targetDir:t,inlineContentJson:r,pluginName:n}=e,o=JSON.parse(r);await(0,Co.mkdir)(t,{recursive:!0});const i={};if(o.rules&&o.rules.length>0){const e=(0,s.join)(t,"rules");await(0,Co.mkdir)(e,{recursive:!0});const r=[];for(const t of o.rules){if(!t.content)continue;if(!1===t.isActive)continue;const n=`${oh(t.name)}.md`,o=[];o.push(`description: ${uU(t.name)}`),t.globs&&t.globs.length>0&&o.push(`globs: ${uU(t.globs.join(", "))}`),o.push(`alwaysApply: ${!0===t.isRequired}`);const i=`---\n${o.join("\n")}\n---\n\n`;await(0,Co.writeFile)((0,s.join)(e,n),i+t.content,"utf-8"),r.push(`rules/${n}`)}r.length>0&&(i.rules=r)}if(o.commands&&o.commands.length>0){const e=(0,s.join)(t,"commands");await(0,Co.mkdir)(e,{recursive:!0});const r=[];for(const t of o.commands){if(!t.content)continue;if(!1===t.isActive)continue;const n=`${oh(t.name)}.md`,o=t.description?`---\ndescription: ${uU(t.description)}\n---\n\n`:"";await(0,Co.writeFile)((0,s.join)(e,n),o+t.content,"utf-8"),r.push(`commands/${n}`)}r.length>0&&(i.commands=r)}if(o.hooks&&o.hooks.length>0){const e=(0,s.join)(t,"hooks");await(0,Co.mkdir)(e,{recursive:!0});const r={};for(const e of o.hooks){const t=e.hookStep;t&&!1!==e.isActive&&lU(e)&&(r[t]||(r[t]=[]),"prompt"===e.hookType?r[t].push({type:"prompt",prompt:e.promptContent??"",...e.promptModel?{model:e.promptModel}:{}}):r[t].push({type:"command",command:e.scriptContent??""}))}await(0,Co.writeFile)((0,s.join)(e,"hooks.json"),JSON.stringify({version:1,hooks:r},null,2),"utf-8")}if(o.mcpServers&&o.mcpServers.length>0){const e={};for(const t of o.mcpServers)t.config&&(e[t.name]=t.config);Object.keys(e).length>0&&await(0,Co.writeFile)((0,s.join)(t,".mcp.json"),JSON.stringify({mcpServers:e},null,2),"utf-8")}const a={name:n,...i},c=(0,s.join)(t,".cursor-plugin");await(0,Co.mkdir)(c,{recursive:!0}),await(0,Co.writeFile)((0,s.join)(c,"plugin.json"),JSON.stringify(a,null,2),"utf-8")}({targetDir:t,inlineContentJson:e.inlineContentJson,pluginName:e.name});else{e.isOriginBacked&&void 0!==this.awaitAuthReady&&await this.awaitAuthReady();try{return void await this.installFromEntryUrls(e,t)}catch(r){const n=function(e){const t=e.originSourceFallback;if(void 0===t)return;let r=e.marketplace;if(void 0!==r)if(void 0!==t.marketplaceGitUrl)r={...r,gitUrl:t.marketplaceGitUrl};else{const{gitUrl:e,gitRef:t,...n}=r;r=n}return{...e,downloadUrl:t.downloadUrl,marketplace:r,isOriginBacked:void 0,originSourceFallback:void 0}}(e);if(void 0===n)throw r;this.pluginLogger.captureException(r,{error_type:"install_plugin_from_origin_distribution"}),this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from the Origin distribution mirror, falling back to the source repo`,{pluginId:e.pluginId,version:e.version,sourceDownloadUrl:n.downloadUrl,sourceMarketplaceGitUrl:n.marketplace?.gitUrl,error:String(r)}),this.pluginLogger.increment("marketplace.origin_distribution.install.source_fallback",1),await(0,Co.rm)(t,{recursive:!0,force:!0});try{await this.installFromEntryUrls(n,t)}catch(e){throw this.pluginLogger.increment("marketplace.origin_distribution.install.source_fallback.error",1),e}}}}async installFromEntryUrls(e,t){if(null===LU(e.downloadUrl))try{if(await this.tryInstallFromMarketplaceCache(e,t))return void this.emitOriginLoadIfApplicable(e)}catch(t){if(this.pluginLogger.captureException(t,{error_type:"install_plugin_from_marketplace_cache"}),this.sparsePluginClones&&this.isDirectInstallSameFetch(e)&&bU(t))throw this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from marketplace cache; skipping direct install fallback because it would repeat the identical fetch`,{pluginId:e.pluginId,version:e.version,error:String(t)}),t;this.pluginLogger.log("warn",`Failed to install plugin ${e.name} from marketplace cache, falling back to direct install`,{pluginId:e.pluginId,version:e.version,error:String(t)})}await async function(e,t,r=Tp,n,i){const a=i?.sparsePluginClones??!1,c=a?pU:void 0,l=LU(e.downloadUrl);if(l){if(e.gitPath){const r=await(0,Co.mkdtemp)((0,s.join)((0,o.tmpdir)(),"release-plugin-"));try{await HU(l.repo,l.asset,l.tag,r,i?.expectedReleaseAssetSha256,i?.githubToken);const n=vf(r,e.gitPath);await(0,Co.mkdir)(t,{recursive:!0}),await(0,Co.cp)(n,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,Co.rm)(r,{recursive:!0,force:!0}).catch((()=>{}))}}else await HU(l.repo,l.asset,l.tag,t,i?.expectedReleaseAssetSha256,i?.githubToken);return}const u=OU(e.downloadUrl);if(!u)throw new Error(`Invalid download URL format for plugin ${e.pluginId}: ${e.downloadUrl}`);const d=await(0,Co.mkdtemp)((0,s.join)((0,o.tmpdir)(),"backend-plugin-"));try{let o;if(await async function(e,t,r,n=Tp,o,s="all",i=!1){const a=performance.now(),c=jU.test(t),l="HEAD"===t.toUpperCase(),u={...o,"safe.directory":r},d=i?pU:void 0,h=i?fU:void 0,{sparse:p,sparseDirs:f}=await Hj(s,i),m=p?["--filter=blob:none","--sparse"]:[],g=!!p||void 0,w=async e=>{p&&await zj(r,f,{extraGitConfig:u,timeoutMs:e,sshBatchMode:!0})},y=async(e,n)=>{let o;return l?(({stderr:o}=await Dj(["clone","--depth","1",...m,e,r],{extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await w(d)):c?(await Dj(["init"],{cwd:r,extraGitConfig:u,timeoutMs:h}),await Dj(["remote","add","origin",e],{cwd:r,extraGitConfig:u,timeoutMs:h}),await w(h),({stderr:o}=await Dj(["fetch","--depth","1",...p?["--filter=blob:none"]:[],"origin",t],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await Dj(["checkout","FETCH_HEAD"],{cwd:r,extraGitConfig:u,timeoutMs:d,sshBatchMode:n})):(({stderr:o}=await Dj(["clone","--depth","1","--branch",t,...m,e,r],{extraGitConfig:u,timeoutMs:d,sshBatchMode:n})),await w(d)),o},v=e.startsWith("git@")||e.startsWith("ssh://")?null:aU(e);let b;if(null!==v)try{b=await y(v,!0)}catch(t){if(i&&bU(t))throw t;await(0,Co.rm)(r,{recursive:!0,force:!0}),await(0,Co.mkdir)(r,{recursive:!0}),b=await y(e,g)}else b=await y(e,g);p&&qj(b)&&(n.log("warn",`shallowClone: server ignored --filter=blob:none for ${e}; sparse clone downloaded a full pack`),n.increment("backend_marketplace_client.shallow_clone.filter_ignored_by_server",1));const S=(performance.now()-a).toFixed(1);EU("shallowClone %s@%s completed in %sms",e,t,S),n.log("info",`shallowClone ${e}@${t} completed in ${S}ms (${p?"sparse":"full"})`)}(u.gitUrl,u.ref,d,r,n,u.gitPath?Wj([u.gitPath]):[],a),u.gitPath)o=vf(d,u.gitPath);else{const t=await async function(e,t){for(const r of zh){const n=(0,s.join)(e,r);let o;try{o=await(0,Co.readFile)(n,"utf-8")}catch{continue}const i=bp(o);if(!i.success)return{type:"manifest-unresolved",reason:`Invalid marketplace manifest at ${r}: ${i.error}`};const a=i.data,c=a.plugins.find((e=>e.name===t.toLowerCase()));if(!c)return{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} not found in ${r}`};if("string"!=typeof c.source&&"git-subdir"===c.source.source)return{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} uses unsupported git-subdir source`};const l=kp(c.source,a.metadata?.pluginRoot);return l&&_p(l)?{type:"resolved",gitPath:l}:{type:"manifest-unresolved",reason:`Plugin ${JSON.stringify(t)} has unresolved or unsafe source path`}}return{type:"no-manifest"}}(d,e.name);if("resolved"===t.type)await Vj(d,Wj([t.gitPath]),{extraGitConfig:n,timeoutMs:c}),o=vf(d,t.gitPath);else{if("manifest-unresolved"===t.type)throw new Error(`Unable to install plugin ${JSON.stringify(e.name)} without gitPath: ${t.reason}`);await Vj(d,"all",{extraGitConfig:n,timeoutMs:c}),o=d}}await(0,Co.mkdir)(t,{recursive:!0}),await(0,Co.cp)(o,t,{recursive:!0,verbatimSymlinks:!0})}finally{await(0,Co.rm)(d,{recursive:!0,force:!0}).catch((()=>{}))}}(e,t,this.pluginLogger,Mj(this.extraGitConfig),{githubToken:this.githubToken,sparsePluginClones:this.sparsePluginClones}),this.emitOriginLoadIfApplicable(e)}emitOriginLoadIfApplicable(e){if(e.isOriginBacked)try{this.pluginLogger.increment("marketplace.origin_distribution.load",1),this.pluginLogger.log("info",`Loaded plugin ${e.pluginId} from Origin distribution (fetch complete)`,{pluginId:e.pluginId})}catch{}}async prewarmMarketplaceClones(e){const t=this.marketplaceCache;if(!t)return;const r=new Map;for(const t of e){const e=t.marketplace;if(!e?.gitUrl)continue;const n=e.gitRef??"main",o=`${e.id}\0${e.gitUrl}\0${n}`;let s=r.get(o);void 0===s&&(s={marketplaceId:e.id,gitUrl:e.gitUrl,gitRef:n,gitPaths:[]},r.set(o,s)),t.gitPath&&s.gitPaths.push(t.gitPath)}for(const e of r.values()){const r=Wj(e.gitPaths),n=performance.now();try{await t.ensureCloned(e.marketplaceId,e.gitUrl,e.gitRef,this.pluginLogger,{materialize:r}),this.pluginLogger.log("info",`Prewarmed marketplace clone ${e.gitUrl}@${e.gitRef} for ${e.gitPaths.length} plugin directories`,{marketplaceId:e.marketplaceId,gitUrl:e.gitUrl,gitRef:e.gitRef,requestedDirs:e.gitPaths.length,materialize:"all"===r?"all":r.length}),this.pluginLogger.increment("marketplace_cache_manager.prewarm.success",1,{materialize:"all"===r?"all":"dirs"})}catch(t){this.pluginLogger.captureException(t,{error_type:"prewarm_marketplace_clone"}),this.pluginLogger.log("warn",`Failed to prewarm marketplace clone ${e.gitUrl}@${e.gitRef}; falling back to per-plugin materialization`,{marketplaceId:e.marketplaceId,gitUrl:e.gitUrl,gitRef:e.gitRef,error:String(t)}),this.pluginLogger.increment("marketplace_cache_manager.prewarm.error",1)}this.pluginLogger.distribution("marketplace_cache_manager.prewarm.duration",performance.now()-n)}}async tryInstallFromMarketplaceCache(e,t){const r=this.marketplaceCache,n=e.marketplace;if(!r||!n||!n.gitUrl)return this.pluginLogger.log("info","No marketplace cache or marketplace metadata, skipping cache check",{pluginId:e.pluginId,name:e.name,version:e.version,marketplaceId:e.marketplace?.id}),!1;const o=await r.ensureCloned(n.id,n.gitUrl,n.gitRef??"main",this.pluginLogger,{materialize:e.gitPath?Wj([e.gitPath]):[]}),s=e.gitPath??await r.resolvePluginPath(o,e.name);if(!s)return this.pluginLogger.log("info","No git path found for plugin, skipping cache check",{pluginId:e.pluginId,name:e.name,version:e.version,marketplaceId:e.marketplace?.id}),!1;void 0===e.gitPath&&await r.ensureMaterialized(o,Wj([s]),this.pluginLogger);const i=r.getPluginDir(o,s);return await r.copyPluginToDir(i,t),!0}async discoverMarketplacePlugins(e,t,r){const n=this.marketplaceCache;if(!n)throw new Error("discoverMarketplacePlugins requires a MarketplaceCacheManager (marketplaceCacheRoot)");const o=await n.ensureCloned(e,t,r,this.pluginLogger,{materialize:[]});return n.discoverPlugins(o)}}function GU(e,t,r,n,o){return new zU(e,t,r,n,o)}function VU(e){const t=e.trim();if(!t)return!1;if(t.startsWith("git@"))return/^git@[a-zA-Z0-9.-]+:[a-zA-Z0-9._~\-/]+(?:\.git)?$/.test(t);try{const e=new URL(t);return"https:"===e.protocol&&""===e.username&&""===e.password&&""===e.search&&""===e.hash}catch{return!1}}class KU extends Error{constructor(e){super(e),this.name="SettingsParseError"}}function JU(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ZU(e){return 65279===e.charCodeAt(0)?e.slice(1):e}async function XU(e){try{return ZU(await(0,Co.readFile)(function(e){return(0,s.join)(e,".cursor","settings.json")}(e),"utf-8"))}catch(e){if(function(e){return e instanceof Error&&"code"in e}(e)&&("ENOENT"===e.code||"ENOTDIR"===e.code))return;throw e}}async function QU(e){const t=await XU(e);return void 0===t?[]:function(e){const t=function(e){const t=ZU(e);if(0===t.trim().length)return{};const r=[],n=(0,Cp.qg)(t,r,{allowTrailingComma:!0});if(r.length>0){const e=r.slice(0,3).map((e=>`${(0,Cp._n)(e.error)} at offset ${e.offset}`)).join("; ");throw new KU(`.cursor/settings.json contains syntax errors: ${e}`)}if(!JU(n))return{};const o=n.plugins;if(void 0===o)return{};if(!JU(o))return{};const s={};for(const[e,t]of Object.entries(o))JU(t)&&(s[e]=t);return{plugins:s}}(e);return t.plugins?Object.entries(t.plugins).filter((([,e])=>!0===e.enabled)).filter((([,e])=>!e.gitUrl||VU(e.gitUrl))).map((([e,t])=>({key:e,entry:t}))):[]}(t)}function YU(e){const t=e.indexOf("/");return-1===t?{name:e}:{name:e.slice(t+1),marketplaceName:e.slice(0,t)}}const eB={supportsBackendContent:!0};function tB(e={}){const t=e.userHomeDirectory??(0,o.homedir)(),r=e.importThirdPartyPlugins??!1,n=e.pluginLogger??{log(e,t,r){switch(e){case"warn":SO.Jz.warn("[local-plugins-bootstrap]",t,r??{});break;case"error":SO.Jz.error("[local-plugins-bootstrap]",t,r??{})}},increment(){},distribution(){},captureException(e,t){SO.Jz.error("[local-plugins-bootstrap] Unexpected plugin exception:",e,t??{})}},i=rB(e.marketplaceOptions),a=void 0!==e.dashboardTransport,c=e.loadCursorFirstParty??(i||a);return{async loadPluginBootstrapOutputs(o){const i=(a=o.workspaceState).projectRoot??a.workspaceRoots[0]??a.workingDirectory;var a;const{discoveredEntries:l,failures:u}=await async function(e){if(void 0===e)return{discoveredEntries:[],failures:[]};try{return{discoveredEntries:(await QU(e)).map((({key:t,entry:r})=>({source:"project-settings",workspacePath:e,key:t,entry:r}))),failures:[]}}catch(e){return{discoveredEntries:[],failures:[{stage:"discovery",source:"project-settings",message:e instanceof Error?`Failed to read project plugin settings: ${e.message}`:`Failed to read project plugin settings: ${String(e)}`,detail:e}]}}}(i),d=e.marketplaceOptions??(e.dashboardTransport?function(e){const t=(0,s.join)(e.userHomeDirectory,".cursor","plugins","marketplaces"),r=(0,ye.createClient)(fj.I,e.dashboardTransport),n=(e,{signal:t})=>r.downloadPluginContent(e,{signal:t}),o=new _h,i=GU((async()=>{try{return await r.getEffectiveUserPlugins(new JD.EwF(eB))}catch{return{plugins:[]}}}),{marketplaceCacheRoot:t,listOptions:{allowedMarketplaceNames:["cursor-public"]},downloadPluginContent:n,contentRetries:o.forListing("account")}),a=e.workspacePath,c=GU((async()=>{if(void 0===a)return{plugins:[]};try{const e=await QU(a);if(0===e.length)return{plugins:[]};const t=e.filter((e=>e.entry.gitUrl)),n=e.filter((e=>!e.entry.gitUrl)),o=t.filter((({entry:e})=>{const t=e.gitUrl;return!t||VU(t)})).map((({key:e,entry:t})=>{const r=YU(e),n=t.gitUrl;return{plugin:{name:r.name,gitUrl:n,gitRef:t.gitRef,gitPath:t.gitPath,marketplace:{name:r.marketplaceName,gitUrl:n,gitRef:t.gitRef}},isEnabled:!0}}));let s=[];if(n.length>0)try{const e=n.map((e=>{const t=YU(e.key);return new JD.vwy({name:t.name,marketplaceName:t.marketplaceName})})),t=await r.resolvePluginsByRef(new JD.WvV({refs:e,...eB}));s=t.plugins?.map((e=>({plugin:e,isEnabled:!0})))??[]}catch{}return{plugins:[...o,...s]}}catch{return{plugins:[]}}}),{marketplaceCacheRoot:t,listOptions:{allowedMarketplaceNames:["cursor-public"]},downloadPluginContent:n,contentRetries:o.forListing("project")});return[{client:i,userId:"",cacheManager:new hh(e.userHomeDirectory),pruneOldVersions:!0},{client:c,userId:"",cacheManager:new hh(e.userHomeDirectory),pruneOldVersions:!0}]}({dashboardTransport:e.dashboardTransport,workspacePath:i,userHomeDirectory:t}):void 0),h=rB(d),p=new UD(void 0!==i?[i]:[],t,(()=>({importThirdPartyPlugins:r,loadCursorFirstParty:c})),d,n);let f=[];const m=[...u];try{f=await p.getAllEnabledPlugins()}catch(e){m.push({stage:"resolution",source:"plugin-loader",message:e instanceof Error?`Failed to load plugins: ${e.message}`:`Failed to load plugins: ${String(e)}`,detail:e})}l.length>0&&!h&&m.push({stage:"resolution",source:"plugin-loader",message:"Project plugin entries were discovered, but no marketplace-backed project plugin source was configured. Those entries remain available through discoveredEntries only.",detail:{workspacePath:i,discoveredEntryCount:l.length}});const g={kind:BO,discoveredEntries:l,loadedPlugins:f,loadFailures:p.getLoadFailures(),bootstrapFailures:m,pluginsService:p,async dispose(){}};for(const e of m)SO.Jz.warn("[local-plugins-bootstrap] Plugin bootstrap failure:",{workspacePath:i,stage:e.stage,source:e.source,message:e.message,detail:e.detail});for(const e of g.loadFailures)SO.Jz.warn("[local-plugins-bootstrap] Plugin load failure:",{workspacePath:i,pluginName:e.pluginName,pluginId:e.pluginId,marketplaceName:e.marketplaceName,errorType:e.errorType,errorMessage:e.errorMessage});return[g]}}}function rB(e){return void 0!==e&&(!Array.isArray(e)||e.length>0)}class nB{async getAllCursorRules(e){return[]}reload(e){}dispose(){}onDidChangeRules(e){return()=>{}}}const oB=["projectFolder","terminalsFolder","agentSharedNotesFolder","agentConversationNotesFolder","agentTranscriptsFolder","processWorkingDirectory","artifactsFolder"];function sB(e){if(e.length<=1)return e;let t=e.length;for(;t>1&&("/"===(r=e[t-1])||"\\"===r)&&(3!==t||":"!==e[1]);)t-=1;var r;return e.slice(0,t)}function iB(e){const t=sB(e).replaceAll("\\","/");return/^[A-Za-z]:\/$/.test(t)?t.slice(0,-1):t}function aB(e){const t=sB(e.reportedWorkspacePath);if(""===e.suffix)return t;const r=t.replaceAll("\\","/"),n="/"===r?e.suffix:`${r}${e.suffix}`;return t.includes("\\")?n.replaceAll("/","\\"):n}function cB(e){const t=iB(e.value),r=e.roots.filter((e=>e.host.length>0)).sort(((e,t)=>iB(t.host).length-iB(e.host).length));for(const e of r){const r=iB(e.host);if(t===r)return aB({reportedWorkspacePath:e.reported,suffix:""});const n="/"===r?"/":`${r}/`;if(t.startsWith(n)){const n="/"===r?t:t.slice(r.length);return aB({reportedWorkspacePath:e.reported,suffix:n})}}}const lB={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1};class uB extends sD{constructor(e,t){super(e),this.sessionMcpLease=t}async dispose(){try{await super.dispose()}finally{await mj(this.sessionMcpLease)}}}function dB(e){const t=new _y;return{async createResources(r){const n=e.createSessionDependencies?.(r)??{pendingDecisionStore:e.pendingDecisionStore,fileChangeTracker:e.fileChangeTracker,permissionsService:e.permissionsService};if(!n.pendingDecisionStore||!n.fileChangeTracker||!n.permissionsService)throw new Error("Local resource provider factory requires either shared dependencies or a per-session dependency factory.");const o=r.workspaceServices.cursorRulesService??new nB,s=r.workspaceServices.subagentsService??new Sg,i=r.workspaceServices.mcpLease??new tI,a=!0===r.options.excludeProjectMcp,c=void 0!==r.options.mcpServersOverride||a?void 0!==e.createSessionMcpLease?await e.createSessionMcpLease(r,r.options.mcpServersOverride):a?new tI:void 0:void 0,l=(u=c??i,0===(d=r.options.extraMcpTools??[]).length?u:"onDidChange"in(h=u)&&"function"==typeof h.onDidChange?new zw(u,d):new qw(u,d));var u,d,h;try{const i=await async function(e,t){return void 0===e?{}:"function"==typeof e?await e({sessionId:t.sessionState.sessionId,metadata:t.metadata}):e}(r.options.localResourceProviderOptions,r),a=await async function(e){if(void 0===e)return lB;try{const t=await e();return{powershellUtf8Console:t.powershellUtf8Console,powershellUtf8ChildEnv:t.powershellUtf8ChildEnv}}catch{return lB}}(e.getPowershellUtf8Options),u={pendingDecisionStore:n.pendingDecisionStore,fileChangeTracker:n.fileChangeTracker,gitExecutor:t,ignoreService:e.ignoreService,grepProvider:e.grepProvider,permissionsService:n.permissionsService,workspacePaths:e.workspacePaths,diagnosticsProvider:e.diagnosticsProvider,mcpLease:l,mcpStateAccessor:e.createMcpStateAccessor?.(l,r.options),cursorRulesService:o,subagentsService:s,repositoryProvider:e.repositoryProvider,projectDir:e.projectDir,shellManager:e.shellManager,_defaultSandboxPolicy:e.defaultSandboxPolicy??{type:"insecure_none"},_defaultSandboxPolicySources:e.defaultSandboxPolicySources,getSandboxEnabled:e.getSandboxEnabled,getSandboxSupported:e.getSandboxSupported,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:e.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:e.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:e.getMockPromptTime,mcpFileOutputThresholdBytes:e.mcpFileOutputThresholdBytes,mcpMetaToolEnabled:e.mcpMetaToolEnabled,attributionConfigProvider:e.attributionConfigProvider,getAgentSkills:r.workspaceServices.getAgentSkills,powershellUtf8Console:a.powershellUtf8Console,powershellUtf8ChildEnv:a.powershellUtf8ChildEnv,...i},d=void 0===c?new sD(u):new uB(u,c);return void 0===r.options.reportedWorkspacePath&&void 0===r.options.reportedProjectFolder||function(e,t){const r=e.get($r);if(void 0===r)return;const{reportedWorkspacePath:n,reportedProjectFolder:o}=t,s=void 0===n?[]:t.workspacePaths.map((e=>({host:e,reported:n}))),i=o??n;void 0!==i&&s.push({host:t.projectDir,reported:i}),e.register($r,{execute:async(e,t,o)=>function(e,t){if("success"!==e.result.case||void 0===e.result.value.requestContext?.env)return e;const r=e.clone();if("success"!==r.result.case)return e;const n=r.result.value.requestContext?.env;if(void 0===n)return r;const{roots:o,reportedWorkspacePath:s}=t;n.workspacePaths=n.workspacePaths.map((e=>cB({value:e,roots:o})??e));for(const e of oB){const t=n[e];if(void 0===t||""===t)continue;const r=cB({value:t,roots:o});n[e]="processWorkingDirectory"===e&&void 0!==s?r??sB(s):r??t}return r}(await r.execute(e,t,o),{roots:s,reportedWorkspacePath:n})})}(d,{reportedWorkspacePath:r.options.reportedWorkspacePath,reportedProjectFolder:r.options.reportedProjectFolder,workspacePaths:u.workspacePaths,projectDir:u.projectDir}),d}catch(e){throw await mj(c),e}}}}const hB=["cursorRulesService","getAgentSkills","subagentsService"],pB=new WeakSet;function fB(e){("object"==typeof e&&null!==e||"function"==typeof e)&&pB.add(e)}function mB(e){return("object"==typeof e&&null!==e||"function"==typeof e)&&pB.has(e)}function gB(e,t){const r=Object.keys(t).filter((e=>!hB.includes(e)));if(r.length>0)throw new Error(`Workspace service contributors may only provide ${hB.join(", ")}. Received unsupported service keys: ${r.join(", ")}.`);for(const r of hB)Object.hasOwn(t,r)&&(e[r]=t[r])}async function wB(e,t,r){const __p=e=>{try{globalThis[Symbol.for("@cursor/sdk.startupPhase")]?.(e)}catch{}};const n={config:void 0,plugins:[],pluginBootstrapOutputs:[],cursorRulesService:void 0,getAgentSkills:void 0,subagentsService:void 0,mcpLease:void 0,hooksRuntime:void 0};try{n.config=e.config?await e.config.loadConfig(t):void 0,(e.plugins||e.pluginBootstrap)&&__p("plugins"),n.plugins=e.plugins?await e.plugins.loadPlugins(t):[];const o=()=>({workspaceState:t,policy:r,services:n});n.pluginBootstrapOutputs=e.pluginBootstrap?await e.pluginBootstrap.loadPluginBootstrapOutputs(o()):n.pluginBootstrapOutputs,e.mcp&&__p("mcp"),n.mcpLease=e.mcp?await e.mcp.createLease(o()):void 0,e.hooks&&__p("hooks"),n.hooksRuntime=e.hooks?await e.hooks.createHooksRuntime(o()):void 0,e.localExtensibility&&__p("skills"),e.localExtensibility?.prepareLocalExtensibility&&await e.localExtensibility.prepareLocalExtensibility(o());const s=e.localExtensibility?await e.localExtensibility.loadLocalExtensibility(o()):void 0;void 0!==s&&(fB(s.cursorRulesService),fB(s.subagentsService),Object.assign(n,s));for(const t of e.workspaceServicesContributors??[]){const e=await t.contributeServices(o());void 0!==e&&gB(n,e)}return __p("connecting"),n}catch(t){try{await yB(n,{disposeLocalExtensibility:void 0===e.localExtensibility?void 0:()=>e.localExtensibility?.disposeLocalExtensibility?.()})}catch(e){throw function(e,t){return new AggregateError([t],"Workspace service loading failed and resource cleanup also failed.",{cause:e})}(t,e)}throw t}}async function yB(e,t){const r=t?.preserveSharedContributorsFrom;let n;const o=async e=>{try{await mj(e)}catch(e){n??=e}};if(e.subagentsService===r?.subagentsService||mB(e.subagentsService)||await o(e.subagentsService),e.cursorRulesService===r?.cursorRulesService||mB(e.cursorRulesService)||await o(e.cursorRulesService),t?.disposeLocalExtensibility)try{await t.disposeLocalExtensibility()}catch(e){n??=e}await o(e.hooksRuntime),await o(e.mcpLease);try{await async function(e){let t;for(let r=e.length-1;r>=0;r-=1)try{await mj(e[r])}catch(e){t??=e}if(void 0!==t)throw t}(e.pluginBootstrapOutputs)}catch(e){n??=e}if(void 0!==n)throw n}const vB=["project","user","team","mdm","plugins"],bB=new Set([...vB,"all"]);function SB(e){if(void 0===e||0===e.length)return _B([]);for(const t of e)if(!bB.has(t))throw new Error(`Unsupported setting source "${t}"`);if(e.includes("all")){if(e.length>1)throw new Error('settingSources cannot mix "all" with individual setting sources');return{..._B(vB),all:!0}}return _B(e.filter((e=>"all"!==e)))}function kB(e,t){return e[t]}function _B(e){const t=new Set(e);return{project:t.has("project"),user:t.has("user"),team:t.has("team"),mdm:t.has("mdm"),plugins:t.has("plugins"),all:!1}}const CB=Object.freeze({}),EB=Object.freeze({allowMcpServers:!0,allowPlugins:!0,allowBackgroundSessions:!0,requireMcpApproval:!1,maxParallelSessions:void 0,sandboxMode:void 0,metadata:CB});async function xB(e){const t=new Set;let r;for(let n=e.length-1;n>=0;n-=1){const o=e[n];if(!t.has(o)){t.add(o);try{await mj(o)}catch(e){r??=e}}}if(void 0!==r)throw r}async function PB(e={}){const t=function(e={}){return{workspace:e.workspace??yO,config:e.config,plugins:e.plugins,pluginBootstrap:e.pluginBootstrap,mcp:e.mcp,hooks:e.hooks,localExtensibility:e.localExtensibility,resourceFactory:e.resourceFactory,resourceWrappers:e.resourceWrappers,workspaceServicesContributors:e.workspaceServicesContributors,lifecycle:e.lifecycle}}(e.adapters),r=await t.workspace.resolveWorkspaceState({workingDirectory:e.workingDirectory,projectRoot:e.projectRoot,projectDirectory:e.projectDirectory,workspaceRoots:e.workspaceRoots}),n=await async function(e,t){return e.resolvePolicy(t)}(e.policyAdapter??function(e={}){const t=Object.freeze({...EB.metadata,...e.metadata}),r={...EB,...e,metadata:t};return{name:"permissive-sdk-local",resolvePolicy:()=>r}}(),{workspaceState:r});let o=await wB(t,r,n),s=!1,i=Promise.resolve();const a=e=>{const t=i.then(e);return i=t.catch((()=>{})),t},c=t.localExtensibility,l=void 0===c?void 0:()=>c.disposeLocalExtensibility?.();return{state:r,get services(){return o},policy:n,async createSessionRuntime(e={}){if(s)throw new Error("Cannot create a session runtime after the workspace runtime has been disposed.");return async function(e){const t={sessionId:e.options?.sessionId??(0,ge.C)(),createdAt:new Date},r=Object.freeze({...e.options?.metadata??{}}),n={options:e.options??{},workspaceState:e.workspaceState,workspaceServices:e.workspaceServices,policy:e.policy,sessionState:t,metadata:r,getAgentSkills:e.workspaceServices.getAgentSkills};let o,s;const i=[];try{o=e.adapters.resourceFactory?await e.adapters.resourceFactory.createResources(n):void 0,s=o,i.push(o);for(const t of e.adapters.resourceWrappers??[])s=await t.wrapResources({...n,baseResources:o,resources:s}),i.push(s);await(e.adapters.lifecycle?.onSessionCreated?.(t))}catch(e){try{await xB(i)}catch(t){throw function(e,t){return new AggregateError([t],"Session creation failed and resource cleanup also failed.",{cause:e})}(e,t)}throw e}let a=!1;return{state:t,resources:{base:o,wrapped:s},metadata:r,workspaceServices:e.workspaceServices,policy:e.policy,async dispose(){if(!a){a=!0;try{await xB(i)}finally{await(e.adapters.lifecycle?.onSessionDisposed?.(t))}}}}}({options:e,workspaceState:r,workspaceServices:o,policy:n,adapters:t})},async reload(){s||await a((async()=>{if(s)return;const e=o,i=await wB(t,r,n);s?await yB(i,{disposeLocalExtensibility:l}):(o=i,await yB(e,{preserveSharedContributorsFrom:i,disposeLocalExtensibility:l}),await(t.lifecycle?.onWorkspaceReload?.(r)))}))},async dispose(){s||(s=!0,await a((async()=>{try{await yB(o,{disposeLocalExtensibility:l})}finally{await(t.lifecycle?.dispose())}})))}}}class RB{async requestApproval(e){return{approved:!0}}}class IB{constructor(e,t,r,n){this.approvalMode=e,this.userConfiguredPolicy=t,this.teamSettingsService=r,this.respectAdminControls=n}async getPermissions(){const e=!(!this.respectAdminControls||"insecure_none"===this.userConfiguredPolicy.type)&&(await this.teamSettingsService.getSandboxingControls()).sandboxingDisabled;return{allow:[],deny:[],approvalMode:this.approvalMode,userConfiguredPolicy:e?{type:"insecure_none"}:this.userConfiguredPolicy}}async updatePermissions(){}}class TB{async open(e,t){}async getDiagnostics(e,t){return[]}}class AB{async getCodebaseReference(e,t){}}class $B{constructor(e,t){this.inner=e,this.allowlistReports=t}async getState(e){const t=await this.inner.getState(e);return await this.reportAllowlists(e),{...t,servers:t.servers.filter((e=>"needsAuth"!==e.status))}}async reportAllowlists(e){if(void 0===this.allowlistReports)return;const{mcpLease:t,onMcpAllowlistInUse:r,onMcpServerBlockedByAllowlist:n}=this.allowlistReports;let o;try{o=await t.getClients(e)}catch(e){return void SO.Jz.warn("[sdk-mcp-state] Could not read the MCP allowlist in use:",e)}for(const[e,t]of Object.entries(o))try{if(void 0!==r){const n=await(t.getAllowlistInUse?.());void 0!==n&&r({serverName:e,allowlist:n})}if(void 0!==n){const r=await(t.getAllowlistRefusal?.());void 0!==r&&n({serverName:e,refusal:r})}}catch(e){SO.Jz.warn("[sdk-mcp-state] Could not read the MCP allowlist in use:",e)}}}class MB{constructor(e){this.subagents=e.map((e=>new vg.zz({fullPath:`sdk-inline://${e.name}`,name:e.name,description:e.description,tools:[],model:e.model,prompt:e.prompt,permissionMode:vg.b$.DEFAULT,isBackground:!1,source:"sdk"})))}async getAllSubagents(){return this.subagents}async reload(){return this.subagents}}class DB{constructor(e={}){this.options=e,this.states=new Map,this.runCounterBySession=new Map,this.dispatchQueueBySession=new Map,this.dispatchInProgress=new Set,this.releaseRequestedBySession=new Set}getState(e){return this.states.get(e)??{status:"idle"}}isBusy(e){return"idle"!==this.getState(e).status}startRun(e,t){const r=this.nextRunId(e);return this.enqueueEvent(e,{type:"startRun",runId:r,abort:t?.abort}),r}queueResume(e,t){this.enqueueEvent(e,{type:"queueResume",queuedResume:t.queuedResume,targetRunId:t.targetRunId,mergeQueuedResume:t.mergeQueuedResume})}finishRun(e,t){this.enqueueEvent(e,{type:"runFinished",runId:t})}clearQueuedResume(e){this.enqueueEvent(e,{type:"clearQueuedResume"})}abort(e){this.enqueueEvent(e,{type:"abort"})}release(e){this.enqueueEvent(e,{type:"release"})}nextRunId(e){const t=(this.runCounterBySession.get(e)??0)+1;return this.runCounterBySession.set(e,t),t}enqueueEvent(e,t){const r=this.dispatchQueueBySession.get(e)??[];r.push(t),this.dispatchQueueBySession.set(e,r),this.drainEventQueue(e)}drainEventQueue(e){if(this.dispatchInProgress.has(e))return;let t;this.dispatchInProgress.add(e);try{const r=this.dispatchQueueBySession.get(e);if(!r)return;for(;r.length>0;){const n=r.shift();if(n)try{this.processEvent(e,n)}catch(e){t??=e}}}finally{this.dispatchQueueBySession.delete(e),this.dispatchInProgress.delete(e)}if(t)throw t}processEvent(e,t){const r=this.getState(e),{nextState:n,effects:o}=function(e,t){switch(e.status){case"idle":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"running",runId:t.runId,abort:t.abort},effects:[]};case"queueResume":return void 0===t.targetRunId?{nextState:e,effects:[]}:{nextState:{status:"runningWithQueuedResume",runId:t.targetRunId,queuedResume:t.queuedResume},effects:[]};case"runFinished":case"clearQueuedResume":case"abort":case"release":return{nextState:e,effects:[]};default:throw new Error(`Unhandled idle-state event: ${String(t)}`)}}(e,t);case"running":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"running",runId:t.runId,abort:t.abort},effects:[{type:"abortActiveRun",abort:e.abort}]};case"queueResume":return{nextState:{status:"runningWithQueuedResume",runId:e.runId,abort:e.abort,queuedResume:t.queuedResume},effects:[]};case"runFinished":return t.runId!==e.runId?{nextState:e,effects:[]}:{nextState:{status:"idle"},effects:[]};case"clearQueuedResume":case"release":return{nextState:e,effects:[]};case"abort":return{nextState:{status:"idle"},effects:[{type:"abortActiveRun",abort:e.abort}]};default:throw new Error(`Unhandled running-state event: ${String(t)}`)}}(e,t);case"runningWithQueuedResume":return function(e,t){switch(t.type){case"startRun":return{nextState:{status:"runningWithQueuedResume",runId:t.runId,abort:t.abort,queuedResume:e.queuedResume},effects:[{type:"abortActiveRun",abort:e.abort}]};case"queueResume":return{nextState:{...e,queuedResume:t.mergeQueuedResume(e.queuedResume,t.queuedResume)},effects:[]};case"runFinished":return t.runId!==e.runId?{nextState:e,effects:[]}:{nextState:{status:"running",runId:e.runId,abort:e.abort},effects:[{type:"startQueuedRun",sourceRunId:e.runId,queuedResume:e.queuedResume}]};case"clearQueuedResume":return{nextState:{status:"running",runId:e.runId,abort:e.abort},effects:[]};case"abort":return{nextState:{status:"idle"},effects:[{type:"abortActiveRun",abort:e.abort}]};case"release":return{nextState:e,effects:[]};default:throw new Error(`Unhandled runningWithQueuedResume-state event: ${String(t)}`)}}(e,t);default:return{nextState:e,effects:[]}}}(r,t);this.states.set(e,n),this.options.onStateChange?.({sessionId:e,previousState:r,nextState:n});for(const t of o)switch(t.type){case"abortActiveRun":t.abort?.();break;case"startQueuedRun":this.options.onQueuedRunReady?.({sessionId:e,sourceRunId:t.sourceRunId,queuedResume:t.queuedResume});break;default:throw new Error(`Unhandled lifecycle manager effect: ${String(t)}`)}const s=this.getState(e);"release"===t.type&&"idle"!==s.status&&this.releaseRequestedBySession.add(e),"idle"!==s.status||"release"!==t.type&&!this.releaseRequestedBySession.has(e)||(this.states.delete(e),this.runCounterBySession.delete(e),this.releaseRequestedBySession.delete(e))}}function OB(e){return"string"==typeof e&&e.trim().length>0}function FB(e,t){return new he.jn({command:t.command??"",workingDirectory:t.workingDirectory??"",error:e,isReadonly:!0})}function NB(e){return{execute:async(t,r)=>new MI.v3({result:{case:"permissionDenied",value:new MI.U7({path:r.path,error:e,isReadonly:!0})}})}}function LB(e){return{execute:async(t,r)=>new jw.Pi({result:{case:"permissionDenied",value:new jw.QG({path:r.path,clientVisibleError:e,isReadonly:!0})}})}}function jB(e){return{execute:async(t,r)=>new Ac.iz({result:{case:"permissionDenied",value:new Ac.HQ({error:`${e} Tool: ${r.name}`,isReadonly:!0})}})}}var UB=r("../agent-kv/dist/subagent-states.js");let BB;function WB(e){const t=process.env.CURSOR_DATA_DIR;if(t?.trim())return _o(e);let r;try{r=(0,o.homedir)()}catch{r=void 0}return function(e){const t=e.cursorDataDir?.trim();return t?(0,s.join)(t,"projects",(0,So.r_)(e.workspacePath)):void 0!==e.homeDir&&function(e){if(""===e.trim())return!1;try{return!!(0,xo.statSync)(e).isDirectory()&&((0,xo.accessSync)(e,xo.constants.W_OK),!0)}catch{return!1}}(e.homeDir)?(0,s.join)(e.homeDir,".cursor","projects",(0,So.r_)(e.workspacePath)):(0,s.join)(e.ensureFallbackRoot(e.tempDir),(0,So.r_)(e.workspacePath))}({workspacePath:e,homeDir:r,tempDir:(0,o.tmpdir)(),ensureFallbackRoot:e=>(void 0===BB&&(BB=function(e){return(0,xo.mkdtempSync)((0,s.join)(e,"cursor-transcripts-"))}(e)),BB)})}async function HB(e,t){const r=(0,s.dirname)(e);await(0,Co.mkdir)(r,{recursive:!0}),await(0,Co.writeFile)(e,t,"utf-8")}class qB{constructor(e){this.writeChain=Promise.resolve(),this.workspacePath=e.workspacePath,this.conversationId=e.conversationId,this.parentConversationId=e.parentConversationId,this.blobStore=e.blobStore,this.projectDir=WB(this.workspacePath);const t=this.parentConversationId?(e,t)=>{const r=DF({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,r)}:void 0;this.transcriptStore=new uN(this.projectDir,e.blobStore,HB,{writeText:!1,writeJsonl:!0,...t?{pathResolver:t}:{}}),this.nestedSubagentTranscriptStore=new uN(this.projectDir,e.blobStore,HB,{writeText:!1,writeJsonl:!0,pathResolver:(e,t)=>{const r=DF({conversationId:e,ext:t,kind:"subagent",parentConversationId:this.conversationId});return(0,s.join)(this.projectDir,r)}})}enqueueWrite(e,t){const r=this.writeChain;return this.writeChain=r.then((async()=>{try{await e()}catch(e){SO.Jz.warn(`${t} ${e instanceof Error?e.message:String(e)}`)}})),this.writeChain}async writeFromState(e,t){return this.enqueueWrite((async()=>{await this.transcriptStore.writeFromStateFull(e,t,this.conversationId);const r=await(0,UB.Vn)(e,t,this.blobStore);for(const[t,n]of Object.entries(r))n?.conversationState&&await this.nestedSubagentTranscriptStore.writeFromStateFull(e,n.conversationState,t)}),"[LocalTranscriptWriter] Failed to write transcript:")}async writeTurnEndedFromState(e,t,r){return this.enqueueWrite((async()=>{await this.transcriptStore.writeFromStateFull(e,t,this.conversationId,{turnEnded:r})}),"[LocalTranscriptWriter] Failed to write turn-ended transcript:")}waitForPendingWrites(){return this.writeChain}getTranscriptPath(){if(this.parentConversationId){const e=DF({conversationId:this.conversationId,ext:"jsonl",kind:"subagent",parentConversationId:this.parentConversationId});return(0,s.join)(this.projectDir,e)}return function(e,t){const r=DF({conversationId:t,ext:"jsonl",kind:"primary"});return(0,s.join)(WB(e),r)}(this.workspacePath,this.conversationId)}getProjectDir(){return this.projectDir}}const zB=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,GB="User aborted/interrupted manually.";class VB{constructor(e){this.sessions=new Map,this.backgroundRuns=new Map,this.activeForegroundExecutions=new Map,this.backgroundPromises=new Set,this.pendingReleaseSessions=new Set,this.childParentIds=new Map,this.parentChildIds=new Map,this.queuedChildCompletions=new Map,this.childCompletionWaiters=new Map,this.childLineageRequestIds=new Map,this.untrackedParentRequestIds=new Map,this.agentClient=e.agentClient,this.getResources=e.getResources,this.mcpTools=e.mcpTools??[],this.workspacePath=e.workspacePath,this.parentConversationId=e.parentConversationId;const t=e.rootRequestId?.trim();this.rootLineageRequestId=void 0!==t&&t.length>0?t:(0,ge.C)(),this.headers=e.headers,this.endlessRetries=e.endlessRetries,this.onSessionCreated=e.onSessionCreated,this.onInteractionUpdate=e.onInteractionUpdate,this.onSessionCompleted=e.onSessionCompleted,this.onSessionReleased=e.onSessionReleased,this.onSubagentTokenDelta=e.onSubagentTokenDelta,this.lifecycleStore=new DB}async createOrResumeSession(e,t){if(t.forkAgentId)throw new Error("forkAgentId is not supported in local subagents.");const r=t.resumeAgentId;if(r&&function(e){if(!zB.test(e))throw new Error(`Invalid resumeAgentId format: ${e}`)}(r),r&&!t.prompt)return r;if(r&&OB(t.prompt)&&this.isBackgroundRunBusy(r))throw new Error("Sub-agent is currently running. You may send the follow-up message when it has completed.");if(r&&this.sessions.get(r))return r;const n=r??(0,ge.C)(),o=function(e){const t=new re.We,r=(0,kO.sh)(e),n=new kO.pH(new re.ve,t);return n.setMetadata("agentId",r.agentId),n.setMetadata("latestRootBlobId",r.latestRootBlobId),n.setMetadata("name",r.name),n.setMetadata("createdAt",r.createdAt),n.setMetadata("mode",r.mode),n.setMetadata("isRunEverything",r.isRunEverything),n.setMetadata("lastUsedModel",r.lastUsedModel),n.setMetadata("lastDebugServerPort",r.lastDebugServerPort),n.setMetadata("currentPlanUri",r.currentPlanUri),n.setMetadata("subagentInfo",r.subagentInfo),n.setMetadata("blobEncryptionKey",r.blobEncryptionKey),n}(n),s=new qB({workspacePath:this.workspacePath,conversationId:n,parentConversationId:this.parentConversationId,blobStore:o.getBlobStore()});return this.sessions.set(n,{agentStore:o,transcriptWriter:s,toolCallId:t.toolCallId}),this.onSessionCreated?.({agentId:n,toolCallId:t.toolCallId,subagentType:t.subagentType,parentAgentId:t.parentConversationId}),n}async runSession(e,t,r,n){if(this.isAwaitBackgroundMode(r))return this.awaitBackgroundRun(r.resumeAgentId,e.signal);const o=this.sessions.get(t);if(!o)return{status:"error",error:`Subagent session not found: ${t}`};if(r.runInBackground){const[n,s]=e.withDetached().withCancel();return this.registerBackgroundRun(t,this.executeSubagent(n,t,r,o),r.parentConversationId,s),{status:"background",backgroundReason:vg.qL.AGENT_REQUEST,toolCallCount:0}}const[s,i]=e.withDetached().withCancel();let a=!1;const c=()=>{a||i()};e.signal.addEventListener("abort",c,{once:!0}),e.signal.aborted&&c();let l=()=>{};const u=new Promise((e=>{l=e})),d={requestBackground:()=>!!a||!s.signal.aborted&&(a=!0,e.signal.removeEventListener("abort",c),l(),!0)};this.activeForegroundExecutions.set(r.toolCallId,d),this.activeForegroundExecutions.set(t,d);try{const e=this.executeSubagent(s,t,r,o),n=await Promise.race([e.then((e=>({handedOff:!1,outcome:e}))),u.then((()=>({handedOff:!0})))]);return n.handedOff?(this.registerBackgroundRun(t,e,r.parentConversationId,i),{status:"background",backgroundReason:vg.qL.USER_REQUEST,toolCallCount:0}):(this.onSessionCompleted?.(t,n.outcome),n.outcome)}finally{this.clearForegroundExecution(r.toolCallId,d),this.clearForegroundExecution(t,d),a||e.signal.removeEventListener("abort",c)}}forceBackgroundByToolCallId(e){const t=this.activeForegroundExecutions.get(e);return t?.requestBackground()?new oo.a3({status:oo.jh.ACCEPTED}):new oo.a3({status:oo.jh.NOT_FOUND})}clearForegroundExecution(e,t){this.activeForegroundExecutions.get(e)===t&&this.activeForegroundExecutions.delete(e)}releaseSession(e){this.lifecycleStore.release(e),this.isBackgroundRunBusy(e)?this.pendingReleaseSessions.add(e):this.cleanupSession(e)}async awaitBackgroundWorkers(){for(;this.backgroundPromises.size>0;)await Promise.allSettled([...this.backgroundPromises])}async waitForBackgroundCompletions(e,t){return this.collectAvailableChildCompletions(e,t)}isBackgroundRunBusy(e){return this.lifecycleStore.isBusy(e)||this.backgroundRuns.has(e)}registerBackgroundRun(e,t,r,n){this.registerParentChildLink(e,r);const o=this.lifecycleStore.startRun(e,{abort:n}),s=t.catch((e=>({status:"error",error:e instanceof Error?e.message:String(e)}))),i={runId:o,promise:s};this.backgroundRuns.set(e,i),this.backgroundPromises.add(s),s.then((t=>{this.lifecycleStore.finishRun(e,o);const r=this.backgroundRuns.get(e);if(r?.runId===o){this.backgroundRuns.delete(e),this.enqueueChildCompletion(e,o,t),this.maybeCleanupReleasedSession(e);try{this.onSessionCompleted?.(e,t)}catch(t){SO.Jz.error("[LocalSubagentHostAdapter] onSessionCompleted threw after background run",{agentId:e,error:t instanceof Error?t.message:String(t)})}}return t})).finally((()=>this.backgroundPromises.delete(s)))}maybeCleanupReleasedSession(e){this.pendingReleaseSessions.has(e)&&!this.isBackgroundRunBusy(e)&&this.cleanupSession(e)}cleanupSession(e){this.pendingReleaseSessions.delete(e);const t=this.sessions.get(e);if(!t)return;const r=this.parentChildIds.get(e);if(r)for(const e of r)this.childParentIds.delete(e);this.removeParentChildLink(e),this.parentChildIds.delete(e),this.queuedChildCompletions.delete(e),this.childCompletionWaiters.delete(e),t.transcriptWriter.waitForPendingWrites().catch((()=>{})),this.sessions.delete(e),this.onSessionReleased?.(e)}async executeSubagent(e,t,r,n){return r.continuationConfig?this.executeSubagentWithContinuation(e,t,r,n,r.continuationConfig):this.executeSubagentOnce(e,t,r,n)}async executeSubagentWithContinuation(e,t,r,n,o){const s=o.maxLoops>0?o.maxLoops:Number.POSITIVE_INFINITY;let i=await this.runContinuationLoop(e,t,r,n,o,s);if(!o.collectBackgroundChildren||"completed"!==i.status)return i;for(let a=0;a<500;a++){if(e.signal.aborted)return{status:"error",error:"Subagent was aborted by the user"};let a;try{a=await this.collectAvailableChildCompletions(t,e.signal)}catch{return{status:"error",error:"Subagent was aborted by the user"}}if(0===a.length)return i;const c=this.buildChildrenCompletedMessage(a,o.childrenCompletedMessageTemplate);if(i=await this.runContinuationLoop(e,t,new oo.Pw({...r,prompt:c,resumeAgentId:t,runInBackground:!1}),n,o,s),"completed"!==i.status)return i}return i}async runContinuationLoop(e,t,r,n,o,s){let i,a,c=0;for(let l=0;l0?(c=0,i=void 0):(c+=1,i=c>=o.idleThreshold?`DONE_${(0,ge.C)().replace(/-/g,"").slice(0,8)}`:void 0)}return a??{status:"error",error:"Subagent continuation exited unexpectedly"}}computeContinuationNudge(e,t,r){return t>=e.idleThreshold&&void 0!==r?e.escapeMessageTemplate.replace("{idle_count}",String(t)).replace("{escape_token}",r):e.nudgeMessage}lineageForChildRun(e){this.childLineageRequestIds.has(e.agentId)||this.childLineageRequestIds.set(e.agentId,(0,ge.C)());const t=e.parentConversationId?.trim()??"",r=e.toolCallId.trim();return{parentRequestId:""===t||t===this.parentConversationId?this.rootLineageRequestId:this.childLineageRequestIds.get(t)??this.untrackedParentRequestId(t),rootParentRequestId:this.rootLineageRequestId,...r.length>0?{parentAgentToolCallId:r}:{}}}untrackedParentRequestId(e){let t=this.untrackedParentRequestIds.get(e);return void 0===t&&(t=(0,ge.C)(),this.untrackedParentRequestIds.set(e,t)),t}async executeSubagentOnce(e,t,r,n){const o=this.lineageForChildRun({agentId:t,parentConversationId:r.parentConversationId,toolCallId:r.toolCallId});let s,a=0;const c=new i.QFf({action:{case:"userMessageAction",value:new i.Vtf({userMessage:new i.RGk({text:r.prompt})})}}),l=new i.Gmx({modelId:r.modelId,displayModelId:r.modelId,displayName:r.modelId});void 0!==r.credentials.case&&(l.credentials=r.credentials);const u=new bO,d={sendUpdate:async(e,r)=>{"tokenDelta"===r.message.case&&this.onSubagentTokenDelta?.(t,r.message.value.tokens),"toolCallStarted"!==r.message.case&&"toolCallCompleted"!==r.message.case&&"partialToolCall"!==r.message.case||this.onInteractionUpdate?.(t,r),"toolCallCompleted"===r.message.case&&a++,"textDelta"===r.message.case&&(s=(s??"")+r.message.value.text)},query:async(e,t)=>function(e){const t=e.query.case;switch(t){case"webSearchRequestQuery":return dr(e.id,"Web search is not supported in local subagent");case"webFetchRequestQuery":return pr(e.id,"Web fetch is not supported in local subagent");case"switchModeRequestQuery":return gr(e.id,"Subagent mode switches are not supported in local subagent");case"askQuestionInteractionQuery":{const t=new Qt.tz({result:{case:"rejected",value:new Qt.ox({reason:"Interactive questions are not supported in local subagent mode"})}});return fr(e.id,t)}default:throw new Error(`Unhandled interaction query type in local subagent: ${String(t)}`)}}(t)},h={handleCheckpoint:async(e,t)=>{await n.agentStore.handleCheckpoint(e,t),n.transcriptWriter.writeFromState(e,t)},getLatestCheckpoint:()=>n.agentStore.getLatestCheckpoint()};try{const i=r.rootParentConversationId?.trim(),p=r.parentConversationId?.trim(),f=void 0!==i&&""!==i?i:void 0!==p&&""!==p?p:t,m=await this.getResources({agentId:t,parentAgentId:r.parentConversationId}),g=r.readonly?new J(m,function(e){const t=[G(HT,NB(e.errorMessage)),G(qT,LB(e.errorMessage)),G(eo,jB(e.errorMessage))];return e.wrapShell&&t.push(G(jT,function(e){return{execute:async(t,r)=>new he.W4({result:{case:"permissionDenied",value:FB(e,r)}})}}(e.errorMessage)),G(ee,function(e){return{async*execute(t,r){yield new he.FI({event:{case:"permissionDenied",value:FB(e,r)}})}}}(e.errorMessage)),G(vA,function(e){return{execute:async(t,r)=>new Do.Lt({result:{case:"permissionDenied",value:FB(e,r)}})}}(e.errorMessage))),e.includeWriteBackgroundShellStdin&&t.push(G(bA,function(e){return{execute:async(t,r)=>new Do.nt({result:{case:"error",value:new Do.Gv({error:e})}})}}(e.errorMessage))),t}({errorMessage:"This operation is not allowed in readonly mode. The subagent was launched with readonly: true, which restricts shell, write, delete, and MCP operations.",wrapShell:!0,includeWriteBackgroundShellStdin:!0})):m;return await this.agentClient.run(e,n.agentStore.getConversationStateStructure(),c,l,d,g,n.agentStore.getBlobStore(),u,h,[...this.mcpTools],{conversationGroupId:f,conversationId:t,...n.transcriptWriter.parentConversationId?{transcriptParentConversationId:n.transcriptWriter.parentConversationId}:{},subagentTypeName:r.subagentType||void 0,...o,headers:CO(n.agentStore.getMetadata("blobEncryptionKey"),this.headers),endlessRetries:this.endlessRetries,subagentModelOverrides:[]}),await n.transcriptWriter.writeTurnEndedFromState(e,n.agentStore.getConversationStateStructure(),e.signal.aborted?{status:"aborted",error:GB}:{status:"success"}),{status:"completed",finalMessage:s,toolCallCount:a}}catch(r){const o=r instanceof Error?r.message:String(r);return SO.Jz.error("[LocalSubagentHostAdapter] Subagent session failed",{agentId:t,error:o}),await n.transcriptWriter.writeTurnEndedFromState(e,n.agentStore.getLatestCheckpoint()??n.agentStore.getConversationStateStructure(),this.getTurnEndedFromError(e,o)),e.signal.aborted?{status:"aborted",error:GB}:{status:"error",error:o}}}getTurnEndedFromError(e,t){return e.signal.aborted?{status:"aborted",error:GB}:{status:"error",error:t}}isAwaitBackgroundMode(e){if(!Boolean(e.resumeAgentId&&!OB(e.prompt)&&e.readonly&&!0!==e.runInBackground))return!1;if(0===(e.parentConversationId??"").trim().length)throw new Error(`Missing parentConversationId for subagent await/status check (subagentId: ${e.resumeAgentId})`);return!0}async awaitBackgroundRun(e,t){const r=this.backgroundRuns.get(e);return r?this.awaitBackgroundEntry(r,t):this.isBackgroundRunBusy(e)?this.awaitBusyLifecycleRun(e,t):{status:"error",error:`No background subagent found for id: ${e}`}}async awaitBackgroundRunBounded(e,t){const r=t.agentId;if(e.signal.aborted)return new oo.zJ({result:{case:"stillRunning",value:new oo.L5({agentId:r})}});const n=this.backgroundRuns.get(r);if(void 0===n){const e=this.takeQueuedChildCompletion(r);return void 0!==e?"success"===e.status?new oo.zJ({result:{case:"complete",value:new oo.bE({agentId:r,finalMessage:e.finalMessage,toolCallCount:e.toolCallCount??0})}}):new oo.zJ({result:{case:"error",value:new oo.Y({agentId:r,error:e.finalMessage||"Subagent was aborted"})}}):this.isBackgroundRunBusy(r)?new oo.zJ({result:{case:"stillRunning",value:new oo.L5({agentId:r})}}):new oo.zJ({result:{case:"notFound",value:new oo.Hq({agentId:r})}})}const[o,s]=e.withTimeoutAndCancel(Math.max(0,t.timeoutMs)),i=await new Promise((e=>{const t=()=>e(void 0);o.signal.addEventListener("abort",t,{once:!0}),n.promise.then(e).finally((()=>{o.signal.removeEventListener("abort",t),s()}))}));return void 0===i||"background"===i.status||e.signal.aborted?new oo.zJ({result:{case:"stillRunning",value:new oo.L5({agentId:r})}}):(this.takeQueuedChildCompletion(r,n.runId),"completed"===i.status?new oo.zJ({result:{case:"complete",value:new oo.bE({agentId:r,finalMessage:i.finalMessage,toolCallCount:i.toolCallCount??0})}}):new oo.zJ({result:{case:"error",value:new oo.Y({agentId:r,error:i.error??"Subagent was aborted"})}}))}takeQueuedChildCompletion(e,t){for(const[r,n]of this.queuedChildCompletions){const o=n.findIndex((r=>r.agentId===e&&(void 0===t||r.runId===t)));if(-1===o)continue;const[s]=n.splice(o,1);return 0===n.length&&this.queuedChildCompletions.delete(r),s}}async awaitBusyLifecycleRun(e,t){for(;this.isBackgroundRunBusy(e);){if(t.aborted)return{status:"error",error:"Await timed out while task is still running"};const r=this.backgroundRuns.get(e);if(r)return this.awaitBackgroundEntry(r,t);await new Promise((e=>setTimeout(e,50)))}return{status:"completed",toolCallCount:0}}async awaitBackgroundEntry(e,t){if(t.aborted)return{status:"error",error:"Await timed out while task is still running"};const r={status:"error",error:"Await timed out while task is still running"};return new Promise((n=>{const o=()=>{n(r)};t.addEventListener("abort",o,{once:!0}),e.promise.then(n).finally((()=>t.removeEventListener("abort",o)))}))}registerParentChildLink(e,t){const r=t?.trim();if(!r||r===e||!this.sessions.has(r)&&r!==this.parentConversationId)return;const n=this.childParentIds.get(e);if(n===r)return;n&&(this.parentChildIds.get(n)?.delete(e),0===(this.parentChildIds.get(n)?.size??0)&&this.parentChildIds.delete(n)),this.childParentIds.set(e,r);const o=this.parentChildIds.get(r)??new Set;o.add(e),this.parentChildIds.set(r,o)}removeParentChildLink(e){const t=this.childParentIds.get(e);if(!t)return;this.childParentIds.delete(e);const r=this.parentChildIds.get(t);r?.delete(e),0===(r?.size??0)&&this.parentChildIds.delete(t)}enqueueChildCompletion(e,t,r){const n=this.childParentIds.get(e);if(!n)return;const o=this.queuedChildCompletions.get(n)??[];o.push({agentId:e,runId:t,status:"completed"===r.status?"success":"error"===r.status?"error":"aborted",finalMessage:"completed"===r.status?r.finalMessage??"":"error"===r.status?r.error:"Subagent was aborted by the user",..."completed"===r.status&&void 0!==r.toolCallCount?{toolCallCount:r.toolCallCount}:{}}),this.queuedChildCompletions.set(n,o),this.removeParentChildLink(e);const s=this.childCompletionWaiters.get(n);if(s){this.childCompletionWaiters.delete(n);for(const e of s)e()}}async collectAvailableChildCompletions(e,t){const r=this.drainChildCompletions(e);return r.length>0?r:this.hasPendingChildSubagents(e)?(await this.waitForChildCompletion(e,t),this.drainChildCompletions(e)):[]}hasPendingChildSubagents(e){return(this.parentChildIds.get(e)?.size??0)>0}drainChildCompletions(e){const t=this.queuedChildCompletions.get(e)??[];return this.queuedChildCompletions.delete(e),t}async waitForChildCompletion(e,t){if(t.aborted)throw new Error("aborted");await new Promise(((r,n)=>{const o=this.childCompletionWaiters.get(e)??new Set,s=()=>{a(),r()},i=()=>{a(),n(new Error("aborted"))},a=()=>{o.delete(s),0===o.size&&this.childCompletionWaiters.delete(e),t.removeEventListener("abort",i)};o.add(s),this.childCompletionWaiters.set(e,o),t.addEventListener("abort",i,{once:!0})}))}buildChildrenCompletedMessage(e,t){const r=e.map((e=>{const t="success"===e.status?"SUCCESS":"FAILED";return`## Agent ${e.agentId} -- ${t}\n\n${e.finalMessage}`})).join("\n\n---\n\n");return t.replace("{summaries}",r)}}var KB=r("../proto/dist/generated/agent/v1/agent_service_connect.js"),JB=r("../proto/dist/generated/agent/v1/requested_model_pb.js"),ZB=r("../proto/dist/generated/agent/v1/selected_context_pb.js"),XB=r("./src/agent/analytics.ts"),QB=r("../proto/dist/generated/agent/v1/todo_tool_pb.js");const YB={[Og.w3.UNSPECIFIED]:"unspecified",[Og.w3.LEFT]:"left",[Og.w3.RIGHT]:"right",[Og.w3.MIDDLE]:"middle",[Og.w3.BACK]:"back",[Og.w3.FORWARD]:"forward"},eW={[Og.Dh.UNSPECIFIED]:"unspecified",[Og.Dh.UP]:"up",[Og.Dh.DOWN]:"down",[Og.Dh.LEFT]:"left",[Og.Dh.RIGHT]:"right"},tW={[Og.EB.UNSPECIFIED]:"unspecified",[Og.EB.TAP]:"tap",[Og.EB.DOWN]:"down",[Og.EB.UP]:"up"};function rW(e){return YB[e]??"unspecified"}function nW(e){return void 0===e?void 0:{x:e.x,y:e.y}}function oW({result:e}){switch(e.case){case"success":return{status:"success",value:{actionCount:e.value.actionCount,durationMs:e.value.durationMs,settleMs:e.value.settleMs,screenshotPath:e.value.screenshotPath,cursorPosition:nW(e.value.cursorPosition),log:e.value.log}};case"error":return{status:"error",error:{message:e.value.error,actionCount:e.value.actionCount,durationMs:e.value.durationMs,screenshotPath:e.value.screenshotPath,log:e.value.log}};default:return}}function sW(e,t){switch(e.message.case){case"textDelta":return{type:"text-delta",text:e.message.value.text};case"thinkingDelta":return{type:"thinking-delta",text:e.message.value.text};case"thinkingCompleted":return{type:"thinking-completed",thinkingDurationMs:e.message.value.thinkingDurationMs};case"userMessageAppended":return{type:"user-message-appended",userMessage:{type:"user_message",session_id:t,text:e.message.value.userMessage?.text??""}};case"tokenDelta":return{type:"token-delta",tokens:e.message.value.tokens};case"summary":return{type:"summary",summary:e.message.value.summary};case"summaryStarted":return{type:"summary-started"};case"summaryCompleted":{const{failed:t,fallback:r}=e.message.value;return{type:"summary-completed",...t?{failed:t}:{},...r?{fallback:r}:{}}}case"shellOutputDelta":return{type:"shell-output-delta",event:e.message.value.event.case?{case:e.message.value.event.case,value:e.message.value.event.value?.toJson?.()??e.message.value.event.value}:{}};case"toolCallStarted":return iW("tool-call-started",e.message.value);case"partialToolCall":return iW("partial-tool-call",e.message.value);case"toolCallCompleted":return iW("tool-call-completed",e.message.value);case"heartbeat":return null;case"turnEnded":{const t=e.message.value;return{type:"turn-ended",...(void 0!==t.inputTokens||void 0!==t.outputTokens||void 0!==t.cacheReadTokens||void 0!==t.cacheWriteTokens)&&{usage:{inputTokens:Number(t.inputTokens??BigInt(0)),outputTokens:Number(t.outputTokens??BigInt(0)),cacheReadTokens:Number(t.cacheReadTokens??BigInt(0)),cacheWriteTokens:Number(t.cacheWriteTokens??BigInt(0)),...t.reasoningTokens&&{reasoningTokens:Number(t.reasoningTokens)}}}}}case"modelCallCompleted":{const t=e.message.value;return{type:"model-call-completed",modelCallId:t.modelCallId,usage:{inputTokens:Number(t.inputTokens),outputTokens:Number(t.outputTokens),cacheReadTokens:Number(t.cacheReadTokens),cacheWriteTokens:Number(t.cacheWriteTokens),...t.reasoningTokens&&{reasoningTokens:Number(t.reasoningTokens)}}}}case"toolCallDelta":{const r=e.message.value,n=r.toolCallDelta;if("taskToolCallDelta"!==n?.delta.case)return null;const o=n.delta.value.interactionUpdate;if(void 0===o)return null;const s=sW(o,t);return null!==s&&function(e){switch(e.type){case"text-delta":case"thinking-delta":case"thinking-completed":case"tool-call-started":case"tool-call-completed":case"partial-tool-call":case"step-started":case"step-completed":case"tool-requests-listed":return!0;default:return!1}}(s)?{type:"tool-call-delta",callId:r.callId,modelCallId:r.modelCallId,taskUpdate:s}:null}case"stepStarted":return{type:"step-started",stepId:Number(e.message.value.stepId)};case"toolRequestsListed":return{type:"tool-requests-listed",callCount:e.message.value.callCount};case"stepCompleted":return{type:"step-completed",stepId:Number(e.message.value.stepId),stepDurationMs:Number(e.message.value.stepDurationMs)};case"postRequestPrompt":case"activeBranchChange":case"feedbackRequest":case"responseComparison":case"contextInjectionState":case"routedModel":case"grokBotNudge":case"thinkingNote":case"voiceCallUtterance":case void 0:return null;default:return e.message,null}}function iW(e,t){const r=function(e){if(!e?.tool)return null;switch(e.tool.case){case"shellToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"shell",args:{command:t.command,...t.workingDirectory?{workingDirectory:t.workingDirectory}:{},...t.timeout?{timeout:t.timeout}:{}},...r?{result:hW(r)}:{}}:null}case"deleteToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"delete",args:{path:t.path},...r?{result:pW(r)}:{}}:null}case"globToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"glob",args:{globPattern:t.globPattern,...t.targetDirectory?{targetDirectory:t.targetDirectory}:{}},...r?{result:fW(r)}:{}}:null}case"grepToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"grep",args:{pattern:t.pattern,...t.path?{path:t.path}:{},...t.glob?{glob:t.glob}:{},...t.outputMode?{outputMode:t.outputMode}:{},...t.contextBefore?{contextBefore:t.contextBefore}:{},...t.contextAfter?{contextAfter:t.contextAfter}:{},...t.context?{context:t.context}:{},...t.caseInsensitive?{caseInsensitive:t.caseInsensitive}:{},...t.type?{type:t.type}:{},...t.headLimit?{headLimit:t.headLimit}:{},...void 0!==t.offset?{offset:t.offset}:{},...t.multiline?{multiline:t.multiline}:{},...t.sort?{sort:t.sort}:{},...t.sortAscending?{sortAscending:t.sortAscending}:{}},...r?{result:mW(r)}:{}}:null}case"readToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"read",args:{path:t.path},...r?{result:wW(r)}:{}}:null}case"editToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"edit",args:{path:t.path},...r?{result:yW(r)}:{}}:null}case"lsToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"ls",args:{path:t.path,...t.ignore&&t.ignore.length>0?{ignore:t.ignore}:{}},...r?{result:vW(r)}:{}}:null}case"readLintsToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"readLints",args:{paths:t.paths},...r?{result:SW(r)}:{}}:null}case"mcpToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"mcp",args:{...t.providerIdentifier?{providerIdentifier:t.providerIdentifier}:{},...t.toolName?{toolName:t.toolName}:{},...t.args?{args:Object.fromEntries(Object.entries(t.args).map((([e,t])=>[e,t.toJson()])))}:{}},...r?{result:kW(r)}:{}}:null}case"generateImageToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"generateImage",args:{description:t.description,...t.filePath?{filePath:t.filePath}:{}},...r?{result:CW(r)}:{}}:null}case"recordScreenToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"recordScreen",args:{mode:EW(t.mode)},...r?{result:xW(r)}:{}}:null}case"semSearchToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"semSearch",args:{query:t.query,...t.targetDirectories&&t.targetDirectories.length>0?{targetDirectories:t.targetDirectories}:{},...t.explanation?{explanation:t.explanation}:{}},...r?{result:_W(r)}:{}}:null}case"createPlanToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"createPlan",args:{plan:t.plan},...r?{result:PW(r)}:{}}:null}case"updateTodosToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"updateTodos",args:{todos:t.todos.map((e=>({content:e.content,status:IW(e.status)})))},...r?{result:RW(r)}:{}}:null}case"fetchToolCall":case"switchModeToolCall":return null;case"computerUseToolCall":return function({args:e,result:t}){return e?{type:"computerUse",args:{actions:e.actions.flatMap((e=>function({action:e}){switch(e.case){case"mouseMove":return{type:"mouseMove",coordinate:nW(e.value.coordinate)};case"click":return{type:"click",coordinate:nW(e.value.coordinate),button:rW(e.value.button),count:e.value.count,modifierKeys:e.value.modifierKeys};case"mouseDown":case"mouseUp":return{type:e.case,button:rW(e.value.button)};case"drag":return{type:"drag",path:e.value.path.map((e=>({x:e.x,y:e.y}))),button:rW(e.value.button),modifierKeys:e.value.modifierKeys};case"scroll":return{type:"scroll",coordinate:nW(e.value.coordinate),direction:eW[e.value.direction]??"unspecified",amount:e.value.amount,modifierKeys:e.value.modifierKeys};case"type":return{type:"type",text:e.value.text};case"key":return{type:"key",key:e.value.key,holdDurationMs:e.value.holdDurationMs,stroke:tW[e.value.stroke]??"unspecified"};case"wait":return{type:"wait",durationMs:e.value.durationMs};case"screenshot":case"cursorPosition":return{type:e.case};default:return}}(e)??[])),description:e.description},result:t?oW(t):void 0}:null}(e.tool.value);case"readTodosToolCall":case"webSearchToolCall":case"listMcpResourcesToolCall":case"readMcpResourceToolCall":return null;case"taskToolCall":{const{args:t,result:r}=e.tool.value;return t?{type:"task",args:aW(t),...r?{result:uW(r)}:{}}:null}case"applyAgentDiffToolCall":case"askQuestionToolCall":case"writeShellStdinToolCall":case"reflectToolCall":case"setupVmEnvironmentToolCall":case"replaceEnvToolCall":case"startGrindExecutionToolCall":case"startGrindPlanningToolCall":case"truncatedToolCall":case"webFetchToolCall":case"reportBugfixResultsToolCall":case"aiAttributionToolCall":case"prManagementToolCall":case"editPrLabelsToolCall":case"fetchCloudAgentDataToolCall":case"mcpAuthToolCall":case"connectScmToolCall":case"searchConversationsToolCall":case"awaitToolCall":case"blameByFilePathToolCall":case"getMcpToolsToolCall":case"reportBugToolCall":case"setActiveBranchToolCall":case"communicateUpdateToolCall":case"sendFinalSummaryToolCall":case"updateOriginPrCodeTourToolCall":case"getOriginPrCodeTourToolCall":case"recordCiInvestigationFindingsToolCall":case"sendMessageToolCall":case"sendToUserToolCall":case"createGoalToolCall":case"updateGoalToolCall":case"getAgentStatusToolCall":case"sendToAgentToolCall":case"readAgentTranscriptToolCall":case"createAgentToolCall":case"createProjectToolCall":case"startProjectUpdatesToolCall":case"stopProjectUpdatesToolCall":case"manageAccessToolCall":case"stopAgentToolCall":case"listTrackedTasksToolCall":case"createTrackedTasksToolCall":case"updateTrackedTasksToolCall":case"deleteTrackedTasksToolCall":case"updateTrackedTaskStatusesToolCall":case"updateTrackedTaskTagsToolCall":case"writeCanvasToolCall":case"readCanvasToolCall":case"generateVideoToolCall":case"xSearchToolCall":case"executeToolCall":case void 0:return null;default:return e.tool}}(t.toolCall);return r?{type:e,callId:t.callId,toolCall:r,modelCallId:t.modelCallId}:null}function aW(e){return{description:e.description??"",prompt:e.prompt??"",...e.subagentType?{subagentType:cW(e.subagentType)}:{},...e.model?{model:e.model}:{},...e.resume?{resume:e.resume}:{},...e.agentId?{agentId:e.agentId}:{},...e.attachments&&e.attachments.length>0?{attachments:e.attachments}:{},...void 0!==e.mode?{mode:lW(e.mode)}:{},...e.respondingToMessageIds&&e.respondingToMessageIds.length>0?{respondingToMessageIds:e.respondingToMessageIds}:{}}}function cW(e){const t=e.type.case;return t?"custom"===t?{kind:t,name:e.type.value.name}:{kind:t}:{kind:"unspecified"}}function lW(e){switch(e){case vg.FL.AGENT:return"agent";case vg.FL.PLAN:return"plan";default:return"unspecified"}}function uW(e){if(e.result?.case)switch(e.result.case){case"success":{const t=e.result.value;return{status:"success",value:{...t.conversationSteps&&t.conversationSteps.length>0?{conversationSteps:t.conversationSteps.map((e=>e.toJson?.()??e))}:{},...t.agentId?{agentId:t.agentId}:{},isBackground:t.isBackground??!1,...void 0!==t.durationMs?{durationMs:Number(t.durationMs)}:{},...t.resultSuffix?{resultSuffix:t.resultSuffix}:{},backgroundReason:dW(t.backgroundReason),...t.transcriptPath?{transcriptPath:t.transcriptPath}:{}}}}case"error":return{status:"error",error:{message:e.result.value.error??"Task failed"}};default:return}}function dW(e){switch(e){case vg.qL.AGENT_REQUEST:return"agentRequest";case vg.qL.USER_REQUEST:return"userRequest";case vg.qL.QUEUED_FOLLOW_UP:return"queuedFollowUp";default:return"unspecified"}}function hW(e){if(e.result?.case)switch(e.result.case){case"success":case"failure":{const t=e.result.value;return{status:"success",value:{exitCode:t.exitCode??0,signal:t.signal??"",stdout:t.stdout??"",stderr:t.stderr??"",executionTime:t.executionTime??0}}}case"timeout":return{status:"error",error:{message:`Command timed out after ${e.result.value.timeoutMs}ms`,command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};case"rejected":return{status:"error",error:{message:e.result.value.reason??"Command rejected",command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};case"spawnError":return{status:"error",error:{message:e.result.value.error??"Failed to spawn command",command:e.result.value.command,workingDirectory:e.result.value.workingDirectory}};default:return}}function pW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{fileSize:Number(e.result.value.fileSize??0)}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.value.clientVisibleError??e.result.case,path:e.result.value.path}}}function fW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{files:e.result.value.files??[],totalFiles:e.result.value.totalFiles??0,clientTruncated:e.result.value.clientTruncated??!1,ripgrepTruncated:e.result.value.ripgrepTruncated??!1}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case}}}function mW(e){if(e.result?.case){if("success"===e.result.case){const t=e.result.value,r={};if(t.workspaceResults)for(const[e,n]of Object.entries(t.workspaceResults))r[e]=gW(n);return{status:"success",value:{...Object.keys(r).length>0?{workspaceResults:r}:{},...t.activeEditorResult?{activeEditorResult:gW(t.activeEditorResult)}:{}}}}return{status:"error",error:{message:e.result.value.error??e.result.case}}}}function gW(e){if(e?.result?.case)switch(e.result.case){case"content":return{type:"content",output:{matches:e.result.value.matches?.map((e=>({file:e.file,...void 0!==e.lineNumber?{lineNumber:e.lineNumber}:{},line:e.line,...e.beforeContext?{beforeContext:e.beforeContext}:{},...e.afterContext?{afterContext:e.afterContext}:{}})))??[],totalMatches:e.result.value.totalMatches??0}};case"files":return{type:"files",output:{files:e.result.value.files??[],count:e.result.value.count??0}};case"count":return{type:"count",output:{counts:e.result.value.counts?.map((e=>({file:e.file,count:e.count})))??[],total:e.result.value.total??0}};default:return}}function wW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{content:"content"===e.result.value.output.case?e.result.value.output.value:"",totalLines:e.result.value.totalLines??0,fileSize:Number(e.result.value.fileSize??0)}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case,path:e.result.value.path}}}function yW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{...void 0!==e.result.value.linesAdded?{linesAdded:e.result.value.linesAdded}:{},...void 0!==e.result.value.linesRemoved?{linesRemoved:e.result.value.linesRemoved}:{},...e.result.value.diffString?{diffString:e.result.value.diffString}:{}}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case,path:e.result.value.path}}}function vW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{directoryTreeRoot:bW(e.result.value.directoryTreeRoot)}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function bW(e){if(e)return{absPath:e.absPath??"",childrenDirs:e.childrenDirs?.map(bW)??[],childrenFiles:e.childrenFiles?.map((e=>({name:e.name})))??[],childrenWereProcessed:e.childrenWereProcessed??!1,fullSubtreeExtensionCounts:e.fullSubtreeExtensionCounts??{},numFiles:e.numFiles??0}}function SW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{fileDiagnostics:e.result.value.fileDiagnostics?.map((e=>({path:e.path,diagnostics:e.diagnostics?.map((e=>({severity:TW(e.severity),...e.range?{range:{...e.range.start?{start:{line:e.range.start.line,character:e.range.start.character}}:{},...e.range.end?{end:{line:e.range.end.line,character:e.range.end.character}}:{}}}:{},message:e.message,source:e.source,code:e.code})))??[],diagnosticsCount:e.diagnosticsCount??0})))??[],totalFiles:e.result.value.totalFiles??0,totalDiagnostics:e.result.value.totalDiagnostics??0}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function kW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{content:e.result.value.content?.map((e=>{const t={};return"text"===e.content?.case?t.text={text:e.content.value.text}:"image"===e.content?.case&&(t.image={data:e.content.value.data,...e.content.value.mimeType?{mimeType:e.content.value.mimeType}:{}}),t}))??[],isError:e.result.value.isError??!1}}:{status:"error",error:{message:e.result.value.error??e.result.value.reason??e.result.case}}}function _W(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{results:e.result.value.results??""}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function CW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{filePath:e.result.value.filePath??""}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function EW(e){switch(e){case P$.$u.START_RECORDING:return"START_RECORDING";case P$.$u.SAVE_RECORDING:return"SAVE_RECORDING";case P$.$u.DISCARD_RECORDING:return"DISCARD_RECORDING";default:throw new Error(`Unknown RecordingMode: ${e}`)}}function xW(e){if(e.result?.case)switch(e.result.case){case"startSuccess":return{status:"success",value:{wasPriorRecordingCancelled:e.result.value.wasPriorRecordingCancelled??!1}};case"saveSuccess":return{status:"success",value:{path:e.result.value.path??"",recordingDurationMs:Number(e.result.value.recordingDurationMs??0)}};case"discardSuccess":return{status:"success",value:{}};case"failure":return{status:"error",error:{message:e.result.value.error??"Unknown error"}};default:return}}function PW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function RW(e){if(e.result?.case)return"success"===e.result.case?{status:"success",value:{todos:e.result.value.todos?.map((e=>({content:e.content,status:IW(e.status)})))??[],totalCount:e.result.value.totalCount??0}}:{status:"error",error:{message:e.result.value.error??e.result.case}}}function IW(e){switch(e){case QB.Vj.UNSPECIFIED:case QB.Vj.PENDING:return"pending";case QB.Vj.IN_PROGRESS:return"inProgress";case QB.Vj.COMPLETED:return"completed";case QB.Vj.CANCELLED:return"cancelled";default:return"pending"}}function TW(e){switch(e){case DA.h_.UNSPECIFIED:case DA.h_.ERROR:return"error";case DA.h_.WARNING:return"warning";case DA.h_.INFORMATION:return"information";case DA.h_.HINT:return"hint";default:return"error"}}const AW={type:"object",properties:{},additionalProperties:!0};function $W(e){const t={};for(const[r,n]of Object.entries(e))t[r]=n;return t}function MW(e){return"text"===e.type?new Ac._Z({content:{case:"text",value:new Ac.zN({text:e.text})}}):new Ac._Z({content:{case:"image",value:new Ac.do({data:n.Buffer.from(e.data,"base64"),mimeType:e.mimeType??""})}})}function DW(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var OW=r("./src/agent/errors.ts");const FW="Shell is not available when local.fs is set: the agent's files live in a FileSystem, and a shell would run on the host disk. Use Read, Grep, Glob, LS, and the edit tools instead.";function NW(e){return{async execute(){throw new Error(e)}}}function LW(e){var t;e.register(jT,NW(FW)),e.register(ee,(t=FW,{async*execute(){throw new Error(t)}})),e.register(vA,NW(FW)),e.register(EA,NW(FW)),e.register(bA,NW(FW)),e.register(UT,NW(FW)),e.register(tA,NW("ReadLints is not available when local.fs is set: lint diagnostics come from a host language service, not the FileSystem.")),e.register(GT,NW("Git is not available when local.fs is set: the agent's files live in a FileSystem, not a host git checkout."))}var jW=r("./src/agent/filesystem/executors.ts"),UW=r("./src/agent/filesystem/compose.ts"),BW=r("./src/agent/filesystem/trees.ts"),WW=r("./src/agent/filesystem/walk.ts");const HW="/tmp",qW=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.txt$/i;function zW(e){const{write:t,hostProjectDir:r}=e;return{async execute(e,n,o){const i=function(e){if(t=e.writePath,!/^([/\\]|[A-Za-z]:[/\\])/.test(t))return;var t;const r=function(e){if(void 0===e.hostProjectDir||""===e.hostProjectDir)return;const t=(0,WW.eI)(e.hostProjectDir),r=(0,WW.eI)(e.writePath);return"/"!==t&&(0,WW.hJ)({path:r,prefix:t})?r.slice(t.length):void 0}(e),n=void 0===r?(0,WW.eI)(e.writePath):(0,WW.eI)(`${HW}/${r}`);if(!(0,WW.hJ)({path:n,prefix:HW}))return;const o=s.default.posix.basename(n),i=s.default.posix.join(HW,$c);return s.default.posix.dirname(n)===i&&qW.test(o)?s.default.posix.join(HW,o):n}({writePath:n.path,hostProjectDir:r});if(void 0===i||i===n.path)return await t.execute(e,n,o);const a=n.clone();a.path=i;const c=await t.execute(e,a,o);return"success"===c.result.case&&(c.result.value.path=i),c}}}class GW{constructor(e,t="/"){this.fs=e,this.listeners=new Set,this.workspace=(0,WW.eI)(t)}getAllCursorRules(e){return this.rules??=async function(e,t){const[r,n]=await Promise.all([VW(e,s.posix.join(t,".cursor/rules")),KW(e,s.posix.join(t,"AGENTS.md"))]);return void 0===n?r:[...r,n]}(this.fs,this.workspace),this.rules}reload(e){this.rules=void 0;for(const e of this.listeners)e()}onDidChangeRules(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}dispose(){this.listeners.clear()}}async function VW(e,t){const r=[];try{for await(const n of e.list(t))"directory"!==n.kind&&n.path.endsWith(".mdc")&&r.push(n.path)}catch{return[]}return(await(0,Or.PH)(r,(async t=>{const r=await JW(e,t),n=void 0===r?null:en(r);if(null!==n)return hg({path:t,body:n.body,frontmatter:n.frontmatter,rawFrontmatter:n.rawFrontmatter})}),{max:8})).filter((e=>void 0!==e))}async function KW(e,t){const r=await JW(e,t);if(void 0!==r)return hg({path:t,body:Zr({content:r,filename:"AGENTS.md"}),frontmatter:{alwaysApply:!0}})}async function JW(e,t){try{const r=await e.read(t);return"string"==typeof r?r:(new TextDecoder).decode(r)}catch{return}}const ZW={getAllCursorRules:async()=>[],reload(){},onDidChangeRules:()=>()=>{},dispose(){}},XW={async exec(){throw new Error("git is not available in a FileSystem session")}},QW={isIgnoredByAny:async()=>!1,isGitIgnored:async()=>!1,isCursorIgnored:async()=>!1,isRepoBlocked:async()=>!1,listCursorIgnoreFilesByRoot:async()=>[],getCursorIgnoreMapping:async()=>({}),getShellSandboxIgnoreMapping:async()=>({}),getGitIgnoreMapping:async()=>({}),getRepoBlockExcludeGlobs:async()=>[]};function YW(e){return{cursorRulesService:!0===e.includeProjectRules?new GW(e.fs,e.workspace):ZW,getAgentSkills:async()=>[],subagentsService:e.subagentsService??new Sg,gitExecutor:XW,ignoreService:QW,requestContextIsWorkingDirHomeDir:!1,reportProcessWorkingDirectory:!1}}function eH(e,t){const r=t.workspace??"/",n=(0,jW.c9)(e,{workspace:r});return{localResourceProviderOptions:{overrideReadExecutor:n.read,overrideWriteExecutor:zW({write:n.write,hostProjectDir:t.hostProjectDir}),overrideGrepExecutor:n.grep,overrideLsExecutor:n.ls,overrideDeleteExecutor:n.delete,suppressDefaultShellExecutor:!0,...YW({...t.settings,fs:e,workspace:r})},reportedWorkspacePath:r,reportedProjectFolder:HW,excludeHooks:!0,excludeProjectMcp:!0}}var tH=r("./src/agent/executor-common.ts");class rH{constructor(){this.countsByMode=new Map,this.failureKindsByMode=new Map,this.record=e=>{let t=this.countsByMode.get(e.mode);switch(void 0===t&&(t={mode:e.mode,checked_calls:0,outside_limit_calls:0,settings_unavailable_calls:0,unknown_server_calls:0},this.countsByMode.set(e.mode,t)),e.outcome){case"within_limit":return void(t.checked_calls+=1);case"outside_limit":return t.checked_calls+=1,void(t.outside_limit_calls+=1);case"settings_unavailable":{t.settings_unavailable_calls+=1;const r=e.settingsFailure;if(void 0===r)return;let n=this.failureKindsByMode.get(e.mode);return void 0===n&&(n=new Map,this.failureKindsByMode.set(e.mode,n)),void n.set(r,(n.get(r)??0)+1)}case"unknown_server":return void(t.unknown_server_calls+=1);default:return e.outcome}}}take(){const e=[...this.countsByMode.values()].map((e=>{const t=function(e){let t;for(const[r,n]of e??[])(void 0===t||n>t.calls)&&(t={kind:r,calls:n});return t?.kind}(this.failureKindsByMode.get(e.mode));return void 0===t?e:{...e,settings_unavailable_kind:t}}));return this.countsByMode.clear(),this.failureKindsByMode.clear(),e}}class nH{constructor(e=e=>{console.warn(e)}){this.write=e,this.printed=new Set,this.report=e=>{if(!this.printed.has(e.serverName)){this.printed.add(e.serverName);try{this.write(function(e){return`[cursor-sdk] ${e.refusal}`}(e))}catch{}}}}}const oH=new class{constructor(e=e=>{console.warn(e)}){this.write=e,this.printed=new Set,this.report=e=>{const t=JSON.stringify([e.serverName,(r=e.allowlist,JSON.stringify([r.list,r.name,r.reason,r.allowedServers??null,r.blockedServers??null]))]);var r;if(!this.printed.has(t)){this.printed.size>=1e3&&this.printed.clear(),this.printed.add(t);try{this.write(function(e){return`[cursor-sdk] MCP server "${e.serverName}" is under ${function(e){return`${e.name}, which applies because ${e.reason}.${r=e.allowedServers,void 0===r?"":0===r.length?" Allowed servers: none.":WC("Allowed servers",r)}${t=e.blockedServers,void 0===t||0===t.length?"":WC("Blocked",t)}`;var t,r}(e.allowlist)}`}(e))}catch{}}}}};var sH=r("./src/agent/native/vendored-tree-sitter.ts"),iH=r("./src/agent/platform-package-locator.ts"),aH=r("./src/agent/sdk-config.ts"),cH=r("../../node_modules/.pnpm/@statsig+js-client@3.31.0/node_modules/@statsig/js-client/src/index.js"),lH=r("./src/agent/utils/logger.ts");const uH={checkFeatureGate:()=>!1,getDynamicConfigValue:({defaultValue:e})=>e},dH=new Map;async function hH(e){try{const t=await async function(e){const t=await(0,tH.dC)(e,tH.EV);if(!t)return;const r=tH.EV.endsWith("/")?tH.EV.slice(0,-1):tH.EV,n=await fetch(`${r}/aiserver.v1.AnalyticsService/BootstrapStatsig`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json","x-cursor-client-type":"sdk","x-cursor-client-version":(0,tH.tF)(),"x-ghost-mode":(0,tH.U)(e)},body:JSON.stringify({})});if(!n.ok)return void lH.v.log(`Failed to bootstrap SDK Statsig: ${n.status} ${n.statusText}`);const o=await n.json();return pH(o)&&"string"==typeof o.config&&o.config.length>0?o.config:void 0}(e);if(!t)return uH;const r=new cH.StatsigClient("client-Bm4HJ0aDjXHQVsoACMREyLNxm5p6zzuzhO50MgtoT5D",function(e){try{const r=JSON.parse(e);if(pH(r)&&"object"==typeof(t=r.user)&&null!==t&&!Array.isArray(t))return{...r.user,custom:{...r.user.custom,clientType:"sdk",clientVersion:(0,tH.tF)()}}}catch(e){lH.v.log(`Failed to parse SDK Statsig bootstrap user: ${e instanceof Error?e.message:String(e)}`)}var t;return{custom:{clientType:"sdk",clientVersion:(0,tH.tF)()}}}(t),{disableLogging:!0,disableStorage:!0,networkConfig:{preventAllNetworkTraffic:!0}});return r.dataAdapter.setData(t),r.initializeSync(),{checkFeatureGate:(e,t)=>{try{return r.checkGate(e,t)}catch{return!1}},getDynamicConfigValue({configName:e,paramName:t,defaultValue:n}){try{return r.getDynamicConfig(e).get(t,n)}catch{return n}}}}catch(e){return lH.v.log(`Failed to initialize SDK Statsig: ${e instanceof Error?e.message:String(e)}`),uH}}function pH(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function fH(e){let t;return e?.then((e=>{t=e}),(()=>{})),()=>t?.checkFeatureGate("grok_bot_mcp_app_payment_token_filter",{disableExposureLog:!0})??!1}var mH=r("./src/agent/tools-option.ts");class gH{async requestApproval(){return{approved:!0}}}function wH(e,t){if(!function(e){return void 0!==e&&Object.keys(e).length>0}(t))return;const r=e.resources.base;if(!(r instanceof sD))throw new OW.j1("SDK custom tools require the default local workspace resource provider.",{isRetryable:!1});const n=r.getMcpExecutionPolicyDeps(),o=r.get(eo),s=function(e,t){return{async execute(r,n,o){const s=n.toolName||function(e){const t=`${zn}-`;return e.startsWith(t)?e.slice(t.length):e}(n.name),i=e[s];if(void 0===i)return new Ac.iz({result:{case:"error",value:new Ac.Nh({error:`Unknown custom tool: ${s}`})}});try{return function(e){const t=function(e){return"object"==typeof(t=e)&&null!==t&&!Array.isArray(t)&&"content"in t&&Array.isArray(t.content)?{content:e.content,isError:e.isError,structuredContent:e.structuredContent}:"string"==typeof e?{content:[{type:"text",text:e}]}:{content:[{type:"text",text:JSON.stringify(e)}],structuredContent:DW(e)?e:void 0};var t}(e),r=void 0!==t.structuredContent?we.Struct.fromJson(t.structuredContent):void 0;return new Ac.iz({result:{case:"success",value:new Ac.QW({content:t.content.map(MW),isError:t.isError??!1,structuredContent:r})}})}(await i.execute(function(e){return Object.fromEntries(Object.entries(e.args).map((([e,t])=>[e,t.toJson()])))}(n),{toolCallId:n.toolCallId||void 0,...void 0===t||""===t?{}:{sessionId:t}}))}catch(e){return new Ac.iz({result:{case:"error",value:new Ac.Nh({error:e instanceof Error?e.message:String(e)})}})}}}}(t,e.state.sessionId),i=new gH;e.resources.base.register(eo,{async execute(e,t,r){if(function(e){return e.providerIdentifier===zn}(t)){const o=await ET(e,t,{...n,pendingDecisionProvider:i,toolDef:{source:"internal"}});return void 0!==o?o:s.execute(e,t,r)}return o.execute(e,t,r)}})}const yH=new Set(["127.0.0.1","localhost","[::1]"]);function vH(e){if(void 0===e)return{};const t=e.resourceProviderOptions;return{...void 0!==t?{localResourceProviderOptions:t}:{},...void 0!==e.reportedWorkspacePath?{reportedWorkspacePath:e.reportedWorkspacePath}:{}}}function bH(){const e=process.env.CURSOR_SDK_MOCK_PROMPT_TIME;if(void 0===e||""===e)return;const t=new Date(e);return Number.isNaN(t.getTime())?void 0:t}const SH={warn(){},error(){}},kH={log(){}};class _H{async requestApproval(e){return{approved:!1,reason:`Local SDK runs cannot request interactive approval for ${CH(e)}. Keep the action within the configured sandbox policy or Smart Auto Review's auto-approval boundary, or re-run without sandboxing/autoReview enabled.`}}}function CH(e){switch(e.type){case Lw.Shell:return"this shell command";case Lw.Mcp:return"this MCP tool call";case Lw.Write:return"this file edit";case Lw.Delete:return"this file deletion";default:return"this operation"}}function EH(e){return void 0!==e&&"insecure_none"!==e.type}async function xH(e,t){const r="string"==typeof e||void 0===e?{workingDirectory:e,apiKey:t}:e,a=(0,y.q6)().with(l._O,kH),c=SB(r.settingSources),u=void 0===r.hostMcpBridgeUrls?void 0:r.hostMcpBridgeUrls.filter((e=>{let t;try{t=new URL(e)}catch{t=void 0}const r=void 0!==t&&"http:"===t.protocol&&""===t.username&&""===t.password&&yH.has(t.hostname);return r||console.warn(`[cursor-sdk] ignoring local.hostMcpBridgeUrls entry ${e}: not an http URL on 127.0.0.1, localhost or [::1]`),r}));!function(e){if(void 0!==e&&(!Number.isFinite(e)||e<=0))throw new Error(`Workspace scan cache TTL must be a positive number of milliseconds, got ${e}`);ya=e}((0,aH.Mu)()),/:\/\/(localhost|127\.0\.0\.1)/.test(tH.EV)&&(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0");const d=performance.now();let h=0;if(r.apiKey){const e=performance.now();await Promise.all([(0,tH.ly)(r.apiKey),(0,tH.mU)(r.apiKey)]),h=performance.now()-e}const p=r.workingDirectory||process.cwd();(0,sH.configureVendoredTreeSitterWorkspaceDir)(p);for(const e of r.dirs??[])(0,sH.configureVendoredTreeSitterWorkspaceDir)(e);const f=(0,So.Rv)((0,o.homedir)(),p),m={hostProjectDir:f,settings:{includeProjectRules:kB(c,"project"),subagentsService:new MB(r.customSubagents??[])}};let g;const w="win32"===process.platform?"rg.exe":"rg",v=process.env.CURSOR_RIPGREP_PATH;g=v&&(0,s.isAbsolute)(v)?v:(0,iH.hQ)({binaryName:w,excludedWorkspaceDir:p}),g||(g=(0,Oo.xS)()),g&&(0,Oo.J)(g);let b,S,k,_={getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getAdminCommandDenylist:async()=>({rules:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}};if(r.apiKey)try{const e=(0,tH.qN)(r.apiKey,r.teamId);b=e.transport,S=e.getAccessToken;const t=(0,ye.createClient)(fj.I,b),n=function(e){let t=dH.get(e);return t||(t=hH(e),dH.set(e,t),t.then((r=>{r===uH&&dH.get(e)===t&&dH.delete(e)}),(()=>{dH.get(e)===t&&dH.delete(e)}))),t}(r.apiKey);k=n;const o={getDefaultNetworkAllowlist:async()=>(await n).getDynamicConfigValue({configName:"sandbox_default_network_allowlist",paramName:"allowlist",defaultValue:[]})};_=new gO(new pO(t,{supportsHostMcpBridgeExemption:!0}),o,{...void 0===u?{}:{hostMcpBridgeUrls:u},mcpAdminToolLimitSurvivesFailedRead:!0,isMcpAccessNetworkAllowlistEnabled:async()=>(await n).checkFeatureGate("mcp_access_network_allowlist"),isMcpSettingsOverhaulEnabled:async e=>(await n).checkFeatureGate("mcp_settings_overhaul",e),isWin32UserExtensionStdioUnsandboxEnabled:async e=>(await n).checkFeatureGate("mcp_user_extension_stdio_unsandboxed_win32",e),isAdminCommandDenylistEnforcementKilled:async()=>(await n).checkFeatureGate("admin_command_denylist_enforcement_killswitch")})}catch(e){lH.v.log(`Failed to initialize authenticated dashboard services: ${e instanceof Error?e.message:String(e)}`)}const C=performance.now(),E=r.apiKey?await(0,Oo.tv)(`${(0,o.homedir)()}/.cursor/sandbox.json`,(0,o.homedir)()):void 0,x=void 0!==r.apiKey?await async function(e){const{cwd:t,perUserSandboxPolicy:r,sandboxOptions:n}=e;if(!1===n?.enabled)return{defaultSandboxPolicy:{type:"insecure_none"},defaultSandboxPolicySources:void 0};const o=EH(r)?r:!0===n?.enabled?function(e,t={}){return{type:e,...t}}("workspace_readwrite",{networkPolicy:(0,Oo.Po)()}):void 0;if(void 0===o)return{defaultSandboxPolicy:{type:"insecure_none"},defaultSandboxPolicySources:void 0};if(function(e){const t="win32"===process.platform?"cursorsandbox.exe":"cursorsandbox",r=(0,iH.hQ)({binaryName:t,excludedWorkspaceDir:e});r&&(0,Oo.St)({sandboxBinaryPath:r})}(t),!(0,Oo.K3)(void 0,{ctx:e.initializationCtx}))throw new OW.j1("Local SDK sandboxing was requested, but sandboxing is not supported in this environment. Disable local.sandboxOptions.enabled or remove ~/.cursor/sandbox.json to run without sandboxing.",{isRetryable:!1});const s={};s.perUser=o;const{policy:i}=await(0,Oo.resolveSandboxPolicyForWorkspace)(t,s);return{defaultSandboxPolicy:i,defaultSandboxPolicySources:s}}({cwd:p,perUserSandboxPolicy:E,sandboxOptions:r.sandboxOptions,initializationCtx:a}):void 0,P=performance.now()-C,R=x?.defaultSandboxPolicy,I=x?.defaultSandboxPolicySources,T=EH(R),A=performance.now(),M=(()=>{const e=[],t=new Set;for(const n of[p,...r.dirs??[]]){const r=(0,s.resolve)(n);t.has(r)||(t.add(r),e.push(n))}return e.length>1?e:void 0})(),D={powershellUtf8Console:!1,powershellUtf8ChildEnv:!1},O=await async function(e){const{workingDirectory:t,projectDir:r}=e,n=function(e,t){const r=[],n=new Set;for(const o of[e,...t??[]]){const e=(0,s.resolve)(o);n.has(e)||(n.add(e),r.push(o))}return r}(t,e.dirs),o=n.length>1?n:void 0,i=SB(e.settingSources),a=e.teamSettingsService??{getDotCursorProtection:async()=>!1,getShouldBlockMcp:async()=>!1,getDeleteFileProtection:async()=>!1,getIsHeadlessDisabled:async()=>!1,isServerBlocked:async()=>!1,getTeamRepos:async()=>{},getAutoRunControls:async()=>({enabled:!1,allowed:[],blocked:[],enableAllowlistMode:!0,enableRunEverything:!1,enableSmartAuto:!0,mcpToolAllowlist:[]}),getAdminCommandDenylist:async()=>({rules:[]}),getMcpToolControls:async()=>{},getNetworkAccessControls:async()=>({allowlist:[],denylist:[],available:!0}),getMcpNetworkControlsConfig:async()=>({enabled:!1}),getDefaultNetworkAllowlist:async()=>({allowlist:[],available:!0}),getSandboxingControls:async()=>({sandboxingDisabled:!1,networkingDisabled:!1,gitDisabled:!1}),isAttributionDisabledByAdmin:async()=>!1,invalidateCache:()=>{}},c=e.defaultSandboxPolicy??{type:"insecure_none"},l=e.getSandboxSupported??(()=>(0,Oo.K3)(c,{ctx:e.initializationCtx})),u=e.getSandboxEnabled??(()=>"insecure_none"!==c.type&&l()),d=new _y,h=new xc(d,a,n),p=new TB,f=new AB,m=e.getSmartModeClassifierAutoModeEnabled?.(),g=new IB(m?"allowlist":e.approvalMode??"unrestricted",c,a,e.respectAdminControls??!1),w=e.pendingDecisionProvider,y={executeIndexedGrep:void 0},v=()=>!0,b=kB(i,"plugins"),S=e.importThirdPartyPlugins??!1,k=e.mcpMetaToolEnabled??!0,_=void 0!==e.mcpServers&&Object.keys(e.mcpServers).length>0,C=void 0!==e.customSubagents&&e.customSubagents.length>0,E=_||kB(i,"project")||kB(i,"user")||b,x=kB(i,"project")||kB(i,"user")||kB(i,"mdm"),P=kB(i,"team"),R=P&&void 0!==e.dashboardTransport,I=kB(i,"project")||kB(i,"user")||P||R||b,T={teamSettingsService:a,initializationCtx:e.initializationCtx,importThirdPartyPlugins:S,ignoreApprovals:!0,includeProjectMcp:kB(i,"project"),includeUserMcp:kB(i,"user"),includePluginMcp:b,isLinkSharedPaymentTokenLogRedactionEnabled:e.isLinkSharedPaymentTokenLogRedactionEnabled,restMcpCursorAuthTokenSupplier:e.restMcpCursorAuthTokenSupplier},A=s=>PB({workingDirectory:t,...void 0!==o?{workspaceRoots:o}:{},adapters:{...s.includeMcp?{mcp:VO({...T,inlineMcpServers:e.mcpServers})}:{},...b?{pluginBootstrap:tB({importThirdPartyPlugins:S,dashboardTransport:e.dashboardTransport})}:{},...x?{hooks:pj({includeProjectHooks:kB(i,"project"),includeUserHooks:kB(i,"user"),includeEnterpriseHooks:kB(i,"mdm"),useCommandHookStdinTransport:e.useCommandHookStdinTransport})}:{},...I?{localExtensibility:gj({includeProjectExtensibility:kB(i,"project"),includeUserExtensibility:kB(i,"user"),includeManagedSkills:R,includeTeamExtensibility:P,includePluginExtensibility:b,teamSettingsService:a,getThirdPartyExtensibilityEnabled:v,dashboardTransport:e.dashboardTransport,importThirdPartyPlugins:S})}:{},resourceFactory:dB({attributionConfigProvider:kB(i,"user")?{get(){try{const{readFileSync:r}=process.getBuiltinModule("node:fs"),{join:j}=process.getBuiltinModule("node:path"),{homedir:h}=process.getBuiltinModule("node:os"),x=process.env.XDG_CONFIG_HOME,d=process.env.CURSOR_CONFIG_DIR||(x&&process.platform!=="darwin"&&process.platform!=="win32"?j(x,"cursor"):j(h(),".cursor"));return JSON.parse(r(j(d,"cli-config.json"),"utf8"))}catch{return}}}:void 0,ignoreService:h,grepProvider:y,workspacePaths:n,diagnosticsProvider:p,repositoryProvider:f,projectDir:r??t,shellManager:void 0,defaultSandboxPolicy:c,defaultSandboxPolicySources:e.defaultSandboxPolicySources,getSandboxEnabled:u,getSandboxSupported:l,getNetworkAllowlistInfo:e.getNetworkAllowlistInfo,getSmartModeClassifierAutoModeEnabled:e.getSmartModeClassifierAutoModeEnabled,devForceNextSmartModeClassifierBlockToken:e.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:e.getMockPromptTime,getPowershellUtf8Options:e.getPowershellUtf8Options,mcpFileOutputThresholdBytes:void 0,mcpMetaToolEnabled:k,createMcpStateAccessor:(e,t)=>new $B(new oM(e),void 0===t?.onMcpAllowlistInUse&&void 0===t?.onMcpServerBlockedByAllowlist?void 0:{mcpLease:e,onMcpAllowlistInUse:t.onMcpAllowlistInUse,onMcpServerBlockedByAllowlist:t.onMcpServerBlockedByAllowlist}),createSessionMcpLease:(t,r)=>VO({...T,includeProjectMcp:T.includeProjectMcp&&!0!==t.options.excludeProjectMcp,inlineMcpServers:r??e.mcpServers}).createLease({workspaceState:t.workspaceState,services:t.workspaceServices,policy:t.policy}),createSessionDependencies:r=>{const n=w??new RB;return{pendingDecisionStore:n,fileChangeTracker:new Bw(t),permissionsService:new t_(h,n,g,a,t,e.respectAdminControls??!1,{enforceMcpAdminToolLimits:e.isMcpAdminToolLimitEnforced,onMcpAdminToolLimitCheck:r.options.onMcpAdminToolLimitCheck})}}}),resourceWrappers:x?[{wrapResources(e){const t=e.workspaceServices.hooksRuntime;if(!0===e.options.excludeHooks||"object"!=typeof(r=t)||null===r||!("hooksConfigLease"in r)||!("createSessionRuntime"in r)||"function"!=typeof r.createSessionRuntime||!function(e){return"object"==typeof e&&null!==e&&"get"in e&&"function"==typeof e.get&&"entries"in e&&"function"==typeof e.entries}(e.resources))return e.resources;var r;const n=t.createSessionRuntime({sessionState:e.sessionState,metadata:e.metadata});return new dj(new oj(e.resources,n.hookExecutor,(()=>function(e,t){const r=aj(t,cj,"conversationId","conversation_id")??e.sessionId??"";return{conversation_id:r,generation_id:aj(t,cj,"generationId","generation_id")??r,model:aj(t,cj,"model")??"unknown",...hF({modelId:aj(t,cj,"modelId","model_id"),modelParams:aj(t,uj,"modelParams","model_params")})}}(e.sessionState,e.metadata)),e.workspaceServices.mcpLease,void 0,void 0,t.hooksConfigLease),n)}}]:[],...C?{workspaceServicesContributors:[{contributeServices:t=>{const r=new MB(e.customSubagents??[]),n=t.services.subagentsService;return{subagentsService:void 0===n?r:new Ig([r,n])}}}]}:{}}});if(!E)return A({includeMcp:!1});try{return await A({includeMcp:!0})}catch(e){return SO.Jz.warn("[default-local-workspace-runtime] Failed to initialize MCP-enabled runtime, retrying without MCP:",{error:e,workingDirectory:t,projectDir:r,enablePlugins:b,importThirdPartyPlugins:S}),A({includeMcp:!1})}}({workingDirectory:p,...void 0!==M?{dirs:M}:{},projectDir:f,teamSettingsService:_,initializationCtx:a,dashboardTransport:b,settingSources:r.settingSources,mcpServers:r.mcpServers,customSubagents:r.customSubagents,defaultSandboxPolicy:R,defaultSandboxPolicySources:I,approvalMode:T?"allowlist":void 0,pendingDecisionProvider:T||!0===r.autoReview?new _H:void 0,getNetworkAllowlistInfo:T?()=>async function(e,t,r){const[n,o]=await Promise.all([e.getDefaultNetworkAllowlist(),e.getNetworkAccessControls()]),s=[...o.allowlist],i=`${t}/.cursor/sandbox.json`,a=await(0,Oo.tv)(i,t);if(a&&"insecure_none"!==a.type&&a.networkPolicy?.allow&&s.push(...a.networkPolicy.allow),"1"!==process.env[Zv.K4]&&r){const e=await(0,Oo.tv)(`${r}/.cursor/sandbox.json`,r);e&&"insecure_none"!==e.type&&e.networkPolicy?.allow&&s.push(...e.networkPolicy.allow)}const c=[...new Set(s)];return{hasDefaults:n.available&&n.allowlist.length>0,explicitEntries:c}}(_,(0,o.homedir)(),p):void 0,getSmartModeClassifierAutoModeEnabled:()=>!0===r.autoReview,devForceNextSmartModeClassifierBlockToken:r.devForceNextSmartModeClassifierBlockToken,getMockPromptTime:bH,getPowershellUtf8Options:async()=>{if(void 0===k)return D;try{const e=await k;return{powershellUtf8Console:e.checkFeatureGate("shell_exec_powershell_utf8_console"),powershellUtf8ChildEnv:e.checkFeatureGate("shell_exec_powershell_utf8_child_env")}}catch{return D}},isLinkSharedPaymentTokenLogRedactionEnabled:fH(k),restMcpCursorAuthTokenSupplier:S,respectAdminControls:void 0!==r.apiKey,isMcpAdminToolLimitEnforced:void 0===k?void 0:(F=k,async()=>{try{return(await F).checkFeatureGate("sdk_local_mcp_admin_tool_limits",{disableExposureLog:!0})}catch{return!1}}),useCommandHookStdinTransport:!0});var F;const N=performance.now()-A;let L,j;return(0,XB.ou)(r.apiKey,{runtime:"local",ensure_ghost_mode_ms:Math.round(h),bootstrap_statsig_ms:0,create_workspace_runtime_ms:Math.round(N),load_sandbox_policy_ms:Math.round(P),total_ms:Math.round(performance.now()-d)}),{run:async(e,t,o)=>(0,SO.ni)(SH,(async()=>{const s=(0,$.VI)((0,y.q6)().withName("sdk.run").with(l._O,kH)),[a,c]=s.ctx.withCancel(),u=t.sessionId??(0,ge.C)(),d=t.mcpServersOverride,h=void 0===(f=t.customTools)?[]:Object.entries(f).map((([e,t])=>({clientKey:zn,providerIdentifier:zn,toolName:e,name:`${zn}-${e}`,description:t.description??"",inputSchema:t.inputSchema??AW,...void 0===t.outputSchema?{}:{outputSchema:t.outputSchema},...void 0===t.annotations?{}:{annotations:$W(t.annotations)},source:"internal"})));var f;let g;const w={...m,workspace:t.fileSystemWorkspace},v=void 0===t.fileSystem?void 0:(_=await async function(e,t){return"function"==typeof e?await e(t):e}(t.fileSystem,{agentId:u,sessionId:u}),C=_,(0,UW.VL)({"/":C,[HW]:(0,BW.Om)()})),b=void 0===t.onMcpAdminToolLimitCounts?void 0:new rH,S=()=>{for(const e of b?.take()??[])try{t.onMcpAdminToolLimitCounts?.(e)}catch{}},k=new nH;var _,C;g=await O.createSessionRuntime({sessionId:u,mcpServersOverride:d,extraMcpTools:h,onMcpAdminToolLimitCheck:b?.record,onMcpAllowlistInUse:oH.report,onMcpServerBlockedByAllowlist:k.report,...void 0===v?vH(t.sessionResources):eH(v,w)});const E=new Map;try{const s=g.resources.wrapped;wH(g,t.customTools),void 0!==v&&LW(g.resources.base);const l=t.blobStore??new re.ve;let f=t.initialState??new i.Y9z({});const m=void 0!==t.model?new JB.G4({modelId:t.model.id,...!0===t.model.maxMode?{maxMode:!0}:{},parameters:(t.model.params??[]).map((e=>new JB.SR({id:e.id,value:e.value})))}):void 0,y=!0===e.summarize?void 0:e.images,_=Array.isArray(y)?y.map((e=>{const t=(0,ge.C)(),r=new Uint8Array(n.Buffer.from(e.data,"base64")),o=(0,tH.v8)(r);return new ZB.d({uuid:t,...o?{mimeType:o}:{},dataOrBlobId:{case:"data",value:r}})})):[],C=_.length>0?new ZB.xv({selectedImages:_}):void 0,R=function(e){switch(e){case"agent":return i.xyI.AGENT;case"plan":return i.xyI.PLAN;default:return}}(t.mode),I=e.resume===!0?new i.QFf({action:{case:"resumeAction",value:new i.qKo}}):!0===e.summarize?new i.QFf({action:{case:"summarizeAction",value:new i.Scs}}):new i.QFf({action:{case:"userMessageAction",value:new i.Vtf({userMessage:new i.RGk({text:e.text,selectedContext:C,...void 0!==R?{mode:R}:{}})})}}),T={sendUpdate:async(e,t)=>{const r=sW(t,u);null!==r&&await o.sendUpdate(r)},query:async(e,r)=>await async function(e,t){if("mcpAuthRequestQuery"===e.query.case&&void 0!==t){const r=await async function(e,t,r){let n;try{n=await e({serverName:r.args?.serverIdentifier??"",toolCallId:r.args?.toolCallId??""})}catch{return kr(t,"The MCP sign-in request failed.")}if(void 0!==n)switch(n.kind){case"approved":return Sr(t);case"rejected":return kr(t,n.reason);default:return n}}(t,e.id,e.query.value);if(void 0!==r)return r}return function(e){switch(e.query.case){case"webSearchRequestQuery":return ur(e.id);case"webFetchRequestQuery":return hr(e.id);case"switchModeRequestQuery":return mr(e.id);case"askQuestionInteractionQuery":return fr(e.id,new Qt.tz({result:{case:"rejected",value:new Qt.ox({reason:"Interactive questions are not supported in local SDK runs"})}}));case"createPlanRequestQuery":return wr(e.id,new Yt.bK({result:{case:"success",value:new Yt.Jo},planUri:""}));case"setupVmEnvironmentArgs":return yr(e.id,new rr.r$({result:{case:"success",value:new rr.JH}}));case"replaceEnvArgs":return vr(e.id,new tr.dV({result:{case:"failure",value:new tr.uq({errorMessage:"Environment replacement is not supported in local SDK runs",setupLogs:""})}}));case"prManagementRequestQuery":return br(e.id,new er.HL({result:{case:"error",value:new er.K$({error:"PR management is only available in cloud agents"})}}));case"mcpAuthRequestQuery":return kr(e.id,"MCP authentication is not supported in local SDK runs");case"connectScmRequestQuery":return _r(e.id,"Connecting GitHub is not supported in local SDK runs");case"generateImageRequestQuery":return Cr(e.id,e.query.value.args?.description);case void 0:throw new OW.j1("Missing interaction query type",{isRetryable:!1});default:throw e.query,new OW.j1("Unhandled interaction query type",{isRetryable:!1})}}(e)}(r,t.onMcpAuthRequest)};if(L!==t.apiKey||!j){await Promise.all([(0,tH.ly)(t.apiKey),(0,tH.mU)(t.apiKey)]);const e=(0,tH.KU)(t.apiKey,r.teamId),n=vo((0,ye.createClient)(KB.N,e),{injectTraceHeaders:!0});j=new Wn(n),L=t.apiKey}const A=(0,tH.Vh)(j,(()=>{const e=(0,tH.KU)(t.apiKey,r.teamId),n=vo((0,ye.createClient)(KB.N,e),{injectTraceHeaders:!0}),o=new Wn(n);return j=o,L=t.apiKey,o})),$=function(e){return{...void 0!==e.allowedTools?{[mH.$$]:e.allowedTools.join(",")}:{},...void 0!==e.disallowedTools&&e.disallowedTools.length>0?{[mH.VJ]:e.disallowedTools.join(",")}:{}}}(t),M=new VB({agentClient:A,rootRequestId:t.requestId,getResources:async({agentId:e})=>{let r=E.get(e);return r||(r=await O.createSessionRuntime({sessionId:e,mcpServersOverride:d,extraMcpTools:h,onMcpAdminToolLimitCheck:b?.record,onMcpAllowlistInUse:oH.report,onMcpServerBlockedByAllowlist:k.report,...void 0===v?vH(t.subagentInherit):eH(v,w)}),wH(r,t.customTools),void 0!==v&&LW(r.resources.base),r.resources.base.register(io,D),r.resources.base.register(ao,F),r.resources.base.register(co,N),E.set(e,r)),r.resources.wrapped},mcpTools:h,workspacePath:p,parentConversationId:u,...(void 0!==t.subagentInherit||void 0!==v)&&Object.keys($).length>0?{headers:$}:{},onSessionReleased:e=>{const t=E.get(e);t&&(t.dispose(),E.delete(e))}}),D=function(e){const t=new Map,r=new Map;async function n(t,r,n){let o;try{o=await e.createOrResumeSession(t,r);const s=await e.runSession(t,o,r,{execId:n?.execId});return"error"===s.status?new oo.vS({result:{case:"error",value:new oo.od({agentId:o,error:s.error})}}):"aborted"===s.status?new oo.vS({result:{case:"error",value:new oo.od({agentId:o,error:s.error??"Subagent was aborted by the user"})}}):"background"===s.status?new oo.vS({result:{case:"success",value:new oo.HJ({agentId:o,finalMessage:s.finalMessage,toolCallCount:s.toolCallCount??0,backgroundReason:s.backgroundReason,transcriptPath:s.transcriptPath})}}):new oo.vS({result:{case:"success",value:new oo.HJ({agentId:o,finalMessage:s.finalMessage,toolCallCount:s.toolCallCount??0})}})}catch(t){if(o&&e.releaseSession&&e.releaseSession(o),t instanceof lr)throw t;const n=t instanceof Error?t.message:String(t),s=o??function(e){return e instanceof so&&e.agentId||e&&"object"==typeof e&&"agentId"in e&&"string"==typeof e.agentId?e.agentId:void 0}(t)??r.resumeAgentId;return new oo.vS({result:{case:"error",value:new oo.od({...s?{agentId:s}:{},error:n})}})}}return{execute(e,o,s){const i=function(e){if(e.toolCallId&&e.parentConversationId)return[e.parentConversationId,e.toolCallId,e.resumeAgentId??"",e.forkAgentId??""].join("\0")}(o);if(void 0===i)return n(e,o,s);const a=r.get(i);if(void 0!==a)return Promise.resolve(a);const c=t.get(i);if(void 0!==c)return c;const l=n(e,o,s).then((e=>("success"===e.result.case&&(r.set(i,e),r.size>1e3&&r.delete(r.keys().next().value)),e))).finally((()=>{t.delete(i)}));return t.set(i,l),l}}}(M),F=(P=M,{execute:(e,t)=>P.awaitBackgroundRunBounded(e,t)}),N=function(e){return{execute:async(t,r)=>e.forceBackgroundByToolCallId(r.toolCallId)}}(M);g.resources.base.register(io,D),g.resources.base.register(ao,F),g.resources.base.register(co,N);const U=O.services.hooksRuntime,B="object"==typeof(x=U)&&null!==x&&"workspacePath"in x&&"string"==typeof x.workspacePath&&"createSessionRuntime"in x&&"function"==typeof x.createSessionRuntime?U:void 0,W=void 0!==B&&void 0===v&&!0!==e.summarize?function(e){const{workspaceRuntime:t}=e;if(!(t.hooksConfigLease.hasHookForStep(xd.sessionStart)||t.hooksConfigLease.hasHookForStep(xd.sessionEnd)||t.hooksConfigLease.hasHookForStep(xd.stop)||t.hooksConfigLease.hasHookForStep(xd.beforeSubmitPrompt)))return{};const r=t.createSessionRuntime({sessionState:e.sessionState,metadata:e.metadata}),{hookExecutor:n}=r;let o;return{async onSessionStart(e){if(o=e,n.hasHooksForStep(xd.sessionStart))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...hF(e),is_background_agent:!1},r=await n.executeHookForStep(xd.sessionStart,t);if(r)return r.env&&n.setSessionEnvironment(r.env),{env:r.env,additionalContext:r.additional_context,blocked:!1===r.continue,blockedReason:r.user_message}}catch(e){SO.Jz.warn("[hooks-adapter] sessionStart hook failed:",e)}},async onSessionEnd(e,t){if(n.hasHooksForStep(xd.sessionEnd))try{const r={conversation_id:o?.conversationId??"",generation_id:o?.generationId??"",model:o?.model??"unknown",...o?hF(o):{},reason:e,duration_ms:t,is_background_agent:!1,final_status:e};await n.executeHookForStep(xd.sessionEnd,r)}catch(e){SO.Jz.warn("[hooks-adapter] sessionEnd hook failed:",e)}finally{n.clearSessionEnvironment()}else n.clearSessionEnvironment()},async onBeforeSubmitPrompt(e){if(n.hasHooksForStep(xd.beforeSubmitPrompt))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...hF(e),prompt:e.promptText??"",attachments:[]};await n.executeHookForStep(xd.beforeSubmitPrompt,t)}catch(e){SO.Jz.warn("[hooks-adapter] beforeSubmitPrompt hook failed:",e)}},async onTurnCompleted(e){if(!n.hasHooksForStep(xd.stop))return;const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...hF(e),status:"completed",loop_count:e.loopCount},r=await n.executeHookForStep(xd.stop,t),o="string"==typeof r?.followup_message?r.followup_message.trim():"";return o.length>0?o:void 0},async onTurnError(e){if(n.hasHooksForStep(xd.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...hF(e),status:"error",loop_count:e.loopCount};await n.executeHookForStep(xd.stop,t)}catch(e){SO.Jz.warn("[hooks-adapter] onTurnError stop hook failed:",e)}},async onTurnAborted(e){if(n.hasHooksForStep(xd.stop))try{const t={conversation_id:e.conversationId,generation_id:e.generationId,model:e.model,...hF(e),status:"aborted",loop_count:e.loopCount};await n.executeHookForStep(xd.stop,t)}catch(e){SO.Jz.warn("[hooks-adapter] onTurnAborted stop hook failed:",e)}},async dispose(){await r.dispose()}}}({workspaceRuntime:B,sessionState:g.state,metadata:g.metadata}):void 0,H=new qB({workspacePath:p,conversationId:u,blobStore:l}),q=function(e,t,r){const{hooks:n}=r,[o,s]=e.withCancel(),a=new bO;let c;const l=new Map,u=(e,t)=>{const r=l.get(e);void 0!==r&&(l.delete(e),clearTimeout(r.ackTimer),r.resolve(t))};let d;const h=[],p=e=>{for(const t of h.splice(0))t.resolve(e)},f=()=>{if(0===h.length)return;const e=h.map((e=>e.text)).join("\n\n");return p("complete_delivered"),RO(e)},m=r.interactionListener,g={async sendUpdate(e,t){const r=t.message;if("contextInjectionState"===r?.case){const e=r.value,t="object"==typeof e&&null!==e&&"injectionId"in e&&"string"==typeof e.injectionId?e.injectionId:void 0,n=function(e){if("object"!=typeof e||null===e||!("state"in e))return;const t=e.state;if("object"!=typeof t||null===t||!("state"in t))return;const r=t.state;return"object"==typeof r&&null!==r&&"case"in r&&"string"==typeof r.case?r.case:void 0}(e),o=function(e){switch(e){case"queued":return"queued";case"delivered":return"delivered";case"queuedForNextTurn":return"queued_for_next_turn";case"cancelled":return"cancelled";default:return"rejected"}}(n),s=void 0===t?void 0:l.get(t);if(void 0!==s&&void 0!==t){const e=function(e){switch(e){case"queued":return"confirm_steering";case"delivered":return"complete_delivered";case"queued_for_next_turn":case"cancelled":case"rejected":return"revert_to_followup";default:throw new Error(`Unknown steer ack state: ${String(e)}`)}}(o);"confirm_steering"===e?clearTimeout(s.ackTimer):(l.delete(t),s.resolve(e))}}await m.sendUpdate(e,t)},query:(e,t)=>m.query(e,t),...void 0!==m.enqueuePostTurnEndedWork?{enqueuePostTurnEndedWork:e=>m.enqueuePostTurnEndedWork?.(e)}:{},...void 0!==m.flushPostTurnEndedWork?{flushPostTurnEndedWork:e=>m.flushPostTurnEndedWork?.(e)??Promise.resolve()}:{}};let w=r.initialState;const y={async handleCheckpoint(e,t){w=t,await(r.onCheckpoint?.(t))},getLatestCheckpoint:()=>w};let v="completed";const b=Date.now(),S=CO(function(e,t){if((0,kO.TU)(t))return t;const r=EO.get(e);if(void 0!==r)return r;const n=(0,kO.sh)(e).blobEncryptionKey;if(void 0===n)throw new Error("getDefaultAgentMetadata did not seed a blobEncryptionKey");return EO.set(e,n),n}(r.conversationId,r.blobEncryptionKey),r.runOptions?.headers);return{done:(async()=>{const e=PO(r,0,xO(t));try{const t=await(n?.onSessionStart?.(e));if(t?.blocked)throw v="error",new Error(t.blockedReason??"Session blocked by sessionStart hook")}catch(e){if("completed"!==v)throw e;SO.Jz.warn("[agent-session-runner] sessionStart hook failed:",e)}let s=t,i=0;for(;s;){const e=PO(r,i,xO(s));try{await(n?.onBeforeSubmitPrompt?.(e))}catch(e){SO.Jz.warn("[agent-session-runner] beforeSubmitPrompt hook failed:",e)}c=r.runOptions?.generationUUID??(0,ge.C)();try{await r.agentClient.run(o,w,s,void 0,g,r.resources,r.blobStore,a,y,r.mcpTools??[],{conversationId:r.conversationId,...r.runOptions,generationUUID:c,headers:S,subagentModelOverrides:r.runOptions?.subagentModelOverrides??[]})}catch(t){throw v=IO(t)?"aborted":"error",TO("aborted"===v?n?.onTurnAborted?.(e):n?.onTurnError?.(e)),t}finally{c=void 0;for(const e of[...l.keys()])u(e,"revert_to_followup")}let t;try{t=await(n?.onTurnCompleted?.(e))}catch(e){throw v="error",e}const h="string"==typeof t?t.trim():"";let m;if(h.length>0)m=RO(h);else{const t=new AbortController;d=t;try{m=await(r.nextAction?.(e,AbortSignal.any([o.signal,t.signal])))}catch(r){if(o.signal.aborted||!t.signal.aborted)throw v=o.signal.aborted||IO(r)?"aborted":"error",TO("aborted"===v?n?.onTurnAborted?.(e):n?.onTurnError?.(e)),r}finally{d=void 0}void 0===m?m=f():p("revert_to_followup")}void 0!==m?(i+=1,a.resetStream(),s=m):s=void 0}})().finally((async()=>{p("revert_to_followup");const e=Date.now()-b;try{await(n?.onSessionEnd?.(v,e))}catch(e){SO.Jz.warn("[agent-session-runner] sessionEnd hook failed:",e)}try{await(n?.dispose?.())}catch(e){SO.Jz.warn("[agent-session-runner] hooks dispose failed:",e)}})),abort(){s()},async steer(e){if(""===e.trim())return"revert_to_followup";const t=c;if(void 0===t){const t=d;if(void 0===t)return"revert_to_followup";const r=new Promise((t=>{h.push({text:e,resolve:t})}));return t.abort(),await r}const r=(0,ge.C)(),n=new Promise((e=>{const t=setTimeout((()=>{u(r,"revert_to_followup")}),15e3);t.unref?.(),l.set(r,{resolve:e,ackTimer:t})}));try{return await a.submitConversationAction(new i.QFf({action:{case:"injectContextAction",value:new i.hGJ({injectionId:r,expectedRunId:t,payload:{case:"userContext",value:new i.oW$({userMessage:new i.RGk({messageId:(0,ge.C)(),text:e})})}})}})),await n}catch(e){return u(r,"revert_to_followup"),SO.Jz.warn("[agent-session-runner] context injection failed:",e),"revert_to_followup"}}}}(a,I,{agentClient:A,interactionListener:T,resources:s,blobStore:l,initialState:f,conversationId:u,mcpTools:h,blobEncryptionKey:t.blobEncryptionKey,runOptions:{generationUUID:t.requestId,requestedModel:m,enableAgentRetries:!1!==r.enableAgentRetries,emitModelCallUsage:!0,...void 0!==t.onConnectionStateChange?{onConnectionStateChange:e=>{!function(e,t){if(void 0!==e)try{e(function(e){switch(e.state){case"connected":return{state:"connected"};case"reconnecting":{const t=e.trigger?.errorClass,r=e.trigger?.stallAborted,n={...void 0!==t?{errorClass:t}:{},...void 0!==r?{stallAborted:r}:{}};return{state:"reconnecting",attempt:e.attempt,...Object.keys(n).length>0?{trigger:n}:{}}}default:return e}}(t))}catch(e){lH.v.warn(`onConnectionStateChange failed: ${e instanceof Error?e.message:String(e)}`)}}(t.onConnectionStateChange,e)}}:{},...Object.keys($).length>0?{headers:$}:{},...void 0!==t.systemPrompt?{customSystemPrompt:t.systemPrompt}:{}},hooks:W,async nextAction(e,t){const r=await M.waitForBackgroundCompletions(u,t);return r.length>0?function(e){return new i.QFf({action:{case:"backgroundTaskCompletionAction",value:new i.Kwc({completions:e.map((e=>new i.KFq({taskId:e.agentId,kind:i.aZc.SUBAGENT,status:"success"===e.status?i.uHL.SUCCESS:"aborted"===e.status?i.uHL.ABORTED:i.uHL.ERROR,...e.finalMessage.length>0?{detail:e.finalMessage}:{}})))})}})}(r):void 0},async onCheckpoint(e){f=e,H.writeFromState(a,e),await(t.onCheckpoint?.(e))}}),z=q.done.finally((async()=>{try{await M.awaitBackgroundWorkers()}finally{await H.waitForPendingWrites().catch((()=>{}));for(const e of E.values())try{await e.dispose()}catch(e){lH.v.log(`Failed to dispose subagent session runtime: ${e instanceof Error?e.message:String(e)}`)}E.clear();try{await g.dispose()}finally{S()}}})).catch((e=>{throw e}));return{abort(){q.abort(),c()},done:z,steer:e=>q.steer(e)}}catch(e){for(const e of E.values())try{await e.dispose()}catch{}E.clear();try{await g.dispose()}finally{S()}throw e}var x,P})),async reload(){await O.reload()},async dispose(){await O.dispose()}}}},"./src/agent/native/tree-sitter-bash.webpack.cjs"(e,r,n){const{loadVendoredTreeSitterModule:o}=n("./src/agent/native/vendored-tree-sitter.ts"),s=o({packageName:"tree-sitter-bash",nativeRequire:t});e.exports=s.available?s.module:{}},"./src/agent/native/tree-sitter.webpack.cjs"(e,r,n){const{createUnavailableParserClass:o,loadVendoredTreeSitterModule:s}=n("./src/agent/native/vendored-tree-sitter.ts"),i=s({packageName:"tree-sitter",nativeRequire:t});e.exports=i.available?i.module:o(i.reason)},"../constants/dist/commercial-cursor-hosts.js"(e,t,r){r.d(t,{H:()=>c,K4:()=>i,Zf:()=>a,ad:()=>l});const n=["cursor.sh","cursor.com","cursorapi.com","cursor.so","cursor-marketplace.com","cursorusercontent.com","anysphere.co"],o=["cursor.blob.core.windows.net"];function s(e){return e.trim().toLowerCase().replace(/\.+$/,"")}const i="CURSOR_ORBIT_BUILD",a="CURSOR_ORBIT_DEPLOYMENT_HOSTS";function c(e){return new Set((e??"").split(",").map(s).filter((e=>""!==e)))}function l(e,t){return function(e){const t=s(e);return o.includes(t)||n.some((e=>t===e||t.endsWith(`.${e}`)))}(e)&&!t.has(s(e))}},"../context/dist/otel.js"(e,t,r){r.d(t,{F:()=>E,HF:()=>_,MG:()=>k,Mf:()=>v,OA:()=>y,V5:()=>C,VI:()=>P,fR:()=>g,fU:()=>w,mJ:()=>b,r2:()=>x,xd:()=>R});var n=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/span_kind.js"),o=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/context-api.js"),s=r("../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace-api.js"),i=r("../context/dist/core.js");const a=(0,i.cF)(Symbol("otel.span"),void 0),c=(0,i.cF)(Symbol("otel.root_span"),void 0),l=(0,i.cF)(Symbol("otel.root_start_ms"),void 0),u=(0,i.cF)(Symbol("otel.suppress_child_spans"),!1),d=(0,i.cF)(Symbol("otel.inheritable_span_attributes"),{});function h(e,t){const r=t.get(d);for(const t in r){const n=r[t];"string"!=typeof n&&"number"!=typeof n&&"boolean"!=typeof n||e.setAttribute(t,n)}}function p(e){return e.name||"anonymous-context"}function f(e,t){return!!t&&(e.get(u)||(p(e),!1))}function m(e="context-tracer"){return s.u.getTracer(e)}function g(e,t){const r=m(),n=e.get(a);if(f(e,n))return e;const i=p(e);let u;if(n){const e=s.u.setSpan(o._.active(),n);u=r.startSpan(i,t,e)}else u=r.startSpan(i,t);h(u,e);const d=Date.now();let g=e.with(a,u);return n||(g=g.with(c,u).with(l,d)),g}function w(e){return e.get(a)}function y(e){return e.with(u,!0)}function v(e,t,r){const n=e.get(d),o=w(e);return o&&null!==r&&o.setAttribute(t,r),e.with(d,{...n,[t]:r})}function b(e){try{const t=w(e);if(!t)return;const r=t.spanContext(),n=e.get(u);return{traceId:r.traceId,spanId:r.spanId,traceFlags:n?0:r.traceFlags,traceState:r.traceState?.serialize()}}catch{return}}const S=Symbol.for("anysphere.context.activeOtelSpanAls");function k(e,t){const r=()=>o._.with(s.u.setSpan(o._.active(),e),t),n=function(){const e=globalThis;if("object"!=typeof(t=e)||null===t||!(S in e))return;var t;const r=e[S];return function(e){return"object"==typeof e&&null!==e&&"run"in e&&"function"==typeof e.run&&"getStore"in e&&"function"==typeof e.getStore}(r)?r:void 0}();return void 0===n?r():n.run(e,r)}function _(e,t){try{const r=m(),n=w(e);if(!n)return;const i=s.u.setSpan(o._.active(),n),a=r.startSpan(t,void 0,i);h(a,e);const u=Date.now(),d=e.get(l),p="number"==typeof d?u-d:0,f=`event.${t}`;(e.get(c)??n).setAttribute(f,p),a.setAttribute(f,p),a.end()}catch{}}function C(e,t,r){const c=m(),l={traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags,isRemote:!0},u=s.u.setSpanContext(o._.active(),l),d=t||"child.span",h=c.startSpan(d,{kind:n.v.INTERNAL},u),p=r??(0,i.q6)();return(t?p.withName(t):p).with(a,h)}function E(e,t,r){const n=s.u.wrapSpanContext({traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags,isRemote:!0}),o=r??(0,i.q6)();return(t?o.withName(t):o).with(a,n)}class x{constructor(e,t,r=!0){this.disposed=!1,this.ctx=e,this.span=t,this.shouldEnd=r}[Symbol.dispose](){this.disposed||(this.disposed=!0,this.shouldEnd&&this.span.end())}}function P(e,t){const r=f(e,w(e)),n=g(e,t),o=w(n);return new x(n,o,!r)}function R(e,t,r){const n=w(e);if(!n||f(e,n))return;const o=w(g(e,t));return o.end(r),o}},"../mcp-core/dist/transport/mcp-url-utils.js"(e,t,r){r.d(t,{$H:()=>Q,ME:()=>G,_N:()=>X,b6:()=>z,bi:()=>P,eA:()=>j,mD:()=>A,rM:()=>J,vc:()=>L});const n=BigInt(0),o=BigInt(8),s=BigInt(16),i=BigInt(65535);function a(e){const t=e.split(".");if(4!==t.length)return;let r=n;for(const e of t){if(!/^\d{1,3}$/.test(e))return;const t=Number(e);if(!Number.isInteger(t)||t<0||t>255)return;r=r<>s&i)),t.push(Number(o.value&i))}else{if(!/^[0-9a-f]{1,4}$/i.test(n))return;t.push(Number.parseInt(n,16))}}return t}function l(e){return a(e)??function(e){const t=H(e);if(0===t.length||t.includes(":::"))return;const r=t.indexOf("::");if(-1===r){const e=c(t);if(!e||8!==e.length)return;return{version:6,value:e.reduce(((e,t)=>e<7?void 0:{version:6,value:[...a,...new Array(8-u).fill(0),...l].reduce(((e,t)=>e<=R&&d.clear();const t=l(e);return d.set(e,t),t}(e);return void 0!==r&&r.version===t.version&&r.value>>t.shift===t.shiftedNetwork}case"subdomainOrBase":return e===t.suffix||e.endsWith(`.${t.suffix}`);case"exact":return e===t.value;default:return t}}(H(e),function(e){const t=u.get(e);if(t)return t;u.size>=R&&u.clear();const r=function(e){const t=H(e);if("*"===t)return{kind:"matchAll"};if(t.includes("/")){const e=t.lastIndexOf("/");if(e<=0||e===t.length-1)return{kind:"invalidCidr"};const r=l(t.slice(0,e));if(!r)return{kind:"invalidCidr"};const n=Number(t.slice(e+1)),o=4===r.version?32:128;if(!Number.isInteger(n)||n<0||n>o)return{kind:"invalidCidr"};const s=BigInt(o-n);return{kind:"cidr",version:r.version,shift:s,shiftedNetwork:r.value>>s}}return t.startsWith("*.")?{kind:"subdomainOrBase",suffix:t.slice(2)}:{kind:"exact",value:t}}(e);return u.set(e,r),r}(t))}new Set(["airtable.com","anysphere.co","api.aws","apify.com","asana.com","ashbyhq.com","atlassian.com","atlassian.net","azuredatabricks.net","box.com","buildkite.com","calendly.com","canva.com","clickhouse.cloud","clickup.com","cloudflare.com","composio.dev","context7.com","cursor.com","cursor.sh","cursorapi.com","databricks.com","datadoghq.com","datadoghq.eu","ddog-gov.com","dropbox.com","elevenlabs.io","exa.ai","figma.com","firecrawl.dev","github.com","githubcopilot.com","gitlab.com","google.com","googleapis.com","granola.ai","hex.tech","hubspot.com","huggingface.co","intercom.com","linear.app","monday.com","neon.tech","notion.com","plain.com","posthog.com","prisma.io","railway.com","ramp.com","render.com","salesforce.com","sentry.dev","sentry.io","slack.com","snowflakecomputing.com","spacelift.io","statsig.com","stripe.com","supabase.com","todoist.net","vercel.com","workos.com","x.ai","x.com","zapier.com"]);const p="Blocked by MCP Network Admin Server Controls";function f(e){return/\s/.test(e)}const m="[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?",g=new RegExp(`^(?:${m}\\.)*${m}$`),w=new RegExp(`^\\*\\.(?:${m}\\.)*${m}$`),y="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)",v=new RegExp(`^${y}(?:\\.${y}){3}$`),b=/^[0-9a-f:]+$/,S=new RegExp(`^(?:${y}(?:\\.${y}){3}|[0-9a-f:]+)\\/\\d{1,3}$`);function k(e){const t=H(e);return t.length>0&&t.length<=253&&g.test(t)}function _(e){const t=H(e);return v.test(t)||function(e){const t=H(e);if(!b.test(t))return!1;try{return new URL(`https://[${t}]`),!0}catch{return!1}}(t)}function C(e,t){return""===t||"http:"===e&&"80"===t||"https:"===e&&"443"===t}function E(e){const t=new URL(e.pathname||"/",e.origin);if(t.search=e.search,t.pathname.endsWith("/")&&t.pathname.length>1&&(t.pathname=t.pathname.slice(0,-1)),"/"===t.pathname&&""===t.search){const t=e.protocol.toLowerCase();let r=`${t}//${e.hostname.toLowerCase()}`;return C(t,e.port)||(r+=`:${e.port}`),r}const r=e.protocol.toLowerCase();let n=`${r}//${e.hostname.toLowerCase()}`;return C(r,e.port)||(n+=`:${e.port}`),`${n}${t.pathname}${t.search}`}function x(e){if(e.includes("://"))return function(e){try{const t=new URL(e);return("http:"===t.protocol||"https:"===t.protocol)&&!(0===t.hostname.length||t.username.length>0||t.password.length>0)&&""===t.hash&&function(e){const t=e.toLowerCase();return!t.includes("*")&&(k(t)||_(t))}(t.hostname)}catch{return!1}}(e);const t=H(e);return"*"===t||!!w.test(t)||(t.includes("/")?function(e){const t=H(e);if(!S.test(t))return!1;const[r]=t.split("/");return void 0!==r&&h(r,t)}(t):k(t)||_(t))}function P(e){if(I.has(e))return I.get(e);I.size>=R&&I.clear();const t=function(e){const t=e.trim();if(0===t.length)return;const r=t.lastIndexOf("/");if(!t.includes("://")&&r>0&&/^\d+$/.test(t.slice(r+1).trim())){const e=`${H(t.slice(0,r))}/${t.slice(r+1).trim()}`;return x(e)?e:void 0}if(f(t)||t.includes("#")||t.includes("@"))return;const n=t.indexOf("://");if(-1!==n){const e=t.slice(0,n).toLowerCase();if("http"!==e&&"https"!==e)return;try{const e=new URL(t);if(0===e.hostname.length||e.username.length>0||e.password.length>0)return;const r="/"!==e.pathname&&""!==e.pathname,n=""!==e.search;if(e.hostname.includes("*"))return;if(r||n){const t=E(e);if(!x(t))return;return t}{const t=E(e);if(!x(t))return;return t}}catch{return}}else if(t.includes("/"))return;const o=t.trim().toLowerCase(),s=function(e){const t=e.indexOf(":");if(-1===t)return e;const r=e.slice(t+1);return/^\d+$/.test(r)?e.slice(0,t):e}(o);return 0===s.length||!x(s)||s!==o&&"*"===s?void 0:s}(e);return I.set(e,t),t}const R=2048,I=new Map,T=new Map;function A(e,t){if(!e.includes("*"))return e===t;const r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(t)}function $(e){return e.endsWith("/")&&e.length>1?e.slice(0,-1):e}function M(e,t){return function(e,t,r){const n=D(t);if(!n)return!1;let o;try{o=new URL(e)}catch{return!1}return""===o.username&&""===o.password&&""===n.username&&""===n.password&&o.protocol===n.protocol&&o.port===n.port&&(s=o.hostname,i=n.hostname,!s.includes("*")&&H(s)===H(i)&&(A(a=o.pathname,c=n.pathname)||A($(a),$(c)))&&function(e,t,r){return""===e?r.allowRequestQueryWhenPatternOmitsQuery||""===t:A(e,t)}(o.search,n.search,r));var s,i,a,c}(e,t,{allowRequestQueryWhenPatternOmitsQuery:!0})}function D(e){const t=e.trim();if(0===t.length||f(t))return;if(function(e){const t=e.indexOf("[");return-1!==t&&-1===e.indexOf("]",t)}(t))return;const r=q(t);if(r&&("http:"===r.protocol||"https:"===r.protocol)&&""===r.username&&""===r.password&&0!==r.hostname.length&&(!H(r.hostname).includes(":")||t.includes("["))){if(t.includes("[")){const e=t.indexOf("["),n=t.indexOf("]",e);if(-1===n)return;const o=t.slice(e+1,n);if(H(r.hostname)!==H(o))return}return r}}function O(e,t){const r=e.toLowerCase(),n=t.toLowerCase();if("*"===r)return!0;if(void 0!==a(n))return A(r,n);if(!r.includes("*"))return r===n;const o=r.slice(1);if(r.startsWith("*.")&&!o.includes("*"))return n.endsWith(o)&&n.length>o.length;const s=r.split("."),i=n.split(".");return s.length===i.length&&!s[s.length-1]?.includes("*")&&A(r,n)}const F=/^([^/?#]+\/\/[^/?#]*):\*(?=[/?#]|$)/,N=/^[^/?#]+\/\/[^/?#]*\*$/;function L(e,t){if("*"===e||e===t)return!0;let r;T.has(t)?r=T.get(t):(T.size>=R&&T.clear(),r=q(t),T.set(t,r));const n=function(e){if(void 0===e||!/[^.]\.$/.test(e.hostname))return;const t=new URL(e.href);return t.hostname=e.hostname.slice(0,-1),t.href}(r);if(void 0!==n&&L(e,n))return!0;const o=function(e){const t=e.trim(),r=t.indexOf("://");if(-1===r)return/^[^/?#]*[^.*/?#]\.$/.test(t)?t.slice(0,-1):void 0;if(!t.includes("*"))return;const n=r+3,o=n+(t.slice(n).split(/[/?#]/,1)[0]??"").replace(/:(?:\d+|\*)$/,"").length;return/[^.*]\.$/.test(t.slice(n,o))?`${t.slice(0,o-1)}${t.slice(o)}`:void 0}(e);return!(void 0===o||!L(o,t))||!!r&&(e.includes("://")?function(e,t){const r=N.test(e),n=r||F.test(e),o=e.indexOf("://"),s=e.slice(0,o).toLowerCase(),i=t.protocol.slice(0,-1),a=q((s.includes("*")&&A(s,i)?`${i}${e.slice(o)}`:e).replace(F,"$1"));if(void 0===a||""!==a.username||""!==a.password||""!==t.username||""!==t.password||a.protocol!==t.protocol||!n&&a.port!==t.port)return!1;const c=a.hostname.replace(/%2a/gi,"*");return(O(c,t.hostname)||r&&O(c.replace(/\*$/,""),t.hostname))&&(r||A(`${a.pathname}${a.search}`,`${t.pathname}${t.search}`))}(e,r):h(r.hostname,e))}function j(e,t){if(A(e,t)||L(e,t))return!0;const r=function(e){const t=e.trim();if(t.includes("*")||!t.includes("://"))return;const r=q(t);return void 0!==r&&""===r.search&&""===r.hash?W(r):void 0}(e);if(void 0===r)return!1;const n=q(t.trim());return void 0!==n&&W(n)===r}const U=/%[0-9a-f]{2}/gi,B=/^[A-Za-z0-9\-._~]$/;function W(e){const t="http:"===e.protocol||"https:"===e.protocol?"http(s):":e.protocol,r=e.hostname.endsWith(".")?e.hostname.slice(0,-1):e.hostname,n=""===e.port?"":`:${e.port}`,o=e.pathname.replace(U,(e=>{const t=String.fromCharCode(Number.parseInt(e.slice(1),16));return B.test(t)?t:e.toUpperCase()})).replace(/\/{2,}/g,"/");return`${t}//${r}${n}${o.endsWith("/")?o.slice(0,-1):o}`}function H(e){const t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function q(e){const t=e.trim();if(0===t.length)return;const r=t.includes("://")?t:`https://${t}`;try{return new URL(r)}catch{return}}function z(e){return(e.mcpNetworkAllowlist??[]).flatMap((e=>{const t=P(e);return void 0===t?[]:[t]}))}function G(e,t){if(!0!==t.enabled)return{allowed:!0};if("no_sandbox"===t.mcpNetworkMode)return{allowed:!0};if(!D(e))return{allowed:!1,message:t.blockMessage??p};const r=z(t);return r.length>0&&r.some((t=>function(e,t){const r=D(t);if(!r)return!1;if(!e.includes("://"))return h(H(r.hostname),e);if(M(e,t))return!0;const n=function(e){try{const t=new URL(e);if(""!==t.username||""!==t.password||"/"!==t.pathname||""!==t.search||""!==t.hash)return;return`${t.protocol}//${t.host}/*`}catch{return}}(e);return void 0!==n&&M(n,t)}(t,e)))?{allowed:!0}:{allowed:!1,message:t.blockMessage??p}}function V(e){const t=e?.trim();return t&&t.length>0?t:void 0}function K(e){return V(e)?.toLowerCase()}function J(e,t){const r=K(e.builtinServer),n=K(t.builtinServer);if(void 0!==r||void 0!==n)return void 0!==r&&r===n;const o=V(e.command),s=V(e.serverUrl);if(void 0===o&&void 0===s)return!1;const i=void 0===o||void 0!==t.command&&A(o,t.command),a=void 0===s||void 0!==t.url&&L(s,t.url);return i&&a}function Z(e,t,r){return void 0!==r?.command&&void 0===r.url&&void 0===t&&!0===e?.allowUserOverrideMcpServers}function X({allowedMcpConfiguration:e,server:t,localAgentNetworkAllowlist:r,blockMessage:n,unmatchedServerAllowlist:o,aggregateManagedServerNetworkAllowlists:s=!0,stdioPlatform:i,unsandboxUserExtensionStdio:a}){const c=e?.allowedMcpServers,l=function(e){if(!0!==e?.allowUserOverrideMcpServers)return;const t=(e.deniedMcpServers??[]).flatMap((e=>{const t=V(e.serverUrl),r=void 0===t?void 0:function(e){const t=e.trim();if(0===t.length)return;if(function(e){const t=e.indexOf("://");if(-1===t)return!1;const r=e.slice(t+3),n=r.indexOf("/");return-1===n?r.includes("?"):r.slice(n).includes("*")}(t)){const e=t.indexOf("://");if(-1!==e){const r=t.slice(e+3).split(/[/?#]/,1)[0];if(r?.includes("*")){const e=P(r.replace(/:\d+$/,""));if(void 0!==e)return e}}return}if(!t.includes("://")&&t.includes("*")&&"*"!==t&&!t.startsWith("*."))return;const r=P(e);if(void 0!==r)return r;const n=e.indexOf("://");if(-1===n)return;const o=e.slice(0,n).toLowerCase();if("http"!==o&&"https"!==o)return;const s=e.slice(n+3).split(/[/?#]/,1)[0];if(void 0===s||s.includes("@"))return;const i=P(s.replace(/:\d+$/,""));if(void 0!==i)return i;try{return P(new URL(e).hostname)}catch{return}}(t);return void 0===r?[]:[r]}));return t.length>0?t:void 0}(e),u=void 0===t?void 0:function(e,t){return e?.find((e=>J(e,t)))}(c,t),d=Z(e,u,t),h=function({allowedMcpConfiguration:e,matchedServer:t,server:r}){return void 0===r?(e?.allowedMcpServers?.length??0)>0:void 0!==t||Z(e,t,r)}({allowedMcpConfiguration:e,matchedServer:u,server:t})||void 0===t&&void 0!==l,p=void 0===t?s?c?.flatMap((e=>e.networkAllowlist??[])):void 0:d?[]:function(e,t,r){return void 0===e?r:[...e.networkAllowlist??[],...void 0!==V(e.serverUrl)&&void 0!==t.url?[t.url]:[]]}(u,t,o),f=d&&"win32"===i&&!0===a;let m;m=void 0===t?void 0:f?"no_sandbox":d?"allow_all":function(e,t){var r;if(void 0!==V(e?.command)&&void 0!==t.command&&void 0===t.url)return r=e?.networkMode,("allow_all"===r||"allowlist"===r||"deny_all"===r||"no_sandbox"===r?r:void 0)??"no_sandbox"}(u,t);const g=void 0===t||d?l:void 0;return{enabled:h,mcpNetworkAllowlist:p,...void 0!==m?{mcpNetworkMode:m}:{},...void 0!==g?{mcpNetworkDenylist:g}:{},...void 0!==r?{localAgentNetworkAllowlist:r}:{},...void 0!==n?{blockMessage:n}:{},...f?{win32UserExtensionUnsandbox:!0}:{}}}function Q(e){if(!0===e?.enabled&&"no_sandbox"!==e.mcpNetworkMode)return e}},"../shell-exec/dist/api/index.js"(e,t,r){r.d(t,{BM:()=>Oo,Ls:()=>f,SandboxUnsupportedError:()=>_r,J:()=>x,St:()=>Er,Fn:()=>Do,Qw:()=>a,ue:()=>s,r5:()=>Ie,getLastSandboxFailureReason:()=>kr,oG:()=>no,Ko:()=>T,CG:()=>ht,W1:()=>Z,G6:()=>Mo,dA:()=>He,_B:()=>Qe,OK:()=>Ze,$b:()=>Xe,K3:()=>Rr,tv:()=>st,wG:()=>vt,fZ:()=>bt,s9:()=>mt,XX:()=>yt,T6:()=>et,Po:()=>Ye,$6:()=>nt,l7:()=>it,xS:()=>E,resolveSandboxPolicyForWorkspace:()=>Ct,fB:()=>Dt,spawnInSandbox:()=>xr,Xw:()=>I});var n=r("node:child_process");new Set;const o=["SSH_CLIENT","SSH2_CLIENT"];function s(e){const t=e||process.env,{ELECTRON_RUN_AS_NODE:r,...n}=t;for(const e of Object.keys(n))e.startsWith("AGENT_HOST_DAEMON_")&&delete n[e];for(const e of o)delete n[e];return n}const i="NODE_COMPILE_CACHE";function a(e){const{[i]:t,...r}=e;return r.NODE_DISABLE_COMPILE_CACHE="1",r}const c=["SSH_AUTH_SOCK","DBUS_SESSION_BUS_ADDRESS","XDG_RUNTIME_DIR","WAYLAND_DISPLAY"];function l(e){const t={...e};for(const e of c)delete t[e];return t}const u=[["core.quotePath","false"]];function d(e){const t=function(e){const t=e.GIT_CONFIG_COUNT;if(void 0===t||""===t)return 0;const r=Number.parseInt(t,10);return Number.isFinite(r)&&r>=0?r:0}(e),r=new Set;for(let n=0;no.endsWith(e)))){const n=S(e,r);if(g.existsSync(n))return k(n,t,r)}for(const o of n){const n=S(`${e}${o}`,r);if(g.existsSync(n))return k(n,t,r)}}return e.match(/\.ps1$/i)?{cmd:m.join(process.env.SYSTEMROOT,"System32","WindowsPowerShell","v1.0","PowerShell.exe"),args:["-ExecutionPolicy","Unrestricted","-NoLogo","-NonInteractive","-File",e].concat(t)}:e.match(/\.(bat|cmd)$/i)?{cmd:m.join(process.env.SYSTEMROOT,"System32","cmd.exe"),args:["/C",e,...t]}:e.match(/\.(js)$/i)?{cmd:process.execPath,args:[e].concat(t)}:{cmd:e,args:t}}let _;const C=["/usr/local/bin","/usr/bin","/bin"];function E(){const e=k("rg",[]).cmd;return"rg"!==e?e:void 0}function x(e){if(!e)throw new Error("configureRipgrepPath: path must not be empty");_=e}function P(e){const t=Object.keys(e).filter((e=>"path"===e.toLowerCase()));if(0!==t.length)return"win32"===process.platform?t.find((e=>"Path"===e))??t[0]:t.find((e=>"PATH"===e))??t[0]}function R(e,t){const r=(0,m.dirname)(t);if(!r||"."===r)return e;let n=function(e){const t=P(e);return void 0!==t?e[t]??"":""}(e).split(m.delimiter).filter(Boolean);return 0===n.length&&"win32"!==process.platform&&(n=C),function(e,t){const r=P(e)??("win32"===process.platform?"Path":"PATH"),n={...e};for(const e of Object.keys(n))e!==r&&"path"===e.toLowerCase()&&delete n[e];return n[r]=t,n}(e,[r,...n.filter((e=>e!==r))].join(m.delimiter))}function I(e){return _&&(0,m.isAbsolute)(_)?{...R(e,_),CURSOR_RIPGREP_PATH:_}:e}function T(){if(!_)throw new Error("Ripgrep path not configured. Call configureRipgrepPath() at startup.");return _}const A="win32"===process.platform;function $(e){return!A&&!!e?.SUDO_ASKPASS}function M(e){return $(e)?"alias sudo='sudo -A'; ":""}function D(e){const t=[];let r=0;for(;r=e.length||/\s/.test(e[n])){let o=n;for(;ovoid 0!==t&&e.toUpperCase()===r))}const F=["PYTHONIOENCODING","PYTHONUTF8","PYTHONLEGACYWINDOWSSTDIO"];function N(e){F.some((t=>O(e,t)))||(e.PYTHONIOENCODING="utf-8:surrogateescape")}function L(e){O(e,"WSL_UTF8")||(e.WSL_UTF8="1")}const j="-Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8 -Dstdout.encoding=UTF-8 -Dstderr.encoding=UTF-8",U=["sun.stdout.encoding","sun.stderr.encoding","stdout.encoding","stderr.encoding"],B=`case " \${MAVEN_OPTS-} \${JAVA_TOOL_OPTIONS-} \${JDK_JAVA_OPTIONS-} \${_JAVA_OPTIONS-} " in ${U.map((e=>`*[[:space:]]-D${e}=*`)).join("|")}) ;; *) builtin export MAVEN_OPTS="\${MAVEN_OPTS:+$MAVEN_OPTS }${j}";; esac; `,W=`if ("$env:MAVEN_OPTS $env:JAVA_TOOL_OPTIONS $env:JDK_JAVA_OPTIONS \${env:_JAVA_OPTIONS}" -cnotmatch '(^|\\s)-D(${U.map((e=>e.replace(/\./g,"\\."))).join("|")})=') {\n if ($env:MAVEN_OPTS) { $env:MAVEN_OPTS = "$env:MAVEN_OPTS ${j}" } else { $env:MAVEN_OPTS = '${j}' }\n}`;var H=r("node:crypto?8af2"),q=r("node:os"),z=r("../utils/dist/workspace-paths.js"),G=r("../utils/dist/test-resets.js");let V;function K(e,t){const r=(0,g.lstatSync)(e);return r.isDirectory()&&r.uid===t&&!(18&r.mode)}function J(e){try{(0,g.mkdirSync)(e,{mode:448})}catch(e){if(!(e instanceof Error&&"code"in e&&"EEXIST"===e.code))throw e}}function Z(e){return X(e,{create:!1})}function X(e,{create:t}){const r=process.getuid?.();if(void 0===r)return;const n=(0,m.join)((0,q.tmpdir)(),`cursor-sandbox-${(0,z.r_)((0,m.resolve)(e))}`);try{for(const e of[n,(0,m.join)(n,"tmp")])if(t&&J(e),!K(e,r))return;return n}catch{return}}(0,G.J)((function(){V=void 0}));const Q='builtin eval "${__CURSOR_SANDBOX_TEMP_RESTORE:-}" 2>/dev/null; ',Y=["TMPDIR","TMP","TEMP","TMPPREFIX","NODE_COMPILE_CACHE","NODE_DISABLE_COMPILE_CACHE"],ee="builtin export NODE_DISABLE_COMPILE_CACHE=1; builtin unset NODE_COMPILE_CACHE; ";function te(e){const t=(0,m.join)(e,"tmp");return{TMPDIR:t,TMP:t,TEMP:t,TMPPREFIX:(0,m.join)(t,"sh-")}}function re(e=(0,m.join)((0,q.tmpdir)(),"cursor-sandbox-cache",function(){return V||(V=(0,H.randomBytes)(16).toString("hex")),V}())){return{NPM_CONFIG_CACHE:(0,m.join)(e,"npm"),PNPM_STORE_PATH:(0,m.join)(e,"pnpm-store"),GOCACHE:(0,m.join)(e,"go-build"),GOMODCACHE:(0,m.join)(e,"go-mod"),CARGO_TARGET_DIR:(0,m.join)(e,"cargo-target"),PIP_CACHE_DIR:(0,m.join)(e,"pip"),UV_CACHE_DIR:(0,m.join)(e,"uv"),BUN_INSTALL_CACHE_DIR:(0,m.join)(e,"bun"),YARN_CACHE_FOLDER:(0,m.join)(e,"yarn"),npm_config_devdir:(0,m.join)(e,"node-gyp"),PLAYWRIGHT_BROWSERS_PATH:(0,m.join)(e,"playwright"),PUPPETEER_CACHE_DIR:(0,m.join)(e,"puppeteer"),TURBO_CACHE_DIR:(0,m.join)(e,"turbo"),GRADLE_USER_HOME:(0,m.join)(e,"gradle"),CONDA_PKGS_DIRS:(0,m.join)(e,"conda"),POETRY_CACHE_DIR:(0,m.join)(e,"poetry"),GEM_SPEC_CACHE:(0,m.join)(e,"gem-specs"),COMPOSER_HOME:(0,m.join)(e,"composer"),HOMEBREW_CACHE:(0,m.join)(e,"homebrew"),CYPRESS_CACHE_FOLDER:(0,m.join)(e,"cypress"),NX_CACHE_DIRECTORY:(0,m.join)(e,"nx"),NUGET_PACKAGES:(0,m.join)(e,"nuget"),CCACHE_DIR:(0,m.join)(e,"ccache"),CP_HOME_DIR:(0,m.join)(e,"cocoapods")}}var ne=r("node:fs/promises"),oe=r("../utils/dist/safe-spawn-cwd.js"),se=r("../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js");function ie(){const e=process.env.CURSOR_SANDBOX_POLICY_DIR?.trim();return e?m.resolve(e):m.resolve(m.join(q.homedir(),".cursor","sandbox-policies"))}let ae=0;function ce(){const e=ie();g.mkdirSync(e,{recursive:!0,mode:448});try{g.chmodSync(e,448)}catch{}const t=Date.now();return t-ae>=9e5&&(ae=t,function(e){let t;try{t=g.readdirSync(e)}catch{return}const r=Date.now();for(const n of t){if(!n.startsWith("sandbox-policy-"))continue;const t=m.join(e,n);try{const e=g.statSync(t);if(!e.isFile())continue;r-e.mtimeMs>36e5&&g.unlinkSync(t)}catch{}}}(e)),e}function le(e){const t=ce(),r=H.randomBytes(8).toString("hex"),n=m.join(t,`sandbox-policy-${r}`);return g.writeFileSync(n,e,{encoding:"utf-8",mode:384}),n}const ue="/tmp/node-compile-cache",de="cursor-compile-cache",he=Symbol.for("cursor.startupNodeCompileCache"),pe=process.platform;function fe(e=q.tmpdir(),t=process.platform){if("win32"===t||0===e.length)return[];const r=m.posix.join(e,"node-compile-cache");return r===ue?[]:[r]}function me(e=q.tmpdir(),t=process.env,r=process.platform){if("win32"===r)return[];const n=new Set(fe(e,r));for(const e of["TMPDIR","TMP","TEMP"]){const o=t[e];if(void 0!==o&&m.posix.isAbsolute(o))for(const e of fe(m.posix.resolve(o),r))n.add(e)}return[...n]}function ge(e=process.env,t=q.homedir(),r=process.platform){if("darwin"===r)return t.length>0?m.posix.join(t,"Library/Caches",de):void 0;if("linux"!==r)return;const n=e.XDG_CACHE_HOME;return void 0!==n&&m.posix.isAbsolute(n)?m.posix.join(n,de):t.length>0?m.posix.join(t,".cache",de):void 0}function we(e=process.env,t=process.platform){if("win32"===t)return;const r=Object.getOwnPropertyDescriptor(globalThis,he)?.value,n="string"==typeof r?r:e.NODE_COMPILE_CACHE;if(void 0===n||!m.posix.isAbsolute(n))return;const o=m.posix.resolve(n);return"/"===o?void 0:o}function ye(e=q.homedir(),t=q.tmpdir(),r=process.env,n=process.platform){if("win32"===n)return[];const o=new Set([ue]);e.length>0&&(o.add(m.posix.join(e,".cache",de)),o.add(m.posix.join(e,"Library/Caches",de)));const s=[];for(const i of[...me(t,r,n),ge(r,e,n),we(r,n)])void 0===i||o.has(i)||(o.add(i),s.push(i));return s}function ve(e=q.homedir(),t=q.tmpdir(),r=process.platform,n=process.env){if("win32"===r)return[];const o=[ue,...me(t,n,r)],s=ge(n,e,r);return void 0===s||o.includes(s)||o.push(s),o}function be(e,t){return e.isSymbolicLink()?"a link, not followed":e.isDirectory()?e.uid!==t?`owned by uid ${e.uid}`:void 0:"not a folder"}function Se(e){return"object"!=typeof e||null===e?{}:Object.fromEntries(Object.entries(e).filter((e=>"string"==typeof e[1])))}function ke(e){return"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:"error"}const _e=[".local/bin",".local/share/mise",".local/share/pnpm",".nvm",".volta",".asdf",".pyenv",".rbenv",".rustup",".cargo/bin",".cargo/registry",".cargo/git"],Ce=["bin","sbin","lib","opt","Cellar","share","Frameworks","etc/gitconfig","etc/openssl@3/cert.pem","etc/openssl@3/openssl.cnf","etc/ca-certificates"],Ee=(e,t)=>t.flatMap((t=>Ce.map((r=>({platform:e,scope:"global",path:`${t}/${r}`}))))),xe={linux:[".cache/node",".cache/yarn"],darwin:[".cache/node","Library/Caches/Yarn"]},Pe=e=>[..._e,...xe[e]].map((t=>({platform:e,scope:"home-dir",path:t}))),Re=[{platform:"linux",scope:"global",path:"/bin"},{platform:"linux",scope:"global",path:"/sbin"},{platform:"linux",scope:"global",path:"/usr/bin"},{platform:"linux",scope:"global",path:"/usr/sbin"},{platform:"linux",scope:"global",path:"/lib"},{platform:"linux",scope:"global",path:"/lib64"},{platform:"linux",scope:"global",path:"/usr/lib"},{platform:"linux",scope:"global",path:"/usr/lib64"},{platform:"linux",scope:"global",path:"/usr/libexec"},{platform:"linux",scope:"global",path:"/usr/share"},{platform:"linux",scope:"global",path:"/etc/ld.so.cache"},{platform:"linux",scope:"global",path:"/etc/ld.so.conf"},{platform:"linux",scope:"global",path:"/etc/ld.so.conf.d"},{platform:"linux",scope:"global",path:"/etc/ssl/certs"},{platform:"linux",scope:"global",path:"/etc/ssl/openssl.cnf"},{platform:"linux",scope:"global",path:"/etc/ssl/cert.pem"},{platform:"linux",scope:"global",path:"/etc/ssl/ca-bundle.pem"},{platform:"linux",scope:"global",path:"/etc/ssl/certs/ca-certificates.crt"},{platform:"linux",scope:"global",path:"/etc/pki/tls/certs"},{platform:"linux",scope:"global",path:"/etc/pki/tls/openssl.cnf"},{platform:"linux",scope:"global",path:"/etc/pki/ca-trust/extracted"},{platform:"linux",scope:"global",path:"/etc/resolv.conf"},{platform:"linux",scope:"global",path:"/etc/hosts"},{platform:"linux",scope:"global",path:"/etc/nsswitch.conf"},{platform:"linux",scope:"global",path:"/etc/gai.conf"},{platform:"linux",scope:"global",path:"/etc/alternatives"},{platform:"linux",scope:"global",path:"/etc/mime.types"},{platform:"linux",scope:"global",path:"/etc/profile"},{platform:"linux",scope:"global",path:"/etc/bash.bashrc"},{platform:"linux",scope:"global",path:"/etc/zsh/zshenv"},{platform:"linux",scope:"global",path:"/etc/zsh/zprofile"},{platform:"linux",scope:"global",path:"/etc/zsh/zshrc"},{platform:"linux",scope:"global",path:"/etc/zsh/zlogin"},{platform:"linux",scope:"global",path:"/etc/gitconfig"},{platform:"linux",scope:"home",path:".bashrc"},{platform:"linux",scope:"home",path:".bash_profile"},{platform:"linux",scope:"home",path:".profile"},{platform:"linux",scope:"home",path:".zshenv"},{platform:"linux",scope:"home",path:".zprofile"},{platform:"linux",scope:"home",path:".zshrc"},{platform:"linux",scope:"home",path:".zlogin"},{platform:"linux",scope:"home",path:".gitconfig"},{platform:"linux",scope:"home",path:".ssh/known_hosts"},{platform:"linux",scope:"home",path:".config/mise/config.toml"},{platform:"linux",scope:"home-dir",path:".cache/dotslash"},...Pe("linux"),...Ee("linux",["/usr/local","/home/linuxbrew/.linuxbrew"]),{platform:"linux",scope:"global",path:"/usr/local/go"},{platform:"linux",scope:"global",path:"/nix/store"},{platform:"linux",scope:"global",path:"/nix/var/nix/profiles"},{platform:"linux",scope:"bundled",path:"ripgrep"},{platform:"darwin",scope:"global",path:"/bin"},{platform:"darwin",scope:"global",path:"/usr/bin"},{platform:"darwin",scope:"global",path:"/usr/lib"},{platform:"darwin",scope:"global",path:"/usr/libexec"},{platform:"darwin",scope:"global",path:"/usr/share"},{platform:"darwin",scope:"global",path:"/System/Library"},{platform:"darwin",scope:"global",path:"/System/Cryptexes"},{platform:"darwin",scope:"global",path:"/Library/Apple"},{platform:"darwin",scope:"global",path:"/Library/Developer/CommandLineTools"},{platform:"darwin",scope:"global",path:"/Applications/Xcode.app"},{platform:"darwin",scope:"global",path:"/Library/Preferences/com.apple.dt.Xcode.plist"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/cert.pem"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/certs"},{platform:"darwin",scope:"global",path:"/private/etc/ssl/openssl.cnf"},{platform:"darwin",scope:"global",path:"/private/etc/hosts"},{platform:"darwin",scope:"global",path:"/private/etc/resolv.conf"},{platform:"darwin",scope:"global",path:"/private/etc/apache2/mime.types"},{platform:"darwin",scope:"global",path:"/etc/profile"},{platform:"darwin",scope:"global",path:"/etc/bashrc"},{platform:"darwin",scope:"global",path:"/etc/zshenv"},{platform:"darwin",scope:"global",path:"/etc/zprofile"},{platform:"darwin",scope:"global",path:"/etc/zshrc"},{platform:"darwin",scope:"global",path:"/etc/zlogin"},{platform:"darwin",scope:"global",path:"/etc/gitconfig"},{platform:"darwin",scope:"home",path:".bashrc"},{platform:"darwin",scope:"home",path:".bash_profile"},{platform:"darwin",scope:"home",path:".profile"},{platform:"darwin",scope:"home",path:".zshenv"},{platform:"darwin",scope:"home",path:".zprofile"},{platform:"darwin",scope:"home",path:".zshrc"},{platform:"darwin",scope:"home",path:".zlogin"},{platform:"darwin",scope:"home",path:".gitconfig"},{platform:"darwin",scope:"home",path:".ssh/known_hosts"},{platform:"darwin",scope:"home",path:"Library/Preferences/.GlobalPreferences.plist"},{platform:"darwin",scope:"home",path:".config/mise/config.toml"},{platform:"darwin",scope:"home-dir",path:"Library/Python"},{platform:"darwin",scope:"home-dir",path:"Library/Caches/dotslash"},...Pe("darwin"),...Ee("darwin",["/opt/homebrew","/usr/local"]),{platform:"darwin",scope:"global",path:"/nix/store"},{platform:"darwin",scope:"global",path:"/nix/var/nix/profiles"},{platform:"darwin",scope:"bundled",path:"ripgrep"},{platform:"darwin",scope:"global",path:"/dev/null"},{platform:"darwin",scope:"global",path:"/dev/zero"},{platform:"darwin",scope:"global",path:"/dev/random"},{platform:"darwin",scope:"global",path:"/dev/urandom"}];function Ie(e=process.platform,t=q.default.homedir(),r={}){const n=[];for(const o of Re){if(o.platform!==e)continue;if("global"===o.scope){n.push(o.path);continue}const s="bundled"===o.scope?r[o.path]:(0,m.join)(t,o.path);if(s)try{let e;switch(o.scope){case"home":e=(0,g.lstatSync)(s).isFile();break;case"home-dir":e=(0,g.lstatSync)(s).isDirectory();break;case"bundled":e=(0,g.statSync)(s).isFile()}e&&n.push(s)}catch{}}return n}const Te=[{type:"workspace",pattern:"**/.cursor/*.json"},{type:"workspace",pattern:"**/.cursor/**/*.json"},{type:"workspace",pattern:"**/.cursor/.workspace-trusted"},{type:"workspace",pattern:"!**/.cursor/rules"},{type:"workspace",pattern:"!**/.cursor/rules/**"},{type:"workspace",pattern:"!**/.cursor/commands"},{type:"workspace",pattern:"!**/.cursor/commands/**"},{type:"workspace",pattern:"!**/.cursor/worktrees"},{type:"workspace",pattern:"!**/.cursor/worktrees/**"},{type:"workspace",pattern:"!**/.cursor/skills"},{type:"workspace",pattern:"!**/.cursor/skills/**"},{type:"workspace",pattern:"!**/.cursor/agents"},{type:"workspace",pattern:"!**/.cursor/agents/**"},{type:"workspace",pattern:"**/.claude/*.json"},{type:"workspace",pattern:"**/.claude/**/*.json"},{type:"workspace",pattern:"**/.vscode/**"},{type:"workspace",pattern:"**/.idea/**"},{type:"workspace",pattern:"**/.venv/"},{type:"workspace",pattern:"**/venv/"},{type:"workspace",pattern:"**/*.code-workspace"},{type:"workspace",pattern:"**/.cursorignore"},{type:"workspace",pattern:"**/.workspace-trusted"},{type:"workspace",pattern:"**/.cursor/**/cli.json"},{type:"workspace",pattern:"**/.cursor/**/cli-config.json"},{type:"workspace",pattern:"**/.cursor/**/mcp.json"},{type:"workspace",pattern:"**/.cursor/**/mcp-approvals.json"},{type:"workspace",pattern:"**/.cursor/**/permissions.json"},{type:"git",pattern:"**/.git/hooks/**"},{type:"git",pattern:"**/.git/config"},{type:"git",pattern:"**/.git/config.worktree"},{type:"git",pattern:"**/.git/info/attributes"},{type:"git",pattern:"**/.git/commondir"},{type:"git",pattern:"**/.git/worktrees/*/commondir"},{type:"git",pattern:"**/.git/worktrees/*/gitdir"},{type:"worktree",pattern:".git"},{type:"absolute",pattern:"/etc/ssl/cert.pem"},{type:"absolute",pattern:"/etc/ssl/ca-bundle.pem"},{type:"absolute",pattern:"/private/etc/ssl/cert.pem"},{type:"absolute",pattern:"/etc/ssl/certs/ca-certificates.crt"},{type:"absolute",pattern:"/etc/pki/tls/certs/ca-bundle.crt"},{type:"absolute",pattern:"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem"},{type:"home",pattern:".cursor/sandbox-policies"},{type:"absolute",pattern:"/tmp/node-compile-cache"},{type:"home",pattern:".cache/cursor-compile-cache"},{type:"home",pattern:"Library/Caches/cursor-compile-cache"}];function Ae(e){const t=Te.filter((e=>"workspace"===e.type)).map((e=>e.pattern));return{[e]:t}}function $e(e){const t=Te.filter((e=>"git"===e.type)).map((e=>e.pattern));return{[e]:t}}function Me(e){const t=Te.filter((e=>"worktree"===e.type)).map((e=>e.pattern));return{[e]:t}}Te.filter((e=>"git"===e.type)).map((e=>e.pattern)),Te.filter((e=>"workspace"===e.type&&e.pattern.startsWith("!")&&!e.pattern.endsWith("/**"))).map((e=>e.pattern.replace(/^!(\*\*\/)?/,"")));const De=[];let Oe=null,Fe=null;function Ne(e){if(!(e instanceof Error&&"code"in e&&"string"==typeof e.code)||e.code.startsWith("ERR_"))throw e}async function Le(e,t=""){const r=await(0,ne.lstat)(e).catch(Ne);if(void 0===r||!r.isFile()||r.size>4096)return;const n=await(0,ne.readFile)(e,"utf8").catch(Ne),o=n?.split("\n",1)[0]?.replace(/\r$/,"");if(void 0===o||!o.startsWith(t))return;const s=o.slice(t.length);return s.length>0&&!s.includes("\0")?s:void 0}async function je(e){if(!(0,oe.$f)(e))return(0,ne.realpath)(e).catch(Ne)}async function Ue(e){const t=await Le((0,m.join)(e,".git"),"gitdir: ");if(void 0===t)return;const r=await je((0,m.resolve)(e,t));if(void 0===r)return;const n=await Le((0,m.join)(r,"commondir")),o=void 0===n?r:await je((0,m.resolve)(r,n));return void 0===o?void 0:{gitDir:r,commonDirLink:n,commonDir:o}}async function Be(e){const t=await Ue(e);if(void 0===t||void 0===t.commonDirLink||"worktrees"!==(0,m.basename)((0,m.dirname)(t.gitDir)))return;const r=(0,m.dirname)((0,m.dirname)(t.gitDir));if(".git"!==(0,m.basename)(r)||(ze?t.commonDir.toLowerCase()!==r.toLowerCase():t.commonDir!==r))return;const n=await Le((0,m.join)(t.gitDir,"gitdir"));if(void 0===n)return;const o=(0,m.join)(e,".git"),[s,i]=await Promise.all([je((0,m.resolve)(t.gitDir,n)),je(o)]);return void 0!==s&&void 0!==i&&(ze?s.toLowerCase()===i.toLowerCase():s===i)?r:void 0}let We=null;function He(e){return function(){const e=q.default.homedir();if(null===We){const t=[];for(const r of Te)switch(r.type){case"absolute":t.push(r.pattern);break;case"home":e.length>0&&t.push((0,m.join)(e,r.pattern))}We=t}return[...We,...ye(e)]}().some((t=>{if(Ke(e,t))return!0;const r=function(e){let t;try{t=g.realpathSync.native((0,m.dirname)(e))}catch(e){const t=e instanceof Error&&"code"in e?e.code:void 0;return"ENOENT"===t||"ENOTDIR"===t?void 0:qe}const r=(0,m.join)(t,(0,m.basename)(e));return r===(0,m.dirname)(r)?void 0:r}(t);return r===qe||void 0!==r&&Ke(e,r)}))}const qe=Symbol("unresolved parent");const ze="win32"===process.platform||"darwin"===process.platform;function Ge(e){if(!e.endsWith(m.sep))return e;const t=e.slice(0,-1);return""===t||"win32"===process.platform&&/^[a-zA-Z]:$/.test(t)?e:t}function Ve(e){return e.endsWith(m.sep)?e:e+m.sep}function Ke(e,t){const r=Ge(t);if(ze){const t=e.toLowerCase(),n=r.toLowerCase();return t===n||t.startsWith(Ve(n))}return e===r||e.startsWith(Ve(r))}function Je(e,t){const r=Ge(e);return ze?(0,m.relative)(r.toLowerCase(),t.toLowerCase()).replace(/\\/g,"/"):(0,m.relative)(r,t).replace(/\\/g,"/")}async function Ze(e,t){if(Ke(e,t)){const r=Je(t,e);if((null===Oe&&(Oe=se({ignoreCase:!0}),Oe.add(Te.filter((e=>"workspace"===e.type)).map((e=>e.pattern)))),Oe).ignores(r))return!0}const{isWorktree:r,gitDirParent:n}=await async function(e){const t=await(0,ne.lstat)((0,m.join)(e,".git")).catch(Ne);if(!t?.isFile())return{isWorktree:!1,gitDirParent:e};const r=await async function(e){return(await Ue(e))?.commonDir}(e);return{isWorktree:!0,gitDirParent:void 0===r?e:(0,m.dirname)(r)}}(t);for(const r of new Set([n,t]))if(Ke(e,r)){const t=Je(r,e);if((null===Fe&&(Fe=se({ignoreCase:!0}),Fe.add(Te.filter((e=>"git"===e.type)).map((e=>e.pattern)))),Fe).ignores(t))return!0}return!(!r||!Ke(e,t)||".git"!==Je(t,e))||He(e)}function Xe(e){return void 0!==e&&("allow"===e.default||void 0!==e.allow&&e.allow.length>0)}function Qe(e){return void 0!==e&&"allow"===e.default}function Ye(){return{version:1,default:"deny"}}function et(){return{version:1,default:"allow"}}var tt=r("../utils/dist/path-utils.js");function rt(e){if(!e)return;const t={version:1};if("allow"!==e.default&&"deny"!==e.default||(t.default=e.default),Array.isArray(e.allow)&&e.allow.length>0&&(t.allow=e.allow.filter((e=>"string"==typeof e))),Array.isArray(e.deny)&&e.deny.length>0&&(t.deny=e.deny.filter((e=>"string"==typeof e))),e.logging){const r={};"string"==typeof e.logging.decisionLogPath&&(r.decisionLogPath=e.logging.decisionLogPath),"jsonl"===e.logging.logFormat&&(r.logFormat="jsonl"),Object.keys(r).length>0&&(t.logging=r)}return t}function nt(e){const t=e.type??"workspace_readwrite",r={debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,enableSharedBuildCache:e.enableSharedBuildCache};if("insecure_none"===t)return{type:"insecure_none",...r};let n;if(Array.isArray(e.additionalReadonlyPaths)){const t=e.additionalReadonlyPaths;n=t.length>0?t:void 0}const o={...r,networkAccess:e.networkAccess,networkPolicy:rt(e.networkPolicy),networkPolicyStrict:e.networkPolicyStrict,additionalReadonlyPaths:n,readBoundary:e.readBoundary,additionalReadPaths:Array.isArray(e.additionalReadPaths)?e.additionalReadPaths:void 0,disableTmpWrite:e.disableTmpWrite,privateTmp:e.privateTmp};return"workspace_readonly"===t?{type:"workspace_readonly",...o}:{type:"workspace_readwrite",...o,additionalReadwritePaths:e.additionalReadwritePaths}}function ot(e){if("object"!=typeof e||null===e)return"Expected an object";const t=Object.fromEntries(Object.entries(e));if(void 0!==t.type){const e=["insecure_none","workspace_readwrite","workspace_readonly"];if("string"!=typeof t.type||!e.includes(t.type))return`Invalid type: expected one of ${e.join(", ")}`}const r=["networkAccess","networkPolicyStrict","disableTmpWrite","privateTmp","enableSharedBuildCache","captureDenies"];for(const e of r)if(void 0!==t[e]&&"boolean"!=typeof t[e])return`Invalid ${e}: expected boolean`;const n=["debugOutputDir"];for(const e of n)if(void 0!==t[e]&&"string"!=typeof t[e])return`Invalid ${e}: expected string`;const o=["additionalReadwritePaths","additionalReadonlyPaths","additionalReadPaths"];for(const e of o)if(void 0!==t[e]){if(!Array.isArray(t[e]))return`Invalid ${e}: expected array`;if(!t[e].every((e=>"string"==typeof e)))return`Invalid ${e}: expected array of strings`}if(void 0!==t.readBoundary&&"system"!==t.readBoundary&&"workspace"!==t.readBoundary)return'Invalid readBoundary: expected "system" or "workspace"';if(void 0!==t.networkPolicy){if("object"!=typeof t.networkPolicy||null===t.networkPolicy)return"Invalid networkPolicy: expected object";const e=Object.fromEntries(Object.entries(t.networkPolicy));if(void 0!==e.default&&"allow"!==e.default&&"deny"!==e.default)return'Invalid networkPolicy.default: expected "allow" or "deny"';if(void 0!==e.allow&&!Array.isArray(e.allow))return"Invalid networkPolicy.allow: expected array";if(void 0!==e.deny&&!Array.isArray(e.deny))return"Invalid networkPolicy.deny: expected array"}}async function st(e,t){const r=await async function(e,t){try{const r=await(0,ne.readFile)(e,"utf-8"),n=JSON.parse(r);if(void 0!==ot(n))return{success:!1,error:`Invalid sandbox policy: ${ot(n)??""}`};let o=nt(n);return t&&(o=it(o,t)),{success:!0,policy:o}}catch(e){return e instanceof Error?"code"in e&&"ENOENT"===e.code?{success:!1,error:"File not found"}:e instanceof SyntaxError?{success:!1,error:`Invalid JSON: ${e.message}`}:{success:!1,error:e.message}:{success:!1,error:"Unknown error"}}}(e,t);if(r.success)return r.policy}function it(e,t){if("insecure_none"===e.type)return e;const r=e.additionalReadonlyPaths?.map((e=>(0,tt.o1)(e,t))),n=e.additionalReadPaths?.map((e=>(0,tt.o1)(e,t)));if("workspace_readonly"===e.type)return{...e,additionalReadonlyPaths:r,additionalReadPaths:n};const o=e.additionalReadwritePaths?.map((e=>(0,tt.o1)(e,t)));return{...e,additionalReadonlyPaths:r,additionalReadPaths:n,additionalReadwritePaths:o}}var at=r("../constants/dist/commercial-cursor-hosts.js");function ct(e){const t=e.replace(/\\/g,"/").replace(/\/+$/,"");return""===t?"/":/^[a-zA-Z]:$/.test(t)?`${t}/`:t}function lt(e){const t=ct(e);return/^[a-zA-Z]:\//.test(t)||t.startsWith("//")?t.toLowerCase():t}const ut={insecure_none:0,workspace_readwrite:1,workspace_readonly:2};function dt(){return"1"===process.env[at.K4]}function ht(e){if(!dt())return e.teamAdmin?.type??e.perRepo?.type??e.perUser?.type??"insecure_none";const t=e.teamAdmin?.type??e.perUser?.type;return void 0===t&&void 0===e.perRepo?"insecure_none":Rt(t??"workspace_readwrite",e.perRepo?.type??"insecure_none")}function pt(...e){return e.some((e=>!0===e))}function ft(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return[];if(t.some((e=>0===e.length)))return[];if(1===t.length)return function(e){const t=new Set,r=[];for(const n of e){const e=lt(n);t.has(e)||(t.add(e),r.push(n))}return r}(t[0]).map(ct);let r=new Map(t[0].map((e=>{const t=ct(e);return[lt(t),t]})));for(let e=1;en.has(e))))}return[...r.values()]}function mt(...e){const t=new Map;for(const r of e)if(r)for(const e of r){const r=ct(e),n=lt(r);t.has(n)||t.set(n,r)}return[...t.values()]}const gt=function({defaultValue:e,rank:t}){return{defaultValue:e,merge:(...r)=>{const n=r.filter((e=>void 0!==e));return 0===n.length?e:n.reduce(((e,r)=>t[r]ft(...e);function yt(...e){return gt.merge(...e)}function vt(...e){return wt(...e)}function bt(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return;let r;for(const e of t){if("deny"===e.default){r="deny";break}"allow"===e.default&&void 0===r&&(r="allow")}const n=new Set;for(const e of t)if(e.deny)for(const t of e.deny)n.add(t);const o=new Set;for(const e of t)if(e.allow)for(const t of e.allow)o.add(t);const s=o.size>0?[...o]:void 0;let i;for(let e=t.length-1;e>=0;e--)if(void 0!==t[e].logging){i=t[e].logging;break}const a={version:1};return void 0!==r&&(a.default=r),void 0!==s&&(a.allow=s),n.size>0&&(a.deny=[...n]),void 0!==i&&(a.logging=i),void 0!==a.default||void 0!==a.allow&&0!==a.allow.length||void 0!==a.deny&&0!==a.deny.length||void 0!==a.logging?a:void 0}function St(e,t){if(!e||0===e.length)return[...t];const r=new Set(e);for(const e of t)r.has(e)&&r.delete(e),r.add(e);return[...r]}function kt(...e){const t=e.filter((e=>void 0!==e));if(0===t.length)return;const r={};for(const e of t)for(const[t,n]of Object.entries(e))r[t]=St(r[t],n);return 0!==Object.keys(r).length?r:void 0}function _t(...e){for(let t=e.length-1;t>=0;t--)if(void 0!==e[t])return e[t]}async function Ct(e,t,r={}){if(!t)return{policy:{type:"insecure_none"}};if(dt()&&(t=Mt(t,e)),(0,oe.$f)(e))return Ot(t,{workspaceDir:e});if("workspace_readwrite"!==(Pt(t)??"workspace_readwrite"))return Ot(t,{workspaceDir:e});const n=r.stat??ne.stat,o=await async function(e,t){for(let r=e;;r=(0,m.dirname)(r)){if((0,oe.$f)(r))return;const e=await Et(r,t);if(void 0!==e)return e;if((0,m.dirname)(r)===r)return}}(e,n);let s=o?.root??e;if(o?.isFile){const e=await Be(o.root);void 0!==e&&(s=(0,m.dirname)(e)),t=xt(t,void 0===e?[]:[e],Me(o.root))}return t=await async function(e,t,r){const n=Nt(e,"workspace_readwrite"),o=mt(n.perUser?.additionalReadwritePaths,n.perRepo?.additionalReadwritePaths,n.teamAdmin?.additionalReadwritePaths);if(0===o.length)return e;const s=(await Promise.all(o.map((async e=>{if(t.has(ct(e))||(0,oe.$f)(e))return[];const n=await Et(e,r);if(void 0===n)return[];const o=[Ae(e),$e(e)];if(n.isFile){o.push(Me(e));const t=await Be(e);void 0!==t&&o.push($e((0,m.dirname)(t)))}return o})))).flat();return 0===s.length?e:xt(e,[],...s)}(t,new Set([ct(e)]),n),Ot(t,{workspaceDir:e,gitDirParent:s})}async function Et(e,t){const r=await t((0,m.join)(e,".git")).catch(Ne);return r?.isFile()||r?.isDirectory()?{root:e,isFile:r.isFile()}:void 0}function xt(e,t,...r){const n=dt(),o=n?e.perUser:e.perRepo,s="workspace_readwrite"===o?.type||void 0===o?o:void 0,i={...s,type:"workspace_readwrite",additionalReadwritePaths:t.length>0?[...s?.additionalReadwritePaths??[],...t]:s?.additionalReadwritePaths,writeProtectionMapping:kt(s?.writeProtectionMapping,...r)};return n?{...e,perUser:i}:{...e,perRepo:i}}function Pt(e){const{perUser:t,perRepo:r,teamAdmin:n}=e,o=[t,r,n].filter((e=>void 0!==e));if(0===o.length)return;const s=o[0].type;for(const e of o)if(e.type!==s)throw new Error(`Cannot merge policies of different types: found "${s}" and "${e.type}". All policies must be of the same type (all workspace_readwrite, all workspace_readonly, or all insecure_none).`);return s}function Rt(e,t){return ut[e]>=ut[t]?e:t}function It(e,t){if(void 0===e||e.type===t)return e;if("insecure_none"===t)return{type:t,debugOutputDir:e.debugOutputDir,captureDenies:e.captureDenies,enableSharedBuildCache:e.enableSharedBuildCache};if("insecure_none"===e.type)return{...e,type:t};if("workspace_readonly"===t){if("workspace_readwrite"===e.type){const{additionalReadwritePaths:r,...n}=e;return{...n,type:t}}return e}return e}function Tt(e){if("deny"===e?.default||void 0!==e?.deny&&0!==e.deny.length)return{version:1,..."deny"===e.default?{default:"deny"}:{},...void 0!==e.deny&&e.deny.length>0?{deny:e.deny}:{}}}function At(e,t,r){if(void 0===e||"insecure_none"===t)return;const n="insecure_none"===e.type?void 0:e,o={captureDenies:!0===e.captureDenies||void 0,networkPolicy:Tt(n?.networkPolicy),networkPolicyStrict:!0===n?.networkPolicyStrict||void 0,readBoundary:"workspace"===n?.readBoundary?"workspace":void 0,additionalReadPaths:void 0===n?.additionalReadPaths?void 0:ft(n.additionalReadPaths,r),additionalReadonlyPaths:n?.additionalReadonlyPaths,disableTmpWrite:!0===n?.disableTmpWrite||void 0,ignoreMapping:n?.ignoreMapping,writeProtectionMapping:n?.writeProtectionMapping};return"workspace_readonly"===t?{type:t,...o}:{type:"workspace_readwrite",...o}}function $t(e,t){return void 0===e||"insecure_none"===e.type||void 0===t?e:{...e,additionalReadPaths:e.additionalReadPaths?.map((e=>ct((0,tt.o1)(e,t))))}}function Mt(e,t){const r=Pt({perUser:e.perUser,teamAdmin:e.teamAdmin})??"workspace_readwrite",n=void 0===e.perRepo?r:Rt(r,e.perRepo.type),o=$t(It(e.perUser,n),t),s=$t(It(e.teamAdmin,n),t),i=mt("insecure_none"===o?.type?void 0:o?.additionalReadPaths,"insecure_none"===s?.type?void 0:s?.additionalReadPaths);return{perUser:o,perRepo:At(e.perRepo,n,i),teamAdmin:s}}function Dt(e,t){return Mt(e,t)}function Ot(e,t){return function(e,t){dt()&&(e=Mt(e,t?.workspaceDir));const r=Pt(e);if(void 0===r)return Ut({},t);switch(r){case"workspace_readwrite":return Ut(Nt(e,r),t);case"workspace_readonly":return function(e,t){const r=t?.debug,n=Lt(e,t),o={policy:jt({type:"workspace_readonly",disableTmpWrite:n.disableTmpWrite,networkPolicyStrict:n.networkPolicyStrict,readBoundary:n.readBoundary,additionalReadPaths:n.additionalReadPaths,additionalReadonlyPaths:n.additionalReadonlyPaths,networkPolicy:n.networkPolicy,debugOutputDir:n.debugOutputDir,captureDenies:n.captureDenies,enableSharedBuildCache:n.enableSharedBuildCache,privateTmp:n.privateTmp,ignoreMapping:n.ignoreMapping,writeProtectionMapping:n.writeProtectionMapping},"workspace_readonly")};return r&&(o.debug={fieldSources:n.fieldSources}),o}(Nt(e,r),t);case"insecure_none":return function(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,s=t?.debug,i={policy:jt({type:"insecure_none",allowlistEscalated:pt(r?.allowlistEscalated,n?.allowlistEscalated,o?.allowlistEscalated)||void 0,debugOutputDir:_t(r?.debugOutputDir,n?.debugOutputDir,o?.debugOutputDir),captureDenies:pt(r?.captureDenies,n?.captureDenies,o?.captureDenies)||void 0,enableSharedBuildCache:_t(r?.enableSharedBuildCache,n?.enableSharedBuildCache,o?.enableSharedBuildCache)},"insecure_none")};return s&&(i.debug={fieldSources:{}}),i}(Nt(e,r),t);default:throw new Error(`Unknown policy type: ${String(r)}`)}}(e,t)}function Ft(e,t){return e?.type===t}function Nt(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e;return{perUser:Ft(r,t)?r:void 0,perRepo:Ft(n,t)?n:void 0,teamAdmin:Ft(o,t)?o:void 0}}function Lt(e,t){const r=t?.debug,{perUser:n,perRepo:o,teamAdmin:s}=e,i=t?.workspaceDir??process.cwd(),a=function(e){const t=function(){if(0!==De.length)return{version:1,deny:[...De]}}(),r=q.default.homedir(),n=[];for(const e of Te)switch(e.type){case"workspace":case"git":case"worktree":break;case"absolute":n.push(e.pattern);break;case"home":r.length>0&&n.push((0,m.join)(r,e.pattern));break;default:{const t=e.type;throw new Error(`Unknown entry type: ${String(t)}`)}}return n.push(...ye(r)),{type:"workspace_readwrite",additionalReadonlyPaths:n,writeProtectionMapping:Ae(e),...t&&{networkPolicy:t},networkPolicyStrict:!0}}(i),c={},l=[n,o,s],u=["perUser","perRepo","teamAdmin","hardcoded"],d=(e,t)=>{r&&(c[e]=u[t]??"unknown")},h=pt(n?.disableTmpWrite,o?.disableTmpWrite,s?.disableTmpWrite);for(let e=l.length-1;e>=0;e--)if(!0===l[e]?.disableTmpWrite){d("disableTmpWrite",e);break}const p=pt(n?.networkPolicyStrict,o?.networkPolicyStrict,s?.networkPolicyStrict,a.networkPolicyStrict);a.networkPolicyStrict&&d("networkPolicyStrict",3);const f=dt()?yt(_t(n?.readBoundary,s?.readBoundary)??"system",o?.readBoundary):_t(n?.readBoundary,o?.readBoundary,s?.readBoundary)??"system",g=_t(n?.additionalReadPaths,o?.additionalReadPaths),w=!1===s?.allowUserOverrideReadPaths?mt(s.additionalReadPaths):mt(g,s?.additionalReadPaths),y="workspace"===f?w:void 0,v=mt(n?.additionalReadonlyPaths,o?.additionalReadonlyPaths,s?.additionalReadonlyPaths,a.additionalReadonlyPaths),b=v.length>0?v:void 0;let S=bt(n?.networkPolicy,o?.networkPolicy,s?.networkPolicy,a.networkPolicy);const k=s?.networkPolicy?.allow;void 0!==k&&k.length>0&&void 0!==S&&(S={...S,allow:[...k]},r&&(c["networkPolicy.allow"]="teamAdmin (replace)"));const _=void 0!==(C=S)?C:{version:1,default:"deny"};var C;const E=_t(n?.debugOutputDir,o?.debugOutputDir,s?.debugOutputDir),x=pt(n?.captureDenies,o?.captureDenies,s?.captureDenies),P=_t(n?.enableSharedBuildCache,o?.enableSharedBuildCache,s?.enableSharedBuildCache),R=_t(n?.privateTmp,o?.privateTmp,s?.privateTmp),I=kt(n?.ignoreMapping,o?.ignoreMapping,s?.ignoreMapping,a.ignoreMapping),T=$e(t?.gitDirParent??i);return{disableTmpWrite:h||void 0,networkPolicyStrict:p,readBoundary:f,additionalReadPaths:y,additionalReadonlyPaths:b,networkPolicy:_,debugOutputDir:E,captureDenies:x||void 0,enableSharedBuildCache:P,privateTmp:R,ignoreMapping:I,writeProtectionMapping:kt(n?.writeProtectionMapping,o?.writeProtectionMapping,s?.writeProtectionMapping,a.writeProtectionMapping,T),fieldSources:c}}function jt(e,t){const r={...e,type:t};for(const[e,t]of Object.entries(r))void 0===t&&Reflect.deleteProperty(r,e);return r}function Ut(e,t){const{perUser:r,perRepo:n,teamAdmin:o}=e,s=t?.debug,i=Lt(e,t),a=mt(r?.additionalReadwritePaths,n?.additionalReadwritePaths,o?.additionalReadwritePaths),c={policy:jt({type:"workspace_readwrite",disableTmpWrite:i.disableTmpWrite,networkPolicyStrict:i.networkPolicyStrict,readBoundary:i.readBoundary,additionalReadPaths:i.additionalReadPaths,additionalReadwritePaths:a.length>0?a:void 0,additionalReadonlyPaths:i.additionalReadonlyPaths,networkPolicy:i.networkPolicy,debugOutputDir:i.debugOutputDir,captureDenies:i.captureDenies,enableSharedBuildCache:i.enableSharedBuildCache,privateTmp:i.privateTmp,ignoreMapping:i.ignoreMapping,writeProtectionMapping:i.writeProtectionMapping},"workspace_readwrite")};return s&&(c.debug={fieldSources:i.fieldSources}),c}var Bt=r("../utils/dist/workload-spawn.js"),Wt=r("../context/dist/logger.js"),Ht=r("../context/dist/core.js"),qt=r("../utils/dist/command-glob.js");const zt=n.execFile,Gt=new WeakMap;function Vt(e,t,r){return e===t?"related":r?.has(e)?"probably_unrelated":"maybe_related"}const Kt="darwin"===process.platform,Jt="linux"===process.platform,Zt=(0,Wt.h)("shell-exec:sandbox");function Xt(e){const t=ce();return e&&0!==e.length?e.includes(t)?e:[...e,t]:[t]}let Qt,Yt=!0,er=!1;function tr(){return Qt}function rr(e){"linux"===process.platform&&Object.assign(e,I(e))}let nr=null,or=null,sr=null,ir=null,ar=!1,cr=null;function lr(e){return{...e,additionalReadonlyPaths:Xt(e.additionalReadonlyPaths)}}class ur extends Error{}function dr(e){return e instanceof Error&&"code"in e&&"string"==typeof e.code?e.code:"unknown"}function hr(e,t,r){let n;e.ignoreMapping&&(n=function(e){return vr(e)}(e.ignoreMapping));const o=function(e,t,r){const n=e&&e.length>0?function(...e){const t={};for(const r of e){let e=!1;try{e=(0,g.existsSync)(r)&&(0,g.statSync)(r).isDirectory()}catch{}if(e)t[r]||(t[r]=[]),t[r].push("**");else{const e=r.lastIndexOf("/"),n=e>0?r.slice(0,e):"/",o=e>=0?r.slice(e+1):r;t[n]||(t[n]=[]),o?t[n].push(o,`${o}/**`):t[n].push("**")}}return t}(...e):{},o=!Jt||yr(r),s={...n};for(const[e,r]of Object.entries(t??{})){const t=e.startsWith("file://")?br(e):e;(o||yr(t))&&(s[e]=St(s[e],r))}if(0!==Object.keys(s).length)return vr(s)}(e.additionalReadonlyPaths,e.writeProtectionMapping,t),s=(i=e.readBoundary,r?.workspaceReadEnabled??function(){const e=Yt;return"function"==typeof e?e():e}()?i??"system":"system");var i;const a=function(e=process.platform){const t=[],r=new Set,n={};try{n.ripgrep=T()}catch{}for(const o of Ie(e,q.homedir(),n))r.has(o)||(r.add(o),t.push(o));return t}(),c=[t,..."workspace_readwrite"===e.type&&e.additionalReadwritePaths||[],Z(t)].filter((e=>void 0!==e)),l="workspace"===s?(e.additionalReadPaths??[]).flatMap((e=>function(e,t){let r=e.trim();(r.startsWith("~/")||r.startsWith("~\\"))&&(r=m.join(q.homedir(),r.slice(2)));const n=e=>e.includes("*")||e.includes("?"),o=/[/\\]\*\*?$/;if(o.test(r)&&n(m.basename(r.replace(/(?:[/\\]\*\*?)+$/,""))))return Zt.warn((0,Ht.q6)(),"[additionalReadPathGrants] a Read Allowlist file-name glob followed by /* or /** grants nothing"),[];const s=m.basename(r);if(o.test(r)||!n(s))return function(e){const t=[],r=new Set;for(const n of e){let e=n.trim();if(!e)continue;"~"===e?e=q.homedir():(e.startsWith("~/")||e.startsWith("~\\"))&&(e=m.join(q.homedir(),e.slice(2))),e=e.replace(/\/\*\*$/,"").replace(/\/\*$/,""),e=e.replace(/\\\*\*$/,"").replace(/\\\*$/,"");const o=m.basename(e);if((o.includes("*")||o.includes("?"))&&(e=m.dirname(e)),!e||"."===e)continue;const s=m.normalize(e);r.has(s)||(r.add(s),t.push(s))}return t}([e]);const i=m.dirname(r);return m.isAbsolute(i)?function(e,t,r){const n=(0,qt.b)(t),o=[];let s;try{const t=(0,g.realpathSync)(e);if(r.filter((e=>g.existsSync(e))).map((e=>(0,g.realpathSync)(e))).some((e=>(0,tt.BJ)(t,e))))return[];s=g.opendirSync(t);for(let e=1;;e++){const r=s.readSync();if(null===r)return o;if(e>1e4)throw new ur("its folder has more than 10000 entries");if(!n(r.name))continue;const i=m.join(t,r.name);try{if(!g.lstatSync(i).isFile()||m.dirname((0,g.realpathSync)(i))!==t)continue}catch(e){Zt.info((0,Ht.q6)(),`[fileNameGlobMatches] skips a matching file: error ${dr(e)}`);continue}if(256===o.length)throw new ur("more than 256 files match");o.push(i)}}catch(e){const t=e instanceof ur?e.message:`error ${dr(e)}`;return Zt.warn((0,Ht.q6)(),`[fileNameGlobMatches] a Read Allowlist file-name glob grants nothing: ${t}`),[]}finally{s?.closeSync()}}(i,s,t):[]}(e,c))):[],u=[...a],d=new Set(a);for(const e of l)d.has(e)||(d.add(e),u.push(e));const h={cwd:t,readBoundary:s,hardcodedReadPaths:u,additionalReadonlyPaths:o,networkAccess:Xe(e.networkPolicy),ignoreMapping:n};return"workspace_readonly"===e.type?{type:e.type,...h}:{type:e.type,...h,additionalReadwritePaths:e.additionalReadwritePaths||[],disableTmpWrite:e.disableTmpWrite||!1}}function pr(e){const t={sandbox:e};return Jt&&function(){const e=er;return"function"==typeof e?e():e}()&&(t.kernelMountBudget=!0),t}function fr(e){if(null!==nr)return nr;try{const t=tr();return Zt.info(e,`[checkBinaryAvailable] Resolved binary path: ${t}`),t?(nr=g.existsSync(t),nr?Zt.info(e,`[checkBinaryAvailable] Binary path exists: ${String(nr)}`):(or=new Error(`Sandbox binary not found at ${t}`),Zt.info(e,`[checkBinaryAvailable] Binary not found at: ${t}`)),nr):(or=new Error("Sandbox binary path was not configured"),nr=!1,Zt.info(e,"[checkBinaryAvailable] Binary path not set, returning false"),!1)}catch(t){return or=t instanceof Error?t:new Error(String(t)),nr=!1,Zt.info(e,`[checkBinaryAvailable] Exception checking binary: ${String(t)}`),!1}}function mr(e){if(null!==ir)return ir;const t=e??(0,Ht.q6)();if(Zt.info(t,"[isSandboxHelperSupported] Starting sandbox support check..."),!fr(t)){const e=or?.message||"Binary check failed";return sr=e,Zt.info(t,`[isSandboxHelperSupported] Binary not available, returning false. Reason: ${e}`),ir=!1,ir}if("win32"===process.platform)return sr="Windows sandbox helper only provides network proxy, not filesystem isolation",Zt.info(t,"[isSandboxHelperSupported] win32: returning false (proxy-only, no filesystem sandbox)"),ir=!1,ir;if("darwin"===process.platform)return sr=null,Zt.info(t,`[isSandboxHelperSupported] ${process.platform} platform, binary available, sandbox supported!`),ir=!0,ir;const{binaryPath:r,args:o,env:s}=function(e,t){const r=pr(hr(lr({type:"workspace_readwrite"}),t)),n=String(tr());Zt.info(e,`[sandboxPreflight] Running preflight with binary: ${n}`),Zt.info(e,`[sandboxPreflight] CWD: ${t}`);const o={...process.env};return rr(o),{binaryPath:n,args:["--policy",le(JSON.stringify(r)),"--preflight-only","--","/bin/true"],env:o}}(t,process.cwd());try{const e=Date.now();(0,Bt.D9)(n.execFileSync,r,o,{stdio:["ignore","ignore","pipe"],timeout:gr,env:s,shell:!1});const i=Date.now()-e;return sr=null,Zt.info(t,`[isSandboxHelperSupported] Preflight succeeded in ${i}ms, sandbox supported!`),ir=!0,ir}catch(e){return function(e,t){const{message:r,status:n,stderrText:o}=t;return Zt.error(e,`[sandboxPreflight] Preflight failed: ${r}`),Zt.error(e,`[sandboxPreflight] Exit status: ${n}`),o&&Zt.error(e,`[sandboxPreflight] Stderr: ${o}`),sr=2===n?`Linux preflight failed with exit code 2 (unsupported kernel features). stderr: ${o||"none"}`:`Linux preflight failed: ${r||"unknown error"}. Exit status: ${n}. stderr: ${o||"none"}`,ir=!1,!1}(t,function(e){if("object"!=typeof e||null===e)return{stderrText:""};const t="message"in e&&"string"==typeof e.message?e.message:void 0,r=!("status"in e)||"number"!=typeof e.status&&null!==e.status?void 0:e.status,n="stderr"in e?e.stderr:void 0;return{message:t,status:r,stderrText:Buffer.isBuffer(n)||"string"==typeof n?n.toString():""}}(e))}}(0,G.J)((function(){ir=null,ar=!1,cr=null,sr=null,nr=null,or=null}));const gr=15e3;function wr(e,t=[],r={},o){const i=(0,Ht.q6)();if(r.env=a(s(r.env)),!fr(i))throw new Error(`Sandbox binary not available: ${or?.message||"binary not configured"}. Please build the binary or use 'insecure_none' policy.`);if("insecure_none"===o.type)return(0,Bt.D9)(n.spawn,e,t,{...r,windowsHide:!0});if("workspace_readwrite"===o.type||"workspace_readonly"===o.type)return function(e,t,r,o){if("workspace_readwrite"!==o.type&&"workspace_readonly"!==o.type)throw new Error("Expected workspace_readwrite or workspace_readonly policy");const i=String(r.cwd??process.cwd()),c=o.sandboxWorkspaceRoot??i;let u=e,d=t;r.shell&&("win32"===process.platform?(u="string"==typeof r.shell?r.shell:"cmd.exe",d=["/c",`${e} ${t.join(" ")}`]):(u="string"==typeof r.shell?r.shell:"/bin/sh",d=["-c",`${e} ${t.join(" ")}`]));const h=function({workspaceRoot:e,executionCwd:t}){const r=m.resolve(e),n=m.resolve(t),o=Sr(r);if(n===r||n===o)return;const s=e=>(0,tt.ZU)({basePath:o,targetPath:e})?m.join(r,m.relative(o,e)):void 0,i=(0,tt.ZU)({basePath:r,targetPath:n})?n:s(n)??n;return{directory:i,fallbackDirectory:s(Sr(n))??i}}({workspaceRoot:c,executionCwd:i});"win32"!==process.platform&&void 0!==h&&({command:u,args:d}=(0,oe.kO)(u,d,h));const p=hr(lr(o),c),f=(0,Ht.q6)();!function({log:e,dirs:t=ve(q.homedir(),q.tmpdir(),pe),createOnly:r=[we(process.env,pe)].filter((e=>void 0!==e)),policyDir:n=ie(),uid:o=process.getuid?.()??-1}){const s=m.join(n,"node-compile-cache-removed-1"),{record:i,problem:a}=function(e){const t=e=>({record:{cleaned:[],kept:{},failed:{}},problem:e});let r,n;try{r=g.readFileSync(e,"utf8")}catch(e){const r=ke(e);return t("ENOENT"===r?void 0:r)}try{n=JSON.parse(r)}catch(e){return t(e instanceof SyntaxError?"not JSON":ke(e))}if("object"!=typeof n||null===n)return t("not a record");const o="cleaned"in n?n.cleaned:void 0;return{record:{cleaned:Array.isArray(o)?o.filter((e=>"string"==typeof e)):[],kept:Se("kept"in n?n.kept:void 0),failed:Se("failed"in n?n.failed:void 0)}}}(s);void 0!==a&&e(`node compile cache: starting a new cleanup record (${a})`);const c=new Set(i.cleaned),l=new Set(t);let u=!1;for(const n of[...t,...r.filter((e=>!l.has(e)))])try{const t=g.lstatSync(n,{throwIfNoEntry:!1});if(void 0!==t){const r=be(t,o);if(void 0!==r){i.kept[n]!==r&&(e(`node compile cache: kept ${n} (${r})`),i.kept[n]=r,u=!0);continue}l.has(n)&&!c.has(n)&&(g.rmSync(n,{recursive:!0,force:!0}),e(`node compile cache: removed ${n}`))}g.mkdirSync(n,{recursive:!0,mode:448}),l.has(n)&&!c.has(n)&&(c.add(n),u=!0),void 0===i.kept[n]&&void 0===i.failed[n]||(delete i.kept[n],delete i.failed[n],u=!0)}catch(t){const r=ke(t);i.failed[n]!==r&&(e(`node compile cache: could not prepare ${n} (${r})`),i.failed[n]=r,u=!0)}u&&function(e,t){const r=`${e}.${process.pid}.tmp`;try{g.writeFileSync(r,`${JSON.stringify(t)}\n`,{mode:384}),g.renameSync(r,e)}catch{g.rmSync(r,{force:!0})}}(s,{...i,cleaned:[...c]})}({log:e=>Zt.info(f,e)});const w=function(e){if(!("workspace"!==e.readBoundary||"workspace_readwrite"===e.type&&e.disableTmpWrite||"win32"===process.platform))return X(e.cwd,{create:!0})}(p);let y;w&&(p.additionalReadwritePaths=[...p.additionalReadwritePaths??[],w],Jt&&!0===o.privateTmp&&(y=te(w).TMPDIR));const v=function(e){if("insecure_none"===e.type)return;const t=e.networkPolicy;if(void 0===t)return;if(!Xe(t))return;const r=void 0!==t.deny&&t.deny.length>0;return"allow"!==t.default||r?{version:1,...t}:void 0}(o),b=pr(p);void 0!==y&&(b.mapTmpTo=y),void 0!==v&&(b.networkPolicy=v),!1===o.networkPolicyStrict&&(b.networkPolicyStrict=!1);const S=["--policy",le(JSON.stringify(b)),"--",u,...d],k=s(process.env),_={..."linux"===process.platform?l(k):k,..."linux"===process.platform&&r.env?l(r.env):r.env,CURSOR_SANDBOX:"native"};rr(_);const C=new Set(Y);if(w){const e=function(e,t,r){const n=te(e);if(r){const r=re();for(const[o,s]of Object.entries(re(e)))t[o]===r[o]&&(n[o]=s)}return n}(w,_,o.enableSharedBuildCache);Object.assign(_,e);for(const t of Object.keys(e))C.add(t);_.__CURSOR_SANDBOX_TEMP_RESTORE=Object.entries(e).map((([e,t])=>`builtin export ${e}='${t.replace(/'/g,"'\\''")}'`)).join("; ")}_.__CURSOR_SANDBOX_OWNED_ENV=[...C].join(" ");const E={cwd:void 0!==y?p.cwd:r.cwd||i,env:a(_),stdio:r.stdio||["pipe","pipe","pipe"],detached:r.detached,windowsHide:!0};try{const e=new Date,t=(0,Bt.D9)(n.spawn,String(tr()),S,E);return Kt&&t.pid&&function(e,t){Gt.set(e,t)}(t,{startTime:e,pid:t.pid}),t}catch(e){throw new Error(`Failed to spawn sandboxed process: ${String(e)}`)}}(e,t,r,o);throw new Error(`Unsupported sandbox policy: ${String(o)}`)}function yr(e,t=e=>g.existsSync(e)){if((0,oe.$f)(e))return!0;let r=m.resolve(e);for(;;){try{if(t(m.join(r,".git")))return!0}catch{}const e=m.dirname(r);if(e===r)return!1;r=e}}function vr(e,t,r,n){const o={};for(const[t,r]of Object.entries(e)){const e=t.startsWith("file://")?br(t):t;o[e]=St(o[e],r);const n=Sr(e);n!==e&&(o[n]=St(o[n],r))}return o}function br(e){let t=e.replace(/^file:\/\//,"");return t=decodeURIComponent(t),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t}function Sr(e,t){if((0,oe.$f)(e))return e;try{return(t??g.realpathSync)(e)}catch{return e}}function kr(){return sr}class _r extends Error{reason;constructor(e,t){super(e),this.reason=t,this.name="SandboxUnsupportedError"}}const Cr="darwin"===process.platform;function Er(e){!function(e){T();const{sandboxBinaryPath:t,workspaceReadEnabled:r,kernelMountBudget:n}=e;Qt||(Qt=t),void 0!==r&&(Yt=r),void 0!==n&&(er=n)}(e)}function xr(e,t=[],r={},o){if(r.env=s(r.env),o.enableSharedBuildCache&&(r={...r,env:{...s(process.env),...re(),...r.env}}),"insecure_none"!==o.type){if(mr())return wr(e,t,r,o);const n=kr();throw new _r(`Sandbox policy '${o.type}' is not supported on this system. Ensure the sandbox helper binary is available, or use 'insecure_none'. Reason: ${n||"unknown"}`,n??void 0)}return function(e,t,r,o={spawn:n.spawn,spawnWorkload:Bt.D9}){return o.spawnWorkload(o.spawn,e,t,{...r,env:a(r.env??process.env),windowsHide:!0})}(e,t,r)}function Pr(e){return Cr?async function(e){const t=Gt.get(e);return t?(r=t.pid,n=t.startTime,o=t.unrelatedPids,new Promise((e=>{try{const t=new Date,s=["show","--style","ndjson","--predicate",'process=="kernel" AND eventMessage CONTAINS "Sandbox:" AND eventMessage contains "deny"',"--last",Math.ceil((t.getTime()-n.getTime())/1e3).toString()];(0,Bt.D9)(zt,"/usr/bin/log",s,((t,n)=>{if(t)return void e([{raw:t.message}]);const s=n.split(/\r?\n/).filter((e=>e.trim().length>0)),i=[];for(const e of s)try{const t=JSON.parse(e),n=t?.eventMessage??"";if(!n||"string"!=typeof n)continue;const s=/^Sandbox:\s+([^(]+)\((\d+)\)\s+([a-zA-Z-]+)\((\d+)\)\s+([^\s]+)\s+(.+)$/.exec(n);if(s){const[,e,a,c,l,u,d]=s,h=Number(a);i.push({timestamp:t.timestamp,processName:e.trim(),pid:h,decision:c.toLowerCase(),decisionCode:Number(l),operation:u,target:d,duplicateCount:1,raw:n,relationship:Vt(h,r,o)});continue}const a=/^(\d+) duplicate report for Sandbox: (.+)$/.exec(n);if(a){const e=Number(a[1]),s=a[2],c=/^([^(]+)\((\d+)\)\s+([a-zA-Z-]+)\((\d+)\)\s+([^\s]+)\s+(.+)$/.exec(s);if(c){const[,s,a,l,u,d,h]=c,p=Number(a);i.push({timestamp:t.timestamp,processName:s.trim(),pid:p,decision:l.toLowerCase(),decisionCode:Number(u),operation:d,target:h,duplicateCount:e,raw:n,relationship:Vt(p,r,o)})}else i.push({timestamp:t.timestamp,duplicateCount:e,raw:n});continue}i.push({timestamp:t.timestamp,raw:n})}catch{}e(i)}))}catch(t){e([{raw:String(t)}])}}))):(console.log("No sandbox metadata found on child process"),[]);var r,n,o}(e):Promise.resolve([])}function Rr(e,t){if(Cr)try{(0,g.accessSync)("/usr/bin/sandbox-exec",g.constants.X_OK)}catch{return!1}return mr(t?.ctx)}var Ir=r("node:stream"),Tr=r("../context/dist/otel.js"),Ar=r("../utils/dist/writable-iterable.js");const $r="--",Mr='builtin eval "$1" 3<&- 4>&-';var Dr=r("node:string_decoder");const Or=50,Fr=262144;class Nr{writable;pending=[];pendingBytes=0;flushTimeout;flushPromise;flushIntervalMs;maxBufferedBytes;constructor(e,t){this.writable=e,this.flushIntervalMs=t?.flushIntervalMs??Or,this.maxBufferedBytes=t?.maxBufferedBytes??Fr}async push(e,t){0!==t.length&&(this.pending.push({type:e,data:t}),this.pendingBytes+=t.length,this.pendingBytes>=this.maxBufferedBytes?await this.flush():this.scheduleFlush())}async flush(){if(this.clearFlushTimeout(),this.flushPromise)return await this.flushPromise,void(this.pendingBytes>0&&await this.flush());if(0===this.pendingBytes)return;const e=this.pending;this.pending=[],this.pendingBytes=0,this.flushPromise=this.writeBufferedOutput(e);try{await this.flushPromise}finally{this.flushPromise=void 0}}async close(){await this.flush()}scheduleFlush(){void 0===this.flushTimeout&&(this.flushTimeout=setTimeout((()=>{this.flushTimeout=void 0,this.flush()}),this.flushIntervalMs))}clearFlushTimeout(){void 0!==this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=void 0)}async writeBufferedOutput(e){for(const t of function(e){if(0===e.length)return[];const t=[];let r=e[0].type,n=[e[0].data];for(let o=1;o{e.writable.write({type:t,data:r}).catch((()=>{}))};return e.stdout?.on("data",(e=>{const n=t.note(e);void 0!==n&&n.length>0&&r("stdout",n)})),e.stderr?.on("data",(e=>{r("stderr",e)})),{get stdoutBytes(){return t.bytes},get stdoutPrefix(){return t.stdoutPrefix},async waitForOutput(){},async releaseHeldStdout(){const e=t.takeHeld();void 0!==e&&e.length>0&&r("stdout",e)},dropHeldStdout(){t.takeHeld()},async flush(){await this.releaseHeldStdout()}}}const r=new Nr(e.writable,e.outputLimiterOptions);let n;const o=Promise.all([jr(e.stdout,r,t),Ur(e.stderr,"stderr",r)]).then((()=>{})).catch((e=>{n=e}));return{get stdoutBytes(){return t.bytes},get stdoutPrefix(){return t.stdoutPrefix},async waitForOutput(){if(await o,void 0!==n)throw(e=n)instanceof Error?e:new Error(String(e));var e},async releaseHeldStdout(){const e=t.takeHeld();void 0!==e&&e.length>0&&await r.push("stdout",e)},dropHeldStdout(){t.takeHeld()},async flush(){await this.releaseHeldStdout(),await r.flush()}}}async function jr(e,t,r){if(e)for await(const n of e){const e=r.note(n);void 0!==e&&e.length>0&&await t.push("stdout",e)}}async function Ur(e,t,r,n){if(e)for await(const o of e)n?.(o),await r.push(t,o)}var Br;!function(e){e.Zsh="zsh",e.ZshLight="zsh-light",e.Bash="bash",e.PowerShell="powershell",e.Naive="naive"}(Br||(Br={}));const Wr={TERM:"dumb",NO_COLOR:"1",FORCE_COLOR:"0",_ZO_DOCTOR:"0"};function Hr(e){return"win32"===e.platform?"windows_tree":e.detached?"process_group":"single_process"}function qr(e,t,r,o={spawn:n.spawn,killPid:process.kill.bind(process)}){const s=e.pid;if(void 0===s)return;const i=()=>{try{e.kill(r)}catch{}};switch(t){case"process_group":try{o.killPid(-s,r)}catch{i()}return;case"windows_tree":try{o.spawn("taskkill",["/pid",String(s),"/t","/f"],{stdio:"ignore",windowsHide:!0}).on("error",i)}catch{i()}return;case"single_process":return void i();default:throw new Error(`Unknown process tree kill mode: ${String(t)}`)}}function zr(e,t=[],r={},n,o){const s=xr(e,t,{...r,env:I(r.env??process.env)},n);return o?Vr(s,{detached:!0===r.detached},o):Gr(s,!0===r.detached),s}function Gr(e,t){"single_process"!==Hr({platform:process.platform,detached:t})&&e.pid}function Vr(e,t,r){const n=Hr({platform:process.platform,detached:t.detached});Gr(e,t.detached);const o=()=>{if(!e.pid)return;qr(e,n,"SIGTERM");const t=setTimeout((()=>{!e.killed&&e.pid&&qr(e,n,"SIGKILL")}),1e3);"process_group"!==n&&e.once("exit",(()=>{clearTimeout(t)}))};r.aborted?o():(r.addEventListener("abort",o,{once:!0}),e.once("exit",(()=>{r.removeEventListener("abort",o)})))}function Kr(e,t,r){if(e){try{process.kill(-e,t)}catch{return}"SIGTERM"===t&&void 0!==r&&r>0&&setTimeout((()=>{try{process.kill(-e,"SIGKILL")}catch{}}),r)}}const Jr=new Set(["SIGTERM","SIGINT","SIGHUP","SIGQUIT","SIGKILL"]);function Zr(e,t,r){null!==t&&Jr.has(t)&&!r&&"win32"!==process.platform&&Kr(e,t)}function Xr(e,{shellName:t,closeGraceMs:r,timeoutMs:n}){const o=r??5e3,s=n??6e4;return new Promise((r=>{const n=[];let i;const a=e=>{n.push(e)},c=()=>{clearTimeout(d),o<=0||(i=setTimeout((()=>{console.warn(`[shell-exec] ${t} state init exited but its stdio did not close within ${o}ms; a startup file left a background process holding the output pipe. Proceeding with the dump received so far.`),u("exit_without_close")}),o))},l=()=>{u("closed")},u=t=>{clearTimeout(d),clearTimeout(i),e.off("exit",c),e.off("close",l),e.stdout?.off("data",a),e.stdout?.resume(),r({outcome:t,stdout:Buffer.concat(n).toString("utf8")})},d=s>0?setTimeout((()=>{console.warn(`[shell-exec] ${t} state init did not exit within ${s}ms; a startup file is blocking. Killing it and falling back to an empty state.`),qr(e,Hr({platform:process.platform,detached:!0}),"SIGKILL"),u("timed_out")}),s):void 0;e.stdout?.on("data",a),Qr(e.stdout),e.on("exit",c),e.on("close",l)}))}function Qr(e){e?.on("error",(()=>{}))}function Yr(e){e.removeAllListeners(),e.on("error",(()=>{})),e.stdout?.removeAllListeners("close"),e.stderr?.removeAllListeners("close");for(const t of e.stdio.slice(3))t?.destroy()}const en="IFS= builtin read -r -d '' __cursor_command <&5 2>/dev/null || { builtin printf '%s\\n' 'The command did not run: a shell startup file ($BASH_ENV or .zshenv) closed or replaced file descriptor 5, which carries the command. Run it again; this shell now passes commands as arguments.' >&2; builtin exit 126; }; exec 5<&-; builtin set -- \"$__cursor_command\"; builtin unset __cursor_command; ";function tn(e,t){return 126===e&&""===t}function rn(){return"win32"!==process.platform}function nn(e,t){const r=e.stdio.at(5);r instanceof Ir.default.Writable&&(Qr(r),r.end(`${t}\0`))}function on(e,t){e&&(Qr(e),e.write(t),e.end())}function sn(e,t){if(!e)return;Qr(e);const r=new Dr.StringDecoder("utf8");e.on("data",(e=>{const n=r.write(e);""!==n&&t(n)})),e.on("end",(()=>{const e=r.end();""!==e&&t(e)}))}function an(e){const t=e.indexOf("\n");return{cwd:Buffer.from(e.substring(0,t),"utf16le").toString("utf16le"),rest:e.substring(t)}}function cn(e,t){const r=t instanceof Error&&"code"in t&&"string"==typeof t.code?t.code:"unknown";console.warn(e,r)}function ln(e,t){const r=`${t}\n`,n=e.indexOf(r);return n>=0?e.slice(n+r.length):e}function un(e){return!1===e?.isLoginShellEnabled?"-ic":"-ilc"}function dn(e,t,r){const n=`${t}\n`;if(!e.startsWith(n))return;const o=e.indexOf(`\n${r}\n`,n.length-1);return o<0?void 0:e.slice(n.length,o+1)}const hn="__CURSOR_BASH_STATE_START__",pn="__CURSOR_BASH_STATE_END__",fn="\n Emit $PWD.Path\n #Log-Timing \"working_dir\"\n\n function ShouldPersistEnvVar {\n param([string]$Name)\n if ($Name -eq 'CURSOR_CONVERSATION_ID') {\n return $false\n }\n if ($Name -eq 'CURSOR_REQUEST_ID') {\n return $false\n }\n if ($Name -like 'CURSOR_AGENT_STORE*') {\n return $false\n }\n if ($Name -like '*CURSOR_SANDBOX*') {\n return $false\n }\n if ($Name -eq 'ELECTRON_RUN_AS_NODE') {\n return $false\n }\n return $true\n }\n\n $envVars = Get-ChildItem Env: | Sort-Object Name\n foreach ($var in $envVars) {\n if (-not (ShouldPersistEnvVar -Name $var.Name)) {\n continue\n }\n $encoded = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes([string]$var.Value))\n Emit ('Set-Item -LiteralPath ''Env:{0}'' -Value ([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String(''{1}'')))' -f $var.Name, $encoded)\n }\n #Log-Timing \"environment\"\n\n $aliases = Get-Alias | Sort-Object Name\n foreach ($alias in $aliases) {\n $definition = $alias.Definition\n\n if ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::ReadOnly) {\n }\n elseif ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::Constant) {\n }\n elseif ($alias.Options -band [System.Management.Automation.ScopedItemOptions]::AllScope) {\n }\n else {\n Emit ('Set-Alias -Name \"{0}\" -Value \"{1}\"' -f $alias.Name, $definition)\n }\n }\n\n #Log-Timing \"finalize\"\n",mn=`\nfunction Dump-PowerShellState {\n param(\n [Parameter(Mandatory = $true)]\n [string]$OutputFile\n )\n\n function Emit {\n param([string]$Content)\n Add-Content -Path $OutputFile -Value $Content -Encoding UTF8\n }\n\n if (Test-Path $OutputFile) {\n Remove-Item $OutputFile -Force\n }\n New-Item -Path $OutputFile -ItemType File -Force | Out-Null\n #Log-Timing "file_init"\n${fn}}\n`,gn=`\nfunction Dump-PowerShellState {\n param(\n [Parameter(Mandatory = $true)]\n [string]$OutputFile,\n [string]$Trailer\n )\n\n $__cursorDumpText = New-Object System.Text.StringBuilder\n $__cursorDumpNewLine = [Environment]::NewLine\n function Emit {\n param([string]$Content)\n [void]$__cursorDumpText.Append($Content).Append($__cursorDumpNewLine)\n }\n${fn}\n if ($Trailer) {\n Emit $Trailer\n }\n [System.IO.File]::WriteAllText($OutputFile, $__cursorDumpText.ToString(), (New-Object System.Text.UTF8Encoding ($PSVersionTable.PSVersion.Major -lt 6)))\n}\n`,wn="# cursor-shell-timings ",yn="[long](([DateTime]::UtcNow.Ticks - 621355968000000000) / 10000)",vn="\ntry { [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\ntry { [Console]::InputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\ntry { $global:OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch { }\n",bn=e=>e.map((e=>`'${e}'`)).join(", "),Sn=` # The body of the proxy for Set-Content and Export-Csv. Its param block comes from the\n # cmdlet itself. Every step of its own is guarded, so a failure in the proxy leaves the\n # file as the cmdlet writes it.\n $__cursorProxyBody = @'\nbegin {\n # The file system paths the call writes, each with its own 'bom' or 'nobom', and what each\n # held before the call; the call gets -Encoding only when every path has a decision.\n $__cursorFiles = $null\n $__cursorDecisions = @{}\n $__cursorBefore = @{}\n $__cursorDecided = $false\n # The command line asked for UTF8 by name, for files whose readers take it without a BOM.\n $__cursorAsked = $false\n $__cursorStrip = $false\n $__cursorStopped = $false\n $__cursorScopeBound = $null\n $__cursorInvoked = "$($MyInvocation.InvocationName)"\n # The first 8 KiB of the file and its length; $null for a file that does not exist.\n $__cursorHeadOf = {\n param([string]$__cursorFile)\n if (-not [System.IO.File]::Exists($__cursorFile)) { return $null }\n $__cursorHead = New-Object byte[] 8192\n $__cursorCount = 0\n $__cursorStream = [System.IO.File]::Open($__cursorFile, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite -bor [System.IO.FileShare]::Delete)\n try {\n $__cursorLength = $__cursorStream.Length\n while ($__cursorCount -lt $__cursorHead.Length) {\n $__cursorRead = $__cursorStream.Read($__cursorHead, $__cursorCount, $__cursorHead.Length - $__cursorCount)\n if ($__cursorRead -le 0) { break }\n $__cursorCount += $__cursorRead\n }\n } finally { $__cursorStream.Dispose() }\n return @{ Length = $__cursorLength; Head = $__cursorHead; Count = $__cursorCount }\n }\n # 'bom' or 'nobom' for a file the proxy writes in UTF-8, $null for one it leaves to the\n # cmdlet: the file's own bytes decide when it has content, its extension otherwise.\n $__cursorEncodingOf = {\n param([string]$__cursorFile, $__cursorWas)\n $__cursorExtension = [System.IO.Path]::GetExtension($__cursorFile).ToLowerInvariant()\n if ($__cursorExtension -in @(${bn([".bat",".cmd",".reg",".ini",".inf",".vbs",".vbe",".wsf"])})) { return $null }\n if ([System.IO.Directory]::Exists($__cursorFile)) { return $null }\n if ($null -ne $__cursorWas -and $__cursorWas.Count -gt 0) {\n $__cursorHead = $__cursorWas.Head\n $__cursorEnd = $__cursorWas.Count\n if ($__cursorEnd -ge 3 -and $__cursorHead[0] -eq 0xEF -and $__cursorHead[1] -eq 0xBB -and $__cursorHead[2] -eq 0xBF) { return 'bom' }\n if ($__cursorEnd -ge 2 -and (($__cursorHead[0] -eq 0xFF -and $__cursorHead[1] -eq 0xFE) -or ($__cursorHead[0] -eq 0xFE -and $__cursorHead[1] -eq 0xFF))) { return $null }\n if ($__cursorEnd -eq $__cursorHead.Length) {\n # A full header may end inside a character; that character is left out.\n $__cursorAt = $__cursorEnd - 1\n while ($__cursorAt -gt $__cursorEnd - 4 -and ($__cursorHead[$__cursorAt] -band 0xC0) -eq 0x80) { $__cursorAt-- }\n if ($__cursorHead[$__cursorAt] -ge 0xC0) {\n $__cursorNeed = if ($__cursorHead[$__cursorAt] -ge 0xF0) { 4 } elseif ($__cursorHead[$__cursorAt] -ge 0xE0) { 3 } else { 2 }\n if ($__cursorEnd - $__cursorAt -lt $__cursorNeed) { $__cursorEnd = $__cursorAt }\n }\n }\n # A strict decode throws on bytes that are not UTF-8; a character beyond ASCII takes\n # more bytes than code units, so all-ASCII content is the one that decodes to as many.\n try { $__cursorText = [System.Text.UTF8Encoding]::new($false, $true).GetString($__cursorHead, 0, $__cursorEnd) } catch { return $null }\n if ($__cursorText.Length -lt $__cursorEnd) { return 'nobom' }\n }\n if ($__cursorExtension -in @(${bn([".ps1",".psm1",".psd1"])})) { return 'bom' }\n if ($__cursorExtension -in @(${bn([".py",".pyw",".pyi",".js",".mjs",".cjs",".jsx",".ts",".tsx",".mts",".cts",".go",".rs",".kt",".kts",".scala",".swift",".dart",".rb",".cs",".fs",".fsx",".vb",".razor",".cshtml",".sh",".bash",".zsh",".html",".htm",".css",".scss",".sass",".less",".vue",".svelte",".json",".jsonc",".json5",".yaml",".yml",".toml",".xml",".xsd",".xsl",".xslt",".svg",".csproj",".props",".targets",".graphql",".gql",".proto",".tf",".hcl",".md",".markdown",".mdx",".rst",".adoc",".gitignore",".gitattributes",".gitmodules",".editorconfig",".cursorignore",".cursorindexingignore",".mdc"])})) { return 'nobom' }\n return $null\n }\n # Whether the -Encoding the call bound is the UTF-8 with a BOM that Windows PowerShell names\n # UTF8. PowerShell 7 binds the encoding object of that name, and reaches this only when a\n # test fakes the version.\n $__cursorIsUtf8Bom = {\n param($__cursorEncoding)\n if ($__cursorEncoding -is [System.Text.Encoding]) { return ($__cursorEncoding -is [System.Text.UTF8Encoding] -and $__cursorEncoding.GetPreamble().Length -gt 0) }\n return ("$__cursorEncoding" -eq 'UTF8')\n }\n # Whether a default under $PSDefaultParameterValues can reach this call's -Encoding: under\n # the cmdlet's name, an alias it had when the proxy was built, or the name the call used. A\n # value such a default put in $PSBoundParameters is not one the command line asked for.\n $__cursorHasEncodingDefault = {\n param([string]$__cursorInvoked)\n foreach ($__cursorKey in @($PSDefaultParameterValues.Keys)) {\n $__cursorKeyParts = "$__cursorKey" -split ':', 2\n if ($__cursorKeyParts.Count -ne 2 -or 'Encoding' -notlike $__cursorKeyParts[1].Trim()) { continue }\n foreach ($__cursorName in @(__CURSORNAMES__, $__cursorInvoked)) {\n if ($__cursorName -like $__cursorKeyParts[0].Trim()) { return $true }\n }\n }\n return $false\n }\n # Whether a UTF8 asked for by name is UTF-8 without a BOM for this file: one whose reader\n # rejects a BOM, and that is new, empty or starts with no BOM of any encoding.\n $__cursorTakesNoBom = {\n param([string]$__cursorFile, $__cursorWas)\n if ([System.IO.Directory]::Exists($__cursorFile)) { return $false }\n if ([System.IO.Path]::GetExtension($__cursorFile).ToLowerInvariant() -notin @(${bn([".json",".py",".js",".ts",".sh",".yaml",".toml",".mdc"])}) -and\n [System.IO.Path]::GetFileName($__cursorFile).ToLowerInvariant() -notin @(${bn([".gitignore",".editorconfig"])})) { return $false }\n if ($null -eq $__cursorWas -or $__cursorWas.Count -lt 2) { return $true }\n $__cursorHead = $__cursorWas.Head\n if ($__cursorWas.Count -ge 3 -and $__cursorHead[0] -eq 0xEF -and $__cursorHead[1] -eq 0xBB -and $__cursorHead[2] -eq 0xBF) { return $false }\n if (($__cursorHead[0] -eq 0xFF -and $__cursorHead[1] -eq 0xFE) -or ($__cursorHead[0] -eq 0xFE -and $__cursorHead[1] -eq 0xFF)) { return $false }\n if ($__cursorWas.Count -ge 4 -and $__cursorHead[0] -eq 0 -and $__cursorHead[1] -eq 0 -and $__cursorHead[2] -eq 0xFE -and $__cursorHead[3] -eq 0xFF) { return $false }\n return $true\n }\n # Takes a UTF-8 BOM off the front of the file in place, unless it is to stay and the\n # content has a character beyond ASCII. A file the cmdlet left as it was is not touched.\n $__cursorStripBom = {\n param([string]$__cursorFile, [bool]$__cursorKeepUnlessAscii, $__cursorWas)\n if (-not [System.IO.File]::Exists($__cursorFile)) { return }\n $__cursorStream = $null\n # The cmdlet may still hold the file for a moment after it returns.\n for ($__cursorAttempt = 0; $__cursorAttempt -lt 5 -and $null -eq $__cursorStream; $__cursorAttempt++) {\n try { $__cursorStream = [System.IO.File]::Open($__cursorFile, [System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None) }\n catch [System.IO.FileNotFoundException] { return }\n catch [System.IO.DirectoryNotFoundException] { return }\n catch [System.IO.IOException] { Start-Sleep -Milliseconds 20 }\n catch { return }\n }\n if ($null -eq $__cursorStream) { return }\n try {\n $__cursorBuffer = New-Object byte[] 65536\n if ($null -ne $__cursorWas -and $__cursorWas.Length -eq $__cursorStream.Length) {\n $__cursorCount = 0\n while ($__cursorCount -lt $__cursorWas.Count) {\n $__cursorRead = $__cursorStream.Read($__cursorBuffer, $__cursorCount, $__cursorWas.Count - $__cursorCount)\n if ($__cursorRead -le 0) { break }\n $__cursorCount += $__cursorRead\n }\n if ($__cursorCount -eq $__cursorWas.Count -and [System.Convert]::ToBase64String($__cursorBuffer, 0, $__cursorCount) -eq [System.Convert]::ToBase64String($__cursorWas.Head, 0, $__cursorCount)) { return }\n $__cursorStream.Position = 0\n }\n if ($__cursorStream.Read($__cursorBuffer, 0, 3) -ne 3 -or $__cursorBuffer[0] -ne 0xEF -or $__cursorBuffer[1] -ne 0xBB -or $__cursorBuffer[2] -ne 0xBF) { return }\n if ($__cursorKeepUnlessAscii) {\n while (($__cursorRead = $__cursorStream.Read($__cursorBuffer, 0, $__cursorBuffer.Length)) -gt 0) {\n if ([regex]::IsMatch([System.Text.Encoding]::UTF8.GetString($__cursorBuffer, 0, $__cursorRead), '[^\\x00-\\x7F]')) { return }\n }\n }\n $__cursorReadAt = 3L\n $__cursorWriteAt = 0L\n while ($__cursorReadAt -lt $__cursorStream.Length) {\n $__cursorStream.Position = $__cursorReadAt\n $__cursorRead = $__cursorStream.Read($__cursorBuffer, 0, $__cursorBuffer.Length)\n if ($__cursorRead -le 0) { break }\n $__cursorStream.Position = $__cursorWriteAt\n $__cursorStream.Write($__cursorBuffer, 0, $__cursorRead)\n $__cursorReadAt += $__cursorRead\n $__cursorWriteAt += $__cursorRead\n }\n $__cursorStream.SetLength($__cursorWriteAt)\n } catch { } finally { $__cursorStream.Dispose() }\n }\n try {\n $__cursorBound = $null\n if ($PSBoundParameters.ContainsKey('Path')) { $__cursorBound = @{ Path = $PSBoundParameters['Path'] } }\n elseif ($PSBoundParameters.ContainsKey('LiteralPath')) { $__cursorBound = @{ LiteralPath = $PSBoundParameters['LiteralPath'] } }\n if ($null -ne $__cursorBound) {\n # The file system paths that -Path or -LiteralPath names; none when one is on another\n # provider or a wildcard matches nothing.\n $__cursorLiteral = $__cursorBound.ContainsKey('LiteralPath')\n $__cursorFiles = New-Object System.Collections.Generic.List[string]\n foreach ($__cursorPath in @(@($__cursorBound.Values)[0])) {\n $__cursorProvider = $null\n $__cursorDrive = $null\n if ($__cursorLiteral -or -not [System.Management.Automation.WildcardPattern]::ContainsWildcardCharacters("$__cursorPath")) {\n $__cursorResolved = @($ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath("$__cursorPath", [ref]$__cursorProvider, [ref]$__cursorDrive))\n } else {\n $__cursorResolved = @($ExecutionContext.SessionState.Path.GetResolvedProviderPathFromPSPath("$__cursorPath", [ref]$__cursorProvider))\n }\n if ($null -ne $__cursorProvider -and $__cursorProvider.Name -in @('Variable', 'Function', 'Alias')) { $__cursorScopeBound = $__cursorProvider.Name }\n if ($null -eq $__cursorProvider -or $__cursorProvider.Name -ne 'FileSystem' -or $__cursorResolved.Count -eq 0) { $__cursorFiles = $null; break }\n $__cursorFiles.AddRange([string[]]$__cursorResolved)\n }\n }\n # -WhatIf sets $WhatIfPreference and -Confirm sets $ConfirmPreference in this scope.\n if ($null -ne $__cursorFiles -and $__cursorFiles.Count -gt 0 -and -not $PSBoundParameters.ContainsKey('Encoding') -and\n -not $WhatIfPreference -and $ConfirmPreference -notin @('Low', 'Medium') -and -not $PSBoundParameters.ContainsKey('Stream') -and\n -not $PSBoundParameters.ContainsKey('Filter') -and -not $PSBoundParameters.ContainsKey('Include') -and\n -not $PSBoundParameters.ContainsKey('Exclude')) {\n $__cursorAppend = ($PSBoundParameters.ContainsKey('Append') -and $PSBoundParameters['Append']) -or ($PSBoundParameters.ContainsKey('NoClobber') -and $PSBoundParameters['NoClobber'])\n $__cursorDecided = $true\n $__cursorStrip = $true\n foreach ($__cursorFile in $__cursorFiles) {\n $__cursorBefore[$__cursorFile] = & $__cursorHeadOf $__cursorFile\n $__cursorDecisions[$__cursorFile] = & $__cursorEncodingOf $__cursorFile $__cursorBefore[$__cursorFile]\n if ($null -eq $__cursorDecisions[$__cursorFile]) { $__cursorDecided = $false; break }\n # An append onto a file with content writes no BOM, so there is none to take off.\n if ($__cursorAppend -and $null -ne $__cursorBefore[$__cursorFile] -and $__cursorBefore[$__cursorFile].Length -gt 0) { $__cursorStrip = $false }\n }\n }\n elseif ($null -ne $__cursorFiles -and $__cursorFiles.Count -gt 0 -and $PSBoundParameters.ContainsKey('Encoding') -and\n (& $__cursorIsUtf8Bom $PSBoundParameters['Encoding']) -and -not (& $__cursorHasEncodingDefault $__cursorInvoked) -and\n -not $WhatIfPreference -and $ConfirmPreference -notin @('Low', 'Medium') -and -not $PSBoundParameters.ContainsKey('Stream') -and\n -not $PSBoundParameters.ContainsKey('Filter') -and -not $PSBoundParameters.ContainsKey('Include') -and\n -not $PSBoundParameters.ContainsKey('Exclude')) {\n # The UTF8 the command line asked for is UTF-8 with a BOM on this shell and without\n # one on PowerShell 7. For a file whose reader rejects a BOM, and that has none, it\n # means what it means there: the cmdlet writes its BOM, and the proxy takes it off.\n $__cursorAsked = $true\n foreach ($__cursorFile in $__cursorFiles) {\n $__cursorBefore[$__cursorFile] = & $__cursorHeadOf $__cursorFile\n if (-not (& $__cursorTakesNoBom $__cursorFile $__cursorBefore[$__cursorFile])) { $__cursorAsked = $false; break }\n $__cursorDecisions[$__cursorFile] = 'nobom'\n }\n $__cursorStrip = $__cursorAsked\n }\n } catch { $__cursorDecided = $false; $__cursorAsked = $false }\n if ($__cursorDecided) { $PSBoundParameters['Encoding'] = '__CURSORUTF8__' }\n if ($null -ne $__cursorScopeBound) {\n Write-Warning "__CURSORNAME__ runs through a function in this shell, so an item it writes to the $__cursorScopeBound provider lives in a scope that ends with the call. Use an assignment, a function definition or Set-Alias instead."\n }\n # An error the caller asked to stop on ends the caller too, as it does from the cmdlet: it\n # goes on as it is, as from the proxy PowerShell itself generates, which rethrows everything\n # with 'throw'. Any other terminating error of the cmdlet ends the statement and the caller\n # goes on; ThrowTerminatingError keeps that rule, where 'throw' would end the caller's whole\n # script, and the pipeline it ended is not stepped again. Of the two, only the cmdlet's own\n # terminating error names this function rather than the cmdlet's type in the suffix of its\n # FullyQualifiedErrorId; the record of an error the caller asked to stop on is the cmdlet's.\n try {\n $outBuffer = $null\n if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 }\n $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('__CURSORTARGET__', [System.Management.Automation.CommandTypes]::Cmdlet)\n $scriptCmd = { & $wrappedCmd @PSBoundParameters }\n $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)\n $steppablePipeline.Begin($PSCmdlet)\n } catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n}\nprocess {\n if ($__cursorStopped) { return }\n try { $steppablePipeline.Process($_) }\n catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n}\nend {\n if ($__cursorStopped) { return }\n try { $steppablePipeline.End() }\n catch [System.Management.Automation.ActionPreferenceStopException] { throw }\n catch { $__cursorStopped = $true; $PSCmdlet.ThrowTerminatingError($_) }\n if (-not $__cursorStrip -or -not ($__cursorDecided -or $__cursorAsked)) { return }\n try {\n foreach ($__cursorFile in $__cursorFiles) { & $__cursorStripBom $__cursorFile ($__cursorDecisions[$__cursorFile] -eq 'bom') $__cursorBefore[$__cursorFile] }\n } catch { }\n}\n'@\n foreach ($__cursorWriter in @('Set-Content', 'Export-Csv')) {\n $__cursorWriterNames = @($__cursorWriter) + @(Get-Alias -Definition $__cursorWriter -ErrorAction Ignore | ForEach-Object { $_.Name })\n $__cursorHasWriterDefault = $false\n foreach ($__cursorKey in @($PSDefaultParameterValues.Keys)) {\n $__cursorKeyParts = "$__cursorKey" -split ':', 2\n if ($__cursorKeyParts.Count -ne 2 -or 'Encoding' -notlike $__cursorKeyParts[1].Trim()) { continue }\n foreach ($__cursorName in $__cursorWriterNames) {\n if ($__cursorName -like $__cursorKeyParts[0].Trim()) { $__cursorHasWriterDefault = $true }\n }\n }\n if ($__cursorHasWriterDefault) { continue }\n try {\n # A function of this name that a profile defined stays in charge; the proxy is built on the cmdlet alone.\n $__cursorCmdlet = @(Microsoft.PowerShell.Core\\Get-Command -Name $__cursorWriter -ErrorAction Stop)[0]\n if ($__cursorCmdlet.CommandType -eq 'Cmdlet') {\n $__cursorTarget = "$($__cursorCmdlet.ModuleName)\\$($__cursorCmdlet.Name)"\n $__cursorMetadata = New-Object System.Management.Automation.CommandMetadata $__cursorCmdlet\n $__cursorNamesList = @($__cursorWriterNames | ForEach-Object { "'" + $_.Replace("'", "''") + "'" }) -join ', '\n $__cursorProxyText = @(\n '<#', ".ForwardHelpTargetName $__cursorTarget", '.ForwardHelpCategory Cmdlet', '#>',\n [System.Management.Automation.ProxyCommand]::GetCmdletBindingAttribute($__cursorMetadata),\n 'param(', [System.Management.Automation.ProxyCommand]::GetParamBlock($__cursorMetadata), ')',\n 'dynamicparam {', [System.Management.Automation.ProxyCommand]::GetDynamicParam($__cursorMetadata), '}',\n $__cursorProxyBody.Replace('__CURSORTARGET__', $__cursorTarget).Replace('__CURSORNAMES__', $__cursorNamesList).Replace('__CURSORNAME__', $__cursorCmdlet.Name).Replace('__CURSORUTF8__', $__cursorUtf8)\n ) -join [Environment]::NewLine\n # Global, as a profile would define it, so that a module's code reaches it too.\n Microsoft.PowerShell.Management\\Set-Item -LiteralPath "function:global:$__cursorWriter" -Value ([scriptblock]::Create($__cursorProxyText)) -ErrorAction Stop\n }\n } catch { }\n }`,kn=String.raw` function global:__cursorUtf8FromLatin1 { param([string]$Text) Set-StrictMode -Off @@ -107,7 +107,7 @@ index e027f4cfecdfb2be8aefcd7a2de7f97bd6ecd3b0..dd13515bda95ced477222c6cdac9bb27 export interface GetUsageOptions { /** diff --git a/dist/esm/index.js b/dist/esm/index.js -index 2aba0a2689fb610e1a5311893aa65f93b4752be1..50d3e5e7b3dfc762c558d4a8bd6f81e2615e9e81 100644 +index 2aba0a2689fb610e1a5311893aa65f93b4752be1..62ccc7a4f9674c0573d3102909537fa09d7ca460 100644 --- a/dist/esm/index.js +++ b/dist/esm/index.js @@ -1 +1 @@ diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e53019e0f39bd..36619d824d225 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -364,7 +364,7 @@ pnpmfileChecksum: sha256-G0L7+qfid3Wo9BlLIlMyF/+fqBnAnqHKSe0HlWAtlg8= patchedDependencies: '@alchemy.run/test@2.0.0-beta.85': 29c0539ea71d9cc372f0b16558640599beb9bc609605feb2a493da268d72713e '@clerk/expo-native-components@0.4.4': 7a808b92da8460750b85818552e13be3fb73d111691c7db76965970351e124e4 - '@cursor/sdk@1.4.2': d9747bbf2d8fa7529b74b690087b70b3b2662fcba0d4d3148afc3b956171b54a + '@cursor/sdk@1.4.2': caa7fd9ce847cbae996855b9c6035055f7d0acc542234032aa3585c39818d918 '@effect/platform-node-shared@4.1.5': 06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14 '@effect/vitest@4.1.5': dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5 '@expo/ui@58.0.27': 9f2547678939f4ec78fe45163b6455aad63d3c80353d7e0cc783f6a61a7ccc2f @@ -858,7 +858,7 @@ importers: version: 0.3.321(@anthropic-ai/sdk@0.93.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.32.2(supports-color@8.1.1)(zod@4.6.7))(zod@4.6.7) '@cursor/sdk': specifier: 1.4.2 - version: 1.4.2(patch_hash=d9747bbf2d8fa7529b74b690087b70b3b2662fcba0d4d3148afc3b956171b54a)(zod@4.6.7) + version: 1.4.2(patch_hash=caa7fd9ce847cbae996855b9c6035055f7d0acc542234032aa3585c39818d918)(zod@4.6.7) '@effect/platform-node': specifier: 4.1.5 version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) @@ -1766,7 +1766,7 @@ importers: dependencies: '@cursor/sdk': specifier: 1.4.2 - version: 1.4.2(patch_hash=d9747bbf2d8fa7529b74b690087b70b3b2662fcba0d4d3148afc3b956171b54a)(zod@4.6.7) + version: 1.4.2(patch_hash=caa7fd9ce847cbae996855b9c6035055f7d0acc542234032aa3585c39818d918)(zod@4.6.7) '@t3tools/contracts': specifier: workspace:* version: link:../contracts @@ -14253,7 +14253,7 @@ snapshots: '@cursor/sdk-win32-x64@1.4.2': optional: true - '@cursor/sdk@1.4.2(patch_hash=d9747bbf2d8fa7529b74b690087b70b3b2662fcba0d4d3148afc3b956171b54a)(zod@4.6.7)': + '@cursor/sdk@1.4.2(patch_hash=caa7fd9ce847cbae996855b9c6035055f7d0acc542234032aa3585c39818d918)(zod@4.6.7)': dependencies: '@bufbuild/protobuf': 1.10.0 '@connectrpc/connect': 1.7.0(@bufbuild/protobuf@1.10.0) From 3e3bb765d12464c0b15e914e954b579746ed747d Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 21:28:20 -0800 Subject: [PATCH 279/324] fix(server): Claude turns no longer stay in memory for 10 minutes after each request (#41238) Co-authored-by: Claude Opus 5.5 --- .../Adapters/ClaudeAdapterV2.test.ts | 83 ++++++++++++++++++- .../Adapters/ClaudeAdapterV2.ts | 23 ++++- 2 files changed, 103 insertions(+), 3 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 3d017de3925fa..f753075022d0d 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -62,6 +62,8 @@ import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Clock from "effect/Clock"; +import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as FileSystem from "effect/FileSystem"; @@ -116,7 +118,10 @@ import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEve import { AGENT_FEEDBACK_INSTRUCTIONS } from "@t3tools/provider-core/server/runtimeInstructions"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; import type * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests"; -import { makeProviderFailure } from "@t3tools/provider-core/server/failure"; +import { + makeProviderFailure, + PROVIDER_RETRY_BUDGET_MS, +} from "@t3tools/provider-core/server/failure"; import * as ClaudeAdapterV2 from "./ClaudeAdapterV2.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProviderInstallationGate from "../../provider/ProviderInstallationGate.ts"; @@ -16758,6 +16763,82 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + it.effect("releases the silence watch once Claude answers each request", () => + Effect.gen(function* () { + // Counts pending sleeps of the silence budget: each one holds the whole turn context. + const clock = yield* Clock.Clock; + let pendingWatches = 0; + const countingClock: Clock.Clock = { + currentTimeMillisUnsafe: () => clock.currentTimeMillisUnsafe(), + currentTimeMillis: clock.currentTimeMillis, + currentTimeNanosUnsafe: () => clock.currentTimeNanosUnsafe(), + currentTimeNanos: clock.currentTimeNanos, + monotonicTimeNanosUnsafe: () => clock.monotonicTimeNanosUnsafe(), + monotonicTimeNanos: clock.monotonicTimeNanos, + sleep: (duration) => + Duration.toMillis(duration) === PROVIDER_RETRY_BUDGET_MS + ? Effect.suspend(() => { + pendingWatches += 1; + return clock.sleep(duration); + }).pipe(Effect.ensuring(Effect.sync(() => (pendingWatches -= 1)))) + : clock.sleep(duration), + }; + yield* Effect.gen(function* () { + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-silence-watch-released"), + text: "start again", + attachments: [], + }), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "command_lifecycle", + command_uuid: harness.promptUuid(0), + state: "started", + uuid: "00000000-0000-4000-8000-0000000007a0", + session_id: WAKE_NATIVE_SESSION, + }), + ); + for (let index = 1; index <= 5; index++) { + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "system", + subtype: "status", + status: "requesting", + uuid: `00000000-0000-4000-8000-0000000007a${index}`, + session_id: WAKE_NATIVE_SESSION, + }), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "stream_event", + event: { type: "message_start", message: { id: `msg_watch_${index}` } }, + parent_tool_use_id: null, + session_id: WAKE_NATIVE_SESSION, + uuid: `00000000-0000-4000-8000-0000000007b${index}`, + }), + ); + } + assert.strictEqual(pendingWatches, 0, "answered requests left silence watches running"); + }).pipe(Effect.provideService(Clock.Clock, countingClock)); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + // regression: #17531 a mod that holds a tool behind a focused pane must fail the turn, not hang it it.effect.each([ { case: "fails a turn whose mod requests focus for a pane T3 cannot show", focus: true }, diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 9ff0c8fc16511..ad34325d04191 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -5272,6 +5272,8 @@ interface ActiveClaudeTurnContext { retryBudgetFailure?: OrchestrationV2ProviderFailure; // Set when the prompt starts or a request goes out; cleared by the turn's next frame. unansweredRequestSince?: DateTime.Utc | undefined; + // Interrupted once the silence clears, so the session scope stops holding this context. + unansweredRequestWatch?: Fiber.Fiber | undefined; readonly queryPolicy: ClaudeRuntimeQueryPolicy; readonly input: ProviderAdapter.ProviderAdapterV2TurnInput; readonly autoCompactWindow: string; @@ -6775,6 +6777,12 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ); }); + const clearUnansweredRequestWatch = (context: ActiveClaudeTurnContext) => { + const watch = context.unansweredRequestWatch; + context.unansweredRequestWatch = undefined; + return watch === undefined ? Effect.void : Fiber.interrupt(watch); + }; + const failStalledTurn = Effect.fn("ClaudeAdapterV2.failStalledTurn")(function* ( context: ActiveClaudeTurnContext, failure: OrchestrationV2ProviderFailure, @@ -10088,6 +10096,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( yield* Ref.update(activeTurn, (current) => current?.providerTurnId === input.context.providerTurnId ? null : current, ); + yield* clearUnansweredRequestWatch(input.context); if (input.status === "completed") { settledTurnByNativeThread.set(input.context.nativeThreadId, input.context); } else { @@ -11139,10 +11148,19 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ) { const since = yield* DateTime.now; context.unansweredRequestSince = since; - yield* failUnansweredRequest(context, since).pipe( - Effect.delay(PROVIDER_RETRY_BUDGET_MS), + const previousWatch = context.unansweredRequestWatch; + // Only the wait is interruptible: a fired failure runs on its own fiber. + context.unansweredRequestWatch = yield* Effect.sleep(PROVIDER_RETRY_BUDGET_MS).pipe( + Effect.andThen( + failUnansweredRequest(context, since).pipe(Effect.forkIn(sessionScope)), + ), Effect.forkIn(sessionScope), ); + if (previousWatch !== undefined) yield* Fiber.interrupt(previousWatch); + // A turn that settled meanwhile already cleared its watch, so drop the new one too. + if ((yield* Ref.get(activeTurn)) !== context) { + yield* clearUnansweredRequestWatch(context); + } } else if ( // Background tasks from earlier turns keep streaming while the root request hangs. // Only the root starts depth-1 tasks, so such a start (a forked skill) is this turn's. @@ -11154,6 +11172,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ) ) { context.unansweredRequestSince = undefined; + yield* clearUnansweredRequestWatch(context); } } const focusedPlugin = claudeFocusRequestedPanePlugin(message); From 0356d68835b7b579bb7151abf2f7919d9cce84f3 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 21:30:07 -0800 Subject: [PATCH 280/324] fix(server): Claude plan ids live with the turn, not the session (#41244) Co-authored-by: Claude Opus 5.5 --- .../orchestration-v2/Adapters/ClaudeAdapterV2.ts | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index ad34325d04191..c93b840f44e4d 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -5284,6 +5284,7 @@ interface ActiveClaudeTurnContext { readonly providerTurnOrdinal: number; readonly startedAt: DateTime.Utc; readonly itemOrdinals: Map; + readonly planIds: Map; readonly assistant: { fallbackText: string; // Result-only replies of steered segments that ended before the current one. @@ -6236,9 +6237,6 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const taskListsByNativeThread = yield* Ref.make( new Map(), ); - const planIdsByNativeItem = yield* Ref.make( - new Map(), - ); const providerRetries = yield* Ref.make( new Map(), ); @@ -8673,8 +8671,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }) { const updatedAt = yield* DateTime.now; const projectionNativeItemId = `${input.kind}:${input.nativeItemId}`; - const planKey = `${input.context.input.threadId}:${projectionNativeItemId}`; - const existingPlanId = (yield* Ref.get(planIdsByNativeItem)).get(planKey); + const existingPlanId = input.context.planIds.get(projectionNativeItemId); const planId = existingPlanId ?? (yield* idAllocator.allocate.plan({ @@ -8682,13 +8679,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( runId: input.context.input.runId, driver: CLAUDE_PROVIDER, })); - if (existingPlanId === undefined) { - yield* Ref.update(planIdsByNativeItem, (current) => { - const updated = new Map(current); - updated.set(planKey, planId); - return updated; - }); - } + input.context.planIds.set(projectionNativeItemId, planId); const nodeId = idAllocator.derive.nodeFromProviderItem({ driver: CLAUDE_PROVIDER, nativeItemId: projectionNativeItemId, @@ -13850,6 +13841,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( providerTurnOrdinal, startedAt, itemOrdinals: new Map(), + planIds: new Map(), assistant: { fallbackText: "", earlierFallbackText: "", From c061593db2ba6ba4289d0ff39390444afe73bbe9 Mon Sep 17 00:00:00 2001 From: Victor Date: Sun, 22 Nov 2026 23:53:33 -0600 Subject: [PATCH 281/324] fix(server): pass explicit null payloads to workflows (#41245) Co-authored-by: Julius Marminge --- .../mcp/toolkits/workflow/handlers.test.ts | 59 +++++++++++++++++++ .../src/mcp/toolkits/workflow/handlers.ts | 2 +- 2 files changed, 60 insertions(+), 1 deletion(-) create mode 100644 apps/server/src/mcp/toolkits/workflow/handlers.test.ts diff --git a/apps/server/src/mcp/toolkits/workflow/handlers.test.ts b/apps/server/src/mcp/toolkits/workflow/handlers.test.ts new file mode 100644 index 0000000000000..c036cb8d7e649 --- /dev/null +++ b/apps/server/src/mcp/toolkits/workflow/handlers.test.ts @@ -0,0 +1,59 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import { expect, it } from "@effect/vitest"; +import { EnvironmentId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Stream from "effect/Stream"; + +import * as Workflows from "../../../workflows/Workflows.ts"; +import * as McpInvocationContext from "../../McpInvocationContext.ts"; +import * as McpToolAccess from "../../McpToolAccess.ts"; +import * as McpToolAccessTestkit from "../../McpToolAccess.testkit.ts"; +import * as WorkflowHandlers from "./handlers.ts"; +import { WorkflowToolkit } from "./tools.ts"; + +it.effect("start passes an explicit null payload through and defaults an omitted one to {}", () => + Effect.gen(function* () { + const payloads: Array = []; + const layerDependencies = Layer.mergeAll( + NodeCrypto.layer, + McpToolAccessTestkit.liveThreadsLayer, + Layer.succeed(McpInvocationContext.McpInvocationContext, { + environmentId: EnvironmentId.make("environment:workflow"), + requestNamespace: "client:workflow", + thread: undefined, + client: { sessionId: "session-1", label: "t3 CLI", access: "full-access" }, + capabilities: new Set(["orchestration" as const]), + issuedAt: 0, + }), + Layer.mock(Workflows.Workflows)({ + start: (_workflow, input) => + Effect.sync(() => { + payloads.push(input); + return { runId: "run-1" }; + }), + get: () => Effect.succeed({ run: undefined, steps: [], references: [] } as never), + }), + ); + yield* Effect.gen(function* () { + const toolkit = yield* WorkflowToolkit; + for (const input of [{ input: null }, {}]) { + yield* toolkit + .handle("t3_workflow", { + action: "start", + workflow: "echo", + idempotencyKey: "trial", + ...input, + }) + .pipe(Stream.unwrap, Stream.runCollect); + } + }).pipe( + Effect.provide( + McpToolAccess.HandlersLayer.layer(WorkflowHandlers.layer).pipe( + Layer.provideMerge(layerDependencies), + ), + ), + ); + expect(payloads).toEqual([null, {}]); + }), +); diff --git a/apps/server/src/mcp/toolkits/workflow/handlers.ts b/apps/server/src/mcp/toolkits/workflow/handlers.ts index fe19b06108480..b3ccb35f28151 100644 --- a/apps/server/src/mcp/toolkits/workflow/handlers.ts +++ b/apps/server/src/mcp/toolkits/workflow/handlers.ts @@ -52,7 +52,7 @@ export const layer = McpToolAccess.toLayer(WorkflowToolkit, { const name = yield* required(input.workflow, "workflow"); const idempotencyKey = yield* required(input.idempotencyKey, "idempotencyKey"); const { runId } = yield* workflows - .start(name, input.input ?? {}, { idempotencyKey }) + .start(name, input.input === undefined ? {} : input.input, { idempotencyKey }) .pipe(Effect.mapError(refused)); return yield* workflows.get(runId).pipe(Effect.mapError(refused)); } From 1f13db585d6af6b5be82e50c7510a57a81eb5ccf Mon Sep 17 00:00:00 2001 From: Victor Date: Sun, 22 Nov 2026 23:54:18 -0600 Subject: [PATCH 282/324] fix(server): accept unquoted HTML favicon attributes (#41239) Co-authored-by: Julius Marminge --- .../project/ProjectFaviconResolver.test.ts | 24 +++++++++++++++ .../src/project/ProjectFaviconResolver.ts | 30 +++++++++++++++---- 2 files changed, 49 insertions(+), 5 deletions(-) diff --git a/apps/server/src/project/ProjectFaviconResolver.test.ts b/apps/server/src/project/ProjectFaviconResolver.test.ts index d4cc22efd220a..7c0207eed557d 100644 --- a/apps/server/src/project/ProjectFaviconResolver.test.ts +++ b/apps/server/src/project/ProjectFaviconResolver.test.ts @@ -231,6 +231,30 @@ it.layer(layerTest)("ProjectFaviconResolverLive", (it) => { expect(yield* resolver.resolvePath(tokenListCwd)).toBe( (yield* Path.Path).join(tokenListCwd, "brand.svg"), ); + + const unquotedCwd = yield* makeTempDir; + yield* writeTextFile( + unquotedCwd, + "index.html", + ``, + ); + yield* writeTextFile(unquotedCwd, "app.css", "body {}"); + yield* writeTextFile(unquotedCwd, "brand.svg", "brand"); + expect(yield* resolver.resolvePath(unquotedCwd)).toBe( + (yield* Path.Path).join(unquotedCwd, "brand.svg"), + ); + + const quotedValueCwd = yield* makeTempDir; + yield* writeTextFile( + quotedValueCwd, + "index.html", + ``, + ); + yield* writeTextFile(quotedValueCwd, "app.css", "body {}"); + yield* writeTextFile(quotedValueCwd, "brand.svg", "brand"); + expect(yield* resolver.resolvePath(quotedValueCwd)).toBe( + (yield* Path.Path).join(quotedValueCwd, "brand.svg"), + ); }), ); diff --git a/apps/server/src/project/ProjectFaviconResolver.ts b/apps/server/src/project/ProjectFaviconResolver.ts index 497538634ae73..12c8e2fc63ea2 100644 --- a/apps/server/src/project/ProjectFaviconResolver.ts +++ b/apps/server/src/project/ProjectFaviconResolver.ts @@ -79,8 +79,9 @@ const ICON_SOURCE_FILES = [ const HTML_LINK_RE = /]*>/gi; // `rel` is an unordered, whitespace-separated token list; any `icon` token marks an icon link. const ICON_REL_VALUE = String.raw`(?:"(?:[^"]*[\t\n\f\r ])?icon(?=[\t\n\f\r "])|'(?:[^']*[\t\n\f\r ])?icon(?=[\t\n\f\r ']))`; -const HTML_ICON_REL_RE = new RegExp(String.raw`\brel=${ICON_REL_VALUE}`, "i"); -const HTML_ICON_HREF_RE = /\bhref=["']([^"'?]+)/i; +// HTML attribute syntax: a name, then an optional double-quoted, single-quoted, or unquoted value. +const HTML_ATTRIBUTE_RE = + /([^\t\n\f\r "'<>/=]+)(?:[\t\n\f\r ]*=[\t\n\f\r ]*(?:"([^"]*)"|'([^']*)'|([^\t\n\f\r >]+)))?/g; const ICON_REL_RE = new RegExp(String.raw`\brel\s*:\s*${ICON_REL_VALUE}`, "i"); const ICON_HREF_RE = /\bhref\s*:\s*["']([^"'?]+)/i; @@ -123,9 +124,28 @@ export class ProjectFaviconResolver extends Context.Service< function extractIconHref(source: string): string | null { for (const [tag] of source.matchAll(HTML_LINK_RE)) { - if (!HTML_ICON_REL_RE.test(tag)) continue; - const hrefMatch = tag.match(HTML_ICON_HREF_RE); - if (hrefMatch?.[1]) return hrefMatch[1]; + const attributes = new Map(); + for (const [, name, doubleQuoted, singleQuoted, unquoted] of tag + .slice(" Date: Sun, 22 Nov 2026 21:58:46 -0800 Subject: [PATCH 283/324] docs(user): explain how settling differs from archiving a thread (#41253) --- docs/user/project-settings.md | 3 +++ docs/user/thread-sidebar.md | 13 +++++++++++++ 2 files changed, 16 insertions(+) diff --git a/docs/user/project-settings.md b/docs/user/project-settings.md index 775adeb67d900..fe367c7b45b3a 100644 --- a/docs/user/project-settings.md +++ b/docs/user/project-settings.md @@ -103,6 +103,9 @@ project starts a new thread there on its next run. Deleting a thread also deletes tasks that post into that thread. Tasks that start a new thread on each run survive deletion of their previous threads. +An archived thread refuses messages, so a task that posts into one stays on and fails +each run until you unarchive the thread or pick another destination. To set a task's thread +aside without breaking it, settle the thread; see [Settle or archive](thread-sidebar.md#settle-or-archive). You can edit, pause, resume, run immediately, or delete a task from the list. Webhook tasks only run when their URL is called, so they can't be run diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index 9bbf3194a9d59..6c63f1b9c342d 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -213,6 +213,19 @@ rules to connected environments that support shared settings. Offline environmen and older servers keep their previous values. Changing a rule does not reopen already settled threads. +### Settle or archive + +Settle is for work that is done for now. A settled thread stays in the sidebar's Settled +section and in search, and a message to it, from you, an agent, or a scheduled task, makes it +active again. Archive is for work you want out of the way. An archived thread leaves the +sidebar and search and shows only in **Settings → Archive**, where you can unarchive or +delete it. It refuses new messages, including ones from agents and scheduled tasks, until you +unarchive it. Removing a project deletes its threads either way. + +A scheduled task that posts into one thread keeps running after you archive that thread, and +each run fails. Settle the thread instead, or move or pause the task in **Settings → Scheduled +tasks**. + ## Link a pull request The server finds the PR for each unsettled thread's saved branch, even when your From f1c13177d8a55237897d4de840372c50d3304f03 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Mon, 23 Nov 2026 00:04:41 -0600 Subject: [PATCH 284/324] fix(web): spreadsheet text and fills no longer vanish when their cell scrolls out (#41263) Co-authored-by: Claude Opus 5.5 Co-authored-by: Cursor --- ...achmentFilePreview.office.browser.test.tsx | 2 + .../components/files/office/sheet-frame.ts | 181 +++++++++++------- .../files/office/sheet-resize.browser.test.ts | 63 ++++++ 3 files changed, 181 insertions(+), 65 deletions(-) diff --git a/apps/web/src/components/files/AttachmentFilePreview.office.browser.test.tsx b/apps/web/src/components/files/AttachmentFilePreview.office.browser.test.tsx index 516ea535fd9b6..6826d3369c76a 100644 --- a/apps/web/src/components/files/AttachmentFilePreview.office.browser.test.tsx +++ b/apps/web/src/components/files/AttachmentFilePreview.office.browser.test.tsx @@ -286,6 +286,8 @@ it("preserves merged text across tile clears", async () => { context, { viewport: { x: 0, y: 0, width: 400, height: 80 }, + behind: { x: 0, y: 0 }, + panes: { width: 0, height: 0 }, list: { width: 400, height: 80, commands: [] }, tiles: [ { diff --git a/apps/web/src/components/files/office/sheet-frame.ts b/apps/web/src/components/files/office/sheet-frame.ts index 3b7868bf2d3fe..80723af7256cd 100644 --- a/apps/web/src/components/files/office/sheet-frame.ts +++ b/apps/web/src/components/files/office/sheet-frame.ts @@ -1,10 +1,5 @@ // Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode. -import { - paintDisplayList, - type DisplayList, - type GridMeta, - type WorkbookHandle, -} from "@betteroffice/xlsx"; +import { paintDisplayList, type DisplayList, type WorkbookHandle } from "@betteroffice/xlsx"; import { attempt } from "./sheet-cells"; import { frozenSize } from "./sheet-paint"; import type { SheetViewport } from "./sheet-protocol"; @@ -21,6 +16,12 @@ const maxSplit = 8; */ const seamOverlap = 8; +/** + * How far before a frame its cells are drawn from, in CSS pixels. The engine draws only the cells from a viewport's + * first track on, so the text of a cell before it, overflowing or merged into the frame, would vanish with that cell. + */ +const reach = { x: 1024, y: 512 }; + /** Part of a frame: its display list, where its origin sits in the frame, and where it starts to show. */ type Tile = { readonly list: DisplayList; @@ -32,12 +33,14 @@ type Tile = { /** * A frame of cells: the tiles that draw it, one display list for its grid and links, without draw commands, and the - * viewport it shows. + * viewport it shows. The tiles' cells past the frozen panes start `behind` the viewport's. */ export type Frame = { readonly list: DisplayList; readonly tiles: readonly Tile[]; readonly viewport: SheetViewport; + readonly behind: { readonly x: number; readonly y: number }; + readonly panes: { readonly width: number; readonly height: number }; }; /** @@ -50,22 +53,20 @@ export function drawFrame( frozen: { readonly rows: number; readonly cols: number }, wider?: SheetViewport, ): Frame | undefined { - const around = wider && untruncated(workbook, wider); - - if (wider && around) - return { - list: around, - tiles: [{ list: around, x: 0, y: 0, clipX: 0, clipY: 0 }], - viewport: wider, - }; - - const whole = untruncated(workbook, viewport); - - if (whole) - return { list: whole, tiles: [{ list: whole, x: 0, y: 0, clipX: 0, clipY: 0 }], viewport }; + return ( + (wider && reaching(workbook, wider, frozen, false)) || + reaching(workbook, viewport, frozen, true) + ); +} - // The engine refuses a viewport with too many cells, as a wide pane of narrow columns has. One row and one column of - // the frame give its tracks, and so where its frozen panes end. +/** A frame of `viewport` drawn from up to `reach` before it, split into tiles when `split` and the engine needs it. */ +function reaching( + workbook: WorkbookHandle, + viewport: SheetViewport, + frozen: { readonly rows: number; readonly cols: number }, + split: boolean, +): Frame | undefined { + // One row and one column of the viewport give its tracks, and so where its frozen panes end. const columns = untruncated(workbook, { ...viewport, height: 1 })?.grid; const rows = untruncated(workbook, { ...viewport, width: 1 })?.grid; @@ -79,8 +80,33 @@ export function drawFrame( ...(columns.colIndices ? { colIndices: columns.colIndices } : {}), colOffsets: columns.colOffsets, }; + const panes = frozenSize(grid, frozen); + const behind = { x: Math.min(reach.x, viewport.x), y: Math.min(reach.y, viewport.y) }; + const area = { + x: viewport.x - behind.x, + y: viewport.y - behind.y, + width: viewport.width + behind.x, + height: viewport.height + behind.y, + }; + const whole = untruncated(workbook, area); + // The engine refuses a viewport with too many cells, as a wide pane of narrow columns has. + const tiles = whole + ? [{ list: whole, x: 0, y: 0, clipX: 0, clipY: 0 }] + : split + ? tiled(workbook, area, panes, 2) + : undefined; - return tiled(workbook, viewport, frozenSize(grid, frozen), grid, 2); + if (!tiles) return undefined; + + const hyperlinks = tiles.flatMap((tile) => tile.list.hyperlinks ?? []); + + return { + list: { width: viewport.width, height: viewport.height, commands: [], grid, hyperlinks }, + tiles, + viewport, + behind, + panes, + }; } /** The engine's screen gridlines: one-pixel solid lines in its gridline grey, unlike any border it draws. */ @@ -133,7 +159,7 @@ export function chartFonts( /** * Draws a frame's tiles with the cells' top-left corner at `origin`, in device pixels, each tile from its seam on, so a - * tile covers the panes it repeats. + * tile covers the panes it repeats. The cells past the frozen panes move back by `behind`; the panes stay put. */ export function paintFrame( context: OffscreenCanvasRenderingContext2D, @@ -148,58 +174,92 @@ export function paintFrame( const tiled = frame.tiles.length > 1; const text = tiled ? new OffscreenCanvas(context.canvas.width, context.canvas.height) : undefined; const textContext = text?.getContext("2d"); - - frame.tiles.forEach((tile) => { - const at = { x: origin.x + tile.x * ratio, y: origin.y + tile.y * ratio }; - const list = tiled - ? { ...tile.list, commands: tile.list.commands.filter((command) => command.op !== "text") } - : tile.list; - - if (tile.clipX === 0 && tile.clipY === 0) return paintDisplayList(painter, list, ratio, at); + const columns = bands(frame.panes.width, frame.behind.x); + const rows = bands(frame.panes.height, frame.behind.y); + const parts = frame.tiles.flatMap((tile) => + rows.flatMap((row) => + columns.flatMap((column) => { + const left = Math.max(column.start, tile.clipX - column.shift); + const top = Math.max(row.start, tile.clipY - row.shift); + + if (left >= column.end || top >= row.end) return []; + + const clip = { + left: Math.round(origin.x + left * ratio), + top: Math.round(origin.y + top * ratio), + right: Math.round(origin.x + column.end * ratio), + bottom: Math.round(origin.y + row.end * ratio), + }; + + return [ + { + tile, + at: { + x: origin.x + (tile.x - column.shift) * ratio, + y: origin.y + (tile.y - row.shift) * ratio, + }, + clip: + left === 0 && top === 0 && column.end === Infinity && row.end === Infinity + ? undefined + : clip, + }, + ]; + }), + ), + ); + const clipped = (clip: (typeof parts)[number]["clip"], paint: () => void) => { + if (!clip) return paint(); context.save(); context.setTransform(1, 0, 0, 1, 0, 0); context.beginPath(); context.rect( - Math.round(origin.x + tile.clipX * ratio), - Math.round(origin.y + tile.clipY * ratio), - context.canvas.width, - context.canvas.height, + clip.left, + clip.top, + Math.min(clip.right, context.canvas.width) - clip.left, + Math.min(clip.bottom, context.canvas.height) - clip.top, ); context.clip(); - paintDisplayList(painter, list, ratio, at); + paint(); context.restore(); + }; + + parts.forEach(({ tile, at, clip }) => { + const list = tiled + ? { ...tile.list, commands: tile.list.commands.filter((command) => command.op !== "text") } + : tile.list; + + clipped(clip, () => paintDisplayList(painter, list, ratio, at)); }); // Text clips can span a merged range beyond its tile. Composite it after all tile clears and backgrounds. if (text && textContext) - frame.tiles.forEach((tile) => { + parts.forEach(({ tile, at, clip }) => { textContext.reset(); paintDisplayList( textContext as unknown as CanvasRenderingContext2D, { ...tile.list, - width: frame.viewport.width - tile.x, - height: frame.viewport.height - tile.y, + width: frame.viewport.width + frame.behind.x - tile.x, + height: frame.viewport.height + frame.behind.y - tile.y, commands: tile.list.commands.filter((command) => command.op === "text"), }, ratio, - { x: origin.x + tile.x * ratio, y: origin.y + tile.y * ratio }, - ); - context.save(); - context.setTransform(1, 0, 0, 1, 0, 0); - context.beginPath(); - context.rect( - Math.round(origin.x + tile.clipX * ratio), - Math.round(origin.y + tile.clipY * ratio), - context.canvas.width, - context.canvas.height, + at, ); - context.clip(); - context.drawImage(text, 0, 0); - context.restore(); + clipped(clip, () => context.drawImage(text, 0, 0)); }); } +/** A side's frozen pane, drawn where it is, and the cells past it, drawn `behind` further on. */ +function bands(panes: number, behind: number) { + return panes > 0 && behind > 0 + ? [ + { start: 0, end: panes, shift: 0 }, + { start: panes, end: Infinity, shift: behind }, + ] + : [{ start: 0, end: Infinity, shift: behind }]; +} + /** * A frame split into `split` tiles a side, each under the engine's cap. A tile past the first along an axis asks for * the frozen panes too, as every viewport has them, so the cells past them start just before its seam. @@ -208,9 +268,8 @@ function tiled( workbook: WorkbookHandle, viewport: SheetViewport, panes: { readonly width: number; readonly height: number }, - grid: GridMeta, split: number, -): Frame | undefined { +): Tile[] | undefined { const columns = segments(viewport.width, panes.width, split); const rows = segments(viewport.height, panes.height, split); const tiles: Tile[] = []; @@ -236,19 +295,11 @@ function tiled( }), ); - if (complete) { - const hyperlinks = tiles.flatMap((tile) => tile.list.hyperlinks ?? []); - - return { - list: { width: viewport.width, height: viewport.height, commands: [], grid, hyperlinks }, - tiles, - viewport, - }; - } + if (complete) return tiles; if (split >= maxSplit) return undefined; - return tiled(workbook, viewport, panes, grid, split + 1); + return tiled(workbook, viewport, panes, split + 1); } /** A viewport's display list, or undefined where the engine refuses it or cuts it short at its cell limit. */ diff --git a/apps/web/src/components/files/office/sheet-resize.browser.test.ts b/apps/web/src/components/files/office/sheet-resize.browser.test.ts index 6029e888e1c20..fc2c6845d7530 100644 --- a/apps/web/src/components/files/office/sheet-resize.browser.test.ts +++ b/apps/web/src/components/files/office/sheet-resize.browser.test.ts @@ -145,6 +145,69 @@ it.each([false, true])( }, ); +it.each([false, true])( + "draws text from cells scrolled out before the frame, frozen: %s", + async (frozen) => { + const archive = new JSZip(); + archive.file( + "xl/workbook.xml", + '', + ); + archive.file( + "xl/_rels/workbook.xml.rels", + '', + ); + archive.file( + "xl/styles.xml", + '', + ); + archive.file( + "xl/worksheets/sheet1.xml", + `${frozen ? '' : ""}${"M".repeat(60)}MMMM`, + ); + const bytes = await archive.generateAsync({ type: "arraybuffer" }); + const client = createWorkerClient( + new Worker(new URL("./spreadsheet.worker.ts", import.meta.url), { type: "module" }), + ); + const inked = async ( + at: { x: number; y: number }, + area: { x: number; y: number; width: number; height: number }, + ) => { + const frame = await client.call("frame", { + sheet: 0, + ...at, + width: 400, + height: 300, + ratio: 1, + offset: { x: 0, y: 0 }, + wider: undefined, + }); + const canvas = new OffscreenCanvas(frame!.bitmap.width, frame!.bitmap.height); + const context = canvas.getContext("2d")!; + context.drawImage(frame!.bitmap, 0, 0); + frame!.bitmap.close(); + const pixels = context.getImageData(area.x, area.y, area.width, area.height).data; + return pixels.some( + (value, index) => index % 4 === 0 && value < 128 && pixels[index + 3]! > 0, + ); + }; + try { + await client.call("open", { + bytes, + view: { hiddenGridlines: [], themeFonts: { major: "Calibri Light", minor: "Calibri" } }, + }); + // B2's text overflows to the right well past B, and the merge centres C4's text far below row 4. + const panes = frozen ? { x: 64, y: 20 } : { x: 0, y: 0 }; + expect( + await inked({ x: 160, y: 0 }, { x: panes.x + 40, y: 20, width: 200, height: 20 }), + ).toBe(true); + expect(await inked({ x: 0, y: 200 }, { x: 128, y: 200, width: 64, height: 80 })).toBe(true); + } finally { + client.close(); + } + }, +); + it("requests current dimensions after resizing and scrolling away and back before a frame arrives", async () => { const archive = new JSZip(); archive.file( From c5095e7708922e4c036846be13b339e377c68dda Mon Sep 17 00:00:00 2001 From: maria Date: Mon, 23 Nov 2026 03:07:22 -0300 Subject: [PATCH 285/324] fix(provider): leave MacPorts-owned agent updates to MacPorts (#25208) Co-authored-by: Yukun Shan <92423096+nateEc@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../src/server/maintenanceResolver.test.ts | 55 +++++++++++++++++++ .../src/server/maintenanceResolver.ts | 41 +++++++++----- 2 files changed, 82 insertions(+), 14 deletions(-) diff --git a/packages/provider-core/src/server/maintenanceResolver.test.ts b/packages/provider-core/src/server/maintenanceResolver.test.ts index dc5be98f3c52d..f392f4b546963 100644 --- a/packages/provider-core/src/server/maintenanceResolver.test.ts +++ b/packages/provider-core/src/server/maintenanceResolver.test.ts @@ -830,6 +830,61 @@ it.layer( isCommandPath: isNativeTestCommandPath("/.local/bin/native-package-tool"), }, }; + for (const fixture of [ + { name: "a launcher outside the prefix's bin", npm: false, alias: true, owner: "claude-code" }, + { name: "an unreadable registry", npm: true, alias: false, owner: null }, + { name: "files MacPorts does not own", npm: true, alias: false, owner: "" }, + ]) { + it.effect.skipIf(windowsHost)(`checks MacPorts ownership for ${fixture.name}`, () => + Effect.gen(function* () { + const prefix = yield* makeTempDir("t3-macports-owner"); + const port = NodePath.join(prefix, "bin", "port"); + writeExecutable(port); + const real = fixture.npm + ? NodePath.join(prefix, "lib", "node_modules", "@anthropic-ai", "claude-code", "cli.js") + : NodePath.join(prefix, "share", "claude-code", "claude"); + const resolved = fixture.alias + ? NodePath.join(prefix, ".local", "bin", "claude") + : NodePath.join(prefix, "bin", "claude"); + writeExecutable(real); + writeExecutable(resolved); + const capabilities = yield* resolvePackageManagedProviderMaintenance(claudeUpdate, { + binaryPath: resolved, + resolvedCommandPath: resolved, + realCommandPath: real, + env: { PATH: "" }, + platform: "darwin", + }).pipe( + Effect.provideService(HostProcess.Platform, "darwin"), + Effect.provideService( + ChildProcessSpawner.ChildProcessSpawner, + stdoutSpawner( + (command, args) => { + expect(command).toBe(port); + expect(args).toEqual(["provides", resolved, real]); + return [resolved, real] + .map((file) => + fixture.owner + ? `${file} is provided by: ${fixture.owner}\n` + : `${file} is not provided by a MacPorts port.\n`, + ) + .join(""); + }, + () => (fixture.owner === null ? 1 : 0), + ), + ), + ); + if (fixture.owner === "") { + expect(capabilities.update?.lockKey).toBe(`npm-global:${normalizeCommandPath(prefix)}`); + } else { + expect(capabilities.update).toBeNull(); + expect(capabilities.manualCommand).toBe( + fixture.owner ? `sudo port upgrade ${fixture.owner}` : undefined, + ); + } + }), + ); + } const resolveInstall = (input: { readonly definition: PackageManagedProviderMaintenanceDefinition; readonly resolved: string; diff --git a/packages/provider-core/src/server/maintenanceResolver.ts b/packages/provider-core/src/server/maintenanceResolver.ts index 0db49cd3abaee..583bb1e02111c 100644 --- a/packages/provider-core/src/server/maintenanceResolver.ts +++ b/packages/provider-core/src/server/maintenanceResolver.ts @@ -1182,9 +1182,10 @@ const isMiseWrapperScript = Effect.fn("isMiseWrapperScript")(function* ( }); /** - * The port that installed the executable, "" when MacPorts owns it under an unusable name, - * or null when it does not. MacPorts prefixes are root-owned and its Claude port disables - * `claude update`, so neither npm nor the native updater can upgrade these installs. + * The port that installed the launcher or its target, "" when MacPorts owns it under an + * unusable name or its registry cannot be read, or null when it does not. MacPorts prefixes + * are root-owned and its Claude port disables `claude update`, so neither npm nor the native + * updater can upgrade these installs. */ export const resolveMacPortsOwner = Effect.fn("resolveMacPortsOwner")(function* ( context: ProviderMaintenanceResolutionContext, @@ -1192,17 +1193,29 @@ export const resolveMacPortsOwner = Effect.fn("resolveMacPortsOwner")(function* if (context.platform === "win32") return null; const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; - const siblingPort = path.join(path.dirname(context.resolvedCommandPath), "port"); - const portPath = (yield* fileSystem.exists(siblingPort).pipe(Effect.orElseSucceed(() => false))) - ? siblingPort - : yield* resolveCommandPath("port", { env: context.env }); - if (!portPath) return null; - const prefix = `${normalizeCommandPath(path.dirname(path.dirname(portPath)))}/`; - if (!normalizeCommandPath(context.realCommandPath).startsWith(prefix)) return null; - const output = yield* runProbe(portPath, ["provides", context.realCommandPath], context.env); - const name = output ? /\bis provided by: (\S+)/.exec(output)?.[1] : undefined; - if (name === undefined) return null; - return /^[\w.+-]+$/.test(name) ? name : ""; + const commandPaths = [...new Set([context.resolvedCommandPath, context.realCommandPath])]; + // A MacPorts prefix holds `bin/port`, so every prefix containing a command path is an ancestor. + const portPaths = new Set(); + for (const commandPath of commandPaths) { + for (let dir = path.dirname(commandPath); ; dir = path.dirname(dir)) { + portPaths.add(path.join(dir, "bin", "port")); + if (path.dirname(dir) === dir) break; + } + } + for (const portPath of portPaths) { + if (!(yield* fileSystem.exists(portPath).pipe(Effect.orElseSucceed(() => false)))) continue; + const prefix = `${normalizeCommandPath(path.dirname(path.dirname(portPath)))}/`; + const owned = commandPaths.filter((commandPath) => + normalizeCommandPath(commandPath).startsWith(prefix), + ); + if (owned.length === 0) continue; + const output = yield* runProbe(portPath, ["provides", ...owned], context.env); + // A failed registry lookup is no proof that the files are free to update. + if (output === null) return ""; + const name = /\bis provided by: (\S+)/.exec(output)?.[1]; + if (name !== undefined) return /^[\w.+-]+$/.test(name) ? name : ""; + } + return null; }); // Volta bin entries only identify its shim; the package image proves ownership. From 9c571f3c1a6f6364f05eab7d7723f5de76528620 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 22:10:46 -0800 Subject: [PATCH 286/324] fix(acp): sessions no longer keep a record of every turn they ran (#41256) Co-authored-by: Claude Opus 5.5 --- .../Adapters/AcpAdapterV2.test.ts | 2 ++ packages/provider-acp/src/server/adapter.ts | 15 ++------------- 2 files changed, 4 insertions(+), 13 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 43db1b82b63a2..a62977eb17fb2 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -7293,6 +7293,8 @@ describe("AcpAdapterV2", () => { if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) break; } const snapshotBeforeRollback = yield* runtime.readThreadSnapshot({ providerThread }); + // Turns reach orchestration as events; the session keeps no record of them. + assert.deepEqual(snapshotBeforeRollback.providerTurns, []); const rolledBack = yield* runtime.rollbackThread({ providerThread: { ...providerThread, appThreadId: rollbackThreadId }, diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 8905317d20f5f..9fb64218c5b29 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -2399,7 +2399,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const emitNativeResponseLifecycle = options.testHooks?.onNativeResponseLifecycle ?? (() => Effect.void); const nextElicitationOrdinal = yield* Ref.make(0); - const providerTurns = yield* Ref.make(new Map()); const snapshot = yield* Ref.make(emptySnapshotState()); const awaitRuntimeTeardown = Effect.fnUntraced(function* () { @@ -8006,7 +8005,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.set(promptRuntimeInstructions, new Map()); yield* Ref.set(compactionMarkers, new Map()); yield* Ref.set(completedCompactionIds, new Set()); - yield* Ref.set(providerTurns, new Map()); yield* Ref.set(snapshot, emptySnapshotState()); yield* continuationPermit.withPermit( Effect.gen(function* () { @@ -8718,11 +8716,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } yield* reportAgentModeChanges(context.input.threadId); const turn = providerTurnPayload(context, settledStatus, now); - yield* Ref.update(providerTurns, (current) => { - const updated = new Map(current); - updated.set(String(turn.id), turn); - return updated; - }); yield* emitProviderEvent({ type: "provider_turn.updated", driver, @@ -9622,11 +9615,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.set(activeTurn, context); yield* Ref.set(stoppedRunQuarantine, false); const runningTurn = providerTurnPayload(context, "running", null); - yield* Ref.update(providerTurns, (current) => { - const updated = new Map(current); - updated.set(String(runningTurn.id), runningTurn); - return updated; - }); yield* emitProviderEvent({ type: "provider_turn.updated", driver, @@ -10707,7 +10695,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( status: "idle" as const, updatedAt: now, }, - providerTurns: [...(yield* Ref.get(providerTurns)).values()], + // Imports read only the transcript; turns reach orchestration as events. + providerTurns: [], messages, reasoningMessageIds: [...state.reasoningIds], runtimeRequests: [], From cbf4ea7ddc715414155d06588a9250529a4128fd Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Mon, 23 Nov 2026 00:12:59 -0600 Subject: [PATCH 287/324] fix(web): shift-scroll and horizontal scrollers no longer navigate history (#41264) Co-authored-by: Cursor --- .../HistorySwipeNavigation.browser.test.tsx | 45 ++++++++++++++++++- .../src/components/HistorySwipeNavigation.tsx | 26 +++++++---- .../RightPanelTabs.browser.test.tsx | 4 +- 3 files changed, 63 insertions(+), 12 deletions(-) diff --git a/apps/web/src/components/HistorySwipeNavigation.browser.test.tsx b/apps/web/src/components/HistorySwipeNavigation.browser.test.tsx index d2a15729b0df2..d36efc1d535d7 100644 --- a/apps/web/src/components/HistorySwipeNavigation.browser.test.tsx +++ b/apps/web/src/components/HistorySwipeNavigation.browser.test.tsx @@ -24,7 +24,19 @@ describe("HistorySwipeNavigation", () => { false, ], ["scrolling left inside a scroller keeps the thread", "light", 100, -130, false], - ["swiping back at a shadow-root scroller's left edge navigates", "shadow", 0, -130, true], + ["scrolling at a shadow-root scroller's left edge keeps the thread", "shadow", 0, -130, false], + [ + "scrolling at a shadow-root scroller's right edge keeps the thread", + "shadow", + 800, + 130, + false, + ], + ["scrolling at a scroller's left edge keeps the thread", "light", 0, -130, false], + ["scrolling at a scroller's right edge keeps the thread", "light", 800, 130, false], + ["scrolling over a preview panel keeps the thread", "preview-panel", 0, -130, false], + ["scrolling over a desktop preview keeps the thread", "preview-viewport", 0, 130, false], + ["scrolling over a streamed preview keeps the thread", "server-browser", 0, -130, false], ["swiping back over a panel without overflow navigates", "none", 0, -130, true], ["a swipe that started in a closed dialog keeps the thread", "closed-dialog", 0, -130, false], ] as const)("%s", async (_name, scroller, scrollLeft, deltaX, navigates) => { @@ -34,7 +46,10 @@ describe("HistorySwipeNavigation", () => { const panel = screen.container.appendChild(document.createElement("div")); const root = scroller.startsWith("shadow") ? panel.attachShadow({ mode: "open" }) : panel; const viewport = root.appendChild(document.createElement("div")); - const noOverflow = scroller === "none" || scroller === "closed-dialog"; + const noOverflow = !scroller.startsWith("shadow") && scroller !== "light"; + if (scroller === "preview-panel") panel.setAttribute("data-preview-panel-mode", "inline"); + if (scroller === "preview-viewport") panel.setAttribute("data-preview-viewport", "tab"); + if (scroller === "server-browser") panel.setAttribute("data-server-browser-surface", "tab"); viewport.style.cssText = `width: 200px; overflow-x: ${noOverflow ? "visible" : "auto"}`; const content = viewport.appendChild(document.createElement("div")); content.style.cssText = `height: 20px; width: ${noOverflow ? 100 : 1000}px`; @@ -72,6 +87,32 @@ describe("HistorySwipeNavigation", () => { expect(navigateHistory).not.toHaveBeenCalled(); }); + it.each([ + ["Shift-scroll keeps the thread", [[-130, true]]], + [ + "pressing Shift during a swipe cancels navigation", + [ + [-130, false], + [-1, true], + ], + ], + [ + "releasing Shift during a scroll keeps the thread", + [ + [-1, true], + [-130, false], + ], + ], + ] as const)("%s", async (_name, events) => { + navigateHistory.mockReset(); + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("MacIntel"); + await using screen = await render(); + for (const [deltaX, shiftKey] of [...events, [0, false] as const]) { + screen.container.dispatchEvent(new WheelEvent("wheel", { deltaX, shiftKey, bubbles: true })); + } + expect(navigateHistory).not.toHaveBeenCalled(); + }); + // A vertical scroll 15° off vertical. const drift = Array.from({ length: 30 }, () => [-4, 15] as const); it.each([ diff --git a/apps/web/src/components/HistorySwipeNavigation.tsx b/apps/web/src/components/HistorySwipeNavigation.tsx index 2924f82cd3136..09b363c2d1f7e 100644 --- a/apps/web/src/components/HistorySwipeNavigation.tsx +++ b/apps/web/src/components/HistorySwipeNavigation.tsx @@ -44,16 +44,12 @@ function readMainContentBounds(): SwipeBounds { } // `event.target` stops at a shadow host; the composed path also reaches scrollers inside it. -function canScrollHorizontally(path: readonly EventTarget[], deltaX: number): boolean { +function hasHorizontalScroller(path: readonly EventTarget[]): boolean { for (const element of path) { if (!(element instanceof Element) || element.scrollWidth <= element.clientWidth) continue; const { overflowX } = getComputedStyle(element); if (overflowX !== "auto" && overflowX !== "scroll") continue; - const canScroll = - deltaX < 0 - ? element.scrollLeft > 0 - : element.scrollLeft + element.clientWidth < element.scrollWidth - 1; - if (canScroll) return true; + return true; } return false; } @@ -71,10 +67,19 @@ function lockSwipeAxis( if (Math.abs(sumX) <= Math.abs(sumY) || isVerticalScroll(Math.abs(sumX), Math.abs(sumY))) { return { kind: "ignored" }; } - if (path.some((node) => node instanceof Element && node.matches('[role="dialog"]'))) { + // Preview contents can scroll in another document or on the server, outside this DOM. + if ( + path.some( + (node) => + node instanceof Element && + node.matches( + '[role="dialog"], [data-preview-panel-mode], [data-preview-viewport], [data-server-browser-surface]', + ), + ) + ) { return { kind: "ignored" }; } - if (canScrollHorizontally(path, sumX)) return { kind: "ignored" }; + if (hasHorizontalScroller(path)) return { kind: "ignored" }; const direction = sumX < 0 ? "back" : "forward"; if (!canNavigateHistory(direction)) return { kind: "ignored" }; return { @@ -134,6 +139,11 @@ export function HistorySwipeNavigation() { gesture = null; }); const onWheel = (event: WheelEvent) => { + if (event.shiftKey) { + if (gesture?.kind === "tracking") hideIndicator(); + gesture = { kind: "ignored" }; + return; + } if (gesture === null) { gesture = event.ctrlKey || event.deltaMode !== WheelEvent.DOM_DELTA_PIXEL diff --git a/apps/web/src/components/RightPanelTabs.browser.test.tsx b/apps/web/src/components/RightPanelTabs.browser.test.tsx index 515d5cdbfb32b..347971993c7c3 100644 --- a/apps/web/src/components/RightPanelTabs.browser.test.tsx +++ b/apps/web/src/components/RightPanelTabs.browser.test.tsx @@ -68,7 +68,7 @@ const surfaces: RightPanelSurface[] = Array.from({ length: 16 }, (_, index) => ( })); describe("RightPanelTabs", () => { - it("a flick that scrolls the tab strip to its left edge keeps the thread, a swipe from the edge goes back", async () => { + it("a flick that scrolls the tab strip to its left edge keeps the thread, and so does a swipe from the edge", async () => { navigateHistory.mockReset(); const { bridge, scroll } = trackpad(); using _bridge = stubGlobal("desktopBridge", bridge); @@ -139,7 +139,7 @@ describe("RightPanelTabs", () => { viewport.scrollLeft = 0; scroll(viewport.querySelector("[data-active-tab]")!, [-40, -40, -40, -40, -40]); - expect(navigateHistory).toHaveBeenCalledExactlyOnceWith("back"); + expect(navigateHistory).not.toHaveBeenCalled(); }); }); From 597c8de32b2692cf18caa9ee50748e42acc7b1d3 Mon Sep 17 00:00:00 2001 From: Jui-Chen Chien Date: Mon, 23 Nov 2026 14:14:16 +0800 Subject: [PATCH 288/324] fix(web): hidden preview tabs larger than the window capture whole (#26965) Co-authored-by: jason chien <3936511+jason5545@users.noreply.github.com> Co-authored-by: Julius Marminge --- apps/web/src/browser/HostedBrowserWebview.tsx | 22 +++++++-------- .../src/browser/browserViewportLayout.test.ts | 27 +++++++++++++++++++ apps/web/src/browser/browserViewportLayout.ts | 24 +++++++++++++++++ 3 files changed, 61 insertions(+), 12 deletions(-) diff --git a/apps/web/src/browser/HostedBrowserWebview.tsx b/apps/web/src/browser/HostedBrowserWebview.tsx index b20d737095116..766f94b597903 100644 --- a/apps/web/src/browser/HostedBrowserWebview.tsx +++ b/apps/web/src/browser/HostedBrowserWebview.tsx @@ -13,6 +13,7 @@ import { } from "~/components/preview/thumbButtons"; import { usePreviewBridge } from "~/components/preview/usePreviewBridge"; import { useClientSettingsHydrated } from "~/hooks/useSettings"; +import { useViewportSize } from "~/hooks/useViewportSize"; import { cn, isMacPlatform } from "~/lib/utils"; import { resolveBrowserSurfacePanelRect, useBrowserSurfaceStore } from "./browserSurfaceStore"; @@ -22,6 +23,7 @@ import { resolveBrowserViewportLayout, resolveBrowserViewportTransform, resolveFittedBrowserViewport, + resolveHiddenBrowserViewportSize, } from "./browserViewportLayout"; import { BrowserDeviceToolbar } from "./BrowserDeviceToolbar"; import { BrowserViewportResizeHandles } from "./BrowserViewportResizeHandles"; @@ -243,18 +245,14 @@ export function HostedBrowserWebview(props: { setAspectRatioLocked(aspectRatio !== null); }; const content = presentation.content; - const hiddenWidth = - viewport._tag !== "fill" - ? viewport.width * layoutZoomFactor - : content - ? content.width / content.scale - : (lastRect?.width ?? 1280); - const hiddenHeight = - viewport._tag !== "fill" - ? viewport.height * layoutZoomFactor - : content - ? content.height / content.scale - : (lastRect?.height ?? 800); + const windowSize = useViewportSize(); + const { width: hiddenWidth, height: hiddenHeight } = resolveHiddenBrowserViewportSize({ + setting: viewport, + zoomFactor: layoutZoomFactor, + content, + lastRect, + windowSize, + }); // Build from primitives on each side of the resize hook to keep both objects cached. const containerSize = active && lastRect ? lastRect : { width: hiddenWidth, height: hiddenHeight }; diff --git a/apps/web/src/browser/browserViewportLayout.test.ts b/apps/web/src/browser/browserViewportLayout.test.ts index c72f68e1e20da..54a6258edb97a 100644 --- a/apps/web/src/browser/browserViewportLayout.test.ts +++ b/apps/web/src/browser/browserViewportLayout.test.ts @@ -2,8 +2,10 @@ import { describe, expect, it } from "vite-plus/test"; import { resizeBrowserViewportFromRail, + resolveBrowserViewportLayout, resolveBrowserViewportTransform, resolveFittedBrowserViewport, + resolveHiddenBrowserViewportSize, } from "./browserViewportLayout"; describe("resolveBrowserViewportLayout", () => { @@ -43,6 +45,31 @@ describe("resolveBrowserViewportLayout", () => { ), ).toEqual({ width: 460, height: 409 }); }); + + it("fits a hidden fixed viewport larger than the window inside the window", () => { + const setting = { _tag: "freeform", width: 1440, height: 1700 } as const; + const windowSize = { width: 1400, height: 1000 }; + const hidden = resolveHiddenBrowserViewportSize({ + setting, + zoomFactor: 1, + content: null, + lastRect: null, + windowSize, + }); + expect(hidden).toEqual({ width: 1400, height: 1000 }); + const layout = resolveBrowserViewportLayout(hidden, setting); + expect(layout.viewportHeight).toBeLessThanOrEqual(windowSize.height); + expect(layout.viewportScale).toBeCloseTo(1000 / 1700); + expect( + resolveHiddenBrowserViewportSize({ + setting: { _tag: "freeform", width: 1280, height: 800 }, + zoomFactor: 1, + content: null, + lastRect: null, + windowSize, + }), + ).toEqual({ width: 1280, height: 800 }); + }); }); describe("resolveBrowserViewportTransform", () => { diff --git a/apps/web/src/browser/browserViewportLayout.ts b/apps/web/src/browser/browserViewportLayout.ts index 7fe6b170c671d..4b1fc5e41b08e 100644 --- a/apps/web/src/browser/browserViewportLayout.ts +++ b/apps/web/src/browser/browserViewportLayout.ts @@ -71,6 +71,30 @@ export function resolveFittedBrowserViewport( return { _tag: "freeform", width: 1280, height: 800 }; } +export function resolveHiddenBrowserViewportSize(input: { + readonly setting: PreviewViewportSetting; + readonly zoomFactor: number; + readonly content: { + readonly width: number; + readonly height: number; + readonly scale: number; + } | null; + readonly lastRect: { readonly width: number; readonly height: number } | null; + readonly windowSize: { readonly width: number; readonly height: number }; +}): { readonly width: number; readonly height: number } { + const { content, lastRect, setting, windowSize, zoomFactor } = input; + if (setting._tag !== "fill") { + // Chromium paints a guest only near the window, so a capture of a larger one loses its far edge. + return { + width: Math.min(windowSize.width, setting.width * zoomFactor), + height: Math.min(windowSize.height, setting.height * zoomFactor), + }; + } + if (content) + return { width: content.width / content.scale, height: content.height / content.scale }; + return { width: lastRect?.width ?? 1280, height: lastRect?.height ?? 800 }; +} + export function resolveBrowserDeviceViewportArea(container: { readonly width: number; readonly height: number; From 5812320a6a6714ef05ada591ffbafc4580d5ee8e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 22:21:51 -0800 Subject: [PATCH 289/324] fix(web): quick clicks on different sidebar threads open each one (#41258) --- .../src/components/Sidebar.browser.test.tsx | 51 +++++++++++++++++++ apps/web/src/components/Sidebar.tsx | 3 +- 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/Sidebar.browser.test.tsx b/apps/web/src/components/Sidebar.browser.test.tsx index 1a0b4c588d64c..1fb930f55fabc 100644 --- a/apps/web/src/components/Sidebar.browser.test.tsx +++ b/apps/web/src/components/Sidebar.browser.test.tsx @@ -329,6 +329,57 @@ describe("sidebar thread rename", () => { ); }); +describe("sidebar thread click", () => { + // regression: #40715 macOS counts quick clicks on different rows, so the next row got detail 2 and was ignored + it("opens another thread when the click arrives with a double-click count", async () => { + const activeProject = project("active"); + const threads = [threadShell(activeProject.id, 0), threadShell(activeProject.id, 1)]; + const routeThreadRef: ScopedThreadRef = { + environmentId: activeProject.environmentId, + threadId: threads[0]!.id, + }; + vi.mocked(useProjects).mockReturnValue([activeProject]); + vi.mocked(useQuietThreadShells).mockReturnValue(threads); + vi.mocked(useThreadRouteTarget).mockReturnValue({ kind: "server", threadRef: routeThreadRef }); + vi.mocked(useHandleNewThread).mockReturnValue({ + activeDraftThread: null, + activeThread: null, + defaultProjectRef: { + environmentId: activeProject.environmentId, + projectId: activeProject.id, + }, + defaultProjectFallbackReady: true, + handleNewThread: vi.fn().mockResolvedValue(null), + routeDraftId: null, + routeThreadRef, + }); + await using screen = await render( + + + , + { router: "/local/thread-0" }, + ); + const navigate = vi.spyOn(screen.router!, "navigate").mockResolvedValue(undefined); + + const openRow = screen.getByText("Thread 0").first().element(); + await act(() => { + openRow.dispatchEvent( + new MouseEvent("click", { bubbles: true, cancelable: true, detail: 2 }), + ); + }); + expect(navigate).not.toHaveBeenCalled(); + + const row = screen.getByText("Thread 1").first().element(); + await act(() => { + row.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, detail: 2 })); + }); + + expect(navigate).toHaveBeenCalledWith( + expect.objectContaining({ params: expect.objectContaining({ threadId: "thread-1" }) }), + ); + }); +}); + describe("sidebar thread menu", () => { it("tells the menu whether the keyboard opened it", async () => { const activeProject = project("active"); diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index e9d45a5c1fd84..2a8dcdff50d86 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -1612,7 +1612,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve rangeSelectTo(threadKey, orderedThreadKeysRef.current); return; } - if (isTrailingDoubleClick(event.detail)) { + // macOS keeps counting quick clicks across rows, so only the open row's trailing click is a double-click. + if (isTrailingDoubleClick(event.detail) && routeThreadKey === threadKey) { return; } navigateToThread(threadRef); From ba588ef663edb350aa333f9ce008b3bd7cbcfe3d Mon Sep 17 00:00:00 2001 From: Yukun Shan <92423096+nateEc@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:22:35 +0800 Subject: [PATCH 290/324] fix(web): match macOS Option shortcuts to the active keyboard layout (#24034) Co-authored-by: maria-rcks Co-authored-by: Julius Marminge --- .../settings/KeybindingsSettings.logic.ts | 7 +- apps/web/src/keybindings.test.ts | 71 ++++++++++++++++ apps/web/src/keybindings.ts | 24 +++++- apps/web/src/keyboardLayout.test.ts | 81 +++++++++++++++++++ apps/web/src/keyboardLayout.ts | 44 ++++++++++ apps/web/src/main.tsx | 4 + packages/shared/src/keybindingMatching.ts | 21 ++++- packages/shared/src/keybindings.ts | 1 + 8 files changed, 246 insertions(+), 7 deletions(-) create mode 100644 apps/web/src/keyboardLayout.test.ts create mode 100644 apps/web/src/keyboardLayout.ts diff --git a/apps/web/src/components/settings/KeybindingsSettings.logic.ts b/apps/web/src/components/settings/KeybindingsSettings.logic.ts index 55d4278b0fe16..9d03b7ab72e48 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.logic.ts +++ b/apps/web/src/components/settings/KeybindingsSettings.logic.ts @@ -557,8 +557,9 @@ function titleCaseCommandSegment(segment: string): string { function recordedLayoutShortcutKey( event: Pick, + platform: string, ): string { - const physicalKey = shortcutKeyFromEvent(event); + const physicalKey = shortcutKeyFromEvent(event, platform); const layoutKey = event.key.toLowerCase(); if (event.altKey || layoutKey.length !== 1) return physicalKey; // Normalize only US shifted glyphs at their US position. Other layouts can @@ -605,7 +606,9 @@ export function keybindingFromKeyboardEvent( }, ): string | null { const keyToken = normalizeShortcutKeyToken( - options?.layoutCharacter ? recordedLayoutShortcutKey(event) : shortcutKeyFromEvent(event), + options?.layoutCharacter + ? recordedLayoutShortcutKey(event, platform) + : shortcutKeyFromEvent(event, platform), ); if (!keyToken) return null; diff --git a/apps/web/src/keybindings.test.ts b/apps/web/src/keybindings.test.ts index fb6f719bb2346..84463efc3abfd 100644 --- a/apps/web/src/keybindings.test.ts +++ b/apps/web/src/keybindings.test.ts @@ -758,6 +758,77 @@ describe("resolveShortcutCommand", () => { ); }); + it("matches Option symbols against the active Latin layout rather than the US position", () => { + const keybindings = compile([ + { shortcut: modShortcut("a", { altKey: true, shiftKey: true }), command: "appearance.cycle" }, + { shortcut: modShortcut("q", { altKey: true, shiftKey: true }), command: "sidebar.toggle" }, + ]); + assert.strictEqual( + resolveShortcutCommand( + event({ key: "Æ", code: "KeyQ", metaKey: true, altKey: true, shiftKey: true }), + keybindings, + { platform: "MacIntel", keyboardLayoutMap: new Map([["KeyQ", "a"]]) }, + ), + "appearance.cycle", + ); + }); + + it("preserves physical punctuation alongside an Option-modified mapped letter", () => { + for (const key of [";", "m"]) { + const keybindings = compile([ + { shortcut: modShortcut(key, { altKey: true }), command: "diff.toggle" }, + ]); + assert.strictEqual( + resolveShortcutCommand( + event({ key: "µ", code: "Semicolon", metaKey: true, altKey: true }), + keybindings, + { platform: "MacIntel", keyboardLayoutMap: new Map([["Semicolon", "m"]]) }, + ), + "diff.toggle", + ); + } + }); + + it("keeps Latin event keys and unsupported layout fallbacks", () => { + const keybindings = compile([ + { shortcut: modShortcut("a", { altKey: true }), command: "appearance.cycle" }, + { shortcut: modShortcut("q", { altKey: true }), command: "sidebar.toggle" }, + ]); + const options = { platform: "MacIntel", keyboardLayoutMap: new Map([["KeyQ", "a"]]) }; + assert.strictEqual( + resolveShortcutCommand( + event({ key: "q", code: "KeyQ", metaKey: true, altKey: true }), + keybindings, + options, + ), + "sidebar.toggle", + ); + for (const keyboardLayoutMap of [new Map(), new Map([["KeyQ", "й"]])]) { + assert.strictEqual( + resolveShortcutCommand( + event({ key: "Æ", code: "KeyQ", metaKey: true, altKey: true }), + keybindings, + { ...options, keyboardLayoutMap }, + ), + "sidebar.toggle", + ); + } + assert.strictEqual( + resolveShortcutCommand( + event({ + key: "Æ", + code: "KeyQ", + ctrlKey: true, + altKey: true, + getModifierState: () => true, + }), + keybindings, + { ...options, platform: "Win32" }, + ), + null, + ); + }); + it("matches non-Latin layout letters using the physical key code", () => { const keybindings = compile([{ shortcut: modShortcut("d"), command: "diff.toggle" }]); diff --git a/apps/web/src/keybindings.ts b/apps/web/src/keybindings.ts index f05067a2e53bc..117847faa95bb 100644 --- a/apps/web/src/keybindings.ts +++ b/apps/web/src/keybindings.ts @@ -17,13 +17,24 @@ import { resolveEventKeys, type ShortcutEventLike as SharedShortcutEventLike, type ShortcutModifierStateLike, + type ShortcutKeyboardLayoutMap, + shortcutKeyFromEvent as sharedShortcutKeyFromEvent, } from "@t3tools/shared/keybindings"; import { isElectron } from "./env"; import { isEditableFocused } from "./lib/editableFocus"; import { projectScriptIdFromCommand } from "./projectScripts"; +import { getKeyboardLayoutMap } from "./keyboardLayout"; export type { ShortcutModifierStateLike } from "@t3tools/shared/keybindings"; -export { shortcutKeyFromEvent } from "@t3tools/shared/keybindings"; +export function shortcutKeyFromEvent( + event: Pick, + platform: string, +) { + return sharedShortcutKeyFromEvent( + event, + isMacPlatform(platform) && event.altKey ? getKeyboardLayoutMap() : undefined, + ); +} export interface ShortcutEventLike extends SharedShortcutEventLike { target?: EventTarget | null; @@ -42,6 +53,7 @@ export interface ShortcutMatchContext { interface ShortcutMatchOptions { platform?: string; + keyboardLayoutMap?: ShortcutKeyboardLayoutMap; context?: Partial; } @@ -194,7 +206,15 @@ export function resolveShortcutCommand( const binding = keybindings[index]; if (!binding) continue; if (!matchesWhenClause(binding.whenAst, context)) continue; - if (!matchesKeybindingShortcut(event, shortcutForContext(binding, context), platform)) continue; + if ( + !matchesKeybindingShortcut( + event, + shortcutForContext(binding, context), + platform, + options?.keyboardLayoutMap ?? getKeyboardLayoutMap(), + ) + ) + continue; return binding.command; } return null; diff --git a/apps/web/src/keyboardLayout.test.ts b/apps/web/src/keyboardLayout.test.ts new file mode 100644 index 0000000000000..b33ef3218041d --- /dev/null +++ b/apps/web/src/keyboardLayout.test.ts @@ -0,0 +1,81 @@ +import { afterEach, assert, it } from "vite-plus/test"; +import { getKeyboardLayoutMap, trackKeyboardLayout } from "./keyboardLayout"; +import { keybindingFromKeyboardEvent } from "./components/settings/KeybindingsSettings.logic"; + +let stop: (() => void) | undefined; +afterEach(() => stop?.()); + +function pendingLayout() { + let resolve!: (layout: Map) => void; + const promise = new Promise>((done) => { + resolve = done; + }); + return { promise, resolve }; +} + +it.each([true, false])( + "records Option symbols and refreshes the current layout (keyboard events: %s)", + async (supportsEvents) => { + let layout = Promise.resolve(new Map([["KeyQ", "a"]])); + const keyboard = Object.assign(supportsEvents ? new EventTarget() : {}, { + getLayoutMap: () => layout, + }); + const focusTarget = new EventTarget(); + stop = trackKeyboardLayout(keyboard, focusTarget); + await keyboard.getLayoutMap(); + const event = { + key: "Æ", + code: "KeyQ", + metaKey: true, + ctrlKey: false, + altKey: true, + shiftKey: true, + }; + assert.strictEqual(keybindingFromKeyboardEvent(event, "MacIntel"), "mod+alt+shift+a"); + assert.strictEqual( + keybindingFromKeyboardEvent(event, "MacIntel", { layoutCharacter: true }), + "mod+alt+shift+a", + ); + const pending = pendingLayout(); + layout = pending.promise; + focusTarget.dispatchEvent(new Event("focus")); + assert.strictEqual(keybindingFromKeyboardEvent(event, "MacIntel"), "mod+alt+shift+a"); + pending.resolve(new Map([["KeyQ", "q"]])); + await layout; + assert.strictEqual(keybindingFromKeyboardEvent(event, "MacIntel"), "mod+alt+shift+q"); + layout = Promise.reject(new Error("Permission denied")); + focusTarget.dispatchEvent(new Event("focus")); + assert.strictEqual(getKeyboardLayoutMap()?.get("KeyQ"), "q"); + await layout.catch(() => undefined); + assert.strictEqual(getKeyboardLayoutMap(), undefined); + layout = Promise.resolve(new Map([["KeyQ", "a"]])); + stop(); + focusTarget.dispatchEvent(new Event("focus")); + await keyboard.getLayoutMap(); + assert.strictEqual(getKeyboardLayoutMap(), undefined); + }, +); + +it("ignores an obsolete layout result", async () => { + const pending = pendingLayout(); + let result = pending.promise; + const keyboard = Object.assign(new EventTarget(), { getLayoutMap: () => result }); + stop = trackKeyboardLayout(keyboard); + result = Promise.resolve(new Map([["KeyQ", "q"]])); + keyboard.dispatchEvent(new Event("layoutchange")); + assert.strictEqual(getKeyboardLayoutMap(), undefined); + await result; + pending.resolve(new Map([["KeyQ", "a"]])); + await pending.promise; + assert.strictEqual(getKeyboardLayoutMap()?.get("KeyQ"), "q"); +}); + +it("does not publish a pending result after disposal", async () => { + const pending = pendingLayout(); + const keyboard = Object.assign(new EventTarget(), { getLayoutMap: () => pending.promise }); + stop = trackKeyboardLayout(keyboard); + stop(); + pending.resolve(new Map([["KeyQ", "a"]])); + await pending.promise; + assert.strictEqual(getKeyboardLayoutMap(), undefined); +}); diff --git a/apps/web/src/keyboardLayout.ts b/apps/web/src/keyboardLayout.ts new file mode 100644 index 0000000000000..61fd6e24a1b57 --- /dev/null +++ b/apps/web/src/keyboardLayout.ts @@ -0,0 +1,44 @@ +import type { ShortcutKeyboardLayoutMap } from "@t3tools/shared/keybindings"; + +interface KeyboardLayoutSource extends Partial< + Pick +> { + getLayoutMap(): Promise; +} + +let keyboardLayoutMap: ShortcutKeyboardLayoutMap | undefined; + +export function getKeyboardLayoutMap() { + return keyboardLayoutMap; +} + +// Option changes event.key to a symbol on macOS; the layout map recovers the +// letter printed on that key without assuming a US physical layout. +export function trackKeyboardLayout( + keyboard = (navigator as Navigator & { keyboard?: KeyboardLayoutSource }).keyboard, + focusTarget: EventTarget | undefined = typeof window === "undefined" ? undefined : window, +) { + let revision = 0; + const refresh = async (clearMap: boolean) => { + const request = ++revision; + if (clearMap) keyboardLayoutMap = undefined; + try { + const layout = await keyboard?.getLayoutMap(); + if (request === revision) keyboardLayoutMap = layout; + } catch { + // Unsupported or permission-blocked browsers keep the existing fallback. + if (request === revision) keyboardLayoutMap = undefined; + } + }; + const onLayoutChange = () => void refresh(true); + const onFocus = () => void refresh(false); + void refresh(true); + keyboard?.addEventListener?.("layoutchange", onLayoutChange); + focusTarget?.addEventListener("focus", onFocus); + return () => { + revision++; + keyboardLayoutMap = undefined; + keyboard?.removeEventListener?.("layoutchange", onLayoutChange); + focusTarget?.removeEventListener("focus", onFocus); + }; +} diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsx index 51aeeade6863d..2640ca1e167d0 100644 --- a/apps/web/src/main.tsx +++ b/apps/web/src/main.tsx @@ -4,6 +4,7 @@ import ReactDOM from "react-dom/client"; import "@fontsource-variable/inter"; import "./index.css"; +import { trackKeyboardLayout } from "./keyboardLayout"; import { hasCloudPublicConfig } from "./cloud/publicConfig"; import { isElectron } from "./env"; import { startAppServices } from "./appInit"; @@ -11,6 +12,9 @@ import { AppRoot } from "./AppRoot"; import { whenLocaleReady } from "./i18n/runtime"; import { chunkLoadState } from "./lib/chunkReloadGuard"; +const stopTrackingKeyboardLayout = trackKeyboardLayout(); +import.meta.hot?.dispose(stopTrackingKeyboardLayout); + const router = startAppServices(); const clerkPublishableKey = import.meta.env.VITE_CLERK_PUBLISHABLE_KEY as string | undefined; diff --git a/packages/shared/src/keybindingMatching.ts b/packages/shared/src/keybindingMatching.ts index 75e6786cd1429..f02e5d47e2aa2 100644 --- a/packages/shared/src/keybindingMatching.ts +++ b/packages/shared/src/keybindingMatching.ts @@ -82,11 +82,16 @@ export function normalizeEventKey(key: string): string { return normalized; } +export type ShortcutKeyboardLayoutMap = Pick, "get">; + export function shortcutKeyFromEvent( event: Pick, + keyboardLayoutMap?: ShortcutKeyboardLayoutMap, ): string { const layoutKey = normalizeEventKey(event.key); if (/^[a-z]$/.test(layoutKey)) return layoutKey; + const mappedKey = event.code ? keyboardLayoutMap?.get(event.code)?.toLowerCase() : undefined; + if (mappedKey && /^[a-z]$/.test(mappedKey)) return mappedKey; // Only the US layout's glyph at its own key: other layouts and AltGr keep their character. const usOptionLetter = event.altKey ? US_MAC_OPTION_GLYPH_LETTERS.get(event.key) : undefined; if (usOptionLetter && event.code === `Key${usOptionLetter.toUpperCase()}`) return usOptionLetter; @@ -97,13 +102,19 @@ export function shortcutKeyFromEvent( return physicalKey ?? layoutKey; } -export function resolveEventKeys(event: ShortcutEventLike): Set { +export function resolveEventKeys( + event: ShortcutEventLike, + keyboardLayoutMap?: ShortcutKeyboardLayoutMap, +): Set { const layoutKey = normalizeEventKey(event.key); const keys = new Set([layoutKey]); const letterCode = event.code?.match(/^Key([A-Z])$/)?.[1]; - if (letterCode && !/^[a-z]$/.test(layoutKey)) { + const shortcutKey = shortcutKeyFromEvent(event, keyboardLayoutMap); + if (letterCode && !/^[a-z]$/.test(shortcutKey)) { keys.add(letterCode.toLowerCase()); } + keys.add(shortcutKey); + // Layout letters supplement, rather than replace, physical punctuation shortcuts. keys.add(shortcutKeyFromEvent(event)); return keys; } @@ -128,6 +139,7 @@ export function matchesKeybindingShortcut( event: ShortcutEventLike, shortcut: KeybindingShortcut, platform: string, + keyboardLayoutMap?: ShortcutKeyboardLayoutMap, ): boolean { if ( !isMacPlatform(platform) && @@ -136,5 +148,8 @@ export function matchesKeybindingShortcut( ) return false; if (!matchesKeybindingShortcutModifiers(event, shortcut, platform)) return false; - return resolveEventKeys(event).has(shortcut.key); + return resolveEventKeys( + event, + isMacPlatform(platform) && event.altKey ? keyboardLayoutMap : undefined, + ).has(shortcut.key); } diff --git a/packages/shared/src/keybindings.ts b/packages/shared/src/keybindings.ts index 29bb71d5f6f1a..3d9fcc0727d3d 100644 --- a/packages/shared/src/keybindings.ts +++ b/packages/shared/src/keybindings.ts @@ -20,6 +20,7 @@ export { shortcutKeyFromEvent, type ShortcutEventLike, type ShortcutModifierStateLike, + type ShortcutKeyboardLayoutMap, } from "./keybindingMatching.ts"; export const US_SHIFTED_TO_UNSHIFTED_KEYS: ReadonlyMap = new Map([ From 52b9b77e3fd74bba9d2d9199517e65c40aa0672c Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 00:28:54 -0600 Subject: [PATCH 291/324] fix(server): let the CLI answer workflow questions by their exact name (#41260) Co-authored-by: Julius Marminge --- apps/server/src/mcp/toolkits/workflow/tools.test.ts | 10 ++++++++++ apps/server/src/mcp/toolkits/workflow/tools.ts | 9 ++++++++- 2 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 apps/server/src/mcp/toolkits/workflow/tools.test.ts diff --git a/apps/server/src/mcp/toolkits/workflow/tools.test.ts b/apps/server/src/mcp/toolkits/workflow/tools.test.ts new file mode 100644 index 0000000000000..996802992338f --- /dev/null +++ b/apps/server/src/mcp/toolkits/workflow/tools.test.ts @@ -0,0 +1,10 @@ +import { expect, it } from "@effect/vitest"; +import * as Schema from "effect/Schema"; + +import { WorkflowToolkit } from "./tools.ts"; + +it("signal keeps a wait's exact name", () => { + const decode = Schema.decodeUnknownSync(WorkflowToolkit.tools.t3_workflow.parametersSchema); + expect(decode({ action: "signal", runId: "run-1", wait: "review " }).wait).toBe("review "); + expect(() => decode({ action: "signal", runId: "run-1", wait: " " })).toThrow(); +}); diff --git a/apps/server/src/mcp/toolkits/workflow/tools.ts b/apps/server/src/mcp/toolkits/workflow/tools.ts index fa01dfb7c5712..70289badab205 100644 --- a/apps/server/src/mcp/toolkits/workflow/tools.ts +++ b/apps/server/src/mcp/toolkits/workflow/tools.ts @@ -29,7 +29,14 @@ const WorkflowTool = Tool.make("t3_workflow", { idempotencyKey: Schema.optional(TrimmedNonEmptyString), runId: Schema.optional(TrimmedNonEmptyString), status: Schema.optional(WorkflowRunStatus), - wait: Schema.optional(TrimmedNonEmptyString), + // Waits match by exact name, so a name keeps its spaces. + wait: Schema.optional( + Schema.String.check( + Schema.makeFilter((name: string) => name.trim().length > 0, { + expected: "a non-blank string", + }), + ), + ), key: Schema.optional(TrimmedNonEmptyString), channel: Schema.optional(TrimmedNonEmptyString), value: Schema.optional(Schema.Json), From 10765a4e47a208a04b94055dd71967a2921f4ac7 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 22:29:33 -0800 Subject: [PATCH 292/324] fix(web): a refused desktop install shows as failed instead of downloaded (#41262) --- .../components/desktopUpdate.logic.test.ts | 56 +++++++++++++++++++ .../web/src/components/desktopUpdate.logic.ts | 39 ++++++++++++- .../components/settings/SettingsPanels.tsx | 16 +++++- .../components/sidebar/SidebarUpdatePill.tsx | 3 +- 4 files changed, 110 insertions(+), 4 deletions(-) diff --git a/apps/web/src/components/desktopUpdate.logic.test.ts b/apps/web/src/components/desktopUpdate.logic.test.ts index 29494789b6cff..601527e51a201 100644 --- a/apps/web/src/components/desktopUpdate.logic.test.ts +++ b/apps/web/src/components/desktopUpdate.logic.test.ts @@ -5,7 +5,9 @@ import { canCheckForUpdate, getDesktopUpdateButtonTooltip, getDesktopUpdateReleaseHistoryUrl, + getDesktopUpdateActionError, getDesktopUpdateReleaseUrl, + installDesktopUpdate, resolveDesktopUpdateButtonAction, } from "./desktopUpdate.logic"; @@ -58,6 +60,60 @@ describe("desktop update button state", () => { ); }); + it("shows the install failure after the desktop returns to downloaded", () => { + // reduceDesktopUpdateStateOnInstallFailure: a refused macOS install prompt lands here. + const state: DesktopUpdateState = { + ...baseState, + status: "downloaded", + availableVersion: "1.1.0", + downloadedVersion: "1.1.0", + message: "Desktop updater install operation reported an error.", + errorContext: "install", + canRetry: true, + }; + expect(resolveDesktopUpdateButtonAction(state)).toBe("install"); + expect(getDesktopUpdateButtonTooltip(state)).toBe("Install failed for 1.1.0. Click to retry."); + }); + + it("reports an install the desktop refuses after accepting it", async () => { + const downloaded: DesktopUpdateState = { + ...baseState, + status: "downloaded", + availableVersion: "1.1.0", + downloadedVersion: "1.1.0", + }; + const failed: DesktopUpdateState = { + ...downloaded, + message: "OSStatus error -60006.", + errorContext: "install", + canRetry: true, + }; + const listeners = new Set<(state: DesktopUpdateState) => void>(); + const emit = (state: DesktopUpdateState) => listeners.forEach((listener) => listener(state)); + const install = installDesktopUpdate({ + onUpdateState: (listener) => { + listeners.add(listener); + return () => listeners.delete(listener); + }, + installUpdate: async () => { + // A retry's pre-install check can restore the previous failure before the restart starts. + emit(failed); + return { accepted: true, completed: false, state: downloaded }; + }, + }); + let settled = false; + void install.then(() => { + settled = true; + }); + await Promise.resolve(); + await Promise.resolve(); + expect(settled).toBe(false); + emit(failed); + const result = await install; + expect(getDesktopUpdateActionError(result)).toBe("OSStatus error -60006."); + expect(listeners.size).toBe(0); + }); + it("never calls a build on the other track up to date", () => { // A Stable build whose switch to Nightly did not finish; the updater discards every release. const state: DesktopUpdateState = { diff --git a/apps/web/src/components/desktopUpdate.logic.ts b/apps/web/src/components/desktopUpdate.logic.ts index d3d4f618c8268..4922ee3b524b7 100644 --- a/apps/web/src/components/desktopUpdate.logic.ts +++ b/apps/web/src/components/desktopUpdate.logic.ts @@ -1,5 +1,9 @@ import { desktopTrackMismatchText } from "@t3tools/client-runtime/state/server"; -import type { DesktopUpdateActionResult, DesktopUpdateState } from "@t3tools/contracts"; +import type { + DesktopBridge, + DesktopUpdateActionResult, + DesktopUpdateState, +} from "@t3tools/contracts"; import { desktopUpdateChannelOf } from "@t3tools/shared/cliRelease"; import { msg } from "gt-react"; @@ -142,6 +146,11 @@ export function getDesktopUpdateButtonTooltip( : resolve(msg("Downloading update")); } if (state.status === "downloaded") { + if (state.errorContext === "install" && state.downloadedVersion) { + return resolve( + msg("Install failed for {version}. Click to retry.", { version: state.downloadedVersion }), + ); + } const version = state.downloadedVersion ?? state.availableVersion; return version === null ? resolve(msg("Update ready downloaded. Click to restart and install.")) @@ -212,6 +221,34 @@ export function getDesktopUpdateActionError(result: DesktopUpdateActionResult): return message.length > 0 ? message : null; } +/** + * macOS can refuse the restart after installUpdate resolves; the desktop then reports it as a + * later state with errorContext "install". Success quits the app, so this never resolves then. + */ +export async function installDesktopUpdate( + bridge: Pick, + expectedVersion?: string, +): Promise { + let awaitingFailure = false; + let reportFailure: (state: DesktopUpdateState) => void = () => {}; + const failure = new Promise((resolve) => { + reportFailure = resolve; + }); + const unsubscribe = bridge.onUpdateState((state) => { + if (awaitingFailure && state.errorContext === "install") reportFailure(state); + }); + try { + const result = await bridge.installUpdate(expectedVersion); + if (!result.accepted || result.completed || getDesktopUpdateActionError(result) !== null) { + return result; + } + awaitingFailure = true; + return { ...result, state: await failure }; + } finally { + unsubscribe(); + } +} + export function shouldToastDesktopUpdateActionResult(result: DesktopUpdateActionResult): boolean { return getDesktopUpdateActionError(result) !== null; } diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index 493d8a1e79565..97b278a463e9e 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -42,9 +42,11 @@ import { CliCommandSettingsRow } from "./CliCommandSettingsRow"; import { MobileAppSettingsRow } from "./MobileAppSettingsRow"; import { canCheckForUpdate, + getDesktopUpdateActionError, getDesktopUpdateButtonTooltip, getDesktopUpdateDisabledReason, getDesktopUpdateInstallConfirmationMessage, + installDesktopUpdate, isDesktopUpdateButtonDisabled, resolveDesktopUpdateButtonAction, } from "../../components/desktopUpdate.logic"; @@ -255,8 +257,18 @@ function AboutVersionSection() { setIsUpdateActionPending(false); return; } - void bridge - .installUpdate() + void installDesktopUpdate(bridge) + .then((result) => { + const actionError = getDesktopUpdateActionError(result); + if (!actionError) return; + toastManager.add( + stackedThreadToast({ + type: "error", + title: gt("Could not install update"), + description: actionError, + }), + ); + }) .catch((error: unknown) => { toastManager.add( stackedThreadToast({ diff --git a/apps/web/src/components/sidebar/SidebarUpdatePill.tsx b/apps/web/src/components/sidebar/SidebarUpdatePill.tsx index 71fce36f3ed43..156e89364670c 100644 --- a/apps/web/src/components/sidebar/SidebarUpdatePill.tsx +++ b/apps/web/src/components/sidebar/SidebarUpdatePill.tsx @@ -22,6 +22,7 @@ import { getDesktopUpdateDownloadedVersion, getDesktopUpdateIdleTooltip, getDesktopUpdateInstallConfirmationMessage, + installDesktopUpdate, isDesktopUpdateButtonDisabled, resolveDesktopUpdateButtonAction, shouldShowArm64IntelBuildWarning, @@ -176,7 +177,7 @@ export async function installLocalUpdate( expectedVersion?: string, ): Promise { try { - const result = await bridge.installUpdate(expectedVersion); + const result = await installDesktopUpdate(bridge, expectedVersion); if (!result.accepted) { showDesktopUpdateDownloadedToast(bridge, result.state); return false; From 21b52875ea5621174638436b6074edfe2fd10590 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 22:31:07 -0800 Subject: [PATCH 293/324] refactor(server): adapter snapshots stop carrying provider turns nothing reads (#41276) Co-authored-by: Claude Opus 5.5 --- .../Adapters/AcpAdapterV2.test.ts | 8 +- .../Adapters/ClaudeAdapterV2.ts | 2 - .../Adapters/CodexAdapterV2.ts | 3 - .../Adapters/OpenCode2AdapterV2.test.ts | 35 +-- packages/provider-acp/src/server/adapter.ts | 2 - .../src/server/ProviderAdapter.ts | 1 - .../provider-cursor/src/server/adapter.ts | 3 - packages/provider-muse/src/server/adapter.ts | 1 - .../src/server/adapter.test.ts | 245 ++++++++---------- .../provider-opencode/src/server/adapter.ts | 1 - .../src/server/v2/adapter.ts | 37 +-- packages/provider-pi/src/server/adapter.ts | 3 +- 12 files changed, 126 insertions(+), 215 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index a62977eb17fb2..105565f79ef2f 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -7292,13 +7292,9 @@ describe("AcpAdapterV2", () => { const event = yield* Queue.take(events); if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) break; } - const snapshotBeforeRollback = yield* runtime.readThreadSnapshot({ providerThread }); - // Turns reach orchestration as events; the session keeps no record of them. - assert.deepEqual(snapshotBeforeRollback.providerTurns, []); - const rolledBack = yield* runtime.rollbackThread({ providerThread: { ...providerThread, appThreadId: rollbackThreadId }, - providerThreadTurns: snapshotBeforeRollback.providerTurns, + providerThreadTurns: [], target: { type: "thread_start", checkpointId: CheckpointId.make("checkpoint-acp-rollback-session"), @@ -7306,7 +7302,6 @@ describe("AcpAdapterV2", () => { }, }); assert.isString(rolledBack.providerThread.nativeThreadRef?.nativeId); - assert.deepEqual(rolledBack.providerTurns, []); assert.equal( runtimeInputs[1]?.processEnvironment?.T3_ACP_MCP_AUTHORIZATION, "Bearer rollback-target-token", @@ -7330,7 +7325,6 @@ describe("AcpAdapterV2", () => { const snapshotAfterRollback = yield* runtime.readThreadSnapshot({ providerThread: rolledBack.providerThread, }); - assert.deepEqual(snapshotAfterRollback.providerTurns, []); assert.deepEqual(snapshotAfterRollback.messages, []); const sessionEventsBeforeSecondTurn = sessionEventCount; diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index c93b840f44e4d..d3c017a54679a 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -15145,7 +15145,6 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }), handoffIds: rollbackInput.providerThread.handoffIds, }, - providerTurns: [], messages: [], runtimeRequests: [], }; @@ -15167,7 +15166,6 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( lastRunOrdinal: rollbackInput.target.appRunOrdinal, updatedAt: now, }, - providerTurns: [], messages: [], runtimeRequests: [], }; diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 1c38aaebffc80..a35767f62eecf 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -9179,7 +9179,6 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( nativeConversationHeadRef: threadInput.providerThread.nativeConversationHeadRef, updatedAt: codexTimestamp(response.thread.updatedAt), }, - providerTurns: [], messages: [], runtimeRequests: [], providerPayload: response.thread, @@ -9212,7 +9211,6 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( nativeConversationHeadRef, status: "idle" as const, }, - providerTurns: [], messages: [], runtimeRequests: [], }; @@ -9255,7 +9253,6 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( status: "idle" as const, updatedAt: codexTimestamp(response.thread.updatedAt), }, - providerTurns: [], messages: [], runtimeRequests: [], providerPayload: response.thread, diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index 0e4bc5d088048..91a00fd60742f 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -6873,7 +6873,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }), ); - it.effect("drops the turns a rollback cut from the snapshot it returns", () => + it.effect("reverts OpenCode at the prompt of the first turn a rollback cuts", () => Effect.gen(function* () { const kept = `msg_t3_turn_${SESSION}:attempt:opencode2-adapter`; const dropped = `msg_t3_turn_${SESSION}:attempt:opencode2-adapter:2`; @@ -6925,7 +6925,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { yield* runtime.startTurn(secondTurn(thread)); yield* Deferred.await(bothEnded); const [first, second] = turns; - const snapshot = yield* runtime.rollbackThread({ + yield* runtime.rollbackThread({ providerThread: thread, target: { type: "provider_turn", @@ -6935,10 +6935,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }, providerThreadTurns: [first!, second!], }); - assert.deepEqual( - snapshot.providerTurns.map((turn) => turn.id), - [first!.id], - ); }), ); @@ -6994,10 +6990,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { ); it.effect.each([ - [ - "keeps the recorded turns before the target when rolling back a session not loaded yet", - false, - ], + ["reverts a session not loaded yet at the first recorded turn after the target", false], ] as const)("%s", ([, running]) => Effect.gen(function* () { const first = `msg_t3_turn_${SESSION}:attempt:first`; @@ -7069,10 +7062,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { ); } else { assert.isTrue(Exit.isSuccess(rollback)); - assert.deepEqual( - Exit.isSuccess(rollback) ? rollback.value.providerTurns.map((turn) => turn.id) : [], - [kept.id], - ); } }), ); @@ -7360,7 +7349,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { ], "msg_external", ); - const snapshot = yield* runtime.rollbackThread({ + yield* runtime.rollbackThread({ providerThread: thread, target: { type: "provider_turn", @@ -7370,10 +7359,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }, providerThreadTurns: [first, second], }); - assert.deepEqual( - snapshot.providerTurns.map((turn) => turn.id), - [first.id], - ); }), ); @@ -7872,7 +7857,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { yield* runtime.startTurn(continuationTurn(thread, offers[1]!)); yield* Deferred.await(bothEnded); const [first, continuation] = turns; - const snapshot = yield* runtime.rollbackThread({ + yield* runtime.rollbackThread({ providerThread: thread, target: { type: "provider_turn", @@ -7882,10 +7867,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }, providerThreadTurns: [first!, continuation!], }); - assert.deepEqual( - snapshot.providerTurns.map((turn) => turn.id), - [first!.id], - ); }), ); @@ -7994,7 +7975,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { yield* runtime.startTurn(continuationTurn(thread, yield* Deferred.await(offered))); yield* Deferred.await(bothEnded); const [first, continuation] = turns; - const snapshot = yield* runtime.rollbackThread({ + yield* runtime.rollbackThread({ providerThread: thread, target: { type: "provider_turn", @@ -8004,10 +7985,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }, providerThreadTurns: [first!, continuation!], }); - assert.deepEqual( - snapshot.providerTurns.map((turn) => turn.id), - [first!.id], - ); }), ); diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 9fb64218c5b29..d9410e4754f35 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -10696,7 +10696,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( updatedAt: now, }, // Imports read only the transcript; turns reach orchestration as events. - providerTurns: [], messages, reasoningMessageIds: [...state.reasoningIds], runtimeRequests: [], @@ -10755,7 +10754,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( status: "idle" as const, updatedAt: now, }, - providerTurns: [], messages: [], runtimeRequests: [], }; diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.ts index 049198f9a6cb4..4d008a7233900 100644 --- a/packages/provider-core/src/server/ProviderAdapter.ts +++ b/packages/provider-core/src/server/ProviderAdapter.ts @@ -648,7 +648,6 @@ export interface ProviderAdapterV2RuntimeRequestResponseInput { export interface ProviderAdapterV2ThreadSnapshot { readonly providerThread: OrchestrationV2ProviderThread; - readonly providerTurns: ReadonlyArray; readonly messages: ReadonlyArray; /** Ids in `messages` that hold the agent's reasoning, not its reply. */ readonly reasoningMessageIds?: ReadonlyArray; diff --git a/packages/provider-cursor/src/server/adapter.ts b/packages/provider-cursor/src/server/adapter.ts index 426bc8b60a264..c758e46a7b3dc 100644 --- a/packages/provider-cursor/src/server/adapter.ts +++ b/packages/provider-cursor/src/server/adapter.ts @@ -3548,7 +3548,6 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( status: "idle" as const, updatedAt: now, }, - providerTurns: [], messages: projectedMessages, runtimeRequests: [], providerPayload: { @@ -3629,7 +3628,6 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( status: "idle" as const, updatedAt: now, }, - providerTurns: [], messages: [], runtimeRequests: [], }; @@ -3659,7 +3657,6 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( status: "idle" as const, updatedAt: now, }, - providerTurns: [], messages: [], runtimeRequests: [], }; diff --git a/packages/provider-muse/src/server/adapter.ts b/packages/provider-muse/src/server/adapter.ts index 66c1fd1a505ff..825e793876571 100644 --- a/packages/provider-muse/src/server/adapter.ts +++ b/packages/provider-muse/src/server/adapter.ts @@ -2245,7 +2245,6 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( const now = yield* DateTime.now; return { providerThread: current, - providerTurns: [], messages: items.flatMap((item): OrchestrationV2ConversationMessage[] => item.kind === "agentMessage" || item.kind === "userMessage" ? [ diff --git a/packages/provider-opencode/src/server/adapter.test.ts b/packages/provider-opencode/src/server/adapter.test.ts index 3cd83ac152f8c..5e0b34c029111 100644 --- a/packages/provider-opencode/src/server/adapter.test.ts +++ b/packages/provider-opencode/src/server/adapter.test.ts @@ -151,6 +151,41 @@ function providerTurn(input: { }; } +// Turns reach orchestration only as `provider_turn.updated` events, so tests read them there. +function trackProviderTurns( + runtime: Pick, +) { + const turns = new Map(); + const events = runtime.events.pipe( + Stream.tap((event) => + Effect.sync(() => { + if (event.type === "provider_turn.updated") { + turns.set(event.providerTurn.id, event.providerTurn); + } + }), + ), + ); + const awaitTurns = Effect.fnUntraced(function* ( + predicate: (turns: ReadonlyArray) => boolean, + ) { + const seen = () => [...turns.values()]; + if (!predicate(seen())) { + yield* events.pipe( + Stream.takeUntil(() => predicate(seen())), + Stream.runDrain, + ); + } + return seen(); + }); + const awaitLatestTurn = ( + predicate: (turn: OrchestrationV2ProviderTurn) => boolean = () => true, + ) => + awaitTurns((seen) => seen.length > 0 && predicate(seen.at(-1)!)).pipe( + Effect.map((seen) => seen.at(-1)!), + ); + return { events, awaitTurns, awaitLatestTurn }; +} + const makeOpenCodeRuntimeHarness = Effect.fn("makeOpenCodeRuntimeHarness")(function* ( suffix: string, nativeSessionId: string, @@ -260,6 +295,7 @@ const makeOpenCodeRuntimeHarness = Effect.fn("makeOpenCodeRuntimeHarness")(funct runtimePolicy: turnPolicy, }); return { + ...trackProviderTurns(runtime), nativeSessionId, now, policy, @@ -466,7 +502,7 @@ describe("OpenCodeAdapterV2", () => { yield* Effect.promise(() => nativeEvents.push({ type: "session.idle", properties: { sessionID: sessionId } }), ); - yield* harness.runtime.events.pipe( + yield* harness.events.pipe( Stream.filter((event) => event.type === "turn.terminal"), Stream.take(1), Stream.runDrain, @@ -538,10 +574,7 @@ describe("OpenCodeAdapterV2", () => { ); const start = yield* harness.startTurn().pipe(Effect.forkScoped); yield* Effect.promise(() => catalogStarted.promise); - const snapshot = yield* harness.runtime.readThreadSnapshot({ - providerThread: harness.providerThread, - }); - const activeTurn = snapshot.providerTurns.at(-1)!; + const activeTurn = yield* harness.awaitLatestTurn(); const steer = (message: string) => harness.runtime .steerTurn({ @@ -616,7 +649,7 @@ describe("OpenCodeAdapterV2", () => { }, }); yield* harness.startTurn(); - const received = yield* harness.runtime.events.pipe( + const received = yield* harness.events.pipe( Stream.takeUntil((event) => event.type === "turn.terminal"), Stream.runCollect, Effect.forkScoped, @@ -648,7 +681,7 @@ describe("OpenCodeAdapterV2", () => { }, }); yield* harness.startTurn(); - const received = yield* harness.runtime.events.pipe( + const received = yield* harness.events.pipe( Stream.takeUntil((event) => event.type === "turn.terminal"), Stream.runCollect, Effect.forkScoped, @@ -864,7 +897,7 @@ describe("OpenCodeAdapterV2", () => { }, }); yield* harness.startTurn(); - const received = yield* harness.runtime.events.pipe( + const received = yield* harness.events.pipe( Stream.takeUntil((event) => event.type === "turn.terminal"), Stream.runCollect, Effect.forkScoped, @@ -999,7 +1032,7 @@ describe("OpenCodeAdapterV2", () => { }, }); yield* harness.startTurn(); - const received = yield* harness.runtime.events.pipe( + const received = yield* harness.events.pipe( Stream.takeUntil((event) => event.type === "turn.terminal"), Stream.runCollect, Effect.forkScoped, @@ -1107,7 +1140,7 @@ describe("OpenCodeAdapterV2", () => { contextUsage: { usedTokens: 150_000, maxTokens: 160_000 }, }, }); - const received = yield* harness.runtime.events.pipe( + const received = yield* harness.events.pipe( Stream.takeUntil((event) => event.type === "turn.terminal"), Stream.runCollect, Effect.forkScoped, @@ -1194,7 +1227,7 @@ describe("OpenCodeAdapterV2", () => { }, }, }); - const received = yield* harness.runtime.events.pipe( + const received = yield* harness.events.pipe( Stream.takeUntil((event) => event.type === "turn.terminal"), Stream.runCollect, Effect.forkScoped, @@ -1236,7 +1269,7 @@ describe("OpenCodeAdapterV2", () => { }, }); yield* harness.startTurn(); - const received = yield* harness.runtime.events.pipe( + const received = yield* harness.events.pipe( Stream.filter( (event) => event.type === "runtime_request.updated" || @@ -1312,7 +1345,7 @@ describe("OpenCodeAdapterV2", () => { }, }); yield* harness.startTurn(); - const received = yield* harness.runtime.events.pipe( + const received = yield* harness.events.pipe( Stream.takeUntil( (event) => event.type === "turn_item.updated" && event.turnItem.type === "compaction", ), @@ -1723,7 +1756,7 @@ describe("OpenCodeAdapterV2", () => { }, }, }); - const awaitTerminal = harness.runtime.events.pipe( + const awaitTerminal = harness.events.pipe( Stream.filter((event) => event.type === "turn.terminal"), Stream.take(1), Stream.runDrain, @@ -1736,14 +1769,9 @@ describe("OpenCodeAdapterV2", () => { yield* awaitTerminal; } assert.equal(offers.length, 0, "foreground admission must not offer a continuation"); - const before = yield* harness.runtime.readThreadSnapshot({ - providerThread: harness.providerThread, - }); - assert.equal(before.providerTurns.length, 1); - assert.equal( - before.providerTurns[0]?.status, - state === "settled" ? "completed" : "running", - ); + const before = yield* harness.awaitTurns((turns) => turns.length > 0); + assert.equal(before.length, 1); + assert.equal(before[0]?.status, state === "settled" ? "completed" : "running"); // Pinned task.ts injects a synthetic root prompt; prompt.ts saves it before starting its loop. yield* push(user("msg_background_result")); @@ -1906,10 +1934,7 @@ describe("OpenCodeAdapterV2", () => { yield* push(status("idle")); yield* Fiber.join(starting); assert.equal(promptIds.length, 1, "failed waiting foreground cannot submit"); - const snapshot = yield* harness.runtime.readThreadSnapshot({ - providerThread: harness.providerThread, - }); - assert.equal(snapshot.providerTurns.at(-1)?.status, "failed"); + yield* harness.awaitLatestTurn((turn) => turn.status === "failed"); return; } if (end === "catalog-live" || end === "catalog-replay") { @@ -1939,15 +1964,13 @@ describe("OpenCodeAdapterV2", () => { yield* TestClock.adjust("10 seconds"); if (idle !== null) yield* Fiber.join(idle); else yield* Fiber.join(starting); - const events = yield* harness.runtime.events.pipe( + const events = yield* harness.events.pipe( Stream.takeUntil((event) => event.type === "turn.terminal"), Stream.runCollect, ); assert.equal(events.find((event) => event.type === "turn.terminal")?.status, "completed"); - const snapshot = yield* harness.runtime.readThreadSnapshot({ - providerThread: harness.providerThread, - }); - assert.equal(snapshot.providerTurns.at(-1)?.status, "completed"); + const turn = yield* harness.awaitLatestTurn((turn) => turn.completedAt !== null); + assert.equal(turn.status, "completed"); return; } assert.equal(offers.length, state === "settled" ? 1 : 0, "only a settled root needs a run"); @@ -1955,10 +1978,8 @@ describe("OpenCodeAdapterV2", () => { yield* offers[0]!.onRunEndedWithoutStarting!(); yield* harness.startTurn("", undefined, undefined, false, "no-wake", {}); yield* awaitTerminal; - const snapshot = yield* harness.runtime.readThreadSnapshot({ - providerThread: harness.providerThread, - }); - assert.equal(snapshot.providerTurns.at(-1)?.status, "completed"); + const turn = yield* harness.awaitLatestTurn((turn) => turn.completedAt !== null); + assert.equal(turn.status, "completed"); assert.equal(promptIds.length, 1); return; } @@ -2122,7 +2143,7 @@ describe("OpenCodeAdapterV2", () => { }); assert.equal(beforeAdmission.runtimeRequests.length, 0); yield* harness.startTurn("", undefined, undefined, false, "held", {}); - const events = yield* harness.runtime.events.pipe( + const events = yield* harness.events.pipe( Stream.takeUntil( (event) => event.type === "runtime_request.updated" && @@ -2215,7 +2236,7 @@ describe("OpenCodeAdapterV2", () => { assert.isTrue(Exit.isFailure(replacement), "uncertain native work requires reconnect"); assert.equal(promptIds.length, 1, "replacement cannot join the surviving native loop"); assert.deepEqual(aborted, [root, "ses_descendant"]); - const events = yield* harness.runtime.events.pipe( + const events = yield* harness.events.pipe( Stream.takeUntil( (event) => event.type === "provider_session.updated" && @@ -2269,19 +2290,13 @@ describe("OpenCodeAdapterV2", () => { yield* Effect.promise(() => routeStarted.promise); yield* TestClock.adjust("10 seconds"); assert.isTrue(Exit.isFailure(yield* Fiber.join(starting))); - const snapshot = yield* harness.runtime.readThreadSnapshot({ - providerThread: harness.providerThread, - }); - assert.equal( - snapshot.providerTurns.at(-1)?.status, - "failed", - "the installed turn must be finalized", - ); + // The installed turn must be finalized. + yield* harness.awaitLatestTurn((turn) => turn.status === "failed"); assert.deepEqual(aborted, [root, "ses_descendant"]); const replacement = yield* harness.startTurn("replacement").pipe(Effect.exit); assert.isTrue(Exit.isFailure(replacement), "incomplete replay requires reconnect"); assert.equal(promptIds.length, 1, "failed replay cannot submit a foreground prompt"); - const events = yield* harness.runtime.events.pipe( + const events = yield* harness.events.pipe( Stream.takeUntil((event) => event.type === "turn.terminal"), Stream.runCollect, ); @@ -2363,7 +2378,7 @@ describe("OpenCodeAdapterV2", () => { if (end === "owned-exit" || end === "failed-stream") { if (end === "owned-exit") yield* Deferred.succeed(nativeExit, 1); else nativeEvents.close(); - yield* harness.runtime.events.pipe( + yield* harness.events.pipe( Stream.filter( (event) => event.type === "provider_session.updated" && @@ -2451,10 +2466,8 @@ describe("OpenCodeAdapterV2", () => { [], "old callbacks cannot abort the installed runtime", ); - const replacementSnapshot = yield* replacement.runtime.readThreadSnapshot({ - providerThread: resumed, - }); - assert.equal(replacementSnapshot.providerTurns.at(-1)?.status, "running"); + const replacementTurn = yield* replacement.awaitLatestTurn(); + assert.equal(replacementTurn.status, "running"); return; } const foreground = @@ -2487,12 +2500,10 @@ describe("OpenCodeAdapterV2", () => { if (end === "foreground-stop" || end === "foreground-eof") { if (end === "foreground-eof") nativeEvents.close(); else { - const snapshot = yield* harness.runtime.readThreadSnapshot({ - providerThread: harness.providerThread, - }); + const turn = yield* harness.awaitLatestTurn((turn) => turn.status === "running"); yield* harness.runtime.interruptTurn({ providerThread: harness.providerThread, - providerTurnId: snapshot.providerTurns.at(-1)!.id, + providerTurnId: turn.id, requestRuntimeRestart: true, }); } @@ -2545,14 +2556,8 @@ describe("OpenCodeAdapterV2", () => { assert.equal(promptIds.length, 2); if (end === "foreground-second-saved") { yield* push({ type: "session.idle", properties: { sessionID: root } }); - const snapshot = yield* harness.runtime.readThreadSnapshot({ - providerThread: harness.providerThread, - }); - assert.equal( - snapshot.providerTurns.at(-1)?.status, - "running", - "an earlier reply cannot admit the foreground prompt", - ); + // An earlier reply cannot admit the foreground prompt. + yield* harness.awaitLatestTurn((turn) => turn.status === "running"); } return; } @@ -2584,7 +2589,7 @@ describe("OpenCodeAdapterV2", () => { if (end === "sequential") yield* secondResult; assert.equal(offers.length, 2, "completed sequential wakes each offer once"); yield* harness.startTurn("", undefined, undefined, false, "wake-two", {}); - const events = yield* harness.runtime.events.pipe( + const events = yield* harness.events.pipe( Stream.takeUntil((event) => event.type === "turn.terminal"), Stream.runCollect, ); @@ -2599,11 +2604,11 @@ describe("OpenCodeAdapterV2", () => { ), ); assert.equal(promptIds.length, 1, "continuations never submit another prompt"); - const snapshot = yield* harness.runtime.readThreadSnapshot({ - providerThread: harness.providerThread, - }); + const turns = yield* harness.awaitTurns( + (turns) => turns.length === 3 && turns.every((turn) => turn.completedAt !== null), + ); assert.deepEqual( - snapshot.providerTurns.map((turn) => turn.status), + turns.map((turn) => turn.status), ["completed", "completed", "completed"], ); return; @@ -2616,10 +2621,7 @@ describe("OpenCodeAdapterV2", () => { if (end === "foreground-buffered" || end === "foreground-buffered-error") yield* harness.startTurn("follow up", undefined, undefined, false, "next"); assert.equal(promptIds.length, 2, "the foreground prompt is submitted"); - const snapshot = yield* harness.runtime.readThreadSnapshot({ - providerThread: harness.providerThread, - }); - assert.equal(snapshot.providerTurns.at(-1)?.status, "running"); + yield* harness.awaitLatestTurn((turn) => turn.status === "running"); yield* push(user(promptIds[1]!)); yield* push({ type: "message.part.updated", @@ -2656,7 +2658,7 @@ describe("OpenCodeAdapterV2", () => { end === "foreground-buffered" || end === "foreground-buffered-error" ) { - const events = yield* harness.runtime.events.pipe( + const events = yield* harness.events.pipe( Stream.takeUntil((event) => event.type === "turn.terminal"), Stream.runCollect, ); @@ -2785,7 +2787,7 @@ describe("OpenCodeAdapterV2", () => { return yield* Effect.die("OpenCode runtime must expose hasPendingBackgroundWork."); } yield* harness.startTurn(); - const received = yield* harness.runtime.events.pipe( + const received = yield* harness.events.pipe( Stream.takeUntil( (event) => event.type === "turn_item.updated" && @@ -2942,7 +2944,7 @@ describe("OpenCodeAdapterV2", () => { }, }); yield* harness.startTurn(); - const childTurns = yield* harness.runtime.events.pipe( + const childTurns = yield* harness.events.pipe( Stream.filter( (event) => event.type === "provider_turn.updated" && @@ -3055,7 +3057,7 @@ describe("OpenCodeAdapterV2", () => { }, }); yield* harness.startTurn(); - const received = yield* harness.runtime.events.pipe( + const received = yield* harness.events.pipe( Stream.takeUntil( (event) => event.type === "turn_item.updated" && event.turnItem.type === "compaction", ), @@ -3174,7 +3176,7 @@ describe("OpenCodeAdapterV2", () => { }, }); yield* harness.startTurn(); - const received = yield* harness.runtime.events.pipe( + const received = yield* harness.events.pipe( Stream.takeUntil((event) => event.type === "plan.updated"), Stream.runCollect, Effect.forkScoped, @@ -3241,7 +3243,7 @@ describe("OpenCodeAdapterV2", () => { }, }); yield* harness.startTurn(); - const received = yield* harness.runtime.events.pipe( + const received = yield* harness.events.pipe( Stream.takeUntil( (event) => event.type === "turn_item.updated" && event.turnItem.type === "compaction", ), @@ -3502,7 +3504,7 @@ describe("OpenCodeAdapterV2", () => { }), ); yield* Fiber.join(start); - const terminal = yield* harness.runtime.events.pipe( + const terminal = yield* harness.events.pipe( Stream.filter((event) => event.type === "turn.terminal"), Stream.take(1), Stream.runCollect, @@ -3564,7 +3566,7 @@ describe("OpenCodeAdapterV2", () => { }, }); yield* harness.startTurn("/compact"); - const events = yield* harness.runtime.events.pipe( + const events = yield* harness.events.pipe( Stream.takeUntil((event) => event.type === "turn.terminal"), Stream.runCollect, ); @@ -3618,7 +3620,7 @@ describe("OpenCodeAdapterV2", () => { id: ProviderThreadId.make("provider-thread:opencode-test:forked-run-row"), }; yield* harness.startTurn("/compact", forkedRow); - const terminal = yield* harness.runtime.events.pipe( + const terminal = yield* harness.events.pipe( Stream.filter( (event): event is Extract => event.type === "turn.terminal", @@ -3739,14 +3741,12 @@ describe("OpenCodeAdapterV2", () => { { options: [{ id: "variant", value: "high" }], interactionMode: "plan" }, ); yield* harness.startTurn(); - const snapshot = yield* harness.runtime.readThreadSnapshot({ - providerThread: harness.providerThread, - }); + const turn = yield* harness.awaitLatestTurn(); yield* harness.runtime.steerTurn({ threadId: harness.threadId, runId: harness.runId, providerThread: harness.providerThread, - providerTurnId: snapshot.providerTurns.at(-1)!.id, + providerTurnId: turn.id, message: { messageId: MessageId.make("message-opencode-steer-agent"), text: "also cover the README", @@ -3865,6 +3865,7 @@ describe("OpenCodeAdapterV2", () => { modelSelection, runtimePolicy: policy, }); + const tracked = trackProviderTurns(runtime); const providerThread = yield* runtime.ensureThread({ threadId, modelSelection, @@ -3972,9 +3973,8 @@ describe("OpenCodeAdapterV2", () => { yield* Effect.promise(() => statusCalled.promise); - const snapshot = yield* runtime.readThreadSnapshot({ providerThread }); - assert.equal(snapshot.providerTurns.at(-1)?.status, "running"); - const activeTurn = snapshot.providerTurns.at(-1)!; + const activeTurn = yield* tracked.awaitLatestTurn(); + assert.equal(activeTurn.status, "running"); const steer = yield* runtime .steerTurn({ threadId, @@ -4080,8 +4080,8 @@ describe("OpenCodeAdapterV2", () => { properties: { sessionID: "native-opencode-race", status: { type: "idle" } }, }), ); - const interrupted = yield* runtime.readThreadSnapshot({ providerThread }); - assert.equal(interrupted.providerTurns.at(-1)?.status, "interrupted"); + const interrupted = yield* tracked.awaitLatestTurn((turn) => turn.completedAt !== null); + assert.equal(interrupted.status, "interrupted"); }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))), ); @@ -4125,10 +4125,7 @@ describe("OpenCodeAdapterV2", () => { }, ); yield* harness.startTurn(); - const snapshot = yield* harness.runtime.readThreadSnapshot({ - providerThread: harness.providerThread, - }); - const turn = snapshot.providerTurns.at(-1)!; + const turn = yield* harness.awaitLatestTurn(); const steer = yield* harness.runtime .steerTurn({ threadId: harness.threadId, @@ -4166,10 +4163,8 @@ describe("OpenCodeAdapterV2", () => { properties: { sessionID: "root", status: { type: "idle" } }, }), ); - const stopped = yield* harness.runtime.readThreadSnapshot({ - providerThread: harness.providerThread, - }); - assert.equal(stopped.providerTurns.at(-1)?.status, "interrupted"); + const stopped = yield* harness.awaitLatestTurn((turn) => turn.completedAt !== null); + assert.equal(stopped.status, "interrupted"); }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))), ); @@ -4252,10 +4247,8 @@ describe("OpenCodeAdapterV2", () => { }, }), ); - const running = yield* harness.runtime.readThreadSnapshot({ - providerThread: harness.providerThread, - }); - yield* harness.runtime.events.pipe( + const running = yield* harness.awaitLatestTurn(); + yield* harness.events.pipe( Stream.tap((event) => event.type === "turn.terminal" ? Deferred.succeed(terminal, undefined) : Effect.void, ), @@ -4267,7 +4260,7 @@ describe("OpenCodeAdapterV2", () => { threadId: harness.threadId, runId: harness.runId, providerThread: harness.providerThread, - providerTurnId: running.providerTurns.at(-1)!.id, + providerTurnId: running.id, message: { messageId: MessageId.make(`message-steer-rejected-${idleTiming}`), text: "also cover the README", @@ -4285,17 +4278,13 @@ describe("OpenCodeAdapterV2", () => { Deferred.await(terminal).pipe(Effect.as("completed")), ); assert.equal(outcome, "rechecked"); - const active = yield* harness.runtime.readThreadSnapshot({ - providerThread: harness.providerThread, - }); - assert.equal(active.providerTurns.at(-1)?.status, "running"); + const active = yield* harness.awaitLatestTurn(); + assert.equal(active.status, "running"); yield* Effect.promise(() => nativeEvents.push(idle)); } if (idleTiming === "after-refused-connection") { - const active = yield* harness.runtime.readThreadSnapshot({ - providerThread: harness.providerThread, - }); - assert.equal(active.providerTurns.at(-1)?.status, "running"); + const active = yield* harness.awaitLatestTurn(); + assert.equal(active.status, "running"); yield* Effect.promise(() => nativeEvents.push(idle)); } yield* Deferred.await(terminal); @@ -4303,10 +4292,8 @@ describe("OpenCodeAdapterV2", () => { assert.equal(statusCalls, idleTiming === "idle-during-status" ? 2 : 1); } - const settled = yield* harness.runtime.readThreadSnapshot({ - providerThread: harness.providerThread, - }); - assert.equal(settled.providerTurns.at(-1)?.status, "completed"); + const settled = yield* harness.awaitLatestTurn((turn) => turn.completedAt !== null); + assert.equal(settled.status, "completed"); }).pipe( Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)), Effect.scoped, @@ -4354,10 +4341,8 @@ describe("OpenCodeAdapterV2", () => { }), ); yield* userMessage(promptIds[0]); - const running = yield* harness.runtime.readThreadSnapshot({ - providerThread: harness.providerThread, - }); - const received = yield* harness.runtime.events.pipe( + const running = yield* harness.awaitLatestTurn(); + const received = yield* harness.events.pipe( Stream.takeUntil((event) => event.type === "turn.terminal"), Stream.runCollect, Effect.forkScoped, @@ -4366,7 +4351,7 @@ describe("OpenCodeAdapterV2", () => { threadId: harness.threadId, runId: harness.runId, providerThread: harness.providerThread, - providerTurnId: running.providerTurns.at(-1)!.id, + providerTurnId: running.id, message: { messageId: MessageId.make("message-steer-reply-lost"), text: "also cover the README", @@ -4510,12 +4495,13 @@ describe("OpenCodeAdapterV2", () => { modelSelection, runtimePolicy: policy, }); + const tracked = trackProviderTurns(runtime); const providerThread = yield* runtime.ensureThread({ threadId, modelSelection, runtimePolicy: policy, }); - const terminalEvents = yield* runtime.events.pipe( + const terminalEvents = yield* tracked.events.pipe( Stream.takeUntil((event) => event.type === "turn.terminal"), Stream.runCollect, Effect.forkScoped, @@ -4566,8 +4552,7 @@ describe("OpenCodeAdapterV2", () => { .pipe(Effect.forkScoped); yield* Effect.promise(() => promptStarted.promise); - const running = yield* runtime.readThreadSnapshot({ providerThread }); - const activeTurn = running.providerTurns.at(-1)!; + const activeTurn = yield* tracked.awaitLatestTurn(); const interrupt = yield* runtime .interruptTurn({ providerThread, providerTurnId: activeTurn.id }) .pipe(Effect.forkScoped); @@ -4635,10 +4620,7 @@ describe("OpenCodeAdapterV2", () => { mcp: { add: async () => ({ data: true }) }, }); yield* harness.startTurn(); - const snapshot = yield* harness.runtime.readThreadSnapshot({ - providerThread: harness.providerThread, - }); - const turn = snapshot.providerTurns.at(-1)!; + const turn = yield* harness.awaitLatestTurn(); const interrupt = yield* harness.runtime .interruptTurn({ providerThread: harness.providerThread, providerTurnId: turn.id }) .pipe(Effect.flip, Effect.forkScoped); @@ -4679,10 +4661,7 @@ describe("OpenCodeAdapterV2", () => { }, ); yield* harness.startTurn(); - const terminalEvents = yield* harness.runtime.events.pipe( - Stream.runCollect, - Effect.forkScoped, - ); + const terminalEvents = yield* harness.events.pipe(Stream.runCollect, Effect.forkScoped); nativeEvents.close(); const received = Array.from(yield* Fiber.join(terminalEvents)); @@ -4736,7 +4715,7 @@ describe("OpenCodeAdapterV2", () => { }, }, ).pipe(Effect.provideService(Clock.Clock, blockingClock)); - const events = yield* harness.runtime.events.pipe(Stream.runCollect, Effect.forkScoped); + const events = yield* harness.events.pipe(Stream.runCollect, Effect.forkScoped); const start = yield* harness.startTurn("/compact").pipe(Effect.forkScoped); yield* Effect.promise(() => summarizeStarted.promise); blockNextClockRead = true; @@ -4809,7 +4788,7 @@ describe("OpenCodeAdapterV2", () => { .pipe(Effect.provideService(Clock.Clock, blockingClock), Effect.exit, Effect.forkScoped); yield* Deferred.await(startClockRead); - const events = yield* harness.runtime.events.pipe(Stream.runCollect, Effect.forkScoped); + const events = yield* harness.events.pipe(Stream.runCollect, Effect.forkScoped); nativeEvents.close(); yield* Fiber.join(events); yield* Deferred.succeed(releaseStartClockRead, undefined); diff --git a/packages/provider-opencode/src/server/adapter.ts b/packages/provider-opencode/src/server/adapter.ts index 6398e8ec74800..39376b09c0b59 100644 --- a/packages/provider-opencode/src/server/adapter.ts +++ b/packages/provider-opencode/src/server/adapter.ts @@ -3496,7 +3496,6 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function status: "idle" as const, updatedAt: snapshotNow, }, - providerTurns: state === undefined ? [] : [...state.providerTurns.values()], messages, runtimeRequests: state === undefined ? [] : [...state.runtimeRequests.values()], providerPayload: nativeMessages, diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index 9cee26a3fb20d..c1426bb234735 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -349,7 +349,6 @@ interface ThreadState { goalRevision: number; goalFresh: boolean; goalRefreshing: boolean; - readonly providerTurns: Map; active: ActiveTurn | undefined; model: ModelRef | undefined; /** Locally ended but possibly live; consume its next execution end without settling a new turn. */ @@ -934,7 +933,6 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr goalRevision: 0, goalFresh: false, goalRefreshing: false, - providerTurns: new Map(), active: undefined, model: undefined, unsettled: false, @@ -1635,20 +1633,14 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr return ids.length === 0 ? {} : { retainedRuntimeRequestIds: ids }; }; - const emitProviderTurn = ( - state: ThreadState, - turn: ActiveTurn, - providerTurn: OrchestrationV2ProviderTurn, - ) => { - state.providerTurns.set(String(providerTurn.id), providerTurn); - return emit({ + const emitProviderTurn = (turn: ActiveTurn, providerTurn: OrchestrationV2ProviderTurn) => + emit({ type: "provider_turn.updated", driver, threadId: turn.input.threadId, providerTurn, ...(providerTurn.completedAt === null ? {} : retainedRequestsOf(turn)), }); - }; const makeTurn = ( owner: TurnOwner, @@ -2289,7 +2281,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr completedAt: null, }, }); - yield* emitProviderTurn(child, turn, providerTurn); + yield* emitProviderTurn(turn, providerTurn); const prompt = subagent.prompt; subagent.prompt = undefined; if (prompt !== undefined && prompt.length > 0) { @@ -2401,7 +2393,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr ); const window = windowOf(turn.input.runtimePolicy.cwd, turn.input.modelSelection.model); const lastStep = turn.lastStep; - yield* emitProviderTurn(state, turn, { + yield* emitProviderTurn(turn, { ...turn.providerTurn, status: terminal.status, completedAt, @@ -4321,7 +4313,6 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr ]; }); const lastUser = history.findLast((message) => message.type === "user")?.id; - const state = threads.get(sessionId); return { providerThread: { ...providerThread, @@ -4330,7 +4321,6 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr status: "idle" as const, updatedAt: snapshotAt, }, - providerTurns: state === undefined ? [] : [...state.providerTurns.values()], messages, runtimeRequests: [], }; @@ -4491,7 +4481,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr } state.active = turn; state.sessionScopedBackground = false; - yield* emitProviderTurn(state, turn, providerTurn); + yield* emitProviderTurn(turn, providerTurn); state.providerThread = { ...state.providerThread, status: "active", @@ -5459,22 +5449,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr if (boundary !== null) { yield* rollBackTo(sessionId, SessionMessage.ID.make(boundary)); } - const keptOrdinal = target.type === "provider_turn" ? target.providerTurn.ordinal : 0; - const loaded = threads.get(sessionId); - for (const [id, turn] of loaded?.providerTurns ?? []) { - if (turn.ordinal > keptOrdinal) loaded?.providerTurns.delete(id); - } - const snapshot = yield* snapshotOf(providerThread, sessionId); - const kept = new Map( - rollbackInput.providerThreadTurns - .filter( - (turn) => - turn.providerThreadId === providerThread.id && turn.ordinal <= keptOrdinal, - ) - .map((turn) => [turn.id, turn] as const), - ); - for (const turn of snapshot.providerTurns) kept.set(turn.id, turn); - return { ...snapshot, providerTurns: [...kept.values()] }; + return yield* snapshotOf(providerThread, sessionId); }, (effect, rollbackInput) => effect.pipe( diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index e7803bbe9c5ee..ad1fce56f9da8 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -3858,7 +3858,6 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( ); return { providerThread: state.providerThread, - providerTurns: [], messages, runtimeRequests: [], }; @@ -4370,7 +4369,7 @@ function piExtensionDisplayName(extensionPath: string | undefined): string { function piThreadSnapshot( providerThread: OrchestrationV2ProviderThread, ): ProviderAdapter.ProviderAdapterV2ThreadSnapshot { - return { providerThread, providerTurns: [], messages: [], runtimeRequests: [] }; + return { providerThread, messages: [], runtimeRequests: [] }; } function piQuestion( From 58e309e75b8f2fb2ad824a6437bfa920ab5398e9 Mon Sep 17 00:00:00 2001 From: Jex Date: Mon, 23 Nov 2026 14:35:49 +0800 Subject: [PATCH 294/324] fix(acp): deliver appContext on startTurn and steerTurn (#41241) Co-authored-by: Julius Marminge --- .../Adapters/AcpAdapterV2.test.ts | 794 ++++++++++++++++++ packages/provider-acp/src/server/adapter.ts | 272 +++++- 2 files changed, 1048 insertions(+), 18 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 105565f79ef2f..54c1137870e73 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -25,10 +25,12 @@ import { assert, beforeAll, describe, it } from "@effect/vitest"; import { CheckpointId, EnvironmentId, + MessageId, type ModelSelection, ProviderDriverKind, ProviderInstanceId, ProviderSessionId, + RunId, ThreadId, type OrchestrationV2ProviderThread, type OrchestrationV2TurnItem, @@ -12614,6 +12616,798 @@ describe("AcpAdapterV2", () => { ]); }).pipe(Effect.provide(layerTest)), ); + + it.live( + "delivers MCP appContext once per session, skips slash commands, and resends after unsuccessful turns, compaction, or runtime restart", + () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* bundledMockAgentPath; + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let sessionUpdateHandler: Parameters[0] | undefined; + let runtimeCount = 0; + let cancelCalled: Deferred.Deferred | undefined; + const prompts: Array = []; + const queuedResponses: Array< + | { readonly _tag: "immediate"; readonly response: EffectAcpSchema.PromptResponse } + | { + readonly _tag: "gated"; + readonly started: Deferred.Deferred; + readonly gate: Deferred.Deferred; + } + > = []; + const instanceId = ProviderInstanceId.make("acp-test-app-context-lifecycle"); + const threadId = ThreadId.make("thread-acp-app-context-lifecycle"); + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + restartRuntimeAfterInterrupt: true, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + wrapRuntime: (runtime) => { + runtimeCount += 1; + return { + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + sessionUpdateHandler = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + cancel: Effect.suspend(() => + cancelCalled === undefined + ? Effect.void + : Deferred.succeed(cancelCalled, undefined).pipe(Effect.asVoid), + ), + prompt: (payload, promptOptions) => + Effect.gen(function* () { + prompts.push( + payload.prompt + .flatMap((block) => (block.type === "text" ? [block.text] : [])) + .join("\n"), + ); + if (promptOptions?.dispatched) { + yield* Deferred.succeed(promptOptions.dispatched, undefined); + } + const next = queuedResponses.shift(); + if (next === undefined) { + return { stopReason: "end_turn" as const }; + } + if (next._tag === "immediate") { + return next.response; + } + yield* Deferred.succeed(next.started, undefined); + return yield* Deferred.await(next.gate); + }), + }; + }, + }), + }, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-app-context-lifecycle"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const sessionId = providerThread.nativeThreadRef?.nativeId; + if (sessionId == null) return assert.fail("expected native session id"); + let ordinal = 0; + const runTurn = (input: { + readonly text: string; + readonly note: string; + readonly response?: EffectAcpSchema.PromptResponse; + }) => + Effect.gen(function* () { + ordinal += 1; + if (input.response !== undefined) { + queuedResponses.push({ _tag: "immediate", response: input.response }); + } + yield* runtime.startTurn({ + ...makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal, + messageText: input.text, + }), + appContext: [{ key: "mcp_app_item-1", text: input.note }], + }); + const events = Array.from( + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ), + ); + const terminal = events.at(-1); + return { + prompt: prompts.at(-1) ?? "", + status: terminal?.type === "turn.terminal" ? terminal.status : null, + }; + }); + + const tag = (note: string) => `${note}`; + + // An unsuccessful stop reason must not mark appContext delivered. + const refusedTurn = yield* runTurn({ + text: "Refused attempt", + note: "Created Jira issue PROJ-42", + response: { stopReason: "refusal" }, + }); + assert.include(refusedTurn.prompt, tag("Created Jira issue PROJ-42")); + + // Interrupted turns must not mark appContext delivered even if the prompt answers end_turn. + const interruptedStarted = yield* Deferred.make(); + const interruptedGate = yield* Deferred.make(); + cancelCalled = yield* Deferred.make(); + queuedResponses.push({ + _tag: "gated", + started: interruptedStarted, + gate: interruptedGate, + }); + ordinal += 1; + const interruptedOrdinal = ordinal; + yield* runtime.startTurn({ + ...makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal: interruptedOrdinal, + messageText: "Interrupted attempt", + }), + appContext: [{ key: "mcp_app_item-1", text: "Created Jira issue PROJ-42" }], + }); + yield* Deferred.await(interruptedStarted); + assert.include(prompts.at(-1) ?? "", tag("Created Jira issue PROJ-42")); + const interruptFiber = yield* runtime + .interruptTurn({ + providerThread, + providerTurnId: idAllocator.derive.providerTurn({ + driver: ACP_TEST_DRIVER, + nativeTurnId: acpScopedNativeId( + instanceId, + `${sessionId}:turn:${interruptedOrdinal}`, + ), + }), + }) + .pipe(Effect.forkScoped); + yield* Deferred.await(cancelCalled); + yield* Deferred.succeed(interruptedGate, { stopReason: "end_turn" }); + yield* Fiber.join(interruptFiber); + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runDrain, + ); + + // Native slash commands skip appContext injection; the next normal turn sends it. + const slashTurn = yield* runTurn({ + text: " /repro-skill", + note: "Created Jira issue PROJ-42", + }); + assert.equal(slashTurn.status, "completed"); + assert.notInclude(slashTurn.prompt, "external_mcp_app_item-1"); + + const deliveredTurn = yield* runTurn({ + text: "What did the app report?", + note: "Created Jira issue PROJ-42", + }); + assert.equal(deliveredTurn.status, "completed"); + assert.include(deliveredTurn.prompt, tag("Created Jira issue PROJ-42")); + + // Unchanged note is not resent; changed note is sent once. + const unchangedTurn = yield* runTurn({ + text: "Follow up", + note: "Created Jira issue PROJ-42", + }); + assert.notInclude(unchangedTurn.prompt, "external_mcp_app_item-1"); + + const changedTurn = yield* runTurn({ + text: "Updated check", + note: "Updated Jira issue PROJ-43", + }); + assert.include(changedTurn.prompt, tag("Updated Jira issue PROJ-43")); + + const afterChangeTurn = yield* runTurn({ + text: "Second follow up", + note: "Updated Jira issue PROJ-43", + }); + assert.notInclude(afterChangeTurn.prompt, "external_mcp_app_item-1"); + + // Compaction clears delivered appContext so the next turn resends it. + yield* sessionUpdateHandler!({ + sessionId, + update: { + sessionUpdate: "compaction_update", + compactionId: "compact-app-context", + status: "completed", + }, + }); + const postCompactTurn = yield* runTurn({ + text: "After compaction", + note: "Updated Jira issue PROJ-43", + }); + assert.include(postCompactTurn.prompt, tag("Updated Jira issue PROJ-43")); + + const afterPostCompactTurn = yield* runTurn({ + text: "Already resent after compaction", + note: "Updated Jira issue PROJ-43", + }); + assert.notInclude(afterPostCompactTurn.prompt, "external_mcp_app_item-1"); + + // Runtime restart clears delivered appContext even when resuming the same session id. + const restartStarted = yield* Deferred.make(); + const restartGate = yield* Deferred.make(); + cancelCalled = yield* Deferred.make(); + queuedResponses.push({ + _tag: "gated", + started: restartStarted, + gate: restartGate, + }); + ordinal += 1; + const restartOrdinal = ordinal; + yield* runtime.startTurn({ + ...makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal: restartOrdinal, + messageText: "Trigger restart", + }), + appContext: [{ key: "mcp_app_item-1", text: "Updated Jira issue PROJ-43" }], + }); + yield* Deferred.await(restartStarted); + const restartInterruptFiber = yield* runtime + .interruptTurn({ + providerThread, + providerTurnId: idAllocator.derive.providerTurn({ + driver: ACP_TEST_DRIVER, + nativeTurnId: acpScopedNativeId(instanceId, `${sessionId}:turn:${restartOrdinal}`), + }), + requestRuntimeRestart: true, + }) + .pipe(Effect.forkScoped); + yield* Deferred.await(cancelCalled); + yield* Deferred.succeed(restartGate, { stopReason: "cancelled" }); + yield* Fiber.join(restartInterruptFiber); + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runDrain, + ); + + const postRestartTurn = yield* runTurn({ + text: "After runtime restart", + note: "Updated Jira issue PROJ-43", + }); + assert.isAbove(runtimeCount, 1); + assert.include(postRestartTurn.prompt, tag("Updated Jira issue PROJ-43")); + }).pipe(Effect.provide(layerTest)), + ); + + it.live( + "delivers changed appContext on steersWithPrompt and preserves undelivered notes on slash or failed steer", + () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* bundledMockAgentPath; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const prompts: Array = []; + const promptGates: Array<{ + readonly started: Deferred.Deferred; + readonly gate: Deferred.Deferred< + EffectAcpSchema.PromptResponse, + EffectAcpErrors.AcpError + >; + }> = []; + const queueGate = () => + Effect.gen(function* () { + const entry = { + started: yield* Deferred.make(), + gate: yield* Deferred.make< + EffectAcpSchema.PromptResponse, + EffectAcpErrors.AcpError + >(), + }; + promptGates.push(entry); + return entry; + }); + const instanceId = ProviderInstanceId.make("acp-test-app-context-steer-prompt"); + const threadId = ThreadId.make("thread-acp-app-context-steer-prompt"); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + steersWithPrompt: () => true, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + wrapRuntime: (runtime) => ({ + ...runtime, + prompt: (payload, promptOptions) => + Effect.gen(function* () { + prompts.push( + payload.prompt + .flatMap((block) => (block.type === "text" ? [block.text] : [])) + .join("\n"), + ); + if (promptOptions?.dispatched) { + yield* Deferred.succeed(promptOptions.dispatched, undefined); + } + const next = promptGates.shift(); + if (next === undefined) return { stopReason: "end_turn" as const }; + yield* Deferred.succeed(next.started, undefined); + return yield* Deferred.await(next.gate); + }), + }), + }), + }, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make( + "provider-session-acp-app-context-steer-prompt", + ), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const sessionId = providerThread.nativeThreadRef?.nativeId; + if (sessionId == null) return assert.fail("expected native session id"); + const tag = (note: string) => `${note}`; + const providerTurnIdFor = (ordinal: number) => + idAllocator.derive.providerTurn({ + driver: ACP_TEST_DRIVER, + nativeTurnId: acpScopedNativeId(instanceId, `${sessionId}:turn:${ordinal}`), + }); + const steer = (ordinal: number, text: string, note: string) => + runtime.steerTurn({ + threadId, + runId: RunId.make(`run:${threadId}:${ordinal}`), + providerThread, + providerTurnId: providerTurnIdFor(ordinal), + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make(`steer-${ordinal}-${prompts.length}`), + text, + attachments: [], + }, + appContext: [{ key: "mcp_app_item-1", text: note }], + }); + + const turn1Initial = yield* queueGate(); + yield* runtime.startTurn({ + ...makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal: 1, + messageText: "Start turn 1", + }), + appContext: [{ key: "mcp_app_item-1", text: "Note A" }], + }); + yield* Deferred.await(turn1Initial.started); + assert.include(prompts.at(-1) ?? "", tag("Note A")); + + // Unchanged note does not repeat on steer. + const steer1 = yield* queueGate(); + yield* steer(1, "Keep going", "Note A"); + yield* Deferred.await(steer1.started); + assert.notInclude(prompts.at(-1) ?? "", "external_mcp_app_item-1"); + yield* Deferred.succeed(turn1Initial.gate, { stopReason: "end_turn" }); + + // Slash steer skips appContext so the next normal steer carries the changed note. + const steerSlash = yield* queueGate(); + yield* steer(1, "/status", "Note B"); + yield* Deferred.await(steerSlash.started); + assert.notInclude(prompts.at(-1) ?? "", "external_mcp_app_item-1"); + yield* Deferred.succeed(steer1.gate, { stopReason: "end_turn" }); + + const steerChanged = yield* queueGate(); + yield* steer(1, "Use updated note", "Note B"); + yield* Deferred.await(steerChanged.started); + assert.include(prompts.at(-1) ?? "", tag("Note B")); + yield* Deferred.succeed(steerSlash.gate, { stopReason: "end_turn" }); + + // Second steer with the same note does not resend it. + const steerSame = yield* queueGate(); + yield* steer(1, "One more detail", "Note B"); + yield* Deferred.await(steerSame.started); + assert.notInclude(prompts.at(-1) ?? "", "external_mcp_app_item-1"); + yield* Deferred.succeed(steerChanged.gate, { stopReason: "end_turn" }); + yield* Deferred.succeed(steerSame.gate, { stopReason: "end_turn" }); + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runDrain, + ); + + // Turn 2 inherits delivered Note B; a failed prompt steer with Note C does not mark Note C delivered. + const turn2Initial = yield* queueGate(); + yield* runtime.startTurn({ + ...makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal: 2, + messageText: "Start turn 2", + }), + appContext: [{ key: "mcp_app_item-1", text: "Note B" }], + }); + yield* Deferred.await(turn2Initial.started); + assert.notInclude(prompts.at(-1) ?? "", "external_mcp_app_item-1"); + + const steerFailed = yield* queueGate(); + yield* steer(2, "Try Note C", "Note C"); + yield* Deferred.await(steerFailed.started); + assert.include(prompts.at(-1) ?? "", tag("Note C")); + yield* Deferred.succeed(turn2Initial.gate, { stopReason: "end_turn" }); + yield* Deferred.fail( + steerFailed.gate, + new EffectAcpErrors.AcpRequestError({ + code: -32603, + errorMessage: "Steer prompt rejected", + method: "session/prompt", + }), + ); + const turn2Events = Array.from( + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ), + ); + const turn2Terminal = turn2Events.at(-1); + assert.equal( + turn2Terminal?.type === "turn.terminal" ? turn2Terminal.status : null, + "failed", + ); + + // Turn 3 must resend Note C because the failed steer did not deliver it. + yield* runtime.startTurn({ + ...makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal: 3, + messageText: "Start turn 3", + }), + appContext: [{ key: "mcp_app_item-1", text: "Note C" }], + }); + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runDrain, + ); + assert.include(prompts.at(-1) ?? "", tag("Note C")); + }).pipe(Effect.provide(layerTest)), + ); + + it.live( + "delivers changed appContext on native flavor.steering and preserves undelivered notes on failure", + () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* bundledMockAgentPath; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let sessionUpdateHandler: Parameters[0] | undefined; + const prompts: Array = []; + const steeredTexts: Array = []; + const steerOutcomes: Array< + | { readonly _tag: "accept" } + | { readonly _tag: "fail" } + | { + readonly _tag: "waitId"; + readonly steerId: string; + readonly sent: Deferred.Deferred; + } + > = []; + const promptGates: Array<{ + readonly started: Deferred.Deferred; + readonly gate: Deferred.Deferred; + }> = []; + const queueGate = () => + Effect.gen(function* () { + const entry = { + started: yield* Deferred.make(), + gate: yield* Deferred.make(), + }; + promptGates.push(entry); + return entry; + }); + const instanceId = ProviderInstanceId.make("acp-test-app-context-native-steer"); + const threadId = ThreadId.make("thread-acp-app-context-native-steer"); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: { + ...AcpProviderCapabilitiesV2, + turns: { + ...AcpProviderCapabilitiesV2.turns, + supportsActiveSteering: true, + }, + }, + steering: { + send: (_runtime, _sessionId, text) => + Effect.gen(function* () { + steeredTexts.push(text); + const outcome = steerOutcomes.shift() ?? { _tag: "accept" as const }; + if (outcome._tag === "fail") { + return yield* new EffectAcpErrors.AcpRequestError({ + code: -32603, + errorMessage: "Steering rejected", + method: "_test/steer", + }); + } + if (outcome._tag === "waitId") { + yield* Deferred.succeed(outcome.sent, undefined); + return outcome.steerId; + } + return undefined; + }), + injectedSteerId: (notification) => { + if (notification.update.sessionUpdate !== "session_info_update") return undefined; + const meta = notification.update._meta as + | { readonly injectedSteerId?: string } + | undefined; + return meta?.injectedSteerId; + }, + }, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + wrapRuntime: (runtime) => ({ + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + sessionUpdateHandler = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + prompt: (payload, promptOptions) => + Effect.gen(function* () { + prompts.push( + payload.prompt + .flatMap((block) => (block.type === "text" ? [block.text] : [])) + .join("\n"), + ); + if (promptOptions?.dispatched) { + yield* Deferred.succeed(promptOptions.dispatched, undefined); + } + const next = promptGates.shift(); + if (next === undefined) return { stopReason: "end_turn" as const }; + yield* Deferred.succeed(next.started, undefined); + return yield* Deferred.await(next.gate); + }), + }), + }), + }, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make( + "provider-session-acp-app-context-native-steer", + ), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const sessionId = providerThread.nativeThreadRef?.nativeId; + if (sessionId == null) return assert.fail("expected native session id"); + const tag = (note: string) => `${note}`; + const providerTurnIdFor = (ordinal: number) => + idAllocator.derive.providerTurn({ + driver: ACP_TEST_DRIVER, + nativeTurnId: acpScopedNativeId(instanceId, `${sessionId}:turn:${ordinal}`), + }); + const steer = (ordinal: number, text: string, note: string) => + runtime.steerTurn({ + threadId, + runId: RunId.make(`run:${threadId}:${ordinal}`), + providerThread, + providerTurnId: providerTurnIdFor(ordinal), + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make(`native-steer-${ordinal}-${steeredTexts.length}`), + text, + attachments: [], + }, + appContext: [{ key: "mcp_app_item-1", text: note }], + }); + + const turn1 = yield* queueGate(); + yield* runtime.startTurn({ + ...makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal: 1, + messageText: "Start native turn 1", + }), + appContext: [{ key: "mcp_app_item-1", text: "Note A" }], + }); + yield* Deferred.await(turn1.started); + assert.include(prompts.at(-1) ?? "", tag("Note A")); + + // Unchanged note is omitted on native steer. + steerOutcomes.push({ _tag: "accept" }); + yield* steer(1, "Keep working", "Note A"); + assert.equal(steeredTexts.at(-1), "Keep working"); + + // Slash steer skips appContext injection. + steerOutcomes.push({ _tag: "accept" }); + yield* steer(1, "/status", "Note B"); + assert.equal(steeredTexts.at(-1), "/status"); + + // Rejected steering.send must not mark Note B delivered. + steerOutcomes.push({ _tag: "fail" }); + const failedExit = yield* Effect.exit(steer(1, "Failed steer", "Note B")); + assert.isTrue(Exit.isFailure(failedExit)); + assert.include(steeredTexts.at(-1) ?? "", tag("Note B")); + + // Next steer with Note B resends it and marks it delivered once accepted. + steerOutcomes.push({ _tag: "accept" }); + yield* steer(1, "Retry Note B", "Note B"); + assert.include(steeredTexts.at(-1) ?? "", tag("Note B")); + + // Repeated steer with Note B omits it. + steerOutcomes.push({ _tag: "accept" }); + yield* steer(1, "After Note B", "Note B"); + assert.equal(steeredTexts.at(-1), "After Note B"); + + // Completing turn 1 must not clobber Note B with Turn 1's earlier Note A. + yield* Deferred.succeed(turn1.gate, { stopReason: "end_turn" }); + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runDrain, + ); + + const turn2 = yield* queueGate(); + yield* runtime.startTurn({ + ...makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal: 2, + messageText: "Start native turn 2", + }), + appContext: [{ key: "mcp_app_item-1", text: "Note B" }], + }); + yield* Deferred.await(turn2.started); + assert.notInclude(prompts.at(-1) ?? "", "external_mcp_app_item-1"); + + // A queued steer whose turn settles before injection must not mark Note C delivered. + const droppedSteerSent = yield* Deferred.make(); + steerOutcomes.push({ + _tag: "waitId", + steerId: "steer-dropped-1", + sent: droppedSteerSent, + }); + const droppedSteerFiber = yield* Effect.forkScoped( + Effect.exit(steer(2, "Dropped steer", "Note C")), + ); + yield* Deferred.await(droppedSteerSent); + yield* Deferred.succeed(turn2.gate, { stopReason: "end_turn" }); + const droppedExit = yield* Fiber.join(droppedSteerFiber); + assert.isTrue(Exit.isFailure(droppedExit)); + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runDrain, + ); + + // Turn 3 must resend Note C; also verify injected steerId delivery works when notified. + const turn3 = yield* queueGate(); + yield* runtime.startTurn({ + ...makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal: 3, + messageText: "Start native turn 3", + }), + appContext: [{ key: "mcp_app_item-1", text: "Note C" }], + }); + yield* Deferred.await(turn3.started); + assert.include(prompts.at(-1) ?? "", tag("Note C")); + + const injectedSteerSent = yield* Deferred.make(); + steerOutcomes.push({ + _tag: "waitId", + steerId: "steer-injected-1", + sent: injectedSteerSent, + }); + const injectedSteerFiber = yield* Effect.forkScoped(steer(3, "Injected steer", "Note D")); + yield* Deferred.await(injectedSteerSent); + yield* sessionUpdateHandler!({ + sessionId, + update: { + sessionUpdate: "session_info_update", + _meta: { injectedSteerId: "steer-injected-1" }, + }, + }); + yield* Fiber.join(injectedSteerFiber); + assert.include(steeredTexts.at(-1) ?? "", tag("Note D")); + yield* Deferred.succeed(turn3.gate, { stopReason: "end_turn" }); + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runDrain, + ); + + // Turn 4 sees Note D already delivered. + yield* runtime.startTurn({ + ...makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal: 4, + messageText: "Start native turn 4", + }), + appContext: [{ key: "mcp_app_item-1", text: "Note D" }], + }); + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runDrain, + ); + assert.notInclude(prompts.at(-1) ?? "", "external_mcp_app_item-1"); + }).pipe(Effect.provide(layerTest)), + ); }); describe("acpPostSettleContinuationOfferEvidence", () => { diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index d9410e4754f35..065f95a3e247a 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -164,6 +164,34 @@ function isAgentBusyPromptError(error: EffectAcpErrors.AcpError): boolean { ); } +type AcpAppContextEntry = NonNullable< + ProviderAdapter.ProviderAdapterV2TurnInput["appContext"] +>[number]; + +function formatAcpAppContextEntry(entry: AcpAppContextEntry): string { + return `${entry.text}`; +} + +function unsentAcpAppContext( + appContext: ProviderAdapter.ProviderAdapterV2TurnInput["appContext"], + seen: ReadonlyMap | undefined, + isNativeSlashCommand: boolean, +): ReadonlyArray { + if (isNativeSlashCommand || appContext === undefined || appContext.length === 0) return []; + return appContext.filter((entry) => seen?.get(entry.key) !== entry.text); +} + +function mergeAcpAppContext( + base: ReadonlyMap | undefined, + entries: ReadonlyArray, +): ReadonlyMap { + const merged = new Map(base); + for (const entry of entries) { + merged.set(entry.key, entry.text); + } + return merged; +} + function sendPromptWhenIdle( turn: { readonly interrupted: boolean; readonly finalized: boolean }, prompt: () => Effect.Effect, @@ -1667,6 +1695,9 @@ interface ActiveAcpTurn { readonly completed: Deferred.Deferred; readonly itemOrdinals: Map; readonly outgoingPrompt?: ReadonlyArray | undefined; + appContextOffered?: ReadonlyMap | undefined; + readonly appContextCommittedSequence: Map; + appContextSequence: number; consumedPromptMessageId?: string; readonly user: ActiveTextStream; readonly assistant: ActiveTextStream; @@ -2343,6 +2374,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( >(null); const promptInstructionStates = yield* Ref.make(new Map()); const promptRuntimeInstructions = yield* Ref.make(new Map()); + const deliveredAppContext = yield* Ref.make(new Map>()); // Unique markers keep delayed prompt completions from clearing later compactions. const compactionMarkers = yield* Ref.make(new Map()); // ACP may patch a completed compaction again; each compaction id marks its session once. @@ -2365,6 +2397,17 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.update(compactionMarkers, (current) => new Map(current).set(sessionId, Symbol()), ); + yield* Ref.update(deliveredAppContext, (current) => { + if (!current.has(sessionId)) return current; + const updated = new Map(current); + updated.delete(sessionId); + return updated; + }); + const currentTurn = yield* Ref.get(activeTurn); + if (currentTurn !== null && currentTurn.nativeThreadId === sessionId) { + currentTurn.appContextOffered = undefined; + currentTurn.appContextCommittedSequence.clear(); + } }); const advertisedCommandNames = yield* SubscriptionRef.make( new Map>(), @@ -8003,6 +8046,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.set(activeInteractionMode, null); yield* Ref.set(promptInstructionStates, new Map()); yield* Ref.set(promptRuntimeInstructions, new Map()); + yield* Ref.set(deliveredAppContext, new Map()); yield* Ref.set(compactionMarkers, new Map()); yield* Ref.set(completedCompactionIds, new Set()); yield* Ref.set(snapshot, emptySnapshotState()); @@ -9101,6 +9145,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( // while the prompt is prepared still resends the notes in this prompt. const previousInstructionState = (yield* Ref.get(promptInstructionStates)).get(sessionId); const compactionMarker = (yield* Ref.get(compactionMarkers)).get(sessionId); + const deliveredContext = (yield* Ref.get(deliveredAppContext)).get(sessionId); + const appContextEntries = unsentAcpAppContext( + turnInput.appContext, + deliveredContext, + isNativeSlashCommand, + ); const text = t3AcpPromptWithInstructions({ prompt: messageText, state: instructionState, @@ -9133,6 +9183,14 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( detail: "ACP turn requires non-empty text or attachments", }); } + if (appContextEntries.length > 0) { + prompt.unshift( + ...appContextEntries.map((entry) => ({ + type: "text" as const, + text: formatAcpAppContextEntry(entry), + })), + ); + } if (sendRuntimeInstructions) { prompt.push({ type: "text", text: runtimeInstructions }); } @@ -9140,6 +9198,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( prompt, instructionState: text === messageText ? undefined : instructionState, runtimeInstructions: sendRuntimeInstructions ? runtimeInstructions : undefined, + appContextEntries, compactionMarker, }; }); @@ -9158,12 +9217,44 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( // A failed prompt may have been dropped, so the fresh runtime sends T3's notes again. yield* Ref.set(promptInstructionStates, new Map()); yield* Ref.set(promptRuntimeInstructions, new Map()); + yield* Ref.set(deliveredAppContext, new Map()); yield* Ref.set(compactionMarkers, new Map()); yield* Ref.set(completedCompactionIds, new Set()); yield* Ref.set(snapshot, emptySnapshotState()); return true; }); + const commitAcpAppContext = Effect.fnUntraced(function* (input: { + readonly context: ActiveAcpTurn; + readonly entries: ReadonlyArray; + readonly compactionMarker: symbol | undefined; + readonly sequence: number; + }) { + if (input.entries.length === 0) return; + if ( + (yield* Ref.get(compactionMarkers)).get(input.context.nativeThreadId) !== + input.compactionMarker + ) { + return; + } + const freshEntries = input.entries.filter( + (entry) => + (input.context.appContextCommittedSequence.get(entry.key) ?? 0) < input.sequence, + ); + if (freshEntries.length === 0) return; + for (const entry of freshEntries) { + input.context.appContextCommittedSequence.set(entry.key, input.sequence); + } + yield* Ref.update(deliveredAppContext, (current) => { + const updated = new Map(current); + updated.set( + input.context.nativeThreadId, + mergeAcpAppContext(current.get(input.context.nativeThreadId), freshEntries), + ); + return updated; + }); + }); + /** Follows a turn's `session/prompt`; a prompt-steer's prompt supersedes the one before. */ const followPrompt = ( context: ActiveAcpTurn, @@ -9176,11 +9267,28 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( | Effect.Success>> | undefined; readonly promptParts: Effect.Success> | null; + readonly appContext?: + | { + readonly entries: ReadonlyArray; + readonly offered: ReadonlyMap | undefined; + readonly before: ReadonlyMap | undefined; + readonly compactionMarker: symbol | undefined; + readonly sequence: number; + } + | undefined; readonly compactSession: AcpAdapterV2Flavor["compactSession"]; }, ): Effect.Effect => { const sequence = ++context.promptSequence; const superseded = () => context.promptSequence !== sequence; + const rollbackOfferedAppContext = () => { + if ( + settle.appContext?.offered !== undefined && + context.appContextOffered === settle.appContext.offered + ) { + context.appContextOffered = settle.appContext.before; + } + }; return prompt(superseded).pipe( // Settle the wire before the completion callback's permit so a settled-soft // Stop sees the native return. Capture usage only before finalize: a late @@ -9223,6 +9331,21 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( updated.set(context.nativeThreadId, promptParts.runtimeInstructions); return updated; }); + if ( + !context.interrupted && + !(context.finalized && context.finalizedStatus !== "completed") + ) { + if (settle.appContext !== undefined) { + yield* commitAcpAppContext({ + context, + entries: settle.appContext.entries, + compactionMarker: settle.appContext.compactionMarker, + sequence: settle.appContext.sequence, + }); + } + } else { + rollbackOfferedAppContext(); + } yield* Ref.update(compactionMarkers, (current) => { if (promptParts?.instructionState === undefined) return current; const observedMarker = promptParts.compactionMarker; @@ -9235,6 +9358,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( updated.delete(context.nativeThreadId); return updated; }); + } else { + rollbackOfferedAppContext(); } if (context.finalized || followsAgentWorkState || superseded()) return; // ACP v2 reports a failed prompt through its idle stop reason, not an RPC error. @@ -9356,6 +9481,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( runRuntimeCallbackAtGeneration( settle.generation, Effect.gen(function* () { + rollbackOfferedAppContext(); if (context.finalized || superseded()) return; const error = Cause.findError(cause); // Native close rejects prompts cancelled before insertion with -32800. @@ -9559,6 +9685,18 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( (yield* Ref.get(activeSessionSetup))?.initializeResult.protocolVersion === 2 ? promptParts?.prompt : undefined, + appContextOffered: + promptParts !== null && + promptParts.appContextEntries.length > 0 && + (yield* Ref.get(compactionMarkers)).get(requestedSessionId) === + promptParts.compactionMarker + ? mergeAcpAppContext( + (yield* Ref.get(deliveredAppContext)).get(requestedSessionId), + promptParts.appContextEntries, + ) + : undefined, + appContextCommittedSequence: new Map(), + appContextSequence: 0, user: { current: null, nextSegment: 0, closedNamedSegments: new Map() }, assistant: { current: null, nextSegment: 0, closedNamedSegments: new Map() }, reasoning: { current: null, nextSegment: 0, closedNamedSegments: new Map() }, @@ -9761,6 +9899,16 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const compactSession = isCompactionMessage(turnInput.message) ? flavor.compactSession : undefined; + const initialAppContext = + promptParts !== null && promptParts.appContextEntries.length > 0 + ? { + entries: promptParts.appContextEntries, + offered: context.appContextOffered, + before: undefined, + compactionMarker: promptParts.compactionMarker, + sequence: ++context.appContextSequence, + } + : undefined; yield* followPrompt( context, (superseded) => @@ -9776,7 +9924,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( stopReason: "end_turn", } satisfies EffectAcpSchema.PromptResponse), ), - { generation: promptGeneration, checkPromptOutcome, promptParts, compactSession }, + { + generation: promptGeneration, + checkPromptOutcome, + promptParts, + appContext: initialAppContext, + compactSession, + }, ).pipe(Effect.forkIn(sessionScope)); }, (effect, turnInput) => @@ -9803,6 +9957,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const steerWithPrompt = Effect.fn("AcpAdapterV2.steerWithPrompt")(function* ( turnInput: ProviderAdapter.ProviderAdapterV2SteerInput, ) { + const isNativeSlashCommand = turnInput.message.text.trimStart().startsWith("/"); const text = yield* providerMessageTextWithAttachmentPaths({ text: turnInput.message.text, attachments: turnInput.message.attachments, @@ -9837,6 +9992,43 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( generation, Effect.gen(function* () { if (context.finalized || context.interrupted) return false; + const compactionMarker = (yield* Ref.get(compactionMarkers)).get( + context.nativeThreadId, + ); + const seenAppContext = + context.appContextOffered ?? + (yield* Ref.get(deliveredAppContext)).get(context.nativeThreadId); + const appContextEntries = unsentAcpAppContext( + turnInput.appContext, + seenAppContext, + isNativeSlashCommand, + ); + const appContextBefore = context.appContextOffered; + const appContextOffered = + appContextEntries.length === 0 + ? undefined + : mergeAcpAppContext(seenAppContext, appContextEntries); + const steerAppContext = + appContextOffered === undefined + ? undefined + : { + entries: appContextEntries, + offered: appContextOffered, + before: appContextBefore, + compactionMarker, + sequence: ++context.appContextSequence, + }; + if (appContextOffered !== undefined) { + context.appContextOffered = appContextOffered; + } + const steerPrompt: Array = [ + ...appContextEntries.map((entry) => ({ + type: "text" as const, + text: formatAcpAppContextEntry(entry), + })), + { type: "text", text }, + ...attachmentBlocks, + ]; // The steer prompt carries the turn on, also past a prompt that already settled. const released = context.foregroundIdle; context.foregroundIdle = yield* Deferred.make(); @@ -9869,7 +10061,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( context, () => runtime.prompt( - { prompt: [{ type: "text", text }, ...attachmentBlocks] }, + { prompt: steerPrompt }, { dispatched, released: releasedForSteer }, ), superseded, @@ -9878,6 +10070,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( generation, checkPromptOutcome, promptParts: null, + appContext: steerAppContext, compactSession: undefined, }, ).pipe(Effect.forkIn(sessionScope)); @@ -10210,26 +10403,69 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( resolveAttachmentPath: host.resolveAttachmentPath, resolveExtractedTextPath: host.resolveExtractedTextPath, }); + const images = yield* imageAttachmentBlocks(turnInput.message.attachments); + const isNativeSlashCommand = turnInput.message.text.trimStart().startsWith("/"); + const compactionMarker = (yield* Ref.get(compactionMarkers)).get( + context.nativeThreadId, + ); + const seenAppContext = + context.appContextOffered ?? + (yield* Ref.get(deliveredAppContext)).get(context.nativeThreadId); + const appContextEntries = unsentAcpAppContext( + turnInput.appContext, + seenAppContext, + isNativeSlashCommand, + ); + const steerText = + appContextEntries.length === 0 + ? text + : text.length > 0 + ? `${appContextEntries.map(formatAcpAppContextEntry).join("\n")}\n\n${text}` + : appContextEntries.map(formatAcpAppContextEntry).join("\n"); + const appContextSequence = + appContextEntries.length === 0 ? 0 : ++context.appContextSequence; const steerId = yield* steering.send( runtime, context.nativeThreadId, - text, - yield* imageAttachmentBlocks(turnInput.message.attachments), + steerText, + images, ); - if (steerId === undefined) return; - const injected = steerInjection(steerId); - // The agent reads a steer at its next step. One that lands after the last - // step is dropped, and the turn settles right after; the orchestrator then - // sends it as a follow-up. The bound keeps Stop from queueing behind a tool. - const outcome = yield* Effect.raceFirst( - Deferred.await(injected).pipe(Effect.as("injected" as const)), - Deferred.await(context.promptWireSettled).pipe(Effect.as("settled" as const)), - ).pipe(Effect.timeoutOption(STEER_DELIVERY_BOUND)); - steerInjections.delete(steerId); - if (Option.contains(outcome, "settled") && !(yield* Deferred.isDone(injected))) { - return yield* new ProviderAdapter.ProviderAdapterProtocolError({ - driver, - detail: `Provider turn ${turnInput.providerTurnId} ended before it read the steering message.`, + let steerConfirmed = true; + if (steerId !== undefined) { + const injected = steerInjection(steerId); + // The agent reads a steer at its next step. One that lands after the last + // step is dropped, and the turn settles right after; the orchestrator then + // sends it as a follow-up. The bound keeps Stop from queueing behind a tool. + const outcome = yield* Effect.raceFirst( + Deferred.await(injected).pipe(Effect.as("injected" as const)), + Deferred.await(context.promptWireSettled).pipe(Effect.as("settled" as const)), + ).pipe(Effect.timeoutOption(STEER_DELIVERY_BOUND)); + steerInjections.delete(steerId); + if (Option.contains(outcome, "settled") && !(yield* Deferred.isDone(injected))) { + return yield* new ProviderAdapter.ProviderAdapterProtocolError({ + driver, + detail: `Provider turn ${turnInput.providerTurnId} ended before it read the steering message.`, + }); + } + // A steer still unread at the bound may yet be dropped, so its notes stay unsent. + steerConfirmed = yield* Deferred.isDone(injected); + } + if ( + steerConfirmed && + appContextEntries.length > 0 && + !context.interrupted && + (yield* Ref.get(compactionMarkers)).get(context.nativeThreadId) === compactionMarker + ) { + context.appContextOffered = mergeAcpAppContext( + context.appContextOffered ?? + (yield* Ref.get(deliveredAppContext)).get(context.nativeThreadId), + appContextEntries, + ); + yield* commitAcpAppContext({ + context, + entries: appContextEntries, + compactionMarker, + sequence: appContextSequence, }); } }, From 49ce71efa38a3ca5ae9cde01bc9c3da04a38dbb2 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 22:45:02 -0800 Subject: [PATCH 295/324] fix(server): later Codex retry or failure no longer sorts above same-turn progress (#41255) --- .../Adapters/CodexAdapterV2.test.ts | 126 ++++++++++++++++++ .../Adapters/CodexAdapterV2.ts | 36 ++++- .../orchestration-v2/ProviderEventIngestor.ts | 3 + .../ProviderSessionManager.test.ts | 1 + .../ProviderSessionManager.ts | 1 + .../orchestration-v2/RunExecutionService.ts | 3 + .../src/server/ProviderAdapter.ts | 2 + packages/provider-core/src/server/failure.ts | 24 ++-- 8 files changed, 182 insertions(+), 14 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 330524c99ad3b..afb1d08147111 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -5805,6 +5805,132 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); + it.effect.each(["retry", "failure"] as const)( + "orders a later provider %s after progress from the same turn", + (tail) => + Effect.gen(function* () { + const scenario = `codex-provider-later-${tail}`; + const nativeThreadId = `native-${scenario}-thread`; + const nativeTurnId = `native-${scenario}-turn`; + const retryNotice = (message: string) => ({ + type: "emit_inbound" as const, + label: `error/retry/${message}`, + frame: { + method: "error", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + willRetry: true, + error: { + message, + additionalDetails: "The response stream disconnected.", + codexErrorInfo: { responseStreamDisconnected: { httpStatusCode: 529 } }, + }, + }, + }, + }); + const commandItem = (status: "inProgress" | "completed") => ({ + type: "commandExecution", + id: "command-between-retries", + command: "pwd", + cwd: "/workspace", + processId: "42", + source: "unifiedExecStartup", + status, + commandActions: [{ type: "unknown", command: "pwd" }], + aggregatedOutput: status === "completed" ? "/workspace\n" : null, + exitCode: status === "completed" ? 0 : null, + durationMs: status === "completed" ? 10 : null, + }); + const transcript = makeCodexReplayTranscript({ + scenario, + entries: [ + ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Run pwd." }), + retryNotice("Reconnecting... 1/5"), + { + type: "emit_inbound", + label: "item/started", + frame: { + method: "item/started", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + startedAtMs: 1782622445000, + item: commandItem("inProgress"), + }, + }, + }, + { + type: "emit_inbound", + label: "item/completed", + frame: { + method: "item/completed", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + completedAtMs: 1782622445010, + item: commandItem("completed"), + }, + }, + }, + ...(tail === "retry" ? [retryNotice("Reconnecting... 1/5")] : []), + { + type: "emit_inbound", + label: "turn/completed", + frame: { + method: "turn/completed", + params: { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ + id: nativeTurnId, + status: tail === "retry" ? "completed" : "failed", + }), + }, + }, + }, + ], + }); + const harness = yield* makeCodexReplayHarness(transcript); + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make(`attempt-${scenario}`), + text: "Run pwd.", + }), + ); + yield* harness.awaitTerminal(1); + + const items = harness.events.flatMap((event) => + event.type === "turn_item.updated" ? [event.turnItem] : [], + ); + const command = items.find((item) => item.type === "command_execution"); + assert.isDefined(command); + const terminal = harness.terminalEvents()[0]; + const firstRetry = items.find((item) => item.type === "error"); + const latest = + tail === "retry" + ? items.findLast((item) => item.type === "error") + : terminal?.status === "failed" + ? { id: terminal.failureItemId, ordinal: terminal.failureItemOrdinal } + : undefined; + assert.isAbove(latest?.ordinal ?? 0, command?.ordinal ?? Infinity); + // Stored positions are per row, so the later notice needs its own row to sort after. + assert.isDefined(latest?.id); + assert.notStrictEqual(latest?.id, firstRetry?.id); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + it.effect("fails a stalled 429 provider retry as a usage limit and stops the Codex turn", () => Effect.gen(function* () { const scenario = "codex-provider-retry-stall"; diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index a35767f62eecf..91dbb2f534970 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -46,6 +46,7 @@ import { type ServerProviderModel, isDelegatedAppThread, ThreadId, + type TurnItemId, } from "@t3tools/contracts"; import { SKILL_MENTION_PATTERN } from "@t3tools/shared/composerInlineTokens"; import { AgentScope } from "@t3tools/shared/AgentScope"; @@ -1390,6 +1391,7 @@ interface ActiveCodexTurnContext { capacityRetryAttempt?: number; capacityRetryPending?: Deferred.Deferred; closedCommandItemIds?: ReadonlySet; + recoveredProviderRetries?: number; latestProviderFailure?: { readonly nativeMessage: string; readonly nativeCode: string | null; @@ -1432,6 +1434,24 @@ interface ActiveCodexProviderRetry { readonly failure: OrchestrationV2ProviderFailure; readonly startedAt: DateTime.Utc; readonly itemOrdinal: number; + readonly id: TurnItemId | undefined; +} + +// Each retry episode after a recovery gets its own row, placed after the turn's progress so far. +function codexFailureItemKey(context: ActiveCodexTurnContext): string { + const key = `terminal-failure:${context.providerTurnId}`; + return context.recoveredProviderRetries === undefined + ? key + : `${key}:${context.recoveredProviderRetries}`; +} + +function codexFailureItemId(context: ActiveCodexTurnContext): TurnItemId | undefined { + return context.recoveredProviderRetries === undefined + ? undefined + : IdAllocator.derive.turnItemFromProviderItem({ + driver: CODEX_PROVIDER, + nativeItemId: codexFailureItemKey(context), + }); } function codexRetryTurnItem( @@ -1443,6 +1463,7 @@ function codexRetryTurnItem( // A continuation keeps the retry row attached to the native turn that failed. const context = state.context ?? activeContext; return makeProviderRetryTurnItem({ + ...(state.id === undefined ? {} : { id: state.id }), driver: CODEX_PROVIDER, threadId: context.projectionThreadId, runId: context.projectionRunId, @@ -2614,6 +2635,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( if (providerRetry === undefined) { return; } + context.recoveredProviderRetries = (context.recoveredProviderRetries ?? 0) + 1; yield* emitProviderEvent({ type: "turn_item.updated", driver: CODEX_PROVIDER, @@ -5428,8 +5450,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ); const itemOrdinal = previous?.itemOrdinal ?? - (yield* resolveItemOrdinal(context, `terminal-failure:${context.providerTurnId}`)); + (yield* resolveItemOrdinal(context, codexFailureItemKey(context))); const state: ActiveCodexProviderRetry = { + id: previous === undefined ? codexFailureItemId(context) : previous.id, ...(previous?.context === undefined ? {} : { context: previous.context }), nativeMessage: payload.error.message, nativeCode: code, @@ -6609,6 +6632,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ) { failure = { ...failure, class: "transport_error" }; } + const failureItemId = codexFailureItemId(input.context); return { type: "turn.terminal", driver: CODEX_PROVIDER, @@ -6617,8 +6641,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( runOrdinal: input.context.input.runOrdinal, failureItemOrdinal: yield* resolveItemOrdinal( input.context, - `terminal-failure:${input.context.providerTurnId}`, + codexFailureItemKey(input.context), ), + ...(failureItemId === undefined ? {} : { failureItemId }), status: terminalStatus, failure: failure.class === "usage_limit" @@ -6674,6 +6699,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( yield* emitProviderEvent(current); if (current.status === "failed" && current.failure.class === "usage_limit") { const item = makeProviderFailureTurnItem({ + ...(current.failureItemId === undefined ? {} : { id: current.failureItemId }), driver: CODEX_PROVIDER, threadId: context.input.threadId, runId: context.input.runId, @@ -7415,10 +7441,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( retry: { attempt, maxAttempts: CODEX_CAPACITY_MAX_RETRIES, retryDelayMs }, itemOrdinal: previous?.itemOrdinal ?? - (yield* resolveItemOrdinal( - context, - `terminal-failure:${context.providerTurnId}`, - )), + (yield* resolveItemOrdinal(context, codexFailureItemKey(context))), + id: previous === undefined ? codexFailureItemId(context) : previous.id, startedAt: previous?.startedAt ?? now, }; yield* Ref.update(providerRetries, (current) => diff --git a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts index 118a13a334266..02057de1cae6d 100644 --- a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts +++ b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts @@ -737,6 +737,9 @@ export const layer: Layer.Layer< yield* makeDomainEvent(input, { type: "turn-item.updated", payload: makeProviderFailureTurnItem({ + ...(input.event.failureItemId === undefined + ? {} + : { id: input.event.failureItemId }), driver: input.event.driver, threadId: input.threadId, runId: input.runId ?? null, diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index 14d17371983b5..f2f992d8f4ee9 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -2534,6 +2534,7 @@ it.effect("ProviderSessionManagerV2 fails a turn whose provider retry never resu providerTurnId, runOrdinal: 1, failureItemOrdinal: 3, + failureItemId: retryItem("running").id, status: "failed", failure: { ...failure, retryable: false }, retry, diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index 6d445f5b0bdf7..dc1ae318a4c2a 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -2942,6 +2942,7 @@ export const layerWithOptions = ( providerTurnId: event.providerTurnId, runOrdinal: event.runOrdinal, failureItemOrdinal: stalled.ordinal, + failureItemId: stalled.id, status: "failed", failure: { ...stalled.failure, retryable: false }, retry: stalled.retry, diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.ts index a5eeaa9cb8b95..21065b41a5f3e 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.ts @@ -993,6 +993,9 @@ export const layer: Layer.Layer< providerInstanceId: input.run.providerInstanceId, occurredAt: completedAt, payload: makeProviderFailureTurnItem({ + ...(input.terminal.failureItemId === undefined + ? {} + : { id: input.terminal.failureItemId }), driver: input.terminal.driver, threadId: input.run.threadId, runId: input.run.id, diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.ts index 4d008a7233900..015a68f48982b 100644 --- a/packages/provider-core/src/server/ProviderAdapter.ts +++ b/packages/provider-core/src/server/ProviderAdapter.ts @@ -234,6 +234,8 @@ export const ProviderAdapterV2Event = Schema.Union([ providerTurnId: ProviderTurnId, runOrdinal: PositiveInt, failureItemOrdinal: PositiveInt, + /** The row the failure lands on; defaults to the turn's `terminal-failure` row. */ + failureItemId: Schema.optional(TurnItemId), status: Schema.Literal("failed"), failure: OrchestrationV2ProviderFailure, retry: Schema.optional(OrchestrationV2ProviderRetry), diff --git a/packages/provider-core/src/server/failure.ts b/packages/provider-core/src/server/failure.ts index e7d47cdb2175e..267e402900d25 100644 --- a/packages/provider-core/src/server/failure.ts +++ b/packages/provider-core/src/server/failure.ts @@ -9,6 +9,7 @@ import type { ProviderTurnId, RunId, ThreadId, + TurnItemId, } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; import * as Cause from "effect/Cause"; @@ -334,6 +335,8 @@ export function makeProviderFailure(input: { } export function makeProviderFailureTurnItem(input: { + // Defaults to the turn's single failure row. + readonly id?: TurnItemId; readonly driver: ProviderDriverKind; readonly threadId: ThreadId; readonly runId: RunId | null; @@ -347,10 +350,12 @@ export function makeProviderFailureTurnItem(input: { readonly occurredAt: DateTime.Utc; }): Extract { return { - id: IdAllocator.derive.turnItemFromProviderItem({ - driver: input.driver, - nativeItemId: `terminal-failure:${input.providerTurnId}`, - }), + id: + input.id ?? + IdAllocator.derive.turnItemFromProviderItem({ + driver: input.driver, + nativeItemId: `terminal-failure:${input.providerTurnId}`, + }), threadId: input.threadId, runId: input.runId, nodeId: input.nodeId, @@ -378,6 +383,7 @@ export function makeProviderFailureTurnItem(input: { export const PROVIDER_RETRY_BUDGET_MS = 10 * 60 * 1000; export function makeProviderRetryTurnItem(input: { + readonly id?: TurnItemId; readonly driver: ProviderDriverKind; readonly threadId: ThreadId; readonly runId: RunId | null; @@ -404,10 +410,12 @@ export function makeProviderRetryTurnItem(input: { title = "Provider retry stopped"; } return { - id: IdAllocator.derive.turnItemFromProviderItem({ - driver: input.driver, - nativeItemId: `terminal-failure:${input.providerTurnId}`, - }), + id: + input.id ?? + IdAllocator.derive.turnItemFromProviderItem({ + driver: input.driver, + nativeItemId: `terminal-failure:${input.providerTurnId}`, + }), threadId: input.threadId, runId: input.runId, nodeId: input.nodeId, From f00893a512b9c32187ac32c795f1e3ef3839521a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 22:52:04 -0800 Subject: [PATCH 296/324] fix(server): branch names keep leading and trailing Unicode whitespace (#41274) --- apps/server/src/git/GitManager.ts | 14 ++- apps/server/src/git/GitWorkflowService.ts | 3 +- apps/server/src/git/remoteRefs.ts | 12 +- apps/server/src/vcs/GitVcsDriverCore.test.ts | 111 +++++++++++-------- apps/server/src/vcs/GitVcsDriverCore.ts | 53 +++++---- packages/contracts/src/baseSchemas.ts | 33 ++++++ packages/contracts/src/git.test.ts | 33 ++++++ packages/contracts/src/git.ts | 55 ++++----- packages/contracts/src/orchestrationV2.ts | 21 ++-- packages/contracts/src/pullRequest.ts | 19 ++-- packages/contracts/src/review.ts | 14 +-- packages/contracts/src/sourceControl.ts | 8 +- packages/contracts/src/threadPullRequest.ts | 9 +- packages/contracts/src/worktreeMcp.ts | 12 +- packages/contracts/src/worktreeSetup.ts | 12 +- 15 files changed, 257 insertions(+), 152 deletions(-) diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index dedf2d19f54ed..4b23f8cd6c66f 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -66,7 +66,11 @@ import { } from "../sourceControl/threadPullRequests.ts"; import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts"; -import { GitManagerError, GitPullRequestMaterializationError } from "@t3tools/contracts"; +import { + GitManagerError, + GitPullRequestMaterializationError, + trimAsciiWhitespace, +} from "@t3tools/contracts"; import { historicalMessage, renderHistory, @@ -278,7 +282,7 @@ const prLookupGitReads = Context.Reference( function parseRemoteNames(stdout: string): ReadonlyArray { return stdout .split("\n") - .map((name) => name.trim()) + .map(trimAsciiWhitespace) .filter((name) => name.length > 0); } @@ -2012,7 +2016,7 @@ export const make = Effect.gen(function* () { timeoutMs: 5_000, })).stdout .split("\n") - .map((ref) => ref.trim()) + .map(trimAsciiWhitespace) .filter((ref) => ref.length > 0), ); const matching = remoteNames.filter((name) => refs.has(`refs/remotes/${name}/${branch}`)); @@ -2049,7 +2053,7 @@ export const make = Effect.gen(function* () { const oidByRef = new Map( refs.stdout .split("\n") - .map((line) => line.trim().split("\u0000")) + .map((line) => trimAsciiWhitespace(line).split("\u0000")) .filter((entry): entry is [string, string] => entry.length === 2), ); const localOid = oidByRef.get(localRef); @@ -3354,7 +3358,7 @@ export const make = Effect.gen(function* () { const refNames = new Set( trackingRefs.stdout .split("\n") - .map((remoteRef) => remoteRef.trim()) + .map(trimAsciiWhitespace) .filter((remoteRef) => remoteRef.length > 0), ); return remoteNames diff --git a/apps/server/src/git/GitWorkflowService.ts b/apps/server/src/git/GitWorkflowService.ts index 4cf3e62d9a93f..ca7c0b03c13d4 100644 --- a/apps/server/src/git/GitWorkflowService.ts +++ b/apps/server/src/git/GitWorkflowService.ts @@ -29,6 +29,7 @@ import { type VcsStatusResult, } from "@t3tools/contracts"; +import { trimAsciiWhitespace } from "@t3tools/contracts"; import * as GitManager from "./GitManager.ts"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts"; @@ -365,7 +366,7 @@ export const make = Effect.gen(function* () { timeoutMs: 5_000, }); if (result.exitCode === 0) { - return result.stdout.trim().replace(/^refs\/heads\//, "") || null; + return trimAsciiWhitespace(result.stdout).replace(/^refs\/heads\//, "") || null; } if (result.exitCode === 1) return null; return yield* new GitCommandError({ diff --git a/apps/server/src/git/remoteRefs.ts b/apps/server/src/git/remoteRefs.ts index e3873effe475e..c5be08c165676 100644 --- a/apps/server/src/git/remoteRefs.ts +++ b/apps/server/src/git/remoteRefs.ts @@ -1,7 +1,9 @@ +import { trimAsciiWhitespace } from "@t3tools/contracts"; + export function parseRemoteNamesInGitOrder(stdout: string): ReadonlyArray { const remoteNames: Array = []; for (const line of stdout.split("\n")) { - const remoteName = line.trim(); + const remoteName = trimAsciiWhitespace(line); if (remoteName.length > 0) { remoteNames.push(remoteName); } @@ -17,7 +19,7 @@ export function parseRemoteRefWithRemoteNames( ref: string, remoteNames: ReadonlyArray, ): { remoteRef: string; remoteName: string; branchName: string } | null { - const trimmedRef = ref.trim(); + const trimmedRef = trimAsciiWhitespace(ref); if (trimmedRef.length === 0) { return null; } @@ -27,7 +29,7 @@ export function parseRemoteRefWithRemoteNames( if (!trimmedRef.startsWith(remotePrefix)) { continue; } - const branchName = trimmedRef.slice(remotePrefix.length).trim(); + const branchName = trimmedRef.slice(remotePrefix.length); if (branchName.length === 0) { return null; } @@ -48,7 +50,7 @@ export function extractBranchNameFromRemoteRef( remoteNames?: ReadonlyArray; }, ): string { - const normalized = ref.trim(); + const normalized = trimAsciiWhitespace(ref); if (normalized.length === 0) { return ""; } @@ -67,5 +69,5 @@ export function extractBranchNameFromRemoteRef( if (firstSlash === -1) { return normalized; } - return normalized.slice(firstSlash + 1).trim(); + return normalized.slice(firstSlash + 1); } diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index d64c0ec5cbb5b..b7125614c0ef7 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -6485,24 +6485,36 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); - it.effect("marks the origin default ref as default when no local copy exists", () => - Effect.gen(function* () { - const cwd = yield* makeTmpDir(); - const remote = yield* makeTmpDir("git-vcs-driver-remote-"); - const { initialBranch } = yield* initRepoWithCommit(cwd); - yield* git(remote, ["init", "--bare"]); - yield* git(cwd, ["remote", "add", "origin", remote]); - yield* git(cwd, ["push", "-u", "origin", initialBranch]); - yield* git(cwd, ["remote", "set-head", "origin", initialBranch]); - yield* git(cwd, ["checkout", "-b", "feature/only-local"]); - yield* git(cwd, ["branch", "-D", initialBranch]); - const driver = yield* GitVcsDriver.GitVcsDriver; + it.effect.each(["trunk", "feature/memo\u3000", "\u00a0release"])( + "marks the origin default ref %s as default when no local copy exists", + (defaultBranch) => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const remote = yield* makeTmpDir("git-vcs-driver-remote-"); + yield* initRepoWithCommit(cwd); + yield* git(remote, ["init", "--bare"]); + yield* git(cwd, ["branch", "-M", defaultBranch]); + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* git(cwd, ["push", "-u", "origin", defaultBranch]); + yield* git(cwd, ["remote", "set-head", "origin", defaultBranch]); + const driver = yield* GitVcsDriver.GitVcsDriver; - const refs = yield* driver.listRefs({ cwd }); - const remoteDefault = refs.refs.find((ref) => ref.name === `origin/${initialBranch}`); - assert.equal(remoteDefault?.isRemote, true); - assert.equal(remoteDefault?.isDefault, true); - }), + const localStatus = yield* driver.statusDetails(cwd); + const remoteStatus = yield* driver.statusDetailsRemote(cwd); + for (const status of [localStatus, remoteStatus]) { + assert.equal(status.branch, defaultBranch); + assert.equal(status.upstreamRef, `origin/${defaultBranch}`); + assert.isTrue(status.isDefaultBranch); + } + + yield* git(cwd, ["checkout", "-b", "feature/only-local"]); + yield* git(cwd, ["branch", "-D", defaultBranch]); + + const refs = yield* driver.listRefs({ cwd }); + const remoteDefault = refs.refs.find((ref) => ref.name === `origin/${defaultBranch}`); + assert.equal(remoteDefault?.isRemote, true); + assert.equal(remoteDefault?.isDefault, true); + }), ); it.effect("preserves exact custom names and refuses collisions without a suffix", () => @@ -7444,37 +7456,42 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); - it.effect.each(["release/v2", "origin/release/v2", "refs/remotes/origin/release/v2"])( - "records a remote-only PR base when creating a worktree from %s", - (baseRef) => - Effect.gen(function* () { - const cwd = yield* makeTmpDir(); - yield* initRepoWithCommit(cwd); - const remote = yield* makeTmpDir("git-remote-"); - yield* git(remote, ["init", "--bare"]); - yield* git(cwd, ["remote", "add", "origin", remote]); - yield* git(cwd, ["push", "origin", "HEAD:refs/heads/release/v2"]); - const commit = yield* git(cwd, ["rev-parse", "origin/release/v2"]); - const path = yield* Path.Path; - const driver = yield* GitVcsDriver.GitVcsDriver; - const worktreePath = path.join(yield* makeTmpDir("git-worktrees-"), "remote"); - yield* driver.createWorktree({ - cwd, - path: worktreePath, - refName: commit, - newRefName: "feature/remote", - baseRefName: baseRef, - }); + it.effect.each([ + "release/v2", + "origin/release/v2", + "refs/remotes/origin/release/v2", + "origin/release/v2\u3000", + ])("records a remote-only PR base when creating a worktree from %s", (baseRef) => + Effect.gen(function* () { + const branch = baseRef.replace(/^(refs\/remotes\/)?origin\//, ""); + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + const remote = yield* makeTmpDir("git-remote-"); + yield* git(remote, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* git(cwd, ["push", "origin", `HEAD:refs/heads/${branch}`]); + const commit = yield* git(cwd, ["rev-parse", `origin/${branch}`]); + const path = yield* Path.Path; + const driver = yield* GitVcsDriver.GitVcsDriver; + const worktreePath = path.join(yield* makeTmpDir("git-worktrees-"), "remote"); + yield* driver.createWorktree({ + cwd, + path: worktreePath, + refName: commit, + newRefName: "feature/remote", + baseRefName: baseRef, + }); - const preview = yield* driver.getReviewDiffPreview({ cwd: worktreePath }); - const comparisonBase = preview.sources.find( - (source) => source.kind === "branch-range", - )!.baseRef; - assert.equal( - yield* git(worktreePath, ["rev-parse", `${comparisonBase}^{commit}`]), - commit, - ); - }), + assert.equal( + yield* driver.readConfigValue(cwd, "branch.feature/remote.t3-merge-base"), + branch, + ); + const preview = yield* driver.getReviewDiffPreview({ cwd: worktreePath }); + const comparisonBase = preview.sources.find( + (source) => source.kind === "branch-range", + )!.baseRef; + assert.equal(yield* git(worktreePath, ["rev-parse", `${comparisonBase}^{commit}`]), commit); + }), ); it("parses checkout progress lines from git's stderr", () => { diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 9ee53e4e90ac3..4981ece0979e4 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -34,6 +34,7 @@ import { type ReviewDiffPreviewInput, type ReviewDiffFileStat, type ReviewDiffPreviewSource, + trimAsciiWhitespace, type VcsRef, } from "@t3tools/contracts"; import { dedupeRemoteBranchesWithLocalMatches } from "@t3tools/shared/git"; @@ -452,8 +453,8 @@ function parseUpstreamRefByFirstSeparator( return null; } - const remoteName = upstreamRef.slice(0, separatorIndex).trim(); - const branchName = upstreamRef.slice(separatorIndex + 1).trim(); + const remoteName = upstreamRef.slice(0, separatorIndex); + const branchName = upstreamRef.slice(separatorIndex + 1); if (remoteName.length === 0 || branchName.length === 0) { return null; } @@ -467,13 +468,13 @@ function parseUpstreamRefByFirstSeparator( function parseTrackingBranchByUpstreamRef(stdout: string, upstreamRef: string): string | null { for (const line of stdout.split("\n")) { - const trimmedLine = line.trim(); + const trimmedLine = trimAsciiWhitespace(line); if (trimmedLine.length === 0) { continue; } const [branchNameRaw, upstreamBranchRaw = ""] = trimmedLine.split("\t"); - const branchName = branchNameRaw?.trim() ?? ""; - const candidateUpstreamRef = upstreamBranchRaw.trim(); + const branchName = branchNameRaw ?? ""; + const candidateUpstreamRef = upstreamBranchRaw; if (branchName.length === 0 || candidateUpstreamRef.length === 0) { continue; } @@ -490,7 +491,7 @@ function deriveLocalBranchNameFromRemoteRef(branchName: string): string | null { if (separatorIndex <= 0 || separatorIndex === branchName.length - 1) { return null; } - const localBranch = branchName.slice(separatorIndex + 1).trim(); + const localBranch = branchName.slice(separatorIndex + 1); return localBranch.length > 0 ? localBranch : null; } @@ -592,19 +593,19 @@ function classifyGitFailure(stderr: string): GitCommandFailureReason | null { // `--short` and `--abbrev-ref` print `heads/` when a tag shares the branch's name, so // branch reads take the full ref and strip the prefix themselves. function branchNameFromHeadRef(value: string): string | null { - const ref = value.trim(); + const ref = trimAsciiWhitespace(value); return ref.startsWith("refs/heads/") && ref.length > "refs/heads/".length ? ref.slice("refs/heads/".length) : null; } function parseDefaultBranchFromRemoteHeadRef(value: string, remoteName: string): string | null { - const trimmed = value.trim(); + const trimmed = trimAsciiWhitespace(value); const prefix = `refs/remotes/${remoteName}/`; if (!trimmed.startsWith(prefix)) { return null; } - const refName = trimmed.slice(prefix.length).trim(); + const refName = trimmed.slice(prefix.length); return refName.length > 0 && refName !== "HEAD" ? refName : null; } @@ -1472,7 +1473,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* cwd, ["rev-parse", "--symbolic-full-name", "@{upstream}"], true, - ).pipe(Effect.map((stdout) => stdout.trim().replace(/^refs\/(?:remotes|heads)\//, ""))); + ).pipe( + Effect.map((stdout) => trimAsciiWhitespace(stdout).replace(/^refs\/(?:remotes|heads)\//, "")), + ); if (upstreamRef.length === 0 || upstreamRef === "@{upstream}") { return null; @@ -2056,7 +2059,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* cwd, ["symbolic-ref", "--quiet", "HEAD"], true, - ).pipe(Effect.map((stdout) => stdout.trim()))); + ).pipe(Effect.map(trimAsciiWhitespace))); if (headRef.length === 0) return undefined; const upstreamRemote = yield* executeGit( "GitVcsDriver.refreshStatusUpstreamIfStale.upstreamRemote", @@ -2065,7 +2068,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* { allowNonZeroExit: true }, ); if (upstreamRemote.exitCode !== 0) return undefined; - const remoteName = upstreamRemote.stdout.trim(); + const remoteName = trimAsciiWhitespace(upstreamRemote.stdout); // Empty means no upstream; `.` means the upstream is a local branch. if (remoteName.length === 0 || remoteName === ".") return remoteName; const gitCommonDir = yield* resolveGitCommonDir(cwd); @@ -2202,7 +2205,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* cwd, ["config", "--get", `branch.${refName}.pushRemote`], true, - ).pipe(Effect.map((stdout) => stdout.trim())); + ).pipe(Effect.map(trimAsciiWhitespace)); if (branchPushRemote.length > 0) { return branchPushRemote; } @@ -2212,7 +2215,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* cwd, ["config", "--get", "remote.pushDefault"], true, - ).pipe(Effect.map((stdout) => stdout.trim())); + ).pipe(Effect.map(trimAsciiWhitespace)); return pushDefaultRemote.length > 0 ? pushDefaultRemote : null; }); @@ -2351,7 +2354,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ["rev-parse", "--symbolic-full-name", `${refName}@{upstream}`], { allowNonZeroExit: true }, ); - const comparisonRef = upstream.stdout.trim(); + const comparisonRef = trimAsciiWhitespace(upstream.stdout); if (upstream.exitCode !== 0 || !comparisonRef.startsWith("refs/remotes/")) return null; return { baseRef: comparisonRef.slice("refs/remotes/".length), comparisonRef }; }); @@ -2665,7 +2668,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* headRef = ""; } else { branch = branchNameFromHeadRef(branchResult.stdout); - headRef = branchResult.stdout.trim(); + headRef = trimAsciiWhitespace(branchResult.stdout); } let upstreamRemoteName: string | undefined; if (refreshUpstream) { @@ -2945,13 +2948,13 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* continue; } if (line.startsWith("# branch.head ")) { - const value = line.slice("# branch.head ".length).trim(); + const value = trimAsciiWhitespace(line.slice("# branch.head ".length)); // `(unknown)` is printed while HEAD names no resolvable branch, e.g. mid-`git clone`. refName = value === "(detached)" || value === "(unknown)" ? null : value; continue; } if (line.startsWith("# branch.upstream ")) { - const value = line.slice("# branch.upstream ".length).trim(); + const value = trimAsciiWhitespace(line.slice("# branch.upstream ".length)); upstreamRef = value.length > 0 ? value : null; continue; } @@ -4031,7 +4034,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* cwd, ["config", "--get-all", `branch.${refName}.merge`], true, - ).pipe(Effect.map((stdout) => stdout.trim().split("\n").filter(Boolean))), + ).pipe(Effect.map((stdout) => trimAsciiWhitespace(stdout).split("\n").filter(Boolean))), runGitStdout( "GitVcsDriver.pullCurrentBranch.currentBranch", cwd, @@ -5233,7 +5236,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const readConfigValue: GitVcsDriver.GitVcsDriver["Service"]["readConfigValue"] = (cwd, key) => runGitStdout("GitVcsDriver.readConfigValue", cwd, ["config", "--get", key], true).pipe( - Effect.map((stdout) => stdout.trim()), + Effect.map(trimAsciiWhitespace), Effect.map((trimmed) => (trimmed.length > 0 ? trimmed : null)), ); @@ -5279,7 +5282,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* input.cwd, ["rev-parse", "--symbolic-full-name", startPoint], { allowNonZeroExit: true }, - ).pipe(Effect.map((result) => (result.exitCode === 0 ? result.stdout.trim() : ""))); + ).pipe( + Effect.map((result) => (result.exitCode === 0 ? trimAsciiWhitespace(result.stdout) : "")), + ); if (!startRef.startsWith("refs/remotes/")) return; yield* executeGitWithStableDiagnostics( `${operation}.track`, @@ -5326,7 +5331,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ? { baseRef: `refs/remotes/${remoteName}/${refName}`, branchName: refName } : null; } - const ref = result.stdout.trim(); + const ref = trimAsciiWhitespace(result.stdout); if (ref.startsWith("refs/heads/")) { const branchName = ref.slice("refs/heads/".length); return { baseRef: ref, branchName }; @@ -6897,7 +6902,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const refName = yield* runGitStdout("GitVcsDriver.switchRef.currentBranch", input.cwd, [ "branch", "--show-current", - ]).pipe(Effect.map((stdout) => stdout.trim() || null)); + ]).pipe(Effect.map((stdout) => trimAsciiWhitespace(stdout) || null)); return { refName }; }, @@ -6937,7 +6942,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* Effect.map((stdout) => { const branchNames: Array = []; for (const line of stdout.split("\n")) { - const branchName = line.trim(); + const branchName = trimAsciiWhitespace(line); if (branchName.length > 0) { branchNames.push(branchName); } diff --git a/packages/contracts/src/baseSchemas.ts b/packages/contracts/src/baseSchemas.ts index d8137fc8ca9ec..be27f15c58753 100644 --- a/packages/contracts/src/baseSchemas.ts +++ b/packages/contracts/src/baseSchemas.ts @@ -28,6 +28,39 @@ const isNonBlank = Schema.makeFilter((value: string) => value.trim().length > 0, }); export const TrimmedNonEmptyString = TrimmedString.check(isNonBlank); +// Git forbids ASCII space and control characters in ref names but allows Unicode whitespace such +// as U+00A0 and U+3000, which `String.prototype.trim` would strip from a name's edges. +export function trimAsciiWhitespace(value: string): string { + let start = 0; + let end = value.length; + while (start < end && isAsciiWhitespace(value.charCodeAt(start))) start++; + while (end > start && isAsciiWhitespace(value.charCodeAt(end - 1))) end--; + return end - start === value.length ? value : value.slice(start, end); +} + +function isAsciiWhitespace(code: number): boolean { + return code === 0x20 || (code >= 0x09 && code <= 0x0d); +} + +const isNonBlankGitRefName = Schema.makeFilter( + (value: string) => trimAsciiWhitespace(value).length > 0, + { + expected: "a non-blank string", + toJsonSchema: () => [{ minLength: 1 }, true], + arbitraryConstraint: { minLength: 1 }, + }, +); +/** A branch, ref or remote name. Unlike `TrimmedNonEmptyString`, it keeps Unicode whitespace. */ +export const GitRefName = Schema.String.pipe( + Schema.decodeTo( + Schema.String, + SchemaTransformation.transformEffect({ + decode: (value) => Effect.succeed(trimAsciiWhitespace(value)), + encode: (value) => Effect.succeed(trimAsciiWhitespace(value)), + }), + ), +).check(isNonBlankGitRefName); + export const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)); export const PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)); export const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 })); diff --git a/packages/contracts/src/git.test.ts b/packages/contracts/src/git.test.ts index ae7b260c368f9..8802b445e53ac 100644 --- a/packages/contracts/src/git.test.ts +++ b/packages/contracts/src/git.test.ts @@ -5,10 +5,18 @@ import { GitCommandError, GitPreparePullRequestThreadResult, GitRunStackedActionInput, + VcsCreateWorktreeInput, + VcsRef, } from "./git.ts"; +import { WorktreeMcpHandoffInput } from "./worktreeMcp.ts"; import { PullRequestDiffFileContentsInput } from "./pullRequest.ts"; import { ReviewDiffFileContentsInput } from "./review.ts"; +const encodeVcsRef = Schema.encodeUnknownSync(VcsRef); +const decodeVcsRef = Schema.decodeUnknownSync(VcsRef); +const encodeCreateWorktreeInput = Schema.encodeUnknownSync(VcsCreateWorktreeInput); +const decodeCreateWorktreeInput = Schema.decodeUnknownSync(VcsCreateWorktreeInput); +const decodeWorktreeHandoffInput = Schema.decodeUnknownSync(WorktreeMcpHandoffInput); const decodeGitCommandError = Schema.decodeUnknownSync(Schema.toCodecJson(GitCommandError)); const decodePreparePullRequestThreadResult = Schema.decodeUnknownSync( GitPreparePullRequestThreadResult, @@ -106,3 +114,28 @@ describe("Git file paths", () => { expect(encode(input)).toEqual(input); }); }); + +describe("Git ref names", () => { + it.each(["origin/release/v2\u3000", "\u00a0release", "\u3000"])( + "keeps Unicode whitespace at the edges of %j across the wire", + (name) => { + const ref = { name, upstreamRef: `refs/remotes/${name}`, current: false, isDefault: false }; + const wireRef = encodeVcsRef({ ...ref, worktreePath: null }); + expect(decodeVcsRef(wireRef)).toMatchObject(ref); + + const input = { cwd: "/repo", refName: name, newRefName: name, baseRefName: name }; + const wireInput = encodeCreateWorktreeInput({ ...input, path: null }); + expect(decodeCreateWorktreeInput(wireInput)).toMatchObject(input); + + const handoff = { branch: name, baseRef: name, startFromOrigin: true }; + expect(decodeWorktreeHandoffInput(handoff)).toEqual(handoff); + }, + ); + + it("still trims ASCII whitespace and rejects a blank name", () => { + expect( + decodeCreateWorktreeInput({ cwd: "/repo", refName: " \tmain\n", path: null }).refName, + ).toBe("main"); + expect(() => decodeCreateWorktreeInput({ cwd: "/repo", refName: " \t", path: null })).toThrow(); + }); +}); diff --git a/packages/contracts/src/git.ts b/packages/contracts/src/git.ts index 751f240f0709e..2faf0ffb8c248 100644 --- a/packages/contracts/src/git.ts +++ b/packages/contracts/src/git.ts @@ -1,6 +1,7 @@ import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import { + GitRefName, ForwardCompatibleOptional, NonNegativeInt, PositiveInt, @@ -81,11 +82,11 @@ const GitRunStackedActionToast = Schema.Struct({ export type GitRunStackedActionToast = typeof GitRunStackedActionToast.Type; export const VcsRef = Schema.Struct({ - name: TrimmedNonEmptyStringSchema, + name: GitRefName, isRemote: Schema.optional(Schema.Boolean), - remoteName: Schema.optional(TrimmedNonEmptyStringSchema), + remoteName: Schema.optional(GitRefName), // Full Git ref, for example refs/remotes/origin/feature. - upstreamRef: Schema.optional(TrimmedNonEmptyStringSchema), + upstreamRef: Schema.optional(GitRefName), current: Schema.Boolean, isDefault: Schema.Boolean, worktreePath: TrimmedNonEmptyStringSchema.pipe(Schema.NullOr), @@ -94,14 +95,14 @@ export type VcsRef = typeof VcsRef.Type; const VcsWorktree = Schema.Struct({ path: TrimmedNonEmptyStringSchema, - refName: TrimmedNonEmptyStringSchema, + refName: GitRefName, }); const GitResolvedPullRequest = Schema.Struct({ number: PositiveInt, title: TrimmedNonEmptyStringSchema, url: Schema.String, - baseBranch: TrimmedNonEmptyStringSchema, - headBranch: TrimmedNonEmptyStringSchema, + baseBranch: GitRefName, + headBranch: GitRefName, state: GitPullRequestState, }); export type GitResolvedPullRequest = typeof GitResolvedPullRequest.Type; @@ -157,9 +158,9 @@ export type VcsListRefsInput = typeof VcsListRefsInput.Type; export const VcsCreateWorktreeInput = Schema.Struct({ cwd: TrimmedNonEmptyStringSchema, - refName: TrimmedNonEmptyStringSchema, - newRefName: Schema.optional(TrimmedNonEmptyStringSchema), - baseRefName: Schema.optional(TrimmedNonEmptyStringSchema), + refName: GitRefName, + newRefName: Schema.optional(GitRefName), + baseRefName: Schema.optional(GitRefName), path: Schema.NullOr(TrimmedNonEmptyStringSchema), }); export type VcsCreateWorktreeInput = typeof VcsCreateWorktreeInput.Type; @@ -187,19 +188,19 @@ export type VcsRemoveWorktreeInput = typeof VcsRemoveWorktreeInput.Type; export const VcsCreateRefInput = Schema.Struct({ cwd: TrimmedNonEmptyStringSchema, - refName: TrimmedNonEmptyStringSchema, + refName: GitRefName, switchRef: Schema.optional(Schema.Boolean), }); export type VcsCreateRefInput = typeof VcsCreateRefInput.Type; export const VcsCreateRefResult = Schema.Struct({ - refName: TrimmedNonEmptyStringSchema, + refName: GitRefName, }); export type VcsCreateRefResult = typeof VcsCreateRefResult.Type; export const VcsSwitchRefInput = Schema.Struct({ cwd: TrimmedNonEmptyStringSchema, - refName: TrimmedNonEmptyStringSchema, + refName: GitRefName, }); export type VcsSwitchRefInput = typeof VcsSwitchRefInput.Type; @@ -213,8 +214,8 @@ const VcsStatusChangeRequest = Schema.Struct({ number: PositiveInt, title: TrimmedNonEmptyStringSchema, url: Schema.String, - baseRef: TrimmedNonEmptyStringSchema, - headRef: TrimmedNonEmptyStringSchema, + baseRef: GitRefName, + headRef: GitRefName, state: VcsStatusChangeRequestState, isDraft: Schema.optional(Schema.Boolean), updatedAt: Schema.optional(Schema.NullOr(Schema.String)), @@ -225,7 +226,7 @@ const VcsStatusLocalShape = { sourceControlProvider: Schema.optional(SourceControlProviderInfo), hasPrimaryRemote: Schema.Boolean, isDefaultRef: Schema.Boolean, - refName: Schema.NullOr(TrimmedNonEmptyStringSchema), + refName: Schema.NullOr(GitRefName), hasWorkingTreeChanges: Schema.Boolean, workingTree: Schema.Struct({ // Absolute worktree root on the environment that every files[].path is @@ -243,7 +244,7 @@ const VcsStatusLocalShape = { }), branchChanges: Schema.optional( Schema.Struct({ - baseRef: Schema.NullOr(TrimmedNonEmptyStringSchema), + baseRef: Schema.NullOr(GitRefName), insertions: NonNegativeInt, deletions: NonNegativeInt, }), @@ -313,7 +314,7 @@ export type GitResolvePullRequestResult = typeof GitResolvePullRequestResult.Typ export const GitPreparePullRequestThreadResult = Schema.Struct({ pullRequest: GitResolvedPullRequest, - branch: TrimmedNonEmptyStringSchema, + branch: GitRefName, worktreePath: TrimmedNonEmptyStringSchema.pipe(Schema.NullOr), /** False when local commits or edits prevented a reused worktree from reaching the PR head. */ isOnPullRequestHead: Schema.Boolean.pipe(Schema.withDecodingDefaultKey(Effect.succeed(true))), @@ -321,7 +322,7 @@ export const GitPreparePullRequestThreadResult = Schema.Struct({ export type GitPreparePullRequestThreadResult = typeof GitPreparePullRequestThreadResult.Type; export const VcsSwitchRefResult = Schema.Struct({ - refName: Schema.NullOr(TrimmedNonEmptyStringSchema), + refName: Schema.NullOr(GitRefName), }); export type VcsSwitchRefResult = typeof VcsSwitchRefResult.Type; @@ -329,7 +330,7 @@ export const GitRunStackedActionResult = Schema.Struct({ action: GitStackedAction, branch: Schema.Struct({ status: GitBranchStepStatus, - name: Schema.optional(TrimmedNonEmptyStringSchema), + name: Schema.optional(GitRefName), }), commit: Schema.Struct({ status: GitCommitStepStatus, @@ -338,16 +339,16 @@ export const GitRunStackedActionResult = Schema.Struct({ }), push: Schema.Struct({ status: GitPushStepStatus, - branch: Schema.optional(TrimmedNonEmptyStringSchema), - upstreamBranch: Schema.optional(TrimmedNonEmptyStringSchema), + branch: Schema.optional(GitRefName), + upstreamBranch: Schema.optional(GitRefName), setUpstream: Schema.optional(Schema.Boolean), }), pr: Schema.Struct({ status: GitPrStepStatus, url: Schema.optional(Schema.String), number: Schema.optional(PositiveInt), - baseBranch: Schema.optional(TrimmedNonEmptyStringSchema), - headBranch: Schema.optional(TrimmedNonEmptyStringSchema), + baseBranch: Schema.optional(GitRefName), + headBranch: Schema.optional(GitRefName), title: Schema.optional(TrimmedNonEmptyStringSchema), }), toast: GitRunStackedActionToast, @@ -356,8 +357,8 @@ export type GitRunStackedActionResult = typeof GitRunStackedActionResult.Type; export const VcsPullResult = Schema.Struct({ status: Schema.Literals(["pulled", "skipped_up_to_date"]), - refName: TrimmedNonEmptyStringSchema, - upstreamRef: TrimmedNonEmptyStringSchema.pipe(Schema.NullOr), + refName: GitRefName, + upstreamRef: GitRefName.pipe(Schema.NullOr), }); export type VcsPullResult = typeof VcsPullResult.Type; @@ -430,8 +431,8 @@ export class GitPullRequestMaterializationError extends Schema.TaggedError Date: Mon, 23 Nov 2026 01:03:32 -0600 Subject: [PATCH 297/324] fix(cli): expand ~ paths in t3 thread --output-schema (#41271) Co-authored-by: Julius Marminge --- apps/server/src/cli/thread.test.ts | 16 ++++++++++++++++ apps/server/src/cli/thread.ts | 6 ++++-- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/apps/server/src/cli/thread.test.ts b/apps/server/src/cli/thread.test.ts index bb0906a9c6919..3e38b6885e9d9 100644 --- a/apps/server/src/cli/thread.test.ts +++ b/apps/server/src/cli/thread.test.ts @@ -27,6 +27,7 @@ import { latestRunError, launchModelSelection, readLatestMessages, + readOutputSchema, resolveProject, threadCommand, type ThreadTools, @@ -524,6 +525,21 @@ it.effect("start rejects a repeated --option before reaching the server", () => ), ); +it.effect("--output-schema reads a ~/ path from the home directory", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-thread-schema-" }); + yield* fs.writeFileString(path.join(home, "schema.json"), '{"type":"object"}'); + + const output = yield* readOutputSchema(Option.some("~/schema.json")).pipe( + Effect.provideService(HostProcess.HomeDirectory, home), + ); + + assert.deepStrictEqual(output, { outputSchema: { type: "object" } }); + }).pipe(Effect.provide(NodeServices.layer)), +); + /** Serves t3_thread_read pages the way the server does: positions count every item. */ const timelineTools = (types: ReadonlyArray) => { const items = types.map((type, position) => ({ position, itemId: `item-${position}`, type })); diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts index 1d81dcc6bd7cb..f57f1eed163f4 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -846,14 +846,16 @@ const outputSchemaFlag = Flag.String("output-schema").pipe( const decodeOutputSchema = Schema.decodeUnknownEffect( Schema.fromJsonString(Schema.Record(Schema.String, Schema.Json)), ); -const readOutputSchema = Effect.fn("cli.thread.readOutputSchema")(function* ( +export const readOutputSchema = Effect.fn("cli.thread.readOutputSchema")(function* ( path: Option.Option, ) { if (Option.isNone(path)) return {}; const fileSystem = yield* FileSystem.FileSystem; const usage = () => new ThreadUsageError({ detail: `${path.value} does not hold a JSON Schema object.` }); - const text = yield* fileSystem.readFileString(path.value).pipe(Effect.mapError(usage)); + const text = yield* fileSystem + .readFileString(yield* expandHomePath(path.value)) + .pipe(Effect.mapError(usage)); return { outputSchema: yield* decodeOutputSchema(text).pipe(Effect.mapError(usage)) }; }); const messageArgument = Argument.String("message").pipe( From c8f8ad17ac50f4edfbc138969e1154fc0678494f Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 01:11:26 -0600 Subject: [PATCH 298/324] fix(web): RTF previews open files that declare code page 0 or 866 (#41277) Co-authored-by: Julius Marminge --- apps/web/src/components/files/FilePreviewPanel.test.ts | 8 ++++++++ apps/web/src/components/files/extendedDocumentPreview.ts | 2 ++ 2 files changed, 10 insertions(+) diff --git a/apps/web/src/components/files/FilePreviewPanel.test.ts b/apps/web/src/components/files/FilePreviewPanel.test.ts index c2b6aa0b306d7..53783c7ded6a3 100644 --- a/apps/web/src/components/files/FilePreviewPanel.test.ts +++ b/apps/web/src/components/files/FilePreviewPanel.test.ts @@ -296,6 +296,14 @@ Third}`; if (mac.type !== "document") throw new Error("Expected document"); expect(mac.pages[0]!.html).toBe("

    Café Crème

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

    Café

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

    Привет

    "], + ] as const) { + const decoded = openRtf(bytes(rtf)); + if (decoded.type !== "document") throw new Error("Expected document"); + expect(decoded.pages[0]!.html).toBe(expected); + } expect(() => openRtf(bytes(String.raw`{\rtf1\ansicpg99999 text}`))).toThrow( expect.objectContaining({ code: "rtf-code-page" }), ); diff --git a/apps/web/src/components/files/extendedDocumentPreview.ts b/apps/web/src/components/files/extendedDocumentPreview.ts index f107ea0266043..d0c6bea968de1 100644 --- a/apps/web/src/components/files/extendedDocumentPreview.ts +++ b/apps/web/src/components/files/extendedDocumentPreview.ts @@ -704,6 +704,8 @@ export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { const label = ( { + 0: "windows-1252", + 866: "ibm866", 65001: "utf-8", 932: "shift_jis", 936: "gbk", From 0d2d6a0233ff8e84c2ee287d4a9533633d7acff3 Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:41:39 +0530 Subject: [PATCH 299/324] fix(shared): composer file links to names with # ? & ' , % ! ~ open after sending (#41270) Co-authored-by: Julius Marminge --- .../shared/src/composerInlineTokens.test.ts | 27 +++++++++++++ packages/shared/src/composerInlineTokens.ts | 2 + packages/shared/src/composerTrigger.ts | 26 ++++++++++++- packages/shared/src/markdownLinks.test.ts | 16 ++++++++ ...-mention-punctuated-name-opens-file.e2e.ts | 39 +++++++++++++++++++ 5 files changed, 109 insertions(+), 1 deletion(-) create mode 100644 scripts/scenarios/sent-file-mention-punctuated-name-opens-file.e2e.ts diff --git a/packages/shared/src/composerInlineTokens.test.ts b/packages/shared/src/composerInlineTokens.test.ts index c8c17b84a9b7b..bd50d1d345b9e 100644 --- a/packages/shared/src/composerInlineTokens.test.ts +++ b/packages/shared/src/composerInlineTokens.test.ts @@ -201,6 +201,33 @@ describe("collectComposerInlineTokens", () => { ]); }); + // regression: #41223 the composer's `./` is not part of the mention's path + it.each([ + "C#/Program.cs", + "docs/R&D/notes.md", + "docs/Bob's notes.md", + "docs/a,b.ts", + "docs/100%.md", + "docs/why?.md", + "icon@2x.png", + ])("reads a link to the punctuated file %s as that file's path", (path) => { + const link = serializeComposerFileLink(path); + expect(collectComposerInlineTokens(`fix ${link} please`)).toMatchObject([ + { type: "mention", value: path, source: link }, + ]); + }); + + // regression: #41223 a `./` the author wrote keeps its meaning, even where the parser rejects the rest + it.each([ + ["[draft:notes.md](./draft:notes.md)", "./draft:notes.md"], + ["[scratch](./%2Fscratch)", ".//scratch"], + ["[a.ts](./src/a.ts)", "./src/a.ts"], + ])("keeps the authored link %s as its own path", (link, value) => { + expect(collectComposerInlineTokens(`fix ${link} please`)).toMatchObject([ + { type: "mention", value, source: link }, + ]); + }); + it.each(["app/routes/posts.$postId.tsx", "pages/posts/[id].tsx"])( "preserves a confirmed TeX-like pill when its trailing delimiter is removed: %s", (path) => { diff --git a/packages/shared/src/composerInlineTokens.ts b/packages/shared/src/composerInlineTokens.ts index 80a1b4d6916ae..f09ada6874a24 100644 --- a/packages/shared/src/composerInlineTokens.ts +++ b/packages/shared/src/composerInlineTokens.ts @@ -1,3 +1,4 @@ +import { composerFileLinkPath } from "./composerTrigger.ts"; import { fileBasename } from "./path.ts"; /** The formulas a Markdown parser finds in text, as source offsets. */ @@ -57,6 +58,7 @@ function collectMentionTokens(text: string): ComposerInlineToken[] { try { path = decodeURIComponent(encodedPath); } catch {} + path = composerFileLinkPath(encodedPath, path); const separatorIndex = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")); const basename = separatorIndex >= 0 ? path.slice(separatorIndex + 1) : path; const hasExternalScheme = URI_SCHEME_REGEX.test(path) && !WINDOWS_DRIVE_PATH_REGEX.test(path); diff --git a/packages/shared/src/composerTrigger.ts b/packages/shared/src/composerTrigger.ts index 2a95d6b34cd0a..0aef14469813a 100644 --- a/packages/shared/src/composerTrigger.ts +++ b/packages/shared/src/composerTrigger.ts @@ -1,3 +1,5 @@ +import { parseMarkdownFileLink } from "./markdownLinks.ts"; + export type ComposerTriggerKind = "path" | "pull-request" | "slash-command" | "skill"; export type ComposerSlashCommand = "model" | "plan" | "default"; @@ -28,9 +30,31 @@ function encodeMarkdownLinkDestination(path: string): string { .replaceAll("\\", "%5C"); } +const URI_OR_ROOTED_PATH_PATTERN = /^(?:[a-z][a-z\d+.-]*:|[\\/])/i; + +// A relative destination the parser rejects (`C%23/Program.cs`) gets `./`, as codexFileCitations does. +function needsDotSlashPrefix(path: string): boolean { + return ( + path.length > 0 && + !parseMarkdownFileLink(encodeMarkdownLinkDestination(path)) && + !URI_OR_ROOTED_PATH_PATTERN.test(path) + ); +} + export function serializeComposerFileLink(path: string): string { const label = escapeMarkdownLinkLabel(composerFileLinkBasename(path)); - return `[${label}](${encodeMarkdownLinkDestination(path)})`; + const destination = encodeMarkdownLinkDestination(path); + return `[${label}](${needsDotSlashPrefix(path) ? `./${destination}` : destination})`; +} + +/** The file a composer link names. Drops only the `./` serializeComposerFileLink adds, not one the author wrote. */ +export function composerFileLinkPath(encodedDestination: string, decodedPath: string): string { + if (!encodedDestination.startsWith("./")) return decodedPath; + const bare = decodedPath.slice(2); + return needsDotSlashPrefix(bare) && + encodeMarkdownLinkDestination(bare) === encodedDestination.slice(2) + ? bare + : decodedPath; } function clampCursor(text: string, cursor: number): number { diff --git a/packages/shared/src/markdownLinks.test.ts b/packages/shared/src/markdownLinks.test.ts index 80204d903892b..27af706363367 100644 --- a/packages/shared/src/markdownLinks.test.ts +++ b/packages/shared/src/markdownLinks.test.ts @@ -95,6 +95,22 @@ describe("parseMarkdownFileLink", () => { expect(parseMarkdownFileLink(destination ?? "")?.path).toBe(path); }); + // regression: #41223 names the parser rejects bare; the composer adds `./` to them + it.each([ + "C#/Program.cs", + "docs/R&D/notes.md", + "docs/Bob's notes.md", + "docs/a,b.ts", + "docs/100%.md", + "docs/why?.md", + "icon@2x.png", + ])("resolves the composer's link to %s", (path) => { + const destination = /\]\((.*)\)$/.exec(serializeComposerFileLink(path))?.[1]; + expect(resolveMarkdownFileLinkTarget(destination ?? "", "/workspace/project")).toBe( + `/workspace/project/${path}`, + ); + }); + it.each([ "https://example.com/docs", "/chat/settings#L3", diff --git a/scripts/scenarios/sent-file-mention-punctuated-name-opens-file.e2e.ts b/scripts/scenarios/sent-file-mention-punctuated-name-opens-file.e2e.ts new file mode 100644 index 0000000000000..eda9c9f9a1e29 --- /dev/null +++ b/scripts/scenarios/sent-file-mention-punctuated-name-opens-file.e2e.ts @@ -0,0 +1,39 @@ +/// +// The DOM lib types the function this scenario runs in the page. +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +const FILE = "C#/Program.cs"; + +test( + "An @-mention of a file whose folder has # opens it after the message is sent", + WEB, + async ({ t3, app, screen, browser }) => { + // The editor renders in a shadow root that locators do not reach. + const editorText = () => + browser.evaluate(() => { + for (const host of document.querySelectorAll("*")) { + const content = host.shadowRoot?.querySelector("[data-content]"); + if (content) return content.textContent ?? ""; + } + return null; + }); + + const project = await t3.project("demo", { [FILE]: "static void Main() {}\nProgram body\n" }); + const thread = await t3.thread({ project, title: "Mention", messages: ["Show me around"] }); + await t3.open(thread); + + const composer = screen.getByRole("textbox"); + await composer.pressSequentially("Review @Program"); + await screen.getByRole("option", "Program.cs", { exact: false }).tap(); + await browser.keyboard.press("Enter"); + + const link = screen.getByRole("link", "Program.cs"); + await link.waitFor(); + await app.screenshot("sent-message"); + await link.tap(); + await expect.poll(editorText).toContain("Program body"); + await app.screenshot("file-opened"); + }, +); From 9f24cac6d42f99e92569b7cbd97ec07932f232d8 Mon Sep 17 00:00:00 2001 From: Kwan Li <71382503+Kwan-Li@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:13:06 +1000 Subject: [PATCH 300/324] fix(web): No project drafts no longer offer New worktree (#41269) Co-authored-by: Julius Marminge --- .../components/BranchToolbar.logic.test.ts | 14 +++ .../web/src/components/BranchToolbar.logic.ts | 10 ++ apps/web/src/components/BranchToolbar.tsx | 99 +++++++++++-------- apps/web/src/components/ChatView.tsx | 11 ++- .../chat/ThreadDetailsPanel.browser.test.tsx | 48 +++++++-- .../components/chat/ThreadDetailsPanel.tsx | 4 + 6 files changed, 135 insertions(+), 51 deletions(-) diff --git a/apps/web/src/components/BranchToolbar.logic.test.ts b/apps/web/src/components/BranchToolbar.logic.test.ts index c6006d36295db..05e49aa667b88 100644 --- a/apps/web/src/components/BranchToolbar.logic.test.ts +++ b/apps/web/src/components/BranchToolbar.logic.test.ts @@ -21,6 +21,7 @@ import { sanitizeNewRefName, shouldIncludeBranchPickerItem, isBranchHoldCurrent, + offersWorkspaceModes, toBranchActionErrorMessage, } from "./BranchToolbar.logic"; @@ -138,6 +139,19 @@ describe("resolveEffectiveEnvMode", () => { }); }); +describe("offersWorkspaceModes", () => { + it("offers worktrees from a repository or tracked repositories, never in No project", () => { + const folder = { isScratchProject: false, isGitRepo: false, tracksGitRepositories: false }; + expect(offersWorkspaceModes(folder)).toBe(false); + expect(offersWorkspaceModes({ ...folder, isGitRepo: true })).toBe(true); + expect(offersWorkspaceModes({ ...folder, tracksGitRepositories: true })).toBe(true); + // Git status assumes a repository until it loads. + expect(offersWorkspaceModes({ ...folder, isScratchProject: true, isGitRepo: true })).toBe( + false, + ); + }); +}); + describe("resolveLockedWorkspaceLabel", () => { it.each([ ["/home/me/.t3/worktrees/app/t3-ff466c42", "t3-ff466c42"], diff --git a/apps/web/src/components/BranchToolbar.logic.ts b/apps/web/src/components/BranchToolbar.logic.ts index 21e75c4d8ed56..944ebe8b937be 100644 --- a/apps/web/src/components/BranchToolbar.logic.ts +++ b/apps/web/src/components/BranchToolbar.logic.ts @@ -81,6 +81,16 @@ export function shouldShowEnvironmentIndicator(input: { return input.activeEnvironment !== null && !input.activeEnvironment.isPrimary; } +/** Whether a new thread here may choose between Current checkout and New worktree. */ +export function offersWorkspaceModes(input: { + isScratchProject: boolean; + isGitRepo: boolean; + tracksGitRepositories: boolean; +}): boolean { + // No project never has git, even while its status loads and isGitRepo still assumes it does. + return !input.isScratchProject && (input.isGitRepo || input.tracksGitRepositories); +} + export function shouldShowComposerContextStrip(input: { isDraftHeroState: boolean; persistInActiveThreads: boolean; diff --git a/apps/web/src/components/BranchToolbar.tsx b/apps/web/src/components/BranchToolbar.tsx index 43ea99b07480b..d42756a7daa5f 100644 --- a/apps/web/src/components/BranchToolbar.tsx +++ b/apps/web/src/components/BranchToolbar.tsx @@ -158,6 +158,8 @@ interface RunContextSelectorProps { displayMode?: "toolbar" | "panel"; workspaceRoot?: string; forceNewWorktree: boolean; + /** False when the folder has no repository a worktree could come from. */ + offersWorkspaceModes: boolean; autoEnvironmentLabel?: string | undefined; onAutoEnvironment?: (() => void) | undefined; envLocked: boolean; @@ -180,7 +182,8 @@ interface RunContextSelectorProps { const RunContextSelector = memo(function RunContextSelector({ displayMode = "toolbar", workspaceRoot, - forceNewWorktree, + forceNewWorktree: requestedForceNewWorktree, + offersWorkspaceModes, autoEnvironmentLabel, onAutoEnvironment, envLocked, @@ -190,7 +193,7 @@ const RunContextSelector = memo(function RunContextSelector({ showEnvironmentPicker, showEnvironmentIndicator, onEnvironmentChange, - effectiveEnvMode, + effectiveEnvMode: requestedEnvMode, activeWorktreePath, onEnvModeChange, previousWorktreeLabel, @@ -204,10 +207,13 @@ const RunContextSelector = memo(function RunContextSelector({ const composerFloatingLayerProps = useComposerMenuProps(); const activeEnvironment = availableEnvironments?.find((env) => env.environmentId === environmentId) ?? null; + // A folder no worktree can come from runs threads in place, whatever mode was requested. + const forceNewWorktree = offersWorkspaceModes && requestedForceNewWorktree; + const effectiveEnvMode = offersWorkspaceModes ? requestedEnvMode : "local"; const WorkspaceIcon = effectiveEnvMode === "worktree" ? FolderGit2Icon - : activeWorktreePath + : activeWorktreePath && offersWorkspaceModes ? FolderGitIcon : FolderIcon; const workspaceLabel = forceNewWorktree @@ -218,7 +224,8 @@ const RunContextSelector = memo(function RunContextSelector({ ? resolveEnvModeLabel("worktree", m) : resolveCurrentWorkspaceLabel(activeWorktreePath, m); const isPanel = displayMode === "panel"; - const isLocked = envLocked || (envModeLocked && (!isPanel || !showEnvironmentPicker)); + const workspaceModesLocked = envModeLocked || !offersWorkspaceModes; + const isLocked = envLocked || (workspaceModesLocked && (!isPanel || !showEnvironmentPicker)); const workspacePath = forceNewWorktree || (effectiveEnvMode === "worktree" && !activeWorktreePath) ? null @@ -328,7 +335,7 @@ const RunContextSelector = memo(function RunContextSelector({ data-composer-context-control data-composer-shortcut={[ showEnvironmentPicker && !envLocked ? "composer.host" : "", - !envModeLocked ? "composer.workspace" : "", + !workspaceModesLocked ? "composer.workspace" : "", ].join(" ")} > {triggerContent} @@ -419,46 +426,52 @@ const RunContextSelector = memo(function RunContextSelector({ ) : null} - + {offersWorkspaceModes ? : null} ) : null} - - - Workspace - - { - if (value === "previous-worktree") { - onUsePreviousWorktree(); - return; - } - onEnvModeChange(value as EnvMode); - }} - > - - - {activeWorktreePath ? ( - - ) : ( - - )} - - - - - - - {resolveEnvModeLabel("worktree", m)} - - - {previousWorktreeLabel ? ( - - + {offersWorkspaceModes ? ( + + + Workspace + + { + if (value === "previous-worktree") { + onUsePreviousWorktree(); + return; + } + onEnvModeChange(value as EnvMode); + }} + > + + + {activeWorktreePath ? ( + + ) : ( + + )} + + + + + + + {resolveEnvModeLabel("worktree", m)} + - ) : null} - - + {previousWorktreeLabel ? ( + + + + ) : null} + + + ) : null} ); @@ -740,6 +753,7 @@ export const BranchToolbar = memo(function BranchToolbar({ displayMode="panel" workspaceRoot={activeProject.workspaceRoot} forceNewWorktree={forceNewWorktree} + offersWorkspaceModes={showGitControls} autoEnvironmentLabel={autoEnvironmentLabel} onAutoEnvironment={onAutoEnvironment} envLocked={envLocked} @@ -790,6 +804,7 @@ export const BranchToolbar = memo(function BranchToolbar({
    }) { +const machines = (["This Mac", "Server"] as const).map((label, index) => ({ + environmentId: EnvironmentId.make(index === 0 ? "environment" : "other"), + projectId: ProjectId.make("project"), + label, + isPrimary: index === 0, + machine: "server" as const, +})); + +function Panel({ + fixture, + draftEnvMode, + onMachines = false, +}: { + fixture: ReturnType; + /** Renders an unsent draft in this mode instead of a started thread. */ + draftEnvMode?: "local" | "worktree"; + onMachines?: boolean; +}) { const noop = () => {}; const scriptResult = async () => ({ ok: true }) as never; return ( @@ -149,8 +166,8 @@ function Panel({ fixture }: { fixture: ReturnType }) { threadId={threadRef.threadId} projectId={ProjectId.make("project")} composerDraftTarget={threadRef} - worktreePath={state.folder} - isServerThread + worktreePath={draftEnvMode === undefined ? state.folder : null} + isServerThread={draftEnvMode === undefined} activeProjectName={state.workspaceRoot === SCRATCH_ROOT ? "No project" : "plain"} activeProjectScripts={undefined} preferredScriptId={null} @@ -161,10 +178,12 @@ function Panel({ fixture }: { fixture: ReturnType }) { gitCwd={state.folder} workspaceMutationId={null} isGitRepo={false} - envLocked - availableEnvironments={[]} + offersWorkspaceModes={false} + envLocked={draftEnvMode === undefined} + availableEnvironments={onMachines ? machines : []} + {...(onMachines ? { onEnvironmentChange: noop } : {})} onEnvModeChange={noop} - envMode="local" + envMode={draftEnvMode ?? "local"} startFromOrigin={false} onStartFromOriginChange={noop} onComposerFocusRequest={noop} @@ -191,6 +210,23 @@ it("offers no git controls in a No project thread, but shows its linked pull req .not.toBeInTheDocument(); }); +it("shows Current checkout where no worktree can come from, even when New worktree is the default", async () => { + using fixture = setup({ workspaceRoot: SCRATCH_ROOT, folder: SCRATCH_ROOT }); + await using _screen = await render(); + await expect.element(page.getByLabelText("Run context: Current checkout")).toBeVisible(); + await expect.element(page.getByRole("button", { name: /Run context/ })).not.toBeInTheDocument(); +}); + +it("offers only machines where no worktree can come from and several machines exist", async () => { + using fixture = setup({ workspaceRoot: SCRATCH_ROOT, folder: SCRATCH_ROOT }); + await using _screen = await render( + , + ); + await page.getByRole("button", { name: "Run context: This Mac, Current checkout" }).click(); + await expect.element(page.getByText("Run on")).toBeVisible(); + await expect.element(page.getByText("New worktree")).not.toBeInTheDocument(); +}); + it("shows a linked pull request in a folder that is not a git repository", async () => { using fixture = setup({ workspaceRoot: "/work/plain", diff --git a/apps/web/src/components/chat/ThreadDetailsPanel.tsx b/apps/web/src/components/chat/ThreadDetailsPanel.tsx index 085815bed02cf..69c3cd7133aff 100644 --- a/apps/web/src/components/chat/ThreadDetailsPanel.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPanel.tsx @@ -71,6 +71,8 @@ interface ThreadDetailsPanelProps extends Pick< gitCwd: string | null; workspaceMutationId: string | null; isGitRepo: boolean; + /** False when no worktree can come from this folder, so it offers no workspace modes. */ + offersWorkspaceModes: boolean; envLocked: boolean; availableEnvironments: readonly EnvironmentOption[]; autoEnvironmentLabel?: string | undefined; @@ -220,6 +222,8 @@ export function ThreadDetailsPanel(props: ThreadDetailsPanelProps) { autoEnvironmentLabel={props.autoEnvironmentLabel} onAutoEnvironment={props.onAutoEnvironment} {...branchToolbarProps} + // Workspace modes follow the composer's rule, not this folder's own status. + showGitControls={props.offersWorkspaceModes} /> ) : null} From 3b3255ccecf75db4c2da996eb153dca77373ff35 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 23:37:53 -0800 Subject: [PATCH 301/324] fix(server): queued messages stay visible when a restart cancels their started run (#41307) --- .../orchestration-v2/ProjectionStore.test.ts | 17 +++ .../src/orchestration-v2/ProjectionStore.ts | 23 +++- .../src/orchestration-v2/ThreadFind.test.ts | 3 +- .../src/orchestration-v2/ThreadSearch.test.ts | 20 +++- .../src/orchestration-v2/ThreadSearch.ts | 5 +- .../state/orchestrationV2Projection.test.ts | 8 +- .../src/orchestrationV2Timeline.test.ts | 110 ++++++++++-------- .../shared/src/orchestrationV2Timeline.ts | 17 +-- 8 files changed, 137 insertions(+), 66 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index f13f3f05409ba..636e69e7574b0 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -5679,6 +5679,23 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { ); } + // Recovery cancels a run that had started; its delivered queued message stays. + const setCancelledStartedAt = (startedAt: string | null) => sql` + UPDATE orchestration_v2_projection_runs + SET payload_json = json_set(payload_json, '$.startedAt', ${startedAt}) + WHERE run_id = ${cancelledRunId} + `; + yield* setCancelledStartedAt(nowIso); + const startedCancelledSnapshot = yield* projectionStore.getThreadSnapshotWindow(threadId, { + rowLimit: sqlPageLimit, + }); + assert.isTrue( + startedCancelledSnapshot.projection.visibleTurnItems.some((row) => + String(row.sourceItemId).includes(":cancelled:"), + ), + ); + yield* setCancelledStartedAt(null); + // A steer moves the cancelled queued message outside the window. const steeredItemId = "turn-item:bounded-sql-history:steered-output"; const steeredRunId = RunId.make("run:bounded-sql-history:1000"); diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 2278284d7fde7..84458e644e509 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -3461,6 +3461,7 @@ export const layer: Layer.Layer = ) ) AND json_extract(item.payload_json, '$.inputIntent') = 'queued_turn' + AND (run.status = 'queued' OR json_extract(run.payload_json, '$.startedAt') IS NULL) ) AND ( ${window.requiredRunId ?? null} IS NULL @@ -7374,7 +7375,9 @@ export const layer: Layer.Layer = const [hidingRuns, superseded] = yield* Effect.all([ sql<{ id: RunId; status: OrchestrationV2Run["status"] }>` SELECT run_id AS id, status FROM orchestration_v2_projection_runs - WHERE thread_id = ${threadId} AND status IN ('rolled_back', 'queued', 'cancelled')`, + WHERE thread_id = ${threadId} + AND (status IN ('rolled_back', 'queued') + OR (status = 'cancelled' AND json_extract(payload_json, '$.startedAt') IS NULL))`, sql<{ runId: RunId; rootNodeId: NodeId; status: "superseded" }>` SELECT run_id AS runId, root_node_id AS rootNodeId, status FROM orchestration_v2_projection_run_attempts @@ -7396,8 +7399,8 @@ export const layer: Layer.Layer = })), }); // Only these runs can hide rows: every row of a rolled-back run, the queued turn of a - // queued or cancelled run, and the stop result of a replaced attempt. So the hidden rows - // are found without reading the thread. + // queued run or a cancelled one that never started, and the stop result of a replaced attempt. + // So the hidden rows are found without reading the thread. const stoppedRuns = new Set(stopRequests.map((row) => row.run_id)); const runsWithStatus = (...statuses: ReadonlyArray) => hidingRuns.flatMap((run) => (statuses.includes(run.status) ? [String(run.id)] : [])); @@ -8672,6 +8675,13 @@ export const layer: Layer.Layer = AND held.type = 'user_message' AND json_valid(held.payload_json) AND json_extract(held.payload_json, '$.inputIntent') = 'queued_turn' + -- A started run delivered its queued input; only held rows load the run's payload. + AND NOT EXISTS ( + SELECT 1 FROM orchestration_v2_projection_runs AS started + WHERE started.run_id = held.run_id + AND started.status <> 'queued' + AND json_extract(started.payload_json, '$.startedAt') IS NOT NULL + ) ) ELSE 0 END AS item_count @@ -8692,6 +8702,13 @@ export const layer: Layer.Layer = AND held.type = 'user_message' AND json_valid(held.payload_json) AND json_extract(held.payload_json, '$.inputIntent') = 'queued_turn' + -- A started run delivered its queued input; only held rows load the run's payload. + AND NOT EXISTS ( + SELECT 1 FROM orchestration_v2_projection_runs AS started + WHERE started.run_id = held.run_id + AND started.status <> 'queued' + AND json_extract(started.payload_json, '$.startedAt') IS NOT NULL + ) ) END) FROM orchestration_v2_projection_runs r INDEXED BY orchestration_v2_projection_runs_hidden_items_idx diff --git a/apps/server/src/orchestration-v2/ThreadFind.test.ts b/apps/server/src/orchestration-v2/ThreadFind.test.ts index 6c6d0232bfce7..60c91be1065c9 100644 --- a/apps/server/src/orchestration-v2/ThreadFind.test.ts +++ b/apps/server/src/orchestration-v2/ThreadFind.test.ts @@ -651,7 +651,8 @@ describe("V2 thread find", () => { Effect.gen(function* () { const projection = yield* setup; const queuedRunId = RunId.make("queued:cancelled"); - yield* commit([run(threadId, queuedRunId, 2, "cancelled")]); + const cancelled = run(threadId, queuedRunId, 2, "cancelled"); + yield* commit([{ ...cancelled, payload: { ...cancelled.payload, startedAt: null } }]); const queued = item("cancelled", 1, "needle", "user_message"); if (queued.type !== "user_message") return; const answer = item("async-answer:question", 2, "needle", "user_message"); diff --git a/apps/server/src/orchestration-v2/ThreadSearch.test.ts b/apps/server/src/orchestration-v2/ThreadSearch.test.ts index 399224533089d..e545d40633643 100644 --- a/apps/server/src/orchestration-v2/ThreadSearch.test.ts +++ b/apps/server/src/orchestration-v2/ThreadSearch.test.ts @@ -746,7 +746,8 @@ it.layer(layerTest)("ThreadSearch filters before it ranks", (it) => { const queued = ThreadId.make("thread:queued"); const stopped = ThreadId.make("thread:stopped"); const recovered = ThreadId.make("thread:recovered"); - const run = (owner: ThreadId, status: "rolled_back" | "cancelled") => + const restarted = ThreadId.make("thread:restarted"); + const run = (owner: ThreadId, status: "rolled_back" | "cancelled", started = true) => ({ id: EventId.make(`run:${owner}`), type: "run.created", @@ -767,7 +768,7 @@ it.layer(layerTest)("ThreadSearch filters before it ranks", (it) => { activeAttemptId: null, status, requestedAt: at(1), - startedAt: at(1), + startedAt: started ? at(1) : null, completedAt: at(2), checkpointId: null, contextHandoffId: null, @@ -818,7 +819,7 @@ it.layer(layerTest)("ThreadSearch filters before it ranks", (it) => { runId: RunId.make(`run:${rewound}`), }), thread(queued, project), - run(queued, "cancelled"), + run(queued, "cancelled", false), message(queued, "queued-prompt", "user", "then mount the albatross drive", { runId: RunId.make(`run:${queued}`), }), @@ -840,6 +841,13 @@ it.layer(layerTest)("ThreadSearch filters before it ranks", (it) => { runId: RunId.make(`run:${recovered}`), }), shown(recovered, "recovered-reply", "reply"), + // A restart cancels a turn that already took its queued prompt. + thread(restarted, project), + run(restarted, "cancelled"), + message(restarted, "delivered-prompt", "user", "then label the albatross drive", { + runId: RunId.make(`run:${restarted}`), + }), + shown(restarted, "delivered-prompt", "queued_turn"), ], projections.apply, { discard: true }, @@ -848,7 +856,11 @@ it.layer(layerTest)("ThreadSearch filters before it ranks", (it) => { (yield* search.search({ query: "albatross" })).matches .map((match) => match.messageId) .sort(), - [MessageId.make("recovered-reply"), MessageId.make("stopped-prompt")], + [ + MessageId.make("delivered-prompt"), + MessageId.make("recovered-reply"), + MessageId.make("stopped-prompt"), + ], ); }), ); diff --git a/apps/server/src/orchestration-v2/ThreadSearch.ts b/apps/server/src/orchestration-v2/ThreadSearch.ts index 3ad48b26f172d..f3f8c6061dbe7 100644 --- a/apps/server/src/orchestration-v2/ThreadSearch.ts +++ b/apps/server/src/orchestration-v2/ThreadSearch.ts @@ -293,7 +293,10 @@ export const messageHitsQuery = ( SELECT 1 FROM orchestration_v2_projection_turn_items AS items WHERE items.run_id = runs.run_id AND json_extract(items.payload_json, '$.messageId') = messages.message_id - AND json_extract(items.payload_json, '$.inputIntent') IS NOT 'queued_turn' + AND ( + json_extract(items.payload_json, '$.inputIntent') IS NOT 'queued_turn' + OR json_extract(runs.payload_json, '$.startedAt') IS NOT NULL + ) ) ) ) diff --git a/packages/client-runtime/src/state/orchestrationV2Projection.test.ts b/packages/client-runtime/src/state/orchestrationV2Projection.test.ts index 16301157a6a4e..6436de7c7d907 100644 --- a/packages/client-runtime/src/state/orchestrationV2Projection.test.ts +++ b/packages/client-runtime/src/state/orchestrationV2Projection.test.ts @@ -486,7 +486,13 @@ describe("applyOrchestrationV2ProjectionEvent", () => { it("hides a steer that fell back to the queue until its run starts", () => { const queuedRunId = RunId.make("run-requeued-steer"); - const queuedRun = { ...run, id: queuedRunId, ordinal: 2, status: "queued" } as const; + const queuedRun = { + ...run, + id: queuedRunId, + ordinal: 2, + status: "queued", + startedAt: null, + } as const; const reply = commandItem("item-reply", "reply", 102); const steer: OrchestrationV2TurnItem = { id: TurnItemId.make("item-steer"), diff --git a/packages/shared/src/orchestrationV2Timeline.test.ts b/packages/shared/src/orchestrationV2Timeline.test.ts index c2b7a0c920159..18a59c28a8fbe 100644 --- a/packages/shared/src/orchestrationV2Timeline.test.ts +++ b/packages/shared/src/orchestrationV2Timeline.test.ts @@ -1,4 +1,5 @@ import { NodeId, RunId } from "@t3tools/contracts"; +import { DateTime } from "effect"; import { describe, expect, it } from "vite-plus/test"; import { @@ -91,62 +92,73 @@ describe.each([ ).toBe(true); }); - it.each([ + it.each<{ + status: VisibilityInput["runs"][number]["status"]; + startedAt?: string; + hidden: string[]; + }>([ ...ordinaryStatuses.map((status) => ({ status, hidden: [] })), { status: "queued", hidden: ["queued"] }, { status: "cancelled", hidden: ["queued"] }, + { status: "cancelled", startedAt: "2026-11-23T06:11:54.535Z", hidden: [] }, { status: "rolled_back", hidden: ["queued", "start", "steer", "promoted", "legacy", "assistant", "request", "result"], }, - ] satisfies ReadonlyArray<{ - status: VisibilityInput["runs"][number]["status"]; - hidden: string[]; - }>)("keeps the correct transcript rows for $status runs", ({ status, hidden }) => { - const rows = [ - { id: "queued", type: "user_message", inputIntent: "queued_turn", runId, nodeId }, - { id: "start", type: "user_message", inputIntent: "turn_start", runId, nodeId }, - { id: "steer", type: "user_message", inputIntent: "steer", runId, nodeId }, - { - id: "promoted", - type: "user_message", - inputIntent: "promoted_queued_to_steer", - runId, - nodeId, - }, - { id: "legacy", type: "user_message", runId, nodeId }, - { id: "assistant", type: "assistant_message", inputIntent: "queued_turn", runId, nodeId }, - { id: "request", type: "run_interrupt_request", runId, nodeId }, - { id: "result", type: "run_interrupt_result", runId, nodeId }, - { id: "null", type: "user_message", inputIntent: "queued_turn", runId: null, nodeId }, - { - id: "missing", - type: "user_message", - inputIntent: "queued_turn", - runId: otherRunId, - nodeId, - }, - ] satisfies ReadonlyArray; - const input = { - runs: [{ id: runId, status }], - attempts: [], - items: rows, - } satisfies VisibilityInput; - expect(rows.filter((item) => isVisible({ ...input, item })).map((item) => item.id)).toEqual( - [ - "queued", - "start", - "steer", - "promoted", - "legacy", - "assistant", - "request", - "result", - "null", - "missing", - ].filter((id) => !hidden.some((hiddenId) => hiddenId === id)), - ); - }); + ])( + "keeps the correct transcript rows for $status runs (started $startedAt)", + ({ status, startedAt, hidden }) => { + const rows = [ + { id: "queued", type: "user_message", inputIntent: "queued_turn", runId, nodeId }, + { id: "start", type: "user_message", inputIntent: "turn_start", runId, nodeId }, + { id: "steer", type: "user_message", inputIntent: "steer", runId, nodeId }, + { + id: "promoted", + type: "user_message", + inputIntent: "promoted_queued_to_steer", + runId, + nodeId, + }, + { id: "legacy", type: "user_message", runId, nodeId }, + { id: "assistant", type: "assistant_message", inputIntent: "queued_turn", runId, nodeId }, + { id: "request", type: "run_interrupt_request", runId, nodeId }, + { id: "result", type: "run_interrupt_result", runId, nodeId }, + { id: "null", type: "user_message", inputIntent: "queued_turn", runId: null, nodeId }, + { + id: "missing", + type: "user_message", + inputIntent: "queued_turn", + runId: otherRunId, + nodeId, + }, + ] satisfies ReadonlyArray; + const input = { + runs: [ + { + id: runId, + status, + ...(startedAt === undefined ? {} : { startedAt: DateTime.makeUnsafe(startedAt) }), + }, + ], + attempts: [], + items: rows, + } satisfies VisibilityInput; + expect(rows.filter((item) => isVisible({ ...input, item })).map((item) => item.id)).toEqual( + [ + "queued", + "start", + "steer", + "promoted", + "legacy", + "assistant", + "request", + "result", + "null", + "missing", + ].filter((id) => !hidden.some((hiddenId) => hiddenId === id)), + ); + }, + ); it.each([ { name: "empty history", runs: [], attempts: [] }, diff --git a/packages/shared/src/orchestrationV2Timeline.ts b/packages/shared/src/orchestrationV2Timeline.ts index e651dbfb01653..292a0dfbbb8ab 100644 --- a/packages/shared/src/orchestrationV2Timeline.ts +++ b/packages/shared/src/orchestrationV2Timeline.ts @@ -5,7 +5,8 @@ import type { OrchestrationV2UserMessageInputIntent, } from "@t3tools/contracts"; -type TimelineRun = Pick; +type TimelineRun = Pick & + Partial>; type TimelineRunAttempt = Pick; type TimelineTurnItem = Pick & { readonly inputIntent?: OrchestrationV2UserMessageInputIntent; @@ -38,6 +39,11 @@ function isOrchestrationV2SupersededInterrupt(input: { return !hasMatchingRequest; } +// A run that started received its queued input, even if recovery cancelled it later. +function isHeldRun(run: TimelineRun): boolean { + return run.status === "queued" || (run.status === "cancelled" && run.startedAt == null); +} + export function isOrchestrationV2TurnItemVisible(input: { readonly item: TimelineTurnItem; readonly runs: ReadonlyArray; @@ -53,14 +59,12 @@ export function isOrchestrationV2TurnItemVisible(input: { } // A steer can return to the queue before delivery. Keep its retained item out - // of conversation history until its run starts; cancelled queued inputs stay hidden. + // of conversation history until its run starts; cancelled undelivered inputs stay hidden. if ( item.type === "user_message" && item.inputIntent === "queued_turn" && item.runId !== null && - input.runs.some( - (run) => run.id === item.runId && (run.status === "queued" || run.status === "cancelled"), - ) + input.runs.some((run) => run.id === item.runId && isHeldRun(run)) ) { return false; } @@ -79,8 +83,7 @@ export function createOrchestrationV2TurnItemVisibility(input: { }): (item: TimelineTurnItem) => boolean { const statuses = new Map(); for (const run of input.runs) { - if (run.status === "rolled_back" || run.status === "cancelled" || run.status === "queued") - statuses.set(run.id, run.status); + if (run.status === "rolled_back" || isHeldRun(run)) statuses.set(run.id, run.status); else statuses.delete(run.id); } const supersededRoots = new Map< From 9cf81e2a6e717510708713fa951d368095a1de71 Mon Sep 17 00:00:00 2001 From: fixfon <12512757+fixfon@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:39:47 +0300 Subject: [PATCH 302/324] fix(desktop): annotation Select picks elements inside open shadow roots (#23180) Co-authored-by: Julius Marminge --- apps/desktop/src/preview/PickPreload.ts | 18 +-- apps/desktop/src/preview/PickTarget.test.ts | 121 ++++++++++++++++++++ apps/desktop/src/preview/PickTarget.ts | 22 ++++ 3 files changed, 154 insertions(+), 7 deletions(-) create mode 100644 apps/desktop/src/preview/PickTarget.test.ts create mode 100644 apps/desktop/src/preview/PickTarget.ts diff --git a/apps/desktop/src/preview/PickPreload.ts b/apps/desktop/src/preview/PickPreload.ts index c7599d217b1a1..5113617a8f324 100644 --- a/apps/desktop/src/preview/PickPreload.ts +++ b/apps/desktop/src/preview/PickPreload.ts @@ -28,6 +28,7 @@ import { type StrokeGeometry, } from "./AnnotationStroke.ts"; import { previewAnnotationStyles } from "./AnnotationStyles.generated.ts"; +import { pickElementAtPoint } from "./PickTarget.ts"; import { installRecordingCursor } from "./RecordingCursor.ts"; import { DEFAULT_RECORDING_INPUT_OPTIONS } from "./RecordingInput.ts"; import { @@ -320,13 +321,16 @@ function isAnnotationNode(element: Element): boolean { } function pickFromPoint(clientX: number, clientY: number): Element | null { - for (const candidate of document.elementsFromPoint(clientX, clientY)) { - if (!(candidate instanceof Element)) continue; - if (isAnnotationNode(candidate) || candidate.hasAttribute(INPUT_LAYER_ATTRIBUTE)) continue; - if (candidate === document.documentElement || candidate === document.body) continue; - return candidate; - } - return null; + return pickElementAtPoint( + document, + clientX, + clientY, + (element) => + isAnnotationNode(element) || + element.hasAttribute(INPUT_LAYER_ATTRIBUTE) || + element === document.documentElement || + element === document.body, + ); } function describeRawElement(element: Element): string { diff --git a/apps/desktop/src/preview/PickTarget.test.ts b/apps/desktop/src/preview/PickTarget.test.ts new file mode 100644 index 0000000000000..cb245e9565a1c --- /dev/null +++ b/apps/desktop/src/preview/PickTarget.test.ts @@ -0,0 +1,121 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { pickElementAtPoint } from "./PickTarget.ts"; + +// Models the DOM contract the picker relies on: hit-testing covers the whole page, and each +// `elementsFromPoint` retargets the hits against the scope it is called on, like Blink does. +class FakeElement { + shadowRoot: FakeScope | null = null; + readonly label: string; + readonly scope: FakeScope; + + constructor(label: string, scope: FakeScope) { + this.label = label; + this.scope = scope; + scope.members.add(this); + } +} + +class FakeScope { + readonly members = new Set(); + readonly host: FakeElement | null; + private readonly page: FakePage; + + constructor(page: FakePage, host: FakeElement | null) { + this.page = page; + this.host = host; + } + + contains(element: FakeElement): boolean { + return this.members.has(element); + } + + elementsFromPoint(): FakeElement[] { + const elements: FakeElement[] = []; + for (const hit of this.page.hits) { + const element = this.retarget(hit); + if (elements.at(-1) !== element) elements.push(element); + } + if (elements.at(-1) !== this.page.html) elements.push(this.page.html); + return elements; + } + + private retarget(target: FakeElement): FakeElement { + let element = target; + while (element.scope.host && !element.scope.encloses(this)) element = element.scope.host; + return element; + } + + private encloses(scope: FakeScope): boolean { + for (let current: FakeScope | null = scope; current; current = current.host?.scope ?? null) { + if (current === this) return true; + } + return false; + } +} + +class FakePage { + hits: FakeElement[] = []; + readonly overlays = new Set(); + readonly document = new FakeScope(this, null); + readonly html = new FakeElement("html", this.document); + readonly body = new FakeElement("body", this.document); + + attachShadow(host: FakeElement, mode: "open" | "closed"): FakeScope { + const root = new FakeScope(this, host); + if (mode === "open") host.shadowRoot = root; + return root; + } + + pick(): FakeElement | null { + return pickElementAtPoint( + this.document, + 0, + 0, + (element) => this.overlays.has(element) || element === this.html || element === this.body, + ); + } +} + +describe("pickElementAtPoint", () => { + it("picks the element inside an open shadow root instead of its host", () => { + const page = new FakePage(); + const host = new FakeElement("shadow-demo", page.document); + const button = new FakeElement("button", page.attachShadow(host, "open")); + page.hits = [button, host, page.body, page.html]; + + expect(page.pick()?.label).toBe("button"); + }); + + it("falls back to the host when the point misses its shadow content", () => { + const page = new FakePage(); + const host = new FakeElement("shadow-demo", page.document); + page.attachShadow(host, "open"); + page.hits = [host, page.body, page.html]; + + expect(page.pick()?.label).toBe("shadow-demo"); + }); + + it("keeps a closed shadow root opaque", () => { + const page = new FakePage(); + const outerHost = new FakeElement("outer-host", page.document); + const outerRoot = page.attachShadow(outerHost, "open"); + const closedHost = new FakeElement("closed-host", outerRoot); + const secret = new FakeElement("secret", page.attachShadow(closedHost, "closed")); + page.hits = [secret, closedHost, outerHost, page.body, page.html]; + + expect(page.pick()?.label).toBe("closed-host"); + }); + + it("picks the page element beneath the picker overlay, never the overlay", () => { + const page = new FakePage(); + const host = new FakeElement("shadow-demo", page.document); + const button = new FakeElement("button", page.attachShadow(host, "open")); + const overlay = new FakeElement("overlay", page.document); + page.overlays.add(overlay); + const toolbar = new FakeElement("toolbar", page.attachShadow(overlay, "closed")); + page.hits = [toolbar, button, host, page.body, page.html]; + + expect(page.pick()?.label).toBe("button"); + }); +}); diff --git a/apps/desktop/src/preview/PickTarget.ts b/apps/desktop/src/preview/PickTarget.ts new file mode 100644 index 0000000000000..af689a07bedda --- /dev/null +++ b/apps/desktop/src/preview/PickTarget.ts @@ -0,0 +1,22 @@ +interface PickScope { + elementsFromPoint(x: number, y: number): ReadonlyArray; + contains(node: NoInfer): boolean; +} + +// Document hit-testing retargets shadow content to its host, so descend into open roots. +// ShadowRoot.elementsFromPoint still lists the host and the rest of the page (the overlay +// too), so only the root's own elements count. Closed roots expose no shadowRoot. +export function pickElementAtPoint | null }>( + scope: PickScope, + x: number, + y: number, + isExcluded: (element: E) => boolean, +): E | null { + for (const candidate of scope.elementsFromPoint(x, y)) { + if (!scope.contains(candidate) || isExcluded(candidate)) continue; + const inner = + candidate.shadowRoot && pickElementAtPoint(candidate.shadowRoot, x, y, isExcluded); + return inner ?? candidate; + } + return null; +} From 65cd6446233a8001c8c4f8e06cb4eee987cac0e9 Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 01:44:31 -0600 Subject: [PATCH 303/324] fix(web): archive folders with leading or repeated slashes show their names (#41301) Co-authored-by: Julius Marminge --- .../AttachmentFilePreview.browser.test.tsx | 57 ++++++++++++------- .../web/src/components/files/BinaryViewer.tsx | 27 ++++++--- 2 files changed, 54 insertions(+), 30 deletions(-) diff --git a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx index 9316935ba2df0..77e339925c97e 100644 --- a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx +++ b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx @@ -238,37 +238,52 @@ describe("bounded binary previews", () => { } }); - it("can leave an archive folder with a repeated separator", async () => { + it("names archive folders whose paths have leading or repeated slashes", async () => { const bytes = new Uint8Array(2048); const write = (offset: number, value: string) => bytes.set(new TextEncoder().encode(value), offset); - write(0, "a//hello.txt"); - write(124, "00000000014\0"); - bytes.fill(32, 148, 156); - write(156, "0"); - write( - 148, - bytes - .subarray(0, 512) - .reduce((sum, byte) => sum + byte, 0) - .toString(8) - .padStart(6, "0") + "\0 ", - ); - write(512, "nested hello"); + const member = (offset: number, name: string, content: string) => { + write(offset, name); + write(offset + 124, content.length.toString(8).padStart(11, "0") + "\0"); + bytes.fill(32, offset + 148, offset + 156); + write(offset + 156, "0"); + write( + offset + 148, + bytes + .subarray(offset, offset + 512) + .reduce((sum, byte) => sum + byte, 0) + .toString(8) + .padStart(6, "0") + "\0 ", + ); + write(offset + 512, content); + }; + member(0, "/a//hello.txt", "nested hello"); + member(1024, "a/hello.txt", "plain hello"); const src = URL.createObjectURL(new Blob([bytes])); try { await using screen = await render(); - const child = () => screen.container.querySelector("tbody button"); - await vi.waitFor(() => expect(child()?.textContent).toBe("a"), 10_000); - await act(() => child()!.click()); - await act(() => child()!.click()); - await vi.waitFor(() => expect(child()?.textContent).toBe("hello.txt")); + const buttons = () => [ + ...screen.container.querySelectorAll("tbody button"), + ]; + const rows = () => buttons().map((button) => button.textContent); + const back = () => + screen.container.querySelector('[aria-label="Back to archive"]')!; + const preview = () => screen.container.querySelector("pre")?.textContent; + await vi.waitFor(() => expect(rows()).toEqual(["a"]), 10_000); + await act(() => buttons()[0]!.click()); + await vi.waitFor(() => expect(rows()).toEqual(["hello.txt", "hello.txt"])); + await act(() => buttons()[0]!.click()); + await vi.waitFor(() => expect(preview()).toContain("nested hello"), 10_000); + await act(() => back().click()); + await act(() => buttons()[1]!.click()); + await vi.waitFor(() => expect(preview()).toContain("plain hello"), 10_000); + await act(() => back().click()); + await vi.waitFor(() => expect(rows()).toEqual(["hello.txt", "hello.txt"])); const parent = () => screen.container.querySelector('[aria-label="Parent folder"]')!; await act(() => parent().click()); - await act(() => parent().click()); expect(parent().disabled).toBe(true); - expect(child()?.textContent).toBe("a"); + expect(rows()).toEqual(["a"]); } finally { URL.revokeObjectURL(src); } diff --git a/apps/web/src/components/files/BinaryViewer.tsx b/apps/web/src/components/files/BinaryViewer.tsx index 0151e9f08c0a7..63a2f119056c1 100644 --- a/apps/web/src/components/files/BinaryViewer.tsx +++ b/apps/web/src/components/files/BinaryViewer.tsx @@ -202,19 +202,28 @@ export default function BinaryViewer(props: { }; const children = new Map< string, - { path: string; directory: boolean; size: number; modified: string | null } + { path: string; entryPath: string; directory: boolean; size: number; modified: string | null } >(); for (const item of archive?.entries ?? []) { - if (!item.path.startsWith(folder)) continue; - const rest = item.path.slice(folder.length).replace(/\/$/, ""); + const name = item.path.replace(/^\/+|\/+$/g, "").replace(/\/{2,}/g, "/"); + if (!name.startsWith(folder)) continue; + const rest = name.slice(folder.length); if (!rest) continue; const slash = rest.indexOf("/"); - const path = slash < 0 ? item.path.replace(/\/$/, "") : `${folder}${rest.slice(0, slash)}`; + const path = slash < 0 ? name : `${folder}${rest.slice(0, slash)}`; const directory = slash >= 0 || item.directory; - const key = `${path}${directory ? "/" : ""}`; + // Files stay keyed by their raw name so `/a.txt` and `a.txt` remain two openable rows. + const key = directory ? `d:${path}` : `f:${item.path}`; const previous = children.get(key); - if (previous) previous.size += item.size; - else children.set(key, { path, directory, size: item.size, modified: item.modified }); + if (previous && directory) previous.size += item.size; + else + children.set(key, { + path, + entryPath: item.path, + directory, + size: item.size, + modified: item.modified, + }); } return (
    @@ -347,7 +356,7 @@ export default function BinaryViewer(props: { ) .map((item) => ( @@ -359,7 +368,7 @@ export default function BinaryViewer(props: { else { setSelectedPath(item.path); setEntry(null); - send({ type: "entry", path: item.path }); + send({ type: "entry", path: item.entryPath }); } }} > From fcdaef886a91bd92e824db6b8670be1fbeb838fe Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 00:00:57 -0800 Subject: [PATCH 304/324] fix(server): provider updates keep running when the client disconnects (#27261) --- .../providerMaintenanceRunner.test.ts | 210 ++++++++++++------ .../src/provider/providerMaintenanceRunner.ts | 28 ++- apps/server/src/server.ts | 2 + apps/server/src/ws.ts | 9 +- 4 files changed, 166 insertions(+), 83 deletions(-) diff --git a/apps/server/src/provider/providerMaintenanceRunner.test.ts b/apps/server/src/provider/providerMaintenanceRunner.test.ts index 985347a66e96b..6fec324302fea 100644 --- a/apps/server/src/provider/providerMaintenanceRunner.test.ts +++ b/apps/server/src/provider/providerMaintenanceRunner.test.ts @@ -8,12 +8,14 @@ import { } from "@t3tools/contracts"; import { ServerProviderUpdateError } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; +import * as Context from "effect/Context"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Ref from "effect/Ref"; +import * as Scope from "effect/Scope"; import * as Schema from "effect/Schema"; import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; @@ -250,27 +252,25 @@ const makeTestRunner = ( }, latestVersions: Layer.Layer = ProviderLatestVersions.layer, ) => - Effect.service(ProviderMaintenanceRunner.ProviderMaintenanceRunner).pipe( - Effect.provide( - ProviderMaintenanceRunner.layer.pipe( - Layer.provide( - Layer.mergeAll( - Layer.succeed(ProviderRegistry.ProviderRegistry, registry), - Layer.succeed(ModelManifest.ModelManifest, { - current: Effect.succeed(manifest), - refresh: Effect.succeed(manifest), - forceRefresh: Effect.succeed(manifest), - refreshOnDemand: Effect.succeed(manifest), - refreshInBackground: Effect.void, - }), - latestVersions, - // Layers memoize by reference, so a test that provides the gate shares it. - ProviderInstallationGate.layer, - ), + Layer.build( + ProviderMaintenanceRunner.layer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.succeed(ProviderRegistry.ProviderRegistry, registry), + Layer.succeed(ModelManifest.ModelManifest, { + current: Effect.succeed(manifest), + refresh: Effect.succeed(manifest), + forceRefresh: Effect.succeed(manifest), + refreshOnDemand: Effect.succeed(manifest), + refreshInBackground: Effect.void, + }), + latestVersions, + // Layers memoize by reference, so a test that provides the gate shares it. + ProviderInstallationGate.layer, ), ), ), - ); + ).pipe(Effect.map(Context.get(ProviderMaintenanceRunner.ProviderMaintenanceRunner))); function layerFailingLatestLookupAfterFirst() { let lookups = 0; @@ -905,14 +905,15 @@ describe("providerMaintenanceRunner", () => { ); }); - it.effect("an interrupted update ends failed instead of running forever", () => { + it.effect("an update stopped by server shutdown ends failed instead of running forever", () => { const started = Deferred.makeUnsafe(); return Effect.gen(function* () { const { registry, updateStatesRef } = yield* makeRegistry(baseNativeCliProvider); - const updater = yield* makeTestRunner(registry); - const update = yield* updater.updateProvider(NATIVE_CLI_DRIVER).pipe(Effect.forkScoped); + const serverScope = yield* Scope.make(); + const updater = yield* makeTestRunner(registry).pipe(Scope.provide(serverScope)); + yield* updater.updateProvider(NATIVE_CLI_DRIVER).pipe(Effect.forkScoped); yield* Deferred.await(started); - yield* Fiber.interrupt(update); + yield* Scope.close(serverScope, Exit.void); const last = (yield* Ref.get(updateStatesRef)).at(-1); assert.deepStrictEqual( [last?.status, last?.message], @@ -931,11 +932,12 @@ describe("providerMaintenanceRunner", () => { ); }); - it.effect("a request dropped while the final state is written still records it", () => { + it.effect("a shutdown while the final state is written still records it", () => { const writing = Deferred.makeUnsafe(); const release = Deferred.makeUnsafe(); return Effect.gen(function* () { const { registry, updateStatesRef } = yield* makeRegistry(baseNativeCliProvider); + const serverScope = yield* Scope.make(); const updater = yield* makeTestRunner({ ...registry, setProviderMaintenanceActionState: (input) => @@ -945,13 +947,13 @@ describe("providerMaintenanceRunner", () => { Effect.andThen(registry.setProviderMaintenanceActionState(input)), ) : registry.setProviderMaintenanceActionState(input), - }); + }).pipe(Scope.provide(serverScope)); - const update = yield* updater.updateProvider(NATIVE_CLI_DRIVER).pipe(Effect.forkScoped); + yield* updater.updateProvider(NATIVE_CLI_DRIVER).pipe(Effect.forkScoped); yield* Deferred.await(writing); - update.interruptUnsafe(); + const shutdown = yield* Scope.close(serverScope, Exit.void).pipe(Effect.forkScoped); yield* Deferred.succeed(release, undefined); - yield* Fiber.await(update); + yield* Fiber.join(shutdown); assert.strictEqual((yield* Ref.get(updateStatesRef)).at(-1)?.status, "succeeded"); }).pipe( @@ -1150,58 +1152,124 @@ describe("providerMaintenanceRunner", () => { ); }); + it.effect("finishes a queued update whose caller is interrupted", () => + Effect.gen(function* () { + const { registry } = yield* makeRegistry(baseProvider, { + installedVersionAfterUpdate: "1.0.0", + }); + const firstFinished = yield* Deferred.make(); + let blockQueuedState = true; + const queuedStateWrittenLatch: { resolve: () => void } = { resolve: () => {} }; + const releaseQueuedStateLatch: { resolve: () => void } = { resolve: () => {} }; + const queuedStateWritten = new Promise((resolve) => { + queuedStateWrittenLatch.resolve = resolve; + }); + const releaseQueuedState = new Promise((resolve) => { + releaseQueuedStateLatch.resolve = resolve; + }); + + const updater = yield* makeTestRunner({ + ...registry, + setProviderMaintenanceActionState: Effect.fn( + "providerMaintenanceRunner.test.blockQueuedState", + )(function* (input) { + const providers = yield* registry.setProviderMaintenanceActionState(input); + if (input.state?.status === "queued" && blockQueuedState) { + queuedStateWrittenLatch.resolve(); + yield* Effect.promise(() => releaseQueuedState); + } + if (input.state?.status === "succeeded") { + yield* Deferred.succeed(firstFinished, undefined); + } + return providers; + }), + }); + + const first = yield* updater.updateProvider(CODEX_DRIVER).pipe(Effect.forkScoped); + yield* Effect.promise(() => queuedStateWritten); + blockQueuedState = false; + + yield* Fiber.interrupt(first); + releaseQueuedStateLatch.resolve(); + yield* Deferred.await(firstFinished); + }).pipe( + Effect.provide( + Layer.mergeAll( + layerNonWindowsPlatform, + layerLatestVersionHttpClient("1.0.0"), + layerMockSpawner(() => ({ stdout: "updated" })), + ), + ), + ), + ); + it.effect( - "releases the running-provider marker when interrupted after queuing but before the lock run starts", + "keeps the update command running and records its result when the caller is interrupted", () => Effect.gen(function* () { - const { registry } = yield* makeRegistry(baseProvider, { - installedVersionAfterUpdate: "1.0.0", - }); - let blockQueuedState = true; - const queuedStateWrittenLatch: { resolve: () => void } = { resolve: () => {} }; - const releaseQueuedStateLatch: { resolve: () => void } = { resolve: () => {} }; - const queuedStateWritten = new Promise((resolve) => { - queuedStateWrittenLatch.resolve = resolve; - }); - const releaseQueuedState = new Promise((resolve) => { - releaseQueuedStateLatch.resolve = resolve; - }); + const kills: Array = []; + const spawned = yield* Deferred.make(); + const exit = yield* Deferred.make(); + const finished = yield* Deferred.make(); + const spawner = ChildProcessSpawner.make(() => + Deferred.succeed(spawned, undefined).pipe( + Effect.as( + ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(1), + exitCode: Deferred.await(exit), + isRunning: Effect.succeed(true), + kill: () => Effect.sync(() => kills.push("kill")), + unref: Effect.succeed(Effect.void), + stdin: Sink.drain, + stdout: Stream.make(encoder.encode("added 1 package")), + stderr: Stream.empty, + all: Stream.empty, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + }), + ), + ), + ); - const updater = yield* makeTestRunner({ - ...registry, - setProviderMaintenanceActionState: Effect.fn( - "providerMaintenanceRunner.test.blockQueuedState", - )(function* (input) { - const providers = yield* registry.setProviderMaintenanceActionState(input); - if (input.state?.status === "queued" && blockQueuedState) { - queuedStateWrittenLatch.resolve(); - yield* Effect.promise(() => releaseQueuedState); - } - return providers; - }), - }); + yield* Effect.gen(function* () { + const { registry } = yield* makeRegistry(baseOpenCodeProvider); + const updater = yield* makeTestRunner({ + ...registry, + setProviderMaintenanceActionState: Effect.fn( + "providerMaintenanceRunner.test.recordFinishedState", + )(function* (input) { + const providers = yield* registry.setProviderMaintenanceActionState(input); + const status = input.state?.status; + if (input.state && status !== "queued" && status !== "running") { + yield* Deferred.succeed(finished, input.state); + } + return providers; + }), + }); - const first = yield* updater.updateProvider(CODEX_DRIVER).pipe(Effect.forkScoped); - yield* Effect.promise(() => queuedStateWritten); - blockQueuedState = false; + const caller = yield* updater.updateProvider(OPENCODE_DRIVER).pipe(Effect.forkChild); + yield* Deferred.await(spawned); + yield* Fiber.interrupt(caller); - yield* Fiber.interrupt(first); - releaseQueuedStateLatch.resolve(); + assert.deepStrictEqual( + kills, + [], + "interrupting the updateProvider caller killed the running npm install", + ); - const second = yield* updater.updateProvider(CODEX_DRIVER).pipe(Effect.exit); - assert.strictEqual(Exit.isSuccess(second), true); - if (Exit.isSuccess(second)) { - assert.strictEqual(second.value.providers[0]?.updateState?.status, "succeeded"); - } - }).pipe( - Effect.provide( - Layer.mergeAll( - layerNonWindowsPlatform, - layerLatestVersionHttpClient("1.0.0"), - layerMockSpawner(() => ({ stdout: "updated" })), + yield* Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)); + const finalState = yield* Deferred.await(finished); + assert.strictEqual(finalState.status, "succeeded"); + }).pipe( + Effect.provide( + Layer.mergeAll( + layerNonWindowsPlatform, + layerLatestVersionHttpClient("0.0.0"), + Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner), + ), ), - ), - ), + ); + }), ); it.effect("resolves npm to a .cmd shim from the provider's PATH on win32", () => { diff --git a/apps/server/src/provider/providerMaintenanceRunner.ts b/apps/server/src/provider/providerMaintenanceRunner.ts index 014aa67c26df0..a09bf1ee7dbba 100644 --- a/apps/server/src/provider/providerMaintenanceRunner.ts +++ b/apps/server/src/provider/providerMaintenanceRunner.ts @@ -13,6 +13,7 @@ import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; @@ -323,6 +324,7 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const httpClient = yield* HttpClient.HttpClient; const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions; + const serviceScope = yield* Effect.scope; const installationGate = yield* ProviderInstallationGate.ProviderInstallationGate; const runMaintenanceCommand = ( update: ProviderMaintenanceCommandAction, @@ -685,7 +687,8 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () { }, ); - return yield* commandCoordinator + // Installers cannot be safely killed mid-install, so the update outlives a disconnecting caller. + const updateFiber = yield* commandCoordinator .withCommandLock({ targetKey, lockKey: update.lockKey, @@ -693,10 +696,10 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () { run: runProviderUpdate(), }) .pipe( - // A dropped request interrupts the update; a "running" state would spin until restart. + // Server shutdown interrupts the update; a "running" state would spin until restart. Effect.onInterrupt(() => Effect.gen(function* () { - // A finished state stays, even if the request drops while it is being written. + // A finished state stays, even if shutdown lands while it is being written. if (yield* Ref.get(settled)) return; yield* setUpdateState( makeUpdateState({ @@ -708,15 +711,18 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () { ); }).pipe(Effect.ignore), ), - Effect.mapError((error) => - isServerProviderUpdateError(error) - ? new ServerProviderUpdateError({ - provider, - reason: error.reason, - }) - : error, - ), + Effect.forkIn(serviceScope), ); + return yield* Fiber.join(updateFiber).pipe( + Effect.mapError((error) => + isServerProviderUpdateError(error) + ? new ServerProviderUpdateError({ + provider, + reason: error.reason, + }) + : error, + ), + ); }); return ProviderMaintenanceRunner.of({ diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 68f32f4ecf0a9..499c1e2acc0ca 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -78,6 +78,7 @@ import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderS import * as OpenCodeRuntime from "@t3tools/provider-opencode/server/OpenCodeRuntime"; import * as OpenCodeServerLedger from "@t3tools/provider-opencode/server/OpenCodeServerLedger"; import * as ProviderHostLive from "./provider/ProviderHostLive.ts"; +import * as ProviderMaintenanceRunner from "./provider/providerMaintenanceRunner.ts"; import * as DocumentText from "./provider/DocumentText.ts"; import * as AcpRegistrySupport from "@t3tools/provider-acp-registry/server/AcpRegistrySupport"; import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts"; @@ -957,6 +958,7 @@ const layerMakeRoutes = Layer.mergeAll( Layer.provide(layerServerSettings), Layer.provide(PreviewAutomationBroker.layer), Layer.provide(ServerSelfUpdate.layer.pipe(Layer.provide(layerDesktopAppUpdate))), + Layer.provide(ProviderMaintenanceRunner.layer), Layer.provide(layerCommandReadiness), Layer.provide(ServerHttp.layerBrowserApiCors), Layer.provide(ServerHttp.layerHttpCompression), diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index ff783eeb57324..b6922b9e90996 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -3729,6 +3729,7 @@ export const layer = Layer.unwrap( Effect.gen(function* () { const serverBrowser = yield* ServerBrowser.ServerBrowser; const serverSelfUpdate = yield* ServerSelfUpdate.ServerSelfUpdate; + const providerMaintenanceRunner = yield* ProviderMaintenanceRunner.ProviderMaintenanceRunner; const npmRelease = yield* NpmRelease.NpmRelease; const pullRequests = yield* PullRequestService.PullRequestService; const issues = yield* IssueService.IssueService; @@ -3820,7 +3821,13 @@ export const layer = Layer.unwrap( Layer.provide(DefectReporter.layer), Layer.provide(AcpRegistrySessions.layer), Layer.provide(Layer.succeed(SqlClient.SqlClient, sql)), - Layer.provide(ProviderMaintenanceRunner.layer), + // Installs outlive the connection that started them and lock across clients. + Layer.provide( + Layer.succeed( + ProviderMaintenanceRunner.ProviderMaintenanceRunner, + providerMaintenanceRunner, + ), + ), Layer.provide(Layer.succeed(NpmRelease.NpmRelease, npmRelease)), Layer.provide(Layer.succeed(ServerSelfUpdate.ServerSelfUpdate, serverSelfUpdate)), // Share server-lifetime PR caches so WS mutations invalidate every client's HTTP diffs. From e20e769b0997adb6b2b3ec26e9562a3c3d55f41a Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 02:01:09 -0600 Subject: [PATCH 305/324] fix(server): reject workflow signals with conflicting destinations (#41312) Co-authored-by: Julius Marminge --- .../mcp/toolkits/workflow/handlers.test.ts | 89 ++++++++++++++----- .../src/mcp/toolkits/workflow/handlers.ts | 7 ++ 2 files changed, 73 insertions(+), 23 deletions(-) diff --git a/apps/server/src/mcp/toolkits/workflow/handlers.test.ts b/apps/server/src/mcp/toolkits/workflow/handlers.test.ts index c036cb8d7e649..77b7036681ad6 100644 --- a/apps/server/src/mcp/toolkits/workflow/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/workflow/handlers.test.ts @@ -12,29 +12,28 @@ import * as McpToolAccessTestkit from "../../McpToolAccess.testkit.ts"; import * as WorkflowHandlers from "./handlers.ts"; import { WorkflowToolkit } from "./tools.ts"; +const handlersWith = (workflows: Partial) => + McpToolAccess.HandlersLayer.layer(WorkflowHandlers.layer).pipe( + Layer.provideMerge( + Layer.mergeAll( + NodeCrypto.layer, + McpToolAccessTestkit.liveThreadsLayer, + Layer.succeed(McpInvocationContext.McpInvocationContext, { + environmentId: EnvironmentId.make("environment:workflow"), + requestNamespace: "client:workflow", + thread: undefined, + client: { sessionId: "session-1", label: "t3 CLI", access: "full-access" }, + capabilities: new Set(["orchestration" as const]), + issuedAt: 0, + }), + Layer.mock(Workflows.Workflows)(workflows), + ), + ), + ); + it.effect("start passes an explicit null payload through and defaults an omitted one to {}", () => Effect.gen(function* () { const payloads: Array = []; - const layerDependencies = Layer.mergeAll( - NodeCrypto.layer, - McpToolAccessTestkit.liveThreadsLayer, - Layer.succeed(McpInvocationContext.McpInvocationContext, { - environmentId: EnvironmentId.make("environment:workflow"), - requestNamespace: "client:workflow", - thread: undefined, - client: { sessionId: "session-1", label: "t3 CLI", access: "full-access" }, - capabilities: new Set(["orchestration" as const]), - issuedAt: 0, - }), - Layer.mock(Workflows.Workflows)({ - start: (_workflow, input) => - Effect.sync(() => { - payloads.push(input); - return { runId: "run-1" }; - }), - get: () => Effect.succeed({ run: undefined, steps: [], references: [] } as never), - }), - ); yield* Effect.gen(function* () { const toolkit = yield* WorkflowToolkit; for (const input of [{ input: null }, {}]) { @@ -49,11 +48,55 @@ it.effect("start passes an explicit null payload through and defaults an omitted } }).pipe( Effect.provide( - McpToolAccess.HandlersLayer.layer(WorkflowHandlers.layer).pipe( - Layer.provideMerge(layerDependencies), - ), + handlersWith({ + start: (_workflow, input) => + Effect.sync(() => { + payloads.push(input); + return { runId: "run-1" }; + }), + get: () => Effect.succeed({ run: undefined, steps: [], references: [] } as never), + }), ), ); expect(payloads).toEqual([null, {}]); }), ); + +it.effect("signal refuses a run destination mixed with a channel destination", () => + Effect.gen(function* () { + const delivered: Array = []; + const results = yield* Effect.gen(function* () { + const toolkit = yield* WorkflowToolkit; + return yield* Effect.forEach( + [ + { runId: "run-1", wait: "review", channel: "other" }, + { workflow: "other", channel: "other", runId: "run-1" }, + { runId: "run-1", wait: "review" }, + ], + (address) => + toolkit + .handle("t3_workflow", { action: "signal", value: { choice: "yes" }, ...address }) + .pipe( + Stream.unwrap, + Stream.runCollect, + Effect.map((parts) => parts.at(-1)?.result), + ), + ); + }).pipe( + Effect.provide( + handlersWith({ + signal: (address) => + Effect.sync(() => { + delivered.push(address); + return "delivered" as const; + }), + }), + ), + ); + for (const result of results.slice(0, -1)) { + expect(result).toMatchObject({ code: "invalid_request" }); + } + expect(results.at(-1)).toEqual({ delivery: "delivered" }); + expect(delivered).toEqual([{ runId: "run-1", wait: "review" }]); + }), +); diff --git a/apps/server/src/mcp/toolkits/workflow/handlers.ts b/apps/server/src/mcp/toolkits/workflow/handlers.ts index b3ccb35f28151..7ebc6ac0cf7a4 100644 --- a/apps/server/src/mcp/toolkits/workflow/handlers.ts +++ b/apps/server/src/mcp/toolkits/workflow/handlers.ts @@ -58,6 +58,13 @@ export const layer = McpToolAccess.toLayer(WorkflowToolkit, { } if (input.action === "signal") { const value = yield* required(input.value, "value"); + const byRun = input.runId !== undefined || input.wait !== undefined; + const byChannel = input.workflow !== undefined || input.channel !== undefined; + if (byRun && byChannel) { + return yield* invalid( + "Address a signal with `runId` and `wait`, or with `workflow` and `channel`, not both.", + ); + } const address = input.runId !== undefined && input.wait !== undefined ? { runId: input.runId, wait: input.wait } From 37b316ac314ebb991c498492b5f1eb036a0eed6c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nguy=E1=BB=85n=20Hu=E1=BB=B3nh=20L=E1=BB=A3i?= Date: Mon, 23 Nov 2026 16:03:59 +0800 Subject: [PATCH 306/324] fix(desktop): declare Apple Events access for Computer Use cleanup (#33869) Co-authored-by: Julius Marminge Co-authored-by: Claude Opus 5.5 --- scripts/build-desktop-artifact.test.ts | 7 ++++++- scripts/build-desktop-artifact.ts | 4 ++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/scripts/build-desktop-artifact.test.ts b/scripts/build-desktop-artifact.test.ts index c9180ec3d3ae6..43e89846bded0 100644 --- a/scripts/build-desktop-artifact.test.ts +++ b/scripts/build-desktop-artifact.test.ts @@ -592,7 +592,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => { ), ); - it.effect("declares Calendar access for hosted commands in macOS builds", () => + it.effect("declares Calendar and Apple Events access for hosted commands in macOS builds", () => Effect.gen(function* () { for (const version of ["0.1.0", "0.1.1-nightly.20261019.1"]) { for (const signed of [false, true]) { @@ -610,6 +610,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => { "NSCalendarsUsageDescription", "NSCalendarsFullAccessUsageDescription", "NSCalendarsWriteOnlyAccessUsageDescription", + "NSAppleEventsUsageDescription", ]) { assert.isString(mac.extendInfo[key], `${version}, signed=${signed}: ${key}`); assert.isNotEmpty(mac.extendInfo[key]); @@ -1591,6 +1592,10 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => { assert.include(entitlements, "webcredentials:clerk.example.com"); assert.include(entitlements, "webcredentials:example.clerk.accounts.dev"); assert.include(entitlements, "com.apple.security.cs.allow-jit"); + assert.match( + entitlements, + /com\.apple\.security\.automation\.apple-events<\/key>\s*/u, + ); assert.match(entitlements, /com\.apple\.security\.device\.camera<\/key>\s*/u); assert.match(entitlements, /com\.apple\.security\.device\.audio-input<\/key>\s*/u); assert.notInclude(entitlements, "keychain-access-groups"); diff --git a/scripts/build-desktop-artifact.ts b/scripts/build-desktop-artifact.ts index 746ac826005b3..90cc9e1118235 100644 --- a/scripts/build-desktop-artifact.ts +++ b/scripts/build-desktop-artifact.ts @@ -1395,6 +1395,8 @@ ${associatedDomains} com.apple.security.cs.disable-library-validation + com.apple.security.automation.apple-events +